[
  {
    "path": ".appveyor.yml",
    "content": "﻿init:\n  - git config --global core.autocrlf true\nbranches:\n  only:\n    - main\n    - /^(.*\\/)?ci-.*$/\n    - /^rel\\/.*/\nconfiguration:\n  - CodeAnalysis\n  - Release\nmatrix:\n  fast_finish: true\nbefore_build:\n  - cmd: .\\build.cmd EnableSkipStrongNames\nbuild_script:\n  - cmd: .\\build.cmd UnitTest /P:Configuration=%Configuration%\nclone_depth: 1\ntest: off\ndeploy: off\nos: Visual Studio 2017\n"
  },
  {
    "path": ".azuredevops/dependabot.yml",
    "content": "version: 2\nenable-campaigned-updates: false\nenable-security-updates: false\n"
  },
  {
    "path": ".config/CredScanSuppressions.json",
    "content": "{\n  \"tool\": \"Credential Scanner\",\n  \"suppressions\": [\n    {\n      \"placeholder\": \"abcdefg\",\n      \"_justification\": \"This is a fake password used in test code.\"\n    },\n    {\n      \"placeholder\": \"Pa$$AAECAw==\",\n      \"_justification\": \"This is a fake password used in test code.\"\n    },\n    {\n      \"placeholder\": \"ALyuoraY/cIWD1hjo+K81/pf83qo6Q6T+UBYcXN9P3A9WHLvEY10f+lwW5qPG6h9xw==\",\n      \"_justification\": \"This is a fake hashed password used in test code.\"\n    },\n    {\n      \"placeholder\": \"abcdefg123\",\n      \"_justification\": \"This is a fake password used in test code.\"\n    },\n    {\n      \"placeholder\": \"3e29b24f825e737d97aed5eb62df5076\",\n      \"_justification\": \"This is a fake password used in test code.\"\n    },\n    {\n      \"placeholder\": \"My Password\",\n      \"_justification\": \"This is a fake password used in test code.\"\n    }\n  ]\n}"
  },
  {
    "path": ".config/tsaoptions.json",
    "content": "{\n  \"areaPath\": \"DevDiv\\\\ASP.NET Core\\\\Policy Violations\",\n  \"codebaseName\": \"AspNetWebStack\",\n  \"instanceUrl\": \"https://devdiv.visualstudio.com/\",\n  \"iterationPath\": \"DevDiv\",\n  \"notificationAliases\": [\n    \"aspnetcore-build@microsoft.com\"\n  ],\n  \"projectName\": \"DEVDIV\",\n  \"repositoryName\": \"AspNetWebStack\",\n  \"template\": \"TFSDEVDIV\"\n}\n"
  },
  {
    "path": ".gitattributes",
    "content": "* text\n\n*.bmp binary\n*.dll binary\n*.gif binary\n*.jpg binary\n*.png binary\n*.snk binary\n\n*.ascx text\n*.cd text\n*.cmd text\n*.coffee text\n*.config text\n*.cs text diff=csharp \n*.csproj text merge=union \n*.cshtml text\n*.css text\n*.dtd text\n*.edmx text\n*.htm text\n*.html text\n*.js text\n*.json text\n*.msbuild text\n*.nuspec text\n*.resx text\n*.ruleset text\n*.StyleCop text\n*.targets text\n*.tt text\n*.txt text\n*.vb text\n*.vbhtml text\n*.vbproj text merge=union \n*.vbs text\n*.wsf text\n*.xml text\n*.xunit text\n\n*.sln text eol=crlf merge=union \n"
  },
  {
    "path": ".gitignore",
    "content": ".msbuild/\n.vs/\nbin/\nobj/\npackages/\n\n*.[Cc]ache\n*.binlog\n*.dll\n*.dot[Cc]over\n*.exe\n*.nupkg\n*.orig\n*.psess\n*.sln.ide\n*.suo\n*.user\n*.vsp\n*[Rr]esharper*\n*launchSettings.json\n"
  },
  {
    "path": ".nuget/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Microsoft.Web.SkipStrongNames\" version=\"1.0.0\" />\n  <package id=\"Microsoft.Web.StyleCop\" version=\"1.0.0\" />\n  <package id=\"StyleCop\" version=\"5.0.0\" />\n  <package id=\"xunit.runner.msbuild\" version=\"2.4.2\" targetFramework=\"net452\" />\n</packages>"
  },
  {
    "path": ".travis.yml",
    "content": "language: csharp\nsudo: false\ndist: trusty\nmono: none\nos:\n  - linux\nbranches:\n  only:\n   - not.a.branch\nscript:\n  - echo Skipping builds for now.\n"
  },
  {
    "path": "CODE-OF-CONDUCT.md",
    "content": "# Code of Conduct\n\nThis project has adopted the code of conduct defined by the Contributor Covenant\nto clarify expected behavior in our community.\n\nFor more information, see the [.NET Foundation Code of Conduct](https://dotnetfoundation.org/code-of-conduct).\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# How to contribute\n\nOne of the easiest ways to contribute is to participate in discussions and discuss issues. You can also contribute by submitting pull requests with code changes.\n\n## Bugs and feature requests?\nFor non-security related bugs please log a new issue in this repo.\n\n## Reporting security issues and bugs\nSecurity issues and bugs should be reported privately, via email, to the Microsoft Security Response Center (MSRC)  secure@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 [Security TechCenter](https://technet.microsoft.com/en-us/security/ff852094.aspx).\n\n## Other discussions\nOur team members also monitor several other discussion forums:\n\n* [ASP.NET MVC forum](https://forums.asp.net/1146.aspx/1?MVC)\n* [ASP.NET Web API forum](https://forums.asp.net/1246.aspx/1?Web+API)\n* [ASP.NET Web Pages forum](https://forums.asp.net/1224.aspx/1?ASP+NET+Web+Pages)\n* [StackOverflow](https://stackoverflow.com/) with the [`asp.net`](https://stackoverflow.com/questions/tagged/asp.net), [`asp.net-mvc`](https://stackoverflow.com/questions/tagged/asp.net-mvc), [`asp.net-web-api`](https://stackoverflow.com/questions/tagged/asp.net-web-api), [`asp.net-webpages`](https://stackoverflow.com/questions/tagged/asp.net-webpages) or [`razor`](https://stackoverflow.com/questions/tagged/razor) tags.\n\n## Filing issues\nWhen filing issues, please use our [bug filing templates](https://github.com/aspnet/Home/wiki/Functional-bug-template).\nThe best way to get your bug fixed is to be as detailed as you can be about the problem.\nProviding a minimal project with steps to reproduce the problem is ideal.\nHere are questions you can answer before you file a bug to make sure you're not missing any important information.\n\n1. Did you read the [documentation](http://www.asp.net/aspnet)?\n2. Did you include the snippet of broken code in the issue?\n3. What are the *EXACT* steps to reproduce this problem?\n4. What package versions are you using (you can see these in the `packages.config` file)?\n5. What operating system are you using?\n6. What version of IIS are you using?\n\nGitHub supports [markdown](https://help.github.com/articles/github-flavored-markdown/), so when filing bugs make sure you check the formatting before clicking submit.\n\n## Contributing code and content\nYou will need to sign a [Contributor License Agreement](https://cla2.dotnetfoundation.org/) before submitting your pull request. To complete the Contributor License Agreement (CLA), you will need to submit a request via the form and then electronically sign the Contributor License Agreement when you receive the email containing the link to the document. This needs to only be done once for any .NET Foundation OSS project.\n\nMake sure you can build the code. Familiarize yourself with the project workflow and our coding conventions. If you don't know what a pull request is read this article: https://help.github.com/articles/using-pull-requests.\n\nBefore submitting a feature or substantial code contribution please discuss it with the team and ensure it follows the product roadmap. You might also read these two blogs posts on contributing code: [Open Source Contribution Etiquette](http://tirania.org/blog/archive/2010/Dec-31.html) by Miguel de Icaza and [Don't \"Push\" Your Pull Requests](https://www.igvita.com/2011/12/19/dont-push-your-pull-requests/) by Ilya Grigorik. Note that all code submissions will be rigorously reviewed and tested by the ASP.NET and Entity Framework teams, and only those that meet an extremely high bar for both quality and design/roadmap appropriateness will be merged into the source.\n\nHere's a few things you should always do when making changes to the code base:\n\n**Commit/Pull Request Format**\n\n```\nSummary of the changes (Less than 80 chars)\n - Detail 1\n - Detail 2\n\nAddresses #bugnumber (in this specific format)\n```\n\n**Tests**\n\n-  Tests need to be provided for every bug/feature that is completed.\n-  Tests only need to be present for issues that need to be verified by QA (e.g. not tasks)\n-  If there is a scenario that is far too hard to test there does not need to be a test for it.\n  - \"Too hard\" is determined by the team as a whole.\n"
  },
  {
    "path": "Directory.Build.props",
    "content": "<Project>\n  <!-- Also stop MsBuild searching parent directories for this file. -->\n\n  <PropertyGroup>\n    <!-- Require VS2017 so VS builds also use MSBuild v15.0. -->\n    <MinimumVisualStudioVersion>16.0</MinimumVisualStudioVersion>\n    <!--\n      Suppress \"MSBUILD : warning : Post-build Code Analysis (FxCopCmd.exe) has been deprecated in favor of FxCop\n      analyzers, which run during build. Refer to https://aka.ms/fxcopanalyzers to migrate to FxCop analyzers.\"\n    -->\n    <SuppressLegacyCodeAnalysisDeprecatedWarning>true</SuppressLegacyCodeAnalysisDeprecatedWarning>\n    <!-- Workaround continued use of netcoreapp2.1; suppress the NETSDK1138 warning. -->\n    <CheckEolTargetFramework>false</CheckEolTargetFramework>\n  </PropertyGroup>\n\n</Project>\n"
  },
  {
    "path": "Directory.Build.targets",
    "content": "<Project>\n  <!-- Stop MsBuild searching parent directories for this file. -->\n</Project>\n"
  },
  {
    "path": "LICENSE.txt",
    "content": "Copyright (c) .NET Foundation. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthese files except in compliance with the License. You may obtain a copy of the\nLicense at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed\nunder the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\nCONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n"
  },
  {
    "path": "NuGet.Config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n  <solution>\n    <add key=\"disableSourceControlIntegration\" value=\"true\" />\n  </solution>\n  <packageSources>\n    <clear />\n    <add key=\"dotnet-public\" value=\"https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-public/nuget/v3/index.json\" />\n    <add key=\"myget-legacy\" value=\"https://pkgs.dev.azure.com/dnceng/public/_packaging/myget-legacy/nuget/v3/index.json\" />\n  </packageSources>\n</configuration>"
  },
  {
    "path": "README.md",
    "content": "# ASP.NET MVC, Web API, Web Pages, and Razor\n\n## 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).\n\nASP.NET MVC is a web framework that gives you a powerful, patterns-based way to build dynamic websites and Web APIs. ASP.NET MVC enables a clean separation of concerns and gives you full control over markup.\n\nThis repo includes:\n\n* ASP.NET MVC 5.x\n* ASP.NET Web API 2.x\n* ASP.NET Web Pages 3.x\n* ASP.NET Razor 3.x\n\n### Contributing\n\nCheck out the [contributing](CONTRIBUTING.md) page to see the best places to log issues and start discussions.\n\n### Tags and releases\n\nGit tag or branch|Other products|MVC package versions|Web API package (product) versions|Web Pages package versions\n--------|--------------|------------|------------|------------\n[v2.0.4](https://github.com/aspnet/AspNetWebStack/tree/v2.0.4)||4.0.40804|4.0.30506|2.0.30506\n[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\n[v3.0.2](https://github.com/aspnet/AspNetWebStack/tree/v3.0.2)||5.0.2|5.0.1 (2.0.1)|3.0.1\n[v3.1.3](https://github.com/aspnet/AspNetWebStack/tree/v3.1.3)||5.1.3|5.1.2 (2.1.2)|3.1.2\n[v3.2.6](https://github.com/aspnet/AspNetWebStack/tree/v3.2.6)||5.2.6|5.2.6|3.2.6\n[v3.2.7](https://github.com/aspnet/AspNetWebStack/tree/v3.2.7)||5.2.7|5.2.7|3.2.7\n[v3.2.8](https://github.com/aspnet/AspNetWebStack/tree/v3.2.8)||5.2.8|5.2.8|3.2.8\n[main](https://github.com/aspnet/AspNetWebStack/tree/main)|New work e.g. MVC 5.2.9-preview1||||\n"
  },
  {
    "path": "Runtime.NetFramework.slnf",
    "content": "{\n  \"solution\": {\n    \"path\": \"Runtime.sln\",\n    \"projects\": [\n      \"src\\\\Microsoft.AspNet.Facebook\\\\Microsoft.AspNet.Facebook.csproj\",\n      \"src\\\\Microsoft.Web.Helpers\\\\Microsoft.Web.Helpers.csproj\",\n      \"src\\\\Microsoft.Web.Mvc\\\\Microsoft.Web.Mvc.csproj\",\n      \"src\\\\Microsoft.Web.WebPages.OAuth\\\\Microsoft.Web.WebPages.OAuth.csproj\",\n      \"src\\\\System.Net.Http.Formatting\\\\System.Net.Http.Formatting.csproj\",\n      \"src\\\\System.Web.Cors\\\\System.Web.Cors.csproj\",\n      \"src\\\\System.Web.Helpers\\\\System.Web.Helpers.csproj\",\n      \"src\\\\System.Web.Http.Cors\\\\System.Web.Http.Cors.csproj\",\n      \"src\\\\System.Web.Http.Owin\\\\System.Web.Http.Owin.csproj\",\n      \"src\\\\System.Web.Http.SelfHost\\\\System.Web.Http.SelfHost.csproj\",\n      \"src\\\\System.Web.Http.SignalR\\\\System.Web.Http.SignalR.csproj\",\n      \"src\\\\System.Web.Http.Tracing\\\\System.Web.Http.Tracing.csproj\",\n      \"src\\\\System.Web.Http.WebHost\\\\System.Web.Http.WebHost.csproj\",\n      \"src\\\\System.Web.Http\\\\System.Web.Http.csproj\",\n      \"src\\\\System.Web.Mvc\\\\System.Web.Mvc.csproj\",\n      \"src\\\\System.Web.Razor\\\\System.Web.Razor.csproj\",\n      \"src\\\\System.Web.WebPages.Administration\\\\System.Web.WebPages.Administration.csproj\",\n      \"src\\\\System.Web.WebPages.Deployment\\\\System.Web.WebPages.Deployment.csproj\",\n      \"src\\\\System.Web.WebPages.Razor\\\\System.Web.WebPages.Razor.csproj\",\n      \"src\\\\System.Web.WebPages\\\\System.Web.WebPages.csproj\",\n      \"src\\\\WebApiHelpPage\\\\VB\\\\WebApiHelpPageVB.vbproj\",\n      \"src\\\\WebApiHelpPage\\\\WebApiHelpPage.csproj\",\n      \"src\\\\WebMatrix.Data\\\\WebMatrix.Data.csproj\",\n      \"src\\\\WebMatrix.WebData\\\\WebMatrix.WebData.csproj\",\n      \"test\\\\Microsoft.AspNet.Facebook.Test\\\\Microsoft.AspNet.Facebook.Test.csproj\",\n      \"test\\\\Microsoft.TestCommon\\\\Microsoft.TestCommon.csproj\",\n      \"test\\\\Microsoft.Web.Helpers.Test\\\\Microsoft.Web.Helpers.Test.csproj\",\n      \"test\\\\Microsoft.Web.Mvc.Test\\\\Microsoft.Web.Mvc.Test.csproj\",\n      \"test\\\\Microsoft.Web.WebPages.OAuth.Test\\\\Microsoft.Web.WebPages.OAuth.Test.csproj\",\n      \"test\\\\System.Net.Http.Formatting.Test\\\\System.Net.Http.Formatting.Test.csproj\",\n      \"test\\\\System.Web.Cors.Test\\\\System.Web.Cors.Test.csproj\",\n      \"test\\\\System.Web.Helpers.Test\\\\System.Web.Helpers.Test.csproj\",\n      \"test\\\\System.Web.Http.Cors.Test\\\\System.Web.Http.Cors.Test.csproj\",\n      \"test\\\\System.Web.Http.Integration.Test\\\\System.Web.Http.Integration.Test.csproj\",\n      \"test\\\\System.Web.Http.Owin.Test\\\\System.Web.Http.Owin.Test.csproj\",\n      \"test\\\\System.Web.Http.SelfHost.Test\\\\System.Web.Http.SelfHost.Test.csproj\",\n      \"test\\\\System.Web.Http.SignalR.Test\\\\System.Web.Http.SignalR.Test.csproj\",\n      \"test\\\\System.Web.Http.Test\\\\System.Web.Http.Test.csproj\",\n      \"test\\\\System.Web.Http.Tracing.Test\\\\System.Web.Http.Tracing.Test.csproj\",\n      \"test\\\\System.Web.Http.WebHost.Test\\\\System.Web.Http.WebHost.Test.csproj\",\n      \"test\\\\System.Web.Mvc.Test\\\\System.Web.Mvc.Test.csproj\",\n      \"test\\\\System.Web.Razor.Test\\\\System.Web.Razor.Test.csproj\",\n      \"test\\\\System.Web.WebPages.Administration.Test\\\\System.Web.WebPages.Administration.Test.csproj\",\n      \"test\\\\System.Web.WebPages.Deployment.Test\\\\System.Web.WebPages.Deployment.Test.csproj\",\n      \"test\\\\System.Web.WebPages.Razor.Test\\\\System.Web.WebPages.Razor.Test.csproj\",\n      \"test\\\\System.Web.WebPages.Test\\\\System.Web.WebPages.Test.csproj\",\n      \"test\\\\WebApiHelpPage.Test\\\\WebApiHelpPage.Test.csproj\",\n      \"test\\\\WebApiHelpPage.VB.Test\\\\WebApiHelpPage.VB.Test.csproj\",\n      \"test\\\\WebMatrix.Data.Test\\\\WebMatrix.Data.Test.csproj\",\n      \"test\\\\WebMatrix.WebData.Test\\\\WebMatrix.WebData.Test.csproj\"\n    ]\n  }\n}"
  },
  {
    "path": "Runtime.NetStandard.slnf",
    "content": "{\n  \"solution\": {\n    \"path\": \"Runtime.sln\",\n    \"projects\": [\n      \"src\\\\System.Net.Http.Formatting.ns1_3\\\\System.Net.Http.Formatting.ns1_3.csproj\",\n      \"src\\\\System.Net.Http.Formatting.ns2_0\\\\System.Net.Http.Formatting.ns2_0.csproj\",\n      \"test\\\\Microsoft.TestCommon\\\\Microsoft.TestCommon.csproj\",\n      \"test\\\\System.Net.Http.Formatting.ns1_3.Test\\\\System.Net.Http.Formatting.ns1_3.Test.csproj\",\n      \"test\\\\System.Net.Http.Formatting.ns2_0.Test\\\\System.Net.Http.Formatting.ns2_0.Test.csproj\"\n    ]\n  }\n}"
  },
  {
    "path": "Runtime.msbuild",
    "content": "<Project DefaultTargets=\"UnitTest\" ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"tools/WebStack.tasks.targets\"/>\n  <UsingTask TaskName=\"SkipStrongNames.CheckSkipStrongNamesStatus\" AssemblyFile=\"$(SkipStrongNamesExe)\" />\n\n  <PropertyGroup>\n    <!-- build.cmd sets /p:Desktop=true. The CI server does not; instead, it does an additional step with /p:Configuration=CodeAnalysis. -->\n    <Configuration Condition=\" '$(Configuration)' == '' and '$(Desktop)' == 'true' \">CodeAnalysis</Configuration>\n    <Configuration Condition=\" '$(Configuration)' == '' \">Release</Configuration>\n    <CodeAnalysis Condition=\" '$(CodeAnalysis)' == '' and '$(Configuration)' != 'Release' \">true</CodeAnalysis>\n    <StyleCopEnabled Condition=\" '$(StyleCopEnabled)' == '' \">true</StyleCopEnabled>\n    <BuildInParallel Condition=\" '$(BuildInParallel)' == '' And $(MSBuildNodeCount) &gt; 1 \">true</BuildInParallel>\n    <BuildInParallel Condition=\" '$(BuildInParallel)' == '' \">false</BuildInParallel>\n    <RestoreInParallel Condition=\" '$(RestoreInParallel)' == '' \">false</RestoreInParallel>\n    <TestInParallel Condition=\" '$(TestInParallel)' == '' \">false</TestInParallel>\n    <TestResultsDirectory>$(MSBuildThisFileDirectory)bin\\$(Configuration)\\test\\TestResults\\</TestResultsDirectory>\n    <SkipStrongNamesExe>$(MSBuildThisFileDirectory)packages\\Microsoft.Web.SkipStrongNames.1.0.0\\tools\\SkipStrongNames.exe</SkipStrongNamesExe>\n    <SkipStrongNamesXml>$(MSBuildThisFileDirectory)tools\\SkipStrongNames.xml</SkipStrongNamesXml>\n    <NuGetExe>.nuget\\NuGet.exe</NuGetExe>\n  </PropertyGroup>\n\n  <Target Name=\"EnableSkipStrongNames\" DependsOnTargets=\"RestoreSkipStrongNames\">\n    <Exec Command='\"$(SkipStrongNamesExe)\" -e \"$(SkipStrongNamesXml)\"' />\n    <CheckSkipStrongNamesStatus AssembliesFile=\"$(SkipStrongNamesXml)\">\n      <Output TaskParameter=\"Status\" PropertyName=\"Status\" />\n    </CheckSkipStrongNamesStatus>\n    <Message Text=\"SkipStrongNames: $(Status)\" Importance=\"High\" />\n  </Target>\n\n  <Target Name=\"DisableSkipStrongNames\" DependsOnTargets=\"RestoreSkipStrongNames\">\n    <Exec Command='\"$(SkipStrongNamesExe)\" -d \"$(SkipStrongNamesXml)\"' />\n    <CheckSkipStrongNamesStatus AssembliesFile=\"$(SkipStrongNamesXml)\">\n      <Output TaskParameter=\"Status\" PropertyName=\"Status\" />\n    </CheckSkipStrongNamesStatus>\n    <Message Text=\"SkipStrongNames: $(Status)\" Importance=\"High\" />\n  </Target>\n\n  <Target Name=\"Integration\" DependsOnTargets=\"Clean;Build;UnitTest\" />\n\n  <Target Name=\"Clean\">\n    <MSBuild\n        Projects=\"Runtime.sln\"\n        Targets=\"Clean\"\n        Properties=\"Configuration=$(Configuration);VisualStudioVersion=$(VisualStudioVersion)\" />\n    <RemoveDir Directories=\"bin\\$(Configuration)\" />\n  </Target>\n\n  <Target Name=\"DownloadNuGet\">\n    <DownloadNuGet OutputFileName=\"$(NuGetExe)\" MinimumVersion=\"2.12.0\" />\n  </Target>\n\n  <Target Name=\"RestoreSkipStrongNames\" DependsOnTargets=\"DownloadNuGet\">\n    <Exec Command='\"$(NuGetExe)\" restore .nuget\\packages.config -PackagesDirectory packages -NonInteractive -Verbosity quiet' />\n  </Target>\n\n  <ItemGroup>\n    <_Testing_NetStandard1_3 Include=\"true;false\" />\n  </ItemGroup>\n\n  <Target Name=\"RestorePackages\" DependsOnTargets=\"DownloadNuGet\">\n    <Message Text=\"%0ARestoring NuGet packages...\" Importance=\"High\" />\n\n    <!--\n      Pre-restore Microsoft.TestCommon due to the many dependencies on this project. Batch it to cover the full\n      set of references. Remove $(Platform) to avoid 'Any CPU' appearing in output paths. Can always restore in\n      parallel because $(Testing_NetStandard1_3) changes both obj/ and bin/ folders entirely.\n    -->\n    <MSBuild Projects=\"test\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\" Targets=\"Restore\"\n      BuildInParallel=\"true\"\n      Properties=\"Configuration=$(Configuration);CodeAnalysis=$(CodeAnalysis);StyleCopEnabled=$(StyleCopEnabled);\n                  RestorePackagesConfig=true;VisualStudioVersion=$(VisualStudioVersion);\n                  Testing_NetStandard1_3=%(_Testing_NetStandard1_3.Identity)\"\n      RemoveProperties=\"Platform\" />\n\n    <MSBuild Projects=\"Runtime.sln\" Targets=\"Restore\"\n      BuildInParallel=\"$(RestoreInParallel)\"\n      Properties=\"Configuration=$(Configuration);CodeAnalysis=$(CodeAnalysis);StyleCopEnabled=$(StyleCopEnabled);\n                  RestorePackagesConfig=true;VisualStudioVersion=$(VisualStudioVersion)\" />\n    <Message Importance=\"High\" Text=\"\" />\n  </Target>\n\n  <!-- Pick the right Microsoft.Web.FxCop package to use and copy it to a standard location. -->\n  <Target Name=\"BuildTools\">\n    <PropertyGroup>\n        <FxCopProjectLocation>$(MSBuildThisFileDirectory)tools\\src\\Microsoft.Web.FxCop\\</FxCopProjectLocation>\n        <CustomFxCopRulesPath>$(MSBuildThisFileDirectory)packages\\CustomFxCopRules</CustomFxCopRulesPath>\n    </PropertyGroup>\n    <MSBuild\n        Condition=\" '$(CodeAnalysis)' == 'true' \"\n        Projects=\"$(FxCopProjectLocation)\\Microsoft.Web.FxCop.csproj\"\n        Properties=\"Configuration=Release;OutputPath=$(CustomFxCopRulesPath)\" />\n  </Target>\n\n  <Target Name=\"Build\" DependsOnTargets=\"RestoreSkipStrongNames;RestorePackages;BuildTools\">\n    <Error Condition=\" '$(CodeAnalysis)' == 'true' and '$(Configuration)' == 'Release' \"\n      Text=\"Unable to run code analysis in Release configuration. Release assemblies do not include SuppressMessage attributes (so code analysis would always fail with the errors that are normally suppressed).\" />\n    <MakeDir Directories=\"bin\\$(Configuration)\" />\n\n    <!--\n      Prebuild Microsoft.TestCommon due to the many dependencies on this project. Batch it to cover the full\n      set of references. Remove $(Platform) to avoid 'Any CPU' appearing in output paths. Can always build in\n      parallel because $(Testing_NetStandard1_3) changes both obj/ and bin/ folders entirely.\n    -->\n    <MSBuild Projects=\"test\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\" Targets=\"Build\"\n      BuildInParallel=\"true\"\n      Properties=\"Configuration=$(Configuration);CodeAnalysis=$(CodeAnalysis);StyleCopEnabled=$(StyleCopEnabled);\n                  VisualStudioVersion=$(VisualStudioVersion);\n                  Testing_NetStandard1_3=%(_Testing_NetStandard1_3.Identity)\"\n      RemoveProperties=\"Platform\" />\n\n    <MSBuild\n        Projects=\"Runtime.sln\"\n        BuildInParallel=\"$(BuildInParallel)\"\n        Targets=\"Build\"\n        Properties=\"Configuration=$(Configuration);CodeAnalysis=$(CodeAnalysis);StyleCopEnabled=$(StyleCopEnabled);\n                    VisualStudioVersion=$(VisualStudioVersion)\" />\n  </Target>\n\n  <Target Name=\"UnitTest\" DependsOnTargets=\"Build;PrintTestRunSummary\" />\n\n  <Target Name=\"RunTests\" DependsOnTargets=\"CheckSkipStrongNames\">\n    <ItemGroup>\n      <_TestDLLsXunit Include=\"bin\\$(Configuration)\\test\\*.Test.dll;\n                               bin\\$(Configuration)\\test\\*\\net4*\\*.Test.dll\" />\n      <_XunitProject Include=\"tools\\WebStack.testing.targets\">\n        <Properties>TestAssembly=%(_TestDLLsXunit.FullPath);\n          XmlPath=$(TestResultsDirectory)%(_TestDLLsXunit.FileName)-XunitResults.xml</Properties>\n      </_XunitProject>\n\n      <_VSTestDLLs Include=\"bin\\$(Configuration)\\test\\ns1_3\\**\\*.Test.dll;\n                            bin\\$(Configuration)\\test\\ns2_0\\**\\*.Test.dll\"\n          Exclude=\"bin\\$(Configuration)\\test\\*\\net4*\\*.Test.dll\" />\n      <_XunitProject Include=\"tools\\WebStack.testing.targets\">\n        <Properties>TestAssembly=%(_VSTestDLLs.FullPath);\n          XmlPath=$(TestResultsDirectory)%(_VSTestDLLs.FileName)-$([System.String]::Copy('%(_VSTestDLLs.RecursiveDir)').Trim('\\\\'))-XunitResults.xml;\n          UseVSTest=true</Properties>\n      </_XunitProject>\n    </ItemGroup>\n\n    <!-- Recreate the test results directory so that print summary doesn't run on old test results. -->\n    <RemoveDir Directories=\"$(TestResultsDirectory)\" />\n    <MakeDir Directories=\"$(TestResultsDirectory)\" />\n\n    <MSBuild Projects=\"@(_XunitProject)\" BuildInParallel=\"$(TestInParallel)\" Targets=\"TestAssembly\">\n      <Output TaskParameter=\"TargetOutputs\" ItemName=\"_ExitCodes\" />\n    </MSBuild>\n  </Target>\n\n  <Target Name=\"CheckSkipStrongNames\" DependsOnTargets=\"RestoreSkipStrongNames\">\n    <CheckSkipStrongNamesStatus AssembliesFile=\"$(SkipStrongNamesXml)\">\n      <Output TaskParameter=\"Status\" PropertyName=\"Status\" />\n    </CheckSkipStrongNamesStatus>\n    <Error Text=\"Unit tests will not run correctly unless SkipStrongNames is Enabled. Current status: $(Status). Run build.cmd EnableSkipStrongNames to fix this problem.\" Condition=\"'$(Status)' != 'Enabled'\" />\n  </Target>\n\n  <Target Name=\"PrintTestRunSummary\" DependsOnTargets=\"RunTests\">\n    <PrintTestRunSummary TestResultsDirectory=\"$(TestResultsDirectory)\" />\n\n    <!-- PrintTestRunSummary stops MSBuild if tests failed. But the Xunit target may fail for other reasons... -->\n    <Error Text=\"Testing failed with exit code '%(Code)':%0A@(_ExitCodes -> '  %(Identity)', '%0A')\"\n        Condition=\" '%(Code)' != '0' \" />\n  </Target>\n</Project>\n"
  },
  {
    "path": "Runtime.sln",
    "content": "﻿\r\nMicrosoft Visual Studio Solution File, Format Version 12.00\r\n# Visual Studio 15\r\nVisualStudioVersion = 15.0.27016.1\r\nMinimumVisualStudioVersion = 15.0\r\nProject(\"{2150E333-8FDC-42A3-9474-1A3956D46DE8}\") = \"src\", \"src\", \"{A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}\"\r\nEndProject\r\nProject(\"{2150E333-8FDC-42A3-9474-1A3956D46DE8}\") = \"test\", \"test\", \"{C40883CD-366D-4534-8B58-3EA0D13136DF}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.Razor\", \"src\\System.Web.Razor\\System.Web.Razor.csproj\", \"{8F18041B-9410-4C36-A9C5-067813DF5F31}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.WebPages.Deployment\", \"src\\System.Web.WebPages.Deployment\\System.Web.WebPages.Deployment.csproj\", \"{22BABB60-8F02-4027-AFFC-ACF069954536}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.WebPages\", \"src\\System.Web.WebPages\\System.Web.WebPages.csproj\", \"{76EFA9C5-8D7E-4FDF-B710-E20F8B6B00D2}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.Helpers\", \"src\\System.Web.Helpers\\System.Web.Helpers.csproj\", \"{9B7E3740-6161-4548-833C-4BBCA43B970E}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.WebPages.Razor\", \"src\\System.Web.WebPages.Razor\\System.Web.WebPages.Razor.csproj\", \"{0939B11A-FE4E-4BA1-8AD6-D97741EE314F}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"WebMatrix.Data\", \"src\\WebMatrix.Data\\WebMatrix.Data.csproj\", \"{4D39BAAF-8A96-473E-AB79-C8A341885137}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"WebMatrix.WebData\", \"src\\WebMatrix.WebData\\WebMatrix.WebData.csproj\", \"{55A15F40-1435-4248-A7F2-2A146BB83586}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"Microsoft.Web.Helpers\", \"src\\Microsoft.Web.Helpers\\Microsoft.Web.Helpers.csproj\", \"{0C7CE809-0F72-4C19-8C64-D6573E4D9521}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.WebPages.Administration\", \"src\\System.Web.WebPages.Administration\\System.Web.WebPages.Administration.csproj\", \"{C23F02FC-4538-43F5-ABBA-38BA069AEA8F}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.Mvc\", \"src\\System.Web.Mvc\\System.Web.Mvc.csproj\", \"{3D3FFD8A-624D-4E9B-954B-E1C105507975}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"Microsoft.Web.Mvc\", \"src\\Microsoft.Web.Mvc\\Microsoft.Web.Mvc.csproj\", \"{D3CF7430-6DA4-42B0-BD90-CA39D16687B2}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.Razor.Test\", \"test\\System.Web.Razor.Test\\System.Web.Razor.Test.csproj\", \"{0BB62A1D-E6B5-49FA-9E3C-6AF679A66DFE}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.WebPages.Deployment.Test\", \"test\\System.Web.WebPages.Deployment.Test\\System.Web.WebPages.Deployment.Test.csproj\", \"{268DEE9D-F323-4A00-8ED8-3784388C3E3A}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.WebPages.Test\", \"test\\System.Web.WebPages.Test\\System.Web.WebPages.Test.csproj\", \"{0F4870DB-A799-4DBA-99DF-0D74BB52FEC2}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.Helpers.Test\", \"test\\System.Web.Helpers.Test\\System.Web.Helpers.Test.csproj\", \"{D3313BDF-8071-4AC8-9D98-ABF7F9E88A57}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.WebPages.Razor.Test\", \"test\\System.Web.WebPages.Razor.Test\\System.Web.WebPages.Razor.Test.csproj\", \"{66A74F3C-A106-4C1E-BAA0-001908FEA2CA}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"WebMatrix.Data.Test\", \"test\\WebMatrix.Data.Test\\WebMatrix.Data.Test.csproj\", \"{E2D008A9-4D1D-4F6B-8325-4ED717D6EA0A}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"WebMatrix.WebData.Test\", \"test\\WebMatrix.WebData.Test\\WebMatrix.WebData.Test.csproj\", \"{CD48EB41-92A5-4628-A0F7-6A43DF58827E}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"Microsoft.Web.Helpers.Test\", \"test\\Microsoft.Web.Helpers.Test\\Microsoft.Web.Helpers.Test.csproj\", \"{2C653A66-8159-4A41-954F-A67915DFDA87}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.WebPages.Administration.Test\", \"test\\System.Web.WebPages.Administration.Test\\System.Web.WebPages.Administration.Test.csproj\", \"{21C729D6-ECF8-47EF-A236-7C6A4272EAF0}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.Mvc.Test\", \"test\\System.Web.Mvc.Test\\System.Web.Mvc.Test.csproj\", \"{8AC2A2E4-2F11-4D40-A887-62E2583A65E6}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"Microsoft.Web.Mvc.Test\", \"test\\Microsoft.Web.Mvc.Test\\Microsoft.Web.Mvc.Test.csproj\", \"{6C28DA70-60F1-4442-967F-591BF3962EC5}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.Http\", \"src\\System.Web.Http\\System.Web.Http.csproj\", \"{DDC1CE0C-486E-4E35-BB3B-EAB61F8F9440}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.Http.Test\", \"test\\System.Web.Http.Test\\System.Web.Http.Test.csproj\", \"{7F2C796F-43B2-4F8F-ABFF-A154EC8AAFA1}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Net.Http.Formatting\", \"src\\System.Net.Http.Formatting\\System.Net.Http.Formatting.csproj\", \"{668E9021-CE84-49D9-98FB-DF125A9FCDB0}\"\r\nEndProject\r\nProject(\"{9A19103F-16F7-4668-BE54-9A1E7A4F7556}\") = \"Microsoft.TestCommon\", \"test\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\", \"{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}\"\r\nEndProject\r\nProject(\"{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}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.Http.SelfHost\", \"src\\System.Web.Http.SelfHost\\System.Web.Http.SelfHost.csproj\", \"{66492E69-CE4C-4FB1-9B1F-88DEE09D06F1}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.Http.WebHost\", \"src\\System.Web.Http.WebHost\\System.Web.Http.WebHost.csproj\", \"{A0187BC2-8325-4BB2-8697-7F955CF4173E}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.Http.Integration.Test\", \"test\\System.Web.Http.Integration.Test\\System.Web.Http.Integration.Test.csproj\", \"{3267DFC6-B34D-4011-BC0F-D3B56AF6F608}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.Http.WebHost.Test\", \"test\\System.Web.Http.WebHost.Test\\System.Web.Http.WebHost.Test.csproj\", \"{EA62944F-BD25-4730-9405-9BE8FF5BEACD}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"Microsoft.Web.WebPages.OAuth\", \"src\\Microsoft.Web.WebPages.OAuth\\Microsoft.Web.WebPages.OAuth.csproj\", \"{4CBFC7D3-1600-4CE5-BC6B-AC7BC2D6F853}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"Microsoft.Web.WebPages.OAuth.Test\", \"test\\Microsoft.Web.WebPages.OAuth.Test\\Microsoft.Web.WebPages.OAuth.Test.csproj\", \"{694C6EDF-EA52-438F-B745-82B025ECC0E7}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.Http.SelfHost.Test\", \"test\\System.Web.Http.SelfHost.Test\\System.Web.Http.SelfHost.Test.csproj\", \"{7F29EE87-6A63-43C6-B7FF-74DD06815830}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"WebApiHelpPage\", \"src\\WebApiHelpPage\\WebApiHelpPage.csproj\", \"{FEDFE6CA-8282-4C5B-A756-E97189690982}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"WebApiHelpPage.Test\", \"test\\WebApiHelpPage.Test\\WebApiHelpPage.Test.csproj\", \"{291EF478-BF24-4935-BC78-E0DCCD0C9A1B}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.Http.Tracing\", \"src\\System.Web.Http.Tracing\\System.Web.Http.Tracing.csproj\", \"{6E81EF98-8F5C-4EED-8B37-456991CA56FD}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.Http.Tracing.Test\", \"test\\System.Web.Http.Tracing.Test\\System.Web.Http.Tracing.Test.csproj\", \"{F87FD911-4A97-4057-8EAE-1CB96B9A1937}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.Http.SignalR\", \"src\\System.Web.Http.SignalR\\System.Web.Http.SignalR.csproj\", \"{8A607AC9-E7DD-4B74-A0B1-47FC95B9838B}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.Http.SignalR.Test\", \"test\\System.Web.Http.SignalR.Test\\System.Web.Http.SignalR.Test.csproj\", \"{E22245AF-D5E1-46F6-B443-C886983EC50C}\"\r\nEndProject\r\nProject(\"{F184B08F-C81C-45F6-A57F-5ABD9991F28F}\") = \"WebApiHelpPageVB\", \"src\\WebApiHelpPage\\VB\\WebApiHelpPageVB.vbproj\", \"{22075D5A-E9A1-4E2D-ABA7-8E7CBF2A049E}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"WebApiHelpPage.VB.Test\", \"test\\WebApiHelpPage.VB.Test\\WebApiHelpPage.VB.Test.csproj\", \"{41D5691F-2720-44A0-9185-EEFE928D2679}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.Http.Owin\", \"src\\System.Web.Http.Owin\\System.Web.Http.Owin.csproj\", \"{66DD7CD7-C68F-4D0E-9F3D-3B58C49D1467}\"\r\nEndProject\r\nProject(\"{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}\"\r\nEndProject\r\nProject(\"{2150E333-8FDC-42A3-9474-1A3956D46DE8}\") = \"Solution items\", \"Solution items\", \"{CB34D534-9A09-4EE4-B350-C1C23AFBF5EE}\"\r\n\tProjectSection(SolutionItems) = preProject\r\n\t\tglobal.json = global.json\r\n\t\tNuGet.Config = NuGet.Config\r\n\t\t.nuget\\packages.config = .nuget\\packages.config\r\n\tEndProjectSection\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.Cors\", \"src\\System.Web.Cors\\System.Web.Cors.csproj\", \"{43C1B979-D593-4A32-BB3A-4316F1C66D66}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.Http.Cors\", \"src\\System.Web.Http.Cors\\System.Web.Http.Cors.csproj\", \"{25DEF6F6-7F99-4EB7-91ED-5181A346AFE1}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.Cors.Test\", \"test\\System.Web.Cors.Test\\System.Web.Cors.Test.csproj\", \"{BF07E947-120D-4E93-93DA-A4BF121753EA}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"System.Web.Http.Cors.Test\", \"test\\System.Web.Http.Cors.Test\\System.Web.Http.Cors.Test.csproj\", \"{1E89A3E9-0A7F-418F-B4BE-6E38A6315373}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"Microsoft.AspNet.Facebook\", \"src\\Microsoft.AspNet.Facebook\\Microsoft.AspNet.Facebook.csproj\", \"{821A136C-7C6F-44C6-A9E6-C39B5BFB1483}\"\r\nEndProject\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"Microsoft.AspNet.Facebook.Test\", \"test\\Microsoft.AspNet.Facebook.Test\\Microsoft.AspNet.Facebook.Test.csproj\", \"{C3BEF382-C7C4-454D-B017-1EAC03E9A82C}\"\r\nEndProject\r\nProject(\"{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}\"\r\nEndProject\r\nProject(\"{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}\"\r\nEndProject\r\nProject(\"{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}\"\r\nEndProject\r\nProject(\"{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}\"\r\nEndProject\r\nGlobal\r\n\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\r\n\t\tCodeAnalysis|Any CPU = CodeAnalysis|Any CPU\r\n\t\tDebug|Any CPU = Debug|Any CPU\r\n\t\tRelease|Any CPU = Release|Any CPU\r\n\tEndGlobalSection\r\n\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\r\n\t\t{8F18041B-9410-4C36-A9C5-067813DF5F31}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{8F18041B-9410-4C36-A9C5-067813DF5F31}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{8F18041B-9410-4C36-A9C5-067813DF5F31}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{8F18041B-9410-4C36-A9C5-067813DF5F31}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{8F18041B-9410-4C36-A9C5-067813DF5F31}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{8F18041B-9410-4C36-A9C5-067813DF5F31}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{22BABB60-8F02-4027-AFFC-ACF069954536}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{22BABB60-8F02-4027-AFFC-ACF069954536}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{22BABB60-8F02-4027-AFFC-ACF069954536}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{22BABB60-8F02-4027-AFFC-ACF069954536}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{22BABB60-8F02-4027-AFFC-ACF069954536}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{22BABB60-8F02-4027-AFFC-ACF069954536}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{76EFA9C5-8D7E-4FDF-B710-E20F8B6B00D2}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{76EFA9C5-8D7E-4FDF-B710-E20F8B6B00D2}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{76EFA9C5-8D7E-4FDF-B710-E20F8B6B00D2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{76EFA9C5-8D7E-4FDF-B710-E20F8B6B00D2}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{76EFA9C5-8D7E-4FDF-B710-E20F8B6B00D2}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{76EFA9C5-8D7E-4FDF-B710-E20F8B6B00D2}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{9B7E3740-6161-4548-833C-4BBCA43B970E}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{9B7E3740-6161-4548-833C-4BBCA43B970E}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{9B7E3740-6161-4548-833C-4BBCA43B970E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{9B7E3740-6161-4548-833C-4BBCA43B970E}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{9B7E3740-6161-4548-833C-4BBCA43B970E}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{9B7E3740-6161-4548-833C-4BBCA43B970E}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{0939B11A-FE4E-4BA1-8AD6-D97741EE314F}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{0939B11A-FE4E-4BA1-8AD6-D97741EE314F}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{0939B11A-FE4E-4BA1-8AD6-D97741EE314F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{0939B11A-FE4E-4BA1-8AD6-D97741EE314F}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{0939B11A-FE4E-4BA1-8AD6-D97741EE314F}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{0939B11A-FE4E-4BA1-8AD6-D97741EE314F}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{4D39BAAF-8A96-473E-AB79-C8A341885137}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{4D39BAAF-8A96-473E-AB79-C8A341885137}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{4D39BAAF-8A96-473E-AB79-C8A341885137}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{4D39BAAF-8A96-473E-AB79-C8A341885137}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{4D39BAAF-8A96-473E-AB79-C8A341885137}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{4D39BAAF-8A96-473E-AB79-C8A341885137}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{55A15F40-1435-4248-A7F2-2A146BB83586}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{55A15F40-1435-4248-A7F2-2A146BB83586}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{55A15F40-1435-4248-A7F2-2A146BB83586}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{55A15F40-1435-4248-A7F2-2A146BB83586}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{55A15F40-1435-4248-A7F2-2A146BB83586}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{55A15F40-1435-4248-A7F2-2A146BB83586}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{0C7CE809-0F72-4C19-8C64-D6573E4D9521}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{0C7CE809-0F72-4C19-8C64-D6573E4D9521}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{0C7CE809-0F72-4C19-8C64-D6573E4D9521}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{0C7CE809-0F72-4C19-8C64-D6573E4D9521}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{0C7CE809-0F72-4C19-8C64-D6573E4D9521}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{0C7CE809-0F72-4C19-8C64-D6573E4D9521}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{C23F02FC-4538-43F5-ABBA-38BA069AEA8F}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{C23F02FC-4538-43F5-ABBA-38BA069AEA8F}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{C23F02FC-4538-43F5-ABBA-38BA069AEA8F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{C23F02FC-4538-43F5-ABBA-38BA069AEA8F}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{C23F02FC-4538-43F5-ABBA-38BA069AEA8F}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{C23F02FC-4538-43F5-ABBA-38BA069AEA8F}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{3D3FFD8A-624D-4E9B-954B-E1C105507975}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{3D3FFD8A-624D-4E9B-954B-E1C105507975}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{3D3FFD8A-624D-4E9B-954B-E1C105507975}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{3D3FFD8A-624D-4E9B-954B-E1C105507975}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{3D3FFD8A-624D-4E9B-954B-E1C105507975}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{3D3FFD8A-624D-4E9B-954B-E1C105507975}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{D3CF7430-6DA4-42B0-BD90-CA39D16687B2}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{D3CF7430-6DA4-42B0-BD90-CA39D16687B2}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{D3CF7430-6DA4-42B0-BD90-CA39D16687B2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{D3CF7430-6DA4-42B0-BD90-CA39D16687B2}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{D3CF7430-6DA4-42B0-BD90-CA39D16687B2}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{D3CF7430-6DA4-42B0-BD90-CA39D16687B2}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{0BB62A1D-E6B5-49FA-9E3C-6AF679A66DFE}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{0BB62A1D-E6B5-49FA-9E3C-6AF679A66DFE}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{0BB62A1D-E6B5-49FA-9E3C-6AF679A66DFE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{0BB62A1D-E6B5-49FA-9E3C-6AF679A66DFE}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{0BB62A1D-E6B5-49FA-9E3C-6AF679A66DFE}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{0BB62A1D-E6B5-49FA-9E3C-6AF679A66DFE}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{268DEE9D-F323-4A00-8ED8-3784388C3E3A}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{268DEE9D-F323-4A00-8ED8-3784388C3E3A}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{268DEE9D-F323-4A00-8ED8-3784388C3E3A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{268DEE9D-F323-4A00-8ED8-3784388C3E3A}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{268DEE9D-F323-4A00-8ED8-3784388C3E3A}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{268DEE9D-F323-4A00-8ED8-3784388C3E3A}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{0F4870DB-A799-4DBA-99DF-0D74BB52FEC2}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{0F4870DB-A799-4DBA-99DF-0D74BB52FEC2}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{0F4870DB-A799-4DBA-99DF-0D74BB52FEC2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{0F4870DB-A799-4DBA-99DF-0D74BB52FEC2}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{0F4870DB-A799-4DBA-99DF-0D74BB52FEC2}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{0F4870DB-A799-4DBA-99DF-0D74BB52FEC2}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{D3313BDF-8071-4AC8-9D98-ABF7F9E88A57}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{D3313BDF-8071-4AC8-9D98-ABF7F9E88A57}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{D3313BDF-8071-4AC8-9D98-ABF7F9E88A57}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{D3313BDF-8071-4AC8-9D98-ABF7F9E88A57}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{D3313BDF-8071-4AC8-9D98-ABF7F9E88A57}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{D3313BDF-8071-4AC8-9D98-ABF7F9E88A57}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{66A74F3C-A106-4C1E-BAA0-001908FEA2CA}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{66A74F3C-A106-4C1E-BAA0-001908FEA2CA}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{66A74F3C-A106-4C1E-BAA0-001908FEA2CA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{66A74F3C-A106-4C1E-BAA0-001908FEA2CA}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{66A74F3C-A106-4C1E-BAA0-001908FEA2CA}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{66A74F3C-A106-4C1E-BAA0-001908FEA2CA}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{E2D008A9-4D1D-4F6B-8325-4ED717D6EA0A}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{E2D008A9-4D1D-4F6B-8325-4ED717D6EA0A}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{E2D008A9-4D1D-4F6B-8325-4ED717D6EA0A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{E2D008A9-4D1D-4F6B-8325-4ED717D6EA0A}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{E2D008A9-4D1D-4F6B-8325-4ED717D6EA0A}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{E2D008A9-4D1D-4F6B-8325-4ED717D6EA0A}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{CD48EB41-92A5-4628-A0F7-6A43DF58827E}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{CD48EB41-92A5-4628-A0F7-6A43DF58827E}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{CD48EB41-92A5-4628-A0F7-6A43DF58827E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{CD48EB41-92A5-4628-A0F7-6A43DF58827E}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{CD48EB41-92A5-4628-A0F7-6A43DF58827E}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{CD48EB41-92A5-4628-A0F7-6A43DF58827E}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{2C653A66-8159-4A41-954F-A67915DFDA87}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{2C653A66-8159-4A41-954F-A67915DFDA87}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{2C653A66-8159-4A41-954F-A67915DFDA87}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{2C653A66-8159-4A41-954F-A67915DFDA87}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{2C653A66-8159-4A41-954F-A67915DFDA87}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{2C653A66-8159-4A41-954F-A67915DFDA87}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{21C729D6-ECF8-47EF-A236-7C6A4272EAF0}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{21C729D6-ECF8-47EF-A236-7C6A4272EAF0}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{21C729D6-ECF8-47EF-A236-7C6A4272EAF0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{21C729D6-ECF8-47EF-A236-7C6A4272EAF0}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{21C729D6-ECF8-47EF-A236-7C6A4272EAF0}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{21C729D6-ECF8-47EF-A236-7C6A4272EAF0}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{8AC2A2E4-2F11-4D40-A887-62E2583A65E6}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{8AC2A2E4-2F11-4D40-A887-62E2583A65E6}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{8AC2A2E4-2F11-4D40-A887-62E2583A65E6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{8AC2A2E4-2F11-4D40-A887-62E2583A65E6}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{8AC2A2E4-2F11-4D40-A887-62E2583A65E6}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{8AC2A2E4-2F11-4D40-A887-62E2583A65E6}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{6C28DA70-60F1-4442-967F-591BF3962EC5}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{6C28DA70-60F1-4442-967F-591BF3962EC5}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{6C28DA70-60F1-4442-967F-591BF3962EC5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{6C28DA70-60F1-4442-967F-591BF3962EC5}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{6C28DA70-60F1-4442-967F-591BF3962EC5}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{6C28DA70-60F1-4442-967F-591BF3962EC5}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{DDC1CE0C-486E-4E35-BB3B-EAB61F8F9440}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{DDC1CE0C-486E-4E35-BB3B-EAB61F8F9440}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{DDC1CE0C-486E-4E35-BB3B-EAB61F8F9440}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{DDC1CE0C-486E-4E35-BB3B-EAB61F8F9440}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{DDC1CE0C-486E-4E35-BB3B-EAB61F8F9440}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{DDC1CE0C-486E-4E35-BB3B-EAB61F8F9440}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{7F2C796F-43B2-4F8F-ABFF-A154EC8AAFA1}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{7F2C796F-43B2-4F8F-ABFF-A154EC8AAFA1}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{7F2C796F-43B2-4F8F-ABFF-A154EC8AAFA1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{7F2C796F-43B2-4F8F-ABFF-A154EC8AAFA1}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{7F2C796F-43B2-4F8F-ABFF-A154EC8AAFA1}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{7F2C796F-43B2-4F8F-ABFF-A154EC8AAFA1}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{668E9021-CE84-49D9-98FB-DF125A9FCDB0}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{668E9021-CE84-49D9-98FB-DF125A9FCDB0}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{668E9021-CE84-49D9-98FB-DF125A9FCDB0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{668E9021-CE84-49D9-98FB-DF125A9FCDB0}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{668E9021-CE84-49D9-98FB-DF125A9FCDB0}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{668E9021-CE84-49D9-98FB-DF125A9FCDB0}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{7AF77741-9158-4D5F-8782-8F21FADF025F}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{7AF77741-9158-4D5F-8782-8F21FADF025F}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{7AF77741-9158-4D5F-8782-8F21FADF025F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{7AF77741-9158-4D5F-8782-8F21FADF025F}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{7AF77741-9158-4D5F-8782-8F21FADF025F}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{7AF77741-9158-4D5F-8782-8F21FADF025F}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{66492E69-CE4C-4FB1-9B1F-88DEE09D06F1}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{66492E69-CE4C-4FB1-9B1F-88DEE09D06F1}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{66492E69-CE4C-4FB1-9B1F-88DEE09D06F1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{66492E69-CE4C-4FB1-9B1F-88DEE09D06F1}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{66492E69-CE4C-4FB1-9B1F-88DEE09D06F1}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{66492E69-CE4C-4FB1-9B1F-88DEE09D06F1}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{A0187BC2-8325-4BB2-8697-7F955CF4173E}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{A0187BC2-8325-4BB2-8697-7F955CF4173E}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{A0187BC2-8325-4BB2-8697-7F955CF4173E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{A0187BC2-8325-4BB2-8697-7F955CF4173E}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{A0187BC2-8325-4BB2-8697-7F955CF4173E}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{A0187BC2-8325-4BB2-8697-7F955CF4173E}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{3267DFC6-B34D-4011-BC0F-D3B56AF6F608}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{3267DFC6-B34D-4011-BC0F-D3B56AF6F608}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{3267DFC6-B34D-4011-BC0F-D3B56AF6F608}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{3267DFC6-B34D-4011-BC0F-D3B56AF6F608}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{3267DFC6-B34D-4011-BC0F-D3B56AF6F608}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{3267DFC6-B34D-4011-BC0F-D3B56AF6F608}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{EA62944F-BD25-4730-9405-9BE8FF5BEACD}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{EA62944F-BD25-4730-9405-9BE8FF5BEACD}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{EA62944F-BD25-4730-9405-9BE8FF5BEACD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{EA62944F-BD25-4730-9405-9BE8FF5BEACD}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{EA62944F-BD25-4730-9405-9BE8FF5BEACD}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{EA62944F-BD25-4730-9405-9BE8FF5BEACD}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{4CBFC7D3-1600-4CE5-BC6B-AC7BC2D6F853}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{4CBFC7D3-1600-4CE5-BC6B-AC7BC2D6F853}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{4CBFC7D3-1600-4CE5-BC6B-AC7BC2D6F853}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{4CBFC7D3-1600-4CE5-BC6B-AC7BC2D6F853}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{4CBFC7D3-1600-4CE5-BC6B-AC7BC2D6F853}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{4CBFC7D3-1600-4CE5-BC6B-AC7BC2D6F853}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{694C6EDF-EA52-438F-B745-82B025ECC0E7}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{694C6EDF-EA52-438F-B745-82B025ECC0E7}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{694C6EDF-EA52-438F-B745-82B025ECC0E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{694C6EDF-EA52-438F-B745-82B025ECC0E7}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{694C6EDF-EA52-438F-B745-82B025ECC0E7}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{694C6EDF-EA52-438F-B745-82B025ECC0E7}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{7F29EE87-6A63-43C6-B7FF-74DD06815830}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{7F29EE87-6A63-43C6-B7FF-74DD06815830}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{7F29EE87-6A63-43C6-B7FF-74DD06815830}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{7F29EE87-6A63-43C6-B7FF-74DD06815830}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{7F29EE87-6A63-43C6-B7FF-74DD06815830}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{7F29EE87-6A63-43C6-B7FF-74DD06815830}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{FEDFE6CA-8282-4C5B-A756-E97189690982}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{FEDFE6CA-8282-4C5B-A756-E97189690982}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{FEDFE6CA-8282-4C5B-A756-E97189690982}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{FEDFE6CA-8282-4C5B-A756-E97189690982}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{FEDFE6CA-8282-4C5B-A756-E97189690982}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{FEDFE6CA-8282-4C5B-A756-E97189690982}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{291EF478-BF24-4935-BC78-E0DCCD0C9A1B}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{291EF478-BF24-4935-BC78-E0DCCD0C9A1B}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{291EF478-BF24-4935-BC78-E0DCCD0C9A1B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{291EF478-BF24-4935-BC78-E0DCCD0C9A1B}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{291EF478-BF24-4935-BC78-E0DCCD0C9A1B}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{291EF478-BF24-4935-BC78-E0DCCD0C9A1B}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{6E81EF98-8F5C-4EED-8B37-456991CA56FD}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{6E81EF98-8F5C-4EED-8B37-456991CA56FD}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{6E81EF98-8F5C-4EED-8B37-456991CA56FD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{6E81EF98-8F5C-4EED-8B37-456991CA56FD}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{6E81EF98-8F5C-4EED-8B37-456991CA56FD}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{6E81EF98-8F5C-4EED-8B37-456991CA56FD}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{F87FD911-4A97-4057-8EAE-1CB96B9A1937}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{F87FD911-4A97-4057-8EAE-1CB96B9A1937}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{F87FD911-4A97-4057-8EAE-1CB96B9A1937}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{F87FD911-4A97-4057-8EAE-1CB96B9A1937}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{F87FD911-4A97-4057-8EAE-1CB96B9A1937}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{F87FD911-4A97-4057-8EAE-1CB96B9A1937}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{8A607AC9-E7DD-4B74-A0B1-47FC95B9838B}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{8A607AC9-E7DD-4B74-A0B1-47FC95B9838B}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{8A607AC9-E7DD-4B74-A0B1-47FC95B9838B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{8A607AC9-E7DD-4B74-A0B1-47FC95B9838B}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{8A607AC9-E7DD-4B74-A0B1-47FC95B9838B}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{8A607AC9-E7DD-4B74-A0B1-47FC95B9838B}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{E22245AF-D5E1-46F6-B443-C886983EC50C}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{E22245AF-D5E1-46F6-B443-C886983EC50C}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{E22245AF-D5E1-46F6-B443-C886983EC50C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{E22245AF-D5E1-46F6-B443-C886983EC50C}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{E22245AF-D5E1-46F6-B443-C886983EC50C}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{E22245AF-D5E1-46F6-B443-C886983EC50C}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{22075D5A-E9A1-4E2D-ABA7-8E7CBF2A049E}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{22075D5A-E9A1-4E2D-ABA7-8E7CBF2A049E}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{22075D5A-E9A1-4E2D-ABA7-8E7CBF2A049E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{22075D5A-E9A1-4E2D-ABA7-8E7CBF2A049E}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{22075D5A-E9A1-4E2D-ABA7-8E7CBF2A049E}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{22075D5A-E9A1-4E2D-ABA7-8E7CBF2A049E}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{41D5691F-2720-44A0-9185-EEFE928D2679}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{41D5691F-2720-44A0-9185-EEFE928D2679}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{41D5691F-2720-44A0-9185-EEFE928D2679}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{41D5691F-2720-44A0-9185-EEFE928D2679}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{41D5691F-2720-44A0-9185-EEFE928D2679}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{41D5691F-2720-44A0-9185-EEFE928D2679}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{66DD7CD7-C68F-4D0E-9F3D-3B58C49D1467}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{66DD7CD7-C68F-4D0E-9F3D-3B58C49D1467}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{66DD7CD7-C68F-4D0E-9F3D-3B58C49D1467}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{66DD7CD7-C68F-4D0E-9F3D-3B58C49D1467}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{66DD7CD7-C68F-4D0E-9F3D-3B58C49D1467}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{66DD7CD7-C68F-4D0E-9F3D-3B58C49D1467}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{C19267DD-3984-430C-AE18-4034F85DE4E5}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{C19267DD-3984-430C-AE18-4034F85DE4E5}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{C19267DD-3984-430C-AE18-4034F85DE4E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{C19267DD-3984-430C-AE18-4034F85DE4E5}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{C19267DD-3984-430C-AE18-4034F85DE4E5}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{C19267DD-3984-430C-AE18-4034F85DE4E5}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{43C1B979-D593-4A32-BB3A-4316F1C66D66}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{43C1B979-D593-4A32-BB3A-4316F1C66D66}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{43C1B979-D593-4A32-BB3A-4316F1C66D66}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{43C1B979-D593-4A32-BB3A-4316F1C66D66}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{43C1B979-D593-4A32-BB3A-4316F1C66D66}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{43C1B979-D593-4A32-BB3A-4316F1C66D66}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{25DEF6F6-7F99-4EB7-91ED-5181A346AFE1}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{25DEF6F6-7F99-4EB7-91ED-5181A346AFE1}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{25DEF6F6-7F99-4EB7-91ED-5181A346AFE1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{25DEF6F6-7F99-4EB7-91ED-5181A346AFE1}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{25DEF6F6-7F99-4EB7-91ED-5181A346AFE1}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{25DEF6F6-7F99-4EB7-91ED-5181A346AFE1}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{BF07E947-120D-4E93-93DA-A4BF121753EA}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{BF07E947-120D-4E93-93DA-A4BF121753EA}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{BF07E947-120D-4E93-93DA-A4BF121753EA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{BF07E947-120D-4E93-93DA-A4BF121753EA}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{BF07E947-120D-4E93-93DA-A4BF121753EA}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{BF07E947-120D-4E93-93DA-A4BF121753EA}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{1E89A3E9-0A7F-418F-B4BE-6E38A6315373}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{1E89A3E9-0A7F-418F-B4BE-6E38A6315373}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{1E89A3E9-0A7F-418F-B4BE-6E38A6315373}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{1E89A3E9-0A7F-418F-B4BE-6E38A6315373}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{1E89A3E9-0A7F-418F-B4BE-6E38A6315373}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{1E89A3E9-0A7F-418F-B4BE-6E38A6315373}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{821A136C-7C6F-44C6-A9E6-C39B5BFB1483}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{821A136C-7C6F-44C6-A9E6-C39B5BFB1483}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{821A136C-7C6F-44C6-A9E6-C39B5BFB1483}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{821A136C-7C6F-44C6-A9E6-C39B5BFB1483}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{821A136C-7C6F-44C6-A9E6-C39B5BFB1483}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{821A136C-7C6F-44C6-A9E6-C39B5BFB1483}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{C3BEF382-C7C4-454D-B017-1EAC03E9A82C}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{C3BEF382-C7C4-454D-B017-1EAC03E9A82C}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{C3BEF382-C7C4-454D-B017-1EAC03E9A82C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{C3BEF382-C7C4-454D-B017-1EAC03E9A82C}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{C3BEF382-C7C4-454D-B017-1EAC03E9A82C}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{C3BEF382-C7C4-454D-B017-1EAC03E9A82C}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{5ABD9968-F3A3-4967-B768-A6142F69759E}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{5ABD9968-F3A3-4967-B768-A6142F69759E}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{5ABD9968-F3A3-4967-B768-A6142F69759E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{5ABD9968-F3A3-4967-B768-A6142F69759E}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{5ABD9968-F3A3-4967-B768-A6142F69759E}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{5ABD9968-F3A3-4967-B768-A6142F69759E}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{9AAFB58C-B8C1-4D7F-80E6-7B95C94A829B}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{9AAFB58C-B8C1-4D7F-80E6-7B95C94A829B}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{9AAFB58C-B8C1-4D7F-80E6-7B95C94A829B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{9AAFB58C-B8C1-4D7F-80E6-7B95C94A829B}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{9AAFB58C-B8C1-4D7F-80E6-7B95C94A829B}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{9AAFB58C-B8C1-4D7F-80E6-7B95C94A829B}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{A1A20049-04C2-4676-93CF-92449C4BBAA9}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{A1A20049-04C2-4676-93CF-92449C4BBAA9}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{A1A20049-04C2-4676-93CF-92449C4BBAA9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{A1A20049-04C2-4676-93CF-92449C4BBAA9}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{A1A20049-04C2-4676-93CF-92449C4BBAA9}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{A1A20049-04C2-4676-93CF-92449C4BBAA9}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\t\t{6C320AD9-F380-4F8B-85F9-0689F88766EC}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU\r\n\t\t{6C320AD9-F380-4F8B-85F9-0689F88766EC}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU\r\n\t\t{6C320AD9-F380-4F8B-85F9-0689F88766EC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{6C320AD9-F380-4F8B-85F9-0689F88766EC}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{6C320AD9-F380-4F8B-85F9-0689F88766EC}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{6C320AD9-F380-4F8B-85F9-0689F88766EC}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\tEndGlobalSection\r\n\tGlobalSection(SolutionProperties) = preSolution\r\n\t\tHideSolutionNode = FALSE\r\n\tEndGlobalSection\r\n\tGlobalSection(NestedProjects) = preSolution\r\n\t\t{8F18041B-9410-4C36-A9C5-067813DF5F31} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}\r\n\t\t{22BABB60-8F02-4027-AFFC-ACF069954536} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}\r\n\t\t{76EFA9C5-8D7E-4FDF-B710-E20F8B6B00D2} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}\r\n\t\t{9B7E3740-6161-4548-833C-4BBCA43B970E} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}\r\n\t\t{0939B11A-FE4E-4BA1-8AD6-D97741EE314F} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}\r\n\t\t{4D39BAAF-8A96-473E-AB79-C8A341885137} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}\r\n\t\t{55A15F40-1435-4248-A7F2-2A146BB83586} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}\r\n\t\t{0C7CE809-0F72-4C19-8C64-D6573E4D9521} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}\r\n\t\t{C23F02FC-4538-43F5-ABBA-38BA069AEA8F} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}\r\n\t\t{3D3FFD8A-624D-4E9B-954B-E1C105507975} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}\r\n\t\t{D3CF7430-6DA4-42B0-BD90-CA39D16687B2} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}\r\n\t\t{0BB62A1D-E6B5-49FA-9E3C-6AF679A66DFE} = {C40883CD-366D-4534-8B58-3EA0D13136DF}\r\n\t\t{268DEE9D-F323-4A00-8ED8-3784388C3E3A} = {C40883CD-366D-4534-8B58-3EA0D13136DF}\r\n\t\t{0F4870DB-A799-4DBA-99DF-0D74BB52FEC2} = {C40883CD-366D-4534-8B58-3EA0D13136DF}\r\n\t\t{D3313BDF-8071-4AC8-9D98-ABF7F9E88A57} = {C40883CD-366D-4534-8B58-3EA0D13136DF}\r\n\t\t{66A74F3C-A106-4C1E-BAA0-001908FEA2CA} = {C40883CD-366D-4534-8B58-3EA0D13136DF}\r\n\t\t{E2D008A9-4D1D-4F6B-8325-4ED717D6EA0A} = {C40883CD-366D-4534-8B58-3EA0D13136DF}\r\n\t\t{CD48EB41-92A5-4628-A0F7-6A43DF58827E} = {C40883CD-366D-4534-8B58-3EA0D13136DF}\r\n\t\t{2C653A66-8159-4A41-954F-A67915DFDA87} = {C40883CD-366D-4534-8B58-3EA0D13136DF}\r\n\t\t{21C729D6-ECF8-47EF-A236-7C6A4272EAF0} = {C40883CD-366D-4534-8B58-3EA0D13136DF}\r\n\t\t{8AC2A2E4-2F11-4D40-A887-62E2583A65E6} = {C40883CD-366D-4534-8B58-3EA0D13136DF}\r\n\t\t{6C28DA70-60F1-4442-967F-591BF3962EC5} = {C40883CD-366D-4534-8B58-3EA0D13136DF}\r\n\t\t{DDC1CE0C-486E-4E35-BB3B-EAB61F8F9440} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}\r\n\t\t{7F2C796F-43B2-4F8F-ABFF-A154EC8AAFA1} = {C40883CD-366D-4534-8B58-3EA0D13136DF}\r\n\t\t{668E9021-CE84-49D9-98FB-DF125A9FCDB0} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}\r\n\t\t{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0} = {C40883CD-366D-4534-8B58-3EA0D13136DF}\r\n\t\t{7AF77741-9158-4D5F-8782-8F21FADF025F} = {C40883CD-366D-4534-8B58-3EA0D13136DF}\r\n\t\t{66492E69-CE4C-4FB1-9B1F-88DEE09D06F1} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}\r\n\t\t{A0187BC2-8325-4BB2-8697-7F955CF4173E} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}\r\n\t\t{3267DFC6-B34D-4011-BC0F-D3B56AF6F608} = {C40883CD-366D-4534-8B58-3EA0D13136DF}\r\n\t\t{EA62944F-BD25-4730-9405-9BE8FF5BEACD} = {C40883CD-366D-4534-8B58-3EA0D13136DF}\r\n\t\t{4CBFC7D3-1600-4CE5-BC6B-AC7BC2D6F853} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}\r\n\t\t{694C6EDF-EA52-438F-B745-82B025ECC0E7} = {C40883CD-366D-4534-8B58-3EA0D13136DF}\r\n\t\t{7F29EE87-6A63-43C6-B7FF-74DD06815830} = {C40883CD-366D-4534-8B58-3EA0D13136DF}\r\n\t\t{FEDFE6CA-8282-4C5B-A756-E97189690982} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}\r\n\t\t{291EF478-BF24-4935-BC78-E0DCCD0C9A1B} = {C40883CD-366D-4534-8B58-3EA0D13136DF}\r\n\t\t{6E81EF98-8F5C-4EED-8B37-456991CA56FD} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}\r\n\t\t{F87FD911-4A97-4057-8EAE-1CB96B9A1937} = {C40883CD-366D-4534-8B58-3EA0D13136DF}\r\n\t\t{8A607AC9-E7DD-4B74-A0B1-47FC95B9838B} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}\r\n\t\t{E22245AF-D5E1-46F6-B443-C886983EC50C} = {C40883CD-366D-4534-8B58-3EA0D13136DF}\r\n\t\t{22075D5A-E9A1-4E2D-ABA7-8E7CBF2A049E} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}\r\n\t\t{41D5691F-2720-44A0-9185-EEFE928D2679} = {C40883CD-366D-4534-8B58-3EA0D13136DF}\r\n\t\t{66DD7CD7-C68F-4D0E-9F3D-3B58C49D1467} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}\r\n\t\t{C19267DD-3984-430C-AE18-4034F85DE4E5} = {C40883CD-366D-4534-8B58-3EA0D13136DF}\r\n\t\t{43C1B979-D593-4A32-BB3A-4316F1C66D66} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}\r\n\t\t{25DEF6F6-7F99-4EB7-91ED-5181A346AFE1} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}\r\n\t\t{BF07E947-120D-4E93-93DA-A4BF121753EA} = {C40883CD-366D-4534-8B58-3EA0D13136DF}\r\n\t\t{1E89A3E9-0A7F-418F-B4BE-6E38A6315373} = {C40883CD-366D-4534-8B58-3EA0D13136DF}\r\n\t\t{821A136C-7C6F-44C6-A9E6-C39B5BFB1483} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}\r\n\t\t{C3BEF382-C7C4-454D-B017-1EAC03E9A82C} = {C40883CD-366D-4534-8B58-3EA0D13136DF}\r\n\t\t{5ABD9968-F3A3-4967-B768-A6142F69759E} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}\r\n\t\t{9AAFB58C-B8C1-4D7F-80E6-7B95C94A829B} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}\r\n\t\t{A1A20049-04C2-4676-93CF-92449C4BBAA9} = {C40883CD-366D-4534-8B58-3EA0D13136DF}\r\n\t\t{6C320AD9-F380-4F8B-85F9-0689F88766EC} = {C40883CD-366D-4534-8B58-3EA0D13136DF}\r\n\tEndGlobalSection\r\n\tGlobalSection(ExtensibilityGlobals) = postSolution\r\n\t\tSolutionGuid = {A855CFDC-9BEE-43A9-A3EA-4C4624A747DB}\r\n\tEndGlobalSection\r\nEndGlobal\r\n"
  },
  {
    "path": "SECURITY.md",
    "content": "# Security Policy\n\n## Reporting a Vulnerability\n\nSecurity 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.\nYou should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your\noriginal 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).\n\nPlease do not open issues for anything you think might have a security implication."
  },
  {
    "path": "Settings.StyleCop",
    "content": "<StyleCopSettings Version=\"105\">\n  <GlobalSettings>\n    <StringProperty Name=\"MergeSettingsFiles\">NoMerge</StringProperty>\n  </GlobalSettings>\n  <Parsers>\n    <Parser ParserId=\"StyleCop.CSharp.CsParser\">\n      <ParserSettings>\n        <BooleanProperty Name=\"AnalyzeDesignerFiles\">False</BooleanProperty>\n      </ParserSettings>\n    </Parser>\n  </Parsers>\n  <Analyzers>\n    <Analyzer AnalyzerId=\"StyleCop.CSharp.NamingRules\">\n      <Rules>\n        <Rule Name=\"FieldNamesMustNotBeginWithUnderscore\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n      </Rules>\n      <AnalyzerSettings>\n        <CollectionProperty Name=\"Hungarian\">\n          <Value>as</Value>\n          <Value>db</Value>\n          <Value>dc</Value>\n          <Value>do</Value>\n          <Value>ef</Value>\n          <Value>id</Value>\n          <Value>if</Value>\n          <Value>in</Value>\n          <Value>is</Value>\n          <Value>my</Value>\n          <Value>no</Value>\n          <Value>on</Value>\n          <Value>sl</Value>\n          <Value>to</Value>\n          <Value>ui</Value>\n          <Value>vs</Value>\n        </CollectionProperty>\n      </AnalyzerSettings>\n    </Analyzer>\n    <Analyzer AnalyzerId=\"StyleCop.CSharp.DocumentationRules\">\n      <Rules>\n        <Rule Name=\"FileMustHaveHeader\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"FileHeaderMustContainFileName\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"FileHeaderFileNameDocumentationMustMatchFileName\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"FileHeaderMustHaveValidCompanyText\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"ConstructorSummaryDocumentationMustBeginWithStandardText\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"DestructorSummaryDocumentationMustBeginWithStandardText\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"DocumentationHeadersMustNotContainBlankLines\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"ElementsMustBeDocumented\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"PartialElementsMustBeDocumented\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"EnumerationItemsMustBeDocumented\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"DocumentationMustContainValidXml\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"ElementDocumentationMustHaveSummary\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"PartialElementDocumentationMustHaveSummary\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"ElementDocumentationMustHaveSummaryText\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"PartialElementDocumentationMustHaveSummaryText\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"ElementDocumentationMustNotHaveDefaultSummary\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"ElementParametersMustBeDocumented\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"ElementParameterDocumentationMustMatchElementParameters\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"ElementParameterDocumentationMustDeclareParameterName\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"ElementParameterDocumentationMustHaveText\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"ElementReturnValueMustBeDocumented\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"ElementReturnValueDocumentationMustHaveText\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"VoidReturnValueMustNotBeDocumented\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"GenericTypeParametersMustBeDocumented\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"GenericTypeParametersMustBeDocumentedPartialClass\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"GenericTypeParameterDocumentationMustMatchTypeParameters\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"GenericTypeParameterDocumentationMustDeclareParameterName\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"GenericTypeParameterDocumentationMustHaveText\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"PropertySummaryDocumentationMustMatchAccessors\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"PropertySummaryDocumentationMustOmitSetAccessorWithRestrictedAccess\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"ElementDocumentationMustNotBeCopiedAndPasted\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"SingleLineCommentsMustNotUseDocumentationStyleSlashes\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"DocumentationTextMustNotBeEmpty\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"DocumentationTextMustContainWhitespace\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"DocumentationMustMeetCharacterPercentage\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"IncludedDocumentationXPathDoesNotExist\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"IncludeNodeDoesNotContainValidFileAndPath\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"InheritDocMustBeUsedWithInheritingClass\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"FileHeaderMustShowCopyright\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"FileHeaderMustHaveCopyrightText\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"FileHeaderFileNameDocumentationMustMatchTypeName\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n      </Rules>\n      <AnalyzerSettings>\n        <BooleanProperty Name=\"IgnorePrivates\">True</BooleanProperty>\n        <BooleanProperty Name=\"IgnoreInternals\">True</BooleanProperty>\n      </AnalyzerSettings>\n    </Analyzer>\n    <Analyzer AnalyzerId=\"StyleCop.CSharp.ReadabilityRules\">\n      <Rules>\n        <Rule Name=\"ParameterMustNotSpanMultipleLines\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"PrefixLocalCallsWithThis\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"ParameterMustFollowComma\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"SplitParametersMustStartOnLineAfterDeclaration\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"ParametersMustBeOnSameLineOrSeparateLines\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"UseBuiltInTypeAlias\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n      </Rules>\n      <AnalyzerSettings />\n    </Analyzer>\n    <Analyzer AnalyzerId=\"StyleCop.CSharp.LayoutRules\">\n      <Rules>\n        <Rule Name=\"AllAccessorsMustBeMultiLineOrSingleLine\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"SingleLineCommentsMustNotBeFollowedByBlankLine\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"ClosingCurlyBracketMustBeFollowedByBlankLine\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"SingleLineCommentMustBePrecededByBlankLine\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"ElementsMustBeSeparatedByBlankLine\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n      </Rules>\n      <AnalyzerSettings />\n    </Analyzer>\n    <Analyzer AnalyzerId=\"StyleCop.CSharp.MaintainabilityRules\">\n      <Rules>\n        <Rule Name=\"FieldsMustBePrivate\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"DebugAssertMustProvideMessageText\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"StatementMustNotUseUnnecessaryParenthesis\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n      </Rules>\n      <AnalyzerSettings />\n    </Analyzer>\n    <Analyzer AnalyzerId=\"StyleCop.CSharp.OrderingRules\">\n      <Rules>\n        <Rule Name=\"UsingDirectivesMustBePlacedWithinNamespace\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"ElementsMustAppearInTheCorrectOrder\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"ElementsMustBeOrderedByAccess\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"ConstantsMustAppearBeforeFields\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"StaticElementsMustAppearBeforeInstanceElements\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n      </Rules>\n      <AnalyzerSettings />\n    </Analyzer>\n    <Analyzer AnalyzerId=\"StyleCop.CSharp.SpacingRules\">\n      <Rules>\n        <Rule Name=\"SingleLineCommentsMustBeginWithSingleSpace\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n      </Rules>\n      <AnalyzerSettings />\n    </Analyzer>\n    <Analyzer AnalyzerId=\"Microsoft.Web.StyleCop.Rules\">\n      <Rules />\n      <AnalyzerSettings>\n        <StringProperty Name=\"FileHeaderText\"> 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.</StringProperty>\n      </AnalyzerSettings>\n    </Analyzer>\n  </Analyzers>\n</StyleCopSettings>"
  },
  {
    "path": "Tools.sln",
    "content": "﻿\r\nMicrosoft Visual Studio Solution File, Format Version 12.00\r\n# Visual Studio 15\r\nVisualStudioVersion = 15.0.27016.1\r\nMinimumVisualStudioVersion = 15.0\r\nProject(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"Microsoft.Web.FxCop\", \"tools\\src\\Microsoft.Web.FxCop\\Microsoft.Web.FxCop.csproj\", \"{F439D4E6-3FAC-4C30-9585-6D258133A2BF}\"\r\nEndProject\r\nGlobal\r\n\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\r\n\t\tDebug|Any CPU = Debug|Any CPU\r\n\t\tRelease|Any CPU = Release|Any CPU\r\n\tEndGlobalSection\r\n\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\r\n\t\t{F439D4E6-3FAC-4C30-9585-6D258133A2BF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\r\n\t\t{F439D4E6-3FAC-4C30-9585-6D258133A2BF}.Debug|Any CPU.Build.0 = Debug|Any CPU\r\n\t\t{F439D4E6-3FAC-4C30-9585-6D258133A2BF}.Release|Any CPU.ActiveCfg = Release|Any CPU\r\n\t\t{F439D4E6-3FAC-4C30-9585-6D258133A2BF}.Release|Any CPU.Build.0 = Release|Any CPU\r\n\tEndGlobalSection\r\n\tGlobalSection(SolutionProperties) = preSolution\r\n\t\tHideSolutionNode = FALSE\r\n\tEndGlobalSection\r\n\tGlobalSection(ExtensibilityGlobals) = postSolution\r\n\t\tSolutionGuid = {F8728741-0321-4EF6-9359-7DF2DCE6E99E}\r\n\tEndGlobalSection\r\nEndGlobal\r\n"
  },
  {
    "path": "azure-pipelines-public.yml",
    "content": "parameters:\n  # Test only the Release build by default.\n- name: ReleaseBuildTarget\n  displayName: 'Build which target for Release?'\n  type: string\n  values: [ Build, Integration, UnitTest ]\n  default: UnitTest\n- name: OtherBuildTarget\n  displayName: 'Build which target for Debug/CodeAnalysis?'\n  type: string\n  values: [ Build, Integration, UnitTest ]\n  default: Build\n\nvariables:\n- name: DOTNET_CLI_TELEMETRY_OPTOUT\n  value: 1\n- name: DOTNET_NOLOGO\n  value: 1\n  # Run CodeQL3000 tasks in a separate internal pipeline; not needed here.\n- name: Codeql.SkipTaskAutoInjection\n  value: true\n\ntrigger: [main]\npr: ['*']\n\nstages:\n- stage: build\n  displayName: Build\n  jobs:\n  - template: /eng/templates/default-build.yml\n    parameters:\n      ReleaseBuildTarget: ${{ parameters.ReleaseBuildTarget }}\n      OtherBuildTarget: ${{ parameters.OtherBuildTarget }}\n"
  },
  {
    "path": "azure-pipelines.yml",
    "content": "parameters:\n  # Test only the Release build by default.\n- name: ReleaseBuildTarget\n  displayName: 'Build which target for Release?'\n  type: string\n  values: [ Build, Integration, UnitTest ]\n  default: Build\n- name: OtherBuildTarget\n  displayName: 'Build which target for Debug/CodeAnalysis?'\n  type: string\n  values: [ Build, Integration, UnitTest ]\n  default: Build\n\nvariables:\n- name: DOTNET_CLI_TELEMETRY_OPTOUT\n  value: 1\n- name: DOTNET_NOLOGO\n  value: 1\n  # Run CodeQL3000 tasks in a separate internal pipeline; not needed here.\n- name: Codeql.SkipTaskAutoInjection\n  value: true\n\ntrigger: [main]\npr: ['*']\n\nresources:\n  repositories:\n  # Repo: 1ESPipelineTemplates/1ESPipelineTemplates\n  - repository: 1esPipelines\n    type: git\n    name: 1ESPipelineTemplates/1ESPipelineTemplates\n    ref: refs/tags/release\n\nextends:\n  template: v1/1ES.Official.PipelineTemplate.yml@1esPipelines\n  parameters:\n    settings:\n      networkIsolationPolicy: Permissive, CFSClean, CFSClean2\n    sdl:\n      policheck:\n        enabled: true\n      tsa:\n        enabled: true\n    pool:\n      name: NetCore1ESPool-Svc-Internal\n      demands:\n      - ImageOverride -equals windows.vs2019.amd64\n      - ImageVersionOverride -equals 2026.0304.014948\n      os: windows\n    stages:\n    - stage: build\n      displayName: Build\n      jobs:\n      - template: /eng/templates/default-build.yml@self\n        parameters:\n          ReleaseBuildTarget: ${{ parameters.ReleaseBuildTarget }}\n          OtherBuildTarget: ${{ parameters.OtherBuildTarget }}\n"
  },
  {
    "path": "build.cmd",
    "content": "@echo off\nsetlocal\n\nif exist bin goto Build\nmkdir bin\n\n:Build\n\nREM Require VS2019 (v16.0) on the system. Use `vswhere` for the search because it can find all VS installations.\nset vswhere=\"%ProgramFiles(x86)%\\Microsoft Visual Studio\\Installer\\vswhere.exe\"\nif not exist %vswhere% (\n  set vswhere=\"%ProgramFiles%\\Microsoft Visual Studio\\Installer\\vswhere.exe\"\n)\nif not exist %vswhere% (\n  REM vswhere.exe not in normal locations; check the Path.\n  for %%X in (vswhere.exe) do (\n    set vswhere=\"%%~$PATH:X\"\n  )\n)\nif not exist %vswhere% (\n  echo Could not find vswhere.exe. Please run this from a Visual Studio developer prompt.\n  goto BuildFail\n)\n\nset InstallDir=\nfor /f \"usebackq tokens=*\" %%i in (`%vswhere% -version 16 -latest -prerelease -products * ^\n    -requires Microsoft.Net.Component.4.5.TargetingPack ^\n    -requires Microsoft.Net.Component.4.5.2.TargetingPack ^\n    -requires Microsoft.Net.Component.4.6.2.TargetingPack ^\n    -property installationPath`) do (\n  set \"InstallDir=%%i\"\n)\n\nif not DEFINED InstallDir (\n  echo \"Could not find a VS2019 installation with the necessary components (targeting packs for v4.5, v4.5.2, and v4.6.2).\"\n  echo Please install VS2019 or the missing components.\n  goto BuildFail\n)\n\nREM Find a 64bit MSBuild and add it to path. Require v17.8.3 or later due to our .NET SDK choice.\nREM Check for VS2022 first.\nset InstallDir=\nfor /f \"usebackq tokens=*\" %%i in (`%vswhere% -version 17.8.3 -latest -prerelease -products * ^\n    -requires Microsoft.Component.MSBuild ^\n    -property installationPath`) do (\n  set \"InstallDir=%%i\"\n)\n\nif DEFINED InstallDir (\n  REM Add MSBuild to the path.\n  set \"PATH=%InstallDir%\\MSBuild\\Current\\Bin;%PATH%\"\n  goto FoundMSBuild\n)\n\nREM Otherwise find or install an xcopy-able MSBuild.\necho \"Could not find a VS2022 installation with the necessary components (MSBuild). Falling back...\"\n\nset \"MSBuildVersion=17.8.5\"\nset \"Command=[System.Threading.Thread]::CurrentThread.CurrentCulture = ''\"\nset \"Command=%Command%; [System.Threading.Thread]::CurrentThread.CurrentUICulture = ''\"\nset \"Command=%Command%; try { & '%~dp0eng\\GetXCopyMSBuild.ps1' %MSBuildVersion%; exit $LASTEXITCODE }\"\nset \"Command=%Command%  catch { write-host $_; exit 1 }\"\nPowerShell -NoProfile -NoLogo -ExecutionPolicy Bypass -Command \"%Command%\"\nif %ERRORLEVEL% neq 0 goto BuildFail\n\nREM Add MSBuild to the path.\nset \"PATH=%~dp0.msbuild\\%MSBuildVersion%\\tools\\MSBuild\\Current\\Bin;%PATH%\"\n\n:FoundMSBuild\nREM Configure NuGet operations to work w/in this repo i.e. do not pollute system packages folder.\nREM Note this causes two copies of packages restored using packages.config to land in this folder e.g.\nREM StyleCpy.5.0.0/ and stylecop/5.0.0/.\nset \"NUGET_PACKAGES=%~dp0packages\"\n\nREM Are we running in a local dev environment (not on CI)?\nif DEFINED CI (set Desktop=false) else if DEFINED TEAMCITY_VERSION (set Desktop=false) else (set Desktop=true)\n\npushd %~dp0\nif \"%1\" == \"\" goto BuildDefaults\n\nMSBuild \"%~dp0Runtime.msbuild\" /m /nr:false /p:Platform=\"Any CPU\" /p:Desktop=%Desktop% /v:M ^\n    /fl /fileLoggerParameters:LogFile=bin\\msbuild.log;Verbosity=Normal /consoleLoggerParameters:Summary /t:%*\nif %ERRORLEVEL% neq 0 goto BuildFail\ngoto BuildSuccess\n\n:BuildDefaults\nMSBuild \"%~dp0Runtime.msbuild\" /m /nr:false /p:Platform=\"Any CPU\" /p:Desktop=%Desktop% /v:M ^\n    /fl /fileLoggerParameters:LogFile=bin\\msbuild.log;Verbosity=Normal /consoleLoggerParameters:Summary\nif %ERRORLEVEL% neq 0 goto BuildFail\ngoto BuildSuccess\n\n:BuildFail\necho.\necho *** BUILD FAILED ***\npopd\nendlocal\nexit /B 999\n\n:BuildSuccess\necho.\necho **** BUILD SUCCESSFUL ***\npopd\nendlocal\nexit /B 0\n"
  },
  {
    "path": "eng/GetXCopyMSBuild.ps1",
    "content": "# Lifted from https://github.com/dotnet/arcade/blob/main/eng/common/tools.ps1\n\n[CmdletBinding(DefaultParameterSetName='Groups')]\nparam(\n    [string]$Version = '17.4.1'\n)\n\nSet-StrictMode -Version 2\n$ErrorActionPreference = 'Stop'\n\nfunction Create-Directory ([string[]] $path) {\n  New-Item -Path $path -Force -ItemType 'Directory' | Out-Null\n}\n\nfunction Unzip([string]$zipfile, [string]$outpath) {\n  Add-Type -AssemblyName System.IO.Compression.FileSystem\n  [System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath)\n}\n\nfunction InitializeXCopyMSBuild([string]$packageVersion, [bool]$install, [string]$ToolsDir) {\n  $packageName = 'RoslynTools.MSBuild'\n  $packageDir = Join-Path $ToolsDir $packageVersion\n  $packagePath = Join-Path $packageDir \"$packageName.$packageVersion.nupkg\"\n\n  if (!(Test-Path $packageDir)) {\n    if (!$install) {\n      return $null\n    }\n\n    Create-Directory $packageDir\n\n    Write-Host \"Downloading $packageName $packageVersion\"\n    $ProgressPreference = 'SilentlyContinue' # Don't display the console progress UI - it's a huge perf hit\n    Invoke-WebRequest \"https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng/nuget/v3/flat2/$packageName/$packageVersion/$packageName.$packageVersion.nupkg\" -OutFile $packagePath\n\n    Unzip $packagePath $packageDir\n  }\n\n  return Join-Path $packageDir 'tools'\n}\n\n$RepoRoot = Resolve-Path (Join-Path $PSScriptRoot '..\\')\nInitializeXCopyMSBuild -packageVersion $Version -install $true -ToolsDir (join-path $RepoRoot .msbuild)\n"
  },
  {
    "path": "eng/templates/default-build.yml",
    "content": "parameters:\n  ReleaseBuildTarget: ''\n  OtherBuildTarget: ''\n\njobs:\n- job: build\n  displayName: Build\n  ${{ if eq(variables['System.TeamProject'], 'public') }}:\n    pool:\n      name: NetCore-Svc-Public\n      demands:\n      - ImageOverride -equals windows.vs2019.amd64.open\n  timeoutInMinutes: 30\n\n  strategy:\n    matrix:\n      Release:\n        _BuildTarget: ${{ parameters.ReleaseBuildTarget }}\n        _Configuration: Release\n        _StyleCopEnabled: true\n        # Do CG work only in internal pipelines.\n        skipComponentGovernanceDetection: ${{ eq(variables['System.TeamProject'], 'public') }}\n      Debug:\n        _BuildTarget: ${{ parameters.OtherBuildTarget }}\n        _Configuration: Debug\n        _StyleCopEnabled: false\n        # Do not redo CG work. Configuration changes in this part of the matrix are not relevant to CG.\n        skipComponentGovernanceDetection: true\n      CodeAnalysis:\n        _BuildTarget: ${{ parameters.OtherBuildTarget }}\n        _Configuration: CodeAnalysis\n        _StyleCopEnabled: false\n        # Do not redo CG work. Configuration changes in this part of the matrix are not relevant to CG.\n        skipComponentGovernanceDetection: true\n\n  steps:\n  - checkout: self\n    clean: true\n    displayName: Checkout\n\n  - task: UseDotNet@2\n    displayName: Get .NET SDK\n    inputs:\n      useGlobalJson: true\n  - task: UseDotNet@2\n    displayName: Get .NET 2.1 runtime\n    inputs:\n      packageType: runtime\n      version: '2.1.x'\n\n  - script: .\\build.cmd EnableSkipStrongNames\n    displayName: Enable SkipStrongNames\n  - script: .\\build.cmd $(_BuildTarget) ^\n      /binaryLogger:artifacts/msbuild.binlog /p:Configuration=$(_Configuration) /p:StyleCopEnabled=$(_StyleCopEnabled) ^\n      /fileLoggerParameters:LogFile=artifacts/msbuild.log;Summary;Verbosity=minimal\n    displayName: Build\n\n  - ${{ if eq(variables['System.TeamProject'], 'public') }}:\n    - task: PublishBuildArtifacts@1\n      displayName: Upload test results\n      condition: and(always(), ne(variables._BuildTarget, 'Build'))\n      continueOnError: true\n      inputs:\n        pathtoPublish: ./bin/$(_Configuration)/Test/TestResults/\n        artifactName: $(_Configuration) Test Results $(System.JobId)\n        artifactType: Container\n        parallel: true\n    - task: PublishTestResults@2\n      condition: and(always(), ne(variables._BuildTarget, 'Build'))\n      continueOnError: true\n      displayName: Publish test results\n      inputs:\n        mergeTestResults: true\n        searchFolder: ./bin/$(_Configuration)/Test/TestResults/\n        testResultsFiles: '*.xml'\n        testRunner: xUnit\n        testRunTitle: $(_Configuration)\n    - task: PublishBuildArtifacts@1\n      displayName: Upload logs\n      condition: always()\n      continueOnError: true\n      inputs:\n        pathtoPublish: ./artifacts/\n        artifactName: $(_Configuration) Logs $(System.JobId)\n        artifactType: Container\n        parallel: true\n  - ${{ if eq(variables['System.TeamProject'], 'internal') }}: \n    - task: 1ES.PublishPipelineArtifact@1\n      inputs:\n        condition: and(always(), ne(variables._BuildTarget, 'Build'))\n        path: ./bin/$(_Configuration)/Test/TestResults/\n        artifact: $(_Configuration) Test Results $(System.JobId)\n    - task: 1ES.PublishPipelineArtifact@1\n      inputs:\n        path: ./artifacts/\n        artifact: $(_Configuration) Logs $(System.JobId)\n"
  },
  {
    "path": "es-metadata.yml",
    "content": "schemaVersion: 0.0.1\nisProduction: true\naccountableOwners:\n  service: 4db45fa9-fb0f-43ce-b523-ad1da773dfbc\nrouting:\n  defaultAreaPath:\n    org: devdiv\n    path: DevDiv\\ASP.NET Core\n"
  },
  {
    "path": "global.json",
    "content": "{\n  \"sdk\": {\n    \"version\": \"8.0.419\",\n    \"rollForward\": \"major\"\n  }\n}\n"
  },
  {
    "path": "src/CodeAnalysisDictionary.xml",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<Dictionary>\n    <Words>\n        <Recognized>\n            <Word>Multi</Word>\n            <Word>Bitly</Word>\n            <Word>Digg</Word>\n            <Word>Facebook</Word>\n            <Word>Reddit</Word>\n            <Word>Captcha</Word>\n            <Word>Facebook</Word>\n            <Word>Gravatar</Word>\n            <Word>JSON</Word>\n            <Word>Lookahead</Word>\n            <Word>MVC</Word>\n            <Word>Param</Word>\n            <Word>Params</Word>\n            <Word>Pluralizer</Word>\n            <Word>Pragma</Word>\n            <Word>Pragmas</Word>\n            <Word>Templating</Word>\n            <Word>Unvalidated</Word>\n            <Word>Validator</Word>\n            <Word>Validators</Word>\n            <Word>Validatable</Word>\n            <Word>WebPage</Word>\n            <Word>cshtml</Word>\n            <Word>vbhtml</Word>\n            <Word>asax</Word>\n            <Word>Eval</Word>\n            <Word>Src</Word>\n            <Word>Charset</Word>\n            <Word>Coords</Word>\n            <Word>Rel</Word>\n            <Word>Dto</Word>\n            <Word>Tokenizer</Word>\n            <Word>ReDim</Word>\n            <Word>OAuth</Word>\n            <Word>OpenID</Word>\n            <Word>Yadis</Word>\n            <Word>fwlink</Word>\n            <Word>Edm</Word>\n            <Word>Deserializer</Word>\n            <Word>Api</Word>\n            <Word>ws</Word>\n            <Word>enc</Word>\n            <Word>dir</Word>\n            <Word>Auth</Word>\n            <Word>bg</Word>\n            <Word>Cors</Word>\n            <Word>Owin</Word>\n            <Word>Unbuffered</Word>\n            <Word>Rfc</Word>\n            <Word>Realtime</Word>\n            <Word>ModelName</Word>\n            <Word>BSON</Word>\n            <Word>Untyped</Word>\n            <Word>Behavior</Word>\n            <Word>Callback</Word>\n            <Word>Canceled</Word>\n            <Word>Color</Word>\n            <Word>Fallback</Word>\n            <Word>Markup</Word>\n            <Word>Preflight</Word>\n        </Recognized>\n        <Compound>\n            <Term CompoundAlternate=\"WebPage\">WebPage</Term>\n            <Term CompoundAlternate=\"WebPages\">WebPages</Term>\n            <Term CompoundAlternate=\"TimeLine\">TimeLine</Term>\n            <Term CompoundAlternate=\"OAuth\">oAuth</Term>\n            <Term CompoundAlternate=\"UserName\">userName</Term>\n            <Term CompoundAlternate=\"ModelName\">modelName</Term>\n            <Term CompoundAlternate=\"HasId\">HasId</Term>\n        </Compound>\n    </Words>\n    <Acronyms>\n        <CasingExceptions>\n            <Acronym>ID</Acronym>\n            <Acronym>Db</Acronym>\n            <Acronym>Dto</Acronym>\n        </CasingExceptions>\n    </Acronyms>\n</Dictionary>"
  },
  {
    "path": "src/Common/AttributeList.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\n\nnamespace System.ComponentModel\n{\n    /// <summary>\n    /// Wrapper for AttributeCollection to provide generic collection implementation.\n    /// </summary>\n    internal sealed class AttributeList : IList<Attribute>\n    {\n        private readonly AttributeCollection _attributes;\n\n        public AttributeList(AttributeCollection attributes)\n        {\n            Contract.Assert(attributes != null);\n            _attributes = attributes;\n        }\n\n        public int Count\n        {\n            get\n            {\n                return _attributes.Count;\n            }\n        }\n\n        public bool IsReadOnly\n        {\n            get\n            {\n                return true;\n            }\n        }\n\n        public Attribute this[int index]\n        {\n            get\n            {\n                return _attributes[index];\n            }\n            set\n            {\n                throw new NotSupportedException();\n            }\n        }\n\n        public void Add(Attribute attribute)\n        {\n            throw new NotSupportedException();\n        }\n\n        public void Clear()\n        {\n            throw new NotSupportedException();\n        }\n\n        public bool Contains(Attribute attribute)\n        {\n            return _attributes.Contains(attribute);\n        }\n\n        public void CopyTo(Attribute[] target, int startIndex)\n        {\n            _attributes.CopyTo(target, startIndex);\n        }\n\n        public IEnumerator<Attribute> GetEnumerator()\n        {\n            for (int i = 0; i < _attributes.Count; i++)\n            {\n                yield return _attributes[i];\n            }\n        }\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return ((IEnumerable)_attributes).GetEnumerator();\n        }\n\n        public int IndexOf(Attribute attribute)\n        {\n            for (int i = 0; i < _attributes.Count; i++)\n            {\n                if (attribute == _attributes[i]) \n                {\n                    return i;\n                }                \n            }\n            return -1;\n        }\n\n        public void Insert(int index, Attribute attribute)\n        {\n            throw new NotSupportedException();\n        }\n\n        bool ICollection<Attribute>.Remove(Attribute attribute)\n        {\n            throw new NotSupportedException();\n        }\n\n        public void RemoveAt(int index)\n        {\n            throw new NotSupportedException();\n        }\n    }\n}\n"
  },
  {
    "path": "src/Common/CollectionExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\n\nnamespace System.Collections.Generic\n{\n    /// <summary>\n    /// Helper extension methods for fast use of collections.\n    /// </summary>\n    internal static class CollectionExtensions\n    {\n        /// <summary>\n        /// Return a new array with the value added to the end. Slow and best suited to long lived arrays with few writes relative to reads.\n        /// </summary>\n        public static T[] AppendAndReallocate<T>(this T[] array, T value)\n        {\n            Contract.Assert(array != null);\n\n            int originalLength = array.Length;\n            T[] newArray = new T[originalLength + 1];\n            array.CopyTo(newArray, 0);\n            newArray[originalLength] = value;\n            return newArray;\n        }\n\n        /// <summary>\n        /// Return the enumerable as an Array, copying if required. Optimized for common case where it is an Array.\n        /// Avoid mutating the return value.\n        /// </summary>\n        public static T[] AsArray<T>(this IEnumerable<T> values)\n        {\n            Contract.Assert(values != null);\n\n            T[] array = values as T[];\n            if (array == null)\n            {\n                array = values.ToArray();\n            }\n            return array;\n        }\n\n        /// <summary>\n        /// Return the enumerable as a Collection of T, copying if required. Optimized for the common case where it is\n        /// a Collection of T and avoiding a copy if it implements IList of T. Avoid mutating the return value.\n        /// </summary>\n        public static Collection<T> AsCollection<T>(this IEnumerable<T> enumerable)\n        {\n            Contract.Assert(enumerable != null);\n\n            Collection<T> collection = enumerable as Collection<T>;\n            if (collection != null)\n            {\n                return collection;\n            }\n            // Check for IList so that collection can wrap it instead of copying\n            IList<T> list = enumerable as IList<T>;\n            if (list == null)\n            {\n                list = new List<T>(enumerable);\n            }\n            return new Collection<T>(list);\n        }\n\n        /// <summary>\n        /// Return the enumerable as a IList of T, copying if required. Avoid mutating the return value.\n        /// </summary>\n        public static IList<T> AsIList<T>(this IEnumerable<T> enumerable)\n        {\n            Contract.Assert(enumerable != null);\n\n            IList<T> list = enumerable as IList<T>;\n            if (list != null)\n            {\n                return list;\n            }\n            return new List<T>(enumerable);\n        }\n\n        /// <summary>\n        /// Return the enumerable as a List of T, copying if required. Optimized for common case where it is an List of T\n        /// or a ListWrapperCollection of T. Avoid mutating the return value.\n        /// </summary>\n        public static List<T> AsList<T>(this IEnumerable<T> enumerable)\n        {\n            Contract.Assert(enumerable != null);\n\n            List<T> list = enumerable as List<T>;\n            if (list != null)\n            {\n                return list;\n            }\n            ListWrapperCollection<T> listWrapper = enumerable as ListWrapperCollection<T>;\n            if (listWrapper != null)\n            {\n                return listWrapper.ItemsList;\n            }\n            return new List<T>(enumerable);\n        }\n\n        /// <summary>\n        /// Remove values from the list starting at the index start.\n        /// </summary>\n        public static void RemoveFrom<T>(this List<T> list, int start)\n        {\n            Contract.Assert(list != null);\n            Contract.Assert(start >= 0 && start <= list.Count);\n\n            list.RemoveRange(start, list.Count - start);\n        }\n\n        /// <summary>\n        /// Return the only value from list, the type's default value if empty, or call the errorAction for 2 or more.\n        /// </summary>\n        public static T SingleDefaultOrError<T, TArg1>(this IList<T> list, Action<TArg1> errorAction, TArg1 errorArg1)\n        {\n            Contract.Assert(list != null);\n            Contract.Assert(errorAction != null);\n\n            switch (list.Count)\n            {\n                case 0:\n                    return default(T);\n\n                case 1:\n                    T value = list[0];\n                    return value;\n\n                default:\n                    errorAction(errorArg1);\n                    return default(T);\n            }\n        }\n\n        /// <summary>\n        /// Returns a single value in list matching type TMatch if there is only one, null if there are none of type TMatch or calls the\n        /// errorAction with errorArg1 if there is more than one.\n        /// </summary>\n        public static TMatch SingleOfTypeDefaultOrError<TInput, TMatch, TArg1>(this IList<TInput> list, Action<TArg1> errorAction, TArg1 errorArg1) where TMatch : class\n        {\n            Contract.Assert(list != null);\n            Contract.Assert(errorAction != null);\n\n            TMatch result = null;\n            for (int i = 0; i < list.Count; i++)\n            {\n                TMatch typedValue = list[i] as TMatch;\n                if (typedValue != null)\n                {\n                    if (result == null)\n                    {\n                        result = typedValue;\n                    }\n                    else\n                    {\n                        errorAction(errorArg1);\n                        return null;\n                    }\n                }\n            }\n            return result;\n        }\n\n        /// <summary>\n        /// Convert an ICollection to an array, removing null values. Fast path for case where there are no null values.\n        /// </summary>\n        public static T[] ToArrayWithoutNulls<T>(this ICollection<T> collection) where T : class\n        {\n            Contract.Assert(collection != null);\n\n            T[] result = new T[collection.Count];\n            int count = 0;\n            foreach (T value in collection)\n            {\n                if (value != null)\n                {\n                    result[count] = value;\n                    count++;\n                }\n            }\n            if (count == collection.Count)\n            {\n                return result;\n            }\n            else\n            {\n                T[] trimmedResult = new T[count];\n                Array.Copy(result, trimmedResult, count);\n                return trimmedResult;\n            }\n        }\n\n        /// <summary>\n        /// Convert the array to a Dictionary using the keySelector to extract keys from values and the specified comparer. Optimized for array input.\n        /// </summary>\n        public static Dictionary<TKey, TValue> ToDictionaryFast<TKey, TValue>(this TValue[] array, Func<TValue, TKey> keySelector, IEqualityComparer<TKey> comparer)\n        {\n            Contract.Assert(array != null);\n            Contract.Assert(keySelector != null);\n\n            Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>(array.Length, comparer);\n            for (int i = 0; i < array.Length; i++)\n            {\n                TValue value = array[i];\n                dictionary.Add(keySelector(value), value);\n            }\n            return dictionary;\n        }\n\n        /// <summary>\n        /// Convert the list to a Dictionary using the keySelector to extract keys from values and the specified comparer. Optimized for IList of T input with fast path for array.\n        /// </summary>\n        public static Dictionary<TKey, TValue> ToDictionaryFast<TKey, TValue>(this IList<TValue> list, Func<TValue, TKey> keySelector, IEqualityComparer<TKey> comparer)\n        {\n            Contract.Assert(list != null);\n            Contract.Assert(keySelector != null);\n\n            TValue[] array = list as TValue[];\n            if (array != null)\n            {\n                return ToDictionaryFast(array, keySelector, comparer);\n            }\n            return ToDictionaryFastNoCheck(list, keySelector, comparer);\n        }\n\n        /// <summary>\n        /// Convert the enumerable to a Dictionary using the keySelector to extract keys from values and the specified comparer. Fast paths for array and IList of T.\n        /// </summary>\n        public static Dictionary<TKey, TValue> ToDictionaryFast<TKey, TValue>(this IEnumerable<TValue> enumerable, Func<TValue, TKey> keySelector, IEqualityComparer<TKey> comparer)\n        {\n            Contract.Assert(enumerable != null);\n            Contract.Assert(keySelector != null);\n\n            TValue[] array = enumerable as TValue[];\n            if (array != null)\n            {\n                return ToDictionaryFast(array, keySelector, comparer);\n            }\n            IList<TValue> list = enumerable as IList<TValue>;\n            if (list != null)\n            {\n                return ToDictionaryFastNoCheck(list, keySelector, comparer);\n            }\n            Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>(comparer);\n            foreach (TValue value in enumerable)\n            {\n                dictionary.Add(keySelector(value), value);\n            }\n            return dictionary;\n        }\n\n        /// <summary>\n        /// Convert the list to a Dictionary using the keySelector to extract keys from values and the specified comparer. Optimized for IList of T input. No checking for other types.\n        /// </summary>\n        private static Dictionary<TKey, TValue> ToDictionaryFastNoCheck<TKey, TValue>(IList<TValue> list, Func<TValue, TKey> keySelector, IEqualityComparer<TKey> comparer)\n        {\n            Contract.Assert(list != null);\n            Contract.Assert(keySelector != null);\n\n            int listCount = list.Count;\n            Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>(listCount, comparer);\n            for (int i = 0; i < listCount; i++)\n            {\n                TValue value = list[i];\n                dictionary.Add(keySelector(value), value);\n            }\n            return dictionary;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Common/CommonWebApiResources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.42000\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace System.Web.Http.Properties {\n    using System;\n    using System.Linq;\n    using System.Reflection;\n\n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class CommonWebApiResources {\n\n        private static global::System.Resources.ResourceManager resourceMan;\n\n        private static global::System.Globalization.CultureInfo resourceCulture;\n\n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal CommonWebApiResources() {\n        }\n\n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n#if NETSTANDARD1_3\n                    var assembly = typeof(CommonWebApiResources).GetTypeInfo().Assembly;\n#else\n                    var assembly = typeof(CommonWebApiResources).Assembly;\n#endif\n\n                    // Find the CommonResources.resources file's full resource name in this assembly\n                    string commonResourcesName = assembly.GetManifestResourceNames().Where(s => s.EndsWith(\"CommonWebApiResources.resources\", StringComparison.OrdinalIgnoreCase)).Single();\n\n                    // Trim off the \".resources\"\n                    commonResourcesName = commonResourcesName.Substring(0, commonResourcesName.Length - 10);\n\n                    // Load the resource manager\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(commonResourcesName, assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n\n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Relative URI values are not supported: &apos;{0}&apos;. The URI must be absolute..\n        /// </summary>\n        internal static string ArgumentInvalidAbsoluteUri {\n            get {\n                return ResourceManager.GetString(\"ArgumentInvalidAbsoluteUri\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Unsupported URI scheme: &apos;{0}&apos;. The URI scheme must be either &apos;{1}&apos; or &apos;{2}&apos;..\n        /// </summary>\n        internal static string ArgumentInvalidHttpUriScheme {\n            get {\n                return ResourceManager.GetString(\"ArgumentInvalidHttpUriScheme\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Value must be greater than or equal to {0}..\n        /// </summary>\n        internal static string ArgumentMustBeGreaterThanOrEqualTo {\n            get {\n                return ResourceManager.GetString(\"ArgumentMustBeGreaterThanOrEqualTo\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Value must be less than or equal to {0}..\n        /// </summary>\n        internal static string ArgumentMustBeLessThanOrEqualTo {\n            get {\n                return ResourceManager.GetString(\"ArgumentMustBeLessThanOrEqualTo\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The argument &apos;{0}&apos; is null or empty..\n        /// </summary>\n        internal static string ArgumentNullOrEmpty {\n            get {\n                return ResourceManager.GetString(\"ArgumentNullOrEmpty\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to URI must not contain a query component or a fragment identifier..\n        /// </summary>\n        internal static string ArgumentUriHasQueryOrFragment {\n            get {\n                return ResourceManager.GetString(\"ArgumentUriHasQueryOrFragment\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The value of argument &apos;{0}&apos; ({1}) is invalid for Enum type &apos;{2}&apos;..\n        /// </summary>\n        internal static string InvalidEnumArgument {\n            get {\n                return ResourceManager.GetString(\"InvalidEnumArgument\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Common/CommonWebApiResources.resx",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"ArgumentInvalidAbsoluteUri\" xml:space=\"preserve\">\n    <value>Relative URI values are not supported: '{0}'. The URI must be absolute.</value>\n  </data>\n  <data name=\"ArgumentInvalidHttpUriScheme\" xml:space=\"preserve\">\n    <value>Unsupported URI scheme: '{0}'. The URI scheme must be either '{1}' or '{2}'.</value>\n  </data>\n  <data name=\"ArgumentMustBeGreaterThanOrEqualTo\" xml:space=\"preserve\">\n    <value>Value must be greater than or equal to {0}.</value>\n  </data>\n  <data name=\"ArgumentMustBeLessThanOrEqualTo\" xml:space=\"preserve\">\n    <value>Value must be less than or equal to {0}.</value>\n  </data>\n  <data name=\"ArgumentNullOrEmpty\" xml:space=\"preserve\">\n    <value>The argument '{0}' is null or empty.</value>\n  </data>\n  <data name=\"ArgumentUriHasQueryOrFragment\" xml:space=\"preserve\">\n    <value>URI must not contain a query component or a fragment identifier.</value>\n  </data>\n  <data name=\"InvalidEnumArgument\" xml:space=\"preserve\">\n    <value>The value of argument '{0}' ({1}) is invalid for Enum type '{2}'.</value>\n  </data>\n</root>"
  },
  {
    "path": "src/Common/DictionaryExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Diagnostics.Contracts;\n\nnamespace System.Collections.Generic\n{\n    /// <summary>\n    /// Extension methods for <see cref=\"IDictionary{TKey,TValue}\"/>.\n    /// </summary>\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    internal static class DictionaryExtensions\n    {\n        /// <summary>\n        /// Remove entries from dictionary that match the removeCondition.\n        /// </summary>\n        public static void RemoveFromDictionary<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, Func<KeyValuePair<TKey, TValue>, bool> removeCondition)\n        {\n            // Pass the delegate as the state to avoid a delegate and closure\n            dictionary.RemoveFromDictionary((entry, innerCondition) =>\n                {\n                    return innerCondition(entry);\n                },\n                removeCondition);\n        }\n\n        /// <summary>\n        /// Remove entries from dictionary that match the removeCondition.\n        /// </summary>\n        public static void RemoveFromDictionary<TKey, TValue, TState>(this IDictionary<TKey, TValue> dictionary, Func<KeyValuePair<TKey, TValue>, TState, bool> removeCondition, TState state)\n        {\n            Contract.Assert(dictionary != null);\n            Contract.Assert(removeCondition != null);\n\n            // Because it is not possible to delete while enumerating, a copy of the keys must be taken. Use the size of the dictionary as an upper bound\n            // to avoid creating more than one copy of the keys.\n            int removeCount = 0;\n            TKey[] keys = new TKey[dictionary.Count];\n            foreach (var entry in dictionary)\n            {\n                if (removeCondition(entry, state))\n                {\n                    keys[removeCount] = entry.Key;\n                    removeCount++;\n                }\n            }\n            for (int i = 0; i < removeCount; i++)\n            {\n                dictionary.Remove(keys[i]);\n            }\n        }\n\n        /// <summary>\n        /// Gets the value of <typeparamref name=\"T\"/> associated with the specified key or <c>default</c> value if\n        /// either the key is not present or the value is not of type <typeparamref name=\"T\"/>. \n        /// </summary>\n        /// <typeparam name=\"T\">The type of the value associated with the specified key.</typeparam>\n        /// <param name=\"collection\">The <see cref=\"IDictionary{TKey,TValue}\"/> instance where <c>TValue</c> is <c>object</c>.</param>\n        /// <param name=\"key\">The key whose value to get.</param>\n        /// <param name=\"value\">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the value parameter.</param>\n        /// <returns><c>true</c> if key was found, value is non-null, and value is of type <typeparamref name=\"T\"/>; otherwise false.</returns>\n        public static bool TryGetValue<T>(this IDictionary<string, object> collection, string key, out T value)\n        {\n            Contract.Assert(collection != null);\n\n            object valueObj;\n            if (collection.TryGetValue(key, out valueObj))\n            {\n                if (valueObj is T)\n                {\n                    value = (T)valueObj;\n                    return true;\n                }\n            }\n\n            value = default(T);\n            return false;\n        }\n\n        internal static IEnumerable<KeyValuePair<string, TValue>> FindKeysWithPrefix<TValue>(this IDictionary<string, TValue> dictionary, string prefix)\n        {\n            Contract.Assert(dictionary != null);\n            Contract.Assert(prefix != null);\n\n            TValue exactMatchValue;\n            if (dictionary.TryGetValue(prefix, out exactMatchValue))\n            {\n                yield return new KeyValuePair<string, TValue>(prefix, exactMatchValue);\n            }\n\n            foreach (var entry in dictionary)\n            {\n                string key = entry.Key;\n\n                if (key.Length <= prefix.Length)\n                {\n                    continue;\n                }\n\n                if (!key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))\n                {\n                    continue;\n                }\n\n                // Everything is prefixed by the empty string\n                if (prefix.Length == 0)\n                {\n                    yield return entry;\n                }\n                else\n                {\n                    char charAfterPrefix = key[prefix.Length];\n                    switch (charAfterPrefix)\n                    {\n                        case '[':\n                        case '.':\n                            yield return entry;\n                            break;\n                    }\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Common/EfficientTypePropertyKey.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http\n{\n    // When the key is cached, it will be more efficient that a normal tuple, because the hash code call\n    // is rather expensive particularly for T as Type or T as long string.\n    internal class EfficientTypePropertyKey<T1, T2> : Tuple<T1, T2>\n    {\n        private int _hashCode;\n\n        public EfficientTypePropertyKey(T1 item1, T2 item2)\n            : base(item1, item2)\n        {\n            _hashCode = base.GetHashCode();\n        }\n\n        public override int GetHashCode()\n        {\n            return _hashCode;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Common/Empty.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Collections.Generic\n{\n    /// <summary>\n    /// Helper to provide empty instances with minimal allocation.\n    /// </summary>\n    internal static class Empty<T>\n    {\n        private static readonly T[] _emptyArray = new T[0];\n\n        /// <summary>\n        /// Returns a zero length array of type. Only allocates once per distinct type.\n        /// </summary>\n        public static T[] Array \n        { \n            get { return _emptyArray; } \n        }\n    }\n}\n"
  },
  {
    "path": "src/Common/Error.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Utility class for creating and unwrapping <see cref=\"Exception\"/> instances.\n    /// </summary>\n    internal static class Error\n    {\n        private const string HttpScheme = \"http\";\n        private const string HttpsScheme = \"https\";\n\n        /// <summary>\n        /// Formats the specified resource string using <see cref=\"M:CultureInfo.CurrentCulture\"/>.\n        /// </summary>\n        /// <param name=\"format\">A composite format string.</param>\n        /// <param name=\"args\">An object array that contains zero or more objects to format.</param>\n        /// <returns>The formatted string.</returns>\n        internal static string Format(string format, params object[] args)\n        {\n            return String.Format(CultureInfo.CurrentCulture, format, args);\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"ArgumentException\"/> with the provided properties.\n        /// </summary>\n        /// <param name=\"messageFormat\">A composite format string explaining the reason for the exception.</param>\n        /// <param name=\"messageArgs\">An object array that contains zero or more objects to format.</param>\n        /// <returns>The logged <see cref=\"Exception\"/>.</returns>\n        internal static ArgumentException Argument(string messageFormat, params object[] messageArgs)\n        {\n            return new ArgumentException(Error.Format(messageFormat, messageArgs));\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"ArgumentException\"/> with the provided properties.\n        /// </summary>\n        /// <param name=\"parameterName\">The name of the parameter that caused the current exception.</param>\n        /// <param name=\"messageFormat\">A composite format string explaining the reason for the exception.</param>\n        /// <param name=\"messageArgs\">An object array that contains zero or more objects to format.</param>\n        /// <returns>The logged <see cref=\"Exception\"/>.</returns>\n        internal static ArgumentException Argument(string parameterName, string messageFormat, params object[] messageArgs)\n        {\n            return new ArgumentException(Error.Format(messageFormat, messageArgs), parameterName);\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"ArgumentException\"/> with a message saying that the argument must be an \"http\" or \"https\" URI.\n        /// </summary>\n        /// <param name=\"parameterName\">The name of the parameter that caused the current exception.</param>\n        /// <param name=\"actualValue\">The value of the argument that causes this exception.</param>\n        /// <returns>The logged <see cref=\"Exception\"/>.</returns>\n        internal static ArgumentException ArgumentUriNotHttpOrHttpsScheme(string parameterName, Uri actualValue)\n        {\n            return new ArgumentException(Error.Format(CommonWebApiResources.ArgumentInvalidHttpUriScheme, actualValue, HttpScheme, HttpsScheme), parameterName);\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"ArgumentException\"/> with a message saying that the argument must be an absolute URI.\n        /// </summary>\n        /// <param name=\"parameterName\">The name of the parameter that caused the current exception.</param>\n        /// <param name=\"actualValue\">The value of the argument that causes this exception.</param>\n        /// <returns>The logged <see cref=\"Exception\"/>.</returns>\n        internal static ArgumentException ArgumentUriNotAbsolute(string parameterName, Uri actualValue)\n        {\n            return new ArgumentException(Error.Format(CommonWebApiResources.ArgumentInvalidAbsoluteUri, actualValue), parameterName);\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"ArgumentException\"/> with a message saying that the argument must be an absolute URI\n        /// without a query or fragment identifier and then logs it with <see cref=\"F:TraceLevel.Error\"/>.\n        /// </summary>\n        /// <param name=\"parameterName\">The name of the parameter that caused the current exception.</param>\n        /// <param name=\"actualValue\">The value of the argument that causes this exception.</param>\n        /// <returns>The logged <see cref=\"Exception\"/>.</returns>\n        internal static ArgumentException ArgumentUriHasQueryOrFragment(string parameterName, Uri actualValue)\n        {\n            return new ArgumentException(Error.Format(CommonWebApiResources.ArgumentUriHasQueryOrFragment, actualValue), parameterName);\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"ArgumentNullException\"/> with the provided properties.\n        /// </summary>\n        /// <returns>The logged <see cref=\"Exception\"/>.</returns>\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2208:InstantiateArgumentExceptionsCorrectly\", Justification = \"The purpose of this API is to return an error for properties\")]\n        internal static ArgumentNullException PropertyNull()\n        {\n            return new ArgumentNullException(\"value\");\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"ArgumentNullException\"/> with the provided properties.\n        /// </summary>\n        /// <param name=\"parameterName\">The name of the parameter that caused the current exception.</param>\n        /// <returns>The logged <see cref=\"Exception\"/>.</returns>\n        internal static ArgumentNullException ArgumentNull(string parameterName)\n        {\n            return new ArgumentNullException(parameterName);\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"ArgumentNullException\"/> with the provided properties.\n        /// </summary>\n        /// <param name=\"parameterName\">The name of the parameter that caused the current exception.</param>\n        /// <param name=\"messageFormat\">A composite format string explaining the reason for the exception.</param>\n        /// <param name=\"messageArgs\">An object array that contains zero or more objects to format.</param>\n        /// <returns>The logged <see cref=\"Exception\"/>.</returns>\n        internal static ArgumentNullException ArgumentNull(string parameterName, string messageFormat, params object[] messageArgs)\n        {\n            return new ArgumentNullException(parameterName, Error.Format(messageFormat, messageArgs));\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"ArgumentException\"/> with a default message.\n        /// </summary>\n        /// <param name=\"parameterName\">The name of the parameter that caused the current exception.</param>\n        /// <returns>The logged <see cref=\"Exception\"/>.</returns>\n        internal static ArgumentException ArgumentNullOrEmpty(string parameterName)\n        {\n            return Error.Argument(parameterName, CommonWebApiResources.ArgumentNullOrEmpty, parameterName);\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"ArgumentOutOfRangeException\"/> with the provided properties.\n        /// </summary>\n        /// <param name=\"parameterName\">The name of the parameter that caused the current exception.</param>\n        /// <param name=\"actualValue\">The value of the argument that causes this exception.</param>\n        /// <param name=\"messageFormat\">A composite format string explaining the reason for the exception.</param>\n        /// <param name=\"messageArgs\">An object array that contains zero or more objects to format.</param>\n        /// <returns>The logged <see cref=\"Exception\"/>.</returns>\n        internal static ArgumentOutOfRangeException ArgumentOutOfRange(string parameterName, object actualValue, string messageFormat, params object[] messageArgs)\n        {\n            return new ArgumentOutOfRangeException(parameterName, actualValue, Error.Format(messageFormat, messageArgs));\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"ArgumentOutOfRangeException\"/> with a message saying that the argument must be greater than or equal to <paramref name=\"minValue\"/>.\n        /// </summary>\n        /// <param name=\"parameterName\">The name of the parameter that caused the current exception.</param>\n        /// <param name=\"actualValue\">The value of the argument that causes this exception.</param>\n        /// <param name=\"minValue\">The minimum size of the argument.</param>\n        /// <returns>The logged <see cref=\"Exception\"/>.</returns>\n        internal static ArgumentOutOfRangeException ArgumentMustBeGreaterThanOrEqualTo(string parameterName, object actualValue, object minValue)\n        {\n            return new ArgumentOutOfRangeException(parameterName, actualValue, Error.Format(CommonWebApiResources.ArgumentMustBeGreaterThanOrEqualTo, minValue));\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"ArgumentOutOfRangeException\"/> with a message saying that the argument must be less than or equal to <paramref name=\"maxValue\"/>.\n        /// </summary>\n        /// <param name=\"parameterName\">The name of the parameter that caused the current exception.</param>\n        /// <param name=\"actualValue\">The value of the argument that causes this exception.</param>\n        /// <param name=\"maxValue\">The maximum size of the argument.</param>\n        /// <returns>The logged <see cref=\"Exception\"/>.</returns>\n        internal static ArgumentOutOfRangeException ArgumentMustBeLessThanOrEqualTo(string parameterName, object actualValue, object maxValue)\n        {\n            return new ArgumentOutOfRangeException(parameterName, actualValue, Error.Format(CommonWebApiResources.ArgumentMustBeLessThanOrEqualTo, maxValue));\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"KeyNotFoundException\"/> with a message saying that the key was not found.\n        /// </summary>\n        /// <returns>The logged <see cref=\"Exception\"/>.</returns>\n        internal static KeyNotFoundException KeyNotFound()\n        {\n            return new KeyNotFoundException();\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"KeyNotFoundException\"/> with a message saying that the key was not found.\n        /// </summary>\n        /// <param name=\"messageFormat\">A composite format string explaining the reason for the exception.</param>\n        /// <param name=\"messageArgs\">An object array that contains zero or more objects to format.</param>\n        /// <returns>The logged <see cref=\"Exception\"/>.</returns>\n        internal static KeyNotFoundException KeyNotFound(string messageFormat, params object[] messageArgs)\n        {\n            return new KeyNotFoundException(Error.Format(messageFormat, messageArgs));\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"ObjectDisposedException\"/> initialized according to guidelines.\n        /// </summary>\n        /// <param name=\"messageFormat\">A composite format string explaining the reason for the exception.</param>\n        /// <param name=\"messageArgs\">An object array that contains zero or more objects to format.</param>\n        /// <returns>The logged <see cref=\"Exception\"/>.</returns>\n        internal static ObjectDisposedException ObjectDisposed(string messageFormat, params object[] messageArgs)\n        {\n            // Pass in null, not disposedObject.GetType().FullName as per the above guideline\n            return new ObjectDisposedException(null, Error.Format(messageFormat, messageArgs));\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"OperationCanceledException\"/> initialized with the provided parameters.\n        /// </summary>\n        /// <returns>The logged <see cref=\"Exception\"/>.</returns>\n        internal static OperationCanceledException OperationCanceled()\n        {\n            return new OperationCanceledException();\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"OperationCanceledException\"/> initialized with the provided parameters.\n        /// </summary>\n        /// <param name=\"messageFormat\">A composite format string explaining the reason for the exception.</param>\n        /// <param name=\"messageArgs\">An object array that contains zero or more objects to format.</param>\n        /// <returns>The logged <see cref=\"Exception\"/>.</returns>\n        internal static OperationCanceledException OperationCanceled(string messageFormat, params object[] messageArgs)\n        {\n            return new OperationCanceledException(Error.Format(messageFormat, messageArgs));\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"ArgumentException\"/> for an invalid enum argument.\n        /// </summary>\n        /// <param name=\"parameterName\">The name of the parameter that caused the current exception.</param>\n        /// <param name=\"invalidValue\">The value of the argument that failed.</param>\n        /// <param name=\"enumClass\">A <see cref=\"Type\"/> that represents the enumeration class with the valid values.</param>\n        /// <returns>The logged <see cref=\"Exception\"/>.</returns>\n        internal static ArgumentException InvalidEnumArgument(string parameterName, int invalidValue, Type enumClass)\n        {\n            return new InvalidEnumArgumentException(parameterName, invalidValue, enumClass);\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"InvalidOperationException\"/>.\n        /// </summary>\n        /// <param name=\"messageFormat\">A composite format string explaining the reason for the exception.</param>\n        /// <param name=\"messageArgs\">An object array that contains zero or more objects to format.</param>\n        /// <returns>The logged <see cref=\"Exception\"/>.</returns>\n        internal static InvalidOperationException InvalidOperation(string messageFormat, params object[] messageArgs)\n        {\n            return new InvalidOperationException(Error.Format(messageFormat, messageArgs));\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"InvalidOperationException\"/>.\n        /// </summary>\n        /// <param name=\"innerException\">Inner exception</param>\n        /// <param name=\"messageFormat\">A composite format string explaining the reason for the exception.</param>\n        /// <param name=\"messageArgs\">An object array that contains zero or more objects to format.</param>\n        /// <returns>The logged <see cref=\"Exception\"/>.</returns>\n        internal static InvalidOperationException InvalidOperation(Exception innerException, string messageFormat, params object[] messageArgs)\n        {\n            return new InvalidOperationException(Error.Format(messageFormat, messageArgs), innerException);\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"NotSupportedException\"/>.\n        /// </summary>\n        /// <param name=\"messageFormat\">A composite format string explaining the reason for the exception.</param>\n        /// <param name=\"messageArgs\">An object array that contains zero or more objects to format.</param>\n        /// <returns>The logged <see cref=\"Exception\"/>.</returns>\n        internal static NotSupportedException NotSupported(string messageFormat, params object[] messageArgs)\n        {\n            return new NotSupportedException(Error.Format(messageFormat, messageArgs));\n        }\n\n#if NETSTANDARD1_3 // InvalidEnumArgumentException not available in netstandard1.3.\n        internal class InvalidEnumArgumentException : ArgumentException\n        {\n            public InvalidEnumArgumentException() : this(null)\n            { }\n\n            public InvalidEnumArgumentException(string message) : base(message)\n            { }\n\n            public InvalidEnumArgumentException(string message, Exception innerException) : base(message, innerException)\n            { }\n\n            public InvalidEnumArgumentException(string argumentName, int invalidValue, Type enumClass) : base(\n                Error.Format(CommonWebApiResources.InvalidEnumArgument, argumentName, invalidValue, enumClass.Name),\n                argumentName)\n            { }\n        }\n#endif\n    }\n}\n"
  },
  {
    "path": "src/Common/HashCodeCombiner.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\n\nnamespace Microsoft.Internal.Web.Utils\n{\n    internal class HashCodeCombiner\n    {\n        private long _combinedHash64 = 0x1505L;\n\n        public int CombinedHash\n        {\n            get { return _combinedHash64.GetHashCode(); }\n        }\n\n        public HashCodeCombiner Add(IEnumerable e)\n        {\n            if (e == null)\n            {\n                Add(0);\n            }\n            else\n            {\n                int count = 0;\n                foreach (object o in e)\n                {\n                    Add(o);\n                    count++;\n                }\n                Add(count);\n            }\n            return this;\n        }\n\n        public HashCodeCombiner Add(int i)\n        {\n            _combinedHash64 = ((_combinedHash64 << 5) + _combinedHash64) ^ i;\n            return this;\n        }\n\n        public HashCodeCombiner Add(object o)\n        {\n            int hashCode = (o != null) ? o.GetHashCode() : 0;\n            Add(hashCode);\n            return this;\n        }\n\n        public static HashCodeCombiner Start()\n        {\n            return new HashCodeCombiner();\n        }\n    }\n}\n"
  },
  {
    "path": "src/Common/HttpMethodHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Various helper methods for the static members of <see cref=\"HttpMethod\"/>. \n    /// </summary>\n    internal static class HttpMethodHelper\n    {\n        /// <summary>\n        /// Gets the static <see cref=\"HttpMethod\"/> instance for any given HTTP method name.\n        /// </summary>\n        /// <param name=\"method\">The HTTP request method.</param>\n        /// <returns>An existing static <see cref=\"HttpMethod\"/> or a new instance if the method was not found.</returns>\n        internal static HttpMethod GetHttpMethod(string method)\n        {\n            if (String.IsNullOrEmpty(method))\n            {\n                return null;\n            }\n\n            if (String.Equals(\"GET\", method, StringComparison.OrdinalIgnoreCase))\n            {\n                return HttpMethod.Get;\n            }\n\n            if (String.Equals(\"POST\", method, StringComparison.OrdinalIgnoreCase))\n            {\n                return HttpMethod.Post;\n            }\n\n            if (String.Equals(\"PUT\", method, StringComparison.OrdinalIgnoreCase))\n            {\n                return HttpMethod.Put;\n            }\n\n            if (String.Equals(\"DELETE\", method, StringComparison.OrdinalIgnoreCase))\n            {\n                return HttpMethod.Delete;\n            }\n\n            if (String.Equals(\"HEAD\", method, StringComparison.OrdinalIgnoreCase))\n            {\n                return HttpMethod.Head;\n            }\n\n            if (String.Equals(\"OPTIONS\", method, StringComparison.OrdinalIgnoreCase))\n            {\n                return HttpMethod.Options;\n            }\n\n            if (String.Equals(\"TRACE\", method, StringComparison.OrdinalIgnoreCase))\n            {\n                return HttpMethod.Trace;\n            }\n\n            return new HttpMethod(method);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Common/ListWrapperCollection.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Collections.ObjectModel\n{\n    /// <summary>\n    /// A class that inherits from Collection of T but also exposes its underlying data as List of T for performance.\n    /// </summary>\n    internal sealed class ListWrapperCollection<T> : Collection<T>\n    {\n        private readonly List<T> _items;\n\n        internal ListWrapperCollection()\n            : this(new List<T>())\n        {\n        }\n\n        internal ListWrapperCollection(List<T> list)\n            : base(list)\n        {\n            _items = list;\n        }\n\n        internal List<T> ItemsList\n        {\n            get { return _items; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Common/NonOwnedStream.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.IO;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http\n{\n    /// <summary>Represents a stream that replaces another stream to prevent actually closing that stream.</summary>\n    /// <remarks>\n    /// This class uses the Decorator [GoF] pattern; it forwards all calls except those related to Dispose and Close.\n    /// </remarks>\n    internal class NonOwnedStream : Stream\n    {\n        protected NonOwnedStream()\n        {\n        }\n\n        public NonOwnedStream(Stream innerStream)\n        {\n            if (innerStream == null)\n            {\n                throw new ArgumentNullException(\"innerStream\");\n            }\n\n            InnerStream = innerStream;\n        }\n\n        protected Stream InnerStream\n        {\n            get;\n            set;\n        }\n\n        protected bool IsDisposed\n        {\n            get;\n            private set;\n        }\n\n        public override bool CanRead\n        {\n            get\n            {\n                // Per documentation, CanRead should return false rather than throw when the stream is closed.\n                if (IsDisposed)\n                {\n                    return false;\n                }\n\n                return InnerStream.CanRead;\n            }\n        }\n\n        public override bool CanSeek\n        {\n            get\n            {\n                // Per documentation, CanSeek should return false rather than throw when the stream is closed.\n                if (IsDisposed)\n                {\n                    return false;\n                }\n\n                return InnerStream.CanSeek;\n            }\n        }\n\n        public override bool CanTimeout\n        {\n            get\n            {\n                // Per documentation, this value apparently is a constant for a particular implementation class.\n                // Throwing when disposed appears inappropriate here.\n                return InnerStream.CanTimeout;\n            }\n        }\n\n        public override bool CanWrite\n        {\n            get\n            {\n                // Per documentation, CanWrite should return false rather than throw when the stream is closed.\n                if (IsDisposed)\n                {\n                    return false;\n                }\n\n                return InnerStream.CanWrite;\n            }\n        }\n\n        public override long Length\n        {\n            get\n            {\n                // Per documentation, this property throws ObjectDisposedException if the stream is closed.\n                ThrowIfDisposed();\n                return InnerStream.Length;\n            }\n        }\n\n        public override long Position\n        {\n            get\n            {\n                // Per documentation, this property throws ObjectDisposedException if the stream is closed.\n                ThrowIfDisposed();\n                return InnerStream.Position;\n            }\n            set\n            {\n                // Per documentation, this property throws ObjectDisposedException if the stream is closed.\n                ThrowIfDisposed();\n                InnerStream.Position = value;\n            }\n        }\n\n        public override int ReadTimeout\n        {\n            get\n            {\n                // Documentation does not state the behavior when the stream is closed. The NetworkStream\n                // implementation suggests the contract should be to throw ObjectDisposedException when the stream is\n                // closed.\n                ThrowIfDisposed();\n                return InnerStream.ReadTimeout;\n            }\n            set\n            {\n                // Documentation does not state the behavior when the stream is closed. The NetworkStream\n                // implementation suggests the contract should be to throw ObjectDisposedException when the stream is\n                // closed.\n                ThrowIfDisposed();\n                InnerStream.ReadTimeout = value;\n            }\n        }\n\n        public override int WriteTimeout\n        {\n            get\n            {\n                // Documentation does not state the behavior when the stream is closed. The NetworkStream\n                // implementation suggests the contract should be to throw ObjectDisposedException when the stream is\n                // closed.\n                ThrowIfDisposed();\n                return InnerStream.WriteTimeout;\n            }\n            set\n            {\n                // Documentation does not state the behavior when the stream is closed. The NetworkStream\n                // implementation suggests the contract should be to throw ObjectDisposedException when the stream is\n                // closed.\n                ThrowIfDisposed();\n                InnerStream.WriteTimeout = value;\n            }\n        }\n\n        public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)\n        {\n            ThrowIfDisposed();\n            return InnerStream.BeginRead(buffer, offset, count, callback, state);\n        }\n\n        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)\n        {\n            ThrowIfDisposed();\n            return InnerStream.BeginWrite(buffer, offset, count, callback, state);\n        }\n\n        public override void Close()\n        {\n            // base.Close() calls Dispose(true) and GC.SuppressFinalize(this), which is exactly what we want.\n            // Note that we do NOT call _innerStream.Close here, as that would actually close the original source\n            // stream, which is the one thing this class is designed to prevent.\n            base.Close();\n        }\n\n        public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)\n        {\n            ThrowIfDisposed();\n            return InnerStream.CopyToAsync(destination, bufferSize, cancellationToken);\n        }\n\n        // Not overriding MarshalByRefObj.CreateObjRef.\n\n        // Not overriding Stream.CreateWaitHandle.\n\n        [SuppressMessage(\n            \"Microsoft.Usage\", \n            \"CA2215:Dispose methods should call base class dispose\",\n            Justification = \"We're intentionally preventing a double dispose here.\")]\n        protected override void Dispose(bool disposing)\n        {\n            // Note that we do NOT call _innerStream.Dispose or Close here, as that would actually close the original\n            // source stream, which is the one thing this class is designed to prevent.\n\n            if (!IsDisposed)\n            {\n                base.Dispose(disposing);\n                IsDisposed = true;\n            }\n        }\n\n        public override int EndRead(IAsyncResult asyncResult)\n        {\n            ThrowIfDisposed();\n            return InnerStream.EndRead(asyncResult);\n        }\n\n        public override void EndWrite(IAsyncResult asyncResult)\n        {\n            ThrowIfDisposed();\n            InnerStream.EndWrite(asyncResult);\n        }\n\n        // Not overriding Object.Equals.\n\n        public override void Flush()\n        {\n            ThrowIfDisposed();\n            InnerStream.Flush();\n        }\n\n        public override Task FlushAsync(CancellationToken cancellationToken)\n        {\n            ThrowIfDisposed();\n            return InnerStream.FlushAsync(cancellationToken);\n        }\n\n        // Not overriding Object.GetHashCode.\n\n        // Not overriding MarshalByRefObj.InitializeLifetimeService.\n\n        // Per documentation, don't override Stream.ObjectInvariant.\n\n        public override int Read(byte[] buffer, int offset, int count)\n        {\n            ThrowIfDisposed();\n            return InnerStream.Read(buffer, offset, count);\n        }\n\n        public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)\n        {\n            ThrowIfDisposed();\n            return InnerStream.ReadAsync(buffer, offset, count, cancellationToken);\n        }\n\n        public override int ReadByte()\n        {\n            ThrowIfDisposed();\n            return InnerStream.ReadByte();\n        }\n\n        public override long Seek(long offset, SeekOrigin origin)\n        {\n            ThrowIfDisposed();\n            return InnerStream.Seek(offset, origin);\n        }\n\n        public override void SetLength(long value)\n        {\n            ThrowIfDisposed();\n            InnerStream.SetLength(value);\n        }\n\n        // Not overriding Object.ToString().\n\n        public override void Write(byte[] buffer, int offset, int count)\n        {\n            ThrowIfDisposed();\n            InnerStream.Write(buffer, offset, count);\n        }\n\n        public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)\n        {\n            ThrowIfDisposed();\n            return InnerStream.WriteAsync(buffer, offset, count, cancellationToken);\n        }\n\n        public override void WriteByte(byte value)\n        {\n            ThrowIfDisposed();\n            InnerStream.WriteByte(value);\n        }\n\n        protected void ThrowIfDisposed()\n        {\n            if (IsDisposed)\n            {\n                throw new ObjectDisposedException(null);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Common/PathHelpers.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\n\nnamespace System.Web\n{\n    /// <summary>\n    /// Helpers for working with IO paths.\n    /// </summary>\n    internal static class PathHelpers\n    {\n        /// <summary>\n        /// Returns whether the path has the specified file extension.\n        /// </summary>\n        public static bool EndsWithExtension(string path, string extension)\n        {\n            Contract.Assert(path != null);\n            Contract.Assert(extension != null && extension.Length > 0);\n\n            if (path.EndsWith(extension, StringComparison.OrdinalIgnoreCase))\n            {\n                int extensionLength = extension.Length;\n                int pathLength = path.Length;\n                return (pathLength > extensionLength && path[pathLength - extensionLength - 1] == '.');\n            }\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Common/PrefixContainer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web\n{\n    /// <summary>\n    /// This is a container for prefix values. It normalizes all the values into dotted-form and then stores\n    /// them in a sorted array. All queries for prefixes are also normalized to dotted-form, and searches\n    /// for ContainsPrefix are done with a binary search.\n    /// </summary>\n    internal class PrefixContainer\n    {\n        private readonly ICollection<string> _originalValues;\n        private readonly string[] _sortedValues;\n\n        internal PrefixContainer(ICollection<string> values)\n        {\n            if (values == null)\n            {\n                throw new ArgumentNullException(\"values\");\n            }\n\n            _originalValues = values;\n            _sortedValues = _originalValues.ToArrayWithoutNulls();\n            Array.Sort(_sortedValues, StringComparer.OrdinalIgnoreCase);\n        }\n\n        internal bool ContainsPrefix(string prefix)\n        {\n            if (prefix == null)\n            {\n                throw new ArgumentNullException(\"prefix\");\n            }\n\n            if (prefix.Length == 0)\n            {\n                return _sortedValues.Length > 0; // only match empty string when we have some value\n            }\n\n            PrefixComparer prefixComparer = new PrefixComparer(prefix);\n            bool containsPrefix = Array.BinarySearch(_sortedValues, prefix, prefixComparer) > -1;\n            if (!containsPrefix)\n            {\n                // If there's something in the search boundary that starts with the same name\n                // as the collection prefix that we're trying to find, the binary search would actually fail.\n                // For example, let's say we have foo.a, foo.bE and foo.b[0]. Calling Array.BinarySearch\n                // will fail to find foo.b because it will land on foo.bE, then look at foo.a and finally\n                // failing to find the prefix which is actually present in the container (foo.b[0]).\n                // Here we're doing another pass looking specifically for collection prefix.\n                containsPrefix = Array.BinarySearch(_sortedValues, prefix + \"[\", prefixComparer) > -1;\n            }\n            return containsPrefix;\n        }\n\n        // Given \"foo.bar\", \"foo.hello\", \"something.other\", foo[abc].baz and asking for prefix \"foo\" will return:\n        // - \"bar\"/\"foo.bar\"\n        // - \"hello\"/\"foo.hello\"\n        // - \"abc\"/\"foo[abc]\"\n        internal IDictionary<string, string> GetKeysFromPrefix(string prefix)\n        {\n            IDictionary<string, string> result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);\n\n            foreach (var entry in _originalValues)\n            {\n                if (entry != null)\n                {\n                    if (entry.Length == prefix.Length)\n                    {\n                        // No key in this entry\n                        continue;\n                    }\n\n                    if (prefix.Length == 0)\n                    {\n                        GetKeyFromEmptyPrefix(entry, result);\n                    }\n                    else if (entry.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))\n                    {\n                        GetKeyFromNonEmptyPrefix(prefix, entry, result);\n                    }\n                }\n            }\n\n            return result;\n        }\n\n        private static void GetKeyFromEmptyPrefix(string entry, IDictionary<string, string> results)\n        {\n            string key;\n            int dotPosition = entry.IndexOf('.');\n            int bracketPosition = entry.IndexOf('[');\n            int delimiterPosition = -1;\n\n            if (dotPosition == -1)\n            {\n                if (bracketPosition != -1)\n                {\n                    delimiterPosition = bracketPosition;\n                }\n            }\n            else\n            {\n                if (bracketPosition == -1)\n                {\n                    delimiterPosition = dotPosition;\n                }\n                else\n                {\n                    delimiterPosition = Math.Min(dotPosition, bracketPosition);\n                }\n            }\n\n            key = delimiterPosition == -1 ? entry : entry.Substring(0, delimiterPosition);\n            results[key] = key;\n        }\n\n        private static void GetKeyFromNonEmptyPrefix(string prefix, string entry, IDictionary<string, string> results)\n        {\n            string key = null;\n            string fullName = null;\n            int keyPosition = prefix.Length + 1;\n\n            switch (entry[prefix.Length])\n            {\n                case '.':\n                    int dotPosition = entry.IndexOf('.', keyPosition);\n                    if (dotPosition == -1)\n                    {\n                        dotPosition = entry.Length;\n                    }\n\n                    key = entry.Substring(keyPosition, dotPosition - keyPosition);\n                    fullName = entry.Substring(0, dotPosition);\n                    break;\n\n                case '[':\n                    int bracketPosition = entry.IndexOf(']', keyPosition);\n                    if (bracketPosition == -1)\n                    {\n                        // Malformed for dictionary\n                        return;\n                    }\n\n                    key = entry.Substring(keyPosition, bracketPosition - keyPosition);\n                    fullName = entry.Substring(0, bracketPosition + 1);\n                    break;\n\n                default:\n                    return;\n            }\n\n            if (!results.ContainsKey(key))\n            {\n                results.Add(key, fullName);\n            }\n        }\n\n        internal static bool IsPrefixMatch(string prefix, string testString)\n        {\n            if (testString == null)\n            {\n                return false;\n            }\n\n            if (prefix.Length == 0)\n            {\n                return true; // shortcut - non-null testString matches empty prefix\n            }\n\n            if (prefix.Length > testString.Length)\n            {\n                return false; // not long enough\n            }\n\n            if (!testString.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))\n            {\n                return false; // prefix doesn't match\n            }\n\n            if (testString.Length == prefix.Length)\n            {\n                return true; // exact match\n            }\n\n            // invariant: testString.Length > prefix.Length\n            switch (testString[prefix.Length])\n            {\n                case '.':\n                case '[':\n                    return true; // known delimiters\n\n                default:\n                    return false; // not known delimiter\n            }\n        }\n\n        private class PrefixComparer : IComparer<String>\n        {\n            private string _prefix;\n\n            public PrefixComparer(string prefix)\n            {\n                _prefix = prefix;\n            }\n\n            public int Compare(string x, string y)\n            {\n                string testString = Object.ReferenceEquals(x, _prefix) ? y : x;\n                if (IsPrefixMatch(_prefix, testString))\n                {\n                    return 0;\n                }\n\n                return StringComparer.OrdinalIgnoreCase.Compare(x, y);\n            }\n        }\n    }\n}"
  },
  {
    "path": "src/Common/PropertyHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing System.Reflection;\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Internal\n#else\nnamespace System.Web.WebPages\n#endif\n{\n    internal class PropertyHelper\n    {\n        private static ConcurrentDictionary<Type, PropertyHelper[]> _reflectionCache = new ConcurrentDictionary<Type, PropertyHelper[]>();\n\n        private Func<object, object> _valueGetter;\n\n        /// <summary>\n        /// Initializes a fast property helper. This constructor does not cache the helper.\n        /// </summary>\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2214:DoNotCallOverridableMethodsInConstructors\", Justification = \"This is intended the Name is auto set differently per type and the type is internal\")]\n        public PropertyHelper(PropertyInfo property)\n        {\n            Contract.Assert(property != null);\n\n            Name = property.Name;\n            _valueGetter = MakeFastPropertyGetter(property);\n        }\n\n        /// <summary>\n        /// Creates a single fast property setter. The result is not cached.\n        /// </summary>\n        /// <param name=\"propertyInfo\">propertyInfo to extract the getter for.</param>\n        /// <returns>a fast setter.</returns>\n        /// <remarks>This method is more memory efficient than a dynamically compiled lambda, and about the same speed.</remarks>\n        public static Action<TDeclaringType, object> MakeFastPropertySetter<TDeclaringType>(PropertyInfo propertyInfo)\n            where TDeclaringType : class\n        {\n            Contract.Assert(propertyInfo != null);\n\n            MethodInfo setMethod = propertyInfo.GetSetMethod();\n\n            Contract.Assert(setMethod != null);\n            Contract.Assert(!setMethod.IsStatic);\n            Contract.Assert(setMethod.GetParameters().Length == 1);\n            Contract.Assert(!propertyInfo.ReflectedType.IsValueType);\n\n            // Instance methods in the CLR can be turned into static methods where the first parameter\n            // is open over \"this\". This parameter is always passed by reference, so we have a code\n            // path for value types and a code path for reference types.\n            Type typeInput = propertyInfo.ReflectedType;\n            Type typeValue = setMethod.GetParameters()[0].ParameterType;\n\n            Delegate callPropertySetterDelegate;\n\n            // Create a delegate TValue -> \"TDeclaringType.Property\"\n            var propertySetterAsAction = setMethod.CreateDelegate(typeof(Action<,>).MakeGenericType(typeInput, typeValue));\n            var callPropertySetterClosedGenericMethod = _callPropertySetterOpenGenericMethod.MakeGenericMethod(typeInput, typeValue);\n            callPropertySetterDelegate = Delegate.CreateDelegate(typeof(Action<TDeclaringType, object>), propertySetterAsAction, callPropertySetterClosedGenericMethod);\n\n            return (Action<TDeclaringType, object>)callPropertySetterDelegate;\n        }\n\n        public virtual string Name { get; protected set; }\n\n        public object GetValue(object instance)\n        {\n            Contract.Assert(_valueGetter != null, \"Must call Initialize before using this object\");\n\n            return _valueGetter(instance);\n        }\n\n        /// <summary>\n        /// Creates and caches fast property helpers that expose getters for every public get property on the underlying type.\n        /// </summary>\n        /// <param name=\"instance\">the instance to extract property accessors for.</param>\n        /// <returns>a cached array of all public property getters from the underlying type of this instance.</returns>\n        public static PropertyHelper[] GetProperties(object instance)\n        {\n            return GetProperties(instance, CreateInstance, _reflectionCache);\n        }\n\n        /// <summary>\n        /// Creates a single fast property getter. The result is not cached.\n        /// </summary>\n        /// <param name=\"propertyInfo\">propertyInfo to extract the getter for.</param>\n        /// <returns>a fast getter.</returns>\n        /// <remarks>This method is more memory efficient than a dynamically compiled lambda, and about the same speed.</remarks>\n        public static Func<object, object> MakeFastPropertyGetter(PropertyInfo propertyInfo)\n        {\n            Contract.Assert(propertyInfo != null);\n\n            MethodInfo getMethod = propertyInfo.GetGetMethod();\n            Contract.Assert(getMethod != null);\n            Contract.Assert(!getMethod.IsStatic);\n            Contract.Assert(getMethod.GetParameters().Length == 0);\n\n            // Instance methods in the CLR can be turned into static methods where the first parameter\n            // is open over \"this\". This parameter is always passed by reference, so we have a code\n            // path for value types and a code path for reference types.\n            Type typeInput = getMethod.ReflectedType;\n            Type typeOutput = getMethod.ReturnType;\n\n            Delegate callPropertyGetterDelegate;\n            if (typeInput.IsValueType)\n            {\n                // Create a delegate (ref TDeclaringType) -> TValue\n                Delegate propertyGetterAsFunc = getMethod.CreateDelegate(typeof(ByRefFunc<,>).MakeGenericType(typeInput, typeOutput));\n                MethodInfo callPropertyGetterClosedGenericMethod = _callPropertyGetterByReferenceOpenGenericMethod.MakeGenericMethod(typeInput, typeOutput);\n                callPropertyGetterDelegate = Delegate.CreateDelegate(typeof(Func<object, object>), propertyGetterAsFunc, callPropertyGetterClosedGenericMethod);\n            }\n            else\n            {\n                // Create a delegate TDeclaringType -> TValue\n                Delegate propertyGetterAsFunc = getMethod.CreateDelegate(typeof(Func<,>).MakeGenericType(typeInput, typeOutput));\n                MethodInfo callPropertyGetterClosedGenericMethod = _callPropertyGetterOpenGenericMethod.MakeGenericMethod(typeInput, typeOutput);\n                callPropertyGetterDelegate = Delegate.CreateDelegate(typeof(Func<object, object>), propertyGetterAsFunc, callPropertyGetterClosedGenericMethod);\n            }\n\n            return (Func<object, object>)callPropertyGetterDelegate;\n        }\n\n        private static PropertyHelper CreateInstance(PropertyInfo property)\n        {\n            return new PropertyHelper(property);\n        }\n\n        // Implementation of the fast getter.\n        private delegate TValue ByRefFunc<TDeclaringType, TValue>(ref TDeclaringType arg);\n\n        private static readonly MethodInfo _callPropertyGetterOpenGenericMethod = typeof(PropertyHelper).GetMethod(\"CallPropertyGetter\", BindingFlags.NonPublic | BindingFlags.Static);\n        private static readonly MethodInfo _callPropertyGetterByReferenceOpenGenericMethod = typeof(PropertyHelper).GetMethod(\"CallPropertyGetterByReference\", BindingFlags.NonPublic | BindingFlags.Static);\n\n        private static object CallPropertyGetter<TDeclaringType, TValue>(Func<TDeclaringType, TValue> getter, object @this)\n        {\n            return getter((TDeclaringType)@this);\n        }\n\n        private static object CallPropertyGetterByReference<TDeclaringType, TValue>(ByRefFunc<TDeclaringType, TValue> getter, object @this)\n        {\n            TDeclaringType unboxed = (TDeclaringType)@this;\n            return getter(ref unboxed);\n        }\n\n        // Implementation of the fast setter.\n        private static readonly MethodInfo _callPropertySetterOpenGenericMethod = typeof(PropertyHelper).GetMethod(\"CallPropertySetter\", BindingFlags.NonPublic | BindingFlags.Static);\n\n        private static void CallPropertySetter<TDeclaringType, TValue>(Action<TDeclaringType, TValue> setter, object @this, object value)\n        {\n            setter((TDeclaringType)@this, (TValue)value);\n        }\n\n        protected static PropertyHelper[] GetProperties(object instance,\n                                                        Func<PropertyInfo, PropertyHelper> createPropertyHelper,\n                                                        ConcurrentDictionary<Type, PropertyHelper[]> cache)\n        {\n            // Using an array rather than IEnumerable, as this will be called on the hot path numerous times.\n            PropertyHelper[] helpers;\n\n            Type type = instance.GetType();\n\n            if (!cache.TryGetValue(type, out helpers))\n            {\n                // We avoid loading indexed properties using the where statement.\n                // Indexed properties are not useful (or valid) for grabbing properties off an anonymous object.\n                IEnumerable<PropertyInfo> properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance)\n                                                           .Where(prop => prop.GetIndexParameters().Length == 0 &&\n                                                                          prop.GetMethod != null);\n\n                var newHelpers = new List<PropertyHelper>();\n\n                foreach (PropertyInfo property in properties)\n                {\n                    PropertyHelper propertyHelper = createPropertyHelper(property);\n\n                    newHelpers.Add(propertyHelper);\n                }\n\n                helpers = newHelpers.ToArray();\n                cache.TryAdd(type, helpers);\n            }\n\n            return helpers;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Common/Routing/Constraints/AlphaRouteConstraint.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing.Constraints\n#else\nnamespace System.Web.Mvc.Routing.Constraints\n#endif\n{\n    /// <summary>\n    /// Constrains a route parameter to contain only lowercase or uppercase letters A through Z in the English alphabet.\n    /// </summary>\n    public class AlphaRouteConstraint : RegexRouteConstraint\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"AlphaRouteConstraint\" /> class.\n        /// </summary>\n        public AlphaRouteConstraint() : base(@\"^[a-z]*$\")\n        {\n        }\n    }\n}"
  },
  {
    "path": "src/Common/Routing/Constraints/BoolRouteConstraint.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\n#if ASPNETWEBAPI\nusing System.Net.Http;\n#else\nusing System.Web.Routing;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing.Constraints\n#else\nnamespace System.Web.Mvc.Routing.Constraints\n#endif\n{\n    /// <summary>\n    /// Constrains a route parameter to represent only Boolean values.\n    /// </summary>\n#if ASPNETWEBAPI\n    public class BoolRouteConstraint : IHttpRouteConstraint\n#else\n    public class BoolRouteConstraint : IRouteConstraint\n#endif\n    {\n        /// <inheritdoc />\n#if ASPNETWEBAPI\n        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)\n#else\n        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)\n#endif\n        {\n            if (parameterName == null)\n            {\n                throw Error.ArgumentNull(\"parameterName\");\n            }\n\n            if (values == null)\n            {\n                throw Error.ArgumentNull(\"values\");\n            }\n\n            object value;\n            if (values.TryGetValue(parameterName, out value) && value != null)\n            {\n                if (value is bool)\n                {\n                    return true;\n                }\n\n                bool result;\n                string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);\n                return Boolean.TryParse(valueString, out result);\n            }\n            return false;\n        }\n    }\n}"
  },
  {
    "path": "src/Common/Routing/Constraints/CompoundRouteConstraint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n#if ASPNETWEBAPI\nusing System.Net.Http;\n#else\nusing System.Web.Routing;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing.Constraints\n#else\nnamespace System.Web.Mvc.Routing.Constraints\n#endif\n{\n    /// <summary>\n    /// Constrains a route by several child constraints.\n    /// </summary>\n#if ASPNETWEBAPI\n    public class CompoundRouteConstraint : IHttpRouteConstraint\n#else\n    public class CompoundRouteConstraint : IRouteConstraint\n#endif\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"CompoundRouteConstraint\" /> class.\n        /// </summary>\n        /// <param name=\"constraints\">The child constraints that must match for this constraint to match.</param>\n#if ASPNETWEBAPI\n        public CompoundRouteConstraint(IList<IHttpRouteConstraint> constraints)\n#else\n        public CompoundRouteConstraint(IList<IRouteConstraint> constraints)\n#endif\n        {\n            if (constraints == null)\n            {\n                throw Error.ArgumentNull(\"constraints\");\n            }\n\n            Constraints = constraints;\n        }\n\n        /// <summary>\n        /// Gets the child constraints that must match for this constraint to match.\n        /// </summary>\n#if ASPNETWEBAPI\n        public IEnumerable<IHttpRouteConstraint> Constraints { get; private set; }\n#else\n        public IEnumerable<IRouteConstraint> Constraints { get; private set; }\n#endif\n\n        /// <inheritdoc />\n#if ASPNETWEBAPI\n        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)\n#else\n        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)\n#endif\n        {\n            foreach (var constraint in Constraints)\n            {\n#if ASPNETWEBAPI\n                if (!constraint.Match(request, route, parameterName, values, routeDirection))\n#else\n                if (!constraint.Match(httpContext, route, parameterName, values, routeDirection))\n#endif\n                {\n                    return false;\n                }\n            }\n            return true;\n        }\n    }\n}"
  },
  {
    "path": "src/Common/Routing/Constraints/DateTimeRouteConstraint.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\n#if ASPNETWEBAPI\nusing System.Net.Http;\n#else\nusing System.Web.Routing;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing.Constraints\n#else\nnamespace System.Web.Mvc.Routing.Constraints\n#endif\n{\n    /// <summary>\n    /// Constrains a route parameter to represent only <see cref=\"DateTime\"/> values.\n    /// </summary>\n#if ASPNETWEBAPI\n    public class DateTimeRouteConstraint : IHttpRouteConstraint\n#else\n    public class DateTimeRouteConstraint : IRouteConstraint\n#endif\n    {\n        /// <inheritdoc />\n#if ASPNETWEBAPI\n        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)\n#else\n        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)\n#endif\n        {\n            if (parameterName == null)\n            {\n                throw Error.ArgumentNull(\"parameterName\");\n            }\n\n            if (values == null)\n            {\n                throw Error.ArgumentNull(\"values\");\n            }\n\n            object value;\n            if (values.TryGetValue(parameterName, out value) && value != null)\n            {\n                if (value is DateTime)\n                {\n                    return true;\n                }\n\n                DateTime result;\n                string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);\n                return DateTime.TryParse(valueString, CultureInfo.InvariantCulture, DateTimeStyles.None, out result);\n            }\n            return false;\n        }\n    }\n}"
  },
  {
    "path": "src/Common/Routing/Constraints/DecimalRouteConstraint.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\n#if ASPNETWEBAPI\nusing System.Net.Http;\n#else\nusing System.Web.Routing;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing.Constraints\n#else\nnamespace System.Web.Mvc.Routing.Constraints\n#endif\n{\n    /// <summary>\n    /// Constrains a route parameter to represent only decimal values.\n    /// </summary>\n#if ASPNETWEBAPI\n    public class DecimalRouteConstraint : IHttpRouteConstraint\n#else\n    public class DecimalRouteConstraint : IRouteConstraint\n#endif\n    {\n        /// <inheritdoc />\n#if ASPNETWEBAPI\n        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)\n#else\n        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)\n#endif\n        {\n            if (parameterName == null)\n            {\n                throw Error.ArgumentNull(\"parameterName\");\n            }\n\n            if (values == null)\n            {\n                throw Error.ArgumentNull(\"values\");\n            }\n\n            object value;\n            if (values.TryGetValue(parameterName, out value) && value != null)\n            {\n                if (value is decimal)\n                {\n                    return true;\n                }\n\n                decimal result;\n                string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);\n                return Decimal.TryParse(valueString, NumberStyles.Number, CultureInfo.InvariantCulture, out result);\n            }\n            return false;\n        }\n    }\n}"
  },
  {
    "path": "src/Common/Routing/Constraints/DoubleRouteConstraint.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\n#if ASPNETWEBAPI\nusing System.Net.Http;\n#else\nusing System.Web.Routing;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing.Constraints\n#else\nnamespace System.Web.Mvc.Routing.Constraints\n#endif\n{\n    /// <summary>\n    /// Constrains a route parameter to represent only 64-bit floating-point values.\n    /// </summary>\n#if ASPNETWEBAPI\n    public class DoubleRouteConstraint : IHttpRouteConstraint\n#else\n    public class DoubleRouteConstraint : IRouteConstraint\n#endif\n    {\n        /// <inheritdoc />\n#if ASPNETWEBAPI\n        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)\n#else\n        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)\n#endif\n        {\n            if (parameterName == null)\n            {\n                throw Error.ArgumentNull(\"parameterName\");\n            }\n\n            if (values == null)\n            {\n                throw Error.ArgumentNull(\"values\");\n            }\n\n            object value;\n            if (values.TryGetValue(parameterName, out value) && value != null)\n            {\n                if (value is double)\n                {\n                    return true;\n                }\n\n                double result;\n                string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);\n                return Double.TryParse(valueString, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out result);\n            }\n            return false;\n        }\n    }\n}"
  },
  {
    "path": "src/Common/Routing/Constraints/FloatRouteConstraint.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\n#if ASPNETWEBAPI\nusing System.Net.Http;\n#else\nusing System.Web.Mvc;\nusing System.Web.Routing;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing.Constraints\n#else\nnamespace System.Web.Mvc.Routing.Constraints\n#endif\n{\n    /// <summary>\n    /// Constrains a route parameter to represent only 32-bit floating-point values.\n    /// </summary>\n#if ASPNETWEBAPI\n    public class FloatRouteConstraint : IHttpRouteConstraint\n#else\n    public class FloatRouteConstraint : IRouteConstraint\n#endif\n    {\n        /// <inheritdoc />\n#if ASPNETWEBAPI\n        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)\n#else\n        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)\n#endif\n        {\n            if (parameterName == null)\n            {\n                throw Error.ArgumentNull(\"parameterName\");\n            }\n\n            if (values == null)\n            {\n                throw Error.ArgumentNull(\"values\");\n            }\n\n            object value;\n            if (values.TryGetValue(parameterName, out value) && value != null)\n            {\n                if (value is float)\n                {\n                    return true;\n                }\n\n                float result;\n                string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);\n                return Single.TryParse(valueString, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out result);\n            }\n            return false;\n        }\n    }\n}"
  },
  {
    "path": "src/Common/Routing/Constraints/GuidRouteConstraint.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\n#if ASPNETWEBAPI\nusing System.Net.Http;\n#else\nusing System.Web.Mvc;\nusing System.Web.Routing;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing.Constraints\n#else\nnamespace System.Web.Mvc.Routing.Constraints\n#endif\n{\n    /// <summary>\n    /// Constrains a route parameter to represent only <see cref=\"Guid\"/> values.\n    /// </summary>\n#if ASPNETWEBAPI\n    public class GuidRouteConstraint : IHttpRouteConstraint\n#else\n    public class GuidRouteConstraint : IRouteConstraint\n#endif\n    {\n        /// <inheritdoc />\n#if ASPNETWEBAPI\n        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)\n#else\n        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)\n#endif\n        {\n            if (parameterName == null)\n            {\n                throw Error.ArgumentNull(\"parameterName\");\n            }\n\n            if (values == null)\n            {\n                throw Error.ArgumentNull(\"values\");\n            }\n\n            object value;\n            if (values.TryGetValue(parameterName, out value) && value != null)\n            {\n                if (value is Guid)\n                {\n                    return true;\n                }\n\n                Guid result;\n                string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);\n                return Guid.TryParse(valueString, out result);\n            }\n            return false;\n        }\n    }\n}"
  },
  {
    "path": "src/Common/Routing/Constraints/IntRouteConstraint.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\n#if ASPNETWEBAPI\nusing System.Net.Http;\n#else\nusing System.Web.Routing;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing.Constraints\n#else\nnamespace System.Web.Mvc.Routing.Constraints\n#endif\n{\n    /// <summary>\n    /// Constrains a route parameter to represent only 32-bit integer values.\n    /// </summary>\n#if ASPNETWEBAPI\n    public class IntRouteConstraint : IHttpRouteConstraint\n#else\n    public class IntRouteConstraint : IRouteConstraint\n#endif\n    {\n        /// <inheritdoc />\n#if ASPNETWEBAPI\n        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)\n#else\n        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)\n#endif\n        {\n            if (parameterName == null)\n            {\n                throw Error.ArgumentNull(\"parameterName\");\n            }\n\n            if (values == null)\n            {\n                throw Error.ArgumentNull(\"values\");\n            }\n\n            object value;\n            if (values.TryGetValue(parameterName, out value) && value != null)\n            {\n                if (value is int)\n                {\n                    return true;\n                }\n\n                int result;\n                string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);\n                return Int32.TryParse(valueString, NumberStyles.Integer, CultureInfo.InvariantCulture, out result);\n            }\n            return false;\n        }\n    }\n}"
  },
  {
    "path": "src/Common/Routing/Constraints/LengthRouteConstraint.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\n#if ASPNETWEBAPI\nusing System.Net.Http;\n#else\nusing System.Web.Routing;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing.Constraints\n#else\nnamespace System.Web.Mvc.Routing.Constraints\n#endif\n{\n    /// <summary>\n    /// Constrains a route parameter to be a string of a given length or within a given range of lengths.\n    /// </summary>\n#if ASPNETWEBAPI\n    public class LengthRouteConstraint : IHttpRouteConstraint\n#else\n    public class LengthRouteConstraint : IRouteConstraint\n#endif\n    {\n        public LengthRouteConstraint(int length)\n        {\n            if (length < 0)\n            {\n                throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"length\", length, 0);\n            }\n\n            Length = length;\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"LengthRouteConstraint\" /> class that constrains\n        /// a route parameter to be a string of a given length.\n        /// </summary>\n        /// <param name=\"minLength\">The minimum length of the route parameter.</param>\n        /// <param name=\"maxLength\">The maximum length of the route parameter.</param>\n        public LengthRouteConstraint(int minLength, int maxLength)\n        {\n            if (minLength < 0)\n            {\n                throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"minLength\", minLength, 0);\n            }\n\n            if (maxLength < 0)\n            {\n                throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"maxLength\", maxLength, 0);\n            }\n\n            MinLength = minLength;\n            MaxLength = maxLength;\n        }\n\n        /// <summary>\n        /// Gets the length of the route parameter, if one is set.\n        /// </summary>\n        public int? Length { get; private set; }\n\n        /// <summary>\n        /// Gets the minimum length of the route parameter, if one is set.\n        /// </summary>\n        public int? MinLength { get; private set; }\n\n        /// <summary>\n        /// Gets the maximum length of the route parameter, if one is set.\n        /// </summary>\n        public int? MaxLength { get; private set; }\n\n        /// <inheritdoc />\n#if ASPNETWEBAPI\n        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)\n#else\n        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)\n#endif\n        {\n            if (parameterName == null)\n            {\n                throw Error.ArgumentNull(\"parameterName\");\n            }\n\n            if (values == null)\n            {\n                throw Error.ArgumentNull(\"values\");\n            }\n\n            object value;\n            if (values.TryGetValue(parameterName, out value) && value != null)\n            {\n                string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);\n                int length = valueString.Length;\n                if (Length.HasValue)\n                {\n                    return length == Length.Value;\n                }\n                else\n                {\n                    return length >= MinLength.Value && length <= MaxLength.Value;\n                }\n            }\n            return false;\n        }\n    }\n}"
  },
  {
    "path": "src/Common/Routing/Constraints/LongRouteConstraint.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\n#if ASPNETWEBAPI\nusing System.Net.Http;\n#else\nusing System.Web.Routing;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing.Constraints\n#else\nnamespace System.Web.Mvc.Routing.Constraints\n#endif\n{\n    /// <summary>\n    /// Constrains a route parameter to represent only 64-bit integer values.\n    /// </summary>\n#if ASPNETWEBAPI\n    public class LongRouteConstraint : IHttpRouteConstraint\n#else\n    public class LongRouteConstraint : IRouteConstraint\n#endif\n    {\n        /// <inheritdoc />\n#if ASPNETWEBAPI\n        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)\n#else\n        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)\n#endif\n        {\n            if (parameterName == null)\n            {\n                throw Error.ArgumentNull(\"parameterName\");\n            }\n\n            if (values == null)\n            {\n                throw Error.ArgumentNull(\"values\");\n            }\n\n            object value;\n            if (values.TryGetValue(parameterName, out value) && value != null)\n            {\n                if (value is long)\n                {\n                    return true;\n                }\n\n                long result;\n                string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);\n                return Int64.TryParse(valueString, NumberStyles.Integer, CultureInfo.InvariantCulture, out result);\n            }\n            return false;\n        }\n    }\n}"
  },
  {
    "path": "src/Common/Routing/Constraints/MaxLengthRouteConstraint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\n#if ASPNETWEBAPI\nusing System.Net.Http;\n#else\nusing System.Web.Routing;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing.Constraints\n#else\nnamespace System.Web.Mvc.Routing.Constraints\n#endif\n{\n    /// <summary>\n    /// Constrains a route parameter to be a string with a maximum length.\n    /// </summary>\n#if ASPNETWEBAPI\n    public class MaxLengthRouteConstraint : IHttpRouteConstraint\n#else\n    public class MaxLengthRouteConstraint : IRouteConstraint\n#endif\n    {\n        public MaxLengthRouteConstraint(int maxLength)\n        {\n            if (maxLength < 0)\n            {\n                throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"maxLength\", maxLength, 0);\n            }\n\n            MaxLength = maxLength;\n        }\n\n        /// <summary>\n        /// Gets the maximum length of the route parameter.\n        /// </summary>\n        public int MaxLength { get; private set; }\n\n        /// <inheritdoc />\n#if ASPNETWEBAPI\n        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)\n#else\n        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)\n#endif\n        {\n            if (parameterName == null)\n            {\n                throw Error.ArgumentNull(\"parameterName\");\n            }\n\n            if (values == null)\n            {\n                throw Error.ArgumentNull(\"values\");\n            }\n\n            object value;\n            if (values.TryGetValue(parameterName, out value) && value != null)\n            {\n                string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);\n                return valueString.Length <= MaxLength;\n            }\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Common/Routing/Constraints/MaxRouteConstraint.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Globalization;\n#if ASPNETWEBAPI\nusing System.Net.Http;\n#else\nusing System.Web.Routing;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing.Constraints\n#else\nnamespace System.Web.Mvc.Routing.Constraints\n#endif\n{\n    /// <summary>\n    /// Constrains a route parameter to be an integer with a maximum value.\n    /// </summary>\n#if ASPNETWEBAPI\n    public class MaxRouteConstraint : IHttpRouteConstraint\n#else\n    public class MaxRouteConstraint : IRouteConstraint\n#endif\n    {\n        public MaxRouteConstraint(long max)\n        {\n            Max = max;\n        }\n\n        /// <summary>\n        /// Gets the maximum value of the route parameter.\n        /// </summary>\n        public long Max { get; private set; }\n\n        /// <inheritdoc />\n#if ASPNETWEBAPI\n        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)\n#else\n        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)\n#endif\n        {\n            if (parameterName == null)\n            {\n                throw Error.ArgumentNull(\"parameterName\");\n            }\n\n            if (values == null)\n            {\n                throw Error.ArgumentNull(\"values\");\n            }\n\n            object value;\n            if (values.TryGetValue(parameterName, out value) && value != null)\n            {\n                long longValue;\n                if (value is long)\n                {\n                    longValue = (long)value;\n                    return longValue <= Max;\n                }\n\n                string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);\n                if (Int64.TryParse(valueString, NumberStyles.Integer, CultureInfo.InvariantCulture, out longValue))\n                {\n                    return longValue <= Max;\n                }\n            }\n            return false;\n        }\n    }\n}"
  },
  {
    "path": "src/Common/Routing/Constraints/MinLengthRouteConstraint.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\n#if ASPNETWEBAPI\nusing System.Net.Http;\n#else\nusing System.Web.Routing;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing.Constraints\n#else\nnamespace System.Web.Mvc.Routing.Constraints\n#endif\n{\n    /// <summary>\n    /// Constrains a route parameter to be a string with a maximum length.\n    /// </summary>\n#if ASPNETWEBAPI\n    public class MinLengthRouteConstraint : IHttpRouteConstraint\n#else\n    public class MinLengthRouteConstraint : IRouteConstraint\n#endif\n    {\n        public MinLengthRouteConstraint(int minLength)\n        {\n            if (minLength < 0)\n            {\n                throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"minLength\", minLength, 0);\n            }\n\n            MinLength = minLength;\n        }\n\n        /// <summary>\n        /// Gets the minimum length of the route parameter.\n        /// </summary>\n        public int MinLength { get; private set; }\n\n        /// <inheritdoc />\n#if ASPNETWEBAPI\n        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)\n#else\n        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)\n#endif\n        {\n            if (parameterName == null)\n            {\n                throw Error.ArgumentNull(\"parameterName\");\n            }\n\n            if (values == null)\n            {\n                throw Error.ArgumentNull(\"values\");\n            }\n\n            object value;\n            if (values.TryGetValue(parameterName, out value) && value != null)\n            {\n                string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);\n                return valueString.Length >= MinLength;\n            }\n            return false;\n        }\n    }\n}"
  },
  {
    "path": "src/Common/Routing/Constraints/MinRouteConstraint.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\n#if ASPNETWEBAPI\nusing System.Net.Http;\n#else\nusing System.Web.Routing;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing.Constraints\n#else\nnamespace System.Web.Mvc.Routing.Constraints\n#endif\n{\n    /// <summary>\n    /// Constrains a route parameter to be a long with a minimum value.\n    /// </summary>\n#if ASPNETWEBAPI\n    public class MinRouteConstraint : IHttpRouteConstraint\n#else\n    public class MinRouteConstraint : IRouteConstraint\n#endif\n    {\n        public MinRouteConstraint(long min)\n        {\n            Min = min;\n        }\n\n        /// <summary>\n        /// Gets the minimum value of the route parameter.\n        /// </summary>\n        public long Min { get; private set; }\n\n        /// <inheritdoc />\n#if ASPNETWEBAPI\n        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)\n#else\n        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)\n#endif\n        {\n            if (parameterName == null)\n            {\n                throw Error.ArgumentNull(\"parameterName\");\n            }\n\n            if (values == null)\n            {\n                throw Error.ArgumentNull(\"values\");\n            }\n\n            object value;\n            if (values.TryGetValue(parameterName, out value) && value != null)\n            {\n                long longValue;\n                if (value is long)\n                {\n                    longValue = (long)value;\n                    return longValue >= Min;\n                }\n\n                string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);\n                if (Int64.TryParse(valueString, NumberStyles.Integer, CultureInfo.InvariantCulture, out longValue))\n                {\n                    return longValue >= Min;\n                }\n            }\n            return false;\n        }\n    }\n}"
  },
  {
    "path": "src/Common/Routing/Constraints/OptionalRouteConstraint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n#if ASPNETWEBAPI\nusing System.Net.Http;\n#else\nusing System.Web.Routing;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing.Constraints\n#else\nnamespace System.Web.Mvc.Routing.Constraints\n#endif\n{\n    /// <summary>\n    /// Constrains a route by an inner constraint that doesn't fail when an optional parameter is set to its default value.\n    /// </summary>\n#if ASPNETWEBAPI\n    public class OptionalRouteConstraint : IHttpRouteConstraint\n#else\n    public class OptionalRouteConstraint : IRouteConstraint\n#endif\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"OptionalRouteConstraint\" /> class.\n        /// </summary>\n        /// <param name=\"innerConstraint\">The inner constraint to match if the parameter is not an optional parameter without a value</param>\n#if ASPNETWEBAPI\n        public OptionalRouteConstraint(IHttpRouteConstraint innerConstraint)\n#else\n        public OptionalRouteConstraint(IRouteConstraint innerConstraint)\n#endif\n        {\n            if (innerConstraint == null)\n            {\n                throw Error.ArgumentNull(\"innerConstraint\");\n            }\n\n            InnerConstraint = innerConstraint;\n        }\n\n        /// <summary>\n        /// Gets the inner constraint to match if the parameter is not an optional parameter without a value.\n        /// </summary>\n#if ASPNETWEBAPI\n        public IHttpRouteConstraint InnerConstraint { get; private set; }\n#else\n        public IRouteConstraint InnerConstraint { get; private set; }\n#endif\n\n        /// <inheritdoc />\n#if ASPNETWEBAPI\n        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)\n#else\n        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)\n#endif\n        {\n            if (route == null)\n            {\n                throw Error.ArgumentNull(\"route\");\n            }\n\n            if (parameterName == null)\n            {\n                throw Error.ArgumentNull(\"parameterName\");\n            }\n\n            if (values == null)\n            {\n                throw Error.ArgumentNull(\"values\");\n            }\n\n            // If the parameter is optional and has no value, then pass the constraint\n            object defaultValue;\n#if ASPNETWEBAPI\n            var optionalParameter = RouteParameter.Optional;\n#else\n            var optionalParameter = UrlParameter.Optional;\n#endif\n            if (route.Defaults.TryGetValue(parameterName, out defaultValue) && defaultValue == optionalParameter)\n            {\n                object value;\n                if (values.TryGetValue(parameterName, out value) && value == optionalParameter)\n                {\n                    return true;\n                }\n            }\n\n#if ASPNETWEBAPI\n            return InnerConstraint.Match(request, route, parameterName, values, routeDirection);\n#else\n            return InnerConstraint.Match(httpContext, route, parameterName, values, routeDirection);\n#endif\n        }\n    }\n}"
  },
  {
    "path": "src/Common/Routing/Constraints/RangeRouteConstraintBase.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\n#if ASPNETWEBAPI\nusing System.Net.Http;\n#else\nusing System.Web.Routing;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing.Constraints\n#else\nnamespace System.Web.Mvc.Routing.Constraints\n#endif\n{\n    /// <summary>\n    /// Constraints a route parameter to be an integer within a given range of values.\n    /// </summary>\n#if ASPNETWEBAPI\n    public class RangeRouteConstraint : IHttpRouteConstraint\n#else\n    public class RangeRouteConstraint : IRouteConstraint\n#endif\n    {\n        public RangeRouteConstraint(long min, long max)\n        {\n            Min = min;\n            Max = max;\n        }\n\n        /// <summary>\n        /// Gets the minimum value of the route parameter.\n        /// </summary>\n        public long Min { get; private set; }\n\n        /// <summary>\n        /// Gets the maximum value of the route parameter.\n        /// </summary>\n        public long Max { get; private set; }\n\n        /// <inheritdoc />\n#if ASPNETWEBAPI\n        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)\n#else\n        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)\n#endif\n        {\n            if (parameterName == null)\n            {\n                throw Error.ArgumentNull(\"parameterName\");\n            }\n\n            if (values == null)\n            {\n                throw Error.ArgumentNull(\"values\");\n            }\n\n            object value;\n            if (values.TryGetValue(parameterName, out value) && value != null)\n            {\n                long longValue;\n                if (value is long)\n                {\n                    longValue = (long)value;\n                    return longValue >= Min && longValue <= Max;\n                }\n\n                string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);\n                if (Int64.TryParse(valueString, NumberStyles.Integer, CultureInfo.InvariantCulture, out longValue))\n                {\n                    return longValue >= Min && longValue <= Max;\n                }\n            }\n            return false;\n        }\n    }\n}"
  },
  {
    "path": "src/Common/Routing/Constraints/RegexRouteConstraint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\n#if ASPNETWEBAPI\nusing System.Net.Http;\nusing System.Text.RegularExpressions;\n#else\nusing System.Text.RegularExpressions;\nusing System.Web.Routing;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing.Constraints\n#else\nnamespace System.Web.Mvc.Routing.Constraints\n#endif\n{\n    /// <summary>\n    /// Constrains a route parameter to match a regular expression.\n    /// </summary>\n#if ASPNETWEBAPI\n    public class RegexRouteConstraint : IHttpRouteConstraint\n#else\n    public class RegexRouteConstraint : IRouteConstraint\n#endif\n    {\n        private readonly Regex _regex;\n\n        public RegexRouteConstraint(string pattern)\n        {\n            Pattern = pattern;\n            _regex = new Regex(pattern, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.Compiled);\n        }\n\n        /// <summary>\n        /// Gets the regular expression pattern to match.\n        /// </summary>\n        public string Pattern { get; private set; }\n\n        /// <inheritdoc />\n#if ASPNETWEBAPI\n        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)\n#else\n        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)\n#endif\n        {\n            if (parameterName == null)\n            {\n                throw Error.ArgumentNull(\"parameterName\");\n            }\n\n            if (values == null)\n            {\n                throw Error.ArgumentNull(\"values\");\n            }\n\n            object value;\n            if (values.TryGetValue(parameterName, out value) && value != null)\n            {\n                string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);\n                return _regex.IsMatch(valueString);\n            }\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Common/Routing/DefaultInlineConstraintResolver.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Reflection;\n#if ASPNETWEBAPI\nusing System.Web.Http.Routing.Constraints;\nusing ErrorResources = System.Web.Http.Properties.SRResources;\n#else\nusing System.Web.Mvc.Routing.Constraints;\nusing System.Web.Routing;\nusing ErrorResources = System.Web.Mvc.Properties.MvcResources;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing\n#else\nnamespace System.Web.Mvc.Routing\n#endif\n{\n    /// <summary>\n    /// The default implementation of <see cref=\"IInlineConstraintResolver\"/>. Resolves constraints by parsing\n    /// a constraint key and constraint arguments, using a map to resolve the constraint type, and calling an\n    /// appropriate constructor for the constraint type.\n    /// </summary>\n    public class DefaultInlineConstraintResolver : IInlineConstraintResolver\n    {\n        private readonly IDictionary<string, Type> _inlineConstraintMap = GetDefaultConstraintMap();\n\n        /// <summary>\n        /// Gets the mutable dictionary that maps constraint keys to a particular constraint type.\n        /// </summary>\n        public IDictionary<string, Type> ConstraintMap\n        {\n            get\n            {\n                return _inlineConstraintMap;\n            }\n        }\n\n        private static IDictionary<string, Type> GetDefaultConstraintMap()\n        {\n            return new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase)\n            {\n                // Type-specific constraints\n                { \"bool\", typeof(BoolRouteConstraint) },\n                { \"datetime\", typeof(DateTimeRouteConstraint) },\n                { \"decimal\", typeof(DecimalRouteConstraint) },\n                { \"double\", typeof(DoubleRouteConstraint) },\n                { \"float\", typeof(FloatRouteConstraint) },\n                { \"guid\", typeof(GuidRouteConstraint) },\n                { \"int\", typeof(IntRouteConstraint) },\n                { \"long\", typeof(LongRouteConstraint) },\n\n                // Length constraints\n                { \"minlength\", typeof(MinLengthRouteConstraint) },\n                { \"maxlength\", typeof(MaxLengthRouteConstraint) },\n                { \"length\", typeof(LengthRouteConstraint) },\n                \n                // Min/Max value constraints\n                { \"min\", typeof(MinRouteConstraint) },\n                { \"max\", typeof(MaxRouteConstraint) },\n                { \"range\", typeof(RangeRouteConstraint) },\n\n                // Regex-based constraints\n                { \"alpha\", typeof(AlphaRouteConstraint) },\n                { \"regex\", typeof(RegexRouteConstraint) }\n            };\n        }\n\n        /// <inheritdoc />\n#if ASPNETWEBAPI\n        public virtual IHttpRouteConstraint ResolveConstraint(string inlineConstraint)\n#else\n        public virtual IRouteConstraint ResolveConstraint(string inlineConstraint)\n#endif\n        {\n            if (inlineConstraint == null)\n            {\n                throw Error.ArgumentNull(\"inlineConstraint\");\n            }\n\n            string constraintKey;\n            string argumentString;\n            int indexOfFirstOpenParens = inlineConstraint.IndexOf('(');\n            if (indexOfFirstOpenParens >= 0 && inlineConstraint.EndsWith(\")\", StringComparison.Ordinal))\n            {\n                constraintKey = inlineConstraint.Substring(0, indexOfFirstOpenParens);\n                argumentString = inlineConstraint.Substring(indexOfFirstOpenParens + 1, inlineConstraint.Length - indexOfFirstOpenParens - 2);\n            }\n            else\n            {\n                constraintKey = inlineConstraint;\n                argumentString = null;\n            }\n\n            Type constraintType;\n            if (!_inlineConstraintMap.TryGetValue(constraintKey, out constraintType))\n            {\n                // Cannot resolve the constraint key\n                return null;\n            }\n\n#if ASPNETWEBAPI\n            if (!typeof(IHttpRouteConstraint).IsAssignableFrom(constraintType))\n#else\n            if (!typeof(IRouteConstraint).IsAssignableFrom(constraintType))\n#endif\n            {\n                throw Error.InvalidOperation(ErrorResources.DefaultInlineConstraintResolver_TypeNotConstraint, constraintType.Name, constraintKey);\n            }\n\n#if ASPNETWEBAPI\n            return (IHttpRouteConstraint)CreateConstraint(constraintType, argumentString);\n#else\n            return (IRouteConstraint)CreateConstraint(constraintType, argumentString);\n#endif\n        }\n\n        private static object CreateConstraint(Type constraintType, string argumentString)\n        {\n            // No arguments - call the default constructor\n            if (argumentString == null)\n            {\n                return Activator.CreateInstance(constraintType);\n            }\n\n            ConstructorInfo activationConstructor = null;\n            object[] parameters = null;\n            ConstructorInfo[] constructors = constraintType.GetConstructors();\n\n            // If there is only one constructor and it has a single parameter, pass the argument string directly\n            // This is necessary for the Regex RouteConstraint to ensure that patterns are not split on commas.\n            if (constructors.Length == 1 && constructors[0].GetParameters().Length == 1)\n            {\n                activationConstructor = constructors[0];\n                parameters = ConvertArguments(activationConstructor.GetParameters(), new string[] { argumentString });\n            }\n            else\n            {\n                string[] arguments = argumentString.Split(',').Select(argument => argument.Trim()).ToArray();\n\n                ConstructorInfo[] matchingConstructors = constructors.Where(ci => ci.GetParameters().Length == arguments.Length).ToArray();\n                int constructorMatches = matchingConstructors.Length;\n\n                if (constructorMatches == 0)\n                {\n                    throw Error.InvalidOperation(ErrorResources.DefaultInlineConstraintResolver_CouldNotFindCtor, constraintType.Name, argumentString.Length);\n                }\n                else if (constructorMatches == 1)\n                {\n                    activationConstructor = matchingConstructors[0];\n                    parameters = ConvertArguments(activationConstructor.GetParameters(), arguments);\n                }\n                else\n                {\n                    throw Error.InvalidOperation(ErrorResources.DefaultInlineConstraintResolver_AmbiguousCtors, constraintType.Name, argumentString.Length);\n                }\n            }\n\n            return activationConstructor.Invoke(parameters);\n        }\n\n        private static object[] ConvertArguments(ParameterInfo[] parameterInfos, string[] arguments)\n        {\n            object[] parameters = new object[parameterInfos.Length];\n            for (int i = 0; i < parameterInfos.Length; i++)\n            {\n                ParameterInfo parameter = parameterInfos[i];\n                Type parameterType = parameter.ParameterType;\n                parameters[i] = Convert.ChangeType(arguments[i], parameterType, CultureInfo.InvariantCulture);\n            }\n            return parameters;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Common/Routing/DirectRouteBuilder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\n#if ASPNETWEBAPI\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Properties;\n#else\nusing System.Web.Routing;\n#endif\n\n#if ASPNETWEBAPI\nusing TActionDescriptor = System.Web.Http.Controllers.HttpActionDescriptor;\nusing TParsedRoute = System.Web.Http.Routing.HttpParsedRoute;\nusing TResources = System.Web.Http.Properties.SRResources;\nusing TRoute = System.Web.Http.Routing.IHttpRoute;\nusing TRouteDictionary = System.Collections.Generic.IDictionary<string, object>;\nusing TRouteDictionaryConcrete = System.Web.Http.Routing.HttpRouteValueDictionary;\n\n#else\n\nusing TActionDescriptor = System.Web.Mvc.ActionDescriptor;\nusing TParsedRoute = System.Web.Mvc.Routing.ParsedRoute;\nusing TResources = System.Web.Mvc.Properties.MvcResources;\nusing TRoute = System.Web.Routing.Route;\nusing TRouteDictionary = System.Web.Routing.RouteValueDictionary;\nusing TRouteDictionaryConcrete = System.Web.Routing.RouteValueDictionary;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing\n#else\nnamespace System.Web.Mvc.Routing\n#endif\n{\n    /// <summary>Represents a builder that creates direct routes to actions (attribute routes).</summary>\n    internal class DirectRouteBuilder : IDirectRouteBuilder\n    {\n        private readonly TActionDescriptor[] _actions;\n        private readonly bool _targetIsAction;\n\n        private string _template;\n\n        /// <summary>Initializes a new instance of the <see cref=\"DirectRouteBuilder\"/> class.</summary>\n        /// <param name=\"actions\">The action descriptors to which to create a route.</param>\n        /// <param name=\"targetIsAction\">\n        /// A value indicating whether the route is configured at the action or controller level.\n        /// </param>\n        public DirectRouteBuilder(IReadOnlyCollection<TActionDescriptor> actions, bool targetIsAction)\n        {\n            if (actions == null)\n            {\n                throw new ArgumentNullException(\"actions\");\n            }\n\n            _actions = actions.ToArray();\n\n            _targetIsAction = targetIsAction;\n        }\n\n        /// <inheritdoc/>\n        public string Name { get; set; }\n\n        /// <inheritdoc/>\n        public string Template\n        {\n            get\n            {\n                return _template;\n            }\n            set\n            {\n                ParsedRoute = null;\n                _template = value;\n            }\n        }\n\n        /// <inheritdoc/>\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\",\n            Justification = \"Null and empty values are legitimate, separate options when constructing a route.\")]\n        public TRouteDictionary Defaults { get; set; }\n\n        /// <inheritdoc/>\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\",\n            Justification = \"Null and empty values are legitimate, separate options when constructing a route.\")]\n        public TRouteDictionary Constraints { get; set; }\n\n        /// <inheritdoc/>\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\",\n            Justification = \"Null and empty values are legitimate, separate options when constructing a route.\")]\n        public TRouteDictionary DataTokens { get; set; }\n\n        internal TParsedRoute ParsedRoute { get; set; }\n\n        /// <inheritdoc/>\n        public int Order { get; set; }\n\n        /// <inheritdoc/>\n        public decimal Precedence { get; set; }\n\n        /// <inheritdoc/>\n        public IReadOnlyCollection<TActionDescriptor> Actions\n        {\n            get { return _actions; }\n        }\n\n        /// <inheritdoc/>\n        public bool TargetIsAction\n        {\n            get { return _targetIsAction; }\n        }\n\n        /// <inheritdoc/>\n        public virtual RouteEntry Build()\n        {\n            if (ParsedRoute == null)\n            {\n                ParsedRoute = RouteParser.Parse(Template);\n            }\n\n            ValidateParameters(ParsedRoute);\n\n            TRouteDictionaryConcrete defaults;\n#if ASPNETWEBAPI\n            defaults = Copy(Defaults);\n#else\n            defaults = Copy(Defaults) ?? new RouteValueDictionary();\n#endif\n            TRouteDictionaryConcrete constraints = Copy(Constraints);\n            TRouteDictionaryConcrete dataTokens = Copy(DataTokens) ?? new TRouteDictionaryConcrete();\n\n            dataTokens[RouteDataTokenKeys.Actions] = _actions;\n\n#if ASPNETWEBAPI\n            if (!TargetIsAction)\n            {\n                dataTokens[RouteDataTokenKeys.Controller] = _actions[0].ControllerDescriptor;\n            }\n#endif\n\n            int order = Order;\n\n            if (order != default(int))\n            {\n                dataTokens[RouteDataTokenKeys.Order] = order;\n            }\n\n            decimal precedence = Precedence;\n\n            if (precedence != default(decimal))\n            {\n                dataTokens[RouteDataTokenKeys.Precedence] = precedence;\n            }\n\n#if ASPNETWEBAPI\n            if (constraints != null)\n            {\n                foreach (var constraint in constraints)\n                {\n                    HttpRoute.ValidateConstraint(Template, constraint.Key, constraint.Value);\n                }\n            }\n\n            HttpMessageHandler handler = null;\n            IHttpRoute route = new HttpRoute(Template, defaults, constraints, dataTokens, handler, ParsedRoute);\n#else\n            ControllerDescriptor controllerDescriptor = GetControllerDescriptor();\n\n            if (controllerDescriptor != null)\n            {\n                defaults[\"controller\"] = controllerDescriptor.ControllerName;\n            }\n\n            if (TargetIsAction && _actions.Length == 1)\n            {\n                ActionDescriptor actionDescriptor = _actions[0];\n                defaults[\"action\"] = actionDescriptor.ActionName;\n\n                dataTokens[RouteDataTokenKeys.TargetIsAction] = true;\n            }\n\n            RouteAreaAttribute area = controllerDescriptor.GetAreaFrom();\n            string areaName = controllerDescriptor.GetAreaName(area);\n\n            if (areaName != null)\n            {\n                dataTokens[RouteDataTokenKeys.Area] = areaName;\n                dataTokens[RouteDataTokenKeys.UseNamespaceFallback] = false;\n\n                Type controllerType = controllerDescriptor.ControllerType;\n\n                if (controllerType != null)\n                {\n                    dataTokens[RouteDataTokenKeys.Namespaces] = new[] { controllerType.Namespace };\n                }\n            }\n\n            Route route = new Route(Template, defaults, constraints, dataTokens, routeHandler: null);\n\n            ConstraintValidation.Validate(route);\n#endif\n\n            return new RouteEntry(Name, route);\n        }\n\n        // Accessible for tests\n        internal virtual void ValidateParameters(TParsedRoute parsedRoute)\n        {\n            Contract.Assert(parsedRoute != null);\n\n            if (parsedRoute.PathSegments != null)\n            {\n                foreach (var contentSegment in parsedRoute.PathSegments.OfType<PathContentSegment>())\n                {\n                    if (contentSegment != null && contentSegment.Subsegments != null)\n                    {\n                        foreach (var parameterSegment in contentSegment.Subsegments.OfType<PathParameterSubsegment>())\n                        {\n                            if (parameterSegment != null)\n                            {\n                                if (String.Equals(parameterSegment.ParameterName, \"controller\", StringComparison.OrdinalIgnoreCase))\n                                {\n                                    throw Error.InvalidOperation(TResources.DirectRoute_InvalidParameter_Controller);\n                                }\n                                else if (TargetIsAction && String.Equals(parameterSegment.ParameterName, \"action\", StringComparison.OrdinalIgnoreCase))\n                                {\n                                    throw Error.InvalidOperation(TResources.DirectRoute_InvalidParameter_Action);\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        internal static void ValidateRouteEntry(RouteEntry entry)\n        {\n            Contract.Assert(entry != null);\n\n            TRoute route = entry.Route;\n            Contract.Assert(route != null);\n\n            TActionDescriptor[] targetActions = route.GetTargetActionDescriptors();\n\n            if (targetActions == null || targetActions.Length == 0)\n            {\n                throw new InvalidOperationException(TResources.DirectRoute_MissingActionDescriptors);\n            }\n#if ASPNETWEBAPI\n            if (route.Handler != null)\n            {\n                throw new InvalidOperationException(TResources.DirectRoute_HandlerNotSupported);\n            }\n#else\n            if (route.RouteHandler != null)\n            {\n                throw new InvalidOperationException(TResources.DirectRoute_RouteHandlerNotSupported);\n            }\n#endif\n        }\n\n        private static TRouteDictionaryConcrete Copy(TRouteDictionary routeDictionary)\n        {\n            if (routeDictionary == null)\n            {\n                return null;\n            }\n\n            return new TRouteDictionaryConcrete(routeDictionary);\n        }\n\n#if !ASPNETWEBAPI\n        private ControllerDescriptor GetControllerDescriptor()\n        {\n            ControllerDescriptor controller = null;\n\n            foreach (ActionDescriptor action in _actions)\n            {\n                if (controller == null)\n                {\n                    controller = action.ControllerDescriptor;\n                }\n                else if (action.ControllerDescriptor != controller)\n                {\n                    controller = null;\n                    break;\n                }\n            }\n\n            return controller;\n        }\n#endif\n    }\n}\n"
  },
  {
    "path": "src/Common/Routing/DirectRouteFactoryContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\n\n#if ASPNETWEBAPI\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Properties;\nusing TActionDescriptor = System.Web.Http.Controllers.HttpActionDescriptor;\nusing TParsedRoute = System.Web.Http.Routing.HttpParsedRoute;\nusing TRouteDictionary = System.Web.Http.Routing.HttpRouteValueDictionary;\n#else\nusing System.Text;\nusing System.Web.Mvc.Properties;\nusing System.Web.Routing;\nusing TActionDescriptor = System.Web.Mvc.ActionDescriptor;\nusing TParsedRoute = System.Web.Mvc.Routing.ParsedRoute;\nusing TRouteDictionary = System.Web.Routing.RouteValueDictionary;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing\n#else\nnamespace System.Web.Mvc.Routing\n#endif\n{\n    /// <summary>Represents a context that supports creating a direct route.</summary>\n    public class DirectRouteFactoryContext\n    {\n        private readonly string _actionName;\n\n#if !ASPNETWEBAPI\n        private readonly string _controllerName;\n#endif\n\n#if ASPNETWEBAPI\n        private readonly string _prefix;\n#else\n        private readonly string _areaPrefix;\n        private readonly string _controllerPrefix;\n#endif\n\n        private readonly IReadOnlyCollection<TActionDescriptor> _actions;\n        private readonly IInlineConstraintResolver _inlineConstraintResolver;\n        private readonly bool _targetIsAction;\n\n#if ASPNETWEBAPI\n        /// <summary>Initializes a new instance of the <see cref=\"DirectRouteFactoryContext\"/></summary>\n        /// <param name=\"prefix\">The route prefix, if any, defined by the controller.</param>\n        /// <param name=\"actions\">The action descriptors to which to create a route.</param>\n        /// <param name=\"inlineConstraintResolver\">The inline constraint resolver.</param>\n        /// <param name=\"targetIsAction\">\n        /// A value indicating whether the route is configured at the action or controller level.\n        /// </param>\n        public DirectRouteFactoryContext(string prefix, IReadOnlyCollection<HttpActionDescriptor> actions,\n            IInlineConstraintResolver inlineConstraintResolver, bool targetIsAction)\n#else\n        /// <summary>Initializes a new instance of the <see cref=\"DirectRouteFactoryContext\"/></summary>\n        /// <param name=\"areaPrefix\">The route prefix, if any, defined by the area.</param>\n        /// <param name=\"controllerPrefix\">The route prefix, if any, defined by the controller.</param>\n        /// <param name=\"actions\">The action descriptors to which to create a route.</param>\n        /// <param name=\"inlineConstraintResolver\">The inline constraint resolver.</param>\n        /// <param name=\"targetIsAction\">\n        /// A value indicating whether the route is configured at the action or controller level.\n        /// </param>\n        public DirectRouteFactoryContext(string areaPrefix, string controllerPrefix,\n            IReadOnlyCollection<ActionDescriptor> actions, IInlineConstraintResolver inlineConstraintResolver,\n            bool targetIsAction)\n#endif\n        {\n            if (actions == null)\n            {\n                throw new ArgumentNullException(\"actions\");\n            }\n\n            if (inlineConstraintResolver == null)\n            {\n                throw new ArgumentNullException(\"inlineConstraintResolver\");\n            }\n\n#if ASPNETWEBAPI\n            _prefix = prefix;\n#else\n            _areaPrefix = areaPrefix;\n            _controllerPrefix = controllerPrefix;\n#endif\n            _actions = actions;\n            _inlineConstraintResolver = inlineConstraintResolver;\n\n            TActionDescriptor firstDescriptor = actions.FirstOrDefault();\n\n            if (firstDescriptor != null)\n            {\n                _actionName = firstDescriptor.ActionName;\n#if !ASPNETWEBAPI\n                ControllerDescriptor controllerDescriptor = firstDescriptor.ControllerDescriptor;\n\n                if (controllerDescriptor != null)\n                {\n                    _controllerName = controllerDescriptor.ControllerName;\n                }\n#endif\n            }\n\n            _targetIsAction = targetIsAction;\n        }\n\n#if ASPNETWEBAPI\n        /// <summary>Gets the route prefix, if any, defined by the controller.</summary>\n        public string Prefix\n        {\n            get { return _prefix; }\n        }\n#else\n        /// <summary>Gets the route prefix, if any, defined by the area.</summary>\n        public string AreaPrefix\n        {\n            get { return _areaPrefix; }\n        }\n\n        /// <summary>Gets the route prefix, if any, defined by the controller.</summary>\n        public string ControllerPrefix\n        {\n            get { return _controllerPrefix; }\n        }\n#endif\n\n        /// <summary>Gets the action descriptors to which to create a route.</summary>\n        public IReadOnlyCollection<TActionDescriptor> Actions\n        {\n            get { return _actions; }\n        }\n\n        /// <summary>Gets the inline constraint resolver.</summary>\n        public IInlineConstraintResolver InlineConstraintResolver\n        {\n            get { return _inlineConstraintResolver; }\n        }\n\n        /// <summary>\n        /// Gets a value indicating whether the route is configured at the action or controller level.\n        /// </summary>\n        /// <remarks>\n        /// <see langword=\"true\"/> when the route is configured at the action level; otherwise <see langword=\"false\"/>\n        /// (if the route is configured at the controller level).\n        /// </remarks>\n        public bool TargetIsAction\n        {\n            get { return _targetIsAction; }\n        }\n\n        /// <summary>Creates a route builder that can build a route matching this context.</summary>\n        /// <param name=\"template\">The route template.</param>\n        /// <returns>A route builder that can build a route matching this context.</returns>\n        public IDirectRouteBuilder CreateBuilder(string template)\n        {\n            return CreateBuilderInternal(template);\n        }\n\n        internal virtual IDirectRouteBuilder CreateBuilderInternal(string template)\n        {\n            return CreateBuilder(template, _inlineConstraintResolver);\n        }\n\n        /// <summary>Creates a route builder that can build a route matching this context.</summary>\n        /// <param name=\"template\">The route template.</param>\n        /// <param name=\"constraintResolver\">\n        /// The inline constraint resolver to use, if any; otherwise, <see langword=\"null\"/>.\n        /// </param>\n        /// <returns>A route builder that can build a route matching this context.</returns>\n        public IDirectRouteBuilder CreateBuilder(string template, IInlineConstraintResolver constraintResolver)\n        {\n            DirectRouteBuilder builder = new DirectRouteBuilder(_actions, _targetIsAction);\n\n#if ASPNETWEBAPI\n            string prefixedTemplate = BuildRouteTemplate(_prefix, template);\n#else\n            string prefixedTemplate = BuildRouteTemplate(_areaPrefix, _controllerPrefix, template ?? String.Empty);\n#endif\n            ValidateTemplate(prefixedTemplate);\n\n            if (constraintResolver != null)\n            {\n                TRouteDictionary defaults = new TRouteDictionary();\n                TRouteDictionary constraints = new TRouteDictionary();\n\n                string detokenizedTemplate = InlineRouteTemplateParser.ParseRouteTemplate(prefixedTemplate, defaults,\n                    constraints, constraintResolver);\n                TParsedRoute parsedRoute = RouteParser.Parse(detokenizedTemplate);\n                decimal precedence = RoutePrecedence.Compute(parsedRoute, constraints);\n\n                builder.Defaults = defaults;\n                builder.Constraints = constraints;\n                builder.Template = detokenizedTemplate;\n                builder.Precedence = precedence;\n                builder.ParsedRoute = parsedRoute;\n            }\n            else\n            {\n                builder.Template = prefixedTemplate;\n            }\n\n            return builder;\n        }\n\n#if ASPNETWEBAPI\n        private static string BuildRouteTemplate(string routePrefix, string routeTemplate)\n        {\n            if (String.IsNullOrEmpty(routeTemplate))\n            {\n                return routePrefix ?? String.Empty;\n            }\n\n            // If the provider's template starts with '~/', ignore the route prefix\n            if (routeTemplate.StartsWith(\"~/\", StringComparison.Ordinal))\n            {\n                return routeTemplate.Substring(2);\n            }\n            else if (String.IsNullOrEmpty(routePrefix))\n            {\n                return routeTemplate;\n            }\n            else\n            {\n                // template and prefix both not null - combine them\n                return routePrefix + '/' + routeTemplate;\n            }\n        }\n#else\n        internal static string BuildRouteTemplate(string areaPrefix, string prefix, string template)\n        {\n            // If the attribute's template starts with '~/', ignore the area and controller prefixes\n            if (template != null && template.StartsWith(\"~/\", StringComparison.Ordinal))\n            {\n                return template.Substring(2);\n            }\n\n            if (prefix == null && areaPrefix == null)\n            {\n                return template;\n            }\n\n            StringBuilder templateBuilder = new StringBuilder();\n\n            if (areaPrefix != null)\n            {\n                templateBuilder.Append(areaPrefix);\n            }\n\n            if (!String.IsNullOrEmpty(prefix))\n            {\n                if (templateBuilder.Length > 0)\n                {\n                    templateBuilder.Append('/');\n                }\n                templateBuilder.Append(prefix);\n            }\n\n            if (!String.IsNullOrEmpty(template))\n            {\n                if (templateBuilder.Length > 0)\n                {\n                    templateBuilder.Append('/');\n                }\n                templateBuilder.Append(template);\n            }\n\n            return templateBuilder.ToString();\n        }\n#endif\n\n        private void ValidateTemplate(string template)\n        {\n            if (template != null && template.StartsWith(\"/\", StringComparison.Ordinal))\n            {\n#if ASPNETWEBAPI\n                string errorMessage = Error.Format(SRResources.AttributeRoutes_InvalidTemplate, template, _actionName);\n#else\n                string errorMessage = Error.Format(MvcResources.RouteTemplate_CannotStart_WithForwardSlash, template,\n                    _actionName, _controllerName);\n#endif\n                throw new InvalidOperationException(errorMessage);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Common/Routing/IDirectRouteBuilder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\n\n#if ASPNETWEBAPI\nusing TActionDescriptor = System.Web.Http.Controllers.HttpActionDescriptor;\nusing TRouteDictionary = System.Collections.Generic.IDictionary<string, object>;\n#else\nusing TActionDescriptor = System.Web.Mvc.ActionDescriptor;\nusing TRouteDictionary = System.Web.Routing.RouteValueDictionary;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing\n#else\nnamespace System.Web.Mvc.Routing\n#endif\n{\n    /// <summary>Defines a builder that creates direct routes to actions (attribute routes).</summary>\n    public interface IDirectRouteBuilder\n    {\n        /// <summary>Gets or sets the route name, if any; otherwise <see langword=\"null\"/>.</summary>\n        string Name { get; set; }\n\n        /// <summary>Gets or sets the route template.</summary>\n        /// <remarks>\n        /// This value is the core route template that remains after resolving and removing any inline constraints.\n        /// </remarks>\n        string Template { get; set; }\n\n        /// <summary>Gets or sets the route defaults.</summary>\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\",\n            Justification = \"Null and empty values are legitimate, separate options when constructing a route.\")]\n        TRouteDictionary Defaults { get; set; }\n\n        /// <summary>Gets or sets the route constraints.</summary>\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\",\n            Justification = \"Null and empty values are legitimate, separate options when constructing a route.\")]\n        TRouteDictionary Constraints { get; set; }\n\n        /// <summary>Gets or sets the route data tokens.</summary>\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\",\n            Justification = \"Null and empty values are legitimate, separate options when constructing a route.\")]\n        TRouteDictionary DataTokens { get; set; }\n\n        /// <summary>Gets or sets the route order.</summary>\n        /// <remarks>\n        /// The route order disambiguates multiple matching routes and overrides precedence.\n        /// The intended use of order is for an explicitly provided precedence override value.\n        /// </remarks>\n        int Order { get; set; }\n\n        /// <summary>Gets or sets the route precedence.</summary>\n        /// <remarks>\n        /// The route order disambiguates multiple matching routes with the same order.\n        /// The intended use of precedence is for default, automatically computed disambiguation based on inline\n        /// constraint types.\n        /// </remarks>\n        decimal Precedence { get; set; }\n\n        /// <summary>Gets the action descriptors to which to create a route.</summary>\n        IReadOnlyCollection<TActionDescriptor> Actions { get; }\n\n        /// <summary>\n        /// Gets a value indicating whether the route is configured at the action or controller level.\n        /// </summary>\n        /// <remarks>\n        /// <see langword=\"true\"/> when the route is configured at the action level; otherwise <see langword=\"false\"/>\n        /// (if the route is configured at the controller level).\n        /// </remarks>\n        bool TargetIsAction { get; }\n\n        /// <summary>Creates a route entry based on the current property values.</summary>\n        /// <returns>The route entry created.</returns>\n        RouteEntry Build();\n    }\n}\n"
  },
  {
    "path": "src/Common/Routing/IDirectRouteFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing\n#else\nnamespace System.Web.Mvc.Routing\n#endif\n{\n    /// <summary>\n    /// Defines a factory that creates a route directly to a set of action descriptors (an attribute route).\n    /// </summary>\n    public interface IDirectRouteFactory\n    {\n        /// <summary>Creates a direct route entry.</summary>\n        /// <param name=\"context\">The context to use to create the route.</param>\n        /// <returns>The direct route entry.</returns>\n        RouteEntry CreateRoute(DirectRouteFactoryContext context);\n    }\n}\n"
  },
  {
    "path": "src/Common/Routing/IDirectRouteProvider.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.Routing\n{\n    /// <summary>\n    /// Defines a provider for routes that directly target action descriptors (attribute routes).\n    /// </summary>\n    public interface IDirectRouteProvider\n    {\n        /// <summary>Gets the direct routes for a controller.</summary>\n        /// <param name=\"controllerDescriptor\">The controller descriptor.</param>\n        /// <param name=\"actionDescriptors\">The action descriptors.</param>\n        /// <param name=\"constraintResolver\">The inline constraint resolver.</param>\n        /// <returns>A set of route entries for the controller.</returns>\n        IReadOnlyList<RouteEntry> GetDirectRoutes(\n            HttpControllerDescriptor controllerDescriptor, \n            IReadOnlyList<HttpActionDescriptor> actionDescriptors,\n            IInlineConstraintResolver constraintResolver);\n    }\n}\n"
  },
  {
    "path": "src/Common/Routing/IInlineConstraintResolver.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n#if ASPNETWEBAPI\nusing TConstraint = System.Web.Http.Routing.IHttpRouteConstraint;\n#else\nusing TConstraint = System.Web.Routing.IRouteConstraint;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing\n#else\nnamespace System.Web.Mvc.Routing\n#endif\n{\n    /// <summary>\n    /// Defines an abstraction for resolving inline constraints as instances of <see cref=\"TConstraint\"/>.\n    /// </summary>\n    public interface IInlineConstraintResolver\n    {\n        /// <summary>\n        /// Resolves the inline constraint.\n        /// </summary>\n        /// <param name=\"inlineConstraint\">The inline constraint to resolve.</param>\n        /// <returns>The <see cref=\"TConstraint\"/> the inline constraint was resolved to.</returns>\n        TConstraint ResolveConstraint(string inlineConstraint);\n    }\n}"
  },
  {
    "path": "src/Common/Routing/IRoutePrefix.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing\n#else\nnamespace System.Web.Mvc.Routing\n#endif\n{\n    /// <summary>Defines a route prefix.</summary>\n    public interface IRoutePrefix\n    {\n        /// <summary>Gets the route prefix.</summary>\n        string Prefix { get; }\n    }\n}"
  },
  {
    "path": "src/Common/Routing/InlineRouteTemplateParser.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Text.RegularExpressions;\n#if ASPNETWEBAPI\nusing System.Web.Http.Routing.Constraints;\nusing ErrorResources = System.Web.Http.Properties.SRResources;\n#else\nusing System.Web.Mvc.Routing.Constraints;\nusing System.Web.Routing;\nusing ErrorResources = System.Web.Mvc.Properties.MvcResources;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing\n#else\nnamespace System.Web.Mvc.Routing\n#endif\n{\n    /// <summary>\n    /// This class is used by the AttributeRouting mapper, during configuration,\n    /// to parse and strip defaults and constraints from the template.\n    /// </summary>\n    internal class InlineRouteTemplateParser\n    {\n        // One or more characters, matches \"id\"\n        private const string ParameterNameRegex = @\"(?<parameterName>.+?)\";\n\n        // Zero or more inline constraints that start with a colon followed by zero or more characters\n        // Optionally the constraint can have arguments within parentheses - necessary to capture characters like \":\" and \"}\"\n        // Matches \":int\", \":length(2)\", \":regex(\\})\", \":regex(:)\" zero or more times\n        private const string ConstraintRegex = @\"(:(?<constraint>.*?(\\(.*?\\))?))*\";\n\n        // Optional \"?\" for optional parameters or a default value with an equal sign followed by zero or more characters\n        // Matches \"?\", \"=\", \"=abc\"\n        private const string DefaultValueRegex = @\"(?<defaultValue>\\?|(=.*?))?\";\n\n        private static readonly Regex _parameterRegex = new Regex(\n            \"{\" + ParameterNameRegex + ConstraintRegex + DefaultValueRegex + \"}\",\n            RegexOptions.Compiled);\n\n        public static string ParseRouteTemplate(string routeTemplate, IDictionary<string, object> defaults, IDictionary<string, object> constraints, IInlineConstraintResolver constraintResolver)\n        {\n            Contract.Assert(defaults != null);\n            Contract.Assert(constraints != null);\n\n            MatchCollection parameterMatches = _parameterRegex.Matches(routeTemplate);\n\n            foreach (Match parameterMatch in parameterMatches)\n            {\n                string parameterName = parameterMatch.Groups[\"parameterName\"].Value;\n                // We may need to strip out the initial wildcard used for wildcard parameters\n                if (parameterName.StartsWith(\"*\", StringComparison.OrdinalIgnoreCase))\n                {\n                    parameterName = parameterName.Substring(1);\n                }\n\n                // Add the default value if present\n                Group defaultValueGroup = parameterMatch.Groups[\"defaultValue\"];\n                object defaultValue = GetDefaultValue(defaultValueGroup);\n                if (defaultValue != null)\n                {\n                    defaults.Add(parameterName, defaultValue);\n                }\n\n                // Register inline constraints if present\n                Group constraintGroup = parameterMatch.Groups[\"constraint\"];\n#if ASPNETWEBAPI\n                bool isOptional = defaultValue == RouteParameter.Optional;\n#else\n                bool isOptional = defaultValue == UrlParameter.Optional;\n#endif\n                var constraint = GetInlineConstraint(constraintGroup, isOptional, constraintResolver);\n                if (constraint != null)\n                {\n                    constraints.Add(parameterName, constraint);\n                }\n            }\n\n            // Replaces parameter matches with just the parameter name in braces\n            // Strips out the optional '?', default value, inline constraints\n            return _parameterRegex.Replace(routeTemplate, @\"{${parameterName}}\");\n        }\n\n        private static object GetDefaultValue(Group defaultValueGroup)\n        {\n            if (defaultValueGroup.Success)\n            {\n                string defaultValueMatch = defaultValueGroup.Value;\n                if (defaultValueMatch == \"?\")\n                {\n#if ASPNETWEBAPI\n                    return RouteParameter.Optional;\n#else\n                    return UrlParameter.Optional;\n#endif\n                }\n                else\n                {\n                    // Strip out the equal sign at the beginning\n                    Contract.Assert(defaultValueMatch.StartsWith(\"=\", StringComparison.Ordinal));\n                    return defaultValueMatch.Substring(1);\n                }\n            }\n            return null;\n        }\n\n#if ASPNETWEBAPI\n        private static IHttpRouteConstraint GetInlineConstraint(Group constraintGroup, bool isOptional, IInlineConstraintResolver constraintResolver)\n#else\n        private static IRouteConstraint GetInlineConstraint(Group constraintGroup, bool isOptional, IInlineConstraintResolver constraintResolver)\n#endif\n        {\n#if ASPNETWEBAPI\n            List<IHttpRouteConstraint> parameterConstraints = new List<IHttpRouteConstraint>();\n#else\n            List<IRouteConstraint> parameterConstraints = new List<IRouteConstraint>();\n#endif\n            foreach (Capture constraintCapture in constraintGroup.Captures)\n            {\n                string inlineConstraint = constraintCapture.Value;\n                var constraint = constraintResolver.ResolveConstraint(inlineConstraint);\n                if (constraint == null)\n                {\n                    throw Error.InvalidOperation(ErrorResources.HttpRouteBuilder_CouldNotResolveConstraint, constraintResolver.GetType().Name, inlineConstraint);\n                }\n                parameterConstraints.Add(constraint);\n            }\n\n            if (parameterConstraints.Count > 0)\n            {\n                var constraint = parameterConstraints.Count == 1 ?\n                    parameterConstraints[0] :\n                    new CompoundRouteConstraint(parameterConstraints);\n\n                if (isOptional)\n                {\n                    // Constraints should match RouteParameter.Optional if the parameter is optional\n                    // This prevents contraining when there's no value specified\n                    constraint = new OptionalRouteConstraint(constraint);\n                }\n\n                return constraint;\n            }\n            return null;\n        }\n    }\n}"
  },
  {
    "path": "src/Common/Routing/PathContentSegment.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing\n#else\nnamespace System.Web.Mvc.Routing\n#endif\n{\n    // Represents a segment of a URI that is not a separator. It contains subsegments such as literals and parameters.\n    internal sealed class PathContentSegment : PathSegment\n    {\n        public PathContentSegment(List<PathSubsegment> subsegments)\n        {\n            Subsegments = subsegments;\n        }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1800:DoNotCastUnnecessarily\", Justification = \"Not changing original algorithm.\")]\n        public bool IsCatchAll\n        {\n            get\n            {\n                // TODO: Verify this is correct. Maybe add an assert.\n                // Performance sensitive\n                // Caching count is faster for IList<T>\n                int subsegmentCount = Subsegments.Count;\n                for (int i = 0; i < subsegmentCount; i++)\n                {\n                    PathSubsegment seg = Subsegments[i];\n                    PathParameterSubsegment paramterSubSegment = seg as PathParameterSubsegment;\n                    if (paramterSubSegment != null && paramterSubSegment.IsCatchAll)\n                    {\n                        return true;\n                    }\n                }\n                return false;\n            }\n        }\n\n        public List<PathSubsegment> Subsegments { get; private set; }\n\n#if ROUTE_DEBUGGING\n        public override string LiteralText\n        {\n            get\n            {\n                List<string> s = new List<string>();\n                foreach (PathSubsegment subsegment in Subsegments)\n                {\n                    s.Add(subsegment.LiteralText);\n                }\n                return String.Join(String.Empty, s.ToArray());\n            }\n        }\n\n        public override string ToString()\n        {\n            List<string> s = new List<string>();\n            foreach (PathSubsegment subsegment in Subsegments)\n            {\n                s.Add(subsegment.ToString());\n            }\n            return \"[ \" + String.Join(\", \", s.ToArray()) + \" ]\";\n        }\n#endif\n    }\n}\n"
  },
  {
    "path": "src/Common/Routing/PathLiteralSubsegment.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing\n#else\nnamespace System.Web.Mvc.Routing\n#endif\n{\n    // Represents a literal subsegment of a ContentPathSegment\n    internal sealed class PathLiteralSubsegment : PathSubsegment\n    {\n        public PathLiteralSubsegment(string literal)\n        {\n            Literal = literal;\n        }\n\n        public string Literal { get; private set; }\n\n#if ROUTE_DEBUGGING\n        public override string LiteralText\n        {\n            get\n            {\n                return Literal;\n            }\n        }\n\n        public override string ToString()\n        {\n            return \"\\\"\" + Literal + \"\\\"\";\n        }\n#endif\n    }\n}\n"
  },
  {
    "path": "src/Common/Routing/PathParameterSubsegment.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing\n#else\nnamespace System.Web.Mvc.Routing\n#endif\n{\n    // Represents a parameter subsegment of a ContentPathSegment\n    internal sealed class PathParameterSubsegment : PathSubsegment\n    {\n        public PathParameterSubsegment(string parameterName)\n        {\n            if (parameterName.StartsWith(\"*\", StringComparison.Ordinal))\n            {\n                ParameterName = parameterName.Substring(1);\n                IsCatchAll = true;\n            }\n            else\n            {\n                ParameterName = parameterName;\n            }\n        }\n\n        public bool IsCatchAll { get; private set; }\n\n        public string ParameterName { get; private set; }\n\n#if ROUTE_DEBUGGING\n        public override string LiteralText\n        {\n            get\n            {\n                return \"{\" + (IsCatchAll ? \"*\" : String.Empty) + ParameterName + \"}\";\n            }\n        }\n\n        public override string ToString()\n        {\n            return \"{\" + (IsCatchAll ? \"*\" : String.Empty) + ParameterName + \"}\";\n        }\n#endif\n    }\n}\n"
  },
  {
    "path": "src/Common/Routing/PathSegment.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing\n#else\nnamespace System.Web.Mvc.Routing\n#endif\n{\n    // Represents a segment of a URI such as a separator or content\n    internal abstract class PathSegment\n    {\n#if ROUTE_DEBUGGING\n        public abstract string LiteralText\n        {\n            get;\n        }\n#endif\n    }\n}\n"
  },
  {
    "path": "src/Common/Routing/PathSeparatorSegment.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing\n#else\nnamespace System.Web.Mvc.Routing\n#endif\n{\n    // Represents a \"/\" separator in a URI\n    internal sealed class PathSeparatorSegment : PathSegment\n    {\n#if ROUTE_DEBUGGING\n        public override string LiteralText\n        {\n            get\n            {\n                return \"/\";\n            }\n        }\n\n        public override string ToString()\n        {\n            return \"\\\"/\\\"\";\n        }\n#endif\n    }\n}\n"
  },
  {
    "path": "src/Common/Routing/PathSubsegment.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing\n#else\nnamespace System.Web.Mvc.Routing\n#endif\n{\n    // Represents a subsegment of a ContentPathSegment such as a parameter or a literal.\n    internal abstract class PathSubsegment\n    {\n#if ROUTE_DEBUGGING\n        public abstract string LiteralText\n        {\n            get;\n        }\n#endif\n    }\n}\n"
  },
  {
    "path": "src/Common/Routing/RouteEntry.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n#if ASPNETWEBAPI\nusing TRoute = System.Web.Http.Routing.IHttpRoute;\n#else\nusing TRoute = System.Web.Routing.Route;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing\n#else\nnamespace System.Web.Mvc.Routing\n#endif\n{\n    /// <summary>Represents a named route.</summary>\n    public class RouteEntry\n    {\n        private readonly string _name;\n        private readonly TRoute _route;\n\n        /// <summary>Initializes a new instance of the <see cref=\"RouteEntry\"/> class.</summary>\n        /// <param name=\"name\">The route name, if any; otherwise, <see langword=\"null\"/>.</param>\n        /// <param name=\"route\">The route.</param>\n        public RouteEntry(string name, TRoute route)\n        {\n            if (route == null)\n            {\n                throw new ArgumentNullException(\"route\");\n            }\n\n            _name = name;\n            _route = route;\n        }\n\n        /// <summary>Gets the route name, if any; otherwise, <see langword=\"null\"/>.</summary>\n        public string Name\n        {\n            get { return _name; }\n        }\n\n        /// <summary>Gets the route.</summary>\n        public TRoute Route\n        {\n            get { return _route; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Common/Routing/RouteFactoryAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\n\n#if ASPNETWEBAPI\nusing TRouteDictionary = System.Collections.Generic.IDictionary<string, object>;\n#else\nusing TRouteDictionary = System.Web.Routing.RouteValueDictionary;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing\n#else\nnamespace System.Web.Mvc.Routing\n#endif\n{\n    /// <summary>Represents an attribute route that may contain custom constraints.</summary>\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = false, AllowMultiple = true)]\n    public abstract class RouteFactoryAttribute : Attribute, IDirectRouteFactory\n    {\n        private readonly string _template;\n\n        /// <summary>Initializes a new instance of the <see cref=\"RouteFactoryAttribute\"/> class.</summary>\n        /// <param name=\"template\">The route template.</param>\n        protected RouteFactoryAttribute(string template)\n        {\n            _template = template;\n        }\n\n        /// <summary>Gets the route template.</summary>\n        public string Template\n        {\n            get { return _template; }\n        }\n\n        /// <summary>Gets or sets the route name, if any; otherwise <see langword=\"null\"/>.</summary>\n        public string Name { get; set; }\n\n        /// <summary>Gets or sets the route order.</summary>\n        public int Order { get; set; }\n\n        /// <summary>Gets the route defaults, if any; otherwise <see langword=\"null\"/>.</summary>\n        public virtual TRouteDictionary Defaults\n        {\n            get { return null; }\n        }\n\n        /// <summary>Gets the route constraints, if any; otherwise <see langword=\"null\"/>.</summary>\n        public virtual TRouteDictionary Constraints\n        {\n            get { return null; }\n        }\n\n        /// <summary>Gets the route data tokens, if any; otherwise <see langword=\"null\"/>.</summary>\n        public virtual TRouteDictionary DataTokens\n        {\n            get { return null; }\n        }\n\n        /// <inheritdoc />\n        public RouteEntry CreateRoute(DirectRouteFactoryContext context)\n        {\n            if (context == null)\n            {\n                throw new ArgumentNullException(\"context\");\n            }\n\n            IDirectRouteBuilder builder = context.CreateBuilder(Template);\n            Contract.Assert(builder != null);\n            builder.Name = Name;\n            builder.Order = Order;\n\n            TRouteDictionary builderDefaults = builder.Defaults;\n\n            if (builderDefaults == null)\n            {\n                builder.Defaults = Defaults;\n            }\n            else\n            {\n                TRouteDictionary defaults = Defaults;\n\n                if (defaults != null)\n                {\n                    foreach (KeyValuePair<string, object> defaultItem in defaults)\n                    {\n                        builderDefaults[defaultItem.Key] = defaultItem.Value;\n                    }\n                }\n            }\n\n            TRouteDictionary builderConstraints = builder.Constraints;\n\n            if (builderConstraints == null)\n            {\n                builder.Constraints = Constraints;\n            }\n            else\n            {\n                TRouteDictionary constraints = Constraints;\n\n                if (constraints != null)\n                {\n                    foreach (KeyValuePair<string, object> constraint in constraints)\n                    {\n                        builderConstraints[constraint.Key] = constraint.Value;\n                    }\n                }\n            }\n\n            TRouteDictionary builderDataTokens = builder.DataTokens;\n\n            if (builderDataTokens == null)\n            {\n                builder.DataTokens = DataTokens;\n            }\n            else\n            {\n                TRouteDictionary dataTokens = DataTokens;\n\n                if (dataTokens != null)\n                {\n                    foreach (KeyValuePair<string, object> dataToken in dataTokens)\n                    {\n                        builderDataTokens[dataToken.Key] = dataToken.Value;\n                    }\n                }\n            }\n\n            return builder.Build();\n        }\n    }\n}\n"
  },
  {
    "path": "src/Common/Routing/RouteInfoDirectRouteFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\n\n#if ASPNETWEBAPI\nusing TRouteInfoProvider = System.Web.Http.Routing.IHttpRouteInfoProvider;\n#else\nusing System.Web.Mvc.Properties;\nusing TRouteInfoProvider = System.Web.Mvc.Routing.IRouteInfoProvider;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing\n#else\nnamespace System.Web.Mvc.Routing\n#endif\n{\n    /// <remarks>\n    /// This class is an adapter that turns an IHttpRouteInfoProvider into an IDirectRouteFactory. We need it because\n    /// we already shipped IHttpRouteInfoProvider but want to standardize the internal implementation around the more\n    /// general IDirectRouteFactory interface.\n    /// We can remove this class if we ever stop supporting custom attributes that implement IHttpRouteInfoProvider.\n    /// </remarks>\n    internal class RouteInfoDirectRouteFactory : IDirectRouteFactory\n    {\n        private readonly TRouteInfoProvider _infoProvider;\n\n        public RouteInfoDirectRouteFactory(TRouteInfoProvider infoProvider)\n        {\n            if (infoProvider == null)\n            {\n                throw new ArgumentNullException(\"infoProvider\");\n            }\n\n            _infoProvider = infoProvider;\n        }\n\n        public RouteEntry CreateRoute(DirectRouteFactoryContext context)\n        {\n            Contract.Assert(context != null);\n\n            IDirectRouteBuilder builder = context.CreateBuilder(_infoProvider.Template);\n            Contract.Assert(builder != null);\n\n            builder.Name = _infoProvider.Name;\n\n#if ASPNETWEBAPI\n            builder.Order = _infoProvider.Order;\n#endif\n\n            return builder.Build();\n        }\n    }\n}\n"
  },
  {
    "path": "src/Common/Routing/RouteParser.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\n#if ASPNETWEBAPI\nusing ErrorResources = System.Web.Http.Properties.SRResources;\nusing TParsedRoute = System.Web.Http.Routing.HttpParsedRoute;\n#else\nusing ErrorResources = System.Web.Mvc.Properties.MvcResources;\nusing TParsedRoute = System.Web.Mvc.Routing.ParsedRoute;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing\n#else\nnamespace System.Web.Mvc.Routing\n#endif\n{\n    // in the MVC case, route parsing is done for AttributeRouting's sake, so that\n    // it could order the discovered routes before pushing them into the routeCollection,\n    // where, unfortunately, they would be parsed again.\n    internal static class RouteParser\n    {\n        private static string GetLiteral(string segmentLiteral)\n        {\n            // Scan for errant single { and } and convert double {{ to { and double }} to }\n\n            // First we eliminate all escaped braces and then check if any other braces are remaining\n            string newLiteral = segmentLiteral.Replace(\"{{\", String.Empty).Replace(\"}}\", String.Empty);\n            if (newLiteral.Contains(\"{\") || newLiteral.Contains(\"}\"))\n            {\n                return null;\n            }\n\n            // If it's a valid format, we unescape the braces\n            return segmentLiteral.Replace(\"{{\", \"{\").Replace(\"}}\", \"}\");\n        }\n\n        private static int IndexOfFirstOpenParameter(string segment, int startIndex)\n        {\n            // Find the first unescaped open brace\n            while (true)\n            {\n                startIndex = segment.IndexOf('{', startIndex);\n                if (startIndex == -1)\n                {\n                    // If there are no more open braces, stop\n                    return -1;\n                }\n                if ((startIndex + 1 == segment.Length) ||\n                    ((startIndex + 1 < segment.Length) && (segment[startIndex + 1] != '{')))\n                {\n                    // If we found an open brace that is followed by a non-open brace, it's\n                    // a parameter delimiter.\n                    // It's also a delimiter if the open brace is the last character - though\n                    // it ends up being being called out as invalid later on.\n                    return startIndex;\n                }\n                // Increment by two since we want to skip both the open brace that\n                // we're on as well as the subsequent character since we know for\n                // sure that it is part of an escape sequence.\n                startIndex += 2;\n            }\n        }\n\n        internal static bool IsSeparator(string s)\n        {\n            return String.Equals(s, \"/\", StringComparison.Ordinal);\n        }\n\n        private static bool IsValidParameterName(string parameterName)\n        {\n            if (parameterName.Length == 0)\n            {\n                return false;\n            }\n\n            for (int i = 0; i < parameterName.Length; i++)\n            {\n                char c = parameterName[i];\n                if (c == '/' || c == '{' || c == '}')\n                {\n                    return false;\n                }\n            }\n\n            return true;\n        }\n\n        internal static bool IsInvalidRouteTemplate(string routeTemplate)\n        {\n            return routeTemplate.StartsWith(\"~\", StringComparison.Ordinal) ||\n                   routeTemplate.StartsWith(\"/\", StringComparison.Ordinal) ||\n                   (routeTemplate.IndexOf('?') != -1);\n        }\n\n        public static TParsedRoute Parse(string routeTemplate)\n        {\n            if (routeTemplate == null)\n            {\n                routeTemplate = String.Empty;\n            }\n\n            if (IsInvalidRouteTemplate(routeTemplate))\n            {\n                throw Error.Argument(\"routeTemplate\", ErrorResources.Route_InvalidRouteTemplate);\n            }\n\n            List<string> uriParts = SplitUriToPathSegmentStrings(routeTemplate);\n            Exception ex = ValidateUriParts(uriParts);\n            if (ex != null)\n            {\n                throw ex;\n            }\n\n            List<PathSegment> pathSegments = SplitUriToPathSegments(uriParts);\n\n            Contract.Assert(uriParts.Count == pathSegments.Count, \"The number of string segments should be the same as the number of path segments\");\n\n            return new TParsedRoute(pathSegments);\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2208:InstantiateArgumentExceptionsCorrectly\",\n            Justification = \"The exceptions are just constructed here, but they are thrown from a method that does have those parameter names.\")]\n        private static List<PathSubsegment> ParseUriSegment(string segment, out Exception exception)\n        {\n            int startIndex = 0;\n\n            List<PathSubsegment> pathSubsegments = new List<PathSubsegment>();\n\n            while (startIndex < segment.Length)\n            {\n                int nextParameterStart = IndexOfFirstOpenParameter(segment, startIndex);\n                if (nextParameterStart == -1)\n                {\n                    // If there are no more parameters in the segment, capture the remainder as a literal and stop\n                    string lastLiteralPart = GetLiteral(segment.Substring(startIndex));\n                    if (lastLiteralPart == null)\n                    {\n                        exception = Error.Argument(\"routeTemplate\", ErrorResources.Route_MismatchedParameter, segment);\n                        return null;\n                    }\n\n                    if (lastLiteralPart.Length > 0)\n                    {\n                        pathSubsegments.Add(new PathLiteralSubsegment(lastLiteralPart));\n                    }\n                    break;\n                }\n\n                int nextParameterEnd = segment.IndexOf('}', nextParameterStart + 1);\n                if (nextParameterEnd == -1)\n                {\n                    exception = Error.Argument(\"routeTemplate\", ErrorResources.Route_MismatchedParameter, segment);\n                    return null;\n                }\n\n                string literalPart = GetLiteral(segment.Substring(startIndex, nextParameterStart - startIndex));\n                if (literalPart == null)\n                {\n                    exception = Error.Argument(\"routeTemplate\", ErrorResources.Route_MismatchedParameter, segment);\n                    return null;\n                }\n\n                if (literalPart.Length > 0)\n                {\n                    pathSubsegments.Add(new PathLiteralSubsegment(literalPart));\n                }\n\n                string parameterName = segment.Substring(nextParameterStart + 1, nextParameterEnd - nextParameterStart - 1);\n                pathSubsegments.Add(new PathParameterSubsegment(parameterName));\n\n                startIndex = nextParameterEnd + 1;\n            }\n\n            exception = null;\n            return pathSubsegments;\n        }\n\n        private static List<PathSegment> SplitUriToPathSegments(List<string> uriParts)\n        {\n            List<PathSegment> pathSegments = new List<PathSegment>();\n\n            foreach (string pathSegment in uriParts)\n            {\n                bool isCurrentPartSeparator = IsSeparator(pathSegment);\n                if (isCurrentPartSeparator)\n                {\n                    pathSegments.Add(new PathSeparatorSegment());\n                }\n                else\n                {\n                    Exception exception;\n                    List<PathSubsegment> subsegments = ParseUriSegment(pathSegment, out exception);\n                    Contract.Assert(exception == null, \"This only gets called after the path has been validated, so there should never be an exception here\");\n                    pathSegments.Add(new PathContentSegment(subsegments));\n                }\n            }\n            return pathSegments;\n        }\n\n        internal static List<string> SplitUriToPathSegmentStrings(string uri)\n        {\n            List<string> parts = new List<string>();\n\n            if (String.IsNullOrEmpty(uri))\n            {\n                return parts;\n            }\n\n            int currentIndex = 0;\n\n            // Split the incoming URI into individual parts\n            while (currentIndex < uri.Length)\n            {\n                int indexOfNextSeparator = uri.IndexOf('/', currentIndex);\n                if (indexOfNextSeparator == -1)\n                {\n                    // If there are no more separators, the rest of the string is the last part\n                    string finalPart = uri.Substring(currentIndex);\n                    if (finalPart.Length > 0)\n                    {\n                        parts.Add(finalPart);\n                    }\n                    break;\n                }\n\n                string nextPart = uri.Substring(currentIndex, indexOfNextSeparator - currentIndex);\n                if (nextPart.Length > 0)\n                {\n                    parts.Add(nextPart);\n                }\n\n                Contract.Assert(uri[indexOfNextSeparator] == '/', \"The separator char itself should always be a '/'.\");\n                parts.Add(\"/\");\n                currentIndex = indexOfNextSeparator + 1;\n            }\n\n            return parts;\n        }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1800:DoNotCastUnnecessarily\", Justification = \"Not changing original algorithm\")]\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2208:InstantiateArgumentExceptionsCorrectly\",\n            Justification = \"The exceptions are just constructed here, but they are thrown from a method that does have those parameter names.\")]\n        private static Exception ValidateUriParts(List<string> pathSegments)\n        {\n            Contract.Assert(pathSegments != null, \"The value should always come from SplitUri(), and that function should never return null.\");\n\n            HashSet<string> usedParameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);\n            bool? isPreviousPartSeparator = null;\n\n            bool foundCatchAllParameter = false;\n\n            foreach (string pathSegment in pathSegments)\n            {\n                if (foundCatchAllParameter)\n                {\n                    // If we ever start an iteration of the loop and we've already found a\n                    // catchall parameter then we have an invalid URI format.\n                    return Error.Argument(\"routeTemplate\", ErrorResources.Route_CatchAllMustBeLast, \"routeTemplate\");\n                }\n\n                bool isCurrentPartSeparator;\n                if (isPreviousPartSeparator == null)\n                {\n                    // Prime the loop with the first value\n                    isPreviousPartSeparator = IsSeparator(pathSegment);\n                    isCurrentPartSeparator = isPreviousPartSeparator.Value;\n                }\n                else\n                {\n                    isCurrentPartSeparator = IsSeparator(pathSegment);\n\n                    // If both the previous part and the current part are separators, it's invalid\n                    if (isCurrentPartSeparator && isPreviousPartSeparator.Value)\n                    {\n                        return Error.Argument(\"routeTemplate\", ErrorResources.Route_CannotHaveConsecutiveSeparators);\n                    }\n\n                    Contract.Assert(isCurrentPartSeparator != isPreviousPartSeparator.Value, \"This assert should only happen if both the current and previous parts are non-separators. This should never happen because consecutive non-separators are always parsed as a single part.\");\n                    isPreviousPartSeparator = isCurrentPartSeparator;\n                }\n\n                // If it's not a separator, parse the segment for parameters and validate it\n                if (!isCurrentPartSeparator)\n                {\n                    Exception exception;\n                    List<PathSubsegment> subsegments = ParseUriSegment(pathSegment, out exception);\n                    if (exception != null)\n                    {\n                        return exception;\n                    }\n\n                    exception = ValidateUriSegment(subsegments, usedParameterNames);\n                    if (exception != null)\n                    {\n                        return exception;\n                    }\n\n                    foundCatchAllParameter = subsegments.Any<PathSubsegment>(seg => (seg is PathParameterSubsegment) && ((PathParameterSubsegment)seg).IsCatchAll);\n                }\n            }\n            return null;\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2208:InstantiateArgumentExceptionsCorrectly\",\n            Justification = \"The exceptions are just constructed here, but they are thrown from a method that does have those parameter names.\")]\n        private static Exception ValidateUriSegment(List<PathSubsegment> pathSubsegments, HashSet<string> usedParameterNames)\n        {\n            bool segmentContainsCatchAll = false;\n\n            Type previousSegmentType = null;\n\n            foreach (PathSubsegment subsegment in pathSubsegments)\n            {\n                if (previousSegmentType != null)\n                {\n                    if (previousSegmentType == subsegment.GetType())\n                    {\n                        return Error.Argument(\"routeTemplate\", ErrorResources.Route_CannotHaveConsecutiveParameters);\n                    }\n                }\n                previousSegmentType = subsegment.GetType();\n\n                PathLiteralSubsegment literalSubsegment = subsegment as PathLiteralSubsegment;\n                if (literalSubsegment != null)\n                {\n                    // Nothing to validate for literals - everything is valid\n                }\n                else\n                {\n                    PathParameterSubsegment parameterSubsegment = subsegment as PathParameterSubsegment;\n                    if (parameterSubsegment != null)\n                    {\n                        string parameterName = parameterSubsegment.ParameterName;\n\n                        if (parameterSubsegment.IsCatchAll)\n                        {\n                            segmentContainsCatchAll = true;\n                        }\n\n                        // Check for valid characters in the parameter name\n                        if (!IsValidParameterName(parameterName))\n                        {\n                            return Error.Argument(\"routeTemplate\", ErrorResources.Route_InvalidParameterName, parameterName);\n                        }\n\n                        if (usedParameterNames.Contains(parameterName))\n                        {\n                            return Error.Argument(\"routeTemplate\", ErrorResources.Route_RepeatedParameter, parameterName);\n                        }\n                        else\n                        {\n                            usedParameterNames.Add(parameterName);\n                        }\n                    }\n                    else\n                    {\n                        Contract.Assert(false, \"Invalid path subsegment type\");\n                    }\n                }\n            }\n\n            if (segmentContainsCatchAll && (pathSubsegments.Count != 1))\n            {\n                return Error.Argument(\"routeTemplate\", ErrorResources.Route_CannotHaveCatchAllInMultiSegment);\n            }\n\n            return null;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Common/Routing/RoutePrecedence.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\n\n#if ASPNETWEBAPI\nusing TParsedRoute = System.Web.Http.Routing.HttpParsedRoute;\n#else\nusing TParsedRoute = System.Web.Mvc.Routing.ParsedRoute;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing\n#else\nnamespace System.Web.Mvc.Routing\n#endif\n{\n    internal static class RoutePrecedence\n    {\n        // Segments have the following order:\n        // 1 - Literal segments\n        // 2 - Constrained parameter segments / Multi-part segments\n        // 3 - Unconstrained parameter segments\n        // 4 - Constrained wildcard parameter segments\n        // 5 - Unconstrained wildcard parameter segments\n        internal static int ComputeDigit(PathContentSegment segment, IDictionary<string, object> constraints)\n        {\n            if (segment.Subsegments.Count > 1)\n            {\n                // Multi-part segments should appear after literal segments but before parameter segments\n                return 2;\n            }\n\n            PathSubsegment subsegment = segment.Subsegments[0];\n            // Literal segments always go first\n            if (subsegment is PathLiteralSubsegment)\n            {\n                return 1;\n            }\n            else\n            {\n                PathParameterSubsegment parameterSegment = subsegment as PathParameterSubsegment;\n                Contract.Assert(parameterSegment != null);\n                int order = parameterSegment.IsCatchAll ? 5 : 3;\n\n                // If there is a route constraint for the parameter, reduce order by 1\n                // Constrained parameters end up with order 2, Constrained catch alls end up with order 4\n                if (constraints != null && constraints.ContainsKey(parameterSegment.ParameterName))\n                {\n                    order--;\n                }\n\n                return order;\n            }\n        }\n\n        public static decimal Compute(TParsedRoute parsedRoute, IDictionary<string, object> constraints)\n        {\n            // Each precedence digit corresponds to one decimal place. For example, 3 segments with precedences 2, 1,\n            // and 4 results in a combined precedence of 2.14 (decimal).\n            IList<PathContentSegment> segments = parsedRoute.PathSegments.OfType<PathContentSegment>().ToArray();\n\n            decimal precedence = 0;\n            uint divisor = 1; // The first digit occupies the one's place.\n\n            for (int i = 0; i < segments.Count; i++)\n            {\n                PathContentSegment segment = segments[i];\n\n                int digit = ComputeDigit(segment, constraints);\n                Contract.Assert(digit >= 0 && digit < 10);\n\n                precedence = precedence + Decimal.Divide(digit, divisor);\n\n                // The next digit occupies the subsequent place (always after the decimal point and growing to the\n                // right).\n                divisor *= 10;\n            }\n\n            return precedence;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Common/Routing/SubRouteCollection.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Linq;\n\n#if ASPNETWEBAPI\nusing System.Web.Http.Properties;\nusing TRoute = System.Web.Http.Routing.IHttpRoute;\nusing TRouteEntry = System.Web.Http.Routing.RouteEntry;\n#else\nusing System.Web.Mvc.Properties;\nusing TRoute = System.Web.Routing.Route;\nusing TRouteEntry = System.Web.Mvc.Routing.RouteEntry;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing\n#else\nnamespace System.Web.Mvc.Routing\n#endif\n{\n    /// <summary>Represents a collection of route entries and the routes they contain.</summary>\n    /// <remarks>\n    /// This is used in attribute routing, where we want to match multiple routes, and then later\n    /// disambiguate which one is best.\n    /// </remarks>\n    internal class SubRouteCollection : IReadOnlyCollection<TRoute>\n    {\n        private readonly List<TRoute> _routes = new List<TRoute>();\n        private readonly List<TRouteEntry> _entries = new List<TRouteEntry>();\n\n        public void Add(TRouteEntry entry)\n        {\n            Contract.Assert(entry != null);\n            TRoute route = entry.Route;\n            Contract.Assert(route != null);\n\n            string name = entry.Name;\n\n            if (name != null)\n            {\n                TRouteEntry duplicateEntry = _entries.SingleOrDefault((e) => e.Name == name);\n\n                if (duplicateEntry != null)\n                {\n                    ThrowExceptionForDuplicateRouteNames(name, route, duplicateEntry.Route);\n                }\n            }\n\n            _routes.Add(route);\n            _entries.Add(entry);\n        }\n\n        public void AddRange(IEnumerable<TRouteEntry> entries)\n        {\n            foreach (RouteEntry entry in entries)\n            {\n                Add(entry);\n            }\n        }\n\n        public int Count\n        {\n            get { return _entries.Count; }\n        }\n\n        public IEnumerator<TRoute> GetEnumerator()\n        {\n            return _routes.GetEnumerator();\n        }\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return ((IEnumerable)_routes).GetEnumerator();\n        }\n\n        public IReadOnlyCollection<TRouteEntry> Entries\n        {\n            get { return _entries; }\n        }\n\n        private static void ThrowExceptionForDuplicateRouteNames(string name, TRoute route1, TRoute route2)\n        {\n#if ASPNETWEBAPI\n            throw new InvalidOperationException(String.Format(\n                CultureInfo.CurrentCulture,\n                SRResources.SubRouteCollection_DuplicateRouteName,\n                name,\n                route1.RouteTemplate,\n                route2.RouteTemplate));\n#else\n            throw new InvalidOperationException(String.Format(\n                CultureInfo.CurrentCulture,\n                MvcResources.SubRouteCollection_DuplicateRouteName,\n                name,\n                route1.Url,\n                route2.Url));\n#endif\n        }\n    }\n}\n"
  },
  {
    "path": "src/Common/TaskHelpers.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Threading.Tasks\n{\n    /// <summary>\n    /// Helpers for safely using Task libraries. \n    /// </summary>\n    internal static class TaskHelpers\n    {\n        private static readonly Task _defaultCompleted = Task.FromResult<AsyncVoid>(default(AsyncVoid));\n\n        private static readonly Task<object> _completedTaskReturningNull = Task.FromResult<object>(null);\n\n        /// <summary>\n        /// Returns a canceled Task. The task is completed, IsCanceled = True, IsFaulted = False.\n        /// </summary>\n        internal static Task Canceled()\n        {\n            return CancelCache<AsyncVoid>.Canceled;\n        }\n\n        /// <summary>\n        /// Returns a canceled Task of the given type. The task is completed, IsCanceled = True, IsFaulted = False.\n        /// </summary>\n        internal static Task<TResult> Canceled<TResult>()\n        {\n            return CancelCache<TResult>.Canceled;\n        }\n\n        /// <summary>\n        /// Returns a completed task that has no result. \n        /// </summary>        \n        internal static Task Completed()\n        {\n            return _defaultCompleted;\n        }\n\n        /// <summary>\n        /// Returns an error task. The task is Completed, IsCanceled = False, IsFaulted = True\n        /// </summary>\n        internal static Task FromError(Exception exception)\n        {\n            return FromError<AsyncVoid>(exception);\n        }\n\n        /// <summary>\n        /// Returns an error task of the given type. The task is Completed, IsCanceled = False, IsFaulted = True\n        /// </summary>\n        /// <typeparam name=\"TResult\"></typeparam>\n        internal static Task<TResult> FromError<TResult>(Exception exception)\n        {\n            TaskCompletionSource<TResult> tcs = new TaskCompletionSource<TResult>();\n            tcs.SetException(exception);\n            return tcs.Task;\n        }\n\n        internal static Task<object> NullResult()\n        {\n            return _completedTaskReturningNull;\n        }\n\n        /// <summary>\n        /// Used as the T in a \"conversion\" of a Task into a Task{T}\n        /// </summary>\n        private struct AsyncVoid\n        {\n        }\n\n        /// <summary>\n        /// This class is a convenient cache for per-type cancelled tasks\n        /// </summary>\n        private static class CancelCache<TResult>\n        {\n            public static readonly Task<TResult> Canceled = GetCancelledTask();\n\n            private static Task<TResult> GetCancelledTask()\n            {\n                TaskCompletionSource<TResult> tcs = new TaskCompletionSource<TResult>();\n                tcs.SetCanceled();\n                return tcs.Task;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Common/TaskHelpersExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Threading.Tasks\n{\n    internal static class TaskHelpersExtensions\n    {\n        /// <summary>\n        /// Cast Task to Task of object\n        /// </summary>\n        internal static async Task<object> CastToObject(this Task task)\n        {\n            await task;\n            return null;\n        }\n\n        /// <summary>\n        /// Cast Task of T to Task of object\n        /// </summary>\n        internal static async Task<object> CastToObject<T>(this Task<T> task)\n        {\n            return (object)await task;\n        }\n\n        /// <summary>\n        /// Throws the first faulting exception for a task which is faulted. It preserves the original stack trace when\n        /// throwing the exception. Note: It is the caller's responsibility not to pass incomplete tasks to this\n        /// method, because it does degenerate into a call to the equivalent of .Wait() on the task when it hasn't yet\n        /// completed.\n        /// </summary>\n        internal static void ThrowIfFaulted(this Task task)\n        {\n            task.GetAwaiter().GetResult();\n        }\n\n        /// <summary>\n        /// Attempts to get the result value for the given task. If the task ran to completion, then\n        /// it will return true and set the result value; otherwise, it will return false.\n        /// </summary>\n        [SuppressMessage(\"Microsoft.Web.FxCop\", \"MW1201\", Justification = \"The usages here are deemed safe, and provide the implementations that this rule relies upon.\")]\n        internal static bool TryGetResult<TResult>(this Task<TResult> task, out TResult result)\n        {\n            if (task.Status == TaskStatus.RanToCompletion)\n            {\n                result = task.Result;\n                return true;\n            }\n\n            result = default(TResult);\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Common/TraceWriterExceptionMapper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Http;\n\nnamespace System.Web.Http.Tracing\n{\n    /// <summary>\n    /// Extension methods for <see cref=\"TraceRecord\"/>.\n    /// </summary>\n    internal static class TraceWriterExceptionMapper\n    {\n        private const string HttpErrorExceptionMessageFormat = \"ExceptionMessage{0}='{1}'\";\n        private const string HttpErrorExceptionTypeFormat = \"ExceptionType{0}='{1}'\";\n        private const string HttpErrorMessageDetailFormat = \"MessageDetail='{0}'\";\n        private const string HttpErrorModelStateErrorFormat = \"ModelStateError=[{0}]\";\n        private const string HttpErrorModelStatePairFormat = \"{0}=[{1}]\";\n        private const string HttpErrorStackTraceFormat = \"StackTrace{0}={1}\";\n        private const string HttpErrorUserMessageFormat = \"UserMessage='{0}'\";\n\n        /// <summary>\n        /// Examines the given <see cref=\"TraceRecord\"/> to determine whether it\n        /// contains an <see cref=\"HttpResponseException\"/> and if so, modifies\n        /// the <see cref=\"TraceRecord\"/> to capture more detailed information.\n        /// </summary>\n        /// <param name=\"traceRecord\">The <see cref=\"TraceRecord\"/> to examine and modify.</param>\n        public static void TranslateHttpResponseException(TraceRecord traceRecord)\n        {\n            Contract.Assert(traceRecord != null);\n\n            HttpResponseException httpResponseException = ExtractHttpResponseException(traceRecord.Exception);\n            if (httpResponseException == null)\n            {\n                return;\n            }\n\n            HttpResponseMessage response = httpResponseException.Response;\n            Contract.Assert(response != null);\n\n            // If the status has been set already, do not overwrite it,\n            // otherwise propagate the status into the record.\n            if (traceRecord.Status == 0)\n            {\n                traceRecord.Status = response.StatusCode;\n            }\n\n            traceRecord.Level = GetMappedTraceLevel(httpResponseException) ?? traceRecord.Level;\n\n            // HttpResponseExceptions often contain HttpError instances that carry\n            // detailed information that may be filtered out by IncludeErrorDetailPolicy\n            // before reaching the client. Capture it here for the trace.\n            ObjectContent objectContent = response.Content as ObjectContent;\n            if (objectContent == null)\n            {\n                return;\n            }\n\n            HttpError httpError = objectContent.Value as HttpError;\n            if (httpError == null)\n            {\n                return;\n            }\n\n            object messageObject = null;\n            object messageDetailsObject = null;\n\n            List<string> messages = new List<string>();\n\n            if (httpError.TryGetValue(HttpErrorKeys.MessageKey, out messageObject))\n            {\n                messages.Add(Error.Format(HttpErrorUserMessageFormat, messageObject));\n            }\n\n            if (httpError.TryGetValue(HttpErrorKeys.MessageDetailKey, out messageDetailsObject))\n            {\n                messages.Add(Error.Format(HttpErrorMessageDetailFormat, messageDetailsObject));\n            }\n\n            // Extract the exception from this HttpError and then incrementally\n            // walk down all inner exceptions.\n            AddExceptions(httpError, messages);\n\n            // ModelState errors are handled with a nested HttpError\n            object modelStateErrorObject = null;\n            if (httpError.TryGetValue(HttpErrorKeys.ModelStateKey, out modelStateErrorObject))\n            {\n                HttpError modelStateError = modelStateErrorObject as HttpError;\n                if (modelStateError != null)\n                {\n                    messages.Add(FormatModelStateErrors(modelStateError));\n                }\n            }\n\n            traceRecord.Message = String.Join(\", \", messages);\n        }\n\n        /// <summary>\n        /// Gets the <see cref=\"TraceLevel\"/> per the <see cref=\"HttpStatusCode\"/> if the given exception is\n        /// a <see cref=\"HttpResponseException\"/>; otherwise <see langword=\"null\"/>.\n        /// </summary>\n        /// <param name=\"exception\">The exception.</param>\n        /// <returns>The corresponding trace level if the exception represents an <see cref=\"HttpResponseException\"/>.</returns>\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\", Justification = \"shared source. called from a different assembly\")]\n        public static TraceLevel? GetMappedTraceLevel(Exception exception)\n        {\n            HttpResponseException httpResponseException = ExtractHttpResponseException(exception);\n            if (httpResponseException == null)\n            {\n                return null;\n            }\n\n            return GetMappedTraceLevel(httpResponseException);\n        }\n\n        /// <summary>\n        /// Gets the <see cref=\"TraceLevel\"/> per the <see cref=\"HttpStatusCode\"/>.\n        /// </summary>\n        /// <param name=\"httpResponseException\">The exception for which the trace level has to be found.</param>\n        /// <returns>The mapped trace level.</returns>\n        public static TraceLevel? GetMappedTraceLevel(HttpResponseException httpResponseException)\n        {\n            Contract.Assert(httpResponseException != null);\n\n            HttpResponseMessage response = httpResponseException.Response;\n            Contract.Assert(response != null);\n\n            TraceLevel? level = null;\n\n            // Client level errors are downgraded to TraceLevel.Warn\n            if ((int)response.StatusCode < (int)HttpStatusCode.InternalServerError)\n            {\n                level = TraceLevel.Warn;\n            }\n\n            // Non errors are downgraded to TraceLevel.Info\n            if ((int)response.StatusCode < (int)HttpStatusCode.BadRequest)\n            {\n                level = TraceLevel.Info;\n            }\n\n            return level;\n        }\n\n        private static HttpResponseException ExtractHttpResponseException(Exception exception)\n        {\n            if (exception == null)\n            {\n                return null;\n            }\n\n            var httpResponseException = exception as HttpResponseException;\n            if (httpResponseException != null)\n            {\n                return httpResponseException;\n            }\n\n            var aggregateException = exception as AggregateException;\n            if (aggregateException != null)\n            {\n                httpResponseException = aggregateException\n                    .Flatten()\n                    .InnerExceptions\n                    .Select(ExtractHttpResponseException)\n                    .Where(ex => ex != null && ex.Response != null)\n                    .OrderByDescending(ex => ex.Response.StatusCode)\n                    .FirstOrDefault();\n                return httpResponseException;\n            }\n\n            return ExtractHttpResponseException(exception.InnerException);\n        }\n\n        /// <summary>\n        /// Unpacks any exceptions in the given <see cref=\"HttpError\"/> and adds\n        /// them into a collection of name-value pairs that can be composed into a single string.\n        /// </summary>\n        /// <remarks>\n        /// This helper also iterates over all inner exceptions and unpacks them too.\n        /// </remarks>\n        /// <param name=\"httpError\">The <see cref=\"HttpError\"/> to unpack.</param>\n        /// <param name=\"messages\">A collection of messages to which the new information should be added.</param>\n        private static void AddExceptions(HttpError httpError, List<string> messages)\n        {\n            Contract.Assert(httpError != null);\n            Contract.Assert(messages != null);\n\n            object exceptionMessageObject = null;\n            object exceptionTypeObject = null;\n            object stackTraceObject = null;\n            object innerExceptionObject = null;\n\n            for (int i = 0; httpError != null; i++)\n            {\n                // For uniqueness, key names append the depth of inner exception\n                string indexText = i == 0 ? String.Empty : Error.Format(\"[{0}]\", i);\n\n                if (httpError.TryGetValue(HttpErrorKeys.ExceptionTypeKey, out exceptionTypeObject))\n                {\n                    messages.Add(Error.Format(HttpErrorExceptionTypeFormat, indexText, exceptionTypeObject));\n                }\n\n                if (httpError.TryGetValue(HttpErrorKeys.ExceptionMessageKey, out exceptionMessageObject))\n                {\n                    messages.Add(Error.Format(HttpErrorExceptionMessageFormat, indexText, exceptionMessageObject));\n                }\n\n                if (httpError.TryGetValue(HttpErrorKeys.StackTraceKey, out stackTraceObject))\n                {\n                    messages.Add(Error.Format(HttpErrorStackTraceFormat, indexText, stackTraceObject));\n                }\n\n                if (!httpError.TryGetValue(HttpErrorKeys.InnerExceptionKey, out innerExceptionObject))\n                {\n                    break;\n                }\n\n                Contract.Assert(!Object.ReferenceEquals(httpError, innerExceptionObject));\n\n                httpError = innerExceptionObject as HttpError;\n            }\n        }\n\n        private static string FormatModelStateErrors(HttpError modelStateError)\n        {\n            Contract.Assert(modelStateError != null);\n\n            List<string> messages = new List<string>();\n            foreach (var pair in modelStateError)\n            {\n                IEnumerable<string> errorList = pair.Value as IEnumerable<string>;\n                if (errorList != null)\n                {\n                    messages.Add(Error.Format(HttpErrorModelStatePairFormat, pair.Key, String.Join(\", \", errorList)));\n                }\n            }\n\n            return Error.Format(HttpErrorModelStateErrorFormat, String.Join(\", \", messages));\n        }\n    }\n}\n"
  },
  {
    "path": "src/Common/TypeExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\n\nnamespace System\n{\n    /// <summary>\n    /// Extension methods for <see cref=\"Type\"/>.\n    /// </summary>\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    internal static class TypeExtensions\n    {\n        public static bool IsNullable(this Type type)\n        {\n            if (type.IsValueType)\n            {\n                // value types are only nullable if they are Nullable<T>\n                return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);\n            }\n            else\n            {\n                // reference types are always nullable\n                return true;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/CommonAssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Reflection;\nusing System.Resources;\nusing System.Runtime.InteropServices;\n\n#if !BUILD_GENERATED_VERSION\n[assembly: AssemblyCompany(\".NET Foundation\")]\n[assembly: AssemblyCopyright(\"Copyright © .NET Foundation. All rights reserved.\")]\n#endif\n[assembly: AssemblyConfiguration(\"\")]\n[assembly: AssemblyTrademark(\"\")]\n[assembly: ComVisible(false)]\n#if !NOT_CLS_COMPLIANT\n[assembly: CLSCompliant(true)]\n#endif\n[assembly: NeutralResourcesLanguage(\"en-US\")]\n[assembly: AssemblyMetadata(\"Serviceable\", \"True\")]\n\n// ===================================================================================\n//  TAKE CARE WHEN EDITING OR REMOVING ANYTHING BELOW THIS COMMENT.\n//  BUILD_GENERATED_VERSION will be set in any CI build. Versions below are not used.\n// ===================================================================================\n\n#if (ASPNETMVC && (ASPNETWEBPAGES || ASPNETFACEBOOK || ASPNETHTTPFORMATTING)) || (ASPNETWEBPAGES && (ASPNETFACEBOOK || ASPNETHTTPFORMATTING)) || (ASPNETFACEBOOK && ASPNETHTTPFORMATTING)\n#error Runtime projects cannot define more than one of ASPNETMVC, ASPNETWEBPAGES, ASPNETFACEBOOK, or ASPNETHTTPFORMATTING\n#elif ASPNETHTTPFORMATTING\n#if !BUILD_GENERATED_VERSION\n[assembly: AssemblyVersion(\"6.0.0.0\")] // ASPNETHTTPFORMATTING\n[assembly: AssemblyFileVersion(\"6.0.0.0\")] // ASPNETHTTPFORMATTING\n#endif\n#elif ASPNETMVC\n#if !BUILD_GENERATED_VERSION\n[assembly: AssemblyVersion(\"5.3.0.0\")] // ASPNETMVC\n[assembly: AssemblyFileVersion(\"5.3.0.0\")] // ASPNETMVC\n#endif\n[assembly: AssemblyProduct(\"Microsoft ASP.NET MVC\")]\n#elif ASPNETWEBPAGES\n#if !BUILD_GENERATED_VERSION\n[assembly: AssemblyVersion(\"3.0.0.0\")] // ASPNETWEBPAGES\n[assembly: AssemblyFileVersion(\"3.0.0.0\")] // ASPNETWEBPAGES\n#endif\n[assembly: AssemblyProduct(\"Microsoft ASP.NET Web Pages\")]\n#elif ASPNETFACEBOOK\n#if !BUILD_GENERATED_VERSION\n[assembly: AssemblyVersion(\"1.1.0.0\")] // ASPNETFACEBOOK\n[assembly: AssemblyFileVersion(\"1.1.0.0\")] // ASPNETFACEBOOK\n#endif\n[assembly: AssemblyProduct(\"Microsoft ASP.NET Facebook\")]\n#else\n#error Runtime projects must define ASPNETMVC, ASPNETWEBPAGES or ASPNETFACEBOOK\n#endif\n"
  },
  {
    "path": "src/CommonAssemblyInfo.vb",
    "content": "﻿' Copyright (c) .NET Foundation. All rights reserved.\n' Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nImports System\nImports System.Reflection\nImports System.Resources\nImports System.Runtime.InteropServices\n\n<Assembly: AssemblyCompany(\".NET Foundation\")>\n<Assembly: AssemblyCopyright(\"Copyright © .NET Foundation. All rights reserved.\")>\n<Assembly: AssemblyConfiguration(\"\")>\n<Assembly: AssemblyTrademark(\"\")>\n<Assembly: ComVisible(False)>\n<Assembly: CLSCompliant(True)>\n\n<Assembly: NeutralResourcesLanguage(\"en-US\")>\n\n' ===========================================================================\n' DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT.\n' Version numbers are automatically generated based on regular expressions.\n' ===========================================================================\n\n<Assembly: AssemblyVersion(\"5.3.0.0\")>   'ASPNETMVC\n<Assembly: AssemblyFileVersion(\"5.3.0.0\")>   'ASPNETMVC\n<Assembly: AssemblyProduct(\"Microsoft ASP.NET MVC\")>"
  },
  {
    "path": "src/CommonResources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.239\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace Microsoft.Internal.Web.Utils {\n    using System;\n    using System.Linq;\n    \n    \n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class CommonResources {\n        \n        private static global::System.Resources.ResourceManager resourceMan;\n        \n        private static global::System.Globalization.CultureInfo resourceCulture;\n        \n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal CommonResources() {\n        }\n        \n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n                    // Find the CommonResources.resources file's full resource name in this assembly\n                    string commonResourcesName = global::System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames().Where(s => s.EndsWith(\"CommonResources.resources\", StringComparison.OrdinalIgnoreCase)).Single();\n\n                    // Trim off the \".resources\"\n                    commonResourcesName = commonResourcesName.Substring(0, commonResourcesName.Length - 10);\n\n                    // Load the resource manager\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(commonResourcesName, typeof(CommonResources).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n        \n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Value cannot be null or an empty string..\n        /// </summary>\n        internal static string Argument_Cannot_Be_Null_Or_Empty {\n            get {\n                return ResourceManager.GetString(\"Argument_Cannot_Be_Null_Or_Empty\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Value must be between {0} and {1}..\n        /// </summary>\n        internal static string Argument_Must_Be_Between {\n            get {\n                return ResourceManager.GetString(\"Argument_Must_Be_Between\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Value must be a value from the &quot;{0}&quot; enumeration..\n        /// </summary>\n        internal static string Argument_Must_Be_Enum_Member {\n            get {\n                return ResourceManager.GetString(\"Argument_Must_Be_Enum_Member\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Value must be greater than {0}..\n        /// </summary>\n        internal static string Argument_Must_Be_GreaterThan {\n            get {\n                return ResourceManager.GetString(\"Argument_Must_Be_GreaterThan\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Value must be greater than or equal to {0}..\n        /// </summary>\n        internal static string Argument_Must_Be_GreaterThanOrEqualTo {\n            get {\n                return ResourceManager.GetString(\"Argument_Must_Be_GreaterThanOrEqualTo\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Value must be less than {0}..\n        /// </summary>\n        internal static string Argument_Must_Be_LessThan {\n            get {\n                return ResourceManager.GetString(\"Argument_Must_Be_LessThan\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Value must be less than or equal to {0}..\n        /// </summary>\n        internal static string Argument_Must_Be_LessThanOrEqualTo {\n            get {\n                return ResourceManager.GetString(\"Argument_Must_Be_LessThanOrEqualTo\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Value cannot be an empty string. It must either be null or a non-empty string..\n        /// </summary>\n        internal static string Argument_Must_Be_Null_Or_Non_Empty {\n            get {\n                return ResourceManager.GetString(\"Argument_Must_Be_Null_Or_Non_Empty\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/CommonResources.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"Argument_Cannot_Be_Null_Or_Empty\" xml:space=\"preserve\">\n    <value>Value cannot be null or an empty string.</value>\n  </data>\n  <data name=\"Argument_Must_Be_Between\" xml:space=\"preserve\">\n    <value>Value must be between {0} and {1}.</value>\n  </data>\n  <data name=\"Argument_Must_Be_Enum_Member\" xml:space=\"preserve\">\n    <value>Value must be a value from the \"{0}\" enumeration.</value>\n  </data>\n  <data name=\"Argument_Must_Be_GreaterThan\" xml:space=\"preserve\">\n    <value>Value must be greater than {0}.</value>\n  </data>\n  <data name=\"Argument_Must_Be_GreaterThanOrEqualTo\" xml:space=\"preserve\">\n    <value>Value must be greater than or equal to {0}.</value>\n  </data>\n  <data name=\"Argument_Must_Be_LessThan\" xml:space=\"preserve\">\n    <value>Value must be less than {0}.</value>\n  </data>\n  <data name=\"Argument_Must_Be_LessThanOrEqualTo\" xml:space=\"preserve\">\n    <value>Value must be less than or equal to {0}.</value>\n  </data>\n  <data name=\"Argument_Must_Be_Null_Or_Non_Empty\" xml:space=\"preserve\">\n    <value>Value cannot be an empty string. It must either be null or a non-empty string.</value>\n  </data>\n</root>"
  },
  {
    "path": "src/Directory.Build.props",
    "content": "<Project>\n  <Import Project=\"..\\Directory.Build.props\" />\n\n  <PropertyGroup>\n    <IsPackable>true</IsPackable>\n    <IsTestProject>false</IsTestProject>\n    <TargetFrameworkVersion Condition=\" !$(MSBuildProjectName.StartsWith('System.Net.Http.Formatting.ns')) \">v4.5</TargetFrameworkVersion>\n  </PropertyGroup>\n</Project>\n"
  },
  {
    "path": "src/GlobalSuppressions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA2210:AssembliesShouldHaveValidStrongNames\", Justification = \"Assembly is delay-signed\")]\n"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/Authorization/FacebookAuthorizeFilter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq;\nusing System.Web;\nusing System.Web.Mvc;\nusing Facebook;\nusing Microsoft.AspNet.Facebook.Client;\n\nnamespace Microsoft.AspNet.Facebook.Authorization\n{\n    /// <summary>\n    /// Authorization filter that verifies the signed requests and permissions from Facebook.\n    /// </summary>\n    public class FacebookAuthorizeFilter : IAuthorizationFilter\n    {\n        private static readonly Uri FacebookUri = new Uri(\"https://www.facebook.com/\");\n        private static readonly Uri DefaultAuthorizationRedirectUrl = FacebookUri;\n        private static readonly Uri DefaultCannotCreateCookiesRedirectPath = FacebookUri;\n        // Facebook Missing Permissions, shortened version to not add excessively long query string parameters to the url.\n        private const string MissingPermissionsQueryName = \"__fb_mps\";\n\n        private FacebookConfiguration _config;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"FacebookAuthorizeFilter\" /> class.\n        /// </summary>\n        /// <param name=\"config\">The <see cref=\"FacebookConfiguration\"/>.</param>\n        public FacebookAuthorizeFilter(FacebookConfiguration config)\n        {\n            if (config == null)\n            {\n                throw new ArgumentNullException(\"config\");\n            }\n\n            _config = config;\n        }\n\n        /// <summary>\n        /// Called when authorization is required.\n        /// </summary>\n        /// <param name=\"filterContext\">The filter context.</param>\n        [SuppressMessage(\"Microsoft.Maintainability\", \"CA1506:AvoidExcessiveClassCoupling\", Justification = \"Type references are needed for authorization\")]\n        public virtual void OnAuthorization(AuthorizationContext filterContext)\n        {\n            if (filterContext == null)\n            {\n                throw new ArgumentNullException(\"filterContext\");\n            }\n\n            IEnumerable<FacebookAuthorizeAttribute> authorizeAttributes = filterContext.ActionDescriptor\n                .GetCustomAttributes(typeof(FacebookAuthorizeAttribute), inherit: true)\n                .Union(filterContext.ActionDescriptor.ControllerDescriptor\n                    .GetCustomAttributes(typeof(FacebookAuthorizeAttribute), inherit: true))\n                .OfType<FacebookAuthorizeAttribute>();\n            if (!authorizeAttributes.Any())\n            {\n                return;\n            }\n\n            FacebookClient client = _config.ClientProvider.CreateClient();\n            HttpRequestBase request = filterContext.HttpContext.Request;\n            dynamic signedRequest = FacebookRequestHelpers.GetSignedRequest(\n                filterContext.HttpContext,\n                rawSignedRequest =>\n                {\n                    return client.ParseSignedRequest(rawSignedRequest);\n                });\n            string userId = null;\n            string accessToken = null;\n            if (signedRequest != null)\n            {\n                userId = signedRequest.user_id;\n                accessToken = signedRequest.oauth_token;\n            }\n\n            NameValueCollection parsedQueries = HttpUtility.ParseQueryString(request.Url.Query);\n            HashSet<string> requiredPermissions = PermissionHelper.GetRequiredPermissions(authorizeAttributes);\n\n            bool handleError = !String.IsNullOrEmpty(parsedQueries[\"error\"]);\n\n            // This must occur AFTER the handleError calculation because it modifies the parsed queries.\n            string redirectUrl = GetRedirectUrl(request, parsedQueries);\n\n            // Check if there was an error and we should handle it.\n            if (handleError)\n            {\n                Uri errorUrl;\n\n                if (String.IsNullOrEmpty(_config.AuthorizationRedirectPath))\n                {\n                    errorUrl = DefaultAuthorizationRedirectUrl;\n                }\n                else\n                {\n                    errorUrl = GetErroredAuthorizeUri(redirectUrl, requiredPermissions);\n                }\n\n                filterContext.Result = CreateRedirectResult(errorUrl);\n\n                // There was an error so short circuit\n                return;\n            }\n\n            FacebookContext facebookContext = new FacebookContext\n            {\n                Client = client,\n                SignedRequest = signedRequest,\n                AccessToken = accessToken,\n                UserId = userId,\n                Configuration = _config\n            };\n\n            PermissionContext permissionContext = new PermissionContext\n            {\n                FacebookContext = facebookContext,\n                FilterContext = filterContext,\n                RequiredPermissions = requiredPermissions,\n            };\n\n            // Check if we need to prompt for default permissions.\n            if (signedRequest == null || String.IsNullOrEmpty(userId) || String.IsNullOrEmpty(accessToken))\n            {\n                PromptDefaultPermissions(permissionContext, redirectUrl);\n            }\n            else if (requiredPermissions.Any())\n            {\n                PermissionsStatus currentPermissionsStatus = _config.PermissionService.GetUserPermissionsStatus(userId, accessToken);\n                // Instead of performing another request to gather \"granted\" permissions just parse the status\n                IEnumerable<string> currentPermissions = PermissionHelper.GetGrantedPermissions(currentPermissionsStatus);\n                IEnumerable<string> missingPermissions = requiredPermissions.Except(currentPermissions);\n\n                // If we have missing permissions than we need to present a prompt or redirect to an error \n                // page if there's an error.\n                if (missingPermissions.Any())\n                {\n                    permissionContext.MissingPermissions = missingPermissions;\n                    permissionContext.DeclinedPermissions = PermissionHelper.GetDeclinedPermissions(currentPermissionsStatus);\n                    permissionContext.SkippedPermissions = PermissionHelper.GetSkippedPermissions(\n                        filterContext.HttpContext.Request,\n                        missingPermissions,\n                        permissionContext.DeclinedPermissions);\n\n                    // Add a query string parameter that enables us to identify if we've already prompted for missing permissions\n                    // and therefore can detect cookies.\n                    AddCookieVerificationQuery(parsedQueries);\n                    // Rebuild the redirect Url so it contains the new query string parameter.\n                    redirectUrl = GetRedirectUrl(request, parsedQueries);\n\n                    PromptMissingPermissions(permissionContext, redirectUrl);\n                }\n            }\n        }\n\n        /// <summary>\n        /// Adds a query string parameter to a <see cref=\"NameValueCollection\"/> that enables a \n        /// <see cref=\"FacebookAuthorizeFilter\"/> to detect when cookies are unavailable and then trigger the \n        /// <see cref=\"OnCannotCreateCookies\"/> hook.\n        /// </summary>\n        /// <param name=\"queries\">List of query parameters that are used to create a url.</param>\n        protected static void AddCookieVerificationQuery(NameValueCollection queries)\n        {\n            // Add a query string parameter that enables us to identify if we've already prompted for missing permissions\n            queries.Add(MissingPermissionsQueryName, \"true\");\n        }\n\n        /// <summary>\n        /// Called when authorization fails and need to create a redirect result.\n        /// </summary>\n        /// <param name=\"redirectUrl\">The redirect URL.</param>\n        /// <returns>The <see cref=\"ActionResult\"/>.</returns>\n        public virtual JavaScriptRedirectResult CreateRedirectResult(Uri redirectUrl)\n        {\n            if (redirectUrl == null)\n            {\n                throw new ArgumentNullException(\"redirectUrl\");\n            }\n\n            return new JavaScriptRedirectResult(redirectUrl);\n        }\n\n        /// <summary>\n        /// Returns an <see cref=\"ActionResult\"/> that indicates we want to show a permission prompt.  Should only be used as a\n        /// return value within the <see cref=\"OnPermissionPrompt\"/> and <see cref=\"OnDeniedPermissionPrompt\"/> methods.\n        /// </summary>\n        /// <returns>An <see cref=\"ActionResult\"/> that indicates that we want to show a permission prompt.</returns>\n        protected ShowPromptResult ShowPrompt(PermissionContext context)\n        {\n            FacebookClient client = context.FacebookContext.Client;\n            Uri navigationUrl = client.GetLoginUrl(context.RedirectUrl,\n                                                   _config.AppId,\n                                                   permissions: String.Join(\",\", context.RequiredPermissions));\n\n            return new ShowPromptResult(navigationUrl);\n        }\n\n        /// <summary>\n        /// Invoked during <see cref=\"OnAuthorization\"/> after determining that cookies cannot be created. Default behavior\n        /// redirects to a no cookies error page.\n        /// </summary>\n        /// <param name=\"context\">Provides access to permission information associated with the user.</param>\n        protected virtual void OnCannotCreateCookies(PermissionContext context)\n        {\n            Uri redirectPath;\n\n            if (String.IsNullOrEmpty(_config.CannotCreateCookieRedirectPath))\n            {\n                redirectPath = DefaultCannotCreateCookiesRedirectPath;\n            }\n            else\n            {\n                redirectPath = GetCannotCreateCookiesUri();\n            }\n\n            context.Result = CreateRedirectResult(redirectPath);\n        }\n\n        /// <summary>\n        /// Invoked during <see cref=\"OnAuthorization\"/> when a prompt requests permissions that were skipped or revoked.\n        /// Set the <paramref name=\"context\"/>'s Result property to modify login flow.\n        /// </summary>\n        /// <param name=\"context\">Provides access to permission information associated with the user.</param>\n        protected virtual void OnDeniedPermissionPrompt(PermissionContext context)\n        {\n        }\n\n        /// <summary>\n        /// Invoked during <see cref=\"OnAuthorization\"/> prior to a permission prompt that is requesting permissions that have\n        /// not been requested before. Set the <paramref name=\"context\"/>'s Result property to modify login flow.\n        /// </summary>\n        /// <param name=\"context\">Provides access to permission information associated with the user.</param>\n        protected virtual void OnPermissionPrompt(PermissionContext context)\n        {\n            context.Result = ShowPrompt(context);\n        }\n\n        private Uri GetErroredAuthorizeUri(string originUrl, HashSet<string> requiredPermissions)\n        {\n            if (requiredPermissions == null)\n            {\n                throw new ArgumentNullException(\"requiredPermissions\");\n            }\n\n            string requiredPermissionString = String.Join(\",\", requiredPermissions);\n            UriBuilder authorizationUrlBuilder = new UriBuilder(new Uri(_config.AppUrl));\n            authorizationUrlBuilder.Path += _config.AuthorizationRedirectPath.Substring(1);\n            authorizationUrlBuilder.Query = String.Format(CultureInfo.InvariantCulture,\n                \"originUrl={0}&permissions={1}\",\n                HttpUtility.UrlEncode(originUrl),\n                HttpUtility.UrlEncode(requiredPermissionString));\n\n            return authorizationUrlBuilder.Uri;\n        }\n\n        private Uri GetCannotCreateCookiesUri()\n        {\n            UriBuilder noCookiesUrlBuilder = new UriBuilder(new Uri(_config.AppUrl));\n            noCookiesUrlBuilder.Path += _config.CannotCreateCookieRedirectPath.Substring(1);\n\n            return noCookiesUrlBuilder.Uri;\n        }\n\n        private string GetRedirectUrl(HttpRequestBase request)\n        {\n            NameValueCollection queryNameValuePair = HttpUtility.ParseQueryString(request.Url.Query);\n            return GetRedirectUrl(request, queryNameValuePair);\n        }\n\n        private string GetRedirectUrl(HttpRequestBase request, NameValueCollection queryNameValuePair)\n        {\n            // Don't propagate query strings added by Facebook OAuth Dialog\n            queryNameValuePair.Remove(\"code\");\n            queryNameValuePair.Remove(\"error\");\n            queryNameValuePair.Remove(\"error_reason\");\n            queryNameValuePair.Remove(\"error_description\");\n\n            string redirectUrl = String.Format(\n                CultureInfo.InvariantCulture,\n                \"{0}/{1}\",\n                _config.AppUrl.TrimEnd('/'),\n                request.AppRelativeCurrentExecutionFilePath.TrimStart('~', '/'));\n\n            string query = queryNameValuePair.ToString();\n            if (!String.IsNullOrEmpty(query))\n            {\n                redirectUrl += \"?\" + query;\n            }\n\n            return redirectUrl;\n        }\n\n        private void PromptDefaultPermissions(PermissionContext permissionContext, string redirectUrl)\n        {\n            FacebookClient client = permissionContext.FacebookContext.Client;\n            // Cannot obtain user information from signed_request, redirect to Facebook OAuth dialog.\n            Uri navigationUrl = client.GetLoginUrl(redirectUrl,\n                                                   _config.AppId,\n                                                   permissions: null);\n\n            permissionContext.FilterContext.Result = CreateRedirectResult(navigationUrl);\n        }\n\n        private void PromptMissingPermissions(PermissionContext permissionContext, string redirectUrl)\n        {\n            AuthorizationContext filterContext = permissionContext.FilterContext;\n            HashSet<string> requiredPermissions = permissionContext.RequiredPermissions;\n\n            // If there were no errors it means that we will be prompted with a permission prompt.\n            // Therefore, invoke the permission prompt hooks and navigate to the prompt.\n\n            IEnumerable<string> declinedPermissions = permissionContext.DeclinedPermissions;\n            IEnumerable<string> skippedPermissions = permissionContext.SkippedPermissions;\n            IEnumerable<string> missingPermissions = permissionContext.MissingPermissions;\n\n            // Declined permissions and skipped permissions can persist through multiple pages.  So we need to cross check\n            // them against the current pages permissions, this will determine if we should invoke the denied permission hook.\n            bool deniedPermissions = missingPermissions.Where(\n                permission => declinedPermissions.Contains(permission) ||\n                              skippedPermissions.Contains(permission)).Any();\n\n            permissionContext.RedirectUrl = redirectUrl;\n\n            // See if our persisted permissions cookie doesn't exist and if we've had missing permissions before.\n            // Essentially this checks to see if we've tried to persist permissions before and were unsuccessful due to an\n            // inability to create cookies.\n            if (!PermissionHelper.RequestedPermissionsCookieExists(filterContext.HttpContext.Request) &&\n                filterContext.HttpContext.Request.QueryString.Get(MissingPermissionsQueryName) != null)\n            {\n                OnCannotCreateCookies(permissionContext);\n            }\n            else\n            {\n                // The DeniedPermissionPromptHook will only be invoked if we detect there are denied permissions.\n                // It is attempted instead of the permission hook to allow app creators to handle situations when a user\n                // skip's or revokes previously prompted permissions. Ex: redirect to a different page.\n                if (deniedPermissions)\n                {\n                    OnDeniedPermissionPrompt(permissionContext);\n                }\n                else\n                {\n                    OnPermissionPrompt(permissionContext);\n                }\n\n                // We persist the requested permissions in a cookie to know if a permission was denied in any way.\n                // The persisted data allows us to detect skipping of permissions.\n                PermissionHelper.PersistRequestedPermissions(filterContext, requiredPermissions);\n            }\n\n            filterContext.Result = permissionContext.Result;\n        }\n    }\n}"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/Client/FacebookClientExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Facebook;\n\nnamespace Microsoft.AspNet.Facebook.Client\n{\n    /// <summary>\n    /// Extension methods for <see cref=\"FacebookClient\"/>.\n    /// </summary>\n    public static class FacebookClientExtensions\n    {\n        private const string PermissionsEndPoint = \"me/permissions\";\n\n        /// <summary>\n        /// Gets the Facebook object located at a given path.\n        /// </summary>\n        /// <param name=\"client\">The client.</param>\n        /// <param name=\"objectPath\">The object path.</param>\n        /// <returns>A Facebook object.</returns>\n        public static Task<object> GetFacebookObjectAsync(this FacebookClient client, string objectPath)\n        {\n            return GetFacebookObjectAsync<object>(client, objectPath);\n        }\n\n        /// <summary>\n        /// Gets the Facebook object located at a given path.\n        /// </summary>\n        /// <typeparam name=\"TFacebookObject\">The type of the Facebook object.</typeparam>\n        /// <param name=\"client\">The client.</param>\n        /// <param name=\"objectPath\">The object path.</param>\n        /// <returns>A Facebook object.</returns>\n        public static Task<TFacebookObject> GetFacebookObjectAsync<TFacebookObject>(this FacebookClient client, string objectPath) where TFacebookObject : class\n        {\n            if (client == null)\n            {\n                throw new ArgumentNullException(\"client\");\n            }\n            if (objectPath == null)\n            {\n                throw new ArgumentNullException(\"objectPath\");\n            }\n\n            string path = objectPath + FacebookQueryHelper.GetFields(typeof(TFacebookObject));\n            return client.GetTaskAsync<TFacebookObject>(path);\n        }\n\n        /// <summary>\n        /// Gets the current user information.\n        /// </summary>\n        /// <param name=\"client\">The client.</param>\n        /// <returns>The current user.</returns>\n        public static Task<object> GetCurrentUserAsync(this FacebookClient client)\n        {\n            return GetCurrentUserAsync<object>(client);\n        }\n\n        /// <summary>\n        /// Gets the current user information.\n        /// </summary>\n        /// <typeparam name=\"TUser\">The type of the user.</typeparam>\n        /// <param name=\"client\">The client.</param>\n        /// <returns>The current user.</returns>\n        public static Task<TUser> GetCurrentUserAsync<TUser>(this FacebookClient client) where TUser : class\n        {\n            return GetFacebookObjectAsync<TUser>(client, \"me\");\n        }\n\n        /// <summary>\n        /// Gets the current user friends information.\n        /// </summary>\n        /// <param name=\"client\">The client.</param>\n        /// <returns>A collection of friends.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"Using tasks\")]\n        public static Task<IList<object>> GetCurrentUserFriendsAsync(this FacebookClient client)\n        {\n            return GetCurrentUserFriendsAsync<object>(client);\n        }\n\n        /// <summary>\n        /// Gets the current user friends information.\n        /// </summary>\n        /// <typeparam name=\"TUserFriend\">The type of the user friend.</typeparam>\n        /// <param name=\"client\">The client.</param>\n        /// <returns>A collection of friends.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"Using tasks\")]\n        public static async Task<IList<TUserFriend>> GetCurrentUserFriendsAsync<TUserFriend>(this FacebookClient client) where TUserFriend : class\n        {\n            FacebookGroupConnection<TUserFriend> friends = await GetFacebookObjectAsync<FacebookGroupConnection<TUserFriend>>(client, \"me/friends\");\n            return friends != null ?\n                friends.Data :\n                new TUserFriend[0];\n        }\n\n        /// <summary>\n        /// Gets the permissions granted by the current user.\n        /// </summary>\n        /// <param name=\"client\">The client.</param>\n        /// <returns>A collection of permissions.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"Using tasks\")]\n        public static async Task<IList<string>> GetCurrentUserPermissionsAsync(this FacebookClient client)\n        {\n            FacebookGroupConnection<IDictionary<string, string>> permissionResults = \n                await client.GetTaskAsync<FacebookGroupConnection<IDictionary<string, string>>>(PermissionsEndPoint);\n            PermissionsStatus permissionsStatus = new PermissionsStatus(permissionResults.Data);\n\n            return PermissionHelper.GetGrantedPermissions(permissionsStatus).ToList();\n        }\n\n        /// <summary>\n        /// Gets the current user statuses.\n        /// </summary>\n        /// <typeparam name=\"TStatus\">The type of the status.</typeparam>\n        /// <param name=\"client\">The client.</param>\n        /// <returns>A collection of statuses.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"Using tasks\")]\n        public static async Task<IList<TStatus>> GetCurrentUserStatusesAsync<TStatus>(this FacebookClient client) where TStatus : class\n        {\n            FacebookGroupConnection<TStatus> statuses = await GetFacebookObjectAsync<FacebookGroupConnection<TStatus>>(client, \"me/statuses\");\n            return statuses != null ?\n                statuses.Data :\n                new TStatus[0];\n        }\n\n        /// <summary>\n        /// Gets the current user photos.\n        /// </summary>\n        /// <typeparam name=\"TPhotos\">The type of the photo.</typeparam>\n        /// <param name=\"client\">The client.</param>\n        /// <returns>A collection of user photos.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"Using tasks\")]\n        public static async Task<IList<TPhotos>> GetCurrentUserPhotosAsync<TPhotos>(this FacebookClient client) where TPhotos : class\n        {\n            FacebookGroupConnection<TPhotos> photos = await GetFacebookObjectAsync<FacebookGroupConnection<TPhotos>>(client, \"me/photos\");\n            return photos != null ?\n                photos.Data :\n                new TPhotos[0];\n        }\n\n        internal static Uri GetLoginUrl(this FacebookClient client, string redirectUrl, string appId, string permissions)\n        {\n            if (String.IsNullOrEmpty(redirectUrl))\n            {\n                throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, \"redirectUrl\");\n            }\n            if (String.IsNullOrEmpty(appId))\n            {\n                throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, \"appId\");\n            }\n\n            Dictionary<string, object> loginUrlParameters = new Dictionary<string, object>();\n            loginUrlParameters[\"redirect_uri\"] = redirectUrl;\n            loginUrlParameters[\"client_id\"] = appId;\n            if (!String.IsNullOrEmpty(permissions))\n            {\n                loginUrlParameters[\"scope\"] = permissions;\n            }\n\n            return client.GetLoginUrl(loginUrlParameters);\n        }\n\n        internal static IList<IDictionary<string, string>> GetCurrentUserPermissionsStatus(this FacebookClient client)\n        {\n            FacebookGroupConnection<IDictionary<string, string>> permissionResults = \n                client.Get<FacebookGroupConnection<IDictionary<string, string>>>(PermissionsEndPoint);\n\n            return permissionResults.Data;\n        }\n    }\n}"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/Client/FacebookQueryHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Reflection;\nusing System.Text;\nusing Newtonsoft.Json;\n\nnamespace Microsoft.AspNet.Facebook.Client\n{\n    /// <summary>\n    /// Helper for constructing Facebook Graph API queries.\n    /// </summary>\n    public static class FacebookQueryHelper\n    {\n        /// <summary>\n        /// Gets the appropriate \"fields\" query parameter for the Facebook Graph API based on the public properties of the model type.\n        /// </summary>\n        /// <param name=\"modelType\">Type of the model.</param>\n        /// <returns>The \"fields\" query parameter.</returns>\n        public static string GetFields(Type modelType)\n        {\n            IList<string> fieldNames = GetFieldNames(modelType, typesVisited: new HashSet<Type>());\n            if (fieldNames.Count > 0 && modelType != typeof(object))\n            {\n                return \"?fields=\" + String.Join(\",\", fieldNames);\n            }\n\n            return String.Empty;\n        }\n\n        private static string GetConnectionFields(Type modelType, HashSet<Type> typesVisited)\n        {\n            if (typesVisited.Contains(modelType))\n            {\n                throw new InvalidOperationException(Resources.CircularReferenceNotSupported);\n            }\n\n            IList<string> fieldNames = GetFieldNames(modelType, typesVisited);\n            if (fieldNames.Count > 0 && modelType != typeof(object))\n            {\n                return \".fields(\" + String.Join(\",\", fieldNames) + \")\";\n            }\n\n            return String.Empty;\n        }\n\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1308:NormalizeStringsToUppercase\", Justification = \"Lowercase is intended for field names.\")]\n        private static IList<string> GetFieldNames(Type modelType, HashSet<Type> typesVisited)\n        {\n            Type connectionType;\n            if (TryUnwrapConnectionType(modelType, out connectionType))\n            {\n                modelType = connectionType;\n            }\n\n            PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);\n            List<string> facebookFields = new List<string>();\n            foreach (PropertyInfo property in properties)\n            {\n                string propertyName = property.Name;\n                AttributeCollection attributes =\n                   TypeDescriptor.GetProperties(modelType)[propertyName].Attributes;\n\n                JsonIgnoreAttribute jsonIgnoreAttribute =\n                   (JsonIgnoreAttribute)attributes[typeof(JsonIgnoreAttribute)];\n\n                if (jsonIgnoreAttribute == null)\n                {\n                    JsonPropertyAttribute jsonPropertyAttribute =\n                        (JsonPropertyAttribute)attributes[typeof(JsonPropertyAttribute)];\n                    FacebookFieldModifierAttribute modifierAttribute =\n                        (FacebookFieldModifierAttribute)attributes[typeof(FacebookFieldModifierAttribute)];\n\n                    StringBuilder fieldName = new StringBuilder(\n                        jsonPropertyAttribute != null ?\n                            jsonPropertyAttribute.PropertyName :\n                            propertyName);\n\n                    if (modifierAttribute != null)\n                    {\n                        fieldName.AppendFormat(CultureInfo.InvariantCulture, \".{0}\", modifierAttribute.FieldModifier);\n                    }\n\n                    Type propertyType = property.PropertyType;\n                    if (TryUnwrapConnectionType(propertyType, out connectionType))\n                    {\n                        typesVisited.Add(property.DeclaringType);\n                        fieldName.Append(GetConnectionFields(connectionType, typesVisited));\n                    }\n\n                    facebookFields.Add(fieldName.ToString().ToLowerInvariant());\n                }\n            }\n\n            return facebookFields;\n        }\n\n        private static bool TryUnwrapConnectionType(Type modelType, out Type connectionType)\n        {\n            if (modelType.IsGenericType)\n            {\n                Type genericTypeDefinition = modelType.GetGenericTypeDefinition();\n                if (genericTypeDefinition == typeof(FacebookConnection<>) ||\n                    genericTypeDefinition == typeof(FacebookGroupConnection<>))\n                {\n                    Type genericArgumentType = modelType.GetGenericArguments()[0];\n                    connectionType = genericArgumentType;\n                    return true;\n                }\n            }\n            connectionType = null;\n            return false;\n        }\n    }\n}"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/Client/FacebookRequestHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web;\n\nnamespace Microsoft.AspNet.Facebook.Client\n{\n    internal static class FacebookRequestHelpers\n    {\n        private const string SignedRequestKey = \"signed_request\";\n        private const string ParsedSignedRequestKey = \"parsed_signed_request\";\n\n        public static dynamic GetSignedRequest(HttpContextBase context, Func<string, object> parseSignedRequest)\n        {\n            if (context.Items.Contains(ParsedSignedRequestKey))\n            {\n                return context.Items[ParsedSignedRequestKey];\n            }\n\n            string rawSignedRequest = context.Request.Form[SignedRequestKey] ?? context.Request.QueryString[SignedRequestKey];\n            object signedRequest = null;\n            if (!String.IsNullOrEmpty(rawSignedRequest))\n            {\n                signedRequest = parseSignedRequest(rawSignedRequest);\n                context.Items.Add(ParsedSignedRequestKey, signedRequest);\n            }\n            return signedRequest;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/FacebookAppSettingKeys.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.AspNet.Facebook\n{\n    internal static class FacebookAppSettingKeys\n    {\n        public static readonly string DisableAuthenticationModule = \"Facebook:DisableAuthenticationModule\";\n        public static readonly string AppId = \"Facebook:AppId\";\n        public static readonly string AppSecret = \"Facebook:AppSecret\";\n        public static readonly string AppNamespace = \"Facebook:AppNamespace\";\n        public static readonly string AppUrl = \"Facebook:AppUrl\";\n        public static readonly string AuthorizationRedirectPath = \"Facebook:AuthorizationRedirectPath\";\n        public static readonly string CannotCreateCookiesRedirectPath = \"Facebook:CannotCreateCookiesRedirectPath\";\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/FacebookAuthenticationModule.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Security.Claims;\nusing System.Threading;\nusing System.Web;\nusing Facebook;\nusing Microsoft.AspNet.Facebook.Client;\n\nnamespace Microsoft.AspNet.Facebook\n{\n    internal sealed class FacebookAuthenticationModule : IHttpModule\n    {\n        public void Init(HttpApplication context)\n        {\n            context.AuthenticateRequest += (sender, e) =>\n            {\n                HttpContext httpContext = ((HttpApplication)sender).Context;\n\n                dynamic signedRequest = FacebookRequestHelpers.GetSignedRequest(\n                    new HttpContextWrapper(httpContext),\n                    rawSignedRequest =>\n                    {\n                        FacebookConfiguration config = GlobalFacebookConfiguration.Configuration;\n                        FacebookClient client = config.ClientProvider.CreateClient();\n                        return client.ParseSignedRequest(rawSignedRequest);\n                    });\n\n                if (signedRequest != null)\n                {\n                    string userId = signedRequest.user_id;\n                    if (!String.IsNullOrEmpty(userId))\n                    {\n                        ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, userId) }));\n                        Thread.CurrentPrincipal = principal;\n                        httpContext.User = principal;\n                    }\n                }\n            };\n        }\n\n        public void Dispose()\n        {\n        }\n    }\n}"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/FacebookAuthorizeAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.ObjectModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq;\n\nnamespace Microsoft.AspNet.Facebook\n{\n    /// <summary>\n    /// Restricts the access to requests with valid Facebook signed request parameter and to users that have the required permissions.\n    /// This attribute can be declared on a controller, an action or both.\n    /// </summary>\n    [SuppressMessage(\"Microsoft.Design\", \"CA1019:DefineAccessorsForAttributeArguments\", Justification = \"The attribute argument is already defined as a ReadOnlyCollection.\")]\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\n    public sealed class FacebookAuthorizeAttribute : Attribute\n    {\n        private ReadOnlyCollection<string> _permissions;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"FacebookAuthorizeAttribute\" /> class without requiring permissions.\n        /// </summary>\n        public FacebookAuthorizeAttribute()\n            : this(new string[0])\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"FacebookAuthorizeAttribute\" /> class requiring permissions.\n        /// </summary>\n        /// <param name=\"permissions\">The permissions.</param>\n        public FacebookAuthorizeAttribute(params string[] permissions)\n        {\n            if (permissions == null)\n            {\n                throw new ArgumentNullException(\"permissions\");\n            }\n\n            foreach (string permission in permissions)\n            {\n                if (permission.Contains(','))\n                {\n                    throw new ArgumentException(\n                        String.Format(\n                            CultureInfo.CurrentCulture,\n                            Resources.PermissionStringShouldNotContainComma,\n                            permission),\n                            \"permissions\");\n                }\n            }\n\n            _permissions = new ReadOnlyCollection<string>(permissions);\n        }\n\n        /// <summary>\n        /// Gets the required permissions.\n        /// </summary>\n        public ReadOnlyCollection<string> Permissions\n        {\n            get\n            {\n                return _permissions;\n            }\n        }\n    }\n}"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/FacebookConfiguration.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Concurrent;\nusing System.Configuration;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing Microsoft.AspNet.Facebook.Providers;\n\nnamespace Microsoft.AspNet.Facebook\n{\n    /// <summary>\n    /// Configuration for the Facebook application.\n    /// </summary>\n    public class FacebookConfiguration\n    {\n        private const string FacebookAppBaseUrl = \"https://apps.facebook.com\";\n        private readonly ConcurrentDictionary<object, object> _properties = new ConcurrentDictionary<object, object>();\n        private string _appUrl;\n        private string _authorizationRedirectPath;\n        private string _cannotCreateCookieRedirectPath;\n\n        /// <summary>\n        /// Gets or sets the App ID.\n        /// </summary>\n        public string AppId { get; set; }\n\n        /// <summary>\n        /// Gets or sets the App Secret.\n        /// </summary>\n        public string AppSecret { get; set; }\n\n        /// <summary>\n        /// Gets or sets the App Namespace.\n        /// </summary>\n        public string AppNamespace { get; set; }\n\n        /// <summary>\n        /// Gets or sets the URL path that the <see cref=\"Microsoft.AspNet.Facebook.Authorization.FacebookAuthorizeFilter\"/> will \n        /// redirect to when the user did not grant the required permissions. If value is not set it will result in a redirection\n        /// to Facebook's home page.\n        /// </summary>\n        public string AuthorizationRedirectPath\n        {\n            get\n            {\n                return _authorizationRedirectPath;\n            }\n            set\n            {\n                EnsureRedirectPath(value, \"AuthorizationRedirectPath\");\n                _authorizationRedirectPath = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets the URL path that the <see cref=\"Microsoft.AspNet.Facebook.Authorization.FacebookAuthorizeFilter\"/> will \n        /// redirect to when the we determine that we are unable to create cookies. If value is not set it will result in a \n        /// redirection to Facebook's home page.\n        /// </summary>\n        public string CannotCreateCookieRedirectPath\n        {\n            get\n            {\n                return _cannotCreateCookieRedirectPath;\n            }\n            set\n            {\n                EnsureRedirectPath(value, \"CannotCreateCookieRedirectPath\");\n\n                _cannotCreateCookieRedirectPath = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets the absolute URL for the Facebook App.\n        /// </summary>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1056:UriPropertiesShouldNotBeStrings\", Justification = \"We prefer strings because this is read from appSettings\")]\n        public string AppUrl\n        {\n            get\n            {\n                if (String.IsNullOrEmpty(_appUrl))\n                {\n                    _appUrl = GetAppUrl();\n                }\n                return _appUrl;\n            }\n            set\n            {\n                _appUrl = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets the <see cref=\"IFacebookClientProvider\"/>.\n        /// </summary>\n        public IFacebookClientProvider ClientProvider { get; set; }\n\n        /// <summary>\n        /// Gets or sets the <see cref=\"IFacebookPermissionService\"/>.\n        /// </summary>\n        public IFacebookPermissionService PermissionService { get; set; }\n\n        /// <summary>\n        /// Gets the additional properties associated with this instance.\n        /// </summary>\n        public ConcurrentDictionary<object, object> Properties\n        {\n            get { return _properties; }\n        }\n\n        /// <summary>\n        /// Loads the configuration properties from app settings.\n        /// </summary>\n        /// <remarks>\n        /// It will map the following keys from appSettings to the corresponding properties:\n        /// Facebook:AppId = AppId,\n        /// Facebook:AppSecret = AppSecret,\n        /// Facebook:AppNamespace = AppNamespace,\n        /// Facebook:AppUrl = AppUrl,\n        /// Facebook:AuthorizationRedirectPath = AuthorizationRedirectPath.\n        /// </remarks>\n        public virtual void LoadFromAppSettings()\n        {\n            AppId = ConfigurationManager.AppSettings[FacebookAppSettingKeys.AppId];\n            if (String.IsNullOrEmpty(AppId))\n            {\n                throw new InvalidOperationException(String.Format(\n                    CultureInfo.CurrentCulture,\n                    Resources.AppSettingIsRequired,\n                    FacebookAppSettingKeys.AppId));\n            }\n\n            AppSecret = ConfigurationManager.AppSettings[FacebookAppSettingKeys.AppSecret];\n            if (String.IsNullOrEmpty(AppSecret))\n            {\n                throw new InvalidOperationException(String.Format(\n                    CultureInfo.CurrentCulture,\n                    Resources.AppSettingIsRequired,\n                    FacebookAppSettingKeys.AppSecret));\n            }\n\n            AppNamespace = ConfigurationManager.AppSettings[FacebookAppSettingKeys.AppNamespace];\n            AppUrl = ConfigurationManager.AppSettings[FacebookAppSettingKeys.AppUrl];\n            AuthorizationRedirectPath = ConfigurationManager.AppSettings[FacebookAppSettingKeys.AuthorizationRedirectPath];\n            CannotCreateCookieRedirectPath = \n                ConfigurationManager.AppSettings[FacebookAppSettingKeys.CannotCreateCookiesRedirectPath];\n        }\n\n        private static void EnsureRedirectPath(string value, string redirectParameterName)\n        {\n            // Check for '~/' prefix while allowing null or empty value to be set.\n            if (!String.IsNullOrEmpty(value) && !value.StartsWith(\"~/\", StringComparison.Ordinal))\n            {\n                throw new ArgumentException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        Resources.InvalidRedirectPath,\n                        redirectParameterName),\n                    \"value\");\n            }\n        }\n\n        private string GetAppUrl()\n        {\n            return String.Format(\n                CultureInfo.InvariantCulture,\n                \"{0}/{1}\",\n                FacebookAppBaseUrl,\n                String.IsNullOrEmpty(AppNamespace) ? AppId : AppNamespace);\n        }\n    }\n}"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/FacebookConnection.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.AspNet.Facebook\n{\n    /// <summary>\n    /// Model for the Facebook object connection.\n    /// </summary>\n    /// <typeparam name=\"T\">Type of the connection.</typeparam>\n    public class FacebookConnection<T>\n    {\n        /// <summary>\n        /// Gets or sets the connection data.\n        /// </summary>\n        public T Data { get; set; }\n    }\n}"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/FacebookContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Facebook;\nusing Microsoft.AspNet.Facebook.ModelBinders;\n\nnamespace Microsoft.AspNet.Facebook\n{\n    /// <summary>\n    /// Provides access to Facebook-specific information.\n    /// </summary>\n    [FacebookContextBinderAttribute]\n    public class FacebookContext\n    {\n        /// <summary>\n        /// Gets or sets the parsed signed request.\n        /// </summary>\n        public dynamic SignedRequest { get; set; }\n\n        /// <summary>\n        /// Gets or sets the access token.\n        /// </summary>\n        public string AccessToken { get; set; }\n\n        /// <summary>\n        /// Gets or sets the user ID.\n        /// </summary>\n        public string UserId { get; set; }\n\n        /// <summary>\n        /// Gets or sets the Facebook client.\n        /// </summary>\n        public FacebookClient Client { get; set; }\n\n        /// <summary>\n        /// Gets or sets the <see cref=\"FacebookConfiguration\"/>.\n        /// </summary>\n        public FacebookConfiguration Configuration { get; set; }\n    }\n}"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/FacebookFieldModifierAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\n\nnamespace Microsoft.AspNet.Facebook\n{\n    /// <summary>\n    /// Allows adding field modifiers when querying Facebook Graph API.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]\n    public sealed class FacebookFieldModifierAttribute : Attribute\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"FacebookFieldModifierAttribute\" /> class.\n        /// </summary>\n        /// <param name=\"fieldModifier\">The field modifier.</param>\n        public FacebookFieldModifierAttribute(string fieldModifier)\n        {\n            FieldModifier = fieldModifier;\n        }\n\n        /// <summary>\n        /// Gets the field modifier.\n        /// </summary>\n        public string FieldModifier { get; private set; }\n    }\n}"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/FacebookGroupConnection.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace Microsoft.AspNet.Facebook\n{\n    /// <summary>\n    /// Model for the Facebook object connection when it contains a collection.\n    /// </summary>\n    /// <typeparam name=\"T\">Type of the collection element.</typeparam>\n    public class FacebookGroupConnection<T>\n    {\n        /// <summary>\n        /// Gets or sets the connection data.\n        /// </summary>\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"Needed for JSON deserialization\")]\n        public IList<T> Data { get; set; }\n    }\n}"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/FacebookHtmlHelperExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Web.Mvc.Html;\n\nnamespace Microsoft.AspNet.Facebook\n{\n    /// <summary>\n    /// Facebook-related extension methods for <see cref=\"HtmlHelper\"/>.\n    /// </summary>\n    public static class FacebookHtmlHelperExtensions\n    {\n        /// <summary>\n        /// Returns the signed_request in a hidden input element.\n        /// </summary>\n        /// <param name=\"htmlHelper\">The <see cref=\"HtmlHelper\"/>.</param>\n        /// <returns>The signed_request in a hidden input element.</returns>\n        public static IHtmlString FacebookSignedRequest(this HtmlHelper htmlHelper)\n        {\n            string signedRequest = htmlHelper.ViewContext.HttpContext.Request.Params[\"signed_request\"];\n            if (!String.IsNullOrEmpty(signedRequest))\n            {\n                return htmlHelper.Hidden(\"signed_request\", signedRequest);\n            }\n            return new HtmlString(String.Empty);\n        }\n    }\n}"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/FacebookRedirectContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing Microsoft.AspNet.Facebook.ModelBinders;\n\nnamespace Microsoft.AspNet.Facebook\n{\n    /// <summary>\n    /// Provides access to the data redirected from <see cref=\"Microsoft.AspNet.Facebook.Authorization.FacebookAuthorizeFilter\"/>.\n    /// </summary>\n    [FacebookRedirectContextBinder]\n    public class FacebookRedirectContext\n    {\n        /// <summary>\n        /// Gets or sets the origin URL.\n        /// </summary>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1056:UriPropertiesShouldNotBeStrings\", Justification = \"We prefer strings because this is read from query strings\")]\n        public string OriginUrl { get; set; }\n\n        /// <summary>\n        /// Gets or sets the redirect URL.\n        /// </summary>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1056:UriPropertiesShouldNotBeStrings\", Justification = \"We prefer strings because this is read from query strings\")]\n        public string RedirectUrl { get; set; }\n\n        /// <summary>\n        /// Gets or sets the required permissions specified on <see cref=\"FacebookAuthorizeAttribute\"/>.\n        /// </summary>\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1819:PropertiesShouldNotReturnArrays\", Justification = \"This is a shipped API\")]\n        public string[] RequiredPermissions { get; set; }\n\n        /// <summary>\n        /// Gets or sets the <see cref=\"FacebookConfiguration\"/>.\n        /// </summary>\n        public FacebookConfiguration Configuration { get; set; }\n    }\n}"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/GlobalFacebookConfiguration.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing Microsoft.AspNet.Facebook.Providers;\n\nnamespace Microsoft.AspNet.Facebook\n{\n    /// <summary>\n    /// Provides a global <see cref=\"FacebookConfiguration\"/> for ASP.NET applications.\n    /// </summary>\n    public static class GlobalFacebookConfiguration\n    {\n        private static readonly Lazy<FacebookConfiguration> _configuration = new Lazy<FacebookConfiguration>(\n        () =>\n        {\n            FacebookConfiguration config = new FacebookConfiguration();\n            config.ClientProvider = new DefaultFacebookClientProvider(config);\n            config.PermissionService = new DefaultFacebookPermissionService(config);\n            return config;\n        });\n\n        /// <summary>\n        /// Gets the global <see cref=\"FacebookConfiguration\"/>.\n        /// </summary>\n        public static FacebookConfiguration Configuration\n        {\n            get\n            {\n                return _configuration.Value;\n            }\n        }\n    }\n}"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/GlobalSuppressions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\",\n    Target = \"Microsoft.AspNet.Facebook.Models\", Justification = \"Namespace follows folder structure\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\",\n    Target = \"Microsoft.AspNet.Facebook.ModelBinders\", Justification = \"Namespace follows folder structure\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\",\n    Target = \"Microsoft.AspNet.Facebook.Realtime\", Justification = \"Namespace follows folder structure\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\",\n    Target = \"Microsoft.AspNet.Facebook.Providers\", Justification = \"Namespace follows folder structure\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\",\n    Target = \"Microsoft.AspNet.Facebook.Client\", Justification = \"Namespace follows folder structure\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\",\n    Target = \"Microsoft.AspNet.Facebook.Authorization\", Justification = \"Namespace follows folder structure\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA2210:AssembliesShouldHaveValidStrongNames\",\n    Justification = \"Assembly is delay-signed\")]"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/JavaScriptRedirectResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Globalization;\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace Microsoft.AspNet.Facebook\n{\n    /// <summary>\n    /// Represents an <see cref=\"ActionResult\"/> that redirects to a permission prompt login via JavaScript.\n    /// </summary>\n    public class JavaScriptRedirectResult : ContentResult\n    {\n        internal Uri RedirectUrl { get; private set; }\n\n        /// <summary>\n        /// Creates a JavaScript based redirect <see cref=\"ActionResult\"/>.\n        /// </summary>\n        /// <param name=\"redirectUrl\">The url to redirect to.</param>\n        public JavaScriptRedirectResult(Uri redirectUrl)\n        {\n            RedirectUrl = redirectUrl;\n\n            ContentType = \"text/html\";\n            Content = String.Format(\n                CultureInfo.InvariantCulture,\n                \"<script>window.top.location = '{0}';</script>\",\n                HttpUtility.JavaScriptStringEncode(RedirectUrl.AbsoluteUri));\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/Microsoft.AspNet.Facebook.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{821A136C-7C6F-44C6-A9E6-C39B5BFB1483}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>Microsoft.AspNet.Facebook</RootNamespace>\n    <AssemblyName>Microsoft.AspNet.Facebook</AssemblyName>\n    <DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>\n    <RunCodeAnalysis>$(CodeAnalysis)</RunCodeAnalysis>\n    <CodeAnalysisRuleSet>..\\Strict.ruleset</CodeAnalysisRuleSet>\n    <DefineConstants>$(DefineConstants);ASPNETFACEBOOK</DefineConstants>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'\">\n    <DefineConstants>TRACE;DEBUG;CODE_ANALYSIS;ASPNETFACEBOOK</DefineConstants>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'Release|AnyCPU'\">\n    <DefineConstants>TRACE;ASPNETFACEBOOK</DefineConstants>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'CodeAnalysis|AnyCPU'\">\n    <DefineConstants>TRACE;CODE_ANALYSIS;ASPNETFACEBOOK</DefineConstants>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Facebook, Version=6.0.10.0, Culture=neutral, PublicKeyToken=58cb4f2111d1e6de, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\..\\packages\\Facebook.6.4.2\\lib\\net45\\Facebook.dll</HintPath>\n    </Reference>\n    <Reference Include=\"Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Newtonsoft.Json.13.0.1\\lib\\net45\\Newtonsoft.Json.dll</HintPath>\n      <SpecificVersion>False</SpecificVersion>\n      <Private>False</Private>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.ComponentModel.DataAnnotations\" />\n    <Reference Include=\"System.configuration\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Data.Entity\" />\n    <Reference Include=\"System.Net.Http\" />\n    <Reference Include=\"System.Net.Http.WebRequest\" />\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"System.XML\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"Client\\FacebookRequestHelper.cs\" />\n    <Compile Include=\"JavaScriptRedirectResult.cs\" />\n    <Compile Include=\"PermissionContext.cs\" />\n    <Compile Include=\"PermissionHelper.cs\" />\n    <Compile Include=\"FacebookAppSettingKeys.cs\" />\n    <Compile Include=\"GlobalSuppressions.cs\" />\n    <Compile Include=\"PermissionsStatus.cs\" />\n    <Compile Include=\"PermissionStatus.cs\" />\n    <Compile Include=\"FacebookAuthenticationModule.cs\" />\n    <Compile Include=\"FacebookHtmlHelperExtensions.cs\" />\n    <Compile Include=\"GlobalFacebookConfiguration.cs\" />\n    <Compile Include=\"ModelBinders\\FacebookRedirectContextBinderAttribute.cs\" />\n    <Compile Include=\"FacebookAuthorizeAttribute.cs\" />\n    <Compile Include=\"FacebookFieldModifierAttribute.cs\" />\n    <Compile Include=\"ModelBinders\\FacebookContextBinderAttribute.cs\" />\n    <Compile Include=\"Authorization\\FacebookAuthorizeFilter.cs\" />\n    <Compile Include=\"Client\\FacebookClientExtensions.cs\" />\n    <Compile Include=\"Client\\FacebookQueryHelper.cs\" />\n    <Compile Include=\"Providers\\IFacebookPermissionService.cs\" />\n    <Compile Include=\"Providers\\DefaultFacebookPermissionService.cs\" />\n    <Compile Include=\"Realtime\\FacebookRealtimeUpdateController.cs\" />\n    <Compile Include=\"Models\\ChangeNotification.cs\" />\n    <Compile Include=\"Models\\ChangeEntry.cs\" />\n    <Compile Include=\"FacebookConnection.cs\" />\n    <Compile Include=\"FacebookGroupConnection.cs\" />\n    <Compile Include=\"ModelBinders\\FacebookRedirectContextModelBinder.cs\" />\n    <Compile Include=\"FacebookRedirectContext.cs\" />\n    <Compile Include=\"FacebookContext.cs\" />\n    <Compile Include=\"ModelBinders\\FacebookContextModelBinder.cs\" />\n    <Compile Include=\"Models\\SubscriptionVerification.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"Providers\\DefaultFacebookClientProvider.cs\" />\n    <Compile Include=\"FacebookConfiguration.cs\" />\n    <Compile Include=\"Providers\\IFacebookClientProvider.cs\" />\n    <Compile Include=\"Resources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>Resources.resx</DependentUpon>\n    </Compile>\n    <Compile Include=\"ShowPromptResult.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <CodeAnalysisDictionary Include=\"..\\CodeAnalysisDictionary.xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\CommonAssemblyInfo.cs\">\n      <Link>Properties\\CommonAssemblyInfo.cs</Link>\n    </Compile>\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\">\n      <SubType>Designer</SubType>\n    </None>\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"Resources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>Resources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\System.Net.Http.Formatting\\System.Net.Http.Formatting.csproj\">\n      <Project>{668e9021-ce84-49d9-98fb-df125a9fcdb0}</Project>\n      <Name>System.Net.Http.Formatting</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.Http.WebHost\\System.Web.Http.WebHost.csproj\">\n      <Project>{a0187bc2-8325-4bb2-8697-7f955cf4173e}</Project>\n      <Name>System.Web.Http.WebHost</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.Http\\System.Web.Http.csproj\">\n      <Project>{ddc1ce0c-486e-4e35-bb3b-eab61f8f9440}</Project>\n      <Name>System.Web.Http</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.Mvc\\System.Web.Mvc.csproj\">\n      <Project>{3d3ffd8a-624d-4e9b-954b-e1c105507975}</Project>\n      <Name>System.Web.Mvc</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.Razor\\System.Web.Razor.csproj\">\n      <Project>{8f18041b-9410-4c36-a9c5-067813df5f31}</Project>\n      <Name>System.Web.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.WebPages.Deployment\\System.Web.WebPages.Deployment.csproj\">\n      <Project>{22babb60-8f02-4027-affc-acf069954536}</Project>\n      <Name>System.Web.WebPages.Deployment</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.WebPages.Razor\\System.Web.WebPages.Razor.csproj\">\n      <Project>{0939b11a-fe4e-4ba1-8ad6-d97741ee314f}</Project>\n      <Name>System.Web.WebPages.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.WebPages\\System.Web.WebPages.csproj\">\n      <Project>{76efa9c5-8d7e-4fdf-b710-e20f8b6b00d2}</Project>\n      <Name>System.Web.WebPages</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.\n       Other similar extension points exist, see Microsoft.Common.targets.\n  <Target Name=\"BeforeBuild\">\n  </Target>\n  <Target Name=\"AfterBuild\">\n  </Target>\n  -->\n</Project>"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/ModelBinders/FacebookContextBinderAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Mvc;\n\nnamespace Microsoft.AspNet.Facebook.ModelBinders\n{\n    [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]\n    internal sealed class FacebookContextBinderAttribute : CustomModelBinderAttribute\n    {\n        public override IModelBinder GetBinder()\n        {\n            return new FacebookContextModelBinder(GlobalFacebookConfiguration.Configuration);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/ModelBinders/FacebookContextModelBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Mvc;\nusing Facebook;\nusing Microsoft.AspNet.Facebook.Client;\n\nnamespace Microsoft.AspNet.Facebook.ModelBinders\n{\n    /// <summary>\n    /// Model binds an action method parameter to a <see cref=\"FacebookContext\"/>.\n    /// </summary>\n    public class FacebookContextModelBinder : IModelBinder\n    {\n        private FacebookConfiguration _config;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"FacebookContextModelBinder\" /> class.\n        /// </summary>\n        /// <param name=\"config\">The <see cref=\"FacebookConfiguration\"/>.</param>\n        public FacebookContextModelBinder(FacebookConfiguration config)\n        {\n            if (config == null)\n            {\n                throw new ArgumentNullException(\"config\");\n            }\n\n            _config = config;\n        }\n\n        /// <summary>\n        /// Binds the model to a value by using the specified controller context and binding context.\n        /// </summary>\n        /// <param name=\"controllerContext\">The controller context.</param>\n        /// <param name=\"bindingContext\">The binding context.</param>\n        /// <returns>\n        /// The bound value.\n        /// </returns>\n        public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)\n        {\n            FacebookClient client = _config.ClientProvider.CreateClient();\n            dynamic signedRequest = FacebookRequestHelpers.GetSignedRequest(\n                controllerContext.HttpContext,\n                rawSignedRequest =>\n                {\n                    return client.ParseSignedRequest(rawSignedRequest);\n                });\n            if (signedRequest != null)\n            {\n                string accessToken = signedRequest.oauth_token;\n                string userId = signedRequest.user_id;\n                client.AccessToken = accessToken;\n                return new FacebookContext\n                {\n                    Client = client,\n                    SignedRequest = signedRequest,\n                    AccessToken = accessToken,\n                    UserId = userId,\n                    Configuration = _config\n                };\n            }\n            else\n            {\n                bindingContext.ModelState.AddModelError(bindingContext.ModelName, Resources.MissingSignedRequest);\n            }\n\n            return null;\n        }\n    }\n}"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/ModelBinders/FacebookRedirectContextBinderAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Mvc;\n\nnamespace Microsoft.AspNet.Facebook.ModelBinders\n{\n    [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]\n    internal sealed class FacebookRedirectContextBinderAttribute : CustomModelBinderAttribute\n    {\n        public override IModelBinder GetBinder()\n        {\n            return new FacebookRedirectContextModelBinder(GlobalFacebookConfiguration.Configuration);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/ModelBinders/FacebookRedirectContextModelBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Globalization;\nusing System.Web;\nusing System.Web.Mvc;\nusing Facebook;\nusing Microsoft.AspNet.Facebook.Client;\n\nnamespace Microsoft.AspNet.Facebook.ModelBinders\n{\n    /// <summary>\n    /// Model binds an action method parameter to a <see cref=\"FacebookRedirectContext\"/>.\n    /// </summary>\n    public class FacebookRedirectContextModelBinder : IModelBinder\n    {\n        private FacebookConfiguration _config;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"FacebookRedirectContextModelBinder\" /> class.\n        /// </summary>\n        /// <param name=\"config\">The <see cref=\"FacebookConfiguration\"/>.</param>\n        public FacebookRedirectContextModelBinder(FacebookConfiguration config)\n        {\n            if (config == null)\n            {\n                throw new ArgumentNullException(\"config\");\n            }\n\n            _config = config;\n        }\n\n        /// <summary>\n        /// Binds the model to a value by using the specified controller context and binding context.\n        /// </summary>\n        /// <param name=\"controllerContext\">The controller context.</param>\n        /// <param name=\"bindingContext\">The binding context.</param>\n        /// <returns>\n        /// The bound value.\n        /// </returns>\n        public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)\n        {\n            HttpRequestBase request = controllerContext.HttpContext.Request;\n            string originUrl = request.QueryString[\"originUrl\"];\n            string permissions = request.QueryString[\"permissions\"];\n\n            if (!String.IsNullOrEmpty(originUrl))\n            {\n                if (!originUrl.StartsWith(_config.AppUrl, StringComparison.OrdinalIgnoreCase))\n                {\n                    bindingContext.ModelState.AddModelError(bindingContext.ModelName,\n                        String.Format(CultureInfo.CurrentCulture, Resources.UrlCannotBeExternal, \"originUrl\", _config.AppUrl));\n                }\n            }\n            else\n            {\n                bindingContext.ModelState.AddModelError(bindingContext.ModelName,\n                    String.Format(CultureInfo.CurrentCulture, Resources.ParameterIsRequired, \"originUrl\"));\n            }\n\n            string redirectUrl = null;\n            string[] requiredPermissions = permissions != null ? permissions.Split(',') : new string[0];\n            if (bindingContext.ModelState.IsValid)\n            {\n                FacebookClient client = _config.ClientProvider.CreateClient();\n                // Don't want to redirect to a permissioned URL, the action authorize filters take care of that.\n                redirectUrl = client.GetLoginUrl(originUrl, _config.AppId, String.Empty).AbsoluteUri;\n            }\n\n            return new FacebookRedirectContext\n            {\n                OriginUrl = originUrl,\n                RequiredPermissions = requiredPermissions,\n                RedirectUrl = redirectUrl,\n                Configuration = _config\n            };\n        }\n    }\n}"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/Models/ChangeEntry.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing Newtonsoft.Json;\n\nnamespace Microsoft.AspNet.Facebook.Models\n{\n    /// <summary>\n    /// Change entry from Facebook as part of Realtime Updates.\n    /// </summary>\n    public class ChangeEntry\n    {\n        /// <summary>\n        /// Gets or sets the user id.\n        /// </summary>\n        [JsonProperty(\"UId\")]\n        public long UserId { get; set; }\n\n        /// <summary>\n        /// Gets or sets the changed fields.\n        /// </summary>\n        [JsonProperty(\"Changed_Fields\")]\n        public IEnumerable<string> ChangedFields { get; set; }\n\n        /// <summary>\n        /// Gets or sets the time.\n        /// </summary>\n        public long Time { get; set; }\n    }\n}"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/Models/ChangeNotification.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace Microsoft.AspNet.Facebook.Models\n{\n    /// <summary>\n    /// Notification from Facebook as part of Realtime Updates.\n    /// </summary>\n    public class ChangeNotification\n    {\n        /// <summary>\n        /// Gets or sets the object that has been updated.\n        /// </summary>\n        /// <value>\n        /// The Facebook object.\n        /// </value>\n        public string Object { get; set; }\n\n        /// <summary>\n        /// Gets or sets the change entry.\n        /// </summary>\n        /// <value>\n        /// The change entry.\n        /// </value>\n        public IEnumerable<ChangeEntry> Entry { get; set; }\n    }\n}"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/Models/SubscriptionVerification.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Http;\n\nnamespace Microsoft.AspNet.Facebook.Models\n{\n    /// <summary>\n    /// Subscription verification data from Facebook as part of Realtime Updates.\n    /// </summary>\n    [FromUri(Name = \"hub\")]\n    public class SubscriptionVerification\n    {\n        /// <summary>\n        /// Gets or sets the mode.\n        /// </summary>\n        /// <value>\n        /// The mode.\n        /// </value>\n        public string Mode { get; set; }\n\n        /// <summary>\n        /// Gets or sets the verify_token.\n        /// </summary>\n        /// <value>\n        /// The verify_token.\n        /// </value>\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1707:IdentifiersShouldNotContainUnderscores\", Justification = \"This is a shipped API\")]\n        public string Verify_Token { get; set; }\n\n        /// <summary>\n        /// Gets or sets the challenge string.\n        /// </summary>\n        /// <value>\n        /// The challenge string.\n        /// </value>\n        public string Challenge { get; set; }\n    }\n}"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/PermissionContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Mvc;\n\nnamespace Microsoft.AspNet.Facebook\n{\n    /// <summary>\n    /// Provides access to permission information associated with a user.\n    /// </summary>\n    public class PermissionContext\n    {\n        /// <summary>\n        /// Permissions that were previously requested for but not granted for the lifetime of this application. This can happen\n        /// by a user revoking, skipping or choosing not to allow permissions in the Facebook login dialog.\n        /// </summary>\n        /// <remarks>\n        /// This should only ever be \"set\" or modified within tests.\n        /// </remarks>\n        public IEnumerable<string> DeclinedPermissions { get; set; }\n\n        /// <summary>\n        /// Provides access to Facebook-specific information.\n        /// </summary>\n        /// <remarks>\n        /// This should only ever be \"set\" or modified within tests.\n        /// </remarks>\n        public FacebookContext FacebookContext { get; set; }\n\n        /// <summary>\n        /// Provides access to filter information.\n        /// </summary>\n        /// <remarks>\n        /// This should only ever be \"set\" or modified within tests.\n        /// </remarks>\n        public AuthorizationContext FilterContext { get; set; }\n\n        /// <summary>\n        /// The entire list of missing permissions for the current page, including <see cref=\"DeclinedPermissions\"/> and \n        /// <see cref=\"SkippedPermissions\"/>.\n        /// </summary>\n        /// <remarks>\n        /// This should only ever be \"set\" or modified within tests.\n        /// </remarks>\n        public IEnumerable<string> MissingPermissions { get; set; }\n\n        /// <summary>\n        /// The entire list of requested permissions for the current page. Includes permissions that were already prompted for.\n        /// </summary>\n        /// <remarks>\n        /// This should only ever be \"set\" or modified within tests.\n        /// </remarks>\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", \n            Justification = \"This is public and can be set in tests.\")]\n        public HashSet<string> RequiredPermissions { get; set; }\n\n        /// <summary>\n        /// The <see cref=\"ActionResult\" /> that should be used to control the login flow.  If value is null then we will continue\n        /// onto the action that is intended to be invoked.  Non-null values short-circuit the action.\n        /// </summary>\n        public ActionResult Result { get; set; }\n\n        /// <summary>\n        /// Permissions that were previously requested for but skipped for the current page. This can happen from a user hitting\n        /// the \"skip\" button when requesting permissions.\n        /// </summary>\n        /// <remarks>Skips are tracked via cookies. If cookies are cleared skips will not be detected.</remarks>\n        /// <remarks>\n        /// This should only ever be \"set\" or modified within tests.\n        /// </remarks>\n        public IEnumerable<string> SkippedPermissions { get; set; }\n\n        internal string RedirectUrl { get; set; }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/PermissionHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace Microsoft.AspNet.Facebook\n{\n    internal static class PermissionHelper\n    {\n        // This cookie name is used to track permissions we've requested of the user to determine skipped permissions.\n        public const string RequestedPermissionCookieName = \"_fb_requested_permissions\";\n\n        public static IEnumerable<string> GetDeclinedPermissions(PermissionsStatus permissionsStatus)\n        {\n            return GetPermissionsWithStatus(permissionsStatus, PermissionStatus.Declined);\n        }\n\n        public static IEnumerable<string> GetGrantedPermissions(PermissionsStatus permissionsStatus)\n        {\n            return GetPermissionsWithStatus(permissionsStatus, PermissionStatus.Granted);\n        }\n\n        public static IEnumerable<string> GetPreviouslyRequestedPermissions(HttpRequestBase request)\n        {\n            HttpCookie existingCookie = request.Cookies.Get(RequestedPermissionCookieName);\n\n            // If there's no cookie or an empty cookie then don't return a 1 element enumerable, return an empty one.\n            if (existingCookie == null || String.IsNullOrEmpty(existingCookie.Value))\n            {\n                return Enumerable.Empty<string>();\n            }\n\n            return existingCookie.Value.Split(',');\n        }\n\n        public static HashSet<string> GetRequiredPermissions(IEnumerable<FacebookAuthorizeAttribute> facebookAuthorizeAttributes)\n        {\n            var requiredPermissions = new HashSet<string>(\n                facebookAuthorizeAttributes.SelectMany(attribute => attribute.Permissions),\n                StringComparer.Ordinal);\n\n            return requiredPermissions;\n        }\n\n        public static IEnumerable<string> GetSkippedPermissions(HttpRequestBase request,\n                                                                IEnumerable<string> missingPermissions,\n                                                                IEnumerable<string> declinedPermissions)\n        {\n            IEnumerable<string> previouslyRequestedPermissions = PermissionHelper.GetPreviouslyRequestedPermissions(request);\n            IEnumerable<string> previouslyRequestedMissingPermissions = missingPermissions.Where((permission) =>\n                previouslyRequestedPermissions.Contains(permission));\n            IEnumerable<string> skippedPermissions = previouslyRequestedMissingPermissions.Except(declinedPermissions);\n\n            return skippedPermissions;\n        }\n\n        public static void PersistRequestedPermissions(AuthorizationContext context, IEnumerable<string> requestedPermissions)\n        {\n            HttpRequestBase request = context.HttpContext.Request;\n            IEnumerable<string> existingRequestedPermissions = GetPreviouslyRequestedPermissions(request);\n            IEnumerable<string> combinedRequestedPermissions = existingRequestedPermissions.Concat(requestedPermissions);\n\n            // No need for duplicates\n            combinedRequestedPermissions = combinedRequestedPermissions.Distinct(StringComparer.Ordinal);\n\n            string newCookieValue = String.Join(\",\", combinedRequestedPermissions);\n\n            HttpCookieCollection responseCookies = context.HttpContext.Response.Cookies;\n            HttpCookie cookie = new HttpCookie(RequestedPermissionCookieName, newCookieValue);\n            responseCookies.Add(cookie);\n        }\n\n        public static bool RequestedPermissionsCookieExists(HttpRequestBase request)\n        {\n            return request.Cookies.Get(RequestedPermissionCookieName) != null;\n        }\n\n        private static IEnumerable<string> GetPermissionsWithStatus(PermissionsStatus permissionsStatus, \n                                                                    PermissionStatus status)\n        {\n            return permissionsStatus.Status.Where(kvp => kvp.Value == status)\n                                           .Select(kvp => kvp.Key);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/PermissionStatus.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.AspNet.Facebook\n{\n    /// <summary>\n    /// Describes the kind of permission for an entry in the <see cref=\"PermissionsStatus.Status\"/> dictionary.\n    /// </summary>\n    public enum PermissionStatus\n    {\n        /// <summary>\n        /// User granted permission.\n        /// </summary>\n        Granted,\n\n        /// <summary>\n        /// User declined permission.\n        /// </summary>\n        Declined,\n\n        /// <summary>\n        /// Unknown status of a permission.\n        /// </summary>\n        Unknown\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/PermissionsStatus.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\n\nnamespace Microsoft.AspNet.Facebook\n{\n    /// <summary>\n    /// Provides access to a users permissions status and the raw data returned from an API.\n    /// </summary>\n    public class PermissionsStatus\n    {\n        // Values representing permission statuses returned by the facebook graph API.\n        private const string FacebookPermissionGranted = \"granted\";\n        private const string FacebookPermissionDeclined = \"declined\";\n\n        /// <summary>\n        /// Constructs a more useable object than the provided api result.\n        /// </summary>\n        /// <param name=\"apiResult\">The raw data returned by the queried API.</param>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\",\n            Justification = \"This type is the raw type of data that Facebook returns to us.\")]\n        public PermissionsStatus(IList<IDictionary<string, string>> apiResult)\n        {\n            ApiResult = apiResult;\n            Status = ConvertApiResult(apiResult);\n        }\n\n        /// <summary>\n        /// A parsed, easier to use version of the <see cref=\"ApiResult\"/>.\n        /// </summary>\n        public IDictionary<string, PermissionStatus> Status { get; private set; }\n\n        /// <summary>\n        /// The raw data returned by the queried API.\n        /// </summary>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", \n            Justification = \"This type is the raw type of data that Facebook returns to us.\")]\n        public IList<IDictionary<string, string>> ApiResult { get; private set; }\n\n        /// <summary>\n        /// Queries the <see cref=\"Status\"/> member for the provided permission name.\n        /// </summary>\n        /// <param name=\"permission\">The name of the permission to query the <see cref=\"Status\"/> for.</param>\n        /// <returns>The permission's status.</returns>\n        public PermissionStatus this[string permission]\n        {\n            get\n            {\n                return Status[permission];\n            }\n        }\n\n        private static PermissionStatus ConvertPermissionStatus(string permissionStatus)\n        {\n            if (String.Equals(permissionStatus, FacebookPermissionGranted, StringComparison.OrdinalIgnoreCase))\n            {\n                return PermissionStatus.Granted;\n            }\n            else if (String.Equals(permissionStatus, FacebookPermissionDeclined, StringComparison.OrdinalIgnoreCase))\n            {\n                return PermissionStatus.Declined;\n            }\n\n            return PermissionStatus.Unknown;\n        }\n\n        private static IDictionary<string, PermissionStatus> ConvertApiResult(IList<IDictionary<string, string>> apiResults)\n        {\n            IDictionary<string, PermissionStatus> transformedPermissions =\n                new Dictionary<string, PermissionStatus>(StringComparer.OrdinalIgnoreCase);\n\n            if (apiResults != null && apiResults.Any())\n            {\n                foreach (IDictionary<string, string> permissionData in apiResults)\n                {\n                    PermissionStatus status = ConvertPermissionStatus(permissionData[\"status\"]);\n                    transformedPermissions.Add(permissionData[\"permission\"], status);\n                }\n            }\n\n            return transformedPermissions;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/Properties/AssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Web;\nusing Microsoft.AspNet.Facebook;\n\n[assembly: AssemblyTitle(\"Microsoft.AspNet.Facebook\")]\n[assembly: AssemblyDescription(\"\")]\n\n[assembly: InternalsVisibleTo(\"Microsoft.AspNet.Facebook.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/Providers/DefaultFacebookClientProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing Facebook;\nusing Newtonsoft.Json;\n\nnamespace Microsoft.AspNet.Facebook.Providers\n{\n    /// <summary>\n    /// Default implementation of <see cref=\"IFacebookClientProvider\"/>.\n    /// </summary>\n    public class DefaultFacebookClientProvider : IFacebookClientProvider\n    {\n        private FacebookConfiguration _config;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"DefaultFacebookClientProvider\" /> class.\n        /// </summary>\n        /// <param name=\"configuration\">The <see cref=\"FacebookConfiguration\"/>.</param>\n        public DefaultFacebookClientProvider(FacebookConfiguration configuration)\n        {\n            if (configuration == null)\n            {\n                throw new ArgumentNullException(\"configuration\");\n            }\n\n            _config = configuration;\n        }\n\n        /// <summary>\n        /// Creates a <see cref=\"FacebookClient\"/> with AppId and AppSecret that uses Json.NET for serialization and deserialization.\n        /// Does not have an access token associated with it by default.\n        /// </summary>\n        /// <returns>The <see cref=\"FacebookClient\"/> instance.</returns>\n        public virtual FacebookClient CreateClient()\n        {\n            FacebookClient client = new FacebookClient();\n            client.AppId = _config.AppId;\n            client.AppSecret = _config.AppSecret;\n            client.SetJsonSerializers(JsonConvert.SerializeObject, JsonConvert.DeserializeObject);\n            return client;\n        }\n    }\n}"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/Providers/DefaultFacebookPermissionService.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing Facebook;\nusing Microsoft.AspNet.Facebook.Client;\n\nnamespace Microsoft.AspNet.Facebook.Providers\n{\n    /// <summary>\n    /// Default implementation of <see cref=\"IFacebookPermissionService\"/>.\n    /// </summary>\n    public class DefaultFacebookPermissionService : IFacebookPermissionService\n    {\n        private FacebookConfiguration _config;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"DefaultFacebookPermissionService\" /> class.\n        /// </summary>\n        /// <param name=\"configuration\">The <see cref=\"FacebookConfiguration\"/>.</param>\n        public DefaultFacebookPermissionService(FacebookConfiguration configuration)\n        {\n            if (configuration == null)\n            {\n                throw new ArgumentNullException(\"configuration\");\n            }\n\n            _config = configuration;\n        }\n\n        /// <summary>\n        /// Gets the user permissions by calling the Facebook Graph API.\n        /// </summary>\n        /// <param name=\"userId\">The user id.</param>\n        /// <param name=\"accessToken\">The access token.</param>\n        /// <returns>The user permissions.</returns>\n        public virtual IEnumerable<string> GetUserPermissions(string userId, string accessToken)\n        {\n            if (userId == null)\n            {\n                throw new ArgumentNullException(\"userId\");\n            }\n\n            if (accessToken == null)\n            {\n                throw new ArgumentNullException(\"accessToken\");\n            }\n\n            PermissionsStatus permissionsStatus = GetUserPermissionsStatus(userId, accessToken);\n\n            return PermissionHelper.GetGrantedPermissions(permissionsStatus);\n        }\n\n        /// <summary>\n        /// Gets the users permission status by calling the Facebook graph API.\n        /// </summary>\n        /// <param name=\"userId\">The user id.</param>\n        /// <param name=\"accessToken\">The access token.</param>\n        /// <returns>The users permission status is in the following format { { \"permissionName\", \"granted|declined\" } }.</returns>\n        public virtual PermissionsStatus GetUserPermissionsStatus(string userId, string accessToken)\n        {\n            if (userId == null)\n            {\n                throw new ArgumentNullException(\"userId\");\n            }\n\n            if (accessToken == null)\n            {\n                throw new ArgumentNullException(\"accessToken\");\n            }\n\n            FacebookClient client = _config.ClientProvider.CreateClient();\n            client.AccessToken = accessToken;\n\n            IList<IDictionary<string, string>> rawPermissionsStatus = client.GetCurrentUserPermissionsStatus();\n            PermissionsStatus permissionsStatus = new PermissionsStatus(rawPermissionsStatus);\n\n            return permissionsStatus;\n        }\n    }\n}"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/Providers/IFacebookClientProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Facebook;\n\nnamespace Microsoft.AspNet.Facebook.Providers\n{\n    /// <summary>\n    /// Provides an abstraction for creating <see cref=\"FacebookClient\"/>.\n    /// </summary>\n    public interface IFacebookClientProvider\n    {\n        /// <summary>\n        /// Creates an instance of <see cref=\"FacebookClient\"/>.\n        /// </summary>\n        /// <returns>The <see cref=\"FacebookClient\"/> instance.</returns>\n        FacebookClient CreateClient();\n    }\n}"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/Providers/IFacebookPermissionService.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace Microsoft.AspNet.Facebook.Providers\n{\n    /// <summary>\n    /// Provides an abstraction for retrieving the user permissions.\n    /// </summary>\n    public interface IFacebookPermissionService\n    {\n        /// <summary>\n        /// Gets the user permissions.\n        /// </summary>\n        /// <param name=\"userId\">The user id.</param>\n        /// <param name=\"accessToken\">The access token.</param>\n        /// <returns>The user permissions.</returns>\n        IEnumerable<string> GetUserPermissions(string userId, string accessToken);\n\n        /// <summary>\n        /// Gets the users permission status.\n        /// </summary>\n        /// <param name=\"userId\">The user id.</param>\n        /// <param name=\"accessToken\">The access token.</param>\n        /// <returns>The user permissions status.</returns>\n        PermissionsStatus GetUserPermissionsStatus(string userId, string accessToken);\n    }\n}"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/Realtime/FacebookRealtimeUpdateController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading.Tasks;\nusing System.Web.Http;\nusing Facebook;\nusing Microsoft.AspNet.Facebook.Models;\n\nnamespace Microsoft.AspNet.Facebook.Realtime\n{\n    /// <summary>\n    /// <see cref=\"ApiController\"/> for handling Facebook Realtime Update subscriptions.\n    /// </summary>\n    public abstract class FacebookRealtimeUpdateController : ApiController\n    {\n        private const string XHubSignatureHeaderName = \"X-Hub-Signature\";\n        private FacebookConfiguration _facebookConfiguration;\n\n        /// <summary>\n        /// Gets the verify token.\n        /// </summary>\n        /// <value>\n        /// The verify token.\n        /// </value>\n        public abstract string VerifyToken { get; }\n\n        /// <summary>\n        /// Gets or sets the <see cref=\"FacebookConfiguration\"/>.\n        /// </summary>\n        /// <value>\n        /// The <see cref=\"FacebookConfiguration\"/>.\n        /// </value>\n        public FacebookConfiguration FacebookConfiguration\n        {\n            get\n            {\n                if (_facebookConfiguration == null)\n                {\n                    _facebookConfiguration = GlobalFacebookConfiguration.Configuration;\n                }\n                return _facebookConfiguration;\n            }\n            set\n            {\n                _facebookConfiguration = value;\n            }\n        }\n\n        /// <summary>\n        /// Handles the update.\n        /// </summary>\n        /// <param name=\"notification\">The notification.</param>\n        [NonAction]\n        public abstract Task HandleUpdateAsync(ChangeNotification notification);\n\n        /// <summary>\n        /// Handles the HTTP GET requests from Facebook for subscription verification.\n        /// </summary>\n        /// <param name=\"subscriptionVerification\">The subscription verification.</param>\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1716:IdentifiersShouldNotMatchKeywords\", MessageId = \"Get\", Justification = \"Needs to be this name to follow routing conventions\")]\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"HttpResponseMessage will be disposed by Web API\")]\n        public virtual HttpResponseMessage Get(SubscriptionVerification subscriptionVerification)\n        {\n            try\n            {\n                FacebookClient client = FacebookConfiguration.ClientProvider.CreateClient();\n                client.VerifyGetSubscription(subscriptionVerification.Mode, subscriptionVerification.Verify_Token, subscriptionVerification.Challenge, VerifyToken);\n            }\n            catch (ArgumentException argumentException)\n            {\n                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, argumentException);\n            }\n\n            return new HttpResponseMessage\n            {\n                Content = new StringContent(subscriptionVerification.Challenge)\n            };\n        }\n\n        /// <summary>\n        /// Handles the HTTP POST requests from Facebook for updates.\n        /// </summary>\n        public virtual async Task<HttpResponseMessage> Post()\n        {\n            IEnumerable<string> headerValues;\n            if (Request.Headers.TryGetValues(XHubSignatureHeaderName, out headerValues))\n            {\n                string signatureHeaderValue = headerValues.FirstOrDefault();\n                try\n                {\n                    string contentString = await Request.Content.ReadAsStringAsync();\n                    FacebookClient client = FacebookConfiguration.ClientProvider.CreateClient();\n                    ChangeNotification notification = client.VerifyPostSubscription(signatureHeaderValue, contentString, typeof(ChangeNotification)) as ChangeNotification;\n                    await HandleUpdateAsync(notification);\n                }\n                catch (ArgumentException argumentException)\n                {\n                    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, argumentException);\n                }\n                catch (HttpResponseException responseException)\n                {\n                    return responseException.Response;\n                }\n            }\n            else\n            {\n                return Request.CreateErrorResponse(\n                    HttpStatusCode.BadRequest,\n                    String.Format(CultureInfo.CurrentCulture, Resources.MissingRequiredHeader, XHubSignatureHeaderName));\n            }\n\n            return Request.CreateResponse(HttpStatusCode.OK);\n        }\n    }\n}"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/Resources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.35317\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace Microsoft.AspNet.Facebook {\n    using System;\n    \n    \n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class Resources {\n        \n        private static global::System.Resources.ResourceManager resourceMan;\n        \n        private static global::System.Globalization.CultureInfo resourceCulture;\n        \n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal Resources() {\n        }\n        \n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"Microsoft.AspNet.Facebook.Resources\", typeof(Resources).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n        \n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The app setting &apos;{0}&apos; is required and cannot be missing or empty. Make sure you set it in the configuration file..\n        /// </summary>\n        internal static string AppSettingIsRequired {\n            get {\n                return ResourceManager.GetString(\"AppSettingIsRequired\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to This argument cannot be null or empty..\n        /// </summary>\n        internal static string ArgumentCannotBeNullOrEmpty {\n            get {\n                return ResourceManager.GetString(\"ArgumentCannotBeNullOrEmpty\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Circular type references are not supported..\n        /// </summary>\n        internal static string CircularReferenceNotSupported {\n            get {\n                return ResourceManager.GetString(\"CircularReferenceNotSupported\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Invalid &apos;{0}&apos;. The &apos;{0}&apos; can only be set relative to the AppUrl. Prefix the path with &apos;~/&apos;..\n        /// </summary>\n        internal static string InvalidRedirectPath {\n            get {\n                return ResourceManager.GetString(\"InvalidRedirectPath\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The required header &apos;{0}&apos; is missing..\n        /// </summary>\n        internal static string MissingRequiredHeader {\n            get {\n                return ResourceManager.GetString(\"MissingRequiredHeader\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The signed request is missing..\n        /// </summary>\n        internal static string MissingSignedRequest {\n            get {\n                return ResourceManager.GetString(\"MissingSignedRequest\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &apos;{0}&apos; parameter is required..\n        /// </summary>\n        internal static string ParameterIsRequired {\n            get {\n                return ResourceManager.GetString(\"ParameterIsRequired\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The provided permission string &apos;{0}&apos; should not contain comma (,)..\n        /// </summary>\n        internal static string PermissionStringShouldNotContainComma {\n            get {\n                return ResourceManager.GetString(\"PermissionStringShouldNotContainComma\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &apos;{0}&apos; cannot be an external URL. It must have &apos;{1}&apos; as the prefix..\n        /// </summary>\n        internal static string UrlCannotBeExternal {\n            get {\n                return ResourceManager.GetString(\"UrlCannotBeExternal\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/Resources.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"AppSettingIsRequired\" xml:space=\"preserve\">\n    <value>The app setting '{0}' is required and cannot be missing or empty. Make sure you set it in the configuration file.</value>\n  </data>\n  <data name=\"ArgumentCannotBeNullOrEmpty\" xml:space=\"preserve\">\n    <value>This argument cannot be null or empty.</value>\n  </data>\n  <data name=\"CircularReferenceNotSupported\" xml:space=\"preserve\">\n    <value>Circular type references are not supported.</value>\n  </data>\n  <data name=\"InvalidRedirectPath\" xml:space=\"preserve\">\n    <value>Invalid '{0}'. The '{0}' can only be set relative to the AppUrl. Prefix the path with '~/'.</value>\n  </data>\n  <data name=\"MissingRequiredHeader\" xml:space=\"preserve\">\n    <value>The required header '{0}' is missing.</value>\n  </data>\n  <data name=\"MissingSignedRequest\" xml:space=\"preserve\">\n    <value>The signed request is missing.</value>\n  </data>\n  <data name=\"ParameterIsRequired\" xml:space=\"preserve\">\n    <value>The '{0}' parameter is required.</value>\n  </data>\n  <data name=\"PermissionStringShouldNotContainComma\" xml:space=\"preserve\">\n    <value>The provided permission string '{0}' should not contain comma (,).</value>\n  </data>\n  <data name=\"UrlCannotBeExternal\" xml:space=\"preserve\">\n    <value>The '{0}' cannot be an external URL. It must have '{1}' as the prefix.</value>\n  </data>\n</root>"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/ShowPromptResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Mvc;\n\nnamespace Microsoft.AspNet.Facebook\n{\n    /// <summary>\n    /// Represents an <see cref=\"ActionResult\"/> that redirects to a permission prompt login via JavaScript.\n    /// </summary>\n    public class ShowPromptResult : JavaScriptRedirectResult\n    {\n        /// <summary>\n        /// Creates a JavaScript based redirect <see cref=\"ActionResult\"/>.\n        /// </summary>\n        /// <param name=\"promptUrl\">The url that the prompt exists at.</param>\n        public ShowPromptResult(Uri promptUrl)\n            : base(promptUrl)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.AspNet.Facebook/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Facebook\" version=\"6.4.2\" targetFramework=\"net45\" />\n  <package id=\"Microsoft.Web.Infrastructure\" version=\"1.0.0.0\" targetFramework=\"net45\" />\n  <package id=\"Newtonsoft.Json\" version=\"13.0.1\" targetFramework=\"net45\" />\n</packages>"
  },
  {
    "path": "src/Microsoft.Web.Helpers/Analytics.cshtml",
    "content": "﻿@* Generator: WebPagesHelper *@\n\n@helper GetGoogleHtml(string webPropertyId) {\n    var webPropertyIdJson = new HtmlString(HttpUtility.JavaScriptStringEncode(webPropertyId, addDoubleQuotes: false));\n\n    <script type=\"text/javascript\">\n        var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");\n        document.write(unescape(\"%3Cscript src='\" + gaJsHost + \"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E\"));\n    </script>\n    <script type=\"text/javascript\">\n        try{\n            var pageTracker = _gat._getTracker(\"@webPropertyIdJson\");\n            pageTracker._trackPageview();\n        } catch(err) {}\n    </script>\n}\n\n@helper GetGoogleAsyncHtml(string webPropertyId) {\n    var webPropertyIdJson = new HtmlString(HttpUtility.JavaScriptStringEncode(webPropertyId, addDoubleQuotes: false));\n    <script type=\"text/javascript\">\n        var _gaq = _gaq || [];\n        _gaq.push(['_setAccount', '@webPropertyIdJson']);\n        _gaq.push(['_trackPageview']);\n        (function() {\n            var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;\n            ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';\n            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);\n        })();\n    </script>\n}\n\n@helper GetYahooHtml(string account) {\n    var accountJson = new HtmlString(HttpUtility.JavaScriptStringEncode(account, addDoubleQuotes: false));\n    <script type=\"text/javascript\">\n        window.ysm_customData = new Object();\n        window.ysm_customData.conversion = \"transId=,currency=,amount=\";\n        var ysm_accountid = \"@accountJson\";\n        document.write(\"<SCR\" + \"IPT language='JavaScript' type='text/javascript' \"\n        + \"SRC=//\" + \"srv3.wa.marketingsolutions.yahoo.com\" + \"/script/ScriptServlet\" + \"?aid=\" + ysm_accountid\n        + \"></SCR\" + \"IPT>\");\n    </script>\n}\n\n@helper GetStatCounterHtml(int project, string security) {\n    var securityJson = new HtmlString(HttpUtility.JavaScriptStringEncode(security, addDoubleQuotes: false));\n\n    <script type=\"text/javascript\">\n    var sc_project=@project;\n    var sc_invisible=1;\n    var sc_security=\"@securityJson\";\n    var sc_text=2;\n    var sc_https=1;\n    var scJsHost = ((\"https:\" == document.location.protocol) ? \"https://secure.\" : \"http://www.\");\n    document.write(\"<sc\" + \"ript type='text/javascript' src='\" + scJsHost + \"statcounter.com/counter/counter_xhtml.js'></\" + \"script>\");\n    </script>\n    <noscript>\n    <div class=\"statcounter\">\n    <a title=\"tumblrstatistics\" class=\"statcounter\" href=\"http://www.statcounter.com/tumblr/\"><img class=\"statcounter\" src=\"https://c.statcounter.com/@project/0/@security/1/\" alt=\"tumblr statistics\"/></a></div>\n    </noscript>\n}     \n       "
  },
  {
    "path": "src/Microsoft.Web.Helpers/Facebook.cshtml",
    "content": "﻿@* Generator: WebPagesHelper *@\n\n@using System.Collections.Specialized\n@using System.Globalization\n@using System.Security\n@using System.Text\n@using System.Web.Helpers\n@using System.Web.WebPages.Scope\n@using WebMatrix.Data\n@using WebMatrix.WebData\n\n@functions {\n    \n    private const string FacebookCredentialsTableName = \"webpages_FacebookCredentials\";\n    private const string FacebookCredentialsIdColumn = \"FacebookId\";\n    private const string FacebookCredentialsUserIdColumn = \"UserId\";\n\n    private const string DefaultUserIdColumn = \"UserId\";\n    private const string DefaultUserNameColumn = \"email\";\n    private const string DefaultUserTableName = \"UserProfile\";\n\n    private const string DefaultFacebookPerms = \"email\";\n    private const string DefaultCallbackUrl = \"~/Facebook/Login\";\n    private const string FacebookApiProfileUrl = \"https://graph.facebook.com/me\";\n    private const string FacebookCookieAccessToken = \"access_token\";\n\n    private static readonly object _isInitializedKey = new object();\n    private static readonly object _membershipDBNameKey = new object();\n    private static readonly object _appIdKey = new object();\n    private static readonly object _appSecretKey = new object();\n    private static readonly object _language = new object();\n\n    public static bool HasMembershipIntegration {\n        get {\n            return !MembershipDBName.IsEmpty();\n        }\n    }\n\n    public static bool IsFacebookUserAuthenticated {\n        get {\n            return !GetFacebookCookieInfo(HttpContext, \"uid\").IsEmpty();\n        }\n    }\n\n    public static bool IsFacebookUserAssociated {\n        get {\n            return !GetAssociatedMembershipUserName().IsEmpty();\n        }\n    }\n\n    public static bool IsInitialized {\n        get {\n            return (bool)(ScopeStorage.CurrentScope[_isInitializedKey] ?? false);\n        }\n\n        private set {\n            ScopeStorage.CurrentScope[_isInitializedKey] = value;\n        }\n    }\n\n    public static string MembershipDBName {\n        get {\n            return (string)(ScopeStorage.CurrentScope[_membershipDBNameKey] ?? \"\");\n        }\n\n        set {\n            ScopeStorage.CurrentScope[_membershipDBNameKey] = value;\n        }\n    }\n\n    public static string AppId {\n        get {\n            return (string)(ScopeStorage.CurrentScope[_appIdKey] ?? \"\");\n        }\n\n        set {\n            ScopeStorage.CurrentScope[_appIdKey] = value;\n        }\n    }\n\n    public static string AppSecret {\n        get {\n            return (string)(ScopeStorage.CurrentScope[_appSecretKey] ?? \"\");\n        }\n\n        set {\n            ScopeStorage.CurrentScope[_appSecretKey] = value;\n        }\n    }\n\n    public static string Language {\n        get {\n            return (string)(ScopeStorage.CurrentScope[_language] ?? \"en_US\");\n        }\n\n        set {\n            ScopeStorage.CurrentScope[_language] = value;\n        }\n    }\n    \n    private static HttpContextBase HttpContext {\n        get {\n            return new HttpContextWrapper(System.Web.HttpContext.Current);\n        }\n    }\n\n    ///<summary>\n    /// Initialize the helper with your Facebook application settings. \n    /// \n    /// If the 'membershipDBName' parameter is specified, Facebook membership integration will be enabled, \n    /// allowing users to register and associate their Facebook user account (identified with the e-mail) \n    /// with your site membership and the WebSecurity helper. \n    /// In this case, the helper will initialize the WebSecurity WebMatrix helper automatically (if not done previously) \n    /// and the store the Facebook membership information in the 'membershipDbName' database.    \n    ///</summary>\n    ///<param name=\"appId\">Facebook application id.</param>        \n    ///<param name=\"appSecret\">Facebook application secret.</param>   \n    ///<param name=\"membershipDbName\">Name of the database used for storing the membership data.</param>   \n    public static void Initialize(string appId, string appSecret, string membershipDbName = \"\") {\n        AppId = appId;\n        AppSecret = appSecret;\n        IsInitialized = true;\n\n        if (!membershipDbName.IsEmpty()) {\n            MembershipDBName = membershipDbName;\n\n            InitializeMembershipProviderIfNeeded();\n            InitializeFacebookTableIfNeeded();\n        }\n    }\n\n    ///<summary>\n    /// Retrieves the Facebook profile of current logged in user.\n    ///</summary>\n    public static UserProfile GetFacebookUserProfile() {\n        var accessToken = GetFacebookCookieInfo(HttpContext, FacebookCookieAccessToken);\n\n        if (accessToken.IsEmpty()) {\n            return null;\n        }\n\n        var userProfileUrl = new Uri(new UrlBuilder(FacebookApiProfileUrl).AddParam(FacebookCookieAccessToken, accessToken));\n\n        using (var client = new WebClient()) {\n            using (var receiveStream = client.OpenRead(userProfileUrl)) {\n                var result = new StreamReader(receiveStream).ReadToEnd();\n                var profile = Json.Decode<UserProfile>(result);\n\n                return profile;\n            }\n        }\n    }\n\n    ///<summary>\n    /// Associates the specified User Name (e.g. email, depending on your membership model) with the current Facebook User Id from the logged user.\n    ///</summary>\n    ///<param name=\"userName\">The user name to associate the current logged-in facebook account to.</param>\n    public static void AssociateMembershipAccount(string userName) {\n        if (!IsFacebookUserAuthenticated) {\n            throw new InvalidOperationException(\"No Facebook user is authenticated.\");\n        }\n\n        if (IsFacebookUserAssociated) {\n            throw new InvalidOperationException(\"The authenticated Facebook user is already associated to a membership account.\");\n        }\n\n        using (var db = Database.Open(MembershipDBName)) {\n            var facebookUserId = GetFacebookCookieInfo(HttpContext, \"uid\").As<long>();\n\n            var userId = WebSecurity.GetUserId(userName);\n            db.Execute(String.Format(CultureInfo.InvariantCulture, \"INSERT INTO {0} ({1}, {2}) VALUES (@0, @1)\", FacebookCredentialsTableName, FacebookCredentialsUserIdColumn, FacebookCredentialsIdColumn), \n                userId, facebookUserId);\n\n            // User is registered in the application\n            FormsAuthentication.SetAuthCookie(userName, false);\n        }\n    }\n\n    public static bool MembershipLogin() {\n        var user = GetAssociatedMembershipUserName();\n\n        if (!user.IsEmpty()) {\n            // User is registered in the application\n            FormsAuthentication.SetAuthCookie(user, false);\n            return true;\n        }\n        else {\n            return false;\n        }\n    }\n\n    private static void InitializeMembershipProviderIfNeeded() {\n        var provider = GetMembershipProvider();\n\n        if (IsMembershipProviderInitialized(provider)) {\n            WebSecurity.InitializeDatabaseConnection(MembershipDBName, DefaultUserTableName, DefaultUserIdColumn, DefaultUserNameColumn, true);\n        }\n    }\n\n    private static void InitializeFacebookTableIfNeeded() {\n        using (var db = Database.Open(MembershipDBName)) {\n            var table = db.QuerySingle(\"SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @0\", FacebookCredentialsTableName);\n\n            if (table == null) {\n                db.Execute(String.Format(CultureInfo.InvariantCulture, \"CREATE TABLE {0} ({1} INT NOT NULL, {2} BIGINT NOT NULL)\", FacebookCredentialsTableName, FacebookCredentialsUserIdColumn, FacebookCredentialsIdColumn));\n            }\n        }\n    }\n\n    private static string GetAssociatedMembershipUserName() {\n        var userName = \"\";\n\n        if (IsFacebookUserAuthenticated) {\n            using (var db = Database.Open(MembershipDBName)) {\n                var userId = db.QueryValue(String.Format(CultureInfo.InvariantCulture, \"SELECT {0} FROM {1} WHERE {2} = LOWER(@0)\", FacebookCredentialsUserIdColumn, FacebookCredentialsTableName, FacebookCredentialsIdColumn),\n                    GetFacebookCookieInfo(HttpContext, \"uid\"));\n                if (userId != null) {\n                    userName = GetUserName(userId);\n                }\n            }\n        }\n\n        return userName;\n    }\n\n    private static string GetUserName(int userId) {\n        var userName = \"\";\n\n        using (var db = Database.Open(MembershipDBName)) {\n            var provider = GetMembershipProvider();\n            userName = db.QueryValue(String.Format(CultureInfo.InvariantCulture, \"SELECT {0} FROM {1} WHERE {2} = @0\", provider.UserNameColumn, provider.UserTableName, provider.UserIdColumn), userId);\n        }\n\n        return userName;\n    }\n\n    private static SimpleMembershipProvider GetMembershipProvider() {\n        var provider = Membership.Provider as SimpleMembershipProvider;\n\n        if (provider == null) {\n            throw new InvalidOperationException(\"Simple Membership Provider not found.\");\n        }\n\n        return provider;\n    }\n\n    private static bool IsMembershipProviderInitialized(SimpleMembershipProvider provider) {\n        return provider.UserTableName.IsEmpty() || provider.UserIdColumn.IsEmpty() || provider.UserNameColumn.IsEmpty();\n    }\n\n    internal static string GetFacebookCookieInfo(HttpContextBase httpContext, string key) {\n        var request = httpContext.Request;\n        var name = \"fbs_\" + AppId;\n\n        if (request.Cookies[name] != null) {\n            var value = request.Cookies[name].Value;\n            var args = HttpUtility.ParseQueryString(value.Replace(\"\\\"\", \"\"));\n\n            if (!IsFacebookCookieValid(args)) {\n                throw new InvalidOperationException(\"Invalid Facebook cookie.\");\n            }\n\n            return args[key];\n        }\n        else {\n            return \"\";\n        }\n    }\n\n    private static bool IsFacebookCookieValid(NameValueCollection args) {\n        var payload = new StringBuilder();\n        var keys = args.AllKeys;\n        Array.Sort(keys);\n        foreach (var key in keys) {\n            if (!key.Equals(\"sig\", StringComparison.OrdinalIgnoreCase)) {\n                payload.AppendFormat(\"{0}={1}\", key, args[key]);\n            }\n        }\n        \n        payload.Append(AppSecret);\n\n        // Review: The HMAC uses MD5 which is not cryptographically secure. We need to investigate other Facebook authentication methods.\n        var signature = new StringBuilder();\n        using (var md5 = System.Security.Cryptography.MD5CryptoServiceProvider.Create()) {\n            var hash = md5.ComputeHash(Encoding.ASCII.GetBytes(payload.ToString()));\n            for (int i = 0; i < hash.Length; i++) {\n                signature.Append(hash[i].ToString(\"X2\", CultureInfo.InvariantCulture));\n            }\n        }\n        return String.Equals(args[\"sig\"], signature.ToString(), StringComparison.OrdinalIgnoreCase);\n    }\n\n    public class UserProfile {\n        public string Id { get; set; }\n        public string Name { get; set; }\n        public string First_Name { get; set; }\n        public string Last_Name { get; set; }\n        public string Link { get; set; }\n        public string Bio { get; set; }\n        public string Gender { get; set; }\n        public string Email { get; set; }\n        public string Timezone { get; set; }\n        public string Locale { get; set; }\n        public string Updated_Time { get; set; }\n    }\n\n    private static IHtmlString RawJS(string text) {\n        return new HtmlString(HttpUtility.JavaScriptStringEncode(text));\n    }\n}\n\n@*\nSummary: \n  Initialize the Facebook JavaScript SDK to be able to support the XFBML tags of the social plugins.\n*@\n@helper GetInitializationScripts() {\n    <div id=\"fb-root\"></div>\n    <script type=\"text/javascript\">\n        window.fbAsyncInit = function () {\n            FB.init({ appId: '@RawJS(AppId)', status: true, cookie: true, xfbml: true });\n        };\n        (function () {\n            var e = document.createElement('script'); e.async = true;\n            e.src = document.location.protocol +\n            '//connect.facebook.net/@RawJS(Language)/all.js';\n            document.getElementById('fb-root').appendChild(e);\n        } ());\n\n        function loginRedirect(url) { window.location = url; }\n    </script>\n}\n\n@*\nSummary:\n  Shows a Facebook Login Button, with site membership integration, allowing users to login on your site with their Facebook account (e-mail).\n  To use this method, you need to provide the 'membershipDbName' in the helper's Initialize() method.\n\nParameter: registerUrl\n    Specifies the URL to register the logged user, and associate it with a Membership account.\nParameter: returnUrl\n    Specifies URL to redirect after the user has successfully logged in (i.e. the Facebook User has a Membership Account).\nParameter: callbackUrl\n    Specifies the URL of the WebMatrix page that will handle the Membership login (default URL is ~/Facebook/Login.cshtml).\nParameter: buttonText\n    Specifies the Login Button Text.\nParameter: autoLogoutLink\n    When set to true, if the user is logged into Facebook the button will display a logout button instead.\nParameter: size\n    Specifies the button size: \"small\", \"medium\", \"large\", \"xlarge\".\nParamter: length\n    Specifies the text lenght: \"long\" --> 'Connect with Facebook\" or \"short\" --> 'Connect'.\nParameter: showFaces\n    Specifies whether to display profile photos below the button.\nParameter: extendedPermissions\n    The extendedPermissions parameter can be used to request extended permissions from the user. For example, if you want to incorporate a user's photos into your application, set this value to “user_photos”.\n*@\n@helper LoginButton(\n        string registerUrl,\n        string returnUrl = \"~/\",\n        string callbackUrl = DefaultCallbackUrl,\n        string buttonText = \"\",\n        bool autoLogoutLink = false,\n        string size = \"medium\",\n        string length = \"long\",\n        bool showFaces = false,\n        string extendedPermissions = \"\") {\n\n    var redirectUrl = new UrlBuilder(callbackUrl)\n                            .AddParam(\"registerUrl\", new UrlBuilder(registerUrl))\n                            .AddParam(\"returnUrl\", new UrlBuilder(returnUrl));\n    var onLogin = String.Format(CultureInfo.InvariantCulture, \"loginRedirect('{0}')\", RawJS(redirectUrl));\n    extendedPermissions = extendedPermissions.IsEmpty() ? \"email\" : String.Concat(\"email,\", extendedPermissions);\n\n    <fb:login-button autologoutlink=\"@autoLogoutLink\" size=\"@size\" length=\"@length\" onlogin=\"@onLogin\" show-faces=\"@showFaces\" perms=\"@extendedPermissions\">@buttonText</fb:login-button>        \n}  \n\n@*\nSummary:\n  Shows a Facebook Login Button, without integrating Facebook login with your site membership.\n\nParameter: buttonText\n    Specifies the Login Button Text.\nParameter: autoLogoutLink\n    When set to true, if the user is logged into Facebook the button will display a logout button instead.\nParameter: size\n    The button size: \"small\", \"medium\", \"large\", \"xlarge\".\nParameter: length\n    The text lenght: \"long\" --> 'Connect with Facebook\" or \"short\" --> 'Connect'\nParameter: onLogin\n    Specifies the JavaScript action to execute after the user login. \nParameter: showFaces\n    Whether to display profile photos below the button.\nParameter: extendedPermissions\n    The extendedPermissions parameter can be used to request extended permissions from the user. For example, if you want to incorporate a user's photos into your application, set this value to “user_photos”.\n*@\n@helper LoginButtonTagOnly(\n    string buttonText = \"\",\n    bool autoLogoutLink = false,\n    string size = \"long\",\n    string length = \"short\",\n    string onLogin = \"\",\n    bool showFaces = false,\n    string extendedPermissions = \"\") {\n    <fb:login-button autologoutlink=\"@autoLogoutLink\" size=\"@size\" length=\"@length\" onlogin=\"@onLogin\" show-faces=\"@showFaces\" perms=\"@extendedPermissions\">@buttonText</fb:login-button>\n}\n    \n@*\nSummary:\n  Shows a Facebook Like Button. When the user clicks the Like button on your site, a story appears in the user's friends' News Feed with a link back to your website.\n\nParameter: href\n    The URL to like.\nParameter: buttonLayout\n    The button layout:\n        - standard: Displays social text to the right of the button and friends' profile photos below. \n            Minimum width: 225 pixels. Default width: 450 pixels. Height: 35 pixels (without photos) or 80 pixels (with photos). \n        - button_count: Displays the total number of likes to the right of the button. \n            Minimum width: 90 pixels. Default width: 90 pixels. Height: 20 pixels.\nParameter: showFaces\n    Specifies whether to display profile photos below the button (standard layout only).\nParameter: width\n    The width of the Like button.\nParameter: height\n    The height of the plugin in pixels.\nParameter: action\n    The verb to display on the button: 'like', 'recommend'. \nParameter: font\n    The font to display in the button: 'arial', 'lucida grande', 'segoe ui', 'tahoma', 'trebuchet ms', 'verdana'.\nParameter: colorScheme\n    The color scheme for the like button: 'light' or 'dark'.\nParameter: refLabel\n    A label for tracking referrals; must be less than 50 characters and can contain alphanumeric characters and some punctuation (currently +/=-.:_).\n    \n*@\n@helper LikeButton(\n            string href = \"\",\n            string buttonLayout = \"standard\",\n            bool showFaces = true,\n            int width = 450,\n            int height = 80,\n            string action = \"like\",\n            string font = \"\",\n            string colorScheme = \"light\",\n            string refLabel = \"\"\n            ) {    \n                \n    if (href.IsEmpty()) {\n        href = Request.Url.OriginalString;\n    }\n\n    var src = new UrlBuilder(\"http://www.facebook.com/plugins/like.php\")\n                    .AddParam(\"href\", href)\n                    .AddParam(\"layout\", buttonLayout)\n                    .AddParam(\"show_faces\", showFaces)\n                    .AddParam(\"width\", width)\n                    .AddParam(\"action\", action)\n                    .AddParam(\"colorscheme\", colorScheme)\n                    .AddParam(\"height\", height)\n                    .AddParam(\"font\", font)\n                    .AddParam(\"locale\", Language)\n                    .AddParam(\"ref\", refLabel);\n        \n    <iframe src=\"@src\" scrolling=\"no\" frameborder=\"0\" style=\"border:none; overflow:hidden; width:@(width)px; height:@(height)px;\" allowTransparency=\"true\"></iframe>\n}\n\n@*\nSummary:\n    Shows a Facebook Comments plugin.\n    The Comments Box easily enables your users to comment on your site's content — whether it's for a web page, article, photo, or other piece of content. \n    Then the user can share the comment on Facebook on their Wall and in their friends' streams.\n    An 'Administer Comments' link will appear below the 'Post' button for developers of the application.\n\nParameter: xid\n    An id associated with the comments object (defaults to URL-encoded page URL).\nParameter: width\n    The width of the plugin, in pixels.\nParameter: numPosts\n    The number of comments to display, or 0 to hide all comments. \nParameter: reverse\n    Changes the order of comments and comment area to allow greater customization.\nParameter: removeRoundedBox\n    Removes the rounded box around the text area where comments are written to allow greater customization.\n*@\n@helper Comments(\n            string xid = \"\",\n            int width = 550,\n            int numPosts = 10,\n            bool reverseOrder = false,\n            bool removeRoundedBox = false) {\n    <fb:comments @if (!xid.IsEmpty()) { <text>xid=\"@xid\" </text> }numposts=\"@numPosts\" width=\"@width\" reverse=\"@reverseOrder\" simple=\"@removeRoundedBox\" ></fb:comments>\n}\n\n@*\nSummary:\n    Shows a Facebook Recommendations plugin. The Recommendations plugin shows personalized recommendations to your users.\n    Since the content is hosted by Facebook, the plugin can display personalized recommendations whether or not the user has logged into your site.\n    To generate the recommendations, the plugin considers all the social interactions with URLs from your site.\n    For a logged in Facebook user, the plugin will give preference to and highlight objects her friends have interacted with.\n    \n    *NOTE*: This helper method requires that your site is published into a public address where others can use it. Check this tutorial on publishing with WebMatrix: http://www.asp.net/webmatrix/tutorials/publish-a-website \n\nParameter: site\n    The address of your published site. For example \"www.fourthcoffee.com\"\nParameter: width\n    The width of the plugin in pixels.\nParameter: height\n    The height of the plugin in pixels.\nParameter: showHeader\n    Whether to show a 'Recommendations' title bar.\nParameter: colorScheme\n    The color scheme of the plugin: 'light' or 'dark'.\nParameter: font\n    The font name for the plugin.\nParameter: borderColor\n    The border color of the plugin. Use common color names as Red, White, Black, and so on.\nParameter: filter\n    Allows you to filter which URLs are shown in the plugin. The plugin will only include URLs which contain the filter term in the first two path parameters of the URL.\nParameter: refLabel\n    A label for tracking referrals; must be less than 50 characters and can contain alphanumeric characters and some punctuation (currently +/=-.:_).\n*@\n@helper Recommendations(\n            string site = \"\",\n            int width = 300,\n            int height = 300,\n            bool showHeader = true,\n            string colorScheme = \"light\",\n            string font = \"\",\n            string borderColor = \"\",\n            string filter = \"\",\n            string refLabel = \"\"\n    ) {\t\n        if (site.IsEmpty()) {\n            site = Request.Url.Host;\n        }\n\n    var src = new UrlBuilder(\"http://www.facebook.com/plugins/recommendations.php\")\n                    .AddParam(\"site\", site)\n                    .AddParam(\"width\", width)\n                    .AddParam(\"height\", height)\n                    .AddParam(\"header\", showHeader)\n                    .AddParam(\"colorscheme\", colorScheme)\n                    .AddParam(\"font\", font)\n                    .AddParam(\"border_color\", borderColor)\n                    .AddParam(\"filter\", filter)\n                    .AddParam(\"ref\", refLabel)\n                    .AddParam(\"locale\", Language);\n    \n    <iframe src=\"@src\" scrolling=\"no\" frameborder=\"0\" style=\"border:none; overflow:hidden; width:@(width)px; height:@(height)px;\" allowTransparency=\"true\"></iframe>\n}\n\n@*\nSummary:\n    Shows a Facebook Like Box. The Like Box is a social plugin that enables Facebook Page owners to attract and gain Likes from their own website.\n    The Like Box enables users to:\n        - See how many users already like this page, and which of their friends like it too\n        - Read recent posts from the page\n        - Like the page with one click, without needing to visit the page   \n\nParameter: href\n    The URL of the Facebook Page for this Like box.\nParameter: width\n    The width of the plugin in pixels.\nParameter: height\n    The height of the plugin in pixels.\nParameter: colorScheme\n    The color scheme of the plugin: 'light' or 'dark'.\nParameter: connections\n    Number of shown users who have liked this Page. Use 0 to avoid showing the users box.\nParameter: showStream\n    Shows the profile stream for the public profile of the page. \nParameter: showHeader\n    Shows the 'Find us on Facebook' bar at top. Only shown when either stream or connections are present.\n*@\n@helper LikeBox(\n            string href,\n            int width = 292,\n            int height = 587,\n            string colorScheme = \"light\",\n            int connections = 10,\n            bool showStream = true,\n            bool showHeader = true) {   \n    \n    var src = new UrlBuilder(\"http://www.facebook.com/plugins/likebox.php\")\n                    .AddParam(\"href\", href)\n                    .AddParam(\"width\", width)\n                    .AddParam(\"height\", height)\n                    .AddParam(\"header\", showHeader)\n                    .AddParam(\"colorscheme\", colorScheme)\n                    .AddParam(\"connections\", connections)\n                    .AddParam(\"stream\", showStream)\n                    .AddParam(\"header\", showHeader)\n                    .AddParam(\"locale\", Language);\n                                 \n    <iframe src=\"@src\" scrolling=\"no\" frameborder=\"0\" style=\"border:none; overflow:hidden; width:@(width)px; height:@(height)px;\" allowTransparency=\"true\"></iframe>                \n}\n\n@*\nSummary:\n    Shows a Facebook Facepile plugin.\n    The Facepile plugin shows the Facebook profile pictures of the user's friends who have already signed up for your site. \n    The plugin doesn't show up if the user is logged out of Facebook or doesn't have friends who have signed up for your site using Facebook.\n\nParameter: maxRows\n    The maximum number of rows of profile pictures to show. The plugin dynamically sizes its height; for example, if you specify a maximum of four rows, and there are only enough friends to fill two rows, the height of the plugin will be only what is needed for two rows of profile pictures. \nParameter: width\n    The width of the plugin in pixels. \n*@\n@helper Facepile(\n            int maxRows = 1,\n            int width = 200) {\n    <fb:facepile max-rows=\"@maxRows\" width=\"@width\"></fb:facepile>\n}\n\n@*\nSummary:\n    Shows a Facebook Live Stream plugin.\n    The Live Stream plugin lets users visiting your site or application share activity and comments in real time. \n    The Live Stream Box works best when you are running a real-time event, like live streaming video for concerts, speeches, or webcasts, live Web chats, \n    webinars, massively multiplayer games.\n\nParameter: width\n    The width of the plugin in pixels.\nParameter: height\n    The height of the plugin in pixels.\nParameter: xid\n    If you have multiple live stream boxes on the same page, specify a unique 'xid' for each.\nParameter: viaUrl\n    The URL that users are redirected to when they click on your app name on a status (if not specified, your Connect URL is used).\nParameter: alwaysPostToFriends\n    If set, all user posts will always go to their profile. This option should only be used when users' posts are likely to make sense outside of the context of the event.\n*@\n@helper LiveStream(\n            int width = 400,\n            int height = 500,\n            string xid = \"\",\n            string viaUrl = \"\",\n            bool alwaysPostToFriends = false) {\n       \n                \n    var builder = new UrlBuilder(\"http://www.facebook.com/plugins/live_stream_box.php\")\n        .AddParam(\"app_id\", AppId)\n        .AddParam(\"width\", width)\n        .AddParam(\"height\", height)\n        .AddParam(\"always_post_to_friends\", alwaysPostToFriends)\n        .AddParam(\"locale\", Language);\n\n    if (!xid.IsEmpty()) {\n        builder.AddParam(\"xid\", xid);\n        builder.AddParam(\"via_url\", viaUrl);\n    }\n    \n    <iframe src=\"@builder\" scrolling=\"no\" frameborder=\"0\" style=\"border:none; overflow:hidden; width:@(width)px; height:@(height)px;\" allowTransparency=\"true\"></iframe>\n}\n\n@*\nSummary:\n    Shows a Facebook Activity Feed plugin.    \n    The Activity Feed plugin displays the most interesting recent activity taking place on your site. Since the content is hosted by Facebook, \n    the plugin can display personalized content whether or not the user has logged into your site. The activity feed displays stories both when \n    users like content on your site and when users share content from your site back to Facebook.\n    \n    *NOTE*: This helper method requires that your site is published into a public address where others can use it. Check this tutorial on publishing with WebMatrix: http://www.asp.net/webmatrix/tutorials/publish-a-website \n\nParameter: site\n    The address of your published site. For example \"www.fourthcoffee.com\"\nParameter: width\n    The width of the plugin in pixels.\nParameter: height\n    The height of the plugin in pixels.\nParameter: showHeader\n    Show the 'Recent Activity' title bar.\nParameter: colorScheme\n    The color scheme of the plugin: 'light' or 'dark'.\nParameter: font\n    The font name for the plugin.\nParameter: borderColor\n    The border color of the plugin. Use common color names as Red, White, Black, and so on.\nParameter: showRecommendations\n    Whether to show recommendations on the activity feed.\n*@\n@helper ActivityFeed(\n        string site = \"\",\n        int width = 300,\n        int height = 300,\n        bool showHeader = true,\n        string colorScheme = \"light\",\n        string font = \"\",\n        string borderColor = \"\",\n        bool showRecommendations = false) {\n    if (site.IsEmpty()) {\n        site = Request.Url.Host;\n    }\n\n    var src = new UrlBuilder(\"http://www.facebook.com/plugins/activity.php\")\n                    .AddParam(\"site\", site)\n                    .AddParam(\"width\", width)\n                    .AddParam(\"height\", height)\n                    .AddParam(\"header\", showHeader)\n                    .AddParam(\"colorscheme\", colorScheme)\n                    .AddParam(\"font\", font)\n                    .AddParam(\"border_color\", borderColor)\n                    .AddParam(\"recommendations\", showRecommendations)\n                    .AddParam(\"locale\", Language);                \n                    \n    <iframe src=\"@src\" scrolling=\"no\" frameborder=\"0\" style=\"border:none; overflow:hidden; width:300px; height:300px;\" allowTransparency=\"true\"></iframe>\n}\n\n@*\nSummary:\n    OpenGraph properties allows you to specify structured information about your web pages to show up your pages richly across Facebook and enable Facebook users to establish connections to your pages.\n    \n    Use this method to show OpenGraph page data, as the page title, URL, and so on.\n    \n    *NOTE*: It is important to notice that the OpenGraph properties are read directly from your site by Facebook, therefore your site needs to be published into a public address to see the OpenGraph properties working. \n    Check this tutorial on publishing with WebMatrix: http://www.asp.net/webmatrix/tutorials/publish-a-website \n\nParameter: siteName\n    A human-readable name for your site, e.g., \"Fourth Coffee\".\nParameter: title\n    The title of your page as it should appear within Facebook, e.g., \"Pecan Pie\".\nParameter: type\n    The type of your page, e.g., \"food\". See the complete list of supported types here: http://developers.facebook.com/docs/opengraph#types\nParameter: url\n    The canonical URL of your object that will be used as its permanent ID in the graph, e.g., http://www.fourthcoffe.com/Product/1/.\nParameter: imageUrl\n    An image URL which should represent your page within the graph. The image must be at least 50px by 50px and have a maximum aspect ratio of 3:1.\nParameter: description\n    A one to two sentence description of your page.\n*@\n@helper OpenGraphRequiredProperties(\n    string siteName,\n    string title,\n    string type,\n    string url,\n    string imageUrl,\n    string description = \"\") {  \n    <meta property=\"og:site_name\" content=\"@siteName\"/>\n    <meta property=\"fb:app_id\" content=\"@AppId\"/>     \n    <meta property=\"og:title\" content=\"@title\"/>\n    <meta property=\"og:type\" content=\"@type\"/>\n    <meta property=\"og:url\" content=\"@url\"/>\n    <meta property=\"og:image\" content=\"@imageUrl\"/>        \n        if (!description.IsEmpty()) {\n    <meta property=\"og:description\" content=\"@description\"/>\n        }\n}\n\n@*\nSummary:\n    OpenGraph properties allows you to specify structured information about your web pages to show up your pages richly across Facebook and enable Facebook users to establish connections to your pages.\n    \n    Use this method to show page location data. This is useful if your pages is a business profile or about anything else with a real-world location. You can specify location via latitude and longitude, a full address, or both.\n    \n    *NOTE*: It is important to notice that the OpenGraph properties are read directly from your site by Facebook, therefore your site needs to be published into a public address to see the OpenGraph properties working. \n    Check this tutorial on publishing with WebMatrix: http://www.asp.net/webmatrix/tutorials/publish-a-website \n*@     \n@helper OpenGraphLocationProperties(\n    string latitude = \"\",\n    string longitude = \"\",\n    string streetAddress = \"\",\n    string locality = \"\",\n    string region = \"\",\n    string postalCode = \"\",\n    string countryName = \"\") {        \n        if (!latitude.IsEmpty()) {\n    <meta property=\"og:latitude\" content=\"@latitude\"/>\n        }\n        if (!longitude.IsEmpty()) {\n    <meta property=\"og:longitude\" content=\"@longitude\"/>\n        }\n        if (!streetAddress.IsEmpty()) {\n    <meta property=\"og:street-address\" content=\"@streetAddress\"/>\n        }\n        if (!locality.IsEmpty()) {\n    <meta property=\"og:locality\" content=\"@locality\"/>\n        }\n        if (!region.IsEmpty()) {\n    <meta property=\"og:region\" content=\"@region\"/>\n        }\n        if (!postalCode.IsEmpty()) {\n    <meta property=\"og:postal-code\" content=\"@postalCode\"/>\n        }\n        if (!countryName.IsEmpty()) {\n    <meta property=\"og:country-name\" content=\"@countryName\"/>\n        }\n}\n\n@*\nSummary:\n    OpenGraph properties allows you to specify structured information about your web pages to show up your pages richly across Facebook and enable Facebook users to establish connections to your pages.\n    \n    Use this method to show contact information about your page. Consider including contact information if your page is about an entity that can be contacted.\n    \n    *NOTE*: It is important to notice that the OpenGraph properties are read directly from your site by Facebook, therefore your site needs to be published into a public address to see the OpenGraph properties working. \n    Check this tutorial on publishing with WebMatrix: http://www.asp.net/webmatrix/tutorials/publish-a-website \n*@\n@helper OpenGraphContactProperties(\n    string email = \"\",\n    string phoneNumber = \"\",\n    string faxNumber = \"\") {        \n    \n        if (!email.IsEmpty()) {\n    <meta property=\"og:email\" content=\"@email\"/>\n        }\n        if (!phoneNumber.IsEmpty()) {\n    <meta property=\"og:phone_number\" content=\"@phoneNumber\"/>\n        }\n        if (!faxNumber.IsEmpty()) {\n    <meta property=\"og:fax_number\" content=\"@faxNumber\"/>\n        }\n    \n}\n\n@*\nSummary:\n    Use this method inside your opening HTML tag for W3C compatibility.\n        For example: <html xmlns=\"http://www.w3.org/1999/xhtml\" @Facebook.FbmlNamespaces()>         \n*@\n@helper FbmlNamespaces() {<text>xmlns:fb=\"http://www.facebook.com/2008/fbml\" xmlns:og=\"http://opengraphprotocol.org/schema/\"</text>}\n"
  },
  {
    "path": "src/Microsoft.Web.Helpers/FileUpload.cshtml",
    "content": "﻿@* Generator: WebPagesHelper *@\n\n@using System.Globalization\n@using System.Web\n@using Microsoft.Internal.Web.Utils\n@using Resources\n\n@functions {\n    private class FileUploadTracker {\n        private static readonly object _countKey = new object();\n        private static readonly object _scriptAlreadyRendered = new object();\n        private readonly HttpContextBase _httpContext;\n\n        public FileUploadTracker(HttpContextBase httpContext) {\n            _httpContext = httpContext;\n        }\n\n        public bool ScriptAlreadyRendered {\n            get {\n                bool? rendered = _httpContext.Items[_scriptAlreadyRendered] as bool?;\n                return rendered.HasValue && rendered.Value;\n            }\n            set {\n                _httpContext.Items[_scriptAlreadyRendered] = value;\n            }\n        }\n\n        public int RenderCount {\n            get {\n                int? count = _httpContext.Items[_countKey] as int?;\n                if (!count.HasValue) {\n                    count = 0;\n                }\n                return count.Value;\n            }\n            set {\n                _httpContext.Items[_countKey] = value;\n            }\n        }\n    }\n}\n\n@helper GetHtml(string name = null,\n            int initialNumberOfFiles = 1,\n            bool allowMoreFilesToBeAdded = true,\n            bool includeFormTag = true,\n            string addText = null,\n            string uploadText = null) {\n    @_GetHtml(new HttpContextWrapper(HttpContext.Current), name, initialNumberOfFiles, allowMoreFilesToBeAdded,\n                includeFormTag, addText, uploadText)\n}\n\n@helper _GetHtml(HttpContextBase context, string name, int initialNumberOfFiles, \n        bool allowMoreFilesToBeAdded, bool includeFormTag, string addText, string uploadText) {\n    \n    if (initialNumberOfFiles < 0) {\n        throw new ArgumentOutOfRangeException(\n            \"initialNumberOfFiles\",\n            String.Format(CultureInfo.InvariantCulture, CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, \"0\"));\n    }\n    var tracker = new FileUploadTracker(context);\n    int count = tracker.RenderCount++;\n\n    name = name ?? \"fileUpload\";\n    uploadText = uploadText ?? HelpersToolkitResources.FileUpload_Upload;\n    addText = addText ?? HelpersToolkitResources.FileUpload_AddMore;\n\n\n    if (allowMoreFilesToBeAdded && !tracker.ScriptAlreadyRendered) {\n        tracker.ScriptAlreadyRendered = true;\n\n        <script type=\"text/javascript\"> \n            if (!window[\"FileUploadHelper\"]) window[\"FileUploadHelper\"] = {};  \n            FileUploadHelper.addInputElement = function(index, name) {  \n                var inputElem = document.createElement(\"input\");  \n                inputElem.type = \"file\";  \n                inputElem.name = name;  \n                var divElem = document.createElement(\"div\");  \n                divElem.appendChild(inputElem.cloneNode(false));   \n                var inputs = document.getElementById(\"file-upload-\" + index);  \n                inputs.appendChild(divElem);  \n            } \n        </script>\n    }\n\n    if (includeFormTag) {\n        @:<form action=\"\" enctype=\"multipart/form-data\" method=\"post\">\n    }\n    <div class=\"file-upload\" id=\"file-upload-@(count)\">\n        @for(int i = 0; i < initialNumberOfFiles; i++) {\n            <div>\n                <input name=\"@name\" type=\"file\" />\n            </div>\n        }\n    </div>\n\n    if (allowMoreFilesToBeAdded || includeFormTag) {\n        <div class=\"file-upload-buttons\">\n        @if (allowMoreFilesToBeAdded) {\n            <a href=\"#\" onclick=\"FileUploadHelper.addInputElement(@count, @HttpUtility.JavaScriptStringEncode(name, addDoubleQuotes: true)); return false;\">@addText</a>\n        }\n        @if (includeFormTag) {\n            <input type=\"submit\" value=\"@uploadText\" />\n        }\n        </div>\n    }\n    \n    if (includeFormTag) {\n        @:</form>\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Helpers/GamerCard.cshtml",
    "content": "﻿@* Generator: WebPagesHelper *@\n\n@using Microsoft.Internal.Web.Utils\n\n@helper GetHtml(string gamerTag) {\n    if (gamerTag.IsEmpty()) {\n        throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"gamerTag\");\n    }\n    <iframe frameborder=\"0\" height=\"140\" scrolling=\"no\" src=\"http://gamercard.xbox.com/@(HttpUtility.UrlPathEncode(gamerTag)).card\" width=\"204\">@gamerTag</iframe>\n}"
  },
  {
    "path": "src/Microsoft.Web.Helpers/GlobalSuppressions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.Facebook.#GetInitializationScripts()\", Justification = \"It is analogous to the get pattern users are familiar with\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.Facebook.#GetFacebookUserProfile()\", Justification = \"It is analogous to the get pattern users are familiar with\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1053:StaticHolderTypesShouldNotHaveConstructors\", Scope = \"type\", Target = \"Microsoft.Web.Helpers.Analytics\", Justification = \"This is the default format in which helpers are generated.\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1053:StaticHolderTypesShouldNotHaveConstructors\", Scope = \"type\", Target = \"Microsoft.Web.Helpers.Bing\", Justification = \"This is the default format in which helpers are generated.\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1053:StaticHolderTypesShouldNotHaveConstructors\", Scope = \"type\", Target = \"Microsoft.Web.Helpers.Facebook\", Justification = \"This is the default format in which helpers are generated.\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1053:StaticHolderTypesShouldNotHaveConstructors\", Scope = \"type\", Target = \"Microsoft.Web.Helpers.FileUpload\", Justification = \"This is the default format in which helpers are generated.\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1053:StaticHolderTypesShouldNotHaveConstructors\", Scope = \"type\", Target = \"Microsoft.Web.Helpers.GamerCard\", Justification = \"This is the default format in which helpers are generated.\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1053:StaticHolderTypesShouldNotHaveConstructors\", Scope = \"type\", Target = \"Microsoft.Web.Helpers.LinkShare\", Justification = \"This is the default format in which helpers are generated.\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1053:StaticHolderTypesShouldNotHaveConstructors\", Scope = \"type\", Target = \"Microsoft.Web.Helpers.Maps\", Justification = \"This is the default format in which helpers are generated.\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1053:StaticHolderTypesShouldNotHaveConstructors\", Scope = \"type\", Target = \"Microsoft.Web.Helpers.ReCaptcha\", Justification = \"This is the default format in which helpers are generated.\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"2#\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.Facebook.#LoginButton(System.String,System.String,System.String,System.String,System.Boolean,System.String,System.String,System.Boolean,System.String)\", Justification = \"We prefer strings to URIs for helpers\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"4#\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.Facebook.#OpenGraphRequiredProperties(System.String,System.String,System.String,System.String,System.String,System.String)\", Justification = \"We prefer strings to URIs for helpers\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"0#\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.Facebook.#LoginButton(System.String,System.String,System.String,System.String,System.Boolean,System.String,System.String,System.Boolean,System.String)\", Justification = \"We prefer strings to URIs for helpers\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.Facebook.#LoginButton(System.String,System.String,System.String,System.String,System.Boolean,System.String,System.String,System.Boolean,System.String)\", Justification = \"We prefer strings to URIs for helpers\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.Bing.#SearchBox(System.String,System.String,System.String)\", Justification = \"We prefer strings to URIs for helpers\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"3#\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.Facebook.#OpenGraphRequiredProperties(System.String,System.String,System.String,System.String,System.String,System.String)\", Justification = \"We prefer strings to URIs for helpers\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"3#\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.Facebook.#LiveStream(System.Int32,System.Int32,System.String,System.String,System.Boolean)\", Justification = \"We prefer strings to URIs for helpers\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1056:UriPropertiesShouldNotBeStrings\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.Bing.#SiteUrl\", Justification = \"We prefer strings to URIs for helpers\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1034:NestedTypesShouldNotBeVisible\", Scope = \"type\", Target = \"Microsoft.Web.Helpers.Facebook+UserProfile\", Justification = \"The type is consumed but never instantiated by a user\")]\n[assembly: SuppressMessage(\"Microsoft.Globalization\", \"CA1308:NormalizeStringsToUppercase\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.Maps.#GetBingHtml(System.String,System.String,System.String,System.String,System.String,System.String,System.Int32,System.String,System.Boolean,System.String,System.Collections.Generic.IEnumerable`1<Microsoft.Web.Helpers.Maps+MapLocation>)\", Justification = \"We're printing a JSON value that needs to be lower case\")]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"Facepile\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.Facebook.#Facepile(System.Int32,System.Int32)\", Justification = \"Facebook related term\")]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"Fbml\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.Facebook.#FbmlNamespaces()\", Justification = \"Facebook related term\")]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"num\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.Facebook.#Comments(System.String,System.Int32,System.Int32,System.Boolean,System.Boolean)\", Justification = \"num is not Hungarian notation\")]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"xid\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.Facebook.#Comments(System.String,System.Int32,System.Int32,System.Boolean,System.Boolean)\", Justification = \"Facebook related term\")]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"xid\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.Facebook.#LiveStream(System.Int32,System.Int32,System.String,System.String,System.Boolean)\", Justification = \"Facebook related term\")]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1709:IdentifiersShouldBeCasedCorrectly\", MessageId = \"Re\", Scope = \"type\", Target = \"Microsoft.Web.Helpers.ReCaptcha\")]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1726:UsePreferredTerms\", MessageId = \"Logout\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.Facebook.#LoginButton(System.String,System.String,System.String,System.String,System.Boolean,System.String,System.String,System.Boolean,System.String)\", Justification = \"We use login and logout in WebMatrix.Security\")]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1726:UsePreferredTerms\", MessageId = \"Login\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.Facebook.#LoginButtonTagOnly(System.String,System.Boolean,System.String,System.String,System.String,System.Boolean,System.String)\", Justification = \"We use login and logout in WebMatrix.Security\")]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1726:UsePreferredTerms\", MessageId = \"Logout\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.Facebook.#LoginButtonTagOnly(System.String,System.Boolean,System.String,System.String,System.String,System.Boolean,System.String)\", Justification = \"We use login and logout in WebMatrix.Security\")]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1726:UsePreferredTerms\", MessageId = \"Login\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.Facebook.#LoginButton(System.String,System.String,System.String,System.String,System.Boolean,System.String,System.String,System.Boolean,System.String)\", Justification = \"We use login and logout in WebMatrix.Security\")]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1726:UsePreferredTerms\", MessageId = \"Login\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.Facebook.#MembershipLogin()\", Justification = \"We use login and logout in WebMatrix.Security\")]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1726:UsePreferredTerms\", MessageId = \"Login\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.LinkShare.#BitlyLogin\", Justification = \"We use login and logout in WebMatrix.Security\")]\n[assembly: SuppressMessage(\"Microsoft.Usage\", \"CA2208:InstantiateArgumentExceptionsCorrectly\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.Bing.#SiteUrl\", Justification = \"Property name is used instead of the generic term value to make it simpler to debug.\")]\n[assembly: SuppressMessage(\"Microsoft.Usage\", \"CA2208:InstantiateArgumentExceptionsCorrectly\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.GamerCard.#GetHtml(System.String)\")]\n[assembly: SuppressMessage(\"Microsoft.Usage\", \"CA2208:InstantiateArgumentExceptionsCorrectly\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.Bing.#SiteTitle\", Justification = \"Property name is used instead of the generic term value to make it simpler to debug.\")]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1707:IdentifiersShouldNotContainUnderscores\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.Facebook+UserProfile.#Updated_Time\", Justification = \"This is serailzed from a JSON schema, so member names have to be exactly this way.\")]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1707:IdentifiersShouldNotContainUnderscores\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.Facebook+UserProfile.#Last_Name\", Justification = \"This is serailzed from a JSON schema, so member names have to be exactly this way.\")]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1707:IdentifiersShouldNotContainUnderscores\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.Facebook+UserProfile.#First_Name\", Justification = \"This is serailzed from a JSON schema, so member names have to be exactly this way.\")]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"Timezone\", Scope = \"member\", Target = \"Microsoft.Web.Helpers.Facebook+UserProfile.#Timezone\", Justification = \"This is serailzed from a JSON schema, so member names have to be exactly this way.\")]\n"
  },
  {
    "path": "src/Microsoft.Web.Helpers/Gravatar.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq;\nusing System.Text;\nusing System.Web;\nusing System.Web.Helpers;\nusing Microsoft.Internal.Web.Utils;\nusing Resources;\n\nnamespace Microsoft.Web.Helpers\n{\n    public static class Gravatar\n    {\n        private const string GravatarUrl = \"http://www.gravatar.com/avatar/\";\n\n        // review - extract conversion of anonymous object to html attributes string into separate helper\n        public static HtmlString GetHtml(string email, int imageSize = 80, string defaultImage = null,\n                                         GravatarRating rating = GravatarRating.Default, string imageExtension = null, object attributes = null)\n        {\n            bool altSpecified = false;\n            string url = GetUrl(email, imageSize, defaultImage, rating, imageExtension);\n            StringBuilder html = new StringBuilder(String.Format(CultureInfo.InvariantCulture, \"<img src=\\\"{0}\\\" \", url));\n            if (attributes != null)\n            {\n                foreach (var p in attributes.GetType().GetProperties().OrderBy(p => p.Name))\n                {\n                    if (!p.Name.Equals(\"src\", StringComparison.OrdinalIgnoreCase))\n                    {\n                        object value = p.GetValue(attributes, null);\n                        if (value != null)\n                        {\n                            string encodedValue = HttpUtility.HtmlAttributeEncode(value.ToString());\n                            html.Append(String.Format(CultureInfo.InvariantCulture, \"{0}=\\\"{1}\\\" \", p.Name, encodedValue));\n                        }\n                        if (p.Name.Equals(\"alt\", StringComparison.OrdinalIgnoreCase))\n                        {\n                            altSpecified = true;\n                        }\n                    }\n                }\n            }\n            if (!altSpecified)\n            {\n                html.Append(\"alt=\\\"gravatar\\\" \");\n            }\n            html.Append(\"/>\");\n            return new HtmlString(html.ToString());\n        }\n\n        // See: http://en.gravatar.com/site/implement/url\n        [SuppressMessage(\"Microsoft.Design\", \"CA1055:UriReturnValuesShouldNotBeStrings\", Justification = \"Strings are easier to work with for Plan9 scenario\")]\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1308:NormalizeStringsToUppercase\", Justification = \"Gravatar.com requires lowercase\")]\n        public static string GetUrl(string email, int imageSize = 80, string defaultImage = null,\n                                    GravatarRating rating = GravatarRating.Default, string imageExtension = null)\n        {\n            if (String.IsNullOrEmpty(email))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"email\");\n            }\n            if ((imageSize <= 0) || (imageSize > 512))\n            {\n                throw new ArgumentException(HelpersToolkitResources.Gravatar_InvalidImageSize, \"imageSize\");\n            }\n\n            StringBuilder url = new StringBuilder(GravatarUrl);\n            email = email.Trim().ToLowerInvariant();\n            url.Append(Crypto.Hash(email, algorithm: \"md5\").ToLowerInvariant());\n\n            if (!String.IsNullOrEmpty(imageExtension))\n            {\n                if (!imageExtension.StartsWith(\".\", StringComparison.Ordinal))\n                {\n                    url.Append('.');\n                }\n                url.Append(imageExtension);\n            }\n\n            url.Append(\"?s=\");\n            url.Append(imageSize);\n\n            if (rating != GravatarRating.Default)\n            {\n                url.Append(\"&r=\");\n                url.Append(rating.ToString().ToLowerInvariant());\n            }\n\n            if (!String.IsNullOrEmpty(defaultImage))\n            {\n                url.Append(\"&d=\");\n                url.Append(HttpUtility.UrlEncode(defaultImage));\n            }\n\n            return HttpUtility.HtmlAttributeEncode(url.ToString());\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Helpers/GravatarRating.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace Microsoft.Web.Helpers\n{\n    public enum GravatarRating\n    {\n        Default,\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"G\", Justification = \"Matches the gravatar.com rating. Suppressed in source because this is a one-time occurrence\")]\n        G,\n        PG,\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"R\", Justification = \"Matches the gravatar.com rating. Suppressed in source because this is a one-time occurrence\")]\n        R,\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"X\", Justification = \"Matches the gravatar.com rating. Suppressed in source because this is a one-time occurrence\")]\n        X\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Helpers/LinkShare.cshtml",
    "content": "﻿@* Generator: WebPagesHelper *@\n\n@using System.Globalization\n@using System.Text\n@using System.Web.WebPages.Scope\n@using Microsoft.Internal.Web.Utils\n@using Resources;\n@functions {\n    internal static readonly object _bitlyApiKey = new object();\n    internal static readonly object _bitlyLogin = new object();\n    private static readonly Lazy<IEnumerable<LinkShareSite>> _allSites = new Lazy<IEnumerable<LinkShareSite>>(() =>\n        from site in (LinkShareSite[])Enum.GetValues(typeof(LinkShareSite))\n#pragma warning disable 0618\n        where site != LinkShareSite.All\n#pragma warning restore 0618\n        select site\n    );\n\n    public static string BitlyApiKey {\n        get {\n            return ScopeStorage.CurrentScope[_bitlyApiKey] as string;\n        }\n\n        set {\n            if (value == null) {\n                throw new ArgumentNullException(\"value\");\n            }\n            ScopeStorage.CurrentScope[_bitlyApiKey] = value;\n        }\n    }\n\n    public static string BitlyLogin {\n        get {\n            return ScopeStorage.CurrentScope[_bitlyLogin] as string;\n        }\n\n        set {\n            if (value == null) {\n                throw new ArgumentNullException(\"value\");\n            }\n            ScopeStorage.CurrentScope[_bitlyLogin] = value;\n        }\n    }\n\n    private static string GetShortenedUrl(string pageLinkBack) {\n        if (BitlyLogin.IsEmpty() || BitlyApiKey.IsEmpty()) {\n            return pageLinkBack;\n        }\n        string encodedPageLinkBack = HttpUtility.UrlEncode(pageLinkBack);\n        string key = \"Bitly_pageLinkBack_\" + BitlyApiKey + \"_\" + encodedPageLinkBack;\n        string shortUrl = WebCache.Get(key) as string;\n        if (shortUrl != null) {\n            return shortUrl;\n        }\n\n        string bitlyReq = \"http://api.bit.ly/v3/shorten?format=txt&longUrl=\" + encodedPageLinkBack + \"&login=\" + BitlyLogin + \"&apiKey=\" + BitlyApiKey;\n        try {\n            shortUrl = GetWebResponse(bitlyReq);\n        }\n        catch (WebException) {\n            return pageLinkBack;\n        }\n        if (shortUrl != null) {\n            WebCache.Set(key, shortUrl);\n            return shortUrl;\n        }\n        return pageLinkBack;\n    }\n\n    private static string GetWebResponse(string address) {\n        WebRequest request = WebRequest.Create(address);\n        request.Method = \"GET\";\n        request.Timeout = 5 * 1000; //5 seconds\n        using (var response = (HttpWebResponse)request.GetResponse()) {\n            if (response.StatusCode != HttpStatusCode.OK) {\n                return null;\n            }\n            using (Stream stream = response.GetResponseStream()) {\n                using (MemoryStream memStream = new MemoryStream()) {\n                    stream.CopyTo(memStream);\n                    // Review: Should we use the ContentEncoding from response?\n                    return Encoding.UTF8.GetString(memStream.ToArray());\n                }\n            }\n        }\n    }\n\n    /// <summary>\n    /// Returns an ordered list of LinkShareSite based on position of \"All\" parameter occurs in the list.\n    /// </summary>\n    /// <remarks>\n    /// The LinkShareSite is accepted as a params array.\n    /// In the event that no value is provided or the LinkShareSite.All is the first param, we display all the sites in the order they appear in the enum.\n    /// If not, the items we look for the first occurence of LinkShareSite.All in the array. \n    /// The items that appear before this appear in the order they are specified. The All is replaced by all items in the enum that were not already specified by the user \n    /// in the order they appear in the enum.\n    /// e.g.  sites = [] { Twitter, Facebook, Digg, All }\n    /// Would result in returning {Twitter, Facebook, Digg, Delicious, Reddit, StumbleUpon} \n    /// </remarks>\n    internal static IEnumerable<LinkShareSite> GetSitesInOrder(LinkShareSite[] linkSites) {\n        var allSites = _allSites.Value;\n        if (linkSites == null || !linkSites.Any() || linkSites.First() == LinkShareSite.All) {\n            // Show all sites\n            return allSites;\n        }\n        var result = linkSites.TakeWhile(c => c != LinkShareSite.All).ToList();\n        if (result.Count != linkSites.Length) {\n            return Enumerable.Concat(result, allSites.Except(result));\n        }\n        else {\n            return result;\n        }\n    }\n\n    private static void ConstructPageLinkBack(ref string pageLinkBack, out string shortenedUrl) {\n        HttpContext context = HttpContext.Current;\n        if ((pageLinkBack == null) && (context != null)) {\n            pageLinkBack = context.Request.Url.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.Unescaped);\n        }\n        shortenedUrl = GetShortenedUrl(pageLinkBack);\n    }\n}\n\n@helper GetHtml(string pageTitle,\n    string pageLinkBack = null,\n    string twitterUserName = null,\n    string additionalTweetText = null,\n    params LinkShareSite[] linkSites) {\n\n    if (pageTitle.IsEmpty()) {\n        throw new ArgumentException(String.Format(CultureInfo.CurrentUICulture, CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"pageTitle\"), \"pageTitle\");\n    }\n\n    string shortenedUrl;\n    ConstructPageLinkBack(ref pageLinkBack, out shortenedUrl);\n\n    pageLinkBack = HttpUtility.UrlEncode(pageLinkBack);\n    shortenedUrl = HttpUtility.UrlEncode(shortenedUrl);\n    pageTitle = HttpUtility.UrlEncode(pageTitle);\n\n    foreach (var site in GetSitesInOrder(linkSites)) {\n        switch (site) {\n            case LinkShareSite.Delicious:\n                <a href=\"http://delicious.com/save?v=5&amp;noui&amp;jump=close&amp;url=@(shortenedUrl)&amp;title=@(pageTitle)\" target=\"_blank\" title=\"Add to del.icio.us\">\n                    <img alt=\"Add to del.icio.us\" src=\"https://delicious.com/favicon.ico\" style=\"border:0; height:16px; width:16px; margin:0 1px;\" title=\"Add to del.icio.us\" /></a>\n                break;\n\n            case LinkShareSite.Digg:\n                <a href=\"http://digg.com/submit?url=@(pageLinkBack)&amp;title=@(pageTitle)\" target=\"_blank\" title=\"Digg!\">\n                    <img alt=\"Digg!\" src=\"http://digg.com/favicon.ico\" style=\"border:0; height:16px; width:16px; margin:0 1px;\" title=\"Digg!\" /></a>\n                break;\n            case LinkShareSite.Facebook:\n                <a href=\"http://www.facebook.com/sharer.php?u=@(shortenedUrl)&amp;t=@(pageTitle)\" target=\"_blank\" title=\"Share on Facebook\">\n                    <img alt=\"Share on Facebook\" src=\"http://facebook.com/favicon.ico\" style=\"border:0; height:16px; width:16px; margin:0 1px;\" title=\"Share on Facebook\" /></a>\n                break;\n            case LinkShareSite.Reddit:\n                <a href=\"http://reddit.com/submit?url=@(pageLinkBack)&amp;title=@(pageTitle)\" target=\"_blank\" title=\"Reddit!\">\n                    <img alt=\"Reddit!\" src=\"http://www.reddit.com/favicon.ico\" style=\"border:0; height:16px; width:16px; margin:0 1px;\" title=\"Reddit!\" /></a>\n                break;\n            case LinkShareSite.StumbleUpon:\n                <a href=\"http://www.stumbleupon.com/submit?url=@(pageLinkBack)&amp;title=@(pageTitle)\" target=\"_blank\" title=\"Stumble it!\">\n                    <img alt=\"Stumble it!\" src=\"http://stumbleupon.com/favicon.ico\" style=\"border:0; height:16px; width:16px; margin:0 1px;\" title=\"Stumble it!\" /></a>\n                break;            \n            case LinkShareSite.Twitter:\n                string status = String.Empty;\n                if (!twitterUserName.IsEmpty()) {\n                    status += \", (via @@\" + twitterUserName + \")\";\n                }\n                if (!additionalTweetText.IsEmpty()) {\n                    status += ' ' + additionalTweetText;\n                }\n                status = HttpUtility.UrlEncode(status);\n                <a href=\"http://twitter.com/home/?status=@(pageTitle)%3a+@(shortenedUrl)@(status)\" target=\"_blank\" title=\"Share on Twitter\">\n                    <img alt=\"Share on Twitter\" src=\"http://twitter.com/favicon.ico\" style=\"border:0; height:16px; width:16px; margin:0 1px;\" title=\"Share on Twitter\" />\n                </a>\n                break;\n            default:\n                throw new NotSupportedException(String.Format(CultureInfo.CurrentUICulture, HelpersToolkitResources.LinkShareValue_NotSupported, site));                \n        }\n    }\n}"
  },
  {
    "path": "src/Microsoft.Web.Helpers/LinkShareSite.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nnamespace Microsoft.Web.Helpers\n{\n    public enum LinkShareSite\n    {\n        Delicious = 0,\n        Digg = 1,\n        // GoogleBuzz = 2, has been deprecated\n        Facebook = 3,\n        Reddit = 4,\n        StumbleUpon = 5,\n        Twitter = 6,\n        All = 7,\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Helpers/Maps.cshtml",
    "content": "﻿@* Generator : WebPagesHelper *@\n\n@using System.Diagnostics\n@using System.Web.WebPages.Scope\n@using System.Web.UI.WebControls\n@using System.Globalization\n@using Microsoft.Internal.Web.Utils\n\n@functions {\n    private const string DefaultWidth = \"300px\";\n    private const string DefaultHeight = \"300px\";\n    private static readonly object _mapIdKey = new object();\n    private static readonly object _mapQuestApiKey = new object();\n    private static readonly object _bingApiKey = new object();\n    private static readonly object _yahooApiKey = new object();\n\n    public static string MapQuestApiKey {\n        get {\n            return (string)ScopeStorage.CurrentScope[_mapQuestApiKey];\n        }\n        set {\n            ScopeStorage.CurrentScope[_mapQuestApiKey] = value;\n        }\n    }\n\n    public static string YahooApiKey {\n        get {\n            return (string)ScopeStorage.CurrentScope[_yahooApiKey];\n        }\n        set {\n            ScopeStorage.CurrentScope[_yahooApiKey] = value;\n        }\n    }\n\n    public static string BingApiKey {\n        get {\n            return (string)ScopeStorage.CurrentScope[_bingApiKey];\n        }\n        set {\n            ScopeStorage.CurrentScope[_bingApiKey] = value;\n        }\n    }\n\n    // allow for stubbing this static resource in tests\n    private static Func<HttpContextBase> _getCurrentHttpContext = (Func<HttpContextBase>)(() => new HttpContextWrapper(HttpContext.Current));\n    internal static Func<HttpContextBase> GetCurrentHttpContext {\n        private get {\n            return _getCurrentHttpContext;\n        }\n        set {\n            _getCurrentHttpContext = value;\n        }\n    }\n\n    private static int MapId {\n        get {\n            var value = (int?)(GetCurrentHttpContext().Items[_mapIdKey]);\n            return value.GetValueOrDefault();\n        }\n        set {\n            GetCurrentHttpContext().Items[_mapIdKey] = value;\n        }\n    }\n    \n    private static string GetMapElementId() {\n        return \"map_\" + MapId;   \n    }\n    \n    private static string TryParseUnit(string value, string defaultValue) {\n        if (String.IsNullOrEmpty(value)) {\n            return defaultValue;\n        }\n        try {\n            return Unit.Parse(value, CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture);\n        } catch (ArgumentException) {\n            return defaultValue;    \n        }    \n    }\n\n    private static IHtmlString RawJS(string text) {\n        return Raw(HttpUtility.JavaScriptStringEncode(text));\n    }\n    \n    private static IHtmlString Raw(string text) {\n        return new HtmlString(text);    \n    }\n    \n    private static string GetApiKey(string apiKey, object scopeStorageKey) {\n        if (apiKey.IsEmpty()) {\n            return (string)ScopeStorage.CurrentScope[scopeStorageKey];   \n        }\n        return apiKey;   \n    }\n\n    public class MapLocation {\n        private readonly string _latitude;\n        private readonly string _longitude;\n        public MapLocation(string latitude, string longitude) {\n            _latitude = latitude;\n            _longitude = longitude;\n        }\n\n        public string Latitude {\n            get { return _latitude; }\n        }\n\n        public string Longitude {\n            get { return _longitude; }\n        }\n    }\n\n    internal static string GetDirectionsQuery(string location, string latitude, string longitude, Func<string, string> encoder = null) {\n        encoder = encoder ?? HttpUtility.UrlEncode;\n        Debug.Assert(!(location.IsEmpty() && latitude.IsEmpty() && longitude.IsEmpty()));\n        if (location.IsEmpty()) {\n            return encoder(latitude + \",\" + longitude);\n        }\n        return encoder(location);\n    }\n}\n\n@**\nSummary:\n    Generates Html to display a Map Quest map.\nParameter:\n    key: Map Quest API key\nParameter location:\n    Address of the location to center the map at\nParameter latitude:\n    Latitude to center on. If both latitude and longitude are specified, location is ignored.\nParameter longitude:\n    Longitude to center on. If both latitude and longitude are specified, location is ignored.\nParameter width: \n    Width of the map with units such as 480px, 100% etc. Defaults to 300px.\nParameter height: \n    Height of the map with units such as 480px, 100% etc. Defaults to 300px.\nParameter zoom:\n    Initial zoom level of the map. Defaults to 7.\nParameter type:\n    Map type to display. Valid values are \"map\", \"sat\" or \"hyb\".\nParameter showDirectionsLink:\n    Determines if a link to get directions should be displayed when a location is specified. Defaults to true.\nParameter directionsLinkText\n    The text for the get directions link. Defaults to \"Get Directions\".\n**@\n@helper GetMapQuestHtml(string key = null, string location = null, string latitude = null, string longitude = null, string width = \"300px\", string height = \"300px\", int zoom = 7, string type = \"map\",\n            bool showDirectionsLink = true, string directionsLinkText = \"Get Directions\", bool showZoomControl = true, IEnumerable<MapLocation> pushpins = null) {\n    key = GetApiKey(key, _mapQuestApiKey);\n    if (key.IsEmpty()) {\n        throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"key\");  \n    }\n    \n    string mapElement = GetMapElementId();\n    string loc = \"null\"; // We want to print the value 'null' in the client\n    if (latitude != null && longitude != null) {\n        loc = String.Format(CultureInfo.InvariantCulture, \"{{lat: {0}, lng: {1}}}\",\n            HttpUtility.JavaScriptStringEncode(latitude, addDoubleQuotes: false), HttpUtility.JavaScriptStringEncode(longitude, addDoubleQuotes: false));\n    }\n\n    // The MapQuest key listed on their website is Url encoded to begin with. \n    <script src=\"http://mapquestapi.com/sdk/js/v6.0.0/mqa.toolkit.js?key=@key\" type=\"text/javascript\"></script>\n    <script type=\"text/javascript\">\n        MQA.EventUtil.observe(window, 'load', function() {\n            var map = new MQA.TileMap(document.getElementById('@mapElement'), @zoom, @Raw(loc), '@RawJS(type)'); \n            @if (showZoomControl) {\n            <text>\n                MQA.withModule('zoomcontrol3', function() {\n\t                map.addControl(new MQA.LargeZoomControl3(), new MQA.MapCornerPlacement(MQA.MapCorner.TOP_LEFT));\n                });\n            </text>\n            }\n            @if (!String.IsNullOrEmpty(location)) {\n            <text>\n                MQA.withModule('geocoder', function() {\n                    map.geocodeAndAddLocations('@RawJS(location)');\n                });\n            </text>\n            }\n            @if (pushpins != null) {\n                foreach (var p in pushpins) {\n                    @: map.addShape(new MQA.Poi({lat:@RawJS(p.Latitude),lng:@RawJS(p.Longitude)}));\n\t            }\n            }\n        });\n    </script>\n    \n    <div id=\"@mapElement\" style=\"width:@TryParseUnit(width, DefaultWidth); height:@TryParseUnit(height, DefaultHeight);\">\n    </div>\n    if (showDirectionsLink) {\n        <a class=\"map-link\" href=\"http://www.mapquest.com/?q=@GetDirectionsQuery(location, latitude, longitude)\">@directionsLinkText</a>\n    }\n    MapId++;\n}\n\n@**\nSummary:\n    Generates Html to display Bing map.\nParameter:\n    key: Bing Maps application key\nParameter location:\n    Address of the location to center the map at\nParameter latitude:\n    Latitude to center on. If both latitude and longitude are specified, location is ignored.\nParameter longitude:\n    Longitude to center on. If both latitude and longitude are specified, location is ignored.\nParameter width: \n    Width of the map with units such as 480px, 100% etc. Defaults to 300px.\nParameter height: \n    Height of the map with units such as 480px, 100% etc. Defaults to 300px.\nParameter zoom:\n    Initial zoom level of the map. Defaults to 14.\nParameter type:\n    Map type to display. Valid values are \"auto\", \"aerial\", \"birdeye\", \"road\" and \"mercator\".\nParameter useAdaptiveOverlay:\n    Determines if the map overlay that adapts to the colors of the current map view is used. Defaults to true.\nParameter showDirectionsLink:\n    Determines if a link to get directions should be displayed when a location is specified. Defaults to true.\nParameter directionsLinkText\n    The text for the get directions link. Defaults to \"Get Directions\".\n**@\n@helper GetBingHtml(string key = null, string location = null, string latitude = null, string longitude = null, string width = null, string height = null, int zoom = 14, string type = \"auto\",\n            bool useAdaptiveOverlay = true, bool showDirectionsLink = true, string directionsLinkText = \"Get Directions\", IEnumerable<MapLocation> pushpins = null) {\n    key = GetApiKey(key, _bingApiKey);\n    if (key.IsEmpty()) {\n        throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"key\");\n    } \n    string mapElement = GetMapElementId();\n    \n    type = (type ?? \"auto\").ToLowerInvariant();\n\n    <script src=\"http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0\" type=\"text/javascript\"></script>\n    <script type=\"text/javascript\">\n        jQuery(window).load(function() { \n            var map = null;\n            @if (useAdaptiveOverlay) {\n                <text>\n                Microsoft.Maps.loadModule('Microsoft.Maps.Overlays.Style', {\n                    callback: function () {\n                        map = new Microsoft.Maps.Map(document.getElementById(\"@mapElement\"), { credentials: '@RawJS(key)', mapTypeId: Microsoft.Maps.MapTypeId['@RawJS(type)'], customizeOverlays: true });\n\n                </text>\n            } else {\n                <text>\n                map = new Microsoft.Maps.Map(document.getElementById(\"@mapElement\"), { credentials: '@RawJS(key)', mapTypeId: Microsoft.Maps.MapTypeId['@RawJS(type)'] });\n                </text>\n            }\n            @if (latitude != null && longitude != null) {\n                @: map.setView({zoom: @zoom, center: new Microsoft.Maps.Location(@RawJS(latitude), @RawJS(longitude))});\n            }\n            else if (location != null) {\n                <text>\n                map.getCredentials(function(credentials) {\n                    $.ajax({\n                        url: 'http://dev.virtualearth.net/REST/v1/Locations/' + encodeURI('@RawJS(location)'),\n                        type: 'GET',\n                        crossDomain: true,\n                        data: { output: 'json', key: credentials }, dataType: 'jsonp', jsonp: 'jsonp',\n                        success: function(data) {\n                            if (data && data.resourceSets && data.resourceSets.length > 0 && data.resourceSets[0].resources && data.resourceSets[0].resources.length > 0) {\n                                var r = data.resourceSets[0].resources[0].point.coordinates;\n                                var loc = new Microsoft.Maps.Location(r[0], r[1]);\n                                map.setView({zoom: @zoom, center: loc});              \n                                map.entities.push(new Microsoft.Maps.Pushpin(loc, null));\n                            }\n                        }\n                    });\n                });\n                </text>\n            }\n            @if (pushpins != null) {\n                foreach(var loc in pushpins) {\n                    @: map.entities.push(new Microsoft.Maps.Pushpin(new Microsoft.Maps.Location(@RawJS(loc.Latitude), @RawJS(loc.Longitude)), null));\n                }\n            }\n            @if (useAdaptiveOverlay) {\n                <text>\n                    }\n                });\n                </text>\n            }\n        });\n    </script>\n    \n    <div class=\"map\" id=\"@mapElement\" style=\"position:relative; width:@TryParseUnit(width, DefaultWidth); height:@TryParseUnit(height, DefaultHeight);\">\n    </div>\n    if (showDirectionsLink) {\n        // Review: Need to figure out if the link needs to be localized. \n        <a class=\"map-link\" href=\"http://www.bing.com/maps/?v=2&where1=@GetDirectionsQuery(location, latitude, longitude)\">@directionsLinkText</a>\n    }\n    MapId++;\n}\n\n@**\nSummary:\n    Generates Html to display a Google map.\nParameter location:\n    Address of the location to center the map at\nParameter latitude:\n    Latitude to center on. If both latitude and longitude are specified, location is ignored.\nParameter longitude:\n    Longitude to center on. If both latitude and longitude are specified, location is ignored.\nParameter width: \n    Width of the map with units such as 480px, 100% etc. Defaults to 300px.\nParameter height: \n    Height of the map with units such as 480px, 100% etc. Defaults to 300px.\nParameter zoom:\n    Initial zoom level of the map. Defaults to 14.\nParameter type:\n    Map type to display. Valid values are \"ROADMAP\", \"HYBRID\", \"SATELLITE\" and \"TERRAIN\".\nParameter showDirectionsLink:\n    Determines if a link to get directions should be displayed when a location is specified. Defaults to true.\nParameter directionsLinkText\n    The text for the get directions link. Defaults to \"Get Directions\".\n**@\n@helper GetGoogleHtml(string location = null, string latitude = null, string longitude = null, string width = null, string height = null, int zoom = 14, string type = \"ROADMAP\",\n                bool showDirectionsLink = true, string directionsLinkText = \"Get Directions\", IEnumerable<MapLocation> pushpins = null) {\n    string mapElement = GetMapElementId();\n    type = (type ?? \"ROADMAP\").ToUpperInvariant(); // Map types are in upper case\n\n    // Google maps does not support null centers. We'll set it to arbitrary values if they are null and only the location is provided.\n    // These locations are somewhere around Microsoft's Redmond Campus.\n    latitude = latitude ?? \"47.652437\";\n    longitude = longitude ?? \"-122.132424\";\n\n    <script src=\"http://maps.google.com/maps/api/js?sensor=false\" type=\"text/javascript\"></script>\n    <script type=\"text/javascript\">\n        $(function() {\n            var map = new google.maps.Map(document.getElementById(\"@mapElement\"), { zoom: @zoom, center: new google.maps.LatLng(@RawJS(latitude), @RawJS(longitude)), mapTypeId: google.maps.MapTypeId['@RawJS(type)'] });\n            @if (!String.IsNullOrEmpty(location)) {\n                <text>\n                new google.maps.Geocoder().geocode({address: '@RawJS(location)'}, function(response, status) {\n                    if (status === google.maps.GeocoderStatus.OK) {\n                        var best = response[0].geometry.location;\n                        map.panTo(best);\n                        new google.maps.Marker({map : map, position: best });\n                    }\n                });\n                </text>\n            }\n            @if (pushpins != null) {\n                foreach(var loc in pushpins) {\n                    @: new google.maps.Marker({map : map, position: new google.maps.LatLng(@RawJS(loc.Latitude), @RawJS(loc.Longitude))});\n                }\n            }\n        });\n    </script>\n    \n    <div class=\"map\" id=\"@mapElement\" style=\"width:@TryParseUnit(width, DefaultWidth); height:@TryParseUnit(height, DefaultHeight);\">\n    </div>\n    if (showDirectionsLink) {\n        <a class=\"map-link\" href=\"http://maps.google.com/maps?q=@GetDirectionsQuery(location, latitude, longitude)\">@directionsLinkText</a>\n    }\n    MapId++;\n}\n\n@**\nSummary:\n    Generates Html to display a Yahoo map.\nParameter:\n    key: Yahoo application ID\nParameter location:\n    Address of the location to center the map at\nParameter latitude:\n    Latitude to center on. If both latitude and longitude are specified, location is ignored.\nParameter longitude:\n    Longitude to center on. If both latitude and longitude are specified, location is ignored.\nParameter width: \n    Width of the map with units such as 480px, 100% etc. Defaults to 300px.\nParameter height: \n    Height of the map with units such as 480px, 100% etc. Defaults to 300px.\nParameter zoom:\n    Initial zoom level of the map. Defaults to 4.\nParameter type:\n    Map type to display. Valid values are \"YAHOO_MAP_SAT\", \"YAHOO_MAP_HYB\" and \"YAHOO_MAP_REG\". \nParameter showDirectionsLink:\n    Determines if a link to get directions should be displayed when a location is specified. Defaults to true.\nParameter directionsLinkText\n    The text for the get directions link. Defaults to \"Get Directions\".\n**@\n@helper GetYahooHtml(string key = null, string location = null, string latitude = null, string longitude = null, string width = null, string height = null, int zoom = 4, string type = \"YAHOO_MAP_REG\",\n                bool showDirectionsLink = true, string directionsLinkText = \"Get Directions\", IEnumerable<MapLocation> pushpins = null) {\n    key = GetApiKey(key, _yahooApiKey);\n    if (key.IsEmpty()) {\n        throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"key\");\n    }                     \n    string mapElement = GetMapElementId();\n\n    <script src=\"http://api.maps.yahoo.com/ajaxymap?v=3.8&appid=@HttpUtility.UrlEncode(key)\" type=\"text/javascript\"></script>\n    <script type=\"text/javascript\">\n        $(function() {\n            var map = new YMap(document.getElementById('@RawJS(mapElement)'));  \n            map.addTypeControl();  \n            map.setMapType(@RawJS(type));  \n            @if (latitude != null && longitude != null) {\n                @: map.drawZoomAndCenter(new YGeoPoint(@RawJS(latitude), @RawJS(longitude)), @zoom);\n            }\n            else if (!String.IsNullOrEmpty(location)) {\n                @: map.drawZoomAndCenter('@RawJS(location)', @zoom);\n            }\n            else {\n                @: map.setZoomLevel(@zoom);\n            }\n            @if(pushpins != null) {\n                foreach (var loc in pushpins) {\n                     @: map.addMarker(new YGeoPoint(@RawJS(loc.Latitude), @RawJS(loc.Longitude)));\n                 }\n            }\n\n        });\n    </script>\n    \n    <div id=\"@mapElement\" style=\"width:@TryParseUnit(width, DefaultWidth); height:@TryParseUnit(height, DefaultHeight);\">\n    </div>\n    if (showDirectionsLink) {\n        <a class=\"map-link\" href=\"http://maps.yahoo.com/#q1=@GetDirectionsQuery(location, latitude, longitude, HttpUtility.UrlPathEncode)\">@directionsLinkText</a>\n    }\n    MapId++;\n}\n\n"
  },
  {
    "path": "src/Microsoft.Web.Helpers/Microsoft.Web.Helpers.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{0C7CE809-0F72-4C19-8C64-D6573E4D9521}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>Microsoft.Web.Helpers</RootNamespace>\n    <AssemblyName>Microsoft.Web.Helpers</AssemblyName>\n    <DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>\n    <RunCodeAnalysis>$(CodeAnalysis)</RunCodeAnalysis>\n    <CodeAnalysisRuleSet>..\\WebHelpers.ruleset</CodeAnalysisRuleSet>\n    <DefineConstants>$(DefineConstants);ASPNETWEBPAGES</DefineConstants>\n    <NoWarn>1591</NoWarn>\n  </PropertyGroup>\n  <ItemGroup>\n    <CodeAnalysisDictionary Include=\"..\\CodeAnalysisDictionary.xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"System.Web.ApplicationServices\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\CommonAssemblyInfo.cs\">\n      <Link>Properties\\CommonAssemblyInfo.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\CommonResources.Designer.cs\">\n      <Link>Common\\CommonResources.Designer.cs</Link>\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>CommonResources.resx</DependentUpon>\n    </Compile>\n    <Compile Include=\"GlobalSuppressions.cs\" />\n    <Compile Include=\"..\\GlobalSuppressions.cs\">\n      <Link>Common\\GlobalSuppressions.cs</Link>\n    </Compile>\n    <Compile Include=\"Gravatar.cs\" />\n    <Compile Include=\"GravatarRating.cs\" />\n    <Compile Include=\"PreApplicationStartCode.cs\" />\n    <Compile Include=\"Resources\\HelpersToolkitResources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>HelpersToolkitResources.resx</DependentUpon>\n    </Compile>\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"Themes.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"ThemesImplementation.cs\" />\n    <Compile Include=\"Video.cs\" />\n    <Compile Include=\"VirtualPathUtilityBase.cs\" />\n    <Compile Include=\"VirtualPathUtilityWrapper.cs\" />\n    <Compile Include=\"UrlBuilder.cs\" />\n    <Compile Include=\"LinkShareSite.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"..\\CommonResources.resx\">\n      <Link>Common\\CommonResources.resx</Link>\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>CommonResources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n    <EmbeddedResource Include=\"Resources\\HelpersToolkitResources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>HelpersToolkitResources.Designer.cs</LastGenOutput>\n      <CustomToolNamespace>Resources</CustomToolNamespace>\n    </EmbeddedResource>\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\System.Web.Helpers\\System.Web.Helpers.csproj\">\n      <Project>{9B7E3740-6161-4548-833C-4BBCA43B970E}</Project>\n      <Name>System.Web.Helpers</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.Razor\\System.Web.Razor.csproj\">\n      <Project>{8F18041B-9410-4C36-A9C5-067813DF5F31}</Project>\n      <Name>System.Web.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.WebPages.Razor\\System.Web.WebPages.Razor.csproj\">\n      <Project>{0939B11A-FE4E-4BA1-8AD6-D97741EE314F}</Project>\n      <Name>System.Web.WebPages.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.WebPages\\System.Web.WebPages.csproj\">\n      <Project>{76EFA9C5-8D7E-4FDF-B710-E20F8B6B00D2}</Project>\n      <Name>System.Web.WebPages</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\WebMatrix.Data\\WebMatrix.Data.csproj\">\n      <Project>{4D39BAAF-8A96-473E-AB79-C8A341885137}</Project>\n      <Name>WebMatrix.Data</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\WebMatrix.WebData\\WebMatrix.WebData.csproj\">\n      <Project>{55A15F40-1435-4248-A7F2-2A146BB83586}</Project>\n      <Name>WebMatrix.WebData</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\" />\n    <RazorSrcFiles Include=\"Analytics.cshtml\" />\n    <RazorSrcFiles Include=\"FileUpload.cshtml\" />\n    <RazorSrcFiles Include=\"GamerCard.cshtml\" />\n    <RazorSrcFiles Include=\"LinkShare.cshtml\" />\n    <RazorSrcFiles Include=\"ReCaptcha.cshtml\" />\n    <RazorSrcFiles Include=\"Facebook.cshtml\" />\n    <RazorSrcFiles Include=\"Maps.cshtml\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  \n  <!-- Note: RazorGenerator.MsBuild uses Razor 3.0 \\ Mvc 5.0 for generating views. In the event we update the Mvc parser, we'll need to ensure this package references the updated Mvc build -->\n  <Import Project=\"..\\..\\packages\\RazorGenerator.MsBuild.2.2.0\\build\\RazorGenerator.MsBuild.targets\" Condition=\"Exists('..\\..\\packages\\RazorGenerator.MsBuild.2.2.0\\build\\RazorGenerator.MsBuild.targets')\" />\n</Project>"
  },
  {
    "path": "src/Microsoft.Web.Helpers/PreApplicationStartCode.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Web.WebPages.Razor;\n\nnamespace Microsoft.Web.Helpers\n{\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class PreApplicationStartCode\n    {\n        private static bool _startWasCalled;\n\n        public static void Start()\n        {\n            // Even though ASP.NET will only call each PreAppStart once, we sometimes internally call one PreAppStart from \n            // another PreAppStart to ensure that things get initialized in the right order. ASP.NET does not guarantee the \n            // order so we have to guard against multiple calls.\n            // All Start calls are made on same thread, so no lock needed here.\n\n            if (_startWasCalled)\n            {\n                return;\n            }\n            _startWasCalled = true;\n\n            // Auto import the Microsoft.Web.Helpers namespace to all apps that are executing.\n            WebPageRazorHost.AddGlobalImport(typeof(PreApplicationStartCode).Namespace);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Helpers/Properties/AssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Web;\nusing Microsoft.Web.Helpers;\n\n// General Information about an assembly is controlled through the following \n// set of attributes. Change these attribute values to modify the information\n// associated with an assembly.\n\n[assembly: AssemblyTitle(\"Microsoft.Web.Helpers\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: PreApplicationStartMethod(typeof(PreApplicationStartCode), \"Start\")]\n[assembly: InternalsVisibleTo(\"Microsoft.Web.Helpers.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n"
  },
  {
    "path": "src/Microsoft.Web.Helpers/ReCaptcha.cshtml",
    "content": "﻿@* Generator: WebPagesHelper *@\n\n@using System\n@using System.Globalization\n@using System.IO\n@using System.Text\n@using System.Web.WebPages.Scope\n@using Microsoft.Internal.Web.Utils\n@using Resources\n\n@functions{\n    private const string _reCaptchaUrl = \"http://www.google.com/recaptcha/api\";\n    private const string _reCaptchaSecureUrl = \"https://www.google.com/recaptcha/api\";\n    private static readonly object _errorCodeCacheKey = new object();\n    internal static readonly object _privateKey = new object();\n    internal static readonly object _publicKey = new object();\n    \n    public static string PrivateKey {\n        get {\n            return ScopeStorage.CurrentScope[_privateKey] as string;\n        }\n\n        set {\n            if (value == null) {\n                throw new ArgumentNullException(\"value\");\n            }\n            ScopeStorage.CurrentScope[_privateKey] = value;\n        }\n    }\n\n    public static string PublicKey {\n        get {\n            return ScopeStorage.CurrentScope[_publicKey] as string;\n        }\n\n        set {\n            if (value == null) {\n                throw new ArgumentNullException(\"value\");\n            }\n            ScopeStorage.CurrentScope[_publicKey] = value;\n        }\n    }\n    \n    public static bool Validate(string privateKey = null) {\n        return Validate(HttpContext.Current == null ? null : new HttpContextWrapper(HttpContext.Current), privateKey, UrlBuilder.DefaultVirtualPathUtility);\n    }   \n\n    internal static string GetLastError(HttpContextBase context) {\n        if (context.Items.Contains(_errorCodeCacheKey)) {\n            return context.Items[_errorCodeCacheKey] as string;\n        }\n        return String.Empty;\n    }\n    \n    internal static bool Validate(HttpContextBase context, string privateKey, VirtualPathUtilityBase virtualPathUtility) {\n        privateKey = privateKey ?? PrivateKey;\n\n        if (String.IsNullOrEmpty(privateKey)) {\n            throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"privateKey\");\n        }\n\n        SetLastError(context, String.Empty);\n        string postedBody = GetValidatePostData(context, privateKey, virtualPathUtility);\n        if (String.IsNullOrEmpty(postedBody)) {\n            return false;\n        }\n        string result = ExecuteValidateRequest(postedBody);\n        return HandleValidateResponse(context, result);\n    }\n\n    internal static string GetValidatePostData(HttpContextBase context, string privateKey, VirtualPathUtilityBase virtualPathUtility) {\n        string remoteIP = context.Request.ServerVariables[\"REMOTE_ADDR\"];\n        if (String.IsNullOrEmpty(remoteIP)) {\n            throw new InvalidOperationException(HelpersToolkitResources.ReCaptcha_RemoteIPNotFound);\n        }\n\n        // Noscript rendering requires the user to copy and paste the challenge string to a textarea.\n        // When the challenge is invalid the recaptcha service doesn't return an error that affects\n        // UI rendering, so Validate should just return false without issuing the web request.\n        string challenge = context.Request.Form[\"recaptcha_challenge_field\"];\n        if (String.IsNullOrEmpty(challenge)) {\n            return String.Empty;\n        }\n        string response = (context.Request.Form[\"recaptcha_response_field\"] ?? String.Empty).Trim();\n\n        var builder = new UrlBuilder(context, virtualPathUtility, path: null, parameters: null)\n                .AddParam(\"privatekey\", privateKey)\n                .AddParam(\"remoteip\", context.Request.ServerVariables[\"REMOTE_ADDR\"])\n                .AddParam(\"challenge\", challenge)\n                .AddParam(\"response\", response);\n        \n        // Trim the leading ? and return the QueryString\n        return builder.QueryString.Substring(1);\n    }\n\n    internal static bool HandleValidateResponse(HttpContextBase context, string response) {\n        if (!String.IsNullOrEmpty(response)) {\n            string[] results = response.Split('\\n');\n            if (results.Length > 0) {\n                bool rval = Convert.ToBoolean(results[0], CultureInfo.InvariantCulture);\n                if (!rval && (results.Length > 1)) {\n                    SetLastError(context, results[1]);\n                }\n                return rval;\n            }\n        }\n        return false;\n    }\n\n    internal static string GetChallengeUrl(HttpContextBase httpContext, string publicKey = null, string errorCode = null) {\n        return GetUrlHelper(httpContext, \"challenge\", publicKey, errorCode: errorCode);\n    }\n\n    private static string ExecuteValidateRequest(string formData) {\n        WebRequest request = WebRequest.Create(_reCaptchaUrl + \"/verify\");\n        request.Method = \"POST\";\n        request.Timeout = 5000; //milliseconds\n        request.ContentType = \"application/x-www-form-urlencoded\";\n\n        byte[] content = Encoding.UTF8.GetBytes(formData);\n        using (Stream stream = request.GetRequestStream()) {\n            stream.Write(content, 0, content.Length);\n        }\n        using (WebResponse response = request.GetResponse()) {\n            using (StreamReader reader = new StreamReader(response.GetResponseStream())) {\n                return reader.ReadToEnd();\n            }\n        }\n    }\n\n    private static string GetUrlHelper(HttpContextBase context, string path, string publicKey, string errorCode) {\n\n        publicKey = publicKey ?? PublicKey;\n        if (String.IsNullOrEmpty(publicKey)) {\n            throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"publicKey\");\n        }\n\n        var builder = new UrlBuilder(context.Request.IsSecureConnection ? _reCaptchaSecureUrl : _reCaptchaUrl);\n        builder.AddPath(path);\n        builder.AddParam(\"k\", publicKey);\n        if (!String.IsNullOrEmpty(errorCode)) {\n            builder.AddParam(\"error\", errorCode);\n        }\n        return builder;\n    }\n\n    private static void SetLastError(HttpContextBase context, string value) {\n        context.Items[_errorCodeCacheKey] = value;\n    }\n}\n\n@helper GetHtml(string publicKey = null, string theme = \"red\", \n    string language = \"en\", int tabIndex = 0) {\n\n    @GetHtmlWithOptions(publicKey, options: new Dictionary<string, object>() {\n        { \"theme\", theme }, { \"lang\", language }, { \"tabindex\", tabIndex }\n    })\n}\n\n@helper GetHtmlWithOptions(string publicKey = null, object options = null) {\n    @GetHtml(HttpContext.Current == null ? null : new HttpContextWrapper(HttpContext.Current), publicKey, options)\n}\n\n@helper GetHtml(HttpContextBase httpContext, string publicKey = null, object options = null) {\n    if (options != null) {\n        var optionJson = new HtmlString(Json.Encode(options));\n        <script type=\"text/javascript\">\n            var RecaptchaOptions=@optionJson;\n        </script>\n    }\n    <script src=\"@GetChallengeUrl(httpContext, publicKey, GetLastError(httpContext))\" type=\"text/javascript\"></script>\n\n    <noscript>\n        <iframe frameborder=\"0\" height=\"300px\" src=\"@GetUrlHelper(httpContext, \"noscript\", publicKey, errorCode: null)\" width=\"500px\"></iframe>\n        <br /><br />\n        <textarea cols=\"40\" name=\"recaptcha_challenge_field\" rows=\"3\"></textarea>\n        <input name=\"recaptcha_response_field\" type=\"hidden\" value=\"manual_challenge\" />\n    </noscript>\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Helpers/Resources/HelpersToolkitResources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.18051\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace Resources {\n    using System;\n    \n    \n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class HelpersToolkitResources {\n        \n        private static global::System.Resources.ResourceManager resourceMan;\n        \n        private static global::System.Globalization.CultureInfo resourceCulture;\n        \n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal HelpersToolkitResources() {\n        }\n        \n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"Microsoft.Web.Helpers.Resources.HelpersToolkitResources\", typeof(HelpersToolkitResources).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n        \n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Add more files.\n        /// </summary>\n        internal static string FileUpload_AddMore {\n            get {\n                return ResourceManager.GetString(\"FileUpload_AddMore\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Upload.\n        /// </summary>\n        internal static string FileUpload_Upload {\n            get {\n                return ResourceManager.GetString(\"FileUpload_Upload\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The Gravatar image size must be between 1 and 512 pixels..\n        /// </summary>\n        internal static string Gravatar_InvalidImageSize {\n            get {\n                return ResourceManager.GetString(\"Gravatar_InvalidImageSize\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to LinkShare value {0} is not supported by the Link Share helper. .\n        /// </summary>\n        internal static string LinkShareValue_NotSupported {\n            get {\n                return ResourceManager.GetString(\"LinkShareValue_NotSupported\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The captcha cannot be validated because the remote address was not found in the request..\n        /// </summary>\n        internal static string ReCaptcha_RemoteIPNotFound {\n            get {\n                return ResourceManager.GetString(\"ReCaptcha_RemoteIPNotFound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to You cannot have a null folder. Try using Themes.GetResourcePath(string fileName) instead if you do not want to specify a folder..\n        /// </summary>\n        internal static string Themes_FolderCannotBeNull {\n            get {\n                return ResourceManager.GetString(\"Themes_FolderCannotBeNull\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Unknown theme &apos;{0}&apos;. Ensure that a directory labeled &apos;{0}&apos; exists under the theme directory..\n        /// </summary>\n        internal static string Themes_InvalidTheme {\n            get {\n                return ResourceManager.GetString(\"Themes_InvalidTheme\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to You must call the &quot;Themes.Initialize&quot; method before you call any other method of the &quot;Themes&quot; class..\n        /// </summary>\n        internal static string Themes_NotInitialized {\n            get {\n                return ResourceManager.GetString(\"Themes_NotInitialized\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The media file &quot;{0}&quot; does not exist..\n        /// </summary>\n        internal static string Video_FileDoesNotExist {\n            get {\n                return ResourceManager.GetString(\"Video_FileDoesNotExist\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Property &quot;{0}&quot; cannot be set through this argument..\n        /// </summary>\n        internal static string Video_PropertyCannotBeSet {\n            get {\n                return ResourceManager.GetString(\"Video_PropertyCannotBeSet\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Helpers/Resources/HelpersToolkitResources.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"FileUpload_AddMore\" xml:space=\"preserve\">\n    <value>Add more files</value>\n  </data>\n  <data name=\"FileUpload_Upload\" xml:space=\"preserve\">\n    <value>Upload</value>\n  </data>\n  <data name=\"Gravatar_InvalidImageSize\" xml:space=\"preserve\">\n    <value>The Gravatar image size must be between 1 and 512 pixels.</value>\n  </data>\n  <data name=\"LinkShareValue_NotSupported\" xml:space=\"preserve\">\n    <value>LinkShare value {0} is not supported by the Link Share helper. </value>\n  </data>\n  <data name=\"ReCaptcha_RemoteIPNotFound\" xml:space=\"preserve\">\n    <value>The captcha cannot be validated because the remote address was not found in the request.</value>\n  </data>\n  <data name=\"Themes_FolderCannotBeNull\" xml:space=\"preserve\">\n    <value>You cannot have a null folder. Try using Themes.GetResourcePath(string fileName) instead if you do not want to specify a folder.</value>\n  </data>\n  <data name=\"Themes_InvalidTheme\" xml:space=\"preserve\">\n    <value>Unknown theme '{0}'. Ensure that a directory labeled '{0}' exists under the theme directory.</value>\n  </data>\n  <data name=\"Themes_NotInitialized\" xml:space=\"preserve\">\n    <value>You must call the \"Themes.Initialize\" method before you call any other method of the \"Themes\" class.</value>\n  </data>\n  <data name=\"Video_FileDoesNotExist\" xml:space=\"preserve\">\n    <value>The media file \"{0}\" does not exist.</value>\n  </data>\n  <data name=\"Video_PropertyCannotBeSet\" xml:space=\"preserve\">\n    <value>Property \"{0}\" cannot be set through this argument.</value>\n  </data>\n</root>"
  },
  {
    "path": "src/Microsoft.Web.Helpers/Themes.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Web.Hosting;\nusing System.Web.WebPages.Scope;\n\nnamespace Microsoft.Web.Helpers\n{\n    public static class Themes\n    {\n        public static string ThemeDirectory\n        {\n            get { return Implementation.ThemeDirectory; }\n        }\n\n        public static string CurrentTheme\n        {\n            get { return Implementation.CurrentTheme; }\n            set { Implementation.CurrentTheme = value; }\n        }\n\n        public static string DefaultTheme\n        {\n            get { return Implementation.DefaultTheme; }\n        }\n\n        public static ReadOnlyCollection<string> AvailableThemes\n        {\n            get { return Implementation.AvailableThemes; }\n        }\n\n        private static ThemesImplementation Implementation\n        {\n            get { return new ThemesImplementation(HostingEnvironment.VirtualPathProvider, ScopeStorage.CurrentScope); }\n        }\n\n        public static void Initialize(string themeDirectory, string defaultTheme)\n        {\n            Implementation.Initialize(themeDirectory, defaultTheme);\n        }\n\n        /// <summary>\n        /// Get a file that lives directly inside the theme directory\n        /// </summary>\n        /// <param name=\"fileName\">The filename to look for</param>\n        /// <returns>The full path to the file that matches the requested file</returns>\n        public static string GetResourcePath(string fileName)\n        {\n            return Implementation.GetResourcePath(fileName);\n        }\n\n        public static string GetResourcePath(string folder, string fileName)\n        {\n            return Implementation.GetResourcePath(folder, fileName);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Helpers/ThemesImplementation.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Web.Hosting;\nusing Microsoft.Internal.Web.Utils;\nusing Resources;\n\nnamespace Microsoft.Web.Helpers\n{\n    internal class ThemesImplementation\n    {\n        internal static readonly object CurrentThemeKey = new object();\n        internal static readonly object ThemeDirectoryKey = new object();\n        internal static readonly object DefaultThemeKey = new object();\n        internal static readonly object ThemesInitializedKey = new object();\n        private readonly VirtualPathProvider _vpp;\n        private readonly IDictionary<object, object> _currentScope;\n\n        public ThemesImplementation(VirtualPathProvider vpp, IDictionary<object, object> scopeStorage)\n        {\n            _vpp = vpp;\n            _currentScope = scopeStorage;\n        }\n\n        public string ThemeDirectory\n        {\n            get\n            {\n                EnsureInitialized();\n                return (string)_currentScope[ThemeDirectoryKey];\n            }\n            private set\n            {\n                Debug.Assert(value != null);\n                _currentScope[ThemeDirectoryKey] = value;\n            }\n        }\n\n        /// <summary>\n        /// This should live throughout the application life cycle\n        /// and be set in _appstart.cshtml\n        /// </summary>\n        public string DefaultTheme\n        {\n            get\n            {\n                EnsureInitialized();\n                return (string)_currentScope[DefaultThemeKey];\n            }\n            private set\n            {\n                Debug.Assert(value != null);\n                _currentScope[DefaultThemeKey] = value;\n            }\n        }\n\n        /// <summary>\n        /// The current theme to use. When this is set,\n        /// all GetResource checks will check if the CurrentTheme\n        /// contains the file, and if it doesn't it will fall back to\n        /// the DefaultTheme\n        /// </summary>\n        public string CurrentTheme\n        {\n            get\n            {\n                EnsureInitialized();\n                return (string)_currentScope[CurrentThemeKey] ?? DefaultTheme;\n            }\n            set\n            {\n                if (String.IsNullOrEmpty(value))\n                {\n                    throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"value\");\n                }\n\n                // EnsureValidTheme would verify if themes have been correctly initialized and that the value specified is a valid theme.\n                if (!IsValidTheme(AvailableThemes, value))\n                {\n                    throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, HelpersToolkitResources.Themes_InvalidTheme, value), \"value\");\n                }\n                _currentScope[CurrentThemeKey] = value;\n            }\n        }\n\n        public ReadOnlyCollection<string> AvailableThemes\n        {\n            get\n            {\n                EnsureInitialized();\n                return GetAvailableThemes(ThemeDirectory);\n            }\n        }\n\n        private string CurrentThemePath\n        {\n            get { return Path.Combine(ThemeDirectory, CurrentTheme); }\n        }\n\n        private string DefaultThemePath\n        {\n            get { return Path.Combine(ThemeDirectory, DefaultTheme); }\n        }\n\n        private bool ThemesInitialized\n        {\n            get\n            {\n                bool? value = (bool?)_currentScope[ThemesInitializedKey];\n                return value != null && value.Value;\n            }\n            set { _currentScope[ThemesInitializedKey] = value; }\n        }\n\n        public void Initialize(string themeDirectory, string defaultTheme)\n        {\n            if (String.IsNullOrEmpty(themeDirectory))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"themeDirectory\");\n            }\n\n            if (String.IsNullOrEmpty(defaultTheme))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"defaultTheme\");\n            }\n\n            var availableThemes = GetAvailableThemes(themeDirectory);\n            if (!IsValidTheme(availableThemes, defaultTheme))\n            {\n                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, HelpersToolkitResources.Themes_InvalidTheme, defaultTheme), \"defaultTheme\");\n            }\n\n            ThemeDirectory = themeDirectory;\n            DefaultTheme = defaultTheme;\n            ThemesInitialized = true;\n        }\n\n        /// <summary>\n        /// Get a file that lives directly inside the theme directory\n        /// </summary>\n        /// <param name=\"fileName\">The filename to look for</param>\n        /// <returns>The full path to the file that matches the requested file</returns>\n        public string GetResourcePath(string fileName)\n        {\n            return GetResourcePath(String.Empty, fileName);\n        }\n\n        public string GetResourcePath(string folder, string fileName)\n        {\n            EnsureInitialized();\n\n            if (folder == null)\n            {\n                throw new ArgumentNullException(\"folder\", HelpersToolkitResources.Themes_FolderCannotBeNull);\n            }\n\n            if (String.IsNullOrEmpty(fileName))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"fileName\");\n            }\n\n            return FindMatchingFile(Path.Combine(CurrentThemePath, folder), fileName) ??\n                   FindMatchingFile(Path.Combine(DefaultThemePath, folder), fileName);\n        }\n\n        /// <summary>\n        /// Try and find a file in the specified folder that matches name.\n        /// </summary>\n        /// <returns>The full path to the file that matches the requested file\n        /// or null if no matching file is found</returns>\n        internal string FindMatchingFile(string folder, string name)\n        {\n            Debug.Assert(!String.IsNullOrEmpty(folder));\n            Debug.Assert(!String.IsNullOrEmpty(name));\n\n            // Get the virtual path information\n            VirtualDirectory directory = _vpp.GetDirectory(folder);\n\n            // If the folder specified doesn't exist\n            // or it doesn't contain any files\n            if (directory == null || directory.Files == null)\n            {\n                return null;\n            }\n\n            // Go through every file in the directory\n            foreach (VirtualFile file in directory.Files)\n            {\n                string path = file.VirtualPath;\n\n                // Compare the filename to the filename that we passed\n                if (Path.GetFileName(path).Equals(name, StringComparison.OrdinalIgnoreCase))\n                {\n                    return path;\n                }\n            }\n\n            // If no matching files, return null\n            return null;\n        }\n\n        private ReadOnlyCollection<string> GetAvailableThemes(string themesRoot)\n        {\n            VirtualDirectory directory = _vpp.GetDirectory(themesRoot);\n\n            var themes = new List<string>();\n\n            // Go through every file in the directory\n            foreach (VirtualDirectory dir in directory.Directories)\n            {\n                themes.Add(dir.Name);\n            }\n            return themes.AsReadOnly();\n        }\n\n        private void EnsureInitialized()\n        {\n            if (!ThemesInitialized)\n            {\n                throw new InvalidOperationException(HelpersToolkitResources.Themes_NotInitialized);\n            }\n        }\n\n        private static bool IsValidTheme(IEnumerable<string> availableThemes, string theme)\n        {\n            return availableThemes.Contains(theme, StringComparer.OrdinalIgnoreCase);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Helpers/UrlBuilder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Globalization;\nusing System.Text;\nusing System.Web;\nusing System.Web.Routing;\nusing System.Web.WebPages;\n\nnamespace Microsoft.Web.Helpers\n{\n    public class UrlBuilder\n    {\n        private static readonly VirtualPathUtilityWrapper _defaultVirtualPathUtility = new VirtualPathUtilityWrapper();\n        private readonly VirtualPathUtilityBase _virtualPathUtility;\n        private readonly StringBuilder _params = new StringBuilder();\n        private string _path;\n\n        /// <summary>\n        /// Constructs an Url with the current page's virtual path and no query string parameters\n        /// </summary>\n        public UrlBuilder()\n            : this(null, null)\n        {\n        }\n\n        /// <summary>\n        /// Constructs an Url with the specified path and no query string parameters.\n        /// </summary>\n        public UrlBuilder(string path)\n            : this(path, null)\n        {\n        }\n\n        /// <summary>\n        /// Constructs an Url with the current page's virtual path and the parameters \n        /// </summary>\n        /// <param name=\"parameters\"></param>\n        public UrlBuilder(object parameters)\n            : this(null, parameters)\n        {\n        }\n\n        public UrlBuilder(string path, object parameters)\n            : this(GetHttpContext(), null, path, parameters)\n        {\n        }\n\n        internal UrlBuilder(HttpContextBase httpContext, VirtualPathUtilityBase virtualPathUtility, string path, object parameters)\n        {\n            _virtualPathUtility = virtualPathUtility;\n            Uri uri;\n            if (Uri.TryCreate(path, UriKind.Absolute, out uri))\n            {\n                _path = uri.GetLeftPart(UriPartial.Path);\n                _params.Append(uri.Query);\n            }\n            else\n            {\n                // If the url is being built as part of a WebPages request, use the template stack to identify the current template's virtual path.\n                _path = GetPageRelativePath(httpContext, path);\n                int queryStringIndex = (_path ?? String.Empty).IndexOf('?');\n                if (queryStringIndex != -1)\n                {\n                    _params.Append(_path.Substring(queryStringIndex));\n                    _path = _path.Substring(0, queryStringIndex);\n                }\n            }\n\n            if (parameters != null)\n            {\n                AddParam(parameters);\n            }\n        }\n\n        internal static VirtualPathUtilityBase DefaultVirtualPathUtility\n        {\n            get { return _defaultVirtualPathUtility; }\n        }\n\n        public string Path\n        {\n            get { return _path; }\n        }\n\n        public string QueryString\n        {\n            get { return _params.ToString(); }\n        }\n\n        private VirtualPathUtilityBase VirtualPathUtility\n        {\n            get { return _virtualPathUtility ?? _defaultVirtualPathUtility; }\n        }\n\n        /// <summary>\n        /// Factory method to create an UrlBuilder instance\n        /// </summary>\n        public static UrlBuilder Create(string path, object parameters = null)\n        {\n            return new UrlBuilder(path, parameters);\n        }\n\n        public UrlBuilder AddPath(string path)\n        {\n            _path = EnsureTrailingSlash(_path);\n            if (!path.IsEmpty())\n            {\n                _path += HttpUtility.UrlPathEncode(path.TrimStart('/'));\n            }\n            return this;\n        }\n\n        public UrlBuilder AddPath(params string[] pathTokens)\n        {\n            foreach (var token in pathTokens)\n            {\n                AddPath(token);\n            }\n            return this;\n        }\n\n        public UrlBuilder AddParam(string name, object value)\n        {\n            if (!String.IsNullOrEmpty(name))\n            {\n                _params.Append(_params.Length == 0 ? '?' : '&');\n                _params.Append(HttpUtility.UrlEncode(name))\n                    .Append('=')\n                    .Append(HttpUtility.UrlEncode(Convert.ToString(value, CultureInfo.InvariantCulture)));\n            }\n            return this;\n        }\n\n        public UrlBuilder AddParam(object values)\n        {\n            var dictionary = new RouteValueDictionary(values);\n            foreach (var item in dictionary)\n            {\n                AddParam(item.Key, item.Value);\n            }\n\n            return this;\n        }\n\n        public override string ToString()\n        {\n            return _path + _params;\n        }\n\n        private static HttpContextBase GetHttpContext()\n        {\n            return HttpContext.Current != null ? new HttpContextWrapper(HttpContext.Current) : null;\n        }\n\n        private static string EnsureTrailingSlash(string path)\n        {\n            if (!path.IsEmpty() && path[path.Length - 1] != '/')\n            {\n                path += '/';\n            }\n            return path;\n        }\n\n        private string GetPageRelativePath(HttpContextBase httpContext, string path)\n        {\n            if (httpContext == null)\n            {\n                return path;\n            }\n            var templateFile = TemplateStack.GetCurrentTemplate(httpContext);\n            if (templateFile != null)\n            {\n                var templateVirtualPath = templateFile.TemplateInfo.VirtualPath;\n                if (path.IsEmpty())\n                {\n                    path = templateVirtualPath;\n                }\n                else\n                {\n                    path = VirtualPathUtility.Combine(templateVirtualPath, path);\n                }\n            }\n            return VirtualPathUtility.ToAbsolute(path ?? \"~/\");\n        }\n\n        public static implicit operator string(UrlBuilder builder)\n        {\n            return builder.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Helpers/Video.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Web;\nusing System.Web.Routing;\nusing System.Web.WebPages;\nusing Microsoft.Internal.Web.Utils;\nusing Resources;\n\nnamespace Microsoft.Web.Helpers\n{\n    public static class Video\n    {\n        private const string FlashCab =\n            \"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab\";\n\n        private const string FlashClassId = \"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\";\n        private const string FlashMimeType = \"application/x-shockwave-flash\";\n        private const string MediaPlayerClassId = \"clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6\";\n        private const string MediaPlayerMimeType = \"application/x-mplayer2\";\n        private const string OleMimeType = \"application/x-oleobject\";\n        private const string SilverlightMimeType = \"application/x-silverlight-2\";\n\n        // These attributes can't be specified using anonymous objects (either because they are available as separate arguments or because\n        // they don't make sense in the context of the helper).\n        private static readonly string[] _globalBlacklist = new[] { \"width\", \"height\", \"type\", \"data\", \"classid\", \"codebase\" };\n        private static readonly string[] _mediaPlayerBlacklist = new[] { \"autoStart\", \"playCount\", \"uiMode\", \"stretchToFit\", \"enableContextMenu\", \"mute\", \"volume\", \"baseURL\" };\n        private static readonly string[] _silverlightBlacklist = new[] { \"background\", \"initparams\", \"minruntimeversion\", \"autoUpgrade\" };\n        private static readonly string[] _flashBlacklist = new[] { \"play\", \"loop\", \"menu\", \"bgColor\", \"quality\", \"scale\", \"wmode\", \"base\" };\n\n        private static VirtualPathUtilityWrapper _pathUtility = new VirtualPathUtilityWrapper();\n\n#if CODE_COVERAGE \n        [ExcludeFromCodeCoverage]\n#endif\n\n        private static HttpContextBase HttpContext\n        {\n            get\n            {\n                var httpContext = System.Web.HttpContext.Current;\n                return httpContext == null ? null : new HttpContextWrapper(httpContext);\n            }\n        }\n\n        // see: http://kb2.adobe.com/cps/127/tn_12701.html\n#if CODE_COVERAGE \n        [ExcludeFromCodeCoverage]\n#endif\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"10#\",\n            Justification = \"string parameter passed to flash in object tag\")]\n        [SuppressMessage(\"StyleCop.CSharp.NamingRules\", \"SA1305:FieldNamesMustNotUseHungarianNotation\", Target = \"bgColor\",\n            Justification = \"This method is public and the parameter name cannot be changed\")]\n        public static HelperResult Flash(string path, string width = null, string height = null,\n                                         bool play = true, bool loop = true, bool menu = true, string bgColor = null,\n                                         string quality = null, string scale = null, string windowMode = null, string baseUrl = null,\n                                         string version = null, object options = null, object htmlAttributes = null, string embedName = null)\n        {\n            return Flash(HttpContext, _pathUtility, path, width, height, play, loop, menu, bgColor,\n                         quality, scale, windowMode, baseUrl, version, options, htmlAttributes, embedName);\n        }\n\n        // see: http://msdn.microsoft.com/en-us/library/aa392321\n#if CODE_COVERAGE \n        [ExcludeFromCodeCoverage]\n#endif\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"10#\",\n            Justification = \"string parameter passed to media player in object tag\")]\n        public static HelperResult MediaPlayer(string path, string width = null, string height = null,\n                                               bool autoStart = true, int playCount = 1, string uiMode = null, bool stretchToFit = false,\n                                               bool enableContextMenu = true, bool mute = false, int volume = -1, string baseUrl = null,\n                                               object options = null, object htmlAttributes = null, string embedName = null)\n        {\n            return MediaPlayer(HttpContext, _pathUtility, path, width, height, autoStart, playCount, uiMode, stretchToFit,\n                               enableContextMenu, mute, volume, baseUrl, options, htmlAttributes, embedName);\n        }\n\n        // should users really use Silverlight.js?\n        // see: http://msdn.microsoft.com/en-us/library/cc838259(v=VS.95).aspx\n#if CODE_COVERAGE \n        [ExcludeFromCodeCoverage]\n#endif\n\n        [SuppressMessage(\"StyleCop.CSharp.NamingRules\", \"SA1305:FieldNamesMustNotUseHungarianNotation\", Target = \"bgColor\",\n           Justification = \"This method is public and the parameter name cannot be changed\")]\n        public static HelperResult Silverlight(string path, string width, string height,\n                                               string bgColor = null, string initParameters = null, string minimumVersion = null, bool autoUpgrade = true,\n                                               object options = null, object htmlAttributes = null)\n        {\n            return Silverlight(HttpContext, _pathUtility, path, width, height, bgColor, initParameters, minimumVersion, autoUpgrade,\n                               options, htmlAttributes);\n        }\n\n        internal static HelperResult Flash(HttpContextBase context, VirtualPathUtilityBase pathUtility, string path,\n                                           string width = null, string height = null, bool play = true, bool loop = true, bool menu = true,\n                                           string backgroundColor = null, string quality = null, string scale = null, string windowMode = null,\n                                           string baseUrl = null, string version = null, object options = null, object htmlAttributes = null, string embedName = null)\n        {\n            var parameters = ObjectToDictionary(options, \"options\", _flashBlacklist);\n            if (!play)\n            {\n                parameters[\"play\"] = false;\n            }\n            if (!loop)\n            {\n                parameters[\"loop\"] = false;\n            }\n            if (!menu)\n            {\n                parameters[\"menu\"] = false;\n            }\n            if (!String.IsNullOrEmpty(backgroundColor))\n            {\n                parameters[\"bgColor\"] = backgroundColor;\n            }\n            if (!String.IsNullOrEmpty(quality))\n            {\n                parameters[\"quality\"] = quality;\n            }\n            if (!String.IsNullOrEmpty(scale))\n            {\n                parameters[\"scale\"] = scale;\n            }\n            if (!String.IsNullOrEmpty(windowMode))\n            {\n                parameters[\"wmode\"] = windowMode;\n            }\n            if (!String.IsNullOrEmpty(baseUrl))\n            {\n                parameters[\"base\"] = baseUrl;\n            }\n\n            string cab = FlashCab;\n            if (!String.IsNullOrEmpty(version))\n            {\n                cab += \"#version=\" + version.Replace('.', ',');\n            }\n            return GetHtml(context, pathUtility, path, width, height,\n                           OleMimeType, null, FlashClassId, cab, \"movie\", FlashMimeType, parameters, htmlAttributes, embedName);\n        }\n\n        internal static HelperResult MediaPlayer(HttpContextBase context, VirtualPathUtilityBase pathUtility, string path, string width = null, string height = null,\n                                                 bool autoStart = true, int playCount = 1, string uiMode = null, bool stretchToFit = false,\n                                                 bool enableContextMenu = true, bool mute = false, int volume = -1, string baseUrl = null,\n                                                 object options = null, object htmlAttributes = null, string embedName = null)\n        {\n            var parameters = ObjectToDictionary(options, \"options\", _mediaPlayerBlacklist);\n            if (!autoStart)\n            {\n                parameters[\"autoStart\"] = false;\n            }\n            if (playCount != 1)\n            {\n                parameters[\"playCount\"] = playCount;\n            }\n            if (!String.IsNullOrEmpty(uiMode))\n            {\n                parameters[\"uiMode\"] = uiMode;\n            }\n            if (stretchToFit)\n            {\n                parameters[\"stretchToFit\"] = true;\n            }\n            if (!enableContextMenu)\n            {\n                parameters[\"enableContextMenu\"] = false;\n            }\n            if (mute)\n            {\n                parameters[\"mute\"] = true;\n            }\n            if (volume >= 0)\n            {\n                parameters[\"volume\"] = Math.Min(volume, 100);\n            }\n            if (!String.IsNullOrEmpty(baseUrl))\n            {\n                parameters[\"baseURL\"] = baseUrl;\n            }\n\n            return GetHtml(context, pathUtility, path, width, height,\n                           null, null, MediaPlayerClassId, null, \"URL\", MediaPlayerMimeType, parameters, htmlAttributes, embedName);\n        }\n\n        internal static HelperResult Silverlight(HttpContextBase context, VirtualPathUtilityBase pathUtility, string path, string width, string height,\n                                                 string backgroundColor = null, string initParameters = null, string minimumVersion = null, bool autoUpgrade = true,\n                                                 object options = null, object htmlAttributes = null)\n        {\n            if (String.IsNullOrEmpty(width))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"width\");\n            }\n            if (String.IsNullOrEmpty(height))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"height\");\n            }\n\n            var parameters = ObjectToDictionary(options, \"options\", _silverlightBlacklist);\n            if (!String.IsNullOrEmpty(backgroundColor))\n            {\n                parameters[\"background\"] = backgroundColor;\n            }\n            if (!String.IsNullOrEmpty(initParameters))\n            {\n                parameters[\"initparams\"] = initParameters;\n            }\n            if (!String.IsNullOrEmpty(minimumVersion))\n            {\n                parameters[\"minruntimeversion\"] = minimumVersion;\n            }\n            if (!autoUpgrade)\n            {\n                parameters[\"autoUpgrade\"] = autoUpgrade;\n            }\n\n            return GetHtml(context, pathUtility, path, width, height,\n                           SilverlightMimeType, \"data:\" + SilverlightMimeType + \",\", // ',' required for Opera support\n                           null, null, \"source\", null, parameters, htmlAttributes, null,\n                           tw =>\n                           {\n                               tw.WriteLine(\"<a href=\\\"http://go.microsoft.com/fwlink/?LinkID=149156\\\" style=\\\"text-decoration:none\\\">\");\n                               tw.WriteLine(\"<img src=\\\"http://go.microsoft.com/fwlink?LinkId=108181\\\" alt=\\\"Get Microsoft Silverlight\\\" style=\\\"border-style:none\\\"/>\");\n                               tw.WriteLine(\"</a>\");\n                           });\n        }\n\n        private static IDictionary<string, object> ObjectToDictionary(object o, string argName, string[] blackList)\n        {\n            var dictionary = new RouteValueDictionary(o);\n\n            foreach (var key in dictionary.Keys)\n            {\n                if (blackList.Contains(key, StringComparer.OrdinalIgnoreCase))\n                {\n                    throw new ArgumentException(String.Format(CultureInfo.CurrentUICulture,\n                                                              HelpersToolkitResources.Video_PropertyCannotBeSet, key), argName);\n                }\n            }\n            return dictionary;\n        }\n\n        private static HelperResult GetHtml(HttpContextBase context, VirtualPathUtilityBase pathUtility,\n                                            string path, string width, string height, string objectType, string objectDataType,\n                                            string objectClassId, string objectCodeBase, string pathParamName, string embedContentType,\n                                            IDictionary<string, object> parameters = null, object htmlAttributes = null, string embedName = null,\n                                            Action<TextWriter> plugin = null)\n        {\n            path = ValidatePath(context, pathUtility, path);\n\n            var objectAttr = ObjectToDictionary(htmlAttributes, \"htmlAttributes\", _globalBlacklist);\n            objectAttr[\"width\"] = width;\n            objectAttr[\"height\"] = height;\n            objectAttr[\"type\"] = objectType;\n            objectAttr[\"data\"] = objectDataType;\n            objectAttr[\"classid\"] = objectClassId;\n            objectAttr[\"codebase\"] = objectCodeBase;\n\n            return new HelperResult(tw =>\n            {\n                tw.Write(\"<object \");\n                foreach (var a in objectAttr.OrderBy(a => a.Key, StringComparer.OrdinalIgnoreCase))\n                {\n                    var value = (a.Value == null) ? null : a.Value.ToString();\n                    WriteIfNotNullOrEmpty(tw, a.Key, value);\n                }\n                tw.WriteLine(\">\");\n\n                // object parameters\n                if (!String.IsNullOrEmpty(pathParamName))\n                {\n                    tw.WriteLine(\"<param name=\\\"{0}\\\" value=\\\"{1}\\\" />\",\n                                 HttpUtility.HtmlAttributeEncode(pathParamName),\n                                 HttpUtility.HtmlAttributeEncode(HttpUtility.UrlPathEncode(path)));\n                }\n                if (parameters != null)\n                {\n                    foreach (var p in parameters)\n                    {\n                        tw.WriteLine(\"<param name=\\\"{0}\\\" value=\\\"{1}\\\" />\",\n                                     HttpUtility.HtmlAttributeEncode(p.Key),\n                                     HttpUtility.HtmlAttributeEncode(p.Value.ToString()));\n                    }\n                }\n\n                if (!String.IsNullOrEmpty(embedContentType))\n                {\n                    tw.Write(\"<embed src=\\\"{0}\\\" \", HttpUtility.HtmlAttributeEncode(HttpUtility.UrlPathEncode(path)));\n                    WriteIfNotNullOrEmpty(tw, \"width\", width);\n                    WriteIfNotNullOrEmpty(tw, \"height\", height);\n                    WriteIfNotNullOrEmpty(tw, \"name\", embedName);\n                    WriteIfNotNullOrEmpty(tw, \"type\", embedContentType);\n                    if (parameters != null)\n                    {\n                        foreach (var p in parameters)\n                        {\n                            tw.Write(\"{0}=\\\"{1}\\\" \", HttpUtility.HtmlEncode(p.Key), HttpUtility.HtmlAttributeEncode(p.Value.ToString()));\n                        }\n                    }\n                    tw.WriteLine(\"/>\");\n                }\n                if (plugin != null)\n                {\n                    plugin(tw);\n                }\n                tw.WriteLine(\"</object>\");\n            });\n        }\n\n        private static string ValidatePath(HttpContextBase context, VirtualPathUtilityBase pathUtility, string path)\n        {\n            if (String.IsNullOrEmpty(path))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"path\");\n            }\n            string originalPath = path;\n            if (!path.StartsWith(\"http\", StringComparison.OrdinalIgnoreCase))\n            {\n                // resolve relative paths\n                path = pathUtility.Combine(context.Request.AppRelativeCurrentExecutionFilePath, path);\n                // resolve to app absolute - SL doesn't support app relative\n                path = pathUtility.ToAbsolute(path);\n                if (!File.Exists(context.Server.MapPath(path)))\n                {\n                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentUICulture,\n                                                                      HelpersToolkitResources.Video_FileDoesNotExist, originalPath));\n                }\n            }\n            return path;\n        }\n\n        private static void WriteIfNotNullOrEmpty(TextWriter tw, string key, string value)\n        {\n            Debug.Assert(!String.IsNullOrEmpty(key));\n\n            if (!String.IsNullOrEmpty(value))\n            {\n                tw.Write(\"{0}=\\\"{1}\\\" \", HttpUtility.HtmlEncode(key), HttpUtility.HtmlAttributeEncode(value));\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Helpers/VirtualPathUtilityBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.Web.Helpers\n{\n    public abstract class VirtualPathUtilityBase\n    {\n        public abstract string Combine(string basePath, string relativePath);\n\n        public abstract string ToAbsolute(string virtualPath);\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Helpers/VirtualPathUtilityWrapper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web;\n\nnamespace Microsoft.Web.Helpers\n{\n    internal sealed class VirtualPathUtilityWrapper : VirtualPathUtilityBase\n    {\n        public override string Combine(string basePath, string relativePath)\n        {\n            return VirtualPathUtility.Combine(basePath, relativePath);\n        }\n\n        public override string ToAbsolute(string virtualPath)\n        {\n            return VirtualPathUtility.ToAbsolute(virtualPath);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Helpers/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"RazorGenerator.MsBuild\" version=\"2.2.0\" targetFramework=\"net45\" />\n</packages>"
  },
  {
    "path": "src/Microsoft.Web.Mvc/AcceptAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Web;\nusing System.Web.Mvc;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]\n    public sealed class AcceptAttribute : DataTypeAttribute, IClientValidatable\n    {\n        public AcceptAttribute()\n            : base(\"upload\")\n        {\n            ErrorMessage = MvcResources.FileExtensionsAttribute_Invalid;\n            ErrorMessage = MvcResources.AcceptAttribute_Invalid;\n        }\n\n        public string MimeTypes { get; set; }\n\n        private string MimeTypesFormatted\n        {\n            get { return MimeTypesParsed.Aggregate((left, right) => left + \", \" + right); }\n        }\n\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1308:NormalizeStringsToUppercase\", Justification = \"These strings are normalized to lowercase because they are presented to the user in lowercase format\")]\n        private string MimeTypesNormalized\n        {\n            get { return MimeTypes.Replace(\" \", String.Empty).ToLowerInvariant(); }\n        }\n\n        private IEnumerable<string> MimeTypesParsed\n        {\n            get { return MimeTypesNormalized.Split(','); }\n        }\n\n        public override string FormatErrorMessage(string name)\n        {\n            return String.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, MimeTypesFormatted);\n        }\n\n        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)\n        {\n            var rule = new ModelClientValidationRule\n            {\n                ValidationType = \"accept\",\n                ErrorMessage = FormatErrorMessage(metadata.GetDisplayName())\n            };\n            rule.ValidationParameters[\"mimetype\"] = MimeTypesNormalized;\n            yield return rule;\n        }\n\n        public override bool IsValid(object value)\n        {\n            if (value == null)\n            {\n                return true;\n            }\n\n            HttpPostedFileBase valueAsFileBase = value as HttpPostedFileBase;\n            if (valueAsFileBase != null)\n            {\n                return ValidateMimeTypes(valueAsFileBase.ContentType);\n            }\n\n            string valueAsString = value as string;\n            if (valueAsString != null)\n            {\n                return ValidateMimeTypes(valueAsString);\n            }\n\n            return false;\n        }\n\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1308:NormalizeStringsToUppercase\", Justification = \"These strings are normalized to lowercase because they are presented to the user in lowercase format\")]\n        private bool ValidateMimeTypes(string mimeType)\n        {\n            return MimeTypesParsed.Contains(mimeType.ToLowerInvariant());\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ActionLinkAreaAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\n\nnamespace Microsoft.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]\n    public sealed class ActionLinkAreaAttribute : Attribute\n    {\n        public ActionLinkAreaAttribute(string area)\n        {\n            if (area == null)\n            {\n                throw new ArgumentNullException(\"area\");\n            }\n\n            Area = area;\n        }\n\n        public string Area { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/AjaxOnlyAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Reflection;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\n    public sealed class AjaxOnlyAttribute : ActionMethodSelectorAttribute\n    {\n        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n\n            // Dev10 #939671 - If this attribute is going to say AJAX *only*, then we need to check the header\n            // specifically, as otherwise clients can modify the form or query string to contain the name/value\n            // pair we're looking for.\n            return (controllerContext.HttpContext.Request.Headers[\"X-Requested-With\"] == \"XMLHttpRequest\");\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/AreaHelpers.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc;\nusing System.Web.Routing;\n\nnamespace Microsoft.Web.Mvc\n{\n    public static class AreaHelpers\n    {\n        public static string GetAreaName(RouteBase route)\n        {\n            IRouteWithArea routeWithArea = route as IRouteWithArea;\n            if (routeWithArea != null)\n            {\n                return routeWithArea.Area;\n            }\n\n            Route castRoute = route as Route;\n            if (castRoute != null && castRoute.DataTokens != null)\n            {\n                return castRoute.DataTokens[\"area\"] as string;\n            }\n\n            return null;\n        }\n\n        public static string GetAreaName(RouteData routeData)\n        {\n            object area;\n            if (routeData.DataTokens.TryGetValue(\"area\", out area))\n            {\n                return area as string;\n            }\n\n            return GetAreaName(routeData.Route);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/AsyncManagerExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Mvc.Async;\n\nnamespace Microsoft.Web.Mvc\n{\n    public static class AsyncManagerExtensions\n    {\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"An unhandled exception here will bring down the worker process.\")]\n        [SuppressMessage(\"StyleCop.CSharp.MaintainabilityRules\", \"SA1409:RemoveUnnecessaryCode\",\n            Justification = \"The empty lock statement is required for synchronization.\")]\n        public static void RegisterTask(this AsyncManager asyncManager, Func<AsyncCallback, IAsyncResult> beginDelegate, Action<IAsyncResult> endDelegate)\n        {\n            if (asyncManager == null)\n            {\n                throw new ArgumentNullException(\"asyncManager\");\n            }\n            if (beginDelegate == null)\n            {\n                throw new ArgumentNullException(\"beginDelegate\");\n            }\n            if (endDelegate == null)\n            {\n                throw new ArgumentNullException(\"endDelegate\");\n            }\n\n            // need to wait to execute the callback until after BeginXxx() has completed\n            object delegateExecutingLockObj = new object();\n\n            AsyncCallback callback = ar =>\n            {\n                lock (delegateExecutingLockObj)\n                {\n                    // this empty lock is required to synchronized with the beginDelegate call\n                }\n                if (!ar.CompletedSynchronously)\n                {\n                    try\n                    {\n                        asyncManager.Sync(() => endDelegate(ar)); // called on different thread, so have to take application lock\n                    }\n                    catch\n                    {\n                        // Need to swallow exceptions, as otherwise unhandled exceptions on a ThreadPool thread\n                        // can bring down the entire worker process.\n                    }\n                    finally\n                    {\n                        asyncManager.OutstandingOperations.Decrement();\n                    }\n                }\n            };\n\n            IAsyncResult asyncResult;\n            asyncManager.OutstandingOperations.Increment();\n            try\n            {\n                lock (delegateExecutingLockObj)\n                {\n                    asyncResult = beginDelegate(callback);\n                }\n            }\n            catch\n            {\n                asyncManager.OutstandingOperations.Decrement();\n                throw;\n            }\n\n            if (asyncResult.CompletedSynchronously)\n            {\n                try\n                {\n                    endDelegate(asyncResult); // call on same thread\n                }\n                finally\n                {\n                    asyncManager.OutstandingOperations.Decrement();\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ButtonBuilder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc\n{\n    public static class ButtonBuilder\n    {\n        public static TagBuilder SubmitButton(string name, string buttonText, IDictionary<string, object> htmlAttributes)\n        {\n            TagBuilder buttonTag = new TagBuilder(\"input\");\n\n            buttonTag.MergeAttribute(\"type\", \"submit\");\n            if (!buttonTag.Attributes.ContainsKey(\"id\") && name != null)\n            {\n                buttonTag.GenerateId(name);\n            }\n\n            if (!String.IsNullOrEmpty(name))\n            {\n                buttonTag.MergeAttribute(\"name\", name);\n            }\n\n            if (!String.IsNullOrEmpty(buttonText))\n            {\n                buttonTag.MergeAttribute(\"value\", buttonText);\n            }\n\n            buttonTag.MergeAttributes(htmlAttributes, true);\n            return buttonTag;\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"The return value is not a regular URL since it may contain ~/ ASP.NET-specific characters\")]\n        public static TagBuilder SubmitImage(string name, string sourceUrl, IDictionary<string, object> htmlAttributes)\n        {\n            TagBuilder buttonTag = new TagBuilder(\"input\");\n\n            buttonTag.MergeAttribute(\"type\", \"image\");\n\n            if (!buttonTag.Attributes.ContainsKey(\"id\"))\n            {\n                buttonTag.GenerateId(name);\n            }\n\n            if (!String.IsNullOrEmpty(name))\n            {\n                buttonTag.MergeAttribute(\"name\", name);\n            }\n\n            if (!String.IsNullOrEmpty(sourceUrl))\n            {\n                buttonTag.MergeAttribute(\"src\", sourceUrl);\n            }\n            buttonTag.MergeAttributes(htmlAttributes, true);\n            return buttonTag;\n        }\n\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1308:NormalizeStringsToUppercase\", Justification = \"This conversion is appropriate because it's for HTML, not for comparsion normalization\")]\n        public static TagBuilder Button(string name, string buttonText, HtmlButtonType type, string onClickMethod, IDictionary<string, object> htmlAttributes)\n        {\n            if (name == null)\n            {\n                throw new ArgumentNullException(\"name\");\n            }\n\n            TagBuilder buttonTag = new TagBuilder(\"button\");\n\n            if (!String.IsNullOrEmpty(name))\n            {\n                buttonTag.MergeAttribute(\"name\", name);\n            }\n\n            buttonTag.MergeAttribute(\"type\", type.ToString().ToLowerInvariant());\n\n            buttonTag.InnerHtml = buttonText;\n\n            if (!String.IsNullOrEmpty(onClickMethod))\n            {\n                buttonTag.MergeAttribute(\"onclick\", onClickMethod);\n            }\n\n            buttonTag.MergeAttributes(htmlAttributes, true);\n            return buttonTag;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ButtonsAndLinkExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc\n{\n    public static class ButtonsAndLinkExtensions\n    {\n        /// <summary>\n        /// Creates a submit button for your form\n        /// </summary>\n        /// <param name=\"helper\">The helper which we extend.</param>\n        /// <param name=\"name\">The name.</param>\n        /// <returns></returns>\n        public static MvcHtmlString SubmitButton(this HtmlHelper helper, string name)\n        {\n            return SubmitButton(helper, name, null, null);\n        }\n\n        /// <summary>\n        /// Creates a submit button for your form\n        /// </summary>\n        /// <param name=\"helper\">The helper which we extend.</param>\n        /// <param name=\"name\">The name.</param>\n        /// <param name=\"buttonText\">The text for the button face</param>\n        /// <returns></returns>\n        public static MvcHtmlString SubmitButton(this HtmlHelper helper, string name, string buttonText)\n        {\n            return SubmitButton(helper, name, buttonText, null);\n        }\n\n        /// <summary>\n        /// Creates a submit button for your form\n        /// </summary>\n        /// <param name=\"helper\">The helper which we extend.</param>\n        public static MvcHtmlString SubmitButton(this HtmlHelper helper)\n        {\n            return SubmitButton(helper, null, null, null);\n        }\n\n        /// <summary>\n        /// Creates a submit button for your form\n        /// </summary>\n        /// <param name=\"helper\">The helper which we extend.</param>\n        /// <param name=\"name\">Name of the button</param>\n        /// <param name=\"buttonText\">The text for the button face</param>\n        /// <param name=\"htmlAttributes\">Any attributes you want set on the tag. Use anonymous-type declaration for this: new{class=cssclass}</param>\n        /// <returns></returns>\n        public static MvcHtmlString SubmitButton(this HtmlHelper helper, string name, string buttonText, object htmlAttributes)\n        {\n            return helper.SubmitButton(name, buttonText, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        /// <summary>\n        /// Creates a submit button for your form\n        /// </summary>\n        /// <param name=\"helper\">The helper which we extend.</param>\n        /// <param name=\"name\">Name of the button</param>\n        /// <param name=\"buttonText\">The text for the button face</param>\n        /// <param name=\"htmlAttributes\">Dictionary of HTML settings</param>\n        /// <returns></returns>\n        [SuppressMessage(\"Microsoft.Usage\", \"CA1801:ReviewUnusedParameters\", MessageId = \"helper\", Justification = \"Required for Extension Method\")]\n        public static MvcHtmlString SubmitButton(this HtmlHelper helper, string name, string buttonText, IDictionary<string, object> htmlAttributes)\n        {\n            return MvcHtmlString.Create(ButtonBuilder.SubmitButton(name, buttonText, htmlAttributes).ToString(TagRenderMode.SelfClosing));\n        }\n\n        /// <summary>\n        /// Creates a submit button for your form using an image\n        /// </summary>\n        /// <param name=\"helper\">The helper which we extend.</param>\n        /// <param name=\"name\">Name of the button</param>\n        /// <param name=\"imageSrc\">The URL for the image</param>\n        /// <returns></returns>\n        public static MvcHtmlString SubmitImage(this HtmlHelper helper, string name, string imageSrc)\n        {\n            return helper.SubmitImage(name, imageSrc, null);\n        }\n\n        /// <summary>\n        /// Creates a submit button for your form using an image\n        /// </summary>\n        /// <param name=\"helper\">The helper which we extend.</param>\n        /// <param name=\"name\">Name of the button</param>\n        /// <param name=\"imageSrc\">The URL for the image</param>\n        /// <param name=\"htmlAttributes\">Any attributes you want set on the tag. Use anonymous-type declaration for this: new{class=cssclass}</param>\n        /// <returns></returns>\n        public static MvcHtmlString SubmitImage(this HtmlHelper helper, string name, string imageSrc, object htmlAttributes)\n        {\n            return helper.SubmitImage(name, imageSrc, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        /// <summary>\n        /// Creates a submit button for your form using an image\n        /// </summary>\n        /// <param name=\"helper\">The helper which we extend.</param>\n        /// <param name=\"name\">Name of the button</param>\n        /// <param name=\"imageSrc\">The URL for the image</param>\n        /// <param name=\"htmlAttributes\">Dictionary of HTML settings</param>\n        /// <returns></returns>\n        public static MvcHtmlString SubmitImage(this HtmlHelper helper, string name, string imageSrc, IDictionary<string, object> htmlAttributes)\n        {\n            if (imageSrc == null)\n            {\n                throw new ArgumentNullException(\"imageSrc\");\n            }\n\n            string resolvedUrl = UrlHelper.GenerateContentUrl(imageSrc, helper.ViewContext.HttpContext);\n            return MvcHtmlString.Create(ButtonBuilder.SubmitImage(name, resolvedUrl, htmlAttributes).ToString(TagRenderMode.SelfClosing));\n        }\n\n        /// <summary>\n        /// A Simple button you can use with javascript\n        /// </summary>\n        /// <param name=\"helper\">The helper which we extend.</param>\n        /// <param name=\"name\">Name of the button</param>\n        /// <param name=\"buttonText\">The text for the button face</param>\n        /// <param name=\"buttonType\">The button type (Button, Submit, or Reset)</param>\n        /// <returns></returns>\n        public static MvcHtmlString Button(this HtmlHelper helper, string name, string buttonText, HtmlButtonType buttonType)\n        {\n            return helper.Button(name, buttonText, buttonType, null, (IDictionary<string, object>)null);\n        }\n\n        /// <summary>\n        /// A Simple button you can use with javascript\n        /// </summary>\n        /// <param name=\"helper\">The helper which we extend.</param>\n        /// <param name=\"name\">Name of the button</param>\n        /// <param name=\"buttonText\">The text for the button face</param>\n        /// <param name=\"buttonType\">The button type (Button, Submit, or Reset)</param>\n        /// <param name=\"onClickMethod\">The method or script routine to call when the button is clicked.</param>\n        /// <returns></returns>\n        public static MvcHtmlString Button(this HtmlHelper helper, string name, string buttonText, HtmlButtonType buttonType, string onClickMethod)\n        {\n            return helper.Button(name, buttonText, buttonType, onClickMethod, (IDictionary<string, object>)null);\n        }\n\n        /// <summary>\n        /// A Simple button you can use with javascript\n        /// </summary>\n        /// <param name=\"helper\">The helper which we extend.</param>\n        /// <param name=\"name\">Name of the button</param>\n        /// <param name=\"buttonText\">The text for the button face</param>\n        /// <param name=\"buttonType\">The button type (Button, Submit, or Reset)</param>\n        /// <param name=\"onClickMethod\">The method or script routine to call when the button is clicked.</param>\n        /// <param name=\"htmlAttributes\">Any attributes you want set on the tag. Use anonymous-type declaration for this: new{class=cssclass}</param>\n        /// <returns></returns>\n        public static MvcHtmlString Button(this HtmlHelper helper, string name, string buttonText, HtmlButtonType buttonType, string onClickMethod, object htmlAttributes)\n        {\n            return helper.Button(name, buttonText, buttonType, onClickMethod, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        /// <summary>\n        /// A Simple button you can use with javascript\n        /// </summary>\n        /// <param name=\"helper\">The helper which we extend.</param>\n        /// <param name=\"name\">Name of the button</param>\n        /// <param name=\"buttonText\">The text for the button face</param>\n        /// <param name=\"buttonType\">The button type (Button, Submit, or Reset)</param>\n        /// <param name=\"onClickMethod\">The method or script routine to call when the button is clicked.</param>\n        /// <param name=\"htmlAttributes\">Any attributes you want set on the tag. Use anonymous-type declaration for this: new{class=cssclass}</param>\n        /// <returns></returns>\n        [SuppressMessage(\"Microsoft.Usage\", \"CA1801:ReviewUnusedParameters\", MessageId = \"helper\", Justification = \"This is an Extension Method and requires this argument\")]\n        public static MvcHtmlString Button(this HtmlHelper helper, string name, string buttonText, HtmlButtonType buttonType, string onClickMethod, IDictionary<string, object> htmlAttributes)\n        {\n            return MvcHtmlString.Create(ButtonBuilder.Button(name, buttonText, buttonType, onClickMethod, htmlAttributes).ToString(TagRenderMode.Normal));\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/CachedExpressionCompiler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\n\nnamespace Microsoft.Web.Mvc\n{\n    // The caching expression tree compiler was copied from MVC core to MVC Futures so that Futures code could benefit\n    // from it and so that it could be exposed as a public API. This is the only public entry point into the system.\n    // See the comments in the ExpressionUtil namespace for more information.\n    //\n    // The unit tests for the ExpressionUtil.* types are in the System.Web.Mvc.Test project.\n    public static class CachedExpressionCompiler\n    {\n        private static readonly ParameterExpression _unusedParameterExpr = Expression.Parameter(typeof(object), \"_unused\");\n\n        // Implements caching around LambdaExpression.Compile() so that equivalent expression trees only have to be\n        // compiled once.\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static Func<TModel, TValue> Compile<TModel, TValue>(this Expression<Func<TModel, TValue>> lambdaExpression)\n        {\n            if (lambdaExpression == null)\n            {\n                throw new ArgumentNullException(\"lambdaExpression\");\n            }\n\n            return ExpressionUtil.CachedExpressionCompiler.Process(lambdaExpression);\n        }\n\n        // Evaluates an expression (not a LambdaExpression), e.g. 2 + 2.\n        public static object Evaluate(Expression arg)\n        {\n            if (arg == null)\n            {\n                throw new ArgumentNullException(\"arg\");\n            }\n\n            Func<object, object> func = Wrap(arg);\n            return func(null);\n        }\n\n        private static Func<object, object> Wrap(Expression arg)\n        {\n            Expression<Func<object, object>> lambdaExpr = Expression.Lambda<Func<object, object>>(Expression.Convert(arg, typeof(object)), _unusedParameterExpr);\n            return ExpressionUtil.CachedExpressionCompiler.Process(lambdaExpr);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ContentTypeAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Mvc;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\n    public sealed class ContentTypeAttribute : ActionFilterAttribute\n    {\n        public ContentTypeAttribute(string contentType)\n        {\n            if (String.IsNullOrEmpty(contentType))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"contentType\");\n            }\n\n            ContentType = contentType;\n        }\n\n        public string ContentType { get; private set; }\n\n        public override void OnResultExecuting(ResultExecutingContext filterContext)\n        {\n            filterContext.HttpContext.Response.ContentType = ContentType;\n        }\n\n        public override void OnResultExecuted(ResultExecutedContext filterContext)\n        {\n            filterContext.HttpContext.Response.ContentType = ContentType;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ControllerExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\nusing System.Web.Mvc;\nusing System.Web.Routing;\nusing ExpressionHelper = Microsoft.Web.Mvc.Internal.ExpressionHelper;\n\nnamespace Microsoft.Web.Mvc\n{\n    public static class ControllerExtensions\n    {\n        // Shortcut to allow users to write this.RedirectToAction(x => x.OtherMethod()) to redirect\n        // to a different method on the same controller.\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static RedirectToRouteResult RedirectToAction<TController>(this TController controller, Expression<Action<TController>> action) where TController : Controller\n        {\n            return RedirectToAction((Controller)controller, action);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static RedirectToRouteResult RedirectToAction<TController>(this Controller controller, Expression<Action<TController>> action) where TController : Controller\n        {\n            if (controller == null)\n            {\n                throw new ArgumentNullException(\"controller\");\n            }\n\n            RouteValueDictionary routeValues = ExpressionHelper.GetRouteValuesFromExpression(action);\n            return new RedirectToRouteResult(routeValues);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Controls/ActionLink.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.ComponentModel;\nusing System.Web.Mvc;\nusing System.Web.Routing;\nusing System.Web.UI;\n\nnamespace Microsoft.Web.Mvc.Controls\n{\n    [ParseChildren(true)]\n    [PersistChildren(false)]\n    public class ActionLink : MvcControl\n    {\n        private string _actionName;\n        private string _controllerName;\n        private string _text;\n        private string _routeName;\n        private RouteValues _values;\n\n        [DefaultValue(\"\")]\n        public string ActionName\n        {\n            get { return _actionName ?? String.Empty; }\n            set { _actionName = value; }\n        }\n\n        [DefaultValue(\"\")]\n        public string ControllerName\n        {\n            get { return _controllerName ?? String.Empty; }\n            set { _controllerName = value; }\n        }\n\n        [DefaultValue(\"\")]\n        public string RouteName\n        {\n            get { return _routeName ?? String.Empty; }\n            set { _routeName = value; }\n        }\n\n        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]\n        [PersistenceMode(PersistenceMode.InnerProperty)]\n        public RouteValues Values\n        {\n            get\n            {\n                if (_values == null)\n                {\n                    _values = new RouteValues();\n                }\n                return _values;\n            }\n        }\n\n        public string Text\n        {\n            get { return _text ?? String.Empty; }\n            set { _text = value; }\n        }\n\n        protected override void Render(HtmlTextWriter writer)\n        {\n            RouteValueDictionary routeValues = new RouteValueDictionary();\n            foreach (var attribute in Values.Attributes)\n            {\n                routeValues.Add(attribute.Key, attribute.Value);\n            }\n\n            if (!String.IsNullOrEmpty(ActionName) && !routeValues.ContainsKey(\"action\"))\n            {\n                routeValues.Add(\"action\", ActionName);\n            }\n            if (!String.IsNullOrEmpty(ControllerName) && !routeValues.ContainsKey(\"controller\"))\n            {\n                routeValues.Add(\"controller\", ControllerName);\n            }\n\n            string href = null;\n            if (DesignMode)\n            {\n                href = \"/\";\n            }\n            else\n            {\n                VirtualPathData vpd = RouteTable.Routes.GetVirtualPathForArea(ViewContext.RequestContext, RouteName, routeValues);\n                if (vpd == null)\n                {\n                    throw new InvalidOperationException(\"A route that matches the requested values could not be located in the route table.\");\n                }\n                href = vpd.VirtualPath;\n            }\n\n            foreach (var attribute in Attributes)\n            {\n                writer.AddAttribute(attribute.Key, attribute.Value);\n            }\n\n            if (!Attributes.ContainsKey(\"href\"))\n            {\n                writer.AddAttribute(HtmlTextWriterAttribute.Href, href);\n            }\n\n            writer.RenderBeginTag(HtmlTextWriterTag.A);\n\n            writer.WriteEncodedText(Text);\n\n            writer.RenderEndTag();\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Controls/DropDownList.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Linq;\nusing System.Web.Mvc;\nusing System.Web.UI;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc.Controls\n{\n    // TODO: Have ListBoxBase class to use with DropDownList and ListBox?\n    // TODO: Do we need a way to explicitly specify the items? And only get the selected value(s) from ViewData?\n\n    public class DropDownList : MvcControl\n    {\n        private string _name;\n        private string _optionLabel;\n\n        [DefaultValue(\"\")]\n        public string Name\n        {\n            get { return _name ?? String.Empty; }\n            set { _name = value; }\n        }\n\n        [DefaultValue(\"\")]\n        public string OptionLabel\n        {\n            get { return _optionLabel ?? String.Empty; }\n            set { _optionLabel = value; }\n        }\n\n        private object GetModelStateValue(string key, Type destinationType)\n        {\n            ModelState modelState;\n            if (ViewData.ModelState.TryGetValue(key, out modelState))\n            {\n                return modelState.Value.ConvertTo(destinationType, null /* culture */);\n            }\n            return null;\n        }\n\n        private IEnumerable<SelectListItem> GetSelectData(string name)\n        {\n            object o = null;\n            if (ViewData != null)\n            {\n                o = ViewData.Eval(name);\n            }\n            if (o == null)\n            {\n                throw new InvalidOperationException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.HtmlHelper_MissingSelectData,\n                        name,\n                        \"IEnumerable<SelectListItem>\"));\n            }\n            IEnumerable<SelectListItem> selectList = o as IEnumerable<SelectListItem>;\n            if (selectList == null)\n            {\n                throw new InvalidOperationException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.HtmlHelper_WrongSelectDataType,\n                        name,\n                        o.GetType().FullName,\n                        \"IEnumerable<SelectListItem>\"));\n            }\n            return selectList;\n        }\n\n        protected override void Render(HtmlTextWriter writer)\n        {\n            if (!DesignMode && String.IsNullOrEmpty(Name))\n            {\n                throw new InvalidOperationException(MvcResources.CommonControls_NameRequired);\n            }\n\n            if (DesignMode)\n            {\n                RenderDesignMode(writer);\n            }\n            else\n            {\n                RenderRuntime(writer);\n            }\n        }\n\n        private void RenderDesignMode(HtmlTextWriter writer)\n        {\n            writer.RenderBeginTag(HtmlTextWriterTag.Select);\n            writer.RenderBeginTag(HtmlTextWriterTag.Option);\n            if (String.IsNullOrEmpty(OptionLabel))\n            {\n                writer.WriteEncodedText(MvcResources.DropDownList_SampleItem);\n            }\n            else\n            {\n                writer.WriteEncodedText(OptionLabel);\n            }\n            writer.RenderEndTag();\n            writer.RenderEndTag();\n        }\n\n        private void RenderRuntime(HtmlTextWriter writer)\n        {\n            // TODO: Move this to the base class once it exists\n            bool allowMultiple = false;\n\n            SortedDictionary<string, string> attrs = new SortedDictionary<string, string>();\n\n            foreach (KeyValuePair<string, string> attribute in Attributes)\n            {\n                attrs.Add(attribute.Key, attribute.Value);\n            }\n\n            attrs.Add(\"name\", Name);\n            if (!String.IsNullOrEmpty(ID))\n            {\n                attrs.Add(\"id\", ID);\n            }\n            if (allowMultiple)\n            {\n                attrs.Add(\"multiple\", \"multiple\");\n            }\n\n            // If there are any errors for a named field, we add the css attribute.\n            ModelState modelState;\n            if (ViewData.ModelState.TryGetValue(Name, out modelState))\n            {\n                if (modelState.Errors.Count > 0)\n                {\n                    string currentValue;\n\n                    if (attrs.TryGetValue(\"class\", out currentValue))\n                    {\n                        attrs[\"class\"] = HtmlHelper.ValidationInputCssClassName + \" \" + currentValue;\n                    }\n                    else\n                    {\n                        attrs[\"class\"] = HtmlHelper.ValidationInputCssClassName;\n                    }\n                }\n            }\n\n            foreach (KeyValuePair<string, string> attribute in attrs)\n            {\n                writer.AddAttribute(attribute.Key, Convert.ToString(attribute.Value, CultureInfo.CurrentCulture));\n            }\n\n            writer.RenderBeginTag(HtmlTextWriterTag.Select);\n\n            // Use ViewData to get the list of items\n            IEnumerable<SelectListItem> selectList = GetSelectData(Name);\n\n            object defaultValue = (allowMultiple) ? GetModelStateValue(Name, typeof(string[])) : GetModelStateValue(Name, typeof(string));\n\n            if (defaultValue != null)\n            {\n                IEnumerable defaultValues = (allowMultiple) ? defaultValue as IEnumerable : new[] { defaultValue };\n                IEnumerable<string> values = from object value in defaultValues\n                                             select Convert.ToString(value, CultureInfo.CurrentCulture);\n                HashSet<string> selectedValues = new HashSet<string>(values, StringComparer.OrdinalIgnoreCase);\n                List<SelectListItem> newSelectList = new List<SelectListItem>();\n\n                foreach (SelectListItem item in selectList)\n                {\n                    item.Selected = (item.Value != null) ? selectedValues.Contains(item.Value) : selectedValues.Contains(item.Text);\n                    newSelectList.Add(item);\n                }\n                selectList = newSelectList;\n            }\n\n            // Render the option label if it exists\n            if (!String.IsNullOrEmpty(OptionLabel))\n            {\n                writer.AddAttribute(HtmlTextWriterAttribute.Value, String.Empty);\n                writer.RenderBeginTag(HtmlTextWriterTag.Option);\n                writer.WriteEncodedText(OptionLabel);\n                writer.RenderEndTag();\n            }\n\n            // Render out the list items\n            foreach (SelectListItem listItem in selectList)\n            {\n                if (listItem.Value != null)\n                {\n                    writer.AddAttribute(HtmlTextWriterAttribute.Value, listItem.Value);\n                }\n                if (listItem.Selected)\n                {\n                    writer.AddAttribute(HtmlTextWriterAttribute.Selected, \"selected\");\n                }\n                writer.RenderBeginTag(HtmlTextWriterTag.Option);\n                writer.WriteEncodedText(listItem.Text);\n                writer.RenderEndTag();\n            }\n\n            writer.RenderEndTag();\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Controls/EncodeType.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.Web.Mvc.Controls\n{\n    public enum EncodeType\n    {\n        Html,\n        HtmlAttribute,\n        None,\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Controls/Hidden.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.Web.Mvc.Controls\n{\n    public class Hidden : MvcInputControl\n    {\n        public Hidden()\n            : base(\"hidden\")\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Controls/Label.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Web;\nusing System.Web.UI;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc.Controls\n{\n    public class Label : MvcControl\n    {\n        private string _format;\n        private string _name;\n        private int _truncateLength = -1;\n        private string _truncateText = \"...\";\n\n        [DefaultValue(EncodeType.Html)]\n        public EncodeType EncodeType { get; set; }\n\n        [DefaultValue(\"\")]\n        public string Format\n        {\n            get { return _format ?? String.Empty; }\n            set { _format = value; }\n        }\n\n        [DefaultValue(\"\")]\n        public string Name\n        {\n            get { return _name ?? String.Empty; }\n            set { _name = value; }\n        }\n\n        [DefaultValue(-1)]\n        [Description(\"The length of the text at which to truncate the value. Set to -1 to never truncate.\")]\n        public int TruncateLength\n        {\n            get { return _truncateLength; }\n            set\n            {\n                if (value < -1)\n                {\n                    throw new ArgumentOutOfRangeException(\"value\", \"The TruncateLength property must be greater than or equal to -1.\");\n                }\n                _truncateLength = value;\n            }\n        }\n\n        [DefaultValue(\"...\")]\n        [Description(\"The text to display at the end of the string if it is truncated. This text is never encoded.\")]\n        public string TruncateText\n        {\n            get { return _truncateText ?? String.Empty; }\n            set { _truncateText = value; }\n        }\n\n        protected override void Render(HtmlTextWriter writer)\n        {\n            if (!DesignMode && String.IsNullOrEmpty(Name))\n            {\n                throw new InvalidOperationException(MvcResources.CommonControls_NameRequired);\n            }\n\n            string stringValue = String.Empty;\n            if (ViewData != null)\n            {\n                object rawValue = ViewData.Eval(Name);\n\n                if (String.IsNullOrEmpty(Format))\n                {\n                    stringValue = Convert.ToString(rawValue, CultureInfo.CurrentCulture);\n                }\n                else\n                {\n                    stringValue = String.Format(CultureInfo.CurrentCulture, Format, rawValue);\n                }\n            }\n\n            writer.AddAttribute(HtmlTextWriterAttribute.Name, Name);\n            if (!String.IsNullOrEmpty(ID))\n            {\n                writer.AddAttribute(HtmlTextWriterAttribute.Id, ID);\n            }\n\n            bool wasTruncated = false;\n            if ((TruncateLength >= 0) && (stringValue.Length > TruncateLength))\n            {\n                stringValue = stringValue.Substring(0, TruncateLength);\n                wasTruncated = true;\n            }\n\n            switch (EncodeType)\n            {\n                case EncodeType.Html:\n                    writer.Write(HttpUtility.HtmlEncode(stringValue));\n                    break;\n                case EncodeType.HtmlAttribute:\n                    writer.Write(HttpUtility.HtmlAttributeEncode(stringValue));\n                    break;\n                case EncodeType.None:\n                    writer.Write(stringValue);\n                    break;\n            }\n\n            if (wasTruncated)\n            {\n                writer.Write(TruncateText);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Controls/MvcControl.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Web.Mvc;\nusing System.Web.UI;\n\nnamespace Microsoft.Web.Mvc.Controls\n{\n    // TODO: Consider using custom HTML writer instead of the default one to get prettier rendering\n\n    public abstract class MvcControl : Control, IAttributeAccessor\n    {\n        private IDictionary<string, string> _attributes;\n        private IViewDataContainer _viewDataContainer;\n        private ViewContext _viewContext;\n\n        [Browsable(false)]\n        public IDictionary<string, string> Attributes\n        {\n            get\n            {\n                EnsureAttributes();\n                return _attributes;\n            }\n        }\n\n        [Browsable(false)]\n        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\n        public override bool EnableViewState\n        {\n            get { return base.EnableViewState; }\n            set { base.EnableViewState = value; }\n        }\n\n        public ViewContext ViewContext\n        {\n            get\n            {\n                if (_viewContext == null)\n                {\n                    // TODO: Is this logic correct? Why not just case Page to ViewPage?\n                    Control parent = Parent;\n                    while (parent != null)\n                    {\n                        ViewPage viewPage = parent as ViewPage;\n                        if (viewPage != null)\n                        {\n                            _viewContext = viewPage.ViewContext;\n                            break;\n                        }\n                        parent = parent.Parent;\n                    }\n                }\n                return _viewContext;\n            }\n        }\n\n        public IViewDataContainer ViewDataContainer\n        {\n            get\n            {\n                if (_viewDataContainer == null)\n                {\n                    Control parent = Parent;\n                    while (parent != null)\n                    {\n                        _viewDataContainer = parent as IViewDataContainer;\n                        if (_viewDataContainer != null)\n                        {\n                            break;\n                        }\n                        parent = parent.Parent;\n                    }\n                }\n                return _viewDataContainer;\n            }\n        }\n\n        public ViewDataDictionary ViewData\n        {\n            get\n            {\n                IViewDataContainer vdc = ViewDataContainer;\n                return (vdc == null) ? null : vdc.ViewData;\n            }\n        }\n\n        private void EnsureAttributes()\n        {\n            if (_attributes == null)\n            {\n                _attributes = new SortedDictionary<string, string>(StringComparer.OrdinalIgnoreCase);\n            }\n        }\n\n        protected virtual string GetAttribute(string key)\n        {\n            EnsureAttributes();\n            string value;\n            _attributes.TryGetValue(key, out value);\n            return value;\n        }\n\n        protected virtual void SetAttribute(string key, string value)\n        {\n            EnsureAttributes();\n            _attributes[key] = value;\n        }\n\n        #region IAttributeAccessor Members\n\n        string IAttributeAccessor.GetAttribute(string key)\n        {\n            return GetAttribute(key);\n        }\n\n        void IAttributeAccessor.SetAttribute(string key, string value)\n        {\n            SetAttribute(key, value);\n        }\n\n        #endregion\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Controls/MvcInputControl.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Web.Mvc;\nusing System.Web.UI;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc.Controls\n{\n    public abstract class MvcInputControl : MvcControl\n    {\n        private string _format;\n        private string _name;\n\n        protected MvcInputControl(string inputType)\n        {\n            if (String.IsNullOrEmpty(inputType))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"inputType\");\n            }\n            InputType = inputType;\n        }\n\n        [DefaultValue(\"\")]\n        public string Format\n        {\n            get { return _format ?? String.Empty; }\n            set { _format = value; }\n        }\n\n        [Browsable(false)]\n        public string InputType { get; private set; }\n\n        [DefaultValue(\"\")]\n        public string Name\n        {\n            get { return _name ?? String.Empty; }\n            set { _name = value; }\n        }\n\n        private ModelState GetModelState()\n        {\n            return ViewData.ModelState[Name];\n        }\n\n        private object GetModelStateValue(Type destinationType)\n        {\n            ModelState modelState = GetModelState();\n            if (modelState != null)\n            {\n                return modelState.Value.ConvertTo(destinationType, null /* culture */);\n            }\n            return null;\n        }\n\n        protected override void Render(HtmlTextWriter writer)\n        {\n            if (!DesignMode && String.IsNullOrEmpty(Name))\n            {\n                throw new InvalidOperationException(MvcResources.CommonControls_NameRequired);\n            }\n\n            SortedDictionary<string, string> attrs = new SortedDictionary<string, string>();\n\n            foreach (KeyValuePair<string, string> attribute in Attributes)\n            {\n                attrs.Add(attribute.Key, attribute.Value);\n            }\n\n            if (!Attributes.ContainsKey(\"type\"))\n            {\n                attrs.Add(\"type\", InputType);\n            }\n            attrs.Add(\"name\", Name);\n            if (!String.IsNullOrEmpty(ID))\n            {\n                attrs.Add(\"id\", ID);\n            }\n\n            if (DesignMode)\n            {\n                // Use a dummy value in design mode\n                attrs.Add(\"value\", \"TextBox\");\n            }\n            else\n            {\n                string attemptedValue = (string)GetModelStateValue(typeof(string));\n\n                if (attemptedValue != null)\n                {\n                    // Never format the attempted value since it was already formatted in the previous request\n                    attrs.Add(\"value\", attemptedValue);\n                }\n                else\n                {\n                    // Use an explicit value attribute if it is available. Otherwise get it from ViewData.\n                    string attributeValue;\n                    Attributes.TryGetValue(\"value\", out attributeValue);\n                    object rawValue = attributeValue ?? ViewData.Eval(Name);\n                    string stringValue;\n\n                    if (String.IsNullOrEmpty(Format))\n                    {\n                        stringValue = Convert.ToString(rawValue, CultureInfo.CurrentCulture);\n                    }\n                    else\n                    {\n                        stringValue = String.Format(CultureInfo.CurrentCulture, Format, rawValue);\n                    }\n\n                    // The HtmlTextWriter will automatically encode this value\n                    attrs.Add(\"value\", stringValue);\n                }\n\n                // If there are any errors for a named field, we add the CSS attribute.\n                ModelState modelState = GetModelState();\n                if ((modelState != null) && (modelState.Errors.Count > 0))\n                {\n                    string currentValue;\n\n                    if (attrs.TryGetValue(\"class\", out currentValue))\n                    {\n                        attrs[\"class\"] = HtmlHelper.ValidationInputCssClassName + \" \" + currentValue;\n                    }\n                    else\n                    {\n                        attrs[\"class\"] = HtmlHelper.ValidationInputCssClassName;\n                    }\n                }\n            }\n\n            foreach (KeyValuePair<string, string> attribute in attrs)\n            {\n                writer.AddAttribute(attribute.Key, Convert.ToString(attribute.Value, CultureInfo.CurrentCulture));\n            }\n\n            writer.RenderBeginTag(HtmlTextWriterTag.Input);\n\n            writer.RenderEndTag();\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Controls/Password.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.Web.Mvc.Controls\n{\n    public class Password : MvcInputControl\n    {\n        public Password()\n            : base(\"password\")\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Controls/Repeater.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections;\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Mvc;\nusing System.Web.UI;\n\nnamespace Microsoft.Web.Mvc.Controls\n{\n    [ParseChildren(true)]\n    [PersistChildren(false)]\n    public class Repeater : MvcControl\n    {\n        private string _name;\n\n        [DefaultValue(null)]\n        [Browsable(false)]\n        [PersistenceMode(PersistenceMode.InnerProperty)]\n        [TemplateContainer(typeof(RepeaterItem))]\n        [TemplateInstance(TemplateInstance.Multiple)]\n        public ITemplate ItemTemplate { get; set; }\n\n        [DefaultValue(null)]\n        [Browsable(false)]\n        [PersistenceMode(PersistenceMode.InnerProperty)]\n        [TemplateContainer(typeof(RepeaterItem))]\n        [TemplateInstance(TemplateInstance.Single)]\n        public ITemplate EmptyDataTemplate { get; set; }\n\n        [DefaultValue(\"\")]\n        public string Name\n        {\n            get { return _name ?? String.Empty; }\n            set { _name = value; }\n        }\n\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"The child objects are disposed when their container is disposed\")]\n        protected override void OnPreRender(EventArgs e)\n        {\n            base.OnPreRender(e);\n\n            // Dummy control to which we parent all the data item controls\n            Control containerControl = new Control();\n\n            IEnumerable dataItems = ViewData.Eval(Name) as IEnumerable;\n            bool hasData = false;\n            if (dataItems != null)\n            {\n                int index = 0;\n                foreach (object dataItem in dataItems)\n                {\n                    hasData = true;\n                    RepeaterItem repeaterItem = new RepeaterItem(index, dataItem)\n                    {\n                        ViewData = new ViewDataDictionary(dataItem),\n                    };\n                    ItemTemplate.InstantiateIn(repeaterItem);\n                    containerControl.Controls.Add(repeaterItem);\n\n                    index++;\n                }\n            }\n\n            if (!hasData)\n            {\n                // If there was no data, instantiate the EmptyDataTemplate\n                Control emptyDataContainer = new Control();\n                EmptyDataTemplate.InstantiateIn(emptyDataContainer);\n                containerControl.Controls.Add(emptyDataContainer);\n            }\n\n            Controls.Add(containerControl);\n\n            containerControl.DataBind();\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Controls/RepeaterItem.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Mvc;\nusing System.Web.UI;\n\nnamespace Microsoft.Web.Mvc.Controls\n{\n    public class RepeaterItem : Control, IDataItemContainer, IViewDataContainer\n    {\n        private object _dataItem;\n        private int _itemIndex;\n\n        public RepeaterItem(int itemIndex, object dataItem)\n        {\n            _itemIndex = itemIndex;\n            _dataItem = dataItem;\n        }\n\n        public object DataItem\n        {\n            get { return _dataItem; }\n        }\n\n        public int DataItemIndex\n        {\n            get { return _itemIndex; }\n        }\n\n        public int DisplayIndex\n        {\n            get { return _itemIndex; }\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"This is intended to be settable for unit testing purposes.\")]\n        public ViewDataDictionary ViewData { get; set; }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Controls/RouteValues.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Web.UI;\n\nnamespace Microsoft.Web.Mvc.Controls\n{\n    public class RouteValues : IAttributeAccessor\n    {\n        private IDictionary<string, string> _attributes;\n\n        public IDictionary<string, string> Attributes\n        {\n            get\n            {\n                EnsureAttributes();\n                return _attributes;\n            }\n        }\n\n        private void EnsureAttributes()\n        {\n            if (_attributes == null)\n            {\n                _attributes = new SortedDictionary<string, string>(StringComparer.OrdinalIgnoreCase);\n            }\n        }\n\n        protected virtual string GetAttribute(string key)\n        {\n            EnsureAttributes();\n            string value;\n            _attributes.TryGetValue(key, out value);\n            return value;\n        }\n\n        protected virtual void SetAttribute(string key, string value)\n        {\n            EnsureAttributes();\n            _attributes[key] = value;\n        }\n\n        #region IAttributeAccessor Members\n\n        string IAttributeAccessor.GetAttribute(string key)\n        {\n            return GetAttribute(key);\n        }\n\n        void IAttributeAccessor.SetAttribute(string key, string value)\n        {\n            SetAttribute(key, value);\n        }\n\n        #endregion\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Controls/TextBox.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.Web.Mvc.Controls\n{\n    public class TextBox : MvcInputControl\n    {\n        public TextBox()\n            : base(\"text\")\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/CookieValueProviderFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc\n{\n    public class CookieValueProviderFactory : ValueProviderFactory\n    {\n        public override IValueProvider GetValueProvider(ControllerContext controllerContext)\n        {\n            HttpCookieCollection cookies = controllerContext.HttpContext.Request.Cookies;\n\n            Dictionary<string, string> backingStore = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);\n            for (int i = 0; i < cookies.Count; i++)\n            {\n                HttpCookie cookie = cookies[i];\n                if (!String.IsNullOrEmpty(cookie.Name))\n                {\n                    backingStore[cookie.Name] = cookie.Value;\n                }\n            }\n\n            return new DictionaryValueProvider<string>(backingStore, CultureInfo.InvariantCulture);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/CopyAsyncParametersAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Mvc;\nusing System.Web.Mvc.Async;\n\nnamespace Microsoft.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\n    public sealed class CopyAsyncParametersAttribute : ActionFilterAttribute\n    {\n        public override void OnActionExecuting(ActionExecutingContext filterContext)\n        {\n            if (filterContext == null)\n            {\n                throw new ArgumentNullException(\"filterContext\");\n            }\n\n            IAsyncManagerContainer container = filterContext.Controller as IAsyncManagerContainer;\n            if (container != null)\n            {\n                AsyncManager asyncManager = container.AsyncManager;\n                foreach (var entry in filterContext.ActionParameters)\n                {\n                    asyncManager.Parameters[entry.Key] = entry.Value;\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/CreditCardAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing System.Web.Mvc;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]\n    public sealed class CreditCardAttribute : DataTypeAttribute, IClientValidatable\n    {\n        public CreditCardAttribute()\n            : base(\"creditcard\")\n        {\n            ErrorMessage = MvcResources.CreditCardAttribute_Invalid;\n        }\n\n        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)\n        {\n            yield return new ModelClientValidationRule\n            {\n                ValidationType = \"creditcard\",\n                ErrorMessage = FormatErrorMessage(metadata.GetDisplayName())\n            };\n        }\n\n        public override bool IsValid(object value)\n        {\n            if (value == null)\n            {\n                return true;\n            }\n\n            string creditCardNumber = value as string;\n            if (creditCardNumber == null)\n            {\n                return false;\n            }\n            creditCardNumber = creditCardNumber.Replace(\"-\", String.Empty);\n\n            int checksum = 0;\n            bool evenDigit = false;\n\n            // http://www.beachnet.com/~hstiles/cardtype.html\n            foreach (char digit in creditCardNumber.Reverse())\n            {\n                if (!Char.IsDigit(digit))\n                {\n                    return false;\n                }\n\n                int digitValue = (digit - '0') * (evenDigit ? 2 : 1);\n                evenDigit = !evenDigit;\n\n                while (digitValue > 0)\n                {\n                    checksum += digitValue % 10;\n                    digitValue /= 10;\n                }\n            }\n\n            return (checksum % 10) == 0;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/CssExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Mvc;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc\n{\n    public static class CssExtensions\n    {\n        public static MvcHtmlString Css(this HtmlHelper helper, string file)\n        {\n            return Css(helper, file, null);\n        }\n\n        public static MvcHtmlString Css(this HtmlHelper helper, string file, string mediaType)\n        {\n            if (String.IsNullOrEmpty(file))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"file\");\n            }\n\n            string src;\n            if (ScriptExtensions.IsRelativeToDefaultPath(file))\n            {\n                src = \"~/Content/\" + file;\n            }\n            else\n            {\n                src = file;\n            }\n\n            TagBuilder linkTag = new TagBuilder(\"link\");\n            linkTag.MergeAttribute(\"type\", \"text/css\");\n            linkTag.MergeAttribute(\"rel\", \"stylesheet\");\n            if (mediaType != null)\n            {\n                linkTag.MergeAttribute(\"media\", mediaType);\n            }\n            linkTag.MergeAttribute(\"href\", UrlHelper.GenerateContentUrl(src, helper.ViewContext.HttpContext));\n            return MvcHtmlString.Create(linkTag.ToString(TagRenderMode.SelfClosing));\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/DeserializeAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]\n    public sealed class DeserializeAttribute : CustomModelBinderAttribute\n    {\n        public DeserializeAttribute()\n        {\n        }\n\n        internal MvcSerializer Serializer { get; set; }\n\n        public override IModelBinder GetBinder()\n        {\n            return new DeserializingModelBinder(Serializer);\n        }\n\n        private sealed class DeserializingModelBinder : IModelBinder\n        {\n            private readonly MvcSerializer _serializer;\n\n            public DeserializingModelBinder(MvcSerializer serializer)\n            {\n                _serializer = serializer ?? new MvcSerializer();\n            }\n\n            [SuppressMessage(\"Microsoft.Globalization\", \"CA1304:SpecifyCultureInfo\", MessageId = \"System.Web.Mvc.ValueProviderResult.ConvertTo(System.Type)\", Justification = \"The target object should make the correct culture determination, not this method.\")]\n            public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)\n            {\n                if (bindingContext == null)\n                {\n                    throw new ArgumentNullException(\"bindingContext\");\n                }\n\n                ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);\n                if (valueProviderResult == null)\n                {\n                    // nothing found\n                    return null;\n                }\n\n                string serializedValue = (string)valueProviderResult.ConvertTo(typeof(string));\n                return _serializer.Deserialize(serializedValue);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/DynamicReflectionObject.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Dynamic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Reflection;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc\n{\n    internal class DynamicReflectionObject : DynamicObject\n    {\n        private readonly object _realObject;\n\n        private DynamicReflectionObject(object realObject)\n        {\n            _realObject = realObject;\n        }\n\n        public override bool TryGetMember(GetMemberBinder binder, out object result)\n        {\n            PropertyInfo propInfo = _realObject.GetType().GetProperty(binder.Name);\n\n            if (propInfo == null)\n            {\n                PropertyInfo[] properties = _realObject.GetType().GetProperties();\n                if (properties.Length == 0)\n                {\n                    throw new InvalidOperationException(\n                        String.Format(CultureInfo.CurrentCulture,\n                                      MvcResources.DynamicViewPage_NoProperties,\n                                      binder.Name));\n                }\n\n                string propNames = properties.Select(p => p.Name)\n                    .OrderBy(name => name)\n                    .Aggregate((left, right) => left + \", \" + right);\n\n                throw new InvalidOperationException(\n                    String.Format(CultureInfo.CurrentCulture,\n                                  MvcResources.DynamicViewPage_PropertyDoesNotExist,\n                                  binder.Name,\n                                  propNames));\n            }\n\n            result = Wrap(propInfo.GetValue(_realObject, null));\n            return true;\n        }\n\n        public static dynamic Wrap(object obj)\n        {\n            // We really only want to wrap anonymous objects, but there's no surefire way to determine\n            // that an object is anonymous. We'll use the best metrics we can (internal non-nested type\n            // that derives directly from Object).\n            if (obj != null)\n            {\n                Type type = obj.GetType();\n                if (!type.IsPublic && type.BaseType == typeof(Object) && type.DeclaringType == null)\n                {\n                    return new DynamicReflectionObject(obj);\n                }\n            }\n\n            return obj;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/DynamicViewDataDictionary.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Dynamic;\nusing System.Web.Mvc;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc\n{\n    internal class DynamicViewDataDictionary : DynamicObject\n    {\n        private readonly ViewDataDictionary _dictionary;\n\n        private DynamicViewDataDictionary(ViewDataDictionary dictionary)\n        {\n            _dictionary = dictionary;\n        }\n\n        public object Model\n        {\n            get { return _dictionary.Model; }\n            set { _dictionary.Model = value; }\n        }\n\n        public ModelMetadata ModelMetadata\n        {\n            get { return _dictionary.ModelMetadata; }\n            set { _dictionary.ModelMetadata = value; }\n        }\n\n        public ModelStateDictionary ModelState\n        {\n            get { return _dictionary.ModelState; }\n        }\n\n        public TemplateInfo TemplateInfo\n        {\n            get { return _dictionary.TemplateInfo; }\n            set { _dictionary.TemplateInfo = value; }\n        }\n\n        private bool GetValue(string name, out object result)\n        {\n            result = DynamicReflectionObject.Wrap(_dictionary.Eval(name)) ?? String.Empty;\n            return true;\n        }\n\n        public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)\n        {\n            if (indexes.Length != 1)\n            {\n                throw new ArgumentException(MvcResources.DynamicViewDataDictionary_SingleIndexerOnly);\n            }\n\n            string name = indexes[0] as string;\n            if (name == null)\n            {\n                throw new ArgumentException(MvcResources.DynamicViewDataDictionary_StringIndexerOnly);\n            }\n\n            return GetValue(name, out result);\n        }\n\n        public override bool TryGetMember(GetMemberBinder binder, out object result)\n        {\n            return GetValue(binder.Name, out result);\n        }\n\n        public static dynamic Wrap(ViewDataDictionary dictionary)\n        {\n            return new DynamicViewDataDictionary(dictionary);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/DynamicViewPage.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc\n{\n    public class DynamicViewPage : ViewPage\n    {\n        public new dynamic Model\n        {\n            get { return DynamicReflectionObject.Wrap(base.Model); }\n        }\n\n        public new dynamic ViewData\n        {\n            get { return DynamicViewDataDictionary.Wrap(base.ViewData); }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/DynamicViewPageOfTModel.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc\n{\n    public class DynamicViewPage<TModel> : ViewPage<TModel>\n    {\n        public new dynamic ViewData\n        {\n            get { return DynamicViewDataDictionary.Wrap(base.ViewData); }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ElementalValueProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Globalization;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc\n{\n    // Represents a value provider that contains a single value.\n    internal sealed class ElementalValueProvider : IValueProvider\n    {\n        public ElementalValueProvider(string name, object rawValue, CultureInfo culture)\n        {\n            Name = name;\n            RawValue = rawValue;\n            Culture = culture;\n        }\n\n        public CultureInfo Culture { get; private set; }\n\n        public string Name { get; private set; }\n\n        public object RawValue { get; private set; }\n\n        public bool ContainsPrefix(string prefix)\n        {\n            return ValueProviderUtil.IsPrefixMatch(prefix, Name);\n        }\n\n        public ValueProviderResult GetValue(string key)\n        {\n            return (String.Equals(key, Name, StringComparison.OrdinalIgnoreCase))\n                       ? new ValueProviderResult(RawValue, Convert.ToString(RawValue, Culture), Culture)\n                       : null;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/EmailAddressAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Text.RegularExpressions;\nusing System.Web.Mvc;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]\n    public sealed class EmailAddressAttribute : DataTypeAttribute, IClientValidatable\n    {\n        private static Regex _regex = new Regex(@\"^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.?$\", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);\n\n        public EmailAddressAttribute()\n            : base(DataType.EmailAddress)\n        {\n            ErrorMessage = MvcResources.EmailAddressAttribute_Invalid;\n        }\n\n        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)\n        {\n            yield return new ModelClientValidationRule\n            {\n                ValidationType = \"email\",\n                ErrorMessage = FormatErrorMessage(metadata.GetDisplayName())\n            };\n        }\n\n        public override bool IsValid(object value)\n        {\n            if (value == null)\n            {\n                return true;\n            }\n\n            string valueAsString = value as string;\n            return valueAsString != null && _regex.Match(valueAsString).Length > 0;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Error.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc\n{\n    internal static class Error\n    {\n        public static InvalidOperationException BindingBehavior_ValueNotFound(string fieldName)\n        {\n            string errorString = String.Format(CultureInfo.CurrentCulture, MvcResources.BindingBehavior_ValueNotFound,\n                                               fieldName);\n            return new InvalidOperationException(errorString);\n        }\n\n        public static ArgumentException Common_TypeMustImplementInterface(Type providedType, Type requiredInterfaceType, string parameterName)\n        {\n            string errorString = String.Format(CultureInfo.CurrentCulture, MvcResources.Common_TypeMustImplementInterface,\n                                               providedType, requiredInterfaceType);\n            return new ArgumentException(errorString, parameterName);\n        }\n\n        public static ArgumentException GenericModelBinderProvider_ParameterMustSpecifyOpenGenericType(Type specifiedType, string parameterName)\n        {\n            string errorString = String.Format(CultureInfo.CurrentCulture, MvcResources.GenericModelBinderProvider_ParameterMustSpecifyOpenGenericType,\n                                               specifiedType);\n            return new ArgumentException(errorString, parameterName);\n        }\n\n        public static ArgumentException GenericModelBinderProvider_TypeArgumentCountMismatch(Type modelType, Type modelBinderType)\n        {\n            string errorString = String.Format(CultureInfo.CurrentCulture, MvcResources.GenericModelBinderProvider_TypeArgumentCountMismatch,\n                                               modelType, modelType.GetGenericArguments().Length, modelBinderType, modelBinderType.GetGenericArguments().Length);\n            return new ArgumentException(errorString, \"modelBinderType\");\n        }\n\n        public static InvalidOperationException ModelBinderProviderCollection_BinderForTypeNotFound(Type modelType)\n        {\n            string errorString = String.Format(CultureInfo.CurrentCulture, MvcResources.ModelBinderProviderCollection_BinderForTypeNotFound,\n                                               modelType);\n            return new InvalidOperationException(errorString);\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2208:InstantiateArgumentExceptionsCorrectly\", Justification = \"The purpose of this class is to throw errors on behalf of other methods\")]\n        public static ArgumentException ModelBinderUtil_ModelCannotBeNull(Type expectedType)\n        {\n            string errorString = String.Format(CultureInfo.CurrentCulture, MvcResources.ModelBinderUtil_ModelCannotBeNull,\n                                               expectedType);\n            return new ArgumentException(errorString, \"bindingContext\");\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2208:InstantiateArgumentExceptionsCorrectly\", Justification = \"The purpose of this class is to throw errors on behalf of other methods\")]\n        public static ArgumentException ModelBinderUtil_ModelInstanceIsWrong(Type actualType, Type expectedType)\n        {\n            string errorString = String.Format(CultureInfo.CurrentCulture, MvcResources.ModelBinderUtil_ModelInstanceIsWrong,\n                                               actualType, expectedType);\n            return new ArgumentException(errorString, \"bindingContext\");\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2208:InstantiateArgumentExceptionsCorrectly\", Justification = \"The purpose of this class is to throw errors on behalf of other methods\")]\n        public static ArgumentException ModelBinderUtil_ModelMetadataCannotBeNull()\n        {\n            return new ArgumentException(MvcResources.ModelBinderUtil_ModelMetadataCannotBeNull, \"bindingContext\");\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2208:InstantiateArgumentExceptionsCorrectly\", Justification = \"The purpose of this class is to throw errors on behalf of other methods\")]\n        public static ArgumentException ModelBinderUtil_ModelTypeIsWrong(Type actualType, Type expectedType)\n        {\n            string errorString = String.Format(CultureInfo.CurrentCulture, MvcResources.ModelBinderUtil_ModelTypeIsWrong,\n                                               actualType, expectedType);\n            return new ArgumentException(errorString, \"bindingContext\");\n        }\n\n        public static InvalidOperationException ModelBindingContext_ModelMetadataMustBeSet()\n        {\n            return new InvalidOperationException(MvcResources.ModelBindingContext_ModelMetadataMustBeSet);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ExpressionUtil/BinaryExpressionFingerprint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\nusing System.Reflection;\n\n#pragma warning disable 659 // overrides AddToHashCodeCombiner instead\n\nnamespace Microsoft.Web.Mvc.ExpressionUtil\n{\n    // BinaryExpression fingerprint class\n    // Useful for things like array[index]\n\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2218:OverrideGetHashCodeOnOverridingEquals\", Justification = \"Overrides AddToHashCodeCombiner() instead.\")]\n    internal sealed class BinaryExpressionFingerprint : ExpressionFingerprint\n    {\n        public BinaryExpressionFingerprint(ExpressionType nodeType, Type type, MethodInfo method)\n            : base(nodeType, type)\n        {\n            // Other properties on BinaryExpression (like IsLifted / IsLiftedToNull) are simply derived\n            // from Type and NodeType, so they're not necessary for inclusion in the fingerprint.\n\n            Method = method;\n        }\n\n        // http://msdn.microsoft.com/en-us/library/system.linq.expressions.binaryexpression.method.aspx\n        public MethodInfo Method { get; private set; }\n\n        public override bool Equals(object obj)\n        {\n            BinaryExpressionFingerprint other = obj as BinaryExpressionFingerprint;\n            return (other != null)\n                   && Equals(this.Method, other.Method)\n                   && this.Equals(other);\n        }\n\n        internal override void AddToHashCodeCombiner(HashCodeCombiner combiner)\n        {\n            combiner.AddObject(Method);\n            base.AddToHashCodeCombiner(combiner);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ExpressionUtil/CachedExpressionCompiler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Linq.Expressions;\nusing System.Reflection;\n\nnamespace Microsoft.Web.Mvc.ExpressionUtil\n{\n    internal static class CachedExpressionCompiler\n    {\n        // This is the entry point to the cached expression compilation system. The system\n        // will try to turn the expression into an actual delegate as quickly as possible,\n        // relying on cache lookups and other techniques to save time if appropriate.\n        // If the provided expression is particularly obscure and the system doesn't know\n        // how to handle it, we'll just compile the expression as normal.\n        public static Func<TModel, TValue> Process<TModel, TValue>(Expression<Func<TModel, TValue>> lambdaExpression)\n        {\n            return Compiler<TModel, TValue>.Compile(lambdaExpression);\n        }\n\n        private static class Compiler<TIn, TOut>\n        {\n            private static Func<TIn, TOut> _identityFunc;\n\n            private static readonly ConcurrentDictionary<MemberInfo, Func<TIn, TOut>> _simpleMemberAccessDict =\n                new ConcurrentDictionary<MemberInfo, Func<TIn, TOut>>();\n\n            private static readonly ConcurrentDictionary<MemberInfo, Func<object, TOut>> _constMemberAccessDict =\n                new ConcurrentDictionary<MemberInfo, Func<object, TOut>>();\n\n            private static readonly ConcurrentDictionary<ExpressionFingerprintChain, Hoisted<TIn, TOut>> _fingerprintedCache =\n                new ConcurrentDictionary<ExpressionFingerprintChain, Hoisted<TIn, TOut>>();\n\n            public static Func<TIn, TOut> Compile(Expression<Func<TIn, TOut>> expr)\n            {\n                return CompileFromIdentityFunc(expr)\n                       ?? CompileFromConstLookup(expr)\n                       ?? CompileFromMemberAccess(expr)\n                       ?? CompileFromFingerprint(expr)\n                       ?? CompileSlow(expr);\n            }\n\n            private static Func<TIn, TOut> CompileFromConstLookup(Expression<Func<TIn, TOut>> expr)\n            {\n                ConstantExpression constExpr = expr.Body as ConstantExpression;\n                if (constExpr != null)\n                {\n                    // model => {const}\n\n                    TOut constantValue = (TOut)constExpr.Value;\n                    return _ => constantValue;\n                }\n\n                return null;\n            }\n\n            private static Func<TIn, TOut> CompileFromIdentityFunc(Expression<Func<TIn, TOut>> expr)\n            {\n                if (expr.Body == expr.Parameters[0])\n                {\n                    // model => model\n\n                    // don't need to lock, as all identity funcs are identical\n                    if (_identityFunc == null)\n                    {\n                        _identityFunc = expr.Compile();\n                    }\n\n                    return _identityFunc;\n                }\n\n                return null;\n            }\n\n            private static Func<TIn, TOut> CompileFromFingerprint(Expression<Func<TIn, TOut>> expr)\n            {\n                List<object> capturedConstants;\n                ExpressionFingerprintChain fingerprint = FingerprintingExpressionVisitor.GetFingerprintChain(expr, out capturedConstants);\n\n                if (fingerprint != null)\n                {\n                    var del = _fingerprintedCache.GetOrAdd(fingerprint, _ =>\n                    {\n                        // Fingerprinting succeeded, but there was a cache miss. Rewrite the expression\n                        // and add the rewritten expression to the cache.\n\n                        var hoistedExpr = HoistingExpressionVisitor<TIn, TOut>.Hoist(expr);\n                        return hoistedExpr.Compile();\n                    });\n                    return model => del(model, capturedConstants);\n                }\n\n                // couldn't be fingerprinted\n                return null;\n            }\n\n            private static Func<TIn, TOut> CompileFromMemberAccess(Expression<Func<TIn, TOut>> expr)\n            {\n                // Performance tests show that on the x64 platform, special-casing static member and\n                // captured local variable accesses is faster than letting the fingerprinting system\n                // handle them. On the x86 platform, the fingerprinting system is faster, but only\n                // by around one microsecond, so it's not worth it to complicate the logic here with\n                // an architecture check.\n\n                MemberExpression memberExpr = expr.Body as MemberExpression;\n                if (memberExpr != null)\n                {\n                    if (memberExpr.Expression == expr.Parameters[0] || memberExpr.Expression == null)\n                    {\n                        // model => model.Member or model => StaticMember\n                        return _simpleMemberAccessDict.GetOrAdd(memberExpr.Member, _ => expr.Compile());\n                    }\n\n                    ConstantExpression constExpr = memberExpr.Expression as ConstantExpression;\n                    if (constExpr != null)\n                    {\n                        // model => {const}.Member (captured local variable)\n                        var del = _constMemberAccessDict.GetOrAdd(memberExpr.Member, _ =>\n                        {\n                            // rewrite as capturedLocal => ((TDeclaringType)capturedLocal).Member\n                            var constParamExpr = Expression.Parameter(typeof(object), \"capturedLocal\");\n                            var constCastExpr = Expression.Convert(constParamExpr, memberExpr.Member.DeclaringType);\n                            var newMemberAccessExpr = memberExpr.Update(constCastExpr);\n                            var newLambdaExpr = Expression.Lambda<Func<object, TOut>>(newMemberAccessExpr, constParamExpr);\n                            return newLambdaExpr.Compile();\n                        });\n\n                        object capturedLocal = constExpr.Value;\n                        return _ => del(capturedLocal);\n                    }\n                }\n\n                return null;\n            }\n\n            private static Func<TIn, TOut> CompileSlow(Expression<Func<TIn, TOut>> expr)\n            {\n                // fallback compilation system - just compile the expression directly\n                return expr.Compile();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ExpressionUtil/ConditionalExpressionFingerprint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\n\n#pragma warning disable 659 // overrides AddToHashCodeCombiner instead\n\nnamespace Microsoft.Web.Mvc.ExpressionUtil\n{\n    // ConditionalExpression fingerprint class\n    // Expression of form (test) ? ifTrue : ifFalse\n\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2218:OverrideGetHashCodeOnOverridingEquals\", Justification = \"Overrides AddToHashCodeCombiner() instead.\")]\n    internal sealed class ConditionalExpressionFingerprint : ExpressionFingerprint\n    {\n        public ConditionalExpressionFingerprint(ExpressionType nodeType, Type type)\n            : base(nodeType, type)\n        {\n            // There are no properties on ConditionalExpression that are worth including in\n            // the fingerprint.\n        }\n\n        public override bool Equals(object obj)\n        {\n            ConditionalExpressionFingerprint other = obj as ConditionalExpressionFingerprint;\n            return (other != null)\n                   && this.Equals(other);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ExpressionUtil/ConstantExpressionFingerprint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\n\n#pragma warning disable 659 // overrides AddToHashCodeCombiner instead\n\nnamespace Microsoft.Web.Mvc.ExpressionUtil\n{\n    // ConstantExpression fingerprint class\n    //\n    // A ConstantExpression might represent a captured local variable, so we can't compile\n    // the value directly into the cached function. Instead, a placeholder is generated\n    // and the value is hoisted into a local variables array. This placeholder can then\n    // be compiled and cached, and the array lookup happens at runtime.\n\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2218:OverrideGetHashCodeOnOverridingEquals\", Justification = \"Overrides AddToHashCodeCombiner() instead.\")]\n    internal sealed class ConstantExpressionFingerprint : ExpressionFingerprint\n    {\n        public ConstantExpressionFingerprint(ExpressionType nodeType, Type type)\n            : base(nodeType, type)\n        {\n            // There are no properties on ConstantExpression that are worth including in\n            // the fingerprint.\n        }\n\n        public override bool Equals(object obj)\n        {\n            ConstantExpressionFingerprint other = obj as ConstantExpressionFingerprint;\n            return (other != null)\n                   && this.Equals(other);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ExpressionUtil/DefaultExpressionFingerprint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\n\n#pragma warning disable 659 // overrides AddToHashCodeCombiner instead\n\nnamespace Microsoft.Web.Mvc.ExpressionUtil\n{\n    // DefaultExpression fingerprint class\n    // Expression of form default(T)\n\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2218:OverrideGetHashCodeOnOverridingEquals\", Justification = \"Overrides AddToHashCodeCombiner() instead.\")]\n    internal sealed class DefaultExpressionFingerprint : ExpressionFingerprint\n    {\n        public DefaultExpressionFingerprint(ExpressionType nodeType, Type type)\n            : base(nodeType, type)\n        {\n            // There are no properties on DefaultExpression that are worth including in\n            // the fingerprint.\n        }\n\n        public override bool Equals(object obj)\n        {\n            DefaultExpressionFingerprint other = obj as DefaultExpressionFingerprint;\n            return (other != null)\n                   && this.Equals(other);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ExpressionUtil/ExpressionFingerprint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Linq.Expressions;\n\nnamespace Microsoft.Web.Mvc.ExpressionUtil\n{\n    // Serves as the base class for all expression fingerprints. Provides a default implementation\n    // of GetHashCode().\n\n    internal abstract class ExpressionFingerprint\n    {\n        protected ExpressionFingerprint(ExpressionType nodeType, Type type)\n        {\n            NodeType = nodeType;\n            Type = type;\n        }\n\n        // the type of expression node, e.g. OP_ADD, MEMBER_ACCESS, etc.\n        public ExpressionType NodeType { get; private set; }\n\n        // the CLR type resulting from this expression, e.g. int, string, etc.\n        public Type Type { get; private set; }\n\n        internal virtual void AddToHashCodeCombiner(HashCodeCombiner combiner)\n        {\n            combiner.AddInt32((int)NodeType);\n            combiner.AddObject(Type);\n        }\n\n        protected bool Equals(ExpressionFingerprint other)\n        {\n            return (other != null)\n                   && (this.NodeType == other.NodeType)\n                   && Equals(this.Type, other.Type);\n        }\n\n        public override bool Equals(object obj)\n        {\n            return Equals(obj as ExpressionFingerprint);\n        }\n\n        public override int GetHashCode()\n        {\n            HashCodeCombiner combiner = new HashCodeCombiner();\n            AddToHashCodeCombiner(combiner);\n            return combiner.CombinedHash;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ExpressionUtil/ExpressionFingerprintChain.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\n\nnamespace Microsoft.Web.Mvc.ExpressionUtil\n{\n    // Expression fingerprint chain class\n    // Contains information used for generalizing, comparing, and recreating Expression instances\n    //\n    // Since Expression objects are immutable and are recreated for every invocation of an expression\n    // helper method, they can't be compared directly. Fingerprinting Expression objects allows\n    // information about them to be abstracted away, and the fingerprints can be directly compared.\n    // Consider the process of fingerprinting that all values (parameters, constants, etc.) are hoisted\n    // and replaced with dummies. What remains can be decomposed into a sequence of operations on specific\n    // types and specific inputs.\n    //\n    // Some sample fingerprints chains:\n    //\n    // 2 + 4 -> OP_ADD, CONST:int, NULL, CONST:int\n    // 2 + 8 -> OP_ADD, CONST:int, NULL, CONST:int\n    // 2.0 + 4.0 -> OP_ADD, CONST:double, NULL, CONST:double\n    //\n    // 2 + 4 and 2 + 8 have the same fingerprint, but 2.0 + 4.0 has a different fingerprint since its\n    // underlying types differ. Note that this looks a bit like prefix notation and is a side effect\n    // of how the ExpressionVisitor class recurses into expressions. (Occasionally there will be a NULL\n    // in the fingerprint chain, which depending on context can denote a static member, a null Conversion\n    // in a BinaryExpression, and so forth.)\n    //\n    // \"Hello \" + \"world\" -> OP_ADD, CONST:string, NULL, CONST:string\n    // \"Hello \" + {model} -> OP_ADD, CONST:string, NULL, PARAM_0:string\n    //\n    // These string concatenations have different fingerprints since the inputs are provided differently:\n    // one is a constant, the other is a parameter.\n    //\n    // ({model} ?? \"sample\").Length -> MEMBER_ACCESS(String.Length), OP_COALESCE, PARAM_0:string, NULL, CONST:string\n    // ({model} ?? \"other sample\").Length -> MEMBER_ACCESS(String.Length), OP_COALESCE, PARAM_0:string, NULL, CONST:string\n    //\n    // These expressions have the same fingerprint since all constants of the same underlying type are\n    // treated equally.\n    //\n    // It's also important that the fingerprints don't reference the actual Expression objects that were\n    // used to generate them, as the fingerprints will be cached, and caching a fingerprint that references\n    // an Expression will root the Expression (and any objects it references).\n\n    internal sealed class ExpressionFingerprintChain : IEquatable<ExpressionFingerprintChain>\n    {\n        public readonly List<ExpressionFingerprint> Elements = new List<ExpressionFingerprint>();\n\n        public bool Equals(ExpressionFingerprintChain other)\n        {\n            // Two chains are considered equal if two elements appearing in the same index in\n            // each chain are equal (value equality, not referential equality).\n\n            if (other == null)\n            {\n                return false;\n            }\n\n            if (this.Elements.Count != other.Elements.Count)\n            {\n                return false;\n            }\n\n            for (int i = 0; i < this.Elements.Count; i++)\n            {\n                if (!Equals(this.Elements[i], other.Elements[i]))\n                {\n                    return false;\n                }\n            }\n\n            return true;\n        }\n\n        public override bool Equals(object obj)\n        {\n            return Equals(obj as ExpressionFingerprintChain);\n        }\n\n        public override int GetHashCode()\n        {\n            HashCodeCombiner combiner = new HashCodeCombiner();\n            Elements.ForEach(combiner.AddFingerprint);\n            return combiner.CombinedHash;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ExpressionUtil/FingerprintingExpressionVisitor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq.Expressions;\n\nnamespace Microsoft.Web.Mvc.ExpressionUtil\n{\n    // This is a visitor which produces a fingerprint of an expression. It doesn't\n    // rewrite the expression in a form which can be compiled and cached.\n\n    internal sealed class FingerprintingExpressionVisitor : ExpressionVisitor\n    {\n        private readonly List<object> _seenConstants = new List<object>();\n        private readonly List<ParameterExpression> _seenParameters = new List<ParameterExpression>();\n        private readonly ExpressionFingerprintChain _currentChain = new ExpressionFingerprintChain();\n        private bool _gaveUp;\n\n        private FingerprintingExpressionVisitor()\n        {\n        }\n\n        private T GiveUp<T>(T node)\n        {\n            // We don't understand this node, so just quit.\n\n            _gaveUp = true;\n            return node;\n        }\n\n        // Returns the fingerprint chain + captured constants list for this expression, or null\n        // if the expression couldn't be fingerprinted.\n        public static ExpressionFingerprintChain GetFingerprintChain(Expression expr, out List<object> capturedConstants)\n        {\n            FingerprintingExpressionVisitor visitor = new FingerprintingExpressionVisitor();\n            visitor.Visit(expr);\n\n            if (visitor._gaveUp)\n            {\n                capturedConstants = null;\n                return null;\n            }\n            else\n            {\n                capturedConstants = visitor._seenConstants;\n                return visitor._currentChain;\n            }\n        }\n\n        public override Expression Visit(Expression node)\n        {\n            if (node == null)\n            {\n                _currentChain.Elements.Add(null);\n                return null;\n            }\n            else\n            {\n                return base.Visit(node);\n            }\n        }\n\n        protected override Expression VisitBinary(BinaryExpression node)\n        {\n            if (_gaveUp)\n            {\n                return node;\n            }\n            _currentChain.Elements.Add(new BinaryExpressionFingerprint(node.NodeType, node.Type, node.Method));\n            return base.VisitBinary(node);\n        }\n\n        protected override Expression VisitBlock(BlockExpression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override CatchBlock VisitCatchBlock(CatchBlock node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitConditional(ConditionalExpression node)\n        {\n            if (_gaveUp)\n            {\n                return node;\n            }\n            _currentChain.Elements.Add(new ConditionalExpressionFingerprint(node.NodeType, node.Type));\n            return base.VisitConditional(node);\n        }\n\n        protected override Expression VisitConstant(ConstantExpression node)\n        {\n            if (_gaveUp)\n            {\n                return node;\n            }\n\n            _seenConstants.Add(node.Value);\n            _currentChain.Elements.Add(new ConstantExpressionFingerprint(node.NodeType, node.Type));\n            return base.VisitConstant(node);\n        }\n\n        protected override Expression VisitDebugInfo(DebugInfoExpression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitDefault(DefaultExpression node)\n        {\n            if (_gaveUp)\n            {\n                return node;\n            }\n            _currentChain.Elements.Add(new DefaultExpressionFingerprint(node.NodeType, node.Type));\n            return base.VisitDefault(node);\n        }\n\n        protected override Expression VisitDynamic(DynamicExpression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override ElementInit VisitElementInit(ElementInit node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitExtension(Expression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitGoto(GotoExpression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitIndex(IndexExpression node)\n        {\n            if (_gaveUp)\n            {\n                return node;\n            }\n            _currentChain.Elements.Add(new IndexExpressionFingerprint(node.NodeType, node.Type, node.Indexer));\n            return base.VisitIndex(node);\n        }\n\n        protected override Expression VisitInvocation(InvocationExpression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitLabel(LabelExpression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override LabelTarget VisitLabelTarget(LabelTarget node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitLambda<T>(Expression<T> node)\n        {\n            if (_gaveUp)\n            {\n                return node;\n            }\n            _currentChain.Elements.Add(new LambdaExpressionFingerprint(node.NodeType, node.Type));\n            return base.VisitLambda(node);\n        }\n\n        protected override Expression VisitListInit(ListInitExpression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitLoop(LoopExpression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitMember(MemberExpression node)\n        {\n            if (_gaveUp)\n            {\n                return node;\n            }\n            _currentChain.Elements.Add(new MemberExpressionFingerprint(node.NodeType, node.Type, node.Member));\n            return base.VisitMember(node);\n        }\n\n        protected override MemberAssignment VisitMemberAssignment(MemberAssignment node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override MemberBinding VisitMemberBinding(MemberBinding node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitMemberInit(MemberInitExpression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override MemberListBinding VisitMemberListBinding(MemberListBinding node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitMethodCall(MethodCallExpression node)\n        {\n            if (_gaveUp)\n            {\n                return node;\n            }\n            _currentChain.Elements.Add(new MethodCallExpressionFingerprint(node.NodeType, node.Type, node.Method));\n            return base.VisitMethodCall(node);\n        }\n\n        protected override Expression VisitNew(NewExpression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitNewArray(NewArrayExpression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitParameter(ParameterExpression node)\n        {\n            if (_gaveUp)\n            {\n                return node;\n            }\n\n            int parameterIndex = _seenParameters.IndexOf(node);\n            if (parameterIndex < 0)\n            {\n                // first time seeing this parameter\n                parameterIndex = _seenParameters.Count;\n                _seenParameters.Add(node);\n            }\n\n            _currentChain.Elements.Add(new ParameterExpressionFingerprint(node.NodeType, node.Type, parameterIndex));\n            return base.VisitParameter(node);\n        }\n\n        protected override Expression VisitRuntimeVariables(RuntimeVariablesExpression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitSwitch(SwitchExpression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override SwitchCase VisitSwitchCase(SwitchCase node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitTry(TryExpression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitTypeBinary(TypeBinaryExpression node)\n        {\n            if (_gaveUp)\n            {\n                return node;\n            }\n            _currentChain.Elements.Add(new TypeBinaryExpressionFingerprint(node.NodeType, node.Type, node.TypeOperand));\n            return base.VisitTypeBinary(node);\n        }\n\n        protected override Expression VisitUnary(UnaryExpression node)\n        {\n            if (_gaveUp)\n            {\n                return node;\n            }\n            _currentChain.Elements.Add(new UnaryExpressionFingerprint(node.NodeType, node.Type, node.Method));\n            return base.VisitUnary(node);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ExpressionUtil/HashCodeCombiner.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\n\nnamespace Microsoft.Web.Mvc.ExpressionUtil\n{\n    // based on System.Web.Util.HashCodeCombiner\n    internal class HashCodeCombiner\n    {\n        private long _combinedHash64 = 0x1505L;\n\n        public int CombinedHash\n        {\n            get { return _combinedHash64.GetHashCode(); }\n        }\n\n        public void AddFingerprint(ExpressionFingerprint fingerprint)\n        {\n            if (fingerprint != null)\n            {\n                fingerprint.AddToHashCodeCombiner(this);\n            }\n            else\n            {\n                AddInt32(0);\n            }\n        }\n\n        public void AddEnumerable(IEnumerable e)\n        {\n            if (e == null)\n            {\n                AddInt32(0);\n            }\n            else\n            {\n                int count = 0;\n                foreach (object o in e)\n                {\n                    AddObject(o);\n                    count++;\n                }\n                AddInt32(count);\n            }\n        }\n\n        public void AddInt32(int i)\n        {\n            _combinedHash64 = ((_combinedHash64 << 5) + _combinedHash64) ^ i;\n        }\n\n        public void AddObject(object o)\n        {\n            int hashCode = (o != null) ? o.GetHashCode() : 0;\n            AddInt32(hashCode);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ExpressionUtil/Hoisted.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace Microsoft.Web.Mvc.ExpressionUtil\n{\n    internal delegate TValue Hoisted<TModel, TValue>(TModel model, List<object> capturedConstants);\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ExpressionUtil/HoistingExpressionVisitor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq.Expressions;\n\nnamespace Microsoft.Web.Mvc.ExpressionUtil\n{\n    // This is a visitor which rewrites constant expressions as parameter lookups. It's meant\n    // to produce an expression which can be cached safely.\n\n    internal sealed class HoistingExpressionVisitor<TIn, TOut> : ExpressionVisitor\n    {\n        private static readonly ParameterExpression _hoistedConstantsParamExpr = Expression.Parameter(typeof(List<object>), \"hoistedConstants\");\n        private int _numConstantsProcessed;\n\n        // factory will create instance\n        private HoistingExpressionVisitor()\n        {\n        }\n\n        public static Expression<Hoisted<TIn, TOut>> Hoist(Expression<Func<TIn, TOut>> expr)\n        {\n            // rewrite Expression<Func<TIn, TOut>> as Expression<Hoisted<TIn, TOut>>\n\n            var visitor = new HoistingExpressionVisitor<TIn, TOut>();\n            var rewrittenBodyExpr = visitor.Visit(expr.Body);\n            var rewrittenLambdaExpr = Expression.Lambda<Hoisted<TIn, TOut>>(rewrittenBodyExpr, expr.Parameters[0], _hoistedConstantsParamExpr);\n            return rewrittenLambdaExpr;\n        }\n\n        protected override Expression VisitConstant(ConstantExpression node)\n        {\n            // rewrite the constant expression as (TConst)hoistedConstants[i];\n            return Expression.Convert(Expression.Property(_hoistedConstantsParamExpr, \"Item\", Expression.Constant(_numConstantsProcessed++)), node.Type);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ExpressionUtil/IndexExpressionFingerprint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\nusing System.Reflection;\n\n#pragma warning disable 659 // overrides AddToHashCodeCombiner instead\n\nnamespace Microsoft.Web.Mvc.ExpressionUtil\n{\n    // IndexExpression fingerprint class\n    // Represents certain forms of array access or indexer property access\n\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2218:OverrideGetHashCodeOnOverridingEquals\", Justification = \"Overrides AddToHashCodeCombiner() instead.\")]\n    internal sealed class IndexExpressionFingerprint : ExpressionFingerprint\n    {\n        public IndexExpressionFingerprint(ExpressionType nodeType, Type type, PropertyInfo indexer)\n            : base(nodeType, type)\n        {\n            // Other properties on IndexExpression (like the argument count) are simply derived\n            // from Type and Indexer, so they're not necessary for inclusion in the fingerprint.\n\n            Indexer = indexer;\n        }\n\n        // http://msdn.microsoft.com/en-us/library/system.linq.expressions.indexexpression.indexer.aspx\n        public PropertyInfo Indexer { get; private set; }\n\n        public override bool Equals(object obj)\n        {\n            IndexExpressionFingerprint other = obj as IndexExpressionFingerprint;\n            return (other != null)\n                   && Equals(this.Indexer, other.Indexer)\n                   && this.Equals(other);\n        }\n\n        internal override void AddToHashCodeCombiner(HashCodeCombiner combiner)\n        {\n            combiner.AddObject(Indexer);\n            base.AddToHashCodeCombiner(combiner);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ExpressionUtil/LambdaExpressionFingerprint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\n\n#pragma warning disable 659 // overrides AddToHashCodeCombiner instead\n\nnamespace Microsoft.Web.Mvc.ExpressionUtil\n{\n    // LambdaExpression fingerprint class\n    // Represents a lambda expression (root element in Expression<T>)\n\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2218:OverrideGetHashCodeOnOverridingEquals\", Justification = \"Overrides AddToHashCodeCombiner() instead.\")]\n    internal sealed class LambdaExpressionFingerprint : ExpressionFingerprint\n    {\n        public LambdaExpressionFingerprint(ExpressionType nodeType, Type type)\n            : base(nodeType, type)\n        {\n            // There are no properties on LambdaExpression that are worth including in\n            // the fingerprint.\n        }\n\n        public override bool Equals(object obj)\n        {\n            LambdaExpressionFingerprint other = obj as LambdaExpressionFingerprint;\n            return (other != null)\n                   && this.Equals(other);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ExpressionUtil/MemberExpressionFingerprint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\nusing System.Reflection;\n\n#pragma warning disable 659 // overrides AddToHashCodeCombiner instead\n\nnamespace Microsoft.Web.Mvc.ExpressionUtil\n{\n    // MemberExpression fingerprint class\n    // Expression of form xxx.FieldOrProperty\n\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2218:OverrideGetHashCodeOnOverridingEquals\", Justification = \"Overrides AddToHashCodeCombiner() instead.\")]\n    internal sealed class MemberExpressionFingerprint : ExpressionFingerprint\n    {\n        public MemberExpressionFingerprint(ExpressionType nodeType, Type type, MemberInfo member)\n            : base(nodeType, type)\n        {\n            Member = member;\n        }\n\n        // http://msdn.microsoft.com/en-us/library/system.linq.expressions.memberexpression.member.aspx\n        public MemberInfo Member { get; private set; }\n\n        public override bool Equals(object obj)\n        {\n            MemberExpressionFingerprint other = obj as MemberExpressionFingerprint;\n            return (other != null)\n                   && Equals(this.Member, other.Member)\n                   && this.Equals(other);\n        }\n\n        internal override void AddToHashCodeCombiner(HashCodeCombiner combiner)\n        {\n            combiner.AddObject(Member);\n            base.AddToHashCodeCombiner(combiner);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ExpressionUtil/MethodCallExpressionFingerprint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\nusing System.Reflection;\n\n#pragma warning disable 659 // overrides AddToHashCodeCombiner instead\n\nnamespace Microsoft.Web.Mvc.ExpressionUtil\n{\n    // MethodCallExpression fingerprint class\n    // Expression of form xxx.Foo(...), xxx[...] (get_Item()), etc.\n\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2218:OverrideGetHashCodeOnOverridingEquals\", Justification = \"Overrides AddToHashCodeCombiner() instead.\")]\n    internal sealed class MethodCallExpressionFingerprint : ExpressionFingerprint\n    {\n        public MethodCallExpressionFingerprint(ExpressionType nodeType, Type type, MethodInfo method)\n            : base(nodeType, type)\n        {\n            // Other properties on MethodCallExpression (like the argument count) are simply derived\n            // from Type and Indexer, so they're not necessary for inclusion in the fingerprint.\n\n            Method = method;\n        }\n\n        // http://msdn.microsoft.com/en-us/library/system.linq.expressions.methodcallexpression.method.aspx\n        public MethodInfo Method { get; private set; }\n\n        public override bool Equals(object obj)\n        {\n            MethodCallExpressionFingerprint other = obj as MethodCallExpressionFingerprint;\n            return (other != null)\n                   && Equals(this.Method, other.Method)\n                   && this.Equals(other);\n        }\n\n        internal override void AddToHashCodeCombiner(HashCodeCombiner combiner)\n        {\n            combiner.AddObject(Method);\n            base.AddToHashCodeCombiner(combiner);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ExpressionUtil/ParameterExpressionFingerprint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\n\n#pragma warning disable 659 // overrides AddToHashCodeCombiner instead\n\nnamespace Microsoft.Web.Mvc.ExpressionUtil\n{\n    // ParameterExpression fingerprint class\n    // Can represent the model parameter or an inner parameter in an open lambda expression\n\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2218:OverrideGetHashCodeOnOverridingEquals\", Justification = \"Overrides AddToHashCodeCombiner() instead.\")]\n    internal sealed class ParameterExpressionFingerprint : ExpressionFingerprint\n    {\n        public ParameterExpressionFingerprint(ExpressionType nodeType, Type type, int parameterIndex)\n            : base(nodeType, type)\n        {\n            ParameterIndex = parameterIndex;\n        }\n\n        // Parameter position within the overall expression, used to maintain alpha equivalence.\n        public int ParameterIndex { get; private set; }\n\n        public override bool Equals(object obj)\n        {\n            ParameterExpressionFingerprint other = obj as ParameterExpressionFingerprint;\n            return (other != null)\n                   && (this.ParameterIndex == other.ParameterIndex)\n                   && this.Equals(other);\n        }\n\n        internal override void AddToHashCodeCombiner(HashCodeCombiner combiner)\n        {\n            combiner.AddInt32(ParameterIndex);\n            base.AddToHashCodeCombiner(combiner);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ExpressionUtil/TypeBinaryExpressionFingerprint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\n\n#pragma warning disable 659 // overrides AddToHashCodeCombiner instead\n\nnamespace Microsoft.Web.Mvc.ExpressionUtil\n{\n    // TypeBinary fingerprint class\n    // Expression of form \"obj is T\"\n\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2218:OverrideGetHashCodeOnOverridingEquals\", Justification = \"Overrides AddToHashCodeCombiner() instead.\")]\n    internal sealed class TypeBinaryExpressionFingerprint : ExpressionFingerprint\n    {\n        public TypeBinaryExpressionFingerprint(ExpressionType nodeType, Type type, Type typeOperand)\n            : base(nodeType, type)\n        {\n            TypeOperand = typeOperand;\n        }\n\n        // http://msdn.microsoft.com/en-us/library/system.linq.expressions.typebinaryexpression.typeoperand.aspx\n        public Type TypeOperand { get; private set; }\n\n        public override bool Equals(object obj)\n        {\n            TypeBinaryExpressionFingerprint other = obj as TypeBinaryExpressionFingerprint;\n            return (other != null)\n                   && Equals(this.TypeOperand, other.TypeOperand)\n                   && this.Equals(other);\n        }\n\n        internal override void AddToHashCodeCombiner(HashCodeCombiner combiner)\n        {\n            combiner.AddObject(TypeOperand);\n            base.AddToHashCodeCombiner(combiner);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ExpressionUtil/UnaryExpressionFingerprint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\nusing System.Reflection;\n\n#pragma warning disable 659 // overrides AddToHashCodeCombiner instead\n\nnamespace Microsoft.Web.Mvc.ExpressionUtil\n{\n    // UnaryExpression fingerprint class\n    // The most common appearance of a UnaryExpression is a cast or other conversion operator\n\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2218:OverrideGetHashCodeOnOverridingEquals\", Justification = \"Overrides AddToHashCodeCombiner() instead.\")]\n    internal sealed class UnaryExpressionFingerprint : ExpressionFingerprint\n    {\n        public UnaryExpressionFingerprint(ExpressionType nodeType, Type type, MethodInfo method)\n            : base(nodeType, type)\n        {\n            // Other properties on UnaryExpression (like IsLifted / IsLiftedToNull) are simply derived\n            // from Type and NodeType, so they're not necessary for inclusion in the fingerprint.\n\n            Method = method;\n        }\n\n        // http://msdn.microsoft.com/en-us/library/system.linq.expressions.unaryexpression.method.aspx\n        public MethodInfo Method { get; private set; }\n\n        public override bool Equals(object obj)\n        {\n            UnaryExpressionFingerprint other = obj as UnaryExpressionFingerprint;\n            return (other != null)\n                   && Equals(this.Method, other.Method)\n                   && this.Equals(other);\n        }\n\n        internal override void AddToHashCodeCombiner(HashCodeCombiner combiner)\n        {\n            combiner.AddObject(Method);\n            base.AddToHashCodeCombiner(combiner);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/FileExtensionsAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Web;\nusing System.Web.Mvc;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]\n    public sealed class FileExtensionsAttribute : DataTypeAttribute, IClientValidatable\n    {\n        private string _extensions;\n\n        public FileExtensionsAttribute()\n            : base(\"upload\")\n        {\n            ErrorMessage = MvcResources.FileExtensionsAttribute_Invalid;\n        }\n\n        public string Extensions\n        {\n            get { return String.IsNullOrWhiteSpace(_extensions) ? \"png,jpg,jpeg,gif\" : _extensions; }\n            set { _extensions = value; }\n        }\n\n        private string ExtensionsFormatted\n        {\n            get { return ExtensionsParsed.Aggregate((left, right) => left + \", \" + right); }\n        }\n\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1308:NormalizeStringsToUppercase\", Justification = \"These strings are normalized to lowercase because they are presented to the user in lowercase format\")]\n        private string ExtensionsNormalized\n        {\n            get { return Extensions.Replace(\" \", String.Empty).Replace(\".\", String.Empty).ToLowerInvariant(); }\n        }\n\n        private IEnumerable<string> ExtensionsParsed\n        {\n            get { return ExtensionsNormalized.Split(',').Select(e => \".\" + e); }\n        }\n\n        public override string FormatErrorMessage(string name)\n        {\n            return String.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, ExtensionsFormatted);\n        }\n\n        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)\n        {\n            var rule = new ModelClientValidationRule\n            {\n                ValidationType = \"extension\",\n                ErrorMessage = FormatErrorMessage(metadata.GetDisplayName())\n            };\n            rule.ValidationParameters[\"extension\"] = ExtensionsNormalized;\n            yield return rule;\n        }\n\n        public override bool IsValid(object value)\n        {\n            if (value == null)\n            {\n                return true;\n            }\n\n            HttpPostedFileBase valueAsFileBase = value as HttpPostedFileBase;\n            if (valueAsFileBase != null)\n            {\n                return ValidateExtension(valueAsFileBase.FileName);\n            }\n\n            string valueAsString = value as string;\n            if (valueAsString != null)\n            {\n                return ValidateExtension(valueAsString);\n            }\n\n            return false;\n        }\n\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1308:NormalizeStringsToUppercase\", Justification = \"These strings are normalized to lowercase because they are presented to the user in lowercase format\")]\n        private bool ValidateExtension(string fileName)\n        {\n            try\n            {\n                return ExtensionsParsed.Contains(Path.GetExtension(fileName).ToLowerInvariant());\n            }\n            catch (ArgumentException)\n            {\n                return false;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/FormExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\nusing System.Web.Mvc;\nusing System.Web.Mvc.Html;\n\nnamespace Microsoft.Web.Mvc\n{\n    public static class FormExtensions\n    {\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcForm BeginForm<TController>(this HtmlHelper helper, Expression<Action<TController>> action) where TController : Controller\n        {\n            return BeginForm(helper, action, FormMethod.Post, null);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcForm BeginForm<TController>(this HtmlHelper helper, Expression<Action<TController>> action, FormMethod method) where TController : Controller\n        {\n            return BeginForm(helper, action, method, null);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcForm BeginForm<TController>(this HtmlHelper helper, Expression<Action<TController>> action, FormMethod method, object htmlAttributes) where TController : Controller\n        {\n            return BeginForm(helper, action, method, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcForm BeginForm<TController>(this HtmlHelper helper, Expression<Action<TController>> action, FormMethod method, IDictionary<string, object> htmlAttributes) where TController : Controller\n        {\n            TagBuilder tagBuilder = new TagBuilder(\"form\");\n            tagBuilder.MergeAttributes(htmlAttributes);\n            string formAction = helper.BuildUrlFromExpression(action);\n            tagBuilder.MergeAttribute(\"action\", formAction);\n            tagBuilder.MergeAttribute(\"method\", HtmlHelper.GetFormMethodString(method));\n\n            helper.ViewContext.Writer.Write(tagBuilder.ToString(TagRenderMode.StartTag));\n            return new MvcForm(helper.ViewContext);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/FuturesFiles/DefaultTemplates/DisplayTemplates/Boolean.ascx",
    "content": "﻿<%@ Control Language=\"C#\" Inherits=\"System.Web.Mvc.ViewUserControl\" %>\n<script runat=\"server\">\n    private bool? Value {\n        get {\n            if (ViewData.Model == null) {\n                return null;\n            }\n            return Convert.ToBoolean(ViewData.Model, System.Globalization.CultureInfo.InvariantCulture);\n        }\n    }\n</script>\n<% if (ViewData.ModelMetadata.IsNullableValueType) { %>\n    <select class=\"list-box tri-state\" disabled=\"disabled\">\n        <option value=\"\" <%= Value.HasValue ? \"\" : \"selected='selected'\" %>>Not Set</option>\n        <option value=\"true\" <%= Value.HasValue && Value.Value ? \"selected='selected'\" : \"\" %>>True</option>\n        <option value=\"false\" <%= Value.HasValue && !Value.Value ? \"selected='selected'\" : \"\" %>>False</option>\n    </select>\n<% } else { %>\n    <input type=\"checkbox\" class=\"check-box\" disabled=\"disabled\" <%= Value.HasValue && Value.Value ? \"checked='checked'\" : \"\" %> />\n<% } %>"
  },
  {
    "path": "src/Microsoft.Web.Mvc/FuturesFiles/DefaultTemplates/DisplayTemplates/Collection.ascx",
    "content": "﻿<%@ Control Language=\"C#\" Inherits=\"System.Web.Mvc.ViewUserControl\" %>\n<%\n    if (Model != null) {\n        string oldPrefix = ViewData.TemplateInfo.HtmlFieldPrefix;\n        int index = 0;\n\n        ViewData.TemplateInfo.HtmlFieldPrefix = String.Empty;\n        \n        foreach (object item in (IEnumerable)Model) {\n            string fieldName = String.Format(System.Globalization.CultureInfo.InvariantCulture, \"{0}[{1}]\", oldPrefix, index++);\n            ViewContext.Writer.Write(Html.DisplayFor(m => item, null, fieldName));\n        }\n        \n        ViewData.TemplateInfo.HtmlFieldPrefix = oldPrefix;\n    }\n%>"
  },
  {
    "path": "src/Microsoft.Web.Mvc/FuturesFiles/DefaultTemplates/DisplayTemplates/Decimal.ascx",
    "content": "﻿<%@ Control Language=\"C#\" Inherits=\"System.Web.Mvc.ViewUserControl\" %>\n<script runat=\"server\">\n    private object FormattedValue {\n        get {\n            if (ViewData.TemplateInfo.FormattedModelValue == ViewData.ModelMetadata.Model) {\n                return String.Format(System.Globalization.CultureInfo.CurrentCulture, \"{0:0.00}\", ViewData.ModelMetadata.Model);\n            }\n            return ViewData.TemplateInfo.FormattedModelValue;\n        }\n    }\n</script>\n<%= Html.Encode(FormattedValue) %>"
  },
  {
    "path": "src/Microsoft.Web.Mvc/FuturesFiles/DefaultTemplates/DisplayTemplates/EmailAddress.ascx",
    "content": "﻿<%@ Control Language=\"C#\" Inherits=\"System.Web.Mvc.ViewUserControl\" %>\n<a href=\"mailto:<%= Html.AttributeEncode(Model) %>\"><%= Html.Encode(ViewData.TemplateInfo.FormattedModelValue) %></a>"
  },
  {
    "path": "src/Microsoft.Web.Mvc/FuturesFiles/DefaultTemplates/DisplayTemplates/HiddenInput.ascx",
    "content": "﻿<%@ Control Language=\"C#\" Inherits=\"System.Web.Mvc.ViewUserControl\" %>\n<% if (!ViewData.ModelMetadata.HideSurroundingHtml) { %>\n    <%= Html.Encode(ViewData.TemplateInfo.FormattedModelValue) %>\n<% } %>"
  },
  {
    "path": "src/Microsoft.Web.Mvc/FuturesFiles/DefaultTemplates/DisplayTemplates/Html.ascx",
    "content": "﻿<%@ Control Language=\"C#\" Inherits=\"System.Web.Mvc.ViewUserControl\" %>\n<%= ViewData.TemplateInfo.FormattedModelValue %>"
  },
  {
    "path": "src/Microsoft.Web.Mvc/FuturesFiles/DefaultTemplates/DisplayTemplates/Object.ascx",
    "content": "﻿<%@ Control Language=\"C#\" Inherits=\"System.Web.Mvc.ViewUserControl\" %>\n<script runat=\"server\">\n    bool ShouldShow(ModelMetadata metadata) {\n        return metadata.ShowForDisplay\n            && metadata.ModelType != typeof(System.Data.EntityState)\n            && !metadata.IsComplexType\n            && !ViewData.TemplateInfo.Visited(metadata);\n    }\n</script>\n<% if (Model == null) { %>\n    <%= ViewData.ModelMetadata.NullDisplayText %>\n<% } else if (ViewData.TemplateInfo.TemplateDepth > 1) { %>\n    <%= ViewData.ModelMetadata.SimpleDisplayText %>\n<% } else { %>\n    <% foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => ShouldShow(pm))) { %>\n        <% if (prop.HideSurroundingHtml) { %>\n            <%= Html.Display(prop.PropertyName) %>\n        <% } else { %>\n            <% if (!String.IsNullOrEmpty(prop.GetDisplayName())) { %>\n                <div class=\"display-label\"><%= prop.GetDisplayName() %></div>\n            <% } %>\n            <div class=\"display-field\"><%= Html.Display(prop.PropertyName) %></div>\n        <% } %>\n    <% } %>\n<% } %>"
  },
  {
    "path": "src/Microsoft.Web.Mvc/FuturesFiles/DefaultTemplates/DisplayTemplates/String.ascx",
    "content": "﻿<%@ Control Language=\"C#\" Inherits=\"System.Web.Mvc.ViewUserControl\" %>\n<%= Html.Encode(ViewData.TemplateInfo.FormattedModelValue) %>"
  },
  {
    "path": "src/Microsoft.Web.Mvc/FuturesFiles/DefaultTemplates/DisplayTemplates/Url.ascx",
    "content": "﻿<%@ Control Language=\"C#\" Inherits=\"System.Web.Mvc.ViewUserControl\" %>\n<a href=\"<%= Html.AttributeEncode(Model) %>\"><%= Html.Encode(ViewData.TemplateInfo.FormattedModelValue) %></a>"
  },
  {
    "path": "src/Microsoft.Web.Mvc/FuturesFiles/DefaultTemplates/EditorTemplates/Boolean.ascx",
    "content": "﻿<%@ Control Language=\"C#\" Inherits=\"System.Web.Mvc.ViewUserControl\" %>\n<script runat=\"server\">\n    private List<SelectListItem> TriStateValues {\n        get {\n            return new List<SelectListItem> {\n                new SelectListItem { Text = \"Not Set\", Value = String.Empty, Selected = !Value.HasValue },\n                new SelectListItem { Text = \"True\", Value = \"true\", Selected = Value.HasValue && Value.Value },\n                new SelectListItem { Text = \"False\", Value = \"false\", Selected = Value.HasValue && !Value.Value },\n            };\n        }\n    }\n    private bool? Value {\n        get {\n            if (ViewData.Model == null) {\n                return null;\n            }\n            return Convert.ToBoolean(ViewData.Model, System.Globalization.CultureInfo.InvariantCulture);\n        }\n    }\n</script>\n<% if (ViewData.ModelMetadata.IsNullableValueType) { %>\n    <%= Html.DropDownList(\"\", TriStateValues, new { @class = \"list-box tri-state\" }) %>\n<% } else { %>\n    <%= Html.CheckBox(\"\", Value ?? false, new { @class = \"check-box\" }) %>\n<% } %>"
  },
  {
    "path": "src/Microsoft.Web.Mvc/FuturesFiles/DefaultTemplates/EditorTemplates/Collection.ascx",
    "content": "﻿<%@ Control Language=\"C#\" Inherits=\"System.Web.Mvc.ViewUserControl\" %>\n<%\n    if (Model != null) {\n        string oldPrefix = ViewData.TemplateInfo.HtmlFieldPrefix;\n        int index = 0;\n\n        ViewData.TemplateInfo.HtmlFieldPrefix = String.Empty;\n        \n        foreach (object item in (IEnumerable)Model) {\n            string fieldName = String.Format(System.Globalization.CultureInfo.InvariantCulture, \"{0}[{1}]\", oldPrefix, index++);\n            ViewContext.Writer.Write(Html.EditorFor(m => item, null, fieldName));\n        }\n        \n        ViewData.TemplateInfo.HtmlFieldPrefix = oldPrefix;\n    }\n%>"
  },
  {
    "path": "src/Microsoft.Web.Mvc/FuturesFiles/DefaultTemplates/EditorTemplates/Decimal.ascx",
    "content": "﻿<%@ Control Language=\"C#\" Inherits=\"System.Web.Mvc.ViewUserControl\" %>\n<script runat=\"server\">\n    private object FormattedValue {\n        get {\n            if (ViewData.TemplateInfo.FormattedModelValue == ViewData.ModelMetadata.Model) {\n                return String.Format(System.Globalization.CultureInfo.CurrentCulture, \"{0:0.00}\", ViewData.ModelMetadata.Model);\n            }\n            return ViewData.TemplateInfo.FormattedModelValue;\n        }\n    }\n</script>\n<%= Html.TextBox(\"\", FormattedValue, new { @class = \"text-box single-line\" }) %>"
  },
  {
    "path": "src/Microsoft.Web.Mvc/FuturesFiles/DefaultTemplates/EditorTemplates/HiddenInput.ascx",
    "content": "﻿<%@ Control Language=\"C#\" Inherits=\"System.Web.Mvc.ViewUserControl\" %>\n<script runat=\"server\">\n    private object ModelValue {\n        get {\n            if (Model is System.Data.Linq.Binary) {\n                return Convert.ToBase64String(((System.Data.Linq.Binary)Model).ToArray());\n            }\n            if (Model is byte[]) {\n                return Convert.ToBase64String((byte[])Model);\n            }\n            return Model;\n        }\n    }\n</script>\n<% if (!ViewData.ModelMetadata.HideSurroundingHtml) { %>\n    <%= Html.Encode(ViewData.TemplateInfo.FormattedModelValue) %>\n<% } %>\n<%= Html.Hidden(\"\", ModelValue) %>"
  },
  {
    "path": "src/Microsoft.Web.Mvc/FuturesFiles/DefaultTemplates/EditorTemplates/MultilineText.ascx",
    "content": "﻿<%@ Control Language=\"C#\" Inherits=\"System.Web.Mvc.ViewUserControl\" %>\n<%= Html.TextArea(\"\", ViewData.TemplateInfo.FormattedModelValue.ToString(), 0, 0, new { @class = \"text-box multi-line\" }) %>"
  },
  {
    "path": "src/Microsoft.Web.Mvc/FuturesFiles/DefaultTemplates/EditorTemplates/Object.ascx",
    "content": "﻿<%@ Control Language=\"C#\" Inherits=\"System.Web.Mvc.ViewUserControl\" %>\n<script runat=\"server\">\n    bool ShouldShow(ModelMetadata metadata) {\n        return metadata.ShowForEdit\n            && metadata.ModelType != typeof(System.Data.EntityState)\n            && !metadata.IsComplexType\n            && !ViewData.TemplateInfo.Visited(metadata);\n    }\n</script>\n<% if (ViewData.TemplateInfo.TemplateDepth > 1) { %>\n    <% if (Model == null) { %>\n        <%= ViewData.ModelMetadata.NullDisplayText %>\n    <% } else { %>\n        <%= ViewData.ModelMetadata.SimpleDisplayText %>\n    <% } %>\n<% } else { %>    \n    <% foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => ShouldShow(pm))) { %>\n        <% if (prop.HideSurroundingHtml) { %>\n            <%= Html.Editor(prop.PropertyName) %>\n        <% } else { %>\n            <% if (!String.IsNullOrEmpty(Html.Label(prop.PropertyName).ToHtmlString())) { %>\n                <div class=\"editor-label\"><%= Html.Label(prop.PropertyName) %></div>\n            <% } %>\n            <div class=\"editor-field\"><%= Html.Editor(prop.PropertyName) %> <%= Html.ValidationMessage(prop.PropertyName, \"*\") %></div>\n        <% } %>\n    <% } %>\n<% } %>"
  },
  {
    "path": "src/Microsoft.Web.Mvc/FuturesFiles/DefaultTemplates/EditorTemplates/Password.ascx",
    "content": "﻿<%@ Control Language=\"C#\" Inherits=\"System.Web.Mvc.ViewUserControl\" %>\n<%= Html.Password(\"\", ViewData.TemplateInfo.FormattedModelValue, new { @class = \"text-box single-line password\" })%>"
  },
  {
    "path": "src/Microsoft.Web.Mvc/FuturesFiles/DefaultTemplates/EditorTemplates/String.ascx",
    "content": "﻿<%@ Control Language=\"C#\" Inherits=\"System.Web.Mvc.ViewUserControl\" %>\n<%= Html.TextBox(\"\", ViewData.TemplateInfo.FormattedModelValue, new { @class = \"text-box single-line\" }) %>"
  },
  {
    "path": "src/Microsoft.Web.Mvc/FuturesFiles/iismap.vbs",
    "content": "Const HKEY_LOCAL_MACHINE = &H80000002\nConst MACHINE_NAME = \"localhost\"\nConst DEFAULT_PATH = \"W3SVC\"\nConst SCRIPT_MAPS = \"ScriptMaps\"\n\nFunction ExtensionExists(extension, fxVersion)\n    Dim scriptExtension\n    iisScriptMaps = GetScriptMaps()\n    \n    For scriptIndex = 0 To UBound(iisScriptMaps)\n        scriptMap = iisScriptMaps(scriptIndex)\n        decomposedScriptMap = Split(scriptMap, \",\")\n        scriptExtension = Right(decomposedScriptMap(0), Len(decomposedScriptMap(0))-1)\n        If StrComp(LCase(scriptExtension), LCase(extension)) = 0 Then\n          If InStr(scriptMap, fxVersion) > 0 Then\n              ExtensionExists = true\n            End If\n        End If\n    Next\n    \n    ExtensionExists = false\nEnd Function\n\nFunction GetFrameworkPath(fxVersion)\n    strComputer = \".\"\n    Set registryObj = GetObject(\"winmgmts:{impersonationLevel=impersonate}!\\\\\" & strComputer & \"\\root\\default:StdRegProv\")\n \n    strKeyPath = \"SOFTWARE\\Microsoft\\.NETFramework\"\n    strValueName = \"InstallRoot\"\n    registryObj.GetStringValue HKEY_LOCAL_MACHINE, strKeyPath, strValueName, strValue\n\n    GetFrameworkPath = strValue & fxVersion\nEnd Function\n\nFunction GetFrameworkVersions()\n    strComputer = \".\"\n    Set registryObj = GetObject(\"winmgmts:{impersonationLevel=impersonate}!\\\\\" & strComputer & \"\\root\\default:StdRegProv\")\n    strKeyPath = \"SOFTWARE\\Microsoft\\.NETFramework\"\n    registryObj.EnumKey HKEY_LOCAL_MACHINE, strKeyPath, arrSubKeys\n    Set regex = New RegExp\n    regex.Pattern = \"^(v(2|4)\\.\\d+\\.\\d+(\\.\\d+)?)$\"\n    regex.Global = True\n    ReDim fxVersions(0)\n\n    For Each key in arrSubKeys\n        If regex.Test(key) Then\n            ReDim Preserve fxVersions(UBound(fxVersions)+1)\n            fxVersions(UBound(fxVersions)-1) = key\n        End If\n    Next\n   \n    If UBound(fxVersions) > 0 Then\n        Redim Preserve fxVersions(UBound(fxVersions)-1)\n    End If\n  \n    GetFrameworkVersions = fxVersions\nEnd Function\n\nFunction IsValidFrameworkVersion(fxVersion)\n    strComputer = \".\"\n    Set registryObj = GetObject(\"winmgmts:{impersonationLevel=impersonate}!\\\\\" & strComputer & \"\\root\\default:StdRegProv\")\n    strKeyPath = \"SOFTWARE\\Microsoft\\.NETFramework\\\" & fxVersion\n    registryObj.EnumKey HKEY_LOCAL_MACHINE, strKeyPath, arrSubKeys\n    \n    IsValidFrameworkVersion = Not IsNull(arrSubKeys)\nEnd Function\n\nFunction GetScriptMaps()\n    Dim iisObject\n    Set iisObject = GetObject(\"IIS://\" & MACHINE_NAME & \"/\" & DEFAULT_PATH)   \n    GetScriptMaps = iisObject.Get(SCRIPT_MAPS)\nEnd Function\n\nSub RegisterExtension(extension, fxVersion)\n    Dim iisScriptMaps\n\n    Set iisObject = GetObject(\"IIS://\" & MACHINE_NAME & \"/\" & DEFAULT_PATH)\n    iisScriptMaps = GetScriptMaps()\n    \n    If ExtensionExists(extension, fxVersion) Then\n        WScript.Echo extension & \" is already registered for .NET Framework \" & fxVersion & \".\"\n        WScript.Quit\n    End If\n    \n    ReDim Preserve iisScriptMaps(UBound(iisScriptMaps)+1)\n    \n    iisScriptMaps(UBound(iisScriptMaps)) = \".\" & extension & \",\" & GetFrameworkPath(fxVersion) & \"\\aspnet_isapi.dll,1,GET,HEAD,POST\"\n    iisObject.Put \"ScriptMaps\", iisScriptMaps\n    iisObject.Setinfo\nEnd Sub\n\nSub SetScriptMaps(ScriptMaps)\n    Dim iisObject\n    \n    Set iisObject = GetObject(\"ISS://\" & MACHINE_NAME & \"/\" & DEFAULT_PATH)\n    \n    iisObject.Put SCRIPT_MAPS, ScriptMaps\n    iisObject.Setinfo\nEnd Sub\n\nSub UnregisterExtension(extension, fxVersion)\n    Dim newScriptMaps\n    \n    Set iisObject = GetObject(\"IIS://\" & MACHINE_NAME & \"/\" & DEFAULT_PATH)\n    iisScriptMaps = GetScriptMaps()\n    \n    If Not ExtensionExists(extension, fxVersion) Then\n        WScript.Echo extension & \" is not registered for .NET Framework \" & fxVersion & \".\"\n        WScript.Quit\n    End If\n\n    ReDim newScriptMaps(UBound(iisScriptMaps)-1)\n    Dim newScriptIndex\n    newScriptIndex = 0\n\n    For scriptIndex = 0 To UBound(iisScriptMaps)\n        scriptMap = iisScriptMaps(scriptIndex)\n        decomposedScriptMap = Split(scriptMap, \",\")\n        scriptExtension = Right(decomposedScriptMap(0), Len(decomposedScriptMap(0))-1)\n        If (StrComp(LCase(scriptExtension), LCase(extension)) <> 0) Or ((StrComp(LCase(scriptExtension), LCase(extension)) = 0) And (InStr(scriptMap, fxVersion) = 0)) Then\n            newScriptMaps(newScriptIndex) = scriptMap\n            newScriptIndex = newScriptIndex + 1\n        End If\n    Next\n    \n    iisObject.Put \"ScriptMaps\", newScriptMaps\n    iisObject.Setinfo\nEnd Sub"
  },
  {
    "path": "src/Microsoft.Web.Mvc/FuturesFiles/registermvc.wsf",
    "content": "<job>\n    <script language=\"VBScript\" src=\"iismap.vbs\">\n        If WScript.Arguments.Count = 0 Then\n            msg = \"You need to specify a .NET Framework version. Please use one of the following:\" & VbCrLf\n            For Each fxVersion in GetFrameworkVersions()\n                msg = msg & fxVersion & VbCrLf\n            Next\n            WScript.Echo msg\n            WScript.Quit\n        ElseIf Not IsValidFrameworkVersion(WScript.Arguments(0)) Then\n            msg = WScript.Arguments(0) & \" is not a valid .NET Framework version. Please use one of the following:\" & VbCrLf\n            For Each fxVersion in GetFrameworkVersions()\n                msg = msg & fxVersion & VbCrLf\n            Next\n            WScript.Echo msg\n            WScript.Quit\n        End If\n        RegisterExtension \"mvc\", WScript.Arguments(0)\n    </script>\n</job>"
  },
  {
    "path": "src/Microsoft.Web.Mvc/FuturesFiles/unregistermvc.wsf",
    "content": "<job>\n    <script language=\"VBScript\" src=\"iismap.vbs\">\n        If WScript.Arguments.Count = 0 Then\n            msg = \"You need to specify a .NET Framework version. Please use one of the following: \" & VbCrLf\n            For Each fxVersion in GetFrameworkVersions()\n                msg = msg & fxVersion & VbCrLf\n            Next\n            WScript.Echo msg\n            WScript.Quit\n        ElseIf Not IsValidFrameworkVersion(WScript.Arguments(0)) Then\n            msg = WScript.Arguments(0) & \" is not a valid .NET Framework version. Please use one of the following: \" & VbCrLf\n            For Each fxVersion in GetFrameworkVersions()\n                msg = msg & fxVersion & VbCrLf\n            Next\n            WScript.Echo msg\n            WScript.Quit\n        End If\n        UnregisterExtension \"mvc\", WScript.Arguments(0)\n    </script>\n</job>"
  },
  {
    "path": "src/Microsoft.Web.Mvc/GlobalSuppressions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\n// This file is used by Code Analysis to maintain SuppressMessage \n// attributes that are applied to this project. \n// Project-level suppressions either have no target or are given \n// a specific target and scoped to a namespace, type, member, etc. \n//\n// To add a suppression to this file, right-click the message in the \n// Error List, point to \"Suppress Message(s)\", and click \n// \"In Project Suppression File\". \n// You do not need to add suppressions to this file manually. \n\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"Microsoft.Web.Mvc.Html\", Justification = \"Helpers reside within a separate namespace to support alternate helper classes.\")]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1703:ResourceStringsShouldBeSpelledCorrectly\", MessageId = \"whitelist\", Scope = \"resource\", Target = \"Microsoft.Web.Mvc.Properties.MvcResources.resources\", Justification = \"The spelling is correct.\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA2210:AssembliesShouldHaveValidStrongNames\", Justification = \"Assembly is delay-signed.\")]\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Html/HtmlHelperExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\nusing System.Web.Mvc;\nusing System.Web.Mvc.Html;\nusing System.Web.Routing;\n\nnamespace Microsoft.Web.Mvc.Html\n{\n    // This class contains definitions of single \"super\" HTML helper methods, which rely on\n    // CLR 4's default values for method parameters to make them more consumable. Methods\n    // which previously took an HTML attributes object/dictionary now have their legal\n    // attribute values all available as optional parameters. Some attributes are only\n    // applicable for some DTDs; deprecated attributes (like \"align\" on input) were\n    // specifically excluded.\n    //\n    // Since htmlAttributes was very often the last parameter to HTML helper methods,\n    // converting to these new syntaxes should be as simple as converting your anonymous\n    // object htmlAttributes collections into optional parameters.\n    //\n    // Where there were two overloads for route values (anonymous object and dictionary),\n    // there is only a single overload now, which takes type object. If what you pass is\n    // a dictionary of the correct type, then we'll use that; otherwise, we'll assume it's\n    // an anonymous object and create the dictionary for you. This should make it simple\n    // to port methods using route values, as they should just continue to work as before.\n    //\n    // Some HTML helpers did not take HTML attributes parameters. They are recreated here\n    // so that the user does not have to import both System.Web.Mvc.Html as well as this\n    // namespace, since the purpose of these methods is to get rid of all the overloads\n    // for the built-in HTML helpers.\n    //\n    // The legal attribute values were derived from: http://www.w3schools.com/tags/\n\n    public static class HtmlHelperExtensions\n    {\n        // ChildActionExtensions\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcHtmlString Action(this HtmlHelper htmlHelper, string actionName, string controllerName = null, object routeValues = null)\n        {\n            return ChildActionExtensions.Action(\n                htmlHelper,\n                actionName,\n                controllerName,\n                routeValues as IDictionary<string, object> ?? new RouteValueDictionary(routeValues));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static void RenderAction(this HtmlHelper htmlHelper, string actionName, string controllerName = null, object routeValues = null)\n        {\n            ChildActionExtensions.RenderAction(\n                htmlHelper,\n                actionName,\n                controllerName,\n                routeValues as IDictionary<string, object> ?? new RouteValueDictionary(routeValues));\n        }\n\n        // DisplayExtensions\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcHtmlString Display(this HtmlHelper htmlHelper, string expression, string templateName = null, string htmlFieldName = null)\n        {\n            return DisplayExtensions.Display(htmlHelper, expression, templateName, htmlFieldName);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcHtmlString DisplayFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, string templateName = null, string htmlFieldName = null)\n        {\n            return DisplayExtensions.DisplayFor(htmlHelper, expression, templateName, htmlFieldName);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcHtmlString DisplayForModel(this HtmlHelper htmlHelper, string templateName = null, string htmlFieldName = null)\n        {\n            return DisplayExtensions.DisplayForModel(htmlHelper, templateName, htmlFieldName);\n        }\n\n        // DisplayTextExtensions\n\n        public static MvcHtmlString DisplayText(this HtmlHelper htmlHelper, string name)\n        {\n            return DisplayTextExtensions.DisplayText(htmlHelper, name);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString DisplayTextFor<TModel, TResult>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TResult>> expression)\n        {\n            return DisplayTextExtensions.DisplayTextFor(htmlHelper, expression);\n        }\n\n        // EditorExtensions\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcHtmlString Editor(this HtmlHelper htmlHelper, string expression, string templateName = null, string htmlFieldName = null)\n        {\n            return EditorExtensions.Editor(htmlHelper, expression, templateName, htmlFieldName);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcHtmlString EditorFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, string templateName = null, string htmlFieldName = null)\n        {\n            return EditorExtensions.EditorFor(htmlHelper, expression, templateName, htmlFieldName);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcHtmlString EditorForModel(this HtmlHelper htmlHelper, string templateName = null, string htmlFieldName = null)\n        {\n            return EditorExtensions.EditorForModel(htmlHelper, templateName, htmlFieldName);\n        }\n\n        // FormExtensions\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName = null, string controllerName = null, object routeValues = null, FormMethod method = FormMethod.Post, string accept = null, string acceptCharset = null, string cssClass = null, string dir = null, string encType = null, string id = null, string lang = null, string name = null, string style = null, string title = null)\n        {\n            return htmlHelper.BeginForm(\n                actionName,\n                controllerName,\n                routeValues as RouteValueDictionary ?? new RouteValueDictionary(routeValues),\n                method,\n                FormAttributes(accept, acceptCharset, cssClass, dir, encType, id, lang, name, style, title));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcForm BeginRouteForm(this HtmlHelper htmlHelper, string routeName, RouteValueDictionary routeValues = null, FormMethod method = FormMethod.Post, string accept = null, string acceptCharset = null, string cssClass = null, string dir = null, string encType = null, string id = null, string lang = null, string name = null, string style = null, string title = null)\n        {\n            return htmlHelper.BeginRouteForm(\n                routeName,\n                routeValues ?? new RouteValueDictionary(routeValues),\n                method,\n                FormAttributes(accept, acceptCharset, cssClass, dir, encType, id, lang, name, style, title));\n        }\n\n        public static void EndForm(this HtmlHelper htmlHelper)\n        {\n            System.Web.Mvc.Html.FormExtensions.EndForm(htmlHelper);\n        }\n\n        // InputExtensions\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcHtmlString CheckBox(this HtmlHelper htmlHelper, string name, bool? isChecked = null, string cssClass = null, string dir = null, bool disabled = false, string id = null, string lang = null, int? maxLength = null, bool readOnly = false, int? size = null, string style = null, int? tabIndex = null, string title = null)\n        {\n            var htmlAttributes = InputAttributes(cssClass, dir, disabled, id, lang, maxLength, readOnly, size, style, tabIndex, title);\n\n            return isChecked.HasValue\n                       ? htmlHelper.CheckBox(name, isChecked.Value, htmlAttributes)\n                       : htmlHelper.CheckBox(name, htmlAttributes);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcHtmlString CheckBoxFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool>> expression, string cssClass = null, string dir = null, bool disabled = false, string id = null, string lang = null, int? maxLength = null, bool readOnly = false, int? size = null, string style = null, int? tabIndex = null, string title = null)\n        {\n            return htmlHelper.CheckBoxFor(\n                expression,\n                InputAttributes(cssClass, dir, disabled, id, lang, maxLength, readOnly, size, style, tabIndex, title));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcHtmlString Hidden(this HtmlHelper htmlHelper, string name, object value = null, string cssClass = null, string id = null, string style = null)\n        {\n            return htmlHelper.Hidden(name, value, Attributes(cssClass, id, style));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcHtmlString HiddenFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string cssClass = null, string id = null, string style = null)\n        {\n            return htmlHelper.HiddenFor(expression, Attributes(cssClass, id, style));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcHtmlString Password(this HtmlHelper htmlHelper, string name, object value = null, string cssClass = null, string dir = null, bool disabled = false, string id = null, string lang = null, int? maxLength = null, bool readOnly = false, int? size = null, string style = null, int? tabIndex = null, string title = null)\n        {\n            return htmlHelper.Password(\n                name,\n                value,\n                InputAttributes(cssClass, dir, disabled, id, lang, maxLength, readOnly, size, style, tabIndex, title));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcHtmlString PasswordFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string cssClass = null, bool disabled = false, string dir = null, string id = null, string lang = null, int? maxLength = null, bool readOnly = false, int? size = null, string style = null, int? tabIndex = null, string title = null)\n        {\n            return htmlHelper.PasswordFor(\n                expression,\n                InputAttributes(cssClass, dir, disabled, id, lang, maxLength, readOnly, size, style, tabIndex, title));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcHtmlString RadioButton(this HtmlHelper htmlHelper, string name, object value, bool? isChecked = null, string cssClass = null, string dir = null, bool disabled = false, string id = null, string lang = null, int? maxLength = null, bool readOnly = false, int? size = null, string style = null, int? tabIndex = null, string title = null)\n        {\n            var htmlAttributes = InputAttributes(cssClass, dir, disabled, id, lang, maxLength, readOnly, size, style, tabIndex, title);\n\n            return isChecked.HasValue\n                       ? htmlHelper.RadioButton(name, value, isChecked.Value, htmlAttributes)\n                       : htmlHelper.RadioButton(name, value, htmlAttributes);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcHtmlString RadioButtonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, string cssClass = null, string dir = null, bool disabled = false, string id = null, string lang = null, int? maxLength = null, bool readOnly = false, int? size = null, string style = null, int? tabIndex = null, string title = null)\n        {\n            return htmlHelper.RadioButtonFor(\n                expression,\n                value,\n                InputAttributes(cssClass, dir, disabled, id, lang, maxLength, readOnly, size, style, tabIndex, title));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcHtmlString TextBox(this HtmlHelper htmlHelper, string name, object value = null, string cssClass = null, string dir = null, bool disabled = false, string id = null, string lang = null, int? maxLength = null, bool readOnly = false, int? size = null, string style = null, int? tabIndex = null, string title = null)\n        {\n            return htmlHelper.TextBox(\n                name,\n                value,\n                InputAttributes(cssClass, dir, disabled, id, lang, maxLength, readOnly, size, style, tabIndex, title));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string cssClass = null, string dir = null, bool disabled = false, string id = null, string lang = null, int? maxLength = null, bool readOnly = false, int? size = null, string style = null, int? tabIndex = null, string title = null)\n        {\n            return htmlHelper.TextBoxFor(\n                expression,\n                InputAttributes(cssClass, dir, disabled, id, lang, maxLength, readOnly, size, style, tabIndex, title));\n        }\n\n        // LabelExtensions\n\n        public static MvcHtmlString Label(this HtmlHelper htmlHelper, string expression)\n        {\n            return LabelExtensions.Label(htmlHelper, expression);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression)\n        {\n            return LabelExtensions.LabelFor(htmlHelper, expression);\n        }\n\n        public static MvcHtmlString LabelForModel(this HtmlHelper htmlHelper)\n        {\n            return LabelExtensions.LabelForModel(htmlHelper);\n        }\n\n        // LinkExtensions\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName = null, string protocol = null, string hostName = null, string fragment = null, object routeValues = null, string accessKey = null, string charset = null, string coords = null, string cssClass = null, string dir = null, string hrefLang = null, string id = null, string lang = null, string name = null, string rel = null, string rev = null, string shape = null, string style = null, string target = null, string title = null)\n        {\n            return htmlHelper.ActionLink(\n                linkText,\n                actionName,\n                controllerName,\n                protocol,\n                hostName,\n                fragment,\n                routeValues as RouteValueDictionary ?? new RouteValueDictionary(routeValues),\n                AnchorAttributes(accessKey, charset, coords, cssClass, dir, hrefLang, id, lang, name, rel, rev, shape, style, target, title));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcHtmlString RouteLink(this HtmlHelper htmlHelper, string linkText, string routeName, string protocol = null, string hostName = null, string fragment = null, object routeValues = null, string accessKey = null, string charset = null, string coords = null, string cssClass = null, string dir = null, string hrefLang = null, string id = null, string lang = null, string name = null, string rel = null, string rev = null, string shape = null, string style = null, string target = null, string title = null)\n        {\n            return htmlHelper.RouteLink(\n                linkText,\n                routeName,\n                protocol,\n                hostName,\n                fragment,\n                routeValues as RouteValueDictionary ?? new RouteValueDictionary(routeValues),\n                AnchorAttributes(accessKey, charset, coords, cssClass, dir, hrefLang, id, lang, name, rel, rev, shape, style, target, title));\n        }\n\n        // PartialExtensions\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName, object model = null, ViewDataDictionary viewData = null)\n        {\n            return PartialExtensions.Partial(\n                htmlHelper,\n                partialViewName,\n                model,\n                viewData ?? htmlHelper.ViewData);\n        }\n\n        // RenderPartialExtensions\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName, object model = null, ViewDataDictionary viewData = null)\n        {\n            RenderPartialExtensions.RenderPartial(\n                htmlHelper,\n                partialViewName,\n                model,\n                viewData ?? htmlHelper.ViewData);\n        }\n\n        // SelectExtensions\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList = null, string optionLabel = null, string cssClass = null, string dir = null, bool disabled = false, string id = null, string lang = null, int? size = null, string style = null, int? tabIndex = null, string title = null)\n        {\n            return htmlHelper.DropDownList(\n                name,\n                selectList,\n                optionLabel,\n                SelectAttributes(cssClass, dir, disabled, id, lang, size, style, tabIndex, title));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList = null, string optionLabel = null, string cssClass = null, string dir = null, bool disabled = false, string id = null, string lang = null, int? size = null, string style = null, int? tabIndex = null, string title = null)\n        {\n            return htmlHelper.DropDownListFor(\n                expression,\n                selectList,\n                optionLabel,\n                SelectAttributes(cssClass, dir, disabled, id, lang, size, style, tabIndex, title));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcHtmlString ListBox(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList = null, string cssClass = null, string dir = null, bool disabled = false, string id = null, string lang = null, int? size = null, string style = null, int? tabIndex = null, string title = null)\n        {\n            return htmlHelper.ListBox(\n                name,\n                selectList,\n                SelectAttributes(cssClass, dir, disabled, id, lang, size, style, tabIndex, title));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcHtmlString ListBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList = null, string cssClass = null, string dir = null, bool disabled = false, string id = null, string lang = null, int? size = null, string style = null, int? tabIndex = null, string title = null)\n        {\n            return htmlHelper.ListBoxFor(\n                expression,\n                selectList,\n                SelectAttributes(cssClass, dir, disabled, id, lang, size, style, tabIndex, title));\n        }\n\n        // TextAreaExtensions\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcHtmlString TextArea(this HtmlHelper htmlHelper, string name, string value = null, string accessKey = null, string cssClass = null, int? cols = null, string dir = null, bool disabled = false, string id = null, string lang = null, bool readOnly = false, int? rows = null, string style = null, int? tabIndex = null, string title = null)\n        {\n            return htmlHelper.TextArea(\n                name,\n                value,\n                TextAreaAttributes(accessKey, cssClass, cols, dir, disabled, id, lang, readOnly, rows, style, tabIndex, title));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcHtmlString TextAreaFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string accessKey = null, string cssClass = null, int? cols = null, string dir = null, bool disabled = false, string id = null, string lang = null, bool readOnly = false, int? rows = null, string style = null, int? tabIndex = null, string title = null)\n        {\n            return htmlHelper.TextAreaFor(\n                expression,\n                TextAreaAttributes(accessKey, cssClass, cols, dir, disabled, id, lang, readOnly, rows, style, tabIndex, title));\n        }\n\n        // ValidationExtensions\n\n        public static void Validate(this HtmlHelper htmlHelper, string modelName)\n        {\n            ValidationExtensions.Validate(htmlHelper, modelName);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static void ValidateFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)\n        {\n            ValidationExtensions.ValidateFor(htmlHelper, expression);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1719:ParameterNamesShouldNotMatchMemberNames\", MessageId = \"2#\", Justification = \"This API has already shipped.\")]\n        public static MvcHtmlString ValidationMessage(this HtmlHelper htmlHelper, string modelName, string validationMessage = null, string cssClass = null, string dir = null, string id = null, string lang = null, string style = null, string title = null)\n        {\n            return htmlHelper.ValidationMessage(\n                modelName,\n                validationMessage,\n                SpanAttributes(cssClass, dir, id, lang, style, title));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcHtmlString ValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string validationMessage = null, string cssClass = null, string dir = null, string id = null, string lang = null, string style = null, string title = null)\n        {\n            return htmlHelper.ValidationMessageFor(\n                expression,\n                validationMessage,\n                SpanAttributes(cssClass, dir, id, lang, style, title));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"The purpose of these helpers is to use default parameters to simplify common usage.\")]\n        public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, string message = null, bool excludePropertyErrors = false, string cssClass = null, string dir = null, string id = null, string lang = null, string style = null, string title = null)\n        {\n            return htmlHelper.ValidationSummary(\n                excludePropertyErrors,\n                message,\n                SpanAttributes(cssClass, dir, id, lang, style, title));\n        }\n\n        // Helper methods\n\n        private static void AddOptional(this IDictionary<string, object> dictionary, string key, bool value)\n        {\n            if (value)\n            {\n                dictionary[key] = key;\n            }\n        }\n\n        private static void AddOptional(this IDictionary<string, object> dictionary, string key, object value)\n        {\n            if (value != null)\n            {\n                dictionary[key] = value;\n            }\n        }\n\n        private static IDictionary<string, object> Attributes(string cssClass, string id, string style)\n        {\n            var htmlAttributes = new RouteValueDictionary();\n\n            htmlAttributes.AddOptional(\"class\", cssClass);\n            htmlAttributes.AddOptional(\"id\", id);\n            htmlAttributes.AddOptional(\"style\", style);\n\n            return htmlAttributes;\n        }\n\n        private static IDictionary<string, object> AnchorAttributes(string accessKey, string charset, string coords, string cssClass, string dir, string hrefLang, string id, string lang, string name, string rel, string rev, string shape, string style, string target, string title)\n        {\n            var htmlAttributes = Attributes(cssClass, id, style);\n\n            htmlAttributes.AddOptional(\"accesskey\", accessKey);\n            htmlAttributes.AddOptional(\"charset\", charset);\n            htmlAttributes.AddOptional(\"coords\", coords);\n            htmlAttributes.AddOptional(\"dir\", dir);\n            htmlAttributes.AddOptional(\"hreflang\", hrefLang);\n            htmlAttributes.AddOptional(\"lang\", lang);\n            htmlAttributes.AddOptional(\"name\", name);\n            htmlAttributes.AddOptional(\"rel\", rel);\n            htmlAttributes.AddOptional(\"rev\", rev);\n            htmlAttributes.AddOptional(\"shape\", shape);\n            htmlAttributes.AddOptional(\"target\", target);\n            htmlAttributes.AddOptional(\"title\", title);\n\n            return htmlAttributes;\n        }\n\n        private static IDictionary<string, object> FormAttributes(string accept, string acceptCharset, string cssClass, string dir, string encType, string id, string lang, string name, string style, string title)\n        {\n            var htmlAttributes = Attributes(cssClass, id, style);\n\n            htmlAttributes.AddOptional(\"accept\", accept);\n            htmlAttributes.AddOptional(\"accept-charset\", acceptCharset);\n            htmlAttributes.AddOptional(\"dir\", dir);\n            htmlAttributes.AddOptional(\"enctype\", encType);\n            htmlAttributes.AddOptional(\"lang\", lang);\n            htmlAttributes.AddOptional(\"name\", name);\n            htmlAttributes.AddOptional(\"title\", title);\n\n            return htmlAttributes;\n        }\n\n        private static IDictionary<string, object> InputAttributes(string cssClass, string dir, bool disabled, string id, string lang, int? maxLength, bool readOnly, int? size, string style, int? tabIndex, string title)\n        {\n            var htmlAttributes = Attributes(cssClass, id, style);\n\n            htmlAttributes.AddOptional(\"dir\", dir);\n            htmlAttributes.AddOptional(\"disabled\", disabled);\n            htmlAttributes.AddOptional(\"lang\", lang);\n            htmlAttributes.AddOptional(\"maxlength\", maxLength);\n            htmlAttributes.AddOptional(\"readonly\", readOnly);\n            htmlAttributes.AddOptional(\"size\", size);\n            htmlAttributes.AddOptional(\"tabindex\", tabIndex);\n            htmlAttributes.AddOptional(\"title\", title);\n\n            return htmlAttributes;\n        }\n\n        private static IDictionary<string, object> SelectAttributes(string cssClass, string dir, bool disabled, string id, string lang, int? size, string style, int? tabIndex, string title)\n        {\n            var htmlAttributes = Attributes(cssClass, id, style);\n\n            htmlAttributes.AddOptional(\"dir\", dir);\n            htmlAttributes.AddOptional(\"disabled\", disabled);\n            htmlAttributes.AddOptional(\"lang\", lang);\n            htmlAttributes.AddOptional(\"size\", size);\n            htmlAttributes.AddOptional(\"tabindex\", tabIndex);\n            htmlAttributes.AddOptional(\"title\", title);\n\n            return htmlAttributes;\n        }\n\n        private static IDictionary<string, object> SpanAttributes(string cssClass, string dir, string id, string lang, string style, string title)\n        {\n            var htmlAttributes = Attributes(cssClass, id, style);\n\n            htmlAttributes.AddOptional(\"dir\", dir);\n            htmlAttributes.AddOptional(\"lang\", lang);\n            htmlAttributes.AddOptional(\"title\", title);\n\n            return htmlAttributes;\n        }\n\n        private static IDictionary<string, object> TextAreaAttributes(string accessKey, string cssClass, int? cols, string dir, bool disabled, string id, string lang, bool readOnly, int? rows, string style, int? tabIndex, string title)\n        {\n            var htmlAttributes = Attributes(cssClass, id, style);\n\n            htmlAttributes.AddOptional(\"accesskey\", accessKey);\n            htmlAttributes.AddOptional(\"cols\", cols);\n            htmlAttributes.AddOptional(\"dir\", dir);\n            htmlAttributes.AddOptional(\"disabled\", disabled);\n            htmlAttributes.AddOptional(\"lang\", lang);\n            htmlAttributes.AddOptional(\"readonly\", readOnly);\n            htmlAttributes.AddOptional(\"rows\", rows);\n            htmlAttributes.AddOptional(\"style\", style);\n            htmlAttributes.AddOptional(\"tabindex\", tabIndex);\n            htmlAttributes.AddOptional(\"title\", title);\n\n            return htmlAttributes;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/HtmlButtonType.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.Web.Mvc\n{\n    public enum HtmlButtonType\n    {\n        Button,\n        Submit,\n        Reset,\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/IMachineKey.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Security;\n\nnamespace Microsoft.Web.Mvc\n{\n    // Used for mocking out the static MachineKey type\n\n    internal interface IMachineKey\n    {\n        byte[] Unprotect(string protectedData, params string[] purposes);\n        string Protect(byte[] userData, params string[] purposes);\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ImageExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Mvc;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc\n{\n    public static class ImageExtensions\n    {\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"The return value is not a regular URL since it may contain ~/ ASP.NET-specific characters\")]\n        public static MvcHtmlString Image(this HtmlHelper helper, string imageRelativeUrl)\n        {\n            return Image(helper, imageRelativeUrl, null, null);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"Required for Extension Method\")]\n        public static MvcHtmlString Image(this HtmlHelper helper, string imageRelativeUrl, string alt)\n        {\n            return Image(helper, imageRelativeUrl, alt, null);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"The return value is not a regular URL since it may contain ~/ ASP.NET-specific characters\")]\n        public static MvcHtmlString Image(this HtmlHelper helper, string imageRelativeUrl, string alt, object htmlAttributes)\n        {\n            return Image(helper, imageRelativeUrl, alt, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"The return value is not a regular URL since it may contain ~/ ASP.NET-specific characters\")]\n        public static MvcHtmlString Image(this HtmlHelper helper, string imageRelativeUrl, object htmlAttributes)\n        {\n            return Image(helper, imageRelativeUrl, null, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"The return value is not a regular URL since it may contain ~/ ASP.NET-specific characters\")]\n        public static MvcHtmlString Image(this HtmlHelper helper, string imageRelativeUrl, IDictionary<string, object> htmlAttributes)\n        {\n            return Image(helper, imageRelativeUrl, null, htmlAttributes);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"The return value is not a regular URL since it may contain ~/ ASP.NET-specific characters\")]\n        public static MvcHtmlString Image(this HtmlHelper helper, string imageRelativeUrl, string alt, IDictionary<string, object> htmlAttributes)\n        {\n            if (String.IsNullOrEmpty(imageRelativeUrl))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"imageRelativeUrl\");\n            }\n\n            string imageUrl = UrlHelper.GenerateContentUrl(imageRelativeUrl, helper.ViewContext.HttpContext);\n            return MvcHtmlString.Create(Image(imageUrl, alt, htmlAttributes).ToString(TagRenderMode.SelfClosing));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"0#\", Justification = \"The value is a not a regular URL since it may contain ~/ ASP.NET-specific characters\")]\n        public static TagBuilder Image(string imageUrl, string alt, IDictionary<string, object> htmlAttributes)\n        {\n            if (String.IsNullOrEmpty(imageUrl))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"imageUrl\");\n            }\n\n            TagBuilder imageTag = new TagBuilder(\"img\");\n\n            if (!String.IsNullOrEmpty(imageUrl))\n            {\n                imageTag.MergeAttribute(\"src\", imageUrl);\n            }\n\n            if (!String.IsNullOrEmpty(alt))\n            {\n                imageTag.MergeAttribute(\"alt\", alt);\n            }\n\n            imageTag.MergeAttributes(htmlAttributes, true);\n\n            if (imageTag.Attributes.ContainsKey(\"alt\") && !imageTag.Attributes.ContainsKey(\"title\"))\n            {\n                imageTag.MergeAttribute(\"title\", (imageTag.Attributes[\"alt\"] ?? String.Empty));\n            }\n            return imageTag;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Internal/ExpressionHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq;\nusing System.Linq.Expressions;\nusing System.Reflection;\nusing System.Web.Mvc;\nusing System.Web.Routing;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc.Internal\n{\n    public static class ExpressionHelper\n    {\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1011:ConsiderPassingBaseTypesAsParameters\", Justification = \"Users cannot use anonymous methods with the LambdaExpression type\")]\n        public static RouteValueDictionary GetRouteValuesFromExpression<TController>(Expression<Action<TController>> action) where TController : Controller\n        {\n            if (action == null)\n            {\n                throw new ArgumentNullException(\"action\");\n            }\n\n            MethodCallExpression call = action.Body as MethodCallExpression;\n            if (call == null)\n            {\n                throw new ArgumentException(MvcResources.ExpressionHelper_MustBeMethodCall, \"action\");\n            }\n\n            string controllerName = typeof(TController).Name;\n            if (!controllerName.EndsWith(\"Controller\", StringComparison.OrdinalIgnoreCase))\n            {\n                throw new ArgumentException(MvcResources.ExpressionHelper_TargetMustEndInController, \"action\");\n            }\n            controllerName = controllerName.Substring(0, controllerName.Length - \"Controller\".Length);\n            if (controllerName.Length == 0)\n            {\n                throw new ArgumentException(MvcResources.ExpressionHelper_CannotRouteToController, \"action\");\n            }\n\n            // TODO: How do we know that this method is even web callable?\n            //      For now, we just let the call itself throw an exception.\n\n            string actionName = GetTargetActionName(call.Method);\n\n            var rvd = new RouteValueDictionary();\n            rvd.Add(\"Controller\", controllerName);\n            rvd.Add(\"Action\", actionName);\n\n            ActionLinkAreaAttribute areaAttr = typeof(TController).GetCustomAttributes(typeof(ActionLinkAreaAttribute), true /* inherit */).FirstOrDefault() as ActionLinkAreaAttribute;\n            if (areaAttr != null)\n            {\n                string areaName = areaAttr.Area;\n                rvd.Add(\"Area\", areaName);\n            }\n\n            AddParameterValuesFromExpressionToDictionary(rvd, call);\n            return rvd;\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1011:ConsiderPassingBaseTypesAsParameters\", Justification = \"Users cannot use anonymous methods with the LambdaExpression type\")]\n        public static string GetInputName<TModel, TProperty>(Expression<Func<TModel, TProperty>> expression)\n        {\n            if (expression.Body.NodeType == ExpressionType.Call)\n            {\n                MethodCallExpression methodCallExpression = (MethodCallExpression)expression.Body;\n                string name = GetInputName(methodCallExpression);\n                return name.Substring(expression.Parameters[0].Name.Length + 1);\n            }\n            return expression.Body.ToString().Substring(expression.Parameters[0].Name.Length + 1);\n        }\n\n        private static string GetInputName(MethodCallExpression expression)\n        {\n            // p => p.Foo.Bar().Baz.ToString() => p.Foo OR throw...\n\n            MethodCallExpression methodCallExpression = expression.Object as MethodCallExpression;\n            if (methodCallExpression != null)\n            {\n                return GetInputName(methodCallExpression);\n            }\n            return expression.Object.ToString();\n        }\n\n        // This method contains some heuristics that will help determine the correct action name from a given MethodInfo\n        // assuming the default sync / async invokers are in use. The logic's not foolproof, but it should be good enough\n        // for most uses.\n        private static string GetTargetActionName(MethodInfo methodInfo)\n        {\n            string methodName = methodInfo.Name;\n\n            // do we know this not to be an action?\n            if (methodInfo.IsDefined(typeof(NonActionAttribute), true /* inherit */))\n            {\n                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,\n                                                                  MvcResources.ExpressionHelper_CannotCallNonAction, methodName));\n            }\n\n            // has this been renamed?\n            ActionNameAttribute nameAttr = methodInfo.GetCustomAttributes(typeof(ActionNameAttribute), true /* inherit */).OfType<ActionNameAttribute>().FirstOrDefault();\n            if (nameAttr != null)\n            {\n                return nameAttr.Name;\n            }\n\n            // targeting an async action?\n            if (methodInfo.DeclaringType.IsSubclassOf(typeof(AsyncController)))\n            {\n                if (methodName.EndsWith(\"Async\", StringComparison.OrdinalIgnoreCase))\n                {\n                    return methodName.Substring(0, methodName.Length - \"Async\".Length);\n                }\n                if (methodName.EndsWith(\"Completed\", StringComparison.OrdinalIgnoreCase))\n                {\n                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,\n                                                                      MvcResources.ExpressionHelper_CannotCallCompletedMethod, methodName));\n                }\n            }\n\n            // fallback\n            return methodName;\n        }\n\n        private static void AddParameterValuesFromExpressionToDictionary(RouteValueDictionary rvd, MethodCallExpression call)\n        {\n            ParameterInfo[] parameters = call.Method.GetParameters();\n\n            if (parameters.Length > 0)\n            {\n                for (int i = 0; i < parameters.Length; i++)\n                {\n                    Expression arg = call.Arguments[i];\n                    object value = null;\n                    ConstantExpression ce = arg as ConstantExpression;\n                    if (ce != null)\n                    {\n                        // If argument is a constant expression, just get the value\n                        value = ce.Value;\n                    }\n                    else\n                    {\n                        value = CachedExpressionCompiler.Evaluate(arg);\n                    }\n                    rvd.Add(parameters[i].Name, value);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/LinkBuilder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\nusing System.Reflection;\nusing System.Web.Mvc;\nusing System.Web.Routing;\nusing ExpressionHelper = Microsoft.Web.Mvc.Internal.ExpressionHelper;\n\nnamespace Microsoft.Web.Mvc\n{\n    public static class LinkBuilder\n    {\n        /// <summary>\n        /// Builds a URL based on the Expression passed in\n        /// </summary>\n        /// <typeparam name=\"TController\">Controller Type Only</typeparam>\n        /// <param name=\"context\">The current ViewContext</param>\n        /// <param name=\"routeCollection\">The <see cref=\"RouteCollection\"/> to use for building the URL.</param>\n        /// <param name=\"action\">The action to invoke</param>\n        /// <returns></returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1055:UriReturnValuesShouldNotBeStrings\", Justification = \"The return value is not a regular URL since it may contain ~/ ASP.NET-specific characters\"), SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an Extension Method which allows the user to provide a strongly-typed argument via Expression\"), SuppressMessage(\"Microsoft.Design\", \"CA1011:ConsiderPassingBaseTypesAsParameters\", Justification = \"Need to be sure the passed-in argument is of type Controller::Action\")]\n        public static string BuildUrlFromExpression<TController>(RequestContext context, RouteCollection routeCollection, Expression<Action<TController>> action) where TController : Controller\n        {\n            RouteValueDictionary routeValues = ExpressionHelper.GetRouteValuesFromExpression(action);\n            VirtualPathData vpd = routeCollection.GetVirtualPathForArea(context, routeValues);\n            return (vpd == null) ? null : vpd.VirtualPath;\n        }\n\n        /// <summary>\n        /// Creates a querystring as a Dictionary based on the passed-in Lambda\n        /// </summary>\n        /// <param name=\"call\">The Lambda of the Controller method</param>\n        /// <returns></returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Allowing Lambda compilation to fail if it doesn't compile at run time - design-time compilation will not allow for runtime Exception\")]\n        public static RouteValueDictionary BuildParameterValuesFromExpression(MethodCallExpression call)\n        {\n            RouteValueDictionary result = new RouteValueDictionary();\n\n            ParameterInfo[] parameters = call.Method.GetParameters();\n\n            if (parameters.Length > 0)\n            {\n                for (int i = 0; i < parameters.Length; i++)\n                {\n                    Expression arg = call.Arguments[i];\n                    object value;\n                    ConstantExpression ce = arg as ConstantExpression;\n                    if (ce != null)\n                    {\n                        // If argument is a constant expression, just get the value\n                        value = ce.Value;\n                    }\n                    else\n                    {\n                        try\n                        {\n                            value = CachedExpressionCompiler.Evaluate(arg);\n                        }\n                        catch\n                        {\n                            // ?????\n                            value = String.Empty;\n                        }\n                    }\n                    // Code should be added here to appropriately escape the value string\n                    result.Add(parameters[i].Name, value);\n                }\n            }\n            return result;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/LinkExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\nusing System.Web.Mvc;\nusing System.Web.Mvc.Html;\nusing System.Web.Routing;\nusing ExpressionHelper = Microsoft.Web.Mvc.Internal.ExpressionHelper;\n\nnamespace Microsoft.Web.Mvc\n{\n    public static class LinkExtensions\n    {\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1055:UriReturnValuesShouldNotBeStrings\", Justification = \"This is a UI method and is required to use strings as Uri\"), SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an Extension Method which allows the user to provide a strongly-typed argument via Expression\")]\n        public static string BuildUrlFromExpression<TController>(this HtmlHelper helper, Expression<Action<TController>> action) where TController : Controller\n        {\n            return LinkBuilder.BuildUrlFromExpression(helper.ViewContext.RequestContext, helper.RouteCollection, action);\n        }\n\n        /// <summary>\n        /// Creates an anchor tag based on the passed in controller type and method\n        /// </summary>\n        /// <typeparam name=\"TController\">The Controller Type</typeparam>\n        /// <param name=\"helper\">The <see cref=\"HtmlHelper\"/> where to create the link.</param>\n        /// <param name=\"action\">The Method to route to</param>\n        /// <param name=\"linkText\">The linked text to appear on the page</param>\n        /// <returns>The anchor tag.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString ActionLink<TController>(this HtmlHelper helper, Expression<Action<TController>> action, string linkText) where TController : Controller\n        {\n            return ActionLink(helper, action, linkText, null);\n        }\n\n        /// <summary>\n        /// Creates an anchor tag based on the passed in controller type and method\n        /// </summary>\n        /// <typeparam name=\"TController\">The Controller Type</typeparam>\n        /// <param name=\"helper\">The <see cref=\"HtmlHelper\"/> where to create the link.</param>\n        /// <param name=\"action\">The Method to route to</param>\n        /// <param name=\"linkText\">The linked text to appear on the page</param>\n        /// <param name=\"htmlAttributes\">Any additional HTML attributes.</param>\n        /// <returns>The anchor tag.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString ActionLink<TController>(this HtmlHelper helper, Expression<Action<TController>> action, string linkText, object htmlAttributes) where TController : Controller\n        {\n            RouteValueDictionary routingValues = ExpressionHelper.GetRouteValuesFromExpression(action);\n\n            return helper.RouteLink(linkText, routingValues, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/MachineKeyWrapper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web;\nusing System.Web.Security;\n\nnamespace Microsoft.Web.Mvc\n{\n    // Concrete implementation of IMachineKey that talks to the static MachineKey type\n\n    internal sealed class MachineKeyWrapper : IMachineKey\n    {\n        private static readonly MachineKeyWrapper _singletonInstance = new MachineKeyWrapper();\n\n        public static MachineKeyWrapper Instance\n        {\n            get\n            {\n                return _singletonInstance;\n            }\n        }\n\n        public byte[] Unprotect(string protectedData, params string[] purposes)\n        {\n            byte[] protectedBytes = Convert.FromBase64String(protectedData);\n            return MachineKey.Unprotect(protectedBytes, purposes);\n        }\n\n        public string Protect(byte[] userData, params string[] purposes)\n        {\n            byte[] protectedBytes = MachineKey.Protect(userData, purposes);\n            return Convert.ToBase64String(protectedBytes);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/MailToExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc\n{\n    [SuppressMessage(\"Microsoft.Naming\", \"CA1702:CompoundWordsShouldBeCasedCorrectly\", MessageId = \"MailTo\", Justification = \"This is correctly cased.\")]\n    public static class MailToExtensions\n    {\n        public static MvcHtmlString Mailto(this HtmlHelper helper, string linkText, string emailAddress)\n        {\n            return Mailto(helper, linkText, emailAddress, null, null, null, null, null);\n        }\n\n        public static MvcHtmlString Mailto(this HtmlHelper helper, string linkText, string emailAddress, object htmlAttributes)\n        {\n            return Mailto(helper, linkText, emailAddress, null, null, null, null, htmlAttributes);\n        }\n\n        public static MvcHtmlString Mailto(this HtmlHelper helper, string linkText, string emailAddress, IDictionary<string, object> htmlAttributes)\n        {\n            return Mailto(helper, linkText, emailAddress, null, null, null, null, htmlAttributes);\n        }\n\n        public static MvcHtmlString Mailto(this HtmlHelper helper, string linkText, string emailAddress, string subject)\n        {\n            return Mailto(helper, linkText, emailAddress, subject, null, null, null, null);\n        }\n\n        public static MvcHtmlString Mailto(this HtmlHelper helper, string linkText, string emailAddress, string subject, object htmlAttributes)\n        {\n            return Mailto(helper, linkText, emailAddress, subject, null, null, null, htmlAttributes);\n        }\n\n        public static MvcHtmlString Mailto(this HtmlHelper helper, string linkText, string emailAddress, string subject, IDictionary<string, object> htmlAttributes)\n        {\n            return Mailto(helper, linkText, emailAddress, subject, null, null, null, htmlAttributes);\n        }\n\n        public static MvcHtmlString Mailto(this HtmlHelper helper, string linkText, string emailAddress, string subject, string body, string cc, string bcc, object htmlAttributes)\n        {\n            return Mailto(helper, linkText, emailAddress, subject, body, cc, bcc, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcHtmlString Mailto(this HtmlHelper helper, string linkText, string emailAddress, string subject,\n                                           string body, string cc, string bcc, IDictionary<string, object> htmlAttributes)\n        {\n            if (emailAddress == null)\n            {\n                throw new ArgumentNullException(\"emailAddress\"); // TODO: Resource message\n            }\n            if (linkText == null)\n            {\n                throw new ArgumentNullException(\"linkText\"); // TODO: Resource message\n            }\n\n            string mailToUrl = \"mailto:\" + emailAddress;\n\n            List<string> mailQuery = new List<string>();\n            if (!String.IsNullOrEmpty(subject))\n            {\n                mailQuery.Add(\"subject=\" + helper.Encode(subject));\n            }\n\n            if (!String.IsNullOrEmpty(cc))\n            {\n                mailQuery.Add(\"cc=\" + helper.Encode(cc));\n            }\n\n            if (!String.IsNullOrEmpty(bcc))\n            {\n                mailQuery.Add(\"bcc=\" + helper.Encode(bcc));\n            }\n\n            if (!String.IsNullOrEmpty(body))\n            {\n                string encodedBody = helper.Encode(body);\n                encodedBody = encodedBody.Replace(Environment.NewLine, \"%0A\");\n                mailQuery.Add(\"body=\" + encodedBody);\n            }\n\n            string query = String.Empty;\n            for (int i = 0; i < mailQuery.Count; i++)\n            {\n                query += mailQuery[i];\n                if (i < mailQuery.Count - 1)\n                {\n                    query += \"&\";\n                }\n            }\n            if (query.Length > 0)\n            {\n                mailToUrl += \"?\" + query;\n            }\n\n            TagBuilder mailtoAnchor = new TagBuilder(\"a\");\n            mailtoAnchor.MergeAttribute(\"href\", mailToUrl);\n            mailtoAnchor.MergeAttributes(htmlAttributes, true);\n            mailtoAnchor.InnerHtml = linkText;\n            return MvcHtmlString.Create(mailtoAnchor.ToString());\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Microsoft.Web.Mvc.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{D3CF7430-6DA4-42B0-BD90-CA39D16687B2}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>Microsoft.Web.Mvc</RootNamespace>\n    <AssemblyName>Microsoft.Web.Mvc</AssemblyName>\n    <DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>\n    <RunCodeAnalysis>$(CodeAnalysis)</RunCodeAnalysis>\n    <CodeAnalysisRuleSet>..\\Strict.ruleset</CodeAnalysisRuleSet>\n    <DefineConstants>$(DefineConstants);ASPNETMVC</DefineConstants>\n    <NoWarn>1591</NoWarn>\n    <!-- Force signing off -->\n    <SignAssembly>false</SignAssembly>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.ComponentModel.DataAnnotations\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Data.Linq\" />\n    <Reference Include=\"System.Runtime.Serialization\" />\n    <Reference Include=\"System.ServiceModel\" />\n    <Reference Include=\"System.ServiceModel.Web\" />\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"System.Web.Abstractions\" />\n    <Reference Include=\"System.Web.Routing\" />\n    <Reference Include=\"System.Xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\CommonAssemblyInfo.cs\">\n      <Link>Properties\\CommonAssemblyInfo.cs</Link>\n    </Compile>\n    <Compile Include=\"AcceptAttribute.cs\" />\n    <Compile Include=\"GlobalSuppressions.cs\" />\n    <Compile Include=\"MachineKeyWrapper.cs\" />\n    <Compile Include=\"IMachineKey.cs\" />\n    <Compile Include=\"CreditCardAttribute.cs\" />\n    <Compile Include=\"EmailAddressAttribute.cs\" />\n    <Compile Include=\"FileExtensionsAttribute.cs\" />\n    <Compile Include=\"AreaHelpers.cs\" />\n    <Compile Include=\"AsyncManagerExtensions.cs\" />\n    <Compile Include=\"CookieValueProviderFactory.cs\" />\n    <Compile Include=\"ActionLinkAreaAttribute.cs\" />\n    <Compile Include=\"ControllerExtensions.cs\" />\n    <Compile Include=\"DynamicReflectionObject.cs\" />\n    <Compile Include=\"DynamicViewDataDictionary.cs\" />\n    <Compile Include=\"DynamicViewPage.cs\">\n      <SubType>ASPXCodeBehind</SubType>\n    </Compile>\n    <Compile Include=\"DynamicViewPageOfTModel.cs\">\n      <SubType>ASPXCodeBehind</SubType>\n    </Compile>\n    <Compile Include=\"ExpressionUtil\\BinaryExpressionFingerprint.cs\" />\n    <Compile Include=\"ExpressionUtil\\CachedExpressionCompiler.cs\" />\n    <Compile Include=\"ExpressionUtil\\ConditionalExpressionFingerprint.cs\" />\n    <Compile Include=\"ExpressionUtil\\ConstantExpressionFingerprint.cs\" />\n    <Compile Include=\"ExpressionUtil\\DefaultExpressionFingerprint.cs\" />\n    <Compile Include=\"ExpressionUtil\\ExpressionFingerprint.cs\" />\n    <Compile Include=\"ExpressionUtil\\ExpressionFingerprintChain.cs\" />\n    <Compile Include=\"ExpressionUtil\\FingerprintingExpressionVisitor.cs\" />\n    <Compile Include=\"ExpressionUtil\\HashCodeCombiner.cs\" />\n    <Compile Include=\"ExpressionUtil\\Hoisted.cs\" />\n    <Compile Include=\"ExpressionUtil\\HoistingExpressionVisitor.cs\" />\n    <Compile Include=\"ExpressionUtil\\IndexExpressionFingerprint.cs\" />\n    <Compile Include=\"ExpressionUtil\\LambdaExpressionFingerprint.cs\" />\n    <Compile Include=\"ExpressionUtil\\MemberExpressionFingerprint.cs\" />\n    <Compile Include=\"ExpressionUtil\\MethodCallExpressionFingerprint.cs\" />\n    <Compile Include=\"ExpressionUtil\\ParameterExpressionFingerprint.cs\" />\n    <Compile Include=\"ExpressionUtil\\TypeBinaryExpressionFingerprint.cs\" />\n    <Compile Include=\"ExpressionUtil\\UnaryExpressionFingerprint.cs\" />\n    <Compile Include=\"Html\\HtmlHelperExtensions.cs\" />\n    <Compile Include=\"ModelBinding\\BinaryDataModelBinderProvider.cs\" />\n    <Compile Include=\"ModelBinding\\ExtensibleModelBinderAttribute.cs\" />\n    <Compile Include=\"ModelBinding\\ModelBinderProviderOptionsAttribute.cs\" />\n    <Compile Include=\"ModelBinding\\ExtensibleModelBinderAdapter.cs\" />\n    <Compile Include=\"ModelBinding\\ExtensibleModelBindingContext.cs\" />\n    <Compile Include=\"ModelBinding\\IExtensibleModelBinder.cs\" />\n    <Compile Include=\"ModelBinding\\ModelBinderErrorMessageProvider.cs\" />\n    <Compile Include=\"ModelCopier.cs\" />\n    <Compile Include=\"ModelBinding\\CollectionModelBinderProvider.cs\" />\n    <Compile Include=\"ModelBinding\\CollectionModelBinderUtil.cs\" />\n    <Compile Include=\"ModelBinding\\CollectionModelBinder.cs\" />\n    <Compile Include=\"ModelBinding\\ComplexModelDtoModelBinderProvider.cs\" />\n    <Compile Include=\"ModelBinding\\ArrayModelBinderProvider.cs\" />\n    <Compile Include=\"ModelBinding\\ArrayModelBinder.cs\" />\n    <Compile Include=\"ModelBinding\\BindingBehaviorAttribute.cs\" />\n    <Compile Include=\"ModelBinding\\BindingBehavior.cs\" />\n    <Compile Include=\"ModelBinding\\BindNeverAttribute.cs\" />\n    <Compile Include=\"ModelBinding\\BindRequiredAttribute.cs\" />\n    <Compile Include=\"ModelBinding\\GenericModelBinderProvider.cs\" />\n    <Compile Include=\"ModelBinding\\DictionaryModelBinderProvider.cs\" />\n    <Compile Include=\"ModelBinding\\DictionaryModelBinder.cs\" />\n    <Compile Include=\"UrlAttribute.cs\" />\n    <Compile Include=\"ValueProviderUtil.cs\" />\n    <Compile Include=\"ElementalValueProvider.cs\" />\n    <Compile Include=\"ModelBinding\\KeyValuePairModelBinderProvider.cs\" />\n    <Compile Include=\"ModelBinding\\KeyValuePairModelBinderUtil.cs\" />\n    <Compile Include=\"ModelBinding\\KeyValuePairModelBinder.cs\" />\n    <Compile Include=\"TypeDescriptorHelper.cs\" />\n    <Compile Include=\"Error.cs\" />\n    <Compile Include=\"ModelBinding\\ComplexModelDto.cs\" />\n    <Compile Include=\"ModelBinding\\ComplexModelDtoModelBinder.cs\" />\n    <Compile Include=\"ModelBinding\\ComplexModelDtoResult.cs\" />\n    <Compile Include=\"ModelBinding\\ModelBinderConfig.cs\" />\n    <Compile Include=\"ModelBinding\\MutableObjectModelBinder.cs\" />\n    <Compile Include=\"ModelBinding\\MutableObjectModelBinderProvider.cs\" />\n    <Compile Include=\"ModelBinding\\SimpleModelBinderProvider.cs\" />\n    <Compile Include=\"ModelBinding\\TypeConverterModelBinder.cs\" />\n    <Compile Include=\"ModelBinding\\TypeConverterModelBinderProvider.cs\" />\n    <Compile Include=\"ModelBinding\\TypeMatchModelBinderProvider.cs\" />\n    <Compile Include=\"ModelBinding\\TypeMatchModelBinder.cs\" />\n    <Compile Include=\"ModelBinding\\ModelBinderProviderCollection.cs\" />\n    <Compile Include=\"ModelBinding\\ModelBinderProvider.cs\" />\n    <Compile Include=\"ModelBinding\\ModelBinderUtil.cs\" />\n    <Compile Include=\"ModelBinding\\ModelValidatedEventArgs.cs\" />\n    <Compile Include=\"ModelBinding\\ModelValidatingEventArgs.cs\" />\n    <Compile Include=\"ModelBinding\\ModelValidationNode.cs\" />\n    <Compile Include=\"ModelBinding\\ModelBinderProviders.cs\" />\n    <Compile Include=\"ServerVariablesValueProviderFactory.cs\" />\n    <Compile Include=\"TempDataValueProviderFactory.cs\" />\n    <Compile Include=\"SessionValueProviderFactory.cs\" />\n    <Compile Include=\"CopyAsyncParametersAttribute.cs\" />\n    <Compile Include=\"CssExtensions.cs\" />\n    <Compile Include=\"Resources\\ActionType.cs\" />\n    <Compile Include=\"Resources\\AjaxHelperExtensions.cs\" />\n    <Compile Include=\"Resources\\AtomEntryActionResult.cs\" />\n    <Compile Include=\"Resources\\AtomFeedActionResult.cs\" />\n    <Compile Include=\"Resources\\AtomServiceDocumentActionResult.cs\" />\n    <Compile Include=\"Resources\\DataContractJsonActionResult.cs\" />\n    <Compile Include=\"Resources\\JsonFormatHandler.cs\" />\n    <Compile Include=\"Resources\\RouteCollectionExtensions.cs\" />\n    <Compile Include=\"Resources\\UriHelperExtensions.cs\" />\n    <Compile Include=\"Resources\\WebApiEnabledAttribute.cs\" />\n    <Compile Include=\"Resources\\XmlFormatHandler.cs\" />\n    <Compile Include=\"Resources\\IResponseFormatHandler.cs\" />\n    <Compile Include=\"Resources\\IRequestFormatHandler.cs\" />\n    <Compile Include=\"Resources\\FormatManager.cs\" />\n    <Compile Include=\"Resources\\HtmlHelperExtensions.cs\" />\n    <Compile Include=\"Resources\\MultiFormatActionResult.cs\" />\n    <Compile Include=\"Resources\\RequestContextExtensions.cs\" />\n    <Compile Include=\"Resources\\ResourceControllerFactory.cs\" />\n    <Compile Include=\"Resources\\ResourceErrorActionResult.cs\" />\n    <Compile Include=\"Resources\\ResourceModelBinder.cs\" />\n    <Compile Include=\"Resources\\ResourceRedirectToRouteResult.cs\" />\n    <Compile Include=\"Resources\\DataContractXmlActionResult.cs\" />\n    <Compile Include=\"Resources\\HttpRequestBaseExtensions.cs\" />\n    <Compile Include=\"Resources\\IEnumerableExtensions.cs\" />\n    <Compile Include=\"Resources\\DefaultFormatHelper.cs\" />\n    <Compile Include=\"Resources\\DefaultFormatManager.cs\" />\n    <Compile Include=\"Resources\\FormatHelper.cs\" />\n    <Compile Include=\"Internal\\ExpressionHelper.cs\" />\n    <Compile Include=\"DeserializeAttribute.cs\" />\n    <Compile Include=\"ScriptExtensions.cs\" />\n    <Compile Include=\"SerializationExtensions.cs\" />\n    <Compile Include=\"MvcSerializer.cs\" />\n    <Compile Include=\"AjaxOnlyAttribute.cs\" />\n    <Compile Include=\"CachedExpressionCompiler.cs\" />\n    <Compile Include=\"ReaderWriterCache.cs\" />\n    <Compile Include=\"ButtonBuilder.cs\" />\n    <Compile Include=\"ButtonsAndLinkExtensions.cs\" />\n    <Compile Include=\"ContentTypeAttribute.cs\" />\n    <Compile Include=\"Controls\\ActionLink.cs\" />\n    <Compile Include=\"Controls\\EncodeType.cs\" />\n    <Compile Include=\"Controls\\DropDownList.cs\" />\n    <Compile Include=\"Controls\\Hidden.cs\" />\n    <Compile Include=\"Controls\\Label.cs\" />\n    <Compile Include=\"Controls\\MvcControl.cs\" />\n    <Compile Include=\"Controls\\MvcInputControl.cs\" />\n    <Compile Include=\"Controls\\Password.cs\" />\n    <Compile Include=\"Controls\\Repeater.cs\" />\n    <Compile Include=\"Controls\\RepeaterItem.cs\" />\n    <Compile Include=\"Controls\\RouteValues.cs\" />\n    <Compile Include=\"Controls\\TextBox.cs\" />\n    <Compile Include=\"SkipBindingAttribute.cs\" />\n    <Compile Include=\"FormExtensions.cs\" />\n    <Compile Include=\"HtmlButtonType.cs\" />\n    <Compile Include=\"LinkBuilder.cs\" />\n    <Compile Include=\"LinkExtensions.cs\" />\n    <Compile Include=\"RadioExtensions.cs\" />\n    <Compile Include=\"ImageExtensions.cs\" />\n    <Compile Include=\"MailToExtensions.cs\" />\n    <Compile Include=\"TypeHelpers.cs\" />\n    <Compile Include=\"ViewExtensions.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"Properties\\MvcResources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>MvcResources.resx</DependentUpon>\n    </Compile>\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\System.Web.Mvc\\System.Web.Mvc.csproj\">\n      <Project>{3D3FFD8A-624D-4E9B-954B-E1C105507975}</Project>\n      <Name>System.Web.Mvc</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.WebPages\\System.Web.WebPages.csproj\">\n      <Project>{76EFA9C5-8D7E-4FDF-B710-E20F8B6B00D2}</Project>\n      <Name>System.Web.WebPages</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"Properties\\MvcResources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>MvcResources.Designer.cs</LastGenOutput>\n      <SubType>Designer</SubType>\n    </EmbeddedResource>\n  </ItemGroup>\n  <ItemGroup>\n    <CodeAnalysisDictionary Include=\"..\\CodeAnalysisDictionary.xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"FuturesFiles\\DefaultTemplates\\DisplayTemplates\\Boolean.ascx\">\n      <SubType>ASPXCodeBehind</SubType>\n    </None>\n    <None Include=\"FuturesFiles\\DefaultTemplates\\DisplayTemplates\\Collection.ascx\" />\n    <None Include=\"FuturesFiles\\DefaultTemplates\\DisplayTemplates\\Decimal.ascx\" />\n    <None Include=\"FuturesFiles\\DefaultTemplates\\DisplayTemplates\\EmailAddress.ascx\" />\n    <None Include=\"FuturesFiles\\DefaultTemplates\\DisplayTemplates\\HiddenInput.ascx\" />\n    <None Include=\"FuturesFiles\\DefaultTemplates\\DisplayTemplates\\Html.ascx\" />\n    <None Include=\"FuturesFiles\\DefaultTemplates\\DisplayTemplates\\Object.ascx\" />\n    <None Include=\"FuturesFiles\\DefaultTemplates\\DisplayTemplates\\String.ascx\" />\n    <None Include=\"FuturesFiles\\DefaultTemplates\\DisplayTemplates\\Url.ascx\" />\n    <None Include=\"FuturesFiles\\DefaultTemplates\\EditorTemplates\\Boolean.ascx\" />\n    <None Include=\"FuturesFiles\\DefaultTemplates\\EditorTemplates\\Collection.ascx\" />\n    <None Include=\"FuturesFiles\\DefaultTemplates\\EditorTemplates\\Decimal.ascx\" />\n    <None Include=\"FuturesFiles\\DefaultTemplates\\EditorTemplates\\HiddenInput.ascx\" />\n    <None Include=\"FuturesFiles\\DefaultTemplates\\EditorTemplates\\MultilineText.ascx\" />\n    <None Include=\"FuturesFiles\\DefaultTemplates\\EditorTemplates\\Object.ascx\" />\n    <None Include=\"FuturesFiles\\DefaultTemplates\\EditorTemplates\\Password.ascx\" />\n    <None Include=\"FuturesFiles\\DefaultTemplates\\EditorTemplates\\String.ascx\" />\n    <None Include=\"FuturesFiles\\iismap.vbs\" />\n    <None Include=\"FuturesFiles\\MvcDiagnostics.aspx\">\n      <SubType>ASPXCodeBehind</SubType>\n    </None>\n    <None Include=\"FuturesFiles\\registermvc.wsf\" />\n    <None Include=\"FuturesFiles\\unregistermvc.wsf\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n</Project>"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/ArrayModelBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    public class ArrayModelBinder<TElement> : CollectionModelBinder<TElement>\n    {\n        protected override bool CreateOrReplaceCollection(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext, IList<TElement> newCollection)\n        {\n            bindingContext.Model = newCollection.ToArray();\n            return true;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/ArrayModelBinderProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    public sealed class ArrayModelBinderProvider : ModelBinderProvider\n    {\n        public override IExtensibleModelBinder GetBinder(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n        {\n            ModelBinderUtil.ValidateBindingContext(bindingContext);\n\n            if (!bindingContext.ModelMetadata.IsReadOnly && bindingContext.ModelType.IsArray &&\n                bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName))\n            {\n                Type elementType = bindingContext.ModelType.GetElementType();\n                return (IExtensibleModelBinder)Activator.CreateInstance(typeof(ArrayModelBinder<>).MakeGenericType(elementType));\n            }\n\n            return null;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/BinaryDataModelBinderProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Data.Linq;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    // This is a single provider that can work with both byte[] and Binary models.\n    public sealed class BinaryDataModelBinderProvider : ModelBinderProvider\n    {\n        private static readonly ModelBinderProvider[] _providers = new ModelBinderProvider[]\n        {\n            new SimpleModelBinderProvider(typeof(byte[]), new ByteArrayExtensibleModelBinder()),\n            new SimpleModelBinderProvider(typeof(Binary), new LinqBinaryExtensibleModelBinder())\n        };\n\n        public override IExtensibleModelBinder GetBinder(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n        {\n            return (from provider in _providers\n                    let binder = provider.GetBinder(controllerContext, bindingContext)\n                    where binder != null\n                    select binder).FirstOrDefault();\n        }\n\n        // This is essentially a clone of the ByteArrayModelBinder from core\n        private class ByteArrayExtensibleModelBinder : IExtensibleModelBinder\n        {\n            [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We want to ignore when the data is corrupted\")]\n            [SuppressMessage(\"Microsoft.Globalization\", \"CA1304:SpecifyCultureInfo\", MessageId = \"System.Web.Mvc.ValueProviderResult.ConvertTo(System.Type)\", Justification = \"The target object should make the correct culture determination, not this method.\")]\n            public bool BindModel(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n            {\n                ModelBinderUtil.ValidateBindingContext(bindingContext);\n                ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);\n\n                // case 1: there was no <input ... /> element containing this data\n                if (valueProviderResult == null)\n                {\n                    return false;\n                }\n\n                string base64String = (string)valueProviderResult.ConvertTo(typeof(string));\n\n                // case 2: there was an <input ... /> element but it was left blank\n                if (String.IsNullOrEmpty(base64String))\n                {\n                    return false;\n                }\n\n                // Future proofing. If the byte array is actually an instance of System.Data.Linq.Binary\n                // then we need to remove these quotes put in place by the ToString() method.\n                string realValue = base64String.Replace(\"\\\"\", String.Empty);\n                try\n                {\n                    bindingContext.Model = ConvertByteArray(Convert.FromBase64String(realValue));\n                    return true;\n                }\n                catch\n                {\n                    // corrupt data - just ignore\n                    return false;\n                }\n            }\n\n            protected virtual object ConvertByteArray(byte[] originalModel)\n            {\n                return originalModel;\n            }\n        }\n\n        // This is essentially a clone of the LinqBinaryModelBinder from core\n        private class LinqBinaryExtensibleModelBinder : ByteArrayExtensibleModelBinder\n        {\n            protected override object ConvertByteArray(byte[] originalModel)\n            {\n                return new Binary(originalModel);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/BindNeverAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]\n    public sealed class BindNeverAttribute : BindingBehaviorAttribute\n    {\n        public BindNeverAttribute()\n            : base(BindingBehavior.Never)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/BindRequiredAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]\n    public sealed class BindRequiredAttribute : BindingBehaviorAttribute\n    {\n        public BindRequiredAttribute()\n            : base(BindingBehavior.Required)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/BindingBehavior.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    public enum BindingBehavior\n    {\n        Optional = 0,\n        Never,\n        Required\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/BindingBehaviorAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]\n    [SuppressMessage(\"Microsoft.Performance\", \"CA1813:AvoidUnsealedAttributes\", Justification = \"This class is designed to be overridden\")]\n    public class BindingBehaviorAttribute : Attribute\n    {\n        private static readonly object _typeId = new object();\n\n        public BindingBehaviorAttribute(BindingBehavior behavior)\n        {\n            Behavior = behavior;\n        }\n\n        public BindingBehavior Behavior { get; private set; }\n\n        public override object TypeId\n        {\n            get { return _typeId; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/CollectionModelBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    public class CollectionModelBinder<TElement> : IExtensibleModelBinder\n    {\n        // Used when the ValueProvider contains the collection to be bound as multiple elements, e.g. foo[0], foo[1].\n        private static List<TElement> BindComplexCollection(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n        {\n            string indexPropertyName = ModelBinderUtil.CreatePropertyModelName(bindingContext.ModelName, \"index\");\n            ValueProviderResult valueProviderResultIndex = bindingContext.ValueProvider.GetValue(indexPropertyName);\n            IEnumerable<string> indexNames = CollectionModelBinderUtil.GetIndexNamesFromValueProviderResult(valueProviderResultIndex);\n            return BindComplexCollectionFromIndexes(controllerContext, bindingContext, indexNames);\n        }\n\n        internal static List<TElement> BindComplexCollectionFromIndexes(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext, IEnumerable<string> indexNames)\n        {\n            bool indexNamesIsFinite;\n            if (indexNames != null)\n            {\n                indexNamesIsFinite = true;\n            }\n            else\n            {\n                indexNamesIsFinite = false;\n                indexNames = CollectionModelBinderUtil.GetZeroBasedIndexes();\n            }\n\n            List<TElement> boundCollection = new List<TElement>();\n            foreach (string indexName in indexNames)\n            {\n                string fullChildName = ModelBinderUtil.CreateIndexModelName(bindingContext.ModelName, indexName);\n                ExtensibleModelBindingContext childBindingContext = new ExtensibleModelBindingContext(bindingContext)\n                {\n                    ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(TElement)),\n                    ModelName = fullChildName\n                };\n\n                object boundValue = null;\n                IExtensibleModelBinder childBinder = bindingContext.ModelBinderProviders.GetBinder(controllerContext, childBindingContext);\n                if (childBinder != null)\n                {\n                    if (childBinder.BindModel(controllerContext, childBindingContext))\n                    {\n                        boundValue = childBindingContext.Model;\n\n                        // merge validation up\n                        bindingContext.ValidationNode.ChildNodes.Add(childBindingContext.ValidationNode);\n                    }\n                }\n                else\n                {\n                    // should we even bother continuing?\n                    if (!indexNamesIsFinite)\n                    {\n                        break;\n                    }\n                }\n\n                boundCollection.Add(ModelBinderUtil.CastOrDefault<TElement>(boundValue));\n            }\n\n            return boundCollection;\n        }\n\n        public virtual bool BindModel(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n        {\n            ModelBinderUtil.ValidateBindingContext(bindingContext);\n\n            ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);\n            List<TElement> boundCollection = (valueProviderResult != null)\n                                                 ? BindSimpleCollection(controllerContext, bindingContext, valueProviderResult.RawValue, valueProviderResult.Culture)\n                                                 : BindComplexCollection(controllerContext, bindingContext);\n\n            bool retVal = CreateOrReplaceCollection(controllerContext, bindingContext, boundCollection);\n            return retVal;\n        }\n\n        // Used when the ValueProvider contains the collection to be bound as a single element, e.g. the raw value\n        // is [ \"1\", \"2\" ] and needs to be converted to an int[].\n        internal static List<TElement> BindSimpleCollection(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext, object rawValue, CultureInfo culture)\n        {\n            if (rawValue == null)\n            {\n                return null; // nothing to do\n            }\n\n            List<TElement> boundCollection = new List<TElement>();\n\n            object[] rawValueArray = ModelBinderUtil.RawValueToObjectArray(rawValue);\n            foreach (object rawValueElement in rawValueArray)\n            {\n                ExtensibleModelBindingContext innerBindingContext = new ExtensibleModelBindingContext(bindingContext)\n                {\n                    ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(TElement)),\n                    ModelName = bindingContext.ModelName,\n                    ValueProvider = new ValueProviderCollection\n                    {\n                        // aggregate value provider\n                        new ElementalValueProvider(bindingContext.ModelName, rawValueElement, culture), // our temporary provider goes at the front of the list\n                        bindingContext.ValueProvider\n                    }\n                };\n\n                object boundValue = null;\n                IExtensibleModelBinder childBinder = bindingContext.ModelBinderProviders.GetBinder(controllerContext, innerBindingContext);\n                if (childBinder != null)\n                {\n                    if (childBinder.BindModel(controllerContext, innerBindingContext))\n                    {\n                        boundValue = innerBindingContext.Model;\n                        bindingContext.ValidationNode.ChildNodes.Add(innerBindingContext.ValidationNode);\n                    }\n                }\n                boundCollection.Add(ModelBinderUtil.CastOrDefault<TElement>(boundValue));\n            }\n\n            return boundCollection;\n        }\n\n        // Extensibility point that allows the bound collection to be manipulated or transformed before\n        // being returned from the binder.\n        protected virtual bool CreateOrReplaceCollection(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext, IList<TElement> newCollection)\n        {\n            CollectionModelBinderUtil.CreateOrReplaceCollection(bindingContext, newCollection, () => new List<TElement>());\n            return true;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/CollectionModelBinderProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    public sealed class CollectionModelBinderProvider : ModelBinderProvider\n    {\n        public override IExtensibleModelBinder GetBinder(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n        {\n            ModelBinderUtil.ValidateBindingContext(bindingContext);\n\n            if (bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName))\n            {\n                return CollectionModelBinderUtil.GetGenericBinder(typeof(ICollection<>), typeof(List<>), typeof(CollectionModelBinder<>), bindingContext.ModelMetadata);\n            }\n            else\n            {\n                return null;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/CollectionModelBinderUtil.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    internal static class CollectionModelBinderUtil\n    {\n        public static void CreateOrReplaceCollection<TElement>(ExtensibleModelBindingContext bindingContext, IEnumerable<TElement> incomingElements, Func<ICollection<TElement>> creator)\n        {\n            ICollection<TElement> collection = bindingContext.Model as ICollection<TElement>;\n            if (collection == null || collection.IsReadOnly)\n            {\n                collection = creator();\n                bindingContext.Model = collection;\n            }\n\n            collection.Clear();\n            foreach (TElement element in incomingElements)\n            {\n                collection.Add(element);\n            }\n        }\n\n        public static void CreateOrReplaceDictionary<TKey, TValue>(ExtensibleModelBindingContext bindingContext, IEnumerable<KeyValuePair<TKey, TValue>> incomingElements, Func<IDictionary<TKey, TValue>> creator)\n        {\n            IDictionary<TKey, TValue> dictionary = bindingContext.Model as IDictionary<TKey, TValue>;\n            if (dictionary == null || dictionary.IsReadOnly)\n            {\n                dictionary = creator();\n                bindingContext.Model = dictionary;\n            }\n\n            dictionary.Clear();\n            foreach (var element in incomingElements)\n            {\n                if (element.Key != null)\n                {\n                    dictionary[element.Key] = element.Value;\n                }\n            }\n        }\n\n        // supportedInterfaceType: type that is updatable by this binder\n        // newInstanceType: type that will be created by the binder if necessary\n        // openBinderType: model binder type\n        // modelMetadata: metadata for the model to bind\n        //\n        // example: GetGenericBinder(typeof(IList<>), typeof(List<>), typeof(ListBinder<>), ...) means that the ListBinder<T>\n        // type can update models that implement IList<T>, and if for some reason the existing model instance is not\n        // updatable the binder will create a List<T> object and bind to that instead. This method will return a ListBinder<T>\n        // or null, depending on whether the type and updatability checks succeed.\n        public static IExtensibleModelBinder GetGenericBinder(Type supportedInterfaceType, Type newInstanceType, Type openBinderType, ModelMetadata modelMetadata)\n        {\n            Type[] typeArguments = GetTypeArgumentsForUpdatableGenericCollection(supportedInterfaceType, newInstanceType, modelMetadata);\n            return (typeArguments != null) ? (IExtensibleModelBinder)Activator.CreateInstance(openBinderType.MakeGenericType(typeArguments)) : null;\n        }\n\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1304:SpecifyCultureInfo\", MessageId = \"System.Web.Mvc.ValueProviderResult.ConvertTo(System.Type)\", Justification = \"This model binder binds collections, so it does not need culture.\")]\n        public static IEnumerable<string> GetIndexNamesFromValueProviderResult(ValueProviderResult valueProviderResultIndex)\n        {\n            IEnumerable<string> indexNames = null;\n            if (valueProviderResultIndex != null)\n            {\n                string[] indexes = (string[])(valueProviderResultIndex.ConvertTo(typeof(string[])));\n                if (indexes != null && indexes.Length > 0)\n                {\n                    indexNames = indexes;\n                }\n            }\n            return indexNames;\n        }\n\n        public static IEnumerable<string> GetZeroBasedIndexes()\n        {\n            int i = 0;\n            while (true)\n            {\n                yield return i.ToString(CultureInfo.InvariantCulture);\n                i++;\n            }\n        }\n\n        // Returns the generic type arguments for the model type if updatable, else null.\n        // supportedInterfaceType: open type (like IList<>) of supported interface, must implement ICollection<>\n        // newInstanceType: open type (like List<>) of object that will be created, must implement supportedInterfaceType\n        public static Type[] GetTypeArgumentsForUpdatableGenericCollection(Type supportedInterfaceType, Type newInstanceType, ModelMetadata modelMetadata)\n        {\n            /*\n             * Check that we can extract proper type arguments from the model.\n             */\n\n            if (!modelMetadata.ModelType.IsGenericType || modelMetadata.ModelType.IsGenericTypeDefinition)\n            {\n                // not a closed generic type\n                return null;\n            }\n\n            Type[] modelTypeArguments = modelMetadata.ModelType.GetGenericArguments();\n            if (modelTypeArguments.Length != supportedInterfaceType.GetGenericArguments().Length)\n            {\n                // wrong number of generic type arguments\n                return null;\n            }\n\n            /*\n             * Is it possible just to change the reference rather than update the collection in-place?\n             */\n\n            if (!modelMetadata.IsReadOnly)\n            {\n                Type closedNewInstanceType = newInstanceType.MakeGenericType(modelTypeArguments);\n                if (modelMetadata.ModelType.IsAssignableFrom(closedNewInstanceType))\n                {\n                    return modelTypeArguments;\n                }\n            }\n\n            /*\n             * At this point, we know we can't change the reference, so we need to verify that\n             * the model instance can be updated in-place.\n             */\n\n            Type closedSupportedInterfaceType = supportedInterfaceType.MakeGenericType(modelTypeArguments);\n            if (!closedSupportedInterfaceType.IsInstanceOfType(modelMetadata.Model))\n            {\n                return null; // not instance of correct interface\n            }\n\n            Type closedCollectionType = TypeHelpers.ExtractGenericInterface(closedSupportedInterfaceType, typeof(ICollection<>));\n            bool collectionInstanceIsReadOnly = (bool)closedCollectionType.GetProperty(\"IsReadOnly\").GetValue(modelMetadata.Model, null);\n            if (collectionInstanceIsReadOnly)\n            {\n                return null;\n            }\n            else\n            {\n                return modelTypeArguments;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/ComplexModelDto.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    // Describes a complex model, but uses a collection rather than individual properties as the data store.\n    public class ComplexModelDto\n    {\n        public ComplexModelDto(ModelMetadata modelMetadata, IEnumerable<ModelMetadata> propertyMetadata)\n        {\n            if (modelMetadata == null)\n            {\n                throw new ArgumentNullException(\"modelMetadata\");\n            }\n            if (propertyMetadata == null)\n            {\n                throw new ArgumentNullException(\"propertyMetadata\");\n            }\n\n            ModelMetadata = modelMetadata;\n            PropertyMetadata = new ReadOnlyCollection<ModelMetadata>(propertyMetadata.ToList());\n            Results = new Dictionary<ModelMetadata, ComplexModelDtoResult>();\n        }\n\n        public ModelMetadata ModelMetadata { get; private set; }\n\n        public ReadOnlyCollection<ModelMetadata> PropertyMetadata { get; private set; }\n\n        // Contains entries corresponding to each property against which binding was\n        // attempted. If binding failed, the entry's value will be null. If binding\n        // was never attempted, this dictionary will not contain a corresponding\n        // entry.\n        public IDictionary<ModelMetadata, ComplexModelDtoResult> Results { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/ComplexModelDtoModelBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    public sealed class ComplexModelDtoModelBinder : IExtensibleModelBinder\n    {\n        public bool BindModel(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n        {\n            ModelBinderUtil.ValidateBindingContext(bindingContext, typeof(ComplexModelDto), false /* allowNullModel */);\n\n            ComplexModelDto dto = (ComplexModelDto)bindingContext.Model;\n            foreach (ModelMetadata propertyMetadata in dto.PropertyMetadata)\n            {\n                ExtensibleModelBindingContext propertyBindingContext = new ExtensibleModelBindingContext(bindingContext)\n                {\n                    ModelMetadata = propertyMetadata,\n                    ModelName = ModelBinderUtil.CreatePropertyModelName(bindingContext.ModelName, propertyMetadata.PropertyName)\n                };\n\n                // bind and propagate the values\n                IExtensibleModelBinder propertyBinder = bindingContext.ModelBinderProviders.GetBinder(controllerContext, propertyBindingContext);\n                if (propertyBinder != null)\n                {\n                    if (propertyBinder.BindModel(controllerContext, propertyBindingContext))\n                    {\n                        dto.Results[propertyMetadata] = new ComplexModelDtoResult(propertyBindingContext.Model, propertyBindingContext.ValidationNode);\n                    }\n                    else\n                    {\n                        dto.Results[propertyMetadata] = null;\n                    }\n                }\n            }\n\n            return true;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/ComplexModelDtoModelBinderProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    // Returns a binder that can bind ComplexModelDto objects.\n    public sealed class ComplexModelDtoModelBinderProvider : ModelBinderProvider\n    {\n        // This is really just a simple binder.\n        private static readonly SimpleModelBinderProvider _underlyingProvider = GetUnderlyingProvider();\n\n        public override IExtensibleModelBinder GetBinder(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n        {\n            return _underlyingProvider.GetBinder(controllerContext, bindingContext);\n        }\n\n        private static SimpleModelBinderProvider GetUnderlyingProvider()\n        {\n            return new SimpleModelBinderProvider(typeof(ComplexModelDto), new ComplexModelDtoModelBinder())\n            {\n                SuppressPrefixCheck = true\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/ComplexModelDtoResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    public sealed class ComplexModelDtoResult\n    {\n        public ComplexModelDtoResult(object model, ModelValidationNode validationNode)\n        {\n            if (validationNode == null)\n            {\n                throw new ArgumentNullException(\"validationNode\");\n            }\n\n            Model = model;\n            ValidationNode = validationNode;\n        }\n\n        public object Model { get; private set; }\n\n        public ModelValidationNode ValidationNode { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/DictionaryModelBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    public class DictionaryModelBinder<TKey, TValue> : CollectionModelBinder<KeyValuePair<TKey, TValue>>\n    {\n        protected override bool CreateOrReplaceCollection(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext, IList<KeyValuePair<TKey, TValue>> newCollection)\n        {\n            CollectionModelBinderUtil.CreateOrReplaceDictionary(bindingContext, newCollection, () => new Dictionary<TKey, TValue>());\n            return true;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/DictionaryModelBinderProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    public sealed class DictionaryModelBinderProvider : ModelBinderProvider\n    {\n        public override IExtensibleModelBinder GetBinder(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n        {\n            ModelBinderUtil.ValidateBindingContext(bindingContext);\n\n            if (bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName))\n            {\n                return CollectionModelBinderUtil.GetGenericBinder(typeof(IDictionary<,>), typeof(Dictionary<,>), typeof(DictionaryModelBinder<,>), bindingContext.ModelMetadata);\n            }\n            else\n            {\n                return null;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/ExtensibleModelBinderAdapter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Linq;\nusing System.Web.Mvc;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    // A model binder that is used to interface between the old system and the new system.\n    public sealed class ExtensibleModelBinderAdapter : IModelBinder\n    {\n        public ExtensibleModelBinderAdapter(ModelBinderProviderCollection providers)\n        {\n            Providers = providers ?? ModelBinderProviders.Providers;\n        }\n\n        public ModelBinderProviderCollection Providers { get; private set; }\n\n        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)\n        {\n            CheckPropertyFilter(bindingContext);\n            ExtensibleModelBindingContext newBindingContext = CreateNewBindingContext(bindingContext, bindingContext.ModelName);\n\n            IExtensibleModelBinder binder = Providers.GetBinder(controllerContext, newBindingContext);\n            if (binder == null && !String.IsNullOrEmpty(bindingContext.ModelName)\n                && bindingContext.FallbackToEmptyPrefix && bindingContext.ModelMetadata.IsComplexType)\n            {\n                // fallback to empty prefix?\n                newBindingContext = CreateNewBindingContext(bindingContext, String.Empty /* modelName */);\n                binder = Providers.GetBinder(controllerContext, newBindingContext);\n            }\n\n            if (binder != null)\n            {\n                bool boundSuccessfully = binder.BindModel(controllerContext, newBindingContext);\n                if (boundSuccessfully)\n                {\n                    // run validation and return the model\n                    newBindingContext.ValidationNode.Validate(controllerContext, null /* parentNode */);\n                    return newBindingContext.Model;\n                }\n            }\n\n            return null; // something went wrong\n        }\n\n        private static void CheckPropertyFilter(ModelBindingContext bindingContext)\n        {\n            if (bindingContext.ModelType.GetProperties().Select(p => p.Name).Any(name => !bindingContext.PropertyFilter(name)))\n            {\n                throw new InvalidOperationException(MvcResources.ExtensibleModelBinderAdapter_PropertyFilterMustNotBeSet);\n            }\n        }\n\n        private ExtensibleModelBindingContext CreateNewBindingContext(ModelBindingContext oldBindingContext, string modelName)\n        {\n            ExtensibleModelBindingContext newBindingContext = new ExtensibleModelBindingContext\n            {\n                ModelBinderProviders = Providers,\n                ModelMetadata = oldBindingContext.ModelMetadata,\n                ModelName = modelName,\n                ModelState = oldBindingContext.ModelState,\n                ValueProvider = oldBindingContext.ValueProvider\n            };\n\n            return newBindingContext;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/ExtensibleModelBinderAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false, Inherited = true)]\n    public sealed class ExtensibleModelBinderAttribute : Attribute\n    {\n        public ExtensibleModelBinderAttribute(Type binderType)\n        {\n            BinderType = binderType;\n        }\n\n        public Type BinderType { get; private set; }\n\n        public bool SuppressPrefixCheck { get; set; }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/ExtensibleModelBindingContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    public class ExtensibleModelBindingContext\n    {\n        private ModelBinderProviderCollection _modelBinderProviders;\n        private string _modelName;\n        private ModelStateDictionary _modelState;\n        private Dictionary<string, ModelMetadata> _propertyMetadata;\n        private ModelValidationNode _validationNode;\n\n        public ExtensibleModelBindingContext()\n            : this(null)\n        {\n        }\n\n        // copies certain values that won't change between parent and child objects,\n        // e.g. ValueProvider, ModelState\n        public ExtensibleModelBindingContext(ExtensibleModelBindingContext bindingContext)\n        {\n            if (bindingContext != null)\n            {\n                ModelBinderProviders = bindingContext.ModelBinderProviders;\n                ModelState = bindingContext.ModelState;\n                ValueProvider = bindingContext.ValueProvider;\n            }\n        }\n\n        public object Model\n        {\n            get\n            {\n                EnsureModelMetadata();\n                return ModelMetadata.Model;\n            }\n            set\n            {\n                EnsureModelMetadata();\n                ModelMetadata.Model = value;\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"This is writeable to support unit testing\")]\n        public ModelBinderProviderCollection ModelBinderProviders\n        {\n            get\n            {\n                if (_modelBinderProviders == null)\n                {\n                    _modelBinderProviders = ModelBinding.ModelBinderProviders.Providers;\n                }\n                return _modelBinderProviders;\n            }\n            set { _modelBinderProviders = value; }\n        }\n\n        public ModelMetadata ModelMetadata { get; set; }\n\n        public string ModelName\n        {\n            get\n            {\n                if (_modelName == null)\n                {\n                    _modelName = String.Empty;\n                }\n                return _modelName;\n            }\n            set { _modelName = value; }\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"This is writeable to support unit testing\")]\n        public ModelStateDictionary ModelState\n        {\n            get\n            {\n                if (_modelState == null)\n                {\n                    _modelState = new ModelStateDictionary();\n                }\n                return _modelState;\n            }\n            set { _modelState = value; }\n        }\n\n        public Type ModelType\n        {\n            get\n            {\n                EnsureModelMetadata();\n                return ModelMetadata.ModelType;\n            }\n        }\n\n        public IDictionary<string, ModelMetadata> PropertyMetadata\n        {\n            get\n            {\n                if (_propertyMetadata == null)\n                {\n                    _propertyMetadata = ModelMetadata.Properties.ToDictionary(m => m.PropertyName, StringComparer.OrdinalIgnoreCase);\n                }\n\n                return _propertyMetadata;\n            }\n        }\n\n        public ModelValidationNode ValidationNode\n        {\n            get\n            {\n                if (_validationNode == null)\n                {\n                    _validationNode = new ModelValidationNode(ModelMetadata, ModelName);\n                }\n                return _validationNode;\n            }\n            set { _validationNode = value; }\n        }\n\n        public IValueProvider ValueProvider { get; set; }\n\n        private void EnsureModelMetadata()\n        {\n            if (ModelMetadata == null)\n            {\n                throw Error.ModelBindingContext_ModelMetadataMustBeSet();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/GenericModelBinderProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    // Returns a user-specified binder for a given open generic type.\n    public sealed class GenericModelBinderProvider : ModelBinderProvider\n    {\n        private readonly Func<Type[], IExtensibleModelBinder> _modelBinderFactory;\n        private readonly Type _modelType;\n\n        public GenericModelBinderProvider(Type modelType, IExtensibleModelBinder modelBinder)\n        {\n            if (modelType == null)\n            {\n                throw new ArgumentNullException(\"modelType\");\n            }\n            if (modelBinder == null)\n            {\n                throw new ArgumentNullException(\"modelBinder\");\n            }\n\n            ValidateParameters(modelType, null /* modelBinderType */);\n\n            _modelType = modelType;\n            _modelBinderFactory = _ => modelBinder;\n        }\n\n        public GenericModelBinderProvider(Type modelType, Type modelBinderType)\n        {\n            // The binder can be a closed type, in which case it will be instantiated directly. If the binder\n            // is an open type, the type arguments will be determined at runtime and the corresponding closed\n            // type instantiated.\n\n            if (modelType == null)\n            {\n                throw new ArgumentNullException(\"modelType\");\n            }\n            if (modelBinderType == null)\n            {\n                throw new ArgumentNullException(\"modelBinderType\");\n            }\n\n            ValidateParameters(modelType, modelBinderType);\n            bool modelBinderTypeIsOpenGeneric = modelBinderType.IsGenericTypeDefinition;\n\n            _modelType = modelType;\n            _modelBinderFactory = typeArguments =>\n            {\n                Type closedModelBinderType = (modelBinderTypeIsOpenGeneric) ? modelBinderType.MakeGenericType(typeArguments) : modelBinderType;\n                try\n                {\n                    return (IExtensibleModelBinder)Activator.CreateInstance(closedModelBinderType);\n                }\n                catch (MissingMethodException exception)\n                {\n                    // Ensure thrown exception contains the type name.  Might be down a few levels.\n                    MissingMethodException replacementException =\n                        ModelBinderUtil.EnsureDebuggableException(exception, closedModelBinderType.FullName);\n                    if (replacementException != null)\n                    {\n                        throw replacementException;\n                    }\n\n                    throw;\n                }\n            };\n        }\n\n        public GenericModelBinderProvider(Type modelType, Func<Type[], IExtensibleModelBinder> modelBinderFactory)\n        {\n            if (modelType == null)\n            {\n                throw new ArgumentNullException(\"modelType\");\n            }\n            if (modelBinderFactory == null)\n            {\n                throw new ArgumentNullException(\"modelBinderFactory\");\n            }\n\n            ValidateParameters(modelType, null /* modelBinderType */);\n\n            _modelType = modelType;\n            _modelBinderFactory = modelBinderFactory;\n        }\n\n        public Type ModelType\n        {\n            get { return _modelType; }\n        }\n\n        public bool SuppressPrefixCheck { get; set; }\n\n        public override IExtensibleModelBinder GetBinder(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n        {\n            ModelBinderUtil.ValidateBindingContext(bindingContext);\n\n            Type[] typeArguments = null;\n            if (ModelType.IsInterface)\n            {\n                Type matchingClosedInterface = TypeHelpers.ExtractGenericInterface(bindingContext.ModelType, ModelType);\n                if (matchingClosedInterface != null)\n                {\n                    typeArguments = matchingClosedInterface.GetGenericArguments();\n                }\n            }\n            else\n            {\n                typeArguments = TypeHelpers.GetTypeArgumentsIfMatch(bindingContext.ModelType, ModelType);\n            }\n\n            if (typeArguments != null)\n            {\n                if (SuppressPrefixCheck || bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName))\n                {\n                    return _modelBinderFactory(typeArguments);\n                }\n            }\n\n            return null;\n        }\n\n        private static void ValidateParameters(Type modelType, Type modelBinderType)\n        {\n            if (!modelType.IsGenericTypeDefinition)\n            {\n                throw Error.GenericModelBinderProvider_ParameterMustSpecifyOpenGenericType(modelType, \"modelType\");\n            }\n            if (modelBinderType != null)\n            {\n                if (!typeof(IExtensibleModelBinder).IsAssignableFrom(modelBinderType))\n                {\n                    throw Error.Common_TypeMustImplementInterface(modelBinderType, typeof(IExtensibleModelBinder), \"modelBinderType\");\n                }\n                if (modelBinderType.IsGenericTypeDefinition)\n                {\n                    if (modelType.GetGenericArguments().Length != modelBinderType.GetGenericArguments().Length)\n                    {\n                        throw Error.GenericModelBinderProvider_TypeArgumentCountMismatch(modelType, modelBinderType);\n                    }\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/IExtensibleModelBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    public interface IExtensibleModelBinder\n    {\n        bool BindModel(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext);\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/KeyValuePairModelBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    public sealed class KeyValuePairModelBinder<TKey, TValue> : IExtensibleModelBinder\n    {\n        private ModelMetadataProvider _metadataProvider;\n\n        internal ModelMetadataProvider MetadataProvider\n        {\n            get\n            {\n                if (_metadataProvider == null)\n                {\n                    _metadataProvider = ModelMetadataProviders.Current;\n                }\n                return _metadataProvider;\n            }\n            set { _metadataProvider = value; }\n        }\n\n        public bool BindModel(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n        {\n            ModelBinderUtil.ValidateBindingContext(bindingContext, typeof(KeyValuePair<TKey, TValue>), true /* allowNullModel */);\n\n            TKey key;\n            bool keyBindingSucceeded = KeyValuePairModelBinderUtil.TryBindStrongModel(controllerContext, bindingContext, \"key\", MetadataProvider, out key);\n\n            TValue value;\n            bool valueBindingSucceeded = KeyValuePairModelBinderUtil.TryBindStrongModel(controllerContext, bindingContext, \"value\", MetadataProvider, out value);\n\n            if (keyBindingSucceeded && valueBindingSucceeded)\n            {\n                bindingContext.Model = new KeyValuePair<TKey, TValue>(key, value);\n            }\n            return keyBindingSucceeded || valueBindingSucceeded;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/KeyValuePairModelBinderProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    public sealed class KeyValuePairModelBinderProvider : ModelBinderProvider\n    {\n        public override IExtensibleModelBinder GetBinder(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n        {\n            ModelBinderUtil.ValidateBindingContext(bindingContext);\n\n            string keyFieldName = ModelBinderUtil.CreatePropertyModelName(bindingContext.ModelName, \"key\");\n            string valueFieldName = ModelBinderUtil.CreatePropertyModelName(bindingContext.ModelName, \"value\");\n\n            if (bindingContext.ValueProvider.ContainsPrefix(keyFieldName) && bindingContext.ValueProvider.ContainsPrefix(valueFieldName))\n            {\n                return ModelBinderUtil.GetPossibleBinderInstance(bindingContext.ModelType, typeof(KeyValuePair<,>) /* supported model type */, typeof(KeyValuePairModelBinder<,>) /* binder type */);\n            }\n            else\n            {\n                // 'key' or 'value' missing\n                return null;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/KeyValuePairModelBinderUtil.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    internal static class KeyValuePairModelBinderUtil\n    {\n        public static bool TryBindStrongModel<TModel>(ControllerContext controllerContext, ExtensibleModelBindingContext parentBindingContext, string propertyName, ModelMetadataProvider metadataProvider, out TModel model)\n        {\n            ExtensibleModelBindingContext propertyBindingContext = new ExtensibleModelBindingContext(parentBindingContext)\n            {\n                ModelMetadata = metadataProvider.GetMetadataForType(null, typeof(TModel)),\n                ModelName = ModelBinderUtil.CreatePropertyModelName(parentBindingContext.ModelName, propertyName)\n            };\n\n            IExtensibleModelBinder binder = parentBindingContext.ModelBinderProviders.GetBinder(controllerContext, propertyBindingContext);\n            if (binder != null)\n            {\n                if (binder.BindModel(controllerContext, propertyBindingContext))\n                {\n                    object untypedModel = propertyBindingContext.Model;\n                    model = ModelBinderUtil.CastOrDefault<TModel>(untypedModel);\n                    parentBindingContext.ValidationNode.ChildNodes.Add(propertyBindingContext.ValidationNode);\n                    return true;\n                }\n            }\n\n            model = default(TModel);\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/ModelBinderConfig.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Globalization;\nusing System.Web.Mvc;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    // Provides configuration settings common to the new model binding system.\n    public static class ModelBinderConfig\n    {\n        private static ModelBinderErrorMessageProvider _typeConversionErrorMessageProvider;\n        private static ModelBinderErrorMessageProvider _valueRequiredErrorMessageProvider;\n\n        public static ModelBinderErrorMessageProvider TypeConversionErrorMessageProvider\n        {\n            get\n            {\n                if (_typeConversionErrorMessageProvider == null)\n                {\n                    _typeConversionErrorMessageProvider = DefaultTypeConversionErrorMessageProvider;\n                }\n                return _typeConversionErrorMessageProvider;\n            }\n            set { _typeConversionErrorMessageProvider = value; }\n        }\n\n        public static ModelBinderErrorMessageProvider ValueRequiredErrorMessageProvider\n        {\n            get\n            {\n                if (_valueRequiredErrorMessageProvider == null)\n                {\n                    _valueRequiredErrorMessageProvider = DefaultValueRequiredErrorMessageProvider;\n                }\n                return _valueRequiredErrorMessageProvider;\n            }\n            set { _valueRequiredErrorMessageProvider = value; }\n        }\n\n        private static string DefaultTypeConversionErrorMessageProvider(ControllerContext controllerContext, ModelMetadata modelMetadata, object incomingValue)\n        {\n            return GetResourceCommon(controllerContext, modelMetadata, incomingValue, GetValueInvalidResource);\n        }\n\n        private static string DefaultValueRequiredErrorMessageProvider(ControllerContext controllerContext, ModelMetadata modelMetadata, object incomingValue)\n        {\n            return GetResourceCommon(controllerContext, modelMetadata, incomingValue, GetValueRequiredResource);\n        }\n\n        private static string GetResourceCommon(ControllerContext controllerContext, ModelMetadata modelMetadata, object incomingValue, Func<ControllerContext, string> resourceAccessor)\n        {\n            string displayName = modelMetadata.GetDisplayName();\n            string errorMessageTemplate = resourceAccessor(controllerContext);\n            string errorMessage = String.Format(CultureInfo.CurrentCulture, errorMessageTemplate, incomingValue, displayName);\n            return errorMessage;\n        }\n\n        private static string GetUserResourceString(ControllerContext controllerContext, string resourceName)\n        {\n            return GetUserResourceString(controllerContext, resourceName, DefaultModelBinder.ResourceClassKey);\n        }\n\n        // If the user specified a ResourceClassKey try to load the resource they specified.\n        // If the class key is invalid, an exception will be thrown.\n        // If the class key is valid but the resource is not found, it returns null, in which\n        // case it will fall back to the MVC default error message.\n        internal static string GetUserResourceString(ControllerContext controllerContext, string resourceName, string resourceClassKey)\n        {\n            return (!String.IsNullOrEmpty(resourceClassKey) && (controllerContext != null) && (controllerContext.HttpContext != null))\n                       ? controllerContext.HttpContext.GetGlobalResourceObject(resourceClassKey, resourceName, CultureInfo.CurrentUICulture) as string\n                       : null;\n        }\n\n        private static string GetValueInvalidResource(ControllerContext controllerContext)\n        {\n            return GetUserResourceString(controllerContext, \"PropertyValueInvalid\") ?? MvcResources.ModelBinderConfig_ValueInvalid;\n        }\n\n        private static string GetValueRequiredResource(ControllerContext controllerContext)\n        {\n            return GetUserResourceString(controllerContext, \"PropertyValueRequired\") ?? MvcResources.ModelBinderConfig_ValueRequired;\n        }\n\n        /*\n         * Initialization routines which replace the default binder implementation with the new binder implementation.\n         */\n\n        public static void Initialize()\n        {\n            Initialize(ModelBinders.Binders, ModelBinderProviders.Providers);\n        }\n\n        internal static void Initialize(ModelBinderDictionary binders, ModelBinderProviderCollection providers)\n        {\n            binders.Clear();\n            binders.DefaultBinder = new ExtensibleModelBinderAdapter(providers);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/ModelBinderErrorMessageProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    public delegate string ModelBinderErrorMessageProvider(ControllerContext controllerContext, ModelMetadata modelMetadata, object incomingValue);\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/ModelBinderProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    public abstract class ModelBinderProvider\n    {\n        public abstract IExtensibleModelBinder GetBinder(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext);\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/ModelBinderProviderCollection.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Globalization;\nusing System.Linq;\nusing System.Web.Mvc;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    public sealed class ModelBinderProviderCollection : Collection<ModelBinderProvider>\n    {\n        public ModelBinderProviderCollection()\n        {\n        }\n\n        public ModelBinderProviderCollection(IList<ModelBinderProvider> list)\n            : base(list)\n        {\n        }\n\n        private static void EnsureNoBindAttribute(Type modelType)\n        {\n            if (TypeDescriptorHelper.Get(modelType).GetAttributes().OfType<BindAttribute>().Any())\n            {\n                string errorMessage = String.Format(CultureInfo.CurrentCulture, MvcResources.ModelBinderProviderCollection_TypeCannotHaveBindAttribute,\n                                                    modelType);\n                throw new InvalidOperationException(errorMessage);\n            }\n        }\n\n        public IExtensibleModelBinder GetBinder(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n            if (bindingContext == null)\n            {\n                throw new ArgumentNullException(\"bindingContext\");\n            }\n\n            EnsureNoBindAttribute(bindingContext.ModelType);\n\n            ModelBinderProvider providerFromAttr;\n            if (TryGetProviderFromAttributes(bindingContext.ModelType, out providerFromAttr))\n            {\n                return providerFromAttr.GetBinder(controllerContext, bindingContext);\n            }\n\n            return (from provider in this\n                    let binder = provider.GetBinder(controllerContext, bindingContext)\n                    where binder != null\n                    select binder).FirstOrDefault();\n        }\n\n        internal IExtensibleModelBinder GetRequiredBinder(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n        {\n            IExtensibleModelBinder binder = GetBinder(controllerContext, bindingContext);\n            if (binder == null)\n            {\n                throw Error.ModelBinderProviderCollection_BinderForTypeNotFound(bindingContext.ModelType);\n            }\n            return binder;\n        }\n\n        protected override void InsertItem(int index, ModelBinderProvider item)\n        {\n            if (item == null)\n            {\n                throw new ArgumentNullException(\"item\");\n            }\n\n            base.InsertItem(index, item);\n        }\n\n        private void InsertSimpleProviderAtFront(ModelBinderProvider provider)\n        {\n            // Don't want to insert simple providers before any that are marked as \"should go first,\"\n            // as that might throw off other providers like the exact type match provider.\n\n            int i = 0;\n            for (; i < Count; i++)\n            {\n                if (!ShouldProviderGoFirst(this[i]))\n                {\n                    break;\n                }\n            }\n\n            base.InsertItem(i, provider);\n        }\n\n        public void RegisterBinderForGenericType(Type modelType, IExtensibleModelBinder modelBinder)\n        {\n            InsertSimpleProviderAtFront(new GenericModelBinderProvider(modelType, modelBinder));\n        }\n\n        public void RegisterBinderForGenericType(Type modelType, Func<Type[], IExtensibleModelBinder> modelBinderFactory)\n        {\n            InsertSimpleProviderAtFront(new GenericModelBinderProvider(modelType, modelBinderFactory));\n        }\n\n        public void RegisterBinderForGenericType(Type modelType, Type modelBinderType)\n        {\n            InsertSimpleProviderAtFront(new GenericModelBinderProvider(modelType, modelBinderType));\n        }\n\n        public void RegisterBinderForType(Type modelType, IExtensibleModelBinder modelBinder)\n        {\n            RegisterBinderForType(modelType, modelBinder, false /* suppressPrefixCheck */);\n        }\n\n        internal void RegisterBinderForType(Type modelType, IExtensibleModelBinder modelBinder, bool suppressPrefixCheck)\n        {\n            SimpleModelBinderProvider provider = new SimpleModelBinderProvider(modelType, modelBinder)\n            {\n                SuppressPrefixCheck = suppressPrefixCheck\n            };\n            InsertSimpleProviderAtFront(provider);\n        }\n\n        public void RegisterBinderForType(Type modelType, Func<IExtensibleModelBinder> modelBinderFactory)\n        {\n            InsertSimpleProviderAtFront(new SimpleModelBinderProvider(modelType, modelBinderFactory));\n        }\n\n        protected override void SetItem(int index, ModelBinderProvider item)\n        {\n            if (item == null)\n            {\n                throw new ArgumentNullException(\"item\");\n            }\n\n            base.SetItem(index, item);\n        }\n\n        private static bool ShouldProviderGoFirst(ModelBinderProvider provider)\n        {\n            ModelBinderProviderOptionsAttribute options = provider.GetType()\n                .GetCustomAttributes(typeof(ModelBinderProviderOptionsAttribute), true /* inherit */)\n                .OfType<ModelBinderProviderOptionsAttribute>()\n                .FirstOrDefault();\n\n            return (options != null) ? options.FrontOfList : false;\n        }\n\n        private static bool TryGetProviderFromAttributes(Type modelType, out ModelBinderProvider provider)\n        {\n            ExtensibleModelBinderAttribute attr = TypeDescriptorHelper.Get(modelType).GetAttributes().OfType<ExtensibleModelBinderAttribute>().FirstOrDefault();\n            if (attr == null)\n            {\n                provider = null;\n                return false;\n            }\n\n            if (typeof(ModelBinderProvider).IsAssignableFrom(attr.BinderType))\n            {\n                provider = (ModelBinderProvider)CreateInstance(attr.BinderType);\n            }\n            else if (typeof(IExtensibleModelBinder).IsAssignableFrom(attr.BinderType))\n            {\n                Type closedBinderType = (attr.BinderType.IsGenericTypeDefinition) ? attr.BinderType.MakeGenericType(modelType.GetGenericArguments()) : attr.BinderType;\n                IExtensibleModelBinder binderInstance = (IExtensibleModelBinder)CreateInstance(closedBinderType);\n                provider = new SimpleModelBinderProvider(modelType, binderInstance) { SuppressPrefixCheck = attr.SuppressPrefixCheck };\n            }\n            else\n            {\n                string errorMessage = String.Format(CultureInfo.CurrentCulture, MvcResources.ModelBinderProviderCollection_InvalidBinderType,\n                                                    attr.BinderType, typeof(ModelBinderProvider), typeof(IExtensibleModelBinder));\n                throw new InvalidOperationException(errorMessage);\n            }\n\n            return true;\n        }\n\n        private static object CreateInstance(Type type)\n        {\n            try\n            {\n                return Activator.CreateInstance(type);\n            }\n            catch (MissingMethodException exception)\n            {\n                // Ensure thrown exception contains the type name.  Might be down a few levels.\n                MissingMethodException replacementException =\n                    ModelBinderUtil.EnsureDebuggableException(exception, type.FullName);\n                if (replacementException != null)\n                {\n                    throw replacementException;\n                }\n\n                throw;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/ModelBinderProviderOptionsAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]\n    public sealed class ModelBinderProviderOptionsAttribute : Attribute\n    {\n        // Specifies that a provider should appear at the front of the list, e.g. other providers should\n        // not be auto-registered at the front unless explicitly requested.\n        public bool FrontOfList { get; set; }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/ModelBinderProviders.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    public static class ModelBinderProviders\n    {\n        private static readonly ModelBinderProviderCollection _providers = CreateDefaultCollection();\n\n        public static ModelBinderProviderCollection Providers\n        {\n            get { return _providers; }\n        }\n\n        private static ModelBinderProviderCollection CreateDefaultCollection()\n        {\n            return new ModelBinderProviderCollection\n            {\n                new TypeMatchModelBinderProvider(),\n                new BinaryDataModelBinderProvider(),\n                new KeyValuePairModelBinderProvider(),\n                new ComplexModelDtoModelBinderProvider(),\n                new ArrayModelBinderProvider(),\n                new DictionaryModelBinderProvider(),\n                new CollectionModelBinderProvider(),\n                new TypeConverterModelBinderProvider(),\n                new MutableObjectModelBinderProvider()\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/ModelBinderUtil.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections;\nusing System.Globalization;\nusing System.Linq;\nusing System.Web.Mvc;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    internal static class ModelBinderUtil\n    {\n        public static TModel CastOrDefault<TModel>(object model)\n        {\n            return (model is TModel) ? (TModel)model : default(TModel);\n        }\n\n        public static string CreateIndexModelName(string parentName, int index)\n        {\n            return CreateIndexModelName(parentName, index.ToString(CultureInfo.InvariantCulture));\n        }\n\n        public static string CreateIndexModelName(string parentName, string index)\n        {\n            return (parentName.Length == 0) ? \"[\" + index + \"]\" : parentName + \"[\" + index + \"]\";\n        }\n\n        public static string CreatePropertyModelName(string prefix, string propertyName)\n        {\n            if (String.IsNullOrEmpty(prefix))\n            {\n                return propertyName ?? String.Empty;\n            }\n            else if (String.IsNullOrEmpty(propertyName))\n            {\n                return prefix ?? String.Empty;\n            }\n            else\n            {\n                return prefix + \".\" + propertyName;\n            }\n        }\n\n        public static IExtensibleModelBinder GetPossibleBinderInstance(Type closedModelType, Type openModelType, Type openBinderType)\n        {\n            Type[] typeArguments = TypeHelpers.GetTypeArgumentsIfMatch(closedModelType, openModelType);\n            return (typeArguments != null) ? (IExtensibleModelBinder)Activator.CreateInstance(openBinderType.MakeGenericType(typeArguments)) : null;\n        }\n\n        public static object[] RawValueToObjectArray(object rawValue)\n        {\n            // precondition: rawValue is not null\n\n            // Need to special-case String so it's not caught by the IEnumerable check which follows\n            if (rawValue is string)\n            {\n                return new[] { rawValue };\n            }\n\n            object[] rawValueAsObjectArray = rawValue as object[];\n            if (rawValueAsObjectArray != null)\n            {\n                return rawValueAsObjectArray;\n            }\n\n            IEnumerable rawValueAsEnumerable = rawValue as IEnumerable;\n            if (rawValueAsEnumerable != null)\n            {\n                return rawValueAsEnumerable.Cast<object>().ToArray();\n            }\n\n            // fallback\n            return new[] { rawValue };\n        }\n\n        public static void ReplaceEmptyStringWithNull(ModelMetadata modelMetadata, ref object model)\n        {\n            if (modelMetadata.ConvertEmptyStringToNull && StringIsEmptyOrWhitespace(model as string))\n            {\n                model = null;\n            }\n        }\n\n        /// <summary>\n        /// Provide a new <see cref=\"MissingMethodException\"/> if original Message does not contain given full Type name.\n        /// </summary>\n        /// <param name=\"originalException\"><see cref=\"MissingMethodException\"/> to check.</param>\n        /// <param name=\"fullTypeName\">Full Type name which Message should contain.</param>\n        /// <returns>New <see cref=\"MissingMethodException\"/> if an update is required; null otherwise.</returns>\n        public static MissingMethodException EnsureDebuggableException(\n            MissingMethodException originalException,\n            string fullTypeName)\n        {\n            MissingMethodException replacementException = null;\n            if (!originalException.Message.Contains(fullTypeName))\n            {\n                string message = String.Format(\n                    CultureInfo.CurrentCulture,\n                    MvcResources.ModelBinderUtil_CannotCreateInstance,\n                    originalException.Message,\n                    fullTypeName);\n                replacementException = new MissingMethodException(message, originalException);\n            }\n\n            return replacementException;\n        }\n\n        // Based on String.IsNullOrWhitespace\n        private static bool StringIsEmptyOrWhitespace(string s)\n        {\n            if (s == null)\n            {\n                return false;\n            }\n\n            if (s.Length != 0)\n            {\n                for (int i = 0; i < s.Length; i++)\n                {\n                    if (!Char.IsWhiteSpace(s[i]))\n                    {\n                        return false;\n                    }\n                }\n            }\n            return true;\n        }\n\n        public static void ValidateBindingContext(ExtensibleModelBindingContext bindingContext)\n        {\n            if (bindingContext == null)\n            {\n                throw new ArgumentNullException(\"bindingContext\");\n            }\n\n            if (bindingContext.ModelMetadata == null)\n            {\n                throw Error.ModelBinderUtil_ModelMetadataCannotBeNull();\n            }\n        }\n\n        public static void ValidateBindingContext(ExtensibleModelBindingContext bindingContext, Type requiredType, bool allowNullModel)\n        {\n            ValidateBindingContext(bindingContext);\n\n            if (bindingContext.ModelType != requiredType)\n            {\n                throw Error.ModelBinderUtil_ModelTypeIsWrong(bindingContext.ModelType, requiredType);\n            }\n\n            if (!allowNullModel && bindingContext.Model == null)\n            {\n                throw Error.ModelBinderUtil_ModelCannotBeNull(requiredType);\n            }\n\n            if (bindingContext.Model != null && !requiredType.IsInstanceOfType(bindingContext.Model))\n            {\n                throw Error.ModelBinderUtil_ModelInstanceIsWrong(bindingContext.Model.GetType(), requiredType);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/ModelValidatedEventArgs.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    public sealed class ModelValidatedEventArgs : EventArgs\n    {\n        public ModelValidatedEventArgs(ControllerContext controllerContext, ModelValidationNode parentNode)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n\n            ControllerContext = controllerContext;\n            ParentNode = parentNode;\n        }\n\n        public ControllerContext ControllerContext { get; private set; }\n\n        public ModelValidationNode ParentNode { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/ModelValidatingEventArgs.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.ComponentModel;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    public sealed class ModelValidatingEventArgs : CancelEventArgs\n    {\n        public ModelValidatingEventArgs(ControllerContext controllerContext, ModelValidationNode parentNode)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n\n            ControllerContext = controllerContext;\n            ParentNode = parentNode;\n        }\n\n        public ControllerContext ControllerContext { get; private set; }\n\n        public ModelValidationNode ParentNode { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/ModelValidationNode.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    public sealed class ModelValidationNode\n    {\n        public ModelValidationNode(ModelMetadata modelMetadata, string modelStateKey)\n            : this(modelMetadata, modelStateKey, null)\n        {\n        }\n\n        public ModelValidationNode(ModelMetadata modelMetadata, string modelStateKey, IEnumerable<ModelValidationNode> childNodes)\n        {\n            if (modelMetadata == null)\n            {\n                throw new ArgumentNullException(\"modelMetadata\");\n            }\n            if (modelStateKey == null)\n            {\n                throw new ArgumentNullException(\"modelStateKey\");\n            }\n\n            ModelMetadata = modelMetadata;\n            ModelStateKey = modelStateKey;\n            ChildNodes = (childNodes != null) ? childNodes.ToList() : new List<ModelValidationNode>();\n        }\n\n        public event EventHandler<ModelValidatedEventArgs> Validated;\n\n        public event EventHandler<ModelValidatingEventArgs> Validating;\n\n        public ICollection<ModelValidationNode> ChildNodes { get; private set; }\n\n        public ModelMetadata ModelMetadata { get; private set; }\n\n        public string ModelStateKey { get; private set; }\n\n        public bool ValidateAllProperties { get; set; }\n\n        public bool SuppressValidation { get; set; }\n\n        public void CombineWith(ModelValidationNode otherNode)\n        {\n            if (otherNode != null && !otherNode.SuppressValidation)\n            {\n                Validated += otherNode.Validated;\n                Validating += otherNode.Validating;\n                foreach (ModelValidationNode childNode in otherNode.ChildNodes)\n                {\n                    ChildNodes.Add(childNode);\n                }\n            }\n        }\n\n        private void OnValidated(ModelValidatedEventArgs e)\n        {\n            EventHandler<ModelValidatedEventArgs> handler = Validated;\n            if (handler != null)\n            {\n                handler(this, e);\n            }\n        }\n\n        private void OnValidating(ModelValidatingEventArgs e)\n        {\n            EventHandler<ModelValidatingEventArgs> handler = Validating;\n            if (handler != null)\n            {\n                handler(this, e);\n            }\n        }\n\n        private object TryConvertContainerToMetadataType(ModelValidationNode parentNode)\n        {\n            if (parentNode != null)\n            {\n                object containerInstance = parentNode.ModelMetadata.Model;\n                if (containerInstance != null)\n                {\n                    Type expectedContainerType = ModelMetadata.ContainerType;\n                    if (expectedContainerType != null)\n                    {\n                        if (expectedContainerType.IsInstanceOfType(containerInstance))\n                        {\n                            return containerInstance;\n                        }\n                    }\n                }\n            }\n\n            return null;\n        }\n\n        public void Validate(ControllerContext controllerContext)\n        {\n            Validate(controllerContext, null /* parentNode */);\n        }\n\n        public void Validate(ControllerContext controllerContext, ModelValidationNode parentNode)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n\n            if (SuppressValidation)\n            {\n                // no-op\n                return;\n            }\n\n            // pre-validation steps\n            ModelValidatingEventArgs validatingEventArgs = new ModelValidatingEventArgs(controllerContext, parentNode);\n            OnValidating(validatingEventArgs);\n            if (validatingEventArgs.Cancel)\n            {\n                return;\n            }\n\n            ValidateChildren(controllerContext);\n            ValidateThis(controllerContext, parentNode);\n\n            // post-validation steps\n            ModelValidatedEventArgs validatedEventArgs = new ModelValidatedEventArgs(controllerContext, parentNode);\n            OnValidated(validatedEventArgs);\n        }\n\n        private void ValidateChildren(ControllerContext controllerContext)\n        {\n            foreach (ModelValidationNode child in ChildNodes)\n            {\n                child.Validate(controllerContext, this);\n            }\n\n            if (ValidateAllProperties)\n            {\n                ValidateProperties(controllerContext);\n            }\n        }\n\n        private void ValidateProperties(ControllerContext controllerContext)\n        {\n            // Based off CompositeModelValidator.\n            ModelStateDictionary modelState = controllerContext.Controller.ViewData.ModelState;\n\n            // DevDiv Bugs #227802 - Caching problem in ModelMetadata requires us to manually regenerate\n            // the ModelMetadata.\n            object model = ModelMetadata.Model;\n            ModelMetadata updatedMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, ModelMetadata.ModelType);\n\n            foreach (ModelMetadata propertyMetadata in updatedMetadata.Properties)\n            {\n                // Only want to add errors to ModelState if something doesn't already exist for the property node,\n                // else we could end up with duplicate or irrelevant error messages.\n                string propertyKeyRoot = ModelBinderUtil.CreatePropertyModelName(ModelStateKey, propertyMetadata.PropertyName);\n\n                if (modelState.IsValidField(propertyKeyRoot))\n                {\n                    foreach (ModelValidator propertyValidator in propertyMetadata.GetValidators(controllerContext))\n                    {\n                        foreach (ModelValidationResult propertyResult in propertyValidator.Validate(model))\n                        {\n                            string thisErrorKey = ModelBinderUtil.CreatePropertyModelName(propertyKeyRoot, propertyResult.MemberName);\n                            modelState.AddModelError(thisErrorKey, propertyResult.Message);\n                        }\n                    }\n                }\n            }\n        }\n\n        private void ValidateThis(ControllerContext controllerContext, ModelValidationNode parentNode)\n        {\n            ModelStateDictionary modelState = controllerContext.Controller.ViewData.ModelState;\n            if (!modelState.IsValidField(ModelStateKey))\n            {\n                return; // short-circuit\n            }\n\n            object container = TryConvertContainerToMetadataType(parentNode);\n            foreach (ModelValidator validator in ModelMetadata.GetValidators(controllerContext))\n            {\n                foreach (ModelValidationResult validationResult in validator.Validate(container))\n                {\n                    string trueModelStateKey = ModelBinderUtil.CreatePropertyModelName(ModelStateKey, validationResult.MemberName);\n                    modelState.AddModelError(trueModelStateKey, validationResult.Message);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/MutableObjectModelBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    public class MutableObjectModelBinder : IExtensibleModelBinder\n    {\n        private ModelMetadataProvider _metadataProvider;\n\n        internal ModelMetadataProvider MetadataProvider\n        {\n            get\n            {\n                if (_metadataProvider == null)\n                {\n                    _metadataProvider = ModelMetadataProviders.Current;\n                }\n                return _metadataProvider;\n            }\n            set { _metadataProvider = value; }\n        }\n\n        public virtual bool BindModel(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n        {\n            ModelBinderUtil.ValidateBindingContext(bindingContext);\n\n            EnsureModel(controllerContext, bindingContext);\n            IEnumerable<ModelMetadata> propertyMetadatas = GetMetadataForProperties(controllerContext, bindingContext);\n            ComplexModelDto dto = CreateAndPopulateDto(controllerContext, bindingContext, propertyMetadatas);\n\n            // post-processing, e.g. property setters and hooking up validation\n            ProcessDto(controllerContext, bindingContext, dto);\n            bindingContext.ValidationNode.ValidateAllProperties = true; // complex models require full validation\n            return true;\n        }\n\n        protected virtual bool CanUpdateProperty(ModelMetadata propertyMetadata)\n        {\n            return CanUpdatePropertyInternal(propertyMetadata);\n        }\n\n        internal static bool CanUpdatePropertyInternal(ModelMetadata propertyMetadata)\n        {\n            return (!propertyMetadata.IsReadOnly || CanUpdateReadOnlyProperty(propertyMetadata.ModelType));\n        }\n\n        private static bool CanUpdateReadOnlyProperty(Type propertyType)\n        {\n            // Value types have copy-by-value semantics, which prevents us from updating\n            // properties that are marked readonly.\n            if (propertyType.IsValueType)\n            {\n                return false;\n            }\n\n            // Arrays are strange beasts since their contents are mutable but their sizes aren't.\n            // Therefore we shouldn't even try to update these. Further reading:\n            // http://blogs.msdn.com/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx\n            if (propertyType.IsArray)\n            {\n                return false;\n            }\n\n            // Special-case known immutable reference types\n            if (propertyType == typeof(string))\n            {\n                return false;\n            }\n\n            return true;\n        }\n\n        private ComplexModelDto CreateAndPopulateDto(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext, IEnumerable<ModelMetadata> propertyMetadatas)\n        {\n            // create a DTO and call into the DTO binder\n            ComplexModelDto originalDto = new ComplexModelDto(bindingContext.ModelMetadata, propertyMetadatas);\n            ExtensibleModelBindingContext dtoBindingContext = new ExtensibleModelBindingContext(bindingContext)\n            {\n                ModelMetadata = MetadataProvider.GetMetadataForType(() => originalDto, typeof(ComplexModelDto)),\n                ModelName = bindingContext.ModelName\n            };\n\n            IExtensibleModelBinder dtoBinder = bindingContext.ModelBinderProviders.GetRequiredBinder(controllerContext, dtoBindingContext);\n            dtoBinder.BindModel(controllerContext, dtoBindingContext);\n            return (ComplexModelDto)dtoBindingContext.Model;\n        }\n\n        protected virtual object CreateModel(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n        {\n            // If the Activator throws an exception, we want to propagate it back up the call stack, since the application\n            // developer should know that this was an invalid type to try to bind to.\n            try\n            {\n                return Activator.CreateInstance(bindingContext.ModelType);\n            }\n            catch (MissingMethodException exception)\n            {\n                // Ensure thrown exception contains the type name.  Might be down a few levels.\n                MissingMethodException replacementException =\n                    ModelBinderUtil.EnsureDebuggableException(exception, bindingContext.ModelType.FullName);\n                if (replacementException != null)\n                {\n                    throw replacementException;\n                }\n\n                throw;\n            }\n        }\n\n        // Called when the property setter null check failed, allows us to add our own error message to ModelState.\n        internal static EventHandler<ModelValidatedEventArgs> CreateNullCheckFailedHandler(ControllerContext controllerContext, ModelMetadata modelMetadata, object incomingValue)\n        {\n            return (sender, e) =>\n            {\n                ModelValidationNode validationNode = (ModelValidationNode)sender;\n                ModelStateDictionary modelState = e.ControllerContext.Controller.ViewData.ModelState;\n\n                if (modelState.IsValidField(validationNode.ModelStateKey))\n                {\n                    string errorMessage = ModelBinderConfig.ValueRequiredErrorMessageProvider(controllerContext, modelMetadata, incomingValue);\n                    if (errorMessage != null)\n                    {\n                        modelState.AddModelError(validationNode.ModelStateKey, errorMessage);\n                    }\n                }\n            };\n        }\n\n        protected virtual void EnsureModel(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n        {\n            if (bindingContext.Model == null)\n            {\n                bindingContext.ModelMetadata.Model = CreateModel(controllerContext, bindingContext);\n            }\n        }\n\n        protected virtual IEnumerable<ModelMetadata> GetMetadataForProperties(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n        {\n            // keep a set of the required properties so that we can cross-reference bound properties later\n            HashSet<string> requiredProperties;\n            HashSet<string> skipProperties;\n            GetRequiredPropertiesCollection(bindingContext.ModelType, out requiredProperties, out skipProperties);\n\n            return from propertyMetadata in bindingContext.ModelMetadata.Properties\n                   let propertyName = propertyMetadata.PropertyName\n                   let shouldUpdateProperty = requiredProperties.Contains(propertyName) || !skipProperties.Contains(propertyName)\n                   where shouldUpdateProperty && CanUpdateProperty(propertyMetadata)\n                   select propertyMetadata;\n        }\n\n        private static object GetPropertyDefaultValue(PropertyDescriptor propertyDescriptor)\n        {\n            DefaultValueAttribute attr = propertyDescriptor.Attributes.OfType<DefaultValueAttribute>().FirstOrDefault();\n            return (attr != null) ? attr.Value : null;\n        }\n\n        internal static void GetRequiredPropertiesCollection(Type modelType, out HashSet<string> requiredProperties, out HashSet<string> skipProperties)\n        {\n            requiredProperties = new HashSet<string>(StringComparer.OrdinalIgnoreCase);\n            skipProperties = new HashSet<string>(StringComparer.OrdinalIgnoreCase);\n\n            // Use attributes on the property before attributes on the type.\n            ICustomTypeDescriptor modelDescriptor = TypeDescriptorHelper.Get(modelType);\n            PropertyDescriptorCollection propertyDescriptors = modelDescriptor.GetProperties();\n            BindingBehaviorAttribute typeAttr = modelDescriptor.GetAttributes().OfType<BindingBehaviorAttribute>().SingleOrDefault();\n\n            foreach (PropertyDescriptor propertyDescriptor in propertyDescriptors)\n            {\n                BindingBehaviorAttribute propAttr = propertyDescriptor.Attributes.OfType<BindingBehaviorAttribute>().SingleOrDefault();\n                BindingBehaviorAttribute workingAttr = propAttr ?? typeAttr;\n                if (workingAttr != null)\n                {\n                    switch (workingAttr.Behavior)\n                    {\n                        case BindingBehavior.Required:\n                            requiredProperties.Add(propertyDescriptor.Name);\n                            break;\n\n                        case BindingBehavior.Never:\n                            skipProperties.Add(propertyDescriptor.Name);\n                            break;\n                    }\n                }\n            }\n        }\n\n        internal void ProcessDto(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext, ComplexModelDto dto)\n        {\n            HashSet<string> requiredProperties;\n            HashSet<string> skipProperties;\n            GetRequiredPropertiesCollection(bindingContext.ModelType, out requiredProperties, out skipProperties);\n\n            // Are all of the required fields accounted for?\n            HashSet<string> missingRequiredProperties = new HashSet<string>(requiredProperties);\n            missingRequiredProperties.ExceptWith(dto.Results.Select(r => r.Key.PropertyName));\n            string missingPropertyName = missingRequiredProperties.FirstOrDefault();\n            if (missingPropertyName != null)\n            {\n                string fullPropertyKey = ModelBinderUtil.CreatePropertyModelName(bindingContext.ModelName, missingPropertyName);\n                throw Error.BindingBehavior_ValueNotFound(fullPropertyKey);\n            }\n\n            // for each property that was bound, call the setter, recording exceptions as necessary\n            foreach (var entry in dto.Results)\n            {\n                ModelMetadata propertyMetadata = entry.Key;\n\n                ComplexModelDtoResult dtoResult = entry.Value;\n                if (dtoResult != null)\n                {\n                    SetProperty(controllerContext, bindingContext, propertyMetadata, dtoResult);\n                    bindingContext.ValidationNode.ChildNodes.Add(dtoResult.ValidationNode);\n                }\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We're recording this exception so that we can act on it later.\")]\n        protected virtual void SetProperty(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext, ModelMetadata propertyMetadata, ComplexModelDtoResult dtoResult)\n        {\n            PropertyDescriptor propertyDescriptor = TypeDescriptorHelper.Get(bindingContext.ModelType).GetProperties().Find(propertyMetadata.PropertyName, true /* ignoreCase */);\n            if (propertyDescriptor == null || propertyDescriptor.IsReadOnly)\n            {\n                return; // nothing to do\n            }\n\n            object value = dtoResult.Model ?? GetPropertyDefaultValue(propertyDescriptor);\n            propertyMetadata.Model = value;\n\n            // 'Required' validators need to run first so that we can provide useful error messages if\n            // the property setters throw, e.g. if we're setting entity keys to null. See comments in\n            // DefaultModelBinder.SetProperty() for more information.\n            if (value == null)\n            {\n                string modelStateKey = dtoResult.ValidationNode.ModelStateKey;\n                if (bindingContext.ModelState.IsValidField(modelStateKey))\n                {\n                    ModelValidator requiredValidator = ModelValidatorProviders.Providers.GetValidators(propertyMetadata, controllerContext).Where(v => v.IsRequired).FirstOrDefault();\n                    if (requiredValidator != null)\n                    {\n                        foreach (ModelValidationResult validationResult in requiredValidator.Validate(bindingContext.Model))\n                        {\n                            bindingContext.ModelState.AddModelError(modelStateKey, validationResult.Message);\n                        }\n                    }\n                }\n            }\n\n            if (value != null || TypeHelpers.TypeAllowsNullValue(propertyDescriptor.PropertyType))\n            {\n                try\n                {\n                    propertyDescriptor.SetValue(bindingContext.Model, value);\n                }\n                catch (Exception ex)\n                {\n                    // don't display a duplicate error message if a binding error has already occurred for this field\n                    string modelStateKey = dtoResult.ValidationNode.ModelStateKey;\n                    if (bindingContext.ModelState.IsValidField(modelStateKey))\n                    {\n                        bindingContext.ModelState.AddModelError(modelStateKey, ex);\n                    }\n                }\n            }\n            else\n            {\n                // trying to set a non-nullable value type to null, need to make sure there's a message\n                string modelStateKey = dtoResult.ValidationNode.ModelStateKey;\n                if (bindingContext.ModelState.IsValidField(modelStateKey))\n                {\n                    dtoResult.ValidationNode.Validated += CreateNullCheckFailedHandler(controllerContext, propertyMetadata, value);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/MutableObjectModelBinderProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    public sealed class MutableObjectModelBinderProvider : ModelBinderProvider\n    {\n        public override IExtensibleModelBinder GetBinder(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n        {\n            ModelBinderUtil.ValidateBindingContext(bindingContext);\n\n            if (!bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName))\n            {\n                // no values to bind\n                return null;\n            }\n\n            if (bindingContext.ModelType == typeof(ComplexModelDto))\n            {\n                // forbidden type - will cause a stack overflow if we try binding this type\n                return null;\n            }\n\n            return new MutableObjectModelBinder();\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/SimpleModelBinderProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    // Returns a user-specified binder for a given type.\n    public sealed class SimpleModelBinderProvider : ModelBinderProvider\n    {\n        private readonly Func<IExtensibleModelBinder> _modelBinderFactory;\n        private readonly Type _modelType;\n\n        public SimpleModelBinderProvider(Type modelType, IExtensibleModelBinder modelBinder)\n        {\n            if (modelType == null)\n            {\n                throw new ArgumentNullException(\"modelType\");\n            }\n            if (modelBinder == null)\n            {\n                throw new ArgumentNullException(\"modelBinder\");\n            }\n\n            _modelType = modelType;\n            _modelBinderFactory = () => modelBinder;\n        }\n\n        public SimpleModelBinderProvider(Type modelType, Func<IExtensibleModelBinder> modelBinderFactory)\n        {\n            if (modelType == null)\n            {\n                throw new ArgumentNullException(\"modelType\");\n            }\n            if (modelBinderFactory == null)\n            {\n                throw new ArgumentNullException(\"modelBinderFactory\");\n            }\n\n            _modelType = modelType;\n            _modelBinderFactory = modelBinderFactory;\n        }\n\n        public Type ModelType\n        {\n            get { return _modelType; }\n        }\n\n        public bool SuppressPrefixCheck { get; set; }\n\n        public override IExtensibleModelBinder GetBinder(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n        {\n            ModelBinderUtil.ValidateBindingContext(bindingContext);\n\n            if (bindingContext.ModelType == ModelType)\n            {\n                if (SuppressPrefixCheck || bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName))\n                {\n                    return _modelBinderFactory();\n                }\n            }\n\n            return null;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/TypeConverterModelBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    public sealed class TypeConverterModelBinder : IExtensibleModelBinder\n    {\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"The exception is recorded to be acted upon later.\")]\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1304:SpecifyCultureInfo\", MessageId = \"System.Web.Mvc.ValueProviderResult.ConvertTo(System.Type)\", Justification = \"The ValueProviderResult already has the necessary context to perform a culture-aware conversion.\")]\n        public bool BindModel(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n        {\n            ModelBinderUtil.ValidateBindingContext(bindingContext);\n\n            ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);\n            if (valueProviderResult == null)\n            {\n                return false; // no entry\n            }\n\n            object newModel;\n            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);\n            try\n            {\n                newModel = valueProviderResult.ConvertTo(bindingContext.ModelType);\n            }\n            catch (Exception ex)\n            {\n                if (IsFormatException(ex))\n                {\n                    // there was a type conversion failure\n                    string errorString = ModelBinderConfig.TypeConversionErrorMessageProvider(controllerContext, bindingContext.ModelMetadata, valueProviderResult.AttemptedValue);\n                    if (errorString != null)\n                    {\n                        bindingContext.ModelState.AddModelError(bindingContext.ModelName, errorString);\n                    }\n                }\n                else\n                {\n                    bindingContext.ModelState.AddModelError(bindingContext.ModelName, ex);\n                }\n                return false;\n            }\n\n            ModelBinderUtil.ReplaceEmptyStringWithNull(bindingContext.ModelMetadata, ref newModel);\n            bindingContext.Model = newModel;\n            return true;\n        }\n\n        private static bool IsFormatException(Exception ex)\n        {\n            for (; ex != null; ex = ex.InnerException)\n            {\n                if (ex is FormatException)\n                {\n                    return true;\n                }\n            }\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/TypeConverterModelBinderProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    // Returns a binder that can perform conversions using a .NET TypeConverter.\n    public sealed class TypeConverterModelBinderProvider : ModelBinderProvider\n    {\n        public override IExtensibleModelBinder GetBinder(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n        {\n            ModelBinderUtil.ValidateBindingContext(bindingContext);\n\n            ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);\n            if (valueProviderResult == null)\n            {\n                return null; // no value to convert\n            }\n\n            if (!TypeDescriptor.GetConverter(bindingContext.ModelType).CanConvertFrom(typeof(string)))\n            {\n                return null; // this type cannot be converted\n            }\n\n            return new TypeConverterModelBinder();\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/TypeMatchModelBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    public sealed class TypeMatchModelBinder : IExtensibleModelBinder\n    {\n        public bool BindModel(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n        {\n            ValueProviderResult valueProviderResult = GetCompatibleValueProviderResult(bindingContext);\n            if (valueProviderResult == null)\n            {\n                return false; // conversion would have failed\n            }\n\n            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);\n            object model = valueProviderResult.RawValue;\n            ModelBinderUtil.ReplaceEmptyStringWithNull(bindingContext.ModelMetadata, ref model);\n            bindingContext.Model = model;\n\n            return true;\n        }\n\n        internal static ValueProviderResult GetCompatibleValueProviderResult(ExtensibleModelBindingContext bindingContext)\n        {\n            ModelBinderUtil.ValidateBindingContext(bindingContext);\n\n            ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);\n            if (valueProviderResult == null)\n            {\n                return null; // the value doesn't exist\n            }\n\n            if (!TypeHelpers.IsCompatibleObject(bindingContext.ModelType, valueProviderResult.RawValue))\n            {\n                return null; // value is of incompatible type\n            }\n\n            return valueProviderResult;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelBinding/TypeMatchModelBinderProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.ModelBinding\n{\n    // Returns a binder that can extract a ValueProviderResult.RawValue and return it directly.\n    [ModelBinderProviderOptions(FrontOfList = true)]\n    public sealed class TypeMatchModelBinderProvider : ModelBinderProvider\n    {\n        public override IExtensibleModelBinder GetBinder(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n        {\n            return (TypeMatchModelBinder.GetCompatibleValueProviderResult(bindingContext) != null)\n                       ? new TypeMatchModelBinder()\n                       : null /* no match */;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ModelCopier.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\n\nnamespace Microsoft.Web.Mvc\n{\n    public static class ModelCopier\n    {\n        public static void CopyCollection<T>(IEnumerable<T> from, ICollection<T> to)\n        {\n            if (from == null || to == null || to.IsReadOnly)\n            {\n                return;\n            }\n\n            to.Clear();\n            foreach (T element in from)\n            {\n                to.Add(element);\n            }\n        }\n\n        public static void CopyModel(object from, object to)\n        {\n            if (from == null || to == null)\n            {\n                return;\n            }\n\n            PropertyDescriptorCollection fromProperties = TypeDescriptor.GetProperties(from);\n            PropertyDescriptorCollection toProperties = TypeDescriptor.GetProperties(to);\n\n            foreach (PropertyDescriptor fromProperty in fromProperties)\n            {\n                PropertyDescriptor toProperty = toProperties.Find(fromProperty.Name, true /* ignoreCase */);\n                if (toProperty != null && !toProperty.IsReadOnly)\n                {\n                    // Can from.Property reference just be assigned directly to to.Property reference?\n                    bool isDirectlyAssignable = toProperty.PropertyType.IsAssignableFrom(fromProperty.PropertyType);\n                    // Is from.Property just the nullable form of to.Property?\n                    bool liftedValueType = (isDirectlyAssignable) ? false : (Nullable.GetUnderlyingType(fromProperty.PropertyType) == toProperty.PropertyType);\n\n                    if (isDirectlyAssignable || liftedValueType)\n                    {\n                        object fromValue = fromProperty.GetValue(from);\n                        if (isDirectlyAssignable || (fromValue != null && liftedValueType))\n                        {\n                            toProperty.SetValue(to, fromValue);\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/MvcSerializer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.IO;\nusing System.Runtime.Serialization;\nusing System.Web.Security;\nusing System.Xml;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc\n{\n    public class MvcSerializer\n    {\n        private static readonly string[] _machineKeyPurposes = new string[] { \"Microsoft.Web.Mvc.MvcSerializer.v1\" };\n\n        private static SerializationException CreateSerializationException(Exception innerException)\n        {\n            return new SerializationException(MvcResources.MvcSerializer_DeserializationFailed, innerException);\n        }\n\n        public virtual object Deserialize(string serializedValue)\n        {\n            return Deserialize(serializedValue, MachineKeyWrapper.Instance);\n        }\n\n        internal static object Deserialize(string serializedValue, IMachineKey machineKey)\n        {\n            if (String.IsNullOrEmpty(serializedValue))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"serializedValue\");\n            }\n\n            try\n            {\n                // First, need to decrypt / verify data\n                byte[] rawBytes = machineKey.Unprotect(serializedValue, _machineKeyPurposes);\n\n                // Finally, deserialize the object graph\n                using (MemoryStream ms = new MemoryStream(rawBytes, 0, rawBytes.Length))\n                {\n                    return DeserializeGraph(ms);\n                }\n            }\n            catch (Exception ex)\n            {\n                throw CreateSerializationException(ex);\n            }\n        }\n\n        // Deserializes a stream to a graph using the NetDataContractSerializer (binary mode)\n        private static object DeserializeGraph(Stream rawBytes)\n        {\n            using (XmlDictionaryReader dr = XmlDictionaryReader.CreateBinaryReader(rawBytes, XmlDictionaryReaderQuotas.Max))\n            {\n                object deserialized = new NetDataContractSerializer().ReadObject(dr);\n                return deserialized;\n            }\n        }\n\n        public virtual string Serialize(object state)\n        {\n            return Serialize(state, MachineKeyWrapper.Instance);\n        }\n\n        internal static string Serialize(object state, IMachineKey machineKey)\n        {\n            try\n            {\n                // First, need to serialize the object graph\n                byte[] rawBytes;\n                using (MemoryStream ms = new MemoryStream())\n                {\n                    SerializeGraph(ms, state);\n                    rawBytes = ms.ToArray();\n                }\n\n                // Then, encrypt / sign data\n                return machineKey.Protect(rawBytes, _machineKeyPurposes);\n            }\n            catch (Exception ex)\n            {\n                throw CreateSerializationException(ex);\n            }\n        }\n\n        // Serializes a graph to a byte array using the NetDataContractSerializer (binary mode)\n        private static void SerializeGraph(Stream outputStream, object graph)\n        {\n            using (XmlDictionaryWriter dw = XmlDictionaryWriter.CreateBinaryWriter(outputStream, null, null, ownsStream: false))\n            {\n                new NetDataContractSerializer().WriteObject(dw, graph);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Properties/AssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\n[assembly: AssemblyTitle(\"Microsoft.Web.Mvc.dll\")]\n[assembly: AssemblyDescription(\"Microsoft.Web.Mvc.dll\")]\n[assembly: Guid(\"f3507a98-9429-404b-9e0e-1b426a5b3ad5\")]\n[assembly: InternalsVisibleTo(\"Microsoft.Web.Mvc.Test\")]\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Properties/MvcResources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.18051\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace Microsoft.Web.Mvc.Properties {\n    using System;\n    \n    \n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class MvcResources {\n        \n        private static global::System.Resources.ResourceManager resourceMan;\n        \n        private static global::System.Globalization.CultureInfo resourceCulture;\n        \n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal MvcResources() {\n        }\n        \n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"Microsoft.Web.Mvc.Properties.MvcResources\", typeof(MvcResources).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n        \n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The {0} field only accepts files with one of the following content types: {1}..\n        /// </summary>\n        internal static string AcceptAttribute_Invalid {\n            get {\n                return ResourceManager.GetString(\"AcceptAttribute_Invalid\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A value for &apos;{0}&apos; is required but was not present in the request..\n        /// </summary>\n        internal static string BindingBehavior_ValueNotFound {\n            get {\n                return ResourceManager.GetString(\"BindingBehavior_ValueNotFound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Value cannot be null or empty..\n        /// </summary>\n        internal static string Common_NullOrEmpty {\n            get {\n                return ResourceManager.GetString(\"Common_NullOrEmpty\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The type &apos;{0}&apos; does not implement the interface &apos;{1}&apos;..\n        /// </summary>\n        internal static string Common_TypeMustImplementInterface {\n            get {\n                return ResourceManager.GetString(\"Common_TypeMustImplementInterface\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &apos;Name&apos; property must be set..\n        /// </summary>\n        internal static string CommonControls_NameRequired {\n            get {\n                return ResourceManager.GetString(\"CommonControls_NameRequired\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The {0} field is not a valid credit card number..\n        /// </summary>\n        internal static string CreditCardAttribute_Invalid {\n            get {\n                return ResourceManager.GetString(\"CreditCardAttribute_Invalid\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Sample Item.\n        /// </summary>\n        internal static string DropDownList_SampleItem {\n            get {\n                return ResourceManager.GetString(\"DropDownList_SampleItem\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to DynamicViewDataDictionary only supports single indexers..\n        /// </summary>\n        internal static string DynamicViewDataDictionary_SingleIndexerOnly {\n            get {\n                return ResourceManager.GetString(\"DynamicViewDataDictionary_SingleIndexerOnly\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to DynamicViewDataDictionary only supports string-based indexers..\n        /// </summary>\n        internal static string DynamicViewDataDictionary_StringIndexerOnly {\n            get {\n                return ResourceManager.GetString(\"DynamicViewDataDictionary_StringIndexerOnly\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The property {0} doesn&apos;t exist. There are no public properties on this object..\n        /// </summary>\n        internal static string DynamicViewPage_NoProperties {\n            get {\n                return ResourceManager.GetString(\"DynamicViewPage_NoProperties\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The property {0} doesn&apos;t exist. Supported properties are: {1}..\n        /// </summary>\n        internal static string DynamicViewPage_PropertyDoesNotExist {\n            get {\n                return ResourceManager.GetString(\"DynamicViewPage_PropertyDoesNotExist\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The {0} field is not a valid e-mail address..\n        /// </summary>\n        internal static string EmailAddressAttribute_Invalid {\n            get {\n                return ResourceManager.GetString(\"EmailAddressAttribute_Invalid\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The method &apos;{0}&apos; is an asynchronous completion method and cannot be called directly..\n        /// </summary>\n        internal static string ExpressionHelper_CannotCallCompletedMethod {\n            get {\n                return ResourceManager.GetString(\"ExpressionHelper_CannotCallCompletedMethod\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The method &apos;{0}&apos; is marked [NonAction] and cannot be called directly..\n        /// </summary>\n        internal static string ExpressionHelper_CannotCallNonAction {\n            get {\n                return ResourceManager.GetString(\"ExpressionHelper_CannotCallNonAction\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Cannot route to class named &apos;Controller&apos;..\n        /// </summary>\n        internal static string ExpressionHelper_CannotRouteToController {\n            get {\n                return ResourceManager.GetString(\"ExpressionHelper_CannotRouteToController\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Expression must be a method call..\n        /// </summary>\n        internal static string ExpressionHelper_MustBeMethodCall {\n            get {\n                return ResourceManager.GetString(\"ExpressionHelper_MustBeMethodCall\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Controller name must end in &apos;Controller&apos;..\n        /// </summary>\n        internal static string ExpressionHelper_TargetMustEndInController {\n            get {\n                return ResourceManager.GetString(\"ExpressionHelper_TargetMustEndInController\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The new model binding system cannot be used when a property whitelist or blacklist has been specified in [Bind] or via the call to UpdateModel() / TryUpdateModel(). Use the [BindRequired] and [BindNever] attributes on the model type or its properties instead..\n        /// </summary>\n        internal static string ExtensibleModelBinderAdapter_PropertyFilterMustNotBeSet {\n            get {\n                return ResourceManager.GetString(\"ExtensibleModelBinderAdapter_PropertyFilterMustNotBeSet\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The {0} field only accepts files with the following extensions: {1}.\n        /// </summary>\n        internal static string FileExtensionsAttribute_Invalid {\n            get {\n                return ResourceManager.GetString(\"FileExtensionsAttribute_Invalid\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The type &apos;{0}&apos; is not an open generic type..\n        /// </summary>\n        internal static string GenericModelBinderProvider_ParameterMustSpecifyOpenGenericType {\n            get {\n                return ResourceManager.GetString(\"GenericModelBinderProvider_ParameterMustSpecifyOpenGenericType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The open model type &apos;{0}&apos; has {1} generic type argument(s), but the open binder type &apos;{2}&apos; has {3} generic type argument(s). The binder type must not be an open generic type or must have the same number of generic arguments as the open model type..\n        /// </summary>\n        internal static string GenericModelBinderProvider_TypeArgumentCountMismatch {\n            get {\n                return ResourceManager.GetString(\"GenericModelBinderProvider_TypeArgumentCountMismatch\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to There is no ViewData item with the key &apos;{0}&apos; of type &apos;{1}&apos;..\n        /// </summary>\n        internal static string HtmlHelper_MissingSelectData {\n            get {\n                return ResourceManager.GetString(\"HtmlHelper_MissingSelectData\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The ViewData item with the key &apos;{0}&apos; is of type &apos;{1}&apos; but needs to be of type &apos;{2}&apos;..\n        /// </summary>\n        internal static string HtmlHelper_WrongSelectDataType {\n            get {\n                return ResourceManager.GetString(\"HtmlHelper_WrongSelectDataType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The value &apos;{0}&apos; is not valid for {1}..\n        /// </summary>\n        internal static string ModelBinderConfig_ValueInvalid {\n            get {\n                return ResourceManager.GetString(\"ModelBinderConfig_ValueInvalid\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A value is required..\n        /// </summary>\n        internal static string ModelBinderConfig_ValueRequired {\n            get {\n                return ResourceManager.GetString(\"ModelBinderConfig_ValueRequired\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A binder for type {0} could not be located..\n        /// </summary>\n        internal static string ModelBinderProviderCollection_BinderForTypeNotFound {\n            get {\n                return ResourceManager.GetString(\"ModelBinderProviderCollection_BinderForTypeNotFound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The type &apos;{0}&apos; does not subclass {1} or implement the interface {2}..\n        /// </summary>\n        internal static string ModelBinderProviderCollection_InvalidBinderType {\n            get {\n                return ResourceManager.GetString(\"ModelBinderProviderCollection_InvalidBinderType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The model of type &apos;{0}&apos; has a [Bind] attribute. The new model binding system cannot be used with models that have type-level [Bind] attributes. Use the [BindRequired] and [BindNever] attributes on the model type or its properties instead..\n        /// </summary>\n        internal static string ModelBinderProviderCollection_TypeCannotHaveBindAttribute {\n            get {\n                return ResourceManager.GetString(\"ModelBinderProviderCollection_TypeCannotHaveBindAttribute\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to {0} Object type &apos;{1}&apos;..\n        /// </summary>\n        internal static string ModelBinderUtil_CannotCreateInstance {\n            get {\n                return ResourceManager.GetString(\"ModelBinderUtil_CannotCreateInstance\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The binding context has a null Model, but this binder requires a non-null model of type &apos;{0}&apos;..\n        /// </summary>\n        internal static string ModelBinderUtil_ModelCannotBeNull {\n            get {\n                return ResourceManager.GetString(\"ModelBinderUtil_ModelCannotBeNull\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The binding context has a Model of type &apos;{0}&apos;, but this binder can only operate on models of type &apos;{1}&apos;..\n        /// </summary>\n        internal static string ModelBinderUtil_ModelInstanceIsWrong {\n            get {\n                return ResourceManager.GetString(\"ModelBinderUtil_ModelInstanceIsWrong\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The binding context cannot have a null ModelMetadata..\n        /// </summary>\n        internal static string ModelBinderUtil_ModelMetadataCannotBeNull {\n            get {\n                return ResourceManager.GetString(\"ModelBinderUtil_ModelMetadataCannotBeNull\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The binding context has a ModelType of &apos;{0}&apos;, but this binder can only operate on models of type &apos;{1}&apos;..\n        /// </summary>\n        internal static string ModelBinderUtil_ModelTypeIsWrong {\n            get {\n                return ResourceManager.GetString(\"ModelBinderUtil_ModelTypeIsWrong\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The ModelMetadata property must be set before accessing this property..\n        /// </summary>\n        internal static string ModelBindingContext_ModelMetadataMustBeSet {\n            get {\n                return ResourceManager.GetString(\"ModelBindingContext_ModelMetadataMustBeSet\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Deserialization failed. Verify that the data is being deserialized using the same SerializationMode with which it was serialized. Otherwise see the inner exception..\n        /// </summary>\n        internal static string MvcSerializer_DeserializationFailed {\n            get {\n                return ResourceManager.GetString(\"MvcSerializer_DeserializationFailed\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Error dispatching on controller {0}, conflicting actions matched: {1}..\n        /// </summary>\n        internal static string ResourceControllerFactory_ConflictingActions {\n            get {\n                return ResourceManager.GetString(\"ResourceControllerFactory_ConflictingActions\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Error dispatching on controller {0}, no actions matched..\n        /// </summary>\n        internal static string ResourceControllerFactory_NoActions {\n            get {\n                return ResourceManager.GetString(\"ResourceControllerFactory_NoActions\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Format &apos;{0}&apos; is not supported..\n        /// </summary>\n        internal static string Resources_UnsupportedFormat {\n            get {\n                return ResourceManager.GetString(\"Resources_UnsupportedFormat\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Unsupported Media Type: &apos;{0}&apos;..\n        /// </summary>\n        internal static string Resources_UnsupportedMediaType {\n            get {\n                return ResourceManager.GetString(\"Resources_UnsupportedMediaType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The {0} field is not a valid fully-qualified http, https, or ftp URL..\n        /// </summary>\n        internal static string UrlAttribute_Invalid {\n            get {\n                return ResourceManager.GetString(\"UrlAttribute_Invalid\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Properties/MvcResources.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"Common_NullOrEmpty\" xml:space=\"preserve\">\n    <value>Value cannot be null or empty.</value>\n  </data>\n  <data name=\"ExpressionHelper_CannotRouteToController\" xml:space=\"preserve\">\n    <value>Cannot route to class named 'Controller'.</value>\n  </data>\n  <data name=\"ExpressionHelper_MustBeMethodCall\" xml:space=\"preserve\">\n    <value>Expression must be a method call.</value>\n  </data>\n  <data name=\"ExpressionHelper_TargetMustEndInController\" xml:space=\"preserve\">\n    <value>Controller name must end in 'Controller'.</value>\n  </data>\n  <data name=\"HtmlHelper_MissingSelectData\" xml:space=\"preserve\">\n    <value>There is no ViewData item with the key '{0}' of type '{1}'.</value>\n  </data>\n  <data name=\"HtmlHelper_WrongSelectDataType\" xml:space=\"preserve\">\n    <value>The ViewData item with the key '{0}' is of type '{1}' but needs to be of type '{2}'.</value>\n  </data>\n  <data name=\"CommonControls_NameRequired\" xml:space=\"preserve\">\n    <value>The 'Name' property must be set.</value>\n  </data>\n  <data name=\"MvcSerializer_DeserializationFailed\" xml:space=\"preserve\">\n    <value>Deserialization failed. Verify that the data is being deserialized using the same SerializationMode with which it was serialized. Otherwise see the inner exception.</value>\n  </data>\n  <data name=\"Resources_UnsupportedMediaType\" xml:space=\"preserve\">\n    <value>Unsupported Media Type: '{0}'.</value>\n  </data>\n  <data name=\"Resources_UnsupportedFormat\" xml:space=\"preserve\">\n    <value>Format '{0}' is not supported.</value>\n  </data>\n  <data name=\"ExpressionHelper_CannotCallCompletedMethod\" xml:space=\"preserve\">\n    <value>The method '{0}' is an asynchronous completion method and cannot be called directly.</value>\n  </data>\n  <data name=\"ExpressionHelper_CannotCallNonAction\" xml:space=\"preserve\">\n    <value>The method '{0}' is marked [NonAction] and cannot be called directly.</value>\n  </data>\n  <data name=\"ModelBinderUtil_ModelCannotBeNull\" xml:space=\"preserve\">\n    <value>The binding context has a null Model, but this binder requires a non-null model of type '{0}'.</value>\n  </data>\n  <data name=\"ModelBinderUtil_ModelInstanceIsWrong\" xml:space=\"preserve\">\n    <value>The binding context has a Model of type '{0}', but this binder can only operate on models of type '{1}'.</value>\n  </data>\n  <data name=\"ModelBinderUtil_ModelMetadataCannotBeNull\" xml:space=\"preserve\">\n    <value>The binding context cannot have a null ModelMetadata.</value>\n  </data>\n  <data name=\"ModelBinderUtil_ModelTypeIsWrong\" xml:space=\"preserve\">\n    <value>The binding context has a ModelType of '{0}', but this binder can only operate on models of type '{1}'.</value>\n  </data>\n  <data name=\"ModelBinderConfig_ValueInvalid\" xml:space=\"preserve\">\n    <value>The value '{0}' is not valid for {1}.</value>\n  </data>\n  <data name=\"ModelBinderConfig_ValueRequired\" xml:space=\"preserve\">\n    <value>A value is required.</value>\n  </data>\n  <data name=\"ModelBinderProviderCollection_BinderForTypeNotFound\" xml:space=\"preserve\">\n    <value>A binder for type {0} could not be located.</value>\n  </data>\n  <data name=\"ModelBindingContext_ModelMetadataMustBeSet\" xml:space=\"preserve\">\n    <value>The ModelMetadata property must be set before accessing this property.</value>\n  </data>\n  <data name=\"Common_TypeMustImplementInterface\" xml:space=\"preserve\">\n    <value>The type '{0}' does not implement the interface '{1}'.</value>\n  </data>\n  <data name=\"GenericModelBinderProvider_ParameterMustSpecifyOpenGenericType\" xml:space=\"preserve\">\n    <value>The type '{0}' is not an open generic type.</value>\n  </data>\n  <data name=\"GenericModelBinderProvider_TypeArgumentCountMismatch\" xml:space=\"preserve\">\n    <value>The open model type '{0}' has {1} generic type argument(s), but the open binder type '{2}' has {3} generic type argument(s). The binder type must not be an open generic type or must have the same number of generic arguments as the open model type.</value>\n  </data>\n  <data name=\"BindingBehavior_ValueNotFound\" xml:space=\"preserve\">\n    <value>A value for '{0}' is required but was not present in the request.</value>\n  </data>\n  <data name=\"ExtensibleModelBinderAdapter_PropertyFilterMustNotBeSet\" xml:space=\"preserve\">\n    <value>The new model binding system cannot be used when a property whitelist or blacklist has been specified in [Bind] or via the call to UpdateModel() / TryUpdateModel(). Use the [BindRequired] and [BindNever] attributes on the model type or its properties instead.</value>\n  </data>\n  <data name=\"ModelBinderProviderCollection_TypeCannotHaveBindAttribute\" xml:space=\"preserve\">\n    <value>The model of type '{0}' has a [Bind] attribute. The new model binding system cannot be used with models that have type-level [Bind] attributes. Use the [BindRequired] and [BindNever] attributes on the model type or its properties instead.</value>\n  </data>\n  <data name=\"ModelBinderProviderCollection_InvalidBinderType\" xml:space=\"preserve\">\n    <value>The type '{0}' does not subclass {1} or implement the interface {2}.</value>\n  </data>\n  <data name=\"DynamicViewDataDictionary_SingleIndexerOnly\" xml:space=\"preserve\">\n    <value>DynamicViewDataDictionary only supports single indexers.</value>\n  </data>\n  <data name=\"DynamicViewDataDictionary_StringIndexerOnly\" xml:space=\"preserve\">\n    <value>DynamicViewDataDictionary only supports string-based indexers.</value>\n  </data>\n  <data name=\"DynamicViewPage_NoProperties\" xml:space=\"preserve\">\n    <value>The property {0} doesn't exist. There are no public properties on this object.</value>\n  </data>\n  <data name=\"DynamicViewPage_PropertyDoesNotExist\" xml:space=\"preserve\">\n    <value>The property {0} doesn't exist. Supported properties are: {1}.</value>\n  </data>\n  <data name=\"DropDownList_SampleItem\" xml:space=\"preserve\">\n    <value>Sample Item</value>\n  </data>\n  <data name=\"ResourceControllerFactory_ConflictingActions\" xml:space=\"preserve\">\n    <value>Error dispatching on controller {0}, conflicting actions matched: {1}.</value>\n  </data>\n  <data name=\"ResourceControllerFactory_NoActions\" xml:space=\"preserve\">\n    <value>Error dispatching on controller {0}, no actions matched.</value>\n  </data>\n  <data name=\"FileExtensionsAttribute_Invalid\" xml:space=\"preserve\">\n    <value>The {0} field only accepts files with the following extensions: {1}</value>\n  </data>\n  <data name=\"CreditCardAttribute_Invalid\" xml:space=\"preserve\">\n    <value>The {0} field is not a valid credit card number.</value>\n  </data>\n  <data name=\"EmailAddressAttribute_Invalid\" xml:space=\"preserve\">\n    <value>The {0} field is not a valid e-mail address.</value>\n  </data>\n  <data name=\"UrlAttribute_Invalid\" xml:space=\"preserve\">\n    <value>The {0} field is not a valid fully-qualified http, https, or ftp URL.</value>\n  </data>\n  <data name=\"AcceptAttribute_Invalid\" xml:space=\"preserve\">\n    <value>The {0} field only accepts files with one of the following content types: {1}.</value>\n  </data>\n  <data name=\"ModelBinderUtil_CannotCreateInstance\" xml:space=\"preserve\">\n    <value>{0} Object type '{1}'.</value>\n  </data>\n</root>"
  },
  {
    "path": "src/Microsoft.Web.Mvc/RadioExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Web.Mvc;\nusing System.Web.Mvc.Html;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc\n{\n    public static class RadioListExtensions\n    {\n        public static MvcHtmlString[] RadioButtonList(this HtmlHelper htmlHelper, string name)\n        {\n            return RadioButtonList(htmlHelper, name, (IDictionary<string, object>)null);\n        }\n\n        public static MvcHtmlString[] RadioButtonList(this HtmlHelper htmlHelper, string name, object htmlAttributes)\n        {\n            return RadioButtonList(htmlHelper, name, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcHtmlString[] RadioButtonList(this HtmlHelper htmlHelper, string name, IDictionary<string, object> htmlAttributes)\n        {\n            IEnumerable<SelectListItem> selectList = htmlHelper.GetSelectData(name);\n            return htmlHelper.RadioButtonListInternal(name, selectList, true /* usedViewData */, htmlAttributes);\n        }\n\n        public static MvcHtmlString[] RadioButtonList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList)\n        {\n            return RadioButtonList(htmlHelper, name, selectList, null);\n        }\n\n        public static MvcHtmlString[] RadioButtonList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, object htmlAttributes)\n        {\n            return RadioButtonList(htmlHelper, name, selectList, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcHtmlString[] RadioButtonList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, IDictionary<string, object> htmlAttributes)\n        {\n            return htmlHelper.RadioButtonListInternal(name, selectList, false /* usedViewData */, htmlAttributes);\n        }\n\n        private static IEnumerable<SelectListItem> GetSelectData(this HtmlHelper htmlHelper, string name)\n        {\n            object o = null;\n            if (htmlHelper.ViewData != null)\n            {\n                o = htmlHelper.ViewData.Eval(name);\n            }\n            if (o == null)\n            {\n                throw new InvalidOperationException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.HtmlHelper_MissingSelectData,\n                        name,\n                        typeof(IEnumerable<SelectListItem>)));\n            }\n            IEnumerable<SelectListItem> selectList = o as IEnumerable<SelectListItem>;\n            if (selectList == null)\n            {\n                throw new InvalidOperationException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.HtmlHelper_WrongSelectDataType,\n                        name,\n                        o.GetType().FullName,\n                        typeof(IEnumerable<SelectListItem>)));\n            }\n            return selectList;\n        }\n\n        private static MvcHtmlString[] RadioButtonListInternal(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, bool usedViewData, IDictionary<string, object> htmlAttributes)\n        {\n            if (String.IsNullOrEmpty(name))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"name\");\n            }\n            if (selectList == null)\n            {\n                throw new ArgumentNullException(\"selectList\");\n            }\n\n            // If we haven't already used ViewData to get the entire list of items then we need to\n            // use the ViewData-supplied value before using the parameter-supplied value.\n            if (!usedViewData)\n            {\n                object defaultValue = htmlHelper.ViewData.Eval(name);\n\n                if (defaultValue != null)\n                {\n                    IEnumerable defaultValues = new[] { defaultValue };\n                    IEnumerable<string> values = from object value in defaultValues\n                                                 select Convert.ToString(value, CultureInfo.CurrentCulture);\n                    HashSet<string> selectedValues = new HashSet<string>(values, StringComparer.OrdinalIgnoreCase);\n                    List<SelectListItem> newSelectList = new List<SelectListItem>();\n\n                    foreach (SelectListItem item in selectList)\n                    {\n                        item.Selected = (item.Value != null) ? selectedValues.Contains(item.Value) : selectedValues.Contains(item.Text);\n                        newSelectList.Add(item);\n                    }\n\n                    selectList = newSelectList;\n                }\n            }\n\n            IEnumerable<MvcHtmlString> radioButtons = selectList.Select(item => htmlHelper.RadioButton(name, item.Value, item.Selected, htmlAttributes));\n\n            return radioButtons.ToArray();\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ReaderWriterCache.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Threading;\n\nnamespace Microsoft.Web.Mvc\n{\n    [SuppressMessage(\"Microsoft.Design\", \"CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable\", Justification = \"Instances of this type are meant to be singletons.\")]\n    internal abstract class ReaderWriterCache<TKey, TValue>\n    {\n        private readonly Dictionary<TKey, TValue> _cache;\n        private readonly ReaderWriterLockSlim _readerWriterLock = new ReaderWriterLockSlim();\n\n        protected ReaderWriterCache()\n            : this(null)\n        {\n        }\n\n        protected ReaderWriterCache(IEqualityComparer<TKey> comparer)\n        {\n            _cache = new Dictionary<TKey, TValue>(comparer);\n        }\n\n        protected Dictionary<TKey, TValue> Cache\n        {\n            get { return _cache; }\n        }\n\n        protected TValue FetchOrCreateItem(TKey key, Func<TValue> creator)\n        {\n            // first, see if the item already exists in the cache\n            _readerWriterLock.EnterReadLock();\n            try\n            {\n                TValue existingEntry;\n                if (_cache.TryGetValue(key, out existingEntry))\n                {\n                    return existingEntry;\n                }\n            }\n            finally\n            {\n                _readerWriterLock.ExitReadLock();\n            }\n\n            // insert the new item into the cache\n            TValue newEntry = creator();\n            _readerWriterLock.EnterWriteLock();\n            try\n            {\n                TValue existingEntry;\n                if (_cache.TryGetValue(key, out existingEntry))\n                {\n                    // another thread already inserted an item, so use that one\n                    return existingEntry;\n                }\n\n                _cache[key] = newEntry;\n                return newEntry;\n            }\n            finally\n            {\n                _readerWriterLock.ExitWriteLock();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Resources/ActionType.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.Web.Mvc.Resources\n{\n    /// <summary>\n    /// This enum is used by the UrlHelper extension methods to create links within resource controllers\n    /// </summary>\n    public enum ActionType\n    {\n        Create,\n        GetCreateForm,\n        Index,\n        Retrieve,\n        Update,\n        GetUpdateForm,\n        Delete,\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Resources/AjaxHelperExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Mvc;\nusing System.Web.Mvc.Ajax;\nusing System.Web.Mvc.Html;\n\nnamespace Microsoft.Web.Mvc.Resources\n{\n    public static class AjaxHelperExtensions\n    {\n        /// <summary>\n        /// Generates the Form preamble, defaulting the link for the Retrieve action\n        /// </summary>\n        /// <param name=\"ajax\"></param>\n        /// <param name=\"controllerName\"></param>\n        /// <param name=\"routeValues\"></param>\n        /// <param name=\"ajaxOptions\"></param>\n        /// <returns></returns>\n        public static MvcForm BeginResourceForm(this AjaxHelper ajax, string controllerName, object routeValues, AjaxOptions ajaxOptions)\n        {\n            return ajax.BeginResourceForm(controllerName, routeValues, ajaxOptions, ActionType.Retrieve);\n        }\n\n        /// <summary>\n        /// Generates the Form preamble\n        /// </summary>\n        /// <param name=\"ajax\"></param>\n        /// <param name=\"controllerName\"></param>\n        /// <param name=\"routeValues\"></param>\n        /// <param name=\"ajaxOptions\"></param>\n        /// <param name=\"actionType\"></param>\n        /// <returns></returns>\n        public static MvcForm BeginResourceForm(this AjaxHelper ajax, string controllerName, object routeValues, AjaxOptions ajaxOptions, ActionType actionType)\n        {\n            switch (actionType)\n            {\n                case ActionType.GetUpdateForm:\n                    return ajax.BeginRouteForm(controllerName + \"-editForm\", routeValues, ajaxOptions);\n                case ActionType.GetCreateForm:\n                    return ajax.BeginRouteForm(controllerName + \"-createForm\", ajaxOptions);\n                case ActionType.Retrieve:\n                case ActionType.Delete:\n                case ActionType.Update:\n                    // can we use ajaxOptions to either add the header?\n                    MvcForm form = ajax.BeginRouteForm(controllerName, routeValues, ajaxOptions);\n                    return form;\n                case ActionType.Create:\n                    return ajax.BeginRouteForm(controllerName + \"-create\", ajaxOptions);\n                case ActionType.Index:\n                    return ajax.BeginRouteForm(controllerName + \"-index\", ajaxOptions);\n                default:\n                    throw new ArgumentOutOfRangeException(\"actionType\");\n            }\n        }\n\n        /// <summary>\n        /// Generates a link to the resource controller, defaulting to the Retrieve action\n        /// </summary>\n        /// <param name=\"ajax\"></param>\n        /// <param name=\"controllerName\"></param>\n        /// <param name=\"routeValues\"></param>\n        /// <param name=\"ajaxOptions\"></param>\n        /// <returns></returns>\n        public static MvcHtmlString ResourceLink(this AjaxHelper ajax, string controllerName, object routeValues, AjaxOptions ajaxOptions)\n        {\n            return ajax.ResourceLink(controllerName, controllerName, routeValues, ajaxOptions, ActionType.Retrieve);\n        }\n\n        /// <summary>\n        /// Generates a link to the resource controller, defaulting to the Retrieve action\n        /// </summary>\n        /// <param name=\"ajax\"></param>\n        /// <param name=\"controllerName\"></param>\n        /// <param name=\"linkText\"></param>\n        /// <param name=\"routeValues\"></param>\n        /// <param name=\"ajaxOptions\"></param>\n        /// <returns></returns>\n        public static MvcHtmlString ResourceLink(this AjaxHelper ajax, string controllerName, string linkText, object routeValues, AjaxOptions ajaxOptions)\n        {\n            return ajax.ResourceLink(linkText, controllerName, routeValues, ajaxOptions, ActionType.Retrieve);\n        }\n\n        /// <summary>\n        /// Generates a link to the resource controller\n        /// </summary>\n        /// <param name=\"ajax\"></param>\n        /// <param name=\"controllerName\"></param>\n        /// <param name=\"linkText\"></param>\n        /// <param name=\"routeValues\"></param>\n        /// <param name=\"ajaxOptions\"></param>\n        /// <param name=\"actionType\"></param>\n        /// <returns></returns>\n        public static MvcHtmlString ResourceLink(this AjaxHelper ajax, string controllerName, string linkText, object routeValues, AjaxOptions ajaxOptions, ActionType actionType)\n        {\n            switch (actionType)\n            {\n                case ActionType.GetUpdateForm:\n                    return ajax.RouteLink(linkText, controllerName + \"-editForm\", routeValues, ajaxOptions);\n                case ActionType.GetCreateForm:\n                    return ajax.RouteLink(linkText, controllerName + \"-createForm\", ajaxOptions);\n                case ActionType.Retrieve:\n                case ActionType.Delete:\n                case ActionType.Update:\n                    return ajax.RouteLink(linkText, controllerName, routeValues, ajaxOptions);\n                case ActionType.Create:\n                    return ajax.RouteLink(linkText, controllerName + \"-create\", ajaxOptions);\n                case ActionType.Index:\n                    return ajax.RouteLink(linkText, controllerName + \"-index\", ajaxOptions);\n                default:\n                    throw new ArgumentOutOfRangeException(\"actionType\");\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Resources/AtomEntryActionResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Globalization;\nusing System.Net;\nusing System.Net.Mime;\nusing System.ServiceModel.Syndication;\nusing System.Text;\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Xml;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc.Resources\n{\n    /// <summary>\n    /// An ActionResult that can render a SyndicationItem to the Atom 1.0 entry format\n    /// </summary>\n    public class AtomEntryActionResult : ActionResult\n    {\n        private ContentType contentType;\n        private SyndicationItem item;\n\n        /// <summary>\n        /// The content type defaults to application/atom+xml; type=entry\n        /// </summary>\n        /// <param name=\"item\"></param>\n        public AtomEntryActionResult(SyndicationItem item)\n            : this(item, new ContentType(\"application/atom+xml;type=entry\"))\n        {\n        }\n\n        public AtomEntryActionResult(SyndicationItem item, ContentType contentType)\n        {\n            if (item == null)\n            {\n                throw new ArgumentNullException(\"item\");\n            }\n            if (contentType == null)\n            {\n                throw new ArgumentNullException(\"contentType\");\n            }\n            this.item = item;\n            this.contentType = contentType;\n        }\n\n        public ContentType ContentType\n        {\n            get { return this.contentType; }\n        }\n\n        public SyndicationItem Item\n        {\n            get { return this.item; }\n        }\n\n        public override void ExecuteResult(ControllerContext context)\n        {\n            Encoding encoding = Encoding.UTF8;\n            if (!String.IsNullOrEmpty(this.ContentType.CharSet))\n            {\n                try\n                {\n                    encoding = Encoding.GetEncoding(this.ContentType.CharSet);\n                }\n                catch (ArgumentException)\n                {\n                    throw new HttpException((int)HttpStatusCode.NotAcceptable, String.Format(CultureInfo.CurrentCulture, MvcResources.Resources_UnsupportedFormat, this.ContentType));\n                }\n            }\n            XmlWriterSettings settings = new XmlWriterSettings { Encoding = encoding };\n            this.ContentType.CharSet = settings.Encoding.HeaderName;\n            context.HttpContext.Response.ContentType = this.ContentType.ToString();\n            using (XmlWriter writer = XmlWriter.Create(context.HttpContext.Response.OutputStream, settings))\n            {\n                this.Item.GetAtom10Formatter().WriteTo(writer);\n                writer.Flush();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Resources/AtomFeedActionResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Globalization;\nusing System.Net;\nusing System.Net.Mime;\nusing System.ServiceModel.Syndication;\nusing System.Text;\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Xml;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc.Resources\n{\n    /// <summary>\n    /// An ActionResult that can render a SyndicationFeed to the Atom 1.0 feed format\n    /// </summary>\n    public class AtomFeedActionResult : ActionResult\n    {\n        private ContentType contentType;\n        private SyndicationFeed feed;\n\n        /// <summary>\n        /// The content type defaults to application/atom+xml\n        /// </summary>\n        /// <param name=\"feed\"></param>\n        public AtomFeedActionResult(SyndicationFeed feed)\n            : this(feed, new ContentType(\"application/atom+xml\"))\n        {\n        }\n\n        public AtomFeedActionResult(SyndicationFeed feed, ContentType contentType)\n        {\n            if (feed == null)\n            {\n                throw new ArgumentNullException(\"feed\");\n            }\n            if (contentType == null)\n            {\n                throw new ArgumentNullException(\"contentType\");\n            }\n            this.feed = feed;\n            this.contentType = contentType;\n        }\n\n        public ContentType ContentType\n        {\n            get { return this.contentType; }\n        }\n\n        public SyndicationFeed Feed\n        {\n            get { return this.feed; }\n        }\n\n        public override void ExecuteResult(ControllerContext context)\n        {\n            Encoding encoding = Encoding.UTF8;\n            if (!String.IsNullOrEmpty(this.ContentType.CharSet))\n            {\n                try\n                {\n                    encoding = Encoding.GetEncoding(this.ContentType.CharSet);\n                }\n                catch (ArgumentException)\n                {\n                    throw new HttpException((int)HttpStatusCode.NotAcceptable, String.Format(CultureInfo.CurrentCulture, MvcResources.Resources_UnsupportedFormat, this.ContentType));\n                }\n            }\n            XmlWriterSettings settings = new XmlWriterSettings { Encoding = encoding };\n            this.ContentType.CharSet = settings.Encoding.HeaderName;\n            context.HttpContext.Response.ContentType = this.ContentType.ToString();\n            using (XmlWriter writer = XmlWriter.Create(context.HttpContext.Response.OutputStream, settings))\n            {\n                this.Feed.GetAtom10Formatter().WriteTo(writer);\n                writer.Flush();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Resources/AtomServiceDocumentActionResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Globalization;\nusing System.Net;\nusing System.Net.Mime;\nusing System.ServiceModel.Syndication;\nusing System.Text;\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Xml;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc.Resources\n{\n    /// <summary>\n    /// An ActionResult that can render a ServiceDocument to the Atom 1.0 ServiceDocument format\n    /// </summary>\n    public class AtomServiceDocumentActionResult : ActionResult\n    {\n        private ContentType contentType;\n        private ServiceDocument document;\n\n        /// <summary>\n        /// The content type defaults to application/atomsvc+xml\n        /// </summary>\n        /// <param name=\"document\"></param>\n        public AtomServiceDocumentActionResult(ServiceDocument document)\n            : this(document, new ContentType(\"application/atomsvc+xml\"))\n        {\n        }\n\n        public AtomServiceDocumentActionResult(ServiceDocument document, ContentType contentType)\n        {\n            if (document == null)\n            {\n                throw new ArgumentNullException(\"document\");\n            }\n            if (contentType == null)\n            {\n                throw new ArgumentNullException(\"contentType\");\n            }\n            this.document = document;\n            this.contentType = contentType;\n        }\n\n        public ContentType ContentType\n        {\n            get { return this.contentType; }\n        }\n\n        public ServiceDocument Document\n        {\n            get { return this.document; }\n        }\n\n        public override void ExecuteResult(ControllerContext context)\n        {\n            Encoding encoding = Encoding.UTF8;\n            if (!String.IsNullOrEmpty(this.ContentType.CharSet))\n            {\n                try\n                {\n                    encoding = Encoding.GetEncoding(this.ContentType.CharSet);\n                }\n                catch (ArgumentException)\n                {\n                    throw new HttpException((int)HttpStatusCode.NotAcceptable, String.Format(CultureInfo.CurrentCulture, MvcResources.Resources_UnsupportedFormat, this.ContentType));\n                }\n            }\n            XmlWriterSettings settings = new XmlWriterSettings { Encoding = encoding };\n            this.ContentType.CharSet = settings.Encoding.HeaderName;\n            context.HttpContext.Response.ContentType = this.ContentType.ToString();\n            using (XmlWriter writer = XmlWriter.Create(context.HttpContext.Response.OutputStream, settings))\n            {\n                this.Document.GetFormatter().WriteTo(writer);\n                writer.Flush();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Resources/DataContractJsonActionResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Globalization;\nusing System.Net;\nusing System.Net.Mime;\nusing System.Runtime.Serialization.Json;\nusing System.Text;\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Xml;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc.Resources\n{\n    /// <summary>\n    /// An ActionResult that can render an object to the json format using the DataContractJsonSerializer\n    /// </summary>\n    public class DataContractJsonActionResult : ActionResult\n    {\n        private ContentType contentType;\n        private object data;\n\n        /// <summary>\n        /// The default content type is application/json\n        /// </summary>\n        /// <param name=\"data\"></param>\n        public DataContractJsonActionResult(object data)\n            : this(data, new ContentType(\"application/json\"))\n        {\n        }\n\n        public DataContractJsonActionResult(object data, ContentType contentType)\n        {\n            this.data = data;\n            this.contentType = contentType;\n        }\n\n        public ContentType ContentType\n        {\n            get { return this.contentType; }\n        }\n\n        public object Data\n        {\n            get { return this.data; }\n        }\n\n        public override void ExecuteResult(ControllerContext context)\n        {\n            Encoding encoding = Encoding.UTF8;\n            if (!String.IsNullOrEmpty(this.ContentType.CharSet))\n            {\n                try\n                {\n                    encoding = Encoding.GetEncoding(this.ContentType.CharSet);\n                }\n                catch (ArgumentException)\n                {\n                    throw new HttpException((int)HttpStatusCode.NotAcceptable, String.Format(CultureInfo.CurrentCulture, MvcResources.Resources_UnsupportedFormat, this.ContentType));\n                }\n            }\n            DataContractJsonSerializer dcs = new DataContractJsonSerializer(this.Data.GetType());\n            this.ContentType.CharSet = encoding.HeaderName;\n            context.HttpContext.Response.ContentType = this.ContentType.ToString();\n            using (XmlWriter writer = JsonReaderWriterFactory.CreateJsonWriter(context.HttpContext.Response.OutputStream, encoding))\n            {\n                dcs.WriteObject(writer, this.Data);\n                writer.Flush();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Resources/DataContractXmlActionResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Globalization;\nusing System.Net;\nusing System.Net.Mime;\nusing System.Runtime.Serialization;\nusing System.Text;\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Xml;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc.Resources\n{\n    /// <summary>\n    /// An ActionResult that can render an object to the xml format using the DataContractSerializer\n    /// </summary>\n    public class DataContractXmlActionResult : ActionResult\n    {\n        private ContentType contentType;\n        private object data;\n\n        /// <summary>\n        /// The content type of the response defaults to application/xml\n        /// </summary>\n        public DataContractXmlActionResult(object data)\n            : this(data, new ContentType(\"application/xml\"))\n        {\n        }\n\n        public DataContractXmlActionResult(object data, ContentType contentType)\n        {\n            this.data = data;\n            this.contentType = contentType;\n        }\n\n        public ContentType ContentType\n        {\n            get { return this.contentType; }\n        }\n\n        public object Data\n        {\n            get { return this.data; }\n        }\n\n        public override void ExecuteResult(ControllerContext context)\n        {\n            Encoding encoding = Encoding.UTF8;\n            if (!String.IsNullOrEmpty(this.ContentType.CharSet))\n            {\n                try\n                {\n                    encoding = Encoding.GetEncoding(this.ContentType.CharSet);\n                }\n                catch (ArgumentException)\n                {\n                    throw new HttpException((int)HttpStatusCode.NotAcceptable, String.Format(CultureInfo.CurrentCulture, MvcResources.Resources_UnsupportedFormat, this.ContentType));\n                }\n            }\n            XmlWriterSettings settings = new XmlWriterSettings { Encoding = encoding };\n            DataContractSerializer dcs = new DataContractSerializer(this.Data.GetType());\n            this.ContentType.CharSet = settings.Encoding.HeaderName;\n            context.HttpContext.Response.ContentType = this.ContentType.ToString();\n            using (XmlWriter writer = XmlWriter.Create(context.HttpContext.Response.OutputStream, settings))\n            {\n                dcs.WriteObject(writer, this.Data);\n                writer.Flush();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Resources/DefaultFormatHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Net;\nusing System.Net.Mime;\nusing System.Text;\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Web.Routing;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc.Resources\n{\n    /// <summary>\n    /// Default implementation of FormatHelper\n    /// The results for GetRequestFormat() and GetResponseFormats() are cached on the HttpContext.Items dictionary:\n    /// HttpContext.Items[\"requestFormat\"]\n    /// HttpContext.Items[\"responseFormat\"]\n    /// </summary>\n    public class DefaultFormatHelper : FormatHelper\n    {\n        private const string FormatVariableName = \"format\";\n        private const string QualityFactor = \"q\";\n\n        public const string RequestFormatKey = \"requestFormat\";\n        public const string ResponseFormatKey = \"responseFormat\";\n\n        /// <summary>\n        /// Returns the format of a given request, according to the following\n        /// rules:\n        /// 1. If a Content-Type header exists it returns a ContentType for it or fails if one can't be created\n        /// 2. Otherwie, if a Content-Type header does not exists it provides the default ContentType of \"application/octet-stream\" (per RFC 2616 7.2.1)\n        /// </summary>\n        /// <param name=\"requestContext\">The request.</param>\n        /// <returns>The format of the request.</returns>\n        /// <exception cref=\"HttpException\">If the format is unrecognized or not supported.</exception>\n        public override ContentType GetRequestFormat(RequestContext requestContext)\n        {\n            ContentType result;\n            if (!requestContext.HttpContext.Items.Contains(RequestFormatKey))\n            {\n                result = GetRequestFormat(requestContext.HttpContext.Request, true);\n                requestContext.HttpContext.Items.Add(RequestFormatKey, result);\n            }\n            else\n            {\n                result = (ContentType)requestContext.HttpContext.Items[RequestFormatKey];\n            }\n            return result;\n        }\n\n        internal static ContentType GetRequestFormat(HttpRequestBase request, bool throwOnError)\n        {\n            if (!String.IsNullOrEmpty(request.ContentType))\n            {\n                ContentType contentType = ParseContentType(request.ContentType);\n                if (contentType != null)\n                {\n                    return contentType;\n                }\n                if (throwOnError)\n                {\n                    throw new HttpException((int)HttpStatusCode.UnsupportedMediaType, String.Format(CultureInfo.CurrentCulture, MvcResources.Resources_UnsupportedMediaType, request.ContentType));\n                }\n                return null;\n            }\n            return new ContentType();\n        }\n\n        /// <summary>\n        /// Returns the preferred content type to use for the response, based on the request, according to the following\n        /// rules:\n        /// 1. If the RouteData contains a value for a key called \"format\", its value is returned as the content type\n        /// 2. Otherwise, if the query string contains a key called \"format\", its value is returned as the content type\n        /// 3. Otherwise, if the request has an Accepts header, the list of content types in order of preference is returned\n        /// 4. Otherwise, if the request has a content type, its value is returned\n        /// </summary>\n        /// <param name=\"requestContext\">The request.</param>\n        /// <returns>The formats to use for rendering a response.</returns>\n        public override IEnumerable<ContentType> GetResponseFormats(RequestContext requestContext)\n        {\n            IEnumerable<ContentType> result;\n            if (!requestContext.HttpContext.Items.Contains(ResponseFormatKey))\n            {\n                result = GetResponseFormatsRouteAware(requestContext);\n                requestContext.HttpContext.Items.Add(ResponseFormatKey, result);\n            }\n            else\n            {\n                result = (IEnumerable<ContentType>)requestContext.HttpContext.Items[ResponseFormatKey];\n            }\n            return result;\n        }\n\n        private static List<ContentType> GetResponseFormatsRouteAware(RequestContext requestContext)\n        {\n            List<ContentType> result = GetResponseFormatsCore(requestContext.HttpContext.Request);\n            ContentType contentType;\n            if (result == null)\n            {\n                contentType = FormatManager.Current.FormatHelper.GetRequestFormat(requestContext);\n                result = new List<ContentType>(new[] { contentType });\n            }\n            if (TryGetFromRouteData(requestContext.RouteData, out contentType))\n            {\n                result.Insert(0, contentType);\n            }\n            return result;\n        }\n\n        /// <summary>\n        /// Returns the preferred content type to use for the response, based on the request, according to the following\n        /// rules:\n        /// 1. If the query string contains a key called \"format\", its value is returned as the content type\n        /// 2. Otherwise, if the request has an Accepts header, the list of content types in order of preference is returned\n        /// 3. Otherwise, if the request has a content type, its value is returned\n        /// </summary>\n        /// <param name=\"request\"></param>\n        /// <returns></returns>\n        internal static List<ContentType> GetResponseFormats(HttpRequestBase request)\n        {\n            List<ContentType> result = GetResponseFormatsCore(request);\n            if (result == null)\n            {\n                ContentType contentType = GetRequestFormat(request, true);\n                result = new List<ContentType>(new[] { contentType });\n            }\n            return result;\n        }\n\n        private static List<ContentType> GetResponseFormatsCore(HttpRequestBase request)\n        {\n            ContentType contentType;\n            if (TryGetFromUri(request, out contentType))\n            {\n                return new List<ContentType>(new[] { contentType });\n            }\n            string[] accepts = request.AcceptTypes;\n            if (accepts != null && accepts.Length > 0)\n            {\n                return GetAcceptHeaderElements(accepts);\n            }\n            return null;\n        }\n\n        // CONSIDER: we currently don't process the Accept-Charset header, need to take it into account, EG:\n        // Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3\n        private static List<ContentType> GetAcceptHeaderElements(string[] acceptHeaderElements)\n        {\n            List<ContentType> contentTypeList = new List<ContentType>(acceptHeaderElements.Length);\n            foreach (string acceptHeaderElement in acceptHeaderElements)\n            {\n                if (acceptHeaderElement != null)\n                {\n                    ContentType contentType = ParseContentType(acceptHeaderElement);\n                    // ignore unknown formats to allow fallback\n                    if (contentType != null)\n                    {\n                        contentTypeList.Add(contentType);\n                    }\n                }\n            }\n            contentTypeList.Sort(new AcceptHeaderElementComparer());\n            // CONSIDER: we used the \"q\" parameter for sorting, so now we strip it\n            // it might be ebtter to strip it later in case someone needs to access it\n            foreach (ContentType ct in contentTypeList)\n            {\n                if (ct.Parameters.ContainsKey(QualityFactor))\n                {\n                    ct.Parameters.Remove(QualityFactor);\n                }\n            }\n            return contentTypeList;\n        }\n\n        public override bool IsBrowserRequest(RequestContext requestContext)\n        {\n            return IsBrowserRequest(requestContext.HttpContext.Request);\n        }\n\n        // Parses a string into a ContentType instance, supports\n        // friendly names and enforces a charset (which defaults to utf-8)\n        internal static ContentType ParseContentType(string contentTypeString)\n        {\n            ContentType contentType = null;\n            try\n            {\n                contentType = new ContentType(contentTypeString);\n            }\n            catch (FormatException)\n            {\n                // This may be a friendly name (for example, \"xml\" instead of \"text/xml\").\n                // if so, try mapping to a content type\n                if (!FormatManager.Current.TryMapFormatFriendlyName(contentTypeString, out contentType))\n                {\n                    return null;\n                }\n            }\n            Encoding encoding = Encoding.UTF8;\n            if (!String.IsNullOrEmpty(contentType.CharSet))\n            {\n                try\n                {\n                    encoding = Encoding.GetEncoding(contentType.CharSet);\n                }\n                catch (ArgumentException)\n                {\n                    return null;\n                }\n            }\n            contentType.CharSet = encoding.HeaderName;\n            return contentType;\n        }\n\n        // Route-based format override so clients can use a route variable\n        private static bool TryGetFromRouteData(RouteData routeData, out ContentType contentType)\n        {\n            contentType = null;\n            if (routeData != null)\n            {\n                string fromRouteData = routeData.Values[FormatVariableName] as string;\n                if (!String.IsNullOrEmpty(fromRouteData))\n                {\n                    contentType = ParseContentType(fromRouteData);\n                }\n            }\n            return contentType != null;\n        }\n\n        // Uri-based format override so clients can use a query string\n        // also useful when using the browser where you can't set headerss\n        private static bool TryGetFromUri(HttpRequestBase request, out ContentType contentType)\n        {\n            string fromParams = request.QueryString[FormatVariableName];\n            if (fromParams != null)\n            {\n                contentType = ParseContentType(fromParams);\n                if (contentType != null)\n                {\n                    return true;\n                }\n            }\n            contentType = null;\n            return false;\n        }\n\n        /// <summary>\n        /// Determines whether the specified HTTP request was sent by a Browser.\n        /// A request is considered to be from the browser if:\n        /// it's a GET or POST\n        /// and does not have a non-HTML entity format (XML/JSON)\n        /// and has a known User-Agent header (as determined by the request's BrowserCapabilities property),\n        /// </summary>\n        /// <param name=\"request\">The request.</param>\n        /// <returns>true if the specified HTTP request is a Browser request; otherwise, false.</returns>\n        internal static bool IsBrowserRequest(HttpRequestBase request)\n        {\n            if (!request.IsHttpMethod(HttpVerbs.Get) && !request.IsHttpMethod(HttpVerbs.Post))\n            {\n                return false;\n            }\n            ContentType requestFormat = GetRequestFormat(request, false);\n            if (requestFormat == null || String.Compare(requestFormat.MediaType, FormatManager.UrlEncoded, StringComparison.OrdinalIgnoreCase) != 0)\n            {\n                if (FormatManager.Current.CanDeserialize(requestFormat))\n                {\n                    return false;\n                }\n            }\n            HttpBrowserCapabilitiesBase browserCapabilities = request.Browser;\n            if (browserCapabilities != null && !String.IsNullOrEmpty(request.Browser.Browser) && request.Browser.Browser != \"Unknown\")\n            {\n                return true;\n            }\n            return false;\n        }\n\n        private class AcceptHeaderElementComparer : IComparer<ContentType>\n        {\n            [SuppressMessage(\"StyleCop.CSharp.NamingRules\", \"SA1305:FieldNamesMustNotUseHungarianNotation\", Target = \"x, y\",\n                Justification = \"No need to fix this since this is a private class.\")]\n            public int Compare(ContentType x, ContentType y)\n            {\n                string[] xTypeSubType = x.MediaType.Split('/');\n                string[] yTypeSubType = y.MediaType.Split('/');\n\n                if (String.Equals(xTypeSubType[0], yTypeSubType[0], StringComparison.OrdinalIgnoreCase))\n                {\n                    if (String.Equals(xTypeSubType[1], yTypeSubType[1], StringComparison.OrdinalIgnoreCase))\n                    {\n                        // need to check the number of parameters to determine which is more specific\n                        bool xHasParam = HasParameters(x);\n                        bool yHasParam = HasParameters(y);\n                        if (xHasParam && !yHasParam)\n                        {\n                            return 1;\n                        }\n                        else if (!xHasParam && yHasParam)\n                        {\n                            return -1;\n                        }\n                    }\n                    else\n                    {\n                        if (xTypeSubType[1][0] == '*' && xTypeSubType[1].Length == 1)\n                        {\n                            return 1;\n                        }\n                        if (yTypeSubType[1][0] == '*' && yTypeSubType[1].Length == 1)\n                        {\n                            return -1;\n                        }\n                    }\n                }\n                else if (xTypeSubType[0][0] == '*' && xTypeSubType[0].Length == 1)\n                {\n                    return 1;\n                }\n                else if (yTypeSubType[0][0] == '*' && yTypeSubType[0].Length == 1)\n                {\n                    return -1;\n                }\n\n                decimal qualityDifference = GetQualityFactor(x) - GetQualityFactor(y);\n                if (qualityDifference < 0)\n                {\n                    return 1;\n                }\n                else if (qualityDifference > 0)\n                {\n                    return -1;\n                }\n                return 0;\n            }\n\n            private static decimal GetQualityFactor(ContentType contentType)\n            {\n                decimal result;\n                foreach (string key in contentType.Parameters.Keys)\n                {\n                    if (String.Equals(QualityFactor, key, StringComparison.OrdinalIgnoreCase))\n                    {\n                        if (Decimal.TryParse(contentType.Parameters[key], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out result) &&\n                            (result <= (decimal)1.0))\n                        {\n                            return result;\n                        }\n                    }\n                }\n\n                return (decimal)1.0;\n            }\n\n            private static bool HasParameters(ContentType contentType)\n            {\n                int number = 0;\n                foreach (string param in contentType.Parameters.Keys)\n                {\n                    if (!String.Equals(QualityFactor, param, StringComparison.OrdinalIgnoreCase))\n                    {\n                        number++;\n                    }\n                }\n\n                return (number > 0);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Resources/DefaultFormatManager.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.Web.Mvc.Resources\n{\n    public class DefaultFormatManager : FormatManager\n    {\n        public DefaultFormatManager()\n        {\n            XmlFormatHandler xmlHandler = new XmlFormatHandler();\n            JsonFormatHandler jsonHandler = new JsonFormatHandler();\n            this.RequestFormatHandlers.Add(xmlHandler);\n            this.RequestFormatHandlers.Add(jsonHandler);\n            this.ResponseFormatHandlers.Add(xmlHandler);\n            this.ResponseFormatHandlers.Add(jsonHandler);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Resources/FormatHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Mime;\nusing System.Web;\nusing System.Web.Routing;\n\nnamespace Microsoft.Web.Mvc.Resources\n{\n    /// <summary>\n    /// Base class for content negotiation support\n    /// </summary>\n    public abstract class FormatHelper\n    {\n        /// <summary>\n        /// Returns the ContentType of a given request.\n        /// </summary>\n        /// <param name=\"requestContext\">The request.</param>\n        /// <returns>The format of the request.</returns>\n        /// <exception cref=\"HttpException\">If the format is unrecognized or not supported.</exception>\n        public abstract ContentType GetRequestFormat(RequestContext requestContext);\n\n        /// <summary>\n        /// Returns a collection of ContentType instances that can be used to render a response to a given request, sorted in priority order.\n        /// </summary>\n        /// <param name=\"requestContext\">The request.</param>\n        /// <returns>The formats to use for rendering a response.</returns>\n        public abstract IEnumerable<ContentType> GetResponseFormats(RequestContext requestContext);\n\n        /// <summary>\n        /// Determines whether the specified HTTP request was sent by a Browser.\n        /// </summary>\n        /// <param name=\"requestContext\">The request.</param>\n        /// <returns></returns>\n        public abstract bool IsBrowserRequest(RequestContext requestContext);\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Resources/FormatManager.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.ObjectModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Net.Mime;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.Resources\n{\n    /// <summary>\n    /// Class that maintains a registration of handlers for\n    /// request and response formats\n    /// </summary>\n    public class FormatManager\n    {\n        public const string UrlEncoded = \"application/x-www-form-urlencoded\";\n\n        private static FormatManager _current = new DefaultFormatManager();\n\n        private Collection<IRequestFormatHandler> _requestHandlers;\n        private Collection<IResponseFormatHandler> _responseHandlers;\n        private FormatHelper _formatHelper;\n\n        public FormatManager()\n        {\n            this._requestHandlers = new Collection<IRequestFormatHandler>();\n            this._responseHandlers = new Collection<IResponseFormatHandler>();\n            this._formatHelper = new DefaultFormatHelper();\n        }\n\n        /// <summary>\n        /// The list of handlers that can parse the request body\n        /// </summary>\n        public Collection<IRequestFormatHandler> RequestFormatHandlers\n        {\n            get { return this._requestHandlers; }\n        }\n\n        /// <summary>\n        /// The list of handlers that can serialize the response body\n        /// </summary>\n        public Collection<IResponseFormatHandler> ResponseFormatHandlers\n        {\n            get { return this._responseHandlers; }\n        }\n\n        public static FormatManager Current\n        {\n            get { return _current; }\n            set\n            {\n                if (value == null)\n                {\n                    throw new ArgumentNullException(\"value\");\n                }\n                _current = value;\n            }\n        }\n\n        // CONSIDER: the FormatHelper is an abstraction that lets users extend the content negotiation process\n        // we must reconsider the FormatManager/FormatHelper factoring and provide a cleaner way of allowing this same extensibility\n        public FormatHelper FormatHelper\n        {\n            get { return _formatHelper; }\n            set\n            {\n                if (value == null)\n                {\n                    throw new ArgumentNullException(\"value\");\n                }\n                _formatHelper = value;\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1007:UseGenericsWhereAppropriate\", Justification = \"This is an existing API; this would be a breaking change\")]\n        public bool TryDeserialize(ControllerContext controllerContext, ModelBindingContext bindingContext, ContentType requestFormat, out object model)\n        {\n            for (int i = 0; i < this.RequestFormatHandlers.Count; ++i)\n            {\n                if (this.RequestFormatHandlers[i].CanDeserialize(requestFormat))\n                {\n                    model = this.RequestFormatHandlers[i].Deserialize(controllerContext, bindingContext, requestFormat);\n                    return true;\n                }\n            }\n            model = null;\n            return false;\n        }\n\n        public bool CanDeserialize(ContentType contentType)\n        {\n            for (int i = 0; i < this.RequestFormatHandlers.Count; ++i)\n            {\n                if (this.RequestFormatHandlers[i].CanDeserialize(contentType))\n                {\n                    return true;\n                }\n            }\n            return false;\n        }\n\n        public bool CanSerialize(ContentType responseFormat)\n        {\n            for (int i = 0; i < this.ResponseFormatHandlers.Count; ++i)\n            {\n                if (this.ResponseFormatHandlers[i].CanSerialize(responseFormat))\n                {\n                    return true;\n                }\n            }\n            return false;\n        }\n\n        public void Serialize(ControllerContext context, object model, ContentType responseFormat)\n        {\n            for (int i = 0; i < this.ResponseFormatHandlers.Count; ++i)\n            {\n                if (this.ResponseFormatHandlers[i].CanSerialize(responseFormat))\n                {\n                    this.ResponseFormatHandlers[i].Serialize(context, model, responseFormat);\n                    return;\n                }\n            }\n            throw new NotSupportedException();\n        }\n\n        public bool TryMapFormatFriendlyName(string formatName, out ContentType contentType)\n        {\n            for (int i = 0; i < this.ResponseFormatHandlers.Count; ++i)\n            {\n                if (this.ResponseFormatHandlers[i].TryMapFormatFriendlyName(formatName, out contentType))\n                {\n                    return true;\n                }\n            }\n            contentType = null;\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Resources/HtmlHelperExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Mvc;\nusing System.Web.Mvc.Html;\n\nnamespace Microsoft.Web.Mvc.Resources\n{\n    public static class HtmlHelperExtensions\n    {\n        /// <summary>\n        /// Generates the Form preamble, defaulting the link for the Retrieve action\n        /// </summary>\n        /// <param name=\"html\"></param>\n        /// <param name=\"controllerName\"></param>\n        /// <param name=\"routeValues\"></param>\n        /// <returns></returns>\n        public static MvcForm BeginResourceForm(this HtmlHelper html, string controllerName, object routeValues)\n        {\n            return html.BeginResourceForm(controllerName, routeValues, ActionType.Retrieve);\n        }\n\n        /// <summary>\n        /// Generates the Form preamble\n        /// </summary>\n        /// <param name=\"html\"></param>\n        /// <param name=\"controllerName\"></param>\n        /// <param name=\"routeValues\"></param>\n        /// <param name=\"actionType\"></param>\n        /// <returns></returns>\n        public static MvcForm BeginResourceForm(this HtmlHelper html, string controllerName, object routeValues, ActionType actionType)\n        {\n            return html.BeginResourceForm(controllerName, routeValues, null, actionType);\n        }\n\n        /// <summary>\n        /// Generates the Form preamble\n        /// </summary>\n        /// <param name=\"html\"></param>\n        /// <param name=\"controllerName\"></param>\n        /// <param name=\"routeValues\"></param>\n        /// <param name=\"htmlAttributes\"></param>\n        /// <param name=\"actionType\"></param>\n        /// <returns></returns>\n        public static MvcForm BeginResourceForm(this HtmlHelper html, string controllerName, object routeValues, object htmlAttributes, ActionType actionType)\n        {\n            switch (actionType)\n            {\n                case ActionType.GetUpdateForm:\n                    return html.BeginRouteForm(controllerName + \"-editForm\", routeValues, FormMethod.Post, htmlAttributes);\n                case ActionType.GetCreateForm:\n                    return html.BeginRouteForm(controllerName + \"-createForm\", FormMethod.Post, htmlAttributes);\n                case ActionType.Retrieve:\n                case ActionType.Delete:\n                case ActionType.Update:\n                    return html.BeginRouteForm(controllerName, routeValues, FormMethod.Post, htmlAttributes);\n                case ActionType.Create:\n                    return html.BeginRouteForm(controllerName + \"-create\", FormMethod.Post, htmlAttributes);\n                case ActionType.Index:\n                    return html.BeginRouteForm(controllerName + \"-index\", FormMethod.Post, htmlAttributes);\n                default:\n                    throw new ArgumentOutOfRangeException(\"actionType\");\n            }\n        }\n\n        /// <summary>\n        /// Generates a link to the resource controller, defaulting to the Retrieve action\n        /// </summary>\n        /// <param name=\"html\"></param>\n        /// <param name=\"controllerName\"></param>\n        /// <param name=\"routeValues\"></param>\n        /// <returns></returns>\n        public static MvcHtmlString ResourceLink(this HtmlHelper html, string controllerName, object routeValues)\n        {\n            return html.ResourceLink(controllerName, controllerName, routeValues, ActionType.Retrieve);\n        }\n\n        /// <summary>\n        /// Generates a link to the resource controller, defaulting to the Retrieve action\n        /// </summary>\n        /// <param name=\"html\"></param>\n        /// <param name=\"controllerName\"></param>\n        /// <param name=\"linkText\"></param>\n        /// <param name=\"routeValues\"></param>\n        /// <returns></returns>\n        public static MvcHtmlString ResourceLink(this HtmlHelper html, string controllerName, string linkText, object routeValues)\n        {\n            return html.ResourceLink(controllerName, linkText, routeValues, ActionType.Retrieve);\n        }\n\n        /// <summary>\n        /// Generates a link to the resource controller\n        /// </summary>\n        /// <param name=\"html\"></param>\n        /// <param name=\"controllerName\"></param>\n        /// <param name=\"linkText\"></param>\n        /// <param name=\"routeValues\"></param>\n        /// <param name=\"actionType\"></param>\n        /// <returns></returns>\n        public static MvcHtmlString ResourceLink(this HtmlHelper html, string controllerName, string linkText, object routeValues, ActionType actionType)\n        {\n            switch (actionType)\n            {\n                case ActionType.GetUpdateForm:\n                    return html.RouteLink(linkText, controllerName + \"-editForm\", routeValues);\n                case ActionType.GetCreateForm:\n                    return html.RouteLink(linkText, controllerName + \"-createForm\", routeValues);\n                case ActionType.Retrieve:\n                case ActionType.Delete:\n                case ActionType.Update:\n                    return html.RouteLink(linkText, controllerName, routeValues);\n                case ActionType.Create:\n                    return html.RouteLink(linkText, controllerName + \"-create\", routeValues);\n                case ActionType.Index:\n                    return html.RouteLink(linkText, controllerName + \"-index\", routeValues);\n                default:\n                    throw new ArgumentOutOfRangeException(\"actionType\");\n            }\n        }\n\n        /// <summary>\n        /// Emits a hidden form variable for X-Http-Method-Override. The only valid values for actionType\n        /// are ActionType.Delete and ActionType.Update\n        /// </summary>\n        /// <param name=\"html\"></param>\n        /// <param name=\"actionType\"></param>\n        /// <returns></returns>\n        public static MvcHtmlString HttpMethodOverride(this HtmlHelper html, ActionType actionType)\n        {\n            if (actionType != ActionType.Delete && actionType != ActionType.Update)\n            {\n                throw new ArgumentOutOfRangeException(\"actionType\");\n            }\n            return html.HttpMethodOverride(actionType == ActionType.Delete ? \"DELETE\" : \"PUT\");\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Resources/HttpRequestBaseExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Net.Mime;\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.Resources\n{\n    /// <summary>\n    /// HttpRequestBase extension methods that call directly into the DefaultFormatHelper\n    /// </summary>\n    public static class HttpRequestBaseExtensions\n    {\n        public static ContentType GetRequestFormat(this HttpRequestBase request)\n        {\n            return DefaultFormatHelper.GetRequestFormat(request, true);\n        }\n\n        public static IEnumerable<ContentType> GetResponseFormats(this HttpRequestBase request)\n        {\n            return DefaultFormatHelper.GetResponseFormats(request);\n        }\n\n        internal static bool HasBody(this HttpRequestBase request)\n        {\n            return request.ContentLength > 0 || String.Compare(\"chunked\", request.Headers[\"Transfer-Encoding\"], StringComparison.OrdinalIgnoreCase) == 0;\n        }\n\n        public static bool IsBrowserRequest(this HttpRequestBase request)\n        {\n            return DefaultFormatHelper.IsBrowserRequest(request);\n        }\n\n        public static bool IsHttpMethod(this HttpRequestBase request, HttpVerbs httpMethod)\n        {\n            return request.IsHttpMethod(httpMethod, false);\n        }\n\n        public static bool IsHttpMethod(this HttpRequestBase request, string httpMethod)\n        {\n            return request.IsHttpMethod(httpMethod, false);\n        }\n\n        // CODEREVIEW: this implementation kind of misses the point of HttpVerbs\n        // by falling back to string comparison, consider something better\n        // also, how do we keep this switch in sync?\n        public static bool IsHttpMethod(this HttpRequestBase request, HttpVerbs httpMethod, bool allowOverride)\n        {\n            switch (httpMethod)\n            {\n                case HttpVerbs.Get:\n                    return request.IsHttpMethod(\"GET\", allowOverride);\n                case HttpVerbs.Post:\n                    return request.IsHttpMethod(\"POST\", allowOverride);\n                case HttpVerbs.Put:\n                    return request.IsHttpMethod(\"PUT\", allowOverride);\n                case HttpVerbs.Delete:\n                    return request.IsHttpMethod(\"DELETE\", allowOverride);\n                case HttpVerbs.Head:\n                    return request.IsHttpMethod(\"HEAD\", allowOverride);\n                case HttpVerbs.Patch:\n                    return request.IsHttpMethod(\"PATCH\", allowOverride);\n                case HttpVerbs.Options:\n                    return request.IsHttpMethod(\"OPTIONS\", allowOverride);\n                default:\n                    // CODEREVIEW: does this look reasonable?\n                    return request.IsHttpMethod(httpMethod.ToString().ToUpperInvariant(), allowOverride);\n            }\n        }\n\n        public static bool IsHttpMethod(this HttpRequestBase request, string httpMethod, bool allowOverride)\n        {\n            string requestHttpMethod = allowOverride ? request.GetHttpMethodOverride() : request.HttpMethod;\n            return String.Equals(requestHttpMethod, httpMethod, StringComparison.OrdinalIgnoreCase);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Resources/IEnumerableExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace Microsoft.Web.Mvc.Resources\n{\n    public static class IEnumerableExtensions\n    {\n        /// <summary>\n        /// Convenience API to allow an IEnumerable{T} (such as returned by Linq2Sql) to be serialized by DataContractSerilizer\n        /// </summary>\n        /// <typeparam name=\"T\"></typeparam>\n        /// <param name=\"collection\"></param>\n        /// <returns></returns>\n        public static IEnumerable<T> AsSerializable<T>(this IEnumerable<T> collection) where T : class\n        {\n            return new IEnumerableWrapper<T>(collection);\n        }\n\n        // This wrapper allows IEnumerable<T> to be serialized by DataContractSerilizer\n        // it implements the minimal amount of surface needed for serialization.\n        private class IEnumerableWrapper<T> : IEnumerable<T>\n            where T : class\n        {\n            private IEnumerable<T> _collection;\n\n            // The DataContractSerilizer needs a default constructor to ensure the object can be\n            // deserialized. We have a dummy one since we don't actually need deserialization.\n            public IEnumerableWrapper()\n            {\n                throw new NotImplementedException();\n            }\n\n            internal IEnumerableWrapper(IEnumerable<T> collection)\n            {\n                this._collection = collection;\n            }\n\n            // The DataContractSerilizer needs an Add method to ensure the object can be\n            // deserialized. We have a dummy one since we don't actually need deserialization.\n            [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"Needed to satisfy the deserialization contract\")]\n            [SuppressMessage(\"Microsoft.Usage\", \"CA1801:ReviewUnusedParameters\", MessageId = \"item\", Justification = \"Needed to satisfy the deserialization contract\")]\n            public void Add(T item)\n            {\n                throw new NotImplementedException();\n            }\n\n            public IEnumerator<T> GetEnumerator()\n            {\n                return this._collection.GetEnumerator();\n            }\n\n            IEnumerator IEnumerable.GetEnumerator()\n            {\n                return ((IEnumerable)this._collection).GetEnumerator();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Resources/IRequestFormatHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Mime;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.Resources\n{\n    /// <summary>\n    /// Extensibility mechanism for deserializing data in additional formats.\n    /// FormatManager.Current.RequestFormatHandlers contains the list of request formats\n    /// supported by the web application\n    /// </summary>\n    public interface IRequestFormatHandler\n    {\n        /// <summary>\n        /// Returns true if the handler can deserialize request's content type\n        /// </summary>\n        /// <param name=\"requestFormat\"></param>\n        /// <returns></returns>\n        bool CanDeserialize(ContentType requestFormat);\n\n        /// <summary>\n        /// Deserialize the request body based on model binding context and return the object.\n        /// Note that the URI parameters are handled by the base infrastructure.\n        /// </summary>\n        /// <param name=\"controllerContext\"></param>\n        /// <param name=\"bindingContext\"></param>\n        /// <param name=\"requestFormat\"></param>\n        /// <returns></returns>\n        object Deserialize(ControllerContext controllerContext, ModelBindingContext bindingContext, ContentType requestFormat);\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Resources/IResponseFormatHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Mime;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.Resources\n{\n    /// <summary>\n    /// Extensibility mechanism for serializing response in\n    /// additional formats. FormatManager.Current.RequestFormatHandlers contains the list of request formats\n    /// supported by the web application\n    /// </summary>\n    public interface IResponseFormatHandler\n    {\n        /// <summary>\n        /// The preferred friendly name for the handled format\n        /// </summary>\n        string FriendlyName { get; }\n\n        /// <summary>\n        /// Return true if the specified friendly name ('xml' for instance) can\n        /// be mapped to a content type ('application/xml' for instance). If the mapping\n        /// can be performed return the content type that the friendlyName maps to\n        /// </summary>\n        /// <param name=\"friendlyName\"></param>\n        /// <param name=\"contentType\"></param>\n        /// <returns></returns>\n        bool TryMapFormatFriendlyName(string friendlyName, out ContentType contentType);\n\n        /// <summary>\n        /// Return true if the specified response format can be serialized\n        /// </summary>\n        /// <param name=\"responseFormat\"></param>\n        /// <returns></returns>\n        bool CanSerialize(ContentType responseFormat);\n\n        /// <summary>\n        /// Serialize the model into the response body in the specified response format\n        /// </summary>\n        /// <param name=\"context\"></param>\n        /// <param name=\"model\"></param>\n        /// <param name=\"responseFormat\"></param>\n        void Serialize(ControllerContext context, object model, ContentType responseFormat);\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Resources/JsonFormatHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Net.Mime;\nusing System.Runtime.Serialization.Json;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.Resources\n{\n    public class JsonFormatHandler : IRequestFormatHandler, IResponseFormatHandler\n    {\n        public string FriendlyName\n        {\n            get { return \"Json\"; }\n        }\n\n        public bool CanDeserialize(ContentType requestFormat)\n        {\n            return requestFormat != null && IsCompatibleMediaType(requestFormat.MediaType);\n        }\n\n        public object Deserialize(ControllerContext controllerContext, ModelBindingContext bindingContext, ContentType requestFormat)\n        {\n            DataContractJsonSerializer json = new DataContractJsonSerializer(bindingContext.ModelType);\n            return json.ReadObject(controllerContext.HttpContext.Request.InputStream);\n        }\n\n        public bool CanSerialize(ContentType responseFormat)\n        {\n            return responseFormat != null && IsCompatibleMediaType(responseFormat.MediaType);\n        }\n\n        public void Serialize(ControllerContext context, object model, ContentType responseFormat)\n        {\n            DataContractJsonActionResult json = new DataContractJsonActionResult(model, responseFormat);\n            json.ExecuteResult(context);\n        }\n\n        protected virtual bool IsCompatibleMediaType(string mediaType)\n        {\n            return (mediaType == \"text/json\" || mediaType == \"application/json\");\n        }\n\n        public bool TryMapFormatFriendlyName(string friendlyName, out ContentType contentType)\n        {\n            if (String.Equals(friendlyName, this.FriendlyName, StringComparison.OrdinalIgnoreCase))\n            {\n                contentType = new ContentType(\"application/json\");\n                return true;\n            }\n            contentType = null;\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Resources/MultiFormatActionResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Net;\nusing System.Net.Mime;\nusing System.Web;\nusing System.Web.Mvc;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc.Resources\n{\n    /// <summary>\n    /// Returns the response in the format specified by the request. By default, supports returning the model\n    /// as a HTML view, XML and JSON.\n    /// If the response format requested is not supported, then the NotAcceptable status code is returned\n    /// </summary>\n    [SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"Multi\", Justification = \"FxCop won't accept this in the custom dictionary, so we're suppressing it in source\")]\n    public class MultiFormatActionResult : ActionResult\n    {\n        private object _model;\n        private ContentType _responseFormat;\n        private HttpStatusCode _statusCode;\n\n        public MultiFormatActionResult(object model, ContentType responseFormat)\n            : this(model, responseFormat, HttpStatusCode.OK)\n        {\n        }\n\n        public MultiFormatActionResult(object model, ContentType responseFormat, HttpStatusCode statusCode)\n        {\n            _model = model;\n            _responseFormat = responseFormat;\n            _statusCode = statusCode;\n        }\n\n        public override void ExecuteResult(ControllerContext context)\n        {\n            if (!TryExecuteResult(context, this._model, this._responseFormat))\n            {\n                throw new HttpException((int)HttpStatusCode.NotAcceptable, String.Format(CultureInfo.CurrentCulture, MvcResources.Resources_UnsupportedFormat, this._responseFormat));\n            }\n        }\n\n        public virtual bool TryExecuteResult(ControllerContext context, object model, ContentType responseFormat)\n        {\n            if (!FormatManager.Current.CanSerialize(responseFormat))\n            {\n                return false;\n            }\n            context.HttpContext.Response.ClearContent();\n            context.HttpContext.Response.StatusCode = (int)_statusCode;\n            FormatManager.Current.Serialize(context, model, responseFormat);\n            return true;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Resources/RequestContextExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Mime;\nusing System.Web.Routing;\n\nnamespace Microsoft.Web.Mvc.Resources\n{\n    /// <summary>\n    /// RequestContext extension methods that call directly into the registered FormatHelper\n    /// </summary>\n    public static class RequestContextExtensions\n    {\n        public static ContentType GetRequestFormat(this RequestContext requestContext)\n        {\n            return FormatManager.Current.FormatHelper.GetRequestFormat(requestContext);\n        }\n\n        public static IEnumerable<ContentType> GetResponseFormats(this RequestContext requestContext)\n        {\n            return FormatManager.Current.FormatHelper.GetResponseFormats(requestContext);\n        }\n\n        public static bool IsBrowserRequest(this RequestContext requestContext)\n        {\n            return FormatManager.Current.FormatHelper.IsBrowserRequest(requestContext);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Resources/ResourceControllerFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Net;\nusing System.Net.Mime;\nusing System.Text;\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Web.Routing;\nusing System.Web.SessionState;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc.Resources\n{\n    /// <summary>\n    /// Specialized ControllerFactory that augments the base controller factory to make it RESTful - specifically, adding\n    /// support for multiple formats, HTTP method based dispatch to controller methods and HTTP error handling\n    /// </summary>\n    public class ResourceControllerFactory : IControllerFactory\n    {\n        private const string RestActionToken = \"$REST$\";\n\n        private IControllerFactory _inner;\n\n        public ResourceControllerFactory()\n        {\n            _inner = ControllerBuilder.Current.GetControllerFactory();\n        }\n\n        public ResourceControllerFactory(IControllerFactory inner)\n        {\n            _inner = inner;\n        }\n\n        public IController CreateController(RequestContext requestContext, string controllerName)\n        {\n            IController ic = _inner.CreateController(requestContext, controllerName);\n            Controller c = ic as Controller;\n            if (c != null && WebApiEnabledAttribute.IsDefined(c))\n            {\n                IActionInvoker iai = c.ActionInvoker;\n                ControllerActionInvoker cai = iai as ControllerActionInvoker;\n                if (cai != null)\n                {\n                    c.ActionInvoker = new ResourceControllerActionInvoker();\n\n                    string actionName = requestContext.RouteData.Values[\"action\"] as string;\n                    if (String.IsNullOrEmpty(actionName))\n                    {\n                        // set it to a well known dummy value to avoid not having an action as that would prevent the fixup\n                        // code in ResourceControllerActionInvoker, which is based on ActionDescriptor, from running\n                        requestContext.RouteData.Values[\"action\"] = RestActionToken;\n                    }\n                }\n            }\n            return ic;\n        }\n\n        public SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName)\n        {\n            return _inner.GetControllerSessionBehavior(requestContext, controllerName);\n        }\n\n        public void ReleaseController(IController controller)\n        {\n            _inner.ReleaseController(controller);\n        }\n\n        // This ActionInvoker allows us to dispatch to a controller when no action was provided by the routing\n        // infrastructure, but the information is available in the request's HTTP verb (GET/PUT/POST/DELETE)\n        private class ResourceControllerActionInvoker : ControllerActionInvoker\n        {\n            protected override ActionDescriptor FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, string actionName)\n            {\n                if (actionName == RestActionToken)\n                {\n                    // cleanup the restActionToken we set earlier\n                    controllerContext.RequestContext.RouteData.Values[\"action\"] = null;\n\n                    List<ActionDescriptor> matches = new List<ActionDescriptor>();\n                    foreach (ActionDescriptor ad in controllerDescriptor.GetCanonicalActions())\n                    {\n                        object[] acceptVerbs = ad.GetCustomAttributes(typeof(AcceptVerbsAttribute), false);\n                        if (acceptVerbs.Length > 0)\n                        {\n                            foreach (object o in acceptVerbs)\n                            {\n                                AcceptVerbsAttribute ava = o as AcceptVerbsAttribute;\n                                if (ava != null)\n                                {\n                                    if (ava.Verbs.Contains(controllerContext.HttpContext.Request.GetHttpMethodOverride().ToUpperInvariant()))\n                                    {\n                                        matches.Add(ad);\n                                    }\n                                }\n                            }\n                        }\n                    }\n                    switch (matches.Count)\n                    {\n                        case 0:\n                            break;\n                        case 1:\n                            ActionDescriptor ad = matches[0];\n                            actionName = ad.ActionName;\n                            controllerContext.RequestContext.RouteData.Values[\"action\"] = actionName;\n                            return ad;\n                        default:\n                            StringBuilder matchesString = new StringBuilder(matches[0].ActionName);\n                            for (int index = 1; index < matches.Count; index++)\n                            {\n                                matchesString.Append(\", \");\n                                matchesString.Append(matches[index].ActionName);\n                            }\n                            return new ResourceErrorActionDescriptor(\n                                controllerDescriptor,\n                                HttpStatusCode.Conflict,\n                                String.Format(\n                                    CultureInfo.CurrentCulture,\n                                    MvcResources.ResourceControllerFactory_ConflictingActions,\n                                    controllerDescriptor.ControllerName,\n                                    matchesString));\n                    }\n                }\n                return base.FindAction(controllerContext, controllerDescriptor, actionName) ??\n                       new ResourceErrorActionDescriptor(\n                           controllerDescriptor,\n                           HttpStatusCode.NotFound,\n                           String.Format(\n                               CultureInfo.CurrentCulture,\n                               MvcResources.ResourceControllerFactory_NoActions,\n                               controllerDescriptor.ControllerName));\n            }\n\n            // This class is used when we don't find an ActionDescriptor or find multiple matches\n            // in this case we want to return an error response but throwing an HttpException from\n            // FindAction bypasses the InvokeExceptionFilters, so instead we throw in this custom ActionDescriptor\n            private class ResourceErrorActionDescriptor : ActionDescriptor\n            {\n                private ControllerDescriptor controllerDescriptor;\n                private string message;\n                private HttpStatusCode statusCode;\n\n                public ResourceErrorActionDescriptor(ControllerDescriptor controllerDescriptor, HttpStatusCode statusCode, string message)\n                {\n                    this.message = message;\n                    this.statusCode = statusCode;\n                    this.controllerDescriptor = controllerDescriptor;\n                }\n\n                public override string ActionName\n                {\n                    get { return RestActionToken; }\n                }\n\n                public override ControllerDescriptor ControllerDescriptor\n                {\n                    get { return this.controllerDescriptor; }\n                }\n\n                public override object Execute(ControllerContext controllerContext, IDictionary<string, object> parameters)\n                {\n                    HttpException he = new HttpException((int)this.statusCode, this.message);\n                    ResourceErrorActionResult rear;\n                    if (!WebApiEnabledAttribute.TryGetErrorResult2(controllerContext.RequestContext, he, out rear))\n                    {\n                        rear = new ResourceErrorActionResult(new HttpException((int)this.statusCode, this.message), new ContentType(\"text/plain\"));\n                    }\n                    return rear;\n                }\n\n                public override ParameterDescriptor[] GetParameters()\n                {\n                    return new ParameterDescriptor[0];\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Resources/ResourceErrorActionResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Mime;\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.Resources\n{\n    /// <summary>\n    /// Action result for returning HTTP errors that result from performing operations on resources, including\n    /// an optional details in the HTTP body\n    /// </summary>\n    public class ResourceErrorActionResult : ActionResult\n    {\n        private object details;\n        private ContentType responseFormat;\n        private HttpStatusCode statusCode;\n\n        /// <summary>\n        /// Sends back a response using the status code in the HttpException.\n        /// The response body contains a details serialized in the responseFormat.\n        /// If the HttpException.Data has a key named \"details\", its value is used as the response body.\n        /// If there is no such key, HttpException.ToString() is used as the response body.\n        /// </summary>\n        /// <param name=\"httpException\"></param>\n        /// <param name=\"responseFormat\"></param>\n        public ResourceErrorActionResult(HttpException httpException, ContentType responseFormat)\n        {\n            this.statusCode = (HttpStatusCode)httpException.GetHttpCode();\n            this.details = httpException.Data.Contains(\"details\") ? httpException.Data[\"details\"] : httpException.ToString();\n            this.responseFormat = responseFormat;\n        }\n\n        public override void ExecuteResult(ControllerContext context)\n        {\n            if (this.details != null)\n            {\n                MultiFormatActionResult rar = new MultiFormatActionResult(this.details, this.responseFormat, this.statusCode);\n                if (rar.TryExecuteResult(context, this.details, this.responseFormat))\n                {\n                    return;\n                }\n            }\n            context.HttpContext.Response.ClearContent();\n            context.HttpContext.Response.StatusCode = (int)this.statusCode;\n            context.HttpContext.Response.TrySkipIisCustomErrors = true;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Resources/ResourceModelBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Net;\nusing System.Net.Mime;\nusing System.Web;\nusing System.Web.Mvc;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc.Resources\n{\n    /// <summary>\n    /// ModelBinder implementation that augments the inner model binder with support for binding to other formats -\n    /// XML and JSON by default.\n    /// </summary>\n    public class ResourceModelBinder : IModelBinder\n    {\n        private IModelBinder _inner;\n\n        /// <summary>\n        /// Wraps the ModelBinders.Binders.DefaultBinder\n        /// </summary>\n        public ResourceModelBinder()\n            : this(ModelBinders.Binders.DefaultBinder)\n        {\n        }\n\n        public ResourceModelBinder(IModelBinder inner)\n        {\n            this._inner = inner;\n        }\n\n        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)\n        {\n            if (WebApiEnabledAttribute.IsDefined(controllerContext.Controller))\n            {\n                if (!controllerContext.RouteData.Values.ContainsKey(bindingContext.ModelName) && controllerContext.HttpContext.Request.HasBody())\n                {\n                    ContentType requestFormat = controllerContext.RequestContext.GetRequestFormat();\n                    object model;\n                    if (TryBindModel(controllerContext, bindingContext, requestFormat, out model))\n                    {\n                        bindingContext.ModelMetadata.Model = model;\n                        MyDefaultModelBinder dmb = new MyDefaultModelBinder();\n                        dmb.CallOnModelUpdated(controllerContext, bindingContext);\n                        if (!MyDefaultModelBinder.IsModelValid(bindingContext))\n                        {\n                            List<ModelError> details = new List<ModelError>();\n                            foreach (ModelState ms in bindingContext.ModelState.Values)\n                            {\n                                foreach (ModelError me in ms.Errors)\n                                {\n                                    details.Add(me);\n                                }\n                            }\n                            HttpException failure = new HttpException((int)HttpStatusCode.ExpectationFailed, \"Invalid Model\");\n                            failure.Data[\"details\"] = details;\n                            throw failure;\n                        }\n                        return model;\n                    }\n                    throw new HttpException((int)HttpStatusCode.UnsupportedMediaType, String.Format(CultureInfo.CurrentCulture, MvcResources.Resources_UnsupportedMediaType, (requestFormat == null ? String.Empty : requestFormat.MediaType)));\n                }\n            }\n            return this._inner.BindModel(controllerContext, bindingContext);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1007:UseGenericsWhereAppropriate\", Justification = \"This is an existing API; this would be a breaking change\")]\n        public bool TryBindModel(ControllerContext controllerContext, ModelBindingContext bindingContext, ContentType requestFormat, out object model)\n        {\n            if (requestFormat != null && String.Compare(requestFormat.MediaType, FormatManager.UrlEncoded, StringComparison.OrdinalIgnoreCase) == 0)\n            {\n                model = this._inner.BindModel(controllerContext, bindingContext);\n                return true;\n            }\n            if (!FormatManager.Current.TryDeserialize(controllerContext, bindingContext, requestFormat, out model))\n            {\n                model = null;\n                return false;\n            }\n            return true;\n        }\n\n        private class MyDefaultModelBinder : DefaultModelBinder\n        {\n            public void CallOnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)\n            {\n                OnModelUpdated(controllerContext, bindingContext);\n            }\n\n            internal static new bool IsModelValid(ModelBindingContext bindingContext)\n            {\n                return DefaultModelBinder.IsModelValid(bindingContext);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Resources/ResourceRedirectToRouteResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.Resources\n{\n    /// <summary>\n    /// Augments the RedirectToRouteResult behavior by sending Created HTTP status code in responses to POST, OK HTTP status code otherwise\n    /// </summary>\n    internal class ResourceRedirectToRouteResult : ActionResult\n    {\n        private RedirectToRouteResult inner;\n\n        public ResourceRedirectToRouteResult(RedirectToRouteResult inner)\n        {\n            this.inner = inner;\n        }\n\n        public override void ExecuteResult(ControllerContext context)\n        {\n            // call the base which we expect to be setting the Location header\n            this.inner.ExecuteResult(context);\n\n            if (!context.RequestContext.IsBrowserRequest())\n            {\n                // on POST we return Created, otherwise (EG: DELETE) we return OK\n                context.HttpContext.Response.ClearContent();\n                context.HttpContext.Response.StatusCode = context.HttpContext.Request.IsHttpMethod(HttpVerbs.Post, true) ? (int)HttpStatusCode.Created : (int)HttpStatusCode.OK;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Resources/RouteCollectionExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Mvc;\nusing System.Web.Routing;\n\nnamespace Microsoft.Web.Mvc.Resources\n{\n    public static class RouteCollectionExtensions\n    {\n        /// <summary>\n        /// Adds the routes to enable RESTful routing of requests to specified controller. The controllerName is the URL prefix to the controller.\n        /// The routeSuffix is used for more specific routing in the resource. For example, a controllerName of \"books\" and a routeSuffix of \"{id}\" will\n        /// result in the following routes being registered for the controller:\n        /// ~/books/, ~/books/{id} to the resource,\n        /// ~/books/CreateForm to the CreateForm controller action,\n        /// ~/books/{id}/EditForm to the EditForm controller action\n        /// </summary>\n        /// <param name=\"routes\"></param>\n        /// <param name=\"controllerName\"></param>\n        /// <param name=\"routeSuffix\"></param>\n        public static void MapResourceRoute(this RouteCollection routes, string controllerName, string routeSuffix)\n        {\n            routes.MapResourceRoute(controllerName, null, routeSuffix, null);\n        }\n\n        /// <summary>\n        /// Adds the routes to enable RESTful routing of requests to specified controller. The controllerName is the URL prefix to the controller.\n        /// The routeSuffix is used for more specific routing in the resource. For example, a controllerName of \"books\" and a routeSuffix of \"{id}\" will\n        /// result in the following routes being registered for the controller:\n        /// ~/books/, ~/books/{id} to the resource,\n        /// ~/books/CreateForm to the CreateForm controller action,\n        /// ~/books/{id}/EditForm to the EditForm controller action\n        /// </summary>\n        /// <param name=\"routes\"></param>\n        /// <param name=\"controllerName\"></param>\n        /// <param name=\"routeSuffix\"></param>\n        /// <param name=\"constraints\"></param>\n        public static void MapResourceRoute(this RouteCollection routes, string controllerName, string routeSuffix, object constraints)\n        {\n            routes.MapResourceRoute(controllerName, null, routeSuffix, constraints);\n        }\n\n        /// <summary>\n        /// Adds the routes to enable RESTful routing of requests to specified controller. The routePrefix is the URL prefix to the controller.\n        /// The routeSuffix is used for more specific routing in the resource. For example, a routePrefix of \"books\" and a routeSuffix of \"{id}\" will\n        /// result in the following routes being registered for the controller:\n        /// ~/books/, ~/books/{id} to the resource,\n        /// ~/books/CreateForm to the CreateForm controller action,\n        /// ~/books/{id}/EditForm to the EditForm controller action\n        /// </summary>\n        /// <param name=\"routes\"></param>\n        /// <param name=\"controllerName\"></param>\n        /// <param name=\"routePrefix\"></param>\n        /// <param name=\"routeSuffix\"></param>\n        public static void MapResourceRoute(this RouteCollection routes, string controllerName, string routePrefix, string routeSuffix)\n        {\n            routes.MapResourceRoute(controllerName, routePrefix, routeSuffix, null);\n        }\n\n        /// <summary>\n        /// Adds the routes to enable RESTful routing of requests to specified controller. The routePrefix is the URL prefix to the controller.\n        /// The routeSuffix is used for more specific routing in the resource. For example, a routePrefix of \"books\" and a routeSuffix of \"{id}\" will\n        /// result in the following routes being registered for the controller:\n        /// ~/books/, ~/books/{id} to the resource,\n        /// ~/books/CreateForm to the CreateForm controller action,\n        /// ~/books/{id}/EditForm to the EditForm controller action\n        /// </summary>\n        /// <param name=\"routes\"></param>\n        /// <param name=\"controllerName\"></param>\n        /// <param name=\"routePrefix\"></param>\n        /// <param name=\"routeSuffix\"></param>\n        /// <param name=\"constraints\"></param>\n        public static void MapResourceRoute(this RouteCollection routes, string controllerName, string routePrefix, string routeSuffix, object constraints)\n        {\n            if (String.IsNullOrEmpty(routePrefix))\n            {\n                routePrefix = controllerName;\n            }\n            else\n            {\n                routePrefix = routePrefix + \"/\" + controllerName;\n            }\n            if (!String.IsNullOrEmpty(routeSuffix))\n            {\n                routeSuffix = \"/\" + routeSuffix;\n            }\n\n            routes.MapRoute(\n                controllerName + \"-editForm\",\n                routePrefix + routeSuffix + \"/EditForm\",\n                new { controller = controllerName, action = \"EditForm\" },\n                constraints);\n            routes.MapRoute(\n                controllerName + \"-createForm\",\n                routePrefix + \"/CreateForm\",\n                new { controller = controllerName, action = \"CreateForm\" });\n            routes.MapRoute(\n                controllerName,\n                routePrefix + routeSuffix,\n                new { controller = controllerName },\n                constraints);\n            routes.MapRoute(\n                controllerName + \"-create\",\n                routePrefix,\n                new { controller = controllerName, action = \"Create\" },\n                new { postOnly = new HttpMethodConstraint(\"POST\") });\n            routes.MapRoute(\n                controllerName + \"-index\",\n                routePrefix,\n                new { controller = controllerName, action = \"Index\" });\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA1801:ReviewUnusedParameters\", MessageId = \"controller\", Justification = \"This is an extension method, the parameter is necessary to provide a place to hook the method\")]\n        public static string GetResourceRouteName(this Controller controller, string controllerName, ActionType actionType)\n        {\n            switch (actionType)\n            {\n                case ActionType.GetUpdateForm:\n                    return controllerName + \"-editForm\";\n                case ActionType.GetCreateForm:\n                    return controllerName + \"-createForm\";\n                case ActionType.Retrieve:\n                case ActionType.Delete:\n                case ActionType.Update:\n                    return controllerName;\n                case ActionType.Create:\n                    return controllerName + \"-create\";\n                case ActionType.Index:\n                    return controllerName + \"-index\";\n                default:\n                    throw new ArgumentOutOfRangeException(\"actionType\");\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Resources/UriHelperExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.Resources\n{\n    public static class UriHelperExtensions\n    {\n        /// <summary>\n        /// Generates the route URL for the resource controller's Retrieve action\n        /// </summary>\n        /// <param name=\"url\"></param>\n        /// <param name=\"controllerName\"></param>\n        /// <param name=\"routeValues\"></param>\n        /// <returns></returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1055:UriReturnValuesShouldNotBeStrings\", Justification = \"The return value is not a regular URL since it may contain ~/ ASP.NET-specific characters\"), SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an Extension Method which allows the user to provide a strongly-typed argument via Expression\"), SuppressMessage(\"Microsoft.Design\", \"CA1011:ConsiderPassingBaseTypesAsParameters\", Justification = \"Need to be sure the passed-in argument is of type Controller::Action\")]\n        public static string ResourceUrl(this UrlHelper url, string controllerName, object routeValues)\n        {\n            return url.ResourceUrl(controllerName, routeValues, ActionType.Retrieve);\n        }\n\n        /// <summary>\n        /// Generates the route URL for the resource\n        /// </summary>\n        /// <param name=\"url\"></param>\n        /// <param name=\"controllerName\"></param>\n        /// <param name=\"routeValues\"></param>\n        /// <param name=\"actionType\"></param>\n        /// <returns></returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1055:UriReturnValuesShouldNotBeStrings\", Justification = \"The return value is not a regular URL since it may contain ~/ ASP.NET-specific characters\"), SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an Extension Method which allows the user to provide a strongly-typed argument via Expression\"), SuppressMessage(\"Microsoft.Design\", \"CA1011:ConsiderPassingBaseTypesAsParameters\", Justification = \"Need to be sure the passed-in argument is of type Controller::Action\")]\n        public static string ResourceUrl(this UrlHelper url, string controllerName, object routeValues, ActionType actionType)\n        {\n            switch (actionType)\n            {\n                case ActionType.GetUpdateForm:\n                    return url.RouteUrl(controllerName + \"-editForm\", routeValues);\n                case ActionType.GetCreateForm:\n                    return url.RouteUrl(controllerName + \"-createForm\");\n                case ActionType.Retrieve:\n                case ActionType.Delete:\n                case ActionType.Update:\n                    return url.RouteUrl(controllerName, routeValues);\n                case ActionType.Create:\n                    return url.RouteUrl(controllerName + \"-create\");\n                case ActionType.Index:\n                    return url.RouteUrl(controllerName + \"-index\");\n                default:\n                    throw new ArgumentOutOfRangeException(\"actionType\");\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Resources/WebApiEnabledAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Net;\nusing System.Net.Mime;\nusing System.Text;\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Web.Routing;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc.Resources\n{\n    /// <summary>\n    /// Attribute indicating that the controller supports multiple formats (HTML, XML, JSON etc), HTTP method based dispatch\n    /// and HTTP error handling.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\n    [SuppressMessage(\"Microsoft.Performance\", \"CA1813:AvoidUnsealedAttributes\", Justification = \"This class is designed to be overridden\")]\n    public class WebApiEnabledAttribute : ActionFilterAttribute, IExceptionFilter\n    {\n        public WebApiEnabledAttribute()\n        {\n            this.StatusOnNullModel = HttpStatusCode.NotFound;\n        }\n\n        /// <summary>\n        /// The HTTP status code to use in case a null value is returned from the controller action method.\n        /// The default is NotFound\n        /// </summary>\n        public HttpStatusCode StatusOnNullModel { get; set; }\n\n        public static bool IsDefined(ControllerBase controller)\n        {\n            Type controllerType = controller.GetType();\n            WebApiEnabledAttribute[] rea = controllerType.GetCustomAttributes(typeof(WebApiEnabledAttribute), true) as WebApiEnabledAttribute[];\n            return rea != null && rea.Length > 0;\n        }\n\n        public override void OnActionExecuted(ActionExecutedContext filterContext)\n        {\n            MultiFormatActionResult multiFormatResult = filterContext.Result as MultiFormatActionResult;\n            if (multiFormatResult == null)\n            {\n                ViewResultBase viewResult = filterContext.Result as ViewResultBase;\n                if (viewResult != null && viewResult.ViewData != null)\n                {\n                    bool handled = false;\n                    foreach (ContentType responseFormat in filterContext.RequestContext.GetResponseFormats())\n                    {\n                        // CONSIDER: making this lookup optional if perf is an issue\n                        for (int i = 0; i < FormatManager.Current.ResponseFormatHandlers.Count; ++i)\n                        {\n                            IResponseFormatHandler handler = FormatManager.Current.ResponseFormatHandlers[i];\n                            if (handler.CanSerialize(responseFormat))\n                            {\n                                // we can't use the full ContentType's name (EG: \"text/xml\")\n                                // instead we use the FriendlyName on the matching IResponseFormatHandler\n                                string friendlyName = handler.FriendlyName;\n                                string viewName = viewResult.ViewName;\n                                if (String.IsNullOrEmpty(viewName))\n                                {\n                                    viewName = filterContext.RouteData.GetRequiredString(\"action\");\n                                }\n                                // CONSIDER: is this naming convention sufficient? look at extensibility (how can I customize the FindView process?)\n                                viewName = viewName + \".\" + friendlyName;\n                                // CONSIDER: ViewEngineCollection queries view engines in registration order and returns 1st match,\n                                // would it make sense to let the client provide a hint in case\n                                ViewEngineResult result = viewResult.ViewEngineCollection.FindView(filterContext, viewName, null);\n                                // ignore errors and fallback to default behavior\n                                if (result != null && result.View != null)\n                                {\n                                    Encoding encoding = Encoding.UTF8;\n                                    if (!String.IsNullOrEmpty(responseFormat.CharSet))\n                                    {\n                                        try\n                                        {\n                                            encoding = Encoding.GetEncoding(responseFormat.CharSet);\n                                        }\n                                        catch (ArgumentException)\n                                        {\n                                            throw new HttpException((int)HttpStatusCode.NotAcceptable, String.Format(CultureInfo.CurrentCulture, MvcResources.Resources_UnsupportedFormat, responseFormat));\n                                        }\n                                    }\n                                    responseFormat.CharSet = encoding.HeaderName;\n                                    filterContext.HttpContext.Response.ContentType = responseFormat.ToString();\n                                    filterContext.HttpContext.Response.ContentEncoding = encoding;\n                                    // we have set the Response.ContentType but know that the webforms view engine will override it\n                                    // a different ViewPage base class that sets this can be used to workaround this\n                                    // so we make the computed responseFormat available in ViewData\n                                    viewResult.ViewData[DefaultFormatHelper.ResponseFormatKey] = responseFormat;\n                                    viewResult.View = result.View;\n                                    viewResult.ViewName = viewName;\n                                    handled = true;\n                                    break;\n                                }\n                            }\n                        }\n                        if (handled)\n                        {\n                            break;\n                        }\n                        if (TryGetResult(viewResult, responseFormat, out multiFormatResult))\n                        {\n                            if (multiFormatResult != null)\n                            {\n                                filterContext.Result = multiFormatResult;\n                            }\n                            handled = true;\n                            break;\n                        }\n                    }\n                    if (!handled)\n                    {\n                        // if enumeration doesn't yield a handler the request is not acceptable\n                        // CONSIDER: returning all formats considered in the exception messages\n                        throw new HttpException((int)HttpStatusCode.NotAcceptable, \"None of the formats specified by the accept header is supported.\");\n                    }\n                }\n            }\n            base.OnActionExecuted(filterContext);\n            RedirectToRouteResult redirectResult = filterContext.Result as RedirectToRouteResult;\n            if (redirectResult != null && !filterContext.RequestContext.IsBrowserRequest())\n            {\n                filterContext.Result = new ResourceRedirectToRouteResult(redirectResult);\n            }\n        }\n\n        public void OnException(ExceptionContext filterContext)\n        {\n            if (filterContext.ExceptionHandled)\n            {\n                return;\n            }\n            HttpException he = filterContext.Exception as HttpException;\n            if (he != null)\n            {\n                ResourceErrorActionResult rear;\n                if (TryGetErrorResult2(filterContext.RequestContext, he, out rear))\n                {\n                    if (rear != null)\n                    {\n                        filterContext.Result = rear;\n                        filterContext.ExceptionHandled = true;\n                    }\n                    return;\n                }\n                // if enumeration doesn't yield a handler the request is not acceptable\n                // CONSIDER: returning all formats considered in the exception messages\n                throw new HttpException((int)HttpStatusCode.NotAcceptable, \"None of the formats specified by the accept header is supported.\");\n            }\n        }\n\n        public virtual bool TryGetErrorResult(HttpException exception, ContentType responseFormat, out ResourceErrorActionResult actionResult)\n        {\n            if (FormatManager.Current.CanSerialize(responseFormat))\n            {\n                actionResult = new ResourceErrorActionResult(exception, responseFormat);\n                return true;\n            }\n            switch (responseFormat.MediaType)\n            {\n                case \"application/octet-stream\":\n                case \"application/x-www-form-urlencoded\":\n                case \"text/html\":\n                case \"*/*\":\n                    actionResult = null;\n                    return true;\n                default:\n                    actionResult = null;\n                    return false;\n            }\n        }\n\n        public virtual bool TryGetResult(ViewResultBase viewResult, ContentType responseFormat, out MultiFormatActionResult actionResult)\n        {\n            if (FormatManager.Current.CanSerialize(responseFormat))\n            {\n                if (viewResult.ViewData.Model == null)\n                {\n                    throw new HttpException((int)this.StatusOnNullModel, this.StatusOnNullModel.ToString());\n                }\n                actionResult = new MultiFormatActionResult(viewResult.ViewData.Model, responseFormat);\n                return true;\n            }\n\n            switch (responseFormat.MediaType)\n            {\n                case \"application/octet-stream\":\n                case \"application/x-www-form-urlencoded\":\n                case \"text/html\":\n                case \"*/*\":\n                    actionResult = null;\n                    return true;\n                default:\n                    actionResult = null;\n                    return false;\n            }\n        }\n\n        internal static bool TryGetErrorResult2(RequestContext requestContext, HttpException he, out ResourceErrorActionResult actionResult)\n        {\n            foreach (ContentType responseFormat in requestContext.GetResponseFormats())\n            {\n                WebApiEnabledAttribute dummy = new WebApiEnabledAttribute();\n                if (dummy.TryGetErrorResult(he, responseFormat, out actionResult))\n                {\n                    return true;\n                }\n            }\n            actionResult = null;\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/Resources/XmlFormatHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Net.Mime;\nusing System.Runtime.Serialization;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc.Resources\n{\n    public class XmlFormatHandler : IRequestFormatHandler, IResponseFormatHandler\n    {\n        public string FriendlyName\n        {\n            get { return \"Xml\"; }\n        }\n\n        public bool CanDeserialize(ContentType requestFormat)\n        {\n            return requestFormat != null && IsCompatibleMediaType(requestFormat.MediaType);\n        }\n\n        public object Deserialize(ControllerContext controllerContext, ModelBindingContext bindingContext, ContentType requestFormat)\n        {\n            DataContractSerializer xml = new DataContractSerializer(bindingContext.ModelType, null, Int32.MaxValue, true, true, null);\n            return xml.ReadObject(controllerContext.HttpContext.Request.InputStream);\n        }\n\n        public bool CanSerialize(ContentType responseFormat)\n        {\n            return responseFormat != null && IsCompatibleMediaType(responseFormat.MediaType);\n        }\n\n        public void Serialize(ControllerContext context, object model, ContentType responseFormat)\n        {\n            DataContractXmlActionResult xml = new DataContractXmlActionResult(model, responseFormat);\n            xml.ExecuteResult(context);\n        }\n\n        protected virtual bool IsCompatibleMediaType(string mediaType)\n        {\n            return (mediaType == \"text/xml\" || mediaType == \"application/xml\");\n        }\n\n        public bool TryMapFormatFriendlyName(string friendlyName, out ContentType contentType)\n        {\n            if (String.Equals(friendlyName, this.FriendlyName, StringComparison.OrdinalIgnoreCase))\n            {\n                contentType = new ContentType(\"application/xml\");\n                return true;\n            }\n            contentType = null;\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ScriptExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Mvc;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc\n{\n    public static class ScriptExtensions\n    {\n        public static MvcHtmlString Script(this HtmlHelper helper, string releaseFile)\n        {\n            return Script(helper, releaseFile, releaseFile);\n        }\n\n        public static MvcHtmlString Script(this HtmlHelper helper, string releaseFile, string debugFile)\n        {\n            if (String.IsNullOrEmpty(releaseFile))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"releaseFile\");\n            }\n            if (String.IsNullOrEmpty(debugFile))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"debugFile\");\n            }\n\n            string src;\n            string file = helper.ViewContext.HttpContext.IsDebuggingEnabled ? debugFile : releaseFile;\n            if (IsRelativeToDefaultPath(file))\n            {\n                src = \"~/Scripts/\" + file;\n            }\n            else\n            {\n                src = file;\n            }\n\n            TagBuilder scriptTag = new TagBuilder(\"script\");\n            scriptTag.MergeAttribute(\"type\", \"text/javascript\");\n            scriptTag.MergeAttribute(\"src\", UrlHelper.GenerateContentUrl(src, helper.ViewContext.HttpContext));\n            return MvcHtmlString.Create(scriptTag.ToString(TagRenderMode.Normal));\n        }\n\n        internal static bool IsRelativeToDefaultPath(string file)\n        {\n            return !(file.StartsWith(\"~\", StringComparison.Ordinal) ||\n                     file.StartsWith(\"../\", StringComparison.Ordinal) ||\n                     file.StartsWith(\"/\", StringComparison.Ordinal) ||\n                     file.StartsWith(\"http://\", StringComparison.OrdinalIgnoreCase) ||\n                     file.StartsWith(\"https://\", StringComparison.OrdinalIgnoreCase));\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/SerializationExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Mvc;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc\n{\n    public static class SerializationExtensions\n    {\n        public static MvcHtmlString Serialize(this HtmlHelper htmlHelper, string name)\n        {\n            return SerializeInternal(htmlHelper, name, null, useViewData: true);\n        }\n\n        internal static MvcHtmlString Serialize(this HtmlHelper htmlHelper, string name, MvcSerializer serializer)\n        {\n            return SerializeInternal(htmlHelper, name, null, useViewData: true, serializer: serializer);\n        }\n\n        public static MvcHtmlString Serialize(this HtmlHelper htmlHelper, string name, object data)\n        {\n            return SerializeInternal(htmlHelper, name, data, useViewData: false);\n        }\n\n        internal static MvcHtmlString Serialize(this HtmlHelper htmlHelper, string name, object data, MvcSerializer serializer)\n        {\n            return SerializeInternal(htmlHelper, name, data, useViewData: false, serializer: serializer);\n        }\n\n        private static MvcHtmlString SerializeInternal(HtmlHelper htmlHelper, string name, object data, bool useViewData)\n        {\n            return SerializeInternal(htmlHelper, name, data, useViewData, null);\n        }\n\n        private static MvcHtmlString SerializeInternal(HtmlHelper htmlHelper, string name, object data, bool useViewData, MvcSerializer serializer)\n        {\n            if (htmlHelper == null)\n            {\n                throw new ArgumentNullException(\"htmlHelper\");\n            }\n\n            if (String.IsNullOrEmpty(name))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"name\");\n            }\n\n            name = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);\n            if (useViewData)\n            {\n                data = htmlHelper.ViewData.Eval(name);\n            }\n\n            string serializedData = (serializer ?? new MvcSerializer()).Serialize(data);\n\n            TagBuilder builder = new TagBuilder(\"input\");\n            builder.Attributes[\"type\"] = \"hidden\";\n            builder.Attributes[\"name\"] = name;\n            builder.Attributes[\"value\"] = serializedData;\n            return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ServerVariablesValueProviderFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing System.Globalization;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc\n{\n    public class ServerVariablesValueProviderFactory : ValueProviderFactory\n    {\n        public override IValueProvider GetValueProvider(ControllerContext controllerContext)\n        {\n            NameValueCollection nvc = controllerContext.HttpContext.Request.ServerVariables;\n            return new NameValueCollectionValueProvider(nvc, CultureInfo.InvariantCulture);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/SessionValueProviderFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc\n{\n    public class SessionValueProviderFactory : ValueProviderFactory\n    {\n        public override IValueProvider GetValueProvider(ControllerContext controllerContext)\n        {\n            HttpSessionStateBase session = controllerContext.HttpContext.Session;\n            if (session == null)\n            {\n                // session is disabled\n                return null;\n            }\n\n            Dictionary<string, object> backingStore = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);\n            foreach (string key in session)\n            {\n                if (key != null)\n                {\n                    backingStore[key] = session[key]; // copy to backing store\n                }\n            }\n\n            // use the invariant culture since Session contains serialized objects\n            return new DictionaryValueProvider<object>(backingStore, CultureInfo.InvariantCulture);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/SkipBindingAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]\n    public sealed class SkipBindingAttribute : CustomModelBinderAttribute\n    {\n        private static readonly NullBinder _nullBinder = new NullBinder();\n\n        public override IModelBinder GetBinder()\n        {\n            return _nullBinder;\n        }\n\n        private class NullBinder : IModelBinder\n        {\n            public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)\n            {\n                return null;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/TempDataValueProviderFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc\n{\n    public class TempDataValueProviderFactory : ValueProviderFactory\n    {\n        public override IValueProvider GetValueProvider(ControllerContext controllerContext)\n        {\n            TempDataDictionary tempData = controllerContext.Controller.TempData;\n            if (tempData.Count == 0)\n            {\n                // fast-track empty TempData\n                return null;\n            }\n\n            return new TempDataValueProvider(tempData);\n        }\n\n        /// <summary>\n        /// dummy struct that resembles Void but can be used in a generic context\n        /// </summary>\n        private struct TempDataVoid\n        {\n        }\n\n        private sealed class TempDataValueProvider : DictionaryValueProvider<TempDataVoid>\n        {\n            private readonly TempDataDictionary _tempData;\n\n            // use invariant culture since TempData should contain objects\n            public TempDataValueProvider(TempDataDictionary tempData)\n                : base(GetVoidDictionary(tempData), CultureInfo.InvariantCulture)\n            {\n                _tempData = tempData;\n            }\n\n            public override ValueProviderResult GetValue(string key)\n            {\n                object rawValue;\n\n                // TryGetValue will mark the entry for removal.\n                if (_tempData.TryGetValue(key, out rawValue))\n                {\n                    string attemptedValue = Convert.ToString(rawValue, CultureInfo.InvariantCulture);\n                    return new ValueProviderResult(rawValue, attemptedValue, CultureInfo.InvariantCulture);\n                }\n                else\n                {\n                    // no value found\n                    return null;\n                }\n            }\n\n            private static Dictionary<string, TempDataVoid> GetVoidDictionary(TempDataDictionary tempData)\n            {\n                // Create a special backing store that doesn't directly hold the values, since the DictionaryValueProvider\n                // enumerates over the backing store but enumerating over TempData marks everything for removal.\n                Dictionary<string, TempDataVoid> d = new Dictionary<string, TempDataVoid>(StringComparer.OrdinalIgnoreCase);\n\n                // Enumerating over TempDataDictionary.Keys doesn't mark them for removal.\n                foreach (string key in tempData.Keys)\n                {\n                    d[key] = default(TempDataVoid);\n                }\n\n                return d;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/TypeDescriptorHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.Mvc\n{\n    internal static class TypeDescriptorHelper\n    {\n        private static readonly MockMetadataProvider _mockMetadataProvider = new MockMetadataProvider();\n\n        public static ICustomTypeDescriptor Get(Type type)\n        {\n            return _mockMetadataProvider.GetTypeDescriptor(type);\n        }\n\n        // System.Web.Mvc.TypeDescriptorHelpers is internal, so this mock subclassed type provides\n        // access to it via the GetTypeDescriptor() virtual method.\n        private sealed class MockMetadataProvider : AssociatedMetadataProvider\n        {\n            protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)\n            {\n                throw new NotImplementedException();\n            }\n\n            public new ICustomTypeDescriptor GetTypeDescriptor(Type type)\n            {\n                return base.GetTypeDescriptor(type);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/TypeHelpers.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Linq;\n\nnamespace Microsoft.Web.Mvc\n{\n    internal static class TypeHelpers\n    {\n        public static Type ExtractGenericInterface(Type queryType, Type interfaceType)\n        {\n            Func<Type, bool> matchesInterface = t => t.IsGenericType && t.GetGenericTypeDefinition() == interfaceType;\n            return (matchesInterface(queryType)) ? queryType : queryType.GetInterfaces().FirstOrDefault(matchesInterface);\n        }\n\n        public static Type[] GetTypeArgumentsIfMatch(Type closedType, Type matchingOpenType)\n        {\n            if (!closedType.IsGenericType)\n            {\n                return null;\n            }\n\n            Type openType = closedType.GetGenericTypeDefinition();\n            return (matchingOpenType == openType) ? closedType.GetGenericArguments() : null;\n        }\n\n        public static bool IsCompatibleObject(Type type, object value)\n        {\n            return ((value == null && TypeAllowsNullValue(type)) || type.IsInstanceOfType(value));\n        }\n\n        public static bool IsNullableValueType(Type type)\n        {\n            return Nullable.GetUnderlyingType(type) != null;\n        }\n\n        public static bool TypeAllowsNullValue(Type type)\n        {\n            return (!type.IsValueType || IsNullableValueType(type));\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/UrlAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Text.RegularExpressions;\nusing System.Web.Mvc;\nusing Microsoft.Web.Mvc.Properties;\n\nnamespace Microsoft.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]\n    public sealed class UrlAttribute : DataTypeAttribute, IClientValidatable\n    {\n        private static Regex _regex = new Regex(@\"^(https?|ftp):\\/\\/(((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&'\\(\\)\\*\\+,;=]|:)*@)?(((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]))|((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.?)(:\\d*)?)(\\/((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&'\\(\\)\\*\\+,;=]|:|@)+(\\/(([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&'\\(\\)\\*\\+,;=]|:|@)*)*)?)?(\\?((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&'\\(\\)\\*\\+,;=]|:|@)|[\\uE000-\\uF8FF]|\\/|\\?)*)?(\\#((([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(%[\\da-f]{2})|[!\\$&'\\(\\)\\*\\+,;=]|:|@)|\\/|\\?)*)?$\", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);\n\n        public UrlAttribute()\n            : base(DataType.Url)\n        {\n            ErrorMessage = MvcResources.UrlAttribute_Invalid;\n        }\n\n        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)\n        {\n            yield return new ModelClientValidationRule\n            {\n                ValidationType = \"url\",\n                ErrorMessage = FormatErrorMessage(metadata.GetDisplayName())\n            };\n        }\n\n        public override bool IsValid(object value)\n        {\n            if (value == null)\n            {\n                return true;\n            }\n\n            string valueAsString = value as string;\n            return valueAsString != null && _regex.Match(valueAsString).Length > 0;\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ValueProviderUtil.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\n\nnamespace Microsoft.Web.Mvc\n{\n    internal static class ValueProviderUtil\n    {\n        public static bool IsPrefixMatch(string prefix, string testString)\n        {\n            if (testString == null)\n            {\n                return false;\n            }\n\n            if (prefix.Length == 0)\n            {\n                return true; // shortcut - non-null testString matches empty prefix\n            }\n\n            if (!testString.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))\n            {\n                return false; // prefix doesn't match\n            }\n\n            if (testString.Length == prefix.Length)\n            {\n                return true; // exact match\n            }\n\n            // invariant: testString.Length > prefix.Length\n            switch (testString[prefix.Length])\n            {\n                case '.':\n                case '[':\n                    return true; // known delimiters\n\n                default:\n                    return false; // not known delimiter\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.Mvc/ViewExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\nusing System.Web.Mvc;\nusing System.Web.Mvc.Html;\nusing System.Web.Routing;\nusing ExpressionHelper = Microsoft.Web.Mvc.Internal.ExpressionHelper;\n\nnamespace Microsoft.Web.Mvc\n{\n    public static class ViewExtensions\n    {\n        public static void RenderRoute(this HtmlHelper helper, RouteValueDictionary routeValues)\n        {\n            if (routeValues == null)\n            {\n                throw new ArgumentNullException(\"routeValues\");\n            }\n\n            string actionName = (string)routeValues[\"action\"];\n            helper.RenderAction(actionName, routeValues);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static void RenderAction<TController>(this HtmlHelper helper, Expression<Action<TController>> action) where TController : Controller\n        {\n            RouteValueDictionary rvd = ExpressionHelper.GetRouteValuesFromExpression(action);\n\n            foreach (var entry in helper.ViewContext.RouteData.Values)\n            {\n                if (!rvd.ContainsKey(entry.Key))\n                {\n                    rvd.Add(entry.Key, entry.Value);\n                }\n            }\n\n            RenderRoute(helper, rvd);\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.WebPages.OAuth/AuthenticationClientData.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing DotNetOpenAuth.AspNet;\n\nnamespace Microsoft.Web.WebPages.OAuth\n{\n    /// <summary>\n    /// Store display name and extra data of an IAuthenticationClient instance.\n    /// </summary>\n    public class AuthenticationClientData\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"AuthenticationClientData\"/> class.\n        /// </summary>\n        /// <param name=\"authenticationClient\">The authentication client.</param>\n        /// <param name=\"displayName\">The display name.</param>\n        /// <param name=\"extraData\">The data bag used to store extra data about this client</param>\n        public AuthenticationClientData(IAuthenticationClient authenticationClient, string displayName, IDictionary<string, object> extraData)\n        {\n            if (authenticationClient == null)\n            {\n                throw new ArgumentNullException(\"authenticationClient\");\n            }\n\n            AuthenticationClient = authenticationClient;\n            DisplayName = displayName;\n            ExtraData = extraData;\n        }\n\n        /// <summary>\n        /// Gets the authentication client.\n        /// </summary>\n        public IAuthenticationClient AuthenticationClient { get; private set; }\n\n        /// <summary>\n        /// Gets the display name.\n        /// </summary>\n        public string DisplayName { get; private set; }\n\n        /// <summary>\n        /// The data bag used to store extra data about this client.\n        /// </summary>\n        public IDictionary<string, object> ExtraData { get; private set; }\n    }\n}"
  },
  {
    "path": "src/Microsoft.Web.WebPages.OAuth/GlobalSuppressions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"Microsoft.Web.WebPages.OAuth\")]\n"
  },
  {
    "path": "src/Microsoft.Web.WebPages.OAuth/Microsoft.Web.WebPages.OAuth.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{4CBFC7D3-1600-4CE5-BC6B-AC7BC2D6F853}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>Microsoft.Web.WebPages.OAuth</RootNamespace>\n    <AssemblyName>Microsoft.Web.WebPages.OAuth</AssemblyName>\n    <DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>\n    <RunCodeAnalysis>$(CodeAnalysis)</RunCodeAnalysis>\n    <CodeAnalysisRuleSet>..\\Strict.ruleset</CodeAnalysisRuleSet>\n    <DefineConstants>$(DefineConstants);ASPNETWEBPAGES</DefineConstants>\n  </PropertyGroup>\n  <ItemGroup>\n    <CodeAnalysisDictionary Include=\"..\\CodeAnalysisDictionary.xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Reference Include=\"DotNetOpenAuth.AspNet, Version=4.0.0.0, Culture=neutral, PublicKeyToken=2780ccd10d57b246, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\..\\packages\\DotNetOpenAuth.AspNet.4.0.3.12153\\lib\\net40-full\\DotNetOpenAuth.AspNet.dll</HintPath>\n    </Reference>\n    <Reference Include=\"DotNetOpenAuth.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=2780ccd10d57b246, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\..\\packages\\DotNetOpenAuth.Core.4.0.3.12153\\lib\\net40-full\\DotNetOpenAuth.Core.dll</HintPath>\n    </Reference>\n    <Reference Include=\"DotNetOpenAuth.OAuth, Version=4.0.0.0, Culture=neutral, PublicKeyToken=2780ccd10d57b246, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\..\\packages\\DotNetOpenAuth.OAuth.Core.4.0.3.12153\\lib\\net40-full\\DotNetOpenAuth.OAuth.dll</HintPath>\n    </Reference>\n    <Reference Include=\"DotNetOpenAuth.OAuth.Consumer, Version=4.0.0.0, Culture=neutral, PublicKeyToken=2780ccd10d57b246, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\..\\packages\\DotNetOpenAuth.OAuth.Consumer.4.0.3.12153\\lib\\net40-full\\DotNetOpenAuth.OAuth.Consumer.dll</HintPath>\n    </Reference>\n    <Reference Include=\"DotNetOpenAuth.OpenId, Version=4.0.0.0, Culture=neutral, PublicKeyToken=2780ccd10d57b246, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\..\\packages\\DotNetOpenAuth.OpenId.Core.4.0.3.12153\\lib\\net40-full\\DotNetOpenAuth.OpenId.dll</HintPath>\n    </Reference>\n    <Reference Include=\"DotNetOpenAuth.OpenId.RelyingParty, Version=4.0.0.0, Culture=neutral, PublicKeyToken=2780ccd10d57b246, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\..\\packages\\DotNetOpenAuth.OpenId.RelyingParty.4.0.3.12153\\lib\\net40-full\\DotNetOpenAuth.OpenId.RelyingParty.dll</HintPath>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"System.Web.ApplicationServices\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\CommonAssemblyInfo.cs\">\n      <Link>Properties\\CommonAssemblyInfo.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\CommonResources.Designer.cs\">\n      <Link>Common\\CommonResources.Designer.cs</Link>\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>CommonResources.resx</DependentUpon>\n    </Compile>\n    <Compile Include=\"..\\GlobalSuppressions.cs\">\n      <Link>Common\\GlobalSuppressions.cs</Link>\n    </Compile>\n    <Compile Include=\"AuthenticationClientData.cs\" />\n    <Compile Include=\"GlobalSuppressions.cs\" />\n    <Compile Include=\"OAuthAccount.cs\" />\n    <Compile Include=\"OAuthWebSecurity.cs\" />\n    <Compile Include=\"PreApplicationStartCode.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"Properties\\WebResources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>WebResources.resx</DependentUpon>\n    </Compile>\n    <Compile Include=\"ProviderUserIdSerializationHelper.cs\" />\n    <Compile Include=\"Resources\\OAuthResources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>OAuthResources.resx</DependentUpon>\n    </Compile>\n    <Compile Include=\"WebPagesOAuthDataProvider.cs\" />\n    <Compile Include=\"WebPagesOAuthTokenManager.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\System.Web.Razor\\System.Web.Razor.csproj\">\n      <Project>{8F18041B-9410-4C36-A9C5-067813DF5F31}</Project>\n      <Name>System.Web.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.WebPages.Razor\\System.Web.WebPages.Razor.csproj\">\n      <Project>{0939B11A-FE4E-4BA1-8AD6-D97741EE314F}</Project>\n      <Name>System.Web.WebPages.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\WebMatrix.WebData\\WebMatrix.WebData.csproj\">\n      <Project>{55A15F40-1435-4248-A7F2-2A146BB83586}</Project>\n      <Name>WebMatrix.WebData</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"..\\CommonResources.resx\">\n      <Link>Common\\CommonResources.resx</Link>\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>CommonResources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n    <EmbeddedResource Include=\"Properties\\WebResources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>WebResources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n    <EmbeddedResource Include=\"Resources\\OAuthResources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>OAuthResources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \n       Other similar extension points exist, see Microsoft.Common.targets.\n  <Target Name=\"BeforeBuild\">\n  </Target>\n  <Target Name=\"AfterBuild\">\n  </Target>\n  -->\n</Project>"
  },
  {
    "path": "src/Microsoft.Web.WebPages.OAuth/OAuthAccount.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Globalization;\nusing Microsoft.Web.WebPages.OAuth.Properties;\n\nnamespace Microsoft.Web.WebPages.OAuth\n{\n    /// <summary>\n    /// Represents an OAuth &amp; OpenID account.\n    /// </summary>\n    public class OAuthAccount\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"OAuthAccount\"/> class.\n        /// </summary>\n        /// <param name=\"provider\">The provider.</param>\n        /// <param name=\"providerUserId\">The provider user id.</param>\n        public OAuthAccount(string provider, string providerUserId)\n        {\n            if (String.IsNullOrEmpty(provider))\n            {\n                throw new ArgumentException(\n                    String.Format(CultureInfo.CurrentCulture, WebResources.Argument_Cannot_Be_Null_Or_Empty, \"provider\"),\n                    \"provider\");\n            }\n\n            if (String.IsNullOrEmpty(providerUserId))\n            {\n                throw new ArgumentException(\n                    String.Format(CultureInfo.CurrentCulture, WebResources.Argument_Cannot_Be_Null_Or_Empty, \"providerUserId\"),\n                    \"providerUserId\");\n            }\n\n            Provider = provider;\n            ProviderUserId = providerUserId;\n        }\n\n        /// <summary>\n        /// Gets the provider name.\n        /// </summary>\n        public string Provider { get; private set; }\n\n        /// <summary>\n        /// Gets the provider user id.\n        /// </summary>\n        public string ProviderUserId { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.WebPages.OAuth/OAuthWebSecurity.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq;\nusing System.Web;\nusing System.Web.Security;\nusing DotNetOpenAuth.AspNet;\nusing DotNetOpenAuth.AspNet.Clients;\nusing Microsoft.Web.WebPages.OAuth.Properties;\nusing WebMatrix.WebData;\n\nnamespace Microsoft.Web.WebPages.OAuth\n{\n    /// <summary>\n    /// Contains APIs to manage authentication against OAuth &amp; OpenID service providers\n    /// </summary>\n    public static class OAuthWebSecurity\n    {\n        internal static IOpenAuthDataProvider OAuthDataProvider = new WebPagesOAuthDataProvider();\n\n        // contains all registered authentication clients\n        private static readonly Dictionary<string, AuthenticationClientData> _authenticationClients =\n            new Dictionary<string, AuthenticationClientData>(StringComparer.OrdinalIgnoreCase);\n\n        /// <summary>\n        /// Gets a value indicating whether the current user is authenticated by an OAuth provider.\n        /// </summary>\n        public static bool IsAuthenticatedWithOAuth\n        {\n            get\n            {\n                if (HttpContext.Current == null)\n                {\n                    throw new InvalidOperationException(WebResources.HttpContextNotAvailable);\n                }\n\n                return GetIsAuthenticatedWithOAuthCore(new HttpContextWrapper(HttpContext.Current));\n            }\n        }\n\n        /// <summary>\n        /// Gets the collection of all registered authentication client;\n        /// </summary>\n        /// <returns></returns>\n        public static ICollection<AuthenticationClientData> RegisteredClientData\n        {\n            get\n            {\n                // the Values property returns a read-only collection.\n                // so we don't need to worry about clients of this method modifying our internal collection.\n                return _authenticationClients.Values;\n            }\n        }\n\n        /// <summary>\n        /// Registers the Facebook client.\n        /// </summary>\n        /// <param name=\"appId\">The app id.</param>\n        /// <param name=\"appSecret\">The app secret.</param>\n        public static void RegisterFacebookClient(string appId, string appSecret)\n        {\n            RegisterFacebookClient(appId, appSecret, displayName: \"Facebook\");\n        }\n\n        /// <summary>\n        /// Registers the Facebook client.\n        /// </summary>\n        /// <param name=\"appId\">The app id.</param>\n        /// <param name=\"appSecret\">The app secret.</param>\n        /// <param name=\"displayName\">The display name of the client.</param>\n        public static void RegisterFacebookClient(string appId, string appSecret, string displayName)\n        {\n            RegisterFacebookClient(appId, appSecret, displayName, extraData: new Dictionary<string, object>());\n        }\n\n        /// <summary>\n        /// Registers the Facebook client.\n        /// </summary>\n        /// <param name=\"appId\">The app id.</param>\n        /// <param name=\"appSecret\">The app secret.</param>\n        /// <param name=\"displayName\">The display name.</param>\n        /// <param name=\"extraData\">The data bag used to store extra data about this client</param>\n        public static void RegisterFacebookClient(string appId, string appSecret, string displayName, IDictionary<string, object> extraData)\n        {\n            RegisterClient(new FacebookClient(appId, appSecret), displayName, extraData);\n        }\n\n        /// <summary>\n        /// Registers the Microsoft account client.\n        /// </summary>\n        /// <param name=\"clientId\">The client id.</param>\n        /// <param name=\"clientSecret\">The client secret.</param>\n        public static void RegisterMicrosoftClient(string clientId, string clientSecret)\n        {\n            RegisterMicrosoftClient(clientId, clientSecret, displayName: \"Microsoft\");\n        }\n\n        /// <summary>\n        /// Registers the Microsoft account client.\n        /// </summary>\n        /// <param name=\"clientId\">The client id.</param>\n        /// <param name=\"clientSecret\">The client secret.</param>\n        /// <param name=\"displayName\">The display name.</param>\n        public static void RegisterMicrosoftClient(string clientId, string clientSecret, string displayName)\n        {\n            RegisterMicrosoftClient(clientId, clientSecret, displayName, new Dictionary<string, object>());\n        }\n\n        /// <summary>\n        /// Registers the Microsoft account client.\n        /// </summary>\n        /// <param name=\"clientId\">The client id.</param>\n        /// <param name=\"clientSecret\">The client secret.</param>\n        /// <param name=\"displayName\">The display name.</param>\n        /// <param name=\"extraData\">The data bag used to store extra data about this client</param>\n        public static void RegisterMicrosoftClient(string clientId, string clientSecret, string displayName, IDictionary<string, object> extraData)\n        {\n            RegisterClient(new MicrosoftClient(clientId, clientSecret), displayName, extraData);\n        }\n\n        /// <summary>\n        /// Registers the Twitter client.\n        /// </summary>\n        /// <param name=\"consumerKey\">The consumer key.</param>\n        /// <param name=\"consumerSecret\">The consumer secret.</param>\n        public static void RegisterTwitterClient(string consumerKey, string consumerSecret)\n        {\n            RegisterTwitterClient(consumerKey, consumerSecret, displayName: \"Twitter\");\n        }\n\n        /// <summary>\n        /// Registers the Twitter client.\n        /// </summary>\n        /// <param name=\"consumerKey\">The consumer key.</param>\n        /// <param name=\"consumerSecret\">The consumer secret.</param>\n        /// <param name=\"displayName\">The display name.</param>\n        public static void RegisterTwitterClient(string consumerKey, string consumerSecret, string displayName)\n        {\n            RegisterTwitterClient(consumerKey, consumerSecret, displayName, new Dictionary<string, object>());\n        }\n\n        /// <summary>\n        /// Registers the Twitter client.\n        /// </summary>\n        /// <param name=\"consumerKey\">The consumer key.</param>\n        /// <param name=\"consumerSecret\">The consumer secret.</param>\n        /// <param name=\"displayName\">The display name.</param>\n        /// <param name=\"extraData\">The data bag used to store extra data about this client</param>\n        public static void RegisterTwitterClient(string consumerKey, string consumerSecret, string displayName, IDictionary<string, object> extraData)\n        {\n            var twitterClient = new TwitterClient(consumerKey, consumerSecret);\n            RegisterClient(twitterClient, displayName, extraData);\n        }\n\n        /// <summary>\n        /// Registers the LinkedIn client.\n        /// </summary>\n        /// <param name=\"consumerKey\">The consumer key.</param>\n        /// <param name=\"consumerSecret\">The consumer secret.</param>\n        public static void RegisterLinkedInClient(string consumerKey, string consumerSecret)\n        {\n            RegisterLinkedInClient(consumerKey, consumerSecret, displayName: \"LinkedIn\");\n        }\n\n        /// <summary>\n        /// Registers the LinkedIn client.\n        /// </summary>\n        /// <param name=\"consumerKey\">The consumer key.</param>\n        /// <param name=\"consumerSecret\">The consumer secret.</param>\n        /// <param name=\"displayName\">The display name.</param>\n        public static void RegisterLinkedInClient(string consumerKey, string consumerSecret, string displayName)\n        {\n            RegisterLinkedInClient(consumerKey, consumerSecret, displayName, new Dictionary<string, object>());\n        }\n\n        /// <summary>\n        /// Registers the LinkedIn client.\n        /// </summary>\n        /// <param name=\"consumerKey\">The consumer key.</param>\n        /// <param name=\"consumerSecret\">The consumer secret.</param>\n        /// <param name=\"displayName\">The display name.</param>\n        /// <param name=\"extraData\">The data bag used to store extra data about this client</param>\n        public static void RegisterLinkedInClient(string consumerKey, string consumerSecret, string displayName, IDictionary<string, object> extraData)\n        {\n            var linkedInClient = new LinkedInClient(consumerKey, consumerSecret);\n            RegisterClient(linkedInClient, displayName, extraData);\n        }\n\n        /// <summary>\n        /// Registers the Google client.\n        /// </summary>\n        public static void RegisterGoogleClient()\n        {\n            RegisterGoogleClient(displayName: \"Google\");\n        }\n\n        /// <summary>\n        /// Registers the Google client.\n        /// </summary>\n        /// <param name=\"displayName\">The display name.</param>\n        public static void RegisterGoogleClient(string displayName)\n        {\n            RegisterClient(new GoogleOpenIdClient(), displayName, new Dictionary<string, object>());\n        }\n\n        /// <summary>\n        /// Registers the Google client.\n        /// </summary>\n        /// <param name=\"displayName\">The display name.</param>\n        /// <param name=\"extraData\">The data bag.</param>\n        public static void RegisterGoogleClient(string displayName, IDictionary<string, object> extraData)\n        {\n            RegisterClient(new GoogleOpenIdClient(), displayName, extraData);\n        }\n\n        /// <summary>\n        /// Registers the Yahoo client.\n        /// </summary>\n        public static void RegisterYahooClient()\n        {\n            RegisterYahooClient(displayName: \"Yahoo\");\n        }\n\n        /// <summary>\n        /// Registers the Yahoo client.\n        /// </summary>\n        /// <param name=\"displayName\">The display name.</param>\n        public static void RegisterYahooClient(string displayName)\n        {\n            RegisterYahooClient(displayName, new Dictionary<string, object>());\n        }\n\n        /// <summary>\n        /// Registers the Yahoo client.\n        /// </summary>\n        /// <param name=\"displayName\">The display name.</param>\n        /// <param name=\"extraData\">The data bag.</param>\n        public static void RegisterYahooClient(string displayName, IDictionary<string, object> extraData)\n        {\n            RegisterClient(new YahooOpenIdClient(), displayName, extraData);\n        }\n\n        /// <summary>\n        /// Registers an authentication client.\n        /// </summary>\n        /// <param name=\"client\">The client to be registered.</param>\n        [CLSCompliant(false)]\n        public static void RegisterClient(IAuthenticationClient client)\n        {\n            RegisterClient(client, displayName: null, extraData: new Dictionary<string, object>());\n        }\n\n        /// <summary>\n        /// Registers an authentication client.\n        /// </summary>\n        /// <param name=\"client\">The client to be registered</param>\n        /// <param name=\"displayName\">The display name.</param>\n        /// <param name=\"extraData\">The data bag used to store extra data about the specified client</param>\n        [CLSCompliant(false)]\n        public static void RegisterClient(IAuthenticationClient client, string displayName, IDictionary<string, object> extraData)\n        {\n            if (client == null)\n            {\n                throw new ArgumentNullException(\"client\");\n            }\n\n            if (String.IsNullOrEmpty(client.ProviderName))\n            {\n                throw new ArgumentException(WebResources.InvalidServiceProviderName, \"client\");\n            }\n\n            if (_authenticationClients.ContainsKey(client.ProviderName))\n            {\n                throw new ArgumentException(WebResources.ServiceProviderNameExists, \"client\");\n            }\n\n            var clientData = new AuthenticationClientData(client, displayName, extraData);\n            _authenticationClients.Add(client.ProviderName, clientData);\n        }\n\n        /// <summary>\n        /// Requests the specified provider to start the authentication by directing users to an external website\n        /// </summary>\n        /// <param name=\"provider\">The provider.</param>\n        public static void RequestAuthentication(string provider)\n        {\n            RequestAuthentication(provider, returnUrl: null);\n        }\n\n        /// <summary>\n        /// Requests the specified provider to start the authentication by directing users to an external website\n        /// </summary>\n        /// <param name=\"provider\">The provider.</param>\n        /// <param name=\"returnUrl\">The return url after user is authenticated.</param>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"We want to allow relative app path, and support ~/\")]\n        public static void RequestAuthentication(string provider, string returnUrl)\n        {\n            if (HttpContext.Current == null)\n            {\n                throw new InvalidOperationException(WebResources.HttpContextNotAvailable);\n            }\n\n            RequestAuthenticationCore(new HttpContextWrapper(HttpContext.Current), provider, returnUrl);\n        }\n\n        /// <summary>\n        /// Requests the authentication core.\n        /// </summary>\n        /// <param name=\"context\">The context.</param>\n        /// <param name=\"provider\">The provider.</param>\n        /// <param name=\"returnUrl\">The return URL.</param>\n        internal static void RequestAuthenticationCore(HttpContextBase context, string provider, string returnUrl)\n        {\n            IAuthenticationClient client = GetOAuthClient(provider);\n            var securityManager = new OpenAuthSecurityManager(context, client, OAuthDataProvider);\n            securityManager.RequestAuthentication(returnUrl);\n        }\n\n        /// <summary>\n        /// Checks if user is successfully authenticated when user is redirected back to this user.\n        /// </summary>\n        [CLSCompliant(false)]\n        public static AuthenticationResult VerifyAuthentication()\n        {\n            return VerifyAuthentication(returnUrl: null);\n        }\n\n        /// <summary>\n        /// Checks if user is successfully authenticated when user is redirected back to this user.\n        /// </summary>\n        /// <param name=\"returnUrl\">The return URL which must match the one passed to RequestAuthentication earlier.</param>\n        [CLSCompliant(false)]\n        [System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"0#\", Justification = \"We want to allow relative app path, and support ~/\")]\n        public static AuthenticationResult VerifyAuthentication(string returnUrl)\n        {\n            if (HttpContext.Current == null)\n            {\n                throw new InvalidOperationException(WebResources.HttpContextNotAvailable);\n            }\n\n            return VerifyAuthenticationCore(new HttpContextWrapper(HttpContext.Current), returnUrl);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"We want to allow relative app path, and support ~/\")]\n        internal static AuthenticationResult VerifyAuthenticationCore(HttpContextBase context, string returnUrl)\n        {\n            string providerName = OpenAuthSecurityManager.GetProviderName(context);\n            if (String.IsNullOrEmpty(providerName))\n            {\n                return AuthenticationResult.Failed;\n            }\n\n            IAuthenticationClient client;\n            if (TryGetOAuthClient(providerName, out client))\n            {\n                var securityManager = new OpenAuthSecurityManager(context, client, OAuthDataProvider);\n                return securityManager.VerifyAuthentication(returnUrl);\n            }\n            else\n            {\n                throw new InvalidOperationException(WebResources.InvalidServiceProviderName);\n            }\n        }\n\n        /// <summary>\n        /// Checks if the specified provider user id represents a valid account.\n        /// If it does, log user in.\n        /// </summary>\n        /// <param name=\"providerName\">Name of the provider.</param>\n        /// <param name=\"providerUserId\">The provider user id.</param>\n        /// <param name=\"createPersistentCookie\">if set to <c>true</c> create persistent cookie as part of the login.</param>\n        /// <returns>\n        ///   <c>true</c> if the login is successful.\n        /// </returns>\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1726:UsePreferredTerms\", MessageId = \"Login\", Justification = \"Login is used more consistently in ASP.Net\")]\n        public static bool Login(string providerName, string providerUserId, bool createPersistentCookie)\n        {\n            if (HttpContext.Current == null)\n            {\n                throw new InvalidOperationException(WebResources.HttpContextNotAvailable);\n            }\n\n            return LoginCore(new HttpContextWrapper(HttpContext.Current), providerName, providerUserId, createPersistentCookie);\n        }\n\n        internal static bool LoginCore(HttpContextBase context, string providerName, string providerUserId, bool createPersistentCookie)\n        {\n            var provider = GetOAuthClient(providerName);\n            var securityManager = new OpenAuthSecurityManager(context, provider, OAuthDataProvider);\n            return securityManager.Login(providerUserId, createPersistentCookie);\n        }\n\n        internal static bool GetIsAuthenticatedWithOAuthCore(HttpContextBase context)\n        {\n            return new OpenAuthSecurityManager(context).IsAuthenticatedWithOpenAuth;\n        }\n\n        /// <summary>\n        /// Creates or update the account with the specified provider, provider user id and associate it with the specified user name.\n        /// </summary>\n        /// <param name=\"providerName\">Name of the provider.</param>\n        /// <param name=\"providerUserId\">The provider user id.</param>\n        /// <param name=\"userName\">The user name.</param>\n        public static void CreateOrUpdateAccount(string providerName, string providerUserId, string userName)\n        {\n            ExtendedMembershipProvider provider = VerifyProvider();\n            provider.CreateOrUpdateOAuthAccount(providerName, providerUserId, userName);\n        }\n\n        /// <summary>\n        /// Gets the registered user name corresponding to the specified provider and provider user id.\n        /// </summary>\n        /// <param name=\"providerName\">Name of the provider.</param>\n        /// <param name=\"providerUserId\">The provider user id.</param>\n        /// <returns></returns>\n        public static string GetUserName(string providerName, string providerUserId)\n        {\n            return OAuthDataProvider.GetUserNameFromOpenAuth(providerName, providerUserId);\n        }\n\n        /// <summary>\n        /// Gets all OAuth &amp; OpenID accounts which are associted with the specified user name.\n        /// </summary>\n        /// <param name=\"userName\">The user name.</param>\n        public static ICollection<OAuthAccount> GetAccountsFromUserName(string userName)\n        {\n            if (String.IsNullOrEmpty(userName))\n            {\n                throw new ArgumentException(\n                    String.Format(CultureInfo.CurrentCulture, WebResources.Argument_Cannot_Be_Null_Or_Empty, \"userName\"),\n                    \"userName\");\n            }\n\n            ExtendedMembershipProvider provider = VerifyProvider();\n            return provider.GetAccountsForUser(userName).Select(p => new OAuthAccount(p.Provider, p.ProviderUserId)).ToList();\n        }\n\n        /// <summary>\n        /// Determines whether there exists a local account (as opposed to OAuth account) with the specified userId.\n        /// </summary>\n        /// <param name=\"userId\">The user id to check for local account.</param>\n        /// <returns>\n        ///   <c>true</c> if there is a local account with the specified user id]; otherwise, <c>false</c>.\n        /// </returns>\n        public static bool HasLocalAccount(int userId)\n        {\n            ExtendedMembershipProvider provider = VerifyProvider();\n            Debug.Assert(provider != null); // VerifyProvider checks this\n            return provider.HasLocalAccount(userId);\n        }\n\n        /// <summary>\n        /// Delete the specified OAuth &amp; OpenID account\n        /// </summary>\n        /// <param name=\"providerName\">Name of the provider.</param>\n        /// <param name=\"providerUserId\">The provider user id.</param>\n        public static bool DeleteAccount(string providerName, string providerUserId)\n        {\n            ExtendedMembershipProvider provider = VerifyProvider();\n\n            string username = GetUserName(providerName, providerUserId);\n            if (String.IsNullOrEmpty(username))\n            {\n                // account doesn't exist\n                return false;\n            }\n\n            provider.DeleteOAuthAccount(providerName, providerUserId);\n            return true;\n        }\n\n        /// <summary>\n        /// Gets the OAuth client data of the specified provider name.\n        /// </summary>\n        /// <param name=\"providerName\">Name of the provider.</param>\n        /// <returns>The AuthenticationClientData of the specified provider name.</returns>\n        public static AuthenticationClientData GetOAuthClientData(string providerName)\n        {\n            if (providerName == null)\n            {\n                throw new ArgumentNullException(\"providerName\");\n            }\n\n            return _authenticationClients[providerName];\n        }\n\n        /// <summary>\n        /// Tries getting the OAuth client data of the specified provider name.\n        /// </summary>\n        /// <param name=\"providerName\">Name of the provider.</param>\n        /// <param name=\"clientData\">The client data of the specified provider name.</param>\n        /// <returns><c>true</c> if the client data is found for the specified provider name. Otherwise, <c>false</c></returns>\n        public static bool TryGetOAuthClientData(string providerName, out AuthenticationClientData clientData)\n        {\n            if (providerName == null)\n            {\n                throw new ArgumentNullException(\"providerName\");\n            }\n\n            return _authenticationClients.TryGetValue(providerName, out clientData);\n        }\n\n        internal static IAuthenticationClient GetOAuthClient(string providerName)\n        {\n            if (!_authenticationClients.ContainsKey(providerName))\n            {\n                throw new ArgumentException(WebResources.ServiceProviderNotFound, \"providerName\");\n            }\n\n            return _authenticationClients[providerName].AuthenticationClient;\n        }\n\n        internal static bool TryGetOAuthClient(string provider, out IAuthenticationClient client)\n        {\n            if (_authenticationClients.ContainsKey(provider))\n            {\n                client = _authenticationClients[provider].AuthenticationClient;\n                return true;\n            }\n            else\n            {\n                client = null;\n                return false;\n            }\n        }\n\n        /// <summary>\n        /// for unit tests\n        /// </summary>\n        internal static void ClearProviders()\n        {\n            _authenticationClients.Clear();\n        }\n\n        private static ExtendedMembershipProvider VerifyProvider()\n        {\n            var provider = Membership.Provider as ExtendedMembershipProvider;\n            if (provider == null)\n            {\n                throw new InvalidOperationException();\n            }\n            return provider;\n        }\n\n        /// <summary>\n        /// Securely serializes a providerName/providerUserId pair.\n        /// </summary>\n        /// <param name=\"providerName\">The provider name.</param>\n        /// <param name=\"providerUserId\">The provider-specific user id.</param>\n        /// <returns>A cryptographically protected serialization of the inputs which is suitable for round-tripping.</returns>\n        /// <remarks>Do not persist the return value to permanent storage. This implementation is subject to change.</remarks>\n        public static string SerializeProviderUserId(string providerName, string providerUserId)\n        {\n            if (providerName == null)\n            {\n                throw new ArgumentNullException(\"providerName\");\n            }\n            if (providerUserId == null)\n            {\n                throw new ArgumentNullException(\"providerUserId\");\n            }\n\n            return ProviderUserIdSerializationHelper.ProtectData(providerName, providerUserId);\n        }\n\n        /// <summary>\n        /// Deserializes a string obtained from <see cref=\"SerializeProviderUserId(string, string)\"/> back into a \n        /// providerName/providerUserId pair.\n        /// </summary>\n        /// <param name=\"data\">The input data.</param>\n        /// <param name=\"providerName\">Will contain the deserialized provider name.</param>\n        /// <param name=\"providerUserId\">Will contain the deserialized provider user id.</param>\n        /// <returns><c>True</c> if successful.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1021:AvoidOutParameters\", MessageId = \"1#\", Justification = \"This design is acceptable\")]\n        public static bool TryDeserializeProviderUserId(string data, out string providerName, out string providerUserId)\n        {\n            if (data == null)\n            {\n                throw new ArgumentNullException(\"data\");\n            }\n\n            return ProviderUserIdSerializationHelper.UnprotectData(data, out providerName, out providerUserId);\n        }\n    }\n}"
  },
  {
    "path": "src/Microsoft.Web.WebPages.OAuth/PreApplicationStartCode.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Web.WebPages.Razor;\n\nnamespace Microsoft.Web.WebPages.OAuth\n{\n    /// <summary>\n    /// Defines Start() method that gets executed when this assembly is loaded by ASP.NET\n    /// </summary>\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class PreApplicationStartCode\n    {\n        /// <summary>\n        /// Register global namepace imports for this assembly \n        /// </summary>\n        public static void Start()\n        {\n            WebPageRazorHost.AddGlobalImport(\"DotNetOpenAuth.AspNet\");\n            WebPageRazorHost.AddGlobalImport(\"Microsoft.Web.WebPages.OAuth\");\n\n            // Disable the \"calls home\" feature of DNOA\n            DotNetOpenAuth.Reporting.Enabled = false;\n        }\n    }\n}"
  },
  {
    "path": "src/Microsoft.Web.WebPages.OAuth/Properties/AssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Web;\n\n[assembly: AssemblyTitle(\"Microsoft.Web.WebPages.OAuth\")]\n[assembly: AssemblyDescription(\"\")]\n\n[assembly: InternalsVisibleTo(\"Microsoft.Web.WebPages.OAuth.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n[assembly: PreApplicationStartMethod(typeof(Microsoft.Web.WebPages.OAuth.PreApplicationStartCode), \"Start\")]\n"
  },
  {
    "path": "src/Microsoft.Web.WebPages.OAuth/Properties/WebResources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.488\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace Microsoft.Web.WebPages.OAuth.Properties {\n    using System;\n    \n    \n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class WebResources {\n        \n        private static global::System.Resources.ResourceManager resourceMan;\n        \n        private static global::System.Globalization.CultureInfo resourceCulture;\n        \n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal WebResources() {\n        }\n        \n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"Microsoft.Web.WebPages.OAuth.Properties.WebResources\", typeof(WebResources).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n        \n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to {0} cannot be null or an empty string..\n        /// </summary>\n        internal static string Argument_Cannot_Be_Null_Or_Empty {\n            get {\n                return ResourceManager.GetString(\"Argument_Cannot_Be_Null_Or_Empty\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to HttpContext is not available in the current thread..\n        /// </summary>\n        internal static string HttpContextNotAvailable {\n            get {\n                return ResourceManager.GetString(\"HttpContextNotAvailable\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Invalid provider name..\n        /// </summary>\n        internal static string InvalidServiceProviderName {\n            get {\n                return ResourceManager.GetString(\"InvalidServiceProviderName\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Another service provider with the same name has already been registered..\n        /// </summary>\n        internal static string ServiceProviderNameExists {\n            get {\n                return ResourceManager.GetString(\"ServiceProviderNameExists\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A service provider could not be found by the specified name..\n        /// </summary>\n        internal static string ServiceProviderNotFound {\n            get {\n                return ResourceManager.GetString(\"ServiceProviderNotFound\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.WebPages.OAuth/Properties/WebResources.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"Argument_Cannot_Be_Null_Or_Empty\" xml:space=\"preserve\">\n    <value>{0} cannot be null or an empty string.</value>\n  </data>\n  <data name=\"HttpContextNotAvailable\" xml:space=\"preserve\">\n    <value>HttpContext is not available in the current thread.</value>\n  </data>\n  <data name=\"InvalidServiceProviderName\" xml:space=\"preserve\">\n    <value>Invalid provider name.</value>\n  </data>\n  <data name=\"ServiceProviderNameExists\" xml:space=\"preserve\">\n    <value>Another service provider with the same name has already been registered.</value>\n  </data>\n  <data name=\"ServiceProviderNotFound\" xml:space=\"preserve\">\n    <value>A service provider could not be found by the specified name.</value>\n  </data>\n</root>"
  },
  {
    "path": "src/Microsoft.Web.WebPages.OAuth/ProviderUserIdSerializationHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.CodeAnalysis;\nusing System.IO;\nusing System.Web.Security;\n\nnamespace Microsoft.Web.WebPages.OAuth\n{\n    internal static class ProviderUserIdSerializationHelper\n    {\n        // Custom message purpose to prevent this data from being readable by a different subsystem.\n        private static byte[] _padding = new byte[] { 0x85, 0xC5, 0x65, 0x72 };\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2202:Do not dispose objects multiple times\", Justification = \"The instances are disposed correctly.\")]\n        public static string ProtectData(string providerName, string providerUserId)\n        {\n            using (MemoryStream ms = new MemoryStream())\n            using (BinaryWriter bw = new BinaryWriter(ms))\n            {\n                bw.Write(providerName);\n                bw.Write(providerUserId);\n                bw.Flush();\n                byte[] serializedWithPadding = new byte[ms.Length + _padding.Length];\n                Buffer.BlockCopy(_padding, 0, serializedWithPadding, 0, _padding.Length);\n                Buffer.BlockCopy(ms.GetBuffer(), 0, serializedWithPadding, _padding.Length, (int)ms.Length);\n#pragma warning disable 0618 // Encode is [Obsolete] in 4.5\n                return MachineKey.Encode(serializedWithPadding, MachineKeyProtection.All);\n#pragma warning restore 0618\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2202:Do not dispose objects multiple times\", Justification = \"The instances are disposed correctly.\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"All exception are being caught on purpose.\")]\n        public static bool UnprotectData(string protectedData, out string providerName, out string providerUserId)\n        {\n            providerName = null;\n            providerUserId = null;\n            if (String.IsNullOrEmpty(protectedData))\n            {\n                return false;\n            }\n#pragma warning disable 0618 // Decode is [Obsolete] in 4.5\n            byte[] decodedWithPadding = MachineKey.Decode(protectedData, MachineKeyProtection.All);\n#pragma warning restore 0618\n            if (decodedWithPadding.Length < _padding.Length)\n            {\n                return false;\n            }\n\n            // timing attacks aren't really applicable to this, so we just do the simple check.\n            for (int i = 0; i < _padding.Length; i++)\n            {\n                if (_padding[i] != decodedWithPadding[i])\n                {\n                    return false;\n                }\n            }\n\n            using (MemoryStream ms = new MemoryStream(decodedWithPadding, _padding.Length, decodedWithPadding.Length - _padding.Length))\n            using (BinaryReader br = new BinaryReader(ms))\n            {\n                try\n                {\n                    // use temp variable to keep both out parameters consistent and only set them when the input stream is read completely\n                    string name = br.ReadString();\n                    string userId = br.ReadString();\n\n                    // make sure that we consume the entire input stream\n                    if (ms.ReadByte() == -1)\n                    {\n                        providerName = name;\n                        providerUserId = userId;\n                        return true;\n                    }\n                }\n                catch\n                {\n                    // Any exceptions will result in this method returning false.\n                }\n            }\n            return false;\n        }\n    }\n}"
  },
  {
    "path": "src/Microsoft.Web.WebPages.OAuth/Resources/OAuthResources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.488\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace Microsoft.Web.WebPages.OAuth.Resources {\n    using System;\n    \n    \n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class OAuthResources {\n        \n        private static global::System.Resources.ResourceManager resourceMan;\n        \n        private static global::System.Globalization.CultureInfo resourceCulture;\n        \n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal OAuthResources() {\n        }\n        \n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"Microsoft.Web.WebPages.OAuth.Resources.OAuthResources\", typeof(OAuthResources).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n        \n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to To call this method, the &quot;Membership.Provider&quot; property must be an instance of &quot;ExtendedMembershipProvider&quot;..\n        /// </summary>\n        internal static string Security_NoExtendedMembershipProvider {\n            get {\n                return ResourceManager.GetString(\"Security_NoExtendedMembershipProvider\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/Microsoft.Web.WebPages.OAuth/Resources/OAuthResources.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"Security_NoExtendedMembershipProvider\" xml:space=\"preserve\">\n    <value>To call this method, the \"Membership.Provider\" property must be an instance of \"ExtendedMembershipProvider\".</value>\n  </data>\n</root>"
  },
  {
    "path": "src/Microsoft.Web.WebPages.OAuth/WebPagesOAuthDataProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Security;\nusing DotNetOpenAuth.AspNet;\nusing Microsoft.Web.WebPages.OAuth.Resources;\nusing WebMatrix.WebData;\n\nnamespace Microsoft.Web.WebPages.OAuth\n{\n    internal class WebPagesOAuthDataProvider : IOpenAuthDataProvider\n    {\n        private static ExtendedMembershipProvider VerifyProvider()\n        {\n            var provider = Membership.Provider as ExtendedMembershipProvider;\n            if (provider == null)\n            {\n                throw new InvalidOperationException(OAuthResources.Security_NoExtendedMembershipProvider);\n            }\n            return provider;\n        }\n\n        public string GetUserNameFromOpenAuth(string openAuthProvider, string openAuthId)\n        {\n            ExtendedMembershipProvider provider = VerifyProvider();\n\n            int userId = provider.GetUserIdFromOAuth(openAuthProvider, openAuthId);\n            if (userId == -1) \n            {\n                return null;\n            }\n\n            return provider.GetUserNameFromId(userId);\n        }\n    }\n}"
  },
  {
    "path": "src/Microsoft.Web.WebPages.OAuth/WebPagesOAuthTokenManager.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Security;\nusing DotNetOpenAuth.AspNet.Clients;\nusing Microsoft.Internal.Web.Utils;\nusing Microsoft.Web.WebPages.OAuth.Resources;\nusing WebMatrix.WebData;\n\nnamespace Microsoft.Web.WebPages.OAuth\n{\n    /// <summary>\n    /// WebPages implementation for the <see cref=\"IOAuthTokenManager\"/> interface which store tokens into SimpleMembership database\n    /// </summary>\n    internal class WebPagesOAuthTokenManager : IOAuthTokenManager\n    {\n        private static ExtendedMembershipProvider VerifyProvider()\n        {\n            var provider = Membership.Provider as ExtendedMembershipProvider;\n            if (provider == null)\n            {\n                throw new InvalidOperationException(OAuthResources.Security_NoExtendedMembershipProvider);\n            }\n            return provider;\n        }\n\n        /// <summary>\n        /// Gets the token secret from the specified token.\n        /// </summary>\n        /// <param name=\"token\">The token.</param>\n        /// <returns>\n        /// The token's secret\n        /// </returns>\n        public string GetTokenSecret(string token)\n        {\n            if (String.IsNullOrEmpty(token))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"token\");\n            }\n\n            return VerifyProvider().GetOAuthTokenSecret(token);\n        }\n\n        /// <summary>\n        /// Replaces the request token with access token.\n        /// </summary>\n        /// <param name=\"requestToken\">The request token.</param>\n        /// <param name=\"accessToken\">The access token.</param>\n        /// <param name=\"accessTokenSecret\">The access token secret.</param>\n        public void ReplaceRequestTokenWithAccessToken(string requestToken, string accessToken, string accessTokenSecret)\n        {\n            if (String.IsNullOrEmpty(requestToken))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"requestToken\");\n            }\n\n            if (String.IsNullOrEmpty(accessToken))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"accessToken\");\n            }\n\n            if (String.IsNullOrEmpty(accessTokenSecret))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"accessTokenSecret\");\n            }\n\n            VerifyProvider().ReplaceOAuthRequestTokenWithAccessToken(requestToken, accessToken, accessTokenSecret);\n        }\n\n        /// <summary>\n        /// Stores the request token together with its secret.\n        /// </summary>\n        /// <param name=\"requestToken\">The request token.</param>\n        /// <param name=\"requestTokenSecret\">The request token secret.</param>\n        public void StoreRequestToken(string requestToken, string requestTokenSecret)\n        {\n            if (String.IsNullOrEmpty(requestToken))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"requestToken\");\n            }\n\n            VerifyProvider().StoreOAuthRequestToken(requestToken, requestTokenSecret);\n        }\n    }\n}"
  },
  {
    "path": "src/Microsoft.Web.WebPages.OAuth/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"DotNetOpenAuth.AspNet\" version=\"4.0.3.12153\" targetFramework=\"net45\" />\n  <package id=\"DotNetOpenAuth.Core\" version=\"4.0.3.12153\" targetFramework=\"net45\" />\n  <package id=\"DotNetOpenAuth.OAuth.Consumer\" version=\"4.0.3.12153\" targetFramework=\"net45\" />\n  <package id=\"DotNetOpenAuth.OAuth.Core\" version=\"4.0.3.12153\" targetFramework=\"net45\" />\n  <package id=\"DotNetOpenAuth.OpenId.Core\" version=\"4.0.3.12153\" targetFramework=\"net45\" />\n  <package id=\"DotNetOpenAuth.OpenId.RelyingParty\" version=\"4.0.3.12153\" targetFramework=\"net45\" />\n</packages>"
  },
  {
    "path": "src/Settings.StyleCop",
    "content": "<StyleCopSettings Version=\"105\">\n  <GlobalSettings>\n    <StringProperty Name=\"MergeSettingsFiles\">Parent</StringProperty>\n  </GlobalSettings>\n</StyleCopSettings>"
  },
  {
    "path": "src/Strict.ruleset",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RuleSet Name=\"FxCop rules for ASP.NET Web Stack\" Description=\"This rule set contains the rules for ASP.NET Web Stack.\" ToolsVersion=\"10.0\">\n  <RuleHintPaths>\n    <Path>..\\packages\\CustomFxCopRules</Path>\n  </RuleHintPaths>\n  <IncludeAll Action=\"Error\" />\n  <Rules AnalyzerId=\"Microsoft.Analyzers.ManagedCodeAnalysis\" RuleNamespace=\"Microsoft.Rules.Managed\">\n    <Rule Id=\"CA1062\" Action=\"None\" />\n    <!-- Ignore int.ToString(...) calls w/o an IFormatProvider in old code. -->\n    <Rule Id=\"CA1305\" Action=\"None\" />\n  </Rules>\n</RuleSet>"
  },
  {
    "path": "src/System.Net.Http.Formatting/ByteRangeStreamContent.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.IO;\nusing System.Linq;\nusing System.Net.Http.Headers;\nusing System.Net.Http.Internal;\nusing System.Threading.Tasks;\nusing System.Web.Http;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// <see cref=\"HttpContent\"/> implementation which provides a byte range view over a stream used to generate HTTP\n    /// 206 (Partial Content) byte range responses. The <see cref=\"ByteRangeStreamContent\"/> supports one or more\n    /// byte ranges regardless of whether the ranges are consecutive or not. If there is only one range then a\n    /// single partial response body containing a Content-Range header is generated. If there are more than one\n    /// ranges then a multipart/byteranges response is generated where each body part contains a range indicated\n    /// by the associated Content-Range header field.\n    /// </summary>\n    public class ByteRangeStreamContent : HttpContent\n    {\n        private const string SupportedRangeUnit = \"bytes\";\n        private const string ByteRangesContentSubtype = \"byteranges\";\n        private const int DefaultBufferSize = 4096;\n        private const int MinBufferSize = 1;\n\n        private readonly Stream _content;\n        private readonly long _start;\n        private readonly HttpContent _byteRangeContent;\n        private bool _disposed;\n\n        /// <summary>\n        /// <see cref=\"HttpContent\"/> implementation which provides a byte range view over a stream used to generate HTTP\n        /// 206 (Partial Content) byte range responses. If none of the requested ranges overlap with the current extend\n        /// of the selected resource represented by the <paramref name=\"content\"/> parameter then an\n        /// <see cref=\"InvalidByteRangeException\"/> is thrown indicating the valid Content-Range of the content.\n        /// </summary>\n        /// <param name=\"content\">The stream over which to generate a byte range view.</param>\n        /// <param name=\"range\">The range or ranges, typically obtained from the Range HTTP request header field.</param>\n        /// <param name=\"mediaType\">The media type of the content stream.</param>\n        public ByteRangeStreamContent(Stream content, RangeHeaderValue range, string mediaType)\n            : this(content, range, new MediaTypeHeaderValue(mediaType), DefaultBufferSize)\n        {\n        }\n\n        /// <summary>\n        /// <see cref=\"HttpContent\"/> implementation which provides a byte range view over a stream used to generate HTTP\n        /// 206 (Partial Content) byte range responses. If none of the requested ranges overlap with the current extend\n        /// of the selected resource represented by the <paramref name=\"content\"/> parameter then an\n        /// <see cref=\"InvalidByteRangeException\"/> is thrown indicating the valid Content-Range of the content.\n        /// </summary>\n        /// <param name=\"content\">The stream over which to generate a byte range view.</param>\n        /// <param name=\"range\">The range or ranges, typically obtained from the Range HTTP request header field.</param>\n        /// <param name=\"mediaType\">The media type of the content stream.</param>\n        /// <param name=\"bufferSize\">The buffer size used when copying the content stream.</param>\n        public ByteRangeStreamContent(Stream content, RangeHeaderValue range, string mediaType, int bufferSize)\n            : this(content, range, new MediaTypeHeaderValue(mediaType), bufferSize)\n        {\n        }\n\n        /// <summary>\n        /// <see cref=\"HttpContent\"/> implementation which provides a byte range view over a stream used to generate HTTP\n        /// 206 (Partial Content) byte range responses. If none of the requested ranges overlap with the current extend\n        /// of the selected resource represented by the <paramref name=\"content\"/> parameter then an\n        /// <see cref=\"InvalidByteRangeException\"/> is thrown indicating the valid Content-Range of the content.\n        /// </summary>\n        /// <param name=\"content\">The stream over which to generate a byte range view.</param>\n        /// <param name=\"range\">The range or ranges, typically obtained from the Range HTTP request header field.</param>\n        /// <param name=\"mediaType\">The media type of the content stream.</param>\n        public ByteRangeStreamContent(Stream content, RangeHeaderValue range, MediaTypeHeaderValue mediaType)\n            : this(content, range, mediaType, DefaultBufferSize)\n        {\n        }\n\n        /// <summary>\n        /// <see cref=\"HttpContent\"/> implementation which provides a byte range view over a stream used to generate HTTP\n        /// 206 (Partial Content) byte range responses. If none of the requested ranges overlap with the current extend\n        /// of the selected resource represented by the <paramref name=\"content\"/> parameter then an\n        /// <see cref=\"InvalidByteRangeException\"/> is thrown indicating the valid Content-Range of the content.\n        /// </summary>\n        /// <param name=\"content\">The stream over which to generate a byte range view.</param>\n        /// <param name=\"range\">The range or ranges, typically obtained from the Range HTTP request header field.</param>\n        /// <param name=\"mediaType\">The media type of the content stream.</param>\n        /// <param name=\"bufferSize\">The buffer size used when copying the content stream.</param>\n        public ByteRangeStreamContent(Stream content, RangeHeaderValue range, MediaTypeHeaderValue mediaType, int bufferSize)\n        {\n            if (content == null)\n            {\n                throw Error.ArgumentNull(\"content\");\n            }\n            if (!content.CanSeek)\n            {\n                throw Error.Argument(\"content\", Properties.Resources.ByteRangeStreamNotSeekable, typeof(ByteRangeStreamContent).Name);\n            }\n            if (range == null)\n            {\n                throw Error.ArgumentNull(\"range\");\n            }\n            if (mediaType == null)\n            {\n                throw Error.ArgumentNull(\"mediaType\");\n            }\n            if (bufferSize < MinBufferSize)\n            {\n                throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"bufferSize\", bufferSize, MinBufferSize);\n            }\n            if (!range.Unit.Equals(SupportedRangeUnit, StringComparison.OrdinalIgnoreCase))\n            {\n                throw Error.Argument(\"range\", Properties.Resources.ByteRangeStreamContentNotBytesRange, range.Unit, SupportedRangeUnit);\n            }\n\n            try\n            {\n                // If we have more than one range then we use a multipart/byteranges content type as wrapper.\n                // Otherwise we use a non-multipart response.\n                if (range.Ranges.Count > 1)\n                {\n                    // Create Multipart content and copy headers to this content\n                    MultipartContent rangeContent = new MultipartContent(ByteRangesContentSubtype);\n                    _byteRangeContent = rangeContent;\n\n                    foreach (RangeItemHeaderValue rangeValue in range.Ranges)\n                    {\n                        try\n                        {\n                            ByteRangeStream rangeStream = new ByteRangeStream(content, rangeValue);\n                            HttpContent rangeBodyPart = new StreamContent(rangeStream, bufferSize);\n                            rangeBodyPart.Headers.ContentType = mediaType;\n                            rangeBodyPart.Headers.ContentRange = rangeStream.ContentRange;\n                            rangeContent.Add(rangeBodyPart);\n                        }\n                        catch (ArgumentOutOfRangeException)\n                        {\n                            // We ignore range errors until we check that we have at least one valid range\n                        }\n                    }\n\n                    // If no overlapping ranges were found then stop\n                    if (!rangeContent.Any())\n                    {\n                        ContentRangeHeaderValue actualContentRange = new ContentRangeHeaderValue(content.Length);\n                        string msg = Error.Format(Properties.Resources.ByteRangeStreamNoneOverlap, range.ToString());\n                        throw new InvalidByteRangeException(actualContentRange, msg);\n                    }\n                }\n                else if (range.Ranges.Count == 1)\n                {\n                    try\n                    {\n                        ByteRangeStream rangeStream = new ByteRangeStream(content, range.Ranges.First());\n                        _byteRangeContent = new StreamContent(rangeStream, bufferSize);\n                        _byteRangeContent.Headers.ContentType = mediaType;\n                        _byteRangeContent.Headers.ContentRange = rangeStream.ContentRange;\n                    }\n                    catch (ArgumentOutOfRangeException)\n                    {\n                        ContentRangeHeaderValue actualContentRange = new ContentRangeHeaderValue(content.Length);\n                        string msg = Error.Format(Properties.Resources.ByteRangeStreamNoOverlap, range.ToString());\n                        throw new InvalidByteRangeException(actualContentRange, msg);\n                    }\n                }\n                else\n                {\n                    throw Error.Argument(\"range\", Properties.Resources.ByteRangeStreamContentNoRanges);\n                }\n\n                // Copy headers from byte range content so that we get the right content type etc.\n                _byteRangeContent.Headers.CopyTo(Headers);\n\n                _content = content;\n                _start = content.Position;\n            }\n            catch\n            {\n                if (_byteRangeContent != null)\n                {\n                    _byteRangeContent.Dispose();\n                }\n                throw;\n            }\n        }\n\n        protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)\n        {\n            // Reset stream to start position\n            _content.Position = _start;\n\n            // Copy result to output\n            return _byteRangeContent.CopyToAsync(stream);\n        }\n\n        protected override bool TryComputeLength(out long length)\n        {\n            long? contentLength = _byteRangeContent.Headers.ContentLength;\n            if (contentLength.HasValue)\n            {\n                length = contentLength.Value;\n                return true;\n            }\n\n            length = -1;\n            return false;\n        }\n\n        protected override void Dispose(bool disposing)\n        {\n            Contract.Assert(_byteRangeContent != null);\n            if (disposing)\n            {\n                if (!_disposed)\n                {\n                    _byteRangeContent.Dispose();\n                    _content.Dispose();\n                    _disposed = true;\n                }\n            }\n            base.Dispose(disposing);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/CloneableExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Net.Http\n{\n    internal static class CloneableExtensions\n    {\n        /// <summary>\n        /// Convenience method for cloning objects that implement <see cref=\"ICloneable\"/> explicitly.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of the cloneable object.</typeparam>\n        /// <param name=\"value\">The cloneable object.</param>\n        /// <returns>The result of cloning the <paramref name=\"value\"/>.</returns>\n        internal static T Clone<T>(this T value) where T : ICloneable\n        {\n            return (T)value.Clone();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/BaseJsonMediaTypeFormatter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.IO;\nusing System.Net.Http.Headers;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Serialization;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// Abstract <see cref=\"MediaTypeFormatter\"/> class to support Bson and Json.\n    /// </summary>\n    public abstract class BaseJsonMediaTypeFormatter : MediaTypeFormatter\n    {\n        // Though MaxDepth is not supported in netstandard1.3, we still override JsonReader's MaxDepth\n        private int _maxDepth = FormattingUtilities.DefaultMaxDepth;\n\n        private readonly IContractResolver _defaultContractResolver;\n\n        private JsonSerializerSettings _jsonSerializerSettings;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"BaseJsonMediaTypeFormatter\"/> class.\n        /// </summary>\n        protected BaseJsonMediaTypeFormatter()\n        {\n            // Initialize serializer settings\n            _defaultContractResolver = new JsonContractResolver(this);\n            _jsonSerializerSettings = CreateDefaultSerializerSettings();\n\n            // Set default supported character encodings\n            SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true));\n            SupportedEncodings.Add(new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true));\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"BaseJsonMediaTypeFormatter\"/> class.\n        /// </summary>\n        /// <param name=\"formatter\">The <see cref=\"BaseJsonMediaTypeFormatter\"/> instance to copy settings from.</param>\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2214:DoNotCallOverridableMethodsInConstructors\",\n            Justification = \"MaxDepth is sealed in existing subclasses and its documentation carries warnings.\")]\n        protected BaseJsonMediaTypeFormatter(BaseJsonMediaTypeFormatter formatter)\n            : base(formatter)\n        {\n            Contract.Assert(formatter != null);\n            SerializerSettings = formatter.SerializerSettings;\n\n            MaxDepth = formatter._maxDepth;\n        }\n\n        /// <summary>\n        /// Gets or sets the <see cref=\"JsonSerializerSettings\"/> used to configure the <see cref=\"JsonSerializer\"/>.\n        /// </summary>\n        public JsonSerializerSettings SerializerSettings\n        {\n            get { return _jsonSerializerSettings; }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.ArgumentNull(\"value\");\n                }\n\n                _jsonSerializerSettings = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets the maximum depth allowed by this formatter.\n        /// </summary>\n        /// <remarks>\n        /// Any override must call the base getter and setter. The setter may be called before a derived class\n        /// constructor runs, so any override should be very careful about using derived class state.\n        /// </remarks>\n        public virtual int MaxDepth\n        {\n            get\n            {\n                return _maxDepth;\n            }\n            set\n            {\n                if (value < FormattingUtilities.DefaultMinDepth)\n                {\n                    throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"value\", value, FormattingUtilities.DefaultMinDepth);\n                }\n\n                _maxDepth = value;\n            }\n        }\n\n        /// <summary>\n        /// Creates a <see cref=\"JsonSerializerSettings\"/> instance with the default settings used by the <see cref=\"BaseJsonMediaTypeFormatter\"/>.\n        /// </summary>\n        public JsonSerializerSettings CreateDefaultSerializerSettings()\n        {\n            return new JsonSerializerSettings()\n            {\n                ContractResolver = _defaultContractResolver,\n                MissingMemberHandling = MissingMemberHandling.Ignore,\n\n                // Do not change this setting\n                // Setting this to None prevents Json.NET from loading malicious, unsafe, or security-sensitive types\n                TypeNameHandling = TypeNameHandling.None\n            };\n        }\n\n        /// <summary>\n        /// Determines whether this <see cref=\"BaseJsonMediaTypeFormatter\"/> can read objects\n        /// of the specified <paramref name=\"type\"/>.\n        /// </summary>\n        /// <param name=\"type\">The <see cref=\"Type\"/> of object that will be read.</param>\n        /// <returns><c>true</c> if objects of this <paramref name=\"type\"/> can be read, otherwise <c>false</c>.</returns>\n        public override bool CanReadType(Type type)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            return true;\n        }\n\n        /// <summary>\n        /// Determines whether this <see cref=\"BaseJsonMediaTypeFormatter\"/> can write objects\n        /// of the specified <paramref name=\"type\"/>.\n        /// </summary>\n        /// <param name=\"type\">The <see cref=\"Type\"/> of object that will be written.</param>\n        /// <returns><c>true</c> if objects of this <paramref name=\"type\"/> can be written, otherwise <c>false</c>.</returns>\n        public override bool CanWriteType(Type type)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            return true;\n        }\n\n        /// <summary>\n        /// Called during deserialization to read an object of the specified <paramref name=\"type\"/>\n        /// from the specified <paramref name=\"readStream\"/>.\n        /// </summary>\n        /// <param name=\"type\">The <see cref=\"Type\"/> of object to read.</param>\n        /// <param name=\"readStream\">The <see cref=\"Stream\"/> from which to read.</param>\n        /// <param name=\"content\">The <see cref=\"HttpContent\"/> for the content being written.</param>\n        /// <param name=\"formatterLogger\">The <see cref=\"IFormatterLogger\"/> to log events to.</param>\n        /// <returns>A <see cref=\"Task\"/> whose result will be the object instance that has been read.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"The caught exception type is reflected into a faulted task.\")]\n        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            if (readStream == null)\n            {\n                throw Error.ArgumentNull(\"readStream\");\n            }\n\n            try\n            {\n                return Task.FromResult(ReadFromStream(type, readStream, content, formatterLogger));\n            }\n            catch (Exception e)\n            {\n                return TaskHelpers.FromError<object>(e);\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\",\n            Justification = \"Caller's formatterLogger is notified of problem in all cases where Exception is not rethrown.\")]\n        private object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)\n        {\n            Contract.Assert(type != null);\n            Contract.Assert(readStream != null);\n\n            HttpContentHeaders contentHeaders = content == null ? null : content.Headers;\n\n            // If content length is 0 then return default value for this type\n            if (contentHeaders != null && contentHeaders.ContentLength == 0)\n            {\n                return GetDefaultValueForType(type);\n            }\n\n            // Get the character encoding for the content\n            // Never non-null since SelectCharacterEncoding() throws in error / not found scenarios\n            Encoding effectiveEncoding = SelectCharacterEncoding(contentHeaders);\n\n            try\n            {\n                return ReadFromStream(type, readStream, effectiveEncoding, formatterLogger);\n            }\n            catch (Exception e)\n            {\n                if (formatterLogger == null)\n                {\n                    throw;\n                }\n\n                formatterLogger.LogError(String.Empty, e);\n                return GetDefaultValueForType(type);\n            }\n        }\n\n        /// <summary>\n        /// Called during deserialization to read an object of the specified <paramref name=\"type\"/>\n        /// from the specified <paramref name=\"readStream\"/>.\n        /// </summary>\n        /// <remarks>\n        /// Public for delegating wrappers of this class.  Expected to be called only from\n        /// <see cref=\"ReadFromStreamAsync\"/>.\n        /// </remarks>\n        /// <param name=\"type\">The <see cref=\"Type\"/> of object to read.</param>\n        /// <param name=\"readStream\">The <see cref=\"Stream\"/> from which to read.</param>\n        /// <param name=\"effectiveEncoding\">The <see cref=\"Encoding\"/> to use when reading.</param>\n        /// <param name=\"formatterLogger\">The <see cref=\"IFormatterLogger\"/> to log events to.</param>\n        /// <returns>The <see cref=\"object\"/> instance that has been read.</returns>\n        public virtual object ReadFromStream(Type type, Stream readStream, Encoding effectiveEncoding, IFormatterLogger formatterLogger)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            if (readStream == null)\n            {\n                throw Error.ArgumentNull(\"readStream\");\n            }\n\n            if (effectiveEncoding == null)\n            {\n                throw Error.ArgumentNull(\"effectiveEncoding\");\n            }\n\n            using (JsonReader jsonReader = CreateJsonReaderInternal(type, readStream, effectiveEncoding))\n            {\n                jsonReader.CloseInput = false;\n                jsonReader.MaxDepth = _maxDepth;\n\n                JsonSerializer jsonSerializer = CreateJsonSerializerInternal();\n\n                EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs> errorHandler = null;\n                if (formatterLogger != null)\n                {\n                    // Error must always be marked as handled\n                    // Failure to do so can cause the exception to be rethrown at every recursive level and overflow the stack for x64 CLR processes\n                    errorHandler = (sender, e) =>\n                    {\n                        Exception exception = e.ErrorContext.Error;\n                        formatterLogger.LogError(e.ErrorContext.Path, exception);\n                        e.ErrorContext.Handled = true;\n                    };\n                    jsonSerializer.Error += errorHandler;\n                }\n\n                try\n                {\n                    return jsonSerializer.Deserialize(jsonReader, type);\n                }\n                finally\n                {\n                    if (errorHandler != null)\n                    {\n                        // Clean up the error handler in case CreateJsonSerializer() reuses a serializer\n                        jsonSerializer.Error -= errorHandler;\n                    }\n                }\n            }\n        }\n\n        private JsonReader CreateJsonReaderInternal(Type type, Stream readStream, Encoding effectiveEncoding)\n        {\n            Contract.Assert(type != null);\n            Contract.Assert(readStream != null);\n            Contract.Assert(effectiveEncoding != null);\n\n            JsonReader reader = CreateJsonReader(type, readStream, effectiveEncoding);\n            if (reader == null)\n            {\n                throw Error.InvalidOperation(Properties.Resources.MediaTypeFormatter_JsonReaderFactoryReturnedNull, \"CreateJsonReader\");\n            }\n\n            return reader;\n        }\n\n        /// <summary>\n        /// Called during deserialization to get the <see cref=\"JsonReader\"/>.\n        /// </summary>\n        /// <remarks>\n        /// Public for delegating wrappers of this class.  Expected to be called only from\n        /// <see cref=\"ReadFromStreamAsync\"/>.\n        /// </remarks>\n        /// <param name=\"type\">The <see cref=\"Type\"/> of object to read.</param>\n        /// <param name=\"readStream\">The <see cref=\"Stream\"/> from which to read.</param>\n        /// <param name=\"effectiveEncoding\">The <see cref=\"Encoding\"/> to use when reading.</param>\n        /// <returns>The <see cref=\"JsonWriter\"/> used during deserialization.</returns>\n        public abstract JsonReader CreateJsonReader(Type type, Stream readStream, Encoding effectiveEncoding);\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"This is a public extensibility point, we can't predict what exceptions will come through\")]\n        private JsonSerializer CreateJsonSerializerInternal()\n        {\n            JsonSerializer serializer = null;\n            try\n            {\n                serializer = CreateJsonSerializer();\n            }\n            catch (Exception exception)\n            {\n                throw Error.InvalidOperation(exception, Properties.Resources.JsonSerializerFactoryThrew, \"CreateJsonSerializer\");\n            }\n\n            if (serializer == null)\n            {\n                throw Error.InvalidOperation(Properties.Resources.JsonSerializerFactoryReturnedNull, \"CreateJsonSerializer\");\n            }\n\n            return serializer;\n        }\n\n        /// <summary>\n        /// Called during serialization and deserialization to get the <see cref=\"JsonSerializer\"/>.\n        /// </summary>\n        /// <remarks>\n        /// Public for delegating wrappers of this class.  Expected to be called only from\n        /// <see cref=\"ReadFromStreamAsync\"/> and <see cref=\"WriteToStreamAsync\"/>.\n        /// </remarks>\n        /// <returns>The <see cref=\"JsonSerializer\"/> used during serialization and deserialization.</returns>\n        public virtual JsonSerializer CreateJsonSerializer()\n        {\n            JsonSerializer jsonSerializer = JsonSerializer.Create(SerializerSettings);\n            return jsonSerializer;\n        }\n\n        /// <inheritdoc />\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"The caught exception type is reflected into a faulted task.\")]\n        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content,\n            TransportContext transportContext, CancellationToken cancellationToken)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n            if (writeStream == null)\n            {\n                throw Error.ArgumentNull(\"writeStream\");\n            }\n            if (cancellationToken.IsCancellationRequested)\n            {\n                return TaskHelpers.Canceled();\n            }\n\n            try\n            {\n                WriteToStream(type, value, writeStream, content);\n                return TaskHelpers.Completed();\n            }\n            catch (Exception e)\n            {\n                return TaskHelpers.FromError(e);\n            }\n        }\n\n        private void WriteToStream(Type type, object value, Stream writeStream, HttpContent content)\n        {\n            Contract.Assert(type != null);\n            Contract.Assert(writeStream != null);\n\n            Encoding effectiveEncoding = SelectCharacterEncoding(content == null ? null : content.Headers);\n            WriteToStream(type, value, writeStream, effectiveEncoding);\n        }\n\n        /// <summary>\n        /// Called during serialization to write an object of the specified <paramref name=\"type\"/>\n        /// to the specified <paramref name=\"writeStream\"/>.\n        /// </summary>\n        /// <remarks>\n        /// Public for delegating wrappers of this class.  Expected to be called only from\n        /// <see cref=\"WriteToStreamAsync\"/>.\n        /// </remarks>\n        /// <param name=\"type\">The <see cref=\"Type\"/> of object to write.</param>\n        /// <param name=\"value\">The object to write.</param>\n        /// <param name=\"writeStream\">The <see cref=\"Stream\"/> to which to write.</param>\n        /// <param name=\"effectiveEncoding\">The <see cref=\"Encoding\"/> to use when writing.</param>\n        public virtual void WriteToStream(Type type, object value, Stream writeStream, Encoding effectiveEncoding)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            if (writeStream == null)\n            {\n                throw Error.ArgumentNull(\"writeStream\");\n            }\n\n            if (effectiveEncoding == null)\n            {\n                throw Error.ArgumentNull(\"effectiveEncoding\");\n            }\n\n            using (JsonWriter jsonWriter = CreateJsonWriterInternal(type, writeStream, effectiveEncoding))\n            {\n                jsonWriter.CloseOutput = false;\n\n                JsonSerializer jsonSerializer = CreateJsonSerializerInternal();\n                jsonSerializer.Serialize(jsonWriter, value);\n                jsonWriter.Flush();\n            }\n        }\n\n        private JsonWriter CreateJsonWriterInternal(Type type, Stream writeStream, Encoding effectiveEncoding)\n        {\n            Contract.Assert(type != null);\n            Contract.Assert(writeStream != null);\n            Contract.Assert(effectiveEncoding != null);\n\n            JsonWriter writer = CreateJsonWriter(type, writeStream, effectiveEncoding);\n            if (writer == null)\n            {\n                throw Error.InvalidOperation(Properties.Resources.MediaTypeFormatter_JsonWriterFactoryReturnedNull, \"CreateJsonWriter\");\n            }\n\n            return writer;\n        }\n\n        /// <summary>\n        /// Called during serialization to get the <see cref=\"JsonWriter\"/>.\n        /// </summary>\n        /// <remarks>\n        /// Public for delegating wrappers of this class.  Expected to be called only from\n        /// <see cref=\"WriteToStreamAsync\"/>.\n        /// </remarks>\n        /// <param name=\"type\">The <see cref=\"Type\"/> of object to write.</param>\n        /// <param name=\"writeStream\">The <see cref=\"Stream\"/> to which to write.</param>\n        /// <param name=\"effectiveEncoding\">The <see cref=\"Encoding\"/> to use when writing.</param>\n        /// <returns>The <see cref=\"JsonWriter\"/> used during serialization.</returns>\n        public abstract JsonWriter CreateJsonWriter(Type type, Stream writeStream, Encoding effectiveEncoding);\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/BsonMediaTypeFormatter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics.Contracts;\nusing System.IO;\nusing System.Net.Http.Headers;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Web.Http;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Bson;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// <see cref=\"MediaTypeFormatter\"/> class to handle Bson.\n    /// </summary>\n    public class BsonMediaTypeFormatter : BaseJsonMediaTypeFormatter\n    {\n        private static readonly Type OpenDictionaryType = typeof(Dictionary<,>);\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"BsonMediaTypeFormatter\"/> class.\n        /// </summary>\n        public BsonMediaTypeFormatter()\n        {\n            // Set default supported media type\n            SupportedMediaTypes.Add(MediaTypeConstants.ApplicationBsonMediaType);\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"BsonMediaTypeFormatter\"/> class.\n        /// </summary>\n        /// <param name=\"formatter\">The <see cref=\"BsonMediaTypeFormatter\"/> instance to copy settings from.</param>\n        protected BsonMediaTypeFormatter(BsonMediaTypeFormatter formatter)\n            : base(formatter)\n        {\n        }\n\n        /// <summary>\n        /// Gets the default media type for Json, namely \"application/bson\".\n        /// </summary>\n        /// <remarks>\n        /// The default media type does not have any <c>charset</c> parameter as\n        /// the <see cref=\"Encoding\"/> can be configured on a per <see cref=\"BsonMediaTypeFormatter\"/>\n        /// instance basis.\n        /// </remarks>\n        /// <value>\n        /// Because <see cref=\"MediaTypeHeaderValue\"/> is mutable, the value\n        /// returned will be a new instance every time.\n        /// </value>\n        public static MediaTypeHeaderValue DefaultMediaType\n        {\n            get\n            {\n                return MediaTypeConstants.ApplicationBsonMediaType;\n            }\n        }\n\n        /// <inheritdoc />\n        public sealed override int MaxDepth\n        {\n            get\n            {\n                return base.MaxDepth;\n            }\n            set\n            {\n                base.MaxDepth = value;\n            }\n        }\n\n        /// <inheritdoc />\n        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            if (readStream == null)\n            {\n                throw Error.ArgumentNull(\"readStream\");\n            }\n\n            if (type == typeof(DBNull) && content != null && content.Headers != null && content.Headers.ContentLength == 0)\n            {\n                // Lower-level Json.Net deserialization can convert null to DBNull.Value. However this formatter treats\n                // DBNull.Value like null and serializes no content. Json.Net code won't be invoked at all (for read or\n                // write). Override BaseJsonMediaTypeFormatter.ReadFromStream()'s call to GetDefaultValueForType()\n                // (which would return null in this case) and instead return expected DBNull.Value. Special case exists\n                // primarily for parity with JsonMediaTypeFormatter.\n                return Task.FromResult((object)DBNull.Value);\n            }\n            else\n            {\n                return base.ReadFromStreamAsync(type, readStream, content, formatterLogger);\n            }\n        }\n\n        /// <inheritdoc />\n        public override object ReadFromStream(Type type, Stream readStream, Encoding effectiveEncoding,\n            IFormatterLogger formatterLogger)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            if (readStream == null)\n            {\n                throw Error.ArgumentNull(\"readStream\");\n            }\n\n            if (effectiveEncoding == null)\n            {\n                throw Error.ArgumentNull(\"effectiveEncoding\");\n            }\n\n            // Special-case for simple types: Deserialize a Dictionary with a single element named Value.\n            // Serialization created this Dictionary<string, object> to work around BSON restrictions: BSON cannot\n            // handle a top-level simple type.  NewtonSoft.Json throws a JsonWriterException with message \"Error\n            // writing Binary value. BSON must start with an Object or Array. Path ''.\" when WriteToStream() is given\n            // such a value.\n            //\n            // Added clause for typeof(byte[]) needed because NewtonSoft.Json sometimes throws above Exception when\n            // WriteToStream() is given a byte[] value.  (Not clear where the bug lies and, worse, it doesn't reproduce\n            // reliably.)\n            //\n            // Request for typeof(object) may cause a simple value to round trip as a JObject.\n            if (IsSimpleType(type) || type == typeof(byte[]))\n            {\n                // Read as exact expected Dictionary<string, T> to ensure NewtonSoft.Json does correct top-level conversion.\n                Type dictionaryType = OpenDictionaryType.MakeGenericType(new Type[] { typeof(string), type });\n                IDictionary dictionary =\n                    base.ReadFromStream(dictionaryType, readStream, effectiveEncoding, formatterLogger) as IDictionary;\n                if (dictionary == null)\n                {\n                    // Not valid since BaseJsonMediaTypeFormatter.ReadFromStream(Type, Stream, HttpContent, IFormatterLogger)\n                    // handles empty content and does not call ReadFromStream(Type, Stream, Encoding, IFormatterLogger)\n                    // in that case.\n                    throw Error.InvalidOperation(Properties.Resources.MediaTypeFormatter_BsonParseError_MissingData,\n                        dictionaryType.Name);\n                }\n\n                // Unfortunately IDictionary doesn't have TryGetValue()...\n                string firstKey = String.Empty;\n                foreach (DictionaryEntry item in dictionary)\n                {\n                    if (dictionary.Count == 1 && (item.Key as string) == \"Value\")\n                    {\n                        // Success\n                        return item.Value;\n                    }\n                    else\n                    {\n                        if (item.Key != null)\n                        {\n                            firstKey = item.Key.ToString();\n                        }\n\n                        break;\n                    }\n                }\n\n                throw Error.InvalidOperation(Properties.Resources.MediaTypeFormatter_BsonParseError_UnexpectedData,\n                    dictionary.Count, firstKey);\n            }\n            else\n            {\n                return base.ReadFromStream(type, readStream, effectiveEncoding, formatterLogger);\n            }\n        }\n\n        /// <inheritdoc />\n        public override JsonReader CreateJsonReader(Type type, Stream readStream, Encoding effectiveEncoding)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            if (readStream == null)\n            {\n                throw Error.ArgumentNull(\"readStream\");\n            }\n\n            if (effectiveEncoding == null)\n            {\n                throw Error.ArgumentNull(\"effectiveEncoding\");\n            }\n\n            BsonDataReader reader = new BsonDataReader(new BinaryReader(readStream, effectiveEncoding));\n\n            try\n            {\n                // Special case discussed at http://stackoverflow.com/questions/16910369/bson-array-deserialization-with-json-net\n                // Dispensed with string (aka IEnumerable<char>) case above in ReadFromStream()\n                reader.ReadRootValueAsArray =\n                    typeof(IEnumerable).IsAssignableFrom(type) && !typeof(IDictionary).IsAssignableFrom(type);\n            }\n            catch\n            {\n                // Ensure instance is cleaned up in case of an issue\n                ((IDisposable)reader).Dispose();\n                throw;\n            }\n\n            return reader;\n        }\n\n        /// <inheritdoc />\n        public override void WriteToStream(Type type, object value, Stream writeStream, Encoding effectiveEncoding)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            if (writeStream == null)\n            {\n                throw Error.ArgumentNull(\"writeStream\");\n            }\n\n            if (effectiveEncoding == null)\n            {\n                throw Error.ArgumentNull(\"effectiveEncoding\");\n            }\n\n            if (value == null)\n            {\n                // Cannot serialize null at the top level. Json.Net throws Newtonsoft.Json.JsonWriterException : Error\n                // writing Null value. BSON must start with an Object or Array. Path ''. Fortunately\n                // BaseJsonMediaTypeFormatter.ReadFromStream(Type, Stream, HttpContent, IFormatterLogger) treats zero-\n                // length content as null or the default value of a struct.\n                return;\n            }\n\n            if (value == DBNull.Value)\n            {\n                // ReadFromStreamAsync() override above converts null to DBNull.Value if given Type is DBNull; normally\n                // however DBNull.Value round-trips as null. There's a known edge case where a full .NET application\n                // uses the portable version of this formatter. The full .NET application may pass DBNull.Value,\n                // leading to a JsonWriterException. If a DBNull is at a lower level in the value, the portable\n                // Json.Net assembly will also fail to special-case that DBNull, serialize it as an empty JSON object\n                // rather than null, and not meet the receiver's expectations.\n                return;\n            }\n\n            // See comments in ReadFromStream() above about this special case and the need to include byte[] in it.\n            // Using runtime type here because Json.Net will throw during serialization whenever it cannot handle the\n            // runtime type at the top level. For e.g. passed type may be typeof(object) and value may be a string.\n            Type runtimeType = value.GetType();\n            if (IsSimpleType(runtimeType) || runtimeType == typeof(byte[]))\n            {\n                // Wrap value in a Dictionary with a single property named \"Value\" to provide BSON with an Object.  Is\n                // written out as binary equivalent of { \"Value\": value } JSON.\n                Dictionary<string, object> temporaryDictionary = new Dictionary<string, object>\n                {\n                    { \"Value\", value },\n                };\n                base.WriteToStream(typeof(Dictionary<string, object>), temporaryDictionary, writeStream, effectiveEncoding);\n            }\n            else\n            {\n                base.WriteToStream(type, value, writeStream, effectiveEncoding);\n            }\n        }\n\n        /// <inheritdoc />\n        public override JsonWriter CreateJsonWriter(Type type, Stream writeStream, Encoding effectiveEncoding)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            if (writeStream == null)\n            {\n                throw Error.ArgumentNull(\"writeStream\");\n            }\n\n            if (effectiveEncoding == null)\n            {\n                throw Error.ArgumentNull(\"effectiveEncoding\");\n            }\n\n            return new BsonDataWriter(new BinaryWriter(writeStream, effectiveEncoding));\n        }\n\n        // Return true if Json.Net will likely convert value of given type to a Json primitive, not JsonArray nor\n        // JsonObject.\n        // To do: https://aspnetwebstack.codeplex.com/workitem/1467\n        private static bool IsSimpleType(Type type)\n        {\n            Contract.Assert(type != null);\n\n            // CanConvertFrom() check is similar to MVC / Web API ModelMetadata.IsComplexType getters. This is\n            // sufficient for many cases but Json.Net uses JsonConverterAttribute and built-in converters, not type\n            // descriptors.\n            bool isSimpleType = TypeDescriptor.GetConverter(type).CanConvertFrom(typeof(string));\n\n            return isSimpleType;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/BufferedMediaTypeFormatter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.IO;\nusing System.Net.Http.Headers;\nusing System.Net.Http.Internal;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// Base class for writing a synchronous formatter on top of the asynchronous formatter infrastructure.\n    /// This does not guarantee non-blocking threads. The only way to guarantee that we don't block a thread on IO is\n    /// to use the asynchronous <see cref=\"MediaTypeFormatter\"/>.\n    /// </summary>\n    public abstract class BufferedMediaTypeFormatter : MediaTypeFormatter\n    {\n        private const int MinBufferSize = 0;\n        private const int DefaultBufferSize = 16 * 1024;\n\n        private int _bufferSizeInBytes = DefaultBufferSize;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"BufferedMediaTypeFormatter\"/> class.\n        /// </summary>\n        protected BufferedMediaTypeFormatter()\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"BufferedMediaTypeFormatter\"/> class.\n        /// </summary>\n        /// <param name=\"formatter\">The <see cref=\"BufferedMediaTypeFormatter\"/> instance to copy settings from.</param>\n        protected BufferedMediaTypeFormatter(BufferedMediaTypeFormatter formatter)\n            : base(formatter)\n        {\n            BufferSize = formatter.BufferSize;\n        }\n\n        /// <summary>\n        /// Suggested size of buffer to use with streams, in bytes. The default size is 16K.\n        /// </summary>\n        public int BufferSize\n        {\n            get { return _bufferSizeInBytes; }\n            set\n            {\n                if (value < MinBufferSize)\n                {\n                    throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"value\", value, MinBufferSize);\n                }\n                _bufferSizeInBytes = value;\n            }\n        }\n\n        /// <summary>\n        /// Writes synchronously to the buffered stream.\n        /// </summary>\n        /// <remarks>\n        /// An implementation of this method should close <paramref name=\"writeStream\"/> upon completion.\n        /// </remarks>\n        /// <param name=\"type\">The type of the object to write.</param>\n        /// <param name=\"value\">The object value to write.  It may be <c>null</c>.</param>\n        /// <param name=\"writeStream\">The <see cref=\"Stream\"/> to which to write.</param>\n        /// <param name=\"content\">The <see cref=\"HttpContent\"/> if available. Note that\n        /// modifying the headers of the content will have no effect on the generated HTTP message; they should only be used to guide the writing.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        public virtual void WriteToStream(Type type, object value, Stream writeStream, HttpContent content,\n            CancellationToken cancellationToken)\n        {\n            WriteToStream(type, value, writeStream, content);\n        }\n\n        /// <summary>\n        /// Writes synchronously to the buffered stream.\n        /// </summary>\n        /// <remarks>\n        /// An implementation of this method should close <paramref name=\"writeStream\"/> upon completion.\n        /// </remarks>\n        /// <param name=\"type\">The type of the object to write.</param>\n        /// <param name=\"value\">The object value to write.  It may be <c>null</c>.</param>\n        /// <param name=\"writeStream\">The <see cref=\"Stream\"/> to which to write.</param>\n        /// <param name=\"content\">The <see cref=\"HttpContent\"/> if available. Note that\n        /// modifying the headers of the content will have no effect on the generated HTTP message; they should only be used to guide the writing.</param>\n        public virtual void WriteToStream(Type type, object value, Stream writeStream, HttpContent content)\n        {\n            throw Error.NotSupported(Properties.Resources.MediaTypeFormatterCannotWriteSync, GetType().Name);\n        }\n\n        /// <summary>\n        /// Reads synchronously from the buffered stream.\n        /// </summary>\n        /// <remarks>\n        /// An implementation of this method should close <paramref name=\"readStream\"/> upon completion.\n        /// </remarks>\n        /// <param name=\"type\">The type of the object to deserialize.</param>\n        /// <param name=\"readStream\">The <see cref=\"Stream\"/> to read.</param>\n        /// <param name=\"content\">The <see cref=\"HttpContent\"/> if available.</param>\n        /// <param name=\"formatterLogger\">The <see cref=\"IFormatterLogger\"/> to log events to.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>An object of the given type.</returns>\n        public virtual object ReadFromStream(Type type, Stream readStream, HttpContent content,\n            IFormatterLogger formatterLogger, CancellationToken cancellationToken)\n        {\n            return ReadFromStream(type, readStream, content, formatterLogger);\n        }\n\n        /// <summary>\n        /// Reads synchronously from the buffered stream.\n        /// </summary>\n        /// <remarks>\n        /// An implementation of this method should close <paramref name=\"readStream\"/> upon completion.\n        /// </remarks>\n        /// <param name=\"type\">The type of the object to deserialize.</param>\n        /// <param name=\"readStream\">The <see cref=\"Stream\"/> to read.</param>\n        /// <param name=\"content\">The <see cref=\"HttpContent\"/> if available.</param>\n        /// <param name=\"formatterLogger\">The <see cref=\"IFormatterLogger\"/> to log events to.</param>\n        /// <returns>An object of the given type.</returns>\n        public virtual object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)\n        {\n            throw Error.NotSupported(Properties.Resources.MediaTypeFormatterCannotReadSync, GetType().Name);\n        }\n\n        // Sealed because derived classes shouldn't override the async version. Override sync version instead.\n        public sealed override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content,\n            TransportContext transportContext)\n        {\n            return WriteToStreamAsync(type, value, writeStream, content, transportContext, CancellationToken.None);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"The caught exception type is reflected into a faulted task.\")]\n        public sealed override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content,\n            TransportContext transportContext, CancellationToken cancellationToken)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            if (writeStream == null)\n            {\n                throw Error.ArgumentNull(\"writeStream\");\n            }\n\n            try\n            {\n                WriteToStreamSync(type, value, writeStream, content, cancellationToken);\n                return TaskHelpers.Completed();\n            }\n            catch (Exception e)\n            {\n                return TaskHelpers.FromError(e);\n            }\n        }\n\n        private void WriteToStreamSync(Type type, object value, Stream writeStream, HttpContent content,\n            CancellationToken cancellationToken)\n        {\n            using (Stream bufferedStream = GetBufferStream(writeStream, _bufferSizeInBytes))\n            {\n                WriteToStream(type, value, bufferedStream, content, cancellationToken);\n            }\n        }\n\n        public sealed override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content,\n            IFormatterLogger formatterLogger)\n        {\n            return ReadFromStreamAsync(type, readStream, content, formatterLogger, CancellationToken.None);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"The caught exception type is reflected into a faulted task.\")]\n        public sealed override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content,\n            IFormatterLogger formatterLogger, CancellationToken cancellationToken)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            if (readStream == null)\n            {\n                throw Error.ArgumentNull(\"readStream\");\n            }\n\n            try\n            {\n                return Task.FromResult(ReadFromStreamSync(type, readStream, content, formatterLogger, cancellationToken));\n            }\n            catch (Exception e)\n            {\n                return TaskHelpers.FromError<object>(e);\n            }\n        }\n\n        private object ReadFromStreamSync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger,\n            CancellationToken cancellationToken)\n        {\n            object result;\n            HttpContentHeaders contentHeaders = content == null ? null : content.Headers;\n            if (contentHeaders != null && contentHeaders.ContentLength == 0)\n            {\n                result = GetDefaultValueForType(type);\n            }\n            else\n            {\n                using (Stream bufferedStream = GetBufferStream(readStream, _bufferSizeInBytes))\n                {\n                    result = ReadFromStream(type, bufferedStream, content, formatterLogger, cancellationToken);\n                }\n            }\n            return result;\n        }\n\n        private static Stream GetBufferStream(Stream innerStream, int bufferSize)\n        {\n            Contract.Assert(innerStream != null);\n\n            // We wrap the inner stream in a non-closing delegating stream so that we allow the user\n            // to use the using (...) pattern yet not break the contract of formatters not closing\n            // the inner stream.\n            Stream nonClosingStream = new NonClosingDelegatingStream(innerStream);\n\n            // This uses a naive buffering. BufferedStream() will block the thread while it drains the buffer.\n            // We can explore a smarter implementation that async drains the buffer.\n            return new BufferedStream(nonClosingStream, bufferSize);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/ContentNegotiationResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http.Headers;\nusing System.Web.Http;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// Represents the result of content negotiation performed using\n    /// <see cref=\"IContentNegotiator.Negotiate(Type, HttpRequestMessage, IEnumerable{MediaTypeFormatter})\"/>\n    /// </summary>\n    public class ContentNegotiationResult\n    {\n        private MediaTypeFormatter _formatter;\n\n        /// <summary>\n        /// Create the content negotiation result object.\n        /// </summary>\n        /// <param name=\"formatter\">The formatter.</param>\n        /// <param name=\"mediaType\">The preferred media type. Can be <c>null</c>.</param>\n        public ContentNegotiationResult(MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType)\n        {\n            if (formatter == null)\n            {\n                throw Error.ArgumentNull(\"formatter\");\n            }\n\n            _formatter = formatter;\n            MediaType = mediaType;\n        }\n\n        /// <summary>\n        /// The formatter chosen for serialization.\n        /// </summary>\n        public MediaTypeFormatter Formatter\n        {\n            get { return _formatter; }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.ArgumentNull(\"value\");\n                }\n                _formatter = value;\n            }\n        }\n\n        /// <summary>\n        /// The media type that is associated with the formatter chosen for serialization. Can be <c>null</c>.\n        /// </summary>\n        public MediaTypeHeaderValue MediaType { get; set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/DefaultContentNegotiator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing System.Net.Http.Headers;\nusing System.Text;\nusing System.Web.Http;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// Class that selects a <see cref=\"MediaTypeFormatter\"/> for an <see cref=\"HttpRequestMessage\"/>\n    /// or <see cref=\"HttpResponseMessage\"/>.\n    /// </summary>\n    public class DefaultContentNegotiator : IContentNegotiator\n    {\n        public DefaultContentNegotiator()\n            : this(false)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"DefaultContentNegotiator\"/> with\n        /// the given setting for <paramref name=\"excludeMatchOnTypeOnly\"/>.\n        /// </summary>\n        /// <param name=\"excludeMatchOnTypeOnly\">\n        /// If ExcludeMatchOnTypeOnly is true then we don't match on type only which means\n        /// that we return null if we can't match on anything in the request. This is useful\n        /// for generating 406 (Not Acceptable) status codes.\n        /// </param>\n        public DefaultContentNegotiator(bool excludeMatchOnTypeOnly)\n        {\n            ExcludeMatchOnTypeOnly = excludeMatchOnTypeOnly;\n        }\n\n        /// <summary>\n        /// If ExcludeMatchOnTypeOnly is true then we don't match on type only which means\n        /// that we return null if we can't match on anything in the request. This is useful\n        /// for generating 406 (Not Acceptable) status codes.\n        /// </summary>\n        public bool ExcludeMatchOnTypeOnly { get; private set; }\n\n        /// <summary>\n        /// Performs content negotiating by selecting the most appropriate <see cref=\"MediaTypeFormatter\"/> out of the passed in\n        /// <paramref name=\"formatters\"/> for the given <paramref name=\"request\"/> that can serialize an object of the given\n        /// <paramref name=\"type\"/>.\n        /// </summary>\n        /// <param name=\"type\">The type to be serialized.</param>\n        /// <param name=\"request\">The request.</param>\n        /// <param name=\"formatters\">The set of <see cref=\"MediaTypeFormatter\"/> objects from which to choose.</param>\n        /// <returns>The result of the negotiation containing the most appropriate <see cref=\"MediaTypeFormatter\"/> instance,\n        /// or <c>null</c> if there is no appropriate formatter.</returns>\n        public virtual ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)\n        {\n            // Performance-sensitive\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n            if (formatters == null)\n            {\n                throw Error.ArgumentNull(\"formatters\");\n            }\n\n            // Go through each formatter to compute how well it matches.\n            Collection<MediaTypeFormatterMatch> matches = ComputeFormatterMatches(type, request, formatters);\n\n            // Select best formatter match among the matches\n            MediaTypeFormatterMatch bestFormatterMatch = SelectResponseMediaTypeFormatter(matches);\n\n            // We found a best formatter\n            if (bestFormatterMatch != null)\n            {\n                // Find the best character encoding for the selected formatter\n                Encoding bestEncodingMatch = SelectResponseCharacterEncoding(request, bestFormatterMatch.Formatter);\n                if (bestEncodingMatch != null)\n                {\n                    bestFormatterMatch.MediaType.CharSet = bestEncodingMatch.WebName;\n                }\n\n                MediaTypeHeaderValue bestMediaType = bestFormatterMatch.MediaType;\n                MediaTypeFormatter bestFormatter = bestFormatterMatch.Formatter.GetPerRequestFormatterInstance(type, request, bestMediaType);\n                return new ContentNegotiationResult(bestFormatter, bestMediaType);\n            }\n\n            return null;\n        }\n\n        /// <summary>\n        /// Determine how well each formatter matches by associating a <see cref=\"MediaTypeFormatterMatchRanking\"/> value\n        /// with the formatter. Then associate the quality of the match based on q-factors and other parameters. The result of this\n        /// method is a collection of the matches found categorized and assigned a quality value.\n        /// </summary>\n        /// <param name=\"type\">The type to be serialized.</param>\n        /// <param name=\"request\">The request.</param>\n        /// <param name=\"formatters\">The set of <see cref=\"MediaTypeFormatter\"/> objects from which to choose.</param>\n        /// <returns>A collection containing all the matches.</returns>\n        protected virtual Collection<MediaTypeFormatterMatch> ComputeFormatterMatches(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)\n        {\n            // Performance-sensitive\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n            if (formatters == null)\n            {\n                throw Error.ArgumentNull(\"formatters\");\n            }\n\n            IEnumerable<MediaTypeWithQualityHeaderValue> sortedAcceptValues = null;\n\n            // Go through each formatter to find how well it matches.\n            ListWrapperCollection<MediaTypeFormatterMatch> matches = new ListWrapperCollection<MediaTypeFormatterMatch>();\n            MediaTypeFormatter[] writingFormatters = GetWritingFormatters(formatters);\n            for (int i = 0; i < writingFormatters.Length; i++)\n            {\n                MediaTypeFormatter formatter = writingFormatters[i];\n                MediaTypeFormatterMatch match = null;\n\n                // Check first that formatter can write the actual type\n                if (!formatter.CanWriteType(type))\n                {\n                    // Formatter can't even write the type so no match at all\n                    continue;\n                }\n\n                // Match against media type mapping.\n                if ((match = MatchMediaTypeMapping(request, formatter)) != null)\n                {\n                    matches.Add(match);\n                    continue;\n                }\n\n                // Match against the accept header values.\n                if (sortedAcceptValues == null)\n                {\n                    // Sort the Accept header values in descending order based on q-factor\n                    sortedAcceptValues = SortMediaTypeWithQualityHeaderValuesByQFactor(request.Headers.Accept);\n                }\n                if ((match = MatchAcceptHeader(sortedAcceptValues, formatter)) != null)\n                {\n                    matches.Add(match);\n                    continue;\n                }\n\n                // Match against request's media type if any\n                if ((match = MatchRequestMediaType(request, formatter)) != null)\n                {\n                    matches.Add(match);\n                    continue;\n                }\n\n                // Check whether we should match on type or stop the matching process.\n                // The latter is used to generate 406 (Not Acceptable) status codes.\n                bool shouldMatchOnType = ShouldMatchOnType(sortedAcceptValues);\n\n                // Match against the type of object we are writing out\n                if (shouldMatchOnType && (match = MatchType(type, formatter)) != null)\n                {\n                    matches.Add(match);\n                    continue;\n                }\n            }\n\n            return matches;\n        }\n\n        /// <summary>\n        /// Select the best match among the candidate matches found.\n        /// </summary>\n        /// <param name=\"matches\">The collection of matches.</param>\n        /// <returns>The <see cref=\"MediaTypeFormatterMatch\"/> determined to be the best match.</returns>\n        protected virtual MediaTypeFormatterMatch SelectResponseMediaTypeFormatter(ICollection<MediaTypeFormatterMatch> matches)\n        {\n            // Performance-sensitive\n            if (matches == null)\n            {\n                throw Error.ArgumentNull(\"matches\");\n            }\n\n            List<MediaTypeFormatterMatch> matchList = matches.AsList();\n\n            MediaTypeFormatterMatch bestMatchOnType = null;\n            MediaTypeFormatterMatch bestMatchOnAcceptHeaderLiteral = null;\n            MediaTypeFormatterMatch bestMatchOnAcceptHeaderSubtypeMediaRange = null;\n            MediaTypeFormatterMatch bestMatchOnAcceptHeaderAllMediaRange = null;\n            MediaTypeFormatterMatch bestMatchOnMediaTypeMapping = null;\n            MediaTypeFormatterMatch bestMatchOnRequestMediaType = null;\n\n            // Go through each formatter to find the best match in each category.\n            for (int i = 0; i < matchList.Count; i++)\n            {\n                MediaTypeFormatterMatch match = matchList[i];\n                switch (match.Ranking)\n                {\n                    case MediaTypeFormatterMatchRanking.MatchOnCanWriteType:\n                        // First match by type trumps all other type matches\n                        if (bestMatchOnType == null)\n                        {\n                            bestMatchOnType = match;\n                        }\n                        break;\n\n                    case MediaTypeFormatterMatchRanking.MatchOnRequestWithMediaTypeMapping:\n                        // Matches on accept headers using mappings must choose the highest quality match\n                        bestMatchOnMediaTypeMapping = UpdateBestMatch(bestMatchOnMediaTypeMapping, match);\n                        break;\n\n                    case MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderLiteral:\n                        // Matches on accept headers must choose the highest quality match.\n                        // A match of 0.0 means we won't use it at all.\n                        bestMatchOnAcceptHeaderLiteral = UpdateBestMatch(bestMatchOnAcceptHeaderLiteral, match);\n                        break;\n\n                    case MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderSubtypeMediaRange:\n                        // Matches on accept headers must choose the highest quality match.\n                        // A match of 0.0 means we won't use it at all.\n                        bestMatchOnAcceptHeaderSubtypeMediaRange = UpdateBestMatch(bestMatchOnAcceptHeaderSubtypeMediaRange, match);\n                        break;\n\n                    case MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderAllMediaRange:\n                        // Matches on accept headers must choose the highest quality match.\n                        // A match of 0.0 means we won't use it at all.\n                        bestMatchOnAcceptHeaderAllMediaRange = UpdateBestMatch(bestMatchOnAcceptHeaderAllMediaRange, match);\n                        break;\n\n                    case MediaTypeFormatterMatchRanking.MatchOnRequestMediaType:\n                        // First match on request content type trumps other request content matches\n                        if (bestMatchOnRequestMediaType == null)\n                        {\n                            bestMatchOnRequestMediaType = match;\n                        }\n                        break;\n                }\n            }\n\n            // If we received matches based on both supported media types and from media type mappings,\n            // we want to give precedence to the media type mappings, but only if their quality is >= that of the supported media type.\n            // We do this because media type mappings are the user's extensibility point and must take precedence over normal\n            // supported media types in the case of a tie. The 99% case is where both have quality 1.0.\n            if (bestMatchOnMediaTypeMapping != null)\n            {\n                MediaTypeFormatterMatch mappingOverride = bestMatchOnMediaTypeMapping;\n                mappingOverride = UpdateBestMatch(mappingOverride, bestMatchOnAcceptHeaderLiteral);\n                mappingOverride = UpdateBestMatch(mappingOverride, bestMatchOnAcceptHeaderSubtypeMediaRange);\n                mappingOverride = UpdateBestMatch(mappingOverride, bestMatchOnAcceptHeaderAllMediaRange);\n                if (mappingOverride != bestMatchOnMediaTypeMapping)\n                {\n                    bestMatchOnMediaTypeMapping = null;\n                }\n            }\n\n            // now select the formatter and media type\n            // A MediaTypeMapping is highest precedence -- it is an extensibility point\n            // allowing the user to override normal accept header matching\n            MediaTypeFormatterMatch bestMatch = null;\n            if (bestMatchOnMediaTypeMapping != null)\n            {\n                bestMatch = bestMatchOnMediaTypeMapping;\n            }\n            else if (bestMatchOnAcceptHeaderLiteral != null ||\n                bestMatchOnAcceptHeaderSubtypeMediaRange != null ||\n                bestMatchOnAcceptHeaderAllMediaRange != null)\n            {\n                bestMatch = UpdateBestMatch(bestMatch, bestMatchOnAcceptHeaderLiteral);\n                bestMatch = UpdateBestMatch(bestMatch, bestMatchOnAcceptHeaderSubtypeMediaRange);\n                bestMatch = UpdateBestMatch(bestMatch, bestMatchOnAcceptHeaderAllMediaRange);\n            }\n            else if (bestMatchOnRequestMediaType != null)\n            {\n                bestMatch = bestMatchOnRequestMediaType;\n            }\n            else if (bestMatchOnType != null)\n            {\n                bestMatch = bestMatchOnType;\n            }\n\n            return bestMatch;\n        }\n\n        /// <summary>\n        /// Determine the best character encoding for writing the response. First we look\n        /// for accept-charset headers and if not found then we try to match\n        /// any charset encoding in the request (in case of PUT, POST, etc.)\n        /// If no encoding is found then we use the default for the formatter.\n        /// </summary>\n        /// <returns>The <see cref=\"Encoding\"/> determined to be the best match.</returns>\n        protected virtual Encoding SelectResponseCharacterEncoding(HttpRequestMessage request, MediaTypeFormatter formatter)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n            if (formatter == null)\n            {\n                throw Error.ArgumentNull(\"formatter\");\n            }\n\n            // If there are any SupportedEncodings then we pick an encoding\n            List<Encoding> supportedEncodings = formatter.SupportedEncodingsInternal;\n            if (supportedEncodings.Count > 0)\n            {\n                // Sort Accept-Charset header values\n                IEnumerable<StringWithQualityHeaderValue> sortedAcceptCharsetValues = SortStringWithQualityHeaderValuesByQFactor(request.Headers.AcceptCharset);\n\n                // Check for match based on accept-charset headers\n                foreach (StringWithQualityHeaderValue acceptCharset in sortedAcceptCharsetValues)\n                {\n                    for (int i = 0; i < supportedEncodings.Count; i++)\n                    {\n                        Encoding encoding = supportedEncodings[i];\n                        if (encoding != null && acceptCharset.Quality != FormattingUtilities.NoMatch &&\n                            (acceptCharset.Value.Equals(encoding.WebName, StringComparison.OrdinalIgnoreCase) ||\n                            acceptCharset.Value.Equals(\"*\", StringComparison.OrdinalIgnoreCase)))\n                        {\n                            return encoding;\n                        }\n                    }\n                }\n\n                // Check for match based on any request entity body\n                return formatter.SelectCharacterEncoding(request.Content != null ? request.Content.Headers : null);\n            }\n\n            return null;\n        }\n\n        /// <summary>\n        /// Match a request against the <see cref=\"MediaTypeMapping\"/>s registered with the formatter.\n        /// </summary>\n        /// <param name=\"request\">The request to match.</param>\n        /// <param name=\"formatter\">The formatter to match against.</param>\n        /// <returns>A <see cref=\"MediaTypeFormatterMatch\"/> indicating the quality of the match or null is no match.</returns>\n        protected virtual MediaTypeFormatterMatch MatchMediaTypeMapping(HttpRequestMessage request, MediaTypeFormatter formatter)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n            if (formatter == null)\n            {\n                throw Error.ArgumentNull(\"formatter\");\n            }\n\n            List<MediaTypeMapping> mediaTypeMappings = formatter.MediaTypeMappingsInternal;\n            for (int i = 0; i < mediaTypeMappings.Count; i++)\n            {\n                MediaTypeMapping mapping = mediaTypeMappings[i];\n                double quality;\n                if (mapping != null && ((quality = mapping.TryMatchMediaType(request)) > FormattingUtilities.NoMatch))\n                {\n                    return new MediaTypeFormatterMatch(formatter, mapping.MediaType, quality, MediaTypeFormatterMatchRanking.MatchOnRequestWithMediaTypeMapping);\n                }\n            }\n\n            return null;\n        }\n\n        /// <summary>\n        /// Match the request accept header field values against the formatter's registered supported media types.\n        /// </summary>\n        /// <param name=\"sortedAcceptValues\">The sorted accept header values to match.</param>\n        /// <param name=\"formatter\">The formatter to match against.</param>\n        /// <returns>A <see cref=\"MediaTypeFormatterMatch\"/> indicating the quality of the match or null is no match.</returns>\n        protected virtual MediaTypeFormatterMatch MatchAcceptHeader(IEnumerable<MediaTypeWithQualityHeaderValue> sortedAcceptValues, MediaTypeFormatter formatter)\n        {\n            if (sortedAcceptValues == null)\n            {\n                throw Error.ArgumentNull(\"sortedAcceptValues\");\n            }\n            if (formatter == null)\n            {\n                throw Error.ArgumentNull(\"formatter\");\n            }\n\n            foreach (MediaTypeWithQualityHeaderValue acceptMediaTypeValue in sortedAcceptValues)\n            {\n                List<MediaTypeHeaderValue> supportedMediaTypes = formatter.SupportedMediaTypesInternal;\n                for (int i = 0; i < supportedMediaTypes.Count; i++)\n                {\n                    MediaTypeHeaderValue supportedMediaType = supportedMediaTypes[i];\n                    MediaTypeHeaderValueRange range;\n                    if (supportedMediaType != null && acceptMediaTypeValue.Quality != FormattingUtilities.NoMatch &&\n                        supportedMediaType.IsSubsetOf(acceptMediaTypeValue, out range))\n                    {\n                        MediaTypeFormatterMatchRanking ranking;\n                        switch (range)\n                        {\n                            case MediaTypeHeaderValueRange.AllMediaRange:\n                                ranking = MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderAllMediaRange;\n                                break;\n\n                            case MediaTypeHeaderValueRange.SubtypeMediaRange:\n                                ranking = MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderSubtypeMediaRange;\n                                break;\n\n                            default:\n                                ranking = MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderLiteral;\n                                break;\n                        }\n\n                        return new MediaTypeFormatterMatch(formatter, supportedMediaType, acceptMediaTypeValue.Quality, ranking);\n                    }\n                }\n            }\n\n            return null;\n        }\n\n        /// <summary>\n        /// Match any request media type (in case there is a request entity body) against the formatter's registered\n        /// media types.\n        /// </summary>\n        /// <param name=\"request\">The request to match.</param>\n        /// <param name=\"formatter\">The formatter to match against.</param>\n        /// <returns>A <see cref=\"MediaTypeFormatterMatch\"/> indicating the quality of the match or null is no match.</returns>\n        protected virtual MediaTypeFormatterMatch MatchRequestMediaType(HttpRequestMessage request, MediaTypeFormatter formatter)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n            if (formatter == null)\n            {\n                throw Error.ArgumentNull(\"formatter\");\n            }\n\n            if (request.Content != null)\n            {\n                MediaTypeHeaderValue requestMediaType = request.Content.Headers.ContentType;\n                if (requestMediaType != null)\n                {\n                    List<MediaTypeHeaderValue> supportedMediaTypes = formatter.SupportedMediaTypesInternal;\n                    for (int i = 0; i < supportedMediaTypes.Count; i++)\n                    {\n                        MediaTypeHeaderValue supportedMediaType = supportedMediaTypes[i];\n                        if (supportedMediaType != null && supportedMediaType.IsSubsetOf(requestMediaType))\n                        {\n                            return new MediaTypeFormatterMatch(formatter, supportedMediaType, FormattingUtilities.Match, MediaTypeFormatterMatchRanking.MatchOnRequestMediaType);\n                        }\n                    }\n                }\n            }\n\n            return null;\n        }\n\n        /// <summary>\n        /// Determine whether to match on type or not. This is used to determine whether to\n        /// generate a 406 response or use the default media type formatter in case there\n        /// is no match against anything in the request. If ExcludeMatchOnTypeOnly is true\n        /// then we don't match on type unless there are no accept headers.\n        /// </summary>\n        /// <param name=\"sortedAcceptValues\">The sorted accept header values to match.</param>\n        /// <returns>True if not ExcludeMatchOnTypeOnly and accept headers with a q-factor bigger than 0.0 are present.</returns>\n        protected virtual bool ShouldMatchOnType(IEnumerable<MediaTypeWithQualityHeaderValue> sortedAcceptValues)\n        {\n            if (sortedAcceptValues == null)\n            {\n                throw Error.ArgumentNull(\"sortedAcceptValues\");\n            }\n\n            return !(ExcludeMatchOnTypeOnly && sortedAcceptValues.Any());\n        }\n\n        /// <summary>\n        /// Pick the first supported media type and indicate we've matched only on type\n        /// </summary>\n        /// <param name=\"type\">The type to be serialized.</param>\n        /// <param name=\"formatter\">The formatter we are matching against.</param>\n        /// <returns>A <see cref=\"MediaTypeFormatterMatch\"/> indicating the quality of the match or null is no match.</returns>\n        protected virtual MediaTypeFormatterMatch MatchType(Type type, MediaTypeFormatter formatter)\n        {\n            // Performance-sensitive\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n            if (formatter == null)\n            {\n                throw Error.ArgumentNull(\"formatter\");\n            }\n\n            // We already know that we do match on type -- otherwise we wouldn't even be called --\n            // so this is just a matter of determining how we match.\n            MediaTypeHeaderValue mediaType = null;\n            List<MediaTypeHeaderValue> supportedMediaTypes = formatter.SupportedMediaTypesInternal;\n            if (supportedMediaTypes.Count > 0)\n            {\n                mediaType = supportedMediaTypes[0];\n            }\n            return new MediaTypeFormatterMatch(formatter, mediaType, FormattingUtilities.Match, MediaTypeFormatterMatchRanking.MatchOnCanWriteType);\n        }\n\n        /// <summary>\n        /// Sort Accept header values and related header field values with similar syntax rules\n        /// (if more than 1) in descending order based on q-factor.\n        /// </summary>\n        /// <param name=\"headerValues\">The header values to sort.</param>\n        /// <returns>The sorted header values.</returns>\n        protected virtual IEnumerable<MediaTypeWithQualityHeaderValue> SortMediaTypeWithQualityHeaderValuesByQFactor(ICollection<MediaTypeWithQualityHeaderValue> headerValues)\n        {\n            if (headerValues == null)\n            {\n                throw Error.ArgumentNull(\"headerValues\");\n            }\n\n            if (headerValues.Count > 1)\n            {\n                // Use OrderBy() instead of Array.Sort() as it performs fewer comparisons. In this case the comparisons\n                // are quite expensive so OrderBy() performs better.\n                return headerValues.OrderByDescending(m => m, MediaTypeWithQualityHeaderValueComparer.QualityComparer).ToArray();\n            }\n            else\n            {\n                return headerValues;\n            }\n        }\n\n        /// <summary>\n        /// Sort Accept-Charset, Accept-Encoding, Accept-Language and related header field values with similar syntax rules\n        /// (if more than 1) in descending order based on q-factor.\n        /// </summary>\n        /// <param name=\"headerValues\">The header values to sort.</param>\n        /// <returns>The sorted header values.</returns>\n        protected virtual IEnumerable<StringWithQualityHeaderValue> SortStringWithQualityHeaderValuesByQFactor(ICollection<StringWithQualityHeaderValue> headerValues)\n        {\n            if (headerValues == null)\n            {\n                throw Error.ArgumentNull(\"headerValues\");\n            }\n\n            if (headerValues.Count > 1)\n            {\n                // Use OrderBy() instead of Array.Sort() as it performs fewer comparisons. In this case the comparisons\n                // are quite expensive so OrderBy() performs better.\n                return headerValues.OrderByDescending(m => m, StringWithQualityHeaderValueComparer.QualityComparer).ToArray();\n            }\n            else\n            {\n                return headerValues;\n            }\n        }\n\n        /// <summary>\n        /// Evaluates whether a match is better than the current match and if so returns the replacement; otherwise returns the\n        /// current match.\n        /// </summary>\n        protected virtual MediaTypeFormatterMatch UpdateBestMatch(MediaTypeFormatterMatch current, MediaTypeFormatterMatch potentialReplacement)\n        {\n            if (potentialReplacement == null)\n            {\n                return current;\n            }\n\n            if (current != null)\n            {\n                return (potentialReplacement.Quality > current.Quality) ? potentialReplacement : current;\n            }\n\n            return potentialReplacement;\n        }\n\n        private static MediaTypeFormatter[] GetWritingFormatters(IEnumerable<MediaTypeFormatter> formatters)\n        {\n            Contract.Assert(formatters != null);\n            MediaTypeFormatterCollection formatterCollection = formatters as MediaTypeFormatterCollection;\n            if (formatterCollection != null)\n            {\n                return formatterCollection.WritingFormatters;\n            }\n            return formatters.AsArray();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/DelegatingEnumerable.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Web.Http;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// Helper class to serialize <see cref=\"IEnumerable{T}\"/> types by delegating them through a concrete implementation.\"/>.\n    /// </summary>\n    /// <typeparam name=\"T\">The interface implementing <see cref=\"IEnumerable{T}\"/> to proxy.</typeparam>\n    [SuppressMessage(\"Microsoft.Naming\", \"CA1710:IdentifiersShouldHaveCorrectSuffix\", Justification = \"Enumerable conveys the meaning of collection\")]\n    public sealed class DelegatingEnumerable<T> : IEnumerable<T>\n    {\n        private IEnumerable<T> _source;\n\n        /// <summary>\n        /// Initialize a DelegatingEnumerable. This constructor is necessary for <see cref=\"System.Runtime.Serialization.DataContractSerializer\"/> to work.\n        /// </summary>\n        public DelegatingEnumerable()\n        {\n            _source = Enumerable.Empty<T>();\n        }\n\n        /// <summary>\n        /// Initialize a DelegatingEnumerable with an <see cref=\"IEnumerable{T}\"/>. This is a helper class to proxy <see cref=\"IEnumerable{T}\"/> interfaces for <see cref=\"System.Xml.Serialization.XmlSerializer\"/>.\n        /// </summary>\n        /// <param name=\"source\">The <see cref=\"IEnumerable{T}\"/> instance to get the enumerator from.</param>\n        public DelegatingEnumerable(IEnumerable<T> source)\n        {\n            if (source == null)\n            {\n                throw Error.ArgumentNull(\"source\");\n            }\n            _source = source;\n        }\n\n        /// <summary>\n        /// Get the enumerator of the associated <see cref=\"IEnumerable{T}\"/>.\n        /// </summary>\n        /// <returns>The enumerator of the <see cref=\"IEnumerable{T}\"/> source.</returns>\n        public IEnumerator<T> GetEnumerator()\n        {\n            return _source.GetEnumerator();\n        }\n\n        /// <summary>\n        /// This method is not implemented but is required method for serialization to work. Do not use.\n        /// </summary>\n        /// <param name=\"item\">The item to add. Unused.</param>\n        [SuppressMessage(\"Microsoft.Usage\", \"CA1801:ReviewUnusedParameters\", Justification = \"Required by XmlSerializer, never used.\")]\n        public void Add(object item)\n        {\n            throw new NotImplementedException();\n        }\n\n        /// <summary>\n        /// Get the enumerator of the associated <see cref=\"IEnumerable{T}\"/>.\n        /// </summary>\n        /// <returns>The enumerator of the <see cref=\"IEnumerable{T}\"/> source.</returns>\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return _source.GetEnumerator();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/FormDataCollection.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Net.Http.Formatting.Internal;\nusing System.Net.Http.Formatting.Parsers;\nusing System.Text;\nusing System.Threading;\nusing System.Web.Http;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// Represent the form data.\n    /// - This has 100% fidelity (including ordering, which is important for deserializing ordered array).\n    /// - using interfaces allows us to optimize the implementation. E.g., we can avoid eagerly string-splitting a 10gb file.\n    /// - This also provides a convenient place to put extension methods.\n    /// </summary>\n    public class FormDataCollection : IEnumerable<KeyValuePair<string, string>>\n    {\n        private readonly IEnumerable<KeyValuePair<string, string>> _pairs;\n\n        private NameValueCollection _nameValueCollection;\n\n        /// <summary>\n        /// Initialize a form collection around incoming data.\n        /// The key value enumeration should be immutable.\n        /// </summary>\n        /// <param name=\"pairs\">incoming set of key value pairs. Ordering is preserved.</param>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is the convention for representing FormData\")]\n        public FormDataCollection(IEnumerable<KeyValuePair<string, string>> pairs)\n        {\n            if (pairs == null)\n            {\n                throw Error.ArgumentNull(\"pairs\");\n            }\n            _pairs = pairs;\n        }\n\n        /// <summary>\n        /// Initialize a form collection from a query string.\n        /// Uri and FormURl body have the same schema.\n        /// </summary>\n        public FormDataCollection(Uri uri)\n        {\n            if (uri == null)\n            {\n                throw Error.ArgumentNull(\"uri\");\n            }\n\n            string query = uri.Query;\n            if (query != null && query.Length > 0 && query[0] == '?')\n            {\n                query = query.Substring(1);\n            }\n\n            _pairs = ParseQueryString(query);\n        }\n\n        /// <summary>\n        /// Initialize a form collection from a URL encoded query string. Any leading question\n        /// mark (?) will be considered part of the query string and treated as any other value.\n        /// </summary>\n        [System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Design\", \"CA1057:StringUriOverloadsCallSystemUriOverloads\", Justification = \"string is a query string, not a URI\")]\n        public FormDataCollection(string query)\n        {\n            _pairs = ParseQueryString(query);\n        }\n\n        /// <summary>\n        /// Gets values associated with a given key. If there are multiple values, they're concatenated.\n        /// </summary>\n        /// <param name=\"name\">The name of the entry that contains the values to get. The name can be null.</param>\n        /// <returns>Values associated with a given key. If there are multiple values, they're concatenated.</returns>\n        public string this[string name]\n        {\n            get\n            {\n                return Get(name);\n            }\n        }\n\n        // Helper to invoke parser around a query string\n        private static IEnumerable<KeyValuePair<string, string>> ParseQueryString(string query)\n        {\n            List<KeyValuePair<string, string>> result = new List<KeyValuePair<string, string>>();\n            if (String.IsNullOrWhiteSpace(query))\n            {\n                return result;\n            }\n\n            byte[] bytes = Encoding.UTF8.GetBytes(query);\n\n            FormUrlEncodedParser parser = new FormUrlEncodedParser(result, Int64.MaxValue);\n\n            int bytesConsumed = 0;\n            ParserState state = parser.ParseBuffer(bytes, bytes.Length, ref bytesConsumed, isFinal: true);\n\n            if (state != ParserState.Done)\n            {\n                throw Error.InvalidOperation(Properties.Resources.FormUrlEncodedParseError, bytesConsumed);\n            }\n\n            return result;\n        }\n\n        /// <summary>\n        /// Get the collection as a NameValueCollection.\n        /// Beware this loses some ordering. Values are ordered within a key,\n        /// but keys are no longer ordered against each other.\n        /// </summary>\n        public NameValueCollection ReadAsNameValueCollection()\n        {\n            if (_nameValueCollection == null)\n            {\n                // Initialize in a private collection to be thread-safe, and swap the finished object.\n                // Ok to double initialize this.\n                HttpValueCollection newCollection = HttpValueCollection.Create(this);\n                Interlocked.Exchange(ref _nameValueCollection, newCollection);\n            }\n            return _nameValueCollection;\n        }\n\n        /// <summary>\n        /// Get values associated with a given key. If there are multiple values, they're concatenated.\n        /// </summary>\n        public string Get(string key)\n        {\n            return ReadAsNameValueCollection().Get(key);\n        }\n\n        /// <summary>\n        /// Get a value associated with a given key.\n        /// </summary>\n        public string[] GetValues(string key)\n        {\n            return ReadAsNameValueCollection().GetValues(key);\n        }\n\n        public IEnumerator<KeyValuePair<string, string>> GetEnumerator()\n        {\n            return _pairs.GetEnumerator();\n        }\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            IEnumerable ie = _pairs;\n            return ie.GetEnumerator();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/FormUrlEncodedJson.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Linq;\nusing System.Text;\nusing System.Web.Http;\nusing Newtonsoft.Json.Linq;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// This class provides a low-level API for parsing HTML form URL-encoded data, also known as <c>application/x-www-form-urlencoded</c>\n    /// data. The output of the parser is a <see cref=\"JObject\"/> instance.\n    /// <remarks>This is a low-level API intended for use by other APIs. It has been optimized for performance and\n    /// is not intended to be called directly from user code.</remarks>\n    /// </summary>\n    internal static class FormUrlEncodedJson\n    {\n        private const string ApplicationFormUrlEncoded = @\"application/x-www-form-urlencoded\";\n        private const int MinDepth = 0;\n\n        private static readonly string[] _emptyPath = new string[]\n        {\n            String.Empty\n        };\n\n        /// <summary>\n        /// Parses a collection of query string values as a <see cref=\"JObject\"/>.\n        /// </summary>\n        /// <remarks>This is a low-level API intended for use by other APIs. It has been optimized for performance and\n        /// is not intended to be called directly from user code.</remarks>\n        /// <param name=\"nameValuePairs\">The collection of query string name-value pairs parsed in lexical order. Both names\n        /// and values must be un-escaped so that they don't contain any <see cref=\"Uri\"/> encoding.</param>\n        /// <returns>The <see cref=\"JObject\"/> corresponding to the given query string values.</returns>\n        public static JObject Parse(IEnumerable<KeyValuePair<string, string>> nameValuePairs)\n        {\n            return ParseInternal(nameValuePairs, Int32.MaxValue, true);\n        }\n\n        /// <summary>\n        /// Parses a collection of query string values as a <see cref=\"JObject\"/>.\n        /// </summary>\n        /// <remarks>This is a low-level API intended for use by other APIs. It has been optimized for performance and\n        /// is not intended to be called directly from user code.</remarks>\n        /// <param name=\"nameValuePairs\">The collection of query string name-value pairs parsed in lexical order. Both names\n        /// and values must be un-escaped so that they don't contain any <see cref=\"Uri\"/> encoding.</param>\n        /// <param name=\"maxDepth\">The maximum depth of object graph encoded as <c>x-www-form-urlencoded</c>.</param>\n        /// <returns>The <see cref=\"JObject\"/> corresponding to the given query string values.</returns>\n        public static JObject Parse(IEnumerable<KeyValuePair<string, string>> nameValuePairs, int maxDepth)\n        {\n            return ParseInternal(nameValuePairs, maxDepth, true);\n        }\n\n        /// <summary>\n        /// Parses a collection of query string values as a <see cref=\"JObject\"/>.\n        /// </summary>\n        /// <remarks>This is a low-level API intended for use by other APIs. It has been optimized for performance and\n        /// is not intended to be called directly from user code.</remarks>\n        /// <param name=\"nameValuePairs\">The collection of query string name-value pairs parsed in lexical order. Both names\n        /// and values must be un-escaped so that they don't contain any <see cref=\"Uri\"/> encoding.</param>\n        /// <param name=\"value\">The parsed result or null if parsing failed.</param>\n        /// <returns><c>true</c> if <paramref name=\"nameValuePairs\"/> was parsed successfully; otherwise false.</returns>\n        public static bool TryParse(IEnumerable<KeyValuePair<string, string>> nameValuePairs, out JObject value)\n        {\n            return (value = ParseInternal(nameValuePairs, Int32.MaxValue, false)) != null;\n        }\n\n        /// <summary>\n        /// Parses a collection of query string values as a <see cref=\"JObject\"/>.\n        /// </summary>\n        /// <remarks>This is a low-level API intended for use by other APIs. It has been optimized for performance and\n        /// is not intended to be called directly from user code.</remarks>\n        /// <param name=\"nameValuePairs\">The collection of query string name-value pairs parsed in lexical order. Both names\n        /// and values must be un-escaped so that they don't contain any <see cref=\"Uri\"/> encoding.</param>\n        /// <param name=\"maxDepth\">The maximum depth of object graph encoded as <c>x-www-form-urlencoded</c>.</param>\n        /// <param name=\"value\">The parsed result or null if parsing failed.</param>\n        /// <returns><c>true</c> if <paramref name=\"nameValuePairs\"/> was parsed successfully; otherwise false.</returns>\n        public static bool TryParse(IEnumerable<KeyValuePair<string, string>> nameValuePairs, int maxDepth, out JObject value)\n        {\n            return (value = ParseInternal(nameValuePairs, maxDepth, false)) != null;\n        }\n\n        /// <summary>\n        /// Parses a collection of query string values as a <see cref=\"JObject\"/>.\n        /// </summary>\n        /// <remarks>This is a low-level API intended for use by other APIs. It has been optimized for performance and\n        /// is not intended to be called directly from user code.</remarks>\n        /// <param name=\"nameValuePairs\">The collection of query string name-value pairs parsed in lexical order. Both names\n        /// and values must be un-escaped so that they don't contain any <see cref=\"Uri\"/> encoding.</param>\n        /// <param name=\"maxDepth\">The maximum depth of object graph encoded as <c>x-www-form-urlencoded</c>.</param>\n        /// <param name=\"throwOnError\">Indicates whether to throw an exception on error or return false</param>\n        /// <returns>The <see cref=\"JObject\"/> corresponding to the given query string values.</returns>\n        private static JObject ParseInternal(IEnumerable<KeyValuePair<string, string>> nameValuePairs, int maxDepth, bool throwOnError)\n        {\n            if (nameValuePairs == null)\n            {\n                throw Error.ArgumentNull(\"nameValuePairs\");\n            }\n\n            if (maxDepth <= MinDepth)\n            {\n                throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"maxDepth\", maxDepth, MinDepth + 1);\n            }\n\n            JObject result = new JObject();\n            foreach (var nameValuePair in nameValuePairs)\n            {\n                string key = nameValuePair.Key;\n                string value = nameValuePair.Value;\n\n                // value is preserved, even if it's null, \"undefined\", \"null\", String.Empty, etc when converting to JToken.\n\n                if (key == null)\n                {\n                    if (String.IsNullOrEmpty(value))\n                    {\n                        if (throwOnError)\n                        {\n                            throw Error.Argument(\"nameValuePairs\", Properties.Resources.QueryStringNameShouldNotNull);\n                        }\n\n                        return null;\n                    }\n\n                    string[] path = new string[] { value };\n                    if (!Insert(result, path, null, throwOnError))\n                    {\n                        return null;\n                    }\n                }\n                else\n                {\n                    string[] path = GetPath(key, maxDepth, throwOnError);\n                    if (path == null || !Insert(result, path, value, throwOnError))\n                    {\n                        return null;\n                    }\n                }\n            }\n\n            FixContiguousArrays(result);\n            return result;\n        }\n\n        private static string[] GetPath(string key, int maxDepth, bool throwOnError)\n        {\n            Contract.Assert(key != null, \"Key cannot be null (this function is only called by Parse if key != null)\");\n\n            if (String.IsNullOrWhiteSpace(key))\n            {\n                return _emptyPath;\n            }\n\n            if (!ValidateQueryString(key, throwOnError))\n            {\n                return null;\n            }\n\n            string[] path = key.Split('[');\n            for (int i = 0; i < path.Length; i++)\n            {\n                if (path[i].EndsWith(\"]\", StringComparison.Ordinal))\n                {\n                    path[i] = path[i].Substring(0, path[i].Length - 1);\n                }\n            }\n\n            // For consistency with JSON, the depth of a[b]=1 is 3 (which is the depth of {a:{b:1}}, given\n            // that in the JSON-XML mapping there's a <root> element wrapping the JSON object:\n            // <root><a><b>1</b></a></root>. So if the length of the path is greater than *or equal* to\n            // maxDepth, then we throw.\n            if (path.Length >= maxDepth)\n            {\n                if (throwOnError)\n                {\n                    throw Error.Argument(Properties.Resources.MaxDepthExceeded, maxDepth);\n                }\n\n                return null;\n            }\n\n            return path;\n        }\n\n        private static bool ValidateQueryString(string key, bool throwOnError)\n        {\n            bool hasUnMatchedLeftBraket = false;\n            for (int i = 0; i < key.Length; i++)\n            {\n                switch (key[i])\n                {\n                    case '[':\n                        if (!hasUnMatchedLeftBraket)\n                        {\n                            hasUnMatchedLeftBraket = true;\n                        }\n                        else\n                        {\n                            if (throwOnError)\n                            {\n                                throw Error.Argument(Properties.Resources.NestedBracketNotValid, ApplicationFormUrlEncoded, i);\n                            }\n\n                            return false;\n                        }\n\n                        break;\n                    case ']':\n                        if (hasUnMatchedLeftBraket)\n                        {\n                            hasUnMatchedLeftBraket = false;\n                        }\n                        else\n                        {\n                            if (throwOnError)\n                            {\n                                throw Error.Argument(Properties.Resources.UnMatchedBracketNotValid, ApplicationFormUrlEncoded, i);\n                            }\n\n                            return false;\n                        }\n\n                        break;\n                }\n            }\n\n            if (hasUnMatchedLeftBraket)\n            {\n                if (throwOnError)\n                {\n                    throw Error.Argument(Properties.Resources.NestedBracketNotValid, ApplicationFormUrlEncoded, key.LastIndexOf('['));\n                }\n\n                return false;\n            }\n\n            return true;\n        }\n\n        private static bool Insert(JObject root, string[] path, string value, bool throwOnError)\n        {\n            // to-do: verify consistent with new parsing, whether single value is in path or value\n            Contract.Assert(root != null, \"Root object can't be null\");\n\n            JObject current = root;\n            JObject parent = null;\n\n            for (int i = 0; i < path.Length - 1; i++)\n            {\n                if (String.IsNullOrEmpty(path[i]))\n                {\n                    if (throwOnError)\n                    {\n                        throw Error.Argument(Properties.Resources.InvalidArrayInsert, BuildPathString(path, i));\n                    }\n\n                    return false;\n                }\n\n                if (!((IDictionary<string, JToken>)current).ContainsKey(path[i]))\n                {\n                    current[path[i]] = new JObject();\n                }\n                else\n                {\n                    // Since the loop goes up to the next-to-last item in the path, if we hit a null\n                    // or a primitive, then we have a mismatching node.\n                    if (current[path[i]] == null || current[path[i]] is JValue)\n                    {\n                        if (throwOnError)\n                        {\n                            throw Error.Argument(Properties.Resources.FormUrlEncodedMismatchingTypes, BuildPathString(path, i));\n                        }\n\n                        return false;\n                    }\n                }\n\n                parent = current;\n                current = current[path[i]] as JObject;\n            }\n\n            string lastKey = path[path.Length - 1];\n            if (String.IsNullOrEmpty(lastKey) && path.Length > 1)\n            {\n                if (!AddToArray(parent, path, value, throwOnError))\n                {\n                    return false;\n                }\n            }\n            else\n            {\n                if (current == null)\n                {\n                    if (throwOnError)\n                    {\n                        throw Error.Argument(Properties.Resources.FormUrlEncodedMismatchingTypes, BuildPathString(path, path.Length - 1));\n                    }\n\n                    return false;\n                }\n\n                if (!AddToObject(current, path, value, throwOnError))\n                {\n                    return false;\n                }\n            }\n\n            return true;\n        }\n\n        private static bool AddToObject(JObject obj, string[] path, string value, bool throwOnError)\n        {\n            Contract.Assert(obj != null, \"JsonObject cannot be null\");\n\n            int pathIndex = path.Length - 1;\n            string key = path[pathIndex];\n\n            if (((IDictionary<string, JToken>)obj).ContainsKey(key))\n            {\n                if (obj[key] == null || obj[key].Type == JTokenType.Null)\n                {\n                    if (throwOnError)\n                    {\n                        throw Error.Argument(Properties.Resources.FormUrlEncodedMismatchingTypes, BuildPathString(path, pathIndex));\n                    }\n\n                    return false;\n                }\n\n                bool isRoot = path.Length == 1;\n                if (isRoot)\n                {\n                    // jQuery 1.3 behavior, make it into an array(object) if primitive\n                    if (obj[key].Type == JTokenType.String)\n                    {\n                        string oldValue = obj[key].ToObject<string>();\n                        JObject jo = new JObject();\n                        jo.Add(\"0\", oldValue);\n                        jo.Add(\"1\", value);\n                        obj[key] = jo;\n                    }\n                    else if (obj[key] is JObject)\n                    {\n                        // if it was already an object, simply add the value\n                        JObject jo = obj[key] as JObject;\n                        string index = GetIndex(jo, throwOnError);\n                        if (index == null)\n                        {\n                            return false;\n                        }\n\n                        jo.Add(index, value);\n                    }\n                }\n                else\n                {\n                    if (throwOnError)\n                    {\n                        throw Error.Argument(Properties.Resources.JQuery13CompatModeNotSupportNestedJson, BuildPathString(path, pathIndex));\n                    }\n\n                    return false;\n                }\n            }\n            else\n            {\n                // if the object didn't contain the key, simply add it now\n                // the null check here is necessary because otherwise the created JValue type will be implictly cast as a string JValue\n                if (value == null)\n                {\n                    obj[key] = null;\n                }\n                else\n                {\n                    obj[key] = value;\n                }\n            }\n\n            return true;\n        }\n\n        // JsonObject passed in is semantically an array\n        private static bool AddToArray(JObject parent, string[] path, string value, bool throwOnError)\n        {\n            Contract.Assert(parent != null, \"Parent cannot be null\");\n            Contract.Assert(path.Length >= 2, \"The path must be at least 2, one for the ending [], and one for before the '[' (which can be empty)\");\n\n            string parentPath = path[path.Length - 2];\n\n            Contract.Assert(((IDictionary<string, JToken>)parent).ContainsKey(parentPath), \"It was added on insert to get to this point\");\n            JObject jo = parent[parentPath] as JObject;\n\n            if (jo == null)\n            {\n                // a[b][c]=1&a[b][]=2 => invalid\n                if (throwOnError)\n                {\n                    throw Error.Argument(Properties.Resources.FormUrlEncodedMismatchingTypes, BuildPathString(path, path.Length - 1));\n                }\n\n                return false;\n            }\n            else\n            {\n                string index = GetIndex(jo, throwOnError);\n                if (index == null)\n                {\n                    return false;\n                }\n\n                jo.Add(index, value);\n            }\n\n            return true;\n        }\n\n        // TODO: consider optimize it by only look at the last one\n        private static string GetIndex(JObject jsonObject, bool throwOnError)\n        {\n            int max = -1;\n            if (jsonObject.Count > 0)\n            {\n                IEnumerable<string> keys = ((IDictionary<string, JToken>)jsonObject).Keys;\n                foreach (var key in keys)\n                {\n                    int tempInt;\n                    if (Int32.TryParse(key, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out tempInt) && tempInt > max)\n                    {\n                        max = tempInt;\n                    }\n                    else\n                    {\n                        if (throwOnError)\n                        {\n                            throw Error.Argument(Properties.Resources.FormUrlEncodedMismatchingTypes, key);\n                        }\n\n                        return null;\n                    }\n                }\n            }\n\n            max++;\n            return max.ToString(CultureInfo.InvariantCulture);\n        }\n\n        private static void FixContiguousArrays(JToken jv)\n        {\n            JArray ja = jv as JArray;\n\n            if (ja != null)\n            {\n                for (int i = 0; i < ja.Count; i++)\n                {\n                    if (ja[i] != null)\n                    {\n                        ja[i] = FixSingleContiguousArray(ja[i]);\n                        FixContiguousArrays(ja[i]);\n                    }\n                }\n            }\n            else\n            {\n                JObject jo = jv as JObject;\n\n                if (jo != null && jo.Count > 0)\n                {\n                    List<string> keys = new List<string>(((IDictionary<string, JToken>)jo).Keys);\n                    foreach (string key in keys)\n                    {\n                        if (jo[key] != null)\n                        {\n                            jo[key] = FixSingleContiguousArray(jo[key]);\n                            FixContiguousArrays(jo[key]);\n                        }\n                    }\n                }\n            }\n\n            //// do nothing for primitives\n        }\n\n        private static JToken FixSingleContiguousArray(JToken original)\n        {\n            JObject jo = original as JObject;\n            if (jo != null && jo.Count > 0)\n            {\n                List<string> childKeys = new List<string>(((IDictionary<string, JToken>)jo).Keys);\n                List<string> sortedKeys;\n                if (CanBecomeArray(childKeys, out sortedKeys))\n                {\n                    JArray newResult = new JArray();\n                    foreach (string sortedKey in sortedKeys)\n                    {\n                        newResult.Add(jo[sortedKey]);\n                    }\n\n                    return newResult;\n                }\n            }\n\n            return original;\n        }\n\n        private static bool CanBecomeArray(List<string> keys, out List<string> sortedKeys)\n        {\n            List<ArrayCandidate> intKeys = new List<ArrayCandidate>();\n            sortedKeys = null;\n            bool areContiguousIndices = true;\n            foreach (string key in keys)\n            {\n                int intKey;\n                if (!Int32.TryParse(key, NumberStyles.None, CultureInfo.InvariantCulture, out intKey))\n                {\n                    // if not a non-negative number, it cannot become an array\n                    areContiguousIndices = false;\n                    break;\n                }\n\n                string strKey = intKey.ToString(CultureInfo.InvariantCulture);\n                if (!strKey.Equals(key, StringComparison.Ordinal))\n                {\n                    // int.Parse returned true, but it's not really the same number.\n                    // It's the case for strings such as \"1\\0\".\n                    areContiguousIndices = false;\n                    break;\n                }\n\n                intKeys.Add(new ArrayCandidate(intKey, strKey));\n            }\n\n            if (areContiguousIndices)\n            {\n                intKeys.Sort((x, y) => x.Key - y.Key);\n\n                for (int i = 0; i < intKeys.Count; i++)\n                {\n                    if (intKeys[i].Key != i)\n                    {\n                        areContiguousIndices = false;\n                        break;\n                    }\n                }\n            }\n\n            if (areContiguousIndices)\n            {\n                sortedKeys = new List<string>(intKeys.Select(x => x.Value));\n            }\n\n            return areContiguousIndices;\n        }\n\n        private static string BuildPathString(string[] path, int i)\n        {\n            StringBuilder errorPath = new StringBuilder(path[0]);\n            for (int p = 1; p <= i; p++)\n            {\n                errorPath.AppendFormat(CultureInfo.InvariantCulture, \"[{0}]\", path[p]);\n            }\n\n            return errorPath.ToString();\n        }\n\n        /// <summary>\n        /// Class that wraps key-value pairs.\n        /// </summary>\n        /// <remarks>\n        /// This use of this class avoids a FxCop warning CA908 which happens if using various generic types.\n        /// </remarks>\n        private class ArrayCandidate\n        {\n            /// <summary>\n            /// Initializes a new instance of the <see cref=\"ArrayCandidate\"/> class.\n            /// </summary>\n            /// <param name=\"key\">The key of this <see cref=\"ArrayCandidate\"/> instance.</param>\n            /// <param name=\"value\">The value of this <see cref=\"ArrayCandidate\"/> instance.</param>\n            public ArrayCandidate(int key, string value)\n            {\n                Key = key;\n                Value = value;\n            }\n\n            /// <summary>\n            /// Gets or sets the key of this <see cref=\"ArrayCandidate\"/> instance.\n            /// </summary>\n            /// <value>\n            /// The key of this <see cref=\"ArrayCandidate\"/> instance.\n            /// </value>\n            public int Key { get; set; }\n\n            /// <summary>\n            /// Gets or sets the value of this <see cref=\"ArrayCandidate\"/> instance.\n            /// </summary>\n            /// <value>\n            /// The value of this <see cref=\"ArrayCandidate\"/> instance.\n            /// </value>\n            public string Value { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/FormUrlEncodedMediaTypeFormatter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.IO;\nusing System.Net.Http.Formatting.Parsers;\nusing System.Net.Http.Headers;\nusing System.Threading.Tasks;\nusing System.Web.Http;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// <see cref=\"MediaTypeFormatter\"/> class for handling HTML form URL-ended data, also known as <c>application/x-www-form-urlencoded</c>.\n    /// </summary>\n    public class FormUrlEncodedMediaTypeFormatter : MediaTypeFormatter\n    {\n        private const int MinBufferSize = 256;\n        private const int DefaultBufferSize = 32 * 1024;\n\n        private int _readBufferSize = DefaultBufferSize;\n        private int _maxDepth = FormattingUtilities.DefaultMaxDepth;\n        private readonly bool _isDerived;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"FormUrlEncodedMediaTypeFormatter\"/> class.\n        /// </summary>\n        public FormUrlEncodedMediaTypeFormatter()\n        {\n            SupportedMediaTypes.Add(MediaTypeConstants.ApplicationFormUrlEncodedMediaType);\n            _isDerived = GetType() != typeof(FormUrlEncodedMediaTypeFormatter);\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"FormUrlEncodedMediaTypeFormatter\"/> class.\n        /// </summary>\n        /// <param name=\"formatter\">The <see cref=\"FormUrlEncodedMediaTypeFormatter\"/> instance to copy settings from.</param>\n        protected FormUrlEncodedMediaTypeFormatter(FormUrlEncodedMediaTypeFormatter formatter)\n            : base(formatter)\n        {\n            MaxDepth = formatter.MaxDepth;\n            ReadBufferSize = formatter.ReadBufferSize;\n            _isDerived = GetType() != typeof(FormUrlEncodedMediaTypeFormatter);\n        }\n\n        /// <summary>\n        /// Gets the default media type for HTML Form URL encoded data, namely <c>application/x-www-form-urlencoded</c>.\n        /// </summary>\n        /// <value>\n        /// Because <see cref=\"MediaTypeHeaderValue\"/> is mutable, the value\n        /// returned will be a new instance every time.\n        /// </value>\n        public static MediaTypeHeaderValue DefaultMediaType\n        {\n            get { return MediaTypeConstants.ApplicationFormUrlEncodedMediaType; }\n        }\n\n        /// <summary>\n        /// Gets or sets the maximum depth allowed by this formatter.\n        /// </summary>\n        public int MaxDepth\n        {\n            get\n            {\n                return _maxDepth;\n            }\n            set\n            {\n                if (value < FormattingUtilities.DefaultMinDepth)\n                {\n                    throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"value\", value, FormattingUtilities.DefaultMinDepth);\n                }\n\n                _maxDepth = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets the size of the buffer when reading the incoming stream.\n        /// </summary>\n        /// <value>\n        /// The size of the read buffer.\n        /// </value>\n        public int ReadBufferSize\n        {\n            get { return _readBufferSize; }\n\n            set\n            {\n                if (value < MinBufferSize)\n                {\n                    throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"value\", value, MinBufferSize);\n                }\n\n                _readBufferSize = value;\n            }\n        }\n\n        internal override bool CanWriteAnyTypes\n        {\n            get\n            {\n                return _isDerived;\n            }\n        }\n\n        /// <summary>\n        /// Determines whether this <see cref=\"FormUrlEncodedMediaTypeFormatter\"/> can read objects\n        /// of the specified <paramref name=\"type\"/>.\n        /// </summary>\n        /// <param name=\"type\">The type of object that will be read.</param>\n        /// <returns><c>true</c> if objects of this <paramref name=\"type\"/> can be read, otherwise <c>false</c>.</returns>\n        public override bool CanReadType(Type type)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            // Can't read arbitrary types.\n            return type == typeof(FormDataCollection) || FormattingUtilities.IsJTokenType(type);\n        }\n\n        /// <summary>\n        /// Determines whether this <see cref=\"FormUrlEncodedMediaTypeFormatter\"/> can write objects\n        /// of the specified <paramref name=\"type\"/>.\n        /// </summary>\n        /// <param name=\"type\">The type of object that will be written.</param>\n        /// <returns><c>true</c> if objects of this <paramref name=\"type\"/> can be written, otherwise <c>false</c>.</returns>\n        public override bool CanWriteType(Type type)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            return false;\n        }\n\n        /// <summary>\n        /// Called during deserialization to read an object of the specified <paramref name=\"type\"/>\n        /// from the specified <paramref name=\"readStream\"/>.\n        /// </summary>\n        /// <param name=\"type\">The type of object to read.</param>\n        /// <param name=\"readStream\">The <see cref=\"Stream\"/> from which to read.</param>\n        /// <param name=\"content\">The <see cref=\"HttpContent\"/> for the content being read.</param>\n        /// <param name=\"formatterLogger\">The <see cref=\"IFormatterLogger\"/> to log events to.</param>\n        /// <returns>A <see cref=\"Task\"/> whose result will be the object instance that has been read.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"The caught exception type is reflected into a faulted task.\")]\n        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            if (readStream == null)\n            {\n                throw Error.ArgumentNull(\"readStream\");\n            }\n\n            try\n            {\n                return Task.FromResult(ReadFromStream(type, readStream));\n            }\n            catch (Exception e)\n            {\n                return TaskHelpers.FromError<object>(e);\n            }\n        }\n\n        private object ReadFromStream(Type type, Stream readStream)\n        {\n            object result;\n            IEnumerable<KeyValuePair<string, string>> nameValuePairs = ReadFormUrlEncoded(readStream, ReadBufferSize);\n\n            if (type == typeof(FormDataCollection))\n            {\n                result = new FormDataCollection(nameValuePairs);\n            }\n            else if (FormattingUtilities.IsJTokenType(type))\n            {\n                result = FormUrlEncodedJson.Parse(nameValuePairs, _maxDepth);\n            }\n            else\n            {\n                // Passed us an unsupported type. Should have called CanReadType() first.\n                throw Error.InvalidOperation(Properties.Resources.SerializerCannotSerializeType, GetType().Name, type.Name);\n            }\n            return result;\n        }\n\n        /// <summary>\n        /// Reads all name-value pairs encoded as HTML Form URL encoded data and add them to\n        /// a collection as UNescaped URI strings.\n        /// </summary>\n        /// <param name=\"input\">Stream to read from.</param>\n        /// <param name=\"bufferSize\">Size of the buffer used to read the contents.</param>\n        /// <returns>Collection of name-value pairs.</returns>\n        private static IEnumerable<KeyValuePair<string, string>> ReadFormUrlEncoded(Stream input, int bufferSize)\n        {\n            Contract.Assert(input != null, \"input stream cannot be null\");\n            Contract.Assert(bufferSize >= MinBufferSize, \"buffer size cannot be less than MinBufferSize\");\n\n            byte[] data = new byte[bufferSize];\n\n            int bytesRead;\n            bool isFinal = false;\n            List<KeyValuePair<string, string>> result = new List<KeyValuePair<string, string>>();\n            FormUrlEncodedParser parser = new FormUrlEncodedParser(result, Int64.MaxValue);\n            ParserState state;\n\n            while (true)\n            {\n                try\n                {\n                    bytesRead = input.Read(data, 0, data.Length);\n                    if (bytesRead == 0)\n                    {\n                        isFinal = true;\n                    }\n                }\n                catch (Exception e)\n                {\n                    throw Error.InvalidOperation(e, Properties.Resources.ErrorReadingFormUrlEncodedStream);\n                }\n\n                int bytesConsumed = 0;\n                state = parser.ParseBuffer(data, bytesRead, ref bytesConsumed, isFinal);\n                if (state != ParserState.NeedMoreData && state != ParserState.Done)\n                {\n                    throw Error.InvalidOperation(Properties.Resources.FormUrlEncodedParseError, bytesConsumed);\n                }\n\n                if (isFinal)\n                {\n                    return result;\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/IContentNegotiator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http.Headers;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// Performs content negotiation. \n    /// This is the process of selecting a response writer (formatter) in compliance with header values in the request.\n    /// </summary>\n    public interface IContentNegotiator\n    {\n        /// <summary>\n        /// Performs content negotiating by selecting the most appropriate <see cref=\"MediaTypeFormatter\"/> out of the passed in\n        /// <paramref name=\"formatters\"/> for the given <paramref name=\"request\"/> that can serialize an object of the given\n        /// <paramref name=\"type\"/>.\n        /// </summary>\n        /// <remarks>\n        /// Implementations of this method should call <see cref=\"MediaTypeFormatter.GetPerRequestFormatterInstance(Type, HttpRequestMessage, MediaTypeHeaderValue)\"/>\n        /// on the selected <see cref=\"MediaTypeFormatter\">formatter</see> and return the result of that method.\n        /// </remarks>\n        /// <param name=\"type\">The type to be serialized.</param>\n        /// <param name=\"request\">Request message, which contains the header values used to perform negotiation.</param>\n        /// <param name=\"formatters\">The set of <see cref=\"MediaTypeFormatter\"/> objects from which to choose.</param>\n        /// <returns>The result of the negotiation containing the most appropriate <see cref=\"MediaTypeFormatter\"/> instance,\n        /// or <c>null</c> if there is no appropriate formatter.</returns>\n        ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters);\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/IFormatterLogger.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// Interface to log events that occur during formatter reads.\n    /// </summary>\n    public interface IFormatterLogger\n    {\n        /// <summary>\n        /// Logs an error.\n        /// </summary>\n        /// <param name=\"errorPath\">The path to the member for which the error is being logged.</param>\n        /// <param name=\"errorMessage\">The error message to be logged.</param>\n        void LogError(string errorPath, string errorMessage);\n\n        /// <summary>\n        /// Logs an error.\n        /// </summary>\n        /// <param name=\"errorPath\">The path to the member for which the error is being logged.</param>\n        /// <param name=\"exception\">The exception to be logged.</param>\n        void LogError(string errorPath, Exception exception);\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/IRequiredMemberSelector.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// Interface to determine which data members on a particular type are required.\n    /// </summary>\n    public interface IRequiredMemberSelector\n    {\n        /// <summary>\n        /// Determines whether a given member is required on deserialization.\n        /// </summary>\n        /// <param name=\"member\">The <see cref=\"MemberInfo\"/> that will be deserialized.</param>\n        /// <returns><c>true</c> if <paramref name=\"member\"/> should be treated as a required member, otherwise <c>false</c>.</returns>\n        bool IsRequiredMember(MemberInfo member);\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/JsonContractResolver.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing System.Web.Http;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Serialization;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// Represents the default <see cref=\"IContractResolver\"/> used by <see cref=\"BaseJsonMediaTypeFormatter\"/>.\n    /// It uses the formatter's <see cref=\"IRequiredMemberSelector\"/> to select required members and recognizes\n    /// the <see cref=\"SerializableAttribute\"/> type annotation.\n    /// </summary>\n    public class JsonContractResolver : DefaultContractResolver\n    {\n        private readonly MediaTypeFormatter _formatter;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"JsonContractResolver\" /> class.\n        /// </summary>\n        /// <param name=\"formatter\">The formatter to use for resolving required members.</param>\n        public JsonContractResolver(MediaTypeFormatter formatter)\n        {\n            if (formatter == null)\n            {\n                throw Error.ArgumentNull(\"formatter\");\n            }\n\n            _formatter = formatter;\n\n#if !NETSTANDARD1_3\n            // Need this setting to have [Serializable] types serialized correctly\n            IgnoreSerializableAttribute = false;\n#endif\n        }\n\n        // Determines whether a member is required or not and sets the appropriate JsonProperty settings\n        private void ConfigureProperty(MemberInfo member, JsonProperty property)\n        {\n            if (_formatter.RequiredMemberSelector != null && _formatter.RequiredMemberSelector.IsRequiredMember(member))\n            {\n                property.Required = Required.AllowNull;\n                property.DefaultValueHandling = DefaultValueHandling.Include;\n                property.NullValueHandling = NullValueHandling.Include;\n            }\n            else\n            {\n                property.Required = Required.Default;\n            }\n        }\n\n        /// <inheritdoc />\n        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)\n        {\n            JsonProperty property = base.CreateProperty(member, memberSerialization);\n            ConfigureProperty(member, property);\n            return property;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/JsonMediaTypeFormatter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.IO;\nusing System.Net.Http.Headers;\n#if !NETSTANDARD1_3 // Unnecessary when targeting netstandard1.3.\nusing System.Net.Http.Internal;\n#endif\nusing System.Runtime.Serialization.Json;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http;\nusing System.Xml;\nusing Newtonsoft.Json;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// <see cref=\"MediaTypeFormatter\"/> class to handle Json.\n    /// </summary>\n    public class JsonMediaTypeFormatter : BaseJsonMediaTypeFormatter\n    {\n        private readonly ConcurrentDictionary<Type, DataContractJsonSerializer> _dataContractSerializerCache = new ConcurrentDictionary<Type, DataContractJsonSerializer>();\n        private readonly XmlDictionaryReaderQuotas _readerQuotas = FormattingUtilities.CreateDefaultReaderQuotas();\n        private readonly RequestHeaderMapping _requestHeaderMapping;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"JsonMediaTypeFormatter\"/> class.\n        /// </summary>\n        public JsonMediaTypeFormatter()\n        {\n            // Set default supported media types\n            SupportedMediaTypes.Add(MediaTypeConstants.ApplicationJsonMediaType);\n            SupportedMediaTypes.Add(MediaTypeConstants.TextJsonMediaType);\n\n            _requestHeaderMapping = new XmlHttpRequestHeaderMapping();\n            MediaTypeMappings.Add(_requestHeaderMapping);\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"JsonMediaTypeFormatter\"/> class.\n        /// </summary>\n        /// <param name=\"formatter\">The <see cref=\"JsonMediaTypeFormatter\"/> instance to copy settings from.</param>\n        protected JsonMediaTypeFormatter(JsonMediaTypeFormatter formatter)\n            : base(formatter)\n        {\n            Contract.Assert(formatter != null);\n\n            UseDataContractJsonSerializer = formatter.UseDataContractJsonSerializer;\n            Indent = formatter.Indent;\n        }\n\n        /// <summary>\n        /// Gets the default media type for Json, namely \"application/json\".\n        /// </summary>\n        /// <remarks>\n        /// The default media type does not have any <c>charset</c> parameter as\n        /// the <see cref=\"Encoding\"/> can be configured on a per <see cref=\"JsonMediaTypeFormatter\"/>\n        /// instance basis.\n        /// </remarks>\n        /// <value>\n        /// Because <see cref=\"MediaTypeHeaderValue\"/> is mutable, the value\n        /// returned will be a new instance every time.\n        /// </value>\n        public static MediaTypeHeaderValue DefaultMediaType\n        {\n            get { return MediaTypeConstants.ApplicationJsonMediaType; }\n        }\n\n        /// <summary>\n        /// Gets or sets a value indicating whether to use <see cref=\"DataContractJsonSerializer\"/> by default.\n        /// </summary>\n        /// <value>\n        ///     <c>true</c> if use <see cref=\"DataContractJsonSerializer\"/> by default; otherwise, <c>false</c>. The default is <c>false</c>.\n        /// </value>\n        public bool UseDataContractJsonSerializer { get; set; }\n\n        /// <summary>\n        /// Gets or sets a value indicating whether to indent elements when writing data.\n        /// </summary>\n        public bool Indent { get; set; }\n\n        /// <inheritdoc/>\n        public sealed override int MaxDepth\n        {\n            get\n            {\n                return base.MaxDepth;\n            }\n            set\n            {\n                base.MaxDepth = value;\n                _readerQuotas.MaxDepth = value;\n            }\n        }\n\n        /// <inheritdoc />\n        public override JsonReader CreateJsonReader(Type type, Stream readStream, Encoding effectiveEncoding)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            if (readStream == null)\n            {\n                throw Error.ArgumentNull(\"readStream\");\n            }\n\n            if (effectiveEncoding == null)\n            {\n                throw Error.ArgumentNull(\"effectiveEncoding\");\n            }\n\n            return new JsonTextReader(new StreamReader(readStream, effectiveEncoding));\n        }\n\n        /// <inheritdoc />\n        public override JsonWriter CreateJsonWriter(Type type, Stream writeStream, Encoding effectiveEncoding)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            if (writeStream == null)\n            {\n                throw Error.ArgumentNull(\"writeStream\");\n            }\n\n            if (effectiveEncoding == null)\n            {\n                throw Error.ArgumentNull(\"effectiveEncoding\");\n            }\n\n            JsonWriter jsonWriter = new JsonTextWriter(new StreamWriter(writeStream, effectiveEncoding));\n            if (Indent)\n            {\n                jsonWriter.Formatting = Newtonsoft.Json.Formatting.Indented;\n            }\n\n            return jsonWriter;\n        }\n\n        /// <inheritdoc />\n        public override bool CanReadType(Type type)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            if (UseDataContractJsonSerializer)\n            {\n                // If there is a registered non-null serializer, we can support this type.\n                DataContractJsonSerializer serializer =\n                    _dataContractSerializerCache.GetOrAdd(type, (t) => CreateDataContractSerializer(t, throwOnError: false));\n\n                // Null means we tested it before and know it is not supported\n                return serializer != null;\n            }\n            else\n            {\n                return base.CanReadType(type);\n            }\n        }\n\n        /// <inheritdoc />\n        public override bool CanWriteType(Type type)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            if (UseDataContractJsonSerializer)\n            {\n                MediaTypeFormatter.TryGetDelegatingTypeForIQueryableGenericOrSame(ref type);\n\n                // If there is a registered non-null serializer, we can support this type.\n                object serializer =\n                    _dataContractSerializerCache.GetOrAdd(type, (t) => CreateDataContractSerializer(t, throwOnError: false));\n\n                // Null means we tested it before and know it is not supported\n                return serializer != null;\n            }\n            else\n            {\n                return base.CanWriteType(type);\n            }\n        }\n\n        /// <inheritdoc />\n        public override object ReadFromStream(Type type, Stream readStream, Encoding effectiveEncoding, IFormatterLogger formatterLogger)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            if (readStream == null)\n            {\n                throw Error.ArgumentNull(\"readStream\");\n            }\n\n            if (effectiveEncoding == null)\n            {\n                throw Error.ArgumentNull(\"effectiveEncoding\");\n            }\n\n            if (UseDataContractJsonSerializer)\n            {\n                DataContractJsonSerializer dataContractSerializer = GetDataContractSerializer(type);\n\n#if NETSTANDARD1_3 // Unreachable when targeting netstandard1.3. Return just to satisfy the compiler.\n                return null;\n#else\n                // DCS encodings are limited to UTF8, UTF16BE, and UTF16LE. Convert to UTF8 as we read.\n                Stream innerStream =\n                    string.Equals(effectiveEncoding.WebName, Utf8Encoding.WebName, StringComparison.OrdinalIgnoreCase) ?\n                    new NonClosingDelegatingStream(readStream) :\n                    new TranscodingStream(readStream, effectiveEncoding, Utf8Encoding, leaveOpen: true);\n\n                // XmlDictionaryReader will always dispose of innerStream when we dispose of the reader.\n                using XmlDictionaryReader reader =\n                    JsonReaderWriterFactory.CreateJsonReader(innerStream, Utf8Encoding, _readerQuotas, onClose: null);\n                return dataContractSerializer.ReadObject(reader);\n#endif\n            }\n            else\n            {\n                return base.ReadFromStream(type, readStream, effectiveEncoding, formatterLogger);\n            }\n        }\n\n        /// <inheritdoc />\n        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content,\n            TransportContext transportContext, CancellationToken cancellationToken)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            if (writeStream == null)\n            {\n                throw Error.ArgumentNull(\"writeStream\");\n            }\n\n            if (UseDataContractJsonSerializer && Indent)\n            {\n                throw Error.NotSupported(Properties.Resources.UnsupportedIndent, typeof(DataContractJsonSerializer));\n            }\n\n            return base.WriteToStreamAsync(type, value, writeStream, content, transportContext, cancellationToken);\n        }\n\n        /// <inheritdoc />\n        public override void WriteToStream(Type type, object value, Stream writeStream, Encoding effectiveEncoding)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            if (writeStream == null)\n            {\n                throw Error.ArgumentNull(\"writeStream\");\n            }\n\n            if (effectiveEncoding == null)\n            {\n                throw Error.ArgumentNull(\"effectiveEncoding\");\n            }\n\n            if (UseDataContractJsonSerializer)\n            {\n                if (MediaTypeFormatter.TryGetDelegatingTypeForIQueryableGenericOrSame(ref type))\n                {\n                    if (value != null)\n                    {\n                        value = MediaTypeFormatter.GetTypeRemappingConstructor(type).Invoke(new object[] { value });\n                    }\n                }\n\n                WritePreamble(writeStream, effectiveEncoding);\n                if (string.Equals(effectiveEncoding.WebName, Utf8Encoding.WebName, StringComparison.OrdinalIgnoreCase))\n                {\n                    WriteObject(writeStream, type, value);\n                }\n                else\n                {\n                    // JsonReaderWriterFactory is internal and DataContractJsonSerializer only writes UTF8 for the\n                    // netstandard1.3 project. In addition, DCS encodings are limited to UTF8, UTF16BE, and UTF16LE.\n                    // Convert to UTF8 as we write.\n                    using var innerStream = new TranscodingStream(writeStream, effectiveEncoding, Utf8Encoding, leaveOpen: true);\n                    WriteObject(innerStream, type, value);\n                }\n            }\n            else\n            {\n                base.WriteToStream(type, value, writeStream, effectiveEncoding);\n            }\n        }\n\n        private void WriteObject(Stream stream, Type type, object value)\n        {\n            DataContractJsonSerializer dataContractSerializer = GetDataContractSerializer(type);\n\n#if !NETSTANDARD1_3 // Unreachable when targeting netstandard1.3.\n            // Do not dispose of the stream. WriteToStream handles that where it's needed.\n            using XmlWriter writer = JsonReaderWriterFactory.CreateJsonWriter(stream, Utf8Encoding, ownsStream: false);\n            dataContractSerializer.WriteObject(writer, value);\n#endif\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Catch all is around an extensibile method\")]\n        private DataContractJsonSerializer CreateDataContractSerializer(Type type, bool throwOnError)\n        {\n            Contract.Assert(type != null);\n\n#if NETSTANDARD1_3 // XsdDataContractExporter is not supported in netstandard1.3\n            if (throwOnError)\n            {\n                throw new PlatformNotSupportedException(Error.Format(\n                    Properties.Resources.JsonMediaTypeFormatter_DCS_NotSupported,\n                    nameof(UseDataContractJsonSerializer)));\n            }\n            else\n            {\n                return null;\n            }\n#else\n\n            DataContractJsonSerializer serializer = null;\n            Exception exception = null;\n\n            try\n            {\n                // Verify that type is a valid data contract by forcing the serializer to try to create a data contract\n                FormattingUtilities.XsdDataContractExporter.GetRootElementName(type);\n\n                serializer = CreateDataContractSerializer(type);\n            }\n            catch (Exception caught)\n            {\n                exception = caught;\n            }\n\n            if (serializer == null && throwOnError)\n            {\n                if (exception != null)\n                {\n                    throw Error.InvalidOperation(exception, Properties.Resources.SerializerCannotSerializeType,\n                                  typeof(DataContractJsonSerializer).Name,\n                                  type.Name);\n                }\n                else\n                {\n                    throw Error.InvalidOperation(Properties.Resources.SerializerCannotSerializeType,\n                                  typeof(DataContractJsonSerializer).Name,\n                                  type.Name);\n                }\n            }\n\n            return serializer;\n#endif\n        }\n\n        /// <summary>\n        /// Called during deserialization to get the <see cref=\"DataContractJsonSerializer\"/>.\n        /// </summary>\n        /// <remarks>\n        /// Public for delegating wrappers of this class.  Expected to be called only from\n        /// <see cref=\"BaseJsonMediaTypeFormatter.ReadFromStreamAsync\"/> and <see cref=\"WriteToStreamAsync\"/>.\n        /// </remarks>\n        /// <param name=\"type\">The type of object that will be serialized or deserialized.</param>\n        /// <returns>The <see cref=\"DataContractJsonSerializer\"/> used to serialize the object.</returns>\n        public virtual DataContractJsonSerializer CreateDataContractSerializer(Type type)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            return new DataContractJsonSerializer(type);\n        }\n\n        private DataContractJsonSerializer GetDataContractSerializer(Type type)\n        {\n            Contract.Assert(type != null, \"Type cannot be null\");\n\n            DataContractJsonSerializer serializer =\n                _dataContractSerializerCache.GetOrAdd(type, (t) => CreateDataContractSerializer(type, throwOnError: true));\n\n            if (serializer == null)\n            {\n                // A null serializer means the type cannot be serialized\n                throw Error.InvalidOperation(Properties.Resources.SerializerCannotSerializeType, typeof(DataContractJsonSerializer).Name, type.Name);\n            }\n\n            return serializer;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/MediaTypeConstants.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Headers;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// Constants related to media types.\n    /// </summary>\n    internal static class MediaTypeConstants\n    {\n        private static readonly MediaTypeHeaderValue _defaultApplicationXmlMediaType = new MediaTypeHeaderValue(\"application/xml\");\n        private static readonly MediaTypeHeaderValue _defaultTextXmlMediaType = new MediaTypeHeaderValue(\"text/xml\");\n        private static readonly MediaTypeHeaderValue _defaultApplicationJsonMediaType = new MediaTypeHeaderValue(\"application/json\");\n        private static readonly MediaTypeHeaderValue _defaultTextJsonMediaType = new MediaTypeHeaderValue(\"text/json\");\n        private static readonly MediaTypeHeaderValue _defaultApplicationOctetStreamMediaType = new MediaTypeHeaderValue(\"application/octet-stream\");\n        private static readonly MediaTypeHeaderValue _defaultApplicationFormUrlEncodedMediaType = new MediaTypeHeaderValue(\"application/x-www-form-urlencoded\");\n        private static readonly MediaTypeHeaderValue _defaultApplicationBsonMediaType = new MediaTypeHeaderValue(\"application/bson\");\n\n        /// <summary>\n        /// Gets a <see cref=\"MediaTypeHeaderValue\"/> instance representing <c>application/octet-stream</c>.\n        /// </summary>\n        /// <value>\n        /// A new <see cref=\"MediaTypeHeaderValue\"/> instance representing <c>application/octet-stream</c>.\n        /// </value>\n        public static MediaTypeHeaderValue ApplicationOctetStreamMediaType\n        {\n            get { return _defaultApplicationOctetStreamMediaType.Clone(); }\n        }\n\n        /// <summary>\n        /// Gets a <see cref=\"MediaTypeHeaderValue\"/> instance representing <c>application/xml</c>.\n        /// </summary>\n        /// <value>\n        /// A new <see cref=\"MediaTypeHeaderValue\"/> instance representing <c>application/xml</c>.\n        /// </value>\n        public static MediaTypeHeaderValue ApplicationXmlMediaType\n        {\n            get { return _defaultApplicationXmlMediaType.Clone(); }\n        }\n\n        /// <summary>\n        /// Gets a <see cref=\"MediaTypeHeaderValue\"/> instance representing <c>application/json</c>.\n        /// </summary>\n        /// <value>\n        /// A new <see cref=\"MediaTypeHeaderValue\"/> instance representing <c>application/json</c>.\n        /// </value>\n        public static MediaTypeHeaderValue ApplicationJsonMediaType\n        {\n            get { return _defaultApplicationJsonMediaType.Clone(); }\n        }\n\n        /// <summary>\n        /// Gets a <see cref=\"MediaTypeHeaderValue\"/> instance representing <c>text/xml</c>.\n        /// </summary>\n        /// <value>\n        /// A new <see cref=\"MediaTypeHeaderValue\"/> instance representing <c>text/xml</c>.\n        /// </value>\n        public static MediaTypeHeaderValue TextXmlMediaType\n        {\n            get { return _defaultTextXmlMediaType.Clone(); }\n        }\n\n        /// <summary>\n        /// Gets a <see cref=\"MediaTypeHeaderValue\"/> instance representing <c>text/json</c>.\n        /// </summary>\n        /// <value>\n        /// A new <see cref=\"MediaTypeHeaderValue\"/> instance representing <c>text/json</c>.\n        /// </value>\n        public static MediaTypeHeaderValue TextJsonMediaType\n        {\n            get { return _defaultTextJsonMediaType.Clone(); }\n        }\n\n        /// <summary>\n        /// Gets a <see cref=\"MediaTypeHeaderValue\"/> instance representing <c>application/x-www-form-urlencoded</c>.\n        /// </summary>\n        /// <value>\n        /// A new <see cref=\"MediaTypeHeaderValue\"/> instance representing <c>application/x-www-form-urlencoded</c>.\n        /// </value>\n        public static MediaTypeHeaderValue ApplicationFormUrlEncodedMediaType\n        {\n            get { return _defaultApplicationFormUrlEncodedMediaType.Clone(); }\n        }\n\n        /// <summary>\n        /// Gets a <see cref=\"MediaTypeHeaderValue\"/> instance representing <c>application/bson</c>.\n        /// </summary>\n        /// <value>\n        /// A new <see cref=\"MediaTypeHeaderValue\"/> instance representing <c>application/bson</c>.\n        /// </value>\n        /// <remarks>\n        /// Not yet a standard. In particular this media type is not currently listed at\n        /// http://www.iana.org/assignments/media-types/application.\n        /// </remarks>\n        public static MediaTypeHeaderValue ApplicationBsonMediaType\n        {\n            get { return _defaultApplicationBsonMediaType.Clone(); }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/MediaTypeFormatter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.IO;\nusing System.Linq;\nusing System.Net.Http.Headers;\nusing System.Reflection;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// Base class to handle serializing and deserializing strongly-typed objects using <see cref=\"ObjectContent\"/>.\n    /// </summary>\n    public abstract class MediaTypeFormatter\n    {\n        private protected static readonly Encoding Utf8Encoding =\n            new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);\n        private const int DefaultMinHttpCollectionKeys = 1;\n        private const int DefaultMaxHttpCollectionKeys = 1000; // same default as ASPNET\n        private const string IWellKnownComparerTypeName = \"System.IWellKnownStringEqualityComparer, mscorlib, Version=4.0.0.0, PublicKeyToken=b77a5c561934e089\";\n\n        private static readonly ConcurrentDictionary<Type, Type> _delegatingEnumerableCache = new ConcurrentDictionary<Type, Type>();\n        private static ConcurrentDictionary<Type, ConstructorInfo> _delegatingEnumerableConstructorCache = new ConcurrentDictionary<Type, ConstructorInfo>();\n        private static Lazy<int> _defaultMaxHttpCollectionKeys = new Lazy<int>(InitializeDefaultCollectionKeySize, true); // Max number of keys is 1000\n        private static int _maxHttpCollectionKeys = -1;\n\n        private readonly List<MediaTypeHeaderValue> _supportedMediaTypes;\n        private readonly List<Encoding> _supportedEncodings;\n        private readonly List<MediaTypeMapping> _mediaTypeMappings;\n        private IRequiredMemberSelector _requiredMemberSelector;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"MediaTypeFormatter\"/> class.\n        /// </summary>\n        protected MediaTypeFormatter()\n        {\n            _supportedMediaTypes = new List<MediaTypeHeaderValue>();\n            SupportedMediaTypes = new MediaTypeHeaderValueCollection(_supportedMediaTypes);\n            _supportedEncodings = new List<Encoding>();\n            SupportedEncodings = new Collection<Encoding>(_supportedEncodings);\n            _mediaTypeMappings = new List<MediaTypeMapping>();\n            MediaTypeMappings = new Collection<MediaTypeMapping>(_mediaTypeMappings);\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"MediaTypeFormatter\"/> class.\n        /// </summary>\n        /// <param name=\"formatter\">The <see cref=\"MediaTypeFormatter\"/> instance to copy settings from.</param>\n        protected MediaTypeFormatter(MediaTypeFormatter formatter)\n        {\n            if (formatter == null)\n            {\n                throw Error.ArgumentNull(\"formatter\");\n            }\n\n            _supportedMediaTypes = formatter._supportedMediaTypes;\n            SupportedMediaTypes = formatter.SupportedMediaTypes;\n            _supportedEncodings = formatter._supportedEncodings;\n            SupportedEncodings = formatter.SupportedEncodings;\n            _mediaTypeMappings = formatter._mediaTypeMappings;\n            MediaTypeMappings = formatter.MediaTypeMappings;\n            _requiredMemberSelector = formatter._requiredMemberSelector;\n        }\n\n        /// <summary>\n        /// Gets or sets the maximum number of keys stored in a NameValueCollection.\n        /// </summary>\n        public static int MaxHttpCollectionKeys\n        {\n            get\n            {\n                if (_maxHttpCollectionKeys < 0)\n                {\n                    _maxHttpCollectionKeys = _defaultMaxHttpCollectionKeys.Value;\n                }\n\n                return _maxHttpCollectionKeys;\n            }\n            set\n            {\n                if (value < DefaultMinHttpCollectionKeys)\n                {\n                    throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"value\", value, DefaultMinHttpCollectionKeys);\n                }\n\n                _maxHttpCollectionKeys = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets the mutable collection of <see cref=\"MediaTypeHeaderValue\"/> elements supported by\n        /// this <see cref=\"MediaTypeFormatter\"/> instance.\n        /// </summary>\n        public Collection<MediaTypeHeaderValue> SupportedMediaTypes { get; private set; }\n\n        internal List<MediaTypeHeaderValue> SupportedMediaTypesInternal\n        {\n            get { return _supportedMediaTypes; }\n        }\n\n        /// <summary>\n        /// Gets the mutable collection of character encodings supported by\n        /// this <see cref=\"MediaTypeFormatter\"/> instance. The encodings are\n        /// used when reading or writing data.\n        /// </summary>\n        public Collection<Encoding> SupportedEncodings { get; private set; }\n\n        internal List<Encoding> SupportedEncodingsInternal\n        {\n            get { return _supportedEncodings; }\n        }\n\n        /// <summary>\n        /// Gets the mutable collection of <see cref=\"MediaTypeMapping\"/> elements used\n        /// by this <see cref=\"MediaTypeFormatter\"/> instance to determine the\n        /// <see cref=\"MediaTypeHeaderValue\"/> of requests or responses.\n        /// </summary>\n        public Collection<MediaTypeMapping> MediaTypeMappings { get; private set; }\n\n        internal List<MediaTypeMapping> MediaTypeMappingsInternal\n        {\n            get { return _mediaTypeMappings; }\n        }\n\n        /// <summary>\n        /// Gets or sets the <see cref=\"IRequiredMemberSelector\"/> used to determine required members.\n        /// </summary>\n        public virtual IRequiredMemberSelector RequiredMemberSelector\n        {\n            get\n            {\n                return _requiredMemberSelector;\n            }\n            set\n            {\n                _requiredMemberSelector = value;\n            }\n        }\n\n        internal virtual bool CanWriteAnyTypes\n        {\n            get { return true; }\n        }\n\n        /// <summary>\n        /// Returns a <see cref=\"Task\"/> to deserialize an object of the given <paramref name=\"type\"/> from the given <paramref name=\"readStream\"/>\n        /// </summary>\n        /// <remarks>\n        /// <para>This implementation throws a <see cref=\"NotSupportedException\"/>. Derived types should override this method if the formatter\n        /// supports reading.</para>\n        /// <para>An implementation of this method should NOT close <paramref name=\"readStream\"/> upon completion. The stream will be closed independently when\n        /// the <see cref=\"HttpContent\"/> instance is disposed.\n        /// </para>\n        /// </remarks>\n        /// <param name=\"type\">The type of the object to deserialize.</param>\n        /// <param name=\"readStream\">The <see cref=\"Stream\"/> to read.</param>\n        /// <param name=\"content\">The <see cref=\"HttpContent\"/> if available. It may be <c>null</c>.</param>\n        /// <param name=\"formatterLogger\">The <see cref=\"IFormatterLogger\"/> to log events to.</param>\n        /// <returns>A <see cref=\"Task\"/> whose result will be an object of the given type.</returns>\n        /// <exception cref=\"NotSupportedException\">Derived types need to support reading.</exception>\n        /// <seealso cref=\"CanReadType(Type)\"/>\n        public virtual Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)\n        {\n            throw Error.NotSupported(Properties.Resources.MediaTypeFormatterCannotRead, GetType().Name);\n        }\n\n        /// <summary>\n        /// Returns a <see cref=\"Task\"/> to deserialize an object of the given <paramref name=\"type\"/> from the given <paramref name=\"readStream\"/>\n        /// </summary>\n        /// <remarks>\n        /// <para>This implementation throws a <see cref=\"NotSupportedException\"/>. Derived types should override this method if the formatter\n        /// supports reading.</para>\n        /// <para>An implementation of this method should NOT close <paramref name=\"readStream\"/> upon completion. The stream will be closed independently when\n        /// the <see cref=\"HttpContent\"/> instance is disposed.\n        /// </para>\n        /// </remarks>\n        /// <param name=\"type\">The type of the object to deserialize.</param>\n        /// <param name=\"readStream\">The <see cref=\"Stream\"/> to read.</param>\n        /// <param name=\"content\">The <see cref=\"HttpContent\"/> if available. It may be <c>null</c>.</param>\n        /// <param name=\"formatterLogger\">The <see cref=\"IFormatterLogger\"/> to log events to.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A <see cref=\"Task\"/> whose result will be an object of the given type.</returns>\n        /// <exception cref=\"NotSupportedException\">Derived types need to support reading.</exception>\n        /// <seealso cref=\"CanReadType(Type)\"/>\n        public virtual Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content,\n            IFormatterLogger formatterLogger, CancellationToken cancellationToken)\n        {\n            if (cancellationToken.IsCancellationRequested)\n            {\n                return TaskHelpers.Canceled<object>();\n            }\n\n            return ReadFromStreamAsync(type, readStream, content, formatterLogger);\n        }\n\n        /// <summary>\n        /// Returns a <see cref=\"Task\"/> that serializes the given <paramref name=\"value\"/> of the given <paramref name=\"type\"/>\n        /// to the given <paramref name=\"writeStream\"/>.\n        /// </summary>\n        /// <remarks>\n        /// <para>This implementation throws a <see cref=\"NotSupportedException\"/>. Derived types should override this method if the formatter\n        /// supports reading.</para>\n        /// <para>An implementation of this method should NOT close <paramref name=\"writeStream\"/> upon completion. The stream will be closed independently when\n        /// the <see cref=\"HttpContent\"/> instance is disposed.\n        /// </para>\n        /// </remarks>\n        /// <param name=\"type\">The type of the object to write.</param>\n        /// <param name=\"value\">The object value to write.  It may be <c>null</c>.</param>\n        /// <param name=\"writeStream\">The <see cref=\"Stream\"/> to which to write.</param>\n        /// <param name=\"content\">The <see cref=\"HttpContent\"/> if available. It may be <c>null</c>.</param>\n        /// <param name=\"transportContext\">The <see cref=\"TransportContext\"/> if available. It may be <c>null</c>.</param>\n        /// <returns>A <see cref=\"Task\"/> that will perform the write.</returns>\n        /// <exception cref=\"NotSupportedException\">Derived types need to support writing.</exception>\n        /// <seealso cref=\"CanWriteType(Type)\"/>\n        public virtual Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)\n        {\n            // HttpContent.SerializeToStreamAsync doesn't take in a CancellationToken. So, there is no easy way to get the CancellationToken\n            // to the formatter while writing response. We are cheating here by passing fake cancellation tokens. We should fix this\n            // when we fix HttpContent.\n            return WriteToStreamAsync(type, value, writeStream, content, transportContext, CancellationToken.None);\n        }\n\n        /// <summary>\n        /// Returns a <see cref=\"Task\"/> that serializes the given <paramref name=\"value\"/> of the given <paramref name=\"type\"/>\n        /// to the given <paramref name=\"writeStream\"/>.\n        /// </summary>\n        /// <remarks>\n        /// <para>This implementation throws a <see cref=\"NotSupportedException\"/>. Derived types should override this method if the formatter\n        /// supports reading.</para>\n        /// <para>An implementation of this method should NOT close <paramref name=\"writeStream\"/> upon completion. The stream will be closed independently when\n        /// the <see cref=\"HttpContent\"/> instance is disposed.\n        /// </para>\n        /// </remarks>\n        /// <param name=\"type\">The type of the object to write.</param>\n        /// <param name=\"value\">The object value to write.  It may be <c>null</c>.</param>\n        /// <param name=\"writeStream\">The <see cref=\"Stream\"/> to which to write.</param>\n        /// <param name=\"content\">The <see cref=\"HttpContent\"/> if available. It may be <c>null</c>.</param>\n        /// <param name=\"transportContext\">The <see cref=\"TransportContext\"/> if available. It may be <c>null</c>.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A <see cref=\"Task\"/> that will perform the write.</returns>\n        /// <exception cref=\"NotSupportedException\">Derived types need to support writing.</exception>\n        /// <seealso cref=\"CanWriteType(Type)\"/>\n        public virtual Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content,\n            TransportContext transportContext, CancellationToken cancellationToken)\n        {\n            throw Error.NotSupported(Properties.Resources.MediaTypeFormatterCannotWrite, GetType().Name);\n        }\n\n        private static bool TryGetDelegatingType(Type interfaceType, ref Type type)\n        {\n            if (type != null && type.IsInterface() && type.IsGenericType())\n            {\n                Type genericType = type.ExtractGenericInterface(interfaceType);\n\n                if (genericType != null)\n                {\n                    type = GetOrAddDelegatingType(type, genericType);\n                    return true;\n                }\n            }\n\n            return false;\n        }\n\n        private static int InitializeDefaultCollectionKeySize()\n        {\n            return Int32.MaxValue;\n        }\n\n        /// <summary>\n        /// This method converts <see cref=\"IEnumerable{T}\"/> (and interfaces that mandate it) to a <see cref=\"DelegatingEnumerable{T}\"/> for serialization purposes.\n        /// </summary>\n        /// <param name=\"type\">The type to potentially be wrapped. If the type is wrapped, it's changed in place.</param>\n        /// <returns>Returns <c>true</c> if the type was wrapped; <c>false</c>, otherwise</returns>\n        internal static bool TryGetDelegatingTypeForIEnumerableGenericOrSame(ref Type type)\n        {\n            return TryGetDelegatingType(FormattingUtilities.EnumerableInterfaceGenericType, ref type);\n        }\n\n        /// <summary>\n        /// This method converts <see cref=\"IQueryable{T}\"/> (and interfaces that mandate it) to a <see cref=\"DelegatingEnumerable{T}\"/> for serialization purposes.\n        /// </summary>\n        /// <param name=\"type\">The type to potentially be wrapped. If the type is wrapped, it's changed in place.</param>\n        /// <returns>Returns <c>true</c> if the type was wrapped; <c>false</c>, otherwise</returns>\n        internal static bool TryGetDelegatingTypeForIQueryableGenericOrSame(ref Type type)\n        {\n            return TryGetDelegatingType(FormattingUtilities.QueryableInterfaceGenericType, ref type);\n        }\n\n        internal static ConstructorInfo GetTypeRemappingConstructor(Type type)\n        {\n            ConstructorInfo constructorInfo;\n            _delegatingEnumerableConstructorCache.TryGetValue(type, out constructorInfo);\n            return constructorInfo;\n        }\n\n        /// <summary>\n        /// Determines the best <see cref=\"Encoding\"/> amongst the supported encodings\n        /// for reading or writing an HTTP entity body based on the provided <paramref name=\"contentHeaders\"/>.\n        /// </summary>\n        /// <param name=\"contentHeaders\">The content headers provided as part of the request or response.</param>\n        /// <returns>The <see cref=\"Encoding\"/> to use when reading the request or writing the response.</returns>\n        public Encoding SelectCharacterEncoding(HttpContentHeaders contentHeaders)\n        {\n            // Performance-sensitive\n            Encoding encoding = null;\n            if (contentHeaders != null && contentHeaders.ContentType != null)\n            {\n                // Find encoding based on content type charset parameter\n                string charset = contentHeaders.ContentType.CharSet;\n                if (!String.IsNullOrWhiteSpace(charset))\n                {\n                    for (int i = 0; i < _supportedEncodings.Count; i++)\n                    {\n                        Encoding supportedEncoding = _supportedEncodings[i];\n                        if (charset.Equals(supportedEncoding.WebName, StringComparison.OrdinalIgnoreCase))\n                        {\n                            encoding = supportedEncoding;\n                            break;\n                        }\n                    }\n                }\n            }\n\n            if (encoding == null)\n            {\n                // We didn't find a character encoding match based on the content headers.\n                // Instead we try getting the default character encoding.\n                if (_supportedEncodings.Count > 0)\n                {\n                    encoding = _supportedEncodings[0];\n                }\n            }\n\n            if (encoding == null)\n            {\n                // No supported encoding was found so there is no way for us to start reading or writing.\n                throw Error.InvalidOperation(Properties.Resources.MediaTypeFormatterNoEncoding, GetType().Name);\n            }\n\n            return encoding;\n        }\n\n        /// <summary>\n        /// Sets the default headers for content that will be formatted using this formatter. This method\n        /// is called from the <see cref=\"ObjectContent\"/> constructor.\n        /// This implementation sets the Content-Type header to the value of <paramref name=\"mediaType\"/> if it is\n        /// not <c>null</c>. If it is <c>null</c> it sets the Content-Type to the default media type of this formatter.\n        /// If the Content-Type does not specify a charset it will set it using this formatters configured\n        /// <see cref=\"Encoding\"/>.\n        /// </summary>\n        /// <remarks>\n        /// Subclasses can override this method to set content headers such as Content-Type etc. Subclasses should\n        /// call the base implementation. Subclasses should treat the passed in <paramref name=\"mediaType\"/> (if not <c>null</c>)\n        /// as the authoritative media type and use that as the Content-Type.\n        /// </remarks>\n        /// <param name=\"type\">The type of the object being serialized. See <see cref=\"ObjectContent\"/>.</param>\n        /// <param name=\"headers\">The content headers that should be configured.</param>\n        /// <param name=\"mediaType\">The authoritative media type. Can be <c>null</c>.</param>\n        public virtual void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n            if (headers == null)\n            {\n                throw Error.ArgumentNull(\"headers\");\n            }\n\n            if (mediaType != null)\n            {\n                headers.ContentType = mediaType.Clone();\n            }\n\n            // If content type is not set then set it based on supported media types.\n            if (headers.ContentType == null)\n            {\n                MediaTypeHeaderValue defaultMediaType = null;\n                if (_supportedMediaTypes.Count > 0)\n                {\n                    defaultMediaType = _supportedMediaTypes[0];\n                }\n                if (defaultMediaType != null)\n                {\n                    headers.ContentType = defaultMediaType.Clone();\n                }\n            }\n\n            // If content type charset parameter is not set then set it based on the supported encodings.\n            if (headers.ContentType != null && headers.ContentType.CharSet == null)\n            {\n                Encoding defaultEncoding = null;\n                if (_supportedEncodings.Count > 0)\n                {\n                    defaultEncoding = _supportedEncodings[0];\n                }\n                if (defaultEncoding != null)\n                {\n                    headers.ContentType.CharSet = defaultEncoding.WebName;\n                }\n            }\n        }\n\n        /// <summary>\n        /// Returns a specialized instance of the <see cref=\"MediaTypeFormatter\"/> that can handle formatting a response for the given\n        /// parameters. This method is called after a formatter has been selected through content negotiation.\n        /// </summary>\n        /// <remarks>\n        /// The default implementation returns <c>this</c> instance. Derived classes can choose to return a new instance if\n        /// they need to close over any of the parameters.\n        /// </remarks>\n        /// <param name=\"type\">The type being serialized.</param>\n        /// <param name=\"request\">The request.</param>\n        /// <param name=\"mediaType\">The media type chosen for the serialization. Can be <c>null</c>.</param>\n        /// <returns>An instance that can format a response to the given <paramref name=\"request\"/>.</returns>\n        public virtual MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            return this;\n        }\n\n        /// <summary>\n        /// Determines whether this <see cref=\"MediaTypeFormatter\"/> can deserialize\n        /// an object of the specified type.\n        /// </summary>\n        /// <remarks>\n        /// Derived classes must implement this method and indicate if a type can or cannot be deserialized.\n        /// </remarks>\n        /// <param name=\"type\">The type of object that will be deserialized.</param>\n        /// <returns><c>true</c> if this <see cref=\"MediaTypeFormatter\"/> can deserialize an object of that type; otherwise <c>false</c>.</returns>\n        public abstract bool CanReadType(Type type);\n\n        /// <summary>\n        /// Determines whether this <see cref=\"MediaTypeFormatter\"/> can serialize\n        /// an object of the specified type.\n        /// </summary>\n        /// <remarks>\n        /// Derived classes must implement this method and indicate if a type can or cannot be serialized.\n        /// </remarks>\n        /// <param name=\"type\">The type of object that will be serialized.</param>\n        /// <returns><c>true</c> if this <see cref=\"MediaTypeFormatter\"/> can serialize an object of that type; otherwise <c>false</c>.</returns>\n        public abstract bool CanWriteType(Type type);\n\n        private static Type GetOrAddDelegatingType(Type type, Type genericType)\n        {\n            return _delegatingEnumerableCache.GetOrAdd(\n                type,\n                (typeToRemap) =>\n                {\n                    // The current method is called by methods that already checked the type for is not null, is generic and is or implements IEnumerable<T>\n                    // This retrieves the T type of the IEnumerable<T> interface.\n                    Type elementType = genericType.GetGenericArguments()[0];\n                    Type delegatingType = FormattingUtilities.DelegatingEnumerableGenericType.MakeGenericType(elementType);\n                    ConstructorInfo delegatingConstructor = delegatingType.GetConstructor(new Type[] { FormattingUtilities.EnumerableInterfaceGenericType.MakeGenericType(elementType) });\n                    _delegatingEnumerableConstructorCache.TryAdd(delegatingType, delegatingConstructor);\n\n                    return delegatingType;\n                });\n        }\n\n        /// <summary>\n        /// Gets the default value for the specified type.\n        /// </summary>\n        public static object GetDefaultValueForType(Type type)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            if (type.IsValueType())\n            {\n                return Activator.CreateInstance(type);\n            }\n            return null;\n        }\n\n        private protected static void WritePreamble(Stream stream, Encoding encoding)\n        {\n            byte[] bytes = encoding.GetPreamble();\n            if (bytes.Length > 0)\n            {\n                stream.Write(bytes, 0, bytes.Length);\n            }\n        }\n\n        /// <summary>\n        /// Collection class that validates it contains only <see cref=\"MediaTypeHeaderValue\"/> instances\n        /// that are not null and not media ranges.\n        /// </summary>\n        internal class MediaTypeHeaderValueCollection : Collection<MediaTypeHeaderValue>\n        {\n            private static readonly Type _mediaTypeHeaderValueType = typeof(MediaTypeHeaderValue);\n\n            internal MediaTypeHeaderValueCollection(IList<MediaTypeHeaderValue> list)\n                : base(list)\n            {\n            }\n\n            /// <summary>\n            /// Inserts the <paramref name=\"item\"/> into the collection at the specified <paramref name=\"index\"/>.\n            /// </summary>\n            /// <param name=\"index\">The zero-based index at which item should be inserted.</param>\n            /// <param name=\"item\">The object to insert. It cannot be <c>null</c>.</param>\n            protected override void InsertItem(int index, MediaTypeHeaderValue item)\n            {\n                ValidateMediaType(item);\n                base.InsertItem(index, item);\n            }\n\n            /// <summary>\n            /// Replaces the element at the specified <paramref name=\"index\"/>.\n            /// </summary>\n            /// <param name=\"index\">The zero-based index of the item that should be replaced.</param>\n            /// <param name=\"item\">The new value for the element at the specified index.  It cannot be <c>null</c>.</param>\n            protected override void SetItem(int index, MediaTypeHeaderValue item)\n            {\n                ValidateMediaType(item);\n                base.SetItem(index, item);\n            }\n\n            private static void ValidateMediaType(MediaTypeHeaderValue item)\n            {\n                if (item == null)\n                {\n                    throw Error.ArgumentNull(\"item\");\n                }\n\n                ParsedMediaTypeHeaderValue parsedMediaType = new ParsedMediaTypeHeaderValue(item);\n                if (parsedMediaType.IsAllMediaRange || parsedMediaType.IsSubtypeMediaRange)\n                {\n                    throw Error.Argument(\"item\", Properties.Resources.CannotUseMediaRangeForSupportedMediaType, _mediaTypeHeaderValueType.Name, item.MediaType);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/MediaTypeFormatterCollection.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Net.Http.Headers;\nusing System.Web.Http;\nusing System.Xml;\nusing System.Xml.Linq;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// Collection class that contains <see cref=\"MediaTypeFormatter\"/> instances.\n    /// </summary>\n    public class MediaTypeFormatterCollection : Collection<MediaTypeFormatter>\n    {\n        private static readonly Type _mediaTypeFormatterType = typeof(MediaTypeFormatter);\n\n        private MediaTypeFormatter[] _writingFormatters;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"MediaTypeFormatterCollection\"/> class.\n        /// </summary>\n        /// <remarks>\n        /// This collection will be initialized to contain default <see cref=\"MediaTypeFormatter\"/>\n        /// instances for Xml, JsonValue and Json.\n        /// </remarks>\n        public MediaTypeFormatterCollection()\n            : this(CreateDefaultFormatters())\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"MediaTypeFormatterCollection\"/> class.\n        /// </summary>\n        /// <param name=\"formatters\">A collection of <see cref=\"MediaTypeFormatter\"/> instances to place in the collection.</param>\n        public MediaTypeFormatterCollection(IEnumerable<MediaTypeFormatter> formatters)\n        {\n            VerifyAndSetFormatters(formatters);\n        }\n\n        internal event EventHandler Changing;\n\n        /// <summary>\n        /// Gets the <see cref=\"MediaTypeFormatter\"/> to use for Xml.\n        /// </summary>\n        public XmlMediaTypeFormatter XmlFormatter\n        {\n            get { return Items.OfType<XmlMediaTypeFormatter>().FirstOrDefault(); }\n        }\n\n        /// <summary>\n        /// Gets the <see cref=\"MediaTypeFormatter\"/> to use for Json.\n        /// </summary>\n        public JsonMediaTypeFormatter JsonFormatter\n        {\n            get { return Items.OfType<JsonMediaTypeFormatter>().FirstOrDefault(); }\n        }\n\n        /// <summary>\n        /// Gets the <see cref=\"MediaTypeFormatter\"/> to use for <c>application/x-www-form-urlencoded</c> data.\n        /// </summary>\n        public FormUrlEncodedMediaTypeFormatter FormUrlEncodedFormatter\n        {\n            get { return Items.OfType<FormUrlEncodedMediaTypeFormatter>().FirstOrDefault(); }\n        }\n\n        internal MediaTypeFormatter[] WritingFormatters\n        {\n            get\n            {\n                if (_writingFormatters == null)\n                {\n                    _writingFormatters = GetWritingFormatters();\n                }\n                return _writingFormatters;\n            }\n        }\n\n        /// <summary>\n        /// Adds the elements of the specified collection to the end of the <see cref=\"MediaTypeFormatterCollection\"/>.\n        /// </summary>\n        /// <param name=\"items\">\n        /// The items that should be added to the end of the <see cref=\"MediaTypeFormatterCollection\"/>.\n        /// The items collection itself cannot be <see langword=\"null\"/>, but it can contain elements that are\n        /// <see langword=\"null\"/>.\n        /// </param>\n        public void AddRange(IEnumerable<MediaTypeFormatter> items)\n        {\n            if (items == null)\n            {\n                throw Error.ArgumentNull(\"items\");\n            }\n\n            foreach (MediaTypeFormatter item in items)\n            {\n                Add(item);\n            }\n        }\n\n        /// <summary>\n        /// Inserts the elements of a collection into the <see cref=\"MediaTypeFormatterCollection\"/> at the specified\n        /// index.\n        /// </summary>\n        /// <param name=\"index\">The zero-based index at which the new elements should be inserted.</param>\n        /// <param name=\"items\">\n        /// The items that should be inserted into the <see cref=\"MediaTypeFormatterCollection\"/>. The items collection\n        /// itself cannot be <see langword=\"null\"/>, but it can contain elements that are <see langword=\"null\"/>.\n        /// </param>\n        public void InsertRange(int index, IEnumerable<MediaTypeFormatter> items)\n        {\n            if (items == null)\n            {\n                throw Error.ArgumentNull(\"items\");\n            }\n\n            foreach (MediaTypeFormatter item in items)\n            {\n                Insert(index++, item);\n            }\n        }\n\n        /// <summary>\n        /// Helper to search a collection for a formatter that can read the .NET type in the given mediaType.\n        /// </summary>\n        /// <param name=\"type\">.NET type to read</param>\n        /// <param name=\"mediaType\">media type to match on.</param>\n        /// <returns>Formatter that can read the type. Null if no formatter found.</returns>\n        public MediaTypeFormatter FindReader(Type type, MediaTypeHeaderValue mediaType)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n            if (mediaType == null)\n            {\n                throw Error.ArgumentNull(\"mediaType\");\n            }\n\n            foreach (MediaTypeFormatter formatter in Items)\n            {\n                if (formatter != null && formatter.CanReadType(type))\n                {\n                    foreach (MediaTypeHeaderValue supportedMediaType in formatter.SupportedMediaTypes)\n                    {\n                        if (supportedMediaType != null && supportedMediaType.IsSubsetOf(mediaType))\n                        {\n                            return formatter;\n                        }\n                    }\n                }\n            }\n\n            return null;\n        }\n\n        /// <summary>\n        /// Helper to search a collection for a formatter that can write the .NET type in the given mediaType.\n        /// </summary>\n        /// <param name=\"type\">.NET type to read</param>\n        /// <param name=\"mediaType\">media type to match on.</param>\n        /// <returns>Formatter that can write the type. Null if no formatter found.</returns>\n        public MediaTypeFormatter FindWriter(Type type, MediaTypeHeaderValue mediaType)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n            if (mediaType == null)\n            {\n                throw Error.ArgumentNull(\"mediaType\");\n            }\n\n            foreach (MediaTypeFormatter formatter in Items)\n            {\n                if (formatter != null && formatter.CanWriteType(type))\n                {\n                    foreach (MediaTypeHeaderValue supportedMediaType in formatter.SupportedMediaTypes)\n                    {\n                        if (supportedMediaType != null && supportedMediaType.IsSubsetOf(mediaType))\n                        {\n                            return formatter;\n                        }\n                    }\n                }\n            }\n\n            return null;\n        }\n\n        /// <summary>\n        /// Returns true if the type is one of those loosely defined types that should be excluded from validation\n        /// </summary>\n        /// <param name=\"type\">.NET <see cref=\"Type\"/> to validate</param>\n        /// <returns><c>true</c> if the type should be excluded.</returns>\n        public static bool IsTypeExcludedFromValidation(Type type)\n        {\n            return\n                typeof(XmlNode).IsAssignableFrom(type) ||\n                typeof(FormDataCollection).IsAssignableFrom(type) ||\n                FormattingUtilities.IsJTokenType(type) ||\n                typeof(XObject).IsAssignableFrom(type) ||\n                typeof(Type).IsAssignableFrom(type) ||\n                type == typeof(byte[]);\n        }\n\n        protected override void ClearItems()\n        {\n            OnChanging();\n            base.ClearItems();\n        }\n\n        protected override void InsertItem(int index, MediaTypeFormatter item)\n        {\n            OnChanging();\n            base.InsertItem(index, item);\n        }\n\n        protected override void RemoveItem(int index)\n        {\n            OnChanging();\n            base.RemoveItem(index);\n        }\n\n        protected override void SetItem(int index, MediaTypeFormatter item)\n        {\n            OnChanging();\n            base.SetItem(index, item);\n        }\n\n        private void OnChanging()\n        {\n            if (Changing != null)\n            {\n                Changing(this, EventArgs.Empty);\n            }\n\n            // Clear cached state\n            _writingFormatters = null;\n        }\n\n        private MediaTypeFormatter[] GetWritingFormatters()\n        {\n            return Items.Where((formatter) => formatter != null && formatter.CanWriteAnyTypes).ToArray();\n        }\n\n        /// <summary>\n        /// Creates a collection of new instances of the default <see cref=\"MediaTypeFormatter\"/>s.\n        /// </summary>\n        /// <returns>The collection of default <see cref=\"MediaTypeFormatter\"/> instances.</returns>\n        private static IEnumerable<MediaTypeFormatter> CreateDefaultFormatters()\n        {\n            return new MediaTypeFormatter[]\n            {\n                new JsonMediaTypeFormatter(),\n                new XmlMediaTypeFormatter()\n#if NETSTANDARD1_3 // XsdDataContractExporter is not supported in netstandard1.3. Cannot use DCS.\n                { UseXmlSerializer = true }\n#endif\n                ,\n                new FormUrlEncodedMediaTypeFormatter()\n            };\n        }\n\n        private void VerifyAndSetFormatters(IEnumerable<MediaTypeFormatter> formatters)\n        {\n            if (formatters == null)\n            {\n                throw Error.ArgumentNull(\"formatters\");\n            }\n\n            foreach (MediaTypeFormatter formatter in formatters)\n            {\n                if (formatter == null)\n                {\n                    throw Error.Argument(\"formatters\", Properties.Resources.CannotHaveNullInList, _mediaTypeFormatterType.Name);\n                }\n\n                Add(formatter);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/MediaTypeFormatterExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Net.Http.Headers;\nusing System.Web.Http;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// Extensions for adding <see cref=\"MediaTypeMapping\"/> items to a <see cref=\"MediaTypeFormatter\"/>.\n    /// </summary>\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class MediaTypeFormatterExtensions\n    {\n        /// <summary>\n        /// Updates the given <paramref name=\"formatter\"/>'s set of <see cref=\"MediaTypeMapping\"/> elements\n        /// so that it associates the <paramref name=\"mediaType\"/> with <see cref=\"Uri\"/>s containing\n        /// a specific query parameter and value.\n        /// </summary>\n        /// <param name=\"formatter\">The <see cref=\"MediaTypeFormatter\"/> to receive the new <see cref=\"QueryStringMapping\"/> item.</param>\n        /// <param name=\"queryStringParameterName\">The name of the query parameter.</param>\n        /// <param name=\"queryStringParameterValue\">The value assigned to that query parameter.</param>\n        /// <param name=\"mediaType\">The <see cref=\"MediaTypeHeaderValue\"/> to associate \n        /// with a <see cref=\"Uri\"/> containing a query string matching <paramref name=\"queryStringParameterName\"/> \n        /// and <paramref name=\"queryStringParameterValue\"/>.</param>\n        public static void AddQueryStringMapping(\n            this MediaTypeFormatter formatter,\n            string queryStringParameterName,\n            string queryStringParameterValue,\n            MediaTypeHeaderValue mediaType)\n        {\n            if (formatter == null)\n            {\n                throw Error.ArgumentNull(\"formatter\");\n            }\n\n            QueryStringMapping mapping = new QueryStringMapping(queryStringParameterName, queryStringParameterValue, mediaType);\n            formatter.MediaTypeMappings.Add(mapping);\n        }\n\n        /// <summary>\n        /// Updates the given <paramref name=\"formatter\"/>'s set of <see cref=\"MediaTypeMapping\"/> elements\n        /// so that it associates the <paramref name=\"mediaType\"/> with <see cref=\"Uri\"/>s containing\n        /// a specific query parameter and value.\n        /// </summary>\n        /// <param name=\"formatter\">The <see cref=\"MediaTypeFormatter\"/> to receive the new <see cref=\"QueryStringMapping\"/> item.</param>\n        /// <param name=\"queryStringParameterName\">The name of the query parameter.</param>\n        /// <param name=\"queryStringParameterValue\">The value assigned to that query parameter.</param>\n        /// <param name=\"mediaType\">The media type to associate \n        /// with a <see cref=\"Uri\"/> containing a query string matching <paramref name=\"queryStringParameterName\"/>\n        /// and <paramref name=\"queryStringParameterValue\"/>.</param>\n        public static void AddQueryStringMapping(\n            this MediaTypeFormatter formatter,\n            string queryStringParameterName,\n            string queryStringParameterValue,\n            string mediaType)\n        {\n            if (formatter == null)\n            {\n                throw Error.ArgumentNull(\"formatter\");\n            }\n\n            QueryStringMapping mapping = new QueryStringMapping(queryStringParameterName, queryStringParameterValue, mediaType);\n            formatter.MediaTypeMappings.Add(mapping);\n        }\n\n        /// <summary>\n        /// Updates the given <paramref name=\"formatter\"/>'s set of <see cref=\"MediaTypeMapping\"/> elements\n        /// so that it associates the <paramref name=\"mediaType\"/> with a specific HTTP request header field\n        /// with a specific value.\n        /// </summary>\n        /// <remarks><see cref=\"RequestHeaderMapping\"/> checks header fields associated with <see cref=\"M:HttpRequestMessage.Headers\"/> for a match. It does\n        /// not check header fields associated with <see cref=\"M:HttpResponseMessage.Headers\"/> or <see cref=\"M:HttpContent.Headers\"/> instances.</remarks>\n        /// <param name=\"formatter\">The <see cref=\"MediaTypeFormatter\"/> to receive the new <see cref=\"MediaTypeMapping\"/> item.</param>\n        /// <param name=\"headerName\">Name of the header to match.</param>\n        /// <param name=\"headerValue\">The header value to match.</param>\n        /// <param name=\"valueComparison\">The <see cref=\"StringComparison\"/> to use when matching <paramref name=\"headerValue\"/>.</param>\n        /// <param name=\"isValueSubstring\">if set to <c>true</c> then <paramref name=\"headerValue\"/> is \n        /// considered a match if it matches a substring of the actual header value.</param>\n        /// <param name=\"mediaType\">The <see cref=\"MediaTypeHeaderValue\"/> to associate \n        /// with a <see cref=\"M:HttpRequestMessage.Header\"/> entry with a name matching <paramref name=\"headerName\"/>\n        /// and a value matching <paramref name=\"headerValue\"/>.</param>\n        public static void AddRequestHeaderMapping(\n            this MediaTypeFormatter formatter,\n            string headerName,\n            string headerValue,\n            StringComparison valueComparison,\n            bool isValueSubstring,\n            MediaTypeHeaderValue mediaType)\n        {\n            if (formatter == null)\n            {\n                throw Error.ArgumentNull(\"formatter\");\n            }\n\n            RequestHeaderMapping mapping = new RequestHeaderMapping(headerName, headerValue, valueComparison, isValueSubstring, mediaType);\n            formatter.MediaTypeMappings.Add(mapping);\n        }\n\n        /// <summary>\n        /// Updates the given <paramref name=\"formatter\"/>'s set of <see cref=\"MediaTypeMapping\"/> elements\n        /// so that it associates the <paramref name=\"mediaType\"/> with a specific HTTP request header field\n        /// with a specific value.\n        /// </summary>\n        /// <remarks><see cref=\"RequestHeaderMapping\"/> checks header fields associated with <see cref=\"M:HttpRequestMessage.Headers\"/> for a match. It does\n        /// not check header fields associated with <see cref=\"M:HttpResponseMessage.Headers\"/> or <see cref=\"M:HttpContent.Headers\"/> instances.</remarks>\n        /// <param name=\"formatter\">The <see cref=\"MediaTypeFormatter\"/> to receive the new <see cref=\"MediaTypeMapping\"/> item.</param>\n        /// <param name=\"headerName\">Name of the header to match.</param>\n        /// <param name=\"headerValue\">The header value to match.</param>\n        /// <param name=\"valueComparison\">The <see cref=\"StringComparison\"/> to use when matching <paramref name=\"headerValue\"/>.</param>\n        /// <param name=\"isValueSubstring\">if set to <c>true</c> then <paramref name=\"headerValue\"/> is \n        /// considered a match if it matches a substring of the actual header value.</param>\n        /// <param name=\"mediaType\">The media type to associate \n        /// with a <see cref=\"M:HttpRequestMessage.Header\"/> entry with a name matching <paramref name=\"headerName\"/>\n        /// and a value matching <paramref name=\"headerValue\"/>.</param>\n        public static void AddRequestHeaderMapping(\n            this MediaTypeFormatter formatter,\n            string headerName,\n            string headerValue,\n            StringComparison valueComparison,\n            bool isValueSubstring,\n            string mediaType)\n        {\n            if (formatter == null)\n            {\n                throw Error.ArgumentNull(\"formatter\");\n            }\n\n            RequestHeaderMapping mapping = new RequestHeaderMapping(headerName, headerValue, valueComparison, isValueSubstring, mediaType);\n            formatter.MediaTypeMappings.Add(mapping);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/MediaTypeFormatterMatch.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Headers;\nusing System.Web.Http;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// This class describes how well a particular <see cref=\"MediaTypeFormatter\"/> matches a request.\n    /// </summary>\n    public class MediaTypeFormatterMatch\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"MediaTypeFormatterMatch\"/> class.\n        /// </summary>\n        /// <param name=\"formatter\">The matching formatter.</param>\n        /// <param name=\"mediaType\">The media type. Can be <c>null</c> in which case the media type <c>application/octet-stream</c> is used.</param>\n        /// <param name=\"quality\">The quality of the match. Can be <c>null</c> in which case it is considered a full match with a value of 1.0</param>\n        /// <param name=\"ranking\">The kind of match.</param>\n        public MediaTypeFormatterMatch(MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, double? quality, MediaTypeFormatterMatchRanking ranking)\n        {\n            if (formatter == null)\n            {\n                throw Error.ArgumentNull(\"formatter\");\n            }\n\n            Formatter = formatter;\n            MediaType = mediaType != null ? mediaType.Clone() : MediaTypeConstants.ApplicationOctetStreamMediaType;\n            Quality = quality ?? FormattingUtilities.Match;\n            Ranking = ranking;\n        }\n\n        /// <summary>\n        /// Gets the media type formatter.\n        /// </summary>\n        public MediaTypeFormatter Formatter { get; private set; }\n\n        /// <summary>\n        /// Gets the matched media type.\n        /// </summary>\n        public MediaTypeHeaderValue MediaType { get; private set; }\n\n        /// <summary>\n        /// Gets the quality of the match\n        /// </summary>\n        public double Quality { get; private set; }\n\n        /// <summary>\n        /// Gets the kind of match that occurred.\n        /// </summary>\n        public MediaTypeFormatterMatchRanking Ranking { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/MediaTypeFormatterMatchRanking.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// Contains information about the degree to which a <see cref=\"MediaTypeFormatter\"/> matches the  \n    /// explicit or implicit preferences found in an incoming request.\n    /// </summary>\n    public enum MediaTypeFormatterMatchRanking\n    {\n        /// <summary>\n        /// No match was found\n        /// </summary>\n        None = 0,\n\n        /// <summary>\n        /// Matched on type meaning that the formatter is able to serialize the type\n        /// </summary>\n        MatchOnCanWriteType,\n\n        /// <summary>\n        /// Matched on explicit literal accept header in <see cref=\"HttpRequestMessage\"/>, \n        /// e.g. \"application/json\".\n        /// </summary>\n        MatchOnRequestAcceptHeaderLiteral,\n\n        /// <summary>\n        /// Matched on explicit subtype range accept header in <see cref=\"HttpRequestMessage\"/>,\n        /// e.g. \"application/*\".\n        /// </summary>\n        MatchOnRequestAcceptHeaderSubtypeMediaRange,\n\n        /// <summary>\n        /// Matched on explicit all media type range accept header in <see cref=\"HttpRequestMessage\"/>,\n        /// e.g. \"*/*\"\n        /// </summary>\n        MatchOnRequestAcceptHeaderAllMediaRange,\n\n        /// <summary>\n        /// Matched on <see cref=\"HttpRequestMessage\"/> after having applied\n        /// the various <see cref=\"MediaTypeMapping\"/>s.\n        /// </summary>\n        MatchOnRequestWithMediaTypeMapping,\n\n        /// <summary>\n        /// Matched on the media type of the <see cref=\"HttpContent\"/> of the <see cref=\"HttpRequestMessage\"/>.\n        /// </summary>\n        MatchOnRequestMediaType,\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/MediaTypeHeaderValueExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing System.Net.Http.Headers;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// Extension methods for <see cref=\"MediaTypeHeaderValue\"/>.\n    /// </summary>\n    internal static class MediaTypeHeaderValueExtensions\n    {\n        /// <summary>\n        /// Determines whether two <see cref=\"MediaTypeHeaderValue\"/> instances match. The instance\n        /// <paramref name=\"mediaType1\"/> is said to match <paramref name=\"mediaType2\"/> if and only if\n        /// <paramref name=\"mediaType1\"/> is a strict subset of the values and parameters of <paramref name=\"mediaType2\"/>.\n        /// That is, if the media type and media type parameters of <paramref name=\"mediaType1\"/> are all present\n        /// and match those of <paramref name=\"mediaType2\"/> then it is a match even though <paramref name=\"mediaType2\"/> may have additional\n        /// parameters.\n        /// </summary>\n        /// <param name=\"mediaType1\">The first media type.</param>\n        /// <param name=\"mediaType2\">The second media type.</param>\n        /// <returns><c>true</c> if this is a subset of <paramref name=\"mediaType2\"/>; false otherwise.</returns>\n        public static bool IsSubsetOf(this MediaTypeHeaderValue mediaType1, MediaTypeHeaderValue mediaType2)\n        {\n            MediaTypeHeaderValueRange mediaType2Range;\n            return IsSubsetOf(mediaType1, mediaType2, out mediaType2Range);\n        }\n\n        /// <summary>\n        /// Determines whether two <see cref=\"MediaTypeHeaderValue\"/> instances match. The instance\n        /// <paramref name=\"mediaType1\"/> is said to match <paramref name=\"mediaType2\"/> if and only if\n        /// <paramref name=\"mediaType1\"/> is a strict subset of the values and parameters of <paramref name=\"mediaType2\"/>.\n        /// That is, if the media type and media type parameters of <paramref name=\"mediaType1\"/> are all present\n        /// and match those of <paramref name=\"mediaType2\"/> then it is a match even though <paramref name=\"mediaType2\"/> may have additional\n        /// parameters.\n        /// </summary>\n        /// <param name=\"mediaType1\">The first media type.</param>\n        /// <param name=\"mediaType2\">The second media type.</param>\n        /// <param name=\"mediaType2Range\">Indicates whether <paramref name=\"mediaType2\"/> is a regular media type, a subtype media range, or a full media range</param>\n        /// <returns><c>true</c> if this is a subset of <paramref name=\"mediaType2\"/>; false otherwise.</returns>\n        public static bool IsSubsetOf(this MediaTypeHeaderValue mediaType1, MediaTypeHeaderValue mediaType2, out MediaTypeHeaderValueRange mediaType2Range)\n        {\n            // Performance-sensitive\n            Contract.Assert(mediaType1 != null);\n\n            if (mediaType2 == null)\n            {\n                mediaType2Range = MediaTypeHeaderValueRange.None;\n                return false;\n            }\n\n            ParsedMediaTypeHeaderValue parsedMediaType1 = new ParsedMediaTypeHeaderValue(mediaType1);\n            ParsedMediaTypeHeaderValue parsedMediaType2 = new ParsedMediaTypeHeaderValue(mediaType2);\n            mediaType2Range = parsedMediaType2.IsAllMediaRange ? MediaTypeHeaderValueRange.AllMediaRange :\n                parsedMediaType2.IsSubtypeMediaRange ? MediaTypeHeaderValueRange.SubtypeMediaRange :\n                MediaTypeHeaderValueRange.None;\n\n            if (!parsedMediaType1.TypesEqual(ref parsedMediaType2))\n            {\n                if (mediaType2Range != MediaTypeHeaderValueRange.AllMediaRange)\n                {\n                    return false;\n                }\n            }\n            else if (!parsedMediaType1.SubTypesEqual(ref parsedMediaType2))\n            {\n                if (mediaType2Range != MediaTypeHeaderValueRange.SubtypeMediaRange)\n                {\n                    return false;\n                }\n            }\n\n            // So far we either have a full match or a subset match. Now check that all of\n            // mediaType1's parameters are present and equal in mediatype2\n            // Optimize for the common case where the parameters inherit from Collection<T> and cache the count which is faster for Collection<T>.\n            Collection<NameValueHeaderValue> parameters1 = mediaType1.Parameters.AsCollection();\n            int parameterCount1 = parameters1.Count;\n            Collection<NameValueHeaderValue> parameters2 = mediaType2.Parameters.AsCollection();\n            int parameterCount2 = parameters2.Count;\n            for (int i = 0; i < parameterCount1; i++)\n            {\n                NameValueHeaderValue parameter1 = parameters1[i];\n                bool found = false;\n                for (int j = 0; j < parameterCount2; j++)\n                {\n                    NameValueHeaderValue parameter2 = parameters2[j];\n                    if (parameter1.Equals(parameter2))\n                    {\n                        found = true;\n                        break;\n                    }\n                }\n                if (!found)\n                {\n                    return false;\n                }\n            }\n            return true;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/MediaTypeHeaderValueRange.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Net.Http.Formatting\n{\n    internal enum MediaTypeHeaderValueRange\n    {\n        /// <summary>\n        /// Not a media type range\n        /// </summary>\n        None = 0,\n\n        /// <summary>\n        /// A subtype media range, e.g. \"application/*\".\n        /// </summary>\n        SubtypeMediaRange,\n\n        /// <summary>\n        /// An all media range, e.g. \"*/*\".\n        /// </summary>\n        AllMediaRange,\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/MediaTypeMapping.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Headers;\nusing System.Web.Http;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// An abstract base class used to create an association between <see cref=\"HttpRequestMessage\"/> or \n    /// <see cref=\"HttpResponseMessage\"/> instances that have certain characteristics \n    /// and a specific <see cref=\"MediaTypeHeaderValue\"/>. \n    /// </summary>\n    public abstract class MediaTypeMapping\n    {\n        /// <summary>\n        /// Initializes a new instance of a <see cref=\"MediaTypeMapping\"/> with the\n        /// given <paramref name=\"mediaType\"/> value.\n        /// </summary>\n        /// <param name=\"mediaType\">\n        /// The <see cref=\"MediaTypeHeaderValue\"/> that is associated with <see cref=\"HttpRequestMessage\"/> or \n        /// <see cref=\"HttpResponseMessage\"/> instances that have the given characteristics of the \n        /// <see cref=\"MediaTypeMapping\"/>.\n        /// </param>\n        protected MediaTypeMapping(MediaTypeHeaderValue mediaType)\n        {\n            if (mediaType == null)\n            {\n                throw Error.ArgumentNull(\"mediaType\");\n            }\n\n            MediaType = mediaType;\n        }\n\n        /// <summary>\n        /// Initializes a new instance of a <see cref=\"MediaTypeMapping\"/> with the\n        /// given <paramref name=\"mediaType\"/> value.\n        /// </summary>\n        /// <param name=\"mediaType\">\n        /// The <see cref=\"string\"/> that is associated with <see cref=\"HttpRequestMessage\"/> or \n        /// <see cref=\"HttpResponseMessage\"/> instances that have the given characteristics of the \n        /// <see cref=\"MediaTypeMapping\"/>.\n        /// </param>\n        protected MediaTypeMapping(string mediaType)\n        {\n            if (String.IsNullOrWhiteSpace(mediaType))\n            {\n                throw Error.ArgumentNull(\"mediaType\");\n            }\n\n            MediaType = new MediaTypeHeaderValue(mediaType);\n        }\n\n        /// <summary>\n        /// Gets the <see cref=\"MediaTypeHeaderValue\"/> that is associated with <see cref=\"HttpRequestMessage\"/> or \n        /// <see cref=\"HttpResponseMessage\"/> instances that have the given characteristics of the \n        /// <see cref=\"MediaTypeMapping\"/>.\n        /// </summary>\n        public MediaTypeHeaderValue MediaType { get; private set; }\n\n        /// <summary>\n        /// Returns the quality of the match of the <see cref=\"MediaTypeHeaderValue\"/>\n        /// associated with <paramref name=\"request\"/>.\n        /// </summary>\n        /// <param name=\"request\">\n        /// The <see cref=\"HttpRequestMessage\"/> to evaluate for the characteristics \n        /// associated with the <see cref=\"MediaTypeHeaderValue\"/>\n        /// of the <see cref=\"MediaTypeMapping\"/>.\n        /// </param> \n        /// <returns>\n        /// The quality of the match. It must be between <c>0.0</c> and <c>1.0</c>.\n        /// A value of <c>0.0</c> signifies no match.\n        /// A value of <c>1.0</c> signifies a complete match.\n        /// </returns>\n        public abstract double TryMatchMediaType(HttpRequestMessage request);\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/MediaTypeWithQualityHeaderValueComparer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Net.Http.Headers;\n\nnamespace System.Net.Http.Formatting\n{\n    /// Implementation of <see cref=\"IComparer{T}\"/> that can compare accept media type header fields\n    /// based on their quality values (a.k.a q-values). See\n    /// <see cref=\"StringWithQualityHeaderValueComparer\"/> for a comparer for other content negotiation\n    /// header field q-values.\n    internal class MediaTypeWithQualityHeaderValueComparer : IComparer<MediaTypeWithQualityHeaderValue>\n    {\n        private static readonly MediaTypeWithQualityHeaderValueComparer _mediaTypeComparer = new MediaTypeWithQualityHeaderValueComparer();\n\n        private MediaTypeWithQualityHeaderValueComparer()\n        {\n        }\n\n        public static MediaTypeWithQualityHeaderValueComparer QualityComparer\n        {\n            get { return _mediaTypeComparer; }\n        }\n\n        /// <summary>\n        /// Compares two <see cref=\"MediaTypeWithQualityHeaderValue\"/> based on their quality value (a.k.a their \"q-value\").\n        /// Values with identical q-values are considered equal (i.e the result is 0) with the exception that sub-type wild-cards are\n        /// considered less than specific media types and full wild-cards are considered less than sub-type wild-cards. This allows to\n        /// sort a sequence of <see cref=\"StringWithQualityHeaderValue\"/> following their q-values in the order of specific media types,\n        /// sub-type wildcards, and last any full wild-cards.\n        /// </summary>\n        /// <param name=\"mediaType1\">The first <see cref=\"MediaTypeWithQualityHeaderValue\"/> to compare.</param>\n        /// <param name=\"mediaType2\">The second <see cref=\"MediaTypeWithQualityHeaderValue\"/> to compare.</param>\n        /// <returns></returns>\n        public int Compare(MediaTypeWithQualityHeaderValue mediaType1, MediaTypeWithQualityHeaderValue mediaType2)\n        {\n            Contract.Assert(mediaType1 != null, \"The 'mediaType1' parameter should not be null.\");\n            Contract.Assert(mediaType2 != null, \"The 'mediaType2' parameter should not be null.\");\n\n            if (Object.ReferenceEquals(mediaType1, mediaType2))\n            {\n                return 0;\n            }\n\n            int returnValue = CompareBasedOnQualityFactor(mediaType1, mediaType2);\n\n            if (returnValue == 0)\n            {\n                ParsedMediaTypeHeaderValue parsedMediaType1 = new ParsedMediaTypeHeaderValue(mediaType1);\n                ParsedMediaTypeHeaderValue parsedMediaType2 = new ParsedMediaTypeHeaderValue(mediaType2);\n\n                if (!parsedMediaType1.TypesEqual(ref parsedMediaType2))\n                {\n                    if (parsedMediaType1.IsAllMediaRange)\n                    {\n                        return -1;\n                    }\n                    else if (parsedMediaType2.IsAllMediaRange)\n                    {\n                        return 1;\n                    }\n                    else if (parsedMediaType1.IsSubtypeMediaRange && !parsedMediaType2.IsSubtypeMediaRange)\n                    {\n                        return -1;\n                    }\n                    else if (!parsedMediaType1.IsSubtypeMediaRange && parsedMediaType2.IsSubtypeMediaRange)\n                    {\n                        return 1;\n                    }\n                }\n                else if (!parsedMediaType1.SubTypesEqual(ref parsedMediaType2))\n                {\n                    if (parsedMediaType1.IsSubtypeMediaRange)\n                    {\n                        return -1;\n                    }\n                    else if (parsedMediaType2.IsSubtypeMediaRange)\n                    {\n                        return 1;\n                    }\n                }\n            }\n\n            return returnValue;\n        }\n\n        private static int CompareBasedOnQualityFactor(MediaTypeWithQualityHeaderValue mediaType1, MediaTypeWithQualityHeaderValue mediaType2)\n        {\n            Contract.Assert(mediaType1 != null);\n            Contract.Assert(mediaType2 != null);\n\n            double mediaType1Quality = mediaType1.Quality ?? FormattingUtilities.Match;\n            double mediaType2Quality = mediaType2.Quality ?? FormattingUtilities.Match;\n            double qualityDifference = mediaType1Quality - mediaType2Quality;\n            if (qualityDifference < 0)\n            {\n                return -1;\n            }\n            else if (qualityDifference > 0)\n            {\n                return 1;\n            }\n\n            return 0;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/ParsedMediaTypeHeaderValue.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net.Http.Headers;\n\nnamespace System.Net.Http.Formatting\n{\n    // This type is instanciated by frequently called comparison methods so is very performance sensitive\n    internal struct ParsedMediaTypeHeaderValue\n    {\n        private const char MediaRangeAsterisk = '*';\n        private const char MediaTypeSubtypeDelimiter = '/';\n\n        private readonly string _mediaType;\n        private readonly int _delimiterIndex;\n        private readonly bool _isAllMediaRange;\n        private readonly bool _isSubtypeMediaRange;\n\n        public ParsedMediaTypeHeaderValue(MediaTypeHeaderValue mediaTypeHeaderValue)\n        {\n            Contract.Assert(mediaTypeHeaderValue != null);\n            string mediaType = _mediaType = mediaTypeHeaderValue.MediaType;\n            _delimiterIndex = mediaType.IndexOf(MediaTypeSubtypeDelimiter);\n            Contract.Assert(_delimiterIndex > 0, \"The constructor of the MediaTypeHeaderValue would have failed if there wasn't a type and subtype.\");\n\n            _isAllMediaRange = false;\n            _isSubtypeMediaRange = false;\n            int mediaTypeLength = mediaType.Length;\n            if (_delimiterIndex == mediaTypeLength - 2)\n            {\n                if (mediaType[mediaTypeLength - 1] == MediaRangeAsterisk)\n                {\n                    _isSubtypeMediaRange = true;\n                    if (_delimiterIndex == 1 && mediaType[0] == MediaRangeAsterisk)\n                    {\n                        _isAllMediaRange = true;\n                    }\n                }\n            }\n        }\n\n        public bool IsAllMediaRange\n        {\n            get { return _isAllMediaRange; }\n        }\n\n        public bool IsSubtypeMediaRange\n        {\n            get { return _isSubtypeMediaRange; }\n        }\n\n        public bool TypesEqual(ref ParsedMediaTypeHeaderValue other)\n        {\n            if (_delimiterIndex != other._delimiterIndex)\n            {\n                return false;\n            }\n            return String.Compare(_mediaType, 0, other._mediaType, 0, _delimiterIndex, StringComparison.OrdinalIgnoreCase) == 0;\n        }\n\n        public bool SubTypesEqual(ref ParsedMediaTypeHeaderValue other)\n        {\n            int _subTypeLength = _mediaType.Length - _delimiterIndex - 1;\n            if (_subTypeLength != other._mediaType.Length - other._delimiterIndex - 1)\n            {\n                return false;\n            }\n            return String.Compare(_mediaType, _delimiterIndex + 1, other._mediaType, other._delimiterIndex + 1, _subTypeLength, StringComparison.OrdinalIgnoreCase) == 0;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/Parsers/FormUrlEncodedParser.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Text;\nusing System.Web.Http;\n\nnamespace System.Net.Http.Formatting.Parsers\n{\n    /// <summary>\n    /// Buffer-oriented parsing of HTML form URL-ended, also known as <c>application/x-www-form-urlencoded</c>, data.\n    /// </summary>\n    internal class FormUrlEncodedParser\n    {\n        private const int MinMessageSize = 1;\n        private long _totalBytesConsumed;\n        private long _maxMessageSize;\n\n        private NameValueState _nameValueState;\n        private ICollection<KeyValuePair<string, string>> _nameValuePairs;\n        private readonly CurrentNameValuePair _currentNameValuePair;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"FormUrlEncodedParser\"/> class.\n        /// </summary>\n        /// <param name=\"nameValuePairs\">The collection to which name value pairs are added as they are parsed.</param>\n        /// <param name=\"maxMessageSize\">Maximum length of all the individual name value pairs.</param>\n        public FormUrlEncodedParser(ICollection<KeyValuePair<string, string>> nameValuePairs, long maxMessageSize)\n        {\n            // The minimum length which would be an empty buffer\n            if (maxMessageSize < MinMessageSize)\n            {\n                throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"maxMessageSize\", maxMessageSize, MinMessageSize);\n            }\n\n            if (nameValuePairs == null)\n            {\n                throw Error.ArgumentNull(\"nameValuePairs\");\n            }\n\n            _nameValuePairs = nameValuePairs;\n            _maxMessageSize = maxMessageSize;\n            _currentNameValuePair = new CurrentNameValuePair();\n        }\n\n        private enum NameValueState\n        {\n            Name = 0,\n            Value\n        }\n\n        /// <summary>\n        /// Parse a buffer of URL form-encoded name-value pairs and add them to the collection.\n        /// Bytes are parsed in a consuming manner from the beginning of the buffer meaning that the same bytes can not be\n        /// present in the buffer.\n        /// </summary>\n        /// <param name=\"buffer\">Buffer from where data is read</param>\n        /// <param name=\"bytesReady\">Size of buffer</param>\n        /// <param name=\"bytesConsumed\">Offset into buffer</param>\n        /// <param name=\"isFinal\">Indicates whether the end of the URL form-encoded data has been reached.</param>\n        /// <returns>State of the parser. Call this method with new data until it reaches a final state.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Exception is translated to parse state.\")]\n        public ParserState ParseBuffer(\n            byte[] buffer,\n            int bytesReady,\n            ref int bytesConsumed,\n            bool isFinal)\n        {\n            if (buffer == null)\n            {\n                throw Error.ArgumentNull(\"buffer\");\n            }\n\n            ParserState parseStatus = ParserState.NeedMoreData;\n\n            if (bytesConsumed >= bytesReady)\n            {\n                if (isFinal)\n                {\n                    parseStatus = CopyCurrent(parseStatus);\n                }\n\n                // We either can already tell we need more data or we are done\n                return parseStatus;\n            }\n\n            try\n            {\n                parseStatus = ParseNameValuePairs(\n                    buffer,\n                    bytesReady,\n                    ref bytesConsumed,\n                    ref _nameValueState,\n                    _maxMessageSize,\n                    ref _totalBytesConsumed,\n                    _currentNameValuePair,\n                    _nameValuePairs);\n\n                if (isFinal)\n                {\n                    parseStatus = CopyCurrent(parseStatus);\n                }\n            }\n            catch (Exception)\n            {\n                parseStatus = ParserState.Invalid;\n            }\n\n            return parseStatus;\n        }\n\n        [SuppressMessage(\"Microsoft.Maintainability\", \"CA1502:AvoidExcessiveComplexity\", Justification = \"This is a parser which cannot be split up for performance reasons.\")]\n        private static ParserState ParseNameValuePairs(\n            byte[] buffer,\n            int bytesReady,\n            ref int bytesConsumed,\n            ref NameValueState nameValueState,\n            long maximumLength,\n            ref long totalBytesConsumed,\n            CurrentNameValuePair currentNameValuePair,\n            ICollection<KeyValuePair<string, string>> nameValuePairs)\n        {\n            Contract.Assert((bytesReady - bytesConsumed) >= 0, \"ParseNameValuePairs()|(inputBufferLength - bytesParsed) < 0\");\n            Contract.Assert(maximumLength <= 0 || totalBytesConsumed <= maximumLength, \"ParseNameValuePairs()|Headers already read exceeds limit.\");\n\n            // Remember where we started.\n            int initialBytesParsed = bytesConsumed;\n            int segmentStart;\n\n            // Set up parsing status with what will happen if we exceed the buffer.\n            ParserState parseStatus = ParserState.DataTooBig;\n            long effectiveMax = maximumLength <= 0 ? Int64.MaxValue : maximumLength - totalBytesConsumed + initialBytesParsed;\n            if (bytesReady < effectiveMax)\n            {\n                parseStatus = ParserState.NeedMoreData;\n                effectiveMax = bytesReady;\n            }\n\n            Contract.Assert(bytesConsumed < effectiveMax, \"We have already consumed more than the max buffer length.\");\n\n            switch (nameValueState)\n            {\n                case NameValueState.Name:\n                    segmentStart = bytesConsumed;\n                    while (buffer[bytesConsumed] != '=' && buffer[bytesConsumed] != '&')\n                    {\n                        if (++bytesConsumed == effectiveMax)\n                        {\n                            string name = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);\n                            currentNameValuePair.Name.Append(name);\n                            goto quit;\n                        }\n                    }\n\n                    if (bytesConsumed > segmentStart)\n                    {\n                        string name = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);\n                        currentNameValuePair.Name.Append(name);\n                    }\n\n                    // Check if we got name=value or just name\n                    if (buffer[bytesConsumed] == '=')\n                    {\n                        // Move part the '='\n                        nameValueState = NameValueState.Value;\n                        if (++bytesConsumed == effectiveMax)\n                        {\n                            goto quit;\n                        }\n\n                        goto case NameValueState.Value;\n                    }\n                    else\n                    {\n                        // Copy parsed name-only to collection\n                        currentNameValuePair.CopyNameOnlyTo(nameValuePairs);\n\n                        // Move past the '&' but stay in same state\n                        if (++bytesConsumed == effectiveMax)\n                        {\n                            goto quit;\n                        }\n\n                        goto case NameValueState.Name;\n                    }\n\n                case NameValueState.Value:\n                    segmentStart = bytesConsumed;\n                    while (buffer[bytesConsumed] != '&')\n                    {\n                        if (++bytesConsumed == effectiveMax)\n                        {\n                            string value = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);\n                            currentNameValuePair.Value.Append(value);\n                            goto quit;\n                        }\n                    }\n\n                    if (bytesConsumed > segmentStart)\n                    {\n                        string value = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);\n                        currentNameValuePair.Value.Append(value);\n                    }\n\n                    // Copy parsed name value pair to collection\n                    currentNameValuePair.CopyTo(nameValuePairs);\n\n                    // Move past the '&'\n                    nameValueState = NameValueState.Name;\n                    if (++bytesConsumed == effectiveMax)\n                    {\n                        goto quit;\n                    }\n\n                    goto case NameValueState.Name;\n            }\n\n        quit:\n            totalBytesConsumed += bytesConsumed - initialBytesParsed;\n            return parseStatus;\n        }\n\n        private ParserState CopyCurrent(ParserState parseState)\n        {\n            // Copy parsed name value pair to collection\n            if (_nameValueState == NameValueState.Name)\n            {\n                if (_totalBytesConsumed > 0)\n                {\n                    _currentNameValuePair.CopyNameOnlyTo(_nameValuePairs);\n                }\n            }\n            else\n            {\n                _currentNameValuePair.CopyTo(_nameValuePairs);\n            }\n\n            // We are done (or in an error state)\n            return parseState == ParserState.NeedMoreData ? ParserState.Done : parseState;\n        }\n\n        /// <summary>\n        /// Maintains information about the current header field being parsed.\n        /// </summary>\n        private class CurrentNameValuePair\n        {\n            private const int DefaultNameAllocation = 128;\n            private const int DefaultValueAllocation = 2 * 1024;\n\n            private readonly StringBuilder _name = new StringBuilder(DefaultNameAllocation);\n            private readonly StringBuilder _value = new StringBuilder(DefaultValueAllocation);\n\n            /// <summary>\n            /// Gets the name of the name value pair.\n            /// </summary>\n            public StringBuilder Name\n            {\n                get { return _name; }\n            }\n\n            /// <summary>\n            /// Gets the value of the name value pair\n            /// </summary>\n            public StringBuilder Value\n            {\n                get { return _value; }\n            }\n\n            /// <summary>\n            /// Copies current name value pair field to the provided collection instance.\n            /// </summary>\n            /// <param name=\"nameValuePairs\">The collection to copy into.</param>\n            public void CopyTo(ICollection<KeyValuePair<string, string>> nameValuePairs)\n            {\n                string unescapedName = WebUtility.UrlDecode(_name.ToString());\n                string escapedValue = _value.ToString();\n                string value = WebUtility.UrlDecode(escapedValue);\n\n                nameValuePairs.Add(new KeyValuePair<string, string>(unescapedName, value));\n\n                Clear();\n            }\n\n            /// <summary>\n            /// Copies current name-only to the provided collection instance.\n            /// </summary>\n            /// <param name=\"nameValuePairs\">The collection to copy into.</param>\n            public void CopyNameOnlyTo(ICollection<KeyValuePair<string, string>> nameValuePairs)\n            {\n                string unescapedName = WebUtility.UrlDecode(_name.ToString());\n                string value = String.Empty;\n                nameValuePairs.Add(new KeyValuePair<string, string>(unescapedName, value));\n                Clear();\n            }\n\n            /// <summary>\n            /// Clears this instance.\n            /// </summary>\n            private void Clear()\n            {\n                _name.Clear();\n                _value.Clear();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/Parsers/HttpRequestHeaderParser.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Http;\n\nnamespace System.Net.Http.Formatting.Parsers\n{\n    /// <summary>\n    /// The <see cref=\"HttpRequestHeaderParser\"/> combines <see cref=\"HttpRequestLineParser\"/> for parsing the HTTP Request Line  \n    /// and <see cref=\"InternetMessageFormatHeaderParser\"/> for parsing each header field. \n    /// </summary>\n    internal class HttpRequestHeaderParser\n    {\n        internal const int DefaultMaxRequestLineSize = 2 * 1024;\n        internal const int DefaultMaxHeaderSize = 16 * 1024; // Same default size as IIS has for regular requests\n\n        private HttpUnsortedRequest _httpRequest;\n        private HttpRequestState _requestStatus = HttpRequestState.RequestLine;\n\n        private HttpRequestLineParser _requestLineParser;\n        private InternetMessageFormatHeaderParser _headerParser;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpRequestHeaderParser\"/> class.\n        /// </summary>\n        /// <param name=\"httpRequest\">The parsed HTTP request without any header sorting.</param>\n        public HttpRequestHeaderParser(HttpUnsortedRequest httpRequest)\n            : this(httpRequest, DefaultMaxRequestLineSize, DefaultMaxHeaderSize)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpRequestHeaderParser\"/> class.\n        /// </summary>\n        /// <param name=\"httpRequest\">The parsed HTTP request without any header sorting.</param>\n        /// <param name=\"maxRequestLineSize\">The max length of the HTTP request line.</param>\n        /// <param name=\"maxHeaderSize\">The max length of the HTTP header.</param>\n        public HttpRequestHeaderParser(HttpUnsortedRequest httpRequest, int maxRequestLineSize, int maxHeaderSize)\n        {\n            if (httpRequest == null)\n            {\n                throw Error.ArgumentNull(\"httpRequest\");\n            }\n\n            _httpRequest = httpRequest;\n\n            // Create request line parser\n            _requestLineParser = new HttpRequestLineParser(_httpRequest, maxRequestLineSize);\n\n            // Create header parser\n            _headerParser = new InternetMessageFormatHeaderParser(_httpRequest.HttpHeaders, maxHeaderSize);\n        }\n\n        private enum HttpRequestState\n        {\n            RequestLine = 0, // parsing request line\n            RequestHeaders // reading headers\n        }\n\n        /// <summary>\n        /// Parse an HTTP request header and fill in the <see cref=\"HttpRequestMessage\"/> instance.\n        /// </summary>\n        /// <param name=\"buffer\">Request buffer from where request is read</param>\n        /// <param name=\"bytesReady\">Size of request buffer</param>\n        /// <param name=\"bytesConsumed\">Offset into request buffer</param>\n        /// <returns>State of the parser.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Exception is propagated.\")]\n        public ParserState ParseBuffer(\n            byte[] buffer,\n            int bytesReady,\n            ref int bytesConsumed)\n        {\n            if (buffer == null)\n            {\n                throw Error.ArgumentNull(\"buffer\");\n            }\n\n            ParserState parseStatus = ParserState.NeedMoreData;\n            ParserState subParseStatus = ParserState.NeedMoreData;\n\n            switch (_requestStatus)\n            {\n                case HttpRequestState.RequestLine:\n                    try\n                    {\n                        subParseStatus = _requestLineParser.ParseBuffer(buffer, bytesReady, ref bytesConsumed);\n                    }\n                    catch (Exception)\n                    {\n                        subParseStatus = ParserState.Invalid;\n                    }\n\n                    if (subParseStatus == ParserState.Done)\n                    {\n                        _requestStatus = HttpRequestState.RequestHeaders;\n                        subParseStatus = ParserState.NeedMoreData;\n                        goto case HttpRequestState.RequestHeaders;\n                    }\n                    else if (subParseStatus != ParserState.NeedMoreData)\n                    {\n                        // Report error - either Invalid or DataTooBig\n                        parseStatus = subParseStatus;\n                        break;\n                    }\n\n                    break; // read more data\n\n                case HttpRequestState.RequestHeaders:\n                    if (bytesConsumed >= bytesReady)\n                    {\n                        // we already can tell we need more data\n                        break;\n                    }\n\n                    try\n                    {\n                        subParseStatus = _headerParser.ParseBuffer(buffer, bytesReady, ref bytesConsumed);\n                    }\n                    catch (Exception)\n                    {\n                        subParseStatus = ParserState.Invalid;\n                    }\n\n                    if (subParseStatus == ParserState.Done)\n                    {\n                        parseStatus = subParseStatus;\n                    }\n                    else if (subParseStatus != ParserState.NeedMoreData)\n                    {\n                        parseStatus = subParseStatus;\n                        break;\n                    }\n\n                    break; // need more data\n            }\n\n            return parseStatus;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/Parsers/HttpRequestLineParser.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Text;\nusing System.Web.Http;\n\nnamespace System.Net.Http.Formatting.Parsers\n{\n    /// <summary>\n    /// HTTP Request Line parser for parsing the first line (the request line) in an HTTP request.\n    /// </summary>\n    internal class HttpRequestLineParser\n    {\n        internal const int MinRequestLineSize = 14;\n        private const int DefaultTokenAllocation = 2 * 1024;\n\n        private int _totalBytesConsumed;\n        private int _maximumHeaderLength;\n\n        private HttpRequestLineState _requestLineState;\n        private HttpUnsortedRequest _httpRequest;\n        private StringBuilder _currentToken = new StringBuilder(DefaultTokenAllocation);\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpRequestLineParser\"/> class.\n        /// </summary>\n        /// <param name=\"httpRequest\"><see cref=\"HttpUnsortedRequest\"/> instance where the request line properties will be set as they are parsed.</param>\n        /// <param name=\"maxRequestLineSize\">Maximum length of HTTP header.</param>\n        public HttpRequestLineParser(HttpUnsortedRequest httpRequest, int maxRequestLineSize)\n        {\n            // The minimum length which would be an empty header terminated by CRLF\n            if (maxRequestLineSize < MinRequestLineSize)\n            {\n                throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"maxRequestLineSize\", maxRequestLineSize, MinRequestLineSize);\n            }\n\n            if (httpRequest == null)\n            {\n                throw Error.ArgumentNull(\"httpRequest\");\n            }\n\n            _httpRequest = httpRequest;\n            _maximumHeaderLength = maxRequestLineSize;\n        }\n\n        private enum HttpRequestLineState\n        {\n            RequestMethod = 0,\n            RequestUri,\n            BeforeVersionNumbers,\n            MajorVersionNumber,\n            MinorVersionNumber,\n            AfterCarriageReturn\n        }\n\n        /// <summary>\n        /// Parse an HTTP request line.\n        /// Bytes are parsed in a consuming manner from the beginning of the request buffer meaning that the same bytes can not be\n        /// present in the request buffer.\n        /// </summary>\n        /// <param name=\"buffer\">Request buffer from where request is read</param>\n        /// <param name=\"bytesReady\">Size of request buffer</param>\n        /// <param name=\"bytesConsumed\">Offset into request buffer</param>\n        /// <returns>State of the parser.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Exception is translated to parse state.\")]\n        public ParserState ParseBuffer(\n            byte[] buffer,\n            int bytesReady,\n            ref int bytesConsumed)\n        {\n            if (buffer == null)\n            {\n                throw Error.ArgumentNull(\"buffer\");\n            }\n\n            ParserState parseStatus = ParserState.NeedMoreData;\n\n            if (bytesConsumed >= bytesReady)\n            {\n                // We already can tell we need more data\n                return parseStatus;\n            }\n\n            try\n            {\n                parseStatus = ParseRequestLine(\n                    buffer,\n                    bytesReady,\n                    ref bytesConsumed,\n                    ref _requestLineState,\n                    _maximumHeaderLength,\n                    ref _totalBytesConsumed,\n                    _currentToken,\n                    _httpRequest);\n            }\n            catch (Exception)\n            {\n                parseStatus = ParserState.Invalid;\n            }\n\n            return parseStatus;\n        }\n\n        [SuppressMessage(\"Microsoft.Maintainability\", \"CA1502:AvoidExcessiveComplexity\", Justification = \"This is a parser which cannot be split up for performance reasons.\")]\n        private static ParserState ParseRequestLine(\n            byte[] buffer,\n            int bytesReady,\n            ref int bytesConsumed,\n            ref HttpRequestLineState requestLineState,\n            int maximumHeaderLength,\n            ref int totalBytesConsumed,\n            StringBuilder currentToken,\n            HttpUnsortedRequest httpRequest)\n        {\n            Contract.Assert((bytesReady - bytesConsumed) >= 0, \"ParseRequestLine()|(bytesReady - bytesConsumed) < 0\");\n            Contract.Assert(maximumHeaderLength <= 0 || totalBytesConsumed <= maximumHeaderLength, \"ParseRequestLine()|Headers already read exceeds limit.\");\n\n            // Remember where we started.\n            int initialBytesParsed = bytesConsumed;\n            int segmentStart;\n\n            // Set up parsing status with what will happen if we exceed the buffer.\n            ParserState parseStatus = ParserState.DataTooBig;\n            int effectiveMax = maximumHeaderLength <= 0 ? Int32.MaxValue : (maximumHeaderLength - totalBytesConsumed + bytesConsumed);\n            if (bytesReady < effectiveMax)\n            {\n                parseStatus = ParserState.NeedMoreData;\n                effectiveMax = bytesReady;\n            }\n\n            Contract.Assert(bytesConsumed < effectiveMax, \"We have already consumed more than the max header length.\");\n\n            switch (requestLineState)\n            {\n                case HttpRequestLineState.RequestMethod:\n                    segmentStart = bytesConsumed;\n                    while (buffer[bytesConsumed] != ' ')\n                    {\n                        if (buffer[bytesConsumed] < 0x21 || buffer[bytesConsumed] > 0x7a)\n                        {\n                            parseStatus = ParserState.Invalid;\n                            goto quit;\n                        }\n\n                        if (++bytesConsumed == effectiveMax)\n                        {\n                            string method = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);\n                            currentToken.Append(method);\n                            goto quit;\n                        }\n                    }\n\n                    if (bytesConsumed > segmentStart)\n                    {\n                        string method = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);\n                        currentToken.Append(method);\n                    }\n\n                    // Copy value out\n                    httpRequest.Method = new HttpMethod(currentToken.ToString());\n                    currentToken.Clear();\n\n                    // Move past the SP\n                    requestLineState = HttpRequestLineState.RequestUri;\n                    if (++bytesConsumed == effectiveMax)\n                    {\n                        goto quit;\n                    }\n\n                    goto case HttpRequestLineState.RequestUri;\n\n                case HttpRequestLineState.RequestUri:\n                    segmentStart = bytesConsumed;\n                    while (buffer[bytesConsumed] != ' ')\n                    {\n                        if (buffer[bytesConsumed] == '\\r')\n                        {\n                            parseStatus = ParserState.Invalid;\n                            goto quit;\n                        }\n\n                        if (++bytesConsumed == effectiveMax)\n                        {\n                            string addr = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);\n                            currentToken.Append(addr);\n                            goto quit;\n                        }\n                    }\n\n                    if (bytesConsumed > segmentStart)\n                    {\n                        string addr = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);\n                        currentToken.Append(addr);\n                    }\n\n                    // URI validation happens when we create the URI later.\n                    if (currentToken.Length == 0)\n                    {\n                        throw new FormatException(Properties.Resources.HttpMessageParserEmptyUri);\n                    }\n\n                    // Copy value out\n                    httpRequest.RequestUri = currentToken.ToString();\n                    currentToken.Clear();\n\n                    // Move past the SP\n                    requestLineState = HttpRequestLineState.BeforeVersionNumbers;\n                    if (++bytesConsumed == effectiveMax)\n                    {\n                        goto quit;\n                    }\n\n                    goto case HttpRequestLineState.BeforeVersionNumbers;\n\n                case HttpRequestLineState.BeforeVersionNumbers:\n                    segmentStart = bytesConsumed;\n                    while (buffer[bytesConsumed] != '/')\n                    {\n                        if (buffer[bytesConsumed] < 0x21 || buffer[bytesConsumed] > 0x7a)\n                        {\n                            parseStatus = ParserState.Invalid;\n                            goto quit;\n                        }\n\n                        if (++bytesConsumed == effectiveMax)\n                        {\n                            string token = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);\n                            currentToken.Append(token);\n                            goto quit;\n                        }\n                    }\n\n                    if (bytesConsumed > segmentStart)\n                    {\n                        string token = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);\n                        currentToken.Append(token);\n                    }\n\n                    // Validate value\n                    string version = currentToken.ToString();\n                    if (String.CompareOrdinal(FormattingUtilities.HttpVersionToken, version) != 0)\n                    {\n                        throw new FormatException(Error.Format(Properties.Resources.HttpInvalidVersion, version, FormattingUtilities.HttpVersionToken));\n                    }\n\n                    currentToken.Clear();\n\n                    // Move past the '/'\n                    requestLineState = HttpRequestLineState.MajorVersionNumber;\n                    if (++bytesConsumed == effectiveMax)\n                    {\n                        goto quit;\n                    }\n\n                    goto case HttpRequestLineState.MajorVersionNumber;\n\n                case HttpRequestLineState.MajorVersionNumber:\n                    segmentStart = bytesConsumed;\n                    while (buffer[bytesConsumed] != '.')\n                    {\n                        if (buffer[bytesConsumed] < '0' || buffer[bytesConsumed] > '9')\n                        {\n                            parseStatus = ParserState.Invalid;\n                            goto quit;\n                        }\n\n                        if (++bytesConsumed == effectiveMax)\n                        {\n                            string major = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);\n                            currentToken.Append(major);\n                            goto quit;\n                        }\n                    }\n\n                    if (bytesConsumed > segmentStart)\n                    {\n                        string major = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);\n                        currentToken.Append(major);\n                    }\n\n                    // Move past the \".\"\n                    currentToken.Append('.');\n                    requestLineState = HttpRequestLineState.MinorVersionNumber;\n                    if (++bytesConsumed == effectiveMax)\n                    {\n                        goto quit;\n                    }\n\n                    goto case HttpRequestLineState.MinorVersionNumber;\n\n                case HttpRequestLineState.MinorVersionNumber:\n                    segmentStart = bytesConsumed;\n                    while (buffer[bytesConsumed] != '\\r')\n                    {\n                        if (buffer[bytesConsumed] < '0' || buffer[bytesConsumed] > '9')\n                        {\n                            parseStatus = ParserState.Invalid;\n                            goto quit;\n                        }\n\n                        if (++bytesConsumed == effectiveMax)\n                        {\n                            string minor = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);\n                            currentToken.Append(minor);\n                            goto quit;\n                        }\n                    }\n\n                    if (bytesConsumed > segmentStart)\n                    {\n                        string minor = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);\n                        currentToken.Append(minor);\n                    }\n\n                    // Copy out value\n                    httpRequest.Version = Version.Parse(currentToken.ToString());\n                    currentToken.Clear();\n\n                    // Move past the CR\n                    requestLineState = HttpRequestLineState.AfterCarriageReturn;\n                    if (++bytesConsumed == effectiveMax)\n                    {\n                        goto quit;\n                    }\n\n                    goto case HttpRequestLineState.AfterCarriageReturn;\n\n                case HttpRequestLineState.AfterCarriageReturn:\n                    if (buffer[bytesConsumed] != '\\n')\n                    {\n                        parseStatus = ParserState.Invalid;\n                        goto quit;\n                    }\n\n                    parseStatus = ParserState.Done;\n                    bytesConsumed++;\n                    break;\n            }\n\n        quit:\n            totalBytesConsumed += bytesConsumed - initialBytesParsed;\n            return parseStatus;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/Parsers/HttpResponseHeaderParser.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Http;\n\nnamespace System.Net.Http.Formatting.Parsers\n{\n    /// <summary>\n    /// The <see cref=\"HttpResponseHeaderParser\"/> combines <see cref=\"HttpStatusLineParser\"/> for parsing the HTTP Status Line  \n    /// and <see cref=\"InternetMessageFormatHeaderParser\"/> for parsing each header field. \n    /// </summary>\n    internal class HttpResponseHeaderParser\n    {\n        internal const int DefaultMaxStatusLineSize = 2 * 1024;\n        internal const int DefaultMaxHeaderSize = 16 * 1024; // Same default size as IIS has for HTTP requests\n\n        private HttpUnsortedResponse _httpResponse;\n        private HttpResponseState _responseStatus = HttpResponseState.StatusLine;\n\n        private HttpStatusLineParser _statusLineParser;\n        private InternetMessageFormatHeaderParser _headerParser;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpResponseHeaderParser\"/> class.\n        /// </summary>\n        /// <param name=\"httpResponse\">The parsed HTTP response without any header sorting.</param>\n        public HttpResponseHeaderParser(HttpUnsortedResponse httpResponse)\n            : this(httpResponse, DefaultMaxStatusLineSize, DefaultMaxHeaderSize)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpResponseHeaderParser\"/> class.\n        /// </summary>\n        /// <param name=\"httpResponse\">The parsed HTTP response without any header sorting.</param>\n        /// <param name=\"maxResponseLineSize\">The max length of the HTTP status line.</param>\n        /// <param name=\"maxHeaderSize\">The max length of the HTTP header.</param>\n        public HttpResponseHeaderParser(HttpUnsortedResponse httpResponse, int maxResponseLineSize, int maxHeaderSize)\n        {\n            if (httpResponse == null)\n            {\n                throw Error.ArgumentNull(\"httpResponse\");\n            }\n\n            _httpResponse = httpResponse;\n\n            // Create status line parser\n            _statusLineParser = new HttpStatusLineParser(_httpResponse, maxResponseLineSize);\n\n            // Create header parser\n            _headerParser = new InternetMessageFormatHeaderParser(_httpResponse.HttpHeaders, maxHeaderSize);\n        }\n\n        private enum HttpResponseState\n        {\n            StatusLine = 0, // parsing status line\n            ResponseHeaders // reading headers\n        }\n\n        /// <summary>\n        /// Parse an HTTP response header and fill in the <see cref=\"HttpResponseMessage\"/> instance.\n        /// </summary>\n        /// <param name=\"buffer\">Response buffer from where response is read</param>\n        /// <param name=\"bytesReady\">Size of response buffer</param>\n        /// <param name=\"bytesConsumed\">Offset into response buffer</param>\n        /// <returns>State of the parser.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Exception is propagated.\")]\n        public ParserState ParseBuffer(\n            byte[] buffer,\n            int bytesReady,\n            ref int bytesConsumed)\n        {\n            if (buffer == null)\n            {\n                throw Error.ArgumentNull(\"buffer\");\n            }\n\n            ParserState parseStatus = ParserState.NeedMoreData;\n            ParserState subParseStatus = ParserState.NeedMoreData;\n\n            switch (_responseStatus)\n            {\n                case HttpResponseState.StatusLine:\n                    try\n                    {\n                        subParseStatus = _statusLineParser.ParseBuffer(buffer, bytesReady, ref bytesConsumed);\n                    }\n                    catch (Exception)\n                    {\n                        subParseStatus = ParserState.Invalid;\n                    }\n\n                    if (subParseStatus == ParserState.Done)\n                    {\n                        _responseStatus = HttpResponseState.ResponseHeaders;\n                        subParseStatus = ParserState.NeedMoreData;\n                        goto case HttpResponseState.ResponseHeaders;\n                    }\n                    else if (subParseStatus != ParserState.NeedMoreData)\n                    {\n                        // Report error - either Invalid or DataTooBig\n                        parseStatus = subParseStatus;\n                        break;\n                    }\n\n                    break; // read more data\n\n                case HttpResponseState.ResponseHeaders:\n                    if (bytesConsumed >= bytesReady)\n                    {\n                        // we already can tell we need more data\n                        break;\n                    }\n\n                    try\n                    {\n                        subParseStatus = _headerParser.ParseBuffer(buffer, bytesReady, ref bytesConsumed);\n                    }\n                    catch (Exception)\n                    {\n                        subParseStatus = ParserState.Invalid;\n                    }\n\n                    if (subParseStatus == ParserState.Done)\n                    {\n                        parseStatus = subParseStatus;\n                    }\n                    else if (subParseStatus != ParserState.NeedMoreData)\n                    {\n                        parseStatus = subParseStatus;\n                        break;\n                    }\n\n                    break; // need more data\n            }\n\n            return parseStatus;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/Parsers/HttpStatusLineParser.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Text;\nusing System.Web.Http;\n\nnamespace System.Net.Http.Formatting.Parsers\n{\n    /// <summary>\n    /// HTTP Status line parser for parsing the first line (the status line) in an HTTP response.\n    /// </summary>\n    internal class HttpStatusLineParser\n    {\n        internal const int MinStatusLineSize = 15;\n        private const int DefaultTokenAllocation = 2 * 1024;\n        private const int MaxStatusCode = 1000;\n\n        private int _totalBytesConsumed;\n        private int _maximumHeaderLength;\n\n        private HttpStatusLineState _statusLineState;\n        private HttpUnsortedResponse _httpResponse;\n        private StringBuilder _currentToken = new StringBuilder(DefaultTokenAllocation);\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpStatusLineParser\"/> class.\n        /// </summary>\n        /// <param name=\"httpResponse\"><see cref=\"HttpUnsortedResponse\"/> instance where the response line properties will be set as they are parsed.</param>\n        /// <param name=\"maxStatusLineSize\">Maximum length of HTTP header.</param>\n        public HttpStatusLineParser(HttpUnsortedResponse httpResponse, int maxStatusLineSize)\n        {\n            // The minimum length which would be an empty header terminated by CRLF\n            if (maxStatusLineSize < MinStatusLineSize)\n            {\n                throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"maxStatusLineSize\", maxStatusLineSize, MinStatusLineSize);\n            }\n\n            if (httpResponse == null)\n            {\n                throw Error.ArgumentNull(\"httpResponse\");\n            }\n\n            _httpResponse = httpResponse;\n            _maximumHeaderLength = maxStatusLineSize;\n        }\n\n        private enum HttpStatusLineState\n        {\n            BeforeVersionNumbers = 0,\n            MajorVersionNumber,\n            MinorVersionNumber,\n            StatusCode,\n            ReasonPhrase,\n            AfterCarriageReturn\n        }\n\n        /// <summary>\n        /// Parse an HTTP status line.\n        /// Bytes are parsed in a consuming manner from the beginning of the response buffer meaning that the same bytes can not be\n        /// present in the response buffer.\n        /// </summary>\n        /// <param name=\"buffer\">Response buffer from where response is read</param>\n        /// <param name=\"bytesReady\">Size of response buffer</param>\n        /// <param name=\"bytesConsumed\">Offset into response buffer</param>\n        /// <returns>State of the parser.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Exception is translated to parse state.\")]\n        public ParserState ParseBuffer(\n            byte[] buffer,\n            int bytesReady,\n            ref int bytesConsumed)\n        {\n            if (buffer == null)\n            {\n                throw Error.ArgumentNull(\"buffer\");\n            }\n\n            ParserState parseStatus = ParserState.NeedMoreData;\n\n            if (bytesConsumed >= bytesReady)\n            {\n                // We already can tell we need more data\n                return parseStatus;\n            }\n\n            try\n            {\n                parseStatus = ParseStatusLine(\n                    buffer,\n                    bytesReady,\n                    ref bytesConsumed,\n                    ref _statusLineState,\n                    _maximumHeaderLength,\n                    ref _totalBytesConsumed,\n                    _currentToken,\n                    _httpResponse);\n            }\n            catch (Exception)\n            {\n                parseStatus = ParserState.Invalid;\n            }\n\n            return parseStatus;\n        }\n\n        [SuppressMessage(\"Microsoft.Maintainability\", \"CA1502:AvoidExcessiveComplexity\", Justification = \"This is a parser which cannot be split up for performance reasons.\")]\n        private static ParserState ParseStatusLine(\n            byte[] buffer,\n            int bytesReady,\n            ref int bytesConsumed,\n            ref HttpStatusLineState statusLineState,\n            int maximumHeaderLength,\n            ref int totalBytesConsumed,\n            StringBuilder currentToken,\n            HttpUnsortedResponse httpResponse)\n        {\n            Contract.Assert((bytesReady - bytesConsumed) >= 0, \"ParseRequestLine()|(bytesReady - bytesConsumed) < 0\");\n            Contract.Assert(maximumHeaderLength <= 0 || totalBytesConsumed <= maximumHeaderLength, \"ParseRequestLine()|Headers already read exceeds limit.\");\n\n            // Remember where we started.\n            int initialBytesParsed = bytesConsumed;\n            int segmentStart;\n\n            // Set up parsing status with what will happen if we exceed the buffer.\n            ParserState parseStatus = ParserState.DataTooBig;\n            int effectiveMax = maximumHeaderLength <= 0 ? Int32.MaxValue : (maximumHeaderLength - totalBytesConsumed + bytesConsumed);\n            if (bytesReady < effectiveMax)\n            {\n                parseStatus = ParserState.NeedMoreData;\n                effectiveMax = bytesReady;\n            }\n\n            Contract.Assert(bytesConsumed < effectiveMax, \"We have already consumed more than the max header length.\");\n\n            switch (statusLineState)\n            {\n                case HttpStatusLineState.BeforeVersionNumbers:\n                    segmentStart = bytesConsumed;\n                    while (buffer[bytesConsumed] != '/')\n                    {\n                        if (buffer[bytesConsumed] < 0x21 || buffer[bytesConsumed] > 0x7a)\n                        {\n                            parseStatus = ParserState.Invalid;\n                            goto quit;\n                        }\n\n                        if (++bytesConsumed == effectiveMax)\n                        {\n                            string token = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);\n                            currentToken.Append(token);\n                            goto quit;\n                        }\n                    }\n\n                    if (bytesConsumed > segmentStart)\n                    {\n                        string token = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);\n                        currentToken.Append(token);\n                    }\n\n                    // Validate value\n                    string version = currentToken.ToString();\n                    if (String.CompareOrdinal(FormattingUtilities.HttpVersionToken, version) != 0)\n                    {\n                        throw new FormatException(Error.Format(Properties.Resources.HttpInvalidVersion, version, FormattingUtilities.HttpVersionToken));\n                    }\n\n                    currentToken.Clear();\n\n                    // Move past the '/'\n                    statusLineState = HttpStatusLineState.MajorVersionNumber;\n                    if (++bytesConsumed == effectiveMax)\n                    {\n                        goto quit;\n                    }\n\n                    goto case HttpStatusLineState.MajorVersionNumber;\n\n                case HttpStatusLineState.MajorVersionNumber:\n                    segmentStart = bytesConsumed;\n                    while (buffer[bytesConsumed] != '.')\n                    {\n                        if (buffer[bytesConsumed] < '0' || buffer[bytesConsumed] > '9')\n                        {\n                            parseStatus = ParserState.Invalid;\n                            goto quit;\n                        }\n\n                        if (++bytesConsumed == effectiveMax)\n                        {\n                            string major = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);\n                            currentToken.Append(major);\n                            goto quit;\n                        }\n                    }\n\n                    if (bytesConsumed > segmentStart)\n                    {\n                        string major = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);\n                        currentToken.Append(major);\n                    }\n\n                    // Move past the \".\"\n                    currentToken.Append('.');\n                    statusLineState = HttpStatusLineState.MinorVersionNumber;\n                    if (++bytesConsumed == effectiveMax)\n                    {\n                        goto quit;\n                    }\n\n                    goto case HttpStatusLineState.MinorVersionNumber;\n\n                case HttpStatusLineState.MinorVersionNumber:\n                    segmentStart = bytesConsumed;\n                    while (buffer[bytesConsumed] != ' ')\n                    {\n                        if (buffer[bytesConsumed] < '0' || buffer[bytesConsumed] > '9')\n                        {\n                            parseStatus = ParserState.Invalid;\n                            goto quit;\n                        }\n\n                        if (++bytesConsumed == effectiveMax)\n                        {\n                            string minor = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);\n                            currentToken.Append(minor);\n                            goto quit;\n                        }\n                    }\n\n                    if (bytesConsumed > segmentStart)\n                    {\n                        string minor = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);\n                        currentToken.Append(minor);\n                    }\n\n                    // Copy out value\n                    httpResponse.Version = Version.Parse(currentToken.ToString());\n                    currentToken.Clear();\n\n                    // Move past the SP\n                    statusLineState = HttpStatusLineState.StatusCode;\n                    if (++bytesConsumed == effectiveMax)\n                    {\n                        goto quit;\n                    }\n\n                    goto case HttpStatusLineState.StatusCode;\n\n                case HttpStatusLineState.StatusCode:\n                    segmentStart = bytesConsumed;\n                    while (buffer[bytesConsumed] != ' ')\n                    {\n                        if (buffer[bytesConsumed] < '0' || buffer[bytesConsumed] > '9')\n                        {\n                            parseStatus = ParserState.Invalid;\n                            goto quit;\n                        }\n\n                        if (++bytesConsumed == effectiveMax)\n                        {\n                            string method = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);\n                            currentToken.Append(method);\n                            goto quit;\n                        }\n                    }\n\n                    if (bytesConsumed > segmentStart)\n                    {\n                        string method = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);\n                        currentToken.Append(method);\n                    }\n\n                    // Copy value out\n                    int statusCode = Int32.Parse(currentToken.ToString(), CultureInfo.InvariantCulture);\n                    if (statusCode < 100 || statusCode > 1000)\n                    {\n                        throw new FormatException(Error.Format(Properties.Resources.HttpInvalidStatusCode, statusCode, 100, 1000));\n                    }\n\n                    httpResponse.StatusCode = (HttpStatusCode)statusCode;\n                    currentToken.Clear();\n\n                    // Move past the SP\n                    statusLineState = HttpStatusLineState.ReasonPhrase;\n                    if (++bytesConsumed == effectiveMax)\n                    {\n                        goto quit;\n                    }\n\n                    goto case HttpStatusLineState.ReasonPhrase;\n\n                case HttpStatusLineState.ReasonPhrase:\n                    segmentStart = bytesConsumed;\n                    while (buffer[bytesConsumed] != '\\r')\n                    {\n                        if (buffer[bytesConsumed] < 0x20 || buffer[bytesConsumed] > 0x7a)\n                        {\n                            parseStatus = ParserState.Invalid;\n                            goto quit;\n                        }\n\n                        if (++bytesConsumed == effectiveMax)\n                        {\n                            string addr = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);\n                            currentToken.Append(addr);\n                            goto quit;\n                        }\n                    }\n\n                    if (bytesConsumed > segmentStart)\n                    {\n                        string addr = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);\n                        currentToken.Append(addr);\n                    }\n\n                    // Copy value out\n                    httpResponse.ReasonPhrase = currentToken.ToString();\n                    currentToken.Clear();\n\n                    // Move past the CR\n                    statusLineState = HttpStatusLineState.AfterCarriageReturn;\n                    if (++bytesConsumed == effectiveMax)\n                    {\n                        goto quit;\n                    }\n\n                    goto case HttpStatusLineState.AfterCarriageReturn;\n\n                case HttpStatusLineState.AfterCarriageReturn:\n                    if (buffer[bytesConsumed] != '\\n')\n                    {\n                        parseStatus = ParserState.Invalid;\n                        goto quit;\n                    }\n\n                    parseStatus = ParserState.Done;\n                    bytesConsumed++;\n                    break;\n            }\n\n        quit:\n            totalBytesConsumed += bytesConsumed - initialBytesParsed;\n            return parseStatus;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/Parsers/InternetMessageFormatHeaderParser.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Net.Http.Headers;\nusing System.Text;\nusing System.Web.Http;\n\nnamespace System.Net.Http.Formatting.Parsers\n{\n    /// <summary>\n    /// Buffer-oriented RFC 5322 style Internet Message Format parser which can be used to pass header\n    /// fields used in HTTP and MIME message entities.\n    /// </summary>\n    internal class InternetMessageFormatHeaderParser\n    {\n        internal const int MinHeaderSize = 2;\n\n        private int _totalBytesConsumed;\n        private int _maxHeaderSize;\n\n        private HeaderFieldState _headerState;\n        private HttpHeaders _headers;\n        private CurrentHeaderFieldStore _currentHeader;\n        private readonly bool _ignoreHeaderValidation;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"InternetMessageFormatHeaderParser\"/> class.\n        /// </summary>\n        /// <param name=\"headers\">Concrete <see cref=\"HttpHeaders\"/> instance where header fields are added as they are parsed.</param>\n        /// <param name=\"maxHeaderSize\">Maximum length of complete header containing all the individual header fields.</param>\n        public InternetMessageFormatHeaderParser(HttpHeaders headers, int maxHeaderSize)\n            : this(headers, maxHeaderSize, ignoreHeaderValidation: false)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"InternetMessageFormatHeaderParser\"/> class.\n        /// </summary>\n        /// <param name=\"headers\">\n        /// Concrete <see cref=\"HttpHeaders\"/> instance where header fields are added as they are parsed.\n        /// </param>\n        /// <param name=\"maxHeaderSize\">\n        /// Maximum length of complete header containing all the individual header fields.\n        /// </param>\n        /// <param name=\"ignoreHeaderValidation\">\n        /// Will validate content and names of headers if set to <c>false</c>.\n        /// </param>\n        public InternetMessageFormatHeaderParser(HttpHeaders headers, int maxHeaderSize, bool ignoreHeaderValidation)\n        {\n            // The minimum length which would be an empty header terminated by CRLF\n            if (maxHeaderSize < InternetMessageFormatHeaderParser.MinHeaderSize)\n            {\n                throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"maxHeaderSize\", maxHeaderSize, MinHeaderSize);\n            }\n\n            if (headers == null)\n            {\n                throw Error.ArgumentNull(\"headers\");\n            }\n\n            _headers = headers;\n            _maxHeaderSize = maxHeaderSize;\n            _ignoreHeaderValidation = ignoreHeaderValidation;\n            _currentHeader = new CurrentHeaderFieldStore();\n        }\n\n        private enum HeaderFieldState\n        {\n            Name = 0,\n            Value,\n            AfterCarriageReturn,\n            FoldingLine\n        }\n\n        /// <summary>\n        /// Parse a buffer of RFC 5322 style header fields and add them to the <see cref=\"HttpHeaders\"/> collection.\n        /// Bytes are parsed in a consuming manner from the beginning of the buffer meaning that the same bytes can not be\n        /// present in the buffer.\n        /// </summary>\n        /// <param name=\"buffer\">Request buffer from where request is read</param>\n        /// <param name=\"bytesReady\">Size of request buffer</param>\n        /// <param name=\"bytesConsumed\">Offset into request buffer</param>\n        /// <returns>State of the parser. Call this method with new data until it reaches a final state.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Exception is translated to parse state.\")]\n        public ParserState ParseBuffer(\n            byte[] buffer,\n            int bytesReady,\n            ref int bytesConsumed)\n        {\n            if (buffer == null)\n            {\n                throw Error.ArgumentNull(\"buffer\");\n            }\n\n            ParserState parseStatus = ParserState.NeedMoreData;\n\n            if (bytesConsumed >= bytesReady)\n            {\n                // We already can tell we need more data\n                return parseStatus;\n            }\n\n            try\n            {\n                parseStatus = InternetMessageFormatHeaderParser.ParseHeaderFields(\n                    buffer,\n                    bytesReady,\n                    ref bytesConsumed,\n                    ref _headerState,\n                    _maxHeaderSize,\n                    ref _totalBytesConsumed,\n                    _currentHeader,\n                    _headers,\n                    _ignoreHeaderValidation);\n            }\n            catch (Exception)\n            {\n                parseStatus = ParserState.Invalid;\n            }\n\n            return parseStatus;\n        }\n\n        [SuppressMessage(\"Microsoft.Maintainability\", \"CA1502:AvoidExcessiveComplexity\", Justification = \"This is a parser which cannot be split up for performance reasons.\")]\n        private static ParserState ParseHeaderFields(\n            byte[] buffer,\n            int bytesReady,\n            ref int bytesConsumed,\n            ref HeaderFieldState requestHeaderState,\n            int maximumHeaderLength,\n            ref int totalBytesConsumed,\n            CurrentHeaderFieldStore currentField,\n            HttpHeaders headers,\n            bool ignoreHeaderValidation)\n        {\n            Contract.Assert((bytesReady - bytesConsumed) >= 0, \"ParseHeaderFields()|(inputBufferLength - bytesParsed) < 0\");\n            Contract.Assert(maximumHeaderLength <= 0 || totalBytesConsumed <= maximumHeaderLength, \"ParseHeaderFields()|Headers already read exceeds limit.\");\n\n            // Remember where we started.\n            int initialBytesParsed = bytesConsumed;\n            int segmentStart;\n\n            // Set up parsing status with what will happen if we exceed the buffer.\n            ParserState parseStatus = ParserState.DataTooBig;\n            int effectiveMax = maximumHeaderLength <= 0 ? Int32.MaxValue : maximumHeaderLength - totalBytesConsumed + initialBytesParsed;\n            if (bytesReady < effectiveMax)\n            {\n                parseStatus = ParserState.NeedMoreData;\n                effectiveMax = bytesReady;\n            }\n\n            Contract.Assert(bytesConsumed < effectiveMax, \"We have already consumed more than the max header length.\");\n\n            switch (requestHeaderState)\n            {\n                case HeaderFieldState.Name:\n                    segmentStart = bytesConsumed;\n                    while (buffer[bytesConsumed] != ':')\n                    {\n                        if (buffer[bytesConsumed] == '\\r')\n                        {\n                            if (!currentField.IsEmpty())\n                            {\n                                parseStatus = ParserState.Invalid;\n                                goto quit;\n                            }\n                            else\n                            {\n                                // Move past the '\\r'\n                                requestHeaderState = HeaderFieldState.AfterCarriageReturn;\n                                if (++bytesConsumed == effectiveMax)\n                                {\n                                    goto quit;\n                                }\n\n                                goto case HeaderFieldState.AfterCarriageReturn;\n                            }\n                        }\n\n                        if (++bytesConsumed == effectiveMax)\n                        {\n                            string headerFieldName = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);\n                            currentField.Name.Append(headerFieldName);\n                            goto quit;\n                        }\n                    }\n\n                    if (bytesConsumed > segmentStart)\n                    {\n                        string headerFieldName = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);\n                        currentField.Name.Append(headerFieldName);\n                    }\n\n                    // Move past the ':'\n                    requestHeaderState = HeaderFieldState.Value;\n                    if (++bytesConsumed == effectiveMax)\n                    {\n                        goto quit;\n                    }\n\n                    goto case HeaderFieldState.Value;\n\n                case HeaderFieldState.Value:\n                    segmentStart = bytesConsumed;\n                    while (buffer[bytesConsumed] != '\\r')\n                    {\n                        if (++bytesConsumed == effectiveMax)\n                        {\n                            string headerFieldValue = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);\n                            currentField.Value.Append(headerFieldValue);\n                            goto quit;\n                        }\n                    }\n\n                    if (bytesConsumed > segmentStart)\n                    {\n                        string headerFieldValue = Encoding.UTF8.GetString(buffer, segmentStart, bytesConsumed - segmentStart);\n                        currentField.Value.Append(headerFieldValue);\n                    }\n\n                    // Move past the CR\n                    requestHeaderState = HeaderFieldState.AfterCarriageReturn;\n                    if (++bytesConsumed == effectiveMax)\n                    {\n                        goto quit;\n                    }\n\n                    goto case HeaderFieldState.AfterCarriageReturn;\n\n                case HeaderFieldState.AfterCarriageReturn:\n                    if (buffer[bytesConsumed] != '\\n')\n                    {\n                        parseStatus = ParserState.Invalid;\n                        goto quit;\n                    }\n\n                    if (currentField.IsEmpty())\n                    {\n                        parseStatus = ParserState.Done;\n                        bytesConsumed++;\n                        goto quit;\n                    }\n\n                    requestHeaderState = HeaderFieldState.FoldingLine;\n                    if (++bytesConsumed == effectiveMax)\n                    {\n                        goto quit;\n                    }\n\n                    goto case HeaderFieldState.FoldingLine;\n\n                case HeaderFieldState.FoldingLine:\n                    if (buffer[bytesConsumed] != ' ' && buffer[bytesConsumed] != '\\t')\n                    {\n                        currentField.CopyTo(headers, ignoreHeaderValidation);\n                        requestHeaderState = HeaderFieldState.Name;\n                        if (bytesConsumed == effectiveMax)\n                        {\n                            goto quit;\n                        }\n\n                        goto case HeaderFieldState.Name;\n                    }\n\n                    // Unfold line by inserting SP instead\n                    currentField.Value.Append(' ');\n\n                    // Continue parsing header field value\n                    requestHeaderState = HeaderFieldState.Value;\n                    if (++bytesConsumed == effectiveMax)\n                    {\n                        goto quit;\n                    }\n\n                    goto case HeaderFieldState.Value;\n            }\n\n        quit:\n            totalBytesConsumed += bytesConsumed - initialBytesParsed;\n            return parseStatus;\n        }\n\n        /// <summary>\n        /// Maintains information about the current header field being parsed.\n        /// </summary>\n        private class CurrentHeaderFieldStore\n        {\n            private const int DefaultFieldNameAllocation = 128;\n            private const int DefaultFieldValueAllocation = 2 * 1024;\n\n            private static readonly char[] _linearWhiteSpace = new char[] { ' ', '\\t' };\n\n            private readonly StringBuilder _name = new StringBuilder(CurrentHeaderFieldStore.DefaultFieldNameAllocation);\n            private readonly StringBuilder _value = new StringBuilder(CurrentHeaderFieldStore.DefaultFieldValueAllocation);\n\n            /// <summary>\n            /// Gets the header field name.\n            /// </summary>\n            public StringBuilder Name\n            {\n                get { return _name; }\n            }\n\n            /// <summary>\n            /// Gets the header field value.\n            /// </summary>\n            public StringBuilder Value\n            {\n                get { return _value; }\n            }\n\n            /// <summary>\n            /// Copies current header field to the provided <see cref=\"HttpHeaders\"/> instance.\n            /// </summary>\n            /// <param name=\"headers\">The headers.</param>\n            /// <param name=\"ignoreHeaderValidation\">Set to false to validate headers</param>\n            public void CopyTo(HttpHeaders headers, bool ignoreHeaderValidation)\n            {\n                var name = _name.ToString();\n                var value = _value.ToString().Trim(CurrentHeaderFieldStore._linearWhiteSpace);\n                if (string.Equals(\"expires\", name, StringComparison.OrdinalIgnoreCase))\n                {\n                    ignoreHeaderValidation = true;\n                }\n\n                if (ignoreHeaderValidation)\n                {\n                    headers.TryAddWithoutValidation(name, value);\n                }\n                else\n                {\n                    headers.Add(name, value);\n                }\n\n                Clear();\n            }\n\n            /// <summary>\n            /// Determines whether this instance is empty.\n            /// </summary>\n            /// <returns>\n            ///   <c>true</c> if this instance is empty; otherwise, <c>false</c>.\n            /// </returns>\n            public bool IsEmpty()\n            {\n                return _name.Length == 0 && _value.Length == 0;\n            }\n\n            /// <summary>\n            /// Clears this instance.\n            /// </summary>\n            private void Clear()\n            {\n                _name.Clear();\n                _value.Clear();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/Parsers/MimeMultipartBodyPartParser.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.IO;\nusing System.Net.Http.Headers;\nusing System.Web.Http;\n\nnamespace System.Net.Http.Formatting.Parsers\n{\n    /// <summary>\n    /// Complete MIME multipart parser that combines <see cref=\"MimeMultipartParser\"/> for parsing the MIME message into individual body parts\n    /// and <see cref=\"InternetMessageFormatHeaderParser\"/> for parsing each body part into a MIME header and a MIME body. The caller of the parser is returned\n    /// the resulting MIME bodies which can then be written to some output.\n    /// </summary>\n    internal class MimeMultipartBodyPartParser : IDisposable\n    {\n        internal const long DefaultMaxMessageSize = Int64.MaxValue;\n        private const int DefaultMaxBodyPartHeaderSize = 4 * 1024;\n\n        // MIME parser\n        private MimeMultipartParser _mimeParser;\n        private MimeMultipartParser.State _mimeStatus = MimeMultipartParser.State.NeedMoreData;\n        private ArraySegment<byte>[] _parsedBodyPart = new ArraySegment<byte>[2];\n        private MimeBodyPart _currentBodyPart;\n        private bool _isFirst = true;\n\n        // Header field parser\n        private ParserState _bodyPartHeaderStatus = ParserState.NeedMoreData;\n        private int _maxBodyPartHeaderSize;\n\n        // Stream provider\n        private MultipartStreamProvider _streamProvider;\n\n        private HttpContent _content;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"MimeMultipartBodyPartParser\"/> class.\n        /// </summary>\n        /// <param name=\"content\">An existing <see cref=\"HttpContent\"/> instance to use for the object's content.</param>\n        /// <param name=\"streamProvider\">A stream provider providing output streams for where to write body parts as they are parsed.</param>\n        public MimeMultipartBodyPartParser(HttpContent content, MultipartStreamProvider streamProvider)\n            : this(content, streamProvider, DefaultMaxMessageSize, DefaultMaxBodyPartHeaderSize)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"MimeMultipartBodyPartParser\"/> class.\n        /// </summary>\n        /// <param name=\"content\">An existing <see cref=\"HttpContent\"/> instance to use for the object's content.</param>\n        /// <param name=\"streamProvider\">A stream provider providing output streams for where to write body parts as they are parsed.</param>\n        /// <param name=\"maxMessageSize\">The max length of the entire MIME multipart message.</param>\n        /// <param name=\"maxBodyPartHeaderSize\">The max length of the MIME header within each MIME body part.</param>\n        public MimeMultipartBodyPartParser(\n            HttpContent content,\n            MultipartStreamProvider streamProvider,\n            long maxMessageSize,\n            int maxBodyPartHeaderSize)\n        {\n            Contract.Assert(content != null, \"content cannot be null.\");\n            Contract.Assert(streamProvider != null, \"streamProvider cannot be null.\");\n\n            string boundary = ValidateArguments(content, maxMessageSize, true);\n\n            _mimeParser = new MimeMultipartParser(boundary, maxMessageSize);\n            _currentBodyPart = new MimeBodyPart(streamProvider, maxBodyPartHeaderSize, content);\n            _content = content;\n            _maxBodyPartHeaderSize = maxBodyPartHeaderSize;\n\n            _streamProvider = streamProvider;\n        }\n\n        /// <summary>\n        /// Determines whether the specified content is MIME multipart content.\n        /// </summary>\n        /// <param name=\"content\">The content.</param>\n        /// <returns>\n        ///   <c>true</c> if the specified content is MIME multipart content; otherwise, <c>false</c>.\n        /// </returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Exception is translated to false return.\")]\n        public static bool IsMimeMultipartContent(HttpContent content)\n        {\n            Contract.Assert(content != null, \"content cannot be null.\");\n            try\n            {\n                string boundary = ValidateArguments(content, DefaultMaxMessageSize, false);\n                return boundary != null;\n            }\n            catch (Exception)\n            {\n                return false;\n            }\n        }\n\n        /// <summary>\n        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.\n        /// </summary>\n        public void Dispose()\n        {\n            Dispose(true);\n            GC.SuppressFinalize(this);\n        }\n\n        /// <summary>\n        /// Parses the data provided and generates parsed MIME body part bodies in the form of <see cref=\"ArraySegment{T}\"/> which are ready to\n        /// write to the output stream.\n        /// </summary>\n        /// <param name=\"data\">The data to parse</param>\n        /// <param name=\"bytesRead\">The number of bytes available in the input data</param>\n        /// <returns>Parsed <see cref=\"MimeBodyPart\"/> instances.</returns>\n        public IEnumerable<MimeBodyPart> ParseBuffer(byte[] data, int bytesRead)\n        {\n            int bytesConsumed = 0;\n            bool isFinal = false;\n\n            // There's a special case here - if we've reached the end of the message and there's no optional\n            // CRLF, then we're out of bytes to read, but we have finished the message.\n            //\n            // If IsWaitingForEndOfMessage is true and we're at the end of the stream, then we're going to\n            // call into the parser again with an empty array as the buffer to signal the end of the parse.\n            // Then the final boundary segment will be marked as complete.\n            if (bytesRead == 0 && !_mimeParser.IsWaitingForEndOfMessage)\n            {\n                CleanupCurrentBodyPart();\n                throw new IOException(Properties.Resources.ReadAsMimeMultipartUnexpectedTermination);\n            }\n\n            // Make sure we remove an old array segments.\n            _currentBodyPart.Segments.Clear();\n\n            while (_mimeParser.CanParseMore(bytesRead, bytesConsumed))\n            {\n                _mimeStatus = _mimeParser.ParseBuffer(data, bytesRead, ref bytesConsumed, out _parsedBodyPart[0], out _parsedBodyPart[1], out isFinal);\n                if (_mimeStatus != MimeMultipartParser.State.BodyPartCompleted && _mimeStatus != MimeMultipartParser.State.NeedMoreData)\n                {\n                    CleanupCurrentBodyPart();\n                    throw Error.InvalidOperation(Properties.Resources.ReadAsMimeMultipartParseError, bytesConsumed, data);\n                }\n\n                // First body is empty preamble which we just ignore\n                if (_isFirst)\n                {\n                    if (_mimeStatus == MimeMultipartParser.State.BodyPartCompleted)\n                    {\n                        _isFirst = false;\n                    }\n\n                    continue;\n                }\n\n                // Parse the two array segments containing parsed body parts that the MIME parser gave us\n                foreach (ArraySegment<byte> part in _parsedBodyPart)\n                {\n                    if (part.Count == 0)\n                    {\n                        continue;\n                    }\n\n                    if (_bodyPartHeaderStatus != ParserState.Done)\n                    {\n                        int headerConsumed = part.Offset;\n                        _bodyPartHeaderStatus = _currentBodyPart.HeaderParser.ParseBuffer(part.Array, part.Count + part.Offset, ref headerConsumed);\n                        if (_bodyPartHeaderStatus == ParserState.Done)\n                        {\n                            // Add the remainder as body part content\n                            _currentBodyPart.Segments.Add(new ArraySegment<byte>(part.Array, headerConsumed, part.Count + part.Offset - headerConsumed));\n                        }\n                        else if (_bodyPartHeaderStatus != ParserState.NeedMoreData)\n                        {\n                            CleanupCurrentBodyPart();\n                            throw Error.InvalidOperation(Properties.Resources.ReadAsMimeMultipartHeaderParseError, headerConsumed, part.Array);\n                        }\n                    }\n                    else\n                    {\n                        // Add the data as body part content\n                        _currentBodyPart.Segments.Add(part);\n                    }\n                }\n\n                if (_mimeStatus == MimeMultipartParser.State.BodyPartCompleted)\n                {\n                    // If body is completed then swap current body part\n                    MimeBodyPart completed = _currentBodyPart;\n                    completed.IsComplete = true;\n                    completed.IsFinal = isFinal;\n\n                    _currentBodyPart = new MimeBodyPart(_streamProvider, _maxBodyPartHeaderSize, _content);\n\n                    _mimeStatus = MimeMultipartParser.State.NeedMoreData;\n                    _bodyPartHeaderStatus = ParserState.NeedMoreData;\n                    yield return completed;\n                }\n                else\n                {\n                    // Otherwise return what we have\n                    yield return _currentBodyPart;\n                }\n            }\n        }\n\n        /// <summary>\n        /// Releases unmanaged and - optionally - managed resources\n        /// </summary>\n        /// <param name=\"disposing\"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>\n        protected void Dispose(bool disposing)\n        {\n            if (disposing)\n            {\n                _mimeParser = null;\n                CleanupCurrentBodyPart();\n            }\n        }\n\n        private static string ValidateArguments(HttpContent content, long maxMessageSize, bool throwOnError)\n        {\n            Contract.Assert(content != null, \"content cannot be null.\");\n            if (maxMessageSize < MimeMultipartParser.MinMessageSize)\n            {\n                if (throwOnError)\n                {\n                    throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"maxMessageSize\", maxMessageSize, MimeMultipartParser.MinMessageSize);\n                }\n                else\n                {\n                    return null;\n                }\n            }\n\n            MediaTypeHeaderValue contentType = content.Headers.ContentType;\n            if (contentType == null)\n            {\n                if (throwOnError)\n                {\n                    throw Error.Argument(\"content\", Properties.Resources.ReadAsMimeMultipartArgumentNoContentType, typeof(HttpContent).Name, \"multipart/\");\n                }\n                else\n                {\n                    return null;\n                }\n            }\n\n            if (!contentType.MediaType.StartsWith(\"multipart\", StringComparison.OrdinalIgnoreCase))\n            {\n                if (throwOnError)\n                {\n                    throw Error.Argument(\"content\", Properties.Resources.ReadAsMimeMultipartArgumentNoMultipart, typeof(HttpContent).Name, \"multipart/\");\n                }\n                else\n                {\n                    return null;\n                }\n            }\n\n            string boundary = null;\n            foreach (NameValueHeaderValue p in contentType.Parameters)\n            {\n                if (p.Name.Equals(\"boundary\", StringComparison.OrdinalIgnoreCase))\n                {\n                    boundary = FormattingUtilities.UnquoteToken(p.Value);\n                    break;\n                }\n            }\n\n            if (boundary == null)\n            {\n                if (throwOnError)\n                {\n                    throw Error.Argument(\"content\", Properties.Resources.ReadAsMimeMultipartArgumentNoBoundary, typeof(HttpContent).Name, \"multipart\", \"boundary\");\n                }\n                else\n                {\n                    return null;\n                }\n            }\n\n            return boundary;\n        }\n\n        private void CleanupCurrentBodyPart()\n        {\n            if (_currentBodyPart != null)\n            {\n                _currentBodyPart.Dispose();\n                _currentBodyPart = null;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/Parsers/MimeMultipartParser.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Text;\nusing System.Web.Http;\n\nnamespace System.Net.Http.Formatting.Parsers\n{\n    /// <summary>\n    /// Buffer-oriented MIME multipart parser.\n    /// </summary>\n    internal class MimeMultipartParser\n    {\n        internal const int MinMessageSize = 10;\n\n        private const int MaxBoundarySize = 256;\n\n        private const byte HTAB = 0x09;\n        private const byte SP = 0x20;\n        private const byte CR = 0x0D;\n        private const byte LF = 0x0A;\n        private const byte Dash = 0x2D;\n        private static readonly ArraySegment<byte> _emptyBodyPart = new ArraySegment<byte>(new byte[0]);\n\n        private long _totalBytesConsumed;\n        private long _maxMessageSize;\n\n        private BodyPartState _bodyPartState;\n        private string _boundary;\n        private CurrentBodyPartStore _currentBoundary;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"MimeMultipartParser\"/> class.\n        /// </summary>\n        /// <param name=\"boundary\">Message boundary</param>\n        /// <param name=\"maxMessageSize\">Maximum length of entire MIME multipart message.</param>\n        public MimeMultipartParser(string boundary, long maxMessageSize)\n        {\n            // The minimum length which would be an empty message terminated by CRLF\n            if (maxMessageSize < MimeMultipartParser.MinMessageSize)\n            {\n                throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"maxMessageSize\", maxMessageSize, MinMessageSize);\n            }\n\n            if (String.IsNullOrWhiteSpace(boundary))\n            {\n                throw Error.ArgumentNull(\"boundary\");\n            }\n\n            if (boundary.Length > MaxBoundarySize - 10)\n            {\n                throw Error.ArgumentMustBeLessThanOrEqualTo(\"boundary\", boundary.Length, MaxBoundarySize - 10);\n            }\n\n            if (boundary.EndsWith(\" \", StringComparison.Ordinal))\n            {\n                throw Error.Argument(\"boundary\", Properties.Resources.MimeMultipartParserBadBoundary);\n            }\n\n            _maxMessageSize = maxMessageSize;\n            _boundary = boundary;\n            _currentBoundary = new CurrentBodyPartStore(_boundary);\n            _bodyPartState = BodyPartState.AfterFirstLineFeed;\n        }\n\n        public bool IsWaitingForEndOfMessage\n        {\n            get\n            {\n                return\n                    _bodyPartState == BodyPartState.AfterBoundary &&\n                    _currentBoundary != null &&\n                    _currentBoundary.IsFinal;\n            }\n        }\n\n        private enum BodyPartState\n        {\n            BodyPart = 0,\n            AfterFirstCarriageReturn,\n            AfterFirstLineFeed,\n            AfterFirstDash,\n            Boundary,\n            AfterBoundary,\n            AfterSecondDash,\n            AfterSecondCarriageReturn\n        }\n\n        private enum MessageState\n        {\n            Boundary = 0, // about to parse boundary\n            BodyPart, // about to parse body-part\n            CloseDelimiter // about to read close-delimiter\n        }\n\n        /// <summary>\n        /// Represents the overall state of the <see cref=\"MimeMultipartParser\"/>.\n        /// </summary>\n        public enum State\n        {\n            /// <summary>\n            /// Need more data\n            /// </summary>\n            NeedMoreData = 0,\n\n            /// <summary>\n            /// Parsing of a complete body part succeeded.\n            /// </summary>\n            BodyPartCompleted,\n\n            /// <summary>\n            /// Bad data format\n            /// </summary>\n            Invalid,\n\n            /// <summary>\n            /// Data exceeds the allowed size\n            /// </summary>\n            DataTooBig,\n        }\n\n        public bool CanParseMore(int bytesRead, int bytesConsumed)\n        {\n            if (bytesConsumed < bytesRead)\n            {\n                // If there's more bytes we haven't parsed, then we can parse more\n                return true;\n            }\n\n            if (bytesRead == 0 && IsWaitingForEndOfMessage)\n            {\n                // If we're waiting for the end of the message and we've arrived there, we want parse to be called\n                // again so we can mark the parse as complete.\n                //\n                // This can happen when the last boundary segment doesn't have a trailing CRLF. We need to wait until\n                // the end of the message to complete the parse because we need to consume any trailing whitespace that's\n                //present.\n                return true;\n            }\n\n            return false;\n        }\n\n        /// <summary>\n        /// Parse a MIME multipart message. Bytes are parsed in a consuming\n        /// manner from the beginning of the request buffer meaning that the same bytes can not be\n        /// present in the request buffer.\n        /// </summary>\n        /// <param name=\"buffer\">Request buffer from where request is read</param>\n        /// <param name=\"bytesReady\">Size of request buffer</param>\n        /// <param name=\"bytesConsumed\">Offset into request buffer</param>\n        /// <param name=\"remainingBodyPart\">Any body part that was considered as a potential MIME multipart boundary but which was in fact part of the body.</param>\n        /// <param name=\"bodyPart\">The bulk of the body part.</param>\n        /// <param name=\"isFinalBodyPart\">Indicates whether the final body part has been found.</param>\n        /// <remarks>In order to get the complete body part, the caller is responsible for concatenating the contents of the\n        /// <paramref name=\"remainingBodyPart\"/> and <paramref name=\"bodyPart\"/> out parameters.</remarks>\n        /// <returns>State of the parser.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Exception is translated to parse state.\")]\n        public State ParseBuffer(\n            byte[] buffer,\n            int bytesReady,\n            ref int bytesConsumed,\n            out ArraySegment<byte> remainingBodyPart,\n            out ArraySegment<byte> bodyPart,\n            out bool isFinalBodyPart)\n        {\n            if (buffer == null)\n            {\n                throw Error.ArgumentNull(\"buffer\");\n            }\n\n            State parseStatus = State.NeedMoreData;\n            remainingBodyPart = MimeMultipartParser._emptyBodyPart;\n            bodyPart = MimeMultipartParser._emptyBodyPart;\n            isFinalBodyPart = false;\n\n            try\n            {\n                parseStatus = MimeMultipartParser.ParseBodyPart(\n                    buffer,\n                    bytesReady,\n                    ref bytesConsumed,\n                    ref _bodyPartState,\n                    _maxMessageSize,\n                    ref _totalBytesConsumed,\n                    _currentBoundary);\n            }\n            catch (Exception)\n            {\n                parseStatus = State.Invalid;\n            }\n\n            remainingBodyPart = _currentBoundary.GetDiscardedBoundary();\n            bodyPart = _currentBoundary.BodyPart;\n            if (parseStatus == State.BodyPartCompleted)\n            {\n                isFinalBodyPart = _currentBoundary.IsFinal;\n                _currentBoundary.ClearAll();\n            }\n            else\n            {\n                _currentBoundary.ClearBodyPart();\n            }\n\n            return parseStatus;\n        }\n\n        [SuppressMessage(\"Microsoft.Maintainability\", \"CA1502:AvoidExcessiveComplexity\", Justification = \"This is a parser which cannot be split up for performance reasons.\")]\n        private static State ParseBodyPart(\n            byte[] buffer,\n            int bytesReady,\n            ref int bytesConsumed,\n            ref BodyPartState bodyPartState,\n            long maximumMessageLength,\n            ref long totalBytesConsumed,\n            CurrentBodyPartStore currentBodyPart)\n        {\n            Contract.Assert((bytesReady - bytesConsumed) >= 0, \"ParseBodyPart()|(bytesReady - bytesConsumed) < 0\");\n            Contract.Assert(maximumMessageLength <= 0 || totalBytesConsumed <= maximumMessageLength, \"ParseBodyPart()|Message already read exceeds limit.\");\n\n            // Remember where we started.\n            int segmentStart;\n            int initialBytesParsed = bytesConsumed;\n\n            if (bytesReady == 0 && bodyPartState == BodyPartState.AfterBoundary && currentBodyPart.IsFinal)\n            {\n                // We've seen the end of the stream - the final body part has no trailing CRLF\n                return State.BodyPartCompleted;\n            }\n\n            // Set up parsing status with what will happen if we exceed the buffer.\n            State parseStatus = State.DataTooBig;\n            long effectiveMax = maximumMessageLength <= 0 ? Int64.MaxValue : (maximumMessageLength - totalBytesConsumed + bytesConsumed);\n            if (effectiveMax == 0)\n            {\n                // effectiveMax is based on our max message size - if we've arrrived at the max size, then we need\n                // to stop parsing.\n                return State.DataTooBig;\n            }\n\n            if (bytesReady <= effectiveMax)\n            {\n                parseStatus = State.NeedMoreData;\n                effectiveMax = bytesReady;\n            }\n\n            currentBodyPart.ResetBoundaryOffset();\n\n            Contract.Assert(bytesConsumed < effectiveMax, \"We have already consumed more than the max header length.\");\n\n            switch (bodyPartState)\n            {\n                case BodyPartState.BodyPart:\n                    while (buffer[bytesConsumed] != MimeMultipartParser.CR)\n                    {\n                        if (++bytesConsumed == effectiveMax)\n                        {\n                            goto quit;\n                        }\n                    }\n\n                    // Remember potential boundary\n                    currentBodyPart.AppendBoundary(MimeMultipartParser.CR);\n\n                    // Move past the CR\n                    bodyPartState = BodyPartState.AfterFirstCarriageReturn;\n                    if (++bytesConsumed == effectiveMax)\n                    {\n                        goto quit;\n                    }\n\n                    goto case BodyPartState.AfterFirstCarriageReturn;\n\n                case BodyPartState.AfterFirstCarriageReturn:\n                    if (buffer[bytesConsumed] != MimeMultipartParser.LF)\n                    {\n                        currentBodyPart.ResetBoundary();\n                        bodyPartState = BodyPartState.BodyPart;\n                        goto case BodyPartState.BodyPart;\n                    }\n\n                    // Remember potential boundary\n                    currentBodyPart.AppendBoundary(MimeMultipartParser.LF);\n\n                    // Move past the CR\n                    bodyPartState = BodyPartState.AfterFirstLineFeed;\n                    if (++bytesConsumed == effectiveMax)\n                    {\n                        goto quit;\n                    }\n\n                    goto case BodyPartState.AfterFirstLineFeed;\n\n                case BodyPartState.AfterFirstLineFeed:\n                    if (buffer[bytesConsumed] == MimeMultipartParser.CR)\n                    {\n                        // Remember potential boundary\n                        currentBodyPart.ResetBoundary();\n                        currentBodyPart.AppendBoundary(MimeMultipartParser.CR);\n\n                        // Move past the CR\n                        bodyPartState = BodyPartState.AfterFirstCarriageReturn;\n                        if (++bytesConsumed == effectiveMax)\n                        {\n                            goto quit;\n                        }\n\n                        goto case BodyPartState.AfterFirstCarriageReturn;\n                    }\n\n                    if (buffer[bytesConsumed] != MimeMultipartParser.Dash)\n                    {\n                        currentBodyPart.ResetBoundary();\n                        bodyPartState = BodyPartState.BodyPart;\n                        goto case BodyPartState.BodyPart;\n                    }\n\n                    // Remember potential boundary\n                    currentBodyPart.AppendBoundary(MimeMultipartParser.Dash);\n\n                    // Move past the Dash\n                    bodyPartState = BodyPartState.AfterFirstDash;\n                    if (++bytesConsumed == effectiveMax)\n                    {\n                        goto quit;\n                    }\n\n                    goto case BodyPartState.AfterFirstDash;\n\n                case BodyPartState.AfterFirstDash:\n                    if (buffer[bytesConsumed] != MimeMultipartParser.Dash)\n                    {\n                        currentBodyPart.ResetBoundary();\n                        bodyPartState = BodyPartState.BodyPart;\n                        goto case BodyPartState.BodyPart;\n                    }\n\n                    // Remember potential boundary\n                    currentBodyPart.AppendBoundary(MimeMultipartParser.Dash);\n\n                    // Move past the Dash\n                    bodyPartState = BodyPartState.Boundary;\n                    if (++bytesConsumed == effectiveMax)\n                    {\n                        goto quit;\n                    }\n\n                    goto case BodyPartState.Boundary;\n\n                case BodyPartState.Boundary:\n                    segmentStart = bytesConsumed;\n                    while (buffer[bytesConsumed] != MimeMultipartParser.CR)\n                    {\n                        if (++bytesConsumed == effectiveMax)\n                        {\n                            if (currentBodyPart.AppendBoundary(buffer, segmentStart, bytesConsumed - segmentStart))\n                            {\n                                if (currentBodyPart.IsBoundaryComplete())\n                                {\n                                    // At this point we've seen the end of a boundary segment that is aligned at the end\n                                    // of the buffer - this might be because we have another segment coming or it might\n                                    // truly be the end of the message.\n                                    bodyPartState = BodyPartState.AfterBoundary;\n                                }\n                            }\n                            else\n                            {\n                                currentBodyPart.ResetBoundary();\n                                bodyPartState = BodyPartState.BodyPart;\n                            }\n                            goto quit;\n                        }\n                    }\n\n                    if (bytesConsumed > segmentStart)\n                    {\n                        if (!currentBodyPart.AppendBoundary(buffer, segmentStart, bytesConsumed - segmentStart))\n                        {\n                            currentBodyPart.ResetBoundary();\n                            bodyPartState = BodyPartState.BodyPart;\n                            goto case BodyPartState.BodyPart;\n                        }\n                    }\n\n                    goto case BodyPartState.AfterBoundary;\n\n                case BodyPartState.AfterBoundary:\n\n                    // This state means that we just saw the end of a boundary. It might by a 'normal' boundary, in which\n                    // case it's followed by optional whitespace and a CRLF. Or it might be the 'final' boundary and will\n                    // be followed by '--', optional whitespace and an optional CRLF.\n                    if (buffer[bytesConsumed] == MimeMultipartParser.Dash && !currentBodyPart.IsFinal)\n                    {\n                        currentBodyPart.AppendBoundary(MimeMultipartParser.Dash);\n                        if (++bytesConsumed == effectiveMax)\n                        {\n                            bodyPartState = BodyPartState.AfterSecondDash;\n                            goto quit;\n                        }\n\n                        goto case BodyPartState.AfterSecondDash;\n                    }\n\n                    // Capture optional whitespace\n                    segmentStart = bytesConsumed;\n                    while (buffer[bytesConsumed] != MimeMultipartParser.CR)\n                    {\n                        if (++bytesConsumed == effectiveMax)\n                        {\n                            if (!currentBodyPart.AppendBoundary(buffer, segmentStart, bytesConsumed - segmentStart))\n                            {\n                                // It's an unexpected character\n                                currentBodyPart.ResetBoundary();\n                                bodyPartState = BodyPartState.BodyPart;\n                            }\n\n                            goto quit;\n                        }\n                    }\n\n                    if (bytesConsumed > segmentStart)\n                    {\n                        if (!currentBodyPart.AppendBoundary(buffer, segmentStart, bytesConsumed - segmentStart))\n                        {\n                            currentBodyPart.ResetBoundary();\n                            bodyPartState = BodyPartState.BodyPart;\n                            goto case BodyPartState.BodyPart;\n                        }\n                    }\n\n                    if (buffer[bytesConsumed] == MimeMultipartParser.CR)\n                    {\n                        currentBodyPart.AppendBoundary(MimeMultipartParser.CR);\n                        if (++bytesConsumed == effectiveMax)\n                        {\n                            bodyPartState = BodyPartState.AfterSecondCarriageReturn;\n                            goto quit;\n                        }\n\n                        goto case BodyPartState.AfterSecondCarriageReturn;\n                    }\n                    else\n                    {\n                        // It's an unexpected character\n                        currentBodyPart.ResetBoundary();\n                        bodyPartState = BodyPartState.BodyPart;\n                        goto case BodyPartState.BodyPart;\n                    }\n\n                case BodyPartState.AfterSecondDash:\n                    if (buffer[bytesConsumed] == MimeMultipartParser.Dash)\n                    {\n                        currentBodyPart.AppendBoundary(MimeMultipartParser.Dash);\n                        bytesConsumed++;\n\n                        if (currentBodyPart.IsBoundaryComplete())\n                        {\n                            Debug.Assert(currentBodyPart.IsFinal);\n\n                            // If we get in here, it means we've see the trailing '--' of the last boundary - in order to consume all of the\n                            // remaining bytes, we don't mark the parse as complete again - wait until this method is called again with the\n                            // empty buffer to do that.\n                            bodyPartState = BodyPartState.AfterBoundary;\n                            parseStatus = State.NeedMoreData;\n                            goto quit;\n                        }\n                        else\n                        {\n                            currentBodyPart.ResetBoundary();\n                            if (bytesConsumed == effectiveMax)\n                            {\n                                goto quit;\n                            }\n\n                            goto case BodyPartState.BodyPart;\n                        }\n                    }\n                    else\n                    {\n                        currentBodyPart.ResetBoundary();\n                        bodyPartState = BodyPartState.BodyPart;\n                        goto case BodyPartState.BodyPart;\n                    }\n\n                case BodyPartState.AfterSecondCarriageReturn:\n                    if (buffer[bytesConsumed] != MimeMultipartParser.LF)\n                    {\n                        currentBodyPart.ResetBoundary();\n                        bodyPartState = BodyPartState.BodyPart;\n                        goto case BodyPartState.BodyPart;\n                    }\n\n                    currentBodyPart.AppendBoundary(MimeMultipartParser.LF);\n                    bytesConsumed++;\n\n                    bodyPartState = BodyPartState.BodyPart;\n                    if (currentBodyPart.IsBoundaryComplete())\n                    {\n                        parseStatus = State.BodyPartCompleted;\n                        goto quit;\n                    }\n                    else\n                    {\n                        currentBodyPart.ResetBoundary();\n                        if (bytesConsumed == effectiveMax)\n                        {\n                            goto quit;\n                        }\n\n                        goto case BodyPartState.BodyPart;\n                    }\n            }\n\n        quit:\n            if (initialBytesParsed < bytesConsumed)\n            {\n                int boundaryLength = currentBodyPart.BoundaryDelta;\n                if (boundaryLength > 0 && parseStatus != State.BodyPartCompleted)\n                {\n                    currentBodyPart.HasPotentialBoundaryLeftOver = true;\n                }\n\n                int bodyPartEnd = bytesConsumed - initialBytesParsed - boundaryLength;\n\n                currentBodyPart.BodyPart = new ArraySegment<byte>(buffer, initialBytesParsed, bodyPartEnd);\n            }\n\n            totalBytesConsumed += bytesConsumed - initialBytesParsed;\n            return parseStatus;\n        }\n\n        /// <summary>\n        /// Maintains information about the current body part being parsed.\n        /// </summary>\n        [DebuggerDisplay(\"{DebuggerToString()}\")]\n        private class CurrentBodyPartStore\n        {\n            private const int InitialOffset = 2;\n\n            private byte[] _boundaryStore = new byte[MaxBoundarySize];\n            private int _boundaryStoreLength;\n\n            private byte[] _referenceBoundary = new byte[MaxBoundarySize];\n            private int _referenceBoundaryLength;\n\n            private byte[] _boundary = new byte[MaxBoundarySize];\n            private int _boundaryLength = 0;\n\n            private ArraySegment<byte> _bodyPart = MimeMultipartParser._emptyBodyPart;\n            private bool _isFinal;\n            private bool _isFirst = true;\n            private bool _releaseDiscardedBoundary;\n            private int _boundaryOffset;\n\n            /// <summary>\n            /// Initializes a new instance of the <see cref=\"CurrentBodyPartStore\"/> class.\n            /// </summary>\n            /// <param name=\"referenceBoundary\">The reference boundary.</param>\n            public CurrentBodyPartStore(string referenceBoundary)\n            {\n                Contract.Assert(referenceBoundary != null);\n\n                _referenceBoundary[0] = MimeMultipartParser.CR;\n                _referenceBoundary[1] = MimeMultipartParser.LF;\n                _referenceBoundary[2] = MimeMultipartParser.Dash;\n                _referenceBoundary[3] = MimeMultipartParser.Dash;\n                _referenceBoundaryLength = 4 + Encoding.UTF8.GetBytes(referenceBoundary, 0, referenceBoundary.Length, _referenceBoundary, 4);\n\n                _boundary[0] = MimeMultipartParser.CR;\n                _boundary[1] = MimeMultipartParser.LF;\n                _boundaryLength = CurrentBodyPartStore.InitialOffset;\n            }\n\n            /// <summary>\n            /// Gets or sets a value indicating whether this instance has potential boundary left over.\n            /// </summary>\n            /// <value>\n            /// <c>true</c> if this instance has potential boundary left over; otherwise, <c>false</c>.\n            /// </value>\n            public bool HasPotentialBoundaryLeftOver { get; set; }\n\n            /// <summary>\n            /// Gets the boundary delta.\n            /// </summary>\n            public int BoundaryDelta\n            {\n                get { return (_boundaryLength - _boundaryOffset > 0) ? _boundaryLength - _boundaryOffset : _boundaryLength; }\n            }\n\n            /// <summary>\n            /// Gets or sets the body part.\n            /// </summary>\n            /// <value>\n            /// The body part.\n            /// </value>\n            public ArraySegment<byte> BodyPart\n            {\n                get { return _bodyPart; }\n\n                set { _bodyPart = value; }\n            }\n\n            /// <summary>\n            /// Gets a value indicating whether this body part instance is final.\n            /// </summary>\n            /// <value>\n            ///   <c>true</c> if this body part instance is final; otherwise, <c>false</c>.\n            /// </value>\n            public bool IsFinal\n            {\n                get { return _isFinal; }\n            }\n\n            /// <summary>\n            /// Resets the boundary offset.\n            /// </summary>\n            public void ResetBoundaryOffset()\n            {\n                _boundaryOffset = _boundaryLength;\n            }\n\n            /// <summary>\n            /// Resets the boundary.\n            /// </summary>\n            public void ResetBoundary()\n            {\n                // If we had a potential boundary left over then store it so that we don't loose it\n                if (HasPotentialBoundaryLeftOver)\n                {\n                    Buffer.BlockCopy(_boundary, 0, _boundaryStore, 0, _boundaryOffset);\n                    _boundaryStoreLength = _boundaryOffset;\n                    HasPotentialBoundaryLeftOver = false;\n                    _releaseDiscardedBoundary = true;\n                }\n\n                _boundaryLength = 0;\n                _boundaryOffset = 0;\n            }\n\n            /// <summary>\n            /// Appends byte to the current boundary.\n            /// </summary>\n            /// <param name=\"data\">The data to append to the boundary.</param>\n            public void AppendBoundary(byte data)\n            {\n                _boundary[_boundaryLength++] = data;\n            }\n\n            /// <summary>\n            /// Appends array of bytes to the current boundary.\n            /// </summary>\n            /// <param name=\"data\">The data to append to the boundary.</param>\n            /// <param name=\"offset\">The offset into the data.</param>\n            /// <param name=\"count\">The number of bytes to append.</param>\n            public bool AppendBoundary(byte[] data, int offset, int count)\n            {\n                // Check that potential boundary is not bigger than our reference boundary.\n                // Allow for 2 extra characters to include the final boundary which ends with\n                // an additional \"--\" sequence + plus up to 4 LWS characters (which are allowed).\n                if (_boundaryLength + count > _referenceBoundaryLength + 6)\n                {\n                    return false;\n                }\n\n                int cnt = _boundaryLength;\n                Buffer.BlockCopy(data, offset, _boundary, _boundaryLength, count);\n                _boundaryLength += count;\n\n                // Verify that boundary matches so far\n                int maxCount = Math.Min(_boundaryLength, _referenceBoundaryLength);\n                for (; cnt < maxCount; cnt++)\n                {\n                    if (_boundary[cnt] != _referenceBoundary[cnt])\n                    {\n                        return false;\n                    }\n                }\n\n                return true;\n            }\n\n            /// <summary>\n            /// Gets the discarded boundary.\n            /// </summary>\n            /// <returns>An <see cref=\"ArraySegment{T}\"/> containing the discarded boundary.</returns>\n            public ArraySegment<byte> GetDiscardedBoundary()\n            {\n                if (_boundaryStoreLength > 0 && _releaseDiscardedBoundary)\n                {\n                    ArraySegment<byte> discarded = new ArraySegment<byte>(_boundaryStore, 0, _boundaryStoreLength);\n                    _boundaryStoreLength = 0;\n                    return discarded;\n                }\n\n                return MimeMultipartParser._emptyBodyPart;\n            }\n\n            /// <summary>\n            /// Determines whether current boundary is valid.\n            /// </summary>\n            /// <returns>\n            ///   <c>true</c> if curent boundary is valid; otherwise, <c>false</c>.\n            /// </returns>\n            public bool IsBoundaryValid()\n            {\n                int offset = 0;\n                if (_isFirst)\n                {\n                    offset = CurrentBodyPartStore.InitialOffset;\n                }\n\n                int count = offset;\n                for (; count < _referenceBoundaryLength; count++)\n                {\n                    if (_boundary[count] != _referenceBoundary[count])\n                    {\n                        return false;\n                    }\n                }\n\n                // Check for final\n                bool boundaryIsFinal = false;\n                if (_boundary[count] == MimeMultipartParser.Dash &&\n                    _boundary[count + 1] == MimeMultipartParser.Dash)\n                {\n                    boundaryIsFinal = true;\n                    count += 2;\n                }\n\n                // Rest of boundary must be ignorable whitespace in order for it to match\n                for (; count < _boundaryLength - 2; count++)\n                {\n                    if (_boundary[count] != MimeMultipartParser.SP && _boundary[count] != MimeMultipartParser.HTAB)\n                    {\n                        return false;\n                    }\n                }\n\n                // We have a valid boundary so whatever we stored in the boundary story is no longer needed\n                _isFinal = boundaryIsFinal;\n                _isFirst = false;\n\n                return true;\n            }\n\n            public bool IsBoundaryComplete()\n            {\n                if (!IsBoundaryValid())\n                {\n                    return false;\n                }\n\n                if (_boundaryLength < _referenceBoundaryLength)\n                {\n                    return false;\n                }\n\n                if (_boundaryLength == _referenceBoundaryLength + 1 &&\n                    _boundary[_referenceBoundaryLength] == MimeMultipartParser.Dash)\n                {\n                    return false;\n                }\n\n                return true;\n            }\n\n            /// <summary>\n            /// Clears the body part.\n            /// </summary>\n            public void ClearBodyPart()\n            {\n                BodyPart = MimeMultipartParser._emptyBodyPart;\n            }\n\n            /// <summary>\n            /// Clears all.\n            /// </summary>\n            public void ClearAll()\n            {\n                _releaseDiscardedBoundary = false;\n                HasPotentialBoundaryLeftOver = false;\n                _boundaryLength = 0;\n                _boundaryOffset = 0;\n                _boundaryStoreLength = 0;\n                _isFinal = false;\n                ClearBodyPart();\n            }\n\n            [SuppressMessage(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\", Justification = \"Used for Debugger Display.\")]\n            private string DebuggerToString()\n            {\n                var referenceBoundary = Encoding.UTF8.GetString(_referenceBoundary, 0, _referenceBoundaryLength);\n                var boundary = Encoding.UTF8.GetString(_boundary, 0, _boundaryLength);\n\n                return String.Format(\n                    CultureInfo.InvariantCulture,\n                    \"Expected: {0} *** Current: {1}\",\n                    referenceBoundary,\n                    boundary);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/Parsers/ParserState.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Net.Http.Formatting.Parsers\n{\n    /// <summary>\n    /// Represents the overall state of various parsers.\n    /// </summary>\n    internal enum ParserState\n    {\n        /// <summary>\n        /// Need more data\n        /// </summary>\n        NeedMoreData = 0,\n\n        /// <summary>\n        /// Parsing completed (final)\n        /// </summary>\n        Done,\n\n        /// <summary>\n        /// Bad data format (final)\n        /// </summary>\n        Invalid,\n\n        /// <summary>\n        /// Data exceeds the allowed size (final)\n        /// </summary>\n        DataTooBig,\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/QueryStringMapping.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing System.Net.Http.Headers;\nusing System.Web.Http;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// Class that provides <see cref=\"MediaTypeHeaderValue\"/>s from query strings.\n    /// </summary>\n    public class QueryStringMapping : MediaTypeMapping\n    {\n        private static readonly Type _queryStringMappingType = typeof(QueryStringMapping);\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"QueryStringMapping\"/> class.\n        /// </summary>\n        /// <param name=\"queryStringParameterName\">The name of the query string parameter to match, if present.</param>\n        /// <param name=\"queryStringParameterValue\">The value of the query string parameter specified by <paramref name=\"queryStringParameterName\"/>.</param>\n        /// <param name=\"mediaType\">The media type to use if the query parameter specified by <paramref name=\"queryStringParameterName\"/> is present\n        /// and assigned the value specified by <paramref name=\"queryStringParameterValue\"/>.</param>\n        public QueryStringMapping(string queryStringParameterName, string queryStringParameterValue, string mediaType)\n            : base(mediaType)\n        {\n            Initialize(queryStringParameterName, queryStringParameterValue);\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"QueryStringMapping\"/> class.\n        /// </summary>\n        /// <param name=\"queryStringParameterName\">The name of the query string parameter to match, if present.</param>\n        /// <param name=\"queryStringParameterValue\">The value of the query string parameter specified by <paramref name=\"queryStringParameterName\"/>.</param>\n        /// <param name=\"mediaType\">The <see cref=\"MediaTypeHeaderValue\"/> to use if the query parameter specified by <paramref name=\"queryStringParameterName\"/> is present\n        /// and assigned the value specified by <paramref name=\"queryStringParameterValue\"/>.</param>\n        public QueryStringMapping(string queryStringParameterName, string queryStringParameterValue, MediaTypeHeaderValue mediaType)\n            : base(mediaType)\n        {\n            Initialize(queryStringParameterName, queryStringParameterValue);\n        }\n\n        /// <summary>\n        /// Gets the query string parameter name.\n        /// </summary>\n        public string QueryStringParameterName { get; private set; }\n\n        /// <summary>\n        /// Gets the query string parameter value.\n        /// </summary>\n        public string QueryStringParameterValue { get; private set; }\n\n        /// <summary>\n        /// Returns a value indicating whether the current <see cref=\"QueryStringMapping\"/>\n        /// instance can return a <see cref=\"MediaTypeHeaderValue\"/> from <paramref name=\"request\"/>.\n        /// </summary>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/> to check.</param>\n        /// <returns>If this instance can produce a <see cref=\"MediaTypeHeaderValue\"/> from <paramref name=\"request\"/>\n        /// it returns <c>1.0</c> otherwise <c>0.0</c>.</returns>\n        public override double TryMatchMediaType(HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            NameValueCollection queryString = GetQueryString(request.RequestUri);\n            return DoesQueryStringMatch(queryString) ? FormattingUtilities.Match : FormattingUtilities.NoMatch;\n        }\n\n        private static NameValueCollection GetQueryString(Uri uri)\n        {\n            if (uri == null)\n            {\n                throw Error.InvalidOperation(Properties.Resources.NonNullUriRequiredForMediaTypeMapping, _queryStringMappingType.Name);\n            }\n\n            return new FormDataCollection(uri).ReadAsNameValueCollection();\n        }\n\n        private void Initialize(string queryStringParameterName, string queryStringParameterValue)\n        {\n            if (String.IsNullOrWhiteSpace(queryStringParameterName))\n            {\n                throw Error.ArgumentNull(\"queryStringParameterName\");\n            }\n\n            if (String.IsNullOrWhiteSpace(queryStringParameterValue))\n            {\n                throw Error.ArgumentNull(\"queryStringParameterValue\");\n            }\n\n            QueryStringParameterName = queryStringParameterName.Trim();\n            QueryStringParameterValue = queryStringParameterValue.Trim();\n        }\n\n        private bool DoesQueryStringMatch(NameValueCollection queryString)\n        {\n            if (queryString != null)\n            {\n                foreach (string queryParameter in queryString.AllKeys)\n                {\n                    if (String.Equals(queryParameter, QueryStringParameterName, StringComparison.OrdinalIgnoreCase))\n                    {\n                        string queryValue = queryString[queryParameter];\n                        if (String.Equals(queryValue, QueryStringParameterValue, StringComparison.OrdinalIgnoreCase))\n                        {\n                            return true;\n                        }\n                    }\n                }\n            }\n\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/RequestHeaderMapping.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Net.Http.Headers;\nusing System.Web.Http;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// This class provides a mapping from an arbitrary HTTP request header field to a <see cref=\"MediaTypeHeaderValue\"/>\n    /// used to select <see cref=\"MediaTypeFormatter\"/> instances for handling the entity body of an <see cref=\"HttpRequestMessage\"/>\n    /// or <see cref=\"HttpResponseMessage\"/>.\n    /// <remarks>This class only checks header fields associated with <see cref=\"HttpRequestMessage.Headers\"/> for a match. It does\n    /// not check header fields associated with <see cref=\"HttpResponseMessage.Headers\"/> or <see cref=\"HttpContent.Headers\"/> instances.</remarks>\n    /// </summary>\n    public class RequestHeaderMapping : MediaTypeMapping\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"RequestHeaderMapping\"/> class.\n        /// </summary>\n        /// <param name=\"headerName\">Name of the header to match.</param>\n        /// <param name=\"headerValue\">The header value to match.</param>\n        /// <param name=\"valueComparison\">The value comparison to use when matching <paramref name=\"headerValue\"/>.</param>\n        /// <param name=\"isValueSubstring\">if set to <c>true</c> then <paramref name=\"headerValue\"/> is\n        /// considered a match if it matches a substring of the actual header value.</param>\n        /// <param name=\"mediaType\">The media type to use if <paramref name=\"headerName\"/> and <paramref name=\"headerValue\"/>\n        /// is considered a match.</param>\n        public RequestHeaderMapping(string headerName, string headerValue, StringComparison valueComparison, bool isValueSubstring, string mediaType)\n            : base(mediaType)\n        {\n            Initialize(headerName, headerValue, valueComparison, isValueSubstring);\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"RequestHeaderMapping\"/> class.\n        /// </summary>\n        /// <param name=\"headerName\">Name of the header to match.</param>\n        /// <param name=\"headerValue\">The header value to match.</param>\n        /// <param name=\"valueComparison\">The <see cref=\"StringComparison\"/> to use when matching <paramref name=\"headerValue\"/>.</param>\n        /// <param name=\"isValueSubstring\">if set to <c>true</c> then <paramref name=\"headerValue\"/> is\n        /// considered a match if it matches a substring of the actual header value.</param>\n        /// <param name=\"mediaType\">The <see cref=\"MediaTypeHeaderValue\"/> to use if <paramref name=\"headerName\"/> and <paramref name=\"headerValue\"/>\n        /// is considered a match.</param>\n        public RequestHeaderMapping(string headerName, string headerValue, StringComparison valueComparison, bool isValueSubstring, MediaTypeHeaderValue mediaType)\n            : base(mediaType)\n        {\n            Initialize(headerName, headerValue, valueComparison, isValueSubstring);\n        }\n\n        /// <summary>\n        /// Gets the name of the header to match.\n        /// </summary>\n        public string HeaderName { get; private set; }\n\n        /// <summary>\n        /// Gets the header value to match.\n        /// </summary>\n        public string HeaderValue { get; private set; }\n\n        /// <summary>\n        /// Gets the <see cref=\"StringComparison\"/> to use when matching <see cref=\"HeaderValue\"/>.\n        /// </summary>\n        public StringComparison HeaderValueComparison { get; private set; }\n\n        /// <summary>\n        /// Gets a value indicating whether <see cref=\"HeaderValue\"/> is\n        /// a matched as a substring of the actual header value.\n        /// this instance is value substring.\n        /// </summary>\n        /// <value>\n        /// <c>true</c> if <see cref=\"HeaderValue\"/> is to be matched as a substring; otherwise <c>false</c>.\n        /// </value>\n        public bool IsValueSubstring { get; private set; }\n\n        /// <summary>\n        /// Returns a value indicating whether the current <see cref=\"RequestHeaderMapping\"/>\n        /// instance can return a <see cref=\"MediaTypeHeaderValue\"/> from <paramref name=\"request\"/>.\n        /// </summary>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/> to check.</param>\n        /// <returns>\n        /// The quality of the match. It must be between <c>0.0</c> and <c>1.0</c>.\n        /// A value of <c>0.0</c> signifies no match.\n        /// A value of <c>1.0</c> signifies a complete match.\n        /// </returns>\n        public override double TryMatchMediaType(HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            return MatchHeaderValue(request, HeaderName, HeaderValue, HeaderValueComparison, IsValueSubstring);\n        }\n\n        private static double MatchHeaderValue(HttpRequestMessage request, string headerName, string headerValue, StringComparison valueComparison, bool isValueSubstring)\n        {\n            Contract.Assert(request != null, \"request should not be null\");\n            Contract.Assert(headerName != null, \"header name should not be null\");\n            Contract.Assert(headerValue != null, \"header value should not be null\");\n\n            IEnumerable<string> values;\n            if (request.Headers.TryGetValues(headerName, out values))\n            {\n                foreach (string value in values)\n                {\n                    if (isValueSubstring)\n                    {\n                        if (value.IndexOf(headerValue, valueComparison) != -1)\n                        {\n                            return FormattingUtilities.Match;\n                        }\n                    }\n                    else\n                    {\n                        if (value.Equals(headerValue, valueComparison))\n                        {\n                            return FormattingUtilities.Match;\n                        }\n                    }\n                }\n            }\n\n            return FormattingUtilities.NoMatch;\n        }\n\n        private void Initialize(string headerName, string headerValue, StringComparison valueComparison, bool isValueSubstring)\n        {\n            if (String.IsNullOrWhiteSpace(headerName))\n            {\n                throw Error.ArgumentNull(\"headerName\");\n            }\n\n            if (String.IsNullOrWhiteSpace(headerValue))\n            {\n                throw Error.ArgumentNull(\"headerValue\");\n            }\n\n            StringComparisonHelper.Validate(valueComparison, \"valueComparison\");\n\n            HeaderName = headerName;\n            HeaderValue = headerValue;\n            HeaderValueComparison = valueComparison;\n            IsValueSubstring = isValueSubstring;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/StringComparisonHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Web.Http;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// Helper class for validating <see cref=\"StringComparison\"/> values.\n    /// </summary>\n    internal static class StringComparisonHelper\n    {\n        /// <summary>\n        /// Determines whether the specified <paramref name=\"value\"/> is defined by the <see cref=\"StringComparison\"/>\n        /// enumeration.\n        /// </summary>\n        /// <param name=\"value\">The value to verify.</param>\n        /// <returns>\n        /// <c>true</c> if the specified options is defined; otherwise, <c>false</c>.\n        /// </returns>\n        public static bool IsDefined(StringComparison value)\n        {\n            return value == StringComparison.CurrentCulture ||\n                   value == StringComparison.CurrentCultureIgnoreCase ||\n#if !NETSTANDARD1_3\n                   value == StringComparison.InvariantCulture ||\n                   value == StringComparison.InvariantCultureIgnoreCase ||\n#endif\n                   value == StringComparison.Ordinal ||\n                   value == StringComparison.OrdinalIgnoreCase;\n        }\n\n        /// <summary>\n        /// Validates the specified <paramref name=\"value\"/> and throws an <see cref=\"ArgumentException\"/>\n        /// exception if not valid.\n        /// </summary>\n        /// <param name=\"value\">The value to validate.</param>\n        /// <param name=\"parameterName\">Name of the parameter to use if throwing exception.</param>\n        public static void Validate(StringComparison value, string parameterName)\n        {\n            if (!IsDefined(value))\n            {\n                throw Error.InvalidEnumArgument(parameterName, (int)value, typeof(StringComparison));\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/StringWithQualityHeaderValueComparer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Net.Http.Headers;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// Implementation of <see cref=\"IComparer{T}\"/> that can compare content negotiation header fields\n    /// based on their quality values (a.k.a q-values). This applies to values used in accept-charset,\n    /// accept-encoding, accept-language and related header fields with similar syntax rules. See\n    /// <see cref=\"MediaTypeWithQualityHeaderValueComparer\"/> for a comparer for media type\n    /// q-values.\n    /// </summary>\n    internal class StringWithQualityHeaderValueComparer : IComparer<StringWithQualityHeaderValue>\n    {\n        private static readonly StringWithQualityHeaderValueComparer _qualityComparer =\n            new StringWithQualityHeaderValueComparer();\n\n        private StringWithQualityHeaderValueComparer()\n        {\n        }\n\n        public static StringWithQualityHeaderValueComparer QualityComparer\n        {\n            get { return _qualityComparer; }\n        }\n\n        /// <summary>\n        /// Compares two <see cref=\"StringWithQualityHeaderValue\"/> based on their quality value (a.k.a their \"q-value\").\n        /// Values with identical q-values are considered equal (i.e the result is 0) with the exception of wild-card\n        /// values (i.e. a value of \"*\") which are considered less than non-wild-card values. This allows to sort\n        /// a sequence of <see cref=\"StringWithQualityHeaderValue\"/> following their q-values ending up with any\n        /// wild-cards at the end.\n        /// </summary>\n        /// <param name=\"stringWithQuality1\">The first value to compare.</param>\n        /// <param name=\"stringWithQuality2\">The second value to compare</param>\n        /// <returns>The result of the comparison.</returns>\n        public int Compare(StringWithQualityHeaderValue stringWithQuality1,\n                           StringWithQualityHeaderValue stringWithQuality2)\n        {\n            Contract.Assert(stringWithQuality1 != null);\n            Contract.Assert(stringWithQuality2 != null);\n\n            double quality1 = stringWithQuality1.Quality ?? FormattingUtilities.Match;\n            double quality2 = stringWithQuality2.Quality ?? FormattingUtilities.Match;\n            double qualityDifference = quality1 - quality2;\n            if (qualityDifference < 0)\n            {\n                return -1;\n            }\n            else if (qualityDifference > 0)\n            {\n                return 1;\n            }\n\n            if (!String.Equals(stringWithQuality1.Value, stringWithQuality2.Value, StringComparison.OrdinalIgnoreCase))\n            {\n                if (String.Equals(stringWithQuality1.Value, \"*\", StringComparison.OrdinalIgnoreCase))\n                {\n                    return -1;\n                }\n                else if (String.Equals(stringWithQuality2.Value, \"*\", StringComparison.OrdinalIgnoreCase))\n                {\n                    return 1;\n                }\n            }\n\n            return 0;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/XmlHttpRequestHeaderMapping.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Net.Http.Headers;\nusing System.Web.Http;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// A <see cref=\"RequestHeaderMapping\"/> that maps the X-Requested-With http header field set by AJAX XmlHttpRequest (XHR)\n    /// to the media type <c>application/json</c> if no explicit Accept header fields are present in the request.\n    /// </summary>\n    public class XmlHttpRequestHeaderMapping : RequestHeaderMapping\n    {\n        /// <summary>\n        /// Initializes a new instance of <see cref=\"XmlHttpRequestHeaderMapping\" /> class\n        /// </summary>\n        public XmlHttpRequestHeaderMapping() :\n            base(FormattingUtilities.HttpRequestedWithHeader, FormattingUtilities.HttpRequestedWithHeaderValue, StringComparison.OrdinalIgnoreCase, isValueSubstring: true, mediaType: MediaTypeConstants.ApplicationJsonMediaType)\n        {\n        }\n\n        /// <summary>\n        /// Returns a value indicating whether the current <see cref=\"RequestHeaderMapping\"/>\n        /// instance can return a <see cref=\"MediaTypeHeaderValue\"/> from <paramref name=\"request\"/>.\n        /// </summary>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/> to check.</param>\n        /// <returns>\n        /// The quality of the match.\n        /// A value of <c>0.0</c> signifies no match.\n        /// A value of <c>1.0</c> signifies a complete match and that the request was made using XmlHttpRequest without an Accept header.\n        /// </returns>\n        public override double TryMatchMediaType(HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            // Accept header trumps XHR mapping.\n            // Accept: */* is equivalent to passing no Accept header.\n            if (request.Headers.Accept.Count == 0\n                || (request.Headers.Accept.Count == 1 && request.Headers.Accept.First().MediaType.Equals(\"*/*\", StringComparison.Ordinal)))\n            {\n                return base.TryMatchMediaType(request);\n            }\n            else\n            {\n                return FormattingUtilities.NoMatch;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Formatting/XmlMediaTypeFormatter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.IO;\nusing System.Net.Http.Headers;\nusing System.Net.Http.Internal;\nusing System.Runtime.Serialization;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http;\nusing System.Xml;\nusing System.Xml.Serialization;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// <see cref=\"MediaTypeFormatter\"/> class to handle Xml.\n    /// </summary>\n    public class XmlMediaTypeFormatter : MediaTypeFormatter\n    {\n        private ConcurrentDictionary<Type, object> _serializerCache = new ConcurrentDictionary<Type, object>();\n        private XmlDictionaryReaderQuotas _readerQuotas = FormattingUtilities.CreateDefaultReaderQuotas();\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"XmlMediaTypeFormatter\"/> class.\n        /// </summary>\n        public XmlMediaTypeFormatter()\n        {\n            // Set default supported media types\n            SupportedMediaTypes.Add(MediaTypeConstants.ApplicationXmlMediaType);\n            SupportedMediaTypes.Add(MediaTypeConstants.TextXmlMediaType);\n\n            // Set default supported character encodings\n            SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true));\n            SupportedEncodings.Add(new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true));\n            WriterSettings = new XmlWriterSettings\n            {\n                OmitXmlDeclaration = true,\n                CloseOutput = false,\n                CheckCharacters = false\n            };\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"XmlMediaTypeFormatter\"/> class.\n        /// </summary>\n        /// <param name=\"formatter\">The <see cref=\"XmlMediaTypeFormatter\"/> instance to copy settings from.</param>\n        protected XmlMediaTypeFormatter(XmlMediaTypeFormatter formatter)\n            : base(formatter)\n        {\n            UseXmlSerializer = formatter.UseXmlSerializer;\n            WriterSettings = formatter.WriterSettings;\n            MaxDepth = formatter.MaxDepth;\n        }\n\n        /// <summary>\n        /// Gets the default media type for xml, namely \"application/xml\".\n        /// </summary>\n        /// <value>\n        /// <remarks>\n        /// The default media type does not have any <c>charset</c> parameter as\n        /// the <see cref=\"Encoding\"/> can be configured on a per <see cref=\"XmlMediaTypeFormatter\"/>\n        /// instance basis.\n        /// </remarks>\n        /// Because <see cref=\"MediaTypeHeaderValue\"/> is mutable, the value\n        /// returned will be a new instance every time.\n        /// </value>\n        public static MediaTypeHeaderValue DefaultMediaType\n        {\n            get { return MediaTypeConstants.ApplicationXmlMediaType; }\n        }\n\n        /// <summary>\n        /// Gets or sets a value indicating whether to use <see cref=\"XmlSerializer\"/> instead of <see cref=\"DataContractSerializer\"/> by default.\n        /// </summary>\n        /// <value>\n        ///     <c>true</c> if use <see cref=\"XmlSerializer\"/> by default; otherwise, <c>false</c>. The default is <c>false</c>.\n        /// </value>\n        [DefaultValue(false)]\n        public bool UseXmlSerializer { get; set; }\n\n        /// <summary>\n        /// Gets or sets a value indicating whether to indent elements when writing data.\n        /// </summary>\n        public bool Indent\n        {\n            get\n            {\n                return WriterSettings.Indent;\n            }\n            set\n            {\n                WriterSettings.Indent = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets the <see cref=\"XmlWriterSettings\"/> to be used while writing.\n        /// </summary>\n        public XmlWriterSettings WriterSettings { get; private set; }\n\n        /// <summary>\n        /// Gets or sets the maximum depth allowed by this formatter.\n        /// </summary>\n        public int MaxDepth\n        {\n            get\n            {\n                return _readerQuotas.MaxDepth;\n            }\n            set\n            {\n                if (value < FormattingUtilities.DefaultMinDepth)\n                {\n                    throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"value\", value, FormattingUtilities.DefaultMinDepth);\n                }\n\n                _readerQuotas.MaxDepth = value;\n            }\n        }\n\n        /// <summary>\n        /// Registers the <see cref=\"XmlObjectSerializer\"/> to use to read or write\n        /// the specified <paramref name=\"type\"/>.\n        /// </summary>\n        /// <param name=\"type\">The type of object that will be serialized or deserialized with <paramref name=\"serializer\"/>.</param>\n        /// <param name=\"serializer\">The <see cref=\"XmlObjectSerializer\"/> instance to use.</param>\n        public void SetSerializer(Type type, XmlObjectSerializer serializer)\n        {\n            VerifyAndSetSerializer(type, serializer);\n        }\n\n        /// <summary>\n        /// Registers the <see cref=\"XmlObjectSerializer\"/> to use to read or write\n        /// the specified <typeparamref name=\"T\"/> type.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of object that will be serialized or deserialized with <paramref name=\"serializer\"/>.</typeparam>\n        /// <param name=\"serializer\">The <see cref=\"XmlObjectSerializer\"/> instance to use.</param>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1004:GenericMethodsShouldProvideTypeParameter\", Justification = \"The T represents a Type parameter.\")]\n        public void SetSerializer<T>(XmlObjectSerializer serializer)\n        {\n            SetSerializer(typeof(T), serializer);\n        }\n\n        /// <summary>\n        /// Registers the <see cref=\"XmlSerializer\"/> to use to read or write\n        /// the specified <paramref name=\"type\"/>.\n        /// </summary>\n        /// <param name=\"type\">The type of objects for which <paramref name=\"serializer\"/> will be used.</param>\n        /// <param name=\"serializer\">The <see cref=\"XmlSerializer\"/> instance to use.</param>\n        public void SetSerializer(Type type, XmlSerializer serializer)\n        {\n            VerifyAndSetSerializer(type, serializer);\n        }\n\n        /// <summary>\n        /// Registers the <see cref=\"XmlSerializer\"/> to use to read or write\n        /// the specified <typeparamref name=\"T\"/> type.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of object that will be serialized or deserialized with <paramref name=\"serializer\"/>.</typeparam>\n        /// <param name=\"serializer\">The <see cref=\"XmlSerializer\"/> instance to use.</param>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1004:GenericMethodsShouldProvideTypeParameter\", Justification = \"The T represents a Type parameter.\")]\n        public void SetSerializer<T>(XmlSerializer serializer)\n        {\n            SetSerializer(typeof(T), serializer);\n        }\n\n        /// <summary>\n        /// Unregisters the serializer currently associated with the given <paramref name=\"type\"/>.\n        /// </summary>\n        /// <remarks>\n        /// Unless another serializer is registered for the <paramref name=\"type\"/>, a default one will be created.\n        /// </remarks>\n        /// <param name=\"type\">The type of object whose serializer should be removed.</param>\n        /// <returns><c>true</c> if a serializer was registered for the <paramref name=\"type\"/>; otherwise <c>false</c>.</returns>\n        public bool RemoveSerializer(Type type)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            object value;\n            return _serializerCache.TryRemove(type, out value);\n        }\n\n        /// <summary>\n        /// Determines whether this <see cref=\"XmlMediaTypeFormatter\"/> can read objects\n        /// of the specified <paramref name=\"type\"/>.\n        /// </summary>\n        /// <param name=\"type\">The type of object that will be read.</param>\n        /// <returns><c>true</c> if objects of this <paramref name=\"type\"/> can be read, otherwise <c>false</c>.</returns>\n        public override bool CanReadType(Type type)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            // If there is a registered non-null serializer, we can support this type.\n            // Otherwise attempt to create the default serializer.\n            object serializer = GetCachedSerializer(type, throwOnError: false);\n\n            // Null means we tested it before and know it is not supported\n            return serializer != null;\n        }\n\n        /// <summary>\n        /// Determines whether this <see cref=\"XmlMediaTypeFormatter\"/> can write objects\n        /// of the specified <paramref name=\"type\"/>.\n        /// </summary>\n        /// <param name=\"type\">The type of object that will be written.</param>\n        /// <returns><c>true</c> if objects of this <paramref name=\"type\"/> can be written, otherwise <c>false</c>.</returns>\n        public override bool CanWriteType(Type type)\n        {\n            // Performance-sensitive\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            if (UseXmlSerializer)\n            {\n                MediaTypeFormatter.TryGetDelegatingTypeForIEnumerableGenericOrSame(ref type);\n            }\n            else\n            {\n                MediaTypeFormatter.TryGetDelegatingTypeForIQueryableGenericOrSame(ref type);\n            }\n\n            // If there is a registered non-null serializer, we can support this type.\n            object serializer = GetCachedSerializer(type, throwOnError: false);\n\n            // Null means we tested it before and know it is not supported\n            return serializer != null;\n        }\n\n        /// <summary>\n        /// Called during deserialization to read an object of the specified <paramref name=\"type\"/>\n        /// from the specified <paramref name=\"readStream\"/>.\n        /// </summary>\n        /// <param name=\"type\">The type of object to read.</param>\n        /// <param name=\"readStream\">The <see cref=\"Stream\"/> from which to read.</param>\n        /// <param name=\"content\">The <see cref=\"HttpContent\"/> for the content being read.</param>\n        /// <param name=\"formatterLogger\">The <see cref=\"IFormatterLogger\"/> to log events to.</param>\n        /// <returns>A <see cref=\"Task\"/> whose result will be the object instance that has been read.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"The caught exception type is reflected into a faulted task.\")]\n        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            if (readStream == null)\n            {\n                throw Error.ArgumentNull(\"readStream\");\n            }\n\n            try\n            {\n                return Task.FromResult(ReadFromStream(type, readStream, content, formatterLogger));\n            }\n            catch (Exception e)\n            {\n                return TaskHelpers.FromError<object>(e);\n            }\n        }\n\n        private object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)\n        {\n            HttpContentHeaders contentHeaders = content == null ? null : content.Headers;\n\n            // If content length is 0 then return default value for this type\n            if (contentHeaders != null && contentHeaders.ContentLength == 0)\n            {\n                return GetDefaultValueForType(type);\n            }\n\n            object serializer = GetDeserializer(type, content);\n\n            try\n            {\n                using (XmlReader reader = CreateXmlReader(readStream, content))\n                {\n                    XmlSerializer xmlSerializer = serializer as XmlSerializer;\n                    if (xmlSerializer != null)\n                    {\n                        return xmlSerializer.Deserialize(reader);\n                    }\n                    else\n                    {\n                        XmlObjectSerializer xmlObjectSerializer = serializer as XmlObjectSerializer;\n                        if (xmlObjectSerializer == null)\n                        {\n                            ThrowInvalidSerializerException(serializer, \"GetDeserializer\");\n                        }\n                        return xmlObjectSerializer.ReadObject(reader);\n                    }\n                }\n            }\n            catch (Exception e)\n            {\n                if (formatterLogger == null)\n                {\n                    throw;\n                }\n                formatterLogger.LogError(String.Empty, e);\n                return GetDefaultValueForType(type);\n            }\n        }\n\n        /// <summary>\n        /// Called during deserialization to get the XML serializer to use for deserializing objects.\n        /// </summary>\n        /// <param name=\"type\">The type of object to deserialize.</param>\n        /// <param name=\"content\">The <see cref=\"HttpContent\"/> for the content being read.</param>\n        /// <returns>An instance of <see cref=\"XmlObjectSerializer\"/> or <see cref=\"XmlSerializer\"/> to use for deserializing the object.</returns>\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", Justification = \"The term deserializer is spelled correctly.\")]\n        protected internal virtual object GetDeserializer(Type type, HttpContent content)\n        {\n            return GetSerializerForType(type);\n        }\n\n        /// <summary>\n        /// Called during deserialization to get the XML reader to use for reading objects from the stream.\n        /// </summary>\n        /// <param name=\"readStream\">The <see cref=\"Stream\"/> to read from.</param>\n        /// <param name=\"content\">The <see cref=\"HttpContent\"/> for the content being read.</param>\n        /// <returns>The <see cref=\"XmlReader\"/> to use for reading objects.</returns>\n        protected internal virtual XmlReader CreateXmlReader(Stream readStream, HttpContent content)\n        {\n            // Get the character encoding for the content\n            Encoding effectiveEncoding = SelectCharacterEncoding(content == null ? null : content.Headers);\n\n            // DCS encodings are limited to UTF8, UTF16BE, and UTF16LE. Convert to UTF8 as we read.\n            Stream innerStream = string.Equals(effectiveEncoding.WebName, Utf8Encoding.WebName, StringComparison.OrdinalIgnoreCase) ?\n                new NonClosingDelegatingStream(readStream) :\n                new TranscodingStream(readStream, effectiveEncoding, Utf8Encoding, leaveOpen: true);\n\n            // XmlDictionaryReader will always dispose of innerStream when caller disposes of the reader.\n            return XmlDictionaryReader.CreateTextReader(innerStream, Utf8Encoding, _readerQuotas, onClose: null);\n        }\n\n        /// <inheritdoc/>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"The caught exception type is reflected into a faulted task.\")]\n        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content,\n            TransportContext transportContext, CancellationToken cancellationToken)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n            if (writeStream == null)\n            {\n                throw Error.ArgumentNull(\"writeStream\");\n            }\n            if (cancellationToken.IsCancellationRequested)\n            {\n                return TaskHelpers.Canceled();\n            }\n\n            try\n            {\n                WriteToStream(type, value, writeStream, content);\n                return TaskHelpers.Completed();\n            }\n            catch (Exception e)\n            {\n                return TaskHelpers.FromError(e);\n            }\n        }\n\n        private void WriteToStream(Type type, object value, Stream writeStream, HttpContent content)\n        {\n            bool isRemapped = false;\n            if (UseXmlSerializer)\n            {\n                isRemapped = MediaTypeFormatter.TryGetDelegatingTypeForIEnumerableGenericOrSame(ref type);\n            }\n            else\n            {\n                isRemapped = MediaTypeFormatter.TryGetDelegatingTypeForIQueryableGenericOrSame(ref type);\n            }\n\n            if (isRemapped && value != null)\n            {\n                value = MediaTypeFormatter.GetTypeRemappingConstructor(type).Invoke(new object[] { value });\n            }\n\n            object serializer = GetSerializer(type, value, content);\n\n            using (XmlWriter writer = CreateXmlWriter(writeStream, content))\n            {\n                XmlSerializer xmlSerializer = serializer as XmlSerializer;\n                if (xmlSerializer != null)\n                {\n                    xmlSerializer.Serialize(writer, value);\n                }\n                else\n                {\n                    XmlObjectSerializer xmlObjectSerializer = serializer as XmlObjectSerializer;\n                    if (xmlObjectSerializer == null)\n                    {\n                        ThrowInvalidSerializerException(serializer, \"GetSerializer\");\n                    }\n                    xmlObjectSerializer.WriteObject(writer, value);\n                }\n            }\n        }\n\n        /// <summary>\n        /// Called during serialization to get the XML serializer to use for serializing objects.\n        /// </summary>\n        /// <param name=\"type\">The type of object to serialize.</param>\n        /// <param name=\"value\">The object to serialize.</param>\n        /// <param name=\"content\">The <see cref=\"HttpContent\"/> for the content being written.</param>\n        /// <returns>An instance of <see cref=\"XmlObjectSerializer\"/> or <see cref=\"XmlSerializer\"/> to use for serializing the object.</returns>\n        protected internal virtual object GetSerializer(Type type, object value, HttpContent content)\n        {\n            return GetSerializerForType(type);\n        }\n\n        /// <summary>\n        /// Called during serialization to get the XML writer to use for writing objects to the stream.\n        /// </summary>\n        /// <param name=\"writeStream\">The <see cref=\"Stream\"/> to write to.</param>\n        /// <param name=\"content\">The <see cref=\"HttpContent\"/> for the content being written.</param>\n        /// <returns>The <see cref=\"XmlWriter\"/> to use for writing objects.</returns>\n        protected internal virtual XmlWriter CreateXmlWriter(Stream writeStream, HttpContent content)\n        {\n            Encoding effectiveEncoding = SelectCharacterEncoding(content != null ? content.Headers : null);\n            WritePreamble(writeStream, effectiveEncoding);\n\n            // DCS encodings are limited to UTF8, UTF16BE, and UTF16LE. Convert to UTF8 as we read.\n            Stream innerStream = string.Equals(effectiveEncoding.WebName, Utf8Encoding.WebName, StringComparison.OrdinalIgnoreCase) ?\n                writeStream :\n                new TranscodingStream(writeStream, effectiveEncoding, Utf8Encoding, leaveOpen: true);\n\n            XmlWriterSettings writerSettings = WriterSettings.Clone();\n            writerSettings.Encoding = Utf8Encoding;\n\n            // Have XmlWriter dispose of innerStream when caller disposes of the writer if using a TranscodingStream.\n            writerSettings.CloseOutput = writeStream != innerStream;\n\n            return XmlWriter.Create(innerStream, writerSettings);\n        }\n\n        /// <summary>\n        /// Called during deserialization to get the XML serializer.\n        /// </summary>\n        /// <param name=\"type\">The type of object that will be serialized or deserialized.</param>\n        /// <returns>The <see cref=\"XmlSerializer\"/> used to serialize the object.</returns>\n        public virtual XmlSerializer CreateXmlSerializer(Type type)\n        {\n            return new XmlSerializer(type);\n        }\n\n        /// <summary>\n        /// Called during deserialization to get the DataContractSerializer serializer.\n        /// </summary>\n        /// <param name=\"type\">The type of object that will be serialized or deserialized.</param>\n        /// <returns>The <see cref=\"DataContractSerializer\"/> used to serialize the object.</returns>\n        public virtual DataContractSerializer CreateDataContractSerializer(Type type)\n        {\n            return new DataContractSerializer(type);\n        }\n\n        /// <summary>\n        /// This method is to support infrastructure and is not intended to be used directly from your code.\n        /// </summary>\n        [EditorBrowsable(EditorBrowsableState.Never)]\n        public XmlReader InvokeCreateXmlReader(Stream readStream, HttpContent content)\n        {\n            return CreateXmlReader(readStream, content);\n        }\n\n        /// <summary>\n        /// This method is to support infrastructure and is not intended to be used directly from your code.\n        /// </summary>\n        [EditorBrowsable(EditorBrowsableState.Never)]\n        public XmlWriter InvokeCreateXmlWriter(Stream writeStream, HttpContent content)\n        {\n            return CreateXmlWriter(writeStream, content);\n        }\n\n        /// <summary>\n        /// This method is to support infrastructure and is not intended to be used directly from your code.\n        /// </summary>\n        [EditorBrowsable(EditorBrowsableState.Never)]\n        public object InvokeGetDeserializer(Type type, HttpContent content)\n        {\n            return GetDeserializer(type, content);\n        }\n\n        /// <summary>\n        /// This method is to support infrastructure and is not intended to be used directly from your code.\n        /// </summary>\n        [EditorBrowsable(EditorBrowsableState.Never)]\n        public object InvokeGetSerializer(Type type, object value, HttpContent content)\n        {\n            return GetSerializer(type, value, content);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Since we use an extensible factory method we cannot control the exceptions being thrown\")]\n        private object CreateDefaultSerializer(Type type, bool throwOnError)\n        {\n            Contract.Assert(type != null, \"type cannot be null.\");\n\n#if NETSTANDARD1_3 // XsdDataContractExporter is not supported in netstandard1.3\n            if (!UseXmlSerializer)\n            {\n                if (throwOnError)\n                {\n                    throw new PlatformNotSupportedException(Error.Format(\n                        Properties.Resources.XmlMediaTypeFormatter_DCS_NotSupported,\n                        nameof(UseXmlSerializer)));\n                }\n                else\n                {\n                    return null;\n                }\n            }\n#endif\n\n            Exception exception = null;\n            object serializer = null;\n\n            try\n            {\n                if (UseXmlSerializer)\n                {\n                    serializer = CreateXmlSerializer(type);\n                }\n                else\n                {\n#if !NETSTANDARD1_3 // Unreachable when targeting netstandard1.3.\n                    // Verify that type is a valid data contract by forcing the serializer to try to create a data contract\n                    FormattingUtilities.XsdDataContractExporter.GetRootElementName(type);\n\n                    serializer = CreateDataContractSerializer(type);\n#endif\n                }\n            }\n            catch (Exception caught)\n            {\n                exception = caught;\n            }\n\n            if (serializer == null && throwOnError)\n            {\n                if (exception != null)\n                {\n                    throw Error.InvalidOperation(exception, Properties.Resources.SerializerCannotSerializeType,\n                                  UseXmlSerializer ? typeof(XmlSerializer).Name : typeof(DataContractSerializer).Name,\n                                  type.Name);\n                }\n                else\n                {\n                    throw Error.InvalidOperation(Properties.Resources.SerializerCannotSerializeType,\n                              UseXmlSerializer ? typeof(XmlSerializer).Name : typeof(DataContractSerializer).Name,\n                              type.Name);\n                }\n            }\n\n            return serializer;\n        }\n\n        private object GetCachedSerializer(Type type, bool throwOnError)\n        {\n            // Performance-sensitive\n            object serializer;\n            if (!_serializerCache.TryGetValue(type, out serializer))\n            {\n                // Race condition on creation has no side effects\n                serializer = CreateDefaultSerializer(type, throwOnError);\n                _serializerCache.TryAdd(type, serializer);\n            }\n            return serializer;\n        }\n\n        private void VerifyAndSetSerializer(Type type, object serializer)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            if (serializer == null)\n            {\n                throw Error.ArgumentNull(\"serializer\");\n            }\n\n            SetSerializerInternal(type, serializer);\n        }\n\n        private void SetSerializerInternal(Type type, object serializer)\n        {\n            Contract.Assert(type != null, \"type cannot be null.\");\n            Contract.Assert(serializer != null, \"serializer cannot be null.\");\n\n            _serializerCache.AddOrUpdate(type, serializer, (key, value) => serializer);\n        }\n\n        private object GetSerializerForType(Type type)\n        {\n            // Performance-sensitive\n            Contract.Assert(type != null, \"Type cannot be null\");\n\n            object serializer = GetCachedSerializer(type, throwOnError: true);\n\n            if (serializer == null)\n            {\n                // A null serializer indicates the type has already been tested\n                // and found unsupportable.\n                throw Error.InvalidOperation(Properties.Resources.SerializerCannotSerializeType,\n                              UseXmlSerializer ? typeof(XmlSerializer).Name : typeof(DataContractSerializer).Name,\n                              type.Name);\n            }\n\n            Contract.Assert(serializer is XmlSerializer || serializer is XmlObjectSerializer, \"Only XmlSerializer or XmlObjectSerializer are supported.\");\n            return serializer;\n        }\n\n        private static void ThrowInvalidSerializerException(object serializer, string getSerializerMethodName)\n        {\n            if (serializer == null)\n            {\n                throw Error.InvalidOperation(Properties.Resources.XmlMediaTypeFormatter_NullReturnedSerializer, getSerializerMethodName);\n            }\n            else\n            {\n                throw Error.InvalidOperation(Properties.Resources.XmlMediaTypeFormatter_InvalidSerializerType, serializer.GetType().Name, getSerializerMethodName);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/FormattingUtilities.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Runtime.Serialization;\nusing System.Xml;\nusing Newtonsoft.Json.Linq;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// Provides various internal utility functions\n    /// </summary>\n    internal static class FormattingUtilities\n    {\n        // Supported date formats for input.\n        private static readonly string[] dateFormats = new string[]\n        {\n            // \"r\", // RFC 1123, required output format but too strict for input\n            \"ddd, d MMM yyyy H:m:s 'GMT'\", // RFC 1123 (r, except it allows both 1 and 01 for date and time)\n            \"ddd, d MMM yyyy H:m:s\", // RFC 1123, no zone - assume GMT\n            \"d MMM yyyy H:m:s 'GMT'\", // RFC 1123, no day-of-week\n            \"d MMM yyyy H:m:s\", // RFC 1123, no day-of-week, no zone\n            \"ddd, d MMM yy H:m:s 'GMT'\", // RFC 1123, short year\n            \"ddd, d MMM yy H:m:s\", // RFC 1123, short year, no zone\n            \"d MMM yy H:m:s 'GMT'\", // RFC 1123, no day-of-week, short year\n            \"d MMM yy H:m:s\", // RFC 1123, no day-of-week, short year, no zone\n\n            \"dddd, d'-'MMM'-'yy H:m:s 'GMT'\", // RFC 850, short year\n            \"dddd, d'-'MMM'-'yy H:m:s\", // RFC 850 no zone\n            \"ddd, d'-'MMM'-'yyyy H:m:s 'GMT'\", // RFC 850, long year\n            \"ddd MMM d H:m:s yyyy\", // ANSI C's asctime() format\n\n            \"ddd, d MMM yyyy H:m:s zzz\", // RFC 5322\n            \"ddd, d MMM yyyy H:m:s\", // RFC 5322 no zone\n            \"d MMM yyyy H:m:s zzz\", // RFC 5322 no day-of-week\n            \"d MMM yyyy H:m:s\", // RFC 5322 no day-of-week, no zone\n        };\n\n        // Valid header token characters are within the range 0x20 < c < 0x7F excluding the following characters\n        private const string NonTokenChars = \"()<>@,;:\\\\\\\"/[]?={}\";\n\n        /// <summary>\n        /// Quality factor to indicate a perfect match.\n        /// </summary>\n        public const double Match = 1.0;\n\n        /// <summary>\n        /// Quality factor to indicate no match.\n        /// </summary>\n        public const double NoMatch = 0.0;\n\n        /// <summary>\n        /// The default max depth for our formatter is 256\n        /// </summary>\n        public const int DefaultMaxDepth = 256;\n\n        /// <summary>\n        /// The default min depth for our formatter is 1\n        /// </summary>\n        public const int DefaultMinDepth = 1;\n\n        /// <summary>\n        /// HTTP X-Requested-With header field name\n        /// </summary>\n        public const string HttpRequestedWithHeader = @\"x-requested-with\";\n\n        /// <summary>\n        /// HTTP X-Requested-With header field value\n        /// </summary>\n        public const string HttpRequestedWithHeaderValue = @\"XMLHttpRequest\";\n\n        /// <summary>\n        /// HTTP Host header field name\n        /// </summary>\n        public const string HttpHostHeader = \"Host\";\n\n        /// <summary>\n        /// HTTP Version token\n        /// </summary>\n        public const string HttpVersionToken = \"HTTP\";\n\n        /// <summary>\n        /// A <see cref=\"Type\"/> representing <see cref=\"HttpRequestMessage\"/>.\n        /// </summary>\n        public static readonly Type HttpRequestMessageType = typeof(HttpRequestMessage);\n\n        /// <summary>\n        /// A <see cref=\"Type\"/> representing <see cref=\"HttpResponseMessage\"/>.\n        /// </summary>\n        public static readonly Type HttpResponseMessageType = typeof(HttpResponseMessage);\n\n        /// <summary>\n        /// A <see cref=\"Type\"/> representing <see cref=\"HttpContent\"/>.\n        /// </summary>\n        public static readonly Type HttpContentType = typeof(HttpContent);\n\n        /// <summary>\n        /// A <see cref=\"Type\"/> representing <see cref=\"DelegatingEnumerable{T}\"/>.\n        /// </summary>\n        public static readonly Type DelegatingEnumerableGenericType = typeof(DelegatingEnumerable<>);\n\n        /// <summary>\n        /// A <see cref=\"Type\"/> representing <see cref=\"IEnumerable{T}\"/>.\n        /// </summary>\n        public static readonly Type EnumerableInterfaceGenericType = typeof(IEnumerable<>);\n\n        /// <summary>\n        /// A <see cref=\"Type\"/> representing <see cref=\"IQueryable{T}\"/>.\n        /// </summary>\n        public static readonly Type QueryableInterfaceGenericType = typeof(IQueryable<>);\n\n#if !NETSTANDARD1_3 // XsdDataContractExporter is not supported in netstandard1.3\n        /// <summary>\n        /// An instance of <see cref=\"XsdDataContractExporter\"/>.\n        /// </summary>\n        public static readonly XsdDataContractExporter XsdDataContractExporter = new XsdDataContractExporter();\n#endif\n\n        /// <summary>\n        /// Determines whether <paramref name=\"type\"/> is a <see cref=\"JToken\"/> type.\n        /// </summary>\n        /// <param name=\"type\">The type to test.</param>\n        /// <returns>\n        ///   <c>true</c> if <paramref name=\"type\"/> is a <see cref=\"JToken\"/> type; otherwise, <c>false</c>.\n        /// </returns>\n        public static bool IsJTokenType(Type type)\n        {\n            return typeof(JToken).IsAssignableFrom(type);\n        }\n\n        /// <summary>\n        /// Creates an empty <see cref=\"HttpContentHeaders\"/> instance. The only way is to get it from a dummy\n        /// <see cref=\"HttpContent\"/> instance.\n        /// </summary>\n        /// <returns>The created instance.</returns>\n        public static HttpContentHeaders CreateEmptyContentHeaders()\n        {\n            HttpContent tempContent = null;\n            HttpContentHeaders contentHeaders = null;\n            try\n            {\n                tempContent = new StringContent(String.Empty);\n                contentHeaders = tempContent.Headers;\n                contentHeaders.Clear();\n            }\n            finally\n            {\n                // We can dispose the content without touching the headers\n                if (tempContent != null)\n                {\n                    tempContent.Dispose();\n                }\n            }\n\n            return contentHeaders;\n        }\n\n        /// <summary>\n        /// Create a default reader quotas with a default depth quota of 1K\n        /// </summary>\n        /// <returns></returns>\n        public static XmlDictionaryReaderQuotas CreateDefaultReaderQuotas()\n        {\n            return new XmlDictionaryReaderQuotas()\n            {\n                MaxArrayLength = Int32.MaxValue,\n                MaxBytesPerRead = Int32.MaxValue,\n                MaxDepth = DefaultMaxDepth,\n                MaxNameTableCharCount = Int32.MaxValue,\n                MaxStringContentLength = Int32.MaxValue\n            };\n        }\n\n        /// <summary>\n        /// Remove bounding quotes on a token if present\n        /// </summary>\n        /// <param name=\"token\">Token to unquote.</param>\n        /// <returns>Unquoted token.</returns>\n        public static string UnquoteToken(string token)\n        {\n            if (String.IsNullOrWhiteSpace(token))\n            {\n                return token;\n            }\n\n            if (token.StartsWith(\"\\\"\", StringComparison.Ordinal) && token.EndsWith(\"\\\"\", StringComparison.Ordinal) && token.Length > 1)\n            {\n                return token.Substring(1, token.Length - 2);\n            }\n\n            return token;\n        }\n\n        public static bool ValidateHeaderToken(string token)\n        {\n            if (token == null)\n            {\n                return false;\n            }\n\n            foreach (char c in token)\n            {\n                if (c < 0x21 || c > 0x7E || NonTokenChars.IndexOf(c) != -1)\n                {\n                    return false;\n                }\n            }\n\n            return true;\n        }\n\n        public static string DateToString(DateTimeOffset dateTime)\n        {\n            // Format according to RFC1123; 'r' uses invariant info (DateTimeFormatInfo.InvariantInfo)\n            return dateTime.ToUniversalTime().ToString(\"r\", CultureInfo.InvariantCulture);\n        }\n\n        public static bool TryParseDate(string input, out DateTimeOffset result)\n        {\n            return DateTimeOffset.TryParseExact(input, dateFormats, DateTimeFormatInfo.InvariantInfo,\n                                                DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AssumeUniversal,\n                                                out result);\n        }\n\n        /// <summary>\n        /// Parses valid integer strings with no leading signs, whitespace or other <see cref=\"NumberStyles\"/>\n        /// </summary>\n        /// <param name=\"value\">The value to parse</param>\n        /// <param name=\"result\">The result</param>\n        /// <returns>True if value was valid; false otherwise.</returns>\n        public static bool TryParseInt32(string value, out int result)\n        {\n            return Int32.TryParse(value, NumberStyles.None, NumberFormatInfo.InvariantInfo, out result);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/GlobalSuppressions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA2210:AssembliesShouldHaveValidStrongNames\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"System.Net.Http.Headers\", Justification = \"We follow the layout of System.Net.Http.\")]\n[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.\")]\n// Some resources are specific to the netstandard1.3 assembly\n[assembly: SuppressMessage(\"Microsoft.Web.FxCop\", \"MW1000:UnusedResourceUsageRule\", Justification = \"There are a few unused resources due to missing netstandard1.3 features.\")]\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Handlers/HttpProgressEventArgs.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\n\nnamespace System.Net.Http.Handlers\n{\n    /// <summary>\n    /// Provides data for the events generated by <see cref=\"ProgressMessageHandler\"/>.\n    /// </summary>\n    public class HttpProgressEventArgs : ProgressChangedEventArgs\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpProgressEventArgs\"/> with the parameters given.\n        /// </summary>\n        /// <param name=\"progressPercentage\">The percent completed of the overall exchange.</param>\n        /// <param name=\"userToken\">Any user state provided as part of reading or writing the data.</param>\n        /// <param name=\"bytesTransferred\">The current number of bytes either received or sent.</param>\n        /// <param name=\"totalBytes\">The total number of bytes expected to be received or sent.</param>\n        public HttpProgressEventArgs(int progressPercentage, object userToken, long bytesTransferred, long? totalBytes)\n            : base(progressPercentage, userToken)\n        {\n            BytesTransferred = bytesTransferred;\n            TotalBytes = totalBytes;\n        }\n\n        /// <summary>\n        /// Gets the current number of bytes transferred.\n        /// </summary>\n        public long BytesTransferred { get; private set; }\n\n        /// <summary>\n        /// Gets the total number of expected bytes to be sent or received. If the number is not known then this is null.\n        /// </summary>\n        public long? TotalBytes { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Handlers/ProgressContent.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.IO;\nusing System.Threading.Tasks;\n\nnamespace System.Net.Http.Handlers\n{\n    /// <summary>\n    /// Wraps an inner <see cref=\"HttpContent\"/> in order to insert a <see cref=\"ProgressStream\"/> on writing data.\n    /// </summary>\n    internal class ProgressContent : HttpContent\n    {\n        private readonly HttpContent _innerContent;\n        private readonly ProgressMessageHandler _handler;\n        private readonly HttpRequestMessage _request;\n\n        public ProgressContent(HttpContent innerContent, ProgressMessageHandler handler, HttpRequestMessage request)\n        {\n            Contract.Assert(innerContent != null);\n            Contract.Assert(handler != null);\n            Contract.Assert(request != null);\n\n            _innerContent = innerContent;\n            _handler = handler;\n            _request = request;\n\n            innerContent.Headers.CopyTo(Headers);\n        }\n\n        protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)\n        {\n            ProgressStream progressStream = new ProgressStream(stream, _handler, _request, response: null);\n            return _innerContent.CopyToAsync(progressStream);\n        }\n\n        protected override bool TryComputeLength(out long length)\n        {\n            long? contentLength = _innerContent.Headers.ContentLength;\n            if (contentLength.HasValue)\n            {\n                length = contentLength.Value;\n                return true;\n            }\n\n            length = -1;\n            return false;\n        }\n\n        protected override void Dispose(bool disposing)\n        {\n            base.Dispose(disposing);\n            if (disposing)\n            {\n                _innerContent.Dispose();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Handlers/ProgressMessageHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Net.Http.Handlers\n{\n    /// <summary>\n    /// The <see cref=\"ProgressMessageHandler\"/> provides a mechanism for getting progress event notifications\n    /// when sending and receiving data in connection with exchanging HTTP requests and responses.\n    /// Register event handlers for the events <see cref=\"HttpSendProgress\"/> and <see cref=\"HttpReceiveProgress\"/>\n    /// to see events for data being sent and received.\n    /// </summary>\n    public class ProgressMessageHandler : DelegatingHandler\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"ProgressMessageHandler\"/> class.\n        /// </summary>\n        public ProgressMessageHandler()\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"ProgressMessageHandler\"/> class.\n        /// </summary>\n        /// <param name=\"innerHandler\">The inner handler to which this handler submits requests.</param>\n        public ProgressMessageHandler(HttpMessageHandler innerHandler)\n            : base(innerHandler)\n        {\n        }\n\n        /// <summary>\n        /// Occurs every time the client sending data is making progress.\n        /// </summary>\n        public event EventHandler<HttpProgressEventArgs> HttpSendProgress;\n\n        /// <summary>\n        /// Occurs every time the client receiving data is making progress.\n        /// </summary>\n        public event EventHandler<HttpProgressEventArgs> HttpReceiveProgress;\n\n        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n        {\n            AddRequestProgress(request);\n            HttpResponseMessage response = await base.SendAsync(request, cancellationToken);\n\n            if (HttpReceiveProgress != null && response != null && response.Content != null)\n            {\n                cancellationToken.ThrowIfCancellationRequested();\n                await AddResponseProgressAsync(request, response);\n            }\n\n            return response;\n        }\n\n        /// <summary>\n        /// Raises the <see cref=\"HttpSendProgress\"/> event.\n        /// </summary>\n        /// <param name=\"request\">The request.</param>\n        /// <param name=\"e\">The <see cref=\"HttpProgressEventArgs\"/> instance containing the event data.</param>\n        protected internal virtual void OnHttpRequestProgress(HttpRequestMessage request, HttpProgressEventArgs e)\n        {\n            if (HttpSendProgress != null)\n            {\n                HttpSendProgress(request, e);\n            }\n        }\n\n        /// <summary>\n        /// Raises the <see cref=\"HttpReceiveProgress\"/> event.\n        /// </summary>\n        /// <param name=\"request\">The request.</param>\n        /// <param name=\"e\">The <see cref=\"HttpProgressEventArgs\"/> instance containing the event data.</param>\n        protected internal virtual void OnHttpResponseProgress(HttpRequestMessage request, HttpProgressEventArgs e)\n        {\n            if (HttpReceiveProgress != null)\n            {\n                HttpReceiveProgress(request, e);\n            }\n        }\n\n        private void AddRequestProgress(HttpRequestMessage request)\n        {\n            if (HttpSendProgress != null && request != null && request.Content != null)\n            {\n                HttpContent progressContent = new ProgressContent(request.Content, this, request);\n                request.Content = progressContent;\n            }\n        }\n\n        private async Task<HttpResponseMessage> AddResponseProgressAsync(HttpRequestMessage request, HttpResponseMessage response)\n        {\n            Stream stream = await response.Content.ReadAsStreamAsync();\n            ProgressStream progressStream = new ProgressStream(stream, this, request, response);\n            HttpContent progressContent = new StreamContent(progressStream);\n            response.Content.Headers.CopyTo(progressContent.Headers);\n            response.Content = progressContent;\n            return response;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Handlers/ProgressStream.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.IO;\nusing System.Net.Http.Internal;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Net.Http.Handlers\n{\n    /// <summary>\n    /// This implementation of <see cref=\"DelegatingStream\"/> registers how much data has been\n    /// read (received) versus written (sent) for a particular HTTP operation. The implementation\n    /// is client side in that the total bytes to send is taken from the request and the total\n    /// bytes to read is taken from the response. In a server side scenario, it would be the\n    /// other way around (reading the request and writing the response).\n    /// </summary>\n    internal class ProgressStream : DelegatingStream\n    {\n        private readonly ProgressMessageHandler _handler;\n        private readonly HttpRequestMessage _request;\n\n        private long _bytesReceived;\n        private long? _totalBytesToReceive;\n\n        private long _bytesSent;\n        private long? _totalBytesToSend;\n\n        public ProgressStream(Stream innerStream, ProgressMessageHandler handler, HttpRequestMessage request, HttpResponseMessage response)\n            : base(innerStream)\n        {\n            Contract.Assert(handler != null);\n            Contract.Assert(request != null);\n\n            if (request.Content != null)\n            {\n                _totalBytesToSend = request.Content.Headers.ContentLength;\n            }\n\n            if (response != null && response.Content != null)\n            {\n                _totalBytesToReceive = response.Content.Headers.ContentLength;\n            }\n\n            _handler = handler;\n            _request = request;\n        }\n\n        public override int Read(byte[] buffer, int offset, int count)\n        {\n            int bytesRead = InnerStream.Read(buffer, offset, count);\n            ReportBytesReceived(bytesRead, userState: null);\n            return bytesRead;\n        }\n\n        public override int ReadByte()\n        {\n            int byteRead = InnerStream.ReadByte();\n            ReportBytesReceived(byteRead == -1 ? 0 : 1, userState: null);\n            return byteRead;\n        }\n\n        public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)\n        {\n            int readCount = await InnerStream.ReadAsync(buffer, offset, count, cancellationToken);\n            ReportBytesReceived(readCount, userState: null);\n            return readCount;\n        }\n\n#if !NETSTANDARD1_3 // BeginX and EndX are not supported on Streams in netstandard1.3\n        public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)\n        {\n            return InnerStream.BeginRead(buffer, offset, count, callback, state);\n        }\n\n        public override int EndRead(IAsyncResult asyncResult)\n        {\n            int bytesRead = InnerStream.EndRead(asyncResult);\n            ReportBytesReceived(bytesRead, asyncResult.AsyncState);\n            return bytesRead;\n        }\n#endif\n\n        public override void Write(byte[] buffer, int offset, int count)\n        {\n            InnerStream.Write(buffer, offset, count);\n            ReportBytesSent(count, userState: null);\n        }\n\n        public override void WriteByte(byte value)\n        {\n            InnerStream.WriteByte(value);\n            ReportBytesSent(1, userState: null);\n        }\n\n       public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)\n        {\n            await InnerStream.WriteAsync(buffer, offset, count, cancellationToken);\n            ReportBytesSent(count, userState: null);\n        }\n\n#if !NETSTANDARD1_3 // BeginX and EndX are not supported on Streams in netstandard1.3\n        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)\n        {\n            return new ProgressWriteAsyncResult(InnerStream, this, buffer, offset, count, callback, state);\n        }\n\n        public override void EndWrite(IAsyncResult asyncResult)\n        {\n            ProgressWriteAsyncResult.End(asyncResult);\n        }\n#endif\n\n        internal void ReportBytesSent(int bytesSent, object userState)\n        {\n            if (bytesSent > 0)\n            {\n                _bytesSent += bytesSent;\n                int percentage = 0;\n                if (_totalBytesToSend.HasValue && _totalBytesToSend != 0)\n                {\n                    percentage = (int)((100L * _bytesSent) / _totalBytesToSend);\n                }\n\n                // We only pass the request as it is guaranteed to be non-null (the response may be null)\n                _handler.OnHttpRequestProgress(_request, new HttpProgressEventArgs(percentage, userState, _bytesSent, _totalBytesToSend));\n            }\n        }\n\n        private void ReportBytesReceived(int bytesReceived, object userState)\n        {\n            if (bytesReceived > 0)\n            {\n                _bytesReceived += bytesReceived;\n                int percentage = 0;\n                if (_totalBytesToReceive.HasValue && _totalBytesToReceive != 0)\n                {\n                    percentage = (int)((100L * _bytesReceived) / _totalBytesToReceive);\n                }\n\n                // We only pass the request as it is guaranteed to be non-null (the response may be null)\n                _handler.OnHttpResponseProgress(_request, new HttpProgressEventArgs(percentage, userState, _bytesReceived, _totalBytesToReceive));\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Handlers/ProgressWriteAsyncResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.IO;\nusing System.Net.Http.Internal;\n\nnamespace System.Net.Http.Handlers\n{\n    internal class ProgressWriteAsyncResult : AsyncResult\n    {\n        private static readonly AsyncCallback _writeCompletedCallback = WriteCompletedCallback;\n\n        private readonly Stream _innerStream;\n        private readonly ProgressStream _progressStream;\n        private readonly int _count;\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Exception is handled as part of IAsyncResult completion.\")]\n        public ProgressWriteAsyncResult(Stream innerStream, ProgressStream progressStream, byte[] buffer, int offset, int count, AsyncCallback callback, object state)\n            : base(callback, state)\n        {\n            Contract.Assert(innerStream != null);\n            Contract.Assert(progressStream != null);\n            Contract.Assert(buffer != null);\n\n            _innerStream = innerStream;\n            _progressStream = progressStream;\n            _count = count;\n\n            try\n            {\n                IAsyncResult result = innerStream.BeginWrite(buffer, offset, count, _writeCompletedCallback, this);\n                if (result.CompletedSynchronously)\n                {\n                    WriteCompleted(result);\n                }\n            }\n            catch (Exception e)\n            {\n                Complete(true, e);\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Exception is handled as part of IAsyncResult completion.\")]\n        private static void WriteCompletedCallback(IAsyncResult result)\n        {\n            if (result.CompletedSynchronously)\n            {\n                return;\n            }\n\n            ProgressWriteAsyncResult thisPtr = (ProgressWriteAsyncResult)result.AsyncState;\n            try\n            {\n                thisPtr.WriteCompleted(result);\n            }\n            catch (Exception e)\n            {\n                thisPtr.Complete(false, e);\n            }\n        }\n\n        private void WriteCompleted(IAsyncResult result)\n        {\n            _innerStream.EndWrite(result);\n            _progressStream.ReportBytesSent(_count, AsyncState);\n            Complete(result.CompletedSynchronously);\n        }\n\n        public static void End(IAsyncResult result)\n        {\n            AsyncResult.End<ProgressWriteAsyncResult>(result);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Headers/CookieHeaderValue.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Collections.Specialized;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Linq;\nusing System.Net.Http.Formatting;\nusing System.Text;\nusing System.Web.Http;\n\nnamespace System.Net.Http.Headers\n{\n    public class CookieHeaderValue : ICloneable\n    {\n        private const string ExpiresToken = \"expires\";\n        private const string MaxAgeToken = \"max-age\";\n        private const string DomainToken = \"domain\";\n        private const string PathToken = \"path\";\n        private const string SecureToken = \"secure\";\n        private const string HttpOnlyToken = \"httponly\";\n        private const string DefaultPath = \"/\";\n\n        private static readonly char[] segmentSeparator = new char[] { ';' };\n        private static readonly char[] nameValueSeparator = new char[] { '=' };\n\n        // Use list instead of dictionary since we may have multiple parameters with the same name.\n        private Collection<CookieState> _cookies;\n\n        public CookieHeaderValue(string name, string value)\n        {\n            CookieState cookie = new CookieState(name, value);\n            Cookies.Add(cookie);\n        }\n\n        public CookieHeaderValue(string name, NameValueCollection values)\n        {\n            CookieState cookie = new CookieState(name, values);\n            Cookies.Add(cookie);\n        }\n\n        /// <summary>\n        /// Constructor to be used by parser to create a new instance of this type.\n        /// </summary>\n        protected CookieHeaderValue()\n        {\n        }\n\n        private CookieHeaderValue(CookieHeaderValue source)\n        {\n            if (source == null)\n            {\n                throw Error.ArgumentNull(\"source\");\n            }\n\n            Expires = source.Expires;\n            MaxAge = source.MaxAge;\n            Domain = source.Domain;\n            Path = source.Path;\n            Secure = source.Secure;\n            HttpOnly = source.HttpOnly;\n\n            foreach (CookieState cookie in source.Cookies)\n            {\n                Cookies.Add(cookie.Clone<CookieState>());\n            }\n        }\n\n        public Collection<CookieState> Cookies\n        {\n            get\n            {\n                if (_cookies == null)\n                {\n                    _cookies = new Collection<CookieState>();\n                }\n                return _cookies;\n            }\n        }\n\n        public DateTimeOffset? Expires { get; set; }\n\n        public TimeSpan? MaxAge { get; set; }\n\n        public string Domain { get; set; }\n\n        public string Path { get; set; }\n\n        public bool Secure { get; set; }\n\n        public bool HttpOnly { get; set; }\n\n        public CookieState this[string name]\n        {\n            get\n            {\n                if (String.IsNullOrEmpty(name))\n                {\n                    return null;\n                }\n\n                CookieState cookie = Cookies.FirstOrDefault(c => String.Equals(c.Name, name, StringComparison.OrdinalIgnoreCase));\n                if (cookie == null)\n                {\n                    cookie = new CookieState(name, String.Empty);\n                    Cookies.Add(cookie);\n                }\n                return cookie;\n            }\n        }\n\n        public override string ToString()\n        {\n            StringBuilder header = new StringBuilder();\n            bool first = true;\n\n            foreach (CookieState cookie in Cookies)\n            {\n                first = AppendSegment(header, first, cookie.ToString(), null);\n            }\n\n            if (Expires.HasValue)\n            {\n                first = AppendSegment(header, first, ExpiresToken, FormattingUtilities.DateToString(Expires.Value));\n            }\n\n            if (MaxAge.HasValue)\n            {\n                first = AppendSegment(header, first, MaxAgeToken, ((int)MaxAge.Value.TotalSeconds).ToString(NumberFormatInfo.InvariantInfo));\n            }\n\n            if (Domain != null)\n            {\n                first = AppendSegment(header, first, DomainToken, Domain);\n            }\n\n            if (Path != null)\n            {\n                first = AppendSegment(header, first, PathToken, Path);\n            }\n\n            if (Secure)\n            {\n                first = AppendSegment(header, first, SecureToken, null);\n            }\n\n            if (HttpOnly)\n            {\n                first = AppendSegment(header, first, HttpOnlyToken, null);\n            }\n\n            return header.ToString();\n        }\n\n        public object Clone()\n        {\n            return new CookieHeaderValue(this);\n        }\n\n        public static bool TryParse(string input, out CookieHeaderValue parsedValue)\n        {\n            parsedValue = null;\n            if (!String.IsNullOrEmpty(input))\n            {\n                string[] segments = input.Split(segmentSeparator);\n                CookieHeaderValue instance = new CookieHeaderValue();\n                foreach (string segment in segments)\n                {\n                    if (!ParseCookieSegment(instance, segment))\n                    {\n                        return false;\n                    }\n                }\n\n                // If we didn't find any cookie state name/value pairs then cookie is not valid\n                if (instance.Cookies.Count == 0)\n                {\n                    return false;\n                }\n\n                parsedValue = instance;\n                return true;\n            }\n\n            return false;\n        }\n\n        private static bool AppendSegment(StringBuilder builder, bool first, string name, string value)\n        {\n            if (first)\n            {\n                first = false;\n            }\n            else\n            {\n                builder.Append(\"; \");\n            }\n\n            builder.Append(name);\n            if (value != null)\n            {\n                builder.Append(\"=\");\n                builder.Append(value);\n            }\n            return first;\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"This is a try method where we do want to ignore errors.\")]\n        private static bool ParseCookieSegment(CookieHeaderValue instance, string segment)\n        {\n            if (String.IsNullOrWhiteSpace(segment))\n            {\n                return true;\n            }\n\n            string[] nameValue = segment.Split(nameValueSeparator, 2);\n            if (nameValue.Length < 1 || String.IsNullOrWhiteSpace(nameValue[0]))\n            {\n                return false;\n            }\n\n            string name = nameValue[0].Trim();\n            if (String.Equals(name, ExpiresToken, StringComparison.OrdinalIgnoreCase))\n            {\n                string value = GetSegmentValue(nameValue, null);\n                DateTimeOffset expires;\n                if (FormattingUtilities.TryParseDate(value, out expires))\n                {\n                    instance.Expires = expires;\n                    return true;\n                }\n                return false;\n            }\n            else if (String.Equals(name, MaxAgeToken, StringComparison.OrdinalIgnoreCase))\n            {\n                string value = GetSegmentValue(nameValue, null);\n                int maxAge;\n                if (FormattingUtilities.TryParseInt32(value, out maxAge))\n                {\n                    instance.MaxAge = new TimeSpan(0, 0, maxAge);\n                    return true;\n                }\n                return false;\n            }\n            else if (String.Equals(name, DomainToken, StringComparison.OrdinalIgnoreCase))\n            {\n                instance.Domain = GetSegmentValue(nameValue, null);\n                return true;\n            }\n            else if (String.Equals(name, PathToken, StringComparison.OrdinalIgnoreCase))\n            {\n                instance.Path = GetSegmentValue(nameValue, DefaultPath);\n                return true;\n            }\n            else if (String.Equals(name, SecureToken, StringComparison.OrdinalIgnoreCase))\n            {\n                string value = GetSegmentValue(nameValue, null);\n                if (!String.IsNullOrWhiteSpace(value))\n                {\n                    return false;\n                }\n                instance.Secure = true;\n                return true;\n            }\n            else if (String.Equals(name, HttpOnlyToken, StringComparison.OrdinalIgnoreCase))\n            {\n                string value = GetSegmentValue(nameValue, null);\n                if (!String.IsNullOrWhiteSpace(value))\n                {\n                    return false;\n                }\n                instance.HttpOnly = true;\n                return true;\n            }\n            else\n            {\n                string value = GetSegmentValue(nameValue, null);\n\n                // We read the cookie segment as form data\n                try\n                {\n                    FormDataCollection formData = new FormDataCollection(value);\n                    NameValueCollection values = formData.ReadAsNameValueCollection();\n                    CookieState cookie = new CookieState(name, values);\n                    instance.Cookies.Add(cookie);\n                    return true;\n                }\n                catch\n                {\n                    return false;\n                }\n            }\n        }\n\n        private static string GetSegmentValue(string[] nameValuePair, string defaultValue)\n        {\n            Contract.Assert(nameValuePair != null);\n            return nameValuePair.Length > 1 ? FormattingUtilities.UnquoteToken(nameValuePair[1]) : defaultValue;\n        }\n    }\n}"
  },
  {
    "path": "src/System.Net.Http.Formatting/Headers/CookieState.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing System.Diagnostics.Contracts;\nusing System.Net.Http.Formatting.Internal;\nusing System.Web.Http;\n\nnamespace System.Net.Http.Headers\n{\n    public class CookieState : ICloneable\n    {\n        private string _name;\n        private NameValueCollection _values = HttpValueCollection.Create();\n\n        public CookieState(string name)\n            : this(name, String.Empty)\n        {\n        }\n\n        public CookieState(string name, string value)\n        {\n            CheckNameFormat(name, \"name\");\n            _name = name;\n\n            CheckValueFormat(value, \"value\");\n            Value = value;\n        }\n\n        public CookieState(string name, NameValueCollection values)\n        {\n            CheckNameFormat(name, \"name\");\n            _name = name;\n\n            if (values == null)\n            {\n                throw Error.ArgumentNull(\"values\");\n            }\n            Values.Add(values);\n        }\n\n        private CookieState(CookieState source)\n        {\n            Contract.Requires(source != null);\n\n            _name = source._name;\n            if (source._values != null)\n            {\n                Values.Add(source._values);\n            }\n        }\n\n        public string Name\n        {\n            get { return _name; }\n            set\n            {\n                CheckNameFormat(value, \"value\");\n                _name = value;\n            }\n        }\n\n        /// <summary>\n        /// If the cookie data is a simple string value then set or retrieve it using the <see cref=\"Value\"/> property.\n        /// If the cookie data is structured then use the <see cref=\"Values\"/> property.\n        /// </summary>\n        public string Value\n        {\n            get\n            {\n                return Values.Count > 0 ? Values.AllKeys[0] : String.Empty;\n            }\n\n            set\n            {\n                CheckValueFormat(value, \"value\");\n                if (Values.Count > 0)\n                {\n                    Values.AllKeys[0] = value;\n                }\n                else\n                {\n                    Values.Add(value, String.Empty);\n                }\n            }\n        }\n\n        /// <summary>\n        /// If the cookie data is structured then use the <see cref=\"Values\"/> property for setting and getting individual sub-name/value pairs.\n        /// If the cookie data is a simple string value then set or retrieve it using the <see cref=\"Value\"/> property.\n        /// </summary>\n        public NameValueCollection Values\n        {\n            get { return _values; }\n        }\n\n        public string this[string subName]\n        {\n            get { return Values[subName]; }\n            set { Values[subName] = value; }\n        }\n\n        public override string ToString()\n        {\n            return _name + \"=\" + (_values != null ? _values.ToString() : String.Empty);\n        }\n\n        public object Clone()\n        {\n            return new CookieState(this);\n        }\n\n        private static void CheckNameFormat(string name, string parameterName)\n        {\n            if (name == null)\n            {\n                throw Error.ArgumentNull(\"name\");\n            }\n\n            if (!FormattingUtilities.ValidateHeaderToken(name))\n            {\n                throw Error.Argument(parameterName, Properties.Resources.CookieInvalidName);\n            }\n        }\n\n        private static void CheckValueFormat(string value, string parameterName)\n        {\n            // Empty string is a valid cookie value\n            if (value == null)\n            {\n                throw Error.ArgumentNull(parameterName);\n            }\n        }\n    }\n}"
  },
  {
    "path": "src/System.Net.Http.Formatting/HttpClientExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// Extension methods that aid in making formatted requests using <see cref=\"HttpClient\"/>.\n    /// </summary>\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class HttpClientExtensions\n    {\n        /// <summary>\n        /// Sends a POST request as an asynchronous operation to the specified Uri with the given <paramref name=\"value\"/> serialized\n        /// as JSON.\n        /// </summary>\n        /// <remarks>\n        /// This method uses a default instance of <see cref=\"JsonMediaTypeFormatter\"/>.\n        /// </remarks>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"We want to support URIs as strings\")]\n        public static Task<HttpResponseMessage> PostAsJsonAsync<T>(this HttpClient client, string requestUri, T value)\n        {\n            return client.PostAsJsonAsync(requestUri, value, CancellationToken.None);\n        }\n\n        /// <summary>\n        /// Sends a POST request as an asynchronous operation to the specified Uri with the given <paramref name=\"value\"/> serialized\n        /// as JSON.\n        /// </summary>\n        /// <remarks>\n        /// This method uses a default instance of <see cref=\"JsonMediaTypeFormatter\"/>.\n        /// </remarks>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"We want to support URIs as strings\")]\n        public static Task<HttpResponseMessage> PostAsJsonAsync<T>(this HttpClient client, string requestUri, T value, CancellationToken cancellationToken)\n        {\n            return client.PostAsync(requestUri, value, new JsonMediaTypeFormatter(), cancellationToken);\n        }\n\n        /// <summary>\n        /// Sends a POST request as an asynchronous operation to the specified Uri with the given <paramref name=\"value\"/> serialized\n        /// as JSON.\n        /// </summary>\n        /// <remarks>\n        /// This method uses a default instance of <see cref=\"JsonMediaTypeFormatter\"/>.\n        /// </remarks>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        public static Task<HttpResponseMessage> PostAsJsonAsync<T>(this HttpClient client, Uri requestUri, T value)\n        {\n            return client.PostAsJsonAsync(requestUri, value, CancellationToken.None);\n        }\n\n        /// <summary>\n        /// Sends a POST request as an asynchronous operation to the specified Uri with the given <paramref name=\"value\"/> serialized\n        /// as JSON.\n        /// </summary>\n        /// <remarks>\n        /// This method uses a default instance of <see cref=\"JsonMediaTypeFormatter\"/>.\n        /// </remarks>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        public static Task<HttpResponseMessage> PostAsJsonAsync<T>(this HttpClient client, Uri requestUri, T value, CancellationToken cancellationToken)\n        {\n            return client.PostAsync(requestUri, value, new JsonMediaTypeFormatter(), cancellationToken);\n        }\n\n        /// <summary>\n        /// Sends a POST request as an asynchronous operation to the specified Uri with the given <paramref name=\"value\"/> serialized\n        /// as XML.\n        /// </summary>\n        /// <remarks>\n        /// This method uses the default instance of <see cref=\"XmlMediaTypeFormatter\"/>.\n        /// </remarks>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"We want to support URIs as strings\")]\n        public static Task<HttpResponseMessage> PostAsXmlAsync<T>(this HttpClient client, string requestUri, T value)\n        {\n            return client.PostAsXmlAsync(requestUri, value, CancellationToken.None);\n        }\n\n        /// <summary>\n        /// Sends a POST request as an asynchronous operation to the specified Uri with the given <paramref name=\"value\"/> serialized\n        /// as XML.\n        /// </summary>\n        /// <remarks>\n        /// This method uses the default instance of <see cref=\"XmlMediaTypeFormatter\"/>.\n        /// </remarks>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"We want to support URIs as strings\")]\n        public static Task<HttpResponseMessage> PostAsXmlAsync<T>(this HttpClient client, string requestUri, T value, CancellationToken cancellationToken)\n        {\n            return client.PostAsync(requestUri, value, new XmlMediaTypeFormatter(), cancellationToken);\n        }\n\n        /// <summary>\n        /// Sends a POST request as an asynchronous operation to the specified Uri with the given <paramref name=\"value\"/> serialized\n        /// as XML.\n        /// </summary>\n        /// <remarks>\n        /// This method uses the default instance of <see cref=\"XmlMediaTypeFormatter\"/>.\n        /// </remarks>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        public static Task<HttpResponseMessage> PostAsXmlAsync<T>(this HttpClient client, Uri requestUri, T value)\n        {\n            return client.PostAsXmlAsync(requestUri, value, CancellationToken.None);\n        }\n\n        /// <summary>\n        /// Sends a POST request as an asynchronous operation to the specified Uri with the given <paramref name=\"value\"/> serialized\n        /// as XML.\n        /// </summary>\n        /// <remarks>\n        /// This method uses the default instance of <see cref=\"XmlMediaTypeFormatter\"/>.\n        /// </remarks>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        public static Task<HttpResponseMessage> PostAsXmlAsync<T>(this HttpClient client, Uri requestUri, T value, CancellationToken cancellationToken)\n        {\n            return client.PostAsync(requestUri, value, new XmlMediaTypeFormatter(), cancellationToken);\n        }\n\n        /// <summary>\n        /// Sends a POST request as an asynchronous operation to the specified Uri with <paramref name=\"value\"/>\n        /// serialized using the given <paramref name=\"formatter\"/>.\n        /// </summary>\n        /// <seealso cref=\"PostAsync{T}(HttpClient, string, T, MediaTypeFormatter, string, CancellationToken)\"/>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <param name=\"formatter\">The formatter used to serialize the <paramref name=\"value\"/>.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"We want to support URIs as strings\")]\n        public static Task<HttpResponseMessage> PostAsync<T>(this HttpClient client, string requestUri, T value, MediaTypeFormatter formatter)\n        {\n            return client.PostAsync(requestUri, value, formatter, CancellationToken.None);\n        }\n\n        /// <summary>\n        /// Sends a POST request as an asynchronous operation to the specified Uri with <paramref name=\"value\"/>\n        /// serialized using the given <paramref name=\"formatter\"/>.\n        /// </summary>\n        /// <seealso cref=\"PostAsync{T}(HttpClient, string, T, MediaTypeFormatter, string, CancellationToken)\"/>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <param name=\"formatter\">The formatter used to serialize the <paramref name=\"value\"/>.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"We want to support URIs as strings\")]\n        public static Task<HttpResponseMessage> PostAsync<T>(this HttpClient client, string requestUri, T value, MediaTypeFormatter formatter, CancellationToken cancellationToken)\n        {\n            return client.PostAsync(requestUri, value, formatter, mediaType: (MediaTypeHeaderValue)null, cancellationToken: cancellationToken);\n        }\n\n        /// <summary>\n        /// Sends a POST request as an asynchronous operation to the specified Uri with <paramref name=\"value\"/>\n        /// serialized using the given <paramref name=\"formatter\"/>.\n        /// </summary>\n        /// <seealso cref=\"PostAsync{T}(HttpClient, string, T, MediaTypeFormatter, string, CancellationToken)\"/>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <param name=\"formatter\">The formatter used to serialize the <paramref name=\"value\"/>.</param>\n        /// <param name=\"mediaType\">The authoritative value of the request's content's Content-Type header. Can be <c>null</c> in which case the\n        /// <paramref name=\"formatter\">formatter's</paramref> default content type will be used.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"We want to support URIs as strings\")]\n        public static Task<HttpResponseMessage> PostAsync<T>(this HttpClient client, string requestUri, T value, MediaTypeFormatter formatter, string mediaType)\n        {\n            return client.PostAsync(requestUri, value, formatter, mediaType, CancellationToken.None);\n        }\n\n        /// <summary>\n        /// Sends a POST request as an asynchronous operation to the specified Uri with <paramref name=\"value\"/>\n        /// serialized using the given <paramref name=\"formatter\"/>.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <param name=\"formatter\">The formatter used to serialize the <paramref name=\"value\"/>.</param>\n        /// <param name=\"mediaType\">The authoritative value of the request's content's Content-Type header. Can be <c>null</c> in which case the\n        /// <paramref name=\"formatter\">formatter's</paramref> default content type will be used.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"We want to support URIs as strings\")]\n        public static Task<HttpResponseMessage> PostAsync<T>(this HttpClient client, string requestUri, T value, MediaTypeFormatter formatter, string mediaType, CancellationToken cancellationToken)\n        {\n            return client.PostAsync(requestUri, value, formatter, ObjectContent.BuildHeaderValue(mediaType), cancellationToken);\n        }\n\n        /// <summary>\n        /// Sends a POST request as an asynchronous operation to the specified Uri with <paramref name=\"value\"/>\n        /// serialized using the given <paramref name=\"formatter\"/>.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <param name=\"formatter\">The formatter used to serialize the <paramref name=\"value\"/>.</param>\n        /// <param name=\"mediaType\">The authoritative value of the request's content's Content-Type header. Can be <c>null</c> in which case the\n        /// <paramref name=\"formatter\">formatter's</paramref> default content type will be used.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"We want to support URIs as strings\")]\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"The caller is responsible for disposing the object\")]\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2234:PassSystemUriObjectsInsteadOfStrings\", Justification = \"The called method will convert to Uri instance.\")]\n        public static Task<HttpResponseMessage> PostAsync<T>(this HttpClient client, string requestUri, T value, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, CancellationToken cancellationToken)\n        {\n            if (client == null)\n            {\n                throw Error.ArgumentNull(\"client\");\n            }\n\n            var content = new ObjectContent<T>(value, formatter, mediaType);\n\n            return client.PostAsync(requestUri, content, cancellationToken);\n        }\n\n        /// <summary>\n        /// Sends a POST request as an asynchronous operation to the specified Uri with <paramref name=\"value\"/>\n        /// serialized using the given <paramref name=\"formatter\"/>.\n        /// </summary>\n        /// <seealso cref=\"PostAsync{T}(HttpClient, string, T, MediaTypeFormatter, string, CancellationToken)\"/>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <param name=\"formatter\">The formatter used to serialize the <paramref name=\"value\"/>.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        public static Task<HttpResponseMessage> PostAsync<T>(this HttpClient client, Uri requestUri, T value, MediaTypeFormatter formatter)\n        {\n            return client.PostAsync(requestUri, value, formatter, CancellationToken.None);\n        }\n\n        /// <summary>\n        /// Sends a POST request as an asynchronous operation to the specified Uri with <paramref name=\"value\"/>\n        /// serialized using the given <paramref name=\"formatter\"/>.\n        /// </summary>\n        /// <seealso cref=\"PostAsync{T}(HttpClient, string, T, MediaTypeFormatter, string, CancellationToken)\"/>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <param name=\"formatter\">The formatter used to serialize the <paramref name=\"value\"/>.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        public static Task<HttpResponseMessage> PostAsync<T>(this HttpClient client, Uri requestUri, T value, MediaTypeFormatter formatter, CancellationToken cancellationToken)\n        {\n            return client.PostAsync(requestUri, value, formatter, mediaType: (MediaTypeHeaderValue)null, cancellationToken: cancellationToken);\n        }\n\n        /// <summary>\n        /// Sends a POST request as an asynchronous operation to the specified Uri with <paramref name=\"value\"/>\n        /// serialized using the given <paramref name=\"formatter\"/>.\n        /// </summary>\n        /// <seealso cref=\"PostAsync{T}(HttpClient, string, T, MediaTypeFormatter, string, CancellationToken)\"/>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <param name=\"formatter\">The formatter used to serialize the <paramref name=\"value\"/>.</param>\n        /// <param name=\"mediaType\">The authoritative value of the request's content's Content-Type header. Can be <c>null</c> in which case the\n        /// <paramref name=\"formatter\">formatter's</paramref> default content type will be used.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        public static Task<HttpResponseMessage> PostAsync<T>(this HttpClient client, Uri requestUri, T value, MediaTypeFormatter formatter, string mediaType)\n        {\n            return client.PostAsync(requestUri, value, formatter, mediaType, CancellationToken.None);\n        }\n\n        /// <summary>\n        /// Sends a POST request as an asynchronous operation to the specified Uri with <paramref name=\"value\"/>\n        /// serialized using the given <paramref name=\"formatter\"/>.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <param name=\"formatter\">The formatter used to serialize the <paramref name=\"value\"/>.</param>\n        /// <param name=\"mediaType\">The authoritative value of the request's content's Content-Type header. Can be <c>null</c> in which case the\n        /// <paramref name=\"formatter\">formatter's</paramref> default content type will be used.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        public static Task<HttpResponseMessage> PostAsync<T>(this HttpClient client, Uri requestUri, T value, MediaTypeFormatter formatter, string mediaType, CancellationToken cancellationToken)\n        {\n            return client.PostAsync(requestUri, value, formatter, ObjectContent.BuildHeaderValue(mediaType), cancellationToken);\n        }\n\n        /// <summary>\n        /// Sends a POST request as an asynchronous operation to the specified Uri with <paramref name=\"value\"/>\n        /// serialized using the given <paramref name=\"formatter\"/>.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <param name=\"formatter\">The formatter used to serialize the <paramref name=\"value\"/>.</param>\n        /// <param name=\"mediaType\">The authoritative value of the request's content's Content-Type header. Can be <c>null</c> in which case the\n        /// <paramref name=\"formatter\">formatter's</paramref> default content type will be used.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"The caller is responsible for disposing the object\")]\n        public static Task<HttpResponseMessage> PostAsync<T>(this HttpClient client, Uri requestUri, T value, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, CancellationToken cancellationToken)\n        {\n            if (client == null)\n            {\n                throw Error.ArgumentNull(\"client\");\n            }\n\n            var content = new ObjectContent<T>(value, formatter, mediaType);\n\n            return client.PostAsync(requestUri, content, cancellationToken);\n        }\n\n        /// <summary>\n        /// Sends a PUT request as an asynchronous operation to the specified Uri with the given <paramref name=\"value\"/> serialized\n        /// as JSON.\n        /// </summary>\n        /// <remarks>\n        /// This method uses a default instance of <see cref=\"JsonMediaTypeFormatter\"/>.\n        /// </remarks>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"We want to support URIs as strings\")]\n        public static Task<HttpResponseMessage> PutAsJsonAsync<T>(this HttpClient client, string requestUri, T value)\n        {\n            return client.PutAsJsonAsync(requestUri, value, CancellationToken.None);\n        }\n\n        /// <summary>\n        /// Sends a PUT request as an asynchronous operation to the specified Uri with the given <paramref name=\"value\"/> serialized\n        /// as JSON.\n        /// </summary>\n        /// <remarks>\n        /// This method uses a default instance of <see cref=\"JsonMediaTypeFormatter\"/>.\n        /// </remarks>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"We want to support URIs as strings\")]\n        public static Task<HttpResponseMessage> PutAsJsonAsync<T>(this HttpClient client, string requestUri, T value, CancellationToken cancellationToken)\n        {\n            return client.PutAsync(requestUri, value, new JsonMediaTypeFormatter(), cancellationToken);\n        }\n\n        /// <summary>\n        /// Sends a PUT request as an asynchronous operation to the specified Uri with the given <paramref name=\"value\"/> serialized\n        /// as JSON.\n        /// </summary>\n        /// <remarks>\n        /// This method uses a default instance of <see cref=\"JsonMediaTypeFormatter\"/>.\n        /// </remarks>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        public static Task<HttpResponseMessage> PutAsJsonAsync<T>(this HttpClient client, Uri requestUri, T value)\n        {\n            return client.PutAsJsonAsync(requestUri, value, CancellationToken.None);\n        }\n\n        /// <summary>\n        /// Sends a PUT request as an asynchronous operation to the specified Uri with the given <paramref name=\"value\"/> serialized\n        /// as JSON.\n        /// </summary>\n        /// <remarks>\n        /// This method uses a default instance of <see cref=\"JsonMediaTypeFormatter\"/>.\n        /// </remarks>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        public static Task<HttpResponseMessage> PutAsJsonAsync<T>(this HttpClient client, Uri requestUri, T value, CancellationToken cancellationToken)\n        {\n            return client.PutAsync(requestUri, value, new JsonMediaTypeFormatter(), cancellationToken);\n        }\n\n        /// <summary>\n        /// Sends a PUT request as an asynchronous operation to the specified Uri with the given <paramref name=\"value\"/> serialized\n        /// as XML.\n        /// </summary>\n        /// <remarks>\n        /// This method uses a default instance of <see cref=\"XmlMediaTypeFormatter\"/>.\n        /// </remarks>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"We want to support URIs as strings\")]\n        public static Task<HttpResponseMessage> PutAsXmlAsync<T>(this HttpClient client, string requestUri, T value)\n        {\n            return client.PutAsXmlAsync(requestUri, value, CancellationToken.None);\n        }\n\n        /// <summary>\n        /// Sends a PUT request as an asynchronous operation to the specified Uri with the given <paramref name=\"value\"/> serialized\n        /// as XML.\n        /// </summary>\n        /// <remarks>\n        /// This method uses the default instance of <see cref=\"XmlMediaTypeFormatter\"/>.\n        /// </remarks>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"We want to support URIs as strings\")]\n        public static Task<HttpResponseMessage> PutAsXmlAsync<T>(this HttpClient client, string requestUri, T value, CancellationToken cancellationToken)\n        {\n            return client.PutAsync(requestUri, value, new XmlMediaTypeFormatter(), cancellationToken);\n        }\n\n        /// <summary>\n        /// Sends a PUT request as an asynchronous operation to the specified Uri with the given <paramref name=\"value\"/> serialized\n        /// as XML.\n        /// </summary>\n        /// <remarks>\n        /// This method uses the default instance of <see cref=\"XmlMediaTypeFormatter\"/>.\n        /// </remarks>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        public static Task<HttpResponseMessage> PutAsXmlAsync<T>(this HttpClient client, Uri requestUri, T value)\n        {\n            return client.PutAsXmlAsync(requestUri, value, CancellationToken.None);\n        }\n\n        /// <summary>\n        /// Sends a PUT request as an asynchronous operation to the specified Uri with the given <paramref name=\"value\"/> serialized\n        /// as XML.\n        /// </summary>\n        /// <remarks>\n        /// This method uses the default instance of <see cref=\"XmlMediaTypeFormatter\"/>.\n        /// </remarks>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        public static Task<HttpResponseMessage> PutAsXmlAsync<T>(this HttpClient client, Uri requestUri, T value, CancellationToken cancellationToken)\n        {\n            return client.PutAsync(requestUri, value, new XmlMediaTypeFormatter(), cancellationToken);\n        }\n\n        /// <summary>\n        /// Sends a PUT request as an asynchronous operation to the specified Uri with <paramref name=\"value\"/>\n        /// serialized using the given <paramref name=\"formatter\"/>.\n        /// </summary>\n        /// <seealso cref=\"PutAsync{T}(HttpClient, string, T, MediaTypeFormatter, string, CancellationToken)\"/>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <param name=\"formatter\">The formatter used to serialize the <paramref name=\"value\"/>.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"We want to support URIs as strings\")]\n        public static Task<HttpResponseMessage> PutAsync<T>(this HttpClient client, string requestUri, T value, MediaTypeFormatter formatter)\n        {\n            return client.PutAsync(requestUri, value, formatter, CancellationToken.None);\n        }\n\n        /// <summary>\n        /// Sends a PUT request as an asynchronous operation to the specified Uri with <paramref name=\"value\"/>\n        /// serialized using the given <paramref name=\"formatter\"/>.\n        /// </summary>\n        /// <seealso cref=\"PutAsync{T}(HttpClient, string, T, MediaTypeFormatter, string, CancellationToken)\"/>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <param name=\"formatter\">The formatter used to serialize the <paramref name=\"value\"/>.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"We want to support URIs as strings\")]\n        public static Task<HttpResponseMessage> PutAsync<T>(this HttpClient client, string requestUri, T value, MediaTypeFormatter formatter, CancellationToken cancellationToken)\n        {\n            return client.PutAsync(requestUri, value, formatter, mediaType: (MediaTypeHeaderValue)null, cancellationToken: cancellationToken);\n        }\n\n        /// <summary>\n        /// Sends a PUT request as an asynchronous operation to the specified Uri with <paramref name=\"value\"/>\n        /// serialized using the given <paramref name=\"formatter\"/>.\n        /// </summary>\n        /// <seealso cref=\"PutAsync{T}(HttpClient, string, T, MediaTypeFormatter, string, CancellationToken)\"/>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <param name=\"formatter\">The formatter used to serialize the <paramref name=\"value\"/>.</param>\n        /// <param name=\"mediaType\">The authoritative value of the request's content's Content-Type header. Can be <c>null</c> in which case the\n        /// <paramref name=\"formatter\">formatter's</paramref> default content type will be used.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"We want to support URIs as strings\")]\n        public static Task<HttpResponseMessage> PutAsync<T>(this HttpClient client, string requestUri, T value, MediaTypeFormatter formatter, string mediaType)\n        {\n            return client.PutAsync(requestUri, value, formatter, mediaType, CancellationToken.None);\n        }\n\n        /// <summary>\n        /// Sends a PUT request as an asynchronous operation to the specified Uri with <paramref name=\"value\"/>\n        /// serialized using the given <paramref name=\"formatter\"/>.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <param name=\"formatter\">The formatter used to serialize the <paramref name=\"value\"/>.</param>\n        /// <param name=\"mediaType\">The authoritative value of the request's content's Content-Type header. Can be <c>null</c> in which case the\n        /// <paramref name=\"formatter\">formatter's</paramref> default content type will be used.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"We want to support URIs as strings\")]\n        public static Task<HttpResponseMessage> PutAsync<T>(this HttpClient client, string requestUri, T value, MediaTypeFormatter formatter, string mediaType, CancellationToken cancellationToken)\n        {\n            return client.PutAsync(requestUri, value, formatter, ObjectContent.BuildHeaderValue(mediaType), cancellationToken);\n        }\n\n        /// <summary>\n        /// Sends a PUT request as an asynchronous operation to the specified Uri with <paramref name=\"value\"/>\n        /// serialized using the given <paramref name=\"formatter\"/>.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <param name=\"formatter\">The formatter used to serialize the <paramref name=\"value\"/>.</param>\n        /// <param name=\"mediaType\">The authoritative value of the request's content's Content-Type header. Can be <c>null</c> in which case the\n        /// <paramref name=\"formatter\">formatter's</paramref> default content type will be used.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"We want to support URIs as strings\")]\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"The caller is responsible for disposing the object\")]\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2234:PassSystemUriObjectsInsteadOfStrings\", Justification = \"The called method will convert to Uri instance.\")]\n        public static Task<HttpResponseMessage> PutAsync<T>(this HttpClient client, string requestUri, T value, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, CancellationToken cancellationToken)\n        {\n            if (client == null)\n            {\n                throw Error.ArgumentNull(\"client\");\n            }\n\n            var content = new ObjectContent<T>(value, formatter, mediaType);\n\n            return client.PutAsync(requestUri, content, cancellationToken);\n        }\n\n        /// <summary>\n        /// Sends a PUT request as an asynchronous operation to the specified Uri with <paramref name=\"value\"/>\n        /// serialized using the given <paramref name=\"formatter\"/>.\n        /// </summary>\n        /// <seealso cref=\"PutAsync{T}(HttpClient, string, T, MediaTypeFormatter, string, CancellationToken)\"/>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <param name=\"formatter\">The formatter used to serialize the <paramref name=\"value\"/>.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        public static Task<HttpResponseMessage> PutAsync<T>(this HttpClient client, Uri requestUri, T value, MediaTypeFormatter formatter)\n        {\n            return client.PutAsync(requestUri, value, formatter, CancellationToken.None);\n        }\n\n        /// <summary>\n        /// Sends a PUT request as an asynchronous operation to the specified Uri with <paramref name=\"value\"/>\n        /// serialized using the given <paramref name=\"formatter\"/>.\n        /// </summary>\n        /// <seealso cref=\"PutAsync{T}(HttpClient, string, T, MediaTypeFormatter, string, CancellationToken)\"/>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <param name=\"formatter\">The formatter used to serialize the <paramref name=\"value\"/>.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        public static Task<HttpResponseMessage> PutAsync<T>(this HttpClient client, Uri requestUri, T value, MediaTypeFormatter formatter, CancellationToken cancellationToken)\n        {\n            return client.PutAsync(requestUri, value, formatter, mediaType: (MediaTypeHeaderValue)null, cancellationToken: cancellationToken);\n        }\n\n        /// <summary>\n        /// Sends a PUT request as an asynchronous operation to the specified Uri with <paramref name=\"value\"/>\n        /// serialized using the given <paramref name=\"formatter\"/>.\n        /// </summary>\n        /// <seealso cref=\"PutAsync{T}(HttpClient, string, T, MediaTypeFormatter, string, CancellationToken)\"/>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <param name=\"formatter\">The formatter used to serialize the <paramref name=\"value\"/>.</param>\n        /// <param name=\"mediaType\">The authoritative value of the request's content's Content-Type header. Can be <c>null</c> in which case the\n        /// <paramref name=\"formatter\">formatter's</paramref> default content type will be used.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        public static Task<HttpResponseMessage> PutAsync<T>(this HttpClient client, Uri requestUri, T value, MediaTypeFormatter formatter, string mediaType)\n        {\n            return client.PutAsync(requestUri, value, formatter, mediaType, CancellationToken.None);\n        }\n\n        /// <summary>\n        /// Sends a PUT request as an asynchronous operation to the specified Uri with <paramref name=\"value\"/>\n        /// serialized using the given <paramref name=\"formatter\"/>.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <param name=\"formatter\">The formatter used to serialize the <paramref name=\"value\"/>.</param>\n        /// <param name=\"mediaType\">The authoritative value of the request's content's Content-Type header. Can be <c>null</c> in which case the\n        /// <paramref name=\"formatter\">formatter's</paramref> default content type will be used.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        public static Task<HttpResponseMessage> PutAsync<T>(this HttpClient client, Uri requestUri, T value, MediaTypeFormatter formatter, string mediaType, CancellationToken cancellationToken)\n        {\n            return client.PutAsync(requestUri, value, formatter, ObjectContent.BuildHeaderValue(mediaType), cancellationToken);\n        }\n\n        /// <summary>\n        /// Sends a PUT request as an asynchronous operation to the specified Uri with <paramref name=\"value\"/>\n        /// serialized using the given <paramref name=\"formatter\"/>.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of <paramref name=\"value\"/>.</typeparam>\n        /// <param name=\"client\">The client used to make the request.</param>\n        /// <param name=\"requestUri\">The Uri the request is sent to.</param>\n        /// <param name=\"value\">The value that will be placed in the request's entity body.</param>\n        /// <param name=\"formatter\">The formatter used to serialize the <paramref name=\"value\"/>.</param>\n        /// <param name=\"mediaType\">The authoritative value of the request's content's Content-Type header. Can be <c>null</c> in which case the\n        /// <paramref name=\"formatter\">formatter's</paramref> default content type will be used.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing the asynchronous operation.</returns>\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"The caller is responsible for disposing the object\")]\n        public static Task<HttpResponseMessage> PutAsync<T>(this HttpClient client, Uri requestUri, T value, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, CancellationToken cancellationToken)\n        {\n            if (client == null)\n            {\n                throw Error.ArgumentNull(\"client\");\n            }\n\n            var content = new ObjectContent<T>(value, formatter, mediaType);\n\n            return client.PutAsync(requestUri, content, cancellationToken);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/HttpClientFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Web.Http;\n\nnamespace System.Net.Http\n{\n    public static class HttpClientFactory\n    {\n        /// <summary>\n        /// Creates a new <see cref=\"HttpClient\"/> instance configured with the handlers provided and with an\n        /// <see cref=\"HttpClientHandler\"/> as the innermost handler.\n        /// </summary>\n        /// <param name=\"handlers\">An ordered list of <see cref=\"DelegatingHandler\"/> instances to be invoked as an \n        /// <see cref=\"HttpRequestMessage\"/> travels from the <see cref=\"HttpClient\"/> to the network and an \n        /// <see cref=\"HttpResponseMessage\"/> travels from the network back to <see cref=\"HttpClient\"/>.\n        /// The handlers are invoked in a top-down fashion. That is, the first entry is invoked first for \n        /// an outbound request message but last for an inbound response message.</param>\n        /// <returns>An <see cref=\"HttpClient\"/> instance with the configured handlers.</returns>\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"Handler is disposed with HttpClient\")]\n        public static HttpClient Create(params DelegatingHandler[] handlers)\n        {\n            return Create(new HttpClientHandler(), handlers);\n        }\n\n        /// <summary>\n        /// Creates a new <see cref=\"HttpClient\"/> instance configured with the handlers provided and with the\n        /// provided <paramref name=\"innerHandler\"/> as the innermost handler.\n        /// </summary>\n        /// <param name=\"innerHandler\">The inner handler represents the destination of the HTTP message channel.</param>\n        /// <param name=\"handlers\">An ordered list of <see cref=\"DelegatingHandler\"/> instances to be invoked as an \n        /// <see cref=\"HttpRequestMessage\"/> travels from the <see cref=\"HttpClient\"/> to the network and an \n        /// <see cref=\"HttpResponseMessage\"/> travels from the network back to <see cref=\"HttpClient\"/>.\n        /// The handlers are invoked in a top-down fashion. That is, the first entry is invoked first for \n        /// an outbound request message but last for an inbound response message.</param>\n        /// <returns>An <see cref=\"HttpClient\"/> instance with the configured handlers.</returns>\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"Handler is disposed with HttpClient\")]\n        public static HttpClient Create(HttpMessageHandler innerHandler, params DelegatingHandler[] handlers)\n        {\n            HttpMessageHandler pipeline = CreatePipeline(innerHandler, handlers);\n            return new HttpClient(pipeline);\n        }\n\n        /// <summary>\n        /// Creates an instance of an <see cref=\"HttpMessageHandler\"/> using the <see cref=\"DelegatingHandler\"/> instances\n        /// provided by <paramref name=\"handlers\"/>. The resulting pipeline can be used to manually create <see cref=\"HttpClient\"/>\n        /// or <see cref=\"HttpMessageInvoker\"/> instances with customized message handlers.\n        /// </summary>\n        /// <param name=\"innerHandler\">The inner handler represents the destination of the HTTP message channel.</param>\n        /// <param name=\"handlers\">An ordered list of <see cref=\"DelegatingHandler\"/> instances to be invoked as part \n        /// of sending an <see cref=\"HttpRequestMessage\"/> and receiving an <see cref=\"HttpResponseMessage\"/>.\n        /// The handlers are invoked in a top-down fashion. That is, the first entry is invoked first for \n        /// an outbound request message but last for an inbound response message.</param>\n        /// <returns>The HTTP message channel.</returns>\n        public static HttpMessageHandler CreatePipeline(HttpMessageHandler innerHandler, IEnumerable<DelegatingHandler> handlers)\n        {\n            if (innerHandler == null)\n            {\n                throw Error.ArgumentNull(\"innerHandler\");\n            }\n\n            if (handlers == null)\n            {\n                return innerHandler;\n            }\n\n            // Wire handlers up in reverse order starting with the inner handler\n            HttpMessageHandler pipeline = innerHandler;\n            IEnumerable<DelegatingHandler> reversedHandlers = handlers.Reverse();\n            foreach (DelegatingHandler handler in reversedHandlers)\n            {\n                if (handler == null)\n                {\n                    throw Error.Argument(\"handlers\", Properties.Resources.DelegatingHandlerArrayContainsNullItem, typeof(DelegatingHandler).Name);\n                }\n\n                if (handler.InnerHandler != null)\n                {\n                    throw Error.Argument(\"handlers\", Properties.Resources.DelegatingHandlerArrayHasNonNullInnerHandler, typeof(DelegatingHandler).Name, \"InnerHandler\", handler.GetType().Name);\n                }\n\n                handler.InnerHandler = pipeline;\n                pipeline = handler;\n            }\n\n            return pipeline;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/HttpContentExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.IO;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// Extension methods to allow strongly typed objects to be read from <see cref=\"HttpContent\"/> instances.\n    /// </summary>\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class HttpContentExtensions\n    {\n        private static MediaTypeFormatterCollection _defaultMediaTypeFormatterCollection = null;\n\n        // Using the JsonMediaTypeFormatter for the first time is rather expensive (due to reflection cost\n        // when creating the default contract resolver). Hence we new up a static collection, such\n        // that the second call is much faster.\n        private static MediaTypeFormatterCollection DefaultMediaTypeFormatterCollection\n        {\n            get\n            {\n                if (_defaultMediaTypeFormatterCollection == null)\n                {\n                    _defaultMediaTypeFormatterCollection = new MediaTypeFormatterCollection();\n                }\n\n                return _defaultMediaTypeFormatterCollection;\n            }\n        }\n\n        /// <summary>\n        /// Returns a <see cref=\"Task\"/> that will yield an object of the specified <paramref name=\"type\"/>\n        /// from the <paramref name=\"content\"/> instance.\n        /// </summary>\n        /// <remarks>This override use the built-in collection of formatters.</remarks>\n        /// <param name=\"content\">The <see cref=\"HttpContent\"/> instance from which to read.</param>\n        /// <param name=\"type\">The type of the object to read.</param>\n        /// <returns>A task object representing reading the content as an object of the specified type.</returns>\n        public static Task<object> ReadAsAsync(this HttpContent content, Type type)\n        {\n            return content.ReadAsAsync(type, DefaultMediaTypeFormatterCollection);\n        }\n\n        /// <summary>\n        /// Returns a <see cref=\"Task\"/> that will yield an object of the specified <paramref name=\"type\"/>\n        /// from the <paramref name=\"content\"/> instance.\n        /// </summary>\n        /// <remarks>This override use the built-in collection of formatters.</remarks>\n        /// <param name=\"content\">The <see cref=\"HttpContent\"/> instance from which to read.</param>\n        /// <param name=\"type\">The type of the object to read.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing reading the content as an object of the specified type.</returns>\n        public static Task<object> ReadAsAsync(this HttpContent content, Type type, CancellationToken cancellationToken)\n        {\n            return content.ReadAsAsync(type, DefaultMediaTypeFormatterCollection, cancellationToken);\n        }\n\n        /// <summary>\n        /// Returns a <see cref=\"Task\"/> that will yield an object of the specified <paramref name=\"type\"/>\n        /// from the <paramref name=\"content\"/> instance using one of the provided <paramref name=\"formatters\"/>\n        /// to deserialize the content.\n        /// </summary>\n        /// <param name=\"content\">The <see cref=\"HttpContent\"/> instance from which to read.</param>\n        /// <param name=\"type\">The type of the object to read.</param>\n        /// <param name=\"formatters\">The collection of <see cref=\"MediaTypeFormatter\"/> instances to use.</param>\n        /// <returns>A task object representing reading the content as an object of the specified type.</returns>\n        public static Task<object> ReadAsAsync(this HttpContent content, Type type, IEnumerable<MediaTypeFormatter> formatters)\n        {\n            return ReadAsAsync<object>(content, type, formatters, null);\n        }\n\n        /// <summary>\n        /// Returns a <see cref=\"Task\"/> that will yield an object of the specified <paramref name=\"type\"/>\n        /// from the <paramref name=\"content\"/> instance using one of the provided <paramref name=\"formatters\"/>\n        /// to deserialize the content.\n        /// </summary>\n        /// <param name=\"content\">The <see cref=\"HttpContent\"/> instance from which to read.</param>\n        /// <param name=\"type\">The type of the object to read.</param>\n        /// <param name=\"formatters\">The collection of <see cref=\"MediaTypeFormatter\"/> instances to use.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing reading the content as an object of the specified type.</returns>\n        public static Task<object> ReadAsAsync(this HttpContent content, Type type, IEnumerable<MediaTypeFormatter> formatters,\n            CancellationToken cancellationToken)\n        {\n            return ReadAsAsync<object>(content, type, formatters, null, cancellationToken);\n        }\n\n        /// <summary>\n        /// Returns a <see cref=\"Task\"/> that will yield an object of the specified <paramref name=\"type\"/>\n        /// from the <paramref name=\"content\"/> instance using one of the provided <paramref name=\"formatters\"/>\n        /// to deserialize the content.\n        /// </summary>\n        /// <param name=\"content\">The <see cref=\"HttpContent\"/> instance from which to read.</param>\n        /// <param name=\"type\">The type of the object to read.</param>\n        /// <param name=\"formatters\">The collection of <see cref=\"MediaTypeFormatter\"/> instances to use.</param>\n        /// <param name=\"formatterLogger\">The <see cref=\"IFormatterLogger\"/> to log events to.</param>\n        /// <returns>A task object representing reading the content as an object of the specified type.</returns>\n        public static Task<object> ReadAsAsync(this HttpContent content, Type type, IEnumerable<MediaTypeFormatter> formatters,\n            IFormatterLogger formatterLogger)\n        {\n            return ReadAsAsync<object>(content, type, formatters, formatterLogger);\n        }\n\n        /// <summary>\n        /// Returns a <see cref=\"Task\"/> that will yield an object of the specified <paramref name=\"type\"/>\n        /// from the <paramref name=\"content\"/> instance using one of the provided <paramref name=\"formatters\"/>\n        /// to deserialize the content.\n        /// </summary>\n        /// <param name=\"content\">The <see cref=\"HttpContent\"/> instance from which to read.</param>\n        /// <param name=\"type\">The type of the object to read.</param>\n        /// <param name=\"formatters\">The collection of <see cref=\"MediaTypeFormatter\"/> instances to use.</param>\n        /// <param name=\"formatterLogger\">The <see cref=\"IFormatterLogger\"/> to log events to.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing reading the content as an object of the specified type.</returns>\n        public static Task<object> ReadAsAsync(this HttpContent content, Type type, IEnumerable<MediaTypeFormatter> formatters,\n            IFormatterLogger formatterLogger, CancellationToken cancellationToken)\n        {\n            return ReadAsAsync<object>(content, type, formatters, formatterLogger, cancellationToken);\n        }\n\n        /// <summary>\n        /// Returns a <see cref=\"Task\"/> that will yield an object of the specified\n        /// type <typeparamref name=\"T\"/> from the <paramref name=\"content\"/> instance.\n        /// </summary>\n        /// <remarks>This override use the built-in collection of formatters.</remarks>\n        /// <typeparam name=\"T\">The type of the object to read.</typeparam>\n        /// <param name=\"content\">The <see cref=\"HttpContent\"/> instance from which to read.</param>\n        /// <returns>A task object representing reading the content as an object of the specified type.</returns>\n        public static Task<T> ReadAsAsync<T>(this HttpContent content)\n        {\n            return content.ReadAsAsync<T>(DefaultMediaTypeFormatterCollection);\n        }\n\n        /// <summary>\n        /// Returns a <see cref=\"Task\"/> that will yield an object of the specified\n        /// type <typeparamref name=\"T\"/> from the <paramref name=\"content\"/> instance.\n        /// </summary>\n        /// <remarks>This override use the built-in collection of formatters.</remarks>\n        /// <typeparam name=\"T\">The type of the object to read.</typeparam>\n        /// <param name=\"content\">The <see cref=\"HttpContent\"/> instance from which to read.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing reading the content as an object of the specified type.</returns>\n        public static Task<T> ReadAsAsync<T>(this HttpContent content, CancellationToken cancellationToken)\n        {\n            return content.ReadAsAsync<T>(DefaultMediaTypeFormatterCollection, cancellationToken);\n        }\n\n        /// <summary>\n        /// Returns a <see cref=\"Task\"/> that will yield an object of the specified\n        /// type <typeparamref name=\"T\"/> from the <paramref name=\"content\"/> instance.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of the object to read.</typeparam>\n        /// <param name=\"content\">The <see cref=\"HttpContent\"/> instance from which to read.</param>\n        /// <param name=\"formatters\">The collection of <see cref=\"MediaTypeFormatter\"/> instances to use.</param>\n        /// <returns>A task object representing reading the content as an object of the specified type.</returns>\n        public static Task<T> ReadAsAsync<T>(this HttpContent content, IEnumerable<MediaTypeFormatter> formatters)\n        {\n            return ReadAsAsync<T>(content, typeof(T), formatters, null);\n        }\n\n        /// <summary>\n        /// Returns a <see cref=\"Task\"/> that will yield an object of the specified\n        /// type <typeparamref name=\"T\"/> from the <paramref name=\"content\"/> instance.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of the object to read.</typeparam>\n        /// <param name=\"content\">The <see cref=\"HttpContent\"/> instance from which to read.</param>\n        /// <param name=\"formatters\">The collection of <see cref=\"MediaTypeFormatter\"/> instances to use.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing reading the content as an object of the specified type.</returns>\n        public static Task<T> ReadAsAsync<T>(this HttpContent content, IEnumerable<MediaTypeFormatter> formatters,\n            CancellationToken cancellationToken)\n        {\n            return ReadAsAsync<T>(content, typeof(T), formatters, null, cancellationToken);\n        }\n\n        /// <summary>\n        /// Returns a <see cref=\"Task\"/> that will yield an object of the specified\n        /// type <typeparamref name=\"T\"/> from the <paramref name=\"content\"/> instance.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of the object to read.</typeparam>\n        /// <param name=\"content\">The <see cref=\"HttpContent\"/> instance from which to read.</param>\n        /// <param name=\"formatters\">The collection of <see cref=\"MediaTypeFormatter\"/> instances to use.</param>\n        /// <param name=\"formatterLogger\">The <see cref=\"IFormatterLogger\"/> to log events to.</param>\n        /// <returns>A task object representing reading the content as an object of the specified type.</returns>\n        public static Task<T> ReadAsAsync<T>(this HttpContent content, IEnumerable<MediaTypeFormatter> formatters,\n            IFormatterLogger formatterLogger)\n        {\n            return ReadAsAsync<T>(content, typeof(T), formatters, formatterLogger);\n        }\n\n        /// <summary>\n        /// Returns a <see cref=\"Task\"/> that will yield an object of the specified\n        /// type <typeparamref name=\"T\"/> from the <paramref name=\"content\"/> instance.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of the object to read.</typeparam>\n        /// <param name=\"content\">The <see cref=\"HttpContent\"/> instance from which to read.</param>\n        /// <param name=\"formatters\">The collection of <see cref=\"MediaTypeFormatter\"/> instances to use.</param>\n        /// <param name=\"formatterLogger\">The <see cref=\"IFormatterLogger\"/> to log events to.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing reading the content as an object of the specified type.</returns>\n        public static Task<T> ReadAsAsync<T>(this HttpContent content, IEnumerable<MediaTypeFormatter> formatters,\n            IFormatterLogger formatterLogger, CancellationToken cancellationToken)\n        {\n            return ReadAsAsync<T>(content, typeof(T), formatters, formatterLogger, cancellationToken);\n        }\n\n        private static Task<T> ReadAsAsync<T>(HttpContent content, Type type, IEnumerable<MediaTypeFormatter> formatters,\n            IFormatterLogger formatterLogger)\n        {\n            return ReadAsAsync<T>(content, type, formatters, formatterLogger, CancellationToken.None);\n        }\n\n        // There are many helper overloads for ReadAs*(). Provide one worker function to ensure the logic is shared.\n        //\n        // For loosely typed, T = Object, type = specific class.\n        // For strongly typed, T == type.GetType()\n        private static Task<T> ReadAsAsync<T>(HttpContent content, Type type, IEnumerable<MediaTypeFormatter> formatters,\n            IFormatterLogger formatterLogger, CancellationToken cancellationToken)\n        {\n            if (content == null)\n            {\n                throw Error.ArgumentNull(\"content\");\n            }\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n            if (formatters == null)\n            {\n                throw Error.ArgumentNull(\"formatters\");\n            }\n\n            ObjectContent objectContent = content as ObjectContent;\n            if (objectContent != null && objectContent.Value != null && type.IsAssignableFrom(objectContent.Value.GetType()))\n            {\n                return Task.FromResult((T)objectContent.Value);\n            }\n\n            MediaTypeFormatter formatter = null;\n            // Default to \"application/octet-stream\" if there is no content-type in accordance with section 7.2.1 of the HTTP spec\n            MediaTypeHeaderValue mediaType = content.Headers.ContentType ?? MediaTypeConstants.ApplicationOctetStreamMediaType;\n\n            formatter = new MediaTypeFormatterCollection(formatters).FindReader(type, mediaType);\n\n            if (formatter == null)\n            {\n                if (content.Headers.ContentLength == 0)\n                {\n                    T defaultValue = (T)MediaTypeFormatter.GetDefaultValueForType(type);\n                    return Task.FromResult<T>(defaultValue);\n                }\n\n                throw new UnsupportedMediaTypeException(\n                    Error.Format(Properties.Resources.NoReadSerializerAvailable, type.Name, mediaType.MediaType),\n                    mediaType);\n            }\n\n            return ReadAsAsyncCore<T>(content, type, formatterLogger, formatter, cancellationToken);\n        }\n\n        private static async Task<T> ReadAsAsyncCore<T>(HttpContent content, Type type, IFormatterLogger formatterLogger,\n            MediaTypeFormatter formatter, CancellationToken cancellationToken)\n        {\n            cancellationToken.ThrowIfCancellationRequested();\n            Stream stream = await content.ReadAsStreamAsync();\n\n            object result = await formatter.ReadFromStreamAsync(type, stream, content, formatterLogger, cancellationToken);\n            return (T)result;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/HttpContentFormDataExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing System.ComponentModel;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// Extension methods to allow HTML form URL-encoded data, also known as <c>application/x-www-form-urlencoded</c>,\n    /// to be read from <see cref=\"HttpContent\"/> instances.\n    /// </summary>\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class HttpContentFormDataExtensions\n    {\n        private const string ApplicationFormUrlEncoded = \"application/x-www-form-urlencoded\";\n\n        /// <summary>\n        /// Determines whether the specified content is HTML form URL-encoded data, also known as <c>application/x-www-form-urlencoded</c> data.\n        /// </summary>\n        /// <param name=\"content\">The content.</param>\n        /// <returns>\n        /// <c>true</c> if the specified content is HTML form URL-encoded data; otherwise, <c>false</c>.\n        /// </returns>\n        public static bool IsFormData(this HttpContent content)\n        {\n            if (content == null)\n            {\n                throw Error.ArgumentNull(\"content\");\n            }\n\n            MediaTypeHeaderValue contentType = content.Headers.ContentType;\n            return contentType != null && String.Equals(ApplicationFormUrlEncoded, contentType.MediaType, StringComparison.OrdinalIgnoreCase);\n        }\n\n        /// <summary>\n        /// Returns a <see cref=\"Task{T}\"/> that will yield a <see cref=\"NameValueCollection\"/> instance containing the form data\n        /// parsed as HTML form URL-encoded from the <paramref name=\"content\"/> instance.\n        /// </summary>\n        /// <param name=\"content\">The content.</param>\n        /// <returns>A <see cref=\"Task{T}\"/> which will provide the result. If the data can not be read\n        /// as HTML form URL-encoded data then the result is null.</returns>\n        public static Task<NameValueCollection> ReadAsFormDataAsync(this HttpContent content)\n        {\n            return ReadAsFormDataAsync(content, CancellationToken.None);\n        }\n\n        /// <summary>\n        /// Returns a <see cref=\"Task{T}\"/> that will yield a <see cref=\"NameValueCollection\"/> instance containing the form data\n        /// parsed as HTML form URL-encoded from the <paramref name=\"content\"/> instance.\n        /// </summary>\n        /// <param name=\"content\">The content.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A <see cref=\"Task{T}\"/> which will provide the result. If the data can not be read\n        /// as HTML form URL-encoded data then the result is null.</returns>\n        public static Task<NameValueCollection> ReadAsFormDataAsync(this HttpContent content, CancellationToken cancellationToken)\n        {\n            if (content == null)\n            {\n                throw Error.ArgumentNull(\"content\");\n            }\n\n            MediaTypeFormatter[] formatters = new MediaTypeFormatter[1] { new FormUrlEncodedMediaTypeFormatter() };\n            return ReadAsAsyncCore(content, formatters, cancellationToken);\n        }\n\n        private static async Task<NameValueCollection> ReadAsAsyncCore(HttpContent content, MediaTypeFormatter[] formatters,\n            CancellationToken cancellationToken)\n        {\n            FormDataCollection formData = await content.ReadAsAsync<FormDataCollection>(formatters, cancellationToken);\n            return formData == null ? null : formData.ReadAsNameValueCollection();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/HttpContentMessageExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Net.Http.Formatting.Parsers;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// Extension methods to read <see cref=\"HttpRequestMessage\"/> and <see cref=\"HttpResponseMessage\"/> entities from <see cref=\"HttpContent\"/> instances.\n    /// </summary>\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class HttpContentMessageExtensions\n    {\n        private const int MinBufferSize = 256;\n        private const int DefaultBufferSize = 32 * 1024;\n\n        /// <summary>\n        /// Determines whether the specified content is HTTP request message content.\n        /// </summary>\n        /// <param name=\"content\">The content.</param>\n        /// <returns>\n        ///   <c>true</c> if the specified content is HTTP message content; otherwise, <c>false</c>.\n        /// </returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Exception translates to false.\")]\n        public static bool IsHttpRequestMessageContent(this HttpContent content)\n        {\n            if (content == null)\n            {\n                throw Error.ArgumentNull(\"content\");\n            }\n\n            try\n            {\n                return HttpMessageContent.ValidateHttpMessageContent(content, true, false);\n            }\n            catch (Exception)\n            {\n                return false;\n            }\n        }\n\n        /// <summary>\n        /// Determines whether the specified content is HTTP response message content.\n        /// </summary>\n        /// <param name=\"content\">The content.</param>\n        /// <returns>\n        ///   <c>true</c> if the specified content is HTTP message content; otherwise, <c>false</c>.\n        /// </returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Exception translates to false.\")]\n        public static bool IsHttpResponseMessageContent(this HttpContent content)\n        {\n            if (content == null)\n            {\n                throw Error.ArgumentNull(\"content\");\n            }\n\n            try\n            {\n                return HttpMessageContent.ValidateHttpMessageContent(content, false, false);\n            }\n            catch (Exception)\n            {\n                return false;\n            }\n        }\n\n        /// <summary>\n        /// Read the <see cref=\"HttpContent\"/> as an <see cref=\"HttpRequestMessage\"/>.\n        /// </summary>\n        /// <param name=\"content\">The content to read.</param>\n        /// <returns>A task object representing reading the content as an <see cref=\"HttpRequestMessage\"/>.</returns>\n        public static Task<HttpRequestMessage> ReadAsHttpRequestMessageAsync(this HttpContent content)\n        {\n            return ReadAsHttpRequestMessageAsync(content, \"http\", DefaultBufferSize);\n        }\n\n        /// <summary>\n        /// Read the <see cref=\"HttpContent\"/> as an <see cref=\"HttpRequestMessage\"/>.\n        /// </summary>\n        /// <param name=\"content\">The content to read.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing reading the content as an <see cref=\"HttpRequestMessage\"/>.</returns>\n        public static Task<HttpRequestMessage> ReadAsHttpRequestMessageAsync(this HttpContent content, CancellationToken cancellationToken)\n        {\n            return ReadAsHttpRequestMessageAsync(content, \"http\", DefaultBufferSize, cancellationToken);\n        }\n\n        /// <summary>\n        /// Read the <see cref=\"HttpContent\"/> as an <see cref=\"HttpRequestMessage\"/>.\n        /// </summary>\n        /// <param name=\"content\">The content to read.</param>\n        /// <param name=\"uriScheme\">The URI scheme to use for the request URI.</param>\n        /// <returns>A task object representing reading the content as an <see cref=\"HttpRequestMessage\"/>.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"This is not a full URI but only the URI scheme\")]\n        public static Task<HttpRequestMessage> ReadAsHttpRequestMessageAsync(this HttpContent content, string uriScheme)\n        {\n            return ReadAsHttpRequestMessageAsync(content, uriScheme, DefaultBufferSize);\n        }\n\n        /// <summary>\n        /// Read the <see cref=\"HttpContent\"/> as an <see cref=\"HttpRequestMessage\"/>.\n        /// </summary>\n        /// <param name=\"content\">The content to read.</param>\n        /// <param name=\"uriScheme\">The URI scheme to use for the request URI.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing reading the content as an <see cref=\"HttpRequestMessage\"/>.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"This is not a full URI but only the URI scheme\")]\n        public static Task<HttpRequestMessage> ReadAsHttpRequestMessageAsync(this HttpContent content, string uriScheme,\n            CancellationToken cancellationToken)\n        {\n            return ReadAsHttpRequestMessageAsync(content, uriScheme, DefaultBufferSize, cancellationToken);\n        }\n\n        /// <summary>\n        /// Read the <see cref=\"HttpContent\"/> as an <see cref=\"HttpRequestMessage\"/>.\n        /// </summary>\n        /// <param name=\"content\">The content to read.</param>\n        /// <param name=\"uriScheme\">The URI scheme to use for the request URI (the\n        /// URI scheme is not actually part of the HTTP Request URI and so must be provided externally).</param>\n        /// <param name=\"bufferSize\">Size of the buffer.</param>\n        /// <returns>A task object representing reading the content as an <see cref=\"HttpRequestMessage\"/>.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"This is not a full URI but only the URI scheme\")]\n        public static Task<HttpRequestMessage> ReadAsHttpRequestMessageAsync(this HttpContent content, string uriScheme, int bufferSize)\n        {\n            return ReadAsHttpRequestMessageAsync(content, uriScheme, bufferSize, HttpRequestHeaderParser.DefaultMaxHeaderSize);\n        }\n\n        /// <summary>\n        /// Read the <see cref=\"HttpContent\"/> as an <see cref=\"HttpRequestMessage\"/>.\n        /// </summary>\n        /// <param name=\"content\">The content to read.</param>\n        /// <param name=\"uriScheme\">The URI scheme to use for the request URI (the\n        /// URI scheme is not actually part of the HTTP Request URI and so must be provided externally).</param>\n        /// <param name=\"bufferSize\">Size of the buffer.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing reading the content as an <see cref=\"HttpRequestMessage\"/>.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"This is not a full URI but only the URI scheme\")]\n        public static Task<HttpRequestMessage> ReadAsHttpRequestMessageAsync(this HttpContent content, string uriScheme,\n            int bufferSize, CancellationToken cancellationToken)\n        {\n            return ReadAsHttpRequestMessageAsync(content, uriScheme, bufferSize,\n                HttpRequestHeaderParser.DefaultMaxHeaderSize, cancellationToken);\n        }\n\n        /// <summary>\n        /// Read the <see cref=\"HttpContent\"/> as an <see cref=\"HttpRequestMessage\"/>.\n        /// </summary>\n        /// <param name=\"content\">The content to read.</param>\n        /// <param name=\"uriScheme\">The URI scheme to use for the request URI (the\n        /// URI scheme is not actually part of the HTTP Request URI and so must be provided externally).</param>\n        /// <param name=\"bufferSize\">Size of the buffer.</param>\n        /// <param name=\"maxHeaderSize\">The max length of the HTTP header.</param>\n        /// <returns>A task object representing reading the content as an <see cref=\"HttpRequestMessage\"/>.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"This is not a full URI but only the URI scheme\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Exception translates to parser state.\")]\n        public static Task<HttpRequestMessage> ReadAsHttpRequestMessageAsync(this HttpContent content, string uriScheme,\n            int bufferSize, int maxHeaderSize)\n        {\n            return ReadAsHttpRequestMessageAsync(content, uriScheme, bufferSize, maxHeaderSize, CancellationToken.None);\n        }\n\n        /// <summary>\n        /// Read the <see cref=\"HttpContent\"/> as an <see cref=\"HttpRequestMessage\"/>.\n        /// </summary>\n        /// <param name=\"content\">The content to read.</param>\n        /// <param name=\"uriScheme\">The URI scheme to use for the request URI (the\n        /// URI scheme is not actually part of the HTTP Request URI and so must be provided externally).</param>\n        /// <param name=\"bufferSize\">Size of the buffer.</param>\n        /// <param name=\"maxHeaderSize\">The max length of the HTTP header.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing reading the content as an <see cref=\"HttpRequestMessage\"/>.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"This is not a full URI but only the URI scheme\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Exception translates to parser state.\")]\n        public static Task<HttpRequestMessage> ReadAsHttpRequestMessageAsync(this HttpContent content, string uriScheme,\n            int bufferSize, int maxHeaderSize, CancellationToken cancellationToken)\n        {\n            if (content == null)\n            {\n                throw Error.ArgumentNull(\"content\");\n            }\n\n            if (uriScheme == null)\n            {\n                throw Error.ArgumentNull(\"uriScheme\");\n            }\n\n            if (!Uri.CheckSchemeName(uriScheme))\n            {\n                throw Error.Argument(\"uriScheme\", Properties.Resources.HttpMessageParserInvalidUriScheme, uriScheme, typeof(Uri).Name);\n            }\n\n            if (bufferSize < MinBufferSize)\n            {\n                throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"bufferSize\", bufferSize, MinBufferSize);\n            }\n\n            if (maxHeaderSize < InternetMessageFormatHeaderParser.MinHeaderSize)\n            {\n                throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"maxHeaderSize\", maxHeaderSize, InternetMessageFormatHeaderParser.MinHeaderSize);\n            }\n\n            HttpMessageContent.ValidateHttpMessageContent(content, true, true);\n\n            return content.ReadAsHttpRequestMessageAsyncCore(uriScheme, bufferSize, maxHeaderSize, cancellationToken);\n        }\n\n        private static async Task<HttpRequestMessage> ReadAsHttpRequestMessageAsyncCore(this HttpContent content,\n            string uriScheme, int bufferSize, int maxHeaderSize, CancellationToken cancellationToken)\n        {\n            cancellationToken.ThrowIfCancellationRequested();\n            Stream stream = await content.ReadAsStreamAsync();\n\n            HttpUnsortedRequest httpRequest = new HttpUnsortedRequest();\n            HttpRequestHeaderParser parser = new HttpRequestHeaderParser(httpRequest,\n                Math.Max(HttpRequestHeaderParser.DefaultMaxRequestLineSize, maxHeaderSize), maxHeaderSize);\n            ParserState parseStatus;\n\n            byte[] buffer = new byte[bufferSize];\n            int bytesRead = 0;\n            int headerConsumed = 0;\n\n            while (true)\n            {\n                try\n                {\n                    bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken);\n                }\n                catch (Exception e)\n                {\n                    throw new IOException(Properties.Resources.HttpMessageErrorReading, e);\n                }\n\n                try\n                {\n                    parseStatus = parser.ParseBuffer(buffer, bytesRead, ref headerConsumed);\n                }\n                catch (Exception)\n                {\n                    parseStatus = ParserState.Invalid;\n                }\n\n                if (parseStatus == ParserState.Done)\n                {\n                    return CreateHttpRequestMessage(uriScheme, httpRequest, stream, bytesRead - headerConsumed);\n                }\n                else if (parseStatus != ParserState.NeedMoreData)\n                {\n                    throw Error.InvalidOperation(Properties.Resources.HttpMessageParserError, headerConsumed, buffer);\n                }\n                else if (bytesRead == 0)\n                {\n                    throw new IOException(Properties.Resources.ReadAsHttpMessageUnexpectedTermination);\n                }\n            }\n        }\n\n        /// <summary>\n        /// Read the <see cref=\"HttpContent\"/> as an <see cref=\"HttpResponseMessage\"/>.\n        /// </summary>\n        /// <param name=\"content\">The content to read.</param>\n        /// <returns>A task object representing reading the content as an <see cref=\"HttpResponseMessage\"/>.</returns>\n        public static Task<HttpResponseMessage> ReadAsHttpResponseMessageAsync(this HttpContent content)\n        {\n            return ReadAsHttpResponseMessageAsync(content, DefaultBufferSize);\n        }\n\n        /// <summary>\n        /// Read the <see cref=\"HttpContent\"/> as an <see cref=\"HttpResponseMessage\"/>.\n        /// </summary>\n        /// <param name=\"content\">The content to read.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing reading the content as an <see cref=\"HttpResponseMessage\"/>.</returns>\n        public static Task<HttpResponseMessage> ReadAsHttpResponseMessageAsync(this HttpContent content, CancellationToken cancellationToken)\n        {\n            return ReadAsHttpResponseMessageAsync(content, DefaultBufferSize, cancellationToken);\n        }\n\n        /// <summary>\n        /// Read the <see cref=\"HttpContent\"/> as an <see cref=\"HttpResponseMessage\"/>.\n        /// </summary>\n        /// <param name=\"content\">The content to read.</param>\n        /// <param name=\"bufferSize\">Size of the buffer.</param>\n        /// <returns>A task object representing reading the content as an <see cref=\"HttpResponseMessage\"/>.</returns>\n        public static Task<HttpResponseMessage> ReadAsHttpResponseMessageAsync(this HttpContent content, int bufferSize)\n        {\n            return ReadAsHttpResponseMessageAsync(content, bufferSize, HttpResponseHeaderParser.DefaultMaxHeaderSize);\n        }\n\n        /// <summary>\n        /// Read the <see cref=\"HttpContent\"/> as an <see cref=\"HttpResponseMessage\"/>.\n        /// </summary>\n        /// <param name=\"content\">The content to read.</param>\n        /// <param name=\"bufferSize\">Size of the buffer.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task object representing reading the content as an <see cref=\"HttpResponseMessage\"/>.</returns>\n        public static Task<HttpResponseMessage> ReadAsHttpResponseMessageAsync(this HttpContent content, int bufferSize,\n            CancellationToken cancellationToken)\n        {\n            return ReadAsHttpResponseMessageAsync(content, bufferSize, HttpResponseHeaderParser.DefaultMaxHeaderSize, cancellationToken);\n        }\n\n        /// <summary>\n        /// Read the <see cref=\"HttpContent\"/> as an <see cref=\"HttpResponseMessage\"/>.\n        /// </summary>\n        /// <param name=\"content\">The content to read.</param>\n        /// <param name=\"bufferSize\">Size of the buffer.</param>\n        /// <param name=\"maxHeaderSize\">The max length of the HTTP header.</param>\n        /// <returns>A task object representing reading the content as an <see cref=\"HttpResponseMessage\"/>.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Exception translates to parser state.\")]\n        public static Task<HttpResponseMessage> ReadAsHttpResponseMessageAsync(this HttpContent content, int bufferSize,\n            int maxHeaderSize)\n        {\n            return ReadAsHttpResponseMessageAsync(content, bufferSize, maxHeaderSize, CancellationToken.None);\n        }\n\n        /// <summary>\n        /// Read the <see cref=\"HttpContent\"/> as an <see cref=\"HttpResponseMessage\"/>.\n        /// </summary>\n        /// <param name=\"content\">The content to read.</param>\n        /// <param name=\"bufferSize\">Size of the buffer.</param>\n        /// <param name=\"maxHeaderSize\">The max length of the HTTP header.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>The parsed <see cref=\"HttpResponseMessage\"/> instance.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Exception translates to parser state.\")]\n        public static Task<HttpResponseMessage> ReadAsHttpResponseMessageAsync(this HttpContent content, int bufferSize,\n            int maxHeaderSize, CancellationToken cancellationToken)\n        {\n            if (content == null)\n            {\n                throw Error.ArgumentNull(\"content\");\n            }\n\n            if (bufferSize < MinBufferSize)\n            {\n                throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"bufferSize\", bufferSize, MinBufferSize);\n            }\n\n            if (maxHeaderSize < InternetMessageFormatHeaderParser.MinHeaderSize)\n            {\n                throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"maxHeaderSize\", maxHeaderSize, InternetMessageFormatHeaderParser.MinHeaderSize);\n            }\n\n            HttpMessageContent.ValidateHttpMessageContent(content, false, true);\n\n            return content.ReadAsHttpResponseMessageAsyncCore(bufferSize, maxHeaderSize, cancellationToken);\n        }\n\n        private static async Task<HttpResponseMessage> ReadAsHttpResponseMessageAsyncCore(this HttpContent content,\n            int bufferSize, int maxHeaderSize, CancellationToken cancellationToken)\n        {\n            cancellationToken.ThrowIfCancellationRequested();\n            Stream stream = await content.ReadAsStreamAsync();\n\n            HttpUnsortedResponse httpResponse = new HttpUnsortedResponse();\n            HttpResponseHeaderParser parser = new HttpResponseHeaderParser(httpResponse, HttpResponseHeaderParser.DefaultMaxStatusLineSize, maxHeaderSize);\n            ParserState parseStatus;\n\n            byte[] buffer = new byte[bufferSize];\n            int bytesRead = 0;\n            int headerConsumed = 0;\n\n            while (true)\n            {\n                try\n                {\n                    bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken);\n                }\n                catch (Exception e)\n                {\n                    throw new IOException(Properties.Resources.HttpMessageErrorReading, e);\n                }\n\n                try\n                {\n                    parseStatus = parser.ParseBuffer(buffer, bytesRead, ref headerConsumed);\n                }\n                catch (Exception)\n                {\n                    parseStatus = ParserState.Invalid;\n                }\n\n                if (parseStatus == ParserState.Done)\n                {\n                    // Create and return parsed HttpResponseMessage\n                    return CreateHttpResponseMessage(httpResponse, stream, bytesRead - headerConsumed);\n                }\n                else if (parseStatus != ParserState.NeedMoreData)\n                {\n                    throw Error.InvalidOperation(Properties.Resources.HttpMessageParserError, headerConsumed, buffer);\n                }\n                else if (bytesRead == 0)\n                {\n                    throw new IOException(Properties.Resources.ReadAsHttpMessageUnexpectedTermination);\n                }\n            }\n        }\n\n        /// <summary>\n        /// Creates the request URI by combining scheme (provided) with parsed values of\n        /// host and path.\n        /// </summary>\n        /// <param name=\"uriScheme\">The URI scheme to use for the request URI.</param>\n        /// <param name=\"httpRequest\">The unsorted HTTP request.</param>\n        /// <returns>A fully qualified request URI.</returns>\n        private static Uri CreateRequestUri(string uriScheme, HttpUnsortedRequest httpRequest)\n        {\n            Contract.Assert(httpRequest != null, \"httpRequest cannot be null.\");\n            Contract.Assert(uriScheme != null, \"uriScheme cannot be null\");\n\n            IEnumerable<string> hostValues;\n            if (httpRequest.HttpHeaders.TryGetValues(FormattingUtilities.HttpHostHeader, out hostValues))\n            {\n                int hostCount = hostValues.Count();\n                if (hostCount != 1)\n                {\n                    throw Error.InvalidOperation(Properties.Resources.HttpMessageParserInvalidHostCount, FormattingUtilities.HttpHostHeader, hostCount);\n                }\n            }\n            else\n            {\n                throw Error.InvalidOperation(Properties.Resources.HttpMessageParserInvalidHostCount, FormattingUtilities.HttpHostHeader, 0);\n            }\n\n            // We don't use UriBuilder as hostValues.ElementAt(0) contains 'host:port' and UriBuilder needs these split out into separate host and port.\n            string requestUri = String.Format(CultureInfo.InvariantCulture, \"{0}://{1}{2}\", uriScheme, hostValues.ElementAt(0), httpRequest.RequestUri);\n            return new Uri(requestUri);\n        }\n\n        /// <summary>\n        /// Copies the unsorted header fields to a sorted collection.\n        /// </summary>\n        /// <param name=\"source\">The unsorted source headers</param>\n        /// <param name=\"destination\">The destination <see cref=\"HttpRequestHeaders\"/> or <see cref=\"HttpResponseHeaders\"/>.</param>\n        /// <param name=\"contentStream\">The input <see cref=\"Stream\"/> used to form any <see cref=\"HttpContent\"/> being part of this HTTP request.</param>\n        /// <param name=\"rewind\">Start location of any request entity within the <paramref name=\"contentStream\"/>.</param>\n        /// <returns>An <see cref=\"HttpContent\"/> instance if header fields contained and <see cref=\"HttpContentHeaders\"/>.</returns>\n        private static HttpContent CreateHeaderFields(HttpHeaders source, HttpHeaders destination, Stream contentStream, int rewind)\n        {\n            Contract.Assert(source != null, \"source headers cannot be null\");\n            Contract.Assert(destination != null, \"destination headers cannot be null\");\n            Contract.Assert(contentStream != null, \"contentStream must be non null\");\n            HttpContentHeaders contentHeaders = null;\n            HttpContent content;\n\n            // Set the header fields\n            foreach (KeyValuePair<string, IEnumerable<string>> header in source)\n            {\n                if (!destination.TryAddWithoutValidation(header.Key, header.Value))\n                {\n                    if (contentHeaders == null)\n                    {\n                        contentHeaders = FormattingUtilities.CreateEmptyContentHeaders();\n                    }\n\n                    contentHeaders.TryAddWithoutValidation(header.Key, header.Value);\n                }\n            }\n\n            // If we have content headers then create an HttpContent for this request or response. Otherwise,\n            // provide a HttpContent instance to overwrite the null or EmptyContent value.\n            if (contentHeaders != null)\n            {\n                // Need to rewind the input stream to be at the position right after the HTTP header\n                // which we may already have parsed as we read the content stream.\n                if (!contentStream.CanSeek)\n                {\n                    throw Error.InvalidOperation(Properties.Resources.HttpMessageContentStreamMustBeSeekable, \"ContentReadStream\", FormattingUtilities.HttpResponseMessageType.Name);\n                }\n\n                contentStream.Seek(0 - rewind, SeekOrigin.Current);\n                content = new StreamContent(contentStream);\n                contentHeaders.CopyTo(content.Headers);\n            }\n            else\n            {\n                content = new StreamContent(Stream.Null);\n            }\n\n            return content;\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"HttpRequestMessage\"/> based on information provided in <see cref=\"HttpUnsortedRequest\"/>.\n        /// </summary>\n        /// <param name=\"uriScheme\">The URI scheme to use for the request URI.</param>\n        /// <param name=\"httpRequest\">The unsorted HTTP request.</param>\n        /// <param name=\"contentStream\">The input <see cref=\"Stream\"/> used to form any <see cref=\"HttpContent\"/> being part of this HTTP request.</param>\n        /// <param name=\"rewind\">Start location of any request entity within the <paramref name=\"contentStream\"/>.</param>\n        /// <returns>A newly created <see cref=\"HttpRequestMessage\"/> instance.</returns>\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"caller becomes owner.\")]\n        private static HttpRequestMessage CreateHttpRequestMessage(string uriScheme, HttpUnsortedRequest httpRequest, Stream contentStream, int rewind)\n        {\n            Contract.Assert(uriScheme != null, \"URI scheme must be non null\");\n            Contract.Assert(httpRequest != null, \"httpRequest must be non null\");\n            Contract.Assert(contentStream != null, \"contentStream must be non null\");\n\n            HttpRequestMessage httpRequestMessage = new HttpRequestMessage();\n\n            // Set method, requestURI, and version\n            httpRequestMessage.Method = httpRequest.Method;\n            httpRequestMessage.RequestUri = CreateRequestUri(uriScheme, httpRequest);\n            httpRequestMessage.Version = httpRequest.Version;\n\n            // Set the header fields and content if any\n            httpRequestMessage.Content = CreateHeaderFields(httpRequest.HttpHeaders, httpRequestMessage.Headers, contentStream, rewind);\n\n            return httpRequestMessage;\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"HttpResponseMessage\"/> based on information provided in <see cref=\"HttpUnsortedResponse\"/>.\n        /// </summary>\n        /// <param name=\"httpResponse\">The unsorted HTTP Response.</param>\n        /// <param name=\"contentStream\">The input <see cref=\"Stream\"/> used to form any <see cref=\"HttpContent\"/> being part of this HTTP Response.</param>\n        /// <param name=\"rewind\">Start location of any Response entity within the <paramref name=\"contentStream\"/>.</param>\n        /// <returns>A newly created <see cref=\"HttpResponseMessage\"/> instance.</returns>\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"caller becomes owner.\")]\n        private static HttpResponseMessage CreateHttpResponseMessage(HttpUnsortedResponse httpResponse, Stream contentStream, int rewind)\n        {\n            Contract.Assert(httpResponse != null, \"httpResponse must be non null\");\n            Contract.Assert(contentStream != null, \"contentStream must be non null\");\n\n            HttpResponseMessage httpResponseMessage = new HttpResponseMessage();\n\n            // Set version, status code and reason phrase\n            httpResponseMessage.Version = httpResponse.Version;\n            httpResponseMessage.StatusCode = httpResponse.StatusCode;\n            httpResponseMessage.ReasonPhrase = httpResponse.ReasonPhrase;\n\n            // Set the header fields and content if any\n            httpResponseMessage.Content = CreateHeaderFields(httpResponse.HttpHeaders, httpResponseMessage.Headers, contentStream, rewind);\n\n            return httpResponseMessage;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/HttpContentMultipartExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.IO;\nusing System.Net.Http.Formatting.Parsers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// Extension methods to read MIME multipart entities from <see cref=\"HttpContent\"/> instances.\n    /// </summary>\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class HttpContentMultipartExtensions\n    {\n        private const int MinBufferSize = 256;\n        private const int DefaultBufferSize = 32 * 1024;\n\n        /// <summary>\n        /// Determines whether the specified content is MIME multipart content.\n        /// </summary>\n        /// <param name=\"content\">The content.</param>\n        /// <returns>\n        ///   <c>true</c> if the specified content is MIME multipart content; otherwise, <c>false</c>.\n        /// </returns>\n        public static bool IsMimeMultipartContent(this HttpContent content)\n        {\n            if (content == null)\n            {\n                throw Error.ArgumentNull(\"content\");\n            }\n\n            return MimeMultipartBodyPartParser.IsMimeMultipartContent(content);\n        }\n\n        /// <summary>\n        /// Determines whether the specified content is MIME multipart content with the\n        /// specified subtype. For example, the subtype <c>mixed</c> would match content\n        /// with a content type of <c>multipart/mixed</c>.\n        /// </summary>\n        /// <param name=\"content\">The content.</param>\n        /// <param name=\"subtype\">The MIME multipart subtype to match.</param>\n        /// <returns>\n        ///   <c>true</c> if the specified content is MIME multipart content with the specified subtype; otherwise, <c>false</c>.\n        /// </returns>\n        public static bool IsMimeMultipartContent(this HttpContent content, string subtype)\n        {\n            if (String.IsNullOrWhiteSpace(subtype))\n            {\n                throw Error.ArgumentNull(\"subtype\");\n            }\n\n            if (IsMimeMultipartContent(content))\n            {\n                if (content.Headers.ContentType.MediaType.Equals(\"multipart/\" + subtype, StringComparison.OrdinalIgnoreCase))\n                {\n                    return true;\n                }\n            }\n\n            return false;\n        }\n\n        /// <summary>\n        /// Reads all body parts within a MIME multipart message into memory using a <see cref=\"MultipartMemoryStreamProvider\"/>.\n        /// </summary>\n        /// <param name=\"content\">An existing <see cref=\"HttpContent\"/> instance to use for the object's content.</param>\n        /// <returns>A <see cref=\"Task{T}\"/> representing the tasks of getting the result of reading the MIME content.</returns>\n        public static Task<MultipartMemoryStreamProvider> ReadAsMultipartAsync(this HttpContent content)\n        {\n            return ReadAsMultipartAsync<MultipartMemoryStreamProvider>(content, new MultipartMemoryStreamProvider(), DefaultBufferSize);\n        }\n\n        /// <summary>\n        /// Reads all body parts within a MIME multipart message into memory using a <see cref=\"MultipartMemoryStreamProvider\"/>.\n        /// </summary>\n        /// <param name=\"content\">An existing <see cref=\"HttpContent\"/> instance to use for the object's content.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A <see cref=\"Task{T}\"/> representing the tasks of getting the result of reading the MIME content.</returns>\n        public static Task<MultipartMemoryStreamProvider> ReadAsMultipartAsync(this HttpContent content, CancellationToken cancellationToken)\n        {\n            return ReadAsMultipartAsync<MultipartMemoryStreamProvider>(content, new MultipartMemoryStreamProvider(), DefaultBufferSize, cancellationToken);\n        }\n\n        /// <summary>\n        /// Reads all body parts within a MIME multipart message using the provided <see cref=\"MultipartStreamProvider\"/> instance\n        /// to determine where the contents of each body part is written.\n        /// </summary>\n        /// <typeparam name=\"T\">The <see cref=\"MultipartStreamProvider\"/> with which to process the data.</typeparam>\n        /// <param name=\"content\">An existing <see cref=\"HttpContent\"/> instance to use for the object's content.</param>\n        /// <param name=\"streamProvider\">A stream provider providing output streams for where to write body parts as they are parsed.</param>\n        /// <returns>A <see cref=\"Task{T}\"/> representing the tasks of getting the result of reading the MIME content.</returns>\n        public static Task<T> ReadAsMultipartAsync<T>(this HttpContent content, T streamProvider) where T : MultipartStreamProvider\n        {\n            return ReadAsMultipartAsync(content, streamProvider, DefaultBufferSize);\n        }\n\n        /// <summary>\n        /// Reads all body parts within a MIME multipart message using the provided <see cref=\"MultipartStreamProvider\"/> instance\n        /// to determine where the contents of each body part is written.\n        /// </summary>\n        /// <typeparam name=\"T\">The <see cref=\"MultipartStreamProvider\"/> with which to process the data.</typeparam>\n        /// <param name=\"content\">An existing <see cref=\"HttpContent\"/> instance to use for the object's content.</param>\n        /// <param name=\"streamProvider\">A stream provider providing output streams for where to write body parts as they are parsed.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A <see cref=\"Task{T}\"/> representing the tasks of getting the result of reading the MIME content.</returns>\n        public static Task<T> ReadAsMultipartAsync<T>(this HttpContent content, T streamProvider, CancellationToken cancellationToken)\n            where T : MultipartStreamProvider\n        {\n            return ReadAsMultipartAsync(content, streamProvider, DefaultBufferSize, cancellationToken);\n        }\n\n        /// <summary>\n        /// Reads all body parts within a MIME multipart message using the provided <see cref=\"MultipartStreamProvider\"/> instance\n        /// to determine where the contents of each body part is written and <paramref name=\"bufferSize\"/> as read buffer size.\n        /// </summary>\n        /// <typeparam name=\"T\">The <see cref=\"MultipartStreamProvider\"/> with which to process the data.</typeparam>\n        /// <param name=\"content\">An existing <see cref=\"HttpContent\"/> instance to use for the object's content.</param>\n        /// <param name=\"streamProvider\">A stream provider providing output streams for where to write body parts as they are parsed.</param>\n        /// <param name=\"bufferSize\">Size of the buffer used to read the contents.</param>\n        /// <returns>A <see cref=\"Task{T}\"/> representing the tasks of getting the result of reading the MIME content.</returns>\n        public static Task<T> ReadAsMultipartAsync<T>(this HttpContent content, T streamProvider, int bufferSize)\n            where T : MultipartStreamProvider\n        {\n            return ReadAsMultipartAsync(content, streamProvider, bufferSize, CancellationToken.None);\n        }\n\n        /// <summary>\n        /// Reads all body parts within a MIME multipart message using the provided <see cref=\"MultipartStreamProvider\"/> instance\n        /// to determine where the contents of each body part is written and <paramref name=\"bufferSize\"/> as read buffer size.\n        /// </summary>\n        /// <typeparam name=\"T\">The <see cref=\"MultipartStreamProvider\"/> with which to process the data.</typeparam>\n        /// <param name=\"content\">An existing <see cref=\"HttpContent\"/> instance to use for the object's content.</param>\n        /// <param name=\"streamProvider\">A stream provider providing output streams for where to write body parts as they are parsed.</param>\n        /// <param name=\"bufferSize\">Size of the buffer used to read the contents.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A <see cref=\"Task{T}\"/> representing the tasks of getting the result of reading the MIME content.</returns>\n        public static async Task<T> ReadAsMultipartAsync<T>(this HttpContent content, T streamProvider, int bufferSize,\n            CancellationToken cancellationToken) where T : MultipartStreamProvider\n        {\n            if (content == null)\n            {\n                throw Error.ArgumentNull(\"content\");\n            }\n\n            if (streamProvider == null)\n            {\n                throw Error.ArgumentNull(\"streamProvider\");\n            }\n\n            if (bufferSize < MinBufferSize)\n            {\n                throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"bufferSize\", bufferSize, MinBufferSize);\n            }\n\n            Stream stream;\n            try\n            {\n                stream = await content.ReadAsStreamAsync();\n            }\n            catch (Exception e)\n            {\n                throw new IOException(Properties.Resources.ReadAsMimeMultipartErrorReading, e);\n            }\n\n            using (var parser = new MimeMultipartBodyPartParser(content, streamProvider))\n            {\n                byte[] data = new byte[bufferSize];\n                MultipartAsyncContext context = new MultipartAsyncContext(stream, parser, data, streamProvider.Contents);\n\n                // Start async read/write loop\n                await MultipartReadAsync(context, cancellationToken);\n\n                // Let the stream provider post-process when everything is complete\n                await streamProvider.ExecutePostProcessingAsync(cancellationToken);\n                return streamProvider;\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Exception is propagated.\")]\n        private static async Task MultipartReadAsync(MultipartAsyncContext context, CancellationToken cancellationToken)\n        {\n            Contract.Assert(context != null, \"context cannot be null\");\n            while (true)\n            {\n                int bytesRead;\n                try\n                {\n                    bytesRead = await context.ContentStream.ReadAsync(context.Data, 0, context.Data.Length, cancellationToken);\n                }\n                catch (Exception e)\n                {\n                    throw new IOException(Properties.Resources.ReadAsMimeMultipartErrorReading, e);\n                }\n\n                IEnumerable<MimeBodyPart> parts = context.MimeParser.ParseBuffer(context.Data, bytesRead);\n\n                foreach (MimeBodyPart part in parts)\n                {\n                    foreach (ArraySegment<byte> segment in part.Segments)\n                    {\n                        try\n                        {\n                            await part.WriteSegment(segment, cancellationToken);\n                        }\n                        catch (Exception e)\n                        {\n                            part.Dispose();\n                            throw new IOException(Properties.Resources.ReadAsMimeMultipartErrorWriting, e);\n                        }\n                    }\n\n                    if (CheckIsFinalPart(part, context.Result))\n                    {\n                        return;\n                    }\n                }\n            }\n        }\n\n        private static bool CheckIsFinalPart(MimeBodyPart part, ICollection<HttpContent> result)\n        {\n            Contract.Assert(part != null, \"part cannot be null.\");\n            Contract.Assert(result != null, \"result cannot be null.\");\n            if (part.IsComplete)\n            {\n                HttpContent partContent = part.GetCompletedHttpContent();\n                if (partContent != null)\n                {\n                    result.Add(partContent);\n                }\n\n                bool isFinal = part.IsFinal;\n                part.Dispose();\n                return isFinal;\n            }\n\n            return false;\n        }\n\n        /// <summary>\n        /// Managing state for asynchronous read and write operations\n        /// </summary>\n        private class MultipartAsyncContext\n        {\n            public MultipartAsyncContext(Stream contentStream, MimeMultipartBodyPartParser mimeParser, byte[] data, ICollection<HttpContent> result)\n            {\n                Contract.Assert(contentStream != null);\n                Contract.Assert(mimeParser != null);\n                Contract.Assert(data != null);\n\n                ContentStream = contentStream;\n                Result = result;\n                MimeParser = mimeParser;\n                Data = data;\n            }\n\n            /// <summary>\n            /// Gets the <see cref=\"Stream\"/> that we read from.\n            /// </summary>\n            public Stream ContentStream { get; private set; }\n\n            /// <summary>\n            /// Gets the collection of parsed <see cref=\"HttpContent\"/> instances.\n            /// </summary>\n            public ICollection<HttpContent> Result { get; private set; }\n\n            /// <summary>\n            /// The data buffer that we use for reading data from the input stream into before processing.\n            /// </summary>\n            public byte[] Data { get; private set; }\n\n            /// <summary>\n            /// Gets the MIME parser instance used to parse the data\n            /// </summary>\n            public MimeMultipartBodyPartParser MimeParser { get; private set; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/HttpHeaderExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Net.Http.Headers;\n\nnamespace System.Net.Http\n{\n    internal static class HttpHeaderExtensions\n    {\n        public static void CopyTo(this HttpContentHeaders fromHeaders, HttpContentHeaders toHeaders)\n        {\n            Contract.Assert(fromHeaders != null, \"fromHeaders cannot be null.\");\n            Contract.Assert(toHeaders != null, \"toHeaders cannot be null.\");\n\n            foreach (KeyValuePair<string, IEnumerable<string>> header in fromHeaders)\n            {\n                toHeaders.TryAddWithoutValidation(header.Key, header.Value);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/HttpMessageContent.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.IO;\nusing System.Net.Http.Headers;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Web.Http;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// Derived <see cref=\"HttpContent\"/> class which can encapsulate an <see cref=\"HttpResponseMessage\"/>\n    /// or an <see cref=\"HttpRequestMessage\"/> as an entity with media type \"application/http\".\n    /// </summary>\n    public class HttpMessageContent : HttpContent\n    {\n        private const string SP = \" \";\n        private const string ColonSP = \": \";\n        private const string CRLF = \"\\r\\n\";\n        private const string CommaSeparator = \", \";\n\n        private const int DefaultHeaderAllocation = 2 * 1024;\n\n        private const string DefaultMediaType = \"application/http\";\n\n        private const string MsgTypeParameter = \"msgtype\";\n        private const string DefaultRequestMsgType = \"request\";\n        private const string DefaultResponseMsgType = \"response\";\n\n        private const string DefaultRequestMediaType = DefaultMediaType + \"; \" + MsgTypeParameter + \"=\" + DefaultRequestMsgType;\n        private const string DefaultResponseMediaType = DefaultMediaType + \"; \" + MsgTypeParameter + \"=\" + DefaultResponseMsgType;\n\n        // Set of header fields that only support single values such as Set-Cookie.\n        private static readonly HashSet<string> _singleValueHeaderFields = new HashSet<string>(StringComparer.OrdinalIgnoreCase)\n        {\n            \"Cookie\",\n            \"Set-Cookie\",\n            \"X-Powered-By\",\n        };\n\n        // Set of header fields that should get serialized as space-separated values such as User-Agent.\n        private static readonly HashSet<string> _spaceSeparatedValueHeaderFields = new HashSet<string>(StringComparer.OrdinalIgnoreCase)\n        {\n            \"User-Agent\",\n        };\n\n        private bool _contentConsumed;\n        private Lazy<Task<Stream>> _streamTask;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpMessageContent\"/> class encapsulating an\n        /// <see cref=\"HttpRequestMessage\"/>.\n        /// </summary>\n        /// <param name=\"httpRequest\">The <see cref=\"HttpResponseMessage\"/> instance to encapsulate.</param>\n        public HttpMessageContent(HttpRequestMessage httpRequest)\n        {\n            if (httpRequest == null)\n            {\n                throw Error.ArgumentNull(\"httpRequest\");\n            }\n\n            HttpRequestMessage = httpRequest;\n            Headers.ContentType = new MediaTypeHeaderValue(DefaultMediaType);\n            Headers.ContentType.Parameters.Add(new NameValueHeaderValue(MsgTypeParameter, DefaultRequestMsgType));\n\n            InitializeStreamTask();\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpMessageContent\"/> class encapsulating an\n        /// <see cref=\"HttpResponseMessage\"/>.\n        /// </summary>\n        /// <param name=\"httpResponse\">The <see cref=\"HttpResponseMessage\"/> instance to encapsulate.</param>\n        public HttpMessageContent(HttpResponseMessage httpResponse)\n        {\n            if (httpResponse == null)\n            {\n                throw Error.ArgumentNull(\"httpResponse\");\n            }\n\n            HttpResponseMessage = httpResponse;\n            Headers.ContentType = new MediaTypeHeaderValue(DefaultMediaType);\n            Headers.ContentType.Parameters.Add(new NameValueHeaderValue(MsgTypeParameter, DefaultResponseMsgType));\n\n            InitializeStreamTask();\n        }\n\n        private HttpContent Content\n        {\n            get { return HttpRequestMessage != null ? HttpRequestMessage.Content : HttpResponseMessage.Content; }\n        }\n\n        /// <summary>\n        /// Gets the HTTP request message.\n        /// </summary>\n        public HttpRequestMessage HttpRequestMessage { get; private set; }\n\n        /// <summary>\n        /// Gets the HTTP response message.\n        /// </summary>\n        public HttpResponseMessage HttpResponseMessage { get; private set; }\n\n        private void InitializeStreamTask()\n        {\n            _streamTask = new Lazy<Task<Stream>>(() => Content == null ? null : Content.ReadAsStreamAsync());\n        }\n\n        /// <summary>\n        /// Validates whether the content contains an HTTP Request or an HTTP Response.\n        /// </summary>\n        /// <param name=\"content\">The content to validate.</param>\n        /// <param name=\"isRequest\">if set to <c>true</c> if the content is either an HTTP Request or an HTTP Response.</param>\n        /// <param name=\"throwOnError\">Indicates whether validation failure should result in an <see cref=\"Exception\"/> or not.</param>\n        /// <returns><c>true</c> if content is either an HTTP Request or an HTTP Response</returns>\n        internal static bool ValidateHttpMessageContent(HttpContent content, bool isRequest, bool throwOnError)\n        {\n            if (content == null)\n            {\n                throw Error.ArgumentNull(\"content\");\n            }\n\n            MediaTypeHeaderValue contentType = content.Headers.ContentType;\n            if (contentType != null)\n            {\n                if (!contentType.MediaType.Equals(DefaultMediaType, StringComparison.OrdinalIgnoreCase))\n                {\n                    if (throwOnError)\n                    {\n                        throw Error.Argument(\"content\", Properties.Resources.HttpMessageInvalidMediaType, FormattingUtilities.HttpContentType.Name,\n                                      isRequest ? DefaultRequestMediaType : DefaultResponseMediaType);\n                    }\n                    else\n                    {\n                        return false;\n                    }\n                }\n\n                foreach (NameValueHeaderValue parameter in contentType.Parameters)\n                {\n                    if (parameter.Name.Equals(MsgTypeParameter, StringComparison.OrdinalIgnoreCase))\n                    {\n                        string msgType = FormattingUtilities.UnquoteToken(parameter.Value);\n                        if (!msgType.Equals(isRequest ? DefaultRequestMsgType : DefaultResponseMsgType, StringComparison.OrdinalIgnoreCase))\n                        {\n                            if (throwOnError)\n                            {\n                                throw Error.Argument(\"content\", Properties.Resources.HttpMessageInvalidMediaType, FormattingUtilities.HttpContentType.Name, isRequest ? DefaultRequestMediaType : DefaultResponseMediaType);\n                            }\n                            else\n                            {\n                                return false;\n                            }\n                        }\n\n                        return true;\n                    }\n                }\n            }\n\n            if (throwOnError)\n            {\n                throw Error.Argument(\"content\", Properties.Resources.HttpMessageInvalidMediaType, FormattingUtilities.HttpContentType.Name, isRequest ? DefaultRequestMediaType : DefaultResponseMediaType);\n            }\n            else\n            {\n                return false;\n            }\n        }\n\n        /// <summary>\n        /// Asynchronously serializes the object's content to the given <paramref name=\"stream\"/>.\n        /// </summary>\n        /// <param name=\"stream\">The <see cref=\"Stream\"/> to which to write.</param>\n        /// <param name=\"context\">The associated <see cref=\"TransportContext\"/>.</param>\n        /// <returns>A <see cref=\"Task\"/> instance that is asynchronously serializing the object's content.</returns>\n        protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)\n        {\n            if (stream == null)\n            {\n                throw Error.ArgumentNull(\"stream\");\n            }\n\n            byte[] header = SerializeHeader();\n            await stream.WriteAsync(header, 0, header.Length);\n\n            if (Content != null)\n            {\n                Stream readStream = await _streamTask.Value;\n                ValidateStreamForReading(readStream);\n                await Content.CopyToAsync(stream);\n            }\n        }\n\n        /// <summary>\n        /// Computes the length of the stream if possible.\n        /// </summary>\n        /// <param name=\"length\">The computed length of the stream.</param>\n        /// <returns><c>true</c> if the length has been computed; otherwise <c>false</c>.</returns>\n        [SuppressMessage(\"StyleCop.CSharp.ReadabilityRules\", \"SA1108:BlockStatementsMustNotContainEmbeddedComments\",\n            Justification = \"The code is more readable with such comments\")]\n        protected override bool TryComputeLength(out long length)\n        {\n            // We have four states we could be in:\n            //   0. We have content and it knows its ContentLength.\n            //   1. We have content, but the task is still running or finished without success\n            //   2. We have content, the task has finished successfully, and the stream came back as a null or non-seekable\n            //   3. We have content, the task has finished successfully, and the stream is seekable, so we know its length\n            //   4. We don't have content (streamTask.Value == null)\n            //\n            // For #1 and #2, we return false.\n            // For #3, we return true & the size of our headers + the content length\n            // For #4, we return true & the size of our headers\n\n            length = 0;\n\n            if (Content?.Headers.ContentLength is not null)\n            {\n                length = (long)Content.Headers.ContentLength; // Case #0\n            }\n            else if (_streamTask.Value is not null)\n            {\n                Stream readStream;\n                if (!_streamTask.Value.TryGetResult(out readStream) // Case #1\n                    || readStream == null || !readStream.CanSeek) // Case #2\n                {\n                    length = -1;\n                    return false;\n                }\n\n                length = readStream.Length; // Case #3\n            }\n\n            // We serialize header to a StringBuilder so that we can determine the length\n            // following the pattern for HttpContent to try and determine the message length.\n            // The perf overhead is no larger than for the other HttpContent implementations.\n            byte[] header = SerializeHeader();\n            length += header.Length;\n            return true;\n        }\n\n        /// <summary>\n        /// Releases unmanaged and - optionally - managed resources\n        /// </summary>\n        /// <param name=\"disposing\"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>\n        protected override void Dispose(bool disposing)\n        {\n            if (disposing)\n            {\n                if (HttpRequestMessage != null)\n                {\n                    HttpRequestMessage.Dispose();\n                    HttpRequestMessage = null;\n                }\n\n                if (HttpResponseMessage != null)\n                {\n                    HttpResponseMessage.Dispose();\n                    HttpResponseMessage = null;\n                }\n            }\n\n            base.Dispose(disposing);\n        }\n\n        /// <summary>\n        /// Serializes the HTTP request line.\n        /// </summary>\n        /// <param name=\"message\">Where to write the request line.</param>\n        /// <param name=\"httpRequest\">The HTTP request.</param>\n        private static void SerializeRequestLine(StringBuilder message, HttpRequestMessage httpRequest)\n        {\n            Contract.Assert(message != null, \"message cannot be null\");\n            message.Append(httpRequest.Method + SP);\n            message.Append(httpRequest.RequestUri.PathAndQuery + SP);\n            message.Append(FormattingUtilities.HttpVersionToken + \"/\" + (httpRequest.Version != null ? httpRequest.Version.ToString(2) : \"1.1\") + CRLF);\n\n            // Only insert host header if not already present.\n            if (httpRequest.Headers.Host == null)\n            {\n                message.Append(FormattingUtilities.HttpHostHeader + ColonSP + httpRequest.RequestUri.Authority + CRLF);\n            }\n        }\n\n        /// <summary>\n        /// Serializes the HTTP status line.\n        /// </summary>\n        /// <param name=\"message\">Where to write the status line.</param>\n        /// <param name=\"httpResponse\">The HTTP response.</param>\n        private static void SerializeStatusLine(StringBuilder message, HttpResponseMessage httpResponse)\n        {\n            Contract.Assert(message != null, \"message cannot be null\");\n            message.Append(FormattingUtilities.HttpVersionToken + \"/\" + (httpResponse.Version != null ? httpResponse.Version.ToString(2) : \"1.1\") + SP);\n            message.Append((int)httpResponse.StatusCode + SP);\n            message.Append(httpResponse.ReasonPhrase + CRLF);\n        }\n\n        /// <summary>\n        /// Serializes the header fields.\n        /// </summary>\n        /// <param name=\"message\">Where to write the status line.</param>\n        /// <param name=\"headers\">The headers to write.</param>\n        private static void SerializeHeaderFields(StringBuilder message, HttpHeaders headers)\n        {\n            Contract.Assert(message != null, \"message cannot be null\");\n            if (headers != null)\n            {\n                foreach (KeyValuePair<string, IEnumerable<string>> header in headers)\n                {\n                    if (_singleValueHeaderFields.Contains(header.Key))\n                    {\n                        foreach (string value in header.Value)\n                        {\n                            message.Append(header.Key + ColonSP + value + CRLF);\n                        }\n                    }\n                    else if (_spaceSeparatedValueHeaderFields.Contains(header.Key))\n                    {\n                        message.Append(header.Key + ColonSP + String.Join(SP, header.Value) + CRLF);\n                    }\n                    else\n                    {\n                        message.Append(header.Key + ColonSP + String.Join(CommaSeparator, header.Value) + CRLF);\n                    }\n                }\n            }\n        }\n\n        private byte[] SerializeHeader()\n        {\n            StringBuilder message = new StringBuilder(DefaultHeaderAllocation);\n            HttpHeaders headers = null;\n            HttpContent content = null;\n            if (HttpRequestMessage != null)\n            {\n                SerializeRequestLine(message, HttpRequestMessage);\n                headers = HttpRequestMessage.Headers;\n                content = HttpRequestMessage.Content;\n            }\n            else\n            {\n                SerializeStatusLine(message, HttpResponseMessage);\n                headers = HttpResponseMessage.Headers;\n                content = HttpResponseMessage.Content;\n            }\n\n            SerializeHeaderFields(message, headers);\n            if (content != null)\n            {\n                SerializeHeaderFields(message, content.Headers);\n            }\n\n            message.Append(CRLF);\n            return Encoding.UTF8.GetBytes(message.ToString());\n        }\n\n        private void ValidateStreamForReading(Stream stream)\n        {\n            // Stream is null case should be an extreme, incredibly unlikely corner case. Every HttpContent from\n            // the framework (see dotnet/runtime or .NET Framework reference source) provides a non-null Stream\n            // in the ReadAsStreamAsync task's return value. Likely need a poorly-designed derived HttpContent\n            // to hit this. Mostly ignoring the fact this message doesn't make much sense for the case.\n            if (stream is null || !stream.CanRead)\n            {\n                throw Error.NotSupported(Properties.Resources.NotSupported_UnreadableStream);\n            }\n\n            // If the content needs to be written to a target stream a 2nd time, then the stream must support\n            // seeking (e.g. a FileStream), otherwise the stream can't be copied a second time to a target\n            // stream (e.g. a NetworkStream).\n            if (_contentConsumed)\n            {\n                if (stream.CanSeek)\n                {\n                    stream.Position = 0;\n                }\n                else\n                {\n                    throw Error.InvalidOperation(Properties.Resources.HttpMessageContentAlreadyRead,\n                                  FormattingUtilities.HttpContentType.Name,\n                                  HttpRequestMessage != null\n                                      ? FormattingUtilities.HttpRequestMessageType.Name\n                                      : FormattingUtilities.HttpResponseMessageType.Name);\n                }\n            }\n\n            _contentConsumed = true;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/HttpRequestHeadersExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Linq;\nusing System.Net.Http.Headers;\nusing System.Web.Http;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// Provides extension methods for the <see cref=\"HttpRequestHeaders\"/> class.\n    /// </summary>\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class HttpRequestHeadersExtensions\n    {\n        private const string Cookie = \"Cookie\";\n\n        /// <summary>\n        /// Gets any cookie headers present in the request. Each <c>Cookie</c> header is \n        /// represented as one <see cref=\"CookieHeaderValue\"/> instance. A <see cref=\"CookieHeaderValue\"/>\n        /// contains information about the domain, path, and other cookie information as well as one or\n        /// more <see cref=\"CookieState\"/> instances. Each <see cref=\"CookieState\"/> instance contains\n        /// a cookie name and whatever cookie state is associate with that name. The state is in the form of a \n        /// <see cref=\"System.Collections.Specialized.NameValueCollection\"/> which on the wire is encoded as HTML Form URL-encoded data. \n        /// This representation allows for multiple related \"cookies\" to be carried within the same\n        /// <c>Cookie</c> header while still providing separation between each cookie state. A sample\n        /// <c>Cookie</c> header is shown below. In this example, there are two <see cref=\"CookieState\"/>\n        /// with names <c>stateA</c> and <c>stateB</c> respectively. Further, each cookie state contains two name/value\n        /// pairs (name1/value1 and name2/value2) and (name3/value3 and name4/value4).\n        /// <code>\n        /// Cookie: stateA=name1=value1&amp;name2=value2; stateB=name3=value3&amp;name4=value4; domain=domain1; path=path1;\n        /// </code>\n        /// </summary>\n        /// <param name=\"headers\">The request headers</param>\n        /// <returns>A collection of <see cref=\"CookieHeaderValue\"/> instances.</returns>\n        public static Collection<CookieHeaderValue> GetCookies(this HttpRequestHeaders headers)\n        {\n            if (headers == null)\n            {\n                throw Error.ArgumentNull(\"headers\");\n            }\n\n            Collection<CookieHeaderValue> result = new Collection<CookieHeaderValue>();\n            IEnumerable<string> cookieHeaders;\n            if (headers.TryGetValues(Cookie, out cookieHeaders))\n            {\n                foreach (string cookieHeader in cookieHeaders)\n                {\n                    CookieHeaderValue cookieHeaderValue;\n                    if (CookieHeaderValue.TryParse(cookieHeader, out cookieHeaderValue))\n                    {\n                        result.Add(cookieHeaderValue);\n                    }\n                }\n            }\n            return result;\n        }\n\n        /// <summary>\n        /// Gets any cookie headers present in the request which contains a <see cref=\"CookieState\"/> with\n        /// a name that matches the provided <paramref name=\"name\"/>. For example, if there are two Cookie\n        /// header fields looking like this:\n        /// <code>\n        /// Cookie: stateA=name1=value1&amp;name2=value2; stateB=name3=value3&amp;name4=value4; domain=domain1; path=path1;\n        /// Cookie: stateC=name5=value5&amp;name6=value6; stateD=name7=value7&amp;name8=value8; domain=domain2; path=path2;\n        /// </code>\n        /// and <c>name</c> is <c>stateD</c> then only the second Cookie header will be returned.\n        /// </summary>\n        /// <param name=\"headers\">The request headers</param>\n        /// <param name=\"name\">The name of the <see cref=\"CookieState\"/> to match.</param>\n        /// <returns>A collection of <see cref=\"CookieHeaderValue\"/> instances with a matching <see cref=\"CookieState\"/>.</returns>\n        public static Collection<CookieHeaderValue> GetCookies(this HttpRequestHeaders headers, string name)\n        {\n            if (name == null)\n            {\n                throw Error.ArgumentNull(\"name\");\n            }\n\n            IEnumerable<CookieHeaderValue> cookieHeaderValues = GetCookies(headers);\n            CookieHeaderValue[] matches = cookieHeaderValues.Where(header => header.Cookies.Any(state => String.Equals(state.Name, name, StringComparison.OrdinalIgnoreCase))).ToArray();\n            return new Collection<CookieHeaderValue>(matches);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/HttpRequestMessageExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.IO;\nusing System.Web.Http;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// Provides extension methods for the <see cref=\"HttpRequestMessage\"/> class.\n    /// </summary>\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class HttpRequestMessageExtensions\n    {\n        /// <summary>\n        /// Creates an <see cref=\"HttpResponseMessage\"/> wired up to the associated <see cref=\"HttpRequestMessage\"/>.\n        /// </summary>\n        /// <param name=\"request\">The HTTP request.</param>\n        /// <param name=\"statusCode\">The HTTP status code.</param>\n        /// <returns>An initialized <see cref=\"HttpResponseMessage\"/>.</returns>\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"Caller will dispose\")]\n        public static HttpResponseMessage CreateResponse(this HttpRequestMessage request, HttpStatusCode statusCode)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            return new HttpResponseMessage\n            {\n                Content = new StreamContent(Stream.Null),\n                StatusCode = statusCode,\n                RequestMessage = request\n            };\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"HttpResponseMessage\"/> wired up to the associated <see cref=\"HttpRequestMessage\"/>.\n        /// </summary>\n        /// <param name=\"request\">The HTTP request.</param>\n        /// <returns>An initialized <see cref=\"HttpResponseMessage\"/>.</returns>\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"Caller will dispose\")]\n        public static HttpResponseMessage CreateResponse(this HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            return new HttpResponseMessage\n            {\n                Content = new StreamContent(Stream.Null),\n                RequestMessage = request\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/HttpResponseHeadersExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Net.Http.Headers;\nusing System.Web.Http;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// Provides extension methods for the <see cref=\"HttpResponseHeaders\"/> class.\n    /// </summary>\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class HttpResponseHeadersExtensions\n    {\n        private const string SetCookie = \"Set-Cookie\";\n\n        /// <summary>\n        /// Adds cookies to a response. Each <c>Set-Cookie</c> header is \n        /// represented as one <see cref=\"CookieHeaderValue\"/> instance. A <see cref=\"CookieHeaderValue\"/>\n        /// contains information about the domain, path, and other cookie information as well as one or\n        /// more <see cref=\"CookieState\"/> instances. Each <see cref=\"CookieState\"/> instance contains\n        /// a cookie name and whatever cookie state is associate with that name. The state is in the form of a \n        /// <see cref=\"System.Collections.Specialized.NameValueCollection\"/> which on the wire is encoded as HTML Form URL-encoded data. \n        /// This representation allows for multiple related \"cookies\" to be carried within the same\n        /// <c>Cookie</c> header while still providing separation between each cookie state. A sample\n        /// <c>Cookie</c> header is shown below. In this example, there are two <see cref=\"CookieState\"/>\n        /// with names <c>state1</c> and <c>state2</c> respectively. Further, each cookie state contains two name/value\n        /// pairs (name1/value1 and name2/value2) and (name3/value3 and name4/value4).\n        /// <code>\n        /// Set-Cookie: state1:name1=value1&amp;name2=value2; state2:name3=value3&amp;name4=value4; domain=domain1; path=path1;\n        /// </code>\n        /// </summary>\n        /// <param name=\"headers\">The response headers</param>\n        /// <param name=\"cookies\">The cookie values to add to the response.</param>\n        public static void AddCookies(this HttpResponseHeaders headers, IEnumerable<CookieHeaderValue> cookies)\n        {\n            if (headers == null)\n            {\n                throw Error.ArgumentNull(\"headers\");\n            }\n\n            if (cookies == null)\n            {\n                throw Error.ArgumentNull(\"cookies\");\n            }\n\n            foreach (CookieHeaderValue cookie in cookies)\n            {\n                if (cookie == null)\n                {\n                    throw Error.Argument(\"cookies\", Properties.Resources.CookieNull);\n                }\n\n                headers.TryAddWithoutValidation(SetCookie, cookie.ToString());\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/HttpUnsortedHeaders.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Headers;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// All of the existing non-abstract <see cref=\"HttpHeaders\"/> implementations, namely\n    /// <see cref=\"HttpRequestHeaders\"/>, <see cref=\"HttpResponseHeaders\"/>, and <see cref=\"HttpContentHeaders\"/>\n    /// enforce strict rules on what kinds of HTTP header fields can be added to each collection.\n    /// When parsing the \"application/http\" media type we need to just get the unsorted list. It\n    /// will get sorted later.\n    /// </summary>\n    internal class HttpUnsortedHeaders : HttpHeaders\n    {\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/HttpUnsortedRequest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Formatting.Parsers;\nusing System.Net.Http.Headers;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// Represents the HTTP Request Line and header parameters parsed by <see cref=\"HttpRequestLineParser\"/>\n    /// and <see cref=\"HttpRequestHeaderParser\"/>.\n    /// </summary>\n    internal class HttpUnsortedRequest\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpUnsortedRequest\"/> class.\n        /// </summary>\n        public HttpUnsortedRequest()\n        {\n            // Collection of unsorted headers. Later we will sort it into the appropriate\n            // HttpContentHeaders, HttpRequestHeaders, and HttpResponseHeaders.\n            HttpHeaders = new HttpUnsortedHeaders();\n        }\n\n        /// <summary>\n        /// Gets or sets the HTTP method.\n        /// </summary>\n        /// <value>\n        /// The HTTP method.\n        /// </value>\n        public HttpMethod Method { get; set; }\n\n        /// <summary>\n        /// Gets or sets the HTTP request URI portion that is carried in the RequestLine (i.e the URI path + query).\n        /// </summary>\n        /// <value>\n        /// The request URI.\n        /// </value>\n        public string RequestUri { get; set; }\n\n        /// <summary>\n        /// Gets or sets the HTTP version.\n        /// </summary>\n        /// <value>\n        /// The HTTP version.\n        /// </value>\n        public Version Version { get; set; }\n\n        /// <summary>\n        /// Gets the unsorted HTTP request headers.\n        /// </summary>\n        public HttpHeaders HttpHeaders { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/HttpUnsortedResponse.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Formatting.Parsers;\nusing System.Net.Http.Headers;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// Represents the HTTP Status Line and header parameters parsed by <see cref=\"HttpStatusLineParser\"/>\n    /// and <see cref=\"HttpResponseHeaderParser\"/>.\n    /// </summary>\n    internal class HttpUnsortedResponse\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpUnsortedRequest\"/> class.\n        /// </summary>\n        public HttpUnsortedResponse()\n        {\n            // Collection of unsorted headers. Later we will sort it into the appropriate\n            // HttpContentHeaders, HttpRequestHeaders, and HttpResponseHeaders.\n            HttpHeaders = new HttpUnsortedHeaders();\n        }\n\n        /// <summary>\n        /// Gets or sets the HTTP version.\n        /// </summary>\n        /// <value>\n        /// The HTTP version.\n        /// </value>\n        public Version Version { get; set; }\n\n        /// <summary>\n        /// Gets or sets the <see cref=\"HttpStatusCode\"/>\n        /// </summary>\n        /// <value>\n        /// The HTTP status code\n        /// </value>\n        public HttpStatusCode StatusCode { get; set; }\n\n        /// <summary>\n        /// Gets or sets the HTTP reason phrase\n        /// </summary>\n        /// <value>\n        /// The response reason phrase\n        /// </value>\n        public string ReasonPhrase { get; set; }\n\n        /// <summary>\n        /// Gets the unsorted HTTP request headers.\n        /// </summary>\n        public HttpHeaders HttpHeaders { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Internal/AsyncResult.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Threading;\nusing System.Web.Http;\n\nnamespace System.Net.Http.Internal\n{\n    [SuppressMessage(\"Microsoft.Design\", \"CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable\", Justification = \"_manualResetEvent is disposed in End<TAsyncResult>\")]\n    internal abstract class AsyncResult : IAsyncResult\n    {\n        private AsyncCallback _callback;\n        private object _state;\n\n        private bool _isCompleted;\n        private bool _completedSynchronously;\n        private bool _endCalled;\n\n        private Exception _exception;\n\n        protected AsyncResult(AsyncCallback callback, object state)\n        {\n            _callback = callback;\n            _state = state;\n        }\n\n        public object AsyncState\n        {\n            get { return _state; }\n        }\n\n        public WaitHandle AsyncWaitHandle\n        {\n            get\n            {\n                Contract.Assert(false, \"AsyncWaitHandle is not supported -- use callbacks instead.\");\n                return null;\n            }\n        }\n\n        public bool CompletedSynchronously\n        {\n            get { return _completedSynchronously; }\n        }\n\n        public bool HasCallback\n        {\n            get { return _callback != null; }\n        }\n\n        public bool IsCompleted\n        {\n            get { return _isCompleted; }\n        }\n\n        protected void Complete(bool completedSynchronously)\n        {\n            if (_isCompleted)\n            {\n                throw Error.InvalidOperation(Properties.Resources.AsyncResult_MultipleCompletes, GetType().Name);\n            }\n\n            _completedSynchronously = completedSynchronously;\n            _isCompleted = true;\n\n            if (_callback != null)\n            {\n                try\n                {\n                    _callback(this);\n                }\n                catch (Exception e)\n                {\n                    throw Error.InvalidOperation(e, Properties.Resources.AsyncResult_CallbackThrewException);\n                }\n            }\n        }\n\n        protected void Complete(bool completedSynchronously, Exception exception)\n        {\n            _exception = exception;\n            Complete(completedSynchronously);\n        }\n\n        protected static TAsyncResult End<TAsyncResult>(IAsyncResult result) where TAsyncResult : AsyncResult\n        {\n            if (result == null)\n            {\n                throw Error.ArgumentNull(\"result\");\n            }\n\n            TAsyncResult thisPtr = result as TAsyncResult;\n\n            if (thisPtr == null)\n            {\n                throw Error.Argument(\"result\", Properties.Resources.AsyncResult_ResultMismatch);\n            }\n\n            if (!thisPtr._isCompleted)\n            {\n                thisPtr.AsyncWaitHandle.WaitOne();\n            }\n\n            if (thisPtr._endCalled)\n            {\n                throw Error.InvalidOperation(Properties.Resources.AsyncResult_MultipleEnds);\n            }\n\n            thisPtr._endCalled = true;\n\n            if (thisPtr._exception != null)\n            {\n                throw thisPtr._exception;\n            }\n\n            return thisPtr;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Internal/ByteRangeStream.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http;\n\nnamespace System.Net.Http.Internal\n{\n    /// <summary>\n    /// Stream which only exposes a read-only only range view of an\n    /// inner stream.\n    /// </summary>\n    internal class ByteRangeStream : DelegatingStream\n    {\n        // The offset stream position at which the range starts.\n        private readonly long _lowerbounds;\n\n        // The total number of bytes within the range.\n        private readonly long _totalCount;\n\n        // The current number of bytes read into the range\n        private long _currentCount;\n\n        public ByteRangeStream(Stream innerStream, RangeItemHeaderValue range)\n            : base(innerStream)\n        {\n            if (range == null)\n            {\n                throw Error.ArgumentNull(\"range\");\n            }\n            if (!innerStream.CanSeek)\n            {\n                throw Error.Argument(\"innerStream\", Properties.Resources.ByteRangeStreamNotSeekable, typeof(ByteRangeStream).Name);\n            }\n            if (innerStream.Length < 1)\n            {\n                throw Error.ArgumentOutOfRange(\"innerStream\", innerStream.Length, Properties.Resources.ByteRangeStreamEmpty, typeof(ByteRangeStream).Name);\n            }\n            if (range.From.HasValue && range.From.Value > innerStream.Length)\n            {\n                throw Error.ArgumentOutOfRange(\"range\", range.From, Properties.Resources.ByteRangeStreamInvalidFrom, innerStream.Length);\n            }\n\n            // Ranges are inclusive so 0-9 means the first 10 bytes\n            long maxLength = innerStream.Length - 1;\n            long upperbounds;\n            if (range.To.HasValue)\n            {\n                if (range.From.HasValue)\n                {\n                    // e.g bytes=0-499 (the first 500 bytes offsets 0-499)\n                    upperbounds = Math.Min(range.To.Value, maxLength);\n                    _lowerbounds = range.From.Value;\n                }\n                else\n                {\n                    // e.g bytes=-500 (the final 500 bytes)\n                    upperbounds = maxLength;\n                    _lowerbounds = Math.Max(innerStream.Length - range.To.Value, 0);\n                }\n            }\n            else\n            {\n                if (range.From.HasValue)\n                {\n                    // e.g bytes=500- (from byte offset 500 and up)\n                    upperbounds = maxLength;\n                    _lowerbounds = range.From.Value;\n                }\n                else\n                {\n                    // e.g. bytes=- (invalid so will never get here)\n                    upperbounds = maxLength;\n                    _lowerbounds = 0;\n                }\n            }\n\n            _totalCount = upperbounds - _lowerbounds + 1;\n            ContentRange = new ContentRangeHeaderValue(_lowerbounds, upperbounds, innerStream.Length);\n        }\n\n        public ContentRangeHeaderValue ContentRange { get; private set; }\n\n        public override long Length\n        {\n            get { return _totalCount; }\n        }\n\n        public override bool CanWrite\n        {\n            get { return false; }\n        }\n\n        public override long Position\n        {\n            get\n            {\n                return _currentCount;\n            }\n            set\n            {\n                if (value < 0)\n                {\n                    throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"value\", value, 0L);\n                }\n\n                _currentCount = value;\n            }\n        }\n\n#if !NETSTANDARD1_3 // BeginX and EndX are not supported on Streams in netstandard1.3\n        public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)\n        {\n            return base.BeginRead(buffer, offset, PrepareStreamForRangeRead(count), callback, state);\n        }\n#endif\n\n        public override int Read(byte[] buffer, int offset, int count)\n        {\n            return base.Read(buffer, offset, PrepareStreamForRangeRead(count));\n        }\n\n        public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)\n        {\n            return base.ReadAsync(buffer, offset, PrepareStreamForRangeRead(count), cancellationToken);\n        }\n\n        public override int ReadByte()\n        {\n            int effectiveCount = PrepareStreamForRangeRead(1);\n            if (effectiveCount <= 0)\n            {\n                return -1;\n            }\n\n            return base.ReadByte();\n        }\n\n        public override long Seek(long offset, SeekOrigin origin)\n        {\n            switch (origin)\n            {\n                case SeekOrigin.Begin:\n                    _currentCount = offset;\n                    break;\n                case SeekOrigin.Current:\n                    _currentCount = _currentCount + offset;\n                    break;\n                case SeekOrigin.End:\n                    _currentCount = _totalCount + offset;\n                    break;\n                default:\n                    throw Error.InvalidEnumArgument(\"origin\", (int)origin, typeof(SeekOrigin));\n            }\n\n            if (_currentCount < 0L)\n            {\n                throw new IOException(Properties.Resources.ByteRangeStreamInvalidOffset);\n            }\n\n            return _currentCount;\n        }\n\n        public override void SetLength(long value)\n        {\n            throw Error.NotSupported(Properties.Resources.ByteRangeStreamReadOnly);\n        }\n\n        public override void Write(byte[] buffer, int offset, int count)\n        {\n            throw Error.NotSupported(Properties.Resources.ByteRangeStreamReadOnly);\n        }\n\n#if !NETSTANDARD1_3 // BeginX and EndX are not supported on Streams in netstandard1.3\n        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)\n        {\n            throw Error.NotSupported(Properties.Resources.ByteRangeStreamReadOnly);\n        }\n\n        public override void EndWrite(IAsyncResult asyncResult)\n        {\n            throw Error.NotSupported(Properties.Resources.ByteRangeStreamReadOnly);\n        }\n#endif\n\n        public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)\n        {\n            throw Error.NotSupported(Properties.Resources.ByteRangeStreamReadOnly);\n        }\n\n        public override void WriteByte(byte value)\n        {\n            throw Error.NotSupported(Properties.Resources.ByteRangeStreamReadOnly);\n        }\n\n        /// <summary>\n        /// Gets the correct count for the next read operation.\n        /// </summary>\n        /// <param name=\"count\">The count requested to be read by the caller.</param>\n        /// <returns>The remaining bytes to read within the range defined for this stream.</returns>\n        private int PrepareStreamForRangeRead(int count)\n        {\n            // A negative count causes base.Raad* methods to throw an ArgumentOutOfRangeException.\n            if (count <= 0)\n            {\n                return count;\n            }\n\n            // Reading past the end simply does nothing.\n            if (_currentCount >= _totalCount)\n            {\n                return 0;\n            }\n\n            long effectiveCount = Math.Min(count, _totalCount - _currentCount);\n\n            // Check if we should update the inner stream's position.\n            var newPosition = _lowerbounds + _currentCount;\n            var position = InnerStream.Position;\n            if (newPosition != position)\n            {\n                InnerStream.Position = newPosition;\n            }\n\n            // Update current number of bytes read.\n            _currentCount += effectiveCount;\n\n            // Effective count can never be bigger than int.\n            return (int)effectiveCount;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Internal/DelegatingStream.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http;\n\nnamespace System.Net.Http.Internal\n{\n    /// <summary>\n    /// Stream that delegates to inner stream.\n    /// This is taken from System.Net.Http\n    /// </summary>\n    internal abstract class DelegatingStream : Stream\n    {\n        private readonly Stream _innerStream;\n\n        protected DelegatingStream(Stream innerStream)\n        {\n            if (innerStream == null)\n            {\n                throw Error.ArgumentNull(\"innerStream\");\n            }\n            _innerStream = innerStream;\n        }\n\n        protected Stream InnerStream\n        {\n            get { return _innerStream; }\n        }\n\n        public override bool CanRead\n        {\n            get { return _innerStream.CanRead; }\n        }\n\n        public override bool CanSeek\n        {\n            get { return _innerStream.CanSeek; }\n        }\n\n        public override bool CanWrite\n        {\n            get { return _innerStream.CanWrite; }\n        }\n\n        public override long Length\n        {\n            get { return _innerStream.Length; }\n        }\n\n        public override long Position\n        {\n            get { return _innerStream.Position; }\n            set { _innerStream.Position = value; }\n        }\n\n        public override int ReadTimeout\n        {\n            get { return _innerStream.ReadTimeout; }\n            set { _innerStream.ReadTimeout = value; }\n        }\n\n        public override bool CanTimeout\n        {\n            get { return _innerStream.CanTimeout; }\n        }\n\n        public override int WriteTimeout\n        {\n            get { return _innerStream.WriteTimeout; }\n            set { _innerStream.WriteTimeout = value; }\n        }\n\n        protected override void Dispose(bool disposing)\n        {\n            if (disposing)\n            {\n                _innerStream.Dispose();\n            }\n            base.Dispose(disposing);\n        }\n\n        public override long Seek(long offset, SeekOrigin origin)\n        {\n            return _innerStream.Seek(offset, origin);\n        }\n\n        public override int Read(byte[] buffer, int offset, int count)\n        {\n            return _innerStream.Read(buffer, offset, count);\n        }\n\n        public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)\n        {\n            return _innerStream.ReadAsync(buffer, offset, count, cancellationToken);\n        }\n\n#if !NETSTANDARD1_3 // BeginX and EndX not supported on Streams in netstandard1.3\n        public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)\n        {\n            return _innerStream.BeginRead(buffer, offset, count, callback, state);\n        }\n\n        public override int EndRead(IAsyncResult asyncResult)\n        {\n            return _innerStream.EndRead(asyncResult);\n        }\n#endif\n\n        public override int ReadByte()\n        {\n            return _innerStream.ReadByte();\n        }\n\n        public override void Flush()\n        {\n            _innerStream.Flush();\n        }\n\n        public override Task FlushAsync(CancellationToken cancellationToken)\n        {\n            return _innerStream.FlushAsync(cancellationToken);\n        }\n\n        public override void SetLength(long value)\n        {\n            _innerStream.SetLength(value);\n        }\n\n        public override void Write(byte[] buffer, int offset, int count)\n        {\n            _innerStream.Write(buffer, offset, count);\n        }\n\n        public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)\n        {\n            return _innerStream.WriteAsync(buffer, offset, count, cancellationToken);\n        }\n\n#if !NETSTANDARD1_3 // BeginX and EndX not supported on Streams in netstandard1.3\n        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)\n        {\n            return _innerStream.BeginWrite(buffer, offset, count, callback, state);\n        }\n\n        public override void EndWrite(IAsyncResult asyncResult)\n        {\n            _innerStream.EndWrite(asyncResult);\n        }\n#endif\n\n        public override void WriteByte(byte value)\n        {\n            _innerStream.WriteByte(value);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Internal/HttpValueCollection.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing System.Net.Http.Internal;\nusing System.Runtime.Serialization;\nusing System.Text;\nusing System.Web.Http;\n\nnamespace System.Net.Http.Formatting.Internal\n{\n    /// <summary>\n    ///  NameValueCollection to represent form data and to generate form data output.\n    /// </summary>\n#if !NETSTANDARD1_3 // NameValueCollection is not serializable in netstandard1.3.\n    [Serializable]\n#endif\n    internal class HttpValueCollection : NameValueCollection\n    {\n#if !NETSTANDARD1_3 // NameValueCollection is not serializable in netstandard1.3.\n        protected HttpValueCollection(SerializationInfo info, StreamingContext context)\n            : base(info, context)\n        {\n        }\n#endif\n\n        private HttpValueCollection()\n            : base(StringComparer.OrdinalIgnoreCase) // case-insensitive keys\n        {\n        }\n\n        // Use a builder function instead of a ctor to avoid virtual calls from the ctor.\n        // The above condition is only important in the Full .NET fx implementation.\n        internal static HttpValueCollection Create()\n        {\n            return new HttpValueCollection();\n        }\n\n        internal static HttpValueCollection Create(IEnumerable<KeyValuePair<string, string>> pairs)\n        {\n            Contract.Assert(pairs != null);\n\n            var hvc = new HttpValueCollection();\n\n            // Ordering example:\n            //   k=A&j=B&k=C --> k:[A,C];j=[B].\n            foreach (KeyValuePair<string, string> kvp in pairs)\n            {\n                hvc.Add(kvp.Key, kvp.Value);\n            }\n\n            hvc.IsReadOnly = false;\n            return hvc;\n        }\n\n        /// <summary>\n        /// Adds a name-value pair to the collection.\n        /// </summary>\n        /// <param name=\"name\">The name to be added as a case insensitive string.</param>\n        /// <param name=\"value\">The value to be added.</param>\n        public override void Add(string name, string value)\n        {\n            ThrowIfMaxHttpCollectionKeysExceeded(Count);\n\n            name = name ?? String.Empty;\n            value = value ?? String.Empty;\n\n            base.Add(name, value);\n        }\n\n        /// <summary>\n        /// Converts the content of this instance to its equivalent string representation.\n        /// </summary>\n        /// <returns>The string representation of the value of this instance, multiple values with a single key are comma separated.</returns>\n        public override string ToString()\n        {\n            return ToString(true);\n        }\n\n        private static void ThrowIfMaxHttpCollectionKeysExceeded(int count)\n        {\n            if (count >= MediaTypeFormatter.MaxHttpCollectionKeys)\n            {\n                throw Error.InvalidOperation(System.Net.Http.Properties.Resources.MaxHttpCollectionKeyLimitReached, MediaTypeFormatter.MaxHttpCollectionKeys, typeof(MediaTypeFormatter));\n            }\n        }\n\n        private string ToString(bool urlEncode)\n        {\n            if (Count == 0)\n            {\n                return String.Empty;\n            }\n\n            StringBuilder builder = new StringBuilder();\n            bool first = true;\n            foreach (string name in this)\n            {\n                string[] values = GetValues(name);\n                if (values == null || values.Length == 0)\n                {\n                    first = AppendNameValuePair(builder, first, urlEncode, name, String.Empty);\n                }\n                else\n                {\n                    foreach (string value in values)\n                    {\n                        first = AppendNameValuePair(builder, first, urlEncode, name, value);\n                    }\n                }\n            }\n\n            return builder.ToString();\n        }\n\n        private static bool AppendNameValuePair(StringBuilder builder, bool first, bool urlEncode, string name, string value)\n        {\n            string effectiveName = name ?? String.Empty;\n            string encodedName = urlEncode ? WebUtility.UrlEncode(effectiveName) : effectiveName;\n\n            string effectiveValue = value ?? String.Empty;\n            string encodedValue = urlEncode ? WebUtility.UrlEncode(effectiveValue) : effectiveValue;\n\n            if (first)\n            {\n                first = false;\n            }\n            else\n            {\n                builder.Append(\"&\");\n            }\n\n            builder.Append(encodedName);\n            if (!String.IsNullOrEmpty(encodedValue))\n            {\n                builder.Append(\"=\");\n                builder.Append(encodedValue);\n            }\n            return first;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Internal/NonClosingDelegatingStream.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\n\nnamespace System.Net.Http.Internal\n{\n    /// <summary>\n    /// Stream that doesn't close the inner stream when closed. This is to work around a limitation\n    /// in the <see cref=\"System.Xml.XmlDictionaryReader\"/> insisting of closing the inner stream.\n    /// The regular <see cref=\"System.Xml.XmlReader\"/> does allow for not closing the inner stream but that\n    /// doesn't have the quota that we need for security reasons. Implementations of\n    /// <see cref=\"System.Net.Http.Formatting.MediaTypeFormatter\"/>\n    /// should not close the input stream when reading or writing so hence this workaround.\n    /// </summary>\n    internal class NonClosingDelegatingStream : DelegatingStream\n    {\n        public NonClosingDelegatingStream(Stream innerStream)\n            : base(innerStream)\n        {\n        }\n\n#if NETSTANDARD1_3\n        protected override void Dispose(bool disposing)\n        {\n        }\n#else\n        public override void Close()\n        {\n        }\n#endif\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Internal/NullableAttributes.cs",
    "content": "// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n\n// From https://github.com/dotnet/runtime/blob/88868b7a781f4e5b9037b8721f30440207a7aa42/src/tools/illink/src/ILLink.RoslynAnalyzer/NullableAttributes.cs\n\nnamespace System.Diagnostics.CodeAnalysis\n{\n#if !NETSTANDARD2_1\n    /// <summary>Specifies that null is allowed as an input even if the corresponding type disallows it.</summary>\n    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)]\n#if SYSTEM_PRIVATE_CORELIB\n    public\n#else\n    internal\n#endif\n        sealed class AllowNullAttribute : Attribute { }\n\n    /// <summary>Specifies that null is disallowed as an input even if the corresponding type allows it.</summary>\n    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)]\n#if SYSTEM_PRIVATE_CORELIB\n    public\n#else\n    internal\n#endif\n        sealed class DisallowNullAttribute : Attribute { }\n\n    /// <summary>Specifies that an output may be null even if the corresponding type disallows it.</summary>\n    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)]\n#if SYSTEM_PRIVATE_CORELIB\n    public\n#else\n    internal\n#endif\n        sealed class MaybeNullAttribute : Attribute { }\n\n    /// <summary>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.</summary>\n    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)]\n#if SYSTEM_PRIVATE_CORELIB\n    public\n#else\n    internal\n#endif\n        sealed class NotNullAttribute : Attribute { }\n\n    /// <summary>Specifies that when a method returns <see cref=\"ReturnValue\"/>, the parameter may be null even if the corresponding type disallows it.</summary>\n    [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]\n#if SYSTEM_PRIVATE_CORELIB\n    public\n#else\n    internal\n#endif\n        sealed class MaybeNullWhenAttribute : Attribute\n    {\n        /// <summary>Initializes the attribute with the specified return value condition.</summary>\n        /// <param name=\"returnValue\">\n        /// The return value condition. If the method returns this value, the associated parameter may be null.\n        /// </param>\n        public MaybeNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;\n\n        /// <summary>Gets the return value condition.</summary>\n        public bool ReturnValue { get; }\n    }\n\n    /// <summary>Specifies that when a method returns <see cref=\"ReturnValue\"/>, the parameter will not be null even if the corresponding type allows it.</summary>\n    [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]\n#if SYSTEM_PRIVATE_CORELIB\n    public\n#else\n    internal\n#endif\n        sealed class NotNullWhenAttribute : Attribute\n    {\n        /// <summary>Initializes the attribute with the specified return value condition.</summary>\n        /// <param name=\"returnValue\">\n        /// The return value condition. If the method returns this value, the associated parameter will not be null.\n        /// </param>\n        public NotNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;\n\n        /// <summary>Gets the return value condition.</summary>\n        public bool ReturnValue { get; }\n    }\n\n    /// <summary>Specifies that the output will be non-null if the named parameter is non-null.</summary>\n    [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]\n#if SYSTEM_PRIVATE_CORELIB\n    public\n#else\n    internal\n#endif\n        sealed class NotNullIfNotNullAttribute : Attribute\n    {\n        /// <summary>Initializes the attribute with the associated parameter name.</summary>\n        /// <param name=\"parameterName\">\n        /// The associated parameter name.  The output will be non-null if the argument to the parameter specified is non-null.\n        /// </param>\n        public NotNullIfNotNullAttribute(string parameterName) => ParameterName = parameterName;\n\n        /// <summary>Gets the associated parameter name.</summary>\n        public string ParameterName { get; }\n    }\n\n    /// <summary>Applied to a method that will never return under any circumstance.</summary>\n    [AttributeUsage(AttributeTargets.Method, Inherited = false)]\n#if SYSTEM_PRIVATE_CORELIB\n    public\n#else\n    internal\n#endif\n        sealed class DoesNotReturnAttribute : Attribute { }\n\n    /// <summary>Specifies that the method will not return if the associated Boolean parameter is passed the specified value.</summary>\n    [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]\n#if SYSTEM_PRIVATE_CORELIB\n    public\n#else\n    internal\n#endif\n        sealed class DoesNotReturnIfAttribute : Attribute\n    {\n        /// <summary>Initializes the attribute with the specified parameter value.</summary>\n        /// <param name=\"parameterValue\">\n        /// The condition parameter value. Code after the method will be considered unreachable by diagnostics if the argument to\n        /// the associated parameter matches this value.\n        /// </param>\n        public DoesNotReturnIfAttribute(bool parameterValue) => ParameterValue = parameterValue;\n\n        /// <summary>Gets the condition parameter value.</summary>\n        public bool ParameterValue { get; }\n    }\n#endif\n\n    /// <summary>Specifies that the method or property will ensure that the listed field and property members have not-null values.</summary>\n    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]\n#if SYSTEM_PRIVATE_CORELIB\n    public\n#else\n    internal\n#endif\n        sealed class MemberNotNullAttribute : Attribute\n    {\n        /// <summary>Initializes the attribute with a field or property member.</summary>\n        /// <param name=\"member\">\n        /// The field or property member that is promised to be not-null.\n        /// </param>\n        public MemberNotNullAttribute(string member) => Members = new[] { member };\n\n        /// <summary>Initializes the attribute with the list of field and property members.</summary>\n        /// <param name=\"members\">\n        /// The list of field and property members that are promised to be not-null.\n        /// </param>\n        public MemberNotNullAttribute(params string[] members) => Members = members;\n\n        /// <summary>Gets field or property member names.</summary>\n        public string[] Members { get; }\n    }\n\n    /// <summary>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.</summary>\n    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]\n#if SYSTEM_PRIVATE_CORELIB\n    public\n#else\n    internal\n#endif\n        sealed class MemberNotNullWhenAttribute : Attribute\n    {\n        /// <summary>Initializes the attribute with the specified return value condition and a field or property member.</summary>\n        /// <param name=\"returnValue\">\n        /// The return value condition. If the method returns this value, the associated parameter will not be null.\n        /// </param>\n        /// <param name=\"member\">\n        /// The field or property member that is promised to be not-null.\n        /// </param>\n        public MemberNotNullWhenAttribute(bool returnValue, string member)\n        {\n            ReturnValue = returnValue;\n            Members = new[] { member };\n        }\n\n        /// <summary>Initializes the attribute with the specified return value condition and list of field and property members.</summary>\n        /// <param name=\"returnValue\">\n        /// The return value condition. If the method returns this value, the associated parameter will not be null.\n        /// </param>\n        /// <param name=\"members\">\n        /// The list of field and property members that are promised to be not-null.\n        /// </param>\n        public MemberNotNullWhenAttribute(bool returnValue, params string[] members)\n        {\n            ReturnValue = returnValue;\n            Members = members;\n        }\n\n        /// <summary>Gets the return value condition.</summary>\n        public bool ReturnValue { get; }\n\n        /// <summary>Gets field or property member names.</summary>\n        public string[] Members { get; }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Internal/TranscodingStream.cs",
    "content": "// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n\n// From https://github.com/dotnet/runtime/blob/88868b7a781f4e5b9037b8721f30440207a7aa42/src/libraries/System.Private.CoreLib/src/System/Text/TranscodingStream.cs\n\nusing System.Buffers;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.IO;\nusing System.Runtime.CompilerServices;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http;\nusing Properties = System.Net.Http.Properties;\n\n#nullable enable\n\nnamespace System.Text\n{\n    internal sealed class TranscodingStream : Stream\n    {\n        private const int DefaultReadByteBufferSize = 4 * 1024; // lifted from StreamReader.cs (FileStream)\n\n        // We optimistically assume 1 byte ~ 1 char during transcoding. This is a good rule of thumb\n        // but isn't always appropriate: transcoding between single-byte and multi-byte encodings\n        // will violate this, as will any invalid data fixups performed by the transcoder itself.\n        // To account for these unknowns we have a minimum scratch buffer size we use during the\n        // transcoding process. This should be generous enough to account for even the largest\n        // fallback mechanism we're likely to see in the real world.\n\n        private const int MinWriteRentedArraySize = 4 * 1024;\n        private const int MaxWriteRentedArraySize = 1024 * 1024;\n\n        private static readonly byte[] EmptyByteBuffer = new byte[0];\n        private static readonly char[] EmptyCharBuffer = new char[0];\n\n        private readonly Encoding _innerEncoding;\n        private readonly Encoding _thisEncoding;\n        private Stream _innerStream; // null if the wrapper has been disposed\n        private readonly bool _leaveOpen;\n        private readonly byte[] _singleByteBuffer = new byte[1];\n\n        /*\n         * Fields used for writing bytes [this] -> chars -> bytes [inner]\n         * Lazily initialized the first time we need to write\n         */\n\n        private Encoder? _innerEncoder;\n        private Decoder? _thisDecoder;\n\n        /*\n         * Fields used for reading bytes [inner] -> chars -> bytes [this]\n         * Lazily initialized the first time we need to read\n         */\n\n        private Encoder? _thisEncoder;\n        private Decoder? _innerDecoder;\n        private int _readCharBufferMaxSize; // the maximum number of characters _innerDecoder.ReadChars can return\n        private byte[]? _readBuffer; // contains the data that Read() should return\n        private int _readBufferOffset;\n        private int _readBufferCount;\n\n        internal TranscodingStream(Stream innerStream, Encoding innerEncoding, Encoding thisEncoding, bool leaveOpen = false)\n        {\n            _innerStream = innerStream ?? throw Error.ArgumentNull(nameof(innerStream));\n            _leaveOpen = leaveOpen;\n\n            _innerEncoding = innerEncoding ?? throw Error.ArgumentNull(nameof(innerEncoding));\n            _thisEncoding = thisEncoding ?? throw Error.ArgumentNull(nameof(thisEncoding));\n        }\n\n        /*\n         * Most CanXyz methods delegate to the inner stream, returning false\n         * if this instance has been disposed. CanSeek is always false.\n         */\n\n        public override bool CanRead => _innerStream?.CanRead ?? false;\n\n        public override bool CanSeek => false;\n\n        public override bool CanWrite => _innerStream?.CanWrite ?? false;\n\n        public override long Length => throw Error.NotSupported(Properties.Resources.NotSupported_UnseekableStream);\n\n        public override long Position\n        {\n            get => throw Error.NotSupported(Properties.Resources.NotSupported_UnseekableStream);\n            set => throw Error.NotSupported(Properties.Resources.NotSupported_UnseekableStream);\n        }\n\n        protected override void Dispose(bool disposing)\n        {\n            Debug.Assert(disposing, \"This type isn't finalizable.\");\n            base.Dispose(disposing);\n\n            if (_innerStream is null)\n            {\n                return; // dispose called multiple times, ignore\n            }\n\n            // First, flush any pending data to the inner stream.\n\n            ArraySegment<byte> pendingData = FinalFlushWriteBuffers();\n            if (pendingData.Count != 0)\n            {\n                _innerStream.Write(pendingData.Array, pendingData.Offset, pendingData.Count);\n            }\n\n            // Mark our object as disposed\n\n            Stream innerStream = _innerStream;\n            _innerStream = null!;\n\n            // And dispose the inner stream if needed\n\n            if (!_leaveOpen)\n            {\n                innerStream.Dispose();\n            }\n        }\n\n#if NETCOREAPP3_1_OR_GREATER || NETSTANDARD2_1\n        public override ValueTask DisposeAsync()\n        {\n            if (_innerStream is null)\n            {\n                return default; // dispose called multiple times, ignore\n            }\n\n            // First, get any pending data destined for the inner stream.\n\n            ArraySegment<byte> pendingData = FinalFlushWriteBuffers();\n\n            if (pendingData.Count == 0)\n            {\n                // Fast path: just dispose of the object graph.\n                // No need to write anything to the stream first.\n\n                Stream innerStream = _innerStream;\n                _innerStream = null!;\n\n                return (_leaveOpen)\n                    ? default /* no work to do */\n                    : innerStream.DisposeAsync();\n            }\n\n            // Slower path; need to perform an async write followed by an async dispose.\n\n            return DisposeAsyncCore(pendingData);\n            async ValueTask DisposeAsyncCore(ArraySegment<byte> pendingData)\n            {\n                Debug.Assert(pendingData.Count != 0);\n\n                Stream innerStream = _innerStream;\n                _innerStream = null!;\n\n                await innerStream.WriteAsync(pendingData.AsMemory()).ConfigureAwait(false);\n\n                if (!_leaveOpen)\n                {\n                    await innerStream.DisposeAsync().ConfigureAwait(false);\n                }\n            }\n        }\n#endif\n\n#pragma warning disable CS3016 // Arrays as attribute arguments is not CLS-compliant\n#pragma warning disable CS8774 // Member must have a non-null value when exiting.\n\n        // Sets up the data structures that are necessary before any read operation takes place,\n        // throwing if the object is in a state where reads are not possible.\n        [MemberNotNull(nameof(_innerDecoder), nameof(_thisEncoder), nameof(_readBuffer))]\n        private void EnsurePreReadConditions()\n        {\n            ThrowIfDisposed();\n            if (_innerDecoder is null)\n            {\n                InitializeReadDataStructures();\n            }\n\n            void InitializeReadDataStructures()\n            {\n                if (!CanRead)\n                {\n                    throw Error.NotSupported(Properties.Resources.NotSupported_UnreadableStream);\n                }\n\n                _innerDecoder = _innerEncoding.GetDecoder();\n                _thisEncoder = _thisEncoding.GetEncoder();\n                _readCharBufferMaxSize = _innerEncoding.GetMaxCharCount(DefaultReadByteBufferSize);\n\n                // Can't use ArrayPool for the below array since it's an instance field of this object.\n                // But since we never expose the raw array contents to our callers we can get away\n                // with skipping the array zero-init during allocation. The segment points to the\n                // data which we haven't yet read; however, we own the entire backing array and can\n                // re-create the segment as needed once the array is repopulated.\n\n#if NET5_0_OR_GREATER\n                _readBuffer = GC.AllocateUninitializedArray<byte>(_thisEncoding.GetMaxByteCount(_readCharBufferMaxSize));\n#else\n                _readBuffer = new byte[_thisEncoding.GetMaxByteCount(_readCharBufferMaxSize)];\n#endif\n            }\n        }\n\n        // Sets up the data structures that are necessary before any write operation takes place,\n        // throwing if the object is in a state where writes are not possible.\n        [MemberNotNull(nameof(_thisDecoder), nameof(_innerEncoder))]\n        private void EnsurePreWriteConditions()\n        {\n            ThrowIfDisposed();\n            if (_innerEncoder is null)\n            {\n                InitializeReadDataStructures();\n            }\n\n            void InitializeReadDataStructures()\n            {\n                if (!CanWrite)\n                {\n                    throw Error.NotSupported(Properties.Resources.NotSupported_UnwritableStream);\n                }\n\n                _innerEncoder = _innerEncoding.GetEncoder();\n                _thisDecoder = _thisEncoding.GetDecoder();\n            }\n        }\n\n#pragma warning restore CS8774 // Member must have a non-null value when exiting.\n#pragma warning restore CS3016 // Arrays as attribute arguments is not CLS-compliant\n\n        // returns any pending data that needs to be flushed to the inner stream before disposal\n        private ArraySegment<byte> FinalFlushWriteBuffers()\n        {\n            // If this stream was never used for writing, no-op.\n\n            if (_thisDecoder is null || _innerEncoder is null)\n            {\n                return default;\n            }\n\n            // convert bytes [this] -> chars\n            // Having leftover data in our buffers should be very rare since it should only\n            // occur if the end of the stream contains an incomplete multi-byte sequence.\n            // Let's not bother complicating this logic with array pool rentals or allocation-\n            // avoiding loops.\n\n            char[] chars = EmptyCharBuffer;\n            int charCount = _thisDecoder.GetCharCount(EmptyByteBuffer, 0, 0, flush: true);\n            if (charCount > 0)\n            {\n                chars = new char[charCount];\n                charCount = _thisDecoder.GetChars(EmptyByteBuffer, 0, 0, chars, 0, flush: true);\n            }\n\n            // convert chars -> bytes [inner]\n            // It's possible that _innerEncoder might need to perform some end-of-text fixup\n            // (due to flush: true), even if _thisDecoder didn't need to do so.\n\n            byte[] bytes = EmptyByteBuffer;\n            int byteCount = _innerEncoder.GetByteCount(chars, 0, charCount, flush: true);\n            if (byteCount > 0)\n            {\n                bytes = new byte[byteCount];\n                byteCount = _innerEncoder.GetBytes(chars, 0, charCount, bytes, 0, flush: true);\n            }\n\n            return new ArraySegment<byte>(bytes, 0, byteCount);\n        }\n\n        public override void Flush()\n        {\n            // Don't pass flush: true to our inner decoder + encoder here, since it could cause data\n            // corruption if a flush occurs mid-stream. Wait until the stream is being closed.\n\n            ThrowIfDisposed();\n            _innerStream.Flush();\n        }\n\n        public override Task FlushAsync(CancellationToken cancellationToken)\n        {\n            // Don't pass flush: true to our inner decoder + encoder here, since it could cause data\n            // corruption if a flush occurs mid-stream. Wait until the stream is being closed.\n\n            ThrowIfDisposed();\n            return _innerStream.FlushAsync(cancellationToken);\n        }\n\n        public override int Read(byte[] buffer, int offset, int count)\n        {\n            ValidateBufferArguments(buffer, offset, count);\n\n            return Read(new Span<byte>(buffer, offset, count));\n        }\n\n#if NETCOREAPP || NETSTANDARD2_1\n        public override\n#else\n        private\n#endif\n        int Read(Span<byte> buffer)\n        {\n            EnsurePreReadConditions();\n\n            // If there's no data in our pending read buffer, we'll need to populate it from\n            // the inner stream. We read the inner stream's bytes, decode that to chars using\n            // the 'inner' encoding, then re-encode those chars under the 'this' encoding.\n            // We've already calculated the worst-case expansions for the intermediate buffers,\n            // so we use GetChars / GetBytes instead of Convert to simplify the below code\n            // and to ensure an exception is thrown if the Encoding reported an incorrect\n            // worst-case expansion.\n\n            if (_readBufferCount == 0)\n            {\n                byte[] rentedBytes = ArrayPool<byte>.Shared.Rent(DefaultReadByteBufferSize);\n                char[] rentedChars = ArrayPool<char>.Shared.Rent(_readCharBufferMaxSize);\n\n                try\n                {\n                    int pendingReadDataPopulatedJustNow;\n                    bool isEofReached;\n\n                    do\n                    {\n                        // Beware: Use our constant value instead of 'rentedBytes.Length' for the count\n                        // parameter below. The reason for this is that the array pool could've returned\n                        // a larger-than-expected array, but our worst-case expansion calculations\n                        // performed earlier didn't take that into account.\n\n                        int innerBytesReadJustNow = _innerStream.Read(rentedBytes, 0, DefaultReadByteBufferSize);\n                        isEofReached = (innerBytesReadJustNow == 0);\n\n                        // Convert bytes [inner] -> chars, then convert chars -> bytes [this].\n                        // We can't return 0 to our caller until inner stream EOF has been reached. But if the\n                        // inner stream returns a non-empty but incomplete buffer, GetBytes may return 0 anyway\n                        // since it can't yet make forward progress on the input data. If this happens, we'll\n                        // loop so that we don't return 0 to our caller until we truly see inner stream EOF.\n\n                        int charsDecodedJustNow = _innerDecoder.GetChars(rentedBytes, 0, innerBytesReadJustNow, rentedChars, 0, flush: isEofReached);\n                        pendingReadDataPopulatedJustNow = _thisEncoder.GetBytes(rentedChars, 0, charsDecodedJustNow, _readBuffer, 0, flush: isEofReached);\n                    } while (!isEofReached && pendingReadDataPopulatedJustNow == 0);\n\n                    _readBufferOffset = 0;\n                    _readBufferCount = pendingReadDataPopulatedJustNow;\n                }\n                finally\n                {\n                    ArrayPool<byte>.Shared.Return(rentedBytes);\n                    ArrayPool<char>.Shared.Return(rentedChars);\n                }\n            }\n\n            // At this point: (a) we've populated our pending read buffer and there's\n            // useful data to return to our caller; or (b) the pending read buffer is\n            // empty because the inner stream has reached EOF and all pending read data\n            // has already been flushed, and we should return 0.\n\n            int bytesToReturn = Math.Min(_readBufferCount, buffer.Length);\n            _readBuffer.AsSpan(_readBufferOffset, bytesToReturn).CopyTo(buffer);\n            _readBufferOffset += bytesToReturn;\n            _readBufferCount -= bytesToReturn;\n            return bytesToReturn;\n        }\n\n        public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)\n        {\n            ValidateBufferArguments(buffer, offset, count);\n\n            return ReadAsync(new Memory<byte>(buffer, offset, count), cancellationToken).AsTask();\n        }\n\n#if NETCOREAPP || NETSTANDARD2_1\n        public override\n#else\n        private\n#endif\n        ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)\n        {\n            EnsurePreReadConditions();\n\n            if (cancellationToken.IsCancellationRequested)\n            {\n#if NETCOREAPP || NETSTANDARD\n                return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken));\n#else\n                // Lose track of the CancellationToken in this case.\n                return new ValueTask<int>(TaskHelpers.Canceled<int>());\n#endif\n            }\n\n            return ReadAsyncCore(buffer, cancellationToken);\n            async ValueTask<int> ReadAsyncCore(Memory<byte> buffer, CancellationToken cancellationToken)\n            {\n                // If there's no data in our pending read buffer, we'll need to populate it from\n                // the inner stream. We read the inner stream's bytes, decode that to chars using\n                // the 'inner' encoding, then re-encode those chars under the 'this' encoding.\n                // We've already calculated the worst-case expansions for the intermediate buffers,\n                // so we use GetChars / GetBytes instead of Convert to simplify the below code\n                // and to ensure an exception is thrown if the Encoding reported an incorrect\n                // worst-case expansion.\n\n                if (_readBufferCount == 0)\n                {\n                    byte[] rentedBytes = ArrayPool<byte>.Shared.Rent(DefaultReadByteBufferSize);\n                    char[] rentedChars = ArrayPool<char>.Shared.Rent(_readCharBufferMaxSize);\n\n                    try\n                    {\n                        int pendingReadDataPopulatedJustNow;\n                        bool isEofReached;\n\n                        do\n                        {\n                            // Beware: Use our constant value instead of 'rentedBytes.Length' when creating\n                            // the Mem<byte> struct. The reason for this is that the array pool could've returned\n                            // a larger-than-expected array, but our worst-case expansion calculations\n                            // performed earlier didn't take that into account.\n\n                            int innerBytesReadJustNow = await _innerStream.ReadAsync(rentedBytes, 0, DefaultReadByteBufferSize, cancellationToken).ConfigureAwait(false);\n                            isEofReached = (innerBytesReadJustNow == 0);\n\n                            // Convert bytes [inner] -> chars, then convert chars -> bytes [this].\n                            // We can't return 0 to our caller until inner stream EOF has been reached. But if the\n                            // inner stream returns a non-empty but incomplete buffer, GetBytes may return 0 anyway\n                            // since it can't yet make forward progress on the input data. If this happens, we'll\n                            // loop so that we don't return 0 to our caller until we truly see inner stream EOF.\n\n                            int charsDecodedJustNow = _innerDecoder.GetChars(rentedBytes, 0, innerBytesReadJustNow, rentedChars, 0, flush: isEofReached);\n                            pendingReadDataPopulatedJustNow = _thisEncoder.GetBytes(rentedChars, 0, charsDecodedJustNow, _readBuffer, 0, flush: isEofReached);\n                        } while (!isEofReached && pendingReadDataPopulatedJustNow == 0);\n\n                        _readBufferOffset = 0;\n                        _readBufferCount = pendingReadDataPopulatedJustNow;\n                    }\n                    finally\n                    {\n                        ArrayPool<byte>.Shared.Return(rentedBytes);\n                        ArrayPool<char>.Shared.Return(rentedChars);\n                    }\n                }\n\n                // At this point: (a) we've populated our pending read buffer and there's\n                // useful data to return to our caller; or (b) the pending read buffer is\n                // empty because the inner stream has reached EOF and all pending read data\n                // has already been flushed, and we should return 0.\n\n                int bytesToReturn = Math.Min(_readBufferCount, buffer.Length);\n                _readBuffer.AsSpan(_readBufferOffset, bytesToReturn).CopyTo(buffer.Span);\n                _readBufferOffset += bytesToReturn;\n                _readBufferCount -= bytesToReturn;\n                return bytesToReturn;\n            }\n        }\n\n        public override int ReadByte()\n        {\n            return Read(_singleByteBuffer, offset: 0, count: 1) != 0 ? _singleByteBuffer[0] : -1;\n        }\n\n        public override long Seek(long offset, SeekOrigin origin)\n            => throw Error.NotSupported(Properties.Resources.NotSupported_UnseekableStream);\n\n        public override void SetLength(long value)\n            => throw Error.NotSupported(Properties.Resources.NotSupported_UnseekableStream);\n\n#if NET6_0_OR_GREATER\n        [StackTraceHidden]\n#endif\n        private void ThrowIfDisposed()\n        {\n            if (_innerStream is null)\n            {\n                ThrowObjectDisposedException();\n            }\n        }\n\n        [DoesNotReturn]\n#if NET6_0_OR_GREATER\n        [StackTraceHidden]\n#endif\n        private void ThrowObjectDisposedException()\n        {\n            throw new ObjectDisposedException(GetType().Name, Properties.Resources.ObjectDisposed_StreamClosed);\n        }\n\n        public override void Write(byte[] buffer, int offset, int count)\n        {\n            ValidateBufferArguments(buffer, offset, count);\n\n#if NETCOREAPP || NETSTANDARD2_1\n            Write(new ReadOnlySpan<byte>(buffer, offset, count));\n#else\n            WriteCore(buffer, offset, count);\n#endif\n        }\n\n#if NETCOREAPP || NETSTANDARD2_1\n        public override void Write(ReadOnlySpan<byte> buffer)\n        {\n            EnsurePreWriteConditions();\n\n            if (buffer.IsEmpty)\n            {\n                return;\n            }\n\n            int rentalLength = buffer.Length < MinWriteRentedArraySize ? MinWriteRentedArraySize :\n                buffer.Length > MaxWriteRentedArraySize ? MaxWriteRentedArraySize :\n                buffer.Length;\n\n            char[] scratchChars = ArrayPool<char>.Shared.Rent(rentalLength);\n            byte[] scratchBytes = ArrayPool<byte>.Shared.Rent(rentalLength);\n\n            try\n            {\n                bool decoderFinished, encoderFinished;\n                do\n                {\n                    // convert bytes [this] -> chars\n\n                    _thisDecoder.Convert(\n                        bytes: buffer,\n                        chars: scratchChars,\n                        flush: false,\n                        out int bytesConsumed,\n                        out int charsWritten,\n                        out decoderFinished);\n\n                    buffer = buffer.Slice(bytesConsumed);\n\n                    // convert chars -> bytes [inner]\n\n                    Span<char> decodedChars = scratchChars.AsSpan(0, charsWritten);\n\n                    do\n                    {\n                        _innerEncoder.Convert(\n                            chars: decodedChars,\n                            bytes: scratchBytes,\n                            flush: false,\n                            out int charsConsumed,\n                            out int bytesWritten,\n                            out encoderFinished);\n\n                        decodedChars = decodedChars.Slice(charsConsumed);\n\n                        // It's more likely that the inner stream provides an optimized implementation of\n                        // Write(byte[], ...) over Write(ROS<byte>), so we'll prefer the byte[]-based overloads.\n\n                        _innerStream.Write(scratchBytes, 0, bytesWritten);\n                    } while (!encoderFinished);\n                } while (!decoderFinished);\n            }\n            finally\n            {\n                ArrayPool<char>.Shared.Return(scratchChars);\n                ArrayPool<byte>.Shared.Return(scratchBytes);\n            }\n        }\n#else\n        private void WriteCore(byte[] buffer, int offset, int count)\n        {\n            EnsurePreWriteConditions();\n\n            if (count == 0)\n            {\n                return;\n            }\n\n            int rentalLength = buffer.Length < MinWriteRentedArraySize ? MinWriteRentedArraySize :\n                buffer.Length > MaxWriteRentedArraySize ? MaxWriteRentedArraySize :\n                buffer.Length;\n\n            char[] scratchChars = ArrayPool<char>.Shared.Rent(rentalLength);\n            byte[] scratchBytes = ArrayPool<byte>.Shared.Rent(rentalLength);\n\n            try\n            {\n                bool decoderFinished, encoderFinished;\n                do\n                {\n                    // convert bytes [this] -> chars\n\n                    _thisDecoder.Convert(\n                        bytes: buffer,\n                        byteIndex: offset,\n                        byteCount: count,\n                        chars: scratchChars,\n                        charIndex: 0,\n                        charCount: rentalLength,\n                        flush: false,\n                        out int bytesConsumed,\n                        out int charsWritten,\n                        out decoderFinished);\n\n                    offset += bytesConsumed;\n                    count -= bytesConsumed;\n\n                    // convert chars -> bytes [inner]\n\n                    int scratchOffset = 0;\n                    do\n                    {\n                        _innerEncoder.Convert(\n                            chars: scratchChars,\n                            charIndex: scratchOffset,\n                            charCount: charsWritten,\n                            bytes: scratchBytes,\n                            byteIndex: 0,\n                            byteCount: rentalLength,\n                            flush: false,\n                            out int charsConsumed,\n                            out int bytesWritten,\n                            out encoderFinished);\n\n                        scratchOffset += charsConsumed;\n                        charsWritten -= charsConsumed;\n\n                        // It's more likely that the inner stream provides an optimized implementation of\n                        // Write(byte[], ...) over Write(ROS<byte>), so we'll prefer the byte[]-based overloads.\n\n                        _innerStream.Write(scratchBytes, 0, bytesWritten);\n                    } while (!encoderFinished);\n                } while (!decoderFinished);\n            }\n            finally\n            {\n                ArrayPool<char>.Shared.Return(scratchChars);\n                ArrayPool<byte>.Shared.Return(scratchBytes);\n            }\n        }\n#endif\n\n        public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)\n        {\n            ValidateBufferArguments(buffer, offset, count);\n\n#if NETCOREAPP || NETSTANDARD2_1\n            return WriteAsync(new ReadOnlyMemory<byte>(buffer, offset, count), cancellationToken).AsTask();\n#else\n            return WriteAsyncCore(buffer, offset, count, cancellationToken).AsTask();\n#endif\n        }\n\n#if NETCOREAPP || NETSTANDARD2_1\n        public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)\n        {\n            EnsurePreWriteConditions();\n\n            if (cancellationToken.IsCancellationRequested)\n            {\n                return new ValueTask(Task.FromCanceled<int>(cancellationToken));\n            }\n\n            if (buffer.IsEmpty)\n            {\n                // ValueTask.CompletedTask\n                return default;\n            }\n\n            return WriteAsyncCore(buffer, cancellationToken);\n            async ValueTask WriteAsyncCore(ReadOnlyMemory<byte> remainingOuterEncodedBytes, CancellationToken cancellationToken)\n            {\n                int rentalLength = remainingOuterEncodedBytes.Length < MinWriteRentedArraySize ? MinWriteRentedArraySize :\n                    remainingOuterEncodedBytes.Length > MaxWriteRentedArraySize ? MaxWriteRentedArraySize:\n                    remainingOuterEncodedBytes.Length;\n\n                char[] scratchChars = ArrayPool<char>.Shared.Rent(rentalLength);\n                byte[] scratchBytes = ArrayPool<byte>.Shared.Rent(rentalLength);\n\n                try\n                {\n                    bool decoderFinished, encoderFinished;\n                    do\n                    {\n                        // convert bytes [this] -> chars\n\n                        _thisDecoder.Convert(\n                            bytes: buffer,\n                            chars: scratchChars,\n                            flush: false,\n                            out int bytesConsumed,\n                            out int charsWritten,\n                            out decoderFinished);\n\n                        buffer = buffer.Slice(bytesConsumed);\n\n                        // convert chars -> bytes [inner]\n\n                        Span<char> decodedChars = scratchChars.AsSpan(0, charsWritten);\n\n                        do\n                        {\n                            _innerEncoder.Convert(\n                                chars: decodedChars,\n                                bytes: scratchBytes,\n                                flush: false,\n                                out int charsConsumed,\n                                out int bytesWritten,\n                                out encoderFinished);\n\n                            decodedChars = decodedChars.Slice(charsConsumed);\n\n                            await _innerStream.WriteAsync(scratchBytes, 0, bytesWritten, cancellationToken).ConfigureAwait(false);\n                        } while (!encoderFinished);\n                    } while (!decoderFinished);\n                }\n                finally\n                {\n                    ArrayPool<char>.Shared.Return(scratchChars);\n                    ArrayPool<byte>.Shared.Return(scratchBytes);\n                }\n            }\n        }\n#else\n        private ValueTask WriteAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken)\n        {\n            EnsurePreWriteConditions();\n\n            if (cancellationToken.IsCancellationRequested)\n            {\n#if NETSTANDARD\n                return new ValueTask(Task.FromCanceled<int>(cancellationToken));\n#else\n                // Lose track of the CancellationToken in this case.\n                return new ValueTask(TaskHelpers.Canceled());\n#endif\n            }\n\n            if (count == 0)\n            {\n                // ValueTask.CompletedTask\n                return default;\n            }\n\n            return WriteAsyncCore(buffer, cancellationToken);\n            async ValueTask WriteAsyncCore(ReadOnlyMemory<byte> remainingOuterEncodedBytes, CancellationToken cancellationToken)\n            {\n                int rentalLength = remainingOuterEncodedBytes.Length < MinWriteRentedArraySize ? MinWriteRentedArraySize :\n                    remainingOuterEncodedBytes.Length > MaxWriteRentedArraySize ? MaxWriteRentedArraySize :\n                    remainingOuterEncodedBytes.Length;\n\n                char[] scratchChars = ArrayPool<char>.Shared.Rent(rentalLength);\n                byte[] scratchBytes = ArrayPool<byte>.Shared.Rent(rentalLength);\n\n                try\n                {\n                    bool decoderFinished, encoderFinished;\n                    do\n                    {\n                        // convert bytes [this] -> chars\n\n                        _thisDecoder.Convert(\n                            bytes: buffer,\n                            byteIndex: offset,\n                            byteCount: count,\n                            chars: scratchChars,\n                            charIndex: 0,\n                            charCount: rentalLength,\n                            flush: false,\n                            out int bytesConsumed,\n                            out int charsWritten,\n                            out decoderFinished);\n\n                        offset += bytesConsumed;\n                        count -= bytesConsumed;\n\n                        // convert chars -> bytes [inner]\n\n                        int scratchOffset = 0;\n                        do\n                        {\n                            _innerEncoder.Convert(\n                                chars: scratchChars,\n                                charIndex: scratchOffset,\n                                charCount: charsWritten,\n                                bytes: scratchBytes,\n                                byteIndex: 0,\n                                byteCount: rentalLength,\n                                flush: false,\n                                out int charsConsumed,\n                                out int bytesWritten,\n                                out encoderFinished);\n\n                            scratchOffset += charsConsumed;\n                            charsWritten -= charsConsumed;\n\n                            await _innerStream.WriteAsync(scratchBytes, 0, bytesWritten, cancellationToken).ConfigureAwait(false);\n                        } while (!encoderFinished);\n                    } while (!decoderFinished);\n                }\n                finally\n                {\n                    ArrayPool<char>.Shared.Return(scratchChars);\n                    ArrayPool<byte>.Shared.Return(scratchBytes);\n                }\n            }\n        }\n#endif\n\n        public override void WriteByte(byte value)\n        {\n            _singleByteBuffer[0] = value;\n            Write(_singleByteBuffer, offset: 0, count: 1);\n        }\n\n        // From https://github.com/dotnet/runtime/blob/88868b7a781f4e5b9037b8721f30440207a7aa42/src/libraries/System.Private.CoreLib/src/System/IO/Stream.cs\n\n        [MethodImpl(MethodImplOptions.AggressiveInlining)]\n        private static void ValidateBufferArguments(byte[] buffer, int offset, int count)\n        {\n            if (buffer is null)\n            {\n                throw Error.ArgumentNull(nameof(buffer));\n            }\n\n            if (offset < 0)\n            {\n                throw Error.ArgumentMustBeGreaterThanOrEqualTo(nameof(offset), offset, minValue: 0);\n            }\n\n            if ((uint)count > buffer.Length - offset)\n            {\n                throw Error.ArgumentOutOfRange(nameof(count), count, Properties.Resources.Argument_InvalidOffLen);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Internal/TypeExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Reflection;\n\nnamespace System.Net.Http\n{\n    internal static class TypeExtensions\n    {\n#if NETSTANDARD1_3\n        private static bool EqualTo(this Type[] t1, Type[] t2)\n        {\n            if (t1.Length != t2.Length)\n            {\n                return false;\n            }\n\n            for (int idx = 0; idx < t1.Length; ++idx)\n            {\n                if (t1[idx] != t2[idx])\n                {\n                    return false;\n                }\n            }\n\n            return true;\n        }\n\n        public static ConstructorInfo GetConstructor(this Type type, Type[] types)\n        {\n            return type.GetTypeInfo().DeclaredConstructors\n                                     .Where(c => c.IsPublic)\n                                     .SingleOrDefault(c => c.GetParameters()\n                                                            .Select(p => p.ParameterType).ToArray().EqualTo(types));\n        }\n#endif\n\n        public static Type ExtractGenericInterface(this Type queryType, Type interfaceType)\n        {\n            Func<Type, bool> matchesInterface = t => t.IsGenericType() && t.GetGenericTypeDefinition() == interfaceType;\n            return (matchesInterface(queryType)) ? queryType : queryType.GetInterfaces().FirstOrDefault(matchesInterface);\n        }\n\n#if NETSTANDARD1_3\n        public static Type[] GetGenericArguments(this Type type)\n        {\n            return type.GetTypeInfo().GenericTypeArguments;\n        }\n\n        public static Type[] GetInterfaces(this Type type)\n        {\n            return type.GetTypeInfo().ImplementedInterfaces.ToArray();\n        }\n#endif\n\n#if NETSTANDARD1_3\n        public static bool IsAssignableFrom(this Type type, Type c)\n        {\n            return type.GetTypeInfo().IsAssignableFrom(c.GetTypeInfo());\n        }\n#endif\n\n        public static bool IsGenericType(this Type type)\n        {\n#if NETSTANDARD1_3\n            return type.GetTypeInfo().IsGenericType;\n#else\n            return type.IsGenericType;\n#endif\n        }\n\n        public static bool IsInterface(this Type type)\n        {\n#if NETSTANDARD1_3\n            return type.GetTypeInfo().IsInterface;\n#else\n            return type.IsInterface;\n#endif\n        }\n\n        public static bool IsValueType(this Type type)\n        {\n#if NETSTANDARD1_3\n            return type.GetTypeInfo().IsValueType;\n#else\n            return type.IsValueType;\n#endif\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/InvalidByteRangeException.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Net.Http.Headers;\nusing System.Runtime.Serialization;\nusing System.Web.Http;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// An exception thrown by <see cref=\"ByteRangeStreamContent\"/> in case none of the requested ranges\n    /// overlap with the current extend of the selected resource. The current extend of the resource\n    /// is indicated in the ContentRange property.\n    /// </summary>\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2237:MarkISerializableTypesWithSerializable\", Justification = \"Exception is not intended to be serialized.\")]\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2240:ImplementISerializableCorrectly\", Justification = \"Exception is not intended to be serialized.\")]\n    [SuppressMessage(\"Microsoft.Design\", \"CA1032:ImplementStandardExceptionConstructors\", Justification = \"The ContentRange is a required parameter.\")]\n    public class InvalidByteRangeException : Exception\n    {\n        public InvalidByteRangeException(ContentRangeHeaderValue contentRange)\n        {\n            Initialize(contentRange);\n        }\n\n        public InvalidByteRangeException(ContentRangeHeaderValue contentRange, string message)\n            : base(message)\n        {\n            Initialize(contentRange);\n        }\n\n        public InvalidByteRangeException(ContentRangeHeaderValue contentRange, string message, Exception innerException)\n            : base(message, innerException)\n        {\n            Initialize(contentRange);\n        }\n\n#if !NETSTANDARD1_3 // Exception is not serializable in netstandard1.3.\n        public InvalidByteRangeException(ContentRangeHeaderValue contentRange, SerializationInfo info, StreamingContext context)\n            : base(info, context)\n        {\n            Initialize(contentRange);\n        }\n#endif\n\n        /// <summary>\n        /// The current extend of the resource indicated in terms of a ContentRange header field.\n        /// </summary>\n        public ContentRangeHeaderValue ContentRange { get; private set; }\n\n        private void Initialize(ContentRangeHeaderValue contentRange)\n        {\n            if (contentRange == null)\n            {\n                throw Error.ArgumentNull(\"contentRange\");\n            }\n            ContentRange = contentRange;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/MimeBodyPart.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.IO;\nusing System.Net.Http.Formatting.Parsers;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// Maintains information about MIME body parts parsed by <see cref=\"MimeMultipartBodyPartParser\"/>.\n    /// </summary>\n    internal class MimeBodyPart : IDisposable\n    {\n        private static readonly Type _streamType = typeof(Stream);\n        private Stream _outputStream;\n        private MultipartStreamProvider _streamProvider;\n        private HttpContent _parentContent;\n        private HttpContent _content;\n        private HttpContentHeaders _headers;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"MimeBodyPart\"/> class.\n        /// </summary>\n        /// <param name=\"streamProvider\">The stream provider.</param>\n        /// <param name=\"maxBodyPartHeaderSize\">The max length of the MIME header within each MIME body part.</param>\n        /// <param name=\"parentContent\">The part's parent content</param>\n        public MimeBodyPart(MultipartStreamProvider streamProvider, int maxBodyPartHeaderSize, HttpContent parentContent)\n        {\n            Contract.Assert(streamProvider != null);\n            Contract.Assert(parentContent != null);\n            _streamProvider = streamProvider;\n            _parentContent = parentContent;\n            Segments = new List<ArraySegment<byte>>(2);\n            _headers = FormattingUtilities.CreateEmptyContentHeaders();\n            HeaderParser = new InternetMessageFormatHeaderParser(\n                _headers,\n                maxBodyPartHeaderSize,\n                ignoreHeaderValidation: true);\n        }\n\n        /// <summary>\n        /// Gets the header parser.\n        /// </summary>\n        /// <value>\n        /// The header parser.\n        /// </value>\n        public InternetMessageFormatHeaderParser HeaderParser { get; private set; }\n\n        /// <summary>\n        /// Gets the part's content as an HttpContent.\n        /// </summary>\n        /// <value>\n        /// The part's content, or null if the part had no content.\n        /// </value>\n        public HttpContent GetCompletedHttpContent()\n        {\n            Contract.Assert(IsComplete);\n\n            if (_content == null)\n            {\n                return null;\n            }\n\n            _headers.CopyTo(_content.Headers);\n            return _content;\n        }\n\n        /// <summary>\n        /// Gets the set of <see cref=\"ArraySegment{T}\"/> pointing to the read buffer with\n        /// contents of this body part.\n        /// </summary>\n        public List<ArraySegment<byte>> Segments { get; private set; }\n\n        /// <summary>\n        /// Gets or sets a value indicating whether the body part has been completed.\n        /// </summary>\n        /// <value>\n        /// <c>true</c> if this instance is complete; otherwise, <c>false</c>.\n        /// </value>\n        public bool IsComplete { get; set; }\n\n        /// <summary>\n        /// Gets or sets a value indicating whether this is the final body part.\n        /// </summary>\n        /// <value>\n        /// <c>true</c> if this instance is complete; otherwise, <c>false</c>.\n        /// </value>\n        public bool IsFinal { get; set; }\n\n        /// <summary>\n        /// Writes the <paramref name=\"segment\"/> into the part's output stream.\n        /// </summary>\n        /// <param name=\"segment\">The current segment to be written to the part's output stream.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        public async Task WriteSegment(ArraySegment<byte> segment, CancellationToken cancellationToken)\n        {\n            var stream = GetOutputStream();\n            await stream.WriteAsync(segment.Array, segment.Offset, segment.Count, cancellationToken);\n        }\n\n        /// <summary>\n        /// Gets the output stream.\n        /// </summary>\n        /// <returns>The output stream to write the body part to.</returns>\n        private Stream GetOutputStream()\n        {\n            if (_outputStream == null)\n            {\n                try\n                {\n                    _outputStream = _streamProvider.GetStream(_parentContent, _headers);\n                }\n                catch (Exception e)\n                {\n                    throw Error.InvalidOperation(e, Properties.Resources.ReadAsMimeMultipartStreamProviderException, _streamProvider.GetType().Name);\n                }\n\n                if (_outputStream == null)\n                {\n                    throw Error.InvalidOperation(Properties.Resources.ReadAsMimeMultipartStreamProviderNull, _streamProvider.GetType().Name, _streamType.Name);\n                }\n\n                if (!_outputStream.CanWrite)\n                {\n                    throw Error.InvalidOperation(Properties.Resources.ReadAsMimeMultipartStreamProviderReadOnly, _streamProvider.GetType().Name, _streamType.Name);\n                }\n                _content = new StreamContent(_outputStream);\n            }\n\n            return _outputStream;\n        }\n\n        /// <summary>\n        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.\n        /// </summary>\n        public void Dispose()\n        {\n            Dispose(true);\n            GC.SuppressFinalize(this);\n        }\n\n        /// <summary>\n        /// Releases unmanaged and - optionally - managed resources\n        /// </summary>\n        /// <param name=\"disposing\"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>\n        protected void Dispose(bool disposing)\n        {\n            if (disposing)\n            {\n                CleanupOutputStream();\n                CleanupHttpContent();\n                _parentContent = null;\n                HeaderParser = null;\n                Segments.Clear();\n            }\n        }\n\n        /// <summary>\n        /// In the success case, the HttpContent is to be used after this Part has been parsed and disposed of.\n        /// Only if Dispose has been called on a non-completed part, the parsed HttpContent needs to be disposed of as well.\n        /// </summary>\n        private void CleanupHttpContent()\n        {\n            if (!IsComplete && _content != null)\n            {\n                _content.Dispose();\n            }\n\n            _content = null;\n        }\n\n        /// <summary>\n        /// Resets the output stream by either closing it or, in the case of a <see cref=\"MemoryStream\"/> resetting\n        /// position to 0 so that it can be read by the caller.\n        /// </summary>\n        private void CleanupOutputStream()\n        {\n            if (_outputStream != null)\n            {\n                MemoryStream output = _outputStream as MemoryStream;\n                if (output != null)\n                {\n                    output.Position = 0;\n                }\n                else\n                {\n#if NETSTANDARD1_3\n                    _outputStream.Dispose();\n#else\n                    _outputStream.Close();\n#endif\n                }\n\n                _outputStream = null;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/MultipartFileData.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Headers;\nusing System.Web.Http;\n\nnamespace System.Net.Http\n{\n    public class MultipartFileData\n    {\n        public MultipartFileData(HttpContentHeaders headers, string localFileName)\n        {\n            if (headers == null)\n            {\n                throw Error.ArgumentNull(\"headers\");\n            }\n\n            if (localFileName == null)\n            {\n                throw Error.ArgumentNull(\"localFileName\");\n            }\n\n            Headers = headers;\n            LocalFileName = localFileName;\n        }\n\n        public HttpContentHeaders Headers { get; private set; }\n\n        public string LocalFileName { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/MultipartFileStreamProvider.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.IO;\nusing System.Net.Http.Headers;\nusing System.Net.Http.Internal;\nusing System.Web.Http;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// A <see cref=\"MultipartStreamProvider\"/> suited for writing each MIME body parts of the MIME multipart\n    /// message to a file using a <see cref=\"FileStream\"/>.\n    /// </summary>\n    public class MultipartFileStreamProvider : MultipartStreamProvider\n    {\n        private const int MinBufferSize = 1;\n        private const int DefaultBufferSize = 0x1000;\n\n        private string _rootPath;\n        private int _bufferSize = DefaultBufferSize;\n\n        private Collection<MultipartFileData> _fileData = new Collection<MultipartFileData>();\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"MultipartFileStreamProvider\"/> class.\n        /// </summary>\n        /// <param name=\"rootPath\">The root path where the content of MIME multipart body parts are written to.</param>\n        public MultipartFileStreamProvider(string rootPath)\n            : this(rootPath, DefaultBufferSize)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"MultipartFileStreamProvider\"/> class.\n        /// </summary>\n        /// <param name=\"rootPath\">The root path where the content of MIME multipart body parts are written to.</param>\n        /// <param name=\"bufferSize\">The number of bytes buffered for writes to a file.</param>\n        public MultipartFileStreamProvider(string rootPath, int bufferSize)\n        {\n            if (rootPath == null)\n            {\n                throw Error.ArgumentNull(\"rootPath\");\n            }\n\n            if (bufferSize < MinBufferSize)\n            {\n                throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"bufferSize\", bufferSize, MinBufferSize);\n            }\n\n            _rootPath = Path.GetFullPath(rootPath);\n            _bufferSize = bufferSize;\n        }\n\n        /// <summary>\n        /// Gets a collection containing the local files names and associated HTTP content headers of MIME \n        /// body parts written to file.\n        /// </summary>\n        public Collection<MultipartFileData> FileData\n        {\n            get { return _fileData; }\n        }\n\n        /// <summary>\n        /// Gets the root path where the content of MIME multipart body parts are written to.\n        /// </summary>\n        protected string RootPath\n        {\n            get { return _rootPath; }\n        }\n\n        /// <summary>\n        /// Gets the number of bytes buffered for writes to a file.\n        /// </summary>\n        protected int BufferSize\n        {\n            get { return _bufferSize; }\n        }\n\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"Stream is closed by caller (MultipartWriteDelegatingStream is just a wrapper that calls into the inner stream.)\")]\n        public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)\n        {\n            if (parent == null)\n            {\n                throw Error.ArgumentNull(\"parent\");\n            }\n\n            if (headers == null)\n            {\n                throw Error.ArgumentNull(\"headers\");\n            }\n\n            string localFilePath;\n            try\n            {\n                string filename = GetLocalFileName(headers);\n                localFilePath = Path.Combine(_rootPath, Path.GetFileName(filename));\n            }\n            catch (Exception e)\n            {\n                throw Error.InvalidOperation(e, Properties.Resources.MultipartStreamProviderInvalidLocalFileName);\n            }\n\n            // Add local file name \n            MultipartFileData fileData = new MultipartFileData(headers, localFilePath);\n            _fileData.Add(fileData);\n\n            return File.Create(localFilePath, _bufferSize, FileOptions.Asynchronous);\n        }\n\n        /// <summary>\n        /// Gets the name of the local file which will be combined with the root path to\n        /// create an absolute file name where the contents of the current MIME body part\n        /// will be stored.\n        /// </summary>\n        /// <param name=\"headers\">The headers for the current MIME body part.</param>\n        /// <returns>A relative filename with no path component.</returns>\n        public virtual string GetLocalFileName(HttpContentHeaders headers)\n        {\n            if (headers == null)\n            {\n                throw Error.ArgumentNull(\"headers\");\n            }\n\n            return String.Format(CultureInfo.InvariantCulture, \"BodyPart_{0}\", Guid.NewGuid());\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/MultipartFormDataRemoteStreamProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Collections.Specialized;\nusing System.IO;\nusing System.Net.Http.Formatting.Internal;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// A <see cref=\"MultipartStreamProvider\"/> implementation suited for use with HTML file uploads for writing file\n    /// content to a remote storage <see cref=\"Stream\"/>. The stream provider looks at the <b>Content-Disposition</b>\n    /// header field and determines an output remote <see cref=\"Stream\"/> based on the presence of a <b>filename</b>\n    /// parameter. If a <b>filename</b> parameter is present in the <b>Content-Disposition</b> header field, then the\n    /// body part is written to a remote <see cref=\"Stream\"/> provided by <see cref=\"GetRemoteStream\"/>.\n    /// Otherwise it is written to a <see cref=\"MemoryStream\"/>.\n    /// </summary>\n    public abstract class MultipartFormDataRemoteStreamProvider : MultipartStreamProvider\n    {\n        private CancellationToken _cancellationToken = CancellationToken.None;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"MultipartFormDataRemoteStreamProvider\"/> class.\n        /// </summary>\n        protected MultipartFormDataRemoteStreamProvider()\n        {\n            FormData = HttpValueCollection.Create();\n            FileData = new Collection<MultipartRemoteFileData>();\n        }\n\n        /// <summary>\n        /// Gets a collection of file data passed as part of the multipart form data.\n        /// </summary>\n        public Collection<MultipartRemoteFileData> FileData { get; private set; }\n\n        /// <summary>\n        /// Gets a <see cref=\"NameValueCollection\"/> of form data passed as part of the multipart form data.\n        /// </summary>\n        public NameValueCollection FormData { get; private set; }\n\n        /// <summary>\n        /// Provides a <see cref=\"RemoteStreamInfo\"/> for <see cref=\"GetStream\"/>. Override this method to provide a\n        /// remote stream to which the data should be written.\n        /// </summary>\n        /// <param name=\"parent\">The parent <see cref=\"HttpContent\"/> MIME multipart instance.</param>\n        /// <param name=\"headers\">The header fields describing the body part's content. </param>\n        /// <returns>\n        /// A result specifying a remote stream where the file will be written to and a location where the file can be\n        /// accessed. It cannot be null and the stream must be writable.\n        /// </returns>\n        public abstract RemoteStreamInfo GetRemoteStream(HttpContent parent, HttpContentHeaders headers);\n\n        /// <inheritdoc />\n        public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)\n        {\n            if (MultipartFormDataStreamProviderHelper.IsFileContent(parent, headers))\n            {\n                RemoteStreamInfo remoteStreamInfo = GetRemoteStream(parent, headers);\n                if (remoteStreamInfo == null)\n                {\n                    throw Error.InvalidOperation(Properties.Resources.RemoteStreamInfoCannotBeNull,\n                        \"GetRemoteStream\", GetType().Name);\n                }\n                FileData.Add(new MultipartRemoteFileData(headers, remoteStreamInfo.Location, remoteStreamInfo.FileName));\n\n                return remoteStreamInfo.RemoteStream;\n            }\n\n            return new MemoryStream();\n        }\n\n        /// <summary>\n        /// Read the non-file contents as form data.\n        /// </summary>\n        /// <returns>A <see cref=\"Task\"/> representing the post processing.</returns>\n        public override Task ExecutePostProcessingAsync()\n        {\n            // In consistency with existing MultipartFormDataStreamProvider,\n            // this method predates support for cancellation, and we need to make sure it is always invoked when\n            // ExecutePostProcessingAsync is called for compatability.\n            return MultipartFormDataStreamProviderHelper.ReadFormDataAsync(Contents, FormData,\n                _cancellationToken);\n        }\n\n        /// <summary>\n        /// Read the non-file contents as form data.\n        /// </summary>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A <see cref=\"Task\"/> representing the post processing.</returns>\n        public override Task ExecutePostProcessingAsync(CancellationToken cancellationToken)\n        {\n            _cancellationToken = cancellationToken;\n            return ExecutePostProcessingAsync();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/MultipartFormDataStreamProvider.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing System.IO;\nusing System.Net.Http.Formatting.Internal;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// A <see cref=\"MultipartStreamProvider\"/> implementation suited for use with HTML file uploads for writing file\n    /// content to a <see cref=\"FileStream\"/>. The stream provider looks at the <b>Content-Disposition</b> header\n    /// field and determines an output <see cref=\"Stream\"/> based on the presence of a <b>filename</b> parameter.\n    /// If a <b>filename</b> parameter is present in the <b>Content-Disposition</b> header field then the body\n    /// part is written to a <see cref=\"FileStream\"/>, otherwise it is written to a <see cref=\"MemoryStream\"/>.\n    /// This makes it convenient to process MIME Multipart HTML Form data which is a combination of form\n    /// data and file content.\n    /// </summary>\n    public class MultipartFormDataStreamProvider : MultipartFileStreamProvider\n    {\n        // pass around cancellation token through field to maintain backward compat.\n        private CancellationToken _cancellationToken;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"MultipartFormDataStreamProvider\"/> class.\n        /// </summary>\n        /// <param name=\"rootPath\">The root path where the content of MIME multipart body parts are written to.</param>\n        public MultipartFormDataStreamProvider(string rootPath)\n            : base(rootPath)\n        {\n            FormData = HttpValueCollection.Create();\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"MultipartFormDataStreamProvider\"/> class.\n        /// </summary>\n        /// <param name=\"rootPath\">The root path where the content of MIME multipart body parts are written to.</param>\n        /// <param name=\"bufferSize\">The number of bytes buffered for writes to the file.</param>\n        public MultipartFormDataStreamProvider(string rootPath, int bufferSize)\n            : base(rootPath, bufferSize)\n        {\n            FormData = HttpValueCollection.Create();\n        }\n\n        /// <summary>\n        /// Gets a <see cref=\"NameValueCollection\"/> of form data passed as part of the multipart form data.\n        /// </summary>\n        public NameValueCollection FormData { get; private set; }\n\n        /// <summary>\n        /// This body part stream provider examines the headers provided by the MIME multipart parser\n        /// and decides whether it should return a file stream or a memory stream for the body part to be\n        /// written to.\n        /// </summary>\n        /// <param name=\"parent\">The parent MIME multipart HttpContent instance.</param>\n        /// <param name=\"headers\">Header fields describing the body part</param>\n        /// <returns>The <see cref=\"Stream\"/> instance where the message body part is written to.</returns>\n        public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)\n        {\n            if (MultipartFormDataStreamProviderHelper.IsFileContent(parent, headers))\n            {\n                return base.GetStream(parent, headers);\n            }\n\n            return new MemoryStream();\n        }\n\n        /// <summary>\n        /// Read the non-file contents as form data.\n        /// </summary>\n        /// <returns>A <see cref=\"Task\"/> representing the post processing.</returns>\n        public override Task ExecutePostProcessingAsync()\n        {\n            // This method predates support for cancellation, and we need to make sure it is always invoked when\n            // ExecutePostProcessingAsync is called for compatability.\n            return MultipartFormDataStreamProviderHelper.ReadFormDataAsync(Contents, FormData,\n                _cancellationToken);\n        }\n\n        /// <summary>\n        /// Read the non-file contents as form data.\n        /// </summary>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A <see cref=\"Task\"/> representing the post processing.</returns>\n        public override Task ExecutePostProcessingAsync(CancellationToken cancellationToken)\n        {\n            _cancellationToken = cancellationToken;\n            return ExecutePostProcessingAsync();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/MultipartFormDataStreamProviderHelper.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Collections.Specialized;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http;\n\nnamespace System.Net.Http\n{\n    internal static class MultipartFormDataStreamProviderHelper\n    {\n        public static bool IsFileContent(HttpContent parent, HttpContentHeaders headers)\n        {\n            if (parent == null)\n            {\n                throw Error.ArgumentNull(\"parent\");\n            }\n\n            if (headers == null)\n            {\n                throw Error.ArgumentNull(\"headers\");\n            }\n\n            // For form data, Content-Disposition header is a requirement.\n            ContentDispositionHeaderValue contentDisposition = headers.ContentDisposition;\n            if (contentDisposition == null)\n            {\n                // If no Content-Disposition header was present.\n                throw Error.InvalidOperation(Properties.Resources.MultipartFormDataStreamProviderNoContentDisposition,\n                    \"Content-Disposition\");\n            }\n\n            // The file name's existence indicates it is a file data.\n            if (!String.IsNullOrEmpty(contentDisposition.FileName))\n            {\n                return true;\n            }\n\n            return false;\n        }\n\n        /// <summary>\n        /// Read the non-file contents as form data.\n        /// </summary>\n        /// <returns>A <see cref=\"Task\"/> representing the post processing.</returns>\n        public static async Task ReadFormDataAsync(Collection<HttpContent> contents,\n            NameValueCollection formData, CancellationToken cancellationToken)\n        {\n            // Find instances of HttpContent for which we created a memory stream and read them asynchronously\n            // to get the string content and then add that as form data\n            foreach (HttpContent content in contents)\n            {\n                ContentDispositionHeaderValue contentDisposition = content.Headers.ContentDisposition;\n                // If FileName is null or empty, the content is form data and will be processed.\n                if (String.IsNullOrEmpty(contentDisposition.FileName))\n                {\n                    // Extract name from Content-Disposition header. We know from earlier that the header is present.\n                    string formFieldName = FormattingUtilities.UnquoteToken(contentDisposition.Name) ?? String.Empty;\n\n                    // Read the contents as string data and add to form data\n                    cancellationToken.ThrowIfCancellationRequested();\n                    string formFieldValue = await content.ReadAsStringAsync();\n                    formData.Add(formFieldName, formFieldValue);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/MultipartMemoryStreamProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Net.Http.Headers;\nusing System.Web.Http;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// Provides a <see cref=\"MultipartStreamProvider\"/> implementation that returns a <see cref=\"MemoryStream\"/> instance.\n    /// This facilitates deserialization or other manipulation of the contents in memory.\n    /// </summary>\n    public class MultipartMemoryStreamProvider : MultipartStreamProvider\n    {\n        /// <summary>\n        /// This <see cref=\"MultipartStreamProvider\"/> implementation returns a <see cref=\"MemoryStream\"/> instance.\n        /// This facilitates deserialization or other manipulation of the contents in memory. \n        /// </summary>\n        public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)\n        {\n            if (parent == null)\n            {\n                throw Error.ArgumentNull(\"parent\");\n            }\n\n            if (headers == null)\n            {\n                throw Error.ArgumentNull(\"headers\");\n            }\n\n            return new MemoryStream();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/MultipartRelatedStreamProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.IO;\nusing System.Linq;\nusing System.Net.Http.Headers;\nusing System.Web.Http;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// An <see cref=\"MultipartStreamProvider\"/> suited for reading MIME body parts following the\n    /// <c>multipart/related</c> media type as defined in RFC 2387 (see http://www.ietf.org/rfc/rfc2387.txt).\n    /// </summary>\n    public class MultipartRelatedStreamProvider : MultipartStreamProvider\n    {\n        private const string RelatedSubType = \"related\";\n        private const string ContentID = \"Content-ID\";\n        private const string StartParameter = \"Start\";\n\n        private HttpContent _rootContent;\n        private HttpContent _parent;\n\n        /// <summary>\n        /// Gets the <see cref=\"HttpContent\"/> instance that has been marked as the <c>root</c> content in the\n        /// MIME multipart related message using the <c>start</c> parameter. If no <c>start</c> parameter is\n        /// present then pick the first of the children.\n        /// </summary>\n        public HttpContent RootContent\n        {\n            get\n            {\n                if (_rootContent == null)\n                {\n                    _rootContent = FindRootContent(_parent, Contents);\n                }\n\n                return _rootContent;\n            }\n        }\n\n        public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)\n        {\n            if (parent == null)\n            {\n                throw Error.ArgumentNull(\"parent\");\n            }\n\n            if (headers == null)\n            {\n                throw Error.ArgumentNull(\"headers\");\n            }\n\n            // See if we need to remember the parent to be able to determine the root content\n            if (_parent == null)\n            {\n                _parent = parent;\n            }\n\n            return new MemoryStream();\n        }\n\n        /// <summary>\n        /// Looks for the \"start\" parameter of the parent's content type and then finds the corresponding\n        /// child HttpContent with a matching Content-ID header field.\n        /// </summary>\n        /// <returns>The matching child or null if none found.</returns>\n        private static HttpContent FindRootContent(HttpContent parent, IEnumerable<HttpContent> children)\n        {\n            Contract.Assert(children != null);\n\n            // Find 'start' parameter from parent content type. The value is used\n            // to identify the MIME body with the corresponding Content-ID header value.\n            NameValueHeaderValue startNameValue = FindMultipartRelatedParameter(parent, StartParameter);\n            if (startNameValue == null)\n            {\n                // If we didn't find a \"start\" parameter then take the first child.\n                return children.FirstOrDefault();\n            }\n\n            // Look for the child with a Content-ID header that corresponds to the \"start\" value.\n            // If no matching child is found then we return null.\n            string startValue = FormattingUtilities.UnquoteToken(startNameValue.Value);\n            return children.FirstOrDefault(\n                content =>\n                {\n                    IEnumerable<string> values;\n                    if (content.Headers.TryGetValues(ContentID, out values))\n                    {\n                        return String.Equals(\n                            FormattingUtilities.UnquoteToken(values.ElementAt(0)),\n                            startValue,\n                            StringComparison.OrdinalIgnoreCase);\n                    }\n\n                    return false;\n                });\n        }\n\n        /// <summary>\n        /// Looks for a parameter in the <see cref=\"MediaTypeHeaderValue\"/>.\n        /// </summary>\n        /// <returns>The matching parameter or null if none found.</returns>\n        private static NameValueHeaderValue FindMultipartRelatedParameter(HttpContent content, string parameterName)\n        {\n            // If no parent then we are done\n            if (content == null)\n            {\n                return null;\n            }\n\n            // Check that we have a parent content type and that it is indeed multipart/related\n            MediaTypeHeaderValue parentContentType = content.Headers.ContentType;\n            if (parentContentType == null || !content.IsMimeMultipartContent(RelatedSubType))\n            {\n                return null;\n            }\n\n            // Look for parameter\n            return parentContentType.Parameters.FirstOrDefault(nvp => String.Equals(nvp.Name, parameterName, StringComparison.OrdinalIgnoreCase));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/MultipartRemoteFileData.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Headers;\nusing System.Web.Http;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// Represents a multipart file data for remote storage.\n    /// </summary>\n    public class MultipartRemoteFileData\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"MultipartRemoteFileData\"/> class.\n        /// </summary>\n        /// <param name=\"headers\">The headers of the multipart file data.</param>\n        /// <param name=\"location\">The remote file's location.</param>\n        /// <param name=\"fileName\">The remote file's name.</param>\n        public MultipartRemoteFileData(HttpContentHeaders headers, string location, string fileName)\n        {\n            if (headers == null)\n            {\n                throw Error.ArgumentNull(\"headers\");\n            }\n\n            if (location == null)\n            {\n                throw Error.ArgumentNull(\"location\");\n            }\n\n            if (fileName == null)\n            {\n                throw Error.ArgumentNull(\"fileName\");\n            }\n\n            FileName = fileName;\n            Headers = headers;\n            Location = location;\n        }\n\n        /// <summary>\n        /// Gets the remote file's name.\n        /// </summary>\n        public string FileName { get; private set; }\n\n        /// <summary>\n        /// Gets the headers of the multipart file data.\n        /// </summary>\n        public HttpContentHeaders Headers { get; private set; }\n\n        /// <summary>\n        /// Gets the remote file's location.\n        /// </summary>\n        public string Location { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/MultipartStreamProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.IO;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// An <see cref=\"MultipartStreamProvider\"/> implementation examines the headers provided by the MIME multipart parser\n    /// as part of the MIME multipart extension methods (see <see cref=\"HttpContentMultipartExtensions\"/>) and decides \n    /// what kind of stream to return for the body part to be written to.\n    /// </summary>\n    public abstract class MultipartStreamProvider\n    {\n        private Collection<HttpContent> _contents = new Collection<HttpContent>();\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"MultipartStreamProvider\"/> class.\n        /// </summary>\n        protected MultipartStreamProvider()\n        {\n        }\n\n        /// <summary>\n        /// Gets the collection of <see cref=\"HttpContent\"/> instances where each instance represents a MIME body part.\n        /// </summary>\n        public Collection<HttpContent> Contents\n        {\n            get { return _contents; }\n        }\n\n        /// <summary>\n        /// When a MIME multipart body part has been parsed this method is called to get a stream for where to write the body part to.\n        /// </summary>\n        /// <param name=\"parent\">The parent <see cref=\"HttpContent\"/> MIME multipart instance.</param>\n        /// <param name=\"headers\">The header fields describing the body parts content. Looking for header fields such as \n        /// Content-Type and Content-Disposition can help provide the appropriate stream. In addition to using the information\n        /// in the provided header fields, it is also possible to add new header fields or modify existing header fields. This can\n        /// be useful to get around situations where the Content-type may say <b>application/octet-stream</b> but based on\n        /// analyzing the <b>Content-Disposition</b> header field it is found that the content in fact is <b>application/json</b>, for example.</param>\n        /// <returns>A stream instance where the contents of a body part will be written to.</returns>\n        public abstract Stream GetStream(HttpContent parent, HttpContentHeaders headers);\n\n        /// <summary>\n        /// Immediately upon reading the last MIME body part but before completing the read task, this method is \n        /// called to enable the <see cref=\"MultipartStreamProvider\"/> to do any post processing on the <see cref=\"HttpContent\"/>\n        /// instances that have been read. For example, it can be used to copy the data to another location, or perform\n        /// some other kind of post processing on the data before completing the read operation.\n        /// </summary>\n        /// <returns>A <see cref=\"Task\"/> representing the post processing.</returns>\n        public virtual Task ExecutePostProcessingAsync()\n        {\n            return TaskHelpers.Completed();\n        }\n\n        /// <summary>\n        /// Immediately upon reading the last MIME body part but before completing the read task, this method is \n        /// called to enable the <see cref=\"MultipartStreamProvider\"/> to do any post processing on the <see cref=\"HttpContent\"/>\n        /// instances that have been read. For example, it can be used to copy the data to another location, or perform\n        /// some other kind of post processing on the data before completing the read operation.\n        /// </summary>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A <see cref=\"Task\"/> representing the post processing.</returns>\n        public virtual Task ExecutePostProcessingAsync(CancellationToken cancellationToken)\n        {\n            // Call the other overload to maintain backward compatibility.\n            return ExecutePostProcessingAsync();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/ObjectContent.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.IO;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Threading.Tasks;\nusing System.Web.Http;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// Contains a value as well as an associated <see cref=\"MediaTypeFormatter\"/> that will be\n    /// used to serialize the value when writing this content.\n    /// </summary>\n    public class ObjectContent : HttpContent\n    {\n        private object _value;\n        private readonly MediaTypeFormatter _formatter;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"ObjectContent\"/> class.\n        /// </summary>\n        /// <param name=\"type\">The type of object this instance will contain.</param>\n        /// <param name=\"value\">The value of the object this instance will contain.</param>\n        /// <param name=\"formatter\">The formatter to use when serializing the value.</param>\n        public ObjectContent(Type type, object value, MediaTypeFormatter formatter)\n            : this(type, value, formatter, (MediaTypeHeaderValue)null)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"ObjectContent\"/> class.\n        /// </summary>\n        /// <param name=\"type\">The type of object this instance will contain.</param>\n        /// <param name=\"value\">The value of the object this instance will contain.</param>\n        /// <param name=\"formatter\">The formatter to use when serializing the value.</param>\n        /// <param name=\"mediaType\">The authoritative value of the content's Content-Type header. Can be <c>null</c> in which case the\n        /// <paramref name=\"formatter\">formatter's</paramref> default content type will be used.</param>\n        public ObjectContent(Type type, object value, MediaTypeFormatter formatter, string mediaType)\n            : this(type, value, formatter, BuildHeaderValue(mediaType))\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"ObjectContent\"/> class.\n        /// </summary>\n        /// <param name=\"type\">The type of object this instance will contain.</param>\n        /// <param name=\"value\">The value of the object this instance will contain.</param>\n        /// <param name=\"formatter\">The formatter to use when serializing the value.</param>\n        /// <param name=\"mediaType\">The authoritative value of the content's Content-Type header. Can be <c>null</c> in which case the\n        /// <paramref name=\"formatter\">formatter's</paramref> default content type will be used.</param>\n        public ObjectContent(Type type, object value, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n            if (formatter == null)\n            {\n                throw Error.ArgumentNull(\"formatter\");\n            }\n\n            if (!formatter.CanWriteType(type))\n            {\n                throw Error.InvalidOperation(Properties.Resources.ObjectContent_FormatterCannotWriteType, formatter.GetType().FullName, type.Name);\n            }\n\n            _formatter = formatter;\n            ObjectType = type;\n\n            VerifyAndSetObject(value);\n            _formatter.SetDefaultContentHeaders(type, Headers, mediaType);\n        }\n\n        /// <summary>\n        /// Gets the type of object managed by this <see cref=\"ObjectContent\"/> instance.\n        /// </summary>\n        public Type ObjectType { get; private set; }\n\n        /// <summary>\n        /// The <see cref=\"MediaTypeFormatter\">formatter</see> associated with this content instance.\n        /// </summary>\n        public MediaTypeFormatter Formatter\n        {\n            get { return _formatter; }\n        }\n\n        /// <summary>\n        /// Gets or sets the value of the current <see cref=\"ObjectContent\"/>.\n        /// </summary>\n        public object Value\n        {\n            get { return _value; }\n            set { _value = value; }\n        }\n\n        internal static MediaTypeHeaderValue BuildHeaderValue(string mediaType)\n        {\n            return mediaType != null ? new MediaTypeHeaderValue(mediaType) : null;\n        }\n\n        /// <summary>\n        /// Asynchronously serializes the object's content to the given <paramref name=\"stream\"/>.\n        /// </summary>\n        /// <param name=\"stream\">The <see cref=\"Stream\"/> to which to write.</param>\n        /// <param name=\"context\">The associated <see cref=\"TransportContext\"/>.</param>\n        /// <returns>A <see cref=\"Task\"/> instance that is asynchronously serializing the object's content.</returns>\n        protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)\n        {\n            return _formatter.WriteToStreamAsync(ObjectType, Value, stream, this, context);\n        }\n\n        /// <summary>\n        /// Computes the length of the stream if possible.\n        /// </summary>\n        /// <param name=\"length\">The computed length of the stream.</param>\n        /// <returns><c>true</c> if the length has been computed; otherwise <c>false</c>.</returns>\n        protected override bool TryComputeLength(out long length)\n        {\n            length = -1;\n            return false;\n        }\n\n        private static bool IsTypeNullable(Type type)\n        {\n            return !type.IsValueType() ||\n                   (type.IsGenericType() &&\n                    type.GetGenericTypeDefinition() == typeof(Nullable<>));\n        }\n\n        private void VerifyAndSetObject(object value)\n        {\n            Contract.Assert(ObjectType != null, \"Type cannot be null\");\n\n            if (value == null)\n            {\n                // Null may not be assigned to value types (unless Nullable<T>)\n                if (!IsTypeNullable(ObjectType))\n                {\n                    throw Error.InvalidOperation(Properties.Resources.CannotUseNullValueType, typeof(ObjectContent).Name, ObjectType.Name);\n                }\n            }\n            else\n            {\n                // Non-null objects must be a type assignable to Type\n                Type objectType = value.GetType();\n                if (!ObjectType.IsAssignableFrom(objectType))\n                {\n                    throw Error.Argument(\"value\", Properties.Resources.ObjectAndTypeDisagree, objectType.Name, ObjectType.Name);\n                }\n            }\n\n            _value = value;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/ObjectContentOfT.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// Generic form of <see cref=\"ObjectContent\"/>.\n    /// </summary>\n    /// <typeparam name=\"T\">The type of object this <see cref=\"ObjectContent\"/> class will contain.</typeparam>\n    public class ObjectContent<T> : ObjectContent\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"ObjectContent{T}\"/> class.\n        /// </summary>\n        /// <param name=\"value\">The value of the object this instance will contain.</param>\n        /// <param name=\"formatter\">The formatter to use when serializing the value.</param>\n        public ObjectContent(T value, MediaTypeFormatter formatter)\n            : this(value, formatter, (MediaTypeHeaderValue)null)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"ObjectContent{T}\"/> class.\n        /// </summary>\n        /// <param name=\"value\">The value of the object this instance will contain.</param>\n        /// <param name=\"formatter\">The formatter to use when serializing the value.</param>\n        /// <param name=\"mediaType\">The authoritative value of the content's Content-Type header. Can be <c>null</c> in which case the\n        /// <paramref name=\"formatter\">formatter's</paramref> default content type will be used.</param>\n        public ObjectContent(T value, MediaTypeFormatter formatter, string mediaType)\n            : this(value, formatter, BuildHeaderValue(mediaType))\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"ObjectContent{T}\"/> class.\n        /// </summary>\n        /// <param name=\"value\">The value of the object this instance will contain.</param>\n        /// <param name=\"formatter\">The formatter to use when serializing the value.</param>\n        /// <param name=\"mediaType\">The authoritative value of the content's Content-Type header. Can be <c>null</c> in which case the\n        /// <paramref name=\"formatter\">formatter's</paramref> default content type will be used.</param>\n        public ObjectContent(T value, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType)\n            : base(typeof(T), value, formatter, mediaType)\n        {\n        }\n    }\n}"
  },
  {
    "path": "src/System.Net.Http.Formatting/Properties/AssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\n// General Information about an assembly is controlled through the following\n// set of attributes. Change these attribute values to modify the information\n// associated with an assembly.\n\n[assembly: AssemblyTitle(\"System.Net.Http.Formatting\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: Guid(\"7fa1ae84-36e2-46b6-812c-c985a8e65e9a\")]\n\n#if NETSTANDARD2_0\n[assembly: InternalsVisibleTo(\"System.Net.Http.Formatting.ns2_0.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n#elif NETSTANDARD1_3\n[assembly: InternalsVisibleTo(\"Microsoft.TestCommon, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n[assembly: InternalsVisibleTo(\"System.Net.Http.Formatting.ns1_3.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n#else\n[assembly: InternalsVisibleTo(\"System.Net.Http.Formatting.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n[assembly: InternalsVisibleTo(\"System.Net.Http.Formatting.Test.Integration, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n#endif\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Properties/Resources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.42000\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace System.Net.Http.Properties {\n    using System;\n    using System.Reflection;\n\n\n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"17.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class Resources {\n\n        private static global::System.Resources.ResourceManager resourceMan;\n\n        private static global::System.Globalization.CultureInfo resourceCulture;\n\n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal Resources() {\n        }\n\n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n#if NETSTANDARD1_3\n                    var assembly = typeof(Resources).GetTypeInfo().Assembly;\n#else\n                    var assembly = typeof(Resources).Assembly;\n#endif\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"System.Net.Http.Properties.Resources\", assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n\n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n\n        /// <summary>\n        ///   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..\n        /// </summary>\n        internal static string Argument_InvalidOffLen {\n            get {\n                return ResourceManager.GetString(\"Argument_InvalidOffLen\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Async Callback threw an exception..\n        /// </summary>\n        internal static string AsyncResult_CallbackThrewException {\n            get {\n                return ResourceManager.GetString(\"AsyncResult_CallbackThrewException\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The IAsyncResult implementation &apos;{0}&apos; 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..\n        /// </summary>\n        internal static string AsyncResult_MultipleCompletes {\n            get {\n                return ResourceManager.GetString(\"AsyncResult_MultipleCompletes\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to End cannot be called twice on an AsyncResult..\n        /// </summary>\n        internal static string AsyncResult_MultipleEnds {\n            get {\n                return ResourceManager.GetString(\"AsyncResult_MultipleEnds\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to An incorrect IAsyncResult was provided to an &apos;End&apos; method. The IAsyncResult object passed to &apos;End&apos; must be the one returned from the matching &apos;Begin&apos; or passed to the callback provided to &apos;Begin&apos;..\n        /// </summary>\n        internal static string AsyncResult_ResultMismatch {\n            get {\n                return ResourceManager.GetString(\"AsyncResult_ResultMismatch\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Found zero byte ranges. There must be at least one byte range provided..\n        /// </summary>\n        internal static string ByteRangeStreamContentNoRanges {\n            get {\n                return ResourceManager.GetString(\"ByteRangeStreamContentNoRanges\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The range unit &apos;{0}&apos; is not valid. The range must have a unit of &apos;{1}&apos;..\n        /// </summary>\n        internal static string ByteRangeStreamContentNotBytesRange {\n            get {\n                return ResourceManager.GetString(\"ByteRangeStreamContentNotBytesRange\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The stream over which &apos;{0}&apos; provides a range view must have a length greater than or equal to 1..\n        /// </summary>\n        internal static string ByteRangeStreamEmpty {\n            get {\n                return ResourceManager.GetString(\"ByteRangeStreamEmpty\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The &apos;From&apos; value of the range must be less than or equal to {0}..\n        /// </summary>\n        internal static string ByteRangeStreamInvalidFrom {\n            get {\n                return ResourceManager.GetString(\"ByteRangeStreamInvalidFrom\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to An attempt was made to move the position before the beginning of the stream..\n        /// </summary>\n        internal static string ByteRangeStreamInvalidOffset {\n            get {\n                return ResourceManager.GetString(\"ByteRangeStreamInvalidOffset\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to None of the requested ranges ({0}) overlap with the current extent of the selected resource..\n        /// </summary>\n        internal static string ByteRangeStreamNoneOverlap {\n            get {\n                return ResourceManager.GetString(\"ByteRangeStreamNoneOverlap\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The requested range ({0}) does not overlap with the current extent of the selected resource..\n        /// </summary>\n        internal static string ByteRangeStreamNoOverlap {\n            get {\n                return ResourceManager.GetString(\"ByteRangeStreamNoOverlap\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The stream over which &apos;{0}&apos; provides a range view must be seekable..\n        /// </summary>\n        internal static string ByteRangeStreamNotSeekable {\n            get {\n                return ResourceManager.GetString(\"ByteRangeStreamNotSeekable\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to This is a read-only stream..\n        /// </summary>\n        internal static string ByteRangeStreamReadOnly {\n            get {\n                return ResourceManager.GetString(\"ByteRangeStreamReadOnly\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to A null &apos;{0}&apos; is not valid..\n        /// </summary>\n        internal static string CannotHaveNullInList {\n            get {\n                return ResourceManager.GetString(\"CannotHaveNullInList\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The &apos;{0}&apos; of &apos;{1}&apos; cannot be used as a supported media type because it is a media range..\n        /// </summary>\n        internal static string CannotUseMediaRangeForSupportedMediaType {\n            get {\n                return ResourceManager.GetString(\"CannotUseMediaRangeForSupportedMediaType\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The &apos;{0}&apos; type cannot accept a null value for the value type &apos;{1}&apos;..\n        /// </summary>\n        internal static string CannotUseNullValueType {\n            get {\n                return ResourceManager.GetString(\"CannotUseNullValueType\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The specified value is not a valid cookie name..\n        /// </summary>\n        internal static string CookieInvalidName {\n            get {\n                return ResourceManager.GetString(\"CookieInvalidName\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Cookie cannot be null..\n        /// </summary>\n        internal static string CookieNull {\n            get {\n                return ResourceManager.GetString(\"CookieNull\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The &apos;{0}&apos; list is invalid because it contains one or more null items..\n        /// </summary>\n        internal static string DelegatingHandlerArrayContainsNullItem {\n            get {\n                return ResourceManager.GetString(\"DelegatingHandlerArrayContainsNullItem\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The &apos;{0}&apos; list is invalid because the property &apos;{1}&apos; of &apos;{2}&apos; is not null..\n        /// </summary>\n        internal static string DelegatingHandlerArrayHasNonNullInnerHandler {\n            get {\n                return ResourceManager.GetString(\"DelegatingHandlerArrayHasNonNullInnerHandler\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Error reading HTML form URL-encoded data stream..\n        /// </summary>\n        internal static string ErrorReadingFormUrlEncodedStream {\n            get {\n                return ResourceManager.GetString(\"ErrorReadingFormUrlEncodedStream\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Mismatched types at node &apos;{0}&apos;..\n        /// </summary>\n        internal static string FormUrlEncodedMismatchingTypes {\n            get {\n                return ResourceManager.GetString(\"FormUrlEncodedMismatchingTypes\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Error parsing HTML form URL-encoded data, byte {0}..\n        /// </summary>\n        internal static string FormUrlEncodedParseError {\n            get {\n                return ResourceManager.GetString(\"FormUrlEncodedParseError\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Invalid HTTP status code: &apos;{0}&apos;. The status code must be between {1} and {2}..\n        /// </summary>\n        internal static string HttpInvalidStatusCode {\n            get {\n                return ResourceManager.GetString(\"HttpInvalidStatusCode\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Invalid HTTP version: &apos;{0}&apos;. The version must start with the characters &apos;{1}&apos;..\n        /// </summary>\n        internal static string HttpInvalidVersion {\n            get {\n                return ResourceManager.GetString(\"HttpInvalidVersion\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The &apos;{0}&apos; of the &apos;{1}&apos; has already been read..\n        /// </summary>\n        internal static string HttpMessageContentAlreadyRead {\n            get {\n                return ResourceManager.GetString(\"HttpMessageContentAlreadyRead\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The &apos;{0}&apos; must be seekable in order to create an &apos;{1}&apos; instance containing an entity body.  .\n        /// </summary>\n        internal static string HttpMessageContentStreamMustBeSeekable {\n            get {\n                return ResourceManager.GetString(\"HttpMessageContentStreamMustBeSeekable\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Error reading HTTP message..\n        /// </summary>\n        internal static string HttpMessageErrorReading {\n            get {\n                return ResourceManager.GetString(\"HttpMessageErrorReading\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Invalid &apos;{0}&apos; instance provided. It does not have a content type header with a value of &apos;{1}&apos;..\n        /// </summary>\n        internal static string HttpMessageInvalidMediaType {\n            get {\n                return ResourceManager.GetString(\"HttpMessageInvalidMediaType\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to HTTP Request URI cannot be an empty string..\n        /// </summary>\n        internal static string HttpMessageParserEmptyUri {\n            get {\n                return ResourceManager.GetString(\"HttpMessageParserEmptyUri\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Error parsing HTTP message header byte {0} of message {1}..\n        /// </summary>\n        internal static string HttpMessageParserError {\n            get {\n                return ResourceManager.GetString(\"HttpMessageParserError\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to An invalid number of &apos;{0}&apos; header fields were present in the HTTP Request. It must contain exactly one &apos;{0}&apos; header field but found {1}..\n        /// </summary>\n        internal static string HttpMessageParserInvalidHostCount {\n            get {\n                return ResourceManager.GetString(\"HttpMessageParserInvalidHostCount\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Invalid URI scheme: &apos;{0}&apos;. The URI scheme must be a valid &apos;{1}&apos; scheme..\n        /// </summary>\n        internal static string HttpMessageParserInvalidUriScheme {\n            get {\n                return ResourceManager.GetString(\"HttpMessageParserInvalidUriScheme\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Invalid array at node &apos;{0}&apos;..\n        /// </summary>\n        internal static string InvalidArrayInsert {\n            get {\n                return ResourceManager.GetString(\"InvalidArrayInsert\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Traditional style array without &apos;[]&apos; is not supported with nested object at location {0}..\n        /// </summary>\n        internal static string JQuery13CompatModeNotSupportNestedJson {\n            get {\n                return ResourceManager.GetString(\"JQuery13CompatModeNotSupportNestedJson\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Unable to validate types on this platform when {0} is &apos;true&apos;. Please reset {0} or move to a supported platform, one where the &apos;netstandard2.0&apos; assembly is usable..\n        /// </summary>\n        internal static string JsonMediaTypeFormatter_DCS_NotSupported {\n            get {\n                return ResourceManager.GetString(\"JsonMediaTypeFormatter_DCS_NotSupported\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The &apos;{0}&apos; method returned null. It must return a JSON serializer instance..\n        /// </summary>\n        internal static string JsonSerializerFactoryReturnedNull {\n            get {\n                return ResourceManager.GetString(\"JsonSerializerFactoryReturnedNull\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The &apos;{0}&apos; method threw an exception when attempting to create a JSON serializer..\n        /// </summary>\n        internal static string JsonSerializerFactoryThrew {\n            get {\n                return ResourceManager.GetString(\"JsonSerializerFactoryThrew\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   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..\n        /// </summary>\n        internal static string MaxDepthExceeded {\n            get {\n                return ResourceManager.GetString(\"MaxDepthExceeded\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The number of keys in a NameValueCollection has exceeded the limit of &apos;{0}&apos;. You can adjust it by modifying the MaxHttpCollectionKeys property on the &apos;{1}&apos; class..\n        /// </summary>\n        internal static string MaxHttpCollectionKeyLimitReached {\n            get {\n                return ResourceManager.GetString(\"MaxHttpCollectionKeyLimitReached\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Error parsing BSON data; unable to read content as a {0}..\n        /// </summary>\n        internal static string MediaTypeFormatter_BsonParseError_MissingData {\n            get {\n                return ResourceManager.GetString(\"MediaTypeFormatter_BsonParseError_MissingData\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Error parsing BSON data; unexpected dictionary content: {0} entries, first key &apos;{1}&apos;..\n        /// </summary>\n        internal static string MediaTypeFormatter_BsonParseError_UnexpectedData {\n            get {\n                return ResourceManager.GetString(\"MediaTypeFormatter_BsonParseError_UnexpectedData\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The &apos;{0}&apos; method returned null. It must return a JSON reader instance..\n        /// </summary>\n        internal static string MediaTypeFormatter_JsonReaderFactoryReturnedNull {\n            get {\n                return ResourceManager.GetString(\"MediaTypeFormatter_JsonReaderFactoryReturnedNull\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The &apos;{0}&apos; method returned null. It must return a JSON writer instance..\n        /// </summary>\n        internal static string MediaTypeFormatter_JsonWriterFactoryReturnedNull {\n            get {\n                return ResourceManager.GetString(\"MediaTypeFormatter_JsonWriterFactoryReturnedNull\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The media type formatter of type &apos;{0}&apos; does not support reading because it does not implement the ReadFromStreamAsync method..\n        /// </summary>\n        internal static string MediaTypeFormatterCannotRead {\n            get {\n                return ResourceManager.GetString(\"MediaTypeFormatterCannotRead\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The media type formatter of type &apos;{0}&apos; does not support reading because it does not implement the ReadFromStream method..\n        /// </summary>\n        internal static string MediaTypeFormatterCannotReadSync {\n            get {\n                return ResourceManager.GetString(\"MediaTypeFormatterCannotReadSync\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The media type formatter of type &apos;{0}&apos; does not support writing because it does not implement the WriteToStreamAsync method..\n        /// </summary>\n        internal static string MediaTypeFormatterCannotWrite {\n            get {\n                return ResourceManager.GetString(\"MediaTypeFormatterCannotWrite\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The media type formatter of type &apos;{0}&apos; does not support writing because it does not implement the WriteToStream method..\n        /// </summary>\n        internal static string MediaTypeFormatterCannotWriteSync {\n            get {\n                return ResourceManager.GetString(\"MediaTypeFormatterCannotWriteSync\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to No encoding found for media type formatter &apos;{0}&apos;. There must be at least one supported encoding registered in order for the media type formatter to read or write content..\n        /// </summary>\n        internal static string MediaTypeFormatterNoEncoding {\n            get {\n                return ResourceManager.GetString(\"MediaTypeFormatterNoEncoding\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to MIME multipart boundary cannot end with an empty space..\n        /// </summary>\n        internal static string MimeMultipartParserBadBoundary {\n            get {\n                return ResourceManager.GetString(\"MimeMultipartParserBadBoundary\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Did not find required &apos;{0}&apos; header field in MIME multipart body part..\n        /// </summary>\n        internal static string MultipartFormDataStreamProviderNoContentDisposition {\n            get {\n                return ResourceManager.GetString(\"MultipartFormDataStreamProviderNoContentDisposition\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Could not determine a valid local file name for the multipart body part..\n        /// </summary>\n        internal static string MultipartStreamProviderInvalidLocalFileName {\n            get {\n                return ResourceManager.GetString(\"MultipartStreamProviderInvalidLocalFileName\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Nested bracket is not valid for &apos;{0}&apos; data at position {1}..\n        /// </summary>\n        internal static string NestedBracketNotValid {\n            get {\n                return ResourceManager.GetString(\"NestedBracketNotValid\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to A non-null request URI must be provided to determine if a &apos;{0}&apos; matches a given request or response message..\n        /// </summary>\n        internal static string NonNullUriRequiredForMediaTypeMapping {\n            get {\n                return ResourceManager.GetString(\"NonNullUriRequiredForMediaTypeMapping\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to No MediaTypeFormatter is available to read an object of type &apos;{0}&apos; from content with media type &apos;{1}&apos;..\n        /// </summary>\n        internal static string NoReadSerializerAvailable {\n            get {\n                return ResourceManager.GetString(\"NoReadSerializerAvailable\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Stream does not support reading..\n        /// </summary>\n        internal static string NotSupported_UnreadableStream {\n            get {\n                return ResourceManager.GetString(\"NotSupported_UnreadableStream\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Stream does not support seeking..\n        /// </summary>\n        internal static string NotSupported_UnseekableStream {\n            get {\n                return ResourceManager.GetString(\"NotSupported_UnseekableStream\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Stream does not support writing..\n        /// </summary>\n        internal static string NotSupported_UnwritableStream {\n            get {\n                return ResourceManager.GetString(\"NotSupported_UnwritableStream\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to An object of type &apos;{0}&apos; cannot be used with a type parameter of &apos;{1}&apos;..\n        /// </summary>\n        internal static string ObjectAndTypeDisagree {\n            get {\n                return ResourceManager.GetString(\"ObjectAndTypeDisagree\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The configured formatter &apos;{0}&apos; cannot write an object of type &apos;{1}&apos;..\n        /// </summary>\n        internal static string ObjectContent_FormatterCannotWriteType {\n            get {\n                return ResourceManager.GetString(\"ObjectContent_FormatterCannotWriteType\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Cannot access a closed stream..\n        /// </summary>\n        internal static string ObjectDisposed_StreamClosed {\n            get {\n                return ResourceManager.GetString(\"ObjectDisposed_StreamClosed\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Query string name cannot be null..\n        /// </summary>\n        internal static string QueryStringNameShouldNotNull {\n            get {\n                return ResourceManager.GetString(\"QueryStringNameShouldNotNull\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Unexpected end of HTTP message stream. HTTP message is not complete..\n        /// </summary>\n        internal static string ReadAsHttpMessageUnexpectedTermination {\n            get {\n                return ResourceManager.GetString(\"ReadAsHttpMessageUnexpectedTermination\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Invalid &apos;{0}&apos; instance provided. It does not have a &apos;{1}&apos; content-type header with a &apos;{2}&apos; parameter..\n        /// </summary>\n        internal static string ReadAsMimeMultipartArgumentNoBoundary {\n            get {\n                return ResourceManager.GetString(\"ReadAsMimeMultipartArgumentNoBoundary\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Invalid &apos;{0}&apos; instance provided. It does not have a content-type header value. &apos;{0}&apos; instances must have a content-type header starting with &apos;{1}&apos;..\n        /// </summary>\n        internal static string ReadAsMimeMultipartArgumentNoContentType {\n            get {\n                return ResourceManager.GetString(\"ReadAsMimeMultipartArgumentNoContentType\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Invalid &apos;{0}&apos; instance provided. It does not have a content type header starting with &apos;{1}&apos;..\n        /// </summary>\n        internal static string ReadAsMimeMultipartArgumentNoMultipart {\n            get {\n                return ResourceManager.GetString(\"ReadAsMimeMultipartArgumentNoMultipart\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Error reading MIME multipart body part..\n        /// </summary>\n        internal static string ReadAsMimeMultipartErrorReading {\n            get {\n                return ResourceManager.GetString(\"ReadAsMimeMultipartErrorReading\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Error writing MIME multipart body part to output stream..\n        /// </summary>\n        internal static string ReadAsMimeMultipartErrorWriting {\n            get {\n                return ResourceManager.GetString(\"ReadAsMimeMultipartErrorWriting\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Error parsing MIME multipart body part header byte {0} of data segment {1}..\n        /// </summary>\n        internal static string ReadAsMimeMultipartHeaderParseError {\n            get {\n                return ResourceManager.GetString(\"ReadAsMimeMultipartHeaderParseError\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Error parsing MIME multipart message byte {0} of data segment {1}..\n        /// </summary>\n        internal static string ReadAsMimeMultipartParseError {\n            get {\n                return ResourceManager.GetString(\"ReadAsMimeMultipartParseError\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The stream provider of type &apos;{0}&apos; threw an exception..\n        /// </summary>\n        internal static string ReadAsMimeMultipartStreamProviderException {\n            get {\n                return ResourceManager.GetString(\"ReadAsMimeMultipartStreamProviderException\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The stream provider of type &apos;{0}&apos; returned null. It must return a writable &apos;{1}&apos; instance..\n        /// </summary>\n        internal static string ReadAsMimeMultipartStreamProviderNull {\n            get {\n                return ResourceManager.GetString(\"ReadAsMimeMultipartStreamProviderNull\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The stream provider of type &apos;{0}&apos; returned a read-only stream. It must return a writable &apos;{1}&apos; instance..\n        /// </summary>\n        internal static string ReadAsMimeMultipartStreamProviderReadOnly {\n            get {\n                return ResourceManager.GetString(\"ReadAsMimeMultipartStreamProviderReadOnly\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Unexpected end of MIME multipart stream. MIME multipart message is not complete..\n        /// </summary>\n        internal static string ReadAsMimeMultipartUnexpectedTermination {\n            get {\n                return ResourceManager.GetString(\"ReadAsMimeMultipartUnexpectedTermination\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The &apos;{0}&apos; method in &apos;{1}&apos; returned null. It must return a RemoteStreamResult instance containing a writable stream and a valid URL..\n        /// </summary>\n        internal static string RemoteStreamInfoCannotBeNull {\n            get {\n                return ResourceManager.GetString(\"RemoteStreamInfoCannotBeNull\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The &apos;{0}&apos; serializer cannot serialize the type &apos;{1}&apos;..\n        /// </summary>\n        internal static string SerializerCannotSerializeType {\n            get {\n                return ResourceManager.GetString(\"SerializerCannotSerializeType\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to There is an unmatched opened bracket for the &apos;{0}&apos; at position {1}..\n        /// </summary>\n        internal static string UnMatchedBracketNotValid {\n            get {\n                return ResourceManager.GetString(\"UnMatchedBracketNotValid\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Indentation is not supported by &apos;{0}&apos;..\n        /// </summary>\n        internal static string UnsupportedIndent {\n            get {\n                return ResourceManager.GetString(\"UnsupportedIndent\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to Unable to validate types on this platform when {0} is &apos;false&apos;. Please set {0} or move to a supported platform, one where the &apos;netstandard2.0&apos; assembly is usable..\n        /// </summary>\n        internal static string XmlMediaTypeFormatter_DCS_NotSupported {\n            get {\n                return ResourceManager.GetString(\"XmlMediaTypeFormatter_DCS_NotSupported\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The object of type &apos;{0}&apos; returned by {1} must be an instance of either XmlObjectSerializer or XmlSerializer..\n        /// </summary>\n        internal static string XmlMediaTypeFormatter_InvalidSerializerType {\n            get {\n                return ResourceManager.GetString(\"XmlMediaTypeFormatter_InvalidSerializerType\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to The object returned by {0} must not be a null value..\n        /// </summary>\n        internal static string XmlMediaTypeFormatter_NullReturnedSerializer {\n            get {\n                return ResourceManager.GetString(\"XmlMediaTypeFormatter_NullReturnedSerializer\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/Properties/Resources.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!--\n    Microsoft ResX Schema\n\n    Version 2.0\n\n    The primary goals of this format is to allow a simple XML format\n    that is mostly human readable. The generation and parsing of the\n    various data types are done through the TypeConverter classes\n    associated with the data types.\n\n    Example:\n\n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n\n    There are any number of \"resheader\" rows that contain simple\n    name/value pairs.\n\n    Each data row contains a name, and value. The row also contains a\n    type or mimetype. Type corresponds to a .NET class that support\n    text/value conversion through the TypeConverter architecture.\n    Classes that don't support this are serialized and stored with the\n    mimetype set.\n\n    The mimetype is used for serialized objects, and tells the\n    ResXResourceReader how to depersist the object. This is currently not\n    extensible. For a given mimetype the value must be set accordingly:\n\n    Note - application/x-microsoft.net.object.binary.base64 is the format\n    that the ResXResourceWriter will generate, however the reader can\n    read any of the formats listed below.\n\n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with\n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with\n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array\n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"CannotHaveNullInList\" xml:space=\"preserve\">\n    <value>A null '{0}' is not valid.</value>\n  </data>\n  <data name=\"CannotUseMediaRangeForSupportedMediaType\" xml:space=\"preserve\">\n    <value>The '{0}' of '{1}' cannot be used as a supported media type because it is a media range.</value>\n  </data>\n  <data name=\"CannotUseNullValueType\" xml:space=\"preserve\">\n    <value>The '{0}' type cannot accept a null value for the value type '{1}'.</value>\n  </data>\n  <data name=\"ErrorReadingFormUrlEncodedStream\" xml:space=\"preserve\">\n    <value>Error reading HTML form URL-encoded data stream.</value>\n  </data>\n  <data name=\"FormUrlEncodedParseError\" xml:space=\"preserve\">\n    <value>Error parsing HTML form URL-encoded data, byte {0}.</value>\n  </data>\n  <data name=\"HttpInvalidStatusCode\" xml:space=\"preserve\">\n    <value>Invalid HTTP status code: '{0}'. The status code must be between {1} and {2}.</value>\n  </data>\n  <data name=\"HttpInvalidVersion\" xml:space=\"preserve\">\n    <value>Invalid HTTP version: '{0}'. The version must start with the characters '{1}'.</value>\n  </data>\n  <data name=\"HttpMessageContentAlreadyRead\" xml:space=\"preserve\">\n    <value>The '{0}' of the '{1}' has already been read.</value>\n  </data>\n  <data name=\"HttpMessageContentStreamMustBeSeekable\" xml:space=\"preserve\">\n    <value>The '{0}' must be seekable in order to create an '{1}' instance containing an entity body.  </value>\n  </data>\n  <data name=\"HttpMessageErrorReading\" xml:space=\"preserve\">\n    <value>Error reading HTTP message.</value>\n  </data>\n  <data name=\"HttpMessageInvalidMediaType\" xml:space=\"preserve\">\n    <value>Invalid '{0}' instance provided. It does not have a content type header with a value of '{1}'.</value>\n  </data>\n  <data name=\"HttpMessageParserEmptyUri\" xml:space=\"preserve\">\n    <value>HTTP Request URI cannot be an empty string.</value>\n  </data>\n  <data name=\"HttpMessageParserError\" xml:space=\"preserve\">\n    <value>Error parsing HTTP message header byte {0} of message {1}.</value>\n  </data>\n  <data name=\"HttpMessageParserInvalidHostCount\" xml:space=\"preserve\">\n    <value>An invalid number of '{0}' header fields were present in the HTTP Request. It must contain exactly one '{0}' header field but found {1}.</value>\n  </data>\n  <data name=\"HttpMessageParserInvalidUriScheme\" xml:space=\"preserve\">\n    <value>Invalid URI scheme: '{0}'. The URI scheme must be a valid '{1}' scheme.</value>\n  </data>\n  <data name=\"MimeMultipartParserBadBoundary\" xml:space=\"preserve\">\n    <value>MIME multipart boundary cannot end with an empty space.</value>\n  </data>\n  <data name=\"MultipartFormDataStreamProviderNoContentDisposition\" xml:space=\"preserve\">\n    <value>Did not find required '{0}' header field in MIME multipart body part.</value>\n  </data>\n  <data name=\"MultipartStreamProviderInvalidLocalFileName\" xml:space=\"preserve\">\n    <value>Could not determine a valid local file name for the multipart body part.</value>\n  </data>\n  <data name=\"NonNullUriRequiredForMediaTypeMapping\" xml:space=\"preserve\">\n    <value>A non-null request URI must be provided to determine if a '{0}' matches a given request or response message.</value>\n  </data>\n  <data name=\"NoReadSerializerAvailable\" xml:space=\"preserve\">\n    <value>No MediaTypeFormatter is available to read an object of type '{0}' from content with media type '{1}'.</value>\n  </data>\n  <data name=\"ObjectAndTypeDisagree\" xml:space=\"preserve\">\n    <value>An object of type '{0}' cannot be used with a type parameter of '{1}'.</value>\n  </data>\n  <data name=\"ReadAsMimeMultipartArgumentNoBoundary\" xml:space=\"preserve\">\n    <value>Invalid '{0}' instance provided. It does not have a '{1}' content-type header with a '{2}' parameter.</value>\n  </data>\n  <data name=\"ReadAsMimeMultipartArgumentNoContentType\" xml:space=\"preserve\">\n    <value>Invalid '{0}' instance provided. It does not have a content-type header value. '{0}' instances must have a content-type header starting with '{1}'.</value>\n  </data>\n  <data name=\"ReadAsMimeMultipartArgumentNoMultipart\" xml:space=\"preserve\">\n    <value>Invalid '{0}' instance provided. It does not have a content type header starting with '{1}'.</value>\n  </data>\n  <data name=\"ReadAsMimeMultipartErrorReading\" xml:space=\"preserve\">\n    <value>Error reading MIME multipart body part.</value>\n  </data>\n  <data name=\"ReadAsMimeMultipartErrorWriting\" xml:space=\"preserve\">\n    <value>Error writing MIME multipart body part to output stream.</value>\n  </data>\n  <data name=\"ReadAsMimeMultipartHeaderParseError\" xml:space=\"preserve\">\n    <value>Error parsing MIME multipart body part header byte {0} of data segment {1}.</value>\n  </data>\n  <data name=\"ReadAsMimeMultipartParseError\" xml:space=\"preserve\">\n    <value>Error parsing MIME multipart message byte {0} of data segment {1}.</value>\n  </data>\n  <data name=\"ReadAsMimeMultipartStreamProviderException\" xml:space=\"preserve\">\n    <value>The stream provider of type '{0}' threw an exception.</value>\n  </data>\n  <data name=\"ReadAsMimeMultipartStreamProviderNull\" xml:space=\"preserve\">\n    <value>The stream provider of type '{0}' returned null. It must return a writable '{1}' instance.</value>\n  </data>\n  <data name=\"ReadAsMimeMultipartStreamProviderReadOnly\" xml:space=\"preserve\">\n    <value>The stream provider of type '{0}' returned a read-only stream. It must return a writable '{1}' instance.</value>\n  </data>\n  <data name=\"ReadAsMimeMultipartUnexpectedTermination\" xml:space=\"preserve\">\n    <value>Unexpected end of MIME multipart stream. MIME multipart message is not complete.</value>\n  </data>\n  <data name=\"SerializerCannotSerializeType\" xml:space=\"preserve\">\n    <value>The '{0}' serializer cannot serialize the type '{1}'.</value>\n  </data>\n  <data name=\"UnsupportedIndent\" xml:space=\"preserve\">\n    <value>Indentation is not supported by '{0}'.</value>\n  </data>\n  <data name=\"MediaTypeFormatterCannotRead\" xml:space=\"preserve\">\n    <value>The media type formatter of type '{0}' does not support reading because it does not implement the ReadFromStreamAsync method.</value>\n  </data>\n  <data name=\"MediaTypeFormatterCannotWrite\" xml:space=\"preserve\">\n    <value>The media type formatter of type '{0}' does not support writing because it does not implement the WriteToStreamAsync method.</value>\n  </data>\n  <data name=\"MediaTypeFormatterCannotReadSync\" xml:space=\"preserve\">\n    <value>The media type formatter of type '{0}' does not support reading because it does not implement the ReadFromStream method.</value>\n  </data>\n  <data name=\"MediaTypeFormatterCannotWriteSync\" xml:space=\"preserve\">\n    <value>The media type formatter of type '{0}' does not support writing because it does not implement the WriteToStream method.</value>\n  </data>\n  <data name=\"ObjectContent_FormatterCannotWriteType\" xml:space=\"preserve\">\n    <value>The configured formatter '{0}' cannot write an object of type '{1}'.</value>\n  </data>\n  <data name=\"FormUrlEncodedMismatchingTypes\" xml:space=\"preserve\">\n    <value>Mismatched types at node '{0}'.</value>\n  </data>\n  <data name=\"InvalidArrayInsert\" xml:space=\"preserve\">\n    <value>Invalid array at node '{0}'.</value>\n  </data>\n  <data name=\"JQuery13CompatModeNotSupportNestedJson\" xml:space=\"preserve\">\n    <value>Traditional style array without '[]' is not supported with nested object at location {0}.</value>\n  </data>\n  <data name=\"MaxDepthExceeded\" xml:space=\"preserve\">\n    <value>The maximum read depth ({0}) has been exceeded because the form url-encoded data being read has more levels of nesting than is allowed.</value>\n  </data>\n  <data name=\"NestedBracketNotValid\" xml:space=\"preserve\">\n    <value>Nested bracket is not valid for '{0}' data at position {1}.</value>\n  </data>\n  <data name=\"QueryStringNameShouldNotNull\" xml:space=\"preserve\">\n    <value>Query string name cannot be null.</value>\n  </data>\n  <data name=\"UnMatchedBracketNotValid\" xml:space=\"preserve\">\n    <value>There is an unmatched opened bracket for the '{0}' at position {1}.</value>\n  </data>\n  <data name=\"MediaTypeFormatterNoEncoding\" xml:space=\"preserve\">\n    <value>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.</value>\n  </data>\n  <data name=\"CookieInvalidName\" xml:space=\"preserve\">\n    <value>The specified value is not a valid cookie name.</value>\n  </data>\n  <data name=\"CookieNull\" xml:space=\"preserve\">\n    <value>Cookie cannot be null.</value>\n  </data>\n  <data name=\"MaxHttpCollectionKeyLimitReached\" xml:space=\"preserve\">\n    <value>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.</value>\n  </data>\n  <data name=\"AsyncResult_CallbackThrewException\" xml:space=\"preserve\">\n    <value>Async Callback threw an exception.</value>\n  </data>\n  <data name=\"AsyncResult_MultipleCompletes\" xml:space=\"preserve\">\n    <value>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.</value>\n  </data>\n  <data name=\"AsyncResult_MultipleEnds\" xml:space=\"preserve\">\n    <value>End cannot be called twice on an AsyncResult.</value>\n  </data>\n  <data name=\"AsyncResult_ResultMismatch\" xml:space=\"preserve\">\n    <value>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'.</value>\n  </data>\n  <data name=\"DelegatingHandlerArrayContainsNullItem\" xml:space=\"preserve\">\n    <value>The '{0}' list is invalid because it contains one or more null items.</value>\n  </data>\n  <data name=\"DelegatingHandlerArrayHasNonNullInnerHandler\" xml:space=\"preserve\">\n    <value>The '{0}' list is invalid because the property '{1}' of '{2}' is not null.</value>\n  </data>\n  <data name=\"ReadAsHttpMessageUnexpectedTermination\" xml:space=\"preserve\">\n    <value>Unexpected end of HTTP message stream. HTTP message is not complete.</value>\n  </data>\n  <data name=\"ByteRangeStreamContentNotBytesRange\" xml:space=\"preserve\">\n    <value>The range unit '{0}' is not valid. The range must have a unit of '{1}'.</value>\n  </data>\n  <data name=\"ByteRangeStreamInvalidFrom\" xml:space=\"preserve\">\n    <value>The 'From' value of the range must be less than or equal to {0}.</value>\n  </data>\n  <data name=\"ByteRangeStreamNoneOverlap\" xml:space=\"preserve\">\n    <value>None of the requested ranges ({0}) overlap with the current extent of the selected resource.</value>\n  </data>\n  <data name=\"ByteRangeStreamNoOverlap\" xml:space=\"preserve\">\n    <value>The requested range ({0}) does not overlap with the current extent of the selected resource.</value>\n  </data>\n  <data name=\"ByteRangeStreamNotSeekable\" xml:space=\"preserve\">\n    <value>The stream over which '{0}' provides a range view must be seekable.</value>\n  </data>\n  <data name=\"ByteRangeStreamReadOnly\" xml:space=\"preserve\">\n    <value>This is a read-only stream.</value>\n  </data>\n  <data name=\"ByteRangeStreamContentNoRanges\" xml:space=\"preserve\">\n    <value>Found zero byte ranges. There must be at least one byte range provided.</value>\n  </data>\n  <data name=\"ByteRangeStreamEmpty\" xml:space=\"preserve\">\n    <value>The stream over which '{0}' provides a range view must have a length greater than or equal to 1.</value>\n  </data>\n  <data name=\"XmlMediaTypeFormatter_InvalidSerializerType\" xml:space=\"preserve\">\n    <value>The object of type '{0}' returned by {1} must be an instance of either XmlObjectSerializer or XmlSerializer.</value>\n  </data>\n  <data name=\"XmlMediaTypeFormatter_NullReturnedSerializer\" xml:space=\"preserve\">\n    <value>The object returned by {0} must not be a null value.</value>\n  </data>\n  <data name=\"JsonSerializerFactoryReturnedNull\" xml:space=\"preserve\">\n    <value>The '{0}' method returned null. It must return a JSON serializer instance.</value>\n  </data>\n  <data name=\"JsonSerializerFactoryThrew\" xml:space=\"preserve\">\n    <value>The '{0}' method threw an exception when attempting to create a JSON serializer.</value>\n  </data>\n  <data name=\"MediaTypeFormatter_JsonReaderFactoryReturnedNull\" xml:space=\"preserve\">\n    <value>The '{0}' method returned null. It must return a JSON reader instance.</value>\n  </data>\n  <data name=\"MediaTypeFormatter_JsonWriterFactoryReturnedNull\" xml:space=\"preserve\">\n    <value>The '{0}' method returned null. It must return a JSON writer instance.</value>\n  </data>\n  <data name=\"MediaTypeFormatter_BsonParseError_MissingData\" xml:space=\"preserve\">\n    <value>Error parsing BSON data; unable to read content as a {0}.</value>\n  </data>\n  <data name=\"MediaTypeFormatter_BsonParseError_UnexpectedData\" xml:space=\"preserve\">\n    <value>Error parsing BSON data; unexpected dictionary content: {0} entries, first key '{1}'.</value>\n  </data>\n  <data name=\"RemoteStreamInfoCannotBeNull\" xml:space=\"preserve\">\n    <value>The '{0}' method in '{1}' returned null. It must return a RemoteStreamResult instance containing a writable stream and a valid URL.</value>\n  </data>\n  <data name=\"ByteRangeStreamInvalidOffset\" xml:space=\"preserve\">\n    <value>An attempt was made to move the position before the beginning of the stream.</value>\n  </data>\n  <data name=\"Argument_InvalidOffLen\" xml:space=\"preserve\">\n    <value>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.</value>\n  </data>\n  <data name=\"NotSupported_UnreadableStream\" xml:space=\"preserve\">\n    <value>Stream does not support reading.</value>\n  </data>\n  <data name=\"NotSupported_UnseekableStream\" xml:space=\"preserve\">\n    <value>Stream does not support seeking.</value>\n  </data>\n  <data name=\"NotSupported_UnwritableStream\" xml:space=\"preserve\">\n    <value>Stream does not support writing.</value>\n  </data>\n  <data name=\"ObjectDisposed_StreamClosed\" xml:space=\"preserve\">\n    <value>Cannot access a closed stream.</value>\n  </data>\n  <data name=\"JsonMediaTypeFormatter_DCS_NotSupported\" xml:space=\"preserve\">\n    <value>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.</value>\n  </data>\n  <data name=\"XmlMediaTypeFormatter_DCS_NotSupported\" xml:space=\"preserve\">\n    <value>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.</value>\n  </data>\n</root>"
  },
  {
    "path": "src/System.Net.Http.Formatting/PushStreamContent.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.IO;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Net.Http.Internal;\nusing System.Threading.Tasks;\nusing System.Web.Http;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// Provides an <see cref=\"HttpContent\"/> implementation that exposes an output <see cref=\"Stream\"/>\n    /// which can be written to directly. The ability to push data to the output stream differs from the\n    /// <see cref=\"StreamContent\"/> where data is pulled and not pushed.\n    /// </summary>\n    public class PushStreamContent : HttpContent\n    {\n        private readonly Func<Stream, HttpContent, TransportContext, Task> _onStreamAvailable;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"PushStreamContent\"/> class. The\n        /// <paramref name=\"onStreamAvailable\"/> action is called when an output stream\n        /// has become available allowing the action to write to it directly. When the\n        /// stream is closed, it will signal to the content that it has completed and the\n        /// HTTP request or response will be completed.\n        /// </summary>\n        /// <param name=\"onStreamAvailable\">The action to call when an output stream is available.</param>\n        public PushStreamContent(Action<Stream, HttpContent, TransportContext> onStreamAvailable)\n            : this(Taskify(onStreamAvailable), (MediaTypeHeaderValue)null)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"PushStreamContent\"/> class.\n        /// </summary>\n        /// <param name=\"onStreamAvailable\">The action to call when an output stream is available. When the\n        /// output stream is closed or disposed, it will signal to the content that it has completed and the\n        /// HTTP request or response will be completed.</param>\n        public PushStreamContent(Func<Stream, HttpContent, TransportContext, Task> onStreamAvailable)\n            : this(onStreamAvailable, (MediaTypeHeaderValue)null)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"PushStreamContent\"/> class with the given media type.\n        /// </summary>\n        /// <param name=\"onStreamAvailable\">The action to call when an output stream is available.</param>\n        /// <param name=\"mediaType\">The value of the Content-Type content header on an HTTP response.</param>\n        public PushStreamContent(Action<Stream, HttpContent, TransportContext> onStreamAvailable, string mediaType)\n            : this(Taskify(onStreamAvailable), new MediaTypeHeaderValue(mediaType))\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"PushStreamContent\"/> class with the given media type.\n        /// </summary>\n        /// <param name=\"onStreamAvailable\">The action to call when an output stream is available. When the\n        /// output stream is closed or disposed, it will signal to the content that it has completed and the\n        /// HTTP request or response will be completed.</param>\n        /// <param name=\"mediaType\">The value of the Content-Type content header on an HTTP response.</param>\n        public PushStreamContent(Func<Stream, HttpContent, TransportContext, Task> onStreamAvailable, string mediaType)\n            : this(onStreamAvailable, new MediaTypeHeaderValue(mediaType))\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"PushStreamContent\"/> class with the given <see cref=\"MediaTypeHeaderValue\"/>.\n        /// </summary>\n        /// <param name=\"onStreamAvailable\">The action to call when an output stream is available.</param>\n        /// <param name=\"mediaType\">The value of the Content-Type content header on an HTTP response.</param>\n        public PushStreamContent(Action<Stream, HttpContent, TransportContext> onStreamAvailable, MediaTypeHeaderValue mediaType)\n            : this(Taskify(onStreamAvailable), mediaType)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"PushStreamContent\"/> class with the given <see cref=\"MediaTypeHeaderValue\"/>.\n        /// </summary>\n        /// <param name=\"onStreamAvailable\">The action to call when an output stream is available. When the\n        /// output stream is closed or disposed, it will signal to the content that it has completed and the\n        /// HTTP request or response will be completed.</param>\n        /// <param name=\"mediaType\">The value of the Content-Type content header on an HTTP response.</param>\n        public PushStreamContent(Func<Stream, HttpContent, TransportContext, Task> onStreamAvailable, MediaTypeHeaderValue mediaType)\n        {\n            if (onStreamAvailable == null)\n            {\n                throw Error.ArgumentNull(\"onStreamAvailable\");\n            }\n\n            _onStreamAvailable = onStreamAvailable;\n            Headers.ContentType = mediaType ?? MediaTypeConstants.ApplicationOctetStreamMediaType;\n        }\n\n        private static Func<Stream, HttpContent, TransportContext, Task> Taskify(\n            Action<Stream, HttpContent, TransportContext> onStreamAvailable)\n        {\n            if (onStreamAvailable == null)\n            {\n                throw Error.ArgumentNull(\"onStreamAvailable\");\n            }\n\n            return (Stream stream, HttpContent content, TransportContext transportContext) =>\n            {\n                onStreamAvailable(stream, content, transportContext);\n                return TaskHelpers.Completed();\n            };\n        }\n\n        /// <summary>\n        /// When this method is called, it calls the action provided in the constructor with the output\n        /// stream to write to. Once the action has completed its work it closes the stream which will\n        /// close this content instance and complete the HTTP request or response.\n        /// </summary>\n        /// <param name=\"stream\">The <see cref=\"Stream\"/> to which to write.</param>\n        /// <param name=\"context\">The associated <see cref=\"TransportContext\"/>.</param>\n        /// <returns>A <see cref=\"Task\"/> instance that is asynchronously serializing the object's content.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Exception is passed as task result.\")]\n        protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)\n        {\n            TaskCompletionSource<bool> serializeToStreamTask = new TaskCompletionSource<bool>();\n\n            Stream wrappedStream = new CompleteTaskOnCloseStream(stream, serializeToStreamTask);\n            await _onStreamAvailable(wrappedStream, this, context);\n\n            // wait for wrappedStream.Close/Dispose to get called.\n            await serializeToStreamTask.Task;\n        }\n\n        /// <summary>\n        /// Computes the length of the stream if possible.\n        /// </summary>\n        /// <param name=\"length\">The computed length of the stream.</param>\n        /// <returns><c>true</c> if the length has been computed; otherwise <c>false</c>.</returns>\n        protected override bool TryComputeLength(out long length)\n        {\n            // We can't know the length of the content being pushed to the output stream.\n            length = -1;\n            return false;\n        }\n\n        internal class CompleteTaskOnCloseStream : DelegatingStream\n        {\n            private TaskCompletionSource<bool> _serializeToStreamTask;\n\n            public CompleteTaskOnCloseStream(Stream innerStream, TaskCompletionSource<bool> serializeToStreamTask)\n                : base(innerStream)\n            {\n                Contract.Assert(serializeToStreamTask != null);\n                _serializeToStreamTask = serializeToStreamTask;\n            }\n\n#if NETSTANDARD1_3\n            [SuppressMessage(\n                \"Microsoft.Usage\",\n                \"CA2215:Dispose methods should call base class dispose\",\n                Justification = \"See comments, this is intentional.\")]\n            protected override void Dispose(bool disposing)\n            {\n                // We don't dispose the underlying stream because we don't own it. Dispose in this case just signifies\n                // that the user's action is finished.\n                _serializeToStreamTask.TrySetResult(true);\n            }\n#else\n            public override void Close()\n            {\n                // We don't Close the underlying stream because we don't own it. Dispose in this case just signifies\n                // that the user's action is finished.\n                _serializeToStreamTask.TrySetResult(true);\n            }\n#endif\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/RemoteStreamInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Web.Http;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// Represents the result for <see cref=\"MultipartFormDataRemoteStreamProvider.GetRemoteStream\"/>.\n    /// </summary>\n    public class RemoteStreamInfo\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"RemoteStreamInfo\"/> class.\n        /// </summary>\n        /// <param name=\"remoteStream\">\n        /// The remote stream instance where the file will be written to.\n        /// </param>\n        /// <param name=\"location\">The remote file's location.</param>\n        /// <param name=\"fileName\">The remote file's name.</param>\n        public RemoteStreamInfo(Stream remoteStream, string location, string fileName)\n        {\n            if (remoteStream == null)\n            {\n                throw Error.ArgumentNull(\"remoteStream\");\n            }\n\n            if (location == null)\n            {\n                throw Error.ArgumentNull(\"location\");\n            }\n\n            if (fileName == null)\n            {\n                throw Error.ArgumentNull(\"fileName\");\n            }\n\n            FileName = fileName;\n            RemoteStream = remoteStream;\n            Location = location;\n        }\n\n        /// <summary>\n        /// Gets the remote file's location.\n        /// </summary>\n        public string FileName { get; private set; }\n\n        /// <summary>\n        /// Gets the remote file's location.\n        /// </summary>\n        public string Location { get; private set; }\n\n        /// <summary>\n        /// Gets the remote stream instance where the file will be written to.\n        /// </summary>\n        public Stream RemoteStream { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/System.Net.Http.Formatting.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{668E9021-CE84-49D9-98FB-DF125A9FCDB0}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>System.Net.Http</RootNamespace>\n    <AssemblyName>System.Net.Http.Formatting</AssemblyName>\n    <DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>\n    <RunCodeAnalysis>$(CodeAnalysis)</RunCodeAnalysis>\n    <CodeAnalysisRuleSet>..\\Strict.ruleset</CodeAnalysisRuleSet>\n    <DefineConstants>$(DefineConstants);ASPNETHTTPFORMATTING</DefineConstants>\n    <TargetFrameworkProfile Condition=\"'$(TargetFrameworkVersion)' != 'v4.5'\">Client</TargetFrameworkProfile>\n    <NoWarn>1591</NoWarn>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Buffers, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\System.Buffers.4.5.1\\lib\\netstandard2.0\\System.Buffers.dll</HintPath>\n      <SpecificVersion>False</SpecificVersion>\n      <Private>False</Private>\n    </Reference>\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Memory, Version=4.0.1.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\System.Memory.4.5.5\\lib\\netstandard2.0\\System.Memory.dll</HintPath>\n      <SpecificVersion>False</SpecificVersion>\n      <Private>False</Private>\n    </Reference>\n    <Reference Include=\"System.Net.Http\" />\n    <Reference Include=\"System.Net.Http.WebRequest\" />\n    <Reference Include=\"System.Runtime.Serialization\" />\n    <Reference Include=\"System.Threading.Tasks.Extensions, Version=4.2.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\System.Threading.Tasks.Extensions.4.5.4\\lib\\netstandard2.0\\System.Threading.Tasks.Extensions.dll</HintPath>\n      <SpecificVersion>False</SpecificVersion>\n      <Private>False</Private>\n    </Reference>\n    <Reference Include=\"System.Xml\" />\n    <Reference Include=\"System.Xml.Linq\" />\n\n    <Reference Include=\"netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\NETStandard.Library.2.0.3\\lib\\netstandard2.0\\netstandard.dll</HintPath>\n      <SpecificVersion>False</SpecificVersion>\n      <Private>False</Private>\n    </Reference>\n    <Reference Include=\"Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Newtonsoft.Json.13.0.1\\lib\\net45\\Newtonsoft.Json.dll</HintPath>\n      <SpecificVersion>False</SpecificVersion>\n      <Private>False</Private>\n    </Reference>\n    <Reference Include=\"Newtonsoft.Json.Bson, Version=1.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Newtonsoft.Json.Bson.1.0.2\\lib\\net45\\Newtonsoft.Json.Bson.dll</HintPath>\n      <SpecificVersion>False</SpecificVersion>\n      <Private>False</Private>\n    </Reference>\n\n    <Compile Include=\"..\\CommonAssemblyInfo.cs\" Link=\"Properties\\CommonAssemblyInfo.cs\" />\n    <Compile Include=\"..\\Common\\CollectionExtensions.cs\" Link=\"Common\\CollectionExtensions.cs\" />\n    <Compile Include=\"..\\Common\\Error.cs\" Link=\"Common\\Error.cs\" />\n    <Compile Include=\"..\\Common\\ListWrapperCollection.cs\" Link=\"Common\\ListWrapperCollection.cs\" />\n    <Compile Include=\"..\\Common\\TaskHelpers.cs\" Link=\"Common\\TaskHelpers.cs\" />\n    <Compile Include=\"..\\Common\\TaskHelpersExtensions.cs\" Link=\"Common\\TaskHelpersExtensions.cs\" />\n\n    <Compile Include=\"**\\*.cs\" Exclude=\"obj\\**\\*.cs;Properties\\Resources.Designer.cs\" />\n\n    <Compile Include=\"..\\Common\\CommonWebApiResources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DependentUpon>CommonWebApiResources.resx</DependentUpon>\n      <DesignTime>True</DesignTime>\n      <Link>Properties\\CommonWebApiResources.Designer.cs</Link>\n    </Compile>\n    <EmbeddedResource Include=\"..\\Common\\CommonWebApiResources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>CommonWebApiResources.Designer.cs</LastGenOutput>\n      <Link>Properties\\CommonWebApiResources.resx</Link>\n    </EmbeddedResource>\n\n    <Compile Include=\"Properties\\Resources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DependentUpon>Resources.resx</DependentUpon>\n      <DesignTime>True</DesignTime>\n    </Compile>\n    <EmbeddedResource Include=\"Properties\\Resources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>Resources.Designer.cs</LastGenOutput>\n      <SubType>Designer</SubType>\n    </EmbeddedResource>\n\n    <CodeAnalysisDictionary Include=\"..\\CodeAnalysisDictionary.xml\" Link=\"CodeAnalysisDictionary.xml\" />\n\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n</Project>\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/UnsupportedMediaTypeException.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Net.Http.Headers;\nusing System.Web.Http;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// Defines an exception type for signalling that a request's media type was not supported.\n    /// </summary>\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2237:MarkISerializableTypesWithSerializable\", Justification = \"This type is not meant to be serialized\")]\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2240:ImplementISerializableCorrectly\", Justification = \"This type is not meant to be serialized\")]\n    [SuppressMessage(\"Microsoft.Design\", \"CA1032:ImplementStandardExceptionConstructors\", Justification = \"UnsupportedMediaTypeException is only used to propagate the media type back to the server layer\")]\n    public class UnsupportedMediaTypeException : Exception\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"UnsupportedMediaTypeException\" /> class.\n        /// </summary>\n        /// <param name=\"message\">The message that describes the error.</param>\n        /// <param name=\"mediaType\">The unsupported media type.</param>\n        public UnsupportedMediaTypeException(string message, MediaTypeHeaderValue mediaType)\n            : base(message)\n        {\n            if (mediaType == null)\n            {\n                throw Error.ArgumentNull(\"mediaType\");\n            }\n\n            MediaType = mediaType;\n        }\n\n        public MediaTypeHeaderValue MediaType { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/UriExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Net.Http.Formatting;\nusing System.Web.Http;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// Extension methods to allow strongly typed objects to be read from the query component of <see cref=\"Uri\"/> instances.\n    /// </summary>\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class UriExtensions\n    {\n        /// <summary>\n        /// Parses the query portion of the specified <see cref=\"Uri\"/>.\n        /// </summary>\n        /// <param name=\"address\">The <see cref=\"Uri\"/> instance from which to read.</param>\n        /// <returns>A <see cref=\"NameValueCollection\"/> containing the parsed result.</returns>\n        public static NameValueCollection ParseQueryString(this Uri address)\n        {\n            if (address == null)\n            {\n                throw Error.ArgumentNull(\"address\");\n            }\n\n            return new FormDataCollection(address).ReadAsNameValueCollection();\n        }\n\n        /// <summary>\n        /// Reads HTML form URL encoded data provided in the <see cref=\"Uri\"/> query component as a <see cref=\"JObject\"/> object.\n        /// </summary>\n        /// <param name=\"address\">The <see cref=\"Uri\"/> instance from which to read.</param>\n        /// <param name=\"value\">An object to be initialized with this instance or null if the conversion cannot be performed.</param>\n        /// <returns><c>true</c> if the query component can be read as <see cref=\"JObject\"/>; otherwise <c>false</c>.</returns>\n        public static bool TryReadQueryAsJson(this Uri address, out JObject value)\n        {\n            if (address == null)\n            {\n                throw Error.ArgumentNull(\"address\");\n            }\n\n            IEnumerable<KeyValuePair<string, string>> query = new FormDataCollection(address);\n            return FormUrlEncodedJson.TryParse(query, out value);\n        }\n\n        /// <summary>\n        /// Reads HTML form URL encoded data provided in the <see cref=\"Uri\"/> query component as an <see cref=\"Object\"/> of the given <paramref name=\"type\"/>.\n        /// </summary>\n        /// <param name=\"address\">The <see cref=\"Uri\"/> instance from which to read.</param>\n        /// <param name=\"type\">The type of the object to read.</param>\n        /// <param name=\"value\">An object to be initialized with this instance or null if the conversion cannot be performed.</param>\n        /// <returns><c>true</c> if the query component can be read as the specified type; otherwise <c>false</c>.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1007:UseGenericsWhereAppropriate\", Justification = \"This is the non-generic version.\")]\n        public static bool TryReadQueryAs(this Uri address, Type type, out object value)\n        {\n            if (address == null)\n            {\n                throw Error.ArgumentNull(\"address\");\n            }\n\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            IEnumerable<KeyValuePair<string, string>> query = new FormDataCollection(address);\n            JObject jsonObject;\n            if (FormUrlEncodedJson.TryParse(query, out jsonObject))\n            {\n                using (JTokenReader jsonReader = new JTokenReader(jsonObject))\n                {\n                    value = new JsonSerializer().Deserialize(jsonReader, type);\n                }\n                return true;\n            }\n\n            value = null;\n            return false;\n        }\n\n        /// <summary>\n        /// Reads HTML form URL encoded data provided in the <see cref=\"Uri\"/> query component as an <see cref=\"Object\"/> of type <typeparamref name=\"T\"/>.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of the object to read.</typeparam>\n        /// <param name=\"address\">The <see cref=\"Uri\"/> instance from which to read.</param>\n        /// <param name=\"value\">An object to be initialized with this instance or null if the conversion cannot be performed.</param>\n        /// <returns><c>true</c> if the query component can be read as the specified type; otherwise <c>false</c>.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1004:GenericMethodsShouldProvideTypeParameter\", Justification = \"The T represents the output parameter, not an input parameter.\")]\n        public static bool TryReadQueryAs<T>(this Uri address, out T value)\n        {\n            if (address == null)\n            {\n                throw Error.ArgumentNull(\"address\");\n            }\n\n            IEnumerable<KeyValuePair<string, string>> query = new FormDataCollection(address);\n            JObject jsonObject;\n            if (FormUrlEncodedJson.TryParse(query, out jsonObject))\n            {\n                value = jsonObject.ToObject<T>();\n                return true;\n            }\n\n            value = default(T);\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Newtonsoft.Json\" version=\"13.0.1\" targetFramework=\"net45\" />\n  <package id=\"Newtonsoft.Json.Bson\" version=\"1.0.2\" targetFramework=\"net45\" />\n  <package id=\"NETStandard.Library\" version=\"2.0.3\" targetFramework=\"netstandard2.0\" />\n  <package id=\"System.Buffers\" version=\"4.5.1\" targetFramework=\"netstandard2.0\" />\n  <package id=\"System.Memory\" version=\"4.5.5\" targetFramework=\"netstandard2.0\" />\n  <package id=\"System.Threading.Tasks.Extensions\" version=\"4.5.4\" targetFramework=\"netstandard2.0\" />\n</packages>"
  },
  {
    "path": "src/System.Net.Http.Formatting.ns1_3/ICloneable.cs",
    "content": "// No ICloneable interface in .NET Standard 1.3.\n\nnamespace System\n{\n    internal interface ICloneable\n    {\n        object Clone();\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting.ns1_3/MediaTypeHeaderValueExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net.Http.Headers;\n\nnamespace System.Net.Http\n{\n    internal static class MediaTypeHeaderValueExtensions\n    {\n        public static MediaTypeHeaderValue Clone(this MediaTypeHeaderValue mediaType)\n        {\n            Contract.Assert(mediaType != null && mediaType.GetType() == typeof(MediaTypeHeaderValue));\n\n            var result = new MediaTypeHeaderValue(mediaType.MediaType);\n            foreach (var parameter in mediaType.Parameters)\n            {\n                result.Parameters.Add(new NameValueHeaderValue(parameter.Name, parameter.Value));\n            }\n\n            return result;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Net.Http.Formatting.ns1_3/System.Net.Http.Formatting.ns1_3.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <TargetFramework>netstandard1.3</TargetFramework>\n    <RootNamespace>System.Net.Http</RootNamespace>\n    <AssemblyName>System.Net.Http.Formatting</AssemblyName>\n    <OutputPath>$(OutputPath)ns1_3\\</OutputPath>\n    <DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>\n    <RunCodeAnalysis>false</RunCodeAnalysis>\n    <DefineConstants>$(DefineConstants);ASPNETHTTPFORMATTING</DefineConstants>\n    <NoWarn>1591</NoWarn>\n    <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>\n    <Configurations>$(Configurations);CodeAnalysis</Configurations>\n    <GenerateAssemblyInfo>false</GenerateAssemblyInfo>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <PackageReference Include=\"System.Collections.Specialized\" Version=\"4.3.0\" />\n    <PackageReference Include=\"System.ComponentModel.EventBasedAsync\" Version=\"4.3.0\" />\n    <PackageReference Include=\"System.Data.Common\" Version=\"4.3.0\" />\n    <PackageReference Include=\"System.Diagnostics.Contracts\" Version=\"4.3.0\" />\n    <PackageReference Include=\"System.Memory\" Version=\"4.5.5\" />\n    <PackageReference Include=\"System.Runtime.Serialization.Json\" Version=\"4.3.0\" />\n    <PackageReference Include=\"System.Runtime.Serialization.Xml\" Version=\"4.3.0\" />\n    <PackageReference Include=\"System.Threading.Tasks.Extensions\" Version=\"4.5.4\" />\n    <PackageReference Include=\"System.Xml.XmlSerializer\" Version=\"4.3.0\" />\n\n    <PackageReference Include=\"Newtonsoft.Json\" Version=\"13.0.1\" />\n    <PackageReference Include=\"Newtonsoft.Json.Bson\" Version=\"1.0.2\" />\n\n    <Compile Include=\"..\\CommonAssemblyInfo.cs\" Link=\"Properties\\CommonAssemblyInfo.cs\" />\n    <Compile Include=\"..\\Common\\CollectionExtensions.cs\" Link=\"Common\\CollectionExtensions.cs\" />\n    <Compile Include=\"..\\Common\\Error.cs\" Link=\"Common\\Error.cs\" />\n    <Compile Include=\"..\\Common\\ListWrapperCollection.cs\" Link=\"Common\\ListWrapperCollection.cs\" />\n    <Compile Include=\"..\\Common\\TaskHelpers.cs\" Link=\"Common\\TaskHelpers.cs\" />\n    <Compile Include=\"..\\Common\\TaskHelpersExtensions.cs\" Link=\"Common\\TaskHelpersExtensions.cs\" />\n\n    <Compile Include=\"..\\System.Net.Http.Formatting\\**\\*.cs\"\n        Exclude=\"..\\System.Net.Http.Formatting\\obj\\**\\*.cs;\n                 ..\\System.Net.Http.Formatting\\Formatting\\BufferedMediaTypeFormatter.cs;\n                 ..\\System.Net.Http.Formatting\\Handlers\\ProgressWriteAsyncResult.cs;\n                 ..\\System.Net.Http.Formatting\\Properties\\Resources.Designer.cs\">\n      <Link>%(RecursiveDir)\\%(Filename).cs</Link>\n    </Compile>\n\n    <Compile Include=\"..\\Common\\CommonWebApiResources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DependentUpon>CommonWebApiResources.resx</DependentUpon>\n      <DesignTime>True</DesignTime>\n      <Link>Properties\\CommonWebApiResources.Designer.cs</Link>\n    </Compile>\n    <EmbeddedResource Include=\"..\\Common\\CommonWebApiResources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>CommonWebApiResources.Designer.cs</LastGenOutput>\n      <Link>Properties\\CommonWebApiResources.resx</Link>\n    </EmbeddedResource>\n\n    <Compile Include=\"..\\System.Net.Http.Formatting\\Properties\\Resources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DependentUpon>Resources.resx</DependentUpon>\n      <DesignTime>True</DesignTime>\n      <Link>Properties\\Resources.Designer.cs</Link>\n    </Compile>\n    <EmbeddedResource Include=\"..\\System.Net.Http.Formatting\\Properties\\Resources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>Resources.Designer.cs</LastGenOutput>\n      <Link>Properties\\Resources.resx</Link>\n      <SubType>Designer</SubType>\n    </EmbeddedResource>\n\n    <CodeAnalysisDictionary Include=\"..\\CodeAnalysisDictionary.xml\" Link=\"CodeAnalysisDictionary.xml\" />\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "src/System.Net.Http.Formatting.ns2_0/System.Net.Http.Formatting.ns2_0.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <TargetFramework>netstandard2.0</TargetFramework>\n    <RootNamespace>System.Net.Http</RootNamespace>\n    <AssemblyName>System.Net.Http.Formatting</AssemblyName>\n    <OutputPath>$(OutputPath)ns2_0\\</OutputPath>\n    <DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>\n    <RunCodeAnalysis>false</RunCodeAnalysis>\n    <DefineConstants>$(DefineConstants);ASPNETHTTPFORMATTING</DefineConstants>\n    <NoWarn>1591</NoWarn>\n    <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>\n    <Configurations>$(Configurations);CodeAnalysis</Configurations>\n    <GenerateAssemblyInfo>false</GenerateAssemblyInfo>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <PackageReference Include=\"System.Memory\" Version=\"4.5.5\" />\n    <PackageReference Include=\"System.Threading.Tasks.Extensions\" Version=\"4.5.4\" />\n\n    <PackageReference Include=\"Newtonsoft.Json\" Version=\"13.0.1\" />\n    <PackageReference Include=\"Newtonsoft.Json.Bson\" Version=\"1.0.2\" />\n\n    <Compile Include=\"..\\CommonAssemblyInfo.cs\" Link=\"Properties\\CommonAssemblyInfo.cs\" />\n    <Compile Include=\"..\\Common\\CollectionExtensions.cs\" Link=\"Common\\CollectionExtensions.cs\" />\n    <Compile Include=\"..\\Common\\Error.cs\" Link=\"Common\\Error.cs\" />\n    <Compile Include=\"..\\Common\\ListWrapperCollection.cs\" Link=\"Common\\ListWrapperCollection.cs\" />\n    <Compile Include=\"..\\Common\\TaskHelpers.cs\" Link=\"Common\\TaskHelpers.cs\" />\n    <Compile Include=\"..\\Common\\TaskHelpersExtensions.cs\" Link=\"Common\\TaskHelpersExtensions.cs\" />\n\n    <Compile Include=\"..\\System.Net.Http.Formatting\\**\\*.cs\"\n        Exclude=\"..\\System.Net.Http.Formatting\\obj\\**\\*.cs;\n                 ..\\System.Net.Http.Formatting\\Properties\\Resources.Designer.cs\">\n      <Link>%(RecursiveDir)\\%(Filename).cs</Link>\n    </Compile>\n\n    <Compile Include=\"..\\Common\\CommonWebApiResources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DependentUpon>CommonWebApiResources.resx</DependentUpon>\n      <DesignTime>True</DesignTime>\n      <Link>Properties\\CommonWebApiResources.Designer.cs</Link>\n    </Compile>\n    <EmbeddedResource Include=\"..\\Common\\CommonWebApiResources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>CommonWebApiResources.Designer.cs</LastGenOutput>\n      <Link>Properties\\CommonWebApiResources.resx</Link>\n    </EmbeddedResource>\n\n    <Compile Include=\"..\\System.Net.Http.Formatting\\Properties\\Resources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DependentUpon>Resources.resx</DependentUpon>\n      <DesignTime>True</DesignTime>\n      <Link>Properties\\Resources.Designer.cs</Link>\n    </Compile>\n    <EmbeddedResource Include=\"..\\System.Net.Http.Formatting\\Properties\\Resources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>Resources.Designer.cs</LastGenOutput>\n      <Link>Properties\\Resources.resx</Link>\n      <SubType>Designer</SubType>\n    </EmbeddedResource>\n\n    <CodeAnalysisDictionary Include=\"..\\CodeAnalysisDictionary.xml\" Link=\"CodeAnalysisDictionary.xml\" />\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "src/System.Web.Cors/CorsConstants.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Cors\n{\n    /// <summary>\n    /// CORS-related constants.\n    /// </summary>\n    public static class CorsConstants\n    {\n        /// <summary>\n        /// The HTTP method for the CORS preflight request.\n        /// </summary>\n        public static readonly string PreflightHttpMethod = \"OPTIONS\";\n\n        /// <summary>\n        /// The Origin request header.\n        /// </summary>\n        public static readonly string Origin = \"Origin\";\n\n        /// <summary>\n        /// The value for the Access-Control-Allow-Origin response header to allow all origins.\n        /// </summary>\n        public static readonly string AnyOrigin = \"*\";\n\n        /// <summary>\n        /// The Access-Control-Request-Method request header.\n        /// </summary>\n        public static readonly string AccessControlRequestMethod = \"Access-Control-Request-Method\";\n\n        /// <summary>\n        /// The Access-Control-Request-Headers request header.\n        /// </summary>\n        public static readonly string AccessControlRequestHeaders = \"Access-Control-Request-Headers\";\n\n        /// <summary>\n        /// The Access-Control-Allow-Origin response header.\n        /// </summary>\n        public static readonly string AccessControlAllowOrigin = \"Access-Control-Allow-Origin\";\n\n        /// <summary>\n        /// The Access-Control-Allow-Headers response header.\n        /// </summary>\n        public static readonly string AccessControlAllowHeaders = \"Access-Control-Allow-Headers\";\n\n        /// <summary>\n        /// The Access-Control-Expose-Headers response header.\n        /// </summary>\n        public static readonly string AccessControlExposeHeaders = \"Access-Control-Expose-Headers\";\n\n        /// <summary>\n        /// The Access-Control-Allow-Methods response header.\n        /// </summary>\n        public static readonly string AccessControlAllowMethods = \"Access-Control-Allow-Methods\";\n\n        /// <summary>\n        /// The Access-Control-Allow-Credentials response header.\n        /// </summary>\n        public static readonly string AccessControlAllowCredentials = \"Access-Control-Allow-Credentials\";\n\n        /// <summary>\n        /// The Access-Control-Max-Age response header.\n        /// </summary>\n        public static readonly string AccessControlMaxAge = \"Access-Control-Max-Age\";\n\n        internal static readonly string[] SimpleRequestHeaders =\n        {\n            \"Origin\",\n            \"Accept\",\n            \"Accept-Language\",\n            \"Content-Language\",\n        };\n\n        internal static readonly string[] SimpleResponseHeaders =\n        {\n            \"Cache-Control\",\n            \"Content-Language\",\n            \"Content-Type\",\n            \"Expires\",\n            \"Last-Modified\",\n            \"Pragma\"\n        };\n\n        internal static readonly string[] SimpleMethods =\n        {\n            \"GET\",\n            \"HEAD\",\n            \"POST\"\n        };\n    }\n}"
  },
  {
    "path": "src/System.Web.Cors/CorsEngine.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Web.Cors.Properties;\n\nnamespace System.Web.Cors\n{\n    /// <summary>\n    /// An implementation of <see cref=\"ICorsEngine\"/> based on the CORS specifications.\n    /// </summary>\n    public class CorsEngine : ICorsEngine\n    {\n        /// <summary>\n        /// Evaluates the policy.\n        /// </summary>\n        /// <param name=\"requestContext\">The <see cref=\"CorsRequestContext\" />.</param>\n        /// <param name=\"policy\">The <see cref=\"CorsPolicy\" />.</param>\n        /// <returns>\n        /// The <see cref=\"CorsResult\" />\n        /// </returns>\n        /// <exception cref=\"System.ArgumentNullException\">\n        /// requestContext\n        /// or\n        /// policy\n        /// </exception>\n        public virtual CorsResult EvaluatePolicy(CorsRequestContext requestContext, CorsPolicy policy)\n        {\n            if (requestContext == null)\n            {\n                throw new ArgumentNullException(\"requestContext\");\n            }\n            if (policy == null)\n            {\n                throw new ArgumentNullException(\"policy\");\n            }\n\n            CorsResult result = new CorsResult();\n\n            if (!TryValidateOrigin(requestContext, policy, result))\n            {\n                return result;\n            }\n\n            result.SupportsCredentials = policy.SupportsCredentials;\n\n            if (requestContext.IsPreflight)\n            {\n                if (!TryValidateMethod(requestContext, policy, result))\n                {\n                    return result;\n                }\n\n                if (!TryValidateHeaders(requestContext, policy, result))\n                {\n                    return result;\n                }\n\n                result.PreflightMaxAge = policy.PreflightMaxAge;\n            }\n            else\n            {\n                AddHeaderValues(result.AllowedExposedHeaders, policy.ExposedHeaders);\n            }\n\n            return result;\n        }\n\n        /// <summary>\n        /// Try to validate the requested method based on <see cref=\"CorsPolicy\"/>.\n        /// </summary>\n        /// <param name=\"requestContext\">The <see cref=\"CorsRequestContext\"/>.</param>\n        /// <param name=\"policy\">The <see cref=\"CorsPolicy\"/>.</param>\n        /// <param name=\"result\">The <see cref=\"CorsResult\"/>.</param>\n        /// <returns><c>true</c> if the requested method is valid; otherwise, <c>false</c>. </returns>\n        /// <exception cref=\"System.ArgumentNullException\">\n        /// requestContext\n        /// or\n        /// policy\n        /// or\n        /// result\n        /// </exception>\n        public virtual bool TryValidateMethod(CorsRequestContext requestContext, CorsPolicy policy, CorsResult result)\n        {\n            if (requestContext == null)\n            {\n                throw new ArgumentNullException(\"requestContext\");\n            }\n            if (policy == null)\n            {\n                throw new ArgumentNullException(\"policy\");\n            }\n            if (result == null)\n            {\n                throw new ArgumentNullException(\"result\");\n            }\n\n            if (policy.AllowAnyMethod ||\n                policy.Methods.Contains(requestContext.AccessControlRequestMethod))\n            {\n                result.AllowedMethods.Add(requestContext.AccessControlRequestMethod);\n            }\n            else\n            {\n                result.ErrorMessages.Add(String.Format(\n                    CultureInfo.CurrentCulture,\n                    SRResources.MethodNotAllowed,\n                    requestContext.AccessControlRequestMethod));\n            }\n\n            return result.IsValid;\n        }\n\n        /// <summary>\n        /// Try to validate the requested headers based on <see cref=\"CorsPolicy\"/>.\n        /// </summary>\n        /// <param name=\"requestContext\">The <see cref=\"CorsRequestContext\"/>.</param>\n        /// <param name=\"policy\">The <see cref=\"CorsPolicy\"/>.</param>\n        /// <param name=\"result\">The <see cref=\"CorsResult\"/>.</param>\n        /// <returns><c>true</c> if the requested headers are valid; otherwise, <c>false</c>. </returns>\n        /// <exception cref=\"System.ArgumentNullException\">\n        /// requestContext\n        /// or\n        /// policy\n        /// or\n        /// result\n        /// </exception>\n        public virtual bool TryValidateHeaders(CorsRequestContext requestContext, CorsPolicy policy, CorsResult result)\n        {\n            if (requestContext == null)\n            {\n                throw new ArgumentNullException(\"requestContext\");\n            }\n            if (policy == null)\n            {\n                throw new ArgumentNullException(\"policy\");\n            }\n            if (result == null)\n            {\n                throw new ArgumentNullException(\"result\");\n            }\n\n            if (policy.AllowAnyHeader ||\n                requestContext.AccessControlRequestHeaders.IsSubsetOf(policy.Headers))\n            {\n                AddHeaderValues(result.AllowedHeaders, requestContext.AccessControlRequestHeaders);\n            }\n            else\n            {\n                result.ErrorMessages.Add(String.Format(\n                    CultureInfo.CurrentCulture,\n                    SRResources.HeadersNotAllowed,\n                    String.Join(\",\", requestContext.AccessControlRequestHeaders)));\n            }\n\n            return result.IsValid;\n        }\n\n        /// <summary>\n        /// Try to validate the request origin based on <see cref=\"CorsPolicy\"/>.\n        /// </summary>\n        /// <param name=\"requestContext\">The <see cref=\"CorsRequestContext\"/>.</param>\n        /// <param name=\"policy\">The <see cref=\"CorsPolicy\"/>.</param>\n        /// <param name=\"result\">The <see cref=\"CorsResult\"/>.</param>\n        /// <returns><c>true</c> if the request origin is valid; otherwise, <c>false</c>. </returns>\n        /// <exception cref=\"System.ArgumentNullException\">\n        /// requestContext\n        /// or\n        /// policy\n        /// or\n        /// result\n        /// </exception>\n        public virtual bool TryValidateOrigin(CorsRequestContext requestContext, CorsPolicy policy, CorsResult result)\n        {\n            if (requestContext == null)\n            {\n                throw new ArgumentNullException(\"requestContext\");\n            }\n            if (policy == null)\n            {\n                throw new ArgumentNullException(\"policy\");\n            }\n            if (result == null)\n            {\n                throw new ArgumentNullException(\"result\");\n            }\n\n            if (requestContext.Origin != null)\n            {\n                if (policy.AllowAnyOrigin)\n                {\n                    if (policy.SupportsCredentials)\n                    {\n                        result.AllowedOrigin = requestContext.Origin;\n                    }\n                    else\n                    {\n                        result.AllowedOrigin = CorsConstants.AnyOrigin;\n                    }\n                }\n                else if (policy.Origins.Contains(requestContext.Origin))\n                {\n                    result.AllowedOrigin = requestContext.Origin;\n                }\n                else\n                {\n                    result.ErrorMessages.Add(String.Format(\n                        CultureInfo.CurrentCulture,\n                        SRResources.OriginNotAllowed,\n                        requestContext.Origin));\n                }\n            }\n            else\n            {\n                result.ErrorMessages.Add(SRResources.NoOriginHeader);\n            }\n\n            return result.IsValid;\n        }\n\n        private static void AddHeaderValues(IList<string> target, IEnumerable<string> headerValues)\n        {\n            foreach (string headerValue in headerValues)\n            {\n                target.Add(headerValue);\n            }\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Cors/CorsPolicy.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Text;\nusing System.Web.Cors.Properties;\n\nnamespace System.Web.Cors\n{\n    /// <summary>\n    /// Defines the policy for Cross-Origin requests based on the CORS specifications.\n    /// </summary>\n    public class CorsPolicy\n    {\n        private long? _preflightMaxAge;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"CorsPolicy\"/> class.\n        /// </summary>\n        public CorsPolicy()\n        {\n            ExposedHeaders = new List<string>();\n            Headers = new List<string>();\n            Methods = new List<string>();\n            Origins = new List<string>();\n        }\n\n        /// <summary>\n        /// Gets or sets a value indicating whether to allow all headers.\n        /// </summary>\n        public bool AllowAnyHeader { get; set; }\n\n        /// <summary>\n        /// Gets or sets a value indicating whether to allow all methods.\n        /// </summary>\n        public bool AllowAnyMethod { get; set; }\n\n        /// <summary>\n        /// Gets or sets a value indicating whether to allow all origins.\n        /// </summary>\n        public bool AllowAnyOrigin { get; set; }\n\n        /// <summary>\n        /// Gets the headers that the resource might use and can be exposed.\n        /// </summary>\n        public IList<string> ExposedHeaders { get; private set; }\n\n        /// <summary>\n        /// Gets the headers that are supported by the resource.\n        /// </summary>\n        public IList<string> Headers { get; private set; }\n\n        /// <summary>\n        /// Gets the methods that are supported by the resource.\n        /// </summary>\n        public IList<string> Methods { get; private set; }\n\n        /// <summary>\n        /// Gets the origins that are allowed to access the resource.\n        /// </summary>\n        public IList<string> Origins { get; private set; }\n\n        /// <summary>\n        /// Gets or sets the number of seconds the results of a preflight request can be cached.\n        /// </summary>\n        public long? PreflightMaxAge\n        {\n            get\n            {\n                return _preflightMaxAge;\n            }\n            set\n            {\n                if (value < 0)\n                {\n                    throw new ArgumentOutOfRangeException(\"value\", SRResources.PreflightMaxAgeOutOfRange);\n                }\n                _preflightMaxAge = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets a value indicating whether the resource supports user credentials in the request.\n        /// </summary>\n        public bool SupportsCredentials { get; set; }\n\n        /// <summary>\n        /// Returns a <see cref=\"System.String\" /> that represents this instance.\n        /// </summary>\n        /// <returns>\n        /// A <see cref=\"System.String\" /> that represents this instance.\n        /// </returns>\n        public override string ToString()\n        {\n            StringBuilder builder = new StringBuilder();\n            builder.Append(\"AllowAnyHeader: \");\n            builder.Append(AllowAnyHeader);\n            builder.Append(\", AllowAnyMethod: \");\n            builder.Append(AllowAnyMethod);\n            builder.Append(\", AllowAnyOrigin: \");\n            builder.Append(AllowAnyOrigin);\n            builder.Append(\", PreflightMaxAge: \");\n            builder.Append(PreflightMaxAge.HasValue ? PreflightMaxAge.Value.ToString(CultureInfo.InvariantCulture) : \"null\");\n            builder.Append(\", SupportsCredentials: \");\n            builder.Append(SupportsCredentials);\n            builder.Append(\", Origins: {\");\n            builder.Append(String.Join(\",\", Origins));\n            builder.Append(\"}\");\n            builder.Append(\", Methods: {\");\n            builder.Append(String.Join(\",\", Methods));\n            builder.Append(\"}\");\n            builder.Append(\", Headers: {\");\n            builder.Append(String.Join(\",\", Headers));\n            builder.Append(\"}\");\n            builder.Append(\", ExposedHeaders: {\");\n            builder.Append(String.Join(\",\", ExposedHeaders));\n            builder.Append(\"}\");\n            return builder.ToString();\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Cors/CorsRequestContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Text;\n\nnamespace System.Web.Cors\n{\n    /// <summary>\n    /// Provides access to CORS-specific information on the request.\n    /// </summary>\n    public class CorsRequestContext\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"CorsRequestContext\"/> class.\n        /// </summary>\n        public CorsRequestContext()\n        {\n            AccessControlRequestHeaders = new HashSet<string>(StringComparer.OrdinalIgnoreCase);\n            Properties = new Dictionary<string, object>();\n        }\n\n        /// <summary>\n        /// Gets or sets the request URI.\n        /// </summary>\n        public Uri RequestUri { get; set; }\n\n        /// <summary>\n        /// Gets or sets the request method.\n        /// </summary>\n        public string HttpMethod { get; set; }\n\n        /// <summary>\n        /// Gets or sets the Origin header value.\n        /// </summary>\n        public string Origin { get; set; }\n\n        /// <summary>\n        /// Gets or sets the Host header value.\n        /// </summary>\n        public string Host { get; set; }\n\n        /// <summary>\n        /// Gets or sets the Access-Control-Request-Method header value.\n        /// </summary>\n        public string AccessControlRequestMethod { get; set; }\n\n        /// <summary>\n        /// Gets the Access-Control-Request-Headers header value.\n        /// </summary>\n        public ISet<string> AccessControlRequestHeaders { get; private set; }\n\n        /// <summary>\n        /// Gets a set of properties for the <see cref=\"CorsRequestContext\"/>.\n        /// </summary>\n        public IDictionary<string, object> Properties { get; private set; }\n\n        /// <summary>\n        /// Gets a value indicating whether this is a preflight request.\n        /// </summary>\n        public bool IsPreflight\n        {\n            get\n            {\n                return Origin != null &&\n                    AccessControlRequestMethod != null &&\n                    String.Equals(HttpMethod, CorsConstants.PreflightHttpMethod, StringComparison.OrdinalIgnoreCase);\n            }\n        }\n\n        /// <summary>\n        /// Returns a <see cref=\"System.String\" /> that represents this instance.\n        /// </summary>\n        /// <returns>\n        /// A <see cref=\"System.String\" /> that represents this instance.\n        /// </returns>\n        public override string ToString()\n        {\n            StringBuilder builder = new StringBuilder();\n            builder.Append(\"Origin: \");\n            builder.Append(Origin ?? \"null\");\n            builder.Append(\", HttpMethod: \");\n            builder.Append(HttpMethod ?? \"null\");\n            builder.Append(\", IsPreflight: \");\n            builder.Append(IsPreflight);\n            builder.Append(\", Host: \");\n            builder.Append(Host);\n            builder.Append(\", AccessControlRequestMethod: \");\n            builder.Append(AccessControlRequestMethod ?? \"null\");\n            builder.Append(\", RequestUri: \");\n            builder.Append(RequestUri);\n            builder.Append(\", AccessControlRequestHeaders: {\");\n            builder.Append(String.Join(\",\", AccessControlRequestHeaders));\n            builder.Append(\"}\");\n            return builder.ToString();\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Cors/CorsResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Text;\nusing System.Web.Cors.Properties;\n\nnamespace System.Web.Cors\n{\n    /// <summary>\n    /// Results returned by <see cref=\"CorsEngine\"/>.\n    /// </summary>\n    public class CorsResult\n    {\n        private long? _preflightMaxAge;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"CorsResult\"/> class.\n        /// </summary>\n        public CorsResult()\n        {\n            AllowedMethods = new List<string>();\n            AllowedHeaders = new List<string>();\n            AllowedExposedHeaders = new List<string>();\n            ErrorMessages = new List<string>();\n        }\n\n        /// <summary>\n        /// Gets a value indicating whether the result is valid.\n        /// </summary>\n        public bool IsValid\n        {\n            get\n            {\n                return ErrorMessages.Count == 0;\n            }\n        }\n\n        /// <summary>\n        /// Gets the error messages.\n        /// </summary>\n        public IList<string> ErrorMessages { get; private set; }\n\n        /// <summary>\n        /// Gets or sets the allowed origin.\n        /// </summary>\n        public string AllowedOrigin { get; set; }\n\n        /// <summary>\n        /// Gets or sets a value indicating whether the resource supports user credentials.\n        /// </summary>\n        public bool SupportsCredentials { get; set; }\n\n        /// <summary>\n        /// Gets the allowed methods.\n        /// </summary>\n        public IList<string> AllowedMethods { get; private set; }\n\n        /// <summary>\n        /// Gets the allowed headers.\n        /// </summary>\n        public IList<string> AllowedHeaders { get; private set; }\n\n        /// <summary>\n        /// Gets the allowed headers that can be exposed on the response.\n        /// </summary>\n        public IList<string> AllowedExposedHeaders { get; private set; }\n\n        /// <summary>\n        /// Gets or sets the number of seconds the results of a preflight request can be cached.\n        /// </summary>\n        public long? PreflightMaxAge\n        {\n            get\n            {\n                return _preflightMaxAge;\n            }\n            set\n            {\n                if (value < 0)\n                {\n                    throw new ArgumentOutOfRangeException(\"value\", SRResources.PreflightMaxAgeOutOfRange);\n                }\n                _preflightMaxAge = value;\n            }\n        }\n\n        /// <summary>\n        /// Returns CORS-specific headers that should be added to the response.\n        /// </summary>\n        /// <returns>The response headers.</returns>\n        public virtual IDictionary<string, string> ToResponseHeaders()\n        {\n            IDictionary<string, string> headers = new Dictionary<string, string>();\n\n            if (AllowedOrigin != null)\n            {\n                headers.Add(CorsConstants.AccessControlAllowOrigin, AllowedOrigin);\n            }\n\n            if (SupportsCredentials)\n            {\n                headers.Add(CorsConstants.AccessControlAllowCredentials, \"true\");\n            }\n\n            if (AllowedMethods.Count > 0)\n            {\n                // Filter out simple methods\n                IEnumerable<string> nonSimpleAllowMethods = AllowedMethods.Where(m =>\n                    !CorsConstants.SimpleMethods.Contains(m, StringComparer.OrdinalIgnoreCase));\n                AddHeader(headers, CorsConstants.AccessControlAllowMethods, nonSimpleAllowMethods);\n            }\n\n            if (AllowedHeaders.Count > 0)\n            {\n                // Filter out simple request headers\n                IEnumerable<string> nonSimpleAllowRequestHeaders = AllowedHeaders.Where(header =>\n                    !CorsConstants.SimpleRequestHeaders.Contains(header, StringComparer.OrdinalIgnoreCase));\n                AddHeader(headers, CorsConstants.AccessControlAllowHeaders, nonSimpleAllowRequestHeaders);\n            }\n\n            if (AllowedExposedHeaders.Count > 0)\n            {\n                // Filter out simple response headers\n                IEnumerable<string> nonSimpleAllowResponseHeaders = AllowedExposedHeaders.Where(header =>\n                    !CorsConstants.SimpleResponseHeaders.Contains(header, StringComparer.OrdinalIgnoreCase));\n                AddHeader(headers, CorsConstants.AccessControlExposeHeaders, nonSimpleAllowResponseHeaders);\n            }\n\n            if (PreflightMaxAge.HasValue)\n            {\n                headers.Add(CorsConstants.AccessControlMaxAge, PreflightMaxAge.ToString());\n            }\n\n            return headers;\n        }\n\n        /// <summary>\n        /// Returns a <see cref=\"System.String\" /> that represents this instance.\n        /// </summary>\n        /// <returns>\n        /// A <see cref=\"System.String\" /> that represents this instance.\n        /// </returns>\n        public override string ToString()\n        {\n            StringBuilder builder = new StringBuilder();\n            builder.Append(\"IsValid: \");\n            builder.Append(IsValid);\n            builder.Append(\", AllowCredentials: \");\n            builder.Append(SupportsCredentials);\n            builder.Append(\", PreflightMaxAge: \");\n            builder.Append(PreflightMaxAge.HasValue ? PreflightMaxAge.Value.ToString(CultureInfo.InvariantCulture) : \"null\");\n            builder.Append(\", AllowOrigin: \");\n            builder.Append(AllowedOrigin);\n            builder.Append(\", AllowExposedHeaders: {\");\n            builder.Append(String.Join(\",\", AllowedExposedHeaders));\n            builder.Append(\"}\");\n            builder.Append(\", AllowHeaders: {\");\n            builder.Append(String.Join(\",\", AllowedHeaders));\n            builder.Append(\"}\");\n            builder.Append(\", AllowMethods: {\");\n            builder.Append(String.Join(\",\", AllowedMethods));\n            builder.Append(\"}\");\n            builder.Append(\", ErrorMessages: {\");\n            builder.Append(String.Join(\",\", ErrorMessages));\n            builder.Append(\"}\");\n            return builder.ToString();\n        }\n\n        private static void AddHeader(IDictionary<string, string> headers, string headerName, IEnumerable<string> headerValues)\n        {\n            string methods = String.Join(\",\", headerValues);\n            if (!String.IsNullOrEmpty(methods))\n            {\n                headers.Add(headerName, methods);\n            }\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Cors/ICorsEngine.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Cors\n{\n    /// <summary>\n    /// Provides an abstraction for evaluating CORS requests based on <see cref=\"CorsPolicy\"/>.\n    /// </summary>\n    public interface ICorsEngine\n    {\n        /// <summary>\n        /// Evaluates the policy.\n        /// </summary>\n        /// <param name=\"requestContext\">The <see cref=\"CorsRequestContext\"/>.</param>\n        /// <param name=\"policy\">The <see cref=\"CorsPolicy\"/>.</param>\n        /// <returns>The <see cref=\"CorsResult\"/></returns>\n        CorsResult EvaluatePolicy(CorsRequestContext requestContext, CorsPolicy policy);\n    }\n}"
  },
  {
    "path": "src/System.Web.Cors/Properties/AssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Reflection;\n\n[assembly: AssemblyTitle(\"System.Web.Cors\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA2210:AssembliesShouldHaveValidStrongNames\", Justification = \"This assembly is delay-signed.\")]"
  },
  {
    "path": "src/System.Web.Cors/Properties/SRResources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.18033\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace System.Web.Cors.Properties {\n    using System;\n    \n    \n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class SRResources {\n        \n        private static global::System.Resources.ResourceManager resourceMan;\n        \n        private static global::System.Globalization.CultureInfo resourceCulture;\n        \n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal SRResources() {\n        }\n        \n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"System.Web.Cors.Properties.SRResources\", typeof(SRResources).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n        \n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The collection of headers &apos;{0}&apos; is not allowed..\n        /// </summary>\n        internal static string HeadersNotAllowed {\n            get {\n                return ResourceManager.GetString(\"HeadersNotAllowed\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The method &apos;{0}&apos; is not allowed..\n        /// </summary>\n        internal static string MethodNotAllowed {\n            get {\n                return ResourceManager.GetString(\"MethodNotAllowed\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The request does not contain the Origin header..\n        /// </summary>\n        internal static string NoOriginHeader {\n            get {\n                return ResourceManager.GetString(\"NoOriginHeader\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The origin &apos;{0}&apos; is not allowed..\n        /// </summary>\n        internal static string OriginNotAllowed {\n            get {\n                return ResourceManager.GetString(\"OriginNotAllowed\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to PreflightMaxAge must be greater than or equal to 0..\n        /// </summary>\n        internal static string PreflightMaxAgeOutOfRange {\n            get {\n                return ResourceManager.GetString(\"PreflightMaxAgeOutOfRange\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Cors/Properties/SRResources.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"HeadersNotAllowed\" xml:space=\"preserve\">\n    <value>The collection of headers '{0}' is not allowed.</value>\n  </data>\n  <data name=\"MethodNotAllowed\" xml:space=\"preserve\">\n    <value>The method '{0}' is not allowed.</value>\n  </data>\n  <data name=\"NoOriginHeader\" xml:space=\"preserve\">\n    <value>The request does not contain the Origin header.</value>\n  </data>\n  <data name=\"OriginNotAllowed\" xml:space=\"preserve\">\n    <value>The origin '{0}' is not allowed.</value>\n  </data>\n  <data name=\"PreflightMaxAgeOutOfRange\" xml:space=\"preserve\">\n    <value>PreflightMaxAge must be greater than or equal to 0.</value>\n  </data>\n</root>"
  },
  {
    "path": "src/System.Web.Cors/System.Web.Cors.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{43C1B979-D593-4A32-BB3A-4316F1C66D66}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>System.Web.Cors</RootNamespace>\n    <AssemblyName>System.Web.Cors</AssemblyName>\n    <DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>\n    <RunCodeAnalysis>$(CodeAnalysis)</RunCodeAnalysis>\n    <CodeAnalysisRuleSet>..\\Strict.ruleset</CodeAnalysisRuleSet>\n    <DefineConstants>$(DefineConstants);ASPNETMVC</DefineConstants>\n  </PropertyGroup>\n  <PropertyGroup>\n    <SignAssembly>true</SignAssembly>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Xml.Linq\" />\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"System.Xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\CommonAssemblyInfo.cs\">\n      <Link>Properties\\CommonAssemblyInfo.cs</Link>\n    </Compile>\n    <Compile Include=\"CorsPolicy.cs\" />\n    <Compile Include=\"ICorsEngine.cs\" />\n    <Compile Include=\"CorsConstants.cs\" />\n    <Compile Include=\"CorsEngine.cs\" />\n    <Compile Include=\"CorsRequestContext.cs\" />\n    <Compile Include=\"CorsResult.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"Properties\\SRResources.Designer.cs\">\n      <DependentUpon>SRResources.resx</DependentUpon>\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n    </Compile>\n  </ItemGroup>\n  <ItemGroup>\n    <CodeAnalysisDictionary Include=\"..\\CodeAnalysisDictionary.xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"Properties\\SRResources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>SRResources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n</Project>"
  },
  {
    "path": "src/System.Web.Helpers/Chart/Chart.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.IO;\nusing System.Text;\nusing System.Web.Helpers.Resources;\nusing System.Web.Hosting;\nusing System.Web.UI.DataVisualization.Charting;\nusing System.Web.UI.WebControls;\nusing System.Web.WebPages;\nusing System.Xml;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Helpers\n{\n    // Post-Beta Work:\n    // -DataBind and Points.DataBind - need to find scenarios\n    // -Elements: Annotations, MapAreas\n    // -Interactivity / AJAX support?\n    public class Chart\n    {\n        private readonly int _height;\n        private readonly int _width;\n        private readonly string _themePath;\n        private readonly string _theme;\n\n        private readonly List<LegendData> _legends = new List<LegendData>();\n        private readonly List<SeriesData> _series = new List<SeriesData>();\n        private readonly List<TitleData> _titles = new List<TitleData>();\n\n        private HttpContextBase _httpContext;\n        private Func<VirtualPathProvider> _virtualPathProviderFunc;\n\n        private string _path;\n\n        private DataSourceData _dataSource;\n        [SuppressMessage(\"StyleCop.CSharp.NamingRules\", \"SA1305:FieldNamesMustNotUseHungarianNotation\", Target = \"_xAxis, _yAxis\",\n           Justification = \"These names make most sense.\")]\n        private ChartAxisData _xAxis, _yAxis;\n\n#if CODE_COVERAGE\n        [ExcludeFromCodeCoverage]\n#endif\n\n        /// <param name=\"width\">Chart width in pixels.</param>\n        /// <param name=\"height\">Chart height in pixels.</param>\n        /// <param name=\"theme\">String containing chart theme definition. Chart's theme defines properties like colors, positions, etc.\n        /// This parameter is primarily meant for one of the predefined Chart themes, however any valid chart theme is acceptable.</param>\n        /// <param name=\"themePath\">Path to a file containing definition of chart theme, default is none.</param>\n        /// <remarks>Both the theme and themePath parameters can be specified. In this case, the Chart class applies the theme xml first \n        /// followed by the content of file at themePath.\n        /// </remarks>\n        /// <example>\n        /// Chart(100, 100, theme: ChartTheme.Blue)\n        /// Chart(100, 100, theme: ChartTheme.Vanilla, themePath: \"my-theme.xml\")\n        /// Chart(100, 100, theme: \".... definition inline ....\" ) \n        /// Chart(100, 100, themePath: \"my-theme.xml\")\n        /// Any valid theme definition can be used as content of the file specified in themePath\n        /// </example>\n        public Chart(\n            int width,\n            int height,\n            string theme = null,\n            string themePath = null)\n            : this(GetDefaultContext(), () => HostingEnvironment.VirtualPathProvider, width, height, theme, themePath)\n        {\n        }\n\n        // Overload used only for testing\n        internal Chart(HttpContextBase httpContext, VirtualPathProvider virtualPathProvider, int width, int height,\n                       string theme = null, string themePath = null)\n            : this(httpContext, () => virtualPathProvider, width, height, theme, themePath)\n        {\n        }\n\n        internal Chart(HttpContextBase httpContext, Func<VirtualPathProvider> virtualPathProviderFunc,\n            int width, int height, string theme = null, string themePath = null)\n        {\n            Contract.Assert(httpContext != null);\n            Contract.Assert(virtualPathProviderFunc != null);\n\n            // HostingEnvironment.VirtualPathProvider never null in running host but may change at any time.\n            Contract.Assert(virtualPathProviderFunc() != null);\n\n            if (width < 0)\n            {\n                throw new ArgumentOutOfRangeException(\"width\", String.Format(\n                    CultureInfo.CurrentCulture,\n                    CommonResources.Argument_Must_Be_GreaterThanOrEqualTo,\n                    0));\n            }\n            if (height < 0)\n            {\n                throw new ArgumentOutOfRangeException(\"height\", String.Format(\n                    CultureInfo.CurrentCulture,\n                    CommonResources.Argument_Must_Be_GreaterThanOrEqualTo,\n                    0));\n            }\n\n            _httpContext = httpContext;\n            _virtualPathProviderFunc = virtualPathProviderFunc;\n            _width = width;\n            _height = height;\n            _theme = theme;\n\n            // path must be app-relative in case chart is rendered from handler in different directory\n            if (!String.IsNullOrEmpty(themePath))\n            {\n                _themePath = VirtualPathUtil.ResolvePath(TemplateStack.GetCurrentTemplate(httpContext), httpContext, themePath);\n                if (!virtualPathProviderFunc().FileExists(_themePath))\n                {\n                    throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, HelpersResources.Chart_ThemeFileNotFound, _themePath), \"themePath\");\n                }\n            }\n        }\n\n        public string FileName\n        {\n            get { return _path; }\n        }\n\n        public int Height\n        {\n            get { return _height; }\n        }\n\n        public int Width\n        {\n            get { return _width; }\n        }\n\n        /// <param name=\"title\">Legend title.</param>\n        /// <param name=\"name\">Legend name.</param>\n        public Chart AddLegend(\n            string title = null,\n            string name = null)\n        {\n            _legends.Add(new LegendData\n            {\n                Name = name,\n                Title = title\n            });\n            return this;\n        }\n\n        /// <param name=\"name\">Series name.</param>\n        /// <param name=\"chartType\">Chart type (see: SeriesChartType).</param>\n        /// <param name=\"chartArea\">Chart area where the series is displayed.</param>\n        /// <param name=\"axisLabel\">Axis label for the series.</param>\n        /// <param name=\"legend\">Legend for the series.</param>\n        /// <param name=\"markerStep\">Axis marker step.</param>\n        /// <param name=\"xValue\">X data source, if data-binding the series.</param>\n        /// <param name=\"xField\">Column for the X data points, if data-binding the series.</param>\n        /// <param name=\"yValues\">Y data source(s), if data-binding the series.</param>\n        /// <param name=\"yFields\">Column(s) for the Y data points, if data-binding the series.</param>\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"x\",\n            Justification = \"Name based on X-axis. Suppressed in source because this is a one-time occurrence\")]\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"y\",\n            Justification = \"Name based on Y-axis. Suppressed in source because this is a one-time occurrence\")]\n        [SuppressMessage(\"StyleCop.CSharp.NamingRules\", \"SA1305:FieldNamesMustNotUseHungarianNotation\", Target = \"xValue, xField, yValues, yFields\",\n            Justification = \"These names cannot be changed because this is a public method.\")]\n        public Chart AddSeries(\n            string name = null,\n            string chartType = \"Column\",\n            string chartArea = null,\n            string axisLabel = null,\n            string legend = null,\n            int markerStep = 1,\n            IEnumerable xValue = null,\n            string xField = null,\n            IEnumerable yValues = null,\n            string yFields = null)\n        {\n            if (String.IsNullOrEmpty(chartType))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"chartType\");\n            }\n\n            DataSourceData dataSource = null;\n            if (yValues != null)\n            {\n                dataSource = new DataSourceData\n                {\n                    XDataSource = xValue,\n                    XField = xField,\n                    DataSource = yValues,\n                    YFields = yFields\n                };\n            }\n\n            _series.Add(new SeriesData\n            {\n                Name = name,\n                ChartType = ConvertStringArgument<SeriesChartType>(\"chartType\", chartType),\n                ChartArea = chartArea,\n                AxisLabel = axisLabel,\n                Legend = legend,\n                MarkerStep = markerStep,\n                DataSource = dataSource\n            });\n            return this;\n        }\n\n        /// <param name=\"text\">Title text.</param>\n        /// <param name=\"name\">Title name.</param>\n        public Chart AddTitle(\n            string text = null,\n            string name = null)\n        {\n            _titles.Add(new TitleData\n            {\n                Name = name,\n                Text = text\n            });\n            return this;\n        }\n\n        /// <param name=\"title\">Title for X-axis</param>\n        /// <param name=\"min\">The minimum value on X-axis. Default 0</param>\n        /// <param name=\"max\">The maximum value on X-axis. Default NaN</param>\n        public Chart SetXAxis(\n            string title = \"\",\n            double min = 0,\n            double max = Double.NaN)\n        {\n            _xAxis = new ChartAxisData { Title = title, Minimum = min, Maximum = max };\n            return this;\n        }\n\n        /// <param name=\"title\">Title for Y-axis</param>\n        /// <param name=\"min\">The minimum value on Y-axis. Default 0</param>\n        /// <param name=\"max\">The maximum value on Y-axis. Default NaN</param>\n        public Chart SetYAxis(\n            string title = \"\",\n            double min = 0,\n            double max = Double.NaN)\n        {\n            _yAxis = new ChartAxisData { Title = title, Minimum = min, Maximum = max };\n            return this;\n        }\n\n        /// <summary>\n        /// Data-binds the chart by grouping values in a series.  The series will be created by the chart.\n        /// </summary>\n        /// <param name=\"dataSource\">Chart data source.</param>\n        /// <param name=\"groupByField\">Column which series should be grouped by.</param>\n        /// <param name=\"xField\">Column for the X data points.</param>\n        /// <param name=\"yFields\">Column(s) for the Y data points, separated by comma.</param>\n        /// <param name=\"otherFields\"></param>\n        /// <param name=\"pointSortOrder\">Sort order (see: PointSortOrder).</param>\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"x\",\n            Justification = \"Name based on X-axis. Suppressed in source because this is a one-time occurrence\")]\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"y\",\n            Justification = \"Name based on Y-axis. Suppressed in source because this is a one-time occurrence\")]\n        [SuppressMessage(\"StyleCop.CSharp.NamingRules\", \"SA1305:FieldNamesMustNotUseHungarianNotation\", Target = \"xField, yFields\",\n            Justification = \"These names cannot be changed because this is a public method.\")]\n        public Chart DataBindCrossTable(IEnumerable dataSource, string groupByField, string xField, string yFields,\n                                        string otherFields = null, string pointSortOrder = \"Ascending\")\n        {\n            if (dataSource == null)\n            {\n                throw new ArgumentNullException(\"dataSource\");\n            }\n            if (dataSource is string)\n            {\n                throw new ArgumentException(HelpersResources.Chart_ExceptionDataBindSeriesToString, \"dataSource\");\n            }\n            if (String.IsNullOrEmpty(groupByField))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"groupByField\");\n            }\n            if (String.IsNullOrEmpty(yFields))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"yFields\");\n            }\n\n            _dataSource = new DataSourceData\n            {\n                DataSource = dataSource,\n                GroupByField = groupByField,\n                XField = xField,\n                YFields = yFields,\n                OtherFields = otherFields,\n                PointSortOrder = ConvertStringArgument<PointSortOrder>(\"pointSortOrder\", pointSortOrder)\n            };\n            return this;\n        }\n\n        /// <summary>\n        /// Data-binds the chart using a data source, with multiple y values supported.  The series will be created by the chart.\n        /// </summary>\n        /// <param name=\"dataSource\">Chart data source.</param>\n        /// <param name=\"xField\">Column for the X data points.</param>\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"x\",\n            Justification = \"Name based on X-axis. Suppressed in source because this is a one-time occurrence\")]\n        [SuppressMessage(\"StyleCop.CSharp.NamingRules\", \"SA1305:FieldNamesMustNotUseHungarianNotation\", Target = \"xField\",\n            Justification = \"These names cannot be changed because this is a public method.\")]\n        public Chart DataBindTable(IEnumerable dataSource, string xField = null)\n        {\n            if (dataSource == null)\n            {\n                throw new ArgumentNullException(\"dataSource\");\n            }\n            if (dataSource is string)\n            {\n                throw new ArgumentException(HelpersResources.Chart_ExceptionDataBindSeriesToString, \"dataSource\");\n            }\n\n            _dataSource = new DataSourceData\n            {\n                DataBindTable = true,\n                DataSource = dataSource,\n                XField = xField\n            };\n            return this;\n        }\n\n        /// <summary>\n        /// Get the bytes for the chart image.\n        /// </summary>\n        /// <param name=\"format\">Image format (see: ChartImageFormat).</param>\n        public byte[] GetBytes(string format = \"jpeg\")\n        {\n            var imageFormat = ConvertStringToChartImageFormat(format);\n            using (MemoryStream stream = new MemoryStream())\n            {\n                ExecuteChartAction(c =>\n                {\n                    c.SaveImage(stream, imageFormat);\n                });\n                return stream.ToArray();\n            }\n        }\n\n#if CODE_COVERAGE\n        [ExcludeFromCodeCoverage]\n#endif\n\n        /// <summary>\n        /// Loads a chart from the cache. This can be used to render from an image handler.\n        /// </summary>\n        /// <param name=\"key\">Cache key.</param>\n        public static Chart GetFromCache(string key)\n        {\n            return GetFromCache(GetDefaultContext(), key);\n        }\n\n        /// <summary>\n        /// Saves the chart image to a file.\n        /// </summary>\n        /// <param name=\"path\">File path.</param>\n        /// <param name=\"format\">Chart image format (see: ChartImageFormat).</param>\n        public Chart Save(string path, string format = \"jpeg\")\n        {\n            return Save(GetDefaultContext(), path, format);\n        }\n\n        internal Chart Save(HttpContextBase httpContext, string path, string format)\n        {\n            if (String.IsNullOrEmpty(path))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"path\");\n            }\n            var imageFormat = ConvertStringToChartImageFormat(format);\n\n            _path = VirtualPathUtil.MapPath(httpContext, path);\n            ExecuteChartAction(c =>\n            {\n                c.RenderType = RenderType.ImageTag;\n                c.SaveImage(FileName, imageFormat);\n            });\n            return this;\n        }\n\n        /// <summary>\n        /// Saves the chart in cache.  This can be used to render from an image handler.\n        /// </summary>\n        /// <param name=\"key\">Cache key.  Uses new GUID by default.</param>\n        /// <param name=\"minutesToCache\">Number of minutes to save in cache.</param>\n        /// <param name=\"slidingExpiration\">Whether a sliding expiration policy is used.</param>\n        /// <returns>Cache key.</returns>\n        public string SaveToCache(string key = null, int minutesToCache = 20, bool slidingExpiration = true)\n        {\n            if (String.IsNullOrEmpty(key))\n            {\n                key = GetUniqueKey();\n            }\n\n            WebCache.Set(key, this, minutesToCache, slidingExpiration);\n            return key;\n        }\n\n        /// <summary>\n        /// Saves the chart to the specified template file.\n        /// </summary>\n        /// <param name=\"path\">XML template file path.</param>\n        public Chart SaveXml(string path)\n        {\n            return SaveXml(GetDefaultContext(), path);\n        }\n\n        /// <summary>\n        /// Saves the chart to the specified template file.\n        /// </summary>\n        /// <param name=\"httpContext\">The <see cref=\"HttpContextBase\"/>.</param>\n        /// <param name=\"path\">XML template file path.</param>\n        internal Chart SaveXml(HttpContextBase httpContext, string path)\n        {\n            if (String.IsNullOrEmpty(path))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"path\");\n            }\n\n            ExecuteChartAction(c =>\n            {\n                c.SaveXml(VirtualPathUtil.MapPath(httpContext, path));\n            });\n            return this;\n        }\n\n        public WebImage ToWebImage(string format = \"jpeg\")\n        {\n            return new WebImage(GetBytes(format));\n        }\n\n        /// <summary>\n        /// Writes the chart image to the response stream.  This can be used to render from an image handler.\n        /// </summary>\n        /// <param name=\"format\">Image format (see: ChartImageFormat).</param>\n        public Chart Write(string format = \"jpeg\")\n        {\n            var response = _httpContext.Response;\n            response.Charset = String.Empty;\n            response.ContentType = \"image/\" + NormalizeFormat(format);\n            response.BinaryWrite(GetBytes(format));\n            return this;\n        }\n\n#if CODE_COVERAGE\n        [ExcludeFromCodeCoverage]\n#endif\n\n        /// <summary>\n        /// Writes a chart stored in cache to the response stream.  This can be used to render from an image handler.\n        /// </summary>\n        /// <param name=\"key\">Cache key.</param>\n        /// <param name=\"format\">Image format (see: ChartImageFormat).</param>\n        public static Chart WriteFromCache(string key, string format = \"jpeg\")\n        {\n            return WriteFromCache(GetDefaultContext(), key, format);\n        }\n\n        // create and execute an action against the WebForm control in a limited scope since the control is disposable.\n        internal void ExecuteChartAction(Action<UI.DataVisualization.Charting.Chart> action)\n        {\n            using (UI.DataVisualization.Charting.Chart chart = new UI.DataVisualization.Charting.Chart())\n            {\n                chart.Width = new Unit(_width);\n                chart.Height = new Unit(_height);\n\n                ApplyChartArea(chart);\n                ApplyLegends(chart);\n                ApplySeries(chart);\n                ApplyTitles(chart);\n\n                DataBindChart(chart);\n\n                // load the template last so that it can be applied to all the chart elements\n                LoadThemes(chart);\n\n                action(chart);\n            }\n        }\n\n        private void LoadThemes(UI.DataVisualization.Charting.Chart chart)\n        {\n            if (!String.IsNullOrEmpty(_theme))\n            {\n                using (MemoryStream memoryStream = new MemoryStream())\n                {\n                    byte[] themeContent = Encoding.UTF8.GetBytes(_theme);\n                    memoryStream.Write(themeContent, 0, themeContent.Length);\n                    memoryStream.Seek(0, SeekOrigin.Begin);\n\n                    LoadChartThemeFromFile(chart, memoryStream);\n                }\n            }\n\n            if (!String.IsNullOrEmpty(_themePath))\n            {\n                using (Stream stream = _virtualPathProviderFunc().GetFile(_themePath).Open())\n                {\n                    LoadChartThemeFromFile(chart, stream);\n                }\n            }\n        }\n\n        private static void LoadChartThemeFromFile(UI.DataVisualization.Charting.Chart chart, Stream templateStream)\n        {\n            // workarounds for Chart templating bugs mentioned in:\n            // http://social.msdn.microsoft.com/Forums/en-US/MSWinWebChart/thread/b50d5b7e-30e2-4948-af7a-370d9be1268a\n            chart.Serializer.Content = SerializationContents.All;\n            chart.Serializer.SerializableContent = String.Empty; // deserialize all content\n            chart.Serializer.IsTemplateMode = true;\n            chart.Serializer.IsResetWhenLoading = false;\n            // loading serializer with stream to avoid bug with template file getting locked in VS\n\n            // The default xml reader used by the serializer does not ignore comments\n            // Using the IsUnknownAttributeIgnored fixes this, but then it would give no feedback to the user \n            // if member names do not match the spelling and casing of Chart properties. \n            XmlReader reader = XmlReader.Create(templateStream, new XmlReaderSettings { IgnoreComments = true });\n            chart.Serializer.Load(reader);\n        }\n\n        internal static Chart GetFromCache(HttpContextBase context, string key)\n        {\n            Contract.Assert(context != null);\n\n            if (String.IsNullOrEmpty(key))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"key\");\n            }\n\n            var chart = WebCache.Get(key) as Chart;\n            if (chart != null)\n            {\n                chart._httpContext = context;\n            }\n            return chart;\n        }\n\n        internal static Chart WriteFromCache(HttpContextBase context, string key, string format = \"jpeg\")\n        {\n            var chart = GetFromCache(context, key);\n            if (chart != null)\n            {\n                chart.Write(format);\n            }\n            return chart;\n        }\n\n        // Notes on ApplyXXX methods:\n        // Chart elements should be configured before they are added to the chart, otherwise there\n        // will be some rendering problems.\n        // We must catch all exceptions when configuring chart elements and dispose of them manually\n        // if they have not been added to the chart yet, otherwise FxCop will complain.\n\n        private void ApplyChartArea(UI.DataVisualization.Charting.Chart chart)\n        {\n            ChartArea chartArea = new ChartArea(\"Default\");\n            try\n            {\n                ApplyAxis(chartArea.AxisX, _xAxis);\n                ApplyAxis(chartArea.AxisY, _yAxis);\n                chart.ChartAreas.Add(chartArea);\n            }\n            catch\n            {\n                // This is to appease FxCop\n                chartArea.Dispose();\n                throw;\n            }\n        }\n\n        private static void ApplyAxis(Axis axis, ChartAxisData axisData)\n        {\n            if (axisData == null)\n            {\n                return;\n            }\n\n            if (!String.IsNullOrEmpty(axisData.Title))\n            {\n                axis.Title = axisData.Title;\n            }\n            axis.Minimum = axisData.Minimum;\n            axis.Maximum = axisData.Maximum;\n        }\n\n        private void ApplyLegends(UI.DataVisualization.Charting.Chart chart)\n        {\n            foreach (var legendData in _legends)\n            {\n                var legend = new Legend();\n                try\n                {\n                    legend.Name = legendData.Name ?? String.Empty;\n                    legend.Title = legendData.Title ?? String.Empty;\n                }\n                catch (Exception)\n                {\n                    // see notes above\n                    legend.Dispose();\n                    throw;\n                }\n                chart.Legends.Add(legend);\n            }\n        }\n\n        [SuppressMessage(\"StyleCop.CSharp.NamingRules\", \"SA1305:FieldNamesMustNotUseHungarianNotation\", Target = \"yValues, yValuesArray\",\n            Justification = \"These names make the most sense.\")]\n        private void ApplySeries(UI.DataVisualization.Charting.Chart chart)\n        {\n            foreach (var seriesData in _series)\n            {\n                var series = new Series();\n                try\n                {\n                    series.AxisLabel = seriesData.AxisLabel ?? String.Empty;\n                    series.ChartArea = seriesData.ChartArea ?? String.Empty;\n                    series.ChartType = seriesData.ChartType;\n                    series.Legend = seriesData.Legend ?? String.Empty;\n                    series.MarkerStep = seriesData.MarkerStep;\n                    series.Name = seriesData.Name ?? String.Empty;\n\n                    // data-bind the series (todo - support o.Points.DataBind())\n                    if (seriesData.DataSource != null)\n                    {\n                        if (String.IsNullOrEmpty(seriesData.DataSource.YFields))\n                        {\n                            var yValues = seriesData.DataSource.DataSource;\n                            var yValuesArray = yValues as IEnumerable[];\n                            if ((yValuesArray != null) && !(yValues is string[]))\n                            {\n                                series.Points.DataBindXY(seriesData.DataSource.XDataSource, yValuesArray);\n                            }\n                            else\n                            {\n                                series.Points.DataBindXY(seriesData.DataSource.XDataSource, yValues);\n                            }\n                        }\n                        else\n                        {\n                            series.Points.DataBindXY(seriesData.DataSource.XDataSource, seriesData.DataSource.XField,\n                                                     seriesData.DataSource.DataSource, seriesData.DataSource.YFields);\n                        }\n                    }\n                }\n                catch (Exception)\n                {\n                    // see notes above\n                    series.Dispose();\n                    throw;\n                }\n                chart.Series.Add(series);\n            }\n        }\n\n        private void ApplyTitles(UI.DataVisualization.Charting.Chart chart)\n        {\n            foreach (var titleData in _titles)\n            {\n                var title = new Title();\n                try\n                {\n                    title.Name = titleData.Name;\n                    title.Text = titleData.Text;\n                }\n                catch (Exception)\n                {\n                    // see notes above\n                    title.Dispose();\n                    throw;\n                }\n                chart.Titles.Add(title);\n            }\n        }\n\n        private static T ConvertStringArgument<T>(string paramName, string value)\n        {\n            object result;\n            if (!ConversionUtil.TryFromString(typeof(T), value, out result))\n            {\n                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture,\n                                                          HelpersResources.Chart_ArgumentConversionFailed, typeof(T).FullName), paramName);\n            }\n            return (T)result;\n        }\n\n        /// <summary>\n        /// Method to convert a string to a ChartImageFormat.\n        /// The chart image needs to be normalized to allow for alternate names such as 'jpg', 'xpng' etc \n        /// to be mapped to their appropriate ChartImageFormat.\n        /// </summary>\n        private static ChartImageFormat ConvertStringToChartImageFormat(string format)\n        {\n            object result;\n            format = NormalizeFormat(format);\n            if (!ConversionUtil.TryFromString(typeof(ChartImageFormat), format, out result))\n            {\n                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture,\n                                                          HelpersResources.Image_IncorrectImageFormat, format), \"format\");\n            }\n            return (ChartImageFormat)result;\n        }\n\n        private void DataBindChart(UI.DataVisualization.Charting.Chart chart)\n        {\n            // NOTE: WebForms chart will throw null refs if optional values are set to null\n            if (_dataSource != null)\n            {\n                if (!String.IsNullOrEmpty(_dataSource.GroupByField))\n                {\n                    chart.DataBindCrossTable(\n                        _dataSource.DataSource,\n                        _dataSource.GroupByField,\n                        _dataSource.XField ?? String.Empty,\n                        _dataSource.YFields,\n                        _dataSource.OtherFields ?? String.Empty,\n                        _dataSource.PointSortOrder);\n                }\n                else if (_dataSource.DataBindTable)\n                {\n                    chart.DataBindTable(\n                        _dataSource.DataSource,\n                        _dataSource.XField ?? String.Empty);\n                }\n                else\n                {\n                    Debug.Assert(false, \"Chart.DataBind was removed - should not reach here\");\n                    //chart.DataSource = _dataSource.DataSource;\n                    //chart.DataBind();\n                }\n            }\n        }\n\n#if CODE_COVERAGE\n        [ExcludeFromCodeCoverage]\n#endif\n\n        private static HttpContextBase GetDefaultContext()\n        {\n            return new HttpContextWrapper(HttpContext.Current);\n        }\n\n        // review: should GUIDs be used in a handler's querystring?\n        private static string GetUniqueKey()\n        {\n            return Guid.NewGuid().ToString();\n        }\n\n        private static string NormalizeFormat(string format)\n        {\n            if (String.IsNullOrEmpty(format))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"format\");\n            }\n            if (format.StartsWith(\"image/\", StringComparison.OrdinalIgnoreCase))\n            {\n                format = format.Substring(6);\n            }\n            return ConversionUtil.NormalizeImageFormat(format);\n        }\n\n        // data-binding can be done through Chart or individual Series\n        private class DataSourceData\n        {\n            public bool DataBindTable { get; set; }\n            public IEnumerable DataSource { get; set; }\n            public string GroupByField { get; set; }\n            public string OtherFields { get; set; }\n            public string XField { get; set; }\n            public string YFields { get; set; }\n            public PointSortOrder PointSortOrder { get; set; }\n\n            // optional XValue for Series.Points.DataBindXY only:\n            public IEnumerable XDataSource { get; set; }\n        }\n\n        private class LegendData\n        {\n            public string Name { get; set; }\n            public string Title { get; set; }\n        }\n\n        private class SeriesData\n        {\n            public string AxisLabel { get; set; }\n            public string ChartArea { get; set; }\n            public SeriesChartType ChartType { get; set; }\n            public string Legend { get; set; }\n            public int MarkerStep { get; set; }\n            public string Name { get; set; }\n            public DataSourceData DataSource { get; set; }\n        }\n\n        private class TitleData\n        {\n            public string Name { get; set; }\n            public string Text { get; set; }\n        }\n\n        private class ChartAxisData\n        {\n            public double Minimum { get; set; }\n            public double Maximum { get; set; }\n            public string Title { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Helpers/Chart/ChartTheme.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Helpers\n{\n    public static class ChartTheme\n    {\n        // Review: Need better names.\n\n        public const string Blue =\n            @\"<Chart BackColor=\"\"#D3DFF0\"\" BackGradientStyle=\"\"TopBottom\"\" BackSecondaryColor=\"\"White\"\" BorderColor=\"\"26, 59, 105\"\" BorderlineDashStyle=\"\"Solid\"\" BorderWidth=\"\"2\"\" Palette=\"\"BrightPastel\"\">\n    <ChartAreas>\n        <ChartArea Name=\"\"Default\"\" _Template_=\"\"All\"\" BackColor=\"\"64, 165, 191, 228\"\" BackGradientStyle=\"\"TopBottom\"\" BackSecondaryColor=\"\"White\"\" BorderColor=\"\"64, 64, 64, 64\"\" BorderDashStyle=\"\"Solid\"\" ShadowColor=\"\"Transparent\"\" /> \n    </ChartAreas>\n    <Legends>\n        <Legend _Template_=\"\"All\"\" BackColor=\"\"Transparent\"\" Font=\"\"Trebuchet MS, 8.25pt, style=Bold\"\" IsTextAutoFit=\"\"False\"\" /> \n    </Legends>\n    <BorderSkin SkinStyle=\"\"Emboss\"\" /> \n  </Chart>\";\n\n        public const string Green =\n            @\"<Chart BackColor=\"\"#C9DC87\"\" BackGradientStyle=\"\"TopBottom\"\" BorderColor=\"\"181, 64, 1\"\" BorderWidth=\"\"2\"\" BorderlineDashStyle=\"\"Solid\"\" Palette=\"\"BrightPastel\"\">\n  <ChartAreas>\n    <ChartArea Name=\"\"Default\"\" _Template_=\"\"All\"\" BackColor=\"\"Transparent\"\" BackSecondaryColor=\"\"White\"\" BorderColor=\"\"64, 64, 64, 64\"\" BorderDashStyle=\"\"Solid\"\" ShadowColor=\"\"Transparent\"\">\n      <AxisY LineColor=\"\"64, 64, 64, 64\"\">\n        <MajorGrid Interval=\"\"Auto\"\" LineColor=\"\"64, 64, 64, 64\"\" />\n        <LabelStyle Font=\"\"Trebuchet MS, 8.25pt, style=Bold\"\" />\n      </AxisY>\n      <AxisX LineColor=\"\"64, 64, 64, 64\"\">\n        <MajorGrid LineColor=\"\"64, 64, 64, 64\"\" />\n        <LabelStyle Font=\"\"Trebuchet MS, 8.25pt, style=Bold\"\" />\n      </AxisX>\n      <Area3DStyle Inclination=\"\"15\"\" IsClustered=\"\"False\"\" IsRightAngleAxes=\"\"False\"\" Perspective=\"\"10\"\" Rotation=\"\"10\"\" WallWidth=\"\"0\"\" />\n    </ChartArea>\n  </ChartAreas>\n  <Legends>\n    <Legend _Template_=\"\"All\"\" Alignment=\"\"Center\"\" BackColor=\"\"Transparent\"\" Docking=\"\"Bottom\"\" Font=\"\"Trebuchet MS, 8.25pt, style=Bold\"\" IsTextAutoFit =\"\"False\"\" LegendStyle=\"\"Row\"\">\n    </Legend>\n  </Legends>\n  <BorderSkin SkinStyle=\"\"Emboss\"\" />\n</Chart>\";\n\n        public const string Vanilla =\n            @\"<Chart Palette=\"\"SemiTransparent\"\" BorderColor=\"\"#000\"\" BorderWidth=\"\"2\"\" BorderlineDashStyle=\"\"Solid\"\">\n<ChartAreas>\n    <ChartArea _Template_=\"\"All\"\" Name=\"\"Default\"\">\n            <AxisX>\n                <MinorGrid Enabled=\"\"False\"\" />\n                <MajorGrid Enabled=\"\"False\"\" />\n            </AxisX>\n            <AxisY>\n                <MajorGrid Enabled=\"\"False\"\" />\n                <MinorGrid Enabled=\"\"False\"\" />\n            </AxisY>\n    </ChartArea>\n</ChartAreas>\n</Chart>\";\n\n        public const string Vanilla3D =\n            @\"<Chart BackColor=\"\"#555\"\" BackGradientStyle=\"\"TopBottom\"\" BorderColor=\"\"181, 64, 1\"\" BorderWidth=\"\"2\"\" BorderlineDashStyle=\"\"Solid\"\" Palette=\"\"SemiTransparent\"\" AntiAliasing=\"\"All\"\">\n    <ChartAreas>\n        <ChartArea Name=\"\"Default\"\" _Template_=\"\"All\"\" BackColor=\"\"Transparent\"\" BackSecondaryColor=\"\"White\"\" BorderColor=\"\"64, 64, 64, 64\"\" BorderDashStyle=\"\"Solid\"\" ShadowColor=\"\"Transparent\"\">\n            <Area3DStyle LightStyle=\"\"Simplistic\"\" Enable3D=\"\"True\"\" Inclination=\"\"30\"\" IsClustered=\"\"False\"\" IsRightAngleAxes=\"\"False\"\" Perspective=\"\"10\"\" Rotation=\"\"-30\"\" WallWidth=\"\"0\"\" />\n        </ChartArea>\n    </ChartAreas>\n</Chart>\";\n\n        public const string Yellow =\n            @\"<Chart BackColor=\"\"#FADA5E\"\" BackGradientStyle=\"\"TopBottom\"\" BorderColor=\"\"#B8860B\"\" BorderWidth=\"\"2\"\" BorderlineDashStyle=\"\"Solid\"\" Palette=\"\"EarthTones\"\">\n  <ChartAreas>\n    <ChartArea Name=\"\"Default\"\" _Template_=\"\"All\"\" BackColor=\"\"Transparent\"\" BackSecondaryColor=\"\"White\"\" BorderColor=\"\"64, 64, 64, 64\"\" BorderDashStyle=\"\"Solid\"\" ShadowColor=\"\"Transparent\"\">\n      <AxisY>\n        <LabelStyle Font=\"\"Trebuchet MS, 8.25pt, style=Bold\"\" />\n      </AxisY>\n      <AxisX LineColor=\"\"64, 64, 64, 64\"\">\n        <LabelStyle Font=\"\"Trebuchet MS, 8.25pt, style=Bold\"\" />\n      </AxisX>\n    </ChartArea>\n  </ChartAreas>\n  <Legends>\n    <Legend _Template_=\"\"All\"\" BackColor=\"\"Transparent\"\" Docking=\"\"Bottom\"\" Font=\"\"Trebuchet MS, 8.25pt, style=Bold\"\" LegendStyle=\"\"Row\"\">\n    </Legend>\n  </Legends>\n  <BorderSkin SkinStyle=\"\"Emboss\"\" />\n</Chart>\";\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Helpers/Common/VirtualPathUtil.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.IO;\nusing System.Web.Helpers.Resources;\nusing System.Web.WebPages;\n\nnamespace System.Web.Helpers\n{\n    internal static class VirtualPathUtil\n    {\n        /// <summary>\n        /// Resolves and maps a path (physical or virtual) to a physical path on the server. \n        /// </summary>\n        /// <param name=\"httpContext\">The <see cref=\"HttpContextBase\"/>.</param>\n        /// <param name=\"path\">Either a physical rooted path or a virtual path to be mapped.\n        /// Physical paths are returned without modifications. Virtual paths are resolved relative to the current executing page.\n        /// </param>\n        /// <remarks>Result of this call should not be shown to the user (e.g. in an exception message) since\n        /// it could be security sensitive. But we need to pass this result to the file APIs like File.WriteAllBytes\n        /// which will show it if exceptions are raised from them. Unfortunately VirtualPathProvider doesn't have\n        /// APIs for writing so we can't use that.</remarks>\n        public static string MapPath(HttpContextBase httpContext, string path)\n        {\n            Debug.Assert(!String.IsNullOrEmpty(path));\n\n            if (Path.IsPathRooted(path))\n            {\n                return path;\n            }\n\n            // There is no TryMapPath API so we have to catch HttpException if we want to\n            // throw ArgumentException instead.  \n            try\n            {\n                return httpContext.Request.MapPath(ResolvePath(TemplateStack.GetCurrentTemplate(httpContext), httpContext, path));\n            }\n            catch (HttpException)\n            {\n                throw new ArgumentException(\n                    String.Format(CultureInfo.InvariantCulture, HelpersResources.PathUtils_IncorrectPath, path), \"path\");\n            }\n        }\n\n        /// <summary>\n        /// Resolves path relative to the current executing page\n        /// </summary>\n        public static string ResolvePath(string virtualPath)\n        {\n            if (String.IsNullOrEmpty(virtualPath))\n            {\n                return virtualPath;\n            }\n\n            if (HttpContext.Current == null)\n            {\n                return virtualPath;\n            }\n            var httpContext = new HttpContextWrapper(HttpContext.Current);\n            return ResolvePath(TemplateStack.GetCurrentTemplate(httpContext), httpContext, virtualPath);\n        }\n\n        internal static string ResolvePath(ITemplateFile templateFile, HttpContextBase httpContext, string virtualPath)\n        {\n            Debug.Assert(!String.IsNullOrEmpty(virtualPath));\n            string basePath;\n            if (templateFile != null)\n            {\n                // If a page is available resolve paths relative to it.\n                basePath = templateFile.TemplateInfo.VirtualPath;\n            }\n            else\n            {\n                basePath = httpContext.Request.AppRelativeCurrentExecutionFilePath;\n            }\n            return VirtualPathUtility.Combine(basePath, virtualPath);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Helpers/ConversionUtil.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Drawing;\nusing System.Drawing.Imaging;\nusing System.Reflection;\n\nnamespace System.Web.Helpers\n{\n    internal static class ConversionUtil\n    {\n        private static MethodInfo _stringToEnumMethod;\n\n        internal static string ToString<T>(T obj)\n        {\n            Type type = typeof(T);\n            if (type.IsEnum)\n            {\n                return obj.ToString();\n            }\n            TypeConverter converter = TypeDescriptor.GetConverter(type);\n            if ((converter != null) && (converter.CanConvertTo(typeof(string))))\n            {\n                return converter.ConvertToInvariantString(obj);\n            }\n            return null;\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\",\n            Justification = \"TypeConverter throws System.Exception instead of a more specific one.\")]\n        internal static bool TryFromString(Type type, string value, out object result)\n        {\n            result = null;\n            if (type == typeof(string))\n            {\n                result = value;\n                return true;\n            }\n            if (type.IsEnum)\n            {\n                return TryFromStringToEnumHelper(type, value, out result);\n            }\n            if (type == typeof(Color))\n            {\n                Color color;\n                bool rval = TryFromStringToColor(value, out color);\n                result = color;\n                return rval;\n            }\n            // TypeConverter doesn't really have TryConvert APIs.  We should avoid TypeConverter.IsValid\n            // which performs a duplicate conversion, and just handle the general exception ourselves.\n            TypeConverter converter = TypeDescriptor.GetConverter(type);\n            if ((converter != null) && converter.CanConvertFrom(typeof(string)))\n            {\n                try\n                {\n                    result = converter.ConvertFromInvariantString(value);\n                    return true;\n                }\n                catch\n                {\n                    // Do nothing\n                }\n            }\n            return false;\n        }\n\n        internal static bool TryFromStringToEnum<T>(string value, out T result) where T : struct\n        {\n            return Enum.TryParse(value, ignoreCase: true, result: out result);\n        }\n\n        private static bool TryFromStringToEnumHelper(Type enumType, string value, out object result)\n        {\n            result = null;\n            if (_stringToEnumMethod == null)\n            {\n                _stringToEnumMethod = typeof(ConversionUtil).GetMethod(\"TryFromStringToEnum\",\n                                                                       BindingFlags.Static | BindingFlags.NonPublic);\n                Debug.Assert(_stringToEnumMethod != null);\n            }\n            var args = new object[] { value, null };\n            var rval = (bool)_stringToEnumMethod.MakeGenericMethod(enumType).Invoke(null, args);\n            result = args[1];\n            return rval;\n        }\n\n        internal static bool TryFromStringToFontFamily(string fontFamily, out FontFamily result)\n        {\n            result = null;\n            bool converted = false;\n            foreach (FontFamily fontFamilyTemp in FontFamily.Families)\n            {\n                if (fontFamily.Equals(fontFamilyTemp.Name, StringComparison.OrdinalIgnoreCase))\n                {\n                    result = fontFamilyTemp;\n                    converted = true;\n                    break;\n                }\n            }\n            return converted;\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\",\n            Justification = \"TypeConverter throws System.Exception instad of a more specific one.\")]\n        internal static bool TryFromStringToColor(string value, out Color result)\n        {\n            result = default(Color);\n\n            // Parse color specified as hex number\n            if (value.StartsWith(\"#\", StringComparison.OrdinalIgnoreCase))\n            {\n                // Only allow colors in form of #RRGGBB or #RGB\n                if ((value.Length != 7) && (value.Length != 4))\n                {\n                    return false;\n                }\n\n                // Expand short version\n                if (value.Length == 4)\n                {\n                    char[] newValue = new char[7];\n                    newValue[0] = '#';\n                    newValue[1] = newValue[2] = value[1];\n                    newValue[3] = newValue[4] = value[2];\n                    newValue[5] = newValue[6] = value[3];\n                    value = new string(newValue);\n                }\n            }\n\n            TypeConverter converter = TypeDescriptor.GetConverter(typeof(Color));\n            Debug.Assert((converter != null) && (converter.CanConvertFrom(typeof(string))));\n\n            // There are no TryConvert APIs on TypeConverter so we have to catch exception. \n            // In addition to that, invalid conversion just throws System.Exception with misleading message,\n            // instead of a more specific exception type. \n            try\n            {\n                result = (Color)converter.ConvertFromInvariantString(value);\n            }\n            catch (Exception)\n            {\n                return false;\n            }\n\n            return true;\n        }\n\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1308:NormalizeStringsToUppercase\",\n            Justification = \"Format names are used in Http headers and are usually specified in lower case\")]\n        internal static string NormalizeImageFormat(string value)\n        {\n            value = value.ToLowerInvariant();\n            switch (value)\n            {\n                case \"jpeg\":\n                case \"jpg\":\n                case \"pjpeg\":\n                    return \"jpeg\";\n\n                case \"png\":\n                case \"x-png\":\n                    return \"png\";\n\n                case \"icon\":\n                case \"ico\":\n                case \"x-icon\":\n                    return \"icon\";\n            }\n            return value;\n        }\n\n        internal static bool TryFromStringToImageFormat(string value, out ImageFormat result)\n        {\n            result = default(ImageFormat);\n\n            if (String.IsNullOrEmpty(value))\n            {\n                return false;\n            }\n            if (value.StartsWith(\"image/\", StringComparison.OrdinalIgnoreCase))\n            {\n                value = value.Substring(\"image/\".Length);\n            }\n            value = NormalizeImageFormat(value);\n\n            TypeConverter converter = TypeDescriptor.GetConverter(typeof(ImageFormat));\n            Debug.Assert((converter != null) && (converter.CanConvertFrom(typeof(string))));\n\n            try\n            {\n                result = (ImageFormat)converter.ConvertFromInvariantString(value);\n            }\n            catch (NotSupportedException)\n            {\n                return false;\n            }\n\n            return true;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Helpers/Crypto.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Runtime.CompilerServices;\nusing System.Security.Cryptography;\nusing System.Text;\nusing System.Web.Helpers.Resources;\n\nnamespace System.Web.Helpers\n{\n    public static class Crypto\n    {\n        private const int PBKDF2IterCount = 1000; // default for Rfc2898DeriveBytes\n        private const int PBKDF2SubkeyLength = 256 / 8; // 256 bits\n        private const int SaltSize = 128 / 8; // 128 bits\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1720:IdentifiersShouldNotContainTypeNames\", MessageId = \"byte\", Justification = \"It really is a byte length\")]\n        internal static byte[] GenerateSaltInternal(int byteLength = SaltSize)\n        {\n            byte[] buf = new byte[byteLength];\n            using (var rng = new RNGCryptoServiceProvider())\n            {\n                rng.GetBytes(buf);\n            }\n            return buf;\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1720:IdentifiersShouldNotContainTypeNames\", MessageId = \"byte\", Justification = \"It really is a byte length\")]\n        public static string GenerateSalt(int byteLength = SaltSize)\n        {\n            return Convert.ToBase64String(GenerateSaltInternal(byteLength));\n        }\n\n        public static string Hash(string input, string algorithm = \"sha256\")\n        {\n            if (input == null)\n            {\n                throw new ArgumentNullException(\"input\");\n            }\n\n            return Hash(Encoding.UTF8.GetBytes(input), algorithm);\n        }\n\n        public static string Hash(byte[] input, string algorithm = \"sha256\")\n        {\n            if (input == null)\n            {\n                throw new ArgumentNullException(\"input\");\n            }\n\n            using (HashAlgorithm alg = HashAlgorithm.Create(algorithm))\n            {\n                if (alg != null)\n                {\n                    byte[] hashData = alg.ComputeHash(input);\n                    return BinaryToHex(hashData);\n                }\n                else\n                {\n                    throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, HelpersResources.Crypto_NotSupportedHashAlg, algorithm));\n                }\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1709:IdentifiersShouldBeCasedCorrectly\", MessageId = \"SHA\", Justification = \"Consistent with the Framework, which uses SHA\")]\n        public static string SHA1(string input)\n        {\n            return Hash(input, \"sha1\");\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1709:IdentifiersShouldBeCasedCorrectly\", MessageId = \"SHA\", Justification = \"Consistent with the Framework, which uses SHA\")]\n        public static string SHA256(string input)\n        {\n            return Hash(input, \"sha256\");\n        }\n\n        /* =======================\n         * HASHED PASSWORD FORMATS\n         * =======================\n         * \n         * Version 0:\n         * PBKDF2 with HMAC-SHA1, 128-bit salt, 256-bit subkey, 1000 iterations.\n         * (See also: SDL crypto guidelines v5.1, Part III)\n         * Format: { 0x00, salt, subkey }\n         */\n\n        public static string HashPassword(string password)\n        {\n            if (password == null)\n            {\n                throw new ArgumentNullException(\"password\");\n            }\n\n            // Produce a version 0 (see comment above) password hash.\n            byte[] salt;\n            byte[] subkey;\n            using (var deriveBytes = new Rfc2898DeriveBytes(password, SaltSize, PBKDF2IterCount))\n            {\n                salt = deriveBytes.Salt;\n                subkey = deriveBytes.GetBytes(PBKDF2SubkeyLength);\n            }\n\n            byte[] outputBytes = new byte[1 + SaltSize + PBKDF2SubkeyLength];\n            Buffer.BlockCopy(salt, 0, outputBytes, 1, SaltSize);\n            Buffer.BlockCopy(subkey, 0, outputBytes, 1 + SaltSize, PBKDF2SubkeyLength);\n            return Convert.ToBase64String(outputBytes);\n        }\n\n        // hashedPassword must be of the format of HashWithPassword (salt + Hash(salt+input)\n        public static bool VerifyHashedPassword(string hashedPassword, string password)\n        {\n            if (hashedPassword == null)\n            {\n                throw new ArgumentNullException(\"hashedPassword\");\n            }\n            if (password == null)\n            {\n                throw new ArgumentNullException(\"password\");\n            }\n\n            byte[] hashedPasswordBytes = Convert.FromBase64String(hashedPassword);\n\n            // Verify a version 0 (see comment above) password hash.\n\n            if (hashedPasswordBytes.Length != (1 + SaltSize + PBKDF2SubkeyLength) || hashedPasswordBytes[0] != 0x00)\n            {\n                // Wrong length or version header.\n                return false;\n            }\n\n            byte[] salt = new byte[SaltSize];\n            Buffer.BlockCopy(hashedPasswordBytes, 1, salt, 0, SaltSize);\n            byte[] storedSubkey = new byte[PBKDF2SubkeyLength];\n            Buffer.BlockCopy(hashedPasswordBytes, 1 + SaltSize, storedSubkey, 0, PBKDF2SubkeyLength);\n\n            byte[] generatedSubkey;\n            using (var deriveBytes = new Rfc2898DeriveBytes(password, salt, PBKDF2IterCount))\n            {\n                generatedSubkey = deriveBytes.GetBytes(PBKDF2SubkeyLength);\n            }\n            return ByteArraysEqual(storedSubkey, generatedSubkey);\n        }\n\n        internal static string BinaryToHex(byte[] data)\n        {\n            char[] hex = new char[data.Length * 2];\n\n            for (int iter = 0; iter < data.Length; iter++)\n            {\n                byte hexChar = ((byte)(data[iter] >> 4));\n                hex[iter * 2] = (char)(hexChar > 9 ? hexChar + 0x37 : hexChar + 0x30);\n                hexChar = ((byte)(data[iter] & 0xF));\n                hex[(iter * 2) + 1] = (char)(hexChar > 9 ? hexChar + 0x37 : hexChar + 0x30);\n            }\n            return new string(hex);\n        }\n\n        // Compares two byte arrays for equality. The method is specifically written so that the loop is not optimized.\n        [MethodImpl(MethodImplOptions.NoOptimization)]\n        private static bool ByteArraysEqual(byte[] a, byte[] b)\n        {\n            if (ReferenceEquals(a, b))\n            {\n                return true;\n            }\n\n            if (a == null || b == null || a.Length != b.Length)\n            {\n                return false;\n            }\n\n            bool areSame = true;\n            for (int i = 0; i < a.Length; i++)\n            {\n                areSame &= (a[i] == b[i]);\n            }\n            return areSame;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Helpers/DynamicHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Dynamic;\nusing System.Linq.Expressions;\nusing System.Runtime.CompilerServices;\nusing Microsoft.CSharp.RuntimeBinder;\n\nnamespace Microsoft.Internal.Web.Utils\n{\n    /// <summary>\n    /// Helper to evaluate different method on dynamic objects\n    /// </summary>\n    internal static class DynamicHelper\n    {\n        // We must pass in \"object\" instead of \"dynamic\" for the target dynamic object because if we use dynamic, the compiler will\n        // convert the call to this helper into a dynamic expression, even though we don't need it to be.  Since this class is internal,\n        // it cannot be accessed from a dynamic expression and thus we get errors.\n\n        // Dev10 Bug 914027 - Changed the first parameter from dynamic to object, see comment at top for details\n        public static bool TryGetMemberValue(object obj, string memberName, out object result)\n        {\n            try\n            {\n                result = GetMemberValue(obj, memberName);\n                return true;\n            }\n            catch (RuntimeBinderException)\n            {\n            }\n            catch (RuntimeBinderInternalCompilerException)\n            {\n            }\n\n            // We catch the C# specific runtime binder exceptions since we're using the C# binder in this case\n            result = null;\n            return false;\n        }\n\n        // Dev10 Bug 914027 - Changed the first parameter from dynamic to object, see comment at top for details\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We want to swallow exceptions that happen during runtime binding\")]\n        public static bool TryGetMemberValue(object obj, GetMemberBinder binder, out object result)\n        {\n            try\n            {\n                // VB us an instance of GetBinderAdapter that does not implement FallbackGetMemeber. This causes lookup of property expressions on dynamic objects to fail.\n                // Since all types are private to the assembly, we assume that as long as they belong to CSharp runtime, it is the right one. \n                if (typeof(Binder).Assembly.Equals(binder.GetType().Assembly))\n                {\n                    // Only use the binder if its a C# binder.\n                    result = GetMemberValue(obj, binder);\n                }\n                else\n                {\n                    result = GetMemberValue(obj, binder.Name);\n                }\n                return true;\n            }\n            catch\n            {\n                result = null;\n                return false;\n            }\n        }\n\n        // Dev10 Bug 914027 - Changed the first parameter from dynamic to object, see comment at top for details\n        public static object GetMemberValue(object obj, string memberName)\n        {\n            var callSite = GetMemberAccessCallSite(memberName);\n            return callSite.Target(callSite, obj);\n        }\n\n        // Dev10 Bug 914027 - Changed the first parameter from dynamic to object, see comment at top for details\n        public static object GetMemberValue(object obj, GetMemberBinder binder)\n        {\n            var callSite = GetMemberAccessCallSite(binder);\n            return callSite.Target(callSite, obj);\n        }\n\n        // dynamic d = new object();\n        // object s = d.Name;\n        // The following code gets generated for this expression:\n        // callSite = CallSite<Func<CallSite, object, object>>.Create(Binder.GetMember(CSharpBinderFlags.None, \"Name\", typeof(Program), new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }));\n        // callSite.Target(callSite, d);\n        // typeof(Program) is the containing type of the dynamic operation.\n        // Dev10 Bug 914027 - Changed the callsite's target parameter from dynamic to object, see comment at top for details\n        public static CallSite<Func<CallSite, object, object>> GetMemberAccessCallSite(string memberName)\n        {\n            var binder = Binder.GetMember(CSharpBinderFlags.None, memberName, typeof(DynamicHelper), new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });\n            return GetMemberAccessCallSite(binder);\n        }\n\n        // Dev10 Bug 914027 - Changed the callsite's target parameter from dynamic to object, see comment at top for details\n        public static CallSite<Func<CallSite, object, object>> GetMemberAccessCallSite(CallSiteBinder binder)\n        {\n            return CallSite<Func<CallSite, object, object>>.Create(binder);\n        }\n\n        // Dev10 Bug 914027 - Changed the first parameter from dynamic to object, see comment at top for details\n        public static IEnumerable<string> GetMemberNames(object obj)\n        {\n            var provider = obj as IDynamicMetaObjectProvider;\n            Debug.Assert(provider != null, \"obj doesn't implement IDynamicMetaObjectProvider\");\n\n            Expression parameter = Expression.Parameter(typeof(object));\n            return provider.GetMetaObject(parameter).GetDynamicMemberNames();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Helpers/DynamicJavaScriptConverter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Dynamic;\nusing System.Web.Script.Serialization;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Helpers\n{\n    /// <summary>\n    /// Converter that knows how to get the member values from a dynamic object.\n    /// </summary>\n    internal class DynamicJavaScriptConverter : JavaScriptConverter\n    {\n        public override IEnumerable<Type> SupportedTypes\n        {\n            get\n            {\n                // REVIEW: For some reason the converters don't pick up interfaces\n                yield return typeof(IDynamicMetaObjectProvider);\n                yield return typeof(DynamicObject);\n            }\n        }\n\n        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)\n        {\n            throw new NotSupportedException();\n        }\n\n        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)\n        {\n            var values = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);\n            var memberNames = DynamicHelper.GetMemberNames(obj);\n\n            // This should never happen\n            Debug.Assert(memberNames != null);\n\n            // Get the value for each member in the dynamic object\n            foreach (string memberName in memberNames)\n            {\n                object value = DynamicHelper.GetMemberValue(obj, memberName);\n                var jsonValue = value as DynamicJsonArray;\n                if (jsonValue != null)\n                {\n                    value = (object[])jsonValue;\n                }\n                values[memberName] = value;\n            }\n\n            return values;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Helpers/DynamicJsonArray.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Dynamic;\nusing System.Linq;\n\nnamespace System.Web.Helpers\n{\n    [SuppressMessage(\"Microsoft.Naming\", \"CA1710:IdentifiersShouldHaveCorrectSuffix\", Justification = \"This class isn't meant to be used directly\")]\n    public class DynamicJsonArray : DynamicObject, IEnumerable<object>\n    {\n        private readonly object[] _arrayValues;\n\n        public DynamicJsonArray(object[] arrayValues)\n        {\n            Debug.Assert(arrayValues != null);\n            _arrayValues = arrayValues.Select(Json.WrapObject).ToArray();\n        }\n\n        public int Length\n        {\n            get { return _arrayValues.Length; }\n        }\n\n        public dynamic this[int index]\n        {\n            get { return _arrayValues[index]; }\n            set { _arrayValues[index] = Json.WrapObject(value); }\n        }\n\n        public override bool TryConvert(ConvertBinder binder, out object result)\n        {\n            if (_arrayValues.GetType().IsAssignableFrom(binder.Type))\n            {\n                result = _arrayValues;\n                return true;\n            }\n            return base.TryConvert(binder, out result);\n        }\n\n        public override bool TryGetMember(GetMemberBinder binder, out object result)\n        {\n            // Testing for members should never throw. This is important when dealing with\n            // services that return different json results. Testing for a member shouldn't throw,\n            // it should just return null (or undefined)\n            result = null;\n            return true;\n        }\n\n        public IEnumerator GetEnumerator()\n        {\n            return _arrayValues.GetEnumerator();\n        }\n\n        private IEnumerable<object> GetEnumerable()\n        {\n            return _arrayValues.AsEnumerable();\n        }\n\n        IEnumerator<object> IEnumerable<object>.GetEnumerator()\n        {\n            return GetEnumerable().GetEnumerator();\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2225:OperatorOverloadsHaveNamedAlternates\", Justification = \"This class isn't meant to be used directly\")]\n        public static implicit operator object[](DynamicJsonArray obj)\n        {\n            return obj._arrayValues;\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2225:OperatorOverloadsHaveNamedAlternates\", Justification = \"This class isn't meant to be used directly\")]\n        public static implicit operator Array(DynamicJsonArray obj)\n        {\n            return obj._arrayValues;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Helpers/DynamicJsonObject.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Dynamic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Web.Helpers.Resources;\n\nnamespace System.Web.Helpers\n{\n    // REVIEW: Consider implementing ICustomTypeDescriptor and IDictionary<string, object>\n    public class DynamicJsonObject : DynamicObject\n    {\n        private readonly IDictionary<string, object> _values;\n\n        public DynamicJsonObject(IDictionary<string, object> values)\n        {\n            Debug.Assert(values != null);\n            _values = values.ToDictionary(p => p.Key, p => Json.WrapObject(p.Value),\n                                          StringComparer.OrdinalIgnoreCase);\n        }\n\n        public override bool TryConvert(ConvertBinder binder, out object result)\n        {\n            result = null;\n            if (binder.Type.IsAssignableFrom(_values.GetType()))\n            {\n                result = _values;\n            }\n            else\n            {\n                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, HelpersResources.Json_UnableToConvertType, binder.Type));\n            }\n            return true;\n        }\n\n        public override bool TryGetMember(GetMemberBinder binder, out object result)\n        {\n            result = GetValue(binder.Name);\n            return true;\n        }\n\n        public override bool TrySetMember(SetMemberBinder binder, object value)\n        {\n            _values[binder.Name] = Json.WrapObject(value);\n            return true;\n        }\n\n        public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)\n        {\n            string key = GetKey(indexes);\n            if (!String.IsNullOrEmpty(key))\n            {\n                _values[key] = Json.WrapObject(value);\n            }\n            return true;\n        }\n\n        public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)\n        {\n            string key = GetKey(indexes);\n            result = null;\n            if (!String.IsNullOrEmpty(key))\n            {\n                result = GetValue(key);\n            }\n            return true;\n        }\n\n        private static string GetKey(object[] indexes)\n        {\n            if (indexes.Length == 1)\n            {\n                return (string)indexes[0];\n            }\n            // REVIEW: Should this throw?\n            return null;\n        }\n\n        public override IEnumerable<string> GetDynamicMemberNames()\n        {\n            return _values.Keys;\n        }\n\n        private object GetValue(string name)\n        {\n            object result;\n            if (_values.TryGetValue(name, out result))\n            {\n                return result;\n            }\n            return null;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Helpers/GlobalSuppressions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n// This file is used by Code Analysis to maintain SuppressMessage \n// attributes that are applied to this project.\n// Project-level suppressions either have no target or are given \n// a specific target and scoped to a namespace, type, member, etc.\n//\n// To add a suppression to this file, right-click the message in the \n// Error List, point to \"Suppress Message(s)\", and click \n// \"In Project Suppression File\".\n// You do not need to add suppressions to this file manually.\n\nusing System.Diagnostics.CodeAnalysis;\n\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1703:ResourceStringsShouldBeSpelledCorrectly\", MessageId = \"sha\", Scope = \"resource\", Target = \"System.Web.Helpers.Resources.HelpersResources.resources\", Justification = \"sha is the algorithm\")]\n"
  },
  {
    "path": "src/System.Web.Helpers/HtmlElement.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.IO;\nusing System.Web.UI;\n\nnamespace System.Web.Helpers\n{\n    internal class HtmlElement\n    {\n        public HtmlElement(string tagName)\n        {\n            TagName = tagName;\n            Attributes = new Dictionary<string, string>();\n            Children = new List<HtmlElement>();\n        }\n\n        internal string TagName { get; set; }\n\n        internal string InnerText { get; set; }\n\n        public IList<HtmlElement> Children { get; set; }\n\n        private IDictionary<string, string> Attributes { get; set; }\n\n        public string this[string name]\n        {\n            get { return Attributes[name]; }\n            set { MergeAttribute(name, value); }\n        }\n\n        public HtmlElement SetInnerText(string innerText)\n        {\n            InnerText = innerText;\n            Children.Clear();\n            return this;\n        }\n\n        public HtmlElement AppendChild(HtmlElement e)\n        {\n            Children.Add(e);\n            return this;\n        }\n\n        public HtmlElement AppendChild(string innerText)\n        {\n            AppendChild(CreateSpan(innerText));\n            return this;\n        }\n\n        private void MergeAttribute(string name, string value)\n        {\n            Attributes[name] = value;\n        }\n\n        public HtmlElement AddCssClass(string className)\n        {\n            string currentValue;\n            if (!Attributes.TryGetValue(\"class\", out currentValue))\n            {\n                Attributes[\"class\"] = className;\n            }\n            else\n            {\n                Attributes[\"class\"] = currentValue + \" \" + className;\n            }\n            return this;\n        }\n\n        public IHtmlString ToHtmlString()\n        {\n            using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture))\n            {\n                WriteTo(sw);\n                return new HtmlString(sw.ToString());\n            }\n        }\n\n        public void WriteTo(TextWriter writer)\n        {\n            WriteToInternal(new HtmlTextWriter(writer));\n        }\n\n        private void WriteToInternal(HtmlTextWriter writer)\n        {\n            foreach (var a in Attributes)\n            {\n                writer.AddAttribute(a.Key, a.Value, true);\n            }\n            writer.RenderBeginTag(TagName);\n            if (!String.IsNullOrEmpty(InnerText))\n            {\n                writer.WriteEncodedText(InnerText);\n            }\n            else\n            {\n                foreach (var e in Children)\n                {\n                    e.WriteToInternal(writer);\n                }\n            }\n            writer.RenderEndTag();\n        }\n\n        public override string ToString()\n        {\n            return ToHtmlString().ToString();\n        }\n\n        internal static HtmlElement CreateSpan(string innerText, string cssClass = null)\n        {\n            var span = new HtmlElement(\"span\");\n            span.SetInnerText(innerText);\n            if (!String.IsNullOrEmpty(cssClass))\n            {\n                span.AddCssClass(cssClass);\n            }\n            return span;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Helpers/HtmlObjectPrinter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Web.Helpers.Resources;\n\nnamespace System.Web.Helpers\n{\n    internal class HtmlObjectPrinter : ObjectVisitor\n    {\n        private const string Styles =\n            @\"<style type=\"\"text/css\"\">       \n    .objectinfo { font-size: 13px; }\n    .objectinfo .type { color: #0000ff; }\n    .objectinfo .complexType { color: #2b91af; }\n    .objectinfo .name { color: Black; }\n    .objectinfo .value { color: Black; }\n    .objectinfo .quote { color: Brown; }\n    .objectinfo .null { color: Red; }\n    .objectinfo .exception { color:Red; }\n    .objectinfo .typeContainer { border-left: solid 2px #7C888A; padding-left: 3px; margin-left:3px; }\n    .objectinfo h3, h2 { margin:0; padding:0; }\n    .objectinfo ul { margin-top:0; margin-bottom:0; list-style-type:none; padding-left:10px; margin-left:10px; }\n</style>\n\";\n\n        private static readonly HtmlElement _nullSpan = HtmlElement.CreateSpan(\"(null)\", \"null\");\n        // List of chars to escape within strings\n        private static readonly Dictionary<char, string> _printableEscapeChars = new Dictionary<char, string>\n        {\n            { '\\0', \"\\\\0\" },\n            { '\\\\', \"\\\\\\\\\" },\n            { '\\'', \"'\" },\n            { '\\\"', \"\\\\\\\"\" },\n            { '\\a', \"\\\\a\" },\n            { '\\b', \"\\\\b\" },\n            { '\\f', \"\\\\f\" },\n            { '\\n', \"\\\\n\" },\n            { '\\r', \"\\\\r\" },\n            { '\\t', \"\\\\t\" },\n            { '\\v', \"\\\\v\" },\n        };\n\n        // We want to exclude the type name next to the value for members\n        private bool _excludeTypeName;\n        private Stack<HtmlElement> _elementStack = new Stack<HtmlElement>();\n\n        public HtmlObjectPrinter(int recursionLimit, int enumerationLimit)\n            : base(recursionLimit, enumerationLimit)\n        {\n        }\n\n        private HtmlElement Current\n        {\n            get\n            {\n                Debug.Assert(_elementStack.Count > 0);\n                return _elementStack.Peek();\n            }\n        }\n\n        public void WriteTo(object value, TextWriter writer)\n        {\n            HtmlElement rootElement = new HtmlElement(\"div\");\n            rootElement.AddCssClass(\"objectinfo\");\n\n            PushElement(rootElement);\n            Visit(value, 0);\n            PopElement();\n\n            Debug.Assert(_elementStack.Count == 0, \"Stack should be empty\");\n\n            // REVIEW: We should only do this once per page/request\n            writer.Write(Styles);\n            rootElement.WriteTo(writer);\n        }\n\n        public override void VisitKeyValues(object value, IEnumerable<object> keys, Func<object, object> valueSelector, int depth)\n        {\n            string id = GetObjectId(value);\n            HtmlElement ul = new HtmlElement(\"ul\");\n            ul.AddCssClass(\"typeEnumeration\");\n            ul[\"id\"] = id;\n\n            PushElement(ul);\n            base.VisitKeyValues(value, keys, valueSelector, depth);\n            PopElement();\n\n            Current.AppendChild(ul);\n        }\n\n        public override void VisitKeyValue(object key, object value, int depth)\n        {\n            HtmlElement keyElement = new HtmlElement(\"span\");\n            PushElement(keyElement);\n            Visit(key, depth);\n            PopElement();\n\n            HtmlElement valueElement = new HtmlElement(\"span\");\n            PushElement(valueElement);\n            Visit(value, depth);\n            PopElement();\n\n            // Append the elements to the li\n            HtmlElement li = new HtmlElement(\"li\");\n            li.AppendChild(keyElement);\n            li.AppendChild(\" = \");\n            li.AppendChild(valueElement);\n            Current.AppendChild(li);\n        }\n\n        public override void VisitEnumerable(IEnumerable enumerable, int depth)\n        {\n            string id = GetObjectId(enumerable);\n\n            HtmlElement ul = new HtmlElement(\"ul\");\n            ul.AddCssClass(\"typeEnumeration\");\n            ul[\"id\"] = id;\n\n            PushElement(ul);\n            base.VisitEnumerable(enumerable, depth);\n            PopElement();\n\n            Current.AppendChild(ul);\n        }\n\n        public override void VisitIndexedEnumeratedValue(int index, object item, int depth)\n        {\n            HtmlElement li = new HtmlElement(\"li\");\n            li.AppendChild(String.Format(CultureInfo.InvariantCulture, \"[{0}] = \", index));\n            PushElement(li);\n            base.VisitIndexedEnumeratedValue(index, item, depth);\n            PopElement();\n            Current.AppendChild(li);\n        }\n\n        public override void VisitEnumeratedValue(object item, int depth)\n        {\n            HtmlElement li = new HtmlElement(\"li\");\n            PushElement(li);\n            base.VisitEnumeratedValue(item, depth);\n            PopElement();\n            Current.AppendChild(li);\n        }\n\n        public override void VisitEnumeratonLimitExceeded()\n        {\n            HtmlElement li = new HtmlElement(\"li\");\n            li.AppendChild(\"...\");\n            Current.AppendChild(li);\n        }\n\n        public override void VisitMembers(IEnumerable<string> names, Func<string, Type> typeSelector, Func<string, object> valueSelector, int depth)\n        {\n            HtmlElement ul = new HtmlElement(\"ul\");\n            ul.AddCssClass(\"typeProperties\");\n\n            PushElement(ul);\n            base.VisitMembers(names, typeSelector, valueSelector, depth);\n            PopElement();\n\n            Current.AppendChild(ul);\n        }\n\n        public override void VisitMember(string name, Type type, object value, int depth)\n        {\n            HtmlElement li = new HtmlElement(\"li\");\n\n            if (type != null)\n            {\n                li.AppendChild(CreateTypeNameSpan(type));\n                li.AppendChild(\" \");\n            }\n\n            li.AppendChild(CreateNameSpan(name));\n            li.AppendChild(\" = \");\n\n            PushElement(li);\n\n            _excludeTypeName = true;\n            base.VisitMember(name, type, value, depth);\n            _excludeTypeName = false;\n\n            PopElement();\n\n            Current.AppendChild(li);\n        }\n\n        public override void VisitComplexObject(object value, int depth)\n        {\n            string id = GetObjectId(value);\n\n            HtmlElement objectElement = new HtmlElement(\"div\");\n            objectElement.AddCssClass(\"typeContainer\");\n            objectElement[\"id\"] = id;\n\n            PushElement(objectElement);\n            base.VisitComplexObject(value, depth);\n            PopElement();\n\n            if (objectElement.Children.Any())\n            {\n                Current.AppendChild(objectElement);\n            }\n        }\n\n        public override void VisitNull()\n        {\n            Current.AppendChild(_nullSpan);\n        }\n\n        public override void VisitStringValue(string stringValue)\n        {\n            // Convert the string escape sequences\n            stringValue = \"\\\"\" + ConvertEscapseSequences(stringValue) + \"\\\"\";\n            Current.AppendChild(CreateQuotedSpan(stringValue));\n        }\n\n        public override void VisitVisitedObject(string id, object value)\n        {\n            Current.AppendChild(CreateVisitedLink(id));\n        }\n\n        public override void Visit(object value, int depth)\n        {\n            if (value != null)\n            {\n                if (!_excludeTypeName)\n                {\n                    Current.AppendChild(CreateTypeNameSpan(value.GetType()));\n                    Current.AppendChild(\" \");\n                }\n                _excludeTypeName = false;\n            }\n\n            base.Visit(value, depth);\n        }\n\n        public override void VisitObjectVisitorException(ObjectVisitorException exception)\n        {\n            Current.AppendChild(CreateExceptionSpan(exception));\n        }\n\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1308:NormalizeStringsToUppercase\", Justification = \"Making the value lowercase has nothing to do with normalization. It's used to show true or false instead of the Title case version\")]\n        public override void VisitConvertedValue(object value, string convertedValue)\n        {\n            Type type = value.GetType();\n            if (type.Equals(typeof(bool)))\n            {\n                // Convert True or False to lowercase\n                convertedValue = convertedValue.ToLowerInvariant();\n                Current.AppendChild(CreateTypeSpan(convertedValue));\n                return;\n            }\n\n            if (type.Equals(typeof(char)))\n            {\n                string charValue = GetCharValue((char)value);\n                Current.AppendChild(CreateQuotedSpan(\"'\" + charValue + \"'\"));\n                return;\n            }\n\n            // See if the value is a Type itself\n            Type valueAsType = value as Type;\n            if (valueAsType != null)\n            {\n                // For types we're going to generate elements that print typeof(TypeName)\n                Current.AppendChild(CreateParentSpan(CreateTypeSpan(\"typeof\"),\n                                                     CreateOperatorSpan(\"(\"),\n                                                     CreateTypeNameSpan(valueAsType),\n                                                     CreateOperatorSpan(\")\")));\n            }\n            else\n            {\n                Current.AppendChild(CreateValueSpan(convertedValue));\n            }\n        }\n\n        private static HtmlElement CreateParentSpan(params HtmlElement[] elements)\n        {\n            HtmlElement span = new HtmlElement(\"span\");\n            foreach (var e in elements)\n            {\n                span.AppendChild(e);\n            }\n            return span;\n        }\n\n        private static HtmlElement CreateNameSpan(string name)\n        {\n            return HtmlElement.CreateSpan(name, \"name\");\n        }\n\n        private static HtmlElement CreateOperatorSpan(string @operator)\n        {\n            return HtmlElement.CreateSpan(@operator, \"operator\");\n        }\n\n        private static HtmlElement CreateValueSpan(string value)\n        {\n            return HtmlElement.CreateSpan(value, \"value\");\n        }\n\n        private static HtmlElement CreateExceptionSpan(ObjectVisitorException exception)\n        {\n            HtmlElement span = new HtmlElement(\"span\");\n            span.AppendChild(HelpersResources.ObjectInfo_PropertyThrewException);\n            span.AppendChild(HtmlElement.CreateSpan(exception.InnerException.Message, \"exception\"));\n            return span;\n        }\n\n        private static HtmlElement CreateQuotedSpan(string value)\n        {\n            return HtmlElement.CreateSpan(value, \"quote\");\n        }\n\n        private static HtmlElement CreateLink(string href, string linkText, string cssClass = null)\n        {\n            HtmlElement a = new HtmlElement(\"a\");\n            a.SetInnerText(linkText);\n            a[\"href\"] = href;\n            if (!String.IsNullOrEmpty(cssClass))\n            {\n                a.AddCssClass(cssClass);\n            }\n            return a;\n        }\n\n        private static HtmlElement CreateVisitedLink(string id)\n        {\n            string text = String.Format(CultureInfo.InvariantCulture, \"[{0}]\", HelpersResources.ObjectInfo_PreviousDisplayed);\n            return CreateLink(\"#\" + id, text);\n        }\n\n        private static HtmlElement CreateTypeSpan(string value)\n        {\n            return HtmlElement.CreateSpan(value, \"type\");\n        }\n\n        private static HtmlElement CreateTypeNameSpan(Type type)\n        {\n            string typeName = GetTypeName(type);\n            HtmlElement span = new HtmlElement(\"span\");\n            StringBuilder sb = new StringBuilder();\n            // Convert the type name into html elements with different css classes\n            foreach (var ch in typeName)\n            {\n                if (IsOperator(ch))\n                {\n                    if (sb.Length > 0)\n                    {\n                        span.AppendChild(CreateTypeSpan(sb.ToString()));\n                        sb.Clear();\n                    }\n                    span.AppendChild(CreateOperatorSpan(ch.ToString()));\n                }\n                else\n                {\n                    sb.Append(ch);\n                }\n            }\n            if (sb.Length > 0)\n            {\n                span.AppendChild(CreateTypeSpan(sb.ToString()));\n            }\n            return span;\n        }\n\n        private static bool IsOperator(char ch)\n        {\n            // These are the operators we expect to see within type names\n            return ch == '[' || ch == ']' || ch == '<' || ch == '>' || ch == '&' || ch == '*';\n        }\n\n        internal void PushElement(HtmlElement element)\n        {\n            _elementStack.Push(element);\n        }\n\n        internal HtmlElement PopElement()\n        {\n            Debug.Assert(_elementStack.Count > 0);\n            return _elementStack.Pop();\n        }\n\n        internal static string ConvertEscapseSequences(string value)\n        {\n            StringBuilder sb = new StringBuilder();\n            foreach (var ch in value)\n            {\n                sb.Append(GetCharValue(ch));\n            }\n            return sb.ToString();\n        }\n\n        private static string GetCharValue(char ch)\n        {\n            string value;\n            if (_printableEscapeChars.TryGetValue(ch, out value))\n            {\n                return value;\n            }\n            // REVIEW: Perf?\n            return ch.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Helpers/Json.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Web.Script.Serialization;\n\nnamespace System.Web.Helpers\n{\n    public static class Json\n    {\n        private static readonly JavaScriptSerializer _serializer = CreateSerializer();\n\n        public static string Encode(object value)\n        {\n            // Serialize our dynamic array type as an array\n            DynamicJsonArray jsonArray = value as DynamicJsonArray;\n            if (jsonArray != null)\n            {\n                return _serializer.Serialize((object[])jsonArray);\n            }\n\n            return _serializer.Serialize(value);\n        }\n\n        public static void Write(object value, TextWriter writer)\n        {\n            writer.Write(_serializer.Serialize(value));\n        }\n\n        public static dynamic Decode(string value)\n        {\n            return WrapObject(_serializer.DeserializeObject(value));\n        }\n\n        public static dynamic Decode(string value, Type targetType)\n        {\n            return WrapObject(_serializer.Deserialize(value, targetType));\n        }\n\n        public static T Decode<T>(string value)\n        {\n            return _serializer.Deserialize<T>(value);\n        }\n\n        private static JavaScriptSerializer CreateSerializer()\n        {\n            JavaScriptSerializer serializer = new JavaScriptSerializer();\n            serializer.RegisterConverters(new[] { new DynamicJavaScriptConverter() });\n            return serializer;\n        }\n\n        internal static dynamic WrapObject(object value)\n        {\n            // The JavaScriptSerializer returns IDictionary<string, object> for objects\n            // and object[] for arrays, so we wrap those in different dynamic objects\n            // so we can access the object graph using dynamic\n            var dictionaryValues = value as IDictionary<string, object>;\n            if (dictionaryValues != null)\n            {\n                return new DynamicJsonObject(dictionaryValues);\n            }\n\n            var arrayValues = value as object[];\n            if (arrayValues != null)\n            {\n                return new DynamicJsonArray(arrayValues);\n            }\n\n            return value;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Helpers/ObjectInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Web.WebPages;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Helpers\n{\n    public static class ObjectInfo\n    {\n        private const int DefaultRecursionLimit = 10;\n        private const int DefaultEnumerationLimit = 1000;\n\n        public static HelperResult Print(object value, int depth = DefaultRecursionLimit, int enumerationLength = DefaultEnumerationLimit)\n        {\n            if (depth < 0)\n            {\n                throw new ArgumentOutOfRangeException(\n                    \"depth\",\n                    String.Format(CultureInfo.InvariantCulture, CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, 0));\n            }\n            if (enumerationLength <= 0)\n            {\n                throw new ArgumentOutOfRangeException(\n                    \"enumerationLength\",\n                    String.Format(CultureInfo.InvariantCulture, CommonResources.Argument_Must_Be_GreaterThan, 0));\n            }\n\n            HtmlObjectPrinter printer = new HtmlObjectPrinter(depth, enumerationLength);\n            return new HelperResult(writer => printer.WriteTo(value, writer));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Helpers/ObjectVisitor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Dynamic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.Serialization;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Helpers\n{\n    internal class ObjectVisitor\n    {\n        private static readonly Dictionary<Type, string> _typeNames = new Dictionary<Type, string>\n        {\n            { typeof(string), \"string\" },\n            { typeof(object), \"object\" },\n            { typeof(int), \"int\" },\n            { typeof(byte), \"byte\" },\n            { typeof(short), \"short\" },\n            { typeof(long), \"long\" },\n            { typeof(decimal), \"decimal\" },\n            { typeof(float), \"float\" },\n            { typeof(double), \"double\" },\n            { typeof(bool), \"bool\" },\n            { typeof(char), \"char\" },\n            { typeof(void), \"void\" }\n        };\n\n        private static readonly char[] _separators = { '&', '[', '*' };\n\n        private readonly int _recursionLimit;\n        private readonly int _enumerationLimit;\n        private Dictionary<object, string> _visited = new Dictionary<object, string>();\n\n        public ObjectVisitor(int recursionLimit, int enumerationLimit)\n        {\n            Debug.Assert(enumerationLimit > 0);\n            Debug.Assert(recursionLimit >= 0);\n            _enumerationLimit = enumerationLimit;\n            _recursionLimit = recursionLimit;\n        }\n\n        protected string GetObjectId(object value)\n        {\n            string id;\n            if (_visited.TryGetValue(value, out id))\n            {\n                return id;\n            }\n            return null;\n        }\n\n        public virtual void Visit(object value, int depth)\n        {\n            if (value == null || DBNull.Value.Equals(value))\n            {\n                VisitNull();\n                return;\n            }\n\n            // Check to see if the we've already visited this object\n            string id;\n            if (_visited.TryGetValue(value, out id))\n            {\n                VisitVisitedObject(id, value);\n                return;\n            }\n\n            string stringValue = value as string;\n            if (stringValue != null)\n            {\n                VisitStringValue(stringValue);\n                return;\n            }\n\n            if (TryConvertToString(value, out stringValue))\n            {\n                VisitConvertedValue(value, stringValue);\n                return;\n            }\n\n            // This exceptin occurs when we try to access the property and it fails\n            // for some reason. The actual exception is wrapped in the ObjectVisitorException\n            ObjectVisitorException exception = value as ObjectVisitorException;\n            if (exception != null)\n            {\n                VisitObjectVisitorException(exception);\n                return;\n            }\n\n            // Mark the object as visited\n            id = CreateObjectId(value);\n            _visited.Add(value, id);\n\n            NameValueCollection nameValueCollection = value as NameValueCollection;\n            if (nameValueCollection != null)\n            {\n                VisitNameValueCollection(nameValueCollection, depth);\n                return;\n            }\n\n            IDictionary dictionary = value as IDictionary;\n            if (dictionary != null)\n            {\n                VisitDictionary(dictionary, depth);\n                return;\n            }\n\n            IEnumerable enumerable = value as IEnumerable;\n            if (enumerable != null)\n            {\n                VisitEnumerable(enumerable, depth);\n                return;\n            }\n\n            VisitComplexObject(value, depth + 1);\n        }\n\n        public virtual void VisitObjectVisitorException(ObjectVisitorException exception)\n        {\n        }\n\n        public virtual void VisitConvertedValue(object value, string convertedValue)\n        {\n            VisitStringValue(convertedValue);\n        }\n\n        public virtual void VisitVisitedObject(string id, object value)\n        {\n        }\n\n        public virtual void VisitNull()\n        {\n        }\n\n        public virtual void VisitStringValue(string stringValue)\n        {\n        }\n\n        public virtual void VisitComplexObject(object value, int depth)\n        {\n            if (depth > _recursionLimit)\n            {\n                return;\n            }\n\n            Debug.Assert(value != null, \"Value should not be null\");\n\n            var dynamicObject = value as IDynamicMetaObjectProvider;\n            // Only look at dynamic objects that do not implement ICustomTypeDescriptor\n            if (dynamicObject != null && !(dynamicObject is ICustomTypeDescriptor))\n            {\n                var memberNames = DynamicHelper.GetMemberNames(dynamicObject);\n\n                if (memberNames != null)\n                {\n                    // Always use the runtime type for dynamic objects since there is no metadata\n                    VisitMembers(memberNames,\n                                 name => null,\n                                 name => DynamicHelper.GetMemberValue(dynamicObject, name),\n                                 depth);\n                }\n            }\n            else\n            {\n                // REVIEW: We should try to filter out properties of certain types\n\n                // Dump properties using type descriptor\n                var props = TypeDescriptor.GetProperties(value);\n                var propNames = from PropertyDescriptor p in props\n                                select p.Name;\n\n                VisitMembers(propNames,\n                             name => props.Find(name, ignoreCase: true).PropertyType,\n                             name => GetPropertyDescriptorValue(value, name, props),\n                             depth);\n\n                // Dump fields\n                var fields = value.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance)\n                    .ToDictionary(field => field.Name);\n\n                VisitMembers(fields.Keys,\n                             name => fields[name].FieldType,\n                             name => GetFieldValue(value, name, fields),\n                             depth);\n            }\n        }\n\n        public virtual void VisitNameValueCollection(NameValueCollection collection, int depth)\n        {\n            VisitKeyValues(collection, collection.AllKeys.Cast<object>(), key => collection[(string)key], depth);\n        }\n\n        public virtual void VisitDictionary(IDictionary dictionary, int depth)\n        {\n            VisitKeyValues(dictionary, dictionary.Keys.Cast<object>(), key => dictionary[key], depth);\n        }\n\n        public virtual void VisitEnumerable(IEnumerable enumerable, int depth)\n        {\n            if (depth > _recursionLimit)\n            {\n                return;\n            }\n\n            Type enumerableType = enumerable.GetType();\n            bool isIndexedEnumeration = ImplementsInterface(enumerableType, typeof(IList<>))\n                                        || ImplementsInterface(enumerableType, typeof(IList));\n\n            int index = 0;\n            foreach (var item in enumerable)\n            {\n                if (index >= _enumerationLimit)\n                {\n                    VisitEnumeratonLimitExceeded();\n                    break;\n                }\n                if (isIndexedEnumeration)\n                {\n                    VisitIndexedEnumeratedValue(index, item, depth);\n                }\n                else\n                {\n                    VisitEnumeratedValue(item, depth);\n                }\n                index++;\n            }\n        }\n\n        public virtual void VisitEnumeratedValue(object item, int depth)\n        {\n            Visit(item, depth);\n        }\n\n        public virtual void VisitIndexedEnumeratedValue(int index, object item, int depth)\n        {\n            Visit(item, depth);\n        }\n\n        public virtual void VisitEnumeratonLimitExceeded()\n        {\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We don't want to fail surface any exceptions throw from getting property accessors\")]\n        public virtual void VisitMembers(IEnumerable<string> names, Func<string, Type> typeSelector, Func<string, object> valueSelector, int depth)\n        {\n            foreach (string name in names)\n            {\n                Type type = null;\n                object value = null;\n                try\n                {\n                    // Get the type and value\n                    type = typeSelector(name);\n                    value = valueSelector(name);\n\n                    // If the type is null try using the runtime type\n                    if (value != null && type == null)\n                    {\n                        type = value.GetType();\n                    }\n                }\n                catch (Exception ex)\n                {\n                    // Set the value as an exception we know about\n                    value = new ObjectVisitorException(null, ex);\n                }\n                finally\n                {\n                    VisitMember(name, type, value, depth);\n                }\n            }\n        }\n\n        public virtual void VisitMember(string name, Type type, object value, int depth)\n        {\n            Visit(value, depth);\n        }\n\n        public virtual void VisitKeyValues(object value, IEnumerable<object> keys, Func<object, object> valueSelector, int depth)\n        {\n            if (depth > _recursionLimit)\n            {\n                return;\n            }\n\n            foreach (var key in keys)\n            {\n                VisitKeyValue(key, valueSelector(key), depth);\n            }\n        }\n\n        public virtual void VisitKeyValue(object key, object value, int depth)\n        {\n            // Dump the key and value\n            Visit(key, depth);\n            Visit(value, depth);\n        }\n\n        protected virtual string CreateObjectId(object value)\n        {\n            // REVIEW: Maybe use a guid?\n            return value.GetHashCode().ToString(CultureInfo.InvariantCulture);\n        }\n\n        internal static string GetTypeName(Type type)\n        {\n            // See if we have the type name stored\n            string typeName;\n            if (_typeNames.TryGetValue(type, out typeName))\n            {\n                return typeName;\n            }\n\n            if (type.IsGenericType)\n            {\n                // Get the generic type name without arguments\n                string genericTypeName = GetGenericTypeName(type);\n                // Create a user friendly type name\n                var arguments = from argType in type.GetGenericArguments()\n                                select GetTypeName(argType);\n\n                return String.Format(CultureInfo.InvariantCulture, \"{0}<{1}>\", genericTypeName, String.Join(\", \", arguments));\n            }\n\n            if (type.IsByRef || type.IsArray || type.IsPointer)\n            {\n                // Get the element type name\n                string elementTypeName = GetTypeName(type.GetElementType());\n                // Append the separator\n                int sepIndex = type.Name.IndexOfAny(_separators);\n                return elementTypeName + type.Name.Substring(sepIndex);\n            }\n\n            // Fallback to using the type name as is\n            return type.Name;\n        }\n\n        private static string GetGenericTypeName(Type type)\n        {\n            Debug.Assert(type.IsGenericType, \"Type is not a generic type\");\n\n            // Check for anonymous types\n            if (IsAnonymousType(type))\n            {\n                return \"AnonymousType\";\n            }\n\n            string genericTypeDefinitionName = type.GetGenericTypeDefinition().Name;\n            int index = genericTypeDefinitionName.IndexOf('`');\n            Debug.Assert(index >= 0);\n            // Get the generic type name without the `\n            return genericTypeDefinitionName.Substring(0, index);\n        }\n\n        // Copied from System.Web.WebPages/Util/TypeHelpers.cs\n        private static bool IsAnonymousType(Type type)\n        {\n            Debug.Assert(type != null, \"Type should not be null\");\n\n            // TODO: The only way to detect anonymous types right now.\n            return Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false)\n                   && type.IsGenericType && type.Name.Contains(\"AnonymousType\")\n                   && (type.Name.StartsWith(\"<>\", StringComparison.OrdinalIgnoreCase) || type.Name.StartsWith(\"VB$\", StringComparison.OrdinalIgnoreCase))\n                   && (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic;\n        }\n\n        private static bool ImplementsInterface(Type type, Type targetInterfaceType)\n        {\n            Func<Type, bool> implementsInterface = t => targetInterfaceType.IsAssignableFrom(t);\n            if (targetInterfaceType.IsGenericType)\n            {\n                implementsInterface = t => t.IsGenericType && targetInterfaceType.IsAssignableFrom(t.GetGenericTypeDefinition());\n            }\n            return implementsInterface(type) || type.GetInterfaces().Any(implementsInterface);\n        }\n\n        private static object GetFieldValue(object value, string name, IDictionary<string, FieldInfo> fields)\n        {\n            FieldInfo fieldInfo;\n            // Get the value from the dictionary\n            bool result = fields.TryGetValue(name, out fieldInfo);\n            Debug.Assert(result, \"Entry should exist\");\n            return fieldInfo.GetValue(value);\n        }\n\n        private static object GetPropertyDescriptorValue(object value, string name, PropertyDescriptorCollection props)\n        {\n            PropertyDescriptor propertyDescriptor = props.Find(name, ignoreCase: true);\n            Debug.Assert(propertyDescriptor != null, \"Property descriptor shouldn't be null\");\n            return propertyDescriptor.GetValue(value);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We don't want to surface any exceptions while trying to convert from string\")]\n        private static bool TryConvertToString(object value, out string stringValue)\n        {\n            stringValue = null;\n            try\n            {\n                IConvertible convertibe = value as IConvertible;\n                if (convertibe != null)\n                {\n                    stringValue = convertibe.ToString(CultureInfo.CurrentCulture);\n                    return true;\n                }\n\n                TypeConverter converter = TypeDescriptor.GetConverter(value);\n                if (converter.CanConvertFrom(typeof(string)))\n                {\n                    stringValue = converter.ConvertToString(value);\n                    return true;\n                }\n\n                Type type = value.GetType();\n                if (type == typeof(object))\n                {\n                    stringValue = value.ToString();\n                    return true;\n                }\n                Type valueAsType = value as Type;\n                if (valueAsType != null)\n                {\n                    stringValue = \"typeof(\" + GetTypeName(valueAsType) + \")\";\n                    return true;\n                }\n            }\n            catch (Exception)\n            {\n                // If we failed to convert the type for any reason return false\n            }\n            return false;\n        }\n\n        [Serializable]\n        public class ObjectVisitorException : Exception\n        {\n            public ObjectVisitorException()\n            {\n            }\n\n            public ObjectVisitorException(string message)\n                : base(message)\n            {\n            }\n\n            public ObjectVisitorException(string message, Exception inner)\n                : base(message, inner)\n            {\n            }\n\n            protected ObjectVisitorException(\n                SerializationInfo info,\n                StreamingContext context)\n                : base(info, context)\n            {\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Helpers/Properties/AssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\n\n// General Information about an assembly is controlled through the following \n// set of attributes. Change these attribute values to modify the information\n// associated with an assembly.\n\n[assembly: AssemblyTitle(\"System.Web.Helpers\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: InternalsVisibleTo(\"System.Web.Helpers.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n"
  },
  {
    "path": "src/System.Web.Helpers/Resources/ChartTemplates.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.1\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace Microsoft.WebPages.Helpers.Resources {\n    using System;\n    \n    \n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class ChartTemplates {\n        \n        private static global::System.Resources.ResourceManager resourceMan;\n        \n        private static global::System.Globalization.CultureInfo resourceCulture;\n        \n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal ChartTemplates() {\n        }\n        \n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"Microsoft.WebPages.Helpers.Resources.ChartTemplates\", typeof(ChartTemplates).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n        \n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to - &lt;Chart BackColor=&quot;#D3DFF0&quot; BackGradientStyle=&quot;TopBottom&quot; BackSecondaryColor=&quot;White&quot; BorderColor=&quot;26, 59, 105&quot; BorderlineDashStyle=&quot;Solid&quot; BorderWidth=&quot;2&quot; Palette=&quot;BrightPastel&quot;&gt;\n        ///- \t&lt;ChartAreas&gt;\n        ///\t\t&lt;ChartArea Name=&quot;Default&quot; _Template_=&quot;All&quot; BackColor=&quot;64, 165, 191, 228&quot; BackGradientStyle=&quot;TopBottom&quot; BackSecondaryColor=&quot;White&quot; BorderColor=&quot;64, 64, 64, 64&quot; BorderDashStyle=&quot;Solid&quot; ShadowColor=&quot;Transparent&quot; /&gt; \n        ///\t&lt;/ChartAreas&gt;\n        ///\t&lt;Legends&gt;\n        ///\t\t&lt;Legend _Template_=&quot;All&quot; BackColor=&quot;Transparent&quot; Font=&quot;Trebuchet MS, [rest of string was truncated]&quot;;.\n        /// </summary>\n        internal static string Blue {\n            get {\n                return ResourceManager.GetString(\"Blue\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;Chart BackColor=&quot;#C9DC87&quot; BackGradientStyle=&quot;TopBottom&quot; BorderColor=&quot;181, 64, 1&quot; BorderWidth=&quot;2&quot; BorderlineDashStyle=&quot;Solid&quot; Palette=&quot;BrightPastel&quot;&gt;\n        ///  &lt;ChartAreas&gt;\n        ///    &lt;ChartArea Name=&quot;Default&quot; _Template_=&quot;All&quot; BackColor=&quot;Transparent&quot; BackSecondaryColor=&quot;White&quot; BorderColor=&quot;64, 64, 64, 64&quot; BorderDashStyle=&quot;Solid&quot; ShadowColor=&quot;Transparent&quot;&gt;\n        ///      &lt;AxisY LineColor=&quot;64, 64, 64, 64&quot;&gt;\n        ///        &lt;MajorGrid Interval=&quot;Auto&quot; LineColor=&quot;64, 64, 64, 64&quot; /&gt;\n        ///        &lt;LabelStyle Font=&quot;Trebuchet MS, 8.25pt, style=Bold [rest of string was truncated]&quot;;.\n        /// </summary>\n        internal static string Green {\n            get {\n                return ResourceManager.GetString(\"Green\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;Chart Palette=&quot;SemiTransparent&quot; BorderColor=&quot;#000&quot; BorderWidth=&quot;2&quot; BorderlineDashStyle=&quot;Solid&quot;&gt;\n        ///&lt;ChartAreas&gt;\n        ///    &lt;ChartArea _Template_=&quot;All&quot; Name=&quot;Default&quot;&gt;\n        ///            &lt;AxisX&gt;\n        ///                &lt;MinorGrid Enabled=&quot;False&quot; /&gt;\n        ///                &lt;MajorGrid Enabled=&quot;False&quot; /&gt;\n        ///            &lt;/AxisX&gt;\n        ///            &lt;AxisY&gt;\n        ///                &lt;MajorGrid Enabled=&quot;False&quot; /&gt;\n        ///                &lt;MinorGrid Enabled=&quot;False&quot; /&gt;\n        ///            &lt;/AxisY&gt;\n        ///    &lt;/ChartArea&gt;\n        ///&lt;/ChartAreas&gt;\n        ///&lt;/Chart&gt;.\n        /// </summary>\n        internal static string Vanilla {\n            get {\n                return ResourceManager.GetString(\"Vanilla\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;Chart BackColor=&quot;#555&quot; BackGradientStyle=&quot;TopBottom&quot; BorderColor=&quot;181, 64, 1&quot; BorderWidth=&quot;2&quot; BorderlineDashStyle=&quot;Solid&quot; Palette=&quot;Excel&quot; AntiAliasing=&quot;All&quot;&gt;\n        ///    &lt;ChartAreas&gt;\n        ///        &lt;ChartArea Name=&quot;Default&quot; _Template_=&quot;All&quot; BackColor=&quot;Transparent&quot; BackSecondaryColor=&quot;White&quot; BorderColor=&quot;64, 64, 64, 64&quot; BorderDashStyle=&quot;Solid&quot; ShadowColor=&quot;Transparent&quot;&gt;\n        ///            &lt;Area3DStyle LightStyle=&quot;Simplistic&quot; Enable3D=&quot;True&quot; Inclination=&quot;5&quot; IsClustered=&quot;False&quot; IsRightAngleAxes=&quot;False&quot; Perspective=&quot;10&quot; Rotation [rest of string was truncated]&quot;;.\n        /// </summary>\n        internal static string Vanilla3D {\n            get {\n                return ResourceManager.GetString(\"Vanilla3D\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;Chart  BackColor=&quot;#FADA5E&quot; BackGradientStyle=&quot;TopBottom&quot; BorderColor=&quot;#B8860B&quot; BorderWidth=&quot;2&quot; BorderlineDashStyle=&quot;Solid&quot; Palette=&quot;EarthTones&quot;&gt;\n        ///  &lt;ChartAreas&gt;\n        ///    &lt;ChartArea Name=&quot;Default&quot; _Template_=&quot;All&quot; BackColor=&quot;Transparent&quot; BackSecondaryColor=&quot;White&quot; BorderColor=&quot;64, 64, 64, 64&quot; BorderDashStyle=&quot;Solid&quot; ShadowColor=&quot;Transparent&quot;&gt;\n        ///      &lt;AxisY&gt;\n        ///        &lt;LabelStyle Font=&quot;Trebuchet MS, 8.25pt, style=Bold&quot; /&gt;\n        ///      &lt;/AxisY&gt;\n        ///      &lt;AxisX LineColor=&quot;64, 64, 64, 64&quot;&gt;\n        ///        &lt;LabelStyle Font=&quot;Trebuch [rest of string was truncated]&quot;;.\n        /// </summary>\n        internal static string Yellow {\n            get {\n                return ResourceManager.GetString(\"Yellow\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Helpers/Resources/ChartTemplates.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"Blue\" xml:space=\"preserve\">\n    <value>&lt;Chart BackColor=\"#D3DFF0\" BackGradientStyle=\"TopBottom\" BackSecondaryColor=\"White\" BorderColor=\"26, 59, 105\" BorderlineDashStyle=\"Solid\" BorderWidth=\"2\" Palette=\"BrightPastel\"&gt;\n \t&lt;ChartAreas&gt;\n\t\t&lt;ChartArea Name=\"Default\" _Template_=\"All\" BackColor=\"64, 165, 191, 228\" BackGradientStyle=\"TopBottom\" BackSecondaryColor=\"White\" BorderColor=\"64, 64, 64, 64\" BorderDashStyle=\"Solid\" ShadowColor=\"Transparent\" /&gt; \n\t&lt;/ChartAreas&gt;\n\t&lt;Legends&gt;\n\t\t&lt;Legend _Template_=\"All\" BackColor=\"Transparent\" Font=\"Trebuchet MS, 8.25pt, style=Bold\" IsTextAutoFit=\"False\" /&gt; \n\t&lt;/Legends&gt;\n\t&lt;BorderSkin SkinStyle=\"Emboss\" /&gt; \n  &lt;/Chart&gt;</value>\n  </data>\n  <data name=\"Green\" xml:space=\"preserve\">\n    <value>&lt;Chart BackColor=\"#C9DC87\" BackGradientStyle=\"TopBottom\" BorderColor=\"181, 64, 1\" BorderWidth=\"2\" BorderlineDashStyle=\"Solid\" Palette=\"BrightPastel\"&gt;\n  &lt;ChartAreas&gt;\n    &lt;ChartArea Name=\"Default\" _Template_=\"All\" BackColor=\"Transparent\" BackSecondaryColor=\"White\" BorderColor=\"64, 64, 64, 64\" BorderDashStyle=\"Solid\" ShadowColor=\"Transparent\"&gt;\n      &lt;AxisY LineColor=\"64, 64, 64, 64\"&gt;\n        &lt;MajorGrid Interval=\"Auto\" LineColor=\"64, 64, 64, 64\" /&gt;\n        &lt;LabelStyle Font=\"Trebuchet MS, 8.25pt, style=Bold\" /&gt;\n      &lt;/AxisY&gt;\n      &lt;AxisX LineColor=\"64, 64, 64, 64\"&gt;\n        &lt;MajorGrid LineColor=\"64, 64, 64, 64\" /&gt;\n        &lt;LabelStyle Font=\"Trebuchet MS, 8.25pt, style=Bold\" /&gt;\n      &lt;/AxisX&gt;\n      &lt;Area3DStyle Inclination=\"15\" IsClustered=\"False\" IsRightAngleAxes=\"False\" Perspective=\"10\" Rotation=\"10\" WallWidth=\"0\" /&gt;\n    &lt;/ChartArea&gt;\n  &lt;/ChartAreas&gt;\n  &lt;Legends&gt;\n    &lt;Legend _Template_=\"All\" Alignment=\"Center\" BackColor=\"Transparent\" Docking=\"Bottom\" Font=\"Trebuchet MS, 8.25pt, style=Bold\" IsTextAutoFit =\"False\" LegendStyle=\"Row\"&gt;\n    &lt;/Legend&gt;\n  &lt;/Legends&gt;\n  &lt;BorderSkin SkinStyle=\"Emboss\" /&gt;\n&lt;/Chart&gt;</value>\n  </data>\n  <data name=\"Vanilla\" xml:space=\"preserve\">\n    <value>&lt;Chart Palette=\"SemiTransparent\" BorderColor=\"#000\" BorderWidth=\"2\" BorderlineDashStyle=\"Solid\"&gt;\n&lt;ChartAreas&gt;\n    &lt;ChartArea _Template_=\"All\" Name=\"Default\"&gt;\n            &lt;AxisX&gt;\n                &lt;MinorGrid Enabled=\"False\" /&gt;\n                &lt;MajorGrid Enabled=\"False\" /&gt;\n            &lt;/AxisX&gt;\n            &lt;AxisY&gt;\n                &lt;MajorGrid Enabled=\"False\" /&gt;\n                &lt;MinorGrid Enabled=\"False\" /&gt;\n            &lt;/AxisY&gt;\n    &lt;/ChartArea&gt;\n&lt;/ChartAreas&gt;\n&lt;/Chart&gt;</value>\n  </data>\n  <data name=\"Vanilla3D\" xml:space=\"preserve\">\n    <value>&lt;Chart BackColor=\"#555\" BackGradientStyle=\"TopBottom\" BorderColor=\"181, 64, 1\" BorderWidth=\"2\" BorderlineDashStyle=\"Solid\" Palette=\"SemiTransparent\" AntiAliasing=\"All\"&gt;\n    &lt;ChartAreas&gt;\n        &lt;ChartArea Name=\"Default\" _Template_=\"All\" BackColor=\"Transparent\" BackSecondaryColor=\"White\" BorderColor=\"64, 64, 64, 64\" BorderDashStyle=\"Solid\" ShadowColor=\"Transparent\"&gt;\n            &lt;Area3DStyle LightStyle=\"Simplistic\" Enable3D=\"True\" Inclination=\"30\" IsClustered=\"False\" IsRightAngleAxes=\"False\" Perspective=\"10\" Rotation=\"-30\" WallWidth=\"0\" /&gt;\n        &lt;/ChartArea&gt;\n    &lt;/ChartAreas&gt;\n&lt;/Chart&gt;</value>\n  </data>\n  <data name=\"Yellow\" xml:space=\"preserve\">\n    <value>&lt;Chart  BackColor=\"#FADA5E\" BackGradientStyle=\"TopBottom\" BorderColor=\"#B8860B\" BorderWidth=\"2\" BorderlineDashStyle=\"Solid\" Palette=\"EarthTones\"&gt;\n  &lt;ChartAreas&gt;\n    &lt;ChartArea Name=\"Default\" _Template_=\"All\" BackColor=\"Transparent\" BackSecondaryColor=\"White\" BorderColor=\"64, 64, 64, 64\" BorderDashStyle=\"Solid\" ShadowColor=\"Transparent\"&gt;\n      &lt;AxisY&gt;\n        &lt;LabelStyle Font=\"Trebuchet MS, 8.25pt, style=Bold\" /&gt;\n      &lt;/AxisY&gt;\n      &lt;AxisX LineColor=\"64, 64, 64, 64\"&gt;\n        &lt;LabelStyle Font=\"Trebuchet MS, 8.25pt, style=Bold\" /&gt;\n      &lt;/AxisX&gt;\n    &lt;/ChartArea&gt;\n  &lt;/ChartAreas&gt;\n  &lt;Legends&gt;\n    &lt;Legend _Template_=\"All\" Alignment=\"Left\" BackColor=\"Transparent\" Docking=\"Bottom\" Font=\"Trebuchet MS, 8.25pt, style=Bold\" LegendStyle=\"Row\"&gt;\n    &lt;/Legend&gt;\n  &lt;/Legends&gt;\n  &lt;BorderSkin SkinStyle=\"Emboss\" /&gt;\n&lt;/Chart&gt;</value>\n  </data>\n</root>"
  },
  {
    "path": "src/System.Web.Helpers/Resources/HelpersResources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.225\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace System.Web.Helpers.Resources {\n    using System;\n    \n    \n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class HelpersResources {\n        \n        private static global::System.Resources.ResourceManager resourceMan;\n        \n        private static global::System.Globalization.CultureInfo resourceCulture;\n        \n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal HelpersResources() {\n        }\n        \n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"System.Web.Helpers.Resources.HelpersResources\", typeof(HelpersResources).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n        \n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Argument conversion to type &quot;{0}&quot; failed..\n        /// </summary>\n        internal static string Chart_ArgumentConversionFailed {\n            get {\n                return ResourceManager.GetString(\"Chart_ArgumentConversionFailed\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A series cannot be data-bound to a string object..\n        /// </summary>\n        internal static string Chart_ExceptionDataBindSeriesToString {\n            get {\n                return ResourceManager.GetString(\"Chart_ExceptionDataBindSeriesToString\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The theme file &quot;{0}&quot; could not be found..\n        /// </summary>\n        internal static string Chart_ThemeFileNotFound {\n            get {\n                return ResourceManager.GetString(\"Chart_ThemeFileNotFound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The hash algorithm &apos;{0}&apos; is not supported, valid values are: sha256, sha1, md5.\n        /// </summary>\n        internal static string Crypto_NotSupportedHashAlg {\n            get {\n                return ResourceManager.GetString(\"Crypto_NotSupportedHashAlg\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &quot;{0}&quot; is invalid image format. Valid values are image format names like: &quot;JPEG&quot;, &quot;BMP&quot;, &quot;GIF&quot;, &quot;PNG&quot;, etc..\n        /// </summary>\n        internal static string Image_IncorrectImageFormat {\n            get {\n                return ResourceManager.GetString(\"Image_IncorrectImageFormat\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Unable to convert to &quot;{0}&quot;. Use Json.Decode&lt;T&gt; instead..\n        /// </summary>\n        internal static string Json_UnableToConvertType {\n            get {\n                return ResourceManager.GetString(\"Json_UnableToConvertType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Previously Displayed.\n        /// </summary>\n        internal static string ObjectInfo_PreviousDisplayed {\n            get {\n                return ResourceManager.GetString(\"ObjectInfo_PreviousDisplayed\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Accessing a property threw an exception: .\n        /// </summary>\n        internal static string ObjectInfo_PropertyThrewException {\n            get {\n                return ResourceManager.GetString(\"ObjectInfo_PropertyThrewException\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to File path &quot;{0}&quot; is invalid..\n        /// </summary>\n        internal static string PathUtils_IncorrectPath {\n            get {\n                return ResourceManager.GetString(\"PathUtils_IncorrectPath\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Additional server information is available when the page is running with high trust..\n        /// </summary>\n        internal static string ServerInfo_AdditionalInfo {\n            get {\n                return ResourceManager.GetString(\"ServerInfo_AdditionalInfo\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Environment Variables.\n        /// </summary>\n        internal static string ServerInfo_EnvVars {\n            get {\n                return ResourceManager.GetString(\"ServerInfo_EnvVars\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to ASP.NET Server Information.\n        /// </summary>\n        internal static string ServerInfo_Header {\n            get {\n                return ResourceManager.GetString(\"ServerInfo_Header\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to HTTP Runtime Information.\n        /// </summary>\n        internal static string ServerInfo_HttpRuntime {\n            get {\n                return ResourceManager.GetString(\"ServerInfo_HttpRuntime\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Legacy Code Access Security.\n        /// </summary>\n        internal static string ServerInfo_LegacyCAS {\n            get {\n                return ResourceManager.GetString(\"ServerInfo_LegacyCAS\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Legacy Code Access Security has been detected on your system. Microsoft WebPage features require the ASP.NET 4 Code Access Security model. For information about how to resolve this, contact your server administrator..\n        /// </summary>\n        internal static string ServerInfo_LegacyCasHelpInfo {\n            get {\n                return ResourceManager.GetString(\"ServerInfo_LegacyCasHelpInfo\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to no value.\n        /// </summary>\n        internal static string ServerInfo_NoValue {\n            get {\n                return ResourceManager.GetString(\"ServerInfo_NoValue\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Server Configuration.\n        /// </summary>\n        internal static string ServerInfo_ServerConfigTable {\n            get {\n                return ResourceManager.GetString(\"ServerInfo_ServerConfigTable\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to ASP.NET Server Variables.\n        /// </summary>\n        internal static string ServerInfo_ServerVars {\n            get {\n                return ResourceManager.GetString(\"ServerInfo_ServerVars\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The column name cannot be null or an empty string unless a custom format is specified..\n        /// </summary>\n        internal static string WebGrid_ColumnNameOrFormatRequired {\n            get {\n                return ResourceManager.GetString(\"WebGrid_ColumnNameOrFormatRequired\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Column &quot;{0}&quot; does not exist..\n        /// </summary>\n        internal static string WebGrid_ColumnNotFound {\n            get {\n                return ResourceManager.GetString(\"WebGrid_ColumnNotFound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The WebGrid instance is already bound to a data source..\n        /// </summary>\n        internal static string WebGrid_DataSourceBound {\n            get {\n                return ResourceManager.GetString(\"WebGrid_DataSourceBound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A data source must be bound before this operation can be performed..\n        /// </summary>\n        internal static string WebGrid_NoDataSourceBound {\n            get {\n                return ResourceManager.GetString(\"WebGrid_NoDataSourceBound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to This operation is not supported when paging is disabled for the &quot;WebGrid&quot; object..\n        /// </summary>\n        internal static string WebGrid_NotSupportedIfPagingIsDisabled {\n            get {\n                return ResourceManager.GetString(\"WebGrid_NotSupportedIfPagingIsDisabled\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to This operation is not supported when sorting is disabled for the &quot;WebGrid&quot; object..\n        /// </summary>\n        internal static string WebGrid_NotSupportedIfSortingIsDisabled {\n            get {\n                return ResourceManager.GetString(\"WebGrid_NotSupportedIfSortingIsDisabled\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to To use this argument, pager mode &quot;{0}&quot; must be enabled..\n        /// </summary>\n        internal static string WebGrid_PagerModeMustBeEnabled {\n            get {\n                return ResourceManager.GetString(\"WebGrid_PagerModeMustBeEnabled\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to This property cannot be set after the &quot;WebGrid&quot; object has been sorted or paged. Make sure that this property is set prior to invoking the &quot;Rows&quot; property directly or indirectly through other methods such as &quot;GetHtml&quot;, &quot;Pager&quot;, &quot;Table&quot;, etc..\n        /// </summary>\n        internal static string WebGrid_PropertySetterNotSupportedAfterDataBound {\n            get {\n                return ResourceManager.GetString(\"WebGrid_PropertySetterNotSupportedAfterDataBound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A value for &quot;rowCount&quot; must be specified when &quot;autoSortAndPage&quot; is set to true and paging is enabled..\n        /// </summary>\n        internal static string WebGrid_RowCountNotSpecified {\n            get {\n                return ResourceManager.GetString(\"WebGrid_RowCountNotSpecified\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Select.\n        /// </summary>\n        internal static string WebGrid_SelectLinkText {\n            get {\n                return ResourceManager.GetString(\"WebGrid_SelectLinkText\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &quot;fontColor&quot; value is invalid. Valid values are names like &quot;White&quot;, &quot;Black&quot;, or &quot;DarkBlue&quot;, or hexadecimal values in the form &quot;#RRGGBB&quot; or &quot;#RGB&quot;..\n        /// </summary>\n        internal static string WebImage_IncorrectColorName {\n            get {\n                return ResourceManager.GetString(\"WebImage_IncorrectColorName\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &quot;fontFamily&quot; value is invalid. Valid values are font family names like: &quot;Arial&quot;, &quot;Times New Roman&quot;, etc. Make sure that the font family you are trying to use is installed on the server..\n        /// </summary>\n        internal static string WebImage_IncorrectFontFamily {\n            get {\n                return ResourceManager.GetString(\"WebImage_IncorrectFontFamily\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &quot;fontStyle&quot; value is invalid. Valid values are: &quot;Regular&quot;, &quot;Bold&quot;, &quot;Italic&quot;, &quot;Underline&quot;, and &quot;Strikeout&quot;..\n        /// </summary>\n        internal static string WebImage_IncorrectFontStyle {\n            get {\n                return ResourceManager.GetString(\"WebImage_IncorrectFontStyle\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &quot;horizontalAlign&quot; value is invalid. Valid values are: &quot;Right&quot;, &quot;Left&quot;, and &quot;Center&quot;..\n        /// </summary>\n        internal static string WebImage_IncorrectHorizontalAlignment {\n            get {\n                return ResourceManager.GetString(\"WebImage_IncorrectHorizontalAlignment\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &quot;verticalAlign&quot; value is invalid. Valid values are: &quot;Top&quot;, &quot;Bottom&quot;, and &quot;Middle&quot;..\n        /// </summary>\n        internal static string WebImage_IncorrectVerticalAlignment {\n            get {\n                return ResourceManager.GetString(\"WebImage_IncorrectVerticalAlignment\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Watermark width and height must both be positive or both be zero..\n        /// </summary>\n        internal static string WebImage_IncorrectWidthAndHeight {\n            get {\n                return ResourceManager.GetString(\"WebImage_IncorrectWidthAndHeight\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to An image could not be constructed from the content provided..\n        /// </summary>\n        internal static string WebImage_InvalidImageContents {\n            get {\n                return ResourceManager.GetString(\"WebImage_InvalidImageContents\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &quot;priority&quot; value is invalid. Valid values are &quot;Low&quot;, &quot;Normal&quot; and &quot;High&quot;..\n        /// </summary>\n        internal static string WebMail_InvalidPriority {\n            get {\n                return ResourceManager.GetString(\"WebMail_InvalidPriority\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A string in the collection is null or empty..\n        /// </summary>\n        internal static string WebMail_ItemInCollectionIsNull {\n            get {\n                return ResourceManager.GetString(\"WebMail_ItemInCollectionIsNull\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &quot;SmtpServer&quot; was not specified..\n        /// </summary>\n        internal static string WebMail_SmtpServerNotSpecified {\n            get {\n                return ResourceManager.GetString(\"WebMail_SmtpServerNotSpecified\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to No &quot;From&quot; email address was specified and a default value could not be assigned..\n        /// </summary>\n        internal static string WebMail_UnableToDetermineFrom {\n            get {\n                return ResourceManager.GetString(\"WebMail_UnableToDetermineFrom\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Helpers/Resources/HelpersResources.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"Chart_ArgumentConversionFailed\" xml:space=\"preserve\">\n    <value>Argument conversion to type \"{0}\" failed.</value>\n  </data>\n  <data name=\"Chart_ExceptionDataBindSeriesToString\" xml:space=\"preserve\">\n    <value>A series cannot be data-bound to a string object.</value>\n  </data>\n  <data name=\"Chart_ThemeFileNotFound\" xml:space=\"preserve\">\n    <value>The theme file \"{0}\" could not be found.</value>\n  </data>\n  <data name=\"Crypto_NotSupportedHashAlg\" xml:space=\"preserve\">\n    <value>The hash algorithm '{0}' is not supported, valid values are: sha256, sha1, md5</value>\n  </data>\n  <data name=\"Image_IncorrectImageFormat\" xml:space=\"preserve\">\n    <value>\"{0}\" is invalid image format. Valid values are image format names like: \"JPEG\", \"BMP\", \"GIF\", \"PNG\", etc.</value>\n  </data>\n  <data name=\"Json_UnableToConvertType\" xml:space=\"preserve\">\n    <value>Unable to convert to \"{0}\". Use Json.Decode&lt;T&gt; instead.</value>\n  </data>\n  <data name=\"ObjectInfo_PreviousDisplayed\" xml:space=\"preserve\">\n    <value>Previously Displayed</value>\n  </data>\n  <data name=\"ObjectInfo_PropertyThrewException\" xml:space=\"preserve\">\n    <value>Accessing a property threw an exception: </value>\n  </data>\n  <data name=\"PathUtils_IncorrectPath\" xml:space=\"preserve\">\n    <value>File path \"{0}\" is invalid.</value>\n  </data>\n  <data name=\"ServerInfo_AdditionalInfo\" xml:space=\"preserve\">\n    <value>Additional server information is available when the page is running with high trust.</value>\n  </data>\n  <data name=\"ServerInfo_EnvVars\" xml:space=\"preserve\">\n    <value>Environment Variables</value>\n  </data>\n  <data name=\"ServerInfo_Header\" xml:space=\"preserve\">\n    <value>ASP.NET Server Information</value>\n  </data>\n  <data name=\"ServerInfo_HttpRuntime\" xml:space=\"preserve\">\n    <value>HTTP Runtime Information</value>\n  </data>\n  <data name=\"ServerInfo_LegacyCAS\" xml:space=\"preserve\">\n    <value>Legacy Code Access Security</value>\n  </data>\n  <data name=\"ServerInfo_LegacyCasHelpInfo\" xml:space=\"preserve\">\n    <value>Legacy Code Access Security has been detected on your system. Microsoft WebPage features require the ASP.NET 4 Code Access Security model. For information about how to resolve this, contact your server administrator.</value>\n  </data>\n  <data name=\"ServerInfo_NoValue\" xml:space=\"preserve\">\n    <value>no value</value>\n  </data>\n  <data name=\"ServerInfo_ServerConfigTable\" xml:space=\"preserve\">\n    <value>Server Configuration</value>\n  </data>\n  <data name=\"ServerInfo_ServerVars\" xml:space=\"preserve\">\n    <value>ASP.NET Server Variables</value>\n  </data>\n  <data name=\"WebGrid_ColumnNameOrFormatRequired\" xml:space=\"preserve\">\n    <value>The column name cannot be null or an empty string unless a custom format is specified.</value>\n  </data>\n  <data name=\"WebGrid_ColumnNotFound\" xml:space=\"preserve\">\n    <value>Column \"{0}\" does not exist.</value>\n  </data>\n  <data name=\"WebGrid_DataSourceBound\" xml:space=\"preserve\">\n    <value>The WebGrid instance is already bound to a data source.</value>\n  </data>\n  <data name=\"WebGrid_NoDataSourceBound\" xml:space=\"preserve\">\n    <value>A data source must be bound before this operation can be performed.</value>\n  </data>\n  <data name=\"WebGrid_NotSupportedIfPagingIsDisabled\" xml:space=\"preserve\">\n    <value>This operation is not supported when paging is disabled for the \"WebGrid\" object.</value>\n  </data>\n  <data name=\"WebGrid_NotSupportedIfSortingIsDisabled\" xml:space=\"preserve\">\n    <value>This operation is not supported when sorting is disabled for the \"WebGrid\" object.</value>\n  </data>\n  <data name=\"WebGrid_PagerModeMustBeEnabled\" xml:space=\"preserve\">\n    <value>To use this argument, pager mode \"{0}\" must be enabled.</value>\n  </data>\n  <data name=\"WebGrid_PropertySetterNotSupportedAfterDataBound\" xml:space=\"preserve\">\n    <value>This property cannot be set after the \"WebGrid\" object has been sorted or paged. Make sure that this property is set prior to invoking the \"Rows\" property directly or indirectly through other methods such as \"GetHtml\", \"Pager\", \"Table\", etc.</value>\n  </data>\n  <data name=\"WebGrid_RowCountNotSpecified\" xml:space=\"preserve\">\n    <value>A value for \"rowCount\" must be specified when \"autoSortAndPage\" is set to true and paging is enabled.</value>\n  </data>\n  <data name=\"WebGrid_SelectLinkText\" xml:space=\"preserve\">\n    <value>Select</value>\n  </data>\n  <data name=\"WebImage_IncorrectColorName\" xml:space=\"preserve\">\n    <value>The \"fontColor\" value is invalid. Valid values are names like \"White\", \"Black\", or \"DarkBlue\", or hexadecimal values in the form \"#RRGGBB\" or \"#RGB\".</value>\n  </data>\n  <data name=\"WebImage_IncorrectFontFamily\" xml:space=\"preserve\">\n    <value>The \"fontFamily\" value is invalid. Valid values are font family names like: \"Arial\", \"Times New Roman\", etc. Make sure that the font family you are trying to use is installed on the server.</value>\n  </data>\n  <data name=\"WebImage_IncorrectFontStyle\" xml:space=\"preserve\">\n    <value>The \"fontStyle\" value is invalid. Valid values are: \"Regular\", \"Bold\", \"Italic\", \"Underline\", and \"Strikeout\".</value>\n  </data>\n  <data name=\"WebImage_IncorrectHorizontalAlignment\" xml:space=\"preserve\">\n    <value>The \"horizontalAlign\" value is invalid. Valid values are: \"Right\", \"Left\", and \"Center\".</value>\n  </data>\n  <data name=\"WebImage_IncorrectVerticalAlignment\" xml:space=\"preserve\">\n    <value>The \"verticalAlign\" value is invalid. Valid values are: \"Top\", \"Bottom\", and \"Middle\".</value>\n  </data>\n  <data name=\"WebImage_IncorrectWidthAndHeight\" xml:space=\"preserve\">\n    <value>Watermark width and height must both be positive or both be zero.</value>\n  </data>\n  <data name=\"WebImage_InvalidImageContents\" xml:space=\"preserve\">\n    <value>An image could not be constructed from the content provided.</value>\n  </data>\n  <data name=\"WebMail_InvalidPriority\" xml:space=\"preserve\">\n    <value>The \"priority\" value is invalid. Valid values are \"Low\", \"Normal\" and \"High\".</value>\n  </data>\n  <data name=\"WebMail_ItemInCollectionIsNull\" xml:space=\"preserve\">\n    <value>A string in the collection is null or empty.</value>\n  </data>\n  <data name=\"WebMail_SmtpServerNotSpecified\" xml:space=\"preserve\">\n    <value>\"SmtpServer\" was not specified.</value>\n  </data>\n  <data name=\"WebMail_UnableToDetermineFrom\" xml:space=\"preserve\">\n    <value>No \"From\" email address was specified and a default value could not be assigned.</value>\n  </data>\n</root>"
  },
  {
    "path": "src/System.Web.Helpers/ServerInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq;\nusing System.Reflection;\nusing System.Security;\nusing System.Text;\nusing System.Web.Helpers.Resources;\nusing System.Web.WebPages;\n\nnamespace System.Web.Helpers\n{\n    /// <summary>\n    /// Provides various info about ASP.NET server.\n    /// </summary>\n    public static class ServerInfo\n    {\n        /// <remarks>\n        /// todo: figure out right place for this\n        /// </remarks>\n        private const string Style =\n            \"<style type=\\\"text/css\\\">\" +\n            \"  div.server-info { text-align: center; }\" +\n            \"  table.server-info { border-collapse:collapse; text-align:center; margin: auto; width:600px; direction: ltr; }\" +\n            \"  table.server-info tbody tr:nth-child(even){ background-color: #EEE; }\" +\n            \"  table.server-info, table.server-info th, table.server-info td { border:1px solid black; }\" +\n            \"  table.server-info th, table.server-info td \" +\n            \" { text-align:left; padding:2px; font-family:Tahoma, Arial, sans-serif; font-size:0.75em; }\" +\n            \"  h1.server-info { font-family:Tahoma, Arial, sans-serif; font-size:150%; text-align:center; }\" +\n            \"  table.server-info h2 { font-family:Tahoma, Arial, sans-serif; font-size:125%; text-align:center; }\" +\n            \"  p.server-info { text-align:center; font-family:Tahoma, Arial, sans-serif; font-size:0.75em; }\" +\n            \"  .ital { font-style: italic; } \" +\n            \"  .warn { color: #F00; } \" +\n            \"</style>\";\n\n        internal static IDictionary<string, string> EnvironmentVariables()\n        {\n            // todo: extract well defined subset for special use?\n\n            // use a case-insensitive dictionary since environment variables are case-insensitive.\n            IDictionary<string, string> environmentVariablesResult = new SortedDictionary<string, string>(StringComparer.OrdinalIgnoreCase);\n            IDictionary environmentVariables;\n\n            // todo: better way to deal with security; query config for trust level?\n            try\n            {\n                environmentVariables = Environment.GetEnvironmentVariables();\n            }\n            catch (SecurityException)\n            {\n                return environmentVariablesResult;\n            }\n\n            foreach (DictionaryEntry entry in environmentVariables)\n            {\n                environmentVariablesResult.Add(entry.Key.ToString(), InsertWhiteSpace(entry.Value.ToString()));\n            }\n\n            return environmentVariablesResult;\n        }\n\n        internal static IDictionary<string, string> ServerVariables()\n        {\n            var httpContext = HttpContext.Current;\n            return ServerVariables(httpContext != null ? new HttpContextWrapper(httpContext) : null);\n        }\n\n        internal static IDictionary<string, string> ServerVariables(HttpContextBase context)\n        {\n            // todo: extract well defined subset for special use?\n\n            IDictionary<string, string> serverVariablesResult = new SortedDictionary<string, string>();\n            NameValueCollection serverVariables;\n\n            // todo: better way to deal with security; query config for trust level?\n            try\n            {\n                if ((context != null) && (context.Request != null))\n                {\n                    serverVariables = context.Request.ServerVariables;\n                }\n                else\n                {\n                    // Just return empty collection when there is no context available.\n                    return serverVariablesResult;\n                }\n            }\n            catch (SecurityException)\n            {\n                return serverVariablesResult;\n            }\n\n            foreach (string key in serverVariables.AllKeys)\n            {\n                // todo: these values contains very long strings with no spaces that distorts table layout - figure out how to deal with it\n                if (key.Equals(\"ALL_HTTP\", StringComparison.OrdinalIgnoreCase) ||\n                    key.Equals(\"ALL_RAW\", StringComparison.OrdinalIgnoreCase) ||\n                    key.Equals(\"HTTP_AUTHORIZATION\", StringComparison.OrdinalIgnoreCase) ||\n                    key.Equals(\"HTTP_COOKIE\", StringComparison.OrdinalIgnoreCase))\n                {\n                    continue;\n                }\n\n                serverVariablesResult.Add(key, InsertWhiteSpace(serverVariables[key]));\n            }\n\n            return serverVariablesResult;\n        }\n\n        internal static IDictionary<string, string> Configuration()\n        {\n            IDictionary<string, string> info = new Dictionary<string, string>();\n\n            // todo: do we need to localize these strings or would that be confusing\n            // (Since we just display API names that are all in English)\n\n            info.Add(\"Current Local Time\", DateTime.Now.ToString(CultureInfo.CurrentCulture));\n            info.Add(\"Current UTC Time\", DateTime.UtcNow.ToString(CultureInfo.CurrentCulture));\n            info.Add(\"Current Culture\", CultureInfo.CurrentCulture.DisplayName);\n\n            info.Add(\"Machine Name\", Environment.MachineName);\n            info.Add(\"OS Version\", Environment.OSVersion.ToString());\n            info.Add(\"ASP.NET Version\", Environment.Version.ToString());\n            info.Add(\"ASP.NET Web Pages Version\", new AssemblyName(typeof(WebPage).Assembly.FullName).Version.ToString());\n            info.Add(\"User Name\", Environment.UserName);\n            info.Add(\"User Interactive\", Environment.UserInteractive.ToString());\n            info.Add(\"Processor Count\", Environment.ProcessorCount.ToString(CultureInfo.InvariantCulture));\n            info.Add(\"Tick Count\", Environment.TickCount.ToString(CultureInfo.InvariantCulture));\n\n            // Calls bellow require full trust.\n\n            try\n            {\n                info.Add(\"Current Directory\", Environment.CurrentDirectory);\n            }\n            catch (SecurityException)\n            {\n                return info;\n            }\n\n            info.Add(\"System Directory\", Environment.SystemDirectory);\n            info.Add(\"User Domain Name\", Environment.UserDomainName);\n            info.Add(\"Working Set\", Environment.WorkingSet.ToString(CultureInfo.InvariantCulture) + \" bytes\");\n\n            return info;\n        }\n\n        internal static IDictionary<string, string> HttpRuntimeInfo()\n        {\n            IDictionary<string, string> info = new Dictionary<string, string>();\n\n            // todo: better way to deal with security; query config for trust level?\n            try\n            {\n                info.Add(\"CLR Install Directory\", HttpRuntime.ClrInstallDirectory);\n            }\n            catch (SecurityException)\n            {\n                return info;\n            }\n\n            try\n            {\n                info.Add(\"Codegen Directory\", HttpRuntime.CodegenDir);\n                info.Add(\"Bin Directory\", HttpRuntime.BinDirectory);\n                info.Add(\"AppDomain Application Path\", HttpRuntime.AppDomainAppPath);\n            }\n            catch (ArgumentException)\n            {\n                // do nothing\n                // These APIs don't check if path is set before setting security demands, which causes exception.\n                // So far this happens only when running from unit tests.\n            }\n\n            info.Add(\"Asp Install Directory\", HttpRuntime.AspInstallDirectory);\n            info.Add(\"Machine Configuration Directory\", HttpRuntime.MachineConfigurationDirectory);\n\n            info.Add(\"AppDomain Id\", HttpRuntime.AppDomainId);\n            info.Add(\"AppDomain Application Id\", HttpRuntime.AppDomainAppId);\n            info.Add(\"AppDomain Application Virtual Path\", HttpRuntime.AppDomainAppVirtualPath);\n\n            info.Add(\"Asp Client Script Physical Path\", HttpRuntime.AspClientScriptPhysicalPath);\n\n            info.Add(\"Asp Client Script Virtual Path\", HttpRuntime.AspClientScriptVirtualPath);\n\n            info.Add(\"Cache Size\", HttpRuntime.Cache.Count.ToString(CultureInfo.InvariantCulture));\n            info.Add(\"Cache Effective Percentage Physical Memory Limit\", HttpRuntime.Cache.EffectivePercentagePhysicalMemoryLimit.ToString(CultureInfo.InvariantCulture));\n            info.Add(\"Cache Effective Private Bytes Limit\", HttpRuntime.Cache.EffectivePrivateBytesLimit.ToString(CultureInfo.InvariantCulture));\n\n            info.Add(\"On UNC Share\", HttpRuntime.IsOnUNCShare.ToString());\n\n            return info;\n        }\n\n        internal static IDictionary<string, string> LegacyCAS()\n        {\n            return LegacyCAS(AppDomain.CurrentDomain);\n        }\n\n        internal static IDictionary<string, string> LegacyCAS(AppDomain appDomain)\n        {\n            IDictionary<string, string> info = new Dictionary<string, string>();\n\n            try\n            {\n                bool legacyCasModeEnabled = !appDomain.IsHomogenous;\n                if (legacyCasModeEnabled)\n                {\n                    info[HelpersResources.ServerInfo_LegacyCAS] = HelpersResources.ServerInfo_LegacyCasHelpInfo;\n                }\n            }\n            catch (SecurityException)\n            {\n                return info;\n            }\n            return info;\n        }\n\n        /// <summary>\n        /// Generates HTML required to display server information.\n        /// </summary>\n        /// <remarks>\n        /// HTML generated is XHTML 1.0 compliant but not XHTML 1.1 or HTML5 compliant. The reason is that we\n        /// generate &lt;style&gt; tag inside &lt;body&gt; tag, which is not allowed. This is by design for now since ServerInfo\n        /// is debugging aid and should not be used as a permanent part of any web page.\n        /// </remarks>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\",\n            Justification = \"This could be time consuming operation that does not just retrieve a field.\")]\n        public static HtmlString GetHtml()\n        {\n            StringBuilder sb = new StringBuilder(Style);\n\n            sb.AppendLine(String.Format(CultureInfo.InvariantCulture, \"<h1 class=\\\"server-info\\\">{0}</h1>\",\n                                        HttpUtility.HtmlEncode(HelpersResources.ServerInfo_Header)));\n\n            var configuration = Configuration();\n            Debug.Assert((configuration != null) && (configuration.Count > 0));\n            PrintInfoSection(sb, HelpersResources.ServerInfo_ServerConfigTable, configuration);\n\n            var serverVariables = ServerVariables();\n            Debug.Assert((serverVariables != null));\n            PrintInfoSection(sb, HelpersResources.ServerInfo_ServerVars, serverVariables);\n\n            var legacyCAS = LegacyCAS();\n            if (legacyCAS.Any())\n            {\n                PrintInfoSection(sb, HelpersResources.ServerInfo_LegacyCAS, legacyCAS);\n            }\n\n            // Info below is not available in medium trust.\n\n            var httpRuntimeInfo = HttpRuntimeInfo();\n            Debug.Assert(httpRuntimeInfo != null);\n\n            if (!httpRuntimeInfo.Any())\n            {\n                sb.AppendLine(String.Format(CultureInfo.InvariantCulture, \"<p class=\\\"server-info\\\">{0}</p>\",\n                                            HttpUtility.HtmlEncode(HelpersResources.ServerInfo_AdditionalInfo)));\n                return new HtmlString(sb.ToString());\n            }\n            else\n            {\n                PrintInfoSection(sb, HelpersResources.ServerInfo_HttpRuntime, httpRuntimeInfo);\n\n                var envVariables = EnvironmentVariables();\n                Debug.Assert(envVariables != null);\n                PrintInfoSection(sb, HelpersResources.ServerInfo_EnvVars, envVariables);\n            }\n\n            return new HtmlString(sb.ToString());\n        }\n\n        /// <summary>\n        /// Renders a table section printing out rows and columns.\n        /// </summary>\n        private static void PrintInfoSection(StringBuilder builder, string sectionTitle, IDictionary<string, string> entries)\n        {\n            builder.AppendLine(\"<div class=\\\"server-info\\\">\");\n            builder.AppendLine(\"<table class=\\\"server-info\\\" dir=\\\"ltr\\\">\");\n            if (!String.IsNullOrEmpty(sectionTitle))\n            {\n                builder.AppendLine(\"<caption>\");\n                builder.AppendFormat(CultureInfo.InvariantCulture, \"<h2>{0}</h2>\", HttpUtility.HtmlEncode(sectionTitle)).AppendLine();\n                builder.AppendLine(\"</caption>\");\n            }\n            builder.AppendLine(\"<colgroup><col style=\\\"width:30%;\\\" /> <col style=\\\"width:70%;\\\"  /></colgroup>\");\n            builder.AppendLine(\"<tbody>\");\n            foreach (var entry in entries)\n            {\n                var css = String.Empty;\n                string value = entry.Value;\n                if (entry.Key == HelpersResources.ServerInfo_LegacyCAS)\n                {\n                    // TODO: suboptimal solution, but its easier to do this than come up with something that works better\n                    css = \"warn\";\n                }\n                else if (String.IsNullOrEmpty(entry.Value))\n                {\n                    css = \"ital\";\n                    value = HelpersResources.ServerInfo_NoValue;\n                }\n                if (css.Any())\n                {\n                    css = \" class=\\\"\" + css + \"\\\"\";\n                }\n                builder.Append(\"<tr>\");\n                builder.AppendFormat(CultureInfo.InvariantCulture, \"<th scope=\\\"row\\\">{0}</th>\", HttpUtility.HtmlEncode(entry.Key));\n                builder.AppendFormat(CultureInfo.InvariantCulture, \"<td{0}>{1}</td>\", css, HttpUtility.HtmlEncode(value));\n                builder.AppendLine(\"</tr>\");\n            }\n            builder.AppendLine(\"</tbody>\");\n            builder.AppendLine(\"</table>\");\n            builder.AppendLine(\"</div>\");\n        }\n\n        /// <summary>\n        /// Inserts spaces after ',' and ';' so table can be rendered properly.\n        /// </summary>\n        private static string InsertWhiteSpace(string s)\n        {\n            return s.Replace(\",\", \", \").Replace(\";\", \"; \");\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Helpers/SortDirection.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Helpers\n{\n    public enum SortDirection\n    {\n        Ascending,\n        Descending\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Helpers/System.Web.Helpers.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{9B7E3740-6161-4548-833C-4BBCA43B970E}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <RootNamespace>System.Web.Helpers</RootNamespace>\n    <AssemblyName>System.Web.Helpers</AssemblyName>\n    <DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>\n    <RunCodeAnalysis>$(CodeAnalysis)</RunCodeAnalysis>\n    <CodeAnalysisRuleSet>..\\WebHelpers.ruleset</CodeAnalysisRuleSet>\n    <DefineConstants>$(DefineConstants);ASPNETWEBPAGES</DefineConstants>\n    <NoWarn>1591</NoWarn>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Drawing\" />\n    <Reference Include=\"System.Runtime.Caching\" />\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"System.Web.DataVisualization\" />\n    <Reference Include=\"System.Web.Extensions\" />\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"System.XML\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\CommonAssemblyInfo.cs\">\n      <Link>Properties\\CommonAssemblyInfo.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\GlobalSuppressions.cs\">\n      <Link>Common\\GlobalSuppressions.cs</Link>\n    </Compile>\n    <Compile Include=\"Chart\\Chart.cs\" />\n    <Compile Include=\"Chart\\ChartTheme.cs\" />\n    <Compile Include=\"Common\\VirtualPathUtil.cs\" />\n    <Compile Include=\"ConversionUtil.cs\" />\n    <Compile Include=\"Crypto.cs\" />\n    <Compile Include=\"DynamicHelper.cs\" />\n    <Compile Include=\"DynamicJavaScriptConverter.cs\" />\n    <Compile Include=\"DynamicJsonArray.cs\" />\n    <Compile Include=\"DynamicJsonObject.cs\" />\n    <Compile Include=\"GlobalSuppressions.cs\" />\n    <Compile Include=\"HtmlElement.cs\" />\n    <Compile Include=\"HtmlObjectPrinter.cs\" />\n    <Compile Include=\"Json.cs\" />\n    <Compile Include=\"ObjectInfo.cs\" />\n    <Compile Include=\"ObjectVisitor.cs\" />\n    <Compile Include=\"WebCache.cs\" />\n    <Compile Include=\"ServerInfo.cs\" />\n    <Compile Include=\"Resources\\HelpersResources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>HelpersResources.resx</DependentUpon>\n    </Compile>\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"SortDirection.cs\" />\n    <Compile Include=\"WebGrid\\IWebGridDataSource.cs\" />\n    <Compile Include=\"WebGrid\\PreComputedGridDataSource.cs\" />\n    <Compile Include=\"WebGrid\\SortInfo.cs\" />\n    <Compile Include=\"WebGrid\\WebGridDataSource.cs\" />\n    <Compile Include=\"WebGrid\\WebGrid.cs\" />\n    <Compile Include=\"WebGrid\\WebGridColumn.cs\" />\n    <Compile Include=\"WebGrid\\WebGridPagerModes.cs\" />\n    <Compile Include=\"WebGrid\\_WebGridRenderer.generated.cs\">\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>_WebGridRenderer.cshtml</DependentUpon>\n    </Compile>\n    <Compile Include=\"WebGrid\\WebGridRow.cs\" />\n    <Compile Include=\"WebImage.cs\" />\n    <Compile Include=\"WebMail.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"Resources\\HelpersResources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>HelpersResources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\System.Web.WebPages\\System.Web.WebPages.csproj\">\n      <Project>{76EFA9C5-8D7E-4FDF-B710-E20F8B6B00D2}</Project>\n      <Name>System.Web.WebPages</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <Content Include=\"WebGrid\\_WebGridRenderer.cshtml\">\n      <Generator>RazorHelperGenerator</Generator>\n      <LastGenOutput>_WebGridRenderer.generated.cs</LastGenOutput>\n      <CustomToolNamespace>System.Web.Helpers</CustomToolNamespace>\n    </Content>\n  </ItemGroup>\n  <ItemGroup>\n    <CodeAnalysisDictionary Include=\"..\\CodeAnalysisDictionary.xml\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n</Project>"
  },
  {
    "path": "src/System.Web.Helpers/WebCache.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Runtime.Caching;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Helpers\n{\n    public static class WebCache\n    {\n        public static void Set(string key, object value, int minutesToCache = 20, bool slidingExpiration = true)\n        {\n            if (minutesToCache <= 0)\n            {\n                throw new ArgumentOutOfRangeException(\"minutesToCache\",\n                                                      String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Must_Be_GreaterThan, 0));\n            }\n            else if (slidingExpiration && (minutesToCache > 365 * 24 * 60))\n            {\n                // For sliding expiration policies, MemoryCache has a time limit of 365 days. \n                throw new ArgumentOutOfRangeException(\"minutesToCache\",\n                                                      String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Must_Be_LessThanOrEqualTo, 365 * 24 * 60));\n            }\n\n            CacheItemPolicy policy = new CacheItemPolicy();\n            TimeSpan expireTime = new TimeSpan(0, minutesToCache, 0);\n\n            if (slidingExpiration)\n            {\n                policy.SlidingExpiration = expireTime;\n            }\n            else\n            {\n                policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(minutesToCache);\n            }\n\n            MemoryCache.Default.Set(key, value, policy);\n        }\n\n        public static dynamic Get(string key)\n        {\n            return MemoryCache.Default.Get(key);\n        }\n\n        public static dynamic Remove(string key)\n        {\n            return MemoryCache.Default.Remove(key);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Helpers/WebGrid/IWebGridDataSource.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Helpers\n{\n    internal interface IWebGridDataSource\n    {\n        int TotalRowCount { get; }\n\n        IList<WebGridRow> GetRows(SortInfo sortInfo, int pageIndex);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Helpers/WebGrid/PreComputedGridDataSource.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\n\nnamespace System.Web.Helpers\n{\n    /// <summary>\n    /// Source wrapper for data provided by the user that is already sorted and paged. The user provides the WebGrid the rows to bind and additionally the total number of rows that \n    /// are available.\n    /// </summary>\n    internal sealed class PreComputedGridDataSource : IWebGridDataSource\n    {\n        private readonly int _totalRows;\n        private readonly IList<WebGridRow> _rows;\n\n        public PreComputedGridDataSource(WebGrid grid, IEnumerable<dynamic> values, int totalRows)\n        {\n            Debug.Assert(grid != null);\n            Debug.Assert(values != null);\n\n            _totalRows = totalRows;\n            _rows = values.Select((value, index) => new WebGridRow(grid, value: value, rowIndex: index)).ToList();\n        }\n\n        public int TotalRowCount\n        {\n            get { return _totalRows; }\n        }\n\n        public IList<WebGridRow> GetRows(SortInfo sortInfo, int pageIndex)\n        {\n            // Data is already sorted and paged. Ignore parameters.\n            return _rows;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Helpers/WebGrid/SortInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Helpers\n{\n    internal sealed class SortInfo : IEquatable<SortInfo>\n    {\n        public string SortColumn { get; set; }\n\n        public SortDirection SortDirection { get; set; }\n\n        public bool Equals(SortInfo other)\n        {\n            return other != null\n                   && String.Equals(SortColumn, other.SortColumn, StringComparison.OrdinalIgnoreCase)\n                   && SortDirection == other.SortDirection;\n        }\n\n        public override bool Equals(object obj)\n        {\n            SortInfo sortInfo = obj as SortInfo;\n            if (sortInfo != null)\n            {\n                return Equals(sortInfo);\n            }\n            return base.Equals(obj);\n        }\n\n        public override int GetHashCode()\n        {\n            return SortColumn.GetHashCode();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Helpers/WebGrid/WebGrid.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Collections.Specialized;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Dynamic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Linq.Expressions;\nusing System.Text;\nusing System.Web.Helpers.Resources;\nusing System.Web.WebPages;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Helpers\n{\n    public class WebGrid\n    {\n        private const string AjaxUpdateScript = \"$({1}).swhgLoad({0},{1}{2});\";\n        private readonly HttpContextBase _context;\n        private readonly bool _canPage;\n        private readonly bool _canSort;\n        private readonly string _ajaxUpdateContainerId;\n        private readonly string _ajaxUpdateCallback;\n        private readonly string _defaultSort;\n        private readonly string _pageFieldName = \"page\";\n        private readonly string _sortDirectionFieldName = \"sortdir\";\n        private readonly string _selectionFieldName = \"row\";\n        private readonly string _sortFieldName = \"sort\";\n        private readonly string _fieldNamePrefix;\n        private int _pageIndex = -1;\n        private bool _pageIndexSet;\n        private int _rowsPerPage;\n        private int _selectedIndex = -1;\n        private bool _selectedIndexSet;\n        private string _sortColumn;\n        private bool _sortColumnSet;\n        private bool _sortColumnExplicitlySet;\n        private SortDirection _sortDirection;\n        private bool _sortDirectionSet;\n        private IWebGridDataSource _dataSource;\n        private bool _dataSourceBound;\n        private bool _dataSourceMaterialized;\n        private IEnumerable<string> _columnNames;\n        private Type _elementType;\n        private IList<WebGridRow> _rows;\n\n        /// <param name=\"source\">Data source</param>\n        /// <param name=\"columnNames\">Data source column names. Auto-populated by default.</param>\n        /// <param name=\"defaultSort\">Default sort column.</param>\n        /// <param name=\"rowsPerPage\">Number of rows per page.</param>\n        /// <param name=\"canPage\"></param>\n        /// <param name=\"canSort\"></param>\n        /// <param name=\"ajaxUpdateContainerId\">ID for the grid's container element. This enables AJAX support.</param>\n        /// <param name=\"ajaxUpdateCallback\">Callback function for the AJAX functionality once the update is complete</param>\n        /// <param name=\"fieldNamePrefix\">Prefix for query string fields to support multiple grids.</param>\n        /// <param name=\"pageFieldName\">Query string field name for page number.</param>\n        /// <param name=\"selectionFieldName\">Query string field name for selected row number.</param>\n        /// <param name=\"sortFieldName\">Query string field name for sort column.</param>\n        /// <param name=\"sortDirectionFieldName\">Query string field name for sort direction.</param>\n#if CODE_COVERAGE \n        [ExcludeFromCodeCoverage]\n#endif\n        public WebGrid(\n            IEnumerable<dynamic> source = null,\n            IEnumerable<string> columnNames = null,\n            string defaultSort = null,\n            int rowsPerPage = 10,\n            bool canPage = true,\n            bool canSort = true,\n            string ajaxUpdateContainerId = null,\n            string ajaxUpdateCallback = null,\n            string fieldNamePrefix = null,\n            string pageFieldName = null,\n            string selectionFieldName = null,\n            string sortFieldName = null,\n            string sortDirectionFieldName = null)\n            : this(new HttpContextWrapper(Web.HttpContext.Current), defaultSort: defaultSort, rowsPerPage: rowsPerPage, canPage: canPage,\n                   canSort: canSort, ajaxUpdateContainerId: ajaxUpdateContainerId, ajaxUpdateCallback: ajaxUpdateCallback, fieldNamePrefix: fieldNamePrefix, pageFieldName: pageFieldName,\n                   selectionFieldName: selectionFieldName, sortFieldName: sortFieldName, sortDirectionFieldName: sortDirectionFieldName)\n        {\n            if (source != null)\n            {\n                Bind(source, columnNames);\n            }\n        }\n\n        // NOTE: WebGrid uses an IEnumerable<dynamic> data source instead of IEnumerable<T> to avoid generics in the syntax.\n        internal WebGrid(\n            HttpContextBase context,\n            string defaultSort = null,\n            int rowsPerPage = 10,\n            bool canPage = true,\n            bool canSort = true,\n            string ajaxUpdateContainerId = null,\n            string ajaxUpdateCallback = null,\n            string fieldNamePrefix = null,\n            string pageFieldName = null,\n            string selectionFieldName = null,\n            string sortFieldName = null,\n            string sortDirectionFieldName = null)\n        {\n            Debug.Assert(context != null);\n\n            if (rowsPerPage < 1)\n            {\n                throw new ArgumentOutOfRangeException(\"rowsPerPage\", String.Format(CultureInfo.CurrentCulture,\n                                                                                   CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, 1));\n            }\n\n            _context = context;\n            _defaultSort = defaultSort;\n            _rowsPerPage = rowsPerPage;\n            _canPage = canPage;\n            _canSort = canSort;\n            _ajaxUpdateContainerId = ajaxUpdateContainerId;\n            _ajaxUpdateCallback = ajaxUpdateCallback;\n\n            _fieldNamePrefix = fieldNamePrefix;\n\n            if (!String.IsNullOrEmpty(pageFieldName))\n            {\n                _pageFieldName = pageFieldName;\n            }\n            if (!String.IsNullOrEmpty(selectionFieldName))\n            {\n                _selectionFieldName = selectionFieldName;\n            }\n            if (!String.IsNullOrEmpty(sortFieldName))\n            {\n                _sortFieldName = sortFieldName;\n            }\n            if (!String.IsNullOrEmpty(sortDirectionFieldName))\n            {\n                _sortDirectionFieldName = sortDirectionFieldName;\n            }\n\n            CustomSorters = new Dictionary<string, Expression>(StringComparer.OrdinalIgnoreCase);\n        }\n\n        public IEnumerable<string> ColumnNames\n        {\n            get\n            {\n                // Review: Assuming that the users always binds the source and provides column names / we infer the default columns names on binding\n                // Would not work if we want to allow column names to be independently set.\n                EnsureDataBound();\n                return _columnNames;\n            }\n        }\n\n        public bool CanSort\n        {\n            get { return _canSort; }\n        }\n\n        public string AjaxUpdateContainerId\n        {\n            get { return _ajaxUpdateContainerId; }\n        }\n\n        public bool IsAjaxEnabled\n        {\n            get { return !String.IsNullOrEmpty(_ajaxUpdateContainerId); }\n        }\n\n        public string AjaxUpdateCallback\n        {\n            get { return _ajaxUpdateCallback; }\n        }\n\n        public string FieldNamePrefix\n        {\n            get { return _fieldNamePrefix ?? String.Empty; }\n        }\n\n        public bool HasSelection\n        {\n            get { return SelectedIndex >= 0; }\n        }\n\n        public int PageCount\n        {\n            get\n            {\n                if (!_canPage)\n                {\n                    return 1;\n                }\n                return (int)Math.Ceiling((double)TotalRowCount / RowsPerPage);\n            }\n        }\n\n        public string PageFieldName\n        {\n            get { return FieldNamePrefix + _pageFieldName; }\n        }\n\n        public int PageIndex\n        {\n            get\n            {\n                if (!_canPage)\n                {\n                    //Default page index is 0\n                    return 0;\n                }\n                if (!_pageIndexSet)\n                {\n                    int page;\n                    if (!_canPage || !Int32.TryParse(QueryString[PageFieldName], out page) || (page < 1))\n                    {\n                        page = 1;\n                    }\n\n                    if (_dataSourceBound && page > PageCount)\n                    {\n                        page = PageCount;\n                    }\n\n                    _pageIndex = page - 1;\n                    _pageIndexSet = true;\n                }\n                return _pageIndex;\n            }\n            set\n            {\n                if (!_canPage)\n                {\n                    throw new NotSupportedException(HelpersResources.WebGrid_NotSupportedIfPagingIsDisabled);\n                }\n\n                if (!_dataSourceBound)\n                {\n                    // Allow the user to specify arbitrary non-negative values before data binding\n                    if (value < 0)\n                    {\n                        throw new ArgumentOutOfRangeException(\"value\", String.Format(CultureInfo.CurrentCulture,\n                                                                                     CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, 0));\n                    }\n                    else\n                    {\n                        _pageIndex = value;\n                        _pageIndexSet = true;\n                    }\n                }\n                else\n                {\n                    // Once data bound, perform bounds check on the PageIndex. Also ensure the data source has not been materialized.\n                    if ((value < 0) || (value >= PageCount))\n                    {\n                        throw new ArgumentOutOfRangeException(\"value\", String.Format(CultureInfo.CurrentCulture,\n                                                                                     CommonResources.Argument_Must_Be_Between, 0, (PageCount - 1)));\n                    }\n                    else if (value != _pageIndex)\n                    {\n                        EnsureDataSourceNotMaterialized();\n                        _pageIndex = value;\n                        _pageIndexSet = true;\n                    }\n                }\n            }\n        }\n\n        public IList<WebGridRow> Rows\n        {\n            get\n            {\n                EnsureDataBound();\n                if (!_dataSourceMaterialized)\n                {\n                    _rows = _dataSource.GetRows(SortInfo, PageIndex);\n                    _dataSourceMaterialized = true;\n                }\n                return _rows;\n            }\n        }\n\n        public int RowsPerPage\n        {\n            get { return _rowsPerPage; }\n        }\n\n        public WebGridRow SelectedRow\n        {\n            get\n            {\n                if ((SelectedIndex >= 0) && (SelectedIndex < Rows.Count))\n                {\n                    return Rows[SelectedIndex];\n                }\n                return null;\n            }\n        }\n\n        public int SelectedIndex\n        {\n            get\n            {\n                if (!_selectedIndexSet)\n                {\n                    int row;\n                    // Range checking should not use Rows.Count since this will cause paging and sorting.\n                    // Review: side effect is that HasSelection will return true if Rows.Count (current page's\n                    // row count) is less than both SelectedIndex and RowsPerPage. This scenario should only\n                    // happen if someone manually modifies the query string.\n                    // If paging isn't enabled, this getter isn't doing a upper bounds check on the value.\n                    if ((!Int32.TryParse(QueryString[SelectionFieldName], out row)) || (row < 1) || (_canPage && (row > RowsPerPage)))\n                    {\n                        row = 0;\n                    }\n                    _selectedIndex = row - 1;\n                    _selectedIndexSet = true;\n                }\n                return _selectedIndex;\n            }\n            set\n            {\n                if (_selectedIndex != value)\n                {\n                    EnsureDataSourceNotMaterialized();\n                    _selectedIndex = value;\n                }\n                _selectedIndexSet = true;\n            }\n        }\n\n        public string SelectionFieldName\n        {\n            get { return FieldNamePrefix + _selectionFieldName; }\n        }\n\n        public string SortColumn\n        {\n            get\n            {\n                if (!_sortColumnSet)\n                {\n                    string sortColumn = QueryString[SortFieldName];\n                    if (!_dataSourceBound || ValidateSortColumn(sortColumn))\n                    {\n                        _sortColumn = sortColumn;\n                        _sortColumnSet = true;\n                    }\n                }\n                if (String.IsNullOrEmpty(_sortColumn))\n                {\n                    return _defaultSort ?? String.Empty;\n                }\n                return _sortColumn;\n            }\n            set\n            {\n                EnsureDataBound();\n                if (!SortColumn.Equals(value, StringComparison.OrdinalIgnoreCase))\n                {\n                    EnsureDataSourceNotMaterialized();\n                    _sortColumn = value;\n                }\n                _sortColumnSet = true;\n                _sortColumnExplicitlySet = true;\n            }\n        }\n\n        public SortDirection SortDirection\n        {\n            get\n            {\n                if (!_sortDirectionSet)\n                {\n                    string sortDirection = QueryString[SortDirectionFieldName];\n                    if (sortDirection != null)\n                    {\n                        if (sortDirection.Equals(\"DESC\", StringComparison.OrdinalIgnoreCase) ||\n                            sortDirection.Equals(\"DESCENDING\", StringComparison.OrdinalIgnoreCase))\n                        {\n                            _sortDirection = SortDirection.Descending;\n                        }\n                    }\n                    _sortDirectionSet = true;\n                }\n                return _sortDirection;\n            }\n            set\n            {\n                if (!_dataSourceBound)\n                {\n                    _sortDirection = value;\n                }\n                else if (_sortDirection != value)\n                {\n                    EnsureDataSourceNotMaterialized();\n                    _sortDirection = value;\n                }\n                _sortDirectionSet = true;\n            }\n        }\n\n        private SortInfo SortInfo\n        {\n            get { return new SortInfo { SortColumn = SortColumn, SortDirection = SortDirection }; }\n        }\n\n        public string SortDirectionFieldName\n        {\n            get { return FieldNamePrefix + _sortDirectionFieldName; }\n        }\n\n        public string SortFieldName\n        {\n            get { return FieldNamePrefix + _sortFieldName; }\n        }\n\n        internal IDictionary<string, Expression> CustomSorters { get; private set; }\n\n        public int TotalRowCount\n        {\n            get\n            {\n                EnsureDataBound();\n                return _dataSource.TotalRowCount;\n            }\n        }\n\n        private HttpContextBase HttpContext\n        {\n            get { return _context; }\n        }\n\n        private NameValueCollection QueryString\n        {\n            get { return HttpContext.Request.QueryString; }\n        }\n\n        internal static Type GetElementType(IEnumerable<dynamic> source)\n        {\n            Debug.Assert(source != null, \"source cannot be null\");\n            Type sourceType = source.GetType();\n\n            if (source.FirstOrDefault() is IDynamicMetaObjectProvider)\n            {\n                return typeof(IDynamicMetaObjectProvider);\n            }\n            else if (sourceType.IsArray)\n            {\n                return sourceType.GetElementType();\n            }\n            Type elementType = sourceType.GetInterfaces().Select(GetGenericEnumerableType).FirstOrDefault(t => t != null);\n\n            Debug.Assert(elementType != null);\n            return elementType;\n        }\n\n        private static Type GetGenericEnumerableType(Type type)\n        {\n            Type enumerableType = typeof(IEnumerable<>);\n            if (type.IsGenericType && enumerableType.IsAssignableFrom(type.GetGenericTypeDefinition()))\n            {\n                return type.GetGenericArguments()[0];\n            }\n            return null;\n        }\n\n        public WebGrid Bind(IEnumerable<dynamic> source, IEnumerable<string> columnNames = null, bool autoSortAndPage = true, int rowCount = -1)\n        {\n            if (_dataSourceBound)\n            {\n                throw new InvalidOperationException(HelpersResources.WebGrid_DataSourceBound);\n            }\n            if (source == null)\n            {\n                throw new ArgumentNullException(\"source\");\n            }\n            if (!autoSortAndPage && _canPage && rowCount == -1)\n            {\n                throw new ArgumentException(HelpersResources.WebGrid_RowCountNotSpecified, \"rowCount\");\n            }\n\n            _elementType = GetElementType(source);\n            if (_columnNames == null)\n            {\n                _columnNames = columnNames ?? GetDefaultColumnNames(source, elementType: _elementType);\n            }\n\n            if (!autoSortAndPage)\n            {\n                _dataSource = new PreComputedGridDataSource(grid: this, values: source, totalRows: rowCount);\n            }\n            else\n            {\n                WebGridDataSource dataSource = new WebGridDataSource(grid: this, values: source, elementType: _elementType, canPage: _canPage, canSort: _canSort);\n                dataSource.DefaultSort = new SortInfo { SortColumn = _defaultSort, SortDirection = SortDirection.Ascending };\n                dataSource.RowsPerPage = _rowsPerPage;\n                _dataSource = dataSource;\n            }\n            _dataSourceBound = true;\n            ValidatePreDataBoundValues();\n            return this;\n        }\n\n        // todo: add templating from file support\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"Non-static for syntax, and in case we want to check column existence.\")]\n        public WebGridColumn Column(string columnName = null, string header = null, Func<dynamic, object> format = null, string style = null,\n                                    bool canSort = true)\n        {\n            if (String.IsNullOrEmpty(columnName))\n            {\n                if (format == null)\n                {\n                    throw new ArgumentException(HelpersResources.WebGrid_ColumnNameOrFormatRequired, \"columnName\");\n                }\n            }\n\n            return new WebGridColumn { ColumnName = columnName, Header = header, Format = format, Style = style, CanSort = canSort };\n        }\n\n        // Should we keep this no-op API for improved WebGrid syntax? Alternatives are:\n        // 1. columns: grid.Columns(\n        //        grid.Column(...), grid.Column(...)\n        //    )\n        // 2. columns: new[] {\n        //        grid.Column(...), grid.Column(...)\n        //    }\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"Review: No-op API for syntax simplification?\")]\n        public WebGridColumn[] Columns(params WebGridColumn[] columnSet)\n        {\n            return columnSet;\n        }\n\n        public IHtmlString GetContainerUpdateScript(string path)\n        {\n            var script = String.Format(CultureInfo.InvariantCulture, AjaxUpdateScript,\n                                       HttpUtility.JavaScriptStringEncode(path, addDoubleQuotes: true),\n                                       HttpUtility.JavaScriptStringEncode('#' + AjaxUpdateContainerId, addDoubleQuotes: true),\n                                       !String.IsNullOrEmpty(AjaxUpdateCallback) ? ',' + HttpUtility.JavaScriptStringEncode(AjaxUpdateCallback) : String.Empty);\n\n            return new HtmlString(HttpUtility.HtmlAttributeEncode(script));\n        }\n\n        /// <summary>\n        /// Gets the HTML for a table with a pager.\n        /// </summary>\n        /// <param name=\"tableStyle\">Table class for styling.</param>\n        /// <param name=\"headerStyle\">Header row class for styling.</param>\n        /// <param name=\"footerStyle\">Footer row class for styling.</param>\n        /// <param name=\"rowStyle\">Row class for styling (odd rows only).</param>\n        /// <param name=\"alternatingRowStyle\">Row class for styling (even rows only).</param>\n        /// <param name=\"selectedRowStyle\">Selected row class for styling.</param>\n        /// <param name=\"displayHeader\">Whether the header row should be displayed.</param>\n        /// <param name=\"caption\">The string displayed as the table caption</param>\n        /// <param name=\"fillEmptyRows\">Whether the table can add empty rows to ensure the rowsPerPage row count.</param>\n        /// <param name=\"emptyRowCellValue\">Value used to populate empty rows. This property is only used when <paramref name=\"fillEmptyRows\"/> is set</param>\n        /// <param name=\"columns\">Column model for customizing column rendering.</param>\n        /// <param name=\"exclusions\">Columns to exclude when auto-populating columns.</param>\n        /// <param name=\"mode\">Modes for pager rendering.</param>\n        /// <param name=\"firstText\">Text for link to first page.</param>\n        /// <param name=\"previousText\">Text for link to previous page.</param>\n        /// <param name=\"nextText\">Text for link to next page.</param>\n        /// <param name=\"lastText\">Text for link to last page.</param>\n        /// <param name=\"numericLinksCount\">Number of numeric links that should display.</param>\n        /// <param name=\"htmlAttributes\">An object that contains the HTML attributes to set for the element.</param>\n        public IHtmlString GetHtml(\n            string tableStyle = null,\n            string headerStyle = null,\n            string footerStyle = null,\n            string rowStyle = null,\n            string alternatingRowStyle = null,\n            string selectedRowStyle = null,\n            string caption = null,\n            bool displayHeader = true,\n            bool fillEmptyRows = false,\n            string emptyRowCellValue = null,\n            IEnumerable<WebGridColumn> columns = null,\n            IEnumerable<string> exclusions = null,\n            WebGridPagerModes mode = WebGridPagerModes.NextPrevious | WebGridPagerModes.Numeric,\n            string firstText = null,\n            string previousText = null,\n            string nextText = null,\n            string lastText = null,\n            int numericLinksCount = 5,\n            object htmlAttributes = null)\n        {\n            Func<dynamic, object> footer = null;\n            if (_canPage && (PageCount > 1))\n            {\n                footer = item => Pager(mode, firstText, previousText, nextText, lastText, numericLinksCount, explicitlyCalled: false);\n            }\n\n            return Table(tableStyle, headerStyle, footerStyle, rowStyle, alternatingRowStyle, selectedRowStyle, caption, displayHeader,\n                         fillEmptyRows, emptyRowCellValue, columns, exclusions, footer: footer,\n                         htmlAttributes: htmlAttributes);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1055:UriReturnValuesShouldNotBeStrings\", Justification = \"Strings are easier for Plan9 developer to work with\")]\n        public string GetPageUrl(int pageIndex)\n        {\n            if (!_canPage)\n            {\n                throw new NotSupportedException(HelpersResources.WebGrid_NotSupportedIfPagingIsDisabled);\n            }\n            if ((pageIndex < 0) || (pageIndex >= PageCount))\n            {\n                throw new ArgumentOutOfRangeException(\"pageIndex\", String.Format(CultureInfo.CurrentCulture,\n                                                                                 CommonResources.Argument_Must_Be_Between, 0, (PageCount - 1)));\n            }\n\n            NameValueCollection queryString = new NameValueCollection(1);\n            queryString[PageFieldName] = (pageIndex + 1L).ToString(CultureInfo.CurrentCulture);\n            return GetPath(queryString, SelectionFieldName);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1055:UriReturnValuesShouldNotBeStrings\", Justification = \"Strings are easier for Plan9 developer to work with\")]\n        public string GetSortUrl(string column)\n        {\n            if (!_canSort)\n            {\n                throw new NotSupportedException(HelpersResources.WebGrid_NotSupportedIfSortingIsDisabled);\n            }\n            if (String.IsNullOrEmpty(column))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"column\");\n            }\n\n            var sort = SortColumn;\n            var sortDir = SortDirection.Ascending;\n            if (column.Equals(sort, StringComparison.OrdinalIgnoreCase))\n            {\n                if (SortDirection == SortDirection.Ascending)\n                {\n                    sortDir = SortDirection.Descending;\n                }\n            }\n\n            NameValueCollection queryString = new NameValueCollection(2);\n            queryString[SortFieldName] = column;\n            queryString[SortDirectionFieldName] = GetSortDirectionString(sortDir);\n            return GetPath(queryString, PageFieldName, SelectionFieldName);\n        }\n\n        /// <summary>\n        /// Gets the HTML for a pager.\n        /// </summary>\n        /// <param name=\"mode\">Modes for pager rendering.</param>\n        /// <param name=\"firstText\">Text for link to first page.</param>\n        /// <param name=\"previousText\">Text for link to previous page.</param>\n        /// <param name=\"nextText\">Text for link to next page.</param>\n        /// <param name=\"lastText\">Text for link to last page.</param>\n        /// <param name=\"numericLinksCount\">Number of numeric links that should display.</param>\n        public HelperResult Pager(\n            WebGridPagerModes mode = WebGridPagerModes.NextPrevious | WebGridPagerModes.Numeric,\n            string firstText = null,\n            string previousText = null,\n            string nextText = null,\n            string lastText = null,\n            int numericLinksCount = 5)\n        {\n            return Pager(mode, firstText, previousText, nextText, lastText, numericLinksCount, explicitlyCalled: true);\n        }\n\n        /// <param name=\"mode\">Modes for pager rendering.</param>\n        /// <param name=\"firstText\">Text for link to first page.</param>\n        /// <param name=\"previousText\">Text for link to previous page.</param>\n        /// <param name=\"nextText\">Text for link to next page.</param>\n        /// <param name=\"lastText\">Text for link to last page.</param>\n        /// <param name=\"numericLinksCount\">Number of numeric links that should display.</param>\n        /// <param name=\"explicitlyCalled\">The Pager can be explicitly called by the public API or is called by the WebGrid when no footer is provided.\n        /// In the explicit scenario, we would need to render a container for the pager to allow identifying the pager links.\n        /// In the implicit scenario, the grid table would be the container.\n        /// </param>\n        private HelperResult Pager(\n            WebGridPagerModes mode,\n            string firstText,\n            string previousText,\n            string nextText,\n            string lastText,\n            int numericLinksCount,\n            bool explicitlyCalled)\n        {\n            if (!_canPage)\n            {\n                throw new NotSupportedException(HelpersResources.WebGrid_NotSupportedIfPagingIsDisabled);\n            }\n            if (!ModeEnabled(mode, WebGridPagerModes.FirstLast) && (firstText != null))\n            {\n                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture,\n                                                          HelpersResources.WebGrid_PagerModeMustBeEnabled, \"FirstLast\"), \"firstText\");\n            }\n            if (!ModeEnabled(mode, WebGridPagerModes.NextPrevious) && (previousText != null))\n            {\n                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture,\n                                                          HelpersResources.WebGrid_PagerModeMustBeEnabled, \"NextPrevious\"), \"previousText\");\n            }\n            if (!ModeEnabled(mode, WebGridPagerModes.NextPrevious) && (nextText != null))\n            {\n                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture,\n                                                          HelpersResources.WebGrid_PagerModeMustBeEnabled, \"NextPrevious\"), \"nextText\");\n            }\n            if (!ModeEnabled(mode, WebGridPagerModes.FirstLast) && (lastText != null))\n            {\n                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture,\n                                                          HelpersResources.WebGrid_PagerModeMustBeEnabled, \"FirstLast\"), \"lastText\");\n            }\n            if (numericLinksCount < 0)\n            {\n                throw new ArgumentOutOfRangeException(\"numericLinksCount\",\n                                                      String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, 0));\n            }\n\n            return WebGridRenderer.Pager(this, HttpContext, mode: mode, firstText: firstText, previousText: previousText, nextText: nextText, lastText: lastText,\n                                         numericLinksCount: numericLinksCount, renderAjaxContainer: explicitlyCalled);\n        }\n\n        /// <summary>\n        /// Gets the HTML for a table with a pager.\n        /// </summary>\n        /// <param name=\"tableStyle\">Table class for styling.</param>\n        /// <param name=\"headerStyle\">Header row class for styling.</param>\n        /// <param name=\"footerStyle\">Footer row class for styling.</param>\n        /// <param name=\"rowStyle\">Row class for styling (odd rows only).</param>\n        /// <param name=\"alternatingRowStyle\">Row class for styling (even rows only).</param>\n        /// <param name=\"selectedRowStyle\">Selected row class for styling.</param>\n        /// <param name=\"caption\">The table caption</param>\n        /// <param name=\"displayHeader\">Whether the header row should be displayed.</param>\n        /// <param name=\"fillEmptyRows\">Whether the table can add empty rows to ensure the rowsPerPage row count.</param>\n        /// <param name=\"emptyRowCellValue\">Value used to populate empty rows. This property is only used when <paramref name=\"fillEmptyRows\"/> is set</param>\n        /// <param name=\"columns\">Column model for customizing column rendering.</param>\n        /// <param name=\"exclusions\">Columns to exclude when auto-populating columns.</param>\n        /// <param name=\"footer\">Table footer template.</param>\n        /// <param name=\"htmlAttributes\">An object that contains the HTML attributes to set for the element.</param>\n        public IHtmlString Table(\n            string tableStyle = null,\n            string headerStyle = null,\n            string footerStyle = null,\n            string rowStyle = null,\n            string alternatingRowStyle = null,\n            string selectedRowStyle = null,\n            string caption = null,\n            bool displayHeader = true,\n            bool fillEmptyRows = false,\n            string emptyRowCellValue = null,\n            IEnumerable<WebGridColumn> columns = null,\n            IEnumerable<string> exclusions = null,\n            Func<dynamic, object> footer = null,\n            object htmlAttributes = null)\n        {\n            if (columns == null)\n            {\n                columns = GetDefaultColumns(exclusions);\n            }\n            // In order of precedence, the parameters that affect the visibility of columns in WebGrid - \n            // (1) \"columns\" argument of this method \n            // (2) \"exclusion\" argument of this method \n            // (3) \"columnNames\" argument of the constructor. \n            // At the time of binding we can verify if a simple property specified in the query string is a column that would be visible to the user. \n            // However, for complex properties or if either of (1) or (2) arguments are specified, we can only verify at this point. \n            EnsureColumnIsSortable(columns);\n\n            if (emptyRowCellValue == null)\n            {\n                emptyRowCellValue = \"&nbsp;\";\n            }\n\n            return WebGridRenderer.Table(this, HttpContext, tableStyle: tableStyle, headerStyle: headerStyle, footerStyle: footerStyle, rowStyle: rowStyle,\n                                         alternatingRowStyle: alternatingRowStyle, selectedRowStyle: selectedRowStyle, caption: caption, displayHeader: displayHeader, fillEmptyRows: fillEmptyRows,\n                                         emptyRowCellValue: emptyRowCellValue, columns: columns, exclusions: exclusions, footer: footer, htmlAttributes: htmlAttributes);\n        }\n\n        /// <summary>\n        /// Adds a specific sort function for a given column.\n        /// </summary>\n        /// <typeparam name=\"TElement\">The type of elements in the grid's source.</typeparam>\n        /// <typeparam name=\"TProperty\">The column type, usually inferred from the keySelector function's return type.</typeparam>\n        /// <param name=\"columnName\">The column name (as used for sorting)</param>\n        /// <param name=\"keySelector\">The function used to select a key to sort by, for each element in the grid's source.</param>\n        /// <returns>The current grid, with the new custom sorter applied.</returns>\n        /// <example>\n        /// <code>\n        /// var grid = new WebGrid(items)\n        ///     .AddSorter(\"Manager.Name\", (Employee x) => (x == null || x.Manager == null) ? null : x.Manager.Name);\n        /// </code>\n        /// </example>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006\", Justification = \"This design make sense, and is a reasonable user experience for users of the helpers\")]\n        public WebGrid AddSorter<TElement, TProperty>(string columnName, Expression<Func<TElement, TProperty>> keySelector)\n        {\n            CustomSorters[columnName] = keySelector;\n            return this;\n        }\n\n        /// <param name=\"columns\">The set of columns that are rendered to the client.</param>\n        private void EnsureColumnIsSortable(IEnumerable<WebGridColumn> columns)\n        {\n            // Fix for bug 941102\n            // The ValidateSortColumn can validate a few regular cases for sorting and reset those values to default. However, for sort columns that are complex expressions,\n            // or if the user specifies a subset of columns in the GetHtml method (via columns / exclusions), the method is ineffective. \n            // Review: Should this method not throw if the data was not explicitly sorted and paged by the user\n            if (_canSort && !_sortColumnExplicitlySet && !String.IsNullOrEmpty(SortColumn) && !StringComparer.OrdinalIgnoreCase.Equals(_defaultSort, SortColumn)\n                && !columns.Select(c => c.ColumnName).Contains(SortColumn, StringComparer.OrdinalIgnoreCase))\n            {\n                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, HelpersResources.WebGrid_ColumnNotFound, SortColumn));\n            }\n        }\n\n        internal static dynamic GetMember(WebGridRow row, string name)\n        {\n            object result;\n            if (row.TryGetMember(name, out result))\n            {\n                return result;\n            }\n            throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,\n                                                              HelpersResources.WebGrid_ColumnNotFound, name));\n        }\n\n        // review: make sure this is ordered\n        internal string GetPath(NameValueCollection queryString, params string[] exclusions)\n        {\n            NameValueCollection temp = new NameValueCollection(QueryString);\n            // update current query string in case values were set programmatically\n            if (temp.AllKeys.Contains(PageFieldName))\n            {\n                temp.Set(PageFieldName, (PageIndex + 1L).ToString(CultureInfo.CurrentCulture));\n            }\n            if (temp.AllKeys.Contains(SelectionFieldName))\n            {\n                if (SelectedIndex < 0)\n                {\n                    temp.Remove(SelectionFieldName);\n                }\n                else\n                {\n                    temp.Set(SelectionFieldName, (SelectedIndex + 1L).ToString(CultureInfo.CurrentCulture));\n                }\n            }\n            if (temp.AllKeys.Contains(SortFieldName))\n            {\n                if (String.IsNullOrEmpty(SortColumn))\n                {\n                    temp.Remove(SortFieldName);\n                }\n                else\n                {\n                    temp.Set(SortFieldName, SortColumn);\n                }\n            }\n            if (temp.AllKeys.Contains(SortDirectionFieldName))\n            {\n                temp.Set(SortDirectionFieldName, GetSortDirectionString(SortDirection));\n            }\n\n            // remove fields from exclusions list\n            foreach (var key in exclusions)\n            {\n                temp.Remove(key);\n            }\n            // replace with new field values\n            foreach (string key in queryString.Keys)\n            {\n                temp.Set(key, queryString[key]);\n            }\n            queryString = temp;\n\n            StringBuilder sb = new StringBuilder(HttpContext.Request.Path);\n\n            sb.Append(\"?\");\n            for (int i = 0; i < queryString.Count; i++)\n            {\n                if (i > 0)\n                {\n                    sb.Append(\"&\");\n                }\n                sb.Append(HttpUtility.UrlEncode(queryString.Keys[i]));\n                sb.Append(\"=\");\n                sb.Append(HttpUtility.UrlEncode(queryString[i]));\n            }\n            return sb.ToString();\n        }\n\n        internal static string GetSortDirectionString(SortDirection sortDir)\n        {\n            return (sortDir == SortDirection.Ascending) ? \"ASC\" : \"DESC\";\n        }\n\n        private void EnsureDataBound()\n        {\n            if (!_dataSourceBound)\n            {\n                throw new InvalidOperationException(HelpersResources.WebGrid_NoDataSourceBound);\n            }\n        }\n\n        private void EnsureDataSourceNotMaterialized()\n        {\n            if (_dataSourceMaterialized)\n            {\n                throw new InvalidOperationException(HelpersResources.WebGrid_PropertySetterNotSupportedAfterDataBound);\n            }\n        }\n\n        private void ValidatePreDataBoundValues()\n        {\n            if (_canPage && _pageIndexSet && PageIndex > PageCount)\n            {\n                PageIndex = PageCount;\n            }\n            else if (_canSort && _sortColumnSet && !ValidateSortColumn(SortColumn))\n            {\n                SortColumn = _defaultSort;\n            }\n        }\n\n        private bool ValidateSortColumn(string value)\n        {\n            Debug.Assert(ColumnNames != null);\n\n            // Navigation columns that contain '.' will be validated during the Sort operation\n            // Validate other properties up-front and ignore any bad columns passed via the query string\n            return _sortColumnExplicitlySet\n                   || String.IsNullOrEmpty(value)\n                   || StringComparer.OrdinalIgnoreCase.Equals(_defaultSort, value)\n                   || ColumnNames.Contains(value, StringComparer.OrdinalIgnoreCase)\n                   || value.Contains('.');\n        }\n\n        private static IEnumerable<string> GetDefaultColumnNames(IEnumerable<dynamic> source, Type elementType)\n        {\n            var dynObj = source.FirstOrDefault() as IDynamicMetaObjectProvider;\n            if (dynObj != null)\n            {\n                return DynamicHelper.GetMemberNames(dynObj);\n            }\n            else\n            {\n                return (from p in elementType.GetProperties()\n                        where IsBindableType(p.PropertyType) && (p.GetIndexParameters().Length == 0)\n                        select p.Name).OrderBy(n => n, StringComparer.OrdinalIgnoreCase).ToArray();\n            }\n        }\n\n        private IEnumerable<WebGridColumn> GetDefaultColumns(IEnumerable<string> exclusions)\n        {\n            IEnumerable<string> names = ColumnNames;\n            if (exclusions != null)\n            {\n                names = names.Except(exclusions);\n            }\n            return (from n in names\n                    select new WebGridColumn { ColumnName = n, CanSort = true }).ToArray();\n        }\n\n        // see: DataBoundControlHelper.IsBindableType\n        private static bool IsBindableType(Type type)\n        {\n            Debug.Assert(type != null);\n\n            Type underlyingType = Nullable.GetUnderlyingType(type);\n            if (underlyingType != null)\n            {\n                type = underlyingType;\n            }\n            return (type.IsPrimitive ||\n                    type.Equals(typeof(string)) ||\n                    type.Equals(typeof(DateTime)) ||\n                    type.Equals(typeof(Decimal)) ||\n                    type.Equals(typeof(Guid)) ||\n                    type.Equals(typeof(DateTimeOffset)) ||\n                    type.Equals(typeof(TimeSpan)));\n        }\n\n        private static bool ModeEnabled(WebGridPagerModes mode, WebGridPagerModes modeCheck)\n        {\n            return (mode & modeCheck) == modeCheck;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Helpers/WebGrid/WebGridColumn.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Helpers\n{\n    public class WebGridColumn\n    {\n        public bool CanSort { get; set; }\n\n        public string ColumnName { get; set; }\n\n        public Func<dynamic, object> Format { get; set; }\n\n        public string Header { get; set; }\n\n        public string Style { get; set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Helpers/WebGrid/WebGridDataSource.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Dynamic;\nusing System.Linq;\nusing System.Linq.Expressions;\nusing System.Reflection;\nusing Microsoft.CSharp.RuntimeBinder;\nusing Binder = Microsoft.CSharp.RuntimeBinder.Binder;\n\nnamespace System.Web.Helpers\n{\n    /// <summary>\n    /// Default data source that sorts results if a sort column is specified.\n    /// </summary>\n    internal sealed class WebGridDataSource : IWebGridDataSource\n    {\n        private static readonly MethodInfo SortGenericExpressionMethod = typeof(WebGridDataSource).GetMethod(\"SortGenericExpression\", BindingFlags.Static | BindingFlags.NonPublic);\n\n        private readonly WebGrid _grid;\n        private readonly Type _elementType;\n        private readonly IEnumerable<dynamic> _values;\n        private readonly bool _canPage;\n        private readonly bool _canSort;\n\n        public WebGridDataSource(WebGrid grid, IEnumerable<dynamic> values, Type elementType, bool canPage, bool canSort)\n        {\n            Debug.Assert(grid != null);\n            Debug.Assert(values != null);\n\n            _grid = grid;\n            _values = values;\n            _elementType = elementType;\n            _canPage = canPage;\n            _canSort = canSort;\n        }\n\n        public SortInfo DefaultSort { get; set; }\n\n        public int RowsPerPage { get; set; }\n\n        public int TotalRowCount\n        {\n            get { return _values.Count(); }\n        }\n\n        public IList<WebGridRow> GetRows(SortInfo sortInfo, int pageIndex)\n        {\n            IEnumerable<dynamic> rowData = _values;\n\n            if (_canSort)\n            {\n                rowData = Sort(_values.AsQueryable(), sortInfo);\n            }\n\n            rowData = Page(rowData, pageIndex);\n\n            try\n            {\n                // Force compile the underlying IQueryable\n                rowData = rowData.ToList();\n            }\n            catch (ArgumentException)\n            {\n                // The OrderBy method uses a generic comparer which fails when the collection contains 2 or more \n                // items that cannot be compared (e.g. DBNulls, mixed types such as strings and ints et al) with the exception\n                // System.ArgumentException: At least one object must implement IComparable.\n                // Silently fail if this exception occurs and declare that the two items are equivalent\n                rowData = Page(_values.AsQueryable(), pageIndex);\n            }\n            return rowData.Select((value, index) => new WebGridRow(_grid, value: value, rowIndex: index)).ToList();\n        }\n\n        private IQueryable<dynamic> Sort(IQueryable<dynamic> data, SortInfo sortInfo)\n        {\n            if (!String.IsNullOrEmpty(sortInfo.SortColumn) || ((DefaultSort != null) && !String.IsNullOrEmpty(DefaultSort.SortColumn)))\n            {\n                return Sort(data, _elementType, sortInfo);\n            }\n            return data;\n        }\n\n        private IEnumerable<dynamic> Page(IEnumerable<dynamic> data, int pageIndex)\n        {\n            if (_canPage)\n            {\n                Debug.Assert(RowsPerPage > 0);\n                return data.Skip(pageIndex * RowsPerPage).Take(RowsPerPage);\n            }\n            return data;\n        }\n\n        private IQueryable<dynamic> Sort(IQueryable<dynamic> data, Type elementType, SortInfo sort)\n        {\n            Debug.Assert(data != null);\n\n            if (typeof(IDynamicMetaObjectProvider).IsAssignableFrom(elementType))\n            {\n                // IDynamicMetaObjectProvider properties are only available through a runtime binder, so we\n                // must build a custom LINQ expression for getting the dynamic property value.\n                // Lambda: o => o.Property (where Property is obtained by runtime binder)\n                // NOTE: lambda must not use internals otherwise this will fail in partial trust when Helpers assembly is in GAC\n                var binder = Binder.GetMember(CSharpBinderFlags.None, sort.SortColumn, typeof(WebGrid), new[]\n                {\n                    CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)\n                });\n                var param = Expression.Parameter(typeof(IDynamicMetaObjectProvider), \"o\");\n                var getter = Expression.Dynamic(binder, typeof(object), param);\n                return SortGenericExpression<IDynamicMetaObjectProvider, object>(data, getter, param, sort.SortDirection);\n            }\n\n            Expression sorterFunctionBody;\n            ParameterExpression sorterFunctionParameter;\n\n            Expression sorter;\n            if (_grid.CustomSorters.TryGetValue(sort.SortColumn, out sorter))\n            {\n                var lambda = sorter as LambdaExpression;\n                Debug.Assert(lambda != null);\n\n                sorterFunctionBody = lambda.Body;\n                sorterFunctionParameter = lambda.Parameters[0];\n            }\n            else\n            {\n                // The IQueryable<dynamic> data source is cast as IQueryable<object> at runtime. We must call\n                // SortGenericExpression using reflection so that the LINQ expressions use the actual element type.\n                // Lambda: o => o.Property[.NavigationProperty,etc]\n                sorterFunctionParameter = Expression.Parameter(elementType, \"o\");\n                Expression member = sorterFunctionParameter;\n                var type = elementType;\n                var sorts = sort.SortColumn.Split('.');\n                foreach (var name in sorts)\n                {\n                    PropertyInfo prop = type.GetProperty(name);\n                    if (prop == null)\n                    {\n                        // no-op in case navigation property came from querystring (falls back to default sort)\n                        if ((DefaultSort != null) && !sort.Equals(DefaultSort) && !String.IsNullOrEmpty(DefaultSort.SortColumn))\n                        {\n                            return Sort(data, elementType, DefaultSort);\n                        }\n                        return data;\n                    }\n                    member = Expression.Property(member, prop);\n                    type = prop.PropertyType;\n                }\n                sorterFunctionBody = member;\n            }\n\n            var actualSortMethod = SortGenericExpressionMethod.MakeGenericMethod(elementType, sorterFunctionBody.Type);\n            return (IQueryable<dynamic>)actualSortMethod.Invoke(null, new object[] { data, sorterFunctionBody, sorterFunctionParameter, sort.SortDirection });\n        }\n\n        private static IQueryable<TElement> SortGenericExpression<TElement, TProperty>(IQueryable<dynamic> data, Expression body,\n                                                                                       ParameterExpression param, SortDirection sortDirection)\n        {\n            Debug.Assert(data != null);\n            Debug.Assert(body != null);\n            Debug.Assert(param != null);\n\n            // The IQueryable<dynamic> data source is cast as an IQueryable<object> at runtime.  We must cast\n            // this to an IQueryable<TElement> so that the reflection done by the LINQ expressions will work.\n            IQueryable<TElement> data2 = data.Cast<TElement>();\n            Expression<Func<TElement, TProperty>> lambda = Expression.Lambda<Func<TElement, TProperty>>(body, param);\n            if (sortDirection == SortDirection.Descending)\n            {\n                return data2.OrderByDescending(lambda);\n            }\n            else\n            {\n                return data2.OrderBy(lambda);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Helpers/WebGrid/WebGridPagerModes.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Helpers\n{\n    [Flags]\n    public enum WebGridPagerModes\n    {\n        Numeric = 0x1,\n        NextPrevious = 0x2,\n        FirstLast = 0x4,\n        All = 0x7\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Helpers/WebGrid/WebGridRow.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Dynamic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Reflection;\nusing System.Web.Helpers.Resources;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Helpers\n{\n    [SuppressMessage(\"Microsoft.Naming\", \"CA1710:IdentifiersShouldHaveCorrectSuffix\", Justification = \"Collection is not an appropriate suffix for this class\")]\n    public class WebGridRow : DynamicObject, IEnumerable<object>\n    {\n        private const string RowIndexMemberName = \"ROW\";\n        private const BindingFlags BindFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase;\n\n        private WebGrid _grid;\n        private IDynamicMetaObjectProvider _dynamic;\n        private int _rowIndex;\n        private object _value;\n        private IEnumerable<dynamic> _values;\n\n        public WebGridRow(WebGrid webGrid, object value, int rowIndex)\n        {\n            _grid = webGrid;\n            _value = value;\n            _rowIndex = rowIndex;\n            _dynamic = value as IDynamicMetaObjectProvider;\n        }\n\n        public dynamic Value\n        {\n            get { return _value; }\n        }\n\n        public WebGrid WebGrid\n        {\n            get { return _grid; }\n        }\n\n        public object this[string name]\n        {\n            get\n            {\n                if (String.IsNullOrEmpty(name))\n                {\n                    throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"name\");\n                }\n                object value = null;\n                if (!TryGetMember(name, out value))\n                {\n                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,\n                                                                      HelpersResources.WebGrid_ColumnNotFound, name));\n                }\n                return value;\n            }\n        }\n\n        public object this[int index]\n        {\n            get\n            {\n                if ((index < 0) || (index >= _grid.ColumnNames.Count()))\n                {\n                    throw new ArgumentOutOfRangeException(\"index\");\n                }\n                return this.Skip(index).First();\n            }\n        }\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return GetEnumerator();\n        }\n\n        public IEnumerator<object> GetEnumerator()\n        {\n            if (_values == null)\n            {\n                _values = _grid.ColumnNames.Select(c => WebGrid.GetMember(this, c));\n            }\n            return _values.GetEnumerator();\n        }\n\n        public IHtmlString GetSelectLink(string text = null)\n        {\n            if (String.IsNullOrEmpty(text))\n            {\n                text = HelpersResources.WebGrid_SelectLinkText;\n            }\n            return WebGridRenderer.GridLink(_grid, GetSelectUrl(), text);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Justification = \"review: I think a method is more appropriate here\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1055:UriReturnValuesShouldNotBeStrings\", Justification = \"Strings are easier for Plan9 developer to work with\")]\n        public string GetSelectUrl()\n        {\n            NameValueCollection queryString = new NameValueCollection(1);\n            queryString[WebGrid.SelectionFieldName] = (_rowIndex + 1L).ToString(CultureInfo.CurrentCulture);\n            return WebGrid.GetPath(queryString);\n        }\n\n        public override bool TryGetMember(GetMemberBinder binder, out object result)\n        {\n            result = null;\n            // Try to get the row index\n            if (TryGetRowIndex(binder.Name, out result))\n            {\n                return true;\n            }\n\n            // Try to evaluate the dynamic member based on the binder\n            if (_dynamic != null && DynamicHelper.TryGetMemberValue(_dynamic, binder, out result))\n            {\n                return true;\n            }\n\n            return TryGetComplexMember(_value, binder.Name, out result);\n        }\n\n        internal bool TryGetMember(string memberName, out object result)\n        {\n            result = null;\n\n            // Try to get the row index\n            if (TryGetRowIndex(memberName, out result))\n            {\n                return true;\n            }\n\n            // Try to evaluate the dynamic member based on the name\n            if (_dynamic != null && DynamicHelper.TryGetMemberValue(_dynamic, memberName, out result))\n            {\n                return true;\n            }\n\n            // Support '.' for navigation properties\n            return TryGetComplexMember(_value, memberName, out result);\n        }\n\n        public override string ToString()\n        {\n            return _value.ToString();\n        }\n\n        private bool TryGetRowIndex(string memberName, out object result)\n        {\n            result = null;\n            if (String.IsNullOrEmpty(memberName))\n            {\n                return false;\n            }\n\n            if (memberName == RowIndexMemberName)\n            {\n                result = _rowIndex;\n                return true;\n            }\n\n            return false;\n        }\n\n        private static bool TryGetComplexMember(object obj, string name, out object result)\n        {\n            result = null;\n\n            string[] names = name.Split('.');\n            for (int i = 0; i < names.Length; i++)\n            {\n                if ((obj == null) || !TryGetMember(obj, names[i], out result))\n                {\n                    result = null;\n                    return false;\n                }\n                obj = result;\n            }\n            return true;\n        }\n\n        private static bool TryGetMember(object obj, string name, out object result)\n        {\n            PropertyInfo property = obj.GetType().GetProperty(name, BindFlags);\n            if ((property != null) && (property.GetIndexParameters().Length == 0))\n            {\n                result = property.GetValue(obj, null);\n                return true;\n            }\n            result = null;\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Helpers/WebGrid/_WebGridRenderer.cshtml",
    "content": "﻿@using System.Globalization \n@using System.Text \n@using System.Web.Helpers.Resources\n@using System.Web.Mvc \n@using System.Web.WebPages.Html \n@using System.Web.WebPages.Scope \n@using Microsoft.Internal.Web.Utils\n\n@helper GridInitScript(WebGrid webGrid, HttpContextBase httpContext) { \n    if (!webGrid.IsAjaxEnabled) {\n        return;\n    } \n    if (!IsGridScriptRendered(httpContext)) { \n        SetGridScriptRendered(httpContext, true);\n        <script type=\"text/javascript\">\n        (function($) {\n            $.fn.swhgLoad = function(url, containerId, callback) {\n                url = url + (url.indexOf('?') == -1 ? '?' : '&') + '__swhg=' + new Date().getTime();\n\n                $('<div/>').load(url + ' ' + containerId, function(data, status, xhr) {\n                    $(containerId).replaceWith($(this).html());\n                    if (typeof(callback) === 'function') {\n                        callback.apply(this, arguments);\n                    }\n                });\n                return this;\n            }\n\n            $(function() {\n                $('table[data-swhgajax=\"true\"],span[data-swhgajax=\"true\"]').each(function() {\n                    var self = $(this);\n                    var containerId = '#' + self.data('swhgcontainer');\n                    var callback = getFunction(self.data('swhgcallback'));\n\n                    $(containerId).parent().delegate(containerId + ' a[data-swhglnk=\"true\"]', 'click', function() {\n                        $(containerId).swhgLoad($(this).attr('href'), containerId, callback);\n                        return false;\n                    });\n                })\n            });\n\n            function getFunction(code, argNames) {\n                argNames = argNames || [];\n                var fn = window, parts = (code || \"\").split(\".\");\n                while (fn && parts.length) {\n                    fn = fn[parts.shift()];\n                }\n                if (typeof (fn) === \"function\") {\n                    return fn;\n                }\n                argNames.push(code);\n                return Function.constructor.apply(null, argNames);\n            }\n        })(jQuery);\n        </script>\n    } \n} \n\n@helper Table(WebGrid webGrid, \n        HttpContextBase httpContext, \n        string tableStyle, \n        string headerStyle, \n        string footerStyle, \n        string rowStyle, \n        string alternatingRowStyle, \n        string selectedRowStyle,\n        string caption, \n        bool displayHeader, \n        bool fillEmptyRows, \n        string emptyRowCellValue,\n        IEnumerable<WebGridColumn> columns,\n        IEnumerable<string> exclusions,\n        Func<dynamic, object> footer,\n        object htmlAttributes) {\n    \n    if (emptyRowCellValue == null) {\n        emptyRowCellValue = \"&nbsp;\";\n    }\n\n    @GridInitScript(webGrid, httpContext) \n\n    var htmlAttributeDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);\n    if (webGrid.IsAjaxEnabled) {\n        htmlAttributeDictionary[\"data-swhgajax\"] = \"true\";\n        htmlAttributeDictionary[\"data-swhgcontainer\"] = webGrid.AjaxUpdateContainerId;\n        htmlAttributeDictionary[\"data-swhgcallback\"] = webGrid.AjaxUpdateCallback;\n    }\n\n    <table@(tableStyle.IsEmpty() ? null : Raw(\" class=\\\"\" + HttpUtility.HtmlAttributeEncode(tableStyle) + \"\\\"\"))@PrintAttributes(htmlAttributeDictionary)>\n    @if (!caption.IsEmpty()) {\n        <caption>@caption</caption>\n    }\n    @if (displayHeader) {\n    <thead>\n        <tr@CssClass(headerStyle)>\n        @foreach (var column in columns) {\n            <th scope=\"col\">\n            @if (ShowSortableColumnHeader(webGrid, column)) {\n                var text = column.Header.IsEmpty() ? column.ColumnName : column.Header;\n                @GridLink(webGrid, webGrid.GetSortUrl(column.ColumnName), text)\n            }\n            else {\n                @(column.Header ?? column.ColumnName)\n            }\n            </th>\n        }\n        </tr>\n    </thead>\n    }\n    @if (footer != null) {\n    <tfoot>\n        <tr @CssClass(footerStyle)>\n            <td colspan=\"@columns.Count()\">@Format(footer, null)</td>\n        </tr>\n    </tfoot>\n    }\n    <tbody>\n    @{\n        int rowIndex = 0;\n    }\n    @foreach (var row in webGrid.Rows) {\n        string style = GetRowStyle(webGrid, rowIndex++, rowStyle, alternatingRowStyle, selectedRowStyle);\n        <tr@CssClass(style)>\n        @foreach (var column in columns) {\n            var value = (column.Format == null) ? HttpUtility.HtmlEncode(row[column.ColumnName]) : Format(column.Format, row).ToString();\n            <td@CssClass(column.Style)>@Raw(value)</td>\n        }\n        </tr>\n    }\n    @if (fillEmptyRows) {\n        rowIndex = webGrid.Rows.Count;\n        while (rowIndex < webGrid.RowsPerPage) {\n            string style = GetRowStyle(webGrid, rowIndex++, rowStyle, alternatingRowStyle, null);\n            <tr@CssClass(style)>\n                @foreach (var column in columns) {\n                    <td@CssClass(column.Style)>@Raw(emptyRowCellValue)</td>\n                }\n            </tr>\n        }\n    }\n    </tbody>\n    </table>\n}\n\n\n@helper Pager(\n        WebGrid webGrid,\n        HttpContextBase httpContext,\n        WebGridPagerModes mode,\n        string firstText,\n        string previousText,\n        string nextText,\n        string lastText,\n        int numericLinksCount,\n        bool renderAjaxContainer) {\n\n    int currentPage = webGrid.PageIndex;\n    int totalPages = webGrid.PageCount;\n    int lastPage = totalPages - 1;\n\n    @GridInitScript(webGrid, httpContext) \n    \n    if (renderAjaxContainer && webGrid.IsAjaxEnabled) {\n        @:<span data-swhgajax=\"true\" data-swhgcontainer=\"@webGrid.AjaxUpdateContainerId\" data-swhgcallback=\"@webGrid.AjaxUpdateCallback\">\n    }\n\n    if (ModeEnabled(mode, WebGridPagerModes.FirstLast) && currentPage > 1) {\n        if (String.IsNullOrEmpty(firstText)) {\n            firstText = \"<<\";\n        }\n        @GridLink(webGrid, webGrid.GetPageUrl(0), firstText)\n        @Raw(\" \")\n    }\n  \n    if (ModeEnabled(mode, WebGridPagerModes.NextPrevious) && currentPage > 0) {\n        if (String.IsNullOrEmpty(previousText)) {\n            previousText = \"<\";\n        }\n        @GridLink(webGrid, webGrid.GetPageUrl(currentPage - 1), previousText)\n        @Raw(\" \")\n    }\n\n    if (ModeEnabled(mode, WebGridPagerModes.Numeric) && (totalPages > 1)) {\n        int last = currentPage + (numericLinksCount / 2);\n        int first = last - numericLinksCount + 1;\n        if (last > lastPage) {\n            first -= last - lastPage;\n            last = lastPage;\n        }\n        if (first < 0) {\n            last = Math.Min(last + (0 - first), lastPage);\n            first = 0;\n        }\n        for (int i = first; i <= last; i++) {\n            var pageText = (i + 1).ToString(CultureInfo.InvariantCulture);\n            if (i == currentPage) {\n              <span>@pageText</span>\n            }\n            else {\n              @GridLink(webGrid, webGrid.GetPageUrl(i), pageText)\n            }\n            @Raw(\" \")\n        }\n    }\n\n    if (ModeEnabled(mode, WebGridPagerModes.NextPrevious) && (currentPage < lastPage)) {\n        if (String.IsNullOrEmpty(nextText)) {\n          nextText = \">\";\n        }\n        @GridLink(webGrid, webGrid.GetPageUrl(currentPage + 1), nextText)\n        @Raw(\" \")\n    }\n    \n    if (ModeEnabled(mode, WebGridPagerModes.FirstLast) && (currentPage < lastPage - 1)) {\n        if (String.IsNullOrEmpty(lastText)) {\n          lastText = \">>\";\n        }\n        @GridLink(webGrid, webGrid.GetPageUrl(lastPage), lastText)\n    }\n    \n    if (renderAjaxContainer && webGrid.IsAjaxEnabled) {\n        @:</span>\n    }\n}\n\n@functions{\n    private static readonly object _gridScriptRenderedKey = new object();\n\n    private static bool IsGridScriptRendered(HttpContextBase context) {\n        bool? value = (bool?)context.Items[_gridScriptRenderedKey];\n        return value.HasValue && value.Value;\n    }\n\n    private static void SetGridScriptRendered(HttpContextBase context, bool value) {\n        context.Items[_gridScriptRenderedKey] = value;\n    }\n\n    private static bool ShowSortableColumnHeader(WebGrid grid, WebGridColumn column) {\n        return grid.CanSort && column.CanSort && !column.ColumnName.IsEmpty();\n    }\n\n    public static IHtmlString GridLink(WebGrid webGrid, string url, string text) {\n        TagBuilder builder = new TagBuilder(\"a\");\n        builder.SetInnerText(text);\n        builder.MergeAttribute(\"href\", url);\n        if (webGrid.IsAjaxEnabled) {\n            builder.MergeAttribute(\"data-swhglnk\", \"true\");\n        }\n        return builder.ToHtmlString(TagRenderMode.Normal);\n    }\n\n    private static IHtmlString Raw(string text) {\n        return new HtmlString(text);\n    }\n\n    private static IHtmlString RawJS(string text) {\n        return new HtmlString(HttpUtility.JavaScriptStringEncode(text));\n    }\n\n    private static IHtmlString CssClass(string className) {\n        return new HtmlString((!className.IsEmpty()) ? \" class=\\\"\" + HttpUtility.HtmlAttributeEncode(className) + \"\\\"\" : String.Empty);\n    }\n\n    private static string GetRowStyle(WebGrid webGrid, int rowIndex, string rowStyle, string alternatingRowStyle, string selectedRowStyle) {\n        StringBuilder style = new StringBuilder();\n\n        if (rowIndex % 2 == 0) {\n            if (!String.IsNullOrEmpty(rowStyle)) {\n                style.Append(rowStyle);\n            }\n        }\n        else {\n            if (!String.IsNullOrEmpty(alternatingRowStyle)) {\n                style.Append(alternatingRowStyle);\n            }\n        }\n\n        if (!String.IsNullOrEmpty(selectedRowStyle) && (rowIndex == webGrid.SelectedIndex)) {\n            if (style.Length > 0) {\n                style.Append(\" \");\n            }\n            style.Append(selectedRowStyle);\n        }\n        return style.ToString();\n    }\n\n    private static HelperResult Format(Func<dynamic, object> format, dynamic arg) {\n        var result = format(arg);\n        return new HelperResult(tw => {\n            var helper = result as HelperResult;\n            if (helper != null) {\n                helper.WriteTo(tw);\n                return;\n            }\n            IHtmlString htmlString = result as IHtmlString;\n            if (htmlString != null) {\n                tw.Write(htmlString);\n                return;\n            }\n            if (result != null) {\n                tw.Write(HttpUtility.HtmlEncode(result));\n            }\n        });\n    }\n\n    private static IHtmlString PrintAttributes(IDictionary<string, object> attributes) {\n        var builder = new StringBuilder();\n        foreach (var item in attributes) {\n            var value = Convert.ToString(item.Value, CultureInfo.InvariantCulture);\n            builder.Append(' ')\n                    .Append(HttpUtility.HtmlEncode(item.Key))\n                    .Append(\"=\\\"\")\n                    .Append(HttpUtility.HtmlAttributeEncode(value))\n                    .Append('\"');\n        }\n        return new HtmlString(builder.ToString());\n    }\n\n    private static bool ModeEnabled(WebGridPagerModes mode, WebGridPagerModes modeCheck) {\n        return (mode & modeCheck) == modeCheck;\n    }\n}"
  },
  {
    "path": "src/System.Web.Helpers/WebGrid/_WebGridRenderer.generated.cs",
    "content": "﻿//------------------------------------------------------------------------------\r// <auto-generated>\r//     This code was generated by a tool.\r//     Runtime Version:4.0.30319.214\r//\r//     Changes to this file may cause incorrect behavior and will be lost if\r//     the code is regenerated.\r// </auto-generated>\r//------------------------------------------------------------------------------\r\rusing System.CodeDom.Compiler;\rusing System.Collections.Generic;\rusing System.Globalization;\rusing System.Linq;\rusing System.Text;\rusing System.Web.Mvc;\rusing System.Web.WebPages;\rusing System.Web.WebPages.Html;\r\rnamespace System.Web.Helpers\r{\r    [GeneratedCode(\"RazorSingleFileGenerator\", \"1.0.0.0\")]\r    internal class WebGridRenderer : HelperPage\r    {\r#line hidden\r#line hidden\r        public static HelperResult GridInitScript(WebGrid webGrid, HttpContextBase httpContext)\r        {\r            return new HelperResult(__razor_helper_writer =>\r            {\r                if (!webGrid.IsAjaxEnabled)\r                {\r                    return;\r                }\r                if (!IsGridScriptRendered(httpContext))\r                {\r                    SetGridScriptRendered(httpContext, true);\r\r                    WriteLiteralTo(@__razor_helper_writer, \"        <script type=\\\"text/javascript\\\">\\r\\n        (function($) {\\r\\n            $.fn\" +\r                                                           \".swhgLoad = function(url, containerId, callback) {\\r\\n                url = url + \" +\r                                                           \"(url.indexOf(\\'?\\') == -1 ? \\'?\\' : \\'&\\') + \\'__swhg=\\' + new Date().getTime();\\r\\n\\r\\n    \" +\r                                                           \"            $(\\'<div/>\\').load(url + \\' \\' + containerId, function(data, status, xhr\" +\r                                                           \") {\\r\\n                    $(containerId).replaceWith($(this).html());\\r\\n          \" +\r                                                           \"          if (typeof(callback) === \\'function\\') {\\r\\n                        callba\" +\r                                                           \"ck.apply(this, arguments);\\r\\n                    }\\r\\n                });\\r\\n        \" +\r                                                           \"        return this;\\r\\n            }\\r\\n\\r\\n            $(function() {\\r\\n             \" +\r                                                           \"   $(\\'table[data-swhgajax=\\\"true\\\"],span[data-swhgajax=\\\"true\\\"]\\').each(function() {\" +\r                                                           \"\\r\\n                    var self = $(this);\\r\\n                    var containerId =\" +\r                                                           \" \\'#\\' + self.data(\\'swhgcontainer\\');\\r\\n                    var callback = getFuncti\" +\r                                                           \"on(self.data(\\'swhgcallback\\'));\\r\\n\\r\\n                    $(containerId).parent().de\" +\r                                                           \"legate(containerId + \\' a[data-swhglnk=\\\"true\\\"]\\', \\'click\\', function() {\\r\\n         \" +\r                                                           \"               $(containerId).swhgLoad($(this).attr(\\'href\\'), containerId, callba\" +\r                                                           \"ck);\\r\\n                        return false;\\r\\n                    });\\r\\n          \" +\r                                                           \"      })\\r\\n            });\\r\\n\\r\\n            function getFunction(code, argNames) {\\r\" +\r                                                           \"\\n                argNames = argNames || [];\\r\\n                var fn = window, pa\" +\r                                                           \"rts = (code || \\\"\\\").split(\\\".\\\");\\r\\n                while (fn && parts.length) {\\r\\n  \" +\r                                                           \"                  fn = fn[parts.shift()];\\r\\n                }\\r\\n                if\" +\r                                                           \" (typeof (fn) === \\\"function\\\") {\\r\\n                    return fn;\\r\\n               \" +\r                                                           \" }\\r\\n                argNames.push(code);\\r\\n                return Function.constr\" +\r                                                           \"uctor.apply(null, argNames);\\r\\n            }\\r\\n        })(jQuery);\\r\\n        </scri\" +\r                                                           \"pt>\\r\\n\");\r                }\r            });\r        }\r\r#line hidden\r        public static HelperResult Table(WebGrid webGrid,\r                                         HttpContextBase httpContext,\r                                         string tableStyle,\r                                         string headerStyle,\r                                         string footerStyle,\r                                         string rowStyle,\r                                         string alternatingRowStyle,\r                                         string selectedRowStyle,\r                                         string caption,\r                                         bool displayHeader,\r                                         bool fillEmptyRows,\r                                         string emptyRowCellValue,\r                                         IEnumerable<WebGridColumn> columns,\r                                         IEnumerable<string> exclusions,\r                                         Func<dynamic, object> footer,\r                                         object htmlAttributes)\r        {\r            return new HelperResult(__razor_helper_writer =>\r            {\r                if (emptyRowCellValue == null)\r                {\r                    emptyRowCellValue = \"&nbsp;\";\r                }\r\r                WriteTo(@__razor_helper_writer, GridInitScript(webGrid, httpContext));\r\r                var htmlAttributeDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);\r                if (webGrid.IsAjaxEnabled)\r                {\r                    htmlAttributeDictionary[\"data-swhgajax\"] = \"true\";\r                    htmlAttributeDictionary[\"data-swhgcontainer\"] = webGrid.AjaxUpdateContainerId;\r                    htmlAttributeDictionary[\"data-swhgcallback\"] = webGrid.AjaxUpdateCallback;\r                }\r\r                WriteLiteralTo(@__razor_helper_writer, \"    <table\");\r\r                WriteTo(@__razor_helper_writer, tableStyle.IsEmpty() ? null : Raw(\" class=\\\"\" + HttpUtility.HtmlAttributeEncode(tableStyle) + \"\\\"\"));\r\r                WriteTo(@__razor_helper_writer, PrintAttributes(htmlAttributeDictionary));\r\r                WriteLiteralTo(@__razor_helper_writer, \">\\r\\n\");\r\r                if (!caption.IsEmpty())\r                {\r                    WriteLiteralTo(@__razor_helper_writer, \"        <caption>\");\r\r                    WriteTo(@__razor_helper_writer, caption);\r\r                    WriteLiteralTo(@__razor_helper_writer, \"</caption>\\r\\n\");\r                }\r\r                if (displayHeader)\r                {\r                    WriteLiteralTo(@__razor_helper_writer, \"    <thead>\\r\\n        <tr\");\r\r                    WriteTo(@__razor_helper_writer, CssClass(headerStyle));\r\r                    WriteLiteralTo(@__razor_helper_writer, \">\\r\\n\");\r\r                    foreach (var column in columns)\r                    {\r                        WriteLiteralTo(@__razor_helper_writer, \"            <th scope=\\\"col\\\">\\r\\n\");\r\r                        if (ShowSortableColumnHeader(webGrid, column))\r                        {\r                            var text = column.Header.IsEmpty() ? column.ColumnName : column.Header;\r\r                            WriteTo(@__razor_helper_writer, GridLink(webGrid, webGrid.GetSortUrl(column.ColumnName), text));\r                        }\r                        else\r                        {\r                            WriteTo(@__razor_helper_writer, column.Header ?? column.ColumnName);\r                        }\r\r                        WriteLiteralTo(@__razor_helper_writer, \"            </th>\\r\\n\");\r                    }\r\r                    WriteLiteralTo(@__razor_helper_writer, \"        </tr>\\r\\n    </thead>\\r\\n\");\r                }\r\r                if (footer != null)\r                {\r                    WriteLiteralTo(@__razor_helper_writer, \"    <tfoot>\\r\\n        <tr \");\r\r                    WriteTo(@__razor_helper_writer, CssClass(footerStyle));\r\r                    WriteLiteralTo(@__razor_helper_writer, \">\\r\\n            <td colspan=\\\"\");\r\r                    WriteTo(@__razor_helper_writer, columns.Count());\r\r                    WriteLiteralTo(@__razor_helper_writer, \"\\\">\");\r\r                    WriteTo(@__razor_helper_writer, Format(footer, null));\r\r                    WriteLiteralTo(@__razor_helper_writer, \"</td>\\r\\n        </tr>\\r\\n    </tfoot>\\r\\n\");\r                }\r\r                WriteLiteralTo(@__razor_helper_writer, \"    <tbody>\\r\\n\");\r\r                int rowIndex = 0;\r\r                foreach (var row in webGrid.Rows)\r                {\r                    string style = GetRowStyle(webGrid, rowIndex++, rowStyle, alternatingRowStyle, selectedRowStyle);\r\r                    WriteLiteralTo(@__razor_helper_writer, \"        <tr\");\r\r                    WriteTo(@__razor_helper_writer, CssClass(style));\r\r                    WriteLiteralTo(@__razor_helper_writer, \">\\r\\n\");\r\r                    foreach (var column in columns)\r                    {\r                        var value = (column.Format == null) ? HttpUtility.HtmlEncode(row[column.ColumnName]) : Format(column.Format, row).ToString();\r\r                        WriteLiteralTo(@__razor_helper_writer, \"            <td\");\r\r                        WriteTo(@__razor_helper_writer, CssClass(column.Style));\r\r                        WriteLiteralTo(@__razor_helper_writer, \">\");\r\r                        WriteTo(@__razor_helper_writer, Raw(value));\r\r                        WriteLiteralTo(@__razor_helper_writer, \"</td>\\r\\n\");\r                    }\r\r                    WriteLiteralTo(@__razor_helper_writer, \"        </tr>\\r\\n\");\r                }\r\r                if (fillEmptyRows)\r                {\r                    rowIndex = webGrid.Rows.Count;\r                    while (rowIndex < webGrid.RowsPerPage)\r                    {\r                        string style = GetRowStyle(webGrid, rowIndex++, rowStyle, alternatingRowStyle, null);\r\r                        WriteLiteralTo(@__razor_helper_writer, \"            <tr\");\r\r                        WriteTo(@__razor_helper_writer, CssClass(style));\r\r                        WriteLiteralTo(@__razor_helper_writer, \">\\r\\n\");\r\r                        foreach (var column in columns)\r                        {\r                            WriteLiteralTo(@__razor_helper_writer, \"                    <td\");\r\r                            WriteTo(@__razor_helper_writer, CssClass(column.Style));\r\r                            WriteLiteralTo(@__razor_helper_writer, \">\");\r\r                            WriteTo(@__razor_helper_writer, Raw(emptyRowCellValue));\r\r                            WriteLiteralTo(@__razor_helper_writer, \"</td>\\r\\n\");\r                        }\r\r                        WriteLiteralTo(@__razor_helper_writer, \"            </tr>\\r\\n\");\r                    }\r                }\r\r                WriteLiteralTo(@__razor_helper_writer, \"    </tbody>\\r\\n    </table>\\r\\n\");\r            });\r        }\r\r#line hidden\r        public static HelperResult Pager(\r            WebGrid webGrid,\r            HttpContextBase httpContext,\r            WebGridPagerModes mode,\r            string firstText,\r            string previousText,\r            string nextText,\r            string lastText,\r            int numericLinksCount,\r            bool renderAjaxContainer)\r        {\r            return new HelperResult(__razor_helper_writer =>\r            {\r                int currentPage = webGrid.PageIndex;\r                int totalPages = webGrid.PageCount;\r                int lastPage = totalPages - 1;\r\r                WriteTo(@__razor_helper_writer, GridInitScript(webGrid, httpContext));\r\r                if (renderAjaxContainer && webGrid.IsAjaxEnabled)\r                {\r                    WriteLiteralTo(@__razor_helper_writer, \"        \");\r\r                    WriteLiteralTo(@__razor_helper_writer, \"<span data-swhgajax=\\\"true\\\" data-swhgcontainer=\\\"\");\r\r                    WriteTo(@__razor_helper_writer, webGrid.AjaxUpdateContainerId);\r\r                    WriteLiteralTo(@__razor_helper_writer, \"\\\" data-swhgcallback=\\\"\");\r\r                    WriteTo(@__razor_helper_writer, webGrid.AjaxUpdateCallback);\r\r                    WriteLiteralTo(@__razor_helper_writer, \"\\\">\\r\\n\");\r                }\r\r                if (ModeEnabled(mode, WebGridPagerModes.FirstLast) && currentPage > 1)\r                {\r                    if (String.IsNullOrEmpty(firstText))\r                    {\r                        firstText = \"<<\";\r                    }\r\r                    WriteTo(@__razor_helper_writer, GridLink(webGrid, webGrid.GetPageUrl(0), firstText));\r\r                    WriteTo(@__razor_helper_writer, Raw(\" \"));\r                }\r\r                if (ModeEnabled(mode, WebGridPagerModes.NextPrevious) && currentPage > 0)\r                {\r                    if (String.IsNullOrEmpty(previousText))\r                    {\r                        previousText = \"<\";\r                    }\r\r                    WriteTo(@__razor_helper_writer, GridLink(webGrid, webGrid.GetPageUrl(currentPage - 1), previousText));\r\r                    WriteTo(@__razor_helper_writer, Raw(\" \"));\r                }\r\r                if (ModeEnabled(mode, WebGridPagerModes.Numeric) && (totalPages > 1))\r                {\r                    int last = currentPage + (numericLinksCount / 2);\r                    int first = last - numericLinksCount + 1;\r                    if (last > lastPage)\r                    {\r                        first -= last - lastPage;\r                        last = lastPage;\r                    }\r                    if (first < 0)\r                    {\r                        last = Math.Min(last + (0 - first), lastPage);\r                        first = 0;\r                    }\r                    for (int i = first; i <= last; i++)\r                    {\r                        var pageText = (i + 1).ToString(CultureInfo.InvariantCulture);\r                        if (i == currentPage)\r                        {\r                            WriteTo(@__razor_helper_writer, pageText);\r                        }\r                        else\r                        {\r                            WriteTo(@__razor_helper_writer, GridLink(webGrid, webGrid.GetPageUrl(i), pageText));\r                        }\r\r                        WriteTo(@__razor_helper_writer, Raw(\" \"));\r                    }\r                }\r\r                if (ModeEnabled(mode, WebGridPagerModes.NextPrevious) && (currentPage < lastPage))\r                {\r                    if (String.IsNullOrEmpty(nextText))\r                    {\r                        nextText = \">\";\r                    }\r\r                    WriteTo(@__razor_helper_writer, GridLink(webGrid, webGrid.GetPageUrl(currentPage + 1), nextText));\r\r                    WriteTo(@__razor_helper_writer, Raw(\" \"));\r                }\r\r                if (ModeEnabled(mode, WebGridPagerModes.FirstLast) && (currentPage < lastPage - 1))\r                {\r                    if (String.IsNullOrEmpty(lastText))\r                    {\r                        lastText = \">>\";\r                    }\r\r                    WriteTo(@__razor_helper_writer, GridLink(webGrid, webGrid.GetPageUrl(lastPage), lastText));\r                }\r\r                if (renderAjaxContainer && webGrid.IsAjaxEnabled)\r                {\r                    WriteLiteralTo(@__razor_helper_writer, \"        \");\r\r                    WriteLiteralTo(@__razor_helper_writer, \"</span>\\r\\n\");\r                }\r            });\r        }\r\r        private static readonly object _gridScriptRenderedKey = new object();\r\r        private static bool IsGridScriptRendered(HttpContextBase context)\r        {\r            bool? value = (bool?)context.Items[_gridScriptRenderedKey];\r            return value.HasValue && value.Value;\r        }\r\r        private static void SetGridScriptRendered(HttpContextBase context, bool value)\r        {\r            context.Items[_gridScriptRenderedKey] = value;\r        }\r\r        private static bool ShowSortableColumnHeader(WebGrid grid, WebGridColumn column)\r        {\r            return grid.CanSort && column.CanSort && !column.ColumnName.IsEmpty();\r        }\r\r        public static IHtmlString GridLink(WebGrid webGrid, string url, string text)\r        {\r            TagBuilder builder = new TagBuilder(\"a\");\r            builder.SetInnerText(text);\r            builder.MergeAttribute(\"href\", url);\r            if (webGrid.IsAjaxEnabled)\r            {\r                builder.MergeAttribute(\"data-swhglnk\", \"true\");\r            }\r            return builder.ToHtmlString(TagRenderMode.Normal);\r        }\r\r        private static IHtmlString Raw(string text)\r        {\r            return new HtmlString(text);\r        }\r\r        private static IHtmlString RawJS(string text)\r        {\r            return new HtmlString(HttpUtility.JavaScriptStringEncode(text));\r        }\r\r        private static IHtmlString CssClass(string className)\r        {\r            return new HtmlString((!className.IsEmpty()) ? \" class=\\\"\" + HttpUtility.HtmlAttributeEncode(className) + \"\\\"\" : String.Empty);\r        }\r\r        private static string GetRowStyle(WebGrid webGrid, int rowIndex, string rowStyle, string alternatingRowStyle, string selectedRowStyle)\r        {\r            StringBuilder style = new StringBuilder();\r\r            if (rowIndex % 2 == 0)\r            {\r                if (!String.IsNullOrEmpty(rowStyle))\r                {\r                    style.Append(rowStyle);\r                }\r            }\r            else\r            {\r                if (!String.IsNullOrEmpty(alternatingRowStyle))\r                {\r                    style.Append(alternatingRowStyle);\r                }\r            }\r\r            if (!String.IsNullOrEmpty(selectedRowStyle) && (rowIndex == webGrid.SelectedIndex))\r            {\r                if (style.Length > 0)\r                {\r                    style.Append(\" \");\r                }\r                style.Append(selectedRowStyle);\r            }\r            return style.ToString();\r        }\r\r        private static HelperResult Format(Func<dynamic, object> format, dynamic arg)\r        {\r            var result = format(arg);\r            return new HelperResult(tw =>\r            {\r                var helper = result as HelperResult;\r                if (helper != null)\r                {\r                    helper.WriteTo(tw);\r                    return;\r                }\r                IHtmlString htmlString = result as IHtmlString;\r                if (htmlString != null)\r                {\r                    tw.Write(htmlString);\r                    return;\r                }\r                if (result != null)\r                {\r                    tw.Write(HttpUtility.HtmlEncode(result));\r                }\r            });\r        }\r\r        private static IHtmlString PrintAttributes(IDictionary<string, object> attributes)\r        {\r            var builder = new StringBuilder();\r            foreach (var item in attributes)\r            {\r                var value = Convert.ToString(item.Value, CultureInfo.InvariantCulture);\r                builder.Append(' ')\r                    .Append(HttpUtility.HtmlEncode(item.Key))\r                    .Append(\"=\\\"\")\r                    .Append(HttpUtility.HtmlAttributeEncode(value))\r                    .Append('\"');\r            }\r            return new HtmlString(builder.ToString());\r        }\r\r        private static bool ModeEnabled(WebGridPagerModes mode, WebGridPagerModes modeCheck)\r        {\r            return (mode & modeCheck) == modeCheck;\r        }\r\r        protected static HttpApplication ApplicationInstance\r        {\r            get { return ((Context.ApplicationInstance)); }\r        }\r    }\r}\r"
  },
  {
    "path": "src/System.Web.Helpers/WebImage.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.Drawing.Imaging;\nusing System.Drawing.Text;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Web.Helpers.Resources;\nusing System.Web.UI.WebControls;\nusing Microsoft.Internal.Web.Utils;\nusing Image = System.Drawing.Image;\n\nnamespace System.Web.Helpers\n{\n    public class WebImage\n    {\n        // Default resolution to use when getting bitmap from image\n        private const float FixedResolution = 96f;\n\n        private static readonly IDictionary<Guid, ImageFormat> _imageFormatLookup = new[]\n        {\n            Drawing.Imaging.ImageFormat.Bmp, Drawing.Imaging.ImageFormat.Emf, Drawing.Imaging.ImageFormat.Exif,\n            Drawing.Imaging.ImageFormat.Gif, Drawing.Imaging.ImageFormat.Icon, Drawing.Imaging.ImageFormat.Jpeg,\n            Drawing.Imaging.ImageFormat.MemoryBmp, Drawing.Imaging.ImageFormat.Png, Drawing.Imaging.ImageFormat.Tiff,\n            Drawing.Imaging.ImageFormat.Wmf\n        }.ToDictionary(format => format.Guid, format => format);\n\n        private static readonly Func<string, byte[]> _defaultReadAction = File.ReadAllBytes;\n\n        // Initial format is the format of the image when it was constructed. \n        // Current format is the format currently stored in the content buffer. This can\n        // be different than initial format since image transformations can change format.\n        private readonly ImageFormat _initialFormat;\n        private readonly List<ImageTransformation> _transformations = new List<ImageTransformation>();\n        private ImageFormat _currentFormat;\n        private byte[] _content;\n        private string _fileName;\n        private int _height = -1;\n        private int _width = -1;\n\n        private PropertyItem[] _properties; // image metadata\n\n        public WebImage(byte[] content)\n        {\n            _initialFormat = ValidateImageContent(content, \"content\");\n            _currentFormat = _initialFormat;\n            _content = (byte[])content.Clone();\n        }\n\n        public WebImage(string filePath)\n            : this(new HttpContextWrapper(HttpContext.Current), _defaultReadAction, filePath)\n        {\n        }\n\n        public WebImage(Stream imageStream)\n        {\n            if (imageStream.CanSeek)\n            {\n                imageStream.Seek(0, SeekOrigin.Begin);\n\n                _content = new byte[imageStream.Length];\n                using (BinaryReader reader = new BinaryReader(imageStream))\n                {\n                    reader.Read(_content, 0, (int)imageStream.Length);\n                }\n            }\n            else\n            {\n                List<byte[]> chunks = new List<byte[]>();\n                int totalSize = 0;\n                using (BinaryReader reader = new BinaryReader(imageStream))\n                {\n                    // Pick some size for chunks that is still under limit\n                    // that causes them to be placed on the large object heap.\n                    int chunkSizeInBytes = 1024 * 50;\n                    byte[] nextChunk = null;\n                    do\n                    {\n                        nextChunk = reader.ReadBytes(chunkSizeInBytes);\n                        totalSize += nextChunk.Length;\n                        chunks.Add(nextChunk);\n                    }\n                    while (nextChunk.Length == chunkSizeInBytes);\n                }\n\n                _content = new byte[totalSize];\n                int startIndex = 0;\n                foreach (var chunk in chunks)\n                {\n                    chunk.CopyTo(_content, startIndex);\n                    startIndex += chunk.Length;\n                }\n            }\n            _initialFormat = ValidateImageContent(_content, \"imageStream\");\n            _currentFormat = _initialFormat;\n        }\n\n        internal WebImage(HttpContextBase httpContext, Func<string, byte[]> readAction, string filePath)\n        {\n            if (String.IsNullOrEmpty(filePath))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"filePath\");\n            }\n\n            _fileName = filePath;\n            _content = readAction(VirtualPathUtil.MapPath(httpContext, filePath));\n            _initialFormat = ValidateImageContent(_content, \"filePath\");\n            _currentFormat = _initialFormat;\n        }\n\n        private WebImage(WebImage other)\n        {\n            Debug.Assert(other != null);\n            Debug.Assert(other._content != null, \"Incorrectly constructed instance.\");\n\n            // We are not validating the contents from this constructor since its a copy constructor. \n            _content = (byte[])other._content.Clone();\n            _initialFormat = other._initialFormat;\n            _currentFormat = other._currentFormat;\n            _fileName = other._fileName;\n\n            _height = other._height;\n            _width = other._width;\n\n            _properties = (other._properties != null) ? (PropertyItem[])other._properties.Clone() : null;\n\n            _transformations = new List<ImageTransformation>(other._transformations);\n        }\n\n        public int Height\n        {\n            get\n            {\n                if ((_transformations.Count > 0) || (_height < 0))\n                {\n                    ApplyTransformationsAndSetProperties();\n                }\n                return _height;\n            }\n        }\n\n        public int Width\n        {\n            get\n            {\n                if ((_transformations.Count > 0) || (_width < 0))\n                {\n                    ApplyTransformationsAndSetProperties();\n                }\n                return _width;\n            }\n        }\n\n        public string FileName\n        {\n            get { return _fileName; }\n            set { _fileName = value; }\n        }\n\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1308:NormalizeStringsToUppercase\",\n            Justification = \"No security decision is made based on this string. It's customary to display MIME format in lowercase.\")]\n        public string ImageFormat\n        {\n            get\n            {\n                if (_transformations.Any())\n                {\n                    ApplyTransformationsAndSetProperties();\n                }\n\n                Debug.Assert(_currentFormat != null);\n                return ConversionUtil.ToString(_currentFormat).ToLowerInvariant();\n            }\n        }\n\n        public static WebImage GetImageFromRequest(string postedFileName = null)\n        {\n            var request = new HttpRequestWrapper(HttpContext.Current.Request);\n            return GetImageFromRequest(request, postedFileName);\n        }\n\n        internal static WebImage GetImageFromRequest(HttpRequestBase request, string postedFileName = null)\n        {\n            Debug.Assert(request != null);\n            if ((request.Files == null) || (request.Files.Count == 0))\n            {\n                return null;\n            }\n            HttpPostedFileBase file = String.IsNullOrEmpty(postedFileName) ? request.Files[0] : request.Files[postedFileName];\n            if (file == null || file.ContentLength < 1)\n            {\n                return null;\n            }\n\n            // The content type is specified by the browser and is unreliable. \n            // Disregard content type, acquire mime type.\n            ImageFormat format;\n            string mimeType = MimeMapping.GetMimeMapping(file.FileName);\n            if (!ConversionUtil.TryFromStringToImageFormat(mimeType, out format))\n            {\n                // Unsupported image format.\n                return null;\n            }\n\n            WebImage webImage = new WebImage(file.InputStream);\n            webImage.FileName = file.FileName;\n            return webImage;\n        }\n\n        public WebImage Clone()\n        {\n            return new WebImage(this);\n        }\n\n        public byte[] GetBytes(string requestedFormat = null)\n        {\n            if (_transformations.Count > 0)\n            {\n                ApplyTransformationsAndSetProperties();\n            }\n\n            ImageFormat requestedImageFormat = null;\n            if (!String.IsNullOrEmpty(requestedFormat))\n            {\n                // This will throw if image format is incorrect.\n                requestedImageFormat = GetImageFormat(requestedFormat);\n            }\n\n            requestedImageFormat = requestedImageFormat ?? _initialFormat;\n            Debug.Assert(requestedImageFormat != null, \"Initial format can never be null\");\n            if (requestedImageFormat.Equals(_currentFormat))\n            {\n                return (byte[])_content.Clone();\n            }\n\n            // Conversion from one format to another\n            using (MemoryStream sourceBuffer = new MemoryStream(_content))\n            {\n                using (Image image = Image.FromStream(sourceBuffer))\n                {\n                    // if _properties are not initialized that means image did not go through any\n                    // transformations yet and original byte array contains all metadata available\n                    if (_properties != null)\n                    {\n                        CopyMetadata(_properties, image);\n                    }\n\n                    using (MemoryStream destinationBuffer = new MemoryStream())\n                    {\n                        image.Save(destinationBuffer, requestedImageFormat);\n                        return destinationBuffer.ToArray();\n                    }\n                }\n            }\n        }\n\n        public WebImage Resize(int width, int height, bool preserveAspectRatio = true, bool preventEnlarge = false)\n        {\n            if (width <= 0)\n            {\n                throw new ArgumentOutOfRangeException(\n                    \"width\",\n                    String.Format(CultureInfo.InvariantCulture, CommonResources.Argument_Must_Be_GreaterThan, 0));\n            }\n            if (height <= 0)\n            {\n                throw new ArgumentOutOfRangeException(\n                    \"height\",\n                    String.Format(CultureInfo.InvariantCulture, CommonResources.Argument_Must_Be_GreaterThan, 0));\n            }\n\n            ResizeTransformation trans = new ResizeTransformation(height, width, preserveAspectRatio, preventEnlarge);\n            _transformations.Add(trans);\n            return this;\n        }\n\n        public WebImage Crop(int top = 0, int left = 0, int bottom = 0, int right = 0)\n        {\n            if (top < 0)\n            {\n                throw new ArgumentOutOfRangeException(\n                    \"top\",\n                    String.Format(CultureInfo.InvariantCulture, CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, 0));\n            }\n            if (left < 0)\n            {\n                throw new ArgumentOutOfRangeException(\n                    \"left\",\n                    String.Format(CultureInfo.InvariantCulture, CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, 0));\n            }\n            if (bottom < 0)\n            {\n                throw new ArgumentOutOfRangeException(\n                    \"bottom\",\n                    String.Format(CultureInfo.InvariantCulture, CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, 0));\n            }\n            if (right < 0)\n            {\n                throw new ArgumentOutOfRangeException(\n                    \"right\",\n                    String.Format(CultureInfo.InvariantCulture, CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, 0));\n            }\n\n            CropTransformation crop = new CropTransformation(top, right, bottom, left);\n            _transformations.Add(crop);\n            return this;\n        }\n\n        public WebImage RotateLeft()\n        {\n            ImageTransformation transform = new RotateTransformation(RotateFlipType.Rotate270FlipNone);\n            _transformations.Add(transform);\n            return this;\n        }\n\n        public WebImage RotateRight()\n        {\n            ImageTransformation transform = new RotateTransformation(RotateFlipType.Rotate90FlipNone);\n            _transformations.Add(transform);\n            return this;\n        }\n\n        public WebImage FlipVertical()\n        {\n            ImageTransformation transform = new RotateTransformation(RotateFlipType.RotateNoneFlipY);\n            _transformations.Add(transform);\n            return this;\n        }\n\n        public WebImage FlipHorizontal()\n        {\n            ImageTransformation transform = new RotateTransformation(RotateFlipType.RotateNoneFlipX);\n            _transformations.Add(transform);\n            return this;\n        }\n\n        /// <summary>\n        /// Adds text watermark to a WebImage.\n        /// </summary>\n        /// <param name=\"text\">Text to use as a watermark.</param>\n        /// <param name=\"fontColor\">Watermark color. Can be specified as a string (e.g. \"White\") or as a hex value (e.g. \"#00FF00\").</param>\n        /// <param name=\"fontSize\">Font size in points.</param>\n        /// <param name=\"fontStyle\">Font style: bold, italics, etc.</param>\n        /// <param name=\"fontFamily\">Font family name: e.g. Microsoft Sans Serif</param>\n        /// <param name=\"horizontalAlign\">Horizontal alignment for watermark text. Can be \"right\", \"left\", or \"center\".</param>\n        /// <param name=\"verticalAlign\">Vertical alignment for watermark text. Can be \"top\", \"bottom\", or \"middle\".</param>\n        /// <param name=\"opacity\">Watermark text opacity. Should be between 0 and 100.</param>\n        /// <param name=\"padding\">Size of padding around watermark text in pixels.</param>\n        /// <returns>Modified WebImage instance with added watermark.</returns>\n        public WebImage AddTextWatermark(\n            string text,\n            string fontColor = \"Black\",\n            int fontSize = 12,\n            string fontStyle = \"Regular\",\n            string fontFamily = \"Microsoft Sans Serif\",\n            string horizontalAlign = \"Right\",\n            string verticalAlign = \"Bottom\",\n            int opacity = 100,\n            int padding = 5)\n        {\n            if (String.IsNullOrEmpty(text))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"text\");\n            }\n\n            Color color;\n            if (!ConversionUtil.TryFromStringToColor(fontColor, out color))\n            {\n                throw new ArgumentException(HelpersResources.WebImage_IncorrectColorName);\n            }\n\n            if ((opacity < 0) || (opacity > 100))\n            {\n                throw new ArgumentOutOfRangeException(\"opacity\", String.Format(CultureInfo.InvariantCulture, CommonResources.Argument_Must_Be_Between, 0, 100));\n            }\n\n            int alpha = 255 * opacity / 100;\n            color = Color.FromArgb(alpha, color);\n\n            if (fontSize <= 0)\n            {\n                throw new ArgumentOutOfRangeException(\n                    \"fontSize\",\n                    String.Format(CultureInfo.InvariantCulture, CommonResources.Argument_Must_Be_GreaterThan, 0));\n            }\n\n            FontStyle fontStyleEnum;\n            if (!ConversionUtil.TryFromStringToEnum(fontStyle, out fontStyleEnum))\n            {\n                throw new ArgumentException(HelpersResources.WebImage_IncorrectFontStyle);\n            }\n\n            FontFamily fontFamilyClass;\n            if (!ConversionUtil.TryFromStringToFontFamily(fontFamily, out fontFamilyClass))\n            {\n                throw new ArgumentException(HelpersResources.WebImage_IncorrectFontFamily);\n            }\n\n            HorizontalAlign horizontalAlignEnum = ParseHorizontalAlign(horizontalAlign);\n            VerticalAlign verticalAlignEnum = ParseVerticalAlign(verticalAlign);\n\n            if (padding < 0)\n            {\n                throw new ArgumentOutOfRangeException(\n                    \"padding\",\n                    String.Format(CultureInfo.InvariantCulture, CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, 0));\n            }\n\n            WatermarkTextTransformation transformation =\n                new WatermarkTextTransformation(text, color, fontSize, fontStyleEnum, fontFamilyClass, horizontalAlignEnum, verticalAlignEnum, padding);\n            _transformations.Add(transformation);\n            return this;\n        }\n\n        /// <summary>\n        /// Adds image watermark to an image.\n        /// </summary>\n        /// <param name=\"watermarkImage\">Image to use as a watermark.</param>\n        /// <param name=\"width\">Width of watermark.</param>\n        /// <param name=\"height\">Height of watermark.</param>\n        /// <param name=\"horizontalAlign\">Horizontal alignment for watermark image. Can be \"right\", \"left\", or \"center\".</param>\n        /// <param name=\"verticalAlign\">Vertical alignment for watermark image. Can be \"top\", \"bottom\", or \"middle\".</param>\n        /// <param name=\"opacity\">Watermark text opacity. Should be between 0 and 100.</param>\n        /// <param name=\"padding\">Size of padding around watermark image in pixels.</param>\n        /// <returns>Modified WebImage instance with added watermark.</returns>\n        public WebImage AddImageWatermark(\n            WebImage watermarkImage,\n            int width = 0,\n            int height = 0,\n            string horizontalAlign = \"Right\",\n            string verticalAlign = \"Bottom\",\n            int opacity = 100,\n            int padding = 5)\n        {\n            if (watermarkImage == null)\n            {\n                throw new ArgumentNullException(\"watermarkImage\");\n            }\n\n            if (width < 0)\n            {\n                throw new ArgumentOutOfRangeException(\n                    \"width\",\n                    String.Format(CultureInfo.InvariantCulture, CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, 0));\n            }\n            if (height < 0)\n            {\n                throw new ArgumentOutOfRangeException(\n                    \"height\",\n                    String.Format(CultureInfo.InvariantCulture, CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, 0));\n            }\n            if (((width == 0) && (height > 0)) || ((width > 0) && (height == 0)))\n            {\n                throw new ArgumentException(HelpersResources.WebImage_IncorrectWidthAndHeight);\n            }\n            if ((opacity < 0) || (opacity > 100))\n            {\n                throw new ArgumentOutOfRangeException(\"opacity\", String.Format(CultureInfo.InvariantCulture, CommonResources.Argument_Must_Be_Between, 0, 100));\n            }\n\n            HorizontalAlign horizontalAlignEnum = ParseHorizontalAlign(horizontalAlign);\n            VerticalAlign verticalAlignEnum = ParseVerticalAlign(verticalAlign);\n\n            if (padding < 0)\n            {\n                throw new ArgumentOutOfRangeException(\n                    \"padding\",\n                    String.Format(CultureInfo.InvariantCulture, CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, 0));\n            }\n\n            WatermarkImageTransformation transformation =\n                new WatermarkImageTransformation(watermarkImage.Clone(), width, height, horizontalAlignEnum, verticalAlignEnum, opacity, padding);\n            _transformations.Add(transformation);\n            return this;\n        }\n\n        /// <summary>\n        /// Adds image watermark to an image.\n        /// </summary>\n        /// <param name=\"watermarkImageFilePath\">File to read watermark image from.</param>\n        /// <param name=\"width\">Width of watermark.</param>\n        /// <param name=\"height\">Height of watermark.</param>\n        /// <param name=\"horizontalAlign\">Horizontal alignment for watermark image. Can be \"right\", \"left\", or \"center\".</param>\n        /// <param name=\"verticalAlign\">Vertical alignment for watermark image. Can be \"top\", \"bottom\", or \"middle\".</param>\n        /// <param name=\"opacity\">Watermark text opacity. Should be between 0 and 100.</param>\n        /// <param name=\"padding\">Size of padding around watermark image in pixels.</param>\n        /// <returns>WebImage instance with added watermark.</returns>\n        public WebImage AddImageWatermark(\n            string watermarkImageFilePath,\n            int width = 0,\n            int height = 0,\n            string horizontalAlign = \"Right\",\n            string verticalAlign = \"Bottom\",\n            int opacity = 100,\n            int padding = 5)\n        {\n            return AddImageWatermark(new HttpContextWrapper(HttpContext.Current), _defaultReadAction, watermarkImageFilePath, width, height,\n                                     horizontalAlign, verticalAlign, opacity, padding);\n        }\n\n        internal WebImage AddImageWatermark(\n            HttpContextBase httpContext,\n            Func<string, byte[]> readAction,\n            string watermarkImageFilePath,\n            int width,\n            int height,\n            string horizontalAlign,\n            string verticalAlign,\n            int opacity,\n            int padding)\n        {\n            return AddImageWatermark(new WebImage(httpContext, readAction, watermarkImageFilePath), width, height, horizontalAlign, verticalAlign, opacity, padding);\n        }\n\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1308:NormalizeStringsToUppercase\",\n            Justification = \"No security decision is made based on this string. It's customary to display MIME format in lowercase.\")]\n        public WebImage Write(string requestedFormat = null)\n        {\n            // GetBytes takes care of executing pending transformations and \n            // determining current image format if we didn't have it set before.\n            // todo: this could be made more efficient by avoiding cloning array \n            // when format is same\n            requestedFormat = requestedFormat ?? _initialFormat.ToString();\n            Debug.Assert(requestedFormat != null);\n            byte[] content = GetBytes(requestedFormat);\n\n            string requestedFormatWithPrefix;\n            if (requestedFormat.StartsWith(\"image/\", StringComparison.OrdinalIgnoreCase))\n            {\n                requestedFormatWithPrefix = requestedFormat;\n            }\n            else\n            {\n                requestedFormatWithPrefix = \"image/\" + requestedFormat;\n            }\n\n            HttpResponse response = HttpContext.Current.Response;\n            response.ContentType = requestedFormatWithPrefix;\n            response.BinaryWrite(content);\n\n            return this;\n        }\n\n        /// <param name=\"filePath\">If no filePath is specified, the method falls back to the file name if the image was constructed from a file or \n        /// the file name on the client (the browser machine) if the image was built off GetImageFromRequest\n        /// </param>\n        /// <param name=\"imageFormat\">The format the image is saved in</param>\n        /// <param name=\"forceCorrectExtension\">Appends a well known extension to the filePath based on the imageFormat specified. \n        /// If the filePath uses a valid extension, no change is made.\n        /// e.g. format: \"jpg\", filePath: \"foo.txt\". Image saved at = \"foo.txt.jpeg\"\n        ///      format: \"png\", filePath: \"foo.png\". Image saved at = \"foo.txt.png\"\n        /// </param>\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1308:NormalizeStringsToUppercase\",\n            Justification = \"File extensions are typically specified in lower case.\")]\n        public WebImage Save(string filePath = null, string imageFormat = null, bool forceCorrectExtension = true)\n        {\n            return Save(new HttpContextWrapper(HttpContext.Current), File.WriteAllBytes, filePath, imageFormat, forceCorrectExtension);\n        }\n\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1308:NormalizeStringsToUppercase\", Justification = \"The string is a file extension which is typically lower case\")]\n        internal WebImage Save(HttpContextBase context, Action<string, byte[]> saveAction, string filePath, string imageFormat, bool forceWellKnownExtension)\n        {\n            filePath = filePath ?? FileName;\n            if (String.IsNullOrEmpty(filePath))\n            {\n                throw new ArgumentNullException(\"filePath\", CommonResources.Argument_Cannot_Be_Null_Or_Empty);\n            }\n\n            // GetBytes takes care of executing pending transformations.\n            // todo: this could be made more efficient by avoiding cloning array \n            // when format is same\n            byte[] content = GetBytes(imageFormat);\n            if (forceWellKnownExtension)\n            {\n                ImageFormat saveImageFormat;\n                ImageFormat requestedImageFormat = String.IsNullOrEmpty(imageFormat) ? _initialFormat : GetImageFormat(imageFormat);\n                var extension = Path.GetExtension(filePath).TrimStart('.');\n                // TryFromStringToImageFormat accepts mime types and image names. For images supported by System.Drawing.Imaging, the image name maps to the extension.\n                // Replace the extension with the current format in the following two events:\n                //  * The extension format cannot be converted to a known format\n                //  * The format does not match. \n                if (!ConversionUtil.TryFromStringToImageFormat(extension, out saveImageFormat) || !saveImageFormat.Equals(requestedImageFormat))\n                {\n                    extension = requestedImageFormat.ToString().ToLowerInvariant();\n                    filePath = filePath + \".\" + extension;\n                }\n            }\n            saveAction(VirtualPathUtil.MapPath(context, filePath), content);\n            // Update the FileName since it may have changed whilst saving.\n            FileName = filePath;\n            return this;\n        }\n\n        /// <summary>\n        /// Constructs a System.Drawing.Image instance from the content which validates the contents of the image.\n        /// </summary>\n        /// <exception cref=\"System.ArgumentException\">When an Image construction fails.</exception>\n        private static ImageFormat ValidateImageContent(byte[] content, string paramName)\n        {\n            try\n            {\n                using (MemoryStream stream = new MemoryStream(content))\n                {\n                    using (Image image = Image.FromStream(stream, useEmbeddedColorManagement: false))\n                    {\n                        var rawFormat = image.RawFormat;\n                        ImageFormat actualFormat;\n                        // RawFormat returns a ImageFormat instance with the same Guid as the predefined types \n                        // This instance is not very useful when it comes to printing human readable strings and file extensions.\n                        // Therefore, lookup the predefined instance \n                        if (!_imageFormatLookup.TryGetValue(rawFormat.Guid, out actualFormat))\n                        {\n                            actualFormat = rawFormat;\n                        }\n                        return actualFormat;\n                    }\n                }\n            }\n            catch (ArgumentException exception)\n            {\n                throw new ArgumentException(HelpersResources.WebImage_InvalidImageContents, paramName, exception);\n            }\n        }\n\n        private static ImageFormat GetImageFormat(string format)\n        {\n            Debug.Assert(!String.IsNullOrEmpty(format), \"format cannot be null\");\n\n            ImageFormat result;\n            if (!ConversionUtil.TryFromStringToImageFormat(format, out result))\n            {\n                throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, HelpersResources.Image_IncorrectImageFormat, format), \"format\");\n            }\n\n            return result;\n        }\n\n        private static HorizontalAlign ParseHorizontalAlign(string alignment)\n        {\n            bool conversionOk;\n            HorizontalAlign horizontalAlign;\n            conversionOk = ConversionUtil.TryFromStringToEnum(alignment, out horizontalAlign);\n            if (!conversionOk || (horizontalAlign == HorizontalAlign.Justify) || (horizontalAlign == HorizontalAlign.NotSet))\n            {\n                throw new ArgumentException(HelpersResources.WebImage_IncorrectHorizontalAlignment);\n            }\n            return horizontalAlign;\n        }\n\n        private static VerticalAlign ParseVerticalAlign(string alignment)\n        {\n            bool conversionOk;\n            VerticalAlign verticalAlign;\n            conversionOk = ConversionUtil.TryFromStringToEnum(alignment, out verticalAlign);\n            if (!conversionOk || (verticalAlign == VerticalAlign.NotSet))\n            {\n                throw new ArgumentException(HelpersResources.WebImage_IncorrectVerticalAlignment);\n            }\n            return verticalAlign;\n        }\n\n        private void GetContentFromImageAndUpdateFormat(Image image)\n        {\n            using (MemoryStream buffer = new MemoryStream())\n            {\n                if (image.RawFormat.Equals(Drawing.Imaging.ImageFormat.MemoryBmp))\n                {\n                    // Memory Bmps are an in-memory format and do not have encoders to save to disk / stream. \n                    // Save it in the current format whenever we encounter which ensures we preserve image information such as transparency.\n                    image.Save(buffer, _currentFormat);\n                }\n                else\n                {\n                    // If the RawFormat has an encoder, save it as-is to prevent the cost of encoding it to another format such as the initial or current format. \n                    image.Save(buffer, image.RawFormat);\n                    _currentFormat = image.RawFormat;\n                }\n\n                _content = buffer.ToArray();\n            }\n        }\n\n        private void ApplyTransformationsAndSetProperties()\n        {\n            Debug.Assert(_content != null, \"Incorrectly constructed instance.\");\n\n            MemoryStream stream = null;\n            Image image = null;\n            try\n            {\n                stream = new MemoryStream(_content);\n                image = Image.FromStream(stream);\n\n                if (_properties == null)\n                {\n                    // makes sure properties is never null after initialization\n                    _properties = image.PropertyItems ?? new PropertyItem[0];\n                }\n\n                foreach (ImageTransformation trans in _transformations)\n                {\n                    Image tempImage = trans.ApplyTransformation(image);\n\n                    // ApplyTransformation could return the same image if no transformations are made or if\n                    // transformations are made on the image itself.\n                    if (tempImage != image)\n                    {\n                        if (stream != null)\n                        {\n                            stream.Dispose();\n                            stream = null;\n                        }\n\n                        Debug.Assert((image != null) && (tempImage != null), \"Image instances should not be null.\");\n                        image.Dispose();\n                        image = tempImage;\n                    }\n\n                    // This is just to keep FxCop happy. Otherwise it thinks that tempImage could be diposed twice.\n                    tempImage = null;\n                }\n\n                // If there were any transformations we need to get new content. This will also update the current format to the RawFormat.\n                if (_transformations.Any())\n                {\n                    GetContentFromImageAndUpdateFormat(image);\n                    _transformations.Clear();\n                }\n\n                _height = image.Size.Height;\n                _width = image.Size.Width;\n            }\n            finally\n            {\n                if (image != null)\n                {\n                    image.Dispose();\n                }\n                if (stream != null)\n                {\n                    stream.Dispose();\n                }\n            }\n        }\n\n        /// <remarks>Caller has to dispose of returned Bitmap object.</remarks>\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\",\n            Justification = \"Callers of this method are responsible for disposing returned Bitmap\")]\n        private static Bitmap GetBitmapFromImage(Image image, int width, int height, bool preserveResolution = true)\n        {\n            bool indexed = (image.PixelFormat == PixelFormat.Format1bppIndexed ||\n                            image.PixelFormat == PixelFormat.Format4bppIndexed ||\n                            image.PixelFormat == PixelFormat.Format8bppIndexed ||\n                            image.PixelFormat == PixelFormat.Indexed);\n\n            Bitmap bitmap = indexed ? new Bitmap(width, height) : new Bitmap(width, height, image.PixelFormat);\n            if (preserveResolution)\n            {\n                bitmap.SetResolution(image.HorizontalResolution, image.VerticalResolution);\n            }\n            else\n            {\n                bitmap.SetResolution(FixedResolution, FixedResolution);\n            }\n\n            using (Graphics graphic = Graphics.FromImage(bitmap))\n            {\n                if (indexed)\n                {\n                    graphic.FillRectangle(Brushes.White, 0, 0, width, height);\n                }\n                graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;\n                graphic.DrawImage(image, 0, 0, width, height);\n            }\n\n            return bitmap;\n        }\n\n        private static void CopyMetadata(PropertyItem[] properties, Image target)\n        {\n            foreach (PropertyItem property in properties)\n            {\n                try\n                {\n                    target.SetPropertyItem(property);\n                }\n                catch (ArgumentException)\n                {\n                    // just ignore it; on some configurations this fails\n                }\n            }\n        }\n\n        private class CropTransformation : ImageTransformation\n        {\n            public CropTransformation(int top, int right, int bottom, int left)\n            {\n                Top = top;\n                Right = right;\n                Bottom = bottom;\n                Left = left;\n            }\n\n            public int Top { get; set; }\n            public int Right { get; set; }\n            public int Bottom { get; set; }\n            public int Left { get; set; }\n\n            public override Image ApplyTransformation(Image image)\n            {\n                if ((Top + Bottom > image.Height) || (Left + Right > image.Width))\n                {\n                    // If Crop arguments are too big (i.e. whole image is cropped) we don't make any changes. \n                    return image;\n                }\n\n                int width = image.Width - (Left + Right);\n                int height = image.Height - (Top + Bottom);\n\n                RectangleF rect = new RectangleF(Left, Top, width, height);\n\n                // todo: check if we can guarantee that rect is inside the image at this point\n                using (Bitmap bitmap = GetBitmapFromImage(image, image.Width, image.Height))\n                {\n                    try\n                    {\n                        return bitmap.Clone(rect, image.PixelFormat);\n                    }\n                    catch (OutOfMemoryException)\n                    {\n                        // Bitmap.Clone unfortunately throws OOM exception when rect is \n                        // outside of the source bitmap bounds\n                        return image;\n                    }\n                }\n            }\n        }\n\n        private abstract class ImageTransformation\n        {\n            public abstract Image ApplyTransformation(Image image);\n        }\n\n        private class ResizeTransformation : ImageTransformation\n        {\n            public ResizeTransformation(int height, int width, bool preserveAspectRatio, bool preventEnlarge)\n            {\n                Height = height;\n                Width = width;\n                PreserveAspectRatio = preserveAspectRatio;\n                PreventEnlarge = preventEnlarge;\n            }\n\n            public int Height { get; set; }\n            public int Width { get; set; }\n            public bool PreserveAspectRatio { get; set; }\n            public bool PreventEnlarge { get; set; }\n\n            public override Image ApplyTransformation(Image image)\n            {\n                int height = Height;\n                int width = Width;\n\n                if (PreserveAspectRatio)\n                {\n                    double heightRatio = (height * 100.0) / image.Height;\n                    double widthRatio = (width * 100.0) / image.Width;\n                    if (heightRatio > widthRatio)\n                    {\n                        height = (int)Math.Round((widthRatio * image.Height) / 100);\n                    }\n                    else if (heightRatio < widthRatio)\n                    {\n                        width = (int)Math.Round((heightRatio * image.Width) / 100);\n                    }\n                }\n\n                if (PreventEnlarge)\n                {\n                    if (height > image.Height)\n                    {\n                        height = image.Height;\n                    }\n                    if (width > image.Width)\n                    {\n                        width = image.Width;\n                    }\n                }\n\n                if ((image.Height == height) && (image.Width == width))\n                {\n                    return image;\n                }\n\n                return GetBitmapFromImage(image, width, height);\n            }\n        }\n\n        private class RotateTransformation : ImageTransformation\n        {\n            public RotateTransformation(RotateFlipType direction)\n            {\n                Direction = direction;\n            }\n\n            public RotateFlipType Direction { get; set; }\n\n            public override Image ApplyTransformation(Image image)\n            {\n                image.RotateFlip(Direction);\n                return image;\n            }\n        }\n\n        private class WatermarkImageTransformation : WatermarkTransformation\n        {\n            public WatermarkImageTransformation(\n                WebImage image,\n                int width,\n                int height,\n                HorizontalAlign horizontalAlign,\n                VerticalAlign verticalAlign,\n                int opacity,\n                int padding)\n                : base(horizontalAlign, verticalAlign, padding)\n            {\n                WatermarkImage = image;\n                Width = width;\n                Height = height;\n                Opacity = opacity;\n            }\n\n            public WebImage WatermarkImage { get; set; }\n            public int Width { get; set; }\n            public int Height { get; set; }\n            public int Opacity { get; set; }\n\n            public override Image ApplyTransformation(Image image)\n            {\n                // Use original image dimensions if user didn't specify any.\n                if (Width == 0)\n                {\n                    Debug.Assert(Height == 0, \"If one dimension is zero the other one must be too.\");\n                    Width = WatermarkImage.Width;\n                    Height = WatermarkImage.Height;\n                }\n\n                if (((Padding * 2) + Width >= image.Width) || ((Padding * 2) + Height >= image.Height))\n                {\n                    // If watermark image + padding is too big we don't make any changes. \n                    return image;\n                }\n\n                WatermarkImage.Resize(Width, Height, preserveAspectRatio: false, preventEnlarge: false);\n                float alphaScaling = ((float)Opacity) / 100;\n\n                byte[] watermarkBuffer = WatermarkImage.GetBytes();\n                Rectangle rect = GetRectangleInsideImage(image, Width, Height);\n\n                using (Graphics targetGraphics = Graphics.FromImage(image))\n                {\n                    using (MemoryStream memStream = new MemoryStream(watermarkBuffer))\n                    {\n                        using (Image watermarkImage = Image.FromStream(memStream))\n                        {\n                            AddWatermark(targetGraphics, watermarkImage, rect, alphaScaling);\n                        }\n                    }\n                }\n\n                return image;\n            }\n        }\n\n        private class WatermarkTextTransformation : WatermarkTransformation\n        {\n            public WatermarkTextTransformation(\n                string text,\n                Color fontColor,\n                int fontSize,\n                FontStyle fontStyle,\n                FontFamily fontFamily,\n                HorizontalAlign alignX,\n                VerticalAlign alignY,\n                int padding)\n                : base(alignX, alignY, padding)\n            {\n                Text = text;\n                FontColor = fontColor;\n                FontSize = fontSize;\n                FontStyle = fontStyle;\n                FontFamily = fontFamily;\n            }\n\n            public string Text { get; set; }\n            public Color FontColor { get; set; }\n            public int FontSize { get; set; }\n            public FontStyle FontStyle { get; set; }\n            public FontFamily FontFamily { get; set; }\n\n            public override Image ApplyTransformation(Image image)\n            {\n                if ((Padding * 2 >= image.Width) || (Padding * 2 >= image.Height))\n                {\n                    // If padding is too big we don't make any changes. \n                    return image;\n                }\n\n                // Get font size and text area that text fits into using fixed size resolution version of the image.\n                // This is needed so we create the same size/position text watermark even when images have different\n                // resolutions. Otherwise, watermark is slightly different even when text & size arguments are the same.\n                int fontSize;\n                SizeF textArea;\n                using (Bitmap fixedResolutionImage = GetBitmapFromImage(image, image.Width, image.Height, preserveResolution: false))\n                {\n                    using (Graphics graphics = Graphics.FromImage(fixedResolutionImage))\n                    {\n                        fontSize = GetBestFontSize(image, graphics, out textArea);\n                    }\n                }\n\n                int textWidth = (int)Math.Ceiling(textArea.Width);\n                int textHeight = (int)Math.Ceiling(textArea.Height);\n                Rectangle area = GetRectangleInsideImage(image, textWidth, textHeight);\n\n                // Create new bitmap that only contains text in the right size.\n                using (Bitmap textBitmap = new Bitmap(textWidth, textHeight))\n                {\n                    using (Graphics graphics = Graphics.FromImage(textBitmap))\n                    {\n                        using (Font font = new Font(FontFamily, fontSize, FontStyle))\n                        {\n                            using (Brush brushToUse = new SolidBrush(FontColor))\n                            {\n                                graphics.TextRenderingHint = TextRenderingHint.AntiAlias;\n                                graphics.DrawString(Text, font, brushToUse, new PointF(0F, 0F));\n                            }\n                        }\n                    }\n\n                    // Use generated bitmap with text to apply as image watermark.\n                    using (Graphics targetGraphics = Graphics.FromImage(image))\n                    {\n                        AddWatermark(targetGraphics, textBitmap, area, 1f);\n                    }\n                }\n\n                return image;\n            }\n\n            private int GetBestFontSize(Image image, Graphics graphics, out SizeF textArea)\n            {\n                SizeF layoutArea = new SizeF(image.Width - (Padding * 2), image.Height - (Padding * 2));\n                int bestFontSize = FontSize;\n                textArea = layoutArea;\n\n                using (StringFormat format = new StringFormat(StringFormatFlags.NoClip | StringFormatFlags.MeasureTrailingSpaces))\n                {\n                    for (int fontSize = FontSize; fontSize >= 2; fontSize--)\n                    {\n                        int numChars = 0, numLines = 0;\n                        using (Font font = new Font(FontFamily, fontSize, FontStyle))\n                        {\n                            textArea = graphics.MeasureString(Text, font, layoutArea, format, out numChars, out numLines);\n                        }\n\n                        if ((numChars >= Text.Length) && (textArea.Width <= layoutArea.Width) && (textArea.Height <= layoutArea.Height))\n                        {\n                            // it fits! Exit now\n                            return fontSize;\n                        }\n                        else\n                        {\n                            bestFontSize = fontSize;\n                        }\n                    }\n                }\n                return bestFontSize;\n            }\n        }\n\n        private abstract class WatermarkTransformation : ImageTransformation\n        {\n            private static readonly float[][] _identityScalingMatrix =\n                {\n                    new float[] { 1, 0, 0, 0, 0 },\n                    new float[] { 0, 1, 0, 0, 0 },\n                    new float[] { 0, 0, 1, 0, 0 },\n                    new float[] { 0, 0, 0, 1, 0 },\n                    new float[] { 0, 0, 0, 0, 1 }\n                };\n\n            public WatermarkTransformation(HorizontalAlign alignX, VerticalAlign alignY, int padding)\n            {\n                HorizontalAlign = alignX;\n                VerticalAlign = alignY;\n                Padding = padding;\n            }\n\n            public HorizontalAlign HorizontalAlign { get; set; }\n            public VerticalAlign VerticalAlign { get; set; }\n            public int Padding { get; set; }\n\n            public Rectangle GetRectangleInsideImage(Image image, int width, int height)\n            {\n                int posX, posY;\n\n                switch (HorizontalAlign)\n                {\n                    case HorizontalAlign.Left:\n                        posX = Padding;\n                        break;\n                    case HorizontalAlign.Right:\n                        posX = image.Width - width - Padding;\n                        break;\n                    case HorizontalAlign.Center:\n                    default:\n                        posX = (image.Width - width) / 2;\n                        break;\n                }\n                switch (VerticalAlign)\n                {\n                    case VerticalAlign.Top:\n                        posY = Padding;\n                        break;\n                    case VerticalAlign.Bottom:\n                        posY = image.Height - height - Padding;\n                        break;\n                    case VerticalAlign.Middle:\n                    default:\n                        posY = (image.Height - height) / 2;\n                        break;\n                }\n\n                return new Rectangle(posX, posY, width, height);\n            }\n\n            private static float[][] GetScalingMatrix(float alphaScaling)\n            {\n                if (alphaScaling == 1)\n                {\n                    return _identityScalingMatrix;\n                }\n\n                float[][] scalingMatrix =\n                    {\n                        new float[] { 1, 0, 0, 0, 0 },\n                        new float[] { 0, 1, 0, 0, 0 },\n                        new float[] { 0, 0, 1, 0, 0 },\n                        new[] { 0, 0, 0, alphaScaling, 0 },\n                        new float[] { 0, 0, 0, 0, 1 }\n                    };\n                return scalingMatrix;\n            }\n\n            public static void AddWatermark(Graphics targetGraphics, Image watermark, Rectangle rect, float alphaScaling)\n            {\n                float[][] scalingMatrix = GetScalingMatrix(alphaScaling);\n                ColorMatrix colorMatrix = new ColorMatrix(scalingMatrix);\n\n                using (ImageAttributes imageAtt = new ImageAttributes())\n                {\n                    imageAtt.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Default);\n                    targetGraphics.DrawImage(watermark, rect, 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAtt);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Helpers/WebMail.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.IO;\nusing System.Net;\nusing System.Net.Mail;\nusing System.Text;\nusing System.Web.Helpers.Resources;\nusing System.Web.WebPages.Scope;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Helpers\n{\n    [SuppressMessage(\"Microsoft.Naming\", \"CA1702:CompoundWordsShouldBeCasedCorrectly\", MessageId = \"WebMail\", Justification = \"The name of this class is consistent with the naming convention followed in other helpers\")]\n    public static class WebMail\n    {\n        internal static readonly object SmtpServerKey = new object();\n        internal static readonly object SmtpPortKey = new object();\n        internal static readonly object SmtpUseDefaultCredentialsKey = new object();\n        internal static readonly object EnableSslKey = new object();\n        internal static readonly object PasswordKey = new object();\n        internal static readonly object UserNameKey = new object();\n        internal static readonly object FromKey = new object();\n        internal static readonly Lazy<IDictionary<object, object>> SmtpDefaults = new Lazy<IDictionary<object, object>>(ReadSmtpDefaults);\n\n        /// <summary>\n        /// MailMessage dictates that headers values that have equivalent properties would be discarded or overwritten. The list of values is available at \n        /// http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.aspx\n        /// </summary>\n        private static readonly Dictionary<string, Action<MailMessage, string>> _actionableHeaders = new Dictionary<string, Action<MailMessage, string>>(StringComparer.OrdinalIgnoreCase)\n        {\n            { \"Bcc\", (message, value) => message.Bcc.Add(value) },\n            { \"Cc\", (message, value) => message.CC.Add(value) },\n            { \"From\", (mailMessage, value) =>\n            {\n                mailMessage.From = new MailAddress(value);\n            }\n                },\n            { \"Priority\", SetPriority },\n            { \"Reply-To\", (mailMessage, value) =>\n            {\n                mailMessage.ReplyToList.Add(value);\n            }\n                },\n            { \"Sender\", (mailMessage, value) =>\n            {\n                mailMessage.Sender = new MailAddress(value);\n            }\n                },\n            { \"To\", (mailMessage, value) =>\n            {\n                mailMessage.To.Add(value);\n            }\n                },\n        };\n\n        ///////////////////////////////////////////////////////////////////////////\n        // Public Properties\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2208:InstantiateArgumentExceptionsCorrectly\", Justification = \"SmtpServer is more descriptive as compared to the actual argument \\\"value\\\"\")]\n        public static string SmtpServer\n        {\n            get { return ReadValue<string>(SmtpServerKey); }\n            set\n            {\n                if (String.IsNullOrEmpty(value))\n                {\n                    throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"SmtpServer\");\n                }\n                ScopeStorage.CurrentScope[SmtpServerKey] = value;\n            }\n        }\n\n        public static int SmtpPort\n        {\n            get { return ReadValue<int>(SmtpPortKey); }\n            set { ScopeStorage.CurrentScope[SmtpPortKey] = value; }\n        }\n\n        public static string From\n        {\n            get { return ReadValue<string>(FromKey); }\n            set { ScopeStorage.CurrentScope[FromKey] = value; }\n        }\n\n        public static bool SmtpUseDefaultCredentials\n        {\n            get { return ReadValue<bool>(SmtpUseDefaultCredentialsKey); }\n            set { ScopeStorage.CurrentScope[SmtpUseDefaultCredentialsKey] = value; }\n        }\n\n        public static bool EnableSsl\n        {\n            get { return ReadValue<bool>(EnableSslKey); }\n            set { ScopeStorage.CurrentScope[EnableSslKey] = value; }\n        }\n\n        public static string UserName\n        {\n            get { return ReadValue<string>(UserNameKey); }\n            set { ScopeStorage.CurrentScope[UserNameKey] = value; }\n        }\n\n        public static string Password\n        {\n            get { return ReadValue<string>(PasswordKey); }\n            set { ScopeStorage.CurrentScope[PasswordKey] = value; }\n        }\n\n        public static void Send(string to,\n                                string subject,\n                                string body,\n                                string from = null,\n                                string cc = null,\n                                IEnumerable<string> filesToAttach = null,\n                                bool isBodyHtml = true,\n                                IEnumerable<string> additionalHeaders = null,\n                                string bcc = null,\n                                string contentEncoding = null,\n                                string headerEncoding = null,\n                                string priority = null,\n                                string replyTo = null)\n        {\n            if (filesToAttach != null)\n            {\n                foreach (string fileName in filesToAttach)\n                {\n                    if (String.IsNullOrEmpty(fileName))\n                    {\n                        throw new ArgumentException(HelpersResources.WebMail_ItemInCollectionIsNull, \"filesToAttach\");\n                    }\n                }\n            }\n\n            if (additionalHeaders != null)\n            {\n                foreach (string header in additionalHeaders)\n                {\n                    if (String.IsNullOrEmpty(header))\n                    {\n                        throw new ArgumentException(HelpersResources.WebMail_ItemInCollectionIsNull, \"additionalHeaders\");\n                    }\n                }\n            }\n\n            MailPriority priorityValue = MailPriority.Normal;\n            if (!String.IsNullOrEmpty(priority) && !ConversionUtil.TryFromStringToEnum(priority, out priorityValue))\n            {\n                throw new ArgumentException(HelpersResources.WebMail_InvalidPriority, \"priority\");\n            }\n\n            if (String.IsNullOrEmpty(SmtpServer))\n            {\n                throw new InvalidOperationException(HelpersResources.WebMail_SmtpServerNotSpecified);\n            }\n\n            using (MailMessage message = new MailMessage())\n            {\n                SetPropertiesOnMessage(message, to, subject, body, from, cc, bcc, replyTo, contentEncoding, headerEncoding, priorityValue,\n                                       filesToAttach, isBodyHtml, additionalHeaders);\n                using (SmtpClient client = new SmtpClient())\n                {\n                    SetPropertiesOnClient(client);\n                    client.Send(message);\n                }\n            }\n        }\n\n        private static TValue ReadValue<TValue>(object key)\n        {\n            return (TValue)(ScopeStorage.CurrentScope[key] ?? SmtpDefaults.Value[key]);\n        }\n\n        private static IDictionary<object, object> ReadSmtpDefaults()\n        {\n            Dictionary<object, object> smtpDefaults = new Dictionary<object, object>();\n            try\n            {\n                // Create a new SmtpClient object: this will read config & tell us what the default value is\n                using (SmtpClient client = new SmtpClient())\n                {\n                    smtpDefaults[SmtpServerKey] = client.Host;\n                    smtpDefaults[SmtpPortKey] = client.Port;\n                    smtpDefaults[EnableSslKey] = client.EnableSsl;\n                    smtpDefaults[SmtpUseDefaultCredentialsKey] = client.UseDefaultCredentials;\n\n                    var credentials = client.Credentials as NetworkCredential;\n                    if (credentials != null)\n                    {\n                        smtpDefaults[UserNameKey] = credentials.UserName;\n                        smtpDefaults[PasswordKey] = credentials.Password;\n                    }\n                    else\n                    {\n                        smtpDefaults[UserNameKey] = null;\n                        smtpDefaults[PasswordKey] = null;\n                    }\n                    using (MailMessage message = new MailMessage())\n                    {\n                        smtpDefaults[FromKey] = (message.From != null) ? message.From.Address : null;\n                    }\n                }\n            }\n            catch (InvalidOperationException)\n            {\n                // Due to Bug Dev10 PS 337470 (\"SmtpClient reports InvalidOperationException when disposed\"), we need to ignore the spurious InvalidOperationException\n            }\n            return smtpDefaults;\n        }\n\n        internal static void SetPropertiesOnClient(SmtpClient client)\n        {\n            // If no value has been assigned to these properties, at the very worst we will simply \n            // write back the values we just read from the SmtpClient\n            if (SmtpServer != null)\n            {\n                client.Host = SmtpServer;\n            }\n            client.Port = SmtpPort;\n            client.UseDefaultCredentials = SmtpUseDefaultCredentials;\n            client.EnableSsl = EnableSsl;\n            if (!String.IsNullOrEmpty(UserName))\n            {\n                client.Credentials = new NetworkCredential(UserName, Password);\n            }\n        }\n\n        internal static void SetPropertiesOnMessage(MailMessage message, string to, string subject,\n                                                    string body, string from, string cc, string bcc, string replyTo,\n                                                    string contentEncoding, string headerEncoding, MailPriority priority,\n                                                    IEnumerable<string> filesToAttach, bool isBodyHtml,\n                                                    IEnumerable<string> additionalHeaders)\n        {\n            message.Subject = subject;\n            message.Body = body;\n            message.IsBodyHtml = isBodyHtml;\n\n            if (additionalHeaders != null)\n            {\n                AssignHeaderValues(message, additionalHeaders);\n            }\n\n            if (to != null)\n            {\n                message.To.Add(to);\n            }\n\n            if (!String.IsNullOrEmpty(cc))\n            {\n                message.CC.Add(cc);\n            }\n\n            if (!String.IsNullOrEmpty(bcc))\n            {\n                message.Bcc.Add(bcc);\n            }\n\n            if (!String.IsNullOrEmpty(replyTo))\n            {\n                message.ReplyToList.Add(replyTo);\n            }\n\n            if (!String.IsNullOrEmpty(contentEncoding))\n            {\n                message.BodyEncoding = Encoding.GetEncoding(contentEncoding);\n            }\n\n            if (!String.IsNullOrEmpty(headerEncoding))\n            {\n                message.HeadersEncoding = Encoding.GetEncoding(headerEncoding);\n            }\n\n            message.Priority = priority;\n\n            if (from != null)\n            {\n                message.From = new MailAddress(from);\n            }\n            else if (!String.IsNullOrEmpty(From))\n            {\n                message.From = new MailAddress(From);\n            }\n            else if (message.From == null || String.IsNullOrEmpty(message.From.Address))\n            {\n                var httpContext = HttpContext.Current;\n                if (httpContext != null)\n                {\n                    message.From = new MailAddress(\"DoNotReply@\" + httpContext.Request.Url.Host);\n                }\n                else\n                {\n                    throw new InvalidOperationException(HelpersResources.WebMail_UnableToDetermineFrom);\n                }\n            }\n\n            if (filesToAttach != null)\n            {\n                foreach (string file in filesToAttach)\n                {\n                    if (!Path.IsPathRooted(file) && HttpRuntime.AppDomainAppPath != null)\n                    {\n                        message.Attachments.Add(new Attachment(Path.Combine(HttpRuntime.AppDomainAppPath, file)));\n                    }\n                    else\n                    {\n                        message.Attachments.Add(new Attachment(file));\n                    }\n                }\n            }\n        }\n\n        internal static void AssignHeaderValues(MailMessage message, IEnumerable<string> headerValues)\n        {\n            // Parse the header value. If this \n            foreach (var header in headerValues)\n            {\n                string key, value;\n                if (TryParseHeader(header, out key, out value))\n                {\n                    // Verify if the header key maps to a property on MailMessage. \n                    Action<MailMessage, string> action;\n                    if (_actionableHeaders.TryGetValue(key, out action))\n                    {\n                        try\n                        {\n                            action(message, value);\n                        }\n                        catch (FormatException)\n                        {\n                            // If the mail address is invalid, swallow the exception.\n                        }\n                    }\n                    message.Headers.Add(key, value);\n                }\n            }\n        }\n\n        /// <summary>\n        /// Parses a SMTP Mail header of the format \"name: value\"\n        /// </summary>\n        /// <returns>True if the header was parsed.</returns>\n        internal static bool TryParseHeader(string header, out string key, out string value)\n        {\n            int pos = header.IndexOf(':');\n            if (pos > 0)\n            {\n                key = header.Substring(0, pos).TrimEnd();\n                value = header.Substring(pos + 1).TrimStart();\n                return key.Length > 0 && value.Length > 0;\n            }\n            key = null;\n            value = null;\n            return false;\n        }\n\n        private static void SetPriority(MailMessage message, string priority)\n        {\n            MailPriority priorityValue;\n            if (!String.IsNullOrEmpty(priority) && ConversionUtil.TryFromStringToEnum(priority, out priorityValue))\n            {\n                // If we can parse it, set it. Do nothing otherwise\n                message.Priority = priorityValue;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/AcceptVerbsAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Specifies what HTTP methods an action supports.\n    /// </summary>\n    [SuppressMessage(\"Microsoft.Design\", \"CA1019:DefineAccessorsForAttributeArguments\", Justification = \"The accessor is exposed as an Collection<HttpMethod>.\")]\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\n    public sealed class AcceptVerbsAttribute : Attribute, IActionHttpMethodProvider\n    {\n        private readonly Collection<HttpMethod> _httpMethods;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"AcceptVerbsAttribute\" /> class.        \n        /// </summary>\n        /// <param name=\"method\">The HTTP method the action supports.</param>\n        /// <remarks>\n        /// This is a CLS compliant constructor.\n        /// </remarks>\n        public AcceptVerbsAttribute(string method)\n            : this(new string[] { method })\n        {\n        }\n        \n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"AcceptVerbsAttribute\" /> class.\n        /// </summary>\n        /// <param name=\"methods\">The HTTP methods the action supports.</param>\n        /// <remarks>\n        /// This constructor is not CLS-compliant.\n        /// </remarks>\n        public AcceptVerbsAttribute(params string[] methods)\n        {\n            _httpMethods = methods != null\n                                   ? new Collection<HttpMethod>(methods.Select(method => HttpMethodHelper.GetHttpMethod(method)).ToArray())\n                                   : new Collection<HttpMethod>(new HttpMethod[0]);\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"AcceptVerbsAttribute\" /> class.\n        /// </summary>\n        /// <param name=\"methods\">The HTTP methods the action supports.</param>\n        internal AcceptVerbsAttribute(params HttpMethod[] methods)\n        {\n            _httpMethods = new Collection<HttpMethod>(methods);\n        }\n\n        /// <summary>\n        /// Gets the HTTP methods the action supports.\n        /// </summary>\n        public Collection<HttpMethod> HttpMethods\n        {\n            get\n            {\n                return _httpMethods;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ActionNameAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http\n{\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\n    public sealed class ActionNameAttribute : Attribute\n    {\n        public ActionNameAttribute(string name)\n        {\n            Name = name;\n        }\n\n        public string Name { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/AllowAnonymousAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Actions and controllers marked with this attribute are skipped by <see cref=\"AuthorizeAttribute\"/> during authorization.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = false)]\n    public sealed class AllowAnonymousAttribute : Attribute\n    {\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ApiController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Security.Principal;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Results;\nusing System.Web.Http.Routing;\nusing System.Web.Http.Validation;\nusing Newtonsoft.Json;\n\nnamespace System.Web.Http\n{\n    public abstract class ApiController : IHttpController, IDisposable\n    {\n        private HttpActionContext _actionContext = new HttpActionContext();\n        private bool _initialized;\n\n        /// <summary>Gets the configuration.</summary>\n        /// <remarks>The setter is intended for unit testing purposes only.</remarks>\n        public HttpConfiguration Configuration\n        {\n            get { return ControllerContext.Configuration; }\n            set { ControllerContext.Configuration = value; }\n        }\n\n        /// <summary>Gets the controller context.</summary>\n        /// <remarks>The setter is intended for unit testing purposes only.</remarks>\n        public HttpControllerContext ControllerContext\n        {\n            get\n            {\n                // unit test only\n                if (ActionContext.ControllerContext == null)\n                {\n                    ActionContext.ControllerContext = new HttpControllerContext\n                    {\n                        RequestContext = new RequestBackedHttpRequestContext()\n                    };\n                }\n                return ActionContext.ControllerContext;\n            }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n\n                ActionContext.ControllerContext = value;\n            }\n        }\n\n        /// <summary>Gets the action context.</summary>\n        /// <remarks>The setter is intended for unit testing purposes only.</remarks>\n        public HttpActionContext ActionContext\n        {\n            get { return _actionContext; }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n                _actionContext = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets model state after the model binding process. This ModelState will be empty before model binding happens.\n        /// </summary>\n        /// <remarks>The setter is intended for unit testing purposes only.</remarks>\n        public ModelStateDictionary ModelState\n        {\n            get\n            {\n                return ActionContext.ModelState;\n            }\n        }\n\n        /// <summary>Gets or sets the HTTP request message.</summary>\n        /// <remarks>The setter is intended for unit testing purposes only.</remarks>\n        public HttpRequestMessage Request\n        {\n            get\n            {\n                return ControllerContext.Request;\n            }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n\n                HttpRequestContext contextOnRequest = value.GetRequestContext();\n                HttpRequestContext contextOnController = RequestContext;\n\n                if (contextOnRequest != null && contextOnRequest != contextOnController)\n                {\n                    // Prevent unit testers from setting conflicting requests contexts.\n                    throw new InvalidOperationException(SRResources.RequestContextConflict);\n                }\n\n                ControllerContext.Request = value;\n                value.SetRequestContext(contextOnController);\n\n                RequestBackedHttpRequestContext requestBackedContext =\n                    contextOnController as RequestBackedHttpRequestContext;\n\n                if (requestBackedContext != null)\n                {\n                    requestBackedContext.Request = value;\n                }\n            }\n        }\n\n        /// <summary>Gets the request context.</summary>\n        /// <remarks>The setter is intended for unit testing purposes only.</remarks>\n        public HttpRequestContext RequestContext\n        {\n            get\n            {\n                return ControllerContext.RequestContext;\n            }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n\n                HttpRequestContext oldContext = ControllerContext.RequestContext;\n                HttpRequestMessage request = Request;\n\n                if (request != null)\n                {\n                    HttpRequestContext contextOnRequest = request.GetRequestContext();\n\n                    if (contextOnRequest != null && contextOnRequest != oldContext && contextOnRequest != value)\n                    {\n                        // Prevent unit testers from setting conflicting requests contexts.\n                        throw new InvalidOperationException(SRResources.RequestContextConflict);\n                    }\n\n                    request.SetRequestContext(value);\n                }\n\n                ControllerContext.RequestContext = value;\n            }\n        }\n\n        /// <summary>Gets a factory used to generate URLs to other APIs.</summary>\n        /// <remarks>The setter is intended for unit testing purposes only.</remarks>\n        public UrlHelper Url\n        {\n            get { return RequestContext.Url; }\n            set { RequestContext.Url = value; }\n        }\n\n        /// <summary>Gets or sets the current principal associated with this request.</summary>\n        /// <remarks>The setter is intended for unit testing purposes only.</remarks>\n        public IPrincipal User\n        {\n            get { return RequestContext.Principal; }\n            set { RequestContext.Principal = value; }\n        }\n\n        [SuppressMessage(\"Microsoft.Maintainability\", \"CA1506:AvoidExcessiveClassCoupling\", Justification = \"This method is a coordinator, so this coupling is expected.\")]\n        public virtual Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)\n        {\n            if (_initialized)\n            {\n                // if user has registered a controller factory which produces the same controller instance, we should throw here\n                throw Error.InvalidOperation(SRResources.CannotSupportSingletonInstance, typeof(ApiController).Name, typeof(IHttpControllerActivator).Name);\n            }\n\n            Initialize(controllerContext);\n\n            // We can't be reused, and we know we're disposable, so make sure we go away when\n            // the request has been completed.\n            if (Request != null)\n            {\n                Request.RegisterForDispose(this);\n            }\n\n            HttpControllerDescriptor controllerDescriptor = controllerContext.ControllerDescriptor;\n            ServicesContainer controllerServices = controllerDescriptor.Configuration.Services;\n\n            HttpActionDescriptor actionDescriptor = controllerServices.GetActionSelector().SelectAction(controllerContext);\n            ActionContext.ActionDescriptor = actionDescriptor;\n            if (Request != null)\n            {\n                Request.SetActionDescriptor(actionDescriptor);\n            }\n\n            FilterGrouping filterGrouping = actionDescriptor.GetFilterGrouping();\n\n            IActionFilter[] actionFilters = filterGrouping.ActionFilters;\n            IAuthenticationFilter[] authenticationFilters = filterGrouping.AuthenticationFilters;\n            IAuthorizationFilter[] authorizationFilters = filterGrouping.AuthorizationFilters;\n            IExceptionFilter[] exceptionFilters = filterGrouping.ExceptionFilters;\n\n            IHttpActionResult result = new ActionFilterResult(actionDescriptor.ActionBinding, ActionContext,\n                controllerServices, actionFilters);\n            if (authorizationFilters.Length > 0)\n            {\n                result = new AuthorizationFilterResult(ActionContext, authorizationFilters, result);\n            }\n            if (authenticationFilters.Length > 0)\n            {\n                result = new AuthenticationFilterResult(ActionContext, this, authenticationFilters, result);\n            }\n            if (exceptionFilters.Length > 0)\n            {\n                IExceptionLogger exceptionLogger = ExceptionServices.GetLogger(controllerServices);\n                IExceptionHandler exceptionHandler = ExceptionServices.GetHandler(controllerServices);\n                result = new ExceptionFilterResult(ActionContext, exceptionFilters, exceptionLogger, exceptionHandler,\n                    result);\n            }\n\n            return result.ExecuteAsync(cancellationToken);\n        }\n\n        /// <summary>\n        /// Validates the given entity and adds the validation errors to the <see cref=\"ApiController.ModelState\"/>\n        /// under the empty prefix, if any.\n        /// </summary>\n        /// <typeparam name=\"TEntity\">The type of the entity to be validated.</typeparam>\n        /// <param name=\"entity\">The entity being validated.</param>\n        public void Validate<TEntity>(TEntity entity)\n        {\n            Validate(entity, keyPrefix: String.Empty);\n        }\n\n        /// <summary>\n        /// Validates the given entity and adds the validation errors to the <see cref=\"ApiController.ModelState\"/>, if any.\n        /// </summary>\n        /// <typeparam name=\"TEntity\">The type of the entity to be validated.</typeparam>\n        /// <param name=\"entity\">The entity being validated.</param>\n        /// <param name=\"keyPrefix\">\n        /// The key prefix under which the model state errors would be added in the <see cref=\"ApiController.ModelState\"/>.\n        /// </param>\n        public void Validate<TEntity>(TEntity entity, string keyPrefix)\n        {\n            if (Configuration == null)\n            {\n                throw Error.InvalidOperation(SRResources.TypePropertyMustNotBeNull, typeof(ApiController).Name, \"Configuration\");\n            }\n\n            IBodyModelValidator validator = Configuration.Services.GetBodyModelValidator();\n            if (validator != null)\n            {\n                ModelMetadataProvider metadataProvider = Configuration.Services.GetModelMetadataProvider();\n                Contract.Assert(metadataProvider != null, \"GetModelMetadataProvider throws on null.\");\n\n                validator.Validate(entity, typeof(TEntity), metadataProvider, ActionContext, keyPrefix);\n            }\n        }\n\n        /// <summary>Creates a <see cref=\"BadRequestResult\"/> (400 Bad Request).</summary>\n        /// <returns>A <see cref=\"BadRequestResult\"/>.</returns>\n        protected internal virtual BadRequestResult BadRequest()\n        {\n            return new BadRequestResult(this);\n        }\n\n        /// <summary>\n        /// Creates a <see cref=\"BadRequestErrorMessageResult\"/> (400 Bad Request) with the specified error message.\n        /// </summary>\n        /// <param name=\"message\">The user-visible error message.</param>\n        /// <returns>A <see cref=\"BadRequestErrorMessageResult\"/> with the specified error message.</returns>\n        protected internal virtual BadRequestErrorMessageResult BadRequest(string message)\n        {\n            return new BadRequestErrorMessageResult(message, this);\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"InvalidModelStateResult\"/> (400 Bad Request) with the specified model state.\n        /// </summary>\n        /// <param name=\"modelState\">The model state to include in the error.</param>\n        /// <returns>An <see cref=\"InvalidModelStateResult\"/> with the specified model state.</returns>\n        protected internal virtual InvalidModelStateResult BadRequest(ModelStateDictionary modelState)\n        {\n            return new InvalidModelStateResult(modelState, this);\n        }\n\n        /// <summary>Creates a <see cref=\"ConflictResult\"/> (409 Conflict).</summary>\n        /// <returns>A <see cref=\"ConflictResult\"/>.</returns>\n        protected internal virtual ConflictResult Conflict()\n        {\n            return new ConflictResult(this);\n        }\n\n        /// <summary>Creates a <see cref=\"NegotiatedContentResult{T}\"/> with the specified values.</summary>\n        /// <typeparam name=\"T\">The type of content in the entity body.</typeparam>\n        /// <param name=\"statusCode\">The HTTP status code for the response message.</param>\n        /// <param name=\"value\">The content value to negotiate and format in the entity body.</param>\n        /// <returns>A <see cref=\"NegotiatedContentResult{T}\"/> with the specified values.</returns>\n        protected internal virtual NegotiatedContentResult<T> Content<T>(HttpStatusCode statusCode, T value)\n        {\n            return new NegotiatedContentResult<T>(statusCode, value, this);\n        }\n\n        /// <summary>Creates a <see cref=\"FormattedContentResult{T}\"/> with the specified values.</summary>\n        /// <typeparam name=\"T\">The type of content in the entity body.</typeparam>\n        /// <param name=\"statusCode\">The HTTP status code for the response message.</param>\n        /// <param name=\"value\">The content value to format in the entity body.</param>\n        /// <param name=\"formatter\">The formatter to use to format the content.</param>\n        /// <returns>A <see cref=\"FormattedContentResult{T}\"/> with the specified values.</returns>\n        protected internal FormattedContentResult<T> Content<T>(HttpStatusCode statusCode, T value,\n            MediaTypeFormatter formatter)\n        {\n            return Content(statusCode, value, formatter, (MediaTypeHeaderValue)null);\n        }\n\n        /// <summary>Creates a <see cref=\"FormattedContentResult{T}\"/> with the specified values.</summary>\n        /// <typeparam name=\"T\">The type of content in the entity body.</typeparam>\n        /// <param name=\"statusCode\">The HTTP status code for the response message.</param>\n        /// <param name=\"value\">The content value to format in the entity body.</param>\n        /// <param name=\"formatter\">The formatter to use to format the content.</param>\n        /// <param name=\"mediaType\">The value for the Content-Type header.</param>\n        /// <returns>A <see cref=\"FormattedContentResult{T}\"/> with the specified values.</returns>\n        protected internal FormattedContentResult<T> Content<T>(HttpStatusCode statusCode, T value,\n            MediaTypeFormatter formatter, string mediaType)\n        {\n            return Content(statusCode, value, formatter, new MediaTypeHeaderValue(mediaType));\n        }\n\n        /// <summary>Creates a <see cref=\"FormattedContentResult{T}\"/> with the specified values.</summary>\n        /// <typeparam name=\"T\">The type of content in the entity body.</typeparam>\n        /// <param name=\"statusCode\">The HTTP status code for the response message.</param>\n        /// <param name=\"value\">The content value to format in the entity body.</param>\n        /// <param name=\"formatter\">The formatter to use to format the content.</param>\n        /// <param name=\"mediaType\">\n        /// The value for the Content-Type header, or <see langword=\"null\"/> to have the formatter pick a default\n        /// value.\n        /// </param>\n        /// <returns>A <see cref=\"FormattedContentResult{T}\"/> with the specified values.</returns>\n        protected internal virtual FormattedContentResult<T> Content<T>(HttpStatusCode statusCode, T value,\n            MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType)\n        {\n            return new FormattedContentResult<T>(statusCode, value, formatter, mediaType, this);\n        }\n\n        /// <summary>\n        /// Creates a <see cref=\"CreatedNegotiatedContentResult{T}\"/> (201 Created) with the specified values.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of content in the entity body.</typeparam>\n        /// <param name=\"location\">\n        /// The location at which the content has been created. Must be a relative or absolute URL.\n        /// </param>\n        /// <param name=\"content\">The content value to negotiate and format in the entity body.</param>\n        /// <returns>A <see cref=\"CreatedNegotiatedContentResult{T}\"/> with the specified values.</returns>\n        protected internal CreatedNegotiatedContentResult<T> Created<T>(string location, T content)\n        {\n            if (location == null)\n            {\n                throw new ArgumentNullException(\"location\");\n            }\n\n            return Created<T>(new Uri(location, UriKind.RelativeOrAbsolute), content);\n        }\n\n        /// <summary>\n        /// Creates a <see cref=\"CreatedNegotiatedContentResult{T}\"/> (201 Created) with the specified values.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of content in the entity body.</typeparam>\n        /// <param name=\"location\">The location at which the content has been created.</param>\n        /// <param name=\"content\">The content value to negotiate and format in the entity body.</param>\n        /// <returns>A <see cref=\"CreatedNegotiatedContentResult{T}\"/> with the specified values.</returns>\n        protected internal virtual CreatedNegotiatedContentResult<T> Created<T>(Uri location, T content)\n        {\n            return new CreatedNegotiatedContentResult<T>(location, content, this);\n        }\n\n        /// <summary>\n        /// Creates a <see cref=\"CreatedAtRouteNegotiatedContentResult{T}\"/> (201 Created) with the specified values.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of content in the entity body.</typeparam>\n        /// <param name=\"routeName\">The name of the route to use for generating the URL.</param>\n        /// <param name=\"routeValues\">The route data to use for generating the URL.</param>\n        /// <param name=\"content\">The content value to negotiate and format in the entity body.</param>\n        /// <returns>A <see cref=\"CreatedAtRouteNegotiatedContentResult{T}\"/> with the specified values.</returns>\n        protected internal CreatedAtRouteNegotiatedContentResult<T> CreatedAtRoute<T>(string routeName,\n            object routeValues, T content)\n        {\n            return CreatedAtRoute<T>(routeName, new HttpRouteValueDictionary(routeValues), content);\n        }\n\n        /// <summary>\n        /// Creates a <see cref=\"CreatedAtRouteNegotiatedContentResult{T}\"/> (201 Created) with the specified values.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of content in the entity body.</typeparam>\n        /// <param name=\"routeName\">The name of the route to use for generating the URL.</param>\n        /// <param name=\"routeValues\">The route data to use for generating the URL.</param>\n        /// <param name=\"content\">The content value to negotiate and format in the entity body.</param>\n        /// <returns>A <see cref=\"CreatedAtRouteNegotiatedContentResult{T}\"/> with the specified values.</returns>\n        protected internal virtual CreatedAtRouteNegotiatedContentResult<T> CreatedAtRoute<T>(string routeName,\n            IDictionary<string, object> routeValues, T content)\n        {\n            return new CreatedAtRouteNegotiatedContentResult<T>(routeName, routeValues, content, this);\n        }\n\n        /// <summary>Creates an <see cref=\"InternalServerErrorResult\"/> (500 Internal Server Error).</summary>\n        /// <returns>A <see cref=\"InternalServerErrorResult\"/>.</returns>\n        protected internal virtual InternalServerErrorResult InternalServerError()\n        {\n            return new InternalServerErrorResult(this);\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"ExceptionResult\"/> (500 Internal Server Error) with the specified exception.\n        /// </summary>\n        /// <param name=\"exception\">The exception to include in the error.</param>\n        /// <returns>An <see cref=\"ExceptionResult\"/> with the specified exception.</returns>\n        protected internal virtual ExceptionResult InternalServerError(Exception exception)\n        {\n            return new ExceptionResult(exception, this);\n        }\n\n        /// <summary>Creates a <see cref=\"JsonResult{T}\"/> (200 OK) with the specified value.</summary>\n        /// <typeparam name=\"T\">The type of content in the entity body.</typeparam>\n        /// <param name=\"content\">The content value to serialize in the entity body.</param>\n        /// <returns>A <see cref=\"JsonResult{T}\"/> with the specified value.</returns>\n        protected internal JsonResult<T> Json<T>(T content)\n        {\n            return Json<T>(content, new JsonSerializerSettings());\n        }\n\n        /// <summary>Creates a <see cref=\"JsonResult{T}\"/> (200 OK) with the specified values.</summary>\n        /// <typeparam name=\"T\">The type of content in the entity body.</typeparam>\n        /// <param name=\"content\">The content value to serialize in the entity body.</param>\n        /// <param name=\"serializerSettings\">The serializer settings.</param>\n        /// <returns>A <see cref=\"JsonResult{T}\"/> with the specified values.</returns>\n        protected internal JsonResult<T> Json<T>(T content, JsonSerializerSettings serializerSettings)\n        {\n            return Json<T>(content, serializerSettings, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false,\n                throwOnInvalidBytes: true));\n        }\n\n        /// <summary>Creates a <see cref=\"JsonResult{T}\"/> (200 OK) with the specified values.</summary>\n        /// <typeparam name=\"T\">The type of content in the entity body.</typeparam>\n        /// <param name=\"content\">The content value to serialize in the entity body.</param>\n        /// <param name=\"serializerSettings\">The serializer settings.</param>\n        /// <param name=\"encoding\">The content encoding.</param>\n        /// <returns>A <see cref=\"JsonResult{T}\"/> with the specified values.</returns>\n        protected internal virtual JsonResult<T> Json<T>(T content, JsonSerializerSettings serializerSettings,\n            Encoding encoding)\n        {\n            return new JsonResult<T>(content, serializerSettings, encoding, this);\n        }\n\n        /// <summary>Creates a <see cref=\"NotFoundResult\"/> (404 Not Found).</summary>\n        /// <returns>A <see cref=\"NotFoundResult\"/>.</returns>\n        protected internal virtual NotFoundResult NotFound()\n        {\n            return new NotFoundResult(this);\n        }\n\n        /// <summary>Creates an <see cref=\"OkResult\"/> (200 OK).</summary>\n        /// <returns>An <see cref=\"OkResult\"/>.</returns>\n        protected internal virtual OkResult Ok()\n        {\n            return new OkResult(this);\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"OkNegotiatedContentResult{T}\"/> (200 OK) with the specified values.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of content in the entity body.</typeparam>\n        /// <param name=\"content\">The content value to negotiate and format in the entity body.</param>\n        /// <returns>An <see cref=\"OkNegotiatedContentResult{T}\"/> with the specified values.</returns>\n        protected internal virtual OkNegotiatedContentResult<T> Ok<T>(T content)\n        {\n            return new OkNegotiatedContentResult<T>(content, this);\n        }\n\n        /// <summary>Creates a <see cref=\"RedirectResult\"/> (302 Found) with the specified value.</summary>\n        /// <param name=\"location\">The location to which to redirect.</param>\n        /// <returns>A <see cref=\"RedirectResult\"/> with the specified value.</returns>\n        protected internal virtual RedirectResult Redirect(string location)\n        {\n            if (location == null)\n            {\n                throw new ArgumentNullException(\"location\");\n            }\n\n            return Redirect(new Uri(location));\n        }\n\n        /// <summary>Creates a <see cref=\"RedirectResult\"/> (302 Found) with the specified value.</summary>\n        /// <param name=\"location\">The location to which to redirect.</param>\n        /// <returns>A <see cref=\"RedirectResult\"/> with the specified value.</returns>\n        protected internal virtual RedirectResult Redirect(Uri location)\n        {\n            return new RedirectResult(location, this);\n        }\n\n        /// <summary>Creates a <see cref=\"RedirectToRouteResult\"/> (302 Found) with the specified values.</summary>\n        /// <param name=\"routeName\">The name of the route to use for generating the URL.</param>\n        /// <param name=\"routeValues\">The route data to use for generating the URL.</param>\n        /// <returns>A <see cref=\"RedirectToRouteResult\"/> with the specified values.</returns>\n        protected internal RedirectToRouteResult RedirectToRoute(string routeName, object routeValues)\n        {\n            return RedirectToRoute(routeName, new HttpRouteValueDictionary(routeValues));\n        }\n\n        /// <summary>Creates a <see cref=\"RedirectToRouteResult\"/> (302 Found) with the specified values.</summary>\n        /// <param name=\"routeName\">The name of the route to use for generating the URL.</param>\n        /// <param name=\"routeValues\">The route data to use for generating the URL.</param>\n        /// <returns>A <see cref=\"RedirectToRouteResult\"/> with the specified values.</returns>\n        protected internal virtual RedirectToRouteResult RedirectToRoute(string routeName,\n            IDictionary<string, object> routeValues)\n        {\n            return new RedirectToRouteResult(routeName, routeValues, this);\n        }\n\n        /// <summary>Creates a <see cref=\"ResponseMessageResult\"/> with the specified response.</summary>\n        /// <param name=\"response\">The HTTP response message.</param>\n        /// <returns>A <see cref=\"ResponseMessageResult\"/> for the specified response.</returns>\n        protected internal virtual ResponseMessageResult ResponseMessage(HttpResponseMessage response)\n        {\n            return new ResponseMessageResult(response);\n        }\n\n        /// <summary>Creates a <see cref=\"StatusCodeResult\"/> with the specified status code.</summary>\n        /// <param name=\"status\">The HTTP status code for the response message</param>\n        /// <returns>A <see cref=\"StatusCodeResult\"/> with the specified status code.</returns>\n        protected internal virtual StatusCodeResult StatusCode(HttpStatusCode status)\n        {\n            return new StatusCodeResult(status, this);\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"UnauthorizedResult\"/> (401 Unauthorized) with the specified values.\n        /// </summary>\n        /// <param name=\"challenges\">The WWW-Authenticate challenges.</param>\n        /// <returns>An <see cref=\"UnauthorizedResult\"/> with the specified values.</returns>\n        protected internal UnauthorizedResult Unauthorized(params AuthenticationHeaderValue[] challenges)\n        {\n            return Unauthorized((IEnumerable<AuthenticationHeaderValue>)challenges);\n        }\n\n        /// <summary>\n        /// Creates an <see cref=\"UnauthorizedResult\"/> (401 Unauthorized) with the specified values.\n        /// </summary>\n        /// <param name=\"challenges\">The WWW-Authenticate challenges.</param>\n        /// <returns>An <see cref=\"UnauthorizedResult\"/> with the specified values.</returns>\n        protected internal virtual UnauthorizedResult Unauthorized(IEnumerable<AuthenticationHeaderValue> challenges)\n        {\n            return new UnauthorizedResult(challenges, this);\n        }\n\n        protected virtual void Initialize(HttpControllerContext controllerContext)\n        {\n            if (controllerContext == null)\n            {\n                throw Error.ArgumentNull(\"controllerContext\");\n            }\n\n            _initialized = true;\n            ControllerContext = controllerContext;\n        }\n\n        #region IDisposable\n\n        public void Dispose()\n        {\n            Dispose(true);\n            GC.SuppressFinalize(this);\n        }\n\n        protected virtual void Dispose(bool disposing)\n        {\n        }\n\n        #endregion IDisposable\n    }\n}"
  },
  {
    "path": "src/System.Web.Http/AuthorizeAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Http;\nusing System.Security.Principal;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// An authorization filter that verifies the request's <see cref=\"IPrincipal\"/>.\n    /// </summary>\n    /// <remarks>You can declare multiple of these attributes per action. You can also use <see cref=\"AllowAnonymousAttribute\"/>\n    /// to disable authorization for a specific action.</remarks>\n    [SuppressMessage(\"Microsoft.Performance\", \"CA1813:AvoidUnsealedAttributes\", Justification = \"We want to support extensibility\")]\n    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]\n    public class AuthorizeAttribute : AuthorizationFilterAttribute\n    {\n        private static readonly string[] _emptyArray = new string[0];\n\n        private readonly object _typeId = new object();\n\n        private string _roles;\n        private string[] _rolesSplit = _emptyArray;\n        private string _users;\n        private string[] _usersSplit = _emptyArray;\n\n        /// <summary>\n        /// Gets or sets the authorized roles.\n        /// </summary>\n        /// <value>\n        /// The roles string.\n        /// </value>\n        /// <remarks>Multiple role names can be specified using the comma character as a separator.</remarks>\n        public string Roles\n        {\n            get { return _roles ?? String.Empty; }\n            set\n            {\n                _roles = value;\n                _rolesSplit = SplitString(value);\n            }\n        }\n\n        /// <summary>\n        /// Gets a unique identifier for this <see cref=\"T:System.Attribute\"/>.\n        /// </summary>\n        /// <returns>The unique identifier for the attribute.</returns>\n        public override object TypeId\n        {\n            get { return _typeId; }\n        }\n\n        /// <summary>\n        /// Gets or sets the authorized users.\n        /// </summary>\n        /// <value>\n        /// The users string.\n        /// </value>\n        /// <remarks>Multiple role names can be specified using the comma character as a separator.</remarks>\n        public string Users\n        {\n            get { return _users ?? String.Empty; }\n            set\n            {\n                _users = value;\n                _usersSplit = SplitString(value);\n            }\n        }\n\n        /// <summary>\n        /// Determines whether access for this particular request is authorized. This method uses the user <see cref=\"IPrincipal\"/>\n        /// returned via <see cref=\"HttpRequestContext.Principal\"/>. Authorization is denied if the user is not authenticated,\n        /// the user is not in the authorized group of <see cref=\"Users\"/> (if defined), or if the user is not in any of the authorized \n        /// <see cref=\"Roles\"/> (if defined).\n        /// </summary>\n        /// <param name=\"actionContext\">The context.</param>\n        /// <returns><c>true</c> if access is authorized; otherwise <c>false</c>.</returns>\n        protected virtual bool IsAuthorized(HttpActionContext actionContext)\n        {\n            if (actionContext == null)\n            {\n                throw Error.ArgumentNull(\"actionContext\");\n            }\n\n            IPrincipal user = actionContext.ControllerContext.RequestContext.Principal;\n            if (user == null || user.Identity == null || !user.Identity.IsAuthenticated)\n            {\n                return false;\n            }\n\n            if (_usersSplit.Length > 0 && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase))\n            {\n                return false;\n            }\n\n            if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole))\n            {\n                return false;\n            }\n\n            return true;\n        }\n\n        /// <summary>\n        /// Called when an action is being authorized. This method uses the user <see cref=\"IPrincipal\"/>\n        /// returned via <see cref=\"HttpRequestContext.Principal\"/>. Authorization is denied if\n        /// - the request is not associated with any user.\n        /// - the user is not authenticated,\n        /// - the user is authenticated but is not in the authorized group of <see cref=\"Users\"/> (if defined), or if the user\n        /// is not in any of the authorized <see cref=\"Roles\"/> (if defined).\n        /// \n        /// If authorization is denied then this method will invoke <see cref=\"HandleUnauthorizedRequest(HttpActionContext)\"/> to process the unauthorized request.\n        /// </summary>\n        /// <remarks>You can use <see cref=\"AllowAnonymousAttribute\"/> to cause authorization checks to be skipped for a particular\n        /// action or controller.</remarks>\n        /// <seealso cref=\"IsAuthorized(HttpActionContext)\" />\n        /// <param name=\"actionContext\">The context.</param>\n        /// <exception cref=\"ArgumentNullException\">The context parameter is null.</exception>\n        public override void OnAuthorization(HttpActionContext actionContext)\n        {\n            if (actionContext == null)\n            {\n                throw Error.ArgumentNull(\"actionContext\");\n            }\n\n            if (SkipAuthorization(actionContext))\n            {\n                return;\n            }\n\n            if (!IsAuthorized(actionContext))\n            {\n                HandleUnauthorizedRequest(actionContext);\n            }\n        }\n\n        /// <summary>\n        /// Processes requests that fail authorization. This default implementation creates a new response with the\n        /// Unauthorized status code. Override this method to provide your own handling for unauthorized requests.\n        /// </summary>\n        /// <param name=\"actionContext\">The context.</param>\n        protected virtual void HandleUnauthorizedRequest(HttpActionContext actionContext)\n        {\n            if (actionContext == null)\n            {\n                throw Error.ArgumentNull(\"actionContext\");\n            }\n\n            actionContext.Response = actionContext.ControllerContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, SRResources.RequestNotAuthorized);\n        }\n\n        private static bool SkipAuthorization(HttpActionContext actionContext)\n        {\n            Contract.Assert(actionContext != null);\n\n            return actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any()\n                   || actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();\n        }\n\n        /// <summary>\n        /// Splits the string on commas and removes any leading/trailing whitespace from each result item.\n        /// </summary>\n        /// <param name=\"original\">The input string.</param>\n        /// <returns>An array of strings parsed from the input <paramref name=\"original\"/> string.</returns>\n        internal static string[] SplitString(string original)\n        {\n            if (String.IsNullOrEmpty(original))\n            {\n                return _emptyArray;\n            }\n\n            var split = from piece in original.Split(',')\n                        let trimmed = piece.Trim()\n                        where !String.IsNullOrEmpty(trimmed)\n                        select trimmed;\n            return split.ToArray();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Batch/BatchExecutionOrder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Batch\n{\n    /// <summary>\n    /// Defines the order of execution for batch requests.\n    /// </summary>\n    public enum BatchExecutionOrder\n    {\n        /// <summary>\n        /// Executes the batch requests sequentially.\n        /// </summary>\n        Sequential = 0,\n\n        /// <summary>\n        /// Executes the batch requests non-sequentially.\n        /// </summary>\n        NonSequential\n    }\n}"
  },
  {
    "path": "src/System.Web.Http/Batch/BatchHttpRequestContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Security.Cryptography.X509Certificates;\nusing System.Security.Principal;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Routing;\n\nnamespace System.Web.Http.Batch\n{\n    internal class BatchHttpRequestContext : HttpRequestContext\n    {\n        private readonly HttpRequestContext _batchContext;\n\n        public BatchHttpRequestContext(HttpRequestContext batchContext)\n        {\n            if (batchContext == null)\n            {\n                throw new ArgumentNullException(\"batchContext\");\n            }\n\n            _batchContext = batchContext;\n        }\n\n        public HttpRequestContext BatchContext\n        {\n            get { return _batchContext; }\n        }\n\n        public override X509Certificate2 ClientCertificate\n        {\n            get\n            {\n                return _batchContext.ClientCertificate;\n            }\n            set\n            {\n                _batchContext.ClientCertificate = value;\n            }\n        }\n\n        public override HttpConfiguration Configuration\n        {\n            get\n            {\n                // Use separate route data for configuration (base, not _batchContext).\n                return base.Configuration;\n            }\n            set\n            {\n                // Use separate route data for configuration (base, not _batchContext).\n                base.Configuration = value;\n            }\n        }\n\n        public override bool IncludeErrorDetail\n        {\n            get\n            {\n                return _batchContext.IncludeErrorDetail;\n            }\n            set\n            {\n                _batchContext.IncludeErrorDetail = value;\n            }\n        }\n\n        public override bool IsLocal\n        {\n            get\n            {\n                return _batchContext.IsLocal;\n            }\n            set\n            {\n                _batchContext.IsLocal = value;\n            }\n        }\n\n        public override IPrincipal Principal\n        {\n            get\n            {\n                return _batchContext.Principal;\n            }\n            set\n            {\n                _batchContext.Principal = value;\n            }\n        }\n\n        public override IHttpRouteData RouteData\n        {\n            get\n            {\n                // Use separate route data for batching (base, not _batchContext).\n                return base.RouteData;\n            }\n            set\n            {\n                // Use separate route data for batching (base, not _batchContext).\n                base.RouteData = value;\n            }\n        }\n\n        public override UrlHelper Url\n        {\n            get\n            {\n                // Use a separate URL factory for batching (base, not _batchContext).\n                return base.Url;\n            }\n            set\n            {\n                // Use a separate URL factory for batching (base, not _batchContext).\n                base.Url = value;\n            }\n        }\n\n        public override string VirtualPathRoot\n        {\n            get\n            {\n                return _batchContext.VirtualPathRoot;\n            }\n            set\n            {\n                _batchContext.VirtualPathRoot = value;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Batch/BatchHttpRequestMessageExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.Routing;\n\nnamespace System.Web.Http.Batch\n{\n    /// <summary>\n    /// Provides extension methods for the <see cref=\"HttpRequestMessage\"/> class.\n    /// </summary>\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class BatchHttpRequestMessageExtensions\n    {\n        private const string HttpBatchContextKey = \"MS_HttpBatchContext\";\n\n        private static readonly string[] BatchRequestPropertyExclusions =\n        {\n            HttpPropertyKeys.HttpRouteDataKey,\n            HttpPropertyKeys.DisposableRequestResourcesKey,\n            HttpPropertyKeys.SynchronizationContextKey,\n            HttpPropertyKeys.HttpConfigurationKey,\n            HttpRoute.RoutingContextKey,\n            HttpBatchContextKey\n        };\n\n        /// <summary>\n        /// Copies the properties from another <see cref=\"HttpRequestMessage\"/>.\n        /// </summary>\n        /// <param name=\"subRequest\">The sub-request.</param>\n        /// <param name=\"batchRequest\">The batch request that contains the properties to copy.</param>\n        public static void CopyBatchRequestProperties(this HttpRequestMessage subRequest, HttpRequestMessage batchRequest)\n        {\n            if (subRequest == null)\n            {\n                throw new ArgumentNullException(\"subRequest\");\n            }\n            if (batchRequest == null)\n            {\n                throw new ArgumentNullException(\"batchRequest\");\n            }\n\n            foreach (KeyValuePair<string, object> property in batchRequest.Properties)\n            {\n                if (!BatchRequestPropertyExclusions.Contains(property.Key))\n                {\n                    subRequest.Properties.Add(property);\n                }\n            }\n\n            HttpRequestContext originalContext = subRequest.GetRequestContext();\n\n            if (originalContext != null)\n            {\n                BatchHttpRequestContext subRequestContext = new BatchHttpRequestContext(originalContext)\n                {\n                    Url = new UrlHelper(subRequest)\n                };\n\n                subRequest.SetRequestContext(subRequestContext);\n            }\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http/Batch/DefaultHttpBatchHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.Batch\n{\n    /// <summary>\n    /// Default implementation of <see cref=\"HttpBatchHandler\"/> that encodes the HTTP request/response messages as MIME multipart.\n    /// </summary>\n    /// <remarks>\n    /// By default, it buffers the HTTP request messages in memory during parsing.\n    /// </remarks>\n    public class DefaultHttpBatchHandler : HttpBatchHandler\n    {\n        private const string MultiPartContentSubtype = \"mixed\";\n        private const string MultiPartMixed = \"multipart/mixed\";\n        private BatchExecutionOrder _executionOrder;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"DefaultHttpBatchHandler\"/> class.\n        /// </summary>\n        /// <param name=\"httpServer\">The <see cref=\"HttpServer\"/> for handling the individual batch requests.</param>\n        public DefaultHttpBatchHandler(HttpServer httpServer)\n            : base(httpServer)\n        {\n            ExecutionOrder = BatchExecutionOrder.Sequential;\n            SupportedContentTypes = new List<string>() { MultiPartMixed };\n        }\n\n        /// <summary>\n        /// Gets or sets the execution order for the batch requests. The default execution order is sequential.\n        /// </summary>\n        /// <exception cref=\"System.ComponentModel.InvalidEnumArgumentException\">value</exception>\n        public BatchExecutionOrder ExecutionOrder\n        {\n            get\n            {\n                return _executionOrder;\n            }\n            set\n            {\n                if (!Enum.IsDefined(typeof(BatchExecutionOrder), value))\n                {\n                    throw new InvalidEnumArgumentException(\"value\", (int)value, typeof(BatchExecutionOrder));\n                }\n                _executionOrder = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets the supported content types for the batch request.\n        /// </summary>\n        public IList<string> SupportedContentTypes { get; private set; }\n\n        /// <summary>\n        /// Creates the batch response message.\n        /// </summary>\n        /// <param name=\"responses\">The responses for the batch requests.</param>\n        /// <param name=\"request\">The original request containing all the batch requests.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>The batch response message.</returns>\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"Caller is responsible for disposing the object.\")]\n        public virtual Task<HttpResponseMessage> CreateResponseMessageAsync(IList<HttpResponseMessage> responses, HttpRequestMessage request, CancellationToken cancellationToken)\n        {\n            if (responses == null)\n            {\n                throw Error.ArgumentNull(\"responses\");\n            }\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            MultipartContent batchContent = new MultipartContent(MultiPartContentSubtype);\n\n            foreach (HttpResponseMessage batchResponse in responses)\n            {\n                batchContent.Add(new HttpMessageContent(batchResponse));\n            }\n\n            HttpResponseMessage response = request.CreateResponse();\n            response.Content = batchContent;\n            return Task.FromResult(response);\n        }\n\n        /// <inheritdoc/>\n        public override async Task<HttpResponseMessage> ProcessBatchAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            ValidateRequest(request);\n\n            IList<HttpRequestMessage> subRequests = await ParseBatchRequestsAsync(request, cancellationToken);\n\n            try\n            {\n                IList<HttpResponseMessage> responses = await ExecuteRequestMessagesAsync(subRequests, cancellationToken);\n                return await CreateResponseMessageAsync(responses, request, cancellationToken);\n            }\n            finally\n            {\n                foreach (HttpRequestMessage subRequest in subRequests)\n                {\n                    request.RegisterForDispose(subRequest.GetResourcesForDisposal());\n                    request.RegisterForDispose(subRequest);\n                }\n            }\n        }\n\n        /// <summary>\n        /// Executes the batch request messages.\n        /// </summary>\n        /// <param name=\"requests\">The collection of batch request messages.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A collection of <see cref=\"HttpResponseMessage\"/> for the batch requests.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"We need to return a collection of response messages asynchronously.\")]\n        public virtual async Task<IList<HttpResponseMessage>> ExecuteRequestMessagesAsync(IEnumerable<HttpRequestMessage> requests, CancellationToken cancellationToken)\n        {\n            if (requests == null)\n            {\n                throw Error.ArgumentNull(\"requests\");\n            }\n\n            List<HttpResponseMessage> responses = new List<HttpResponseMessage>();\n\n            try\n            {\n                switch (ExecutionOrder)\n                {\n                    case BatchExecutionOrder.Sequential:\n                        foreach (HttpRequestMessage request in requests)\n                        {\n                            responses.Add(await Invoker.SendAsync(request, cancellationToken));\n                        }\n                        break;\n\n                    case BatchExecutionOrder.NonSequential:\n                        responses.AddRange(await Task.WhenAll(requests.Select(request => Invoker.SendAsync(request, cancellationToken))));\n                        break;\n                }\n            }\n            catch\n            {\n                foreach (HttpResponseMessage response in responses)\n                {\n                    if (response != null)\n                    {\n                        response.Dispose();\n                    }\n                }\n                throw;\n            }\n\n            return responses;\n        }\n\n        /// <summary>\n        /// Converts the incoming batch request into a collection of request messages.\n        /// </summary>\n        /// <param name=\"request\">The request containing the batch request messages.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A collection of <see cref=\"HttpRequestMessage\"/>.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"We need to return a collection of request messages asynchronously.\")]\n        public virtual async Task<IList<HttpRequestMessage>> ParseBatchRequestsAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            List<HttpRequestMessage> requests = new List<HttpRequestMessage>();\n            cancellationToken.ThrowIfCancellationRequested();\n            MultipartStreamProvider streamProvider = await request.Content.ReadAsMultipartAsync();\n            foreach (HttpContent httpContent in streamProvider.Contents)\n            {\n                cancellationToken.ThrowIfCancellationRequested();\n                HttpRequestMessage innerRequest = request.RequestUri == null ? await httpContent.ReadAsHttpRequestMessageAsync() : await httpContent.ReadAsHttpRequestMessageAsync(request.RequestUri.Scheme);\n                innerRequest.CopyBatchRequestProperties(request);\n                requests.Add(innerRequest);\n            }\n            return requests;\n        }\n\n        /// <summary>\n        /// Validates the incoming request that contains the batch request messages.\n        /// </summary>\n        /// <param name=\"request\">The request containing the batch request messages.</param>\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"Caller is responsible for disposing the object.\")]\n        public virtual void ValidateRequest(HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            if (request.Content == null)\n            {\n                throw new HttpResponseException(request.CreateErrorResponse(\n                    HttpStatusCode.BadRequest,\n                    SRResources.BatchRequestMissingContent));\n            }\n\n            MediaTypeHeaderValue contentType = request.Content.Headers.ContentType;\n            if (contentType == null)\n            {\n                throw new HttpResponseException(request.CreateErrorResponse(\n                    HttpStatusCode.BadRequest,\n                    SRResources.BatchContentTypeMissing));\n            }\n\n            if (!SupportedContentTypes.Contains(contentType.MediaType, StringComparer.OrdinalIgnoreCase))\n            {\n                throw new HttpResponseException(request.CreateErrorResponse(\n                    HttpStatusCode.BadRequest,\n                    Error.Format(SRResources.BatchMediaTypeNotSupported, contentType.MediaType)));\n            }\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http/Batch/HttpBatchHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics;\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.Net.Http;\nusing System.Runtime.ExceptionServices;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Hosting;\n\nnamespace System.Web.Http.Batch\n{\n    /// <summary>\n    /// Defines the abstraction for handling HTTP batch requests.\n    /// </summary>\n    // Class Hierarchy\n    // - HttpBatchHandler\n    //   - DefaultHttpBatchHandler\n    //   - ODataBatchHandler\n    //     - DefaultODataBatchHandler\n    //     - UnbufferedODataBatchHandler\n    public abstract class HttpBatchHandler : HttpMessageHandler\n    {\n        private readonly HttpServer _server;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpBatchHandler\"/> class.\n        /// </summary>\n        /// <param name=\"httpServer\">The <see cref=\"HttpServer\"/> for handling the individual batch requests.</param>\n        protected HttpBatchHandler(HttpServer httpServer)\n        {\n            if (httpServer == null)\n            {\n                throw Error.ArgumentNull(\"httpServer\");\n            }\n\n            _server = httpServer;\n            Invoker = new HttpMessageInvoker(httpServer);\n        }\n\n        /// <summary>\n        /// Gets the invoker to send the batch requests to the <see cref=\"HttpServer\"/>.\n        /// </summary>\n        public HttpMessageInvoker Invoker { get; private set; }\n\n        /// <remarks>This property is internal and settable only for unit testing purposes.</remarks>\n        internal IExceptionLogger ExceptionLogger\n        {\n            get\n            {\n                return _server.ExceptionLogger;\n            }\n            set\n            {\n                _server.ExceptionLogger = value;\n            }\n        }\n\n        /// <remarks>This property is internal and settable only for unit testing purposes.</remarks>\n        internal IExceptionHandler ExceptionHandler\n        {\n            get\n            {\n                return _server.ExceptionHandler;\n            }\n            set\n            {\n                _server.ExceptionHandler = value;\n            }\n        }\n\n        /// <inheritdoc/>\n        protected sealed override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            request.Properties[HttpPropertyKeys.IsBatchRequest] = true;\n\n            ExceptionDispatchInfo exceptionInfo;\n\n            try\n            {\n                return await ProcessBatchAsync(request, cancellationToken);\n            }\n            catch (OperationCanceledException)\n            {\n                // Propogate the canceled task without calling exception loggers or handlers.\n                throw;\n            }\n            catch (HttpResponseException httpResponseException)\n            {\n                return httpResponseException.Response;\n            }\n            catch (Exception exception)\n            {\n                exceptionInfo = ExceptionDispatchInfo.Capture(exception);\n            }\n\n            Debug.Assert(exceptionInfo.SourceException != null);\n\n            ExceptionContext exceptionContext = new ExceptionContext(exceptionInfo.SourceException,\n                ExceptionCatchBlocks.HttpBatchHandler, request);\n            await ExceptionLogger.LogAsync(exceptionContext, cancellationToken);\n            HttpResponseMessage response = await ExceptionHandler.HandleAsync(exceptionContext, cancellationToken);\n\n            if (response == null)\n            {\n                exceptionInfo.Throw();\n            }\n\n            return response;\n        }\n\n        /// <summary>\n        /// Processes the incoming batch request as a single <see cref=\"HttpRequestMessage\"/>.\n        /// </summary>\n        /// <param name=\"request\">The batch request.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>The batch response.</returns>\n        public abstract Task<HttpResponseMessage> ProcessBatchAsync(HttpRequestMessage request, CancellationToken cancellationToken);\n    }\n}"
  },
  {
    "path": "src/System.Web.Http/Controllers/ActionFilterResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Filters;\n\nnamespace System.Web.Http.Controllers\n{\n    internal class ActionFilterResult : IHttpActionResult\n    {\n        private readonly HttpActionBinding _binding;\n        private readonly HttpActionContext _context;\n        private readonly ServicesContainer _services;\n        private readonly IActionFilter[] _filters;\n\n        public ActionFilterResult(HttpActionBinding binding, HttpActionContext context, ServicesContainer services,\n            IActionFilter[] filters)\n        {\n            Contract.Assert(binding != null);\n            Contract.Assert(context != null);\n            Contract.Assert(services != null);\n            Contract.Assert(filters != null);\n\n            _binding = binding;\n            _context = context;\n            _services = services;\n            _filters = filters;\n        }\n\n        public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)\n        {\n            await _binding.ExecuteBindingAsync(_context, cancellationToken);\n\n            ActionInvoker actionInvoker = new ActionInvoker(_context, cancellationToken, _services);\n            // Empty filters is the default case so avoid delegates\n            // Ensure empty case remains the same as the filtered case\n            if (_filters.Length == 0)\n            {\n                return await actionInvoker.InvokeActionAsync();\n            }\n            // Ensure delegate continues to use the C# Compiler static delegate caching optimization\n            Func<ActionInvoker, Task<HttpResponseMessage>> invokeCallback = (innerInvoker) =>\n                innerInvoker.InvokeActionAsync();\n            return await InvokeActionWithActionFilters(_context, cancellationToken, _filters, invokeCallback,\n                actionInvoker)();\n        }\n\n        public static Func<Task<HttpResponseMessage>> InvokeActionWithActionFilters(HttpActionContext actionContext,\n            CancellationToken cancellationToken, IActionFilter[] filters, Func<Task<HttpResponseMessage>> innerAction)\n        {\n            Contract.Assert(actionContext != null);\n            Contract.Assert(filters != null);\n            Contract.Assert(innerAction != null);\n\n            // Because the continuation gets built from the inside out we need to reverse the filter list so that least\n            // specific filters (Global) get run first and the most specific filters (Action) get run last.\n            Func<Task<HttpResponseMessage>> result = innerAction;\n            for (int i = filters.Length - 1; i >= 0; i--)\n            {\n                IActionFilter filter = filters[i];\n                Func<Func<Task<HttpResponseMessage>>, IActionFilter, Func<Task<HttpResponseMessage>>>\n                    chainContinuation = (continuation, innerFilter) =>\n                    {\n                        return () => innerFilter.ExecuteActionFilterAsync(actionContext, cancellationToken,\n                            continuation);\n                    };\n                result = chainContinuation(result, filter);\n            }\n\n            return result;\n        }\n\n        private static Func<Task<HttpResponseMessage>> InvokeActionWithActionFilters<T>(\n            HttpActionContext actionContext, CancellationToken cancellationToken, IActionFilter[] filters,\n            Func<T, Task<HttpResponseMessage>> innerAction, T state)\n        {\n            return InvokeActionWithActionFilters(actionContext, cancellationToken, filters, () => innerAction(state));\n        }\n\n        // Keep as struct to avoid allocation\n        private struct ActionInvoker\n        {\n            private readonly HttpActionContext _context;\n            private readonly CancellationToken _cancellationToken;\n            private readonly ServicesContainer _controllerServices;\n\n            public ActionInvoker(HttpActionContext context, CancellationToken cancellationToken,\n                ServicesContainer controllerServices)\n            {\n                Contract.Assert(controllerServices != null);\n\n                _context = context;\n                _cancellationToken = cancellationToken;\n                _controllerServices = controllerServices;\n            }\n\n            public Task<HttpResponseMessage> InvokeActionAsync()\n            {\n                return _controllerServices.GetActionInvoker().InvokeActionAsync(_context, _cancellationToken);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/ApiControllerActionInvoker.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.Controllers\n{\n    public class ApiControllerActionInvoker : IHttpActionInvoker\n    {\n        public virtual Task<HttpResponseMessage> InvokeActionAsync(HttpActionContext actionContext, CancellationToken cancellationToken)\n        {\n            if (actionContext == null)\n            {\n                throw Error.ArgumentNull(\"actionContext\");\n            }\n\n            return InvokeActionAsyncCore(actionContext, cancellationToken);\n        }\n\n        private static async Task<HttpResponseMessage> InvokeActionAsyncCore(HttpActionContext actionContext, CancellationToken cancellationToken)\n        {\n            HttpActionDescriptor actionDescriptor = actionContext.ActionDescriptor;\n            Contract.Assert(actionDescriptor != null);\n\n            HttpControllerContext controllerContext = actionContext.ControllerContext;\n            Contract.Assert(controllerContext != null);\n\n            try\n            {\n                object result = await actionDescriptor.ExecuteAsync(controllerContext, actionContext.ActionArguments, cancellationToken);\n\n                // This is cached in a local for performance reasons. ReturnType is a virtual property on HttpActionDescriptor,\n                // or else we'd want to cache this as part of that class.\n                bool isDeclaredTypeActionResult = typeof(IHttpActionResult).IsAssignableFrom(actionDescriptor.ReturnType);\n                if (result == null && isDeclaredTypeActionResult)\n                {\n                    // If the return type of the action descriptor is IHttpActionResult, it's not valid to return null\n                    throw Error.InvalidOperation(SRResources.ApiControllerActionInvoker_NullHttpActionResult);\n                }\n                \n                if (isDeclaredTypeActionResult || actionDescriptor.ReturnType == typeof(object))\n                {\n                    IHttpActionResult actionResult = result as IHttpActionResult;\n\n                    if (actionResult == null && isDeclaredTypeActionResult)\n                    {\n                        // If the return type of the action descriptor is IHttpActionResult, it's not valid to return an\n                        // object that doesn't implement IHttpActionResult\n                        throw Error.InvalidOperation(SRResources.ApiControllerActionInvoker_InvalidHttpActionResult, result.GetType());\n                    }\n                    else if (actionResult != null)\n                    {\n                        HttpResponseMessage response = await actionResult.ExecuteAsync(cancellationToken);\n                        if (response == null)\n                        {\n                            throw Error.InvalidOperation(SRResources.ResponseMessageResultConverter_NullHttpResponseMessage);\n                        }\n\n                        response.EnsureResponseHasRequest(actionContext.Request);\n                        return response;\n                    }\n                }\n \n                // This is a non-IHttpActionResult, so run the converter\n                return actionDescriptor.ResultConverter.Convert(controllerContext, result);\n            }\n            catch (HttpResponseException httpResponseException)\n            {\n                HttpResponseMessage response = httpResponseException.Response;\n                response.EnsureResponseHasRequest(actionContext.Request);\n\n                return response;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/ApiControllerActionSelector.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Http;\nusing System.Reflection;\nusing System.Text;\nusing System.Threading;\nusing System.Web.Http.Internal;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Routing;\n\nnamespace System.Web.Http.Controllers\n{\n    /// <summary>\n    /// Reflection based action selector.\n    /// We optimize for the case where we have an <see cref=\"ApiControllerActionSelector\"/> instance per <see cref=\"HttpControllerDescriptor\"/>\n    /// instance but can support cases where there are many <see cref=\"HttpControllerDescriptor\"/> instances for one\n    /// <see cref=\"ApiControllerActionSelector\"/> as well. In the latter case the lookup is slightly slower because it goes through\n    /// the <see cref=\"P:HttpControllerDescriptor.Properties\"/> dictionary.\n    /// </summary>\n    public class ApiControllerActionSelector : IHttpActionSelector\n    {\n        private ActionSelectorCacheItem _fastCache;\n        private readonly object _cacheKey = new object();\n\n        public virtual HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)\n        {\n            if (controllerContext == null)\n            {\n                throw Error.ArgumentNull(\"controllerContext\");\n            }\n\n            ActionSelectorCacheItem internalSelector = GetInternalSelector(controllerContext.ControllerDescriptor);\n            return internalSelector.SelectAction(controllerContext);\n        }\n\n        public virtual ILookup<string, HttpActionDescriptor> GetActionMapping(HttpControllerDescriptor controllerDescriptor)\n        {\n            if (controllerDescriptor == null)\n            {\n                throw Error.ArgumentNull(\"controllerDescriptor\");\n            }\n\n            ActionSelectorCacheItem internalSelector = GetInternalSelector(controllerDescriptor);\n            return internalSelector.GetActionMapping();\n        }\n\n        private ActionSelectorCacheItem GetInternalSelector(HttpControllerDescriptor controllerDescriptor)\n        {\n            // Performance-sensitive\n\n            // First check in the local fast cache and if not a match then look in the broader \n            // HttpControllerDescriptor.Properties cache\n            if (_fastCache == null)\n            {\n                ActionSelectorCacheItem selector = new ActionSelectorCacheItem(controllerDescriptor);\n                Interlocked.CompareExchange(ref _fastCache, selector, null);\n                return selector;\n            }\n            else if (_fastCache.HttpControllerDescriptor == controllerDescriptor)\n            {\n                // If the key matches and we already have the delegate for creating an instance then just execute it\n                return _fastCache;\n            }\n            else\n            {\n                // If the key doesn't match then lookup/create delegate in the HttpControllerDescriptor.Properties for\n                // that HttpControllerDescriptor instance\n                object cacheValue;\n                if (controllerDescriptor.Properties.TryGetValue(_cacheKey, out cacheValue))\n                {\n                    return (ActionSelectorCacheItem)cacheValue;\n                }\n                // Race condition on initialization has no side effects\n                ActionSelectorCacheItem selector = new ActionSelectorCacheItem(controllerDescriptor);\n                controllerDescriptor.Properties.TryAdd(_cacheKey, selector);\n                return selector;\n            }\n        }\n\n        // All caching is in a dedicated cache class, which may be optionally shared across selector instances.\n        // Make this a private nested class so that nobody else can conflict with our state.\n        // Cache is initialized during ctor on a single thread.\n        private class ActionSelectorCacheItem\n        {\n            private readonly HttpControllerDescriptor _controllerDescriptor;\n\n            // Includes action descriptors for actionsByVerb with and without route attributes.\n            private readonly CandidateAction[] _combinedCandidateActions;\n\n            private readonly IDictionary<HttpActionDescriptor, string[]> _actionParameterNames = new Dictionary<HttpActionDescriptor, string[]>();\n\n            // Includes action descriptors for actionsByVerb with and without route attributes.\n            private readonly ILookup<string, HttpActionDescriptor> _combinedActionNameMapping;\n\n            // Selection commonly looks up an action by verb.\n            // Cache this mapping. These caches are completely optional and we still behave correctly if we cache miss.\n            // We can adjust the specific set we cache based on profiler information.\n            // Conceptually, this set of caches could be a HttpMethod --> ReflectedHttpActionDescriptor[].\n            // - Beware that HttpMethod has a very slow hash function (it does case-insensitive string hashing). So don't use Dict.\n            // - there are unbounded number of http methods, so make sure the cache doesn't grow indefinitely.\n            // - we can build the cache at startup and don't need to continually add to it.\n            private static readonly HttpMethod[] _cacheListVerbKinds = new HttpMethod[] { HttpMethod.Get, HttpMethod.Put, HttpMethod.Post };\n\n            private StandardActionSelectionCache _standardActions;\n\n            public ActionSelectorCacheItem(HttpControllerDescriptor controllerDescriptor)\n            {\n                Contract.Assert(controllerDescriptor != null);\n\n                // Initialize the cache entirely in the ctor on a single thread.\n                _controllerDescriptor = controllerDescriptor;\n\n                MethodInfo[] allMethods = _controllerDescriptor.ControllerType.GetMethods(BindingFlags.Instance | BindingFlags.Public);\n                MethodInfo[] validMethods = Array.FindAll(allMethods, IsValidActionMethod);\n\n                _combinedCandidateActions = new CandidateAction[validMethods.Length];\n                for (int i = 0; i < validMethods.Length; i++)\n                {\n                    MethodInfo method = validMethods[i];\n                    ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(_controllerDescriptor, method);\n                    _combinedCandidateActions[i] = new CandidateAction\n                    {\n                        ActionDescriptor = actionDescriptor\n                    };\n                    HttpActionBinding actionBinding = actionDescriptor.ActionBinding;\n\n                    // Building an action parameter name mapping to compare against the URI parameters coming from the request. Here we only take into account required parameters that are simple types and come from URI.\n                    _actionParameterNames.Add(\n                        actionDescriptor,\n                        actionBinding.ParameterBindings\n                            .Where(binding => !binding.Descriptor.IsOptional && TypeHelper.CanConvertFromString(binding.Descriptor.ParameterType) && binding.WillReadUri())\n                            .Select(binding => binding.Descriptor.Prefix ?? binding.Descriptor.ParameterName).ToArray());\n                }\n\n                _combinedActionNameMapping = \n                    _combinedCandidateActions\n                    .Select(c => c.ActionDescriptor)\n                    .ToLookup(actionDesc => actionDesc.ActionName, StringComparer.OrdinalIgnoreCase);\n            }\n\n            public HttpControllerDescriptor HttpControllerDescriptor\n            {\n                get { return _controllerDescriptor; }\n            }\n\n            // This method lazy-initializes the data needed for action selection. This is a safe race-condition. This is\n            // done because we don't know whether or not an action/controller is attribute routed until after attribute\n            // routes are added.\n            private void InitializeStandardActions()\n            {\n                if (_standardActions != null)\n                {\n                    return;\n                }\n\n                StandardActionSelectionCache standardActions = new StandardActionSelectionCache();\n\n                if (_controllerDescriptor.IsAttributeRouted())\n                {\n                    // The controller has an attribute route; no actionsByVerb are accessible via standard routing.\n                    standardActions.StandardCandidateActions = new CandidateAction[0];\n                }\n                else\n                {\n                    // The controller does not have an attribute route; some actionsByVerb may be accessible via standard\n                    // routing.\n                    List<CandidateAction> standardCandidateActions = new List<CandidateAction>();\n\n                    for (int i = 0; i < _combinedCandidateActions.Length; i++)\n                    {\n                        CandidateAction candidate = _combinedCandidateActions[i];\n\n                        // We know that this cast is safe before we created all of the action descriptors for standard actions\n                        ReflectedHttpActionDescriptor action = (ReflectedHttpActionDescriptor)candidate.ActionDescriptor;\n\n                        // Allow standard routes access inherited actionsByVerb or actionsByVerb without Route attributes.\n                        if (action.MethodInfo.DeclaringType != _controllerDescriptor.ControllerType\n                            || !candidate.ActionDescriptor.IsAttributeRouted())\n                        {\n                            standardCandidateActions.Add(candidate);\n                        }\n                    }\n\n                    standardActions.StandardCandidateActions = standardCandidateActions.ToArray();\n                }\n\n                standardActions.StandardActionNameMapping = \n                    standardActions.StandardCandidateActions\n                    .Select(c => c.ActionDescriptor)\n                    .ToLookup(actionDesc => actionDesc.ActionName, StringComparer.OrdinalIgnoreCase);\n\n                // Bucket the action descriptors by common verbs.\n                int len = _cacheListVerbKinds.Length;\n                standardActions.CacheListVerbs = new CandidateAction[len][];\n                for (int i = 0; i < len; i++)\n                {\n                    standardActions.CacheListVerbs[i] = FindActionsForVerbWorker(_cacheListVerbKinds[i], standardActions.StandardCandidateActions);\n                }\n\n                _standardActions = standardActions;\n            }\n\n            public HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)\n            {\n                InitializeStandardActions();\n                \n                List<CandidateActionWithParams> selectedCandidates = FindMatchingActions(controllerContext); \n\n                switch (selectedCandidates.Count)\n                {\n                    case 0:\n                        throw new HttpResponseException(CreateSelectionError(controllerContext));\n                    case 1:\n                        ElevateRouteData(controllerContext, selectedCandidates[0]);\n                        return selectedCandidates[0].ActionDescriptor;\n                    default:\n\n                        // Throws exception because multiple actionsByVerb match the request\n                        string ambiguityList = CreateAmbiguousMatchList(selectedCandidates);\n                        throw Error.InvalidOperation(SRResources.ApiControllerActionSelector_AmbiguousMatch, ambiguityList);\n                }\n            }\n\n            private static void ElevateRouteData(HttpControllerContext controllerContext, CandidateActionWithParams selectedCandidate)\n            {\n                controllerContext.RouteData = selectedCandidate.RouteDataSource;\n            }\n                        \n            // Find all actionsByVerb on this controller that match the request. \n            // if ignoreVerbs = true, then don't filter actionsByVerb based on mismatching Http verb. This is useful for detecting 404/405. \n            private List<CandidateActionWithParams> FindMatchingActions(HttpControllerContext controllerContext, bool ignoreVerbs = false)\n            {\n                // If matched with direct route?\n                IHttpRouteData routeData = controllerContext.RouteData;\n                IEnumerable<IHttpRouteData> subRoutes = routeData.GetSubRoutes();\n                                \n                IEnumerable<CandidateActionWithParams> actionsWithParameters = (subRoutes == null) ? \n                    GetInitialCandidateWithParameterListForRegularRoutes(controllerContext, ignoreVerbs) :\n                    GetInitialCandidateWithParameterListForDirectRoutes(controllerContext, subRoutes, ignoreVerbs);\n\n                // Make sure the action parameter matches the route and query parameters.\n                List<CandidateActionWithParams> actionsFoundByParams = FindActionMatchRequiredRouteAndQueryParameters(actionsWithParameters);\n\n                List<CandidateActionWithParams> orderCandidates = RunOrderFilter(actionsFoundByParams);\n                List<CandidateActionWithParams> precedenceCandidates = RunPrecedenceFilter(orderCandidates);\n\n                // Overload resolution logic is applied when needed.\n                List<CandidateActionWithParams> selectedCandidates = FindActionMatchMostRouteAndQueryParameters(precedenceCandidates);\n\n                return selectedCandidates;\n            }\n\n            // Selection error. Caller has already determined the request is an error, and now we need to provide the best error message.\n            // If there's another verb that could satisfy this URL, then return 405.\n            // Else return 404.\n            [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"Caller is responsible for disposing of response instance.\")]\n            private HttpResponseMessage CreateSelectionError(HttpControllerContext controllerContext)\n            {\n                // Check for 405.  \n                List<CandidateActionWithParams> actionsFoundByParams = FindMatchingActions(controllerContext, ignoreVerbs: true);\n\n                if (actionsFoundByParams.Count > 0)\n                {\n                    return Create405Response(controllerContext, actionsFoundByParams);\n                }\n\n                // Throws HttpResponseException with NotFound status because no action matches the request\n                return CreateActionNotFoundResponse(controllerContext);\n            }\n\n            // Create a 405 error response with proper headers and message string. \n            [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"Caller is responsible for disposing of response instance.\")]\n            private static HttpResponseMessage Create405Response(HttpControllerContext controllerContext, IEnumerable<CandidateActionWithParams> allowedCandidates)\n            {\n                HttpMethod incomingMethod = controllerContext.Request.Method;\n                HttpResponseMessage response = controllerContext.Request.CreateErrorResponse(\n                    HttpStatusCode.MethodNotAllowed,\n                    Error.Format(SRResources.ApiControllerActionSelector_HttpMethodNotSupported, incomingMethod));\n\n                // 405 must include an Allow content-header with the allowable methods.\n                // See: https://tools.ietf.org/html/rfc2616#section-14.7\n                HashSet<HttpMethod> methods = new HashSet<HttpMethod>();\n                foreach (var candidate in allowedCandidates)\n                {\n                    methods.UnionWith(candidate.ActionDescriptor.SupportedHttpMethods);\n                }\n                foreach (var method in methods)\n                {\n                    response.Content.Headers.Allow.Add(method.ToString());\n                }\n\n                return response;\n            }\n\n            // Create a 404\n            private HttpResponseMessage CreateActionNotFoundResponse(HttpControllerContext controllerContext)\n            {\n                return controllerContext.Request.CreateErrorResponse(\n                    HttpStatusCode.NotFound,\n                    Error.Format(SRResources.ResourceNotFound, controllerContext.Request.RequestUri),\n                    Error.Format(SRResources.ApiControllerActionSelector_ActionNotFound, _controllerDescriptor.ControllerName));\n            }\n\n            // Create a 404, including the name of the action we were looking for. \n            // This overload includes the action name. \n            private HttpResponseMessage CreateActionNotFoundResponse(HttpControllerContext controllerContext, string actionName)\n            {\n                return controllerContext.Request.CreateErrorResponse(\n                    HttpStatusCode.NotFound,\n                    Error.Format(SRResources.ResourceNotFound, controllerContext.Request.RequestUri),\n                    Error.Format(SRResources.ApiControllerActionSelector_ActionNameNotFound, _controllerDescriptor.ControllerName, actionName));\n            }\n\n            // Call for direct routes. \n            private static List<CandidateActionWithParams> GetInitialCandidateWithParameterListForDirectRoutes(HttpControllerContext controllerContext, IEnumerable<IHttpRouteData> subRoutes, bool ignoreVerbs)\n            {\n                HttpRequestMessage request = controllerContext.Request;\n                HttpMethod incomingMethod = controllerContext.Request.Method;\n\n                var queryNameValuePairs = request.GetQueryNameValuePairs();\n\n                List<CandidateActionWithParams> candidateActionWithParams = new List<CandidateActionWithParams>();\n\n                foreach (IHttpRouteData subRouteData in subRoutes)\n                {\n                    // Each route may have different route parameters.\n                    ISet<string> combinedParameterNames = GetCombinedParameterNames(queryNameValuePairs, subRouteData.Values);\n\n                    CandidateAction[] candidates = subRouteData.Route.GetDirectRouteCandidates();\n\n                    string actionName;\n                    subRouteData.Values.TryGetValue(RouteValueKeys.Action, out actionName);\n\n                    foreach (var candidate in candidates)\n                    {\n                        if ((actionName == null) || candidate.MatchName(actionName))\n                        {\n                            if (ignoreVerbs || candidate.MatchVerb(incomingMethod))\n                            {\n                                candidateActionWithParams.Add(new CandidateActionWithParams(candidate, combinedParameterNames, subRouteData));\n                            }\n                        }\n                    }\n                }\n                return candidateActionWithParams;\n            }\n\n            // Call for non-direct routes\n            private IEnumerable<CandidateActionWithParams> GetInitialCandidateWithParameterListForRegularRoutes(HttpControllerContext controllerContext, bool ignoreVerbs = false)\n            {\n                CandidateAction[] candidates = GetInitialCandidateList(controllerContext, ignoreVerbs);\n                return GetCandidateActionsWithBindings(controllerContext, candidates);\n            }\n\n            private CandidateAction[] GetInitialCandidateList(HttpControllerContext controllerContext, bool ignoreVerbs = false)\n            {\n                // Initial candidate list is determined by:\n                // - Direct route?\n                // - {action} value?\n                // - ignore verbs?\n                string actionName;\n\n                HttpMethod incomingMethod = controllerContext.Request.Method;\n                IHttpRouteData routeData = controllerContext.RouteData;\n\n                Contract.Assert(routeData.GetSubRoutes() == null, \"Should not be called on a direct route\");\n                CandidateAction[] candidates;\n\n                if (routeData.Values.TryGetValue(RouteValueKeys.Action, out actionName))\n                {\n                    // We have an explicit {action} value, do traditional binding. Just lookup by actionName\n                    HttpActionDescriptor[] actionsFoundByName = _standardActions.StandardActionNameMapping[actionName].ToArray();\n\n                    // Throws HttpResponseException with NotFound status because no action matches the Name\n                    if (actionsFoundByName.Length == 0)\n                    {\n                        throw new HttpResponseException(CreateActionNotFoundResponse(controllerContext, actionName));\n                    }\n\n                    CandidateAction[] candidatesFoundByName = new CandidateAction[actionsFoundByName.Length];\n\n                    for (int i = 0; i < actionsFoundByName.Length; i++)\n                    {\n                        candidatesFoundByName[i] = new CandidateAction\n                        {\n                            ActionDescriptor = actionsFoundByName[i]\n                        };\n                    }\n\n                    if (ignoreVerbs)\n                    {\n                        candidates = candidatesFoundByName;\n                    }\n                    else\n                    {\n                        candidates = FilterIncompatibleVerbs(incomingMethod, candidatesFoundByName);\n                    }\n                }\n                else\n                {\n                    if (ignoreVerbs)\n                    {\n                        candidates = _standardActions.StandardCandidateActions;\n                    }\n                    else\n                    {\n                        // No direct routing or {action} parameter, infer it from the verb.\n                        candidates = FindActionsForVerb(incomingMethod, _standardActions.CacheListVerbs, _standardActions.StandardCandidateActions);\n                    }\n                }\n\n                return candidates;\n            }\n\n            private static CandidateAction[] FilterIncompatibleVerbs(HttpMethod incomingMethod, CandidateAction[] candidatesFoundByName)\n            {\n                return candidatesFoundByName.Where(candidate => candidate.ActionDescriptor.SupportedHttpMethods.Contains(incomingMethod)).ToArray();\n            }\n\n            public ILookup<string, HttpActionDescriptor> GetActionMapping()\n            {\n                return _combinedActionNameMapping;\n            }\n\n            // Get a non-null set that combines both the route and query parameters. \n            private static ISet<string> GetCombinedParameterNames(IEnumerable<KeyValuePair<string, string>> queryNameValuePairs, IDictionary<string, object> routeValues)\n            {\n                HashSet<string> routeParameterNames = new HashSet<string>(routeValues.Keys, StringComparer.OrdinalIgnoreCase);\n                routeParameterNames.Remove(RouteValueKeys.Controller);\n                routeParameterNames.Remove(RouteValueKeys.Action);\n\n                var combinedParameterNames = new HashSet<string>(routeParameterNames, StringComparer.OrdinalIgnoreCase);\n                if (queryNameValuePairs != null)\n                {\n                    foreach (var queryNameValuePair in queryNameValuePairs)\n                    {\n                        combinedParameterNames.Add(queryNameValuePair.Key);\n                    }\n                }\n                return combinedParameterNames;\n            }\n\n            private List<CandidateActionWithParams> FindActionMatchRequiredRouteAndQueryParameters(IEnumerable<CandidateActionWithParams> candidatesFound)\n            {\n                List<CandidateActionWithParams> matches = new List<CandidateActionWithParams>();\n\n                foreach (var candidate in candidatesFound)\n                {\n                    HttpActionDescriptor descriptor = candidate.ActionDescriptor;\n                    if (IsSubset(_actionParameterNames[descriptor], candidate.CombinedParameterNames))\n                    {\n                        matches.Add(candidate);\n                    }\n                }\n\n                return matches;\n            }\n\n            private List<CandidateActionWithParams> FindActionMatchMostRouteAndQueryParameters(List<CandidateActionWithParams> candidatesFound)\n            {\n                if (candidatesFound.Count > 1)\n                {\n                    // select the results that match the most number of required parameters\n                    return candidatesFound\n                        .GroupBy(candidate => _actionParameterNames[candidate.ActionDescriptor].Length)\n                        .OrderByDescending(g => g.Key)\n                        .First()\n                        .ToList();\n                }\n\n                return candidatesFound;\n            }\n\n            // Given a list of candidate actionsByVerb, return a parallel list that includes the parameter information. \n            // This is used for regular routing where all candidates come from a single route, so they all share the same route parameter names. \n            private static CandidateActionWithParams[] GetCandidateActionsWithBindings(HttpControllerContext controllerContext, CandidateAction[] candidatesFound)\n            {\n                HttpRequestMessage request = controllerContext.Request;\n                var queryNameValuePairs = request.GetQueryNameValuePairs();\n                IHttpRouteData routeData = controllerContext.RouteData;\n                IDictionary<string, object> routeValues = routeData.Values;\n                ISet<string> combinedParameterNames = GetCombinedParameterNames(queryNameValuePairs, routeValues);\n\n                CandidateActionWithParams[] candidatesWithParams = Array.ConvertAll(candidatesFound, candidate => new CandidateActionWithParams(candidate, combinedParameterNames, routeData));\n                return candidatesWithParams;\n            }\n\n            private static bool IsSubset(string[] actionParameters, ISet<string> routeAndQueryParameters)\n            {\n                foreach (string actionParameter in actionParameters)\n                {\n                    if (!routeAndQueryParameters.Contains(actionParameter))\n                    {\n                        return false;\n                    }\n                }\n\n                return true;\n            }\n\n            private static List<CandidateActionWithParams> RunOrderFilter(List<CandidateActionWithParams> candidatesFound)\n            {\n                if (candidatesFound.Count == 0)\n                {\n                    return candidatesFound;\n                }\n                int minOrder = candidatesFound.Min(c => c.CandidateAction.Order);\n                return candidatesFound.Where(c => c.CandidateAction.Order == minOrder).AsList();\n            }\n\n            private static List<CandidateActionWithParams> RunPrecedenceFilter(List<CandidateActionWithParams> candidatesFound)\n            {\n                if (candidatesFound.Count == 0)\n                {\n                    return candidatesFound;\n                }\n                decimal highestPrecedence = candidatesFound.Min(c => c.CandidateAction.Precedence);\n                return candidatesFound.Where(c => c.CandidateAction.Precedence == highestPrecedence).AsList();\n            }\n\n            // This is called when we don't specify an Action name\n            // Get list of actionsByVerb that match a given verb. This can match by name or IActionHttpMethodSelector\n            private static CandidateAction[] FindActionsForVerb(HttpMethod verb, CandidateAction[][] actionsByVerb, CandidateAction[] otherActions)\n            {\n                // Check cache for common verbs.\n                for (int i = 0; i < _cacheListVerbKinds.Length; i++)\n                {\n                    // verb selection on common verbs is normalized to have object reference identity.\n                    // This is significantly more efficient than comparing the verbs based on strings.\n                    if (Object.ReferenceEquals(verb, _cacheListVerbKinds[i]))\n                    {\n                        return actionsByVerb[i];\n                    }\n                }\n\n                // General case for any verbs.\n                return FindActionsForVerbWorker(verb, otherActions);\n            }\n\n            // Given a list of actionsByVerb, filter it to ones that match a given verb. This can match by name or IActionHttpMethodSelector.\n            // Since this list is fixed for a given verb type, it can be pre-computed and cached.\n            // This function should not do caching. It's the helper that builds the caches.\n            private static CandidateAction[] FindActionsForVerbWorker(HttpMethod verb, CandidateAction[] candidates)\n            {\n                List<CandidateAction> listCandidates = new List<CandidateAction>();\n\n                FindActionsForVerbWorker(verb, candidates, listCandidates);\n\n                return listCandidates.ToArray();\n            }\n\n            // Adds to existing list rather than send back as a return value.\n            private static void FindActionsForVerbWorker(HttpMethod verb, CandidateAction[] candidates, List<CandidateAction> listCandidates)\n            {\n                foreach (CandidateAction candidate in candidates)\n                {\n                    if (candidate.ActionDescriptor != null && candidate.ActionDescriptor.SupportedHttpMethods.Contains(verb))\n                    {\n                        listCandidates.Add(candidate);\n                    }\n                }\n            }\n\n            private static string CreateAmbiguousMatchList(IEnumerable<CandidateActionWithParams> ambiguousCandidates)\n            {\n                StringBuilder exceptionMessageBuilder = new StringBuilder();\n                foreach (CandidateActionWithParams candidate in ambiguousCandidates)\n                {\n                    HttpActionDescriptor descriptor = candidate.ActionDescriptor;\n                    Contract.Assert(descriptor != null);\n\n                    string controllerTypeName;\n\n                    if (descriptor.ControllerDescriptor != null\n                        && descriptor.ControllerDescriptor.ControllerType != null)\n                    {\n                        controllerTypeName = descriptor.ControllerDescriptor.ControllerType.FullName;\n                    }\n                    else\n                    {\n                        controllerTypeName = String.Empty;\n                    }\n\n                    exceptionMessageBuilder.AppendLine();\n                    exceptionMessageBuilder.Append(Error.Format(\n                        SRResources.ActionSelector_AmbiguousMatchType,\n                        descriptor.ActionName, controllerTypeName));\n                }\n\n                return exceptionMessageBuilder.ToString();\n            }\n\n            private static bool IsValidActionMethod(MethodInfo methodInfo)\n            {\n                if (methodInfo.IsSpecialName)\n                {\n                    // not a normal method, e.g. a constructor or an event\n                    return false;\n                }\n\n                if (methodInfo.GetBaseDefinition().DeclaringType.IsAssignableFrom(TypeHelper.ApiControllerType))\n                {\n                    // is a method on Object, IHttpController, ApiController\n                    return false;\n                }\n\n                if (methodInfo.GetCustomAttribute<NonActionAttribute>() != null)\n                {\n                    return false;\n                }\n\n                return true;\n            }\n        }\n\n        // Associate parameter (route and query) with each action. \n        // For regular routing, there was just a single route, and so single set of route parameters and so all of these\n        // may share the same set of combined parameter names.\n        // For attribute routing, there may be multiple routes, each with different route parameter names, and \n        // so each instance of a CandidateActionWithParams may have a different parameter set.\n        [DebuggerDisplay(\"{DebuggerToString()}\")]\n        private class CandidateActionWithParams\n        {\n            public CandidateActionWithParams(CandidateAction candidateAction, ISet<string> parameters, IHttpRouteData routeDataSource)\n            {\n                CandidateAction = candidateAction;\n                CombinedParameterNames = parameters;\n                RouteDataSource = routeDataSource;\n            }\n\n            public CandidateAction CandidateAction { get; private set; }\n            public ISet<string> CombinedParameterNames { get; private set; }\n\n            // Remember this so that we can apply it for model binding. \n            public IHttpRouteData RouteDataSource { get; private set; }\n\n            public HttpActionDescriptor ActionDescriptor\n            {\n                get\n                {\n                    return CandidateAction.ActionDescriptor;\n                }\n            }\n\n            [SuppressMessage(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\", Justification = \"Called from DebuggerDisplay\")]\n            private string DebuggerToString()\n            {\n                StringBuilder sb = new StringBuilder();\n                sb.Append(CandidateAction.DebuggerToString());\n                if (CombinedParameterNames.Count > 0)\n                {\n                    sb.Append(\", Params =\");\n                    foreach (string param in CombinedParameterNames)\n                    {\n                        sb.AppendFormat(\" {0}\", param);\n                    }\n                }\n                return sb.ToString();\n            }\n        }\n\n        // A cache of the 'standard actions' for a controller - the actions that are reachable via traditional routes.\n        private class StandardActionSelectionCache\n        {\n            // Includes action descriptors only for actions accessible via standard routing (without route attributes).\n            public ILookup<string, HttpActionDescriptor> StandardActionNameMapping { get; set; }\n\n            // Includes action descriptors only for actions accessible via standard routing (without route attributes).\n            public CandidateAction[] StandardCandidateActions { get; set; }\n\n            public CandidateAction[][] CacheListVerbs { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/AuthenticationFilterResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Hosting;\n\nnamespace System.Web.Http.Controllers\n{\n    internal class AuthenticationFilterResult : IHttpActionResult\n    {\n        private readonly HttpActionContext _context;\n        private readonly ApiController _controller;\n        private readonly IAuthenticationFilter[] _filters;\n        private readonly IHttpActionResult _innerResult;\n\n        public AuthenticationFilterResult(HttpActionContext context, ApiController controller,\n            IAuthenticationFilter[] filters, IHttpActionResult innerResult)\n        {\n            Contract.Assert(context != null);\n            Contract.Assert(controller != null);\n            Contract.Assert(filters != null);\n            Contract.Assert(innerResult != null);\n\n            _context = context;\n            _controller = controller;\n            _filters = filters;\n            _innerResult = innerResult;\n        }\n\n        public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)\n        {\n            IHttpActionResult result = _innerResult;\n            IPrincipal originalPrincipal = _controller.User;\n            HttpAuthenticationContext authenticationContext = new HttpAuthenticationContext(_context,\n                originalPrincipal);\n\n            for (int i = 0; i < _filters.Length; i++)\n            {\n                IAuthenticationFilter filter = _filters[i];\n                await filter.AuthenticateAsync(authenticationContext, cancellationToken);\n\n                IHttpActionResult error = authenticationContext.ErrorResult;\n\n                // Short-circuit on the first authentication filter to provide an error result.\n                if (error != null)\n                {\n                    result = error;\n                    break;\n                }\n            }\n\n            IPrincipal newPrincipal = authenticationContext.Principal;\n\n            if (newPrincipal != originalPrincipal)\n            {\n                _controller.User = newPrincipal;\n            }\n\n            // Run challenge on all filters (passing the result of each into the next). If a filter failed, the\n            // challenges run on the failure result. If no filter failed, the challenges run on the original inner\n            // result.\n            HttpAuthenticationChallengeContext challengeContext = new HttpAuthenticationChallengeContext(_context,\n                result);\n\n            for (int i = 0; i < _filters.Length; i++)\n            {\n                IAuthenticationFilter filter = _filters[i];\n                await filter.ChallengeAsync(challengeContext, cancellationToken);\n            }\n\n            Contract.Assert(challengeContext.Result != null);\n            result = challengeContext.Result;\n\n            return await result.ExecuteAsync(cancellationToken);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/AuthorizationFilterResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Filters;\n\nnamespace System.Web.Http.Controllers\n{\n    internal class AuthorizationFilterResult : IHttpActionResult\n    {\n        private readonly HttpActionContext _context;\n        private readonly IAuthorizationFilter[] _filters;\n        private readonly IHttpActionResult _innerResult;\n\n        public AuthorizationFilterResult(HttpActionContext context, IAuthorizationFilter[] filters,\n            IHttpActionResult innerResult)\n        {\n            Contract.Assert(context != null);\n            Contract.Assert(filters != null);\n            Contract.Assert(innerResult != null);\n\n            _context = context;\n            _filters = filters;\n            _innerResult = innerResult;\n        }\n\n        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)\n        {\n            // We need to reverse the filter list so that least specific filters (Global) get run first and the most\n            // specific filters (Action) get run last.\n            Func<Task<HttpResponseMessage>> result = () => _innerResult.ExecuteAsync(cancellationToken);\n            for (int i = _filters.Length - 1; i >= 0; i--)\n            {\n                IAuthorizationFilter filter = _filters[i];\n                Func<Func<Task<HttpResponseMessage>>, IAuthorizationFilter, Func<Task<HttpResponseMessage>>>\n                    chainContinuation = (continuation, innerFilter) =>\n                    {\n                        return () => innerFilter.ExecuteAuthorizationFilterAsync(_context, cancellationToken,\n                            continuation);\n                    };\n                result = chainContinuation(result, filter);\n            }\n\n            return result();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/CandidateAction.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.Routing\n{\n    // This is static description of an action and can be shared across requests. \n    // Direct routes may cache a list of these. \n    [DebuggerDisplay(\"{DebuggerToString()}\")]\n    internal class CandidateAction\n    {\n        public HttpActionDescriptor ActionDescriptor { get; set; }\n        public int Order { get; set; }\n        public decimal Precedence { get; set; }\n\n        public bool MatchName(string actionName)\n        {\n            return String.Equals(ActionDescriptor.ActionName, actionName, StringComparison.OrdinalIgnoreCase);\n        }\n\n        public bool MatchVerb(HttpMethod method)\n        {\n            return ActionDescriptor.SupportedHttpMethods.Contains(method);\n        }\n\n        internal string DebuggerToString()\n        {\n            return String.Format(CultureInfo.CurrentCulture, \"{0}, Order={1}, Prec={2}\", ActionDescriptor.ActionName, Order, Precedence);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/ExceptionFilterResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics;\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Runtime.ExceptionServices;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Filters;\n\nnamespace System.Web.Http.Controllers\n{\n    internal class ExceptionFilterResult : IHttpActionResult\n    {\n        private readonly HttpActionContext _context;\n        private readonly IExceptionFilter[] _filters;\n        private readonly IExceptionLogger _exceptionLogger;\n        private readonly IExceptionHandler _exceptionHandler;\n\n        private readonly IHttpActionResult _innerResult;\n\n        public ExceptionFilterResult(HttpActionContext context, IExceptionFilter[] filters,\n            IExceptionLogger exceptionLogger, IExceptionHandler exceptionHandler, IHttpActionResult innerResult)\n        {\n            Contract.Assert(context != null);\n            Contract.Assert(filters != null);\n            Contract.Assert(exceptionLogger != null);\n            Contract.Assert(exceptionHandler != null);\n            Contract.Assert(innerResult != null);\n\n            _context = context;\n            _filters = filters;\n            _exceptionLogger = exceptionLogger;\n            _exceptionHandler = exceptionHandler;\n            _innerResult = innerResult;\n        }\n\n        public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)\n        {\n            ExceptionDispatchInfo exceptionInfo;\n\n            try\n            {\n                return await _innerResult.ExecuteAsync(cancellationToken);\n            }\n            catch (Exception e)\n            {\n                exceptionInfo = ExceptionDispatchInfo.Capture(e);\n            }\n\n            // This code path only runs if the task is faulted with an exception\n            Exception exception = exceptionInfo.SourceException;\n            Debug.Assert(exception != null);\n\n            bool isCancellationException = exception is OperationCanceledException;\n\n            ExceptionContext exceptionContext = new ExceptionContext(\n                exception,\n                ExceptionCatchBlocks.IExceptionFilter,\n                _context);\n\n            if (!isCancellationException)\n            {\n                // We don't log cancellation exceptions because it doesn't represent an error.\n                await _exceptionLogger.LogAsync(exceptionContext, cancellationToken);\n            }\n\n            HttpActionExecutedContext executedContext = new HttpActionExecutedContext(_context, exception);\n\n            // Note: exception filters need to be scheduled in the reverse order so that\n            // the more specific filter (e.g. Action) executes before the less specific ones (e.g. Global)\n            for (int i = _filters.Length - 1; i >= 0; i--)\n            {\n                IExceptionFilter exceptionFilter = _filters[i];\n                await exceptionFilter.ExecuteExceptionFilterAsync(executedContext, cancellationToken);\n            }\n\n            if (executedContext.Response == null && !isCancellationException)\n            {\n                // We don't log cancellation exceptions because it doesn't represent an error.\n                executedContext.Response = await _exceptionHandler.HandleAsync(exceptionContext, cancellationToken);\n            }\n\n            if (executedContext.Response != null)\n            {\n                return executedContext.Response;\n            }\n            else\n            {\n                // Preserve the original stack trace when the exception is not changed by any filter.\n                if (exception == executedContext.Exception)\n                {\n                    exceptionInfo.Throw();\n                }\n\n                // If the exception is changed by a filter, throw the new exception instead.\n                throw executedContext.Exception;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/FilterGrouping.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Http.Filters;\n\nnamespace System.Web.Http.Controllers\n{\n    /// <summary>\n    /// Quickly split filters into different types\n    /// </summary>\n    internal class FilterGrouping\n    {\n        private IActionFilter[] _actionFilters;\n        private IAuthorizationFilter[] _authorizationFilters;\n        private IAuthenticationFilter[] _authenticationFilters;\n        private IExceptionFilter[] _exceptionFilters;\n\n        public FilterGrouping(IEnumerable<FilterInfo> filters)\n        {\n            // evaluate the 'filters' enumerable only once since the operation can be quite expensive\n            List<FilterInfo> orderedCache = filters.ToList();\n\n            List<FilterInfo> overrides = orderedCache.Where(f => f.Instance is IOverrideFilter).ToList();\n\n            FilterScope actionOverride = SelectLastOverrideScope<IActionFilter>(overrides);\n            FilterScope authorizationOverride = SelectLastOverrideScope<IAuthorizationFilter>(overrides);\n            FilterScope authenticationOverride = SelectLastOverrideScope<IAuthenticationFilter>(overrides);\n            FilterScope exceptionOverride = SelectLastOverrideScope<IExceptionFilter>(overrides);\n\n            _actionFilters = SelectAvailable<IActionFilter>(orderedCache, actionOverride);\n            _authorizationFilters = SelectAvailable<IAuthorizationFilter>(orderedCache, authorizationOverride);\n            _authenticationFilters = SelectAvailable<IAuthenticationFilter>(orderedCache, authenticationOverride);\n            _exceptionFilters = SelectAvailable<IExceptionFilter>(orderedCache, exceptionOverride);\n        }\n\n        public IActionFilter[] ActionFilters\n        {\n            get { return _actionFilters; }\n        }\n\n        public IAuthorizationFilter[] AuthorizationFilters\n        {\n            get { return _authorizationFilters; }\n        }\n\n        public IAuthenticationFilter[] AuthenticationFilters\n        {\n            get { return _authenticationFilters; }\n        }\n\n        public IExceptionFilter[] ExceptionFilters\n        {\n            get { return _exceptionFilters; }\n        }\n\n        private static T[] SelectAvailable<T>(List<FilterInfo> filters, FilterScope overrideFiltersBeforeScope)\n        {\n            // Determine which filters are available for this filter type, given the current overrides in place.\n            // A filter should be processed if:\n            //  1. It implements the appropriate interface for this filter type.\n            //  2. It has not been overridden (its scope is not before the scope of the last override for this\n            //     type).\n            return filters.Where(f => f.Scope >= overrideFiltersBeforeScope\n                && (f.Instance is T)).Select(f => (T)f.Instance).ToArray();\n        }\n\n        private static FilterScope SelectLastOverrideScope<T>(List<FilterInfo> overrideFilters)\n        {\n            // A filter type (such as action filter) can be overridden, which means every filter of that type at an\n            // earlier scope must be ignored. Determine the scope of the last override filter (if any). Only\n            // filters at this scope or later will be processed.\n\n            FilterInfo lastOverride = overrideFilters.Where(\n                f => ((IOverrideFilter)f.Instance).FiltersToOverride == typeof(T)).LastOrDefault();\n\n            // If no override is present, the filter is not overridden (and filters at any scope, starting with\n            // First are processed). Not overriding a filter is equivalent to placing an override at the First\n            // filter scope (since there's nothing before First to override).\n            if (lastOverride == null)\n            {\n                return FilterScope.Global;\n            }\n\n            return lastOverride.Scope;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/HttpActionBinding.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Metadata;\n\nnamespace System.Web.Http.Controllers\n{\n    /// <summary>\n    /// This describes *how* the binding will happen. Does not actually bind. \n    /// This is static for a given action descriptor and can be reused across requests. \n    /// This may be a nice thing to log. Or set a breakpoint after we create and preview what's about to happen. \n    /// In theory, this could be precompiled for each Action descriptor.  \n    /// </summary>\n    public class HttpActionBinding\n    {\n        private HttpActionDescriptor _actionDescriptor;\n        private HttpParameterBinding[] _parameterBindings;\n\n        private ModelMetadataProvider _metadataProvider;\n\n        public HttpActionBinding()\n        {\n        }\n\n        public HttpActionBinding(HttpActionDescriptor actionDescriptor, HttpParameterBinding[] bindings)\n        {\n            ActionDescriptor = actionDescriptor;\n            ParameterBindings = bindings;\n        }\n\n        /// <summary>\n        /// Back pointer to the action this binding is for. \n        /// This can also provide the Type[], string[] names for the parameters.\n        /// </summary>\n        public HttpActionDescriptor ActionDescriptor\n        {\n            get\n            {\n                return _actionDescriptor;\n            }\n            set\n            {\n                if (value == null)\n                {\n                    throw new ArgumentNullException(\"value\");\n                }\n                _actionDescriptor = value;\n            }\n        }\n\n        /// <summary>\n        /// Specifies synchronous bindings for each parameter.This is a parallel array to the ActionDescriptor's parameter array. \n        /// </summary>\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1819:PropertiesShouldNotReturnArrays\", Justification = \"Want an array\")]\n        public HttpParameterBinding[] ParameterBindings\n        {\n            get\n            {\n                return _parameterBindings;\n            }\n            set\n            {\n                if (value == null)\n                {\n                    throw new ArgumentNullException(\"value\");\n                }\n                _parameterBindings = value;\n            }\n        }\n\n        public virtual Task ExecuteBindingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)\n        {\n            if (_parameterBindings.Length == 0)\n            {\n                return TaskHelpers.Completed();\n            }\n\n            // First, make sure the actionBinding is valid before trying to execute it. This keeps us in a known state in case of errors.\n            for (int i = 0; i < ParameterBindings.Length; i++)\n            {\n                HttpParameterBinding parameterBinder = ParameterBindings[i];\n                if (!parameterBinder.IsValid)\n                {\n                    // Throwing an exception because the webService developer's action signature is bad.\n                    // This exception will be caught and converted into a 500 by the dispatcher\n                    throw new InvalidOperationException(parameterBinder.ErrorMessage);\n                }\n            }\n\n            if (_metadataProvider == null)\n            {\n                HttpConfiguration config = actionContext.ControllerContext.Configuration;\n                _metadataProvider = config.Services.GetModelMetadataProvider();\n            }\n\n            return ExecuteBindingAsyncCore(actionContext, cancellationToken);\n        }\n\n        private async Task ExecuteBindingAsyncCore(HttpActionContext actionContext, CancellationToken cancellationToken)\n        {\n            // Execute all the binders.\n            for (int index = 0; index < ParameterBindings.Length; index++)\n            {\n                HttpParameterBinding parameterBinder = ParameterBindings[index];\n\n                await parameterBinder.ExecuteBindingAsync(_metadataProvider, actionContext, cancellationToken);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/HttpActionContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Web.Http.ModelBinding;\n\nnamespace System.Web.Http.Controllers\n{\n    /// <summary>\n    /// Contains information for the executing action.\n    /// </summary>\n    public class HttpActionContext\n    {\n        private readonly ModelStateDictionary _modelState = new ModelStateDictionary();\n        private readonly Dictionary<string, object> _operationArguments = new Dictionary<string, object>();\n        private HttpActionDescriptor _actionDescriptor;\n        private HttpControllerContext _controllerContext;\n       \n        public HttpActionContext(HttpControllerContext controllerContext, HttpActionDescriptor actionDescriptor)\n        {\n            if (controllerContext == null)\n            {\n                throw Error.ArgumentNull(\"controllerContext\");\n            }\n\n            if (actionDescriptor == null)\n            {\n                throw Error.ArgumentNull(\"actionDescriptor\");\n            }\n\n            _controllerContext = controllerContext;\n            _actionDescriptor = actionDescriptor;\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpActionContext\"/> class.\n        /// </summary>\n        /// <remarks>The default constructor is intended for use by unit testing only.</remarks>\n        public HttpActionContext()\n        {\n        }\n\n        public HttpControllerContext ControllerContext\n        {\n            get { return _controllerContext; }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n\n                _controllerContext = value;\n            }\n        }\n\n        public HttpActionDescriptor ActionDescriptor\n        {\n            get { return _actionDescriptor; }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n\n                _actionDescriptor = value;\n            }\n        }\n\n        public ModelStateDictionary ModelState\n        {\n            get { return _modelState; }\n        }\n\n        public Dictionary<string, object> ActionArguments\n        {\n            get { return _operationArguments; }\n        }\n\n        public HttpResponseMessage Response { get; set; }\n\n        /// <summary>\n        /// Gets the current <see cref=\"HttpRequestMessage\"/>.\n        /// </summary>\n        public HttpRequestMessage Request\n        {\n            get { return _controllerContext != null ? _controllerContext.Request : null; }\n        }\n\n        /// <summary>\n        /// Gets the current <see cref=\"HttpRequestContext\"/>.\n        /// </summary>\n        public HttpRequestContext RequestContext\n        {\n            get { return _controllerContext != null ? _controllerContext.RequestContext : null; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/HttpActionContextExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing System.Runtime.CompilerServices;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.Validation;\n\nnamespace System.Web.Http.Controllers\n{\n    /// <summary>\n    /// Extension methods for <see cref=\"HttpActionContext\"/>.\n    /// </summary>\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class HttpActionContextExtensions\n    {\n        /// <summary>\n        /// Gets the <see cref=\"ModelMetadataProvider\"/> instance for a given <see cref=\"HttpActionContext\"/>.\n        /// </summary>\n        /// <param name=\"actionContext\">The context.</param>\n        /// <returns>An <see cref=\"ModelMetadataProvider\"/> instance.</returns>\n        public static ModelMetadataProvider GetMetadataProvider(this HttpActionContext actionContext)\n        {\n            if (actionContext == null)\n            {\n                throw Error.ArgumentNull(\"actionContext\");\n            }\n\n            return actionContext.ControllerContext.Configuration.Services.GetModelMetadataProvider();\n        }\n\n        /// <summary>\n        /// Gets the collection of registered <see cref=\"ModelValidatorProvider\"/> instances.\n        /// </summary>\n        /// <param name=\"actionContext\">The context.</param>\n        /// <returns>A collection of <see cref=\"ModelValidatorProvider\"/> instances.</returns>\n        public static IEnumerable<ModelValidatorProvider> GetValidatorProviders(this HttpActionContext actionContext)\n        {\n            if (actionContext == null)\n            {\n                throw Error.ArgumentNull(\"actionContext\");\n            }\n\n            return actionContext.ControllerContext.Configuration.Services.GetModelValidatorProviders();\n        }\n\n        /// <summary>\n        /// Gets the collection of registered <see cref=\"ModelValidator\"/> instances.\n        /// </summary>\n        /// <param name=\"actionContext\">The context.</param>\n        /// <param name=\"metadata\">The metadata.</param>\n        /// <returns>A collection of registered <see cref=\"ModelValidator\"/> instances.</returns>\n        public static IEnumerable<ModelValidator> GetValidators(this HttpActionContext actionContext, ModelMetadata metadata)\n        {\n            if (actionContext == null)\n            {\n                throw Error.ArgumentNull(\"actionContext\");\n            }\n\n            IModelValidatorCache validatorCache = actionContext.GetValidatorCache();\n            return actionContext.GetValidators(metadata, validatorCache);\n        }\n\n        internal static IEnumerable<ModelValidator> GetValidators(this HttpActionContext actionContext, ModelMetadata metadata, IModelValidatorCache validatorCache)\n        {\n            if (validatorCache == null)\n            {\n                // slow path: there is no validator cache on the configuration\n                return metadata.GetValidators(actionContext.GetValidatorProviders());\n            }\n            else\n            {\n                return validatorCache.GetValidators(metadata);\n            }\n        }\n\n        internal static IModelValidatorCache GetValidatorCache(this HttpActionContext actionContext)\n        {\n            Contract.Assert(actionContext != null);\n\n            HttpConfiguration configuration = actionContext.ControllerContext.Configuration;\n            return configuration.Services.GetModelValidatorCache();\n        }\n\n        public static bool TryBindStrongModel<TModel>(this HttpActionContext actionContext, ModelBindingContext parentBindingContext, string propertyName, ModelMetadataProvider metadataProvider, out TModel model)\n        {\n            if (actionContext == null)\n            {\n                throw Error.ArgumentNull(\"actionContext\");\n            }\n\n            ModelBindingContext propertyBindingContext = new ModelBindingContext(parentBindingContext)\n            {\n                ModelMetadata = metadataProvider.GetMetadataForType(null, typeof(TModel)),\n                ModelName = ModelBindingHelper.CreatePropertyModelName(parentBindingContext.ModelName, propertyName)\n            };\n\n            if (actionContext.Bind(propertyBindingContext))\n            {\n                object untypedModel = propertyBindingContext.Model;\n                model = ModelBindingHelper.CastOrDefault<TModel>(untypedModel);\n                parentBindingContext.ValidationNode.ChildNodes.Add(propertyBindingContext.ValidationNode);\n                return true;\n            }\n\n            model = default(TModel);\n            return false;\n        }\n\n        // Pulls binders from the config\n        public static bool Bind(this HttpActionContext actionContext, ModelBindingContext bindingContext)\n        {\n            Type modelType = bindingContext.ModelType;\n            HttpConfiguration config = actionContext.ControllerContext.Configuration;\n\n            IEnumerable<IModelBinder> binders = from provider in config.Services.GetModelBinderProviders()\n                                                select provider.GetBinder(config, modelType);\n\n            return Bind(actionContext, bindingContext, binders);\n        }\n\n        /// <summary>\n        /// Attempt to bind against the given ActionContext.\n        /// </summary>\n        /// <param name=\"actionContext\">The action context.</param>\n        /// <param name=\"bindingContext\">The binding context.</param>\n        /// <param name=\"binders\">set of binders to use for binding</param>\n        /// <returns>True if the bind was successful, else false.</returns>\n        public static bool Bind(this HttpActionContext actionContext, ModelBindingContext bindingContext, IEnumerable<IModelBinder> binders)\n        {\n            if (actionContext == null)\n            {\n                throw Error.ArgumentNull(\"actionContext\");\n            }\n\n            if (bindingContext == null)\n            {\n                throw Error.ArgumentNull(\"bindingContext\");\n            }\n\n            // Protects against stack overflow for deeply nested model binding\n            RuntimeHelpers.EnsureSufficientExecutionStack();\n\n            Type modelType = bindingContext.ModelType;\n            HttpConfiguration config = actionContext.ControllerContext.Configuration;\n\n            ModelBinderProvider providerFromAttr;\n            if (ModelBindingHelper.TryGetProviderFromAttributes(modelType, out providerFromAttr))\n            {\n                IModelBinder binder = providerFromAttr.GetBinder(config, modelType);\n                if (binder != null)\n                {\n                    return binder.BindModel(actionContext, bindingContext);\n                }\n            }\n\n            foreach (IModelBinder binder in binders)\n            {\n                if (binder != null)\n                {\n                    if (binder.BindModel(actionContext, bindingContext))\n                    {\n                        return true;\n                    }\n                }\n            }\n\n            // Either we couldn't find a binder, or the binder couldn't bind. Distinction is not important.\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/HttpActionDescriptor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Internal;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.Controllers\n{\n    public abstract class HttpActionDescriptor\n    {\n        private readonly ConcurrentDictionary<object, object> _properties = new ConcurrentDictionary<object, object>();\n\n        private IActionResultConverter _converter;\n        private readonly Lazy<Collection<FilterInfo>> _filterPipeline;\n        private FilterGrouping _filterGrouping;\n        private Collection<FilterInfo> _filterPipelineForGrouping;\n\n        private HttpConfiguration _configuration;\n        private HttpControllerDescriptor _controllerDescriptor;\n        private readonly Collection<HttpMethod> _supportedHttpMethods = new Collection<HttpMethod>();\n\n        private HttpActionBinding _actionBinding;\n\n        private static readonly ResponseMessageResultConverter _responseMessageResultConverter = new ResponseMessageResultConverter();\n        private static readonly VoidResultConverter _voidResultConverter = new VoidResultConverter();\n\n        protected HttpActionDescriptor()\n        {\n            _filterPipeline = new Lazy<Collection<FilterInfo>>(InitializeFilterPipeline);\n        }\n\n        protected HttpActionDescriptor(HttpControllerDescriptor controllerDescriptor)\n            : this()\n        {\n            if (controllerDescriptor == null)\n            {\n                throw Error.ArgumentNull(\"controllerDescriptor\");\n            }\n\n            _controllerDescriptor = controllerDescriptor;\n            _configuration = _controllerDescriptor.Configuration;\n        }\n\n        public abstract string ActionName { get; }\n\n        public HttpConfiguration Configuration\n        {\n            get { return _configuration; }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n                _configuration = value;\n            }\n        }\n\n        public virtual HttpActionBinding ActionBinding\n        {\n            get\n            {\n                if (_actionBinding == null)\n                {\n                    ServicesContainer controllerServices = _controllerDescriptor.Configuration.Services;\n                    IActionValueBinder actionValueBinder = controllerServices.GetActionValueBinder();\n                    HttpActionBinding actionBinding = actionValueBinder.GetBinding(this);\n                    _actionBinding = actionBinding;\n                }\n                return _actionBinding;\n            }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n                _actionBinding = value;\n            }\n        }\n\n        public HttpControllerDescriptor ControllerDescriptor\n        {\n            get { return _controllerDescriptor; }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n                _controllerDescriptor = value;\n            }\n        }\n\n        /// <summary>\n        /// The return type of the method or <c>null</c> if the method does not return a value (e.g. a method returning\n        /// <c>void</c>).\n        /// </summary>\n        /// <remarks>\n        /// This property should describe the type of the value contained by the result of executing the action\n        /// via the <see cref=\"ExecuteAsync(HttpControllerContext, IDictionary{string, object}, CancellationToken)\"/>.\n        /// </remarks>\n        public abstract Type ReturnType { get; }\n\n        /// <summary>\n        /// Gets the converter for correctly transforming the result of calling\n        /// <see cref=\"ExecuteAsync(HttpControllerContext, IDictionary{string, object}, CancellationToken)\"/> into an instance of\n        /// <see cref=\"HttpResponseMessage\"/>. \n        /// </summary>\n        /// <remarks>\n        /// <para>This converter is not used when the runtime return value of an action is an <see cref=\"IHttpActionResult\"/>.</para>\n        /// <para>\n        /// This value is <see langword=\"null\" /> when the declared <see cref=\"ReturnType\"/> is an <see cref=\"IHttpActionResult\"/>.\n        /// </para>\n        /// <para>\n        /// The behavior of the returned converter should align with the action's declared <see cref=\"ReturnType\"/>.\n        /// </para>\n        /// </remarks>\n        public virtual IActionResultConverter ResultConverter\n        {\n            get\n            {\n                // This initialization is not thread safe but that's fine since the converters do not have\n                // any interesting state. If 2 threads get 2 different instances of the same converter type\n                // we don't really care.\n                if (_converter == null)\n                {\n                    _converter = GetResultConverter(ReturnType);\n                }\n                return _converter;\n            }\n        }\n\n        public virtual Collection<HttpMethod> SupportedHttpMethods\n        {\n            get { return _supportedHttpMethods; }\n        }\n\n        /// <summary>\n        /// Gets the properties associated with this instance.\n        /// </summary>\n        public virtual ConcurrentDictionary<object, object> Properties\n        {\n            get { return _properties; }\n        }\n\n        /// <summary>\n        /// Gets the custom attributes.\n        /// </summary>\n        /// <typeparam name=\"T\"></typeparam>\n        /// <returns></returns>\n        public virtual Collection<T> GetCustomAttributes<T>() where T : class\n        {\n            return GetCustomAttributes<T>(inherit: true);\n        }\n\n        /// <summary>\n        /// Gets the custom attributes for the action.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of attribute to search for.</typeparam>\n        /// <param name=\"inherit\"><c>true</c> to search this action's inheritance chain to find the attributes; otherwise, <c>false</c>.</param>\n        /// <returns>The collection of custom attributes applied to this action.</returns>\n        public virtual Collection<T> GetCustomAttributes<T>(bool inherit) where T : class\n        {\n            return new Collection<T>();\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Justification = \"Filters can be built dynamically\")]\n        public virtual Collection<IFilter> GetFilters()\n        {\n            return new Collection<IFilter>();\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Justification = \"Parameters can be built dynamically\")]\n        public abstract Collection<HttpParameterDescriptor> GetParameters();\n\n        internal static IActionResultConverter GetResultConverter(Type type)\n        {\n            if (type != null && type.IsGenericParameter)\n            {\n                // This can happen if somebody declares an action method as:\n                // public T Get<T>() { }\n                throw Error.InvalidOperation(SRResources.HttpActionDescriptor_NoConverterForGenericParamterTypeExists, type);\n            }\n\n            if (type == null)\n            {\n                return _voidResultConverter;\n            }\n            else if (typeof(HttpResponseMessage).IsAssignableFrom(type))\n            {\n                return _responseMessageResultConverter;\n            }\n            else if (typeof(IHttpActionResult).IsAssignableFrom(type))\n            {\n                return null;\n            }\n            else\n            {\n                Type valueConverterType = typeof(ValueResultConverter<>).MakeGenericType(type);\n                return TypeActivator.Create<IActionResultConverter>(valueConverterType).Invoke();\n            }\n        }\n\n        /// <summary>\n        /// Executes the described action and returns a <see cref=\"Task{T}\"/> that once completed will\n        /// contain the return value of the action.\n        /// </summary>\n        /// <param name=\"controllerContext\">The context.</param>\n        /// <param name=\"arguments\">The arguments.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A <see cref=\"Task{T}\"/> that once completed will contain the return value of the action.</returns>\n        public abstract Task<object> ExecuteAsync(HttpControllerContext controllerContext, IDictionary<string, object> arguments, CancellationToken cancellationToken);\n\n        /// <summary>\n        /// Returns the filters for the given configuration and action. The filter collection is ordered\n        /// according to the FilterScope (in order from least specific to most specific: First, Global, Controller, Action).\n        /// \n        /// If a given filter disallows duplicates (AllowMultiple=False) then the most specific filter is maintained\n        /// and less specific filters get removed (e.g. if there is a Authorize filter with a Controller scope and another\n        /// one with an Action scope then the one with the Action scope will be maintained and the one with the Controller\n        /// scope will be discarded).\n        /// </summary>\n        /// <returns>A <see cref=\"Collection{T}\"/> of all filters associated with this <see cref=\"HttpActionDescriptor\"/>.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Justification = \"Filter pipeline can be built dynamically\")]\n        public virtual Collection<FilterInfo> GetFilterPipeline()\n        {\n            return _filterPipeline.Value;\n        }\n\n        internal FilterGrouping GetFilterGrouping()\n        {\n            // Performance-sensitive\n            // Filter grouping is expensive so cache whenever possible\n            // For compatibility, the virtual method must be called\n            Collection<FilterInfo> currentFilterPipeline = GetFilterPipeline();\n            if (_filterGrouping == null || _filterPipelineForGrouping != currentFilterPipeline)\n            {\n                _filterGrouping = new FilterGrouping(currentFilterPipeline);\n                _filterPipelineForGrouping = currentFilterPipeline;\n            }\n            return _filterGrouping;\n        }\n\n        private Collection<FilterInfo> InitializeFilterPipeline()\n        {\n            IEnumerable<IFilterProvider> filterProviders = _configuration.Services.GetFilterProviders();\n\n            IEnumerable<FilterInfo> filters = filterProviders.SelectMany(fp => fp.GetFilters(_configuration, this)).OrderBy(f => f, FilterInfoComparer.Instance);\n\n            // Need to discard duplicate filters from the end, so that most specific ones get kept (Action scope) and\n            // less specific ones get removed (Global)\n            filters = RemoveDuplicates(filters.Reverse()).Reverse();\n\n            return new Collection<FilterInfo>(filters.ToList());\n        }\n\n        private static IEnumerable<FilterInfo> RemoveDuplicates(IEnumerable<FilterInfo> filters)\n        {\n            Contract.Assert(filters != null);\n\n            HashSet<Type> visitedTypes = new HashSet<Type>();\n\n            foreach (FilterInfo filter in filters)\n            {\n                object filterInstance = filter.Instance;\n                Type filterInstanceType = filterInstance.GetType();\n\n                if (!visitedTypes.Contains(filterInstanceType) || AllowMultiple(filterInstance))\n                {\n                    yield return filter;\n                    visitedTypes.Add(filterInstanceType);\n                }\n            }\n        }\n\n        private static bool AllowMultiple(object filterInstance)\n        {\n            IFilter filter = filterInstance as IFilter;\n            return filter == null || filter.AllowMultiple;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/HttpActionDescriptorExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Controllers\n{\n    internal static class HttpActionDescriptorExtensions\n    {\n        private const string AttributeRoutedPropertyKey = \"MS_IsAttributeRouted\";\n\n        public static bool IsAttributeRouted(this HttpActionDescriptor actionDescriptor)\n        {\n            if (actionDescriptor == null)\n            {\n                throw new ArgumentNullException(\"actionDescriptor\");\n            }\n\n            object value;\n            actionDescriptor.Properties.TryGetValue(AttributeRoutedPropertyKey, out value);\n            return value as bool? ?? false;\n        }\n\n        public static void SetIsAttributeRouted(this HttpActionDescriptor actionDescriptor, bool value)\n        {\n            if (actionDescriptor == null)\n            {\n                throw new ArgumentNullException(\"actionDescriptor\");\n            }\n\n            actionDescriptor.Properties[AttributeRoutedPropertyKey] = value;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/HttpControllerContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Http.Routing;\n\nnamespace System.Web.Http.Controllers\n{\n    /// <summary>\n    /// Contains information for a single HTTP operation.\n    /// </summary>\n    public class HttpControllerContext\n    {\n        private HttpRequestContext _requestContext;\n        private HttpRequestMessage _request;\n        private HttpControllerDescriptor _controllerDescriptor;\n        private IHttpController _controller;\n\n        /// <summary>Initializes a new instance of the <see cref=\"HttpControllerContext\"/> class.</summary>\n        /// <param name=\"requestContext\">The request context.</param>\n        /// <param name=\"request\">The HTTP request.</param>\n        /// <param name=\"controllerDescriptor\">The controller descriptor.</param>\n        /// <param name=\"controller\">The controller.</param>\n        public HttpControllerContext(HttpRequestContext requestContext, HttpRequestMessage request,\n            HttpControllerDescriptor controllerDescriptor, IHttpController controller)\n        {\n            if (requestContext == null)\n            {\n                throw Error.ArgumentNull(\"requestContext\");\n            }\n\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            if (controllerDescriptor == null)\n            {\n                throw Error.ArgumentNull(\"controllerDescriptor\");\n            }\n\n            if (controller == null)\n            {\n                throw Error.ArgumentNull(\"controller\");\n            }\n\n            _requestContext = requestContext;\n            _request = request;\n            _controllerDescriptor = controllerDescriptor;\n            _controller = controller;\n        }\n\n        public HttpControllerContext(HttpConfiguration configuration, IHttpRouteData routeData,\n            HttpRequestMessage request)\n        {\n            if (configuration == null)\n            {\n                throw Error.ArgumentNull(\"configuration\");\n            }\n\n            if (routeData == null)\n            {\n                throw Error.ArgumentNull(\"routeData\");\n            }\n\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            _requestContext = new HttpRequestContext\n            {\n                Configuration = configuration,\n                RouteData = routeData\n            };\n            _request = request;\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpControllerContext\"/> class.\n        /// </summary>\n        /// <remarks>The default constructor is intended for use by unit testing only.</remarks>\n        public HttpControllerContext()\n        {\n            // Note: This constructor is also used by a FormDataCollectionExtensions where we attempt to create a \n            // controller context with incomplete request context.\n            _requestContext = new HttpRequestContext();\n        }\n\n        public HttpConfiguration Configuration\n        {\n            get\n            {\n                return _requestContext.Configuration;\n            }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n\n                _requestContext.Configuration = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets the controller descriptor.\n        /// </summary>\n        /// <value>\n        /// The controller descriptor.\n        /// </value>\n        public HttpControllerDescriptor ControllerDescriptor\n        {\n            get { return _controllerDescriptor; }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n\n                _controllerDescriptor = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets the HTTP controller.\n        /// </summary>\n        /// <value>\n        /// The HTTP controller.\n        /// </value>\n        public IHttpController Controller\n        {\n            get { return _controller; }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n\n                _controller = value;\n            }\n        }\n\n        public HttpRequestMessage Request\n        {\n            get { return _request; }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n\n                _request = value;\n            }\n        }\n\n        /// <summary>Gets or sets the request context.</summary>\n        public HttpRequestContext RequestContext\n        {\n            get { return _requestContext; }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n\n                _requestContext = value;\n            }\n        }\n\n        public IHttpRouteData RouteData\n        {\n            get { return _requestContext.RouteData; }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n\n                _requestContext.RouteData = value;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/HttpControllerDescriptor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Collections.ObjectModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Internal;\n\nnamespace System.Web.Http.Controllers\n{\n    /// <summary>\n    /// Description and configuration for a controller.\n    /// </summary>\n    public class HttpControllerDescriptor\n    {\n        private readonly ConcurrentDictionary<object, object> _properties = new ConcurrentDictionary<object, object>();\n\n        private HttpConfiguration _configuration;\n\n        private string _controllerName;\n        private Type _controllerType;\n\n        private object[] _attributeCache;\n        private object[] _declaredOnlyAttributeCache;\n\n        public HttpControllerDescriptor(HttpConfiguration configuration, string controllerName, Type controllerType)\n        {\n            if (configuration == null)\n            {\n                throw Error.ArgumentNull(\"configuration\");\n            }\n\n            if (controllerName == null)\n            {\n                throw Error.ArgumentNull(\"controllerName\");\n            }\n\n            if (controllerType == null)\n            {\n                throw Error.ArgumentNull(\"controllerType\");\n            }\n\n            _configuration = configuration;\n            _controllerName = controllerName;\n            _controllerType = controllerType;\n\n            Initialize();\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpControllerDescriptor\"/> class.\n        /// </summary>\n        /// <remarks>The default constructor is intended for use by unit testing only.</remarks>\n        public HttpControllerDescriptor()\n        {\n        }\n\n        // For unit testing purposes. \n        internal HttpControllerDescriptor(HttpConfiguration configuration)\n        {\n            Initialize(configuration);\n        }\n\n        /// <summary>\n        /// Gets the properties associated with this instance.\n        /// </summary>\n        public virtual ConcurrentDictionary<object, object> Properties\n        {\n            get { return _properties; }\n        }\n\n        /// <summary>\n        /// Gets the configuration associated with the <see cref=\"HttpControllerDescriptor\"/>. \n        /// </summary>\n        public HttpConfiguration Configuration\n        {\n            get { return _configuration; }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n                _configuration = value;\n            }\n        }\n\n        public string ControllerName\n        {\n            get { return _controllerName; }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n                _controllerName = value;\n            }\n        }\n\n        public Type ControllerType\n        {\n            get { return _controllerType; }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n                _controllerType = value;\n            }\n        }\n\n        /// <summary>\n        /// Creates a controller instance for the given <see cref=\"HttpRequestMessage\"/>\n        /// </summary>\n        /// <param name=\"request\">The request message</param>\n        /// <returns></returns>\n        public virtual IHttpController CreateController(HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            // Invoke the controller activator\n            IHttpControllerActivator activator = Configuration.Services.GetHttpControllerActivator();\n            IHttpController instance = activator.Create(request, this, ControllerType);\n            return instance;\n        }\n\n        /// <summary>\n        /// Returns the collection of <see cref=\"IFilter\">filters</see> associated with this descriptor's controller.\n        /// </summary>\n        /// <remarks>The default implementation calls <see cref=\"GetCustomAttributes{IFilter}()\"/>.</remarks>\n        /// <returns>A collection of filters associated with this controller.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Justification = \"Filters can be built dynamically\")]\n        public virtual Collection<IFilter> GetFilters()\n        {\n            return GetCustomAttributes<IFilter>();\n        }\n\n        /// <summary>\n        /// Returns a collection of attributes that can be assigned to <typeparamref name=\"T\"/> for this descriptor's controller.\n        /// </summary>\n        /// <remarks>The default implementation retrieves the matching set of attributes declared on <see cref=\"ControllerType\"/>.</remarks>\n        /// <typeparam name=\"T\">Used to filter the collection of attributes. Use a value of <see cref=\"Object\"/> to retrieve all attributes.</typeparam>\n        /// <returns>A collection of attributes associated with this controller.</returns>\n        public virtual Collection<T> GetCustomAttributes<T>() where T : class\n        {\n            return GetCustomAttributes<T>(inherit: true);\n        }\n\n        /// <summary>\n        /// Returns a collection of attributes that can be assigned to <typeparamref name=\"T\"/> for this descriptor's controller.\n        /// </summary>\n        /// <remarks>The default implementation retrieves the matching set of attributes declared on <see cref=\"ControllerType\"/>.</remarks>\n        /// <typeparam name=\"T\">Used to filter the collection of attributes. Use a value of <see cref=\"Object\"/> to retrieve all attributes.</typeparam>\n        /// <param name=\"inherit\"><c>true</c> to search this controller's inheritance chain to find the attributes; otherwise, <c>false</c>.</param>\n        /// <returns>A collection of attributes associated with this controller.</returns>\n        public virtual Collection<T> GetCustomAttributes<T>(bool inherit) where T : class\n        {\n            object[] attributes;\n            // Getting custom attributes via reflection is slow. \n            // But iterating over a object[] to pick out specific types is fast. \n            // Furthermore, many different services may call to ask for different attributes, so we have multiple callers. \n            // That means there's not a single cache for the callers, which means there's some value caching here.\n            if (inherit)\n            {\n                if (_attributeCache == null)\n                {\n                    // Even in a race, we'll just ask for the custom attributes twice.\n                    _attributeCache = ControllerType.GetCustomAttributes(inherit: true);\n                }\n                attributes = _attributeCache;\n            }\n            else\n            {\n                if (_declaredOnlyAttributeCache == null)\n                {\n                    // Even in a race, we'll just ask for the custom attributes twice.\n                    _declaredOnlyAttributeCache = ControllerType.GetCustomAttributes(inherit: false);\n                }\n                attributes = _declaredOnlyAttributeCache;\n            }\n\n            return new Collection<T>(TypeHelper.OfType<T>(attributes));\n        }\n\n        // For unit tests for initializing mock objects. Controller may not have a type, so we can't do the normal Initialize() path. \n        internal void Initialize(HttpConfiguration configuration)\n        {\n            _configuration = configuration;\n        }\n\n        // Initialize the Controller Descriptor. This invokes all IControllerConfiguration attributes\n        // on the controller type (and its base types)\n        private void Initialize()\n        {\n            InvokeAttributesOnControllerType(this, ControllerType);\n        }\n\n        // Helper to invoke any Controller config attributes on this controller type or its base classes.\n        private static void InvokeAttributesOnControllerType(HttpControllerDescriptor controllerDescriptor, Type type)\n        {\n            Contract.Assert(controllerDescriptor != null);\n\n            if (type == null)\n            {\n                return;\n            }\n            // Initialize base class before derived classes (same order as ctors).\n            InvokeAttributesOnControllerType(controllerDescriptor, type.BaseType);\n\n            // Check for attribute\n            object[] attrs = type.GetCustomAttributes(inherit: false);\n            foreach (object attr in attrs)\n            {\n                var controllerConfig = attr as IControllerConfiguration;\n                if (controllerConfig != null)\n                {\n                    var originalConfig = controllerDescriptor.Configuration;\n                    var controllerSettings = new HttpControllerSettings(originalConfig);\n                    controllerConfig.Initialize(controllerSettings, controllerDescriptor);\n                    controllerDescriptor.Configuration = HttpConfiguration.ApplyControllerSettings(controllerSettings, originalConfig);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/HttpControllerDescriptorExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Controllers\n{\n    internal static class HttpControllerDescriptorExtensions\n    {\n        private const string AttributeRoutedPropertyKey = \"MS_IsAttributeRouted\";\n\n        public static bool IsAttributeRouted(this HttpControllerDescriptor controllerDescriptor)\n        {\n            if (controllerDescriptor == null)\n            {\n                throw new ArgumentNullException(\"controllerDescriptor\");\n            }\n\n            object value;\n            controllerDescriptor.Properties.TryGetValue(AttributeRoutedPropertyKey, out value);\n            return value as bool? ?? false;\n        }\n\n        public static void SetIsAttributeRouted(this HttpControllerDescriptor controllerDescriptor, bool value)\n        {\n            if (controllerDescriptor == null)\n            {\n                throw new ArgumentNullException(\"controllerDescriptor\");\n            }\n\n            controllerDescriptor.Properties[AttributeRoutedPropertyKey] = value;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/HttpControllerSettings.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Net.Http.Formatting;\nusing System.Web.Http.ModelBinding;\n\nnamespace System.Web.Http.Controllers\n{\n    [SuppressMessage(\"Microsoft.Design\", \"CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable\", Justification = \"ServicesContainer is disposed with the configuration\")]\n    public sealed class HttpControllerSettings\n    {\n        private MediaTypeFormatterCollection _formatters;\n        private ParameterBindingRulesCollection _parameterBindingRules;\n        private ServicesContainer _services;\n        private HttpConfiguration _configuration;\n\n        public HttpControllerSettings(HttpConfiguration configuration)\n        {\n            if (configuration == null)\n            {\n                throw Error.ArgumentNull(\"configuration\");\n            }\n\n            _configuration = configuration;\n        }\n\n        public MediaTypeFormatterCollection Formatters\n        {\n            get\n            {\n                if (_formatters == null)\n                {\n                    _formatters = new MediaTypeFormatterCollection(_configuration.Formatters);\n                }\n\n                return _formatters;\n            }\n        }\n\n        public ParameterBindingRulesCollection ParameterBindingRules\n        {\n            get\n            {\n                if (_parameterBindingRules == null)\n                {\n                    _parameterBindingRules = new ParameterBindingRulesCollection();\n                    foreach (var parameterBindingRule in _configuration.ParameterBindingRules)\n                    {\n                        _parameterBindingRules.Add(parameterBindingRule);\n                    }\n                }\n\n                return _parameterBindingRules;\n            }\n        }\n\n        public ServicesContainer Services\n        {\n            get\n            {\n                if (_services == null)\n                {\n                    _services = new ControllerServices(_configuration.Services);\n                }\n\n                return _services;\n            }\n        }\n\n        internal bool IsFormatterCollectionInitialized\n        {\n            get { return _formatters != null; }\n        }\n\n        internal bool IsParameterBindingRuleCollectionInitialized\n        {\n            get { return _parameterBindingRules != null; }\n        }\n\n        internal bool IsServiceCollectionInitialized\n        {\n            get { return _services != null; }\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http/Controllers/HttpParameterBinding.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Metadata;\n\nnamespace System.Web.Http.Controllers\n{\n    /// <summary>\n    /// Describes how a parameter is bound. The binding should be static (based purely on the descriptor) and \n    /// can be shared across requests. \n    /// </summary>\n    public abstract class HttpParameterBinding\n    {\n        private readonly HttpParameterDescriptor _descriptor;\n\n        protected HttpParameterBinding(HttpParameterDescriptor descriptor)\n        {\n            if (descriptor == null)\n            {\n                throw Error.ArgumentNull(\"descriptor\");\n            }\n            _descriptor = descriptor;\n        }\n\n        /// <summary>\n        /// True iff this binding owns the body. This is important since the body can be a stream that is only read once.\n        /// This lets us know who is trying to read the body, and enforce that there is only one reader. \n        /// </summary>\n        public virtual bool WillReadBody\n        {\n            get { return false; }\n        }\n\n        /// <summary>\n        /// True if the binding was successful and ExecuteBinding can be called. \n        /// False if there was an error determining this binding. This means a developer error somewhere, such as \n        /// configuration, parameter types, proper attributes, etc. \n        /// </summary>\n        public bool IsValid\n        {\n            get { return ErrorMessage == null; }\n        }\n\n        /// <summary>\n        /// Get an error message describing why this binding is invalid. \n        /// </summary>\n        public virtual string ErrorMessage\n        {\n            get { return null; }\n        }\n\n        public HttpParameterDescriptor Descriptor\n        {\n            get { return _descriptor; }\n        }\n\n        /// <summary>\n        /// Execute the binding for the given request.\n        /// On success, this will add the parameter to the actionContext.ActionArguments dictionary.\n        /// Caller ensures <see cref=\"IsValid\"/> is true.\n        /// </summary>\n        /// <param name=\"metadataProvider\">metadata provider to use for validation.</param>\n        /// <param name=\"actionContext\">action context for the binding. This contains the parameter dictionary that will get populated.</param>\n        /// <param name=\"cancellationToken\">Cancellation token for cancelling the binding operation. Or a binder can also bind a parameter to this.</param>\n        /// <returns>Task that is signaled when the binding is complete. For simple bindings from a URI, this should be signalled immediately.\n        /// For bindings that read the content body, this may do network IO.</returns>\n        public abstract Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken);\n\n        /// <summary>\n        /// Helper to get the parameter value from the action context's argument dictionary\n        /// </summary>\n        /// <param name=\"actionContext\">action context </param>\n        /// <returns>the value for this parameter in the given action context, or null if the parameter has not yet been set.</returns>\n        protected object GetValue(HttpActionContext actionContext)\n        {\n            if (actionContext == null)\n            {\n                throw Error.ArgumentNull(\"actionContext\");\n            }\n\n            object value;\n            actionContext.ActionArguments.TryGetValue(Descriptor.ParameterName, out value);\n            return value;\n        }\n\n        /// <summary>\n        /// Helper to set the result of this parameter binding in the action context's argument dictionary. \n        /// </summary>\n        /// <param name=\"actionContext\">action context.</param>\n        /// <param name=\"value\">parameter value.</param>\n        protected void SetValue(HttpActionContext actionContext, object value)\n        {\n            if (actionContext == null)\n            {\n                throw Error.ArgumentNull(\"actionContext\");\n            }\n            actionContext.ActionArguments[Descriptor.ParameterName] = value;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/HttpParameterDescriptor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Web.Http.Internal;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.Controllers\n{\n    public abstract class HttpParameterDescriptor\n    {\n        private readonly ConcurrentDictionary<object, object> _properties = new ConcurrentDictionary<object, object>();\n\n        private ParameterBindingAttribute _parameterBindingAttribute;\n        private bool _searchedModelBinderAttribute;\n        private HttpConfiguration _configuration;\n        private HttpActionDescriptor _actionDescriptor;\n\n        protected HttpParameterDescriptor()\n        {\n        }\n\n        protected HttpParameterDescriptor(HttpActionDescriptor actionDescriptor)\n        {\n            if (actionDescriptor == null)\n            {\n                throw Error.ArgumentNull(\"actionDescriptor\");\n            }\n\n            _actionDescriptor = actionDescriptor;\n            _configuration = _actionDescriptor.Configuration;\n        }\n\n        public HttpConfiguration Configuration\n        {\n            get { return _configuration; }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n                _configuration = value;\n            }\n        }\n\n        public HttpActionDescriptor ActionDescriptor\n        {\n            get { return _actionDescriptor; }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n                _actionDescriptor = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets the properties associated with this instance.\n        /// </summary>\n        public ConcurrentDictionary<object, object> Properties\n        {\n            get { return _properties; }\n        }\n\n        public virtual object DefaultValue\n        {\n            get { return null; }\n        }\n\n        public abstract string ParameterName { get; }\n\n        public abstract Type ParameterType { get; }\n\n        public virtual string Prefix\n        {\n            get\n            {\n                ParameterBindingAttribute attribute = ParameterBinderAttribute;\n                ModelBinderAttribute modelAttribute = attribute as ModelBinderAttribute;\n                return modelAttribute != null\n                           ? modelAttribute.Name\n                           : null;\n            }\n        }\n\n        /// <summary>\n        /// Gets a value indicating whether the parameter is optional.\n        /// </summary>\n        /// <value>\n        /// <c>true</c> if the parameter is optional; otherwise, <c>false</c>.\n        /// </value>\n        public virtual bool IsOptional\n        {\n            get { return false; }\n        }\n\n        /// <summary>\n        /// Return a <see cref=\"ParameterBindingAttribute\"/> if present on this parameter's signature or declared type.\n        /// Returns null if no attribute is specified.\n        /// </summary>\n        public virtual ParameterBindingAttribute ParameterBinderAttribute\n        {\n            get\n            {\n                if (_parameterBindingAttribute == null)\n                {\n                    if (!_searchedModelBinderAttribute)\n                    {\n                        _searchedModelBinderAttribute = true;\n                        _parameterBindingAttribute = FindParameterBindingAttribute();\n                    }\n                }\n\n                return _parameterBindingAttribute;\n            }\n\n            set { _parameterBindingAttribute = value; }\n        }\n\n        public virtual Collection<T> GetCustomAttributes<T>() where T : class\n        {\n            return new Collection<T>();\n        }\n\n        private ParameterBindingAttribute FindParameterBindingAttribute()\n        {\n            // Can be on parameter itself or on the parameter's type.  Nearest wins.\n            return ChooseAttribute(GetCustomAttributes<ParameterBindingAttribute>())\n                ?? ChooseAttribute(ParameterType.GetCustomAttributes<ParameterBindingAttribute>(false));\n        }\n\n        private static ParameterBindingAttribute ChooseAttribute(IList<ParameterBindingAttribute> list)\n        {\n            if (list.Count == 0)\n            {\n                return null;\n            }\n            if (list.Count > 1)\n            {\n                // Multiple attributes specified at the same level\n                return new AmbiguousParameterBindingAttribute();\n            }\n            return list[0];\n        }\n\n        // Helper class to return an error binding if an parameter has an invalid attribute combination. \n        private sealed class AmbiguousParameterBindingAttribute : ParameterBindingAttribute\n        {\n            public override HttpParameterBinding GetBinding(HttpParameterDescriptor parameter)\n            {\n                string message = Error.Format(SRResources.ParameterBindingConflictingAttributes, parameter.ParameterName);\n                return parameter.BindAsError(message);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/HttpParameterDescriptorExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http.Formatting;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.Validation;\nusing System.Web.Http.ValueProviders;\n\nnamespace System.Web.Http.Controllers\n{\n    /// <summary>\n    /// Convenience helpers to easily create specific types of parameter bindings\n    /// These provide a direct programmatic counterpart to the <see cref=\"ParameterBindingAttribute\"/> attributes. \n    /// </summary>\n    public static class ParameterBindingExtensions\n    {\n        /// <summary>\n        /// If we know statically that this binding can never succeed, then use an error binding.\n        /// This will prevent the action from executing.\n        /// </summary>\n        /// <param name=\"parameter\">parameter to provide binding for.</param>\n        /// <param name=\"message\">error message for user.</param>\n        /// <returns>an error binding. Specifically, IsValid on the binding will be false.</returns>\n        public static HttpParameterBinding BindAsError(this HttpParameterDescriptor parameter, string message)\n        {\n            return new ErrorParameterBinding(parameter, message);\n        }\n\n        /// <summary>\n        /// Bind the parameter as if it had the given attribute on the declaration.\n        /// </summary>\n        /// <param name=\"parameter\">parameter to provide binding for.</param>\n        /// <param name=\"attribute\">attribute to describe the binding.</param>\n        /// <returns>a binding</returns>\n        public static HttpParameterBinding BindWithAttribute(this HttpParameterDescriptor parameter, ParameterBindingAttribute attribute)\n        {\n            return attribute.GetBinding(parameter);\n        }\n\n        /// <summary>\n        /// Bind the parameter using model binding. Get all other information from the configuration.\n        /// This is the same as having a plain ModelBinderAttribute on the parameter.\n        /// </summary>\n        /// <param name=\"parameter\">parameter to provide binding for.</param>\n        /// <returns>a binding</returns>\n        public static HttpParameterBinding BindWithModelBinding(this HttpParameterDescriptor parameter)\n        {\n            return BindWithAttribute(parameter, new ModelBinderAttribute());\n        }\n\n        /// <summary>\n        /// Bind the parameter using the given model binder. \n        /// </summary>\n        /// <param name=\"parameter\">parameter to provide binding for.</param>\n        /// <param name=\"binder\">model binder to use on parameter</param>\n        /// <returns>a binding</returns>\n        public static HttpParameterBinding BindWithModelBinding(this HttpParameterDescriptor parameter, IModelBinder binder)\n        {\n            HttpConfiguration config = parameter.Configuration;\n            IEnumerable<ValueProviderFactory> valueProviderFactories = new ModelBinderAttribute().GetValueProviderFactories(config);\n\n            return BindWithModelBinding(parameter, binder, valueProviderFactories);\n        }\n\n        /// <summary>\n        /// Bind the parameter using default model binding but with the supplied value providers.\n        /// </summary>\n        /// <param name=\"parameter\">parameter to provide binding for.</param>\n        /// <param name=\"valueProviderFactories\">value provider factories to feed to model binders</param>\n        /// <returns>a binding</returns>\n        public static HttpParameterBinding BindWithModelBinding(this HttpParameterDescriptor parameter, params ValueProviderFactory[] valueProviderFactories)\n        {\n            return BindWithModelBinding(parameter, (IEnumerable<ValueProviderFactory>)valueProviderFactories);\n        }\n\n        /// <summary>\n        /// Bind the parameter using default model binding but with the supplied value providers.\n        /// </summary>\n        /// <param name=\"parameter\">parameter to provide binding for.</param>\n        /// <param name=\"valueProviderFactories\">value provider factories to feed to model binders</param>\n        /// <returns>a binding</returns>\n        public static HttpParameterBinding BindWithModelBinding(this HttpParameterDescriptor parameter, IEnumerable<ValueProviderFactory> valueProviderFactories)\n        {\n            HttpConfiguration config = parameter.Configuration;\n            IModelBinder binder = new ModelBinderAttribute().GetModelBinder(config, parameter.ParameterType);\n\n            return new ModelBinderParameterBinding(parameter, binder, valueProviderFactories);\n        }\n\n        /// <summary>\n        /// Bind the parameter using the supplied binder and value providers.\n        /// </summary>\n        /// <param name=\"parameter\">parameter to provide binding for.</param>\n        /// <param name=\"binder\">model binder to use for binding.</param>\n        /// <param name=\"valueProviderFactories\">value provider factories to feed to model binder.</param>\n        /// <returns>a binding</returns>\n        public static HttpParameterBinding BindWithModelBinding(this HttpParameterDescriptor parameter, IModelBinder binder, IEnumerable<ValueProviderFactory> valueProviderFactories)\n        {\n            return new ModelBinderParameterBinding(parameter, binder, valueProviderFactories);\n        }\n\n        /// <summary>\n        /// Bind the parameter from the body using the formatters from the configuration. \n        /// This is like having a [FromBody] attribute on the parameter\n        /// </summary>\n        /// <param name=\"parameter\">parameter to provide binding for.</param>\n        /// <returns>a binding</returns>\n        public static HttpParameterBinding BindWithFormatter(this HttpParameterDescriptor parameter)\n        {\n            HttpConfiguration config = parameter.Configuration;\n            IEnumerable<MediaTypeFormatter> formatters = config.Formatters;\n            IBodyModelValidator validators = config.Services.GetBodyModelValidator();\n\n            return new FormatterParameterBinding(parameter, formatters, validators);\n        }\n\n        /// <summary>\n        /// Bind this parameter from the body using the supplied set of formatters.\n        /// </summary>\n        /// <param name=\"parameter\">parameter to provide binding for.</param>\n        /// <param name=\"formatters\">formatters to choose from when binding the body</param>\n        /// <returns>a binding</returns>\n        public static HttpParameterBinding BindWithFormatter(this HttpParameterDescriptor parameter, params MediaTypeFormatter[] formatters)\n        {\n            return BindWithFormatter(parameter, (IEnumerable<MediaTypeFormatter>)formatters);\n        }\n\n        /// <summary>\n        /// Bind this parameter from the body using the supplied set of formatters.\n        /// </summary>\n        /// <param name=\"parameter\">parameter to provide binding for.</param>\n        /// <param name=\"formatters\">formatters to choose from when binding the body</param>\n        /// <returns>a binding</returns>\n        public static HttpParameterBinding BindWithFormatter(this HttpParameterDescriptor parameter, IEnumerable<MediaTypeFormatter> formatters)\n        {\n            HttpConfiguration config = parameter.Configuration;\n            IBodyModelValidator validators = config.Services.GetBodyModelValidator();\n            return new FormatterParameterBinding(parameter, formatters, validators);\n        }\n\n        /// <summary>\n        /// Bind this parameter from the body using the supplied set of formatters and validator. \n        /// </summary>\n        /// <param name=\"parameter\">parameter to provide binding for.</param>\n        /// <param name=\"formatters\">formatters to choose from when binding the body</param>\n        /// <param name=\"bodyModelValidator\">a validator. Null to disable validation for this parameter.</param>\n        /// <returns>a binding</returns>\n        public static HttpParameterBinding BindWithFormatter(this HttpParameterDescriptor parameter, IEnumerable<MediaTypeFormatter> formatters, IBodyModelValidator bodyModelValidator)\n        {\n            return new FormatterParameterBinding(parameter, formatters, bodyModelValidator);\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http/Controllers/HttpRequestContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Security.Cryptography.X509Certificates;\nusing System.Security.Principal;\nusing System.Web.Http.Routing;\n\nnamespace System.Web.Http.Controllers\n{\n    /// <summary>Represents the context associated with a request.</summary>\n    public class HttpRequestContext\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpRequestContext\"/> class.\n        /// </summary>\n        public HttpRequestContext()\n        {\n            // This is constructor is available to allow placing breakpoints on construction.\n        }\n\n        /// <summary>Gets or sets the client certificate.</summary>\n        public virtual X509Certificate2 ClientCertificate { get; set; }\n\n        /// <summary>Gets or sets the configuration.</summary>\n        public virtual HttpConfiguration Configuration { get; set; }\n\n        /// <summary>\n        /// Gets or sets a value indicating whether error details, such as exception messages and stack traces,\n        /// should be included in the response for this request.\n        /// </summary>\n        public virtual bool IncludeErrorDetail { get; set; }\n\n        /// <summary>Gets or sets a value indicating whether the request originates from a local address.</summary>\n        public virtual bool IsLocal { get; set; }\n\n        /// <summary>Gets or sets the principal.</summary>\n        public virtual IPrincipal Principal { get; set; }\n\n        /// <summary>Gets or sets the route data.</summary>\n        public virtual IHttpRouteData RouteData { get; set; }\n\n        /// <summary>Gets or sets the factory used to generate URLs to other APIs.</summary>\n        public virtual UrlHelper Url { get; set; }\n\n        /// <summary>Gets or sets the virtual path root.</summary>\n        public virtual string VirtualPathRoot { get; set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/IActionHttpMethodProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Net.Http;\n\nnamespace System.Web.Http.Controllers\n{\n    public interface IActionHttpMethodProvider\n    {\n        Collection<HttpMethod> HttpMethods { get; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/IActionResultConverter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Threading;\n\nnamespace System.Web.Http.Controllers\n{\n    /// <summary>\n    /// A contract for a conversion routine that can take the result of an action returned from\n    /// <see cref=\"HttpActionDescriptor.ExecuteAsync(HttpControllerContext, IDictionary{string, object}, CancellationToken)\"/>\n    /// and synchronously convert it to an instance of <see cref=\"HttpResponseMessage\"/>.\n    /// </summary>\n    /// <remarks>\n    /// This interface is not used when the runtime return value of an action is an <see cref=\"IHttpActionResult\"/>.\n    /// </remarks>\n    public interface IActionResultConverter\n    {\n        HttpResponseMessage Convert(HttpControllerContext controllerContext, object actionResult);\n    }\n}"
  },
  {
    "path": "src/System.Web.Http/Controllers/IActionValueBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Controllers\n{\n    public interface IActionValueBinder\n    {\n        HttpActionBinding GetBinding(HttpActionDescriptor actionDescriptor);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/IControllerConfiguration.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Controllers\n{\n    /// <summary>\n    /// If a controller is decorated with an attribute with this interface, then it gets invoked\n    /// to initialize the controller settings. \n    /// </summary>\n    public interface IControllerConfiguration\n    {\n        /// <summary>\n        /// Callback invoked to set per-controller overrides for this controllerDescriptor.\n        /// </summary>\n        /// <param name=\"controllerSettings\">The controller settings to initialize.</param>\n        /// <param name=\"controllerDescriptor\">The controller descriptor. Note that the <see cref=\"HttpControllerDescriptor\"/> can be associated with the derived controller type given that <see cref=\"IControllerConfiguration\"/> is inherited.</param>\n        void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/IHttpActionInvoker.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.Controllers\n{\n    public interface IHttpActionInvoker\n    {\n        Task<HttpResponseMessage> InvokeActionAsync(HttpActionContext actionContext, CancellationToken cancellationToken);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/IHttpActionSelector.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nnamespace System.Web.Http.Controllers\n{\n    public interface IHttpActionSelector\n    {\n        /// <summary>\n        /// Selects the action.\n        /// </summary>\n        /// <param name=\"controllerContext\">The controller context.</param>\n        /// <returns>The selected action.</returns>\n        HttpActionDescriptor SelectAction(HttpControllerContext controllerContext);\n\n        /// <summary>\n        /// Returns a map, keyed by action string, of all <see cref=\"HttpActionDescriptor\"/> that the selector can select. \n        /// This is primarily called by <see cref=\"System.Web.Http.Description.IApiExplorer\"/> to discover all the possible actions in the controller.\n        /// </summary>\n        /// <param name=\"controllerDescriptor\">The controller descriptor.</param>\n        /// <returns>A map of <see cref=\"HttpActionDescriptor\"/> that the selector can select, or null if the selector does not have a well-defined mapping of <see cref=\"HttpActionDescriptor\"/>.</returns>\n        ILookup<string, HttpActionDescriptor> GetActionMapping(HttpControllerDescriptor controllerDescriptor);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/IHttpController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.Controllers\n{\n    public interface IHttpController\n    {\n        Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/ReflectedHttpActionDescriptor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing System.Linq.Expressions;\nusing System.Net;\nusing System.Net.Http;\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Internal;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.Controllers\n{\n    /// <summary>\n    /// An action descriptor representing a reflected synchronous or asynchronous action method.\n    /// </summary>\n    public class ReflectedHttpActionDescriptor : HttpActionDescriptor\n    {\n        private static readonly object[] _empty = new object[0];\n\n        private readonly Lazy<Collection<HttpParameterDescriptor>> _parameters;\n        private ParameterInfo[] _parameterInfos;\n\n        private Lazy<ActionExecutor> _actionExecutor;\n        private MethodInfo _methodInfo;\n        private Type _returnType;\n        private string _actionName;\n        private Collection<HttpMethod> _supportedHttpMethods;\n\n        // Getting custom attributes via reflection is slow. \n        // But iterating over a object[] to pick out specific types is fast. \n        // Furthermore, many different services may call to ask for different attributes, so we have multiple callers. \n        // That means there's not a single cache for the callers, which means there's some value caching here.\n        // This cache can be a 2x speedup in some benchmarks.\n        private object[] _attributeCache;\n        private object[] _declaredOnlyAttributeCache;\n\n        private static readonly HttpMethod[] _supportedHttpMethodsByConvention = \n        { \n            HttpMethod.Get, \n            HttpMethod.Post, \n            HttpMethod.Put, \n            HttpMethod.Delete, \n            HttpMethod.Head, \n            HttpMethod.Options, \n            new HttpMethod(\"PATCH\") \n        };\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"ReflectedHttpActionDescriptor\"/> class.\n        /// </summary>\n        /// <remarks>The default constructor is intended for use by unit testing only.</remarks>\n        public ReflectedHttpActionDescriptor()\n        {\n            _parameters = new Lazy<Collection<HttpParameterDescriptor>>(() => InitializeParameterDescriptors());\n            _supportedHttpMethods = new Collection<HttpMethod>();\n        }\n\n        public ReflectedHttpActionDescriptor(HttpControllerDescriptor controllerDescriptor, MethodInfo methodInfo)\n            : base(controllerDescriptor)\n        {\n            if (methodInfo == null)\n            {\n                throw Error.ArgumentNull(\"methodInfo\");\n            }\n\n            InitializeProperties(methodInfo);\n            _parameters = new Lazy<Collection<HttpParameterDescriptor>>(() => InitializeParameterDescriptors());\n        }\n\n        public override string ActionName\n        {\n            get { return _actionName; }\n        }\n\n        public override Collection<HttpMethod> SupportedHttpMethods\n        {\n            get { return _supportedHttpMethods; }\n        }\n\n        public MethodInfo MethodInfo\n        {\n            get { return _methodInfo; }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n\n                InitializeProperties(value);\n            }\n        }\n\n        private ParameterInfo[] ParameterInfos\n        {\n            get\n            {\n                if (_parameterInfos == null)\n                {\n                    _parameterInfos = _methodInfo.GetParameters();\n                }\n                return _parameterInfos;\n            }\n        }\n\n        /// <inheritdoc/>\n        public override Type ReturnType\n        {\n            get { return _returnType; }\n        }\n\n        /// <inheritdoc/>\n        public override Collection<T> GetCustomAttributes<T>(bool inherit)\n        {\n            object[] attributes = inherit ? _attributeCache : _declaredOnlyAttributeCache;\n            return new Collection<T>(TypeHelper.OfType<T>(attributes));\n        }\n\n        /// <inheritdoc/>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"The caught exception type is reflected into a faulted task.\")]\n        public override Task<object> ExecuteAsync(HttpControllerContext controllerContext, IDictionary<string, object> arguments, CancellationToken cancellationToken)\n        {\n            if (controllerContext == null)\n            {\n                throw Error.ArgumentNull(\"controllerContext\");\n            }\n\n            if (arguments == null)\n            {\n                throw Error.ArgumentNull(\"arguments\");\n            }\n\n            if (cancellationToken.IsCancellationRequested)\n            {\n                return TaskHelpers.Canceled<object>();\n            }\n\n            try\n            {\n                object[] argumentValues = PrepareParameters(arguments, controllerContext);\n                return _actionExecutor.Value.Execute(controllerContext.Controller, argumentValues);\n            }\n            catch (Exception e)\n            {\n                return TaskHelpers.FromError<object>(e);\n            }\n        }\n\n        public override Collection<IFilter> GetFilters()\n        {\n            return new Collection<IFilter>(GetCustomAttributes<IFilter>().Concat(base.GetFilters()).ToList());\n        }\n\n        public override Collection<HttpParameterDescriptor> GetParameters()\n        {\n            return _parameters.Value;\n        }\n\n        private void InitializeProperties(MethodInfo methodInfo)\n        {\n            _methodInfo = methodInfo;\n            _parameterInfos = null;\n            _returnType = GetReturnType(methodInfo);\n            _actionExecutor = new Lazy<ActionExecutor>(() => InitializeActionExecutor(_methodInfo));\n            _declaredOnlyAttributeCache = _methodInfo.GetCustomAttributes(inherit: false);\n            _attributeCache = _methodInfo.GetCustomAttributes(inherit: true);\n            _actionName = GetActionName(_methodInfo, _attributeCache);\n            _supportedHttpMethods = GetSupportedHttpMethods(_methodInfo, _attributeCache);\n        }\n\n        internal static Type GetReturnType(MethodInfo methodInfo)\n        {\n            Type result = methodInfo.ReturnType;\n            if (typeof(Task).IsAssignableFrom(result))\n            {\n                result = TypeHelper.GetTaskInnerTypeOrNull(methodInfo.ReturnType);\n            }\n            if (result == typeof(void))\n            {\n                result = null;\n            }\n            return result;\n        }\n\n        private Collection<HttpParameterDescriptor> InitializeParameterDescriptors()\n        {\n            Contract.Assert(_methodInfo != null);\n\n            List<HttpParameterDescriptor> parameterInfos = ParameterInfos.Select(\n                (item) => new ReflectedHttpParameterDescriptor(this, item)).ToList<HttpParameterDescriptor>();\n            return new Collection<HttpParameterDescriptor>(parameterInfos);\n        }\n\n        private object[] PrepareParameters(IDictionary<string, object> parameters, HttpControllerContext controllerContext)\n        {\n            // This is on a hotpath, so a quick check to avoid the allocation if we have no parameters. \n            if (_parameters.Value.Count == 0)\n            {\n                return _empty;\n            }\n\n            ParameterInfo[] parameterInfos = ParameterInfos;\n            int parameterCount = parameterInfos.Length;\n            object[] parameterValues = new object[parameterCount];\n            for (int parameterIndex = 0; parameterIndex < parameterCount; parameterIndex++)\n            {\n                parameterValues[parameterIndex] = ExtractParameterFromDictionary(parameterInfos[parameterIndex], parameters, controllerContext);\n            }\n            return parameterValues;\n        }\n\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"Caller is responsible for disposing of response instance.\")]\n        private object ExtractParameterFromDictionary(ParameterInfo parameterInfo, IDictionary<string, object> parameters, HttpControllerContext controllerContext)\n        {\n            object value;\n\n            if (!parameters.TryGetValue(parameterInfo.Name, out value))\n            {\n                // the key should always be present, even if the parameter value is null\n                throw new HttpResponseException(controllerContext.Request.CreateErrorResponse(\n                    HttpStatusCode.BadRequest,\n                    SRResources.BadRequest,\n                    Error.Format(SRResources.ReflectedActionDescriptor_ParameterNotInDictionary,\n                                 parameterInfo.Name, parameterInfo.ParameterType, MethodInfo, MethodInfo.DeclaringType)));\n            }\n\n            if (value == null && !TypeHelper.TypeAllowsNullValue(parameterInfo.ParameterType))\n            {\n                // tried to pass a null value for a non-nullable parameter type\n                throw new HttpResponseException(controllerContext.Request.CreateErrorResponse(\n                    HttpStatusCode.BadRequest,\n                    SRResources.BadRequest,\n                    Error.Format(SRResources.ReflectedActionDescriptor_ParameterCannotBeNull,\n                                    parameterInfo.Name, parameterInfo.ParameterType, MethodInfo, MethodInfo.DeclaringType)));\n            }\n\n            if (value != null && !parameterInfo.ParameterType.IsInstanceOfType(value))\n            {\n                // value was supplied but is not of the proper type\n                throw new HttpResponseException(controllerContext.Request.CreateErrorResponse(\n                    HttpStatusCode.BadRequest,\n                    SRResources.BadRequest,\n                    Error.Format(SRResources.ReflectedActionDescriptor_ParameterValueHasWrongType,\n                                    parameterInfo.Name, MethodInfo, MethodInfo.DeclaringType, value.GetType(), parameterInfo.ParameterType)));\n            }\n\n            return value;\n        }\n\n        private static string GetActionName(MethodInfo methodInfo, object[] actionAttributes)\n        {\n            ActionNameAttribute nameAttribute = TypeHelper.OfType<ActionNameAttribute>(actionAttributes).FirstOrDefault();\n            return nameAttribute != null\n                       ? nameAttribute.Name\n                       : methodInfo.Name;\n        }\n\n        private static Collection<HttpMethod> GetSupportedHttpMethods(MethodInfo methodInfo, object[] actionAttributes)\n        {\n            Collection<HttpMethod> supportedHttpMethods = new Collection<HttpMethod>();\n            ICollection<IActionHttpMethodProvider> httpMethodProviders = TypeHelper.OfType<IActionHttpMethodProvider>(actionAttributes);\n            if (httpMethodProviders.Count > 0)\n            {\n                // Get HttpMethod from attributes\n                foreach (IActionHttpMethodProvider httpMethodSelector in httpMethodProviders)\n                {\n                    foreach (HttpMethod httpMethod in httpMethodSelector.HttpMethods)\n                    {\n                        supportedHttpMethods.Add(httpMethod);\n                    }\n                }\n            }\n            else\n            {\n                // Get HttpMethod from method name convention \n                for (int i = 0; i < _supportedHttpMethodsByConvention.Length; i++)\n                {\n                    if (methodInfo.Name.StartsWith(_supportedHttpMethodsByConvention[i].Method, StringComparison.OrdinalIgnoreCase))\n                    {\n                        supportedHttpMethods.Add(_supportedHttpMethodsByConvention[i]);\n                        break;\n                    }\n                }\n            }\n\n            if (supportedHttpMethods.Count == 0)\n            {\n                // Use POST as the default HttpMethod\n                supportedHttpMethods.Add(HttpMethod.Post);\n            }\n\n            return supportedHttpMethods;\n        }\n\n        // Implementing Equals and GetHashCode is needed here because when tracing is enabled, a different set of action descriptors\n        // are available at configuration time for attribute routing and at runtime. This is because the default action selector\n        // clears its action descriptor cache when the controller descriptor is different. And since tracing wraps the controller\n        // descriptor for tracing, the cache gets cleared and new action descriptors get created for tracing. We need to compare\n        // the action descriptors by method info to be able to correlate attribute routing actions to the tracing action descriptors.\n\n        /// <inheritdoc />\n        public override int GetHashCode()\n        {\n            if (_methodInfo != null)\n            {\n                return _methodInfo.GetHashCode();\n            }\n\n            return base.GetHashCode();\n        }\n\n        /// <inheritdoc />\n        public override bool Equals(object obj)\n        {\n            if (_methodInfo != null)\n            {\n                ReflectedHttpActionDescriptor otherDescriptor = obj as ReflectedHttpActionDescriptor;\n                if (otherDescriptor == null)\n                {\n                    return false;\n                }\n\n                return _methodInfo.Equals(otherDescriptor._methodInfo);\n            }\n\n            return base.Equals(obj);\n        }\n\n        private static ActionExecutor InitializeActionExecutor(MethodInfo methodInfo)\n        {\n            if (methodInfo.ContainsGenericParameters)\n            {\n                throw Error.InvalidOperation(SRResources.ReflectedHttpActionDescriptor_CannotCallOpenGenericMethods,\n                                     methodInfo, methodInfo.ReflectedType.FullName);\n            }\n\n            return new ActionExecutor(methodInfo);\n        }\n\n        private sealed class ActionExecutor\n        {\n            private readonly Func<object, object[], Task<object>> _executor;\n            private static MethodInfo _convertOfTMethod = typeof(ActionExecutor).GetMethod(\"Convert\", BindingFlags.Static | BindingFlags.NonPublic);\n\n            public ActionExecutor(MethodInfo methodInfo)\n            {\n                Contract.Assert(methodInfo != null);\n                _executor = GetExecutor(methodInfo);\n            }\n\n            public Task<object> Execute(object instance, object[] arguments)\n            {\n                return _executor(instance, arguments);\n            }\n\n            // Method called via reflection.\n            private static Task<object> Convert<T>(object taskAsObject)\n            {\n                Task<T> task = (Task<T>)taskAsObject;\n                return task.CastToObject<T>();\n            }\n\n            // Do not inline or optimize this method to avoid stack-related reflection demand issues when\n            // running from the GAC in medium trust\n            [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]\n            private static Func<object, Task<object>> CompileGenericTaskConversionDelegate(Type taskValueType)\n            {\n                Contract.Assert(taskValueType != null);\n\n                return (Func<object, Task<object>>)Delegate.CreateDelegate(typeof(Func<object, Task<object>>), _convertOfTMethod.MakeGenericMethod(taskValueType));\n            }\n\n            private static Func<object, object[], Task<object>> GetExecutor(MethodInfo methodInfo)\n            {\n                // Parameters to executor\n                ParameterExpression instanceParameter = Expression.Parameter(typeof(object), \"instance\");\n                ParameterExpression parametersParameter = Expression.Parameter(typeof(object[]), \"parameters\");\n\n                // Build parameter list\n                List<Expression> parameters = new List<Expression>();\n                ParameterInfo[] paramInfos = methodInfo.GetParameters();\n                for (int i = 0; i < paramInfos.Length; i++)\n                {\n                    ParameterInfo paramInfo = paramInfos[i];\n                    BinaryExpression valueObj = Expression.ArrayIndex(parametersParameter, Expression.Constant(i));\n                    UnaryExpression valueCast = Expression.Convert(valueObj, paramInfo.ParameterType);\n\n                    // valueCast is \"(Ti) parameters[i]\"\n                    parameters.Add(valueCast);\n                }\n\n                // Call method\n                UnaryExpression instanceCast = (!methodInfo.IsStatic) ? Expression.Convert(instanceParameter, methodInfo.ReflectedType) : null;\n                MethodCallExpression methodCall = Expression.Call(instanceCast, methodInfo, parameters);\n\n                // methodCall is \"((MethodInstanceType) instance).method((T0) parameters[0], (T1) parameters[1], ...)\"\n                // Create function\n                if (methodCall.Type == typeof(void))\n                {\n                    // for: public void Action()\n                    Expression<Action<object, object[]>> lambda = Expression.Lambda<Action<object, object[]>>(methodCall, instanceParameter, parametersParameter);\n                    Action<object, object[]> voidExecutor = lambda.Compile();\n                    return (instance, methodParameters) =>\n                    {\n                        voidExecutor(instance, methodParameters);\n                        return TaskHelpers.NullResult();\n                    };\n                }\n                else\n                {\n                    // must coerce methodCall to match Func<object, object[], object> signature\n                    UnaryExpression castMethodCall = Expression.Convert(methodCall, typeof(object));\n                    Expression<Func<object, object[], object>> lambda = Expression.Lambda<Func<object, object[], object>>(castMethodCall, instanceParameter, parametersParameter);\n                    Func<object, object[], object> compiled = lambda.Compile();\n                    if (methodCall.Type == typeof(Task))\n                    {\n                        // for: public Task Action()\n                        return (instance, methodParameters) =>\n                        {\n                            Task r = (Task)compiled(instance, methodParameters);\n                            ThrowIfWrappedTaskInstance(methodInfo, r.GetType());\n                            return r.CastToObject();\n                        };\n                    }\n                    else if (typeof(Task).IsAssignableFrom(methodCall.Type))\n                    {\n                        // for: public Task<T> Action()\n                        // constructs: return (Task<object>)Convert<T>(((Task<T>)instance).method((T0) param[0], ...))\n                        Type taskValueType = TypeHelper.GetTaskInnerTypeOrNull(methodCall.Type);\n                        var compiledConversion = CompileGenericTaskConversionDelegate(taskValueType);\n\n                        return (instance, methodParameters) =>\n                        {\n                            object callResult = compiled(instance, methodParameters);\n                            Task<object> convertedResult = compiledConversion(callResult);\n                            return convertedResult;\n                        };\n                    }\n                    else\n                    {\n                        // for: public T Action()\n                        return (instance, methodParameters) =>\n                        {\n                            var result = compiled(instance, methodParameters);\n                            // Throw when the result of a method is Task. Asynchronous methods need to declare that they\n                            // return a Task.\n                            Task resultAsTask = result as Task;\n                            if (resultAsTask != null)\n                            {\n                                throw Error.InvalidOperation(SRResources.ActionExecutor_UnexpectedTaskInstance,\n                                    methodInfo.Name, methodInfo.DeclaringType.Name);\n                            }\n                            return Task.FromResult(result);\n                        };\n                    }\n                }\n            }\n\n            private static void ThrowIfWrappedTaskInstance(MethodInfo method, Type type)\n            {\n                // Throw if a method declares a return type of Task and returns an instance of Task<Task> or Task<Task<T>>\n                // This most likely indicates that the developer forgot to call Unwrap() somewhere.\n                Contract.Assert(method.ReturnType == typeof(Task));\n                // Fast path: check if type is exactly Task first.\n                if (type != typeof(Task))\n                {\n                    Type innerTaskType = TypeHelper.GetTaskInnerTypeOrNull(type);\n                    if (innerTaskType != null && typeof(Task).IsAssignableFrom(innerTaskType))\n                    {\n                        throw Error.InvalidOperation(SRResources.ActionExecutor_WrappedTaskInstance,\n                            method.Name, method.DeclaringType.Name, type.FullName);\n                    }\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/ReflectedHttpParameterDescriptor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Reflection;\nusing System.Web.Http.Internal;\n\nnamespace System.Web.Http.Controllers\n{\n    public class ReflectedHttpParameterDescriptor : HttpParameterDescriptor\n    {\n        private ParameterInfo _parameterInfo;\n\n        public ReflectedHttpParameterDescriptor(HttpActionDescriptor actionDescriptor, ParameterInfo parameterInfo)\n            : base(actionDescriptor)\n        {\n            if (parameterInfo == null)\n            {\n                throw Error.ArgumentNull(\"parameterInfo\");\n            }\n\n            ParameterInfo = parameterInfo;\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"ReflectedHttpParameterDescriptor\"/> class.\n        /// </summary>\n        /// <remarks>The default constructor is intended for use by unit testing only.</remarks>\n        public ReflectedHttpParameterDescriptor()\n        {\n        }\n\n        public override object DefaultValue\n        {\n            get\n            {\n                object value;\n                if (ParameterInfo.TryGetDefaultValue(out value))\n                {\n                    return value;\n                }\n                else\n                {\n                    return base.DefaultValue;\n                }\n            }\n        }\n\n        public ParameterInfo ParameterInfo\n        {\n            get { return _parameterInfo; }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n                _parameterInfo = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets a value indicating whether the parameter is optional.\n        /// </summary>\n        /// <value>\n        /// <c>true</c> if the parameter is optional; otherwise, <c>false</c>.\n        /// </value>\n        public override bool IsOptional\n        {\n            get { return ParameterInfo.IsOptional; }\n        }\n\n        public override string ParameterName\n        {\n            get { return ParameterInfo.Name; }\n        }\n\n        public override Type ParameterType\n        {\n            get { return ParameterInfo.ParameterType; }\n        }\n\n        public override Collection<TAttribute> GetCustomAttributes<TAttribute>()\n        {\n            return new Collection<TAttribute>((TAttribute[])ParameterInfo.GetCustomAttributes(typeof(TAttribute), inherit: false)); \n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/RequestBackedHttpRequestContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Security.Cryptography.X509Certificates;\nusing System.Threading;\nusing System.Web.Http.Routing;\n\nnamespace System.Web.Http.Controllers\n{\n    /// <summary>\n    /// Represents a request context that does not change the behavior of legacy properties. Once a request context is\n    /// set, things like route data and client certificate start coming from it instead of from the legacy request\n    /// properties. This class is a request context that will do the same thing as the legacy request properties would\n    /// have done while still allowing GetRequestContext to return non-null.\n    /// </summary>\n    internal sealed class RequestBackedHttpRequestContext : HttpRequestContext\n    {\n        private HttpRequestMessage _request;\n\n        private X509Certificate2 _certificate;\n        private bool _certificateSet;\n\n        private HttpConfiguration _configuration;\n        private bool _configurationSet;\n\n        private bool _includeErrorDetail;\n        private bool _includeErrorDetailSet;\n\n        private bool _isLocal;\n        private bool _isLocalSet;\n\n        private IHttpRouteData _routeData;\n        private bool _routeDataSet;\n\n        private UrlHelper _url;\n        private bool _urlSet;\n\n        private string _virtualPathRoot;\n        private bool _virtualPathRootSet;\n\n        public RequestBackedHttpRequestContext()\n        {\n            // We don't have to override Principal since the base class provides the simple property.\n            Principal = Thread.CurrentPrincipal;\n        }\n\n        public RequestBackedHttpRequestContext(HttpRequestMessage request)\n            : this()\n        {\n            if (request == null)\n            {\n                throw new ArgumentNullException(\"request\");\n            }\n\n            _request = request;\n        }\n\n        public HttpRequestMessage Request\n        {\n            get\n            {\n                return _request;\n            }\n            set\n            {\n                _request = value;\n            }\n        }\n\n        public override X509Certificate2 ClientCertificate\n        {\n            get\n            {\n                if (_certificateSet)\n                {\n                    return _certificate;\n                }\n                else if (_request != null)\n                {\n                    return _request.LegacyGetClientCertificate();\n                }\n                else\n                {\n                    return null;\n                }\n            }\n            set\n            {\n                _certificate = value;\n                _certificateSet = true;\n            }\n        }\n\n        public override HttpConfiguration Configuration\n        {\n            get\n            {\n                if (_configurationSet)\n                {\n                    return _configuration;\n                }\n                else if (_request != null)\n                {\n                    return _request.LegacyGetConfiguration();\n                }\n                else\n                {\n                    return null;\n                }\n            }\n            set\n            {\n                _configuration = value;\n                _configurationSet = true;\n            }\n        }\n\n        public override bool IncludeErrorDetail\n        {\n            get\n            {\n                if (_includeErrorDetailSet)\n                {\n                    return _includeErrorDetail;\n                }\n                else if (_request != null)\n                {\n                    return _request.LegacyShouldIncludeErrorDetail();\n                }\n                else\n                {\n                    return false;\n                }\n            }\n            set\n            {\n                _includeErrorDetail = value;\n                _includeErrorDetailSet = true;\n            }\n        }\n\n        public override bool IsLocal\n        {\n            get\n            {\n                if (_isLocalSet)\n                {\n                    return _isLocal;\n                }\n                else if (_request != null)\n                {\n                    return _request.LegacyIsLocal();\n                }\n                else\n                {\n                    return false;\n                }\n            }\n            set\n            {\n                _isLocal = value;\n                _isLocalSet = true;\n            }\n        }\n\n        public override IHttpRouteData RouteData\n        {\n            get\n            {\n                if (_routeDataSet)\n                {\n                    return _routeData;\n                }\n                else if (_request != null)\n                {\n                    return _request.LegacyGetRouteData();\n                }\n                else\n                {\n                    return null;\n                }\n            }\n            set\n            {\n                _routeData = value;\n                _routeDataSet = true;\n            }\n        }\n\n        public override UrlHelper Url\n        {\n            get\n            {\n                if (_urlSet)\n                {\n                    return _url;\n                }\n                else if (_request != null)\n                {\n                    return new UrlHelper(_request);\n                }\n                else\n                {\n                    return null;\n                }\n            }\n            set\n            {\n                _url = value;\n                _urlSet = true;\n            }\n        }\n\n        public override string VirtualPathRoot\n        {\n            get\n            {\n                if (_virtualPathRootSet)\n                {\n                    return _virtualPathRoot;\n                }\n\n                HttpConfiguration configuration = Configuration;\n\n                if (configuration != null)\n                {\n                    return configuration.VirtualPathRoot;\n                }\n                else\n                {\n                    return null;\n                }\n            }\n            set\n            {\n                _virtualPathRoot = value;\n                _virtualPathRootSet = true;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/ResponseMessageResultConverter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.Controllers\n{\n    /// <summary>\n    /// A converter for actions with a return type of <see cref=\"HttpResponseMessage\"/>.\n    /// </summary>\n    public class ResponseMessageResultConverter : IActionResultConverter\n    {\n        public HttpResponseMessage Convert(HttpControllerContext controllerContext, object actionResult)\n        {\n            if (controllerContext == null)\n            {\n                throw Error.ArgumentNull(\"controllerContext\");\n            }\n\n            HttpResponseMessage response = (HttpResponseMessage)actionResult;\n            if (response == null)\n            {\n                throw Error.InvalidOperation(SRResources.ResponseMessageResultConverter_NullHttpResponseMessage);\n            }\n\n            response.EnsureResponseHasRequest(controllerContext.Request);\n            return response;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/ValueResultConverter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\n\nnamespace System.Web.Http.Controllers\n{\n    /// <summary>\n    /// A converter for creating responses from actions that return an arbitrary T value.\n    /// </summary>\n    /// <typeparam name=\"T\">The declared return type of an action.</typeparam>\n    public class ValueResultConverter<T> : IActionResultConverter\n    {\n        public HttpResponseMessage Convert(HttpControllerContext controllerContext, object actionResult)\n        {\n            if (controllerContext == null)\n            {\n                throw Error.ArgumentNull(\"controllerContext\");\n            }\n\n            HttpResponseMessage resultAsResponse = actionResult as HttpResponseMessage;\n            if (resultAsResponse != null)\n            {\n                resultAsResponse.EnsureResponseHasRequest(controllerContext.Request);\n                return resultAsResponse;\n            }\n\n            T value = (T)actionResult;\n            return controllerContext.Request.CreateResponse<T>(HttpStatusCode.OK, value, controllerContext.Configuration);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Controllers/VoidResultConverter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.Net.Http;\n\nnamespace System.Web.Http.Controllers\n{\n    /// <summary>\n    /// A converter for creating a response from actions that do not return a value.\n    /// </summary>\n    public class VoidResultConverter : IActionResultConverter\n    {\n        public HttpResponseMessage Convert(HttpControllerContext controllerContext, object actionResult)\n        {\n            if (controllerContext == null)\n            {\n                throw Error.ArgumentNull(\"controllerContext\");\n            }\n\n            Contract.Assert(actionResult == null);\n            return controllerContext.Request.CreateResponse(HttpStatusCode.NoContent);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Dependencies/EmptyResolver.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace System.Web.Http.Dependencies\n{\n    internal class EmptyResolver : IDependencyResolver\n    {\n        private static readonly IDependencyResolver _instance = new EmptyResolver();\n\n        private EmptyResolver()\n        {\n        }\n\n        public static IDependencyResolver Instance\n        {\n            get { return _instance; }\n        }\n\n        public IDependencyScope BeginScope()\n        {\n            return this;\n        }\n\n        public void Dispose()\n        {\n        }\n\n        public object GetService(Type serviceType)\n        {\n            return null;\n        }\n\n        public IEnumerable<object> GetServices(Type serviceType)\n        {\n            return Enumerable.Empty<object>();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Dependencies/IDependencyResolver.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Dependencies\n{\n    /// <summary>\n    /// Represents a dependency injection container.\n    /// </summary>\n    public interface IDependencyResolver : IDependencyScope\n    {\n        /// <summary>\n        /// Starts a resolution scope. Objects which are resolved in the given scope will belong to\n        /// that scope, and when the scope is disposed, those objects are returned to the container.\n        /// Implementers should return a new instance of <see cref=\"IDependencyScope\"/> every time this\n        /// method is called, unless the container does not have any concept of scope or resource\n        /// release (in which case, it would be okay to return 'this', so long as the calls to\n        /// <see cref=\"IDisposable.Dispose\"/> are effectively NOOPs).\n        /// </summary>\n        /// <returns>The dependency scope.</returns>\n        IDependencyScope BeginScope();\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Dependencies/IDependencyScope.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Http.Dependencies\n{\n    /// <summary>\n    /// Represents a scope that is tracked by the dependency injection container. The scope is\n    /// used to keep track of resources that have been provided, so that they can then be\n    /// subsequently released when <see cref=\"IDisposable.Dispose\"/> is called.\n    /// </summary>\n    public interface IDependencyScope : IDisposable\n    {\n        /// <summary>\n        /// Gets an instance of the given <paramref name=\"serviceType\"/>. Must return <c>null</c>\n        /// if the service is not available (must not throw).\n        /// </summary>\n        /// <param name=\"serviceType\">The object type.</param>\n        /// <returns>The requested object, if found; <c>null</c> otherwise.</returns>\n        object GetService(Type serviceType);\n\n        /// <summary>\n        /// Gets all instances of the given <paramref name=\"serviceType\"/>. Must return an empty\n        /// collection if the service is not available (must not return <c>null</c> or throw).\n        /// </summary>\n        /// <param name=\"serviceType\">The object type.</param>\n        /// <returns>A sequence of instances of the requested <paramref name=\"serviceType\"/>. The sequence\n        /// should be empty (not <c>null</c>) if no objects of the given type are available.</returns>\n        IEnumerable<object> GetServices(Type serviceType);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Description/ApiDescription.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Routing;\n\nnamespace System.Web.Http.Description\n{\n    /// <summary>\n    /// Describes an API defined by relative URI path and HTTP method.\n    /// </summary>\n    public class ApiDescription\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"ApiDescription\"/> class.\n        /// </summary>\n        public ApiDescription()\n        {\n            SupportedRequestBodyFormatters = new Collection<MediaTypeFormatter>();\n            SupportedResponseFormatters = new Collection<MediaTypeFormatter>();\n            ParameterDescriptions = new Collection<ApiParameterDescription>();\n            ResponseDescription = new ResponseDescription();\n        }\n\n        /// <summary>\n        /// Gets or sets the HTTP method.\n        /// </summary>\n        /// <value>\n        /// The HTTP method.\n        /// </value>\n        public HttpMethod HttpMethod { get; set; }\n\n        /// <summary>\n        /// Gets or sets the relative path.\n        /// </summary>\n        /// <value>\n        /// The relative path.\n        /// </value>\n        public string RelativePath { get; set; }\n\n        /// <summary>\n        /// Gets or sets the action descriptor that will handle the API.\n        /// </summary>\n        /// <value>\n        /// The action descriptor.\n        /// </value>\n        public HttpActionDescriptor ActionDescriptor { get; set; }\n\n        /// <summary>\n        /// Gets or sets the registered route for the API.\n        /// </summary>\n        /// <value>\n        /// The route.\n        /// </value>\n        public IHttpRoute Route { get; set; }\n\n        /// <summary>\n        /// Gets or sets the documentation of the API.\n        /// </summary>\n        /// <value>\n        /// The documentation.\n        /// </value>\n        public string Documentation { get; set; }\n\n        /// <summary>\n        /// Gets the supported response formatters.\n        /// </summary>\n        public Collection<MediaTypeFormatter> SupportedResponseFormatters { get; internal set; }\n\n        /// <summary>\n        /// Gets the supported request body formatters.\n        /// </summary>\n        public Collection<MediaTypeFormatter> SupportedRequestBodyFormatters { get; internal set; }\n\n        /// <summary>\n        /// Gets the parameter descriptions.\n        /// </summary>\n        public Collection<ApiParameterDescription> ParameterDescriptions { get; internal set; }\n\n        /// <summary>\n        /// Gets the response description.\n        /// </summary>\n        public ResponseDescription ResponseDescription { get; internal set; }\n\n        /// <summary>\n        /// Gets the ID. The ID is unique within <see cref=\"HttpServer\"/>.\n        /// </summary>\n        public string ID\n        {\n            get\n            {\n                return (HttpMethod != null ? HttpMethod.Method : String.Empty) +\n                    (RelativePath ?? String.Empty);\n            }\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http/Description/ApiExplorer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Reflection;\nusing System.Text.RegularExpressions;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.Internal;\nusing System.Web.Http.ModelBinding.Binders;\nusing System.Web.Http.Routing;\nusing System.Web.Http.Services;\n\nnamespace System.Web.Http.Description\n{\n    /// <summary>\n    /// Explores the URI space of the service based on routes, controllers and actions available in the system.\n    /// </summary>\n    public class ApiExplorer : IApiExplorer\n    {\n        private Lazy<Collection<ApiDescription>> _apiDescriptions;\n        private readonly HttpConfiguration _config;\n        private static readonly Regex _actionVariableRegex = new Regex(String.Format(CultureInfo.CurrentCulture, \"{{{0}}}\", RouteValueKeys.Action), RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);\n        private static readonly Regex _controllerVariableRegex = new Regex(String.Format(CultureInfo.CurrentCulture, \"{{{0}}}\", RouteValueKeys.Controller), RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"ApiExplorer\"/> class.\n        /// </summary>\n        /// <param name=\"configuration\">The configuration.</param>\n        public ApiExplorer(HttpConfiguration configuration)\n        {\n            _config = configuration;\n            _apiDescriptions = new Lazy<Collection<ApiDescription>>(InitializeApiDescriptions);\n        }\n\n        /// <summary>\n        /// Gets the API descriptions. The descriptions are initialized on the first access.\n        /// </summary>\n        public Collection<ApiDescription> ApiDescriptions\n        {\n            get\n            {\n                return _apiDescriptions.Value;\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets the documentation provider. The provider will be responsible for documenting the API.\n        /// </summary>\n        /// <value>\n        /// The documentation provider.\n        /// </value>\n        public IDocumentationProvider DocumentationProvider { get; set; }\n\n        /// <summary>\n        /// Determines whether the controller should be considered for <see cref=\"ApiExplorer.ApiDescriptions\"/> generation. Called when initializing the <see cref=\"ApiExplorer.ApiDescriptions\"/>.\n        /// </summary>\n        /// <param name=\"controllerVariableValue\">The controller variable value from the route.</param>\n        /// <param name=\"controllerDescriptor\">The controller descriptor.</param>\n        /// <param name=\"route\">The route.</param>\n        /// <returns><c>true</c> if the controller should be considered for <see cref=\"ApiExplorer.ApiDescriptions\"/> generation, <c>false</c> otherwise.</returns>\n        public virtual bool ShouldExploreController(string controllerVariableValue, HttpControllerDescriptor controllerDescriptor, IHttpRoute route)\n        {\n            if (controllerDescriptor == null)\n            {\n                throw Error.ArgumentNull(\"controllerDescriptor\");\n            }\n\n            if (route == null)\n            {\n                throw Error.ArgumentNull(\"route\");\n            }\n\n            ApiExplorerSettingsAttribute setting = controllerDescriptor.GetCustomAttributes<ApiExplorerSettingsAttribute>().FirstOrDefault();\n            return (setting == null || !setting.IgnoreApi) &&\n                MatchRegexConstraint(route, RouteValueKeys.Controller, controllerVariableValue);\n        }\n\n        /// <summary>\n        /// Determines whether the action should be considered for <see cref=\"ApiExplorer.ApiDescriptions\"/> generation. Called when initializing the <see cref=\"ApiExplorer.ApiDescriptions\"/>.\n        /// </summary>\n        /// <param name=\"actionVariableValue\">The action variable value from the route.</param>\n        /// <param name=\"actionDescriptor\">The action descriptor.</param>\n        /// <param name=\"route\">The route.</param>\n        /// <returns><c>true</c> if the action should be considered for <see cref=\"ApiExplorer.ApiDescriptions\"/> generation, <c>false</c> otherwise.</returns>\n        public virtual bool ShouldExploreAction(string actionVariableValue, HttpActionDescriptor actionDescriptor, IHttpRoute route)\n        {\n            if (actionDescriptor == null)\n            {\n                throw Error.ArgumentNull(\"actionDescriptor\");\n            }\n\n            if (route == null)\n            {\n                throw Error.ArgumentNull(\"route\");\n            }\n\n            ApiExplorerSettingsAttribute setting = actionDescriptor.GetCustomAttributes<ApiExplorerSettingsAttribute>().FirstOrDefault();\n            return (setting == null || !setting.IgnoreApi) &&\n                MatchRegexConstraint(route, RouteValueKeys.Action, actionVariableValue);\n        }\n\n        /// <summary>\n        /// Gets a collection of HttpMethods supported by the action. Called when initializing the <see cref=\"ApiExplorer.ApiDescriptions\"/>.\n        /// </summary>\n        /// <param name=\"route\">The route.</param>\n        /// <param name=\"actionDescriptor\">The action descriptor.</param>\n        /// <returns>A collection of HttpMethods supported by the action.</returns>\n        public virtual Collection<HttpMethod> GetHttpMethodsSupportedByAction(IHttpRoute route, HttpActionDescriptor actionDescriptor)\n        {\n            if (route == null)\n            {\n                throw Error.ArgumentNull(\"route\");\n            }\n\n            if (actionDescriptor == null)\n            {\n                throw Error.ArgumentNull(\"actionDescriptor\");\n            }\n\n            IList<HttpMethod> supportedMethods = new List<HttpMethod>();\n            IList<HttpMethod> actionHttpMethods = actionDescriptor.SupportedHttpMethods;\n            HttpMethodConstraint httpMethodConstraint = route.Constraints.Values.FirstOrDefault(c => typeof(HttpMethodConstraint).IsAssignableFrom(c.GetType())) as HttpMethodConstraint;\n\n            if (httpMethodConstraint == null)\n            {\n                supportedMethods = actionHttpMethods;\n            }\n            else\n            {\n                supportedMethods = httpMethodConstraint.AllowedMethods.Intersect(actionHttpMethods).ToList();\n            }\n\n            return new Collection<HttpMethod>(supportedMethods);\n        }\n\n        private IEnumerable<IHttpRoute> FlattenRoutes(IEnumerable<IHttpRoute> routes)\n        {\n            foreach (IHttpRoute route in routes)\n            {\n                IEnumerable<IHttpRoute> nested = route as IEnumerable<IHttpRoute>;\n                if (nested != null)\n                {\n                    foreach (var subRoute in FlattenRoutes(nested))\n                    {\n                        yield return subRoute;\n                    }\n                }\n                else\n                {\n                    yield return route;\n                }\n            }\n        }\n\n        private static HttpControllerDescriptor GetDirectRouteController(CandidateAction[] directRouteCandidates)\n        {\n            if (directRouteCandidates != null)\n            {\n                // Set the controller descriptor for the first action descriptor\n                HttpControllerDescriptor controllerDescriptor = directRouteCandidates[0].ActionDescriptor.ControllerDescriptor;\n\n                // Check that all other action descriptors share the same controller descriptor\n                for (int i = 1; i < directRouteCandidates.Length; i++)\n                {\n                    if (directRouteCandidates[i].ActionDescriptor.ControllerDescriptor != controllerDescriptor)\n                    {\n                        // This can happen if a developer puts the same route template on different actions\n                        // in different controllers.\n                        return null;\n                    }\n                }\n\n                return controllerDescriptor;\n            }\n\n            return null;\n        }\n\n        private Collection<ApiDescription> InitializeApiDescriptions()\n        {\n            Collection<ApiDescription> apiDescriptions = new Collection<ApiDescription>();\n            IHttpControllerSelector controllerSelector = _config.Services.GetHttpControllerSelector();\n            IDictionary<string, HttpControllerDescriptor> controllerMappings = controllerSelector.GetControllerMapping();\n            if (controllerMappings != null)\n            {\n                ApiDescriptionComparer descriptionComparer = new ApiDescriptionComparer();\n                foreach (IHttpRoute route in FlattenRoutes(_config.Routes))\n                {\n                    CandidateAction[] directRouteCandidates = route.GetDirectRouteCandidates();\n\n                    HttpControllerDescriptor directRouteController = GetDirectRouteController(directRouteCandidates);\n                    Collection<ApiDescription> descriptionsFromRoute =\n                        (directRouteController != null && directRouteCandidates != null) ?\n                            ExploreDirectRoute(directRouteController, directRouteCandidates, route) :\n                            ExploreRouteControllers(controllerMappings, route);\n\n                    // Remove ApiDescription that will lead to ambiguous action matching.\n                    // E.g. a controller with Post() and PostComment(). When the route template is {controller}, it produces POST /controller and POST /controller.\n                    descriptionsFromRoute = RemoveInvalidApiDescriptions(descriptionsFromRoute);\n\n                    foreach (ApiDescription description in descriptionsFromRoute)\n                    {\n                        // Do not add the description if the previous route has a matching description with the same HTTP method and relative path.\n                        // E.g. having two routes with the templates \"api/Values/{id}\" and \"api/{controller}/{id}\" can potentially produce the same\n                        // relative path \"api/Values/{id}\" but only the first one matters.\n                        if (!apiDescriptions.Contains(description, descriptionComparer))\n                        {\n                            apiDescriptions.Add(description);\n                        }\n                    }\n                }\n            }\n\n            return apiDescriptions;\n        }\n\n        private Collection<ApiDescription> ExploreDirectRoute(HttpControllerDescriptor controllerDescriptor, CandidateAction[] candidates, IHttpRoute route)\n        {\n            Collection<ApiDescription> descriptions = new Collection<ApiDescription>();\n\n            if (ShouldExploreController(controllerDescriptor.ControllerName, controllerDescriptor, route))\n            {\n                foreach (CandidateAction action in candidates)\n                {\n                    HttpActionDescriptor actionDescriptor = action.ActionDescriptor;\n                    string actionName = actionDescriptor.ActionName;\n\n                    if (ShouldExploreAction(actionName, actionDescriptor, route))\n                    {\n                        string routeTemplate = route.RouteTemplate;\n                        if (_actionVariableRegex.IsMatch(routeTemplate))\n                        {\n                            // expand {action} variable\n                            routeTemplate = _actionVariableRegex.Replace(routeTemplate, actionName);\n                        }\n\n                        PopulateActionDescriptions(actionDescriptor, route, routeTemplate, descriptions);\n                    }\n                }\n            }\n\n            return descriptions;\n        }\n\n        private Collection<ApiDescription> ExploreRouteControllers(IDictionary<string, HttpControllerDescriptor> controllerMappings, IHttpRoute route)\n        {\n            Collection<ApiDescription> apiDescriptions = new Collection<ApiDescription>();\n            string routeTemplate = route.RouteTemplate;\n            string controllerVariableValue;\n            if (_controllerVariableRegex.IsMatch(routeTemplate))\n            {\n                // unbound controller variable, {controller}\n                foreach (KeyValuePair<string, HttpControllerDescriptor> controllerMapping in controllerMappings)\n                {\n                    controllerVariableValue = controllerMapping.Key;\n                    HttpControllerDescriptor controllerDescriptor = controllerMapping.Value;\n                    if (ShouldExploreController(controllerVariableValue, controllerDescriptor, route))\n                    {\n                        // expand {controller} variable\n                        string expandedRouteTemplate = _controllerVariableRegex.Replace(routeTemplate, controllerVariableValue);\n                        ExploreRouteActions(route, expandedRouteTemplate, controllerDescriptor, apiDescriptions);\n                    }\n                }\n            }\n            else if (route.Defaults.TryGetValue(RouteValueKeys.Controller, out controllerVariableValue))\n            {\n                // bound controller variable, {controller = \"controllerName\"}\n                HttpControllerDescriptor controllerDescriptor;\n                if (controllerMappings.TryGetValue(controllerVariableValue, out controllerDescriptor) && ShouldExploreController(controllerVariableValue, controllerDescriptor, route))\n                {\n                    ExploreRouteActions(route, routeTemplate, controllerDescriptor, apiDescriptions);\n                }\n            }\n\n            return apiDescriptions;\n        }\n\n        private void ExploreRouteActions(IHttpRoute route, string localPath, HttpControllerDescriptor controllerDescriptor, Collection<ApiDescription> apiDescriptions)\n        {\n            // exclude controllers that are marked with route attributes.\n            if (!controllerDescriptor.IsAttributeRouted())\n            {\n                ServicesContainer controllerServices = controllerDescriptor.Configuration.Services;\n                ILookup<string, HttpActionDescriptor> actionMappings = controllerServices.GetActionSelector().GetActionMapping(controllerDescriptor);\n                string actionVariableValue;\n                if (actionMappings != null)\n                {\n                    if (_actionVariableRegex.IsMatch(localPath))\n                    {\n                        // unbound action variable, {action}\n                        foreach (IGrouping<string, HttpActionDescriptor> actionMapping in actionMappings)\n                        {\n                            // expand {action} variable\n                            actionVariableValue = actionMapping.Key;\n                            string expandedLocalPath = _actionVariableRegex.Replace(localPath, actionVariableValue);\n                            PopulateActionDescriptions(actionMapping, actionVariableValue, route, expandedLocalPath, apiDescriptions);\n                        }\n                    }\n                    else if (route.Defaults.TryGetValue(RouteValueKeys.Action, out actionVariableValue))\n                    {\n                        // bound action variable, { action = \"actionName\" }\n                        PopulateActionDescriptions(actionMappings[actionVariableValue], actionVariableValue, route, localPath, apiDescriptions);\n                    }\n                    else\n                    {\n                        // no {action} specified, e.g. {controller}/{id}\n                        foreach (IGrouping<string, HttpActionDescriptor> actionMapping in actionMappings)\n                        {\n                            PopulateActionDescriptions(actionMapping, null, route, localPath, apiDescriptions);\n                        }\n                    }\n                }\n            }\n        }\n\n        private void PopulateActionDescriptions(IEnumerable<HttpActionDescriptor> actionDescriptors, string actionVariableValue, IHttpRoute route, string localPath, Collection<ApiDescription> apiDescriptions)\n        {\n            foreach (HttpActionDescriptor actionDescriptor in actionDescriptors)\n            {\n                if (ShouldExploreAction(actionVariableValue, actionDescriptor, route))\n                {\n                    // exclude actions that are marked with route attributes except for the inherited actions.\n                    if (!actionDescriptor.IsAttributeRouted())\n                    {\n                        PopulateActionDescriptions(actionDescriptor, route, localPath, apiDescriptions);\n                    }\n                }\n            }\n        }\n\n        private void PopulateActionDescriptions(HttpActionDescriptor actionDescriptor, IHttpRoute route, string localPath, Collection<ApiDescription> apiDescriptions)\n        {\n            string apiDocumentation = GetApiDocumentation(actionDescriptor);\n\n            HttpParsedRoute parsedRoute = RouteParser.Parse(localPath);\n\n            // parameters\n            IList<ApiParameterDescription> parameterDescriptions = CreateParameterDescriptions(actionDescriptor, parsedRoute, route.Defaults);\n\n            // expand all parameter variables\n            string finalPath;\n\n            if (!TryExpandUriParameters(route, parsedRoute, parameterDescriptions, out finalPath))\n            {\n                // the action cannot be reached due to parameter mismatch, e.g. routeTemplate = \"/users/{name}\" and GetUsers(id)\n                return;\n            }\n\n            // request formatters\n            ApiParameterDescription bodyParameter = parameterDescriptions.FirstOrDefault(description => description.Source == ApiParameterSource.FromBody);\n            IEnumerable<MediaTypeFormatter> supportedRequestBodyFormatters = bodyParameter != null ?\n                actionDescriptor.Configuration.Formatters.Where(f => f.CanReadType(bodyParameter.ParameterDescriptor.ParameterType)) :\n                Enumerable.Empty<MediaTypeFormatter>();\n\n            // response formatters\n            ResponseDescription responseDescription = CreateResponseDescription(actionDescriptor);\n            Type returnType = responseDescription.ResponseType ?? responseDescription.DeclaredType;\n            IEnumerable<MediaTypeFormatter> supportedResponseFormatters = (returnType != null && returnType != typeof(void)) ?\n                actionDescriptor.Configuration.Formatters.Where(f => f.CanWriteType(returnType)) :\n                Enumerable.Empty<MediaTypeFormatter>();\n\n            // Replacing the formatter tracers with formatters if tracers are present.\n            supportedRequestBodyFormatters = GetInnerFormatters(supportedRequestBodyFormatters);\n            supportedResponseFormatters = GetInnerFormatters(supportedResponseFormatters);\n\n            // get HttpMethods supported by an action. Usually there is one HttpMethod per action but we allow multiple of them per action as well.\n            IList<HttpMethod> supportedMethods = GetHttpMethodsSupportedByAction(route, actionDescriptor);\n\n            foreach (HttpMethod method in supportedMethods)\n            {\n                apiDescriptions.Add(new ApiDescription\n                {\n                    Documentation = apiDocumentation,\n                    HttpMethod = method,\n                    RelativePath = finalPath,\n                    ActionDescriptor = actionDescriptor,\n                    Route = route,\n                    SupportedResponseFormatters = new Collection<MediaTypeFormatter>(supportedResponseFormatters.ToList()),\n                    SupportedRequestBodyFormatters = new Collection<MediaTypeFormatter>(supportedRequestBodyFormatters.ToList()),\n                    ParameterDescriptions = new Collection<ApiParameterDescription>(parameterDescriptions),\n                    ResponseDescription = responseDescription\n                });\n            }\n        }\n\n        private ResponseDescription CreateResponseDescription(HttpActionDescriptor actionDescriptor)\n        {\n            Collection<ResponseTypeAttribute> responseTypeAttribute = actionDescriptor.GetCustomAttributes<ResponseTypeAttribute>();\n            Type responseType = responseTypeAttribute.Select(attribute => attribute.ResponseType).FirstOrDefault();\n\n            return new ResponseDescription\n            {\n                DeclaredType = actionDescriptor.ReturnType,\n                ResponseType = responseType,\n                Documentation = GetApiResponseDocumentation(actionDescriptor)\n            };\n        }\n\n        private static IEnumerable<MediaTypeFormatter> GetInnerFormatters(IEnumerable<MediaTypeFormatter> mediaTypeFormatters)\n        {\n            foreach (MediaTypeFormatter formatter in mediaTypeFormatters)\n            {\n                yield return Decorator.GetInner(formatter);\n            }\n        }\n\n        private static bool ShouldEmitPrefixes(ICollection<ApiParameterDescription> parameterDescriptions)\n        {\n            // Determine if there are two or more complex objects from the Uri so TryExpandUriParameters needs to emit prefixes.\n            return parameterDescriptions.Count(parameter =>\n                        parameter.Source == ApiParameterSource.FromUri &&\n                        parameter.ParameterDescriptor != null &&\n                        !TypeHelper.CanConvertFromString(parameter.ParameterDescriptor.ParameterType) &&\n                        parameter.CanConvertPropertiesFromString()) > 1;\n        }\n\n        // Set as internal for the unit test.\n        internal static bool TryExpandUriParameters(IHttpRoute route, HttpParsedRoute parsedRoute, ICollection<ApiParameterDescription> parameterDescriptions, out string expandedRouteTemplate)\n        {\n            Dictionary<string, object> parameterValuesForRoute = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);\n            bool emitPrefixes = ShouldEmitPrefixes(parameterDescriptions);\n            string prefix = String.Empty;\n            foreach (ApiParameterDescription parameterDescription in parameterDescriptions)\n            {\n                if (parameterDescription.Source == ApiParameterSource.FromUri)\n                {\n                    if (parameterDescription.ParameterDescriptor == null)\n                    {\n                        // Undeclared route parameter handling generates query string like\n                        // \"?name={name}\"\n                        AddPlaceholder(parameterValuesForRoute, parameterDescription.Name);\n                    }\n                    else if (TypeHelper.CanConvertFromString(parameterDescription.ParameterDescriptor.ParameterType))\n                    {\n                        // Simple type generates query string like\n                        // \"?name={name}\"\n                        AddPlaceholder(parameterValuesForRoute, parameterDescription.Name);\n                    }\n                    else if (IsBindableCollection(parameterDescription.ParameterDescriptor.ParameterType))\n                    {\n                        string parameterName = parameterDescription.ParameterDescriptor.ParameterName;\n                        Type innerType =\n                            GetCollectionElementType(parameterDescription.ParameterDescriptor.ParameterType);\n                        PropertyInfo[] innerTypeProperties =\n                            ApiParameterDescription.GetBindableProperties(innerType).ToArray();\n                        if (innerTypeProperties.Any())\n                        {\n                            // Complex array and collection generate query string like\n                            // \"?name[0].foo={name[0].foo}&name[0].bar={name[0].bar}\n                            //  &name[1].foo={name[1].foo}&name[1].bar={name[1].bar}\"\n                            AddPlaceholderForProperties(parameterValuesForRoute,\n                                                        innerTypeProperties,\n                                                        parameterName + \"[0].\");\n                            AddPlaceholderForProperties(parameterValuesForRoute,\n                                                        innerTypeProperties,\n                                                        parameterName + \"[1].\");\n                        }\n                        else\n                        {\n                            // Simple array and collection generate query string like\n                            // \"?name[0]={name[0]}&name[1]={name[1]}\".\n                            AddPlaceholder(parameterValuesForRoute, parameterName + \"[0]\");\n                            AddPlaceholder(parameterValuesForRoute, parameterName + \"[1]\");\n                        }\n                    }\n                    else if (IsBindableKeyValuePair(parameterDescription.ParameterDescriptor.ParameterType))\n                    {\n                        // KeyValuePair generates query string like\n                        // \"?key={key}&value={value}\"\n                        AddPlaceholder(parameterValuesForRoute, \"key\");\n                        AddPlaceholder(parameterValuesForRoute, \"value\");\n                    }\n                    else if (IsBindableDictionry(parameterDescription.ParameterDescriptor.ParameterType))\n                    {\n                        // Dictionary generates query string like\n                        // \"?dict[0].key={dict[0].key}&dict[0].value={dict[0].value}\n                        //  &dict[1].key={dict[1].key}&dict[1].value={dict[1].value}\"\n                        string parameterName = parameterDescription.ParameterDescriptor.ParameterName;\n                        AddPlaceholder(parameterValuesForRoute, parameterName + \"[0].key\");\n                        AddPlaceholder(parameterValuesForRoute, parameterName + \"[0].value\");\n                        AddPlaceholder(parameterValuesForRoute, parameterName + \"[1].key\");\n                        AddPlaceholder(parameterValuesForRoute, parameterName + \"[1].value\");\n                    }\n                    else if (parameterDescription.CanConvertPropertiesFromString())\n                    {\n                        if (emitPrefixes)\n                        {\n                            prefix = parameterDescription.Name + \".\";\n                        }\n\n                        // Inserting the individual properties of the object in the query string\n                        // as all the complex object can not be converted from string, but all its\n                        // individual properties can.\n                        AddPlaceholderForProperties(parameterValuesForRoute,\n                                                    parameterDescription.GetBindableProperties(),\n                                                    prefix);\n                    }\n                }\n            }\n\n            BoundRouteTemplate boundRouteTemplate = parsedRoute.Bind(null, parameterValuesForRoute, new HttpRouteValueDictionary(route.Defaults), new HttpRouteValueDictionary(route.Constraints));\n            if (boundRouteTemplate == null)\n            {\n                expandedRouteTemplate = null;\n                return false;\n            }\n\n            expandedRouteTemplate = Uri.UnescapeDataString(boundRouteTemplate.BoundTemplate);\n            return true;\n        }\n\n        private static Type GetCollectionElementType(Type collectionType)\n        {\n            Contract.Assert(!typeof(IDictionary).IsAssignableFrom(collectionType));\n\n            Type elementType = collectionType.GetElementType();\n            if (elementType == null)\n            {\n                elementType = CollectionModelBinderUtil\n                    .GetGenericBinderTypeArgs(typeof(ICollection<>), collectionType)\n                    .First();\n            }\n            return elementType;\n        }\n\n        private static void AddPlaceholderForProperties(Dictionary<string, object> parameterValuesForRoute,\n                                                        IEnumerable<PropertyInfo> properties,\n                                                        string prefix)\n        {\n            foreach (PropertyInfo property in properties)\n            {\n                string queryParameterName = prefix + property.Name;\n                AddPlaceholder(parameterValuesForRoute, queryParameterName);\n            }\n        }\n\n        private static bool IsBindableCollection(Type type)\n        {\n            Contract.Assert(type != null);\n\n            return type.IsArray || new CollectionModelBinderProvider().GetBinder(null, type) != null;\n        }\n\n        private static bool IsBindableDictionry(Type type)\n        {\n            Contract.Assert(type != null);\n\n            return new DictionaryModelBinderProvider().GetBinder(null, type) != null;\n        }\n\n        private static bool IsBindableKeyValuePair(Type type)\n        {\n            Contract.Assert(type != null);\n\n            return TypeHelper.GetTypeArgumentsIfMatch(type, typeof(KeyValuePair<,>)) != null;\n        }\n\n        private static void AddPlaceholder(Dictionary<string, object> parameterValuesForRoute,\n                                          string queryParameterName)\n        {\n            if (!parameterValuesForRoute.ContainsKey(queryParameterName))\n            {\n                parameterValuesForRoute.Add(queryParameterName, \"{\" + queryParameterName + \"}\");\n            }\n        }\n\n        private IList<ApiParameterDescription> CreateParameterDescriptions(HttpActionDescriptor actionDescriptor, HttpParsedRoute parsedRoute, IDictionary<string, object> routeDefaults)\n        {\n            IList<ApiParameterDescription> parameterDescriptions = new List<ApiParameterDescription>();\n            HttpActionBinding actionBinding = GetActionBinding(actionDescriptor);\n\n            // try get parameter binding information if available\n            if (actionBinding != null)\n            {\n                HttpParameterBinding[] parameterBindings = actionBinding.ParameterBindings;\n                if (parameterBindings != null)\n                {\n                    foreach (HttpParameterBinding parameter in parameterBindings)\n                    {\n                        parameterDescriptions.Add(CreateParameterDescriptionFromBinding(parameter));\n                    }\n                }\n            }\n            else\n            {\n                Collection<HttpParameterDescriptor> parameters = actionDescriptor.GetParameters();\n                if (parameters != null)\n                {\n                    foreach (HttpParameterDescriptor parameter in parameters)\n                    {\n                        parameterDescriptions.Add(CreateParameterDescriptionFromDescriptor(parameter));\n                    }\n                }\n            }\n\n            // Adding route parameters not declared on the action. We're doing this because route parameters may or\n            // may not be part of the action parameters and we want to have them in the description.\n            AddUndeclaredRouteParameters(parsedRoute, routeDefaults, parameterDescriptions);\n\n            return parameterDescriptions;\n        }\n\n        private static void AddUndeclaredRouteParameters(HttpParsedRoute parsedRoute, IDictionary<string, object> routeDefaults, IList<ApiParameterDescription> parameterDescriptions)\n        {\n            foreach (PathSegment path in parsedRoute.PathSegments)\n            {\n                PathContentSegment content = path as PathContentSegment;\n                if (content != null)\n                {\n                    foreach (PathSubsegment subSegment in content.Subsegments)\n                    {\n                        PathParameterSubsegment parameter = subSegment as PathParameterSubsegment;\n                        if (parameter != null)\n                        {\n                            object parameterValue;\n                            string parameterName = parameter.ParameterName;\n                            if (!parameterDescriptions.Any(p => String.Equals(p.Name, parameterName, StringComparison.OrdinalIgnoreCase)) &&\n                                (!routeDefaults.TryGetValue(parameterName, out parameterValue) ||\n                                parameterValue != RouteParameter.Optional))\n                            {\n                                parameterDescriptions.Add(\n                                    new ApiParameterDescription\n                                    {\n                                        Name = parameterName,\n                                        Source = ApiParameterSource.FromUri\n                                    });\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        private ApiParameterDescription CreateParameterDescriptionFromDescriptor(HttpParameterDescriptor parameter)\n        {\n            Contract.Assert(parameter != null);\n            return new ApiParameterDescription\n            {\n                ParameterDescriptor = parameter,\n                Name = parameter.Prefix ?? parameter.ParameterName,\n                Documentation = GetApiParameterDocumentation(parameter),\n                Source = ApiParameterSource.Unknown,\n            };\n        }\n\n        private ApiParameterDescription CreateParameterDescriptionFromBinding(HttpParameterBinding parameterBinding)\n        {\n            ApiParameterDescription parameterDescription = CreateParameterDescriptionFromDescriptor(parameterBinding.Descriptor);\n            if (parameterBinding.WillReadBody)\n            {\n                parameterDescription.Source = ApiParameterSource.FromBody;\n            }\n            else if (parameterBinding.WillReadUri())\n            {\n                parameterDescription.Source = ApiParameterSource.FromUri;\n            }\n\n            return parameterDescription;\n        }\n\n        private string GetApiDocumentation(HttpActionDescriptor actionDescriptor)\n        {\n            IDocumentationProvider documentationProvider = DocumentationProvider ?? actionDescriptor.Configuration.Services.GetDocumentationProvider();\n            if (documentationProvider != null)\n            {\n                return documentationProvider.GetDocumentation(actionDescriptor);\n            }\n\n            return null;\n        }\n\n        private string GetApiParameterDocumentation(HttpParameterDescriptor parameterDescriptor)\n        {\n            IDocumentationProvider documentationProvider = DocumentationProvider ?? parameterDescriptor.Configuration.Services.GetDocumentationProvider();\n            if (documentationProvider != null)\n            {\n                return documentationProvider.GetDocumentation(parameterDescriptor);\n            }\n\n            return null;\n        }\n\n        private string GetApiResponseDocumentation(HttpActionDescriptor actionDescriptor)\n        {\n            IDocumentationProvider documentationProvider = DocumentationProvider ?? actionDescriptor.Configuration.Services.GetDocumentationProvider();\n            if (documentationProvider != null)\n            {\n                return documentationProvider.GetResponseDocumentation(actionDescriptor);\n            }\n\n            return null;\n        }\n\n        // remove ApiDescription that will lead to ambiguous action matching.\n        private static Collection<ApiDescription> RemoveInvalidApiDescriptions(Collection<ApiDescription> apiDescriptions)\n        {\n            HashSet<string> duplicateApiDescriptionIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);\n            HashSet<string> visitedApiDescriptionIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);\n\n            foreach (ApiDescription description in apiDescriptions)\n            {\n                string apiDescriptionId = description.ID;\n                if (visitedApiDescriptionIds.Contains(apiDescriptionId))\n                {\n                    duplicateApiDescriptionIds.Add(apiDescriptionId);\n                }\n                else\n                {\n                    visitedApiDescriptionIds.Add(apiDescriptionId);\n                }\n            }\n\n            Collection<ApiDescription> filteredApiDescriptions = new Collection<ApiDescription>();\n            foreach (ApiDescription apiDescription in apiDescriptions)\n            {\n                string apiDescriptionId = apiDescription.ID;\n                if (!duplicateApiDescriptionIds.Contains(apiDescriptionId))\n                {\n                    filteredApiDescriptions.Add(apiDescription);\n                }\n            }\n\n            return filteredApiDescriptions;\n        }\n\n        private static bool MatchRegexConstraint(IHttpRoute route, string parameterName, string parameterValue)\n        {\n            IDictionary<string, object> constraints = route.Constraints;\n            if (constraints != null)\n            {\n                object constraint;\n                if (constraints.TryGetValue(parameterName, out constraint))\n                {\n                    // treat the constraint as a string which represents a Regex.\n                    // note that we don't support custom constraint (IHttpRouteConstraint) because it might rely on the request and some runtime states\n                    string constraintsRule = constraint as string;\n                    if (constraintsRule != null)\n                    {\n                        string constraintsRegEx = \"^(\" + constraintsRule + \")$\";\n                        return parameterValue != null && Regex.IsMatch(parameterValue, constraintsRegEx, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);\n                    }\n                }\n            }\n\n            return true;\n        }\n\n        private static HttpActionBinding GetActionBinding(HttpActionDescriptor actionDescriptor)\n        {\n            HttpControllerDescriptor controllerDescriptor = actionDescriptor.ControllerDescriptor;\n            if (controllerDescriptor == null)\n            {\n                return null;\n            }\n\n            ServicesContainer controllerServices = controllerDescriptor.Configuration.Services;\n            IActionValueBinder actionValueBinder = controllerServices.GetActionValueBinder();\n            HttpActionBinding actionBinding = actionValueBinder != null ? actionValueBinder.GetBinding(actionDescriptor) : null;\n            return actionBinding;\n        }\n\n        private sealed class ApiDescriptionComparer : IEqualityComparer<ApiDescription>\n        {\n            public bool Equals(ApiDescription x, ApiDescription y)\n            {\n                return String.Equals(x.ID, y.ID, StringComparison.OrdinalIgnoreCase);\n            }\n\n            public int GetHashCode(ApiDescription obj)\n            {\n                return obj.ID.ToUpperInvariant().GetHashCode();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Description/ApiExplorerSettingsAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Description\n{\n    /// <summary>\n    /// This attribute can be used on the controllers and actions to influence the behavior of <see cref=\"ApiExplorer\"/>.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]\n    public sealed class ApiExplorerSettingsAttribute : Attribute\n    {\n        /// <summary>\n        /// Gets or sets a value indicating whether to exclude the controller or action from the ApiDescriptions generated by <see cref=\"ApiExplorer\"/>.\n        /// </summary>\n        /// <value>\n        ///   <c>true</c> if the controller or action should be ignored; otherwise, <c>false</c>.\n        /// </value>\n        public bool IgnoreApi { get; set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Description/ApiParameterDescription.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Internal;\n\nnamespace System.Web.Http.Description\n{\n    /// <summary>\n    /// Describes a parameter on the API defined by relative URI path and HTTP method.\n    /// </summary>\n    public class ApiParameterDescription\n    {\n        /// <summary>\n        /// Gets or sets the name.\n        /// </summary>\n        /// <value>\n        /// The name.\n        /// </value>\n        public string Name { get; set; }\n\n        /// <summary>\n        /// Gets or sets the documentation.\n        /// </summary>\n        /// <value>\n        /// The documentation.\n        /// </value>\n        public string Documentation { get; set; }\n\n        /// <summary>\n        /// Gets or sets the source of the parameter. It may come from the request URI, request body or other places.\n        /// </summary>\n        /// <value>\n        /// The source.\n        /// </value>\n        public ApiParameterSource Source { get; set; }\n\n        /// <summary>\n        /// Gets or sets the parameter descriptor.\n        /// </summary>\n        /// <value>\n        /// The parameter descriptor. <see langref=\"null\"/> if (and only if) a <see cref=\"ApiParameterSource.FromUri\"/>\n        /// parameter is declared in route template but unused in the API. Never-<see langref=\"null\"/> for other\n        /// sources.\n        /// </value>\n        /// <remarks>\n        /// For more information on the <see langref=\"null\"/> case, search <see cref=\"ApiExplorer\"/> for \"undeclared\"\n        /// route parameter handling.\n        /// </remarks>\n        public HttpParameterDescriptor ParameterDescriptor { get; set; }\n\n        internal IEnumerable<PropertyInfo> GetBindableProperties()\n        {\n            return GetBindableProperties(ParameterDescriptor.ParameterType);\n        }\n\n        internal bool CanConvertPropertiesFromString()\n        {\n            return GetBindableProperties().All(p => TypeHelper.CanConvertFromString(p.PropertyType));\n        }\n\n        internal static IEnumerable<PropertyInfo> GetBindableProperties(Type type)\n        {\n            return type.GetProperties(BindingFlags.Instance | BindingFlags.Public)\n                       .Where(p => p.GetGetMethod() != null && p.GetSetMethod() != null);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Description/ApiParameterSource.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Description\n{\n    /// <summary>\n    /// Describes where the parameter come from.\n    /// </summary>\n    public enum ApiParameterSource\n    {\n        FromUri = 0,\n        FromBody,\n        Unknown\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Description/IApiExplorer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\n\nnamespace System.Web.Http.Description\n{\n    /// <summary>\n    /// Defines the interface for getting a collection of <see cref=\"ApiDescription\"/>.\n    /// </summary>\n    public interface IApiExplorer\n    {\n        /// <summary>\n        /// Gets the API descriptions.\n        /// </summary>\n        Collection<ApiDescription> ApiDescriptions { get; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Description/IDocumentationProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.Description\n{\n    /// <summary>\n    /// Defines the provider responsible for documenting the service.\n    /// </summary>\n    public interface IDocumentationProvider\n    {\n        /// <summary>\n        /// Gets the documentation based on <see cref=\"HttpControllerDescriptor\"/>.\n        /// </summary>\n        /// <param name=\"controllerDescriptor\">The controller descriptor.</param>\n        /// <returns>Documentation for the controller.</returns>\n        string GetDocumentation(HttpControllerDescriptor controllerDescriptor);\n\n        /// <summary>\n        /// Gets the documentation based on <see cref=\"HttpActionDescriptor\"/>.\n        /// </summary>\n        /// <param name=\"actionDescriptor\">The action descriptor.</param>\n        /// <returns>Documentation for the action.</returns>\n        string GetDocumentation(HttpActionDescriptor actionDescriptor);\n\n        /// <summary>\n        /// Gets the documentation based on <see cref=\"HttpParameterDescriptor\"/>.\n        /// </summary>\n        /// <param name=\"parameterDescriptor\">The parameter descriptor.</param>\n        /// <returns>Documentation for the parameter.</returns>\n        string GetDocumentation(HttpParameterDescriptor parameterDescriptor);\n\n        /// <summary>\n        /// Gets the response documentation based on <see cref=\"HttpActionDescriptor\"/>.\n        /// </summary>\n        /// <param name=\"actionDescriptor\">The action descriptor.</param>\n        /// <returns>Documentation for the action response.</returns>\n        string GetResponseDocumentation(HttpActionDescriptor actionDescriptor);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Description/ResponseDescription.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Description\n{\n    /// <summary>\n    /// Describes the API response.\n    /// </summary>\n    public class ResponseDescription\n    {\n        /// <summary>\n        /// Gets or sets the declared response type.\n        /// </summary>\n        public Type DeclaredType { get; set; }\n\n        /// <summary>\n        /// Gets or sets the actual response type.\n        /// </summary>\n        public Type ResponseType { get; set; }\n\n        /// <summary>\n        /// Gets or sets the response documentation.\n        /// </summary>\n        public string Documentation { get; set; }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http/Description/ResponseTypeAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Description\n{\n    /// <summary>\n    /// Use this to specify the entity type returned by an action when the declared return type\n    /// is <see cref=\"System.Net.Http.HttpResponseMessage\"/> or <see cref=\"IHttpActionResult\"/>.\n    /// The <see cref=\"ResponseType\"/> will be read by <see cref=\"ApiExplorer\"/> when generating <see cref=\"ApiDescription\"/>.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]\n    public sealed class ResponseTypeAttribute : Attribute\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"ResponseTypeAttribute\"/> class.\n        /// </summary>\n        /// <param name=\"responseType\">The response type.</param>\n        public ResponseTypeAttribute(Type responseType)\n        {\n            ResponseType = responseType;\n        }\n\n        /// <summary>\n        /// Gets the response type.\n        /// </summary>\n        public Type ResponseType { get; private set; }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http/Dispatcher/DefaultAssembliesResolver.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Reflection;\n\nnamespace System.Web.Http.Dispatcher\n{\n    /// <summary>\n    /// Provides an implementation of <see cref=\"IAssembliesResolver\"/> with no external dependencies.\n    /// </summary>\n    public class DefaultAssembliesResolver : IAssembliesResolver\n    {\n        /// <summary>\n        /// Returns a list of assemblies available for the application.\n        /// </summary>\n        /// <returns>A <see cref=\"Collection{Assembly}\"/> of assemblies.</returns>\n        public virtual ICollection<Assembly> GetAssemblies()\n        {\n            return AppDomain.CurrentDomain.GetAssemblies().ToList();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Dispatcher/DefaultHttpControllerActivator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Internal;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.Dispatcher\n{\n    /// <summary>\n    /// Default implementation of an <see cref=\"IHttpControllerActivator\"/>.\n    /// A different implementation can be registered via the <see cref=\"T:System.Web.Http.Services.DependencyResolver\"/>.\n    /// We optimize for the case where we have an <see cref=\"Controllers.ApiControllerActionInvoker\"/> \n    /// instance per <see cref=\"HttpControllerDescriptor\"/> instance but can support cases where there are\n    /// many <see cref=\"HttpControllerDescriptor\"/> instances for one <see cref=\"System.Web.Http.Controllers.ApiControllerActionInvoker\"/> \n    /// as well. In the latter case the lookup is slightly slower because it goes through the \n    /// <see cref=\"P:HttpControllerDescriptor.Properties\"/> dictionary.\n    /// </summary>\n    public class DefaultHttpControllerActivator : IHttpControllerActivator\n    {\n        private Tuple<HttpControllerDescriptor, Func<IHttpController>> _fastCache;\n        private object _cacheKey = new object();\n\n        /// <summary>\n        /// Creates the <see cref=\"IHttpController\"/> specified by <paramref name=\"controllerType\"/> using the given <paramref name=\"request\"/>\n        /// </summary>\n        /// <param name=\"request\">The request message.</param>\n        /// <param name=\"controllerType\">Type of the controller.</param>\n        /// <param name=\"controllerDescriptor\">The controller descriptor</param>\n        /// <returns>An instance of type <paramref name=\"controllerType\"/>.</returns>\n        public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            if (controllerDescriptor == null)\n            {\n                throw Error.ArgumentNull(\"controllerDescriptor\");\n            }\n\n            if (controllerType == null)\n            {\n                throw Error.ArgumentNull(\"controllerType\");\n            }\n\n            try\n            {\n                Func<IHttpController> activator;\n\n                // First check in the local fast cache and if not a match then look in the broader \n                // HttpControllerDescriptor.Properties cache\n                if (_fastCache == null)\n                {\n                    IHttpController controller = GetInstanceOrActivator(request, controllerType, out activator);\n                    if (controller != null)\n                    {\n                        // we have a controller registered with the dependency resolver for this controller type\n                        return controller;\n                    }\n                    else\n                    {\n                        Tuple<HttpControllerDescriptor, Func<IHttpController>> cacheItem = Tuple.Create(controllerDescriptor, activator);\n                        Interlocked.CompareExchange(ref _fastCache, cacheItem, null);\n                    }\n                }\n                else if (_fastCache.Item1 == controllerDescriptor)\n                {\n                    // If the key matches and we already have the delegate for creating an instance.\n                    activator = _fastCache.Item2;\n                }\n                else\n                {\n                    // If the key doesn't match then lookup/create delegate in the HttpControllerDescriptor.Properties for\n                    // that HttpControllerDescriptor instance\n                    object value;\n                    if (controllerDescriptor.Properties.TryGetValue(_cacheKey, out value))\n                    {\n                        activator = (Func<IHttpController>)value;\n                    }\n                    else\n                    {\n                        IHttpController controller = GetInstanceOrActivator(request, controllerType, out activator);\n                        if (controller != null)\n                        {\n                            // we have a controller registered with the dependency resolver for this controller type\n                            return controller;\n                        }\n                        else\n                        {\n                            controllerDescriptor.Properties.TryAdd(_cacheKey, activator);\n                        }\n                    }\n                }\n\n                return activator();\n            }\n            catch (Exception ex)\n            {\n                throw Error.InvalidOperation(ex, SRResources.DefaultControllerFactory_ErrorCreatingController, controllerType.Name);\n            }\n        }\n\n        // Returns the controller instance from the dependency resolver if there is one registered\n        // else returns the activator that calls the default ctor for the give controllerType.\n        private static IHttpController GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, out Func<IHttpController> activator)\n        {\n            Contract.Assert(request != null);\n            Contract.Assert(controllerType != null);\n\n            // If dependency resolver returns controller object then use it.\n            IHttpController instance = (IHttpController)request.GetDependencyScope().GetService(controllerType);\n            if (instance != null)\n            {\n                activator = null;\n                return instance;\n            }\n\n            // Otherwise create a delegate for creating a new instance of the type\n            activator = TypeActivator.Create<IHttpController>(controllerType);\n            return null;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Dispatcher/DefaultHttpControllerSelector.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Http;\nusing System.Text;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Routing;\n\nnamespace System.Web.Http.Dispatcher\n{\n    /// <summary>\n    /// Default <see cref=\"IHttpControllerSelector\"/> instance for choosing a <see cref=\"HttpControllerDescriptor\"/> given a <see cref=\"HttpRequestMessage\"/>\n    /// A different implementation can be registered via the <see cref=\"HttpConfiguration.Services\"/>.\n    /// </summary>\n    public class DefaultHttpControllerSelector : IHttpControllerSelector\n    {\n        public static readonly string ControllerSuffix = \"Controller\";\n\n        private const string ControllerKey = \"controller\";\n\n        private readonly HttpConfiguration _configuration;\n        private readonly HttpControllerTypeCache _controllerTypeCache;\n        private readonly Lazy<ConcurrentDictionary<string, HttpControllerDescriptor>> _controllerInfoCache;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"DefaultHttpControllerSelector\"/> class.\n        /// </summary>\n        /// <param name=\"configuration\">The configuration.</param>\n        public DefaultHttpControllerSelector(HttpConfiguration configuration)\n        {\n            if (configuration == null)\n            {\n                throw Error.ArgumentNull(\"configuration\");\n            }\n\n            _controllerInfoCache = new Lazy<ConcurrentDictionary<string, HttpControllerDescriptor>>(InitializeControllerInfoCache);\n            _configuration = configuration;\n            _controllerTypeCache = new HttpControllerTypeCache(_configuration);\n        }\n\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"Caller is responsible for disposing of response instance.\")]\n        public virtual HttpControllerDescriptor SelectController(HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            IHttpRouteData routeData = request.GetRouteData();\n            HttpControllerDescriptor controllerDescriptor;\n            if (routeData != null)\n            {   \n                controllerDescriptor = GetDirectRouteController(routeData);\n                if (controllerDescriptor != null)\n                {\n                    return controllerDescriptor;\n                }                \n            }\n\n            string controllerName = GetControllerName(request);\n            if (String.IsNullOrEmpty(controllerName))\n            {\n                throw new HttpResponseException(request.CreateErrorResponse(\n                    HttpStatusCode.NotFound,\n                    Error.Format(SRResources.ResourceNotFound, request.RequestUri),\n                    Error.Format(SRResources.ControllerNameNotFound, request.RequestUri)));\n            }\n\n            if (_controllerInfoCache.Value.TryGetValue(controllerName, out controllerDescriptor))\n            {\n                return controllerDescriptor;\n            }\n\n            ICollection<Type> matchingTypes = _controllerTypeCache.GetControllerTypes(controllerName);\n\n            // ControllerInfoCache is already initialized.\n            Contract.Assert(matchingTypes.Count != 1);\n\n            if (matchingTypes.Count == 0)\n            {\n                // no matching types\n                throw new HttpResponseException(request.CreateErrorResponse(\n                    HttpStatusCode.NotFound,\n                    Error.Format(SRResources.ResourceNotFound, request.RequestUri),\n                    Error.Format(SRResources.DefaultControllerFactory_ControllerNameNotFound, controllerName)));\n            }\n            else\n            {\n                // multiple matching types\n                throw CreateAmbiguousControllerException(request.GetRouteData().Route, controllerName, matchingTypes);\n            }\n        }\n\n        public virtual IDictionary<string, HttpControllerDescriptor> GetControllerMapping()\n        {\n            return _controllerInfoCache.Value.ToDictionary(c => c.Key, c => c.Value, StringComparer.OrdinalIgnoreCase);\n        }\n\n        public virtual string GetControllerName(HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            IHttpRouteData routeData = request.GetRouteData();\n            if (routeData == null)\n            {\n                return null;\n            }\n\n            // Look up controller in route data\n            string controllerName = null;\n            routeData.Values.TryGetValue(ControllerKey, out controllerName);\n            return controllerName;\n        }\n\n        // If routeData is from an attribute route, get the controller that can handle it. \n        // Else return null. Throws an exception if multiple controllers match\n        private static HttpControllerDescriptor GetDirectRouteController(IHttpRouteData routeData)\n        {\n            CandidateAction[] candidates = routeData.GetDirectRouteCandidates();\n            if (candidates != null)\n            {\n                // Set the controller descriptor for the first action descriptor\n                Contract.Assert(candidates.Length > 0);\n                Contract.Assert(candidates[0].ActionDescriptor != null);\n\n                HttpControllerDescriptor controllerDescriptor = candidates[0].ActionDescriptor.ControllerDescriptor;\n\n                // Check that all other candidate action descriptors share the same controller descriptor\n                for (int i = 1; i < candidates.Length; i++)\n                {\n                    CandidateAction candidate = candidates[i];\n                    if (candidate.ActionDescriptor.ControllerDescriptor != controllerDescriptor)\n                    {\n                        // We've found an ambiguity (multiple controllers matched)\n                        throw CreateDirectRouteAmbiguousControllerException(candidates);\n                    }\n                }\n\n                return controllerDescriptor;\n            }\n\n            return null;\n        }\n\n        private static Exception CreateDirectRouteAmbiguousControllerException(CandidateAction[] candidates)\n        {\n            Contract.Assert(candidates != null);\n            Contract.Assert(candidates.Length > 1);\n\n            HashSet<Type> matchingTypes = new HashSet<Type>();\n            for (int i = 0; i < candidates.Length; i++)\n            {\n                matchingTypes.Add(candidates[i].ActionDescriptor.ControllerDescriptor.ControllerType);\n            }\n\n            // we need to generate an exception containing all the controller types\n            StringBuilder typeList = new StringBuilder();\n            foreach (Type matchedType in matchingTypes)\n            {\n                typeList.AppendLine();\n                typeList.Append(matchedType.FullName);\n            }\n\n            return Error.InvalidOperation(SRResources.DirectRoute_AmbiguousController, typeList, Environment.NewLine);\n        }\n\n        private static Exception CreateAmbiguousControllerException(IHttpRoute route, string controllerName, ICollection<Type> matchingTypes)\n        {\n            Contract.Assert(route != null);\n            Contract.Assert(controllerName != null);\n            Contract.Assert(matchingTypes != null);\n\n            // Generate an exception containing all the controller types\n            StringBuilder typeList = new StringBuilder();\n            foreach (Type matchedType in matchingTypes)\n            {\n                typeList.AppendLine();\n                typeList.Append(matchedType.FullName);\n            }\n\n            string errorMessage = Error.Format(SRResources.DefaultControllerFactory_ControllerNameAmbiguous_WithRouteTemplate, controllerName, route.RouteTemplate, typeList, Environment.NewLine);\n            return new InvalidOperationException(errorMessage);\n        }\n\n        private ConcurrentDictionary<string, HttpControllerDescriptor> InitializeControllerInfoCache()\n        {\n            var result = new ConcurrentDictionary<string, HttpControllerDescriptor>(StringComparer.OrdinalIgnoreCase);\n            var duplicateControllers = new HashSet<string>();\n            Dictionary<string, ILookup<string, Type>> controllerTypeGroups = _controllerTypeCache.Cache;\n\n            foreach (KeyValuePair<string, ILookup<string, Type>> controllerTypeGroup in controllerTypeGroups)\n            {\n                string controllerName = controllerTypeGroup.Key;\n\n                foreach (IGrouping<string, Type> controllerTypesGroupedByNs in controllerTypeGroup.Value)\n                {\n                    foreach (Type controllerType in controllerTypesGroupedByNs)\n                    {\n                        if (result.Keys.Contains(controllerName))\n                        {\n                            duplicateControllers.Add(controllerName);\n                            break;\n                        }\n                        else\n                        {\n                            result.TryAdd(controllerName, new HttpControllerDescriptor(_configuration, controllerName, controllerType));\n                        }\n                    }\n                }\n            }\n\n            foreach (string duplicateController in duplicateControllers)\n            {\n                HttpControllerDescriptor descriptor;\n                result.TryRemove(duplicateController, out descriptor);\n            }\n\n            return result;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Dispatcher/DefaultHttpControllerTypeResolver.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing System.Reflection;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.Dispatcher\n{\n    /// <summary>\n    /// Provides an implementation of <see cref=\"IHttpControllerTypeResolver\"/> with no external dependencies.\n    /// </summary>\n    public class DefaultHttpControllerTypeResolver : IHttpControllerTypeResolver\n    {\n        private readonly Predicate<Type> _isControllerTypePredicate;\n        private Func<Assembly, Type[]> _getTypesFunc = GetTypes;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"DefaultHttpControllerTypeResolver\"/> with a default\n        /// filter for detecting controller types.\n        /// </summary>\n        public DefaultHttpControllerTypeResolver()\n            : this(IsControllerType)\n        {\n        }\n\n        /// <summary>\n        /// Creates a new <see cref=\"DefaultHttpControllerTypeResolver\"/> instance using a predicate to filter controller types.\n        /// </summary>\n        /// <param name=\"predicate\">The predicate.</param>\n        public DefaultHttpControllerTypeResolver(Predicate<Type> predicate)\n        {\n            if (predicate == null)\n            {\n                throw Error.ArgumentNull(\"predicate\");\n            }\n\n            _isControllerTypePredicate = predicate;\n        }\n\n        protected internal virtual Predicate<Type> IsControllerTypePredicate\n        {\n            get { return _isControllerTypePredicate; }\n        }\n\n        internal static bool IsControllerType(Type t)\n        {\n            Contract.Assert(t != null);\n            return\n                t != null &&\n                t.IsClass &&\n                t.IsVisible &&\n                !t.IsAbstract &&\n                typeof(IHttpController).IsAssignableFrom(t) &&\n                HasValidControllerName(t);\n        }\n\n        /// <summary>\n        /// Returns a list of controllers available for the application.\n        /// </summary>\n        /// <returns>An <see cref=\"ICollection{Type}\"/> of controllers.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Catching all exceptions in this case is the right to do.\")]\n        public virtual ICollection<Type> GetControllerTypes(IAssembliesResolver assembliesResolver)\n        {\n            if (assembliesResolver == null)\n            {\n                throw Error.ArgumentNull(\"assembliesResolver\");\n            }\n\n            List<Type> result = new List<Type>();\n\n            // Go through all assemblies referenced by the application and search for types matching a predicate\n            ICollection<Assembly> assemblies = assembliesResolver.GetAssemblies();\n            foreach (Assembly assembly in assemblies)\n            {\n                Type[] exportedTypes = null;\n                if (assembly == null || assembly.IsDynamic)\n                {\n                    // can't call GetTypes on a null (or dynamic?) assembly\n                    continue;\n                }\n\n                try\n                {\n                    exportedTypes = _getTypesFunc(assembly);\n                }\n                catch (ReflectionTypeLoadException ex)\n                {\n                    exportedTypes = ex.Types;\n                }\n                catch\n                {\n                    // We deliberately ignore all exceptions when building the cache. If \n                    // a controller type is not found then we will respond later with a 404.\n                    // However, until then we don't know whether an exception at all will\n                    // have an impact on finding a controller.\n                    continue;\n                }\n\n                if (exportedTypes != null)\n                {\n                    result.AddRange(exportedTypes.Where(x => TypeIsVisible(x) && IsControllerTypePredicate(x)));\n                }\n            }\n\n            return result;\n        }\n\n        /// <summary>\n        /// Returns an array of <see cref=\"Type\"/>s in the given <paramref name=\"assembly\"/>.\n        /// </summary>\n        /// <remarks>Available separately only to allow a tracing override.</remarks>\n        /// <param name=\"assembly\">The <see cref=\"Assembly\"/> to check.</param>\n        /// <returns>Array of <see cref=\"Type\"/>s types in the assembly.</returns>\n        internal static Type[] GetTypes(Assembly assembly)\n        {\n            return assembly.GetTypes();\n        }\n\n        /// <summary>\n        /// We match if type name ends with \"Controller\" and that is not the only part of the \n        /// name (i.e it can't be just \"Controller\"). The reason is that the route name has to \n        /// be a non-empty prefix of the controller type name.\n        /// </summary>\n        internal static bool HasValidControllerName(Type controllerType)\n        {\n            Contract.Assert(controllerType != null);\n            string controllerSuffix = DefaultHttpControllerSelector.ControllerSuffix;\n            return controllerType.Name.Length > controllerSuffix.Length && controllerType.Name.EndsWith(controllerSuffix, StringComparison.OrdinalIgnoreCase);\n        }\n\n        internal void SetGetTypesFunc(Func<Assembly, Type[]> getTypesFunc)\n        {\n            _getTypesFunc = getTypesFunc;\n        }\n\n        private static bool TypeIsVisible(Type type)\n        {\n            return (type != null && type.IsVisible);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Dispatcher/HttpControllerDispatcher.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.Net.Http;\nusing System.Runtime.ExceptionServices;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Routing;\n\nnamespace System.Web.Http.Dispatcher\n{\n    /// <summary>\n    /// Dispatches an incoming <see cref=\"HttpRequestMessage\"/> to an <see cref=\"IHttpController\"/> implementation for processing.\n    /// </summary>\n    public class HttpControllerDispatcher : HttpMessageHandler\n    {\n        private readonly HttpConfiguration _configuration;\n\n        private IExceptionLogger _exceptionLogger;\n        private IExceptionHandler _exceptionHandler;\n        private IHttpControllerSelector _controllerSelector;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpControllerDispatcher\"/> class.\n        /// </summary>\n        public HttpControllerDispatcher(HttpConfiguration configuration)\n        {\n            if (configuration == null)\n            {\n                throw Error.ArgumentNull(\"configuration\");\n            }\n\n            _configuration = configuration;\n        }\n\n        /// <summary>\n        /// Gets the <see cref=\"HttpConfiguration\"/>.\n        /// </summary>\n        public HttpConfiguration Configuration\n        {\n            get { return _configuration; }\n        }\n\n        /// <remarks>This property is internal and settable only for unit testing purposes.</remarks>\n        internal IExceptionLogger ExceptionLogger\n        {\n            get\n            {\n                if (_exceptionLogger == null)\n                {\n                    _exceptionLogger = ExceptionServices.GetLogger(_configuration);\n                }\n\n                return _exceptionLogger;\n            }\n            set\n            {\n                _exceptionLogger = value;\n            }\n        }\n\n        /// <remarks>This property is internal and settable only for unit testing purposes.</remarks>\n        internal IExceptionHandler ExceptionHandler\n        {\n            get\n            {\n                if (_exceptionHandler == null)\n                {\n                    _exceptionHandler = ExceptionServices.GetHandler(_configuration);\n                }\n\n                return _exceptionHandler;\n            }\n            set\n            {\n                _exceptionHandler = value;\n            }\n        }\n\n        private IHttpControllerSelector ControllerSelector\n        {\n            get\n            {\n                if (_controllerSelector == null)\n                {\n                    _controllerSelector = _configuration.Services.GetHttpControllerSelector();\n                }\n\n                return _controllerSelector;\n            }\n        }\n\n        /// <summary>\n        /// Dispatches an incoming <see cref=\"HttpRequestMessage\"/> to an <see cref=\"IHttpController\"/>.\n        /// </summary>\n        /// <param name=\"request\">The request to dispatch</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A <see cref=\"Task{HttpResponseMessage}\"/> representing the ongoing operation.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We report the error in the HTTP response.\")]\n        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            ExceptionDispatchInfo exceptionInfo;\n            HttpControllerContext controllerContext = null;\n\n            try\n            {\n                HttpControllerDescriptor controllerDescriptor = ControllerSelector.SelectController(request);\n                if (controllerDescriptor == null)\n                {\n                    return request.CreateErrorResponse(\n                        HttpStatusCode.NotFound,\n                        Error.Format(SRResources.ResourceNotFound, request.RequestUri),\n                        SRResources.NoControllerSelected);\n                }\n\n                IHttpController controller = controllerDescriptor.CreateController(request);\n                if (controller == null)\n                {\n                    return request.CreateErrorResponse(\n                        HttpStatusCode.NotFound,\n                        Error.Format(SRResources.ResourceNotFound, request.RequestUri),\n                        SRResources.NoControllerCreated);\n                }\n\n                controllerContext = CreateControllerContext(request, controllerDescriptor, controller);\n                return await controller.ExecuteAsync(controllerContext, cancellationToken);\n            }\n            catch (OperationCanceledException)\n            {\n                // Propogate the canceled task without calling exception loggers or handlers.\n                throw;\n            }\n            catch (HttpResponseException httpResponseException)\n            {\n                return httpResponseException.Response;\n            }\n            catch (Exception exception)\n            {\n                exceptionInfo = ExceptionDispatchInfo.Capture(exception);\n            }\n\n            Debug.Assert(exceptionInfo.SourceException != null);\n\n            ExceptionContext exceptionContext = new ExceptionContext(\n                exceptionInfo.SourceException,\n                ExceptionCatchBlocks.HttpControllerDispatcher,\n                request)\n                {\n                    ControllerContext = controllerContext,\n                };\n\n            await ExceptionLogger.LogAsync(exceptionContext, cancellationToken);\n            HttpResponseMessage response = await ExceptionHandler.HandleAsync(exceptionContext, cancellationToken);\n\n            if (response == null)\n            {\n                exceptionInfo.Throw();\n            }\n\n            return response;\n        }\n\n        private static HttpControllerContext CreateControllerContext(\n            HttpRequestMessage request, \n            HttpControllerDescriptor controllerDescriptor,\n            IHttpController controller)\n        {\n            Contract.Assert(request != null);\n            Contract.Assert(controllerDescriptor != null);\n            Contract.Assert(controller != null);\n\n            HttpConfiguration controllerConfiguration = controllerDescriptor.Configuration;\n\n            // Set the controller configuration on the request properties\n            HttpConfiguration requestConfig = request.GetConfiguration();\n            if (requestConfig == null)\n            {\n                request.SetConfiguration(controllerConfiguration);\n            }\n            else\n            {\n                if (requestConfig != controllerConfiguration)\n                {\n                    request.SetConfiguration(controllerConfiguration);\n                }\n            }\n\n            HttpRequestContext requestContext = request.GetRequestContext();\n\n            // if the host doesn't create the context we will fallback to creating it.\n            if (requestContext == null)\n            {\n                requestContext = new RequestBackedHttpRequestContext(request)\n                {\n                    // we are caching controller configuration to support per controller configuration.\n                    Configuration = controllerConfiguration,\n                };\n\n                // if the host did not set a request context we will also set it back to the request.\n                request.SetRequestContext(requestContext);\n            }\n\n            return new HttpControllerContext(requestContext, request, controllerDescriptor, controller);\n        }\n\n        private static HttpConfiguration EnsureNonNull(HttpConfiguration configuration)\n        {\n            if (configuration == null)\n            {\n                throw Error.ArgumentNull(\"configuration\");\n            }\n\n            return configuration;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Dispatcher/HttpControllerTypeCache.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace System.Web.Http.Dispatcher\n{\n    /// <summary>\n    /// Manages a cache of <see cref=\"System.Web.Http.Controllers.IHttpController\"/> types detected in the system.\n    /// </summary>\n    internal sealed class HttpControllerTypeCache\n    {\n        private readonly HttpConfiguration _configuration;\n        private readonly Lazy<Dictionary<string, ILookup<string, Type>>> _cache;\n\n        public HttpControllerTypeCache(HttpConfiguration configuration)\n        {\n            if (configuration == null)\n            {\n                throw Error.ArgumentNull(\"configuration\");\n            }\n\n            _configuration = configuration;\n            _cache = new Lazy<Dictionary<string, ILookup<string, Type>>>(InitializeCache);\n        }\n\n        internal Dictionary<string, ILookup<string, Type>> Cache\n        {\n            get { return _cache.Value; }\n        }\n\n        public ICollection<Type> GetControllerTypes(string controllerName)\n        {\n            if (String.IsNullOrEmpty(controllerName))\n            {\n                throw Error.ArgumentNullOrEmpty(\"controllerName\");\n            }\n\n            HashSet<Type> matchingTypes = new HashSet<Type>();\n\n            ILookup<string, Type> namespaceLookup;\n            if (_cache.Value.TryGetValue(controllerName, out namespaceLookup))\n            {\n                foreach (var namespaceGroup in namespaceLookup)\n                {\n                    matchingTypes.UnionWith(namespaceGroup);\n                }\n            }\n\n            return matchingTypes;\n        }\n\n        private Dictionary<string, ILookup<string, Type>> InitializeCache()\n        {\n            IAssembliesResolver assembliesResolver = _configuration.Services.GetAssembliesResolver();\n            IHttpControllerTypeResolver controllersResolver = _configuration.Services.GetHttpControllerTypeResolver();\n\n            ICollection<Type> controllerTypes = controllersResolver.GetControllerTypes(assembliesResolver);\n            var groupedByName = controllerTypes.GroupBy(\n                t => t.Name.Substring(0, t.Name.Length - DefaultHttpControllerSelector.ControllerSuffix.Length),\n                StringComparer.OrdinalIgnoreCase);\n\n            return groupedByName.ToDictionary(\n                g => g.Key,\n                g => g.ToLookup(t => t.Namespace ?? String.Empty, StringComparer.OrdinalIgnoreCase),\n                StringComparer.OrdinalIgnoreCase);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Dispatcher/HttpRoutingDispatcher.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Routing;\n\nnamespace System.Web.Http.Dispatcher\n{\n    /// <summary>\n    /// This class is the default endpoint message handler which examines the <see cref=\"IHttpRoute\"/>\n    /// of the matched route, and chooses which message handler to call. If <see cref=\"IHttpRoute.Handler\"/>\n    /// is <c>null</c>, then it delegates to <see cref=\"HttpControllerDispatcher\"/>.\n    /// </summary>\n    public class HttpRoutingDispatcher : HttpMessageHandler\n    {\n        private readonly HttpConfiguration _configuration;\n        private readonly HttpMessageInvoker _defaultInvoker;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpRoutingDispatcher\"/> class,\n        /// using the provided <see cref=\"HttpConfiguration\"/> and <see cref=\"HttpControllerDispatcher\"/>\n        /// as the default handler.\n        /// </summary>\n        /// <param name=\"configuration\">The server configuration.</param>\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"HttpControllerDispatcher does not require disposal\")]\n        public HttpRoutingDispatcher(HttpConfiguration configuration)\n            : this(configuration, new HttpControllerDispatcher(configuration))\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpRoutingDispatcher\"/> class,\n        /// using the provided <see cref=\"HttpConfiguration\"/> and <see cref=\"HttpMessageHandler\"/>.\n        /// </summary>\n        /// <param name=\"configuration\">The server configuration.</param>\n        /// <param name=\"defaultHandler\">The default handler to use when the <see cref=\"IHttpRoute\"/> has no <see cref=\"IHttpRoute.Handler\"/>.</param>\n        public HttpRoutingDispatcher(HttpConfiguration configuration, HttpMessageHandler defaultHandler)\n        {\n            if (configuration == null)\n            {\n                throw Error.ArgumentNull(\"configuration\");\n            }\n            if (defaultHandler == null)\n            {\n                throw Error.ArgumentNull(\"defaultHandler\");\n            }\n\n            _configuration = configuration;\n            _defaultInvoker = new HttpMessageInvoker(defaultHandler);\n        }\n\n        /// <inheritdoc/>\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"The Web API framework will dispose of the response after sending it\")]\n        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n        {\n            // Lookup route data, or if not found as a request property then we look it up in the route table\n            IHttpRouteData routeData = request.GetRouteData();\n            if (routeData == null)\n            {\n                routeData = _configuration.Routes.GetRouteData(request);\n                if (routeData != null)\n                {\n                    request.SetRouteData(routeData);\n                }\n            }\n\n            if (routeData == null || (routeData.Route != null && routeData.Route.Handler is StopRoutingHandler))\n            {\n                request.Properties.Add(HttpPropertyKeys.NoRouteMatched, true);\n                return Task.FromResult(request.CreateErrorResponse(\n                    HttpStatusCode.NotFound,\n                    Error.Format(SRResources.ResourceNotFound, request.RequestUri),\n                    SRResources.NoRouteData));\n            }\n\n            routeData.RemoveOptionalRoutingParameters();\n\n            // routeData.Route could be null if user adds a custom route that derives from System.Web.Routing.Route explicitly \n            // and add that to the RouteCollection in the web hosted case\n            var invoker = (routeData.Route == null || routeData.Route.Handler == null) ?\n                _defaultInvoker : new HttpMessageInvoker(routeData.Route.Handler, disposeHandler: false);\n            return invoker.SendAsync(request, cancellationToken);\n        }       \n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Dispatcher/IAssembliesResolver.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Reflection;\n\nnamespace System.Web.Http.Dispatcher\n{\n    /// <summary>\n    /// Provides an abstraction for managing the assemblies of an application. A different\n    /// implementation can be registered via the <see cref=\"T:System.Web.Http.Services.DependencyResolver\"/>.\n    /// </summary>\n    public interface IAssembliesResolver\n    {\n        /// <summary>\n        /// Returns a list of assemblies available for the application.\n        /// </summary>\n        /// <returns>An <see cref=\"ICollection{Assembly}\"/> of assemblies.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Justification = \"This is better handled as a method.\")]\n        ICollection<Assembly> GetAssemblies();\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Dispatcher/IHttpControllerActivator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.Dispatcher\n{\n    /// <summary>\n    /// Defines the methods that are required for an <see cref=\"IHttpControllerActivator\"/>.\n    /// </summary>\n    public interface IHttpControllerActivator\n    {\n        IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Dispatcher/IHttpControllerSelector.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.Dispatcher\n{\n    /// <summary>\n    /// Defines the methods that are required for an <see cref=\"IHttpController\"/> factory.\n    /// </summary>\n    public interface IHttpControllerSelector\n    {\n        /// <summary>\n        /// Selects a <see cref=\"HttpControllerDescriptor\"/> for the given <see cref=\"HttpRequestMessage\"/>.\n        /// </summary>\n        /// <param name=\"request\">The request message.</param>\n        /// <returns>An <see cref=\"HttpControllerDescriptor\"/> instance.</returns>\n        HttpControllerDescriptor SelectController(HttpRequestMessage request);\n\n        /// <summary>\n        /// Returns a map, keyed by controller string, of all <see cref=\"HttpControllerDescriptor\"/> that the selector can select. \n        /// This is primarily called by <see cref=\"System.Web.Http.Description.IApiExplorer\"/> to discover all the possible controllers in the system.\n        /// </summary>\n        /// <returns>A map of all <see cref=\"HttpControllerDescriptor\"/> that the selector can select, or null if the selector does not have a well-defined mapping of <see cref=\"HttpControllerDescriptor\"/>.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Justification = \"This is better handled as a method.\")]\n        IDictionary<string, HttpControllerDescriptor> GetControllerMapping();\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Dispatcher/IHttpControllerTypeResolver.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.Http.Dispatcher\n{\n    /// <summary>\n    /// Provides an abstraction for managing the controller types of an application. A different\n    /// implementation can be registered via the <see cref=\"T:System.Web.Http.Services.DependencyResolver\"/>.\n    /// </summary>\n    public interface IHttpControllerTypeResolver\n    {\n        /// <summary>\n        /// Returns a list of controllers available for the application.\n        /// </summary>\n        /// <returns>An <see cref=\"ICollection{Type}\"/> of controllers.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Justification = \"This is better handled as a method.\")]\n        ICollection<Type> GetControllerTypes(IAssembliesResolver assembliesResolver);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/EmptyReadOnlyDictionary.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\n\nnamespace System.Web.Http\n{\n    internal class EmptyReadOnlyDictionary<TKey, TValue>\n    {\n        private static readonly ReadOnlyDictionary<TKey, TValue> _value = new ReadOnlyDictionary<TKey, TValue>(new Dictionary<TKey, TValue>());\n\n        public static IDictionary<TKey, TValue> Value\n        {\n            get { return _value; }\n        }        \n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ExceptionHandling/CompositeExceptionLogger.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    internal class CompositeExceptionLogger : IExceptionLogger\n    {\n        private readonly IExceptionLogger[] _loggers;\n\n        public CompositeExceptionLogger(params IExceptionLogger[] loggers)\n            : this((IEnumerable<IExceptionLogger>)loggers)\n        {\n        }\n\n        public CompositeExceptionLogger(IEnumerable<IExceptionLogger> loggers)\n        {\n            if (loggers == null)\n            {\n                throw new ArgumentNullException(\"loggers\");\n            }\n\n            _loggers = loggers.ToArray();\n        }\n\n        public IEnumerable<IExceptionLogger> Loggers\n        {\n            get { return _loggers; }\n        }\n\n        public Task LogAsync(ExceptionLoggerContext context, CancellationToken cancellationToken)\n        {\n            List<Task> tasks = new List<Task>();\n\n            Contract.Assert(_loggers != null);\n\n            foreach (IExceptionLogger logger in _loggers)\n            {\n                if (logger == null)\n                {\n                    throw new InvalidOperationException(Error.Format(SRResources.TypeInstanceMustNotBeNull,\n                        typeof(IExceptionLogger).Name));\n                }\n\n                Task task = logger.LogAsync(context, cancellationToken);\n                tasks.Add(task);\n            }\n\n            return Task.WhenAll(tasks);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ExceptionHandling/DefaultExceptionHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Results;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    /// <summary>Provides the default implementation for handling exceptions within Web API.</summary>\n    /// <remarks>\n    /// This class preserves the legacy behavior of catch blocks and is the the default registered IExceptionHandler.\n    /// This default service allows adding the IExceptionHandler service extensibility point without making any\n    /// breaking changes in the default implementation.\n    /// </remarks>\n    internal class DefaultExceptionHandler : IExceptionHandler\n    {\n        public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)\n        {\n            Handle(context);\n            return TaskHelpers.Completed();\n        }\n\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\",\n            Justification = \"We already shipped this code; avoiding even minor breaking changes in error handling.\")]\n        private static void Handle(ExceptionHandlerContext context)\n        {\n            if (context == null)\n            {\n                throw new ArgumentNullException(\"context\");\n            }\n\n            ExceptionContext exceptionContext = context.ExceptionContext;\n            Contract.Assert(exceptionContext != null);\n            Exception exception = exceptionContext.Exception;\n\n            HttpRequestMessage request = exceptionContext.Request;\n\n            if (request == null)\n            {\n                throw new ArgumentException(Error.Format(SRResources.TypePropertyMustNotBeNull,\n                    typeof(ExceptionContext).Name, \"Request\"), \"context\");\n            }\n\n            if (exceptionContext.CatchBlock == ExceptionCatchBlocks.IExceptionFilter)\n            {\n                // The exception filter stage propagates unhandled exceptions by default (when no filter handles the\n                // exception).\n                return;\n            }\n\n            context.Result = new ResponseMessageResult(request.CreateErrorResponse(HttpStatusCode.InternalServerError,\n                exception));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ExceptionHandling/EmptyExceptionHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    /// <summary>\n    /// Represents an exception handler that leaves exceptions unhandled (allowing them to propagate).\n    /// </summary>\n    /// <remarks>\n    /// This class represents the behavior of having no IExceptionHandler service, such as when the registered service\n    /// is removed (Null Object pattern).\n    /// </remarks>\n    internal class EmptyExceptionHandler : IExceptionHandler\n    {\n        public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)\n        {\n            // For exceptions at the top of the call stack, Result will start out non-null (due to\n            // LastChanceExceptionHandler). This class does not force exceptions back to unhandled in such cases, so it\n            // will not not trigger the host-level exception processing, such as the ASP.NET yellow screen.\n            return TaskHelpers.Completed();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ExceptionHandling/ExceptionCatchBlocks.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Batch;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.Filters;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    /// <summary>Provides the catch blocks used within this assembly.</summary>\n    public static class ExceptionCatchBlocks\n    {\n        private static readonly ExceptionContextCatchBlock _httpBatchHandler =\n            new ExceptionContextCatchBlock(typeof(HttpBatchHandler).Name, isTopLevel: false, callsHandler: true);\n        private static readonly ExceptionContextCatchBlock _httpControllerDispatcher =\n            new ExceptionContextCatchBlock(typeof(HttpControllerDispatcher).Name, isTopLevel: false, callsHandler: true);\n        private static readonly ExceptionContextCatchBlock _httpServer =\n            new ExceptionContextCatchBlock(typeof(HttpServer).Name, isTopLevel: true, callsHandler: true);\n        private static readonly ExceptionContextCatchBlock _exceptionFilter =\n            new ExceptionContextCatchBlock(typeof(IExceptionFilter).Name, isTopLevel: false, callsHandler: true);\n\n        /// <summary>Gets the catch block in <see cref=\"HttpBatchHandler\"/>.SendAsync.</summary>\n        public static ExceptionContextCatchBlock HttpBatchHandler\n        {\n            get { return _httpBatchHandler; }\n        }\n\n        /// <summary>Gets the catch block in <see cref=\"HttpControllerDispatcher\"/>.SendAsync.</summary>\n        public static ExceptionContextCatchBlock HttpControllerDispatcher\n        {\n            get { return _httpControllerDispatcher; }\n        }\n\n        /// <summary>Gets the catch block in <see cref=\"HttpServer\"/>.SendAsync</summary>\n        public static ExceptionContextCatchBlock HttpServer\n        {\n            get { return _httpServer; }\n        }\n\n        /// <summary>\n        /// Gets the catch block in <see cref=\"ApiController\"/>.ExecuteAsync when using <see cref=\"IExceptionFilter\"/>.\n        /// </summary>\n        public static ExceptionContextCatchBlock IExceptionFilter\n        {\n            get { return _exceptionFilter; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ExceptionHandling/ExceptionContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    /// <summary>Represents an exception and the contextual data associated with it when it was caught.</summary>\n    public class ExceptionContext\n    {\n        /// <summary>Initializes a new instance of the <see cref=\"ExceptionContext\"/> class.</summary>\n        /// <param name=\"exception\">The exception caught.</param>\n        /// <param name=\"catchBlock\">The catch block where the exception was caught.</param>\n        /// <remarks>This constructor is for unit testing purposes only.</remarks>\n        public ExceptionContext(Exception exception, ExceptionContextCatchBlock catchBlock)\n        {\n            if (exception == null)\n            {\n                throw new ArgumentNullException(\"exception\");\n            }\n\n            Exception = exception;\n\n            if (catchBlock == null)\n            {\n                throw new ArgumentNullException(\"catchBlock\");\n            }\n\n            CatchBlock = catchBlock;\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"ExceptionContext\"/> class using the values provided.\n        /// </summary>\n        /// <param name=\"exception\">The exception caught.</param>\n        /// <param name=\"catchBlock\">The catch block where the exception was caught.</param>\n        /// <param name=\"actionContext\">The action context in which the exception occurred.</param>\n        public ExceptionContext(Exception exception, ExceptionContextCatchBlock catchBlock,\n            HttpActionContext actionContext)\n            : this(exception, catchBlock)\n        {\n            if (actionContext == null)\n            {\n                throw new ArgumentNullException(\"actionContext\");\n            }\n\n            ActionContext = actionContext;\n\n            HttpControllerContext controllerContext = actionContext.ControllerContext;\n\n            if (controllerContext == null)\n            {\n                throw new ArgumentException(Error.Format(SRResources.TypePropertyMustNotBeNull,\n                    typeof(HttpActionContext).Name, \"ControllerContext\"), \"actionContext\");\n            }\n\n            ControllerContext = controllerContext;\n\n            HttpRequestContext requestContext = controllerContext.RequestContext;\n            Contract.Assert(requestContext != null);\n            RequestContext = requestContext;\n\n            HttpRequestMessage request = controllerContext.Request;\n\n            if (request == null)\n            {\n                throw new ArgumentException(Error.Format(SRResources.TypePropertyMustNotBeNull,\n                    typeof(HttpControllerContext).Name, \"Request\"), \"actionContext\");\n            }\n\n            Request = request;\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"ExceptionContext\"/> class using the values provided.\n        /// </summary>\n        /// <param name=\"exception\">The exception caught.</param>\n        /// <param name=\"catchBlock\">The catch block where the exception was caught.</param>\n        /// <param name=\"request\">The request being processed when the exception was caught.</param>\n        public ExceptionContext(Exception exception, ExceptionContextCatchBlock catchBlock, HttpRequestMessage request)\n            : this(exception, catchBlock)\n        {\n            if (request == null)\n            {\n                throw new ArgumentNullException(\"request\");\n            }\n\n            Request = request;\n            RequestContext = request.GetRequestContext();\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"ExceptionContext\"/> class using the values provided.\n        /// </summary>\n        /// <param name=\"exception\">The exception caught.</param>\n        /// <param name=\"catchBlock\">The catch block where the exception was caught.</param>\n        /// <param name=\"request\">The request being processed when the exception was caught.</param>\n        /// <param name=\"response\">The repsonse being returned when the exception was caught.</param>\n        public ExceptionContext(Exception exception, ExceptionContextCatchBlock catchBlock, HttpRequestMessage request,\n            HttpResponseMessage response) : this(exception, catchBlock)\n        {\n            if (request == null)\n            {\n                throw new ArgumentNullException(\"request\");\n            }\n\n            Request = request;\n            RequestContext = request.GetRequestContext();\n\n            if (response == null)\n            {\n                throw new ArgumentNullException(\"response\");\n            }\n\n            Response = response;\n        }\n\n        /// <summary>Gets the exception caught.</summary>\n        public Exception Exception { get; private set; }\n\n        /// <summary>Gets the catch block in which the exception was caught.</summary>\n        public ExceptionContextCatchBlock CatchBlock { get; private set; }\n\n        /// <summary>Gets the request being processed when the exception was caught.</summary>\n        /// <remarks>The setter is for unit testing purposes only.</remarks>\n        public HttpRequestMessage Request { get; set; }\n\n        /// <summary>Gets the request context in which the exception occurred.</summary>\n        /// <remarks>The setter is for unit testing purposes only.</remarks>\n        public HttpRequestContext RequestContext { get; set; }\n\n        /// <summary>Gets the controller context in which the exception occurred, if available.</summary>\n        /// <remarks>\n        /// <para>This property will be <see langword=\"null\"/> in most cases.</para>\n        /// <para>The setter is for unit testing purposes only.</para>\n        /// </remarks>\n        public HttpControllerContext ControllerContext { get; set; }\n\n        /// <summary>Gets the action context in which the exception occurred, if available.</summary>\n        /// <remarks>\n        /// <para>This property will be <see langword=\"null\"/> in most cases.</para>\n        /// <para>The setter is for unit testing purposes only.</para>\n        /// </remarks>\n        public HttpActionContext ActionContext { get; set; }\n\n        /// <summary>Gets the response being sent when the exception was caught.</summary>\n        /// <remarks>\n        /// <para>This property will be <see langword=\"null\"/> in most cases.</para>\n        /// <para>The setter is for unit testing purposes only.</para>\n        /// </remarks>\n        public HttpResponseMessage Response { get; set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ExceptionHandling/ExceptionContextCatchBlock.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    /// <summary>Represents the catch block location for an <see cref=\"ExceptionContext\"/>.</summary>\n    [DebuggerDisplay(\"Name: {Name}, IsTopLevel: {IsTopLevel}\")]\n    public class ExceptionContextCatchBlock\n    {\n        private readonly string _name;\n        private readonly bool _isTopLevel;\n        private readonly bool _callsHandler;\n\n        /// <summary>\n        /// Initializes a new instance of <see cref=\"ExceptionContextCatchBlock\"/> with the values provided.\n        /// </summary>\n        /// <param name=\"name\">The label for the catch block where the exception was caught.</param>\n        /// <param name=\"isTopLevel\">\n        /// A value indicating whether the catch block where the exception was caught is the last one before the host.\n        /// </param>\n        /// <param name=\"callsHandler\">\n        /// A value indicating whether exceptions in the catch block can be handled after they are logged.\n        /// </param>\n        /// <remarks>\n        /// To compare an exception catch block with a well-known value, see classes like\n        /// <see cref=\"ExceptionCatchBlocks\"/> for the specific objects to use.\n        /// This constructor is only intended for use within static classes that define such well-known catch blocks.\n        /// </remarks>\n        public ExceptionContextCatchBlock(string name, bool isTopLevel, bool callsHandler)\n        {\n            if (name == null)\n            {\n                throw new ArgumentNullException(\"name\");\n            }\n\n            _name = name;\n            _isTopLevel = isTopLevel;\n            _callsHandler = callsHandler;\n        }\n\n        /// <summary>Gets a label for the catch block in which the exception was caught.</summary>\n        public string Name\n        {\n            get { return _name; }\n        }\n\n        /// <summary>\n        /// Gets a value indicating whether the catch block where the exception was caught is the last one before the\n        /// host.\n        /// </summary>\n        public bool IsTopLevel\n        {\n            get { return _isTopLevel; }\n        }\n\n        /// <summary>\n        /// Gets a value indicating whether exceptions in the catch block can be handled after they are logged.\n        /// </summary>\n        /// <remarks>\n        /// <para>\n        /// Some exceptions are caught after a response is already partially sent, which prevents sending a new\n        /// response to handle the exception. In such cases, <see cref=\"IExceptionLogger\"/> will be called to log the\n        /// exception, but the <see cref=\"IExceptionHandler\"/> will not be called.\n        /// </para>\n        /// <para>\n        /// If this value is <see langword=\"true\"/>, exceptions from this catch block will be provided to both\n        /// <see cref=\"IExceptionLogger\"/> and <see cref=\"IExceptionHandler\"/>. If this value is\n        /// see langword=\"false\"/>, exceptions from this catch block cannot be handled and will only be provided to\n        /// <see cref=\"IExceptionLogger\"/>.\n        /// </para>\n        /// </remarks>\n        public bool CallsHandler\n        {\n            get { return _callsHandler; }\n        }\n\n        /// <inheritdoc/>\n        public override string ToString()\n        {\n            return _name;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ExceptionHandling/ExceptionHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    /// <summary>Represents an unhandled exception handler.</summary>\n    public abstract class ExceptionHandler : IExceptionHandler\n    {\n        /// <inheritdoc />\n        Task IExceptionHandler.HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)\n        {\n            if (context == null)\n            {\n                throw new ArgumentNullException(\"context\");\n            }\n\n            ExceptionContext exceptionContext = context.ExceptionContext;\n            Contract.Assert(exceptionContext != null);\n\n            if (!ShouldHandle(context))\n            {\n                return TaskHelpers.Completed();\n            }\n\n            return HandleAsync(context, cancellationToken);\n        }\n\n        /// <summary>When overridden in a derived class, handles the exception asynchronously.</summary>\n        /// <param name=\"context\">The exception handler context.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task representing the asynchronous exception handling operation.</returns>\n        public virtual Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)\n        {\n            Handle(context);\n            return TaskHelpers.Completed();\n        }\n\n        /// <summary>When overridden in a derived class, handles the exception synchronously.</summary>\n        /// <param name=\"context\">The exception handler context.</param>\n        public virtual void Handle(ExceptionHandlerContext context)\n        {\n        }\n\n        /// <summary>Determines whether the exception should be handled.</summary>\n        /// <param name=\"context\">The exception handler context.</param>\n        /// <returns>\n        /// <see langword=\"true\"/> if the exception should be handled; otherwise, <see langword=\"false\"/>.\n        /// </returns>\n        /// <remarks>The default decision is only to handle exceptions caught at top-level catch blocks.</remarks>\n        public virtual bool ShouldHandle(ExceptionHandlerContext context)\n        {\n            if (context == null)\n            {\n                throw new ArgumentNullException(\"context\");\n            }\n\n            ExceptionContext exceptionContext = context.ExceptionContext;\n            Contract.Assert(exceptionContext != null);\n\n            ExceptionContextCatchBlock catchBlock = exceptionContext.CatchBlock;\n\n            return catchBlock.IsTopLevel;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ExceptionHandling/ExceptionHandlerContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    /// <summary>Represents the context within which unhandled exception handling occurs.</summary>\n    public class ExceptionHandlerContext\n    {\n        private readonly ExceptionContext _exceptionContext;\n\n        /// <summary>Initializes a new instance of the <see cref=\"ExceptionHandlerContext\"/> class.</summary>\n        /// <param name=\"exceptionContext\">The exception context.</param>\n        public ExceptionHandlerContext(ExceptionContext exceptionContext)\n        {\n            if (exceptionContext == null)\n            {\n                throw new ArgumentNullException(\"exceptionContext\");\n            }\n\n            _exceptionContext = exceptionContext;\n        }\n\n        /// <summary>Gets the exception context providing the exception and related data.</summary>\n        public ExceptionContext ExceptionContext\n        {\n            get { return _exceptionContext; }\n        }\n\n        /// <summary>Gets or sets the result providing the response message when the exception is handled.</summary>\n        /// <remarks>\n        /// If this value is <see langword=\"null\"/>, the exception is left unhandled and will be re-thrown.\n        /// </remarks>\n        public IHttpActionResult Result { get; set; }\n\n        /// <summary>Gets the exception caught.</summary>\n        public Exception Exception\n        {\n            get { return _exceptionContext.Exception; }\n        }\n\n        /// <summary>Gets the catch block in which the exception was caught.</summary>\n        public ExceptionContextCatchBlock CatchBlock\n        {\n            get { return _exceptionContext.CatchBlock; }\n        }\n\n        /// <summary>Gets the request being processed when the exception was caught.</summary>\n        public HttpRequestMessage Request\n        {\n            get { return _exceptionContext.Request; }\n        }\n\n        /// <summary>Gets the request context in which the exception occurred.</summary>\n        public HttpRequestContext RequestContext\n        {\n            get { return _exceptionContext.RequestContext; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ExceptionHandling/ExceptionHandlerExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    /// <summary>Provides extension methods for <see cref=\"IExceptionHandler\"/>.</summary>\n    public static class ExceptionHandlerExtensions\n    {\n        /// <summary>Calls an exception handler and determines the response handling it, if any.</summary>\n        /// <param name=\"handler\">The unhandled exception handler.</param>\n        /// <param name=\"context\">The exception context.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>\n        /// A task that, when completed, contains the response message to return when the exception is handled, or\n        /// <see langword=\"null\"/> when the exception remains unhandled.\n        /// </returns>\n        public static Task<HttpResponseMessage> HandleAsync(this IExceptionHandler handler,\n            ExceptionContext context, CancellationToken cancellationToken)\n        {\n            if (handler == null)\n            {\n                throw new ArgumentNullException(\"handler\");\n            }\n\n            if (context == null)\n            {\n                throw new ArgumentNullException(\"context\");\n            }\n\n            ExceptionHandlerContext handlerContext = new ExceptionHandlerContext(context);\n            return HandleAsyncCore(handler, handlerContext, cancellationToken);\n        }\n\n        private static async Task<HttpResponseMessage> HandleAsyncCore(IExceptionHandler handler,\n            ExceptionHandlerContext context, CancellationToken cancellationToken)\n        {\n            Contract.Assert(handler != null);\n            Contract.Assert(context != null);\n\n            await handler.HandleAsync(context, cancellationToken);\n\n            IHttpActionResult result = context.Result;\n\n            if (result == null)\n            {\n                return null;\n            }\n\n            HttpResponseMessage response = await result.ExecuteAsync(cancellationToken);\n\n            if (response == null)\n            {\n                throw new InvalidOperationException(Error.Format(SRResources.TypeMethodMustNotReturnNull,\n                    typeof(IHttpActionResult).Name, \"ExecuteAsync\"));\n            }\n\n            return response;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ExceptionHandling/ExceptionLogger.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    /// <summary>Represents an unhandled exception logger.</summary>\n    public abstract class ExceptionLogger : IExceptionLogger\n    {\n        internal const string LoggedByKey = \"MS_LoggedBy\";\n\n        /// <inheritdoc />\n        Task IExceptionLogger.LogAsync(ExceptionLoggerContext context, CancellationToken cancellationToken)\n        {\n            if (context == null)\n            {\n                throw new ArgumentNullException(\"context\");\n            }\n\n            ExceptionContext exceptionContext = context.ExceptionContext;\n            Contract.Assert(exceptionContext != null);\n\n            if (!ShouldLog(context))\n            {\n                return TaskHelpers.Completed();\n            }\n\n            return LogAsync(context, cancellationToken);\n        }\n\n        /// <summary>When overridden in a derived class, logs the exception asynchronously.</summary>\n        /// <param name=\"context\">The exception logger context.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task representing the asynchronous exception logging operation.</returns>\n        public virtual Task LogAsync(ExceptionLoggerContext context, CancellationToken cancellationToken)\n        {\n            Log(context);\n            return TaskHelpers.Completed();\n        }\n\n        /// <summary>When overridden in a derived class, logs the exception synchronously.</summary>\n        /// <param name=\"context\">The exception logger context.</param>\n        public virtual void Log(ExceptionLoggerContext context)\n        {\n        }\n\n        /// <summary>Determines whether the exception should be logged.</summary>\n        /// <param name=\"context\">The exception logger context.</param>\n        /// <returns>\n        /// <see langword=\"true\"/> if the exception should be logged; otherwise, <see langword=\"false\"/>.\n        /// </returns>\n        /// <remarks>\n        /// The default decision is only to log an exception instance the first time it is seen by this logger.\n        /// </remarks>\n        public virtual bool ShouldLog(ExceptionLoggerContext context)\n        {\n            if (context == null)\n            {\n                throw new ArgumentNullException(\"context\");\n            }\n\n            ExceptionContext exceptionContext = context.ExceptionContext;\n            Contract.Assert(exceptionContext != null);\n\n            IDictionary data = exceptionContext.Exception.Data;\n\n            if (data == null || data.IsReadOnly)\n            {\n                // If the exception doesn't have a mutable Data collection, we can't prevent duplicate logging. In this\n                // case, just log every time.\n                return true;\n            }\n\n            ICollection<object> loggedBy;\n\n            if (data.Contains(LoggedByKey))\n            {\n                object untypedLoggedBy = data[LoggedByKey];\n\n                loggedBy = untypedLoggedBy as ICollection<object>;\n\n                if (loggedBy == null)\n                {\n                    // If exception.Data[\"MS_LoggedBy\"] exists but is not of the right type, we can't prevent duplicate\n                    // logging. In this case, just log every time.\n                    return true;\n                }\n\n                if (loggedBy.Contains(this))\n                {\n                    // If this logger has already logged this exception, don't log again.\n                    return false;\n                }\n            }\n            else\n            {\n                loggedBy = new List<object>();\n                data.Add(LoggedByKey, loggedBy);\n            }\n\n            // Either loggedBy did not exist before (we just added it) or it already existed of the right type and did\n            // not already contain this logger. Log now, but mark not to log this exception again for this logger.\n            Contract.Assert(loggedBy != null);\n            loggedBy.Add(this);\n            return true;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ExceptionHandling/ExceptionLoggerContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    /// <summary>Represents the context within which unhandled exception logging occurs.</summary>\n    public class ExceptionLoggerContext\n    {\n        private readonly ExceptionContext _exceptionContext;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"ExceptionLoggerContext\"/> class using the values provided.\n        /// </summary>\n        /// <param name=\"exceptionContext\">The exception context.</param>\n        public ExceptionLoggerContext(ExceptionContext exceptionContext)\n        {\n            if (exceptionContext == null)\n            {\n                throw new ArgumentNullException(\"exceptionContext\");\n            }\n\n            _exceptionContext = exceptionContext;\n        }\n\n        /// <summary>Gets the exception context providing the exception and related data.</summary>\n        public ExceptionContext ExceptionContext\n        {\n            get { return _exceptionContext; }\n        }\n\n        /// <summary>Gets the exception caught.</summary>\n        public Exception Exception\n        {\n            get { return _exceptionContext.Exception; }\n        }\n\n        /// <summary>Gets the catch block in which the exception was caught.</summary>\n        public ExceptionContextCatchBlock CatchBlock\n        {\n            get { return _exceptionContext.CatchBlock; }\n        }\n\n        /// <summary>Gets the request being processed when the exception was caught.</summary>\n        public HttpRequestMessage Request\n        {\n            get { return _exceptionContext.Request; }\n        }\n\n        /// <summary>Gets the request context in which the exception occurred.</summary>\n        public HttpRequestContext RequestContext\n        {\n            get { return _exceptionContext.RequestContext; }\n        }\n\n        /// <summary>\n        /// Gets or sets a value indicating whether the exception can subsequently be handled by an\n        /// <see cref=\"IExceptionHandler\"/> to produce a new response message.\n        /// </summary>\n        /// <remarks>\n        /// <para>\n        /// Some exceptions are caught after a response is already partially sent, which prevents sending a new\n        /// response to handle the exception. In such cases, <see cref=\"IExceptionLogger\"/> will be called to log the\n        /// exception, but the <see cref=\"IExceptionHandler\"/> will not be called.\n        /// </para>\n        /// <para>\n        /// If this value is <see langword=\"true\"/>, exceptions from this catch block will be provided to both\n        /// <see cref=\"IExceptionLogger\"/> and <see cref=\"IExceptionHandler\"/>. If this value is\n        /// see langword=\"false\"/>, exceptions from this catch block cannot be handled and will only be provided to\n        /// <see cref=\"IExceptionLogger\"/>.\n        /// </para>\n        /// </remarks>\n        public bool CallsHandler\n        {\n            get\n            {\n                Contract.Assert(_exceptionContext != null);\n                ExceptionContextCatchBlock catchBlock = _exceptionContext.CatchBlock;\n\n                return catchBlock.CallsHandler;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ExceptionHandling/ExceptionLoggerExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    /// <summary>Provides extension methods for <see cref=\"IExceptionLogger\"/>.</summary>\n    public static class ExceptionLoggerExtensions\n    {\n        /// <summary>Calls an exception logger.</summary>\n        /// <param name=\"logger\">The unhandled exception logger.</param>\n        /// <param name=\"context\">The exception context.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task representing the asynchronous exception logging operation.</returns>\n        public static Task LogAsync(this IExceptionLogger logger, ExceptionContext context,\n            CancellationToken cancellationToken)\n        {\n            if (logger == null)\n            {\n                throw new ArgumentNullException(\"logger\");\n            }\n\n            if (context == null)\n            {\n                throw new ArgumentNullException(\"context\");\n            }\n\n            ExceptionLoggerContext loggerContext = new ExceptionLoggerContext(context);\n            return logger.LogAsync(loggerContext, cancellationToken);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ExceptionHandling/ExceptionServices.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    /// <summary>Creates exception services to call logging and handling from catch blocks.</summary>\n    public static class ExceptionServices\n    {\n        /// <summary>Gets an exception logger that calls all registered logger services.</summary>\n        /// <param name=\"configuration\">The configuration.</param>\n        /// <returns>A composite logger.</returns>\n        public static IExceptionLogger GetLogger(HttpConfiguration configuration)\n        {\n            if (configuration == null)\n            {\n                throw new ArgumentNullException(\"configuration\");\n            }\n\n            ServicesContainer services = configuration.Services;\n            Contract.Assert(services != null);\n            return GetLogger(services);\n        }\n\n        /// <summary>Gets an exception logger that calls all registered logger services.</summary>\n        /// <param name=\"services\">The services container.</param>\n        /// <returns>A composite logger.</returns>\n        public static IExceptionLogger GetLogger(ServicesContainer services)\n        {\n            if (services == null)\n            {\n                throw new ArgumentNullException(\"services\");\n            }\n\n            Lazy<IExceptionLogger> exceptionServicesLogger = services.ExceptionServicesLogger;\n            Contract.Assert(exceptionServicesLogger != null);\n            return exceptionServicesLogger.Value;\n        }\n\n        internal static IExceptionLogger CreateLogger(ServicesContainer services)\n        {\n            Contract.Assert(services != null);\n\n            IEnumerable<IExceptionLogger> loggers = services.GetExceptionLoggers();\n            Contract.Assert(loggers != null);\n            return new CompositeExceptionLogger(loggers);\n        }\n\n        /// <summary>\n        /// Gets an exception handler that calls the registered handler service, if any, and ensures exceptions do not\n        /// accidentally propagate to the host.\n        /// </summary>\n        /// <param name=\"configuration\">The configuration.</param>\n        /// <returns>\n        /// An exception handler that calls any registered handler and ensures exceptions do not accidentally propagate\n        /// to the host.\n        /// </returns>\n        public static IExceptionHandler GetHandler(HttpConfiguration configuration)\n        {\n            if (configuration == null)\n            {\n                throw new ArgumentNullException(\"configuration\");\n            }\n\n            ServicesContainer services = configuration.Services;\n            Contract.Assert(services != null);\n            return GetHandler(services);\n        }\n\n        /// <summary>\n        /// Gets an exception handler that calls the registered handler service, if any, and ensures exceptions do not\n        /// accidentally propagate to the host.\n        /// </summary>\n        /// <param name=\"services\">The services container.</param>\n        /// <returns>\n        /// An exception handler that calls any registered handler and ensures exceptions do not accidentally propagate\n        /// to the host.\n        /// </returns>\n        public static IExceptionHandler GetHandler(ServicesContainer services)\n        {\n            if (services == null)\n            {\n                throw new ArgumentNullException(\"services\");\n            }\n\n            Lazy<IExceptionHandler> exceptionServicesHandler = services.ExceptionServicesHandler;\n            Contract.Assert(exceptionServicesHandler != null);\n            return exceptionServicesHandler.Value;\n        }\n\n        internal static IExceptionHandler CreateHandler(ServicesContainer services)\n        {\n            Contract.Assert(services != null);\n\n            IExceptionHandler innerHandler = services.GetExceptionHandler() ?? new EmptyExceptionHandler();\n            return new LastChanceExceptionHandler(innerHandler);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ExceptionHandling/IExceptionHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    /// <summary>Defines an unhandled exception handler.</summary>\n    /// <remarks>\n    /// An unhandled exception handler can either handle the exception (by providing a response) or allow it to\n    /// propagate (by providing no response).\n    /// </remarks>\n    public interface IExceptionHandler\n    {\n        /// <summary>\n        /// Process an unhandled exception, either allowing it to propagate or handling it by providing a response\n        /// message to return instead.\n        /// </summary>\n        /// <param name=\"context\">The exception handler context.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task representing the asynchronous exception handling operation.</returns>\n        /// <remarks>\n        /// <para>\n        /// The exception handler either handles the exception or allows it to propagate. An exception is handled by\n        /// setting <see cref=\"ExceptionHandlerContext.Result\"/>, which provides the response message to return in\n        /// place of the exception thrown. If <see cref=\"ExceptionHandlerContext.Result\"/> is\n        /// <see langword=\"null\"/>, the exception remains unhandled, and the exception will continue to propagate up\n        /// the call stack.\n        /// </para>\n        /// <para>\n        /// If the exception propagates when <see cref=\"ExceptionContextCatchBlock.IsTopLevel\"/> is\n        /// <see langword=\"true\"/>, the host will see the exception thrown. If the exception propagates when\n        /// <see cref=\"ExceptionContextCatchBlock.IsTopLevel\"/> is <see langword=\"false\"/>, another catch block within\n        /// Web API will be the next to see the exception, and the exception handler will be called again to make a\n        /// decision at that point.\n        /// </para>\n        /// </remarks>\n        Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ExceptionHandling/IExceptionLogger.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    /// <summary>Defines an unhandled exception logger.</summary>\n    public interface IExceptionLogger\n    {\n        /// <summary>Logs an unhandled exception.</summary>\n        /// <param name=\"context\">The exception logger context.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task representing the asynchronous exception logging operation.</returns>\n        Task LogAsync(ExceptionLoggerContext context, CancellationToken cancellationToken);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ExceptionHandling/LastChanceExceptionHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Results;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    internal class LastChanceExceptionHandler : IExceptionHandler\n    {\n        private readonly IExceptionHandler _innerHandler;\n\n        public LastChanceExceptionHandler(IExceptionHandler innerHandler)\n        {\n            if (innerHandler == null)\n            {\n                throw new ArgumentNullException(\"innerHandler\");\n            }\n\n            _innerHandler = innerHandler;\n        }\n\n        public IExceptionHandler InnerHandler\n        {\n            get { return _innerHandler; }\n        }\n\n        public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)\n        {\n            if (context != null)\n            {\n                ExceptionContext exceptionContext = context.ExceptionContext;\n                Contract.Assert(exceptionContext != null);\n\n                ExceptionContextCatchBlock catchBlock = exceptionContext.CatchBlock;\n\n                if (catchBlock != null && catchBlock.IsTopLevel)\n                {\n                    context.Result = CreateDefaultLastChanceResult(exceptionContext);\n                }\n            }\n\n            return _innerHandler.HandleAsync(context, cancellationToken);\n        }\n\n        private static IHttpActionResult CreateDefaultLastChanceResult(ExceptionContext context)\n        {\n            Contract.Assert(context != null);\n\n            Exception exception = context.Exception;\n\n            if (exception == null)\n            {\n                return null;\n            }\n\n            HttpRequestMessage request = context.Request;\n\n            if (request == null)\n            {\n                return null;\n            }\n\n            HttpRequestContext requestContext = context.RequestContext;\n\n            if (requestContext == null)\n            {\n                return null;\n            }\n\n            HttpConfiguration configuration = requestContext.Configuration;\n\n            if (configuration == null)\n            {\n                return null;\n            }\n\n            ServicesContainer services = configuration.Services;\n            Contract.Assert(services != null);\n            IContentNegotiator contentNegotiator = services.GetContentNegotiator();\n\n            if (contentNegotiator == null)\n            {\n                return null;\n            }\n\n            IEnumerable<MediaTypeFormatter> formatters = configuration.Formatters;\n            Contract.Assert(formatters != null);\n\n            return new ExceptionResult(exception, requestContext.IncludeErrorDetail, contentNegotiator, request,\n                formatters);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Filters/ActionDescriptorFilterProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.Filters\n{\n    /// <summary>\n    /// This <see cref=\"IFilterProvider\"/> implementation retrieves <see cref=\"FilterInfo\">filters</see> associated with an <see cref=\"HttpActionDescriptor\"/>\n    /// instance.\n    /// </summary>\n    public class ActionDescriptorFilterProvider : IFilterProvider\n    {\n        /// <summary>\n        /// Returns the collection of filters associated with <paramref name=\"actionDescriptor\"/>.\n        /// </summary>\n        /// <remarks>\n        /// The implementation invokes <see cref=\"HttpActionDescriptor.GetFilters()\"/> and <see cref=\"HttpControllerDescriptor.GetFilters()\"/>.\n        /// </remarks>\n        /// <param name=\"configuration\">The configuration. This value is not used.</param>\n        /// <param name=\"actionDescriptor\">The action descriptor.</param>\n        /// <returns>A collection of filters.</returns>\n        public IEnumerable<FilterInfo> GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor)\n        {\n            if (configuration == null)\n            {\n                throw Error.ArgumentNull(\"configuration\");\n            }\n\n            if (actionDescriptor == null)\n            {\n                throw Error.ArgumentNull(\"actionDescriptor\");\n            }\n\n            IEnumerable<FilterInfo> controllerFilters = actionDescriptor.ControllerDescriptor.GetFilters().Select(instance => new FilterInfo(instance, FilterScope.Controller));\n            IEnumerable<FilterInfo> actionFilters = actionDescriptor.GetFilters().Select(instance => new FilterInfo(instance, FilterScope.Action));\n\n            return controllerFilters.Concat(actionFilters);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Filters/ActionFilterAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Net.Http;\nusing System.Runtime.ExceptionServices;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.Filters\n{\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]\n    public abstract class ActionFilterAttribute : FilterAttribute, IActionFilter\n    {\n        public virtual void OnActionExecuting(HttpActionContext actionContext)\n        {\n        }\n\n        public virtual void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)\n        {\n        }\n\n        [System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"exception is flowed through the task\")]\n        public virtual Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)\n        {\n            try\n            {\n                OnActionExecuting(actionContext);\n            }\n            catch (Exception ex)\n            {\n                return TaskHelpers.FromError(ex);\n            }\n\n            return TaskHelpers.Completed();\n        }\n\n        [System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"exception is flowed through the task\")]\n        public virtual Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)\n        {\n            try\n            {\n                OnActionExecuted(actionExecutedContext);\n            }\n            catch (Exception ex)\n            {\n                return TaskHelpers.FromError(ex);\n            }\n\n            return TaskHelpers.Completed();\n        }\n\n        Task<HttpResponseMessage> IActionFilter.ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)\n        {\n            if (actionContext == null)\n            {\n                throw Error.ArgumentNull(\"actionContext\");\n            }\n            if (continuation == null)\n            {\n                throw Error.ArgumentNull(\"continuation\");\n            }\n\n            return ExecuteActionFilterAsyncCore(actionContext, cancellationToken, continuation);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We want to intercept all exceptions\")]\n        private async Task<HttpResponseMessage> ExecuteActionFilterAsyncCore(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)\n        {\n            await OnActionExecutingAsync(actionContext, cancellationToken);\n\n            if (actionContext.Response != null)\n            {\n                return actionContext.Response;\n            }\n\n            return await CallOnActionExecutedAsync(actionContext, cancellationToken, continuation);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We want to intercept all exceptions\")]\n        private async Task<HttpResponseMessage> CallOnActionExecutedAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)\n        {\n            cancellationToken.ThrowIfCancellationRequested();\n\n            HttpResponseMessage response = null;\n            ExceptionDispatchInfo exceptionInfo = null;\n            try\n            {\n                response = await continuation();\n            }\n            catch (Exception e)\n            {\n                exceptionInfo = ExceptionDispatchInfo.Capture(e);\n            }\n\n            Exception exception;\n\n            if (exceptionInfo == null)\n            {\n                exception = null;\n            }\n            else\n            {\n                exception = exceptionInfo.SourceException;\n            }\n\n            HttpActionExecutedContext executedContext = new HttpActionExecutedContext(actionContext, exception)\n            {\n                Response = response\n            };\n\n            try\n            {\n                await OnActionExecutedAsync(executedContext, cancellationToken);\n            }\n            catch\n            {\n                // Catch is running because OnActionExecuted threw an exception, so we just want to re-throw.\n                // We also need to reset the response to forget about it since a filter threw an exception.\n                actionContext.Response = null;\n                throw;\n            }\n\n            if (executedContext.Response != null)\n            {\n                return executedContext.Response;\n            }\n\n            Exception newException = executedContext.Exception;\n\n            if (newException != null)\n            {\n                if (newException == exception)\n                {\n                    exceptionInfo.Throw();\n                }\n                else\n                {\n                    throw newException;\n                }\n            }\n\n            throw Error.InvalidOperation(SRResources.ActionFilterAttribute_MustSupplyResponseOrException, GetType().Name);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Filters/AuthorizationFilterAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.Filters\n{\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]\n    public abstract class AuthorizationFilterAttribute : FilterAttribute, IAuthorizationFilter\n    {\n        public virtual void OnAuthorization(HttpActionContext actionContext)\n        {\n        }\n\n        [System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"exception is flowed through the task\")]\n        public virtual Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)\n        {\n            try\n            {\n                OnAuthorization(actionContext);\n            }\n            catch (Exception ex)\n            {\n                return TaskHelpers.FromError(ex);\n            }\n\n            return TaskHelpers.Completed();\n        }\n\n        Task<HttpResponseMessage> IAuthorizationFilter.ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)\n        {\n            if (actionContext == null)\n            {\n                throw Error.ArgumentNull(\"actionContext\");\n            }\n            if (continuation == null)\n            {\n                throw Error.ArgumentNull(\"continuation\");\n            }\n\n            return ExecuteAuthorizationFilterAsyncCore(actionContext, cancellationToken, continuation);\n        }\n\n        private async Task<HttpResponseMessage> ExecuteAuthorizationFilterAsyncCore(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)\n        {\n            await OnAuthorizationAsync(actionContext, cancellationToken);\n\n            if (actionContext.Response != null)\n            {\n                return actionContext.Response;\n            }\n            else\n            {\n                return await continuation();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Filters/ConfigurationFilterProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.Filters\n{\n    public class ConfigurationFilterProvider : IFilterProvider\n    {\n        public IEnumerable<FilterInfo> GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor)\n        {\n            if (configuration == null)\n            {\n                throw Error.ArgumentNull(\"configuration\");\n            }\n\n            return configuration.Filters;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Filters/ExceptionFilterAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.Filters\n{\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]\n    public abstract class ExceptionFilterAttribute : FilterAttribute, IExceptionFilter\n    {\n        public virtual void OnException(HttpActionExecutedContext actionExecutedContext)\n        {\n        }\n\n        [System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"The exception is flowed in the task\")]\n        public virtual Task OnExceptionAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)\n        {\n            try\n            {\n                OnException(actionExecutedContext);\n            }\n            catch (Exception ex)\n            {\n                return TaskHelpers.FromError(ex);\n            }\n\n            return TaskHelpers.Completed();\n        }\n\n        Task IExceptionFilter.ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)\n        {\n            if (actionExecutedContext == null)\n            {\n                throw Error.ArgumentNull(\"actionExecutedContext\");\n            }\n\n            return ExecuteExceptionFilterAsyncCore(actionExecutedContext, cancellationToken);\n        }\n\n        private async Task ExecuteExceptionFilterAsyncCore(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)\n        {\n            await OnExceptionAsync(actionExecutedContext, cancellationToken);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Filters/FilterAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Web.Http.Internal;\n\nnamespace System.Web.Http.Filters\n{\n    [SuppressMessage(\"Microsoft.Performance\", \"CA1813:AvoidUnsealedAttributes\", Justification = \"We want to allow inheritance\")]\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]\n    public abstract class FilterAttribute : Attribute, IFilter\n    {\n        private static readonly ConcurrentDictionary<Type, bool> _attributeUsageCache = new ConcurrentDictionary<Type, bool>();\n\n        public virtual bool AllowMultiple\n        {\n            get { return AllowsMultiple(GetType()); }\n        }\n\n        private static bool AllowsMultiple(Type attributeType)\n        {\n            return _attributeUsageCache.GetOrAdd(\n                attributeType,\n                type => type.GetCustomAttributes<AttributeUsageAttribute>(inherit: true).First().AllowMultiple);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Filters/FilterInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Filters\n{\n    public sealed class FilterInfo\n    {\n        public FilterInfo(IFilter instance, FilterScope scope)\n        {\n            if (instance == null)\n            {\n                throw Error.ArgumentNull(\"instance\");\n            }\n\n            Instance = instance;\n            Scope = scope;\n        }\n\n        public IFilter Instance { get; private set; }\n\n        public FilterScope Scope { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Filters/FilterInfoComparer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Http.Filters\n{\n    internal sealed class FilterInfoComparer : IComparer<FilterInfo>\n    {\n        private static readonly FilterInfoComparer _instance = new FilterInfoComparer();\n\n        public static FilterInfoComparer Instance\n        {\n            get { return _instance; }\n        }\n\n        public int Compare(FilterInfo x, FilterInfo y)\n        {\n            if (x == null && y == null)\n            {\n                return 0;\n            }\n            else if (x == null)\n            {\n                return -1;\n            }\n            else if (y == null)\n            {\n                return 1;\n            }\n            else\n            {\n                var r = x.Scope - y.Scope;\n                return r;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Filters/FilterScope.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Filters\n{\n    public enum FilterScope\n    {\n        Global = 0,\n        Controller = 10,\n        Action = 20,\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Filters/HttpActionExecutedContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.Filters\n{\n    public class HttpActionExecutedContext\n    {\n        private HttpActionContext _actionContext;\n\n        public HttpActionExecutedContext(HttpActionContext actionContext, Exception exception)\n        {\n            if (actionContext == null)\n            {\n                throw Error.ArgumentNull(\"actionContext\");\n            }\n\n            Exception = exception;\n            _actionContext = actionContext;\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpActionExecutedContext\"/> class.\n        /// </summary>\n        /// <remarks>The default constructor is intended for use by unit testing only.</remarks>\n        public HttpActionExecutedContext()\n        {\n        }\n\n        public HttpActionContext ActionContext\n        {\n            get { return _actionContext; }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n                _actionContext = value;\n            }\n        }\n\n        public Exception Exception { get; set; }\n\n        public HttpResponseMessage Response\n        {\n            get\n            {\n                return ActionContext != null ? ActionContext.Response : null;\n            }\n\n            set\n            {\n                ActionContext.Response = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets the current <see cref=\"HttpRequestMessage\"/>.\n        /// </summary>\n        public HttpRequestMessage Request\n        {\n            get\n            {\n                return (ActionContext != null && ActionContext.ControllerContext != null)\n                           ? ActionContext.ControllerContext.Request\n                           : null;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Filters/HttpAuthenticationChallengeContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.Filters\n{\n    /// <summary>\n    /// Represents an authentication challenge context containing information for executing an authentication\n    /// challenge.\n    /// </summary>\n    public class HttpAuthenticationChallengeContext\n    {\n        private IHttpActionResult _result;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpAuthenticationChallengeContext\"/> class.\n        /// </summary>\n        /// <param name=\"actionContext\">The action context.</param>\n        /// <param name=\"result\">The current action result.</param>\n        public HttpAuthenticationChallengeContext(HttpActionContext actionContext, IHttpActionResult result)\n        {\n            if (actionContext == null)\n            {\n                throw new ArgumentNullException(\"actionContext\");\n            }\n\n            if (result == null)\n            {\n                throw new ArgumentNullException(\"result\");\n            }\n\n            ActionContext = actionContext;\n            Result = result;\n        }\n\n        /// <summary>Gets the action context.</summary>\n        public HttpActionContext ActionContext { get; private set; }\n\n        /// <summary>Gets or sets the action result to execute.</summary>\n        /// <remarks>\n        /// Authentication filters wishing to add an authentication challenge will often chain the result (set the\n        /// value to an action result that executes the previous value and then does something additional, such as add\n        /// a WWW-Authenticate header).\n        /// </remarks>\n        public IHttpActionResult Result\n        {\n            get\n            {\n                return _result;\n            }\n            set\n            {\n                if (value == null)\n                {\n                    throw new ArgumentNullException(\"value\");\n                }\n\n                _result = value;\n            }\n        }\n\n        /// <summary>Gets the request message.</summary>\n        public HttpRequestMessage Request\n        {\n            get\n            {\n                Contract.Assert(ActionContext != null);\n                return ActionContext.Request;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Filters/HttpAuthenticationContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Security.Principal;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.Filters\n{\n    /// <summary>Represents an authentication context containing information for performing authentication.</summary>\n    public class HttpAuthenticationContext\n    {\n        /// <summary>Initializes a new instance of the <see cref=\"HttpAuthenticationContext\"/> class.</summary>\n        /// <param name=\"actionContext\">The action context.</param>\n        /// <param name=\"principal\">The current principal.</param>\n        public HttpAuthenticationContext(HttpActionContext actionContext, IPrincipal principal)\n        {\n            if (actionContext == null)\n            {\n                throw new ArgumentNullException(\"actionContext\");\n            }\n\n            ActionContext = actionContext;\n            Principal = principal;\n        }\n\n        /// <summary>Gets the action context.</summary>\n        public HttpActionContext ActionContext { get; private set; }\n\n        /// <summary>Gets or sets the authenticated principal.</summary>\n        public IPrincipal Principal { get; set; }\n\n        /// <summary>\n        /// Gets or sets an action result that will produce an error response (if authentication failed; otherwise,\n        /// <see langword=\"null\"/>).\n        /// </summary>\n        public IHttpActionResult ErrorResult { get; set; }\n\n        /// <summary>Gets the request message.</summary>\n        public HttpRequestMessage Request\n        {\n            get\n            {\n                Contract.Assert(ActionContext != null);\n                return ActionContext.Request;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Filters/HttpFilterCollection.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Linq;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.Filters\n{\n    public class HttpFilterCollection : IEnumerable<FilterInfo>\n    {\n        private readonly List<FilterInfo> _filters = new List<FilterInfo>();\n\n        public int Count\n        {\n            get { return _filters.Count; }\n        }\n\n        public void Add(IFilter filter)\n        {\n            if (filter == null)\n            {\n                throw Error.ArgumentNull(\"filter\");\n            }\n\n            _filters.Add(CreateFilterInfo(filter));\n        }\n\n        /// <summary>\n        /// Adds the elements of the specified collection to the end of the filter collection.\n        /// </summary>\n        /// <param name=\"filters\">The collection of filters to add.</param>\n        public void AddRange(IEnumerable<IFilter> filters)\n        {\n            if (filters == null)\n            {\n                throw Error.ArgumentNull(\"filters\");\n            }\n\n            // ToArray used here to avoid iterating the filter collection twice.\n            IFilter[] cachedFilters = filters.ToArray();\n            for (int i = 0; i < cachedFilters.Length; i++)\n            {\n                if (cachedFilters[i] == null)\n                {\n                    throw new ArgumentException(\n                        String.Format(CultureInfo.CurrentCulture, SRResources.CollectionParameterContainsNullElement, \"filters\"),\n                        \"filters\");\n                }\n            }\n\n            for (int i = 0; i < cachedFilters.Length; i++)\n            {\n                _filters.Add(CreateFilterInfo(cachedFilters[i]));\n            }\n        }\n\n        private static FilterInfo CreateFilterInfo(IFilter filter)\n        {\n            Contract.Assert(filter != null);\n            return new FilterInfo(filter, FilterScope.Global);\n        }\n\n        public void Clear()\n        {\n            _filters.Clear();\n        }\n\n        public bool Contains(IFilter filter)\n        {\n            return _filters.Any(f => f.Instance == filter);\n        }\n\n        public IEnumerator<FilterInfo> GetEnumerator()\n        {\n            return _filters.GetEnumerator();\n        }\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return GetEnumerator();\n        }\n\n        public void Remove(IFilter filter)\n        {\n            _filters.RemoveAll(f => f.Instance == filter);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Filters/IActionFilter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.Filters\n{\n    public interface IActionFilter : IFilter\n    {\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"Represents a continuation call\")]\n        Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Filters/IAuthenticationFilter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.Filters\n{\n    /// <summary>Defines a filter that performs authentication.</summary>\n    public interface IAuthenticationFilter : IFilter\n    {\n        /// <summary>Authenticates the request.</summary>\n        /// <param name=\"context\">The authentication context.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A <see cref=\"Task\"/> that will perform authentication.</returns>\n        Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken);\n\n        /// <summary>Adds an authentication challenge to the inner <see cref=\"IHttpActionResult\"/>.</summary>\n        /// <param name=\"context\">The authentication challenge context.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A <see cref=\"Task\"/> that will perform the authentication challenge.</returns>\n        Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Filters/IAuthorizationFilter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.Filters\n{\n    public interface IAuthorizationFilter : IFilter\n    {\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"Represents a continuation call\")]\n        Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Filters/IExceptionFilter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.Filters\n{\n    public interface IExceptionFilter : IFilter\n    {\n        Task ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Filters/IFilter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Filters\n{\n    public interface IFilter\n    {\n        bool AllowMultiple { get; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Filters/IFilterProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.Filters\n{\n    public interface IFilterProvider\n    {\n        IEnumerable<FilterInfo> GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Filters/IOverrideFilter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Filters\n{\n    /// <summary>Defines a filter that overrides other filters.</summary>\n    public interface IOverrideFilter : IFilter\n    {\n        /// <summary>Gets the type of filters to override.</summary>\n        /// <remarks>\n        /// The following types of filters may be overridden:\n        /// <list type=\"bullet\">\n        /// <item><description><see cref=\"IActionFilter\"/></description></item>\n        /// <item><description><see cref=\"IAuthenticationFilter\"/></description></item>\n        /// <item><description><see cref=\"IAuthorizationFilter\"/></description></item>\n        /// <item><description><see cref=\"IExceptionFilter\"/></description></item>\n        /// </list>\n        /// </remarks>\n        Type FiltersToOverride { get; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/FromBodyAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Validation;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// This attribute is used on action parameters to indicate\n    /// they come only from the content body of the incoming <see cref=\"HttpRequestMessage\"/>.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)]\n    public sealed class FromBodyAttribute : ParameterBindingAttribute\n    {\n        public override HttpParameterBinding GetBinding(HttpParameterDescriptor parameter)\n        {\n            if (parameter == null)\n            {\n                throw Error.ArgumentNull(\"parameter\");\n            }\n\n            IEnumerable<MediaTypeFormatter> formatters = parameter.Configuration.Formatters;\n            IBodyModelValidator validator = parameter.Configuration.Services.GetBodyModelValidator();\n\n            return parameter.BindWithFormatter(formatters, validator);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/FromUriAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.ValueProviders;\n\nnamespace System.Web.Http\n{\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)]\n    public sealed class FromUriAttribute : ModelBinderAttribute\n    {\n        public override IEnumerable<ValueProviderFactory> GetValueProviderFactories(HttpConfiguration configuration)\n        {\n            if (configuration == null)\n            {\n                throw Error.ArgumentNull(\"configuration\");\n            }\n\n            foreach (ValueProviderFactory f in base.GetValueProviderFactories(configuration))\n            {\n                if (f is IUriValueProviderFactory)\n                {\n                    yield return f;\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/GlobalSuppressions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA2210:AssembliesShouldHaveValidStrongNames\",\n    Justification = \"The assembly is delay signed\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\",\n    Target = \"System.Net.Http\",\n    Justification = \"Functionality logically belongs in a namespace defined in a different binary\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\",\n    Target = \"System.Net.Http.Formatting\", Justification = \"Namespace follows folder structure\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\",\n    Target = \"System.Web.Http.Batch\", Justification = \"Namespace follows folder structure\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\",\n    Target = \"System.Web.Http.Dependencies\", Justification = \"Namespace follows folder structure\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\",\n    Target = \"System.Web.Http.Hosting\", Justification = \"Removing this namespace now would be a breaking change.\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\",\n    Target = \"System.Web.Http.Metadata\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\",\n    Target = \"System.Web.Http.Services\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\",\n    Target = \"System.Web.Http.Validation.Validators\", Justification = \"Namespace follows folder structure\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1033:InterfaceMethodsShouldBeCallableByChildTypes\", Scope = \"member\",\n    Target = \"System.Web.Http.Filters.ActionFilterAttribute.#System.Web.Http.Filters.IActionFilter.ExecuteActionFilterAsync(System.Web.Http.Controllers.HttpActionContext,System.Threading.CancellationToken,System.Func`1<System.Threading.Tasks.Task`1<System.Net.Http.HttpResponseMessage>>)\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1033:InterfaceMethodsShouldBeCallableByChildTypes\", Scope = \"member\",\n    Target = \"System.Web.Http.Filters.AuthorizationFilterAttribute.#System.Web.Http.Filters.IAuthorizationFilter.ExecuteAuthorizationFilterAsync(System.Web.Http.Controllers.HttpActionContext,System.Threading.CancellationToken,System.Func`1<System.Threading.Tasks.Task`1<System.Net.Http.HttpResponseMessage>>)\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1033:InterfaceMethodsShouldBeCallableByChildTypes\", Scope = \"member\",\n    Target = \"System.Web.Http.Filters.ExceptionFilterAttribute.#System.Web.Http.Filters.IExceptionFilter.ExecuteExceptionFilterAsync(System.Web.Http.Filters.HttpActionExecutedContext,System.Threading.CancellationToken)\")]\n"
  },
  {
    "path": "src/System.Web.Http/Hosting/HttpPropertyKeys.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Routing;\n\nnamespace System.Web.Http.Hosting\n{\n    /// <summary>\n    /// Provides common keys for properties stored in the <see cref=\"HttpRequestMessage.Properties\"/>\n    /// </summary>\n    public static class HttpPropertyKeys\n    {\n        /// <summary>\n        /// Provides a key for the <see cref=\"HttpConfiguration\"/> associated with this request.\n        /// </summary>\n        public static readonly string HttpConfigurationKey = \"MS_HttpConfiguration\";\n\n        /// <summary>\n        /// Provides a key for the <see cref=\"IHttpRouteData\"/> associated with this request.\n        /// </summary>\n        public static readonly string HttpRouteDataKey = \"MS_HttpRouteData\";\n\n        /// <summary>\n        /// Provides a key for the <see cref=\"System.Web.Http.Controllers.HttpActionDescriptor\"/> associated with this request.\n        /// </summary>\n        public static readonly string HttpActionDescriptorKey = \"MS_HttpActionDescriptor\";\n\n        /// <summary>\n        /// Provides a key for the current <see cref=\"SynchronizationContext\"/> stored in <see cref=\"HttpRequestMessage.Properties\"/>.\n        /// If <see cref=\"SynchronizationContext.Current\"/> is <c>null</c> then no context is stored.\n        /// </summary>\n        public static readonly string SynchronizationContextKey = \"MS_SynchronizationContext\";\n\n        /// <summary>\n        /// Provides a key for the collection of resources that should be disposed when a request is disposed.\n        /// </summary>\n        public static readonly string DisposableRequestResourcesKey = \"MS_DisposableRequestResources\";\n\n        /// <summary>\n        /// Provides a key for the dependency scope for this request.\n        /// </summary>\n        public static readonly string DependencyScope = \"MS_DependencyScope\";\n\n        /// <summary>\n        /// Provides a key for the client certificate for this request.\n        /// </summary>\n        public static readonly string ClientCertificateKey = \"MS_ClientCertificate\";\n\n        /// <summary>\n        /// Provides a key for a delegate which can retrieve the client certificate for this request.\n        /// </summary>\n        public static readonly string RetrieveClientCertificateDelegateKey = \"MS_RetrieveClientCertificateDelegate\";\n\n        /// <summary>\n        /// Provides a key for the <see cref=\"HttpRequestContext\"/> for this request.\n        /// </summary>\n        public static readonly string RequestContextKey = \"MS_RequestContext\";\n\n        /// <summary>\n        /// Provides a key for the <see cref=\"Guid\"/> stored in <see cref=\"HttpRequestMessage.Properties\"/>.\n        /// This is the correlation id for that request.\n        /// </summary>\n        public static readonly string RequestCorrelationKey = \"MS_RequestId\";\n\n        /// <summary>\n        /// Provides a key that indicates whether the request originates from a local address.\n        /// </summary>\n        public static readonly string IsLocalKey = \"MS_IsLocal\";\n\n        /// <summary>\n        /// Provides a key that indicates whether the request failed to match a route.\n        /// </summary>\n        public static readonly string NoRouteMatched = \"MS_NoRouteMatched\";\n\n        /// <summary>\n        /// Provides a key that indicates whether error details are to be included in the response for this HTTP request.\n        /// </summary>\n        public static readonly string IncludeErrorDetailKey = \"MS_IncludeErrorDetail\";\n\n        /// <summary>\n        /// Provides a key for the parsed query string stored in <see cref=\"HttpRequestMessage.Properties\"/>.\n        /// </summary>\n        public static readonly string RequestQueryNameValuePairsKey = \"MS_QueryNameValuePairs\";\n\n        /// <summary>\n        /// Provides the original query string for the parsed query string stored in <see cref=\"HttpRequestMessage.Properties\"/>\n        /// under the key <see cref=\"HttpPropertyKeys.RequestQueryNameValuePairsKey\" />.\n        /// </summary>\n        public static readonly string CachedRequestQueryKey = \"MS_CachedRequestQuery\";\n\n        /// <summary>\n        /// Provides a key that indicates whether the request is a batch request.\n        /// </summary>\n        public static readonly string IsBatchRequest = \"MS_BatchRequest\";\n    }\n}"
  },
  {
    "path": "src/System.Web.Http/Hosting/IHostBufferPolicySelector.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\n\nnamespace System.Web.Http.Hosting\n{\n    /// <summary>\n    /// Interface for controlling the use of buffering requests and responses in the host. If a host\n    /// provides support for buffering requests and/or responses then it can use this interface to \n    /// determine the policy for when buffering is to be used.\n    /// </summary>\n    public interface IHostBufferPolicySelector\n    {\n        /// <summary>\n        /// Determines whether the host should buffer the entity body when processing a request with content.\n        /// </summary>\n        /// <param name=\"hostContext\">The host-specific context.</param>\n        /// <returns><c>true</c> if buffering should be used; otherwise a streamed request should be used.</returns>\n        bool UseBufferedInputStream(object hostContext);\n\n        /// <summary>\n        /// Determines whether the host should buffer the <see cref=\"HttpResponseMessage\"/> entity body.\n        /// </summary>\n        /// <param name=\"response\">The <see cref=\"HttpResponseMessage\"/>response for which to determine\n        /// whether host output buffering should be used for the response entity body.</param>\n        /// <returns><c>true</c> if buffering should be used; otherwise a streamed response should be used.</returns>\n        bool UseBufferedOutputStream(HttpResponseMessage response);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Hosting/SuppressHostPrincipalMessageHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Security.Claims;\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.Hosting\n{\n    /// <summary>Represents a message handler that suppresses host authentication results.</summary>\n    /// <remarks>\n    /// This message handler sets the current principal to anonymous upon entry. As a result, any authentication\n    /// performed by the host is ignored. The subsequent pipeline, including <see cref=\"IAuthenticationFilter\"/>s, is\n    /// then the exclusive authority for authentication.\n    /// </remarks>\n    public class SuppressHostPrincipalMessageHandler : DelegatingHandler\n    {\n        private static readonly Lazy<IPrincipal> _anonymousPrincipal = new Lazy<IPrincipal>(\n            () => new ClaimsPrincipal(new ClaimsIdentity()), isThreadSafe: true);\n\n        /// <inheritdoc />\n        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,\n            CancellationToken cancellationToken)\n        {\n            if (request == null)\n            {\n                throw new ArgumentNullException(\"request\");\n            }\n\n            var previousPrincipal = SetCurrentPrincipal(request, _anonymousPrincipal.Value);\n            try\n            {\n                return await base.SendAsync(request, cancellationToken);\n            }\n            finally\n            {\n                SetCurrentPrincipal(request, previousPrincipal);\n            }\n        }\n\n        private static IPrincipal SetCurrentPrincipal(HttpRequestMessage request, IPrincipal principal)\n        {\n            Contract.Assert(request != null);\n\n            HttpRequestContext requestContext = request.GetRequestContext();\n            if (requestContext == null)\n            {\n                throw new ArgumentException(SRResources.Request_RequestContextMustNotBeNull, \"request\");\n            }\n\n            var previousPrincipal = requestContext.Principal;\n            requestContext.Principal = principal;\n\n            return previousPrincipal;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/HttpBindNeverAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.ModelBinding;\n\nnamespace System.Web.Http\n{\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]\n    public sealed class HttpBindNeverAttribute : HttpBindingBehaviorAttribute\n    {\n        public HttpBindNeverAttribute()\n            : base(HttpBindingBehavior.Never)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/HttpBindRequiredAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.ModelBinding;\n\nnamespace System.Web.Http\n{\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]\n    public sealed class HttpBindRequiredAttribute : HttpBindingBehaviorAttribute\n    {\n        public HttpBindRequiredAttribute()\n            : base(HttpBindingBehavior.Required)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/HttpConfiguration.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Dependencies;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.Services;\nusing System.Web.Http.Tracing;\nusing System.Web.Http.Validation;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Configuration of <see cref=\"HttpServer\"/> instances.\n    /// </summary>\n    public class HttpConfiguration : IDisposable\n    {\n        private readonly HttpRouteCollection _routes;\n        private readonly ConcurrentDictionary<object, object> _properties = new ConcurrentDictionary<object, object>();\n        private readonly MediaTypeFormatterCollection _formatters;\n        private readonly Collection<DelegatingHandler> _messageHandlers = new Collection<DelegatingHandler>();\n        private readonly HttpFilterCollection _filters = new HttpFilterCollection();\n\n        private IDependencyResolver _dependencyResolver = EmptyResolver.Instance;\n        private Action<HttpConfiguration> _initializer = DefaultInitializer;\n        private bool _initialized;\n\n        private bool _disposed;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpConfiguration\"/> class.\n        /// </summary>\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\",\n            Justification = \"The route collection is disposed as part of this class.\")]\n        public HttpConfiguration()\n            : this(new HttpRouteCollection(String.Empty))\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpConfiguration\"/> class.\n        /// </summary>\n        /// <param name=\"routes\">The <see cref=\"HttpRouteCollection\"/> to associate with this instance.</param>\n        public HttpConfiguration(HttpRouteCollection routes)\n        {\n            if (routes == null)\n            {\n                throw Error.ArgumentNull(\"routes\");\n            }\n\n            _routes = routes;\n            _formatters = DefaultFormatters(this);\n\n            Services = new DefaultServices(this);\n            ParameterBindingRules = DefaultActionValueBinder.GetDefaultParameterBinders();\n        }\n\n        private HttpConfiguration(HttpConfiguration configuration, HttpControllerSettings settings)\n        {\n            _routes = configuration.Routes;\n            _filters = configuration.Filters;\n            _messageHandlers = configuration.MessageHandlers;\n            _properties = configuration.Properties;\n            _dependencyResolver = configuration.DependencyResolver;\n            IncludeErrorDetailPolicy = configuration.IncludeErrorDetailPolicy;\n\n            // per-controller settings\n            Services = settings.IsServiceCollectionInitialized ? settings.Services : configuration.Services;\n            _formatters = settings.IsFormatterCollectionInitialized ? settings.Formatters : configuration.Formatters;\n            ParameterBindingRules = settings.IsParameterBindingRuleCollectionInitialized ? settings.ParameterBindingRules : configuration.ParameterBindingRules;\n\n            // Use the original configuration's initializer so that its Initialize()\n            // will perform the same logic on this clone as on the original.\n            Initializer = configuration.Initializer;\n\n            // create a new validator cache if the validator providers have changed\n            if (settings.IsServiceCollectionInitialized &&\n                !settings.Services.GetModelValidatorProviders().SequenceEqual(configuration.Services.GetModelValidatorProviders()))\n            {\n                ModelValidatorCache validatorCache = new ModelValidatorCache(new Lazy<IEnumerable<ModelValidatorProvider>>(() => Services.GetModelValidatorProviders()));\n                settings.Services.Replace(typeof(IModelValidatorCache), validatorCache);\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets the action that will perform final initialization\n        /// of the <see cref=\"HttpConfiguration\"/> instance before it is used\n        /// to process requests.\n        /// </summary>\n        /// <remarks>The Action returned by this property will be called to perform\n        /// final initialization of an <see cref=\"HttpConfiguration\"/> before it is\n        /// used to process a request.\n        /// <para>\n        /// The <see cref=\"HttpConfiguration\"/> passed to this action should be\n        /// considered immutable after the action returns.\n        /// </para>\n        /// </remarks>\n        public Action<HttpConfiguration> Initializer\n        {\n            get\n            {\n                return _initializer;\n            }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.ArgumentNull(\"value\");\n                }\n\n                _initializer = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets the list of filters that apply to all requests served using this HttpConfiguration instance.\n        /// </summary>\n        public HttpFilterCollection Filters\n        {\n            get { return _filters; }\n        }\n\n        /// <summary>\n        /// Gets an ordered list of <see cref=\"DelegatingHandler\"/> instances to be invoked as an\n        /// <see cref=\"HttpRequestMessage\"/> travels up the stack and an <see cref=\"HttpResponseMessage\"/> travels down in\n        /// stack in return. The handlers are invoked in a top-down fashion in the incoming path and bottom-up in the outgoing \n        /// path. That is, the first entry is invoked first for an incoming request message but last for an outgoing \n        /// response message.\n        /// </summary>\n        /// <value>\n        /// The message handler collection.\n        /// </value>\n        public Collection<DelegatingHandler> MessageHandlers\n        {\n            get { return _messageHandlers; }\n        }\n\n        /// <summary>\n        /// Gets the <see cref=\"HttpRouteCollection\"/> associated with this <see cref=\"HttpServer\"/> instance.\n        /// </summary>\n        /// <value>\n        /// The <see cref=\"HttpRouteCollection\"/>.\n        /// </value>\n        public HttpRouteCollection Routes\n        {\n            get { return _routes; }\n        }\n\n        /// <summary>\n        /// Gets the properties associated with this instance.\n        /// </summary>\n        public ConcurrentDictionary<object, object> Properties\n        {\n            get { return _properties; }\n        }\n\n        /// <summary>\n        /// Gets the root virtual path. The <see cref=\"VirtualPathRoot\"/> property always returns \n        /// \"/\" as the first character of the returned value.\n        /// </summary>\n        public string VirtualPathRoot\n        {\n            get { return _routes.VirtualPathRoot; }\n        }\n\n        /// <summary>\n        /// Gets or sets the dependency resolver associated with this <see cref=\"HttpConfiguration\"/>.\n        /// </summary>\n        public IDependencyResolver DependencyResolver\n        {\n            get { return _dependencyResolver; }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n\n                _dependencyResolver = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets the container of default services associated with this <see cref=\"HttpConfiguration\"/>.\n        /// Only supports the list of service types documented on <see cref=\"DefaultServices\"/>. For general\n        /// purpose types, please use <see cref=\"DependencyResolver\"/>.\n        /// </summary>\n        public ServicesContainer Services { get; internal set; }\n\n        /// <summary>\n        /// Top level hook for how parameters should be bound. \n        /// This should be respected by the IActionValueBinder. If a parameter is not claimed by the list, the IActionValueBinder still binds it. \n        /// </summary>\n        public ParameterBindingRulesCollection ParameterBindingRules { get; internal set; }\n\n        /// <summary>\n        /// Gets or sets a value indicating whether error details should be included in error messages.\n        /// </summary>\n        public IncludeErrorDetailPolicy IncludeErrorDetailPolicy { get; set; }\n\n        /// <summary>\n        /// Gets the media type formatters.\n        /// </summary>\n        public MediaTypeFormatterCollection Formatters\n        {\n            get { return _formatters; }\n        }\n\n        private static MediaTypeFormatterCollection DefaultFormatters(HttpConfiguration config)\n        {\n            var formatters = new MediaTypeFormatterCollection();\n\n            // Basic FormUrlFormatter does not support binding to a T. \n            // Use our JQuery formatter instead.\n            formatters.Add(new JQueryMvcFormUrlEncodedFormatter(config));\n\n            return formatters;\n        }\n\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"Caller owns the disposable object\")]\n        internal static HttpConfiguration ApplyControllerSettings(HttpControllerSettings settings, HttpConfiguration configuration)\n        {\n            if (!settings.IsFormatterCollectionInitialized && !settings.IsParameterBindingRuleCollectionInitialized && !settings.IsServiceCollectionInitialized)\n            {\n                return configuration;\n            }\n\n            // Create a clone of the original configuration, including its initialization rules.\n            // Invoking Initialize therefore initializes the cloned config the same way as the original.\n            HttpConfiguration newConfiguration = new HttpConfiguration(configuration, settings);\n            newConfiguration.Initializer(newConfiguration);\n            return newConfiguration;\n        }\n\n        private static void DefaultInitializer(HttpConfiguration configuration)\n        {\n            // Register the default IRequiredMemberSelector for formatters that haven't been assigned one\n            ModelMetadataProvider metadataProvider = configuration.Services.GetModelMetadataProvider();\n            IEnumerable<ModelValidatorProvider> validatorProviders = configuration.Services.GetModelValidatorProviders();\n            IRequiredMemberSelector defaultRequiredMemberSelector = new ModelValidationRequiredMemberSelector(metadataProvider, validatorProviders);\n\n            foreach (MediaTypeFormatter formatter in configuration.Formatters)\n            {\n                if (formatter.RequiredMemberSelector == null)\n                {\n                    formatter.RequiredMemberSelector = defaultRequiredMemberSelector;\n                }\n            }\n\n            // Initialize the tracing layer.\n            // This must be the last initialization code to execute\n            // because it alters the configuration and expects no\n            // further changes.  As a default service, we know it\n            // must be present.\n            ITraceManager traceManager = configuration.Services.GetTraceManager();\n            Contract.Assert(traceManager != null);\n            traceManager.Initialize(configuration);\n        }\n\n        /// <summary>\n        /// Invoke the Intializer hook. It is considered immutable from this point forward.\n        /// It's safe to call this multiple times. \n        /// </summary>\n        public void EnsureInitialized()\n        { \n            if (_initialized)\n            {\n                return;\n            }\n            _initialized = true;\n            Initializer(this);            \n        }\n\n        public void Dispose()\n        {\n            Dispose(true);\n            GC.SuppressFinalize(this);\n        }\n\n        protected virtual void Dispose(bool disposing)\n        {\n            if (!_disposed)\n            {\n                _disposed = true;\n\n                if (disposing)\n                {\n                    _routes.Dispose();\n                    DependencyResolver.Dispose();\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/HttpConfigurationExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.ModelBinding.Binders;\nusing System.Web.Http.Routing;\n\nnamespace System.Web.Http\n{\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class HttpConfigurationExtensions\n    {\n        /// <summary>\n        /// Register that the given parameter type on an Action is to be bound using the model binder.\n        /// </summary>\n        /// <param name=\"configuration\">configuration to be updated.</param>\n        /// <param name=\"type\">parameter type that binder is applied to</param>\n        /// <param name=\"binder\">a model binder</param>\n        public static void BindParameter(this HttpConfiguration configuration, Type type, IModelBinder binder)\n        {\n            if (configuration == null)\n            {\n                throw Error.ArgumentNull(\"configuration\");\n            }\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n            if (binder == null)\n            {\n                throw Error.ArgumentNull(\"binder\");\n            }\n\n            // Add a provider so that we can use this type recursively\n            // Be sure to insert at position 0 to preempt any eager binders (eg, MutableObjectBinder) that \n            // may eagerly claim all types.\n            configuration.Services.Insert(typeof(ModelBinderProvider), 0, new SimpleModelBinderProvider(type, binder));\n\n            // Add the binder to the list of rules. \n            // This ensures that the parameter binding will actually use model binding instead of Formatters.            \n            // Without this, the parameter binding system may see the parameter type is complex and choose\n            // to use formatters instead, in which case it would ignore the registered model binders. \n            configuration.ParameterBindingRules.Insert(0, type, param => param.BindWithModelBinding(binder));\n        }\n\n        /// <summary>\n        /// Maps the attribute-defined routes for the application.\n        /// </summary>\n        /// <param name=\"configuration\">The server configuration.</param>\n        // Corresponds to the MVC implementation of attribute routing in\n        // System.Web.Mvc.RouteCollectionAttributeRoutingExtensions.\n        public static void MapHttpAttributeRoutes(this HttpConfiguration configuration)\n        {\n            if (configuration == null)\n            {\n                throw new ArgumentNullException(\"configuration\");\n            }\n\n            AttributeRoutingMapper.MapAttributeRoutes(configuration, new DefaultInlineConstraintResolver(), new DefaultDirectRouteProvider());\n        }\n\n        /// <summary>\n        /// Maps the attribute-defined routes for the application.\n        /// </summary>\n        /// <param name=\"configuration\">The server configuration.</param>\n        /// <param name=\"constraintResolver\">\n        /// The <see cref=\"IInlineConstraintResolver\"/> to use for resolving inline constraints.\n        /// </param>\n        // Corresponds to the MVC implementation of attribute routing in\n        // System.Web.Mvc.RouteCollectionAttributeRoutingExtensions.\n        public static void MapHttpAttributeRoutes(this HttpConfiguration configuration,\n            IInlineConstraintResolver constraintResolver)\n        {\n            if (configuration == null)\n            {\n                throw new ArgumentNullException(\"configuration\");\n            }\n\n            if (constraintResolver == null)\n            {\n                throw new ArgumentNullException(\"constraintResolver\");\n            }\n\n            AttributeRoutingMapper.MapAttributeRoutes(configuration, constraintResolver, new DefaultDirectRouteProvider());\n        }\n\n        /// <summary>\n        /// Maps the attribute-defined routes for the application.\n        /// </summary>\n        /// <param name=\"configuration\">The server configuration.</param>\n        /// <param name=\"directRouteProvider\">\n        /// The <see cref=\"IDirectRouteProvider\"/> to use for discovering and building routes.\n        /// </param>\n        // Corresponds to the MVC implementation of attribute routing in\n        // System.Web.Mvc.RouteCollectionAttributeRoutingExtensions.\n        public static void MapHttpAttributeRoutes(\n            this HttpConfiguration configuration,\n            IDirectRouteProvider directRouteProvider)\n        {\n            if (configuration == null)\n            {\n                throw new ArgumentNullException(\"configuration\");\n            }\n\n            if (directRouteProvider == null)\n            {\n                throw new ArgumentNullException(\"directRouteProvider\");\n            }\n\n            AttributeRoutingMapper.MapAttributeRoutes(configuration, new DefaultInlineConstraintResolver(), directRouteProvider);\n        }\n\n        /// <summary>\n        /// Maps the attribute-defined routes for the application.\n        /// </summary>\n        /// <param name=\"configuration\">The server configuration.</param>\n        /// <param name=\"constraintResolver\">\n        /// The <see cref=\"IInlineConstraintResolver\"/> to use for resolving inline constraints.\n        /// </param>\n        /// <param name=\"directRouteProvider\">\n        /// The <see cref=\"IDirectRouteProvider\"/> to use for discovering and building routes.\n        /// </param>\n        // Corresponds to the MVC implementation of attribute routing in\n        // System.Web.Mvc.RouteCollectionAttributeRoutingExtensions.\n        public static void MapHttpAttributeRoutes(\n            this HttpConfiguration configuration,\n            IInlineConstraintResolver constraintResolver,\n            IDirectRouteProvider directRouteProvider)\n        {\n            if (configuration == null)\n            {\n                throw new ArgumentNullException(\"configuration\");\n            }\n\n            if (constraintResolver == null)\n            {\n                throw new ArgumentNullException(\"constraintResolver\");\n            }\n\n            if (directRouteProvider == null)\n            {\n                throw new ArgumentNullException(\"directRouteProvider\");\n            }\n\n            AttributeRoutingMapper.MapAttributeRoutes(configuration, constraintResolver, directRouteProvider);\n        }\n\n        // Test Hook for inspecting the route table generated by MapHttpAttributeRoutes. \n        // MapHttpAttributeRoutes doesn't return the route collection because it's an implementation detail\n        // that attr routes even generate a meaningful route collection. \n        // Public APIs can get similar functionality by querying the IHttpRoute for IReadOnlyCollection<IHttpRoute>.\n        internal static IReadOnlyCollection<IHttpRoute> GetAttributeRoutes(this HttpConfiguration configuration)\n        {\n            configuration.EnsureInitialized();\n\n            HttpRouteCollection routes = configuration.Routes;\n            foreach (IHttpRoute route in routes)\n            {\n                var attrRoute = route as IReadOnlyCollection<IHttpRoute>;\n                if (attrRoute != null)\n                {\n                    return attrRoute;\n                }\n            }\n            return null;\n        }\n\n        /// <summary>Enables suppression of the host's principal.</summary>\n        /// <param name=\"configuration\">The server configuration.</param>\n        /// <remarks>\n        /// When the host's principal is suppressed, the current principal is set to anonymous upon entering the\n        /// <see cref=\"HttpServer\"/>'s first message handler. As a result, any authentication performed by the host is\n        /// ignored. The remaining pipeline within the <see cref=\"HttpServer\"/>, including\n        /// <see cref=\"IAuthenticationFilter\"/>s, is then the exclusive authority for authentication.\n        /// </remarks>\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\",\n            Justification = \"Message handler should be disposed with parent configuration.\")]\n        public static void SuppressHostPrincipal(this HttpConfiguration configuration)\n        {\n            if (configuration == null)\n            {\n                throw new ArgumentNullException(\"configuration\");\n            }\n\n            Contract.Assert(configuration.MessageHandlers != null);\n            configuration.MessageHandlers.Insert(0, new SuppressHostPrincipalMessageHandler());\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/HttpDeleteAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Specifies that an action supports the DELETE HTTP method.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\n    public sealed class HttpDeleteAttribute : Attribute, IActionHttpMethodProvider\n    {\n        private static readonly Collection<HttpMethod> _supportedMethods = new Collection<HttpMethod>(new HttpMethod[] { HttpMethod.Delete });\n\n        public Collection<HttpMethod> HttpMethods\n        {\n            get\n            {\n                return _supportedMethods;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/HttpError.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.Properties;\nusing System.Xml;\nusing System.Xml.Schema;\nusing System.Xml.Serialization;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Defines a serializable container for storing error information. This information is stored \n    /// as key/value pairs. The dictionary keys to look up standard error information are available \n    /// on the <see cref=\"HttpErrorKeys\"/> type.\n    /// </summary>\n    [SuppressMessage(\"Microsoft.Naming\", \"CA1710:IdentifiersShouldHaveCorrectSuffix\", Justification = \"This type is only a dictionary to get the right serialization format\")]\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2237:MarkISerializableTypesWithSerializable\", Justification = \"DCS does not support IXmlSerializable types that are also marked as [Serializable]\")]\n    [XmlRoot(\"Error\")]\n    public sealed class HttpError : Dictionary<string, object>, IXmlSerializable\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpError\"/> class.\n        /// </summary>\n        public HttpError()\n            : base(StringComparer.OrdinalIgnoreCase)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpError\"/> class containing error message <paramref name=\"message\"/>.\n        /// </summary>\n        /// <param name=\"message\">The error message to associate with this instance.</param>\n        public HttpError(string message)\n            : this()\n        {\n            if (message == null)\n            {\n                throw Error.ArgumentNull(\"message\");\n            }\n\n            Message = message;\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpError\"/> class for <paramref name=\"exception\"/>.\n        /// </summary>\n        /// <param name=\"exception\">The exception to use for error information.</param>\n        /// <param name=\"includeErrorDetail\"><c>true</c> to include the exception information in the error; <c>false</c> otherwise</param>\n        public HttpError(Exception exception, bool includeErrorDetail)\n            : this()\n        {\n            if (exception == null)\n            {\n                throw Error.ArgumentNull(\"exception\");\n            }\n\n            Message = SRResources.ErrorOccurred;\n\n            if (includeErrorDetail)\n            {\n                Add(HttpErrorKeys.ExceptionMessageKey, exception.Message);\n                Add(HttpErrorKeys.ExceptionTypeKey, exception.GetType().FullName);\n                Add(HttpErrorKeys.StackTraceKey, exception.StackTrace);\n                if (exception.InnerException != null)\n                {\n                    Add(HttpErrorKeys.InnerExceptionKey, new HttpError(exception.InnerException, includeErrorDetail));\n                }\n            }\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpError\"/> class for <paramref name=\"modelState\"/>.\n        /// </summary>\n        /// <param name=\"modelState\">The invalid model state to use for error information.</param>\n        /// <param name=\"includeErrorDetail\"><c>true</c> to include exception messages in the error; <c>false</c> otherwise</param>\n        public HttpError(ModelStateDictionary modelState, bool includeErrorDetail)\n            : this()\n        {\n            if (modelState == null)\n            {\n                throw Error.ArgumentNull(\"modelState\");\n            }\n\n            if (modelState.IsValid)\n            {\n                throw Error.Argument(\"modelState\", SRResources.ValidModelState);\n            }\n\n            Message = SRResources.BadRequest;\n\n            HttpError modelStateError = new HttpError();\n            foreach (KeyValuePair<string, ModelState> keyModelStatePair in modelState)\n            {\n                string key = keyModelStatePair.Key;\n                ModelErrorCollection errors = keyModelStatePair.Value.Errors;\n                if (errors != null && errors.Count > 0)\n                {\n                    IEnumerable<string> errorMessages = errors.Select(error =>\n                    {\n                        if (includeErrorDetail && error.Exception != null)\n                        {\n                            return error.Exception.Message;\n                        }\n                        else\n                        {\n                            return String.IsNullOrEmpty(error.ErrorMessage) ? SRResources.ErrorOccurred : error.ErrorMessage;\n                        }\n                    }).ToArray();\n                    modelStateError.Add(key, errorMessages);\n                }\n            }\n\n            Add(HttpErrorKeys.ModelStateKey, modelStateError);\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpError\"/> class containing error message <paramref name=\"message\"/> \n        /// and error message detail <paramref name=\"messageDetail\"/>.\n        /// </summary>\n        /// <param name=\"message\">The error message to associate with this instance.</param>\n        /// <param name=\"messageDetail\">The error message detail to associate with this instance.</param>\n        internal HttpError(string message, string messageDetail)\n            : this(message)\n        {\n            if (messageDetail == null)\n            {\n                throw Error.ArgumentNull(\"message\");\n            }\n\n            Add(HttpErrorKeys.MessageDetailKey, messageDetail);\n        }\n\n        /// <summary>\n        /// The high-level, user-visible message explaining the cause of the error. Information carried in this field \n        /// should be considered public in that it will go over the wire regardless of the <see cref=\"IncludeErrorDetailPolicy\"/>. \n        /// As a result care should be taken not to disclose sensitive information about the server or the application.\n        /// </summary>\n        public string Message\n        {\n            get { return GetPropertyValue<String>(HttpErrorKeys.MessageKey); }\n            set { this[HttpErrorKeys.MessageKey] = value; }\n        }\n\n        /// <summary>\n        /// The <see cref=\"ModelState\"/> containing information about the errors that occurred during model binding.\n        /// </summary>\n        /// <remarks>\n        /// The inclusion of <see cref=\"System.Exception\"/> information carried in the <see cref=\"ModelState\"/> is\n        /// controlled by the <see cref=\"IncludeErrorDetailPolicy\"/>. All other information in the <see cref=\"ModelState\"/>\n        /// should be considered public in that it will go over the wire. As a result care should be taken not to \n        /// disclose sensitive information about the server or the application.\n        /// </remarks>\n        public HttpError ModelState\n        {\n            get { return GetPropertyValue<HttpError>(HttpErrorKeys.ModelStateKey); }\n        }\n\n        /// <summary>\n        /// A detailed description of the error intended for the developer to understand exactly what failed.\n        /// </summary>\n        /// <remarks>\n        /// The inclusion of this field is controlled by the <see cref=\"IncludeErrorDetailPolicy\"/>. The \n        /// field is expected to contain information about the server or the application that should not \n        /// be disclosed broadly.\n        /// </remarks>\n        public string MessageDetail\n        {\n            get { return GetPropertyValue<String>(HttpErrorKeys.MessageDetailKey); }\n            set { this[HttpErrorKeys.MessageDetailKey] = value; }\n        }\n\n        /// <summary>\n        /// The message of the <see cref=\"System.Exception\"/> if available.\n        /// </summary>\n        /// <remarks>\n        /// The inclusion of this field is controlled by the <see cref=\"IncludeErrorDetailPolicy\"/>. The \n        /// field is expected to contain information about the server or the application that should not \n        /// be disclosed broadly.\n        /// </remarks>\n        public string ExceptionMessage\n        {\n            get { return GetPropertyValue<String>(HttpErrorKeys.ExceptionMessageKey); }\n            set { this[HttpErrorKeys.ExceptionMessageKey] = value; }\n        }\n\n        /// <summary>\n        /// The type of the <see cref=\"System.Exception\"/> if available.\n        /// </summary>\n        /// <remarks>\n        /// The inclusion of this field is controlled by the <see cref=\"IncludeErrorDetailPolicy\"/>. The \n        /// field is expected to contain information about the server or the application that should not \n        /// be disclosed broadly.\n        /// </remarks>\n        public string ExceptionType\n        {\n            get { return GetPropertyValue<String>(HttpErrorKeys.ExceptionTypeKey); }\n            set { this[HttpErrorKeys.ExceptionTypeKey] = value; }\n        }\n\n        /// <summary>\n        /// The stack trace information associated with this instance if available.\n        /// </summary>\n        /// <remarks>\n        /// The inclusion of this field is controlled by the <see cref=\"IncludeErrorDetailPolicy\"/>. The \n        /// field is expected to contain information about the server or the application that should not \n        /// be disclosed broadly.\n        /// </remarks>\n        public string StackTrace\n        {\n            get { return GetPropertyValue<String>(HttpErrorKeys.StackTraceKey); }\n            set { this[HttpErrorKeys.StackTraceKey] = value; }\n        }\n\n        /// <summary>\n        /// The inner <see cref=\"System.Exception\"/> associated with this instance if available.\n        /// </summary>\n        /// <remarks>\n        /// The inclusion of this field is controlled by the <see cref=\"IncludeErrorDetailPolicy\"/>. The \n        /// field is expected to contain information about the server or the application that should not \n        /// be disclosed broadly.\n        /// </remarks>\n        public HttpError InnerException\n        {\n            get { return GetPropertyValue<HttpError>(HttpErrorKeys.InnerExceptionKey); }\n        }\n\n        /// <summary>\n        /// Gets a particular property value from this error instance.\n        /// </summary>\n        /// <typeparam name=\"TValue\">The type of the property.</typeparam>\n        /// <param name=\"key\">The name of the error property.</param>\n        /// <returns>The value of the error property.</returns>\n        public TValue GetPropertyValue<TValue>(string key)\n        {\n            TValue value;\n            if (this.TryGetValue(key, out value))\n            {\n                return value;\n            }\n            return default(TValue);\n        }\n\n        XmlSchema IXmlSerializable.GetSchema()\n        {\n            return null;\n        }\n\n        void IXmlSerializable.ReadXml(XmlReader reader)\n        {\n            if (reader.IsEmptyElement)\n            {\n                reader.Read();\n                return;\n            }\n\n            reader.ReadStartElement();\n            while (reader.NodeType != System.Xml.XmlNodeType.EndElement)\n            {\n                string key = XmlConvert.DecodeName(reader.LocalName);\n                string value = reader.ReadInnerXml();\n\n                this.Add(key, value);\n                reader.MoveToContent();\n            }\n            reader.ReadEndElement();\n        }\n\n        void IXmlSerializable.WriteXml(XmlWriter writer)\n        {\n            foreach (KeyValuePair<string, object> keyValuePair in this)\n            {\n                string key = keyValuePair.Key;\n                object value = keyValuePair.Value;\n                writer.WriteStartElement(XmlConvert.EncodeLocalName(key));\n                if (value != null)\n                {\n                    HttpError innerError = value as HttpError;\n                    if (innerError == null)\n                    {\n                        writer.WriteValue(value);\n                    }\n                    else\n                    {\n                        ((IXmlSerializable)innerError).WriteXml(writer);\n                    }\n                }\n                writer.WriteEndElement();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/HttpErrorKeys.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Provides keys to look up error information stored in the <see cref=\"HttpError\"/> dictionary.\n    /// </summary>\n    public static class HttpErrorKeys\n    {\n        /// <summary>\n        /// Provides a key for the Message.\n        /// </summary>\n        public static readonly string MessageKey = \"Message\";\n\n        /// <summary>\n        /// Provides a key for the MessageDetail.\n        /// </summary>\n        public static readonly string MessageDetailKey = \"MessageDetail\";\n\n        /// <summary>\n        /// Provides a key for the ModelState.\n        /// </summary>\n        public static readonly string ModelStateKey = \"ModelState\";\n\n        /// <summary>\n        /// Provides a key for the ExceptionMessage.\n        /// </summary>\n        public static readonly string ExceptionMessageKey = \"ExceptionMessage\";\n\n        /// <summary>\n        /// Provides a key for the ExceptionType.\n        /// </summary>\n        public static readonly string ExceptionTypeKey = \"ExceptionType\";\n\n        /// <summary>\n        /// Provides a key for the StackTrace.\n        /// </summary>\n        public static readonly string StackTraceKey = \"StackTrace\";\n\n        /// <summary>\n        /// Provides a key for the InnerException.\n        /// </summary>\n        public static readonly string InnerExceptionKey = \"InnerException\";\n\n        /// <summary>\n        /// Provides a key for the MessageLanguage.\n        /// </summary>\n        public static readonly string MessageLanguageKey = \"MessageLanguage\";\n\n        /// <summary>\n        /// Provides a key for the ErrorCode.\n        /// </summary>\n        public static readonly string ErrorCodeKey = \"ErrorCode\";\n    }\n}"
  },
  {
    "path": "src/System.Web.Http/HttpGetAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Specifies that an action supports the GET HTTP method.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\n    public sealed class HttpGetAttribute : Attribute, IActionHttpMethodProvider\n    {\n        private static readonly Collection<HttpMethod> _supportedMethods = new Collection<HttpMethod>(new HttpMethod[] { HttpMethod.Get });\n\n        public Collection<HttpMethod> HttpMethods\n        {\n            get\n            {\n                return _supportedMethods;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/HttpHeadAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Specifies that an action supports the HEAD HTTP method.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\n    public sealed class HttpHeadAttribute : Attribute, IActionHttpMethodProvider\n    {\n        private static readonly Collection<HttpMethod> _supportedMethods = new Collection<HttpMethod>(new HttpMethod[] { HttpMethod.Head });\n\n        public Collection<HttpMethod> HttpMethods\n        {\n            get\n            {\n                return _supportedMethods;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/HttpOptionsAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Specifies that an action supports the OPTIONS HTTP method.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\n    public sealed class HttpOptionsAttribute : Attribute, IActionHttpMethodProvider\n    {\n        private static readonly Collection<HttpMethod> _supportedMethods = new Collection<HttpMethod>(new HttpMethod[] { HttpMethod.Options });\n\n        public Collection<HttpMethod> HttpMethods\n        {\n            get\n            {\n                return _supportedMethods;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/HttpPatchAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Specifies that an action supports the PATCH HTTP method.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\n    public sealed class HttpPatchAttribute : Attribute, IActionHttpMethodProvider\n    {\n        private static readonly Collection<HttpMethod> _supportedMethods = new Collection<HttpMethod>(new HttpMethod[] { new HttpMethod(\"PATCH\") });\n\n        public Collection<HttpMethod> HttpMethods\n        {\n            get\n            {\n                return _supportedMethods;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/HttpPostAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Specifies that an action supports the POST HTTP method.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\n    public sealed class HttpPostAttribute : Attribute, IActionHttpMethodProvider\n    {\n        private static readonly Collection<HttpMethod> _supportedMethods = new Collection<HttpMethod>(new HttpMethod[] { HttpMethod.Post });\n\n        public Collection<HttpMethod> HttpMethods\n        {\n            get\n            {\n                return _supportedMethods;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/HttpPutAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Specifies that an action supports the PUT HTTP method.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\n    public sealed class HttpPutAttribute : Attribute, IActionHttpMethodProvider\n    {\n        private static readonly Collection<HttpMethod> _supportedMethods = new Collection<HttpMethod>(new HttpMethod[] { HttpMethod.Put });\n\n        public Collection<HttpMethod> HttpMethods\n        {\n            get\n            {\n                return _supportedMethods;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/HttpRequestMessageExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Security.Cryptography.X509Certificates;\nusing System.Threading;\nusing System.Web.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Dependencies;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Results;\nusing System.Web.Http.Routing;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// Provides extension methods for the <see cref=\"HttpRequestMessage\"/> class.\n    /// </summary>\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class HttpRequestMessageExtensions\n    {\n        /// <summary>\n        /// Gets the <see cref=\"HttpConfiguration\"/> for the given request.\n        /// </summary>\n        /// <param name=\"request\">The HTTP request.</param>\n        /// <returns>The <see cref=\"HttpConfiguration\"/>.</returns>\n        public static HttpConfiguration GetConfiguration(this HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            HttpRequestContext requestContext = GetRequestContext(request);\n\n            if (requestContext != null)\n            {\n                return requestContext.Configuration;\n            }\n\n            return request.LegacyGetConfiguration();\n        }\n\n        internal static HttpConfiguration LegacyGetConfiguration(this HttpRequestMessage request)\n        {\n            return request.GetProperty<HttpConfiguration>(HttpPropertyKeys.HttpConfigurationKey);\n        }\n\n        /// <summary>\n        /// Sets the <see cref=\"HttpConfiguration\"/> for the given request.\n        /// </summary>\n        /// <param name=\"request\">The HTTP request.</param>\n        /// <param name=\"configuration\">The <see cref=\"HttpConfiguration\"/> to set.</param>\n        public static void SetConfiguration(this HttpRequestMessage request, HttpConfiguration configuration)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n            if (configuration == null)\n            {\n                throw Error.ArgumentNull(\"configuration\");\n            }\n\n            HttpRequestContext requestContext = GetRequestContext(request);\n\n            if (requestContext != null)\n            {\n                requestContext.Configuration = configuration;\n            }\n\n            request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration;\n        }\n\n        /// <summary>\n        /// Gets the dependency resolver scope associated with this <see cref=\"HttpRequestMessage\"/>.\n        /// Services which are retrieved from this scope will be released when the request is\n        /// cleaned up by the framework.\n        /// </summary>\n        /// <param name=\"request\">The HTTP request.</param>\n        /// <returns>The <see cref=\"IDependencyScope\"/> for the given request.</returns>\n        public static IDependencyScope GetDependencyScope(this HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            IDependencyScope result;\n            if (!request.Properties.TryGetValue<IDependencyScope>(HttpPropertyKeys.DependencyScope, out result))\n            {\n                IDependencyResolver dependencyResolver = request.GetConfiguration().DependencyResolver;\n                result = dependencyResolver.BeginScope();\n                if (result == null)\n                {\n                    throw Error.InvalidOperation(SRResources.DependencyResolver_BeginScopeReturnsNull, dependencyResolver.GetType().Name);\n                }\n                request.Properties[HttpPropertyKeys.DependencyScope] = result;\n                request.RegisterForDispose(result);\n            }\n\n            return result;\n        }\n\n        /// <summary>Gets the <see cref=\"HttpRequestContext\"/> associated with this request.</summary>\n        /// <param name=\"request\">The HTTP request.</param>\n        /// <returns>The <see cref=\"HttpRequestContext\"/> associated with this request.</returns>\n        public static HttpRequestContext GetRequestContext(this HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            return request.GetProperty<HttpRequestContext>(HttpPropertyKeys.RequestContextKey);\n        }\n\n        /// <summary>Gets an <see cref=\"HttpRequestContext\"/> associated with this request.</summary>\n        /// <param name=\"request\">The HTTP request.</param>\n        /// <param name=\"context\">The <see cref=\"HttpRequestContext\"/> to associate with this request.</param>\n        public static void SetRequestContext(this HttpRequestMessage request, HttpRequestContext context)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            if (context == null)\n            {\n                throw Error.ArgumentNull(\"context\");\n            }\n\n            request.Properties[HttpPropertyKeys.RequestContextKey] = context;\n        }\n\n        /// <summary>\n        /// Gets the <see cref=\"System.Threading.SynchronizationContext\"/> for the given request or null if not available.\n        /// </summary>\n        /// <param name=\"request\">The HTTP request.</param>\n        /// <returns>The <see cref=\"System.Threading.SynchronizationContext\"/> or null.</returns>\n        public static SynchronizationContext GetSynchronizationContext(this HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            return request.GetProperty<SynchronizationContext>(HttpPropertyKeys.SynchronizationContextKey);\n        }\n\n        internal static void SetSynchronizationContext(this HttpRequestMessage request, SynchronizationContext synchronizationContext)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            request.Properties[HttpPropertyKeys.SynchronizationContextKey] = synchronizationContext;\n        }\n\n        /// <summary>\n        /// Gets the current <see cref=\"T:System.Security.Cryptography.X509Certificates.X509Certificate2\"/> or null if not available.\n        /// </summary>\n        /// <param name=\"request\">The HTTP request.</param>\n        /// <returns>The <see cref=\"T:System.Security.Cryptography.X509Certificates.X509Certificate2\"/> or null.</returns>\n        public static X509Certificate2 GetClientCertificate(this HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            HttpRequestContext requestContext = GetRequestContext(request);\n\n            if (requestContext != null)\n            {\n                return requestContext.ClientCertificate;\n            }\n\n            return request.LegacyGetClientCertificate();\n        }\n\n        internal static X509Certificate2 LegacyGetClientCertificate(this HttpRequestMessage request)\n        {\n            X509Certificate2 result = null;\n\n            if (!request.Properties.TryGetValue(HttpPropertyKeys.ClientCertificateKey, out result))\n            {\n                // now let us get out the delegate and try to invoke it\n                Func<HttpRequestMessage, X509Certificate2> retrieveCertificate;\n\n                if (request.Properties.TryGetValue(HttpPropertyKeys.RetrieveClientCertificateDelegateKey, out retrieveCertificate))\n                {\n                    result = retrieveCertificate(request);\n\n                    if (result != null)\n                    {\n                        request.Properties.Add(HttpPropertyKeys.ClientCertificateKey, result);\n                    }\n                }\n            }\n\n            return result;\n        }\n\n        /// <summary>\n        /// Gets the <see cref=\"System.Web.Http.Routing.IHttpRouteData\"/> for the given request or null if not available.\n        /// </summary>\n        /// <param name=\"request\">The HTTP request.</param>\n        /// <returns>The <see cref=\"System.Web.Http.Routing.IHttpRouteData\"/> or null.</returns>\n        public static IHttpRouteData GetRouteData(this HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            HttpRequestContext requestContext = GetRequestContext(request);\n\n            if (requestContext != null)\n            {\n                return requestContext.RouteData;\n            }\n\n            return request.LegacyGetRouteData();\n        }\n\n        internal static IHttpRouteData LegacyGetRouteData(this HttpRequestMessage request)\n        {\n            return request.GetProperty<IHttpRouteData>(HttpPropertyKeys.HttpRouteDataKey);\n        }\n\n        /// <summary>\n        /// Sets the <see cref=\"System.Web.Http.Routing.IHttpRouteData\"/> for the given request.\n        /// </summary>\n        /// <param name=\"request\">The HTTP request.</param>\n        /// <param name=\"routeData\">The HTTP route data.</param>\n        public static void SetRouteData(this HttpRequestMessage request, IHttpRouteData routeData)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            if (routeData == null)\n            {\n                throw Error.ArgumentNull(\"routeData\");\n            }\n\n            HttpRequestContext requestContext = GetRequestContext(request);\n\n            if (requestContext != null)\n            {\n                requestContext.RouteData = routeData;\n            }\n\n            request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData;\n        }\n\n        /// <summary>\n        /// Gets the <see cref=\"System.Web.Http.Controllers.HttpActionDescriptor\"/> selected for the given request or null if not available.\n        /// </summary>\n        /// <param name=\"request\">The HTTP request.</param>\n        /// <returns>The <see cref=\"System.Web.Http.Controllers.HttpActionDescriptor\"/> or null.</returns>\n        public static HttpActionDescriptor GetActionDescriptor(this HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            return request.GetProperty<HttpActionDescriptor>(HttpPropertyKeys.HttpActionDescriptorKey);\n        }\n\n        internal static void SetActionDescriptor(this HttpRequestMessage request, HttpActionDescriptor actionDescriptor)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            request.Properties[HttpPropertyKeys.HttpActionDescriptorKey] = actionDescriptor;\n        }\n\n        private static T GetProperty<T>(this HttpRequestMessage request, string key)\n        {\n            T value;\n            request.Properties.TryGetValue(key, out value);\n            return value;\n        }\n\n        /// <summary>\n        /// Helper method for creating an <see cref=\"HttpResponseMessage\"/> message with a \"416 (Requested Range Not Satisfiable)\" status code.\n        /// This response can be used in combination with the <see cref=\"ByteRangeStreamContent\"/> to indicate that the requested range or\n        /// ranges do not overlap with the current resource. The response contains a \"Content-Range\" header indicating the valid upper and lower\n        /// bounds for requested ranges.\n        /// </summary>\n        /// <param name=\"request\">The request.</param>\n        /// <param name=\"invalidByteRangeException\">An <see cref=\"InvalidByteRangeException\"/> instance, typically thrown by a\n        /// <see cref=\"ByteRangeStreamContent\"/> instance.</param>\n        /// <returns>An 416 (Requested Range Not Satisfiable) error response with a Content-Range header indicating the valid range.</returns>\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"Caller will dispose\")]\n        public static HttpResponseMessage CreateErrorResponse(this HttpRequestMessage request, InvalidByteRangeException invalidByteRangeException)\n        {\n            if (invalidByteRangeException == null)\n            {\n                throw Error.ArgumentNull(\"invalidByteRangeException\");\n            }\n\n            HttpResponseMessage rangeNotSatisfiableResponse = request.CreateErrorResponse(HttpStatusCode.RequestedRangeNotSatisfiable, invalidByteRangeException);\n            rangeNotSatisfiableResponse.Content.Headers.ContentRange = invalidByteRangeException.ContentRange;\n            return rangeNotSatisfiableResponse;\n        }\n\n        /// <summary>\n        /// Helper method that performs content negotiation and creates a <see cref=\"HttpResponseMessage\"/> representing an error\n        /// with an instance of <see cref=\"ObjectContent{T}\"/> wrapping an <see cref=\"HttpError\"/> with message <paramref name=\"message\"/>.\n        /// If no formatter is found, this method returns a response with status 406 NotAcceptable.\n        /// </summary>\n        /// <remarks>\n        /// This method requires that <paramref name=\"request\"/> has been associated with an instance of\n        /// <see cref=\"HttpConfiguration\"/>.\n        /// </remarks>\n        /// <param name=\"request\">The request.</param>\n        /// <param name=\"statusCode\">The status code of the created response.</param>\n        /// <param name=\"message\">The error message.</param>\n        /// <returns>An error response with error message <paramref name=\"message\"/> and status code <paramref name=\"statusCode\"/>.</returns>\n        public static HttpResponseMessage CreateErrorResponse(this HttpRequestMessage request, HttpStatusCode statusCode, string message)\n        {\n            return request.CreateErrorResponse(statusCode, new HttpError(message));\n        }\n\n        /// <summary>\n        /// Helper method that performs content negotiation and creates a <see cref=\"HttpResponseMessage\"/> representing an error\n        /// with an instance of <see cref=\"ObjectContent{T}\"/> wrapping an <see cref=\"HttpError\"/> with message <paramref name=\"message\"/>\n        /// and message detail <paramref name=\"messageDetail\"/>.If no formatter is found, this method returns a response with\n        /// status 406 NotAcceptable.\n        /// </summary>\n        /// <remarks>\n        /// This method requires that <paramref name=\"request\"/> has been associated with an instance of\n        /// <see cref=\"HttpConfiguration\"/>.\n        /// </remarks>\n        /// <param name=\"request\">The request.</param>\n        /// <param name=\"statusCode\">The status code of the created response.</param>\n        /// <param name=\"message\">The error message. This message will always be seen by clients.</param>\n        /// <param name=\"messageDetail\">The error message detail. This message will only be seen by clients if we should include error detail.</param>\n        /// <returns>An error response with error message <paramref name=\"message\"/> and message detail <paramref name=\"messageDetail\"/>\n        /// and status code <paramref name=\"statusCode\"/>.</returns>\n        internal static HttpResponseMessage CreateErrorResponse(this HttpRequestMessage request, HttpStatusCode statusCode, string message, string messageDetail)\n        {\n            return request.CreateErrorResponse(statusCode, includeErrorDetail => includeErrorDetail ? new HttpError(message, messageDetail) : new HttpError(message));\n        }\n\n        /// <summary>\n        /// Helper method that performs content negotiation and creates a <see cref=\"HttpResponseMessage\"/> representing an error\n        /// with an instance of <see cref=\"ObjectContent{T}\"/> wrapping an <see cref=\"HttpError\"/> with error message <paramref name=\"message\"/>\n        /// for exception <paramref name=\"exception\"/>. If no formatter is found, this method returns a response with status 406 NotAcceptable.\n        /// </summary>\n        /// <remarks>\n        /// This method requires that <paramref name=\"request\"/> has been associated with an instance of\n        /// <see cref=\"HttpConfiguration\"/>.\n        /// </remarks>\n        /// <param name=\"request\">The request.</param>\n        /// <param name=\"statusCode\">The status code of the created response.</param>\n        /// <param name=\"message\">The error message.</param>\n        /// <param name=\"exception\">The exception.</param>\n        /// <returns>An error response for <paramref name=\"exception\"/> with error message <paramref name=\"message\"/>\n        /// and status code <paramref name=\"statusCode\"/>.</returns>\n        public static HttpResponseMessage CreateErrorResponse(this HttpRequestMessage request, HttpStatusCode statusCode, string message, Exception exception)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            return request.CreateErrorResponse(statusCode, includeErrorDetail => new HttpError(exception, includeErrorDetail) { Message = message });\n        }\n\n        /// <summary>\n        /// Helper method that performs content negotiation and creates a <see cref=\"HttpResponseMessage\"/> representing an error\n        /// with an instance of <see cref=\"ObjectContent{T}\"/> wrapping an <see cref=\"HttpError\"/> for exception <paramref name=\"exception\"/>.\n        /// If no formatter is found, this method returns a response with status 406 NotAcceptable.\n        /// </summary>\n        /// <remarks>\n        /// This method requires that <paramref name=\"request\"/> has been associated with an instance of\n        /// <see cref=\"HttpConfiguration\"/>.\n        /// </remarks>\n        /// <param name=\"request\">The request.</param>\n        /// <param name=\"statusCode\">The status code of the created response.</param>\n        /// <param name=\"exception\">The exception.</param>\n        /// <returns>An error response for <paramref name=\"exception\"/> with status code <paramref name=\"statusCode\"/>.</returns>\n        public static HttpResponseMessage CreateErrorResponse(this HttpRequestMessage request, HttpStatusCode statusCode, Exception exception)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            return request.CreateErrorResponse(statusCode, includeErrorDetail => new HttpError(exception, includeErrorDetail));\n        }\n\n        /// <summary>\n        /// Helper method that performs content negotiation and creates a <see cref=\"HttpResponseMessage\"/> representing an error\n        /// with an instance of <see cref=\"ObjectContent{T}\"/> wrapping an <see cref=\"HttpError\"/> for model state <paramref name=\"modelState\"/>.\n        /// If no formatter is found, this method returns a response with status 406 NotAcceptable.\n        /// </summary>\n        /// <remarks>\n        /// This method requires that <paramref name=\"request\"/> has been associated with an instance of\n        /// <see cref=\"HttpConfiguration\"/>.\n        /// </remarks>\n        /// <param name=\"request\">The request.</param>\n        /// <param name=\"statusCode\">The status code of the created response.</param>\n        /// <param name=\"modelState\">The model state.</param>\n        /// <returns>An error response for <paramref name=\"modelState\"/> with status code <paramref name=\"statusCode\"/>.</returns>\n        public static HttpResponseMessage CreateErrorResponse(this HttpRequestMessage request, HttpStatusCode statusCode, ModelStateDictionary modelState)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            return request.CreateErrorResponse(statusCode, includeErrorDetail => new HttpError(modelState, includeErrorDetail));\n        }\n\n        /// <summary>\n        /// Helper method that performs content negotiation and creates a <see cref=\"HttpResponseMessage\"/> representing an error\n        /// with an instance of <see cref=\"ObjectContent{T}\"/> wrapping <paramref name=\"error\"/> as the content. If no formatter\n        /// is found, this method returns a response with status 406 NotAcceptable.\n        /// </summary>\n        /// <remarks>\n        /// This method requires that <paramref name=\"request\"/> has been associated with an instance of\n        /// <see cref=\"HttpConfiguration\"/>.\n        /// </remarks>\n        /// <param name=\"request\">The request.</param>\n        /// <param name=\"statusCode\">The status code of the created response.</param>\n        /// <param name=\"error\">The error to wrap.</param>\n        /// <returns>An error response wrapping <paramref name=\"error\"/> with status code <paramref name=\"statusCode\"/>.</returns>\n        public static HttpResponseMessage CreateErrorResponse(this HttpRequestMessage request, HttpStatusCode statusCode, HttpError error)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            return request.CreateErrorResponse(statusCode, includeErrorDetail => error);\n        }\n\n        private static HttpResponseMessage CreateErrorResponse(this HttpRequestMessage request, HttpStatusCode statusCode, Func<bool, HttpError> errorCreator)\n        {\n            HttpConfiguration configuration = request.GetConfiguration();\n\n            HttpError error = errorCreator(request.ShouldIncludeErrorDetail());\n\n            // CreateErrorResponse should never fail, even if there is no configuration associated with the request\n            // In that case, use the default HttpConfiguration to con-neg the response media type\n            if (configuration == null)\n            {\n                using (HttpConfiguration defaultConfig = new HttpConfiguration())\n                {\n                    return request.CreateResponse<HttpError>(statusCode, error, defaultConfig);\n                }\n            }\n            else\n            {\n                return request.CreateResponse<HttpError>(statusCode, error, configuration);\n            }\n        }\n\n        /// <summary>\n        /// Helper method that performs content negotiation and creates a <see cref=\"HttpResponseMessage\"/> with an instance\n        /// of <see cref=\"ObjectContent{T}\"/> as the content and <see cref=\"System.Net.HttpStatusCode.OK\"/> as the status code\n        /// if a formatter can be found. If no formatter is found, this method returns a response with status 406 NotAcceptable.\n        /// This forwards the call to <see cref=\"CreateResponse{T}(HttpRequestMessage, HttpStatusCode, T, HttpConfiguration)\"/> with\n        /// <see cref=\"System.Net.HttpStatusCode.OK\"/> status code and a <c>null</c> configuration.\n        /// </summary>\n        /// <remarks>\n        /// This method requires that <paramref name=\"request\"/> has been associated with an instance of\n        /// <see cref=\"HttpConfiguration\"/>.\n        /// </remarks>\n        /// <typeparam name=\"T\">The type of the value.</typeparam>\n        /// <param name=\"request\">The request.</param>\n        /// <param name=\"value\">The value to wrap. Can be <c>null</c>.</param>\n        /// <returns>A response wrapping <paramref name=\"value\"/> with <see cref=\"System.Net.HttpStatusCode.OK\"/> status code.</returns>\n        public static HttpResponseMessage CreateResponse<T>(this HttpRequestMessage request, T value)\n        {\n            return request.CreateResponse<T>(HttpStatusCode.OK, value, configuration: null);\n        }\n\n        /// <summary>\n        /// Helper method that performs content negotiation and creates a <see cref=\"HttpResponseMessage\"/> with an instance\n        /// of <see cref=\"ObjectContent{T}\"/> as the content if a formatter can be found. If no formatter is found, this\n        /// method returns a response with status 406 NotAcceptable. This forwards the call to\n        /// <see cref=\"CreateResponse{T}(HttpRequestMessage, HttpStatusCode, T, HttpConfiguration)\"/> with a <c>null</c>\n        /// configuration.\n        /// </summary>\n        /// <remarks>\n        /// This method requires that <paramref name=\"request\"/> has been associated with an instance of\n        /// <see cref=\"HttpConfiguration\"/>.\n        /// </remarks>\n        /// <typeparam name=\"T\">The type of the value.</typeparam>\n        /// <param name=\"request\">The request.</param>\n        /// <param name=\"statusCode\">The status code of the created response.</param>\n        /// <param name=\"value\">The value to wrap. Can be <c>null</c>.</param>\n        /// <returns>A response wrapping <paramref name=\"value\"/> with <paramref name=\"statusCode\"/>.</returns>\n        public static HttpResponseMessage CreateResponse<T>(this HttpRequestMessage request, HttpStatusCode statusCode, T value)\n        {\n            return request.CreateResponse<T>(statusCode, value, configuration: null);\n        }\n\n        /// <summary>\n        /// Helper method that performs content negotiation and creates a <see cref=\"HttpResponseMessage\"/> with an instance\n        /// of <see cref=\"ObjectContent{T}\"/> as the content if a formatter can be found. If no formatter is found, this\n        /// method returns a response with status 406 NotAcceptable.\n        /// </summary>\n        /// <remarks>\n        /// This method will use the provided <paramref name=\"configuration\"/> or it will get the\n        /// <see cref=\"HttpConfiguration\"/> instance associated with <paramref name=\"request\"/>.\n        /// </remarks>\n        /// <typeparam name=\"T\">The type of the value.</typeparam>\n        /// <param name=\"request\">The request.</param>\n        /// <param name=\"statusCode\">The status code of the created response.</param>\n        /// <param name=\"value\">The value to wrap. Can be <c>null</c>.</param>\n        /// <param name=\"configuration\">The configuration to use. Can be <c>null</c>.</param>\n        /// <returns>A response wrapping <paramref name=\"value\"/> with <paramref name=\"statusCode\"/>.</returns>\n        public static HttpResponseMessage CreateResponse<T>(this HttpRequestMessage request, HttpStatusCode statusCode, T value, HttpConfiguration configuration)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            configuration = configuration ?? request.GetConfiguration();\n            if (configuration == null)\n            {\n                throw Error.InvalidOperation(SRResources.HttpRequestMessageExtensions_NoConfiguration);\n            }\n\n            IContentNegotiator contentNegotiator = configuration.Services.GetContentNegotiator();\n            if (contentNegotiator == null)\n            {\n                throw Error.InvalidOperation(SRResources.HttpRequestMessageExtensions_NoContentNegotiator, typeof(IContentNegotiator).FullName);\n            }\n\n            IEnumerable<MediaTypeFormatter> formatters = configuration.Formatters;\n\n            return NegotiatedContentResult<T>.Execute(statusCode, value, contentNegotiator, request, formatters);\n        }\n\n        /// <summary>\n        /// Helper method that creates a <see cref=\"HttpResponseMessage\"/> with an <see cref=\"ObjectContent{T}\"/> instance containing the provided\n        /// <paramref name=\"value\"/>. The given <paramref name=\"mediaType\"/> is used to find an instance of <see cref=\"MediaTypeFormatter\"/>.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of the value.</typeparam>\n        /// <param name=\"request\">The request.</param>\n        /// <param name=\"statusCode\">The status code of the created response.</param>\n        /// <param name=\"value\">The value to wrap. Can be <c>null</c>.</param>\n        /// <param name=\"mediaType\">The media type used to look up an instance of <see cref=\"MediaTypeFormatter\"/>.</param>\n        /// <exception cref=\"InvalidOperationException\">Thrown if the <paramref name=\"request\"/> does not have an associated\n        /// <see cref=\"HttpConfiguration\"/> instance or if the configuration does not have a formatter matching <paramref name=\"mediaType\"/>.</exception>\n        /// <returns>A response wrapping <paramref name=\"value\"/> with <paramref name=\"statusCode\"/>.</returns>\n        public static HttpResponseMessage CreateResponse<T>(this HttpRequestMessage request, HttpStatusCode statusCode, T value, string mediaType)\n        {\n            return request.CreateResponse(statusCode, value, new MediaTypeHeaderValue(mediaType));\n        }\n\n        /// <summary>\n        /// Helper method that creates a <see cref=\"HttpResponseMessage\"/> with an <see cref=\"ObjectContent{T}\"/> instance containing the provided\n        /// <paramref name=\"value\"/>. The given <paramref name=\"mediaType\"/> is used to find an instance of <see cref=\"MediaTypeFormatter\"/>.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of the value.</typeparam>\n        /// <param name=\"request\">The request.</param>\n        /// <param name=\"statusCode\">The status code of the created response.</param>\n        /// <param name=\"value\">The value to wrap. Can be <c>null</c>.</param>\n        /// <param name=\"mediaType\">The media type used to look up an instance of <see cref=\"MediaTypeFormatter\"/>.</param>\n        /// <exception cref=\"InvalidOperationException\">Thrown if the <paramref name=\"request\"/> does not have an associated\n        /// <see cref=\"HttpConfiguration\"/> instance or if the configuration does not have a formatter matching <paramref name=\"mediaType\"/>.</exception>\n        /// <returns>A response wrapping <paramref name=\"value\"/> with <paramref name=\"statusCode\"/>.</returns>\n        public static HttpResponseMessage CreateResponse<T>(this HttpRequestMessage request, HttpStatusCode statusCode, T value, MediaTypeHeaderValue mediaType)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n            if (mediaType == null)\n            {\n                throw Error.ArgumentNull(\"mediaType\");\n            }\n\n            HttpConfiguration configuration = request.GetConfiguration();\n            if (configuration == null)\n            {\n                throw Error.InvalidOperation(SRResources.HttpRequestMessageExtensions_NoConfiguration);\n            }\n\n            MediaTypeFormatter formatter = configuration.Formatters.FindWriter(typeof(T), mediaType);\n            if (formatter == null)\n            {\n                throw Error.InvalidOperation(SRResources.HttpRequestMessageExtensions_NoMatchingFormatter, mediaType, typeof(T).Name);\n            }\n\n            return request.CreateResponse(statusCode, value, formatter, mediaType);\n        }\n\n        /// <summary>\n        /// Helper method that creates a <see cref=\"HttpResponseMessage\"/> with an <see cref=\"ObjectContent{T}\"/> instance containing the provided\n        /// <paramref name=\"value\"/> and the given <paramref name=\"formatter\"/>.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of the value.</typeparam>\n        /// <param name=\"request\">The request.</param>\n        /// <param name=\"statusCode\">The status code of the created response.</param>\n        /// <param name=\"value\">The value to wrap. Can be <c>null</c>.</param>\n        /// <param name=\"formatter\">The formatter to use.</param>\n        /// <returns>A response wrapping <paramref name=\"value\"/> with <paramref name=\"statusCode\"/>.</returns>\n        public static HttpResponseMessage CreateResponse<T>(this HttpRequestMessage request, HttpStatusCode statusCode, T value, MediaTypeFormatter formatter)\n        {\n            return request.CreateResponse(statusCode, value, formatter, (MediaTypeHeaderValue)null);\n        }\n\n        /// <summary>\n        /// Helper method that creates a <see cref=\"HttpResponseMessage\"/> with an <see cref=\"ObjectContent{T}\"/> instance containing the provided\n        /// <paramref name=\"value\"/> and the given <paramref name=\"formatter\"/>.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of the value.</typeparam>\n        /// <param name=\"request\">The request.</param>\n        /// <param name=\"statusCode\">The status code of the created response.</param>\n        /// <param name=\"value\">The value to wrap. Can be <c>null</c>.</param>\n        /// <param name=\"formatter\">The formatter to use.</param>\n        /// <param name=\"mediaType\">The media type override to set on the response's content. Can be <c>null</c>.</param>\n        /// <returns>A response wrapping <paramref name=\"value\"/> with <paramref name=\"statusCode\"/>.</returns>\n        public static HttpResponseMessage CreateResponse<T>(this HttpRequestMessage request, HttpStatusCode statusCode, T value, MediaTypeFormatter formatter, string mediaType)\n        {\n            MediaTypeHeaderValue mediaTypeHeader = mediaType != null ? new MediaTypeHeaderValue(mediaType) : null;\n            return request.CreateResponse(statusCode, value, formatter, mediaTypeHeader);\n        }\n\n        /// <summary>\n        /// Helper method that creates a <see cref=\"HttpResponseMessage\"/> with an <see cref=\"ObjectContent{T}\"/> instance containing the provided\n        /// <paramref name=\"value\"/> and the given <paramref name=\"formatter\"/>.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of the value.</typeparam>\n        /// <param name=\"request\">The request.</param>\n        /// <param name=\"statusCode\">The status code of the created response.</param>\n        /// <param name=\"value\">The value to wrap. Can be <c>null</c>.</param>\n        /// <param name=\"formatter\">The formatter to use.</param>\n        /// <param name=\"mediaType\">The media type override to set on the response's content. Can be <c>null</c>.</param>\n        /// <returns>A response wrapping <paramref name=\"value\"/> with <paramref name=\"statusCode\"/>.</returns>\n        public static HttpResponseMessage CreateResponse<T>(this HttpRequestMessage request, HttpStatusCode statusCode, T value, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n            if (formatter == null)\n            {\n                throw Error.ArgumentNull(\"formatter\");\n            }\n\n            return FormattedContentResult<T>.Execute(statusCode, value, formatter, mediaType, request);\n        }\n\n        /// <summary>\n        /// Adds the given <paramref name=\"resource\"/> to a list of resources that will be disposed by a host once\n        /// the <paramref name=\"request\"/> is disposed.\n        /// </summary>\n        /// <param name=\"request\">The request controlling the lifecycle of <paramref name=\"resource\"/>.</param>\n        /// <param name=\"resource\">The resource to dispose when <paramref name=\"request\"/> is being disposed. Can be <c>null</c>.</param>\n        public static void RegisterForDispose(this HttpRequestMessage request, IDisposable resource)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            if (resource == null)\n            {\n                return;\n            }\n\n            List<IDisposable> trackedResources = GetRegisteredResourcesForDispose(request);\n\n            trackedResources.Add(resource);\n        }\n\n        /// <summary>\n        /// Adds the given <paramref name=\"resources\"/> to a list of resources that will be disposed by a host once\n        /// the <paramref name=\"request\"/> is disposed.\n        /// </summary>\n        /// <param name=\"request\">The request controlling the lifecycle of <paramref name=\"resources\"/>.</param>\n        /// <param name=\"resources\">The resources to dispose when <paramref name=\"request\"/> is being disposed. Can be <c>null</c>.</param>\n        public static void RegisterForDispose(this HttpRequestMessage request, IEnumerable<IDisposable> resources)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            if (resources == null)\n            {\n                throw Error.ArgumentNull(\"resources\");\n            }\n\n            List<IDisposable> trackedResources = GetRegisteredResourcesForDispose(request);\n\n            foreach (IDisposable resource in resources)\n            {\n                if (resource != null)\n                {\n                    trackedResources.Add(resource);\n                }\n            }\n        }\n\n        /// <summary>\n        /// Disposes of all tracked resources associated with the <paramref name=\"request\"/> which were added via the\n        /// <see cref=\"RegisterForDispose(HttpRequestMessage, IDisposable)\"/> method.\n        /// </summary>\n        /// <param name=\"request\">The request.</param>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We want to ignore all exceptions.\")]\n        public static void DisposeRequestResources(this HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            List<IDisposable> resourcesToDispose;\n            if (request.Properties.TryGetValue(HttpPropertyKeys.DisposableRequestResourcesKey, out resourcesToDispose))\n            {\n                foreach (IDisposable resource in resourcesToDispose)\n                {\n                    try\n                    {\n                        resource.Dispose();\n                    }\n                    catch\n                    {\n                        // ignore exceptions\n                    }\n                }\n                resourcesToDispose.Clear();\n            }\n        }\n\n        /// <summary>\n        /// Retrieves the <see cref=\"Guid\"/> which has been assigned as the\n        /// correlation id associated with the given <paramref name=\"request\"/>.\n        /// The value will be created and set the first time this method is called.\n        /// </summary>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/></param>\n        /// <returns>The <see cref=\"Guid\"/> associated with that request.</returns>\n        public static Guid GetCorrelationId(this HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            Guid correlationId;\n            if (!request.Properties.TryGetValue<Guid>(HttpPropertyKeys.RequestCorrelationKey, out correlationId))\n            {\n                // Check if the Correlation Manager ID is set; otherwise fallback to creating a new GUID\n                correlationId = Trace.CorrelationManager.ActivityId;\n                if (correlationId == Guid.Empty)\n                {\n                    correlationId = Guid.NewGuid();\n                }\n\n                request.Properties.Add(HttpPropertyKeys.RequestCorrelationKey, correlationId);\n            }\n\n            return correlationId;\n        }\n\n        /// <summary>\n        /// Retrieves the parsed query string as a collection of key-value pairs.\n        /// </summary>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/></param>\n        /// <returns>The query string as a collection of key-value pairs.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"NameValuePairsValueProvider takes an IEnumerable<KeyValuePair<string, string>>\")]\n        public static IEnumerable<KeyValuePair<string, string>> GetQueryNameValuePairs(this HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            Uri uri = request.RequestUri;\n\n            // Unit tests may not always provide a Uri in the request\n            if (uri == null || String.IsNullOrEmpty(uri.Query))\n            {\n                return Enumerable.Empty<KeyValuePair<string, string>>();\n            }\n\n            IEnumerable<KeyValuePair<string, string>> queryStringData;\n            string cachedQueryString;\n\n            request.Properties.TryGetValue<IEnumerable<KeyValuePair<string, string>>>(HttpPropertyKeys.RequestQueryNameValuePairsKey, out queryStringData);\n            request.Properties.TryGetValue<string>(HttpPropertyKeys.CachedRequestQueryKey, out cachedQueryString);\n\n            if (queryStringData == null ||\n               (cachedQueryString != null && !Object.ReferenceEquals(cachedQueryString, uri.Query ?? String.Empty)))\n            {\n                FormDataCollection formData = new FormDataCollection(uri);\n\n                // The ToArray call here avoids reparsing the query string, and avoids storing an Enumerator state\n                // machine in the request state.\n                queryStringData = formData.GetJQueryNameValuePairs().ToArray();\n                request.Properties[HttpPropertyKeys.RequestQueryNameValuePairsKey] = queryStringData;\n                request.Properties[HttpPropertyKeys.CachedRequestQueryKey] = uri.Query ?? String.Empty;\n            }\n\n            return queryStringData;\n        }\n\n        /// <summary>\n        /// Retrieves the <see cref=\"UrlHelper\"/> instance associated with this request.\n        /// </summary>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/>.</param>\n        /// <returns>The <see cref=\"UrlHelper\"/> instance associated with this request.</returns>\n        public static UrlHelper GetUrlHelper(this HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            HttpRequestContext requestContext = GetRequestContext(request);\n\n            if (requestContext != null)\n            {\n                return requestContext.Url;\n            }\n\n            return new UrlHelper(request);\n        }\n\n        /// <summary>\n        /// Gets a value indicating whether the request originates from a local address or not.\n        /// </summary>\n        /// <param name=\"request\">The HTTP request.</param>\n        /// <returns><see langword=\"true\"/> if the request originates from a local address; otherwise, <see langword=\"false\"/>.</returns>\n        public static bool IsLocal(this HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            HttpRequestContext requestContext = GetRequestContext(request);\n\n            if (requestContext != null)\n            {\n                return requestContext.IsLocal;\n            }\n\n            return request.LegacyIsLocal();\n        }\n\n        internal static bool LegacyIsLocal(this HttpRequestMessage request)\n        {\n            Lazy<bool> isLocal = request.GetProperty<Lazy<bool>>(HttpPropertyKeys.IsLocalKey);\n\n            return isLocal == null ? false : isLocal.Value;\n        }\n\n        /// <summary>\n        /// Gets a value indicating whether the request originates from a batch.\n        /// </summary>\n        /// <param name=\"request\">The HTTP request.</param>\n        /// <returns><see langword=\"true\"/> if the request originates from a batch; otherwise, <see langword=\"false\"/>.</returns>\n        public static bool IsBatchRequest(this HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            return request.GetProperty<bool>(HttpPropertyKeys.IsBatchRequest);\n        }\n\n        /// <summary>\n        /// Gets a value indicating whether error details, such as exception messages and stack traces, should be included for this HTTP request.\n        /// </summary>\n        /// <param name=\"request\">The HTTP request.</param>\n        /// <returns><see langword=\"true\"/> if the error details are to be included; otherwise, <see langword=\"false\"/>.</returns>\n        public static bool ShouldIncludeErrorDetail(this HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            HttpRequestContext requestContext = GetRequestContext(request);\n\n            if (requestContext != null)\n            {\n                return requestContext.IncludeErrorDetail;\n            }\n\n            return request.LegacyShouldIncludeErrorDetail();\n        }\n\n        internal static bool LegacyShouldIncludeErrorDetail(this HttpRequestMessage request)\n        {\n            HttpConfiguration configuration = request.GetConfiguration();\n            IncludeErrorDetailPolicy includeErrorDetailPolicy = IncludeErrorDetailPolicy.Default;\n            if (configuration != null)\n            {\n                includeErrorDetailPolicy = configuration.IncludeErrorDetailPolicy;\n            }\n            switch (includeErrorDetailPolicy)\n            {\n                case IncludeErrorDetailPolicy.Default:\n                    Lazy<bool> includeErrorDetail = request.GetProperty<Lazy<bool>>(HttpPropertyKeys.IncludeErrorDetailKey);\n                    if (includeErrorDetail != null)\n                    {\n                        // If we are on webhost and the user hasn't changed the IncludeErrorDetailPolicy\n                        // look up into the Request's property bag else default to LocalOnly.\n                        return includeErrorDetail.Value;\n                    }\n\n                    goto case IncludeErrorDetailPolicy.LocalOnly;\n\n                case IncludeErrorDetailPolicy.LocalOnly:\n                    return request.IsLocal();\n\n                case IncludeErrorDetailPolicy.Always:\n                    return true;\n\n                case IncludeErrorDetailPolicy.Never:\n                default:\n                    return false;\n            }\n        }\n\n        /// <summary>\n        /// Gets the collection of resources registered for dispose once the <paramref name=\"request\"/> is disposed.\n        /// </summary>\n        /// <param name=\"request\">The request.</param>\n        /// <returns>A collection of resources registered for dispose.</returns>\n        public static IEnumerable<IDisposable> GetResourcesForDisposal(this HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            return GetRegisteredResourcesForDispose(request);\n        }\n\n        private static List<IDisposable> GetRegisteredResourcesForDispose(HttpRequestMessage request)\n        {\n            List<IDisposable> registeredResourcesForDispose;\n            if (!request.Properties.TryGetValue(HttpPropertyKeys.DisposableRequestResourcesKey, out registeredResourcesForDispose))\n            {\n                registeredResourcesForDispose = new List<IDisposable>();\n                request.Properties[HttpPropertyKeys.DisposableRequestResourcesKey] = registeredResourcesForDispose;\n            }\n            return registeredResourcesForDispose;\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http/HttpResponseException.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Net;\nusing System.Net.Http;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// An exception that allows for a given <see cref=\"HttpResponseMessage\"/>\n    /// to be returned to the client.\n    /// </summary>\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2237:MarkISerializableTypesWithSerializable\", Justification = \"This type is not meant to be serialized\")]\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2240:Implement ISerializable correctly\", Justification = \"This type has no serializable state\")]\n    [SuppressMessage(\"Microsoft.Design\", \"CA1032:ImplementStandardExceptionConstructors\", Justification = \"HttpResponseException is not a real exception and is just an easy way to return HttpResponseMessage\")]\n    public class HttpResponseException : Exception\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpResponseException\"/> class.\n        /// </summary>\n        /// <param name=\"statusCode\">The status code of the response.</param>\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"Instance is disposed elsewhere\")]\n        public HttpResponseException(HttpStatusCode statusCode)\n            : this(new HttpResponseMessage(statusCode))\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpResponseException\"/> class.\n        /// </summary>\n        /// <param name=\"response\">The response message.</param>\n        public HttpResponseException(HttpResponseMessage response)\n            : base(SRResources.HttpResponseExceptionMessage)\n        {\n            if (response == null)\n            {\n                throw Error.ArgumentNull(\"response\");\n            }\n\n            Response = response;\n        }\n\n        /// <summary>\n        /// Gets the <see cref=\"HttpResponseMessage\"/> to return to the client.\n        /// </summary>\n        public HttpResponseMessage Response { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/HttpResponseMessageExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Web.Http;\n\nnamespace System.Net.Http\n{\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class HttpResponseMessageExtensions\n    {\n        /// <summary>\n        /// Attempts to retrieve a strongly-typed value from a <paramref name=\"response\"/>.\n        /// </summary>\n        /// <remarks>\n        /// If <see cref=\"HttpResponseMessage.Content\"/> is an instance of <see cref=\"ObjectContent\"/>\n        /// attempts to retrieve the <see cref=\"ObjectContent.Value\"/> if it is compatible with <typeparamref name=\"T\"/>.\n        /// If it is it returns <c>true</c> and sets <paramref name=\"value\"/>. If not it returns <c>false</c> and\n        /// sets <paramref name=\"value\"/> to the default instance of <typeparamref name=\"T\"/>.\n        /// </remarks>\n        /// <typeparam name=\"T\">The type of the value to retrieve.</typeparam>\n        /// <param name=\"response\">The response.</param>\n        /// <param name=\"value\">Will contain the retrieved value if this method succeeds.</param>\n        /// <returns>Returns <c>true</c> if the response has a content with a value that can be cast to <typeparamref name=\"T\"/>,\n        /// <c>false</c> otherwise.</returns>\n        public static bool TryGetContentValue<T>(this HttpResponseMessage response, out T value)\n        {\n            if (response == null)\n            {\n                throw Error.ArgumentNull(\"response\");\n            }\n\n            ObjectContent content = response.Content as ObjectContent;\n            if (content != null)\n            {\n                if (content.Value is T)\n                {\n                    value = (T)content.Value;\n                    return true;\n                }\n            }\n\n            value = default(T);\n            return false;\n        }\n\n        /// <summary>\n        /// Attaches the given <paramref name=\"request\"/> to the <paramref name=\"response\"/> if the response does not already\n        /// have a pointer to a request.\n        /// </summary>\n        /// <param name=\"response\">The response.</param>\n        /// <param name=\"request\">The request.</param>\n        internal static void EnsureResponseHasRequest(this HttpResponseMessage response, HttpRequestMessage request)\n        {\n            if (response != null && response.RequestMessage == null)\n            {\n                response.RequestMessage = request;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/HttpRouteCollection.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Routing;\n\nnamespace System.Web.Http\n{\n    public class HttpRouteCollection : ICollection<IHttpRoute>, IDisposable\n    {\n        // Arbitrary base address for evaluating the root virtual path\n        private static readonly Uri _referenceBaseAddress = new Uri(\"http://localhost\");\n\n        private readonly string _virtualPathRoot;\n        private readonly List<IHttpRoute> _collection = new List<IHttpRoute>();\n        private readonly IDictionary<string, IHttpRoute> _dictionary = new Dictionary<string, IHttpRoute>(StringComparer.OrdinalIgnoreCase);\n        private bool _disposed;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpRouteCollection\"/> class with a <see cref=\"M:VirtualPathRoot\"/>\n        /// value of \"/\".\n        /// </summary>\n        public HttpRouteCollection()\n            : this(\"/\")\n        {\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2234:PassSystemUriObjectsInsteadOfStrings\", Justification = \"Relative URIs are not URIs\")]\n        public HttpRouteCollection(string virtualPathRoot)\n        {\n            if (virtualPathRoot == null)\n            {\n                throw Error.ArgumentNull(\"virtualPathRoot\");\n            }\n\n            // Validate virtual path\n            Uri address = new Uri(_referenceBaseAddress, virtualPathRoot);\n            _virtualPathRoot = \"/\" + address.GetComponents(UriComponents.Path, UriFormat.Unescaped);\n        }\n\n        public virtual string VirtualPathRoot\n        {\n            get { return _virtualPathRoot; }\n        }\n\n        public virtual int Count\n        {\n            get { return _collection.Count; }\n        }\n\n        public virtual bool IsReadOnly\n        {\n            get { return false; }\n        }\n\n        public virtual IHttpRoute this[int index]\n        {\n            get { return _collection[index]; }\n        }\n\n        public virtual IHttpRoute this[string name]\n        {\n            get { return _dictionary[name]; }\n        }\n\n        public virtual IHttpRouteData GetRouteData(HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            for (int i = 0; i < _collection.Count; i++)\n            {\n                string virtualPathRoot = GetVirtualPathRoot(request.GetRequestContext());\n                IHttpRouteData routeData = _collection[i].GetRouteData(virtualPathRoot, request);\n                if (routeData != null)\n                {\n                    return routeData;\n                }\n            }\n\n            return null;\n        }\n\n        public virtual IHttpVirtualPathData GetVirtualPath(HttpRequestMessage request, string name, IDictionary<string, object> values)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            if (name == null)\n            {\n                throw Error.ArgumentNull(\"name\");\n            }\n\n            IHttpRoute route;\n            if (!_dictionary.TryGetValue(name, out route))\n            {\n                throw Error.Argument(\"name\", SRResources.RouteCollection_NameNotFound, name);\n            }\n            IHttpVirtualPathData virtualPath = route.GetVirtualPath(request, values);\n            if (virtualPath == null)\n            {\n                return null;\n            }\n\n            // Construct a new VirtualPathData with the resolved app path\n            string virtualPathRoot = GetVirtualPathRoot(request.GetRequestContext());\n            if (!virtualPathRoot.EndsWith(\"/\", StringComparison.Ordinal))\n            {\n                virtualPathRoot += \"/\";\n            }\n\n            // Note: The virtual path root here always ends with a \"/\" and the\n            // virtual path never starts with a \"/\" (that's how routes work).\n            return new HttpVirtualPathData(virtualPath.Route, virtualPathRoot + virtualPath.VirtualPath);\n        }\n\n        // Returns the virtual path root on the request context if present\n        // Otherwise, fall back on the virtual path root for the route collection\n        private string GetVirtualPathRoot(HttpRequestContext requestContext)\n        {\n            if (requestContext != null)\n            {\n                return requestContext.VirtualPathRoot ?? String.Empty;\n            }\n\n            return _virtualPathRoot;\n        }\n\n        public IHttpRoute CreateRoute(string routeTemplate, object defaults, object constraints)\n        {\n            IDictionary<string, object> dataTokens = new Dictionary<string, object>();\n\n            return CreateRoute(routeTemplate, new HttpRouteValueDictionary(defaults), new HttpRouteValueDictionary(constraints), dataTokens, handler: null);\n        }\n\n        public IHttpRoute CreateRoute(string routeTemplate, IDictionary<string, object> defaults, IDictionary<string, object> constraints, IDictionary<string, object> dataTokens)\n        {\n            return CreateRoute(routeTemplate, defaults, constraints, dataTokens, handler: null);\n        }\n\n        public virtual IHttpRoute CreateRoute(string routeTemplate, IDictionary<string, object> defaults, IDictionary<string, object> constraints, IDictionary<string, object> dataTokens, HttpMessageHandler handler)\n        {\n            HttpRouteValueDictionary routeDefaults = new HttpRouteValueDictionary(defaults);\n            HttpRouteValueDictionary routeConstraints = new HttpRouteValueDictionary(constraints);\n            HttpRouteValueDictionary routeDataTokens = new HttpRouteValueDictionary(dataTokens);\n\n            foreach (var constraint in routeConstraints)\n            {\n                ValidateConstraint(routeTemplate, constraint.Key, constraint.Value);\n            }\n\n            return new HttpRoute(routeTemplate, routeDefaults, routeConstraints, routeDataTokens, handler);\n        }\n\n        /// <summary>\n        /// Validates that a constraint is valid for an <see cref=\"IHttpRoute\"/> created by a call\n        /// to the <see cref=\"HttpRouteCollection.CreateRoute(string, IDictionary&lt;string, object&gt;, IDictionary&lt;string, object&gt;, IDictionary&lt;string, object&gt;, HttpMessageHandler)\"/> method.\n        /// </summary>\n        /// <param name=\"routeTemplate\">The route template.</param>\n        /// <param name=\"name\">The constraint name.</param>\n        /// <param name=\"constraint\">The constraint object.</param>\n        /// <remarks>\n        /// Implement this method when deriving from <see cref=\"HttpRouteCollection\"/> to allow contraints of\n        /// types other than <see cref=\"string\"/> and <see cref=\"IHttpRouteConstraint\"/>.\n        /// </remarks>\n        protected virtual void ValidateConstraint(string routeTemplate, string name, object constraint)\n        {\n            if (name == null)\n            {\n                throw Error.ArgumentNull(\"name\");\n            }\n\n            if (constraint == null)\n            {\n                throw Error.ArgumentNull(\"constraint\");\n            }\n\n            HttpRoute.ValidateConstraint(routeTemplate, name, constraint);\n        }\n\n        void ICollection<IHttpRoute>.Add(IHttpRoute route)\n        {\n            throw Error.NotSupported(SRResources.Route_AddRemoveWithNoKeyNotSupported, typeof(HttpRouteCollection).Name);\n        }\n\n        public virtual void Add(string name, IHttpRoute route)\n        {\n            if (name == null)\n            {\n                throw Error.ArgumentNull(\"name\");\n            }\n\n            if (route == null)\n            {\n                throw Error.ArgumentNull(\"route\");\n            }\n\n            _dictionary.Add(name, route);\n            _collection.Add(route);\n        }\n\n        public virtual void Clear()\n        {\n            _dictionary.Clear();\n            _collection.Clear();\n        }\n\n        public virtual bool Contains(IHttpRoute item)\n        {\n            if (item == null)\n            {\n                throw Error.ArgumentNull(\"item\");\n            }\n\n            return _collection.Contains(item);\n        }\n\n        public virtual bool ContainsKey(string name)\n        {\n            if (name == null)\n            {\n                throw Error.ArgumentNull(\"name\");\n            }\n\n            return _dictionary.ContainsKey(name);\n        }\n\n        public virtual void CopyTo(IHttpRoute[] array, int arrayIndex)\n        {\n            _collection.CopyTo(array, arrayIndex);\n        }\n\n        public virtual void CopyTo(KeyValuePair<string, IHttpRoute>[] array, int arrayIndex)\n        {\n            _dictionary.CopyTo(array, arrayIndex);\n        }\n\n        public virtual void Insert(int index, string name, IHttpRoute value)\n        {\n            if (name == null)\n            {\n                throw Error.ArgumentNull(\"name\");\n            }\n\n            if (value == null)\n            {\n                throw Error.ArgumentNull(\"value\");\n            }\n\n            // Check that index is valid\n            if (_collection[index] != null)\n            {\n                _dictionary.Add(name, value);\n                _collection.Insert(index, value);\n            }\n        }\n\n        bool ICollection<IHttpRoute>.Remove(IHttpRoute route)\n        {\n            throw Error.NotSupported(SRResources.Route_AddRemoveWithNoKeyNotSupported, typeof(HttpRouteCollection).Name);\n        }\n\n        public virtual bool Remove(string name)\n        {\n            if (name == null)\n            {\n                throw Error.ArgumentNull(\"name\");\n            }\n\n            IHttpRoute value;\n            if (_dictionary.TryGetValue(name, out value))\n            {\n                bool dictionaryRemove = _dictionary.Remove(name);\n                bool collectionRemove = _collection.Remove(value);\n                Contract.Assert(dictionaryRemove == collectionRemove);\n                return dictionaryRemove;\n            }\n\n            return false;\n        }\n\n        public virtual IEnumerator<IHttpRoute> GetEnumerator()\n        {\n            return _collection.GetEnumerator();\n        }\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return OnGetEnumerator();\n        }\n\n        protected virtual IEnumerator OnGetEnumerator()\n        {\n            return _collection.GetEnumerator();\n        }\n\n        public virtual bool TryGetValue(string name, out IHttpRoute route)\n        {\n            return _dictionary.TryGetValue(name, out route);\n        }\n\n        public void Dispose()\n        {\n            Dispose(true);\n            GC.SuppressFinalize(this);\n        }\n\n        protected virtual void Dispose(bool disposing)\n        {\n            if (!_disposed)\n            {\n                if (disposing)\n                {\n                    // Creating a collection to avoid double-disposing any handlers that are shared between routes\n                    HashSet<IDisposable> handlers = new HashSet<IDisposable>();\n                    foreach (var route in this)\n                    {\n                        if (route.Handler != null)\n                        {\n                            handlers.Add(route.Handler);\n                        }\n                    }\n\n                    foreach (var handler in handlers)\n                    {\n                        handler.Dispose();\n                    }\n                }\n\n                _disposed = true;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/HttpRouteCollectionExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Net.Http;\nusing System.Web.Http.Batch;\nusing System.Web.Http.Routing;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Extension methods for <see cref=\"HttpRouteCollection\"/>\n    /// </summary>\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class HttpRouteCollectionExtensions\n    {\n        /// <summary>\n        /// Maps the specified route template.\n        /// </summary>\n        /// <param name=\"routes\">A collection of routes for the application.</param>\n        /// <param name=\"name\">The name of the route to map.</param>\n        /// <param name=\"routeTemplate\">The route template for the route.</param>\n        /// <returns>A reference to the mapped route.</returns>\n        public static IHttpRoute MapHttpRoute(this HttpRouteCollection routes, string name, string routeTemplate)\n        {\n            return MapHttpRoute(routes, name, routeTemplate, defaults: null, constraints: null, handler: null);\n        }\n\n        /// <summary>\n        /// Maps the specified route template and sets default constraints.\n        /// </summary>\n        /// <param name=\"routes\">A collection of routes for the application.</param>\n        /// <param name=\"name\">The name of the route to map.</param>\n        /// <param name=\"routeTemplate\">The route template for the route.</param>\n        /// <param name=\"defaults\">An object that contains default route values.</param>\n        /// <returns>A reference to the mapped route.</returns>\n        public static IHttpRoute MapHttpRoute(this HttpRouteCollection routes, string name, string routeTemplate, object defaults)\n        {\n            return MapHttpRoute(routes, name, routeTemplate, defaults, constraints: null, handler: null);\n        }\n\n        /// <summary>\n        /// Maps the specified route template and sets default route values and constraints.\n        /// </summary>\n        /// <param name=\"routes\">A collection of routes for the application.</param>\n        /// <param name=\"name\">The name of the route to map.</param>\n        /// <param name=\"routeTemplate\">The route template for the route.</param>\n        /// <param name=\"defaults\">An object that contains default route values.</param>\n        /// <param name=\"constraints\">A set of expressions that specify values for <paramref name=\"routeTemplate\"/>.</param>\n        /// <returns>A reference to the mapped route.</returns>\n        public static IHttpRoute MapHttpRoute(this HttpRouteCollection routes, string name, string routeTemplate, object defaults, object constraints)\n        {\n            return MapHttpRoute(routes, name, routeTemplate, defaults, constraints, handler: null);\n        }\n\n        /// <summary>\n        /// Maps the specified route template and sets default route values, constraints, and end-point message handler.\n        /// </summary>\n        /// <param name=\"routes\">A collection of routes for the application.</param>\n        /// <param name=\"name\">The name of the route to map.</param>\n        /// <param name=\"routeTemplate\">The route template for the route.</param>\n        /// <param name=\"defaults\">An object that contains default route values.</param>\n        /// <param name=\"constraints\">A set of expressions that specify values for <paramref name=\"routeTemplate\"/>.</param>\n        /// <param name=\"handler\">The handler to which the request will be dispatched.</param>\n        /// <returns>A reference to the mapped route.</returns>\n        public static IHttpRoute MapHttpRoute(this HttpRouteCollection routes, string name, string routeTemplate, object defaults, object constraints, HttpMessageHandler handler)\n        {\n            if (routes == null)\n            {\n                throw Error.ArgumentNull(\"routes\");\n            }\n\n            HttpRouteValueDictionary defaultsDictionary = new HttpRouteValueDictionary(defaults);\n            HttpRouteValueDictionary constraintsDictionary = new HttpRouteValueDictionary(constraints);\n            IHttpRoute route = routes.CreateRoute(routeTemplate, defaultsDictionary, constraintsDictionary, dataTokens: null, handler: handler);\n            routes.Add(name, route);\n            return route;\n        }\n\n        /// <summary>\n        /// Maps the specified route for handling HTTP batch requests.\n        /// </summary>\n        /// <param name=\"routes\">A collection of routes for the application.</param>\n        /// <param name=\"routeName\">The name of the route to map.</param>\n        /// <param name=\"routeTemplate\">The route template for the route.</param>\n        /// <param name=\"batchHandler\">The <see cref=\"HttpBatchHandler\"/> for handling batch requests.</param>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1011:ConsiderPassingBaseTypesAsParameters\", Justification = \"We want the handler to be a batch handler.\")]\n        public static IHttpRoute MapHttpBatchRoute(this HttpRouteCollection routes, string routeName, string routeTemplate, HttpBatchHandler batchHandler)\n        {\n            return routes.MapHttpRoute(routeName, routeTemplate, defaults: null, constraints: null, handler: batchHandler);\n        }\n\n        /// <summary>\n        /// Ignores the specified route.\n        /// </summary>\n        /// <param name=\"routes\">A collection of routes for the application.</param>\n        /// <param name=\"routeName\">The name of the route to ignore.</param>\n        /// <param name=\"routeTemplate\">The route template for the route.</param>\n        public static IHttpRoute IgnoreRoute(this HttpRouteCollection routes, string routeName, string routeTemplate)\n        {\n            return IgnoreRoute(routes, routeName, routeTemplate, constraints: null);\n        }\n\n        /// <summary>\n        /// Ignores the specified route.\n        /// </summary>\n        /// <param name=\"routes\">A collection of routes for the application.</param>\n        /// <param name=\"routeName\">The name of the route to ignore.</param>\n        /// <param name=\"routeTemplate\">The route template for the route.</param>\n        /// <param name=\"constraints\">A set of expressions that specify values for <paramref name=\"routeTemplate\"/>.</param>\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:DisposeObjectsBeforeLosingScope\", Justification = \"The handler instance is owned by the Route. StopRoutingHandler.Dispose() doesn't do anything, so we don't care if we throw and fail to dispose it. Currently it will never be disposed, see https://aspnetwebstack.codeplex.com/workitem/1393.\")]\n        public static IHttpRoute IgnoreRoute(this HttpRouteCollection routes, string routeName, string routeTemplate, object constraints)\n        {\n            if (routes == null)\n            {\n                throw new ArgumentNullException(\"routes\");\n            }\n            if (routeName == null)\n            {\n                throw new ArgumentNullException(\"routeName\");\n            }\n            if (routeTemplate == null)\n            {\n                throw new ArgumentNullException(\"routeTemplate\");\n            }\n\n            IgnoreHttpRouteInternal route = new IgnoreHttpRouteInternal(routeTemplate, new HttpRouteValueDictionary(constraints), new StopRoutingHandler());\n            routes.Add(routeName, route);\n            return route;\n        }\n\n        private sealed class IgnoreHttpRouteInternal : HttpRoute\n        {\n            public IgnoreHttpRouteInternal(string routeTemplate, HttpRouteValueDictionary constraints, HttpMessageHandler handler)\n                : base(routeTemplate, constraints: constraints, handler: handler, dataTokens: null, defaults: null)\n            {\n            }\n\n            public override IHttpVirtualPathData GetVirtualPath(HttpRequestMessage request, IDictionary<string, object> values)\n            {\n                // Never match during route generation. This avoids the scenario where an IgnoreRoute with\n                // fairly relaxed constraints ends up eagerly matching all generated URLs.\n                return null;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/HttpServer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Net;\nusing System.Net.Http;\nusing System.Runtime.ExceptionServices;\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Defines an implementation of an <see cref=\"HttpMessageHandler\"/> which dispatches an \n    /// incoming <see cref=\"HttpRequestMessage\"/> and creates an <see cref=\"HttpResponseMessage\"/> as a result.\n    /// </summary>\n    public class HttpServer : DelegatingHandler\n    {\n        // _anonymousPrincipal needs thread-safe intialization so use a static field initializer\n        private static readonly IPrincipal _anonymousPrincipal = new GenericPrincipal(new GenericIdentity(String.Empty), new string[0]);\n\n        private readonly HttpConfiguration _configuration;\n        private readonly HttpMessageHandler _dispatcher;\n\n        private IExceptionLogger _exceptionLogger;\n        private IExceptionHandler _exceptionHandler;\n        private bool _disposed;\n        private bool _initialized = false;\n        private object _initializationLock = new object();\n        private object _initializationTarget;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpServer\"/> class with default configuration and dispatcher.\n        /// </summary>\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\",\n            Justification = \"The configuration object is disposed as part of this class.\")]\n        public HttpServer()\n            : this(new HttpConfiguration())\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpServer\"/> class with default dispatcher.\n        /// </summary>\n        /// <param name=\"configuration\">The <see cref=\"HttpConfiguration\"/> used to configure this <see cref=\"HttpServer\"/> instance.</param>\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\",\n            Justification = \"The configuration object is disposed as part of this class.\")]\n        public HttpServer(HttpConfiguration configuration)\n            : this(configuration, new HttpRoutingDispatcher(configuration))\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpServer\"/> class with a custom dispatcher.\n        /// </summary>\n        /// <param name=\"dispatcher\">Http dispatcher responsible for handling incoming requests.</param>\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\",\n            Justification = \"The configuration object is disposed as part of this class.\")]\n        public HttpServer(HttpMessageHandler dispatcher)\n            : this(new HttpConfiguration(), dispatcher)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpServer\"/> class.\n        /// </summary>\n        /// <param name=\"configuration\">The <see cref=\"HttpConfiguration\"/> used to configure this <see cref=\"HttpServer\"/> instance.</param>\n        /// <param name=\"dispatcher\">Http dispatcher responsible for handling incoming requests.</param>\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1804:RemoveUnusedLocals\", MessageId = \"principal\",\n            Justification = \"Must access Thread.CurrentPrincipal to work around problem in .NET 4.5\")]\n        public HttpServer(HttpConfiguration configuration, HttpMessageHandler dispatcher)\n        {\n            if (configuration == null)\n            {\n                throw Error.ArgumentNull(\"configuration\");\n            }\n\n            if (dispatcher == null)\n            {\n                throw Error.ArgumentNull(\"dispatcher\");\n            }\n\n            // Read the thread principal to work around a problem up to .NET 4.5.1 that CurrentPrincipal creates a new instance each time it is read in async \n            // code if it has not been queried from the spawning thread.\n            IPrincipal principal = Thread.CurrentPrincipal;\n\n            _dispatcher = dispatcher;\n            _configuration = configuration;\n        }\n\n        /// <summary>\n        /// Gets the dispatcher.\n        /// </summary>\n        public HttpMessageHandler Dispatcher\n        {\n            get { return _dispatcher; }\n        }\n\n        /// <summary>\n        /// Gets the <see cref=\"HttpConfiguration\"/>.\n        /// </summary>\n        public HttpConfiguration Configuration\n        {\n            get { return _configuration; }\n        }\n\n        /// <remarks>This property is settable only for unit testing purposes.</remarks>\n        internal IExceptionLogger ExceptionLogger\n        {\n            get\n            {\n                if (_exceptionLogger == null)\n                {\n                    _exceptionLogger = ExceptionServices.GetLogger(_configuration);\n                }\n\n                return _exceptionLogger;\n            }\n            set\n            {\n                _exceptionLogger = value;\n            }\n        }\n\n        /// <remarks>This property is settable only for unit testing purposes.</remarks>\n        internal IExceptionHandler ExceptionHandler\n        {\n            get\n            {\n                if (_exceptionHandler == null)\n                {\n                    _exceptionHandler = ExceptionServices.GetHandler(_configuration);\n                }\n\n                return _exceptionHandler;\n            }\n            set\n            {\n                _exceptionHandler = value;\n            }\n        }\n\n        /// <summary>\n        /// Releases unmanaged and - optionally - managed resources\n        /// </summary>\n        /// <param name=\"disposing\"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged SRResources.</param>\n        protected override void Dispose(bool disposing)\n        {\n            if (!_disposed)\n            {\n                _disposed = true;\n                if (disposing)\n                {\n                    _configuration.Dispose();\n                }\n            }\n\n            base.Dispose(disposing);\n        }\n\n        /// <summary>\n        /// Dispatches an incoming <see cref=\"HttpRequestMessage\"/>.\n        /// </summary>\n        /// <param name=\"request\">The request to dispatch</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A <see cref=\"Task{HttpResponseMessage}\"/> representing the ongoing operation.</returns>\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"Caller becomes owner.\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"we are converting exceptions to error responses.\")]\n        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            if (_disposed)\n            {\n                return request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, SRResources.HttpServerDisposed);\n            }\n\n            // The first request initializes the server\n            EnsureInitialized();\n\n            // Capture current synchronization context and add it as a parameter to the request\n            SynchronizationContext context = SynchronizationContext.Current;\n            if (context != null)\n            {\n                request.SetSynchronizationContext(context);\n            }\n\n            // Add HttpConfiguration object as a parameter to the request \n            request.SetConfiguration(_configuration);\n\n            // Ensure we have a principal, even if the host didn't give us one\n            IPrincipal originalPrincipal = Thread.CurrentPrincipal;\n            if (originalPrincipal == null)\n            {\n                Thread.CurrentPrincipal = _anonymousPrincipal;\n            }\n\n            // Ensure we have a principal on the request context (if there is a request context).\n            HttpRequestContext requestContext = request.GetRequestContext();\n\n            if (requestContext == null)\n            {\n                requestContext = new RequestBackedHttpRequestContext(request);\n\n                // if the host did not set a request context we will also set it back to the request.\n                request.SetRequestContext(requestContext);\n            }\n\n            try\n            {\n                ExceptionDispatchInfo exceptionInfo;\n\n                try\n                {\n                    return await base.SendAsync(request, cancellationToken);\n                }\n                catch (OperationCanceledException)\n                {\n                    // Propogate the canceled task without calling exception loggers or handlers.\n                    throw;\n                }\n                catch (HttpResponseException exception)\n                {\n                    return exception.Response;\n                }\n                catch (Exception exception)\n                {\n                    exceptionInfo = ExceptionDispatchInfo.Capture(exception);\n                }\n\n                Debug.Assert(exceptionInfo.SourceException != null);\n\n                ExceptionContext exceptionContext = new ExceptionContext(exceptionInfo.SourceException,\n                    ExceptionCatchBlocks.HttpServer, request);\n                await ExceptionLogger.LogAsync(exceptionContext, cancellationToken);\n                HttpResponseMessage response = await ExceptionHandler.HandleAsync(exceptionContext,\n                    cancellationToken);\n\n                if (response == null)\n                {\n                    exceptionInfo.Throw();\n                }\n\n                return response;\n            }\n            finally\n            {\n                Thread.CurrentPrincipal = originalPrincipal;\n            }\n        }\n\n        private void EnsureInitialized()\n        {\n            LazyInitializer.EnsureInitialized(ref _initializationTarget, ref _initialized, ref _initializationLock, () =>\n            {\n                Initialize();\n                return null;\n            });\n        }\n\n        /// <summary>\n        /// Prepares the server for operation.\n        /// </summary>\n        /// <remarks>\n        /// This method must be called after all configuration is complete\n        /// but before the first request is processed.\n        /// </remarks>\n        protected virtual void Initialize()\n        {\n            // Do final initialization of the configuration.\n            // It is considered immutable from this point forward.\n            _configuration.EnsureInitialized();\n\n            // Create pipeline\n            InnerHandler = HttpClientFactory.CreatePipeline(_dispatcher, _configuration.MessageHandlers);\n        }\n\n        private static HttpConfiguration EnsureNonNull(HttpConfiguration configuration)\n        {\n            if (configuration == null)\n            {\n                throw new ArgumentNullException(\"configuration\");\n            }\n\n            return configuration;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/IHttpActionResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http\n{\n    /// <summary>Defines a command that asynchronously creates an <see cref=\"HttpResponseMessage\"/>.</summary>\n    public interface IHttpActionResult\n    {\n        /// <summary>Creates an <see cref=\"HttpResponseMessage\"/> asynchronously.</summary>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>A task that, when completed, contains the <see cref=\"HttpResponseMessage\"/>.</returns>\n        Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/IncludeErrorDetailPolicy.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Enum to indicate whether error details, such as exception messages and stack traces, should be included in error messages.\n    /// </summary>\n    public enum IncludeErrorDetailPolicy\n    {\n        /// <summary>\n        /// Default to the host specific behavior. This looks at the CustomErrors setting on webhost and\n        /// defaults to LocalOnly in selfhost.\n        /// </summary>\n        Default = 0,\n\n        /// <summary>\n        /// Only include error details when responding to a local request.\n        /// </summary>\n        LocalOnly,\n\n        /// <summary>\n        /// Always include error details.\n        /// </summary>\n        Always,\n\n        /// <summary>\n        /// Never include error details.\n        /// </summary>\n        Never\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Internal/CollectionModelBinderUtil.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.ValueProviders;\n\nnamespace System.Web.Http.Internal\n{\n    internal static class CollectionModelBinderUtil\n    {\n        internal static void CreateOrReplaceCollection<TElement>(ModelBindingContext bindingContext, IEnumerable<TElement> incomingElements, Func<ICollection<TElement>> creator)\n        {\n            ICollection<TElement> collection = bindingContext.Model as ICollection<TElement>;\n            if (collection == null || collection.IsReadOnly)\n            {\n                collection = creator();\n                bindingContext.Model = collection;\n            }\n\n            collection.Clear();\n            foreach (TElement element in incomingElements)\n            {\n                collection.Add(element);\n            }\n        }\n\n        internal static void CreateOrReplaceDictionary<TKey, TValue>(ModelBindingContext bindingContext, IEnumerable<KeyValuePair<TKey, TValue>> incomingElements, Func<IDictionary<TKey, TValue>> creator)\n        {\n            IDictionary<TKey, TValue> dictionary = bindingContext.Model as IDictionary<TKey, TValue>;\n            if (dictionary == null || dictionary.IsReadOnly)\n            {\n                dictionary = creator();\n                bindingContext.Model = dictionary;\n            }\n\n            dictionary.Clear();\n            foreach (var element in incomingElements)\n            {\n                if (element.Key != null)\n                {\n                    dictionary[element.Key] = element.Value;\n                }\n            }\n        }\n\n        /// <summary>\n        /// Instantiate a generic binder.\n        /// </summary>\n        /// <param name=\"supportedInterfaceType\">Type that is updatable by this binder.</param>\n        /// <param name=\"newInstanceType\">Type that will be created by the binder if necessary.</param>\n        /// <param name=\"openBinderType\">Model binder type.</param>\n        /// <param name=\"modelType\">Model type.</param>\n        /// <returns></returns>\n        // Example: GetGenericBinder(typeof(IList<>), typeof(List<>), typeof(ListBinder<>), ...) means that the ListBinder<T>\n        // type can update models that implement IList<T>, and if for some reason the existing model instance is not\n        // updatable the binder will create a List<T> object and bind to that instead. This method will return a ListBinder<T>\n        // or null, depending on whether the type and updatability checks succeed.\n        internal static IModelBinder GetGenericBinder(Type supportedInterfaceType, Type newInstanceType, Type openBinderType, Type modelType)\n        {\n            Contract.Assert(supportedInterfaceType != null);\n            Contract.Assert(openBinderType != null);\n            Contract.Assert(modelType != null);\n\n            Type[] modelTypeArguments = GetGenericBinderTypeArgs(supportedInterfaceType, modelType);\n\n            if (modelTypeArguments == null)\n            {\n                return null;\n            }\n\n            Type closedNewInstanceType = newInstanceType.MakeGenericType(modelTypeArguments);\n            if (!modelType.IsAssignableFrom(closedNewInstanceType))\n            {\n                return null;\n            }\n\n            Type closedBinderType = openBinderType.MakeGenericType(modelTypeArguments);\n            var binder = (IModelBinder)Activator.CreateInstance(closedBinderType);\n            return binder;\n        }\n\n        // Get the generic arguments for the binder, based on the model type. Or null if not compatible.\n        internal static Type[] GetGenericBinderTypeArgs(Type supportedInterfaceType, Type modelType)\n        {\n            if (!modelType.IsGenericType || modelType.IsGenericTypeDefinition)\n            {\n                // not a closed generic type\n                return null;\n            }\n\n            Type[] modelTypeArguments = modelType.GetGenericArguments();\n            if (modelTypeArguments.Length != supportedInterfaceType.GetGenericArguments().Length)\n            {\n                // wrong number of generic type arguments\n                return null;\n            }\n\n            return modelTypeArguments;\n        }\n\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1304:SpecifyCultureInfo\", MessageId = \"System.Web.Http.ValueProviders.ValueProviderResult.ConvertTo(System.Type)\", Justification = \"The ValueProviderResult already has the necessary context to perform a culture-aware conversion.\")]\n        internal static IEnumerable<string> GetIndexNamesFromValueProviderResult(ValueProviderResult valueProviderResultIndex)\n        {\n            IEnumerable<string> indexNames = null;\n            if (valueProviderResultIndex != null)\n            {\n                string[] indexes = (string[])valueProviderResultIndex.ConvertTo(typeof(string[]));\n                if (indexes != null && indexes.Length > 0)\n                {\n                    indexNames = indexes;\n                }\n            }\n            return indexNames;\n        }\n\n        internal static IEnumerable<string> GetZeroBasedIndexes()\n        {\n            int i = 0;\n            while (true)\n            {\n                yield return i.ToString(CultureInfo.InvariantCulture);\n                i++;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Internal/HttpParameterBindingExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.ValueProviders;\n\nnamespace System.Web.Http.Internal\n{\n    internal static class HttpParameterBindingExtensions\n    {\n        public static bool WillReadUri(this HttpParameterBinding parameterBinding)\n        {\n            if (parameterBinding == null)\n            {\n                throw Error.ArgumentNull(\"parameterBinding\");\n            }\n\n            IValueProviderParameterBinding valueProviderParameterBinding = parameterBinding as IValueProviderParameterBinding;\n            if (valueProviderParameterBinding != null)\n            {\n                IEnumerable<ValueProviderFactory> valueProviderFactories = valueProviderParameterBinding.ValueProviderFactories;\n                if (valueProviderFactories.Any() && valueProviderFactories.All(factory => factory is IUriValueProviderFactory))\n                {\n                    return true;\n                }\n            }\n\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Internal/MemberInfoExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\n\nnamespace System.Web.Http.Internal\n{\n    internal static class MemberInfoExtensions\n    {\n        public static TAttribute[] GetCustomAttributes<TAttribute>(this MemberInfo member, bool inherit) where TAttribute : class\n        {\n            if (member == null)\n            {\n                throw Error.ArgumentNull(\"member\");\n            }\n\n            return (TAttribute[])member.GetCustomAttributes(typeof(TAttribute), inherit);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Internal/ParameterInfoExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Reflection;\n\nnamespace System.Web.Http.Internal\n{\n    internal static class ParameterInfoExtensions\n    {\n        public static bool TryGetDefaultValue(this ParameterInfo parameterInfo, out object value)\n        {\n            if (parameterInfo == null)\n            {\n                throw Error.ArgumentNull(\"parameterInfo\");\n            }\n\n            // this will get the default value as seen by the VB / C# compilers\n            // if no value was baked in, RawDefaultValue returns DBNull.Value\n            object defaultValue = parameterInfo.DefaultValue;\n            if (defaultValue != DBNull.Value)\n            {\n                value = defaultValue;\n                return true;\n            }\n\n            // if the compiler did not bake in a default value, check the [DefaultValue] attribute\n            DefaultValueAttribute[] attrs = (DefaultValueAttribute[])parameterInfo.GetCustomAttributes(typeof(DefaultValueAttribute), false);\n            if (attrs == null || attrs.Length == 0)\n            {\n                value = default(object);\n                return false;\n            }\n            else\n            {\n                value = attrs[0].Value;\n                return true;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Internal/TypeActivator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Linq.Expressions;\n\nnamespace System.Web.Http.Internal\n{\n    internal static class TypeActivator\n    {\n        public static Func<TBase> Create<TBase>(Type instanceType) where TBase : class\n        {\n            Contract.Assert(instanceType != null);\n            NewExpression newInstanceExpression = Expression.New(instanceType);\n            return Expression.Lambda<Func<TBase>>(newInstanceExpression).Compile();\n        }\n\n        public static Func<TInstance> Create<TInstance>() where TInstance : class\n        {\n            return Create<TInstance>(typeof(TInstance));\n        }\n\n        public static Func<object> Create(Type instanceType)\n        {\n            Contract.Assert(instanceType != null);\n            return Create<object>(instanceType);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Internal/TypeDescriptorHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.ComponentModel.DataAnnotations;\nusing System.Security;\n\nnamespace System.Web.Http.Internal\n{\n    internal static class TypeDescriptorHelper\n    {\n        internal static ICustomTypeDescriptor Get(Type type)\n        {\n            return new AssociatedMetadataTypeTypeDescriptionProvider(type).GetTypeDescriptor(type);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Internal/TypeHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Diagnostics.Contracts;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.Internal\n{\n    /// <summary>\n    /// A static class that provides various <see cref=\"Type\"/> related helpers.\n    /// </summary>\n    internal static class TypeHelper\n    {\n        private static readonly Type TaskGenericType = typeof(Task<>);\n\n        internal static readonly Type ApiControllerType = typeof(ApiController);\n\n        internal static Type GetTaskInnerTypeOrNull(Type type)\n        {\n            Contract.Assert(type != null);\n            if (type.IsGenericType && !type.IsGenericTypeDefinition)\n            {\n                Type genericTypeDefinition = type.GetGenericTypeDefinition();\n\n                if (TaskGenericType == genericTypeDefinition)\n                {\n                    return type.GetGenericArguments()[0];\n                }\n            }\n\n            return null;\n        }\n\n        internal static Type[] GetTypeArgumentsIfMatch(Type closedType, Type matchingOpenType)\n        {\n            if (!closedType.IsGenericType)\n            {\n                return null;\n            }\n\n            Type openType = closedType.GetGenericTypeDefinition();\n            return (matchingOpenType == openType) ? closedType.GetGenericArguments() : null;\n        }\n\n        internal static bool IsCompatibleObject(Type type, object value)\n        {\n            return (value == null && TypeAllowsNullValue(type)) || type.IsInstanceOfType(value);\n        }\n\n        internal static bool IsNullableValueType(Type type)\n        {\n            return Nullable.GetUnderlyingType(type) != null;\n        }\n\n        internal static bool TypeAllowsNullValue(Type type)\n        {\n            return !type.IsValueType || IsNullableValueType(type);\n        }\n\n        internal static bool IsSimpleType(Type type)\n        {\n            return type.IsPrimitive ||\n                   type.Equals(typeof(string)) ||\n                   type.Equals(typeof(DateTime)) ||\n                   type.Equals(typeof(Decimal)) ||\n                   type.Equals(typeof(Guid)) ||\n                   type.Equals(typeof(DateTimeOffset)) ||\n                   type.Equals(typeof(TimeSpan));\n        }\n\n        internal static bool IsSimpleUnderlyingType(Type type)\n        {\n            Type underlyingType = Nullable.GetUnderlyingType(type);\n            if (underlyingType != null)\n            {\n                type = underlyingType;\n            }\n\n            return TypeHelper.IsSimpleType(type);\n        }\n\n        internal static bool CanConvertFromString(Type type)\n        {\n            return TypeHelper.IsSimpleUnderlyingType(type) ||\n                TypeHelper.HasStringConverter(type);\n        }\n\n        internal static bool HasStringConverter(Type type)\n        {\n            return TypeDescriptor.GetConverter(type).CanConvertFrom(typeof(string));\n        }\n\n        /// <summary>\n        /// Fast implementation to get the subset of a given type.\n        /// </summary>\n        /// <typeparam name=\"T\">type to search for</typeparam>\n        /// <returns>subset of objects that can be assigned to T</returns>\n        internal static ReadOnlyCollection<T> OfType<T>(object[] objects) where T : class\n        {\n            int max = objects.Length;\n            List<T> list = new List<T>(max);\n            int idx = 0;\n            for (int i = 0; i < max; i++)\n            {\n                T attr = objects[i] as T;\n                if (attr != null)\n                {\n                    list.Add(attr);\n                    idx++;\n                }\n            }\n            list.Capacity = idx;\n\n            return new ReadOnlyCollection<T>(list);\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http/Metadata/ModelMetadata.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Web.Http.Internal;\nusing System.Web.Http.Validation;\n\nnamespace System.Web.Http.Metadata\n{\n    public class ModelMetadata\n    {\n        private readonly Type _containerType;\n        private readonly Type _modelType;\n        private readonly string _propertyName;\n        private EfficientTypePropertyKey<Type, string> _cacheKey;\n\n        /// <summary>\n        /// Explicit backing store for the things we want initialized by default, so don't have to call\n        /// the protected virtual setters of an auto-generated property.\n        /// </summary>\n        private Dictionary<string, object> _additionalValues;\n        private bool _convertEmptyStringToNull = true;\n        private object _model;\n        private Func<object> _modelAccessor;\n        private IEnumerable<ModelMetadata> _properties;\n        private Type _realModelType;\n\n        public ModelMetadata(ModelMetadataProvider provider, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)\n        {\n            if (provider == null)\n            {\n                throw Error.ArgumentNull(\"provider\");\n            }\n            if (modelType == null)\n            {\n                throw Error.ArgumentNull(\"modelType\");\n            }\n\n            Provider = provider;\n\n            _containerType = containerType;\n            _modelAccessor = modelAccessor;\n            _modelType = modelType;\n            _propertyName = propertyName;\n        }\n\n        internal ModelMetadata(ModelMetadataProvider provider, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName, EfficientTypePropertyKey<Type, string> cacheKey)\n            : this(provider, containerType, modelAccessor, modelType, propertyName)\n        {\n            if (cacheKey == null)\n            {\n                throw Error.ArgumentNull(\"cacheKey\");\n            }\n\n            _cacheKey = cacheKey;\n        }\n\n        public virtual Dictionary<string, object> AdditionalValues\n        {\n            get\n            {\n                if (_additionalValues == null)\n                {\n                    _additionalValues = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);\n                }\n\n                return _additionalValues;\n            }\n        }\n\n        public Type ContainerType\n        {\n            get { return _containerType; }\n        }\n\n        public virtual bool ConvertEmptyStringToNull\n        {\n            get { return _convertEmptyStringToNull; }\n            set { _convertEmptyStringToNull = value; }\n        }\n\n        public virtual string Description { get; set; }\n\n        public virtual bool IsComplexType\n        {\n            get { return !TypeHelper.HasStringConverter(ModelType); }\n        }\n\n        public bool IsNullableValueType\n        {\n            get { return TypeHelper.IsNullableValueType(ModelType); }\n        }\n\n        public virtual bool IsReadOnly { get; set; }\n\n        public object Model\n        {\n            get\n            {\n                if (_modelAccessor != null)\n                {\n                    _model = _modelAccessor();\n                    _modelAccessor = null;\n                }\n                return _model;\n            }\n            set\n            {\n                _model = value;\n                _modelAccessor = null;\n                _properties = null;\n                _realModelType = null;\n            }\n        }\n\n        public Type ModelType\n        {\n            get { return _modelType; }\n        }\n\n        public virtual IEnumerable<ModelMetadata> Properties\n        {\n            get\n            {\n                if (_properties == null)\n                {\n                    _properties = Provider.GetMetadataForProperties(Model, RealModelType);\n                }\n                return _properties;\n            }\n        }\n\n        public string PropertyName\n        {\n            get { return _propertyName; }\n        }\n\n        protected ModelMetadataProvider Provider { get; set; }\n\n        internal Type RealModelType\n        {\n            get\n            {\n                if (_realModelType == null)\n                {\n                    _realModelType = ModelType;\n\n                    // Don't call GetType() if the model is Nullable<T>, because it will\n                    // turn Nullable<T> into T for non-null values\n                    if (Model != null && !TypeHelper.IsNullableValueType(ModelType))\n                    {\n                        _realModelType = Model.GetType();\n                    }\n                }\n\n                return _realModelType;\n            }\n        }\n\n        internal EfficientTypePropertyKey<Type, string> CacheKey\n        {\n            get\n            {\n                if (_cacheKey == null)\n                {\n                    _cacheKey = CreateCacheKey(ContainerType, ModelType, PropertyName);\n                }\n\n                return _cacheKey;\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Justification = \"The method is a delegating helper to choose among multiple property values\")]\n        public virtual string GetDisplayName()\n        {\n            return PropertyName ?? ModelType.Name;\n        }\n\n        public virtual IEnumerable<ModelValidator> GetValidators(IEnumerable<ModelValidatorProvider> validatorProviders)\n        {\n            if (validatorProviders == null)\n            {\n                throw Error.ArgumentNull(\"validatorProviders\");\n            }\n\n            return validatorProviders.SelectMany(provider => provider.GetValidators(this, validatorProviders));\n        }\n\n        private static EfficientTypePropertyKey<Type, string> CreateCacheKey(Type containerType, Type modelType, string propertyName)\n        {\n            // If metadata is for a property then containerType != null && propertyName != null\n            // If metadata is for a type then containerType == null && propertyName == null, so we have to use modelType for the cache key.\n            return new EfficientTypePropertyKey<Type, string>(containerType ?? modelType, propertyName);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Metadata/ModelMetadataProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Http.Metadata\n{\n    public abstract class ModelMetadataProvider\n    {\n        public abstract IEnumerable<ModelMetadata> GetMetadataForProperties(object container, Type containerType);\n\n        public abstract ModelMetadata GetMetadataForProperty(Func<object> modelAccessor, Type containerType, string propertyName);\n\n        public abstract ModelMetadata GetMetadataForType(Func<object> modelAccessor, Type modelType);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Metadata/Providers/AssociatedMetadataProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics.Contracts;\nusing System.Reflection;\nusing System.Reflection.Emit;\nusing System.Web.Http.Internal;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.Metadata.Providers\n{\n    public abstract class AssociatedMetadataProvider<TModelMetadata> : ModelMetadataProvider\n        where TModelMetadata : ModelMetadata\n    {\n        private ConcurrentDictionary<Type, TypeInformation> _typeInfoCache = new ConcurrentDictionary<Type, TypeInformation>();\n\n        public sealed override IEnumerable<ModelMetadata> GetMetadataForProperties(object container, Type containerType)\n        {\n            if (containerType == null)\n            {\n                throw Error.ArgumentNull(\"containerType\");\n            }\n\n            return GetMetadataForPropertiesImpl(container, containerType);\n        }\n\n        private IEnumerable<ModelMetadata> GetMetadataForPropertiesImpl(object container, Type containerType)\n        {\n            TypeInformation typeInfo = GetTypeInformation(containerType);\n            foreach (KeyValuePair<string, PropertyInformation> kvp in typeInfo.Properties)\n            {\n                PropertyInformation propertyInfo = kvp.Value;\n                Func<object> modelAccessor = null;\n                if (container != null)\n                {\n                    Func<object, object> propertyGetter = propertyInfo.ValueAccessor;\n                    modelAccessor = () => propertyGetter(container);\n                }\n                yield return CreateMetadataFromPrototype(propertyInfo.Prototype, modelAccessor);\n            }\n        }\n\n        public sealed override ModelMetadata GetMetadataForProperty(Func<object> modelAccessor, Type containerType, string propertyName)\n        {\n            if (containerType == null)\n            {\n                throw Error.ArgumentNull(\"containerType\");\n            }\n            if (String.IsNullOrEmpty(propertyName))\n            {\n                throw Error.ArgumentNullOrEmpty(\"propertyName\");\n            }\n\n            TypeInformation typeInfo = GetTypeInformation(containerType);\n            PropertyInformation propertyInfo;\n            if (!typeInfo.Properties.TryGetValue(propertyName, out propertyInfo))\n            {\n                throw Error.Argument(\"propertyName\", SRResources.Common_PropertyNotFound, containerType, propertyName);\n            }\n\n            return CreateMetadataFromPrototype(propertyInfo.Prototype, modelAccessor);\n        }\n\n        public sealed override ModelMetadata GetMetadataForType(Func<object> modelAccessor, Type modelType)\n        {\n            if (modelType == null)\n            {\n                throw Error.ArgumentNull(\"modelType\");\n            }\n\n            TModelMetadata prototype = GetTypeInformation(modelType).Prototype;\n            return CreateMetadataFromPrototype(prototype, modelAccessor);\n        }\n\n        // Override for creating the prototype metadata (without the accessor)\n        protected abstract TModelMetadata CreateMetadataPrototype(IEnumerable<Attribute> attributes, Type containerType, Type modelType, string propertyName);\n\n        // Override for applying the prototype + modelAccess to yield the final metadata\n        protected abstract TModelMetadata CreateMetadataFromPrototype(TModelMetadata prototype, Func<object> modelAccessor);\n\n        private TypeInformation GetTypeInformation(Type type)\n        {\n            // This retrieval is implemented as a TryGetValue/TryAdd instead of a GetOrAdd to avoid the performance cost of creating instance delegates\n            TypeInformation typeInfo;\n            if (!_typeInfoCache.TryGetValue(type, out typeInfo))\n            {\n                typeInfo = CreateTypeInformation(type);\n                _typeInfoCache.TryAdd(type, typeInfo);\n            }\n            return typeInfo;\n        }\n\n        private TypeInformation CreateTypeInformation(Type type)\n        {\n            TypeInformation info = new TypeInformation();\n            ICustomTypeDescriptor typeDescriptor = TypeDescriptorHelper.Get(type);\n            info.TypeDescriptor = typeDescriptor;\n            info.Prototype = CreateMetadataPrototype(AsAttributes(typeDescriptor.GetAttributes()), containerType: null, modelType: type, propertyName: null);\n            \n            Dictionary<string, PropertyInformation> properties = new Dictionary<string, PropertyInformation>();\n            foreach (PropertyDescriptor property in typeDescriptor.GetProperties())\n            {\n                // Avoid re-generating a property descriptor if one has already been generated for the property name\n                if (!properties.ContainsKey(property.Name))\n                {\n                    properties.Add(property.Name, CreatePropertyInformation(type, property));\n                }\n            }\n            info.Properties = properties;\n\n            return info;\n        }\n\n        private PropertyInformation CreatePropertyInformation(Type containerType, PropertyDescriptor property)\n        {\n            PropertyInformation info = new PropertyInformation();\n            info.ValueAccessor = CreatePropertyValueAccessor(property);\n            info.Prototype = CreateMetadataPrototype(AsAttributes(property.Attributes), containerType, property.PropertyType, property.Name);\n            return info;\n        }\n\n        // Optimization: yield provides much better performance than the LINQ .Cast<Attribute>() in this case\n        private static IEnumerable<Attribute> AsAttributes(IEnumerable attributes)\n        {\n            foreach (object attribute in attributes)\n            {\n                yield return attribute as Attribute;\n            }\n        }\n\n        private static Func<object, object> CreatePropertyValueAccessor(PropertyDescriptor property)\n        {\n            Type declaringType = property.ComponentType;\n            if (declaringType.IsVisible)\n            {\n                string propertyName = property.Name;\n                PropertyInfo propertyInfo = declaringType.GetProperty(propertyName, property.PropertyType);\n\n                if (propertyInfo != null && propertyInfo.CanRead)\n                {\n                    MethodInfo getMethodInfo = propertyInfo.GetGetMethod();\n                    if (getMethodInfo != null)\n                    {\n                        return CreateDynamicValueAccessor(getMethodInfo, declaringType, propertyName);\n                    }\n                }\n            }\n\n            // If either the type isn't public or we can't find a public getter, use the slow Reflection path\n            return container => property.GetValue(container);\n        }\n\n        // Uses Lightweight Code Gen to generate a tiny delegate that gets the property value\n        // This is an optimization to avoid having to go through the much slower System.Reflection APIs\n        // e.g. generates (object o) => (Person)o.Id\n        private static Func<object, object> CreateDynamicValueAccessor(MethodInfo getMethodInfo, Type declaringType, string propertyName)\n        {\n            Contract.Assert(getMethodInfo != null && getMethodInfo.IsPublic && !getMethodInfo.IsStatic);\n\n            Type propertyType = getMethodInfo.ReturnType;\n            DynamicMethod dynamicMethod = new DynamicMethod(\"Get\" + propertyName + \"From\" + declaringType.Name, typeof(object), new Type[] { typeof(object) });\n            ILGenerator ilg = dynamicMethod.GetILGenerator();\n\n            // Load the container onto the stack, convert from object => declaring type for the property\n            ilg.Emit(OpCodes.Ldarg_0);\n            if (declaringType.IsValueType)\n            {\n                ilg.Emit(OpCodes.Unbox, declaringType);\n            }\n            else\n            {\n                ilg.Emit(OpCodes.Castclass, declaringType);\n            }\n\n            // if declaring type is value type, we use Call : structs don't have inheritance\n            // if get method is sealed or isn't virtual, we use Call : it can't be overridden\n            if (declaringType.IsValueType || !getMethodInfo.IsVirtual || getMethodInfo.IsFinal)\n            {\n                ilg.Emit(OpCodes.Call, getMethodInfo);\n            }\n            else\n            {\n                ilg.Emit(OpCodes.Callvirt, getMethodInfo);\n            }\n\n            // Box if the property type is a value type, so it can be returned as an object\n            if (propertyType.IsValueType)\n            {\n                ilg.Emit(OpCodes.Box, propertyType);\n            }\n\n            // Return property value\n            ilg.Emit(OpCodes.Ret);\n\n            return (Func<object, object>)dynamicMethod.CreateDelegate(typeof(Func<object, object>));\n        }\n\n        private class TypeInformation\n        {\n            public ICustomTypeDescriptor TypeDescriptor { get; set; }\n            public TModelMetadata Prototype { get; set; }\n            public Dictionary<string, PropertyInformation> Properties { get; set; }\n        }\n\n        private class PropertyInformation\n        {\n            public Func<object, object> ValueAccessor { get; set; }\n            public TModelMetadata Prototype { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Metadata/Providers/CachedDataAnnotationsMetadataAttributes.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing System.Security;\n\nnamespace System.Web.Http.Metadata.Providers\n{\n    public class CachedDataAnnotationsMetadataAttributes\n    {\n        public CachedDataAnnotationsMetadataAttributes(IEnumerable<Attribute> attributes)\n        {\n            Display = attributes.OfType<DisplayAttribute>().FirstOrDefault();\n            DisplayFormat = attributes.OfType<DisplayFormatAttribute>().FirstOrDefault();\n            DisplayName = attributes.OfType<DisplayNameAttribute>().FirstOrDefault();\n            Editable = attributes.OfType<EditableAttribute>().FirstOrDefault();\n            ReadOnly = attributes.OfType<ReadOnlyAttribute>().FirstOrDefault();\n        }\n\n        public DisplayAttribute Display { get; protected set; }\n\n        public DisplayNameAttribute DisplayName { get; protected set; }\n\n        public DisplayFormatAttribute DisplayFormat { get; protected set; }\n\n        public EditableAttribute Editable { get; protected set; }\n\n        public ReadOnlyAttribute ReadOnly { get; protected set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Metadata/Providers/CachedDataAnnotationsModelMetadata.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Http.Metadata.Providers\n{\n    // REVIEW: No access to HiddenInputAttribute\n    public class CachedDataAnnotationsModelMetadata : CachedModelMetadata<CachedDataAnnotationsMetadataAttributes>\n    {\n        public CachedDataAnnotationsModelMetadata(CachedDataAnnotationsModelMetadata prototype, Func<object> modelAccessor)\n            : base(prototype, modelAccessor)\n        {\n        }\n\n        public CachedDataAnnotationsModelMetadata(DataAnnotationsModelMetadataProvider provider, Type containerType, Type modelType, string propertyName, IEnumerable<Attribute> attributes)\n            : base(provider, containerType, modelType, propertyName, new CachedDataAnnotationsMetadataAttributes(attributes))\n        {\n        }\n\n        protected override bool ComputeConvertEmptyStringToNull()\n        {\n            return PrototypeCache.DisplayFormat != null\n                       ? PrototypeCache.DisplayFormat.ConvertEmptyStringToNull\n                       : base.ComputeConvertEmptyStringToNull();\n        }\n\n        protected override string ComputeDescription()\n        {\n            return PrototypeCache.Display != null\n                       ? PrototypeCache.Display.GetDescription()\n                       : base.ComputeDescription();\n        }\n\n        protected override bool ComputeIsReadOnly()\n        {\n            if (PrototypeCache.Editable != null)\n            {\n                return !PrototypeCache.Editable.AllowEdit;\n            }\n\n            if (PrototypeCache.ReadOnly != null)\n            {\n                return PrototypeCache.ReadOnly.IsReadOnly;\n            }\n\n            return base.ComputeIsReadOnly();\n        }\n\n        public override string GetDisplayName()\n        {\n            // DisplayName could be provided by either the DisplayAttribute, or DisplayNameAttribute. If neither of\n            // those supply a name, then we fall back to the property name (in base.GetDisplayName()).\n            // \n            // DisplayName has lower precedence than Display.Name, for consistency with MVC.\n\n            // DisplayAttribute doesn't require you to set a name, so this could be null. \n            if (PrototypeCache.Display != null)\n            {\n                string name = PrototypeCache.Display.GetName();\n                if (name != null)\n                {\n                    return name;\n                }\n            }\n\n            // It's also possible for DisplayNameAttribute to be used without setting a name. If a user does that, then DisplayName will\n            // return the empty string - but for consistency with MVC we allow it. We do fallback to the property name in the (unlikely)\n            // scenario that the user sets null as the DisplayName, again, for consistency with MVC.\n            if (PrototypeCache.DisplayName != null)\n            {\n                string name = PrototypeCache.DisplayName.DisplayName;\n                if (name != null)\n                {\n                    return name;\n                }\n            }\n\n            // If neither attribute specifies a name, we'll fall back to the property name.\n            return base.GetDisplayName();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Metadata/Providers/CachedModelMetadata.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Metadata.Providers\n{\n    // This class assumes that model metadata is expensive to create, and allows the user to\n    // stash a cache object that can be copied around as a prototype to make creation and\n    // computation quicker. It delegates the retrieval of values to getter methods, the results\n    // of which are cached on a per-metadata-instance basis.\n    //\n    // This allows flexible caching strategies: either caching the source of information across\n    // instances or caching of the actual information itself, depending on what the developer\n    // decides to put into the prototype cache.\n    public abstract class CachedModelMetadata<TPrototypeCache> : ModelMetadata\n    {\n        private bool _convertEmptyStringToNull;\n        private string _description;\n        private bool _isReadOnly;\n        private bool _isComplexType;\n\n        private bool _convertEmptyStringToNullComputed;\n        private bool _descriptionComputed;\n        private bool _isReadOnlyComputed;\n        private bool _isComplexTypeComputed;\n\n        // Constructor for creating real instances of the metadata class based on a prototype\n        protected CachedModelMetadata(CachedModelMetadata<TPrototypeCache> prototype, Func<object> modelAccessor)\n            : base(prototype.Provider, prototype.ContainerType, modelAccessor, prototype.ModelType, prototype.PropertyName, prototype.CacheKey)\n        {\n            PrototypeCache = prototype.PrototypeCache;\n\n            _isComplexType = prototype.IsComplexType;\n            _isComplexTypeComputed = true;\n        }\n\n        // Constructor for creating the prototype instances of the metadata class\n        protected CachedModelMetadata(DataAnnotationsModelMetadataProvider provider, Type containerType, Type modelType, string propertyName, TPrototypeCache prototypeCache)\n            : base(provider, containerType, null /* modelAccessor */, modelType, propertyName)\n        {\n            PrototypeCache = prototypeCache;\n        }\n\n        public sealed override bool ConvertEmptyStringToNull\n        {\n            get\n            {\n                if (!_convertEmptyStringToNullComputed)\n                {\n                    _convertEmptyStringToNull = ComputeConvertEmptyStringToNull();\n                    _convertEmptyStringToNullComputed = true;\n                }\n                return _convertEmptyStringToNull;\n            }\n            set\n            {\n                _convertEmptyStringToNull = value;\n                _convertEmptyStringToNullComputed = true;\n            }\n        }\n\n        public sealed override string Description\n        {\n            get\n            {\n                if (!_descriptionComputed)\n                {\n                    _description = ComputeDescription();\n                    _descriptionComputed = true;\n                }\n                return _description;\n            }\n            set\n            {\n                _description = value;\n                _descriptionComputed = true;\n            }\n        }\n\n        public sealed override bool IsReadOnly\n        {\n            get\n            {\n                if (!_isReadOnlyComputed)\n                {\n                    _isReadOnly = ComputeIsReadOnly();\n                    _isReadOnlyComputed = true;\n                }\n                return _isReadOnly;\n            }\n            set\n            {\n                _isReadOnly = value;\n                _isReadOnlyComputed = true;\n            }\n        }\n\n        public sealed override bool IsComplexType\n        {\n            get\n            {\n                if (!_isComplexTypeComputed)\n                {\n                    _isComplexType = ComputeIsComplexType();\n                    _isComplexTypeComputed = true;\n                }\n                return _isComplexType;\n            }\n        }\n\n        protected TPrototypeCache PrototypeCache { get; set; }\n\n        protected virtual bool ComputeConvertEmptyStringToNull()\n        {\n            return base.ConvertEmptyStringToNull;\n        }\n\n        protected virtual string ComputeDescription()\n        {\n            return base.Description;\n        }\n\n        protected virtual bool ComputeIsReadOnly()\n        {\n            return base.IsReadOnly;\n        }\n\n        protected virtual bool ComputeIsComplexType()\n        {\n            return base.IsComplexType;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Metadata/Providers/DataAnnotationsModelMetadataProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Http.Metadata.Providers\n{\n    public class DataAnnotationsModelMetadataProvider : AssociatedMetadataProvider<CachedDataAnnotationsModelMetadata>\n    {\n        protected override CachedDataAnnotationsModelMetadata CreateMetadataPrototype(IEnumerable<Attribute> attributes, Type containerType, Type modelType, string propertyName)\n        {\n            return new CachedDataAnnotationsModelMetadata(this, containerType, modelType, propertyName, attributes);\n        }\n\n        protected override CachedDataAnnotationsModelMetadata CreateMetadataFromPrototype(CachedDataAnnotationsModelMetadata prototype, Func<object> modelAccessor)\n        {\n            return new CachedDataAnnotationsModelMetadata(prototype, modelAccessor);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Metadata/Providers/EmptyMetadataProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Http.Metadata.Providers\n{\n    public class EmptyModelMetadataProvider : AssociatedMetadataProvider<ModelMetadata>\n    {\n        protected override ModelMetadata CreateMetadataPrototype(IEnumerable<Attribute> attributes, Type containerType, Type modelType, string propertyName)\n        {\n            return new ModelMetadata(this, containerType, null, modelType, propertyName);\n        }\n\n        protected override ModelMetadata CreateMetadataFromPrototype(ModelMetadata prototype, Func<object> modelAccessor)\n        {\n            return new ModelMetadata(this, prototype.ContainerType, modelAccessor, prototype.ModelType, prototype.PropertyName);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/Binders/ArrayModelBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public class ArrayModelBinder<TElement> : CollectionModelBinder<TElement>\n    {\n        public override bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)\n        {\n            if (bindingContext.ModelMetadata.IsReadOnly)\n            {\n                return false;\n            }\n\n            return base.BindModel(actionContext, bindingContext);\n        }\n\n        protected override bool CreateOrReplaceCollection(HttpActionContext actionContext, ModelBindingContext bindingContext, IList<TElement> newCollection)\n        {\n            bindingContext.Model = newCollection.ToArray();\n            return true;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/Binders/ArrayModelBinderProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public sealed class ArrayModelBinderProvider : ModelBinderProvider\n    {\n        public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)\n        {\n            if (modelType == null)\n            {\n                throw Error.ArgumentNull(\"modelType\");\n            }\n\n            if (!modelType.IsArray)\n            {\n                return null;\n            }\n\n            Type elementType = modelType.GetElementType();\n            return (IModelBinder)Activator.CreateInstance(typeof(ArrayModelBinder<>).MakeGenericType(elementType));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/Binders/CollectionModelBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Internal;\nusing System.Web.Http.ValueProviders;\nusing System.Web.Http.ValueProviders.Providers;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public class CollectionModelBinder<TElement> : IModelBinder\n    {\n        // Used when the ValueProvider contains the collection to be bound as multiple elements, e.g. foo[0], foo[1].\n        private static List<TElement> BindComplexCollection(HttpActionContext actionContext, ModelBindingContext bindingContext)\n        {\n            string indexPropertyName = ModelBindingHelper.CreatePropertyModelName(bindingContext.ModelName, \"index\");\n            ValueProviderResult valueProviderResultIndex = bindingContext.ValueProvider.GetValue(indexPropertyName);\n            IEnumerable<string> indexNames = CollectionModelBinderUtil.GetIndexNamesFromValueProviderResult(valueProviderResultIndex);\n            return BindComplexCollectionFromIndexes(actionContext, bindingContext, indexNames);\n        }\n\n        internal static List<TElement> BindComplexCollectionFromIndexes(HttpActionContext actionContext, ModelBindingContext bindingContext, IEnumerable<string> indexNames)\n        {\n            bool indexNamesIsFinite;\n            if (indexNames != null)\n            {\n                indexNamesIsFinite = true;\n            }\n            else\n            {\n                indexNamesIsFinite = false;\n                indexNames = CollectionModelBinderUtil.GetZeroBasedIndexes();\n            }\n\n            List<TElement> boundCollection = new List<TElement>();\n            foreach (string indexName in indexNames)\n            {\n                string fullChildName = ModelBindingHelper.CreateIndexModelName(bindingContext.ModelName, indexName);\n                ModelBindingContext childBindingContext = new ModelBindingContext(bindingContext)\n                {\n                    ModelMetadata = actionContext.GetMetadataProvider().GetMetadataForType(null, typeof(TElement)),\n                    ModelName = fullChildName\n                };\n\n                bool didBind = false;\n                object boundValue = null;                \n                if (actionContext.Bind(childBindingContext))                \n                {\n                    didBind = true;\n                    boundValue = childBindingContext.Model;\n\n                    // merge validation up\n                    bindingContext.ValidationNode.ChildNodes.Add(childBindingContext.ValidationNode);\n                }                \n\n                // infinite size collection stops on first bind failure\n                if (!didBind && !indexNamesIsFinite)\n                {\n                    break;\n                }\n\n                boundCollection.Add(ModelBindingHelper.CastOrDefault<TElement>(boundValue));\n            }\n\n            return boundCollection;\n        }\n\n        public virtual bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)\n        {\n            ModelBindingHelper.ValidateBindingContext(bindingContext);\n\n            if (!bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName))\n            {\n                return false;\n            }\n\n            ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);\n            List<TElement> boundCollection = (valueProviderResult != null)\n                                                 ? BindSimpleCollection(actionContext, bindingContext, valueProviderResult.RawValue, valueProviderResult.Culture)\n                                                 : BindComplexCollection(actionContext, bindingContext);\n\n            bool retVal = CreateOrReplaceCollection(actionContext, bindingContext, boundCollection);\n            return retVal;\n        }\n\n        // Used when the ValueProvider contains the collection to be bound as a single element, e.g. the raw value\n        // is [ \"1\", \"2\" ] and needs to be converted to an int[].\n        internal static List<TElement> BindSimpleCollection(HttpActionContext actionContext, ModelBindingContext bindingContext, object rawValue, CultureInfo culture)\n        {\n            if (rawValue == null)\n            {\n                return null; // nothing to do\n            }\n\n            List<TElement> boundCollection = new List<TElement>();\n\n            object[] rawValueArray = ModelBindingHelper.RawValueToObjectArray(rawValue);\n            foreach (object rawValueElement in rawValueArray)\n            {\n                ModelBindingContext innerBindingContext = new ModelBindingContext(bindingContext)\n                {\n                    ModelMetadata = actionContext.GetMetadataProvider().GetMetadataForType(null, typeof(TElement)),\n                    ModelName = bindingContext.ModelName,\n                    ValueProvider = new CompositeValueProvider\n                    {\n                        new ElementalValueProvider(bindingContext.ModelName, rawValueElement, culture), // our temporary provider goes at the front of the list\n                        bindingContext.ValueProvider\n                    }\n                };\n\n                object boundValue = null;\n                if (actionContext.Bind(innerBindingContext))                \n                {\n                    boundValue = innerBindingContext.Model;\n                    bindingContext.ValidationNode.ChildNodes.Add(innerBindingContext.ValidationNode);\n                }                \n                boundCollection.Add(ModelBindingHelper.CastOrDefault<TElement>(boundValue));\n            }\n\n            return boundCollection;\n        }\n\n        // Extensibility point that allows the bound collection to be manipulated or transformed before\n        // being returned from the binder.\n        protected virtual bool CreateOrReplaceCollection(HttpActionContext actionContext, ModelBindingContext bindingContext, IList<TElement> newCollection)\n        {\n            CollectionModelBinderUtil.CreateOrReplaceCollection(bindingContext, newCollection, () => new List<TElement>());\n            return true;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/Binders/CollectionModelBinderProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Internal;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public sealed class CollectionModelBinderProvider : ModelBinderProvider\n    {\n        public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)\n        {            \n            return CollectionModelBinderUtil.GetGenericBinder(typeof(ICollection<>), typeof(List<>), typeof(CollectionModelBinder<>), modelType); \n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/Binders/ComplexModelDto.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Web.Http.Metadata;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    // Describes a complex model, but uses a collection rather than individual properties as the data store.\n    public class ComplexModelDto\n    {\n        public ComplexModelDto(ModelMetadata modelMetadata, IEnumerable<ModelMetadata> propertyMetadata)\n        {\n            if (modelMetadata == null)\n            {\n                throw Error.ArgumentNull(\"modelMetadata\");\n            }\n\n            if (propertyMetadata == null)\n            {\n                throw Error.ArgumentNull(\"propertyMetadata\");\n            }\n\n            ModelMetadata = modelMetadata;\n            PropertyMetadata = new Collection<ModelMetadata>(propertyMetadata.ToList());\n            Results = new Dictionary<ModelMetadata, ComplexModelDtoResult>();\n        }\n\n        public ModelMetadata ModelMetadata { get; private set; }\n\n        public Collection<ModelMetadata> PropertyMetadata { get; private set; }\n\n        // Contains entries corresponding to each property against which binding was\n        // attempted. If binding failed, the entry's value will be null. If binding\n        // was never attempted, this dictionary will not contain a corresponding\n        // entry.\n        public IDictionary<ModelMetadata, ComplexModelDtoResult> Results { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/Binders/ComplexModelDtoModelBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.ValueProviders;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public sealed class ComplexModelDtoModelBinder : IModelBinder\n    {\n        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)\n        {\n            ModelBindingHelper.ValidateBindingContext(bindingContext, typeof(ComplexModelDto), false /* allowNullModel */);\n\n            ComplexModelDto dto = (ComplexModelDto)bindingContext.Model;\n            foreach (ModelMetadata propertyMetadata in dto.PropertyMetadata)\n            {\n                ModelBindingContext propertyBindingContext = new ModelBindingContext(bindingContext)\n                {\n                    ModelMetadata = propertyMetadata,\n                    ModelName = ModelBindingHelper.CreatePropertyModelName(bindingContext.ModelName, propertyMetadata.PropertyName)\n                };\n\n                // bind and propagate the values\n                // If we can't bind, then leave the result missing (don't add a null).\n                if (actionContext.Bind(propertyBindingContext))\n                {\n                    dto.Results[propertyMetadata] = new ComplexModelDtoResult(propertyBindingContext.Model, propertyBindingContext.ValidationNode);\n                }\n            }\n\n            return true;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/Binders/ComplexModelDtoModelBinderProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    // Returns a binder that can bind ComplexModelDto objects.\n    public sealed class ComplexModelDtoModelBinderProvider : ModelBinderProvider\n    {\n        // This is really just a simple binder.\n        private static readonly SimpleModelBinderProvider _underlyingProvider = GetUnderlyingProvider();\n\n        public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)\n        {\n            return _underlyingProvider.GetBinder(configuration, modelType);\n        }\n\n        private static SimpleModelBinderProvider GetUnderlyingProvider()\n        {\n            return new SimpleModelBinderProvider(typeof(ComplexModelDto), new ComplexModelDtoModelBinder())\n            {\n                SuppressPrefixCheck = true\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/Binders/ComplexModelDtoResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Validation;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public sealed class ComplexModelDtoResult\n    {\n        public ComplexModelDtoResult(object model, ModelValidationNode validationNode)\n        {\n            if (validationNode == null)\n            {\n                throw Error.ArgumentNull(\"validationNode\");\n            }\n\n            Model = model;\n            ValidationNode = validationNode;\n        }\n\n        public object Model { get; private set; }\n\n        public ModelValidationNode ValidationNode { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/Binders/CompositeModelBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    /// <summary>\n    /// This class is an <see cref=\"IModelBinder\"/> that delegates to one of a collection of\n    /// <see cref=\"ModelBinderProvider\"/> instances.\n    /// </summary>\n    /// <remarks>\n    /// If no binder is available and the <see cref=\"ModelBindingContext\"/> allows it,\n    /// this class tries to find a binder using an empty prefix.\n    /// </remarks>\n    public class CompositeModelBinder : IModelBinder\n    {\n        public CompositeModelBinder(IEnumerable<IModelBinder> binders)\n            : this(binders.ToArray())\n        {\n        }\n\n        public CompositeModelBinder(params IModelBinder[] binders)\n        {\n            Binders = binders;\n        }\n\n        private IModelBinder[] Binders { get; set; }\n\n        public virtual bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)\n        {\n            ModelBindingContext newBindingContext = CreateNewBindingContext(bindingContext, bindingContext.ModelName);\n\n            bool boundSuccessfully = TryBind(actionContext, newBindingContext);\n            if (!boundSuccessfully && !String.IsNullOrEmpty(bindingContext.ModelName)\n                && bindingContext.FallbackToEmptyPrefix)\n            {\n                // fallback to empty prefix?\n                newBindingContext = CreateNewBindingContext(bindingContext, modelName: String.Empty);\n                boundSuccessfully = TryBind(actionContext, newBindingContext);\n            }\n\n            if (!boundSuccessfully)\n            {\n                return false; // something went wrong\n            }\n\n            // run validation and return the model\n            // If we fell back to an empty prefix above and are dealing with simple types,\n            // propagate the non-blank model name through for user clarity in validation errors.\n            // Complex types will reveal their individual properties as model names and do not require this.\n            if (!newBindingContext.ModelMetadata.IsComplexType && String.IsNullOrEmpty(newBindingContext.ModelName))\n            {\n                newBindingContext.ValidationNode = new Validation.ModelValidationNode(newBindingContext.ModelMetadata, bindingContext.ModelName);\n            }\n\n            newBindingContext.ValidationNode.Validate(actionContext, null /* parentNode */);\n            bindingContext.Model = newBindingContext.Model;\n            return true;\n        }\n\n        private bool TryBind(HttpActionContext actionContext, ModelBindingContext bindingContext)\n        {\n            return actionContext.Bind(bindingContext, Binders);\n        }\n\n        private static ModelBindingContext CreateNewBindingContext(ModelBindingContext oldBindingContext, string modelName)\n        {\n            ModelBindingContext newBindingContext = new ModelBindingContext\n            {\n                ModelMetadata = oldBindingContext.ModelMetadata,\n                ModelName = modelName,\n                ModelState = oldBindingContext.ModelState,\n                ValueProvider = oldBindingContext.ValueProvider\n            };\n\n            // validation is expensive to create, so copy it over if we can\n            if (Object.ReferenceEquals(modelName, oldBindingContext.ModelName))\n            {\n                newBindingContext.ValidationNode = oldBindingContext.ValidationNode;\n            }\n\n            return newBindingContext;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/Binders/CompositeModelBinderProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public sealed class CompositeModelBinderProvider : ModelBinderProvider\n    {\n        private ModelBinderProvider[] _providers;\n\n        public CompositeModelBinderProvider()\n        {\n        }\n\n        public CompositeModelBinderProvider(IEnumerable<ModelBinderProvider> providers)\n        {\n            if (providers == null)\n            {\n                throw Error.ArgumentNull(\"providers\");\n            }\n\n            _providers = providers.ToArray();\n        }\n\n        public IEnumerable<ModelBinderProvider> Providers\n        {\n            get { return _providers; }\n        }\n\n        public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)\n        {\n            IEnumerable<ModelBinderProvider> providers = _providers ?? configuration.Services.GetModelBinderProviders();\n\n            // Pre-filter out any binders that we know can't match. \n            IEnumerable<IModelBinder> binders = from provider in providers \n                                                let binder = provider.GetBinder(configuration, modelType) \n                                                where binder != null \n                                                select binder;\n            return new CompositeModelBinder(binders);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/Binders/DictionaryModelBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Internal;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public class DictionaryModelBinder<TKey, TValue> : CollectionModelBinder<KeyValuePair<TKey, TValue>>\n    {\n        protected override bool CreateOrReplaceCollection(HttpActionContext actionContext, ModelBindingContext bindingContext, IList<KeyValuePair<TKey, TValue>> newCollection)\n        {\n            CollectionModelBinderUtil.CreateOrReplaceDictionary(bindingContext, newCollection, () => new Dictionary<TKey, TValue>());\n            return true;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/Binders/DictionaryModelBinderProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http.Internal;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public sealed class DictionaryModelBinderProvider : ModelBinderProvider\n    {\n        public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)\n        {\n            return CollectionModelBinderUtil.GetGenericBinder(typeof(IDictionary<,>), typeof(Dictionary<,>), typeof(DictionaryModelBinder<,>), modelType);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/Binders/KeyValuePairModelBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Internal;\nusing System.Web.Http.Metadata;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public sealed class KeyValuePairModelBinder<TKey, TValue> : IModelBinder\n    {\n        internal ModelMetadataProvider MetadataProvider { private get; set; }\n\n        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)\n        {\n            ModelMetadataProvider metadataProvider = MetadataProvider ?? actionContext.GetMetadataProvider();\n            ModelBindingHelper.ValidateBindingContext(bindingContext, typeof(KeyValuePair<TKey, TValue>), true /* allowNullModel */);\n\n            TKey key;\n            bool keyBindingSucceeded = actionContext.TryBindStrongModel(bindingContext, \"key\", metadataProvider, out key);\n\n            TValue value;\n            bool valueBindingSucceeded = actionContext.TryBindStrongModel(bindingContext, \"value\", metadataProvider, out value);\n\n            if (keyBindingSucceeded && valueBindingSucceeded)\n            {\n                bindingContext.Model = new KeyValuePair<TKey, TValue>(key, value);\n            }\n            return keyBindingSucceeded || valueBindingSucceeded;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/Binders/KeyValuePairModelBinderProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public sealed class KeyValuePairModelBinderProvider : ModelBinderProvider\n    {\n        public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)\n        {\n            return ModelBindingHelper.GetPossibleBinderInstance(\n                closedModelType: modelType, \n                openModelType: typeof(KeyValuePair<,>), \n                openBinderType: typeof(KeyValuePairModelBinder<,>));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/Binders/MutableObjectModelBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Internal;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Validation;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public class MutableObjectModelBinder : IModelBinder\n    {\n        internal ModelMetadataProvider MetadataProvider { private get; set; }\n\n        internal static bool CanBindType(Type modelType)\n        {\n            // Simple types cannot use this binder\n            bool isComplexType = !TypeHelper.HasStringConverter(modelType);\n            if (!isComplexType)\n            {\n                return false;\n            }\n\n            if (modelType == typeof(ComplexModelDto))\n            {\n                // forbidden type - will cause a stack overflow if we try binding this type\n                return false;\n            }\n            return true;\n        }\n\n        public virtual bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)\n        {\n            ModelBindingHelper.ValidateBindingContext(bindingContext);\n\n            if (!bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName))\n            {\n                // no values to bind\n                return false;\n            }\n\n            if (!CanBindType(bindingContext.ModelType))\n            {\n                return false;\n            }\n\n            EnsureModel(actionContext, bindingContext);\n            IEnumerable<ModelMetadata> propertyMetadatas = GetMetadataForProperties(actionContext, bindingContext);\n            ComplexModelDto dto = CreateAndPopulateDto(actionContext, bindingContext, propertyMetadatas);\n\n            // post-processing, e.g. property setters and hooking up validation\n            ProcessDto(actionContext, bindingContext, dto);\n            bindingContext.ValidationNode.ValidateAllProperties = true; // complex models require full validation\n            return true;\n        }\n\n        protected virtual bool CanUpdateProperty(ModelMetadata propertyMetadata)\n        {\n            return CanUpdatePropertyInternal(propertyMetadata);\n        }\n\n        internal static bool CanUpdatePropertyInternal(ModelMetadata propertyMetadata)\n        {\n            return !propertyMetadata.IsReadOnly || CanUpdateReadOnlyProperty(propertyMetadata.ModelType);\n        }\n\n        private static bool CanUpdateReadOnlyProperty(Type propertyType)\n        {\n            // Value types have copy-by-value semantics, which prevents us from updating\n            // properties that are marked readonly.\n            if (propertyType.IsValueType)\n            {\n                return false;\n            }\n\n            // Arrays are strange beasts since their contents are mutable but their sizes aren't.\n            // Therefore we shouldn't even try to update these. Further reading:\n            // http://blogs.msdn.com/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx\n            if (propertyType.IsArray)\n            {\n                return false;\n            }\n\n            // Special-case known immutable reference types\n            if (propertyType == typeof(string))\n            {\n                return false;\n            }\n\n            return true;\n        }\n\n        private ComplexModelDto CreateAndPopulateDto(HttpActionContext actionContext, ModelBindingContext bindingContext, IEnumerable<ModelMetadata> propertyMetadatas)\n        {\n            ModelMetadataProvider metadataProvider = MetadataProvider ?? actionContext.GetMetadataProvider();\n\n            // create a DTO and call into the DTO binder\n            ComplexModelDto originalDto = new ComplexModelDto(bindingContext.ModelMetadata, propertyMetadatas);\n            ModelBindingContext dtoBindingContext = new ModelBindingContext(bindingContext)\n            {\n                ModelMetadata = metadataProvider.GetMetadataForType(() => originalDto, typeof(ComplexModelDto)),\n                ModelName = bindingContext.ModelName\n            };\n\n            actionContext.Bind(dtoBindingContext);\n            return (ComplexModelDto)dtoBindingContext.Model;\n        }\n\n        protected virtual object CreateModel(HttpActionContext actionContext, ModelBindingContext bindingContext)\n        {\n            // If the Activator throws an exception, we want to propagate it back up the call stack, since the application\n            // developer should know that this was an invalid type to try to bind to.\n            return Activator.CreateInstance(bindingContext.ModelType);\n        }\n\n        // Called when the property setter null check failed, allows us to add our own error message to ModelState.\n        internal static EventHandler<ModelValidatedEventArgs> CreateNullCheckFailedHandler(ModelMetadata modelMetadata, object incomingValue)\n        {\n            return (sender, e) =>\n            {\n                ModelValidationNode validationNode = (ModelValidationNode)sender;\n                ModelStateDictionary modelState = e.ActionContext.ModelState;\n\n                if (modelState.IsValidField(validationNode.ModelStateKey))\n                {\n                    string errorMessage = ModelBinderConfig.ValueRequiredErrorMessageProvider(e.ActionContext, modelMetadata, incomingValue);\n                    if (errorMessage != null)\n                    {\n                        modelState.AddModelError(validationNode.ModelStateKey, errorMessage);\n                    }\n                }\n            };\n        }\n\n        protected virtual void EnsureModel(HttpActionContext actionContext, ModelBindingContext bindingContext)\n        {            \n            if (bindingContext.Model == null)\n            {\n                bindingContext.ModelMetadata.Model = CreateModel(actionContext, bindingContext);\n            }\n        }\n\n        protected virtual IEnumerable<ModelMetadata> GetMetadataForProperties(HttpActionContext actionContext, ModelBindingContext bindingContext)\n        {\n            // keep a set of the required properties so that we can cross-reference bound properties later\n            HashSet<string> requiredProperties;\n            Dictionary<string, ModelValidator> requiredValidators;\n            HashSet<string> skipProperties;\n            GetRequiredPropertiesCollection(actionContext, bindingContext, out requiredProperties, out requiredValidators, out skipProperties);\n\n            return from propertyMetadata in bindingContext.ModelMetadata.Properties\n                   let propertyName = propertyMetadata.PropertyName\n                   let shouldUpdateProperty = requiredProperties.Contains(propertyName) || !skipProperties.Contains(propertyName)\n                   where shouldUpdateProperty && CanUpdateProperty(propertyMetadata)\n                   select propertyMetadata;\n        }\n\n        private static object GetPropertyDefaultValue(PropertyDescriptor propertyDescriptor)\n        {\n            DefaultValueAttribute attr = propertyDescriptor.Attributes.OfType<DefaultValueAttribute>().FirstOrDefault();\n            return (attr != null) ? attr.Value : null;\n        }\n\n        internal static void GetRequiredPropertiesCollection(HttpActionContext actionContext, ModelBindingContext bindingContext, out HashSet<string> requiredProperties, out Dictionary<string, ModelValidator> requiredValidators, out HashSet<string> skipProperties)\n        {\n            requiredProperties = new HashSet<string>(StringComparer.OrdinalIgnoreCase);\n            requiredValidators = new Dictionary<string, ModelValidator>(StringComparer.OrdinalIgnoreCase);\n            skipProperties = new HashSet<string>(StringComparer.OrdinalIgnoreCase);\n\n            // Use attributes on the property before attributes on the type.\n            ICustomTypeDescriptor modelDescriptor = TypeDescriptorHelper.Get(bindingContext.ModelType);\n            PropertyDescriptorCollection propertyDescriptors = modelDescriptor.GetProperties();\n            HttpBindingBehaviorAttribute typeAttr = modelDescriptor.GetAttributes().OfType<HttpBindingBehaviorAttribute>().SingleOrDefault();\n\n            foreach (PropertyDescriptor propertyDescriptor in propertyDescriptors)\n            {\n                string propertyName = propertyDescriptor.Name;\n                ModelMetadata propertyMetadata = bindingContext.PropertyMetadata[propertyName];\n                ModelValidator requiredValidator = actionContext.GetValidators(propertyMetadata).Where(v => v.IsRequired).FirstOrDefault();\n                requiredValidators[propertyName] = requiredValidator;\n\n                HttpBindingBehaviorAttribute propAttr = propertyDescriptor.Attributes.OfType<HttpBindingBehaviorAttribute>().SingleOrDefault();\n                HttpBindingBehaviorAttribute workingAttr = propAttr ?? typeAttr;\n                if (workingAttr != null)\n                {\n                    switch (workingAttr.Behavior)\n                    {\n                        case HttpBindingBehavior.Required:\n                            requiredProperties.Add(propertyName);\n                            break;\n\n                        case HttpBindingBehavior.Never:\n                            skipProperties.Add(propertyName);\n                            break;\n                    }\n                }\n                else if (requiredValidator != null)\n                {\n                    requiredProperties.Add(propertyName);\n                }\n            }\n        }\n\n        internal void ProcessDto(HttpActionContext actionContext, ModelBindingContext bindingContext, ComplexModelDto dto)\n        {\n            HashSet<string> requiredProperties;\n            Dictionary<string, ModelValidator> requiredValidators;\n            HashSet<string> skipProperties;\n            GetRequiredPropertiesCollection(actionContext, bindingContext, out requiredProperties, out requiredValidators, out skipProperties);\n\n            // Eliminate provided properties from requiredProperties; leaving just *missing* required properties.\n            requiredProperties.ExceptWith(dto.Results.Select(r => r.Key.PropertyName));\n\n            foreach (string missingRequiredProperty in requiredProperties)\n            {\n                string modelStateKey = ModelBindingHelper.CreatePropertyModelName(\n                    bindingContext.ValidationNode.ModelStateKey, missingRequiredProperty);\n\n                // Update Model as SetProperty() would: Place null value where validator will check for non-null. This\n                // ensures a failure result from a required validator (if any) even for a non-nullable property.\n                // (Otherwise, propertyMetadata.Model is likely already null.)\n                ModelMetadata propertyMetadata = bindingContext.PropertyMetadata[missingRequiredProperty];\n                propertyMetadata.Model = null;\n\n                // Execute validator (if any) to get custom error message.\n                ModelValidator validator = requiredValidators[missingRequiredProperty];\n                bool addedError = RunValidator(validator, bindingContext, propertyMetadata, modelStateKey);\n\n                // Fall back to default message if HttpBindingBehaviorAttribute required this property or validator\n                // (oddly) succeeded.\n                if (!addedError)\n                {\n                    bindingContext.ModelState.AddModelError(modelStateKey,\n                        Error.Format(SRResources.MissingRequiredMember, missingRequiredProperty));\n                }\n            }\n\n            // for each property that was bound, call the setter, recording exceptions as necessary\n            foreach (var entry in dto.Results)\n            {\n                ModelMetadata propertyMetadata = entry.Key;\n\n                ComplexModelDtoResult dtoResult = entry.Value;\n                if (dtoResult != null)\n                {\n                    SetProperty(actionContext, bindingContext, propertyMetadata, dtoResult, requiredValidators[propertyMetadata.PropertyName]);\n                    bindingContext.ValidationNode.ChildNodes.Add(dtoResult.ValidationNode);\n                }\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We're recording this exception so that we can act on it later.\")]\n        protected virtual void SetProperty(HttpActionContext actionContext, ModelBindingContext bindingContext, ModelMetadata propertyMetadata, ComplexModelDtoResult dtoResult, ModelValidator requiredValidator)\n        {\n            PropertyDescriptor propertyDescriptor = TypeDescriptorHelper.Get(bindingContext.ModelType).GetProperties().Find(propertyMetadata.PropertyName, true /* ignoreCase */);\n            if (propertyDescriptor == null || propertyDescriptor.IsReadOnly)\n            {\n                return; // nothing to do\n            }\n\n            object value = dtoResult.Model ?? GetPropertyDefaultValue(propertyDescriptor);\n            propertyMetadata.Model = value;\n\n            // 'Required' validators need to run first so that we can provide useful error messages if\n            // the property setters throw, e.g. if we're setting entity keys to null. See comments in\n            // DefaultModelBinder.SetProperty() for more information.\n            if (value == null)\n            {\n                string modelStateKey = dtoResult.ValidationNode.ModelStateKey;\n                if (bindingContext.ModelState.IsValidField(modelStateKey))\n                {\n                    RunValidator(requiredValidator, bindingContext, propertyMetadata, modelStateKey);\n                }\n            }\n\n            if (value != null || TypeHelper.TypeAllowsNullValue(propertyDescriptor.PropertyType))\n            {\n                try\n                {\n                    propertyDescriptor.SetValue(bindingContext.Model, value);\n                }\n                catch (Exception ex)\n                {\n                    // don't display a duplicate error message if a binding error has already occurred for this field\n                    string modelStateKey = dtoResult.ValidationNode.ModelStateKey;\n                    if (bindingContext.ModelState.IsValidField(modelStateKey))\n                    {\n                        bindingContext.ModelState.AddModelError(modelStateKey, ex);\n                    }\n                }\n            }\n            else\n            {\n                // trying to set a non-nullable value type to null, need to make sure there's a message\n                string modelStateKey = dtoResult.ValidationNode.ModelStateKey;\n                if (bindingContext.ModelState.IsValidField(modelStateKey))\n                {\n                    dtoResult.ValidationNode.Validated += CreateNullCheckFailedHandler(propertyMetadata, value);\n                }\n            }\n        }\n\n        // Returns true if validator execution adds a model error.\n        private static bool RunValidator(ModelValidator validator, ModelBindingContext bindingContext,\n            ModelMetadata propertyMetadata, string modelStateKey)\n        {\n            bool addedError = false;\n            if (validator != null)\n            {\n                foreach (ModelValidationResult validationResult in validator.Validate(propertyMetadata, bindingContext.Model))\n                {\n                    bindingContext.ModelState.AddModelError(modelStateKey, validationResult.Message);\n                    addedError = true;\n                }\n            }\n\n            return addedError;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/Binders/MutableObjectModelBinderProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public sealed class MutableObjectModelBinderProvider : ModelBinderProvider\n    {\n        public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)\n        {\n            if (!MutableObjectModelBinder.CanBindType(modelType))\n            {\n                return null;\n            }\n\n            return new MutableObjectModelBinder();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/Binders/SimpleModelBinderProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    // Returns a user-specified binder for a given type.\n    public sealed class SimpleModelBinderProvider : ModelBinderProvider\n    {\n        private readonly Func<IModelBinder> _modelBinderFactory;\n        private readonly Type _modelType;\n\n        public SimpleModelBinderProvider(Type modelType, IModelBinder modelBinder)\n        {\n            if (modelType == null)\n            {\n                throw Error.ArgumentNull(\"modelType\");\n            }\n            if (modelBinder == null)\n            {\n                throw Error.ArgumentNull(\"modelBinder\");\n            }\n\n            _modelType = modelType;\n            _modelBinderFactory = () => modelBinder;\n        }\n\n        public SimpleModelBinderProvider(Type modelType, Func<IModelBinder> modelBinderFactory)\n        {\n            if (modelType == null)\n            {\n                throw Error.ArgumentNull(\"modelType\");\n            }\n            if (modelBinderFactory == null)\n            {\n                throw Error.ArgumentNull(\"modelBinderFactory\");\n            }\n\n            _modelType = modelType;\n            _modelBinderFactory = modelBinderFactory;\n        }\n\n        public Type ModelType\n        {\n            get { return _modelType; }\n        }\n\n        public bool SuppressPrefixCheck { get; set; }\n\n        public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)\n        {\n            if (modelType == null)\n            {\n                throw Error.ArgumentNull(\"modelType\");\n            }\n\n            if (modelType == ModelType)\n            {\n                if (SuppressPrefixCheck)\n                {\n                    // If we're suppressing a prefix check, then we don't need any further info from the ActionContext\n                    // to know that we're using this binder. \n                    return _modelBinderFactory();\n                }\n                else\n                {\n                    return new SimpleModelBinder(this);\n                }\n            }\n            return null;\n        }\n\n        // Helper binder to do the prefix check before invoking into the user's binder. \n        private class SimpleModelBinder : IModelBinder\n        {\n            private readonly SimpleModelBinderProvider _parent;\n\n            public SimpleModelBinder(SimpleModelBinderProvider parent)\n            {\n                _parent = parent;\n            }\n\n            public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)\n            {\n                Contract.Assert(!_parent.SuppressPrefixCheck); // wouldn't have even created this binder \n                if (bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName))\n                {\n                    IModelBinder binder = _parent._modelBinderFactory();\n                    return binder.BindModel(actionContext, bindingContext);\n                }\n                return false;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/Binders/TypeConverterModelBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Internal;\nusing System.Web.Http.ValueProviders;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public sealed class TypeConverterModelBinder : IModelBinder\n    {\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"The exception is recorded to be acted upon later.\")]\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1304:SpecifyCultureInfo\", MessageId = \"System.Web.Http.ValueProviders.ValueProviderResult.ConvertTo(System.Type)\", Justification = \"The ValueProviderResult already has the necessary context to perform a culture-aware conversion.\")]\n        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)\n        {\n            ModelBindingHelper.ValidateBindingContext(bindingContext);\n\n            ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);\n            if (valueProviderResult == null)\n            {\n                return false; // no entry\n            }\n\n            // Provider should have verified this before creating\n            Contract.Assert(TypeHelper.HasStringConverter(bindingContext.ModelType));            \n\n            object newModel;\n            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);\n            try\n            {\n                newModel = valueProviderResult.ConvertTo(bindingContext.ModelType);\n            }\n            catch (Exception ex)\n            {\n                if (IsFormatException(ex))\n                {\n                    // there was a type conversion failure\n                    string errorString = ModelBinderConfig.TypeConversionErrorMessageProvider(actionContext, bindingContext.ModelMetadata, valueProviderResult.AttemptedValue);\n                    if (errorString != null)\n                    {\n                        bindingContext.ModelState.AddModelError(bindingContext.ModelName, errorString);\n                    }\n                }\n                else\n                {\n                    bindingContext.ModelState.AddModelError(bindingContext.ModelName, ex);\n                }\n                return false;\n            }\n\n            ModelBindingHelper.ReplaceEmptyStringWithNull(bindingContext.ModelMetadata, ref newModel);\n            bindingContext.Model = newModel;\n            return true;\n        }\n\n        private static bool IsFormatException(Exception ex)\n        {\n            for (; ex != null; ex = ex.InnerException)\n            {\n                if (ex is FormatException)\n                {\n                    return true;\n                }\n            }\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/Binders/TypeConverterModelBinderProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Internal;\nusing System.Web.Http.ValueProviders;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    // Returns a binder that can perform conversions using a .NET TypeConverter.\n    public sealed class TypeConverterModelBinderProvider : ModelBinderProvider\n    {\n        public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)\n        {\n            if (modelType == null)\n            {\n                throw Error.ArgumentNull(\"modelType\");\n            }\n\n            if (!TypeHelper.HasStringConverter(modelType))\n            {\n                return null; // this type cannot be converted\n            }\n            return new TypeConverterModelBinder();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/Binders/TypeMatchModelBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Internal;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Validation;\nusing System.Web.Http.ValueProviders;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public sealed class TypeMatchModelBinder : IModelBinder\n    {\n        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)\n        {\n            ValueProviderResult valueProviderResult = GetCompatibleValueProviderResult(bindingContext);\n            if (valueProviderResult == null)\n            {\n                return false; // conversion would have failed\n            }\n\n            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);\n            object model = valueProviderResult.RawValue;\n            ModelBindingHelper.ReplaceEmptyStringWithNull(bindingContext.ModelMetadata, ref model);\n            bindingContext.Model = model;\n            if (bindingContext.ModelMetadata.IsComplexType)\n            {\n                HttpControllerContext controllerContext = actionContext.ControllerContext;\n                if (controllerContext == null)\n                {\n                    throw Error.Argument(\"actionContext\", SRResources.TypePropertyMustNotBeNull,\n                        typeof(HttpActionContext).Name, \"ControllerContext\");\n                }\n\n                HttpConfiguration configuration = controllerContext.Configuration;\n                if (configuration == null)\n                {\n                    throw Error.Argument(\"actionContext\", SRResources.TypePropertyMustNotBeNull,\n                        typeof(HttpControllerContext).Name, \"Configuration\");\n                }\n\n                ServicesContainer services = configuration.Services;\n                Contract.Assert(services != null);\n\n                IBodyModelValidator validator = services.GetBodyModelValidator();\n                ModelMetadataProvider metadataProvider = services.GetModelMetadataProvider();\n                if (validator != null && metadataProvider != null)\n                {\n                    validator.Validate(model, bindingContext.ModelType, metadataProvider, actionContext, bindingContext.ModelName);\n                }\n            }\n\n            return true;\n        }\n\n        internal static ValueProviderResult GetCompatibleValueProviderResult(ModelBindingContext bindingContext)\n        {\n            ModelBindingHelper.ValidateBindingContext(bindingContext);\n\n            ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);\n            if (valueProviderResult == null)\n            {\n                return null; // the value doesn't exist\n            }\n\n            if (!TypeHelper.IsCompatibleObject(bindingContext.ModelType, valueProviderResult.RawValue))\n            {\n                return null; // value is of incompatible type\n            }\n\n            return valueProviderResult;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/Binders/TypeMatchModelBinderProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    // Returns a binder that can extract a ValueProviderResult.RawValue and return it directly.\n    public sealed class TypeMatchModelBinderProvider : ModelBinderProvider\n    {\n        private static readonly TypeMatchModelBinder _binder = new TypeMatchModelBinder();\n\n        public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)\n        {\n            return _binder;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/CancellationTokenParameterBinding.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata;\n\nnamespace System.Web.Http.ModelBinding\n{\n    /// <summary>\n    /// Bind directly to the cancellation token\n    /// </summary>\n    public class CancellationTokenParameterBinding : HttpParameterBinding\n    {\n        public CancellationTokenParameterBinding(HttpParameterDescriptor descriptor)\n            : base(descriptor)\n        {\n        }\n\n        public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)\n        {\n            string name = Descriptor.ParameterName;\n            actionContext.ActionArguments.Add(name, cancellationToken);\n            return TaskHelpers.Completed();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/CustomModelBinderAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.Http.ModelBinding\n{\n    [AttributeUsage(ValidTargets, AllowMultiple = false, Inherited = false)]\n    public abstract class CustomModelBinderAttribute : Attribute\n    {\n        internal const AttributeTargets ValidTargets = AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Struct;\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Justification = \"This method can potentially perform a non-trivial amount of work.\")]\n        public abstract IModelBinder GetBinder();\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/DefaultActionValueBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Internal;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.ModelBinding\n{\n    public class DefaultActionValueBinder : IActionValueBinder\n    {\n        /// <summary>\n        /// Implementation of <see cref=\"IActionValueBinder\"/>, Primary entry point for binding parameters for an action.\n        /// </summary>\n        public virtual HttpActionBinding GetBinding(HttpActionDescriptor actionDescriptor)\n        {\n            if (actionDescriptor == null)\n            {\n                throw Error.ArgumentNull(\"actionDescriptor\");\n            }\n\n            HttpParameterDescriptor[] parameters = actionDescriptor.GetParameters().ToArray();\n            HttpParameterBinding[] binders = Array.ConvertAll(parameters, GetParameterBinding);\n\n            HttpActionBinding actionBinding = new HttpActionBinding(actionDescriptor, binders);\n\n            EnsureOneBodyParameter(actionBinding);\n\n            return actionBinding;\n        }\n\n        /// <summary>\n        /// Update actionBinding to enforce there is at most 1 body parameter.\n        /// If there are multiple, convert them all to <see cref=\"ErrorParameterBinding\"/>\n        /// </summary>\n        private static void EnsureOneBodyParameter(HttpActionBinding actionBinding)\n        {\n            IList<HttpParameterDescriptor> parameters = actionBinding.ActionDescriptor.GetParameters();\n\n            int idxFromBody = -1;\n            for (int i = 0; i < actionBinding.ParameterBindings.Length; i++)\n            {\n                if (actionBinding.ParameterBindings[i].WillReadBody)\n                {\n                    if (idxFromBody >= 0)\n                    {\n                        // This is the 2nd parameter to read from the body. Flag an error.\n                        string name1 = parameters[idxFromBody].ParameterName;\n                        string name2 = parameters[i].ParameterName;\n\n                        string message = Error.Format(SRResources.ParameterBindingCantHaveMultipleBodyParameters, name1, name2);\n                        actionBinding.ParameterBindings[i] = new ErrorParameterBinding(parameters[i], message);\n                        actionBinding.ParameterBindings[idxFromBody] = new ErrorParameterBinding(parameters[idxFromBody], message);\n                    }\n                    else\n                    {\n                        idxFromBody = i;\n                    }\n                }\n            }\n        }\n\n        // Determine how a single parameter will get bound.\n        // This is all sync. We don't need to actually read the body just to determine that we'll bind to the body.\n        protected virtual HttpParameterBinding GetParameterBinding(HttpParameterDescriptor parameter)\n        {\n            // Attribute has the highest precedence\n            // Presence of a model binder attribute overrides.\n            ParameterBindingAttribute attr = parameter.ParameterBinderAttribute;\n            if (attr != null)\n            {\n                return attr.GetBinding(parameter);\n            }\n\n            // No attribute, so lookup in global map.\n            ParameterBindingRulesCollection pb = parameter.Configuration.ParameterBindingRules;\n            if (pb != null)\n            {\n                HttpParameterBinding binding = pb.LookupBinding(parameter);\n                if (binding != null)\n                {\n                    return binding;\n                }\n            }\n\n            // Not explicitly specified in global map or attribute.\n            // Use a default policy to determine it. These are catch-all policies.\n            Type type = parameter.ParameterType;\n            if (TypeHelper.CanConvertFromString(type))\n            {\n                // For simple types, the default is to look in URI. Exactly as if the parameter had a [FromUri] attribute.\n                return parameter.BindWithAttribute(new FromUriAttribute());\n            }\n\n            // Fallback. Must be a complex type. Default is to look in body. Exactly as if this type had a [FromBody] attribute.\n            attr = new FromBodyAttribute();\n            return attr.GetBinding(parameter);\n        }\n\n        // Create an instance and add some default binders\n        internal static ParameterBindingRulesCollection GetDefaultParameterBinders()\n        {\n            ParameterBindingRulesCollection pb = new ParameterBindingRulesCollection();\n\n            pb.Add(typeof(CancellationToken), parameter => new CancellationTokenParameterBinding(parameter));\n            pb.Add(typeof(HttpRequestMessage), parameter => new HttpRequestParameterBinding(parameter));\n\n            // Warning binder for HttpContent.\n            pb.Add(parameter => typeof(HttpContent).IsAssignableFrom(parameter.ParameterType) ?\n                                    parameter.BindAsError(Error.Format(SRResources.ParameterBindingIllegalType, parameter.ParameterType.Name, parameter.ParameterName))\n                                    : null);\n\n            return pb;\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/ErrorParameterBinding.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata;\n\nnamespace System.Web.Http.ModelBinding\n{\n    /// <summary>\n    /// Describe a binding error.  This includes a message that can give meaningful information to a client.\n    /// </summary>\n    public class ErrorParameterBinding : HttpParameterBinding\n    {\n        private readonly string _message;\n\n        public ErrorParameterBinding(HttpParameterDescriptor descriptor, string message)\n            : base(descriptor)\n        {\n            if (message == null)\n            {\n                throw Error.ArgumentNull(\"message\");\n            }\n            _message = message;\n        }\n\n        public override string ErrorMessage\n        {\n            get\n            {\n                return _message;\n            }\n        }\n\n        public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)\n        {\n            // Caller should have already checked IsError before executing, so we shoulnd't be here. \n            return TaskHelpers.FromError(new InvalidOperationException());\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/FormDataCollectionExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Net.Http.Formatting;\nusing System.Text;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.ModelBinding.Binders;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Validation;\nusing System.Web.Http.Validation.Providers;\nusing System.Web.Http.ValueProviders;\nusing System.Web.Http.ValueProviders.Providers;\n\nnamespace System.Web.Http.ModelBinding\n{\n    public static class FormDataCollectionExtensions\n    {\n        // This is a helper method to use Model Binding over a JQuery syntax. \n        // Normalize from JQuery to MVC keys. The model binding infrastructure uses MVC keys\n        // x[] --> x\n        // [] --> \"\"\n        // x[field]  --> x.field, where field is not a number\n        internal static string NormalizeJQueryToMvc(string key)\n        {\n            if (key == null)\n            {\n                return String.Empty;\n            }\n\n            StringBuilder sb = null;\n            int i = 0;\n            while (true)\n            {\n                int indexOpen = key.IndexOf('[', i);\n                if (indexOpen < 0)\n                {\n                    // Fast path, no normalization needed.\n                    // This skips the string conversion and allocating the string builder.\n                    if (i == 0)\n                    {\n                        return key;\n                    }\n                    sb = sb ?? new StringBuilder();\n                    sb.Append(key, i, key.Length - i);\n                    break; // no more brackets\n                }\n\n                sb = sb ?? new StringBuilder();\n                sb.Append(key, i, indexOpen - i); // everything up to \"[\"\n\n                // Find closing bracket.\n                int indexClose = key.IndexOf(']', indexOpen);\n                if (indexClose == -1)\n                {\n                    throw Error.Argument(\"key\", SRResources.JQuerySyntaxMissingClosingBracket);\n                }\n\n                if (indexClose == indexOpen + 1)\n                {\n                    // Empty bracket. Signifies array. Just remove. \n                }\n                else\n                {\n                    if (Char.IsDigit(key[indexOpen + 1]))\n                    {\n                        // array index. Leave unchanged. \n                        sb.Append(key, indexOpen, indexClose - indexOpen + 1);\n                    }\n                    else\n                    {\n                        // Field name.  Convert to dot notation. \n                        sb.Append('.');\n                        sb.Append(key, indexOpen + 1, indexClose - indexOpen - 1);\n                    }\n                }\n\n                i = indexClose + 1;\n                if (i >= key.Length)\n                {\n                    break; // end of string\n                }\n            }\n            return sb.ToString();\n        }\n\n        internal static IEnumerable<KeyValuePair<string, string>> GetJQueryNameValuePairs(this FormDataCollection formData)\n        {\n            if (formData == null)\n            {\n                throw Error.ArgumentNull(\"formData\");\n            }\n\n            int count = 0;\n\n            foreach (KeyValuePair<string, string> kv in formData)\n            {\n                ThrowIfMaxHttpCollectionKeysExceeded(count);\n\n                string key = NormalizeJQueryToMvc(kv.Key);\n                string value = kv.Value ?? String.Empty;\n                yield return new KeyValuePair<string, string>(key, value);\n\n                count++;\n            }\n        }\n\n        private static void ThrowIfMaxHttpCollectionKeysExceeded(int count)\n        {\n            if (count >= MediaTypeFormatter.MaxHttpCollectionKeys)\n            {\n                throw Error.InvalidOperation(SRResources.MaxHttpCollectionKeyLimitReached, MediaTypeFormatter.MaxHttpCollectionKeys, typeof(MediaTypeFormatter));\n            }\n        }\n\n        // Create a IValueProvider for the given form, assuming a JQuery syntax.\n        internal static IValueProvider GetJQueryValueProvider(this FormDataCollection formData)\n        {\n            if (formData == null)\n            {\n                throw Error.ArgumentNull(\"formData\");\n            }\n\n            IEnumerable<KeyValuePair<string, string>> nvc = formData.GetJQueryNameValuePairs();\n            return new NameValuePairsValueProvider(nvc, CultureInfo.InvariantCulture);\n        }\n\n        public static T ReadAs<T>(this FormDataCollection formData)\n        {\n            return (T)ReadAs(formData, typeof(T));\n        }\n\n        public static T ReadAs<T>(this FormDataCollection formData, HttpActionContext actionContext)\n        {\n            return (T)ReadAs(formData, typeof(T), String.Empty, actionContext: actionContext);\n        }\n\n        public static object ReadAs(this FormDataCollection formData, Type type)\n        {\n            return ReadAs(formData, type, String.Empty, requiredMemberSelector: null, formatterLogger: null);\n        }\n\n        public static object ReadAs(this FormDataCollection formData, Type type, HttpActionContext actionContext)\n        {\n            return ReadAs(formData, type, String.Empty, actionContext);\n        }\n\n        public static T ReadAs<T>(this FormDataCollection formData, string modelName, IRequiredMemberSelector requiredMemberSelector, IFormatterLogger formatterLogger)\n        {\n            return (T)ReadAs(formData, typeof(T), modelName, requiredMemberSelector, formatterLogger);\n        }\n\n        public static T ReadAs<T>(this FormDataCollection formData, string modelName, HttpActionContext actionContext)\n        {\n            return (T)ReadAs(formData, typeof(T), modelName, actionContext);\n        }\n\n        public static object ReadAs(this FormDataCollection formData, Type type, string modelName, HttpActionContext actionContext)\n        {\n            if (formData == null)\n            {\n                throw Error.ArgumentNull(\"formData\");\n            }\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n            if (actionContext == null)\n            {\n                throw Error.ArgumentNull(\"actionContext\");\n            }\n\n            return ReadAsInternal(formData, type, modelName, actionContext);\n        }\n\n        public static object ReadAs(this FormDataCollection formData, Type type, string modelName,\n            IRequiredMemberSelector requiredMemberSelector, IFormatterLogger formatterLogger)\n        {\n            return ReadAs(formData, type, modelName, requiredMemberSelector, formatterLogger, config: null);\n        }\n\n        /// <summary>\n        /// Deserialize the form data to the given type, using model binding.  \n        /// </summary>\n        /// <param name=\"formData\">collection with parsed form url data</param>\n        /// <param name=\"type\">target type to read as</param>\n        /// <param name=\"modelName\">null or empty to read the entire form as a single object. \n        /// This is common for body data. Or the name of a model to do a partial binding against the form data. \n        /// This is common for extracting individual fields.</param>\n        /// <param name=\"requiredMemberSelector\">The <see cref=\"IRequiredMemberSelector\"/> \n        /// used to determine required members.</param>\n        /// <param name=\"formatterLogger\">The <see cref=\"IFormatterLogger\"/> to log events to.</param>\n        /// <param name=\"config\">The <see cref=\"HttpConfiguration\"/> configuration to pick binder from.\n        /// Can be null if the config was not created already. In that case a new config is created.</param>\n        /// <returns>best attempt to bind the object. The best attempt may be null.</returns>\n        public static object ReadAs(this FormDataCollection formData, Type type, string modelName, \n                                        IRequiredMemberSelector requiredMemberSelector,\n                                        IFormatterLogger formatterLogger, HttpConfiguration config)\n        {\n            if (formData == null)\n            {\n                throw Error.ArgumentNull(\"formData\");\n            }\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            object result = null;\n            HttpActionContext actionContext = null;\n\n            bool validateRequiredMembers = requiredMemberSelector != null && formatterLogger != null;\n\n            if (validateRequiredMembers)\n            {\n                // We wrap the config so we can override the services and cache \n                // without affecting outside callers or users of the config.\n                using (HttpConfiguration wrapperConfig = new HttpConfiguration())\n                {\n                    config = config == null ? wrapperConfig : config;\n                    wrapperConfig.Services = new ServicesContainerWrapper(config,\n                                                new RequiredMemberModelValidatorProvider(requiredMemberSelector));\n\n                    // The HttpActionContext provides access to configuration for ModelBinders, and is also provided\n                    // to the IModelBinder when binding occurs. Since HttpActionContext was not provided, create a default.\n                    actionContext = CreateActionContextForModelBinding(wrapperConfig);\n                    result = ReadAs(formData, type, modelName, actionContext);\n                }\n            }\n            else\n            {\n                if (config == null)\n                {\n                    using (config = new HttpConfiguration())\n                    {\n                        actionContext = CreateActionContextForModelBinding(config);\n                        result = ReadAs(formData, type, modelName, actionContext);\n                    }\n                }\n                else\n                {\n                    actionContext = CreateActionContextForModelBinding(config);\n                    result = ReadAs(formData, type, modelName, actionContext);\n                }\n            }\n\n            // The model binding will log any errors to the HttpActionContext's ModelState. Since this is a context\n            // that we created and doesn't map to a real action invocation, we want to forward the errors to \n            // the user-specified IFormatterLogger.\n            if (formatterLogger != null)\n            {\n                foreach (KeyValuePair<string, ModelState> modelStatePair in actionContext.ModelState)\n                {\n                    foreach (ModelError modelError in modelStatePair.Value.Errors)\n                    {\n                        if (modelError.Exception != null)\n                        {\n                            formatterLogger.LogError(modelStatePair.Key, modelError.Exception);\n                        }\n                        else\n                        {\n                            formatterLogger.LogError(modelStatePair.Key, modelError.ErrorMessage);\n                        }\n                    }\n                }\n            }\n\n            return result;\n        }\n\n        private static object ReadAsInternal(this FormDataCollection formData, Type type, string modelName, HttpActionContext actionContext)\n        {\n            Contract.Assert(formData != null);\n            Contract.Assert(type != null);\n            Contract.Assert(actionContext != null);\n\n            IValueProvider valueProvider = formData.GetJQueryValueProvider();\n            ModelBindingContext bindingContext = CreateModelBindingContext(actionContext, modelName ?? String.Empty, type, valueProvider);\n\n            ModelBinderProvider modelBinderProvider = CreateModelBindingProvider(actionContext);\n\n            IModelBinder modelBinder = modelBinderProvider.GetBinder(actionContext.ControllerContext.Configuration, type);\n            bool haveResult = modelBinder.BindModel(actionContext, bindingContext);\n            if (haveResult)\n            {\n                return bindingContext.Model;\n            }\n\n            return MediaTypeFormatter.GetDefaultValueForType(type);\n        }\n\n        // Helper for ReadAs() to get a ModelBinderProvider to read FormUrl data. \n        private static ModelBinderProvider CreateModelBindingProvider(HttpActionContext actionContext)\n        {\n            Contract.Assert(actionContext != null);\n\n            ServicesContainer cs = actionContext.ControllerContext.Configuration.Services;\n            IEnumerable<ModelBinderProvider> providers = cs.GetModelBinderProviders();\n            ModelBinderProvider modelBinderProvider = new CompositeModelBinderProvider(providers);\n            return modelBinderProvider;\n        }\n\n        // Helper for ReadAs() to get a ModelBindingContext to invoke model binding over FormUrl data. \n        private static ModelBindingContext CreateModelBindingContext(HttpActionContext actionContext, string modelName, Type type, IValueProvider vp)\n        {\n            Contract.Assert(actionContext != null);\n            Contract.Assert(type != null);\n            Contract.Assert(vp != null);\n\n            ServicesContainer cs = actionContext.ControllerContext.Configuration.Services;\n            ModelMetadataProvider metadataProvider = cs.GetModelMetadataProvider();\n\n            ModelBindingContext ctx = new ModelBindingContext()\n            {\n                ModelName = modelName,\n                FallbackToEmptyPrefix = false,\n                ModelMetadata = metadataProvider.GetMetadataForType(null, type),\n                ModelState = actionContext.ModelState,\n                ValueProvider = vp\n            };\n            return ctx;\n        }\n\n        // Creates a default action context to invoke model binding\n        private static HttpActionContext CreateActionContextForModelBinding(HttpConfiguration config)\n        {\n            Contract.Assert(config != null);\n\n            HttpControllerContext controllerContext = new HttpControllerContext() { Configuration = config };\n            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(config);\n\n            HttpActionContext actionContext = new HttpActionContext { ControllerContext = controllerContext };\n\n            return actionContext;\n        }\n\n        // This class is internal for Unit Testing purposes\n        internal class ServicesContainerWrapper : ServicesContainer\n        {\n            private HttpConfiguration _originalConfig;\n            private ModelValidatorProvider _requiredMemberModelValidatorProvider;\n\n            public ServicesContainerWrapper(\n                                HttpConfiguration originalConfig,\n                                ModelValidatorProvider requiredMemberModelValidatorProvider)\n            {\n                _originalConfig = originalConfig;\n                _requiredMemberModelValidatorProvider = requiredMemberModelValidatorProvider;\n            }\n\n            // Without modifying the original config, the wrapper returns only the expected\n            // Validator Provider. Since the cache is expected to have the original config's\n            // cache entries, it is wrapped as well.\n            public override object GetService(Type serviceType)\n            {\n                if (serviceType == typeof(IModelValidatorCache))\n                {\n                    return new ModelValidatorCache(\n                                    new Lazy<IEnumerable<ModelValidatorProvider>>(\n                                        () => this.GetServices<ModelValidatorProvider>()));\n                }\n                else if (serviceType == typeof(ModelValidatorProvider))\n                {\n                    return _requiredMemberModelValidatorProvider;\n                }\n                else\n                {\n                    return _originalConfig.Services.GetService(serviceType);\n                }\n            }\n\n            public override IEnumerable<object> GetServices(Type serviceType)\n            {\n                if (serviceType == typeof(ModelValidatorProvider))\n                {\n                    return new ModelValidatorProvider[] { _requiredMemberModelValidatorProvider };\n                }\n                else\n                {\n                    return _originalConfig.Services.GetServices(serviceType);\n                }\n            }\n\n            protected override List<object> GetServiceInstances(Type serviceType)\n            {\n                throw new NotImplementedException();\n            }\n\n            // The following methods are expected to work the same way irrespective of the wrapper.\n            // Hence they are not special cased for the Validator Providers / Cache.\n            public override bool IsSingleService(Type serviceType)\n            {\n                return _originalConfig.Services.IsSingleService(serviceType);\n            }\n\n            protected override void ClearSingle(Type serviceType)\n            {\n                _originalConfig.Services.Clear(serviceType);\n            }\n\n            protected override void ReplaceSingle(Type serviceType, object service)\n            {\n                _originalConfig.Services.Replace(serviceType, service);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/FormatterParameterBinding.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Validation;\n\nnamespace System.Web.Http.ModelBinding\n{\n    /// <summary>\n    /// Parameter binding that will read from the body and invoke the formatters. \n    /// </summary>\n    public class FormatterParameterBinding : HttpParameterBinding\n    {\n        // Magic key to pass cancellation token through the request property bag to maintain backward compat.\n        private const string CancellationTokenKey = \"MS_FormatterParameterBinding_CancellationToken\";\n\n        private IEnumerable<MediaTypeFormatter> _formatters;\n        private string _errorMessage;\n\n        public FormatterParameterBinding(HttpParameterDescriptor descriptor, IEnumerable<MediaTypeFormatter> formatters, IBodyModelValidator bodyModelValidator)\n            : base(descriptor)\n        {\n            if (descriptor.IsOptional)\n            {\n                _errorMessage = Error.Format(SRResources.OptionalBodyParameterNotSupported, descriptor.Prefix ?? descriptor.ParameterName, GetType().Name);\n            }\n            Formatters = formatters;\n            BodyModelValidator = bodyModelValidator;\n        }\n\n        public override bool WillReadBody\n        {\n            get { return true; }\n        }\n\n        public override string ErrorMessage\n        {\n            get\n            {\n                return _errorMessage;\n            }\n        }\n\n        public IEnumerable<MediaTypeFormatter> Formatters\n        {\n            get { return _formatters; }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.ArgumentNull(\"formatters\");\n                }\n                _formatters = value;\n            }\n        }\n\n        public IBodyModelValidator BodyModelValidator\n        {\n            get;\n            set;\n        }\n\n        public virtual Task<object> ReadContentAsync(HttpRequestMessage request, Type type,\n            IEnumerable<MediaTypeFormatter> formatters, IFormatterLogger formatterLogger)\n        {\n            // Try to get the cancellation token if it is set earlier during the magic handshake\n            // to maintain backward compatibility.\n            object cancellationToken;\n            if (!request.Properties.TryGetValue(CancellationTokenKey, out cancellationToken))\n            {\n                cancellationToken = CancellationToken.None;\n            }\n\n            return ReadContentAsync(request, type, formatters, formatterLogger, (CancellationToken)cancellationToken);\n        }\n\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"Disposed later\")]\n        public virtual Task<object> ReadContentAsync(HttpRequestMessage request, Type type,\n            IEnumerable<MediaTypeFormatter> formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\n        {\n            HttpContent content = request.Content;\n            if (content == null)\n            {\n                object defaultValue = MediaTypeFormatter.GetDefaultValueForType(type);\n                if (defaultValue == null)\n                {\n                    return TaskHelpers.NullResult();\n                }\n                else\n                {\n                    return Task.FromResult(defaultValue);\n                }\n            }\n\n            try\n            {\n                return content.ReadAsAsync(type, formatters, formatterLogger, cancellationToken);\n            }\n            catch (UnsupportedMediaTypeException exception)\n            {\n                // If there is no Content-Type header, provide a better error message\n                string errorFormat = content.Headers.ContentType == null ?\n                    SRResources.UnsupportedMediaTypeNoContentType :\n                    SRResources.UnsupportedMediaType;\n\n                throw new HttpResponseException(\n                    request.CreateErrorResponse(\n                        HttpStatusCode.UnsupportedMediaType,\n                        Error.Format(errorFormat, exception.MediaType.MediaType),\n                        exception));\n            }\n        }\n\n        public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext,\n            CancellationToken cancellationToken)\n        {\n            HttpParameterDescriptor paramFromBody = this.Descriptor;\n            Type type = paramFromBody.ParameterType;\n            HttpRequestMessage request = actionContext.ControllerContext.Request;\n            IFormatterLogger formatterLogger = new ModelStateFormatterLogger(actionContext.ModelState, paramFromBody.ParameterName);\n\n            return ExecuteBindingAsyncCore(metadataProvider, actionContext, paramFromBody, type, request, formatterLogger, cancellationToken);\n        }\n\n        // Perf-sensitive - keeping the async method as small as possible\n        private async Task ExecuteBindingAsyncCore(ModelMetadataProvider metadataProvider, HttpActionContext actionContext,\n            HttpParameterDescriptor paramFromBody, Type type, HttpRequestMessage request, IFormatterLogger formatterLogger,\n            CancellationToken cancellationToken)\n        {\n            // pass the cancellation token through the request as we cannot call the ReadContentAsync overload that takes\n            // CancellationToken for backword compatibility reasons.\n            request.Properties[CancellationTokenKey] = cancellationToken;\n            object model = await ReadContentAsync(request, type, _formatters, formatterLogger);\n\n            // Put the parameter result into the action context.\n            SetValue(actionContext, model);\n\n            // validate the object graph.\n            // null indicates we want no body parameter validation\n            if (BodyModelValidator != null)\n            {\n                BodyModelValidator.Validate(model, type, metadataProvider, actionContext, paramFromBody.ParameterName);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/HttpBindingBehavior.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.ModelBinding\n{\n    public enum HttpBindingBehavior\n    {\n        Optional = 0,\n        Never,\n        Required\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/HttpBindingBehaviorAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.Http.ModelBinding\n{\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]\n    [SuppressMessage(\"Microsoft.Performance\", \"CA1813:AvoidUnsealedAttributes\", Justification = \"This class is designed to be overridden\")]\n    public class HttpBindingBehaviorAttribute : Attribute\n    {\n        private static readonly object _typeId = new object();\n\n        public HttpBindingBehaviorAttribute(HttpBindingBehavior behavior)\n        {\n            Behavior = behavior;\n        }\n\n        public HttpBindingBehavior Behavior { get; private set; }\n\n        public override object TypeId\n        {\n            get { return _typeId; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/HttpRequestParameterBinding.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata;\n\nnamespace System.Web.Http.ModelBinding\n{\n    /// <summary>\n    /// Parameter binds to the request\n    /// </summary>\n    public class HttpRequestParameterBinding : HttpParameterBinding\n    {\n        public HttpRequestParameterBinding(HttpParameterDescriptor descriptor)\n            : base(descriptor)\n        {            \n        }        \n\n        // Execute the binding for the given request.\n        // On success, this will add the parameter to the actionContext.ActionArguments dictionary.\n        // Caller ensures IsError==false. \n        public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)\n        {\n            string name = Descriptor.ParameterName;\n            HttpRequestMessage request = actionContext.ControllerContext.Request;\n            actionContext.ActionArguments.Add(name, request);\n\n            return TaskHelpers.Completed();\n        }        \n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/IModelBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.ModelBinding\n{\n    /// <summary>\n    /// Interface for model binding.\n    /// </summary>\n    public interface IModelBinder\n    {\n        bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/IValueProviderParameterBinding.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http.ValueProviders;\n\nnamespace System.Web.Http.ModelBinding\n{\n    /// <summary>\n    /// Describes a parameter binding that uses one or more instances of <see cref=\"ValueProviderFactory\"/>\n    /// </summary>\n    public interface IValueProviderParameterBinding\n    {\n        /// <summary>\n        /// Gets the <see cref=\"ValueProviderFactory\"/> instances used by this\n        /// parameter binding.\n        /// </summary>\n        IEnumerable<ValueProviderFactory> ValueProviderFactories { get; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/JQueryMVCFormUrlEncodedFormatter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.ModelBinding\n{\n    // Supports JQuery schema on FormURL. \n    public class JQueryMvcFormUrlEncodedFormatter : FormUrlEncodedMediaTypeFormatter\n    {\n        private readonly HttpConfiguration _configuration = null;\n\n        public JQueryMvcFormUrlEncodedFormatter()\n        {\n        }\n\n        public JQueryMvcFormUrlEncodedFormatter(HttpConfiguration config)\n        {\n            _configuration = config;\n        }\n\n        public override bool CanReadType(Type type)\n        {\n            if (type == null)\n            {\n                throw new ArgumentNullException(\"type\");\n            }\n\n            return true;\n        }\n\n        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)\n        {\n            if (type == null)\n            {\n                throw new ArgumentNullException(\"type\");\n            }\n\n            if (readStream == null)\n            {\n                throw new ArgumentNullException(\"readStream\");\n            }\n\n            // For simple types, defer to base class\n            if (base.CanReadType(type))\n            {\n                return base.ReadFromStreamAsync(type, readStream, content, formatterLogger);\n            }\n\n            return ReadFromStreamAsyncCore(type, readStream, content, formatterLogger);\n        }\n\n        private async Task<object> ReadFromStreamAsyncCore(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)\n        {\n            object obj = await base.ReadFromStreamAsync(typeof(FormDataCollection), readStream, content, formatterLogger);\n            FormDataCollection fd = (FormDataCollection)obj;\n\n            try\n            {\n                return fd.ReadAs(type, String.Empty, RequiredMemberSelector, formatterLogger, _configuration);\n            }\n            catch (Exception e)\n            {\n                if (formatterLogger == null)\n                {\n                    throw;\n                }\n                formatterLogger.LogError(String.Empty, e);\n                return GetDefaultValueForType(type);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/ModelBinderAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Dependencies;\nusing System.Web.Http.ModelBinding.Binders;\nusing System.Web.Http.Properties;\nusing System.Web.Http.ValueProviders;\n\nnamespace System.Web.Http.ModelBinding\n{\n    /// <summary>\n    /// Specify this parameter uses a model binder. This can optionally specify the specific model binder and \n    /// value providers that drive that model binder. \n    /// Derived attributes may provide convenience settings for the model binder or value provider. \n    /// </summary>\n    [SuppressMessage(\"Microsoft.Design\", \"CA1019:DefineAccessorsForAttributeArguments\", Justification = \"want constructor argument shortcut\")]\n    [SuppressMessage(\"Microsoft.Performance\", \"CA1813:AvoidUnsealedAttributes\", Justification = \"part of a class hierarchy\")]\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)]\n    public class ModelBinderAttribute : ParameterBindingAttribute\n    {\n        public ModelBinderAttribute()\n            : this(null)\n        {\n        }\n\n        public ModelBinderAttribute(Type binderType)\n        {\n            BinderType = binderType;\n        }\n\n        /// <summary>\n        /// Sets the type of the model binder. \n        /// This type must be a subclass of <see cref=\"ModelBinderProvider\"/>  or <see cref=\"IModelBinder\"/>      \n        /// If null, uses the default from the configuration. \n        /// </summary>   \n        public Type BinderType { get; set; }\n\n        /// <summary>\n        /// Gets or sets the name to consider as the parameter name during model binding\n        /// </summary>\n        public string Name { get; set; }\n\n        public bool SuppressPrefixCheck { get; set; }\n\n        public override HttpParameterBinding GetBinding(HttpParameterDescriptor parameter)\n        {\n            HttpConfiguration config = parameter.Configuration;\n            IModelBinder binder = GetModelBinder(config, parameter.ParameterType);\n            IEnumerable<ValueProviderFactory> valueProviderFactories = GetValueProviderFactories(config);\n\n            return new ModelBinderParameterBinding(parameter, binder, valueProviderFactories);\n        }\n\n        // This will get called by a parameter binding, which will cache the results. \n        public ModelBinderProvider GetModelBinderProvider(HttpConfiguration configuration)\n        {\n            if (BinderType != null)\n            {\n                object value = GetOrInstantiate(configuration, BinderType);\n\n                if (value != null)\n                {\n                    VerifyBinderType(value.GetType());\n                    ModelBinderProvider result = (ModelBinderProvider)value;\n                    return result;\n                }\n            }\n\n            // Create default over config\n            IEnumerable<ModelBinderProvider> providers = configuration.Services.GetModelBinderProviders();\n\n            if (providers.Count() == 1)\n            {\n                return providers.First();\n            }\n\n            return new CompositeModelBinderProvider(providers);\n        }\n\n        /// <summary>\n        /// Get the IModelBinder for this type.\n        /// </summary>\n        /// <param name=\"configuration\">The configuration.</param>\n        /// <param name=\"modelType\">model type that the binder is expected to bind.</param>\n        /// <returns>\n        /// a non-null model binder.\n        /// </returns>\n        public IModelBinder GetModelBinder(HttpConfiguration configuration, Type modelType)\n        {\n            if (BinderType == null)\n            {\n                ModelBinderProvider provider = GetModelBinderProvider(configuration);\n                return provider.GetBinder(configuration, modelType);\n            }\n\n            // This may create a IModelBinder or a ModelBinderProvider\n            object value = GetOrInstantiate(configuration, BinderType);\n\n            Contract.Assert(value != null); // Activator would have thrown\n\n            IModelBinder binder = value as IModelBinder;\n            if (binder != null)\n            {\n                return binder;\n            }\n            else\n            {\n                ModelBinderProvider provider = value as ModelBinderProvider;\n                if (provider != null)\n                {\n                    return provider.GetBinder(configuration, modelType);\n                }\n            }\n\n            Type required = typeof(IModelBinder);\n            throw Error.InvalidOperation(SRResources.ValueProviderFactory_Cannot_Create, required.Name, value.GetType().Name, required.Name);\n        }\n\n        /// <summary>\n        /// Value providers that will be fed to the model binder.\n        /// </summary>\n        public virtual IEnumerable<ValueProviderFactory> GetValueProviderFactories(HttpConfiguration configuration)\n        {\n            // By default, just get all registered value provider factories\n            return configuration.Services.GetValueProviderFactories();\n        }\n\n        private static void VerifyBinderType(Type attemptedType)\n        {\n            Type required = typeof(ModelBinderProvider);\n            if (!required.IsAssignableFrom(attemptedType))\n            {\n                throw Error.InvalidOperation(SRResources.ValueProviderFactory_Cannot_Create, required.Name, attemptedType.Name, required.Name);\n            }\n        }\n\n        private static object GetOrInstantiate(HttpConfiguration configuration, Type type)\n        {\n            IDependencyResolver dr = configuration.DependencyResolver;\n            object value = dr.GetService(type);\n            if (value != null)\n            {\n                return value;\n            }\n\n            return Activator.CreateInstance(type);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/ModelBinderConfig.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.ModelBinding\n{\n    // REVIEW: Need a way to get the user's resource string choice\n    // Provides configuration settings common to the new model binding system.\n    public static class ModelBinderConfig\n    {\n        private static string _resourceClassKey;\n        private static ModelBinderErrorMessageProvider _typeConversionErrorMessageProvider;\n        private static ModelBinderErrorMessageProvider _valueRequiredErrorMessageProvider;\n\n        public static string ResourceClassKey\n        {\n            get { return _resourceClassKey ?? String.Empty; }\n            set { _resourceClassKey = value; }\n        }\n\n        public static ModelBinderErrorMessageProvider TypeConversionErrorMessageProvider\n        {\n            get\n            {\n                if (_typeConversionErrorMessageProvider == null)\n                {\n                    _typeConversionErrorMessageProvider = DefaultTypeConversionErrorMessageProvider;\n                }\n                return _typeConversionErrorMessageProvider;\n            }\n            set { _typeConversionErrorMessageProvider = value; }\n        }\n\n        public static ModelBinderErrorMessageProvider ValueRequiredErrorMessageProvider\n        {\n            get\n            {\n                if (_valueRequiredErrorMessageProvider == null)\n                {\n                    _valueRequiredErrorMessageProvider = DefaultValueRequiredErrorMessageProvider;\n                }\n                return _valueRequiredErrorMessageProvider;\n            }\n            set { _valueRequiredErrorMessageProvider = value; }\n        }\n\n        private static string DefaultTypeConversionErrorMessageProvider(HttpActionContext actionContext, ModelMetadata modelMetadata, object incomingValue)\n        {\n            return GetResourceCommon(actionContext, modelMetadata, incomingValue, GetValueInvalidResource);\n        }\n\n        private static string DefaultValueRequiredErrorMessageProvider(HttpActionContext actionContext, ModelMetadata modelMetadata, object incomingValue)\n        {\n            return GetResourceCommon(actionContext, modelMetadata, incomingValue, GetValueRequiredResource);\n        }\n\n        private static string GetResourceCommon(HttpActionContext actionContext, ModelMetadata modelMetadata, object incomingValue, Func<HttpActionContext, string> resourceAccessor)\n        {\n            string displayName = modelMetadata.GetDisplayName();\n            string errorMessageTemplate = resourceAccessor(actionContext);\n            return Error.Format(errorMessageTemplate, incomingValue, displayName);\n        }\n\n        private static string GetUserResourceString(HttpActionContext actionContext, string resourceName)\n        {\n            return GetUserResourceString(actionContext, resourceName, ResourceClassKey);\n        }\n\n        // If the user specified a ResourceClassKey try to load the resource they specified.\n        // If the class key is invalid, an exception will be thrown.\n        // If the class key is valid but the resource is not found, it returns null, in which\n        // case it will fall back to the MVC default error message.\n        [SuppressMessage(\"Microsoft.Usage\", \"CA1801:ReviewUnusedParameters\", MessageId = \"resourceName\", Justification = \"Temporary\")]\n        [SuppressMessage(\"Microsoft.Usage\", \"CA1801:ReviewUnusedParameters\", MessageId = \"resourceClassKey\", Justification = \"Temporary\")]\n        [SuppressMessage(\"Microsoft.Usage\", \"CA1801:ReviewUnusedParameters\", MessageId = \"actionContext\", Justification = \"Temporary\")]\n        internal static string GetUserResourceString(HttpActionContext actionContext, string resourceName, string resourceClassKey)\n        {\n#if false\n            return (!String.IsNullOrEmpty(resourceClassKey) && (actionContext != null) && (actionContext.HttpContext != null))\n                       ? actionContext.HttpContext.GetGlobalResourceObject(resourceClassKey, resourceName, CultureInfo.CurrentUICulture) as string\n                       : null;\n#else\n            return null;\n#endif\n        }\n\n        private static string GetValueInvalidResource(HttpActionContext actionContext)\n        {\n            return GetUserResourceString(actionContext, \"PropertyValueInvalid\") ?? SRResources.ModelBinderConfig_ValueInvalid;\n        }\n\n        private static string GetValueRequiredResource(HttpActionContext actionContext)\n        {\n            return GetUserResourceString(actionContext, \"PropertyValueRequired\") ?? SRResources.ModelBinderConfig_ValueRequired;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/ModelBinderErrorMessageProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata;\n\nnamespace System.Web.Http.ModelBinding\n{\n    public delegate string ModelBinderErrorMessageProvider(HttpActionContext actionContext, ModelMetadata modelMetadata, object incomingValue);\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/ModelBinderParameterBinding.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Validation;\nusing System.Web.Http.ValueProviders;\nusing System.Web.Http.ValueProviders.Providers;\n\nnamespace System.Web.Http.ModelBinding\n{\n    /// <summary>\n    /// Describes a parameter that gets bound via ModelBinding.  \n    /// </summary>\n    public class ModelBinderParameterBinding : HttpParameterBinding, IValueProviderParameterBinding\n    {\n        private readonly ValueProviderFactory[] _valueProviderFactories;\n        private readonly IModelBinder _binder;\n\n        public ModelBinderParameterBinding(HttpParameterDescriptor descriptor,\n            IModelBinder modelBinder,\n            IEnumerable<ValueProviderFactory> valueProviderFactories)\n            : base(descriptor)\n        {\n            if (modelBinder == null)\n            {\n                throw Error.ArgumentNull(\"modelBinder\");\n            }\n            if (valueProviderFactories == null)\n            {\n                throw Error.ArgumentNull(\"valueProviderFactories\");\n            }\n\n            _binder = modelBinder;\n            _valueProviderFactories = valueProviderFactories.ToArray();\n        }\n\n        public IEnumerable<ValueProviderFactory> ValueProviderFactories\n        {\n            get { return _valueProviderFactories; }\n        }\n\n        public IModelBinder Binder\n        {\n            get { return _binder; }\n        }\n\n        public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)\n        {\n            ModelBindingContext ctx = GetModelBindingContext(metadataProvider, actionContext);\n\n            bool haveResult = _binder.BindModel(actionContext, ctx);\n            object model = haveResult ? ctx.Model : Descriptor.DefaultValue;\n            SetValue(actionContext, model);\n\n            return TaskHelpers.Completed();\n        }\n\n        private ModelBindingContext GetModelBindingContext(ModelMetadataProvider metadataProvider, HttpActionContext actionContext)\n        {\n            string name = Descriptor.ParameterName;\n            Type type = Descriptor.ParameterType;\n\n            string prefix = Descriptor.Prefix;\n\n            IValueProvider vp = CompositeValueProviderFactory.GetValueProvider(actionContext, _valueProviderFactories);\n\n            ModelBindingContext ctx = new ModelBindingContext()\n            {\n                ModelName = prefix ?? name,\n                FallbackToEmptyPrefix = prefix == null, // only fall back if prefix not specified\n                ModelMetadata = metadataProvider.GetMetadataForType(null, type),\n                ModelState = actionContext.ModelState,\n                ValueProvider = vp\n            };\n\n            return ctx;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/ModelBinderProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.ModelBinding\n{\n    public abstract class ModelBinderProvider\n    {\n        /// <summary>\n        /// Find a binder for the given type\n        /// </summary>\n        /// <param name=\"configuration\">a configuration object</param>\n        /// <param name=\"modelType\">the type of the model to bind against.</param>\n        /// <returns>a binder, which can attempt to bind this type. Or null if the binder knows statically that it will never be able to bind the type.</returns>\n        public abstract IModelBinder GetBinder(HttpConfiguration configuration, Type modelType);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/ModelBindingContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Validation;\nusing System.Web.Http.ValueProviders;\n\nnamespace System.Web.Http.ModelBinding\n{\n    public class ModelBindingContext\n    {\n        private string _modelName;\n        private ModelStateDictionary _modelState;\n        private Dictionary<string, ModelMetadata> _propertyMetadata;\n        private ModelValidationNode _validationNode;\n\n        public ModelBindingContext()\n            : this(null)\n        {\n        }\n\n        // copies certain values that won't change between parent and child objects,\n        // e.g. ValueProvider, ModelState\n        public ModelBindingContext(ModelBindingContext bindingContext)\n        {\n            if (bindingContext != null)\n            {\n                ModelState = bindingContext.ModelState;\n                ValueProvider = bindingContext.ValueProvider;\n            }\n        }\n\n        public object Model\n        {\n            get\n            {\n                EnsureModelMetadata();\n                return ModelMetadata.Model;\n            }\n            set\n            {\n                EnsureModelMetadata();\n                ModelMetadata.Model = value;\n            }\n        }\n\n        public ModelMetadata ModelMetadata { get; set; }\n\n        public string ModelName\n        {\n            get\n            {\n                if (_modelName == null)\n                {\n                    _modelName = String.Empty;\n                }\n                return _modelName;\n            }\n            set { _modelName = value; }\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"This is writeable to support unit testing\")]\n        public ModelStateDictionary ModelState\n        {\n            get\n            {\n                if (_modelState == null)\n                {\n                    _modelState = new ModelStateDictionary();\n                }\n                return _modelState;\n            }\n            set { _modelState = value; }\n        }\n\n        public Type ModelType\n        {\n            get\n            {\n                EnsureModelMetadata();\n                return ModelMetadata.ModelType;\n            }\n        }\n\n        public IDictionary<string, ModelMetadata> PropertyMetadata\n        {\n            get\n            {\n                if (_propertyMetadata == null)\n                {\n                    _propertyMetadata = ModelMetadata.Properties.ToDictionary(m => m.PropertyName, StringComparer.OrdinalIgnoreCase);\n                }\n\n                return _propertyMetadata;\n            }\n        }\n\n        public ModelValidationNode ValidationNode\n        {\n            get\n            {\n                if (_validationNode == null)\n                {\n                    _validationNode = new ModelValidationNode(ModelMetadata, ModelName);\n                }\n                return _validationNode;\n            }\n            set { _validationNode = value; }\n        }\n\n        public IValueProvider ValueProvider { get; set; }\n\n        public bool FallbackToEmptyPrefix { get; set; }\n\n        private void EnsureModelMetadata()\n        {\n            if (ModelMetadata == null)\n            {\n                throw Error.InvalidOperation(SRResources.ModelBindingContext_ModelMetadataMustBeSet);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/ModelBindingHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Concurrent;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Linq;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Internal;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.ModelBinding.Binders;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.ModelBinding\n{\n    internal static class ModelBindingHelper\n    {\n        private static readonly ConcurrentDictionary<Type, ModelBinderAttribute> _modelBinderAttributeCache = new ConcurrentDictionary<Type, ModelBinderAttribute>();\n\n        internal static TModel CastOrDefault<TModel>(object model)\n        {\n            return (model is TModel) ? (TModel)model : default(TModel);\n        }\n\n        internal static string CreateIndexModelName(string parentName, int index)\n        {\n            return CreateIndexModelName(parentName, index.ToString(CultureInfo.InvariantCulture));\n        }\n\n        internal static string CreateIndexModelName(string parentName, string index)\n        {\n            return (parentName.Length == 0) ? \"[\" + index + \"]\" : parentName + \"[\" + index + \"]\";\n        }\n\n        internal static string CreatePropertyModelName(string prefix, string propertyName)\n        {\n            if (String.IsNullOrEmpty(prefix))\n            {\n                return propertyName ?? String.Empty;\n            }\n            else if (String.IsNullOrEmpty(propertyName))\n            {\n                return prefix ?? String.Empty;\n            }\n            else\n            {\n                return prefix + \".\" + propertyName;\n            }\n        }\n\n        // Concatenate model keys, if suffix is an indexer, concat strings; otherwise insert a period between the two\n        internal static string ConcatenateKeys(string prefix, string suffix)\n        {\n            Contract.Assert(!String.IsNullOrEmpty(prefix));\n            if (String.IsNullOrEmpty(suffix))\n            {\n                return prefix;\n            }\n            return suffix.StartsWith(\"[\", StringComparison.Ordinal) ? prefix + suffix : prefix + \".\" + suffix;\n        }\n\n        internal static IModelBinder GetPossibleBinderInstance(Type closedModelType, Type openModelType, Type openBinderType)\n        {\n            Type[] typeArguments = TypeHelper.GetTypeArgumentsIfMatch(closedModelType, openModelType);\n            return (typeArguments != null) ? (IModelBinder)Activator.CreateInstance(openBinderType.MakeGenericType(typeArguments)) : null;\n        }\n\n        internal static object[] RawValueToObjectArray(object rawValue)\n        {\n            // precondition: rawValue is not null\n\n            // Need to special-case String so it's not caught by the IEnumerable check which follows\n            if (rawValue is string)\n            {\n                return new[] { rawValue };\n            }\n\n            object[] rawValueAsObjectArray = rawValue as object[];\n            if (rawValueAsObjectArray != null)\n            {\n                return rawValueAsObjectArray;\n            }\n\n            IEnumerable rawValueAsEnumerable = rawValue as IEnumerable;\n            if (rawValueAsEnumerable != null)\n            {\n                return rawValueAsEnumerable.Cast<object>().ToArray();\n            }\n\n            // fallback\n            return new[] { rawValue };\n        }\n\n        internal static void ReplaceEmptyStringWithNull(ModelMetadata modelMetadata, ref object model)\n        {\n            if (model is string &&\n                modelMetadata.ConvertEmptyStringToNull &&\n                String.IsNullOrWhiteSpace(model as string))\n            {\n                model = null;\n            }\n        }\n\n        internal static bool TryGetProviderFromAttribute(Type modelType, ModelBinderAttribute modelBinderAttribute, out ModelBinderProvider provider)\n        {\n            Contract.Assert(modelType != null, \"modelType cannot be null.\");\n            Contract.Assert(modelBinderAttribute != null, \"modelBinderAttribute cannot be null\");\n\n            // TODO, 386718, remove the following if statement when the bug is resolved\n            if (modelBinderAttribute.BinderType == null)\n            {\n                provider = null;\n                return false;\n            }\n\n            if (typeof(ModelBinderProvider).IsAssignableFrom(modelBinderAttribute.BinderType))\n            {\n                // REVIEW: DI?\n                provider = (ModelBinderProvider)Activator.CreateInstance(modelBinderAttribute.BinderType);\n            }\n            else if (typeof(IModelBinder).IsAssignableFrom(modelBinderAttribute.BinderType))\n            {\n                Type closedBinderType =\n                    modelBinderAttribute.BinderType.IsGenericTypeDefinition\n                        ? modelBinderAttribute.BinderType.MakeGenericType(modelType.GetGenericArguments())\n                        : modelBinderAttribute.BinderType;\n\n                IModelBinder binderInstance = (IModelBinder)Activator.CreateInstance(closedBinderType);\n                provider = new SimpleModelBinderProvider(modelType, binderInstance) { SuppressPrefixCheck = modelBinderAttribute.SuppressPrefixCheck };\n            }\n            else\n            {\n                throw Error.InvalidOperation(SRResources.ModelBinderProviderCollection_InvalidBinderType, modelBinderAttribute.BinderType, typeof(ModelBinderProvider), typeof(IModelBinder));\n            }\n\n            return true;\n        }\n\n        internal static bool TryGetProviderFromAttributes(Type modelType, out ModelBinderProvider provider)\n        {\n            ModelBinderAttribute attr = GetModelBinderAttribute(modelType);\n            if (attr == null)\n            {\n                provider = null;\n                return false;\n            }\n\n            return TryGetProviderFromAttribute(modelType, attr, out provider);\n        }\n\n        private static ModelBinderAttribute GetModelBinderAttribute(Type modelType)\n        {\n            ModelBinderAttribute modelBinderAttribute;\n            if (!_modelBinderAttributeCache.TryGetValue(modelType, out modelBinderAttribute))\n            {\n                modelBinderAttribute = TypeDescriptorHelper.Get(modelType).GetAttributes().OfType<ModelBinderAttribute>().FirstOrDefault();\n                _modelBinderAttributeCache.TryAdd(modelType, modelBinderAttribute);\n            }\n            return modelBinderAttribute;\n        }\n\n        internal static void ValidateBindingContext(ModelBindingContext bindingContext)\n        {\n            if (bindingContext == null)\n            {\n                throw Error.ArgumentNull(\"bindingContext\");\n            }\n\n            if (bindingContext.ModelMetadata == null)\n            {\n                throw Error.Argument(\"bindingContext\", SRResources.ModelBinderUtil_ModelMetadataCannotBeNull);\n            }\n        }\n\n        internal static void ValidateBindingContext(ModelBindingContext bindingContext, Type requiredType, bool allowNullModel)\n        {\n            ValidateBindingContext(bindingContext);\n\n            if (bindingContext.ModelType != requiredType)\n            {\n                throw Error.Argument(\"bindingContext\", SRResources.ModelBinderUtil_ModelTypeIsWrong, bindingContext.ModelType, requiredType);\n            }\n\n            if (!allowNullModel && bindingContext.Model == null)\n            {\n                throw Error.Argument(\"bindingContext\", SRResources.ModelBinderUtil_ModelCannotBeNull, requiredType);\n            }\n\n            if (bindingContext.Model != null && !requiredType.IsInstanceOfType(bindingContext.Model))\n            {\n                throw Error.Argument(\"bindingContext\", SRResources.ModelBinderUtil_ModelInstanceIsWrong, bindingContext.Model.GetType(), requiredType);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/ModelError.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.ModelBinding\n{\n    [Serializable]\n    public class ModelError\n    {\n        public ModelError(Exception exception)\n            : this(exception, errorMessage: null)\n        {\n        }\n\n        public ModelError(Exception exception, string errorMessage)\n            : this(errorMessage)\n        {\n            if (exception == null)\n            {\n                throw Error.ArgumentNull(\"exception\");\n            }\n\n            Exception = exception;\n        }\n\n        public ModelError(string errorMessage)\n        {\n            ErrorMessage = errorMessage ?? String.Empty;\n        }\n\n        public Exception Exception { get; private set; }\n\n        public string ErrorMessage { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/ModelErrorCollection.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\n\nnamespace System.Web.Http.ModelBinding\n{\n    [Serializable]\n    public class ModelErrorCollection : Collection<ModelError>\n    {\n        public void Add(Exception exception)\n        {\n            Add(new ModelError(exception));\n        }\n\n        public void Add(string errorMessage)\n        {\n            Add(new ModelError(errorMessage));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/ModelState.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.ValueProviders;\n\nnamespace System.Web.Http.ModelBinding\n{\n    [Serializable]\n    public class ModelState\n    {\n        private ModelErrorCollection _errors = new ModelErrorCollection();\n\n        public ValueProviderResult Value { get; set; }\n\n        public ModelErrorCollection Errors\n        {\n            get { return _errors; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/ModelStateDictionary.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Http.ValueProviders;\n\nnamespace System.Web.Http.ModelBinding\n{\n    [Serializable]\n    public class ModelStateDictionary : IDictionary<string, ModelState>\n    {\n        private readonly Dictionary<string, ModelState> _innerDictionary;\n\n        public ModelStateDictionary()\n        {\n            _innerDictionary = new Dictionary<string, ModelState>(StringComparer.OrdinalIgnoreCase);\n        }\n\n        public ModelStateDictionary(ModelStateDictionary dictionary)\n        {\n            if (dictionary == null)\n            {\n                throw Error.ArgumentNull(\"dictionary\");\n            }\n\n            _innerDictionary = new Dictionary<string, ModelState>(dictionary, StringComparer.OrdinalIgnoreCase);\n        }\n\n        public int Count\n        {\n            get { return _innerDictionary.Count; }\n        }\n\n        public bool IsReadOnly\n        {\n            get { return ((IDictionary<string, ModelState>)_innerDictionary).IsReadOnly; }\n        }\n\n        public bool IsValid\n        {\n            get { return Values.All(modelState => modelState.Errors.Count == 0); }\n        }\n\n        public ICollection<string> Keys\n        {\n            get { return _innerDictionary.Keys; }\n        }\n\n        public ICollection<ModelState> Values\n        {\n            get { return _innerDictionary.Values; }\n        }\n\n        public ModelState this[string key]\n        {\n            get\n            {\n                ModelState value;\n                _innerDictionary.TryGetValue(key, out value);\n                return value;\n            }\n            set { _innerDictionary[key] = value; }\n        }\n\n        public void Add(KeyValuePair<string, ModelState> item)\n        {\n            ((IDictionary<string, ModelState>)_innerDictionary).Add(item);\n        }\n\n        public void Add(string key, ModelState value)\n        {\n            _innerDictionary.Add(key, value);\n        }\n\n        public void AddModelError(string key, Exception exception)\n        {\n            GetModelStateForKey(key).Errors.Add(exception);\n        }\n\n        public void AddModelError(string key, string errorMessage)\n        {\n            GetModelStateForKey(key).Errors.Add(errorMessage);\n        }\n\n        public void Clear()\n        {\n            _innerDictionary.Clear();\n        }\n\n        public bool Contains(KeyValuePair<string, ModelState> item)\n        {\n            return ((IDictionary<string, ModelState>)_innerDictionary).Contains(item);\n        }\n\n        public bool ContainsKey(string key)\n        {\n            return _innerDictionary.ContainsKey(key);\n        }\n\n        public void CopyTo(KeyValuePair<string, ModelState>[] array, int arrayIndex)\n        {\n            ((IDictionary<string, ModelState>)_innerDictionary).CopyTo(array, arrayIndex);\n        }\n\n        public IEnumerator<KeyValuePair<string, ModelState>> GetEnumerator()\n        {\n            return _innerDictionary.GetEnumerator();\n        }\n\n        private ModelState GetModelStateForKey(string key)\n        {\n            if (key == null)\n            {\n                throw Error.ArgumentNull(\"key\");\n            }\n\n            ModelState modelState;\n            if (!TryGetValue(key, out modelState))\n            {\n                modelState = new ModelState();\n                this[key] = modelState;\n            }\n\n            return modelState;\n        }\n\n        public bool IsValidField(string key)\n        {\n            if (key == null)\n            {\n                throw Error.ArgumentNull(\"key\");\n            }\n\n            // if the key is not found in the dictionary, we just say that it's valid (since there are no errors)\n            foreach (KeyValuePair<string, ModelState> entry in this.FindKeysWithPrefix(key))\n            {\n                if (entry.Value.Errors.Count != 0)\n                {\n                    return false;\n                }\n            }\n            return true;\n        }\n\n        public void Merge(ModelStateDictionary dictionary)\n        {\n            if (dictionary == null)\n            {\n                return;\n            }\n\n            foreach (var entry in dictionary)\n            {\n                this[entry.Key] = entry.Value;\n            }\n        }\n\n        public bool Remove(KeyValuePair<string, ModelState> item)\n        {\n            return ((IDictionary<string, ModelState>)_innerDictionary).Remove(item);\n        }\n\n        public bool Remove(string key)\n        {\n            return _innerDictionary.Remove(key);\n        }\n\n        public void SetModelValue(string key, ValueProviderResult value)\n        {\n            GetModelStateForKey(key).Value = value;\n        }\n\n        public bool TryGetValue(string key, out ModelState value)\n        {\n            return _innerDictionary.TryGetValue(key, out value);\n        }\n\n        #region IEnumerable Members\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return ((IEnumerable)_innerDictionary).GetEnumerator();\n        }\n\n        #endregion\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ModelBinding/ParameterBindingRulesCollection.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.ModelBinding\n{    \n    /// <summary>\n    /// Collection of functions that can produce a parameter binding for a given parameter.   \n    /// </summary>\n    public class ParameterBindingRulesCollection : Collection<Func<HttpParameterDescriptor, HttpParameterBinding>>\n    {\n        // Helper to wrap the lambda in a type-check\n        // This is for convenience overloads that want to register by type, which should be a common case.\n        private static Func<HttpParameterDescriptor, HttpParameterBinding> TypeCheck(Type type, Func<HttpParameterDescriptor, HttpParameterBinding> func)\n        {\n            return (param => (param.ParameterType == type) ? func(param) : null);\n        }\n                \n        /// <summary>\n        /// Adds function to the end of the collection. \n        /// The function added is a wrapper around funcInner that checks that parameterType matches typeMatch.\n        /// </summary>\n        /// <param name=\"typeMatch\">type to match against HttpParameterDescriptor.ParameterType</param>\n        /// <param name=\"funcInner\">inner function that is invoked if type match succeeds</param>\n        public void Add(Type typeMatch, Func<HttpParameterDescriptor, HttpParameterBinding> funcInner)\n        {\n            Add(TypeCheck(typeMatch, funcInner));\n        }\n\n        /// <summary>\n        /// Insert a function at the specified index in the collection.\n        /// /// The function added is a wrapper around funcInner that checks that parameterType matches typeMatch.\n        /// </summary>\n        /// <param name=\"index\">index to insert at.</param>\n        /// <param name=\"typeMatch\">type to match against HttpParameterDescriptor.ParameterType</param>\n        /// <param name=\"funcInner\">inner function that is invoked if type match succeeds</param>\n        public void Insert(int index, Type typeMatch, Func<HttpParameterDescriptor, HttpParameterBinding> funcInner)\n        {\n            Insert(index, TypeCheck(typeMatch, funcInner));\n        }\n                \n        /// <summary>\n        /// Execute each binding function in order until one of them returns a non-null binding. \n        /// </summary>\n        /// <param name=\"parameter\">parameter to bind.</param>\n        /// <returns>the first non-null binding produced for the parameter. Of null if no binding is produced.</returns>\n        public HttpParameterBinding LookupBinding(HttpParameterDescriptor parameter)\n        {\n            foreach (Func<HttpParameterDescriptor, HttpParameterBinding> func in this)\n            {\n                HttpParameterBinding binding = func(parameter);\n                if (binding != null)\n                {\n                    return binding;\n                }\n            }\n            return null;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/NonActionAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Apply this attribute on a method so that it is not publicly reachable via routing. \n    /// The method will not be considered an action.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\n    public sealed class NonActionAttribute : Attribute\n    {\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/OverrideActionFiltersAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Filters;\n\nnamespace System.Web.Http\n{\n    /// <summary>Represents a filter attribute that overrides action filters defined at a higher level.</summary>\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\n    public sealed class OverrideActionFiltersAttribute : Attribute, IOverrideFilter\n    {\n        /// <inheritdoc />\n        public bool AllowMultiple\n        {\n            get { return false; }\n        }\n\n        /// <inheritdoc />\n        public Type FiltersToOverride\n        {\n            get { return typeof(IActionFilter); }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/OverrideAuthenticationAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Filters;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Represents a filter attribute that overrides authentication filters defined at a higher level.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\n    public sealed class OverrideAuthenticationAttribute : Attribute, IOverrideFilter\n    {\n        public bool AllowMultiple\n        {\n            get { return false; }\n        }\n\n        public Type FiltersToOverride\n        {\n            get { return typeof(IAuthenticationFilter); }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/OverrideAuthorizationAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Filters;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Represents a filter attribute that overrides authorization filters defined at a higher level.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\n    public sealed class OverrideAuthorizationAttribute : Attribute, IOverrideFilter\n    {\n        public bool AllowMultiple\n        {\n            get { return false; }\n        }\n\n        public Type FiltersToOverride\n        {\n            get { return typeof(IAuthorizationFilter); }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/OverrideExceptionFiltersAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Filters;\n\nnamespace System.Web.Http\n{\n    /// <summary>Represents a filter attribute that overrides exception filters defined at a higher level.</summary>\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\n    public sealed class OverrideExceptionFiltersAttribute : Attribute, IOverrideFilter\n    {\n        public bool AllowMultiple\n        {\n            get { return false; }\n        }\n\n        public Type FiltersToOverride\n        {\n            get { return typeof(IExceptionFilter); }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ParameterBindingAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Attribute on a parameter or type that produces a <see cref=\"HttpParameterBinding\"/>. \n    /// If the attribute is on a type-declaration, then it's as if that attribute is present on all action parameters \n    /// of that type.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)]\n    public abstract class ParameterBindingAttribute : Attribute\n    {\n        public abstract HttpParameterBinding GetBinding(HttpParameterDescriptor parameter);\n    }\n}"
  },
  {
    "path": "src/System.Web.Http/Properties/AssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\n[assembly: AssemblyTitle(\"System.Web.Http\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: Guid(\"70cecdcd-46f5-492b-9e1f-1d9a947f1fd1\")]\n[assembly: InternalsVisibleTo(\"System.Web.Http.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n[assembly: InternalsVisibleTo(\"System.Web.Http.Integration.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n"
  },
  {
    "path": "src/System.Web.Http/Properties/SRResources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.34011\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace System.Web.Http.Properties {\n    using System;\n    \n    \n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class SRResources {\n        \n        private static global::System.Resources.ResourceManager resourceMan;\n        \n        private static global::System.Globalization.CultureInfo resourceCulture;\n        \n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal SRResources() {\n        }\n        \n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"System.Web.Http.Properties.SRResources\", typeof(SRResources).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n        \n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The method &apos;{0}&apos; on type &apos;{1}&apos; returned a Task instance even though it is not an asynchronous method..\n        /// </summary>\n        internal static string ActionExecutor_UnexpectedTaskInstance {\n            get {\n                return ResourceManager.GetString(\"ActionExecutor_UnexpectedTaskInstance\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The method &apos;{0}&apos; on type &apos;{1}&apos; returned an instance of &apos;{2}&apos;. Make sure to call Unwrap on the returned value to avoid unobserved faulted Task..\n        /// </summary>\n        internal static string ActionExecutor_WrappedTaskInstance {\n            get {\n                return ResourceManager.GetString(\"ActionExecutor_WrappedTaskInstance\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to After calling {0}.OnActionExecuted, the HttpActionExecutedContext properties Result and Exception were both null. At least one of these values must be non-null. To provide a new response, please set the Result object; to indicate an error, please throw an exception..\n        /// </summary>\n        internal static string ActionFilterAttribute_MustSupplyResponseOrException {\n            get {\n                return ResourceManager.GetString(\"ActionFilterAttribute_MustSupplyResponseOrException\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to {0} on type {1}.\n        /// </summary>\n        internal static string ActionSelector_AmbiguousMatchType {\n            get {\n                return ResourceManager.GetString(\"ActionSelector_AmbiguousMatchType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to ApiController.Request must not be null..\n        /// </summary>\n        internal static string ApiController_RequestMustNotBeNull {\n            get {\n                return ResourceManager.GetString(\"ApiController_RequestMustNotBeNull\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to An object of type &apos;{0}&apos; was returned where an instance of IHttpActionResult was expected..\n        /// </summary>\n        internal static string ApiControllerActionInvoker_InvalidHttpActionResult {\n            get {\n                return ResourceManager.GetString(\"ApiControllerActionInvoker_InvalidHttpActionResult\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A null value was returned where an instance of IHttpActionResult was expected..\n        /// </summary>\n        internal static string ApiControllerActionInvoker_NullHttpActionResult {\n            get {\n                return ResourceManager.GetString(\"ApiControllerActionInvoker_NullHttpActionResult\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to No action was found on the controller &apos;{0}&apos; that matches the name &apos;{1}&apos;..\n        /// </summary>\n        internal static string ApiControllerActionSelector_ActionNameNotFound {\n            get {\n                return ResourceManager.GetString(\"ApiControllerActionSelector_ActionNameNotFound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to No action was found on the controller &apos;{0}&apos; that matches the request..\n        /// </summary>\n        internal static string ApiControllerActionSelector_ActionNotFound {\n            get {\n                return ResourceManager.GetString(\"ApiControllerActionSelector_ActionNotFound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Multiple actions were found that match the request: {0}.\n        /// </summary>\n        internal static string ApiControllerActionSelector_AmbiguousMatch {\n            get {\n                return ResourceManager.GetString(\"ApiControllerActionSelector_AmbiguousMatch\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The requested resource does not support http method &apos;{0}&apos;..\n        /// </summary>\n        internal static string ApiControllerActionSelector_HttpMethodNotSupported {\n            get {\n                return ResourceManager.GetString(\"ApiControllerActionSelector_HttpMethodNotSupported\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The route prefix &apos;{0}&apos; on the controller named &apos;{1}&apos; cannot end with a &apos;/&apos; character..\n        /// </summary>\n        internal static string AttributeRoutes_InvalidPrefix {\n            get {\n                return ResourceManager.GetString(\"AttributeRoutes_InvalidPrefix\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The route template &apos;{0}&apos; on the action named &apos;{1}&apos; cannot start with a &apos;/&apos; character..\n        /// </summary>\n        internal static string AttributeRoutes_InvalidTemplate {\n            get {\n                return ResourceManager.GetString(\"AttributeRoutes_InvalidTemplate\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The authentication filter did not encounter an error or set a principal..\n        /// </summary>\n        internal static string AuthenticationFilterDidNothing {\n            get {\n                return ResourceManager.GetString(\"AuthenticationFilterDidNothing\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The authentication filter encountered an error. ErrorResult=&apos;{0}&apos;..\n        /// </summary>\n        internal static string AuthenticationFilterErrorResult {\n            get {\n                return ResourceManager.GetString(\"AuthenticationFilterErrorResult\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The authentication filter successfully set a principal to a known identity. Identity.Name=&apos;{0}&apos;. Identity.AuthenticationType=&apos;{1}&apos;..\n        /// </summary>\n        internal static string AuthenticationFilterSetPrincipalToKnownIdentity {\n            get {\n                return ResourceManager.GetString(\"AuthenticationFilterSetPrincipalToKnownIdentity\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The authentication filter set a principal to an unknown identity..\n        /// </summary>\n        internal static string AuthenticationFilterSetPrincipalToUnknownIdentity {\n            get {\n                return ResourceManager.GetString(\"AuthenticationFilterSetPrincipalToUnknownIdentity\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The request is invalid..\n        /// </summary>\n        internal static string BadRequest {\n            get {\n                return ResourceManager.GetString(\"BadRequest\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The batch request must have a &quot;Content-Type&quot; header..\n        /// </summary>\n        internal static string BatchContentTypeMissing {\n            get {\n                return ResourceManager.GetString(\"BatchContentTypeMissing\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The batch request of media type &apos;{0}&apos; is not supported..\n        /// </summary>\n        internal static string BatchMediaTypeNotSupported {\n            get {\n                return ResourceManager.GetString(\"BatchMediaTypeNotSupported\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &apos;Content&apos; property on the batch request cannot be null..\n        /// </summary>\n        internal static string BatchRequestMissingContent {\n            get {\n                return ResourceManager.GetString(\"BatchRequestMissingContent\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Cannot reuse an &apos;{0}&apos; instance. &apos;{0}&apos; has to be constructed per incoming message. Check your custom &apos;{1}&apos; and make sure that it will not manufacture the same instance..\n        /// </summary>\n        internal static string CannotSupportSingletonInstance {\n            get {\n                return ResourceManager.GetString(\"CannotSupportSingletonInstance\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The parameter &apos;{0}&apos; cannot contain a null element..\n        /// </summary>\n        internal static string CollectionParameterContainsNullElement {\n            get {\n                return ResourceManager.GetString(\"CollectionParameterContainsNullElement\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The property {0}.{1} could not be found..\n        /// </summary>\n        internal static string Common_PropertyNotFound {\n            get {\n                return ResourceManager.GetString(\"Common_PropertyNotFound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The type {0} must derive from {1}..\n        /// </summary>\n        internal static string Common_TypeMustDriveFromType {\n            get {\n                return ResourceManager.GetString(\"Common_TypeMustDriveFromType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to No route providing a controller name was found to match request URI &apos;{0}&apos;.\n        /// </summary>\n        internal static string ControllerNameNotFound {\n            get {\n                return ResourceManager.GetString(\"ControllerNameNotFound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The type {0} must have a public constructor which accepts three parameters of types {1}, {2}, and {3}..\n        /// </summary>\n        internal static string DataAnnotationsModelValidatorProvider_ConstructorRequirements {\n            get {\n                return ResourceManager.GetString(\"DataAnnotationsModelValidatorProvider_ConstructorRequirements\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The type {0} must have a public constructor which accepts two parameters of types {1} and {2}..\n        /// </summary>\n        internal static string DataAnnotationsModelValidatorProvider_ValidatableConstructorRequirements {\n            get {\n                return ResourceManager.GetString(\"DataAnnotationsModelValidatorProvider_ValidatableConstructorRequirements\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Multiple types were found that match the controller named &apos;{0}&apos;. This can happen if the route that services this request (&apos;{1}&apos;) found multiple controllers defined with the same name but differing namespaces, which is not supported.{3}{3}The request for &apos;{0}&apos; has found the following matching controllers:{2}.\n        /// </summary>\n        internal static string DefaultControllerFactory_ControllerNameAmbiguous_WithRouteTemplate {\n            get {\n                return ResourceManager.GetString(\"DefaultControllerFactory_ControllerNameAmbiguous_WithRouteTemplate\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to No type was found that matches the controller named &apos;{0}&apos;..\n        /// </summary>\n        internal static string DefaultControllerFactory_ControllerNameNotFound {\n            get {\n                return ResourceManager.GetString(\"DefaultControllerFactory_ControllerNameNotFound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to An error occurred when trying to create a controller of type &apos;{0}&apos;. Make sure that the controller has a parameterless public constructor..\n        /// </summary>\n        internal static string DefaultControllerFactory_ErrorCreatingController {\n            get {\n                return ResourceManager.GetString(\"DefaultControllerFactory_ErrorCreatingController\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The constructor to use for activating the constraint type &apos;{0}&apos; is ambiguous. Multiple constructors were found with the following number of parameters: {1}..\n        /// </summary>\n        internal static string DefaultInlineConstraintResolver_AmbiguousCtors {\n            get {\n                return ResourceManager.GetString(\"DefaultInlineConstraintResolver_AmbiguousCtors\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Could not find a constructor for constraint type &apos;{0}&apos; with the following number of parameters: {1}..\n        /// </summary>\n        internal static string DefaultInlineConstraintResolver_CouldNotFindCtor {\n            get {\n                return ResourceManager.GetString(\"DefaultInlineConstraintResolver_CouldNotFindCtor\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The constraint type &apos;{0}&apos; which is mapped to constraint key &apos;{1}&apos; must implement the IHttpRouteConstraint interface..\n        /// </summary>\n        internal static string DefaultInlineConstraintResolver_TypeNotConstraint {\n            get {\n                return ResourceManager.GetString(\"DefaultInlineConstraintResolver_TypeNotConstraint\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The service type {0} is not supported..\n        /// </summary>\n        internal static string DefaultServices_InvalidServiceType {\n            get {\n                return ResourceManager.GetString(\"DefaultServices_InvalidServiceType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A dependency resolver of type &apos;{0}&apos; 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..\n        /// </summary>\n        internal static string DependencyResolver_BeginScopeReturnsNull {\n            get {\n                return ResourceManager.GetString(\"DependencyResolver_BeginScopeReturnsNull\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to No service registered for type &apos;{0}&apos;..\n        /// </summary>\n        internal static string DependencyResolverNoService {\n            get {\n                return ResourceManager.GetString(\"DependencyResolverNoService\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Multiple controller types were found that match the URL. This can happen if attribute routes on multiple controllers match the requested URL.{1}{1}The request has found the following matching controller types: {0}.\n        /// </summary>\n        internal static string DirectRoute_AmbiguousController {\n            get {\n                return ResourceManager.GetString(\"DirectRoute_AmbiguousController\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Direct routing does not support per-route message handlers..\n        /// </summary>\n        internal static string DirectRoute_HandlerNotSupported {\n            get {\n                return ResourceManager.GetString(\"DirectRoute_HandlerNotSupported\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A direct route for an action method cannot use the parameter &apos;action&apos;. Specify a literal path in place of this parameter to create a route to the action..\n        /// </summary>\n        internal static string DirectRoute_InvalidParameter_Action {\n            get {\n                return ResourceManager.GetString(\"DirectRoute_InvalidParameter_Action\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A direct route cannot use the parameter &apos;controller&apos;. Specify a literal path in place of this parameter to create a route to a controller..\n        /// </summary>\n        internal static string DirectRoute_InvalidParameter_Controller {\n            get {\n                return ResourceManager.GetString(\"DirectRoute_InvalidParameter_Controller\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The route does not have any associated action descriptors. Routing requires that each direct route map to a non-empty set of actions..\n        /// </summary>\n        internal static string DirectRoute_MissingActionDescriptors {\n            get {\n                return ResourceManager.GetString(\"DirectRoute_MissingActionDescriptors\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to An error has occurred..\n        /// </summary>\n        internal static string ErrorOccurred {\n            get {\n                return ResourceManager.GetString(\"ErrorOccurred\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to No action result converter could be constructed for a generic parameter type &apos;{0}&apos;..\n        /// </summary>\n        internal static string HttpActionDescriptor_NoConverterForGenericParamterTypeExists {\n            get {\n                return ResourceManager.GetString(\"HttpActionDescriptor_NoConverterForGenericParamterTypeExists\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to HttpControllerContext.Configuration must not be null..\n        /// </summary>\n        internal static string HttpControllerContext_ConfigurationMustNotBeNull {\n            get {\n                return ResourceManager.GetString(\"HttpControllerContext_ConfigurationMustNotBeNull\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The request does not have an associated configuration object or the provided configuration was null..\n        /// </summary>\n        internal static string HttpRequestMessageExtensions_NoConfiguration {\n            get {\n                return ResourceManager.GetString(\"HttpRequestMessageExtensions_NoConfiguration\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The provided configuration does not have an instance of the &apos;{0}&apos; service registered..\n        /// </summary>\n        internal static string HttpRequestMessageExtensions_NoContentNegotiator {\n            get {\n                return ResourceManager.GetString(\"HttpRequestMessageExtensions_NoContentNegotiator\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Could not find a formatter matching the media type &apos;{0}&apos; that can write an instance of &apos;{1}&apos;..\n        /// </summary>\n        internal static string HttpRequestMessageExtensions_NoMatchingFormatter {\n            get {\n                return ResourceManager.GetString(\"HttpRequestMessageExtensions_NoMatchingFormatter\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by the &apos;Response&apos; property of this exception for details..\n        /// </summary>\n        internal static string HttpResponseExceptionMessage {\n            get {\n                return ResourceManager.GetString(\"HttpResponseExceptionMessage\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The inline constraint resolver of type &apos;{0}&apos; was unable to resolve the following inline constraint: &apos;{1}&apos;..\n        /// </summary>\n        internal static string HttpRouteBuilder_CouldNotResolveConstraint {\n            get {\n                return ResourceManager.GetString(\"HttpRouteBuilder_CouldNotResolveConstraint\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The server is no longer available..\n        /// </summary>\n        internal static string HttpServerDisposed {\n            get {\n                return ResourceManager.GetString(\"HttpServerDisposed\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The key is invalid JQuery syntax because it is missing a closing bracket.\n        /// </summary>\n        internal static string JQuerySyntaxMissingClosingBracket {\n            get {\n                return ResourceManager.GetString(\"JQuerySyntaxMissingClosingBracket\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The number of keys in a NameValueCollection has exceeded the limit of &apos;{0}&apos;. You can adjust it by modifying the MaxHttpCollectionKeys property on the &apos;{1}&apos; class..\n        /// </summary>\n        internal static string MaxHttpCollectionKeyLimitReached {\n            get {\n                return ResourceManager.GetString(\"MaxHttpCollectionKeyLimitReached\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Property &apos;{0}&apos; on type &apos;{1}&apos; is invalid. Value-typed properties marked as [Required] must also be marked with [DataMember(IsRequired=true)] to be recognized as required. Consider attributing the declaring type with [DataContract] and the property with [DataMember(IsRequired=true)]..\n        /// </summary>\n        internal static string MissingDataMemberIsRequired {\n            get {\n                return ResourceManager.GetString(\"MissingDataMemberIsRequired\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The {0} property is required..\n        /// </summary>\n        internal static string MissingRequiredMember {\n            get {\n                return ResourceManager.GetString(\"MissingRequiredMember\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The value &apos;{0}&apos; is not valid for {1}..\n        /// </summary>\n        internal static string ModelBinderConfig_ValueInvalid {\n            get {\n                return ResourceManager.GetString(\"ModelBinderConfig_ValueInvalid\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A value is required..\n        /// </summary>\n        internal static string ModelBinderConfig_ValueRequired {\n            get {\n                return ResourceManager.GetString(\"ModelBinderConfig_ValueRequired\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The type &apos;{0}&apos; does not subclass {1} or implement the interface {2}..\n        /// </summary>\n        internal static string ModelBinderProviderCollection_InvalidBinderType {\n            get {\n                return ResourceManager.GetString(\"ModelBinderProviderCollection_InvalidBinderType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The binding context has a null Model, but this binder requires a non-null model of type &apos;{0}&apos;..\n        /// </summary>\n        internal static string ModelBinderUtil_ModelCannotBeNull {\n            get {\n                return ResourceManager.GetString(\"ModelBinderUtil_ModelCannotBeNull\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The binding context has a Model of type &apos;{0}&apos;, but this binder can only operate on models of type &apos;{1}&apos;..\n        /// </summary>\n        internal static string ModelBinderUtil_ModelInstanceIsWrong {\n            get {\n                return ResourceManager.GetString(\"ModelBinderUtil_ModelInstanceIsWrong\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The binding context cannot have a null ModelMetadata..\n        /// </summary>\n        internal static string ModelBinderUtil_ModelMetadataCannotBeNull {\n            get {\n                return ResourceManager.GetString(\"ModelBinderUtil_ModelMetadataCannotBeNull\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The binding context has a ModelType of &apos;{0}&apos;, but this binder can only operate on models of type &apos;{1}&apos;..\n        /// </summary>\n        internal static string ModelBinderUtil_ModelTypeIsWrong {\n            get {\n                return ResourceManager.GetString(\"ModelBinderUtil_ModelTypeIsWrong\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The ModelMetadata property must be set before accessing this property..\n        /// </summary>\n        internal static string ModelBindingContext_ModelMetadataMustBeSet {\n            get {\n                return ResourceManager.GetString(\"ModelBindingContext_ModelMetadataMustBeSet\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to No controller was created to handle this request..\n        /// </summary>\n        internal static string NoControllerCreated {\n            get {\n                return ResourceManager.GetString(\"NoControllerCreated\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to No controller was selected to handle this request..\n        /// </summary>\n        internal static string NoControllerSelected {\n            get {\n                return ResourceManager.GetString(\"NoControllerSelected\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to No route data was found for this request..\n        /// </summary>\n        internal static string NoRouteData {\n            get {\n                return ResourceManager.GetString(\"NoRouteData\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application&apos;s startup code after all other initialization code..\n        /// </summary>\n        internal static string Object_NotYetInitialized {\n            get {\n                return ResourceManager.GetString(\"Object_NotYetInitialized\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Optional parameter &apos;{0}&apos; is not supported by &apos;{1}&apos;..\n        /// </summary>\n        internal static string OptionalBodyParameterNotSupported {\n            get {\n                return ResourceManager.GetString(\"OptionalBodyParameterNotSupported\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Can&apos;t bind multiple parameters (&apos;{0}&apos; and &apos;{1}&apos;) to the request&apos;s content..\n        /// </summary>\n        internal static string ParameterBindingCantHaveMultipleBodyParameters {\n            get {\n                return ResourceManager.GetString(\"ParameterBindingCantHaveMultipleBodyParameters\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Can&apos;t bind parameter &apos;{0}&apos; because it has conflicting attributes on it..\n        /// </summary>\n        internal static string ParameterBindingConflictingAttributes {\n            get {\n                return ResourceManager.GetString(\"ParameterBindingConflictingAttributes\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Can&apos;t bind parameter &apos;{1}&apos;. Must specify a custom model binder to bind parameters of type &apos;{0}&apos;..\n        /// </summary>\n        internal static string ParameterBindingIllegalType {\n            get {\n                return ResourceManager.GetString(\"ParameterBindingIllegalType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The parameters dictionary contains a null entry for parameter &apos;{0}&apos; of non-nullable type &apos;{1}&apos; for method &apos;{2}&apos; in &apos;{3}&apos;. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter..\n        /// </summary>\n        internal static string ReflectedActionDescriptor_ParameterCannotBeNull {\n            get {\n                return ResourceManager.GetString(\"ReflectedActionDescriptor_ParameterCannotBeNull\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The parameters dictionary does not contain an entry for parameter &apos;{0}&apos; of type &apos;{1}&apos; for method &apos;{2}&apos; in &apos;{3}&apos;. The dictionary must contain an entry for each parameter, including parameters that have null values..\n        /// </summary>\n        internal static string ReflectedActionDescriptor_ParameterNotInDictionary {\n            get {\n                return ResourceManager.GetString(\"ReflectedActionDescriptor_ParameterNotInDictionary\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The parameters dictionary contains an invalid entry for parameter &apos;{0}&apos; for method &apos;{1}&apos; in &apos;{2}&apos;. The dictionary contains a value of type &apos;{3}&apos;, but the parameter requires a value of type &apos;{4}&apos;..\n        /// </summary>\n        internal static string ReflectedActionDescriptor_ParameterValueHasWrongType {\n            get {\n                return ResourceManager.GetString(\"ReflectedActionDescriptor_ParameterValueHasWrongType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Cannot call action method &apos;{0}&apos; on controller &apos;{1}&apos; because the action method is a generic method..\n        /// </summary>\n        internal static string ReflectedHttpActionDescriptor_CannotCallOpenGenericMethods {\n            get {\n                return ResourceManager.GetString(\"ReflectedHttpActionDescriptor_CannotCallOpenGenericMethods\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The request must have a request context..\n        /// </summary>\n        internal static string Request_RequestContextMustNotBeNull {\n            get {\n                return ResourceManager.GetString(\"Request_RequestContextMustNotBeNull\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The request context property on the request must be null or match ApiController.RequestContext..\n        /// </summary>\n        internal static string RequestContextConflict {\n            get {\n                return ResourceManager.GetString(\"RequestContextConflict\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The property &apos;Request&apos; on &apos;{0}&apos; is null. The property must be initialized with a non-null value..\n        /// </summary>\n        internal static string RequestIsNull {\n            get {\n                return ResourceManager.GetString(\"RequestIsNull\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Authorization has been denied for this request..\n        /// </summary>\n        internal static string RequestNotAuthorized {\n            get {\n                return ResourceManager.GetString(\"RequestNotAuthorized\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to No HTTP resource was found that matches the request URI &apos;{0}&apos;..\n        /// </summary>\n        internal static string ResourceNotFound {\n            get {\n                return ResourceManager.GetString(\"ResourceNotFound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A null value was returned where an instance of HttpResponseMessage was expected..\n        /// </summary>\n        internal static string ResponseMessageResultConverter_NullHttpResponseMessage {\n            get {\n                return ResourceManager.GetString(\"ResponseMessageResultConverter_NullHttpResponseMessage\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Adding or removing items from a &apos;{0}&apos; is not supported. Please use a key when adding and removing items..\n        /// </summary>\n        internal static string Route_AddRemoveWithNoKeyNotSupported {\n            get {\n                return ResourceManager.GetString(\"Route_AddRemoveWithNoKeyNotSupported\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A path segment that contains more than one section, such as a literal section or a parameter, cannot contain a catch-all parameter..\n        /// </summary>\n        internal static string Route_CannotHaveCatchAllInMultiSegment {\n            get {\n                return ResourceManager.GetString(\"Route_CannotHaveCatchAllInMultiSegment\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A path segment cannot contain two consecutive parameters. They must be separated by a &apos;/&apos; or by a literal string..\n        /// </summary>\n        internal static string Route_CannotHaveConsecutiveParameters {\n            get {\n                return ResourceManager.GetString(\"Route_CannotHaveConsecutiveParameters\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The route template separator character &apos;/&apos; cannot appear consecutively. It must be separated by either a parameter or a literal value..\n        /// </summary>\n        internal static string Route_CannotHaveConsecutiveSeparators {\n            get {\n                return ResourceManager.GetString(\"Route_CannotHaveConsecutiveSeparators\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A catch-all parameter can only appear as the last segment of the route template..\n        /// </summary>\n        internal static string Route_CatchAllMustBeLast {\n            get {\n                return ResourceManager.GetString(\"Route_CatchAllMustBeLast\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The route parameter name &apos;{0}&apos; is invalid. Route parameter names must be non-empty and cannot contain these characters: &quot;{{&quot;, &quot;}}&quot;, &quot;/&quot;, &quot;?&quot;.\n        /// </summary>\n        internal static string Route_InvalidParameterName {\n            get {\n                return ResourceManager.GetString(\"Route_InvalidParameterName\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The route template cannot start with a &apos;/&apos; or &apos;~&apos; character and it cannot contain a &apos;?&apos; character..\n        /// </summary>\n        internal static string Route_InvalidRouteTemplate {\n            get {\n                return ResourceManager.GetString(\"Route_InvalidRouteTemplate\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to There is an incomplete parameter in this path segment: &apos;{0}&apos;. Check that each &apos;{{&apos; character has a matching &apos;}}&apos; character..\n        /// </summary>\n        internal static string Route_MismatchedParameter {\n            get {\n                return ResourceManager.GetString(\"Route_MismatchedParameter\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The route parameter name &apos;{0}&apos; appears more than one time in the route template..\n        /// </summary>\n        internal static string Route_RepeatedParameter {\n            get {\n                return ResourceManager.GetString(\"Route_RepeatedParameter\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The constraint entry &apos;{0}&apos; on the route with route template &apos;{1}&apos; must have a string value or be of a type which implements &apos;{2}&apos;..\n        /// </summary>\n        internal static string Route_ValidationMustBeStringOrCustomConstraint {\n            get {\n                return ResourceManager.GetString(\"Route_ValidationMustBeStringOrCustomConstraint\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A route named &apos;{0}&apos; could not be found in the route collection..\n        /// </summary>\n        internal static string RouteCollection_NameNotFound {\n            get {\n                return ResourceManager.GetString(\"RouteCollection_NameNotFound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Only one route prefix attribute is supported. Remove extra attributes from the controller of type &apos;{0}&apos;..\n        /// </summary>\n        internal static string RoutePrefix_CannotSupportMultiRoutePrefix {\n            get {\n                return ResourceManager.GetString(\"RoutePrefix_CannotSupportMultiRoutePrefix\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The property &apos;prefix&apos; from route prefix attribute on controller of type &apos;{0}&apos; cannot be null..\n        /// </summary>\n        internal static string RoutePrefix_PrefixCannotBeNull {\n            get {\n                return ResourceManager.GetString(\"RoutePrefix_PrefixCannotBeNull\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A route named &apos;{0}&apos; is already in the route collection. Route names must be unique.\n        ///\n        ///Duplicates:\n        ///{1}\n        ///{2}.\n        /// </summary>\n        internal static string SubRouteCollection_DuplicateRouteName {\n            get {\n                return ResourceManager.GetString(\"SubRouteCollection_DuplicateRouteName\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Action filter for &apos;{0}&apos;.\n        /// </summary>\n        internal static string TraceActionFilterMessage {\n            get {\n                return ResourceManager.GetString(\"TraceActionFilterMessage\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Action=&apos;{0}&apos;.\n        /// </summary>\n        internal static string TraceActionInvokeMessage {\n            get {\n                return ResourceManager.GetString(\"TraceActionInvokeMessage\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Action returned &apos;{0}&apos;.\n        /// </summary>\n        internal static string TraceActionReturnValue {\n            get {\n                return ResourceManager.GetString(\"TraceActionReturnValue\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Selected action &apos;{0}&apos;.\n        /// </summary>\n        internal static string TraceActionSelectedMessage {\n            get {\n                return ResourceManager.GetString(\"TraceActionSelectedMessage\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Binding parameter &apos;{0}&apos;.\n        /// </summary>\n        internal static string TraceBeginParameterBind {\n            get {\n                return ResourceManager.GetString(\"TraceBeginParameterBind\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Cancelled.\n        /// </summary>\n        internal static string TraceCancelledMessage {\n            get {\n                return ResourceManager.GetString(\"TraceCancelledMessage\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Parameter &apos;{0}&apos; bound to the value &apos;{1}&apos;.\n        /// </summary>\n        internal static string TraceEndParameterBind {\n            get {\n                return ResourceManager.GetString(\"TraceEndParameterBind\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Parameter &apos;{0}&apos; failed to bind..\n        /// </summary>\n        internal static string TraceEndParameterBindNoBind {\n            get {\n                return ResourceManager.GetString(\"TraceEndParameterBindNoBind\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Will use same &apos;{0}&apos; formatter.\n        /// </summary>\n        internal static string TraceGetPerRequestFormatterEndMessage {\n            get {\n                return ResourceManager.GetString(\"TraceGetPerRequestFormatterEndMessage\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Will use new &apos;{0}&apos; formatter.\n        /// </summary>\n        internal static string TraceGetPerRequestFormatterEndMessageNew {\n            get {\n                return ResourceManager.GetString(\"TraceGetPerRequestFormatterEndMessageNew\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Obtaining formatter of type &apos;{0}&apos; for type=&apos;{1}&apos;, mediaType=&apos;{2}&apos;.\n        /// </summary>\n        internal static string TraceGetPerRequestFormatterMessage {\n            get {\n                return ResourceManager.GetString(\"TraceGetPerRequestFormatterMessage\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Null formatter.\n        /// </summary>\n        internal static string TraceGetPerRequestNullFormatterEndMessage {\n            get {\n                return ResourceManager.GetString(\"TraceGetPerRequestNullFormatterEndMessage\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Exception thrown while getting types from &apos;{0}&apos;..\n        /// </summary>\n        internal static string TraceHttpControllerTypeResolverError {\n            get {\n                return ResourceManager.GetString(\"TraceHttpControllerTypeResolverError\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Invoking action &apos;{0}&apos;.\n        /// </summary>\n        internal static string TraceInvokingAction {\n            get {\n                return ResourceManager.GetString(\"TraceInvokingAction\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to {0}: {1}.\n        /// </summary>\n        internal static string TraceModelStateErrorMessage {\n            get {\n                return ResourceManager.GetString(\"TraceModelStateErrorMessage\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Model state is invalid. {0}.\n        /// </summary>\n        internal static string TraceModelStateInvalidMessage {\n            get {\n                return ResourceManager.GetString(\"TraceModelStateInvalidMessage\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Type=&apos;{0}&apos;, formatters=[{1}].\n        /// </summary>\n        internal static string TraceNegotiateFormatter {\n            get {\n                return ResourceManager.GetString(\"TraceNegotiateFormatter\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to none.\n        /// </summary>\n        internal static string TraceNoneObjectMessage {\n            get {\n                return ResourceManager.GetString(\"TraceNoneObjectMessage\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Type=&apos;{0}&apos;, content-type=&apos;{1}&apos;.\n        /// </summary>\n        internal static string TraceReadFromStreamMessage {\n            get {\n                return ResourceManager.GetString(\"TraceReadFromStreamMessage\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Value read=&apos;{0}&apos;.\n        /// </summary>\n        internal static string TraceReadFromStreamValueMessage {\n            get {\n                return ResourceManager.GetString(\"TraceReadFromStreamValueMessage\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Content-type=&apos;{0}&apos;, content-length={1}.\n        /// </summary>\n        internal static string TraceRequestCompleteMessage {\n            get {\n                return ResourceManager.GetString(\"TraceRequestCompleteMessage\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Route=&apos;{0}&apos;.\n        /// </summary>\n        internal static string TraceRouteMessage {\n            get {\n                return ResourceManager.GetString(\"TraceRouteMessage\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Selected formatter=&apos;{0}&apos;, content-type=&apos;{1}&apos;.\n        /// </summary>\n        internal static string TraceSelectedFormatter {\n            get {\n                return ResourceManager.GetString(\"TraceSelectedFormatter\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to unknown.\n        /// </summary>\n        internal static string TraceUnknownMessage {\n            get {\n                return ResourceManager.GetString(\"TraceUnknownMessage\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Model state is valid. Values: {0}.\n        /// </summary>\n        internal static string TraceValidModelState {\n            get {\n                return ResourceManager.GetString(\"TraceValidModelState\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Value=&apos;{0}&apos;, type=&apos;{1}&apos;, content-type=&apos;{2}&apos;.\n        /// </summary>\n        internal static string TraceWriteToStreamMessage {\n            get {\n                return ResourceManager.GetString(\"TraceWriteToStreamMessage\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The {0} instance must not be null..\n        /// </summary>\n        internal static string TypeInstanceMustNotBeNull {\n            get {\n                return ResourceManager.GetString(\"TypeInstanceMustNotBeNull\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to {0}.{1} must not return null..\n        /// </summary>\n        internal static string TypeMethodMustNotReturnNull {\n            get {\n                return ResourceManager.GetString(\"TypeMethodMustNotReturnNull\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to {0}.{1} must not be null..\n        /// </summary>\n        internal static string TypePropertyMustNotBeNull {\n            get {\n                return ResourceManager.GetString(\"TypePropertyMustNotBeNull\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The request entity&apos;s media type &apos;{0}&apos; is not supported for this resource..\n        /// </summary>\n        internal static string UnsupportedMediaType {\n            get {\n                return ResourceManager.GetString(\"UnsupportedMediaType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The request contains an entity body but no Content-Type header. The inferred media type &apos;{0}&apos; is not supported for this resource..\n        /// </summary>\n        internal static string UnsupportedMediaTypeNoContentType {\n            get {\n                return ResourceManager.GetString(\"UnsupportedMediaTypeNoContentType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to UrlHelper.Link must not return null..\n        /// </summary>\n        internal static string UrlHelper_LinkMustNotReturnNull {\n            get {\n                return ResourceManager.GetString(\"UrlHelper_LinkMustNotReturnNull\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The model object inside the metadata claimed to be compatible with {0}, but was actually {1}..\n        /// </summary>\n        internal static string ValidatableObjectAdapter_IncompatibleType {\n            get {\n                return ResourceManager.GetString(\"ValidatableObjectAdapter_IncompatibleType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A value is required but was not present in the request..\n        /// </summary>\n        internal static string Validation_ValueNotFound {\n            get {\n                return ResourceManager.GetString(\"Validation_ValueNotFound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Field &apos;{0}&apos; on type &apos;{1}&apos; is attributed with one or more validation attributes. Validation attributes on fields are not supported. Consider using a public property for validation instead..\n        /// </summary>\n        internal static string ValidationAttributeOnField {\n            get {\n                return ResourceManager.GetString(\"ValidationAttributeOnField\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Non-public property &apos;{0}&apos; on type &apos;{1}&apos; is attributed with one or more validation attributes. Validation attributes on non-public properties are not supported. Consider using a public property for validation instead..\n        /// </summary>\n        internal static string ValidationAttributeOnNonPublicProperty {\n            get {\n                return ResourceManager.GetString(\"ValidationAttributeOnNonPublicProperty\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The model state is valid..\n        /// </summary>\n        internal static string ValidModelState {\n            get {\n                return ResourceManager.GetString(\"ValidModelState\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Could not create a &apos;{0}&apos; from &apos;{1}&apos;. Please ensure it derives from &apos;{0}&apos; and has a public parameterless constructor..\n        /// </summary>\n        internal static string ValueProviderFactory_Cannot_Create {\n            get {\n                return ResourceManager.GetString(\"ValueProviderFactory_Cannot_Create\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The parameter conversion from type &apos;{0}&apos; to type &apos;{1}&apos; failed. See the inner exception for more information..\n        /// </summary>\n        internal static string ValueProviderResult_ConversionThrew {\n            get {\n                return ResourceManager.GetString(\"ValueProviderResult_ConversionThrew\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The parameter conversion from type &apos;{0}&apos; to type &apos;{1}&apos; failed because no type converter can convert between these types..\n        /// </summary>\n        internal static string ValueProviderResult_NoConverterExists {\n            get {\n                return ResourceManager.GetString(\"ValueProviderResult_NoConverterExists\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Properties/SRResources.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"ModelBinderUtil_ModelCannotBeNull\" xml:space=\"preserve\">\n    <value>The binding context has a null Model, but this binder requires a non-null model of type '{0}'.</value>\n  </data>\n  <data name=\"ModelBinderUtil_ModelInstanceIsWrong\" xml:space=\"preserve\">\n    <value>The binding context has a Model of type '{0}', but this binder can only operate on models of type '{1}'.</value>\n  </data>\n  <data name=\"ModelBinderUtil_ModelMetadataCannotBeNull\" xml:space=\"preserve\">\n    <value>The binding context cannot have a null ModelMetadata.</value>\n  </data>\n  <data name=\"ModelBinderUtil_ModelTypeIsWrong\" xml:space=\"preserve\">\n    <value>The binding context has a ModelType of '{0}', but this binder can only operate on models of type '{1}'.</value>\n  </data>\n  <data name=\"ModelBinderConfig_ValueInvalid\" xml:space=\"preserve\">\n    <value>The value '{0}' is not valid for {1}.</value>\n  </data>\n  <data name=\"ModelBinderConfig_ValueRequired\" xml:space=\"preserve\">\n    <value>A value is required.</value>\n  </data>\n  <data name=\"ModelBindingContext_ModelMetadataMustBeSet\" xml:space=\"preserve\">\n    <value>The ModelMetadata property must be set before accessing this property.</value>\n  </data>\n  <data name=\"Common_PropertyNotFound\" xml:space=\"preserve\">\n    <value>The property {0}.{1} could not be found.</value>\n  </data>\n  <data name=\"ModelBinderProviderCollection_InvalidBinderType\" xml:space=\"preserve\">\n    <value>The type '{0}' does not subclass {1} or implement the interface {2}.</value>\n  </data>\n  <data name=\"ValueProviderResult_ConversionThrew\" xml:space=\"preserve\">\n    <value>The parameter conversion from type '{0}' to type '{1}' failed. See the inner exception for more information.</value>\n  </data>\n  <data name=\"ValueProviderResult_NoConverterExists\" xml:space=\"preserve\">\n    <value>The parameter conversion from type '{0}' to type '{1}' failed because no type converter can convert between these types.</value>\n  </data>\n  <data name=\"Common_TypeMustDriveFromType\" xml:space=\"preserve\">\n    <value>The type {0} must derive from {1}.</value>\n  </data>\n  <data name=\"DataAnnotationsModelValidatorProvider_ConstructorRequirements\" xml:space=\"preserve\">\n    <value>The type {0} must have a public constructor which accepts three parameters of types {1}, {2}, and {3}.</value>\n  </data>\n  <data name=\"DataAnnotationsModelValidatorProvider_ValidatableConstructorRequirements\" xml:space=\"preserve\">\n    <value>The type {0} must have a public constructor which accepts two parameters of types {1} and {2}.</value>\n  </data>\n  <data name=\"ValidatableObjectAdapter_IncompatibleType\" xml:space=\"preserve\">\n    <value>The model object inside the metadata claimed to be compatible with {0}, but was actually {1}.</value>\n  </data>\n  <data name=\"HttpResponseExceptionMessage\" xml:space=\"preserve\">\n    <value>Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by the 'Response' property of this exception for details.</value>\n  </data>\n  <data name=\"ApiControllerActionSelector_AmbiguousMatch\" xml:space=\"preserve\">\n    <value>Multiple actions were found that match the request: {0}</value>\n  </data>\n  <data name=\"DefaultControllerFactory_ControllerNameAmbiguous_WithRouteTemplate\" xml:space=\"preserve\">\n    <value>Multiple types were found that match the controller named '{0}'. This can happen if the route that services this request ('{1}') found multiple controllers defined with the same name but differing namespaces, which is not supported.{3}{3}The request for '{0}' has found the following matching controllers:{2}</value>\n  </data>\n  <data name=\"DefaultControllerFactory_ControllerNameNotFound\" xml:space=\"preserve\">\n    <value>No type was found that matches the controller named '{0}'.</value>\n  </data>\n  <data name=\"DefaultControllerFactory_ErrorCreatingController\" xml:space=\"preserve\">\n    <value>An error occurred when trying to create a controller of type '{0}'. Make sure that the controller has a parameterless public constructor.</value>\n  </data>\n  <data name=\"DependencyResolverNoService\" xml:space=\"preserve\">\n    <value>No service registered for type '{0}'.</value>\n  </data>\n  <data name=\"ApiControllerActionSelector_ActionNotFound\" xml:space=\"preserve\">\n    <value>No action was found on the controller '{0}' that matches the request.</value>\n  </data>\n  <data name=\"ApiControllerActionSelector_ActionNameNotFound\" xml:space=\"preserve\">\n    <value>No action was found on the controller '{0}' that matches the name '{1}'.</value>\n  </data>\n  <data name=\"ApiControllerActionSelector_HttpMethodNotSupported\" xml:space=\"preserve\">\n    <value>The requested resource does not support http method '{0}'.</value>\n  </data>\n  <data name=\"ActionSelector_AmbiguousMatchType\" xml:space=\"preserve\">\n    <value>{0} on type {1}</value>\n  </data>\n  <data name=\"ReflectedActionDescriptor_ParameterCannotBeNull\" xml:space=\"preserve\">\n    <value>The parameters dictionary contains a null entry for parameter '{0}' of non-nullable type '{1}' for method '{2}' in '{3}'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.</value>\n  </data>\n  <data name=\"ReflectedActionDescriptor_ParameterNotInDictionary\" xml:space=\"preserve\">\n    <value>The parameters dictionary does not contain an entry for parameter '{0}' of type '{1}' for method '{2}' in '{3}'. The dictionary must contain an entry for each parameter, including parameters that have null values.</value>\n  </data>\n  <data name=\"ReflectedActionDescriptor_ParameterValueHasWrongType\" xml:space=\"preserve\">\n    <value>The parameters dictionary contains an invalid entry for parameter '{0}' for method '{1}' in '{2}'. The dictionary contains a value of type '{3}', but the parameter requires a value of type '{4}'.</value>\n  </data>\n  <data name=\"Route_CannotHaveCatchAllInMultiSegment\" xml:space=\"preserve\">\n    <value>A path segment that contains more than one section, such as a literal section or a parameter, cannot contain a catch-all parameter.</value>\n  </data>\n  <data name=\"Route_CannotHaveConsecutiveParameters\" xml:space=\"preserve\">\n    <value>A path segment cannot contain two consecutive parameters. They must be separated by a '/' or by a literal string.</value>\n  </data>\n  <data name=\"Route_CannotHaveConsecutiveSeparators\" xml:space=\"preserve\">\n    <value>The route template separator character '/' cannot appear consecutively. It must be separated by either a parameter or a literal value.</value>\n  </data>\n  <data name=\"Route_CatchAllMustBeLast\" xml:space=\"preserve\">\n    <value>A catch-all parameter can only appear as the last segment of the route template.</value>\n  </data>\n  <data name=\"Route_InvalidParameterName\" xml:space=\"preserve\">\n    <value>The route parameter name '{0}' is invalid. Route parameter names must be non-empty and cannot contain these characters: \"{{\", \"}}\", \"/\", \"?\"</value>\n  </data>\n  <data name=\"Route_InvalidRouteTemplate\" xml:space=\"preserve\">\n    <value>The route template cannot start with a '/' or '~' character and it cannot contain a '?' character.</value>\n  </data>\n  <data name=\"Route_MismatchedParameter\" xml:space=\"preserve\">\n    <value>There is an incomplete parameter in this path segment: '{0}'. Check that each '{{' character has a matching '}}' character.</value>\n  </data>\n  <data name=\"Route_RepeatedParameter\" xml:space=\"preserve\">\n    <value>The route parameter name '{0}' appears more than one time in the route template.</value>\n  </data>\n  <data name=\"Route_ValidationMustBeStringOrCustomConstraint\" xml:space=\"preserve\">\n    <value>The constraint entry '{0}' on the route with route template '{1}' must have a string value or be of a type which implements '{2}'.</value>\n  </data>\n  <data name=\"Route_AddRemoveWithNoKeyNotSupported\" xml:space=\"preserve\">\n    <value>Adding or removing items from a '{0}' is not supported. Please use a key when adding and removing items.</value>\n  </data>\n  <data name=\"ValueProviderFactory_Cannot_Create\" xml:space=\"preserve\">\n    <value>Could not create a '{0}' from '{1}'. Please ensure it derives from '{0}' and has a public parameterless constructor.</value>\n  </data>\n  <data name=\"Validation_ValueNotFound\" xml:space=\"preserve\">\n    <value>A value is required but was not present in the request.</value>\n  </data>\n  <data name=\"CannotSupportSingletonInstance\" xml:space=\"preserve\">\n    <value>Cannot reuse an '{0}' instance. '{0}' has to be constructed per incoming message. Check your custom '{1}' and make sure that it will not manufacture the same instance.</value>\n  </data>\n  <data name=\"ActionFilterAttribute_MustSupplyResponseOrException\" xml:space=\"preserve\">\n    <value>After calling {0}.OnActionExecuted, the HttpActionExecutedContext properties Result and Exception were both null. At least one of these values must be non-null. To provide a new response, please set the Result object; to indicate an error, please throw an exception.</value>\n  </data>\n  <data name=\"TraceActionInvokeMessage\" xml:space=\"preserve\">\n    <value>Action='{0}'</value>\n  </data>\n  <data name=\"TraceActionFilterMessage\" xml:space=\"preserve\">\n    <value>Action filter for '{0}'</value>\n  </data>\n  <data name=\"TraceActionSelectedMessage\" xml:space=\"preserve\">\n    <value>Selected action '{0}'</value>\n  </data>\n  <data name=\"TraceCancelledMessage\" xml:space=\"preserve\">\n    <value>Cancelled</value>\n  </data>\n  <data name=\"TraceRouteMessage\" xml:space=\"preserve\">\n    <value>Route='{0}'</value>\n  </data>\n  <data name=\"TraceModelStateInvalidMessage\" xml:space=\"preserve\">\n    <value>Model state is invalid. {0}</value>\n  </data>\n  <data name=\"TraceNoneObjectMessage\" xml:space=\"preserve\">\n    <value>none</value>\n  </data>\n  <data name=\"TraceReadFromStreamMessage\" xml:space=\"preserve\">\n    <value>Type='{0}', content-type='{1}'</value>\n  </data>\n  <data name=\"TraceReadFromStreamValueMessage\" xml:space=\"preserve\">\n    <value>Value read='{0}'</value>\n  </data>\n  <data name=\"TraceRequestCompleteMessage\" xml:space=\"preserve\">\n    <value>Content-type='{0}', content-length={1}</value>\n  </data>\n  <data name=\"TraceSelectedFormatter\" xml:space=\"preserve\">\n    <value>Selected formatter='{0}', content-type='{1}'</value>\n  </data>\n  <data name=\"TraceNegotiateFormatter\" xml:space=\"preserve\">\n    <value>Type='{0}', formatters=[{1}]</value>\n  </data>\n  <data name=\"TraceUnknownMessage\" xml:space=\"preserve\">\n    <value>unknown</value>\n  </data>\n  <data name=\"TraceWriteToStreamMessage\" xml:space=\"preserve\">\n    <value>Value='{0}', type='{1}', content-type='{2}'</value>\n  </data>\n  <data name=\"HttpRequestMessageExtensions_NoConfiguration\" xml:space=\"preserve\">\n    <value>The request does not have an associated configuration object or the provided configuration was null.</value>\n  </data>\n  <data name=\"TraceGetPerRequestFormatterEndMessage\" xml:space=\"preserve\">\n    <value>Will use same '{0}' formatter</value>\n  </data>\n  <data name=\"TraceGetPerRequestFormatterMessage\" xml:space=\"preserve\">\n    <value>Obtaining formatter of type '{0}' for type='{1}', mediaType='{2}'</value>\n  </data>\n  <data name=\"RouteCollection_NameNotFound\" xml:space=\"preserve\">\n    <value>A route named '{0}' could not be found in the route collection.</value>\n  </data>\n  <data name=\"ParameterBindingCantHaveMultipleBodyParameters\" xml:space=\"preserve\">\n    <value>Can't bind multiple parameters ('{0}' and '{1}') to the request's content.</value>\n  </data>\n  <data name=\"ParameterBindingConflictingAttributes\" xml:space=\"preserve\">\n    <value>Can't bind parameter '{0}' because it has conflicting attributes on it.</value>\n  </data>\n  <data name=\"ParameterBindingIllegalType\" xml:space=\"preserve\">\n    <value>Can't bind parameter '{1}'. Must specify a custom model binder to bind parameters of type '{0}'.</value>\n  </data>\n  <data name=\"TraceBeginParameterBind\" xml:space=\"preserve\">\n    <value>Binding parameter '{0}'</value>\n  </data>\n  <data name=\"TraceEndParameterBind\" xml:space=\"preserve\">\n    <value>Parameter '{0}' bound to the value '{1}'</value>\n  </data>\n  <data name=\"TraceEndParameterBindNoBind\" xml:space=\"preserve\">\n    <value>Parameter '{0}' failed to bind.</value>\n  </data>\n  <data name=\"TraceInvokingAction\" xml:space=\"preserve\">\n    <value>Invoking action '{0}'</value>\n  </data>\n  <data name=\"TraceActionReturnValue\" xml:space=\"preserve\">\n    <value>Action returned '{0}'</value>\n  </data>\n  <data name=\"TraceModelStateErrorMessage\" xml:space=\"preserve\">\n    <value>{0}: {1}</value>\n  </data>\n  <data name=\"TraceGetPerRequestNullFormatterEndMessage\" xml:space=\"preserve\">\n    <value>Null formatter</value>\n  </data>\n  <data name=\"TraceValidModelState\" xml:space=\"preserve\">\n    <value>Model state is valid. Values: {0}</value>\n  </data>\n  <data name=\"TraceGetPerRequestFormatterEndMessageNew\" xml:space=\"preserve\">\n    <value>Will use new '{0}' formatter</value>\n  </data>\n  <data name=\"JQuerySyntaxMissingClosingBracket\" xml:space=\"preserve\">\n    <value>The key is invalid JQuery syntax because it is missing a closing bracket</value>\n  </data>\n  <data name=\"HttpRequestMessageExtensions_NoContentNegotiator\" xml:space=\"preserve\">\n    <value>The provided configuration does not have an instance of the '{0}' service registered.</value>\n  </data>\n  <data name=\"ReflectedHttpActionDescriptor_CannotCallOpenGenericMethods\" xml:space=\"preserve\">\n    <value>Cannot call action method '{0}' on controller '{1}' because the action method is a generic method.</value>\n  </data>\n  <data name=\"ResponseMessageResultConverter_NullHttpResponseMessage\" xml:space=\"preserve\">\n    <value>A null value was returned where an instance of HttpResponseMessage was expected.</value>\n  </data>\n  <data name=\"ActionExecutor_UnexpectedTaskInstance\" xml:space=\"preserve\">\n    <value>The method '{0}' on type '{1}' returned a Task instance even though it is not an asynchronous method.</value>\n  </data>\n  <data name=\"ActionExecutor_WrappedTaskInstance\" xml:space=\"preserve\">\n    <value>The method '{0}' on type '{1}' returned an instance of '{2}'. Make sure to call Unwrap on the returned value to avoid unobserved faulted Task.</value>\n  </data>\n  <data name=\"HttpActionDescriptor_NoConverterForGenericParamterTypeExists\" xml:space=\"preserve\">\n    <value>No action result converter could be constructed for a generic parameter type '{0}'.</value>\n  </data>\n  <data name=\"MissingRequiredMember\" xml:space=\"preserve\">\n    <value>The {0} property is required.</value>\n  </data>\n  <data name=\"HttpRequestMessageExtensions_NoMatchingFormatter\" xml:space=\"preserve\">\n    <value>Could not find a formatter matching the media type '{0}' that can write an instance of '{1}'.</value>\n  </data>\n  <data name=\"DefaultServices_InvalidServiceType\" xml:space=\"preserve\">\n    <value>The service type {0} is not supported.</value>\n  </data>\n  <data name=\"MaxHttpCollectionKeyLimitReached\" xml:space=\"preserve\">\n    <value>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.</value>\n  </data>\n  <data name=\"ControllerNameNotFound\" xml:space=\"preserve\">\n    <value>No route providing a controller name was found to match request URI '{0}'</value>\n  </data>\n  <data name=\"HttpServerDisposed\" xml:space=\"preserve\">\n    <value>The server is no longer available.</value>\n  </data>\n  <data name=\"NoControllerCreated\" xml:space=\"preserve\">\n    <value>No controller was created to handle this request.</value>\n  </data>\n  <data name=\"NoControllerSelected\" xml:space=\"preserve\">\n    <value>No controller was selected to handle this request.</value>\n  </data>\n  <data name=\"NoRouteData\" xml:space=\"preserve\">\n    <value>No route data was found for this request.</value>\n  </data>\n  <data name=\"RequestNotAuthorized\" xml:space=\"preserve\">\n    <value>Authorization has been denied for this request.</value>\n  </data>\n  <data name=\"ValidModelState\" xml:space=\"preserve\">\n    <value>The model state is valid.</value>\n  </data>\n  <data name=\"ErrorOccurred\" xml:space=\"preserve\">\n    <value>An error has occurred.</value>\n  </data>\n  <data name=\"BadRequest\" xml:space=\"preserve\">\n    <value>The request is invalid.</value>\n  </data>\n  <data name=\"ResourceNotFound\" xml:space=\"preserve\">\n    <value>No HTTP resource was found that matches the request URI '{0}'.</value>\n  </data>\n  <data name=\"OptionalBodyParameterNotSupported\" xml:space=\"preserve\">\n    <value>Optional parameter '{0}' is not supported by '{1}'.</value>\n  </data>\n  <data name=\"MissingDataMemberIsRequired\" xml:space=\"preserve\">\n    <value>Property '{0}' on type '{1}' is invalid. Value-typed properties marked as [Required] must also be marked with [DataMember(IsRequired=true)] to be recognized as required. Consider attributing the declaring type with [DataContract] and the property with [DataMember(IsRequired=true)].</value>\n  </data>\n  <data name=\"ValidationAttributeOnField\" xml:space=\"preserve\">\n    <value>Field '{0}' on type '{1}' is attributed with one or more validation attributes. Validation attributes on fields are not supported. Consider using a public property for validation instead.</value>\n  </data>\n  <data name=\"ValidationAttributeOnNonPublicProperty\" xml:space=\"preserve\">\n    <value>Non-public property '{0}' on type '{1}' is attributed with one or more validation attributes. Validation attributes on non-public properties are not supported. Consider using a public property for validation instead.</value>\n  </data>\n  <data name=\"DependencyResolver_BeginScopeReturnsNull\" xml:space=\"preserve\">\n    <value>A dependency resolver of type '{0}' 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.</value>\n  </data>\n  <data name=\"UnsupportedMediaType\" xml:space=\"preserve\">\n    <value>The request entity's media type '{0}' is not supported for this resource.</value>\n  </data>\n  <data name=\"UnsupportedMediaTypeNoContentType\" xml:space=\"preserve\">\n    <value>The request contains an entity body but no Content-Type header. The inferred media type '{0}' is not supported for this resource.</value>\n  </data>\n  <data name=\"DefaultInlineConstraintResolver_CouldNotFindCtor\" xml:space=\"preserve\">\n    <value>Could not find a constructor for constraint type '{0}' with the following number of parameters: {1}.</value>\n  </data>\n  <data name=\"DefaultInlineConstraintResolver_TypeNotConstraint\" xml:space=\"preserve\">\n    <value>The constraint type '{0}' which is mapped to constraint key '{1}' must implement the IHttpRouteConstraint interface.</value>\n  </data>\n  <data name=\"HttpRouteBuilder_CouldNotResolveConstraint\" xml:space=\"preserve\">\n    <value>The inline constraint resolver of type '{0}' was unable to resolve the following inline constraint: '{1}'.</value>\n  </data>\n  <data name=\"DefaultInlineConstraintResolver_AmbiguousCtors\" xml:space=\"preserve\">\n    <value>The constructor to use for activating the constraint type '{0}' is ambiguous. Multiple constructors were found with the following number of parameters: {1}.</value>\n  </data>\n  <data name=\"AttributeRoutes_InvalidPrefix\" xml:space=\"preserve\">\n    <value>The route prefix '{0}' on the controller named '{1}' cannot end with a '/' character.</value>\n  </data>\n  <data name=\"AttributeRoutes_InvalidTemplate\" xml:space=\"preserve\">\n    <value>The route template '{0}' on the action named '{1}' cannot start with a '/' character.</value>\n  </data>\n  <data name=\"BatchMediaTypeNotSupported\" xml:space=\"preserve\">\n    <value>The batch request of media type '{0}' is not supported.</value>\n  </data>\n  <data name=\"BatchContentTypeMissing\" xml:space=\"preserve\">\n    <value>The batch request must have a \"Content-Type\" header.</value>\n  </data>\n  <data name=\"BatchRequestMissingContent\" xml:space=\"preserve\">\n    <value>The 'Content' property on the batch request cannot be null.</value>\n  </data>\n  <data name=\"ApiControllerActionInvoker_InvalidHttpActionResult\" xml:space=\"preserve\">\n    <value>An object of type '{0}' was returned where an instance of IHttpActionResult was expected.</value>\n  </data>\n  <data name=\"ApiControllerActionInvoker_NullHttpActionResult\" xml:space=\"preserve\">\n    <value>A null value was returned where an instance of IHttpActionResult was expected.</value>\n  </data>\n  <data name=\"ApiController_RequestMustNotBeNull\" xml:space=\"preserve\">\n    <value>ApiController.Request must not be null.</value>\n  </data>\n  <data name=\"HttpControllerContext_ConfigurationMustNotBeNull\" xml:space=\"preserve\">\n    <value>HttpControllerContext.Configuration must not be null.</value>\n  </data>\n  <data name=\"UrlHelper_LinkMustNotReturnNull\" xml:space=\"preserve\">\n    <value>UrlHelper.Link must not return null.</value>\n  </data>\n  <data name=\"RequestIsNull\" xml:space=\"preserve\">\n    <value>The property 'Request' on '{0}' is null. The property must be initialized with a non-null value.</value>\n  </data>\n  <data name=\"Object_NotYetInitialized\" xml:space=\"preserve\">\n    <value>The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup code after all other initialization code.</value>\n  </data>\n  <data name=\"RequestContextConflict\" xml:space=\"preserve\">\n    <value>The request context property on the request must be null or match ApiController.RequestContext.</value>\n  </data>\n  <data name=\"Request_RequestContextMustNotBeNull\" xml:space=\"preserve\">\n    <value>The request must have a request context.</value>\n  </data>\n  <data name=\"TypeInstanceMustNotBeNull\" xml:space=\"preserve\">\n    <value>The {0} instance must not be null.</value>\n  </data>\n  <data name=\"TypePropertyMustNotBeNull\" xml:space=\"preserve\">\n    <value>{0}.{1} must not be null.</value>\n  </data>\n  <data name=\"TypeMethodMustNotReturnNull\" xml:space=\"preserve\">\n    <value>{0}.{1} must not return null.</value>\n  </data>\n  <data name=\"SubRouteCollection_DuplicateRouteName\" xml:space=\"preserve\">\n    <value>A route named '{0}' is already in the route collection. Route names must be unique.\n\nDuplicates:\n{1}\n{2}</value>\n  </data>\n  <data name=\"DirectRoute_MissingActionDescriptors\" xml:space=\"preserve\">\n    <value>The route does not have any associated action descriptors. Routing requires that each direct route map to a non-empty set of actions.</value>\n  </data>\n  <data name=\"RoutePrefix_CannotSupportMultiRoutePrefix\" xml:space=\"preserve\">\n    <value>Only one route prefix attribute is supported. Remove extra attributes from the controller of type '{0}'.</value>\n  </data>\n  <data name=\"RoutePrefix_PrefixCannotBeNull\" xml:space=\"preserve\">\n    <value>The property 'prefix' from route prefix attribute on controller of type '{0}' cannot be null.</value>\n  </data>\n  <data name=\"DirectRoute_AmbiguousController\" xml:space=\"preserve\">\n    <value>Multiple controller types were found that match the URL. This can happen if attribute routes on multiple controllers match the requested URL.{1}{1}The request has found the following matching controller types: {0}</value>\n  </data>\n  <data name=\"DirectRoute_HandlerNotSupported\" xml:space=\"preserve\">\n    <value>Direct routing does not support per-route message handlers.</value>\n  </data>\n  <data name=\"TraceHttpControllerTypeResolverError\" xml:space=\"preserve\">\n    <value>Exception thrown while getting types from '{0}'.</value>\n  </data>\n  <data name=\"DirectRoute_InvalidParameter_Action\" xml:space=\"preserve\">\n    <value>A direct route for an action method cannot use the parameter 'action'. Specify a literal path in place of this parameter to create a route to the action.</value>\n  </data>\n  <data name=\"DirectRoute_InvalidParameter_Controller\" xml:space=\"preserve\">\n    <value>A direct route cannot use the parameter 'controller'. Specify a literal path in place of this parameter to create a route to a controller.</value>\n  </data>\n  <data name=\"CollectionParameterContainsNullElement\" xml:space=\"preserve\">\n    <value>The parameter '{0}' cannot contain a null element.</value>\n  </data>\n  <data name=\"AuthenticationFilterErrorResult\" xml:space=\"preserve\">\n    <value>The authentication filter encountered an error. ErrorResult='{0}'.</value>\n  </data>\n  <data name=\"AuthenticationFilterSetPrincipalToKnownIdentity\" xml:space=\"preserve\">\n    <value>The authentication filter successfully set a principal to a known identity. Identity.Name='{0}'. Identity.AuthenticationType='{1}'.</value>\n  </data>\n  <data name=\"AuthenticationFilterDidNothing\" xml:space=\"preserve\">\n    <value>The authentication filter did not encounter an error or set a principal.</value>\n  </data>\n  <data name=\"AuthenticationFilterSetPrincipalToUnknownIdentity\" xml:space=\"preserve\">\n    <value>The authentication filter set a principal to an unknown identity.</value>\n  </data>\n</root>"
  },
  {
    "path": "src/System.Web.Http/Results/BadRequestErrorMessageResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.Results\n{\n    /// <summary>\n    /// Represents an action result that returns a <see cref=\"HttpStatusCode.BadRequest\"/> response and performs\n    /// content negotiation on an <see cref=\"HttpError\"/> with a <see cref=\"HttpError.Message\"/>.\n    /// </summary>\n    public class BadRequestErrorMessageResult : IHttpActionResult\n    {\n        private readonly string _message;\n        private readonly NegotiatedContentResult<HttpError>.IDependencyProvider _dependencies;\n\n        /// <summary>Initializes a new instance of the <see cref=\"BadRequestErrorMessageResult\"/> class.</summary>\n        /// <param name=\"message\">The user-visible error message.</param>\n        /// <param name=\"contentNegotiator\">The content negotiator to handle content negotiation.</param>\n        /// <param name=\"request\">The request message which led to this result.</param>\n        /// <param name=\"formatters\">The formatters to use to negotiate and format the content.</param>\n        public BadRequestErrorMessageResult(string message, IContentNegotiator contentNegotiator,\n            HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)\n            : this(message, new NegotiatedContentResult<HttpError>.DirectDependencyProvider(contentNegotiator, request,\n                formatters))\n        {\n        }\n\n        /// <summary>Initializes a new instance of the <see cref=\"BadRequestErrorMessageResult\"/> class.</summary>\n        /// <param name=\"message\">The user-visible error message.</param>\n        /// <param name=\"controller\">The controller from which to obtain the dependencies needed for execution.</param>\n        public BadRequestErrorMessageResult(string message, ApiController controller)\n            : this(message, new NegotiatedContentResult<HttpError>.ApiControllerDependencyProvider(controller))\n        {\n        }\n\n        private BadRequestErrorMessageResult(string message,\n            NegotiatedContentResult<HttpError>.IDependencyProvider dependencies)\n        {\n            if (message == null)\n            {\n                throw new ArgumentNullException(\"message\");\n            }\n\n            Contract.Assert(dependencies != null);\n\n            _message = message;\n            _dependencies = dependencies;\n        }\n\n        /// <summary>Gets the user-visible error message.</summary>\n        public string Message\n        {\n            get { return _message; }\n        }\n\n        /// <summary>Gets the content negotiator to handle content negotiation.</summary>\n        public IContentNegotiator ContentNegotiator\n        {\n            get { return _dependencies.ContentNegotiator; }\n        }\n\n        /// <summary>Gets the request message which led to this result.</summary>\n        public HttpRequestMessage Request\n        {\n            get { return _dependencies.Request; }\n        }\n\n        /// <summary>Gets the formatters to use to negotiate and format the content.</summary>\n        public IEnumerable<MediaTypeFormatter> Formatters\n        {\n            get { return _dependencies.Formatters; }\n        }\n\n        /// <inheritdoc />\n        public virtual Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)\n        {\n            return Task.FromResult(Execute());\n        }\n\n        private HttpResponseMessage Execute()\n        {\n            HttpError error = new HttpError(_message);\n            return NegotiatedContentResult<HttpError>.Execute(HttpStatusCode.BadRequest, error,\n                _dependencies.ContentNegotiator, _dependencies.Request, _dependencies.Formatters);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Results/BadRequestResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.Results\n{\n    /// <summary>\n    /// Represents an action result that returns an empty <see cref=\"HttpStatusCode.BadRequest\"/> response.\n    /// </summary>\n    public class BadRequestResult : IHttpActionResult\n    {\n        private readonly StatusCodeResult.IDependencyProvider _dependencies;\n\n        /// <summary>Initializes a new instance of the <see cref=\"BadRequestResult\"/> class.</summary>\n        /// <param name=\"request\">The request message which led to this result.</param>\n        public BadRequestResult(HttpRequestMessage request)\n            : this(new StatusCodeResult.DirectDependencyProvider(request))\n        {\n        }\n\n        /// <summary>Initializes a new instance of the <see cref=\"BadRequestResult\"/> class.</summary>\n        /// <param name=\"controller\">The controller from which to obtain the dependencies needed for execution.</param>\n        public BadRequestResult(ApiController controller)\n            : this(new StatusCodeResult.ApiControllerDependencyProvider(controller))\n        {\n        }\n\n        private BadRequestResult(StatusCodeResult.IDependencyProvider dependencies)\n        {\n            Contract.Assert(dependencies != null);\n\n            _dependencies = dependencies;\n        }\n\n        /// <summary>Gets the request message which led to this result.</summary>\n        public HttpRequestMessage Request\n        {\n            get { return _dependencies.Request; }\n        }\n\n        /// <inheritdoc />\n        public virtual Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)\n        {\n            return Task.FromResult(StatusCodeResult.Execute(HttpStatusCode.BadRequest, _dependencies.Request));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Results/ConflictResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.Results\n{\n    /// <summary>\n    /// Represents an action result that returns an empty <see cref=\"HttpStatusCode.Conflict\"/> response.\n    /// </summary>\n    public class ConflictResult : IHttpActionResult\n    {\n        private readonly StatusCodeResult.IDependencyProvider _dependencies;\n\n        /// <summary>Initializes a new instance of the <see cref=\"ConflictResult\"/> class.</summary>\n        /// <param name=\"request\">The request message which led to this result.</param>\n        public ConflictResult(HttpRequestMessage request)\n            : this(new StatusCodeResult.DirectDependencyProvider(request))\n        {\n        }\n\n        /// <summary>Initializes a new instance of the <see cref=\"ConflictResult\"/> class.</summary>\n        /// <param name=\"controller\">The controller from which to obtain the dependencies needed for execution.</param>\n        public ConflictResult(ApiController controller)\n            : this(new StatusCodeResult.ApiControllerDependencyProvider(controller))\n        {\n        }\n\n        private ConflictResult(StatusCodeResult.IDependencyProvider dependencies)\n        {\n            Contract.Assert(dependencies != null);\n\n            _dependencies = dependencies;\n        }\n\n        /// <summary>Gets the request message which led to this result.</summary>\n        public HttpRequestMessage Request\n        {\n            get { return _dependencies.Request; }\n        }\n\n        /// <inheritdoc />\n        public virtual Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)\n        {\n            return Task.FromResult(StatusCodeResult.Execute(HttpStatusCode.Conflict, _dependencies.Request));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Results/CreatedAtRouteNegotiatedContentResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Routing;\n\nnamespace System.Web.Http.Results\n{\n    /// <summary>\n    /// Represents an action result that performs route generation and content negotiation and returns a\n    /// <see cref=\"HttpStatusCode.Created\"/> response when content negotiation succeeds.\n    /// </summary>\n    /// <typeparam name=\"T\">The type of content in the entity body.</typeparam>\n    public class CreatedAtRouteNegotiatedContentResult<T> : IHttpActionResult\n    {\n        private readonly string _routeName;\n        private readonly IDictionary<string, object> _routeValues;\n        private readonly T _content;\n        private readonly IDependencyProvider _dependencies;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"CreatedAtRouteNegotiatedContentResult{T}\"/> class with the\n        /// values provided.\n        /// </summary>\n        /// <param name=\"routeName\">The name of the route to use for generating the URL.</param>\n        /// <param name=\"routeValues\">The route data to use for generating the URL.</param>\n        /// <param name=\"content\">The content value to negotiate and format in the entity body.</param>\n        /// <param name=\"urlFactory\">The factory to use to generate the route URL.</param>\n        /// <param name=\"contentNegotiator\">The content negotiator to handle content negotiation.</param>\n        /// <param name=\"request\">The request message which led to this result.</param>\n        /// <param name=\"formatters\">The formatters to use to negotiate and format the content.</param>\n        public CreatedAtRouteNegotiatedContentResult(string routeName, IDictionary<string, object> routeValues,\n            T content, UrlHelper urlFactory, IContentNegotiator contentNegotiator, HttpRequestMessage request,\n            IEnumerable<MediaTypeFormatter> formatters)\n            : this(routeName, routeValues, content, new DirectDependencyProvider(urlFactory, contentNegotiator,\n                request, formatters))\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"CreatedAtRouteNegotiatedContentResult{T}\"/> class with the\n        /// values provided.\n        /// </summary>\n        /// <param name=\"routeName\">The name of the route to use for generating the URL.</param>\n        /// <param name=\"routeValues\">The route data to use for generating the URL.</param>\n        /// <param name=\"content\">The content value to negotiate and format in the entity body.</param>\n        /// <param name=\"controller\">The controller from which to obtain the dependencies needed for execution.</param>\n        public CreatedAtRouteNegotiatedContentResult(string routeName, IDictionary<string, object> routeValues,\n            T content, ApiController controller)\n            : this(routeName, routeValues, content, new ApiControllerDependencyProvider(controller))\n        {\n        }\n\n        private CreatedAtRouteNegotiatedContentResult(string routeName, IDictionary<string, object> routeValues,\n            T content, IDependencyProvider dependencies)\n        {\n            if (routeName == null)\n            {\n                throw new ArgumentNullException(\"routeName\");\n            }\n\n            Contract.Assert(dependencies != null);\n\n            _routeName = routeName;\n            _routeValues = routeValues;\n            _content = content;\n            _dependencies = dependencies;\n        }\n\n        /// <summary>Gets the name of the route to use for generating the URL.</summary>\n        public string RouteName\n        {\n            get { return _routeName; }\n        }\n\n        /// <summary>Gets the route data to use for generating the URL.</summary>\n        public IDictionary<string, object> RouteValues\n        {\n            get { return _routeValues; }\n        }\n\n        /// <summary>Gets the content value to negotiate and format in the entity body.</summary>\n        public T Content\n        {\n            get { return _content; }\n        }\n\n        /// <summary>Gets the factory to use to generate the route URL.</summary>\n        public UrlHelper UrlFactory\n        {\n            get { return _dependencies.UrlFactory; }\n        }\n\n        /// <summary>Gets the content negotiator to handle content negotiation.</summary>\n        public IContentNegotiator ContentNegotiator\n        {\n            get { return _dependencies.ContentNegotiator; }\n        }\n\n        /// <summary>Gets the request message which led to this result.</summary>\n        public HttpRequestMessage Request\n        {\n            get { return _dependencies.Request; }\n        }\n\n        /// <summary>Gets the formatters to use to negotiate and format the content.</summary>\n        public IEnumerable<MediaTypeFormatter> Formatters\n        {\n            get { return _dependencies.Formatters; }\n        }\n\n        /// <inheritdoc />\n        public virtual Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)\n        {\n            return Task.FromResult(Execute());\n        }\n\n        private HttpResponseMessage Execute()\n        {\n            // Run content negotiation.\n            ContentNegotiationResult result = _dependencies.ContentNegotiator.Negotiate(typeof(T),\n                _dependencies.Request, _dependencies.Formatters);\n\n            HttpResponseMessage response = new HttpResponseMessage();\n\n            try\n            {\n                if (result == null)\n                {\n                    // A null result from content negotiation indicates that the response should be a 406.\n                    response.StatusCode = HttpStatusCode.NotAcceptable;\n                }\n                else\n                {\n                    response.StatusCode = HttpStatusCode.Created;\n\n                    string link = _dependencies.UrlFactory.Link(_routeName, _routeValues);\n\n                    if (link == null)\n                    {\n                        throw new InvalidOperationException(SRResources.UrlHelper_LinkMustNotReturnNull);\n                    }\n\n                    response.Headers.Location = new Uri(link);\n                    Contract.Assert(result.Formatter != null);\n                    // At this point mediaType should be a cloned value. (The content negotiator is responsible for\n                    // returning a new copy.)\n                    response.Content = new ObjectContent<T>(_content, result.Formatter, result.MediaType);\n                }\n\n                response.RequestMessage = _dependencies.Request;\n            }\n            catch\n            {\n                response.Dispose();\n                throw;\n            }\n\n            return response;\n        }\n\n        /// <summary>Defines a provider for dependencies that are not always directly available.</summary>\n        /// <remarks>\n        /// This abstraction supports the unit testing scenario of creating the result without creating a content\n        /// negotiator, request message, or formatters. (The ApiController provider implementation does lazy evaluation\n        /// to make that scenario work.)\n        /// </remarks>\n        private interface IDependencyProvider\n        {\n            UrlHelper UrlFactory { get; }\n\n            IContentNegotiator ContentNegotiator { get; }\n\n            HttpRequestMessage Request { get; }\n\n            IEnumerable<MediaTypeFormatter> Formatters { get; }\n        }\n\n        private sealed class DirectDependencyProvider : IDependencyProvider\n        {\n            private readonly UrlHelper _urlFactory;\n            private readonly IContentNegotiator _contentNegotiator;\n            private readonly HttpRequestMessage _request;\n            private readonly IEnumerable<MediaTypeFormatter> _formatters;\n\n            public DirectDependencyProvider(UrlHelper urlFactory, IContentNegotiator contentNegotiator,\n                HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)\n            {\n                if (urlFactory == null)\n                {\n                    throw new ArgumentNullException(\"urlFactory\");\n                }\n\n                if (contentNegotiator == null)\n                {\n                    throw new ArgumentNullException(\"contentNegotiator\");\n                }\n\n                if (request == null)\n                {\n                    throw new ArgumentNullException(\"request\");\n                }\n\n                if (formatters == null)\n                {\n                    throw new ArgumentNullException(\"formatters\");\n                }\n\n                _urlFactory = urlFactory;\n                _contentNegotiator = contentNegotiator;\n                _request = request;\n                _formatters = formatters;\n            }\n\n            public UrlHelper UrlFactory\n            {\n                get { return _urlFactory; }\n            }\n\n            public IContentNegotiator ContentNegotiator\n            {\n                get { return _contentNegotiator; }\n            }\n\n            public HttpRequestMessage Request\n            {\n                get { return _request; }\n            }\n\n            public IEnumerable<MediaTypeFormatter> Formatters\n            {\n                get { return _formatters; }\n            }\n        }\n\n        private sealed class ApiControllerDependencyProvider : IDependencyProvider\n        {\n            private readonly ApiController _controller;\n\n            private IDependencyProvider _resolvedDependencies;\n\n            public ApiControllerDependencyProvider(ApiController controller)\n            {\n                if (controller == null)\n                {\n                    throw new ArgumentNullException(\"controller\");\n                }\n\n                _controller = controller;\n            }\n\n            public UrlHelper UrlFactory\n            {\n                get\n                {\n                    EnsureResolved();\n                    return _resolvedDependencies.UrlFactory;\n                }\n            }\n\n            public IContentNegotiator ContentNegotiator\n            {\n                get\n                {\n                    EnsureResolved();\n                    return _resolvedDependencies.ContentNegotiator;\n                }\n            }\n\n            public HttpRequestMessage Request\n            {\n                get\n                {\n                    EnsureResolved();\n                    return _resolvedDependencies.Request;\n                }\n            }\n\n            public IEnumerable<MediaTypeFormatter> Formatters\n            {\n                get\n                {\n                    EnsureResolved();\n                    return _resolvedDependencies.Formatters;\n                }\n            }\n\n            private void EnsureResolved()\n            {\n                if (_resolvedDependencies == null)\n                {\n                    HttpRequestMessage request = _controller.Request;\n\n                    if (request == null)\n                    {\n                        throw new InvalidOperationException(SRResources.ApiController_RequestMustNotBeNull);\n                    }\n\n                    UrlHelper urlFactory = _controller.Url ?? new UrlHelper(request);\n\n                    HttpConfiguration configuration = _controller.Configuration;\n\n                    if (configuration == null)\n                    {\n                        throw new InvalidOperationException(\n                            SRResources.HttpControllerContext_ConfigurationMustNotBeNull);\n                    }\n\n                    ServicesContainer services = configuration.Services;\n                    Contract.Assert(services != null);\n                    IContentNegotiator contentNegotiator = services.GetContentNegotiator();\n\n                    if (contentNegotiator == null)\n                    {\n                        throw new InvalidOperationException(Error.Format(\n                            SRResources.HttpRequestMessageExtensions_NoContentNegotiator, typeof(IContentNegotiator)));\n                    }\n\n                    IEnumerable<MediaTypeFormatter> formatters = configuration.Formatters;\n                    Contract.Assert(formatters != null);\n\n                    _resolvedDependencies = new DirectDependencyProvider(urlFactory, contentNegotiator, request,\n                        formatters);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Results/CreatedNegotiatedContentResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.Results\n{\n    /// <summary>\n    /// Represents an action result that performs content negotiation and returns a\n    /// <see cref=\"HttpStatusCode.Created\"/> response when it succeeds.\n    /// </summary>\n    /// <typeparam name=\"T\">The type of content in the entity body.</typeparam>\n    public class CreatedNegotiatedContentResult<T> : IHttpActionResult\n    {\n        private readonly Uri _location;\n        private readonly T _content;\n        private readonly NegotiatedContentResult<T>.IDependencyProvider _dependencies;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"CreatedNegotiatedContentResult{T}\"/> class with the values\n        /// provided.\n        /// </summary>\n        /// <param name=\"location\">The location at which the content has been created.</param>\n        /// <param name=\"content\">The content value to negotiate and format in the entity body.</param>\n        /// <param name=\"contentNegotiator\">The content negotiator to handle content negotiation.</param>\n        /// <param name=\"request\">The request message which led to this result.</param>\n        /// <param name=\"formatters\">The formatters to use to negotiate and format the content.</param>\n        public CreatedNegotiatedContentResult(Uri location, T content, IContentNegotiator contentNegotiator,\n            HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)\n            : this(location, content, new NegotiatedContentResult<T>.DirectDependencyProvider(contentNegotiator,\n                request, formatters))\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"CreatedNegotiatedContentResult{T}\"/> class with the values\n        /// provided.\n        /// </summary>\n        /// <param name=\"location\">The location at which the content has been created.</param>\n        /// <param name=\"content\">The content value to negotiate and format in the entity body.</param>\n        /// <param name=\"controller\">The controller from which to obtain the dependencies needed for execution.</param>\n        public CreatedNegotiatedContentResult(Uri location, T content, ApiController controller)\n            : this(location, content, new NegotiatedContentResult<T>.ApiControllerDependencyProvider(controller))\n        {\n        }\n\n        private CreatedNegotiatedContentResult(Uri location, T content,\n            NegotiatedContentResult<T>.IDependencyProvider dependencies)\n        {\n            if (location == null)\n            {\n                throw new ArgumentNullException(\"location\");\n            }\n\n            Contract.Assert(dependencies != null);\n\n            _location = location;\n            _content = content;\n            _dependencies = dependencies;\n        }\n\n        /// <summary>Gets the location at which the content has been created.</summary>\n        public Uri Location\n        {\n            get { return _location; }\n        }\n\n        /// <summary>Gets the content value to negotiate and format in the entity body.</summary>\n        public T Content\n        {\n            get { return _content; }\n        }\n\n        /// <summary>Gets the content negotiator to handle content negotiation.</summary>\n        public IContentNegotiator ContentNegotiator\n        {\n            get { return _dependencies.ContentNegotiator; }\n        }\n\n        /// <summary>Gets the request message which led to this result.</summary>\n        public HttpRequestMessage Request\n        {\n            get { return _dependencies.Request; }\n        }\n\n        /// <summary>Gets the formatters to use to negotiate and format the content.</summary>\n        public IEnumerable<MediaTypeFormatter> Formatters\n        {\n            get { return _dependencies.Formatters; }\n        }\n\n        /// <inheritdoc />\n        public virtual Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)\n        {\n            return Task.FromResult(Execute());\n        }\n\n        private HttpResponseMessage Execute()\n        {\n            // Run content negotiation.\n            ContentNegotiationResult result = _dependencies.ContentNegotiator.Negotiate(typeof(T),\n                _dependencies.Request, _dependencies.Formatters);\n\n            HttpResponseMessage response = new HttpResponseMessage();\n\n            try\n            {\n                if (result == null)\n                {\n                    // A null result from content negotiation indicates that the response should be a 406.\n                    response.StatusCode = HttpStatusCode.NotAcceptable;\n                }\n                else\n                {\n                    response.StatusCode = HttpStatusCode.Created;\n                    response.Headers.Location = _location;\n                    Contract.Assert(result.Formatter != null);\n                    // At this point mediaType should be a cloned value. (The content negotiator is responsible for\n                    // returning a new copy.)\n                    response.Content = new ObjectContent<T>(_content, result.Formatter, result.MediaType);\n                }\n\n                response.RequestMessage = _dependencies.Request;\n            }\n            catch\n            {\n                response.Dispose();\n                throw;\n            }\n\n            return response;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Results/ExceptionResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.Results\n{\n    /// <summary>\n    /// Represents an action result that returns a <see cref=\"HttpStatusCode.InternalServerError\"/> response and\n    /// performs content negotiation on an <see cref=\"HttpError\"/> based on an <see cref=\"Exception\"/>.\n    /// </summary>\n    public class ExceptionResult : IHttpActionResult\n    {\n        private readonly Exception _exception;\n        private readonly IDependencyProvider _dependencies;\n\n        /// <summary>Initializes a new instance of the <see cref=\"ExceptionResult\"/> class.</summary>\n        /// <param name=\"exception\">The exception to include in the error.</param>\n        /// <param name=\"includeErrorDetail\">\n        /// <see langword=\"true\"/> if the error should include exception messages; otherwise, <see langword=\"false\"/>.\n        /// </param>\n        /// <param name=\"contentNegotiator\">The content negotiator to handle content negotiation.</param>\n        /// <param name=\"request\">The request message which led to this result.</param>\n        /// <param name=\"formatters\">The formatters to use to negotiate and format the content.</param>\n        public ExceptionResult(Exception exception, bool includeErrorDetail, IContentNegotiator contentNegotiator,\n            HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)\n            : this(exception, new DirectDependencyProvider(includeErrorDetail, contentNegotiator, request,\n                formatters))\n        {\n        }\n\n        /// <summary>Initializes a new instance of the <see cref=\"ExceptionResult\"/> class.</summary>\n        /// <param name=\"exception\">The exception to include in the error.</param>\n        /// <param name=\"controller\">The controller from which to obtain the dependencies needed for execution.</param>\n        public ExceptionResult(Exception exception, ApiController controller)\n            : this(exception, new ApiControllerDependencyProvider(controller))\n        {\n        }\n\n        private ExceptionResult(Exception exception, IDependencyProvider dependencies)\n        {\n            if (exception == null)\n            {\n                throw new ArgumentNullException(\"exception\");\n            }\n\n            Contract.Assert(dependencies != null);\n\n            _exception = exception;\n            _dependencies = dependencies;\n        }\n\n        /// <summary>Gets the exception to include in the error.</summary>\n        public Exception Exception\n        {\n            get { return _exception; }\n        }\n\n        /// <summary>Gets a value indicating whether the error should include exception messages.</summary>\n        public bool IncludeErrorDetail\n        {\n            get { return _dependencies.IncludeErrorDetail; }\n        }\n\n        /// <summary>Gets the content negotiator to handle content negotiation.</summary>\n        public IContentNegotiator ContentNegotiator\n        {\n            get { return _dependencies.ContentNegotiator; }\n        }\n\n        /// <summary>Gets the request message which led to this result.</summary>\n        public HttpRequestMessage Request\n        {\n            get { return _dependencies.Request; }\n        }\n\n        /// <summary>Gets the formatters to use to negotiate and format the content.</summary>\n        public IEnumerable<MediaTypeFormatter> Formatters\n        {\n            get { return _dependencies.Formatters; }\n        }\n\n        /// <inheritdoc />\n        public virtual Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)\n        {\n            return Task.FromResult(Execute());\n        }\n\n        private HttpResponseMessage Execute()\n        {\n            HttpError error = new HttpError(_exception, _dependencies.IncludeErrorDetail);\n            return NegotiatedContentResult<HttpError>.Execute(HttpStatusCode.InternalServerError, error,\n                _dependencies.ContentNegotiator, _dependencies.Request, _dependencies.Formatters);\n        }\n\n        /// <summary>Defines a provider for dependencies that are not always directly available.</summary>\n        /// <remarks>\n        /// This abstraction supports the unit testing scenario of creating the result without creating a content\n        /// negotiator, request message, or formatters. (The ApiController provider implementation does lazy evaluation\n        /// to make that scenario work.)\n        /// </remarks>\n        internal interface IDependencyProvider\n        {\n            bool IncludeErrorDetail { get; }\n\n            IContentNegotiator ContentNegotiator { get; }\n\n            HttpRequestMessage Request { get; }\n\n            IEnumerable<MediaTypeFormatter> Formatters { get; }\n        }\n\n        internal sealed class DirectDependencyProvider : IDependencyProvider\n        {\n            private readonly bool _includeErrorDetail;\n            private readonly IContentNegotiator _contentNegotiator;\n            private readonly HttpRequestMessage _request;\n            private readonly IEnumerable<MediaTypeFormatter> _formatters;\n\n            public DirectDependencyProvider(bool includeErrorDetail, IContentNegotiator contentNegotiator,\n                HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)\n            {\n                if (contentNegotiator == null)\n                {\n                    throw new ArgumentNullException(\"contentNegotiator\");\n                }\n\n                if (request == null)\n                {\n                    throw new ArgumentNullException(\"request\");\n                }\n\n                if (formatters == null)\n                {\n                    throw new ArgumentNullException(\"formatters\");\n                }\n\n                _includeErrorDetail = includeErrorDetail;\n                _contentNegotiator = contentNegotiator;\n                _request = request;\n                _formatters = formatters;\n            }\n\n            public bool IncludeErrorDetail\n            {\n                get { return _includeErrorDetail; }\n            }\n\n            public IContentNegotiator ContentNegotiator\n            {\n                get { return _contentNegotiator; }\n            }\n\n            public HttpRequestMessage Request\n            {\n                get { return _request; }\n            }\n\n            public IEnumerable<MediaTypeFormatter> Formatters\n            {\n                get { return _formatters; }\n            }\n        }\n\n        internal sealed class ApiControllerDependencyProvider : IDependencyProvider\n        {\n            private readonly ApiController _controller;\n\n            private IDependencyProvider _resolvedDependencies;\n\n            public ApiControllerDependencyProvider(ApiController controller)\n            {\n                if (controller == null)\n                {\n                    throw new ArgumentNullException(\"controller\");\n                }\n\n                _controller = controller;\n            }\n\n            public bool IncludeErrorDetail\n            {\n                get\n                {\n                    EnsureResolved();\n                    return _resolvedDependencies.IncludeErrorDetail;\n                }\n            }\n\n            public IContentNegotiator ContentNegotiator\n            {\n                get\n                {\n                    EnsureResolved();\n                    return _resolvedDependencies.ContentNegotiator;\n                }\n            }\n\n            public HttpRequestMessage Request\n            {\n                get\n                {\n                    EnsureResolved();\n                    return _resolvedDependencies.Request;\n                }\n            }\n\n            public IEnumerable<MediaTypeFormatter> Formatters\n            {\n                get\n                {\n                    EnsureResolved();\n                    return _resolvedDependencies.Formatters;\n                }\n            }\n\n            private void EnsureResolved()\n            {\n                if (_resolvedDependencies == null)\n                {\n                    HttpRequestContext requestContext = _controller.RequestContext;\n                    Contract.Assert(requestContext != null);\n                    bool includeErrorDetail = requestContext.IncludeErrorDetail;\n\n                    HttpConfiguration configuration = _controller.Configuration;\n\n                    if (configuration == null)\n                    {\n                        throw new InvalidOperationException(\n                            SRResources.HttpControllerContext_ConfigurationMustNotBeNull);\n                    }\n\n                    ServicesContainer services = configuration.Services;\n                    Contract.Assert(services != null);\n                    IContentNegotiator contentNegotiator = services.GetContentNegotiator();\n\n                    if (contentNegotiator == null)\n                    {\n                        throw new InvalidOperationException(Error.Format(\n                            SRResources.HttpRequestMessageExtensions_NoContentNegotiator, typeof(IContentNegotiator)));\n                    }\n\n                    HttpRequestMessage request = _controller.Request;\n\n                    if (request == null)\n                    {\n                        throw new InvalidOperationException(SRResources.ApiController_RequestMustNotBeNull);\n                    }\n\n                    IEnumerable<MediaTypeFormatter> formatters = configuration.Formatters;\n                    Contract.Assert(formatters != null);\n\n                    _resolvedDependencies = new DirectDependencyProvider(includeErrorDetail, contentNegotiator, request,\n                        formatters);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Results/FormattedContentResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.Results\n{\n    /// <summary>Represents an action result that returns formatted content.</summary>\n    /// <typeparam name=\"T\">The type of content in the entity body.</typeparam>\n    public class FormattedContentResult<T> : IHttpActionResult\n    {\n        private readonly HttpStatusCode _statusCode;\n        private readonly T _content;\n        private readonly MediaTypeFormatter _formatter;\n        private readonly MediaTypeHeaderValue _mediaType;\n        private readonly StatusCodeResult.IDependencyProvider _dependencies;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"FormattedContentResult{T}\"/> class with the values provided.\n        /// </summary>\n        /// <param name=\"statusCode\">The HTTP status code for the response message.</param>\n        /// <param name=\"content\">The content value to format in the entity body.</param>\n        /// <param name=\"formatter\">The formatter to use to format the content.</param>\n        /// <param name=\"mediaType\">\n        /// The value for the Content-Type header, or <see langword=\"null\"/> to have the formatter pick a default\n        /// value.\n        /// </param>\n        /// <param name=\"request\">The request message which led to this result.</param>\n        public FormattedContentResult(HttpStatusCode statusCode, T content, MediaTypeFormatter formatter,\n            MediaTypeHeaderValue mediaType, HttpRequestMessage request)\n            : this(statusCode, content, formatter, mediaType, new StatusCodeResult.DirectDependencyProvider(request))\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"FormattedContentResult{T}\"/> class with the values provided.\n        /// </summary>\n        /// <param name=\"statusCode\">The HTTP status code for the response message.</param>\n        /// <param name=\"content\">The content value to format in the entity body.</param>\n        /// <param name=\"formatter\">The formatter to use to format the content.</param>\n        /// <param name=\"mediaType\">\n        /// The value for the Content-Type header, or <see langword=\"null\"/> to have the formatter pick a default\n        /// value.\n        /// </param>\n        /// <param name=\"controller\">The controller from which to obtain the dependencies needed for execution.</param>\n        public FormattedContentResult(HttpStatusCode statusCode, T content, MediaTypeFormatter formatter,\n            MediaTypeHeaderValue mediaType, ApiController controller)\n            : this(statusCode, content, formatter, mediaType, new StatusCodeResult.ApiControllerDependencyProvider(\n                controller))\n        {\n        }\n\n        private FormattedContentResult(HttpStatusCode statusCode, T content, MediaTypeFormatter formatter,\n            MediaTypeHeaderValue mediaType, StatusCodeResult.IDependencyProvider dependencies)\n        {\n            if (formatter == null)\n            {\n                throw new ArgumentNullException(\"formatter\");\n            }\n\n            Contract.Assert(dependencies != null);\n\n            _statusCode = statusCode;\n            _content = content;\n            _formatter = formatter;\n            _mediaType = mediaType;\n            _dependencies = dependencies;\n        }\n\n        /// <summary>Gets the HTTP status code for the response message.</summary>\n        public HttpStatusCode StatusCode\n        {\n            get { return _statusCode; }\n        }\n\n        /// <summary>Gets the content value to format in the entity body.</summary>\n        public T Content\n        {\n            get { return _content; }\n        }\n\n        /// <summary>Gets the formatter to use to format the content.</summary>\n        public MediaTypeFormatter Formatter\n        {\n            get { return _formatter; }\n        }\n\n        /// <summary>\n        /// Gets the value for the Content-Type header, or <see langword=\"null\"/> to have the formatter pick a default\n        /// value.\n        /// </summary>\n        public MediaTypeHeaderValue MediaType\n        {\n            get { return _mediaType; }\n        }\n\n        /// <summary>Gets the request message which led to this result.</summary>\n        public HttpRequestMessage Request\n        {\n            get { return _dependencies.Request; }\n        }\n\n        /// <inheritdoc />\n        public virtual Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)\n        {\n            return Task.FromResult(Execute());\n        }\n\n        private HttpResponseMessage Execute()\n        {\n            return Execute(_statusCode, _content, _formatter, _mediaType, _dependencies.Request);\n        }\n\n        internal static HttpResponseMessage Execute(HttpStatusCode statusCode, T content, MediaTypeFormatter formatter,\n            MediaTypeHeaderValue mediaType, HttpRequestMessage request)\n        {\n            HttpResponseMessage response = new HttpResponseMessage(statusCode);\n\n            try\n            {\n                response.Content = new ObjectContent<T>(content, formatter, mediaType);\n                response.RequestMessage = request;\n            }\n            catch\n            {\n                response.Dispose();\n                throw;\n            }\n\n            return response;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Results/InternalServerErrorResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.Results\n{\n    /// <summary>\n    /// Represents an action result that returns an empty <see cref=\"HttpStatusCode.InternalServerError\"/> response.\n    /// </summary>\n    public class InternalServerErrorResult : IHttpActionResult\n    {\n        private readonly StatusCodeResult.IDependencyProvider _dependencies;\n\n        /// <summary>Initializes a new instance of the <see cref=\"InternalServerErrorResult\"/> class.</summary>\n        /// <param name=\"request\">The request message which led to this result.</param>\n        public InternalServerErrorResult(HttpRequestMessage request)\n            : this(new StatusCodeResult.DirectDependencyProvider(request))\n        {\n        }\n\n        /// <summary>Initializes a new instance of the <see cref=\"InternalServerErrorResult\"/> class.</summary>\n        /// <param name=\"controller\">The controller from which to obtain the dependencies needed for execution.</param>\n        public InternalServerErrorResult(ApiController controller)\n            : this(new StatusCodeResult.ApiControllerDependencyProvider(controller))\n        {\n        }\n\n        private InternalServerErrorResult(StatusCodeResult.IDependencyProvider dependencies)\n        {\n            Contract.Assert(dependencies != null);\n\n            _dependencies = dependencies;\n        }\n\n        /// <summary>Gets the request message which led to this result.</summary>\n        public HttpRequestMessage Request\n        {\n            get { return _dependencies.Request; }\n        }\n\n        /// <inheritdoc />\n        public virtual Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)\n        {\n            return Task.FromResult(StatusCodeResult.Execute(HttpStatusCode.InternalServerError,\n                _dependencies.Request));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Results/InvalidModelStateResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.ModelBinding;\n\nnamespace System.Web.Http.Results\n{\n    /// <summary>\n    /// Represents an action result that returns a <see cref=\"HttpStatusCode.BadRequest\"/> response and performs\n    /// content negotiation on an <see cref=\"HttpError\"/> based on a <see cref=\"ModelStateDictionary\"/>.\n    /// </summary>\n    public class InvalidModelStateResult : IHttpActionResult\n    {\n        private readonly ModelStateDictionary _modelState;\n        private readonly ExceptionResult.IDependencyProvider _dependencies;\n\n        /// <summary>Initializes a new instance of the <see cref=\"InvalidModelStateResult\"/> class.</summary>\n        /// <param name=\"modelState\">The model state to include in the error.</param>\n        /// <param name=\"includeErrorDetail\">\n        /// <see langword=\"true\"/> if the error should include exception messages; otherwise, <see langword=\"false\"/>.\n        /// </param>\n        /// <param name=\"contentNegotiator\">The content negotiator to handle content negotiation.</param>\n        /// <param name=\"request\">The request message which led to this result.</param>\n        /// <param name=\"formatters\">The formatters to use to negotiate and format the content.</param>\n        public InvalidModelStateResult(ModelStateDictionary modelState, bool includeErrorDetail,\n            IContentNegotiator contentNegotiator, HttpRequestMessage request,\n            IEnumerable<MediaTypeFormatter> formatters)\n            : this(modelState, new ExceptionResult.DirectDependencyProvider(includeErrorDetail, contentNegotiator,\n                request, formatters))\n        {\n        }\n\n        /// <summary>Initializes a new instance of the <see cref=\"InvalidModelStateResult\"/> class.</summary>\n        /// <param name=\"modelState\">The model state to include in the error.</param>\n        /// <param name=\"controller\">The controller from which to obtain the dependencies needed for execution.</param>\n        public InvalidModelStateResult(ModelStateDictionary modelState, ApiController controller)\n            : this(modelState, new ExceptionResult.ApiControllerDependencyProvider(controller))\n        {\n        }\n\n        private InvalidModelStateResult(ModelStateDictionary modelState,\n            ExceptionResult.IDependencyProvider dependencies)\n        {\n            if (modelState == null)\n            {\n                throw new ArgumentNullException(\"modelState\");\n            }\n\n            Contract.Assert(dependencies != null);\n\n            _modelState = modelState;\n            _dependencies = dependencies;\n        }\n\n        /// <summary>Gets the model state to include in the error.</summary>\n        public ModelStateDictionary ModelState\n        {\n            get { return _modelState; }\n        }\n\n        /// <summary>Gets a value indicating whether the error should include exception messages.</summary>\n        public bool IncludeErrorDetail\n        {\n            get { return _dependencies.IncludeErrorDetail; }\n        }\n\n        /// <summary>Gets the content negotiator to handle content negotiation.</summary>\n        public IContentNegotiator ContentNegotiator\n        {\n            get { return _dependencies.ContentNegotiator; }\n        }\n\n        /// <summary>Gets the request message which led to this result.</summary>\n        public HttpRequestMessage Request\n        {\n            get { return _dependencies.Request; }\n        }\n\n        /// <summary>Gets the formatters to use to negotiate and format the content.</summary>\n        public IEnumerable<MediaTypeFormatter> Formatters\n        {\n            get { return _dependencies.Formatters; }\n        }\n\n        /// <inheritdoc />\n        public virtual Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)\n        {\n            return Task.FromResult(Execute());\n        }\n\n        private HttpResponseMessage Execute()\n        {\n            HttpError error = new HttpError(_modelState, _dependencies.IncludeErrorDetail);\n            return NegotiatedContentResult<HttpError>.Execute(HttpStatusCode.BadRequest, error,\n                _dependencies.ContentNegotiator, _dependencies.Request, _dependencies.Formatters);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Results/JsonResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.IO;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Headers;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Newtonsoft.Json;\n\nnamespace System.Web.Http.Results\n{\n    /// <summary>\n    /// Represents an action result that returns an <see cref=\"HttpStatusCode.OK\"/> response with JSON data.\n    /// </summary>\n    /// <typeparam name=\"T\">The type of content in the entity body.</typeparam>\n    public class JsonResult<T> : IHttpActionResult\n    {\n        private readonly T _content;\n        private readonly JsonSerializerSettings _serializerSettings;\n        private readonly Encoding _encoding;\n        private readonly StatusCodeResult.IDependencyProvider _dependencies;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"JsonResult{T}\"/> class with the values provided.\n        /// </summary>\n        /// <param name=\"content\">The content value to serialize in the entity body.</param>\n        /// <param name=\"serializerSettings\">The serializer settings.</param>\n        /// <param name=\"encoding\">The content encoding.</param>\n        /// <param name=\"request\">The request message which led to this result.</param>\n        public JsonResult(T content, JsonSerializerSettings serializerSettings, Encoding encoding,\n            HttpRequestMessage request)\n            : this(content, serializerSettings, encoding, new StatusCodeResult.DirectDependencyProvider(request))\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"JsonResult{T}\"/> class with the values provided.\n        /// </summary>\n        /// <param name=\"content\">The content value to serialize in the entity body.</param>\n        /// <param name=\"serializerSettings\">The serializer settings.</param>\n        /// <param name=\"encoding\">The content encoding.</param>\n        /// <param name=\"controller\">The controller from which to obtain the dependencies needed for execution.</param>\n        public JsonResult(T content, JsonSerializerSettings serializerSettings, Encoding encoding,\n            ApiController controller)\n            : this(content, serializerSettings, encoding, new StatusCodeResult.ApiControllerDependencyProvider(\n                controller))\n        {\n        }\n\n        private JsonResult(T content, JsonSerializerSettings serializerSettings, Encoding encoding,\n            StatusCodeResult.IDependencyProvider dependencies)\n        {\n            if (serializerSettings == null)\n            {\n                throw new ArgumentNullException(\"serializerSettings\");\n            }\n\n            if (encoding == null)\n            {\n                throw new ArgumentNullException(\"encoding\");\n            }\n\n            Contract.Assert(dependencies != null);\n\n            _content = content;\n            _serializerSettings = serializerSettings;\n            _encoding = encoding;\n            _dependencies = dependencies;\n        }\n\n        /// <summary>Gets the content value to serialize in the entity body.</summary>\n        public T Content\n        {\n            get { return _content; }\n        }\n\n        /// <summary>Gets the serializer settings.</summary>\n        public JsonSerializerSettings SerializerSettings\n        {\n            get { return _serializerSettings; }\n        }\n\n        /// <summary>Gets the content encoding.</summary>\n        public Encoding Encoding\n        {\n            get { return _encoding; }\n        }\n\n        /// <summary>Gets the request message which led to this result.</summary>\n        public HttpRequestMessage Request\n        {\n            get { return _dependencies.Request; }\n        }\n\n        /// <inheritdoc />\n        public virtual Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)\n        {\n            return Task.FromResult(Execute());\n        }\n\n        private HttpResponseMessage Execute()\n        {\n            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);\n\n            try\n            {\n                ArraySegment<byte> segment = Serialize();\n                response.Content = new ByteArrayContent(segment.Array, segment.Offset, segment.Count);\n                MediaTypeHeaderValue contentType = new MediaTypeHeaderValue(\"application/json\");\n                contentType.CharSet = _encoding.WebName;\n                response.Content.Headers.ContentType = contentType;\n                response.RequestMessage = _dependencies.Request;\n            }\n            catch\n            {\n                response.Dispose();\n                throw;\n            }\n\n            return response;\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2202:Do not dispose objects multiple times\", Justification =\n            \"False positive; specifying leaveOpen: true and CloseOutput=false prevents this condition.\")]\n        private ArraySegment<byte> Serialize()\n        {\n            JsonSerializer serializer = JsonSerializer.Create(_serializerSettings);\n\n            using (MemoryStream stream = new MemoryStream())\n            {\n                const int DefaultStreamWriterBufferSize = 0x400;\n                using (TextWriter textWriter = new StreamWriter(stream, _encoding,\n                    bufferSize: DefaultStreamWriterBufferSize, leaveOpen: true))\n                {\n                    using (JsonWriter jsonWriter = new JsonTextWriter(textWriter) { CloseOutput = false })\n                    {\n                        serializer.Serialize(jsonWriter, _content);\n                        jsonWriter.Flush();\n                    }\n                }\n\n                Contract.Assert(stream.Length <= Int32.MaxValue);\n                return new ArraySegment<byte>(stream.GetBuffer(), 0, (int)stream.Length);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Results/NegotiatedContentResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.Results\n{\n    /// <summary>Represents an action result that performs content negotiation.</summary>\n    /// <typeparam name=\"T\">The type of content in the entity body.</typeparam>\n    public class NegotiatedContentResult<T> : IHttpActionResult\n    {\n        private readonly HttpStatusCode _statusCode;\n        private readonly T _content;\n        private readonly IDependencyProvider _dependencies;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"NegotiatedContentResult{T}\"/> class with the values provided.\n        /// </summary>\n        /// <param name=\"statusCode\">The HTTP status code for the response message.</param>\n        /// <param name=\"content\">The content value to negotiate and format in the entity body.</param>\n        /// <param name=\"contentNegotiator\">The content negotiator to handle content negotiation.</param>\n        /// <param name=\"request\">The request message which led to this result.</param>\n        /// <param name=\"formatters\">The formatters to use to negotiate and format the content.</param>\n        public NegotiatedContentResult(HttpStatusCode statusCode, T content, IContentNegotiator contentNegotiator,\n            HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)\n            : this(statusCode, content, new DirectDependencyProvider(contentNegotiator, request, formatters))\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"NegotiatedContentResult{T}\"/> class with the values provided.\n        /// </summary>\n        /// <param name=\"statusCode\">The HTTP status code for the response message.</param>\n        /// <param name=\"content\">The content value to negotiate and format in the entity body.</param>\n        /// <param name=\"controller\">The controller from which to obtain the dependencies needed for execution.</param>\n        public NegotiatedContentResult(HttpStatusCode statusCode, T content, ApiController controller)\n            : this(statusCode, content, new ApiControllerDependencyProvider(controller))\n        {\n        }\n\n        private NegotiatedContentResult(HttpStatusCode statusCode, T content, IDependencyProvider dependencies)\n        {\n            Contract.Assert(dependencies != null);\n\n            _statusCode = statusCode;\n            _content = content;\n            _dependencies = dependencies;\n        }\n\n        /// <summary>Gets the HTTP status code for the response message.</summary>\n        public HttpStatusCode StatusCode\n        {\n            get { return _statusCode; }\n        }\n\n        /// <summary>Gets the content value to negotiate and format in the entity body.</summary>\n        public T Content\n        {\n            get { return _content; }\n        }\n\n        /// <summary>Gets the content negotiator to handle content negotiation.</summary>\n        public IContentNegotiator ContentNegotiator\n        {\n            get { return _dependencies.ContentNegotiator; }\n        }\n\n        /// <summary>Gets the request message which led to this result.</summary>\n        public HttpRequestMessage Request\n        {\n            get { return _dependencies.Request; }\n        }\n\n        /// <summary>Gets the formatters to use to negotiate and format the content.</summary>\n        public IEnumerable<MediaTypeFormatter> Formatters\n        {\n            get { return _dependencies.Formatters; }\n        }\n\n        /// <inheritdoc />\n        public virtual Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)\n        {\n            return Task.FromResult(Execute());\n        }\n\n        private HttpResponseMessage Execute()\n        {\n            return Execute(_statusCode, _content, _dependencies.ContentNegotiator, _dependencies.Request,\n                _dependencies.Formatters);\n        }\n\n        internal static HttpResponseMessage Execute(HttpStatusCode statusCode, T content,\n            IContentNegotiator contentNegotiator, HttpRequestMessage request,\n            IEnumerable<MediaTypeFormatter> formatters)\n        {\n            Contract.Assert(contentNegotiator != null);\n            Contract.Assert(request != null);\n            Contract.Assert(formatters != null);\n\n            // Run content negotiation.\n            ContentNegotiationResult result = contentNegotiator.Negotiate(typeof(T), request, formatters);\n\n            HttpResponseMessage response = new HttpResponseMessage();\n\n            try\n            {\n                if (result == null)\n                {\n                    // A null result from content negotiation indicates that the response should be a 406.\n                    response.StatusCode = HttpStatusCode.NotAcceptable;\n                }\n                else\n                {\n                    response.StatusCode = statusCode;\n                    Contract.Assert(result.Formatter != null);\n                    // At this point mediaType should be a cloned value. (The content negotiator is responsible for\n                    // returning a new copy.)\n                    response.Content = new ObjectContent<T>(content, result.Formatter, result.MediaType);\n                }\n\n                response.RequestMessage = request;\n            }\n            catch\n            {\n                response.Dispose();\n                throw;\n            }\n\n            return response;\n        }\n\n        /// <summary>Defines a provider for dependencies that are not always directly available.</summary>\n        /// <remarks>\n        /// This abstraction supports the unit testing scenario of creating the result without creating a content\n        /// negotiator, request message, or formatters. (The ApiController provider implementation does lazy evaluation\n        /// to make that scenario work.)\n        /// </remarks>\n        internal interface IDependencyProvider\n        {\n            IContentNegotiator ContentNegotiator { get; }\n\n            HttpRequestMessage Request { get; }\n\n            IEnumerable<MediaTypeFormatter> Formatters { get; }\n        }\n\n        internal sealed class DirectDependencyProvider : IDependencyProvider\n        {\n            private readonly IContentNegotiator _contentNegotiator;\n            private readonly HttpRequestMessage _request;\n            private readonly IEnumerable<MediaTypeFormatter> _formatters;\n\n            public DirectDependencyProvider(IContentNegotiator contentNegotiator, HttpRequestMessage request,\n                IEnumerable<MediaTypeFormatter> formatters)\n            {\n                if (contentNegotiator == null)\n                {\n                    throw new ArgumentNullException(\"contentNegotiator\");\n                }\n\n                if (request == null)\n                {\n                    throw new ArgumentNullException(\"request\");\n                }\n\n                if (formatters == null)\n                {\n                    throw new ArgumentNullException(\"formatters\");\n                }\n\n                _contentNegotiator = contentNegotiator;\n                _request = request;\n                _formatters = formatters;\n            }\n\n            public IContentNegotiator ContentNegotiator\n            {\n                get { return _contentNegotiator; }\n            }\n\n            public HttpRequestMessage Request\n            {\n                get { return _request; }\n            }\n\n            public IEnumerable<MediaTypeFormatter> Formatters\n            {\n                get { return _formatters; }\n            }\n        }\n\n        internal sealed class ApiControllerDependencyProvider : IDependencyProvider\n        {\n            private readonly ApiController _controller;\n\n            private IDependencyProvider _resolvedDependencies;\n\n            public ApiControllerDependencyProvider(ApiController controller)\n            {\n                if (controller == null)\n                {\n                    throw new ArgumentNullException(\"controller\");\n                }\n\n                _controller = controller;\n            }\n\n            public IContentNegotiator ContentNegotiator\n            {\n                get\n                {\n                    EnsureResolved();\n                    return _resolvedDependencies.ContentNegotiator;\n                }\n            }\n\n            public HttpRequestMessage Request\n            {\n                get\n                {\n                    EnsureResolved();\n                    return _resolvedDependencies.Request;\n                }\n            }\n\n            public IEnumerable<MediaTypeFormatter> Formatters\n            {\n                get\n                {\n                    EnsureResolved();\n                    return _resolvedDependencies.Formatters;\n                }\n            }\n\n            private void EnsureResolved()\n            {\n                if (_resolvedDependencies == null)\n                {\n                    HttpConfiguration configuration = _controller.Configuration;\n\n                    if (configuration == null)\n                    {\n                        throw new InvalidOperationException(\n                            SRResources.HttpControllerContext_ConfigurationMustNotBeNull);\n                    }\n\n                    ServicesContainer services = configuration.Services;\n                    Contract.Assert(services != null);\n                    IContentNegotiator contentNegotiator = services.GetContentNegotiator();\n\n                    if (contentNegotiator == null)\n                    {\n                        throw new InvalidOperationException(Error.Format(\n                            SRResources.HttpRequestMessageExtensions_NoContentNegotiator, typeof(IContentNegotiator)));\n                    }\n\n                    HttpRequestMessage request = _controller.Request;\n\n                    if (request == null)\n                    {\n                        throw new InvalidOperationException(SRResources.ApiController_RequestMustNotBeNull);\n                    }\n\n                    IEnumerable<MediaTypeFormatter> formatters = configuration.Formatters;\n                    Contract.Assert(formatters != null);\n\n                    _resolvedDependencies = new DirectDependencyProvider(contentNegotiator, request, formatters);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Results/NotFoundResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.Results\n{\n    /// <summary>\n    /// Represents an action result that returns an empty <see cref=\"HttpStatusCode.NotFound\"/> response.\n    /// </summary>\n    public class NotFoundResult : IHttpActionResult\n    {\n        private readonly StatusCodeResult.IDependencyProvider _dependencies;\n\n        /// <summary>Initializes a new instance of the <see cref=\"NotFoundResult\"/> class.</summary>\n        /// <param name=\"request\">The request message which led to this result.</param>\n        public NotFoundResult(HttpRequestMessage request)\n            : this(new StatusCodeResult.DirectDependencyProvider(request))\n        {\n        }\n\n        /// <summary>Initializes a new instance of the <see cref=\"NotFoundResult\"/> class.</summary>\n        /// <param name=\"controller\">The controller from which to obtain the dependencies needed for execution.</param>\n        public NotFoundResult(ApiController controller)\n            : this(new StatusCodeResult.ApiControllerDependencyProvider(controller))\n        {\n        }\n\n        private NotFoundResult(StatusCodeResult.IDependencyProvider dependencies)\n        {\n            Contract.Assert(dependencies != null);\n\n            _dependencies = dependencies;\n        }\n\n        /// <summary>Gets the request message which led to this result.</summary>\n        public HttpRequestMessage Request\n        {\n            get { return _dependencies.Request; }\n        }\n\n        /// <inheritdoc />\n        public virtual Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)\n        {\n            return Task.FromResult(StatusCodeResult.Execute(HttpStatusCode.NotFound, _dependencies.Request));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Results/OkNegotiatedContentResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.Results\n{\n    /// <summary>\n    /// Represents an action result that performs content negotiation and returns an <see cref=\"HttpStatusCode.OK\"/>\n    /// response when it succeeds.\n    /// </summary>\n    /// <typeparam name=\"T\">The type of content in the entity body.</typeparam>\n    public class OkNegotiatedContentResult<T> : IHttpActionResult\n    {\n        private readonly T _content;\n        private readonly NegotiatedContentResult<T>.IDependencyProvider _dependencies;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"OkNegotiatedContentResult{T}\"/> class with the values\n        /// provided.\n        /// </summary>\n        /// <param name=\"content\">The content value to negotiate and format in the entity body.</param>\n        /// <param name=\"contentNegotiator\">The content negotiator to handle content negotiation.</param>\n        /// <param name=\"request\">The request message which led to this result.</param>\n        /// <param name=\"formatters\">The formatters to use to negotiate and format the content.</param>\n        public OkNegotiatedContentResult(T content, IContentNegotiator contentNegotiator, HttpRequestMessage request,\n            IEnumerable<MediaTypeFormatter> formatters)\n            : this(content, new NegotiatedContentResult<T>.DirectDependencyProvider(contentNegotiator, request,\n            formatters))\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"OkNegotiatedContentResult{T}\"/> class with the values\n        /// provided.\n        /// </summary>\n        /// <param name=\"content\">The content value to negotiate and format in the entity body.</param>\n        /// <param name=\"controller\">The controller from which to obtain the dependencies needed for execution.</param>\n        public OkNegotiatedContentResult(T content, ApiController controller)\n            : this(content, new NegotiatedContentResult<T>.ApiControllerDependencyProvider(controller))\n        {\n        }\n\n        private OkNegotiatedContentResult(T content, NegotiatedContentResult<T>.IDependencyProvider dependencies)\n        {\n            Contract.Assert(dependencies != null);\n\n            _content = content;\n            _dependencies = dependencies;\n        }\n\n        /// <summary>Gets the content value to negotiate and format in the entity body.</summary>\n        public T Content\n        {\n            get { return _content; }\n        }\n\n        /// <summary>Gets the content negotiator to handle content negotiation.</summary>\n        public IContentNegotiator ContentNegotiator\n        {\n            get { return _dependencies.ContentNegotiator; }\n        }\n\n        /// <summary>Gets the request message which led to this result.</summary>\n        public HttpRequestMessage Request\n        {\n            get { return _dependencies.Request; }\n        }\n\n        /// <summary>Gets the formatters to use to negotiate and format the content.</summary>\n        public IEnumerable<MediaTypeFormatter> Formatters\n        {\n            get { return _dependencies.Formatters; }\n        }\n\n        /// <inheritdoc />\n        public virtual Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)\n        {\n            return Task.FromResult(NegotiatedContentResult<T>.Execute(HttpStatusCode.OK, _content,\n                _dependencies.ContentNegotiator, _dependencies.Request, _dependencies.Formatters));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Results/OkResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.Results\n{\n    /// <summary>Represents an action result that returns an empty <see cref=\"HttpStatusCode.OK\"/> response.</summary>\n    public class OkResult : IHttpActionResult\n    {\n        private readonly StatusCodeResult.IDependencyProvider _dependencies;\n\n        /// <summary>Initializes a new instance of the <see cref=\"OkResult\"/> class.</summary>\n        /// <param name=\"request\">The request message which led to this result.</param>\n        public OkResult(HttpRequestMessage request)\n            : this(new StatusCodeResult.DirectDependencyProvider(request))\n        {\n        }\n\n        /// <summary>Initializes a new instance of the <see cref=\"OkResult\"/> class.</summary>\n        /// <param name=\"controller\">The controller from which to obtain the dependencies needed for execution.</param>\n        public OkResult(ApiController controller)\n            : this(new StatusCodeResult.ApiControllerDependencyProvider(controller))\n        {\n        }\n\n        private OkResult(StatusCodeResult.IDependencyProvider dependencies)\n        {\n            Contract.Assert(dependencies != null);\n\n            _dependencies = dependencies;\n        }\n\n        /// <summary>Gets the request message which led to this result.</summary>\n        public HttpRequestMessage Request\n        {\n            get { return _dependencies.Request; }\n        }\n\n        /// <inheritdoc />\n        public virtual Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)\n        {\n            return Task.FromResult(StatusCodeResult.Execute(HttpStatusCode.OK, _dependencies.Request));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Results/RedirectResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.Results\n{\n    /// <summary>\n    /// Represents an action result for a <see cref=\"HttpStatusCode.Redirect\"/>.\n    /// </summary>\n    public class RedirectResult : IHttpActionResult\n    {\n        private readonly Uri _location;\n        private readonly StatusCodeResult.IDependencyProvider _dependencies;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"RedirectResult\"/> class with the values provided.\n        /// </summary>\n        /// <param name=\"location\">The location to which to redirect.</param>\n        /// <param name=\"request\">The request message which led to this result.</param>\n        public RedirectResult(Uri location, HttpRequestMessage request)\n            : this(location, new StatusCodeResult.DirectDependencyProvider(request))\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"RedirectResult\"/> class with the values provided.\n        /// </summary>\n        /// <param name=\"location\">The location to which to redirect.</param>\n        /// <param name=\"controller\">The controller from which to obtain the dependencies needed for execution.</param>\n        public RedirectResult(Uri location, ApiController controller)\n            : this(location, new StatusCodeResult.ApiControllerDependencyProvider(controller))\n        {\n        }\n\n        private RedirectResult(Uri location, StatusCodeResult.IDependencyProvider dependencies)\n        {\n            if (location == null)\n            {\n                throw new ArgumentNullException(\"location\");\n            }\n\n            Contract.Assert(dependencies != null);\n\n            _location = location;\n            _dependencies = dependencies;\n        }\n\n        /// <summary>Gets the location at which the content has been created.</summary>\n        public Uri Location\n        {\n            get { return _location; }\n        }\n\n        /// <summary>Gets the request message which led to this result.</summary>\n        public HttpRequestMessage Request\n        {\n            get { return _dependencies.Request; }\n        }\n\n        /// <inheritdoc />\n        public virtual Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)\n        {\n            return Task.FromResult(Execute());\n        }\n\n        private HttpResponseMessage Execute()\n        {\n            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Redirect);\n\n            try\n            {\n                response.Headers.Location = _location;\n                response.RequestMessage = _dependencies.Request;\n            }\n            catch\n            {\n                response.Dispose();\n                throw;\n            }\n\n            return response;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Results/RedirectToRouteResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Routing;\n\nnamespace System.Web.Http.Results\n{\n    /// <summary>\n    /// Represents an action result that performs route generation and returns a <see cref=\"HttpStatusCode.Redirect\"/>\n    /// response.\n    /// </summary>\n    public class RedirectToRouteResult : IHttpActionResult\n    {\n        private readonly string _routeName;\n        private readonly IDictionary<string, object> _routeValues;\n        private readonly IDependencyProvider _dependencies;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"RedirectToRouteResult\"/> class with the values provided.\n        /// </summary>\n        /// <param name=\"routeName\">The name of the route to use for generating the URL.</param>\n        /// <param name=\"routeValues\">The route data to use for generating the URL.</param>\n        /// <param name=\"urlFactory\">The factory to use to generate the route URL.</param>\n        /// <param name=\"request\">The request message which led to this result.</param>\n        public RedirectToRouteResult(string routeName, IDictionary<string, object> routeValues, UrlHelper urlFactory,\n            HttpRequestMessage request)\n            : this(routeName, routeValues, new DirectDependencyProvider(urlFactory, request))\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"RedirectToRouteResult\"/> class with the values provided.\n        /// </summary>\n        /// <param name=\"routeName\">The name of the route to use for generating the URL.</param>\n        /// <param name=\"routeValues\">The route data to use for generating the URL.</param>\n        /// <param name=\"controller\">The controller from which to obtain the dependencies needed for execution.</param>\n        public RedirectToRouteResult(string routeName, IDictionary<string, object> routeValues,\n            ApiController controller)\n            : this(routeName, routeValues, new ApiControllerDependencyProvider(controller))\n        {\n        }\n\n        private RedirectToRouteResult(string routeName, IDictionary<string, object> routeValues,\n            IDependencyProvider dependencies)\n        {\n            if (routeName == null)\n            {\n                throw new ArgumentNullException(\"routeName\");\n            }\n\n            Contract.Assert(dependencies != null);\n\n            _routeName = routeName;\n            _routeValues = routeValues;\n            _dependencies = dependencies;\n        }\n\n        /// <summary>Gets the name of the route to use for generating the URL.</summary>\n        public string RouteName\n        {\n            get { return _routeName; }\n        }\n\n        /// <summary>Gets the route data to use for generating the URL.</summary>\n        public IDictionary<string, object> RouteValues\n        {\n            get { return _routeValues; }\n        }\n\n        /// <summary>Gets the factory to use to generate the route URL.</summary>\n        public UrlHelper UrlFactory\n        {\n            get { return _dependencies.UrlFactory; }\n        }\n\n        /// <summary>Gets the request message which led to this result.</summary>\n        public HttpRequestMessage Request\n        {\n            get { return _dependencies.Request; }\n        }\n\n        /// <inheritdoc />\n        public virtual Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)\n        {\n            return Task.FromResult(Execute());\n        }\n\n        private HttpResponseMessage Execute()\n        {\n            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Redirect);\n\n            try\n            {\n                string link = _dependencies.UrlFactory.Link(_routeName, _routeValues);\n\n                if (link == null)\n                {\n                    throw new InvalidOperationException(SRResources.UrlHelper_LinkMustNotReturnNull);\n                }\n\n                response.Headers.Location = new Uri(link);\n                response.RequestMessage = _dependencies.Request;\n            }\n            catch\n            {\n                response.Dispose();\n                throw;\n            }\n\n            return response;\n        }\n\n        /// <summary>Defines a provider for dependencies that are not always directly available.</summary>\n        /// <remarks>\n        /// This abstraction supports the unit testing scenario of creating the result without creating a content\n        /// negotiator, request message, or formatters. (The ApiController provider implementation does lazy evaluation\n        /// to make that scenario work.)\n        /// </remarks>\n        private interface IDependencyProvider\n        {\n            UrlHelper UrlFactory { get; }\n\n            HttpRequestMessage Request { get; }\n        }\n\n        private sealed class DirectDependencyProvider : IDependencyProvider\n        {\n            private readonly UrlHelper _urlFactory;\n            private readonly HttpRequestMessage _request;\n\n            public DirectDependencyProvider(UrlHelper urlFactory, HttpRequestMessage request)\n            {\n                if (urlFactory == null)\n                {\n                    throw new ArgumentNullException(\"urlFactory\");\n                }\n\n                if (request == null)\n                {\n                    throw new ArgumentNullException(\"request\");\n                }\n\n                _urlFactory = urlFactory;\n                _request = request;\n            }\n\n            public UrlHelper UrlFactory\n            {\n                get { return _urlFactory; }\n            }\n\n            public HttpRequestMessage Request\n            {\n                get { return _request; }\n            }\n        }\n\n        private sealed class ApiControllerDependencyProvider : IDependencyProvider\n        {\n            private readonly ApiController _controller;\n\n            private IDependencyProvider _resolvedDependencies;\n\n            public ApiControllerDependencyProvider(ApiController controller)\n            {\n                if (controller == null)\n                {\n                    throw new ArgumentNullException(\"controller\");\n                }\n\n                _controller = controller;\n            }\n\n            public UrlHelper UrlFactory\n            {\n                get\n                {\n                    EnsureResolved();\n                    return _resolvedDependencies.UrlFactory;\n                }\n            }\n\n            public HttpRequestMessage Request\n            {\n                get\n                {\n                    EnsureResolved();\n                    return _resolvedDependencies.Request;\n                }\n            }\n\n            private void EnsureResolved()\n            {\n                if (_resolvedDependencies == null)\n                {\n                    HttpRequestMessage request = _controller.Request;\n\n                    if (request == null)\n                    {\n                        throw new InvalidOperationException(SRResources.ApiController_RequestMustNotBeNull);\n                    }\n\n                    UrlHelper urlFactory = _controller.Url ?? new UrlHelper(request);\n\n                    _resolvedDependencies = new DirectDependencyProvider(urlFactory, request);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Results/ResponseMessageResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.Results\n{\n    /// <summary>Represents an action result that returns a specified response message.</summary>\n    public class ResponseMessageResult : IHttpActionResult\n    {\n        private readonly HttpResponseMessage _response;\n\n        /// <summary>Initializes a new instance of the <see cref=\"ResponseMessageResult\"/> class.</summary>\n        /// <param name=\"response\">The response message.</param>\n        public ResponseMessageResult(HttpResponseMessage response)\n        {\n            if (response == null)\n            {\n                throw new ArgumentNullException(\"response\");\n            }\n\n            _response = response;\n        }\n\n        /// <summary>Gets the response message.</summary>\n        public HttpResponseMessage Response\n        {\n            get { return _response; }\n        }\n\n        /// <inheritdoc />\n        public virtual Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)\n        {\n            return Task.FromResult(_response);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Results/StatusCodeResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.Results\n{\n    /// <summary>Represents an action result that returns a specified HTTP status code.</summary>\n    public class StatusCodeResult : IHttpActionResult\n    {\n        private readonly HttpStatusCode _statusCode;\n        private readonly IDependencyProvider _dependencies;\n\n        /// <summary>Initializes a new instance of the <see cref=\"StatusCodeResult\"/> class.</summary>\n        /// <param name=\"statusCode\">The HTTP status code for the response message.</param>\n        /// <param name=\"request\">The request message which led to this result.</param>\n        public StatusCodeResult(HttpStatusCode statusCode, HttpRequestMessage request)\n            : this(statusCode, new DirectDependencyProvider(request))\n        {\n        }\n\n        /// <summary>Initializes a new instance of the <see cref=\"StatusCodeResult\"/> class.</summary>\n        /// <param name=\"statusCode\">The HTTP status code for the response message.</param>\n        /// <param name=\"controller\">The controller from which to obtain the dependencies needed for execution.</param>\n        public StatusCodeResult(HttpStatusCode statusCode, ApiController controller)\n            : this(statusCode, new ApiControllerDependencyProvider(controller))\n        {\n        }\n\n        private StatusCodeResult(HttpStatusCode statusCode, IDependencyProvider dependencies)\n        {\n            Contract.Assert(dependencies != null);\n\n            _statusCode = statusCode;\n            _dependencies = dependencies;\n        }\n\n        /// <summary>Gets the HTTP status code for the response message.</summary>\n        public HttpStatusCode StatusCode\n        {\n            get { return _statusCode; }\n        }\n\n        /// <summary>Gets the request message which led to this result.</summary>\n        public HttpRequestMessage Request\n        {\n            get { return _dependencies.Request; }\n        }\n\n        /// <inheritdoc />\n        public virtual Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)\n        {\n            return Task.FromResult(Execute());\n        }\n\n        private HttpResponseMessage Execute()\n        {\n            return Execute(_statusCode, _dependencies.Request);\n        }\n\n        internal static HttpResponseMessage Execute(HttpStatusCode statusCode, HttpRequestMessage request)\n        {\n            HttpResponseMessage response = new HttpResponseMessage(statusCode);\n\n            try\n            {\n                response.RequestMessage = request;\n            }\n            catch\n            {\n                response.Dispose();\n                throw;\n            }\n\n            return response;\n        }\n\n        /// <summary>Defines a provider for dependencies that are not always directly available.</summary>\n        /// <remarks>\n        /// This abstraction supports the unit testing scenario of creating the result without creating a request\n        /// message. (The ApiController provider implementation does lazy evaluation to make that scenario work.)\n        /// </remarks>\n        internal interface IDependencyProvider\n        {\n            HttpRequestMessage Request { get; }\n        }\n\n        internal sealed class DirectDependencyProvider : IDependencyProvider\n        {\n            private readonly HttpRequestMessage _request;\n\n            public DirectDependencyProvider(HttpRequestMessage request)\n            {\n                if (request == null)\n                {\n                    throw new ArgumentNullException(\"request\");\n                }\n\n                _request = request;\n            }\n\n            public HttpRequestMessage Request\n            {\n                get { return _request; }\n            }\n        }\n\n        internal sealed class ApiControllerDependencyProvider : IDependencyProvider\n        {\n            private readonly ApiController _controller;\n\n            private HttpRequestMessage _request;\n\n            public ApiControllerDependencyProvider(ApiController controller)\n            {\n                if (controller == null)\n                {\n                    throw new ArgumentNullException(\"controller\");\n                }\n\n                _controller = controller;\n            }\n\n            public HttpRequestMessage Request\n            {\n                get\n                {\n                    EnsureResolved();\n                    return _request;\n                }\n            }\n\n            private void EnsureResolved()\n            {\n                if (_request == null)\n                {\n                    HttpRequestMessage request = _controller.Request;\n\n                    if (request == null)\n                    {\n                        throw new InvalidOperationException(SRResources.ApiController_RequestMustNotBeNull);\n                    }\n\n                    _request = request;\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Results/UnauthorizedResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.Results\n{\n    /// <summary>\n    /// Represents an action result that returns an <see cref=\"HttpStatusCode.Unauthorized\"/> response.\n    /// </summary>\n    public class UnauthorizedResult : IHttpActionResult\n    {\n        private readonly IEnumerable<AuthenticationHeaderValue> _challenges;\n        private readonly StatusCodeResult.IDependencyProvider _dependencies;\n\n        /// <summary>Initializes a new instance of the <see cref=\"StatusCodeResult\"/> class.</summary>\n        /// <param name=\"challenges\">The WWW-Authenticate challenges.</param>\n        /// <param name=\"request\">The request message which led to this result.</param>\n        public UnauthorizedResult(IEnumerable<AuthenticationHeaderValue> challenges, HttpRequestMessage request)\n            : this(challenges, new StatusCodeResult.DirectDependencyProvider(request))\n        {\n        }\n\n        /// <summary>Initializes a new instance of the <see cref=\"StatusCodeResult\"/> class.</summary>\n        /// <param name=\"challenges\">The WWW-Authenticate challenges.</param>\n        /// <param name=\"controller\">The controller from which to obtain the dependencies needed for execution.</param>\n        public UnauthorizedResult(IEnumerable<AuthenticationHeaderValue> challenges, ApiController controller)\n            : this(challenges, new StatusCodeResult.ApiControllerDependencyProvider(controller))\n        {\n        }\n\n        private UnauthorizedResult(IEnumerable<AuthenticationHeaderValue> challenges,\n            StatusCodeResult.IDependencyProvider dependencies)\n        {\n            if (challenges == null)\n            {\n                throw new ArgumentNullException(\"challenges\");\n            }\n\n            Contract.Assert(dependencies != null);\n\n            _challenges = challenges;\n            _dependencies = dependencies;\n        }\n\n        /// <summary>Gets the WWW-Authenticate challenges.</summary>\n        public IEnumerable<AuthenticationHeaderValue> Challenges\n        {\n            get { return _challenges; }\n        }\n\n        /// <summary>Gets the request message which led to this result.</summary>\n        public HttpRequestMessage Request\n        {\n            get { return _dependencies.Request; }\n        }\n\n        /// <inheritdoc />\n        public virtual Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)\n        {\n            return Task.FromResult(Execute());\n        }\n\n        private HttpResponseMessage Execute()\n        {\n            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized);\n\n            try\n            {\n                foreach (AuthenticationHeaderValue challenge in _challenges)\n                {\n                    response.Headers.WwwAuthenticate.Add(challenge);\n                }\n\n                response.RequestMessage = _dependencies.Request;\n            }\n            catch\n            {\n                response.Dispose();\n                throw;\n            }\n\n            return response;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/RouteAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Web.Http.Routing;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Place on a controller or action to expose it directly via a route. \n    /// When placed on a controller, it applies to actions that do not have any <see cref=\"RouteAttribute\"/>s on them.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]\n    public sealed class RouteAttribute : Attribute, IDirectRouteFactory, IHttpRouteInfoProvider\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"RouteAttribute\" /> class.\n        /// </summary>\n        public RouteAttribute()\n        {\n            Template = String.Empty;\n        }\n        \n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"RouteAttribute\" /> class.\n        /// </summary>\n        /// <param name=\"template\">The route template describing the URI pattern to match against.</param>\n        public RouteAttribute(string template)\n        {\n            if (template == null)\n            {\n                throw Error.ArgumentNull(\"template\");\n            }\n            Template = template;\n        }\n\n        /// <inheritdoc />\n        public string Name { get; set; }\n\n        /// <inheritdoc />\n        public int Order { get; set; }\n\n        /// <inheritdoc />\n        public string Template { get; private set; }\n\n        RouteEntry IDirectRouteFactory.CreateRoute(DirectRouteFactoryContext context)\n        {\n            Contract.Assert(context != null);\n\n            IDirectRouteBuilder builder = context.CreateBuilder(Template);\n            Contract.Assert(builder != null);\n\n            builder.Name = Name;\n            builder.Order = Order;\n            return builder.Build();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/RouteParameter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// The <see cref=\"RouteParameter\"/> class can be used to indicate properties about a route parameter (the literals and placeholders \n    /// located within segments of a <see cref=\"M:IHttpRoute.RouteTemplate\"/>). \n    /// It can for example be used to indicate that a route parameter is optional.\n    /// </summary>\n    public sealed class RouteParameter\n    {\n        /// <summary>\n        /// Optional Parameter\n        /// </summary>\n        [SuppressMessage(\"Microsoft.Security\", \"CA2104:DoNotDeclareReadOnlyMutableReferenceTypes\", Justification = \"This type is immutable.\")]\n        public static readonly RouteParameter Optional = new RouteParameter();\n\n        // singleton constructor\n        private RouteParameter()\n        {\n        }\n\n        /// <summary>\n        /// Returns a <see cref=\"System.String\"/> that represents this instance.\n        /// </summary>\n        /// <returns>\n        /// A <see cref=\"System.String\"/> that represents this instance.\n        /// </returns>\n        public override string ToString()\n        {\n            return String.Empty;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/RoutePrefixAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Http.Routing;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Annotates a controller with a route prefix that applies to actions that have any <see cref=\"RouteAttribute\"/>s on them.\n    /// </summary>\n    [SuppressMessage(\"Microsoft.Performance\", \"CA1813:AvoidUnsealedAttributes\", Justification = \"This attribute is intended to be extended by the user.\")]\n    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]\n    public class RoutePrefixAttribute : Attribute, IRoutePrefix\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"RoutePrefixAttribute\" /> class without specifying any parameters.\n        /// </summary>\n        protected RoutePrefixAttribute()\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"RoutePrefixAttribute\" /> class.\n        /// </summary>\n        /// <param name=\"prefix\">The route prefix for the controller.</param>\n        public RoutePrefixAttribute(string prefix)\n        {\n            if (prefix == null)\n            {\n                throw Error.ArgumentNull(\"prefix\");\n            }\n\n            Prefix = prefix;\n        }\n\n        /// <summary>\n        /// Gets the route prefix.\n        /// </summary>\n        public virtual string Prefix { get; private set; }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http/Routing/AttributeRoutingMapper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.Routing\n{\n    /// <remarks>\n    /// Corresponds to the MVC implementation of attribute routing in System.Web.Mvc.Routing.AttributeRoutingMapper.\n    /// </remarks>\n    internal static class AttributeRoutingMapper\n    {\n        // Attribute routing will inject a single top-level route into the route table.\n        private const string AttributeRouteName = \"MS_attributerouteWebApi\";\n\n        public static void MapAttributeRoutes(\n            HttpConfiguration configuration,\n            IInlineConstraintResolver constraintResolver,\n            IDirectRouteProvider directRouteProvider)\n        {\n            if (configuration == null)\n            {\n                throw new ArgumentNullException(\"configuration\");\n            }\n\n            if (constraintResolver == null)\n            {\n                throw new ArgumentNullException(\"constraintResolver\");\n            }\n\n            if (directRouteProvider == null)\n            {\n                throw new ArgumentNullException(\"directRouteProvider\");\n            }\n\n            RouteCollectionRoute aggregateRoute = new RouteCollectionRoute();\n            configuration.Routes.Add(AttributeRouteName, aggregateRoute);\n\n            Action<HttpConfiguration> previousInitializer = configuration.Initializer;\n            configuration.Initializer = config =>\n                {\n                    // Chain to the previous initializer hook. Do this before we access the config since\n                    // initialization may make last minute changes to the configuration.\n                    previousInitializer(config);\n\n                    SubRouteCollection subRoutes = null;\n\n                    // Add a single placeholder route that handles all of attribute routing.\n                    // Add an initialize hook that initializes these routes after the config has been initialized.\n                    Func<SubRouteCollection> initializer = () =>\n                    {\n                        subRoutes = new SubRouteCollection();\n                        AddRouteEntries(subRoutes, configuration, constraintResolver, directRouteProvider);\n                        return subRoutes;\n                    };\n\n                    // This won't change config. It wants to pick up the finalized config.\n                    aggregateRoute.EnsureInitialized(initializer);\n\n                    if (subRoutes != null)\n                    {\n                        AddGenerationHooksForSubRoutes(config.Routes, subRoutes.Entries);\n                    }\n                };\n        }\n\n        // Add generation hooks for the Attribute-routing subroutes.\n        // This lets us generate urls for routes supplied by attr-based routing.\n        private static void AddGenerationHooksForSubRoutes(HttpRouteCollection routeTable,\n            IEnumerable<RouteEntry> entries)\n        {\n            Contract.Assert(entries != null);\n            foreach (RouteEntry entry in entries)\n            {\n                Contract.Assert(entry != null);\n                string name = entry.Name;\n\n                if (name != null)\n                {\n                    IHttpRoute route = entry.Route;\n                    Contract.Assert(route != null);\n                    IHttpRoute linkGenerationRoute = new LinkGenerationRoute(route);\n                    routeTable.Add(name, linkGenerationRoute);\n                }\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Maintainability\", \"CA1506:AvoidExcessiveClassCoupling\",\n            Justification = \"This method is a coordinator, so this coupling is expected. Also fine unless building Debug configuration.\")]\n        private static void AddRouteEntries(\n            SubRouteCollection collector,\n            HttpConfiguration configuration,\n            IInlineConstraintResolver constraintResolver,\n            IDirectRouteProvider directRouteProvider)\n        {\n            Contract.Assert(configuration != null);\n            Contract.Assert(directRouteProvider != null);\n\n            IHttpControllerSelector controllerSelector = configuration.Services.GetHttpControllerSelector();\n            IDictionary<string, HttpControllerDescriptor> controllerMap = controllerSelector.GetControllerMapping();\n            if (controllerMap != null)\n            {\n                foreach (HttpControllerDescriptor controllerDescriptor in controllerMap.Values)\n                {\n                    IHttpActionSelector actionSelector = controllerDescriptor.Configuration.Services.GetActionSelector();\n\n                    ILookup<string, HttpActionDescriptor> actionsByName =\n                        actionSelector.GetActionMapping(controllerDescriptor);\n                    if (actionsByName == null)\n                    {\n                        continue;\n                    }\n\n                    List<HttpActionDescriptor> actions = actionsByName.SelectMany(g => g).ToList();\n                    IReadOnlyCollection<RouteEntry> newEntries =\n                        directRouteProvider.GetDirectRoutes(controllerDescriptor, actions, constraintResolver);\n                    if (newEntries == null)\n                    {\n                        throw Error.InvalidOperation(\n                            SRResources.TypeMethodMustNotReturnNull,\n                            typeof(IDirectRouteProvider).Name, \"GetDirectRoutes\");\n                    }\n\n                    foreach (RouteEntry entry in newEntries)\n                    {\n                        if (entry == null)\n                        {\n                            throw Error.InvalidOperation(\n                                SRResources.TypeMethodMustNotReturnNull,\n                                typeof(IDirectRouteProvider).Name, \"GetDirectRoutes\");\n                        }\n\n                        DirectRouteBuilder.ValidateRouteEntry(entry);\n\n                        // We need to mark each action as only reachable by direct routes so that traditional routes\n                        // don't accidentally hit them.\n                        HttpControllerDescriptor routeControllerDescriptor = entry.Route.GetTargetControllerDescriptor();\n                        if (routeControllerDescriptor == null)\n                        {\n                            HttpActionDescriptor[] actionDescriptors = entry.Route.GetTargetActionDescriptors();\n                            foreach (var actionDescriptor in actionDescriptors)\n                            {\n                                actionDescriptor.SetIsAttributeRouted(true);\n                            }\n                        }\n                        else\n                        {\n                            routeControllerDescriptor.SetIsAttributeRouted(true);\n                        }\n                    }\n\n                    collector.AddRange(newEntries);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Routing/BoundRouteTemplate.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Routing\n{\n    /// <summary>\n    /// Represents a URI generated from a <see cref=\"HttpParsedRoute\"/>. \n    /// </summary>\n    internal class BoundRouteTemplate\n    {\n        public string BoundTemplate { get; set; }\n\n        public HttpRouteValueDictionary Values { get; set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Routing/DefaultDirectRouteProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Diagnostics.Contracts;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.Routing\n{\n    /// <summary>\n    /// A default implementation of <see cref=\"IDirectRouteProvider\"/>.\n    /// </summary>\n    public class DefaultDirectRouteProvider : IDirectRouteProvider\n    {\n        /// <summary>\n        /// Gets direct routes for the given controller descriptor and action descriptors based on \n        /// <see cref=\"IDirectRouteFactory\"/> attributes.\n        /// </summary>\n        /// <param name=\"controllerDescriptor\">The controller descriptor.</param>\n        /// <param name=\"actionDescriptors\">The action descriptors for all actions.</param>\n        /// <param name=\"constraintResolver\">The constraint resolver.</param>\n        /// <returns>A set of route entries.</returns>\n        /// <remarks>\n        /// The implementation returns route entries for the given controller and actions. \n        /// \n        /// Any actions that have associated <see cref=\"IDirectRouteFactory\"/> instances will produce route\n        /// entries that route direct to those actions.\n        /// \n        /// Any actions that do not have an associated <see cref=\"IDirectRouteFactory\"/> instances will be\n        /// associated with the controller. If the controller has any associated <see cref=\"IDirectRouteProvider\"/>\n        /// instances, then route entries will be created for the controller and associated actions.\n        /// </remarks>\n        public virtual IReadOnlyList<RouteEntry> GetDirectRoutes(\n            HttpControllerDescriptor controllerDescriptor, \n            IReadOnlyList<HttpActionDescriptor> actionDescriptors,\n            IInlineConstraintResolver constraintResolver)\n        {\n            List<RouteEntry> entries = new List<RouteEntry>();\n\n            List<HttpActionDescriptor> actionsWithoutRoutes = new List<HttpActionDescriptor>();\n\n            foreach (HttpActionDescriptor action in actionDescriptors)\n            {\n                IReadOnlyList<IDirectRouteFactory> factories = GetActionRouteFactories(action);\n\n                if (factories != null && factories.Count > 0)\n                {\n                    IReadOnlyCollection<RouteEntry> actionEntries = GetActionDirectRoutes(action, factories, constraintResolver);\n                    if (actionEntries != null)\n                    {\n                        entries.AddRange(actionEntries);\n                    }\n                }\n                else\n                {\n                    // IF there are no routes on the specific action, attach it to the controller routes (if any).\n                    actionsWithoutRoutes.Add(action);\n                }\n            }\n\n            if (actionsWithoutRoutes.Count > 0)\n            {\n                IReadOnlyList<IDirectRouteFactory> controllerFactories = GetControllerRouteFactories(controllerDescriptor);\n                if (controllerFactories != null && controllerFactories.Count > 0)\n                {\n                    IReadOnlyCollection<RouteEntry> controllerEntries = GetControllerDirectRoutes(\n                        controllerDescriptor,\n                        actionsWithoutRoutes, \n                        controllerFactories, \n                        constraintResolver);\n\n                    if (controllerEntries != null)\n                    {\n                        entries.AddRange(controllerEntries);\n                    }\n                }\n            }\n\n            return entries;\n        }\n\n        /// <summary>\n        /// Gets route factories for the given controller descriptor.\n        /// </summary>\n        /// <param name=\"controllerDescriptor\">The controller descriptor.</param>\n        /// <returns>A set of route factories.</returns>\n        /// <remarks>\n        /// The implementation returns <see cref=\"IDirectRouteFactory\"/> instances based on attributes on the controller.\n        /// </remarks>\n        protected virtual IReadOnlyList<IDirectRouteFactory> GetControllerRouteFactories(HttpControllerDescriptor controllerDescriptor)\n        {\n            Collection<IDirectRouteFactory> newFactories = controllerDescriptor.GetCustomAttributes<IDirectRouteFactory>(inherit: false);\n\n            Collection<IHttpRouteInfoProvider> oldProviders = controllerDescriptor.GetCustomAttributes<IHttpRouteInfoProvider>(inherit: false);\n\n            List<IDirectRouteFactory> combined = new List<IDirectRouteFactory>();\n            combined.AddRange(newFactories);\n\n            foreach (IHttpRouteInfoProvider oldProvider in oldProviders)\n            {\n                if (oldProvider is IDirectRouteFactory)\n                {\n                    continue;\n                }\n\n                combined.Add(new RouteInfoDirectRouteFactory(oldProvider));\n            }\n\n            return combined;\n        }\n\n        /// <summary>\n        /// Gets a set of route factories for the given action descriptor.\n        /// </summary>\n        /// <param name=\"actionDescriptor\">The action descriptor.</param>\n        /// <returns>A set of route factories.</returns>\n        /// <remarks>\n        /// The implementation returns <see cref=\"IDirectRouteFactory\"/> instances based on attributes on the action. Returns\n        /// null if the action was defined on a base class of this controller.\n        /// </remarks>\n        protected virtual IReadOnlyList<IDirectRouteFactory> GetActionRouteFactories(HttpActionDescriptor actionDescriptor)\n        {\n            // Ignore the Route attributes from inherited actions.\n            ReflectedHttpActionDescriptor reflectedActionDescriptor = actionDescriptor as ReflectedHttpActionDescriptor;\n            if (reflectedActionDescriptor != null &&\n                reflectedActionDescriptor.MethodInfo != null &&\n                reflectedActionDescriptor.MethodInfo.DeclaringType != actionDescriptor.ControllerDescriptor.ControllerType)\n            {\n                return null;\n            }\n\n            Collection<IDirectRouteFactory> newFactories = actionDescriptor.GetCustomAttributes<IDirectRouteFactory>(inherit: false);\n\n            Collection<IHttpRouteInfoProvider> oldProviders = actionDescriptor.GetCustomAttributes<IHttpRouteInfoProvider>(inherit: false);\n\n            List<IDirectRouteFactory> combined = new List<IDirectRouteFactory>();\n            combined.AddRange(newFactories);\n\n            foreach (IHttpRouteInfoProvider oldProvider in oldProviders)\n            {\n                if (oldProvider is IDirectRouteFactory)\n                {\n                    continue;\n                }\n\n                combined.Add(new RouteInfoDirectRouteFactory(oldProvider));\n            }\n\n            return combined;\n        }\n\n        /// <summary>\n        /// Creates <see cref=\"RouteEntry\"/> instances based on the provided factories, controller and actions. The route\n        /// entries provided direct routing to the provided controller and can reach the set of provided actions.\n        /// </summary>\n        /// <param name=\"controllerDescriptor\">The controller descriptor.</param>\n        /// <param name=\"actionDescriptors\">The action descriptors.</param>\n        /// <param name=\"factories\">The direct route factories.</param>\n        /// <param name=\"constraintResolver\">The constraint resolver.</param>\n        /// <returns>A set of route entries.</returns>\n        protected virtual IReadOnlyList<RouteEntry> GetControllerDirectRoutes(\n            HttpControllerDescriptor controllerDescriptor,\n            IReadOnlyList<HttpActionDescriptor> actionDescriptors,\n            IReadOnlyList<IDirectRouteFactory> factories,\n            IInlineConstraintResolver constraintResolver)\n        {\n            return CreateRouteEntries(\n                GetRoutePrefix(controllerDescriptor), \n                factories, \n                actionDescriptors, \n                constraintResolver, \n                targetIsAction: false);\n        }\n\n        /// <summary>\n        /// Creates <see cref=\"RouteEntry\"/> instances based on the provided factories and action. The route entries\n        /// provide direct routing to the provided action.\n        /// </summary>\n        /// <param name=\"actionDescriptor\">The action descriptor.</param>\n        /// <param name=\"factories\">The direct route factories.</param>\n        /// <param name=\"constraintResolver\">The constraint resolver.</param>\n        /// <returns>A set of route entries.</returns>\n        protected virtual IReadOnlyList<RouteEntry> GetActionDirectRoutes(\n            HttpActionDescriptor actionDescriptor, \n            IReadOnlyList<IDirectRouteFactory> factories,\n            IInlineConstraintResolver constraintResolver)\n        {\n            return CreateRouteEntries(\n                GetRoutePrefix(actionDescriptor.ControllerDescriptor), \n                factories, \n                new HttpActionDescriptor[] { actionDescriptor }, \n                constraintResolver, \n                targetIsAction: true);\n        }\n\n        /// <summary>\n        /// Gets the route prefix from the provided controller.\n        /// </summary>\n        /// <param name=\"controllerDescriptor\">The controller descriptor.</param>\n        /// <returns>The route prefix or null.</returns>\n        protected virtual string GetRoutePrefix(HttpControllerDescriptor controllerDescriptor)\n        {\n            Collection<IRoutePrefix> attributes = controllerDescriptor.GetCustomAttributes<IRoutePrefix>(inherit: false);\n\n            if (attributes == null)\n            {\n                return null;\n            }\n\n            if (attributes.Count > 1)\n            {\n                string errorMessage = Error.Format(SRResources.RoutePrefix_CannotSupportMultiRoutePrefix, controllerDescriptor.ControllerType.FullName);\n                throw new InvalidOperationException(errorMessage);\n            }\n\n            if (attributes.Count == 1)\n            {\n                IRoutePrefix attribute = attributes[0];\n\n                if (attribute != null)\n                {\n                    string prefix = attribute.Prefix;\n                    if (prefix == null)\n                    {\n                        string errorMessage = Error.Format(\n                            SRResources.RoutePrefix_PrefixCannotBeNull,\n                            controllerDescriptor.ControllerType.FullName);\n                        throw new InvalidOperationException(errorMessage);\n                    }\n\n                    if (prefix.EndsWith(\"/\", StringComparison.Ordinal))\n                    {\n                        throw Error.InvalidOperation(SRResources.AttributeRoutes_InvalidPrefix, prefix,\n                            controllerDescriptor.ControllerName);\n                    }\n\n                    return prefix;\n                }\n            }\n\n            return null;\n        }\n\n        private static IReadOnlyList<RouteEntry> CreateRouteEntries(\n            string prefix,\n            IReadOnlyCollection<IDirectRouteFactory> factories,\n            IReadOnlyCollection<HttpActionDescriptor> actions, \n            IInlineConstraintResolver constraintResolver, \n            bool targetIsAction)\n        {\n            List<RouteEntry> entries = new List<RouteEntry>();\n            foreach (IDirectRouteFactory factory in factories)\n            {\n                RouteEntry entry = CreateRouteEntry(prefix, factory, actions, constraintResolver, targetIsAction);\n                entries.Add(entry);\n            }\n\n            return entries;\n        }\n\n        private static RouteEntry CreateRouteEntry(\n            string prefix,\n            IDirectRouteFactory factory,\n            IReadOnlyCollection<HttpActionDescriptor> actions,\n            IInlineConstraintResolver constraintResolver,\n            bool targetIsAction)\n        {\n            Contract.Assert(factory != null);\n\n            DirectRouteFactoryContext context = new DirectRouteFactoryContext(prefix, actions, constraintResolver, targetIsAction);\n            RouteEntry entry = factory.CreateRoute(context);\n\n            if (entry == null)\n            {\n                throw Error.InvalidOperation(SRResources.TypeMethodMustNotReturnNull,\n                    typeof(IDirectRouteFactory).Name, \"CreateRoute\");\n            }\n\n            DirectRouteBuilder.ValidateRouteEntry(entry);\n\n            return entry;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Routing/HttpMethodConstraint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Net.Http;\n\nnamespace System.Web.Http.Routing\n{\n    public class HttpMethodConstraint : IHttpRouteConstraint\n    {\n        public HttpMethodConstraint(params HttpMethod[] allowedMethods)\n        {\n            if (allowedMethods == null)\n            {\n                throw Error.ArgumentNull(\"allowedMethods\");\n            }\n\n            AllowedMethods = new Collection<HttpMethod>(allowedMethods);\n        }\n\n        public Collection<HttpMethod> AllowedMethods { get; private set; }\n\n        protected virtual bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            if (route == null)\n            {\n                throw Error.ArgumentNull(\"route\");\n            }\n\n            if (parameterName == null)\n            {\n                throw Error.ArgumentNull(\"parameterName\");\n            }\n\n            if (values == null)\n            {\n                throw Error.ArgumentNull(\"values\");\n            }\n\n            switch (routeDirection)\n            {\n                case HttpRouteDirection.UriResolution:\n                    return AllowedMethods.Contains(request.Method);\n\n                case HttpRouteDirection.UriGeneration:\n                    // We need to see if the user specified the HTTP method explicitly.  Consider these two routes:\n                    //\n                    // a) Route: template = \"/{foo}\", Constraints = { httpMethod = new HttpMethodConstraint(\"GET\") }\n                    // b) Route: template = \"/{foo}\", Constraints = { httpMethod = new HttpMethodConstraint(\"POST\") }\n                    //\n                    // A user might know ahead of time that a URI he/she is generating might be used with a particular HTTP\n                    // method.  If a URI will be used for an HTTP POST but we match on (a) while generating the URI, then\n                    // the HTTP GET-specific route will be used for URI generation, which might have undesired behavior.\n                    // To prevent this, a user might call RouteCollection.GetVirtualPath(..., { httpMethod = \"POST\" }) to\n                    // signal that he is generating a URI that will be used for an HTTP POST, so he wants the URI\n                    // generation to be performed by the (b) route instead of the (a) route, consistent with what would\n                    // happen on incoming requests.\n                    HttpMethod constraint;\n                    if (!values.TryGetValue(parameterName, out constraint))\n                    {\n                        return true;\n                    }\n\n                    return AllowedMethods.Contains(constraint);\n\n                default:\n                    throw Error.InvalidEnumArgument(String.Empty, (int)routeDirection, typeof(HttpRouteDirection));\n            }\n        }\n\n        bool IHttpRouteConstraint.Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)\n        {\n            return Match(request, route, parameterName, values, routeDirection);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Routing/HttpParsedRoute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Linq;\nusing System.Text;\nusing System.Text.RegularExpressions;\n\nnamespace System.Web.Http.Routing\n{\n    internal sealed class HttpParsedRoute\n    {\n        public HttpParsedRoute(List<PathSegment> pathSegments)\n        {\n            Contract.Assert(pathSegments != null);\n            PathSegments = pathSegments;\n        }\n\n        public List<PathSegment> PathSegments { get; private set; }\n\n        [SuppressMessage(\"Microsoft.Maintainability\", \"CA1502:AvoidExcessiveComplexity\", Justification = \"Not changing original algorithm\")]\n        [SuppressMessage(\"Microsoft.Maintainability\", \"CA1505:AvoidUnmaintainableCode\", Justification = \"Not changing original algorithm\")]\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1809:AvoidExcessiveLocals\",\n            Justification = \"Not changing original algorithm. Also fine unless building Debug configuration.\")]\n        public BoundRouteTemplate Bind(IDictionary<string, object> currentValues, IDictionary<string, object> values, HttpRouteValueDictionary defaultValues, HttpRouteValueDictionary constraints)\n        {\n            if (currentValues == null)\n            {\n                currentValues = new HttpRouteValueDictionary();\n            }\n\n            if (values == null)\n            {\n                values = new HttpRouteValueDictionary();\n            }\n\n            if (defaultValues == null)\n            {\n                defaultValues = new HttpRouteValueDictionary();\n            }\n\n            // The set of values we should be using when generating the URI in this route\n            HttpRouteValueDictionary acceptedValues = new HttpRouteValueDictionary();\n\n            // Keep track of which new values have been used\n            HashSet<string> unusedNewValues = new HashSet<string>(values.Keys, StringComparer.OrdinalIgnoreCase);\n\n            // Step 1: Get the list of values we're going to try to use to match and generate this URI\n\n            // Find out which entries in the URI are valid for the URI we want to generate.\n            // If the URI had ordered parameters a=\"1\", b=\"2\", c=\"3\" and the new values\n            // specified that b=\"9\", then we need to invalidate everything after it. The new\n            // values should then be a=\"1\", b=\"9\", c=<no value>.\n            ForEachParameter(PathSegments, delegate(PathParameterSubsegment parameterSubsegment)\n            {\n                // If it's a parameter subsegment, examine the current value to see if it matches the new value\n                string parameterName = parameterSubsegment.ParameterName;\n\n                object newParameterValue;\n                bool hasNewParameterValue = values.TryGetValue(parameterName, out newParameterValue);\n                if (hasNewParameterValue)\n                {\n                    unusedNewValues.Remove(parameterName);\n                }\n\n                object currentParameterValue;\n                bool hasCurrentParameterValue = currentValues.TryGetValue(parameterName, out currentParameterValue);\n\n                if (hasNewParameterValue && hasCurrentParameterValue)\n                {\n                    if (!RoutePartsEqual(currentParameterValue, newParameterValue))\n                    {\n                        // Stop copying current values when we find one that doesn't match\n                        return false;\n                    }\n                }\n\n                // If the parameter is a match, add it to the list of values we will use for URI generation\n                if (hasNewParameterValue)\n                {\n                    if (IsRoutePartNonEmpty(newParameterValue))\n                    {\n                        acceptedValues.Add(parameterName, newParameterValue);\n                    }\n                }\n                else\n                {\n                    if (hasCurrentParameterValue)\n                    {\n                        acceptedValues.Add(parameterName, currentParameterValue);\n                    }\n                }\n                return true;\n            });\n\n            // Add all remaining new values to the list of values we will use for URI generation\n            foreach (var newValue in values)\n            {\n                if (IsRoutePartNonEmpty(newValue.Value))\n                {\n                    if (!acceptedValues.ContainsKey(newValue.Key))\n                    {\n                        acceptedValues.Add(newValue.Key, newValue.Value);\n                    }\n                }\n            }\n\n            // Add all current values that aren't in the URI at all\n            foreach (var currentValue in currentValues)\n            {\n                string parameterName = currentValue.Key;\n                if (!acceptedValues.ContainsKey(parameterName))\n                {\n                    PathParameterSubsegment parameterSubsegment = GetParameterSubsegment(PathSegments, parameterName);\n                    if (parameterSubsegment == null)\n                    {\n                        acceptedValues.Add(parameterName, currentValue.Value);\n                    }\n                }\n            }\n\n            // Add all remaining default values from the route to the list of values we will use for URI generation\n            ForEachParameter(PathSegments, delegate(PathParameterSubsegment parameterSubsegment)\n            {\n                if (!acceptedValues.ContainsKey(parameterSubsegment.ParameterName))\n                {\n                    object defaultValue;\n                    if (!IsParameterRequired(parameterSubsegment, defaultValues, out defaultValue))\n                    {\n                        // Add the default value only if there isn't already a new value for it and\n                        // only if it actually has a default value, which we determine based on whether\n                        // the parameter value is required.\n                        acceptedValues.Add(parameterSubsegment.ParameterName, defaultValue);\n                    }\n                }\n                return true;\n            });\n\n            // All required parameters in this URI must have values from somewhere (i.e. the accepted values)\n            bool hasAllRequiredValues = ForEachParameter(PathSegments, delegate(PathParameterSubsegment parameterSubsegment)\n            {\n                object defaultValue;\n                if (IsParameterRequired(parameterSubsegment, defaultValues, out defaultValue))\n                {\n                    if (!acceptedValues.ContainsKey(parameterSubsegment.ParameterName))\n                    {\n                        // If the route parameter value is required that means there's\n                        // no default value, so if there wasn't a new value for it\n                        // either, this route won't match.\n                        return false;\n                    }\n                }\n                return true;\n            });\n            if (!hasAllRequiredValues)\n            {\n                return null;\n            }\n\n            // All other default values must match if they are explicitly defined in the new values\n            HttpRouteValueDictionary otherDefaultValues = new HttpRouteValueDictionary(defaultValues);\n            ForEachParameter(PathSegments, delegate(PathParameterSubsegment parameterSubsegment)\n            {\n                otherDefaultValues.Remove(parameterSubsegment.ParameterName);\n                return true;\n            });\n\n            foreach (var defaultValue in otherDefaultValues)\n            {\n                object value;\n                if (values.TryGetValue(defaultValue.Key, out value))\n                {\n                    unusedNewValues.Remove(defaultValue.Key);\n                    if (!RoutePartsEqual(value, defaultValue.Value))\n                    {\n                        // If there is a non-parameterized value in the route and there is a\n                        // new value for it and it doesn't match, this route won't match.\n                        return null;\n                    }\n                }\n            }\n\n            // Step 2: If the route is a match generate the appropriate URI\n\n            StringBuilder uri = new StringBuilder();\n            StringBuilder pendingParts = new StringBuilder();\n\n            bool pendingPartsAreAllSafe = false;\n            bool blockAllUriAppends = false;\n\n            for (int i = 0; i < PathSegments.Count; i++)\n            {\n                PathSegment pathSegment = PathSegments[i]; // parsedRouteUriPart\n\n                if (pathSegment is PathSeparatorSegment)\n                {\n                    if (pendingPartsAreAllSafe)\n                    {\n                        // Accept\n                        if (pendingParts.Length > 0)\n                        {\n                            if (blockAllUriAppends)\n                            {\n                                return null;\n                            }\n\n                            // Append any pending literals to the URI\n                            uri.Append(pendingParts.ToString());\n                            pendingParts.Length = 0;\n                        }\n                    }\n                    pendingPartsAreAllSafe = false;\n\n                    // Guard against appending multiple separators for empty segments\n                    if (pendingParts.Length > 0 && pendingParts[pendingParts.Length - 1] == '/')\n                    {\n                        // Dev10 676725: Route should not be matched if that causes mismatched tokens\n                        // Dev11 86819: We will allow empty matches if all subsequent segments are null\n                        if (blockAllUriAppends)\n                        {\n                            return null;\n                        }\n\n                        // Append any pending literals to the URI (without the trailing slash) and prevent any future appends\n                        uri.Append(pendingParts.ToString(0, pendingParts.Length - 1));\n                        pendingParts.Length = 0;\n                        blockAllUriAppends = true;\n                    }\n                    else\n                    {\n                        pendingParts.Append(\"/\");\n                    }\n                }\n                else\n                {\n                    PathContentSegment contentPathSegment = pathSegment as PathContentSegment;\n                    if (contentPathSegment != null)\n                    {\n                        // Segments are treated as all-or-none. We should never output a partial segment.\n                        // If we add any subsegment of this segment to the generated URI, we have to add\n                        // the complete match. For example, if the subsegment is \"{p1}-{p2}.xml\" and we\n                        // used a value for {p1}, we have to output the entire segment up to the next \"/\".\n                        // Otherwise we could end up with the partial segment \"v1\" instead of the entire\n                        // segment \"v1-v2.xml\".\n                        bool addedAnySubsegments = false;\n\n                        for (int j = 0; j < contentPathSegment.Subsegments.Count; j++)\n                        {\n                            PathSubsegment subsegment = contentPathSegment.Subsegments[j];\n                            PathLiteralSubsegment literalSubsegment = subsegment as PathLiteralSubsegment;\n                            if (literalSubsegment != null)\n                            {\n                                // If it's a literal we hold on to it until we are sure we need to add it\n                                pendingPartsAreAllSafe = true;\n                                pendingParts.Append(literalSubsegment.Literal);\n                            }\n                            else\n                            {\n                                PathParameterSubsegment parameterSubsegment = subsegment as PathParameterSubsegment;\n                                if (parameterSubsegment != null)\n                                {\n                                    if (pendingPartsAreAllSafe)\n                                    {\n                                        // Accept\n                                        if (pendingParts.Length > 0)\n                                        {\n                                            if (blockAllUriAppends)\n                                            {\n                                                return null;\n                                            }\n\n                                            // Append any pending literals to the URI\n                                            uri.Append(pendingParts.ToString());\n                                            pendingParts.Length = 0;\n\n                                            addedAnySubsegments = true;\n                                        }\n                                    }\n                                    pendingPartsAreAllSafe = false;\n\n                                    // If it's a parameter, get its value\n                                    object acceptedParameterValue;\n                                    bool hasAcceptedParameterValue = acceptedValues.TryGetValue(parameterSubsegment.ParameterName, out acceptedParameterValue);\n                                    if (hasAcceptedParameterValue)\n                                    {\n                                        unusedNewValues.Remove(parameterSubsegment.ParameterName);\n                                    }\n\n                                    object defaultParameterValue;\n                                    defaultValues.TryGetValue(parameterSubsegment.ParameterName, out defaultParameterValue);\n\n                                    if (RoutePartsEqual(acceptedParameterValue, defaultParameterValue))\n                                    {\n                                        // If the accepted value is the same as the default value, mark it as pending since\n                                        // we won't necessarily add it to the URI we generate.\n                                        pendingParts.Append(Convert.ToString(acceptedParameterValue, CultureInfo.InvariantCulture));\n                                    }\n                                    else\n                                    {\n                                        if (blockAllUriAppends)\n                                        {\n                                            return null;\n                                        }\n\n                                        // Add the new part to the URI as well as any pending parts\n                                        if (pendingParts.Length > 0)\n                                        {\n                                            // Append any pending literals to the URI\n                                            uri.Append(pendingParts.ToString());\n                                            pendingParts.Length = 0;\n                                        }\n                                        uri.Append(Convert.ToString(acceptedParameterValue, CultureInfo.InvariantCulture));\n\n                                        addedAnySubsegments = true;\n                                    }\n                                }\n                                else\n                                {\n                                    Contract.Assert(false, \"Invalid path subsegment type\");\n                                }\n                            }\n                        }\n\n                        if (addedAnySubsegments)\n                        {\n                            // See comment above about why we add the pending parts\n                            if (pendingParts.Length > 0)\n                            {\n                                if (blockAllUriAppends)\n                                {\n                                    return null;\n                                }\n\n                                // Append any pending literals to the URI\n                                uri.Append(pendingParts.ToString());\n                                pendingParts.Length = 0;\n                            }\n                        }\n                    }\n                    else\n                    {\n                        Contract.Assert(false, \"Invalid path segment type\");\n                    }\n                }\n            }\n\n            if (pendingPartsAreAllSafe)\n            {\n                // Accept\n                if (pendingParts.Length > 0)\n                {\n                    if (blockAllUriAppends)\n                    {\n                        return null;\n                    }\n\n                    // Append any pending literals to the URI\n                    uri.Append(pendingParts.ToString());\n                }\n            }\n\n            // Process constraints keys\n            if (constraints != null)\n            {\n                // If there are any constraints, mark all the keys as being used so that we don't\n                // generate query string items for custom constraints that don't appear as parameters\n                // in the URI format.\n                foreach (var constraintsItem in constraints)\n                {\n                    unusedNewValues.Remove(constraintsItem.Key);\n                }\n            }\n\n            // Encode the URI before we append the query string, otherwise we would double encode the query string\n            StringBuilder encodedUri = new StringBuilder();\n            encodedUri.Append(UriEncode(uri.ToString()));\n            uri = encodedUri;\n\n            // Add remaining new values as query string parameters to the URI\n            if (unusedNewValues.Count > 0)\n            {\n                // Generate the query string\n                bool firstParam = true;\n                foreach (string unusedNewValue in unusedNewValues)\n                {\n                    object value;\n                    if (acceptedValues.TryGetValue(unusedNewValue, out value))\n                    {\n                        uri.Append(firstParam ? '?' : '&');\n                        firstParam = false;\n                        uri.Append(Uri.EscapeDataString(unusedNewValue));\n                        uri.Append('=');\n                        uri.Append(Uri.EscapeDataString(Convert.ToString(value, CultureInfo.InvariantCulture)));\n                    }\n                }\n            }\n\n            return new BoundRouteTemplate\n            {\n                BoundTemplate = uri.ToString(),\n                Values = acceptedValues\n            };\n        }\n\n        private static string EscapeReservedCharacters(Match m)\n        {\n            return Uri.HexEscape(m.Value[0]);\n        }\n\n        private static bool ForEachParameter(List<PathSegment> pathSegments, Func<PathParameterSubsegment, bool> action)\n        {\n            for (int i = 0; i < pathSegments.Count; i++)\n            {\n                PathSegment pathSegment = pathSegments[i];\n\n                if (pathSegment is PathSeparatorSegment)\n                {\n                    // We only care about parameter subsegments, so skip this\n                    continue;\n                }\n                else\n                {\n                    PathContentSegment contentPathSegment = pathSegment as PathContentSegment;\n                    if (contentPathSegment != null)\n                    {\n                        for (int j = 0; j < contentPathSegment.Subsegments.Count; j++)\n                        {\n                            PathSubsegment subsegment = contentPathSegment.Subsegments[j];\n                            PathLiteralSubsegment literalSubsegment = subsegment as PathLiteralSubsegment;\n                            if (literalSubsegment != null)\n                            {\n                                // We only care about parameter subsegments, so skip this\n                                continue;\n                            }\n                            else\n                            {\n                                PathParameterSubsegment parameterSubsegment = subsegment as PathParameterSubsegment;\n                                if (parameterSubsegment != null)\n                                {\n                                    if (!action(parameterSubsegment))\n                                    {\n                                        return false;\n                                    }\n                                }\n                                else\n                                {\n                                    Contract.Assert(false, \"Invalid path subsegment type\");\n                                }\n                            }\n                        }\n                    }\n                    else\n                    {\n                        Contract.Assert(false, \"Invalid path segment type\");\n                    }\n                }\n            }\n\n            return true;\n        }\n\n        private static PathParameterSubsegment GetParameterSubsegment(List<PathSegment> pathSegments, string parameterName)\n        {\n            PathParameterSubsegment foundParameterSubsegment = null;\n\n            ForEachParameter(pathSegments, delegate(PathParameterSubsegment parameterSubsegment)\n            {\n                if (String.Equals(parameterName, parameterSubsegment.ParameterName, StringComparison.OrdinalIgnoreCase))\n                {\n                    foundParameterSubsegment = parameterSubsegment;\n                    return false;\n                }\n                else\n                {\n                    return true;\n                }\n            });\n\n            return foundParameterSubsegment;\n        }\n\n        private static bool IsParameterRequired(PathParameterSubsegment parameterSubsegment, HttpRouteValueDictionary defaultValues, out object defaultValue)\n        {\n            if (parameterSubsegment.IsCatchAll)\n            {\n                defaultValue = null;\n                return false;\n            }\n\n            return !defaultValues.TryGetValue(parameterSubsegment.ParameterName, out defaultValue);\n        }\n\n        private static bool IsRoutePartNonEmpty(object routePart)\n        {\n            string routePartString = routePart as string;\n            if (routePartString != null)\n            {\n                return routePartString.Length > 0;\n            }\n            return routePart != null;\n        }\n\n        public HttpRouteValueDictionary Match(RoutingContext context, HttpRouteValueDictionary defaultValues)\n        {\n            List<string> requestPathSegments = context.PathSegments;\n\n            if (defaultValues == null)\n            {\n                defaultValues = new HttpRouteValueDictionary();\n            }\n\n            HttpRouteValueDictionary matchedValues = new HttpRouteValueDictionary();\n\n            // This flag gets set once all the data in the URI has been parsed through, but\n            // the route we're trying to match against still has more parts. At this point\n            // we'll only continue matching separator characters and parameters that have\n            // default values.\n            bool ranOutOfStuffToParse = false;\n\n            // This value gets set once we start processing a catchall parameter (if there is one\n            // at all). Once we set this value we consume all remaining parts of the URI into its\n            // parameter value.\n            bool usedCatchAllParameter = false;\n\n            for (int i = 0; i < PathSegments.Count; i++)\n            {\n                PathSegment pathSegment = PathSegments[i];\n\n                if (requestPathSegments.Count <= i)\n                {\n                    ranOutOfStuffToParse = true;\n                }\n\n                string requestPathSegment = ranOutOfStuffToParse ? null : requestPathSegments[i];\n\n                if (pathSegment is PathSeparatorSegment)\n                {\n                    if (ranOutOfStuffToParse)\n                    {\n                        // If we're trying to match a separator in the route but there's no more content, that's OK\n                    }\n                    else\n                    {\n                        if (!String.Equals(requestPathSegment, \"/\", StringComparison.Ordinal))\n                        {\n                            return null;\n                        }\n                    }\n                }\n                else\n                {\n                    PathContentSegment contentPathSegment = pathSegment as PathContentSegment;\n                    if (contentPathSegment != null)\n                    {\n                        if (contentPathSegment.IsCatchAll)\n                        {\n                            Contract.Assert(i == (PathSegments.Count - 1), \"If we're processing a catch-all, we should be on the last route segment.\");\n                            MatchCatchAll(contentPathSegment, requestPathSegments.Skip(i), defaultValues, matchedValues);\n                            usedCatchAllParameter = true;\n                        }\n                        else\n                        {\n                            if (!MatchContentPathSegment(contentPathSegment, requestPathSegment, defaultValues, matchedValues))\n                            {\n                                return null;\n                            }\n                        }\n                    }\n                    else\n                    {\n                        Contract.Assert(false, \"Invalid path segment type\");\n                    }\n                }\n            }\n\n            if (!usedCatchAllParameter)\n            {\n                if (PathSegments.Count < requestPathSegments.Count)\n                {\n                    // If we've already gone through all the parts defined in the route but the URI\n                    // still contains more content, check that the remaining content is all separators.\n                    for (int i = PathSegments.Count; i < requestPathSegments.Count; i++)\n                    {\n                        if (!RouteParser.IsSeparator(requestPathSegments[i]))\n                        {\n                            return null;\n                        }\n                    }\n                }\n            }\n\n            // Copy all remaining default values to the route data\n            if (defaultValues != null)\n            {\n                foreach (var defaultValue in defaultValues)\n                {\n                    if (!matchedValues.ContainsKey(defaultValue.Key))\n                    {\n                        matchedValues.Add(defaultValue.Key, defaultValue.Value);\n                    }\n                }\n            }\n\n            return matchedValues;\n        }\n\n        private static void MatchCatchAll(PathContentSegment contentPathSegment, IEnumerable<string> remainingRequestSegments, HttpRouteValueDictionary defaultValues, HttpRouteValueDictionary matchedValues)\n        {\n            string remainingRequest = String.Join(String.Empty, remainingRequestSegments.ToArray());\n\n            PathParameterSubsegment catchAllSegment = contentPathSegment.Subsegments[0] as PathParameterSubsegment;\n\n            object catchAllValue;\n\n            if (remainingRequest.Length > 0)\n            {\n                catchAllValue = remainingRequest;\n            }\n            else\n            {\n                defaultValues.TryGetValue(catchAllSegment.ParameterName, out catchAllValue);\n            }\n\n            matchedValues.Add(catchAllSegment.ParameterName, catchAllValue);\n        }\n\n        private static bool MatchContentPathSegment(PathContentSegment routeSegment, string requestPathSegment, HttpRouteValueDictionary defaultValues, HttpRouteValueDictionary matchedValues)\n        {\n            if (String.IsNullOrEmpty(requestPathSegment))\n            {\n                // If there's no data to parse, we must have exactly one parameter segment and no other segments - otherwise no match\n\n                if (routeSegment.Subsegments.Count > 1)\n                {\n                    return false;\n                }\n\n                PathParameterSubsegment parameterSubsegment = routeSegment.Subsegments[0] as PathParameterSubsegment;\n                if (parameterSubsegment == null)\n                {\n                    return false;\n                }\n\n                // We must have a default value since there's no value in the request URI\n                object parameterValue;\n                if (defaultValues.TryGetValue(parameterSubsegment.ParameterName, out parameterValue))\n                {\n                    // If there's a default value for this parameter, use that default value\n                    matchedValues.Add(parameterSubsegment.ParameterName, parameterValue);\n                    return true;\n                }\n                else\n                {\n                    // If there's no default value, this segment doesn't match\n                    return false;\n                }\n            }\n\n            // Optimize for the common case where there is only one subsegment in the segment - either a parameter or a literal\n            if (routeSegment.Subsegments.Count == 1)\n            {\n                return MatchSingleContentPathSegment(routeSegment.Subsegments[0], requestPathSegment, matchedValues);\n            }\n\n            // Find last literal segment and get its last index in the string\n\n            int lastIndex = requestPathSegment.Length;\n            int indexOfLastSegmentUsed = routeSegment.Subsegments.Count - 1;\n\n            PathParameterSubsegment parameterNeedsValue = null; // Keeps track of a parameter segment that is pending a value\n            PathLiteralSubsegment lastLiteral = null; // Keeps track of the left-most literal we've encountered\n\n            while (indexOfLastSegmentUsed >= 0)\n            {\n                int newLastIndex = lastIndex;\n\n                PathParameterSubsegment parameterSubsegment = routeSegment.Subsegments[indexOfLastSegmentUsed] as PathParameterSubsegment;\n                if (parameterSubsegment != null)\n                {\n                    // Hold on to the parameter so that we can fill it in when we locate the next literal\n                    parameterNeedsValue = parameterSubsegment;\n                }\n                else\n                {\n                    PathLiteralSubsegment literalSubsegment = routeSegment.Subsegments[indexOfLastSegmentUsed] as PathLiteralSubsegment;\n                    if (literalSubsegment != null)\n                    {\n                        lastLiteral = literalSubsegment;\n\n                        int startIndex = lastIndex - 1;\n                        // If we have a pending parameter subsegment, we must leave at least one character for that\n                        if (parameterNeedsValue != null)\n                        {\n                            startIndex--;\n                        }\n\n                        if (startIndex < 0)\n                        {\n                            return false;\n                        }\n\n                        int indexOfLiteral = requestPathSegment.LastIndexOf(literalSubsegment.Literal, startIndex, StringComparison.OrdinalIgnoreCase);\n                        if (indexOfLiteral == -1)\n                        {\n                            // If we couldn't find this literal index, this segment cannot match\n                            return false;\n                        }\n\n                        // If the first subsegment is a literal, it must match at the right-most extent of the request URI.\n                        // Without this check if your route had \"/Foo/\" we'd match the request URI \"/somethingFoo/\".\n                        // This check is related to the check we do at the very end of this function.\n                        if (indexOfLastSegmentUsed == (routeSegment.Subsegments.Count - 1))\n                        {\n                            if ((indexOfLiteral + literalSubsegment.Literal.Length) != requestPathSegment.Length)\n                            {\n                                return false;\n                            }\n                        }\n\n                        newLastIndex = indexOfLiteral;\n                    }\n                    else\n                    {\n                        Contract.Assert(false, \"Invalid path segment type\");\n                    }\n                }\n\n                if ((parameterNeedsValue != null) && (((lastLiteral != null) && (parameterSubsegment == null)) || (indexOfLastSegmentUsed == 0)))\n                {\n                    // If we have a pending parameter that needs a value, grab that value\n\n                    int parameterStartIndex;\n                    int parameterTextLength;\n\n                    if (lastLiteral == null)\n                    {\n                        if (indexOfLastSegmentUsed == 0)\n                        {\n                            parameterStartIndex = 0;\n                        }\n                        else\n                        {\n                            parameterStartIndex = newLastIndex;\n                            Contract.Assert(false, \"indexOfLastSegementUsed should always be 0 from the check above\");\n                        }\n                        parameterTextLength = lastIndex;\n                    }\n                    else\n                    {\n                        // If we're getting a value for a parameter that is somewhere in the middle of the segment\n                        if ((indexOfLastSegmentUsed == 0) && (parameterSubsegment != null))\n                        {\n                            parameterStartIndex = 0;\n                            parameterTextLength = lastIndex;\n                        }\n                        else\n                        {\n                            parameterStartIndex = newLastIndex + lastLiteral.Literal.Length;\n                            parameterTextLength = lastIndex - parameterStartIndex;\n                        }\n                    }\n\n                    string parameterValueString = requestPathSegment.Substring(parameterStartIndex, parameterTextLength);\n\n                    if (String.IsNullOrEmpty(parameterValueString))\n                    {\n                        // If we're here that means we have a segment that contains multiple sub-segments.\n                        // For these segments all parameters must have non-empty values. If the parameter\n                        // has an empty value it's not a match.\n                        return false;\n                    }\n                    else\n                    {\n                        // If there's a value in the segment for this parameter, use the subsegment value\n                        matchedValues.Add(parameterNeedsValue.ParameterName, parameterValueString);\n                    }\n\n                    parameterNeedsValue = null;\n                    lastLiteral = null;\n                }\n\n                lastIndex = newLastIndex;\n                indexOfLastSegmentUsed--;\n            }\n\n            // If the last subsegment is a parameter, it's OK that we didn't parse all the way to the left extent of\n            // the string since the parameter will have consumed all the remaining text anyway. If the last subsegment\n            // is a literal then we *must* have consumed the entire text in that literal. Otherwise we end up matching\n            // the route \"Foo\" to the request URI \"somethingFoo\". Thus we have to check that we parsed the *entire*\n            // request URI in order for it to be a match.\n            // This check is related to the check we do earlier in this function for LiteralSubsegments.\n            return (lastIndex == 0) || (routeSegment.Subsegments[0] is PathParameterSubsegment);\n        }\n\n        private static bool MatchSingleContentPathSegment(PathSubsegment pathSubsegment, string requestPathSegment, HttpRouteValueDictionary matchedValues)\n        {\n            PathParameterSubsegment parameterSubsegment = pathSubsegment as PathParameterSubsegment;\n            if (parameterSubsegment == null)\n            {\n                // Handle a single literal segment\n                PathLiteralSubsegment literalSubsegment = pathSubsegment as PathLiteralSubsegment;\n                Contract.Assert(literalSubsegment != null, \"Invalid path segment type\");\n                return literalSubsegment.Literal.Equals(requestPathSegment, StringComparison.OrdinalIgnoreCase);\n            }\n            else\n            {\n                // Handle a single parameter segment\n                matchedValues.Add(parameterSubsegment.ParameterName, requestPathSegment);\n                return true;\n            }\n        }\n\n        private static bool RoutePartsEqual(object a, object b)\n        {\n            string sa = a as string;\n            string sb = b as string;\n            if (sa != null && sb != null)\n            {\n                // For strings do a case-insensitive comparison\n                return String.Equals(sa, sb, StringComparison.OrdinalIgnoreCase);\n            }\n            else\n            {\n                if (a != null && b != null)\n                {\n                    // Explicitly call .Equals() in case it is overridden in the type\n                    return a.Equals(b);\n                }\n                else\n                {\n                    // At least one of them is null. Return true if they both are\n                    return a == b;\n                }\n            }\n        }\n\n        private static string UriEncode(string str)\n        {\n            string escape = Uri.EscapeUriString(str);\n            return Regex.Replace(escape, \"([#?])\", new MatchEvaluator(EscapeReservedCharacters));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Routing/HttpRoute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Text.RegularExpressions;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.Routing\n{\n    /// <summary>\n    /// Route class for self-host (i.e. hosted outside of ASP.NET). This class is mostly the\n    /// same as the System.Web.Routing.Route implementation.\n    /// This class has the same URL matching functionality as System.Web.Routing.Route. However,\n    /// in order for this route to match when generating URLs, a special \"httproute\" key must be\n    /// specified when generating the URL.\n    /// </summary>\n    public class HttpRoute : IHttpRoute\n    {\n        /// <summary>\n        /// Key used to signify that a route URL generation request should include HTTP routes (e.g. Web API).\n        /// If this key is not specified then no HTTP routes will match.\n        /// </summary>\n        public static readonly string HttpRouteKey = \"httproute\";\n\n        internal const string RoutingContextKey = \"MS_RoutingContext\";\n\n        private string _routeTemplate;\n        private HttpRouteValueDictionary _defaults;\n        private HttpRouteValueDictionary _constraints;\n        private HttpRouteValueDictionary _dataTokens;\n\n        public HttpRoute()\n            : this(routeTemplate: null, defaults: null, constraints: null, dataTokens: null, handler: null, parsedRoute: null)\n        {\n        }\n\n        public HttpRoute(string routeTemplate)\n            : this(routeTemplate, defaults: null, constraints: null, dataTokens: null, handler: null, parsedRoute: null)\n        {\n        }\n\n        public HttpRoute(string routeTemplate, HttpRouteValueDictionary defaults)\n            : this(routeTemplate, defaults, constraints: null, dataTokens: null, handler: null, parsedRoute: null)\n        {\n        }\n\n        public HttpRoute(string routeTemplate, HttpRouteValueDictionary defaults, HttpRouteValueDictionary constraints)\n            : this(routeTemplate, defaults, constraints, dataTokens: null, handler: null, parsedRoute: null)\n        {\n        }\n\n        public HttpRoute(string routeTemplate, HttpRouteValueDictionary defaults, HttpRouteValueDictionary constraints, HttpRouteValueDictionary dataTokens)\n            : this(routeTemplate, defaults, constraints, dataTokens, handler: null, parsedRoute: null)\n        {\n        }\n\n        public HttpRoute(string routeTemplate, HttpRouteValueDictionary defaults, HttpRouteValueDictionary constraints, HttpRouteValueDictionary dataTokens, HttpMessageHandler handler)\n            : this(routeTemplate, defaults, constraints, dataTokens, handler, parsedRoute: null)\n        {\n        }\n\n        internal HttpRoute(string routeTemplate, HttpRouteValueDictionary defaults, HttpRouteValueDictionary constraints, HttpRouteValueDictionary dataTokens, HttpMessageHandler handler, HttpParsedRoute parsedRoute)\n        {\n            _routeTemplate = routeTemplate == null ? String.Empty : routeTemplate;\n            _defaults = defaults ?? new HttpRouteValueDictionary();\n            _constraints = constraints ?? new HttpRouteValueDictionary();\n            _dataTokens = dataTokens ?? new HttpRouteValueDictionary();\n            Handler = handler;\n\n            if (parsedRoute == null)\n            {\n                // The parser will throw for invalid routes.\n                ParsedRoute = RouteParser.Parse(routeTemplate);\n            }\n            else\n            {\n                ParsedRoute = parsedRoute;\n            }\n        }\n\n        public IDictionary<string, object> Defaults\n        {\n            get { return _defaults; }\n        }\n\n        public IDictionary<string, object> Constraints\n        {\n            get { return _constraints; }\n        }\n\n        public IDictionary<string, object> DataTokens\n        {\n            get { return _dataTokens; }\n        }\n\n        public HttpMessageHandler Handler { get; private set; }\n\n        public string RouteTemplate\n        {\n            get { return _routeTemplate; }\n        }\n\n        internal HttpParsedRoute ParsedRoute { get; private set; }\n\n        public virtual IHttpRouteData GetRouteData(string virtualPathRoot, HttpRequestMessage request)\n        {\n            if (virtualPathRoot == null)\n            {\n                throw Error.ArgumentNull(\"virtualPathRoot\");\n            }\n\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            RoutingContext context = GetOrCreateRoutingContext(virtualPathRoot, request);\n            if (!context.IsValid)\n            {\n                return null;\n            }\n\n            HttpRouteValueDictionary values = ParsedRoute.Match(context, _defaults);\n            if (values == null)\n            {\n                // If we got back a null value set, that means the URI did not match\n                return null;\n            }\n\n            // Validate the values\n            if (!ProcessConstraints(request, values, HttpRouteDirection.UriResolution))\n            {\n                return null;\n            }\n\n            return new HttpRouteData(this, values);\n        }\n\n        private static RoutingContext GetOrCreateRoutingContext(string virtualPathRoot, HttpRequestMessage request)\n        {\n            RoutingContext context;\n            if (!request.Properties.TryGetValue<RoutingContext>(RoutingContextKey, out context))\n            {\n                context = CreateRoutingContext(virtualPathRoot, request);\n                request.Properties[RoutingContextKey] = context;\n            }\n\n            return context;\n        }\n\n        private static RoutingContext CreateRoutingContext(string virtualPathRoot, HttpRequestMessage request)\n        {\n            // Note: we don't validate host/port as this is expected to be done at the host level\n            string requestPath = \"/\" + request.RequestUri.GetComponents(UriComponents.Path, UriFormat.Unescaped);\n\n            // This code is optimized for the common path being an exact case match on the virtual path string.\n            // An Ordinal (case-sensitive) comparison is significantly faster than OrdinalIgnoreCase.\n            if (!requestPath.StartsWith(virtualPathRoot, StringComparison.Ordinal))\n            {\n                if (!requestPath.StartsWith(virtualPathRoot, StringComparison.OrdinalIgnoreCase))\n                {\n                    return RoutingContext.Invalid();\n                }\n            }\n\n            string relativeRequestPath = null;\n            int virtualPathLength = virtualPathRoot.Length;\n            if (requestPath.Length > virtualPathLength && requestPath[virtualPathLength] == '/')\n            {\n                relativeRequestPath = requestPath.Substring(virtualPathLength + 1);\n            }\n            else\n            {\n                relativeRequestPath = requestPath.Substring(virtualPathLength);\n            }\n\n            return RoutingContext.Valid(RouteParser.SplitUriToPathSegmentStrings(relativeRequestPath));\n        }\n\n        /// <summary>\n        /// Attempt to generate a URI that represents the values passed in based on current\n        /// values from the <see cref=\"HttpRouteData\"/> and new values using the specified <see cref=\"HttpRoute\"/>.\n        /// </summary>\n        /// <param name=\"request\">The HTTP request message.</param>\n        /// <param name=\"values\">The route values.</param>\n        /// <returns>A <see cref=\"HttpVirtualPathData\"/> instance or null if URI cannot be generated.</returns>\n        public virtual IHttpVirtualPathData GetVirtualPath(HttpRequestMessage request, IDictionary<string, object> values)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            // Only perform URL generation if the \"httproute\" key was specified. This allows these\n            // routes to be ignored when a regular MVC app tries to generate URLs. Without this special\n            // key an HTTP route used for Web API would normally take over almost all the routes in a\n            // typical app.\n            if (values != null && !values.Keys.Contains(HttpRouteKey, StringComparer.OrdinalIgnoreCase))\n            {\n                return null;\n            }\n            // Remove the value from the collection so that it doesn't affect the generated URL\n            var newValues = GetRouteDictionaryWithoutHttpRouteKey(values);\n\n            IHttpRouteData routeData = request.GetRouteData();\n            IDictionary<string, object> requestValues = routeData == null ? null : routeData.Values;\n\n            BoundRouteTemplate result = ParsedRoute.Bind(requestValues, newValues, _defaults, _constraints);\n            if (result == null)\n            {\n                return null;\n            }\n\n            // Verify that the route matches the validation rules\n            if (!ProcessConstraints(request, result.Values, HttpRouteDirection.UriGeneration))\n            {\n                return null;\n            }\n\n            return new HttpVirtualPathData(this, result.BoundTemplate);\n        }\n\n        private static IDictionary<string, object> GetRouteDictionaryWithoutHttpRouteKey(IDictionary<string, object> routeValues)\n        {\n            var newRouteValues = new HttpRouteValueDictionary();\n            if (routeValues != null)\n            {\n                foreach (var routeValue in routeValues)\n                {\n                    if (!String.Equals(routeValue.Key, HttpRouteKey, StringComparison.OrdinalIgnoreCase))\n                    {\n                        newRouteValues.Add(routeValue.Key, routeValue.Value);\n                    }\n                }\n            }\n            return newRouteValues;\n        }\n\n        protected virtual bool ProcessConstraint(HttpRequestMessage request, object constraint, string parameterName, HttpRouteValueDictionary values, HttpRouteDirection routeDirection)\n        {\n            IHttpRouteConstraint customConstraint = constraint as IHttpRouteConstraint;\n            if (customConstraint != null)\n            {\n                return customConstraint.Match(request, this, parameterName, values, routeDirection);\n            }\n\n            // If there was no custom constraint, then treat the constraint as a string which represents a Regex.\n            string constraintsRule = constraint as string;\n            if (constraintsRule == null)\n            {\n                throw Error.InvalidOperation(SRResources.Route_ValidationMustBeStringOrCustomConstraint, parameterName, RouteTemplate, typeof(IHttpRouteConstraint).Name);\n            }\n\n            object parameterValue;\n            values.TryGetValue(parameterName, out parameterValue);\n            string parameterValueString = Convert.ToString(parameterValue, CultureInfo.InvariantCulture);\n            string constraintsRegEx = \"^(\" + constraintsRule + \")$\";\n            return Regex.IsMatch(parameterValueString, constraintsRegEx, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);\n        }\n\n        private bool ProcessConstraints(HttpRequestMessage request, HttpRouteValueDictionary values, HttpRouteDirection routeDirection)\n        {\n            if (Constraints != null)\n            {\n                foreach (KeyValuePair<string, object> constraintsItem in Constraints)\n                {\n                    if (!ProcessConstraint(request, constraintsItem.Value, constraintsItem.Key, values, routeDirection))\n                    {\n                        return false;\n                    }\n                }\n            }\n\n            return true;\n        }\n\n        // Validates that a constraint is of a type that HttpRoute can process. This is not valid to\n        // call when a route implements IHttpRoute or inherits from HttpRoute - as the derived class can handle\n        // any types of constraints it wants to support.\n        internal static void ValidateConstraint(string routeTemplate, string name, object constraint)\n        {\n            if (constraint is IHttpRouteConstraint)\n            {\n                return;\n            }\n\n            if (constraint is string)\n            {\n                return;\n            }\n\n            throw CreateInvalidConstraintTypeException(routeTemplate, name);\n        }\n\n        private static Exception CreateInvalidConstraintTypeException(string routeTemplate, string name)\n        {\n            return Error.InvalidOperation(\n                SRResources.Route_ValidationMustBeStringOrCustomConstraint,\n                name,\n                routeTemplate,\n                typeof(IHttpRouteConstraint).FullName);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Routing/HttpRouteData.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Http.Routing\n{\n    public class HttpRouteData : IHttpRouteData\n    {\n        private IHttpRoute _route;\n        private IDictionary<string, object> _values;\n\n        public HttpRouteData(IHttpRoute route)\n            : this(route, new HttpRouteValueDictionary())\n        {\n        }\n\n        public HttpRouteData(IHttpRoute route, HttpRouteValueDictionary values)\n        {\n            if (route == null)\n            {\n                throw Error.ArgumentNull(\"route\");\n            }\n\n            if (values == null)\n            {\n                throw Error.ArgumentNull(\"values\");\n            }\n\n            _route = route;\n            _values = values;\n        }\n\n        public IHttpRoute Route\n        {\n            get { return _route; }\n        }\n\n        public IDictionary<string, object> Values\n        {\n            get { return _values; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Routing/HttpRouteDataExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\n\nnamespace System.Web.Http.Routing\n{\n    public static class HttpRouteDataExtensions\n    {\n        /// <summary>\n        /// Remove all optional parameters that do not have a value from the route data. \n        /// </summary>\n        /// <param name=\"routeData\">route data, to be mutated in-place.</param>\n        public static void RemoveOptionalRoutingParameters(this IHttpRouteData routeData)\n        {\n            RemoveOptionalRoutingParameters(routeData.Values);\n\n            var subRouteData = routeData.GetSubRoutes();\n            if (subRouteData != null)\n            {\n                foreach (IHttpRouteData sub in subRouteData)\n                {\n                    RemoveOptionalRoutingParameters(sub);\n                }\n            }\n        }\n\n        private static void RemoveOptionalRoutingParameters(IDictionary<string, object> routeValueDictionary)\n        {\n            Contract.Assert(routeValueDictionary != null);\n\n            // Get all keys for which the corresponding value is 'Optional'.\n            // Having a separate array is necessary so that we don't manipulate the dictionary while enumerating.\n            // This is on a hot-path and linq expressions are showing up on the profile, so do array manipulation.\n            int max = routeValueDictionary.Count;\n            int i = 0;\n            string[] matching = new string[max];\n            foreach (KeyValuePair<string, object> kv in routeValueDictionary)\n            {\n                if (kv.Value == RouteParameter.Optional)\n                {\n                    matching[i] = kv.Key;\n                    i++;\n                }\n            }\n            for (int j = 0; j < i; j++)\n            {\n                string key = matching[j];\n                routeValueDictionary.Remove(key);\n            }\n        }\n\n        /// <summary>\n        /// If a route is really a union of other routes, return the set of sub routes. \n        /// </summary>\n        /// <param name=\"routeData\">a union route data</param>\n        /// <returns>set of sub soutes contained within this route</returns>\n        public static IEnumerable<IHttpRouteData> GetSubRoutes(this IHttpRouteData routeData)\n        {\n            IHttpRouteData[] subRoutes = null;\n            if (routeData.Values.TryGetValue(RouteCollectionRoute.SubRouteDataKey, out subRoutes))\n            {\n                return subRoutes;\n            }\n            return null;\n        }\n\n        // If routeData is from an attribute route, get the action descriptors, order and precedence that it may match\n        // to. Caller still needs to run action selection to pick the specific action.\n        // Else return null.\n        internal static CandidateAction[] GetDirectRouteCandidates(this IHttpRouteData routeData)\n        {\n            Contract.Assert(routeData != null);\n            IEnumerable<IHttpRouteData> subRoutes = routeData.GetSubRoutes();\n\n            // Possible this is being called on a subroute. This can happen after ElevateRouteData. Just chain. \n            if (subRoutes == null)\n            {\n                if (routeData.Route == null)\n                {\n                    // If the matched route is a System.Web.Routing.Route (in web host) then routeData.Route\n                    // will be null. Normally a System.Web.Routing.Route match would go through an MVC handler\n                    // but we can get here through HttpRoutingDispatcher in WebAPI batching. If that happens, \n                    // then obviously it's not a WebAPI attribute routing match.\n                    return null;\n                }\n                else\n                {\n                    return routeData.Route.GetDirectRouteCandidates();\n                }\n            }\n\n            var list = new List<CandidateAction>();\n\n            foreach (IHttpRouteData subData in subRoutes)\n            {\n                CandidateAction[] candidates = subData.Route.GetDirectRouteCandidates();\n                if (candidates != null)\n                {\n                    list.AddRange(candidates);\n                }\n            }\n            return list.ToArray();\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http/Routing/HttpRouteDirection.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Routing\n{\n    public enum HttpRouteDirection\n    {\n        UriResolution = 0,\n        UriGeneration\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Routing/HttpRouteExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.Routing\n{\n    internal static class HttpRouteExtensions\n    {\n        // If route is a direct route, get the action descriptors, order and precedence it may map to.\n        public static CandidateAction[] GetDirectRouteCandidates(this IHttpRoute route)\n        {\n            Contract.Assert(route != null);\n\n            IDictionary<string, object> dataTokens = route.DataTokens;\n            if (dataTokens == null)\n            {\n                return null;\n            }\n\n            List<CandidateAction> candidates = new List<CandidateAction>();\n\n            HttpActionDescriptor[] directRouteActions = null;\n            HttpActionDescriptor[] possibleDirectRouteActions;\n            if (dataTokens.TryGetValue<HttpActionDescriptor[]>(RouteDataTokenKeys.Actions, out possibleDirectRouteActions))\n            {\n                if (possibleDirectRouteActions != null && possibleDirectRouteActions.Length > 0)\n                {\n                    directRouteActions = possibleDirectRouteActions;\n                }\n            }\n\n            if (directRouteActions == null)\n            {\n                return null;\n            }\n\n            int order = 0;\n            int possibleOrder;\n            if (dataTokens.TryGetValue<int>(RouteDataTokenKeys.Order, out possibleOrder))\n            {\n                order = possibleOrder;\n            }\n\n            decimal precedence = 0M;\n            decimal possiblePrecedence;\n\n            if (dataTokens.TryGetValue<decimal>(RouteDataTokenKeys.Precedence, out possiblePrecedence))\n            {\n                precedence = possiblePrecedence;\n            }\n\n            foreach (HttpActionDescriptor actionDescriptor in directRouteActions)\n            {\n                candidates.Add(new CandidateAction\n                {\n                    ActionDescriptor = actionDescriptor,\n                    Order = order,\n                    Precedence = precedence\n                });\n            }\n\n            return candidates.ToArray();\n        }\n\n        public static HttpActionDescriptor[] GetTargetActionDescriptors(this IHttpRoute route)\n        {\n            Contract.Assert(route != null);\n            IDictionary<string, object> dataTokens = route.DataTokens;\n\n            if (dataTokens == null)\n            {\n                return null;\n            }\n\n            HttpActionDescriptor[] actions;\n\n            if (!dataTokens.TryGetValue<HttpActionDescriptor[]>(RouteDataTokenKeys.Actions, out actions))\n            {\n                return null;\n            }\n\n            return actions;\n        }\n\n        public static HttpControllerDescriptor GetTargetControllerDescriptor(this IHttpRoute route)\n        {\n            Contract.Assert(route != null);\n            IDictionary<string, object> dataTokens = route.DataTokens;\n\n            if (dataTokens == null)\n            {\n                return null;\n            }\n\n            HttpControllerDescriptor controller;\n\n            if (!dataTokens.TryGetValue<HttpControllerDescriptor>(RouteDataTokenKeys.Controller, out controller))\n            {\n                return null;\n            }\n\n            return controller;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Routing/HttpRouteValueDictionary.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Http.Internal;\n\nnamespace System.Web.Http.Routing\n{\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2237:MarkISerializableTypesWithSerializable\", Justification = \"This class will never be serialized.\")]\n    public class HttpRouteValueDictionary : Dictionary<string, object>\n    {\n        public HttpRouteValueDictionary()\n            : base(StringComparer.OrdinalIgnoreCase)\n        {\n        }\n\n        public HttpRouteValueDictionary(IDictionary<string, object> dictionary)\n            : base(StringComparer.OrdinalIgnoreCase)\n        {\n            if (dictionary != null)\n            {\n                foreach (KeyValuePair<string, object> current in dictionary)\n                {\n                    Add(current.Key, current.Value);\n                }\n            }\n        }\n\n        public HttpRouteValueDictionary(object values)\n            : base(StringComparer.OrdinalIgnoreCase)\n        {\n            IDictionary<string, object> valuesAsDictionary = values as IDictionary<string, object>;\n            if (valuesAsDictionary != null)\n            {\n                foreach (KeyValuePair<string, object> current in valuesAsDictionary)\n                {\n                    Add(current.Key, current.Value);\n                }\n            }\n            else if (values != null)\n            {\n                foreach (PropertyHelper property in PropertyHelper.GetProperties(values))\n                {\n                    // Extract the property values from the property helper\n                    // The advantage here is that the property helper caches fast accessors.\n                    Add(property.Name, property.GetValue(values));\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Routing/HttpVirtualPathData.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Routing\n{\n    public class HttpVirtualPathData : IHttpVirtualPathData\n    {\n        private string _virtualPath;\n\n        public HttpVirtualPathData(IHttpRoute route, string virtualPath)\n        {\n            if (route == null)\n            {\n                throw Error.ArgumentNull(\"route\");\n            }\n\n            if (virtualPath == null)\n            {\n                throw Error.ArgumentNull(\"virtualPath\");\n            }\n\n            Route = route;\n            VirtualPath = virtualPath;\n        }\n\n        public IHttpRoute Route { get; private set; }\n\n        public string VirtualPath\n        {\n            get { return _virtualPath; }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n                _virtualPath = value;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Routing/IHttpRoute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.Routing\n{\n    /// <summary>\n    /// <see cref=\"IHttpRoute\"/> defines the interface for a route expressing how to map an incoming <see cref=\"HttpRequestMessage\"/> to a particular controller\n    /// and action.\n    /// </summary>\n    public interface IHttpRoute\n    {\n        /// <summary>\n        /// Gets the route template describing the URI pattern to match against. \n        /// </summary>\n        string RouteTemplate { get; }\n\n        /// <summary>\n        /// Gets the default values for route parameters if not provided by the incoming <see cref=\"HttpRequestMessage\"/>.\n        /// </summary>\n        IDictionary<string, object> Defaults { get; }\n\n        /// <summary>\n        /// Gets the constraints for the route parameters.\n        /// </summary>\n        IDictionary<string, object> Constraints { get; }\n\n        /// <summary>\n        /// Gets any additional data tokens not used directly to determine whether a route matches an incoming <see cref=\"HttpRequestMessage\"/>.\n        /// </summary>\n        IDictionary<string, object> DataTokens { get; }\n\n        /// <summary>\n        /// Gets the message handler that will be the recipient of the request. If <c>null</c>, the default handler will\n        /// be used (which dispatches messages to implementations of <see cref=\"IHttpController\"/>).\n        /// </summary>\n        HttpMessageHandler Handler { get; }\n\n        /// <summary>\n        /// Determine whether this route is a match for the incoming request by looking up the <see cref=\"IHttpRouteData\"/> for the route.\n        /// </summary>\n        /// <param name=\"virtualPathRoot\">The virtual path root.</param>\n        /// <param name=\"request\">The request.</param>\n        /// <returns>The <see cref=\"IHttpRouteData\"/> for a route if matches; otherwise <c>null</c>.</returns>\n        IHttpRouteData GetRouteData(string virtualPathRoot, HttpRequestMessage request);\n\n        /// <summary>\n        /// Compute a URI based on the route and the values provided.\n        /// </summary>\n        /// <param name=\"request\">The request message.</param>\n        /// <param name=\"values\">The values.</param>\n        /// <returns></returns>\n        IHttpVirtualPathData GetVirtualPath(HttpRequestMessage request, IDictionary<string, object> values);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Routing/IHttpRouteConstraint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\n\nnamespace System.Web.Http.Routing\n{\n    /// <summary>\n    /// Defines an abstraction for constraining a route.\n    /// </summary>\n    public interface IHttpRouteConstraint\n    {\n        /// <summary>\n        /// Attempts to match the specified request.\n        /// </summary>\n        /// <param name=\"request\">The request.</param>\n        /// <param name=\"route\">The route that is being constrained.</param>\n        /// <param name=\"parameterName\">The name of the parameter.</param>\n        /// <param name=\"values\">The route value dictionary.</param>\n        /// <param name=\"routeDirection\">The direction of the routing, i.e. URI resolution or URI generation.</param>\n        /// <returns><c>false</c> if the route should not match the specified request, or <c>true</c> otherwise</returns>\n        bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Routing/IHttpRouteData.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Http.Routing\n{\n    public interface IHttpRouteData\n    {\n        IHttpRoute Route { get; }\n\n        IDictionary<string, object> Values { get; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Routing/IHttpRouteInfoProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.Routing\n{\n    /// <summary>\n    /// Provides information for defining a route.\n    /// </summary>\n    public interface IHttpRouteInfoProvider\n    {\n        /// <summary>\n        /// Gets the name of the route to generate.\n        /// </summary>\n        string Name { get; }\n\n        /// <summary>\n        /// Gets the route template describing the URI pattern to match against.\n        /// </summary>\n        string Template { get; }\n\n        /// <summary>\n        /// Gets the order of the route relative to other routes. Default value is 0.\n        /// </summary>\n        int Order { get; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Routing/IHttpVirtualPathData.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Routing\n{\n    public interface IHttpVirtualPathData\n    {\n        IHttpRoute Route { get; }\n\n        string VirtualPath { get; set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Routing/LinkGenerationRoute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\n\nnamespace System.Web.Http.Routing\n{\n    /// <summary>\n    /// Route that generates a virtual path, but does not claim any routes. \n    /// This can be used with RouteCollectionRoute to provide generation by names. \n    /// Delegates to an inner route to do actual generation.\n    /// </summary>\n    /// <remarks>\n    /// Parallel to the MVC implementation of attribute routing in System.Web.Mvc.Routing.LinkGenerationRoute.\n    /// </remarks>\n    internal class LinkGenerationRoute : IHttpRoute\n    {\n        private readonly IHttpRoute _innerRoute;\n\n        public LinkGenerationRoute(IHttpRoute innerRoute)\n        {\n            if (innerRoute == null)\n            {\n                throw new ArgumentNullException(\"innerRoute\");\n            }\n\n            _innerRoute = innerRoute;\n        }\n\n        public string RouteTemplate\n        {\n            get { return _innerRoute.RouteTemplate; }\n        }\n\n        public IDictionary<string, object> Defaults\n        {\n            get { return _innerRoute.Defaults; }\n        }\n\n        public IDictionary<string, object> Constraints\n        {\n            get { return _innerRoute.Constraints; }\n        }\n\n        public IDictionary<string, object> DataTokens\n        {\n            get { return _innerRoute.DataTokens; }\n        }\n\n        public HttpMessageHandler Handler\n        {\n            get { return null; }\n        }\n\n        public IHttpRouteData GetRouteData(string virtualPathRoot, HttpRequestMessage request)\n        {\n            // Claims no routes\n            return null;\n        }\n\n        public IHttpVirtualPathData GetVirtualPath(HttpRequestMessage request, IDictionary<string, object> values)\n        {\n            return _innerRoute.GetVirtualPath(request, values);\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http/Routing/MediaTypeFormatterExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Net.Http.Headers;\nusing System.Web.Http.Routing;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// Extensions for adding <see cref=\"MediaTypeMapping\"/> items to a <see cref=\"MediaTypeFormatter\"/>.\n    /// </summary>\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class MediaTypeFormatterExtensions\n    {\n        /// <summary>\n        /// Updates the given <paramref name=\"formatter\"/>'s set of <see cref=\"MediaTypeMapping\"/> elements\n        /// so that it associates the <paramref name=\"mediaType\"/> with <see cref=\"HttpRequestMessage\"/> whose <see cref=\"IHttpRouteData\"/> contains a URL Parameter {ext}\n        /// with the given <paramref name=\"uriPathExtension\"/>.\n        /// </summary>\n        /// <param name=\"formatter\">The <see cref=\"MediaTypeFormatter\"/> to receive the new <see cref=\"UriPathExtensionMapping\"/> item.</param>\n        /// <param name=\"uriPathExtension\">The string of the <see cref=\"Uri\"/> path extension.</param>\n        /// <param name=\"mediaType\">The <see cref=\"MediaTypeHeaderValue\"/> to associate with.</param>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", Justification = \"There is no meaningful System.Uri representation for a path suffix such as '.xml'\")]\n        public static void AddUriPathExtensionMapping(\n            this MediaTypeFormatter formatter,\n            string uriPathExtension,\n            MediaTypeHeaderValue mediaType)\n        {\n            if (formatter == null)\n            {\n                throw new ArgumentNullException(\"formatter\");\n            }\n\n            UriPathExtensionMapping mapping = new UriPathExtensionMapping(uriPathExtension, mediaType);\n            formatter.MediaTypeMappings.Add(mapping);\n        }\n\n        /// <summary>\n        /// Updates the given <paramref name=\"formatter\"/>'s set of <see cref=\"MediaTypeMapping\"/> elements\n        /// so that it associates the <paramref name=\"mediaType\"/> with <see cref=\"HttpRequestMessage\"/> whose <see cref=\"IHttpRouteData\"/> contains a URL Parameter {ext}\n        /// with the given <paramref name=\"uriPathExtension\"/>.\n        /// </summary>\n        /// <param name=\"formatter\">The <see cref=\"MediaTypeFormatter\"/> to receive the new <see cref=\"UriPathExtensionMapping\"/> item.</param>\n        /// <param name=\"uriPathExtension\">The string of the <see cref=\"Uri\"/> path extension.</param>\n        /// <param name=\"mediaType\">The string media type to associate with.</param>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", Justification = \"There is no meaningful System.Uri representation for a path suffix such as '.xml'\")]\n        public static void AddUriPathExtensionMapping(this MediaTypeFormatter formatter, string uriPathExtension, string mediaType)\n        {\n            if (formatter == null)\n            {\n                throw new ArgumentNullException(\"formatter\");\n            }\n\n            UriPathExtensionMapping mapping = new UriPathExtensionMapping(uriPathExtension, mediaType);\n            formatter.MediaTypeMappings.Add(mapping);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Routing/RouteCollectionRoute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.Routing\n{\n    /// <summary>\n    /// A single route that is the composite of multiple \"sub routes\".  \n    /// </summary>\n    /// <remarks>\n    /// Corresponds to the MVC implementation of attribute routing in System.Web.Mvc.Routing.RouteCollectionRoute.\n    /// </remarks>\n    internal class RouteCollectionRoute : IHttpRoute, IReadOnlyCollection<IHttpRoute>\n    {\n        // Key for accessing SubRoutes on a RouteData.\n        // We expose this through the RouteData.Values instead of a derived class because \n        // RouteData can get wrapped in another type, but Values still gets persisted through the wrappers. \n        // Prefix with a \\0 to protect against conflicts with user keys. \n        public const string SubRouteDataKey = \"MS_SubRoutes\";\n\n        private IReadOnlyCollection<IHttpRoute> _subRoutes;\n\n        private static readonly IDictionary<string, object> _empty = EmptyReadOnlyDictionary<string, object>.Value;\n        \n        public RouteCollectionRoute()\n        {\n        }\n\n        // This will enumerate all controllers and action descriptors, which will run those \n        // Initialization hooks, which may try to initialize controller-specific config, which\n        // may call back to the initialize hook. So guard against that reentrancy.\n        private bool _beingInitialized;\n\n        // deferred hook for initializing the sub routes. The composite route can be added during the middle of \n        // intializing, but then the actual sub routes can get populated after initialization has finished. \n        public void EnsureInitialized(Func<IReadOnlyCollection<IHttpRoute>> initializer)\n        {\n            if (_beingInitialized && _subRoutes == null)\n            {\n                // Avoid reentrant initialization\n                return;\n            }\n\n            try\n            {\n                _beingInitialized = true;\n\n                _subRoutes = initializer();\n                Contract.Assert(_subRoutes != null);                \n            }\n            finally\n            {\n                _beingInitialized = false;\n            }\n        }\n\n        private IReadOnlyCollection<IHttpRoute> SubRoutes\n        {\n            get\n            {\n                // Caller should have already explicitly called EnsureInitialize. \n                // Avoid lazy initilization from within the route table because the route table\n                // is shared resource and init can happen \n                if (_subRoutes == null)\n                {\n                    string msg = Error.Format(SRResources.Object_NotYetInitialized);\n                    throw new InvalidOperationException(msg);\n                }\n\n                return _subRoutes;\n            }\n        }\n\n        public string RouteTemplate\n        {\n            get { return String.Empty; }\n        }\n\n        public IDictionary<string, object> Defaults\n        {\n            get { return _empty; }\n        }\n\n        public IDictionary<string, object> Constraints\n        {\n            get { return _empty; }\n        }\n\n        public IDictionary<string, object> DataTokens\n        {\n            get { return null; }\n        }\n\n        public HttpMessageHandler Handler\n        {\n            get\n            {\n                return null;\n            }\n        }\n                \n        // Returns null if no match. \n        // Else, returns a composite route data that encapsulates the possible routes this may match against. \n        public IHttpRouteData GetRouteData(string virtualPathRoot, HttpRequestMessage request)\n        {\n            List<IHttpRouteData> matches = new List<IHttpRouteData>();\n            foreach (IHttpRoute route in SubRoutes)\n            {\n                IHttpRouteData match = route.GetRouteData(virtualPathRoot, request);\n                if (match != null)\n                {\n                    matches.Add(match);\n                }\n            }\n            if (matches.Count == 0)\n            {\n                return null;  // no matches\n            }\n\n            return new RouteCollectionRouteData(this, matches.ToArray());\n        }\n\n        public IHttpVirtualPathData GetVirtualPath(HttpRequestMessage request, IDictionary<string, object> values)\n        {\n            // Use LinkGenerationRoute stubs to get placeholders for all the sub routes. \n            return null;\n        }\n\n        public int Count\n        {\n            get { return SubRoutes.Count; }\n        }\n\n        public IEnumerator<IHttpRoute> GetEnumerator()\n        {\n            return SubRoutes.GetEnumerator();\n        }\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return SubRoutes.GetEnumerator();\n        }\n\n        // Represents a union of multiple IHttpRouteDatas. \n        private class RouteCollectionRouteData : IHttpRouteData\n        {\n            public RouteCollectionRouteData(IHttpRoute parent, IHttpRouteData[] subRouteDatas)\n            {\n                Route = parent;\n\n                // Each sub route may have different values. Callers need to enumerate the subroutes \n                // and individually query each. \n                // Find sub-routes via the SubRouteDataKey; don't expose as a property since the RouteData \n                // can be wrapped in an outer type that doesn't propagate properties. \n                Values = new HttpRouteValueDictionary() { { SubRouteDataKey, subRouteDatas } };\n            }\n\n            public IHttpRoute Route { get; private set; }\n\n            public IDictionary<string, object> Values { get; private set; }\n        }        \n    }\n}"
  },
  {
    "path": "src/System.Web.Http/Routing/RouteDataTokenKeys.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Routing\n{\n    /// <summary>\n    /// Provides keys for looking up route values and data tokens.\n    /// </summary>\n    internal static class RouteDataTokenKeys\n    {\n        // Used to provide the action descriptors to consider for attribute routing\n        public const string Actions = \"actions\";\n\n        // Used to indicate that a route is a controller-level attribute route.\n        public const string Controller = \"controller\";\n\n        // Used to allow customer-provided disambiguation between multiple matching attribute routes\n        public const string Order = \"order\";\n\n        // Used to allow URI constraint-based disambiguation between multiple matching attribute routes\n        public const string Precedence = \"precedence\";\n    }\n}"
  },
  {
    "path": "src/System.Web.Http/Routing/RouteValueKeys.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Routing\n{\n    /// <summary>Provides keys for looking up route values.</summary>\n    internal static class RouteValueKeys\n    {\n        // Used to provide the action and controller name\n        public const string Action = \"action\";\n        public const string Controller = \"controller\";\n    }\n}"
  },
  {
    "path": "src/System.Web.Http/Routing/RoutingContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Http.Routing\n{\n    /// <summary>\n    /// Parameter class for URL matching in routing.\n    /// </summary>\n    internal class RoutingContext\n    {\n        private static readonly RoutingContext CachedInvalid = new RoutingContext() { IsValid = false };\n\n        public static RoutingContext Invalid()\n        {\n            return CachedInvalid;\n        }\n\n        public static RoutingContext Valid(List<string> pathSegments)\n        {\n            return new RoutingContext()\n            {\n                PathSegments = pathSegments,\n                IsValid = true,\n            };\n        }\n\n        private RoutingContext()\n        {\n        }\n\n        public bool IsValid\n        {\n            get;\n            private set;\n        }\n\n        public List<string> PathSegments\n        {\n            get;\n            private set;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Routing/StopRoutingHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.Routing\n{\n    /// <summary>\n    /// Represents a handler that specifies routing should not handle requests for a route template. When a route provides this class as a handler, requests matching against the route will be ignored.\n    /// </summary>\n    public sealed class StopRoutingHandler : HttpMessageHandler\n    {\n        /// <summary>\n        /// Like <see cref=\"T:System.Web.Routing.StopRoutingHandler\"/>, the handler does nothing but throws a NotSupportedException. This method should never be called,\n        /// and the NotSupportedException should never be thrown directly, because this handler will be replaced by responding a message saying that no route is matched.\n        /// </summary>\n        /// <param name=\"request\">The HTTP request message to send.</param>\n        /// <param name=\"cancellationToken\">The notification that operations should be canceled.</param>\n        /// <returns>Throws NotSupportedException.</returns>\n        protected override Task<HttpResponseMessage> SendAsync(\n            HttpRequestMessage request, CancellationToken cancellationToken)\n        {\n            throw new NotSupportedException();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Routing/UriPathExtensionMapping.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Net.Http.Headers;\nusing System.Web.Http.Routing;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// Class that provides <see cref=\"MediaTypeHeaderValue\"/>'s from path extension appearing in <see cref=\"IHttpRouteData\"/>.\n    /// It uses the value of the {ext} URL parameter from <see cref=\"IHttpRouteData\"/> for a match.\n    /// </summary>\n    /// <example>\n    /// This sample shows how to use the UriPathExtensionMapping to map urls ending with \".json\" to \"application/json\"\n    /// <code>\n    /// config.Routes.MapHttpRoute(\"Default\", \"{controller}\");\n    /// config.Routes.MapHttpRoute(\"DefaultWithExt\", \"{controller}.{ext}\");\n    /// config.Formatters.JsonFormatter.AddUriPathExtensionMapping(\"json\", \"application/json\");\n    /// </code>\n    /// </example>\n    public class UriPathExtensionMapping : MediaTypeMapping\n    {\n        public static readonly string UriPathExtensionKey = \"ext\";\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"UriPathExtensionMapping\"/> class.\n        /// </summary>\n        /// <param name=\"uriPathExtension\">The extension corresponding to <paramref name=\"mediaType\"/>.\n        /// This value should not include a dot or wildcards.</param>\n        /// <param name=\"mediaType\">The media type that will be returned if <paramref name=\"uriPathExtension\"/> is matched.</param>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", Justification = \"There is no meaningful System.Uri representation for a path suffix such as '.xml'\")]\n        public UriPathExtensionMapping(string uriPathExtension, string mediaType)\n            : base(mediaType)\n        {\n            Initialize(uriPathExtension);\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"UriPathExtensionMapping\"/> class.\n        /// </summary>\n        /// <param name=\"uriPathExtension\">The extension corresponding to <paramref name=\"mediaType\"/>.\n        /// This value should not include a dot or wildcards.</param>\n        /// <param name=\"mediaType\">The <see cref=\"MediaTypeHeaderValue\"/> that will be returned if <paramref name=\"uriPathExtension\"/> is matched.</param>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", Justification = \"There is no meaningful System.Uri representation for a path suffix such as '.xml'\")]\n        public UriPathExtensionMapping(string uriPathExtension, MediaTypeHeaderValue mediaType)\n            : base(mediaType)\n        {\n            Initialize(uriPathExtension);\n        }\n\n        /// <summary>\n        /// Gets the <see cref=\"Uri\"/> path extension.\n        /// </summary>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1056:UriPropertiesShouldNotBeStrings\", Justification = \"There is no meaningful System.Uri representation for a path suffix such as '.xml'\")]\n        public string UriPathExtension { get; private set; }\n\n        /// <summary>\n        /// Returns a value indicating whether this <see cref=\"UriPathExtensionMapping\"/>\n        /// instance can provide a <see cref=\"MediaTypeHeaderValue\"/> for the given <paramref name=\"request\"/>.\n        /// </summary>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/> to check.</param>\n        /// <returns>If this <paramref name=\"request\"/>'s route data contains a match for <see cref=\"UriPathExtension\"/>\n        /// it returns <c>1.0</c> otherwise <c>0.0</c>.</returns>\n        public override double TryMatchMediaType(HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw new ArgumentNullException(\"request\");\n            }\n\n            string extension = GetUriPathExtensionOrNull(request);\n            return String.Equals(extension, UriPathExtension, StringComparison.OrdinalIgnoreCase) ? 1.0 : 0.0;\n        }\n\n        private static string GetUriPathExtensionOrNull(HttpRequestMessage request)\n        {\n            IHttpRouteData routeData = request.GetRouteData();\n\n            if (routeData != null)\n            {\n                string extension;\n                if (routeData.Values.TryGetValue(UriPathExtensionKey, out extension))\n                {\n                    return extension;\n                }\n            }\n\n            return null;\n        }\n\n        private void Initialize(string uriPathExtension)\n        {\n            if (String.IsNullOrWhiteSpace(uriPathExtension))\n            {\n                throw new ArgumentNullException(\"uriPathExtension\");\n            }\n\n            UriPathExtension = uriPathExtension.Trim().TrimStart('.');\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Routing/UrlHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.Routing\n{\n    /// <summary>\n    /// Represents a factory for creating URLs.\n    /// </summary>\n    public class UrlHelper\n    {\n        private HttpRequestMessage _request;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"UrlHelper\"/> class.\n        /// </summary>\n        /// <remarks>The default constructor is intended for use by unit testing only.</remarks>\n        public UrlHelper()\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"UrlHelper\"/> class.\n        /// </summary>\n        /// <param name=\"request\">The HTTP request message containing the context under which the URLs are generated.</param>\n        public UrlHelper(HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            Request = request;\n        }\n\n        /// <summary>\n        /// Gets the <see cref=\"HttpRequestMessage\"/> of the current <see cref=\"UrlHelper\"/>.\n        /// The setter is not intended to be used other than for unit testing purpose. \n        /// </summary>\n        public HttpRequestMessage Request\n        {\n            get { return _request; }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n\n                _request = value;\n            }\n        }\n\n        /// <summary>\n        /// Creates an absolute URL using the specified path.\n        /// </summary>\n        /// <param name=\"path\">The URL path, which may be a relative URL, a rooted URL, or a virtual path.</param>\n        /// <returns>The generated URL.</returns>\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2234:PassSystemUriObjectsInsteadOfStrings\", Justification = \"It is safe to pass string here\")]\n        public virtual string Content(string path)\n        {\n            if (String.IsNullOrEmpty(path))\n            {\n                throw Error.ArgumentNullOrEmpty(\"path\");\n            }\n\n            if (Request == null)\n            {\n                throw Error.InvalidOperation(SRResources.RequestIsNull, \"UrlHelper\");\n            }\n\n            if (path.StartsWith(\"~/\", StringComparison.Ordinal))\n            {\n                // This is a virtual path, we need to combine it with the virtual path root\n                string virtualPathRoot;\n                HttpRequestContext requestContext = Request.GetRequestContext();\n\n                if (requestContext != null)\n                {\n                    virtualPathRoot = requestContext.VirtualPathRoot;\n                }\n                else\n                {\n                    HttpConfiguration configuration = Request.GetConfiguration();\n                    if (configuration == null)\n                    {\n                        throw Error.InvalidOperation(SRResources.HttpRequestMessageExtensions_NoConfiguration);\n                    }\n\n                    virtualPathRoot = configuration.VirtualPathRoot;\n                }\n\n                if (virtualPathRoot == null)\n                {\n                    virtualPathRoot = \"/\";\n                }\n\n                if (!virtualPathRoot.StartsWith(\"/\", StringComparison.Ordinal))\n                {\n                    virtualPathRoot = \"/\" + virtualPathRoot;\n                }\n                if (!virtualPathRoot.EndsWith(\"/\", StringComparison.Ordinal))\n                {\n                    virtualPathRoot += \"/\";\n                }\n\n                return new Uri(Request.RequestUri, virtualPathRoot + path.Substring(\"~/\".Length)).AbsoluteUri;\n            }\n            else\n            {\n                return new Uri(Request.RequestUri, path).AbsoluteUri;\n            }\n        }\n\n        /// <summary>\n        /// Creates a relative URL using the specified route and route data.\n        /// </summary>\n        /// <param name=\"routeName\">The name of the route to use for generating the URL.</param>\n        /// <param name=\"routeValues\">The route data to use for generating the URL.</param>\n        /// <returns>The generated URL.</returns>\n        public virtual string Route(string routeName, object routeValues)\n        {\n            return Route(routeName, new HttpRouteValueDictionary(routeValues));\n        }\n\n        /// <summary>\n        /// Creates a relative URL using the specified route and route data.\n        /// </summary>\n        /// <param name=\"routeName\">The name of the route to use for generating the URL.</param>\n        /// <param name=\"routeValues\">The route data to use for generating the URL.</param>\n        /// <returns>The generated URL.</returns>\n        public virtual string Route(string routeName, IDictionary<string, object> routeValues)\n        {\n            return GetVirtualPath(Request, routeName, routeValues);\n        }\n\n        /// <summary>\n        /// Creates an absolute URL using the given route and route data.\n        /// </summary>\n        /// <param name=\"routeName\">The name of the route to use for generating the URL.</param>\n        /// <param name=\"routeValues\">The route data to use for generating the URL.</param>\n        /// <returns>The generated URL.</returns>\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2234:PassSystemUriObjectsInsteadOfStrings\", Justification = \"It is safe to pass string here\")]\n        public virtual string Link(string routeName, object routeValues)\n        {\n            return Link(routeName, new HttpRouteValueDictionary(routeValues));\n        }\n\n        /// <summary>\n        /// Creates an absolute URL using the specified route and route data.\n        /// </summary>\n        /// <param name=\"routeName\">The name of the route to use for generating the URL.</param>\n        /// <param name=\"routeValues\">The route data to use for generating the URL.</param>\n        /// <returns>The generated URL.</returns>\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2234:PassSystemUriObjectsInsteadOfStrings\", Justification = \"It is safe to pass string here\")]\n        public virtual string Link(string routeName, IDictionary<string, object> routeValues)\n        {\n            string link = Route(routeName, routeValues);\n            if (!String.IsNullOrEmpty(link))\n            {\n                link = new Uri(Request.RequestUri, link).AbsoluteUri;\n            }\n\n            return link;\n        }\n\n        private static string GetVirtualPath(HttpRequestMessage request, string routeName, IDictionary<string, object> routeValues)\n        {\n            if (routeValues == null)\n            {\n                // If no route values were passed in at all we have to create a new dictionary\n                // so that we can add the extra \"httproute\" key.\n                routeValues = new HttpRouteValueDictionary();\n                routeValues.Add(HttpRoute.HttpRouteKey, true);\n            }\n            else\n            {\n                // Copy the dictionary so that we can guarantee that routeValues uses an OrdinalIgnoreCase comparer\n                // and to add the extra \"httproute\" key used by all Web API routes to disambiguate them from other MVC routes.\n                routeValues = new HttpRouteValueDictionary(routeValues);\n                if (!routeValues.ContainsKey(HttpRoute.HttpRouteKey))\n                {\n                    routeValues.Add(HttpRoute.HttpRouteKey, true);\n                }\n            }\n\n            HttpConfiguration configuration = request.GetConfiguration();\n            if (configuration == null)\n            {\n                throw Error.InvalidOperation(SRResources.HttpRequestMessageExtensions_NoConfiguration);\n            }\n\n            IHttpVirtualPathData vpd = configuration.Routes.GetVirtualPath(\n                request: request,\n                name: routeName,\n                values: routeValues);\n            if (vpd == null)\n            {\n                return null;\n            }\n            return vpd.VirtualPath;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Services/ControllerServices.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.Http.Controllers\n{\n    /// <summary>\n    /// Represents a container for services that can be specific to a controller. \n    /// This shadows the services from its parent <see cref=\"ServicesContainer\"/>. A controller can either set a service here, or fall through \n    /// to the more global set of services. \n    /// </summary>\n    public class ControllerServices : ServicesContainer\n    {\n        // This lists specific services that have been over ridden for the controller.\n        // Anything missing means just fall through and ask the _parent. \n        // This dictionary is only written at initialization time, and then read-only during steady state.\n        // So it can be safely read from multiple threads after initialization.\n        private Dictionary<Type, object> _overrideSingle;\n        private Dictionary<Type, List<object>> _overrideMulti;\n        private readonly ServicesContainer _parent;\n\n        public ControllerServices(ServicesContainer parent)\n        {\n            if (parent == null)\n            {\n                throw Error.ArgumentNull(\"parent\");\n            }\n            _parent = parent;\n        }\n\n        public override bool IsSingleService(Type serviceType)\n        {\n            return _parent.IsSingleService(serviceType);\n        }\n\n        public override object GetService(Type serviceType)\n        {\n            if (_overrideSingle != null)\n            {\n                object item;\n                if (_overrideSingle.TryGetValue(serviceType, out item))\n                {\n                    return item;\n                }\n            }\n            return _parent.GetService(serviceType);\n        }\n\n        public override IEnumerable<object> GetServices(Type serviceType)\n        {\n            if (_overrideMulti != null)\n            {\n                List<object> list;\n                if (_overrideMulti.TryGetValue(serviceType, out list))\n                {\n                    return list;\n                }\n            }\n            return _parent.GetServices(serviceType);\n        }\n\n        /// <inheritdoc/>\n        protected override void ReplaceSingle(Type serviceType, object service)\n        {\n            if (_overrideSingle == null)\n            {\n                _overrideSingle = new Dictionary<Type, object>();\n            }\n            _overrideSingle[serviceType] = service;\n        }\n\n        /// <inheritdoc/>\n        protected override void ClearSingle(Type serviceType)\n        {\n            if (_overrideSingle == null)\n            {\n                return;\n            }\n            _overrideSingle.Remove(serviceType);\n        }\n\n        // This is called to request a mutation to services.\n        [SuppressMessage(\"Microsoft.Design\", \"CA1002:DoNotExposeGenericLists\", Justification = \"want a mutable list\")]\n        protected override List<object> GetServiceInstances(Type serviceType)\n        {\n            if (_overrideMulti == null)\n            {\n                _overrideMulti = new Dictionary<Type, List<object>>();\n            }\n            List<object> list;\n            if (!_overrideMulti.TryGetValue(serviceType, out list))\n            {\n                // Copy parents list. \n                list = new List<object>(_parent.GetServices(serviceType));\n\n                // Copy into per-controller. If they're asking for the list, the expectation is that it's going to get mutated.\n                _overrideMulti[serviceType] = list;\n            }\n            return list;\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http/Services/Decorator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Services\n{\n    /// <summary>\n    /// Provides a method for retrieving the innermost object of an object that might be wrapped by an <see cref=\"IDecorator{T}\"/>.\n    /// </summary>\n    public static class Decorator\n    {\n        /// <summary>\n        /// Gets the innermost object which does not implement <see cref=\"IDecorator{T}\"/>.\n        /// </summary>\n        /// <param name=\"outer\">Object which needs to be unwrapped.</param>\n        /// <returns>The innermost object of Type T which does not implement <see cref=\"IDecorator{T}\"/>.</returns>\n        public static T GetInner<T>(T outer)\n        {\n            T inner = outer;\n            IDecorator<T> decorator = inner as IDecorator<T>;\n            while (decorator != null)\n            {\n                inner = decorator.Inner;\n                IDecorator<T> innerDecorator = inner as IDecorator<T>;\n                if (decorator == innerDecorator)\n                {\n                    break;\n                }\n                decorator = innerDecorator;\n            }\n\n            return inner;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Services/DefaultServices.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing System.Net.Http.Formatting;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Dependencies;\nusing System.Web.Http.Description;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Metadata.Providers;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.ModelBinding.Binders;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Tracing;\nusing System.Web.Http.Validation;\nusing System.Web.Http.Validation.Providers;\nusing System.Web.Http.ValueProviders;\nusing System.Web.Http.ValueProviders.Providers;\n\nnamespace System.Web.Http.Services\n{\n    /// <summary>\n    ///     <para>\n    ///         Represents a container for service instances used by the <see cref=\"HttpConfiguration\"/>. Note that\n    ///         this container only supports known types, and methods to get or set arbitrary service types will\n    ///         throw <see cref=\"ArgumentException\"/> when called. For creation of arbitrary types, please use\n    ///         <see cref=\"IDependencyResolver\"/> instead. The supported types for this container are:\n    ///     </para>\n    ///     <list type=\"bullet\">\n    ///         <item><see cref=\"IActionValueBinder\"/></item>\n    ///         <item><see cref=\"IApiExplorer\"/></item>\n    ///         <item><see cref=\"IAssembliesResolver\"/></item>\n    ///         <item><see cref=\"IBodyModelValidator\"/></item>\n    ///         <item><see cref=\"IContentNegotiator\"/></item>\n    ///         <item><see cref=\"IDocumentationProvider\"/></item>\n    ///         <item><see cref=\"IExceptionHandler\"/></item>\n    ///         <item><see cref=\"IExceptionLogger\"/></item>\n    ///         <item><see cref=\"IFilterProvider\"/></item>\n    ///         <item><see cref=\"IHostBufferPolicySelector\"/></item>\n    ///         <item><see cref=\"IHttpActionInvoker\"/></item>\n    ///         <item><see cref=\"IHttpActionSelector\"/></item>\n    ///         <item><see cref=\"IHttpControllerActivator\"/></item>\n    ///         <item><see cref=\"IHttpControllerSelector\"/></item>\n    ///         <item><see cref=\"IHttpControllerTypeResolver\"/></item>\n    ///         <item><see cref=\"ITraceManager\"/></item>\n    ///         <item><see cref=\"ITraceWriter\"/></item>\n    ///         <item><see cref=\"ModelBinderProvider\"/></item>\n    ///         <item><see cref=\"ModelMetadataProvider\"/></item>\n    ///         <item><see cref=\"ModelValidatorProvider\"/></item>\n    ///         <item><see cref=\"ValueProviderFactory\"/></item>\n    ///     </list>\n    ///     <para>\n    ///         Passing any type which is not on this to any method on this interface will cause\n    ///         an <see cref=\"ArgumentException\"/> to be thrown.\n    ///     </para>\n    /// </summary>\n    [SuppressMessage(\"Microsoft.Design\", \"CA1063:ImplementIDisposableCorrectly\", Justification = \"Although this class is not sealed, end users cannot set instances of it so in practice it is sealed.\")]\n    public class DefaultServices : ServicesContainer\n    {\n        private ConcurrentDictionary<Type, object[]> _cacheMulti = new ConcurrentDictionary<Type, object[]>();\n        private ConcurrentDictionary<Type, object> _cacheSingle = new ConcurrentDictionary<Type, object>();\n        private readonly HttpConfiguration _configuration;\n\n        // Mutation operations delegate (throw if applied to wrong set)\n        private readonly Dictionary<Type, object> _defaultServicesSingle = new Dictionary<Type, object>();\n\n        private readonly Dictionary<Type, List<object>> _defaultServicesMulti = new Dictionary<Type, List<object>>();\n        private IDependencyResolver _lastKnownDependencyResolver;\n        private readonly HashSet<Type> _serviceTypesSingle;\n        private readonly HashSet<Type> _serviceTypesMulti;\n\n        /// <summary>\n        /// This constructor is for unit testing purposes only.\n        /// </summary>\n        protected DefaultServices()\n        {\n        }\n\n        private void SetSingle<T>(T instance) where T : class\n        {\n            _defaultServicesSingle[typeof(T)] = instance;\n        }\n        private void SetMultiple<T>(params T[] instances) where T : class\n        {\n            var x = (IEnumerable<object>)instances;\n            _defaultServicesMulti[typeof(T)] = new List<object>(x);\n        }\n\n        [SuppressMessage(\"Microsoft.Maintainability\", \"CA1506:AvoidExcessiveClassCoupling\", Justification = \"Class needs references to large number of types.\")]\n        public DefaultServices(HttpConfiguration configuration)\n        {\n            if (configuration == null)\n            {\n                throw Error.ArgumentNull(\"configuration\");\n            }\n\n            _configuration = configuration;\n\n            // Initialize the dictionary with all known service types, even if the list for that service type is\n            // empty, because we will throw if the developer tries to read or write unsupported types.\n\n            SetSingle<IActionValueBinder>(new DefaultActionValueBinder());\n            SetSingle<IApiExplorer>(new ApiExplorer(configuration));\n            SetSingle<IAssembliesResolver>(new DefaultAssembliesResolver());\n            SetSingle<IBodyModelValidator>(new DefaultBodyModelValidator());\n            SetSingle<IContentNegotiator>(new DefaultContentNegotiator());\n            SetSingle<IDocumentationProvider>(null); // Missing\n\n            SetMultiple<IFilterProvider>(new ConfigurationFilterProvider(),\n                                      new ActionDescriptorFilterProvider());\n\n            SetSingle<IHostBufferPolicySelector>(null);\n            SetSingle<IHttpActionInvoker>(new ApiControllerActionInvoker());\n            SetSingle<IHttpActionSelector>(new ApiControllerActionSelector());\n            SetSingle<IHttpControllerActivator>(new DefaultHttpControllerActivator());\n            SetSingle<IHttpControllerSelector>(new DefaultHttpControllerSelector(configuration));\n            SetSingle<IHttpControllerTypeResolver>(new DefaultHttpControllerTypeResolver());\n            SetSingle<ITraceManager>(new TraceManager());\n            SetSingle<ITraceWriter>(null);\n\n            // This is a priority list. So put the most common binders at the top. \n            SetMultiple<ModelBinderProvider>(new TypeConverterModelBinderProvider(),\n                                        new TypeMatchModelBinderProvider(),\n                                        new KeyValuePairModelBinderProvider(),\n                                        new ComplexModelDtoModelBinderProvider(),\n                                        new ArrayModelBinderProvider(),\n                                        new DictionaryModelBinderProvider(),\n                                        new CollectionModelBinderProvider(),\n                                        new MutableObjectModelBinderProvider());\n            SetSingle<ModelMetadataProvider>(new DataAnnotationsModelMetadataProvider());\n            SetMultiple<ModelValidatorProvider>(new DataAnnotationsModelValidatorProvider(),\n                                        new DataMemberModelValidatorProvider());\n\n            // This is an ordered list,so put the most common providers at the top. \n            SetMultiple<ValueProviderFactory>(new QueryStringValueProviderFactory(),\n                                           new RouteDataValueProviderFactory());\n\n            ModelValidatorCache validatorCache = new ModelValidatorCache(new Lazy<IEnumerable<ModelValidatorProvider>>(() => this.GetModelValidatorProviders()));\n            SetSingle<IModelValidatorCache>(validatorCache);\n\n            SetSingle<IExceptionHandler>(new DefaultExceptionHandler());\n            SetMultiple<IExceptionLogger>();\n\n            _serviceTypesSingle = new HashSet<Type>(_defaultServicesSingle.Keys);\n            _serviceTypesMulti = new HashSet<Type>(_defaultServicesMulti.Keys);\n\n            // Reset the caches and the known dependency scope\n            ResetCache();\n        }\n\n        public override bool IsSingleService(Type serviceType)\n        {\n            if (serviceType == null)\n            {\n                throw Error.ArgumentNull(\"serviceType\");\n            }\n            return _serviceTypesSingle.Contains(serviceType);\n        }\n\n        /// <summary>\n        /// Try to get a service of the given type.\n        /// </summary>\n        /// <param name=\"serviceType\">The service type.</param>\n        /// <returns>The first instance of the service, or null if the service is not found.</returns>\n        public override object GetService(Type serviceType)\n        {\n            // Cached read case is very performance-sensitive\n            if (serviceType == null)\n            {\n                throw Error.ArgumentNull(\"serviceType\");\n            }\n\n            // Invalidate the cache if the dependency scope has switched\n            if (_lastKnownDependencyResolver != _configuration.DependencyResolver)\n            {\n                ResetCache();\n            }\n\n            object result;\n\n            if (_cacheSingle.TryGetValue(serviceType, out result))\n            {\n                return result;\n            }\n\n            // Check input after initial read attempt for performance.\n            if (!_serviceTypesSingle.Contains(serviceType))\n            {\n                throw Error.Argument(\"serviceType\", SRResources.DefaultServices_InvalidServiceType, serviceType.Name);\n            }\n\n            // Get the service from DI. If we're coming up hot, this might\n            // mean we end up creating the service more than once.\n            object dependencyService = _lastKnownDependencyResolver.GetService(serviceType);\n\n            if (!_cacheSingle.TryGetValue(serviceType, out result))\n            {\n                result = dependencyService ?? _defaultServicesSingle[serviceType];\n                _cacheSingle.TryAdd(serviceType, result);\n            }\n\n            return result;\n        }\n\n        /// <summary>\n        /// Try to get a list of services of the given type.\n        /// </summary>\n        /// <param name=\"serviceType\">The service type.</param>\n        /// <returns>The list of service instances of the given type. Returns an empty enumeration if the\n        /// service is not found. </returns>\n        public override IEnumerable<object> GetServices(Type serviceType)\n        {\n            // Cached read case is very performance-sensitive\n            if (serviceType == null)\n            {\n                throw Error.ArgumentNull(\"serviceType\");\n            }\n\n            // Invalidate the cache if the dependency scope has switched\n            if (_lastKnownDependencyResolver != _configuration.DependencyResolver)\n            {\n                ResetCache();\n            }\n\n            object[] result;\n\n            if (_cacheMulti.TryGetValue(serviceType, out result))\n            {\n                return result;\n            }\n\n            // Check input after initial read attempt for performance.\n            if (!_serviceTypesMulti.Contains(serviceType))\n            {\n                throw Error.Argument(\"serviceType\", SRResources.DefaultServices_InvalidServiceType, serviceType.Name);\n            }\n\n            // Get the service from DI. If we're coming up hot, this might\n            // mean we end up creating the service more than once.\n            IEnumerable<object> dependencyServices = _lastKnownDependencyResolver.GetServices(serviceType);\n\n            if (!_cacheMulti.TryGetValue(serviceType, out result))\n            {\n                result = dependencyServices.Where(s => s != null)\n                                            .Concat(_defaultServicesMulti[serviceType])\n                                            .ToArray();\n                _cacheMulti.TryAdd(serviceType, result);\n            }\n\n            return result;\n        }\n\n        // Returns the List<object> for the given service type. Also validates serviceType is in the known service type list.\n        [SuppressMessage(\"Microsoft.Design\", \"CA1002:DoNotExposeGenericLists\", Justification = \"inherits from base\")]\n        protected override List<object> GetServiceInstances(Type serviceType)\n        {\n            Contract.Assert(serviceType != null);\n\n            List<object> result;\n            if (!_defaultServicesMulti.TryGetValue(serviceType, out result))\n            {\n                throw Error.Argument(\"serviceType\", SRResources.DefaultServices_InvalidServiceType, serviceType.Name);\n            }\n\n            return result;\n        }\n\n        protected override void ClearSingle(Type serviceType)\n        {\n            _defaultServicesSingle[serviceType] = null;\n        }\n\n        protected override void ReplaceSingle(Type serviceType, object service)\n        {\n            if (serviceType == null)\n            {\n                throw Error.ArgumentNull(\"serviceType\");\n            }\n            _defaultServicesSingle[serviceType] = service;\n        }\n\n        // Removes the cached values for all service types. Called when the dependency scope\n        // has changed since the last time we made a request.\n        private void ResetCache()\n        {\n            _cacheSingle = new ConcurrentDictionary<Type, object>();\n            _cacheMulti = new ConcurrentDictionary<Type, object[]>();\n            _lastKnownDependencyResolver = _configuration.DependencyResolver;\n        }\n\n        // Removes the cached values for a single service type. Called whenever the user manipulates\n        // the local service list for a given service type.\n        protected override void ResetCache(Type serviceType)\n        {\n            object single;\n            _cacheSingle.TryRemove(serviceType, out single);\n            object[] multiple;\n            _cacheMulti.TryRemove(serviceType, out multiple);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Services/IDecorator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Services\n{\n    /// <summary>\n    /// Defines a decorator that exposes the inner decorated object.\n    /// </summary>\n    public interface IDecorator<out T>\n    {\n        /// <summary>\n        /// Gets the inner object.\n        /// </summary>\n        T Inner { get; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Services/ServicesContainer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.Controllers\n{\n    // This is common to both per-controller and global config. \n    // It facilitates sharing all the mutation operations between them.\n    public abstract class ServicesContainer : IDisposable\n    {\n        // Wrapped/composite versions of the exception service interfaces designed for consumption in catch blocks.\n        // See ExceptionServices.GetLogger/Handler for how these internal services are used.\n        // These instances must be stored separately and not provided via GetService because existing stores for \n        // GetService do not provide concurrency control and these two wrappers are potentially initialized late.\n        internal readonly Lazy<IExceptionLogger> ExceptionServicesLogger;\n        internal readonly Lazy<IExceptionHandler> ExceptionServicesHandler;\n\n        /// <summary>Initializes a new instance of the <see cref=\"ServicesContainer\"/> class.</summary>\n        protected ServicesContainer()\n        {\n            ExceptionServicesLogger = new Lazy<IExceptionLogger>(CreateExceptionServicesLogger);\n            ExceptionServicesHandler = new Lazy<IExceptionHandler>(CreateExceptionServicesHandler);\n        }\n\n        public abstract object GetService(Type serviceType);\n        public abstract IEnumerable<object> GetServices(Type serviceType);\n\n        // critical method for mutation operations (Add,Insert,Clear,Replace, etc)\n        // This is used for multi-services. \n        // There are other abstract methods to mutate the single services.\n        [SuppressMessage(\"Microsoft.Design\", \"CA1002:DoNotExposeGenericLists\", Justification = \"expose for mutation\")]\n        protected abstract List<object> GetServiceInstances(Type serviceType);\n\n        protected virtual void ResetCache(Type serviceType)\n        {\n        }\n\n        /// <summary>\n        /// Determine whether the service type should be fetched with GetService or GetServices. \n        /// </summary>\n        /// <param name=\"serviceType\">type of service to query</param>\n        /// <returns>true iff the service is singular. </returns>\n        public abstract bool IsSingleService(Type serviceType);\n\n        /// <summary>\n        /// Adds a service to the end of services list for the given service type. \n        /// </summary>\n        /// <param name=\"serviceType\">The service type.</param>\n        /// <param name=\"service\">The service instance.</param>\n        public void Add(Type serviceType, object service)\n        {\n            Insert(serviceType, Int32.MaxValue, service);\n        }\n\n        /// <summary>\n        /// Adds the services of the specified collection to the end of the services list for\n        /// the given service type.\n        /// </summary>\n        /// <param name=\"serviceType\">The service type.</param>\n        /// <param name=\"services\">The services to add.</param>\n        public void AddRange(Type serviceType, IEnumerable<object> services)\n        {\n            InsertRange(serviceType, Int32.MaxValue, services);\n        }\n\n        /// <summary>\n        /// Removes all the service instances of the given service type. \n        /// </summary>\n        /// <param name=\"serviceType\">The service type to clear from the services list.</param>\n        public virtual void Clear(Type serviceType)\n        {\n            if (serviceType == null)\n            {\n                throw Error.ArgumentNull(\"serviceType\");\n            }\n\n            if (IsSingleService(serviceType))\n            {\n                ClearSingle(serviceType);\n            }\n            else\n            {\n                ClearMultiple(serviceType);\n            }\n            ResetCache(serviceType);\n        }\n\n        protected abstract void ClearSingle(Type serviceType);\n\n        protected virtual void ClearMultiple(Type serviceType)\n        {\n            List<object> instances = GetServiceInstances(serviceType);\n            instances.Clear();\n        }\n\n        /// <summary>\n        /// Searches for a service that matches the conditions defined by the specified\n        /// predicate, and returns the zero-based index of the first occurrence.\n        /// </summary>\n        /// <param name=\"serviceType\">The service type.</param>\n        /// <param name=\"match\">The delegate that defines the conditions of the element\n        /// to search for. </param>\n        /// <returns>The zero-based index of the first occurrence, if found; otherwise, -1.</returns>\n        public int FindIndex(Type serviceType, Predicate<object> match)\n        {\n            if (serviceType == null)\n            {\n                throw Error.ArgumentNull(\"serviceType\");\n            }\n            if (match == null)\n            {\n                throw Error.ArgumentNull(\"match\");\n            }\n\n            List<object> instances = GetServiceInstances(serviceType);\n            return instances.FindIndex(match);\n        }\n\n        /// <summary>\n        /// Inserts a service into the collection at the specified index.\n        /// </summary>\n        /// <param name=\"serviceType\">The service type.</param>\n        /// <param name=\"index\">The zero-based index at which the service should be inserted.\n        /// If <see cref=\"Int32.MaxValue\"/> is passed, ensures the element is added to the end.</param>\n        /// <param name=\"service\">The service to insert.</param>\n        public void Insert(Type serviceType, int index, object service)\n        {\n            if (serviceType == null)\n            {\n                throw Error.ArgumentNull(\"serviceType\");\n            }\n            if (service == null)\n            {\n                throw Error.ArgumentNull(\"service\");\n            }\n            if (!serviceType.IsAssignableFrom(service.GetType()))\n            {\n                throw Error.Argument(\"service\", SRResources.Common_TypeMustDriveFromType, service.GetType().Name, serviceType.Name);\n            }\n\n            List<object> instances = GetServiceInstances(serviceType);\n            if (index == Int32.MaxValue)\n            {\n                index = instances.Count;\n            }\n\n            instances.Insert(index, service);\n\n            ResetCache(serviceType);\n        }\n\n        /// <summary>\n        /// Inserts the elements of the collection into the service list at the specified index.\n        /// </summary>\n        /// <param name=\"serviceType\">The service type.</param>\n        /// <param name=\"index\">The zero-based index at which the new elements should be inserted.\n        /// If <see cref=\"Int32.MaxValue\"/> is passed, ensures the elements are added to the end.</param>\n        /// <param name=\"services\">The collection of services to insert.</param>\n        public void InsertRange(Type serviceType, int index, IEnumerable<object> services)\n        {\n            if (serviceType == null)\n            {\n                throw Error.ArgumentNull(\"serviceType\");\n            }\n            if (services == null)\n            {\n                throw Error.ArgumentNull(\"services\");\n            }\n\n            object[] filteredServices = services.Where(svc => svc != null).ToArray();\n            object incorrectlyTypedService = filteredServices.FirstOrDefault(svc => !serviceType.IsAssignableFrom(svc.GetType()));\n            if (incorrectlyTypedService != null)\n            {\n                throw Error.Argument(\"services\", SRResources.Common_TypeMustDriveFromType, incorrectlyTypedService.GetType().Name, serviceType.Name);\n            }\n\n            List<object> instances = GetServiceInstances(serviceType);\n            if (index == Int32.MaxValue)\n            {\n                index = instances.Count;\n            }\n\n            instances.InsertRange(index, filteredServices);\n\n            ResetCache(serviceType);\n        }\n\n        /// <summary>\n        /// Removes the first occurrence of the given service from the service list for the given service type.\n        /// </summary>\n        /// <param name=\"serviceType\">The service type.</param>\n        /// <param name=\"service\">The service instance to remove.</param>\n        /// <returns> <c>true</c> if the item is successfully removed; otherwise, <c>false</c>.</returns>\n        public bool Remove(Type serviceType, object service)\n        {\n            if (serviceType == null)\n            {\n                throw Error.ArgumentNull(\"serviceType\");\n            }\n            if (service == null)\n            {\n                throw Error.ArgumentNull(\"service\");\n            }\n\n            List<object> instances = GetServiceInstances(serviceType);\n            bool result = instances.Remove(service);\n\n            ResetCache(serviceType);\n\n            return result;\n        }\n\n        /// <summary>\n        /// Removes all the elements that match the conditions defined by the specified predicate.\n        /// </summary>\n        /// <param name=\"serviceType\">The service type.</param>\n        /// <param name=\"match\">The delegate that defines the conditions of the elements to remove.</param>\n        /// <returns>The number of elements removed from the list.</returns>\n        public int RemoveAll(Type serviceType, Predicate<object> match)\n        {\n            if (serviceType == null)\n            {\n                throw Error.ArgumentNull(\"serviceType\");\n            }\n            if (match == null)\n            {\n                throw Error.ArgumentNull(\"match\");\n            }\n\n            List<object> instances = GetServiceInstances(serviceType);\n            int result = instances.RemoveAll(match);\n\n            ResetCache(serviceType);\n\n            return result;\n        }\n\n        /// <summary>\n        /// Removes the service at the specified index.\n        /// </summary>\n        /// <param name=\"serviceType\">The service type.</param>\n        /// <param name=\"index\">The zero-based index of the service to remove.</param>\n        public void RemoveAt(Type serviceType, int index)\n        {\n            if (serviceType == null)\n            {\n                throw Error.ArgumentNull(\"serviceType\");\n            }\n\n            List<object> instances = GetServiceInstances(serviceType);\n            instances.RemoveAt(index);\n\n            ResetCache(serviceType);\n        }\n\n        /// <summary>\n        /// Replaces all existing services for the given service type with the given\n        /// service instance. This works for both singular and plural services. \n        /// </summary>\n        /// <param name=\"serviceType\">The service type.</param>\n        /// <param name=\"service\">The service instance.</param>\n        /// <inheritdoc/>        \n        public void Replace(Type serviceType, object service)\n        {\n            // Check this early, so we don't call RemoveAll before Insert would catch the null service.\n            if (serviceType == null)\n            {\n                throw Error.ArgumentNull(\"serviceType\");\n            }\n\n            if ((service != null) && (!serviceType.IsAssignableFrom(service.GetType())))\n            {\n                throw Error.Argument(\"service\", SRResources.Common_TypeMustDriveFromType, service.GetType().Name, serviceType.Name);\n            }\n\n            if (IsSingleService(serviceType))\n            {\n                ReplaceSingle(serviceType, service);\n            }\n            else\n            {\n                ReplaceMultiple(serviceType, service);\n            }\n            ResetCache(serviceType);\n        }\n\n        protected abstract void ReplaceSingle(Type serviceType, object service);\n\n        protected virtual void ReplaceMultiple(Type serviceType, object service)\n        {\n            RemoveAll(serviceType, _ => true);\n            Insert(serviceType, 0, service);\n        }\n\n        /// <summary>\n        /// Replaces all existing services for the given service type with the given\n        /// service instances.\n        /// </summary>\n        /// <param name=\"serviceType\">The service type.</param>\n        /// <param name=\"services\">The service instances.</param>\n        public void ReplaceRange(Type serviceType, IEnumerable<object> services)\n        {\n            // Check this early, so we don't call RemoveAll before InsertRange would catch the null services.\n            if (services == null)\n            {\n                throw Error.ArgumentNull(\"services\");\n            }\n\n            RemoveAll(serviceType, _ => true);\n            InsertRange(serviceType, 0, services);\n        }\n\n        /// <inheritdoc/>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1063:ImplementIDisposableCorrectly\", Justification = \"Although this class is not sealed, end users cannot set instances of it so in practice it is sealed.\")]\n        [SuppressMessage(\"Microsoft.Usage\", \"CA1816:CallGCSuppressFinalizeCorrectly\", Justification = \"Although this class is not sealed, end users cannot set instances of it so in practice it is sealed.\")]\n        public virtual void Dispose()\n        {\n        }\n\n        private IExceptionLogger CreateExceptionServicesLogger()\n        {\n            return ExceptionServices.CreateLogger(this);\n        }\n\n        private IExceptionHandler CreateExceptionServicesHandler()\n        {\n            return ExceptionServices.CreateHandler(this);\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http/ServicesExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Description;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Tracing;\nusing System.Web.Http.Validation;\nusing System.Web.Http.ValueProviders;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// This provides a centralized list of type-safe accessors describing where and how we get services.\n    /// This also provides a single entry point for each service request. That makes it easy\n    /// to see which parts of the code use it, and provides a single place to comment usage.\n    /// Accessors encapsulate usage like:\n    /// <list type=\"bullet\">\n    /// <item>Type-safe using {T} instead of unsafe <see cref=\"System.Type\"/>.</item>\n    /// <item>which type do we key off? This is interesting with type hierarchies.</item>\n    /// <item>do we ask for singular or plural?</item>\n    /// <item>is it optional or mandatory?</item>\n    /// <item>what are the ordering semantics</item>\n    /// </list>\n    /// Expected that any <see cref=\"IEnumerable{T}\"/> we return is non-null, although possibly empty.\n    /// </summary>\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class ServicesExtensions\n    {\n        public static IEnumerable<ModelBinderProvider> GetModelBinderProviders(this ServicesContainer services)\n        {\n            return services.GetServices<ModelBinderProvider>();\n        }\n\n        public static ModelMetadataProvider GetModelMetadataProvider(this ServicesContainer services)\n        {\n            return services.GetServiceOrThrow<ModelMetadataProvider>();\n        }\n\n        public static IEnumerable<ModelValidatorProvider> GetModelValidatorProviders(this ServicesContainer services)\n        {\n            return services.GetServices<ModelValidatorProvider>();\n        }\n\n        internal static IModelValidatorCache GetModelValidatorCache(this ServicesContainer services)\n        {\n            return services.GetService<IModelValidatorCache>();\n        }\n\n        public static IContentNegotiator GetContentNegotiator(this ServicesContainer services)\n        {\n            return services.GetService<IContentNegotiator>();\n        }\n\n        /// <summary>\n        /// Controller activator is used to instantiate an <see cref=\"IHttpController\"/>.\n        /// </summary>\n        /// <returns>\n        /// An <see cref=\"IHttpControllerActivator\"/> instance or null if none are registered.\n        /// </returns>\n        public static IHttpControllerActivator GetHttpControllerActivator(this ServicesContainer services)\n        {\n            return services.GetServiceOrThrow<IHttpControllerActivator>();\n        }\n\n        public static IHttpActionSelector GetActionSelector(this ServicesContainer services)\n        {\n            return services.GetServiceOrThrow<IHttpActionSelector>();\n        }\n\n        public static IHttpActionInvoker GetActionInvoker(this ServicesContainer services)\n        {\n            return services.GetServiceOrThrow<IHttpActionInvoker>();\n        }\n\n        public static IActionValueBinder GetActionValueBinder(this ServicesContainer services)\n        {\n            return services.GetService<IActionValueBinder>();\n        }\n\n        /// <summary>\n        /// Get ValueProviderFactories. The order of returned providers is the priority order that we search the factories.\n        /// </summary>\n        public static IEnumerable<ValueProviderFactory> GetValueProviderFactories(this ServicesContainer services)\n        {\n            return services.GetServices<ValueProviderFactory>();\n        }\n\n        public static IBodyModelValidator GetBodyModelValidator(this ServicesContainer services)\n        {\n            return services.GetService<IBodyModelValidator>();\n        }\n\n        public static IHostBufferPolicySelector GetHostBufferPolicySelector(this ServicesContainer services)\n        {\n            return services.GetService<IHostBufferPolicySelector>();\n        }\n\n        /// <summary>\n        /// Get a controller selector, which selects an <see cref=\"HttpControllerDescriptor\"/> given an <see cref=\"HttpRequestMessage\"/>.\n        /// </summary>\n        public static IHttpControllerSelector GetHttpControllerSelector(this ServicesContainer services)\n        {\n            return services.GetServiceOrThrow<IHttpControllerSelector>();\n        }\n\n        public static IAssembliesResolver GetAssembliesResolver(this ServicesContainer services)\n        {\n            return services.GetServiceOrThrow<IAssembliesResolver>();\n        }\n\n        public static IHttpControllerTypeResolver GetHttpControllerTypeResolver(this ServicesContainer services)\n        {\n            return services.GetServiceOrThrow<IHttpControllerTypeResolver>();\n        }\n\n        public static IApiExplorer GetApiExplorer(this ServicesContainer services)\n        {\n            return services.GetServiceOrThrow<IApiExplorer>();\n        }\n\n        public static IDocumentationProvider GetDocumentationProvider(this ServicesContainer services)\n        {\n            return services.GetService<IDocumentationProvider>();\n        }\n\n        /// <summary>Returns the registered unhandled exception handler, if any.</summary>\n        /// <param name=\"services\">The services container.</param>\n        /// <returns>\n        /// The registered unhandled exception hander, if present; otherwise, <see langword=\"null\"/>.\n        /// </returns>\n        public static IExceptionHandler GetExceptionHandler(this ServicesContainer services)\n        {\n            return services.GetService<IExceptionHandler>();\n        }\n\n        /// <summary>Returns the collection of registered unhandled exception loggers.</summary>\n        /// <param name=\"services\">The services container.</param>\n        /// <returns>The collection of registered unhandled exception loggers.</returns>\n        public static IEnumerable<IExceptionLogger> GetExceptionLoggers(this ServicesContainer services)\n        {\n            return services.GetServices<IExceptionLogger>();\n        }\n\n        public static IEnumerable<IFilterProvider> GetFilterProviders(this ServicesContainer services)\n        {\n            return services.GetServices<IFilterProvider>();\n        }\n\n        public static ITraceManager GetTraceManager(this ServicesContainer services)\n        {\n            return services.GetService<ITraceManager>();\n        }\n\n        public static ITraceWriter GetTraceWriter(this ServicesContainer services)\n        {\n            return services.GetService<ITraceWriter>();\n        }\n\n        internal static IEnumerable<TService> GetServices<TService>(this ServicesContainer services)\n        {\n            if (services == null)\n            {\n                throw Error.ArgumentNull(\"services\");\n            }\n\n            return services.GetServices(typeof(TService)).Cast<TService>();\n        }\n\n        // Runtime code shouldn't call GetService() directly. Instead, have a wrapper (like the ones above)\n        // and call through the wrapper.\n        private static TService GetService<TService>(this ServicesContainer services)\n        {\n            if (services == null)\n            {\n                throw Error.ArgumentNull(\"services\");\n            }\n\n            return (TService)services.GetService(typeof(TService));\n        }\n\n        private static T GetServiceOrThrow<T>(this ServicesContainer services)\n        {\n            T result = services.GetService<T>();\n            if (result == null)\n            {\n                throw Error.InvalidOperation(SRResources.DependencyResolverNoService, typeof(T).FullName);\n            }\n\n            return result;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/SingleResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Runtime.CompilerServices;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Represents an <see cref=\"IQueryable\"/> containing zero or one entities. Use together with an\n    /// <c>[EnableQuery]</c> from the System.Web.Http.OData or System.Web.OData namespace.\n    /// </summary>\n    [TypeForwardedFrom(\"System.Web.Http.OData, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\")]\n    public abstract class SingleResult\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"SingleResult\"/> class.\n        /// </summary>\n        /// <param name=\"queryable\">The <see cref=\"IQueryable\"/> containing zero or one entities.</param>\n        protected SingleResult(IQueryable queryable)\n        {\n            if (queryable == null)\n            {\n                throw Error.ArgumentNull(\"queryable\");\n            }\n\n            Queryable = queryable;\n        }\n\n        /// <summary>\n        /// The <see cref=\"IQueryable\"/> containing zero or one entities.\n        /// </summary>\n        public IQueryable Queryable { get; private set; }\n\n        /// <summary>\n        /// Creates a <see cref=\"SingleResult{T}\"/> from an <see cref=\"IQueryable{T}\"/>. A helper method to instantiate\n        /// a <see cref=\"SingleResult{T}\"/> object without having to explicitly specify the type\n        /// <typeparamref name=\"T\"/>.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of the data in the data source.</typeparam>\n        /// <param name=\"queryable\">The <see cref=\"IQueryable{T}\"/> containing zero or one entities.</param>\n        /// <returns>The created <see cref=\"SingleResult{T}\"/>.</returns>\n        public static SingleResult<T> Create<T>(IQueryable<T> queryable)\n        {\n            return new SingleResult<T>(queryable);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/SingleResultOfT.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Runtime.CompilerServices;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Represents an <see cref=\"IQueryable{T}\"/> containing zero or one entities. Use together with an\n    /// <c>[EnableQuery]</c> from the System.Web.Http.OData or System.Web.OData namespace.\n    /// </summary>\n    /// <typeparam name=\"T\">The type of the data in the data source.</typeparam>\n    [TypeForwardedFrom(\"System.Web.Http.OData, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\")]\n    public sealed class SingleResult<T> : SingleResult\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"SingleResult{T}\"/> class.\n        /// </summary>\n        /// <param name=\"queryable\">The <see cref=\"IQueryable{T}\"/> containing zero or one entities.</param>\n        public SingleResult(IQueryable<T> queryable)\n            : base(queryable)\n        {\n        }\n\n        /// <summary>\n        /// The <see cref=\"IQueryable{T}\"/> containing zero or one entities.\n        /// </summary>\n        public new IQueryable<T> Queryable\n        {\n            get\n            {\n                return base.Queryable as IQueryable<T>;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/System.Web.Http.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{DDC1CE0C-486E-4E35-BB3B-EAB61F8F9440}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>System.Web.Http</RootNamespace>\n    <AssemblyName>System.Web.Http</AssemblyName>\n    <DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>\n    <RunCodeAnalysis>$(CodeAnalysis)</RunCodeAnalysis>\n    <CodeAnalysisRuleSet>..\\Strict.ruleset</CodeAnalysisRuleSet>\n    <DefineConstants>$(DefineConstants);ASPNETMVC;ASPNETWEBAPI</DefineConstants>\n    <NoWarn>1591</NoWarn>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Newtonsoft.Json.13.0.1\\lib\\net45\\Newtonsoft.Json.dll</HintPath>\n      <SpecificVersion>False</SpecificVersion>\n      <Private>False</Private>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.ComponentModel.DataAnnotations\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Data.Linq\" />\n    <Reference Include=\"System.Net.Http\" />\n    <Reference Include=\"System.Net.Http.WebRequest\" />\n    <Reference Include=\"System.Runtime.Serialization\" />\n    <Reference Include=\"System.Xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\CommonAssemblyInfo.cs\">\n      <Link>Properties\\CommonAssemblyInfo.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\CollectionExtensions.cs\">\n      <Link>Common\\CollectionExtensions.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\DictionaryExtensions.cs\">\n      <Link>Common\\DictionaryExtensions.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\EfficientTypePropertyKey.cs\">\n      <Link>Metadata\\EfficientTypePropertyKey.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Error.cs\">\n      <Link>Common\\Error.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\HttpMethodHelper.cs\">\n      <Link>Common\\HttpMethodHelper.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\ListWrapperCollection.cs\">\n      <Link>Common\\ListWrapperCollection.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\PrefixContainer.cs\">\n      <Link>Common\\PrefixContainer.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\PropertyHelper.cs\">\n      <Link>Routing\\PropertyHelper.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\DirectRouteBuilder.cs\">\n      <Link>Routing\\DirectRouteBuilder.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\DirectRouteFactoryContext.cs\">\n      <Link>Routing\\DirectRouteFactoryContext.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\IDirectRouteBuilder.cs\">\n      <Link>Routing\\IDirectRouteBuilder.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\IDirectRouteFactory.cs\">\n      <Link>Routing\\IDirectRouteFactory.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\IDirectRouteProvider.cs\">\n      <Link>Routing\\IDirectRouteProvider.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\IInlineConstraintResolver.cs\">\n      <Link>Routing\\IInlineConstraintResolver.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\RouteEntry.cs\">\n      <Link>Routing\\RouteEntry.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\RouteFactoryAttribute.cs\">\n      <Link>Routing\\RouteFactoryAttribute.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\RouteInfoDirectRouteFactory.cs\">\n      <Link>Routing\\RouteInfoDirectRouteFactory.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\RouteParser.cs\">\n      <Link>Routing\\RouteParser.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\RoutePrecedence.cs\">\n      <Link>Routing\\RoutePrecedence.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\TaskHelpers.cs\">\n      <Link>Common\\TaskHelpers.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\TaskHelpersExtensions.cs\">\n      <Link>Common\\TaskHelpersExtensions.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\TraceWriterExceptionMapper.cs\">\n      <Link>Tracing\\TraceWriterExceptionMapper.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\TypeExtensions.cs\">\n      <Link>Common\\TypeExtensions.cs</Link>\n    </Compile>\n    <Compile Include=\"AcceptVerbsAttribute.cs\" />\n    <Compile Include=\"Batch\\BatchExecutionOrder.cs\" />\n    <Compile Include=\"Batch\\BatchHttpRequestContext.cs\" />\n    <Compile Include=\"Batch\\HttpBatchHandler.cs\" />\n    <Compile Include=\"Batch\\DefaultHttpBatchHandler.cs\" />\n    <Compile Include=\"Batch\\BatchHttpRequestMessageExtensions.cs\" />\n    <Compile Include=\"Controllers\\ActionFilterResult.cs\" />\n    <Compile Include=\"Controllers\\AuthenticationFilterResult.cs\" />\n    <Compile Include=\"Controllers\\AuthorizationFilterResult.cs\" />\n    <Compile Include=\"Controllers\\ExceptionFilterResult.cs\" />\n    <Compile Include=\"Controllers\\HttpActionDescriptorExtensions.cs\" />\n    <Compile Include=\"Controllers\\HttpControllerDescriptorExtensions.cs\" />\n    <Compile Include=\"Controllers\\RequestBackedHttpRequestContext.cs\" />\n    <Compile Include=\"Controllers\\HttpControllerSettings.cs\" />\n    <Compile Include=\"Controllers\\HttpParameterDescriptorExtensions.cs\" />\n    <Compile Include=\"Controllers\\HttpRequestContext.cs\" />\n    <Compile Include=\"Controllers\\IActionResultConverter.cs\" />\n    <Compile Include=\"Controllers\\HttpActionContext.cs\" />\n    <Compile Include=\"Controllers\\IControllerConfiguration.cs\" />\n    <Compile Include=\"Description\\ResponseTypeAttribute.cs\" />\n    <Compile Include=\"Description\\ResponseDescription.cs\" />\n    <Compile Include=\"EmptyReadOnlyDictionary.cs\" />\n    <Compile Include=\"ExceptionHandling\\CompositeExceptionLogger.cs\" />\n    <Compile Include=\"ExceptionHandling\\ExceptionContextCatchBlock.cs\" />\n    <Compile Include=\"ExceptionHandling\\ExceptionHandlerExtensions.cs\" />\n    <Compile Include=\"ExceptionHandling\\ExceptionLogger.cs\" />\n    <Compile Include=\"ExceptionHandling\\DefaultExceptionHandler.cs\" />\n    <Compile Include=\"ExceptionHandling\\ExceptionContext.cs\" />\n    <Compile Include=\"ExceptionHandling\\ExceptionHandler.cs\" />\n    <Compile Include=\"ExceptionHandling\\ExceptionHandlerContext.cs\" />\n    <Compile Include=\"ExceptionHandling\\ExceptionLoggerExtensions.cs\" />\n    <Compile Include=\"ExceptionHandling\\ExceptionServices.cs\" />\n    <Compile Include=\"ExceptionHandling\\ExceptionCatchBlocks.cs\" />\n    <Compile Include=\"ExceptionHandling\\IExceptionHandler.cs\" />\n    <Compile Include=\"ExceptionHandling\\IExceptionLogger.cs\" />\n    <Compile Include=\"ExceptionHandling\\ExceptionLoggerContext.cs\" />\n    <Compile Include=\"ExceptionHandling\\EmptyExceptionHandler.cs\" />\n    <Compile Include=\"ExceptionHandling\\LastChanceExceptionHandler.cs\" />\n    <Compile Include=\"Filters\\HttpAuthenticationChallengeContext.cs\" />\n    <Compile Include=\"Properties\\SRResources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>SRResources.resx</DependentUpon>\n    </Compile>\n    <Compile Include=\"Results\\BadRequestResult.cs\" />\n    <Compile Include=\"Results\\RedirectToRouteResult.cs\" />\n    <Compile Include=\"Results\\RedirectResult.cs\" />\n    <Compile Include=\"Results\\CreatedAtRouteNegotiatedContentResult.cs\" />\n    <Compile Include=\"Results\\BadRequestErrorMessageResult.cs\" />\n    <Compile Include=\"Results\\JsonResult.cs\" />\n    <Compile Include=\"Results\\ConflictResult.cs\" />\n    <Compile Include=\"Results\\UnauthorizedResult.cs\" />\n    <Compile Include=\"Results\\ExceptionResult.cs\" />\n    <Compile Include=\"Results\\OkResult.cs\" />\n    <Compile Include=\"Results\\InternalServerErrorResult.cs\" />\n    <Compile Include=\"Results\\NotFoundResult.cs\" />\n    <Compile Include=\"Results\\CreatedNegotiatedContentResult.cs\" />\n    <Compile Include=\"Results\\OkNegotiatedContentResult.cs\" />\n    <Compile Include=\"Results\\InvalidModelStateResult.cs\" />\n    <Compile Include=\"Results\\FormattedContentResult.cs\" />\n    <Compile Include=\"Hosting\\SuppressHostPrincipalMessageHandler.cs\" />\n    <Compile Include=\"Results\\NegotiatedContentResult.cs\" />\n    <Compile Include=\"Results\\StatusCodeResult.cs\" />\n    <Compile Include=\"IHttpActionResult.cs\" />\n    <Compile Include=\"HttpErrorKeys.cs\" />\n    <Compile Include=\"Controllers\\FilterGrouping.cs\" />\n    <Compile Include=\"RoutePrefixAttribute.cs\" />\n    <Compile Include=\"Filters\\HttpAuthenticationContext.cs\" />\n    <Compile Include=\"Results\\ResponseMessageResult.cs\" />\n    <Compile Include=\"Filters\\IAuthenticationFilter.cs\" />\n    <Compile Include=\"Filters\\IOverrideFilter.cs\" />\n    <Compile Include=\"OverrideActionFiltersAttribute.cs\" />\n    <Compile Include=\"OverrideAuthenticationAttribute.cs\" />\n    <Compile Include=\"OverrideAuthorizationAttribute.cs\" />\n    <Compile Include=\"OverrideExceptionFiltersAttribute.cs\" />\n    <Compile Include=\"RouteAttribute.cs\" />\n    <Compile Include=\"Controllers\\CandidateAction.cs\" />\n    <Compile Include=\"Routing\\AttributeRoutingMapper.cs\" />\n    <Compile Include=\"Routing\\DefaultDirectRouteProvider.cs\" />\n    <Compile Include=\"Routing\\RouteValueKeys.cs\" />\n    <Compile Include=\"Routing\\RouteCollectionRoute.cs\" />\n    <Compile Include=\"Routing\\LinkGenerationRoute.cs\" />\n    <Compile Include=\"Routing\\HttpRouteDataExtensions.cs\" />\n    <Compile Include=\"Routing\\HttpRouteExtensions.cs\" />\n    <Compile Include=\"Routing\\RouteDataTokenKeys.cs\" />\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\AlphaRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\AlphaRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\BoolRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\BoolRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\CompoundRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\CompoundRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\DateTimeRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\DateTimeRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\DecimalRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\DecimalRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\DoubleRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\DoubleRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\FloatRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\FloatRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\GuidRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\GuidRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\IntRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\IntRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\LengthRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\LengthRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\LongRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\LongRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\MaxLengthRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\MaxLengthRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\MaxRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\MaxRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\MinLengthRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\MinLengthRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\MinRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\MinRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\RangeRouteConstraintBase.cs\">\n      <Link>Routing\\Constraints\\RangeRouteConstraintBase.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\RegexRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\RegexRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\OptionalRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\OptionalRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\DefaultInlineConstraintResolver.cs\">\n      <Link>Routing\\DefaultInlineConstraintResolver.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\InlineRouteTemplateParser.cs\">\n      <Link>Routing\\InlineRouteTemplateParser.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\SubRouteCollection.cs\">\n      <Link>Routing\\SubRouteCollection.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\IRoutePrefix.cs\">\n      <Link>Routing\\IRoutePrefix.cs</Link>\n    </Compile>\n    <Compile Include=\"Routing\\IHttpRouteInfoProvider.cs\" />\n    <Compile Include=\"Routing\\RoutingContext.cs\" />\n    <Compile Include=\"Routing\\StopRoutingHandler.cs\" />\n    <Compile Include=\"Services\\Decorator.cs\" />\n    <Compile Include=\"Services\\IDecorator.cs\" />\n    <Compile Include=\"SingleResult.cs\" />\n    <Compile Include=\"SingleResultOfT.cs\" />\n    <Compile Include=\"Tracing\\TraceLevelHelper.cs\" />\n    <Compile Include=\"Tracing\\TraceKindHelper.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\AuthenticationFilterTracer.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\FormatterLoggerTraceWrapper.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\DefaultHttpControllerTypeResolverTracer.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\OverrideFilterTracer.cs\" />\n    <Compile Include=\"Validation\\BodyModelValidatorContext.cs\" />\n    <Compile Include=\"Validation\\IModelValidatorCache.cs\" />\n    <Compile Include=\"Validation\\IBodyModelValidatorKeyBuilder.cs\" />\n    <Compile Include=\"Validation\\ModelValidatorCache.cs\" />\n    <Compile Include=\"Controllers\\ResponseMessageResultConverter.cs\" />\n    <Compile Include=\"Controllers\\ValueResultConverter.cs\" />\n    <Compile Include=\"Controllers\\VoidResultConverter.cs\" />\n    <Compile Include=\"Dependencies\\IDependencyScope.cs\" />\n    <Compile Include=\"Dispatcher\\DefaultAssembliesResolver.cs\" />\n    <Compile Include=\"Dispatcher\\HttpRoutingDispatcher.cs\" />\n    <Compile Include=\"Dispatcher\\IAssembliesResolver.cs\" />\n    <Compile Include=\"Hosting\\IHostBufferPolicySelector.cs\" />\n    <Compile Include=\"HttpConfigurationExtensions.cs\" />\n    <Compile Include=\"HttpOptionsAttribute.cs\" />\n    <Compile Include=\"HttpHeadAttribute.cs\" />\n    <Compile Include=\"HttpPatchAttribute.cs\" />\n    <Compile Include=\"Description\\ApiDescription.cs\" />\n    <Compile Include=\"Description\\ApiExplorer.cs\" />\n    <Compile Include=\"Description\\ApiExplorerSettingsAttribute.cs\" />\n    <Compile Include=\"Description\\ApiParameterDescription.cs\" />\n    <Compile Include=\"Description\\ApiParameterSource.cs\" />\n    <Compile Include=\"Description\\IDocumentationProvider.cs\" />\n    <Compile Include=\"Description\\IApiExplorer.cs\" />\n    <Compile Include=\"IncludeErrorDetailPolicy.cs\" />\n    <Compile Include=\"Filters\\HttpActionExecutedContext.cs\" />\n    <Compile Include=\"Internal\\HttpParameterBindingExtensions.cs\" />\n    <Compile Include=\"ModelBinding\\FormatterParameterBinding.cs\" />\n    <Compile Include=\"ModelBinding\\CancellationTokenParameterBinding.cs\" />\n    <Compile Include=\"ModelBinding\\ErrorParameterBinding.cs\" />\n    <Compile Include=\"ModelBinding\\FormDataCollectionExtensions.cs\" />\n    <Compile Include=\"Controllers\\HttpActionBinding.cs\" />\n    <Compile Include=\"Controllers\\HttpActionDescriptor.cs\" />\n    <Compile Include=\"ActionNameAttribute.cs\" />\n    <Compile Include=\"Controllers\\ReflectedHttpActionDescriptor.cs\" />\n    <Compile Include=\"AllowAnonymousAttribute.cs\" />\n    <Compile Include=\"HttpError.cs\" />\n    <Compile Include=\"HttpResponseException.cs\" />\n    <Compile Include=\"ModelBinding\\HttpRequestParameterBinding.cs\" />\n    <Compile Include=\"ModelBinding\\IValueProviderParameterBinding.cs\" />\n    <Compile Include=\"ModelBinding\\JQueryMVCFormUrlEncodedFormatter.cs\" />\n    <Compile Include=\"ModelBinding\\ModelBinderParameterBinding.cs\" />\n    <Compile Include=\"ModelBinding\\ParameterBindingRulesCollection.cs\" />\n    <Compile Include=\"ParameterBindingAttribute.cs\" />\n    <Compile Include=\"HttpResponseMessageExtensions.cs\" />\n    <Compile Include=\"Dispatcher\\DefaultHttpControllerActivator.cs\" />\n    <Compile Include=\"Controllers\\HttpControllerDescriptor.cs\" />\n    <Compile Include=\"Dispatcher\\IHttpControllerActivator.cs\" />\n    <Compile Include=\"HttpRouteCollection.cs\" />\n    <Compile Include=\"HttpPutAttribute.cs\" />\n    <Compile Include=\"HttpDeleteAttribute.cs\" />\n    <Compile Include=\"Controllers\\IActionHttpMethodProvider.cs\" />\n    <Compile Include=\"Controllers\\ApiControllerActionInvoker.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"AuthorizeAttribute.cs\" />\n    <Compile Include=\"HttpGetAttribute.cs\" />\n    <Compile Include=\"HttpPostAttribute.cs\" />\n    <Compile Include=\"HttpRequestMessageExtensions.cs\" />\n    <Compile Include=\"Filters\\HttpFilterCollection.cs\" />\n    <Compile Include=\"Filters\\IFilter.cs\" />\n    <Compile Include=\"HttpServer.cs\" />\n    <Compile Include=\"Internal\\TypeActivator.cs\" />\n    <Compile Include=\"ModelBinding\\DefaultActionValueBinder.cs\" />\n    <Compile Include=\"Controllers\\IHttpActionInvoker.cs\" />\n    <Compile Include=\"Controllers\\IActionValueBinder.cs\" />\n    <Compile Include=\"Controllers\\IHttpActionSelector.cs\" />\n    <Compile Include=\"Filters\\ActionFilterAttribute.cs\" />\n    <Compile Include=\"Filters\\AuthorizationFilterAttribute.cs\" />\n    <Compile Include=\"Filters\\ExceptionFilterAttribute.cs\" />\n    <Compile Include=\"Filters\\ActionDescriptorFilterProvider.cs\" />\n    <Compile Include=\"Filters\\FilterInfo.cs\" />\n    <Compile Include=\"Filters\\FilterInfoComparer.cs\" />\n    <Compile Include=\"Filters\\FilterScope.cs\" />\n    <Compile Include=\"Filters\\ConfigurationFilterProvider.cs\" />\n    <Compile Include=\"Filters\\IActionFilter.cs\" />\n    <Compile Include=\"Filters\\IAuthorizationFilter.cs\" />\n    <Compile Include=\"Filters\\IExceptionFilter.cs\" />\n    <Compile Include=\"Filters\\IFilterProvider.cs\" />\n    <Compile Include=\"Internal\\MemberInfoExtensions.cs\" />\n    <Compile Include=\"ModelBinding\\Binders\\CompositeModelBinderProvider.cs\" />\n    <Compile Include=\"ModelBinding\\Binders\\CompositeModelBinder.cs\" />\n    <Compile Include=\"HttpRouteCollectionExtensions.cs\" />\n    <Compile Include=\"RouteParameter.cs\" />\n    <Compile Include=\"Routing\\BoundRouteTemplate.cs\" />\n    <Compile Include=\"Routing\\IHttpVirtualPathData.cs\" />\n    <Compile Include=\"Routing\\IHttpRouteData.cs\" />\n    <Compile Include=\"Routing\\IHttpRoute.cs\" />\n    <Compile Include=\"Routing\\HttpMethodConstraint.cs\" />\n    <Compile Include=\"Routing\\HttpParsedRoute.cs\" />\n    <Compile Include=\"Routing\\HttpRoute.cs\" />\n    <Compile Include=\"Routing\\HttpRouteData.cs\" />\n    <Compile Include=\"Routing\\HttpRouteDirection.cs\" />\n    <Compile Include=\"Routing\\HttpRouteValueDictionary.cs\" />\n    <Compile Include=\"Routing\\HttpVirtualPathData.cs\" />\n    <Compile Include=\"Routing\\IHttpRouteConstraint.cs\" />\n    <Compile Include=\"Routing\\MediaTypeFormatterExtensions.cs\" />\n    <Compile Include=\"..\\Common\\Routing\\PathContentSegment.cs\">\n      <Link>Routing\\PathContentSegment.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\PathLiteralSubsegment.cs\">\n      <Link>Routing\\PathLiteralSubsegment.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\PathParameterSubsegment.cs\">\n      <Link>Routing\\PathParameterSubsegment.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\PathSegment.cs\">\n      <Link>Routing\\PathSegment.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\PathSeparatorSegment.cs\">\n      <Link>Routing\\PathSeparatorSegment.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\PathSubsegment.cs\">\n      <Link>Routing\\PathSubsegment.cs</Link>\n    </Compile>\n    <Compile Include=\"NonActionAttribute.cs\" />\n    <Compile Include=\"Routing\\UriPathExtensionMapping.cs\" />\n    <Compile Include=\"Routing\\UrlHelper.cs\" />\n    <Compile Include=\"Dispatcher\\HttpControllerTypeCache.cs\" />\n    <Compile Include=\"Dispatcher\\DefaultHttpControllerSelector.cs\" />\n    <Compile Include=\"Dispatcher\\DefaultHttpControllerTypeResolver.cs\" />\n    <Compile Include=\"ServicesExtensions.cs\" />\n    <Compile Include=\"Dependencies\\EmptyResolver.cs\" />\n    <Compile Include=\"Dependencies\\IDependencyResolver.cs\" />\n    <Compile Include=\"Dispatcher\\IHttpControllerSelector.cs\" />\n    <Compile Include=\"Filters\\FilterAttribute.cs\" />\n    <Compile Include=\"Hosting\\HttpPropertyKeys.cs\" />\n    <Compile Include=\"Dispatcher\\HttpControllerDispatcher.cs\" />\n    <Compile Include=\"Dispatcher\\IHttpControllerTypeResolver.cs\" />\n    <Compile Include=\"Internal\\TypeHelper.cs\" />\n    <Compile Include=\"Internal\\ParameterInfoExtensions.cs\" />\n    <Compile Include=\"Controllers\\ReflectedHttpParameterDescriptor.cs\" />\n    <Compile Include=\"HttpBindNeverAttribute.cs\" />\n    <Compile Include=\"HttpBindRequiredAttribute.cs\" />\n    <Compile Include=\"Controllers\\HttpActionContextExtensions.cs\" />\n    <Compile Include=\"ModelBinding\\ModelBindingHelper.cs\" />\n    <Compile Include=\"Controllers\\ApiControllerActionSelector.cs\" />\n    <Compile Include=\"Controllers\\HttpParameterBinding.cs\" />\n    <Compile Include=\"Controllers\\HttpParameterDescriptor.cs\" />\n    <Compile Include=\"Services\\ControllerServices.cs\" />\n    <Compile Include=\"Services\\DefaultServices.cs\" />\n    <Compile Include=\"GlobalSuppressions.cs\" />\n    <Compile Include=\"Controllers\\IHttpController.cs\" />\n    <Compile Include=\"Internal\\TypeDescriptorHelper.cs\" />\n    <Compile Include=\"Internal\\CollectionModelBinderUtil.cs\" />\n    <Compile Include=\"Metadata\\Providers\\AssociatedMetadataProvider.cs\" />\n    <Compile Include=\"Metadata\\Providers\\CachedDataAnnotationsMetadataAttributes.cs\" />\n    <Compile Include=\"Metadata\\Providers\\CachedModelMetadata.cs\" />\n    <Compile Include=\"Metadata\\ModelMetadata.cs\" />\n    <Compile Include=\"Metadata\\ModelMetadataProvider.cs\" />\n    <Compile Include=\"Metadata\\Providers\\CachedDataAnnotationsModelMetadata.cs\" />\n    <Compile Include=\"Metadata\\Providers\\DataAnnotationsModelMetadataProvider.cs\" />\n    <Compile Include=\"Metadata\\Providers\\EmptyMetadataProvider.cs\" />\n    <Compile Include=\"ModelBinding\\Binders\\ArrayModelBinderProvider.cs\" />\n    <Compile Include=\"ModelBinding\\Binders\\ArrayModelBinder.cs\" />\n    <Compile Include=\"ModelBinding\\HttpBindingBehavior.cs\" />\n    <Compile Include=\"ModelBinding\\HttpBindingBehaviorAttribute.cs\" />\n    <Compile Include=\"ModelBinding\\Binders\\CollectionModelBinderProvider.cs\" />\n    <Compile Include=\"ModelBinding\\Binders\\CollectionModelBinder.cs\" />\n    <Compile Include=\"ModelBinding\\Binders\\ComplexModelDto.cs\" />\n    <Compile Include=\"ModelBinding\\Binders\\ComplexModelDtoModelBinder.cs\" />\n    <Compile Include=\"ModelBinding\\Binders\\ComplexModelDtoModelBinderProvider.cs\" />\n    <Compile Include=\"ModelBinding\\Binders\\ComplexModelDtoResult.cs\" />\n    <Compile Include=\"ModelBinding\\Binders\\DictionaryModelBinderProvider.cs\" />\n    <Compile Include=\"ModelBinding\\Binders\\DictionaryModelBinder.cs\" />\n    <Compile Include=\"ModelBinding\\ModelBinderAttribute.cs\" />\n    <Compile Include=\"ModelBinding\\CustomModelBinderAttribute.cs\" />\n    <Compile Include=\"ModelBinding\\ModelBindingContext.cs\" />\n    <Compile Include=\"ModelBinding\\IModelBinder.cs\" />\n    <Compile Include=\"ModelBinding\\Binders\\KeyValuePairModelBinderProvider.cs\" />\n    <Compile Include=\"ModelBinding\\Binders\\KeyValuePairModelBinder.cs\" />\n    <Compile Include=\"ModelBinding\\ModelBinderConfig.cs\" />\n    <Compile Include=\"ModelBinding\\ModelBinderErrorMessageProvider.cs\" />\n    <Compile Include=\"ModelBinding\\ModelBinderProvider.cs\" />\n    <Compile Include=\"Controllers\\HttpControllerContext.cs\" />\n    <Compile Include=\"ModelBinding\\ModelError.cs\" />\n    <Compile Include=\"ModelBinding\\ModelErrorCollection.cs\" />\n    <Compile Include=\"ModelBinding\\ModelState.cs\" />\n    <Compile Include=\"ModelBinding\\ModelStateDictionary.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"Services\\ServicesContainer.cs\" />\n    <Compile Include=\"Tracing\\IFormatterTracer.cs\" />\n    <Compile Include=\"Tracing\\ITraceManager.cs\" />\n    <Compile Include=\"Tracing\\ITraceWriter.cs\" />\n    <Compile Include=\"Tracing\\ITraceWriterExtensions.cs\" />\n    <Compile Include=\"Tracing\\TraceManager.cs\" />\n    <Compile Include=\"Tracing\\TraceCategories.cs\" />\n    <Compile Include=\"Tracing\\TraceKind.cs\" />\n    <Compile Include=\"Tracing\\TraceLevel.cs\" />\n    <Compile Include=\"Tracing\\TraceRecord.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\HttpActionBindingTracer.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\HttpActionDescriptorTracer.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\ActionFilterAttributeTracer.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\ActionFilterTracer.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\HttpActionInvokerTracer.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\HttpActionSelectorTracer.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\ActionValueBinderTracer.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\HttpControllerDescriptorTracer.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\HttpControllerTracer.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\AuthorizationFilterAttributeTracer.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\AuthorizationFilterTracer.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\BufferedMediaTypeFormatterTracer.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\HttpControllerActivatorTracer.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\HttpControllerSelectorTracer.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\ExceptionFilterAttributeTracer.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\ExceptionFilterTracer.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\FilterTracer.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\ContentNegotiatorTracer.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\FormatterParameterBindingTracer.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\FormUrlEncodedMediaTypeFormatterTracer.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\HttpParameterBindingTracer.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\JsonMediaTypeFormatterTracer.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\MediaTypeFormatterTracer.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\MessageHandlerTracer.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\RequestMessageHandlerTracer.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\XmlMediaTypeFormatterTracer.cs\" />\n    <Compile Include=\"Tracing\\FormattingUtilities.cs\" />\n    <Compile Include=\"Validation\\DefaultBodyModelValidator.cs\" />\n    <Compile Include=\"Validation\\IBodyModelValidator.cs\" />\n    <Compile Include=\"Validation\\ModelStateFormatterLogger.cs\" />\n    <Compile Include=\"Validation\\ModelValidatedEventArgs.cs\" />\n    <Compile Include=\"Validation\\ModelValidatingEventArgs.cs\" />\n    <Compile Include=\"Validation\\ModelValidationNode.cs\" />\n    <Compile Include=\"ModelBinding\\Binders\\MutableObjectModelBinder.cs\" />\n    <Compile Include=\"ModelBinding\\Binders\\MutableObjectModelBinderProvider.cs\" />\n    <Compile Include=\"ModelBinding\\Binders\\SimpleModelBinderProvider.cs\" />\n    <Compile Include=\"ModelBinding\\Binders\\TypeConverterModelBinder.cs\" />\n    <Compile Include=\"ModelBinding\\Binders\\TypeConverterModelBinderProvider.cs\" />\n    <Compile Include=\"ModelBinding\\Binders\\TypeMatchModelBinder.cs\" />\n    <Compile Include=\"ModelBinding\\Binders\\TypeMatchModelBinderProvider.cs\" />\n    <Compile Include=\"Validation\\ModelValidationRequiredMemberSelector.cs\" />\n    <Compile Include=\"Validation\\ModelValidationResult.cs\" />\n    <Compile Include=\"Validation\\ModelValidator.cs\" />\n    <Compile Include=\"Validation\\ModelValidatorProvider.cs\" />\n    <Compile Include=\"Validation\\Providers\\AssociatedValidatorProvider.cs\" />\n    <Compile Include=\"Validation\\Providers\\DataAnnotationsModelValidatorProvider.cs\" />\n    <Compile Include=\"Validation\\Providers\\DataMemberModelValidatorProvider.cs\" />\n    <Compile Include=\"Validation\\Providers\\InvalidModelValidatorProvider.cs\" />\n    <Compile Include=\"Validation\\Providers\\RequiredMemberModelValidatorProvider.cs\" />\n    <Compile Include=\"Validation\\ReferenceEqualityComparer.cs\" />\n    <Compile Include=\"Validation\\Validators\\ErrorModelValidator.cs\" />\n    <Compile Include=\"Validation\\Validators\\RequiredMemberModelValidator.cs\" />\n    <Compile Include=\"Validation\\Validators\\ValidatableObjectAdapter.cs\" />\n    <Compile Include=\"Validation\\Validators\\DataAnnotationsModelValidator.cs\" />\n    <Compile Include=\"FromBodyAttribute.cs\" />\n    <Compile Include=\"FromUriAttribute.cs\" />\n    <Compile Include=\"ValueProviders\\IUriValueProviderFactory.cs\" />\n    <Compile Include=\"ValueProviders\\Providers\\CompositeValueProvider.cs\" />\n    <Compile Include=\"ValueProviders\\Providers\\CompositeValueProviderFactory.cs\" />\n    <Compile Include=\"ValueProviders\\Providers\\NameValuePairsValueProvider.cs\" />\n    <Compile Include=\"ValueProviders\\Providers\\ElementalValueProvider.cs\" />\n    <Compile Include=\"ValueProviders\\IEnumerableValueProvider.cs\" />\n    <Compile Include=\"ValueProviders\\Providers\\RouteDataValueProvider.cs\" />\n    <Compile Include=\"ValueProviders\\Providers\\RouteDataValueProviderFactory.cs\" />\n    <Compile Include=\"ValueProviders\\ValueProviderFactory.cs\" />\n    <Compile Include=\"ValueProviders\\Providers\\QueryStringValueProvider.cs\" />\n    <Compile Include=\"ValueProviders\\Providers\\QueryStringValueProviderFactory.cs\" />\n    <Compile Include=\"ValueProviders\\ValueProviderAttribute.cs\" />\n    <Compile Include=\"ValueProviders\\ValueProviderResult.cs\" />\n    <Compile Include=\"ValueProviders\\IValueProvider.cs\" />\n    <Compile Include=\"HttpConfiguration.cs\" />\n    <Compile Include=\"ApiController.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <CodeAnalysisDictionary Include=\"..\\CodeAnalysisDictionary.xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\Common\\CommonWebApiResources.Designer.cs\">\n      <Link>Properties\\CommonWebApiResources.Designer.cs</Link>\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>CommonWebApiResources.resx</DependentUpon>\n    </Compile>\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"..\\Common\\CommonWebApiResources.resx\">\n      <Link>Properties\\CommonWebApiResources.resx</Link>\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>CommonWebApiResources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"Properties\\SRResources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <SubType>Designer</SubType>\n      <LastGenOutput>SRResources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\System.Net.Http.Formatting\\System.Net.Http.Formatting.csproj\">\n      <Project>{668E9021-CE84-49D9-98FB-DF125A9FCDB0}</Project>\n      <Name>System.Net.Http.Formatting</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n</Project>"
  },
  {
    "path": "src/System.Web.Http/Tracing/FormattingUtilities.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Linq;\nusing System.Net.Http.Formatting;\nusing System.Text;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.ModelBinding.Binders;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Routing;\nusing System.Web.Http.ValueProviders;\nusing System.Web.Http.ValueProviders.Providers;\n\nnamespace System.Web.Http.Tracing\n{\n    /// <summary>\n    /// General purpose utilities to format strings used in tracing.\n    /// </summary>\n    internal static class FormattingUtilities\n    {\n        public static readonly string NullMessage = \"null\";\n\n        public static string ActionArgumentsToString(IDictionary<string, object> actionArguments)\n        {\n            Contract.Assert(actionArguments != null);\n            return String.Join(\", \",\n                               actionArguments.Keys.Select<string, string>(\n                                   (k) => k + \"=\" + ValueToString(actionArguments[k], CultureInfo.CurrentCulture)));\n        }\n\n        public static string ActionDescriptorToString(HttpActionDescriptor actionDescriptor)\n        {\n            Contract.Assert(actionDescriptor != null);\n\n            string parameterList = String.Join(\", \",\n                                               actionDescriptor.GetParameters().Select<HttpParameterDescriptor, string>(\n                                                   (p) => p.ParameterType.Name + \" \" + p.ParameterName));\n\n            return actionDescriptor.ActionName + \"(\" + parameterList + \")\";\n        }\n\n        public static string ActionInvokeToString(HttpActionContext actionContext)\n        {\n            Contract.Assert(actionContext != null);\n            return ActionInvokeToString(actionContext.ActionDescriptor.ActionName, actionContext.ActionArguments);\n        }\n\n        public static string ActionInvokeToString(string actionName, IDictionary<string, object> arguments)\n        {\n            Contract.Assert(actionName != null);\n            Contract.Assert(arguments != null);\n\n            return actionName + \"(\" + ActionArgumentsToString(arguments) + \")\";\n        }\n\n        public static string FormattersToString(IEnumerable<MediaTypeFormatter> formatters)\n        {\n            Contract.Assert(formatters != null);\n\n            return String.Join(\", \", formatters.Select<MediaTypeFormatter, string>((f) => f.GetType().Name));\n        }\n\n        public static string ModelBinderToString(ModelBinderProvider provider)\n        {\n            Contract.Assert(provider != null);\n\n            CompositeModelBinderProvider composite = provider as CompositeModelBinderProvider;\n            if (composite == null)\n            {\n                return provider.GetType().Name;\n            }\n\n            string modelBinderList = String.Join(\", \", composite.Providers.Select<ModelBinderProvider, string>(ModelBinderToString));\n\n            return provider.GetType().Name + \"(\" + modelBinderList + \")\";\n        }\n\n        public static string ModelStateToString(ModelStateDictionary modelState)\n        {\n            Contract.Assert(modelState != null);\n\n            if (modelState.IsValid)\n            {\n                return String.Empty;\n            }\n\n            StringBuilder modelStateBuilder = new StringBuilder();\n            foreach (string key in modelState.Keys)\n            {\n                ModelState state = modelState[key];\n                if (state.Errors.Count > 0)\n                {\n                    foreach (ModelError error in state.Errors)\n                    {\n                        string errorString = Error.Format(SRResources.TraceModelStateErrorMessage, \n                                                           key,\n                                                           error.ErrorMessage);\n                        if (modelStateBuilder.Length > 0)\n                        {\n                            modelStateBuilder.Append(',');\n                        }\n\n                        modelStateBuilder.Append(errorString);\n                    }\n                }\n            }\n\n            return modelStateBuilder.ToString();\n        }\n\n        public static string RouteToString(IHttpRouteData routeData)\n        {\n            Contract.Assert(routeData != null);\n\n            return String.Join(\",\", routeData.Values.Select((pair) => Error.Format(\"{0}:{1}\", pair.Key, pair.Value)));\n        }\n\n        public static string ValueProviderToString(IValueProvider provider)\n        {\n            Contract.Assert(provider != null);\n\n            CompositeValueProvider composite = provider as CompositeValueProvider;\n            if (composite == null)\n            {\n                return provider.GetType().Name;\n            }\n\n            string providerList = String.Join(\", \", composite.Select<IValueProvider, string>(ValueProviderToString));\n            return provider.GetType().Name + \"(\" + providerList + \")\";\n        }\n\n        public static string ValueToString(object value, CultureInfo cultureInfo)\n        {\n            Contract.Assert(cultureInfo != null);\n\n            if (value == null)\n            {\n                return NullMessage;\n            }\n\n            return Convert.ToString(value, cultureInfo);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/IFormatterTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Web.Http.Tracing.Tracers;\n\nnamespace System.Web.Http.Tracing\n{\n    /// <summary>\n    /// Interface used to mark <see cref=\"MediaTypeFormatterTracer\"/> classes.\n    /// </summary>\n    internal interface IFormatterTracer\n    {\n        /// <summary>\n        /// Gets the associated <see cref=\"HttpRequestMessage\"/>.\n        /// </summary>\n        HttpRequestMessage Request { get; }\n\n        /// <summary>\n        /// Gets the inner <see cref=\"MediaTypeFormatter\"/> this tracer is monitoring.\n        /// </summary>\n        MediaTypeFormatter InnerFormatter { get; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/ITraceManager.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Tracing\n{\n    /// <summary>\n    /// Interface to initialize the tracing layer.\n    /// </summary>\n    /// <remarks>\n    /// This is an extensibility interface that may be inserted into\n    /// <see cref=\"HttpConfiguration.Services\"/> to provide a replacement for the\n    /// entire tracing layer.\n    /// </remarks>\n    public interface ITraceManager\n    {\n        void Initialize(HttpConfiguration configuration);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/ITraceWriter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\n\nnamespace System.Web.Http.Tracing\n{\n    /// <summary>\n    /// Interface to write <see cref=\"TraceRecord\"/> instances.\n    /// </summary>\n    public interface ITraceWriter\n    {\n        /// <summary>\n        /// Creates and writes a new <see cref=\"TraceRecord\"/> to the current <see cref=\"ITraceWriter\"/>\n        /// if tracing is enabled for the given <paramref name=\"category\"/> and <paramref name=\"level\"/>.\n        /// </summary>\n        /// <remarks>\n        /// The decision whether tracing is enabled for a specific category and level\n        /// is an implementation detail of each individual <see cref=\"ITraceWriter\"/>.\n        /// <para>\n        /// If the current <see cref=\"ITraceWriter\"/> decides tracing is enabled for the given \n        /// category and level, it will construct a new <see cref=\"TraceRecord\"/> and invoke \n        /// the caller's <paramref name=\"traceAction\"/> to allow the caller to fill in additional\n        /// information.\n        /// </para>\n        /// <para>\n        /// If the current <see cref=\"ITraceWriter\"/> decides tracing is not enabled for the given\n        /// category and level, no <see cref=\"TraceRecord\"/> will be created,\n        /// and the <paramref name=\"traceAction\"/> will not be called.\n        /// </para> \n        /// </remarks>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/> with which to associate\n        /// the <see cref=\"TraceRecord\"/>.  It may be <c>null</c> but doing so will result in\n        /// a <see cref=\"TraceRecord\"/> that is not correlated with its originating request.</param>\n        /// <param name=\"category\">The logical category for the trace.  Users may define their own.</param>\n        /// <param name=\"level\">The <see cref=\"TraceLevel\"/> at which to write this trace.</param>\n        /// <param name=\"traceAction\">The action to invoke if tracing is enabled.  The caller is expected\n        /// to fill in any or all of the values of the given <see cref=\"TraceRecord\"/> in this action.</param>\n        void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/ITraceWriterExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading.Tasks;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.Tracing\n{\n    /// <summary>\n    /// Extension methods for <see cref=\"ITraceWriter\"/>.\n    /// </summary>\n    public static class ITraceWriterExtensions\n    {\n        /// <summary>\n        /// Writes a <see cref=\"TraceRecord\"/> at <see cref=\"TraceLevel.Debug\"/> with the given message.\n        /// </summary>\n        /// <param name=\"traceWriter\">The <see cref=\"ITraceWriter\"/></param>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/> with which to correlate the request.  \n        /// It may be null, but if so will not be correlated with any request.</param>\n        /// <param name=\"category\">The category for the trace.</param>\n        /// <param name=\"messageFormat\">The string to use to format a message.  It may not be null.</param>\n        /// <param name=\"messageArguments\">Optional list of arguments for the <paramref name=\"messageFormat\"/>.</param>\n        public static void Debug(this ITraceWriter traceWriter, HttpRequestMessage request, string category, string messageFormat, params object[] messageArguments)\n        {\n            Trace(traceWriter, request, category, TraceLevel.Debug, messageFormat, messageArguments);\n        }\n\n        /// <summary>\n        /// Writes a <see cref=\"TraceRecord\"/> at <see cref=\"TraceLevel.Debug\"/> with the given <paramref name=\"exception\"/>.\n        /// </summary>\n        /// <param name=\"traceWriter\">The <see cref=\"ITraceWriter\"/></param>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/> with which to correlate the request.  \n        /// It may be null, but if so will not be correlated with any request.</param>\n        /// <param name=\"category\">The category for the trace.</param>\n        /// <param name=\"exception\">The exception to trace</param>\n        public static void Debug(this ITraceWriter traceWriter, HttpRequestMessage request, string category, Exception exception)\n        {\n            Trace(traceWriter, request, category, TraceLevel.Debug, exception);\n        }\n\n        /// <summary>\n        /// Writes a <see cref=\"TraceRecord\"/> at <see cref=\"TraceLevel.Debug\"/> with the given message and exception.\n        /// </summary>\n        /// <param name=\"traceWriter\">The <see cref=\"ITraceWriter\"/></param>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/> with which to correlate the request.  \n        /// It may be null, but if so will not be correlated with any request.</param>\n        /// <param name=\"category\">The category for the trace.</param>\n        /// <param name=\"exception\">The exception to trace</param>\n        /// <param name=\"messageFormat\">The string to use to format a message.  It may not be null.</param>\n        /// <param name=\"messageArguments\">Optional list of arguments for the <paramref name=\"messageFormat\"/>.</param>\n        public static void Debug(this ITraceWriter traceWriter, HttpRequestMessage request, string category, Exception exception, string messageFormat, params object[] messageArguments)\n        {\n            Trace(traceWriter, request, category, TraceLevel.Debug, exception, messageFormat, messageArguments);\n        }\n\n        /// <summary>\n        /// Writes a <see cref=\"TraceRecord\"/> at <see cref=\"TraceLevel.Error\"/> with the given message.\n        /// </summary>\n        /// <param name=\"traceWriter\">The <see cref=\"ITraceWriter\"/></param>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/> with which to correlate the request.  \n        /// It may be null, but if so will not be correlated with any request.</param>\n        /// <param name=\"category\">The category for the trace.</param>\n        /// <param name=\"messageFormat\">The string to use to format a message.  It may not be null.</param>\n        /// <param name=\"messageArguments\">Optional list of arguments for the <paramref name=\"messageFormat\"/>.</param>\n        public static void Error(this ITraceWriter traceWriter, HttpRequestMessage request, string category, string messageFormat, params object[] messageArguments)\n        {\n            Trace(traceWriter, request, category, TraceLevel.Error, messageFormat, messageArguments);\n        }\n\n        /// <summary>\n        /// Writes a <see cref=\"TraceRecord\"/> at <see cref=\"TraceLevel.Error\"/> with the given <paramref name=\"exception\"/>.\n        /// </summary>\n        /// <param name=\"traceWriter\">The <see cref=\"ITraceWriter\"/></param>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/> with which to correlate the request.  \n        /// It may be null, but if so will not be correlated with any request.</param>\n        /// <param name=\"category\">The category for the trace.</param>\n        /// <param name=\"exception\">The exception to trace</param>\n        public static void Error(this ITraceWriter traceWriter, HttpRequestMessage request, string category, Exception exception)\n        {\n            Trace(traceWriter, request, category, TraceLevel.Error, exception);\n        }\n\n        /// <summary>\n        /// Writes a <see cref=\"TraceRecord\"/> at <see cref=\"TraceLevel.Error\"/> with the given message and exception.\n        /// </summary>\n        /// <param name=\"traceWriter\">The <see cref=\"ITraceWriter\"/></param>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/> with which to correlate the request.  \n        /// It may be null, but if so will not be correlated with any request.</param>\n        /// <param name=\"category\">The category for the trace.</param>\n        /// <param name=\"exception\">The exception to trace</param>\n        /// <param name=\"messageFormat\">The string to use to format a message.  It may not be null.</param>\n        /// <param name=\"messageArguments\">Optional list of arguments for the <paramref name=\"messageFormat\"/>.</param>\n        public static void Error(this ITraceWriter traceWriter, HttpRequestMessage request, string category, Exception exception, string messageFormat, params object[] messageArguments)\n        {\n            Trace(traceWriter, request, category, TraceLevel.Error, exception, messageFormat, messageArguments);\n        }\n\n        /// <summary>\n        /// Writes a <see cref=\"TraceRecord\"/> at <see cref=\"TraceLevel.Fatal\"/> with the given message.\n        /// </summary>\n        /// <param name=\"traceWriter\">The <see cref=\"ITraceWriter\"/></param>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/> with which to correlate the request.  \n        /// It may be null, but if so will not be correlated with any request.</param>\n        /// <param name=\"category\">The category for the trace.</param>\n        /// <param name=\"messageFormat\">The string to use to format a message.  It may not be null.</param>\n        /// <param name=\"messageArguments\">Optional list of arguments for the <paramref name=\"messageFormat\"/>.</param>\n        public static void Fatal(this ITraceWriter traceWriter, HttpRequestMessage request, string category, string messageFormat, params object[] messageArguments)\n        {\n            Trace(traceWriter, request, category, TraceLevel.Fatal, messageFormat, messageArguments);\n        }\n\n        /// <summary>\n        /// Writes a <see cref=\"TraceRecord\"/> at <see cref=\"TraceLevel.Fatal\"/> with the given <paramref name=\"exception\"/>.\n        /// </summary>\n        /// <param name=\"traceWriter\">The <see cref=\"ITraceWriter\"/></param>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/> with which to correlate the request.  \n        /// It may be null, but if so will not be correlated with any request.</param>\n        /// <param name=\"category\">The category for the trace.</param>\n        /// <param name=\"exception\">The exception to trace</param>\n        public static void Fatal(this ITraceWriter traceWriter, HttpRequestMessage request, string category, Exception exception)\n        {\n            Trace(traceWriter, request, category, TraceLevel.Fatal, exception);\n        }\n\n        /// <summary>\n        /// Writes a <see cref=\"TraceRecord\"/> at <see cref=\"TraceLevel.Fatal\"/> with the given message and exception.\n        /// </summary>\n        /// <param name=\"traceWriter\">The <see cref=\"ITraceWriter\"/></param>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/> with which to correlate the request.  \n        /// It may be null, but if so will not be correlated with any request.</param>\n        /// <param name=\"category\">The category for the trace.</param>\n        /// <param name=\"exception\">The exception to trace</param>\n        /// <param name=\"messageFormat\">The string to use to format a message.  It may not be null.</param>\n        /// <param name=\"messageArguments\">Optional list of arguments for the <paramref name=\"messageFormat\"/>.</param>\n        public static void Fatal(this ITraceWriter traceWriter, HttpRequestMessage request, string category, Exception exception, string messageFormat, params object[] messageArguments)\n        {\n            Trace(traceWriter, request, category, TraceLevel.Fatal, exception, messageFormat, messageArguments);\n        }\n\n        /// <summary>\n        /// Writes a <see cref=\"TraceRecord\"/> at <see cref=\"TraceLevel.Info\"/> with the given message.\n        /// </summary>\n        /// <param name=\"traceWriter\">The <see cref=\"ITraceWriter\"/></param>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/> with which to correlate the request.  \n        /// It may be null, but if so will not be correlated with any request.</param>\n        /// <param name=\"category\">The category for the trace.</param>\n        /// <param name=\"messageFormat\">The string to use to format a message.  It may not be null.</param>\n        /// <param name=\"messageArguments\">Optional list of arguments for the <paramref name=\"messageFormat\"/>.</param>\n        public static void Info(this ITraceWriter traceWriter, HttpRequestMessage request, string category, string messageFormat, params object[] messageArguments)\n        {\n            Trace(traceWriter, request, category, TraceLevel.Info, messageFormat, messageArguments);\n        }\n\n        /// <summary>\n        /// Writes a <see cref=\"TraceRecord\"/> at <see cref=\"TraceLevel.Info\"/> with the given <paramref name=\"exception\"/>.\n        /// </summary>\n        /// <param name=\"traceWriter\">The <see cref=\"ITraceWriter\"/></param>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/> with which to correlate the request.  \n        /// It may be null, but if so will not be correlated with any request.</param>\n        /// <param name=\"category\">The category for the trace.</param>\n        /// <param name=\"exception\">The exception to trace</param>\n        public static void Info(this ITraceWriter traceWriter, HttpRequestMessage request, string category, Exception exception)\n        {\n            Trace(traceWriter, request, category, TraceLevel.Info, exception);\n        }\n\n        /// <summary>\n        /// Writes a <see cref=\"TraceRecord\"/> at <see cref=\"TraceLevel.Info\"/> with the given message and exception.\n        /// </summary>\n        /// <param name=\"traceWriter\">The <see cref=\"ITraceWriter\"/></param>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/> with which to correlate the request.  \n        /// It may be null, but if so will not be correlated with any request.</param>\n        /// <param name=\"category\">The category for the trace.</param>\n        /// <param name=\"exception\">The exception to trace</param>\n        /// <param name=\"messageFormat\">The string to use to format a message.  It may not be null.</param>\n        /// <param name=\"messageArguments\">Optional list of arguments for the <paramref name=\"messageFormat\"/>.</param>\n        public static void Info(this ITraceWriter traceWriter, HttpRequestMessage request, string category, Exception exception, string messageFormat, params object[] messageArguments)\n        {\n            Trace(traceWriter, request, category, TraceLevel.Info, exception, messageFormat, messageArguments);\n        }\n\n        /// <summary>\n        /// Writes a single <see cref=\"TraceRecord\"/> to the given <see cref=\"ITraceWriter\"/> if the trace writer\n        /// is enabled for the given <paramref name=\"category\"/> and <paramref name=\"level\"/>.\n        /// </summary>\n        /// <param name=\"traceWriter\">The <see cref=\"ITraceWriter\"/></param>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/> with which to correlate the request.  \n        /// It may be null, but if so cannot be correlated with any request.</param>\n        /// <param name=\"category\">The category for the trace.</param>\n        /// <param name=\"level\">The <see cref=\"TraceLevel\"/> for the trace.</param>\n        /// <param name=\"exception\">The <see cref=\"Exception\"/> to trace.   It may not be null.</param>\n        public static void Trace(this ITraceWriter traceWriter, HttpRequestMessage request, string category, TraceLevel level, Exception exception)\n        {\n            if (traceWriter == null)\n            {\n                throw System.Web.Http.Error.ArgumentNull(\"traceWriter\");\n            }\n\n            if (exception == null)\n            {\n                throw System.Web.Http.Error.ArgumentNull(\"exception\");\n            }\n\n            traceWriter.Trace(\n                request,\n                category,\n                level,\n                (TraceRecord traceRecord) =>\n                {\n                    traceRecord.Exception = exception;\n                });\n        }\n\n        /// <summary>\n        /// Writes a single <see cref=\"TraceRecord\"/> to the given <see cref=\"ITraceWriter\"/> if the trace writer\n        /// is enabled for the given <paramref name=\"category\"/> and <paramref name=\"level\"/>.\n        /// </summary>\n        /// <param name=\"traceWriter\">The <see cref=\"ITraceWriter\"/></param>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/> with which to correlate the request.  \n        /// It may be null, but if so will not be correlated with any request.</param>\n        /// <param name=\"category\">The category for the trace.</param>\n        /// <param name=\"level\">The <see cref=\"TraceLevel\"/> for the trace.</param>\n        /// <param name=\"exception\">The <see cref=\"Exception\"/> to trace.   It may not be null.</param>\n        /// <param name=\"messageFormat\">The string to use to format a message.  It may not be null.</param>\n        /// <param name=\"messageArguments\">Optional list of arguments for the <paramref name=\"messageFormat\"/>.</param>\n        public static void Trace(this ITraceWriter traceWriter, HttpRequestMessage request, string category, TraceLevel level, Exception exception, string messageFormat, params object[] messageArguments)\n        {\n            if (traceWriter == null)\n            {\n                throw System.Web.Http.Error.ArgumentNull(\"traceWriter\");\n            }\n\n            if (exception == null)\n            {\n                throw System.Web.Http.Error.ArgumentNull(\"exception\");\n            }\n\n            if (messageFormat == null)\n            {\n                throw System.Web.Http.Error.ArgumentNull(\"messageFormat\");\n            }\n\n            traceWriter.Trace(\n                request,\n                category,\n                level,\n                (TraceRecord traceRecord) =>\n                {\n                    traceRecord.Exception = exception;\n                    traceRecord.Message = System.Web.Http.Error.Format(messageFormat, messageArguments);\n                });\n        }\n\n        /// <summary>\n        /// Writes a single <see cref=\"TraceRecord\"/> to the given <see cref=\"ITraceWriter\"/> if the trace writer\n        /// is enabled for the given <paramref name=\"category\"/> and <paramref name=\"level\"/>.\n        /// </summary>\n        /// <param name=\"traceWriter\">The <see cref=\"ITraceWriter\"/></param>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/> with which to correlate the request.  \n        /// It may be null, but if so will not be correlated with any request.</param>\n        /// <param name=\"category\">The category for the trace.</param>\n        /// <param name=\"level\">The <see cref=\"TraceLevel\"/> for the trace.</param>\n        /// <param name=\"messageFormat\">The string to use to format a message.  It may not be null.</param>\n        /// <param name=\"messageArguments\">Optional list of arguments for the <paramref name=\"messageFormat\"/>.</param>\n        public static void Trace(this ITraceWriter traceWriter, HttpRequestMessage request, string category, TraceLevel level, string messageFormat, params object[] messageArguments)\n        {\n            if (traceWriter == null)\n            {\n                throw System.Web.Http.Error.ArgumentNull(\"traceWriter\");\n            }\n\n            if (messageFormat == null)\n            {\n                throw System.Web.Http.Error.ArgumentNull(\"messageFormat\");\n            }\n\n            traceWriter.Trace(\n                request,\n                category,\n                level,\n                (TraceRecord traceRecord) =>\n                {\n                    traceRecord.Message = System.Web.Http.Error.Format(messageFormat, messageArguments);\n                });\n        }\n\n        /// <summary>\n        /// Traces both a begin and an end trace around a specified operation.\n        /// </summary>\n        /// <param name=\"traceWriter\">The <see cref=\"ITraceWriter\"/>.</param>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/> with which to associate the trace.  It may be null.</param>\n        /// <param name=\"category\">The logical category of the trace.</param>\n        /// <param name=\"level\">The <see cref=\"TraceLevel\"/> of the trace.</param>\n        /// <param name=\"operatorName\">The name of the object performing the operation.  It may be null.</param>\n        /// <param name=\"operationName\">The name of the operation being performed.  It may be null.</param>\n        /// <param name=\"beginTrace\">The <see cref=\"Action\"/> to invoke prior to performing the operation, \n        /// allowing the given <see cref=\"TraceRecord\"/> to be filled in.  It may be null.</param>\n        /// <param name=\"execute\">An <see cref=\"Action\"/> that performs the operation.</param>\n        /// <param name=\"endTrace\">The <see cref=\"Action\"/> to invoke after successfully performing the operation, \n        /// allowing the given <see cref=\"TraceRecord\"/> to be filled in.  It may be null.</param>\n        /// <param name=\"errorTrace\">The <see cref=\"Action\"/> to invoke if an error was encountered performing the operation, \n        /// allowing the given <see cref=\"TraceRecord\"/> to be filled in.  It may be null.</param>\n        public static void TraceBeginEnd(this ITraceWriter traceWriter,\n                                        HttpRequestMessage request,\n                                        string category,\n                                        TraceLevel level,\n                                        string operatorName,\n                                        string operationName,\n                                        Action<TraceRecord> beginTrace,\n                                        Action execute,\n                                        Action<TraceRecord> endTrace,\n                                        Action<TraceRecord> errorTrace)\n        {\n            if (traceWriter == null)\n            {\n                throw System.Web.Http.Error.ArgumentNull(\"traceWriter\");\n            }\n\n            if (execute == null)\n            {\n                throw System.Web.Http.Error.ArgumentNull(\"execute\");\n            }\n\n            traceWriter.Trace(\n                request,\n                category,\n                level,\n                (TraceRecord traceRecord) =>\n                {\n                    traceRecord.Kind = TraceKind.Begin;\n                    traceRecord.Operator = operatorName;\n                    traceRecord.Operation = operationName;\n                    if (beginTrace != null)\n                    {\n                        beginTrace(traceRecord);\n                    }\n                });\n            try\n            {\n                execute();\n\n                traceWriter.Trace(\n                    request,\n                    category,\n                    level,\n                    (TraceRecord traceRecord) =>\n                    {\n                        traceRecord.Kind = TraceKind.End;\n                        traceRecord.Operator = operatorName;\n                        traceRecord.Operation = operationName;\n                        if (endTrace != null)\n                        {\n                            endTrace(traceRecord);\n                        }\n                    });\n            }\n            catch (Exception exception)\n            {\n                traceWriter.TraceError(exception, request, category, operatorName, operationName, errorTrace);\n                throw;\n            }\n        }\n\n        /// <summary>\n        /// Traces both a begin and an end trace around a specified asynchronous operation.\n        /// </summary>\n        /// <remarks>The end trace will occur when the asynchronous operation completes, either success or failure.</remarks>\n        /// <typeparam name=\"TResult\">The type of result produced by the <see cref=\"Task\"/>.</typeparam>\n        /// /// <param name=\"traceWriter\">The <see cref=\"ITraceWriter\"/>.</param>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/> with which to associate the trace.  It may be null.</param>\n        /// <param name=\"category\">The logical category of the trace.</param>\n        /// <param name=\"level\">The <see cref=\"TraceLevel\"/> of the trace.</param>\n        /// <param name=\"operatorName\">The name of the object performing the operation.  It may be null.</param>\n        /// <param name=\"operationName\">The name of the operation being performed.  It may be null.</param>\n        /// <param name=\"beginTrace\">The <see cref=\"Action\"/> to invoke prior to performing the operation, \n        /// allowing the given <see cref=\"TraceRecord\"/> to be filled in.  It may be null.</param>\n        /// <param name=\"execute\">An <see cref=\"Func{Task}\"/> that returns the <see cref=\"Task\"/> that will perform the operation.</param>\n        /// <param name=\"endTrace\">The <see cref=\"Action\"/> to invoke after successfully performing the operation, \n        /// allowing the given <see cref=\"TraceRecord\"/> to be filled in.  The result of the completed task will also\n        /// be passed to this action.  This action may be null.</param>\n        /// <param name=\"errorTrace\">The <see cref=\"Action\"/> to invoke if an error was encountered performing the operation, \n        /// allowing the given <see cref=\"TraceRecord\"/> to be filled in.  It may be null.</param>\n        /// <returns>The <see cref=\"Task\"/> returned by the operation.</returns>\n        [System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"Nested generic required for this method.\")]\n        public static Task<TResult> TraceBeginEndAsync<TResult>(this ITraceWriter traceWriter,\n                                HttpRequestMessage request,\n                                string category,\n                                TraceLevel level,\n                                string operatorName,\n                                string operationName,\n                                Action<TraceRecord> beginTrace,\n                                Func<Task<TResult>> execute,\n                                Action<TraceRecord, TResult> endTrace,\n                                Action<TraceRecord> errorTrace)\n        {\n            if (traceWriter == null)\n            {\n                throw System.Web.Http.Error.ArgumentNull(\"traceWriter\");\n            }\n\n            if (execute == null)\n            {\n                throw System.Web.Http.Error.ArgumentNull(\"execute\");\n            }\n\n            traceWriter.Trace(\n                request,\n                category,\n                level,\n                (TraceRecord traceRecord) =>\n                {\n                    traceRecord.Kind = TraceKind.Begin;\n                    traceRecord.Operator = operatorName;\n                    traceRecord.Operation = operationName;\n                    if (beginTrace != null)\n                    {\n                        beginTrace(traceRecord);\n                    }\n                });\n            try\n            {\n                Task<TResult> task = execute();\n\n                // If the operation returned a null Task, we cannot do any\n                // further tracing.  Return that null to the caller as\n                // would happen if tracing were not enabled.\n                if (task == null)\n                {\n                    return task;\n                }\n\n                return traceWriter.TraceBeginEndAsyncCore<TResult>(request, category, level, operatorName, operationName, endTrace, errorTrace, task);\n            }\n            catch (Exception exception)\n            {\n                traceWriter.TraceError(exception, request, category, operatorName, operationName, errorTrace);\n                throw;\n            }\n        }\n\n        private static async Task<TResult> TraceBeginEndAsyncCore<TResult>(this ITraceWriter traceWriter,\n            HttpRequestMessage request,\n            string category, TraceLevel level,\n            string operatorName,\n            string operationName,\n            Action<TraceRecord, TResult> endTrace,\n            Action<TraceRecord> errorTrace,\n            Task<TResult> task)\n        {\n            try\n            {\n                TResult result = await task;\n                traceWriter.Trace(\n                    request,\n                    category,\n                    level,\n                    (TraceRecord traceRecord) =>\n                    {\n                        traceRecord.Kind = TraceKind.End;\n                        traceRecord.Operator = operatorName;\n                        traceRecord.Operation = operationName;\n                        if (endTrace != null)\n                        {\n                            endTrace(traceRecord, result);\n                        }\n                    });\n\n                return result;\n            }\n            catch (OperationCanceledException)\n            {\n                traceWriter.Trace(\n                        request,\n                        category,\n                        TraceLevel.Warn,\n                        (TraceRecord traceRecord) =>\n                        {\n                            traceRecord.Kind = TraceKind.End;\n                            traceRecord.Operator = operatorName;\n                            traceRecord.Operation = operationName;\n                            traceRecord.Message = SRResources.TraceCancelledMessage;\n                            if (errorTrace != null)\n                            {\n                                errorTrace(traceRecord);\n                            }\n                        });\n\n                throw;\n            }\n            catch (Exception exception)\n            {\n                traceWriter.TraceError(exception, request, category, operatorName, operationName, errorTrace);\n                throw;\n            }\n        }\n\n        /// <summary>\n        /// Traces both a begin and an end trace around a specified asynchronous operation.\n        /// </summary>\n        /// <remarks>The end trace will occur when the asynchronous operation completes, either success or failure.</remarks>\n        /// <param name=\"traceWriter\">The <see cref=\"ITraceWriter\"/>.</param>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/> with which to associate the trace.  It may be null.</param>\n        /// <param name=\"category\">The logical category of the trace.</param>\n        /// <param name=\"level\">The <see cref=\"TraceLevel\"/> of the trace.</param>\n        /// <param name=\"operatorName\">The name of the object performing the operation.  It may be null.</param>\n        /// <param name=\"operationName\">The name of the operation being performed.  It may be null.</param>\n        /// <param name=\"beginTrace\">The <see cref=\"Action\"/> to invoke prior to performing the operation, \n        /// allowing the given <see cref=\"TraceRecord\"/> to be filled in.  It may be null.</param>\n        /// <param name=\"execute\">An <see cref=\"Func{Task}\"/> that returns the <see cref=\"Task\"/> that will perform the operation.</param>\n        /// <param name=\"endTrace\">The <see cref=\"Action\"/> to invoke after successfully performing the operation, \n        /// allowing the given <see cref=\"TraceRecord\"/> to be filled in.  It may be null.</param>\n        /// <param name=\"errorTrace\">The <see cref=\"Action\"/> to invoke if an error was encountered performing the operation, \n        /// allowing the given <see cref=\"TraceRecord\"/> to be filled in.  It may be null.</param>\n        /// <returns>The <see cref=\"Task\"/> returned by the operation.</returns>\n        public static Task TraceBeginEndAsync(this ITraceWriter traceWriter,\n                                HttpRequestMessage request,\n                                string category,\n                                TraceLevel level,\n                                string operatorName,\n                                string operationName,\n                                Action<TraceRecord> beginTrace,\n                                Func<Task> execute,\n                                Action<TraceRecord> endTrace,\n                                Action<TraceRecord> errorTrace)\n        {\n            if (traceWriter == null)\n            {\n                throw System.Web.Http.Error.ArgumentNull(\"traceWriter\");\n            }\n\n            if (execute == null)\n            {\n                throw System.Web.Http.Error.ArgumentNull(\"execute\");\n            }\n\n            traceWriter.Trace(\n                request,\n                category,\n                level,\n                (TraceRecord traceRecord) =>\n                {\n                    traceRecord.Kind = TraceKind.Begin;\n                    traceRecord.Operator = operatorName;\n                    traceRecord.Operation = operationName;\n                    if (beginTrace != null)\n                    {\n                        beginTrace(traceRecord);\n                    }\n                });\n            try\n            {\n                Task task = execute();\n\n                // If the operation returned a null Task, we cannot do any\n                // further tracing.  Return that null to the caller as\n                // would happen if tracing were not enabled.\n                if (task == null)\n                {\n                    return task;\n                }\n\n                return traceWriter.TraceBeginEndAsyncCore(request, category, level, operatorName, operationName, endTrace, errorTrace, task);\n            }\n            catch (Exception exception)\n            {\n                traceWriter.TraceError(exception, request, category, operatorName, operationName, errorTrace);\n                throw;\n            }\n        }\n\n        private static async Task TraceBeginEndAsyncCore(this ITraceWriter traceWriter,\n            HttpRequestMessage request,\n            string category,\n            TraceLevel level,\n            string operatorName,\n            string operationName,\n            Action<TraceRecord> endTrace,\n            Action<TraceRecord> errorTrace,\n            Task task)\n        {\n            try\n            {\n                await task;\n                traceWriter.Trace(\n                        request,\n                        category,\n                        level,\n                        (TraceRecord traceRecord) =>\n                        {\n                            traceRecord.Kind = TraceKind.End;\n                            traceRecord.Operator = operatorName;\n                            traceRecord.Operation = operationName;\n                            if (endTrace != null)\n                            {\n                                endTrace(traceRecord);\n                            }\n                        });\n            }\n            catch (OperationCanceledException)\n            {\n                traceWriter.Trace(\n                        request,\n                        category,\n                        TraceLevel.Warn,\n                        (TraceRecord traceRecord) =>\n                        {\n                            traceRecord.Kind = TraceKind.End;\n                            traceRecord.Operator = operatorName;\n                            traceRecord.Operation = operationName;\n                            traceRecord.Message = SRResources.TraceCancelledMessage;\n                            if (errorTrace != null)\n                            {\n                                errorTrace(traceRecord);\n                            }\n                        });\n\n                throw;\n            }\n            catch (Exception exception)\n            {\n                traceWriter.TraceError(exception, request, category, operatorName, operationName, errorTrace);\n                throw;\n            }\n        }\n\n        /// <summary>\n        /// Writes a <see cref=\"TraceRecord\"/> at <see cref=\"TraceLevel.Warn\"/> with the given message.\n        /// </summary>\n        /// <param name=\"traceWriter\">The <see cref=\"ITraceWriter\"/></param>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/> with which to correlate the request.  \n        /// It may be null, but if so will not be correlated with any request.</param>\n        /// <param name=\"category\">The category for the trace.</param>\n        /// <param name=\"messageFormat\">The string to use to format a message.  It may not be null.</param>\n        /// <param name=\"messageArguments\">Optional list of arguments for the <paramref name=\"messageFormat\"/>.</param>\n        public static void Warn(this ITraceWriter traceWriter, HttpRequestMessage request, string category, string messageFormat, params object[] messageArguments)\n        {\n            Trace(traceWriter, request, category, TraceLevel.Warn, messageFormat, messageArguments);\n        }\n\n        /// <summary>\n        /// Writes a <see cref=\"TraceRecord\"/> at <see cref=\"TraceLevel.Warn\"/> with the given <paramref name=\"exception\"/>.\n        /// </summary>\n        /// <param name=\"traceWriter\">The <see cref=\"ITraceWriter\"/></param>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/> with which to correlate the request.  \n        /// It may be null, but if so will not be correlated with any request.</param>\n        /// <param name=\"category\">The category for the trace.</param>\n        /// <param name=\"exception\">The exception to trace</param>\n        public static void Warn(this ITraceWriter traceWriter, HttpRequestMessage request, string category, Exception exception)\n        {\n            Trace(traceWriter, request, category, TraceLevel.Warn, exception);\n        }\n\n        /// <summary>\n        /// Writes a <see cref=\"TraceRecord\"/> at <see cref=\"TraceLevel.Warn\"/> with the given message and exception.\n        /// </summary>\n        /// <param name=\"traceWriter\">The <see cref=\"ITraceWriter\"/></param>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/> with which to correlate the request.  \n        /// It may be null, but if so will not be correlated with any request.</param>\n        /// <param name=\"category\">The category for the trace.</param>\n        /// <param name=\"exception\">The exception to trace</param>\n        /// <param name=\"messageFormat\">The string to use to format a message.  It may not be null.</param>\n        /// <param name=\"messageArguments\">Optional list of arguments for the <paramref name=\"messageFormat\"/>.</param>\n        public static void Warn(this ITraceWriter traceWriter, HttpRequestMessage request, string category, Exception exception, string messageFormat, params object[] messageArguments)\n        {\n            Trace(traceWriter, request, category, TraceLevel.Warn, exception, messageFormat, messageArguments);\n        }\n\n        private static void TraceError(this ITraceWriter traceWriter, Exception exception, HttpRequestMessage request,\n            string category, string operatorName, string operationName, Action<TraceRecord> errorTrace)\n        {\n            TraceLevel traceLevel = TraceWriterExceptionMapper.GetMappedTraceLevel(exception) ?? TraceLevel.Error;\n            traceWriter.Trace(request, category, traceLevel, (traceRecord) =>\n                {\n                    traceRecord.Kind = TraceKind.End;\n                    traceRecord.Operator = operatorName;\n                    traceRecord.Operation = operationName;\n                    traceRecord.Exception = exception;\n                    TraceWriterExceptionMapper.TranslateHttpResponseException(traceRecord);\n                    if (errorTrace != null)\n                    {\n                        errorTrace(traceRecord);\n                    }\n                });\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/TraceCategories.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Tracing\n{\n    /// <summary>\n    /// Category names traced by the default tracing implementation.\n    /// </summary>\n    /// <remarks>\n    /// The list of permitted category names is open-ended, and users may define their own.\n    /// It is recommended that category names reflect the namespace of their\n    /// respective area.  This prevents name conflicts and allows external\n    /// logging tools to enable or disable tracing by namespace.\n    /// </remarks>\n    public static class TraceCategories\n    {\n        public static readonly string ActionCategory = \"System.Web.Http.Action\";\n        public static readonly string ControllersCategory = \"System.Web.Http.Controllers\";\n        public static readonly string FiltersCategory = \"System.Web.Http.Filters\";\n        public static readonly string FormattingCategory = \"System.Net.Http.Formatting\";\n        public static readonly string MessageHandlersCategory = \"System.Web.Http.MessageHandlers\";\n        public static readonly string ModelBindingCategory = \"System.Web.Http.ModelBinding\";\n        public static readonly string RequestCategory = \"System.Web.Http.Request\";\n        public static readonly string RoutingCategory = \"System.Web.Http.Routing\";\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/TraceKind.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Tracing\n{\n    /// <summary>\n    /// Describes the kind of <see cref=\"TraceRecord\"/> for an individual trace operation.\n    /// </summary>\n    public enum TraceKind\n    {\n        /// <summary>\n        /// Single trace, not part of a Begin/End trace pair\n        /// </summary>\n        Trace = 0,\n\n        /// <summary>\n        /// Trace marking the beginning of some operation.\n        /// </summary>\n        Begin,\n\n        /// <summary>\n        /// Trace marking the end of some operation.\n        /// </summary>\n        End,\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/TraceKindHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Tracing\n{\n    internal static class TraceKindHelper\n    {\n        public static bool IsDefined(TraceKind traceKind)\n        {\n            return traceKind == TraceKind.Trace ||\n                   traceKind == TraceKind.Begin ||\n                   traceKind == TraceKind.End;\n        }\n\n        public static void Validate(TraceKind value, string parameterValue)\n        {\n            if (!IsDefined(value))\n            {\n                throw Error.InvalidEnumArgument(parameterValue, (int)value, typeof(TraceKind));\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/TraceLevel.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Tracing\n{\n    /// <summary>\n    /// Available trace levels.\n    /// </summary>\n    /// <remarks>\n    /// The interpretation of these levels is the responsibility of the\n    /// <see cref=\"ITraceWriter\"/> implementation.   The general convention is that\n    /// enabling a particular trace level also enables all levels greater than or\n    /// equal to it.  For example, tracing at <see cref=\"Warn\"/> level would\n    /// generally trace if the trace writer was enabled to trace at level <see cref=\"Info\"/>.\n    /// </remarks>\n    public enum TraceLevel\n    {\n        /// <summary>\n        /// Tracing is disabled\n        /// </summary>\n        Off = 0,\n\n        /// <summary>\n        /// Trace level for debugging traces\n        /// </summary>\n        Debug = 1,\n\n        /// <summary>\n        /// Trace level for informational traces\n        /// </summary>\n        Info = 2,\n\n        /// <summary>\n        /// Trace level for warning traces\n        /// </summary>\n        Warn = 3,\n\n        /// <summary>\n        /// Trace level for error traces\n        /// </summary>\n        Error = 4,\n\n        /// <summary>\n        /// Trace level for fatal traces\n        /// </summary>\n        Fatal = 5\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/TraceLevelHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Tracing\n{\n    internal static class TraceLevelHelper\n    {\n        public static bool IsDefined(TraceLevel traceLevel)\n        {\n            return traceLevel == TraceLevel.Off ||\n                   traceLevel == TraceLevel.Debug ||\n                   traceLevel == TraceLevel.Info ||\n                   traceLevel == TraceLevel.Warn ||\n                   traceLevel == TraceLevel.Error ||\n                   traceLevel == TraceLevel.Fatal;\n        }\n\n        public static void Validate(TraceLevel value, string parameterValue)\n        {\n            if (!IsDefined(value))\n            {\n                throw Error.InvalidEnumArgument(parameterValue, (int)value, typeof(TraceLevel));\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/TraceManager.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.Services;\nusing System.Web.Http.Tracing.Tracers;\n\nnamespace System.Web.Http.Tracing\n{\n    internal class TraceManager : ITraceManager\n    {\n        public void Initialize(HttpConfiguration configuration)\n        {\n            ITraceWriter traceWriter = configuration.Services.GetTraceWriter();\n            if (traceWriter != null)\n            {\n                // Install tracers only when a custom trace writer has been registered\n                CreateAllTracers(configuration, traceWriter);\n            }\n        }\n\n        private static void CreateAllTracers(HttpConfiguration configuration, ITraceWriter traceWriter)\n        {\n            CreateActionInvokerTracer(configuration, traceWriter);\n            CreateActionSelectorTracer(configuration, traceWriter);\n            CreateActionValueBinderTracer(configuration, traceWriter);\n            CreateContentNegotiatorTracer(configuration, traceWriter);\n            CreateControllerActivatorTracer(configuration, traceWriter);\n            CreateControllerSelectorTracer(configuration, traceWriter);\n            CreateHttpControllerTypeResolverTracer(configuration, traceWriter);\n            CreateMessageHandlerTracers(configuration, traceWriter);\n            CreateMediaTypeFormatterTracers(configuration, traceWriter);\n        }\n\n        // Get services from the global config. These are normally per-controller services, but we're getting the global fallbacks.\n        private static TService GetService<TService>(ServicesContainer services)\n        {\n            return (TService)services.GetService(typeof(TService));\n        }\n\n        private static void CreateActionInvokerTracer(HttpConfiguration configuration, ITraceWriter traceWriter)\n        {\n            IHttpActionInvoker invoker = GetService<IHttpActionInvoker>(configuration.Services);\n            if (invoker != null && !(invoker is HttpActionInvokerTracer))\n            {\n                HttpActionInvokerTracer tracer = new HttpActionInvokerTracer(invoker, traceWriter);\n                configuration.Services.Replace(typeof(IHttpActionInvoker), tracer);\n            }\n        }\n\n        private static void CreateActionSelectorTracer(HttpConfiguration configuration, ITraceWriter traceWriter)\n        {\n            IHttpActionSelector selector = GetService<IHttpActionSelector>(configuration.Services);\n            if (selector != null && !(selector is HttpActionSelectorTracer))\n            {\n                HttpActionSelectorTracer tracer = new HttpActionSelectorTracer(selector, traceWriter);\n                configuration.Services.Replace(typeof(IHttpActionSelector), tracer);\n            }\n        }\n\n        private static void CreateActionValueBinderTracer(HttpConfiguration configuration, ITraceWriter traceWriter)\n        {\n            IActionValueBinder binder = GetService<IActionValueBinder>(configuration.Services);\n            if (binder != null && !(binder is ActionValueBinderTracer))\n            {\n                ActionValueBinderTracer tracer = new ActionValueBinderTracer(binder, traceWriter);\n                configuration.Services.Replace(typeof(IActionValueBinder), tracer);\n            }\n        }\n\n        private static void CreateContentNegotiatorTracer(HttpConfiguration configuration, ITraceWriter traceWriter)\n        {\n            IContentNegotiator negotiator = configuration.Services.GetContentNegotiator();\n            if (negotiator != null && !(negotiator is ContentNegotiatorTracer))\n            {\n                ContentNegotiatorTracer tracer = new ContentNegotiatorTracer(negotiator, traceWriter);\n                configuration.Services.Replace(typeof(IContentNegotiator), tracer);\n            }\n        }\n\n        private static void CreateControllerActivatorTracer(HttpConfiguration configuration, ITraceWriter traceWriter)\n        {\n            IHttpControllerActivator activator = GetService<IHttpControllerActivator>(configuration.Services);\n            if (activator != null && !(activator is HttpControllerActivatorTracer))\n            {\n                HttpControllerActivatorTracer tracer = new HttpControllerActivatorTracer(activator, traceWriter);\n                configuration.Services.Replace(typeof(IHttpControllerActivator), tracer);\n            }\n        }\n\n        private static void CreateControllerSelectorTracer(HttpConfiguration configuration, ITraceWriter traceWriter)\n        {\n            IHttpControllerSelector controllerSelector = configuration.Services.GetHttpControllerSelector();\n            if (controllerSelector != null && !(controllerSelector is HttpControllerSelectorTracer))\n            {\n                HttpControllerSelectorTracer tracer = new HttpControllerSelectorTracer(controllerSelector, traceWriter);\n                configuration.Services.Replace(typeof(IHttpControllerSelector), tracer);\n            }\n        }\n\n        private static void CreateHttpControllerTypeResolverTracer(HttpConfiguration configuration, ITraceWriter traceWriter)\n        {\n            DefaultHttpControllerTypeResolver resolver =\n                configuration.Services.GetHttpControllerTypeResolver() as DefaultHttpControllerTypeResolver;\n            if (resolver != null)\n            {\n                IHttpControllerTypeResolver tracer = new DefaultHttpControllerTypeResolverTracer(resolver, traceWriter);\n                configuration.Services.Replace(typeof(IHttpControllerTypeResolver), tracer);\n            }\n        }\n\n        private static void CreateMediaTypeFormatterTracers(HttpConfiguration configuration, ITraceWriter traceWriter)\n        {\n            for (int i = 0; i < configuration.Formatters.Count; i++)\n            {\n                MediaTypeFormatter formatter = configuration.Formatters[i];\n                if (!(formatter is IFormatterTracer))\n                {\n                    configuration.Formatters[i] = MediaTypeFormatterTracer.CreateTracer(\n                                                    configuration.Formatters[i],\n                                                    traceWriter,\n                                                    request: null);\n                }\n            }\n        }\n\n        [System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"Will be disposed when pipeline is disposed.\")]\n        private static void CreateMessageHandlerTracers(HttpConfiguration configuration, ITraceWriter traceWriter)\n        {\n            int handlerCount = configuration.MessageHandlers.Count;\n\n            // If message handlers have already been wired into the pipeline,\n            // we do not install tracing message handlers. This scenario occurs\n            // when initialization is attempted twice, such as per-controller configuration. \n            if (handlerCount > 0 && configuration.MessageHandlers[0].InnerHandler != null)\n            {\n                return;\n            }\n\n            // RequestMessageHandlerTracer will be the first tracer to get executed and each messageHandlerTracer\n            // will execute before its respective handler. For the MessageHandlerTracers to be registered, \n            // the message handler list must be of the form:\n            // requestMessageHandlerTracer\n            // messageHandler1Tracer\n            // messageHandler1\n            // ...\n            // ...\n            // messageHandlerNTracer\n            // messageHandlerN\n            // Where \"N\" is a non-negative integer. That is, there could be zero or more pairs of handlers/tracers, plus a \n            // request tracer at the beginning. If the state does not match this pattern, the tracer list is recreated.\n            if (!AreMessageHandlerTracersRegistered(configuration.MessageHandlers))\n            {\n                // Removing the MessageHandlerTracer and RequestMessageHandlerTracer in the reverse order.\n                for (int i = handlerCount - 1; i >= 0; i--)\n                {\n                    if (configuration.MessageHandlers[i] is RequestMessageHandlerTracer || configuration.MessageHandlers[i] is MessageHandlerTracer)\n                    {\n                        configuration.MessageHandlers.RemoveAt(i);\n                    }\n                }\n                handlerCount = configuration.MessageHandlers.Count;\n\n                // Insert a tracing handler before each existing message handler (in execution order)\n                for (int i = 0; i < handlerCount * 2; i += 2)\n                {\n                    DelegatingHandler innerHandler = configuration.MessageHandlers[i];\n                    DelegatingHandler handlerTracer = new MessageHandlerTracer(innerHandler, traceWriter);\n                    configuration.MessageHandlers.Insert(i, handlerTracer);\n                }\n\n                configuration.MessageHandlers.Insert(0, new RequestMessageHandlerTracer(traceWriter));\n            }\n        }\n\n        private static bool AreMessageHandlerTracersRegistered(Collection<DelegatingHandler> messageHandlers)\n        {\n            int handlerCount = messageHandlers.Count;\n            \n            // if the handler count is zero, exit early.\n            if (handlerCount == 0)\n            {\n                return false;\n            }\n\n            // if RequestMessageHandlerTracer is absent, exit early.\n            if (!(messageHandlers[0] is RequestMessageHandlerTracer))\n            {\n                return false;\n            }\n\n            // Message handler list must be an odd number (2*N+1) for N message handlers.\n            if (handlerCount % 2 != 1)\n            {\n                return false;\n            }\n\n            // Check if all odd positions have tracers and even positions have their corresponding handlers.\n            for (int i = 2; i < handlerCount; i += 2)\n            {\n                DelegatingHandler tracer = messageHandlers[i - 1];\n                DelegatingHandler messageHandler = messageHandlers[i];\n                if (!(tracer is MessageHandlerTracer))\n                {\n                    return false;\n                }\n\n                DelegatingHandler innerHandler = Decorator.GetInner(tracer);\n                if (innerHandler != messageHandler)\n                {\n                    return false;\n                }\n            }\n\n            return true;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/TraceRecord.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Net;\nusing System.Net.Http;\n\nnamespace System.Web.Http.Tracing\n{\n    /// <summary>\n    /// Data object used by <see cref=\"ITraceWriter\"/> to record traces.\n    /// </summary>\n    [DebuggerDisplay(\"Category: {Category}, Operation: {Operation}, Level: {Level}, Kind: {Kind}\")]\n    public class TraceRecord\n    {\n        private TraceKind _traceKind;\n        private TraceLevel _traceLevel;\n\n        private Lazy<Dictionary<object, object>> _properties = new Lazy<Dictionary<object, object>>(\n            () => new Dictionary<object, object>());\n\n        public TraceRecord(HttpRequestMessage request, string category, TraceLevel level)\n        {\n            Timestamp = DateTime.UtcNow;\n            Request = request;\n            RequestId = request != null ? request.GetCorrelationId() : Guid.Empty;\n            Category = category;\n            Level = level;\n        }\n\n        /// <summary>\n        /// Gets or sets the tracing category.\n        /// </summary>\n        public string Category { get; set; }\n\n        /// <summary>\n        /// Gets or sets the exception.\n        /// </summary>\n        public Exception Exception { get; set; }\n\n        /// <summary>\n        /// Gets or sets the kind of trace.\n        /// </summary>\n        public TraceKind Kind\n        {\n            get\n            {\n                return _traceKind;\n            }\n            set\n            {\n                TraceKindHelper.Validate(value, \"value\");\n                _traceKind = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets the tracing level.\n        /// </summary>\n        public TraceLevel Level\n        {\n            get\n            {\n                return _traceLevel;\n            }\n            set\n            {\n                TraceLevelHelper.Validate(value, \"value\");\n                _traceLevel = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets the message.\n        /// </summary>\n        public string Message { get; set; }\n\n        /// <summary>\n        /// Gets or sets the logical operation name being performed.\n        /// </summary>\n        public string Operation { get; set; }\n\n        /// <summary>\n        /// Gets or sets the logical name of the object performing the operation\n        /// </summary>\n        public string Operator { get; set; }\n\n        /// <summary>\n        /// Optional user-defined property bag.\n        /// </summary>\n        public Dictionary<object, object> Properties\n        {\n            get { return _properties.Value; }\n        }\n\n        /// <summary>\n        /// Gets the <see cref=\"HttpRequestMessage\"/>\n        /// </summary>\n        public HttpRequestMessage Request { get; private set; }\n\n        /// <summary>\n        /// Gets the correlation ID  from the <see cref=\"Request\"/>.\n        /// </summary>\n        public Guid RequestId { get; private set; }\n\n        /// <summary>\n        /// Gets or sets the <see cref=\"HttpStatusCode\"/> associated with the <see cref=\"HttpResponseMessage\"/>.\n        /// </summary>\n        public HttpStatusCode Status { get; set; }\n\n        /// <summary>\n        /// Gets the <see cref=\"DateTime\"/> of this trace (via <see cref=\"DateTime.UtcNow\"/>)\n        /// </summary>\n        public DateTime Timestamp { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/ActionFilterAttributeTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Runtime.CompilerServices;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Services;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    /// <summary>\n    /// Tracer for <see cref=\"ActionFilterAttribute\"/>.\n    /// </summary>\n    [SuppressMessage(\"Microsoft.Performance\", \"CA1813:AvoidUnsealedAttributes\", Justification = \"internal type needs to override, tracer are not sealed\")]\n    internal class ActionFilterAttributeTracer : ActionFilterAttribute, IDecorator<ActionFilterAttribute>\n    {\n        private readonly ActionFilterAttribute _innerFilter;\n        private readonly ITraceWriter _traceWriter;\n\n        public ActionFilterAttributeTracer(ActionFilterAttribute innerFilter, ITraceWriter traceWriter)\n        {\n            Contract.Assert(innerFilter != null);\n            Contract.Assert(traceWriter != null);\n\n            _innerFilter = innerFilter;\n            _traceWriter = traceWriter;\n        }\n\n        public ActionFilterAttribute Inner\n        {\n            get { return _innerFilter; }\n        }\n\n        public override bool AllowMultiple\n        {\n            get\n            {\n                return _innerFilter.AllowMultiple;\n            }\n        }\n\n        public override object TypeId\n        {\n            get\n            {\n                return _innerFilter.TypeId;\n            }\n        }\n\n        public override bool Equals(object obj)\n        {\n            return _innerFilter.Equals(obj);\n        }\n\n        public override int GetHashCode()\n        {\n            return _innerFilter.GetHashCode();\n        }\n\n        public override bool IsDefaultAttribute()\n        {\n            return _innerFilter.IsDefaultAttribute();\n        }\n\n        public override bool Match(object obj)\n        {\n            return _innerFilter.Match(obj);\n        }\n\n        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)\n        {\n            // This will never get called, all the traces are going through OnActionExecutingAsync, which calls directly the inner method.\n        }\n\n        public override Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)\n        {\n            return OnActionExecutedAsyncCore(actionExecutedContext, cancellationToken);\n        }\n\n        private Task OnActionExecutedAsyncCore(HttpActionExecutedContext actionExecutedContext,\n                                               CancellationToken cancellationToken,\n                                               [CallerMemberName] string methodName = null)\n        {\n            return _traceWriter.TraceBeginEndAsync(\n                actionExecutedContext.Request,\n                TraceCategories.FiltersCategory,\n                TraceLevel.Info,\n                _innerFilter.GetType().Name,\n                methodName,\n                beginTrace: (tr) =>\n                {\n                    tr.Message = Error.Format(\n                                        SRResources.TraceActionFilterMessage,\n                                        FormattingUtilities.ActionDescriptorToString(\n                                            actionExecutedContext.ActionContext.ActionDescriptor));\n                    tr.Exception = actionExecutedContext.Exception;\n                    HttpResponseMessage response = actionExecutedContext.Response;\n                    if (response != null)\n                    {\n                        tr.Status = response.StatusCode;\n                    }\n                },\n                execute: async () =>\n                {\n                    await _innerFilter.OnActionExecutedAsync(actionExecutedContext, cancellationToken);\n                },\n                endTrace: (tr) =>\n                {\n                    tr.Exception = actionExecutedContext.Exception;\n                    HttpResponseMessage response = actionExecutedContext.Response;\n                    if (response != null)\n                    {\n                        tr.Status = response.StatusCode;\n                    }\n                },\n                errorTrace: (tr) =>\n                {\n                    HttpResponseMessage response = actionExecutedContext.Response;\n                    if (response != null)\n                    {\n                        tr.Status = response.StatusCode;\n                    }\n                });\n        }\n\n        public override void OnActionExecuting(HttpActionContext actionContext)\n        {\n            // This will never get called, all the traces are going through OnActionExecutingAsync, which calls directly the inner method.\n        }\n\n        public override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)\n        {\n            return OnActionExecutingAsyncCore(actionContext, cancellationToken);\n        }\n\n        private Task OnActionExecutingAsyncCore(HttpActionContext actionContext,\n                                                CancellationToken cancellationToken,\n                                                [CallerMemberName] string methodName = null)\n        {\n            return _traceWriter.TraceBeginEndAsync(\n                actionContext.Request,\n                TraceCategories.FiltersCategory,\n                TraceLevel.Info,\n                _innerFilter.GetType().Name,\n                methodName,\n                beginTrace: (tr) =>\n                {\n                    tr.Message = Error.Format(\n                                    SRResources.TraceActionFilterMessage,\n                                    FormattingUtilities.ActionDescriptorToString(\n                                        actionContext.ActionDescriptor));\n\n                    HttpResponseMessage response = actionContext.Response;\n                    if (response != null)\n                    {\n                        tr.Status = response.StatusCode;\n                    }\n                },\n                execute: async () =>\n                {\n                    await _innerFilter.OnActionExecutingAsync(actionContext, cancellationToken);\n                },\n                endTrace: (tr) =>\n                {\n                    HttpResponseMessage response = actionContext.Response;\n                    if (response != null)\n                    {\n                        tr.Status = response.StatusCode;\n                    }\n                },\n                errorTrace: (tr) =>\n                {\n                    HttpResponseMessage response = actionContext.Response;\n                    if (response != null)\n                    {\n                        tr.Status = response.StatusCode;\n                    }\n                });\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/ActionFilterTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Services;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    /// <summary>\n    /// Tracer for <see cref=\"IActionFilter\"/>.\n    /// </summary>\n    internal class ActionFilterTracer : FilterTracer, IActionFilter, IDecorator<IActionFilter>\n    {\n        private const string ExecuteActionFilterAsyncMethodName = \"ExecuteActionFilterAsync\";\n\n        public ActionFilterTracer(IActionFilter innerFilter, ITraceWriter traceWriter)\n            : base(innerFilter, traceWriter)\n        {\n        }\n\n        public new IActionFilter Inner\n        {\n            get { return InnerActionFilter; }\n        }\n\n        private IActionFilter InnerActionFilter\n        {\n            get { return InnerFilter as IActionFilter; }\n        }\n\n        Task<HttpResponseMessage> IActionFilter.ExecuteActionFilterAsync(HttpActionContext actionContext,\n                                                                         CancellationToken cancellationToken,\n                                                                         Func<Task<HttpResponseMessage>> continuation)\n        {\n            return TraceWriter.TraceBeginEndAsync<HttpResponseMessage>(\n                actionContext.Request,\n                TraceCategories.FiltersCategory,\n                TraceLevel.Info,\n                InnerActionFilter.GetType().Name,\n                ExecuteActionFilterAsyncMethodName,\n                beginTrace: null,\n                execute: () => InnerActionFilter.ExecuteActionFilterAsync(actionContext, cancellationToken, continuation),\n                endTrace: (tr, response) =>\n                {\n                    if (response != null)\n                    {\n                        tr.Status = response.StatusCode;\n                    }\n                },\n                errorTrace: null);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/ActionValueBinderTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.Services;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    /// <summary>\n    /// Tracer for <see cref=\"IActionValueBinder\"/>\n    /// </summary>\n    internal class ActionValueBinderTracer : IActionValueBinder, IDecorator<IActionValueBinder>\n    {\n        private readonly IActionValueBinder _innerBinder;\n        private readonly ITraceWriter _traceWriter;\n\n        public ActionValueBinderTracer(IActionValueBinder innerBinder, ITraceWriter traceWriter)\n        {\n            Contract.Assert(innerBinder != null);\n            Contract.Assert(traceWriter != null);\n\n            _innerBinder = innerBinder;\n            _traceWriter = traceWriter;\n        }\n\n        public IActionValueBinder Inner\n        {\n            get { return _innerBinder; }\n        }\n\n        // Creates wrapping tracers for all HttpParameterBindings\n        HttpActionBinding IActionValueBinder.GetBinding(HttpActionDescriptor actionDescriptor)\n        {\n            HttpActionBinding actionBinding = _innerBinder.GetBinding(actionDescriptor);\n\n            if (actionBinding == null)\n            {\n                return null;\n            }\n\n            HttpParameterBinding[] parameterBindings = actionBinding.ParameterBindings;\n            HttpParameterBinding[] newParameterBindings = new HttpParameterBinding[parameterBindings.Length];\n            for (int i = 0; i < newParameterBindings.Length; i++)\n            {\n                HttpParameterBinding parameterBinding = parameterBindings[i];\n\n                // Intercept FormatterParameterBinding to replace its formatters\n                FormatterParameterBinding formatterParameterBinding = parameterBinding as FormatterParameterBinding;\n                newParameterBindings[i] = formatterParameterBinding != null\n                                            ? (HttpParameterBinding)new FormatterParameterBindingTracer(formatterParameterBinding, _traceWriter)\n                                            : (HttpParameterBinding)new HttpParameterBindingTracer(parameterBinding, _traceWriter);\n            }\n\n            // Replace the inner HttpActionBinding's parameter bindings with our tracing versions.\n            // This allows each individual parameter binding to trace.\n            actionBinding.ParameterBindings = newParameterBindings;\n\n            // Then create an HttpActionBindingTracer to wrap the actual HttpActionBinding\n            if (!(actionBinding is HttpActionBindingTracer))\n            {\n                return new HttpActionBindingTracer(actionBinding, _traceWriter);\n            }\n\n            return actionBinding;\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/AuthenticationFilterTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Services;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    /// <summary>Represents a tracer for an <see cref=\"IAuthenticationFilter\"/>.</summary>\n    internal class AuthenticationFilterTracer : FilterTracer, IAuthenticationFilter, IDecorator<IAuthenticationFilter>\n    {\n        private const string AuthenticateAsyncMethodName = \"AuthenticateAsync\";\n        private const string ChallengeAsyncMethodName = \"ChallengeAsync\";\n\n        private readonly IAuthenticationFilter _innerFilter;\n\n        public AuthenticationFilterTracer(IAuthenticationFilter innerFilter, ITraceWriter traceWriter)\n            : base(innerFilter, traceWriter)\n        {\n            _innerFilter = innerFilter;\n        }\n\n        public new IAuthenticationFilter Inner\n        {\n            get { return _innerFilter; }\n        }\n\n        public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)\n        {\n            IPrincipal originalPrincipal = null;\n            return TraceWriter.TraceBeginEndAsync(\n                request: context != null ? context.Request : null,\n                category: TraceCategories.FiltersCategory,\n                level: TraceLevel.Info,\n                operatorName: _innerFilter.GetType().Name,\n                operationName: AuthenticateAsyncMethodName,\n                beginTrace: (tr) =>\n                {\n                    if (context != null)\n                    {\n                        originalPrincipal = context.Principal;\n                    }\n                },\n                execute: () => _innerFilter.AuthenticateAsync(context, cancellationToken),\n                endTrace: (tr) =>\n                {\n                    if (context != null)\n                    {\n                        if (context.ErrorResult != null)\n                        {\n                            tr.Message = String.Format(CultureInfo.CurrentCulture,\n                                SRResources.AuthenticationFilterErrorResult,\n                                context.ErrorResult);\n                        }\n                        else if (context.Principal != originalPrincipal)\n                        {\n                            if (context.Principal == null || context.Principal.Identity == null)\n                            {\n                                tr.Message = SRResources.AuthenticationFilterSetPrincipalToUnknownIdentity;\n                            }\n                            else\n                            {\n                                tr.Message = String.Format(CultureInfo.CurrentCulture,\n                                    SRResources.AuthenticationFilterSetPrincipalToKnownIdentity,\n                                    context.Principal.Identity.Name,\n                                    context.Principal.Identity.AuthenticationType);\n                            }\n                        }\n                        else\n                        {\n                            tr.Message = SRResources.AuthenticationFilterDidNothing;\n                        }\n                    }\n                },\n                errorTrace: null);\n        }\n\n        public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)\n        {\n            return TraceWriter.TraceBeginEndAsync(\n                request: context != null ? context.Request : null,\n                category: TraceCategories.FiltersCategory,\n                level: TraceLevel.Info,\n                operatorName: _innerFilter.GetType().Name,\n                operationName: ChallengeAsyncMethodName,\n                beginTrace: null,\n                execute: () => _innerFilter.ChallengeAsync(context, cancellationToken),\n                endTrace: null,\n                errorTrace: null);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/AuthorizationFilterAttributeTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Runtime.CompilerServices;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Services;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    /// <summary>\n    /// Tracer for <see cref=\"AuthorizationFilterAttribute\"/>\n    /// </summary>\n    [SuppressMessage(\"Microsoft.Performance\", \"CA1813:AvoidUnsealedAttributes\", Justification = \"internal type needs to override, tracer are not sealed\")]\n    internal class AuthorizationFilterAttributeTracer : AuthorizationFilterAttribute, IDecorator<AuthorizationFilterAttribute>\n    {\n        private readonly AuthorizationFilterAttribute _innerFilter;\n        private readonly ITraceWriter _traceStore;\n\n        public AuthorizationFilterAttributeTracer(AuthorizationFilterAttribute innerFilter, ITraceWriter traceWriter)\n        {\n            Contract.Assert(innerFilter != null);\n            Contract.Assert(traceWriter != null);\n\n            _innerFilter = innerFilter;\n            _traceStore = traceWriter;\n        }\n\n        public AuthorizationFilterAttribute Inner\n        {\n            get { return _innerFilter; }\n        }\n\n        public override bool AllowMultiple\n        {\n            get\n            {\n                return _innerFilter.AllowMultiple;\n            }\n        }\n\n        public override object TypeId\n        {\n            get\n            {\n                return _innerFilter.TypeId;\n            }\n        }\n\n        public override bool Equals(object obj)\n        {\n            return _innerFilter.Equals(obj);\n        }\n\n        public override int GetHashCode()\n        {\n            return _innerFilter.GetHashCode();\n        }\n\n        public override bool IsDefaultAttribute()\n        {\n            return _innerFilter.IsDefaultAttribute();\n        }\n\n        public override bool Match(object obj)\n        {\n            return _innerFilter.Match(obj);\n        }\n\n        public override void OnAuthorization(HttpActionContext actionContext)\n        {\n           // this will not trace, all traces go through the async call.\n        }\n\n        public override Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)\n        {\n            return OnAuthorizationSyncCore(actionContext, cancellationToken);\n        }\n\n        private Task OnAuthorizationSyncCore(HttpActionContext actionContext,\n                                             CancellationToken cancellationToken,\n                                             [CallerMemberName] string methodName = null)\n        {\n            return _traceStore.TraceBeginEndAsync(\n                actionContext.ControllerContext.Request,\n                TraceCategories.FiltersCategory,\n                TraceLevel.Info,\n                _innerFilter.GetType().Name,\n                methodName,\n                beginTrace: (tr) =>\n                {\n                    HttpResponseMessage response = actionContext.Response;\n                    if (response != null)\n                    {\n                        tr.Status = response.StatusCode;\n                    }\n                },\n                execute: async () => { await _innerFilter.OnAuthorizationAsync(actionContext, cancellationToken); },\n                endTrace: (tr) =>\n                {\n                    HttpResponseMessage response = actionContext.Response;\n                    if (response != null)\n                    {\n                        tr.Status = response.StatusCode;\n                    }\n                },\n                errorTrace: (tr) =>\n                {\n                    HttpResponseMessage response = actionContext.Response;\n                    if (response != null)\n                    {\n                        tr.Status = response.StatusCode;\n                    }\n                });\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/AuthorizationFilterTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Services;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    /// <summary>\n    /// Tracer for <see cref=\"IAuthorizationFilter\"/>.\n    /// </summary>\n    internal class AuthorizationFilterTracer : FilterTracer, IAuthorizationFilter, IDecorator<IAuthorizationFilter>\n    {\n        private const string ExecuteAuthorizationFilterAsyncMethodName = \"ExecuteAuthorizationFilterAsync\";\n\n        public AuthorizationFilterTracer(IAuthorizationFilter innerFilter, ITraceWriter traceWriter)\n            : base(innerFilter, traceWriter)\n        {\n        }\n\n        public new IAuthorizationFilter Inner\n        {\n            get { return InnerAuthorizationFilter; }\n        }\n\n        private IAuthorizationFilter InnerAuthorizationFilter\n        {\n            get { return InnerFilter as IAuthorizationFilter; }\n        }\n\n        public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext,\n                                                                         CancellationToken cancellationToken,\n                                                                         Func<Task<HttpResponseMessage>> continuation)\n        {\n            return TraceWriter.TraceBeginEndAsync<HttpResponseMessage>(\n                actionContext.Request,\n                TraceCategories.FiltersCategory,\n                TraceLevel.Info,\n                InnerAuthorizationFilter.GetType().Name,\n                ExecuteAuthorizationFilterAsyncMethodName,\n                beginTrace: null,\n                execute: () => InnerAuthorizationFilter.ExecuteAuthorizationFilterAsync(actionContext, cancellationToken, continuation),\n                endTrace: (tr, response) =>\n                {\n                    if (response != null)\n                    {\n                        tr.Status = response.StatusCode;\n                    }\n                },\n                errorTrace: null);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/BufferedMediaTypeFormatterTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.IO;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Services;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    internal class BufferedMediaTypeFormatterTracer : BufferedMediaTypeFormatter, IFormatterTracer, IDecorator<BufferedMediaTypeFormatter>\n    {\n        private const string OnReadFromStreamMethodName = \"ReadFromStream\";\n        private const string OnWriteToStreamMethodName = \"WriteToStream\";\n\n        private readonly BufferedMediaTypeFormatter _inner;\n        private MediaTypeFormatterTracer _innerTracer;\n\n        public BufferedMediaTypeFormatterTracer(BufferedMediaTypeFormatter innerFormatter, ITraceWriter traceWriter, HttpRequestMessage request)\n            : base(innerFormatter)\n        {\n            _inner = innerFormatter;\n            _innerTracer = new MediaTypeFormatterTracer(innerFormatter, traceWriter, request);\n        }\n\n        HttpRequestMessage IFormatterTracer.Request\n        {\n            get { return _innerTracer.Request; }\n        }\n\n        public BufferedMediaTypeFormatter Inner\n        {\n            get { return _inner; }\n        }\n\n        public MediaTypeFormatter InnerFormatter\n        {\n            get { return _innerTracer.InnerFormatter; }\n        }\n\n        public override IRequiredMemberSelector RequiredMemberSelector\n        {\n            get\n            {\n                return _innerTracer.RequiredMemberSelector;\n            }\n            set\n            {\n                _innerTracer.RequiredMemberSelector = value;\n            }\n        }\n\n        public override bool CanReadType(Type type)\n        {\n            return _innerTracer.CanReadType(type);\n        }\n\n        public override bool CanWriteType(Type type)\n        {\n            return _innerTracer.CanWriteType(type);\n        }\n\n        public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)\n        {\n            return _innerTracer.GetPerRequestFormatterInstance(type, request, mediaType);\n        }\n\n        public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)\n        {\n            _innerTracer.SetDefaultContentHeaders(type, headers, mediaType);\n        }\n\n        public override object ReadFromStream(Type type, Stream readStream, HttpContent content,\n            IFormatterLogger formatterLogger)\n        {\n            return ReadFromStreamCore(type, readStream, content, formatterLogger);\n        }\n\n        public override object ReadFromStream(Type type, Stream stream, HttpContent content,\n            IFormatterLogger formatterLogger, CancellationToken cancellationToken)\n        {\n            return ReadFromStreamCore(type, stream, content, formatterLogger, cancellationToken);\n        }\n\n        private object ReadFromStreamCore(Type type, Stream stream, HttpContent content,\n            IFormatterLogger formatterLogger, CancellationToken? cancellationToken = null)\n        {\n            BufferedMediaTypeFormatter innerFormatter = InnerFormatter as BufferedMediaTypeFormatter;\n            HttpContentHeaders contentHeaders = content == null ? null : content.Headers;\n            MediaTypeHeaderValue contentType = contentHeaders == null ? null : contentHeaders.ContentType;\n            object value = null;\n\n            _innerTracer.TraceWriter.TraceBeginEnd(\n                _innerTracer.Request,\n                TraceCategories.FormattingCategory,\n                TraceLevel.Info,\n                _innerTracer.InnerFormatter.GetType().Name,\n                OnReadFromStreamMethodName,\n                beginTrace: (tr) =>\n                {\n                    tr.Message = Error.Format(\n                            SRResources.TraceReadFromStreamMessage,\n                            type.Name,\n                            contentType == null ? SRResources.TraceNoneObjectMessage : contentType.ToString());\n                },\n                execute: () =>\n                {\n                    if (cancellationToken.HasValue)\n                    {\n                        value = innerFormatter.ReadFromStream(type, stream, content, formatterLogger, cancellationToken.Value);\n                    }\n                    else\n                    {\n                        value = innerFormatter.ReadFromStream(type, stream, content, formatterLogger);\n                    }\n                },\n                endTrace: (tr) =>\n                {\n                    tr.Message = Error.Format(\n                                SRResources.TraceReadFromStreamValueMessage,\n                                FormattingUtilities.ValueToString(value, CultureInfo.CurrentCulture));\n                },\n                errorTrace: null);\n\n            return value;\n        }\n\n        public override void WriteToStream(Type type, object value, Stream writeStream, HttpContent content)\n        {\n            WriteToStreamCore(type, value, writeStream, content);\n        }\n\n        public override void WriteToStream(Type type, object value, Stream writeStream, HttpContent content,\n            CancellationToken cancellationToken)\n        {\n            WriteToStreamCore(type, value, writeStream, content, cancellationToken);\n        }\n\n        private void WriteToStreamCore(Type type, object value, Stream writeStream, HttpContent content,\n            CancellationToken? cancellationToken = null)\n        {\n            BufferedMediaTypeFormatter innerFormatter = InnerFormatter as BufferedMediaTypeFormatter;\n\n            HttpContentHeaders contentHeaders = content == null ? null : content.Headers;\n            MediaTypeHeaderValue contentType = contentHeaders == null\n                           ? null\n                           : contentHeaders.ContentType;\n\n            _innerTracer.TraceWriter.TraceBeginEnd(\n                _innerTracer.Request,\n                TraceCategories.FormattingCategory,\n                TraceLevel.Info,\n                _innerTracer.InnerFormatter.GetType().Name,\n                OnWriteToStreamMethodName,\n                beginTrace: (tr) =>\n                {\n                    tr.Message = Error.Format(\n                            SRResources.TraceWriteToStreamMessage,\n                            FormattingUtilities.ValueToString(value, CultureInfo.CurrentCulture),\n                            type.Name,\n                            contentType == null ? SRResources.TraceNoneObjectMessage : contentType.ToString());\n                },\n                execute: () =>\n                {\n                    if (cancellationToken.HasValue)\n                    {\n                        innerFormatter.WriteToStream(type, value, writeStream, content, cancellationToken.Value);\n                    }\n                    else\n                    {\n                        innerFormatter.WriteToStream(type, value, writeStream, content);\n                    }\n                },\n                endTrace: null,\n                errorTrace: null);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/ContentNegotiatorTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Services;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    /// <summary>\n    /// Tracer for <see cref=\"IContentNegotiator\"/>.\n    /// </summary>\n    internal class ContentNegotiatorTracer : IContentNegotiator, IDecorator<IContentNegotiator>\n    {\n        private const string NegotiateMethodName = \"Negotiate\";\n\n        private readonly IContentNegotiator _innerNegotiator;\n        private readonly ITraceWriter _traceWriter;\n\n        public ContentNegotiatorTracer(IContentNegotiator innerNegotiator, ITraceWriter traceWriter)\n        {\n            Contract.Assert(innerNegotiator != null);\n            Contract.Assert(traceWriter != null);\n\n            _innerNegotiator = innerNegotiator;\n            _traceWriter = traceWriter;\n        }\n\n        public IContentNegotiator Inner\n        {\n            get { return _innerNegotiator; }\n        }\n\n        public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)\n        {\n            ContentNegotiationResult result = null;\n\n            _traceWriter.TraceBeginEnd(\n                request,\n                TraceCategories.FormattingCategory,\n                TraceLevel.Info,\n                _innerNegotiator.GetType().Name,\n                NegotiateMethodName,\n\n                beginTrace: (tr) =>\n                {\n                    tr.Message = Error.Format(\n                        SRResources.TraceNegotiateFormatter,\n                        type.Name,\n                        FormattingUtilities.FormattersToString(formatters));\n                },\n\n                execute: () =>\n                {\n                    result = _innerNegotiator.Negotiate(type, request, formatters);\n                },\n\n                endTrace: (tr) =>\n                {\n                    tr.Message = Error.Format(\n                        SRResources.TraceSelectedFormatter,\n                        result == null\n                            ? SRResources.TraceNoneObjectMessage\n                            : MediaTypeFormatterTracer.ActualMediaTypeFormatter(result.Formatter).GetType().Name,\n                        result == null || result.MediaType == null\n                            ? SRResources.TraceNoneObjectMessage\n                            : result.MediaType.ToString());\n                },\n\n                errorTrace: null);\n\n            if (result != null)\n            {\n                result.Formatter = MediaTypeFormatterTracer.CreateTracer(result.Formatter, _traceWriter, request);\n            }\n\n            return result;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/DefaultHttpControllerTypeResolverTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Reflection;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Services;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    /// <summary>\n    /// Internal class to trace use of <see cref=\"DefaultHttpControllerTypeResolver\"/>.\n    /// </summary>\n    internal class DefaultHttpControllerTypeResolverTracer\n        : DefaultHttpControllerTypeResolver, IDecorator<DefaultHttpControllerTypeResolver>\n    {\n        private readonly DefaultHttpControllerTypeResolver _innerResolver;\n        private readonly ITraceWriter _traceWriter;\n        private readonly string _innerTypeName;\n\n        public DefaultHttpControllerTypeResolverTracer(DefaultHttpControllerTypeResolver innerResolver,\n            ITraceWriter traceWriter)\n        {\n            Contract.Assert(innerResolver != null);\n            Contract.Assert(traceWriter != null);\n\n            _innerResolver = innerResolver;\n            _traceWriter = traceWriter;\n            _innerTypeName = _innerResolver.GetType().Name;\n\n            // Update inner resolver to call back here. Works around fact GetControllerTypes swallows exceptions and\n            // improves tracing.\n            _innerResolver.SetGetTypesFunc(GetTypesAndTrace);\n        }\n\n        public DefaultHttpControllerTypeResolver Inner\n        {\n            get { return _innerResolver; }\n        }\n\n        protected internal override Predicate<Type> IsControllerTypePredicate\n        {\n            get { return _innerResolver.IsControllerTypePredicate; }\n        }\n\n        // Trace beginning and end of GetControllerTypes() invocations. Error tracing should never occur since base\n        // implementation swallows all exceptions.\n        public override ICollection<Type> GetControllerTypes(IAssembliesResolver assembliesResolver)\n        {\n            ICollection<Type> result = null;\n            _traceWriter.TraceBeginEnd(request: null,\n                category: TraceCategories.ControllersCategory,\n                level: TraceLevel.Debug,\n                operatorName: _innerTypeName,\n                operationName: \"GetControllerTypes\",\n                beginTrace: null,\n                execute: () => { result = _innerResolver.GetControllerTypes(assembliesResolver); },\n                endTrace: null,\n                errorTrace: null);\n\n            return result;\n        }\n\n        // Warn about any exceptions encountered in GetTypes() invocations. Do not trace beginning or end since that\n        // could be quite noisy.\n        private Type[] GetTypesAndTrace(Assembly assembly)\n        {\n            try\n            {\n                return DefaultHttpControllerTypeResolver.GetTypes(assembly);\n            }\n            catch (Exception exception)\n            {\n                _traceWriter.Warn(request: null,\n                    category: TraceCategories.ControllersCategory,\n                    exception: exception,\n                    messageFormat: SRResources.TraceHttpControllerTypeResolverError,\n                    messageArguments: assembly.FullName);\n\n                throw;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/ExceptionFilterAttributeTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Runtime.CompilerServices;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Services;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    /// <summary>\n    /// Tracer for <see cref=\"ExceptionFilterAttribute\"/>.\n    /// </summary>\n    [SuppressMessage(\"Microsoft.Performance\", \"CA1813:AvoidUnsealedAttributes\", Justification = \"internal type needs to override, tracer are not sealed\")]\n    internal class ExceptionFilterAttributeTracer : ExceptionFilterAttribute, IDecorator<ExceptionFilterAttribute>\n    {\n        private readonly ExceptionFilterAttribute _innerFilter;\n        private readonly ITraceWriter _traceStore;\n\n        public ExceptionFilterAttributeTracer(ExceptionFilterAttribute innerFilter, ITraceWriter traceWriter)\n        {\n            Contract.Assert(innerFilter != null);\n            Contract.Assert(traceWriter != null);\n\n            _innerFilter = innerFilter;\n            _traceStore = traceWriter;\n        }\n\n        public ExceptionFilterAttribute Inner\n        {\n            get { return _innerFilter; }\n        }\n\n        public override bool AllowMultiple\n        {\n            get\n            {\n                return _innerFilter.AllowMultiple;\n            }\n        }\n\n        public override object TypeId\n        {\n            get\n            {\n                return _innerFilter.TypeId;\n            }\n        }\n\n        public override bool Equals(object obj)\n        {\n            return _innerFilter.Equals(obj);\n        }\n\n        public override int GetHashCode()\n        {\n            return _innerFilter.GetHashCode();\n        }\n\n        public override bool IsDefaultAttribute()\n        {\n            return _innerFilter.IsDefaultAttribute();\n        }\n\n        public override bool Match(object obj)\n        {\n            return _innerFilter.Match(obj);\n        }\n\n        public override void OnException(HttpActionExecutedContext actionExecutedContext)\n        {\n           // this will not trace, all traces go through the async call.\n        }\n\n        public override Task OnExceptionAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)\n        {\n            return OnExceptionAsyncCore(actionExecutedContext, cancellationToken);\n        }\n\n        private Task OnExceptionAsyncCore(HttpActionExecutedContext actionExecutedContext,\n                                          CancellationToken cancellationToken,\n                                          [CallerMemberName] string methodName = null)\n        {\n            return _traceStore.TraceBeginEndAsync(\n                actionExecutedContext.Request,\n                TraceCategories.FiltersCategory,\n                TraceLevel.Info,\n                _innerFilter.GetType().Name,\n                methodName,\n                beginTrace: (tr) =>\n                {\n                    HttpResponseMessage response = actionExecutedContext.Response;\n                    if (response != null)\n                    {\n                        tr.Status = response.StatusCode;\n                    }\n                },\n                execute: async () =>\n                {\n                    await _innerFilter.OnExceptionAsync(actionExecutedContext, cancellationToken);\n                },\n                endTrace: (tr) =>\n                {\n                    Exception returnedException = actionExecutedContext.Exception;\n                    tr.Level = returnedException == null ? TraceLevel.Info : TraceLevel.Error;\n                    tr.Exception = returnedException;\n                    HttpResponseMessage response = actionExecutedContext.Response;\n                    if (response != null)\n                    {\n                        tr.Status = response.StatusCode;\n                    }\n                },\n                errorTrace: (tr) =>\n                {\n                    HttpResponseMessage response = actionExecutedContext.Response;\n                    if (response != null)\n                    {\n                        tr.Status = response.StatusCode;\n                    }\n                });\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/ExceptionFilterTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Services;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    /// <summary>\n    /// Tracer for <see cref=\"IExceptionFilter\"/>.\n    /// </summary>\n    internal class ExceptionFilterTracer : FilterTracer, IExceptionFilter, IDecorator<IExceptionFilter>\n    {\n        private const string ExecuteExceptionFilterAsyncMethodName = \"ExecuteExceptionFilterAsync\";\n\n        public ExceptionFilterTracer(IExceptionFilter innerFilter, ITraceWriter traceWriter)\n            : base(innerFilter, traceWriter)\n        {\n        }\n\n        public new IExceptionFilter Inner\n        {\n            get { return InnerExceptionFilter; }\n        }\n\n        public IExceptionFilter InnerExceptionFilter\n        {\n            get { return InnerFilter as IExceptionFilter; }\n        }\n\n        public Task ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext,\n                                                CancellationToken cancellationToken)\n        {\n            return TraceWriter.TraceBeginEndAsync(\n                actionExecutedContext.Request,\n                TraceCategories.FiltersCategory,\n                TraceLevel.Info,\n                InnerExceptionFilter.GetType().Name,\n                ExecuteExceptionFilterAsyncMethodName,\n                beginTrace: (tr) =>\n                {\n                    tr.Exception = actionExecutedContext.Exception;\n                },\n\n                execute: () => InnerExceptionFilter.ExecuteExceptionFilterAsync(actionExecutedContext, cancellationToken),\n\n                endTrace: (tr) =>\n                {\n                    tr.Exception = actionExecutedContext.Exception;\n                },\n\n                errorTrace: null);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/FilterTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Services;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    /// <summary>\n    /// Base class and helper for the creation of filter tracers.\n    /// </summary>\n    internal class FilterTracer : IFilter, IDecorator<IFilter>\n    {\n        public FilterTracer(IFilter innerFilter, ITraceWriter traceWriter)\n        {\n            Contract.Assert(innerFilter != null);\n            Contract.Assert(traceWriter != null);\n\n            InnerFilter = innerFilter;\n            TraceWriter = traceWriter;\n        }\n\n        public IFilter Inner\n        {\n            get { return InnerFilter; }\n        }\n\n        public IFilter InnerFilter { get; set; }\n\n        public ITraceWriter TraceWriter { get; set; }\n\n        public bool AllowMultiple\n        {\n            get { return InnerFilter.AllowMultiple; }\n        }\n\n        public static IEnumerable<IFilter> CreateFilterTracers(IFilter filter, ITraceWriter traceWriter)\n        {\n            List<IFilter> filters = new List<IFilter>();\n            bool addedActionAttributeTracer = false;\n            bool addedAuthorizationAttributeTracer = false;\n            bool addedExceptionAttributeTracer = false;\n\n            ActionFilterAttribute actionFilterAttribute = filter as ActionFilterAttribute;\n            if (actionFilterAttribute != null)\n            {\n                filters.Add(new ActionFilterAttributeTracer(actionFilterAttribute, traceWriter));\n                addedActionAttributeTracer = true;\n            }\n\n            AuthorizationFilterAttribute authorizationFilterAttribute = filter as AuthorizationFilterAttribute;\n            if (authorizationFilterAttribute != null)\n            {\n                filters.Add(new AuthorizationFilterAttributeTracer(authorizationFilterAttribute, traceWriter));\n                addedAuthorizationAttributeTracer = true;\n            }\n\n            ExceptionFilterAttribute exceptionFilterAttribute = filter as ExceptionFilterAttribute;\n            if (exceptionFilterAttribute != null)\n            {\n                filters.Add(new ExceptionFilterAttributeTracer(exceptionFilterAttribute, traceWriter));\n                addedExceptionAttributeTracer = true;\n            }\n\n            // Do not add an IActionFilter tracer if we already added an ActionFilterAttribute tracer\n            IActionFilter actionFilter = filter as IActionFilter;\n            if (actionFilter != null && !addedActionAttributeTracer)\n            {\n                filters.Add(new ActionFilterTracer(actionFilter, traceWriter));\n            }\n\n            // Do not add an IAuthorizationFilter tracer if we already added an AuthorizationFilterAttribute tracer\n            IAuthorizationFilter authorizationFilter = filter as IAuthorizationFilter;\n            if (authorizationFilter != null && !addedAuthorizationAttributeTracer)\n            {\n                filters.Add(new AuthorizationFilterTracer(authorizationFilter, traceWriter));\n            }\n\n            IAuthenticationFilter authenticationFilter = filter as IAuthenticationFilter;\n            if (authenticationFilter != null)\n            {\n                filters.Add(new AuthenticationFilterTracer(authenticationFilter, traceWriter));\n            }\n\n            // Do not add an IExceptionFilter tracer if we already added an ExceptoinFilterAttribute tracer\n            IExceptionFilter exceptionFilter = filter as IExceptionFilter;\n            if (exceptionFilter != null && !addedExceptionAttributeTracer)\n            {\n                filters.Add(new ExceptionFilterTracer(exceptionFilter, traceWriter));\n            }\n\n            IOverrideFilter overrideFilter = filter as IOverrideFilter;\n            if (overrideFilter != null)\n            {\n                filters.Add(new OverrideFilterTracer(overrideFilter, traceWriter));\n            }\n\n            if (filters.Count == 0)\n            {\n                filters.Add(new FilterTracer(filter, traceWriter));\n            }\n            \n            return filters;\n        }\n\n        public static IEnumerable<FilterInfo> CreateFilterTracers(FilterInfo filter, ITraceWriter traceWriter)\n        {\n            IFilter filterInstance = filter.Instance;\n            IEnumerable<IFilter> filterTracers = CreateFilterTracers(filterInstance, traceWriter);\n            List<FilterInfo> filters = new List<FilterInfo>();\n            foreach (IFilter filterTracer in filterTracers)\n            {\n                filters.Add(new FilterInfo(filterTracer, filter.Scope));\n            }\n\n            return filters;\n        }\n\n        public static bool IsFilterTracer(IFilter filter)\n        {\n            return filter is FilterTracer ||\n                   filter is ActionFilterAttributeTracer ||\n                   filter is AuthorizationFilterAttributeTracer ||\n                   filter is ExceptionFilterAttributeTracer;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/FormUrlEncodedMediaTypeFormatterTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Services;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    /// <summary>\n    /// Tracer for <see cref=\"FormUrlEncodedMediaTypeFormatter\"/>.  \n    /// It is required because users can select formatters by this type.\n    /// </summary>\n    internal class FormUrlEncodedMediaTypeFormatterTracer : FormUrlEncodedMediaTypeFormatter, IFormatterTracer, IDecorator<FormUrlEncodedMediaTypeFormatter>\n    {\n        private readonly FormUrlEncodedMediaTypeFormatter _inner;\n        private MediaTypeFormatterTracer _innerTracer;\n\n        public FormUrlEncodedMediaTypeFormatterTracer(FormUrlEncodedMediaTypeFormatter innerFormatter, ITraceWriter traceWriter, HttpRequestMessage request)\n            : base(innerFormatter)\n        {\n            _inner = innerFormatter;\n            _innerTracer = new MediaTypeFormatterTracer(innerFormatter, traceWriter, request);\n        }\n\n        HttpRequestMessage IFormatterTracer.Request\n        {\n            get { return _innerTracer.Request; }\n        }\n\n        public FormUrlEncodedMediaTypeFormatter Inner\n        {\n            get { return _inner; }\n        }\n\n        public MediaTypeFormatter InnerFormatter\n        {\n            get { return _innerTracer.InnerFormatter; }\n        }\n\n        public override IRequiredMemberSelector RequiredMemberSelector\n        {\n            get\n            {\n                return _innerTracer.RequiredMemberSelector;\n            }\n            set\n            {\n                _innerTracer.RequiredMemberSelector = value;\n            }\n        }\n\n        public override bool CanReadType(Type type)\n        {\n            return _innerTracer.CanReadType(type);\n        }\n\n        public override bool CanWriteType(Type type)\n        {\n            return _innerTracer.CanWriteType(type);\n        }\n\n        public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)\n        {\n            return _innerTracer.GetPerRequestFormatterInstance(type, request, mediaType);\n        }\n\n        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content,\n            IFormatterLogger formatterLogger, CancellationToken cancellationToken)\n        {\n            return _innerTracer.ReadFromStreamAsync(type, readStream, content, formatterLogger, cancellationToken);\n        }\n\n        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)\n        {\n            return _innerTracer.ReadFromStreamAsync(type, readStream, content, formatterLogger);\n        }\n\n        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content,\n            TransportContext transportContext, CancellationToken cancellationToken)\n        {\n            return _innerTracer.WriteToStreamAsync(type, value, writeStream, content, transportContext, cancellationToken);\n        }\n\n        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)\n        {\n            return _innerTracer.WriteToStreamAsync(type, value, writeStream, content, transportContext);\n        }\n\n        public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)\n        {\n            _innerTracer.SetDefaultContentHeaders(type, headers, mediaType);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/FormatterLoggerTraceWrapper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    /// <summary>\n    /// FormatterLogger to trace an error while logging.\n    /// </summary>\n    internal class FormatterLoggerTraceWrapper : IFormatterLogger\n    {\n        private readonly IFormatterLogger _formatterLogger;\n        private readonly ITraceWriter _traceWriter;\n        private readonly HttpRequestMessage _request;\n        private readonly string _operatorName;\n        private readonly string _operationName;\n\n        public FormatterLoggerTraceWrapper(IFormatterLogger formatterLogger,\n                                           ITraceWriter traceWriter,\n                                           HttpRequestMessage request,\n                                           string operatorName,\n                                           string operationName)\n        {\n            Contract.Assert(formatterLogger != null);\n            Contract.Assert(traceWriter != null);\n\n            _formatterLogger = formatterLogger;\n            _traceWriter = traceWriter;\n            _request = request;\n            _operatorName = operatorName;\n            _operationName = operationName;\n        }\n\n        public void LogError(string errorPath, string errorMessage)\n        {\n            _traceWriter.Trace(_request, TraceCategories.FormattingCategory, TraceLevel.Error, (traceRecord) =>\n                {\n                    traceRecord.Kind = TraceKind.Trace;\n                    traceRecord.Operator = _operatorName;\n                    traceRecord.Operation = _operationName;\n                    traceRecord.Message = errorMessage;\n                });\n            _formatterLogger.LogError(errorPath, errorMessage);\n        }\n\n        public void LogError(string errorPath, Exception exception)\n        {\n            _traceWriter.Trace(_request, TraceCategories.FormattingCategory, TraceLevel.Error, (traceRecord) =>\n                {\n                    traceRecord.Kind = TraceKind.Trace;\n                    traceRecord.Operator = _operatorName;\n                    traceRecord.Operation = _operationName;\n                    traceRecord.Exception = exception;\n                });\n            _formatterLogger.LogError(errorPath, exception);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/FormatterParameterBindingTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Services;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    /// <summary>\n    /// Tracer to wrap a <see cref=\"FormatterParameterBinding\"/>.\n    /// Its primary purpose is to intercept binding requests so that it can create tracers for the formatters.\n    /// </summary>\n    internal class FormatterParameterBindingTracer : FormatterParameterBinding, IDecorator<FormatterParameterBinding>\n    {\n        private const string ExecuteBindingAsyncMethodName = \"ExecuteBindingAsync\";\n\n        private readonly FormatterParameterBinding _innerBinding;\n        private readonly ITraceWriter _traceWriter;\n\n        public FormatterParameterBindingTracer(FormatterParameterBinding innerBinding, ITraceWriter traceWriter)\n            : base(innerBinding.Descriptor, innerBinding.Formatters, innerBinding.BodyModelValidator)\n        {\n            Contract.Assert(innerBinding != null);\n            Contract.Assert(traceWriter != null);\n\n            _innerBinding = innerBinding;\n            _traceWriter = traceWriter;\n        }\n\n        public FormatterParameterBinding Inner\n        {\n            get { return _innerBinding; }\n        }\n\n        public override string ErrorMessage\n        {\n            get { return _innerBinding.ErrorMessage; }\n        }\n\n        public override bool WillReadBody\n        {\n            get { return _innerBinding.WillReadBody; }\n        }\n\n        public override Task<object> ReadContentAsync(HttpRequestMessage request, Type type,\n            IEnumerable<MediaTypeFormatter> formatters, IFormatterLogger formatterLogger)\n        {\n            // Intercept this method solely to wrap formatters with request-aware formatter tracers\n            // There is no other interception point where a request and a formatter are paired.\n            return _innerBinding.ReadContentAsync(request, type, CreateFormatterTracers(request, formatters), formatterLogger);\n        }\n\n        public override Task<object> ReadContentAsync(HttpRequestMessage request, Type type,\n            IEnumerable<MediaTypeFormatter> formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\n        {\n            return _innerBinding.ReadContentAsync(request, type, formatters, formatterLogger, cancellationToken);\n        }\n\n        public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext,\n            CancellationToken cancellationToken)\n        {\n            return _traceWriter.TraceBeginEndAsync(\n                actionContext.Request,\n                TraceCategories.ModelBindingCategory,\n                TraceLevel.Info,\n                _innerBinding.GetType().Name,\n                ExecuteBindingAsyncMethodName,\n                beginTrace: (tr) =>\n                {\n                    tr.Message = Error.Format(SRResources.TraceBeginParameterBind,\n                                              _innerBinding.Descriptor.ParameterName);\n                },\n\n                execute: () => _innerBinding.ExecuteBindingAsync(metadataProvider, actionContext, cancellationToken),\n\n                endTrace: (tr) =>\n                {\n                    string parameterName = _innerBinding.Descriptor.ParameterName;\n                    tr.Message = actionContext.ActionArguments.ContainsKey(parameterName)\n                                    ? Error.Format(SRResources.TraceEndParameterBind, parameterName,\n                                                    FormattingUtilities.ValueToString(actionContext.ActionArguments[parameterName], CultureInfo.CurrentCulture))\n                                    : Error.Format(SRResources.TraceEndParameterBindNoBind,\n                                                    parameterName);\n                },\n                errorTrace: null);\n        }\n\n        private IEnumerable<MediaTypeFormatter> CreateFormatterTracers(HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)\n        {\n            List<MediaTypeFormatter> formatterTracers = new List<MediaTypeFormatter>();\n            foreach (MediaTypeFormatter formatter in formatters)\n            {\n                formatterTracers.Add(MediaTypeFormatterTracer.CreateTracer(formatter, _traceWriter, request));\n            }\n\n            return formatterTracers;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/HttpActionBindingTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Services;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    internal class HttpActionBindingTracer : HttpActionBinding, IDecorator<HttpActionBinding>\n    {\n        private const string ExecuteBindingAsyncMethodName = \"ExecuteBindingAsync\";\n\n        private readonly HttpActionBinding _innerBinding;\n        private readonly ITraceWriter _traceWriter;\n\n        public HttpActionBindingTracer(HttpActionBinding innerBinding, ITraceWriter traceWriter)\n        {\n            Contract.Assert(innerBinding != null);\n            Contract.Assert(traceWriter != null);\n\n            _innerBinding = innerBinding;\n            _traceWriter = traceWriter;\n\n            // Properties that cannot be delegated to the inner must be replicated.\n            // They must also avoid an ArgumentNullException for null values.\n            if (_innerBinding.ParameterBindings != null)\n            {\n                ParameterBindings = _innerBinding.ParameterBindings;\n            }\n\n            if (_innerBinding.ActionDescriptor != null)\n            {\n                ActionDescriptor = _innerBinding.ActionDescriptor;\n            }\n        }\n\n        public HttpActionBinding Inner\n        {\n            get { return _innerBinding; }\n        }\n\n        public override Task ExecuteBindingAsync(Controllers.HttpActionContext actionContext, CancellationToken cancellationToken)\n        {\n            return _traceWriter.TraceBeginEndAsync(\n                actionContext.ControllerContext.Request,\n                TraceCategories.ModelBindingCategory,\n                TraceLevel.Info,\n                _innerBinding.GetType().Name,\n                ExecuteBindingAsyncMethodName,\n                beginTrace: null,\n                execute: () => _innerBinding.ExecuteBindingAsync(actionContext, cancellationToken),\n                endTrace: (tr) =>\n                {\n                    if (!actionContext.ModelState.IsValid)\n                    {\n                        tr.Message = Error.Format(SRResources.TraceModelStateInvalidMessage,\n                                                  FormattingUtilities.ModelStateToString(\n                                                        actionContext.ModelState));\n                    }\n                    else\n                    {\n                        if (actionContext.ActionDescriptor.GetParameters().Count > 0)\n                        {\n                            tr.Message = Error.Format(SRResources.TraceValidModelState,\n                                                      FormattingUtilities.ActionArgumentsToString(\n                                                            actionContext.ActionArguments));\n                        }\n                    }\n                },\n                errorTrace: null);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/HttpActionDescriptorTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Services;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    /// <summary>\n    /// Tracer for <see cref=\"HttpActionDescriptor\"/>.\n    /// </summary>\n    internal class HttpActionDescriptorTracer : HttpActionDescriptor, IDecorator<HttpActionDescriptor>\n    {\n        private const string ExecuteMethodName = \"ExecuteAsync\";\n\n        private readonly HttpActionDescriptor _innerDescriptor;\n        private readonly ITraceWriter _traceWriter;\n\n        public HttpActionDescriptorTracer(HttpControllerContext controllerContext, HttpActionDescriptor innerDescriptor, ITraceWriter traceWriter)\n            : base(controllerContext.ControllerDescriptor)\n        {\n            Contract.Assert(innerDescriptor != null);\n            Contract.Assert(traceWriter != null);\n\n            _innerDescriptor = innerDescriptor;\n            _traceWriter = traceWriter;\n        }\n\n        public HttpActionDescriptor Inner\n        {\n            get { return _innerDescriptor; }\n        }\n\n        public override ConcurrentDictionary<object, object> Properties\n        {\n            get\n            {\n                return _innerDescriptor.Properties;\n            }\n        }\n\n        public override HttpActionBinding ActionBinding\n        {\n            get\n            {\n                return _innerDescriptor.ActionBinding;\n            }\n            set\n            {\n                _innerDescriptor.ActionBinding = value;\n            }\n        }\n\n        public override Collection<HttpMethod> SupportedHttpMethods\n        {\n            get\n            {\n                return _innerDescriptor.SupportedHttpMethods;\n            }\n        }\n\n        public override string ActionName\n        {\n            get { return _innerDescriptor.ActionName; }\n        }\n\n        public override IActionResultConverter ResultConverter\n        {\n            get { return _innerDescriptor.ResultConverter; }\n        }\n\n        public override Type ReturnType\n        {\n            get { return _innerDescriptor.ReturnType; }\n        }\n\n        public override Task<object> ExecuteAsync(HttpControllerContext controllerContext, IDictionary<string, object> arguments, CancellationToken cancellationToken)\n        {\n            return _traceWriter.TraceBeginEndAsync<object>(\n                controllerContext.Request,\n                TraceCategories.ActionCategory,\n                TraceLevel.Info,\n                _innerDescriptor.GetType().Name,\n                ExecuteMethodName,\n                beginTrace: (tr) =>\n                {\n                    tr.Message = Error.Format(SRResources.TraceInvokingAction,\n                                              FormattingUtilities.ActionInvokeToString(ActionName, arguments));\n                },\n                execute: () =>\n                {\n                    return _innerDescriptor.ExecuteAsync(controllerContext, arguments, cancellationToken);\n                },\n                endTrace: (tr, value) =>\n                {\n                    tr.Message = Error.Format(SRResources.TraceActionReturnValue,\n                                              FormattingUtilities.ValueToString(value, CultureInfo.CurrentCulture));\n                },\n                errorTrace: null);\n        }\n\n        public override Collection<T> GetCustomAttributes<T>()\n        {\n            return _innerDescriptor.GetCustomAttributes<T>();\n        }\n\n        public override Collection<T> GetCustomAttributes<T>(bool inherit)\n        {\n            return _innerDescriptor.GetCustomAttributes<T>(inherit);\n        }\n\n        public override Collection<IFilter> GetFilters()\n        {\n            List<IFilter> filters = new List<IFilter>(_innerDescriptor.GetFilters());\n            List<IFilter> returnFilters = new List<IFilter>(filters.Count);\n            for (int i = 0; i < filters.Count; i++)\n            {\n                if (FilterTracer.IsFilterTracer(filters[i]))\n                {\n                    returnFilters.Add(filters[i]);\n                }\n                else\n                {\n                    IEnumerable<IFilter> filterTracers = FilterTracer.CreateFilterTracers(filters[i], _traceWriter);\n                    foreach (IFilter filterTracer in filterTracers)\n                    {\n                        returnFilters.Add(filterTracer);\n                    }\n                }\n            }\n\n            return new Collection<IFilter>(returnFilters);\n        }\n\n        public override Collection<FilterInfo> GetFilterPipeline()\n        {\n            List<FilterInfo> filters = new List<FilterInfo>(_innerDescriptor.GetFilterPipeline());\n            List<FilterInfo> returnFilters = new List<FilterInfo>(filters.Count);\n            for (int i = 0; i < filters.Count; i++)\n            {\n                // If this filter has been wrapped already, use as is\n                if (FilterTracer.IsFilterTracer(filters[i].Instance))\n                {\n                    returnFilters.Add(filters[i]);\n                }\n                else\n                {\n                    IEnumerable<FilterInfo> filterTracers = FilterTracer.CreateFilterTracers(filters[i], _traceWriter);\n                    foreach (FilterInfo filterTracer in filterTracers)\n                    {\n                        returnFilters.Add(filterTracer);\n                    }\n                }\n            }\n\n            return new Collection<FilterInfo>(returnFilters);\n        }\n\n        public override Collection<HttpParameterDescriptor> GetParameters()\n        {\n            return _innerDescriptor.GetParameters();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/HttpActionInvokerTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Services;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    /// <summary>\n    /// Tracer for <see cref=\"IHttpActionInvoker\"/>.\n    /// </summary>\n    internal class HttpActionInvokerTracer : IHttpActionInvoker, IDecorator<IHttpActionInvoker>\n    {\n        private const string InvokeActionAsyncMethodName = \"InvokeActionAsync\";\n\n        private readonly IHttpActionInvoker _innerInvoker;\n        private readonly ITraceWriter _traceWriter;\n\n        public HttpActionInvokerTracer(IHttpActionInvoker innerInvoker, ITraceWriter traceWriter)\n        {\n            Contract.Assert(innerInvoker != null);\n            Contract.Assert(traceWriter != null);\n\n            _innerInvoker = innerInvoker;\n            _traceWriter = traceWriter;\n        }\n\n        public IHttpActionInvoker Inner\n        {\n            get { return _innerInvoker; }\n        }\n\n        Task<HttpResponseMessage> IHttpActionInvoker.InvokeActionAsync(HttpActionContext actionContext, CancellationToken cancellationToken)\n        {\n            if (actionContext == null)\n            {\n                throw new ArgumentNullException(\"actionContext\");\n            }\n\n            return _traceWriter.TraceBeginEndAsync<HttpResponseMessage>(\n                actionContext.ControllerContext.Request,\n                TraceCategories.ActionCategory,\n                TraceLevel.Info,\n                _innerInvoker.GetType().Name,\n                InvokeActionAsyncMethodName,\n\n                beginTrace: (tr) =>\n                {\n                    tr.Message = Error.Format(\n                        SRResources.TraceActionInvokeMessage,\n                        FormattingUtilities.ActionInvokeToString(actionContext));\n                },\n\n                execute: () => (Task<HttpResponseMessage>)_innerInvoker.InvokeActionAsync(actionContext, cancellationToken),\n\n                endTrace: (tr, result) =>\n                {\n                    HttpResponseMessage response = result;\n                    if (response != null)\n                    {\n                        tr.Status = response.StatusCode;\n                    }\n                },\n\n                errorTrace: null);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/HttpActionSelectorTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Services;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    /// <summary>\n    /// Tracer for <see cref=\"IHttpActionSelector\"/>.\n    /// </summary>\n    internal class HttpActionSelectorTracer : IHttpActionSelector, IDecorator<IHttpActionSelector>\n    {\n        private const string SelectActionMethodName = \"SelectAction\";\n\n        private readonly IHttpActionSelector _innerSelector;\n        private readonly ITraceWriter _traceWriter;\n\n        public HttpActionSelectorTracer(IHttpActionSelector innerSelector, ITraceWriter traceWriter)\n        {\n            Contract.Assert(innerSelector != null);\n            Contract.Assert(traceWriter != null);\n\n            _innerSelector = innerSelector;\n            _traceWriter = traceWriter;\n        }\n\n        public IHttpActionSelector Inner\n        {\n            get { return _innerSelector; }\n        }\n\n        public ILookup<string, HttpActionDescriptor> GetActionMapping(HttpControllerDescriptor controllerDescriptor)\n        {\n            return _innerSelector.GetActionMapping(controllerDescriptor);\n        }\n\n        HttpActionDescriptor IHttpActionSelector.SelectAction(HttpControllerContext controllerContext)\n        {\n            HttpActionDescriptor actionDescriptor = null;\n\n            _traceWriter.TraceBeginEnd(\n                    controllerContext.Request,\n                    TraceCategories.ActionCategory,\n                    TraceLevel.Info,\n                    _innerSelector.GetType().Name,\n                    SelectActionMethodName,\n                    beginTrace: null,\n                    execute: () => { actionDescriptor = _innerSelector.SelectAction(controllerContext); },\n                    endTrace: (tr) =>\n                    {\n                        tr.Message = Error.Format(\n                            SRResources.TraceActionSelectedMessage,\n                            FormattingUtilities.ActionDescriptorToString(actionDescriptor));\n                    },\n\n                    errorTrace: null);\n\n            // Intercept returned HttpActionDescriptor with a tracing version\n            if (actionDescriptor != null && !(actionDescriptor is HttpActionDescriptorTracer))\n            {\n                return new HttpActionDescriptorTracer(controllerContext, actionDescriptor, _traceWriter);\n            }\n\n            return actionDescriptor;\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/HttpControllerActivatorTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Services;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    /// <summary>\n    /// Tracer for <see cref=\"IHttpControllerActivator\"/>.\n    /// </summary>\n    internal class HttpControllerActivatorTracer : IHttpControllerActivator, IDecorator<IHttpControllerActivator>\n    {\n        private const string CreateMethodName = \"Create\";\n\n        private readonly IHttpControllerActivator _innerActivator;\n        private readonly ITraceWriter _traceWriter;\n\n        public HttpControllerActivatorTracer(IHttpControllerActivator innerActivator, ITraceWriter traceWriter)\n        {\n            Contract.Assert(innerActivator != null);\n            Contract.Assert(traceWriter != null);\n\n            _innerActivator = innerActivator;\n            _traceWriter = traceWriter;\n        }\n\n        public IHttpControllerActivator Inner\n        {\n            get { return _innerActivator; }\n        }\n\n        [System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"disposable controller is later released in ReleaseController\")]\n        IHttpController IHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\n        {\n            IHttpController controller = null;\n\n            _traceWriter.TraceBeginEnd(\n                request,\n                TraceCategories.ControllersCategory,\n                TraceLevel.Info,\n                _innerActivator.GetType().Name,\n                CreateMethodName,\n                beginTrace: null,\n                execute: () =>\n                {\n                    controller = _innerActivator.Create(request, controllerDescriptor, controllerType);\n                },\n                endTrace: (tr) =>\n                {\n                    tr.Message = controller == null ? SRResources.TraceNoneObjectMessage : controller.GetType().FullName;\n                },\n                errorTrace: null);\n\n            if (controller != null && !(controller is HttpControllerTracer))\n            {\n                controller = new HttpControllerTracer(request, controller, _traceWriter);\n            }\n\n            return controller;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/HttpControllerDescriptorTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Collections.ObjectModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Services;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    /// <summary>\n    /// Tracer for <see cref=\" HttpControllerDescriptor\"/>\n    /// </summary>\n    internal class HttpControllerDescriptorTracer : HttpControllerDescriptor, IDecorator<HttpControllerDescriptor>\n    {\n        private const string CreateControllerMethodName = \"CreateController\";\n\n        private readonly HttpControllerDescriptor _innerDescriptor;\n        private readonly ITraceWriter _traceWriter;\n\n        public HttpControllerDescriptorTracer(HttpControllerDescriptor innerDescriptor, ITraceWriter traceWriter)\n        {\n            Contract.Assert(innerDescriptor != null);\n            Contract.Assert(traceWriter != null);\n\n            Configuration = innerDescriptor.Configuration;\n            ControllerName = innerDescriptor.ControllerName;\n            ControllerType = innerDescriptor.ControllerType;\n\n            _innerDescriptor = innerDescriptor;\n            _traceWriter = traceWriter;\n        }\n\n        public HttpControllerDescriptor Inner\n        {\n            get { return _innerDescriptor; }\n        }\n\n        public override ConcurrentDictionary<object, object> Properties\n        {\n            get\n            {\n                return _innerDescriptor.Properties;\n            }\n        }\n\n        public override Collection<T> GetCustomAttributes<T>()\n        {\n            return _innerDescriptor.GetCustomAttributes<T>();\n        }\n\n        public override Collection<T> GetCustomAttributes<T>(bool inherit)\n        {\n            return _innerDescriptor.GetCustomAttributes<T>(inherit);\n        }\n\n        public override Collection<Filters.IFilter> GetFilters()\n        {\n            return _innerDescriptor.GetFilters();\n        }\n\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"This object is returned back to the caller\")]\n        public override IHttpController CreateController(HttpRequestMessage request)\n        {\n            IHttpController controller = null;\n\n            _traceWriter.TraceBeginEnd(\n                request,\n                TraceCategories.ControllersCategory,\n                TraceLevel.Info,\n                _innerDescriptor.GetType().Name,\n                CreateControllerMethodName,\n                beginTrace: null,\n                execute: () =>\n                {\n                    controller = _innerDescriptor.CreateController(request);\n                },\n                endTrace: (tr) =>\n                {\n                    tr.Message = controller == null\n                                        ? SRResources.TraceNoneObjectMessage\n                                        : HttpControllerTracer.ActualControllerType(controller).FullName;\n                },\n                errorTrace: null);\n\n            if (controller != null && !(controller is HttpControllerTracer))\n            {\n                return new HttpControllerTracer(request, controller, _traceWriter);\n            }\n\n            return controller;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/HttpControllerSelectorTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Services;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    /// <summary>\n    /// Tracer for <see cref=\"IHttpControllerSelector\"/>.\n    /// </summary>\n    internal class HttpControllerSelectorTracer : IHttpControllerSelector, IDecorator<IHttpControllerSelector>\n    {\n        private const string SelectControllerMethodName = \"SelectController\";\n\n        private readonly IHttpControllerSelector _innerSelector;\n        private readonly ITraceWriter _traceWriter;\n\n        public HttpControllerSelectorTracer(IHttpControllerSelector innerSelector, ITraceWriter traceWriter)\n        {\n            Contract.Assert(innerSelector != null);\n            Contract.Assert(traceWriter != null);\n\n            _innerSelector = innerSelector;\n            _traceWriter = traceWriter;\n        }\n\n        public IHttpControllerSelector Inner\n        {\n            get { return _innerSelector; }\n        }\n\n        HttpControllerDescriptor IHttpControllerSelector.SelectController(HttpRequestMessage request)\n        {\n            HttpControllerDescriptor controllerDescriptor = null;\n\n            _traceWriter.TraceBeginEnd(\n                request,\n                TraceCategories.ControllersCategory,\n                TraceLevel.Info,\n                _innerSelector.GetType().Name,\n                SelectControllerMethodName,\n                beginTrace: (tr) =>\n                {\n                    tr.Message = Error.Format(\n                                    SRResources.TraceRouteMessage,\n                                    FormattingUtilities.RouteToString(request.GetRouteData()));\n                },\n                execute: () =>\n                {\n                    controllerDescriptor = _innerSelector.SelectController(request);\n                },\n                endTrace: (tr) =>\n                {\n                    tr.Message = controllerDescriptor == null\n                                        ? SRResources.TraceNoneObjectMessage\n                                        : controllerDescriptor.ControllerName;\n                },\n                errorTrace: null);\n\n            if (controllerDescriptor != null && !(controllerDescriptor is HttpControllerDescriptorTracer))\n            {\n                return new HttpControllerDescriptorTracer(controllerDescriptor, _traceWriter);\n            }\n\n            return controllerDescriptor;\n        }\n\n        IDictionary<string, HttpControllerDescriptor> IHttpControllerSelector.GetControllerMapping()\n        {\n            return _innerSelector.GetControllerMapping();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/HttpControllerTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.Services;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    /// <summary>\n    /// Tracer for <see cref=\"IHttpController\"/>.\n    /// </summary>\n    internal class HttpControllerTracer : IHttpController, IDisposable, IDecorator<IHttpController>\n    {\n        private const string DisposeMethodName = \"Dispose\";\n        private const string ExecuteAsyncMethodName = \"ExecuteAsync\";\n\n        private readonly IHttpController _innerController;\n        private readonly HttpRequestMessage _request;\n        private readonly ITraceWriter _traceWriter;\n\n        public HttpControllerTracer(HttpRequestMessage request, IHttpController innerController, ITraceWriter traceWriter)\n        {\n            Contract.Assert(innerController != null);\n            Contract.Assert(traceWriter != null);\n\n            _innerController = innerController;\n            _request = request;\n            _traceWriter = traceWriter;\n        }\n\n        public IHttpController Inner\n        {\n            get { return _innerController; }\n        }\n\n        void IDisposable.Dispose()\n        {\n            IDisposable disposable = _innerController as IDisposable;\n            if (disposable != null)\n            {\n                _traceWriter.TraceBeginEnd(\n                    _request,\n                    TraceCategories.ControllersCategory,\n                    TraceLevel.Info,\n                    _innerController.GetType().Name,\n                    DisposeMethodName,\n                    beginTrace: null,\n                    execute: disposable.Dispose,\n                    endTrace: null,\n                    errorTrace: null);\n            }\n        }\n\n        Task<HttpResponseMessage> IHttpController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)\n        {\n            return _traceWriter.TraceBeginEndAsync<HttpResponseMessage>(\n                controllerContext.Request,\n                TraceCategories.ControllersCategory,\n                TraceLevel.Info,\n                _innerController.GetType().Name,\n                ExecuteAsyncMethodName,\n                beginTrace: null,\n                execute: () =>\n                {\n                    // Critical to allow wrapped controller to have itself in ControllerContext\n                    controllerContext.Controller = ActualController(controllerContext.Controller);\n                    return ExecuteAsyncCore(controllerContext, cancellationToken);\n                },\n                endTrace: (tr, response) =>\n                {\n                    if (response != null)\n                    {\n                        tr.Status = response.StatusCode;\n                    }\n                },\n                errorTrace: null);\n        }\n\n        private async Task<HttpResponseMessage> ExecuteAsyncCore(HttpControllerContext controllerContext, CancellationToken cancellationToken)\n        {\n            try\n            {\n                return await _innerController.ExecuteAsync(controllerContext, cancellationToken);\n            }\n            finally\n            {\n                IDisposable disposable = _innerController as IDisposable;\n\n                if (disposable != null)\n                {\n                    // Need to remove the original controller from the disposables list, if it's\n                    // there, and put ourselves in there instead, so we can trace the dispose.\n                    // This currently knows a little too much about how RegisterForDispose works,\n                    // but that's unavoidable unless we want to offer UnregisterForDispose.\n                    IList<IDisposable> disposables;\n                    if (_request.Properties.TryGetValue(HttpPropertyKeys.DisposableRequestResourcesKey, out disposables))\n                    {\n                        disposables.Remove(disposable);\n                        disposables.Add(this);\n                    }\n                }\n            }\n        }\n\n        public static IHttpController ActualController(IHttpController controller)\n        {\n            HttpControllerTracer tracer = controller as HttpControllerTracer;\n            return tracer == null ? controller : tracer._innerController;\n        }\n\n        public static Type ActualControllerType(IHttpController controller)\n        {\n            return ActualController(controller).GetType();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/HttpParameterBindingTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Services;\nusing System.Web.Http.ValueProviders;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    /// <summary>\n    /// Tracer to wrap an <see cref=\"HttpParameterBinding\"/>.\n    /// Its primary purpose is to monitor <see cref=\"ExecuteBindingAsync\"/>.\n    /// </summary>\n    internal class HttpParameterBindingTracer : HttpParameterBinding, IValueProviderParameterBinding, IDecorator<HttpParameterBinding>\n    {\n        private const string ExecuteBindingAsyncMethodName = \"ExecuteBindingAsync\";\n\n        public HttpParameterBindingTracer(HttpParameterBinding innerBinding, ITraceWriter traceWriter) : base(innerBinding.Descriptor)\n        {\n            Contract.Assert(innerBinding != null);\n            Contract.Assert(traceWriter != null);\n\n            InnerBinding = innerBinding;\n            TraceWriter = traceWriter;\n        }\n\n        public HttpParameterBinding Inner\n        {\n            get { return InnerBinding; }\n        }\n\n        protected HttpParameterBinding InnerBinding { get; private set; }\n\n        protected ITraceWriter TraceWriter { get; private set; }\n\n        public override string ErrorMessage\n        {\n            get\n            {\n                return InnerBinding.ErrorMessage;\n            }\n        }\n\n        public override bool WillReadBody\n        {\n            get\n            {\n                return InnerBinding.WillReadBody;\n            }\n        }\n\n        public IEnumerable<ValueProviderFactory> ValueProviderFactories\n        {\n            get\n            {\n                IValueProviderParameterBinding valueProviderParameterBinding = InnerBinding as IValueProviderParameterBinding;\n                return valueProviderParameterBinding != null ? valueProviderParameterBinding.ValueProviderFactories : Enumerable.Empty<ValueProviderFactory>();\n            }\n        }\n\n        public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)\n        {\n            return TraceWriter.TraceBeginEndAsync(\n                actionContext.Request,\n                TraceCategories.ModelBindingCategory,\n                TraceLevel.Info,\n                InnerBinding.GetType().Name,\n                ExecuteBindingAsyncMethodName,\n                beginTrace: (tr) =>\n                {\n                    tr.Message = Error.Format(SRResources.TraceBeginParameterBind,\n                                              InnerBinding.Descriptor.ParameterName);\n                },\n\n                execute: () => InnerBinding.ExecuteBindingAsync(metadataProvider, actionContext, cancellationToken),\n\n                endTrace: (tr) =>\n                {\n                    string parameterName = InnerBinding.Descriptor.ParameterName;\n\n                    // Model binding error for this parameter shows the error\n                    if (!actionContext.ModelState.IsValid && actionContext.ModelState.ContainsKey(parameterName))\n                    {\n                        tr.Message = Error.Format(SRResources.TraceModelStateInvalidMessage,\n                                                  FormattingUtilities.ModelStateToString(\n                                                       actionContext.ModelState));\n                    }\n                    else\n                    {\n                        tr.Message = actionContext.ActionArguments.ContainsKey(parameterName)\n                                         ? Error.Format(SRResources.TraceEndParameterBind, parameterName,\n                                                        FormattingUtilities.ValueToString(\n                                                             actionContext.ActionArguments[parameterName],\n                                                             CultureInfo.CurrentCulture))\n                                         : Error.Format(SRResources.TraceEndParameterBindNoBind,\n                                                        parameterName);\n                    }\n                },\n                errorTrace: null);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/JsonMediaTypeFormatterTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Runtime.Serialization.Json;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Services;\nusing Newtonsoft.Json;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    /// <summary>\n    /// Tracer for <see cref=\"JsonMediaTypeFormatter\"/>.  \n    /// It is required because users can select formatters by this type.\n    /// </summary>\n    internal class JsonMediaTypeFormatterTracer : JsonMediaTypeFormatter, IFormatterTracer, IDecorator<JsonMediaTypeFormatter>\n    {\n        private readonly JsonMediaTypeFormatter _inner;\n        private MediaTypeFormatterTracer _innerTracer;\n\n        public JsonMediaTypeFormatterTracer(JsonMediaTypeFormatter innerFormatter, ITraceWriter traceWriter, HttpRequestMessage request)\n            : base(innerFormatter)\n        {\n            _inner = innerFormatter;\n            _innerTracer = new MediaTypeFormatterTracer(innerFormatter, traceWriter, request);\n        }\n\n        HttpRequestMessage IFormatterTracer.Request\n        {\n            get { return _innerTracer.Request; }\n        }\n\n        public JsonMediaTypeFormatter Inner\n        {\n            get { return _inner; }\n        }\n\n        public MediaTypeFormatter InnerFormatter\n        {\n            get { return _innerTracer.InnerFormatter; }\n        }\n\n        public override IRequiredMemberSelector RequiredMemberSelector\n        {\n            get\n            {\n                return _innerTracer.RequiredMemberSelector;\n            }\n            set\n            {\n                _innerTracer.RequiredMemberSelector = value;\n            }\n        }\n\n        public override bool CanReadType(Type type)\n        {\n            return _innerTracer.CanReadType(type);\n        }\n\n        public override bool CanWriteType(Type type)\n        {\n            return _innerTracer.CanWriteType(type);\n        }\n\n        public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)\n        {\n            return _innerTracer.GetPerRequestFormatterInstance(type, request, mediaType);\n        }\n\n        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content,\n            IFormatterLogger formatterLogger)\n        {\n            return _innerTracer.ReadFromStreamAsync(type, readStream, content, formatterLogger);\n        }\n\n        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content,\n            IFormatterLogger formatterLogger, CancellationToken cancellationToken)\n        {\n            return _innerTracer.ReadFromStreamAsync(type, readStream, content, formatterLogger, cancellationToken);\n        }\n\n        // Callback from ReadFromStreamAsync is not expected to be called; _innerTracer.ReadFromStreamAsync uses\n        // _inner.ReadFromStreamAsync\n        public override object ReadFromStream(Type type, Stream readStream, Encoding effectiveEncoding, IFormatterLogger formatterLogger)\n        {\n            return _inner.ReadFromStream(type, readStream, effectiveEncoding, formatterLogger);\n        }\n\n        // Callback from ReadFromStreamAsync is not expected to be called; _innerTracer.ReadFromStreamAsync uses\n        // _inner.ReadFromStreamAsync\n        public override JsonReader CreateJsonReader(Type type, Stream readStream, Encoding effectiveEncoding)\n        {\n            return _inner.CreateJsonReader(type, readStream, effectiveEncoding);\n        }\n\n        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content,\n            TransportContext transportContext)\n        {\n            return _innerTracer.WriteToStreamAsync(type, value, writeStream, content, transportContext);\n        }\n\n        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content,\n            TransportContext transportContext, CancellationToken cancellationToken)\n        {\n            return _innerTracer.WriteToStreamAsync(type, value, writeStream, content, transportContext, cancellationToken);\n        }\n\n        // Callback from WriteToStreamAsync is not expected to be called; _innerTracer.WriteToStreamAsync uses\n        // _inner.WriteToStreamAsync\n        public override void WriteToStream(Type type, object value, Stream writeStream, Encoding effectiveEncoding)\n        {\n            _inner.WriteToStream(type, value, writeStream, effectiveEncoding);\n        }\n\n        // Callback from WriteToStreamAsync is not expected to be called; _innerTracer.WriteToStreamAsync uses\n        // _inner.WriteToStreamAsync\n        public override JsonWriter CreateJsonWriter(Type type, Stream writeStream, Encoding effectiveEncoding)\n        {\n            return _inner.CreateJsonWriter(type, writeStream, effectiveEncoding);\n        }\n\n        public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)\n        {\n            _innerTracer.SetDefaultContentHeaders(type, headers, mediaType);\n        }\n\n        // Callback is not expected to be called; _innerTracer methods won't use our base methods\n        public override JsonSerializer CreateJsonSerializer()\n        {\n            return _inner.CreateJsonSerializer();\n        }\n\n        // Callback is not expected to be called; _innerTracer methods won't use our base methods\n        public override DataContractJsonSerializer CreateDataContractSerializer(Type type)\n        {\n            return _inner.CreateDataContractSerializer(type);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/MediaTypeFormatterTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.IO;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Services;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    /// <summary>\n    /// Tracer to monitor <see cref=\"MediaTypeFormatter\"/> instances.\n    /// </summary>\n    internal class MediaTypeFormatterTracer : MediaTypeFormatter, IFormatterTracer, IDecorator<MediaTypeFormatter>\n    {\n        private const string ReadFromStreamAsyncMethodName = \"ReadFromStreamAsync\";\n        private const string WriteToStreamAsyncMethodName = \"WriteToStreamAsync\";\n        private const string GetPerRequestFormatterInstanceMethodName = \"GetPerRequestFormatterInstance\";\n\n        private readonly MediaTypeFormatter _inner;\n\n        public MediaTypeFormatterTracer(MediaTypeFormatter innerFormatter, ITraceWriter traceWriter, HttpRequestMessage request)\n            : base(innerFormatter)\n        {\n            Contract.Assert(innerFormatter != null);\n            Contract.Assert(traceWriter != null);\n\n            InnerFormatter = innerFormatter;\n            TraceWriter = traceWriter;\n            Request = request;\n            _inner = innerFormatter;\n        }\n\n        public MediaTypeFormatter Inner\n        {\n            get { return _inner; }\n        }\n\n        public MediaTypeFormatter InnerFormatter { get; private set; }\n\n        public ITraceWriter TraceWriter { get; set; }\n\n        public HttpRequestMessage Request { get; set; }\n\n        public override IRequiredMemberSelector RequiredMemberSelector\n        {\n            get\n            {\n                return InnerFormatter.RequiredMemberSelector;\n            }\n            set\n            {\n                InnerFormatter.RequiredMemberSelector = value;\n            }\n        }\n\n        public static MediaTypeFormatter ActualMediaTypeFormatter(MediaTypeFormatter formatter)\n        {\n            IFormatterTracer tracer = formatter as IFormatterTracer;\n            return tracer == null ? formatter : tracer.InnerFormatter;\n        }\n\n        public static MediaTypeFormatter CreateTracer(MediaTypeFormatter formatter, ITraceWriter traceWriter, HttpRequestMessage request)\n        {\n            // If we have been asked to wrap a tracer around a formatter, it could be\n            // already wrapped, and there is nothing to do.  But if we see it is a tracer\n            // that is not associated with a request, we wrap it into a new tracer that\n            // does have a request.  The only formatter tracers without requests are the\n            // ones in the default MediaTypeFormatterCollection in the HttpConfiguration.\n            IFormatterTracer formatterTracer = formatter as IFormatterTracer;\n            if (formatterTracer != null)\n            {\n                if (formatterTracer.Request == request)\n                {\n                    return formatter;\n                }\n\n                formatter = formatterTracer.InnerFormatter;\n            }\n\n            MediaTypeFormatter tracer = null;\n\n            XmlMediaTypeFormatter xmlFormatter = formatter as XmlMediaTypeFormatter;\n            JsonMediaTypeFormatter jsonFormatter = formatter as JsonMediaTypeFormatter;\n            FormUrlEncodedMediaTypeFormatter formUrlFormatter = formatter as FormUrlEncodedMediaTypeFormatter;\n            BufferedMediaTypeFormatter bufferedFormatter = formatter as BufferedMediaTypeFormatter;\n\n            // We special-case Xml, Json and FormUrlEncoded formatters because we expect to be able\n            // to find them with IsAssignableFrom in the MediaTypeFormatterCollection.\n            if (xmlFormatter != null)\n            {\n                tracer = new XmlMediaTypeFormatterTracer(xmlFormatter, traceWriter, request);\n            }\n            else if (jsonFormatter != null)\n            {\n                tracer = new JsonMediaTypeFormatterTracer(jsonFormatter, traceWriter, request);\n            }\n            else if (formUrlFormatter != null)\n            {\n                tracer = new FormUrlEncodedMediaTypeFormatterTracer(formUrlFormatter, traceWriter, request);\n            }\n            else if (bufferedFormatter != null)\n            {\n                tracer = new BufferedMediaTypeFormatterTracer(bufferedFormatter, traceWriter, request);\n            }\n            else\n            {\n                tracer = new MediaTypeFormatterTracer(formatter, traceWriter, request);\n            }\n\n            return tracer;\n        }\n\n        public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)\n        {\n            MediaTypeFormatter formatter = null;\n\n            TraceWriter.TraceBeginEnd(\n                request,\n                TraceCategories.FormattingCategory,\n                TraceLevel.Info,\n                InnerFormatter.GetType().Name,\n                GetPerRequestFormatterInstanceMethodName,\n                beginTrace: (tr) =>\n                {\n                    tr.Message = Error.Format(\n                        SRResources.TraceGetPerRequestFormatterMessage,\n                        InnerFormatter.GetType().Name,\n                        type.Name,\n                        mediaType);\n                },\n                execute: () => { formatter = InnerFormatter.GetPerRequestFormatterInstance(type, request, mediaType); },\n                endTrace: (tr) =>\n                {\n                    if (formatter == null)\n                    {\n                        tr.Message = SRResources.TraceGetPerRequestNullFormatterEndMessage;\n                    }\n                    else\n                    {\n                        string formatMessage =\n                            Object.ReferenceEquals(MediaTypeFormatterTracer.ActualMediaTypeFormatter(formatter),\n                                                   InnerFormatter)\n                                ? SRResources.TraceGetPerRequestFormatterEndMessage\n                                : SRResources.TraceGetPerRequestFormatterEndMessageNew;\n\n                        tr.Message = Error.Format(formatMessage, formatter.GetType().Name);\n                    }\n                },\n                errorTrace: null);\n\n            if (formatter != null && !(formatter is IFormatterTracer))\n            {\n                formatter = MediaTypeFormatterTracer.CreateTracer(formatter, TraceWriter, request);\n            }\n\n            return formatter;\n        }\n\n        public override bool CanReadType(Type type)\n        {\n            return InnerFormatter.CanReadType(type);\n        }\n\n        public override bool CanWriteType(Type type)\n        {\n            return InnerFormatter.CanWriteType(type);\n        }\n\n        public override bool Equals(object obj)\n        {\n            return InnerFormatter.Equals(obj);\n        }\n\n        public override int GetHashCode()\n        {\n            return InnerFormatter.GetHashCode();\n        }\n\n        public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)\n        {\n            InnerFormatter.SetDefaultContentHeaders(type, headers, mediaType);\n        }\n\n        public override string ToString()\n        {\n            return InnerFormatter.ToString();\n        }\n\n        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content,\n            IFormatterLogger formatterLogger)\n        {\n            return ReadFromStreamAsyncCore(type, readStream, content, formatterLogger, cancellationToken: null);\n        }\n\n        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content,\n            IFormatterLogger formatterLogger, CancellationToken cancellationToken)\n        {\n            return ReadFromStreamAsyncCore(type, readStream, content, formatterLogger, cancellationToken);\n        }\n\n        private Task<object> ReadFromStreamAsyncCore(Type type, Stream readStream, HttpContent content,\n            IFormatterLogger formatterLogger, CancellationToken? cancellationToken)\n        {\n            HttpContentHeaders contentHeaders = content == null ? null : content.Headers;\n            MediaTypeHeaderValue contentType = contentHeaders == null ? null : contentHeaders.ContentType;\n\n            IFormatterLogger formatterLoggerTraceWrapper =\n                (formatterLogger == null) ? null : new FormatterLoggerTraceWrapper(formatterLogger,\n                                                                                   TraceWriter,\n                                                                                   Request,\n                                                                                   InnerFormatter.GetType().Name,\n                                                                                   ReadFromStreamAsyncMethodName);\n\n            return TraceWriter.TraceBeginEndAsync<object>(\n                Request,\n                TraceCategories.FormattingCategory,\n                TraceLevel.Info,\n                InnerFormatter.GetType().Name,\n                ReadFromStreamAsyncMethodName,\n                beginTrace: (tr) =>\n                {\n                    tr.Message = Error.Format(\n                                        SRResources.TraceReadFromStreamMessage,\n                                        type.Name,\n                                        contentType == null ? SRResources.TraceNoneObjectMessage : contentType.ToString());\n                },\n\n                execute: () =>\n                {\n                    if (cancellationToken.HasValue)\n                    {\n                        return InnerFormatter.ReadFromStreamAsync(type, readStream, content, formatterLoggerTraceWrapper, cancellationToken.Value);\n                    }\n                    else\n                    {\n                        return InnerFormatter.ReadFromStreamAsync(type, readStream, content, formatterLoggerTraceWrapper);\n                    }\n                },\n                endTrace: (tr, value) =>\n                {\n                    tr.Message = Error.Format(\n                                        SRResources.TraceReadFromStreamValueMessage,\n                                        FormattingUtilities.ValueToString(value, CultureInfo.CurrentCulture));\n                },\n\n                errorTrace: null);\n        }\n\n        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content,\n            TransportContext transportContext)\n        {\n            return WriteToStreamAsyncCore(type, value, writeStream, content, transportContext);\n        }\n\n        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content,\n            TransportContext transportContext, CancellationToken cancellationToken)\n        {\n            return WriteToStreamAsyncCore(type, value, writeStream, content, transportContext, cancellationToken);\n        }\n\n        private Task WriteToStreamAsyncCore(Type type, object value, Stream writeStream, HttpContent content,\n            TransportContext transportContext, CancellationToken? cancellationToken = null)\n        {\n            HttpContentHeaders contentHeaders = content == null ? null : content.Headers;\n            MediaTypeHeaderValue contentType = contentHeaders == null\n                                       ? null\n                                       : contentHeaders.ContentType;\n\n            return TraceWriter.TraceBeginEndAsync(\n                Request,\n                TraceCategories.FormattingCategory,\n                TraceLevel.Info,\n                InnerFormatter.GetType().Name,\n                WriteToStreamAsyncMethodName,\n                beginTrace: (tr) =>\n                {\n                    tr.Message = Error.Format(\n                                        SRResources.TraceWriteToStreamMessage,\n                                        FormattingUtilities.ValueToString(value, CultureInfo.CurrentCulture),\n                                        type.Name,\n                                        contentType == null ? SRResources.TraceNoneObjectMessage : contentType.ToString());\n                },\n                execute: () =>\n                {\n                    if (cancellationToken.HasValue)\n                    {\n                        return InnerFormatter.WriteToStreamAsync(type, value, writeStream, content, transportContext, cancellationToken.Value);\n                    }\n                    else\n                    {\n                        return InnerFormatter.WriteToStreamAsync(type, value, writeStream, content, transportContext);\n                    }\n                },\n                endTrace: null,\n                errorTrace: null);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/MessageHandlerTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Services;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    /// <summary>\n    /// Tracer to wrap a <see cref=\"DelegatingHandler\"/>.\n    /// </summary>\n    internal class MessageHandlerTracer : DelegatingHandler, IDecorator<DelegatingHandler>\n    {\n        private const string SendAsyncMethodName = \"SendAsync\";\n\n        private readonly DelegatingHandler _innerHandler;\n        private readonly ITraceWriter _traceWriter;\n\n        public MessageHandlerTracer(DelegatingHandler innerHandler, ITraceWriter traceWriter)\n        {\n            Contract.Assert(innerHandler != null);\n            Contract.Assert(traceWriter != null);\n\n            _innerHandler = innerHandler;\n            _traceWriter = traceWriter;\n        }\n\n        public DelegatingHandler Inner\n        {\n            get { return _innerHandler; }\n        }\n\n        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n        {\n            return _traceWriter.TraceBeginEndAsync<HttpResponseMessage>(\n                request,\n                TraceCategories.MessageHandlersCategory,\n                TraceLevel.Info,\n                _innerHandler.GetType().Name,\n                SendAsyncMethodName,\n                beginTrace: null,\n                execute: () => base.SendAsync(request, cancellationToken),\n                endTrace: (tr, response) =>\n                {\n                    if (response != null)\n                    {\n                        tr.Status = response.StatusCode;\n                    }\n                },\n                errorTrace: null);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/OverrideFilterTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Filters;\nusing System.Web.Http.Services;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    internal class OverrideFilterTracer : FilterTracer, IOverrideFilter, IDecorator<IOverrideFilter>\n    {\n        private readonly IOverrideFilter _innerFilter;\n\n        public OverrideFilterTracer(IOverrideFilter innerFilter, ITraceWriter traceWriter)\n            : base(innerFilter, traceWriter)\n        {\n            _innerFilter = innerFilter;\n        }\n\n        public new IOverrideFilter Inner\n        {\n            get { return _innerFilter; }\n        }\n\n        public Type FiltersToOverride\n        {\n            get { return _innerFilter.FiltersToOverride; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/RequestMessageHandlerTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Net.Http;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    /// <summary>\n    /// Internal <see cref=\"DelegatingHandler\"/> that executes before and after all of the installed message handlers.\n    /// The begin trace of this handler is the first trace for the request.\n    /// </summary>\n    internal class RequestMessageHandlerTracer : DelegatingHandler\n    {\n        private readonly ITraceWriter _traceWriter;\n\n        public RequestMessageHandlerTracer(ITraceWriter traceWriter)\n        {\n            Contract.Assert(traceWriter != null);\n\n            _traceWriter = traceWriter;\n        }\n\n        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n        {\n            return _traceWriter.TraceBeginEndAsync<HttpResponseMessage>(\n                request,\n                TraceCategories.RequestCategory,\n                TraceLevel.Info,\n                String.Empty,\n                String.Empty,\n                beginTrace: (tr) =>\n                {\n                    tr.Message = request.RequestUri == null ? SRResources.TraceNoneObjectMessage : request.RequestUri.ToString();\n                },\n\n                execute: () => base.SendAsync(request, cancellationToken),\n\n                endTrace: (tr, response) =>\n                {\n                    MediaTypeHeaderValue contentType = response == null\n                                                            ? null\n                                                            : response.Content == null\n                                                                    ? null\n                                                                    : response.Content.Headers.ContentType;\n\n                    long? contentLength = response == null\n                                                ? null\n                                                : response.Content == null\n                                                    ? null\n                                                    : response.Content.Headers.ContentLength;\n\n                    if (response != null)\n                    {\n                        tr.Status = response.StatusCode;\n                    }\n\n                    tr.Message =\n                        Error.Format(SRResources.TraceRequestCompleteMessage,\n                                     contentType == null\n                                        ? SRResources.TraceNoneObjectMessage\n                                        : contentType.ToString(),\n                                     contentLength.HasValue\n                                        ? contentLength.Value.ToString(CultureInfo.CurrentCulture)\n                                        : SRResources.TraceUnknownMessage);\n                },\n                errorTrace: null);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Tracing/Tracers/XmlMediaTypeFormatterTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Runtime.Serialization;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Services;\nusing System.Xml;\nusing System.Xml.Serialization;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    /// <summary>\n    /// Tracer for <see cref=\"XmlMediaTypeFormatter\"/>.  \n    /// It is required because users can select formatters by this type.\n    /// </summary>\n    internal class XmlMediaTypeFormatterTracer : XmlMediaTypeFormatter, IFormatterTracer, IDecorator<XmlMediaTypeFormatter>\n    {\n        private readonly XmlMediaTypeFormatter _inner;\n        private readonly MediaTypeFormatterTracer _innerTracer;\n\n        public XmlMediaTypeFormatterTracer(XmlMediaTypeFormatter innerFormatter, ITraceWriter traceWriter, HttpRequestMessage request)\n            : base(innerFormatter)\n        {\n            _inner = innerFormatter;\n            _innerTracer = new MediaTypeFormatterTracer(innerFormatter, traceWriter, request);\n        }\n\n        HttpRequestMessage IFormatterTracer.Request\n        {\n            get { return _innerTracer.Request; }\n        }\n\n        public XmlMediaTypeFormatter Inner\n        {\n            get { return _inner; }\n        }\n\n        public MediaTypeFormatter InnerFormatter\n        {\n            get { return _innerTracer.InnerFormatter; }\n        }\n\n        public override IRequiredMemberSelector RequiredMemberSelector\n        {\n            get\n            {\n                return _innerTracer.RequiredMemberSelector;\n            }\n            set\n            {\n                _innerTracer.RequiredMemberSelector = value;\n            }\n        }\n\n        public override bool CanReadType(Type type)\n        {\n            return _innerTracer.CanReadType(type);\n        }\n\n        public override bool CanWriteType(Type type)\n        {\n            return _innerTracer.CanWriteType(type);\n        }\n\n        public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)\n        {\n            return _innerTracer.GetPerRequestFormatterInstance(type, request, mediaType);\n        }\n\n        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content,\n            IFormatterLogger formatterLogger, CancellationToken cancellationToken)\n        {\n            return _innerTracer.ReadFromStreamAsync(type, readStream, content, formatterLogger, cancellationToken);\n        }\n\n        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)\n        {\n            return _innerTracer.ReadFromStreamAsync(type, readStream, content, formatterLogger);\n        }\n\n        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content,\n            TransportContext transportContext, CancellationToken cancellationToken)\n        {\n            return _innerTracer.WriteToStreamAsync(type, value, writeStream, content, transportContext, cancellationToken);\n        }\n\n        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)\n        {\n            return _innerTracer.WriteToStreamAsync(type, value, writeStream, content, transportContext);\n        }\n\n        public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)\n        {\n            _innerTracer.SetDefaultContentHeaders(type, headers, mediaType);\n        }\n\n        public override XmlSerializer CreateXmlSerializer(Type type)\n        {\n            return _inner.CreateXmlSerializer(type);\n        }\n\n        public override DataContractSerializer CreateDataContractSerializer(Type type)\n        {\n            return _inner.CreateDataContractSerializer(type);\n        }\n\n        protected override XmlReader CreateXmlReader(Stream readStream, HttpContent content)\n        {\n            return _inner.InvokeCreateXmlReader(readStream, content);\n        }\n\n        protected override XmlWriter CreateXmlWriter(Stream writeStream, HttpContent content)\n        {\n            return _inner.InvokeCreateXmlWriter(writeStream, content);\n        }\n\n        protected override object GetDeserializer(Type type, HttpContent content)\n        {\n            return _inner.InvokeGetDeserializer(type, content);\n        }\n\n        protected override object GetSerializer(Type type, object value, HttpContent content)\n        {\n            return _inner.InvokeGetSerializer(type, value, content);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Validation/BodyModelValidatorContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.ModelBinding;\n\nnamespace System.Web.Http.Validation\n{\n    /// <summary>\n    /// Context passed between <see cref=\"DefaultBodyModelValidator\"/> methods.\n    /// </summary>\n    public class BodyModelValidatorContext\n    {\n        public BodyModelValidatorContext(ModelStateDictionary modelState)\n        {\n            if (modelState == null)\n            {\n                throw new ArgumentNullException(\"modelState\");\n            }\n\n            KeyBuilders = new Stack<IBodyModelValidatorKeyBuilder>();\n            ModelState = modelState;\n            Visited = new HashSet<object>(ReferenceEqualityComparer.Instance);\n        }\n\n        /// <summary>\n        /// Gets or sets the <see cref=\"ModelMetadataProvider\"/> used to provide the model metadata.\n        /// </summary>\n        public ModelMetadataProvider MetadataProvider { get; set; }\n\n        /// <summary>\n        /// Gets or sets the <see cref=\"HttpActionContext\"/> within which the model is being validated.\n        /// </summary>\n        public HttpActionContext ActionContext { get; set; }\n\n        /// <summary>\n        /// Gets or sets the <see cref=\"IModelValidatorCache\"/>.\n        /// </summary>\n        public IModelValidatorCache ValidatorCache { get; set; }\n\n        /// <summary>\n        /// Gets the current <see cref=\"ModelStateDictionary\"/>.\n        /// </summary>\n        public ModelStateDictionary ModelState { get; private set; }\n\n        /// <summary>\n        /// Gets the set of model objects visited in this validation. Includes the model being validated in the\n        /// current scope.\n        /// </summary>\n        public HashSet<object> Visited { get; private set; }\n\n        /// <summary>\n        /// Gets the stack of <see cref=\"IBodyModelValidatorKeyBuilder\"/>s used in this validation. Includes\n        /// the <see cref=\"IBodyModelValidatorKeyBuilder\"/> to generate model state keys for the current scope.\n        /// </summary>\n        public Stack<IBodyModelValidatorKeyBuilder> KeyBuilders { get; private set; }\n\n        /// <summary>\n        /// Gets or sets the model state prefix for the root scope of this validation.\n        /// </summary>\n        public string RootPrefix { get; set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Validation/DefaultBodyModelValidator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing System.Net.Http.Formatting;\nusing System.Runtime.CompilerServices;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Internal;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.ModelBinding;\n\nnamespace System.Web.Http.Validation\n{\n    /// <summary>\n    /// Recursively validate an object.\n    /// </summary>\n    public class DefaultBodyModelValidator : IBodyModelValidator\n    {\n        /// <summary>\n        /// Determines whether the <paramref name=\"model\"/> is valid and adds any validation errors to the <paramref name=\"actionContext\"/>'s <see cref=\"ModelStateDictionary\"/>\n        /// </summary>\n        /// <param name=\"model\">The model to be validated.</param>\n        /// <param name=\"type\">The <see cref=\"Type\"/> to use for validation.</param>\n        /// <param name=\"metadataProvider\">The <see cref=\"ModelMetadataProvider\"/> used to provide the model metadata.</param>\n        /// <param name=\"actionContext\">The <see cref=\"HttpActionContext\"/> within which the model is being validated.</param>\n        /// <param name=\"keyPrefix\">The <see cref=\"string\"/> to append to the key for any validation errors.</param>\n        /// <returns><c>true</c>if <paramref name=\"model\"/> is valid, <c>false</c> otherwise.</returns>\n        public bool Validate(object model, Type type, ModelMetadataProvider metadataProvider, HttpActionContext actionContext, string keyPrefix)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            if (metadataProvider == null)\n            {\n                throw Error.ArgumentNull(\"metadataProvider\");\n            }\n\n            if (actionContext == null)\n            {\n                throw Error.ArgumentNull(\"actionContext\");\n            }\n\n            if (model != null && !ShouldValidateType(model.GetType()))\n            {\n                return true;\n            }\n\n            ModelValidatorProvider[] validatorProviders = actionContext.GetValidatorProviders().ToArray();\n            // Optimization : avoid validating the object graph if there are no validator providers\n            if (validatorProviders == null || validatorProviders.Length == 0)\n            {\n                return true;\n            }\n\n            ModelMetadata metadata = metadataProvider.GetMetadataForType(() => model, type);\n            BodyModelValidatorContext validationContext = new BodyModelValidatorContext(actionContext.ModelState)\n            {\n                MetadataProvider = metadataProvider,\n                ActionContext = actionContext,\n                ValidatorCache = actionContext.GetValidatorCache(),\n                RootPrefix = keyPrefix\n            };\n            return ValidateNodeAndChildren(metadata, validationContext, container: null, validators: null);\n        }\n\n        /// <summary>\n        /// Determines whether instances of a particular type should be validated\n        /// </summary>\n        /// <param name=\"type\">The type to validate.</param>\n        /// <returns><c>true</c> if the type should be validated; <c>false</c> otherwise</returns>\n        public virtual bool ShouldValidateType(Type type)\n        {\n            return !MediaTypeFormatterCollection.IsTypeExcludedFromValidation(type);\n        }\n\n        /// <summary>\n        /// Recursively validate the given <paramref name=\"metadata\"/> and <paramref name=\"container\"/>.\n        /// </summary>\n        /// <param name=\"metadata\">The <see cref=\"ModelMetadata\"/> for the object to validate.</param>\n        /// <param name=\"validationContext\">The <see cref=\"BodyModelValidatorContext\"/>.</param>\n        /// <param name=\"container\">The object containing the object to validate.</param>\n        /// <param name=\"validators\">The collection of <see cref=\"ModelValidator\"/>s.</param>\n        /// <returns>\n        /// <see langword=\"true\"/> if validation succeeds for the given <paramref name=\"metadata\"/>,\n        /// <paramref name=\"container\"/>, and child nodes; <see langword=\"false\"/> otherwise.\n        /// </returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"See comment below\")]\n        protected virtual bool ValidateNodeAndChildren(\n            ModelMetadata metadata,\n            BodyModelValidatorContext validationContext,\n            object container,\n            IEnumerable<ModelValidator> validators)\n        {\n            // Recursion guard to avoid stack overflows\n            RuntimeHelpers.EnsureSufficientExecutionStack();\n\n            if (metadata == null)\n            {\n                throw Error.ArgumentNull(\"metadata\");\n            }\n            if (validationContext == null)\n            {\n                throw Error.ArgumentNull(\"validationContext\");\n            }\n\n            object model = null;\n            try\n            {\n                model = metadata.Model;\n            }\n            catch\n            {\n                // Retrieving the model failed - typically caused by a property getter throwing\n                // Being unable to retrieve a property is not a validation error - many properties can only be retrieved if certain conditions are met\n                // For example, Uri.AbsoluteUri throws for relative URIs but it shouldn't be considered a validation error\n                return true;\n            }\n\n            bool isValid = true;\n\n            if (validators == null)\n            {\n                validators = validationContext.ActionContext.GetValidators(metadata, validationContext.ValidatorCache);\n            }\n\n            // We don't need to recursively traverse the graph for null values\n            if (model == null)\n            {\n                return ShallowValidate(metadata, validationContext, container, validators);\n            }\n\n            // We don't need to recursively traverse the graph for types that shouldn't be validated\n            Type modelType = model.GetType();\n            if (TypeHelper.IsSimpleType(modelType) || !ShouldValidateType(modelType))\n            {\n                return ShallowValidate(metadata, validationContext, container, validators);\n            }\n\n            // Check to avoid infinite recursion. This can happen with cycles in an object graph.\n            if (validationContext.Visited.Contains(model))\n            {\n                return true;\n            }\n            validationContext.Visited.Add(model);\n\n            // Validate the children first - depth-first traversal\n            IEnumerable enumerableModel = model as IEnumerable;\n            if (enumerableModel == null)\n            {\n                isValid = ValidateProperties(metadata, validationContext);\n            }\n            else\n            {\n                isValid = ValidateElements(enumerableModel, validationContext);\n            }\n            if (isValid)\n            {\n                // Don't bother to validate this node if children failed.\n                isValid = ShallowValidate(metadata, validationContext, container, validators);\n            }\n\n            // Pop the object so that it can be validated again in a different path\n            validationContext.Visited.Remove(model);\n\n            return isValid;\n        }\n\n        /// <summary>\n        /// Recursively validate the properties of the given <paramref name=\"metadata\"/>.\n        /// </summary>\n        /// <param name=\"metadata\">The <see cref=\"ModelMetadata\"/> for the object to validate.</param>\n        /// <param name=\"validationContext\">The <see cref=\"BodyModelValidatorContext\"/>.</param>\n        /// <returns>\n        /// <see langword=\"true\"/> if validation succeeds for all properties in <paramref name=\"metadata\"/>;\n        /// <see langword=\"false\"/> otherwise.\n        /// </returns>\n        protected virtual bool ValidateProperties(ModelMetadata metadata, BodyModelValidatorContext validationContext)\n        {\n            if (metadata == null)\n            {\n                throw Error.ArgumentNull(\"metadata\");\n            }\n            if (validationContext == null)\n            {\n                throw Error.ArgumentNull(\"validationContext\");\n            }\n\n            bool isValid = true;\n            PropertyScope propertyScope = new PropertyScope();\n            validationContext.KeyBuilders.Push(propertyScope);\n            foreach (ModelMetadata childMetadata in validationContext.MetadataProvider.GetMetadataForProperties(metadata.Model, metadata.RealModelType))\n            {\n                propertyScope.PropertyName = childMetadata.PropertyName;\n                if (!ValidateNodeAndChildren(childMetadata, validationContext, metadata.Model, validators: null))\n                {\n                    isValid = false;\n                }\n            }\n            validationContext.KeyBuilders.Pop();\n            return isValid;\n        }\n\n        /// <summary>\n        /// Recursively validate the elements of the <paramref name=\"model\"/> collection.\n        /// </summary>\n        /// <param name=\"model\">The <see cref=\"IEnumerable\"/> instance containing the elements to validate.</param>\n        /// <param name=\"validationContext\">The <see cref=\"BodyModelValidatorContext\"/>.</param>\n        /// <returns>\n        /// <see langword=\"true\"/> if validation succeeds for all elements of <paramref name=\"model\"/>;\n        /// <see langword=\"false\"/> otherwise.\n        /// </returns>\n        protected virtual bool ValidateElements(IEnumerable model, BodyModelValidatorContext validationContext)\n        {\n            if (model == null)\n            {\n                throw Error.ArgumentNull(\"model\");\n            }\n            if (validationContext == null)\n            {\n                throw Error.ArgumentNull(\"validationContext\");\n            }\n\n            bool isValid = true;\n            Type elementType = GetElementType(model.GetType());\n            ModelMetadata elementMetadata = validationContext.MetadataProvider.GetMetadataForType(null, elementType);\n\n            ElementScope elementScope = new ElementScope() { Index = 0 };\n            validationContext.KeyBuilders.Push(elementScope);\n            IEnumerable<ModelValidator> validators = validationContext.ActionContext.GetValidators(elementMetadata, validationContext.ValidatorCache);\n\n            // if there are no validators or the object is null we bail out quickly\n            // when there are large arrays of null, this will save a significant amount of processing\n            // with minimal impact to other scenarios.\n            bool anyValidatorsDefined = validators.Any();\n\n            foreach (object element in model)\n            {\n                // If the element is non null, the recursive calls might find more validators.\n                // If it's null, then a shallow validation will be performed.\n                if (element != null || anyValidatorsDefined)\n                {\n                    elementMetadata.Model = element;\n\n                    if (!ValidateNodeAndChildren(elementMetadata, validationContext, model, validators))\n                    {\n                        isValid = false;\n                    }\n                }\n\n                elementScope.Index++;\n            }\n            validationContext.KeyBuilders.Pop();\n            return isValid;\n        }\n\n        /// <summary>\n        /// Validate a single node, not including its children.\n        /// </summary>\n        /// <param name=\"metadata\">The <see cref=\"ModelMetadata\"/>.</param>\n        /// <param name=\"validationContext\">The <see cref=\"BodyModelValidatorContext\"/>.</param>\n        /// <param name=\"container\">The object to validate.</param>\n        /// <param name=\"validators\">The collection of <see cref=\"ModelValidator\"/>s.</param>\n        /// <returns>\n        /// <see langword=\"true\"/> if validation succeeds for the given <paramref name=\"metadata\"/> and\n        /// <paramref name=\"container\"/>; <see langword=\"false\"/> otherwise.\n        /// </returns>\n        protected virtual bool ShallowValidate(\n            ModelMetadata metadata,\n            BodyModelValidatorContext validationContext,\n            object container,\n            IEnumerable<ModelValidator> validators)\n        {\n            if (metadata == null)\n            {\n                throw Error.ArgumentNull(\"metadata\");\n            }\n            if (validationContext == null)\n            {\n                throw Error.ArgumentNull(\"validationContext\");\n            }\n            if (validators == null)\n            {\n                throw Error.ArgumentNull(\"validators\");\n            }\n\n            bool isValid = true;\n            string modelKey = null;\n\n            // When the are no validators we bail quickly. This saves a GetEnumerator allocation.\n            // In a large array (tens of thousands or more) scenario it's very significant.\n            ICollection validatorsAsCollection = validators as ICollection;\n            if (validatorsAsCollection != null && validatorsAsCollection.Count == 0)\n            {\n                return isValid;\n            }\n\n            foreach (ModelValidator validator in validators)\n            {\n                foreach (ModelValidationResult error in validator.Validate(metadata, container))\n                {\n                    if (modelKey == null)\n                    {\n                        modelKey = validationContext.RootPrefix;\n                        foreach (IBodyModelValidatorKeyBuilder keyBuilder in validationContext.KeyBuilders.Reverse())\n                        {\n                            modelKey = keyBuilder.AppendTo(modelKey);\n                        }\n                    }\n                    string errorKey = ModelBindingHelper.CreatePropertyModelName(modelKey, error.MemberName);\n                    validationContext.ModelState.AddModelError(errorKey, error.Message);\n                    isValid = false;\n                }\n            }\n            return isValid;\n        }\n\n        private static Type GetElementType(Type type)\n        {\n            Contract.Assert(typeof(IEnumerable).IsAssignableFrom(type));\n            if (type.IsArray)\n            {\n                return type.GetElementType();\n            }\n\n            foreach (Type implementedInterface in type.GetInterfaces())\n            {\n                if (implementedInterface.IsGenericType && implementedInterface.GetGenericTypeDefinition() == typeof(IEnumerable<>))\n                {\n                    return implementedInterface.GetGenericArguments()[0];\n                }\n            }\n\n            return typeof(object);\n        }\n\n        private class PropertyScope : IBodyModelValidatorKeyBuilder\n        {\n            public string PropertyName { get; set; }\n\n            public string AppendTo(string prefix)\n            {\n                return ModelBindingHelper.CreatePropertyModelName(prefix, PropertyName);\n            }\n        }\n\n        private class ElementScope : IBodyModelValidatorKeyBuilder\n        {\n            public int Index { get; set; }\n\n            public string AppendTo(string prefix)\n            {\n                return ModelBindingHelper.CreateIndexModelName(prefix, Index);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Validation/IBodyModelValidator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Formatting;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.ModelBinding;\n\nnamespace System.Web.Http.Validation\n{\n    /// <summary>\n    /// Validates the body parameter of an action after the parameter has been read by the <see cref=\"MediaTypeFormatter\"/>.\n    /// </summary>\n    public interface IBodyModelValidator\n    {\n        /// <summary>\n        /// Determines whether the <paramref name=\"model\"/> is valid and adds any validation errors to the <paramref name=\"actionContext\"/>'s <see cref=\"ModelStateDictionary\"/>\n        /// </summary>\n        /// <param name=\"model\">The model to be validated.</param>\n        /// <param name=\"type\">The <see cref=\"Type\"/> to use for validation.</param>\n        /// <param name=\"metadataProvider\">The <see cref=\"ModelMetadataProvider\"/> used to provide the model metadata.</param>\n        /// <param name=\"actionContext\">The <see cref=\"HttpActionContext\"/> within which the model is being validated.</param>\n        /// <param name=\"keyPrefix\">The <see cref=\"string\"/> to append to the key for any validation errors.</param>\n        /// <returns><c>true</c>if <paramref name=\"model\"/> is valid, <c>false</c> otherwise.</returns>\n        bool Validate(object model, Type type, ModelMetadataProvider metadataProvider, HttpActionContext actionContext, string keyPrefix);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Validation/IBodyModelValidatorKeyBuilder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Validation\n{\n    /// <summary>\n    /// Abstraction for creating keys used in nested validation scopes. Intended for use in\n    /// <see cref=\"IBodyModelValidator\"/> implementations, especially <see cref=\"DefaultBodyModelValidator\"/>.\n    /// </summary>\n    public interface IBodyModelValidatorKeyBuilder\n    {\n        /// <summary>\n        /// Returns the key for a nested scope within the <paramref name=\"prefix\"/> scope.\n        /// </summary>\n        /// <param name=\"prefix\">Key for the current scope.</param>\n        /// <returns>Key for a nested scope. Usually appends a property name to <paramref name=\"prefix\"/>.</returns>\n        string AppendTo(string prefix);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Validation/IModelValidatorCache.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Metadata;\n\nnamespace System.Web.Http.Validation\n{\n    /// <summary>\n    /// Defines a cache for <see cref=\"ModelValidator\"/>s. This cache is keyed on the type or property that the\n    /// metadata is associated with.\n    /// </summary>\n    public interface IModelValidatorCache\n    {\n        /// <summary>\n        /// Returns the <see cref=\"ModelValidator\"/>s for the given <paramref name=\"metadata\"/>.\n        /// </summary>\n        /// <param name=\"metadata\">The <see cref=\"ModelMetadata\"/>.</param>\n        /// <returns>An array of <see cref=\"ModelValidator\"/>s for the given <paramref name=\"metadata\"/>.</returns>\n        ModelValidator[] GetValidators(ModelMetadata metadata);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Validation/ModelStateFormatterLogger.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Formatting;\nusing System.Web.Http.ModelBinding;\n\nnamespace System.Web.Http.Validation\n{\n    /// <summary>\n    /// This <see cref=\"IFormatterLogger\"/> logs formatter errors to the provided <see cref=\"ModelStateDictionary\"/>.\n    /// </summary>\n    public class ModelStateFormatterLogger : IFormatterLogger\n    {\n        private readonly ModelStateDictionary _modelState;\n        private readonly string _prefix;\n\n        public ModelStateFormatterLogger(ModelStateDictionary modelState, string prefix)\n        {\n            if (modelState == null)\n            {\n                throw Error.ArgumentNull(\"modelState\");\n            }\n\n            _modelState = modelState;\n            _prefix = prefix;\n        }\n\n        public void LogError(string errorPath, string errorMessage)\n        {\n            if (errorPath == null)\n            {\n                throw Error.ArgumentNull(\"errorPath\");\n            }\n            if (errorMessage == null)\n            {\n                throw Error.ArgumentNull(\"errorMessage\");\n            }\n\n            string key = ModelBindingHelper.ConcatenateKeys(_prefix, errorPath);\n            _modelState.AddModelError(key, errorMessage);\n        }\n\n        public void LogError(string errorPath, Exception exception)\n        {\n            if (errorPath == null)\n            {\n                throw Error.ArgumentNull(\"errorPath\");\n            }\n            if (exception == null)\n            {\n                throw Error.ArgumentNull(\"exception\");\n            }\n\n            string key = ModelBindingHelper.ConcatenateKeys(_prefix, errorPath);\n            _modelState.AddModelError(key, exception);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Validation/ModelValidatedEventArgs.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.Validation\n{\n    public sealed class ModelValidatedEventArgs : EventArgs\n    {\n        public ModelValidatedEventArgs(HttpActionContext actionContext, ModelValidationNode parentNode)\n        {\n            if (actionContext == null)\n            {\n                throw Error.ArgumentNull(\"actionContext\");\n            }\n\n            ActionContext = actionContext;\n            ParentNode = parentNode;\n        }\n\n        public HttpActionContext ActionContext { get; private set; }\n\n        public ModelValidationNode ParentNode { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Validation/ModelValidatingEventArgs.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.Validation\n{\n    public sealed class ModelValidatingEventArgs : CancelEventArgs\n    {\n        public ModelValidatingEventArgs(HttpActionContext actionContext, ModelValidationNode parentNode)\n        {\n            if (actionContext == null)\n            {\n                throw Error.ArgumentNull(\"actionContext\");\n            }\n\n            ActionContext = actionContext;\n            ParentNode = parentNode;\n        }\n\n        public HttpActionContext ActionContext { get; private set; }\n\n        public ModelValidationNode ParentNode { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Validation/ModelValidationNode.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.Validation\n{\n    public sealed class ModelValidationNode\n    {\n        private IEnumerable<ModelValidator> _validators;\n        private readonly List<ModelValidationNode> _childNodes;\n\n        public ModelValidationNode(ModelMetadata modelMetadata, string modelStateKey)\n            : this(modelMetadata, modelStateKey, null)\n        {\n        }\n\n        public ModelValidationNode(ModelMetadata modelMetadata, string modelStateKey, IEnumerable<ModelValidationNode> childNodes)\n        {\n            if (modelMetadata == null)\n            {\n                throw Error.ArgumentNull(\"modelMetadata\");\n            }\n            if (modelStateKey == null)\n            {\n                throw Error.ArgumentNull(\"modelStateKey\");\n            }\n\n            ModelMetadata = modelMetadata;\n            ModelStateKey = modelStateKey;\n            _childNodes = (childNodes != null) ? childNodes.ToList() : new List<ModelValidationNode>();\n        }\n\n        public event EventHandler<ModelValidatedEventArgs> Validated;\n\n        public event EventHandler<ModelValidatingEventArgs> Validating;\n\n        public ICollection<ModelValidationNode> ChildNodes \n        {\n            get { return _childNodes; }\n        }\n\n        public ModelMetadata ModelMetadata { get; private set; }\n\n        public string ModelStateKey { get; private set; }\n\n        public bool ValidateAllProperties { get; set; }\n\n        public bool SuppressValidation { get; set; }\n\n        public void CombineWith(ModelValidationNode otherNode)\n        {\n            if (otherNode != null && !otherNode.SuppressValidation)\n            {\n                Validated += otherNode.Validated;\n                Validating += otherNode.Validating;\n                List<ModelValidationNode> otherChildNodes = otherNode._childNodes;\n                for (int i = 0; i < otherChildNodes.Count; i++)\n                {\n                    ModelValidationNode childNode = otherChildNodes[i];\n                    _childNodes.Add(childNode);\n                }\n            }\n        }\n\n        private void OnValidated(ModelValidatedEventArgs e)\n        {\n            EventHandler<ModelValidatedEventArgs> handler = Validated;\n            if (handler != null)\n            {\n                handler(this, e);\n            }\n        }\n\n        private void OnValidating(ModelValidatingEventArgs e)\n        {\n            EventHandler<ModelValidatingEventArgs> handler = Validating;\n            if (handler != null)\n            {\n                handler(this, e);\n            }\n        }\n\n        private object TryConvertContainerToMetadataType(ModelValidationNode parentNode)\n        {\n            if (parentNode != null)\n            {\n                object containerInstance = parentNode.ModelMetadata.Model;\n                if (containerInstance != null)\n                {\n                    Type expectedContainerType = ModelMetadata.ContainerType;\n                    if (expectedContainerType != null)\n                    {\n                        if (expectedContainerType.IsInstanceOfType(containerInstance))\n                        {\n                            return containerInstance;\n                        }\n                    }\n                }\n            }\n\n            return null;\n        }\n\n        public void Validate(HttpActionContext actionContext)\n        {\n            Validate(actionContext, null /* parentNode */);\n        }\n\n        public void Validate(HttpActionContext actionContext, ModelValidationNode parentNode)\n        {\n            if (actionContext == null)\n            {\n                throw Error.ArgumentNull(\"actionContext\");\n            }\n\n            if (SuppressValidation)\n            {\n                // no-op\n                return;\n            }\n\n            // pre-validation steps\n            ModelValidatingEventArgs validatingEventArgs = new ModelValidatingEventArgs(actionContext, parentNode);\n            OnValidating(validatingEventArgs);\n            if (validatingEventArgs.Cancel)\n            {\n                return;\n            }\n\n            ValidateChildren(actionContext);\n            ValidateThis(actionContext, parentNode);\n\n            // post-validation steps\n            ModelValidatedEventArgs validatedEventArgs = new ModelValidatedEventArgs(actionContext, parentNode);\n            OnValidated(validatedEventArgs);\n        }\n\n        private void ValidateChildren(HttpActionContext actionContext)\n        {\n            for (int i = 0; i < _childNodes.Count; i++)\n            {\n                ModelValidationNode child = _childNodes[i];\n                child.Validate(actionContext, this);\n            }\n\n            if (ValidateAllProperties)\n            {\n                ValidateProperties(actionContext);\n            }\n        }\n\n        private void ValidateProperties(HttpActionContext actionContext)\n        {\n            // Based off CompositeModelValidator.\n            ModelStateDictionary modelState = actionContext.ModelState;\n\n            // DevDiv Bugs #227802 - Caching problem in ModelMetadata requires us to manually regenerate\n            // the ModelMetadata.\n            object model = ModelMetadata.Model;\n            ModelMetadata updatedMetadata = actionContext.GetMetadataProvider().GetMetadataForType(() => model, ModelMetadata.ModelType);\n\n            foreach (ModelMetadata propertyMetadata in updatedMetadata.Properties)\n            {\n                // Only want to add errors to ModelState if something doesn't already exist for the property node,\n                // else we could end up with duplicate or irrelevant error messages.\n                string propertyKeyRoot = ModelBindingHelper.CreatePropertyModelName(ModelStateKey, propertyMetadata.PropertyName);\n\n                if (modelState.IsValidField(propertyKeyRoot))\n                {\n                    foreach (ModelValidator propertyValidator in actionContext.GetValidators(propertyMetadata))\n                    {\n                        foreach (ModelValidationResult propertyResult in propertyValidator.Validate(propertyMetadata, model))\n                        {\n                            string thisErrorKey = ModelBindingHelper.CreatePropertyModelName(propertyKeyRoot, propertyResult.MemberName);\n                            modelState.AddModelError(thisErrorKey, propertyResult.Message);\n                        }\n                    }\n                }\n            }\n        }\n\n        private void ValidateThis(HttpActionContext actionContext, ModelValidationNode parentNode)\n        {\n            ModelStateDictionary modelState = actionContext.ModelState;\n            if (!modelState.IsValidField(ModelStateKey))\n            {\n                return; // short-circuit\n            }\n\n            // If 'this' is null and there is no parent, we cannot validate, and\n            // the DataAnnotationsModelValidator will throw.   So we intercept here\n            // to provide a catch-all value-required validation error\n            if (parentNode == null && ModelMetadata.Model == null)\n            {\n                string trueModelStateKey = ModelBindingHelper.CreatePropertyModelName(ModelStateKey, ModelMetadata.GetDisplayName());\n                modelState.AddModelError(trueModelStateKey, SRResources.Validation_ValueNotFound);\n                return;\n            }\n\n            _validators = actionContext.GetValidators(ModelMetadata);\n\n            object container = TryConvertContainerToMetadataType(parentNode);\n            // Optimize for the common case where the validators are in an array\n            ModelValidator[] validators = _validators.AsArray();\n            for (int i = 0; i < validators.Length; i++)\n            {\n                ModelValidator validator = validators[i];\n                foreach (ModelValidationResult validationResult in validator.Validate(ModelMetadata, container))\n                {\n                    string trueModelStateKey = ModelBindingHelper.CreatePropertyModelName(ModelStateKey, validationResult.MemberName);\n                    modelState.AddModelError(trueModelStateKey, validationResult.Message);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Validation/ModelValidationRequiredMemberSelector.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http.Formatting;\nusing System.Reflection;\nusing System.Web.Http.Metadata;\n\nnamespace System.Web.Http.Validation\n{\n    /// <summary>\n    /// This <see cref=\"IRequiredMemberSelector\"/> selects required members by checking for any \n    /// required ModelValidators associated with the member. This is the default implementation used by\n    /// <see cref=\"HttpConfiguration\"/>.\n    /// </summary>\n    public sealed class ModelValidationRequiredMemberSelector : IRequiredMemberSelector\n    {\n        private readonly ModelMetadataProvider _metadataProvider;\n        private readonly List<ModelValidatorProvider> _validatorProviders;\n\n        public ModelValidationRequiredMemberSelector(ModelMetadataProvider metadataProvider, IEnumerable<ModelValidatorProvider> validatorProviders)\n        {\n            if (metadataProvider == null)\n            {\n                throw Error.ArgumentNull(\"metadataProvider\");\n            }\n            if (validatorProviders == null)\n            {\n                throw Error.ArgumentNull(\"validatorProviders\");\n            }\n\n            _metadataProvider = metadataProvider;\n            _validatorProviders = validatorProviders.ToList();\n        }\n\n        public bool IsRequiredMember(MemberInfo member)\n        {\n            if (member == null)\n            {\n                throw Error.ArgumentNull(\"member\");\n            }\n\n            // Optimization : avoid computing validators if there are no validator providers\n            if (_validatorProviders == null || !_validatorProviders.Any())\n            {\n                return false;\n            }\n\n            PropertyInfo property = member as PropertyInfo;\n            // if member is not a property or there is no public getter\n            if (property == null || property.GetGetMethod() == null)\n            {\n                return false;\n            }\n\n            ModelMetadata metadata = _metadataProvider.GetMetadataForProperty(() => null, member.DeclaringType, member.Name);\n            if (metadata.ModelType.IsNullable())\n            {\n                // If the model type is nullable, the value validator will raise a model error for the null member\n                // Only non-nullable property types need to be checked by the formatter\n                return false;\n            }\n\n            IEnumerable<ModelValidator> validators = metadata.GetValidators(_validatorProviders);\n            return validators.Any(validator => validator.IsRequired);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Validation/ModelValidationResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Validation\n{\n    public class ModelValidationResult\n    {\n        private string _memberName;\n        private string _message;\n\n        public string MemberName\n        {\n            get { return _memberName ?? String.Empty; }\n            set { _memberName = value; }\n        }\n\n        public string Message\n        {\n            get { return _message ?? String.Empty; }\n            set { _message = value; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Validation/ModelValidator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.ModelBinding;\n\nnamespace System.Web.Http.Validation\n{\n    public abstract class ModelValidator\n    {\n        protected ModelValidator(IEnumerable<ModelValidatorProvider> validatorProviders)\n        {\n            if (validatorProviders == null)\n            {\n                throw Error.ArgumentNull(\"validatorProviders\");\n            }\n\n            ValidatorProviders = validatorProviders;\n        }\n\n        protected internal IEnumerable<ModelValidatorProvider> ValidatorProviders { get; private set; }\n\n        public virtual bool IsRequired\n        {\n            get { return false; }\n        }\n\n        public static ModelValidator GetModelValidator(IEnumerable<ModelValidatorProvider> validatorProviders)\n        {\n            return new CompositeModelValidator(validatorProviders);\n        }\n\n        public abstract IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container);\n\n        private class CompositeModelValidator : ModelValidator\n        {\n            public CompositeModelValidator(IEnumerable<ModelValidatorProvider> validatorProviders)\n                : base(validatorProviders)\n            {\n            }\n\n            public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container)\n            {\n                bool propertiesValid = true;\n\n                foreach (ModelMetadata propertyMetadata in metadata.Properties)\n                {\n                    foreach (ModelValidator propertyValidator in propertyMetadata.GetValidators(ValidatorProviders))\n                    {\n                        foreach (ModelValidationResult propertyResult in propertyValidator.Validate(metadata, container))\n                        {\n                            propertiesValid = false;\n                            yield return new ModelValidationResult\n                            {\n                                MemberName = ModelBindingHelper.CreatePropertyModelName(propertyMetadata.PropertyName, propertyResult.MemberName),\n                                Message = propertyResult.Message\n                            };\n                        }\n                    }\n                }\n\n                if (propertiesValid)\n                {\n                    foreach (ModelValidator typeValidator in metadata.GetValidators(ValidatorProviders))\n                    {\n                        foreach (ModelValidationResult typeResult in typeValidator.Validate(metadata, container))\n                        {\n                            yield return typeResult;\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Validation/ModelValidatorCache.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\nusing System.Web.Http.Metadata;\n\nnamespace System.Web.Http.Validation\n{\n    /// <summary>\n    /// Defines a cache for <see cref=\"ModelValidator\"/>s. This cache is keyed on the type or property that the metadata is associated with.\n    /// </summary>\n    internal class ModelValidatorCache : IModelValidatorCache\n    {\n        private ConcurrentDictionary<EfficientTypePropertyKey<Type, string>, ModelValidator[]> _validatorCache = new ConcurrentDictionary<EfficientTypePropertyKey<Type, string>, ModelValidator[]>();\n        private Lazy<IEnumerable<ModelValidatorProvider>> _validatorProviders;\n\n        public ModelValidatorCache(Lazy<IEnumerable<ModelValidatorProvider>> validatorProviders)\n        {\n            _validatorProviders = validatorProviders;\n        }\n\n        public ModelValidator[] GetValidators(ModelMetadata metadata)\n        {\n            ModelValidator[] validators;\n            if (!_validatorCache.TryGetValue(metadata.CacheKey, out validators))\n            {\n                // Compute validators\n                // There are no side-effects if the same validators are created more than once\n                validators = metadata.GetValidators(_validatorProviders.Value).ToArray();\n                _validatorCache.TryAdd(metadata.CacheKey, validators);\n            }\n            return validators;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Validation/ModelValidatorProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http.Metadata;\n\nnamespace System.Web.Http.Validation\n{\n    public abstract class ModelValidatorProvider\n    {\n        public abstract IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Validation/Providers/AssociatedValidatorProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Linq;\nusing System.Web.Http.Internal;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.Validation.Providers\n{\n    public abstract class AssociatedValidatorProvider : ModelValidatorProvider\n    {\n        protected virtual ICustomTypeDescriptor GetTypeDescriptor(Type type)\n        {\n            return TypeDescriptorHelper.Get(type);\n        }\n\n        public sealed override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders)\n        {\n            if (metadata == null)\n            {\n                throw Error.ArgumentNull(\"metadata\");\n            }\n            if (validatorProviders == null)\n            {\n                throw Error.ArgumentNull(\"validatorProviders\");\n            }\n\n            if (metadata.ContainerType != null && !String.IsNullOrEmpty(metadata.PropertyName))\n            {\n                return GetValidatorsForProperty(metadata, validatorProviders);\n            }\n\n            return GetValidatorsForType(metadata, validatorProviders);\n        }\n\n        protected abstract IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders, IEnumerable<Attribute> attributes);\n\n        private IEnumerable<ModelValidator> GetValidatorsForProperty(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders)\n        {\n            ICustomTypeDescriptor typeDescriptor = GetTypeDescriptor(metadata.ContainerType);\n            PropertyDescriptor property = typeDescriptor.GetProperties().Find(metadata.PropertyName, true);\n            if (property == null)\n            {\n                throw Error.Argument(\"metadata\", SRResources.Common_PropertyNotFound, metadata.ContainerType, metadata.PropertyName);\n            }\n\n            return GetValidators(metadata, validatorProviders, property.Attributes.OfType<Attribute>());\n        }\n\n        private IEnumerable<ModelValidator> GetValidatorsForType(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders)\n        {\n            return GetValidators(metadata, validatorProviders, GetTypeDescriptor(metadata.ModelType).GetAttributes().Cast<Attribute>());\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Validation/Providers/DataAnnotationsModelValidatorProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Reflection;\nusing System.Security;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Validation.Validators;\n\nnamespace System.Web.Http.Validation.Providers\n{\n    // A factory for validators based on ValidationAttribute\n    public delegate ModelValidator DataAnnotationsModelValidationFactory(IEnumerable<ModelValidatorProvider> validatorProviders, ValidationAttribute attribute);\n\n    // A factory for validators based on IValidatableObject\n    public delegate ModelValidator DataAnnotationsValidatableObjectAdapterFactory(IEnumerable<ModelValidatorProvider> validatorProviders);\n\n    /// <summary>\n    /// An implementation of <see cref=\"ModelValidatorProvider\"/> which providers validators\n    /// for attributes which derive from <see cref=\"ValidationAttribute\"/>. It also provides\n    /// a validator for types which implement <see cref=\"IValidatableObject\"/>.\n    /// </summary>\n    public class DataAnnotationsModelValidatorProvider : AssociatedValidatorProvider\n    {\n        // Factories for validation attributes\n\n        internal DataAnnotationsModelValidationFactory DefaultAttributeFactory =\n            (validationProviders, attribute) => new DataAnnotationsModelValidator(validationProviders, attribute);\n\n        internal Dictionary<Type, DataAnnotationsModelValidationFactory> AttributeFactories =\n            new Dictionary<Type, DataAnnotationsModelValidationFactory>();\n\n        // Factories for IValidatableObject models\n        internal DataAnnotationsValidatableObjectAdapterFactory DefaultValidatableFactory =\n            (validationProviders) => new ValidatableObjectAdapter(validationProviders);\n\n        internal Dictionary<Type, DataAnnotationsValidatableObjectAdapterFactory> ValidatableFactories =\n            new Dictionary<Type, DataAnnotationsValidatableObjectAdapterFactory>();\n\n        protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders, IEnumerable<Attribute> attributes)\n        {\n                List<ModelValidator> results = new List<ModelValidator>();\n\n                // Produce a validator for each validation attribute we find\n                foreach (ValidationAttribute attribute in attributes.OfType<ValidationAttribute>())\n                {\n                    DataAnnotationsModelValidationFactory factory;\n                    if (!AttributeFactories.TryGetValue(attribute.GetType(), out factory))\n                    {\n                        factory = DefaultAttributeFactory;\n                    }\n                    results.Add(factory(validatorProviders, attribute));\n                }\n\n                // Produce a validator if the type supports IValidatableObject\n                if (typeof(IValidatableObject).IsAssignableFrom(metadata.ModelType))\n                {\n                    DataAnnotationsValidatableObjectAdapterFactory factory;\n                    if (!ValidatableFactories.TryGetValue(metadata.ModelType, out factory))\n                    {\n                        factory = DefaultValidatableFactory;\n                    }\n                    results.Add(factory(validatorProviders));\n                }\n\n                return results;\n            }\n\n        #region Validation attribute adapter registration\n\n        public void RegisterAdapter(Type attributeType, Type adapterType)\n        {\n            ValidateAttributeType(attributeType);\n            ValidateAttributeAdapterType(adapterType);\n            ConstructorInfo constructor = GetAttributeAdapterConstructor(attributeType, adapterType);\n\n                AttributeFactories[attributeType] = (context, attribute) => (ModelValidator)constructor.Invoke(new object[] { context, attribute });\n            }\n\n        public void RegisterAdapterFactory(Type attributeType, DataAnnotationsModelValidationFactory factory)\n        {\n            ValidateAttributeType(attributeType);\n            ValidateAttributeFactory(factory);\n\n                AttributeFactories[attributeType] = factory;\n            }\n\n        public void RegisterDefaultAdapter(Type adapterType)\n        {\n            ValidateAttributeAdapterType(adapterType);\n            ConstructorInfo constructor = GetAttributeAdapterConstructor(typeof(ValidationAttribute), adapterType);\n\n            DefaultAttributeFactory = (context, attribute) => (ModelValidator)constructor.Invoke(new object[] { context, attribute });\n        }\n\n        public void RegisterDefaultAdapterFactory(DataAnnotationsModelValidationFactory factory)\n        {\n            ValidateAttributeFactory(factory);\n\n            DefaultAttributeFactory = factory;\n        }\n\n        // Helpers \n\n        private static ConstructorInfo GetAttributeAdapterConstructor(Type attributeType, Type adapterType)\n        {\n            ConstructorInfo constructor = adapterType.GetConstructor(new[] { typeof(IEnumerable<ModelValidatorProvider>), attributeType });\n            if (constructor == null)\n            {\n                throw Error.Argument(\"adapterType\", SRResources.DataAnnotationsModelValidatorProvider_ConstructorRequirements, adapterType.Name, typeof(ModelMetadata).Name, \"IEnumerable<\" + typeof(ModelValidatorProvider).Name + \">\", attributeType.Name);\n            }\n\n            return constructor;\n        }\n\n        private static void ValidateAttributeAdapterType(Type adapterType)\n        {\n            if (adapterType == null)\n            {\n                throw Error.ArgumentNull(\"adapterType\");\n            }\n\n            if (!typeof(ModelValidator).IsAssignableFrom(adapterType))\n            {\n                throw Error.Argument(\"adapterType\", SRResources.Common_TypeMustDriveFromType, adapterType.Name, typeof(ModelValidator).Name);\n            }\n        }\n\n        private static void ValidateAttributeType(Type attributeType)\n        {\n            if (attributeType == null)\n            {\n                throw Error.ArgumentNull(\"attributeType\");\n            }\n\n            if (!typeof(ValidationAttribute).IsAssignableFrom(attributeType))\n            {\n                throw Error.Argument(\"attributeType\", SRResources.Common_TypeMustDriveFromType, attributeType.Name, typeof(ValidationAttribute).Name);\n            }\n        }\n\n        private static void ValidateAttributeFactory(DataAnnotationsModelValidationFactory factory)\n        {\n            if (factory == null)\n            {\n                throw Error.ArgumentNull(\"factory\");\n            }\n        }\n\n        #endregion\n\n        #region IValidatableObject adapter registration\n\n        /// <summary>\n        /// Registers an adapter type for the given <paramref name=\"modelType\"/>, which must\n        /// implement <see cref=\"IValidatableObject\"/>. The adapter type must derive from\n        /// <see cref=\"ModelValidator\"/> and it must contain a public constructor\n        /// which takes two parameters of types <see cref=\"ModelMetadata\"/> and\n        /// <see cref=\"HttpActionContext\"/>.\n        /// </summary>\n        public void RegisterValidatableObjectAdapter(Type modelType, Type adapterType)\n        {\n            ValidateValidatableModelType(modelType);\n            ValidateValidatableAdapterType(adapterType);\n            ConstructorInfo constructor = GetValidatableAdapterConstructor(adapterType);\n\n                ValidatableFactories[modelType] = context => (ModelValidator)constructor.Invoke(new object[] { context });\n            }\n\n        /// <summary>\n        /// Registers an adapter factory for the given <paramref name=\"modelType\"/>, which must\n        /// implement <see cref=\"IValidatableObject\"/>.\n        /// </summary>\n        public void RegisterValidatableObjectAdapterFactory(Type modelType, DataAnnotationsValidatableObjectAdapterFactory factory)\n        {\n            ValidateValidatableModelType(modelType);\n            ValidateValidatableFactory(factory);\n\n                ValidatableFactories[modelType] = factory;\n            }\n\n        /// <summary>\n        /// Registers the default adapter type for objects which implement\n        /// <see cref=\"IValidatableObject\"/>. The adapter type must derive from\n        /// <see cref=\"ModelValidator\"/> and it must contain a public constructor\n        /// which takes two parameters of types <see cref=\"ModelMetadata\"/> and\n        /// <see cref=\"HttpActionContext\"/>.\n        /// </summary>\n        public void RegisterDefaultValidatableObjectAdapter(Type adapterType)\n        {\n            ValidateValidatableAdapterType(adapterType);\n            ConstructorInfo constructor = GetValidatableAdapterConstructor(adapterType);\n\n            DefaultValidatableFactory = context => (ModelValidator)constructor.Invoke(new object[] { context });\n        }\n\n        /// <summary>\n        /// Registers the default adapter factory for objects which implement\n        /// <see cref=\"IValidatableObject\"/>.\n        /// </summary>\n        public void RegisterDefaultValidatableObjectAdapterFactory(DataAnnotationsValidatableObjectAdapterFactory factory)\n        {\n            ValidateValidatableFactory(factory);\n\n            DefaultValidatableFactory = factory;\n        }\n\n        // Helpers \n\n        private static ConstructorInfo GetValidatableAdapterConstructor(Type adapterType)\n        {\n            ConstructorInfo constructor = adapterType.GetConstructor(new[] { typeof(IEnumerable<ModelValidatorProvider>) });\n            if (constructor == null)\n            {\n                throw Error.Argument(\"adapterType\", SRResources.DataAnnotationsModelValidatorProvider_ValidatableConstructorRequirements, adapterType.Name, typeof(ModelMetadata).Name, \"IEnumerable<\" + typeof(ModelValidatorProvider).Name + \">\");\n            }\n\n            return constructor;\n        }\n\n        private static void ValidateValidatableAdapterType(Type adapterType)\n        {\n            if (adapterType == null)\n            {\n                throw Error.ArgumentNull(\"adapterType\");\n            }\n            if (!typeof(ModelValidator).IsAssignableFrom(adapterType))\n            {\n                throw Error.Argument(\"adapterType\", SRResources.Common_TypeMustDriveFromType, adapterType.Name, typeof(ModelValidator).Name);\n            }\n        }\n\n        private static void ValidateValidatableModelType(Type modelType)\n        {\n            if (modelType == null)\n            {\n                throw Error.ArgumentNull(\"modelType\");\n            }\n            if (!typeof(IValidatableObject).IsAssignableFrom(modelType))\n            {\n                throw Error.Argument(\"modelType\", SRResources.Common_TypeMustDriveFromType, modelType.Name, typeof(IValidatableObject).Name);\n            }\n        }\n\n        private static void ValidateValidatableFactory(DataAnnotationsValidatableObjectAdapterFactory factory)\n        {\n            if (factory == null)\n            {\n                throw Error.ArgumentNull(\"factory\");\n            }\n        }\n\n        #endregion\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Validation/Providers/DataMemberModelValidatorProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Runtime.Serialization;\nusing System.Web.Http.Internal;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Validation.Validators;\n\nnamespace System.Web.Http.Validation.Providers\n{\n    /// <summary>\n    /// This <see cref=\"ModelValidatorProvider\"/> provides a required ModelValidator for members marked as [DataMember(IsRequired=true)].\n    /// </summary>\n    public class DataMemberModelValidatorProvider : AssociatedValidatorProvider\n    {\n        protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders, IEnumerable<Attribute> attributes)\n        {\n            // Types cannot be required; only properties can\n            if (metadata.ContainerType == null || String.IsNullOrEmpty(metadata.PropertyName))\n            {\n                return Enumerable.Empty<ModelValidator>();\n            }\n\n            if (IsRequiredDataMember(metadata.ContainerType, attributes))\n            {\n                return new[] { new RequiredMemberModelValidator(validatorProviders) };\n            }\n\n            return Enumerable.Empty<ModelValidator>();\n        }\n\n        internal static bool IsRequiredDataMember(Type containerType, IEnumerable<Attribute> attributes)\n        {\n            DataMemberAttribute dataMemberAttribute = attributes.OfType<DataMemberAttribute>().FirstOrDefault();\n            if (dataMemberAttribute != null)\n            {\n                // isDataContract == true iff the container type has at least one DataContractAttribute\n                bool isDataContract = TypeDescriptorHelper.Get(containerType).GetAttributes().OfType<DataContractAttribute>().Any();\n                if (isDataContract && dataMemberAttribute.IsRequired)\n                {\n                    return true;\n                }\n            }\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Validation/Providers/InvalidModelValidatorProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing System.Reflection;\nusing System.Security;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Properties;\nusing System.Web.Http.Validation.Validators;\n\nnamespace System.Web.Http.Validation.Providers\n{\n    /// <summary>\n    /// An implementation of <see cref=\"ModelValidatorProvider\"/> which provides validators that throw exceptions when the model is invalid.\n    /// </summary>\n    public class InvalidModelValidatorProvider : AssociatedValidatorProvider\n    {\n        protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders, IEnumerable<Attribute> attributes)\n        {\n            if (metadata.ContainerType == null || String.IsNullOrEmpty(metadata.PropertyName))\n            {\n                // Validate that the type's fields and nonpublic properties don't have any validation attributes on them\n                // Validation only runs against public properties\n                Type type = metadata.ModelType;\n                PropertyInfo[] nonPublicProperties = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance);\n                foreach (PropertyInfo nonPublicProperty in nonPublicProperties)\n                {\n                    if (nonPublicProperty.GetCustomAttributes(typeof(ValidationAttribute), inherit: true).Length > 0)\n                    {\n                        yield return new ErrorModelValidator(validatorProviders, Error.Format(SRResources.ValidationAttributeOnNonPublicProperty, nonPublicProperty.Name, type));\n                    }\n                }\n\n                FieldInfo[] allFields = metadata.ModelType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);\n                foreach (FieldInfo field in allFields)\n                {\n                    if (field.GetCustomAttributes(typeof(ValidationAttribute), inherit: true).Length > 0)\n                    {\n                        yield return new ErrorModelValidator(validatorProviders, Error.Format(SRResources.ValidationAttributeOnField, field.Name, type));\n                    }\n                }\n            }\n            else\n            {\n                // Validate that value-typed properties marked as [Required] are also marked as [DataMember(IsRequired=true)]\n                // Certain formatters may not recognize a member as required if it's marked as [Required] but not [DataMember(IsRequired=true)]\n                // This is not a problem for reference types because [Required] will still cause a model error to be raised after a null value is deserialized\n                if (metadata.ModelType.IsValueType && attributes.Any(attribute => attribute is RequiredAttribute))\n                {\n                    if (!DataMemberModelValidatorProvider.IsRequiredDataMember(metadata.ContainerType, attributes))\n                    {\n                        yield return new ErrorModelValidator(validatorProviders, Error.Format(SRResources.MissingDataMemberIsRequired, metadata.PropertyName, metadata.ContainerType));\n                    }\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Validation/Providers/RequiredMemberModelValidatorProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http.Formatting;\nusing System.Reflection;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Validation.Validators;\n\nnamespace System.Web.Http.Validation.Providers\n{\n    public class RequiredMemberModelValidatorProvider : ModelValidatorProvider\n    {\n        private IRequiredMemberSelector _requiredMemberSelector;\n\n        public RequiredMemberModelValidatorProvider(IRequiredMemberSelector requiredMemberSelector)\n        {\n            _requiredMemberSelector = requiredMemberSelector;\n        }\n\n        public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders)\n        {\n            string propertyName = metadata.PropertyName;\n            // if we're validating a property and not a type\n            if (propertyName != null)\n            {\n                PropertyInfo metadataProperty = metadata.ContainerType.GetProperty(propertyName);\n                if (_requiredMemberSelector.IsRequiredMember(metadataProperty))\n                {\n                    return new ModelValidator[] { new RequiredMemberModelValidator(validatorProviders) };\n                }\n            }\n\n            return Enumerable.Empty<ModelValidator>();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Validation/ReferenceEqualityComparer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Runtime.CompilerServices;\n\nnamespace System.Web.Http.Validation\n{\n    internal class ReferenceEqualityComparer : IEqualityComparer<object>\n    {\n        private static readonly ReferenceEqualityComparer _instance = new ReferenceEqualityComparer();\n\n        public static ReferenceEqualityComparer Instance\n        {\n            get\n            {\n                return _instance;\n            }\n        }\n\n        public new bool Equals(object x, object y)\n        {\n            return Object.ReferenceEquals(x, y);\n        }\n\n        public int GetHashCode(object obj)\n        {\n            return RuntimeHelpers.GetHashCode(obj);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Validation/Validators/DataAnnotationsModelValidator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.ComponentModel.DataAnnotations;\nusing System.Configuration;\nusing System.Linq;\nusing System.Web.Http.Metadata;\n\nnamespace System.Web.Http.Validation.Validators\n{\n    public class DataAnnotationsModelValidator : ModelValidator\n    {\n        internal static readonly string UseLegacyValidationMemberNameKey = \"webapi:UseLegacyValidationMemberName\";\n        private static bool _useLegacyValidationMemberName =\n            GetUseLegacyValidationMemberName(ConfigurationManager.AppSettings);\n\n        public DataAnnotationsModelValidator(\n            IEnumerable<ModelValidatorProvider> validatorProviders,\n            ValidationAttribute attribute)\n            : base(validatorProviders)\n        {\n            if (attribute == null)\n            {\n                throw Error.ArgumentNull(\"attribute\");\n            }\n\n            Attribute = attribute;\n        }\n\n        // Internal for testing\n        internal static bool UseLegacyValidationMemberName\n        {\n            get { return _useLegacyValidationMemberName; }\n            set { _useLegacyValidationMemberName = value; }\n        }\n\n        protected internal ValidationAttribute Attribute { get; private set; }\n\n        public override bool IsRequired\n        {\n            get { return Attribute is RequiredAttribute; }\n        }\n\n        public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container)\n        {\n            string memberName;\n            if (_useLegacyValidationMemberName)\n            {\n                // Using member name from a Display or DisplayFormat attribute is generally incorrect. This\n                // (configuration-controlled) override is provided only for corner cases where strict\n                // back-compatibility is required.\n                memberName = metadata.GetDisplayName();\n            }\n            else\n            {\n                // MemberName expression matches GetDisplayName() except it ignores Display and DisplayName\n                // attributes. ModelType fallback isn't great and can separate errors and attempted values in the\n                // ModelState. But, expression matches MVC, avoids a null MemberName, and is mostly back-compatible.\n                memberName = metadata.PropertyName ?? metadata.ModelType.Name;\n            }\n\n            // Per the WCF RIA Services team, instance can never be null (if you have\n            // no parent, you pass yourself for the \"instance\" parameter).\n            ValidationContext context = new ValidationContext(instance: container ?? metadata.Model)\n            {\n                DisplayName = metadata.GetDisplayName(),\n                MemberName = memberName,\n            };\n\n            ValidationResult result = Attribute.GetValidationResult(metadata.Model, context);\n\n            if (result != ValidationResult.Success)\n            {\n                // ModelValidationResult.MemberName is used by invoking validators (such as ModelValidationNode) to\n                // construct the ModelKey for ModelStateDictionary. When validating at type level we want to append the\n                // returned MemberNames if specified (e.g. person.Address.FirstName). For property validation, the\n                // ModelKey can be constructed using the ModelMetadata and we should ignore MemberName (we don't want\n                // (person.Name.Name). However the invoking validator does not have a way to distinguish between these two\n                // cases. Consequently we'll only set MemberName if this validation returns a MemberName that is different\n                // from the property being validated.\n\n                string errorMemberName = result.MemberNames.FirstOrDefault();\n                if (String.Equals(errorMemberName, memberName, StringComparison.Ordinal))\n                {\n                    errorMemberName = null;\n                }\n\n                var validationResult = new ModelValidationResult\n                {\n                    Message = result.ErrorMessage,\n                    MemberName = errorMemberName\n                };\n\n                return new ModelValidationResult[] { validationResult };\n            }\n\n            return Enumerable.Empty<ModelValidationResult>();\n        }\n\n        // Internal for testing\n        internal static bool GetUseLegacyValidationMemberName(NameValueCollection appSettings)\n        {\n            var useLegacyMemberNameArray = appSettings.GetValues(UseLegacyValidationMemberNameKey);\n            if (useLegacyMemberNameArray != null &&\n                useLegacyMemberNameArray.Length > 0)\n            {\n                bool useLegacyMemberName;\n                if (bool.TryParse(useLegacyMemberNameArray[0], out useLegacyMemberName) &&\n                    useLegacyMemberName)\n                {\n                    return true;\n                }\n            }\n\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Validation/Validators/ErrorModelValidator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http.Metadata;\n\nnamespace System.Web.Http.Validation.Validators\n{\n    /// <summary>\n    /// A <see cref=\"ModelValidator\"/> to represent an error. This validator will always throw an exception regardless of the actual model value.\n    /// </summary>\n    public class ErrorModelValidator : ModelValidator\n    {\n        private string _errorMessage;\n\n        public ErrorModelValidator(IEnumerable<ModelValidatorProvider> validatorProviders, string errorMessage) : base(validatorProviders)\n        {\n            if (errorMessage == null)\n            {\n                throw Error.ArgumentNull(\"errorMessage\");\n            }\n\n            _errorMessage = errorMessage;\n        }\n\n        public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container)\n        {\n            throw Error.InvalidOperation(_errorMessage);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Validation/Validators/RequiredMemberModelValidator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Http.Metadata;\n\nnamespace System.Web.Http.Validation.Validators\n{\n    /// <summary>\n    /// <see cref=\"ModelValidator\"/> for required members.\n    /// </summary>\n    public class RequiredMemberModelValidator : ModelValidator\n    {\n        public RequiredMemberModelValidator(IEnumerable<ModelValidatorProvider> validatorProviders)\n            : base(validatorProviders)\n        {\n        }\n\n        public override bool IsRequired\n        {\n            get { return true; }\n        }\n\n        public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container)\n        {\n            return Enumerable.Empty<ModelValidationResult>();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/Validation/Validators/ValidatableObjectAdapter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.Validation.Validators\n{\n    public class ValidatableObjectAdapter : ModelValidator\n    {\n        public ValidatableObjectAdapter(IEnumerable<ModelValidatorProvider> validatorProviders)\n            : base(validatorProviders)\n        {\n        }\n\n        public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container)\n        {\n            // NOTE: Container is never used here, because IValidatableObject doesn't give you\n            // any way to get access to your container.\n\n            object model = metadata.Model;\n            if (model == null)\n            {\n                return Enumerable.Empty<ModelValidationResult>();\n            }\n\n            IValidatableObject validatable = model as IValidatableObject;\n            if (validatable == null)\n            {\n                throw Error.InvalidOperation(SRResources.ValidatableObjectAdapter_IncompatibleType, model.GetType());\n            }\n\n            ValidationContext validationContext = new ValidationContext(validatable, null, null);\n            return ConvertResults(validatable.Validate(validationContext));\n        }\n\n        private static IEnumerable<ModelValidationResult> ConvertResults(IEnumerable<ValidationResult> results)\n        {\n            foreach (ValidationResult result in results)\n            {\n                if (result != ValidationResult.Success)\n                {\n                    if (result.MemberNames == null || !result.MemberNames.Any())\n                    {\n                        yield return new ModelValidationResult { Message = result.ErrorMessage };\n                    }\n                    else\n                    {\n                        foreach (string memberName in result.MemberNames)\n                        {\n                            yield return new ModelValidationResult { Message = result.ErrorMessage, MemberName = memberName };\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ValueProviders/IEnumerableValueProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Http.ValueProviders\n{\n    public interface IEnumerableValueProvider : IValueProvider\n    {\n        IDictionary<string, string> GetKeysFromPrefix(string prefix);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ValueProviders/IUriValueProviderFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.Http.ValueProviders\n{\n    /// <summary>\n    /// This interface is implemented by any <see cref=\"ValueProviderFactory\"/> that supports\n    /// the creation of a <see cref=\"IValueProvider\"/> to access the <see cref=\"T:System.Uri\"/> of\n    /// an incoming <see cref=\"T:System.Net.Http.HttpRequestMessage\"/>.\n    /// </summary>\n    [SuppressMessage(\"Microsoft.Design\", \"CA1040:AvoidEmptyInterfaces\", Justification = \"Tagging interface is intentional to allow Linq TypeOf\")]\n    public interface IUriValueProviderFactory\n    {\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ValueProviders/IValueProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.ValueProviders\n{\n    /// <summary>\n    /// Defines the methods that are required for a value provider in ASP.NET Web Api.\n    /// </summary>\n    public interface IValueProvider\n    {\n        /// <summary>\n        /// Determines whether the collection contains the specified prefix.\n        /// </summary>\n        /// <param name=\"prefix\">The prefix to search for.</param>\n        /// <returns>true if the collection contains the specified prefix; otherwise, false.</returns>\n        bool ContainsPrefix(string prefix);\n\n        /// <summary>\n        /// Retrieves a value object using the specified key.\n        /// </summary>\n        /// <param name=\"key\">The key of the value object to retrieve.</param>\n        /// <returns>The value object for the specified key. If the exact key is not found, null.</returns>\n        ValueProviderResult GetValue(string key);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ValueProviders/Providers/CompositeValueProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\n\nnamespace System.Web.Http.ValueProviders.Providers\n{\n    [SuppressMessage(\"Microsoft.Naming\", \"CA1710:IdentifiersShouldHaveCorrectSuffix\", Justification = \"It is more fundamentally a value provider than a collection\")]\n    public class CompositeValueProvider : Collection<IValueProvider>, IValueProvider, IEnumerableValueProvider\n    {\n        public CompositeValueProvider()\n        {\n        }\n\n        public CompositeValueProvider(IList<IValueProvider> list)\n            : base(list)\n        {\n        }\n\n        public virtual bool ContainsPrefix(string prefix)\n        {\n            foreach (IValueProvider vp in this)\n            {\n                if (vp.ContainsPrefix(prefix))\n                {\n                    return true;\n                }\n            }\n            return false;\n        }\n\n        public virtual ValueProviderResult GetValue(string key)\n        {\n            // Performance-sensitive\n            // Caching the count is faster for IList<T>\n            int itemCount = Items.Count;\n            for (int i = 0; i < itemCount; i++)\n            {\n                IValueProvider vp = Items[i];\n                ValueProviderResult result = vp.GetValue(key);\n                if (result != null)\n                {\n                    return result;\n                }\n            }\n            return null;\n        }\n\n        public virtual IDictionary<string, string> GetKeysFromPrefix(string prefix)\n        {\n            foreach (IValueProvider vp in this)\n            {\n                IDictionary<string, string> result = GetKeysFromPrefixFromProvider(vp, prefix);\n                if (result != null && result.Count > 0)\n                {\n                    return result;\n                }\n            }\n            return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);\n        }\n\n        internal static IDictionary<string, string> GetKeysFromPrefixFromProvider(IValueProvider provider, string prefix)\n        {\n            IEnumerableValueProvider enumeratedProvider = provider as IEnumerableValueProvider;\n            return (enumeratedProvider != null) ? enumeratedProvider.GetKeysFromPrefix(prefix) : null;\n        }\n\n        protected override void InsertItem(int index, IValueProvider item)\n        {\n            if (item == null)\n            {\n                throw Error.ArgumentNull(\"item\");\n            }\n            base.InsertItem(index, item);\n        }\n\n        protected override void SetItem(int index, IValueProvider item)\n        {\n            if (item == null)\n            {\n                throw Error.ArgumentNull(\"item\");\n            }\n            base.SetItem(index, item);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ValueProviders/Providers/CompositeValueProviderFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.ValueProviders.Providers\n{\n    public class CompositeValueProviderFactory : ValueProviderFactory\n    {\n        private ValueProviderFactory[] _factories;\n\n        public CompositeValueProviderFactory(IEnumerable<ValueProviderFactory> factories)\n        {\n            _factories = factories.ToArray();\n        }\n\n        public override IValueProvider GetValueProvider(HttpActionContext actionContext)\n        {\n            return GetValueProvider(actionContext, _factories);\n        }\n\n        // Get a single ValueProvider from a collection of factories. \n        // This will never return null.\n        internal static IValueProvider GetValueProvider(HttpActionContext actionContext, ValueProviderFactory[] factories)\n        {\n            // Fast-path the case of just one factory\n            if (factories.Length == 1)\n            {\n                IValueProvider provider = factories[0].GetValueProvider(actionContext);\n                if (provider != null)\n                {\n                    return provider;\n                }\n            }\n\n            List<IValueProvider> providers = new List<IValueProvider>();\n            foreach (ValueProviderFactory factory in factories)\n            {\n                IValueProvider vp = factory.GetValueProvider(actionContext);\n                if (vp != null)\n                {\n                    providers.Add(vp);\n                }\n            }\n\n            // Fast-path the case of just one provider\n            if (providers.Count == 1)\n            {\n                return providers[0];\n            }\n            \n            return new CompositeValueProvider(providers);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ValueProviders/Providers/ElementalValueProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\n\nnamespace System.Web.Http.ValueProviders.Providers\n{\n    // Represents a value provider that contains a single value.\n    internal sealed class ElementalValueProvider : IValueProvider\n    {\n        public ElementalValueProvider(string name, object rawValue, CultureInfo culture)\n        {\n            Name = name;\n            RawValue = rawValue;\n            Culture = culture;\n        }\n\n        public CultureInfo Culture { get; private set; }\n\n        public string Name { get; private set; }\n\n        public object RawValue { get; private set; }\n\n        public bool ContainsPrefix(string prefix)\n        {\n            return PrefixContainer.IsPrefixMatch(prefix, Name);\n        }\n\n        public ValueProviderResult GetValue(string key)\n        {\n            return String.Equals(key, Name, StringComparison.OrdinalIgnoreCase)\n                       ? new ValueProviderResult(RawValue, Convert.ToString(RawValue, Culture), Culture)\n                       : null;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ValueProviders/Providers/NameValuePairsValueProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\n\nnamespace System.Web.Http.ValueProviders.Providers\n{\n    public class NameValuePairsValueProvider : IEnumerableValueProvider\n    {\n        private readonly CultureInfo _culture;\n        private PrefixContainer _prefixContainer;\n        private Dictionary<string, object> _values;\n        private readonly Lazy<Dictionary<string, object>> _lazyValues;\n\n        /// <summary>\n        /// Creates a NameValuePairsProvider wrapping an existing set of key value pairs.\n        /// </summary>\n        /// <param name=\"values\">The key value pairs to wrap.</param>\n        /// <param name=\"culture\">The culture to return with ValueProviderResult instances.</param>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"Represents a collection of name/value pairs, cannot use NameValueCollection because it performs poorly\")]\n        public NameValuePairsValueProvider(IEnumerable<KeyValuePair<string, string>> values, CultureInfo culture)\n        {\n            if (values == null)\n            {\n                throw Error.ArgumentNull(\"values\");\n            }\n\n            _values = InitializeValues(values);\n            _culture = culture;\n        }\n\n        /// <summary>\n        /// Creates a NameValuePairsProvider wrapping a lazily evaluated set of key value pairs.\n        /// </summary>\n        /// <param name=\"valuesFactory\">A function returning the key value pairs to wrap.</param>\n        /// <param name=\"culture\">The culture to return with ValueProviderResult instances.</param>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"Represents a collection of name/value pairs, cannot use NameValueCollection because it performs poorly\")]\n        public NameValuePairsValueProvider(Func<IEnumerable<KeyValuePair<string, string>>> valuesFactory, CultureInfo culture)\n        {\n            if (valuesFactory == null)\n            {\n                throw Error.ArgumentNull(\"valuesFactory\");\n            }\n            _lazyValues = new Lazy<Dictionary<string, object>>(() => InitializeValues(valuesFactory()), isThreadSafe: true);\n            _culture = culture;\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"NameValuePairsValueProvider\"/> class.\n        /// </summary>\n        /// <param name=\"values\">The name value pairs.</param>\n        /// <param name=\"culture\">The culture to return with ValueProviderResult instances.</param>\n        public NameValuePairsValueProvider(IDictionary<string, object> values, CultureInfo culture)\n        {\n            if (values == null)\n            {\n                throw Error.ArgumentNull(\"values\");\n            }\n\n            _values = InitializeValues(values);\n            _culture = culture;\n        }\n\n        // For unit testing purposes\n        internal CultureInfo Culture\n        {\n            get\n            {\n                return _culture;\n            }\n        }\n\n        private PrefixContainer PrefixContainer\n        {\n            get\n            {\n                if (_prefixContainer == null)\n                {\n                    // Initialization race is OK providing data remains read-only and object identity is not significant\n                    _prefixContainer = new PrefixContainer(Values.Keys);\n                }\n                return _prefixContainer;\n            }\n        }\n\n        private Dictionary<string, object> Values\n        {\n            get\n            {\n                if (_values == null)\n                {\n                    Contract.Assert(_lazyValues != null);\n                    _values = _lazyValues.Value;\n                }\n                return _values;\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1800:DoNotCastUnnecessarily\", Justification = \"One of the casts is conditionally compiled\")]\n        private static Dictionary<string, object> InitializeValues<T>(IEnumerable<KeyValuePair<string, T>> nameValuePairs)\n            where T : class\n        {\n            // Performance-sensitive.\n            // Optimize for the cases of 0 pairs, and for names being unique when present.\n            Dictionary<string, object> valuesDictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);\n\n            // Avoid looping in the 0 case.\n            KeyValuePair<string, string>[] nameValuePairsArray = nameValuePairs as KeyValuePair<string, string>[];\n            if (nameValuePairsArray != null && nameValuePairsArray.Length == 0)\n            {\n                return valuesDictionary;\n            }\n            Dictionary<string, object> nameValuePairsDictionary = nameValuePairs as Dictionary<string, object>;\n            if (nameValuePairsDictionary != null && nameValuePairsDictionary.Count == 0)\n            {\n                return valuesDictionary;\n            }\n\n            foreach (KeyValuePair<string, T> nameValuePair in nameValuePairs)\n            {\n                string name = nameValuePair.Key;\n                object value;\n                // We optimize for the common case of a name being associated with exactly one value by avoiding a List\n                // allocation if we can avoid it. The first time the key appears, the value gets stored as a string. \n                // Only if the key appears a second time do we allocate a List to store the values for that key.\n                if (valuesDictionary.TryGetValue(name, out value))\n                {\n                    List<T> values = value as List<T>;\n                    if (values == null)\n                    {\n                        // allocate a new list to store the first value and the second, new value\n                        valuesDictionary[name] = new List<T>() { value as T, nameValuePair.Value };\n                    }\n                    else\n                    {\n                        values.Add(nameValuePair.Value);\n                    }\n                }\n                else\n                {\n                    valuesDictionary[name] = nameValuePair.Value;\n                }\n            }\n            return valuesDictionary;\n        }\n\n        public virtual bool ContainsPrefix(string prefix)\n        {\n            return PrefixContainer.ContainsPrefix(prefix);\n        }\n\n        public virtual IDictionary<string, string> GetKeysFromPrefix(string prefix)\n        {\n            if (prefix == null)\n            {\n                throw Error.ArgumentNull(\"prefix\");\n            }\n\n            return PrefixContainer.GetKeysFromPrefix(prefix);\n        }\n\n        public virtual ValueProviderResult GetValue(string key)\n        {\n            if (key == null)\n            {\n                throw Error.ArgumentNull(\"key\");\n            }\n\n            object value;\n            if (Values.TryGetValue(key, out value))\n            {\n                return new ValueProviderResult(value, GetAttemptedValue(value), _culture);\n            }\n            else\n            {\n                return null;\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1800:DoNotCastUnnecessarily\", Justification = \"One of the casts is conditionally compiled\")]\n        private static string GetAttemptedValue(object value)\n        {\n            List<string> valueStrings = value as List<string>;\n            if (valueStrings == null)\n            {\n                return value as string;\n            }\n            else\n            {\n                return String.Join(\",\", valueStrings);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ValueProviders/Providers/QueryStringValueProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.ValueProviders.Providers\n{\n    public class QueryStringValueProvider : NameValuePairsValueProvider\n    {\n        public QueryStringValueProvider(HttpActionContext actionContext, CultureInfo culture)\n            : base(actionContext.ControllerContext.Request.GetQueryNameValuePairs(), culture)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ValueProviders/Providers/QueryStringValueProviderFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.ValueProviders.Providers\n{\n    public class QueryStringValueProviderFactory : ValueProviderFactory, IUriValueProviderFactory\n    {\n        private const string RequestLocalStorageKey = \"{8572540D-3BD9-46DA-B112-A1E6C9086003}\";\n\n        public override IValueProvider GetValueProvider(HttpActionContext actionContext)\n        {\n            if (actionContext == null)\n            {\n                throw Error.ArgumentNull(\"actionContext\");\n            }\n\n            // Only parse the query string once-per request. \n                        \n            QueryStringValueProvider provider;\n            IDictionary<string, object> storage  = actionContext.Request.Properties;\n\n            if (!storage.TryGetValue(RequestLocalStorageKey, out provider))\n            {\n                provider = new QueryStringValueProvider(actionContext, CultureInfo.InvariantCulture);\n                storage[RequestLocalStorageKey] = provider;\n            }            \n            \n            return provider;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ValueProviders/Providers/RouteDataValueProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Routing;\n\nnamespace System.Web.Http.ValueProviders.Providers\n{\n    public class RouteDataValueProvider : NameValuePairsValueProvider\n    {\n        public RouteDataValueProvider(HttpActionContext actionContext, CultureInfo culture)\n            : base(GetRouteValues(actionContext.ControllerContext.RouteData), culture)\n        {\n        }\n\n        internal static IEnumerable<KeyValuePair<string, string>> GetRouteValues(IHttpRouteData routeData)\n        {\n            foreach (KeyValuePair<string, object> pair in routeData.Values)\n            {\n                string value = (pair.Value == null) ? null : pair.Value.ToString();\n                yield return new KeyValuePair<string, string>(pair.Key, value);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ValueProviders/Providers/RouteDataValueProviderFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.ValueProviders.Providers\n{\n    public class RouteDataValueProviderFactory : ValueProviderFactory, IUriValueProviderFactory\n    {\n        private const string RequestLocalStorageKey = \"{C0E50671-A1D4-429E-93C9-2AA63779924F}\";\n\n        public override IValueProvider GetValueProvider(HttpActionContext actionContext)\n        {\n            if (actionContext == null)\n            {\n                throw Error.ArgumentNull(\"actionContext\");\n            }\n\n            // cache the route provider across requests so that we don't recompute on every parameter.\n            RouteDataValueProvider provider;\n            IDictionary<string, object> storage = actionContext.Request.Properties;\n\n            if (!storage.TryGetValue(RequestLocalStorageKey, out provider))\n            {\n                provider = new RouteDataValueProvider(actionContext, CultureInfo.InvariantCulture);\n                storage[RequestLocalStorageKey] = provider;\n            }\n\n            return provider;       \n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ValueProviders/ValueProviderAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.ValueProviders\n{\n    /// <summary>\n    /// This attribute is used to specify a custom <see cref=\"ValueProviderFactory\"/>.\n    /// </summary>\n    [SuppressMessage(\"Microsoft.Design\", \"CA1019:DefineAccessorsForAttributeArguments\", Justification = \"property already exposed in plural form\")]\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)]\n    public sealed class ValueProviderAttribute : ModelBinderAttribute\n    {\n        private readonly Type[] _valueProviderFactoryTypes;\n\n        // Provide CLS compliant overload\n        public ValueProviderAttribute(Type valueProviderFactory)\n            : this(new Type[] { valueProviderFactory })\n        {\n        }\n\n        // Convenience for multiple types. This is not cls-compliant.\n        public ValueProviderAttribute(params Type[] valueProviderFactories)\n        {\n            _valueProviderFactoryTypes = valueProviderFactories;\n        }\n\n        public IEnumerable<Type> ValueProviderFactoryTypes\n        {\n            get { return _valueProviderFactoryTypes; }\n        }\n\n        public override IEnumerable<ValueProviderFactory> GetValueProviderFactories(HttpConfiguration configuration)\n        {\n            // By default, just get all registered value provider factories\n            return Array.ConvertAll(_valueProviderFactoryTypes, Instantiate);\n        }\n\n        private static ValueProviderFactory Instantiate(Type factoryType)\n        {\n            if (factoryType == null)\n            {\n                throw new ArgumentNullException(\"factoryType\");\n            }\n\n            if (!typeof(ValueProviderFactory).IsAssignableFrom(factoryType))\n            {\n                throw Error.InvalidOperation(SRResources.ValueProviderFactory_Cannot_Create, typeof(ValueProviderFactory), factoryType);\n            }\n\n            return (ValueProviderFactory)Activator.CreateInstance(factoryType);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ValueProviders/ValueProviderFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.ValueProviders\n{\n    public abstract class ValueProviderFactory\n    {\n        /// <summary>\n        /// Get a value provider with values from the given <paramref name=\"actionContext\"/>.\n        /// </summary>\n        /// <param name=\"actionContext\">action context that value provider will populate from</param>\n        /// <returns>a value provider instance or null</returns>\n        public abstract IValueProvider GetValueProvider(HttpActionContext actionContext);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/ValueProviders/ValueProviderResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Web.Http.Properties;\n\nnamespace System.Web.Http.ValueProviders\n{\n    [Serializable]\n    public class ValueProviderResult\n    {\n        private static readonly CultureInfo _staticCulture = CultureInfo.InvariantCulture;\n        private CultureInfo _instanceCulture;\n\n        // default constructor so that subclassed types can set the properties themselves\n        protected ValueProviderResult()\n        {\n        }\n\n        public ValueProviderResult(object rawValue, string attemptedValue, CultureInfo culture)\n        {\n            RawValue = rawValue;\n            AttemptedValue = attemptedValue;\n            Culture = culture;\n        }\n\n        public string AttemptedValue { get; protected set; }\n\n        public CultureInfo Culture\n        {\n            get\n            {\n                if (_instanceCulture == null)\n                {\n                    _instanceCulture = _staticCulture;\n                }\n                return _instanceCulture;\n            }\n            protected set { _instanceCulture = value; }\n        }\n\n        public object RawValue { get; protected set; }\n\n        private static object ConvertSimpleType(CultureInfo culture, object value, Type destinationType)\n        {\n            if (value == null || destinationType.IsInstanceOfType(value))\n            {\n                return value;\n            }\n\n            // if this is a user-input value but the user didn't type anything, return no value\n            string valueAsString = value as string;\n\n            if (valueAsString != null && String.IsNullOrWhiteSpace(valueAsString))\n            {\n                return null;\n            }\n\n            TypeConverter converter = TypeDescriptor.GetConverter(destinationType);\n            bool canConvertFrom = converter.CanConvertFrom(value.GetType());\n            if (!canConvertFrom)\n            {\n                converter = TypeDescriptor.GetConverter(value.GetType());\n            }\n            if (!(canConvertFrom || converter.CanConvertTo(destinationType)))\n            {\n                // EnumConverter cannot convert integer, so we verify manually\n                if (destinationType.IsEnum && value is int)\n                {\n                    return Enum.ToObject(destinationType, (int)value);\n                }\n\n                // In case of a Nullable object, we try again with its underlying type.\n                Type underlyingType = Nullable.GetUnderlyingType(destinationType);\n                if (underlyingType != null)\n                {\n                    return ConvertSimpleType(culture, value, underlyingType);\n                }\n\n                throw Error.InvalidOperation(SRResources.ValueProviderResult_NoConverterExists, value.GetType(), destinationType);\n            }\n\n            try\n            {\n                return canConvertFrom\n                           ? converter.ConvertFrom(null, culture, value)\n                           : converter.ConvertTo(null, culture, value, destinationType);\n            }\n            catch (Exception ex)\n            {\n                throw Error.InvalidOperation(ex, SRResources.ValueProviderResult_ConversionThrew, value.GetType(), destinationType);\n            }\n        }\n\n        public object ConvertTo(Type type)\n        {\n            return ConvertTo(type, null /* culture */);\n        }\n\n        public virtual object ConvertTo(Type type, CultureInfo culture)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            object value = RawValue;\n            if (value == null)\n            {\n                // treat null route parameters as though they were the default value for the type\n                return type.IsValueType ? Activator.CreateInstance(type) : null;\n            }\n\n            if (type.IsInstanceOfType(value))\n            {\n                return value;\n            }\n\n            CultureInfo cultureToUse = culture ?? Culture;\n            return UnwrapPossibleListType(cultureToUse, value, type);\n        }\n\n        private static object UnwrapPossibleListType(CultureInfo culture, object value, Type destinationType)\n        {\n            // array conversion results in four cases, as below\n            IList valueAsList = value as IList;\n            if (destinationType.IsArray)\n            {\n                Type destinationElementType = destinationType.GetElementType();\n                if (valueAsList != null)\n                {\n                    // case 1: both destination + source type are lists, so convert each element\n                    IList converted = Array.CreateInstance(destinationElementType, valueAsList.Count);\n                    for (int i = 0; i < valueAsList.Count; i++)\n                    {\n                        converted[i] = ConvertSimpleType(culture, valueAsList[i], destinationElementType);\n                    }\n                    return converted;\n                }\n                else\n                {\n                    // case 2: destination type is array but source is single element, so wrap element in array + convert\n                    object element = ConvertSimpleType(culture, value, destinationElementType);\n                    IList converted = Array.CreateInstance(destinationElementType, 1);\n                    converted[0] = element;\n                    return converted;\n                }\n            }\n            else if (valueAsList != null)\n            {\n                // case 3: destination type is single element but source is array, so extract first element + convert\n                if (valueAsList.Count > 0)\n                {\n                    value = valueAsList[0];\n                    return ConvertSimpleType(culture, value, destinationType);\n                }\n                else\n                {\n                    // case 3(a): source is empty array, so can't perform conversion\n                    return null;\n                }\n            }\n\n            // case 4: both destination + source type are single elements, so convert\n            return ConvertSimpleType(culture, value, destinationType);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Newtonsoft.Json\" version=\"13.0.1\" targetFramework=\"net45\" />\n</packages>"
  },
  {
    "path": "src/System.Web.Http.Cors/AttributeBasedPolicyProviderFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Web.Cors;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Cors.Properties;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.Routing;\n\nnamespace System.Web.Http.Cors\n{\n    /// <summary>\n    /// An implementation of <see cref=\"ICorsPolicyProviderFactory\"/> that returns the <see cref=\"ICorsPolicyProvider\"/> from the controller or action attribute.\n    /// </summary>\n    public class AttributeBasedPolicyProviderFactory : ICorsPolicyProviderFactory\n    {\n        private const string HttpContextBaseKey = \"MS_HttpContext\";\n\n        /// <summary>\n        /// Gets or sets the default <see cref=\"ICorsPolicyProvider\"/>.\n        /// </summary>\n        public ICorsPolicyProvider DefaultPolicyProvider { get; set; }\n\n        /// <summary>\n        /// Gets the <see cref=\"ICorsPolicyProvider\" /> for the request.\n        /// </summary>\n        /// <param name=\"request\">The request.</param>\n        /// <returns>\n        /// The <see cref=\"ICorsPolicyProvider\" />.\n        /// </returns>\n        /// <exception cref=\"System.ArgumentNullException\">request</exception>\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"The object is registered for disposal when the request message is disposed.\")]\n        public virtual ICorsPolicyProvider GetCorsPolicyProvider(HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw new ArgumentNullException(\"request\");\n            }\n\n            CorsRequestContext corsRequestContext = request.GetCorsRequestContext();\n            HttpActionDescriptor actionDescriptor = null;\n            if (corsRequestContext.IsPreflight)\n            {\n                HttpRequestMessage targetRequest = new HttpRequestMessage(new HttpMethod(corsRequestContext.AccessControlRequestMethod), request.RequestUri);\n\n                request.RegisterForDispose(targetRequest);\n\n                try\n                {\n                    foreach (var property in request.Properties)\n                    {\n                        // The RouteData and HttpContext from the preflight request properties contain information\n                        // relevant to the preflight request and not the actual request, therefore we need to exclude them.\n                        if (property.Key != HttpPropertyKeys.HttpRouteDataKey &&\n                            property.Key != HttpContextBaseKey)\n                        {\n                            targetRequest.Properties.Add(property.Key, property.Value);\n                        }\n                    }\n\n                    HttpConfiguration config = request.GetConfiguration();\n                    if (config == null)\n                    {\n                        throw new InvalidOperationException(SRResources.NoConfiguration);\n                    }\n\n                    IHttpRouteData routeData = config.Routes.GetRouteData(request);\n                    if (routeData == null)\n                    {\n                        // No route data found for selecting action with EnableCorsAttribute, thus no ICorsPolicyProvider is returned\n                        // and let the CorsMessageHandler flow the request to the normal Web API pipeline.\n                        return null;\n                    }\n\n                    actionDescriptor = SelectAction(targetRequest, routeData, config);\n                }\n                catch\n                {\n                    if (DefaultPolicyProvider != null)\n                    {\n                        return DefaultPolicyProvider;\n                    }\n                    throw;\n                }\n            }\n            else\n            {\n                actionDescriptor = request.GetActionDescriptor();\n            }\n\n            return GetCorsPolicyProvider(actionDescriptor);\n        }\n\n        private ICorsPolicyProvider GetCorsPolicyProvider(HttpActionDescriptor actionDescriptor)\n        {\n            ICorsPolicyProvider policyProvider = null;\n            if (actionDescriptor != null)\n            {\n                HttpControllerDescriptor controllerDescriptor = actionDescriptor.ControllerDescriptor;\n                policyProvider = actionDescriptor.GetCustomAttributes<ICorsPolicyProvider>().FirstOrDefault();\n                if (policyProvider == null && controllerDescriptor != null)\n                {\n                    policyProvider = controllerDescriptor.GetCustomAttributes<ICorsPolicyProvider>().FirstOrDefault();\n                }\n            }\n\n            if (policyProvider == null)\n            {\n                policyProvider = DefaultPolicyProvider;\n            }\n\n            return policyProvider;\n        }\n\n        private static HttpActionDescriptor SelectAction(HttpRequestMessage request, IHttpRouteData routeData, HttpConfiguration config)\n        {\n            request.SetRouteData(routeData);\n\n            routeData.RemoveOptionalRoutingParameters();\n\n            HttpControllerDescriptor controllerDescriptor = config.Services.GetHttpControllerSelector().SelectController(request);\n\n            // Get the per-controller configuration\n            config = controllerDescriptor.Configuration;\n            request.SetConfiguration(config);\n            HttpRequestContext requestContext = request.GetRequestContext();\n\n            if (requestContext == null)\n            {\n                requestContext = new HttpRequestContext\n                {\n                    Configuration = config,\n                    RouteData = routeData,\n                    Url = new UrlHelper(request),\n                    VirtualPathRoot = config.VirtualPathRoot\n                };\n            }\n\n            IHttpController controller = controllerDescriptor.CreateController(request);\n            using (controller as IDisposable)\n            {\n                HttpControllerContext controllerContext = new HttpControllerContext(requestContext, request, controllerDescriptor, controller);\n                return config.Services.GetActionSelector().SelectAction(controllerContext);\n            }\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http.Cors/CorsHttpConfigurationExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Cors;\nusing System.Web.Http.Cors;\nusing System.Web.Http.Cors.Tracing;\nusing System.Web.Http.Tracing;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// CORS-related extension methods for <see cref=\"HttpConfiguration\"/>.\n    /// </summary>\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class CorsHttpConfigurationExtensions\n    {\n        private const string CorsEngineKey = \"MS_CorsEngineKey\";\n        private const string CorsPolicyProviderFactoryKey = \"MS_CorsPolicyProviderFactoryKey\";\n        private const string CorsEnabledKey = \"MS_CorsEnabledKey\";\n\n        /// <summary>\n        /// Enables the support for CORS.\n        /// </summary>\n        /// <param name=\"httpConfiguration\">The <see cref=\"HttpConfiguration\"/>.</param>\n        public static void EnableCors(this HttpConfiguration httpConfiguration)\n        {\n            EnableCors(httpConfiguration, null, false);\n        }\n        \n        /// <summary>\n        /// Enables the support for CORS.\n        /// </summary>\n        /// <param name=\"httpConfiguration\">The <see cref=\"HttpConfiguration\"/>.</param>\n        /// <param name=\"rethrowExceptions\">Indicates whether upstream exceptions should be rethrown</param>\n        public static void EnableCors(this HttpConfiguration httpConfiguration, bool rethrowExceptions)\n        {\n            EnableCors(httpConfiguration, null, rethrowExceptions);\n        }\n\n        /// <summary>\n        /// Enables the support for CORS.\n        /// </summary>\n        /// <param name=\"httpConfiguration\">The <see cref=\"HttpConfiguration\"/>.</param>\n        /// <param name=\"defaultPolicyProvider\">The default <see cref=\"ICorsPolicyProvider\"/>.</param>\n        public static void EnableCors(this HttpConfiguration httpConfiguration, ICorsPolicyProvider defaultPolicyProvider)\n        {\n            EnableCors(httpConfiguration, defaultPolicyProvider, false);\n        }\n\n        /// <summary>\n        /// Enables the support for CORS.\n        /// </summary>\n        /// <param name=\"httpConfiguration\">The <see cref=\"HttpConfiguration\"/>.</param>\n        /// <param name=\"defaultPolicyProvider\">The default <see cref=\"ICorsPolicyProvider\"/>.</param>\n        /// <param name=\"rethrowExceptions\">Indicates whether upstream exceptions should be rethrown</param>\n        /// <exception cref=\"System.ArgumentNullException\">httpConfiguration</exception>\n        public static void EnableCors(this HttpConfiguration httpConfiguration, ICorsPolicyProvider defaultPolicyProvider,\n            bool rethrowExceptions)\n        {\n            if (httpConfiguration == null)\n            {\n                throw new ArgumentNullException(\"httpConfiguration\");\n            }\n\n            if (defaultPolicyProvider != null)\n            {\n                AttributeBasedPolicyProviderFactory policyProviderFactory = new AttributeBasedPolicyProviderFactory();\n                policyProviderFactory.DefaultPolicyProvider = defaultPolicyProvider;\n                httpConfiguration.SetCorsPolicyProviderFactory(policyProviderFactory);\n            }\n\n            AddCorsMessageHandler(httpConfiguration, rethrowExceptions);\n        }\n\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"Caller owns the disposable object\")]\n        private static void AddCorsMessageHandler(this HttpConfiguration httpConfiguration, bool rethrowExceptions)\n        {\n            object corsEnabled;\n            if (!httpConfiguration.Properties.TryGetValue(CorsEnabledKey, out corsEnabled))\n            {\n                Action<HttpConfiguration> defaultInitializer = httpConfiguration.Initializer;\n                httpConfiguration.Initializer = config =>\n                {\n                    if (!config.Properties.TryGetValue(CorsEnabledKey, out corsEnabled))\n                    {\n                        // Execute this in the Initializer to ensure that the CorsMessageHandler is added last.\n                        config.MessageHandlers.Add(new CorsMessageHandler(config, rethrowExceptions));\n\n                        ITraceWriter traceWriter = config.Services.GetTraceWriter();\n\n                        if (traceWriter != null)\n                        {\n                            ICorsPolicyProviderFactory factory = config.GetCorsPolicyProviderFactory();\n                            config.SetCorsPolicyProviderFactory(new CorsPolicyProviderFactoryTracer(factory, traceWriter));\n                            ICorsEngine corsEngine = config.GetCorsEngine();\n                            config.SetCorsEngine(new CorsEngineTracer(corsEngine, traceWriter));\n                        }\n\n                        config.Properties[CorsEnabledKey] = true;\n                    }\n                    defaultInitializer(config);\n                };\n            }\n        }\n\n        /// <summary>\n        /// Sets the <see cref=\"ICorsEngine\"/> on the <see cref=\"HttpConfiguration\"/>.\n        /// </summary>\n        /// <param name=\"httpConfiguration\">The <see cref=\"HttpConfiguration\"/>.</param>\n        /// <param name=\"corsEngine\">The <see cref=\"ICorsEngine\"/>.</param>\n        /// <exception cref=\"System.ArgumentNullException\">\n        /// httpConfiguration\n        /// or\n        /// corsEngine\n        /// </exception>\n        public static void SetCorsEngine(this HttpConfiguration httpConfiguration, ICorsEngine corsEngine)\n        {\n            if (httpConfiguration == null)\n            {\n                throw new ArgumentNullException(\"httpConfiguration\");\n            }\n            if (corsEngine == null)\n            {\n                throw new ArgumentNullException(\"corsEngine\");\n            }\n\n            httpConfiguration.Properties[CorsEngineKey] = corsEngine;\n        }\n\n        /// <summary>\n        /// Gets the <see cref=\"ICorsEngine\"/> from the <see cref=\"HttpConfiguration\"/>.\n        /// </summary>\n        /// <param name=\"httpConfiguration\">The <see cref=\"HttpConfiguration\"/>.</param>\n        /// <returns>The <see cref=\"ICorsEngine\"/>.</returns>\n        /// <exception cref=\"System.ArgumentNullException\">httpConfiguration</exception>\n        public static ICorsEngine GetCorsEngine(this HttpConfiguration httpConfiguration)\n        {\n            if (httpConfiguration == null)\n            {\n                throw new ArgumentNullException(\"httpConfiguration\");\n            }\n\n            return (ICorsEngine)httpConfiguration.Properties.GetOrAdd(CorsEngineKey, k => new CorsEngine());\n        }\n\n        /// <summary>\n        /// Sets the <see cref=\"ICorsPolicyProviderFactory\"/> on the <see cref=\"HttpConfiguration\"/>.\n        /// </summary>\n        /// <param name=\"httpConfiguration\">The <see cref=\"HttpConfiguration\"/>.</param>\n        /// <param name=\"corsPolicyProviderFactory\">The <see cref=\"ICorsPolicyProviderFactory\"/>.</param>\n        /// <exception cref=\"System.ArgumentNullException\">\n        /// httpConfiguration\n        /// or\n        /// corsPolicyProviderFactory\n        /// </exception>\n        public static void SetCorsPolicyProviderFactory(this HttpConfiguration httpConfiguration, ICorsPolicyProviderFactory corsPolicyProviderFactory)\n        {\n            if (httpConfiguration == null)\n            {\n                throw new ArgumentNullException(\"httpConfiguration\");\n            }\n            if (corsPolicyProviderFactory == null)\n            {\n                throw new ArgumentNullException(\"corsPolicyProviderFactory\");\n            }\n\n            httpConfiguration.Properties[CorsPolicyProviderFactoryKey] = corsPolicyProviderFactory;\n        }\n\n        /// <summary>\n        /// Gets the <see cref=\"ICorsPolicyProviderFactory\"/> from the <see cref=\"HttpConfiguration\"/>.\n        /// </summary>\n        /// <param name=\"httpConfiguration\">The <see cref=\"HttpConfiguration\"/>.</param>\n        /// <returns>The <see cref=\"ICorsPolicyProviderFactory\"/>.</returns>\n        /// <exception cref=\"System.ArgumentNullException\">httpConfiguration</exception>\n        public static ICorsPolicyProviderFactory GetCorsPolicyProviderFactory(this HttpConfiguration httpConfiguration)\n        {\n            if (httpConfiguration == null)\n            {\n                throw new ArgumentNullException(\"httpConfiguration\");\n            }\n\n            return (ICorsPolicyProviderFactory)httpConfiguration.Properties.GetOrAdd(CorsPolicyProviderFactoryKey, k => new AttributeBasedPolicyProviderFactory());\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http.Cors/CorsHttpRequestMessageExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Web.Cors;\n\nnamespace System.Web.Http.Cors\n{\n    /// <summary>\n    /// CORS-related extension methods for <see cref=\"HttpRequestMessage\"/>.\n    /// </summary>\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class CorsHttpRequestMessageExtensions\n    {\n        private const string CorsRequestContextKey = \"MS_CorsRequestContextKey\";\n\n        /// <summary>\n        /// Gets the <see cref=\"CorsRequestContext\"/> for a given request.\n        /// </summary>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/>.</param>\n        /// <returns>The <see cref=\"CorsRequestContext\"/>.</returns>\n        /// <exception cref=\"System.ArgumentNullException\">request</exception>\n        public static CorsRequestContext GetCorsRequestContext(this HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw new ArgumentNullException(\"request\");\n            }\n\n            object corsRequestContext;\n            if (!request.Properties.TryGetValue(CorsRequestContextKey, out corsRequestContext))\n            {\n                if (!request.Headers.Contains(CorsConstants.Origin))\n                {\n                    return null;\n                }\n\n                CorsRequestContext requestContext = new CorsRequestContext\n                {\n                    RequestUri = request.RequestUri,\n                    HttpMethod = request.Method.Method,\n                    Host = request.Headers.Host,\n                    Origin = request.GetHeader(CorsConstants.Origin),\n                    AccessControlRequestMethod = request.GetHeader(CorsConstants.AccessControlRequestMethod)\n                };\n                requestContext.Properties.Add(typeof(HttpRequestMessage).FullName, request);\n\n                IEnumerable<string> accessControlRequestHeaders = request.GetHeaders(CorsConstants.AccessControlRequestHeaders);\n                foreach (string accessControlRequestHeader in accessControlRequestHeaders)\n                {\n                    if (accessControlRequestHeader != null)\n                    {\n                        IEnumerable<string> headerValues = accessControlRequestHeader.Split(',').Select(x => x.Trim());\n                        foreach (string header in headerValues)\n                        {\n                            requestContext.AccessControlRequestHeaders.Add(header);\n                        }\n                    }\n                }\n\n                request.Properties.Add(CorsRequestContextKey, requestContext);\n                corsRequestContext = requestContext;\n            }\n\n            return (CorsRequestContext)corsRequestContext;\n        }\n\n        private static string GetHeader(this HttpRequestMessage request, string name)\n        {\n            return request.GetHeaders(name).FirstOrDefault();\n        }\n\n        private static IEnumerable<string> GetHeaders(this HttpRequestMessage request, string name)\n        {\n            IEnumerable<string> headerValues;\n            if (request.Headers.TryGetValues(name, out headerValues))\n            {\n                if (headerValues != null)\n                {\n                    return headerValues;\n                }\n            }\n\n            return Enumerable.Empty<string>();\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http.Cors/CorsHttpResponseMessageExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Net.Http;\nusing System.Web.Cors;\n\nnamespace System.Web.Http.Cors\n{\n    /// <summary>\n    /// CORS-related extension methods for <see cref=\"HttpResponseMessage\"/>.\n    /// </summary>\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class CorsHttpResponseMessageExtensions\n    {\n        /// <summary>\n        /// Writes the CORS headers on the response.\n        /// </summary>\n        /// <param name=\"response\">The <see cref=\"HttpResponseMessage\"/>.</param>\n        /// <param name=\"corsResult\">The <see cref=\"CorsResult\"/>.</param>\n        /// <exception cref=\"System.ArgumentNullException\">\n        /// response\n        /// or\n        /// corsResult\n        /// </exception>\n        public static void WriteCorsHeaders(this HttpResponseMessage response, CorsResult corsResult)\n        {\n            if (response == null)\n            {\n                throw new ArgumentNullException(\"response\");\n            }\n            if (corsResult == null)\n            {\n                throw new ArgumentNullException(\"corsResult\");\n            }\n\n            IDictionary<string, string> corsHeaders = corsResult.ToResponseHeaders();\n            if (corsHeaders != null)\n            {\n                foreach (KeyValuePair<string, string> header in corsHeaders)\n                {\n                    response.Headers.TryAddWithoutValidation(header.Key, header.Value);\n                }\n            }\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http.Cors/CorsMessageHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Cors;\nusing System.Web.Http.Cors.Properties;\n\nnamespace System.Web.Http.Cors\n{\n    /// <summary>\n    /// Custom <see cref=\"DelegatingHandler\"/> for handling CORS requests.\n    /// </summary>\n    public class CorsMessageHandler : DelegatingHandler\n    {\n        private HttpConfiguration _httpConfiguration;\n        private bool _rethrowExceptions;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"CorsMessageHandler\"/> class.\n        /// </summary>\n        /// <param name=\"httpConfiguration\">The <see cref=\"HttpConfiguration\"/>.</param>\n        /// <exception cref=\"System.ArgumentNullException\">httpConfiguration</exception>\n        public CorsMessageHandler(HttpConfiguration httpConfiguration) : this(httpConfiguration, false)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"CorsMessageHandler\"/> class.\n        /// </summary>\n        /// <param name=\"httpConfiguration\">The <see cref=\"HttpConfiguration\"/>.</param>\n        /// <param name=\"rethrowExceptions\">Indicates whether upstream exceptions should be rethrown</param>\n        /// <exception cref=\"System.ArgumentNullException\">httpConfiguration</exception>\n        public CorsMessageHandler(HttpConfiguration httpConfiguration, bool rethrowExceptions)\n        {\n            if (httpConfiguration == null)\n            {\n                throw new ArgumentNullException(\"httpConfiguration\");\n            }\n\n            _httpConfiguration = httpConfiguration;\n            _rethrowExceptions = rethrowExceptions;\n        }\n\n        /// <summary>\n        /// Sends an HTTP request to the inner handler to send to the server as an asynchronous operation.\n        /// </summary>\n        /// <param name=\"request\">The HTTP request message to send to the server.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>\n        /// Returns <see cref=\"T:System.Threading.Tasks.Task`1\" />. The task object representing the asynchronous operation.\n        /// </returns>\n        protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n        {\n            CorsRequestContext corsRequestContext = request.GetCorsRequestContext();\n            if (corsRequestContext != null)\n            {\n                try\n                {\n                    if (corsRequestContext.IsPreflight)\n                    {\n                        return await HandleCorsPreflightRequestAsync(request, corsRequestContext, cancellationToken);\n                    }\n                    else\n                    {\n                        return await HandleCorsRequestAsync(request, corsRequestContext, cancellationToken);\n                    }\n                }\n                catch (Exception exception)\n                {\n                    if (_rethrowExceptions)\n                    {\n                        throw;\n                    }\n\n                    return HandleException(request, exception);\n                }\n            }\n            else\n            {\n                return await base.SendAsync(request, cancellationToken);\n            }\n        }\n\n        /// <summary>\n        /// Handles the actual CORS request.\n        /// </summary>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/>.</param>\n        /// <param name=\"corsRequestContext\">The <see cref=\"CorsRequestContext\"/>.</param>\n        /// <param name=\"cancellationToken\">The <see cref=\"CancellationToken\"/>.</param>\n        /// <returns>The <see cref=\"Task{HttpResponseMessage}\"/>.</returns>\n        /// <exception cref=\"System.ArgumentNullException\">\n        /// request\n        /// or\n        /// corsRequestContext\n        /// </exception>\n        public virtual async Task<HttpResponseMessage> HandleCorsRequestAsync(HttpRequestMessage request, CorsRequestContext corsRequestContext, CancellationToken cancellationToken)\n        {\n            if (request == null)\n            {\n                throw new ArgumentNullException(\"request\");\n            }\n            if (corsRequestContext == null)\n            {\n                throw new ArgumentNullException(\"corsRequestContext\");\n            }\n\n            HttpResponseMessage response = await base.SendAsync(request, cancellationToken);\n            CorsPolicy corsPolicy = await GetCorsPolicyAsync(request, cancellationToken);\n            if (corsPolicy != null)\n            {\n                CorsResult result;\n                if (TryEvaluateCorsPolicy(corsRequestContext, corsPolicy, out result))\n                {\n                    if (response != null)\n                    {\n                        response.WriteCorsHeaders(result);\n                    }\n                }\n            }\n            return response;\n        }\n\n        /// <summary>\n        /// Handles the preflight request specified by CORS.\n        /// </summary>\n        /// <param name=\"request\">The request.</param>\n        /// <param name=\"corsRequestContext\">The cors request context.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>The <see cref=\"Task{HttpResponseMessage}\"/></returns>\n        /// <exception cref=\"System.ArgumentNullException\">\n        /// request\n        /// or\n        /// corsRequestContext\n        /// </exception>\n        public virtual async Task<HttpResponseMessage> HandleCorsPreflightRequestAsync(HttpRequestMessage request, CorsRequestContext corsRequestContext, CancellationToken cancellationToken)\n        {\n            if (request == null)\n            {\n                throw new ArgumentNullException(\"request\");\n            }\n            if (corsRequestContext == null)\n            {\n                throw new ArgumentNullException(\"corsRequestContext\");\n            }\n\n            try\n            {\n                // Make sure Access-Control-Request-Method is valid.\n                new HttpMethod(corsRequestContext.AccessControlRequestMethod);\n            }\n            catch (ArgumentException)\n            {\n                return request.CreateErrorResponse(HttpStatusCode.BadRequest,\n                        SRResources.AccessControlRequestMethodCannotBeNullOrEmpty);\n            }\n            catch (FormatException)\n            {\n                return request.CreateErrorResponse(HttpStatusCode.BadRequest,\n                    String.Format(CultureInfo.CurrentCulture,\n                        SRResources.InvalidAccessControlRequestMethod,\n                        corsRequestContext.AccessControlRequestMethod));\n            }\n\n            CorsPolicy corsPolicy = await GetCorsPolicyAsync(request, cancellationToken);\n            if (corsPolicy != null)\n            {\n                HttpResponseMessage response = null;\n                CorsResult result;\n                if (TryEvaluateCorsPolicy(corsRequestContext, corsPolicy, out result))\n                {\n                    response = request.CreateResponse(HttpStatusCode.OK);\n                    response.WriteCorsHeaders(result);\n                }\n                else\n                {\n                    response = result != null ?\n                        request.CreateErrorResponse(HttpStatusCode.BadRequest, String.Join(\" | \", result.ErrorMessages)) :\n                        request.CreateResponse(HttpStatusCode.BadRequest);\n                }\n\n                return response;\n            }\n            else\n            {\n                return await base.SendAsync(request, cancellationToken);\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"Caller owns HttpRequestMessage instance.\")]\n        private static HttpResponseMessage HandleException(HttpRequestMessage request, Exception exception)\n        {\n            HttpResponseException httpResponseException = exception as HttpResponseException;\n\n            if (httpResponseException != null)\n            {\n                return httpResponseException.Response;\n            }\n\n            return request.CreateErrorResponse(HttpStatusCode.InternalServerError, exception);\n        }\n\n        private async Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n        {\n            CorsPolicy corsPolicy = null;\n            ICorsPolicyProviderFactory corsPolicyProviderFactory = _httpConfiguration.GetCorsPolicyProviderFactory();\n            ICorsPolicyProvider corsPolicyProvider = corsPolicyProviderFactory.GetCorsPolicyProvider(request);\n            if (corsPolicyProvider != null)\n            {\n                corsPolicy = await corsPolicyProvider.GetCorsPolicyAsync(request, cancellationToken);\n            }\n            return corsPolicy;\n        }\n\n        private bool TryEvaluateCorsPolicy(CorsRequestContext requestContext, CorsPolicy corsPolicy, out CorsResult corsResult)\n        {\n            ICorsEngine engine = _httpConfiguration.GetCorsEngine();\n            corsResult = engine.EvaluatePolicy(requestContext, corsPolicy);\n            return corsResult != null && corsResult.IsValid;\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http.Cors/DisableCorsAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Cors;\n\nnamespace System.Web.Http.Cors\n{\n    /// <summary>\n    /// This class defines an attribute that can be applied to an action or a controller to disable CORS.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]\n    public sealed class DisableCorsAttribute : Attribute, ICorsPolicyProvider\n    {\n        /// <inheritdoc />\n        public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n        {\n            return Task.FromResult<CorsPolicy>(null);\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http.Cors/EnableCorsAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Cors;\nusing System.Web.Http.Cors.Properties;\n\nnamespace System.Web.Http.Cors\n{\n    /// <summary>\n    /// This class defines an attribute that can be applied to an action or a controller to enable CORS.\n    /// By default, it allows all origins, methods and headers.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]\n    [SuppressMessage(\"Microsoft.Design\", \"CA1019:DefineAccessorsForAttributeArguments\", Justification = \"Attribute arguments are accessible as collections.\")]\n    public sealed class EnableCorsAttribute : Attribute, ICorsPolicyProvider\n    {\n        private CorsPolicy _corsPolicy;\n        private bool _originsValidated;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"EnableCorsAttribute\" /> class.\n        /// </summary>\n        /// <param name=\"origins\">Comma-separated list of origins that are allowed to access the resource. Use \"*\" to allow all.</param>\n        /// <param name=\"headers\">Comma-separated list of headers that are supported by the resource. Use \"*\" to allow all. Use null or empty string to allow none.</param>\n        /// <param name=\"methods\">\n        /// Comma-separated list of methods that are supported by the resource. Use \"*\" to allow all. Use null or empty string to allow none.\n        /// Note:\n        /// Http verbs are case-sensitive, if you don't use \"*\", you should use upper case when specifying GET, PUT, POST, DELETE etc.\n        /// For example:\n        /// var cors = new EnableCorsAttribute(\"http://localhost:1234\", \"*\", \"GET,PUT,POST,DELETE\");\n        /// </param>\n        public EnableCorsAttribute(string origins, string headers, string methods)\n            : this(origins, headers, methods, null)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"EnableCorsAttribute\" /> class.\n        /// </summary>\n        /// <param name=\"origins\">Comma-separated list of origins that are allowed to access the resource. Use \"*\" to allow all.</param>\n        /// <param name=\"headers\">Comma-separated list of headers that are supported by the resource. Use \"*\" to allow all. Use null or empty string to allow none.</param>\n        /// <param name=\"methods\">\n        /// Comma-separated list of methods that are supported by the resource. Use \"*\" to allow all. Use null or empty string to allow none.\n        /// Note:\n        /// Http verbs are case-sensitive, if you don't use \"*\", you should use upper case when specifying GET, PUT, POST, DELETE etc.\n        /// For example:\n        /// var cors = new EnableCorsAttribute(\"http://localhost:1234\", \"*\", \"GET,PUT,POST,DELETE\");\n        /// </param>\n        /// <param name=\"exposedHeaders\">Comma-separated list of headers that the resource might use and can be exposed. Use null or empty string to expose none.</param>\n        public EnableCorsAttribute(string origins, string headers, string methods, string exposedHeaders)\n        {\n            if (String.IsNullOrEmpty(origins))\n            {\n                throw new ArgumentException(\n                    SRResources.ArgumentCannotBeNullOrEmpty,\n                    \"origins\");\n            }\n\n            _corsPolicy = new CorsPolicy();\n            if (origins == \"*\")\n            {\n                _corsPolicy.AllowAnyOrigin = true;\n            }\n            else\n            {\n                AddCommaSeparatedValuesToCollection(origins, _corsPolicy.Origins);\n            }\n\n            if (!String.IsNullOrEmpty(headers))\n            {\n                if (headers == \"*\")\n                {\n                    _corsPolicy.AllowAnyHeader = true;\n                }\n                else\n                {\n                    AddCommaSeparatedValuesToCollection(headers, _corsPolicy.Headers);\n                }\n            }\n\n            if (!String.IsNullOrEmpty(methods))\n            {\n                if (methods == \"*\")\n                {\n                    _corsPolicy.AllowAnyMethod = true;\n                }\n                else\n                {\n                    AddCommaSeparatedValuesToCollection(methods, _corsPolicy.Methods);\n                }\n            }\n\n            if (!String.IsNullOrEmpty(exposedHeaders))\n            {\n                AddCommaSeparatedValuesToCollection(exposedHeaders, _corsPolicy.ExposedHeaders);\n            }\n        }\n\n        /// <summary>\n        /// Gets the headers that the resource might use and can be exposed.\n        /// </summary>\n        public IList<string> ExposedHeaders\n        {\n            get\n            {\n                return _corsPolicy.ExposedHeaders;\n            }\n        }\n\n        /// <summary>\n        /// Gets the headers that are supported by the resource.\n        /// </summary>\n        public IList<string> Headers\n        {\n            get\n            {\n                return _corsPolicy.Headers;\n            }\n        }\n\n        /// <summary>\n        /// Gets the methods that are supported by the resource.\n        /// </summary>\n        public IList<string> Methods\n        {\n            get\n            {\n                return _corsPolicy.Methods;\n            }\n        }\n\n        /// <summary>\n        /// Gets the origins that are allowed to access the resource.\n        /// </summary>\n        public IList<string> Origins\n        {\n            get\n            {\n                return _corsPolicy.Origins;\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets the number of seconds the results of a preflight request can be cached.\n        /// </summary>\n        public long PreflightMaxAge\n        {\n            get\n            {\n                return _corsPolicy.PreflightMaxAge ?? -1;\n            }\n            set\n            {\n                _corsPolicy.PreflightMaxAge = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets a value indicating whether the resource supports user credentials in the request.\n        /// </summary>\n        public bool SupportsCredentials\n        {\n            get\n            {\n                return _corsPolicy.SupportsCredentials;\n            }\n            set\n            {\n                _corsPolicy.SupportsCredentials = value;\n            }\n        }\n\n        /// <inheritdoc />\n        public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n        {\n            if (!_originsValidated)\n            {\n                ValidateOrigins(_corsPolicy.Origins);\n                _originsValidated = true;\n            }\n\n            return Task.FromResult(_corsPolicy);\n        }\n\n        private static void ValidateOrigins(IList<string> origins)\n        {\n            foreach (string origin in origins)\n            {\n                if (String.IsNullOrEmpty(origin))\n                {\n                    throw new InvalidOperationException(SRResources.OriginCannotBeNullOrEmpty);\n                }\n\n                if (origin.EndsWith(\"/\", StringComparison.Ordinal))\n                {\n                    throw new InvalidOperationException(\n                        String.Format(\n                            CultureInfo.CurrentCulture,\n                            SRResources.OriginCannotEndWithSlash,\n                            origin));\n                }\n\n                if (!Uri.IsWellFormedUriString(origin, UriKind.Absolute))\n                {\n                    throw new InvalidOperationException(\n                        String.Format(\n                            CultureInfo.CurrentCulture,\n                            SRResources.OriginNotWellFormed,\n                            origin));\n                }\n\n                Uri originUri = new Uri(origin);\n                if ((!String.IsNullOrEmpty(originUri.AbsolutePath) && !String.Equals(originUri.AbsolutePath, \"/\", StringComparison.Ordinal)) ||\n                    !String.IsNullOrEmpty(originUri.Query) ||\n                    !String.IsNullOrEmpty(originUri.Fragment))\n                {\n                    throw new InvalidOperationException(\n                        String.Format(\n                            CultureInfo.CurrentCulture,\n                            SRResources.OriginMustNotContainPathQueryOrFragment,\n                            origin));\n                }\n            }\n        }\n\n        private static void AddCommaSeparatedValuesToCollection(string commaSeparatedValues, IList<string> collection)\n        {\n            string[] values = commaSeparatedValues.Split(',');\n            for (int i = 0; i < values.Length; i++)\n            {\n                string value = values[i].Trim();\n                if (!String.IsNullOrEmpty(value))\n                {\n                    collection.Add(value);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.Cors/ICorsPolicyProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Cors;\n\nnamespace System.Web.Http.Cors\n{\n    /// <summary>\n    /// Provides an abstraction for getting the <see cref=\"CorsPolicy\"/>.\n    /// </summary>\n    public interface ICorsPolicyProvider\n    {\n        /// <summary>\n        /// Gets the <see cref=\"CorsPolicy\"/>.\n        /// </summary>\n        /// <param name=\"request\">The request.</param>\n        /// <param name=\"cancellationToken\">The token to monitor for cancellation requests.</param>\n        /// <returns>The <see cref=\"CorsPolicy\"/>.</returns>\n        Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken);\n    }\n}"
  },
  {
    "path": "src/System.Web.Http.Cors/ICorsPolicyProviderFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\n\nnamespace System.Web.Http.Cors\n{\n    /// <summary>\n    /// Provides an abstraction for getting the <see cref=\"ICorsPolicyProvider\"/>.\n    /// </summary>\n    public interface ICorsPolicyProviderFactory\n    {\n        /// <summary>\n        /// Gets the <see cref=\"ICorsPolicyProvider\"/> for the request.\n        /// </summary>\n        /// <param name=\"request\">The request.</param>\n        /// <returns>The <see cref=\"ICorsPolicyProvider\"/>.</returns>\n        ICorsPolicyProvider GetCorsPolicyProvider(HttpRequestMessage request);\n    }\n}"
  },
  {
    "path": "src/System.Web.Http.Cors/Properties/AssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\n\n[assembly: AssemblyTitle(\"System.Web.Http.Cors\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: InternalsVisibleTo(\"System.Web.Http.Cors.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA2210:AssembliesShouldHaveValidStrongNames\", Justification = \"This assembly is delay-signed.\")]\n[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"System.Web.Http\", Justification = \"More types exist in this namespace within other assemblies\")]\n[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"System.Web.Http.Cors.Tracing\", Justification = \"Namespace follows folder structure\")]"
  },
  {
    "path": "src/System.Web.Http.Cors/Properties/SRResources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.18213\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace System.Web.Http.Cors.Properties {\n    using System;\n    \n    \n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class SRResources {\n        \n        private static global::System.Resources.ResourceManager resourceMan;\n        \n        private static global::System.Globalization.CultureInfo resourceCulture;\n        \n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal SRResources() {\n        }\n        \n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"System.Web.Http.Cors.Properties.SRResources\", typeof(SRResources).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n        \n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &quot;Access-Control-Request-Method&quot; header value cannot be null or empty..\n        /// </summary>\n        internal static string AccessControlRequestMethodCannotBeNullOrEmpty {\n            get {\n                return ResourceManager.GetString(\"AccessControlRequestMethodCannotBeNullOrEmpty\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Value cannot be null or an empty string..\n        /// </summary>\n        internal static string ArgumentCannotBeNullOrEmpty {\n            get {\n                return ResourceManager.GetString(\"ArgumentCannotBeNullOrEmpty\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &quot;Access-Control-Request-Method&quot; header value &apos;{0}&apos; is invalid..\n        /// </summary>\n        internal static string InvalidAccessControlRequestMethod {\n            get {\n                return ResourceManager.GetString(\"InvalidAccessControlRequestMethod\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The request does not have an associated configuration object..\n        /// </summary>\n        internal static string NoConfiguration {\n            get {\n                return ResourceManager.GetString(\"NoConfiguration\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The specified policy origin cannot be null or empty..\n        /// </summary>\n        internal static string OriginCannotBeNullOrEmpty {\n            get {\n                return ResourceManager.GetString(\"OriginCannotBeNullOrEmpty\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The specified policy origin &apos;{0}&apos; is invalid. It cannot end with a forward slash..\n        /// </summary>\n        internal static string OriginCannotEndWithSlash {\n            get {\n                return ResourceManager.GetString(\"OriginCannotEndWithSlash\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The specified policy origin &apos;{0}&apos; is invalid. It must not contain a path, query, or fragment..\n        /// </summary>\n        internal static string OriginMustNotContainPathQueryOrFragment {\n            get {\n                return ResourceManager.GetString(\"OriginMustNotContainPathQueryOrFragment\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The specified policy origin &apos;{0}&apos; is invalid. It must be correctly formed with the scheme, the host, and optionally, the port..\n        /// </summary>\n        internal static string OriginNotWellFormed {\n            get {\n                return ResourceManager.GetString(\"OriginNotWellFormed\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to CorsRequestContext: &apos;{0}&apos;.\n        /// </summary>\n        internal static string TraceCorsRequestContext {\n            get {\n                return ResourceManager.GetString(\"TraceCorsRequestContext\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to CorsResult returned: &apos;{0}&apos;.\n        /// </summary>\n        internal static string TraceEndCorsResultReturned {\n            get {\n                return ResourceManager.GetString(\"TraceEndCorsResultReturned\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to No CorsResult returned..\n        /// </summary>\n        internal static string TraceEndNoCorsResultReturned {\n            get {\n                return ResourceManager.GetString(\"TraceEndNoCorsResultReturned\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to No CorsPolicyProvider selected.\n        /// </summary>\n        internal static string TraceEndNoPolicyProviderReturned {\n            get {\n                return ResourceManager.GetString(\"TraceEndNoPolicyProviderReturned\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to No CorsPolicy selected.\n        /// </summary>\n        internal static string TraceEndNoPolicyReturned {\n            get {\n                return ResourceManager.GetString(\"TraceEndNoPolicyReturned\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to CorsPolicyProvider selected: &apos;{0}&apos;.\n        /// </summary>\n        internal static string TraceEndPolicyProviderReturned {\n            get {\n                return ResourceManager.GetString(\"TraceEndPolicyProviderReturned\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to CorsPolicy selected: &apos;{0}&apos;.\n        /// </summary>\n        internal static string TraceEndPolicyReturned {\n            get {\n                return ResourceManager.GetString(\"TraceEndPolicyReturned\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.Cors/Properties/SRResources.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"AccessControlRequestMethodCannotBeNullOrEmpty\" xml:space=\"preserve\">\n    <value>The \"Access-Control-Request-Method\" header value cannot be null or empty.</value>\n  </data>\n  <data name=\"ArgumentCannotBeNullOrEmpty\" xml:space=\"preserve\">\n    <value>Value cannot be null or an empty string.</value>\n  </data>\n  <data name=\"InvalidAccessControlRequestMethod\" xml:space=\"preserve\">\n    <value>The \"Access-Control-Request-Method\" header value '{0}' is invalid.</value>\n  </data>\n  <data name=\"NoConfiguration\" xml:space=\"preserve\">\n    <value>The request does not have an associated configuration object.</value>\n  </data>\n  <data name=\"OriginCannotBeNullOrEmpty\" xml:space=\"preserve\">\n    <value>The specified policy origin cannot be null or empty.</value>\n  </data>\n  <data name=\"OriginCannotEndWithSlash\" xml:space=\"preserve\">\n    <value>The specified policy origin '{0}' is invalid. It cannot end with a forward slash.</value>\n  </data>\n  <data name=\"OriginMustNotContainPathQueryOrFragment\" xml:space=\"preserve\">\n    <value>The specified policy origin '{0}' is invalid. It must not contain a path, query, or fragment.</value>\n  </data>\n  <data name=\"OriginNotWellFormed\" xml:space=\"preserve\">\n    <value>The specified policy origin '{0}' is invalid. It must be correctly formed with the scheme, the host, and optionally, the port.</value>\n  </data>\n  <data name=\"TraceCorsRequestContext\" xml:space=\"preserve\">\n    <value>CorsRequestContext: '{0}'</value>\n  </data>\n  <data name=\"TraceEndCorsResultReturned\" xml:space=\"preserve\">\n    <value>CorsResult returned: '{0}'</value>\n  </data>\n  <data name=\"TraceEndNoCorsResultReturned\" xml:space=\"preserve\">\n    <value>No CorsResult returned.</value>\n  </data>\n  <data name=\"TraceEndNoPolicyProviderReturned\" xml:space=\"preserve\">\n    <value>No CorsPolicyProvider selected</value>\n  </data>\n  <data name=\"TraceEndNoPolicyReturned\" xml:space=\"preserve\">\n    <value>No CorsPolicy selected</value>\n  </data>\n  <data name=\"TraceEndPolicyProviderReturned\" xml:space=\"preserve\">\n    <value>CorsPolicyProvider selected: '{0}'</value>\n  </data>\n  <data name=\"TraceEndPolicyReturned\" xml:space=\"preserve\">\n    <value>CorsPolicy selected: '{0}'</value>\n  </data>\n</root>"
  },
  {
    "path": "src/System.Web.Http.Cors/System.Web.Http.Cors.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{25DEF6F6-7F99-4EB7-91ED-5181A346AFE1}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>System.Web.Http.Cors</RootNamespace>\n    <AssemblyName>System.Web.Http.Cors</AssemblyName>\n    <DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>\n    <RunCodeAnalysis>$(CodeAnalysis)</RunCodeAnalysis>\n    <CodeAnalysisRuleSet>..\\Strict.ruleset</CodeAnalysisRuleSet>\n    <DefineConstants>$(DefineConstants);ASPNETMVC</DefineConstants>\n  </PropertyGroup>\n  <PropertyGroup>\n    <SignAssembly>true</SignAssembly>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Net.Http\" />\n    <Reference Include=\"System.Xml.Linq\" />\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"System.Xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\CommonAssemblyInfo.cs\">\n      <Link>Properties\\CommonAssemblyInfo.cs</Link>\n    </Compile>\n    <Compile Include=\"AttributeBasedPolicyProviderFactory.cs\" />\n    <Compile Include=\"Tracing\\CorsEngineTracer.cs\" />\n    <Compile Include=\"Tracing\\TraceCategories.cs\" />\n    <Compile Include=\"Tracing\\CorsPolicyProviderFactoryTracer.cs\" />\n    <Compile Include=\"Tracing\\CorsPolicyProviderTracer.cs\" />\n    <Compile Include=\"DisableCorsAttribute.cs\" />\n    <Compile Include=\"EnableCorsAttribute.cs\" />\n    <Compile Include=\"ICorsPolicyProvider.cs\" />\n    <Compile Include=\"ICorsPolicyProviderFactory.cs\" />\n    <Compile Include=\"CorsHttpConfigurationExtensions.cs\" />\n    <Compile Include=\"CorsHttpRequestMessageExtensions.cs\" />\n    <Compile Include=\"CorsHttpResponseMessageExtensions.cs\" />\n    <Compile Include=\"CorsMessageHandler.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"Properties\\SRResources.Designer.cs\">\n      <DependentUpon>SRResources.resx</DependentUpon>\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n    </Compile>\n  </ItemGroup>\n  <ItemGroup>\n    <CodeAnalysisDictionary Include=\"..\\CodeAnalysisDictionary.xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\System.Net.Http.Formatting\\System.Net.Http.Formatting.csproj\">\n      <Project>{668e9021-ce84-49d9-98fb-df125a9fcdb0}</Project>\n      <Name>System.Net.Http.Formatting</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.Cors\\System.Web.Cors.csproj\">\n      <Project>{43c1b979-d593-4a32-bb3a-4316f1c66d66}</Project>\n      <Name>System.Web.Cors</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.Http\\System.Web.Http.csproj\">\n      <Project>{ddc1ce0c-486e-4e35-bb3b-eab61f8f9440}</Project>\n      <Name>System.Web.Http</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"Properties\\SRResources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>SRResources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n</Project>"
  },
  {
    "path": "src/System.Web.Http.Cors/Tracing/CorsEngineTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Net.Http;\nusing System.Web.Cors;\nusing System.Web.Http.Cors.Properties;\nusing System.Web.Http.Tracing;\n\nnamespace System.Web.Http.Cors.Tracing\n{\n    internal class CorsEngineTracer : ICorsEngine\n    {\n        private ICorsEngine _innerCorsEngine;\n        private ITraceWriter _traceWriter;\n        private const string MethodName = \"EvaluatePolicy\";\n\n        public CorsEngineTracer(ICorsEngine corsEngine, ITraceWriter traceWriter)\n        {\n            Contract.Assert(corsEngine != null);\n            Contract.Assert(traceWriter != null);\n\n            _innerCorsEngine = corsEngine;\n            _traceWriter = traceWriter;\n        }\n\n        public CorsResult EvaluatePolicy(CorsRequestContext requestContext, CorsPolicy policy)\n        {\n            CorsResult corsResult = null;\n            object request;\n            requestContext.Properties.TryGetValue(typeof(HttpRequestMessage).FullName, out request);\n\n            _traceWriter.TraceBeginEnd(\n                request as HttpRequestMessage,\n                TraceCategories.CorsCategory,\n                TraceLevel.Info,\n                _innerCorsEngine.GetType().Name,\n                MethodName,\n                beginTrace: null,\n                execute: () => { corsResult = _innerCorsEngine.EvaluatePolicy(requestContext, policy); },\n                endTrace: (tr) =>\n                {\n                    if (corsResult != null)\n                    {\n                        tr.Message = String.Format(CultureInfo.CurrentCulture, SRResources.TraceEndCorsResultReturned, corsResult);\n                    }\n                    else\n                    {\n                        tr.Message = SRResources.TraceEndNoCorsResultReturned;\n                    }\n                },\n                errorTrace: null);\n\n            return corsResult;\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http.Cors/Tracing/CorsPolicyProviderFactoryTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Net.Http;\nusing System.Web.Http.Cors.Properties;\nusing System.Web.Http.Tracing;\n\nnamespace System.Web.Http.Cors.Tracing\n{\n    internal class CorsPolicyProviderFactoryTracer : ICorsPolicyProviderFactory\n    {\n        private ICorsPolicyProviderFactory _innerPolicyProviderFactory;\n        private ITraceWriter _traceWriter;\n        private const string MethodName = \"GetCorsPolicyProvider\";\n\n        public CorsPolicyProviderFactoryTracer(ICorsPolicyProviderFactory innerPolicyProviderFactory, ITraceWriter traceWriter)\n        {\n            Contract.Assert(innerPolicyProviderFactory != null);\n            Contract.Assert(traceWriter != null);\n\n            _innerPolicyProviderFactory = innerPolicyProviderFactory;\n            _traceWriter = traceWriter;\n        }\n\n        public ICorsPolicyProvider GetCorsPolicyProvider(HttpRequestMessage request)\n        {\n            ICorsPolicyProvider policyProvider = null;\n\n            _traceWriter.TraceBeginEnd(\n                request,\n                TraceCategories.CorsCategory,\n                TraceLevel.Info,\n                _innerPolicyProviderFactory.GetType().Name,\n                MethodName,\n                beginTrace: (tr) =>\n                {\n                    tr.Message = String.Format(CultureInfo.CurrentCulture, SRResources.TraceCorsRequestContext, request.GetCorsRequestContext());\n                },\n                execute: () => { policyProvider = _innerPolicyProviderFactory.GetCorsPolicyProvider(request); },\n                endTrace: (tr) =>\n                {\n                    if (policyProvider != null)\n                    {\n                        tr.Message = String.Format(CultureInfo.CurrentCulture, SRResources.TraceEndPolicyProviderReturned, policyProvider);\n                    }\n                    else\n                    {\n                        tr.Message = SRResources.TraceEndNoPolicyProviderReturned;\n                    }\n                },\n                errorTrace: null);\n\n            if (policyProvider != null)\n            {\n                return new CorsPolicyProviderTracer(policyProvider, _traceWriter);\n            }\n\n            return null;\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http.Cors/Tracing/CorsPolicyProviderTracer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Cors;\nusing System.Web.Http.Cors.Properties;\nusing System.Web.Http.Tracing;\n\nnamespace System.Web.Http.Cors.Tracing\n{\n    internal class CorsPolicyProviderTracer : ICorsPolicyProvider\n    {\n        private ICorsPolicyProvider _innerPolicyProvider;\n        private ITraceWriter _traceWriter;\n        private const string MethodName = \"GetCorsPolicyAsync\";\n\n        public CorsPolicyProviderTracer(ICorsPolicyProvider innerPolicyProvider, ITraceWriter traceWriter)\n        {\n            Contract.Assert(innerPolicyProvider != null);\n            Contract.Assert(traceWriter != null);\n\n            _innerPolicyProvider = innerPolicyProvider;\n            _traceWriter = traceWriter;\n        }\n\n        public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n        {\n            return _traceWriter.TraceBeginEndAsync<CorsPolicy>(\n                request,\n                TraceCategories.CorsCategory,\n                TraceLevel.Info,\n                _innerPolicyProvider.GetType().Name,\n                MethodName,\n                beginTrace: (tr) =>\n                {\n                    tr.Message = String.Format(CultureInfo.CurrentCulture, SRResources.TraceCorsRequestContext, request.GetCorsRequestContext());\n                },\n                execute: () => _innerPolicyProvider.GetCorsPolicyAsync(request, cancellationToken),\n                endTrace: (tr, policy) =>\n                {\n                    if (policy != null)\n                    {\n                        tr.Message = String.Format(CultureInfo.CurrentCulture, SRResources.TraceEndPolicyReturned, policy);\n                    }\n                    else\n                    {\n                        tr.Message = SRResources.TraceEndNoPolicyReturned;\n                    }\n                },\n                errorTrace: null);\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http.Cors/Tracing/TraceCategories.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Cors.Tracing\n{\n    /// <summary>\n    /// Category names traced by the default CORS tracing implementation.\n    /// </summary>\n    public static class TraceCategories\n    {\n        /// <summary>\n        /// The trace category for CORS-related events.\n        /// </summary>\n        public static readonly string CorsCategory = \"System.Web.Http.Cors\";\n    }\n}"
  },
  {
    "path": "src/System.Web.Http.Owin/ExceptionHandling/DefaultExceptionHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Owin.Properties;\nusing System.Web.Http.Results;\n\nnamespace System.Web.Http.Owin.ExceptionHandling\n{\n    internal class DefaultExceptionHandler : IExceptionHandler\n    {\n        public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)\n        {\n            Handle(context);\n            return TaskHelpers.Completed();\n        }\n\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\",\n            Justification = \"We already shipped this code; avoiding even minor breaking changes in error handling.\")]\n        private static void Handle(ExceptionHandlerContext context)\n        {\n            if (context == null)\n            {\n                throw new ArgumentNullException(\"context\");\n            }\n\n            ExceptionContext exceptionContext = context.ExceptionContext;\n            Contract.Assert(exceptionContext != null);\n\n            HttpRequestMessage request = exceptionContext.Request;\n\n            if (request == null)\n            {\n                throw new ArgumentException(Error.Format(OwinResources.TypePropertyMustNotBeNull,\n                    typeof(ExceptionContext).Name, \"Request\"), \"context\");\n            }\n\n            context.Result = new ResponseMessageResult(request.CreateErrorResponse(HttpStatusCode.InternalServerError,\n                exceptionContext.Exception));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.Owin/ExceptionHandling/EmptyExceptionLogger.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.ExceptionHandling;\n\nnamespace System.Web.Http.Owin.ExceptionHandling\n{\n    internal class EmptyExceptionLogger : IExceptionLogger\n    {\n        public Task LogAsync(ExceptionLoggerContext context, CancellationToken cancellationToken)\n        {\n            return TaskHelpers.Completed();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.Owin/GlobalSuppressions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA2210:AssembliesShouldHaveValidStrongNames\", Justification = \"The assembly is delay signed\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"Owin\", Justification = \"More types exist in this namespace within other assemblies\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"System.Net.Http\", Justification = \"More types exist in this namespace within other assemblies\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"System.Web.Http\", Justification = \"More types exist in this namespace within other assemblies.\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"System.Web.Http.Owin\")]\n"
  },
  {
    "path": "src/System.Web.Http.Owin/HostAuthenticationAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Filters;\n\nnamespace System.Web.Http\n{\n    /// <summary>Represents an authentication attribute that authenticates via OWIN middleware.</summary>\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]\n    public sealed class HostAuthenticationAttribute : Attribute, IAuthenticationFilter\n    {\n        private readonly IAuthenticationFilter _innerFilter;\n        private readonly string _authenticationType;\n\n        /// <summary>Initializes a new instance of the <see cref=\"HostAuthenticationAttribute\"/> class.</summary>\n        /// <param name=\"authenticationType\">The authentication type of the OWIN middleware to use.</param>\n        public HostAuthenticationAttribute(string authenticationType)\n            : this(new HostAuthenticationFilter(authenticationType))\n        {\n            _authenticationType = authenticationType;\n        }\n\n        internal HostAuthenticationAttribute(IAuthenticationFilter innerFilter)\n        {\n            if (innerFilter == null)\n            {\n                throw new ArgumentNullException(\"innerFilter\");\n            }\n\n            _innerFilter = innerFilter;\n        }\n\n        /// <inheritdoc />\n        public bool AllowMultiple\n        {\n            get { return true; }\n        }\n\n        /// <summary>Gets the authentication type of the OWIN middleware to use.</summary>\n        public string AuthenticationType\n        {\n            get { return _authenticationType; }\n        }\n\n        internal IAuthenticationFilter InnerFilter\n        {\n            get\n            {\n                return _innerFilter;\n            }\n        }\n\n        /// <inheritdoc />\n        public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)\n        {\n            return _innerFilter.AuthenticateAsync(context, cancellationToken);\n        }\n\n        /// <inheritdoc />\n        public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)\n        {\n            return _innerFilter.ChallengeAsync(context, cancellationToken);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.Owin/HostAuthenticationFilter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Security.Claims;\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Owin.Properties;\nusing Microsoft.Owin;\nusing Microsoft.Owin.Security;\n\nnamespace System.Web.Http\n{\n    /// <summary>Represents an authentication filter that authenticates via OWIN middleware.</summary>\n    public class HostAuthenticationFilter : IAuthenticationFilter\n    {\n        private readonly string _authenticationType;\n\n        /// <summary>Initializes a new instance of the <see cref=\"HostAuthenticationFilter\"/> class.</summary>\n        /// <param name=\"authenticationType\">The authentication type of the OWIN middleware to use.</param>\n        public HostAuthenticationFilter(string authenticationType)\n        {\n            if (authenticationType == null)\n            {\n                throw new ArgumentNullException(\"authenticationType\");\n            }\n\n            _authenticationType = authenticationType;\n        }\n\n        /// <summary>Gets the authentication type of the OWIN middleware to use.</summary>\n        public string AuthenticationType\n        {\n            get { return _authenticationType; }\n        }\n\n        /// <inheritdoc />\n        public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)\n        {\n            if (context == null)\n            {\n                throw new ArgumentNullException(\"context\");\n            }\n\n            HttpRequestMessage request = context.Request;\n\n            if (request == null)\n            {\n                throw new InvalidOperationException(OwinResources.HttpAuthenticationContext_RequestMustNotBeNull);\n            }\n\n            IAuthenticationManager authenticationManager = GetAuthenticationManagerOrThrow(request);\n\n            cancellationToken.ThrowIfCancellationRequested();\n            AuthenticateResult result = await authenticationManager.AuthenticateAsync(_authenticationType);\n\n            if (result != null)\n            {\n                IIdentity identity = result.Identity;\n\n                if (identity != null)\n                {\n                    context.Principal = new ClaimsPrincipal(identity);\n                }\n            }\n        }\n\n        /// <inheritdoc />\n        public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)\n        {\n            if (context == null)\n            {\n                throw new ArgumentNullException(\"context\");\n            }\n\n            HttpRequestMessage request = context.Request;\n\n            if (request == null)\n            {\n                throw new InvalidOperationException(OwinResources.HttpAuthenticationChallengeContext_RequestMustNotBeNull);\n            }\n\n            IAuthenticationManager authenticationManager = GetAuthenticationManagerOrThrow(request);\n\n            // Control the challenges that OWIN middleware adds later.\n            authenticationManager.AuthenticationResponseChallenge = AddChallengeAuthenticationType(\n                authenticationManager.AuthenticationResponseChallenge, _authenticationType);\n\n            return TaskHelpers.Completed();\n        }\n\n        /// <inheritdoc />\n        public bool AllowMultiple\n        {\n            get { return true; }\n        }\n\n        private static AuthenticationResponseChallenge AddChallengeAuthenticationType(\n            AuthenticationResponseChallenge challenge, string authenticationType)\n        {\n            Contract.Assert(authenticationType != null);\n\n            List<string> authenticationTypes = new List<string>();\n            AuthenticationProperties properties;\n\n            if (challenge != null)\n            {\n                string[] currentAuthenticationTypes = challenge.AuthenticationTypes;\n\n                if (currentAuthenticationTypes != null)\n                {\n                    authenticationTypes.AddRange(currentAuthenticationTypes);\n                }\n\n                properties = challenge.Properties;\n            }\n            else\n            {\n                properties = new AuthenticationProperties();\n            }\n\n            authenticationTypes.Add(authenticationType);\n\n            return new AuthenticationResponseChallenge(authenticationTypes.ToArray(), properties);\n        }\n\n        private static IAuthenticationManager GetAuthenticationManagerOrThrow(HttpRequestMessage request)\n        {\n            Contract.Assert(request != null);\n\n            IAuthenticationManager authenticationManager = request.GetAuthenticationManager();\n\n            if (authenticationManager == null)\n            {\n                throw new InvalidOperationException(OwinResources.IAuthenticationManagerNotAvailable);\n            }\n\n            return authenticationManager;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.Owin/HttpMessageHandlerAdapter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.IO;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Headers;\nusing System.Runtime.ExceptionServices;\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.Owin.ExceptionHandling;\nusing System.Web.Http.Owin.Properties;\nusing Microsoft.Owin;\n\nnamespace System.Web.Http.Owin\n{\n    /// <summary>\n    /// Represents an OWIN component that submits requests to an <see cref=\"HttpMessageHandler\"/> when invoked.\n    /// </summary>\n    public class HttpMessageHandlerAdapter : OwinMiddleware, IDisposable\n    {\n        private readonly HttpMessageHandler _messageHandler;\n        private readonly HttpMessageInvoker _messageInvoker;\n        private readonly IHostBufferPolicySelector _bufferPolicySelector;\n        private readonly IExceptionLogger _exceptionLogger;\n        private readonly IExceptionHandler _exceptionHandler;\n        private readonly CancellationToken _appDisposing;\n\n        private bool _disposed;\n\n        /// <summary>Initializes a new instance of the <see cref=\"HttpMessageHandlerAdapter\"/> class.</summary>\n        /// <param name=\"next\">The next component in the pipeline.</param>\n        /// <param name=\"options\">The options to configure this adapter.</param>\n        public HttpMessageHandlerAdapter(OwinMiddleware next, HttpMessageHandlerOptions options)\n            : base(next)\n        {\n            if (options == null)\n            {\n                throw new ArgumentNullException(\"options\");\n            }\n\n            _messageHandler = options.MessageHandler;\n\n            if (_messageHandler == null)\n            {\n                throw new ArgumentException(Error.Format(OwinResources.TypePropertyMustNotBeNull,\n                    typeof(HttpMessageHandlerOptions).Name, \"MessageHandler\"), \"options\");\n            }\n\n            _messageInvoker = new HttpMessageInvoker(_messageHandler);\n            _bufferPolicySelector = options.BufferPolicySelector;\n\n            if (_bufferPolicySelector == null)\n            {\n                throw new ArgumentException(Error.Format(OwinResources.TypePropertyMustNotBeNull,\n                    typeof(HttpMessageHandlerOptions).Name, \"BufferPolicySelector\"), \"options\");\n            }\n\n            _exceptionLogger = options.ExceptionLogger;\n\n            if (_exceptionLogger == null)\n            {\n                throw new ArgumentException(Error.Format(OwinResources.TypePropertyMustNotBeNull,\n                    typeof(HttpMessageHandlerOptions).Name, \"ExceptionLogger\"), \"options\");\n            }\n\n            _exceptionHandler = options.ExceptionHandler;\n\n            if (_exceptionHandler == null)\n            {\n                throw new ArgumentException(Error.Format(OwinResources.TypePropertyMustNotBeNull,\n                    typeof(HttpMessageHandlerOptions).Name, \"ExceptionHandler\"), \"options\");\n            }\n\n            _appDisposing = options.AppDisposing;\n\n            if (_appDisposing.CanBeCanceled)\n            {\n                _appDisposing.Register(OnAppDisposing);\n            }\n        }\n\n        /// <summary>Initializes a new instance of the <see cref=\"HttpMessageHandlerAdapter\"/> class.</summary>\n        /// <param name=\"next\">The next component in the pipeline.</param>\n        /// <param name=\"messageHandler\">The <see cref=\"HttpMessageHandler\"/> to submit requests to.</param>\n        /// <param name=\"bufferPolicySelector\">\n        /// The <see cref=\"IHostBufferPolicySelector\"/> that determines whether or not to buffer requests and\n        /// responses.\n        /// </param>\n        /// <remarks>\n        /// This constructor is retained for backwards compatibility. The constructor taking\n        /// <see cref=\"HttpMessageHandlerOptions\"/> should be used instead.\n        /// </remarks>\n        [Obsolete(\"Use the HttpMessageHandlerAdapter(OwinMiddleware, HttpMessageHandlerOptions) constructor instead.\")]\n        public HttpMessageHandlerAdapter(OwinMiddleware next, HttpMessageHandler messageHandler,\n            IHostBufferPolicySelector bufferPolicySelector)\n            : this(next, CreateOptions(messageHandler, bufferPolicySelector))\n        {\n        }\n\n        /// <summary>Gets the <see cref=\"HttpMessageHandler\"/> to submit requests to.</summary>\n        public HttpMessageHandler MessageHandler\n        {\n            get { return _messageHandler; }\n        }\n\n        /// <summary>\n        /// Gets the <see cref=\"IHostBufferPolicySelector\"/> that determines whether or not to buffer requests and\n        /// responses.\n        /// </summary>\n        public IHostBufferPolicySelector BufferPolicySelector\n        {\n            get { return _bufferPolicySelector; }\n        }\n\n        /// <summary>Gets the <see cref=\"IExceptionLogger\"/> to use to log unhandled exceptions.</summary>\n        public IExceptionLogger ExceptionLogger\n        {\n            get { return _exceptionLogger; }\n        }\n\n        /// <summary>Gets the <see cref=\"IExceptionHandler\"/> to use to process unhandled exceptions.</summary>\n        public IExceptionHandler ExceptionHandler\n        {\n            get { return _exceptionHandler; }\n        }\n\n        /// <summary>Gets the <see cref=\"CancellationToken\"/> that triggers cleanup of this component.</summary>\n        public CancellationToken AppDisposing\n        {\n            get { return _appDisposing; }\n        }\n\n        /// <inheritdoc />\n        public override Task Invoke(IOwinContext context)\n        {\n            if (context == null)\n            {\n                throw new ArgumentNullException(\"context\");\n            }\n\n            IOwinRequest owinRequest = context.Request;\n            IOwinResponse owinResponse = context.Response;\n\n            if (owinRequest == null)\n            {\n                throw Error.InvalidOperation(OwinResources.OwinContext_NullRequest);\n            }\n            if (owinResponse == null)\n            {\n                throw Error.InvalidOperation(OwinResources.OwinContext_NullResponse);\n            }\n\n            return InvokeCore(context, owinRequest, owinResponse);\n        }\n\n        private async Task InvokeCore(IOwinContext context, IOwinRequest owinRequest, IOwinResponse owinResponse)\n        {\n            CancellationToken cancellationToken = owinRequest.CallCancelled;\n            HttpContent requestContent;\n\n            bool bufferInput = _bufferPolicySelector.UseBufferedInputStream(hostContext: context);\n\n            if (!bufferInput)\n            {\n                owinRequest.DisableBuffering();\n            }\n\n            if (!owinRequest.Body.CanSeek && bufferInput)\n            {\n                requestContent = await CreateBufferedRequestContentAsync(owinRequest, cancellationToken);\n            }\n            else\n            {\n                requestContent = CreateStreamedRequestContent(owinRequest);\n            }\n\n            HttpRequestMessage request = CreateRequestMessage(owinRequest, requestContent);\n            MapRequestProperties(request, context);\n\n            SetPrincipal(owinRequest.User);\n\n            HttpResponseMessage response = null;\n            bool callNext;\n\n            try\n            {\n                response = await _messageInvoker.SendAsync(request, cancellationToken);\n\n                // Handle null responses\n                if (response == null)\n                {\n                    throw Error.InvalidOperation(OwinResources.SendAsync_ReturnedNull);\n                }\n\n                // Handle soft 404s where no route matched - call the next component\n                if (IsSoftNotFound(request, response))\n                {\n                    callNext = true;\n                }\n                else\n                {\n                    callNext = false;\n\n                    // Compute Content-Length before calling UseBufferedOutputStream because the default implementation\n                    // accesses that header and we want to catch any exceptions calling TryComputeLength here.\n\n                    if (response.Content == null\n                        || await ComputeContentLengthAsync(request, response, owinResponse, cancellationToken))\n                    {\n                        bool bufferOutput = _bufferPolicySelector.UseBufferedOutputStream(response);\n\n                        if (!bufferOutput)\n                        {\n                            owinResponse.DisableBuffering();\n                        }\n                        else if (response.Content != null)\n                        {\n                            response = await BufferResponseContentAsync(request, response, cancellationToken);\n                        }\n\n                        if (await PrepareHeadersAsync(request, response, owinResponse, cancellationToken))\n                        {\n                            await SendResponseMessageAsync(request, response, owinResponse, cancellationToken);\n                        }\n                    }\n                }\n            }\n            finally\n            {\n                request.DisposeRequestResources();\n                request.Dispose();\n                if (response != null)\n                {\n                    response.Dispose();\n                }\n            }\n\n            // Call the next component if no route matched\n            if (callNext && Next != null)\n            {\n                await Next.Invoke(context);\n            }\n        }\n\n        private static HttpContent CreateStreamedRequestContent(IOwinRequest owinRequest)\n        {\n            // Note that we must NOT dispose owinRequest.Body in this case. Disposing it would close the input\n            // stream and prevent cascaded components from accessing it. The server MUST handle any necessary\n            // cleanup upon request completion. NonOwnedStream prevents StreamContent (or its callers including\n            // HttpRequestMessage) from calling Close or Dispose on owinRequest.Body.\n            return new StreamContent(new NonOwnedStream(owinRequest.Body));\n        }\n\n        private static async Task<HttpContent> CreateBufferedRequestContentAsync(IOwinRequest owinRequest,\n            CancellationToken cancellationToken)\n        {\n            // We need to replace the request body with a buffered stream so that other components can read the stream.\n            // For this stream to be useful, it must NOT be diposed along with the request. Streams created by\n            // StreamContent do get disposed along with the request, so use MemoryStream to buffer separately.\n            MemoryStream buffer;\n            int? contentLength = owinRequest.GetContentLength();\n\n            if (!contentLength.HasValue)\n            {\n                buffer = new MemoryStream();\n            }\n            else\n            {\n                buffer = new MemoryStream(Math.Min(4 * 1024, contentLength.Value));\n            }\n\n            cancellationToken.ThrowIfCancellationRequested();\n\n            using (StreamContent copier = new StreamContent(owinRequest.Body))\n            {\n                await copier.CopyToAsync(buffer);\n            }\n\n            // Provide the non-disposing, buffered stream to later OWIN components (set to the stream's beginning).\n            buffer.Position = 0;\n            owinRequest.Body = buffer;\n\n            // For MemoryStream, Length is guaranteed to be an int.\n            return new ByteArrayContent(buffer.GetBuffer(), 0, (int)buffer.Length);\n        }\n\n        private static HttpRequestMessage CreateRequestMessage(IOwinRequest owinRequest, HttpContent requestContent)\n        {\n            // Create the request\n            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(owinRequest.Method), owinRequest.Uri);\n\n            try\n            {\n                // Set the body\n                request.Content = requestContent;\n\n                // Copy the headers\n                foreach (KeyValuePair<string, string[]> header in owinRequest.Headers)\n                {\n                    if (!request.Headers.TryAddWithoutValidation(header.Key, header.Value))\n                    {\n                        bool success = requestContent.Headers.TryAddWithoutValidation(header.Key, header.Value);\n                        Contract.Assert(success,\n                            \"Every header can be added either to the request headers or to the content headers\");\n                    }\n                }\n            }\n            catch\n            {\n                request.Dispose();\n                throw;\n            }\n\n            return request;\n        }\n\n        private static void MapRequestProperties(HttpRequestMessage request, IOwinContext context)\n        {\n            // Set the OWIN context on the request\n            request.SetOwinContext(context);\n\n            // Set a request context on the request that lazily populates each property.\n            HttpRequestContext requestContext = new OwinHttpRequestContext(context, request);\n            request.SetRequestContext(requestContext);\n        }\n\n        private static void SetPrincipal(IPrincipal user)\n        {\n            if (user != null)\n            {\n                Thread.CurrentPrincipal = user;\n            }\n        }\n\n        private static bool IsSoftNotFound(HttpRequestMessage request, HttpResponseMessage response)\n        {\n            if (response.StatusCode == HttpStatusCode.NotFound)\n            {\n                bool routingFailure;\n                if (request.Properties.TryGetValue<bool>(HttpPropertyKeys.NoRouteMatched, out routingFailure)\n                    && routingFailure)\n                {\n                    return true;\n                }\n            }\n            return false;\n        }\n\n        private async Task<HttpResponseMessage> BufferResponseContentAsync(HttpRequestMessage request,\n            HttpResponseMessage response, CancellationToken cancellationToken)\n        {\n            ExceptionDispatchInfo exceptionInfo;\n\n            cancellationToken.ThrowIfCancellationRequested();\n\n            try\n            {\n                await response.Content.LoadIntoBufferAsync();\n                return response;\n            }\n            catch (OperationCanceledException)\n            {\n                // Propogate the canceled task without calling exception loggers or handlers.\n                throw;\n            }\n            catch (Exception exception)\n            {\n                exceptionInfo = ExceptionDispatchInfo.Capture(exception);\n            }\n\n            // If the content can't be buffered, create a buffered error response for the exception\n            // This code will commonly run when a formatter throws during the process of serialization\n\n            Debug.Assert(exceptionInfo.SourceException != null);\n\n            ExceptionContext exceptionContext = new ExceptionContext(exceptionInfo.SourceException,\n                OwinExceptionCatchBlocks.HttpMessageHandlerAdapterBufferContent, request, response);\n\n            await _exceptionLogger.LogAsync(exceptionContext, cancellationToken);\n            HttpResponseMessage errorResponse = await _exceptionHandler.HandleAsync(exceptionContext,\n                cancellationToken);\n\n            response.Dispose();\n\n            if (errorResponse == null)\n            {\n                exceptionInfo.Throw();\n                return null;\n            }\n\n            // We have an error response to try to buffer and send back.\n\n            response = errorResponse;\n            cancellationToken.ThrowIfCancellationRequested();\n\n            Exception errorException;\n\n            try\n            {\n                // Try to buffer the error response and send it back.\n                await response.Content.LoadIntoBufferAsync();\n                return response;\n            }\n            catch (OperationCanceledException)\n            {\n                // Propogate the canceled task without calling exception loggers.\n                throw;\n            }\n            catch (Exception exception)\n            {\n                errorException = exception;\n            }\n\n            // We tried to send back an error response with content, but we couldn't. It's an edge case; the best we\n            // can do is to log that exception and send back an empty 500.\n\n            ExceptionContext errorExceptionContext = new ExceptionContext(errorException,\n                OwinExceptionCatchBlocks.HttpMessageHandlerAdapterBufferError, request, response);\n            await _exceptionLogger.LogAsync(errorExceptionContext, cancellationToken);\n\n            response.Dispose();\n            return request.CreateResponse(HttpStatusCode.InternalServerError);\n        }\n\n        // Prepares Content-Length and Transfer-Encoding headers.\n        private Task<bool> PrepareHeadersAsync(HttpRequestMessage request, HttpResponseMessage response,\n            IOwinResponse owinResponse, CancellationToken cancellationToken)\n        {\n            Contract.Assert(response != null);\n            HttpResponseHeaders responseHeaders = response.Headers;\n            Contract.Assert(responseHeaders != null);\n            HttpContent content = response.Content;\n            bool isTransferEncodingChunked = responseHeaders.TransferEncodingChunked == true;\n            HttpHeaderValueCollection<TransferCodingHeaderValue> transferEncoding = responseHeaders.TransferEncoding;\n\n            if (content != null)\n            {\n                HttpContentHeaders contentHeaders = content.Headers;\n                Contract.Assert(contentHeaders != null);\n\n                if (isTransferEncodingChunked)\n                {\n                    // According to section 4.4 of the HTTP 1.1 spec, HTTP responses that use chunked transfer\n                    // encoding must not have a content length set. Chunked should take precedence over content\n                    // length in this case because chunked is always set explicitly by users while the Content-Length\n                    // header can be added implicitly by System.Net.Http.\n                    contentHeaders.ContentLength = null;\n                }\n                else\n                {\n                    // Copy the response content headers only after ensuring they are complete.\n                    // We ask for Content-Length first because HttpContent lazily computes this header and only\n                    // afterwards writes the value into the content headers.\n                    return ComputeContentLengthAsync(request, response, owinResponse, cancellationToken);\n                }\n            }\n\n            // Ignore the Transfer-Encoding header if it is just \"chunked\"; the host will likely provide it when no\n            // Content-Length is present (and if the host does not, there's not much better this code could do to\n            // transmit the current response, since HttpContent is assumed to be unframed; in that case, silently drop\n            // the Transfer-Encoding: chunked header).\n            // HttpClient sets this header when it receives chunked content, but HttpContent does not include the\n            // frames. The OWIN contract is to set this header only when writing chunked frames to the stream.\n            // A Web API caller who desires custom framing would need to do a different Transfer-Encoding (such as\n            // \"identity, chunked\").\n            if (isTransferEncodingChunked && transferEncoding.Count == 1)\n            {\n                transferEncoding.Clear();\n            }\n\n            return Task.FromResult(true);\n        }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1804:RemoveUnusedLocals\", MessageId = \"unused\",\n            Justification = \"unused variable necessary to call getter\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\",\n            Justification = \"Exception is turned into an error response.\")]\n        private Task<bool> ComputeContentLengthAsync(HttpRequestMessage request, HttpResponseMessage response,\n            IOwinResponse owinResponse, CancellationToken cancellationToken)\n        {\n            Contract.Assert(response != null);\n            HttpResponseHeaders responseHeaders = response.Headers;\n            Contract.Assert(responseHeaders != null);\n            HttpContent content = response.Content;\n            Contract.Assert(content != null);\n            HttpContentHeaders contentHeaders = content.Headers;\n            Contract.Assert(contentHeaders != null);\n\n            Exception exception;\n\n            try\n            {\n                var unused = contentHeaders.ContentLength;\n\n                return Task.FromResult(true);\n            }\n            catch (Exception ex)\n            {\n                exception = ex;\n            }\n\n            return HandleTryComputeLengthExceptionAsync(exception, request, response, owinResponse, cancellationToken);\n        }\n\n        private async Task<bool> HandleTryComputeLengthExceptionAsync(Exception exception, HttpRequestMessage request,\n            HttpResponseMessage response, IOwinResponse owinResponse, CancellationToken cancellationToken)\n        {\n            Contract.Assert(owinResponse != null);\n\n            ExceptionContext exceptionContext = new ExceptionContext(exception,\n                OwinExceptionCatchBlocks.HttpMessageHandlerAdapterComputeContentLength, request, response);\n            await _exceptionLogger.LogAsync(exceptionContext, cancellationToken);\n\n            // Send back an empty error response if TryComputeLength throws.\n            owinResponse.StatusCode = (int)HttpStatusCode.InternalServerError;\n            SetHeadersForEmptyResponse(owinResponse.Headers);\n            return false;\n        }\n\n        private Task SendResponseMessageAsync(HttpRequestMessage request, HttpResponseMessage response,\n            IOwinResponse owinResponse, CancellationToken cancellationToken)\n        {\n            owinResponse.StatusCode = (int)response.StatusCode;\n            owinResponse.ReasonPhrase = response.ReasonPhrase;\n\n            // Copy non-content headers\n            IDictionary<string, string[]> responseHeaders = owinResponse.Headers;\n            foreach (KeyValuePair<string, IEnumerable<string>> header in response.Headers)\n            {\n                responseHeaders[header.Key] = header.Value.AsArray();\n            }\n\n            HttpContent responseContent = response.Content;\n            if (responseContent == null)\n            {\n                SetHeadersForEmptyResponse(responseHeaders);\n                return TaskHelpers.Completed();\n            }\n            else\n            {\n                // Copy content headers\n                foreach (KeyValuePair<string, IEnumerable<string>> contentHeader in responseContent.Headers)\n                {\n                    responseHeaders[contentHeader.Key] = contentHeader.Value.AsArray();\n                }\n\n                // Copy body\n                return SendResponseContentAsync(request, response, owinResponse, cancellationToken);\n            }\n        }\n\n        private static void SetHeadersForEmptyResponse(IDictionary<string, string[]> headers)\n        {\n            // Set the content-length to 0 to prevent the server from sending back the response chunked\n            headers[\"Content-Length\"] = new string[] { \"0\" };\n        }\n\n        private async Task SendResponseContentAsync(HttpRequestMessage request, HttpResponseMessage response,\n            IOwinResponse owinResponse, CancellationToken cancellationToken)\n        {\n            Contract.Assert(response != null);\n            Contract.Assert(response.Content != null);\n\n            Exception exception;\n            cancellationToken.ThrowIfCancellationRequested();\n\n            try\n            {\n                await response.Content.CopyToAsync(owinResponse.Body);\n                return;\n            }\n            catch (OperationCanceledException)\n            {\n                // Propogate the canceled task without calling exception loggers;\n                throw;\n            }\n            catch (Exception ex)\n            {\n                exception = ex;\n            }\n\n            // We're streaming content, so we can only call loggers, not handlers, as we've already (possibly) send the\n            // status code and headers across the wire. Log the exception, but then just abort.\n            ExceptionContext exceptionContext = new ExceptionContext(exception,\n                OwinExceptionCatchBlocks.HttpMessageHandlerAdapterStreamContent, request, response);\n            await _exceptionLogger.LogAsync(exceptionContext, cancellationToken);\n            await AbortResponseAsync();\n        }\n\n        private static Task AbortResponseAsync()\n        {\n            // OWIN doesn't yet support an explicit Abort event. Returning a canceled task is the best contract at the\n            // moment.\n            return TaskHelpers.Canceled();\n        }\n\n        // Provides HttpMessageHandlerOptions for callers using the old constructor.\n        private static HttpMessageHandlerOptions CreateOptions(HttpMessageHandler messageHandler,\n            IHostBufferPolicySelector bufferPolicySelector)\n        {\n            if (messageHandler == null)\n            {\n                throw new ArgumentNullException(\"messageHandler\");\n            }\n\n            if (bufferPolicySelector == null)\n            {\n                throw new ArgumentNullException(\"bufferPolicySelector\");\n            }\n\n            // Callers using the old constructor get the default exception handler, no exception logging support, and no\n            // app cleanup support.\n\n            return new HttpMessageHandlerOptions\n            {\n                MessageHandler = messageHandler,\n                BufferPolicySelector = bufferPolicySelector,\n                ExceptionLogger = new EmptyExceptionLogger(),\n                ExceptionHandler = new DefaultExceptionHandler(),\n                AppDisposing = CancellationToken.None\n            };\n        }\n\n        /// <summary>\n        /// Releases unmanaged and optionally managed resources.\n        /// </summary>\n        /// <param name=\"disposing\">\n        /// <see langword=\"true\"/> to release both managed and unmanaged resources; <see langword=\"false\"/> to release\n        /// only unmanaged resources.\n        /// </param>\n        /// <remarks>\n        /// This class implements <see cref=\"IDisposable\"/> for legacy reasons. New callers should instead provide a\n        /// cancellation token via <see cref=\"AppDisposing\"/> using the constructor that takes\n        /// <see cref=\"HttpMessageHandlerOptions\"/>.\n        /// </remarks>\n        protected virtual void Dispose(bool disposing)\n        {\n            if (disposing)\n            {\n                OnAppDisposing();\n            }\n        }\n\n        /// <inheritdoc />\n        /// <remarks>\n        /// This class implements <see cref=\"IDisposable\"/> for legacy reasons. New callers should instead provide a\n        /// cancellation token via <see cref=\"AppDisposing\"/> using the constructor that takes\n        /// <see cref=\"HttpMessageHandlerOptions\"/>.\n        /// </remarks>\n        public void Dispose()\n        {\n            Dispose(true);\n            GC.SuppressFinalize(this);\n        }\n\n        private void OnAppDisposing()\n        {\n            if (!_disposed)\n            {\n                _messageInvoker.Dispose();\n                _disposed = true;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.Owin/HttpMessageHandlerOptions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Hosting;\n\nnamespace System.Web.Http.Owin\n{\n    /// <summary>Represents the options for configuring an <see cref=\"HttpMessageHandlerAdapter\"/>.</summary>\n    public class HttpMessageHandlerOptions\n    {\n        /// <summary>\n        /// Gets or sets the <see cref=\"HttpMessageHandler\"/> to submit requests to.\n        /// </summary>\n        public HttpMessageHandler MessageHandler { get; set; }\n\n        /// <summary>\n        /// Gets or sets the <see cref=\"IHostBufferPolicySelector\"/> that determines whether or not to buffer requests\n        /// and responses.\n        /// </summary>\n        public IHostBufferPolicySelector BufferPolicySelector { get; set; }\n\n        /// <summary>Gets or sets the <see cref=\"IExceptionLogger\"/> to use to log unhandled exceptions.</summary>\n        public IExceptionLogger ExceptionLogger { get; set; }\n\n        /// <summary>Gets or sets the <see cref=\"IExceptionHandler\"/> to use to process unhandled exceptions.</summary>\n        public IExceptionHandler ExceptionHandler { get; set; }\n\n        /// <summary>\n        /// Gets or sets the <see cref=\"CancellationToken\"/> that triggers cleanup of the\n        /// <see cref=\"HttpMessageHandlerAdapter\"/>.\n        /// </summary>\n        public CancellationToken AppDisposing { get; set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.Owin/OwinBufferPolicySelector.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Http.Hosting;\n\nnamespace System.Web.Http.Owin\n{\n    /// <summary>\n    /// Provides the default implementation of <see cref=\"IHostBufferPolicySelector\"/> used by the OWIN Web API adapter.\n    /// </summary>\n    public class OwinBufferPolicySelector : IHostBufferPolicySelector\n    {\n        /// <inheritdoc />\n        public bool UseBufferedInputStream(object hostContext)\n        {\n            return false;\n        }\n\n        /// <inheritdoc />\n        public bool UseBufferedOutputStream(HttpResponseMessage response)\n        {\n            if (response == null)\n            {\n                throw Error.ArgumentNull(\"response\");\n            }\n\n            HttpContent content = response.Content;\n            if (content == null)\n            {\n                return false;\n            }\n\n            // Any HttpContent that knows its length is presumably already buffered internally.\n            long? contentLength = content.Headers.ContentLength;\n            if (contentLength.HasValue && contentLength.Value >= 0)\n            {\n                return false;\n            }\n\n            // If the response is meant to use chunked transfer encoding, don't buffer.\n            bool? transferEncodingChunked = response.Headers.TransferEncodingChunked;\n            if (transferEncodingChunked.HasValue && transferEncodingChunked.Value)\n            {\n                return false;\n            }\n\n            // Content length is null or -1 (meaning not known).  \n            // Buffer any HttpContent except StreamContent and PushStreamContent\n            if (content is StreamContent || content is PushStreamContent)\n            {\n                return false;\n            }\n\n            return true;\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http.Owin/OwinConstants.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Owin\n{\n    /// <summary>\n    /// Standard keys and values for use within the OWIN interfaces.\n    /// </summary>\n    internal static class OwinConstants\n    {\n        // Request keys\n        public const string ClientCertifiateKey = \"ssl.ClientCertificate\";\n        public const string IsLocalKey = \"server.IsLocal\";\n    }\n}"
  },
  {
    "path": "src/System.Web.Http.Owin/OwinExceptionCatchBlocks.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Hosting;\n\nnamespace System.Web.Http.Owin\n{\n    /// <summary>Provides the catch blocks used within this assembly.</summary>\n    public static class OwinExceptionCatchBlocks\n    {\n        private static readonly ExceptionContextCatchBlock _httpMessageHandlerAdapterBufferContent =\n            new ExceptionContextCatchBlock(typeof(HttpMessageHandlerAdapter).Name + \".BufferContent\",\n                isTopLevel: true, callsHandler: true);\n        private static readonly ExceptionContextCatchBlock _httpMessageHandlerAdapterBufferError =\n            new ExceptionContextCatchBlock(typeof(HttpMessageHandlerAdapter).Name + \".BufferError\", isTopLevel: true,\n                callsHandler: false);\n        private static readonly ExceptionContextCatchBlock _httpMessageHandlerAdapterComputeContentLength =\n            new ExceptionContextCatchBlock(typeof(HttpMessageHandlerAdapter).Name + \".ComputeContentLength\",\n                isTopLevel: true, callsHandler: false);\n        private static readonly ExceptionContextCatchBlock _httpMessageHandlerAdapterStreamContent =\n            new ExceptionContextCatchBlock(typeof(HttpMessageHandlerAdapter).Name + \".StreamContent\",\n                isTopLevel: true, callsHandler: false);\n\n        /// <summary>Gets the catch block in <see cref=\"HttpMessageHandlerAdapter\"/>.BufferContent.</summary>\n        /// <remarks>\n        /// This catch block handles exceptions when writing the <see cref=\"HttpContent\"/> under an\n        /// <see cref=\"IHostBufferPolicySelector\"/> that buffers.\n        /// </remarks>\n        public static ExceptionContextCatchBlock HttpMessageHandlerAdapterBufferContent\n        {\n            get\n            {\n                return _httpMessageHandlerAdapterBufferContent;\n            }\n        }\n\n        /// <summary>Gets the catch block in <see cref=\"HttpMessageHandlerAdapter\"/>.BufferError.</summary>\n        /// <remarks>\n        /// This catch block handles exceptions when writing the <see cref=\"HttpContent\"/> of the error response itself\n        /// (after <see cref=\"HttpMessageHandlerAdapterBufferContent\"/>).\n        /// </remarks>\n        public static ExceptionContextCatchBlock HttpMessageHandlerAdapterBufferError\n        {\n            get\n            {\n                return _httpMessageHandlerAdapterBufferError;\n            }\n        }\n\n        /// <summary>Gets the catch block in <see cref=\"HttpMessageHandlerAdapter\"/>.ComputeContentLength.</summary>\n        /// <remarks>\n        /// This catch block handles exceptions when calling <see cref=\"HttpContent.TryComputeLength\"/>.\n        /// </remarks>\n        public static ExceptionContextCatchBlock HttpMessageHandlerAdapterComputeContentLength\n        {\n            get\n            {\n                return _httpMessageHandlerAdapterComputeContentLength;\n            }\n        }\n\n        /// <summary>Gets the catch block in <see cref=\"HttpMessageHandlerAdapter\"/>.StreamContent.</summary>\n        /// <remarks>\n        /// This catch block handles exceptions when writing the <see cref=\"HttpContent\"/> under an\n        /// <see cref=\"IHostBufferPolicySelector\"/> that does not buffer.\n        /// </remarks>\n        public static ExceptionContextCatchBlock HttpMessageHandlerAdapterStreamContent\n        {\n            get\n            {\n                return _httpMessageHandlerAdapterStreamContent;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.Owin/OwinHttpConfigurationExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Owin;\n\nnamespace System.Web.Http\n{\n    /// <summary>Provides extension methods for the <see cref=\"HttpConfiguration\"/> class.</summary>\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class OwinHttpConfigurationExtensions\n    {\n        /// <summary>Enables suppression of the host's default authentication.</summary>\n        /// <param name=\"configuration\">The server configuration.</param>\n        /// <remarks>\n        /// When the host's default authentication is suppressed, the current principal is set to anonymous upon\n        /// entering the <see cref=\"HttpServer\"/>'s first message handler. As a result, any default authentication\n        /// performed by the host is ignored. The remaining pipeline within the <see cref=\"HttpServer\"/>, including\n        /// <see cref=\"IAuthenticationFilter\"/>s, is then the exclusive authority for authentication.\n        /// </remarks>\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\",\n            Justification = \"Message handler should be disposed with parent configuration.\")]\n        public static void SuppressDefaultHostAuthentication(this HttpConfiguration configuration)\n        {\n            if (configuration == null)\n            {\n                throw new ArgumentNullException(\"configuration\");\n            }\n\n            Contract.Assert(configuration.MessageHandlers != null);\n            configuration.MessageHandlers.Insert(0, new PassiveAuthenticationMessageHandler());\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.Owin/OwinHttpRequestContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Security.Cryptography.X509Certificates;\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Routing;\nusing Microsoft.Owin;\n\nnamespace System.Web.Http.Owin\n{\n    internal class OwinHttpRequestContext : HttpRequestContext\n    {\n        private readonly IOwinContext _context;\n        private readonly HttpRequestMessage _request;\n\n        private X509Certificate2 _clientCertificate;\n        private bool _clientCertificateSet;\n\n        private bool _includeErrorDetail;\n        private bool _includeErrorDetailSet;\n\n        private bool _isLocal;\n        private bool _isLocalSet;\n\n        private UrlHelper _url;\n        private bool _urlSet;\n\n        private string _virtualPathRoot;\n        private bool _virtualPathRootSet;\n\n        public OwinHttpRequestContext(IOwinContext context, HttpRequestMessage request)\n        {\n            Contract.Assert(context != null);\n            Contract.Assert(context.Request != null);\n            Contract.Assert(request != null);\n            _context = context;\n            _request = request;\n        }\n\n        public IOwinContext Context\n        {\n            get { return _context; }\n        }\n\n        public HttpRequestMessage Request\n        {\n            get { return _request; }\n        }\n\n        //// Configuration and RouteData are not overridden; these values are provided by later points in the\n        ////  pipeline (HttpServer and HttpRoutingDispatcher)\n\n        public override X509Certificate2 ClientCertificate\n        {\n            get\n            {\n                if (!_clientCertificateSet)\n                {\n                    _clientCertificate = _context.Get<X509Certificate2>(OwinConstants.ClientCertifiateKey);\n                    _clientCertificateSet = true;\n                }\n\n                return _clientCertificate;\n            }\n            set\n            {\n                _clientCertificate = value;\n                _clientCertificateSet = true;\n            }\n        }\n\n        public override bool IncludeErrorDetail\n        {\n            get\n            {\n                if (!_includeErrorDetailSet)\n                {\n                    HttpConfiguration configuration = Configuration;\n                    IncludeErrorDetailPolicy includeErrorDetailPolicy;\n\n                    if (configuration != null)\n                    {\n                        includeErrorDetailPolicy = configuration.IncludeErrorDetailPolicy;\n                    }\n                    else\n                    {\n                        includeErrorDetailPolicy = IncludeErrorDetailPolicy.Default;\n                    }\n\n                    bool value;\n\n                    switch (includeErrorDetailPolicy)\n                    {\n                        case IncludeErrorDetailPolicy.Default:\n                        case IncludeErrorDetailPolicy.LocalOnly:\n                            value = IsLocal;\n                            break;\n\n                        case IncludeErrorDetailPolicy.Always:\n                            value = true;\n                            break;\n\n                        case IncludeErrorDetailPolicy.Never:\n                        default:\n                            value = false;\n                            break;\n                    }\n\n                    _includeErrorDetail = value;\n                    _includeErrorDetailSet = true;\n                }\n\n                return _includeErrorDetail;\n            }\n            set\n            {\n                _includeErrorDetail = value;\n                _includeErrorDetailSet = true;\n            }\n        }\n\n        public override bool IsLocal\n        {\n            get\n            {\n                if (!_isLocalSet)\n                {\n                    _isLocal = _context.Get<bool>(OwinConstants.IsLocalKey);\n                    _isLocalSet = true;\n                }\n\n                return _isLocal;\n            }\n            set\n            {\n                _isLocal = value;\n                _isLocalSet = true;\n            }\n        }\n\n        public override IPrincipal Principal\n        {\n            get\n            {\n                return _context.Request.User;\n            }\n            set\n            {\n                _context.Request.User = value;\n                Thread.CurrentPrincipal = value;\n            }\n        }\n\n        public override UrlHelper Url\n        {\n            get\n            {\n                if (!_urlSet)\n                {\n                    _url = new UrlHelper(_request);\n                    _urlSet = true;\n                }\n\n                return _url;\n            }\n            set\n            {\n                _url = value;\n                _urlSet = true;\n            }\n        }\n\n        public override string VirtualPathRoot\n        {\n            get\n            {\n                if (!_virtualPathRootSet)\n                {\n                    // Set the virtual path root for link resolution and link generation to work\n                    // OWIN spec requires request path base to be either the empty string or start with \"/\"\n                    string requestPathBase = _context.Request.PathBase.Value;\n                    _virtualPathRoot = String.IsNullOrEmpty(requestPathBase) ? \"/\" : requestPathBase;\n                    _virtualPathRootSet = true;\n                }\n\n                return _virtualPathRoot;\n            }\n            set\n            {\n                _virtualPathRoot = value;\n                _virtualPathRootSet = true;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.Owin/OwinHttpRequestMessageExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing Microsoft.Owin;\nusing Microsoft.Owin.Security;\n\nnamespace System.Net.Http\n{\n    /// <summary>\n    /// Provides extension methods for the <see cref=\"HttpRequestMessage\"/> class.\n    /// </summary>\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class OwinHttpRequestMessageExtensions\n    {\n        private const string OwinEnvironmentKey = \"MS_OwinEnvironment\";\n        private const string OwinContextKey = \"MS_OwinContext\";\n\n        /// <summary>Gets the OWIN context for the specified request.</summary>\n        /// <param name=\"request\">The HTTP request message.</param>\n        /// <returns>\n        /// The OWIN environment for the specified context, if available; otherwise <see langword=\"null\"/>.\n        /// </returns>\n        public static IOwinContext GetOwinContext(this HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw new ArgumentNullException(\"request\");\n            }\n\n            IOwinContext context;\n            if (!request.Properties.TryGetValue<IOwinContext>(OwinContextKey, out context))\n            {\n                // If the OWIN context is not available, try to create by upgrading an OWIN environment property\n                // instead.\n                IDictionary<string, object> environment;\n                if (request.Properties.TryGetValue<IDictionary<string, object>>(OwinEnvironmentKey, out environment))\n                {\n                    context = new OwinContext(environment);\n                    SetOwinContext(request, context);\n                    request.Properties.Remove(OwinEnvironmentKey);\n                }\n            }\n            return context;\n        }\n\n        /// <summary>Sets the OWIN context for the specified request.</summary>\n        /// <param name=\"request\">The HTTP request message.</param>\n        /// <param name=\"context\">The OWIN context to set.</param>\n        public static void SetOwinContext(this HttpRequestMessage request, IOwinContext context)\n        {\n            if (request == null)\n            {\n                throw new ArgumentNullException(\"request\");\n            }\n\n            if (context == null)\n            {\n                throw new ArgumentNullException(\"context\");\n            }\n\n            request.Properties[OwinContextKey] = context;\n            // Make sure only one of the two properties exists (single source of truth).\n            request.Properties.Remove(OwinEnvironmentKey);\n        }\n\n        /// <summary>Gets the OWIN environment for the specified request.</summary>\n        /// <param name=\"request\">The HTTP request message.</param>\n        /// <returns>\n        /// The OWIN environment for the specified request, if available; otherwise <see langword=\"null\"/>.\n        /// </returns>\n        public static IDictionary<string, object> GetOwinEnvironment(this HttpRequestMessage request)\n        {\n            IOwinContext context = GetOwinContext(request);\n\n            if (context == null)\n            {\n                return null;\n            }\n\n            return context.Environment;\n        }\n\n        /// <summary>Sets the OWIN environment for the specified request.</summary>\n        /// <param name=\"request\">The HTTP request message.</param>\n        /// <param name=\"environment\">The OWIN environment to set.</param>\n        public static void SetOwinEnvironment(this HttpRequestMessage request, IDictionary<string, object> environment)\n        {\n            SetOwinContext(request, new OwinContext(environment));\n        }\n\n        internal static IAuthenticationManager GetAuthenticationManager(this HttpRequestMessage request)\n        {\n            IOwinContext context = GetOwinContext(request);\n\n            if (context == null)\n            {\n                return null;\n            }\n\n            return context.Authentication;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.Owin/OwinRequestExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing Microsoft.Owin;\n\nnamespace System.Web.Http.Owin\n{\n    internal static class OwinRequestExtensions\n    {\n        private const string ContentLengthHeaderName = \"Content-Length\";\n        private const string DisableRequestBufferingKey = \"server.DisableRequestBuffering\";\n\n        public static void DisableBuffering(this IOwinRequest request)\n        {\n            if (request == null)\n            {\n                throw new ArgumentNullException(\"request\");\n            }\n\n            IDictionary<string, object> environment = request.Environment;\n\n            if (environment == null)\n            {\n                return;\n            }\n\n            Action action;\n\n            if (!environment.TryGetValue(DisableRequestBufferingKey, out action))\n            {\n                return;\n            }\n\n            Contract.Assert(action != null);\n            action.Invoke();\n        }\n\n        public static int? GetContentLength(this IOwinRequest request)\n        {\n            Contract.Assert(request != null);\n\n            IHeaderDictionary headers = request.Headers;\n\n            if (headers == null)\n            {\n                return null;\n            }\n\n            string[] values;\n\n            if (!headers.TryGetValue(ContentLengthHeaderName, out values))\n            {\n                return null;\n            }\n\n            if (values == null || values.Length != 1)\n            {\n                return null;\n            }\n\n            string value = values[0];\n\n            if (value == null)\n            {\n                return null;\n            }\n\n            int parsed;\n\n            if (!Int32.TryParse(value, out parsed))\n            {\n                return null;\n            }\n\n            if (parsed < 0)\n            {\n                return null;\n            }\n\n            return parsed;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.Owin/OwinResponseExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing Microsoft.Owin;\n\nnamespace System.Web.Http.Owin\n{\n    internal static class OwinResponseExtensions\n    {\n        private const string DisableResponseBufferingKey = \"server.DisableResponseBuffering\";\n\n        public static void DisableBuffering(this IOwinResponse response)\n        {\n            if (response == null)\n            {\n                throw new ArgumentNullException(\"response\");\n            }\n\n            IDictionary<string, object> environment = response.Environment;\n\n            if (environment == null)\n            {\n                return;\n            }\n\n            Action action;\n\n            if (!environment.TryGetValue(DisableResponseBufferingKey, out action))\n            {\n                return;\n            }\n\n            Contract.Assert(action != null);\n            action.Invoke();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.Owin/PassiveAuthenticationMessageHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Security.Claims;\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Owin.Properties;\nusing Microsoft.Owin.Security;\n\nnamespace System.Web.Http.Owin\n{\n    /// <summary>Represents a message handler that treats all OWIN authentication middleware as passive.</summary>\n    /// <remarks>\n    /// This message handler sets the current principal to anonymous upon entry and disables the default OWIN\n    /// authentication middleware challenges. As a result, any default authentication performed by the host is ignored.\n    /// The subsequent pipeline, including <see cref=\"IAuthenticationFilter\"/>s, is then the exclusive authority for\n    /// authentication.\n    /// </remarks>\n    public class PassiveAuthenticationMessageHandler : DelegatingHandler\n    {\n        private static readonly Lazy<IPrincipal> _anonymousPrincipal = new Lazy<IPrincipal>(\n            () => new ClaimsPrincipal(new ClaimsIdentity()), isThreadSafe: true);\n\n        /// <inheritdoc />\n        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,\n            CancellationToken cancellationToken)\n        {\n            if (request == null)\n            {\n                throw new ArgumentNullException(\"request\");\n            }\n\n            HttpResponseMessage response;\n            var previousPrincipal = SetCurrentPrincipal(request, _anonymousPrincipal.Value);\n            try\n            {\n                response = await base.SendAsync(request, cancellationToken);\n            }\n            finally\n            {\n                SetCurrentPrincipal(request, previousPrincipal);\n            }\n\n            SuppressDefaultAuthenticationChallenges(request);\n\n            return response;\n        }\n\n        private static IPrincipal SetCurrentPrincipal(HttpRequestMessage request, IPrincipal principal)\n        {\n            Contract.Assert(request != null);\n\n            HttpRequestContext requestContext = request.GetRequestContext();\n            if (requestContext == null)\n            {\n                throw new ArgumentException(OwinResources.Request_RequestContextMustNotBeNull, \"request\");\n            }\n\n            var previousPrincipal = requestContext.Principal;\n            requestContext.Principal = principal;\n\n            return previousPrincipal;\n        }\n\n        private static void SuppressDefaultAuthenticationChallenges(HttpRequestMessage request)\n        {\n            Contract.Assert(request != null);\n\n            IAuthenticationManager authenticationManager = request.GetAuthenticationManager();\n\n            if (authenticationManager == null)\n            {\n                throw new InvalidOperationException(OwinResources.IAuthenticationManagerNotAvailable);\n            }\n\n            AuthenticationResponseChallenge currentChallenge = authenticationManager.AuthenticationResponseChallenge;\n\n            // A null challenge or challenge.AuthenticationTypes == null or empty represents the the default behavior\n            // of running all active authentication middleware challenges.\n            // Provide an array with a single null item to suppress this default behavior.\n            string[] suppressAuthenticationTypes = new string[] { null };\n\n            if (currentChallenge == null)\n            {\n                authenticationManager.AuthenticationResponseChallenge = new AuthenticationResponseChallenge(\n                    suppressAuthenticationTypes, new AuthenticationProperties());\n            }\n            else if (currentChallenge.AuthenticationTypes == null || currentChallenge.AuthenticationTypes.Length == 0)\n            {\n                authenticationManager.AuthenticationResponseChallenge = new AuthenticationResponseChallenge(\n                    suppressAuthenticationTypes, currentChallenge.Properties);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.Owin/Properties/AssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\n[assembly: AssemblyTitle(\"System.Web.Http.Owin\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: Guid(\"41f9da53-4a52-4cd7-af85-77a214c5b13b\")]\n[assembly: InternalsVisibleTo(\"System.Web.Http.Owin.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]"
  },
  {
    "path": "src/System.Web.Http.Owin/Properties/OwinResources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.18051\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace System.Web.Http.Owin.Properties {\n    using System;\n    \n    \n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class OwinResources {\n        \n        private static global::System.Resources.ResourceManager resourceMan;\n        \n        private static global::System.Globalization.CultureInfo resourceCulture;\n        \n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal OwinResources() {\n        }\n        \n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"System.Web.Http.Owin.Properties.OwinResources\", typeof(OwinResources).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n        \n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to HttpAuthenticationChallengeContext.Request must not be null..\n        /// </summary>\n        internal static string HttpAuthenticationChallengeContext_RequestMustNotBeNull {\n            get {\n                return ResourceManager.GetString(\"HttpAuthenticationChallengeContext_RequestMustNotBeNull\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to HttpAuthenticationContext.Request must not be null..\n        /// </summary>\n        internal static string HttpAuthenticationContext_RequestMustNotBeNull {\n            get {\n                return ResourceManager.GetString(\"HttpAuthenticationContext_RequestMustNotBeNull\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to No OWIN authentication manager is associated with the request..\n        /// </summary>\n        internal static string IAuthenticationManagerNotAvailable {\n            get {\n                return ResourceManager.GetString(\"IAuthenticationManagerNotAvailable\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The OWIN context&apos;s Request property must not be null..\n        /// </summary>\n        internal static string OwinContext_NullRequest {\n            get {\n                return ResourceManager.GetString(\"OwinContext_NullRequest\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The OWIN context&apos;s Response property must not be null..\n        /// </summary>\n        internal static string OwinContext_NullResponse {\n            get {\n                return ResourceManager.GetString(\"OwinContext_NullResponse\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The request must have a request context..\n        /// </summary>\n        internal static string Request_RequestContextMustNotBeNull {\n            get {\n                return ResourceManager.GetString(\"Request_RequestContextMustNotBeNull\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The message handler did not return a response message..\n        /// </summary>\n        internal static string SendAsync_ReturnedNull {\n            get {\n                return ResourceManager.GetString(\"SendAsync_ReturnedNull\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to {0}.{1} must not be null..\n        /// </summary>\n        internal static string TypePropertyMustNotBeNull {\n            get {\n                return ResourceManager.GetString(\"TypePropertyMustNotBeNull\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.Owin/Properties/OwinResources.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"HttpAuthenticationChallengeContext_RequestMustNotBeNull\" xml:space=\"preserve\">\n    <value>HttpAuthenticationChallengeContext.Request must not be null.</value>\n  </data>\n  <data name=\"HttpAuthenticationContext_RequestMustNotBeNull\" xml:space=\"preserve\">\n    <value>HttpAuthenticationContext.Request must not be null.</value>\n  </data>\n  <data name=\"IAuthenticationManagerNotAvailable\" xml:space=\"preserve\">\n    <value>No OWIN authentication manager is associated with the request.</value>\n  </data>\n  <data name=\"OwinContext_NullRequest\" xml:space=\"preserve\">\n    <value>The OWIN context's Request property must not be null.</value>\n  </data>\n  <data name=\"OwinContext_NullResponse\" xml:space=\"preserve\">\n    <value>The OWIN context's Response property must not be null.</value>\n  </data>\n  <data name=\"Request_RequestContextMustNotBeNull\" xml:space=\"preserve\">\n    <value>The request must have a request context.</value>\n  </data>\n  <data name=\"SendAsync_ReturnedNull\" xml:space=\"preserve\">\n    <value>The message handler did not return a response message.</value>\n  </data>\n  <data name=\"TypePropertyMustNotBeNull\" xml:space=\"preserve\">\n    <value>{0}.{1} must not be null.</value>\n  </data>\n</root>"
  },
  {
    "path": "src/System.Web.Http.Owin/System.Web.Http.Owin.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{66DD7CD7-C68F-4D0E-9F3D-3B58C49D1467}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>System.Web.Http.Owin</RootNamespace>\n    <AssemblyName>System.Web.Http.Owin</AssemblyName>\n    <DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>\n    <RunCodeAnalysis>$(CodeAnalysis)</RunCodeAnalysis>\n    <CodeAnalysisRuleSet>..\\Strict.ruleset</CodeAnalysisRuleSet>\n    <DefineConstants>$(DefineConstants);ASPNETMVC</DefineConstants>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Microsoft.Owin\">\n      <HintPath>..\\..\\packages\\Microsoft.Owin.4.2.2\\lib\\net45\\Microsoft.Owin.dll</HintPath>\n    </Reference>\n    <Reference Include=\"Owin\">\n      <HintPath>..\\..\\packages\\Owin.1.0\\lib\\net40\\Owin.dll</HintPath>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Net.Http\" />\n    <Reference Include=\"System.Xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\CommonAssemblyInfo.cs\">\n      <Link>Properties\\CommonAssemblyInfo.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\CollectionExtensions.cs\">\n      <Link>Common\\CollectionExtensions.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\DictionaryExtensions.cs\">\n      <Link>Common\\DictionaryExtensions.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Error.cs\">\n      <Link>Common\\Error.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\ListWrapperCollection.cs\">\n      <Link>Common\\ListWrapperCollection.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\NonOwnedStream.cs\">\n      <Link>Common\\NonOwnedStream.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\TaskHelpers.cs\">\n      <Link>Common\\TaskHelpers.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\TaskHelpersExtensions.cs\">\n      <Link>Common\\TaskHelpersExtensions.cs</Link>\n    </Compile>\n    <Compile Include=\"ExceptionHandling\\DefaultExceptionHandler.cs\" />\n    <Compile Include=\"ExceptionHandling\\EmptyExceptionLogger.cs\" />\n    <Compile Include=\"OwinExceptionCatchBlocks.cs\" />\n    <Compile Include=\"HostAuthenticationAttribute.cs\" />\n    <Compile Include=\"HttpMessageHandlerOptions.cs\" />\n    <Compile Include=\"OwinHttpConfigurationExtensions.cs\" />\n    <Compile Include=\"HostAuthenticationFilter.cs\" />\n    <Compile Include=\"OwinBufferPolicySelector.cs\" />\n    <Compile Include=\"OwinConstants.cs\" />\n    <Compile Include=\"GlobalSuppressions.cs\" />\n    <Compile Include=\"HttpMessageHandlerAdapter.cs\" />\n    <Compile Include=\"OwinHttpRequestContext.cs\" />\n    <Compile Include=\"OwinHttpRequestMessageExtensions.cs\" />\n    <Compile Include=\"OwinRequestExtensions.cs\" />\n    <Compile Include=\"OwinResponseExtensions.cs\" />\n    <Compile Include=\"PassiveAuthenticationMessageHandler.cs\" />\n    <Compile Include=\"WebApiAppBuilderExtensions.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"Properties\\OwinResources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>OwinResources.resx</DependentUpon>\n    </Compile>\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\Common\\CommonWebApiResources.Designer.cs\">\n      <Link>Properties\\CommonWebApiResources.Designer.cs</Link>\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>CommonWebApiResources.resx</DependentUpon>\n    </Compile>\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"..\\Common\\CommonWebApiResources.resx\">\n      <Link>Properties\\CommonWebApiResources.resx</Link>\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>CommonWebApiResources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n    <EmbeddedResource Include=\"Properties\\OwinResources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>OwinResources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\System.Net.Http.Formatting\\System.Net.Http.Formatting.csproj\">\n      <Project>{668e9021-ce84-49d9-98fb-df125a9fcdb0}</Project>\n      <Name>System.Net.Http.Formatting</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.Http\\System.Web.Http.csproj\">\n      <Project>{ddc1ce0c-486e-4e35-bb3b-eab61f8f9440}</Project>\n      <Name>System.Web.Http</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <CodeAnalysisDictionary Include=\"..\\CodeAnalysisDictionary.xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\">\n      <SubType>Designer</SubType>\n    </None>\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n</Project>"
  },
  {
    "path": "src/System.Web.Http.Owin/WebApiAppBuilderExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Threading;\nusing System.Web.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.Owin;\n\nnamespace Owin\n{\n    /// <summary>\n    /// Provides extension methods for the <see cref=\"IAppBuilder\"/> class.\n    /// </summary>\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class WebApiAppBuilderExtensions\n    {\n        private static readonly IHostBufferPolicySelector _defaultBufferPolicySelector =\n            new OwinBufferPolicySelector();\n\n        /// <summary>Adds a component to the OWIN pipeline for running a Web API endpoint.</summary>\n        /// <param name=\"builder\">The application builder.</param>\n        /// <param name=\"configuration\">The <see cref=\"HttpConfiguration\"/> used to configure the endpoint.</param>\n        /// <returns>The application builder.</returns>\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\",\n            Justification = \"In the success path, HttpMessageHandlerAdapter owns the message handler.\")]\n        public static IAppBuilder UseWebApi(this IAppBuilder builder, HttpConfiguration configuration)\n        {\n            if (builder == null)\n            {\n                throw new ArgumentNullException(\"builder\");\n            }\n\n            if (configuration == null)\n            {\n                throw new ArgumentNullException(\"configuration\");\n            }\n\n            HttpServer server = new HttpServer(configuration);\n\n            try\n            {\n                HttpMessageHandlerOptions options = CreateOptions(builder, server, configuration);\n                return UseMessageHandler(builder, options);\n            }\n            catch\n            {\n                server.Dispose();\n                throw;\n            }\n        }\n\n        /// <summary>Adds a component to the OWIN pipeline for running a Web API endpoint.</summary>\n        /// <param name=\"builder\">The application builder.</param>\n        /// <param name=\"httpServer\">The http server.</param>\n        /// <returns>The application builder.</returns>\n        public static IAppBuilder UseWebApi(this IAppBuilder builder, HttpServer httpServer)\n        {\n            if (builder == null)\n            {\n                throw new ArgumentNullException(\"builder\");\n            }\n\n            if (httpServer == null)\n            {\n                throw new ArgumentNullException(\"httpServer\");\n            }\n\n            HttpConfiguration configuration = httpServer.Configuration;\n            Contract.Assert(configuration != null);\n\n            HttpMessageHandlerOptions options = CreateOptions(builder, httpServer, configuration);\n            return UseMessageHandler(builder, options);\n        }\n\n        private static IAppBuilder UseMessageHandler(this IAppBuilder builder, HttpMessageHandlerOptions options)\n        {\n            Contract.Assert(builder != null);\n            Contract.Assert(options != null);\n\n            return builder.Use(typeof(HttpMessageHandlerAdapter), options);\n        }\n\n        private static HttpMessageHandlerOptions CreateOptions(IAppBuilder builder, HttpServer server,\n            HttpConfiguration configuration)\n        {\n            Contract.Assert(builder != null);\n            Contract.Assert(server != null);\n            Contract.Assert(configuration != null);\n\n            ServicesContainer services = configuration.Services;\n            Contract.Assert(services != null);\n\n            IHostBufferPolicySelector bufferPolicySelector = services.GetHostBufferPolicySelector()\n                ?? _defaultBufferPolicySelector;\n            IExceptionLogger exceptionLogger = ExceptionServices.GetLogger(services);\n            IExceptionHandler exceptionHandler = ExceptionServices.GetHandler(services);\n\n            return new HttpMessageHandlerOptions\n            {\n                MessageHandler = server,\n                BufferPolicySelector = bufferPolicySelector,\n                ExceptionLogger = exceptionLogger,\n                ExceptionHandler = exceptionHandler,\n                AppDisposing = builder.GetOnAppDisposingProperty()\n            };\n        }\n\n        internal static CancellationToken GetOnAppDisposingProperty(this IAppBuilder builder)\n        {\n            Contract.Assert(builder != null);\n\n            IDictionary<string, object> properties = builder.Properties;\n\n            if (properties == null)\n            {\n                return CancellationToken.None;\n            }\n\n            object value;\n\n            if (!properties.TryGetValue(\"host.OnAppDisposing\", out value))\n            {\n                return CancellationToken.None;\n            }\n\n            CancellationToken? token = value as CancellationToken?;\n\n            if (!token.HasValue)\n            {\n                return CancellationToken.None;\n            }\n\n            return token.Value;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.Owin/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Microsoft.Owin\" version=\"4.2.2\" targetFramework=\"net45\" />\n  <package id=\"Owin\" version=\"1.0\" targetFramework=\"net45\" />\n</packages>"
  },
  {
    "path": "src/System.Web.Http.SelfHost/Channels/HttpBinding.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.ServiceModel;\nusing System.ServiceModel.Channels;\nusing System.Web.Http.SelfHost.ServiceModel;\nusing System.Web.Http.SelfHost.ServiceModel.Channels;\n\nnamespace System.Web.Http.SelfHost.Channels\n{   \n    /// <summary>\n    /// A binding used with endpoints for web services that use strongly-type HTTP request \n    /// and response messages.\n    /// </summary>\n    public class HttpBinding : Binding, IBindingRuntimePreferences\n    {\n        internal const string CollectionElementName = \"httpBinding\";\n        internal const TransferMode DefaultTransferMode = System.ServiceModel.TransferMode.Buffered;\n        \n        private HttpsTransportBindingElement _httpsTransportBindingElement;\n        private HttpTransportBindingElement _httpTransportBindingElement;\n        private HttpBindingSecurity _security;\n        private HttpMessageEncodingBindingElement _httpMessageEncodingBindingElement;\n        private Action<HttpTransportBindingElement> _configureTransportBindingElement;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpBinding\"/> class.\n        /// </summary>\n        public HttpBinding()\n        {\n            Initialize();\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpBinding\"/> class with the \n        /// type of security used by the binding explicitly specified.\n        /// </summary>\n        /// <param name=\"securityMode\">The value of <see cref=\"HttpBindingSecurityMode\"/> that \n        /// specifies the type of security that is used to configure a service endpoint using the\n        /// <see cref=\"HttpBinding\"/> binding.\n        /// </param>\n        public HttpBinding(HttpBindingSecurityMode securityMode)\n            : this()\n        {\n            _security.Mode = securityMode;\n        }\n\n        /// <summary>\n        /// Gets the envelope version that is used by endpoints that are configured to use an \n        /// <see cref=\"HttpBinding\"/> binding.  Always returns <see cref=\"System.ServiceModel.EnvelopeVersion.None\"/>.\n        /// </summary>\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"This is existing public API\")]\n        public EnvelopeVersion EnvelopeVersion\n        {\n            get { return EnvelopeVersion.None; }\n        }\n\n        /// <summary>\n        /// Gets or sets a value that indicates whether the hostname is used to reach the \n        /// service when matching the URI.\n        /// </summary>\n        [DefaultValue(HttpTransportDefaults.HostNameComparisonMode)]\n        public HostNameComparisonMode HostNameComparisonMode\n        {\n            get { return _httpTransportBindingElement.HostNameComparisonMode; }\n\n            set\n            {\n                _httpTransportBindingElement.HostNameComparisonMode = value;\n                _httpsTransportBindingElement.HostNameComparisonMode = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets the maximum amount of memory allocated for the buffer manager that manages the buffers \n        /// required by endpoints that use this binding.\n        /// </summary>\n        [DefaultValue(TransportDefaults.MaxBufferPoolSize)]\n        public long MaxBufferPoolSize\n        {\n            get { return _httpTransportBindingElement.MaxBufferPoolSize; }\n\n            set\n            {\n                _httpTransportBindingElement.MaxBufferPoolSize = value;\n                _httpsTransportBindingElement.MaxBufferPoolSize = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets the maximum amount of memory that is allocated for use by the manager of the message \n        /// buffers that receive messages from the channel.\n        /// </summary>\n        [DefaultValue(TransportDefaults.MaxBufferSize)]\n        public int MaxBufferSize\n        {\n            get { return _httpTransportBindingElement.MaxBufferSize; }\n\n            set\n            {\n                _httpTransportBindingElement.MaxBufferSize = value;\n                _httpsTransportBindingElement.MaxBufferSize = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets the maximum size for a message that can be processed by the binding.\n        /// </summary>\n        [DefaultValue(TransportDefaults.MaxReceivedMessageSize)]\n        public long MaxReceivedMessageSize\n        {\n            get { return _httpTransportBindingElement.MaxReceivedMessageSize; }\n\n            set\n            {\n                _httpTransportBindingElement.MaxReceivedMessageSize = value;\n                _httpsTransportBindingElement.MaxReceivedMessageSize = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets the delegate which can configure the <see cref=\"HttpTransportBindingElement\"/> that this binding creates.\n        /// </summary>\n        public Action<HttpTransportBindingElement> ConfigureTransportBindingElement\n        {\n            get { return _configureTransportBindingElement; }\n\n            set \n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n\n                _configureTransportBindingElement = value;              \n            }\n        }\n\n        /// <summary>\n        /// Gets the URI transport scheme for the channels and listeners that are configured \n        /// with this binding. (Overrides <see cref=\"System.ServiceModel.Channels.Binding.Scheme\">\n        /// Binding.Scheme</see>.)\n        /// </summary>\n        public override string Scheme\n        {\n            get { return GetTransport().Scheme; }\n        }\n\n        /// <summary>\n        /// Gets or sets the security settings used with this binding. \n        /// </summary>\n        public HttpBindingSecurity Security\n        {\n            get { return _security; }\n\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.ArgumentNull(\"value\");\n                }\n\n                _security = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets a value that indicates whether the service configured with the \n        /// binding uses streamed or buffered (or both) modes of message transfer.\n        /// </summary>\n        [DefaultValue(HttpTransportDefaults.TransferMode)]\n        public TransferMode TransferMode\n        {\n            get { return _httpTransportBindingElement.TransferMode; }\n\n            set\n            {\n                _httpTransportBindingElement.TransferMode = value;\n                _httpsTransportBindingElement.TransferMode = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets a value indicating whether incoming requests can be handled more efficiently synchronously or asynchronously.\n        /// </summary>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1033:InterfaceMethodsShouldBeCallableByChildTypes\", Justification = \"This is the pattern used by all standard bindings.\")]\n        bool IBindingRuntimePreferences.ReceiveSynchronously\n        {\n            get { return false; }\n        }\n\n        /// <summary>\n        /// Returns an ordered collection of binding elements contained in the current binding. \n        /// (Overrides <see cref=\"System.ServiceModel.Channels.Binding.CreateBindingElements\">\n        /// Binding.CreateBindingElements</see>.)\n        /// </summary>\n        /// <returns>\n        /// An ordered collection of binding elements contained in the current binding.\n        /// </returns>\n        public override BindingElementCollection CreateBindingElements()\n        {\n            BindingElementCollection bindingElements = new BindingElementCollection();\n\n            bindingElements.Add(_httpMessageEncodingBindingElement);\n            bindingElements.Add(GetTransport());\n\n            return bindingElements.Clone();\n        }\n\n        private TransportBindingElement GetTransport()\n        {\n            HttpTransportBindingElement result = null;\n\n            if (_security.Mode == HttpBindingSecurityMode.Transport)\n            {\n                _security.Transport.ConfigureTransportProtectionAndAuthentication(_httpsTransportBindingElement);\n                result = _httpsTransportBindingElement;\n            }\n            else if (_security.Mode == HttpBindingSecurityMode.TransportCredentialOnly)\n            {\n                _security.Transport.ConfigureTransportAuthentication(_httpTransportBindingElement);\n                result = _httpTransportBindingElement;\n            }\n            else\n            {\n                _security.Transport.DisableTransportAuthentication(_httpTransportBindingElement);\n                result = _httpTransportBindingElement;\n            }\n\n            // give customer final chance to customize the auth scheme\n            if (_configureTransportBindingElement != null)\n            {\n                _configureTransportBindingElement(result);\n            }\n\n            return result;\n        }\n\n        private void Initialize()\n        {\n            _security = new HttpBindingSecurity();\n\n            _httpTransportBindingElement = new HttpTransportBindingElement();\n            _httpTransportBindingElement.ManualAddressing = true;\n\n            _httpsTransportBindingElement = new HttpsTransportBindingElement();\n            _httpsTransportBindingElement.ManualAddressing = true;\n\n            _httpMessageEncodingBindingElement = new HttpMessageEncodingBindingElement();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/Channels/HttpBindingSecurity.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ServiceModel;\n\nnamespace System.Web.Http.SelfHost.Channels\n{\n    /// <summary>\n    /// Specifies the types of security available to a service endpoint configured to use an\n    /// <see cref=\"HttpBinding\"/> binding.\n    /// </summary>\n    public sealed class HttpBindingSecurity\n    {\n        internal const HttpBindingSecurityMode DefaultMode = HttpBindingSecurityMode.None;\n\n        private HttpBindingSecurityMode _mode;\n        private HttpTransportSecurity _transportSecurity;\n\n        /// <summary>\n        /// Creates a new instance of the <see cref=\"HttpBindingSecurity\"/> class.\n        /// </summary>\n        public HttpBindingSecurity()\n        {\n            _mode = DefaultMode;\n            _transportSecurity = new HttpTransportSecurity();\n        }\n\n        /// <summary>\n        /// Gets or sets the mode of security that is used by an endpoint configured to use an\n        /// <see cref=\"HttpBinding\"/> binding.\n        /// </summary>\n        public HttpBindingSecurityMode Mode\n        {\n            get { return _mode; }\n\n            set\n            {\n                HttpBindingSecurityModeHelper.Validate(value, \"value\");\n                _mode = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets an object that contains the transport-level security settings for the \n        /// <see cref=\"HttpBinding\"/> binding.\n        /// </summary>\n        public HttpTransportSecurity Transport\n        {\n            get { return _transportSecurity; }\n\n            set { _transportSecurity = value ?? new HttpTransportSecurity(); }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/Channels/HttpBindingSecurityMode.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.SelfHost.Channels\n{\n    /// <summary>\n    /// Defines the modes of security that can be used to configure a service endpoint that uses the\n    /// <see cref=\"HttpBinding\"/>.\n    /// </summary>\n    public enum HttpBindingSecurityMode\n    {\n        /// <summary>\n        /// Indicates no security is used with HTTP requests.\n        /// </summary>\n        None,\n\n        /// <summary>\n        /// Indicates that transport-level security is used with HTTP requests.\n        /// </summary>\n        Transport,\n\n        /// <summary>\n        /// Indicates that only HTTP-based client authentication is provided.\n        /// </summary>\n        TransportCredentialOnly,\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/Channels/HttpBindingSecurityModeHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\n\nnamespace System.Web.Http.SelfHost.Channels\n{\n    /// <summary>\n    /// Internal helper class to validate <see cref=\"HttpBindingSecurityMode\"/> enum values.\n    /// </summary>\n    internal static class HttpBindingSecurityModeHelper\n    {\n        /// <summary>\n        /// Determines whether the specified <paramref name=\"value\"/> is defined by the <see cref=\"HttpBindingSecurityMode\"/>\n        /// enumeration.\n        /// </summary>\n        /// <param name=\"value\">The value to test.</param>\n        /// <returns><c>true</c> if <paramref name=\"value\"/> is a valid <see cref=\"HttpBindingSecurityMode\"/> value; otherwise<c> false</c>.</returns>\n        public static bool IsDefined(HttpBindingSecurityMode value)\n        {\n            return value == HttpBindingSecurityMode.None ||\n                   value == HttpBindingSecurityMode.Transport ||\n                   value == HttpBindingSecurityMode.TransportCredentialOnly;\n        }\n\n        /// <summary>\n        /// Validates the specified <paramref name=\"value\"/> and throws an <see cref=\"InvalidEnumArgumentException\"/>\n        /// exception if not valid.\n        /// </summary>\n        /// <param name=\"value\">The value to validate.</param>\n        /// <param name=\"parameterName\">Name of the parameter to use if throwing exception.</param>\n        public static void Validate(HttpBindingSecurityMode value, string parameterName)\n        {\n            if (!IsDefined(value))\n            {\n                throw Error.InvalidEnumArgument(parameterName, (int)value, typeof(HttpBindingSecurityMode));\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/Channels/HttpMessage.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.ServiceModel.Channels;\nusing System.Web.Http.SelfHost.Properties;\nusing System.Xml;\n\nnamespace System.Web.Http.SelfHost.Channels\n{\n    internal sealed class HttpMessage : Message\n    {\n        private HttpRequestMessage _request;\n        private HttpResponseMessage _response;\n        private MessageHeaders _headers;\n        private MessageProperties _properties;\n\n        public HttpMessage(HttpRequestMessage request)\n        {\n            Contract.Assert(request != null, \"The 'request' parameter should not be null.\");\n            _request = request;\n            Headers.To = request.RequestUri;\n            IsRequest = true;\n        }\n\n        public HttpMessage(HttpResponseMessage response)\n        {\n            Contract.Assert(response != null, \"The 'response' parameter should not be null.\");\n            _response = response;\n            IsRequest = false;\n        }\n\n        public override MessageVersion Version\n        {\n            get\n            {\n                EnsureNotDisposed();\n                return MessageVersion.None;\n            }\n        }\n\n        public override MessageHeaders Headers\n        {\n            get\n            {\n                EnsureNotDisposed();\n                if (_headers == null)\n                {\n                    _headers = new MessageHeaders(MessageVersion.None);\n                }\n\n                return _headers;\n            }\n        }\n\n        public override MessageProperties Properties\n        {\n            get\n            {\n                EnsureNotDisposed();\n                if (_properties == null)\n                {\n                    _properties = new MessageProperties();\n                    _properties.AllowOutputBatching = false;\n                }\n\n                return _properties;\n            }\n        }\n\n        public override bool IsEmpty\n        {\n            get\n            {\n                long? contentLength = GetHttpContentLength();\n                return contentLength.HasValue && contentLength.Value == 0;\n            }\n        }\n\n        public override bool IsFault\n        {\n            get { return false; }\n        }\n\n        public bool IsRequest { get; private set; }\n\n        public HttpRequestMessage GetHttpRequestMessage(bool extract)\n        {\n            EnsureNotDisposed();\n            Contract.Assert(IsRequest, \"This method should only be called when IsRequest is true.\");\n            if (extract)\n            {\n                HttpRequestMessage req = _request;\n                _request = null;\n                return req;\n            }\n\n            return _request;\n        }\n\n        public HttpResponseMessage GetHttpResponseMessage(bool extract)\n        {\n            EnsureNotDisposed();\n            Contract.Assert(!IsRequest, \"This method should only be called when IsRequest is false.\");\n            if (extract)\n            {\n                HttpResponseMessage res = _response;\n                _response = null;\n                return res;\n            }\n\n            return _response;\n        }\n\n        protected override void OnWriteBodyContents(XmlDictionaryWriter writer)\n        {\n            throw Error.NotSupported(GetNotSupportedMessage());\n        }\n\n        protected override MessageBuffer OnCreateBufferedCopy(int maxBufferSize)\n        {\n            throw Error.NotSupported(GetNotSupportedMessage());\n        }\n\n        protected override XmlDictionaryReader OnGetReaderAtBodyContents()\n        {\n            throw Error.NotSupported(GetNotSupportedMessage());\n        }\n\n        protected override string OnGetBodyAttribute(string localName, string ns)\n        {\n            throw Error.NotSupported(GetNotSupportedMessage());\n        }\n\n        protected override void OnWriteStartBody(XmlDictionaryWriter writer)\n        {\n            throw Error.NotSupported(GetNotSupportedMessage());\n        }\n\n        protected override void OnWriteStartEnvelope(XmlDictionaryWriter writer)\n        {\n            throw Error.NotSupported(GetNotSupportedMessage());\n        }\n\n        protected override void OnBodyToString(XmlDictionaryWriter writer)\n        {\n            if (writer == null)\n            {\n                throw Error.ArgumentNull(\"writer\");\n            }\n\n            long? contentLength = GetHttpContentLength();\n            string contentString = null;\n\n            if (IsRequest)\n            {\n                contentString = contentLength.HasValue\n                                    ? Error.Format(SRResources.MessageBodyIsHttpRequestMessageWithKnownContentLength, contentLength.Value)\n                                    : SRResources.MessageBodyIsHttpRequestMessageWithUnknownContentLength;\n            }\n            else\n            {\n                contentString = contentLength.HasValue\n                                    ? Error.Format(SRResources.MessageBodyIsHttpResponseMessageWithKnownContentLength, contentLength.Value)\n                                    : SRResources.MessageBodyIsHttpResponseMessageWithUnknownContentLength;\n            }\n\n            writer.WriteString(contentString);\n        }\n\n        protected override void OnWriteMessage(XmlDictionaryWriter writer)\n        {\n            throw Error.NotSupported(GetNotSupportedMessage());\n        }\n\n        protected override void OnWriteStartHeaders(XmlDictionaryWriter writer)\n        {\n            throw Error.NotSupported(GetNotSupportedMessage());\n        }\n\n        protected override void OnClose()\n        {\n            base.OnClose();\n            if (_request != null)\n            {\n                _request.DisposeRequestResources();\n                _request.Dispose();\n                _request = null;\n            }\n\n            if (_response != null)\n            {\n                _response.Dispose();\n                _response = null;\n            }\n        }\n\n        private static string GetNotSupportedMessage()\n        {\n            return Error.Format(\n                SRResources.MessageReadWriteCopyNotSupported,\n                HttpMessageExtensions.ToHttpRequestMessageMethodName,\n                HttpMessageExtensions.ToHttpResponseMessageMethodName,\n                typeof(HttpMessage).Name);\n        }\n\n        private void EnsureNotDisposed()\n        {\n            if (IsDisposed)\n            {\n                throw Error.ObjectDisposed(SRResources.MessageClosed, typeof(Message).Name);\n            }\n        }\n\n        private long? GetHttpContentLength()\n        {\n            HttpContent content = IsRequest\n                                      ? GetHttpRequestMessage(false).Content\n                                      : GetHttpResponseMessage(false).Content;\n\n            if (content == null)\n            {\n                return 0;\n            }\n\n            return content.Headers.ContentLength;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/Channels/HttpMessageEncoderFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.IO;\nusing System.Net.Http;\nusing System.ServiceModel;\nusing System.ServiceModel.Channels;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.SelfHost.Properties;\nusing System.Web.Http.SelfHost.ServiceModel.Channels;\n\nnamespace System.Web.Http.SelfHost.Channels\n{\n    internal class HttpMessageEncoderFactory : MessageEncoderFactory\n    {\n        private HttpMessageEncoder _encoder;\n\n        public HttpMessageEncoderFactory()\n        {\n            _encoder = new HttpMessageEncoder();\n        }\n\n        public override MessageEncoder Encoder\n        {\n            get { return _encoder; }\n        }\n\n        public override MessageVersion MessageVersion\n        {\n            get { return MessageVersion.None; }\n        }\n\n        public override MessageEncoder CreateSessionEncoder()\n        {\n            throw Error.NotSupported(SRResources.HttpMessageEncoderFactoryDoesNotSupportSessionEncoder, typeof(HttpMessageEncoderFactory).Name);\n        }\n\n        private class HttpMessageEncoder : MessageEncoder\n        {\n            private const string ContentTypeHeaderName = \"Content-Type\";\n            private const string MaxSentMessageSizeExceededResourceStringName = \"MaxSentMessageSizeExceeded\";\n            private static readonly string _httpBindingClassName = typeof(HttpBinding).FullName;\n            private static readonly string _httpResponseMessageClassName = typeof(HttpResponseMessage).FullName;\n\n            public override string ContentType\n            {\n                get { return String.Empty; }\n            }\n\n            public override string MediaType\n            {\n                get { return String.Empty; }\n            }\n\n            public override MessageVersion MessageVersion\n            {\n                get { return MessageVersion.None; }\n            }\n\n            public override bool IsContentTypeSupported(string contentType)\n            {\n                if (contentType == null)\n                {\n                    throw Error.ArgumentNull(\"contentType\");\n                }\n\n                return true;\n            }\n\n            [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"disposed later.\")]\n            public override Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType)\n            {\n                if (bufferManager == null)\n                {\n                    throw Error.ArgumentNull(\"bufferManager\");\n                }\n\n                HttpRequestMessage request = new HttpRequestMessage();\n                request.Content = new ByteArrayBufferManagerContent(bufferManager, buffer.Array, buffer.Offset, buffer.Count);\n                if (!String.IsNullOrEmpty(contentType))\n                {\n                    request.Content.Headers.TryAddWithoutValidation(ContentTypeHeaderName, contentType);\n                }\n\n                Message message = request.ToMessage();\n                message.Properties.Encoder = this;\n\n                return message;\n            }\n\n            [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"disposed later.\")]\n            public override Message ReadMessage(Stream stream, int maxSizeOfHeaders, string contentType)\n            {\n                if (stream == null)\n                {\n                    throw Error.ArgumentNull(\"stream\");\n                }\n\n                HttpRequestMessage request = new HttpRequestMessage();\n                request.Content = new StreamContent(stream);\n                if (!String.IsNullOrEmpty(contentType))\n                {\n                    request.Content.Headers.TryAddWithoutValidation(ContentTypeHeaderName, contentType);\n                }\n\n                Message message = request.ToMessage();\n                message.Properties.Encoder = this;\n\n                return message;\n            }\n\n            public override ArraySegment<byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset)\n            {\n                if (message == null)\n                {\n                    throw Error.ArgumentNull(\"message\");\n                }\n\n                if (bufferManager == null)\n                {\n                    throw Error.ArgumentNull(\"bufferManager\");\n                }\n\n                if (maxMessageSize < 0)\n                {\n                    throw Error.ArgumentOutOfRange(\"maxMessageSize\", maxMessageSize, SRResources.NonnegativeNumberRequired);\n                }\n\n                if (messageOffset < 0)\n                {\n                    throw Error.ArgumentOutOfRange(\"messageOffset\", messageOffset, SRResources.NonnegativeNumberRequired);\n                }\n\n                if (messageOffset > maxMessageSize)\n                {\n                    throw Error.Argument(String.Empty, SRResources.ParameterMustBeLessThanOrEqualSecondParameter, \"messageOffset\", \"maxMessageSize\");\n                }\n\n                // TODO: DevDiv2 bug #378887 -- find out how to eliminate this middle buffer\n                using (BufferManagerOutputStream stream = new BufferManagerOutputStream(MaxSentMessageSizeExceededResourceStringName, 0, maxMessageSize, bufferManager))\n                {\n                    int num;\n                    stream.Skip(messageOffset);\n                    WriteMessage(message, stream);\n\n                    byte[] buffer = stream.ToArray(out num);\n                    ArraySegment<byte> messageData = new ArraySegment<byte>(buffer, 0, num - messageOffset);\n\n                    // ToArray transfers full ownership of buffer to us, meaning we are responsible for returning it to BufferManager.\n                    // But we must delay that release until WCF has finished with the buffer we are returning from this method.\n                    HttpMessageEncodingRequestContext requestContext = HttpMessageEncodingRequestContext.GetContextFromMessage(message);\n                    Contract.Assert(requestContext != null);\n                    requestContext.BufferManager = bufferManager;\n                    requestContext.BufferToReturn = buffer;\n\n                    return messageData;\n                }\n            }\n\n            [SuppressMessage(\"Microsoft.Web.FxCop\", \"MW1201:DoNotCallProblematicMethodsOnTask\", Justification = \"The WriteMessage() API is synchronous, and Wait() won't deadlock in self-host.\")]\n            public override void WriteMessage(Message message, Stream stream)\n            {\n                if (message == null)\n                {\n                    throw Error.ArgumentNull(\"message\");\n                }\n\n                if (stream == null)\n                {\n                    throw Error.ArgumentNull(\"stream\");\n                }\n\n                ThrowIfMismatchedMessageVersion(message);\n\n                message.Properties.Encoder = this;\n\n                HttpResponseMessage response = GetHttpResponseMessageOrThrow(message);\n\n                if (response.Content != null)\n                {\n                    HttpMessageEncodingRequestContext requestContext =\n                        HttpMessageEncodingRequestContext.GetContextFromMessage(message);\n\n                    WriteMessageCore(response, stream, requestContext).Wait();\n                }\n            }\n\n            private static async Task WriteMessageCore(\n                HttpResponseMessage response,\n                Stream stream,\n                HttpMessageEncodingRequestContext requestContext)\n            {\n                try\n                {\n                    await response.Content.CopyToAsync(stream);\n                }\n                catch (Exception ex)\n                {\n                    if (requestContext != null)\n                    {\n                        requestContext.Exception = ex;\n                    }\n\n                    throw;\n                }\n            }\n\n            internal void ThrowIfMismatchedMessageVersion(Message message)\n            {\n                if (message.Version != MessageVersion)\n                {\n                    throw new ProtocolException(Error.Format(SRResources.EncoderMessageVersionMismatch, message.Version, MessageVersion));\n                }\n            }\n\n            private static HttpResponseMessage GetHttpResponseMessageOrThrow(Message message)\n            {\n                HttpResponseMessage response = message.ToHttpResponseMessage();\n                if (response == null)\n                {\n                    throw Error.InvalidOperation(\n                        SRResources.MessageInvalidForHttpMessageEncoder,\n                        _httpBindingClassName,\n                        HttpMessageExtensions.ToMessageMethodName,\n                        _httpResponseMessageClassName);\n                }\n\n                return response;\n            }\n\n            private class ByteArrayBufferManagerContent : ByteArrayContent\n            {\n                private BufferManager _bufferManager;\n                private byte[] _content;\n\n                public ByteArrayBufferManagerContent(BufferManager bufferManager, byte[] content, int offset, int count)\n                    : base(content, offset, count)\n                {\n                    Contract.Assert(bufferManager != null, \"The 'bufferManager' parameter should never be null.\");\n\n                    _bufferManager = bufferManager;\n                    _content = content;\n                }\n\n                protected override void Dispose(bool disposing)\n                {\n                    try\n                    {\n                        if (disposing)\n                        {\n                            BufferManager oldBufferManager = Interlocked.Exchange(ref _bufferManager, null);\n                            if (oldBufferManager != null)\n                            {\n                                oldBufferManager.ReturnBuffer(_content);\n                                _content = null;\n                            }\n                        }\n                    }\n                    finally\n                    {\n                        base.Dispose(disposing);\n                    }\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/Channels/HttpMessageEncodingBindingElement.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.ServiceModel.Channels;\nusing System.Web.Http.SelfHost.Properties;\n\nnamespace System.Web.Http.SelfHost.Channels\n{\n    /// <summary>\n    /// Provides an <see cref=\"HttpMessageEncoderFactory\"/> that returns a <see cref=\"MessageEncoder\"/> \n    /// that is able to produce and consume <see cref=\"HttpMessage\"/> instances.\n    /// </summary>\n    internal sealed class HttpMessageEncodingBindingElement : MessageEncodingBindingElement\n    {\n        private static readonly Type _replyChannelType = typeof(IReplyChannel);\n\n        /// <summary>\n        /// Gets or sets the message version that can be handled by the message encoders produced by the message encoder factory.\n        /// </summary>\n        /// <returns>The <see cref=\"MessageVersion\"/> used by the encoders produced by the message encoder factory.</returns>\n        public override MessageVersion MessageVersion\n        {\n            get { return MessageVersion.None; }\n\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.ArgumentNull(\"value\");\n                }\n\n                if (value != MessageVersion.None)\n                {\n                    throw Error.NotSupported(SRResources.OnlyMessageVersionNoneSupportedOnHttpMessageEncodingBindingElement, typeof(HttpMessageEncodingBindingElement).Name);\n                }\n            }\n        }\n\n        /// <summary>\n        /// Returns a value that indicates whether the binding element can build a listener for a specific type of channel.\n        /// </summary>\n        /// <typeparam name=\"TChannel\">The type of channel the listener accepts.</typeparam>\n        /// <param name=\"context\">The <see cref=\"BindingContext\"/> that provides context for the binding element</param>\n        /// <returns>true if the <see cref=\"IChannelListener{TChannel}\"/> of type <see cref=\"IChannel\"/> can be built by the binding element; otherwise, false.</returns>\n        public override bool CanBuildChannelFactory<TChannel>(BindingContext context)\n        {\n            return false;\n        }\n\n        /// <summary>\n        /// Returns a value that indicates whether the binding element can build a channel factory for a specific type of channel.\n        /// </summary>\n        /// <typeparam name=\"TChannel\">The type of channel the channel factory produces.</typeparam>\n        /// <param name=\"context\">The <see cref=\"BindingContext\"/> that provides context for the binding element</param>\n        /// <returns>ALways false.</returns>\n        public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context)\n        {\n            throw Error.NotSupported(SRResources.ChannelFactoryNotSupported, typeof(HttpMessageEncodingBindingElement).Name, typeof(IChannelFactory).Name);\n        }\n\n        /// <summary>\n        /// Returns a value that indicates whether the binding element can build a channel factory for a specific type of channel.\n        /// </summary>\n        /// <typeparam name=\"TChannel\">The type of channel the channel factory produces.</typeparam>\n        /// <param name=\"context\">The <see cref=\"BindingContext\"/> that provides context for the binding element</param>\n        /// <returns>ALways false.</returns>\n        public override bool CanBuildChannelListener<TChannel>(BindingContext context)\n        {\n            if (context == null)\n            {\n                throw Error.ArgumentNull(\"context\");\n            }\n\n            context.BindingParameters.Add(this);\n\n            return IsChannelShapeSupported<TChannel>() && context.CanBuildInnerChannelListener<TChannel>();\n        }\n\n        /// <summary>\n        /// Initializes a channel listener to accept channels of a specified type from the binding context.\n        /// </summary>\n        /// <typeparam name=\"TChannel\">The type of channel the listener is built to accept.</typeparam>\n        /// <param name=\"context\">The <see cref=\"BindingContext\"/> that provides context for the binding element</param>\n        /// <returns>The <see cref=\"IChannelListener{TChannel}\"/> of type <see cref=\"IChannel\"/> initialized from the context.</returns>\n        public override IChannelListener<TChannel> BuildChannelListener<TChannel>(BindingContext context)\n        {\n            if (context == null)\n            {\n                throw Error.ArgumentNull(\"context\");\n            }\n\n            if (!IsChannelShapeSupported<TChannel>())\n            {\n                throw Error.NotSupported(SRResources.ChannelShapeNotSupported, typeof(HttpMessageEncodingBindingElement).Name, typeof(IReplyChannel).Name);\n            }\n\n            context.BindingParameters.Add(this);\n\n            IChannelListener<IReplyChannel> innerListener = context.BuildInnerChannelListener<IReplyChannel>();\n\n            if (innerListener == null)\n            {\n                return null;\n            }\n\n            return (IChannelListener<TChannel>)new HttpMessageEncodingChannelListener(context.Binding, innerListener);\n        }\n\n        /// <summary>\n        /// Returns a copy of the binding element object.\n        /// </summary>\n        /// <returns>A <see cref=\"BindingElement\"/> object that is a deep clone of the original.</returns>\n        public override BindingElement Clone()\n        {\n            return new HttpMessageEncodingBindingElement();\n        }\n\n        /// <summary>\n        /// Creates a factory for producing message encoders that are able to \n        /// produce and consume <see cref=\"HttpMessage\"/> instances.\n        /// </summary>\n        /// <returns>\n        /// The <see cref=\"MessageEncoderFactory\"/> used to produce message encoders that are able to \n        /// produce and consume <see cref=\"HttpMessage\"/> instances.\n        /// </returns>\n        public override MessageEncoderFactory CreateMessageEncoderFactory()\n        {\n            return new HttpMessageEncoderFactory();\n        }\n\n        private static bool IsChannelShapeSupported<TChannel>()\n        {\n            return typeof(TChannel) == _replyChannelType;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/Channels/HttpMessageEncodingChannelListener.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ServiceModel.Channels;\nusing System.Web.Http.SelfHost.ServiceModel.Channels;\n\nnamespace System.Web.Http.SelfHost.Channels\n{\n    internal class HttpMessageEncodingChannelListener : LayeredChannelListener<IReplyChannel>\n    {\n        private IChannelListener<IReplyChannel> _innerChannelListener;\n\n        public HttpMessageEncodingChannelListener(Binding binding, IChannelListener<IReplyChannel> innerListener) :\n            base(binding, innerListener)\n        {\n        }\n\n        protected override void OnOpening()\n        {\n            _innerChannelListener = (IChannelListener<IReplyChannel>)InnerChannelListener;\n            base.OnOpening();\n        }\n\n        protected override IReplyChannel OnAcceptChannel(TimeSpan timeout)\n        {\n            IReplyChannel innerChannel = _innerChannelListener.AcceptChannel(timeout);\n            return WrapInnerChannel(innerChannel);\n        }\n\n        protected override IAsyncResult OnBeginAcceptChannel(TimeSpan timeout, AsyncCallback callback, object state)\n        {\n            return _innerChannelListener.BeginAcceptChannel(timeout, callback, state);\n        }\n\n        protected override IReplyChannel OnEndAcceptChannel(IAsyncResult result)\n        {\n            IReplyChannel innerChannel = _innerChannelListener.EndAcceptChannel(result);\n            return WrapInnerChannel(innerChannel);\n        }\n\n        protected override IAsyncResult OnBeginWaitForChannel(TimeSpan timeout, AsyncCallback callback, object state)\n        {\n            return _innerChannelListener.BeginWaitForChannel(timeout, callback, state);\n        }\n\n        protected override bool OnEndWaitForChannel(IAsyncResult result)\n        {\n            return _innerChannelListener.EndWaitForChannel(result);\n        }\n\n        protected override bool OnWaitForChannel(TimeSpan timeout)\n        {\n            return _innerChannelListener.WaitForChannel(timeout);\n        }\n\n        private IReplyChannel WrapInnerChannel(IReplyChannel innerChannel)\n        {\n            return (innerChannel != null)\n                       ? new HttpMessageEncodingReplyChannel(this, innerChannel)\n                       : (IReplyChannel)null;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/Channels/HttpMessageEncodingReplyChannel.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.ServiceModel;\nusing System.ServiceModel.Channels;\nusing System.Web.Http.SelfHost.ServiceModel.Channels;\n\nnamespace System.Web.Http.SelfHost.Channels\n{\n    internal class HttpMessageEncodingReplyChannel : LayeredChannel<IReplyChannel>, IReplyChannel, IChannel, ICommunicationObject\n    {\n        public HttpMessageEncodingReplyChannel(ChannelManagerBase channelManager, IReplyChannel innerChannel)\n            : base(channelManager, innerChannel)\n        {\n        }\n\n        public EndpointAddress LocalAddress\n        {\n            get { return InnerChannel.LocalAddress; }\n        }\n\n        public IAsyncResult BeginReceiveRequest(AsyncCallback callback, object state)\n        {\n            return InnerChannel.BeginReceiveRequest(callback, state);\n        }\n\n        public IAsyncResult BeginReceiveRequest(TimeSpan timeout, AsyncCallback callback, object state)\n        {\n            return InnerChannel.BeginReceiveRequest(timeout, callback, state);\n        }\n\n        public IAsyncResult BeginTryReceiveRequest(TimeSpan timeout, AsyncCallback callback, object state)\n        {\n            return InnerChannel.BeginTryReceiveRequest(timeout, callback, state);\n        }\n\n        public IAsyncResult BeginWaitForRequest(TimeSpan timeout, AsyncCallback callback, object state)\n        {\n            return InnerChannel.BeginWaitForRequest(timeout, callback, state);\n        }\n\n        public RequestContext EndReceiveRequest(IAsyncResult result)\n        {\n            RequestContext innerContext = InnerChannel.EndReceiveRequest(result);\n            return WrapRequestContext(innerContext);\n        }\n\n        public bool EndTryReceiveRequest(IAsyncResult result, out RequestContext context)\n        {\n            RequestContext innerContext;\n            context = null;\n            if (!InnerChannel.EndTryReceiveRequest(result, out innerContext))\n            {\n                return false;\n            }\n\n            context = WrapRequestContext(innerContext);\n            return true;\n        }\n\n        public bool EndWaitForRequest(IAsyncResult result)\n        {\n            return InnerChannel.EndWaitForRequest(result);\n        }\n\n        public RequestContext ReceiveRequest()\n        {\n            RequestContext innerContext = InnerChannel.ReceiveRequest();\n            return WrapRequestContext(innerContext);\n        }\n\n        public RequestContext ReceiveRequest(TimeSpan timeout)\n        {\n            RequestContext innerContext = InnerChannel.ReceiveRequest(timeout);\n            return WrapRequestContext(innerContext);\n        }\n\n        public bool TryReceiveRequest(TimeSpan timeout, out RequestContext context)\n        {\n            RequestContext innerContext;\n            if (InnerChannel.TryReceiveRequest(timeout, out innerContext))\n            {\n                context = WrapRequestContext(innerContext);\n                return true;\n            }\n\n            context = null;\n            return false;\n        }\n\n        public bool WaitForRequest(TimeSpan timeout)\n        {\n            return InnerChannel.WaitForRequest(timeout);\n        }\n\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"disposed later.\")]\n        private static RequestContext WrapRequestContext(RequestContext innerContext)\n        {\n            return (innerContext != null)\n                       ? new HttpMessageEncodingRequestContext(innerContext)\n                       : (RequestContext)null;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/Channels/HttpMessageEncodingRequestContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Headers;\nusing System.ServiceModel.Channels;\nusing System.Web.Http.SelfHost.Properties;\n\nnamespace System.Web.Http.SelfHost.Channels\n{\n    internal class HttpMessageEncodingRequestContext : RequestContext\n    {\n        private const string HttpMessageEncodingRequestContextPropertyName = \"MS_HttpMessageEncodingRequestContextKey\";\n        private const string DefaultReasonPhrase = \"OK\";\n\n        private RequestContext _innerContext;\n        private Message _configuredRequestMessage;\n\n        public HttpMessageEncodingRequestContext(RequestContext innerContext)\n        {\n            Contract.Assert(innerContext != null, \"The 'innerContext' parameter should not be null.\");\n            _innerContext = innerContext;\n        }\n\n        internal Exception Exception { get; set; }\n        internal BufferManager BufferManager { get; set; }\n        internal byte[] BufferToReturn { get; set; }\n\n        public override Message RequestMessage\n        {\n            get\n            {\n                if (_configuredRequestMessage == null)\n                {\n                    _configuredRequestMessage = ConfigureRequestMessage(_innerContext.RequestMessage);\n                }\n\n                return _configuredRequestMessage;\n            }\n        }\n\n        public override void Abort()\n        {\n            Cleanup();\n            _innerContext.Abort();\n        }\n\n        public override IAsyncResult BeginReply(Message message, TimeSpan timeout, AsyncCallback callback, object state)\n        {\n            ConfigureResponseMessage(message);\n            return _innerContext.BeginReply(message, timeout, callback, state);\n        }\n\n        public override IAsyncResult BeginReply(Message message, AsyncCallback callback, object state)\n        {\n            ConfigureResponseMessage(message);\n            return _innerContext.BeginReply(message, callback, state);\n        }\n\n        public override void Close(TimeSpan timeout)\n        {\n            Cleanup();\n            _innerContext.Close(timeout);\n        }\n\n        public override void Close()\n        {\n            Cleanup();\n            _innerContext.Close();\n        }\n\n        public override void EndReply(IAsyncResult result)\n        {\n            try\n            {\n                _innerContext.EndReply(result);\n            }\n            catch (Exception ex)\n            {\n                Exception = ex;\n                throw;\n            }\n        }\n\n        public override void Reply(Message message, TimeSpan timeout)\n        {\n            ConfigureResponseMessage(message);\n            _innerContext.Reply(message, timeout);\n        }\n\n        public override void Reply(Message message)\n        {\n            ConfigureResponseMessage(message);\n            _innerContext.Reply(message);\n        }\n\n        protected override void Dispose(bool disposing)\n        {\n            if (disposing)\n            {\n                // To avoid double buffering, we use the BufferedOutputStream's own buffer\n                // that it created through the BufferManager passed to WriteStream.\n                // We are responsible for returning that buffer to the BufferManager\n                // because we used BufferedOutputStream.ToArray to take ownership\n                // of its buffers.\n                if (BufferManager != null && BufferToReturn != null)\n                {\n                    BufferManager.ReturnBuffer(BufferToReturn);\n                    BufferToReturn = null;\n                }\n            }\n\n            base.Dispose(disposing);\n        }\n\n        internal static HttpMessageEncodingRequestContext GetContextFromMessage(Message message)\n        {\n            HttpMessageEncodingRequestContext context = null;\n            message.Properties.TryGetValue<HttpMessageEncodingRequestContext>(HttpMessageEncodingRequestContextPropertyName, out context);\n            return context;\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Cleanup exceptions are ignored as they are not fatal to the host.\")]\n        private void Cleanup()\n        {\n            if (_configuredRequestMessage != null)\n            {\n                try\n                {\n                    _configuredRequestMessage.Close();\n                }\n                catch\n                {\n                }\n            }\n        }\n\n        private static void CopyHeadersToNameValueCollection(HttpHeaders headers, NameValueCollection nameValueCollection)\n        {\n            foreach (KeyValuePair<string, IEnumerable<string>> header in headers)\n            {\n                foreach (string value in header.Value)\n                {\n                    nameValueCollection.Add(header.Key, value);\n                }\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"disposed later.\")]\n        private static Message ConfigureRequestMessage(Message message)\n        {\n            if (message == null)\n            {\n                return null;\n            }\n\n            HttpRequestMessageProperty requestProperty;\n            if (!message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out requestProperty))\n            {\n                throw Error.InvalidOperation(\n                    SRResources.RequestMissingHttpRequestMessageProperty,\n                    HttpRequestMessageProperty.Name,\n                    typeof(HttpRequestMessageProperty).Name);\n            }\n\n            Uri uri = message.Headers.To;\n            if (uri == null)\n            {\n                throw Error.InvalidOperation(SRResources.RequestMissingToHeader);\n            }\n\n            HttpRequestMessage httpRequestMessage = message.ToHttpRequestMessage();\n            if (httpRequestMessage == null)\n            {\n                if (!message.IsEmpty)\n                {\n                    throw Error.InvalidOperation(SRResources.NonHttpMessageMustBeEmpty, HttpMessageExtensions.ToHttpRequestMessageMethodName, typeof(HttpMessage).Name);\n                }\n\n                httpRequestMessage = new HttpRequestMessage();\n                Message oldMessage = message;\n                message = httpRequestMessage.ToMessage();\n                message.Properties.CopyProperties(oldMessage.Properties);\n                oldMessage.Close();\n            }\n            else\n            {\n                // Clear headers but not properties.\n                message.Headers.Clear();\n            }\n\n            // Copy message properties to HttpRequestMessage. While it does have the\n            // risk of allowing properties to get out of sync they in virtually all cases are\n            // read-only so the risk is low. The downside to not doing it is that it isn't\n            // possible to access anything from HttpRequestMessage (or OperationContent.Current)\n            // which is worse.\n            foreach (KeyValuePair<string, object> kv in message.Properties)\n            {\n                httpRequestMessage.Properties.Add(kv.Key, kv.Value);\n            }\n\n            if (httpRequestMessage.Content == null)\n            {\n                httpRequestMessage.Content = new ByteArrayContent(new byte[0]);\n            }\n            else\n            {\n                httpRequestMessage.Content.Headers.Clear();\n            }\n\n            message.Headers.To = uri;\n\n            httpRequestMessage.RequestUri = uri;\n            httpRequestMessage.Method = HttpMethodHelper.GetHttpMethod(requestProperty.Method);\n\n            WebHeaderCollection headers = requestProperty.Headers;\n            foreach (var headerName in headers.AllKeys)\n            {\n                string headerValue = headers[headerName];\n                if (!httpRequestMessage.Headers.TryAddWithoutValidation(headerName, headerValue))\n                {\n                    httpRequestMessage.Content.Headers.TryAddWithoutValidation(headerName, headerValue);\n                }\n            }\n\n            return message;\n        }\n\n        private void ConfigureResponseMessage(Message message)\n        {\n            Contract.Assert(message != null);\n\n            HttpResponseMessageProperty responseProperty = new HttpResponseMessageProperty();\n            HttpResponseMessage httpResponseMessage = message.ToHttpResponseMessage();\n\n            if (httpResponseMessage == null)\n            {\n                responseProperty.StatusCode = HttpStatusCode.InternalServerError;\n                responseProperty.SuppressEntityBody = true;\n            }\n            else\n            {\n                responseProperty.StatusCode = httpResponseMessage.StatusCode;\n                if (httpResponseMessage.ReasonPhrase != null &&\n                    httpResponseMessage.ReasonPhrase != DefaultReasonPhrase)\n                {\n                    responseProperty.StatusDescription = httpResponseMessage.ReasonPhrase;\n                }\n\n                CopyHeadersToNameValueCollection(httpResponseMessage.Headers, responseProperty.Headers);\n                HttpContent content = httpResponseMessage.Content;\n                if (content != null)\n                {\n                    CopyHeadersToNameValueCollection(httpResponseMessage.Content.Headers, responseProperty.Headers);\n                }\n                else\n                {\n                    responseProperty.SuppressEntityBody = true;\n                }\n            }\n\n            message.Properties.Clear();\n            message.Headers.Clear();\n\n            message.Properties.Add(HttpResponseMessageProperty.Name, responseProperty);\n\n            // The current request context flows with the Message for later use\n            // by HttpMessageEncoder.WriteMessage\n            message.Properties.Add(HttpMessageEncodingRequestContextPropertyName, this);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/Channels/HttpMessageExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.ServiceModel.Channels;\n\nnamespace System.Web.Http.SelfHost.Channels\n{\n    /// <summary>\n    /// Provides extension methods for getting an <see cref=\"HttpRequestMessage\"/> instance or\n    /// an <see cref=\"HttpResponseMessage\"/> instance from a <see cref=\"Message\"/> instance and\n    /// provides extension methods for creating a <see cref=\"Message\"/> instance from either an \n    /// <see cref=\"HttpRequestMessage\"/> instance or an \n    /// <see cref=\"HttpResponseMessage\"/> instance.\n    /// </summary>\n    internal static class HttpMessageExtensions\n    {\n        internal const string ToHttpRequestMessageMethodName = \"ToHttpRequestMessage\";\n        internal const string ToHttpResponseMessageMethodName = \"ToHttpResponseMessage\";\n        internal const string ToMessageMethodName = \"ToMessage\";\n\n        /// <summary>\n        /// Returns a reference to the <see cref=\"HttpRequestMessage\"/> \n        /// instance held by the given <see cref=\"Message\"/> or null if the <see cref=\"Message\"/> does not\n        /// hold a reference to an <see cref=\"HttpRequestMessage\"/> \n        /// instance.\n        /// </summary>\n        /// <param name=\"message\">The given <see cref=\"Message\"/> that holds a reference to an \n        /// <see cref=\"HttpRequestMessage\"/> instance.\n        /// </param>\n        /// <returns>\n        /// A reference to the <see cref=\"HttpRequestMessage\"/> \n        /// instance held by the given <see cref=\"Message\"/> or null if the <see cref=\"Message\"/> does not\n        /// hold a reference to an <see cref=\"HttpRequestMessage\"/> \n        /// instance.\n        /// </returns>\n        public static HttpRequestMessage ToHttpRequestMessage(this Message message)\n        {\n            if (message == null)\n            {\n                throw Error.ArgumentNull(\"message\");\n            }\n\n            HttpMessage httpMessage = message as HttpMessage;\n            if (httpMessage != null && httpMessage.IsRequest)\n            {\n                return httpMessage.GetHttpRequestMessage(false);\n            }\n\n            return null;\n        }\n\n        /// <summary>\n        /// Returns a reference to the <see cref=\"HttpResponseMessage\"/> \n        /// instance held by the given <see cref=\"Message\"/> or null if the <see cref=\"Message\"/> does not\n        /// hold a reference to an <see cref=\"HttpResponseMessage\"/> \n        /// instance.\n        /// </summary>\n        /// <param name=\"message\">The given <see cref=\"Message\"/> that holds a reference to an \n        /// <see cref=\"HttpResponseMessage\"/> instance.\n        /// </param>\n        /// <returns>\n        /// A reference to the <see cref=\"HttpResponseMessage\"/> \n        /// instance held by the given <see cref=\"Message\"/> or null if the <see cref=\"Message\"/> does not\n        /// hold a reference to an <see cref=\"HttpResponseMessage\"/> \n        /// instance.\n        /// </returns>\n        public static HttpResponseMessage ToHttpResponseMessage(this Message message)\n        {\n            if (message == null)\n            {\n                throw Error.ArgumentNull(\"message\");\n            }\n\n            HttpMessage httpMessage = message as HttpMessage;\n            if (httpMessage != null && !httpMessage.IsRequest)\n            {\n                return httpMessage.GetHttpResponseMessage(false);\n            }\n\n            return null;\n        }\n\n        /// <summary>\n        /// Returns a reference to the <see cref=\"HttpResponseMessage\"/> \n        /// instance held by the given <see cref=\"Message\"/> or null if the <see cref=\"Message\"/> does not\n        /// hold a reference to an <see cref=\"HttpResponseMessage\"/> \n        /// instance.\n        /// </summary>\n        /// <remarks>The caller takes over the ownership of the associated <see cref=\"HttpRequestMessage\"/> and is responsible for its disposal.</remarks>\n        /// <param name=\"message\">The given <see cref=\"Message\"/> that holds a reference to an \n        /// <see cref=\"HttpResponseMessage\"/> instance.\n        /// </param>\n        /// <returns>\n        /// A reference to the <see cref=\"HttpResponseMessage\"/> \n        /// instance held by the given <see cref=\"Message\"/> or null if the <see cref=\"Message\"/> does not\n        /// hold a reference to an <see cref=\"HttpResponseMessage\"/> \n        /// instance.\n        /// The caller is responsible for disposing any <see cref=\"HttpResponseMessage\"/> instance returned.\n        /// </returns>\n        public static HttpResponseMessage ExtractHttpResponseMessage(this Message message)\n        {\n            if (message == null)\n            {\n                throw Error.ArgumentNull(\"message\");\n            }\n\n            HttpMessage httpMessage = message as HttpMessage;\n            if (httpMessage != null && !httpMessage.IsRequest)\n            {\n                return httpMessage.GetHttpResponseMessage(true);\n            }\n\n            return null;\n        }\n\n        /// <summary>\n        /// Creates a new <see cref=\"Message\"/> that holds a reference to the given \n        /// <see cref=\"HttpRequestMessage\"/> instance.\n        /// </summary>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/> \n        /// instance to which the new <see cref=\"Message\"/> should hold a reference.\n        /// </param>\n        /// <returns>A <see cref=\"Message\"/> that holds a reference to the given\n        /// <see cref=\"HttpRequestMessage\"/> instance.\n        /// </returns>\n        public static Message ToMessage(this HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            return new HttpMessage(request);\n        }\n\n        /// <summary>\n        /// Creates a new <see cref=\"Message\"/> that holds a reference to the given\n        /// <see cref=\"HttpResponseMessage\"/> instance.\n        /// </summary>\n        /// <param name=\"response\">The <see cref=\"HttpResponseMessage\"/> \n        /// instance to which the new <see cref=\"Message\"/> should hold a reference.\n        /// </param>\n        /// <returns>A <see cref=\"Message\"/> that holds a reference to the given\n        /// <see cref=\"HttpResponseMessage\"/> instance.\n        /// </returns>\n        public static Message ToMessage(this HttpResponseMessage response)\n        {\n            if (response == null)\n            {\n                throw Error.ArgumentNull(\"response\");\n            }\n\n            return new HttpMessage(response);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/GlobalSuppressions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA2210:AssembliesShouldHaveValidStrongNames\", Justification = \"These assemblies are delay-signed.\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Justification = \"Classes are grouped logically for user clarity.\", Scope = \"Namespace\", Target = \"System.Net.Http\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Justification = \"Classes are grouped logically for user clarity.\", Scope = \"Namespace\", Target = \"System.Web.Http.SelfHost\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Justification = \"Classes are grouped logically for user clarity.\", Scope = \"Namespace\", Target = \"System.Web.Http.SelfHost.Activation\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Justification = \"Classes are grouped logically for user clarity.\", Scope = \"Namespace\", Target = \"System.Web.Http.SelfHost.Channels\")]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1701:ResourceStringCompoundWordsShouldBeCasedCorrectly\", MessageId = \"URIs\", Scope = \"resource\", Target = \"System.Web.Http.SelfHost.Properties.SRResources.resources\", Justification = \"FxCop does not seem to allow adding an exception to this term in its dictionary.\")]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1703:ResourceStringsShouldBeSpelledCorrectly\", MessageId = \"URIs\", Scope = \"resource\", Target = \"System.Web.Http.SelfHost.Properties.SRResources.resources\", Justification = \"FxCop does not seem to allow adding an exception to this term in its dictionary.\")]\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/HttpRequestMessageExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.ServiceModel.Security;\nusing System.Web.Http;\nusing System.Web.Http.SelfHost;\n\nnamespace System.Net.Http\n{\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class HttpRequestMessageExtensions\n    {\n        /// <summary>\n        /// Gets the current <see cref=\"T:System.ServiceModel.Security.SecurityMessageProperty\"/> \n        /// stored in <see cref=\"M:HttpRequestMessage.Properties\"/> for the given request.\n        /// </summary>\n        /// <param name=\"request\">The HTTP request.</param>\n        /// <returns>The <see cref=\"SecurityMessageProperty\"/>.</returns>\n        public static SecurityMessageProperty GetSecurityMessageProperty(this HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            return request.GetProperty<SecurityMessageProperty>(HttpSelfHostServer.SecurityKey);\n        }\n\n        private static T GetProperty<T>(this HttpRequestMessage request, string key)\n        {\n            T value;\n            request.Properties.TryGetValue(key, out value);\n            return value;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/HttpSelfHostConfiguration.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.IdentityModel.Selectors;\nusing System.ServiceModel;\nusing System.ServiceModel.Channels;\nusing System.ServiceModel.Description;\nusing System.ServiceModel.Security;\nusing System.Web.Http.SelfHost.Channels;\nusing System.Web.Http.SelfHost.Properties;\nusing System.Web.Http.SelfHost.ServiceModel;\nusing System.Web.Http.SelfHost.ServiceModel.Channels;\n\nnamespace System.Web.Http.SelfHost\n{\n    /// <summary>\n    /// The configuration class for Http Services\n    /// </summary>\n    public class HttpSelfHostConfiguration : HttpConfiguration\n    {\n        private const int DefaultMaxConcurrentRequests = 100;\n        private const int DefaultMaxBufferSize = 64 * 1024;\n        private const int DefaultReceivedMessageSize = 64 * 1024;\n\n        private const int MinConcurrentRequests = 1;\n        private const int MinBufferSize = 1;\n        private const int MinReceivedMessageSize = 1;\n\n        private static readonly TimeSpan DefaultReceiveTimeout = new TimeSpan(0, 10, 0);\n        private static readonly TimeSpan DefaultSendTimeout = new TimeSpan(0, 1, 0);\n\n        private Uri _baseAddress;\n        private int _maxConcurrentRequests;\n        private ServiceCredentials _credentials = new ServiceCredentials();\n        private HttpClientCredentialType _clientCredentialType = HttpClientCredentialType.None;\n        private TransferMode _transferMode;\n        private int _maxBufferSize = DefaultMaxBufferSize;\n        private bool _maxBufferSizeIsInitialized;\n        private long _maxReceivedMessageSize = DefaultReceivedMessageSize;\n        private TimeSpan _receiveTimeout = DefaultReceiveTimeout;\n        private TimeSpan _sendTimeout = DefaultSendTimeout;\n        private HostNameComparisonMode _hostNameComparisonMode;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpSelfHostConfiguration\"/> class.\n        /// </summary>\n        /// <param name=\"baseAddress\">The base address.</param>\n        public HttpSelfHostConfiguration(string baseAddress)\n            : this(CreateBaseAddress(baseAddress))\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpSelfHostConfiguration\"/> class.\n        /// </summary>\n        /// <param name=\"baseAddress\">The base address.</param>\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"caller owns object\")]\n        public HttpSelfHostConfiguration(Uri baseAddress)\n            : base(new HttpRouteCollection(ValidateBaseAddress(baseAddress).AbsolutePath))\n        {\n            _baseAddress = ValidateBaseAddress(baseAddress);\n            _maxConcurrentRequests = MultiplyByProcessorCount(DefaultMaxConcurrentRequests);\n            _maxBufferSize = TransportDefaults.MaxBufferSize;\n            _maxReceivedMessageSize = TransportDefaults.MaxReceivedMessageSize;\n        }\n\n        /// <summary>\n        /// Gets the base address.\n        /// </summary>\n        /// <value>\n        /// The base address.\n        /// </value>\n        public Uri BaseAddress\n        {\n            get { return _baseAddress; }\n        }\n\n        /// <summary>\n        /// Gets or sets the upper limit of how many concurrent <see cref=\"T:System.Net.Http.HttpRequestMessage\"/> instances \n        /// can be processed at any given time. The default is 100 times the number of CPU cores.\n        /// </summary>\n        /// <value>\n        /// The maximum concurrent <see cref=\"T:System.Net.Http.HttpRequestMessage\"/> instances processed at any given time.\n        /// </value>\n        public int MaxConcurrentRequests\n        {\n            get { return _maxConcurrentRequests; }\n\n            set\n            {\n                if (value < MinConcurrentRequests)\n                {\n                    throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"value\", value, MinConcurrentRequests);\n                }\n                _maxConcurrentRequests = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets the transfer mode.\n        /// </summary>\n        /// <value>\n        /// The transfer mode.\n        /// </value>\n        public TransferMode TransferMode\n        {\n            get { return _transferMode; }\n\n            set\n            {\n                TransferModeHelper.Validate(value, \"value\");\n                _transferMode = value;\n            }\n        }\n\n        /// <summary>\n        /// Specifies how the host name should be used in URI comparisons when dispatching an incoming message.\n        /// </summary>\n        public HostNameComparisonMode HostNameComparisonMode\n        {\n            get { return _hostNameComparisonMode; }\n\n            set\n            {\n                HostNameComparisonModeHelper.Validate(value, \"value\");\n                _hostNameComparisonMode = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets the size of the max buffer.\n        /// </summary>\n        /// <value>\n        /// The size of the max buffer.\n        /// </value>\n        public int MaxBufferSize\n        {\n            get\n            {\n                if (_maxBufferSizeIsInitialized || TransferMode != TransferMode.Buffered)\n                {\n                    return _maxBufferSize;\n                }\n\n                long maxReceivedMessageSize = MaxReceivedMessageSize;\n                if (maxReceivedMessageSize > Int32.MaxValue)\n                {\n                    return Int32.MaxValue;\n                }\n                return (int)maxReceivedMessageSize;\n            }\n\n            set\n            {\n                if (value < MinBufferSize)\n                {\n                    throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"value\", value, MinBufferSize);\n                }\n                _maxBufferSizeIsInitialized = true;\n                _maxBufferSize = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets the size of the max received message.\n        /// </summary>\n        /// <value>\n        /// The size of the max received message.\n        /// </value>\n        public long MaxReceivedMessageSize\n        {\n            get { return _maxReceivedMessageSize; }\n\n            set\n            {\n                if (value < MinReceivedMessageSize)\n                {\n                    throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"value\", value, MinReceivedMessageSize);\n                }\n                _maxReceivedMessageSize = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets the interval of time that a connection can remain inactive, during which no application messages are received, before it is dropped.\n        /// </summary>\n        /// <value>\n        /// The interval of time that a connection can remain inactive, during which no application messages are received, before it is dropped.\n        /// </value>\n        public TimeSpan ReceiveTimeout\n        {\n            get { return _receiveTimeout; }\n\n            set\n            {\n                if (value < TimeSpan.Zero)\n                {\n                    throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"value\", value, TimeSpan.Zero);\n                }\n\n                _receiveTimeout = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets the interval of time provided for a write operation to complete before the transport raises an exception.\n        /// </summary>\n        /// <value>\n        /// The interval of time provided for a write operation to complete before the transport raises an exception.\n        /// </value>\n        public TimeSpan SendTimeout\n        {\n            get { return _sendTimeout; }\n\n            set\n            {\n                if (value < TimeSpan.Zero)\n                {\n                    throw Error.ArgumentMustBeGreaterThanOrEqualTo(\"value\", value, TimeSpan.Zero);\n                }\n\n                _sendTimeout = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets UserNamePasswordValidator so that it can be used to validate the username and password\n        /// sent over HTTP or HTTPS\n        /// </summary>\n        /// <value>\n        /// The server certificate.\n        /// </value>\n        public UserNamePasswordValidator UserNamePasswordValidator\n        {\n            get { return _credentials.UserNameAuthentication.CustomUserNamePasswordValidator; }\n\n            set \n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n\n                _clientCredentialType = HttpClientCredentialType.Basic;\n                _credentials.UserNameAuthentication.CustomUserNamePasswordValidator = value;\n                _credentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets X509CertificateValidator so that it can be used to validate the client certificate\n        /// sent over HTTPS\n        /// </summary>\n        /// <value>\n        /// The server certificate.\n        /// </value>\n        public X509CertificateValidator X509CertificateValidator\n        {\n            get { return _credentials.ClientCertificate.Authentication.CustomCertificateValidator; }\n\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n\n                _clientCredentialType = HttpClientCredentialType.Certificate;\n                _credentials.ClientCertificate.Authentication.CustomCertificateValidator = value;\n                _credentials.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.Custom;\n            }\n        }\n\n        /// <summary>\n        /// Gets/Sets the ClientCredentialType that server is expecting. \n        /// </summary>\n        /// <value>\n        /// The default value is HttpClientCredentialType.None.\n        /// </value>\n        public HttpClientCredentialType ClientCredentialType\n        {\n            get { return _clientCredentialType; }\n            set { _clientCredentialType = value; }\n        }\n\n        /// <summary>\n        /// Internal method called to configure <see cref=\"HttpBinding\"/> settings.\n        /// </summary>\n        /// <param name=\"httpBinding\">Http binding.</param>\n        /// <returns>The <see cref=\"BindingParameterCollection\"/> to use when building the <see cref=\"IChannelListener\"/> or null if no binding parameters are present.</returns>\n        internal BindingParameterCollection ConfigureBinding(HttpBinding httpBinding)\n        {\n            return OnConfigureBinding(httpBinding);\n        }\n\n        /// <summary>\n        /// Called to apply the configuration on the endpoint level.\n        /// </summary>\n        /// <param name=\"httpBinding\">Http endpoint.</param>\n        /// <returns>The <see cref=\"BindingParameterCollection\"/> to use when building the <see cref=\"IChannelListener\"/> or null if no binding parameters are present.</returns>\n        protected virtual BindingParameterCollection OnConfigureBinding(HttpBinding httpBinding)\n        {\n            if (httpBinding == null)\n            {\n                throw Error.ArgumentNull(\"httpBinding\");\n            }\n\n            if (_clientCredentialType != HttpClientCredentialType.Basic && _credentials.UserNameAuthentication.CustomUserNamePasswordValidator != null)\n            {\n                throw Error.InvalidOperation(SRResources.CannotUseOtherClientCredentialTypeWithUserNamePasswordValidator);\n            }\n\n            if (_clientCredentialType != HttpClientCredentialType.Certificate && _credentials.ClientCertificate.Authentication.CustomCertificateValidator != null)\n            {\n                throw Error.InvalidOperation(SRResources.CannotUseOtherClientCredentialTypeWithX509CertificateValidator);\n            }\n\n            httpBinding.MaxBufferSize = MaxBufferSize;\n            httpBinding.MaxReceivedMessageSize = MaxReceivedMessageSize;\n            httpBinding.TransferMode = TransferMode;\n            httpBinding.HostNameComparisonMode = HostNameComparisonMode;\n            httpBinding.ReceiveTimeout = ReceiveTimeout;\n            httpBinding.SendTimeout = SendTimeout;\n\n            // Set up binding parameters\n            if (_baseAddress.Scheme == Uri.UriSchemeHttps)\n            {\n                // we need to use SSL\n                httpBinding.Security = new HttpBindingSecurity()\n                {\n                    Mode = HttpBindingSecurityMode.Transport,\n                };\n            }\n            \n            if (_clientCredentialType != HttpClientCredentialType.None)\n            {       \n                if (httpBinding.Security == null || httpBinding.Security.Mode == HttpBindingSecurityMode.None)\n                {\n                    // Basic over HTTP case\n                    httpBinding.Security = new HttpBindingSecurity()\n                    {\n                        Mode = HttpBindingSecurityMode.TransportCredentialOnly,\n                    };\n                }\n\n                httpBinding.Security.Transport.ClientCredentialType = _clientCredentialType;                \n            }\n\n            if (UserNamePasswordValidator != null || X509CertificateValidator != null)\n            {\n                // those are the only two things that affect service credentials\n                return AddCredentialsToBindingParameters();\n            }\n            else\n            {\n                return null;\n            }\n        }\n\n        private BindingParameterCollection AddCredentialsToBindingParameters()\n        {\n            BindingParameterCollection bindingParameters = new BindingParameterCollection();\n            bindingParameters.Add(_credentials);\n            return bindingParameters;\n        }\n\n        private static Uri CreateBaseAddress(string baseAddress)\n        {\n            if (baseAddress == null)\n            {\n                throw Error.ArgumentNull(\"baseAddress\");\n            }\n\n            return new Uri(baseAddress, UriKind.RelativeOrAbsolute);\n        }\n\n        private static Uri ValidateBaseAddress(Uri baseAddress)\n        {\n            if (baseAddress == null)\n            {\n                throw Error.ArgumentNull(\"baseAddress\");\n            }\n\n            if (!baseAddress.IsAbsoluteUri)\n            {\n                throw Error.ArgumentUriNotAbsolute(\"baseAddress\", baseAddress);\n            }\n\n            if (!String.IsNullOrEmpty(baseAddress.Query) || !String.IsNullOrEmpty(baseAddress.Fragment))\n            {\n                throw Error.ArgumentUriHasQueryOrFragment(\"baseAddress\", baseAddress);\n            }\n\n            if (!ReferenceEquals(baseAddress.Scheme, Uri.UriSchemeHttp) && !ReferenceEquals(baseAddress.Scheme, Uri.UriSchemeHttps))\n            {\n                throw Error.ArgumentUriNotHttpOrHttpsScheme(\"baseAddress\", baseAddress);\n            }\n\n            return baseAddress;\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We never want to fail here so we have to catch all exceptions.\")]\n        internal static int MultiplyByProcessorCount(int value)\n        {\n            Contract.Assert(value > 0);\n            try\n            {\n                return Math.Max(Environment.ProcessorCount * value, value);\n            }\n            catch\n            {\n                return value;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/HttpSelfHostServer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.IdentityModel.Claims;\nusing System.Net;\nusing System.Net.Http;\nusing System.Security.Cryptography.X509Certificates;\nusing System.Security.Principal;\nusing System.ServiceModel;\nusing System.ServiceModel.Channels;\nusing System.ServiceModel.Security;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.Routing;\nusing System.Web.Http.SelfHost.Channels;\nusing System.Web.Http.SelfHost.Properties;\nusing System.Web.Http.SelfHost.ServiceModel.Channels;\n\nnamespace System.Web.Http.SelfHost\n{\n    /// <summary>\n    /// Implementation of an <see cref=\"HttpServer\"/> which listens directly to HTTP.\n    /// </summary>\n    public sealed class HttpSelfHostServer : HttpServer\n    {\n        internal const string SecurityKey = \"Security\";\n\n        private static readonly AsyncCallback _onCloseListenerComplete = new AsyncCallback(OnCloseListenerComplete);\n        private static readonly AsyncCallback _onCloseChannelComplete = new AsyncCallback(OnCloseChannelComplete);\n\n        private static readonly TimeSpan _acceptTimeout = TimeSpan.MaxValue;\n        private static readonly TimeSpan _receiveTimeout = TimeSpan.MaxValue;\n\n        private static readonly Func<HttpRequestMessage, X509Certificate2> _retrieveClientCertificate = new Func<HttpRequestMessage, X509Certificate2>(RetrieveClientCertificate);\n\n        // Window size gets increased if the ratio of outstanding requests to the window size is greater than IncreaseWindowSizeRatio\n        // Window size gets decreased if the ratio of outstanding requests to the window size is less than DecreaseWindowsSizeRatio\n        private const double IncreaseWindowSizeRatio = .8;\n        private const double DecreaseWindowSizeRatio = .2;\n        private const int InitialWindowSizeMultiplier = 8;\n        private const int MinimumWindowSizeMultiplier = 1;\n        private static readonly int InitialWindowSize = HttpSelfHostConfiguration.MultiplyByProcessorCount(InitialWindowSizeMultiplier);\n        private static readonly int MinimumWindowSize = HttpSelfHostConfiguration.MultiplyByProcessorCount(MinimumWindowSizeMultiplier);\n\n        private AsyncCallback _onOpenListenerComplete;\n        private AsyncCallback _onAcceptChannelComplete;\n        private AsyncCallback _onOpenChannelComplete;\n        private AsyncCallback _onReceiveRequestContextComplete;\n        private AsyncCallback _onReplyComplete;\n\n        private ConcurrentBag<IReplyChannel> _channels = new ConcurrentBag<IReplyChannel>();\n        private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();\n\n        private bool _disposed;\n        private HttpSelfHostConfiguration _configuration;\n        private IChannelListener<IReplyChannel> _listener;\n        private TaskCompletionSource<bool> _openTaskCompletionSource;\n        private TaskCompletionSource<bool> _closeTaskCompletionSource;\n\n        // State: 0 = new, 1 = open, 2 = closed\n        private int _state;\n\n        private int _requestsOutstanding;\n        private int _windowSize;\n        private readonly object _windowSizeLock = new object();\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpSelfHostServer\"/> class.\n        /// </summary>\n        /// <param name=\"configuration\">The configuration.</param>\n        public HttpSelfHostServer(HttpSelfHostConfiguration configuration)\n            : base(configuration)\n        {\n            if (configuration == null)\n            {\n                throw Error.ArgumentNull(\"configuration\");\n            }\n\n            _configuration = configuration;\n            InitializeCallbacks();\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpSelfHostServer\"/> class.\n        /// </summary>\n        /// <param name=\"configuration\">The configuration.</param>\n        /// <param name=\"dispatcher\">The dispatcher.</param>\n        public HttpSelfHostServer(HttpSelfHostConfiguration configuration, HttpMessageHandler dispatcher)\n            : base(configuration, dispatcher)\n        {\n            if (configuration == null)\n            {\n                throw Error.ArgumentNull(\"configuration\");\n            }\n\n            _configuration = configuration;\n            InitializeCallbacks();\n        }\n\n        /// <summary>\n        /// Initialize async callbacks.\n        /// </summary>\n        private void InitializeCallbacks()\n        {\n            _onOpenListenerComplete = new AsyncCallback(OnOpenListenerComplete);\n            _onAcceptChannelComplete = new AsyncCallback(OnAcceptChannelComplete);\n            _onOpenChannelComplete = new AsyncCallback(OnOpenChannelComplete);\n            _onReceiveRequestContextComplete = new AsyncCallback(OnReceiveRequestContextComplete);\n            _onReplyComplete = new AsyncCallback(OnReplyComplete);\n        }\n\n        /// <summary>\n        /// Opens the current <see cref=\"HttpServer\"/> instance.\n        /// </summary>\n        /// <returns>A <see cref=\"Task\"/> representing the asynchronous <see cref=\"HttpServer\"/> open operation. Once this task completes successfully the server is running.</returns>\n        public Task OpenAsync()\n        {\n            if (Interlocked.CompareExchange(ref _state, 1, 0) == 1)\n            {\n                throw Error.InvalidOperation(SRResources.HttpServerAlreadyRunning, typeof(HttpSelfHostServer).Name);\n            }\n\n            _openTaskCompletionSource = new TaskCompletionSource<bool>();\n            BeginOpenListener(this);\n            return _openTaskCompletionSource.Task;\n        }\n\n        /// <summary>\n        /// Closes the current <see cref=\"HttpServer\"/> instance.\n        /// </summary>\n        /// <returns>A <see cref=\"Task\"/> representing the asynchronous <see cref=\"HttpServer\"/> close operation.</returns>\n        public Task CloseAsync()\n        {\n            if (Interlocked.CompareExchange(ref _state, 2, 1) != 1)\n            {\n                return TaskHelpers.Completed();\n            }\n\n            _closeTaskCompletionSource = new TaskCompletionSource<bool>();\n\n            // Cancel requests currently being processed\n            _cancellationTokenSource.Cancel();\n\n            BeginCloseListener(this);\n            return _closeTaskCompletionSource.Task;\n        }\n\n        /// <summary>\n        /// Releases unmanaged and - optionally - managed resources\n        /// </summary>\n        /// <param name=\"disposing\"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged SRResources.</param>\n        protected override void Dispose(bool disposing)\n        {\n            if (!_disposed)\n            {\n                _disposed = true;\n                if (_cancellationTokenSource != null)\n                {\n                    _cancellationTokenSource.Dispose();\n                    _cancellationTokenSource = null;\n                }\n            }\n\n            base.Dispose(disposing);\n        }\n\n        // async void is OK here. This is a fire and forget method and any exceptions that occur will be turned into\n        // HTTP responses that get sent back to clients.\n        private async void ProcessRequestContext(ChannelContext channelContext, RequestContext requestContext)\n        {\n            Contract.Assert(channelContext != null);\n            Contract.Assert(requestContext != null);\n\n            HttpResponseMessage response = await SendAsync(channelContext, requestContext);\n            Message reply = response.ToMessage();\n            BeginReply(new ReplyContext(channelContext, requestContext, reply));\n        }\n\n        private async Task<HttpResponseMessage> SendAsync(ChannelContext channelContext, RequestContext requestContext)\n        {\n            HttpRequestMessage request = null;\n            try\n            {\n                request = CreateHttpRequestMessage(requestContext);\n            }\n            catch\n            {\n                return new HttpResponseMessage(HttpStatusCode.BadRequest);\n            }\n\n            // Submit request up the stack\n            try\n            {\n                HttpResponseMessage response = await channelContext.Server.SendAsync(request, channelContext.Server._cancellationTokenSource.Token);\n\n                if (response == null)\n                {\n                    response = request.CreateResponse(HttpStatusCode.InternalServerError);\n                }\n\n                return response;\n            }\n            catch (OperationCanceledException operationCanceledException)\n            {\n                return request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, SRResources.RequestCancelled, operationCanceledException);\n            }\n        }\n\n        private HttpRequestMessage CreateHttpRequestMessage(RequestContext requestContext)\n        {\n            // Get the HTTP request from the WCF Message\n            HttpRequestMessage request = requestContext.RequestMessage.ToHttpRequestMessage();\n            if (request == null)\n            {\n                throw Error.InvalidOperation(SRResources.HttpMessageHandlerInvalidMessage, requestContext.RequestMessage.GetType());\n            }\n\n            // create principal information and add it the request for the windows auth case\n            SetCurrentPrincipal(request);\n\n            HttpRequestContext httpRequestContext = new SelfHostHttpRequestContext(requestContext, _configuration,\n                request);\n            request.SetRequestContext(httpRequestContext);\n\n            // The following two properties are set for backwards compatibility only. The request context controls the\n            // behavior for all cases except when accessing the property directly by key.\n\n            // Add the retrieve client certificate delegate to the property bag to enable lookup later on\n            request.Properties.Add(HttpPropertyKeys.RetrieveClientCertificateDelegateKey, _retrieveClientCertificate);\n\n            // Add information about whether the request is local or not\n            request.Properties.Add(HttpPropertyKeys.IsLocalKey, new Lazy<bool>(() => IsLocal(requestContext.RequestMessage)));\n            return request;\n        }\n\n        internal static bool IsLocal(Message message)\n        {\n            RemoteEndpointMessageProperty remoteEndpointProperty;\n            if (message.Properties.TryGetValue(RemoteEndpointMessageProperty.Name, out remoteEndpointProperty))\n            {\n                IPAddress remoteAddress;\n                if (IPAddress.TryParse(remoteEndpointProperty.Address, out remoteAddress))\n                {\n                    return IPAddress.IsLoopback(remoteAddress);\n                }\n            }\n            return false;\n        }\n\n        private static void SetCurrentPrincipal(HttpRequestMessage request)\n        {\n            SecurityMessageProperty property = request.GetSecurityMessageProperty();\n            if (property != null)\n            {\n                ServiceSecurityContext context = property.ServiceSecurityContext;\n                if (context != null && context.PrimaryIdentity != null)\n                {\n                    WindowsIdentity windowsIdentity = context.PrimaryIdentity as WindowsIdentity;\n\n                    if (windowsIdentity != null)\n                    {\n                        Thread.CurrentPrincipal = new WindowsPrincipal(windowsIdentity);\n                    }\n                }\n            }\n        }\n\n        internal static X509Certificate2 RetrieveClientCertificate(HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            SecurityMessageProperty property = request.GetSecurityMessageProperty();\n            X509Certificate2 result = null;\n\n            if (property != null && property.ServiceSecurityContext != null && property.ServiceSecurityContext.AuthorizationContext != null)\n            {\n                X509CertificateClaimSet certClaimSet = null;\n                foreach (ClaimSet claimSet in property.ServiceSecurityContext.AuthorizationContext.ClaimSets)\n                {\n                    certClaimSet = claimSet as X509CertificateClaimSet;\n\n                    if (certClaimSet != null)\n                    {\n                        result = certClaimSet.X509Certificate;\n                        break;\n                    }\n                }\n            }\n\n            return result;\n        }\n\n        private static void CancelTask(TaskCompletionSource<bool> taskCompletionSource)\n        {\n            Contract.Assert(taskCompletionSource != null);\n            taskCompletionSource.TrySetCanceled();\n        }\n\n        private static void FaultTask(TaskCompletionSource<bool> taskCompletionSource, Exception exception)\n        {\n            Contract.Assert(taskCompletionSource != null);\n            taskCompletionSource.TrySetException(exception);\n        }\n\n        private static void CompleteTask(TaskCompletionSource<bool> taskCompletionSource)\n        {\n            Contract.Assert(taskCompletionSource != null);\n            taskCompletionSource.TrySetResult(true);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We never want to fail here so we have to catch all exceptions.\")]\n        private void BeginOpenListener(HttpSelfHostServer server)\n        {\n            Contract.Assert(server != null);\n\n            try\n            {\n                // Create WCF HTTP transport channel\n                HttpBinding binding = new HttpBinding();\n\n                // Get it configured\n                BindingParameterCollection bindingParameters = server._configuration.ConfigureBinding(binding);\n                if (bindingParameters == null)\n                {\n                    bindingParameters = new BindingParameterCollection();\n                }\n\n                // Build channel listener\n                server._listener = binding.BuildChannelListener<IReplyChannel>(server._configuration.BaseAddress, bindingParameters);\n                if (server._listener == null)\n                {\n                    throw Error.InvalidOperation(SRResources.InvalidChannelListener, typeof(IChannelListener).Name, typeof(IReplyChannel).Name);\n                }\n\n                IAsyncResult result = server._listener.BeginOpen(_onOpenListenerComplete, server);\n                if (result.CompletedSynchronously)\n                {\n                    OpenListenerComplete(result);\n                }\n            }\n            catch (Exception e)\n            {\n                FaultTask(server._openTaskCompletionSource, e);\n            }\n        }\n\n        private void OnOpenListenerComplete(IAsyncResult result)\n        {\n            Contract.Assert(result != null);\n\n            if (result.CompletedSynchronously)\n            {\n                return;\n            }\n\n            OpenListenerComplete(result);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We never want to fail here so we have to catch all exceptions.\")]\n        private void OpenListenerComplete(IAsyncResult result)\n        {\n            HttpSelfHostServer server = (HttpSelfHostServer)result.AsyncState;\n            Contract.Assert(server != null);\n            Contract.Assert(server._listener != null);\n\n            try\n            {\n                server._listener.EndOpen(result);\n\n                // Start accepting channel\n                BeginAcceptChannel(server);\n            }\n            catch (Exception e)\n            {\n                FaultTask(server._openTaskCompletionSource, e);\n            }\n        }\n\n        private void BeginAcceptChannel(HttpSelfHostServer server)\n        {\n            Contract.Assert(server != null);\n            Contract.Assert(server._listener != null);\n\n            IAsyncResult result = BeginTryAcceptChannel(server, _onAcceptChannelComplete);\n            if (result.CompletedSynchronously)\n            {\n                AcceptChannelComplete(result);\n            }\n        }\n\n        private void OnAcceptChannelComplete(IAsyncResult result)\n        {\n            if (result.CompletedSynchronously)\n            {\n                return;\n            }\n\n            AcceptChannelComplete(result);\n        }\n\n        private void AcceptChannelComplete(IAsyncResult result)\n        {\n            Contract.Assert(result != null);\n\n            HttpSelfHostServer server = (HttpSelfHostServer)result.AsyncState;\n            Contract.Assert(server != null, \"host cannot be null\");\n            Contract.Assert(server._listener != null, \"host.listener cannot be null\");\n\n            IReplyChannel channel;\n            if (EndTryAcceptChannel(result, out channel))\n            {\n                // If we didn't get a channel then we stop accepting new channels\n                if (channel != null)\n                {\n                    server._channels.Add(channel);\n                    BeginOpenChannel(new ChannelContext(server, channel));\n                }\n                else\n                {\n                    CancelTask(server._openTaskCompletionSource);\n                }\n            }\n            else\n            {\n                // Start accepting next channel\n                BeginAcceptChannel(server);\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We never want to fail here so we have to catch all exceptions.\")]\n        private static IAsyncResult BeginTryAcceptChannel(HttpSelfHostServer server, AsyncCallback callback)\n        {\n            Contract.Assert(server != null);\n            Contract.Assert(server._listener != null);\n            Contract.Assert(callback != null);\n\n            try\n            {\n                return server._listener.BeginAcceptChannel(_acceptTimeout, callback, server);\n            }\n            catch (CommunicationObjectAbortedException)\n            {\n                return new CompletedAsyncResult<bool>(true, callback, server);\n            }\n            catch (CommunicationObjectFaultedException)\n            {\n                return new CompletedAsyncResult<bool>(true, callback, server);\n            }\n            catch (TimeoutException)\n            {\n                return new CompletedAsyncResult<bool>(false, callback, server);\n            }\n            catch (CommunicationException)\n            {\n                return new CompletedAsyncResult<bool>(false, callback, server);\n            }\n            catch\n            {\n                return new CompletedAsyncResult<bool>(false, callback, server);\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We never want to fail here so we have to catch all exceptions.\")]\n        private static bool EndTryAcceptChannel(IAsyncResult result, out IReplyChannel channel)\n        {\n            Contract.Assert(result != null);\n\n            CompletedAsyncResult<bool> handlerResult = result as CompletedAsyncResult<bool>;\n            if (handlerResult != null)\n            {\n                channel = null;\n                return CompletedAsyncResult<bool>.End(handlerResult);\n            }\n            else\n            {\n                try\n                {\n                    HttpSelfHostServer server = (HttpSelfHostServer)result.AsyncState;\n                    Contract.Assert(server != null);\n                    Contract.Assert(server._listener != null);\n                    channel = server._listener.EndAcceptChannel(result);\n                    return true;\n                }\n                catch (CommunicationObjectAbortedException)\n                {\n                    channel = null;\n                    return true;\n                }\n                catch (CommunicationObjectFaultedException)\n                {\n                    channel = null;\n                    return true;\n                }\n                catch (TimeoutException)\n                {\n                    channel = null;\n                    return false;\n                }\n                catch (CommunicationException)\n                {\n                    channel = null;\n                    return false;\n                }\n                catch\n                {\n                    channel = null;\n                    return false;\n                }\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We never want to fail here so we have to catch all exceptions.\")]\n        private void BeginOpenChannel(ChannelContext channelContext)\n        {\n            Contract.Assert(channelContext != null);\n            Contract.Assert(channelContext.Channel != null);\n\n            try\n            {\n                IAsyncResult result = channelContext.Channel.BeginOpen(_onOpenChannelComplete, channelContext);\n                if (result.CompletedSynchronously)\n                {\n                    OpenChannelComplete(result);\n                }\n            }\n            catch (Exception e)\n            {\n                FaultTask(channelContext.Server._openTaskCompletionSource, e);\n            }\n        }\n\n        private void OnOpenChannelComplete(IAsyncResult result)\n        {\n            Contract.Assert(result != null);\n\n            if (result.CompletedSynchronously)\n            {\n                return;\n            }\n\n            OpenChannelComplete(result);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We never want to fail here so we have to catch all exceptions.\")]\n        private void OpenChannelComplete(IAsyncResult result)\n        {\n            ChannelContext channelContext = (ChannelContext)result.AsyncState;\n            Contract.Assert(channelContext != null);\n            Contract.Assert(channelContext.Channel != null);\n\n            try\n            {\n                channelContext.Channel.EndOpen(result);\n\n                // The channel is open and we can complete the open task\n                CompleteTask(channelContext.Server._openTaskCompletionSource);\n\n                // Start pumping messages\n                int initialWindowSize = Math.Min(InitialWindowSize, _configuration.MaxConcurrentRequests);\n                Interlocked.Add(ref _windowSize, initialWindowSize);\n                for (int index = 0; index < initialWindowSize; index++)\n                {\n                    BeginReceiveRequestContext(channelContext);\n                }\n\n                // Start accepting next channel\n                BeginAcceptChannel(channelContext.Server);\n            }\n            catch (Exception e)\n            {\n                FaultTask(channelContext.Server._openTaskCompletionSource, e);\n            }\n        }\n\n        private void BeginReceiveRequestContext(ChannelContext context)\n        {\n            Contract.Assert(context != null);\n\n            if (context.Channel.State != CommunicationState.Opened)\n            {\n                return;\n            }\n\n            IAsyncResult result = BeginTryReceiveRequestContext(context, _onReceiveRequestContextComplete);\n            if (result.CompletedSynchronously)\n            {\n                ReceiveRequestContextComplete(result);\n            }\n        }\n\n        private void OnReceiveRequestContextComplete(IAsyncResult result)\n        {\n            if (result.CompletedSynchronously)\n            {\n                return;\n            }\n\n            ReceiveRequestContextComplete(result);\n        }\n\n        private void ReceiveRequestContextComplete(IAsyncResult result)\n        {\n            Contract.Assert(result != null);\n\n            ChannelContext channelContext = (ChannelContext)result.AsyncState;\n            Contract.Assert(channelContext != null);\n\n            System.ServiceModel.Channels.RequestContext requestContext;\n            if (EndTryReceiveRequestContext(result, out requestContext))\n            {\n                if (requestContext != null)\n                {\n                    Interlocked.Increment(ref _requestsOutstanding);\n                    if (TryIncreaseWindowSize())\n                    {\n                        // Spin off an additional BeginReceiveRequest to increase the window size by 1\n                        BeginReceiveRequestContext(channelContext);\n                    }\n                    ProcessRequestContext(channelContext, requestContext);\n                }\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We never want to fail here so we have to catch all exceptions.\")]\n        private static IAsyncResult BeginTryReceiveRequestContext(ChannelContext channelContext, AsyncCallback callback)\n        {\n            Contract.Assert(channelContext != null);\n            Contract.Assert(callback != null);\n\n            try\n            {\n                return channelContext.Channel.BeginTryReceiveRequest(_receiveTimeout, callback, channelContext);\n            }\n            catch (CommunicationObjectAbortedException)\n            {\n                return new CompletedAsyncResult<bool>(true, callback, channelContext);\n            }\n            catch (CommunicationObjectFaultedException)\n            {\n                return new CompletedAsyncResult<bool>(true, callback, channelContext);\n            }\n            catch (CommunicationException)\n            {\n                return new CompletedAsyncResult<bool>(false, callback, channelContext);\n            }\n            catch (TimeoutException)\n            {\n                return new CompletedAsyncResult<bool>(false, callback, channelContext);\n            }\n            catch\n            {\n                return new CompletedAsyncResult<bool>(false, callback, channelContext);\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We never want to fail here so we have to catch all exceptions.\")]\n        private static bool EndTryReceiveRequestContext(IAsyncResult result, out System.ServiceModel.Channels.RequestContext requestContext)\n        {\n            Contract.Assert(result != null);\n\n            CompletedAsyncResult<bool> handlerResult = result as CompletedAsyncResult<bool>;\n            if (handlerResult != null)\n            {\n                requestContext = null;\n                return CompletedAsyncResult<bool>.End(handlerResult);\n            }\n            else\n            {\n                try\n                {\n                    ChannelContext channelContext = (ChannelContext)result.AsyncState;\n                    Contract.Assert(channelContext != null, \"context cannot be null\");\n                    return channelContext.Channel.EndTryReceiveRequest(result, out requestContext);\n                }\n                catch (CommunicationObjectAbortedException)\n                {\n                    requestContext = null;\n                    return true;\n                }\n                catch (CommunicationObjectFaultedException)\n                {\n                    requestContext = null;\n                    return true;\n                }\n                catch (CommunicationException)\n                {\n                    requestContext = null;\n                    return false;\n                }\n                catch (TimeoutException)\n                {\n                    requestContext = null;\n                    return false;\n                }\n                catch\n                {\n                    requestContext = null;\n                    return false;\n                }\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We never want to fail here so we have to catch all exceptions.\")]\n        private void BeginReply(ReplyContext replyContext)\n        {\n            Contract.Assert(replyContext != null);\n\n            try\n            {\n                IAsyncResult result = replyContext.RequestContext.BeginReply(replyContext.Reply, _onReplyComplete, replyContext);\n                if (result.CompletedSynchronously)\n                {\n                    ReplyComplete(result);\n                }\n            }\n            catch\n            {\n                Interlocked.Decrement(ref _requestsOutstanding);\n                BeginNextRequest(replyContext.ChannelContext);\n                replyContext.Dispose();\n            }\n        }\n\n        private void OnReplyComplete(IAsyncResult result)\n        {\n            Contract.Assert(result != null);\n\n            if (result.CompletedSynchronously)\n            {\n                return;\n            }\n\n            ReplyComplete(result);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We never want to fail here so we have to catch all exceptions.\")]\n        private void ReplyComplete(IAsyncResult result)\n        {\n            ReplyContext replyContext = (ReplyContext)result.AsyncState;\n            Contract.Assert(replyContext != null);\n\n            try\n            {\n                replyContext.RequestContext.EndReply(result);\n            }\n            catch\n            {\n            }\n            finally\n            {\n                Interlocked.Decrement(ref _requestsOutstanding);\n                BeginNextRequest(replyContext.ChannelContext);\n                replyContext.Dispose();\n            }\n        }\n\n        private void BeginNextRequest(ChannelContext context)\n        {\n            if (TryDecreaseWindowSize())\n            {\n                // Decrease the window size by 1 by avoiding calling BeginReceiveRequest\n                return;\n            }\n\n            BeginReceiveRequestContext(context);\n        }\n\n        private bool TryIncreaseWindowSize()\n        {\n            if (ShouldIncreaseWindowSize())\n            {\n                // If we can't get the lock, just keep the window size the same\n                // It's better to keep the window size the same than risk affecting performance by waiting on a lock\n                // And if the lock is taken, some other thread is already updating the window size to a better value\n                if (Monitor.TryEnter(_windowSizeLock))\n                {\n                    try\n                    {\n                        // Recheck that we should increase the window size to guard for changes between the time we take the lock and the time we increase the window size\n                        if (ShouldIncreaseWindowSize())\n                        {\n                            // Increase Window Size\n                            _windowSize++;\n                            return true;\n                        }\n                    }\n                    finally\n                    {\n                        Monitor.Exit(_windowSizeLock);\n                    }\n                }\n            }\n            return false;\n        }\n\n        private bool TryDecreaseWindowSize()\n        {\n            if (ShouldDecreaseWindowSize())\n            {\n                // If we can't get the lock, just keep the window size the same\n                // It's better to keep the window size the same than risk affecting performance by waiting on a lock\n                // And if the lock is taken, some other thread is already updating the window size to a better value\n                if (Monitor.TryEnter(_windowSizeLock))\n                {\n                    try\n                    {\n                        // Recheck that we should decrease the window size to guard for changes between the time we take the lock and the time we increase the window size\n                        if (ShouldDecreaseWindowSize())\n                        {\n                            _windowSize--;\n                            return true;\n                        }\n                    }\n                    finally\n                    {\n                        Monitor.Exit(_windowSizeLock);\n                    }\n                }\n            }\n            return false;\n        }\n\n        private bool ShouldIncreaseWindowSize()\n        {\n            return _windowSize < _configuration.MaxConcurrentRequests && _requestsOutstanding > _windowSize * IncreaseWindowSizeRatio;\n        }\n\n        private bool ShouldDecreaseWindowSize()\n        {\n            return _windowSize > MinimumWindowSize && _requestsOutstanding < _windowSize * DecreaseWindowSizeRatio;\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We never want to fail here so we have to catch all exceptions.\")]\n        private static void BeginCloseListener(HttpSelfHostServer server)\n        {\n            Contract.Assert(server != null);\n\n            try\n            {\n                if (server._listener != null)\n                {\n                    IAsyncResult result = server._listener.BeginClose(_onCloseListenerComplete, server);\n                    if (result.CompletedSynchronously)\n                    {\n                        CloseListenerComplete(result);\n                    }\n                }\n            }\n            catch\n            {\n                CloseNextChannel(server);\n            }\n        }\n\n        private static void OnCloseListenerComplete(IAsyncResult result)\n        {\n            Contract.Assert(result != null);\n\n            if (result.CompletedSynchronously)\n            {\n                return;\n            }\n\n            CloseListenerComplete(result);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We never want to fail here so we have to catch all exceptions.\")]\n        private static void CloseListenerComplete(IAsyncResult result)\n        {\n            HttpSelfHostServer server = (HttpSelfHostServer)result.AsyncState;\n            Contract.Assert(server != null);\n            Contract.Assert(server._listener != null);\n\n            try\n            {\n                server._listener.EndClose(result);\n            }\n            catch\n            {\n            }\n            finally\n            {\n                CloseNextChannel(server);\n            }\n        }\n\n        private static void CloseNextChannel(HttpSelfHostServer server)\n        {\n            Contract.Assert(server != null);\n\n            IReplyChannel channel;\n            if (server._channels.TryTake(out channel))\n            {\n                BeginCloseChannel(new ChannelContext(server, channel));\n            }\n            else\n            {\n                CompleteTask(server._closeTaskCompletionSource);\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We never want to fail here so we have to catch all exceptions.\")]\n        private static void BeginCloseChannel(ChannelContext channelContext)\n        {\n            Contract.Assert(channelContext != null);\n\n            try\n            {\n                IAsyncResult result = channelContext.Channel.BeginClose(_onCloseChannelComplete, channelContext);\n                if (result.CompletedSynchronously)\n                {\n                    CloseChannelComplete(result);\n                }\n            }\n            catch\n            {\n                CloseNextChannel(channelContext.Server);\n            }\n        }\n\n        private static void OnCloseChannelComplete(IAsyncResult result)\n        {\n            Contract.Assert(result != null);\n\n            if (result.CompletedSynchronously)\n            {\n                return;\n            }\n\n            CloseChannelComplete(result);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We never want to fail here so we have to catch all exceptions.\")]\n        private static void CloseChannelComplete(IAsyncResult result)\n        {\n            ChannelContext channelContext = (ChannelContext)result.AsyncState;\n            Contract.Assert(channelContext != null);\n\n            try\n            {\n                channelContext.Channel.EndClose(result);\n            }\n            catch\n            {\n            }\n            finally\n            {\n                CloseNextChannel(channelContext.Server);\n            }\n        }\n\n        /// <summary>\n        /// Provides context for receiving an <see cref=\"System.ServiceModel.Channels.RequestContext\"/> instance asynchronously.\n        /// </summary>\n        private class ChannelContext\n        {\n            /// <summary>\n            /// Initializes a new instance of the <see cref=\"ChannelContext\"/> class.\n            /// </summary>\n            /// <param name=\"server\">The host to associate with this context.</param>\n            /// <param name=\"channel\">The channel to associate with this channel.</param>\n            public ChannelContext(HttpSelfHostServer server, IReplyChannel channel)\n            {\n                Contract.Assert(server != null);\n                Contract.Assert(channel != null);\n                Server = server;\n                Channel = channel;\n            }\n\n            /// <summary>\n            /// Gets the <see cref=\"HttpSelfHostServer\"/> instance.\n            /// </summary>\n            /// <value>\n            /// The <see cref=\"HttpSelfHostServer\"/> instance.\n            /// </value>\n            public HttpSelfHostServer Server { get; private set; }\n\n            /// <summary>\n            /// Gets the <see cref=\"IReplyChannel\"/> instance.\n            /// </summary>\n            /// <value>\n            /// The <see cref=\"System.ServiceModel.Channels.RequestContext\"/> instance.\n            /// </value>\n            public IReplyChannel Channel { get; private set; }\n        }\n\n        /// <summary>\n        /// Provides context for sending a <see cref=\"System.ServiceModel.Channels.Message\"/> instance asynchronously in response\n        /// to a request.\n        /// </summary>\n        private class ReplyContext : IDisposable\n        {\n            private bool _disposed;\n\n            /// <summary>\n            /// Initializes a new instance of the <see cref=\"ChannelContext\"/> class.\n            /// </summary>\n            /// <param name=\"channelContext\">The channel context to associate with this reply context.</param>\n            /// <param name=\"requestContext\">The request context to associate with this reply context.</param>\n            /// <param name=\"reply\">The reply to associate with this reply context.</param>\n            public ReplyContext(ChannelContext channelContext, RequestContext requestContext, Message reply)\n            {\n                Contract.Assert(channelContext != null);\n                Contract.Assert(requestContext != null);\n                Contract.Assert(reply != null);\n\n                ChannelContext = channelContext;\n                RequestContext = requestContext;\n                Reply = reply;\n            }\n\n            /// <summary>\n            /// Gets the <see cref=\"ChannelContext\"/> instance.\n            /// </summary>\n            /// <value>\n            /// The <see cref=\"ChannelContext\"/> instance.\n            /// </value>\n            public ChannelContext ChannelContext { get; private set; }\n\n            /// <summary>\n            /// Gets the <see cref=\"System.ServiceModel.Channels.RequestContext\"/> instance.\n            /// </summary>\n            /// <value>\n            /// The <see cref=\"System.ServiceModel.Channels.RequestContext\"/> instance.\n            /// </value>\n            public RequestContext RequestContext { get; private set; }\n\n            /// <summary>\n            /// Gets the reply <see cref=\"System.ServiceModel.Channels.Message\"/> instance.\n            /// </summary>\n            /// <value>\n            /// The reply <see cref=\"System.ServiceModel.Channels.Message\"/> instance.\n            /// </value>\n            public Message Reply { get; private set; }\n\n            /// <summary>\n            /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged SRResources.\n            /// </summary>\n            public void Dispose()\n            {\n                Dispose(true);\n                GC.SuppressFinalize(this);\n            }\n\n            /// <summary>\n            /// Releases unmanaged and - optionally - managed resources\n            /// </summary>\n            /// <param name=\"disposing\"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged SRResources.</param>\n            [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We never want to fail here so we have to catch all exceptions.\")]\n            protected virtual void Dispose(bool disposing)\n            {\n                if (!_disposed)\n                {\n                    if (disposing)\n                    {\n                        // RequestContext.Close can throw if the client disconnects before it finishes receiving the response\n                        // Catch here to avoid throwing in a Dispose method\n                        try\n                        {\n                            RequestContext.Close();\n                        }\n                        catch\n                        {\n                        }\n\n                        // HttpMessage.Close can throw if the request message throws in its Dispose implementation\n                        // Catch here to avoid throwing in a Dispose method\n                        try\n                        {\n                            Reply.Close();\n                        }\n                        catch\n                        {\n                        }\n                    }\n\n                    _disposed = true;\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/Properties/AssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\n\n[assembly: AssemblyTitle(\"System.Web.Http.SelfHost\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: InternalsVisibleTo(\"System.Web.Http.SelfHost.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/Properties/SRResources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.239\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace System.Web.Http.SelfHost.Properties {\n    using System;\n    \n    \n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class SRResources {\n        \n        private static global::System.Resources.ResourceManager resourceMan;\n        \n        private static global::System.Globalization.CultureInfo resourceCulture;\n        \n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal SRResources() {\n        }\n        \n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"System.Web.Http.SelfHost.Properties.SRResources\", typeof(SRResources).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n        \n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to End cannot be called twice on an AsyncResult..\n        /// </summary>\n        internal static string AsyncResultAlreadyEnded {\n            get {\n                return ResourceManager.GetString(\"AsyncResultAlreadyEnded\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The IAsyncResult implementation &apos;{0}&apos; 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..\n        /// </summary>\n        internal static string AsyncResultCompletedTwice {\n            get {\n                return ResourceManager.GetString(\"AsyncResultCompletedTwice\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The size quota for this stream ({0}) has been exceeded..\n        /// </summary>\n        internal static string BufferedOutputStreamQuotaExceeded {\n            get {\n                return ResourceManager.GetString(\"BufferedOutputStreamQuotaExceeded\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to ClientCredentialType must be set to Certificate when a X509CertificateValidator is specified on the HttpSelfHostConfiguration..\n        /// </summary>\n        internal static string CannotUseOtherClientCredentialTypeWithX509CertificateValidator {\n            get {\n                return ResourceManager.GetString(\"CannotUseOtherClientCredentialTypeWithX509CertificateValidator\", resourceCulture);\n            }\n        }\n\n        /// <summary>\n        ///   Looks up a localized string similar to ClientCredentialType must be set to Certificate when a UserNamePasswordValidator is specified on the HttpSelfHostConfiguration..\n        /// </summary>\n        internal static string CannotUseOtherClientCredentialTypeWithUserNamePasswordValidator\n        {\n            get\n            {\n                return ResourceManager.GetString(\"CannotUseOtherClientCredentialTypeWithUserNamePasswordValidator\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Certificate-based client authentication is not supported in TransportCredentialOnly security mode. Select the Transport security mode..\n        /// </summary>\n        internal static string CertificateUnsupportedForHttpTransportCredentialOnly {\n            get {\n                return ResourceManager.GetString(\"CertificateUnsupportedForHttpTransportCredentialOnly\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &apos;{0}&apos; type does not support building &apos;{1}&apos; instances..\n        /// </summary>\n        internal static string ChannelFactoryNotSupported {\n            get {\n                return ResourceManager.GetString(\"ChannelFactoryNotSupported\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &apos;{0}&apos; type does not support the &apos;{1}&apos; channel shape. Implement the &apos;{2}&apos; channel shape to use this type..\n        /// </summary>\n        internal static string ChannelShapeNotSupported {\n            get {\n                return ResourceManager.GetString(\"ChannelShapeNotSupported\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The message version of the outgoing message ({0}) does not match that of the encoder ({1}). Make sure the binding is configured with the same version as the message..\n        /// </summary>\n        internal static string EncoderMessageVersionMismatch {\n            get {\n                return ResourceManager.GetString(\"EncoderMessageVersionMismatch\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &apos;{0}&apos; type does not support a session encoder..\n        /// </summary>\n        internal static string HttpMessageEncoderFactoryDoesNotSupportSessionEncoder {\n            get {\n                return ResourceManager.GetString(\"HttpMessageEncoderFactoryDoesNotSupportSessionEncoder\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Could not obtain an HTTP request from message of type &apos;{0}&apos;..\n        /// </summary>\n        internal static string HttpMessageHandlerInvalidMessage {\n            get {\n                return ResourceManager.GetString(\"HttpMessageHandlerInvalidMessage\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to This &apos;{0}&apos; instance has already been started once. To start another instance, please create a new &apos;{0}&apos; object and start that..\n        /// </summary>\n        internal static string HttpServerAlreadyRunning {\n            get {\n                return ResourceManager.GetString(\"HttpServerAlreadyRunning\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The inner listener factory of {0} must be set before this operation..\n        /// </summary>\n        internal static string InnerListenerFactoryNotSet {\n            get {\n                return ResourceManager.GetString(\"InnerListenerFactoryNotSet\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to An incorrect IAsyncResult was provided to an &apos;End&apos; method. The IAsyncResult object passed to &apos;End&apos; must be the one returned from the matching &apos;Begin&apos; or passed to the callback provided to &apos;Begin&apos;..\n        /// </summary>\n        internal static string InvalidAsyncResult {\n            get {\n                return ResourceManager.GetString(\"InvalidAsyncResult\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to An incorrect implementation of the IAsyncResult interface may be returning incorrect values from the CompletedSynchronously property or calling the AsyncCallback more than once. The type {0} could be the incorrect implementation..\n        /// </summary>\n        internal static string InvalidAsyncResultImplementation {\n            get {\n                return ResourceManager.GetString(\"InvalidAsyncResultImplementation\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to An incorrect implementation of the IAsyncResult interface may be returning incorrect values from the CompletedSynchronously property or calling the AsyncCallback more than once..\n        /// </summary>\n        internal static string InvalidAsyncResultImplementationGeneric {\n            get {\n                return ResourceManager.GetString(\"InvalidAsyncResultImplementationGeneric\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Error creating &apos;{0}&apos; instance using &apos;{1}&apos;..\n        /// </summary>\n        internal static string InvalidChannelListener {\n            get {\n                return ResourceManager.GetString(\"InvalidChannelListener\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A null value was returned from an async &apos;Begin&apos; method or passed to an AsyncCallback. Async &apos;Begin&apos; implementations must return a non-null IAsyncResult and pass the same IAsyncResult object as the parameter to the AsyncCallback..\n        /// </summary>\n        internal static string InvalidNullAsyncResult {\n            get {\n                return ResourceManager.GetString(\"InvalidNullAsyncResult\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to HTTP request message body with a content length of &apos;{0}&apos; bytes..\n        /// </summary>\n        internal static string MessageBodyIsHttpRequestMessageWithKnownContentLength {\n            get {\n                return ResourceManager.GetString(\"MessageBodyIsHttpRequestMessageWithKnownContentLength\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to HTTP request message body with an undetermined content length..\n        /// </summary>\n        internal static string MessageBodyIsHttpRequestMessageWithUnknownContentLength {\n            get {\n                return ResourceManager.GetString(\"MessageBodyIsHttpRequestMessageWithUnknownContentLength\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to HTTP response message body with a content length of &apos;{0}&apos; bytes..\n        /// </summary>\n        internal static string MessageBodyIsHttpResponseMessageWithKnownContentLength {\n            get {\n                return ResourceManager.GetString(\"MessageBodyIsHttpResponseMessageWithKnownContentLength\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to HTTP response message body with an undetermined content length..\n        /// </summary>\n        internal static string MessageBodyIsHttpResponseMessageWithUnknownContentLength {\n            get {\n                return ResourceManager.GetString(\"MessageBodyIsHttpResponseMessageWithUnknownContentLength\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &apos;{0}&apos; is closed and can no longer be used..\n        /// </summary>\n        internal static string MessageClosed {\n            get {\n                return ResourceManager.GetString(\"MessageClosed\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The response message is not valid for the encoder used by the &apos;{0}&apos; binding, which requires that the response message have been created with the &apos;{1}&apos; extension method on the &apos;{2}&apos; class..\n        /// </summary>\n        internal static string MessageInvalidForHttpMessageEncoder {\n            get {\n                return ResourceManager.GetString(\"MessageInvalidForHttpMessageEncoder\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The message instance does not support being read, written out or copied. Use the &apos;{0}&apos; or &apos;{1}&apos; extension methods on the &apos;{2}&apos; class to access the message content..\n        /// </summary>\n        internal static string MessageReadWriteCopyNotSupported {\n            get {\n                return ResourceManager.GetString(\"MessageReadWriteCopyNotSupported\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The message instance is non-empty but the &apos;{0}&apos; extension method on the &apos;{1}&apos; class returned null. Message instances that do not support the &apos;{0}&apos; extension method must be empty. .\n        /// </summary>\n        internal static string NonHttpMessageMustBeEmpty {\n            get {\n                return ResourceManager.GetString(\"NonHttpMessageMustBeEmpty\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Nonnegative number required.\n        /// </summary>\n        internal static string NonnegativeNumberRequired {\n            get {\n                return ResourceManager.GetString(\"NonnegativeNumberRequired\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &apos;{0}&apos; type supports only MessageVersion.None. .\n        /// </summary>\n        internal static string OnlyMessageVersionNoneSupportedOnHttpMessageEncodingBindingElement {\n            get {\n                return ResourceManager.GetString(\"OnlyMessageVersionNoneSupportedOnHttpMessageEncodingBindingElement\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The value of the &apos;{0}&apos; parameter must be less than or equal to the value of the &apos;{1}&apos; parameter..\n        /// </summary>\n        internal static string ParameterMustBeLessThanOrEqualSecondParameter {\n            get {\n                return ResourceManager.GetString(\"ParameterMustBeLessThanOrEqualSecondParameter\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Read not supported on this stream..\n        /// </summary>\n        internal static string ReadNotSupported {\n            get {\n                return ResourceManager.GetString(\"ReadNotSupported\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Processing of the request was cancelled..\n        /// </summary>\n        internal static string RequestCancelled {\n            get {\n                return ResourceManager.GetString(\"RequestCancelled\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The incoming message does not have the required &apos;{0}&apos; property of type &apos;{1}&apos;..\n        /// </summary>\n        internal static string RequestMissingHttpRequestMessageProperty {\n            get {\n                return ResourceManager.GetString(\"RequestMissingHttpRequestMessageProperty\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The incoming message does not have the required &apos;To&apos; header..\n        /// </summary>\n        internal static string RequestMissingToHeader {\n            get {\n                return ResourceManager.GetString(\"RequestMissingToHeader\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Seek not supported on this stream..\n        /// </summary>\n        internal static string SeekNotSupported {\n            get {\n                return ResourceManager.GetString(\"SeekNotSupported\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Value must be non-negative..\n        /// </summary>\n        internal static string ValueMustBeNonNegative {\n            get {\n                return ResourceManager.GetString(\"ValueMustBeNonNegative\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/Properties/SRResources.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"AsyncResultAlreadyEnded\" xml:space=\"preserve\">\n    <value>End cannot be called twice on an AsyncResult.</value>\n  </data>\n  <data name=\"AsyncResultCompletedTwice\" xml:space=\"preserve\">\n    <value>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.</value>\n  </data>\n  <data name=\"CannotUseOtherClientCredentialTypeWithUserNamePasswordValidator\" xml:space=\"preserve\">\n    <value>ClientCredentialType must be set to Basic when a UserNamePasswordValidator is specified on the HttpSelfHostConfiguration.</value>\n  </data>\n  <data name=\"CannotUseOtherClientCredentialTypeWithX509CertificateValidator\" xml:space=\"preserve\">\n    <value>ClientCredentialType must be set to Certificate when a X509CertificateValidator is specified on the HttpSelfHostConfiguration.</value>\n  </data>\n  <data name=\"CertificateUnsupportedForHttpTransportCredentialOnly\" xml:space=\"preserve\">\n    <value>Certificate-based client authentication is not supported in TransportCredentialOnly security mode. Select the Transport security mode.</value>\n  </data>\n  <data name=\"ChannelFactoryNotSupported\" xml:space=\"preserve\">\n    <value>The '{0}' type does not support building '{1}' instances.</value>\n  </data>\n  <data name=\"ChannelShapeNotSupported\" xml:space=\"preserve\">\n    <value>The '{0}' type does not support the '{1}' channel shape. Implement the '{2}' channel shape to use this type.</value>\n  </data>\n  <data name=\"EncoderMessageVersionMismatch\" xml:space=\"preserve\">\n    <value>The message version of the outgoing message ({0}) does not match that of the encoder ({1}). Make sure the binding is configured with the same version as the message.</value>\n  </data>\n  <data name=\"HttpMessageEncoderFactoryDoesNotSupportSessionEncoder\" xml:space=\"preserve\">\n    <value>The '{0}' type does not support a session encoder.</value>\n  </data>\n  <data name=\"HttpMessageHandlerInvalidMessage\" xml:space=\"preserve\">\n    <value>Could not obtain an HTTP request from message of type '{0}'.</value>\n  </data>\n  <data name=\"HttpServerAlreadyRunning\" xml:space=\"preserve\">\n    <value>This '{0}' instance has already been started once. To start another instance, please create a new '{0}' object and start that.</value>\n  </data>\n  <data name=\"InnerListenerFactoryNotSet\" xml:space=\"preserve\">\n    <value>The inner listener factory of {0} must be set before this operation.</value>\n  </data>\n  <data name=\"InvalidAsyncResult\" xml:space=\"preserve\">\n    <value>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'.</value>\n  </data>\n  <data name=\"InvalidAsyncResultImplementation\" xml:space=\"preserve\">\n    <value>An incorrect implementation of the IAsyncResult interface may be returning incorrect values from the CompletedSynchronously property or calling the AsyncCallback more than once. The type {0} could be the incorrect implementation.</value>\n  </data>\n  <data name=\"InvalidAsyncResultImplementationGeneric\" xml:space=\"preserve\">\n    <value>An incorrect implementation of the IAsyncResult interface may be returning incorrect values from the CompletedSynchronously property or calling the AsyncCallback more than once.</value>\n  </data>\n  <data name=\"InvalidChannelListener\" xml:space=\"preserve\">\n    <value>Error creating '{0}' instance using '{1}'.</value>\n  </data>\n  <data name=\"InvalidNullAsyncResult\" xml:space=\"preserve\">\n    <value>A null value was returned from an async 'Begin' method or passed to an AsyncCallback. Async 'Begin' implementations must return a non-null IAsyncResult and pass the same IAsyncResult object as the parameter to the AsyncCallback.</value>\n  </data>\n  <data name=\"MessageBodyIsHttpRequestMessageWithKnownContentLength\" xml:space=\"preserve\">\n    <value>HTTP request message body with a content length of '{0}' bytes.</value>\n  </data>\n  <data name=\"MessageBodyIsHttpRequestMessageWithUnknownContentLength\" xml:space=\"preserve\">\n    <value>HTTP request message body with an undetermined content length.</value>\n  </data>\n  <data name=\"MessageBodyIsHttpResponseMessageWithKnownContentLength\" xml:space=\"preserve\">\n    <value>HTTP response message body with a content length of '{0}' bytes.</value>\n  </data>\n  <data name=\"MessageBodyIsHttpResponseMessageWithUnknownContentLength\" xml:space=\"preserve\">\n    <value>HTTP response message body with an undetermined content length.</value>\n  </data>\n  <data name=\"MessageClosed\" xml:space=\"preserve\">\n    <value>The '{0}' is closed and can no longer be used.</value>\n  </data>\n  <data name=\"MessageInvalidForHttpMessageEncoder\" xml:space=\"preserve\">\n    <value>The response message is not valid for the encoder used by the '{0}' binding, which requires that the response message have been created with the '{1}' extension method on the '{2}' class.</value>\n  </data>\n  <data name=\"MessageReadWriteCopyNotSupported\" xml:space=\"preserve\">\n    <value>The message instance does not support being read, written out or copied. Use the '{0}' or '{1}' extension methods on the '{2}' class to access the message content.</value>\n  </data>\n  <data name=\"NonHttpMessageMustBeEmpty\" xml:space=\"preserve\">\n    <value>The message instance is non-empty but the '{0}' extension method on the '{1}' class returned null. Message instances that do not support the '{0}' extension method must be empty. </value>\n  </data>\n  <data name=\"NonnegativeNumberRequired\" xml:space=\"preserve\">\n    <value>Nonnegative number required</value>\n  </data>\n  <data name=\"OnlyMessageVersionNoneSupportedOnHttpMessageEncodingBindingElement\" xml:space=\"preserve\">\n    <value>The '{0}' type supports only MessageVersion.None. </value>\n  </data>\n  <data name=\"ParameterMustBeLessThanOrEqualSecondParameter\" xml:space=\"preserve\">\n    <value>The value of the '{0}' parameter must be less than or equal to the value of the '{1}' parameter.</value>\n  </data>\n  <data name=\"RequestMissingHttpRequestMessageProperty\" xml:space=\"preserve\">\n    <value>The incoming message does not have the required '{0}' property of type '{1}'.</value>\n  </data>\n  <data name=\"RequestMissingToHeader\" xml:space=\"preserve\">\n    <value>The incoming message does not have the required 'To' header.</value>\n  </data>\n  <data name=\"BufferedOutputStreamQuotaExceeded\" xml:space=\"preserve\">\n    <value>The size quota for this stream ({0}) has been exceeded.</value>\n  </data>\n  <data name=\"ReadNotSupported\" xml:space=\"preserve\">\n    <value>Read not supported on this stream.</value>\n  </data>\n  <data name=\"SeekNotSupported\" xml:space=\"preserve\">\n    <value>Seek not supported on this stream.</value>\n  </data>\n  <data name=\"ValueMustBeNonNegative\" xml:space=\"preserve\">\n    <value>Value must be non-negative.</value>\n  </data>\n  <data name=\"RequestCancelled\" xml:space=\"preserve\">\n    <value>Processing of the request was cancelled.</value>\n  </data>\n</root>"
  },
  {
    "path": "src/System.Web.Http.SelfHost/SelfHostHttpRequestContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.IdentityModel.Claims;\nusing System.Net;\nusing System.Net.Http;\nusing System.Security.Cryptography.X509Certificates;\nusing System.Security.Principal;\nusing System.ServiceModel;\nusing System.ServiceModel.Channels;\nusing System.ServiceModel.Security;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.Routing;\nusing System.Web.Http.SelfHost.Channels;\nusing System.Web.Http.SelfHost.Properties;\nusing System.Web.Http.SelfHost.ServiceModel.Channels;\n\nnamespace System.Web.Http.SelfHost\n{\n    internal class SelfHostHttpRequestContext : HttpRequestContext\n    {\n        private readonly RequestContext _requestContext;\n        private readonly HttpRequestMessage _request;\n\n        private HttpConfiguration _configuration;\n\n        private X509Certificate2 _clientCertificate;\n        private bool _clientCertificateSet;\n\n        private bool _includeErrorDetail;\n        private bool _includeErrorDetailSet;\n\n        private bool _isLocal;\n        private bool _isLocalSet;\n\n        private UrlHelper _url;\n        private bool _urlSet;\n\n        private string _virtualPathRoot;\n        private bool _virtualPathRootSet;\n\n        public SelfHostHttpRequestContext(RequestContext requestContext, HttpConfiguration configuration,\n            HttpRequestMessage request)\n        {\n            Contract.Assert(requestContext != null);\n            Contract.Assert(configuration != null);\n            Contract.Assert(request != null);\n            _requestContext = requestContext;\n            _configuration = configuration;\n            _request = request;\n        }\n\n        public RequestContext RequestContext\n        {\n            get { return _requestContext; }\n        }\n\n        public HttpRequestMessage Request\n        {\n            get { return _request; }\n        }\n\n        // RouteData is not overridden; it is provided in a later point in the pipeline (HttpRoutingDispatcher).\n\n        public override X509Certificate2 ClientCertificate\n        {\n            get\n            {\n                if (!_clientCertificateSet)\n                {\n                    _clientCertificate = HttpSelfHostServer.RetrieveClientCertificate(_request);\n                    _clientCertificateSet = true;\n                }\n\n                return _clientCertificate;\n            }\n            set\n            {\n                _clientCertificate = value;\n                _clientCertificateSet = true;\n            }\n        }\n\n        public override HttpConfiguration Configuration\n        {\n            get\n            {\n                return _configuration;\n            }\n            set\n            {\n                _configuration = value;\n            }\n        }\n\n        public override bool IncludeErrorDetail\n        {\n            get\n            {\n                if (!_includeErrorDetailSet)\n                {\n                    IncludeErrorDetailPolicy includeErrorDetailPolicy;\n\n                    if (_configuration != null)\n                    {\n                        includeErrorDetailPolicy = _configuration.IncludeErrorDetailPolicy;\n                    }\n                    else\n                    {\n                        includeErrorDetailPolicy = IncludeErrorDetailPolicy.Default;\n                    }\n\n                    bool value;\n\n                    switch (includeErrorDetailPolicy)\n                    {\n                        case IncludeErrorDetailPolicy.Default:\n                        case IncludeErrorDetailPolicy.LocalOnly:\n                            value = IsLocal;\n                            break;\n\n                        case IncludeErrorDetailPolicy.Always:\n                            value = true;\n                            break;\n\n                        case IncludeErrorDetailPolicy.Never:\n                        default:\n                            value = false;\n                            break;\n                    }\n\n                    _includeErrorDetail = value;\n                    _includeErrorDetailSet = true;\n                }\n\n                return _includeErrorDetail;\n            }\n            set\n            {\n                _includeErrorDetail = value;\n                _includeErrorDetailSet = true;\n            }\n        }\n\n        public override bool IsLocal\n        {\n            get\n            {\n                if (!_isLocalSet)\n                {\n                    _isLocal = HttpSelfHostServer.IsLocal(_requestContext.RequestMessage);\n                    _isLocalSet = true;\n                }\n\n                return _isLocal;\n            }\n            set\n            {\n                _isLocal = value;\n                _isLocalSet = true;\n            }\n        }\n\n        public override IPrincipal Principal\n        {\n            get\n            {\n                return Thread.CurrentPrincipal;\n            }\n            set\n            {\n                Thread.CurrentPrincipal = value;\n            }\n        }\n\n        public override UrlHelper Url\n        {\n            get\n            {\n                if (!_urlSet)\n                {\n                    _url = new UrlHelper(_request);\n                    _urlSet = true;\n                }\n\n                return _url;\n            }\n            set\n            {\n                _url = value;\n                _urlSet = true;\n            }\n        }\n\n        public override string VirtualPathRoot\n        {\n            get\n            {\n                if (!_virtualPathRootSet)\n                {\n                    string value;\n\n                    if (_configuration != null)\n                    {\n                        value = _configuration.VirtualPathRoot;\n                    }\n                    else\n                    {\n                        value = \"/\";\n                    }\n\n                    _virtualPathRoot = value;\n                    _virtualPathRootSet = true;\n                }\n\n                return _virtualPathRoot;\n            }\n            set\n            {\n                _virtualPathRoot = value;\n                _virtualPathRootSet = true;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/ServiceModel/Channels/AsyncResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Threading;\nusing System.Web.Http.SelfHost.Properties;\n\nnamespace System.Web.Http.SelfHost.ServiceModel.Channels\n{\n    // AsyncResult starts acquired; Complete releases.\n    [SuppressMessage(\"Microsoft.Design\", \"CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable\", Justification = \"Ported from WCF\")]\n    internal abstract class AsyncResult : IAsyncResult\n    {\n        private static AsyncCallback _asyncCompletionWrapperCallback;\n        private readonly AsyncCallback _completionCallback;\n        private bool _completedSynchronously;\n        private bool _endCalled;\n        private Exception _exception;\n        private bool _isCompleted;\n        private AsyncCompletion _nextAsyncCompletion;\n        private readonly object _state;\n        private Action _beforePrepareAsyncCompletionAction;\n        private Func<IAsyncResult, bool> _checkSyncValidationFunc;\n        private ManualResetEvent _manualResetEvent;\n        private readonly object _manualResetEventLock = new object();\n\n        protected AsyncResult(AsyncCallback callback, object state)\n        {\n            _completionCallback = callback;\n            _state = state;\n        }\n\n        /// <summary>\n        /// Can be utilized by subclasses to write core completion code for both the sync and async paths\n        /// in one location, signalling chainable synchronous completion with the boolean result,\n        /// and leveraging PrepareAsyncCompletion for conversion to an AsyncCallback.\n        /// </summary>\n        /// <remarks>NOTE: requires that \"this\" is passed in as the state object to the asynchronous sub-call being used with a completion routine.</remarks>\n        protected delegate bool AsyncCompletion(IAsyncResult result);\n\n        public object AsyncState\n        {\n            get { return _state; }\n        }\n\n        public WaitHandle AsyncWaitHandle\n        {\n            get\n            {\n                lock (_manualResetEventLock)\n                {\n                    if (_manualResetEvent == null)\n                    {\n                        _manualResetEvent = new ManualResetEvent(_isCompleted);\n                    }\n                }\n\n                return _manualResetEvent;\n            }\n        }\n\n        public bool CompletedSynchronously\n        {\n            get { return _completedSynchronously; }\n        }\n\n        public bool HasCallback\n        {\n            get { return _completionCallback != null; }\n        }\n\n        public bool IsCompleted\n        {\n            get { return _isCompleted; }\n        }\n\n        // used in conjunction with PrepareAsyncCompletion to allow for finally blocks\n        protected Action<AsyncResult, Exception> OnCompleting { get; set; }\n\n        // subclasses like TraceAsyncResult can use this to wrap the callback functionality in a scope\n        protected Action<AsyncCallback, IAsyncResult> VirtualCallback { get; set; }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Exception is propagated or FailFast\")]\n        protected void Complete(bool didCompleteSynchronously)\n        {\n            if (_isCompleted)\n            {\n                throw Error.InvalidOperation(SRResources.AsyncResultCompletedTwice, GetType());\n            }\n\n            _completedSynchronously = didCompleteSynchronously;\n            if (OnCompleting != null)\n            {\n                // Allow exception replacement, like a catch/throw pattern.\n                try\n                {\n                    OnCompleting(this, _exception);\n                }\n                catch (Exception e)\n                {\n                    _exception = e;\n                }\n            }\n\n            if (didCompleteSynchronously)\n            {\n                // If we completedSynchronously, then there's no chance that the manualResetEvent was created so\n                // we don't need to worry about a race\n                Contract.Assert(_manualResetEvent == null, \"No ManualResetEvent should be created for a synchronous AsyncResult.\");\n                _isCompleted = true;\n            }\n            else\n            {\n                lock (_manualResetEventLock)\n                {\n                    _isCompleted = true;\n                    if (_manualResetEvent != null)\n                    {\n                        _manualResetEvent.Set();\n                    }\n                }\n            }\n\n            if (_completionCallback != null)\n            {\n                try\n                {\n                    if (VirtualCallback != null)\n                    {\n                        VirtualCallback(_completionCallback, this);\n                    }\n                    else\n                    {\n                        _completionCallback(this);\n                    }\n                }\n#pragma warning disable 1634\n#pragma warning suppress 56500 // transferring exception to another thread\n                catch (Exception e)\n                {\n                    // String is not resourced because it occurs only in debug build, only with a fatal assert,\n                    // and because it appears as an unused resource in a release build\n                    Contract.Assert(false, Error.Format(\"{0}{1}{2}\", \"Async Callback threw an exception.\", Environment.NewLine, e.ToString()));\n                }\n#pragma warning restore 1634\n            }\n        }\n\n        protected void Complete(bool didCompleteSynchronously, Exception error)\n        {\n            _exception = error;\n            Complete(didCompleteSynchronously);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Exception is propagated\")]\n        private static void AsyncCompletionWrapperCallback(IAsyncResult result)\n        {\n            if (result == null)\n            {\n                throw Error.InvalidOperation(SRResources.InvalidNullAsyncResult);\n            }\n            if (result.CompletedSynchronously)\n            {\n                return;\n            }\n\n            AsyncResult thisPtr = (AsyncResult)result.AsyncState;\n            if (!thisPtr.OnContinueAsyncCompletion(result))\n            {\n                return;\n            }\n\n            AsyncCompletion callback = thisPtr.GetNextCompletion();\n            if (callback == null)\n            {\n                ThrowInvalidAsyncResult(result);\n            }\n\n            bool completeSelf = false;\n            Exception completionException = null;\n            try\n            {\n                completeSelf = callback(result);\n            }\n            catch (Exception e)\n            {\n                completeSelf = true;\n                completionException = e;\n            }\n\n            if (completeSelf)\n            {\n                thisPtr.Complete(false, completionException);\n            }\n        }\n\n        // Note: this should be only derived by the TransactedAsyncResult\n        protected virtual bool OnContinueAsyncCompletion(IAsyncResult result)\n        {\n            return true;\n        }\n\n        // Note: this should be used only by the TransactedAsyncResult\n        protected void SetBeforePrepareAsyncCompletionAction(Action completionAction)\n        {\n            _beforePrepareAsyncCompletionAction = completionAction;\n        }\n\n        // Note: this should be used only by the TransactedAsyncResult\n        protected void SetCheckSyncValidationFunc(Func<IAsyncResult, bool> validationFunc)\n        {\n            _checkSyncValidationFunc = validationFunc;\n        }\n\n        protected AsyncCallback PrepareAsyncCompletion(AsyncCompletion callback)\n        {\n            if (_beforePrepareAsyncCompletionAction != null)\n            {\n                _beforePrepareAsyncCompletionAction();\n            }\n\n            _nextAsyncCompletion = callback;\n            if (AsyncResult._asyncCompletionWrapperCallback == null)\n            {\n                AsyncResult._asyncCompletionWrapperCallback = new AsyncCallback(AsyncCompletionWrapperCallback);\n            }\n            return AsyncResult._asyncCompletionWrapperCallback;\n        }\n\n        protected bool CheckSyncContinue(IAsyncResult result)\n        {\n            AsyncCompletion dummy;\n            return TryContinueHelper(result, out dummy);\n        }\n\n        protected bool SyncContinue(IAsyncResult result)\n        {\n            AsyncCompletion callback;\n            if (TryContinueHelper(result, out callback))\n            {\n                return callback(result);\n            }\n            else\n            {\n                return false;\n            }\n        }\n\n        private bool TryContinueHelper(IAsyncResult result, out AsyncCompletion callback)\n        {\n            if (result == null)\n            {\n                throw Error.InvalidOperation(SRResources.InvalidNullAsyncResult);\n            }\n\n            callback = null;\n            if (_checkSyncValidationFunc != null)\n            {\n                if (!_checkSyncValidationFunc(result))\n                {\n                    return false;\n                }\n            }\n            else if (!result.CompletedSynchronously)\n            {\n                return false;\n            }\n\n            callback = GetNextCompletion();\n            if (callback == null)\n            {\n                ThrowInvalidAsyncResult(\"Only call Check/SyncContinue once per async operation (once per PrepareAsyncCompletion).\");\n            }\n            return true;\n        }\n\n        private AsyncCompletion GetNextCompletion()\n        {\n            AsyncCompletion result = _nextAsyncCompletion;\n            _nextAsyncCompletion = null;\n            return result;\n        }\n\n        protected static void ThrowInvalidAsyncResult(IAsyncResult result)\n        {\n            if (result == null)\n            {\n                throw Error.ArgumentNull(\"result\");\n            }\n\n            throw Error.InvalidOperation(SRResources.InvalidAsyncResultImplementation, result.GetType());\n        }\n\n        protected static void ThrowInvalidAsyncResult(string debugText)\n        {\n            string message = SRResources.InvalidAsyncResultImplementationGeneric;\n            if (debugText != null)\n            {\n#if DEBUG\n                message += \" \" + debugText;\n#endif\n            }\n            throw Error.InvalidOperation(message);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1004:GenericMethodsShouldProvideTypeParameter\", Justification = \"Existing API\")]\n        protected static TAsyncResult End<TAsyncResult>(IAsyncResult result)\n            where TAsyncResult : AsyncResult\n        {\n            if (result == null)\n            {\n                throw Error.ArgumentNull(\"result\");\n            }\n\n            TAsyncResult asyncResult = result as TAsyncResult;\n\n            if (asyncResult == null)\n            {\n                throw Error.Argument(\"result\", SRResources.InvalidAsyncResult);\n            }\n\n            if (asyncResult._endCalled)\n            {\n                throw Error.InvalidOperation(SRResources.AsyncResultAlreadyEnded);\n            }\n\n            asyncResult._endCalled = true;\n\n            if (!asyncResult._isCompleted)\n            {\n                asyncResult.AsyncWaitHandle.WaitOne();\n            }\n\n            if (asyncResult._manualResetEvent != null)\n            {\n                asyncResult._manualResetEvent.Close();\n            }\n\n            if (asyncResult._exception != null)\n            {\n                throw asyncResult._exception;\n            }\n\n            return asyncResult;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/ServiceModel/Channels/BufferManagerOutputStream.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ServiceModel;\nusing System.ServiceModel.Channels;\n\nnamespace System.Web.Http.SelfHost.ServiceModel.Channels\n{\n    internal class BufferManagerOutputStream : BufferedOutputStream\n    {\n        private readonly string _quotaExceededString;\n\n        public BufferManagerOutputStream(string quotaExceededString, int initialSize, int maxSize, BufferManager bufferManager)\n            : base(initialSize, maxSize, bufferManager)\n        {\n            _quotaExceededString = quotaExceededString;\n        }\n\n        public void Init(int initialSize, int maxSizeQuota, BufferManager bufferManager)\n        {\n            Init(initialSize, maxSizeQuota, maxSizeQuota, bufferManager);\n        }\n\n        public void Init(int initialSize, int maxSizeQuota, int effectiveMaxSize, BufferManager bufferManager)\n        {\n            Reinitialize(initialSize, maxSizeQuota, effectiveMaxSize, bufferManager);\n        }\n\n        protected override Exception CreateQuotaExceededException(int maxSizeQuota)\n        {\n            string excMsg = Error.Format(_quotaExceededString, maxSizeQuota);\n            return new QuotaExceededException(excMsg);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/ServiceModel/Channels/BufferedOutputStream.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.IO;\nusing System.ServiceModel.Channels;\nusing System.Web.Http.SelfHost.Properties;\n\nnamespace System.Web.Http.SelfHost.ServiceModel.Channels\n{\n    internal class BufferedOutputStream : Stream\n    {\n        private BufferManager _bufferManager;\n\n        private byte[][] _chunks;\n\n        private int _chunkCount;\n        private byte[] _currentChunk;\n        private int _currentChunkSize;\n        private int _maxSize;\n        private int _theMaxSizeQuota;\n        private int _totalSize;\n        private bool _callerReturnsBuffer;\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1823:AvoidUnusedPrivateFields\", Justification = \"Used for internal checking\")]\n        private bool _bufferReturned;\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1823:AvoidUnusedPrivateFields\", Justification = \"Used for internal checking\")]\n        private bool _initialized;\n\n        // requires an explicit call to Init() by the caller\n        public BufferedOutputStream()\n        {\n            _chunks = new byte[4][];\n        }\n\n        public BufferedOutputStream(int initialSize, int maxSize, BufferManager bufferManager)\n            : this()\n        {\n            Reinitialize(initialSize, maxSize, bufferManager);\n        }\n\n        public override bool CanRead\n        {\n            get { return false; }\n        }\n\n        public override bool CanSeek\n        {\n            get { return false; }\n        }\n\n        public override bool CanWrite\n        {\n            get { return true; }\n        }\n\n        public override long Length\n        {\n            get { return _totalSize; }\n        }\n\n        public override long Position\n        {\n            get { throw Error.NotSupported(SRResources.SeekNotSupported); }\n\n            set { throw Error.NotSupported(SRResources.SeekNotSupported); }\n        }\n\n        public void Reinitialize(int initialSize, int maxSizeQuota, BufferManager bufferManager)\n        {\n            Reinitialize(initialSize, maxSizeQuota, maxSizeQuota, bufferManager);\n        }\n\n        public void Reinitialize(int initialSize, int maxSizeQuota, int effectiveMaxSize, BufferManager bufferManager)\n        {\n            Contract.Assert(!_initialized, \"Clear must be called before re-initializing stream\");\n\n            if (bufferManager == null)\n            {\n                throw Error.ArgumentNull(\"bufferManager\");\n            }\n\n            _theMaxSizeQuota = maxSizeQuota;\n            _maxSize = effectiveMaxSize;\n            _bufferManager = bufferManager;\n            _currentChunk = bufferManager.TakeBuffer(initialSize);\n            _currentChunkSize = 0;\n            _totalSize = 0;\n            _chunkCount = 1;\n            _chunks[0] = _currentChunk;\n            _initialized = true;\n        }\n\n        public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)\n        {\n            throw Error.NotSupported(SRResources.ReadNotSupported);\n        }\n\n        public override int EndRead(IAsyncResult asyncResult)\n        {\n            throw Error.NotSupported(SRResources.ReadNotSupported);\n        }\n\n        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)\n        {\n            Write(buffer, offset, count);\n            return new CompletedAsyncResult(callback, state);\n        }\n\n        public override void EndWrite(IAsyncResult asyncResult)\n        {\n            CompletedAsyncResult.End(asyncResult);\n        }\n\n        public void Clear()\n        {\n            if (!_callerReturnsBuffer)\n            {\n                for (int i = 0; i < _chunkCount; i++)\n                {\n                    _bufferManager.ReturnBuffer(_chunks[i]);\n                    _chunks[i] = null;\n                }\n            }\n\n            _callerReturnsBuffer = false;\n            _initialized = false;\n            _bufferReturned = false;\n            _chunkCount = 0;\n            _currentChunk = null;\n        }\n\n        public override void Close()\n        {\n            // Called directly or via base.Dispose, ensure all buffers are returned to the BufferManager\n            Clear();\n        }\n\n        public override void Flush()\n        {\n        }\n\n        public override int Read(byte[] buffer, int offset, int count)\n        {\n            throw Error.NotSupported(SRResources.ReadNotSupported);\n        }\n\n        public override int ReadByte()\n        {\n            throw Error.NotSupported(SRResources.ReadNotSupported);\n        }\n\n        public override long Seek(long offset, SeekOrigin origin)\n        {\n            throw Error.NotSupported(SRResources.SeekNotSupported);\n        }\n\n        public override void SetLength(long value)\n        {\n            throw Error.NotSupported(SRResources.SeekNotSupported);\n        }\n\n        public MemoryStream ToMemoryStream()\n        {\n            int bufferSize;\n            byte[] buffer = ToArray(out bufferSize);\n            return new MemoryStream(buffer, 0, bufferSize);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1021:AvoidOutParameters\", Justification = \"Out parameter is fine here.\")]\n        public byte[] ToArray(out int bufferSize)\n        {\n            Contract.Assert(_initialized, \"No data to return from uninitialized stream\");\n            Contract.Assert(!_bufferReturned, \"ToArray cannot be called more than once\");\n\n            byte[] buffer;\n            if (_chunkCount == 1)\n            {\n                buffer = _currentChunk;\n                bufferSize = _currentChunkSize;\n                _callerReturnsBuffer = true;\n            }\n            else\n            {\n                buffer = _bufferManager.TakeBuffer(_totalSize);\n                int offset = 0;\n                int count = _chunkCount - 1;\n                for (int i = 0; i < count; i++)\n                {\n                    byte[] chunk = _chunks[i];\n                    Buffer.BlockCopy(chunk, 0, buffer, offset, chunk.Length);\n                    offset += chunk.Length;\n                }\n\n                Buffer.BlockCopy(_currentChunk, 0, buffer, offset, _currentChunkSize);\n                bufferSize = _totalSize;\n            }\n\n            _bufferReturned = true;\n            return buffer;\n        }\n\n        public void Skip(int size)\n        {\n            WriteCore(null, 0, size);\n        }\n\n        public override void Write(byte[] buffer, int offset, int count)\n        {\n            WriteCore(buffer, offset, count);\n        }\n\n        public override void WriteByte(byte value)\n        {\n            Contract.Assert(_initialized, \"Cannot write to uninitialized stream\");\n            Contract.Assert(!_bufferReturned, \"Cannot write to stream once ToArray has been called.\");\n\n            if (_totalSize == _maxSize)\n            {\n                throw CreateQuotaExceededException(_maxSize);\n            }\n\n            if (_currentChunkSize == _currentChunk.Length)\n            {\n                AllocNextChunk(1);\n            }\n\n            _currentChunk[_currentChunkSize++] = value;\n        }\n\n        protected virtual Exception CreateQuotaExceededException(int maxSizeQuota)\n        {\n            return new InvalidOperationException(Error.Format(SRResources.BufferedOutputStreamQuotaExceeded, maxSizeQuota));\n        }\n\n        private void WriteCore(byte[] buffer, int offset, int size)\n        {\n            Contract.Assert(_initialized, \"Cannot write to uninitialized stream\");\n            Contract.Assert(!_bufferReturned, \"Cannot write to stream once ToArray has been called.\");\n\n            if (size < 0)\n            {\n                throw Error.ArgumentOutOfRange(\"size\", size, SRResources.ValueMustBeNonNegative);\n            }\n\n            if ((Int32.MaxValue - size) < _totalSize)\n            {\n                throw CreateQuotaExceededException(_theMaxSizeQuota);\n            }\n\n            int newTotalSize = _totalSize + size;\n            if (newTotalSize > _maxSize)\n            {\n                throw CreateQuotaExceededException(_theMaxSizeQuota);\n            }\n\n            int remainingSizeInChunk = _currentChunk.Length - _currentChunkSize;\n            if (size > remainingSizeInChunk)\n            {\n                if (remainingSizeInChunk > 0)\n                {\n                    if (buffer != null)\n                    {\n                        Buffer.BlockCopy(buffer, offset, _currentChunk, _currentChunkSize, remainingSizeInChunk);\n                    }\n\n                    _currentChunkSize = _currentChunk.Length;\n                    offset += remainingSizeInChunk;\n                    size -= remainingSizeInChunk;\n                }\n\n                AllocNextChunk(size);\n            }\n\n            if (buffer != null)\n            {\n                Buffer.BlockCopy(buffer, offset, _currentChunk, _currentChunkSize, size);\n            }\n\n            _totalSize = newTotalSize;\n            _currentChunkSize += size;\n        }\n\n        private void AllocNextChunk(int minimumChunkSize)\n        {\n            int newChunkSize;\n            if (_currentChunk.Length > (Int32.MaxValue / 2))\n            {\n                newChunkSize = Int32.MaxValue;\n            }\n            else\n            {\n                newChunkSize = _currentChunk.Length * 2;\n            }\n\n            if (minimumChunkSize > newChunkSize)\n            {\n                newChunkSize = minimumChunkSize;\n            }\n\n            byte[] newChunk = _bufferManager.TakeBuffer(newChunkSize);\n            if (_chunkCount == _chunks.Length)\n            {\n                byte[][] newChunks = new byte[_chunks.Length * 2][];\n                Array.Copy(_chunks, newChunks, _chunks.Length);\n                _chunks = newChunks;\n            }\n\n            _chunks[_chunkCount++] = newChunk;\n            _currentChunk = newChunk;\n            _currentChunkSize = 0;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/ServiceModel/Channels/ChannelAcceptor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ServiceModel;\nusing System.ServiceModel.Channels;\n\nnamespace System.Web.Http.SelfHost.ServiceModel.Channels\n{\n    internal abstract class ChannelAcceptor<TChannel> : CommunicationObject, IChannelAcceptor<TChannel>\n        where TChannel : class, IChannel\n    {\n        private ChannelManagerBase _channelManager;\n\n        protected ChannelAcceptor(ChannelManagerBase channelManager)\n        {\n            _channelManager = channelManager;\n        }\n\n        protected ChannelManagerBase ChannelManager\n        {\n            get { return _channelManager; }\n        }\n\n        protected override TimeSpan DefaultCloseTimeout\n        {\n            get { return ((IDefaultCommunicationTimeouts)_channelManager).CloseTimeout; }\n        }\n\n        protected override TimeSpan DefaultOpenTimeout\n        {\n            get { return ((IDefaultCommunicationTimeouts)_channelManager).OpenTimeout; }\n        }\n\n        public abstract TChannel AcceptChannel(TimeSpan timeout);\n\n        public abstract IAsyncResult BeginAcceptChannel(TimeSpan timeout, AsyncCallback callback, object state);\n\n        public abstract TChannel EndAcceptChannel(IAsyncResult result);\n\n        public abstract bool WaitForChannel(TimeSpan timeout);\n\n        public abstract IAsyncResult BeginWaitForChannel(TimeSpan timeout, AsyncCallback callback, object state);\n\n        public abstract bool EndWaitForChannel(IAsyncResult result);\n\n        protected override void OnAbort()\n        {\n        }\n\n        protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)\n        {\n            return new CompletedAsyncResult(callback, state);\n        }\n\n        protected override void OnEndClose(IAsyncResult result)\n        {\n            CompletedAsyncResult.End(result);\n        }\n\n        protected override void OnClose(TimeSpan timeout)\n        {\n        }\n\n        protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)\n        {\n            return new CompletedAsyncResult(callback, state);\n        }\n\n        protected override void OnEndOpen(IAsyncResult result)\n        {\n            CompletedAsyncResult.End(result);\n        }\n\n        protected override void OnOpen(TimeSpan timeout)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/ServiceModel/Channels/ChannelBindingUtility.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Security.Authentication.ExtendedProtection;\nusing System.Security.Authentication.ExtendedProtection.Configuration;\n\nnamespace System.Web.Http.SelfHost.ServiceModel.Channels\n{\n    internal static class ChannelBindingUtility\n    {\n        private static ExtendedProtectionPolicy disabledPolicy = new ExtendedProtectionPolicy(PolicyEnforcement.Never);\n        private static ExtendedProtectionPolicy defaultPolicy = disabledPolicy;\n\n        public static bool IsDefaultPolicy(ExtendedProtectionPolicy policy)\n        {\n            return Object.ReferenceEquals(policy, defaultPolicy);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/ServiceModel/Channels/CompletedAsyncResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\n\nnamespace System.Web.Http.SelfHost.ServiceModel.Channels\n{\n    //An AsyncResult that completes as soon as it is instantiated.\n    internal class CompletedAsyncResult : AsyncResult\n    {\n        public CompletedAsyncResult(AsyncCallback callback, object state)\n            : base(callback, state)\n        {\n            Complete(true);\n        }\n\n        public static void End(IAsyncResult result)\n        {\n            Contract.Assert(result != null, \"CompletedAsyncResult was null.\");\n            Contract.Assert(result.IsCompleted, \"CompletedAsyncResult was not completed!\");\n            AsyncResult.End<CompletedAsyncResult>(result);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/ServiceModel/Channels/CompletedAsyncResultOfT.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\n\nnamespace System.Web.Http.SelfHost.ServiceModel.Channels\n{\n    internal class CompletedAsyncResult<T> : AsyncResult\n    {\n        private T data;\n\n        public CompletedAsyncResult(T data, AsyncCallback callback, object state)\n            : base(callback, state)\n        {\n            this.data = data;\n            Complete(true);\n        }\n\n        public static T End(IAsyncResult result)\n        {\n            Contract.Assert(result != null, \"CompletedAsyncResult<T> was null.\");\n            Contract.Assert(result.IsCompleted, \"CompletedAsyncResult<T> was not completed!\");\n            CompletedAsyncResult<T> completedResult = AsyncResult.End<CompletedAsyncResult<T>>(result);\n            return completedResult.data;\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http.SelfHost/ServiceModel/Channels/HttpTransportDefaults.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ServiceModel;\n\nnamespace System.Web.Http.SelfHost.ServiceModel.Channels\n{\n    internal static class HttpTransportDefaults\n    {\n        internal const HostNameComparisonMode HostNameComparisonMode = System.ServiceModel.HostNameComparisonMode.StrongWildcard;\n        internal const TransferMode TransferMode = System.ServiceModel.TransferMode.Buffered;\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/ServiceModel/Channels/IChannelAcceptor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ServiceModel;\nusing System.ServiceModel.Channels;\n\nnamespace System.Web.Http.SelfHost.ServiceModel.Channels\n{\n    internal interface IChannelAcceptor<TChannel> : ICommunicationObject\n        where TChannel : class, IChannel\n    {\n        TChannel AcceptChannel(TimeSpan timeout);\n\n        IAsyncResult BeginAcceptChannel(TimeSpan timeout, AsyncCallback callback, object state);\n\n        TChannel EndAcceptChannel(IAsyncResult result);\n\n        bool WaitForChannel(TimeSpan timeout);\n\n        IAsyncResult BeginWaitForChannel(TimeSpan timeout, AsyncCallback callback, object state);\n\n        bool EndWaitForChannel(IAsyncResult result);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/ServiceModel/Channels/LayeredChannel.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.ServiceModel.Channels;\n\nnamespace System.Web.Http.SelfHost.ServiceModel.Channels\n{\n    internal abstract class LayeredChannel<TInnerChannel> : ChannelBase\n        where TInnerChannel : class, IChannel\n    {\n        private TInnerChannel _innerChannel;\n        private EventHandler _onInnerChannelFaulted;\n\n        protected LayeredChannel(ChannelManagerBase channelManager, TInnerChannel innerChannel)\n            : base(channelManager)\n        {\n            Contract.Assert(innerChannel != null);\n\n            _innerChannel = innerChannel;\n            _onInnerChannelFaulted = new EventHandler(OnInnerChannelFaulted);\n            _innerChannel.Faulted += _onInnerChannelFaulted;\n        }\n\n        protected TInnerChannel InnerChannel\n        {\n            get { return _innerChannel; }\n        }\n\n        public override T GetProperty<T>()\n        {\n            T baseProperty = base.GetProperty<T>();\n            if (baseProperty != null)\n            {\n                return baseProperty;\n            }\n\n            return InnerChannel.GetProperty<T>();\n        }\n\n        protected override void OnClosing()\n        {\n            _innerChannel.Faulted -= _onInnerChannelFaulted;\n            base.OnClosing();\n        }\n\n        protected override void OnAbort()\n        {\n            _innerChannel.Abort();\n        }\n\n        protected override void OnClose(TimeSpan timeout)\n        {\n            _innerChannel.Close(timeout);\n        }\n\n        protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)\n        {\n            return _innerChannel.BeginClose(timeout, callback, state);\n        }\n\n        protected override void OnEndClose(IAsyncResult result)\n        {\n            _innerChannel.EndClose(result);\n        }\n\n        protected override void OnOpen(TimeSpan timeout)\n        {\n            _innerChannel.Open(timeout);\n        }\n\n        protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)\n        {\n            return _innerChannel.BeginOpen(timeout, callback, state);\n        }\n\n        protected override void OnEndOpen(IAsyncResult result)\n        {\n            _innerChannel.EndOpen(result);\n        }\n\n        private void OnInnerChannelFaulted(object sender, EventArgs e)\n        {\n            Fault();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/ServiceModel/Channels/LayeredChannelAcceptor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ServiceModel.Channels;\n\nnamespace System.Web.Http.SelfHost.ServiceModel.Channels\n{\n    internal abstract class LayeredChannelAcceptor<TChannel, TInnerChannel> : ChannelAcceptor<TChannel>\n        where TChannel : class, IChannel\n        where TInnerChannel : class, IChannel\n    {\n        private IChannelListener<TInnerChannel> _innerListener;\n\n        protected LayeredChannelAcceptor(ChannelManagerBase channelManager, IChannelListener<TInnerChannel> innerListener)\n            : base(channelManager)\n        {\n            _innerListener = innerListener;\n        }\n\n        public override TChannel AcceptChannel(TimeSpan timeout)\n        {\n            TInnerChannel innerChannel = _innerListener.AcceptChannel(timeout);\n            if (innerChannel == null)\n            {\n                return null;\n            }\n            else\n            {\n                return OnAcceptChannel(innerChannel);\n            }\n        }\n\n        public override IAsyncResult BeginAcceptChannel(TimeSpan timeout, AsyncCallback callback, object state)\n        {\n            return _innerListener.BeginAcceptChannel(timeout, callback, state);\n        }\n\n        public override TChannel EndAcceptChannel(IAsyncResult result)\n        {\n            TInnerChannel innerChannel = _innerListener.EndAcceptChannel(result);\n            if (innerChannel == null)\n            {\n                return null;\n            }\n            else\n            {\n                return OnAcceptChannel(innerChannel);\n            }\n        }\n\n        public override bool WaitForChannel(TimeSpan timeout)\n        {\n            return _innerListener.WaitForChannel(timeout);\n        }\n\n        public override IAsyncResult BeginWaitForChannel(TimeSpan timeout, AsyncCallback callback, object state)\n        {\n            return _innerListener.BeginWaitForChannel(timeout, callback, state);\n        }\n\n        public override bool EndWaitForChannel(IAsyncResult result)\n        {\n            return _innerListener.EndWaitForChannel(result);\n        }\n\n        protected abstract TChannel OnAcceptChannel(TInnerChannel innerChannel);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/ServiceModel/Channels/LayeredChannelListener.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.ServiceModel;\nusing System.ServiceModel.Channels;\nusing System.Web.Http.SelfHost.Properties;\n\nnamespace System.Web.Http.SelfHost.ServiceModel.Channels\n{\n    internal abstract class LayeredChannelListener<TChannel> : ChannelListenerBase<TChannel>\n        where TChannel : class, IChannel\n    {\n        private IChannelListener _innerChannelListener;\n        private bool _sharedInnerListener;\n        private EventHandler _onInnerListenerFaulted;\n\n        protected LayeredChannelListener(bool sharedInnerListener, IDefaultCommunicationTimeouts timeouts, IChannelListener innerChannelListener)\n            : base(timeouts)\n        {\n            _sharedInnerListener = sharedInnerListener;\n            _innerChannelListener = innerChannelListener;\n            _onInnerListenerFaulted = new EventHandler(OnInnerListenerFaulted);\n            if (_innerChannelListener != null)\n            {\n                _innerChannelListener.Faulted += _onInnerListenerFaulted;\n            }\n        }\n\n        protected LayeredChannelListener(bool sharedInnerListener, IDefaultCommunicationTimeouts timeouts)\n            : this(sharedInnerListener, timeouts, null)\n        {\n        }\n\n        protected LayeredChannelListener(bool sharedInnerListener)\n            : this(sharedInnerListener, null, null)\n        {\n        }\n\n        protected LayeredChannelListener(IDefaultCommunicationTimeouts timeouts, IChannelListener innerChannelListener)\n            : this(false, timeouts, innerChannelListener)\n        {\n        }\n\n        public override Uri Uri\n        {\n            get { return GetInnerListenerSnapshot().Uri; }\n        }\n\n        internal virtual IChannelListener InnerChannelListener\n        {\n            get { return _innerChannelListener; }\n\n            set\n            {\n                lock (ThisLock)\n                {\n                    ThrowIfDisposedOrImmutable();\n                    if (_innerChannelListener != null)\n                    {\n                        _innerChannelListener.Faulted -= _onInnerListenerFaulted;\n                    }\n\n                    _innerChannelListener = value;\n                    if (_innerChannelListener != null)\n                    {\n                        _innerChannelListener.Faulted += _onInnerListenerFaulted;\n                    }\n                }\n            }\n        }\n\n        internal bool SharedInnerListener\n        {\n            get { return _sharedInnerListener; }\n        }\n\n        public override T GetProperty<T>()\n        {\n            T baseProperty = base.GetProperty<T>();\n            if (baseProperty != null)\n            {\n                return baseProperty;\n            }\n\n            IChannelListener channelListener = InnerChannelListener;\n            if (channelListener != null)\n            {\n                return channelListener.GetProperty<T>();\n            }\n            else\n            {\n                return default(T);\n            }\n        }\n\n        internal void ThrowIfInnerListenerNotSet()\n        {\n            if (InnerChannelListener == null)\n            {\n                throw Error.InvalidOperation(SRResources.InnerListenerFactoryNotSet, GetType().ToString());\n            }\n        }\n\n        internal IChannelListener GetInnerListenerSnapshot()\n        {\n            IChannelListener innerListener = InnerChannelListener;\n\n            if (innerListener == null)\n            {\n                throw Error.InvalidOperation(SRResources.InnerListenerFactoryNotSet, GetType().ToString());\n            }\n\n            return innerListener;\n        }\n\n        protected override void OnOpening()\n        {\n            base.OnOpening();\n            ThrowIfInnerListenerNotSet();\n        }\n\n        protected override void OnOpen(TimeSpan timeout)\n        {\n            if (InnerChannelListener != null && !_sharedInnerListener)\n            {\n                InnerChannelListener.Open(timeout);\n            }\n        }\n\n        protected override void OnEndOpen(IAsyncResult result)\n        {\n            OpenAsyncResult.End(result);\n        }\n\n        protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)\n        {\n            return new OpenAsyncResult(InnerChannelListener, _sharedInnerListener, timeout, callback, state);\n        }\n\n        protected override void OnClose(TimeSpan timeout)\n        {\n            OnCloseOrAbort();\n            if (InnerChannelListener != null && !_sharedInnerListener)\n            {\n                InnerChannelListener.Close(timeout);\n            }\n        }\n\n        protected override void OnEndClose(IAsyncResult result)\n        {\n            CloseAsyncResult.End(result);\n        }\n\n        protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)\n        {\n            OnCloseOrAbort();\n            return new CloseAsyncResult(InnerChannelListener, _sharedInnerListener, timeout, callback, state);\n        }\n\n        protected override void OnAbort()\n        {\n            lock (ThisLock)\n            {\n                OnCloseOrAbort();\n            }\n\n            IChannelListener channelListener = InnerChannelListener;\n            if (channelListener != null && !_sharedInnerListener)\n            {\n                channelListener.Abort();\n            }\n        }\n\n        private void OnInnerListenerFaulted(object sender, EventArgs e)\n        {\n            // if our inner listener faulted, we should fault as well\n            Fault();\n        }\n\n        private void OnCloseOrAbort()\n        {\n            IChannelListener channelListener = InnerChannelListener;\n            if (channelListener != null)\n            {\n                channelListener.Faulted -= _onInnerListenerFaulted;\n            }\n        }\n\n        private class CloseAsyncResult : AsyncResult\n        {\n            private static AsyncCallback _onCloseComplete = new AsyncCallback(OnCloseComplete);\n\n            private ICommunicationObject _communicationObject;\n\n            public CloseAsyncResult(ICommunicationObject communicationObject, bool sharedInnerListener, TimeSpan timeout, AsyncCallback callback, object state)\n                : base(callback, state)\n            {\n                _communicationObject = communicationObject;\n\n                if (_communicationObject == null || sharedInnerListener)\n                {\n                    Complete(true);\n                    return;\n                }\n\n                IAsyncResult result = _communicationObject.BeginClose(timeout, _onCloseComplete, this);\n\n                if (result.CompletedSynchronously)\n                {\n                    _communicationObject.EndClose(result);\n                    Complete(true);\n                }\n            }\n\n            public static void End(IAsyncResult result)\n            {\n                AsyncResult.End<CloseAsyncResult>(result);\n            }\n\n            [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Exception is propagated.\")]\n            private static void OnCloseComplete(IAsyncResult result)\n            {\n                if (result.CompletedSynchronously)\n                {\n                    return;\n                }\n\n                CloseAsyncResult thisPtr = (CloseAsyncResult)result.AsyncState;\n                Exception exception = null;\n\n                try\n                {\n                    thisPtr._communicationObject.EndClose(result);\n                }\n                catch (Exception e)\n                {\n                    exception = e;\n                }\n\n                thisPtr.Complete(false, exception);\n            }\n        }\n\n        private class OpenAsyncResult : AsyncResult\n        {\n            private static AsyncCallback _onOpenComplete = new AsyncCallback(OnOpenComplete);\n\n            private ICommunicationObject _communicationObject;\n\n            public OpenAsyncResult(ICommunicationObject communicationObject, bool sharedInnerListener, TimeSpan timeout, AsyncCallback callback, object state)\n                : base(callback, state)\n            {\n                _communicationObject = communicationObject;\n\n                if (_communicationObject == null || sharedInnerListener)\n                {\n                    Complete(true);\n                    return;\n                }\n\n                IAsyncResult result = _communicationObject.BeginOpen(timeout, _onOpenComplete, this);\n                if (result.CompletedSynchronously)\n                {\n                    _communicationObject.EndOpen(result);\n                    Complete(true);\n                }\n            }\n\n            public static void End(IAsyncResult result)\n            {\n                AsyncResult.End<OpenAsyncResult>(result);\n            }\n\n            [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Exception is propagated.\")]\n            private static void OnOpenComplete(IAsyncResult result)\n            {\n                if (result.CompletedSynchronously)\n                {\n                    return;\n                }\n\n                OpenAsyncResult thisPtr = (OpenAsyncResult)result.AsyncState;\n                Exception exception = null;\n\n                try\n                {\n                    thisPtr._communicationObject.EndOpen(result);\n                }\n                catch (Exception e)\n                {\n                    exception = e;\n                }\n\n                thisPtr.Complete(false, exception);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/ServiceModel/Channels/TransportDefaults.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.SelfHost.ServiceModel.Channels\n{\n    internal static class TransportDefaults\n    {\n        internal const long MaxReceivedMessageSize = 65536;\n        internal const long MaxBufferPoolSize = 512 * 1024;\n        internal const int MaxBufferSize = (int)MaxReceivedMessageSize;\n        internal const int MaxFaultSize = MaxBufferSize;\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/ServiceModel/HostNameComparisonModeHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ServiceModel;\n\nnamespace System.Web.Http.SelfHost.ServiceModel\n{\n    internal static class HostNameComparisonModeHelper\n    {\n        public static bool IsDefined(HostNameComparisonMode value)\n        {\n            return\n                value == HostNameComparisonMode.StrongWildcard\n                || value == HostNameComparisonMode.Exact\n                || value == HostNameComparisonMode.WeakWildcard;\n        }\n\n        public static void Validate(HostNameComparisonMode value, string parameterName)\n        {\n            if (!IsDefined(value))\n            {\n                throw Error.InvalidEnumArgument(parameterName, (int)value, typeof(HostNameComparisonMode));\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/ServiceModel/HttpClientCredentialTypeHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.ServiceModel;\n\nnamespace System.Web.Http.SelfHost.ServiceModel\n{\n    internal static class HttpClientCredentialTypeHelper\n    {\n        internal static AuthenticationSchemes MapToAuthenticationScheme(HttpClientCredentialType clientCredentialType)\n        {\n            switch (clientCredentialType)\n            {\n                case HttpClientCredentialType.None:\n                case HttpClientCredentialType.Certificate:\n                    return AuthenticationSchemes.Anonymous;\n\n                case HttpClientCredentialType.Basic:\n                    return AuthenticationSchemes.Basic;\n\n                case HttpClientCredentialType.Digest:\n                    return AuthenticationSchemes.Digest;\n\n                case HttpClientCredentialType.Ntlm:\n                    return AuthenticationSchemes.Ntlm;\n\n                case HttpClientCredentialType.Windows:\n                    return AuthenticationSchemes.Negotiate;\n            }\n\n            Contract.Assert(false, \"Invalid clientCredentialType \" + clientCredentialType);\n            return AuthenticationSchemes.Anonymous;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/ServiceModel/HttpProxyCredentialTypeHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.ServiceModel;\n\nnamespace System.Web.Http.SelfHost.ServiceModel\n{\n    internal static class HttpProxyCredentialTypeHelper\n    {\n        internal static AuthenticationSchemes MapToAuthenticationScheme(HttpProxyCredentialType proxyCredentialType)\n        {\n            switch (proxyCredentialType)\n            {\n                case HttpProxyCredentialType.None:\n                    return AuthenticationSchemes.Anonymous;\n\n                case HttpProxyCredentialType.Basic:\n                    return AuthenticationSchemes.Basic;\n\n                case HttpProxyCredentialType.Digest:\n                    return AuthenticationSchemes.Digest;\n\n                case HttpProxyCredentialType.Ntlm:\n                    return AuthenticationSchemes.Ntlm;\n\n                case HttpProxyCredentialType.Windows:\n                    return AuthenticationSchemes.Negotiate;\n            }\n\n            Contract.Assert(false, \"Invalid proxyCredentialType \" + proxyCredentialType);\n            return AuthenticationSchemes.Anonymous;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/ServiceModel/HttpTransportSecurityExtensionMethods.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.ServiceModel;\nusing System.ServiceModel.Channels;\nusing System.Web.Http.SelfHost.Properties;\n\nnamespace System.Web.Http.SelfHost.ServiceModel\n{\n    internal static class HttpTransportSecurityExtensionMethods\n    {\n        internal static void ConfigureTransportProtectionAndAuthentication(this HttpTransportSecurity httpTransportSecurity, HttpsTransportBindingElement httpsTransportBindingElement)\n        {\n            Contract.Assert(httpTransportSecurity != null);\n            Contract.Assert(httpsTransportBindingElement != null);\n\n            httpTransportSecurity.ConfigureAuthentication(httpsTransportBindingElement);\n            httpsTransportBindingElement.RequireClientCertificate = httpTransportSecurity.ClientCredentialType == HttpClientCredentialType.Certificate;\n        }\n\n        internal static void ConfigureTransportAuthentication(this HttpTransportSecurity httpTransportSecurity, HttpTransportBindingElement httpTransportBindingElement)\n        {\n            Contract.Assert(httpTransportSecurity != null);\n            Contract.Assert(httpTransportBindingElement != null);\n\n            if (httpTransportSecurity.ClientCredentialType == HttpClientCredentialType.Certificate)\n            {\n                throw Error.InvalidOperation(SRResources.CertificateUnsupportedForHttpTransportCredentialOnly);\n            }\n\n            httpTransportSecurity.ConfigureAuthentication(httpTransportBindingElement);\n        }\n\n        internal static void DisableTransportAuthentication(this HttpTransportSecurity httpTransportSecurity, HttpTransportBindingElement httpTransportBindingElement)\n        {\n            Contract.Assert(httpTransportSecurity != null);\n            Contract.Assert(httpTransportBindingElement != null);\n\n            httpTransportBindingElement.AuthenticationScheme = AuthenticationSchemes.Anonymous;\n            httpTransportBindingElement.ProxyAuthenticationScheme = AuthenticationSchemes.Anonymous;\n            httpTransportBindingElement.Realm = String.Empty;\n            httpTransportBindingElement.ExtendedProtectionPolicy = httpTransportSecurity.ExtendedProtectionPolicy;\n        }\n\n        private static void ConfigureAuthentication(this HttpTransportSecurity httpTransportSecurity, HttpTransportBindingElement httpTransportBindingElement)\n        {\n            Contract.Assert(httpTransportSecurity != null);\n            Contract.Assert(httpTransportBindingElement != null);\n\n            httpTransportBindingElement.AuthenticationScheme = HttpClientCredentialTypeHelper.MapToAuthenticationScheme(httpTransportSecurity.ClientCredentialType);\n            httpTransportBindingElement.ProxyAuthenticationScheme = HttpProxyCredentialTypeHelper.MapToAuthenticationScheme(httpTransportSecurity.ProxyCredentialType);\n            httpTransportBindingElement.Realm = httpTransportSecurity.Realm;\n            httpTransportBindingElement.ExtendedProtectionPolicy = httpTransportSecurity.ExtendedProtectionPolicy;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/ServiceModel/TransferModeHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ServiceModel;\n\nnamespace System.Web.Http.SelfHost.ServiceModel\n{\n    internal static class TransferModeHelper\n    {\n        public static bool IsDefined(TransferMode transferMode)\n        {\n            return transferMode == TransferMode.Buffered ||\n                   transferMode == TransferMode.Streamed ||\n                   transferMode == TransferMode.StreamedRequest ||\n                   transferMode == TransferMode.StreamedResponse;\n        }\n\n        public static void Validate(TransferMode value, string parameterValue)\n        {\n            if (!IsDefined(value))\n            {\n                throw Error.InvalidEnumArgument(parameterValue, (int)value, typeof(TransferMode));\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SelfHost/System.Web.Http.SelfHost.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{66492E69-CE4C-4FB1-9B1F-88DEE09D06F1}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>System.Web.Http.SelfHost</RootNamespace>\n    <AssemblyName>System.Web.Http.SelfHost</AssemblyName>\n    <DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>\n    <RunCodeAnalysis>$(CodeAnalysis)</RunCodeAnalysis>\n    <CodeAnalysisRuleSet>..\\Strict.ruleset</CodeAnalysisRuleSet>\n    <DefineConstants>$(DefineConstants);ASPNETMVC</DefineConstants>\n    <NoWarn>1591</NoWarn>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.IdentityModel\" />\n    <Reference Include=\"System.Net.Http\" />\n    <Reference Include=\"System.Runtime.Serialization\" />\n    <Reference Include=\"System.ServiceModel\" />\n    <Reference Include=\"System.Xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\CommonAssemblyInfo.cs\">\n      <Link>Properties\\CommonAssemblyInfo.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\DictionaryExtensions.cs\">\n      <Link>Common\\DictionaryExtensions.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Error.cs\">\n      <Link>Common\\Error.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\HttpMethodHelper.cs\">\n      <Link>Common\\HttpMethodHelper.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\TaskHelpers.cs\">\n      <Link>Common\\TaskHelpers.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\TaskHelpersExtensions.cs\">\n      <Link>Common\\TaskHelpersExtensions.cs</Link>\n    </Compile>\n    <Compile Include=\"HttpRequestMessageExtensions.cs\" />\n    <Compile Include=\"Properties\\SRResources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>SRResources.resx</DependentUpon>\n    </Compile>\n    <Compile Include=\"Channels\\HttpMessage.cs\" />\n    <Compile Include=\"Channels\\HttpMessageEncoderFactory.cs\" />\n    <Compile Include=\"Channels\\HttpMessageEncodingBindingElement.cs\" />\n    <Compile Include=\"Channels\\HttpMessageEncodingChannelListener.cs\" />\n    <Compile Include=\"Channels\\HttpMessageEncodingReplyChannel.cs\" />\n    <Compile Include=\"Channels\\HttpMessageEncodingRequestContext.cs\" />\n    <Compile Include=\"Channels\\HttpMessageExtensions.cs\" />\n    <Compile Include=\"Channels\\HttpBinding.cs\" />\n    <Compile Include=\"Channels\\HttpBindingSecurity.cs\" />\n    <Compile Include=\"Channels\\HttpBindingSecurityMode.cs\" />\n    <Compile Include=\"Channels\\HttpBindingSecurityModeHelper.cs\" />\n    <Compile Include=\"HttpSelfHostConfiguration.cs\" />\n    <Compile Include=\"HttpSelfHostServer.cs\" />\n    <Compile Include=\"SelfHostHttpRequestContext.cs\" />\n    <Compile Include=\"ServiceModel\\Channels\\AsyncResult.cs\" />\n    <Compile Include=\"ServiceModel\\Channels\\BufferedOutputStream.cs\" />\n    <Compile Include=\"ServiceModel\\Channels\\BufferManagerOutputStream.cs\" />\n    <Compile Include=\"ServiceModel\\Channels\\ChannelAcceptor.cs\" />\n    <Compile Include=\"ServiceModel\\Channels\\ChannelBindingUtility.cs\" />\n    <Compile Include=\"ServiceModel\\Channels\\CompletedAsyncResult.cs\" />\n    <Compile Include=\"ServiceModel\\Channels\\HttpTransportDefaults.cs\" />\n    <Compile Include=\"ServiceModel\\Channels\\IChannelAcceptor.cs\" />\n    <Compile Include=\"ServiceModel\\Channels\\LayeredChannel.cs\" />\n    <Compile Include=\"ServiceModel\\Channels\\LayeredChannelAcceptor.cs\" />\n    <Compile Include=\"ServiceModel\\Channels\\LayeredChannelListener.cs\" />\n    <Compile Include=\"ServiceModel\\Channels\\TransportDefaults.cs\" />\n    <Compile Include=\"ServiceModel\\Channels\\CompletedAsyncResultOfT.cs\" />\n    <Compile Include=\"ServiceModel\\HostNameComparisonModeHelper.cs\" />\n    <Compile Include=\"ServiceModel\\HttpClientCredentialTypeHelper.cs\" />\n    <Compile Include=\"ServiceModel\\HttpProxyCredentialTypeHelper.cs\" />\n    <Compile Include=\"ServiceModel\\HttpTransportSecurityExtensionMethods.cs\" />\n    <Compile Include=\"ServiceModel\\TransferModeHelper.cs\" />\n    <Compile Include=\"GlobalSuppressions.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\Common\\CommonWebApiResources.Designer.cs\">\n      <Link>Properties\\CommonWebApiResources.Designer.cs</Link>\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>CommonWebApiResources.resx</DependentUpon>\n    </Compile>\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"..\\Common\\CommonWebApiResources.resx\">\n      <Link>Properties\\CommonWebApiResources.resx</Link>\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>CommonWebApiResources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"Properties\\SRResources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>SRResources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\System.Net.Http.Formatting\\System.Net.Http.Formatting.csproj\">\n      <Project>{668E9021-CE84-49D9-98FB-DF125A9FCDB0}</Project>\n      <Name>System.Net.Http.Formatting</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.Http\\System.Web.Http.csproj\">\n      <Project>{DDC1CE0C-486E-4E35-BB3B-EAB61F8F9440}</Project>\n      <Name>System.Web.Http</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <CodeAnalysisDictionary Include=\"..\\CodeAnalysisDictionary.xml\">\n      <Link>CodeAnalysisDictionary.xml</Link>\n    </CodeAnalysisDictionary>\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n</Project>"
  },
  {
    "path": "src/System.Web.Http.SignalR/GlobalSuppressions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"System.Web.Http\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA2210:AssembliesShouldHaveValidStrongNames\", Justification = \"This is until SignalR gets signed.\")]\n"
  },
  {
    "path": "src/System.Web.Http.SignalR/HubController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing Microsoft.AspNet.SignalR;\nusing Microsoft.AspNet.SignalR.Hubs;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Defines a base class for <see cref=\"ApiController\"/> that exposes functionality for calling back\n    /// to clients connected to a particular SignalR hub.\n    /// </summary>\n    [CLSCompliant(false)]\n    public abstract class HubController : HubControllerBase\n    {\n        private string _hubName;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HubController\" /> class.\n        /// </summary>\n        /// <param name=\"hubName\">Name of the hub as specified by the <see cref=\"HubNameAttribute\"/>.</param>\n        protected HubController(string hubName)\n        {\n            if (hubName == null)\n            {\n                throw Error.ArgumentNull(\"hubName\");\n            }\n            _hubName = hubName;\n        }\n\n        /// <summary>\n        /// Gets the <see cref=\"IHubContext\"/> for the associated hub.\n        /// </summary>\n        protected override IHubContext HubContext\n        {\n            get\n            {\n                Contract.Assert(ConnectionManager != null);\n                return ConnectionManager.GetHubContext(_hubName);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SignalR/HubControllerBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Web.Http.Properties;\nusing Microsoft.AspNet.SignalR;\nusing Microsoft.AspNet.SignalR.Hubs;\nusing Microsoft.AspNet.SignalR.Infrastructure;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Defines a base class for <see cref=\"ApiController\"/> that exposes functionality for calling back\n    /// to clients connected to a particular SignalR hub.\n    /// </summary>\n    [CLSCompliant(false)]\n    public abstract class HubControllerBase : ApiController\n    {\n        private IConnectionManager _connectionManager;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HubControllerBase\" /> class.\n        /// </summary>\n        protected HubControllerBase()\n        {\n        }\n\n        /// <summary>\n        /// Gets an <see cref=\"IHubConnectionContext\"/> that represents the clients connected to the hub.\n        /// </summary>\n        public IHubConnectionContext Clients\n        {\n            get\n            {\n                if (HubContext == null)\n                {\n                    throw Error.InvalidOperation(SRResources.NullHubContext, GetType().Name);\n                }\n                return HubContext.Clients;\n            }\n        }\n\n        /// <summary>\n        /// Gets the <see cref=\"IGroupManager\"/> for the hub.\n        /// </summary>\n        public IGroupManager Groups\n        {\n            get\n            {\n                if (HubContext == null)\n                {\n                    throw Error.InvalidOperation(SRResources.NullHubContext, GetType().Name);\n                }\n                return HubContext.Groups;\n            }\n        }\n\n        /// <summary>\n        /// Gets the <see cref=\"IHubContext\"/> for the associated hub.\n        /// </summary>\n        protected abstract IHubContext HubContext\n        {\n            get;\n        }\n\n        /// <summary>\n        /// Gets the <see cref=\"IConnectionManager\"/> used to resolve hub contexts. The connection manager will\n        /// be resolved by the controller's <see cref=\"HttpConfiguration\"/> dependency resolver if the service is\n        /// available. Otherwise, the default GlobalHost <see cref=\"IConnectionManager\"/> will be returned instead.\n        /// </summary>\n        protected IConnectionManager ConnectionManager\n        {\n            get\n            {\n                if (_connectionManager == null)\n                {\n                    _connectionManager = ResolveConnectionManager();\n                }\n                return _connectionManager;\n            }\n        }\n\n        private IConnectionManager ResolveConnectionManager()\n        {\n            if (Configuration != null)\n            {\n                Contract.Assert(Configuration.DependencyResolver != null);\n                IConnectionManager connectionManager = Configuration.DependencyResolver.GetService(typeof(IConnectionManager)) as IConnectionManager;\n                if (connectionManager != null)\n                {\n                    return connectionManager;\n                }\n            }\n\n            // If connection manager cannot be resolved by DependencyResolver, use the default connection manager instead.\n            return GlobalHost.ConnectionManager;\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http.SignalR/HubControllerOfTHub.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing Microsoft.AspNet.SignalR;\nusing Microsoft.AspNet.SignalR.Hubs;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Defines a base class for <see cref=\"ApiController\"/> that exposes functionality for calling back\n    /// to clients connected to a particular SignalR hub.\n    /// </summary>\n    /// <typeparam name=\"THub\">The type of the hub. Must implement the <see cref=\"IHub\"/> interface.</typeparam>\n    [CLSCompliant(false)]\n    public abstract class HubController<THub> : HubControllerBase where THub : IHub\n    {\n        /// <summary>\n        /// Gets the <see cref=\"IHubContext\"/> for the associated hub.\n        /// </summary>\n        protected override IHubContext HubContext\n        {\n            get\n            {\n                Contract.Assert(ConnectionManager != null);\n                return ConnectionManager.GetHubContext<THub>();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SignalR/Properties/AssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\n\n[assembly: AssemblyTitle(\"System.Web.Http.SignalR\")]\n[assembly: AssemblyDescription(\"\")]\n\n[assembly: InternalsVisibleTo(\"System.Web.Http.SignalR.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n"
  },
  {
    "path": "src/System.Web.Http.SignalR/Properties/SRResources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.17929\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace System.Web.Http.Properties {\n    using System;\n    \n    \n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class SRResources {\n        \n        private static global::System.Resources.ResourceManager resourceMan;\n        \n        private static global::System.Globalization.CultureInfo resourceCulture;\n        \n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal SRResources() {\n        }\n        \n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"System.Web.Http.Properties.SRResources\", typeof(SRResources).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n        \n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to No hub context could be found for the HubController of type &apos;{0}&apos;..\n        /// </summary>\n        internal static string NullHubContext {\n            get {\n                return ResourceManager.GetString(\"NullHubContext\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.SignalR/Properties/SRResources.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"NullHubContext\" xml:space=\"preserve\">\n    <value>No hub context could be found for the HubController of type '{0}'.</value>\n  </data>\n</root>"
  },
  {
    "path": "src/System.Web.Http.SignalR/System.Web.Http.SignalR.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{8A607AC9-E7DD-4B74-A0B1-47FC95B9838B}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>System.Web.Http</RootNamespace>\n    <AssemblyName>System.Web.Http.SignalR</AssemblyName>\n    <DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>\n    <RunCodeAnalysis>$(CodeAnalysis)</RunCodeAnalysis>\n    <CodeAnalysisRuleSet>..\\Strict.ruleset</CodeAnalysisRuleSet>\n    <DefineConstants>$(DefineConstants);ASPNETMVC</DefineConstants>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Microsoft.AspNet.SignalR.Core\">\n      <HintPath>..\\..\\packages\\Microsoft.AspNet.SignalR.Core.1.0.0\\lib\\net40\\Microsoft.AspNet.SignalR.Core.dll</HintPath>\n    </Reference>\n    <Reference Include=\"Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Newtonsoft.Json.13.0.1\\lib\\net45\\Newtonsoft.Json.dll</HintPath>\n      <SpecificVersion>False</SpecificVersion>\n      <Private>False</Private>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Net.Http\" />\n    <Reference Include=\"System.Net.Http.WebRequest\" />\n    <Reference Include=\"System.XML\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\Common\\Error.cs\">\n      <Link>Common\\Error.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\CommonAssemblyInfo.cs\">\n      <Link>Properties\\CommonAssemblyInfo.cs</Link>\n    </Compile>\n    <Compile Include=\"GlobalSuppressions.cs\" />\n    <Compile Include=\"HubController.cs\" />\n    <Compile Include=\"HubControllerBase.cs\" />\n    <Compile Include=\"HubControllerOfTHub.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"Properties\\SRResources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>SRResources.resx</DependentUpon>\n    </Compile>\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"..\\Common\\CommonWebApiResources.resx\">\n      <Link>Properties\\CommonWebApiResources.resx</Link>\n    </EmbeddedResource>\n    <Compile Include=\"..\\Common\\CommonWebApiResources.Designer.cs\">\n      <Link>Properties\\CommonWebApiResources.Designer.cs</Link>\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>CommonWebApiResources.resx</DependentUpon>\n    </Compile>\n    <EmbeddedResource Include=\"Properties\\SRResources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>SRResources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\System.Net.Http.Formatting\\System.Net.Http.Formatting.csproj\">\n      <Project>{668e9021-ce84-49d9-98fb-df125a9fcdb0}</Project>\n      <Name>System.Net.Http.Formatting</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.Http\\System.Web.Http.csproj\">\n      <Project>{ddc1ce0c-486e-4e35-bb3b-eab61f8f9440}</Project>\n      <Name>System.Web.Http</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n</Project>"
  },
  {
    "path": "src/System.Web.Http.SignalR/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Microsoft.AspNet.SignalR.Core\" version=\"1.0.0\" targetFramework=\"net45\" />\n  <package id=\"Newtonsoft.Json\" version=\"13.0.1\" targetFramework=\"net45\" />\n</packages>"
  },
  {
    "path": "src/System.Web.Http.Tracing/GlobalSuppressions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA2210:AssembliesShouldHaveValidStrongNames\", Justification = \"These assemblies are delay-signed.\")]\n[assembly: SuppressMessage(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\", Scope = \"member\", Target = \"System.Web.Http.Error.#NotSupported(System.String,System.Object[])\", Justification = \"Error imported from main project\")]\n[assembly: SuppressMessage(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\", Scope = \"member\", Target = \"System.Web.Http.Error.#InvalidOperation(System.Exception,System.String,System.Object[])\", Justification = \"Error imported from main project\")]\n[assembly: SuppressMessage(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\", Scope = \"member\", Target = \"System.Web.Http.Error.#InvalidOperation(System.String,System.Object[])\", Justification = \"Error imported from main project\")]\n[assembly: SuppressMessage(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\", Scope = \"member\", Target = \"System.Web.Http.Error.#InvalidEnumArgument(System.String,System.Int32,System.Type)\", Justification = \"Error imported from main project\")]\n[assembly: SuppressMessage(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\", Scope = \"member\", Target = \"System.Web.Http.Error.#OperationCanceled(System.String,System.Object[])\", Justification = \"Error imported from main project\")]\n[assembly: SuppressMessage(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\", Scope = \"member\", Target = \"System.Web.Http.Error.#OperationCanceled()\", Justification = \"Error imported from main project\")]\n[assembly: SuppressMessage(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\", Scope = \"member\", Target = \"System.Web.Http.Error.#ObjectDisposed(System.String,System.Object[])\", Justification = \"Error imported from main project\")]\n[assembly: SuppressMessage(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\", Scope = \"member\", Target = \"System.Web.Http.Error.#KeyNotFound(System.String,System.Object[])\", Justification = \"Error imported from main project\")]\n[assembly: SuppressMessage(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\", Scope = \"member\", Target = \"System.Web.Http.Error.#KeyNotFound()\", Justification = \"Error imported from main project\")]\n[assembly: SuppressMessage(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\", Scope = \"member\", Target = \"System.Web.Http.Error.#ArgumentMustBeLessThanOrEqualTo(System.String,System.Object,System.Object)\", Justification = \"Error imported from main project\")]\n[assembly: SuppressMessage(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\", Scope = \"member\", Target = \"System.Web.Http.Error.#ArgumentMustBeGreaterThanOrEqualTo(System.String,System.Object,System.Object)\", Justification = \"Error imported from main project\")]\n[assembly: SuppressMessage(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\", Scope = \"member\", Target = \"System.Web.Http.Error.#ArgumentNullOrEmpty(System.String)\", Justification = \"Error imported from main project\")]\n[assembly: SuppressMessage(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\", Scope = \"member\", Target = \"System.Web.Http.Error.#PropertyNull()\", Justification = \"Error imported from main project\")]\n[assembly: SuppressMessage(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\", Scope = \"member\", Target = \"System.Web.Http.Error.#ArgumentUriHasQueryOrFragment(System.String,System.Uri)\", Justification = \"Error imported from main project\")]\n[assembly: SuppressMessage(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\", Scope = \"member\", Target = \"System.Web.Http.Error.#ArgumentNull(System.String,System.String,System.Object[])\", Justification = \"Error imported from main project\")]\n[assembly: SuppressMessage(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\", Scope = \"member\", Target = \"System.Web.Http.Error.#ArgumentUriNotHttpOrHttpsScheme(System.String,System.Uri)\", Justification = \"Error imported from main project\")]\n[assembly: SuppressMessage(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\", Scope = \"member\", Target = \"System.Web.Http.Error.#Argument(System.String,System.String,System.Object[])\", Justification = \"Error imported from main project\")]\n[assembly: SuppressMessage(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\", Scope = \"member\", Target = \"System.Web.Http.Error.#Argument(System.String,System.Object[])\", Justification = \"Error imported from main project\")]\n[assembly: SuppressMessage(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\", Scope = \"member\", Target = \"System.Web.Http.Error.#ArgumentUriNotAbsolute(System.String,System.Uri)\", Justification = \"Error imported from main project\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"System.Web.Http\", Justification = \"Small extension project, distinct namespace\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"System.Web.Http.Tracing\", Justification = \"Small extension project, distinct namespace\")]"
  },
  {
    "path": "src/System.Web.Http.Tracing/HttpConfigurationExtensions.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Web.Http.Tracing;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// This static class contains helper methods related to the registration\n    /// of <see cref=\"ITraceWriter\"/> instances.\n    /// </summary>\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class HttpConfigurationTracingExtensions\n    {\n        /// <summary>\n        /// Creates and registers an <see cref=\"ITraceWriter\"/> implementation to use\n        /// for this application.\n        /// </summary>\n        /// <param name=\"configuration\">The <see cref=\"HttpConfiguration\"/> for which\n        /// to register the created trace writer.</param>\n        /// <remarks>The returned SystemDiagnosticsTraceWriter may be further configured to change it's default settings.</remarks>\n        /// <returns>The <see cref=\"SystemDiagnosticsTraceWriter\"/> which was created and registered.</returns>\n        public static SystemDiagnosticsTraceWriter EnableSystemDiagnosticsTracing(this HttpConfiguration configuration)\n        {\n            if (configuration == null)\n            {\n                throw new ArgumentNullException(\"configuration\");\n            }\n\n            SystemDiagnosticsTraceWriter traceWriter =\n                new SystemDiagnosticsTraceWriter()\n                {\n                    MinimumLevel = TraceLevel.Info,\n                    IsVerbose = false\n                };\n\n            configuration.Services.Replace(typeof(ITraceWriter), traceWriter);\n\n            return traceWriter;\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http.Tracing/Properties/AssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\n\n// General Information about an assembly is controlled through the following \n// set of attributes. Change these attribute values to modify the information\n// associated with an assembly.\n[assembly: AssemblyTitle(\"System.Web.Http.Tracing\")]\n[assembly: AssemblyDescription(\"\")]\n\n// The following GUID is for the ID of the typelib if this project is exposed to COM\n[assembly: Guid(\"8a696567-259c-46ed-b431-4179725fbe80\")]\n"
  },
  {
    "path": "src/System.Web.Http.Tracing/Properties/SRResources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.34003\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace System.Web.Http.Tracing.Properties {\n    using System;\n    \n    \n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class SRResources {\n        \n        private static global::System.Resources.ResourceManager resourceMan;\n        \n        private static global::System.Globalization.CultureInfo resourceCulture;\n        \n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal SRResources() {\n        }\n        \n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"System.Web.Http.Tracing.Properties.SRResources\", typeof(SRResources).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n        \n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Category=&apos;{0}&apos;.\n        /// </summary>\n        internal static string CategoryFormat {\n            get {\n                return ResourceManager.GetString(\"CategoryFormat\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Exception={0}.\n        /// </summary>\n        internal static string ExceptionFormat {\n            get {\n                return ResourceManager.GetString(\"ExceptionFormat\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Method={0}.\n        /// </summary>\n        internal static string HttpMethodFormat {\n            get {\n                return ResourceManager.GetString(\"HttpMethodFormat\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Status={0} ({1}).\n        /// </summary>\n        internal static string HttpStatusFormat {\n            get {\n                return ResourceManager.GetString(\"HttpStatusFormat\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Id={0}.\n        /// </summary>\n        internal static string IdFormat {\n            get {\n                return ResourceManager.GetString(\"IdFormat\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Message=&apos;{0}&apos;.\n        /// </summary>\n        internal static string MessageFormat {\n            get {\n                return ResourceManager.GetString(\"MessageFormat\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Operation={0}.{1}.\n        /// </summary>\n        internal static string OperationFormat {\n            get {\n                return ResourceManager.GetString(\"OperationFormat\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Request.\n        /// </summary>\n        internal static string ShortRequestFormat {\n            get {\n                return ResourceManager.GetString(\"ShortRequestFormat\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Response.\n        /// </summary>\n        internal static string ShortResponseFormat {\n            get {\n                return ResourceManager.GetString(\"ShortResponseFormat\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to [{0}] Level={1}, Kind={2}.\n        /// </summary>\n        internal static string TimeLevelKindFormat {\n            get {\n                return ResourceManager.GetString(\"TimeLevelKindFormat\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to [{0}] Request received.\n        /// </summary>\n        internal static string TimeRequestFormat {\n            get {\n                return ResourceManager.GetString(\"TimeRequestFormat\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to [{0}] Sending response.\n        /// </summary>\n        internal static string TimeResponseFormat {\n            get {\n                return ResourceManager.GetString(\"TimeResponseFormat\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The TraceLevel property must be a value between TraceLevel.Off and TraceLevel.Fatal, inclusive..\n        /// </summary>\n        internal static string TraceLevelOutOfRange {\n            get {\n                return ResourceManager.GetString(\"TraceLevelOutOfRange\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Url={0}.\n        /// </summary>\n        internal static string UrlFormat {\n            get {\n                return ResourceManager.GetString(\"UrlFormat\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.Tracing/Properties/SRResources.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"CategoryFormat\" xml:space=\"preserve\">\n    <value>Category='{0}'</value>\n  </data>\n  <data name=\"ExceptionFormat\" xml:space=\"preserve\">\n    <value>Exception={0}</value>\n  </data>\n  <data name=\"HttpMethodFormat\" xml:space=\"preserve\">\n    <value>Method={0}</value>\n  </data>\n  <data name=\"HttpStatusFormat\" xml:space=\"preserve\">\n    <value>Status={0} ({1})</value>\n  </data>\n  <data name=\"IdFormat\" xml:space=\"preserve\">\n    <value>Id={0}</value>\n  </data>\n  <data name=\"MessageFormat\" xml:space=\"preserve\">\n    <value>Message='{0}'</value>\n  </data>\n  <data name=\"OperationFormat\" xml:space=\"preserve\">\n    <value>Operation={0}.{1}</value>\n  </data>\n  <data name=\"ShortRequestFormat\" xml:space=\"preserve\">\n    <value>Request</value>\n  </data>\n  <data name=\"ShortResponseFormat\" xml:space=\"preserve\">\n    <value>Response</value>\n  </data>\n  <data name=\"TimeLevelKindFormat\" xml:space=\"preserve\">\n    <value>[{0}] Level={1}, Kind={2}</value>\n  </data>\n  <data name=\"TimeRequestFormat\" xml:space=\"preserve\">\n    <value>[{0}] Request received</value>\n  </data>\n  <data name=\"TimeResponseFormat\" xml:space=\"preserve\">\n    <value>[{0}] Sending response</value>\n  </data>\n  <data name=\"TraceLevelOutOfRange\" xml:space=\"preserve\">\n    <value>The TraceLevel property must be a value between TraceLevel.Off and TraceLevel.Fatal, inclusive.</value>\n  </data>\n  <data name=\"UrlFormat\" xml:space=\"preserve\">\n    <value>Url={0}</value>\n  </data>\n</root>"
  },
  {
    "path": "src/System.Web.Http.Tracing/System.Web.Http.Tracing.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{6E81EF98-8F5C-4EED-8B37-456991CA56FD}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>System.Web.Http.Tracing</RootNamespace>\n    <AssemblyName>System.Web.Http.Tracing</AssemblyName>\n    <DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>\n    <RunCodeAnalysis>$(CodeAnalysis)</RunCodeAnalysis>\n    <CodeAnalysisRuleSet>..\\Strict.ruleset</CodeAnalysisRuleSet>\n    <DefineConstants>$(DefineConstants);ASPNETMVC</DefineConstants>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Newtonsoft.Json.13.0.1\\lib\\net45\\Newtonsoft.Json.dll</HintPath>\n      <SpecificVersion>False</SpecificVersion>\n      <Private>False</Private>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Net.Http\" />\n    <Reference Include=\"System.Xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\CommonAssemblyInfo.cs\">\n      <Link>Properties\\CommonAssemblyInfo.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Error.cs\">\n      <Link>Common\\Error.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\TraceWriterExceptionMapper.cs\">\n      <Link>Common\\TraceWriterExceptionMapper.cs</Link>\n    </Compile>\n    <Compile Include=\"GlobalSuppressions.cs\" />\n    <Compile Include=\"HttpConfigurationExtensions.cs\" />\n    <Compile Include=\"SystemDiagnosticsTraceWriter.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"Properties\\SRResources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>SRResources.resx</DependentUpon>\n    </Compile>\n    <Compile Include=\"..\\Common\\CommonWebApiResources.Designer.cs\">\n      <Link>Properties\\CommonWebApiResources.Designer.cs</Link>\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>CommonWebApiResources.resx</DependentUpon>\n    </Compile>\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"..\\Common\\CommonWebApiResources.resx\">\n      <Link>Properties\\CommonWebApiResources.resx</Link>\n    </EmbeddedResource>\n    <EmbeddedResource Include=\"Properties\\SRResources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>SRResources.Designer.cs</LastGenOutput>\n      <SubType>Designer</SubType>\n    </EmbeddedResource>\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\System.Net.Http.Formatting\\System.Net.Http.Formatting.csproj\">\n      <Project>{668e9021-ce84-49d9-98fb-df125a9fcdb0}</Project>\n      <Name>System.Net.Http.Formatting</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.Http\\System.Web.Http.csproj\">\n      <Project>{ddc1ce0c-486e-4e35-bb3b-eab61f8f9440}</Project>\n      <Name>System.Web.Http</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n</Project>"
  },
  {
    "path": "src/System.Web.Http.Tracing/SystemDiagnosticsTraceWriter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Net.Http;\nusing System.Web.Http.Tracing.Properties;\n\nnamespace System.Web.Http.Tracing\n{\n    /// <summary>\n    /// Implementation of <see cref=\"ITraceWriter\"/> that traces to <see cref=\"System.Diagnostics.Trace\"/>\n    /// </summary>\n    public class SystemDiagnosticsTraceWriter : ITraceWriter\n    {\n        // Duplicate of internal category name traced by WebApi for start/end of request\n        private const string SystemWebHttpRequestCategory = \"System.Web.Http.Request\";\n\n        private static readonly TraceEventType[] TraceLevelToTraceEventType = new TraceEventType[]\n        {\n            // TraceLevel.Off\n            (TraceEventType)0,\n\n            // TraceLevel.Debug\n            TraceEventType.Verbose,\n\n            // TraceLevel.Info\n            TraceEventType.Information,\n\n            // TraceLevel.Warn\n            TraceEventType.Warning,\n\n            // TraceLevel.Error\n            TraceEventType.Error,\n\n            // TraceLevel.Fatal\n            TraceEventType.Critical\n        };\n\n        private TraceLevel _minLevel = TraceLevel.Info;\n\n        /// <summary>\n        /// Gets or sets the minimum trace level.\n        /// </summary>\n        /// <value>\n        /// Any <see cref=\"System.Web.Http.Tracing.TraceLevel\"/> below this\n        /// level will be ignored. The default for this property\n        /// is <see cref=\"TraceLevel.Info\"/>.\n        /// </value>\n        public TraceLevel MinimumLevel\n        {\n            get\n            {\n                return _minLevel;\n            }\n            set\n            {\n                if (value < TraceLevel.Off || value > TraceLevel.Fatal)\n                {\n                    throw Error.ArgumentOutOfRange(\"value\",\n                                                    value,\n                                                    SRResources.TraceLevelOutOfRange);\n                }\n\n                _minLevel = value;\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets a value indicating whether the formatted message\n        /// should be the verbose format, meaning it displays all fields\n        /// of the <see cref=\"TraceRecord\"/>.\n        /// </summary>\n        /// <value><c>true</c> means all <see cref=\"TraceRecord\"/> fields\n        /// will be traced, <c>false</c> means only minimal information\n        /// will be traced. The default value is <c>false</c>.</value>\n        public bool IsVerbose { get; set; }\n\n        /// <summary>\n        /// Gets or sets the <see cref=\"TraceSource\"/> to which the\n        /// traces will be sent.\n        /// </summary>\n        /// <value>\n        /// This property allows a custom <see cref=\"TraceSource\"/> \n        /// to be used when writing the traces.\n        /// This allows an application to configure and use its\n        /// own <see cref=\"TraceSource\"/> other than the default\n        /// <see cref=\"System.Diagnostics.Trace\"/>.\n        /// If the value is <c>null</c>, this trace writer will\n        /// send traces to <see cref=\"System.Diagnostics.Trace\"/>.\n        /// </value>\n        public TraceSource TraceSource { get; set; }\n\n        /// <summary>\n        /// Writes a trace to <see cref=\"System.Diagnostics.Trace\"/> if the\n        /// <paramref name=\"level\"/> is greater than or equal <see cref=\"MinimumLevel\"/>.\n        /// </summary>\n        /// <param name=\"request\">The <see cref=\"HttpRequestMessage\"/> associated with this trace. \n        /// It may be <c>null</c> but the resulting trace will contain no correlation ID.</param>\n        /// <param name=\"category\">The category for the trace. This can be any user-defined\n        /// value. It is not interpreted by this implementation but is written to the trace.</param>\n        /// <param name=\"level\">The <see cref=\"TraceLevel\"/> of this trace. If it is less than\n        /// <see cref=\"MinimumLevel\"/>, this trace request will be ignored.</param>\n        /// <param name=\"traceAction\">The user callback to invoke to fill in a <see cref=\"TraceRecord\"/>\n        /// with additional information to add to the trace.</param>\n        public virtual void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)\n        {\n            if (category == null)\n            {\n                throw Error.ArgumentNull(\"category\");\n            }\n\n            if (traceAction == null)\n            {\n                throw Error.ArgumentNull(\"traceAction\");\n            }\n\n            if (level < TraceLevel.Off || level > TraceLevel.Fatal)\n            {\n                throw Error.ArgumentOutOfRange(\"level\",\n                                                level,\n                                                SRResources.TraceLevelOutOfRange);\n            }\n\n            if (MinimumLevel == TraceLevel.Off || level < MinimumLevel)\n            {\n                return;\n            }\n\n            TraceRecord traceRecord = new TraceRecord(request, category, level);\n            traceAction(traceRecord);\n            TranslateHttpResponseException(traceRecord);\n            string message = Format(traceRecord);\n            if (!String.IsNullOrEmpty(message))\n            {\n                // Level may have changed in Translate above\n                TraceMessage(traceRecord.Level, message);\n            }\n        }\n\n        /// <summary>\n        /// Formats the contents of the given <see cref=\"TraceRecord\"/> into\n        /// a single string containing comma-separated name-value pairs\n        /// for each <see cref=\"TraceRecord\"/> property.\n        /// </summary>\n        /// <param name=\"traceRecord\">The <see cref=\"TraceRecord\"/> from which \n        /// to produce the result.</param>\n        /// <returns>A string containing comma-separated name-value pairs.</returns>\n        public virtual string Format(TraceRecord traceRecord)\n        {\n            if (traceRecord == null)\n            {\n                throw Error.ArgumentNull(\"traceRecord\");\n            }\n\n            // The first and last traces are injected by the tracing system itself.\n            // We use these to format unique strings identifying the incoming request\n            // and the outgoing response.\n            if (String.Equals(traceRecord.Category, SystemWebHttpRequestCategory, StringComparison.Ordinal))\n            {\n                return FormatRequestEnvelope(traceRecord);\n            }\n\n            List<string> messages = new List<string>();\n\n            if (!IsVerbose)\n            {\n                // In short format mode, we trace only End traces because it is\n                // where the results of each operation will appear.\n                if (traceRecord.Kind == TraceKind.Begin)\n                {\n                    return null;\n                }\n            }\n            else\n            {\n                messages.Add(Error.Format(SRResources.TimeLevelKindFormat,\n                                            FormatDateTime(traceRecord.Timestamp),\n                                            traceRecord.Level.ToString(),\n                                            traceRecord.Kind.ToString()));\n\n                if (!String.IsNullOrEmpty(traceRecord.Category))\n                {\n                    messages.Add(Error.Format(SRResources.CategoryFormat, traceRecord.Category));\n                }\n\n                messages.Add(Error.Format(SRResources.IdFormat, traceRecord.RequestId.ToString()));\n            }\n\n            if (!String.IsNullOrEmpty(traceRecord.Message))\n            {\n                messages.Add(Error.Format(SRResources.MessageFormat, traceRecord.Message));\n            }\n\n            if (traceRecord.Operator != null || traceRecord.Operation != null)\n            {\n                messages.Add(Error.Format(SRResources.OperationFormat, traceRecord.Operator, traceRecord.Operation));\n            }\n\n            if (traceRecord.Status != 0)\n            {\n                messages.Add(Error.Format(SRResources.HttpStatusFormat, (int)traceRecord.Status, traceRecord.Status.ToString()));\n            }\n\n            if (traceRecord.Exception != null)\n            {\n                messages.Add(Error.Format(SRResources.ExceptionFormat, traceRecord.Exception.ToString()));\n            }\n\n            return String.Join(\", \", messages);\n        }\n\n        /// <summary>\n        /// Formats the given <see cref=\"TraceRecord\"/> into a string describing\n        /// either the initial receipt of the incoming request or the final send\n        /// of the response, depending on <see cref=\"TraceKind\"/>.\n        /// </summary>\n        /// <param name=\"traceRecord\">The <see cref=\"TraceRecord\"/> from which to \n        /// produce the result.</param>\n        /// <returns>A string containing comma-separated name-value pairs.</returns>\n        public virtual string FormatRequestEnvelope(TraceRecord traceRecord)\n        {\n            if (traceRecord == null)\n            {\n                throw Error.ArgumentNull(\"traceRecord\");\n            }\n\n            List<string> messages = new List<string>();\n\n            if (IsVerbose)\n            {\n                messages.Add(Error.Format((traceRecord.Kind == TraceKind.Begin)\n                                                ? SRResources.TimeRequestFormat\n                                                : SRResources.TimeResponseFormat,\n                                            FormatDateTime(traceRecord.Timestamp)));\n            }\n            else\n            {\n                messages.Add((traceRecord.Kind == TraceKind.Begin)\n                                ? SRResources.ShortRequestFormat\n                                : SRResources.ShortResponseFormat);\n            }\n\n            if (traceRecord.Status != 0)\n            {\n                messages.Add(Error.Format(SRResources.HttpStatusFormat, (int)traceRecord.Status, traceRecord.Status.ToString()));\n            }\n\n            if (traceRecord.Request != null)\n            {\n                messages.Add(Error.Format(SRResources.HttpMethodFormat, traceRecord.Request.Method));\n\n                if (traceRecord.Request.RequestUri != null)\n                {\n                    messages.Add(Error.Format(SRResources.UrlFormat, traceRecord.Request.RequestUri.ToString()));\n                }\n            }\n\n            if (IsVerbose)\n            {\n                messages.Add(Error.Format(SRResources.IdFormat, traceRecord.RequestId.ToString()));\n            }\n\n            // The Message and Exception fields do not contain interesting information unless\n            // there is a problem, so they appear after the more informative trace information.\n            if (!String.IsNullOrEmpty(traceRecord.Message))\n            {\n                messages.Add(Error.Format(SRResources.MessageFormat, traceRecord.Message));\n            }\n\n            if (traceRecord.Exception != null)\n            {\n                messages.Add(Error.Format(SRResources.ExceptionFormat, traceRecord.Exception.ToString()));\n            }\n\n            return String.Join(\", \", messages);\n        }\n\n        /// <summary>\n        /// Examines the given <see cref=\"TraceRecord\"/> to determine whether it\n        /// contains an <see cref=\"HttpResponseException\"/> and if so, modifies\n        /// the <see cref=\"TraceRecord\"/> to capture more detailed information.\n        /// </summary>\n        /// <param name=\"traceRecord\">The <see cref=\"TraceRecord\"/> to examine and modify.</param>\n        public virtual void TranslateHttpResponseException(TraceRecord traceRecord)\n        {\n            if (traceRecord == null)\n            {\n                throw Error.ArgumentNull(\"traceRecord\");\n            }\n\n            TraceWriterExceptionMapper.TranslateHttpResponseException(traceRecord);\n        }\n\n        /// <summary>\n        /// Formats a <see cref=\"DateTime\"/> for the trace.\n        /// </summary>\n        /// <remarks>\n        /// The default implementation uses the ISO 8601 convention\n        /// for round-trippable dates so they can be parsed.\n        /// </remarks>\n        /// <param name=\"dateTime\">The <see cref=\"DateTime\"/></param>\n        /// <returns>The <see cref=\"DateTime\"/> formatted as a string</returns>\n        public virtual string FormatDateTime(DateTime dateTime)\n        {\n            // The 'o' format is ISO 8601 for a round-trippable DateTime.\n            // It is culture-invariant and can be parsed.\n            return dateTime.ToString(\"o\", CultureInfo.InvariantCulture);\n        }\n\n        private void TraceMessage(TraceLevel level, string message)\n        {\n            Contract.Assert(level >= TraceLevel.Off && level <= TraceLevel.Fatal);\n\n            // If the user registered a custom TraceSource, we write a trace event to it\n            // directly, preserving the event type.\n            TraceSource traceSource = TraceSource;\n            if (traceSource != null)\n            {\n                traceSource.TraceEvent(eventType: TraceLevelToTraceEventType[(int)level], id: 0, message: message);\n                return;\n            }\n\n            // If there is no custom TraceSource, trace to System.Diagnostics.Trace.\n            // But System.Diagnostics.Trace does not offer a public API to trace\n            // TraceEventType.Verbose or TraceEventType.Critical, meaning our\n            // TraceLevel.Debug and TraceLevel.Fatal cannot be report directly.\n            // Consequently, we translate Verbose to Trace.WriteLine and\n            // Critical to TraceEventType.Error.\n            // Windows Azure Diagnostics' TraceListener already translates\n            // a WriteLine to a Verbose, so on Azure the Debug trace will be\n            // handled properly.\n            switch (level)\n            {\n                case TraceLevel.Off:\n                    return;\n\n                case TraceLevel.Debug:\n                    System.Diagnostics.Trace.WriteLine(message);\n                    return;\n\n                case TraceLevel.Info:\n                    System.Diagnostics.Trace.TraceInformation(message);\n                    return;\n\n                case TraceLevel.Warn:\n                    System.Diagnostics.Trace.TraceWarning(message);\n                    return;\n\n                case TraceLevel.Error:\n                case TraceLevel.Fatal:\n                    System.Diagnostics.Trace.TraceError(message);\n                    return;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.Tracing/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Newtonsoft.Json\" version=\"13.0.1\" targetFramework=\"net45\" />\n</packages>"
  },
  {
    "path": "src/System.Web.Http.WebHost/GlobalConfiguration.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.WebHost;\nusing System.Web.Http.WebHost.Routing;\nusing System.Web.Routing;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Provides a global <see cref=\"T:System.Web.Http.HttpConfiguration\"/> for ASP.NET applications.\n    /// </summary>\n    public static class GlobalConfiguration\n    {\n        private static Lazy<HttpConfiguration> _configuration = CreateConfiguration();\n\n        private static Lazy<HttpMessageHandler> _defaultHandler = CreateDefaultHandler();\n\n        private static Lazy<HttpServer> _defaultServer = CreateDefaultServer();\n\n        /// <summary>\n        /// Gets the global <see cref=\"T:System.Web.Http.HttpConfiguration\"/>.\n        /// </summary>\n        public static HttpConfiguration Configuration\n        {\n            get { return _configuration.Value; }\n        }\n\n        /// <summary>\n        /// Gets the default message handler that will be called for all requests.\n        /// </summary>\n        public static HttpMessageHandler DefaultHandler\n        {\n            get { return _defaultHandler.Value; }\n        }\n\n        /// <summary>\n        /// Gets the global <see cref=\"T:System.Web.Http.HttpServer\"/>.\n        /// </summary>\n        public static HttpServer DefaultServer\n        {\n            get { return _defaultServer.Value; }\n        }\n\n        /// <summary>\n        /// Performs configuration for <see cref=\"GlobalConfiguration.Configuration\"/> and ensures that it is\n        /// initialized.\n        /// </summary>\n        /// <param name=\"configurationCallback\">The callback that will perform the configuration.</param>\n        public static void Configure(Action<HttpConfiguration> configurationCallback)\n        {\n            if (configurationCallback == null)\n            {\n                throw new ArgumentNullException(\"configurationCallback\");\n            }\n\n            configurationCallback.Invoke(Configuration);\n            Configuration.EnsureInitialized();\n        }\n\n        internal static void Reset()\n        {\n            _configuration = CreateConfiguration();\n            _defaultHandler = CreateDefaultHandler();\n            _defaultServer = CreateDefaultServer();\n        }\n\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000\",\n            Justification = \"It does not appear possible for this construction code to throw.\")]\n        private static Lazy<HttpConfiguration> CreateConfiguration()\n        {\n            return new Lazy<HttpConfiguration>(() =>\n            {\n                HttpConfiguration config = new HttpConfiguration(new HostedHttpRouteCollection(RouteTable.Routes));\n                ServicesContainer services = config.Services;\n                Contract.Assert(services != null);\n                services.Replace(typeof(IAssembliesResolver), new WebHostAssembliesResolver());\n                services.Replace(typeof(IHttpControllerTypeResolver), new WebHostHttpControllerTypeResolver());\n                services.Replace(typeof(IHostBufferPolicySelector), new WebHostBufferPolicySelector());\n                services.Replace(typeof(IExceptionHandler),\n                    new WebHostExceptionHandler(services.GetExceptionHandler()));\n                return config;\n            });\n        }\n\n        private static Lazy<HttpMessageHandler> CreateDefaultHandler()\n        {\n            return new Lazy<HttpMessageHandler>(() => new HttpRoutingDispatcher(_configuration.Value));\n        }\n\n        private static Lazy<HttpServer> CreateDefaultServer()\n        {\n            return new Lazy<HttpServer>(() => new HttpServer(_configuration.Value, _defaultHandler.Value));\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http.WebHost/GlobalSuppressions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA2210:AssembliesShouldHaveValidStrongNames\", Justification = \"These assemblies are delay-signed.\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Justification = \"Classes are grouped logically for user clarity.\", Scope = \"Namespace\", Target = \"System.Net.Http\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Justification = \"Classes are grouped logically for user clarity.\", Scope = \"Namespace\", Target = \"System.Web.Http.WebHost\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Justification = \"Classes are here so that they're shared with the main DLL's namespace\", Scope = \"Namespace\", Target = \"System.Web.Http\")]\n[assembly: SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Scope = \"member\", Target = \"System.Web.Http.GlobalConfiguration.#.cctor()\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"System.Web.Http.WebHost.Routing\", Justification = \"This is the most logical namespace for this type.\")]\n[assembly: SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Scope = \"member\", Target = \"System.Web.Http.WebHost.HttpControllerHandler.#.cctor()\", Justification = \"HttpServer is disposed by HttpMessageInvoker.\")]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1703:ResourceStringsShouldBeSpelledCorrectly\", MessageId = \"Bufferless\", Scope = \"resource\", Target = \"System.Web.Http.WebHost.Properties.SRResources.resources\", Justification = \"The term Bufferless comes from the API\")]\n"
  },
  {
    "path": "src/System.Web.Http.WebHost/HttpBatchContextWrapper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Net.Http;\nusing System.Security.Principal;\nusing System.Web.Http.WebHost.Routing;\n\nnamespace System.Web.Http.WebHost\n{\n    internal class HttpBatchContextWrapper : HttpContextBase\n    {\n        private HttpRequestMessageWrapper _httpRequestWrapper;\n        private HttpContextBase _httpContextBase;\n        private Hashtable _items;\n\n        public HttpBatchContextWrapper(HttpContextBase httpContext, HttpRequestMessage httpRequest)\n        {\n            _httpContextBase = httpContext;\n            _items = new Hashtable();\n            _httpRequestWrapper = new HttpRequestMessageWrapper(httpContext.Request.ApplicationPath, httpRequest);\n        }\n\n        public override HttpRequestBase Request\n        {\n            get { return _httpRequestWrapper; }\n        }\n\n        public override HttpResponseBase Response\n        {\n            get { return _httpContextBase.Response; }\n        }\n\n        public override IDictionary Items\n        {\n            get { return _items; }\n        }\n\n        public override IPrincipal User\n        {\n            get\n            {\n                return _httpContextBase.User;\n            }\n            set\n            {\n                _httpContextBase.User = value;\n            }\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http.WebHost/HttpControllerHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.IO;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Headers;\nusing System.Runtime.ExceptionServices;\nusing System.Security.Cryptography.X509Certificates;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Configuration;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.Routing;\nusing System.Web.Http.WebHost.Properties;\nusing System.Web.Http.WebHost.Routing;\nusing System.Web.Routing;\n\nnamespace System.Web.Http.WebHost\n{\n    /// <summary>\n    /// An <see cref=\"HttpTaskAsyncHandler\"/> that uses an <see cref=\"HttpServer\"/> to process ASP.NET requests asynchronously.\n    /// </summary>\n    [SuppressMessage(\"Microsoft.Maintainability\", \"CA1506:AvoidExcessiveClassCoupling\", Justification = \"This class is a coordinator, so this coupling is expected.\")]\n    [SuppressMessage(\"Microsoft.Design\", \"CA1001:Implement IDisposable\", Justification = \"HttpMessageInvoker doesn’t have any resources of its own to dispose.\")]\n    public class HttpControllerHandler : HttpTaskAsyncHandler\n    {\n        // See Microsoft.Owin.Host.SystemWeb.\n        internal static readonly string OwinEnvironmentHttpContextKey = \"owin.Environment\";\n\n        internal static readonly string OwinEnvironmentKey = \"MS_OwinEnvironment\";\n\n        private static readonly Lazy<Action<HttpContextBase>> _suppressRedirectAction =\n            new Lazy<Action<HttpContextBase>>(\n                () =>\n                {\n                    // If the behavior is explicitly disabled, do nothing\n                    if (!SuppressFormsAuthRedirectHelper.GetEnabled(WebConfigurationManager.AppSettings))\n                    {\n                        return httpContext => { };\n                    }\n\n                    return httpContext => httpContext.Response.SuppressFormsAuthenticationRedirect = true;\n                });\n\n        private static readonly Lazy<IHostBufferPolicySelector> _bufferPolicySelector =\n            new Lazy<IHostBufferPolicySelector>(() => GlobalConfiguration.Configuration.Services.GetHostBufferPolicySelector());\n\n        private static readonly Lazy<IExceptionHandler> _exceptionHandler = new Lazy<IExceptionHandler>(() =>\n            ExceptionServices.GetHandler(GlobalConfiguration.Configuration));\n        private static readonly Lazy<IExceptionLogger> _exceptionLogger = new Lazy<IExceptionLogger>(() =>\n            ExceptionServices.GetLogger(GlobalConfiguration.Configuration));\n\n        private static readonly Func<HttpRequestMessage, X509Certificate2> _retrieveClientCertificate = new Func<HttpRequestMessage, X509Certificate2>(RetrieveClientCertificate);\n\n        private readonly IHttpRouteData _routeData;\n        private readonly HttpMessageInvoker _server;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpControllerHandler\"/> class.\n        /// </summary>\n        /// <param name=\"routeData\">The route data.</param>\n        public HttpControllerHandler(RouteData routeData)\n            : this(routeData, GlobalConfiguration.DefaultServer)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpControllerHandler\"/> class.\n        /// </summary>\n        /// <param name=\"routeData\">The route data.</param>\n        /// <param name=\"handler\">The message handler to dispatch requests to.</param>\n        public HttpControllerHandler(RouteData routeData, HttpMessageHandler handler)\n        {\n            if (routeData == null)\n            {\n                throw Error.ArgumentNull(\"routeData\");\n            }\n            if (handler == null)\n            {\n                throw Error.ArgumentNull(\"handler\");\n            }\n\n            _routeData = new HostedHttpRouteData(routeData);\n            _server = new HttpMessageInvoker(handler);\n        }\n\n        public override Task ProcessRequestAsync(HttpContext context)\n        {\n            return ProcessRequestAsyncCore(new HttpContextWrapper(context));\n        }\n\n        internal async Task ProcessRequestAsyncCore(HttpContextBase contextBase)\n        {\n            HttpRequestMessage request = contextBase.GetHttpRequestMessage() ?? ConvertRequest(contextBase);\n\n            // Add route data\n            request.SetRouteData(_routeData);\n            CancellationToken cancellationToken = contextBase.Response.GetClientDisconnectedTokenWhenFixed();\n            HttpResponseMessage response = null;\n\n            try\n            {\n                response = await _server.SendAsync(request, cancellationToken);\n                await CopyResponseAsync(contextBase, request, response, _exceptionLogger.Value, _exceptionHandler.Value,\n                    cancellationToken);\n            }\n            catch (OperationCanceledException)\n            {\n                // HttpTaskAsyncHandler treats a canceled task as an unhandled exception (logged to Application event\n                // log). Instead of returning a canceled task, abort the request and return a completed task.\n                contextBase.Request.Abort();\n            }\n            finally\n            {\n                // The other HttpTaskAsyncHandler is HttpRouteExceptionHandler; it has similar cleanup logic.\n                request.DisposeRequestResources();\n                request.Dispose();\n\n                if (response != null)\n                {\n                    response.Dispose();\n                }\n            }\n        }\n\n        private static void CopyHeaders(HttpHeaders from, HttpContextBase to)\n        {\n            Contract.Assert(from != null);\n            Contract.Assert(to != null);\n\n            foreach (var header in from)\n            {\n                string name = header.Key;\n                foreach (var value in header.Value)\n                {\n                    to.Response.AppendHeader(name, value);\n                }\n            }\n        }\n\n        private static void AddHeaderToHttpRequestMessage(HttpRequestMessage httpRequestMessage, string headerName, string[] headerValues)\n        {\n            Contract.Assert(httpRequestMessage != null);\n            Contract.Assert(headerName != null);\n            Contract.Assert(headerValues != null);\n\n            if (!httpRequestMessage.Headers.TryAddWithoutValidation(headerName, headerValues))\n            {\n                httpRequestMessage.Content.Headers.TryAddWithoutValidation(headerName, headerValues);\n            }\n        }\n\n        internal static async Task CopyResponseAsync(HttpContextBase httpContextBase, HttpRequestMessage request,\n            HttpResponseMessage response, IExceptionLogger exceptionLogger, IExceptionHandler exceptionHandler,\n            CancellationToken cancellationToken)\n        {\n            Contract.Assert(httpContextBase != null);\n            Contract.Assert(request != null);\n\n            // A null response creates a 500 with no content\n            if (response == null)\n            {\n                SetEmptyErrorResponse(httpContextBase.Response);\n                return;\n            }\n\n            if (!await CopyResponseStatusAndHeadersAsync(httpContextBase, request, response, exceptionLogger,\n                cancellationToken))\n            {\n                return;\n            }\n\n            // TODO 335085: Consider this when coming up with our caching story\n            if (response.Headers.CacheControl == null)\n            {\n                // DevDiv2 #332323. ASP.NET by default always emits a cache-control: private header.\n                // However, we don't want requests to be cached by default.\n                // If nobody set an explicit CacheControl then explicitly set to no-cache to override the\n                // default behavior. This will cause the following response headers to be emitted:\n                //     Cache-Control: no-cache\n                //     Pragma: no-cache\n                //     Expires: -1\n                httpContextBase.Response.Cache.SetCacheability(HttpCacheability.NoCache);\n            }\n\n            // Asynchronously write the response body.  If there is no body, we use\n            // a completed task to share the Finally() below.\n            // The response-writing task will not fault -- it handles errors internally.\n            if (response.Content != null)\n            {\n                await WriteResponseContentAsync(httpContextBase, request, response, exceptionLogger, exceptionHandler, cancellationToken);\n            }\n        }\n\n        internal static HttpRequestMessage ConvertRequest(HttpContextBase httpContextBase)\n        {\n            return ConvertRequest(httpContextBase, _bufferPolicySelector.Value);\n        }\n\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"Caller becomes owner\")]\n        internal static HttpRequestMessage ConvertRequest(HttpContextBase httpContextBase, IHostBufferPolicySelector policySelector)\n        {\n            Contract.Assert(httpContextBase != null);\n\n            HttpRequestBase requestBase = httpContextBase.Request;\n            HttpMethod method = HttpMethodHelper.GetHttpMethod(requestBase.HttpMethod);\n            Uri uri = requestBase.Url;\n            HttpRequestMessage request = new HttpRequestMessage(method, uri);\n\n            // Choose a buffered or bufferless input stream based on user's policy\n            bool bufferInput = policySelector == null ? true : policySelector.UseBufferedInputStream(httpContextBase);\n            request.Content = GetStreamContent(requestBase, bufferInput);\n\n            foreach (string headerName in requestBase.Headers)\n            {\n                string[] values = requestBase.Headers.GetValues(headerName);\n                AddHeaderToHttpRequestMessage(request, headerName, values);\n            }\n\n            // Add context to enable route lookup later on\n            request.SetHttpContext(httpContextBase);\n\n            HttpRequestContext requestContext = new WebHostHttpRequestContext(httpContextBase, requestBase, request);\n            request.SetRequestContext(requestContext);\n\n            IDictionary httpContextItems = httpContextBase.Items;\n\n            // Add the OWIN environment, when available (such as when using the OWIN integrated pipeline HTTP module).\n            if (httpContextItems != null && httpContextItems.Contains(OwinEnvironmentHttpContextKey))\n            {\n                request.Properties.Add(OwinEnvironmentKey, httpContextItems[OwinEnvironmentHttpContextKey]);\n            }\n\n            // The following three properties are set for backwards compatibility only. The request context controls\n            // the behavior for all cases except when accessing the property directly by key.\n\n            // Add the retrieve client certificate delegate to the property bag to enable lookup later on\n            request.Properties.Add(HttpPropertyKeys.RetrieveClientCertificateDelegateKey, _retrieveClientCertificate);\n\n            // Add information about whether the request is local or not\n            request.Properties.Add(HttpPropertyKeys.IsLocalKey, new Lazy<bool>(() => requestBase.IsLocal));\n\n            // Add information about whether custom errors are enabled for this request or not\n            request.Properties.Add(HttpPropertyKeys.IncludeErrorDetailKey, new Lazy<bool>(() => !httpContextBase.IsCustomErrorEnabled));\n\n            return request;\n        }\n\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"Caller becomes owner\")]\n        private static HttpContent GetStreamContent(HttpRequestBase requestBase, bool bufferInput)\n        {\n            if (bufferInput)\n            {\n                return new LazyStreamContent(() =>\n                {\n                    if (requestBase.ReadEntityBodyMode == ReadEntityBodyMode.None)\n                    {\n                        return new SeekableBufferedRequestStream(requestBase);\n                    }\n                    else if (requestBase.ReadEntityBodyMode == ReadEntityBodyMode.Classic)\n                    {\n                        requestBase.InputStream.Position = 0;\n                        return requestBase.InputStream;\n                    }\n                    else if (requestBase.ReadEntityBodyMode == ReadEntityBodyMode.Buffered)\n                    {\n                        if (requestBase.GetBufferedInputStream().Position > 0)\n                        {\n                            // If GetBufferedInputStream() was completely read, we can continue accessing it via Request.InputStream.\n                            // If it was partially read, accessing InputStream will throw, but at that point we have no\n                            // way of recovering.\n                            requestBase.InputStream.Position = 0;\n                            return requestBase.InputStream;\n                        }\n                        return new SeekableBufferedRequestStream(requestBase);\n                    }\n                    else\n                    {\n                        Contract.Assert(requestBase.ReadEntityBodyMode == ReadEntityBodyMode.Bufferless);\n                        throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,\n                                                                          SRResources.RequestBodyAlreadyReadInMode,\n                                                                          ReadEntityBodyMode.Bufferless));\n                    }\n                });\n            }\n            else\n            {\n                return new LazyStreamContent(() =>\n                {\n                    if (requestBase.ReadEntityBodyMode == ReadEntityBodyMode.None)\n                    {\n                        return requestBase.GetBufferlessInputStream();\n                    }\n                    else if (requestBase.ReadEntityBodyMode == ReadEntityBodyMode.Classic)\n                    {\n                        // The user intended that the request be read in a bufferless manner, but we are starting with a buffered stream.\n                        // To maintain compatibility with legacy behavior, we'll throw in this case.\n                        throw new InvalidOperationException(SRResources.RequestStreamCannotBeReadBufferless);\n                    }\n                    else if (requestBase.ReadEntityBodyMode == ReadEntityBodyMode.Bufferless)\n                    {\n                        Stream bufferlessInputStream = requestBase.GetBufferlessInputStream();\n                        if (bufferlessInputStream.Position > 0)\n                        {\n                            throw new InvalidOperationException(SRResources.RequestBodyAlreadyRead);\n                        }\n                        return bufferlessInputStream;\n                    }\n                    else\n                    {\n                        Contract.Assert(requestBase.ReadEntityBodyMode == ReadEntityBodyMode.Buffered);\n                        throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SRResources.RequestBodyAlreadyReadInMode, ReadEntityBodyMode.Buffered));\n                    }\n                });\n            }\n        }\n\n        /// <summary>\n        /// Prevents the <see cref=\"T:System.Web.Security.FormsAuthenticationModule\"/> from altering a 401 response to 302 by\n        /// setting <see cref=\"P:System.Web.HttpResponseBase.SuppressFormsAuthenticationRedirect\" /> to <c>true</c> if available.\n        /// </summary>\n        /// <param name=\"httpContextBase\">The HTTP context base.</param>\n        internal static void EnsureSuppressFormsAuthenticationRedirect(HttpContextBase httpContextBase)\n        {\n            Contract.Assert(httpContextBase != null);\n\n            // Only if the response is status code is 401\n            if (httpContextBase.Response.StatusCode == (int)HttpStatusCode.Unauthorized)\n            {\n                _suppressRedirectAction.Value(httpContextBase);\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1804:RemoveUnusedLocals\", MessageId = \"unused\", Justification = \"unused variable necessary to call getter\")]\n        private static Task WriteResponseContentAsync(HttpContextBase httpContextBase, HttpRequestMessage request,\n            HttpResponseMessage response, IExceptionLogger exceptionLogger, IExceptionHandler exceptionHandler,\n            CancellationToken cancellationToken)\n        {\n            Contract.Assert(httpContextBase != null);\n            Contract.Assert(response != null);\n            Contract.Assert(request != null);\n            Contract.Assert(response.Content != null);\n\n            HttpResponseBase httpResponseBase = httpContextBase.Response;\n            HttpContent responseContent = response.Content;\n\n            CopyHeaders(responseContent.Headers, httpContextBase);\n\n            // PrepareHeadersAsync already evaluated the buffer policy.\n            bool isBuffered = httpResponseBase.BufferOutput;\n\n            return isBuffered\n                    ? WriteBufferedResponseContentAsync(httpContextBase, request, response, exceptionLogger, exceptionHandler, cancellationToken)\n                    : WriteStreamedResponseContentAsync(httpContextBase, request, response, exceptionLogger, cancellationToken);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"All exceptions caught here become error responses\")]\n        internal static async Task WriteStreamedResponseContentAsync(HttpContextBase httpContextBase,\n            HttpRequestMessage request, HttpResponseMessage response, IExceptionLogger exceptionLogger,\n            CancellationToken cancellationToken)\n        {\n            Contract.Assert(httpContextBase != null);\n            Contract.Assert(httpContextBase.Response != null);\n            Contract.Assert(request != null);\n            Contract.Assert(response != null);\n            Contract.Assert(response.Content != null);\n\n            Exception exception = null;\n            cancellationToken.ThrowIfCancellationRequested();\n\n            try\n            {\n                // Copy the HttpContent into the output stream asynchronously.\n                await response.Content.CopyToAsync(httpContextBase.Response.OutputStream);\n                return;\n            }\n            catch (OperationCanceledException)\n            {\n                // Propogate the canceled task without calling exception loggers.\n                throw;\n            }\n            catch (Exception ex)\n            {\n                exception = ex;\n            }\n\n            Contract.Assert(exception != null);\n\n            ExceptionContextCatchBlock catchBlock = WebHostExceptionCatchBlocks.HttpControllerHandlerStreamContent;\n            ExceptionContext exceptionContext = new ExceptionContext(exception, catchBlock, request, response);\n            await exceptionLogger.LogAsync(exceptionContext, cancellationToken);\n\n            // Streamed content may have been written and cannot be recalled.\n            // Our only choice is to abort the connection.\n            httpContextBase.Request.Abort();\n        }\n\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"continuation task owned by caller\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"All exceptions caught here become error responses\")]\n        internal static async Task WriteBufferedResponseContentAsync(HttpContextBase httpContextBase,\n            HttpRequestMessage request, HttpResponseMessage response, IExceptionLogger exceptionLogger,\n            IExceptionHandler exceptionHandler, CancellationToken cancellationToken)\n        {\n            Contract.Assert(httpContextBase != null);\n            Contract.Assert(httpContextBase.Response != null);\n            Contract.Assert(request != null);\n            Contract.Assert(response != null);\n            Contract.Assert(response.Content != null);\n\n            HttpResponseBase httpResponseBase = httpContextBase.Response;\n\n            // Return a task that writes the response body asynchronously.\n            // We guarantee we will handle all error responses internally\n            // and always return a non-faulted task, except for custom error handlers that choose to propagate these\n            // exceptions.\n            ExceptionDispatchInfo exceptionInfo;\n            cancellationToken.ThrowIfCancellationRequested();\n\n            try\n            {\n                // Copy the HttpContent into the output stream asynchronously.\n                await response.Content.CopyToAsync(httpResponseBase.OutputStream);\n                return;\n            }\n            catch (OperationCanceledException)\n            {\n                // Propogate the canceled task without calling exception loggers or handlers.\n                throw;\n            }\n            catch (Exception exception)\n            {\n                // Can't use await inside a catch block\n                exceptionInfo = ExceptionDispatchInfo.Capture(exception);\n            }\n\n            Debug.Assert(exceptionInfo.SourceException != null);\n\n            // If we were using a buffered stream, we can still set the headers and status code, and we can create an\n            // error response with the exception.\n            // We create a continuation task to write an error response that will run after returning from this Catch()\n            // but before other continuations the caller appends to this task.\n            // The error response writing task handles errors internally and will not show as faulted, except for\n            // custom error handlers that choose to propagate these exceptions.\n            ExceptionContextCatchBlock catchBlock = WebHostExceptionCatchBlocks.HttpControllerHandlerBufferContent;\n\n            if (!await CopyErrorResponseAsync(catchBlock, httpContextBase, request, response,\n                exceptionInfo.SourceException, exceptionLogger, exceptionHandler, cancellationToken))\n            {\n                exceptionInfo.Throw();\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"All exceptions caught here become error responses\")]\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"errorResponse gets disposed in the async continuation\")]\n        internal static async Task<bool> CopyErrorResponseAsync(ExceptionContextCatchBlock catchBlock,\n            HttpContextBase httpContextBase, HttpRequestMessage request, HttpResponseMessage response,\n            Exception exception, IExceptionLogger exceptionLogger, IExceptionHandler exceptionHandler,\n            CancellationToken cancellationToken)\n        {\n            Contract.Assert(httpContextBase != null);\n            Contract.Assert(httpContextBase.Response != null);\n            Contract.Assert(request != null);\n            Contract.Assert(exception != null);\n            Contract.Assert(catchBlock != null);\n            Contract.Assert(catchBlock.CallsHandler);\n\n            HttpResponseBase httpResponseBase = httpContextBase.Response;\n            HttpResponseMessage errorResponse = null;\n            HttpResponseException responseException = exception as HttpResponseException;\n\n            // Ensure all headers and content are cleared to eliminate any partial results.\n            ClearContentAndHeaders(httpResponseBase);\n\n            // If the exception we are handling is HttpResponseException,\n            // that becomes the error response.\n            if (responseException != null)\n            {\n                errorResponse = responseException.Response;\n            }\n            else\n            {\n                ExceptionContext exceptionContext = new ExceptionContext(exception, catchBlock, request)\n                {\n                    Response = response\n                };\n                await exceptionLogger.LogAsync(exceptionContext, cancellationToken);\n                errorResponse = await exceptionHandler.HandleAsync(exceptionContext, cancellationToken);\n\n                if (errorResponse == null)\n                {\n                    return false;\n                }\n            }\n\n            Contract.Assert(errorResponse != null);\n            if (!await CopyResponseStatusAndHeadersAsync(httpContextBase, request, errorResponse, exceptionLogger,\n                cancellationToken))\n            {\n                // Don't rethrow the original exception unless explicitly requested to do so. In this case, the\n                // exception handler indicated it wanted to handle the exception; it simply failed create a stable\n                // response to send.\n                return true;\n            }\n\n            // The error response may return a null content if content negotiation\n            // fails to find a formatter, or this may be an HttpResponseException without\n            // content.  In either case, cleanup and return a completed task.\n\n            if (errorResponse.Content == null)\n            {\n                errorResponse.Dispose();\n                return true;\n            }\n\n            CopyHeaders(errorResponse.Content.Headers, httpContextBase);\n\n            await WriteErrorResponseContentAsync(httpResponseBase, request, errorResponse, cancellationToken,\n                exceptionLogger);\n            return true;\n        }\n\n        private static async Task WriteErrorResponseContentAsync(HttpResponseBase httpResponseBase,\n            HttpRequestMessage request, HttpResponseMessage errorResponse, CancellationToken cancellationToken,\n            IExceptionLogger exceptionLogger)\n        {\n            HttpRequestMessage ignoreUnused = request;\n\n            try\n            {\n                Exception exception = null;\n                cancellationToken.ThrowIfCancellationRequested();\n\n                try\n                {\n                    // Asynchronously write the content of the new error HttpResponseMessage\n                    await errorResponse.Content.CopyToAsync(httpResponseBase.OutputStream);\n                    return;\n                }\n                catch (OperationCanceledException)\n                {\n                    // Propogate the canceled task without calling exception loggers.\n                    throw;\n                }\n                catch (Exception ex)\n                {\n                    exception = ex;\n                }\n\n                Contract.Assert(exception != null);\n\n                ExceptionContext exceptionContext = new ExceptionContext(exception,\n                    WebHostExceptionCatchBlocks.HttpControllerHandlerBufferError, request, errorResponse);\n                await exceptionLogger.LogAsync(exceptionContext, cancellationToken);\n\n                // Failure writing the error response.  Likely cause is a formatter\n                // serialization exception.  Create empty error response and\n                // return a non-faulted task.\n                SetEmptyErrorResponse(httpResponseBase);\n            }\n            finally\n            {\n                // Dispose the temporary HttpResponseMessage carrying the error response\n                errorResponse.Dispose();\n            }\n        }\n\n        private static async Task<bool> CopyResponseStatusAndHeadersAsync(HttpContextBase httpContextBase,\n            HttpRequestMessage request, HttpResponseMessage response, IExceptionLogger exceptionLogger,\n            CancellationToken cancellationToken)\n        {\n            Contract.Assert(httpContextBase != null);\n            HttpResponseBase httpResponseBase = httpContextBase.Response;\n            httpResponseBase.StatusCode = (int)response.StatusCode;\n            httpResponseBase.StatusDescription = response.ReasonPhrase;\n            httpResponseBase.TrySkipIisCustomErrors = true;\n            EnsureSuppressFormsAuthenticationRedirect(httpContextBase);\n\n            if (!await PrepareHeadersAsync(httpResponseBase, request, response, exceptionLogger, cancellationToken))\n            {\n                return false;\n            }\n\n            CopyHeaders(response.Headers, httpContextBase);\n            return true;\n        }\n\n        // Prepares Content-Length and Transfer-Encoding headers.\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1804:RemoveUnusedLocals\", MessageId = \"unused\", Justification = \"unused variable necessary to call getter\")]\n        internal static async Task<bool> PrepareHeadersAsync(HttpResponseBase responseBase, HttpRequestMessage request,\n            HttpResponseMessage response, IExceptionLogger exceptionLogger, CancellationToken cancellationToken)\n        {\n            Contract.Assert(response != null);\n            HttpResponseHeaders responseHeaders = response.Headers;\n            Contract.Assert(responseHeaders != null);\n            HttpContent content = response.Content;\n            bool isTransferEncodingChunked = responseHeaders.TransferEncodingChunked == true;\n            HttpHeaderValueCollection<TransferCodingHeaderValue> transferEncoding = responseHeaders.TransferEncoding;\n\n            if (content != null)\n            {\n                HttpContentHeaders contentHeaders = content.Headers;\n                Contract.Assert(contentHeaders != null);\n\n                if (isTransferEncodingChunked)\n                {\n                    // According to section 4.4 of the HTTP 1.1 spec, HTTP responses that use chunked transfer\n                    // encoding must not have a content length set. Chunked should take precedence over content\n                    // length in this case because chunked is always set explicitly by users while the Content-Length\n                    // header can be added implicitly by System.Net.Http.\n                    contentHeaders.ContentLength = null;\n                }\n                else\n                {\n                    Exception exception = null;\n\n                    // Copy the response content headers only after ensuring they are complete.\n                    // We ask for Content-Length first because HttpContent lazily computes this\n                    // and only afterwards writes the value into the content headers.\n                    try\n                    {\n                        var unused = contentHeaders.ContentLength;\n                    }\n                    catch (Exception ex)\n                    {\n                        exception = ex;\n                    }\n\n                    if (exception != null)\n                    {\n                        ExceptionContext exceptionContext = new ExceptionContext(exception,\n                            WebHostExceptionCatchBlocks.HttpControllerHandlerComputeContentLength, request, response);\n                        await exceptionLogger.LogAsync(exceptionContext, cancellationToken);\n\n                        SetEmptyErrorResponse(responseBase);\n                        return false;\n                    }\n                }\n\n                // Select output buffering based on the user-controlled buffering policy\n                bool isBuffered = _bufferPolicySelector.Value != null ?\n                    _bufferPolicySelector.Value.UseBufferedOutputStream(response) : true;\n                responseBase.BufferOutput = isBuffered;\n            }\n\n            // Ignore the Transfer-Encoding header if it is just \"chunked\"; the host will provide it when no\n            // Content-Length is present and BufferOutput is disabled (and this method guarantees those conditions).\n            // HttpClient sets this header when it receives chunked content, but HttpContent does not include the\n            // frames. The ASP.NET contract is to set this header only when writing chunked frames to the stream.\n            // A Web API caller who desires custom framing would need to do a different Transfer-Encoding (such as\n            // \"identity, chunked\").\n            if (isTransferEncodingChunked && transferEncoding.Count == 1)\n            {\n                transferEncoding.Clear();\n\n                // In the case of a conflict between a Transfer-Encoding: chunked header and the output buffering\n                // policy, honor the Transnfer-Encoding: chunked header and ignore the buffer policy.\n                // If output buffering is not disabled, ASP.NET will not write the TransferEncoding: chunked header.\n                responseBase.BufferOutput = false;\n            }\n\n            return true;\n        }\n\n        private static void ClearContentAndHeaders(HttpResponseBase httpResponseBase)\n        {\n            httpResponseBase.Clear();\n\n            // Despite what the documentation indicates, calling Clear on its own doesn't fully clear the headers.\n            httpResponseBase.ClearHeaders();\n        }\n\n        private static void SetEmptyErrorResponse(HttpResponseBase httpResponseBase)\n        {\n            ClearContentAndHeaders(httpResponseBase);\n            httpResponseBase.StatusCode = (int)HttpStatusCode.InternalServerError;\n            httpResponseBase.SuppressContent = true;\n        }\n\n        private static X509Certificate2 RetrieveClientCertificate(HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            X509Certificate2 result = null;\n\n            HttpContextBase httpContextBase = request.GetHttpContext();\n            if (httpContextBase != null)\n            {\n                if (httpContextBase.Request.ClientCertificate.Certificate != null && httpContextBase.Request.ClientCertificate.Certificate.Length > 0)\n                {\n                    result = new X509Certificate2(httpContextBase.Request.ClientCertificate.Certificate);\n                }\n            }\n\n            return result;\n        }\n\n        private class DelegatingStreamContent : StreamContent\n        {\n            public DelegatingStreamContent(Stream stream)\n                : base(stream)\n            {\n            }\n\n            public Task WriteToStreamAsync(Stream stream, TransportContext context)\n            {\n                return SerializeToStreamAsync(stream, context);\n            }\n\n            public Task<Stream> GetContentReadStreamAsync()\n            {\n                return CreateContentReadStreamAsync();\n            }\n\n            protected override bool TryComputeLength(out long length)\n            {\n                // Do not attempt to calculate length because SeekableBufferedRequestStream (for example)\n                // may report 0 until the underlying Stream has been read to end.\n                length = 0L;\n                return false;\n            }\n        }\n\n        private class LazyStreamContent : HttpContent\n        {\n            private readonly Func<Stream> _getStream;\n            private DelegatingStreamContent _streamContent;\n\n            public LazyStreamContent(Func<Stream> getStream)\n            {\n                _getStream = getStream;\n            }\n\n            private DelegatingStreamContent StreamContent\n            {\n                get\n                {\n                    if (_streamContent == null)\n                    {\n                        _streamContent = new DelegatingStreamContent(_getStream());\n                    }\n                    return _streamContent;\n                }\n            }\n\n            protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)\n            {\n                return StreamContent.WriteToStreamAsync(stream, context);\n            }\n\n            protected override Task<Stream> CreateContentReadStreamAsync()\n            {\n                return StreamContent.GetContentReadStreamAsync();\n            }\n\n            protected override bool TryComputeLength(out long length)\n            {\n                // Do not attempt to calculate length because SeekableBufferedRequestStream (for example)\n                // may report 0 until the underlying Stream has been read to end.\n                length = 0L;\n                return false;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.WebHost/HttpControllerRouteHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Routing;\n\nnamespace System.Web.Http.WebHost\n{\n    /// <summary>\n    /// A <see cref=\"IRouteHandler\"/> that returns instances of <see cref=\"HttpControllerHandler\"/> that\n    /// can pass requests to a given <see cref=\"HttpServer\"/> instance.\n    /// </summary>\n    public class HttpControllerRouteHandler : IRouteHandler\n    {\n        private static readonly Lazy<HttpControllerRouteHandler> _instance =\n            new Lazy<HttpControllerRouteHandler>(() => new HttpControllerRouteHandler(), isThreadSafe: true);\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HttpControllerRouteHandler\"/> class.\n        /// </summary>\n        protected HttpControllerRouteHandler()\n        {\n        }\n\n        /// <summary>\n        /// Gets the singleton <see cref=\"HttpControllerRouteHandler\"/> instance.\n        /// </summary>\n        public static HttpControllerRouteHandler Instance\n        {\n            get { return _instance.Value; }\n        }\n\n        /// <summary>\n        /// Provides the object that processes the request.\n        /// </summary>\n        /// <param name=\"requestContext\">An object that encapsulates information about the request.</param>\n        /// <returns>\n        /// An object that processes the request.\n        /// </returns>\n        IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)\n        {\n            return GetHttpHandler(requestContext);\n        }\n\n        /// <summary>\n        /// Provides the object that processes the request.\n        /// </summary>\n        /// <param name=\"requestContext\">An object that encapsulates information about the request.</param>\n        /// <returns>\n        /// An object that processes the request.\n        /// </returns>\n        protected virtual IHttpHandler GetHttpHandler(RequestContext requestContext)\n        {\n            return new HttpControllerHandler(requestContext.RouteData);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.WebHost/HttpControllerTypeCacheSerializer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.WebHost.Properties;\nusing System.Xml;\n\nnamespace System.Web.Http.WebHost\n{\n    // Processes files with this format:\n    //\n    // <typeCache lastModified=... mvcVersionId=...>\n    //   <assembly name=...>\n    //     <module versionId=...>\n    //       <type>...</type>\n    //     </module>\n    //   </assembly>\n    // </typeCache>\n    //\n    // This is used to store caches of files between AppDomain resets, leading to improved cold boot time\n    // and more efficient use of memory.\n\n    /// <summary>\n    /// Manages serializing and deserializing the cache managed by <see cref=\"HttpControllerTypeCache\"/>.\n    /// </summary>\n    internal sealed class HttpControllerTypeCacheSerializer\n    {\n        private static readonly Guid _mvcVersionId = typeof(HttpControllerTypeCacheSerializer).Module.ModuleVersionId;\n\n        // used for unit testing\n\n        private DateTime CurrentDate\n        {\n            get { return CurrentDateOverride ?? DateTime.Now; }\n        }\n\n        internal DateTime? CurrentDateOverride { get; set; }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"This is an instance method for consistency with the SerializeTypes() method.\")]\n        public ICollection<Type> DeserializeTypes(TextReader input)\n        {\n            // DevDiv: 314059: TypeCacheSerializer should use regular serialization instead of DOM\n            XmlDocument doc = new XmlDocument();\n            doc.Load(input);\n            XmlElement rootElement = doc.DocumentElement;\n\n            Guid readMvcVersionId = new Guid(rootElement.Attributes[\"mvcVersionId\"].Value);\n            if (readMvcVersionId != _mvcVersionId)\n            {\n                // The cache is outdated because the cache file was produced by a different version\n                // of MVC.\n                return null;\n            }\n\n            List<Type> deserializedTypes = new List<Type>();\n            foreach (XmlNode assemblyNode in rootElement.ChildNodes)\n            {\n                string assemblyName = assemblyNode.Attributes[\"name\"].Value;\n                Assembly assembly = Assembly.Load(assemblyName);\n\n                foreach (XmlNode moduleNode in assemblyNode.ChildNodes)\n                {\n                    Guid moduleVersionId = new Guid(moduleNode.Attributes[\"versionId\"].Value);\n\n                    foreach (XmlNode typeNode in moduleNode.ChildNodes)\n                    {\n                        string typeName = typeNode.InnerText;\n                        Type type = assembly.GetType(typeName);\n                        if (type == null || type.Module.ModuleVersionId != moduleVersionId)\n                        {\n                            // The cache is outdated because we couldn't find a previously recorded\n                            // type or the type's containing module was modified.\n                            return null;\n                        }\n                        else\n                        {\n                            deserializedTypes.Add(type);\n                        }\n                    }\n                }\n            }\n\n            return deserializedTypes;\n        }\n\n        public void SerializeTypes(IEnumerable<Type> types, TextWriter output)\n        {\n            var groupedByAssembly = from type in types\n                                    group type by type.Module\n                                    into groupedByModule\n                                    group groupedByModule by groupedByModule.Key.Assembly;\n\n            XmlDocument doc = new XmlDocument();\n            doc.AppendChild(doc.CreateComment(SRResources.TypeCache_DoNotModify));\n\n            XmlElement typeCacheElement = doc.CreateElement(\"typeCache\");\n            doc.AppendChild(typeCacheElement);\n            typeCacheElement.SetAttribute(\"lastModified\", CurrentDate.ToString(CultureInfo.InvariantCulture));\n            typeCacheElement.SetAttribute(\"mvcVersionId\", _mvcVersionId.ToString());\n\n            foreach (var assemblyGroup in groupedByAssembly)\n            {\n                XmlElement assemblyElement = doc.CreateElement(\"assembly\");\n                typeCacheElement.AppendChild(assemblyElement);\n                assemblyElement.SetAttribute(\"name\", assemblyGroup.Key.FullName);\n\n                foreach (var moduleGroup in assemblyGroup)\n                {\n                    XmlElement moduleElement = doc.CreateElement(\"module\");\n                    assemblyElement.AppendChild(moduleElement);\n                    moduleElement.SetAttribute(\"versionId\", moduleGroup.Key.ModuleVersionId.ToString());\n\n                    foreach (Type type in moduleGroup)\n                    {\n                        XmlElement typeElement = doc.CreateElement(\"type\");\n                        moduleElement.AppendChild(typeElement);\n                        typeElement.AppendChild(doc.CreateTextNode(type.FullName));\n                    }\n                }\n            }\n\n            doc.Save(output);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.WebHost/HttpRequestMessageExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\n\nnamespace System.Web.Http.WebHost\n{\n    internal static class HttpRequestMessageExtensions\n    {\n        private const string HttpContextBaseKey = \"MS_HttpContext\";\n        private const string HttpBatchContextKey = \"MS_HttpBatchContext\";\n\n        public static HttpContextBase GetHttpContext(this HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw new ArgumentNullException(\"request\");\n            }\n\n            HttpContextBase context;\n\n            if (request.IsBatchRequest())\n            {\n                if (!request.Properties.TryGetValue(HttpBatchContextKey, out context))\n                {\n                    if (request.Properties.TryGetValue(HttpContextBaseKey, out context))\n                    {\n                        context = new HttpBatchContextWrapper(context, request);\n                        request.Properties[HttpBatchContextKey] = context;\n                    }\n                    else\n                    {\n                        context = null;\n                    }\n                }\n            }\n            else if (!request.Properties.TryGetValue(HttpContextBaseKey, out context))\n            {\n                context = null;\n            }\n\n            return context;\n        }\n\n        public static void SetHttpContext(this HttpRequestMessage request, HttpContextBase context)\n        {\n            if (request == null)\n            {\n                throw new ArgumentNullException(\"request\");\n            }\n            if (context == null)\n            {\n                throw new ArgumentNullException(\"context\");\n            }\n\n            request.Properties[HttpContextBaseKey] = context;\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http.WebHost/HttpResponseBaseExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing System.Threading;\n\nnamespace System.Web.Http.WebHost\n{\n    internal static class HttpResponseBaseExtensions\n    {\n        private static readonly bool _isSystemWebVersion451OrGreater = IsSystemWebVersion451OrGreater();\n        private static readonly bool _isClientDisconnectedTokenAvailable = IsClientDisconnectedTokenAvailable();\n\n        public static CancellationToken GetClientDisconnectedTokenWhenFixed(this HttpResponseBase response)\n        {\n            if (response == null)\n            {\n                throw new ArgumentNullException(\"response\");\n            }\n\n            // On some platforms/configurations, accessing response.ClientDisconnectedToken would always throw.\n            // Also, on .NET 4.5 and earlier, using response.ClientDisconnectedToken can cause application crashes.\n            // Gracefully degrade to CancellationToken.None unless ClientDisconnectedToken is both available and\n            // reliable.\n            if (!_isClientDisconnectedTokenAvailable || !_isSystemWebVersion451OrGreater)\n            {\n                return CancellationToken.None;\n            }\n\n            return response.ClientDisconnectedToken;\n        }\n\n        private static bool IsClientDisconnectedTokenAvailable()\n        {\n            // Accessing HttpResponse.ClientDisconnectedToken throws PlatformNotSupportedException unless both:\n            // 1) Using IIS 7.5 or newer, and\n            // 2) Using integrated pipeline\n            Version iis75 = new Version(7, 5);\n            Version iisVersion = HttpRuntime.IISVersion;\n            return iisVersion != null && iisVersion >= iis75 && HttpRuntime.UsingIntegratedPipeline;\n        }\n\n        private static bool IsSystemWebVersion451OrGreater()\n        {\n            Assembly systemWeb = typeof(HttpContextBase).Assembly;\n            // System.Web.AspNetEventSource only exists in .NET 4.5.1 and will not be back-ported to .NET 4.5.\n            return systemWeb.GetType(\"System.Web.AspNetEventSource\") != null;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.WebHost/PreApplicationStartCode.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\n\nnamespace System.Web.Http.WebHost\n{\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    [Obsolete(\"Use of this type is not recommended because it no longer has initialization logic.\")]\n    public static class PreApplicationStartCode\n    {\n        private static bool _startWasCalled;\n\n        public static void Start()\n        {\n            // Guard against multiple calls. All Start calls are made on same thread, so no lock needed here\n            if (_startWasCalled)\n            {\n                return;\n            }\n            _startWasCalled = true;\n\n            // We need to keep this for App-Compat reasons. Prior to 4.5 we registered a module here.\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.WebHost/Properties/AssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Web;\nusing System.Web.Http.WebHost;\n\n[assembly: AssemblyTitle(\"System.Web.Http.WebHost\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: InternalsVisibleTo(\"System.Web.Http.WebHost.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n"
  },
  {
    "path": "src/System.Web.Http.WebHost/Properties/SRResources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.34003\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace System.Web.Http.WebHost.Properties {\n    using System;\n    \n    \n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class SRResources {\n        \n        private static global::System.Resources.ResourceManager resourceMan;\n        \n        private static global::System.Globalization.CultureInfo resourceCulture;\n        \n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal SRResources() {\n        }\n        \n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"System.Web.Http.WebHost.Properties.SRResources\", typeof(SRResources).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n        \n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Unable to read the entity body. A portion of the request stream has already been read..\n        /// </summary>\n        internal static string RequestBodyAlreadyRead {\n            get {\n                return ResourceManager.GetString(\"RequestBodyAlreadyRead\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Unable to read the entity body. The request stream has already been read in &apos;{0}&apos; mode..\n        /// </summary>\n        internal static string RequestBodyAlreadyReadInMode {\n            get {\n                return ResourceManager.GetString(\"RequestBodyAlreadyReadInMode\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Unable to read the entity body in Bufferless mode. The request stream has already been buffered..\n        /// </summary>\n        internal static string RequestStreamCannotBeReadBufferless {\n            get {\n                return ResourceManager.GetString(\"RequestStreamCannotBeReadBufferless\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The constraint entry &apos;{0}&apos; on the route with route template &apos;{1}&apos; must have a string value or be of a type which implements &apos;{2}&apos; or &apos;{3}&apos;..\n        /// </summary>\n        internal static string Route_ValidationMustBeStringOrCustomConstraint {\n            get {\n                return ResourceManager.GetString(\"Route_ValidationMustBeStringOrCustomConstraint\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to This operation is not supported by &apos;{0}&apos;..\n        /// </summary>\n        internal static string RouteCollectionNotSupported {\n            get {\n                return ResourceManager.GetString(\"RouteCollectionNotSupported\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The index cannot be less than 0 or equal to or larger than the number of items in the collection..\n        /// </summary>\n        internal static string RouteCollectionOutOfRange {\n            get {\n                return ResourceManager.GetString(\"RouteCollectionOutOfRange\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to This operation is only supported by directly calling it on &apos;{0}&apos;..\n        /// </summary>\n        internal static string RouteCollectionUseDirectly {\n            get {\n                return ResourceManager.GetString(\"RouteCollectionUseDirectly\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &apos;{0}&apos; type failed to serialize the response body..\n        /// </summary>\n        internal static string Serialize_Response_Failed {\n            get {\n                return ResourceManager.GetString(\"Serialize_Response_Failed\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &apos;{0}&apos; type failed to serialize the response body for content type &apos;{1}&apos;..\n        /// </summary>\n        internal static string Serialize_Response_Failed_MediaType {\n            get {\n                return ResourceManager.GetString(\"Serialize_Response_Failed_MediaType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to This file is automatically generated. Please do not modify the contents of this file..\n        /// </summary>\n        internal static string TypeCache_DoNotModify {\n            get {\n                return ResourceManager.GetString(\"TypeCache_DoNotModify\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to {0}.{1} must not be null..\n        /// </summary>\n        internal static string TypePropertyMustNotBeNull {\n            get {\n                return ResourceManager.GetString(\"TypePropertyMustNotBeNull\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.WebHost/Properties/SRResources.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"RequestBodyAlreadyRead\" xml:space=\"preserve\">\n    <value>Unable to read the entity body. A portion of the request stream has already been read.</value>\n  </data>\n  <data name=\"RequestBodyAlreadyReadInMode\" xml:space=\"preserve\">\n    <value>Unable to read the entity body. The request stream has already been read in '{0}' mode.</value>\n  </data>\n  <data name=\"RequestStreamCannotBeReadBufferless\" xml:space=\"preserve\">\n    <value>Unable to read the entity body in Bufferless mode. The request stream has already been buffered.</value>\n  </data>\n  <data name=\"RouteCollectionNotSupported\" xml:space=\"preserve\">\n    <value>This operation is not supported by '{0}'.</value>\n  </data>\n  <data name=\"RouteCollectionOutOfRange\" xml:space=\"preserve\">\n    <value>The index cannot be less than 0 or equal to or larger than the number of items in the collection.</value>\n  </data>\n  <data name=\"RouteCollectionUseDirectly\" xml:space=\"preserve\">\n    <value>This operation is only supported by directly calling it on '{0}'.</value>\n  </data>\n  <data name=\"Route_ValidationMustBeStringOrCustomConstraint\" xml:space=\"preserve\">\n    <value>The constraint entry '{0}' on the route with route template '{1}' must have a string value or be of a type which implements '{2}' or '{3}'.</value>\n  </data>\n  <data name=\"Serialize_Response_Failed\" xml:space=\"preserve\">\n    <value>The '{0}' type failed to serialize the response body.</value>\n  </data>\n  <data name=\"Serialize_Response_Failed_MediaType\" xml:space=\"preserve\">\n    <value>The '{0}' type failed to serialize the response body for content type '{1}'.</value>\n  </data>\n  <data name=\"TypeCache_DoNotModify\" xml:space=\"preserve\">\n    <value>This file is automatically generated. Please do not modify the contents of this file.</value>\n  </data>\n  <data name=\"TypePropertyMustNotBeNull\" xml:space=\"preserve\">\n    <value>{0}.{1} must not be null.</value>\n  </data>\n</root>"
  },
  {
    "path": "src/System.Web.Http.WebHost/RouteCollectionExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Net.Http;\nusing System.Web.Http.Routing;\nusing System.Web.Http.WebHost.Routing;\nusing System.Web.Routing;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Extension methods for <see cref=\"RouteCollection\"/>\n    /// </summary>\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class RouteCollectionExtensions\n    {\n        /// <summary>\n        /// Maps the specified route template.\n        /// </summary>\n        /// <param name=\"routes\">A collection of routes for the application.</param>\n        /// <param name=\"name\">The name of the route to map.</param>\n        /// <param name=\"routeTemplate\">The route template for the route.</param>\n        /// <returns>A reference to the mapped route.</returns>\n        public static Route MapHttpRoute(this RouteCollection routes, string name, string routeTemplate)\n        {\n            return MapHttpRoute(routes, name, routeTemplate, defaults: null, constraints: null, handler: null);\n        }\n\n        /// <summary>\n        /// Maps the specified route template and sets default constraints, and namespaces.\n        /// </summary>\n        /// <param name=\"routes\">A collection of routes for the application.</param>\n        /// <param name=\"name\">The name of the route to map.</param>\n        /// <param name=\"routeTemplate\">The route template for the route.</param>\n        /// <param name=\"defaults\">An object that contains default route values.</param>\n        /// <returns>A reference to the mapped route.</returns>\n        public static Route MapHttpRoute(this RouteCollection routes, string name, string routeTemplate, object defaults)\n        {\n            return MapHttpRoute(routes, name, routeTemplate, defaults, constraints: null, handler: null);\n        }\n\n        /// <summary>\n        /// Maps the specified route template and sets default route values, constraints, and namespaces.\n        /// </summary>\n        /// <param name=\"routes\">A collection of routes for the application.</param>\n        /// <param name=\"name\">The name of the route to map.</param>\n        /// <param name=\"routeTemplate\">The route template for the route.</param>\n        /// <param name=\"defaults\">An object that contains default route values.</param>\n        /// <param name=\"constraints\">A set of expressions that specify values for <paramref name=\"routeTemplate\"/>.</param>\n        /// <returns>A reference to the mapped route.</returns>\n        public static Route MapHttpRoute(this RouteCollection routes, string name, string routeTemplate, object defaults, object constraints)\n        {\n            return MapHttpRoute(routes, name, routeTemplate, defaults, constraints, handler: null);\n        }\n\n        /// <summary>\n        /// Maps the specified route template and sets default route values, constraints, namespaces, and end-point message handler.\n        /// </summary>\n        /// <param name=\"routes\">A collection of routes for the application.</param>\n        /// <param name=\"name\">The name of the route to map.</param>\n        /// <param name=\"routeTemplate\">The route template for the route.</param>\n        /// <param name=\"defaults\">An object that contains default route values.</param>\n        /// <param name=\"constraints\">A set of expressions that specify values for <paramref name=\"routeTemplate\"/>.</param>\n        /// <param name=\"handler\">The handler to which the request will be dispatched.</param>\n        /// <returns>A reference to the mapped route.</returns>\n        public static Route MapHttpRoute(this RouteCollection routes, string name, string routeTemplate, object defaults, object constraints, HttpMessageHandler handler)\n        {\n            if (routes == null)\n            {\n                throw Error.ArgumentNull(\"routes\");\n            }\n\n            HttpRouteValueDictionary defaultsDictionary = new HttpRouteValueDictionary(defaults);\n            HttpRouteValueDictionary constraintsDictionary = new HttpRouteValueDictionary(constraints);\n            HostedHttpRoute httpRoute = (HostedHttpRoute)GlobalConfiguration.Configuration.Routes.CreateRoute(routeTemplate, defaultsDictionary, constraintsDictionary, dataTokens: null, handler: handler);\n            Route route = httpRoute.OriginalRoute;\n            routes.Add(name, route);\n            return route;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.WebHost/Routing/HostedHttpRoute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Web.Http.Routing;\nusing System.Web.Routing;\n\nnamespace System.Web.Http.WebHost.Routing\n{\n    internal class HostedHttpRoute : IHttpRoute\n    {\n        public HostedHttpRoute(string uriTemplate, IDictionary<string, object> defaults, IDictionary<string, object> constraints, IDictionary<string, object> dataTokens, HttpMessageHandler handler)\n        {\n            RouteValueDictionary routeDefaults = defaults != null ? new RouteValueDictionary(defaults) : null;\n            RouteValueDictionary routeConstraints = constraints != null ? new RouteValueDictionary(constraints) : null;\n            RouteValueDictionary routeDataTokens = dataTokens != null ? new RouteValueDictionary(dataTokens) : null;\n            OriginalRoute = new HttpWebRoute(uriTemplate, routeDefaults, routeConstraints, routeDataTokens, HttpControllerRouteHandler.Instance, this);\n            Handler = handler;\n        }\n\n        public string RouteTemplate\n        {\n            get { return OriginalRoute.Url; }\n        }\n\n        public IDictionary<string, object> Defaults\n        {\n            get { return OriginalRoute.Defaults; }\n        }\n\n        public IDictionary<string, object> Constraints\n        {\n            get { return OriginalRoute.Constraints; }\n        }\n\n        public IDictionary<string, object> DataTokens\n        {\n            get { return OriginalRoute.DataTokens; }\n        }\n\n        public HttpMessageHandler Handler { get; private set; }\n\n        internal Route OriginalRoute { get; private set; }\n\n        public IHttpRouteData GetRouteData(string rootVirtualPath, HttpRequestMessage request)\n        {\n            if (rootVirtualPath == null)\n            {\n                throw Error.ArgumentNull(\"rootVirtualPath\");\n            }\n\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            HttpContextBase httpContextBase = request.GetHttpContext();\n            if (httpContextBase == null)\n            {\n                httpContextBase = new HttpRequestMessageContextWrapper(rootVirtualPath, request);\n            }\n\n            RouteData routeData = OriginalRoute.GetRouteData(httpContextBase);\n            if (routeData != null)\n            {\n                return new HostedHttpRouteData(routeData);\n            }\n\n            return null;\n        }\n\n        public IHttpVirtualPathData GetVirtualPath(HttpRequestMessage request, IDictionary<string, object> values)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            HttpContextBase httpContextBase = request.GetHttpContext();\n            if (httpContextBase != null)\n            {\n                HostedHttpRouteData routeData = request.GetRouteData() as HostedHttpRouteData;\n                if (routeData != null)\n                {\n                    RequestContext requestContext = new RequestContext(httpContextBase, routeData.OriginalRouteData);\n                    VirtualPathData virtualPathData = OriginalRoute.GetVirtualPath(requestContext, new RouteValueDictionary(values));\n                    if (virtualPathData != null)\n                    {\n                        return new HostedHttpVirtualPathData(virtualPathData, routeData.Route);\n                    }\n                }\n            }\n\n            return null;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.WebHost/Routing/HostedHttpRouteCollection.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Web.Hosting;\nusing System.Web.Http.Routing;\nusing System.Web.Http.WebHost.Properties;\nusing System.Web.Routing;\n\nnamespace System.Web.Http.WebHost.Routing\n{\n    internal class HostedHttpRouteCollection : HttpRouteCollection\n    {\n        private readonly RouteCollection _routeCollection;\n        private readonly string _virtualPathRoot;\n\n        public HostedHttpRouteCollection(RouteCollection routeCollection)\n            : this(routeCollection, virtualPathRoot: null)\n        {\n        }\n\n        public HostedHttpRouteCollection(RouteCollection routeCollection, string virtualPathRoot)\n        {\n            if (routeCollection == null)\n            {\n                throw Error.ArgumentNull(\"routeCollection\");\n            }\n\n            _routeCollection = routeCollection;\n            _virtualPathRoot = virtualPathRoot;\n        }\n\n        /// <inheritdoc/>\n        public override string VirtualPathRoot\n        {\n            get\n            {\n                if (_virtualPathRoot == null)\n                {\n                    return HostingEnvironment.ApplicationVirtualPath;\n                }\n                else\n                {\n                    return _virtualPathRoot;\n                }\n            }\n        }\n\n        /// <inheritdoc/>\n        public override int Count\n        {\n            get { return _routeCollection.Count; }\n        }\n\n        /// <inheritdoc/>\n        public override IHttpRoute this[string name]\n        {\n            get\n            {\n                HttpWebRoute route = _routeCollection[name] as HttpWebRoute;\n                if (route != null)\n                {\n                    return route.HttpRoute;\n                }\n\n                throw Error.KeyNotFound();\n            }\n        }\n\n        /// <inheritdoc/>\n        public override IHttpRoute this[int index]\n        {\n            get\n            {\n                HttpWebRoute route = _routeCollection[index] as HttpWebRoute;\n                if (route != null)\n                {\n                    return route.HttpRoute;\n                }\n\n                throw Error.ArgumentOutOfRange(\"index\", index, SRResources.RouteCollectionOutOfRange);\n            }\n        }\n\n        /// <inheritdoc/>\n        public override IHttpRouteData GetRouteData(HttpRequestMessage request)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            HttpContextBase httpContextBase = request.GetHttpContext();\n            if (httpContextBase == null)\n            {\n                httpContextBase = new HttpRequestMessageContextWrapper(VirtualPathRoot, request);\n            }\n\n            if (httpContextBase.GetHttpRequestMessage() == null)\n            {\n                httpContextBase.SetHttpRequestMessage(request);\n            }\n\n            RouteData routeData = _routeCollection.GetRouteData(httpContextBase);\n            // If the match is from an IgnoreRoute, do not return a RouteData but return a null, which will be treated as a 404 NoRouteMatched.\n            if (routeData != null && !(routeData.RouteHandler is System.Web.Routing.StopRoutingHandler))\n            {\n                return new HostedHttpRouteData(routeData);\n            }\n\n            return null;\n        }\n\n        /// <inheritdoc/>\n        public override IHttpVirtualPathData GetVirtualPath(HttpRequestMessage request, string name, IDictionary<string, object> values)\n        {\n            if (request == null)\n            {\n                throw Error.ArgumentNull(\"request\");\n            }\n\n            HttpContextBase httpContextBase = request.GetHttpContext();\n            if (httpContextBase == null)\n            {\n                httpContextBase = new HttpRequestMessageContextWrapper(VirtualPathRoot, request);\n            }\n\n            if (httpContextBase.GetHttpRequestMessage() == null)\n            {\n                httpContextBase.SetHttpRequestMessage(request);\n            }\n\n            IHttpRouteData routeData = request.GetRouteData();\n            if (routeData == null)\n            {\n                return null;\n            }\n\n            RequestContext requestContext = new RequestContext(httpContextBase, routeData.ToRouteData());\n            RouteValueDictionary routeValues = values != null ? new RouteValueDictionary(values) : new RouteValueDictionary();\n            VirtualPathData virtualPathData = _routeCollection.GetVirtualPath(requestContext, name, routeValues);\n\n            if (virtualPathData != null)\n            {\n                // If the route is not an HttpWebRoute, try getting a virtual path without the httproute key in the route value dictionary\n                // This ensures that httproute isn't picked up by non-WebAPI routes that might pollute the virtual path with httproute\n                if (!(virtualPathData.Route is HttpWebRoute))\n                {\n                    if (routeValues.Remove(HttpWebRoute.HttpRouteKey))\n                    {\n                        VirtualPathData virtualPathDataWithoutHttpRouteValue = _routeCollection.GetVirtualPath(requestContext, name, routeValues);\n                        if (virtualPathDataWithoutHttpRouteValue != null)\n                        {\n                            virtualPathData = virtualPathDataWithoutHttpRouteValue;\n                        }\n                    }\n                }\n\n                return new HostedHttpVirtualPathData(virtualPathData, routeData.Route);\n            }\n\n            return null;\n        }\n\n        /// <inheritdoc/>\n        public override IHttpRoute CreateRoute(string uriTemplate, IDictionary<string, object> defaults, IDictionary<string, object> constraints, IDictionary<string, object> dataTokens, HttpMessageHandler handler)\n        {\n            if (constraints != null)\n            {\n                foreach (var constraint in constraints)\n                {\n                    ValidateConstraint(uriTemplate, constraint.Key, constraint.Value);\n                }\n            }\n\n            return new HostedHttpRoute(uriTemplate, defaults, constraints, dataTokens, handler);\n        }\n\n        /// <inheritdoc/>\n        protected override void ValidateConstraint(string routeTemplate, string name, object constraint)\n        {\n            // In WebHost the constraint might be IHttpRouteConstraint or IRouteConstraint (System.Web) or a string\n            HttpWebRoute.ValidateConstraint(routeTemplate, name, constraint);\n        }\n\n        /// <inheritdoc/>\n        public override void Add(string name, IHttpRoute route)\n        {\n            _routeCollection.Add(name, route.ToRoute());\n        }\n\n        /// <inheritdoc/>\n        public override void Clear()\n        {\n            _routeCollection.Clear();\n        }\n\n        /// <inheritdoc/>\n        public override bool Contains(IHttpRoute item)\n        {\n            foreach (RouteBase route in _routeCollection)\n            {\n                HttpWebRoute webRoute = route as HttpWebRoute;\n                if (webRoute != null && webRoute.HttpRoute == item)\n                {\n                    return true;\n                }\n            }\n\n            return false;\n        }\n\n        /// <inheritdoc/>\n        public override bool ContainsKey(string name)\n        {\n            return _routeCollection[name] != null;\n        }\n\n        /// <inheritdoc/>\n        public override void CopyTo(IHttpRoute[] array, int arrayIndex)\n        {\n            throw NotSupportedByHostedRouteCollection();\n        }\n\n        /// <inheritdoc/>\n        public override void CopyTo(KeyValuePair<string, IHttpRoute>[] array, int arrayIndex)\n        {\n            throw NotSupportedByRouteCollection();\n        }\n\n        /// <inheritdoc/>\n        public override void Insert(int index, string name, IHttpRoute value)\n        {\n            throw NotSupportedByRouteCollection();\n        }\n\n        /// <inheritdoc/>\n        public override bool Remove(string name)\n        {\n            throw NotSupportedByRouteCollection();\n        }\n\n        /// <inheritdoc/>\n        public override IEnumerator<IHttpRoute> GetEnumerator()\n        {\n            // Here we only care about Web API routes.\n            return _routeCollection\n                .OfType<HttpWebRoute>()\n                .Select(httpWebRoute => httpWebRoute.HttpRoute)\n                .GetEnumerator();\n        }\n\n        /// <inheritdoc/>\n        public override bool TryGetValue(string name, out IHttpRoute route)\n        {\n            HttpWebRoute rt = _routeCollection[name] as HttpWebRoute;\n            if (rt != null)\n            {\n                route = rt.HttpRoute;\n                return true;\n            }\n\n            route = null;\n            return false;\n        }\n\n        private static NotSupportedException NotSupportedByRouteCollection()\n        {\n            return Error.NotSupported(SRResources.RouteCollectionNotSupported, typeof(HostedHttpRouteCollection).Name);\n        }\n\n        private static NotSupportedException NotSupportedByHostedRouteCollection()\n        {\n            return Error.NotSupported(SRResources.RouteCollectionUseDirectly, typeof(RouteCollection).Name);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.WebHost/Routing/HostedHttpRouteData.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http.Routing;\nusing System.Web.Routing;\n\nnamespace System.Web.Http.WebHost.Routing\n{\n    internal class HostedHttpRouteData : IHttpRouteData\n    {\n        public HostedHttpRouteData(RouteData routeData)\n        {\n            if (routeData == null)\n            {\n                throw Error.ArgumentNull(\"routeData\");\n            }\n\n            OriginalRouteData = routeData;\n\n            HttpWebRoute route = routeData.Route as HttpWebRoute;\n            Route = route == null ? null : route.HttpRoute;\n        }\n\n        public IHttpRoute Route { get; private set; }\n\n        public IDictionary<string, object> Values\n        {\n            get { return OriginalRouteData.Values; }\n        }\n\n        internal RouteData OriginalRouteData { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.WebHost/Routing/HostedHttpVirtualPathData.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Routing;\nusing System.Web.Routing;\n\nnamespace System.Web.Http.WebHost.Routing\n{\n    internal class HostedHttpVirtualPathData : IHttpVirtualPathData\n    {\n        private readonly VirtualPathData _virtualPath;\n\n        public HostedHttpVirtualPathData(VirtualPathData virtualPath, IHttpRoute httpRoute)\n        {\n            if (virtualPath == null)\n            {\n                throw Error.ArgumentNull(\"route\");\n            }\n\n            _virtualPath = virtualPath;\n            Route = httpRoute;\n        }\n\n        public IHttpRoute Route { get; private set; }\n\n        public string VirtualPath\n        {\n            get { return _virtualPath.VirtualPath; }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.PropertyNull();\n                }\n                _virtualPath.VirtualPath = value;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.WebHost/Routing/HttpContextBaseExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\n\nnamespace System.Web.Http.WebHost.Routing\n{\n    internal static class HttpContextBaseExtensions\n    {\n        internal static readonly string HttpRequestMessageKey = \"MS_HttpRequestMessage\";\n\n        public static HttpRequestMessage GetHttpRequestMessage(this HttpContextBase context)\n        {\n            if (context == null)\n            {\n                throw Error.ArgumentNull(\"context\");\n            }\n\n            if (context.Items == null || !context.Items.Contains(HttpRequestMessageKey))\n            {\n                return null;\n            }\n\n            return context.Items[HttpRequestMessageKey] as HttpRequestMessage;\n        }\n\n        public static void SetHttpRequestMessage(this HttpContextBase context, HttpRequestMessage request)\n        {\n            if (context.Items != null)\n            {\n                context.Items.Add(HttpRequestMessageKey, request);\n            }\n        }\n\n        public static HttpRequestMessage GetOrCreateHttpRequestMessage(this HttpContextBase context)\n        {\n            if (context == null)\n            {\n                throw Error.ArgumentNull(\"context\");\n            }\n\n            HttpRequestMessage request = context.GetHttpRequestMessage();\n            if (request == null)\n            {\n                request = HttpControllerHandler.ConvertRequest(context);\n                context.SetHttpRequestMessage(request);\n            }\n\n            return request;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.WebHost/Routing/HttpRequestMessageContextWrapper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Net.Http;\n\nnamespace System.Web.Http.WebHost.Routing\n{\n    internal class HttpRequestMessageContextWrapper : HttpContextBase\n    {\n        private HttpRequestMessageWrapper _httpWrapper;\n\n        // Using Hashtable to be consistent with HttpContext.Items\n        private Hashtable _items;\n\n        public HttpRequestMessageContextWrapper(string virtualPathRoot, HttpRequestMessage httpRequest)\n        {\n            _httpWrapper = new HttpRequestMessageWrapper(virtualPathRoot, httpRequest);\n            _items = new Hashtable();\n        }\n\n        public override HttpRequestBase Request\n        {\n            get { return _httpWrapper; }\n        }\n\n        public override IDictionary Items\n        {\n            get { return _items; }\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http.WebHost/Routing/HttpRequestMessageWrapper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Net.Http;\nusing System.Web.Http.Hosting;\n\nnamespace System.Web.Http.WebHost.Routing\n{\n    internal class HttpRequestMessageWrapper : HttpRequestBase\n    {\n        private readonly string _virtualPathRoot;\n        private readonly HttpRequestMessage _httpRequest;\n\n        public HttpRequestMessageWrapper(string virtualPathRoot, HttpRequestMessage httpRequest)\n        {\n            if (virtualPathRoot == null)\n            {\n                throw Http.Error.ArgumentNull(\"virtualPathRoot\");\n            }\n\n            if (httpRequest == null)\n            {\n                throw Http.Error.ArgumentNull(\"httpRequest\");\n            }\n\n            _virtualPathRoot = virtualPathRoot;\n            _httpRequest = httpRequest;\n        }\n\n        public override string ApplicationPath\n        {\n            get { return _virtualPathRoot; }\n        }\n\n        public override string AppRelativeCurrentExecutionFilePath\n        {\n            get\n            {\n                string absolutePath = Path;\n                if (absolutePath.StartsWith(_virtualPathRoot, StringComparison.OrdinalIgnoreCase))\n                {\n                    string relativePath = _virtualPathRoot.Length == 1 ? absolutePath : absolutePath.Substring(_virtualPathRoot.Length);\n                    return \"~\" + relativePath.TrimEnd('/');\n                }\n                return null;\n            }\n        }\n\n        public override string CurrentExecutionFilePath\n        {\n            get { return FilePath; }\n        }\n\n        public override string FilePath\n        {\n            get\n            {\n                string absolutePath = Path;\n                if (absolutePath.StartsWith(_virtualPathRoot, StringComparison.OrdinalIgnoreCase))\n                {\n                    return absolutePath.TrimEnd('/');\n                }\n                return null;\n            }\n        }\n\n        public override string HttpMethod\n        {\n            get { return _httpRequest.Method.ToString(); }\n        }\n\n        public override bool IsLocal\n        {\n            get { return _httpRequest.IsLocal(); }\n        }\n\n        public override string Path\n        {\n            get\n            {\n                // All of the HttpContextBase methods are supposed to return paths that are unescaped\n                // and begin with '/'. Don't use Uri.AbsolutePath here because it's escaped.\n                return \"/\" + _httpRequest.RequestUri.GetComponents(UriComponents.Path, UriFormat.Unescaped);\n            }\n        }\n\n        public override string PathInfo\n        {\n            get { return String.Empty; }\n        }\n\n        public override NameValueCollection QueryString\n        {\n            get { return _httpRequest.RequestUri.ParseQueryString(); }\n        }\n\n        public override string RawUrl\n        {\n            get \n            {\n                // All of the HttpContextBase methods are supposed to return paths that are unescaped\n                // and begin with '/'. Don't use Uri.PathAndQuery here because it's escaped.\n                return _httpRequest.RequestUri.GetComponents(UriComponents.PathAndQuery, UriFormat.Unescaped); \n            }\n        }\n\n        public override string RequestType\n        {\n            get { return _httpRequest.Method.ToString(); }\n        }\n\n        public override Uri Url\n        {\n            get { return _httpRequest.RequestUri; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.WebHost/Routing/HttpRouteDataExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http.Routing;\nusing System.Web.Routing;\n\nnamespace System.Web.Http.WebHost.Routing\n{\n    internal static class HttpRouteDataExtensions\n    {\n        public static RouteData ToRouteData(this IHttpRouteData httpRouteData)\n        {\n            if (httpRouteData == null)\n            {\n                throw Error.ArgumentNull(\"httpRouteData\");\n            }\n\n            HostedHttpRouteData hostedHttpRouteData = httpRouteData as HostedHttpRouteData;\n            if (hostedHttpRouteData != null)\n            {\n                return hostedHttpRouteData.OriginalRouteData;\n            }\n\n            Route route = httpRouteData.Route.ToRoute();\n            RouteData result = new RouteData(route, HttpControllerRouteHandler.Instance);\n            foreach (KeyValuePair<string, object> pair in httpRouteData.Values)\n            {\n                result.Values.Add(pair.Key, pair.Value);\n            }\n            return result;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.WebHost/Routing/HttpRouteExceptionHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Runtime.ExceptionServices;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.ExceptionHandling;\n\nnamespace System.Web.Http.WebHost.Routing\n{\n    /// <summary>Represents a handler that asynchronously handles an unhandled exception from routing.</summary>\n    internal class HttpRouteExceptionHandler : HttpTaskAsyncHandler\n    {\n        private readonly ExceptionDispatchInfo _exceptionInfo;\n        private readonly IExceptionLogger _exceptionLogger;\n        private readonly IExceptionHandler _exceptionHandler;\n\n        public HttpRouteExceptionHandler(ExceptionDispatchInfo exceptionInfo)\n            : this(exceptionInfo, ExceptionServices.GetLogger(GlobalConfiguration.Configuration),\n            ExceptionServices.GetHandler(GlobalConfiguration.Configuration))\n        {\n        }\n\n        internal HttpRouteExceptionHandler(ExceptionDispatchInfo exceptionInfo,\n            IExceptionLogger exceptionLogger, IExceptionHandler exceptionHandler)\n        {\n            Contract.Assert(exceptionInfo != null);\n            Contract.Assert(exceptionLogger != null);\n            Contract.Assert(exceptionHandler != null);\n\n            _exceptionInfo = exceptionInfo;\n            _exceptionLogger = exceptionLogger;\n            _exceptionHandler = exceptionHandler;\n        }\n\n        internal ExceptionDispatchInfo ExceptionInfo\n        {\n            get { return _exceptionInfo; }\n        }\n\n        internal IExceptionLogger ExceptionLogger\n        {\n            get { return _exceptionLogger; }\n        }\n\n        internal IExceptionHandler ExceptionHandler\n        {\n            get { return _exceptionHandler; }\n        }\n\n        public override Task ProcessRequestAsync(HttpContext context)\n        {\n            return ProcessRequestAsync(new HttpContextWrapper(context));\n        }\n\n        internal async Task ProcessRequestAsync(HttpContextBase context)\n        {\n            Exception exception = _exceptionInfo.SourceException;\n            Contract.Assert(exception != null);\n\n            OperationCanceledException canceledException = exception as OperationCanceledException;\n            if (canceledException != null)\n            {\n                // If the route throws a cancelation exception, then we'll abort the request instead of\n                // reporting an 'error'. We don't expect this to happen, but aborting the request is \n                // consistent with our behavior in other hosts.\n                context.Request.Abort();\n                return;\n            }\n\n            HttpRequestMessage request = context.GetOrCreateHttpRequestMessage();\n            HttpResponseMessage response = null;\n            CancellationToken cancellationToken = context.Response.GetClientDisconnectedTokenWhenFixed();\n\n            HttpResponseException responseException = exception as HttpResponseException;\n\n            try\n            {\n                if (responseException != null)\n                {\n                    response = responseException.Response;\n                    Contract.Assert(response != null);\n\n                    // This method call is hardened and designed not to throw exceptions (since they won't be caught\n                    // and handled further by its callers).\n                    await HttpControllerHandler.CopyResponseAsync(context, request, response, _exceptionLogger,\n                        _exceptionHandler, cancellationToken);\n                }\n                else\n                {\n                    // This method call is hardened and designed not to throw exceptions (since they won't be caught and\n                    // handled further by its callers).\n                    bool handled = await HttpControllerHandler.CopyErrorResponseAsync(\n                        WebHostExceptionCatchBlocks.HttpWebRoute, context, request, null,\n                        _exceptionInfo.SourceException, _exceptionLogger, _exceptionHandler, cancellationToken);\n\n                    if (!handled)\n                    {\n                        _exceptionInfo.Throw();\n                    }\n                }\n            }\n            catch (OperationCanceledException)\n            {\n                // This block handles cancellations that might occur while we're writing an 'error' response.\n                //\n                // HttpTaskAsyncHandler treats a canceled task as an unhandled exception (logged to Application event\n                // log). Instead of returning a canceled task, abort the request and return a completed task.\n                context.Request.Abort();\n            }\n            finally\n            {\n                // The other HttpTaskAsyncHandler is HttpControllerHandler; it has similar cleanup logic.\n                request.DisposeRequestResources();\n                request.Dispose();\n\n                if (response != null)\n                {\n                    response.Dispose();\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.WebHost/Routing/HttpRouteExceptionRouteHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Runtime.ExceptionServices;\nusing System.Web.Routing;\n\nnamespace System.Web.Http.WebHost.Routing\n{\n    /// <summary>Represents a route handler that asynchronously handles an unhandled exception from routing.</summary>\n    internal class HttpRouteExceptionRouteHandler : IRouteHandler\n    {\n        private readonly ExceptionDispatchInfo _exceptionInfo;\n\n        public HttpRouteExceptionRouteHandler(ExceptionDispatchInfo exceptionInfo)\n        {\n            Contract.Assert(exceptionInfo != null);\n            _exceptionInfo = exceptionInfo;\n        }\n\n        internal ExceptionDispatchInfo ExceptionInfo\n        {\n            get { return _exceptionInfo; }\n        }\n\n        public IHttpHandler GetHttpHandler(RequestContext requestContext)\n        {\n            return new HttpRouteExceptionHandler(_exceptionInfo);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.WebHost/Routing/HttpRouteExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http.Routing;\nusing System.Web.Routing;\n\nnamespace System.Web.Http.WebHost.Routing\n{\n    internal static class HttpRouteExtensions\n    {\n        public static Route ToRoute(this IHttpRoute httpRoute)\n        {\n            if (httpRoute == null)\n            {\n                throw Error.ArgumentNull(\"httpRoute\");\n            }\n\n            HostedHttpRoute hostedHttpRoute = httpRoute as HostedHttpRoute;\n            if (hostedHttpRoute != null)\n            {\n                return hostedHttpRoute.OriginalRoute;\n            }\n\n            IRouteHandler handler =\n                (httpRoute.Handler is System.Web.Http.Routing.StopRoutingHandler) ? (new System.Web.Routing.StopRoutingHandler() as IRouteHandler) : HttpControllerRouteHandler.Instance;\n\n            return new HttpWebRoute(\n                httpRoute.RouteTemplate,\n                MakeRouteValueDictionary(httpRoute.Defaults),\n                MakeRouteValueDictionary(httpRoute.Constraints),\n                MakeRouteValueDictionary(httpRoute.DataTokens),\n                handler,\n                httpRoute);\n        }\n\n        private static RouteValueDictionary MakeRouteValueDictionary(IDictionary<string, object> dictionary)\n        {\n            return dictionary == null\n                ? new RouteValueDictionary()\n                : new RouteValueDictionary(dictionary);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.WebHost/Routing/HttpWebRoute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Net.Http;\nusing System.Runtime.ExceptionServices;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Routing;\nusing System.Web.Http.WebHost.Properties;\nusing System.Web.Routing;\n\nnamespace System.Web.Http.WebHost.Routing\n{\n    /// <summary>\n    /// Mimics the System.Web.Routing.Route class to work better for Web API scenarios. The only\n    /// difference between the base class and this class is that this one will match only when\n    /// a special \"httproute\" key is specified when generating URLs. There is no special behavior\n    /// for incoming URLs.\n    /// </summary>\n    internal class HttpWebRoute : Route\n    {\n        /// <summary>\n        /// Key used to signify that a route URL generation request should include HTTP routes (e.g. Web API).\n        /// If this key is not specified then no HTTP routes will match.\n        /// </summary>\n        internal const string HttpRouteKey = \"httproute\";\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"0#\", Justification = \"Matches the base class's parameter names.\")]\n        public HttpWebRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens, IRouteHandler routeHandler, IHttpRoute httpRoute)\n            : base(url, defaults, constraints, dataTokens, routeHandler)\n        {\n            if (httpRoute == null)\n            {\n                throw Error.ArgumentNull(\"httpRoute\");\n            }\n\n            HttpRoute = httpRoute;\n        }\n\n        /// <summary>\n        /// Gets the <see cref=\"IHttpRoute\"/> associated with this <see cref=\"HttpWebRoute\"/>.\n        /// </summary>\n        public IHttpRoute HttpRoute { get; private set; }\n\n        protected override bool ProcessConstraint(HttpContextBase httpContext, object constraint, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)\n        {\n            // The base class will validate that a constraint is either a string or IRoutingConstraint inside its\n            // ProcessConstraint method. We're doing the validation up front here because we also support \n            // IHttpRouteConstraint and we want the error message to reflect all three valid possibilities.\n            ValidateConstraint(HttpRoute.RouteTemplate, parameterName, constraint);\n\n            IHttpRouteConstraint httpRouteConstraint = constraint as IHttpRouteConstraint;\n            if (httpRouteConstraint != null)\n            {\n                HttpRequestMessage request = httpContext.GetOrCreateHttpRequestMessage();\n                return httpRouteConstraint.Match(request, HttpRoute, parameterName, values, ConvertRouteDirection(routeDirection));\n            }\n\n            return base.ProcessConstraint(httpContext, constraint, parameterName, values, routeDirection);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\",\n            Justification = \"Top-level catch block for unhandled routing exceptions.\")]\n        public override RouteData GetRouteData(HttpContextBase httpContext)\n        {\n            try\n            {\n                if (HttpRoute is HostedHttpRoute)\n                {\n                    return base.GetRouteData(httpContext);\n                }\n                else\n                {\n                    // if user passed us a custom IHttpRoute, then we should invoke their function instead of the base\n                    HttpRequestMessage request = httpContext.GetOrCreateHttpRequestMessage();\n                    IHttpRouteData data = HttpRoute.GetRouteData(httpContext.Request.ApplicationPath, request);\n                    return data == null ? null : data.ToRouteData();\n                }\n            }\n            catch (Exception exception)\n            {\n                // Processing an exception involves async work, and this method is synchronous.\n                // Instead of waiting on the async work here, it's better to return a handler that will deal with the\n                // exception asynchronously during its request processing method.\n                ExceptionDispatchInfo exceptionInfo = ExceptionDispatchInfo.Capture(exception);\n                return new RouteData(this, new HttpRouteExceptionRouteHandler(exceptionInfo));\n            }\n        }\n\n        public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)\n        {\n            // Only perform URL generation if the \"httproute\" key was specified. This allows these\n            // routes to be ignored when a regular MVC app tries to generate URLs. Without this special\n            // key an HTTP route used for Web API would normally take over almost all the routes in a\n            // typical app.\n            if (!values.ContainsKey(HttpRouteKey))\n            {\n                return null;\n            }\n            // Remove the value from the collection so that it doesn't affect the generated URL\n            RouteValueDictionary newValues = GetRouteDictionaryWithoutHttpRouteKey(values);\n\n            if (HttpRoute is HostedHttpRoute)\n            {\n                return base.GetVirtualPath(requestContext, newValues);\n            }\n            else\n            {\n                // if user passed us a custom IHttpRoute, then we should invoke their function instead of the base\n                HttpRequestMessage request = requestContext.HttpContext.GetOrCreateHttpRequestMessage();\n                IHttpVirtualPathData virtualPathData = HttpRoute.GetVirtualPath(request, values);\n\n                return virtualPathData == null ? null : new VirtualPathData(this, virtualPathData.VirtualPath);\n            }\n        }\n\n        private static RouteValueDictionary GetRouteDictionaryWithoutHttpRouteKey(IDictionary<string, object> routeValues)\n        {\n            var newRouteValues = new RouteValueDictionary();\n            foreach (var routeValue in routeValues)\n            {\n                if (!String.Equals(routeValue.Key, HttpRouteKey, StringComparison.OrdinalIgnoreCase))\n                {\n                    newRouteValues.Add(routeValue.Key, routeValue.Value);\n                }\n            }\n            return newRouteValues;\n        }\n\n        private static HttpRouteDirection ConvertRouteDirection(RouteDirection routeDirection)\n        {\n            if (routeDirection == RouteDirection.IncomingRequest)\n            {\n                return HttpRouteDirection.UriResolution;\n            }\n\n            if (routeDirection == RouteDirection.UrlGeneration)\n            {\n                return HttpRouteDirection.UriGeneration;\n            }\n\n            throw Error.InvalidEnumArgument(\"routeDirection\", (int)routeDirection, typeof(RouteDirection));\n        }\n\n        // Validates that this constraint is of a type that HttpWebRoute can process. This is not valid to\n        // call when a route inherits from HttpWebRoute - as the derived class can handle any types of \n        // constraints it wants to support.\n        internal static void ValidateConstraint(string routeTemplate, string name, object constraint)\n        {\n            if (constraint is IHttpRouteConstraint)\n            {\n                return;\n            }\n\n            // This validation is repeated in the call to base.ProcessConstraint, but if we do it here we can give a\n            // better error message. base.ProcessConstraint doesn't handle IHttpRouteConstraint, but this class does.\n            if (constraint is IRouteConstraint)\n            {\n                return;\n            }\n\n            if (constraint is string)\n            {\n                return;\n            }\n\n            throw CreateInvalidConstraintTypeException(routeTemplate, name);\n        }\n\n        private static Exception CreateInvalidConstraintTypeException(string routeTemplate, string name)\n        {\n            return Error.InvalidOperation(\n                SRResources.Route_ValidationMustBeStringOrCustomConstraint,\n                name,\n                routeTemplate,\n                typeof(IHttpRouteConstraint).FullName,\n                typeof(IRouteConstraint).FullName);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.WebHost/SeekableBufferedRequestStream.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.WebHost\n{\n    internal class SeekableBufferedRequestStream : NonOwnedStream\n    {\n        private const int ReadBufferSize = 1024;\n\n        private readonly HttpRequestBase _request;\n\n        private bool _isReadToEndComplete;\n\n        public SeekableBufferedRequestStream(HttpRequestBase request)\n        {\n            if (request == null)\n            {\n                throw new ArgumentNullException(\"request\");\n            }\n\n            _request = request;\n            InnerStream = request.GetBufferedInputStream();\n        }\n\n        public override bool CanSeek\n        {\n            get\n            {\n                return !IsDisposed;\n            }\n        }\n\n        public override long Position\n        {\n            get\n            {\n                ThrowIfDisposed();\n                return InnerStream.Position;\n            }\n            set\n            {\n                ThrowIfDisposed();\n                Seek(value, SeekOrigin.Begin);\n            }\n        }\n\n        public override int EndRead(IAsyncResult asyncResult)\n        {\n            ThrowIfDisposed();\n\n            int bytesRead = InnerStream.EndRead(asyncResult);\n            if (bytesRead == 0 && !_isReadToEndComplete)\n            {\n                SwapToSeekableStream();\n            }\n\n            return bytesRead;\n        }\n\n        public override int Read(byte[] buffer, int offset, int count)\n        {\n            ThrowIfDisposed();\n\n            int bytesRead = InnerStream.Read(buffer, offset, count);\n            if (bytesRead == 0 && !_isReadToEndComplete)\n            {\n                SwapToSeekableStream();\n            }\n\n            return bytesRead;\n        }\n\n        public async override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)\n        {\n            ThrowIfDisposed();\n\n            int bytesRead = await InnerStream.ReadAsync(buffer, offset, count, cancellationToken);\n            if (bytesRead == 0 && !_isReadToEndComplete)\n            {\n                SwapToSeekableStream();\n            }\n\n            return bytesRead;\n        }\n\n        public override int ReadByte()\n        {\n            ThrowIfDisposed();\n\n            int result = InnerStream.ReadByte();\n            if (result == -1 && !_isReadToEndComplete)\n            {\n                SwapToSeekableStream();\n            }\n\n            return result;\n        }\n\n        public override long Seek(long offset, SeekOrigin origin)\n        {\n            ThrowIfDisposed();\n\n            long currentPosition = InnerStream.Position;\n            long? newPosition = null;\n            switch (origin)\n            {\n                case SeekOrigin.Begin:\n                    newPosition = offset;\n                    break;\n                case SeekOrigin.Current:\n                    newPosition = currentPosition + offset;\n                    break;\n                case SeekOrigin.End:\n                    // We have to check Length here because we might not know the length in some scenarios. \n                    // If we don't know, then we just do the safe thing and force a read to end.\n                    if (Length >= 0)\n                    {\n                        newPosition = Length + offset;\n                    }\n                    break;\n                default:\n                    throw new InvalidEnumArgumentException(\"origin\", (int)origin, typeof(SeekOrigin));\n            }\n\n            if (newPosition == currentPosition)\n            {\n                // This is a no-op, we want to short circuit because we do significant work on a seek.\n                return currentPosition;\n            }\n\n            if (!_isReadToEndComplete)\n            {\n                // The current stream is the one returned from GetBufferedInputStream(), and it's not\n                // seekable in the web host case.\n                //\n                // We need to read the non-seekable stream to the end, which will populate the seekable stream\n                // that's provided by .InputStream. This is only done for the side-effect, and we just ignore the\n                // data, it's already being buffered for us.\n                //\n                // This is done synchronously, because we need to block the calling thread so that the result of\n                // Seek can be returned.\n                byte[] buffer = new byte[ReadBufferSize];\n                while (InnerStream.Read(buffer, 0, buffer.Length) > 0)\n                {\n                }\n\n                SwapToSeekableStream();\n            }\n\n            return InnerStream.Seek(offset, origin);\n        }\n\n        private void SwapToSeekableStream()\n        {\n            // At this point we've actually read the non-seekable stream to the end, and we're about to swap streams\n            // and toggle the value of _isReadToEndComplete. Reading the non-seekable stream to the end will populate\n            // InnerStream with the buffered data, so we can use it for all future operations.\n            Debug.Assert(!_isReadToEndComplete);\n\n            Stream seekableStream = _request.InputStream;\n            seekableStream.Position = InnerStream.Position;\n            InnerStream = seekableStream;\n\n            _isReadToEndComplete = true;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.WebHost/SuppressFormsAuthRedirectHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Specialized;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Net;\nusing System.Reflection;\nusing System.Web.Configuration;\nusing System.Web.Security;\n\nnamespace System.Web.Http.WebHost\n{\n    /// <summary>\n    /// Helper methods for Suppressing Form Authentication Redirect\n    /// </summary>\n    internal static class SuppressFormsAuthRedirectHelper\n    {\n        internal static readonly string AppSettingsSuppressFormsAuthenticationRedirectKey = \"webapi:EnableSuppressRedirect\";\n\n        /// <summary>\n        /// Returns whether the module is explicitly enabled or not\n        /// </summary>\n        internal static bool GetEnabled(NameValueCollection appSettings)\n        {\n            string disableSuppressRedirect = appSettings.Get(AppSettingsSuppressFormsAuthenticationRedirectKey);\n\n            if (!String.IsNullOrEmpty(disableSuppressRedirect))\n            {\n                bool enabled;\n\n                // anything but \"false\" will return true, which is the default behavior\n                if (Boolean.TryParse(disableSuppressRedirect, out enabled))\n                {\n                    if (!enabled)\n                    {\n                        return false;\n                    }\n                }\n            }\n\n            return true;\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Http.WebHost/System.Web.Http.WebHost.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{A0187BC2-8325-4BB2-8697-7F955CF4173E}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>System.Web.Http.WebHost</RootNamespace>\n    <AssemblyName>System.Web.Http.WebHost</AssemblyName>\n    <DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>\n    <RunCodeAnalysis>$(CodeAnalysis)</RunCodeAnalysis>\n    <CodeAnalysisRuleSet>..\\Strict.ruleset</CodeAnalysisRuleSet>\n    <DefineConstants>$(DefineConstants);ASPNETMVC</DefineConstants>\n    <NoWarn>1591</NoWarn>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.configuration\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Net.Http\" />\n    <Reference Include=\"System.Net.Http.WebRequest\" />\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"System.XML\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\CommonAssemblyInfo.cs\">\n      <Link>Properties\\CommonAssemblyInfo.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\DictionaryExtensions.cs\">\n      <Link>Common\\DictionaryExtensions.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Error.cs\">\n      <Link>Common\\Error.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\HttpMethodHelper.cs\">\n      <Link>Common\\HttpMethodHelper.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\NonOwnedStream.cs\">\n      <Link>Common\\NonOwnedStream.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\TaskHelpers.cs\">\n      <Link>Common\\TaskHelpers.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\TaskHelpersExtensions.cs\">\n      <Link>Common\\TaskHelpersExtensions.cs</Link>\n    </Compile>\n    <Compile Include=\"HttpResponseBaseExtensions.cs\" />\n    <Compile Include=\"Routing\\HttpRouteExceptionHandler.cs\" />\n    <Compile Include=\"Routing\\HttpRouteExceptionRouteHandler.cs\" />\n    <Compile Include=\"SeekableBufferedRequestStream.cs\" />\n    <Compile Include=\"WebHostExceptionCatchBlocks.cs\" />\n    <Compile Include=\"HttpBatchContextWrapper.cs\" />\n    <Compile Include=\"HttpRequestMessageExtensions.cs\" />\n    <Compile Include=\"Routing\\HttpRequestMessageWrapper.cs\" />\n    <Compile Include=\"Routing\\HttpRequestMessageContextWrapper.cs\" />\n    <Compile Include=\"WebHostBufferPolicySelector.cs\" />\n    <Compile Include=\"PreApplicationStartCode.cs\" />\n    <Compile Include=\"HttpControllerTypeCacheSerializer.cs\" />\n    <Compile Include=\"Routing\\HttpContextBaseExtensions.cs\" />\n    <Compile Include=\"WebHostExceptionHandler.cs\" />\n    <Compile Include=\"WebHostHttpControllerTypeResolver.cs\" />\n    <Compile Include=\"Routing\\HostedHttpRouteCollection.cs\" />\n    <Compile Include=\"Routing\\HostedHttpRoute.cs\" />\n    <Compile Include=\"Routing\\HostedHttpRouteData.cs\" />\n    <Compile Include=\"Routing\\HostedHttpVirtualPathData.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"GlobalConfiguration.cs\" />\n    <Compile Include=\"Routing\\HttpRouteDataExtensions.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"Routing\\HttpRouteExtensions.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"Routing\\HttpWebRoute.cs\" />\n    <Compile Include=\"SuppressFormsAuthRedirectHelper.cs\" />\n    <Compile Include=\"WebHostAssembliesResolver.cs\" />\n    <Compile Include=\"Properties\\SRResources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>SRResources.resx</DependentUpon>\n    </Compile>\n    <Compile Include=\"GlobalSuppressions.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"HttpControllerHandler.cs\" />\n    <Compile Include=\"HttpControllerRouteHandler.cs\" />\n    <Compile Include=\"RouteCollectionExtensions.cs\" />\n    <Compile Include=\"TaskWrapperAsyncResult.cs\" />\n    <Compile Include=\"WebHostHttpRequestContext.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\Common\\CommonWebApiResources.Designer.cs\">\n      <Link>Properties\\CommonWebApiResources.Designer.cs</Link>\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>CommonWebApiResources.resx</DependentUpon>\n    </Compile>\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"..\\Common\\CommonWebApiResources.resx\">\n      <Link>Properties\\CommonWebApiResources.resx</Link>\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>CommonWebApiResources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"Properties\\SRResources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>SRResources.Designer.cs</LastGenOutput>\n      <SubType>Designer</SubType>\n    </EmbeddedResource>\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\System.Net.Http.Formatting\\System.Net.Http.Formatting.csproj\">\n      <Project>{668E9021-CE84-49D9-98FB-DF125A9FCDB0}</Project>\n      <Name>System.Net.Http.Formatting</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.Http\\System.Web.Http.csproj\">\n      <Project>{DDC1CE0C-486E-4E35-BB3B-EAB61F8F9440}</Project>\n      <Name>System.Web.Http</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <CodeAnalysisDictionary Include=\"..\\CodeAnalysisDictionary.xml\">\n      <Link>CodeAnalysisDictionary.xml</Link>\n    </CodeAnalysisDictionary>\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\">\n      <SubType>Designer</SubType>\n    </None>\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n</Project>"
  },
  {
    "path": "src/System.Web.Http.WebHost/TaskWrapperAsyncResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.WebHost\n{\n    /// <summary>\n    /// Wraps a <see cref=\"Task\"/>, optionally overriding the State object (since the Task Asynchronous Pattern doesn't normally use it).\n    /// </summary>\n    /// <remarks>Class copied from System.Web.Mvc, but with modifications</remarks>\n    internal sealed class TaskWrapperAsyncResult : IAsyncResult\n    {\n        private bool? _completedSynchronously;\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"TaskWrapperAsyncResult\"/> class.\n        /// </summary>\n        /// <param name=\"task\">The <see cref=\"Task\"/> to wrap.</param>\n        /// <param name=\"asyncState\">User-defined object that qualifies or contains information about an asynchronous operation.</param>\n        public TaskWrapperAsyncResult(Task task, object asyncState)\n        {\n            if (task == null)\n            {\n                throw Error.ArgumentNull(\"task\");\n            }\n\n            Task = task;\n            AsyncState = asyncState;\n        }\n\n        /// <summary>\n        /// Gets a user-defined object that qualifies or contains information about an asynchronous operation.\n        /// </summary>\n        /// <returns>A user-defined object that qualifies or contains information about an asynchronous operation.</returns>\n        public object AsyncState { get; private set; }\n\n        /// <summary>\n        /// Gets a <see cref=\"T:System.Threading.WaitHandle\"/> that is used to wait for an asynchronous operation to complete.\n        /// </summary>\n        /// <returns>A <see cref=\"T:System.Threading.WaitHandle\"/> that is used to wait for an asynchronous operation to complete.</returns>\n        public WaitHandle AsyncWaitHandle\n        {\n            get { return ((IAsyncResult)Task).AsyncWaitHandle; }\n        }\n\n        /// <summary>\n        /// Gets a value indicating whether the asynchronous operation completed synchronously.\n        /// </summary>\n        /// <returns>true if the asynchronous operation completed synchronously; otherwise, false.</returns>\n        public bool CompletedSynchronously\n        {\n            get { return _completedSynchronously ?? ((IAsyncResult)Task).CompletedSynchronously; }\n            internal set { _completedSynchronously = value; }\n        }\n\n        /// <summary>\n        /// Gets a value indicating whether the asynchronous operation has completed.\n        /// </summary>\n        /// <returns>true if the operation is complete; otherwise, false.</returns>\n        public bool IsCompleted\n        {\n            get { return ((IAsyncResult)Task).IsCompleted; }\n        }\n\n        /// <summary>\n        /// Gets the task.\n        /// </summary>\n        public Task Task { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.WebHost/WebHostAssembliesResolver.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing System.Web.Compilation;\nusing System.Web.Http.Dispatcher;\n\nnamespace System.Web.Http.WebHost\n{\n    /// <summary>\n    /// Provides an implementation of <see cref=\"IAssembliesResolver\"/> using <see cref=\"BuildManager\"/>.\n    /// </summary>\n    internal sealed class WebHostAssembliesResolver : IAssembliesResolver\n    {\n        /// <summary>\n        /// Returns a list of assemblies that will be searched for types that implement IHttpController, such as ApiController.\n        /// </summary>\n        /// <returns>An <see cref=\"ICollection{Assembly}\" /> of assemblies.</returns>\n        ICollection<Assembly> IAssembliesResolver.GetAssemblies()\n        {\n            return BuildManager.GetReferencedAssemblies().OfType<Assembly>().ToList();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.WebHost/WebHostBufferPolicySelector.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web;\nusing System.Web.Http.Hosting;\n\nnamespace System.Web.Http.WebHost\n{\n    /// <summary>\n    /// Provides an implementation of <see cref=\"IHostBufferPolicySelector\"/> suited for use\n    /// in an ASP.NET environment which provides direct support for input and output buffering.\n    /// </summary>\n    public class WebHostBufferPolicySelector : IHostBufferPolicySelector\n    {\n        /// <summary>\n        /// Determines whether the host should buffer the entity body when processing a request with content.\n        /// </summary>\n        /// <param name=\"hostContext\">The host-specific context.  In this case, it is an instance\n        /// of <see cref=\"HttpContextBase\"/>.</param>\n        /// <returns><c>true</c> if buffering should be used; otherwise a streamed request should be used.</returns>\n        public virtual bool UseBufferedInputStream(object hostContext)\n        {\n            if (hostContext == null)\n            {\n                throw Error.ArgumentNull(\"hostContext\");\n            }\n\n            return true;\n        }\n\n        /// <summary>\n        /// Determines whether the host should buffer the <see cref=\"HttpResponseMessage\"/> entity body.\n        /// </summary>\n        /// <param name=\"response\">The <see cref=\"HttpResponseMessage\"/>response for which to determine\n        /// whether host output buffering should be used for the response entity body.</param>\n        /// <returns><c>true</c> if buffering should be used; otherwise a streamed response should be used.</returns>\n        public virtual bool UseBufferedOutputStream(HttpResponseMessage response)\n        {\n            if (response == null)\n            {\n                throw Error.ArgumentNull(\"response\");\n            }\n\n            // Any HttpContent that knows its length is presumably already buffered internally.\n            HttpContent content = response.Content;\n            if (content != null)\n            {\n                long? contentLength = content.Headers.ContentLength;\n                if (contentLength.HasValue && contentLength.Value >= 0)\n                {\n                    return false;\n                }\n\n                // Content length is null or -1 (meaning not known).  \n                // Buffer any HttpContent except StreamContent and PushStreamContent\n                return !(content is StreamContent || content is PushStreamContent);\n            }\n\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.WebHost/WebHostExceptionCatchBlocks.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.WebHost.Routing;\n\nnamespace System.Web.Http.WebHost\n{\n    /// <summary>Provides the catch blocks used within this assembly.</summary>\n    public static class WebHostExceptionCatchBlocks\n    {\n        private static readonly ExceptionContextCatchBlock _httpControllerHandlerBufferContent =\n            new ExceptionContextCatchBlock(typeof(HttpControllerHandler).Name + \".BufferContent\", isTopLevel: true,\n                callsHandler: true);\n        private static readonly ExceptionContextCatchBlock _httpControllerHandlerBufferError =\n            new ExceptionContextCatchBlock(typeof(HttpControllerHandler).Name + \".BufferError\", isTopLevel: true,\n                callsHandler: false);\n        private static readonly ExceptionContextCatchBlock _httpControllerHandlerComputeContentLength =\n            new ExceptionContextCatchBlock(typeof(HttpControllerHandler).Name + \".ComputeContentLength\",\n                isTopLevel: true, callsHandler: false);\n        private static readonly ExceptionContextCatchBlock _httpControllerHandlerStreamContent =\n            new ExceptionContextCatchBlock(typeof(HttpControllerHandler).Name + \".StreamContent\", isTopLevel: true,\n                callsHandler: false);\n        private static readonly ExceptionContextCatchBlock _httpWebRoute =\n            new ExceptionContextCatchBlock(typeof(HttpWebRoute).Name, isTopLevel: true, callsHandler: true);\n\n        /// <summary>\n        /// Gets the label for the catch block in\n        /// <see cref=\"HttpControllerHandler\"/>.WriteBufferedResponseContentAsync.\n        /// </summary>\n        /// <remarks>\n        /// This catch block handles exceptions when writing the <see cref=\"HttpContent\"/> under an\n        /// <see cref=\"IHostBufferPolicySelector\"/> that buffers.\n        /// </remarks>\n        public static ExceptionContextCatchBlock HttpControllerHandlerBufferContent\n        {\n            get { return _httpControllerHandlerBufferContent; }\n        }\n\n        /// <summary>\n        /// Gets the label for the catch block in <see cref=\"HttpControllerHandler\"/>.WriteErrorResponseContentAsync.\n        /// </summary>\n        /// <remarks>\n        /// This catch block handles exceptions when writing the <see cref=\"HttpContent\"/> of the error response itself\n        /// (after <see cref=\"HttpControllerHandlerBufferContent\"/> or <see cref=\"HttpWebRoute\"/>).\n        /// </remarks>\n        public static ExceptionContextCatchBlock HttpControllerHandlerBufferError\n        {\n            get { return _httpControllerHandlerBufferError; }\n        }\n\n        /// <summary>\n        /// Gets the label for the catch block in <see cref=\"HttpControllerHandler\"/>.ComputeContentLength.\n        /// </summary>\n        /// <remarks>\n        /// This catch block handles exceptions when calling <see cref=\"HttpContent.TryComputeLength\"/>.\n        /// </remarks>\n        public static ExceptionContextCatchBlock HttpControllerHandlerComputeContentLength\n        {\n            get { return _httpControllerHandlerComputeContentLength; }\n        }\n\n        /// <summary>\n        /// Gets the label for the catch block in\n        /// <see cref=\"HttpControllerHandler\"/>.WriteStreamedResponseContentAsync.\n        /// </summary>\n        /// <remarks>\n        /// This catch block handles exceptions when writing the <see cref=\"HttpContent\"/> under an\n        /// <see cref=\"IHostBufferPolicySelector\"/> that does not buffer.\n        /// </remarks>\n        public static ExceptionContextCatchBlock HttpControllerHandlerStreamContent\n        {\n            get { return _httpControllerHandlerStreamContent; }\n        }\n\n        /// <summary>Gets the label for the catch block in <see cref=\"HttpWebRoute\"/>.GetRouteData.</summary>\n        public static ExceptionContextCatchBlock HttpWebRoute\n        {\n            get { return _httpWebRoute; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.WebHost/WebHostExceptionHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Results;\nusing System.Web.Http.WebHost.Properties;\n\nnamespace System.Web.Http.WebHost\n{\n    /// <summary>Provides the default implementation for handling exceptions within Web API web host.</summary>\n    /// <remarks>\n    /// This class preserves the legacy behavior of catch blocks and is the the default registered IExceptionHandler\n    /// for web host.\n    /// </remarks>\n    internal class WebHostExceptionHandler : IExceptionHandler\n    {\n        private readonly IExceptionHandler _innerHandler;\n\n        public WebHostExceptionHandler(IExceptionHandler innerHandler)\n        {\n            Contract.Assert(innerHandler != null);\n            _innerHandler = innerHandler;\n        }\n\n        public IExceptionHandler InnerHandler\n        {\n            get { return _innerHandler; }\n        }\n\n        public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)\n        {\n            if (context == null)\n            {\n                throw new ArgumentNullException(\"context\");\n            }\n\n            ExceptionContext exceptionContext = context.ExceptionContext;\n            Contract.Assert(exceptionContext != null);\n\n            if (exceptionContext.CatchBlock ==\n                WebHostExceptionCatchBlocks.HttpControllerHandlerBufferContent)\n            {\n                HandleWebHostBufferedContentException(context);\n                return TaskHelpers.Completed();\n            }\n\n            return _innerHandler.HandleAsync(context, cancellationToken);\n        }\n\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\",\n            Justification = \"We already shipped this code; avoiding even minor breaking changes in error handling.\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\",\n            Justification = \"All exceptions caught here become error responses\")]\n        private static void HandleWebHostBufferedContentException(ExceptionHandlerContext context)\n        {\n            Contract.Assert(context != null);\n\n            ExceptionContext exceptionContext = context.ExceptionContext;\n            Contract.Assert(exceptionContext != null);\n\n            Exception exception = exceptionContext.Exception;\n            Contract.Assert(exception != null);\n\n            HttpRequestMessage request = exceptionContext.Request;\n\n            if (request == null)\n            {\n                throw new ArgumentException(Error.Format(SRResources.TypePropertyMustNotBeNull,\n                    typeof(ExceptionContext).Name, \"Request\"), \"context\");\n            }\n\n            HttpResponseMessage response = exceptionContext.Response;\n\n            if (response == null)\n            {\n                throw new ArgumentException(Error.Format(SRResources.TypePropertyMustNotBeNull,\n                    typeof(ExceptionContext).Name, \"Response\"), \"context\");\n            }\n\n            HttpContent responseContent = response.Content;\n\n            if (responseContent == null)\n            {\n                throw new ArgumentException(Error.Format(SRResources.TypePropertyMustNotBeNull,\n                    typeof(HttpResponseMessage).Name, \"Content\"), \"context\");\n            }\n\n            HttpResponseMessage errorResponse;\n\n            // Create a 500 response with content containing an explanatory message and\n            // stack trace, subject to content negotiation and policy for error details.\n            try\n            {\n                MediaTypeHeaderValue mediaType = responseContent.Headers.ContentType;\n                string messageDetails = (mediaType != null)\n                                            ? Error.Format(\n                                                SRResources.Serialize_Response_Failed_MediaType,\n                                                responseContent.GetType().Name,\n                                                mediaType)\n                                            : Error.Format(\n                                                SRResources.Serialize_Response_Failed,\n                                                responseContent.GetType().Name);\n\n                errorResponse = request.CreateErrorResponse(\n                                            HttpStatusCode.InternalServerError,\n                                            new InvalidOperationException(messageDetails, exception));\n\n                // CreateErrorResponse will choose 406 if it cannot find a formatter,\n                // but we want our default error response to be 500 always\n                errorResponse.StatusCode = HttpStatusCode.InternalServerError;\n            }\n            catch\n            {\n                // Failed creating an HttpResponseMessage for the error response.\n                // This can happen for missing config, missing conneg service, etc.\n                // Create an empty error response and return a non-faulted task.\n                errorResponse = request.CreateResponse(HttpStatusCode.InternalServerError);\n            }\n\n            context.Result = new ResponseMessageResult(errorResponse);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.WebHost/WebHostHttpControllerTypeResolver.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.IO;\nusing System.Linq;\nusing System.Web.Compilation;\nusing System.Web.Http.Dispatcher;\n\nnamespace System.Web.Http.WebHost\n{\n    /// <summary>\n    /// Wraps ASP build manager\n    /// </summary>\n    internal sealed class WebHostHttpControllerTypeResolver : DefaultHttpControllerTypeResolver\n    {\n        private const string TypeCacheName = \"MS-ApiControllerTypeCache.xml\";\n\n        /// <summary>\n        /// Returns a list of controllers available for the application.\n        /// </summary>\n        /// <returns>An <see cref=\"ICollection{Type}\" /> of controllers.</returns>\n        public override ICollection<Type> GetControllerTypes(IAssembliesResolver assembliesResolver)\n        {\n            HttpControllerTypeCacheSerializer serializer = new HttpControllerTypeCacheSerializer();\n\n            // First, try reading from the cache on disk\n            List<Type> matchingTypes = ReadTypesFromCache(TypeCacheName, IsControllerTypePredicate, serializer);\n            if (matchingTypes != null)\n            {\n                return matchingTypes;\n            }\n\n            // If reading from the cache failed, enumerate over every assembly looking for a matching type\n            matchingTypes = base.GetControllerTypes(assembliesResolver).ToList();\n\n            // Finally, save the cache back to disk\n            SaveTypesToCache(TypeCacheName, matchingTypes, serializer);\n\n            return matchingTypes;\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Cache failures are not fatal, and the code should continue executing normally.\")]\n        private static List<Type> ReadTypesFromCache(string cacheName, Predicate<Type> predicate, HttpControllerTypeCacheSerializer serializer)\n        {\n            try\n            {\n                Stream stream = BuildManager.ReadCachedFile(cacheName);\n                if (stream != null)\n                {\n                    using (StreamReader reader = new StreamReader(stream))\n                    {\n                        ICollection<Type> deserializedTypes = serializer.DeserializeTypes(reader);\n                        if (deserializedTypes != null && deserializedTypes.All(type => predicate(type)))\n                        {\n                            // If all read types still match the predicate, success!\n                            return deserializedTypes.ToList();\n                        }\n                    }\n                }\n            }\n            catch\n            {\n                // cache failures are not considered fatal -- keep running.\n            }\n\n            return null;\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Cache failures are not fatal, and the code should continue executing normally.\")]\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"Disposed later\")]\n        private static void SaveTypesToCache(string cacheName, IEnumerable<Type> matchingTypes, HttpControllerTypeCacheSerializer serializer)\n        {\n            try\n            {\n                Stream stream = BuildManager.CreateCachedFile(cacheName);\n                if (stream != null)\n                {\n                    using (StreamWriter writer = new StreamWriter(stream))\n                    {\n                        serializer.SerializeTypes(matchingTypes, writer);\n                    }\n                }\n            }\n            catch\n            {\n                // cache failures are not considered fatal -- keep running.\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.WebHost/WebHostHttpRequestContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Net.Http;\nusing System.Security.Cryptography.X509Certificates;\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Routing;\n\nnamespace System.Web.Http.WebHost\n{\n    internal class WebHostHttpRequestContext : HttpRequestContext\n    {\n        private readonly HttpContextBase _contextBase;\n        private readonly HttpRequestBase _requestBase;\n        private readonly HttpRequestMessage _request;\n\n        private X509Certificate2 _clientCertificate;\n        private bool _clientCertificateSet;\n\n        private HttpConfiguration _configuration;\n        private bool _configurationSet;\n\n        private bool _includeErrorDetail;\n        private bool _includeErrorDetailSet;\n\n        private bool _isLocal;\n        private bool _isLocalSet;\n\n        private UrlHelper _url;\n        private bool _urlSet;\n\n        private string _virtualPathRoot;\n        private bool _virtualPathRootSet;\n\n        public WebHostHttpRequestContext(HttpContextBase contextBase, HttpRequestBase requestBase,\n            HttpRequestMessage request)\n        {\n            Contract.Assert(contextBase != null);\n            Contract.Assert(requestBase != null);\n            Contract.Assert(request != null);\n            _contextBase = contextBase;\n            _requestBase = requestBase;\n            _request = request;\n        }\n\n        public HttpContextBase Context\n        {\n            get { return _contextBase; }\n        }\n\n        public HttpRequestBase WebRequest\n        {\n            get { return _requestBase; }\n        }\n\n        public HttpRequestMessage Request\n        {\n            get { return _request; }\n        }\n\n        // RouteData is not overridden; it is provided by a later point in the pipeline\n        //  (HttpControllerHandler.ProcessRequestAsyncCore).\n\n        public override X509Certificate2 ClientCertificate\n        {\n            get\n            {\n                if (!_clientCertificateSet)\n                {\n                    X509Certificate2 value;\n\n                    if (_requestBase.ClientCertificate != null && _requestBase.ClientCertificate.Certificate != null\n                        && _requestBase.ClientCertificate.Certificate.Length > 0)\n                    {\n                        value = new X509Certificate2(_requestBase.ClientCertificate.Certificate);\n                    }\n                    else\n                    {\n                        value = null;\n                    }\n\n                    _clientCertificate = value;\n                    _clientCertificateSet = true;\n                }\n\n                return _clientCertificate;\n            }\n            set\n            {\n                _clientCertificate = value;\n                _clientCertificateSet = true;\n            }\n        }\n\n        public override HttpConfiguration Configuration\n        {\n            get\n            {\n                if (!_configurationSet)\n                {\n                    _configuration = GlobalConfiguration.Configuration;\n                    _configurationSet = true;\n                }\n\n                return _configuration;\n            }\n            set\n            {\n                _configuration = value;\n                _configurationSet = true;\n            }\n        }\n\n        public override bool IncludeErrorDetail\n        {\n            get\n            {\n                if (!_includeErrorDetailSet)\n                {\n                    IncludeErrorDetailPolicy includeErrorDetailPolicy;\n\n                    if (_configuration != null)\n                    {\n                        includeErrorDetailPolicy = _configuration.IncludeErrorDetailPolicy;\n                    }\n                    else\n                    {\n                        includeErrorDetailPolicy = IncludeErrorDetailPolicy.Default;\n                    }\n\n                    bool value;\n\n                    switch (includeErrorDetailPolicy)\n                    {\n                        case IncludeErrorDetailPolicy.Default:\n                            value = !_contextBase.IsCustomErrorEnabled;\n                            break;\n\n                        case IncludeErrorDetailPolicy.LocalOnly:\n                            value = IsLocal;\n                            break;\n\n                        case IncludeErrorDetailPolicy.Always:\n                            value = true;\n                            break;\n\n                        case IncludeErrorDetailPolicy.Never:\n                        default:\n                            value = false;\n                            break;\n                    }\n\n                    _includeErrorDetail = value;\n                    _includeErrorDetailSet = true;\n                }\n\n                return _includeErrorDetail;\n            }\n            set\n            {\n                _includeErrorDetail = value;\n                _includeErrorDetailSet = true;\n            }\n        }\n\n        public override bool IsLocal\n        {\n            get\n            {\n                if (!_isLocalSet)\n                {\n                    _isLocal = _requestBase.IsLocal;\n                    _isLocalSet = true;\n                }\n\n                return _isLocal;\n            }\n            set\n            {\n                _isLocal = value;\n                _isLocalSet = true;\n            }\n        }\n\n        public override IPrincipal Principal\n        {\n            get\n            {\n                return _contextBase.User;\n            }\n            set\n            {\n                _contextBase.User = value;\n                Thread.CurrentPrincipal = value;\n            }\n        }\n\n        public override UrlHelper Url\n        {\n            get\n            {\n                if (!_urlSet)\n                {\n                    _url = new UrlHelper(_request);\n                    _urlSet = true;\n                }\n\n                return _url;\n            }\n            set\n            {\n                _url = value;\n                _urlSet = true;\n            }\n        }\n\n        public override string VirtualPathRoot\n        {\n            get\n            {\n                if (!_virtualPathRootSet)\n                {\n                    string value;\n\n                    if (_configuration != null)\n                    {\n                        value = _configuration.VirtualPathRoot;\n                    }\n                    else\n                    {\n                        value = null;\n                    }\n\n                    _virtualPathRoot = value;\n                    _virtualPathRootSet = true;\n                }\n\n                return _virtualPathRoot;\n            }\n            set\n            {\n                _virtualPathRoot = value;\n                _virtualPathRootSet = true;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Http.WebHost/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Microsoft.Web.Infrastructure\" version=\"1.0.0.0\" targetFramework=\"net45\" />\n</packages>"
  },
  {
    "path": "src/System.Web.Mvc/AcceptVerbsAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Reflection;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    [SuppressMessage(\"Microsoft.Design\", \"CA1019:DefineAccessorsForAttributeArguments\", Justification = \"The accessor is exposed as an ICollection<string>.\")]\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\n    public sealed class AcceptVerbsAttribute : ActionMethodSelectorAttribute\n    {\n        public AcceptVerbsAttribute(HttpVerbs verbs)\n            : this(EnumToArray(verbs))\n        {\n        }\n\n        public AcceptVerbsAttribute(params string[] verbs)\n        {\n            if (verbs == null || verbs.Length == 0)\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"verbs\");\n            }\n\n            Verbs = new ReadOnlyCollection<string>(verbs);\n        }\n\n        public ICollection<string> Verbs { get; private set; }\n\n        private static void AddEntryToList(HttpVerbs verbs, HttpVerbs match, List<string> verbList, string entryText)\n        {\n            if ((verbs & match) != 0)\n            {\n                verbList.Add(entryText);\n            }\n        }\n\n        internal static string[] EnumToArray(HttpVerbs verbs)\n        {\n            List<string> verbList = new List<string>();\n\n            AddEntryToList(verbs, HttpVerbs.Get, verbList, \"GET\");\n            AddEntryToList(verbs, HttpVerbs.Post, verbList, \"POST\");\n            AddEntryToList(verbs, HttpVerbs.Put, verbList, \"PUT\");\n            AddEntryToList(verbs, HttpVerbs.Delete, verbList, \"DELETE\");\n            AddEntryToList(verbs, HttpVerbs.Head, verbList, \"HEAD\");\n            AddEntryToList(verbs, HttpVerbs.Patch, verbList, \"PATCH\");\n            AddEntryToList(verbs, HttpVerbs.Options, verbList, \"OPTIONS\");\n\n            return verbList.ToArray();\n        }\n\n        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n\n            string incomingVerb = controllerContext.HttpContext.Request.GetHttpMethodOverride();\n\n            return Verbs.Contains(incomingVerb, StringComparer.OrdinalIgnoreCase);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ActionDescriptor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq;\nusing System.Reflection;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    public abstract class ActionDescriptor : ICustomAttributeProvider, IUniquelyIdentifiable\n    {\n        private static readonly ActionMethodDispatcherCache _staticDispatcherCache = new ActionMethodDispatcherCache();\n\n        private static readonly ActionSelector[] _emptySelectors = new ActionSelector[0];\n        private static readonly ActionNameSelector[] _emptyNameSelectors = new ActionNameSelector[0];\n        private string _uniqueId;\n        private ActionMethodDispatcherCache _instanceDispatcherCache;\n\n        protected ActionDescriptor()\n        {\n        }\n\n        public abstract string ActionName { get; }\n\n        public abstract ControllerDescriptor ControllerDescriptor { get; }\n\n        internal ActionMethodDispatcherCache DispatcherCache\n        {\n            get\n            {\n                if (_instanceDispatcherCache == null)\n                {\n                    _instanceDispatcherCache = _staticDispatcherCache;\n                }\n                return _instanceDispatcherCache;\n            }\n            set { _instanceDispatcherCache = value; }\n        }\n\n        [SuppressMessage(\"Microsoft.Security\", \"CA2119:SealMethodsThatSatisfyPrivateInterfaces\", Justification = \"This is overridden elsewhere in System.Web.Mvc\")]\n        public virtual string UniqueId\n        {\n            get \n            {\n                if (_uniqueId == null)\n                {\n                    _uniqueId = CreateUniqueId();\n                }\n                return _uniqueId; \n            }\n        }\n\n        private string CreateUniqueId()\n        {\n            return DescriptorUtil.CreateUniqueId(GetType(), ControllerDescriptor, ActionName);\n        }\n\n        public abstract object Execute(ControllerContext controllerContext, IDictionary<string, object> parameters);\n\n        internal static object ExtractParameterFromDictionary(ParameterInfo parameterInfo, IDictionary<string, object> parameters, MethodInfo methodInfo)\n        {\n            object value;\n\n            if (!parameters.TryGetValue(parameterInfo.Name, out value))\n            {\n                // the key should always be present, even if the parameter value is null\n                string message = String.Format(CultureInfo.CurrentCulture, MvcResources.ReflectedActionDescriptor_ParameterNotInDictionary,\n                                               parameterInfo.Name, parameterInfo.ParameterType, methodInfo, methodInfo.DeclaringType);\n                throw new ArgumentException(message, \"parameters\");\n            }\n\n            if (value == null && !TypeHelpers.TypeAllowsNullValue(parameterInfo.ParameterType))\n            {\n                // tried to pass a null value for a non-nullable parameter type\n                string message = String.Format(CultureInfo.CurrentCulture, MvcResources.ReflectedActionDescriptor_ParameterCannotBeNull,\n                                               parameterInfo.Name, parameterInfo.ParameterType, methodInfo, methodInfo.DeclaringType);\n                throw new ArgumentException(message, \"parameters\");\n            }\n\n            if (value != null && !parameterInfo.ParameterType.IsInstanceOfType(value))\n            {\n                // value was supplied but is not of the proper type\n                string message = String.Format(CultureInfo.CurrentCulture, MvcResources.ReflectedActionDescriptor_ParameterValueHasWrongType,\n                                               parameterInfo.Name, methodInfo, methodInfo.DeclaringType, value.GetType(), parameterInfo.ParameterType);\n                throw new ArgumentException(message, \"parameters\");\n            }\n\n            return value;\n        }\n\n        internal static object ExtractParameterOrDefaultFromDictionary(ParameterInfo parameterInfo, IDictionary<string, object> parameters)\n        {\n            Type parameterType = parameterInfo.ParameterType;\n\n            object value;\n            parameters.TryGetValue(parameterInfo.Name, out value);\n\n            // if wrong type, replace with default instance\n            if (parameterType.IsInstanceOfType(value))\n            {\n                return value;\n            }\n            else\n            {\n                object defaultValue;\n                if (ParameterInfoUtil.TryGetDefaultValue(parameterInfo, out defaultValue))\n                {\n                    return defaultValue;\n                }\n                else\n                {\n                    return TypeHelpers.GetDefaultValue(parameterType);\n                }\n            }\n        }\n\n        public virtual object[] GetCustomAttributes(bool inherit)\n        {\n            return GetCustomAttributes(typeof(object), inherit);\n        }\n\n        public virtual object[] GetCustomAttributes(Type attributeType, bool inherit)\n        {\n            if (attributeType == null)\n            {\n                throw new ArgumentNullException(\"attributeType\");\n            }\n\n            return (object[])Array.CreateInstance(attributeType, 0);\n        }\n\n        public virtual IEnumerable<FilterAttribute> GetFilterAttributes(bool useCache)\n        {\n            return GetCustomAttributes(typeof(FilterAttribute), inherit: true).Cast<FilterAttribute>();\n        }\n\n        [EditorBrowsable(EditorBrowsableState.Never)]\n        [Obsolete(\"Please call System.Web.Mvc.FilterProviders.Providers.GetFilters() now.\", true)]\n        public virtual FilterInfo GetFilters()\n        {\n            return new FilterInfo();\n        }\n\n        public abstract ParameterDescriptor[] GetParameters();\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Justification = \"This method may perform non-trivial work.\")]\n        public virtual ICollection<ActionSelector> GetSelectors()\n        {\n            return _emptySelectors;\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Justification = \"This method may perform non-trivial work.\")]\n        internal virtual ICollection<ActionNameSelector> GetNameSelectors()\n        {\n            return _emptyNameSelectors;\n        }\n\n        public virtual bool IsDefined(Type attributeType, bool inherit)\n        {\n            if (attributeType == null)\n            {\n                throw new ArgumentNullException(\"attributeType\");\n            }\n\n            return false;\n        }\n\n        internal static string VerifyActionMethodIsCallable(MethodInfo methodInfo)\n        {\n            // we can't call static methods\n            if (methodInfo.IsStatic)\n            {\n                return String.Format(CultureInfo.CurrentCulture,\n                                     MvcResources.ReflectedActionDescriptor_CannotCallStaticMethod,\n                                     methodInfo,\n                                     methodInfo.ReflectedType.FullName);\n            }\n\n            // we can't call instance methods where the 'this' parameter is a type other than ControllerBase\n            if (!typeof(ControllerBase).IsAssignableFrom(methodInfo.ReflectedType))\n            {\n                return String.Format(CultureInfo.CurrentCulture, MvcResources.ReflectedActionDescriptor_CannotCallInstanceMethodOnNonControllerType,\n                                     methodInfo, methodInfo.ReflectedType.FullName);\n            }\n\n            // we can't call methods with open generic type parameters\n            if (methodInfo.ContainsGenericParameters)\n            {\n                return String.Format(CultureInfo.CurrentCulture, MvcResources.ReflectedActionDescriptor_CannotCallOpenGenericMethods,\n                                     methodInfo, methodInfo.ReflectedType.FullName);\n            }\n\n            // we can't call methods with ref/out parameters\n            ParameterInfo[] parameterInfos = methodInfo.GetParameters();\n            foreach (ParameterInfo parameterInfo in parameterInfos)\n            {\n                if (parameterInfo.IsOut || parameterInfo.ParameterType.IsByRef)\n                {\n                    return String.Format(CultureInfo.CurrentCulture, MvcResources.ReflectedActionDescriptor_CannotCallMethodsWithOutOrRefParameters,\n                                         methodInfo, methodInfo.ReflectedType.FullName, parameterInfo);\n                }\n            }\n\n            // we can call this method\n            return null;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ActionDescriptorHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Reflection;\n\nnamespace System.Web.Mvc\n{\n    internal static class ActionDescriptorHelper\n    {\n        public static ICollection<ActionSelector> GetSelectors(MethodInfo methodInfo)\n        {\n            ActionMethodSelectorAttribute[] attrs = (ActionMethodSelectorAttribute[])methodInfo.GetCustomAttributes(typeof(ActionMethodSelectorAttribute), inherit: true);\n            ActionSelector[] selectors = Array.ConvertAll(attrs, attr => (ActionSelector)(controllerContext => attr.IsValidForRequest(controllerContext, methodInfo)));\n            return selectors;\n        }\n\n        public static ICollection<ActionNameSelector> GetNameSelectors(MethodInfo methodInfo)\n        {\n            ActionNameSelectorAttribute[] attrs = (ActionNameSelectorAttribute[])methodInfo.GetCustomAttributes(typeof(ActionNameSelectorAttribute), inherit: true);\n            ActionNameSelector[] selectors = Array.ConvertAll(attrs, attr => (ActionNameSelector)((controllerContext, actionName) => attr.IsValidName(controllerContext, actionName, methodInfo)));\n            return selectors;\n        }\n\n        public static bool IsDefined(MemberInfo methodInfo, Type attributeType, bool inherit)\n        {\n            return methodInfo.IsDefined(attributeType, inherit);\n        }\n\n        public static object[] GetCustomAttributes(MemberInfo methodInfo, bool inherit)\n        {\n            return methodInfo.GetCustomAttributes(inherit);\n        }\n\n        public static object[] GetCustomAttributes(MemberInfo methodInfo, Type attributeType, bool inherit)\n        {\n            return methodInfo.GetCustomAttributes(attributeType, inherit);\n        }\n\n        public static ParameterDescriptor[] GetParameters(ActionDescriptor actionDescriptor, MethodInfo methodInfo, ref ParameterDescriptor[] parametersCache)\n        {\n            ParameterDescriptor[] parameters = LazilyFetchParametersCollection(actionDescriptor, methodInfo, ref parametersCache);\n\n            // need to clone array so that user modifications aren't accidentally stored\n            return (ParameterDescriptor[])parameters.Clone();\n        }\n\n        private static ParameterDescriptor[] LazilyFetchParametersCollection(ActionDescriptor actionDescriptor, MethodInfo methodInfo, ref ParameterDescriptor[] parametersCache)\n        {\n            // Frequently called, so ensure the delegates remain static\n            return DescriptorUtil.LazilyFetchOrCreateDescriptors(\n                cacheLocation: ref parametersCache,\n                initializer: (CreateDescriptorState state) => state.MethodInfo.GetParameters(),\n                converter: (ParameterInfo parameterInfo, CreateDescriptorState state) => new ReflectedParameterDescriptor(parameterInfo, state.ActionDescriptor),\n                state: new CreateDescriptorState() { ActionDescriptor = actionDescriptor, MethodInfo = methodInfo });\n        }\n\n        // Used to pass generic arguments to frequently called delegates, so keep as a struct to prevent heap allocation\n        private struct CreateDescriptorState\n        {\n            internal ActionDescriptor ActionDescriptor;\n            internal MethodInfo MethodInfo;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ActionExecutedContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.Mvc\n{\n    public class ActionExecutedContext : ControllerContext\n    {\n        private ActionResult _result;\n\n        // parameterless constructor used for mocking\n        public ActionExecutedContext()\n        {\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2214:DoNotCallOverridableMethodsInConstructors\", Justification = \"The virtual property setters are only to support mocking frameworks, in which case this constructor shouldn't be called anyway.\")]\n        public ActionExecutedContext(ControllerContext controllerContext, ActionDescriptor actionDescriptor, bool canceled, Exception exception)\n            : base(controllerContext)\n        {\n            if (actionDescriptor == null)\n            {\n                throw new ArgumentNullException(\"actionDescriptor\");\n            }\n\n            ActionDescriptor = actionDescriptor;\n            Canceled = canceled;\n            Exception = exception;\n        }\n\n        public virtual ActionDescriptor ActionDescriptor { get; set; }\n\n        public virtual bool Canceled { get; set; }\n\n        public virtual Exception Exception { get; set; }\n\n        public bool ExceptionHandled { get; set; }\n\n        public ActionResult Result\n        {\n            get { return _result ?? EmptyResult.Instance; }\n            set { _result = value; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ActionExecutingContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.Mvc\n{\n    public class ActionExecutingContext : ControllerContext\n    {\n        // parameterless constructor used for mocking\n        public ActionExecutingContext()\n        {\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2214:DoNotCallOverridableMethodsInConstructors\", Justification = \"The virtual property setters are only to support mocking frameworks, in which case this constructor shouldn't be called anyway.\")]\n        public ActionExecutingContext(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary<string, object> actionParameters)\n            : base(controllerContext)\n        {\n            if (actionDescriptor == null)\n            {\n                throw new ArgumentNullException(\"actionDescriptor\");\n            }\n            if (actionParameters == null)\n            {\n                throw new ArgumentNullException(\"actionParameters\");\n            }\n\n            ActionDescriptor = actionDescriptor;\n            ActionParameters = actionParameters;\n        }\n\n        public virtual ActionDescriptor ActionDescriptor { get; set; }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"The property setter is only here to support mocking this type and should not be called at runtime.\")]\n        public virtual IDictionary<string, object> ActionParameters { get; set; }\n\n        public ActionResult Result { get; set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ActionFilterAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\n    public abstract class ActionFilterAttribute : FilterAttribute, IActionFilter, IResultFilter\n    {\n        // The OnXxx() methods are virtual rather than abstract so that a developer need override\n        // only the ones that interest him.\n\n        public virtual void OnActionExecuting(ActionExecutingContext filterContext)\n        {\n        }\n\n        public virtual void OnActionExecuted(ActionExecutedContext filterContext)\n        {\n        }\n\n        public virtual void OnResultExecuting(ResultExecutingContext filterContext)\n        {\n        }\n\n        public virtual void OnResultExecuted(ResultExecutedContext filterContext)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ActionMethodDispatcher.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq.Expressions;\nusing System.Reflection;\n\nnamespace System.Web.Mvc\n{\n    // The methods in this class don't perform error checking; that is the responsibility of the\n    // caller.\n    internal sealed class ActionMethodDispatcher\n    {\n        private ActionExecutor _executor;\n\n        public ActionMethodDispatcher(MethodInfo methodInfo)\n        {\n            _executor = GetExecutor(methodInfo);\n            MethodInfo = methodInfo;\n        }\n\n        private delegate object ActionExecutor(ControllerBase controller, object[] parameters);\n\n        private delegate void VoidActionExecutor(ControllerBase controller, object[] parameters);\n\n        public MethodInfo MethodInfo { get; private set; }\n\n        public object Execute(ControllerBase controller, object[] parameters)\n        {\n            return _executor(controller, parameters);\n        }\n\n        private static ActionExecutor GetExecutor(MethodInfo methodInfo)\n        {\n            // Parameters to executor\n            ParameterExpression controllerParameter = Expression.Parameter(typeof(ControllerBase), \"controller\");\n            ParameterExpression parametersParameter = Expression.Parameter(typeof(object[]), \"parameters\");\n\n            // Build parameter list\n            List<Expression> parameters = new List<Expression>();\n            ParameterInfo[] paramInfos = methodInfo.GetParameters();\n            for (int i = 0; i < paramInfos.Length; i++)\n            {\n                ParameterInfo paramInfo = paramInfos[i];\n                BinaryExpression valueObj = Expression.ArrayIndex(parametersParameter, Expression.Constant(i));\n                UnaryExpression valueCast = Expression.Convert(valueObj, paramInfo.ParameterType);\n\n                // valueCast is \"(Ti) parameters[i]\"\n                parameters.Add(valueCast);\n            }\n\n            // Call method\n            UnaryExpression instanceCast = (!methodInfo.IsStatic) ? Expression.Convert(controllerParameter, methodInfo.ReflectedType) : null;\n            MethodCallExpression methodCall = methodCall = Expression.Call(instanceCast, methodInfo, parameters);\n\n            // methodCall is \"((TController) controller) method((T0) parameters[0], (T1) parameters[1], ...)\"\n            // Create function\n            if (methodCall.Type == typeof(void))\n            {\n                Expression<VoidActionExecutor> lambda = Expression.Lambda<VoidActionExecutor>(methodCall, controllerParameter, parametersParameter);\n                VoidActionExecutor voidExecutor = lambda.Compile();\n                return WrapVoidAction(voidExecutor);\n            }\n            else\n            {\n                // must coerce methodCall to match ActionExecutor signature\n                UnaryExpression castMethodCall = Expression.Convert(methodCall, typeof(object));\n                Expression<ActionExecutor> lambda = Expression.Lambda<ActionExecutor>(castMethodCall, controllerParameter, parametersParameter);\n                return lambda.Compile();\n            }\n        }\n\n        private static ActionExecutor WrapVoidAction(VoidActionExecutor executor)\n        {\n            return delegate(ControllerBase controller, object[] parameters)\n            {\n                executor(controller, parameters);\n                return null;\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ActionMethodDispatcherCache.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\n\nnamespace System.Web.Mvc\n{\n    internal sealed class ActionMethodDispatcherCache : ReaderWriterCache<MethodInfo, ActionMethodDispatcher>\n    {\n        public ActionMethodDispatcherCache()\n        {\n        }\n\n        public ActionMethodDispatcher GetDispatcher(MethodInfo methodInfo)\n        {\n            // Frequently called, so ensure delegate remains static\n            return FetchOrCreateItem(methodInfo, (MethodInfo methodInfoInner) => new ActionMethodDispatcher(methodInfoInner), methodInfo);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ActionMethodSelector.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\n\nnamespace System.Web.Mvc\n{\n    internal sealed class ActionMethodSelector : ActionMethodSelectorBase\n    {\n        public ActionMethodSelector(Type controllerType)            \n        {\n            Initialize(controllerType);\n        }\n                \n        protected override bool IsValidActionMethod(MethodInfo methodInfo)\n        {\n            return !(methodInfo.IsSpecialName ||\n                     methodInfo.GetBaseDefinition().DeclaringType.IsAssignableFrom(typeof(Controller)));\n        }        \n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ActionMethodSelectorAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\n\nnamespace System.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\n    public abstract class ActionMethodSelectorAttribute : Attribute\n    {\n        /// <summary>\n        /// Determines whether the action method selection is valid for the specified controller context.\n        /// </summary>\n        /// <param name=\"controllerContext\">The controller context.</param>\n        /// <param name=\"methodInfo\">Information about the action method.</param>\n        /// <returns><see langword=\"true\"/> if the action method selection is valid for the specified controller context; otherwise, <see langword=\"false\"/>.</returns>\n        public abstract bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ActionMethodSelectorBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Diagnostics;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Linq;\nusing System.Reflection;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Web.Mvc.Async;\nusing System.Web.Mvc.Properties;\nusing System.Web.Mvc.Routing;\nusing System.Web.Routing;\n\nnamespace System.Web.Mvc\n{\n    // Common base class for Async and Sync action selectors\n    internal abstract class ActionMethodSelectorBase\n    {\n        private StandardRouteActionMethodCache _standardRouteCache;\n\n        protected void Initialize(Type controllerType)\n        {\n            ControllerType = controllerType;\n\n            var allMethods = ControllerType.GetMethods(BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public);\n            ActionMethods = Array.FindAll(allMethods, IsValidActionMethod);\n\n            // The attribute routing mapper will remove methods from this set as they are mapped.\n            // The lookup tables are initialized lazily to ensure that direct routing's changes are respected.\n            StandardRouteMethods = new HashSet<MethodInfo>(ActionMethods);\n        }\n\n        public Type ControllerType { get; private set; }\n\n        /// <summary>\n        /// All action methods.\n        /// </summary>\n        public MethodInfo[] ActionMethods { get; private set; }\n\n        /// <summary>\n        /// Methods with no direct route, reachable via standard routing only\n        /// </summary>\n        public HashSet<MethodInfo> StandardRouteMethods { get; private set; }\n\n        /// <summary>\n        /// Methods which have ActionNameSelectorAttributes - these methods have dynamic functionality\n        /// and might choose to opt-in to any request.\n        /// </summary>\n        public MethodInfo[] AliasedMethods \n        { \n            get \n            {\n                return StandardRouteCache.AliasedMethods;\n            }\n        }\n\n        /// <summary>\n        /// Methods which do not have ActionNameSelectorAttributes - these are selected statically by name.\n        /// </summary>\n        public ILookup<string, MethodInfo> NonAliasedMethods\n        {\n            get\n            {\n                return StandardRouteCache.NonAliasedMethods;\n            }\n        }\n\n        private StandardRouteActionMethodCache StandardRouteCache\n        {\n            get\n            {\n                if (_standardRouteCache == null)\n                {\n                    // This data structure is immutable, so it's safe for multiple threads to race to create it.\n                    _standardRouteCache = CreateStandardRouteCache();\n                }\n\n                return _standardRouteCache;\n            }\n        }\n\n        protected AmbiguousMatchException CreateAmbiguousActionMatchException(IEnumerable<MethodInfo> ambiguousMethods, string actionName)\n        {\n            string ambiguityList = CreateAmbiguousMatchList(ambiguousMethods);\n            string message = String.Format(CultureInfo.CurrentCulture, MvcResources.ActionMethodSelector_AmbiguousMatch,\n                                           actionName, ControllerType.Name, ambiguityList);\n            return new AmbiguousMatchException(message);\n        }\n\n        protected AmbiguousMatchException CreateAmbiguousMethodMatchException(IEnumerable<MethodInfo> ambiguousMethods, string methodName)\n        {\n            string ambiguityList = CreateAmbiguousMatchList(ambiguousMethods);\n            string message = String.Format(CultureInfo.CurrentCulture, MvcResources.AsyncActionMethodSelector_AmbiguousMethodMatch,\n                                           methodName, ControllerType.Name, ambiguityList);\n            return new AmbiguousMatchException(message);\n        }\n\n        protected static string CreateAmbiguousMatchList(IEnumerable<MethodInfo> ambiguousMethods)\n        {\n            StringBuilder exceptionMessageBuilder = new StringBuilder();\n            foreach (MethodInfo methodInfo in ambiguousMethods)\n            {\n                string controllerAction = Convert.ToString(methodInfo, CultureInfo.CurrentCulture);\n                string controllerType = methodInfo.DeclaringType.FullName;\n\n                exceptionMessageBuilder.AppendLine();\n                exceptionMessageBuilder.AppendFormat(CultureInfo.CurrentCulture, MvcResources.ActionMethodSelector_AmbiguousMatchType, controllerAction, controllerType);\n            }\n\n            return exceptionMessageBuilder.ToString();\n        }\n\n        private static bool IsMethodDecoratedWithAliasingAttribute(MethodInfo methodInfo)\n        {\n            return methodInfo.IsDefined(typeof(ActionNameSelectorAttribute), true /* inherit */);\n        }\n\n        protected abstract bool IsValidActionMethod(MethodInfo methodInfo);\n\n        // Get the method name (before applying Aliasing attributes).\n        protected virtual string GetCanonicalMethodName(MethodInfo methodInfo)\n        {\n            string methodName = methodInfo.Name;\n            return methodName;\n        }\n\n        private StandardRouteActionMethodCache CreateStandardRouteCache()\n        {\n            var cache = new StandardRouteActionMethodCache();\n            cache.AliasedMethods = StandardRouteMethods.Where(IsMethodDecoratedWithAliasingAttribute).ToArray();\n            cache.NonAliasedMethods = StandardRouteMethods\n                .Except(cache.AliasedMethods)\n                .ToLookup(GetCanonicalMethodName, StringComparer.OrdinalIgnoreCase);\n\n            return cache;\n        }\n\n        protected List<MethodInfo> FindActionMethods(ControllerContext controllerContext, string actionName)\n        {\n            List<MethodInfo> matches = new List<MethodInfo>();\n\n            var cache = StandardRouteCache;\n\n            // Performance sensitive, so avoid foreach\n            for (int i = 0; i < cache.AliasedMethods.Length; i++)\n            {\n                MethodInfo method = cache.AliasedMethods[i];\n                if (IsMatchingAliasedMethod(method, controllerContext, actionName))\n                {\n                    matches.Add(method);\n                }\n            }\n            matches.AddRange(cache.NonAliasedMethods[actionName]);\n            RunSelectionFilters(controllerContext, matches);\n            return matches;\n        }\n\n        protected static bool IsMatchingAliasedMethod(MethodInfo method, ControllerContext controllerContext, string actionName)\n        {\n            // return if aliased method is opting in to this request\n            // to opt in, all attributes defined on the method must return true\n            ReadOnlyCollection<ActionNameSelectorAttribute> attributes = ReflectedAttributeCache.GetActionNameSelectorAttributes(method);\n            // Caching count is faster for ReadOnlyCollection\n            int attributeCount = attributes.Count;\n            // Performance sensitive, so avoid foreach\n            for (int i = 0; i < attributeCount; i++)\n            {\n                if (!attributes[i].IsValidName(controllerContext, actionName, method))\n                {\n                    return false;\n                }\n            }\n            return true;\n        }\n\n        protected static bool IsValidMethodSelector(ReadOnlyCollection<ActionMethodSelectorAttribute> attributes, ControllerContext controllerContext, MethodInfo method)\n        {\n            int attributeCount = attributes.Count;\n            Contract.Assert(attributeCount > 0);\n            for (int i = 0; i < attributeCount; i++)\n            {\n                if (!attributes[i].IsValidForRequest(controllerContext, method))\n                {\n                    return false;\n                }\n            }\n            return true;\n        }\n\n        protected static void RunSelectionFilters(ControllerContext controllerContext, List<MethodInfo> methodInfos)\n        {\n            // Filter depending on the selection attribute.\n            // Methods with valid selection attributes override all others.\n            // Methods with one or more invalid selection attributes are removed.\n\n            bool hasValidSelectionAttributes = false;\n            // loop backwards for fastest removal\n            for (int i = methodInfos.Count - 1; i >= 0; i--)\n            {\n                MethodInfo methodInfo = methodInfos[i];\n                ReadOnlyCollection<ActionMethodSelectorAttribute> attrs = ReflectedAttributeCache.GetActionMethodSelectorAttributesCollection(methodInfo);\n                if (attrs.Count == 0)\n                {\n                    // case 1: this method does not have a MethodSelectionAttribute\n\n                    if (hasValidSelectionAttributes)\n                    {\n                        // if there is already method with a valid selection attribute, remove method without one\n                        methodInfos.RemoveAt(i);\n                    }\n                }\n                else if (IsValidMethodSelector(attrs, controllerContext, methodInfo))\n                {\n                    // case 2: this method has MethodSelectionAttributes that are all valid\n\n                    // if a matching action method had a selection attribute, consider it more specific than a matching action method\n                    // without a selection attribute\n                    if (!hasValidSelectionAttributes)\n                    {\n                        // when the first selection attribute is discovered, remove any items later in the list without selection attributes\n                        if (i + 1 < methodInfos.Count)\n                        {\n                            methodInfos.RemoveFrom(i + 1);\n                        }\n                        hasValidSelectionAttributes = true;\n                    }\n                }\n                else\n                {\n                    // case 3: this method has a method selection attribute but it is not valid\n\n                    // remove the method since it is opting out of this request\n                    methodInfos.RemoveAt(i);\n                }\n            }\n        }\n\n        // Get the action name for the method.         \n        public string GetActionName(MethodInfo methodInfo)\n        {\n            // Check for ActionName attribute\n            object[] nameAttributes = methodInfo.GetCustomAttributes(typeof(ActionNameAttribute), inherit: true);\n            if (nameAttributes.Length > 0)\n            {\n                ActionNameAttribute nameAttribute = nameAttributes[0] as ActionNameAttribute;\n                if (nameAttribute != null)\n                {\n                    return nameAttribute.Name;\n                }\n            }\n\n            return GetCanonicalMethodName(methodInfo);\n        }\n\n        public MethodInfo FindActionMethod(ControllerContext controllerContext, string actionName)\n        {\n            if (controllerContext == null)\n            {\n                throw Error.ArgumentNull(\"controllerContext\");\n            }\n\n            if (actionName == null)\n            {\n                throw Error.ArgumentNull(\"actionName\");\n            }\n\n            List<MethodInfo> finalMethods = FindActionMethods(controllerContext, actionName);\n\n            switch (finalMethods.Count)\n            {\n                case 0:\n                    return null;\n\n                case 1:\n                    return finalMethods[0];\n\n                default:\n                    throw CreateAmbiguousActionMatchException(finalMethods, actionName);\n            }\n        }\n\n        private class StandardRouteActionMethodCache\n        {\n            public MethodInfo[] AliasedMethods { get; set; }\n\n            public ILookup<string, MethodInfo> NonAliasedMethods { get; set; }\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Mvc/ActionNameAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\n    public sealed class ActionNameAttribute : ActionNameSelectorAttribute\n    {\n        public ActionNameAttribute(string name)\n        {\n            if (String.IsNullOrEmpty(name))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"name\");\n            }\n\n            Name = name;\n        }\n\n        public string Name { get; private set; }\n\n        public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)\n        {\n            return String.Equals(actionName, Name, StringComparison.OrdinalIgnoreCase);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ActionNameSelector.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    internal delegate bool ActionNameSelector(ControllerContext controllerContext, string actionName);\n}"
  },
  {
    "path": "src/System.Web.Mvc/ActionNameSelectorAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\n\nnamespace System.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\n    public abstract class ActionNameSelectorAttribute : Attribute\n    {\n        public abstract bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ActionResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public abstract class ActionResult\n    {\n        public abstract void ExecuteResult(ControllerContext context);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ActionSelector.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public delegate bool ActionSelector(ControllerContext controllerContext);\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/AdditionalMetaDataAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Property, AllowMultiple = true)]\n    public sealed class AdditionalMetadataAttribute : Attribute, IMetadataAware\n    {\n        private object _typeId = new object();\n\n        public AdditionalMetadataAttribute(string name, object value)\n        {\n            if (name == null)\n            {\n                throw new ArgumentNullException(\"name\");\n            }\n\n            Name = name;\n            Value = value;\n        }\n\n        public override object TypeId\n        {\n            get { return _typeId; }\n        }\n\n        public string Name { get; private set; }\n\n        public object Value { get; private set; }\n\n        public void OnMetadataCreated(ModelMetadata metadata)\n        {\n            if (metadata == null)\n            {\n                throw new ArgumentNullException(\"metadata\");\n            }\n\n            metadata.AdditionalValues[Name] = Value;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Ajax/AjaxExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Web.Mvc.Html;\nusing System.Web.Mvc.Properties;\nusing System.Web.Routing;\nusing System.Web.WebPages;\n\nnamespace System.Web.Mvc.Ajax\n{\n    public static class AjaxExtensions\n    {\n        private const string LinkOnClickFormat = \"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), {0});\";\n        private const string FormOnClickValue = \"Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));\";\n        private const string FormOnSubmitFormat = \"Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), {0});\";\n\n        public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, AjaxOptions ajaxOptions)\n        {\n            return ActionLink(ajaxHelper, linkText, actionName, (string)null /* controllerName */, ajaxOptions);\n        }\n\n        public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, object routeValues, AjaxOptions ajaxOptions)\n        {\n            return ActionLink(ajaxHelper, linkText, actionName, (string)null /* controllerName */, routeValues, ajaxOptions);\n        }\n\n        public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes)\n        {\n            return ActionLink(ajaxHelper, linkText, actionName, (string)null /* controllerName */, routeValues, ajaxOptions, htmlAttributes);\n        }\n\n        public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions)\n        {\n            return ActionLink(ajaxHelper, linkText, actionName, (string)null /* controllerName */, routeValues, ajaxOptions);\n        }\n\n        public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)\n        {\n            return ActionLink(ajaxHelper, linkText, actionName, (string)null /* controllerName */, routeValues, ajaxOptions, htmlAttributes);\n        }\n\n        public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, AjaxOptions ajaxOptions)\n        {\n            return ActionLink(ajaxHelper, linkText, actionName, controllerName, null /* values */, ajaxOptions, null /* htmlAttributes */);\n        }\n\n        public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, object routeValues, AjaxOptions ajaxOptions)\n        {\n            return ActionLink(ajaxHelper, linkText, actionName, controllerName, routeValues, ajaxOptions, null /* htmlAttributes */);\n        }\n\n        public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes)\n        {\n            RouteValueDictionary newValues = TypeHelper.ObjectToDictionary(routeValues);\n            RouteValueDictionary newAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);\n            return ActionLink(ajaxHelper, linkText, actionName, controllerName, newValues, ajaxOptions, newAttributes);\n        }\n\n        public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions)\n        {\n            return ActionLink(ajaxHelper, linkText, actionName, controllerName, routeValues, ajaxOptions, null /* htmlAttributes */);\n        }\n\n        public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)\n        {\n            if (String.IsNullOrEmpty(linkText))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"linkText\");\n            }\n\n            string targetUrl = UrlHelper.GenerateUrl(null, actionName, controllerName, routeValues, ajaxHelper.RouteCollection, ajaxHelper.ViewContext.RequestContext, true /* includeImplicitMvcValues */);\n\n            return MvcHtmlString.Create(GenerateLink(ajaxHelper, linkText, targetUrl, GetAjaxOptions(ajaxOptions), htmlAttributes));\n        }\n\n        public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, string protocol, string hostName, string fragment, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes)\n        {\n            RouteValueDictionary newValues = TypeHelper.ObjectToDictionary(routeValues);\n            RouteValueDictionary newAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);\n            return ActionLink(ajaxHelper, linkText, actionName, controllerName, protocol, hostName, fragment, newValues, ajaxOptions, newAttributes);\n        }\n\n        public static MvcHtmlString ActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, string protocol, string hostName, string fragment, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)\n        {\n            if (String.IsNullOrEmpty(linkText))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"linkText\");\n            }\n\n            string targetUrl = UrlHelper.GenerateUrl(null /* routeName */, actionName, controllerName, protocol, hostName, fragment, routeValues, ajaxHelper.RouteCollection, ajaxHelper.ViewContext.RequestContext, true /* includeImplicitMvcValues */);\n\n            return MvcHtmlString.Create(GenerateLink(ajaxHelper, linkText, targetUrl, ajaxOptions, htmlAttributes));\n        }\n\n        public static MvcForm BeginForm(this AjaxHelper ajaxHelper, AjaxOptions ajaxOptions)\n        {\n            string formAction = ajaxHelper.ViewContext.HttpContext.Request.RawUrl;\n            return FormHelper(ajaxHelper, formAction, ajaxOptions, new RouteValueDictionary());\n        }\n\n        public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, AjaxOptions ajaxOptions)\n        {\n            return BeginForm(ajaxHelper, actionName, (string)null /* controllerName */, ajaxOptions);\n        }\n\n        public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, object routeValues, AjaxOptions ajaxOptions)\n        {\n            return BeginForm(ajaxHelper, actionName, (string)null /* controllerName */, routeValues, ajaxOptions);\n        }\n\n        public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes)\n        {\n            return BeginForm(ajaxHelper, actionName, (string)null /* controllerName */, routeValues, ajaxOptions, htmlAttributes);\n        }\n\n        public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions)\n        {\n            return BeginForm(ajaxHelper, actionName, (string)null /* controllerName */, routeValues, ajaxOptions);\n        }\n\n        public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)\n        {\n            return BeginForm(ajaxHelper, actionName, (string)null /* controllerName */, routeValues, ajaxOptions, htmlAttributes);\n        }\n\n        public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, string controllerName, AjaxOptions ajaxOptions)\n        {\n            return BeginForm(ajaxHelper, actionName, controllerName, null /* values */, ajaxOptions, null /* htmlAttributes */);\n        }\n\n        public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, string controllerName, object routeValues, AjaxOptions ajaxOptions)\n        {\n            return BeginForm(ajaxHelper, actionName, controllerName, routeValues, ajaxOptions, null /* htmlAttributes */);\n        }\n\n        public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, string controllerName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes)\n        {\n            RouteValueDictionary newValues = new RouteValueDictionary(routeValues);\n            RouteValueDictionary newAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);\n            return BeginForm(ajaxHelper, actionName, controllerName, newValues, ajaxOptions, newAttributes);\n        }\n\n        public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, string controllerName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions)\n        {\n            return BeginForm(ajaxHelper, actionName, controllerName, routeValues, ajaxOptions, null /* htmlAttributes */);\n        }\n\n        public static MvcForm BeginForm(this AjaxHelper ajaxHelper, string actionName, string controllerName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)\n        {\n            // get target URL\n            string formAction = UrlHelper.GenerateUrl(null, actionName, controllerName, routeValues ?? new RouteValueDictionary(), ajaxHelper.RouteCollection, ajaxHelper.ViewContext.RequestContext, true /* includeImplicitMvcValues */);\n            return FormHelper(ajaxHelper, formAction, ajaxOptions, htmlAttributes);\n        }\n\n        public static MvcForm BeginRouteForm(this AjaxHelper ajaxHelper, string routeName, AjaxOptions ajaxOptions)\n        {\n            return BeginRouteForm(ajaxHelper, routeName, null /* routeValues */, ajaxOptions, null /* htmlAttributes */);\n        }\n\n        public static MvcForm BeginRouteForm(this AjaxHelper ajaxHelper, string routeName, object routeValues, AjaxOptions ajaxOptions)\n        {\n            return BeginRouteForm(ajaxHelper, routeName, (object)routeValues, ajaxOptions, null /* htmlAttributes */);\n        }\n\n        public static MvcForm BeginRouteForm(this AjaxHelper ajaxHelper, string routeName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes)\n        {\n            RouteValueDictionary newAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);\n            return BeginRouteForm(ajaxHelper, routeName, new RouteValueDictionary(routeValues), ajaxOptions, newAttributes);\n        }\n\n        public static MvcForm BeginRouteForm(this AjaxHelper ajaxHelper, string routeName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions)\n        {\n            return BeginRouteForm(ajaxHelper, routeName, routeValues, ajaxOptions, null /* htmlAttributes */);\n        }\n\n        public static MvcForm BeginRouteForm(this AjaxHelper ajaxHelper, string routeName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)\n        {\n            string formAction = UrlHelper.GenerateUrl(routeName, null /* actionName */, null /* controllerName */, routeValues ?? new RouteValueDictionary(), ajaxHelper.RouteCollection, ajaxHelper.ViewContext.RequestContext, false /* includeImplicitMvcValues */);\n            return FormHelper(ajaxHelper, formAction, ajaxOptions, htmlAttributes);\n        }\n\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"You don't want to dispose of this object unless you intend to write to the response\")]\n        private static MvcForm FormHelper(this AjaxHelper ajaxHelper, string formAction, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)\n        {\n            TagBuilder builder = new TagBuilder(\"form\");\n            builder.MergeAttributes(htmlAttributes);\n            builder.MergeAttribute(\"action\", formAction);\n            builder.MergeAttribute(\"method\", \"post\");\n\n            ajaxOptions = GetAjaxOptions(ajaxOptions);\n\n            if (ajaxHelper.ViewContext.UnobtrusiveJavaScriptEnabled)\n            {\n                builder.MergeAttributes(ajaxOptions.ToUnobtrusiveHtmlAttributes());\n            }\n            else\n            {\n                builder.MergeAttribute(\"onclick\", FormOnClickValue);\n                builder.MergeAttribute(\"onsubmit\", GenerateAjaxScript(ajaxOptions, FormOnSubmitFormat));\n            }\n\n            if (ajaxHelper.ViewContext.ClientValidationEnabled)\n            {\n                // forms must have an ID for client validation\n                builder.GenerateId(ajaxHelper.ViewContext.FormIdGenerator());\n            }\n\n            ajaxHelper.ViewContext.Writer.Write(builder.ToString(TagRenderMode.StartTag));\n            MvcForm theForm = new MvcForm(ajaxHelper.ViewContext);\n\n            if (ajaxHelper.ViewContext.ClientValidationEnabled)\n            {\n                ajaxHelper.ViewContext.FormContext.FormId = builder.Attributes[\"id\"];\n            }\n\n            return theForm;\n        }\n\n        public static MvcHtmlString GlobalizationScript(this AjaxHelper ajaxHelper)\n        {\n            return GlobalizationScript(ajaxHelper, CultureInfo.CurrentCulture);\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA1801:ReviewUnusedParameters\", MessageId = \"ajaxHelper\", Justification = \"This is an extension method\")]\n        public static MvcHtmlString GlobalizationScript(this AjaxHelper ajaxHelper, CultureInfo cultureInfo)\n        {\n            return GlobalizationScriptHelper(AjaxHelper.GlobalizationScriptPath, cultureInfo);\n        }\n\n        internal static MvcHtmlString GlobalizationScriptHelper(string scriptPath, CultureInfo cultureInfo)\n        {\n            if (cultureInfo == null)\n            {\n                throw new ArgumentNullException(\"cultureInfo\");\n            }\n\n            TagBuilder tagBuilder = new TagBuilder(\"script\");\n            tagBuilder.MergeAttribute(\"type\", \"text/javascript\");\n\n            string src = VirtualPathUtility.AppendTrailingSlash(scriptPath) + HttpUtility.UrlEncode(cultureInfo.Name) + \".js\";\n            tagBuilder.MergeAttribute(\"src\", src);\n\n            return tagBuilder.ToMvcHtmlString(TagRenderMode.Normal);\n        }\n\n        public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, object routeValues, AjaxOptions ajaxOptions)\n        {\n            return RouteLink(ajaxHelper, linkText, null /* routeName */, new RouteValueDictionary(routeValues), ajaxOptions,\n                             new Dictionary<string, object>());\n        }\n\n        public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes)\n        {\n            return RouteLink(ajaxHelper, linkText, null /* routeName */, new RouteValueDictionary(routeValues), ajaxOptions,\n                             HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, RouteValueDictionary routeValues, AjaxOptions ajaxOptions)\n        {\n            return RouteLink(ajaxHelper, linkText, null /* routeName */, routeValues, ajaxOptions,\n                             new Dictionary<string, object>());\n        }\n\n        public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)\n        {\n            return RouteLink(ajaxHelper, linkText, null /* routeName */, routeValues, ajaxOptions, htmlAttributes);\n        }\n\n        public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, string routeName, AjaxOptions ajaxOptions)\n        {\n            return RouteLink(ajaxHelper, linkText, routeName, new RouteValueDictionary(), ajaxOptions,\n                             new Dictionary<string, object>());\n        }\n\n        public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, string routeName, AjaxOptions ajaxOptions, object htmlAttributes)\n        {\n            return RouteLink(ajaxHelper, linkText, routeName, new RouteValueDictionary(), ajaxOptions, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, string routeName, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)\n        {\n            return RouteLink(ajaxHelper, linkText, routeName, new RouteValueDictionary(), ajaxOptions, htmlAttributes);\n        }\n\n        public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, string routeName, object routeValues, AjaxOptions ajaxOptions)\n        {\n            return RouteLink(ajaxHelper, linkText, routeName, new RouteValueDictionary(routeValues), ajaxOptions,\n                             new Dictionary<string, object>());\n        }\n\n        public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, string routeName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes)\n        {\n            return RouteLink(ajaxHelper, linkText, routeName, new RouteValueDictionary(routeValues), ajaxOptions,\n                             HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, string routeName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions)\n        {\n            return RouteLink(ajaxHelper, linkText, routeName, routeValues, ajaxOptions, new Dictionary<string, object>());\n        }\n\n        public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, string routeName, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)\n        {\n            if (String.IsNullOrEmpty(linkText))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"linkText\");\n            }\n\n            string targetUrl = UrlHelper.GenerateUrl(routeName, null /* actionName */, null /* controllerName */, routeValues ?? new RouteValueDictionary(), ajaxHelper.RouteCollection, ajaxHelper.ViewContext.RequestContext, false /* includeImplicitMvcValues */);\n\n            return MvcHtmlString.Create(GenerateLink(ajaxHelper, linkText, targetUrl, GetAjaxOptions(ajaxOptions), htmlAttributes));\n        }\n\n        public static MvcHtmlString RouteLink(this AjaxHelper ajaxHelper, string linkText, string routeName, string protocol, string hostName, string fragment, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)\n        {\n            if (String.IsNullOrEmpty(linkText))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"linkText\");\n            }\n\n            string targetUrl = UrlHelper.GenerateUrl(routeName, null /* actionName */, null /* controllerName */, protocol, hostName, fragment, routeValues ?? new RouteValueDictionary(), ajaxHelper.RouteCollection, ajaxHelper.ViewContext.RequestContext, false /* includeImplicitMvcValues */);\n\n            return MvcHtmlString.Create(GenerateLink(ajaxHelper, linkText, targetUrl, GetAjaxOptions(ajaxOptions), htmlAttributes));\n        }\n\n        private static string GenerateLink(AjaxHelper ajaxHelper, string linkText, string targetUrl, AjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)\n        {\n            TagBuilder tag = new TagBuilder(\"a\")\n            {\n                InnerHtml = HttpUtility.HtmlEncode(linkText)\n            };\n\n            tag.MergeAttributes(htmlAttributes);\n            tag.MergeAttribute(\"href\", targetUrl);\n\n            if (ajaxHelper.ViewContext.UnobtrusiveJavaScriptEnabled)\n            {\n                tag.MergeAttributes(ajaxOptions.ToUnobtrusiveHtmlAttributes());\n            }\n            else\n            {\n                tag.MergeAttribute(\"onclick\", GenerateAjaxScript(ajaxOptions, LinkOnClickFormat));\n            }\n\n            return tag.ToString(TagRenderMode.Normal);\n        }\n\n        private static string GenerateAjaxScript(AjaxOptions ajaxOptions, string scriptFormat)\n        {\n            string optionsString = ajaxOptions.ToJavascriptString();\n            return String.Format(CultureInfo.InvariantCulture, scriptFormat, optionsString);\n        }\n\n        private static AjaxOptions GetAjaxOptions(AjaxOptions ajaxOptions)\n        {\n            return (ajaxOptions != null) ? ajaxOptions : new AjaxOptions();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Ajax/AjaxOptions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Text;\nusing System.Text.RegularExpressions;\n\nnamespace System.Web.Mvc.Ajax\n{\n    public class AjaxOptions\n    {\n        private static readonly Regex _idRegex = new Regex(@\"[.:[\\]]\");\n        private string _confirm;\n        private string _httpMethod;\n        private InsertionMode _insertionMode = InsertionMode.Replace;\n        private string _loadingElementId;\n        private string _onBegin;\n        private string _onComplete;\n        private string _onFailure;\n        private string _onSuccess;\n        private string _updateTargetId;\n        private string _url;\n\n        public string Confirm\n        {\n            get { return _confirm ?? String.Empty; }\n            set { _confirm = value; }\n        }\n\n        public string HttpMethod\n        {\n            get { return _httpMethod ?? String.Empty; }\n            set { _httpMethod = value; }\n        }\n\n        public InsertionMode InsertionMode\n        {\n            get { return _insertionMode; }\n            set\n            {\n                switch (value)\n                {\n                    case InsertionMode.Replace:\n                    case InsertionMode.InsertAfter:\n                    case InsertionMode.InsertBefore:\n                    case InsertionMode.ReplaceWith:\n                        _insertionMode = value;\n                        return;\n\n                    default:\n                        throw new ArgumentOutOfRangeException(\"value\");\n                }\n            }\n        }\n\n        internal string InsertionModeString\n        {\n            get\n            {\n                switch (InsertionMode)\n                {\n                    case InsertionMode.Replace:\n                        return \"Sys.Mvc.InsertionMode.replace\";\n                    case InsertionMode.InsertBefore:\n                        return \"Sys.Mvc.InsertionMode.insertBefore\";\n                    case InsertionMode.InsertAfter:\n                        return \"Sys.Mvc.InsertionMode.insertAfter\";\n                    default:\n                        return ((int)InsertionMode).ToString(CultureInfo.InvariantCulture);\n                }\n            }\n        }\n\n        internal string InsertionModeUnobtrusive\n        {\n            get\n            {\n                switch (InsertionMode)\n                {\n                    case InsertionMode.Replace:\n                        return \"replace\";\n                    case InsertionMode.InsertBefore:\n                        return \"before\";\n                    case InsertionMode.InsertAfter:\n                        return \"after\";\n                    case InsertionMode.ReplaceWith:\n                        return \"replace-with\";\n                    default:\n                        return ((int)InsertionMode).ToString(CultureInfo.InvariantCulture);\n                }\n            }\n        }\n\n        public int LoadingElementDuration { get; set; }\n\n        public string LoadingElementId\n        {\n            get { return _loadingElementId ?? String.Empty; }\n            set { _loadingElementId = value; }\n        }\n\n        public string OnBegin\n        {\n            get { return _onBegin ?? String.Empty; }\n            set { _onBegin = value; }\n        }\n\n        public string OnComplete\n        {\n            get { return _onComplete ?? String.Empty; }\n            set { _onComplete = value; }\n        }\n\n        public string OnFailure\n        {\n            get { return _onFailure ?? String.Empty; }\n            set { _onFailure = value; }\n        }\n\n        public string OnSuccess\n        {\n            get { return _onSuccess ?? String.Empty; }\n            set { _onSuccess = value; }\n        }\n\n        public string UpdateTargetId\n        {\n            get { return _updateTargetId ?? String.Empty; }\n            set { _updateTargetId = value; }\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1056:UriPropertiesShouldNotBeStrings\", Justification = \"This property is used by the optionsBuilder which always accepts a string.\")]\n        public string Url\n        {\n            get { return _url ?? String.Empty; }\n            set { _url = value; }\n        }\n\n        public bool AllowCache { get; set; }\n\n        internal string ToJavascriptString()\n        {\n            // creates a string of the form { key1: value1, key2 : value2, ... }\n            // This method is used for generating obtrusive JavaScript (using MicrosoftMvcAjax.js) which is no longer \n            // actively maintained. Consequently, we'll ignore the AllowCache option if it's set for this code path.\n            StringBuilder optionsBuilder = new StringBuilder(\"{\");\n            optionsBuilder.AppendFormat(CultureInfo.InvariantCulture, \" insertionMode: {0},\", InsertionModeString);\n            optionsBuilder.Append(PropertyStringIfSpecified(\"confirm\", Confirm));\n            optionsBuilder.Append(PropertyStringIfSpecified(\"httpMethod\", HttpMethod));\n            optionsBuilder.Append(PropertyStringIfSpecified(\"loadingElementId\", LoadingElementId));\n            optionsBuilder.Append(PropertyStringIfSpecified(\"updateTargetId\", UpdateTargetId));\n            optionsBuilder.Append(PropertyStringIfSpecified(\"url\", Url));\n            optionsBuilder.Append(EventStringIfSpecified(\"onBegin\", OnBegin));\n            optionsBuilder.Append(EventStringIfSpecified(\"onComplete\", OnComplete));\n            optionsBuilder.Append(EventStringIfSpecified(\"onFailure\", OnFailure));\n            optionsBuilder.Append(EventStringIfSpecified(\"onSuccess\", OnSuccess));\n            optionsBuilder.Length--;\n            optionsBuilder.Append(\" }\");\n            return optionsBuilder.ToString();\n        }\n\n        public IDictionary<string, object> ToUnobtrusiveHtmlAttributes()\n        {\n            var result = new Dictionary<string, object>\n            {\n                { \"data-ajax\", \"true\" },\n            };\n\n            AddToDictionaryIfSpecified(result, \"data-ajax-url\", Url);\n            AddToDictionaryIfSpecified(result, \"data-ajax-method\", HttpMethod);\n            AddToDictionaryIfSpecified(result, \"data-ajax-confirm\", Confirm);\n\n            AddToDictionaryIfSpecified(result, \"data-ajax-begin\", OnBegin);\n            AddToDictionaryIfSpecified(result, \"data-ajax-complete\", OnComplete);\n            AddToDictionaryIfSpecified(result, \"data-ajax-failure\", OnFailure);\n            AddToDictionaryIfSpecified(result, \"data-ajax-success\", OnSuccess);\n\n            if (AllowCache)\n            {\n                // On the client, the absence of the data-ajax-cache attribute is equivalent to setting it to false.\n                // Consequently we'll only set it if the user wants to opt into caching. \n                AddToDictionaryIfSpecified(result, \"data-ajax-cache\", \"true\");\n            }\n\n            if (!String.IsNullOrWhiteSpace(LoadingElementId))\n            {\n                result.Add(\"data-ajax-loading\", EscapeIdSelector(LoadingElementId));\n\n                if (LoadingElementDuration > 0)\n                {\n                    result.Add(\"data-ajax-loading-duration\", LoadingElementDuration);\n                }\n            }\n\n            if (!String.IsNullOrWhiteSpace(UpdateTargetId))\n            {\n                result.Add(\"data-ajax-update\", EscapeIdSelector(UpdateTargetId));\n                result.Add(\"data-ajax-mode\", InsertionModeUnobtrusive);\n            }\n\n            return result;\n        }\n\n        // Helpers\n\n        private static void AddToDictionaryIfSpecified(IDictionary<string, object> dictionary, string name, string value)\n        {\n            if (!String.IsNullOrWhiteSpace(value))\n            {\n                dictionary.Add(name, value);\n            }\n        }\n\n        private static string EventStringIfSpecified(string propertyName, string handler)\n        {\n            if (!String.IsNullOrEmpty(handler))\n            {\n                return String.Format(CultureInfo.InvariantCulture, \" {0}: Function.createDelegate(this, {1}),\", propertyName, handler.ToString());\n            }\n            return String.Empty;\n        }\n\n        private static string PropertyStringIfSpecified(string propertyName, string propertyValue)\n        {\n            if (!String.IsNullOrEmpty(propertyValue))\n            {\n                string escapedPropertyValue = propertyValue.Replace(\"'\", @\"\\'\");\n                return String.Format(CultureInfo.InvariantCulture, \" {0}: '{1}',\", propertyName, escapedPropertyValue);\n            }\n            return String.Empty;\n        }\n\n        private static string EscapeIdSelector(string selector)\n        {\n            // The string returned by this function is used as a value for jQuery's selector. The characters dot, colon and \n            // square brackets are valid id characters but need to be properly escaped since they have special meaning. For\n            // e.g., for the id a.b, $('#a.b') would cause \".b\" to treated as a class selector. The correct way to specify\n            // this selector would be to escape the dot to get $('#a\\.b').\n            // See http://learn.jquery.com/using-jquery-core/faq/how-do-i-select-an-element-by-an-id-that-has-characters-used-in-css-notation/\n            return '#' + _idRegex.Replace(selector, @\"\\$&\");\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Ajax/InsertionMode.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc.Ajax\n{\n    public enum InsertionMode\n    {\n        /// <summary>\n        /// Replace the contents of the element.\n        /// </summary>\n        Replace = 0,\n\n        /// <summary>\n        /// Insert before the element.\n        /// </summary>\n        InsertBefore = 1,\n\n        /// <summary>\n        /// Insert after the element.\n        /// </summary>\n        InsertAfter = 2,\n\n        /// <summary>\n        /// Replace the entire element.\n        /// </summary>\n        ReplaceWith = 3\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/AjaxHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Routing;\n\nnamespace System.Web.Mvc\n{\n    public class AjaxHelper\n    {\n        private static string _globalizationScriptPath;\n\n        private DynamicViewDataDictionary _dynamicViewDataDictionary;\n\n        public AjaxHelper(ViewContext viewContext, IViewDataContainer viewDataContainer)\n            : this(viewContext, viewDataContainer, RouteTable.Routes)\n        {\n        }\n\n        public AjaxHelper(ViewContext viewContext, IViewDataContainer viewDataContainer, RouteCollection routeCollection)\n        {\n            if (viewContext == null)\n            {\n                throw new ArgumentNullException(\"viewContext\");\n            }\n            if (viewDataContainer == null)\n            {\n                throw new ArgumentNullException(\"viewDataContainer\");\n            }\n            if (routeCollection == null)\n            {\n                throw new ArgumentNullException(\"routeCollection\");\n            }\n            ViewContext = viewContext;\n            ViewDataContainer = viewDataContainer;\n            RouteCollection = routeCollection;\n        }\n\n        public static string GlobalizationScriptPath\n        {\n            get\n            {\n                if (String.IsNullOrEmpty(_globalizationScriptPath))\n                {\n                    _globalizationScriptPath = \"~/Scripts/Globalization\";\n                }\n                return _globalizationScriptPath;\n            }\n            set { _globalizationScriptPath = value; }\n        }\n\n        public RouteCollection RouteCollection { get; private set; }\n\n        public dynamic ViewBag\n        {\n            get\n            {\n                if (_dynamicViewDataDictionary == null)\n                {\n                    _dynamicViewDataDictionary = new DynamicViewDataDictionary(() => ViewData);\n                }\n                return _dynamicViewDataDictionary;\n            }\n        }\n\n        public ViewContext ViewContext { get; private set; }\n\n        public ViewDataDictionary ViewData\n        {\n            get { return ViewDataContainer.ViewData; }\n        }\n\n        public IViewDataContainer ViewDataContainer { get; internal set; }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"Instance method for consistency with other helpers.\")]\n        public string JavaScriptStringEncode(string message)\n        {\n            if (String.IsNullOrEmpty(message))\n            {\n                return message;\n            }\n\n            return HttpUtility.JavaScriptStringEncode(message);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/AjaxHelperOfTModel.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Routing;\n\nnamespace System.Web.Mvc\n{\n    public class AjaxHelper<TModel> : AjaxHelper\n    {\n        private DynamicViewDataDictionary _dynamicViewDataDictionary;\n        private ViewDataDictionary<TModel> _viewData;\n\n        public AjaxHelper(ViewContext viewContext, IViewDataContainer viewDataContainer)\n            : this(viewContext, viewDataContainer, RouteTable.Routes)\n        {\n        }\n\n        public AjaxHelper(ViewContext viewContext, IViewDataContainer viewDataContainer, RouteCollection routeCollection)\n            : base(viewContext, viewDataContainer, routeCollection)\n        {\n            _viewData = new ViewDataDictionary<TModel>(viewDataContainer.ViewData);\n        }\n\n        public new dynamic ViewBag\n        {\n            get\n            {\n                if (_dynamicViewDataDictionary == null)\n                {\n                    _dynamicViewDataDictionary = new DynamicViewDataDictionary(() => ViewData);\n                }\n\n                return _dynamicViewDataDictionary;\n            }\n        }\n\n        public new ViewDataDictionary<TModel> ViewData\n        {\n            get { return _viewData; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/AjaxRequestExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public static class AjaxRequestExtensions\n    {\n        public static bool IsAjaxRequest(this HttpRequestBase request)\n        {\n            if (request == null)\n            {\n                throw new ArgumentNullException(\"request\");\n            }\n\n            return (request[\"X-Requested-With\"] == \"XMLHttpRequest\") || ((request.Headers != null) && (request.Headers[\"X-Requested-With\"] == \"XMLHttpRequest\"));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/AllowAnonymousAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    /// <summary>\n    /// Actions and controllers with the AllowAnonymous attribute are skipped by the Authorize attribute\n    /// on authorization. See AccountController.cs in the project template for an example.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\n    public sealed class AllowAnonymousAttribute : Attribute\n    {\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/AllowHtmlAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    // This attribute can be applied to a model property to specify that the particular property to\n    // which it is applied should not go through request validation.\n\n    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]\n    public sealed class AllowHtmlAttribute : Attribute, IMetadataAware\n    {\n        public void OnMetadataCreated(ModelMetadata metadata)\n        {\n            if (metadata == null)\n            {\n                throw new ArgumentNullException(\"metadata\");\n            }\n\n            metadata.RequestValidationEnabled = false;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/AreaHelpers.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc.Routing;\nusing System.Web.Routing;\n\nnamespace System.Web.Mvc\n{\n    internal static class AreaHelpers\n    {\n        public static string GetAreaName(RouteBase route)\n        {\n            IRouteWithArea routeWithArea = route as IRouteWithArea;\n            if (routeWithArea != null)\n            {\n                return routeWithArea.Area;\n            }\n\n            Route castRoute = route as Route;\n            if (castRoute != null && castRoute.DataTokens != null)\n            {\n                return castRoute.DataTokens[RouteDataTokenKeys.Area] as string;\n            }\n\n            return null;\n        }\n\n        public static string GetAreaName(RouteData routeData)\n        {\n            object area;\n            if (routeData.DataTokens.TryGetValue(RouteDataTokenKeys.Area, out area))\n            {\n                return area as string;\n            }\n\n            return GetAreaName(routeData.Route);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/AreaReference.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    /// <summary>\n    /// Controls interpretation of a controller name when constructing a <see cref=\"RemoteAttribute\"/>.\n    /// </summary>\n    public enum AreaReference\n    {\n        /// <summary>\n        /// Find the controller in the current area.\n        /// </summary>\n        UseCurrent = 0,\n\n        /// <summary>\n        /// Find the controller in the root area.\n        /// </summary>\n        UseRoot = 1,\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/AreaRegistration.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Routing;\n\nnamespace System.Web.Mvc\n{\n    public abstract class AreaRegistration\n    {\n        private const string TypeCacheName = \"MVC-AreaRegistrationTypeCache.xml\";\n\n        public abstract string AreaName { get; }\n\n        internal void CreateContextAndRegister(RouteCollection routes, object state)\n        {\n            AreaRegistrationContext context = new AreaRegistrationContext(AreaName, routes, state);\n\n            string thisNamespace = GetType().Namespace;\n            if (thisNamespace != null)\n            {\n                context.Namespaces.Add(thisNamespace + \".*\");\n            }\n\n            RegisterArea(context);\n        }\n\n        private static bool IsAreaRegistrationType(Type type)\n        {\n            return\n                typeof(AreaRegistration).IsAssignableFrom(type) &&\n                type.GetConstructor(Type.EmptyTypes) != null;\n        }\n\n        public static void RegisterAllAreas()\n        {\n            RegisterAllAreas(null);\n        }\n\n        public static void RegisterAllAreas(object state)\n        {\n            RegisterAllAreas(RouteTable.Routes, new BuildManagerWrapper(), state);\n        }\n\n        internal static void RegisterAllAreas(RouteCollection routes, IBuildManager buildManager, object state)\n        {\n            List<Type> areaRegistrationTypes = TypeCacheUtil.GetFilteredTypesFromAssemblies(TypeCacheName, IsAreaRegistrationType, buildManager);\n            foreach (Type areaRegistrationType in areaRegistrationTypes)\n            {\n                AreaRegistration registration = (AreaRegistration)Activator.CreateInstance(areaRegistrationType);\n                registration.CreateContextAndRegister(routes, state);\n            }\n        }\n\n        public abstract void RegisterArea(AreaRegistrationContext context);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/AreaRegistrationContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Web.Mvc.Routing;\nusing System.Web.Routing;\n\nnamespace System.Web.Mvc\n{\n    public class AreaRegistrationContext\n    {\n        private readonly HashSet<string> _namespaces = new HashSet<string>(StringComparer.OrdinalIgnoreCase);\n\n        public AreaRegistrationContext(string areaName, RouteCollection routes)\n            : this(areaName, routes, null)\n        {\n        }\n\n        public AreaRegistrationContext(string areaName, RouteCollection routes, object state)\n        {\n            if (String.IsNullOrEmpty(areaName))\n            {\n                throw Error.ParameterCannotBeNullOrEmpty(\"areaName\");\n            }\n            if (routes == null)\n            {\n                throw new ArgumentNullException(\"routes\");\n            }\n\n            AreaName = areaName;\n            Routes = routes;\n            State = state;\n        }\n\n        public string AreaName { get; private set; }\n\n        public ICollection<string> Namespaces\n        {\n            get { return _namespaces; }\n        }\n\n        public RouteCollection Routes { get; private set; }\n\n        public object State { get; private set; }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"This is not a regular URL as it may contain special routing characters.\")]\n        public Route MapRoute(string name, string url)\n        {\n            return MapRoute(name, url, (object)null /* defaults */);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"This is not a regular URL as it may contain special routing characters.\")]\n        public Route MapRoute(string name, string url, object defaults)\n        {\n            return MapRoute(name, url, defaults, (object)null /* constraints */);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"This is not a regular URL as it may contain special routing characters.\")]\n        public Route MapRoute(string name, string url, object defaults, object constraints)\n        {\n            return MapRoute(name, url, defaults, constraints, null /* namespaces */);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"This is not a regular URL as it may contain special routing characters.\")]\n        public Route MapRoute(string name, string url, string[] namespaces)\n        {\n            return MapRoute(name, url, (object)null /* defaults */, namespaces);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"This is not a regular URL as it may contain special routing characters.\")]\n        public Route MapRoute(string name, string url, object defaults, string[] namespaces)\n        {\n            return MapRoute(name, url, defaults, null /* constraints */, namespaces);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"This is not a regular URL as it may contain special routing characters.\")]\n        public Route MapRoute(string name, string url, object defaults, object constraints, string[] namespaces)\n        {\n            if (namespaces == null && Namespaces != null)\n            {\n                namespaces = Namespaces.ToArray();\n            }\n\n            Route route = Routes.MapRoute(name, url, defaults, constraints, namespaces);\n            route.DataTokens[RouteDataTokenKeys.Area] = AreaName;\n\n            // disabling the namespace lookup fallback mechanism keeps this areas from accidentally picking up\n            // controllers belonging to other areas\n            bool useNamespaceFallback = (namespaces == null || namespaces.Length == 0);\n            route.DataTokens[RouteDataTokenKeys.UseNamespaceFallback] = useNamespaceFallback;\n\n            return route;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/AssociatedMetadataProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Linq;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    // This class provides a good implementation of ModelMetadataProvider for people who will be\n    // using traditional classes with properties. It uses the buddy class support from\n    // DataAnnotations, and consolidates the three operations down to a single override\n    // for reading the attribute values and creating the metadata class.\n    public abstract class AssociatedMetadataProvider : ModelMetadataProvider\n    {\n        private static void ApplyMetadataAwareAttributes(IEnumerable<Attribute> attributes, ModelMetadata result)\n        {\n            foreach (IMetadataAware awareAttribute in attributes.OfType<IMetadataAware>())\n            {\n                awareAttribute.OnMetadataCreated(result);\n            }\n        }\n\n        protected abstract ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName);\n\n        protected virtual IEnumerable<Attribute> FilterAttributes(Type containerType, PropertyDescriptor propertyDescriptor, IEnumerable<Attribute> attributes)\n        {\n            if (typeof(ViewPage).IsAssignableFrom(containerType) || typeof(ViewUserControl).IsAssignableFrom(containerType))\n            {\n                return attributes.Where(a => !(a is ReadOnlyAttribute));\n            }\n\n            return attributes;\n        }\n\n        public override IEnumerable<ModelMetadata> GetMetadataForProperties(object container, Type containerType)\n        {\n            if (containerType == null)\n            {\n                throw new ArgumentNullException(\"containerType\");\n            }\n\n            PropertyDescriptorCollection properties = GetTypeDescriptor(containerType).GetProperties();\n\n            // The return value is sorted from the ModelMetadata type, so returning as an array is best for performance\n            ModelMetadata[] metadata = new ModelMetadata[properties.Count];\n            for (int i = 0; i < properties.Count; i++)\n            {\n                PropertyDescriptor property = properties[i];\n                Func<object> modelAccessor = container == null ? null : GetPropertyValueAccessor(container, property);\n                ModelMetadata propertyMetadata = GetMetadataForProperty(modelAccessor, containerType, property);\n                if (propertyMetadata != null)\n                {\n                    propertyMetadata.Container = container;\n                }\n                metadata[i] = propertyMetadata;\n            }\n            return metadata;\n        }\n\n        public override ModelMetadata GetMetadataForProperty(Func<object> modelAccessor, Type containerType, string propertyName)\n        {\n            if (containerType == null)\n            {\n                throw new ArgumentNullException(\"containerType\");\n            }\n            if (String.IsNullOrEmpty(propertyName))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"propertyName\");\n            }\n\n            ICustomTypeDescriptor typeDescriptor = GetTypeDescriptor(containerType);\n            PropertyDescriptor property = typeDescriptor.GetProperties().Find(propertyName, true);\n            if (property == null)\n            {\n                throw new ArgumentException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.Common_PropertyNotFound,\n                        containerType.FullName, propertyName));\n            }\n\n            return GetMetadataForProperty(modelAccessor, containerType, property);\n        }\n\n        protected virtual ModelMetadata GetMetadataForProperty(Func<object> modelAccessor, Type containerType, PropertyDescriptor propertyDescriptor)\n        {\n            IEnumerable<Attribute> attributes = FilterAttributes(containerType, propertyDescriptor, new AttributeList(propertyDescriptor.Attributes));\n            ModelMetadata result = CreateMetadata(attributes, containerType, modelAccessor, propertyDescriptor.PropertyType, propertyDescriptor.Name);\n            ApplyMetadataAwareAttributes(attributes, result);\n            return result;\n        }\n\n        public override ModelMetadata GetMetadataForType(Func<object> modelAccessor, Type modelType)\n        {\n            if (modelType == null)\n            {\n                throw new ArgumentNullException(\"modelType\");\n            }\n\n            AttributeList attributes = new AttributeList(GetTypeDescriptor(modelType).GetAttributes());\n            ModelMetadata result = CreateMetadata(attributes, null /* containerType */, modelAccessor, modelType, null /* propertyName */);\n            ApplyMetadataAwareAttributes(attributes, result);\n            return result;\n        }\n\n        private static Func<object> GetPropertyValueAccessor(object container, PropertyDescriptor property)\n        {\n            return () => property.GetValue(container);\n        }\n\n        protected virtual ICustomTypeDescriptor GetTypeDescriptor(Type type)\n        {\n            return TypeDescriptorHelper.Get(type);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/AssociatedValidatorProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Linq;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    public abstract class AssociatedValidatorProvider : ModelValidatorProvider\n    {\n        protected virtual ICustomTypeDescriptor GetTypeDescriptor(Type type)\n        {\n            return TypeDescriptorHelper.Get(type);\n        }\n\n        public sealed override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context)\n        {\n            if (metadata == null)\n            {\n                throw new ArgumentNullException(\"metadata\");\n            }\n            if (context == null)\n            {\n                throw new ArgumentNullException(\"context\");\n            }\n\n            if (metadata.ContainerType != null && !String.IsNullOrEmpty(metadata.PropertyName))\n            {\n                return GetValidatorsForProperty(metadata, context);\n            }\n\n            return GetValidatorsForType(metadata, context);\n        }\n\n        protected abstract IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes);\n\n        private IEnumerable<ModelValidator> GetValidatorsForProperty(ModelMetadata metadata, ControllerContext context)\n        {\n            ICustomTypeDescriptor typeDescriptor = GetTypeDescriptor(metadata.ContainerType);\n            PropertyDescriptor property = typeDescriptor.GetProperties().Find(metadata.PropertyName, true);\n            if (property == null)\n            {\n                throw new ArgumentException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.Common_PropertyNotFound,\n                        metadata.ContainerType.FullName, metadata.PropertyName),\n                    \"metadata\");\n            }\n            return GetValidators(metadata, context, new AttributeList(property.Attributes));\n        }\n\n        private IEnumerable<ModelValidator> GetValidatorsForType(ModelMetadata metadata, ControllerContext context)\n        {\n            return GetValidators(metadata, context, new AttributeList(GetTypeDescriptor(metadata.ModelType).GetAttributes()));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Async/ActionDescriptorCreator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc.Async\n{\n    internal delegate ActionDescriptor ActionDescriptorCreator(string actionName, ControllerDescriptor controllerDescriptor);\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Async/AsyncActionDescriptor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc.Async\n{\n    public abstract class AsyncActionDescriptor : ActionDescriptor\n    {\n        public abstract IAsyncResult BeginExecute(ControllerContext controllerContext, IDictionary<string, object> parameters, AsyncCallback callback, object state);\n\n        public abstract object EndExecute(IAsyncResult asyncResult);\n\n        public override object Execute(ControllerContext controllerContext, IDictionary<string, object> parameters)\n        {\n            string errorMessage = String.Format(CultureInfo.CurrentCulture, MvcResources.AsyncActionDescriptor_CannotExecuteSynchronously,\n                                                ActionName);\n\n            throw new InvalidOperationException(errorMessage);\n        }\n\n        internal static AsyncManager GetAsyncManager(ControllerBase controller)\n        {\n            IAsyncManagerContainer helperContainer = controller as IAsyncManagerContainer;\n            if (helperContainer == null)\n            {\n                throw Error.AsyncCommon_ControllerMustImplementIAsyncManagerContainer(controller.GetType());\n            }\n\n            return helperContainer.AsyncManager;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Async/AsyncActionMethodSelector.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Mvc.Async\n{\n    internal sealed class AsyncActionMethodSelector : ActionMethodSelectorBase\n    {\n        // This flag controls async action binding for backwards compat since Controller now supports async. \n        // Set to true for classes that derive from AsyncController. In this case, FooAsync/FooCompleted is \n        // bound as a single async action pair \"Foo\". If false, they're bound as 2 separate sync actions. \n        // Practically, if this is false, then IsAsyncSuffixedMethod and IsCompeltedSuffixedMethod return false.\n        private readonly bool _allowLegacyAsyncActions;\n\n        public AsyncActionMethodSelector(Type controllerType, bool allowLegacyAsyncActions = true)\n        {\n            _allowLegacyAsyncActions = allowLegacyAsyncActions;\n            Initialize(controllerType);\n        }\n        \n        public ActionDescriptorCreator FindAction(ControllerContext controllerContext, string actionName)\n        {\n            MethodInfo method = FindActionMethod(controllerContext, actionName);\n\n            if (method == null)\n            {\n                return null;\n            }\n\n            return GetActionDescriptorDelegate(method);\n        }\n\n        internal bool AllowLegacyAsyncActions\n        {\n            get { return _allowLegacyAsyncActions; }\n        }\n\n        // This method and GetMethodInfo need to stay in sync, we need to be able to\n        // get a method info from each type of action descriptor we create.\n        internal ActionDescriptorCreator GetActionDescriptorDelegate(MethodInfo entryMethod)\n        {\n            // Does the action return a Task?\n            if (entryMethod.ReturnType != null && typeof(Task).IsAssignableFrom(entryMethod.ReturnType))\n            {\n                return (actionName, controllerDescriptor) => new TaskAsyncActionDescriptor(entryMethod, actionName, controllerDescriptor);\n            }\n\n            // Is this the FooAsync() / FooCompleted() pattern?\n            if (IsAsyncSuffixedMethod(entryMethod))\n            {\n                string completionMethodName = entryMethod.Name.Substring(0, entryMethod.Name.Length - \"Async\".Length) + \"Completed\";\n                MethodInfo completionMethod = GetMethodByName(completionMethodName);\n                if (completionMethod != null)\n                {\n                    return (actionName, controllerDescriptor) => new ReflectedAsyncActionDescriptor(entryMethod, completionMethod, actionName, controllerDescriptor);\n                }\n                else\n                {\n                    throw Error.AsyncActionMethodSelector_CouldNotFindMethod(completionMethodName, ControllerType);\n                }\n            }\n\n            // Fallback to synchronous method\n            return (actionName, controllerDescriptor) => new ReflectedActionDescriptor(entryMethod, actionName, controllerDescriptor);\n        }\n\n        protected override bool IsValidActionMethod(MethodInfo methodInfo)\n        {\n            return IsValidActionMethod(methodInfo, true /* stripInfrastructureMethods */);\n        }\n\n        private bool IsValidActionMethod(MethodInfo methodInfo, bool stripInfrastructureMethods)\n        {\n            if (methodInfo.IsSpecialName)\n            {\n                // not a normal method, e.g. a constructor or an event\n                return false;\n            }\n\n            if (methodInfo.GetBaseDefinition().DeclaringType.IsAssignableFrom(typeof(AsyncController)))\n            {\n                // is a method on Object, ControllerBase, Controller, or AsyncController\n                return false;\n            }\n\n            if (stripInfrastructureMethods)\n            {\n                if (IsCompletedSuffixedMethod(methodInfo))\n                {\n                    // do not match FooCompleted() methods, as these are infrastructure methods\n                    return false;\n                }\n            }\n\n            return true;\n        }\n\n        protected override string GetCanonicalMethodName(MethodInfo methodInfo)\n        {\n            string methodName = methodInfo.Name;\n            return (IsAsyncSuffixedMethod(methodInfo))\n                       ? methodName.Substring(0, methodName.Length - \"Async\".Length)\n                       : methodName;\n        }\n\n        private bool IsAsyncSuffixedMethod(MethodInfo methodInfo)\n        {\n            return _allowLegacyAsyncActions && methodInfo.Name.EndsWith(\"Async\", StringComparison.OrdinalIgnoreCase);\n        }\n\n        private bool IsCompletedSuffixedMethod(MethodInfo methodInfo)\n        {\n            return _allowLegacyAsyncActions && methodInfo.Name.EndsWith(\"Completed\", StringComparison.OrdinalIgnoreCase);\n        }\n\n        private MethodInfo GetMethodByName(string methodName)\n        {\n            List<MethodInfo> methods = (from MethodInfo methodInfo in ControllerType.GetMember(methodName, MemberTypes.Method, BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.IgnoreCase)\n                                        where IsValidActionMethod(methodInfo, false /* stripInfrastructureMethods */)\n                                        select methodInfo).ToList();\n\n            switch (methods.Count)\n            {\n                case 0:\n                    return null;\n\n                case 1:\n                    return methods[0];\n\n                default:\n                    throw CreateAmbiguousMethodMatchException(methods, methodName);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Async/AsyncControllerActionInvoker.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Threading;\nusing System.Web.Mvc.Filters;\nusing System.Web.Mvc.Routing;\n\nnamespace System.Web.Mvc.Async\n{\n    public class AsyncControllerActionInvoker : ControllerActionInvoker, IAsyncActionInvoker\n    {\n        private static readonly object _invokeActionTag = new object();\n        private static readonly object _invokeActionMethodTag = new object();\n        private static readonly object _invokeActionMethodWithFiltersTag = new object();\n\n        [SuppressMessage(\"Microsoft.Maintainability\", \"CA1500:VariableNamesShouldNotMatchFieldNames\", Justification = \"FxCop unable to handle what new compiler generates.\")]\n        [SuppressMessage(\"Microsoft.Maintainability\", \"CA1506:AvoidExcessiveClassCoupling\", Justification = \"Refactoring to reduce coupling not currently justified.\")]\n        public virtual IAsyncResult BeginInvokeAction(ControllerContext controllerContext, string actionName, AsyncCallback callback, object state)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n\n            Contract.Assert(controllerContext.RouteData != null);\n            if (String.IsNullOrEmpty(actionName) && !controllerContext.RouteData.HasDirectRouteMatch())\n            {\n                throw Error.ParameterCannotBeNullOrEmpty(\"actionName\");\n            }\n\n            ControllerDescriptor controllerDescriptor = GetControllerDescriptor(controllerContext);\n            ActionDescriptor actionDescriptor = FindAction(controllerContext, controllerDescriptor, actionName);\n            if (actionDescriptor != null)\n            {\n                FilterInfo filterInfo = GetFilters(controllerContext, actionDescriptor);\n                Action continuation = null;\n\n                BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState)\n                {\n                    try\n                    {\n                        AuthenticationContext authenticationContext = InvokeAuthenticationFilters(controllerContext,\n                            filterInfo.AuthenticationFilters, actionDescriptor);\n                        if (authenticationContext.Result != null)\n                        {\n                            // An authentication filter signaled that we should short-circuit the request. Let all\n                            // authentication filters contribute to an action result (to combine authentication\n                            // challenges). Then, run this action result.\n                            AuthenticationChallengeContext challengeContext =\n                                InvokeAuthenticationFiltersChallenge(controllerContext,\n                                filterInfo.AuthenticationFilters, actionDescriptor, authenticationContext.Result);\n                            continuation = () => InvokeActionResult(controllerContext,\n                                challengeContext.Result ?? authenticationContext.Result);\n                        }\n                        else\n                        {\n                            AuthorizationContext authorizationContext = InvokeAuthorizationFilters(controllerContext, filterInfo.AuthorizationFilters, actionDescriptor);\n                            if (authorizationContext.Result != null)\n                            {\n                                // An authorization filter signaled that we should short-circuit the request. Let all\n                                // authentication filters contribute to an action result (to combine authentication\n                                // challenges). Then, run this action result.\n                                AuthenticationChallengeContext challengeContext =\n                                    InvokeAuthenticationFiltersChallenge(controllerContext,\n                                    filterInfo.AuthenticationFilters, actionDescriptor, authorizationContext.Result);\n                                continuation = () => InvokeActionResult(controllerContext,\n                                    challengeContext.Result ?? authorizationContext.Result);\n                            }\n                            else\n                            {\n                                if (controllerContext.Controller.ValidateRequest)\n                                {\n                                    ValidateRequest(controllerContext);\n                                }\n\n                                IDictionary<string, object> parameters = GetParameterValues(controllerContext, actionDescriptor);\n                                IAsyncResult asyncResult = BeginInvokeActionMethodWithFilters(controllerContext, filterInfo.ActionFilters, actionDescriptor, parameters, asyncCallback, asyncState);\n                                continuation = () =>\n                                {\n                                    ActionExecutedContext postActionContext = EndInvokeActionMethodWithFilters(asyncResult);\n                                    // The action succeeded. Let all authentication filters contribute to an action\n                                    // result (to combine authentication challenges; some authentication filters need\n                                    // to do negotiation even on a successful result). Then, run this action result.\n                                    AuthenticationChallengeContext challengeContext =\n                                        InvokeAuthenticationFiltersChallenge(controllerContext,\n                                        filterInfo.AuthenticationFilters, actionDescriptor,\n                                        postActionContext.Result);\n                                    InvokeActionResultWithFilters(controllerContext, filterInfo.ResultFilters,\n                                        challengeContext.Result ?? postActionContext.Result);\n                                };\n                                return asyncResult;\n                            }\n                        }\n                    }\n                    catch (ThreadAbortException)\n                    {\n                        // This type of exception occurs as a result of Response.Redirect(), but we special-case so that\n                        // the filters don't see this as an error.\n                        throw;\n                    }\n                    catch (Exception ex)\n                    {\n                        // something blew up, so execute the exception filters\n                        ExceptionContext exceptionContext = InvokeExceptionFilters(controllerContext, filterInfo.ExceptionFilters, ex);\n                        if (!exceptionContext.ExceptionHandled)\n                        {\n                            throw;\n                        }\n\n                        continuation = () => InvokeActionResult(controllerContext, exceptionContext.Result);\n                    }\n\n                    return BeginInvokeAction_MakeSynchronousAsyncResult(asyncCallback, asyncState);\n                };\n\n                EndInvokeDelegate<bool> endDelegate = delegate(IAsyncResult asyncResult)\n                {\n                    try\n                    {\n                        continuation();\n                    }\n                    catch (ThreadAbortException)\n                    {\n                        // This type of exception occurs as a result of Response.Redirect(), but we special-case so that\n                        // the filters don't see this as an error.\n                        throw;\n                    }\n                    catch (Exception ex)\n                    {\n                        // something blew up, so execute the exception filters\n                        ExceptionContext exceptionContext = InvokeExceptionFilters(controllerContext, filterInfo.ExceptionFilters, ex);\n                        if (!exceptionContext.ExceptionHandled)\n                        {\n                            throw;\n                        }\n                        InvokeActionResult(controllerContext, exceptionContext.Result);\n                    }\n\n                    return true;\n                };\n\n                return AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, _invokeActionTag);\n            }\n            else\n            {\n                // Notify the controller that no action was found.\n                return BeginInvokeAction_ActionNotFound(callback, state);\n            }\n        }\n\n        private static IAsyncResult BeginInvokeAction_ActionNotFound(AsyncCallback callback, object state)\n        {\n            BeginInvokeDelegate beginDelegate = BeginInvokeAction_MakeSynchronousAsyncResult;\n\n            EndInvokeDelegate<bool> endDelegate = delegate(IAsyncResult asyncResult)\n            {\n                return false;\n            };\n\n            return AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, _invokeActionTag);\n        }\n\n        private static IAsyncResult BeginInvokeAction_MakeSynchronousAsyncResult(AsyncCallback callback, object state)\n        {\n            SimpleAsyncResult asyncResult = new SimpleAsyncResult(state);\n            asyncResult.MarkCompleted(true /* completedSynchronously */, callback);\n            return asyncResult;\n        }\n\n        protected internal virtual IAsyncResult BeginInvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters, AsyncCallback callback, object state)\n        {\n            AsyncActionDescriptor asyncActionDescriptor = actionDescriptor as AsyncActionDescriptor;\n            if (asyncActionDescriptor != null)\n            {\n                return BeginInvokeAsynchronousActionMethod(controllerContext, asyncActionDescriptor, parameters, callback, state);\n            }\n            else\n            {\n                return BeginInvokeSynchronousActionMethod(controllerContext, actionDescriptor, parameters, callback, state);\n            }\n        }\n\n        protected internal virtual IAsyncResult BeginInvokeActionMethodWithFilters(ControllerContext controllerContext, IList<IActionFilter> filters, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters, AsyncCallback callback, object state)\n        {\n            Func<ActionExecutedContext> endContinuation = null;\n\n            BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState)\n            {\n                AsyncInvocationWithFilters invocation = new AsyncInvocationWithFilters(this, controllerContext, actionDescriptor, filters, parameters, asyncCallback, asyncState);\n\n                const int StartingFilterIndex = 0;\n                endContinuation = invocation.InvokeActionMethodFilterAsynchronouslyRecursive(StartingFilterIndex);\n\n                if (invocation.InnerAsyncResult != null)\n                {\n                    // we're just waiting for the inner result to complete\n                    return invocation.InnerAsyncResult;\n                }\n                else\n                {\n                    // something was short-circuited and the action was not called, so this was a synchronous operation\n                    SimpleAsyncResult newAsyncResult = new SimpleAsyncResult(asyncState);\n                    newAsyncResult.MarkCompleted(completedSynchronously: true, callback: asyncCallback);\n                    return newAsyncResult;\n                }\n            };\n\n            EndInvokeDelegate<ActionExecutedContext> endDelegate = delegate(IAsyncResult asyncResult)\n            {\n                return endContinuation();\n            };\n\n            return AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, _invokeActionMethodWithFiltersTag);\n        }\n\n        private IAsyncResult BeginInvokeAsynchronousActionMethod(ControllerContext controllerContext, AsyncActionDescriptor actionDescriptor, IDictionary<string, object> parameters, AsyncCallback callback, object state)\n        {\n            BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState)\n            {\n                return actionDescriptor.BeginExecute(controllerContext, parameters, asyncCallback, asyncState);\n            };\n\n            EndInvokeDelegate<ActionResult> endDelegate = delegate(IAsyncResult asyncResult)\n            {\n                object returnValue = actionDescriptor.EndExecute(asyncResult);\n                ActionResult result = CreateActionResult(controllerContext, actionDescriptor, returnValue);\n                return result;\n            };\n\n            return AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, _invokeActionMethodTag);\n        }\n\n        private IAsyncResult BeginInvokeSynchronousActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters, AsyncCallback callback, object state)\n        {\n            // Frequently called so ensure delegate remains static and arguments do not allocate\n            EndInvokeDelegate<ActionInvocation, ActionResult> endInvokeFunc = (asyncResult, innerInvokeState) =>\n                {\n                    return innerInvokeState.InvokeSynchronousActionMethod();\n                };\n            ActionInvocation endInvokeState = new ActionInvocation(this, controllerContext, actionDescriptor, parameters);\n            return AsyncResultWrapper.BeginSynchronous(callback, state, endInvokeFunc, endInvokeState, _invokeActionMethodTag);\n        }\n\n        public virtual bool EndInvokeAction(IAsyncResult asyncResult)\n        {\n            return AsyncResultWrapper.End<bool>(asyncResult, _invokeActionTag);\n        }\n\n        protected internal virtual ActionResult EndInvokeActionMethod(IAsyncResult asyncResult)\n        {\n            return AsyncResultWrapper.End<ActionResult>(asyncResult, _invokeActionMethodTag);\n        }\n\n        protected internal virtual ActionExecutedContext EndInvokeActionMethodWithFilters(IAsyncResult asyncResult)\n        {\n            return AsyncResultWrapper.End<ActionExecutedContext>(asyncResult, _invokeActionMethodWithFiltersTag);\n        }\n\n        protected override ControllerDescriptor GetControllerDescriptor(ControllerContext controllerContext)\n        {\n            // Frequently called, so ensure delegate is static\n            Type controllerType = controllerContext.Controller.GetType();\n            ControllerDescriptor controllerDescriptor = DescriptorCache.GetDescriptor(\n                controllerType: controllerType,\n                creator: ReflectedAsyncControllerDescriptor.DefaultDescriptorFactory,\n                state: controllerType);\n            return controllerDescriptor;\n        }\n\n        // Keep as value type to avoid per-call allocation\n        private struct ActionInvocation\n        {\n            private readonly AsyncControllerActionInvoker _invoker;\n            private readonly ControllerContext _controllerContext;\n            private readonly ActionDescriptor _actionDescriptor;\n            private readonly IDictionary<string, object> _parameters;\n\n            internal ActionInvocation(AsyncControllerActionInvoker invoker, ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters)\n            {\n                Contract.Assert(invoker != null);\n                Contract.Assert(controllerContext != null);\n                Contract.Assert(actionDescriptor != null);\n                Contract.Assert(parameters != null);\n\n                _invoker = invoker;\n                _controllerContext = controllerContext;\n                _actionDescriptor = actionDescriptor;\n                _parameters = parameters;\n            }\n\n            internal ActionResult InvokeSynchronousActionMethod()\n            {\n                return _invoker.InvokeActionMethod(_controllerContext, _actionDescriptor, _parameters);\n            }\n        }\n\n        // Large and passed to many function calls, so keep as a reference type to minimize copying\n        private class AsyncInvocationWithFilters\n        {\n            private readonly AsyncControllerActionInvoker _invoker;\n            private readonly ControllerContext _controllerContext;\n            private readonly ActionDescriptor _actionDescriptor;\n            private readonly IList<IActionFilter> _filters;\n            private readonly IDictionary<string, object> _parameters;\n            private readonly AsyncCallback _asyncCallback;\n            private readonly object _asyncState;\n            private readonly int _filterCount;\n            private readonly ActionExecutingContext _preContext;\n\n            internal IAsyncResult InnerAsyncResult;\n\n            internal AsyncInvocationWithFilters(AsyncControllerActionInvoker invoker, ControllerContext controllerContext, ActionDescriptor actionDescriptor, IList<IActionFilter> filters, IDictionary<string, object> parameters, AsyncCallback asyncCallback, object asyncState)\n            {\n                Contract.Assert(invoker != null);\n                Contract.Assert(controllerContext != null);\n                Contract.Assert(actionDescriptor != null);\n                Contract.Assert(filters != null);\n                Contract.Assert(parameters != null);\n\n                _invoker = invoker;\n                _controllerContext = controllerContext;\n                _actionDescriptor = actionDescriptor;\n                _filters = filters;\n                _parameters = parameters;\n                _asyncCallback = asyncCallback;\n                _asyncState = asyncState;\n\n                _preContext = new ActionExecutingContext(controllerContext, actionDescriptor, parameters);\n                // For IList<T> it is faster to cache the count\n                _filterCount = _filters.Count;\n            }\n\n            internal Func<ActionExecutedContext> InvokeActionMethodFilterAsynchronouslyRecursive(int filterIndex)\n            {\n                // Performance-sensitive\n\n                // For compatability, the following behavior must be maintained\n                //   The OnActionExecuting events must fire in forward order\n                //   The Begin and End events must fire\n                //   The OnActionExecuted events must fire in reverse order\n                //   Earlier filters can process the results and exceptions from the handling of later filters\n                // This is achieved by calling recursively and moving through the filter list forwards\n\n                // If there are no more filters to recurse over, create the main result\n                if (filterIndex > _filterCount - 1)\n                {\n                    InnerAsyncResult = _invoker.BeginInvokeActionMethod(_controllerContext, _actionDescriptor, _parameters, _asyncCallback, _asyncState);\n                    return () =>\n                           new ActionExecutedContext(_controllerContext, _actionDescriptor, canceled: false, exception: null)\n                           {\n                               Result = _invoker.EndInvokeActionMethod(InnerAsyncResult)\n                           };\n                }\n\n                // Otherwise process the filters recursively\n                IActionFilter filter = _filters[filterIndex];\n                ActionExecutingContext preContext = _preContext;\n                filter.OnActionExecuting(preContext);\n                if (preContext.Result != null)\n                {\n                    ActionExecutedContext shortCircuitedPostContext = new ActionExecutedContext(preContext, preContext.ActionDescriptor, canceled: true, exception: null)\n                    {\n                        Result = preContext.Result\n                    };\n                    return () => shortCircuitedPostContext;\n                }\n\n                // There is a nested try / catch block here that contains much the same logic as the outer block.\n                // Since an exception can occur on either side of the asynchronous invocation, we need guards on\n                // on both sides. In the code below, the second side is represented by the nested delegate. This\n                // is really just a parallel of the synchronous ControllerActionInvoker.InvokeActionMethodFilter()\n                // method.\n\n                try\n                {\n                    // Use the filters in forward direction\n                    int nextFilterIndex = filterIndex + 1;\n                    Func<ActionExecutedContext> continuation = InvokeActionMethodFilterAsynchronouslyRecursive(nextFilterIndex);\n\n                    // add our own continuation, then return the new function\n                    return () =>\n                    {\n                        ActionExecutedContext postContext;\n                        bool wasError = true;\n\n                        try\n                        {\n                            postContext = continuation();\n                            wasError = false;\n                        }\n                        catch (ThreadAbortException)\n                        {\n                            // This type of exception occurs as a result of Response.Redirect(), but we special-case so that\n                            // the filters don't see this as an error.\n                            postContext = new ActionExecutedContext(preContext, preContext.ActionDescriptor, canceled: false, exception: null);\n                            filter.OnActionExecuted(postContext);\n                            throw;\n                        }\n                        catch (Exception ex)\n                        {\n                            postContext = new ActionExecutedContext(preContext, preContext.ActionDescriptor, canceled: false, exception: ex);\n                            filter.OnActionExecuted(postContext);\n                            if (!postContext.ExceptionHandled)\n                            {\n                                throw;\n                            }\n                        }\n                        if (!wasError)\n                        {\n                            filter.OnActionExecuted(postContext);\n                        }\n\n                        return postContext;\n                    };\n                }\n                catch (ThreadAbortException)\n                {\n                    // This type of exception occurs as a result of Response.Redirect(), but we special-case so that\n                    // the filters don't see this as an error.\n                    ActionExecutedContext postContext = new ActionExecutedContext(preContext, preContext.ActionDescriptor, canceled: false, exception: null);\n                    filter.OnActionExecuted(postContext);\n                    throw;\n                }\n                catch (Exception ex)\n                {\n                    ActionExecutedContext postContext = new ActionExecutedContext(preContext, preContext.ActionDescriptor, canceled: false, exception: ex);\n                    filter.OnActionExecuted(postContext);\n                    if (postContext.ExceptionHandled)\n                    {\n                        return () => postContext;\n                    }\n                    else\n                    {\n                        throw;\n                    }\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Async/AsyncManager.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Threading;\n\nnamespace System.Web.Mvc.Async\n{\n    public class AsyncManager\n    {\n        private readonly SynchronizationContext _syncContext;\n\n        /// <summary>\n        /// default timeout is 45 sec\n        /// </summary>\n        /// <remarks>\n        /// from: http://msdn.microsoft.com/en-us/library/system.web.ui.page.asynctimeout.aspx\n        /// </remarks>\n        private int _timeout = 45 * 1000;\n\n        public AsyncManager()\n            : this(null /* syncContext */)\n        {\n        }\n\n        public AsyncManager(SynchronizationContext syncContext)\n        {\n            _syncContext = syncContext ?? SynchronizationContextUtil.GetSynchronizationContext();\n\n            OutstandingOperations = new OperationCounter();\n            OutstandingOperations.Completed += delegate\n            {\n                Finish();\n            };\n\n            Parameters = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);\n        }\n\n        public event EventHandler Finished;\n\n        public OperationCounter OutstandingOperations { get; private set; }\n\n        public IDictionary<string, object> Parameters { get; private set; }\n\n        /// <summary>\n        /// Measured in milliseconds, Timeout.Infinite means 'no timeout'\n        /// </summary>\n        public int Timeout\n        {\n            get { return _timeout; }\n            set\n            {\n                if (value < -1)\n                {\n                    throw Error.AsyncCommon_InvalidTimeout(\"value\");\n                }\n                _timeout = value;\n            }\n        }\n\n        /// <summary>\n        /// The developer may call this function to signal that all operations are complete instead of\n        /// waiting for the operation counter to reach zero.\n        /// </summary>\n        public virtual void Finish()\n        {\n            EventHandler handler = Finished;\n            if (handler != null)\n            {\n                handler(this, EventArgs.Empty);\n            }\n        }\n\n        /// <summary>\n        /// Executes a callback in the current synchronization context, which gives access to HttpContext and related items.\n        /// </summary>\n        /// <param name=\"action\"></param>\n        public virtual void Sync(Action action)\n        {\n            _syncContext.Sync(action);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Async/AsyncResultWrapper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Threading;\n\nnamespace System.Web.Mvc.Async\n{\n    // This class is used for the following pattern:\n\n    // public IAsyncResult BeginInner(..., callback, state);\n    // public TInnerResult EndInner(asyncResult);\n    // public IAsyncResult BeginOuter(..., callback, state);\n    // public TOuterResult EndOuter(asyncResult);\n\n    // That is, Begin/EndOuter() wrap Begin/EndInner(), potentially with pre- and post-processing.\n\n    [DebuggerNonUserCode]\n    internal static class AsyncResultWrapper\n    {\n        // helper methods\n\n        private static readonly EndInvokeDelegate<Action, AsyncVoid> _voidEndInvoke = (IAsyncResult asyncResult, Action action) =>\n        {\n            action();\n            return default(AsyncVoid);\n        };\n\n        // kicks off an asynchronous operation\n\n        public static IAsyncResult Begin<TResult>(AsyncCallback callback, object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate<TResult> endDelegate, object tag = null, int timeout = Timeout.Infinite)\n        {\n            WrappedAsyncResult<TResult> asyncResult = new WrappedAsyncResult<TResult>(beginDelegate, endDelegate, tag, callbackSyncContext: null);\n            asyncResult.Begin(callback, state, timeout);\n            return asyncResult;\n        }\n\n        public static IAsyncResult Begin<TResult, TState>(AsyncCallback callback, object callbackState, BeginInvokeDelegate<TState> beginDelegate, EndInvokeDelegate<TState, TResult> endDelegate, TState invokeState, object tag = null, int timeout = Timeout.Infinite, SynchronizationContext callbackSyncContext = null)\n        {\n            WrappedAsyncResult<TResult, TState> asyncResult = new WrappedAsyncResult<TResult, TState>(beginDelegate, endDelegate, invokeState, tag, callbackSyncContext);\n            asyncResult.Begin(callback, callbackState, timeout);\n            return asyncResult;\n        }\n\n        public static IAsyncResult Begin<TState>(AsyncCallback callback, object callbackState, BeginInvokeDelegate<TState> beginDelegate, EndInvokeVoidDelegate<TState> endDelegate, TState invokeState, object tag = null, int timeout = Timeout.Infinite, SynchronizationContext callbackSyncContext = null)\n        {\n            WrappedAsyncVoid<TState> asyncResult = new WrappedAsyncVoid<TState>(beginDelegate, endDelegate, invokeState, tag, callbackSyncContext);\n            asyncResult.Begin(callback, callbackState, timeout);\n            return asyncResult;\n        }\n\n        // wraps a synchronous operation in an asynchronous wrapper, but still completes synchronously\n\n        public static IAsyncResult BeginSynchronous<TResult, TState>(AsyncCallback callback, object callbackState, EndInvokeDelegate<TState, TResult> func, TState funcState, object tag)\n        {\n            // Frequently called, so use static delegates\n\n            // Inline delegates that take a generic argument from a generic method don't get cached by the compiler so use a field from a static generic class\n            BeginInvokeDelegate<TState> beginDelegate = CachedDelegates<TState>.CompletedBeginInvoke;\n\n            // Pass in the blocking function as the End() method\n            WrappedAsyncResult<TResult, TState> asyncResult = new WrappedAsyncResult<TResult, TState>(beginDelegate, func, funcState, tag, callbackSyncContext: null);\n            asyncResult.Begin(callback, callbackState, Timeout.Infinite);\n            return asyncResult;\n        }\n\n        public static IAsyncResult BeginSynchronous(AsyncCallback callback, object state, Action action, object tag)\n        {\n            return BeginSynchronous<AsyncVoid, Action>(callback, state, _voidEndInvoke, action, tag);\n        }\n\n        // completes an asynchronous operation\n\n        public static TResult End<TResult>(IAsyncResult asyncResult)\n        {\n            return End<TResult>(asyncResult, tag: null);\n        }\n\n        public static TResult End<TResult>(IAsyncResult asyncResult, object tag)\n        {\n            return WrappedAsyncResultBase<TResult>.Cast(asyncResult, tag).End();\n        }\n\n        public static void End(IAsyncResult asyncResult)\n        {\n            End(asyncResult, tag: null);\n        }\n\n        public static void End(IAsyncResult asyncResult, object tag)\n        {\n            End<AsyncVoid>(asyncResult, tag);\n        }\n\n        private static class CachedDelegates<TState>\n        {\n            internal static BeginInvokeDelegate<TState> CompletedBeginInvoke = (AsyncCallback asyncCallback, object asyncState, TState invokeState) =>\n            {\n                // Begin() doesn't perform any work on its own and returns immediately.\n                SimpleAsyncResult innerAsyncResult = new SimpleAsyncResult(asyncState);\n                innerAsyncResult.MarkCompleted(completedSynchronously: true, callback: asyncCallback);\n                return innerAsyncResult;\n            };\n        }\n\n        [DebuggerNonUserCode]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable\", Justification = \"The Timer will be disposed of either when it fires or when the operation completes successfully.\")]\n        private abstract class WrappedAsyncResultBase<TResult> : IAsyncResult\n        {\n            private const int AsyncStateNone = 0;\n            private const int AsyncStateBeginUnwound = 1;\n            private const int AsyncStateCallbackFired = 2;\n\n            private int _asyncState;\n            private readonly object _beginDelegateLockObj = new object();\n            private readonly SingleEntryGate _endExecutedGate = new SingleEntryGate(); // prevent End() from being called twice\n            private readonly SingleEntryGate _handleCallbackGate = new SingleEntryGate(); // prevent callback from being handled multiple times\n            private readonly object _tag; // prevent an instance of this type from being passed to the wrong End() method\n            private IAsyncResult _innerAsyncResult;\n            private AsyncCallback _originalCallback;\n            private volatile bool _timedOut;\n            private Timer _timer;\n            private readonly SynchronizationContext _callbackSyncContext;\n\n            protected WrappedAsyncResultBase(object tag, SynchronizationContext callbackSyncContext)\n            {\n                _tag = tag;\n                _callbackSyncContext = callbackSyncContext;\n            }\n\n            public object AsyncState\n            {\n                get { return _innerAsyncResult.AsyncState; }\n            }\n\n            public WaitHandle AsyncWaitHandle\n            {\n                get { return null; }\n            }\n\n            public bool CompletedSynchronously { get; private set; }\n\n            public bool IsCompleted\n            {\n                get { return _timedOut || _innerAsyncResult.IsCompleted; }\n            }\n\n            // kicks off the process, instantiates a timer if requested\n            public void Begin(AsyncCallback callback, object state, int timeout)\n            {\n                _originalCallback = callback;\n\n                // Force the target Begin() operation to complete before the callback can continue,\n                // since the target operation might perform post-processing of the data.\n                lock (_beginDelegateLockObj)\n                {\n                    _innerAsyncResult = CallBeginDelegate(HandleAsynchronousCompletion, state);\n\n                    // If the callback has already fired, then the completion routine has no-oped and we\n                    // can just treat this as if it were a normal synchronous completion.\n                    int originalState = Interlocked.Exchange(ref _asyncState, AsyncStateBeginUnwound);\n                    bool callbackAlreadyFired = (originalState == AsyncStateCallbackFired);\n\n                    CompletedSynchronously = callbackAlreadyFired || _innerAsyncResult.CompletedSynchronously;\n\n                    if (!CompletedSynchronously)\n                    {\n                        if (timeout > Timeout.Infinite)\n                        {\n                            CreateTimer(timeout);\n                        }\n                    }\n                }\n\n                if (CompletedSynchronously)\n                {\n                    if (callback != null)\n                    {\n                        callback(this);\n                    }\n                }\n            }\n\n            protected abstract IAsyncResult CallBeginDelegate(AsyncCallback callback, object callbackState);\n\n            protected abstract TResult CallEndDelegate(IAsyncResult asyncResult);\n\n            public static WrappedAsyncResultBase<TResult> Cast(IAsyncResult asyncResult, object tag)\n            {\n                if (asyncResult == null)\n                {\n                    throw new ArgumentNullException(\"asyncResult\");\n                }\n\n                WrappedAsyncResultBase<TResult> castResult = asyncResult as WrappedAsyncResultBase<TResult>;\n                if (castResult != null && Equals(castResult._tag, tag))\n                {\n                    return castResult;\n                }\n                else\n                {\n                    throw Error.AsyncCommon_InvalidAsyncResult(\"asyncResult\");\n                }\n            }\n\n            private void CallbackUsingSyncContext()\n            {\n                _callbackSyncContext.Sync(() => _originalCallback(this));\n            }\n\n            private void CreateTimer(int timeout)\n            {\n                // this method should be called within a lock(_beginDelegateLockObj)\n                _timer = new Timer(HandleTimeout, null, timeout, Timeout.Infinite /* disable periodic signaling */);\n            }\n\n            public TResult End()\n            {\n                if (!_endExecutedGate.TryEnter())\n                {\n                    throw Error.AsyncCommon_AsyncResultAlreadyConsumed();\n                }\n\n                if (_timedOut)\n                {\n                    throw new TimeoutException();\n                }\n                WaitForBeginToCompleteAndDestroyTimer();\n\n                return CallEndDelegate(_innerAsyncResult);\n            }\n\n            private void ExecuteAsynchronousCallback(bool timedOut)\n            {\n                WaitForBeginToCompleteAndDestroyTimer();\n\n                if (_handleCallbackGate.TryEnter())\n                {\n                    _timedOut = timedOut;\n                    if (_originalCallback != null)\n                    {\n                        if (_callbackSyncContext != null)\n                        {\n                            CallbackUsingSyncContext();\n                        }\n                        else\n                        {\n                            _originalCallback(this);\n                        }\n                    }\n                }\n            }\n\n            private void HandleAsynchronousCompletion(IAsyncResult asyncResult)\n            {\n                // Transition the async state to CALLBACK_FIRED. If the Begin* method hasn't yet unwound,\n                // then we can no-op here since the Begin method will query the _asyncState field and\n                // treat this as a regular synchronous completion.\n                int originalState = Interlocked.Exchange(ref _asyncState, AsyncStateCallbackFired);\n                if (originalState != AsyncStateBeginUnwound)\n                {\n                    return;\n                }\n\n                ExecuteAsynchronousCallback(timedOut: false);\n            }\n\n            private void HandleTimeout(object state)\n            {\n                ExecuteAsynchronousCallback(timedOut: true);\n            }\n\n            private void WaitForBeginToCompleteAndDestroyTimer()\n            {\n                lock (_beginDelegateLockObj)\n                {\n                    // Wait for the target Begin() method to complete, as it might be performing\n                    // post-processing. This also forces a memory barrier, so _innerAsyncResult\n                    // is guaranteed to be non-null at this point.\n\n                    if (_timer != null)\n                    {\n                        _timer.Dispose();\n                    }\n                    _timer = null;\n                }\n            }\n        }\n\n        private sealed class WrappedAsyncResult<TResult> : WrappedAsyncResultBase<TResult>\n        {\n            private readonly BeginInvokeDelegate _beginDelegate;\n            private readonly EndInvokeDelegate<TResult> _endDelegate;\n\n            public WrappedAsyncResult(BeginInvokeDelegate beginDelegate, EndInvokeDelegate<TResult> endDelegate, object tag, SynchronizationContext callbackSyncContext)\n                : base(tag, callbackSyncContext)\n            {\n                _beginDelegate = beginDelegate;\n                _endDelegate = endDelegate;\n            }\n\n            protected override IAsyncResult CallBeginDelegate(AsyncCallback callback, object callbackState)\n            {\n                return _beginDelegate(callback, callbackState);\n            }\n\n            protected override TResult CallEndDelegate(IAsyncResult asyncResult)\n            {\n                return _endDelegate(asyncResult);\n            }\n        }\n\n        private sealed class WrappedAsyncResult<TResult, TState> : WrappedAsyncResultBase<TResult>\n        {\n            private readonly BeginInvokeDelegate<TState> _beginDelegate;\n            private readonly EndInvokeDelegate<TState, TResult> _endDelegate;\n            private readonly TState _state;\n\n            public WrappedAsyncResult(BeginInvokeDelegate<TState> beginDelegate, EndInvokeDelegate<TState, TResult> endDelegate, TState state, object tag, SynchronizationContext callbackSyncContext)\n                : base(tag, callbackSyncContext)\n            {\n                _beginDelegate = beginDelegate;\n                _endDelegate = endDelegate;\n                _state = state;\n            }\n\n            protected override TResult CallEndDelegate(IAsyncResult asyncResult)\n            {\n                return _endDelegate(asyncResult, _state);\n            }\n\n            protected override IAsyncResult CallBeginDelegate(AsyncCallback callback, object callbackState)\n            {\n                return _beginDelegate(callback, callbackState, _state);\n            }\n        }\n\n        private sealed class WrappedAsyncVoid<TState> : WrappedAsyncResultBase<AsyncVoid>\n        {\n            private readonly BeginInvokeDelegate<TState> _beginDelegate;\n            private readonly EndInvokeVoidDelegate<TState> _endDelegate;\n            private readonly TState _state;\n\n            public WrappedAsyncVoid(BeginInvokeDelegate<TState> beginDelegate, EndInvokeVoidDelegate<TState> endDelegate, TState state, object tag, SynchronizationContext callbackSyncContext)\n                : base(tag, callbackSyncContext)\n            {\n                _beginDelegate = beginDelegate;\n                _endDelegate = endDelegate;\n                _state = state;\n            }\n\n            protected override AsyncVoid CallEndDelegate(IAsyncResult asyncResult)\n            {\n                _endDelegate(asyncResult, _state);\n                return default(AsyncVoid);\n            }\n\n            protected override IAsyncResult CallBeginDelegate(AsyncCallback callback, object callbackState)\n            {\n                return _beginDelegate(callback, callbackState, _state);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Async/AsyncVoid.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc.Async\n{\n    // Dummy type used for passing something resembling 'void' to the async delegate functions\n    internal struct AsyncVoid\n    {\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Async/BeginInvokeDelegate.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc.Async\n{\n    internal delegate IAsyncResult BeginInvokeDelegate(AsyncCallback callback, object state);\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Async/BeginInvokeDelegateOfTState.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc.Async\n{\n    internal delegate IAsyncResult BeginInvokeDelegate<TState>(AsyncCallback callback, object callbackState, TState invokeState);\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Async/EndInvokeDelegateOfTResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc.Async\n{\n    internal delegate TResult EndInvokeDelegate<TResult>(IAsyncResult asyncResult);\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Async/EndInvokeDelegateOfTResultTState.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc.Async\n{\n    internal delegate TResult EndInvokeDelegate<TState, TResult>(IAsyncResult asyncResult, TState state);\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Async/EndInvokeVoidDelegate.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc.Async\n{\n    internal delegate void EndInvokeVoidDelegate<TState>(IAsyncResult asyncResult, TState state);\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Async/IAsyncActionInvoker.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc.Async\n{\n    public interface IAsyncActionInvoker : IActionInvoker\n    {\n        IAsyncResult BeginInvokeAction(ControllerContext controllerContext, string actionName, AsyncCallback callback, object state);\n        bool EndInvokeAction(IAsyncResult asyncResult);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Async/IAsyncActionInvokerFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc.Async\n{\n    /// <summary>\n    /// Used to create an <see cref=\"IAsyncActionInvoker\"/> instance for the current request.\n    /// </summary>\n    public interface IAsyncActionInvokerFactory\n    {\n        /// <summary>\n        /// Creates an instance of async action invoker for the current request.\n        /// </summary>\n        /// <returns>The created <see cref=\"IAsyncActionInvoker\"/>.</returns>\n        IAsyncActionInvoker CreateInstance();\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Async/IAsyncController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Routing;\n\nnamespace System.Web.Mvc.Async\n{\n    public interface IAsyncController : IController\n    {\n        IAsyncResult BeginExecute(RequestContext requestContext, AsyncCallback callback, object state);\n        void EndExecute(IAsyncResult asyncResult);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Async/IAsyncManagerContainer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc.Async\n{\n    public interface IAsyncManagerContainer\n    {\n        AsyncManager AsyncManager { get; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Async/OperationCounter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\n\nnamespace System.Web.Mvc.Async\n{\n    public sealed class OperationCounter\n    {\n        private int _count;\n\n        public event EventHandler Completed;\n\n        public int Count\n        {\n            get { return Thread.VolatileRead(ref _count); }\n        }\n\n        private int AddAndExecuteCallbackIfCompleted(int value)\n        {\n            int newCount = Interlocked.Add(ref _count, value);\n            if (newCount == 0)\n            {\n                OnCompleted();\n            }\n\n            return newCount;\n        }\n\n        public int Decrement()\n        {\n            return AddAndExecuteCallbackIfCompleted(-1);\n        }\n\n        public int Decrement(int value)\n        {\n            return AddAndExecuteCallbackIfCompleted(-value);\n        }\n\n        public int Increment()\n        {\n            return AddAndExecuteCallbackIfCompleted(1);\n        }\n\n        public int Increment(int value)\n        {\n            return AddAndExecuteCallbackIfCompleted(value);\n        }\n\n        private void OnCompleted()\n        {\n            EventHandler handler = Completed;\n            if (handler != null)\n            {\n                handler(this, EventArgs.Empty);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Async/ReflectedAsyncActionDescriptor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing System.Threading;\n\nnamespace System.Web.Mvc.Async\n{\n    public class ReflectedAsyncActionDescriptor : AsyncActionDescriptor, IMethodInfoActionDescriptor\n    {\n        private readonly object _executeTag = new object();\n\n        private readonly string _actionName;\n        private readonly ControllerDescriptor _controllerDescriptor;\n        private readonly Lazy<string> _uniqueId;\n        private ParameterDescriptor[] _parametersCache;\n\n        public ReflectedAsyncActionDescriptor(MethodInfo asyncMethodInfo, MethodInfo completedMethodInfo, string actionName, ControllerDescriptor controllerDescriptor)\n            : this(asyncMethodInfo, completedMethodInfo, actionName, controllerDescriptor, true /* validateMethods */)\n        {\n        }\n\n        internal ReflectedAsyncActionDescriptor(MethodInfo asyncMethodInfo, MethodInfo completedMethodInfo, string actionName, ControllerDescriptor controllerDescriptor, bool validateMethods)\n        {\n            if (asyncMethodInfo == null)\n            {\n                throw new ArgumentNullException(\"asyncMethodInfo\");\n            }\n            if (completedMethodInfo == null)\n            {\n                throw new ArgumentNullException(\"completedMethodInfo\");\n            }\n            if (String.IsNullOrEmpty(actionName))\n            {\n                throw Error.ParameterCannotBeNullOrEmpty(\"actionName\");\n            }\n            if (controllerDescriptor == null)\n            {\n                throw new ArgumentNullException(\"controllerDescriptor\");\n            }\n\n            if (validateMethods)\n            {\n                string asyncFailedMessage = VerifyActionMethodIsCallable(asyncMethodInfo);\n                if (asyncFailedMessage != null)\n                {\n                    throw new ArgumentException(asyncFailedMessage, \"asyncMethodInfo\");\n                }\n\n                string completedFailedMessage = VerifyActionMethodIsCallable(completedMethodInfo);\n                if (completedFailedMessage != null)\n                {\n                    throw new ArgumentException(completedFailedMessage, \"completedMethodInfo\");\n                }\n            }\n\n            AsyncMethodInfo = asyncMethodInfo;\n            CompletedMethodInfo = completedMethodInfo;\n            _actionName = actionName;\n            _controllerDescriptor = controllerDescriptor;\n            _uniqueId = new Lazy<string>(CreateUniqueId);\n        }\n\n        public override string ActionName\n        {\n            get { return _actionName; }\n        }\n\n        public MethodInfo AsyncMethodInfo { get; private set; }\n\n        public MethodInfo CompletedMethodInfo { get; private set; }\n\n        public override ControllerDescriptor ControllerDescriptor\n        {\n            get { return _controllerDescriptor; }\n        }\n\n        public MethodInfo MethodInfo\n        {\n            get { return AsyncMethodInfo; }\n        }\n\n        public override string UniqueId\n        {\n            get { return _uniqueId.Value; }\n        }\n\n        public override IAsyncResult BeginExecute(ControllerContext controllerContext, IDictionary<string, object> parameters, AsyncCallback callback, object state)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n            if (parameters == null)\n            {\n                throw new ArgumentNullException(\"parameters\");\n            }\n\n            AsyncManager asyncManager = GetAsyncManager(controllerContext.Controller);\n\n            BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState)\n            {\n                // call the XxxAsync() method\n                ParameterInfo[] parameterInfos = AsyncMethodInfo.GetParameters();\n                var rawParameterValues = from parameterInfo in parameterInfos\n                                         select ExtractParameterFromDictionary(parameterInfo, parameters, AsyncMethodInfo);\n                object[] parametersArray = rawParameterValues.ToArray();\n\n                TriggerListener listener = new TriggerListener();\n                SimpleAsyncResult asyncResult = new SimpleAsyncResult(asyncState);\n\n                // hook the Finished event to notify us upon completion\n                Trigger finishTrigger = listener.CreateTrigger();\n                asyncManager.Finished += delegate\n                {\n                    finishTrigger.Fire();\n                };\n                asyncManager.OutstandingOperations.Increment();\n\n                // to simplify the logic, force the rest of the pipeline to execute in an asynchronous callback\n                listener.SetContinuation(() => ThreadPool.QueueUserWorkItem(_ => asyncResult.MarkCompleted(false /* completedSynchronously */, asyncCallback)));\n\n                // the inner operation might complete synchronously, so all setup work has to be done before this point\n                ActionMethodDispatcher dispatcher = DispatcherCache.GetDispatcher(AsyncMethodInfo);\n                dispatcher.Execute(controllerContext.Controller, parametersArray); // ignore return value from this method\n\n                // now that the XxxAsync() method has completed, kick off any pending operations\n                asyncManager.OutstandingOperations.Decrement();\n                listener.Activate();\n                return asyncResult;\n            };\n\n            EndInvokeDelegate<object> endDelegate = delegate(IAsyncResult asyncResult)\n            {\n                // call the XxxCompleted() method\n                ParameterInfo[] completionParametersInfos = CompletedMethodInfo.GetParameters();\n                var rawCompletionParameterValues = from parameterInfo in completionParametersInfos\n                                                   select ExtractParameterOrDefaultFromDictionary(parameterInfo, asyncManager.Parameters);\n                object[] completionParametersArray = rawCompletionParameterValues.ToArray();\n\n                ActionMethodDispatcher dispatcher = DispatcherCache.GetDispatcher(CompletedMethodInfo);\n                object actionReturnValue = dispatcher.Execute(controllerContext.Controller, completionParametersArray);\n                return actionReturnValue;\n            };\n\n            return AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, _executeTag, asyncManager.Timeout);\n        }\n\n        private string CreateUniqueId()\n        {\n            return base.UniqueId + DescriptorUtil.CreateUniqueId(AsyncMethodInfo, CompletedMethodInfo);\n        }\n\n        public override object EndExecute(IAsyncResult asyncResult)\n        {\n            return AsyncResultWrapper.End<object>(asyncResult, _executeTag);\n        }\n\n        public override object[] GetCustomAttributes(bool inherit)\n        {\n            return ActionDescriptorHelper.GetCustomAttributes(AsyncMethodInfo, inherit);\n        }\n\n        public override object[] GetCustomAttributes(Type attributeType, bool inherit)\n        {\n            return ActionDescriptorHelper.GetCustomAttributes(AsyncMethodInfo, attributeType, inherit);\n        }\n\n        public override IEnumerable<FilterAttribute> GetFilterAttributes(bool useCache)\n        {\n            if (useCache && GetType() == typeof(ReflectedAsyncActionDescriptor))\n            {\n                // Do not look at cache in types derived from this type because they might incorrectly implement GetCustomAttributes\n                return ReflectedAttributeCache.GetMethodFilterAttributes(AsyncMethodInfo);\n            }\n            return base.GetFilterAttributes(useCache);\n        }\n\n        public override ParameterDescriptor[] GetParameters()\n        {\n            return ActionDescriptorHelper.GetParameters(this, AsyncMethodInfo, ref _parametersCache);\n        }\n\n        public override ICollection<ActionSelector> GetSelectors()\n        {\n            return ActionDescriptorHelper.GetSelectors(AsyncMethodInfo);\n        }\n\n        internal override ICollection<ActionNameSelector> GetNameSelectors()\n        {\n            return ActionDescriptorHelper.GetNameSelectors(AsyncMethodInfo);\n        }\n\n        public override bool IsDefined(Type attributeType, bool inherit)\n        {\n            return ActionDescriptorHelper.IsDefined(AsyncMethodInfo, attributeType, inherit);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Async/ReflectedAsyncControllerDescriptor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Mvc.Async\n{\n    public class ReflectedAsyncControllerDescriptor : ControllerDescriptor\n    {\n        internal static readonly Func<Type, ControllerDescriptor> DefaultDescriptorFactory =\n            (type) => new ReflectedAsyncControllerDescriptor(type);\n\n        private static readonly ActionDescriptor[] _emptyCanonicalActions = new ActionDescriptor[0];\n\n        private readonly Type _controllerType;\n        private readonly AsyncActionMethodSelector _selector;\n\n        public ReflectedAsyncControllerDescriptor(Type controllerType)\n        {\n            if (controllerType == null)\n            {\n                throw new ArgumentNullException(\"controllerType\");\n            }\n\n            _controllerType = controllerType;\n            bool allowLegacyAsyncActions = AllowLegacyAsyncActions(_controllerType);\n            _selector = new AsyncActionMethodSelector(_controllerType, allowLegacyAsyncActions);\n        }\n\n        public sealed override Type ControllerType\n        {\n            get { return _controllerType; }\n        }\n\n        internal AsyncActionMethodSelector Selector\n        {\n            get { return _selector; }\n        }\n\n        /// <summary>\n        /// Determines if we should bind \"Foo\" to FooAsync/FooCompleted pattern. \n        /// </summary>\n        /// <param name=\"controllerType\"></param>\n        /// <returns></returns>\n        private static bool AllowLegacyAsyncActions(Type controllerType)\n        {\n            if (typeof(AsyncController).IsAssignableFrom(controllerType))\n            {\n                return true;\n            }\n            if (typeof(Controller).IsAssignableFrom(controllerType))\n            {\n                // for backwards compat. Controller now supports IAsyncController, \n                // but still use synchronous bindings patterns. \n                return false;\n            }\n            if (!typeof(IAsyncController).IsAssignableFrom(controllerType))\n            {\n                return false;\n            }\n            return true;\n        }\n\n        public override ActionDescriptor FindAction(ControllerContext controllerContext, string actionName)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n            if (String.IsNullOrEmpty(actionName))\n            {\n                throw Error.ParameterCannotBeNullOrEmpty(\"actionName\");\n            }\n\n            ActionDescriptorCreator creator = _selector.FindAction(controllerContext, actionName);\n            if (creator == null)\n            {\n                return null;\n            }\n\n            return creator(actionName, this);\n        }\n\n        public override ActionDescriptor[] GetCanonicalActions()\n        {\n            // everything is looked up dymanically, so there are no 'canonical' actions\n            return _emptyCanonicalActions;\n        }\n\n        public override object[] GetCustomAttributes(bool inherit)\n        {\n            return ControllerType.GetCustomAttributes(inherit);\n        }\n\n        public override object[] GetCustomAttributes(Type attributeType, bool inherit)\n        {\n            return ControllerType.GetCustomAttributes(attributeType, inherit);\n        }\n\n        public override IEnumerable<FilterAttribute> GetFilterAttributes(bool useCache)\n        {\n            if (useCache && GetType() == typeof(ReflectedAsyncControllerDescriptor))\n            {\n                // Do not look at cache in types derived from this type because they might incorrectly implement GetCustomAttributes\n                return ReflectedAttributeCache.GetTypeFilterAttributes(ControllerType);\n            }\n            return base.GetFilterAttributes(useCache);\n        }\n\n        public override bool IsDefined(Type attributeType, bool inherit)\n        {\n            return ControllerType.IsDefined(attributeType, inherit);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Async/SimpleAsyncResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\n\nnamespace System.Web.Mvc.Async\n{\n    internal sealed class SimpleAsyncResult : IAsyncResult\n    {\n        private readonly object _asyncState;\n        private bool _completedSynchronously;\n        private volatile bool _isCompleted;\n\n        public SimpleAsyncResult(object asyncState)\n        {\n            _asyncState = asyncState;\n        }\n\n        public object AsyncState\n        {\n            get { return _asyncState; }\n        }\n\n        // ASP.NET IAsyncResult objects should never expose a WaitHandle due to potential deadlocking\n        public WaitHandle AsyncWaitHandle\n        {\n            get { return null; }\n        }\n\n        public bool CompletedSynchronously\n        {\n            get { return _completedSynchronously; }\n        }\n\n        public bool IsCompleted\n        {\n            get { return _isCompleted; }\n        }\n\n        // Proper order of execution:\n        // 1. Set the CompletedSynchronously property to the correct value\n        // 2. Set the IsCompleted flag\n        // 3. Execute the callback\n        // 4. Signal the WaitHandle (which we don't have)\n        public void MarkCompleted(bool completedSynchronously, AsyncCallback callback)\n        {\n            _completedSynchronously = completedSynchronously;\n            _isCompleted = true;\n\n            if (callback != null)\n            {\n                callback(this);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Async/SingleEntryGate.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\n\nnamespace System.Web.Mvc.Async\n{\n    // used to synchronize access to a single-use consumable resource\n    internal sealed class SingleEntryGate\n    {\n        private const int NotEntered = 0;\n        private const int Entered = 1;\n\n        private int _status;\n\n        // returns true if this is the first call to TryEnter(), false otherwise\n        public bool TryEnter()\n        {\n            int oldStatus = Interlocked.Exchange(ref _status, Entered);\n            return (oldStatus == NotEntered);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Async/SynchronizationContextUtil.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Threading;\n\nnamespace System.Web.Mvc.Async\n{\n    internal static class SynchronizationContextUtil\n    {\n        public static SynchronizationContext GetSynchronizationContext()\n        {\n            // In a runtime environment, SynchronizationContext.Current will be set to an instance\n            // of AspNetSynchronizationContext. In a unit test environment, the Current property\n            // won't be set and we have to create one on the fly.\n            return SynchronizationContext.Current ?? new SynchronizationContext();\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"The exception is swallowed and immediately re-thrown\")]\n        public static T Sync<T>(this SynchronizationContext syncContext, Func<T> func)\n        {\n            T theValue = default(T);\n            Exception thrownException = null;\n\n            syncContext.Send(o =>\n            {\n                try\n                {\n                    theValue = func();\n                }\n                catch (Exception ex)\n                {\n                    // by default, the AspNetSynchronizationContext type will swallow thrown exceptions,\n                    // so we need to save and propagate them\n                    thrownException = ex;\n                }\n            }, null);\n\n            if (thrownException != null)\n            {\n                throw Error.SynchronizationContextUtil_ExceptionThrown(thrownException);\n            }\n            return theValue;\n        }\n\n        public static void Sync(this SynchronizationContext syncContext, Action action)\n        {\n            Sync<AsyncVoid>(syncContext, () =>\n            {\n                action();\n                return default(AsyncVoid);\n            });\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Async/SynchronousOperationException.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Runtime.Serialization;\n\nnamespace System.Web.Mvc.Async\n{\n    // This exception type is thrown by the SynchronizationContextUtil helper class since the AspNetSynchronizationContext\n    // type swallows exceptions. The inner exception contains the data the user cares about.\n\n    [Serializable]\n    public sealed class SynchronousOperationException : HttpException\n    {\n        public SynchronousOperationException()\n        {\n        }\n\n        private SynchronousOperationException(SerializationInfo info, StreamingContext context)\n            : base(info, context)\n        {\n        }\n\n        public SynchronousOperationException(string message)\n            : base(message)\n        {\n        }\n\n        public SynchronousOperationException(string message, Exception innerException)\n            : base(message, innerException)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Async/TaskAsyncActionDescriptor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq;\nusing System.Linq.Expressions;\nusing System.Reflection;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc.Async\n{\n    /// <summary>\n    /// When an action method returns either Task or Task{T} the TaskAsyncActionDescriptor provides information about the action.\n    /// </summary>\n    public class TaskAsyncActionDescriptor : AsyncActionDescriptor, IMethodInfoActionDescriptor\n    {\n        /// <summary>\n        /// dictionary to hold methods that can read Task{T}.Result\n        /// </summary>\n        private static readonly ConcurrentDictionary<Type, Func<object, object>> _taskValueExtractors = new ConcurrentDictionary<Type, Func<object, object>>();\n        private readonly string _actionName;\n        private readonly ControllerDescriptor _controllerDescriptor;\n        private readonly Lazy<string> _uniqueId;\n        private ParameterDescriptor[] _parametersCache;\n\n        public TaskAsyncActionDescriptor(MethodInfo taskMethodInfo, string actionName, ControllerDescriptor controllerDescriptor)\n            : this(taskMethodInfo, actionName, controllerDescriptor, validateMethod: true)\n        {\n        }\n\n        internal TaskAsyncActionDescriptor(MethodInfo taskMethodInfo, string actionName, ControllerDescriptor controllerDescriptor, bool validateMethod)\n        {\n            if (taskMethodInfo == null)\n            {\n                throw new ArgumentNullException(\"taskMethodInfo\");\n            }\n            if (String.IsNullOrEmpty(actionName))\n            {\n                throw Error.ParameterCannotBeNullOrEmpty(\"actionName\");\n            }\n            if (controllerDescriptor == null)\n            {\n                throw new ArgumentNullException(\"controllerDescriptor\");\n            }\n\n            if (validateMethod)\n            {\n                string taskFailedMessage = VerifyActionMethodIsCallable(taskMethodInfo);\n                if (taskFailedMessage != null)\n                {\n                    throw new ArgumentException(taskFailedMessage, \"taskMethodInfo\");\n                }\n            }\n\n            TaskMethodInfo = taskMethodInfo;\n            _actionName = actionName;\n            _controllerDescriptor = controllerDescriptor;\n            _uniqueId = new Lazy<string>(CreateUniqueId);\n        }\n\n        public override string ActionName\n        {\n            get { return _actionName; }\n        }\n\n        public MethodInfo TaskMethodInfo { get; private set; }\n\n        public override ControllerDescriptor ControllerDescriptor\n        {\n            get { return _controllerDescriptor; }\n        }\n\n        public MethodInfo MethodInfo\n        {\n            get { return TaskMethodInfo; }\n        }\n\n        public override string UniqueId\n        {\n            get { return _uniqueId.Value; }\n        }\n\n        private string CreateUniqueId()\n        {\n            var builder = new StringBuilder(base.UniqueId);\n            DescriptorUtil.AppendUniqueId(builder, MethodInfo);\n            return builder.ToString();\n        }\n\n        [SuppressMessage(\"Microsoft.Web.FxCop\", \"MW1201:DoNotCallProblematicMethodsOnTask\", Justification = \"This is commented in great detail.\")]\n        public override IAsyncResult BeginExecute(ControllerContext controllerContext, IDictionary<string, object> parameters, AsyncCallback callback, object state)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n            if (parameters == null)\n            {\n                throw new ArgumentNullException(\"parameters\");\n            }\n\n            ParameterInfo[] parameterInfos = TaskMethodInfo.GetParameters();\n            var rawParameterValues = from parameterInfo in parameterInfos\n                                     select ExtractParameterFromDictionary(parameterInfo, parameters, TaskMethodInfo);\n            object[] parametersArray = rawParameterValues.ToArray();\n\n            CancellationTokenSource tokenSource = null;\n            bool disposedTimer = false;\n            Timer taskCancelledTimer = null;\n            bool taskCancelledTimerRequired = false;\n\n            int timeout = GetAsyncManager(controllerContext.Controller).Timeout;\n\n            for (int i = 0; i < parametersArray.Length; i++)\n            {\n                if (default(CancellationToken).Equals(parametersArray[i]))\n                {\n                    tokenSource = new CancellationTokenSource();\n                    parametersArray[i] = tokenSource.Token;\n\n                    // If there is a timeout we will create a timer to cancel the task when the\n                    // timeout expires.\n                    taskCancelledTimerRequired = timeout > Timeout.Infinite;\n                    break;\n                }\n            }\n\n            ActionMethodDispatcher dispatcher = DispatcherCache.GetDispatcher(TaskMethodInfo);\n\n            if (taskCancelledTimerRequired)\n            {\n                taskCancelledTimer = new Timer(_ =>\n                {\n                    lock (tokenSource)\n                    {\n                        if (!disposedTimer)\n                        {\n                            tokenSource.Cancel();\n                        }\n                    }\n                }, state: null, dueTime: timeout, period: Timeout.Infinite);\n            }\n\n            Task taskUser = dispatcher.Execute(controllerContext.Controller, parametersArray) as Task;\n            Action cleanupAtEndExecute = () =>\n            {\n                // Cleanup code that's run in EndExecute, after we've waited on the task value.\n\n                if (taskCancelledTimer != null)\n                {\n                    // Timer callback may still fire after Dispose is called.\n                    taskCancelledTimer.Dispose();\n                }\n\n                if (tokenSource != null)\n                {\n                    lock (tokenSource)\n                    {\n                        disposedTimer = true;\n                        tokenSource.Dispose();\n                        if (tokenSource.IsCancellationRequested)\n                        {\n                            // Give Timeout exceptions higher priority over other exceptions, mainly OperationCancelled exceptions\n                            // that were signaled with out timeout token.\n                            throw new TimeoutException();\n                        }\n                    }\n                }\n            };\n\n            TaskWrapperAsyncResult result = new TaskWrapperAsyncResult(taskUser, state, cleanupAtEndExecute);\n\n            // if user supplied a callback, invoke that when their task has finished running.\n            if (callback != null)\n            {\n                if (taskUser.IsCompleted)\n                {\n                    // If the underlying task is already finished, from our caller's perspective this is just\n                    // a synchronous completion.\n                    result.CompletedSynchronously = true;\n                    callback(result);\n                }\n                else\n                {\n                    // If the underlying task isn't yet finished, from our caller's perspective this will be\n                    // an asynchronous completion. We'll use ContinueWith instead of Finally for two reasons:\n                    //\n                    // - Finally propagates the antecedent Task's exception, which we don't need to do here.\n                    //   Out caller will eventually call EndExecute, which correctly observes the\n                    //   antecedent Task's exception anyway if it faulted.\n                    //\n                    // - Finally invokes the callback on the captured SynchronizationContext, which is\n                    //   unnecessary when using APM (Begin / End). APM assumes that the callback is invoked\n                    //   on an arbitrary ThreadPool thread with no SynchronizationContext set up, so\n                    //   ContinueWith gets us closer to the desired semantic.\n                    result.CompletedSynchronously = false;\n                    taskUser.ContinueWith(_ =>\n                    {\n                        callback(result);\n                    });\n                }\n            }\n\n            return result;\n        }\n\n        public override object Execute(ControllerContext controllerContext, IDictionary<string, object> parameters)\n        {\n            string errorMessage = String.Format(CultureInfo.CurrentCulture, MvcResources.TaskAsyncActionDescriptor_CannotExecuteSynchronously,\n                                                ActionName);\n\n            throw new InvalidOperationException(errorMessage);\n        }\n\n        public override object EndExecute(IAsyncResult asyncResult)\n        {\n            TaskWrapperAsyncResult wrapperResult = (TaskWrapperAsyncResult)asyncResult;\n\n            // Throw an exception with the correct call stack\n            try\n            {\n                wrapperResult.Task.ThrowIfFaulted();\n            }\n            finally\n            {\n                if (wrapperResult.CleanupThunk != null)\n                {\n                    wrapperResult.CleanupThunk();\n                }\n            }\n\n            // Extract the result of the task if there is a result\n            return _taskValueExtractors.GetOrAdd(TaskMethodInfo.ReturnType, CreateTaskValueExtractor)(wrapperResult.Task);\n        }\n\n        private static Func<object, object> CreateTaskValueExtractor(Type taskType)\n        {\n            // Task<T>?\n            if (taskType.IsGenericType && taskType.GetGenericTypeDefinition() == typeof(Task<>))\n            {\n                // lambda = arg => (object)(((Task<T>)arg).Result)\n                var arg = Expression.Parameter(typeof(object));\n                var castArg = Expression.Convert(arg, taskType);\n                var fieldAccess = Expression.Property(castArg, \"Result\");\n                var castResult = Expression.Convert(fieldAccess, typeof(object));\n                var lambda = Expression.Lambda<Func<object, object>>(castResult, arg);\n                return lambda.Compile();\n            }\n\n            // Any exceptions should be thrown before getting the task value so just return null.\n            return theTask =>\n            {\n                return null;\n            };\n        }\n\n        public override object[] GetCustomAttributes(bool inherit)\n        {\n            return ActionDescriptorHelper.GetCustomAttributes(TaskMethodInfo, inherit);\n        }\n\n        public override object[] GetCustomAttributes(Type attributeType, bool inherit)\n        {\n            return ActionDescriptorHelper.GetCustomAttributes(TaskMethodInfo, attributeType, inherit);\n        }\n\n        public override ParameterDescriptor[] GetParameters()\n        {\n            return ActionDescriptorHelper.GetParameters(this, TaskMethodInfo, ref _parametersCache);\n        }\n\n        public override ICollection<ActionSelector> GetSelectors()\n        {\n            return ActionDescriptorHelper.GetSelectors(TaskMethodInfo);\n        }\n\n        internal override ICollection<ActionNameSelector> GetNameSelectors()\n        {\n            return ActionDescriptorHelper.GetNameSelectors(TaskMethodInfo);\n        }\n\n        public override bool IsDefined(Type attributeType, bool inherit)\n        {\n            return ActionDescriptorHelper.IsDefined(TaskMethodInfo, attributeType, inherit);\n        }\n\n        public override IEnumerable<FilterAttribute> GetFilterAttributes(bool useCache)\n        {\n            if (useCache && GetType() == typeof(TaskAsyncActionDescriptor))\n            {\n                // Do not look at cache in types derived from this type because they might incorrectly implement GetCustomAttributes\n                return ReflectedAttributeCache.GetMethodFilterAttributes(TaskMethodInfo);\n            }\n            return base.GetFilterAttributes(useCache);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Async/TaskWrapperAsyncResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Mvc.Async\n{\n    /// <summary>\n    /// Wraps a <see cref=\"Task\"/> class, optionally overriding the State object (since the Task Asynchronous Pattern doesn't normally use it).\n    /// Copied from System.Web.\n    /// </summary>\n    internal sealed class TaskWrapperAsyncResult : IAsyncResult\n    {\n        private bool? _completedSynchronously;\n\n        internal TaskWrapperAsyncResult(Task task, object asyncState, Action cleanupThunk = null)\n        {\n            Task = task;\n            AsyncState = asyncState;\n            CleanupThunk = cleanupThunk;\n        }\n\n        public object AsyncState { get; private set; }\n\n        public WaitHandle AsyncWaitHandle\n        {\n            get { return ((IAsyncResult)Task).AsyncWaitHandle; }\n        }\n\n        /// <summary>\n        /// Cleanup logic to run after Task is finished\n        /// </summary>\n        public Action CleanupThunk { get; private set; }\n\n        /// <summary>\n        /// Gets a value indicating whether the asynchronous operation completed synchronously.\n        /// </summary>\n        /// <returns>true if the asynchronous operation completed synchronously; otherwise, false.</returns>\n        public bool CompletedSynchronously\n        {\n            get { return _completedSynchronously ?? ((IAsyncResult)Task).CompletedSynchronously; }\n            internal set { _completedSynchronously = value; }\n        }\n\n        public bool IsCompleted\n        {\n            get { return ((IAsyncResult)Task).IsCompleted; }\n        }\n\n        internal Task Task { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Async/Trigger.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc.Async\n{\n    // Provides a trigger for the TriggerListener class.\n\n    internal sealed class Trigger\n    {\n        private readonly Action _fireAction;\n\n        // Constructor should only be called by TriggerListener.\n        internal Trigger(Action fireAction)\n        {\n            _fireAction = fireAction;\n        }\n\n        public void Fire()\n        {\n            _fireAction();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Async/TriggerListener.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\n\nnamespace System.Web.Mvc.Async\n{\n    // This class is used to wait for triggers and a continuation. When the continuation has been provded\n    // and all triggers have been fired, the continuation is called. Similar to WaitHandle.WaitAll().\n    // New instances of this type are initially in the inactive state; activation is enabled by a call\n    // to Activate().\n\n    // This class is thread-safe.\n\n    internal sealed class TriggerListener\n    {\n        private readonly Trigger _activateTrigger;\n        private readonly SingleEntryGate _continuationFiredGate = new SingleEntryGate();\n        private readonly Trigger _setContinuationTrigger;\n        private volatile Action _continuation;\n        private int _outstandingTriggers;\n\n        public TriggerListener()\n        {\n            _activateTrigger = CreateTrigger();\n            _setContinuationTrigger = CreateTrigger();\n        }\n\n        public void Activate()\n        {\n            _activateTrigger.Fire();\n        }\n\n        public Trigger CreateTrigger()\n        {\n            Interlocked.Increment(ref _outstandingTriggers);\n\n            SingleEntryGate triggerFiredGate = new SingleEntryGate();\n            return new Trigger(() =>\n            {\n                if (triggerFiredGate.TryEnter())\n                {\n                    HandleTriggerFired();\n                }\n            });\n        }\n\n        private void HandleTriggerFired()\n        {\n            if (Interlocked.Decrement(ref _outstandingTriggers) == 0)\n            {\n                if (_continuationFiredGate.TryEnter())\n                {\n                    _continuation();\n                }\n            }\n        }\n\n        public void SetContinuation(Action continuation)\n        {\n            if (continuation != null)\n            {\n                _continuation = continuation;\n                _setContinuationTrigger.Fire();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/AsyncController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    // Controller now supports asynchronous operations.\n    // This class only exists \n    // a) for backwards compat for callers that derive from it,\n    // b) ActionMethodSelector can detect it to bind to ActionAsync/ActionCompleted patterns. \n    public abstract class AsyncController : Controller\n    {\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/AsyncTimeoutAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Mvc.Async;\n\nnamespace System.Web.Mvc\n{\n    [SuppressMessage(\"Microsoft.Performance\", \"CA1813:AvoidUnsealedAttributes\", Justification = \"Unsealed so that subclassed types can set properties in the default constructor.\")]\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\n    public class AsyncTimeoutAttribute : ActionFilterAttribute\n    {\n        // duration is specified in milliseconds\n        public AsyncTimeoutAttribute(int duration)\n        {\n            if (duration < -1)\n            {\n                throw Error.AsyncCommon_InvalidTimeout(\"duration\");\n            }\n\n            Duration = duration;\n        }\n\n        public int Duration { get; private set; }\n\n        public override void OnActionExecuting(ActionExecutingContext filterContext)\n        {\n            if (filterContext == null)\n            {\n                throw new ArgumentNullException(\"filterContext\");\n            }\n\n            IAsyncManagerContainer container = filterContext.Controller as IAsyncManagerContainer;\n            if (container == null)\n            {\n                throw Error.AsyncCommon_ControllerMustImplementIAsyncManagerContainer(filterContext.Controller.GetType());\n            }\n\n            container.AsyncManager.Timeout = Duration;\n\n            base.OnActionExecuting(filterContext);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/AuthorizationContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.Mvc\n{\n    public class AuthorizationContext : ControllerContext\n    {\n        // parameterless constructor used for mocking\n        public AuthorizationContext()\n        {\n        }\n\n        [Obsolete(\"The recommended alternative is the constructor AuthorizationContext(ControllerContext controllerContext, ActionDescriptor actionDescriptor).\")]\n        public AuthorizationContext(ControllerContext controllerContext)\n            : base(controllerContext)\n        {\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2214:DoNotCallOverridableMethodsInConstructors\", Justification = \"The virtual property setters are only to support mocking frameworks, in which case this constructor shouldn't be called anyway.\")]\n        public AuthorizationContext(ControllerContext controllerContext, ActionDescriptor actionDescriptor)\n            : base(controllerContext)\n        {\n            if (actionDescriptor == null)\n            {\n                throw new ArgumentNullException(\"actionDescriptor\");\n            }\n\n            ActionDescriptor = actionDescriptor;\n        }\n\n        public virtual ActionDescriptor ActionDescriptor { get; set; }\n\n        public ActionResult Result { get; set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/AuthorizeAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Security.Principal;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    [SuppressMessage(\"Microsoft.Performance\", \"CA1813:AvoidUnsealedAttributes\", Justification = \"Unsealed so that subclassed types can set properties in the default constructor or override our behavior.\")]\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]\n    public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter\n    {\n        private static readonly char[] _splitParameter = new[] { ',' };\n        private readonly object _typeId = new object();\n\n        private string _roles;\n        private string[] _rolesSplit = new string[0];\n        private string _users;\n        private string[] _usersSplit = new string[0];\n\n        public string Roles\n        {\n            get { return _roles ?? String.Empty; }\n            set\n            {\n                _roles = value;\n                _rolesSplit = SplitString(value);\n            }\n        }\n\n        public override object TypeId\n        {\n            get { return _typeId; }\n        }\n\n        public string Users\n        {\n            get { return _users ?? String.Empty; }\n            set\n            {\n                _users = value;\n                _usersSplit = SplitString(value);\n            }\n        }\n\n        // This method must be thread-safe since it is called by the thread-safe OnCacheAuthorization() method.\n        protected virtual bool AuthorizeCore(HttpContextBase httpContext)\n        {\n            if (httpContext == null)\n            {\n                throw new ArgumentNullException(\"httpContext\");\n            }\n\n            IPrincipal user = httpContext.User;\n            if (!user.Identity.IsAuthenticated)\n            {\n                return false;\n            }\n\n            if (_usersSplit.Length > 0 && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase))\n            {\n                return false;\n            }\n\n            if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole))\n            {\n                return false;\n            }\n\n            return true;\n        }\n\n        private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus)\n        {\n            validationStatus = OnCacheAuthorization(new HttpContextWrapper(context));\n        }\n\n        public virtual void OnAuthorization(AuthorizationContext filterContext)\n        {\n            if (filterContext == null)\n            {\n                throw new ArgumentNullException(\"filterContext\");\n            }\n\n            if (OutputCacheAttribute.IsChildActionCacheActive(filterContext))\n            {\n                // If a child action cache block is active, we need to fail immediately, even if authorization\n                // would have succeeded. The reason is that there's no way to hook a callback to rerun\n                // authorization before the fragment is served from the cache, so we can't guarantee that this\n                // filter will be re-run on subsequent requests.\n                throw new InvalidOperationException(MvcResources.AuthorizeAttribute_CannotUseWithinChildActionCache);\n            }\n\n            bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true)\n                                     || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true);\n\n            if (skipAuthorization)\n            {\n                return;\n            }\n\n            if (AuthorizeCore(filterContext.HttpContext))\n            {\n                // ** IMPORTANT **\n                // Since we're performing authorization at the action level, the authorization code runs\n                // after the output caching module. In the worst case this could allow an authorized user\n                // to cause the page to be cached, then an unauthorized user would later be served the\n                // cached page. We work around this by telling proxies not to cache the sensitive page,\n                // then we hook our custom authorization code into the caching mechanism so that we have\n                // the final say on whether a page should be served from the cache.\n\n                HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;\n                cachePolicy.SetProxyMaxAge(new TimeSpan(0));\n                cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);\n            }\n            else\n            {\n                HandleUnauthorizedRequest(filterContext);\n            }\n        }\n\n        protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext)\n        {\n            // Returns HTTP 401 - see comment in HttpUnauthorizedResult.cs.\n            filterContext.Result = new HttpUnauthorizedResult();\n        }\n\n        // This method must be thread-safe since it is called by the caching module.\n        protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext)\n        {\n            if (httpContext == null)\n            {\n                throw new ArgumentNullException(\"httpContext\");\n            }\n\n            bool isAuthorized = AuthorizeCore(httpContext);\n            return (isAuthorized) ? HttpValidationStatus.Valid : HttpValidationStatus.IgnoreThisRequest;\n        }\n\n        internal static string[] SplitString(string original)\n        {\n            if (String.IsNullOrEmpty(original))\n            {\n                return new string[0];\n            }\n\n            var split = from piece in original.Split(_splitParameter)\n                        let trimmed = piece.Trim()\n                        where !String.IsNullOrEmpty(trimmed)\n                        select trimmed;\n            return split.ToArray();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/BindAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace System.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]\n    public sealed class BindAttribute : Attribute\n    {\n        private string _exclude;\n        private string[] _excludeSplit = new string[0];\n        private string _include;\n        private string[] _includeSplit = new string[0];\n\n        public string Exclude\n        {\n            get { return _exclude ?? String.Empty; }\n            set\n            {\n                _exclude = value;\n                _excludeSplit = AuthorizeAttribute.SplitString(value);\n            }\n        }\n\n        public string Include\n        {\n            get { return _include ?? String.Empty; }\n            set\n            {\n                _include = value;\n                _includeSplit = AuthorizeAttribute.SplitString(value);\n            }\n        }\n\n        public string Prefix { get; set; }\n\n        internal static bool IsPropertyAllowed(string propertyName, ICollection<string> includeProperties, ICollection<string> excludeProperties)\n        {\n            // We allow a property to be bound if its both in the include list AND not in the exclude list.\n            // An empty include list implies all properties are allowed.\n            // An empty exclude list implies no properties are disallowed.\n            bool includeProperty = (includeProperties == null) || (includeProperties.Count == 0) || includeProperties.Contains(propertyName, StringComparer.OrdinalIgnoreCase);\n            bool excludeProperty = (excludeProperties != null) && excludeProperties.Contains(propertyName, StringComparer.OrdinalIgnoreCase);\n            return includeProperty && !excludeProperty;\n        }\n\n        public bool IsPropertyAllowed(string propertyName)\n        {\n            return IsPropertyAllowed(propertyName, _includeSplit, _excludeSplit);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/BuildManagerCompiledView.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.IO;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    public abstract class BuildManagerCompiledView : IView\n    {\n        internal IViewPageActivator ViewPageActivator;\n        private IBuildManager _buildManager;\n        private ControllerContext _controllerContext;\n\n        protected BuildManagerCompiledView(ControllerContext controllerContext, string viewPath)\n            : this(controllerContext, viewPath, null)\n        {\n        }\n\n        protected BuildManagerCompiledView(ControllerContext controllerContext, string viewPath, IViewPageActivator viewPageActivator)\n            : this(controllerContext, viewPath, viewPageActivator, null)\n        {\n        }\n\n        internal BuildManagerCompiledView(ControllerContext controllerContext, string viewPath, IViewPageActivator viewPageActivator, IDependencyResolver dependencyResolver)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n            if (String.IsNullOrEmpty(viewPath))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"viewPath\");\n            }\n\n            _controllerContext = controllerContext;\n\n            ViewPath = viewPath;\n\n            ViewPageActivator = viewPageActivator ?? new BuildManagerViewEngine.DefaultViewPageActivator(dependencyResolver);\n        }\n\n        internal IBuildManager BuildManager\n        {\n            get\n            {\n                if (_buildManager == null)\n                {\n                    _buildManager = new BuildManagerWrapper();\n                }\n                return _buildManager;\n            }\n            set { _buildManager = value; }\n        }\n\n        public string ViewPath { get; protected set; }\n\n        public virtual void Render(ViewContext viewContext, TextWriter writer)\n        {\n            if (viewContext == null)\n            {\n                throw new ArgumentNullException(\"viewContext\");\n            }\n\n            object instance = null;\n\n            Type type = BuildManager.GetCompiledType(ViewPath);\n            if (type != null)\n            {\n                instance = ViewPageActivator.Create(_controllerContext, type);\n            }\n\n            if (instance == null)\n            {\n                throw new InvalidOperationException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.CshtmlView_ViewCouldNotBeCreated,\n                        ViewPath));\n            }\n\n            RenderView(viewContext, writer, instance);\n        }\n\n        protected abstract void RenderView(ViewContext viewContext, TextWriter writer, object instance);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/BuildManagerViewEngine.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Threading;\nusing System.Web.Hosting;\nusing System.Web.WebPages;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Mvc\n{\n    public abstract class BuildManagerViewEngine : VirtualPathProviderViewEngine\n    {\n        private static object _isPrecompiledNonUpdateableSiteInitializedLock = new object();\n        private static bool _isPrecompiledNonUpdateableSite;\n        private static bool _isPrecompiledNonUpdateableSiteInitialized;\n        private static FileExistenceCache _sharedFileExistsCache;\n\n        private IBuildManager _buildManager;\n        private IViewPageActivator _viewPageActivator;\n        private IResolver<IViewPageActivator> _activatorResolver;\n        private FileExistenceCache _fileExistsCache;\n\n        protected BuildManagerViewEngine()\n            : this(null, null, null, null)\n        {\n        }\n\n        protected BuildManagerViewEngine(IViewPageActivator viewPageActivator)\n            : this(viewPageActivator, null, null, null)\n        {\n        }\n\n        internal BuildManagerViewEngine(IViewPageActivator viewPageActivator, IResolver<IViewPageActivator> activatorResolver,\n            IDependencyResolver dependencyResolver, VirtualPathProvider pathProvider)\n        {\n            if (viewPageActivator != null)\n            {\n                _viewPageActivator = viewPageActivator;\n            }\n            else\n            {\n                _activatorResolver = activatorResolver ?? new SingleServiceResolver<IViewPageActivator>(\n                                                              () => null,\n                                                              new DefaultViewPageActivator(dependencyResolver),\n                                                              \"BuildManagerViewEngine constructor\");\n            }\n\n            if (pathProvider != null)\n            {\n                Func<VirtualPathProvider> providerFunc = () => pathProvider;\n                _fileExistsCache = new FileExistenceCache(providerFunc);\n                VirtualPathProviderFunc = providerFunc;\n            }\n            else\n            {\n                if (_sharedFileExistsCache == null)\n                {\n                    // Startup initialization race is OK providing service remains read-only\n                    _sharedFileExistsCache = new FileExistenceCache(() => HostingEnvironment.VirtualPathProvider);\n                }\n\n                _fileExistsCache = _sharedFileExistsCache;\n            }\n        }\n\n        internal IBuildManager BuildManager\n        {\n            get\n            {\n                if (_buildManager == null)\n                {\n                    _buildManager = new BuildManagerWrapper();\n                }\n                return _buildManager;\n            }\n            set { _buildManager = value; }\n        }\n\n        protected IViewPageActivator ViewPageActivator\n        {\n            get\n            {\n                if (_viewPageActivator != null)\n                {\n                    return _viewPageActivator;\n                }\n                _viewPageActivator = _activatorResolver.Current;\n                return _viewPageActivator;\n            }\n        }\n\n        protected virtual bool IsPrecompiledNonUpdateableSite\n        {\n            get\n            {\n                return LazyInitializer.EnsureInitialized(ref _isPrecompiledNonUpdateableSite,\n                                                         ref _isPrecompiledNonUpdateableSiteInitialized,\n                                                         ref _isPrecompiledNonUpdateableSiteInitializedLock,\n                                                         GetPrecompiledNonUpdateable);\n            }\n        }\n\n        protected override bool FileExists(ControllerContext controllerContext, string virtualPath)\n        {\n            // When dealing with non-updateable precompiled views, the view files may not exist on disk. The correct\n            // way to check for existence of a file in this case is by querying the BuildManager.\n            // For all other scenarios, checking for files on disk is faster and should suffice.\n            Contract.Assert(_fileExistsCache != null);\n            return _fileExistsCache.FileExists(virtualPath) ||\n                   (IsPrecompiledNonUpdateableSite && BuildManager.FileExists(virtualPath));\n        }\n\n        private static bool GetPrecompiledNonUpdateable()\n        {\n            IVirtualPathUtility virtualPathUtility = new VirtualPathUtilityWrapper();\n            return WebPages.BuildManagerWrapper.IsNonUpdateablePrecompiledApp(HostingEnvironment.VirtualPathProvider,\n                                                                              virtualPathUtility);\n        }\n\n        internal class DefaultViewPageActivator : IViewPageActivator\n        {\n            private Func<IDependencyResolver> _resolverThunk;\n\n            public DefaultViewPageActivator()\n                : this(null)\n            {\n            }\n\n            public DefaultViewPageActivator(IDependencyResolver resolver)\n            {\n                if (resolver == null)\n                {\n                    _resolverThunk = () => DependencyResolver.Current;\n                }\n                else\n                {\n                    _resolverThunk = () => resolver;\n                }\n            }\n\n            public object Create(ControllerContext controllerContext, Type type)\n            {\n                try\n                {\n                    return _resolverThunk().GetService(type) ?? Activator.CreateInstance(type);\n                }\n                catch (MissingMethodException exception)\n                {\n                    // Ensure thrown exception contains the type name.  Might be down a few levels.\n                    MissingMethodException replacementException =\n                        TypeHelpers.EnsureDebuggableException(exception, type.FullName);\n                    if (replacementException != null)\n                    {\n                        throw replacementException;\n                    }\n\n                    throw;\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/BuildManagerWrapper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.IO;\nusing System.Web.Compilation;\n\nnamespace System.Web.Mvc\n{\n    internal sealed class BuildManagerWrapper : IBuildManager\n    {\n        bool IBuildManager.FileExists(string virtualPath)\n        {\n            return BuildManager.GetObjectFactory(virtualPath, throwIfNotFound: false) != null;\n        }\n\n        Type IBuildManager.GetCompiledType(string virtualPath)\n        {\n            return BuildManager.GetCompiledType(virtualPath);\n        }\n\n        ICollection IBuildManager.GetReferencedAssemblies()\n        {\n            return BuildManager.GetReferencedAssemblies();\n        }\n\n        Stream IBuildManager.ReadCachedFile(string fileName)\n        {\n            return BuildManager.ReadCachedFile(fileName);\n        }\n\n        Stream IBuildManager.CreateCachedFile(string fileName)\n        {\n            return BuildManager.CreateCachedFile(fileName);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ByteArrayModelBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public class ByteArrayModelBinder : IModelBinder\n    {\n        public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)\n        {\n            if (bindingContext == null)\n            {\n                throw new ArgumentNullException(\"bindingContext\");\n            }\n\n            ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);\n\n            // case 1: there was no <input ... /> element containing this data\n            if (valueResult == null)\n            {\n                return null;\n            }\n\n            string value = valueResult.AttemptedValue;\n\n            // case 2: there was an <input ... /> element but it was left blank\n            if (String.IsNullOrEmpty(value))\n            {\n                return null;\n            }\n\n            // Future proofing. If the byte array is actually an instance of System.Data.Linq.Binary\n            // then we need to remove these quotes put in place by the ToString() method.\n            string realValue = value.Replace(\"\\\"\", String.Empty);\n            return Convert.FromBase64String(realValue);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/CachedAssociatedMetadataProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Runtime.Caching;\n\nnamespace System.Web.Mvc\n{\n    public abstract class CachedAssociatedMetadataProvider<TModelMetadata> : AssociatedMetadataProvider\n        where TModelMetadata : ModelMetadata\n    {\n        private static ConcurrentDictionary<Type, string> _typeIds = new ConcurrentDictionary<Type, string>();\n        private string _cacheKeyPrefix;\n        private CacheItemPolicy _cacheItemPolicy = new CacheItemPolicy { SlidingExpiration = TimeSpan.FromMinutes(20) };\n        private ObjectCache _prototypeCache;\n\n        protected internal CacheItemPolicy CacheItemPolicy\n        {\n            get { return _cacheItemPolicy; }\n            set { _cacheItemPolicy = value; }\n        }\n\n        protected string CacheKeyPrefix\n        {\n            get\n            {\n                if (_cacheKeyPrefix == null)\n                {\n                    _cacheKeyPrefix = \"MetadataPrototypes::\" + GetType().GUID.ToString(\"B\");\n                }\n                return _cacheKeyPrefix;\n            }\n        }\n\n        protected internal ObjectCache PrototypeCache\n        {\n            get { return _prototypeCache ?? MemoryCache.Default; }\n            set { _prototypeCache = value; }\n        }\n\n        protected sealed override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)\n        {\n            // If metadata is being created for a property then containerType != null && propertyName != null\n            // If metadata is being created for a type then containerType == null && propertyName == null, so we have to use modelType for the cache key.\n            Type typeForCache = containerType ?? modelType;\n            string cacheKey = GetCacheKey(typeForCache, propertyName);\n            TModelMetadata prototype = PrototypeCache.Get(cacheKey) as TModelMetadata;\n            if (prototype == null)\n            {\n                prototype = CreateMetadataPrototype(attributes, containerType, modelType, propertyName);\n                PrototypeCache.Add(cacheKey, prototype, CacheItemPolicy);\n            }\n\n            return CreateMetadataFromPrototype(prototype, modelAccessor);\n        }\n\n        // New override for creating the prototype metadata (without the accessor)\n        protected abstract TModelMetadata CreateMetadataPrototype(IEnumerable<Attribute> attributes, Type containerType, Type modelType, string propertyName);\n\n        // New override for applying the prototype + modelAccess to yield the final metadata\n        protected abstract TModelMetadata CreateMetadataFromPrototype(TModelMetadata prototype, Func<object> modelAccessor);\n\n        internal string GetCacheKey(Type type, string propertyName = null)\n        {\n            propertyName = propertyName ?? String.Empty;\n            return CacheKeyPrefix + GetTypeId(type) + propertyName;\n        }\n\n        public sealed override ModelMetadata GetMetadataForProperty(Func<object> modelAccessor, Type containerType, string propertyName)\n        {\n            return base.GetMetadataForProperty(modelAccessor, containerType, propertyName);\n        }\n\n        protected sealed override ModelMetadata GetMetadataForProperty(Func<object> modelAccessor, Type containerType, PropertyDescriptor propertyDescriptor)\n        {\n            return base.GetMetadataForProperty(modelAccessor, containerType, propertyDescriptor);\n        }\n\n        public sealed override IEnumerable<ModelMetadata> GetMetadataForProperties(object container, Type containerType)\n        {\n            return base.GetMetadataForProperties(container, containerType);\n        }\n\n        public sealed override ModelMetadata GetMetadataForType(Func<object> modelAccessor, Type modelType)\n        {\n            return base.GetMetadataForType(modelAccessor, modelType);\n        }\n\n        private static string GetTypeId(Type type)\n        {\n            // It's fine using a random Guid since we store the mapping for types to guids.\n            return _typeIds.GetOrAdd(type, _ => Guid.NewGuid().ToString(\"B\"));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/CachedDataAnnotationsMetadataAttributes.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\n\nnamespace System.Web.Mvc\n{\n    public class CachedDataAnnotationsMetadataAttributes\n    {\n        public CachedDataAnnotationsMetadataAttributes(Attribute[] attributes)\n        {\n            DataType = attributes.OfType<DataTypeAttribute>().FirstOrDefault();\n            Display = attributes.OfType<DisplayAttribute>().FirstOrDefault();\n            DisplayColumn = attributes.OfType<DisplayColumnAttribute>().FirstOrDefault();\n            DisplayFormat = attributes.OfType<DisplayFormatAttribute>().FirstOrDefault();\n            DisplayName = attributes.OfType<DisplayNameAttribute>().FirstOrDefault();\n            Editable = attributes.OfType<EditableAttribute>().FirstOrDefault();\n            HiddenInput = attributes.OfType<HiddenInputAttribute>().FirstOrDefault();\n            ReadOnly = attributes.OfType<ReadOnlyAttribute>().FirstOrDefault();\n            Required = attributes.OfType<RequiredAttribute>().FirstOrDefault();\n            ScaffoldColumn = attributes.OfType<ScaffoldColumnAttribute>().FirstOrDefault();\n\n            var uiHintAttributes = attributes.OfType<UIHintAttribute>();\n            UIHint = uiHintAttributes.FirstOrDefault(a => String.Equals(a.PresentationLayer, \"MVC\", StringComparison.OrdinalIgnoreCase))\n                     ?? uiHintAttributes.FirstOrDefault(a => String.IsNullOrEmpty(a.PresentationLayer));\n\n            if (DisplayFormat == null && DataType != null)\n            {\n                DisplayFormat = DataType.DisplayFormat;\n            }\n        }\n\n        public DataTypeAttribute DataType { get; protected set; }\n\n        public DisplayAttribute Display { get; protected set; }\n\n        public DisplayColumnAttribute DisplayColumn { get; protected set; }\n\n        public DisplayFormatAttribute DisplayFormat { get; protected set; }\n\n        public DisplayNameAttribute DisplayName { get; protected set; }\n\n        public EditableAttribute Editable { get; protected set; }\n\n        public HiddenInputAttribute HiddenInput { get; protected set; }\n\n        public ReadOnlyAttribute ReadOnly { get; protected set; }\n\n        public RequiredAttribute Required { get; protected set; }\n\n        public ScaffoldColumnAttribute ScaffoldColumn { get; protected set; }\n\n        public UIHintAttribute UIHint { get; protected set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/CachedDataAnnotationsModelMetadata.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Globalization;\nusing System.Linq;\nusing System.Reflection;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    public class CachedDataAnnotationsModelMetadata : CachedModelMetadata<CachedDataAnnotationsMetadataAttributes>\n    {\n        private bool _isEditFormatStringFromCache;\n\n        public CachedDataAnnotationsModelMetadata(CachedDataAnnotationsModelMetadata prototype, Func<object> modelAccessor)\n            : base(prototype, modelAccessor)\n        {\n        }\n\n        public CachedDataAnnotationsModelMetadata(CachedDataAnnotationsModelMetadataProvider provider, Type containerType, Type modelType, string propertyName, IEnumerable<Attribute> attributes)\n            : base(provider, containerType, modelType, propertyName, new CachedDataAnnotationsMetadataAttributes(attributes.ToArray()))\n        {\n        }\n\n        protected override bool ComputeConvertEmptyStringToNull()\n        {\n            return PrototypeCache.DisplayFormat != null\n                       ? PrototypeCache.DisplayFormat.ConvertEmptyStringToNull\n                       : base.ComputeConvertEmptyStringToNull();\n        }\n\n        protected override string ComputeDataTypeName()\n        {\n            if (PrototypeCache.DataType != null)\n            {\n                return PrototypeCache.DataType.ToDataTypeName();\n            }\n\n            if (PrototypeCache.DisplayFormat != null && !PrototypeCache.DisplayFormat.HtmlEncode)\n            {\n                return DataTypeUtil.HtmlTypeName;\n            }\n\n            return base.ComputeDataTypeName();\n        }\n\n        protected override string ComputeDescription()\n        {\n            return PrototypeCache.Display != null\n                       ? PrototypeCache.Display.GetDescription()\n                       : base.ComputeDescription();\n        }\n\n        protected override string ComputeDisplayFormatString()\n        {\n            return PrototypeCache.DisplayFormat != null\n                       ? PrototypeCache.DisplayFormat.DataFormatString\n                       : base.ComputeDisplayFormatString();\n        }\n\n        protected override string ComputeDisplayName()\n        {\n            string result = null;\n\n            if (PrototypeCache.Display != null)\n            {\n                result = PrototypeCache.Display.GetName();\n            }\n\n            if (result == null && PrototypeCache.DisplayName != null)\n            {\n                result = PrototypeCache.DisplayName.DisplayName;\n            }\n\n            return result ?? base.ComputeDisplayName();\n        }\n\n        protected override string ComputeEditFormatString()\n        {\n            if (PrototypeCache.DisplayFormat != null && PrototypeCache.DisplayFormat.ApplyFormatInEditMode)\n            {\n                _isEditFormatStringFromCache = true;\n                return PrototypeCache.DisplayFormat.DataFormatString;\n            }\n\n            return base.ComputeEditFormatString();\n        }\n\n        protected override bool ComputeHasNonDefaultEditFormat()\n        {\n            if (!String.IsNullOrEmpty(EditFormatString) && _isEditFormatStringFromCache)\n            {\n                // Have a non-empty EditFormatString based on [DisplayFormat] from our cache\n                if (PrototypeCache.DataType == null)\n                {\n                    // Attributes include no [DataType]; [DisplayFormat] was applied directly\n                    return true;\n                }\n\n                if (PrototypeCache.DataType.DisplayFormat != PrototypeCache.DisplayFormat)\n                {\n                    // Attributes include separate [DataType] and [DisplayFormat]; [DisplayFormat] provided override\n                    return true;\n                }\n\n                if (PrototypeCache.DataType.GetType() != typeof(DataTypeAttribute))\n                {\n                    // Attributes include [DisplayFormat] copied from [DataType] and [DataType] was of a subclass.\n                    // Assume the [DataType] constructor used the protected DisplayFormat setter to override its\n                    // default.  That is derived [DataType] provided override.\n                    return true;\n                }\n            }\n\n            return base.ComputeHasNonDefaultEditFormat();\n        }\n\n        protected override bool ComputeHideSurroundingHtml()\n        {\n            return PrototypeCache.HiddenInput != null\n                       ? !PrototypeCache.HiddenInput.DisplayValue\n                       : base.ComputeHideSurroundingHtml();\n        }\n\n        protected override bool ComputeHtmlEncode()\n        {\n            return (PrototypeCache.DisplayFormat != null)\n                ? PrototypeCache.DisplayFormat.HtmlEncode\n                : base.ComputeHtmlEncode();\n        }\n\n        protected override bool ComputeIsReadOnly()\n        {\n            if (PrototypeCache.Editable != null)\n            {\n                return !PrototypeCache.Editable.AllowEdit;\n            }\n\n            if (PrototypeCache.ReadOnly != null)\n            {\n                return PrototypeCache.ReadOnly.IsReadOnly;\n            }\n\n            return base.ComputeIsReadOnly();\n        }\n\n        protected override bool ComputeIsRequired()\n        {\n            return PrototypeCache.Required != null\n                       ? true\n                       : base.ComputeIsRequired();\n        }\n\n        protected override string ComputeNullDisplayText()\n        {\n            return PrototypeCache.DisplayFormat != null\n                       ? PrototypeCache.DisplayFormat.NullDisplayText\n                       : base.ComputeNullDisplayText();\n        }\n\n        protected override int ComputeOrder()\n        {\n            int? result = null;\n\n            if (PrototypeCache.Display != null)\n            {\n                result = PrototypeCache.Display.GetOrder();\n            }\n\n            return result ?? base.ComputeOrder();\n        }\n\n        protected override string ComputeShortDisplayName()\n        {\n            return PrototypeCache.Display != null\n                       ? PrototypeCache.Display.GetShortName()\n                       : base.ComputeShortDisplayName();\n        }\n\n        protected override bool ComputeShowForDisplay()\n        {\n            return PrototypeCache.ScaffoldColumn != null\n                       ? PrototypeCache.ScaffoldColumn.Scaffold\n                       : base.ComputeShowForDisplay();\n        }\n\n        protected override bool ComputeShowForEdit()\n        {\n            return PrototypeCache.ScaffoldColumn != null\n                       ? PrototypeCache.ScaffoldColumn.Scaffold\n                       : base.ComputeShowForEdit();\n        }\n\n        protected override string ComputeSimpleDisplayText()\n        {\n            if (Model != null)\n            {\n                if (PrototypeCache.DisplayColumn != null && !String.IsNullOrEmpty(PrototypeCache.DisplayColumn.DisplayColumn))\n                {\n                    PropertyInfo displayColumnProperty = ModelType.GetProperty(PrototypeCache.DisplayColumn.DisplayColumn, BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance);\n                    ValidateDisplayColumnAttribute(PrototypeCache.DisplayColumn, displayColumnProperty, ModelType);\n\n                    object simpleDisplayTextValue = displayColumnProperty.GetValue(Model, new object[0]);\n                    if (simpleDisplayTextValue != null)\n                    {\n                        return simpleDisplayTextValue.ToString();\n                    }\n                }\n            }\n\n            return base.ComputeSimpleDisplayText();\n        }\n\n        protected override string ComputeTemplateHint()\n        {\n            if (PrototypeCache.UIHint != null)\n            {\n                return PrototypeCache.UIHint.UIHint;\n            }\n\n            if (PrototypeCache.HiddenInput != null)\n            {\n                return \"HiddenInput\";\n            }\n\n            return base.ComputeTemplateHint();\n        }\n\n        protected override string ComputeWatermark()\n        {\n            return PrototypeCache.Display != null\n                       ? PrototypeCache.Display.GetPrompt()\n                       : base.ComputeWatermark();\n        }\n\n        private static void ValidateDisplayColumnAttribute(DisplayColumnAttribute displayColumnAttribute, PropertyInfo displayColumnProperty, Type modelType)\n        {\n            if (displayColumnProperty == null)\n            {\n                throw new InvalidOperationException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.DataAnnotationsModelMetadataProvider_UnknownProperty,\n                        modelType.FullName, displayColumnAttribute.DisplayColumn));\n            }\n            if (displayColumnProperty.GetGetMethod() == null)\n            {\n                throw new InvalidOperationException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.DataAnnotationsModelMetadataProvider_UnreadableProperty,\n                        modelType.FullName, displayColumnAttribute.DisplayColumn));\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/CachedDataAnnotationsModelMetadataProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Mvc\n{\n    public class CachedDataAnnotationsModelMetadataProvider : CachedAssociatedMetadataProvider<CachedDataAnnotationsModelMetadata>\n    {\n        protected override CachedDataAnnotationsModelMetadata CreateMetadataPrototype(IEnumerable<Attribute> attributes, Type containerType, Type modelType, string propertyName)\n        {\n            return new CachedDataAnnotationsModelMetadata(this, containerType, modelType, propertyName, attributes);\n        }\n\n        protected override CachedDataAnnotationsModelMetadata CreateMetadataFromPrototype(CachedDataAnnotationsModelMetadata prototype, Func<object> modelAccessor)\n        {\n            return new CachedDataAnnotationsModelMetadata(prototype, modelAccessor);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/CachedModelMetadata.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    // This class assumes that model metadata is expensive to create, and allows the user to\n    // stash a cache object that can be copied around as a prototype to make creation and\n    // computation quicker. It delegates the retrieval of values to getter methods, the results\n    // of which are cached on a per-metadata-instance basis.\n    //\n    // This allows flexible caching strategies: either caching the source of information across\n    // instances or caching of the actual information itself, depending on what the developer\n    // decides to put into the prototype cache.\n    public abstract class CachedModelMetadata<TPrototypeCache> : ModelMetadata\n    {\n        private bool _convertEmptyStringToNull;\n        private string _dataTypeName;\n        private string _description;\n        private string _displayFormatString;\n        private string _displayName;\n        private string _editFormatString;\n        private bool _hasNonDefaultEditFormat;\n        private bool _hideSurroundingHtml;\n        private bool _htmlEncode;\n        private bool _isReadOnly;\n        private bool _isRequired;\n        private string _nullDisplayText;\n        private int _order;\n        private string _shortDisplayName;\n        private bool _showForDisplay;\n        private bool _showForEdit;\n        private string _templateHint;\n        private string _watermark;\n\n        private bool _convertEmptyStringToNullComputed;\n        private bool _dataTypeNameComputed;\n        private bool _descriptionComputed;\n        private bool _displayFormatStringComputed;\n        private bool _displayNameComputed;\n        private bool _editFormatStringComputed;\n        private bool _hasNonDefaultEditFormatComputed;\n        private bool _hideSurroundingHtmlComputed;\n        private bool _htmlEncodeComputed;\n        private bool _isReadOnlyComputed;\n        private bool _isRequiredComputed;\n        private bool _nullDisplayTextComputed;\n        private bool _orderComputed;\n        private bool _shortDisplayNameComputed;\n        private bool _showForDisplayComputed;\n        private bool _showForEditComputed;\n        private bool _templateHintComputed;\n        private bool _watermarkComputed;\n\n        // Constructor for creating real instances of the metadata class based on a prototype\n        protected CachedModelMetadata(CachedModelMetadata<TPrototypeCache> prototype, Func<object> modelAccessor)\n            : base(prototype.Provider, prototype.ContainerType, modelAccessor, prototype.ModelType, prototype.PropertyName)\n        {\n            PrototypeCache = prototype.PrototypeCache;\n        }\n\n        // Constructor for creating the prototype instances of the metadata class\n        protected CachedModelMetadata(CachedDataAnnotationsModelMetadataProvider provider, Type containerType, Type modelType, string propertyName, TPrototypeCache prototypeCache)\n            : base(provider, containerType, null /* modelAccessor */, modelType, propertyName)\n        {\n            PrototypeCache = prototypeCache;\n        }\n\n        public sealed override bool ConvertEmptyStringToNull\n        {\n            get\n            {\n                if (!_convertEmptyStringToNullComputed)\n                {\n                    _convertEmptyStringToNull = ComputeConvertEmptyStringToNull();\n                    _convertEmptyStringToNullComputed = true;\n                }\n                return _convertEmptyStringToNull;\n            }\n            set\n            {\n                _convertEmptyStringToNull = value;\n                _convertEmptyStringToNullComputed = true;\n            }\n        }\n\n        public sealed override string DataTypeName\n        {\n            get\n            {\n                if (!_dataTypeNameComputed)\n                {\n                    _dataTypeName = ComputeDataTypeName();\n                    _dataTypeNameComputed = true;\n                }\n                return _dataTypeName;\n            }\n            set\n            {\n                _dataTypeName = value;\n                _dataTypeNameComputed = true;\n            }\n        }\n\n        public sealed override string Description\n        {\n            get\n            {\n                if (!_descriptionComputed)\n                {\n                    _description = ComputeDescription();\n                    _descriptionComputed = true;\n                }\n                return _description;\n            }\n            set\n            {\n                _description = value;\n                _descriptionComputed = true;\n            }\n        }\n\n        public sealed override string DisplayFormatString\n        {\n            get\n            {\n                if (!_displayFormatStringComputed)\n                {\n                    _displayFormatString = ComputeDisplayFormatString();\n                    _displayFormatStringComputed = true;\n                }\n                return _displayFormatString;\n            }\n            set\n            {\n                _displayFormatString = value;\n                _displayFormatStringComputed = true;\n            }\n        }\n\n        public sealed override string DisplayName\n        {\n            get\n            {\n                if (!_displayNameComputed)\n                {\n                    _displayName = ComputeDisplayName();\n                    _displayNameComputed = true;\n                }\n                return _displayName;\n            }\n            set\n            {\n                _displayName = value;\n                _displayNameComputed = true;\n            }\n        }\n\n        public sealed override string EditFormatString\n        {\n            get\n            {\n                if (!_editFormatStringComputed)\n                {\n                    _editFormatString = ComputeEditFormatString();\n                    _editFormatStringComputed = true;\n                }\n                return _editFormatString;\n            }\n            set\n            {\n                _editFormatString = value;\n                _editFormatStringComputed = true;\n            }\n        }\n\n        internal sealed override bool HasNonDefaultEditFormat\n        {\n            get\n            {\n                if (!_hasNonDefaultEditFormatComputed)\n                {\n                    _hasNonDefaultEditFormat = ComputeHasNonDefaultEditFormat();\n                    _hasNonDefaultEditFormatComputed = true;\n                }\n\n                return _hasNonDefaultEditFormat;\n            }\n            set\n            {\n                _hasNonDefaultEditFormat = value;\n                _hasNonDefaultEditFormatComputed = true;\n            }\n        }\n\n        public sealed override bool HideSurroundingHtml\n        {\n            get\n            {\n                if (!_hideSurroundingHtmlComputed)\n                {\n                    _hideSurroundingHtml = ComputeHideSurroundingHtml();\n                    _hideSurroundingHtmlComputed = true;\n                }\n                return _hideSurroundingHtml;\n            }\n            set\n            {\n                _hideSurroundingHtml = value;\n                _hideSurroundingHtmlComputed = true;\n            }\n        }\n\n        public sealed override bool HtmlEncode\n        {\n            get\n            {\n                if (!_htmlEncodeComputed)\n                {\n                    _htmlEncode = ComputeHtmlEncode();\n                    _htmlEncodeComputed = true;\n                }\n                return _htmlEncode;\n            }\n            set\n            {\n                _htmlEncode = value;\n                _htmlEncodeComputed = true;\n            }\n        }\n\n        public sealed override bool IsReadOnly\n        {\n            get\n            {\n                if (!_isReadOnlyComputed)\n                {\n                    _isReadOnly = ComputeIsReadOnly();\n                    _isReadOnlyComputed = true;\n                }\n                return _isReadOnly;\n            }\n            set\n            {\n                _isReadOnly = value;\n                _isReadOnlyComputed = true;\n            }\n        }\n\n        public sealed override bool IsRequired\n        {\n            get\n            {\n                if (!_isRequiredComputed)\n                {\n                    _isRequired = ComputeIsRequired();\n                    _isRequiredComputed = true;\n                }\n                return _isRequired;\n            }\n            set\n            {\n                _isRequired = value;\n                _isRequiredComputed = true;\n            }\n        }\n\n        public sealed override string NullDisplayText\n        {\n            get\n            {\n                if (!_nullDisplayTextComputed)\n                {\n                    _nullDisplayText = ComputeNullDisplayText();\n                    _nullDisplayTextComputed = true;\n                }\n                return _nullDisplayText;\n            }\n            set\n            {\n                _nullDisplayText = value;\n                _nullDisplayTextComputed = true;\n            }\n        }\n\n        public sealed override int Order\n        {\n            get\n            {\n                if (!_orderComputed)\n                {\n                    _order = ComputeOrder();\n                    _orderComputed = true;\n                }\n                return _order;\n            }\n            set\n            {\n                _order = value;\n                _orderComputed = true;\n            }\n        }\n\n        protected TPrototypeCache PrototypeCache { get; set; }\n\n        public sealed override string ShortDisplayName\n        {\n            get\n            {\n                if (!_shortDisplayNameComputed)\n                {\n                    _shortDisplayName = ComputeShortDisplayName();\n                    _shortDisplayNameComputed = true;\n                }\n                return _shortDisplayName;\n            }\n            set\n            {\n                _shortDisplayName = value;\n                _shortDisplayNameComputed = true;\n            }\n        }\n\n        public sealed override bool ShowForDisplay\n        {\n            get\n            {\n                if (!_showForDisplayComputed)\n                {\n                    _showForDisplay = ComputeShowForDisplay();\n                    _showForDisplayComputed = true;\n                }\n                return _showForDisplay;\n            }\n            set\n            {\n                _showForDisplay = value;\n                _showForDisplayComputed = true;\n            }\n        }\n\n        public sealed override bool ShowForEdit\n        {\n            get\n            {\n                if (!_showForEditComputed)\n                {\n                    _showForEdit = ComputeShowForEdit();\n                    _showForEditComputed = true;\n                }\n                return _showForEdit;\n            }\n            set\n            {\n                _showForEdit = value;\n                _showForEditComputed = true;\n            }\n        }\n\n        public sealed override string SimpleDisplayText\n        {\n            get\n            {\n                // This is already cached in the base class with an appropriate override available\n                return base.SimpleDisplayText;\n            }\n            set { base.SimpleDisplayText = value; }\n        }\n\n        public sealed override string TemplateHint\n        {\n            get\n            {\n                if (!_templateHintComputed)\n                {\n                    _templateHint = ComputeTemplateHint();\n                    _templateHintComputed = true;\n                }\n                return _templateHint;\n            }\n            set\n            {\n                _templateHint = value;\n                _templateHintComputed = true;\n            }\n        }\n\n        public sealed override string Watermark\n        {\n            get\n            {\n                if (!_watermarkComputed)\n                {\n                    _watermark = ComputeWatermark();\n                    _watermarkComputed = true;\n                }\n                return _watermark;\n            }\n            set\n            {\n                _watermark = value;\n                _watermarkComputed = true;\n            }\n        }\n\n        protected virtual bool ComputeConvertEmptyStringToNull()\n        {\n            return base.ConvertEmptyStringToNull;\n        }\n\n        protected virtual string ComputeDataTypeName()\n        {\n            return base.DataTypeName;\n        }\n\n        protected virtual string ComputeDescription()\n        {\n            return base.Description;\n        }\n\n        protected virtual string ComputeDisplayFormatString()\n        {\n            return base.DisplayFormatString;\n        }\n\n        protected virtual string ComputeDisplayName()\n        {\n            return base.DisplayName;\n        }\n\n        protected virtual string ComputeEditFormatString()\n        {\n            return base.EditFormatString;\n        }\n\n        protected virtual bool ComputeHasNonDefaultEditFormat()\n        {\n            return base.HasNonDefaultEditFormat;\n        }\n\n        protected virtual bool ComputeHideSurroundingHtml()\n        {\n            return base.HideSurroundingHtml;\n        }\n\n        protected virtual bool ComputeHtmlEncode()\n        {\n            return base.HtmlEncode;\n        }\n\n        protected virtual bool ComputeIsReadOnly()\n        {\n            return base.IsReadOnly;\n        }\n\n        protected virtual bool ComputeIsRequired()\n        {\n            return base.IsRequired;\n        }\n\n        protected virtual string ComputeNullDisplayText()\n        {\n            return base.NullDisplayText;\n        }\n\n        protected virtual int ComputeOrder()\n        {\n            return base.Order;\n        }\n\n        protected virtual string ComputeShortDisplayName()\n        {\n            return base.ShortDisplayName;\n        }\n\n        protected virtual bool ComputeShowForDisplay()\n        {\n            return base.ShowForDisplay;\n        }\n\n        protected virtual bool ComputeShowForEdit()\n        {\n            return base.ShowForEdit;\n        }\n\n        protected virtual string ComputeSimpleDisplayText()\n        {\n            return base.GetSimpleDisplayText();\n        }\n\n        protected virtual string ComputeTemplateHint()\n        {\n            return base.TemplateHint;\n        }\n\n        protected virtual string ComputeWatermark()\n        {\n            return base.Watermark;\n        }\n\n        protected sealed override string GetSimpleDisplayText()\n        {\n            // Rename for consistency\n            return ComputeSimpleDisplayText();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/CancellationTokenModelBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\n\nnamespace System.Web.Mvc\n{\n    public class CancellationTokenModelBinder : IModelBinder\n    {\n        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)\n        {\n            return default(CancellationToken);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ChildActionOnlyAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\n    public sealed class ChildActionOnlyAttribute : FilterAttribute, IAuthorizationFilter\n    {\n        public void OnAuthorization(AuthorizationContext filterContext)\n        {\n            if (filterContext == null)\n            {\n                throw new ArgumentNullException(\"filterContext\");\n            }\n\n            if (!filterContext.IsChildAction)\n            {\n                throw Error.ChildActionOnlyAttribute_MustBeInChildRequest(filterContext.ActionDescriptor);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ChildActionValueProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\n\nnamespace System.Web.Mvc\n{\n    public sealed class ChildActionValueProvider : DictionaryValueProvider<object>\n    {\n        private static string _childActionValuesKey = Guid.NewGuid().ToString();\n\n        public ChildActionValueProvider(ControllerContext controllerContext)\n            : base(controllerContext.RouteData.Values, CultureInfo.InvariantCulture)\n        {\n        }\n\n        internal static string ChildActionValuesKey\n        {\n            get { return _childActionValuesKey; }\n        }\n\n        public override ValueProviderResult GetValue(string key)\n        {\n            if (key == null)\n            {\n                throw new ArgumentNullException(\"key\");\n            }\n\n            ValueProviderResult explicitValues = base.GetValue(ChildActionValuesKey);\n            if (explicitValues != null)\n            {\n                DictionaryValueProvider<object> rawExplicitValues = explicitValues.RawValue as DictionaryValueProvider<object>;\n                if (rawExplicitValues != null)\n                {\n                    return rawExplicitValues.GetValue(key);\n                }\n            }\n\n            return null;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ChildActionValueProviderFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public sealed class ChildActionValueProviderFactory : ValueProviderFactory\n    {\n        public override IValueProvider GetValueProvider(ControllerContext controllerContext)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n\n            return new ChildActionValueProvider(controllerContext);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ClientDataTypeModelValidatorProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    public class ClientDataTypeModelValidatorProvider : ModelValidatorProvider\n    {\n        private static readonly HashSet<Type> _numericTypes = new HashSet<Type>(new Type[]\n        {\n            typeof(byte), typeof(sbyte),\n            typeof(short), typeof(ushort),\n            typeof(int), typeof(uint),\n            typeof(long), typeof(ulong),\n            typeof(float), typeof(double), typeof(decimal)\n        });\n\n        private static string _resourceClassKey;\n\n        public static string ResourceClassKey\n        {\n            get { return _resourceClassKey ?? String.Empty; }\n            set { _resourceClassKey = value; }\n        }\n\n        public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context)\n        {\n            if (metadata == null)\n            {\n                throw new ArgumentNullException(\"metadata\");\n            }\n            if (context == null)\n            {\n                throw new ArgumentNullException(\"context\");\n            }\n\n            return GetValidatorsImpl(metadata, context);\n        }\n\n        private static IEnumerable<ModelValidator> GetValidatorsImpl(ModelMetadata metadata, ControllerContext context)\n        {\n            Type type = metadata.ModelType;\n\n            if (IsDateTimeType(type, metadata))\n            {\n                yield return new DateModelValidator(metadata, context);\n            }\n\n            if (IsNumericType(type))\n            {\n                yield return new NumericModelValidator(metadata, context);\n            }\n        }\n\n        private static bool IsNumericType(Type type)\n        {\n            return _numericTypes.Contains(GetTypeToValidate(type));\n        }\n\n        private static bool IsDateTimeType(Type type, ModelMetadata metadata)\n        {\n            return typeof(DateTime) == GetTypeToValidate(type)\n                && !String.Equals(metadata.DataTypeName, \"Time\", StringComparison.OrdinalIgnoreCase);\n        }\n\n        private static Type GetTypeToValidate(Type type)\n        {\n            return Nullable.GetUnderlyingType(type) ?? type; // strip off the Nullable<>\n        }\n\n        // If the user specified a ResourceClassKey try to load the resource they specified.\n        // If the class key is invalid, an exception will be thrown.\n        // If the class key is valid but the resource is not found, it returns null, in which\n        // case it will fall back to the MVC default error message.\n        private static string GetUserResourceString(ControllerContext controllerContext, string resourceName)\n        {\n            string result = null;\n\n            if (!String.IsNullOrEmpty(ResourceClassKey) && (controllerContext != null) && (controllerContext.HttpContext != null))\n            {\n                result = controllerContext.HttpContext.GetGlobalResourceObject(ResourceClassKey, resourceName, CultureInfo.CurrentUICulture) as string;\n            }\n\n            return result;\n        }\n\n        private static string GetFieldMustBeNumericResource(ControllerContext controllerContext)\n        {\n            return GetUserResourceString(controllerContext, \"FieldMustBeNumeric\") ?? MvcResources.ClientDataTypeModelValidatorProvider_FieldMustBeNumeric;\n        }\n\n        private static string GetFieldMustBeDateResource(ControllerContext controllerContext)\n        {\n            return GetUserResourceString(controllerContext, \"FieldMustBeDate\") ?? MvcResources.ClientDataTypeModelValidatorProvider_FieldMustBeDate;\n        }\n\n        internal class ClientModelValidator : ModelValidator\n        {\n            private string _errorMessage;\n            private string _validationType;\n\n            public ClientModelValidator(ModelMetadata metadata, ControllerContext controllerContext, string validationType, string errorMessage)\n                : base(metadata, controllerContext)\n            {\n                if (String.IsNullOrEmpty(validationType))\n                {\n                    throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"validationType\");\n                }\n\n                if (String.IsNullOrEmpty(errorMessage))\n                {\n                    throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"errorMessage\");\n                }\n\n                _validationType = validationType;\n                _errorMessage = errorMessage;\n            }\n\n            public sealed override IEnumerable<ModelClientValidationRule> GetClientValidationRules()\n            {\n                ModelClientValidationRule rule = new ModelClientValidationRule()\n                {\n                    ValidationType = _validationType,\n                    ErrorMessage = FormatErrorMessage(Metadata.GetDisplayName())\n                };\n\n                return new ModelClientValidationRule[] { rule };\n            }\n\n            private string FormatErrorMessage(string displayName)\n            {\n                // use CurrentCulture since this message is intended for the site visitor\n                return String.Format(CultureInfo.CurrentCulture, _errorMessage, displayName);\n            }\n\n            public sealed override IEnumerable<ModelValidationResult> Validate(object container)\n            {\n                // this is not a server-side validator\n                return Enumerable.Empty<ModelValidationResult>();\n            }\n        }\n\n        internal sealed class DateModelValidator : ClientModelValidator\n        {\n            public DateModelValidator(ModelMetadata metadata, ControllerContext controllerContext)\n                : base(metadata, controllerContext, \"date\", GetFieldMustBeDateResource(controllerContext))\n            {\n            }\n        }\n\n        internal sealed class NumericModelValidator : ClientModelValidator\n        {\n            public NumericModelValidator(ModelMetadata metadata, ControllerContext controllerContext)\n                : base(metadata, controllerContext, \"number\", GetFieldMustBeNumericResource(controllerContext))\n            {\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/CompareAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Reflection;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    [Obsolete(\"The recommended alternative is to use the System.ComponentModel.DataAnnotations.CompareAttribute type, which has the same functionality as this type.\")]\n    [AttributeUsage(AttributeTargets.Property)]\n    [SuppressMessage(\"Microsoft.Performance\", \"CA1813:AvoidUnsealedAttributes\", Justification = \"This attribute is designed to be a base class for other attributes.\")]\n    public class CompareAttribute : ValidationAttribute, IClientValidatable\n    {\n        public CompareAttribute(string otherProperty)\n            : base(MvcResources.CompareAttribute_MustMatch)\n        {\n            if (otherProperty == null)\n            {\n                throw new ArgumentNullException(\"otherProperty\");\n            }\n            OtherProperty = otherProperty;\n        }\n\n        public string OtherProperty { get; private set; }\n\n        public string OtherPropertyDisplayName { get; internal set; }\n\n        public override string FormatErrorMessage(string name)\n        {\n            return String.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, OtherPropertyDisplayName ?? OtherProperty);\n        }\n\n        protected override ValidationResult IsValid(object value, ValidationContext validationContext)\n        {\n            PropertyInfo otherPropertyInfo = validationContext.ObjectType.GetProperty(OtherProperty);\n            if (otherPropertyInfo == null)\n            {\n                return new ValidationResult(String.Format(CultureInfo.CurrentCulture, MvcResources.CompareAttribute_UnknownProperty, OtherProperty));\n            }\n\n            object otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);\n            if (!Equals(value, otherPropertyValue))\n            {\n                if (OtherPropertyDisplayName == null)\n                {\n                    OtherPropertyDisplayName = ModelMetadataProviders.Current.GetMetadataForProperty(() => validationContext.ObjectInstance, validationContext.ObjectType, OtherProperty).GetDisplayName();\n                }\n                return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));\n            }\n            return null;\n        }\n\n        public static string FormatPropertyForClientValidation(string property)\n        {\n            if (property == null)\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"property\");\n            }\n            return \"*.\" + property;\n        }\n\n        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)\n        {\n            if (metadata.ContainerType != null)\n            {\n                if (OtherPropertyDisplayName == null)\n                {\n                    OtherPropertyDisplayName = ModelMetadataProviders.Current.GetMetadataForProperty(() => metadata.Model, metadata.ContainerType, OtherProperty).GetDisplayName();\n                }\n            }\n            yield return new ModelClientValidationEqualToRule(FormatErrorMessage(metadata.GetDisplayName()), FormatPropertyForClientValidation(OtherProperty));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/CompareAttributeAdapter.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing DataAnnotationsCompareAttribute = System.ComponentModel.DataAnnotations.CompareAttribute;\n\nnamespace System.Web.Mvc\n{\n    internal class CompareAttributeAdapter : DataAnnotationsModelValidator<DataAnnotationsCompareAttribute>\n    {\n        public CompareAttributeAdapter(ModelMetadata metadata, ControllerContext context, DataAnnotationsCompareAttribute attribute)\n            : base(metadata, context, new CompareAttributeWrapper(attribute, metadata))\n        {\n            Contract.Assert(attribute.GetType() == typeof(DataAnnotationsCompareAttribute));\n        }\n\n        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()\n        {\n            yield return new ModelClientValidationEqualToRule(ErrorMessage, FormatPropertyForClientValidation(Attribute.OtherProperty));\n        }\n\n        private static string FormatPropertyForClientValidation(string property)\n        {\n            Contract.Assert(property != null);\n\n            return \"*.\" + property;\n        }\n\n        // Wrapper for CompareAttribute that will eagerly get the OtherPropertyDisplayName and use it on the error message for client validation.\n        // The System.ComponentModel.DataAnnotations.CompareAttribute doesn't populate the OtherPropertyDisplayName until after IsValid() \n        // is called. Therefore, by the time we get the error message for client validation, the display name is not populated and won't be used.\n        private sealed class CompareAttributeWrapper : DataAnnotationsCompareAttribute\n        {\n            private readonly string _otherPropertyDisplayName;\n\n            public CompareAttributeWrapper(DataAnnotationsCompareAttribute attribute, ModelMetadata metadata)\n                : base(attribute.OtherProperty)\n            {\n                _otherPropertyDisplayName = attribute.OtherPropertyDisplayName;\n                if (_otherPropertyDisplayName == null && metadata.ContainerType != null)\n                {\n                    _otherPropertyDisplayName = ModelMetadataProviders.Current.GetMetadataForProperty(() => metadata.Model, metadata.ContainerType, attribute.OtherProperty).GetDisplayName();\n                }\n\n                if (_otherPropertyDisplayName == null)\n                {\n                    _otherPropertyDisplayName = attribute.OtherProperty;\n                }\n\n                // Copy settable properties from wrapped attribute. Don't reset default message accessor (set as\n                // CompareAttribute constructor calls ValidationAttribute constructor) when all properties are null to\n                // preserve default error message. Reset the message accessor when just ErrorMessageResourceType is\n                // non-null to ensure correct InvalidOperationException.\n                if (!String.IsNullOrEmpty(attribute.ErrorMessage) ||\n                    !String.IsNullOrEmpty(attribute.ErrorMessageResourceName) ||\n                    attribute.ErrorMessageResourceType != null)\n                {\n                    ErrorMessage = attribute.ErrorMessage;\n                    ErrorMessageResourceName = attribute.ErrorMessageResourceName;\n                    ErrorMessageResourceType = attribute.ErrorMessageResourceType;\n                }\n            }\n\n            public override string FormatErrorMessage(string name)\n            {\n                return String.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, _otherPropertyDisplayName);\n            }\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Mvc/ContentResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Text;\n\nnamespace System.Web.Mvc\n{\n    public class ContentResult : ActionResult\n    {\n        public string Content { get; set; }\n\n        public Encoding ContentEncoding { get; set; }\n\n        public string ContentType { get; set; }\n\n        public override void ExecuteResult(ControllerContext context)\n        {\n            if (context == null)\n            {\n                throw new ArgumentNullException(\"context\");\n            }\n\n            HttpResponseBase response = context.HttpContext.Response;\n\n            if (!String.IsNullOrEmpty(ContentType))\n            {\n                response.ContentType = ContentType;\n            }\n            if (ContentEncoding != null)\n            {\n                response.ContentEncoding = ContentEncoding;\n            }\n            if (Content != null)\n            {\n                response.Write(Content);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Controller.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.IO;\nusing System.Security.Principal;\nusing System.Text;\nusing System.Web.Mvc.Async;\nusing System.Web.Mvc.Filters;\nusing System.Web.Mvc.Properties;\nusing System.Web.Mvc.Routing;\nusing System.Web.Profile;\nusing System.Web.Routing;\nusing System.Web.WebPages;\n\nnamespace System.Web.Mvc\n{\n    [SuppressMessage(\"Microsoft.Maintainability\", \"CA1506:AvoidExcessiveClassCoupling\", Justification = \"Class complexity dictated by public surface area\")]\n    public abstract class Controller : ControllerBase, IActionFilter, IAuthenticationFilter, IAuthorizationFilter, IDisposable, IExceptionFilter, IResultFilter, IAsyncController, IAsyncManagerContainer\n    {\n        private static readonly object _executeTag = new object();\n        private static readonly object _executeCoreTag = new object();\n\n        private readonly AsyncManager _asyncManager = new AsyncManager();\n        private IActionInvoker _actionInvoker;\n        private ModelBinderDictionary _binders;\n        private RouteCollection _routeCollection;\n        private ITempDataProvider _tempDataProvider;\n        private ViewEngineCollection _viewEngineCollection;\n\n        private IDependencyResolver _resolver;\n\n        /// <summary>\n        /// Represents a replaceable dependency resolver providing services.\n        /// By default, it uses the <see cref=\"DependencyResolver.CurrentCache\"/>. \n        /// </summary>\n        public IDependencyResolver Resolver\n        {\n            get { return _resolver ?? DependencyResolver.CurrentCache; }\n            set { _resolver = value; }\n        }\n\n        public AsyncManager AsyncManager\n        {\n            get { return _asyncManager; }\n        }\n\n        /// <summary>\n        /// This is for backwards compat. MVC 4.0 starts allowing Controller to support asynchronous patterns.\n        /// This means ExecuteCore doesn't get called on derived classes. Derived classes can override this\n        /// flag and set to true if they still need ExecuteCore to be called.\n        /// </summary>\n        protected virtual bool DisableAsyncSupport\n        {\n            get { return false; }\n        }\n\n        public IActionInvoker ActionInvoker\n        {\n            get\n            {\n                if (_actionInvoker == null)\n                {\n                    _actionInvoker = CreateActionInvoker();\n                }\n                return _actionInvoker;\n            }\n            set { _actionInvoker = value; }\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"Property is settable so that the dictionary can be provided for unit testing purposes.\")]\n        protected internal ModelBinderDictionary Binders\n        {\n            get\n            {\n                if (_binders == null)\n                {\n                    _binders = ModelBinders.Binders;\n                }\n                return _binders;\n            }\n            set { _binders = value; }\n        }\n\n        public HttpContextBase HttpContext\n        {\n            get { return ControllerContext == null ? null : ControllerContext.HttpContext; }\n        }\n\n        public ModelStateDictionary ModelState\n        {\n            get { return ViewData.ModelState; }\n        }\n\n        public ProfileBase Profile\n        {\n            get { return HttpContext == null ? null : HttpContext.Profile; }\n        }\n\n        public HttpRequestBase Request\n        {\n            get { return HttpContext == null ? null : HttpContext.Request; }\n        }\n\n        public HttpResponseBase Response\n        {\n            get { return HttpContext == null ? null : HttpContext.Response; }\n        }\n\n        internal RouteCollection RouteCollection\n        {\n            get\n            {\n                if (_routeCollection == null)\n                {\n                    _routeCollection = RouteTable.Routes;\n                }\n                return _routeCollection;\n            }\n            set { _routeCollection = value; }\n        }\n\n        public RouteData RouteData\n        {\n            get { return ControllerContext == null ? null : ControllerContext.RouteData; }\n        }\n\n        public HttpServerUtilityBase Server\n        {\n            get { return HttpContext == null ? null : HttpContext.Server; }\n        }\n\n        public HttpSessionStateBase Session\n        {\n            get { return HttpContext == null ? null : HttpContext.Session; }\n        }\n\n        public ITempDataProvider TempDataProvider\n        {\n            get\n            {\n                if (_tempDataProvider == null)\n                {\n                    _tempDataProvider = CreateTempDataProvider();\n                }\n                return _tempDataProvider;\n            }\n            set { _tempDataProvider = value; }\n        }\n\n        public UrlHelper Url { get; set; }\n\n        public IPrincipal User\n        {\n            get { return HttpContext == null ? null : HttpContext.User; }\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"This entire type is meant to be mutable.\")]\n        public ViewEngineCollection ViewEngineCollection\n        {\n            get { return _viewEngineCollection ?? ViewEngines.Engines; }\n            set { _viewEngineCollection = value; }\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1719:ParameterNamesShouldNotMatchMemberNames\", MessageId = \"0#\", Justification = \"'Content' refers to ContentResult type; 'content' refers to ContentResult.Content property.\")]\n        protected internal ContentResult Content(string content)\n        {\n            return Content(content, null /* contentType */);\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1719:ParameterNamesShouldNotMatchMemberNames\", MessageId = \"0#\", Justification = \"'Content' refers to ContentResult type; 'content' refers to ContentResult.Content property.\")]\n        protected internal ContentResult Content(string content, string contentType)\n        {\n            return Content(content, contentType, null /* contentEncoding */);\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1719:ParameterNamesShouldNotMatchMemberNames\", MessageId = \"0#\", Justification = \"'Content' refers to ContentResult type; 'content' refers to ContentResult.Content property.\")]\n        protected internal virtual ContentResult Content(string content, string contentType, Encoding contentEncoding)\n        {\n            return new ContentResult\n            {\n                Content = content,\n                ContentType = contentType,\n                ContentEncoding = contentEncoding\n            };\n        }\n\n        protected virtual IActionInvoker CreateActionInvoker()\n        {\n            // Controller supports asynchronous operations by default. \n            // Those factories can be customized in order to create an action invoker for each request.\n            IAsyncActionInvokerFactory asyncActionInvokerFactory = Resolver.GetService<IAsyncActionInvokerFactory>();\n            if (asyncActionInvokerFactory != null)\n            {\n                return asyncActionInvokerFactory.CreateInstance();\n            }\n            IActionInvokerFactory actionInvokerFactory = Resolver.GetService<IActionInvokerFactory>();\n            if (actionInvokerFactory != null)\n            {\n                return actionInvokerFactory.CreateInstance();\n            }\n\n            // Note that getting a service from the current cache will return the same instance for every request.\n            return Resolver.GetService<IAsyncActionInvoker>() ??\n                Resolver.GetService<IActionInvoker>() ??\n                new AsyncControllerActionInvoker();\n        }\n\n        protected virtual ITempDataProvider CreateTempDataProvider()\n        {\n            // The factory can be customized in order to create an ITempDataProvider for the controller.\n            ITempDataProviderFactory tempDataProviderFactory = Resolver.GetService<ITempDataProviderFactory>();\n            if (tempDataProviderFactory != null)\n            {\n                return tempDataProviderFactory.CreateInstance();\n            }\n\n            // Note that getting a service from the current cache will return the same instance for every controller.\n            return Resolver.GetService<ITempDataProvider>() ?? new SessionStateTempDataProvider();\n        }\n\n        // The default invoker will never match methods defined on the Controller type, so\n        // the Dispose() method is not web-callable.  However, in general, since implicitly-\n        // implemented interface methods are public, they are web-callable unless decorated with\n        // [NonAction].\n        public void Dispose()\n        {\n            Dispose(true /* disposing */);\n            GC.SuppressFinalize(this);\n        }\n\n        protected virtual void Dispose(bool disposing)\n        {\n        }\n\n        protected override void ExecuteCore()\n        {\n            // If code in this method needs to be updated, please also check the BeginExecuteCore() and\n            // EndExecuteCore() methods of AsyncController to see if that code also must be updated.\n\n            PossiblyLoadTempData();\n            try\n            {\n                string actionName = GetActionName(RouteData);\n                if (!ActionInvoker.InvokeAction(ControllerContext, actionName))\n                {\n                    HandleUnknownAction(actionName);\n                }\n            }\n            finally\n            {\n                PossiblySaveTempData();\n            }\n        }\n\n        protected internal FileContentResult File(byte[] fileContents, string contentType)\n        {\n            return File(fileContents, contentType, null /* fileDownloadName */);\n        }\n\n        protected internal virtual FileContentResult File(byte[] fileContents, string contentType, string fileDownloadName)\n        {\n            return new FileContentResult(fileContents, contentType) { FileDownloadName = fileDownloadName };\n        }\n\n        protected internal FileStreamResult File(Stream fileStream, string contentType)\n        {\n            return File(fileStream, contentType, null /* fileDownloadName */);\n        }\n\n        protected internal virtual FileStreamResult File(Stream fileStream, string contentType, string fileDownloadName)\n        {\n            return new FileStreamResult(fileStream, contentType) { FileDownloadName = fileDownloadName };\n        }\n\n        protected internal FilePathResult File(string fileName, string contentType)\n        {\n            return File(fileName, contentType, null /* fileDownloadName */);\n        }\n\n        protected internal virtual FilePathResult File(string fileName, string contentType, string fileDownloadName)\n        {\n            return new FilePathResult(fileName, contentType) { FileDownloadName = fileDownloadName };\n        }\n\n        private static string GetActionName(RouteData routeData)\n        {\n            Contract.Assert(routeData != null);\n\n            // If this is an attribute routing match then the 'RouteData' has a list of sub-matches rather than\n            // the traditional controller and action values. When the match is an attribute routing match\n            // we'll pass null to the action selector, and let it choose a sub-match to use.\n            if (routeData.HasDirectRouteMatch())\n            {\n                return null;\n            }\n            else\n            {\n                return routeData.GetRequiredString(\"action\");\n            }\n        }\n\n        protected virtual void HandleUnknownAction(string actionName)\n        {\n            // If this is a direct route we might not yet have an action name\n            if (String.IsNullOrEmpty(actionName))\n            {\n                throw new HttpException(404, String.Format(CultureInfo.CurrentCulture,\n                                           MvcResources.Controller_UnknownAction_NoActionName, GetType().FullName));\n            }\n            else\n            {\n                throw new HttpException(404, String.Format(CultureInfo.CurrentCulture,\n                                                           MvcResources.Controller_UnknownAction, actionName, GetType().FullName));\n            }\n        }\n\n        protected internal HttpNotFoundResult HttpNotFound()\n        {\n            return HttpNotFound(null);\n        }\n\n        protected internal virtual HttpNotFoundResult HttpNotFound(string statusDescription)\n        {\n            return new HttpNotFoundResult(statusDescription);\n        }\n\n        protected internal virtual JavaScriptResult JavaScript(string script)\n        {\n            return new JavaScriptResult { Script = script };\n        }\n\n        protected internal JsonResult Json(object data)\n        {\n            return Json(data, null /* contentType */, null /* contentEncoding */, JsonRequestBehavior.DenyGet);\n        }\n\n        protected internal JsonResult Json(object data, string contentType)\n        {\n            return Json(data, contentType, null /* contentEncoding */, JsonRequestBehavior.DenyGet);\n        }\n\n        protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding)\n        {\n            return Json(data, contentType, contentEncoding, JsonRequestBehavior.DenyGet);\n        }\n\n        protected internal JsonResult Json(object data, JsonRequestBehavior behavior)\n        {\n            return Json(data, null /* contentType */, null /* contentEncoding */, behavior);\n        }\n\n        protected internal JsonResult Json(object data, string contentType, JsonRequestBehavior behavior)\n        {\n            return Json(data, contentType, null /* contentEncoding */, behavior);\n        }\n\n        protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)\n        {\n            return new JsonResult\n            {\n                Data = data,\n                ContentType = contentType,\n                ContentEncoding = contentEncoding,\n                JsonRequestBehavior = behavior\n            };\n        }\n\n        protected override void Initialize(RequestContext requestContext)\n        {\n            base.Initialize(requestContext);\n            Url = new UrlHelper(requestContext);\n        }\n\n        protected virtual void OnActionExecuting(ActionExecutingContext filterContext)\n        {\n        }\n\n        protected virtual void OnActionExecuted(ActionExecutedContext filterContext)\n        {\n        }\n\n        protected virtual void OnAuthentication(AuthenticationContext filterContext)\n        {\n        }\n\n        protected virtual void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)\n        {\n        }\n\n        protected virtual void OnAuthorization(AuthorizationContext filterContext)\n        {\n        }\n\n        protected virtual void OnException(ExceptionContext filterContext)\n        {\n        }\n\n        protected virtual void OnResultExecuted(ResultExecutedContext filterContext)\n        {\n        }\n\n        protected virtual void OnResultExecuting(ResultExecutingContext filterContext)\n        {\n        }\n\n        protected internal PartialViewResult PartialView()\n        {\n            return PartialView(null /* viewName */, null /* model */);\n        }\n\n        protected internal PartialViewResult PartialView(object model)\n        {\n            return PartialView(null /* viewName */, model);\n        }\n\n        protected internal PartialViewResult PartialView(string viewName)\n        {\n            return PartialView(viewName, null /* model */);\n        }\n\n        protected internal virtual PartialViewResult PartialView(string viewName, object model)\n        {\n            if (model != null)\n            {\n                ViewData.Model = model;\n            }\n\n            return new PartialViewResult\n            {\n                ViewName = viewName,\n                ViewData = ViewData,\n                TempData = TempData,\n                ViewEngineCollection = ViewEngineCollection\n            };\n        }\n\n        internal void PossiblyLoadTempData()\n        {\n            if (!ControllerContext.IsChildAction)\n            {\n                TempData.Load(ControllerContext, TempDataProvider);\n            }\n        }\n\n        internal void PossiblySaveTempData()\n        {\n            if (!ControllerContext.IsChildAction)\n            {\n                TempData.Save(ControllerContext, TempDataProvider);\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"0#\", Justification = \"Response.Redirect() takes its URI as a string parameter.\")]\n        protected internal virtual RedirectResult Redirect(string url)\n        {\n            if (String.IsNullOrEmpty(url))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"url\");\n            }\n\n            return new RedirectResult(url);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"0#\", Justification = \"Response.RedirectPermanent() takes its URI as a string parameter.\")]\n        protected internal virtual RedirectResult RedirectPermanent(string url)\n        {\n            if (String.IsNullOrEmpty(url))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"url\");\n            }\n\n            return new RedirectResult(url, permanent: true);\n        }\n\n        protected internal RedirectToRouteResult RedirectToAction(string actionName)\n        {\n            return RedirectToAction(actionName, (RouteValueDictionary)null);\n        }\n\n        protected internal RedirectToRouteResult RedirectToAction(string actionName, object routeValues)\n        {\n            return RedirectToAction(actionName, TypeHelper.ObjectToDictionary(routeValues));\n        }\n\n        protected internal RedirectToRouteResult RedirectToAction(string actionName, RouteValueDictionary routeValues)\n        {\n            return RedirectToAction(actionName, null /* controllerName */, routeValues);\n        }\n\n        protected internal RedirectToRouteResult RedirectToAction(string actionName, string controllerName)\n        {\n            return RedirectToAction(actionName, controllerName, (RouteValueDictionary)null);\n        }\n\n        protected internal RedirectToRouteResult RedirectToAction(string actionName, string controllerName, object routeValues)\n        {\n            return RedirectToAction(actionName, controllerName, TypeHelper.ObjectToDictionary(routeValues));\n        }\n\n        protected internal virtual RedirectToRouteResult RedirectToAction(string actionName, string controllerName, RouteValueDictionary routeValues)\n        {\n            RouteValueDictionary mergedRouteValues;\n\n            if (RouteData == null)\n            {\n                mergedRouteValues = RouteValuesHelpers.MergeRouteValues(actionName, controllerName, null, routeValues, includeImplicitMvcValues: true);\n            }\n            else\n            {\n                mergedRouteValues = RouteValuesHelpers.MergeRouteValues(actionName, controllerName, RouteData.Values, routeValues, includeImplicitMvcValues: true);\n            }\n\n            return new RedirectToRouteResult(mergedRouteValues);\n        }\n\n        protected internal RedirectToRouteResult RedirectToActionPermanent(string actionName)\n        {\n            return RedirectToActionPermanent(actionName, (RouteValueDictionary)null);\n        }\n\n        protected internal RedirectToRouteResult RedirectToActionPermanent(string actionName, object routeValues)\n        {\n            return RedirectToActionPermanent(actionName, TypeHelper.ObjectToDictionary(routeValues));\n        }\n\n        protected internal RedirectToRouteResult RedirectToActionPermanent(string actionName, RouteValueDictionary routeValues)\n        {\n            return RedirectToActionPermanent(actionName, null /* controllerName */, routeValues);\n        }\n\n        protected internal RedirectToRouteResult RedirectToActionPermanent(string actionName, string controllerName)\n        {\n            return RedirectToActionPermanent(actionName, controllerName, (RouteValueDictionary)null);\n        }\n\n        protected internal RedirectToRouteResult RedirectToActionPermanent(string actionName, string controllerName, object routeValues)\n        {\n            return RedirectToActionPermanent(actionName, controllerName, TypeHelper.ObjectToDictionary(routeValues));\n        }\n\n        protected internal virtual RedirectToRouteResult RedirectToActionPermanent(string actionName, string controllerName, RouteValueDictionary routeValues)\n        {\n            RouteValueDictionary implicitRouteValues = (RouteData != null) ? RouteData.Values : null;\n\n            RouteValueDictionary mergedRouteValues =\n                RouteValuesHelpers.MergeRouteValues(actionName, controllerName, implicitRouteValues, routeValues, includeImplicitMvcValues: true);\n\n            return new RedirectToRouteResult(null, mergedRouteValues, permanent: true);\n        }\n\n        protected internal RedirectToRouteResult RedirectToRoute(object routeValues)\n        {\n            return RedirectToRoute(TypeHelper.ObjectToDictionary(routeValues));\n        }\n\n        protected internal RedirectToRouteResult RedirectToRoute(RouteValueDictionary routeValues)\n        {\n            return RedirectToRoute(null /* routeName */, routeValues);\n        }\n\n        protected internal RedirectToRouteResult RedirectToRoute(string routeName)\n        {\n            return RedirectToRoute(routeName, (RouteValueDictionary)null);\n        }\n\n        protected internal RedirectToRouteResult RedirectToRoute(string routeName, object routeValues)\n        {\n            return RedirectToRoute(routeName, TypeHelper.ObjectToDictionary(routeValues));\n        }\n\n        protected internal virtual RedirectToRouteResult RedirectToRoute(string routeName, RouteValueDictionary routeValues)\n        {\n            return new RedirectToRouteResult(routeName, RouteValuesHelpers.GetRouteValues(routeValues));\n        }\n\n        protected internal RedirectToRouteResult RedirectToRoutePermanent(object routeValues)\n        {\n            return RedirectToRoutePermanent(TypeHelper.ObjectToDictionary(routeValues));\n        }\n\n        protected internal RedirectToRouteResult RedirectToRoutePermanent(RouteValueDictionary routeValues)\n        {\n            return RedirectToRoutePermanent(null /* routeName */, routeValues);\n        }\n\n        protected internal RedirectToRouteResult RedirectToRoutePermanent(string routeName)\n        {\n            return RedirectToRoutePermanent(routeName, (RouteValueDictionary)null);\n        }\n\n        protected internal RedirectToRouteResult RedirectToRoutePermanent(string routeName, object routeValues)\n        {\n            return RedirectToRoutePermanent(routeName, TypeHelper.ObjectToDictionary(routeValues));\n        }\n\n        protected internal virtual RedirectToRouteResult RedirectToRoutePermanent(string routeName, RouteValueDictionary routeValues)\n        {\n            return new RedirectToRouteResult(routeName, RouteValuesHelpers.GetRouteValues(routeValues), permanent: true);\n        }\n\n        protected internal bool TryUpdateModel<TModel>(TModel model) where TModel : class\n        {\n            return TryUpdateModel(model, null, null, null, ValueProvider);\n        }\n\n        protected internal bool TryUpdateModel<TModel>(TModel model, string prefix) where TModel : class\n        {\n            return TryUpdateModel(model, prefix, null, null, ValueProvider);\n        }\n\n        protected internal bool TryUpdateModel<TModel>(TModel model, string[] includeProperties) where TModel : class\n        {\n            return TryUpdateModel(model, null, includeProperties, null, ValueProvider);\n        }\n\n        protected internal bool TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties) where TModel : class\n        {\n            return TryUpdateModel(model, prefix, includeProperties, null, ValueProvider);\n        }\n\n        protected internal bool TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) where TModel : class\n        {\n            return TryUpdateModel(model, prefix, includeProperties, excludeProperties, ValueProvider);\n        }\n\n        protected internal bool TryUpdateModel<TModel>(TModel model, IValueProvider valueProvider) where TModel : class\n        {\n            return TryUpdateModel(model, null, null, null, valueProvider);\n        }\n\n        protected internal bool TryUpdateModel<TModel>(TModel model, string prefix, IValueProvider valueProvider) where TModel : class\n        {\n            return TryUpdateModel(model, prefix, null, null, valueProvider);\n        }\n\n        protected internal bool TryUpdateModel<TModel>(TModel model, string[] includeProperties, IValueProvider valueProvider) where TModel : class\n        {\n            return TryUpdateModel(model, null, includeProperties, null, valueProvider);\n        }\n\n        protected internal bool TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, IValueProvider valueProvider) where TModel : class\n        {\n            return TryUpdateModel(model, prefix, includeProperties, null, valueProvider);\n        }\n\n        protected internal bool TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties, IValueProvider valueProvider) where TModel : class\n        {\n            if (model == null)\n            {\n                throw new ArgumentNullException(\"model\");\n            }\n            if (valueProvider == null)\n            {\n                throw new ArgumentNullException(\"valueProvider\");\n            }\n\n            Predicate<string> propertyFilter = propertyName => BindAttribute.IsPropertyAllowed(propertyName, includeProperties, excludeProperties);\n            IModelBinder binder = Binders.GetBinder(typeof(TModel));\n\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, typeof(TModel)),\n                ModelName = prefix,\n                ModelState = ModelState,\n                PropertyFilter = propertyFilter,\n                ValueProvider = valueProvider\n            };\n            binder.BindModel(ControllerContext, bindingContext);\n            return ModelState.IsValid;\n        }\n\n        protected internal bool TryValidateModel(object model)\n        {\n            return TryValidateModel(model, null /* prefix */);\n        }\n\n        protected internal bool TryValidateModel(object model, string prefix)\n        {\n            if (model == null)\n            {\n                throw new ArgumentNullException(\"model\");\n            }\n\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());\n\n            foreach (ModelValidationResult validationResult in ModelValidator.GetModelValidator(metadata, ControllerContext).Validate(null))\n            {\n                ModelState.AddModelError(DefaultModelBinder.CreateSubPropertyName(prefix, validationResult.MemberName), validationResult.Message);\n            }\n\n            return ModelState.IsValid;\n        }\n\n        protected internal void UpdateModel<TModel>(TModel model) where TModel : class\n        {\n            UpdateModel(model, null, null, null, ValueProvider);\n        }\n\n        protected internal void UpdateModel<TModel>(TModel model, string prefix) where TModel : class\n        {\n            UpdateModel(model, prefix, null, null, ValueProvider);\n        }\n\n        protected internal void UpdateModel<TModel>(TModel model, string[] includeProperties) where TModel : class\n        {\n            UpdateModel(model, null, includeProperties, null, ValueProvider);\n        }\n\n        protected internal void UpdateModel<TModel>(TModel model, string prefix, string[] includeProperties) where TModel : class\n        {\n            UpdateModel(model, prefix, includeProperties, null, ValueProvider);\n        }\n\n        protected internal void UpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) where TModel : class\n        {\n            UpdateModel(model, prefix, includeProperties, excludeProperties, ValueProvider);\n        }\n\n        protected internal void UpdateModel<TModel>(TModel model, IValueProvider valueProvider) where TModel : class\n        {\n            UpdateModel(model, null, null, null, valueProvider);\n        }\n\n        protected internal void UpdateModel<TModel>(TModel model, string prefix, IValueProvider valueProvider) where TModel : class\n        {\n            UpdateModel(model, prefix, null, null, valueProvider);\n        }\n\n        protected internal void UpdateModel<TModel>(TModel model, string[] includeProperties, IValueProvider valueProvider) where TModel : class\n        {\n            UpdateModel(model, null, includeProperties, null, valueProvider);\n        }\n\n        protected internal void UpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, IValueProvider valueProvider) where TModel : class\n        {\n            UpdateModel(model, prefix, includeProperties, null, valueProvider);\n        }\n\n        protected internal void UpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties, IValueProvider valueProvider) where TModel : class\n        {\n            bool success = TryUpdateModel(model, prefix, includeProperties, excludeProperties, valueProvider);\n            if (!success)\n            {\n                string message = String.Format(CultureInfo.CurrentCulture, MvcResources.Controller_UpdateModel_UpdateUnsuccessful,\n                                               typeof(TModel).FullName);\n                throw new InvalidOperationException(message);\n            }\n        }\n\n        protected internal void ValidateModel(object model)\n        {\n            ValidateModel(model, null /* prefix */);\n        }\n\n        protected internal void ValidateModel(object model, string prefix)\n        {\n            if (!TryValidateModel(model, prefix))\n            {\n                throw new InvalidOperationException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.Controller_Validate_ValidationFailed,\n                        model.GetType().FullName));\n            }\n        }\n\n        protected internal ViewResult View()\n        {\n            return View(viewName: null, masterName: null, model: null);\n        }\n\n        protected internal ViewResult View(object model)\n        {\n            return View(null /* viewName */, null /* masterName */, model);\n        }\n\n        protected internal ViewResult View(string viewName)\n        {\n            return View(viewName, masterName: null, model: null);\n        }\n\n        protected internal ViewResult View(string viewName, string masterName)\n        {\n            return View(viewName, masterName, null /* model */);\n        }\n\n        protected internal ViewResult View(string viewName, object model)\n        {\n            return View(viewName, null /* masterName */, model);\n        }\n\n        protected internal virtual ViewResult View(string viewName, string masterName, object model)\n        {\n            if (model != null)\n            {\n                ViewData.Model = model;\n            }\n\n            return new ViewResult\n            {\n                ViewName = viewName,\n                MasterName = masterName,\n                ViewData = ViewData,\n                TempData = TempData,\n                ViewEngineCollection = ViewEngineCollection\n            };\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1719:ParameterNamesShouldNotMatchMemberNames\", MessageId = \"0#\", Justification = \"The method name 'View' is a convenient shorthand for 'CreateViewResult'.\")]\n        protected internal ViewResult View(IView view)\n        {\n            return View(view, null /* model */);\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1719:ParameterNamesShouldNotMatchMemberNames\", MessageId = \"0#\", Justification = \"The method name 'View' is a convenient shorthand for 'CreateViewResult'.\")]\n        protected internal virtual ViewResult View(IView view, object model)\n        {\n            if (model != null)\n            {\n                ViewData.Model = model;\n            }\n\n            return new ViewResult\n            {\n                View = view,\n                ViewData = ViewData,\n                TempData = TempData\n            };\n        }\n\n        IAsyncResult IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, object state)\n        {\n            return BeginExecute(requestContext, callback, state);\n        }\n\n        void IAsyncController.EndExecute(IAsyncResult asyncResult)\n        {\n            EndExecute(asyncResult);\n        }\n\n        protected virtual IAsyncResult BeginExecute(RequestContext requestContext, AsyncCallback callback, object state)\n        {\n            if (DisableAsyncSupport)\n            {\n                // For backwards compat, we can disallow async support and just chain to the sync Execute() function.\n                Action action = () =>\n                {\n                    Execute(requestContext);\n                };\n\n                return AsyncResultWrapper.BeginSynchronous(callback, state, action, _executeTag);\n            }\n            else\n            {\n                if (requestContext == null)\n                {\n                    throw new ArgumentNullException(\"requestContext\");\n                }\n\n                // Support Asynchronous behavior. \n                // Execute/ExecuteCore are no longer called.\n\n                VerifyExecuteCalledOnce();\n                Initialize(requestContext);\n\n                // Ensure delegates continue to use the C# Compiler static delegate caching optimization.\n                BeginInvokeDelegate<Controller> beginDelegate = (AsyncCallback asyncCallback, object callbackState, Controller controller) =>\n                    {\n                        return controller.BeginExecuteCore(asyncCallback, callbackState);\n                    };\n                EndInvokeVoidDelegate<Controller> endDelegate = (IAsyncResult asyncResult, Controller controller) =>\n                    {\n                        controller.EndExecuteCore(asyncResult);\n                    };\n                return AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, this, _executeTag);\n            }\n        }\n\n        protected virtual IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)\n        {\n            // If code in this method needs to be updated, please also check the ExecuteCore() method\n            // of Controller to see if that code also must be updated.\n            PossiblyLoadTempData();\n            try\n            {\n                string actionName = GetActionName(RouteData);\n                IActionInvoker invoker = ActionInvoker;\n                IAsyncActionInvoker asyncInvoker = invoker as IAsyncActionInvoker;\n                if (asyncInvoker != null)\n                {\n                    // asynchronous invocation\n                    // Ensure delegates continue to use the C# Compiler static delegate caching optimization.\n                    BeginInvokeDelegate<ExecuteCoreState> beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState, ExecuteCoreState innerState)\n                    {\n                        return innerState.AsyncInvoker.BeginInvokeAction(innerState.Controller.ControllerContext, innerState.ActionName, asyncCallback, asyncState);\n                    };\n\n                    EndInvokeVoidDelegate<ExecuteCoreState> endDelegate = delegate(IAsyncResult asyncResult, ExecuteCoreState innerState)\n                    {\n                        if (!innerState.AsyncInvoker.EndInvokeAction(asyncResult))\n                        {\n                            innerState.Controller.HandleUnknownAction(innerState.ActionName);\n                        }\n                    };\n                    ExecuteCoreState executeState = new ExecuteCoreState() { Controller = this, AsyncInvoker = asyncInvoker, ActionName = actionName };\n\n                    return AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, executeState, _executeCoreTag);\n                }\n                else\n                {\n                    // synchronous invocation\n                    Action action = () =>\n                    {\n                        if (!invoker.InvokeAction(ControllerContext, actionName))\n                        {\n                            HandleUnknownAction(actionName);\n                        }\n                    };\n                    return AsyncResultWrapper.BeginSynchronous(callback, state, action, _executeCoreTag);\n                }\n            }\n            catch\n            {\n                PossiblySaveTempData();\n                throw;\n            }\n        }\n\n        protected virtual void EndExecute(IAsyncResult asyncResult)\n        {\n            AsyncResultWrapper.End(asyncResult, _executeTag);\n        }\n\n        protected virtual void EndExecuteCore(IAsyncResult asyncResult)\n        {\n            // If code in this method needs to be updated, please also check the ExecuteCore() method\n            // of Controller to see if that code also must be updated.\n\n            try\n            {\n                AsyncResultWrapper.End(asyncResult, _executeCoreTag);\n            }\n            finally\n            {\n                PossiblySaveTempData();\n            }\n        }\n\n        #region IActionFilter Members\n\n        void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)\n        {\n            OnActionExecuting(filterContext);\n        }\n\n        void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)\n        {\n            OnActionExecuted(filterContext);\n        }\n\n        #endregion\n\n        #region IAuthenticationFilter Members\n\n        void IAuthenticationFilter.OnAuthentication(AuthenticationContext filterContext)\n        {\n            OnAuthentication(filterContext);\n        }\n\n        void IAuthenticationFilter.OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)\n        {\n            OnAuthenticationChallenge(filterContext);\n        }\n\n        #endregion\n\n        #region IAuthorizationFilter Members\n\n        void IAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext)\n        {\n            OnAuthorization(filterContext);\n        }\n\n        #endregion\n\n        #region IExceptionFilter Members\n\n        void IExceptionFilter.OnException(ExceptionContext filterContext)\n        {\n            OnException(filterContext);\n        }\n\n        #endregion\n\n        #region IResultFilter Members\n\n        void IResultFilter.OnResultExecuting(ResultExecutingContext filterContext)\n        {\n            OnResultExecuting(filterContext);\n        }\n\n        void IResultFilter.OnResultExecuted(ResultExecutedContext filterContext)\n        {\n            OnResultExecuted(filterContext);\n        }\n\n        #endregion\n\n        // Keep as value type to avoid allocating\n        private struct ExecuteCoreState\n        {\n            internal IAsyncActionInvoker AsyncInvoker;\n            internal Controller Controller;\n            internal string ActionName;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ControllerActionInvoker.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Linq;\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Web.Mvc.Filters;\nusing System.Web.Mvc.Properties;\nusing System.Web.Mvc.Routing;\nusing System.Web.Routing;\nusing Microsoft.Web.Infrastructure.DynamicValidationHelper;\n\nnamespace System.Web.Mvc\n{\n    [SuppressMessage(\n        \"Microsoft.Maintainability\", \n        \"CA1506:AvoidExcessiveClassCoupling\",\n        Justification = \"This class has to work with both traditional and direct routing, which is the cause of the high\" +\n        \"number of classes it uses.\")]\n    public class ControllerActionInvoker : IActionInvoker\n    {\n        private static readonly ControllerDescriptorCache _staticDescriptorCache = new ControllerDescriptorCache();\n\n        private ModelBinderDictionary _binders;\n        private Func<ControllerContext, ActionDescriptor, IEnumerable<Filter>> _getFiltersThunk = FilterProviders.Providers.GetFilters;\n        private ControllerDescriptorCache _instanceDescriptorCache;\n\n        public ControllerActionInvoker()\n        {\n        }\n\n        internal ControllerActionInvoker(params object[] filters)\n            : this()\n        {\n            if (filters != null)\n            {\n                _getFiltersThunk = (cc, ad) => filters.Select(f => new Filter(f, FilterScope.Action, null));\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"Property is settable so that the dictionary can be provided for unit testing purposes.\")]\n        protected internal ModelBinderDictionary Binders\n        {\n            get\n            {\n                if (_binders == null)\n                {\n                    _binders = ModelBinders.Binders;\n                }\n                return _binders;\n            }\n            set { _binders = value; }\n        }\n\n        internal ControllerDescriptorCache DescriptorCache\n        {\n            get\n            {\n                if (_instanceDescriptorCache == null)\n                {\n                    _instanceDescriptorCache = _staticDescriptorCache;\n                }\n                return _instanceDescriptorCache;\n            }\n            set { _instanceDescriptorCache = value; }\n        }\n\n        protected virtual ActionResult CreateActionResult(ControllerContext controllerContext, ActionDescriptor actionDescriptor, object actionReturnValue)\n        {\n            if (actionReturnValue == null)\n            {\n                return new EmptyResult();\n            }\n\n            ActionResult actionResult = (actionReturnValue as ActionResult) ??\n                                        new ContentResult { Content = Convert.ToString(actionReturnValue, CultureInfo.InvariantCulture) };\n            return actionResult;\n        }\n\n        protected virtual ControllerDescriptor GetControllerDescriptor(ControllerContext controllerContext)\n        {\n            // Frequently called, so ensure delegate is static\n            Type controllerType = controllerContext.Controller.GetType();\n            ControllerDescriptor controllerDescriptor = DescriptorCache.GetDescriptor(\n                controllerType: controllerType,\n                creator: (Type innerType) => new ReflectedControllerDescriptor(innerType),\n                state: controllerType);\n            return controllerDescriptor;\n        }\n\n        protected virtual ActionDescriptor FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, string actionName)\n        {\n            Contract.Assert(controllerContext != null);\n            Contract.Assert(controllerContext.RouteData != null);\n            Contract.Assert(controllerDescriptor != null);\n\n            if (controllerContext.RouteData.HasDirectRouteMatch())\n            {\n                List<DirectRouteCandidate> candidates = GetDirectRouteCandidates(controllerContext);\n\n                DirectRouteCandidate bestCandidate = DirectRouteCandidate.SelectBestCandidate(candidates, controllerContext);\n                if (bestCandidate == null)\n                {\n                    return null;\n                }\n                else\n                {\n                    // We need to stash the RouteData of the matched route into the context, so it can be\n                    // used for binding.\n                    controllerContext.RouteData = bestCandidate.RouteData;\n                    controllerContext.RequestContext.RouteData = bestCandidate.RouteData;\n\n                    // We need to remove any optional parameters that haven't gotten a value (See MvcHandler)\n                    bestCandidate.RouteData.Values.RemoveFromDictionary((entry) => entry.Value == UrlParameter.Optional);\n\n                    return bestCandidate.ActionDescriptor;\n                }\n            }\n            else\n            {\n                ActionDescriptor actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName);\n                return actionDescriptor;\n            }\n        }\n\n        private static List<DirectRouteCandidate> GetDirectRouteCandidates(ControllerContext controllerContext)\n        {\n            Debug.Assert(controllerContext != null);\n            Debug.Assert(controllerContext.RouteData != null);\n\n            List<DirectRouteCandidate> candiates = new List<DirectRouteCandidate>();\n\n            RouteData routeData = controllerContext.RouteData;\n            foreach (var directRoute in routeData.GetDirectRouteMatches())\n            {\n                if (directRoute == null)\n                {\n                    continue;\n                }\n\n                ControllerDescriptor controllerDescriptor = directRoute.GetTargetControllerDescriptor();\n                if (controllerDescriptor == null)\n                {\n                    throw new InvalidOperationException(MvcResources.DirectRoute_MissingControllerDescriptor);\n                }\n\n                ActionDescriptor[] actionDescriptors = directRoute.GetTargetActionDescriptors();\n                if (actionDescriptors == null || actionDescriptors.Length == 0)\n                {\n                    throw new InvalidOperationException(MvcResources.DirectRoute_MissingActionDescriptors);\n                }\n\n                foreach (var actionDescriptor in actionDescriptors)\n                {\n                    if (actionDescriptor != null)\n                    {\n                        candiates.Add(new DirectRouteCandidate()\n                        {\n                            ActionDescriptor = actionDescriptor,\n                            ActionNameSelectors = actionDescriptor.GetNameSelectors(),\n                            ActionSelectors = actionDescriptor.GetSelectors(),\n                            Order = directRoute.GetOrder(),\n                            Precedence = directRoute.GetPrecedence(),\n                            RouteData = directRoute,\n                        });\n                    }\n                }\n            }\n\n            return candiates;\n        }\n\n        protected virtual FilterInfo GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)\n        {\n            return new FilterInfo(_getFiltersThunk(controllerContext, actionDescriptor));\n        }\n\n        private IModelBinder GetModelBinder(ParameterDescriptor parameterDescriptor)\n        {\n            // look on the parameter itself, then look in the global table\n            return parameterDescriptor.BindingInfo.Binder ?? Binders.GetBinder(parameterDescriptor.ParameterType);\n        }\n\n        protected virtual object GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor)\n        {\n            // collect all of the necessary binding properties\n            Type parameterType = parameterDescriptor.ParameterType;\n            IModelBinder binder = GetModelBinder(parameterDescriptor);\n            IValueProvider valueProvider = controllerContext.Controller.ValueProvider;\n            string parameterName = parameterDescriptor.BindingInfo.Prefix ?? parameterDescriptor.ParameterName;\n            Predicate<string> propertyFilter = GetPropertyFilter(parameterDescriptor);\n\n            // finally, call into the binder\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                FallbackToEmptyPrefix = (parameterDescriptor.BindingInfo.Prefix == null), // only fall back if prefix not specified\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, parameterType),\n                ModelName = parameterName,\n                ModelState = controllerContext.Controller.ViewData.ModelState,\n                PropertyFilter = propertyFilter,\n                ValueProvider = valueProvider\n            };\n\n            object result = binder.BindModel(controllerContext, bindingContext);\n            return result ?? parameterDescriptor.DefaultValue;\n        }\n\n        protected virtual IDictionary<string, object> GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor)\n        {\n            Dictionary<string, object> parametersDict = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);\n            ParameterDescriptor[] parameterDescriptors = actionDescriptor.GetParameters();\n\n            foreach (ParameterDescriptor parameterDescriptor in parameterDescriptors)\n            {\n                parametersDict[parameterDescriptor.ParameterName] = GetParameterValue(controllerContext, parameterDescriptor);\n            }\n            return parametersDict;\n        }\n\n        private static Predicate<string> GetPropertyFilter(ParameterDescriptor parameterDescriptor)\n        {\n            ParameterBindingInfo bindingInfo = parameterDescriptor.BindingInfo;\n            return propertyName => BindAttribute.IsPropertyAllowed(propertyName, bindingInfo.Include, bindingInfo.Exclude);\n        }\n\n        public virtual bool InvokeAction(ControllerContext controllerContext, string actionName)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n\n            Contract.Assert(controllerContext.RouteData != null);\n            if (String.IsNullOrEmpty(actionName) && !controllerContext.RouteData.HasDirectRouteMatch())\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"actionName\");\n            }\n\n            ControllerDescriptor controllerDescriptor = GetControllerDescriptor(controllerContext);\n            ActionDescriptor actionDescriptor = FindAction(controllerContext, controllerDescriptor, actionName);\n\n            if (actionDescriptor != null)\n            {\n                FilterInfo filterInfo = GetFilters(controllerContext, actionDescriptor);\n\n                try\n                {\n                    AuthenticationContext authenticationContext = InvokeAuthenticationFilters(controllerContext, filterInfo.AuthenticationFilters, actionDescriptor);\n\n                    if (authenticationContext.Result != null)\n                    {\n                        // An authentication filter signaled that we should short-circuit the request. Let all\n                        // authentication filters contribute to an action result (to combine authentication\n                        // challenges). Then, run this action result.\n                        AuthenticationChallengeContext challengeContext = InvokeAuthenticationFiltersChallenge(\n                            controllerContext, filterInfo.AuthenticationFilters, actionDescriptor,\n                            authenticationContext.Result);\n                        InvokeActionResult(controllerContext, challengeContext.Result ?? authenticationContext.Result);\n                    }\n                    else\n                    {\n                        AuthorizationContext authorizationContext = InvokeAuthorizationFilters(controllerContext, filterInfo.AuthorizationFilters, actionDescriptor);\n                        if (authorizationContext.Result != null)\n                        {\n                            // An authorization filter signaled that we should short-circuit the request. Let all\n                            // authentication filters contribute to an action result (to combine authentication\n                            // challenges). Then, run this action result.\n                            AuthenticationChallengeContext challengeContext = InvokeAuthenticationFiltersChallenge(\n                                controllerContext, filterInfo.AuthenticationFilters, actionDescriptor,\n                                authorizationContext.Result);\n                            InvokeActionResult(controllerContext, challengeContext.Result ?? authorizationContext.Result);\n                        }\n                        else\n                        {\n                            if (controllerContext.Controller.ValidateRequest)\n                            {\n                                ValidateRequest(controllerContext);\n                            }\n\n                            IDictionary<string, object> parameters = GetParameterValues(controllerContext, actionDescriptor);\n                            ActionExecutedContext postActionContext = InvokeActionMethodWithFilters(controllerContext, filterInfo.ActionFilters, actionDescriptor, parameters);\n\n                            // The action succeeded. Let all authentication filters contribute to an action result (to\n                            // combine authentication challenges; some authentication filters need to do negotiation\n                            // even on a successful result). Then, run this action result.\n                            AuthenticationChallengeContext challengeContext = InvokeAuthenticationFiltersChallenge(\n                                controllerContext, filterInfo.AuthenticationFilters, actionDescriptor,\n                                postActionContext.Result);\n                            InvokeActionResultWithFilters(controllerContext, filterInfo.ResultFilters,\n                                challengeContext.Result ?? postActionContext.Result);\n                        }\n                    }\n                }\n                catch (ThreadAbortException)\n                {\n                    // This type of exception occurs as a result of Response.Redirect(), but we special-case so that\n                    // the filters don't see this as an error.\n                    throw;\n                }\n                catch (Exception ex)\n                {\n                    // something blew up, so execute the exception filters\n                    ExceptionContext exceptionContext = InvokeExceptionFilters(controllerContext, filterInfo.ExceptionFilters, ex);\n                    if (!exceptionContext.ExceptionHandled)\n                    {\n                        throw;\n                    }\n                    InvokeActionResult(controllerContext, exceptionContext.Result);\n                }\n\n                return true;\n            }\n\n            // notify controller that no method matched\n            return false;\n        }\n\n        protected virtual ActionResult InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters)\n        {\n            object returnValue = actionDescriptor.Execute(controllerContext, parameters);\n            ActionResult result = CreateActionResult(controllerContext, actionDescriptor, returnValue);\n            return result;\n        }\n\n        internal static ActionExecutedContext InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func<ActionExecutedContext> continuation)\n        {\n            filter.OnActionExecuting(preContext);\n            if (preContext.Result != null)\n            {\n                return new ActionExecutedContext(preContext, preContext.ActionDescriptor, true /* canceled */, null /* exception */)\n                {\n                    Result = preContext.Result\n                };\n            }\n\n            bool wasError = false;\n            ActionExecutedContext postContext = null;\n            try\n            {\n                postContext = continuation();\n            }\n            catch (ThreadAbortException)\n            {\n                // This type of exception occurs as a result of Response.Redirect(), but we special-case so that\n                // the filters don't see this as an error.\n                postContext = new ActionExecutedContext(preContext, preContext.ActionDescriptor, false /* canceled */, null /* exception */);\n                filter.OnActionExecuted(postContext);\n                throw;\n            }\n            catch (Exception ex)\n            {\n                wasError = true;\n                postContext = new ActionExecutedContext(preContext, preContext.ActionDescriptor, false /* canceled */, ex);\n                filter.OnActionExecuted(postContext);\n                if (!postContext.ExceptionHandled)\n                {\n                    throw;\n                }\n            }\n            if (!wasError)\n            {\n                filter.OnActionExecuted(postContext);\n            }\n            return postContext;\n        }\n\n        protected virtual ActionExecutedContext InvokeActionMethodWithFilters(ControllerContext controllerContext, IList<IActionFilter> filters, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters)\n        {\n            ActionExecutingContext preContext = new ActionExecutingContext(controllerContext, actionDescriptor, parameters);\n            Func<ActionExecutedContext> continuation = () =>\n                                                       new ActionExecutedContext(controllerContext, actionDescriptor, false /* canceled */, null /* exception */)\n                                                       {\n                                                           Result = InvokeActionMethod(controllerContext, actionDescriptor, parameters)\n                                                       };\n\n            // need to reverse the filter list because the continuations are built up backward\n            Func<ActionExecutedContext> thunk = filters.Reverse().Aggregate(continuation,\n                                                                            (next, filter) => () => InvokeActionMethodFilter(filter, preContext, next));\n            return thunk();\n        }\n\n        protected virtual void InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)\n        {\n            actionResult.ExecuteResult(controllerContext);\n        }\n\n        private ResultExecutedContext InvokeActionResultFilterRecursive(IList<IResultFilter> filters, int filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)\n        {\n            // Performance-sensitive\n\n            // For compatbility, the following behavior must be maintained\n            //   The OnResultExecuting events must fire in forward order\n            //   The InvokeActionResult must then fire\n            //   The OnResultExecuted events must fire in reverse order\n            //   Earlier filters can process the results and exceptions from the handling of later filters\n            // This is achieved by calling recursively and moving through the filter list forwards\n\n            // If there are no more filters to recurse over, create the main result\n            if (filterIndex > filters.Count - 1)\n            {\n                InvokeActionResult(controllerContext, actionResult);\n                return new ResultExecutedContext(controllerContext, actionResult, canceled: false, exception: null);\n            }\n\n            // Otherwise process the filters recursively\n            IResultFilter filter = filters[filterIndex];\n            filter.OnResultExecuting(preContext);\n            if (preContext.Cancel)\n            {\n                return new ResultExecutedContext(preContext, preContext.Result, canceled: true, exception: null);\n            }\n\n            bool wasError = false;\n            ResultExecutedContext postContext = null;\n            try\n            {\n                // Use the filters in forward direction\n                int nextFilterIndex = filterIndex + 1;\n                postContext = InvokeActionResultFilterRecursive(filters, nextFilterIndex, preContext, controllerContext, actionResult);\n            }\n            catch (ThreadAbortException)\n            {\n                // This type of exception occurs as a result of Response.Redirect(), but we special-case so that\n                // the filters don't see this as an error.\n                postContext = new ResultExecutedContext(preContext, preContext.Result, canceled: false, exception: null);\n                filter.OnResultExecuted(postContext);\n                throw;\n            }\n            catch (Exception ex)\n            {\n                wasError = true;\n                postContext = new ResultExecutedContext(preContext, preContext.Result, canceled: false, exception: ex);\n                filter.OnResultExecuted(postContext);\n                if (!postContext.ExceptionHandled)\n                {\n                    throw;\n                }\n            }\n            if (!wasError)\n            {\n                filter.OnResultExecuted(postContext);\n            }\n            return postContext;\n        }\n\n        protected virtual ResultExecutedContext InvokeActionResultWithFilters(ControllerContext controllerContext, IList<IResultFilter> filters, ActionResult actionResult)\n        {\n            ResultExecutingContext preContext = new ResultExecutingContext(controllerContext, actionResult);\n\n            int startingFilterIndex = 0;\n            return InvokeActionResultFilterRecursive(filters, startingFilterIndex, preContext, controllerContext, actionResult);\n        }\n\n        protected virtual AuthenticationContext InvokeAuthenticationFilters(ControllerContext controllerContext,\n            IList<IAuthenticationFilter> filters, ActionDescriptor actionDescriptor)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n\n            Contract.Assert(controllerContext.HttpContext != null);\n            IPrincipal originalPrincipal = controllerContext.HttpContext.User;\n            AuthenticationContext context = new AuthenticationContext(controllerContext, actionDescriptor,\n                originalPrincipal);\n            foreach (IAuthenticationFilter filter in filters)\n            {\n                filter.OnAuthentication(context);\n                // short-circuit evaluation when an error occurs\n                if (context.Result != null)\n                {\n                    break;\n                }\n            }\n\n            IPrincipal newPrincipal = context.Principal;\n\n            if (newPrincipal != originalPrincipal)\n            {\n                Contract.Assert(context.HttpContext != null);\n                context.HttpContext.User = newPrincipal;\n                Thread.CurrentPrincipal = newPrincipal;\n            }\n\n            return context;\n        }\n\n        protected virtual AuthenticationChallengeContext InvokeAuthenticationFiltersChallenge(\n            ControllerContext controllerContext, IList<IAuthenticationFilter> filters,\n            ActionDescriptor actionDescriptor, ActionResult result)\n        {\n            AuthenticationChallengeContext context = new AuthenticationChallengeContext(controllerContext,\n                actionDescriptor, result);\n            foreach (IAuthenticationFilter filter in filters)\n            {\n                filter.OnAuthenticationChallenge(context);\n                // unlike other filter types, don't short-circuit evaluation when context.Result != null (since it\n                // starts out that way, and multiple filters may add challenges to the result)\n            }\n\n            return context;\n        }\n\n        protected virtual AuthorizationContext InvokeAuthorizationFilters(ControllerContext controllerContext, IList<IAuthorizationFilter> filters, ActionDescriptor actionDescriptor)\n        {\n            AuthorizationContext context = new AuthorizationContext(controllerContext, actionDescriptor);\n            foreach (IAuthorizationFilter filter in filters)\n            {\n                filter.OnAuthorization(context);\n                // short-circuit evaluation when an error occurs\n                if (context.Result != null)\n                {\n                    break;\n                }\n            }\n\n            return context;\n        }\n\n        protected virtual ExceptionContext InvokeExceptionFilters(ControllerContext controllerContext, IList<IExceptionFilter> filters, Exception exception)\n        {\n            ExceptionContext context = new ExceptionContext(controllerContext, exception);\n            foreach (IExceptionFilter filter in filters.Reverse())\n            {\n                filter.OnException(context);\n            }\n\n            return context;\n        }\n\n        internal static void ValidateRequest(ControllerContext controllerContext)\n        {\n            if (controllerContext.IsChildAction)\n            {\n                return;\n            }\n\n            // DevDiv 214040: Enable Request Validation by default for all controller requests\n            // \n            // Earlier versions of this method dereferenced Request.RawUrl to force validation of\n            // that field. This was necessary for Routing before ASP.NET v4, which read the incoming\n            // path from RawUrl. Request validation has been moved earlier in the pipeline by default and\n            // routing no longer consumes this property, so we don't have to either.\n\n            // Tolerate null HttpContext for testing\n            HttpContext currentContext = HttpContext.Current;\n            if (currentContext != null)\n            {\n                ValidationUtility.EnableDynamicValidation(currentContext);\n            }\n\n            controllerContext.HttpContext.Request.ValidateInput();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ControllerBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Web.Mvc.Async;\nusing System.Web.Mvc.Properties;\nusing System.Web.Routing;\nusing System.Web.WebPages.Scope;\n\nnamespace System.Web.Mvc\n{\n    public abstract class ControllerBase : IController\n    {\n        private readonly SingleEntryGate _executeWasCalledGate = new SingleEntryGate();\n\n        private DynamicViewDataDictionary _dynamicViewDataDictionary;\n        private TempDataDictionary _tempDataDictionary;\n        private bool _validateRequest = true;\n        private IValueProvider _valueProvider;\n        private ViewDataDictionary _viewDataDictionary;\n\n        public ControllerContext ControllerContext { get; set; }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"This property is settable so that unit tests can provide mock implementations.\")]\n        public TempDataDictionary TempData\n        {\n            get\n            {\n                if (ControllerContext != null && ControllerContext.IsChildAction)\n                {\n                    return ControllerContext.ParentActionViewContext.TempData;\n                }\n                if (_tempDataDictionary == null)\n                {\n                    _tempDataDictionary = new TempDataDictionary();\n                }\n                return _tempDataDictionary;\n            }\n            set { _tempDataDictionary = value; }\n        }\n\n        public bool ValidateRequest\n        {\n            get { return _validateRequest; }\n            set { _validateRequest = value; }\n        }\n\n        public IValueProvider ValueProvider\n        {\n            get\n            {\n                if (_valueProvider == null)\n                {\n                    _valueProvider = ValueProviderFactories.Factories.GetValueProvider(ControllerContext);\n                }\n                return _valueProvider;\n            }\n            set { _valueProvider = value; }\n        }\n\n        public dynamic ViewBag\n        {\n            get\n            {\n                if (_dynamicViewDataDictionary == null)\n                {\n                    _dynamicViewDataDictionary = new DynamicViewDataDictionary(() => ViewData);\n                }\n                return _dynamicViewDataDictionary;\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"This property is settable so that unit tests can provide mock implementations.\")]\n        public ViewDataDictionary ViewData\n        {\n            get\n            {\n                if (_viewDataDictionary == null)\n                {\n                    _viewDataDictionary = new ViewDataDictionary();\n                }\n                return _viewDataDictionary;\n            }\n            set { _viewDataDictionary = value; }\n        }\n\n        protected virtual void Execute(RequestContext requestContext)\n        {\n            if (requestContext == null)\n            {\n                throw new ArgumentNullException(\"requestContext\");\n            }\n            if (requestContext.HttpContext == null)\n            {\n                throw new ArgumentException(MvcResources.ControllerBase_CannotExecuteWithNullHttpContext, \"requestContext\");\n            }\n\n            VerifyExecuteCalledOnce();\n            Initialize(requestContext);\n\n            using (ScopeStorage.CreateTransientScope())\n            {\n                ExecuteCore();\n            }\n        }\n\n        protected abstract void ExecuteCore();\n\n        protected virtual void Initialize(RequestContext requestContext)\n        {\n            ControllerContext = new ControllerContext(requestContext, this);\n        }\n\n        internal void VerifyExecuteCalledOnce()\n        {\n            if (!_executeWasCalledGate.TryEnter())\n            {\n                string message = String.Format(CultureInfo.CurrentCulture, MvcResources.ControllerBase_CannotHandleMultipleRequests, GetType());\n                throw new InvalidOperationException(message);\n            }\n        }\n\n        #region IController Members\n\n        void IController.Execute(RequestContext requestContext)\n        {\n            Execute(requestContext);\n        }\n\n        #endregion\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ControllerBuilder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    public class ControllerBuilder\n    {\n        private static ControllerBuilder _instance = new ControllerBuilder();\n        private Func<IControllerFactory> _factoryThunk = () => null;\n        private HashSet<string> _namespaces = new HashSet<string>(StringComparer.OrdinalIgnoreCase);\n        private IResolver<IControllerFactory> _serviceResolver;\n\n        public ControllerBuilder()\n            : this(null)\n        {\n        }\n\n        internal ControllerBuilder(IResolver<IControllerFactory> serviceResolver)\n        {\n            _serviceResolver = serviceResolver ?? new SingleServiceResolver<IControllerFactory>(\n                                                      () => _factoryThunk(),\n                                                      new DefaultControllerFactory { ControllerBuilder = this },\n                                                      \"ControllerBuilder.GetControllerFactory\");\n        }\n\n        public static ControllerBuilder Current\n        {\n            get { return _instance; }\n        }\n\n        public HashSet<string> DefaultNamespaces\n        {\n            get { return _namespaces; }\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Justification = \"Calling method multiple times might return different objects.\")]\n        public IControllerFactory GetControllerFactory()\n        {\n            return _serviceResolver.Current;\n        }\n\n        public void SetControllerFactory(IControllerFactory controllerFactory)\n        {\n            if (controllerFactory == null)\n            {\n                throw new ArgumentNullException(\"controllerFactory\");\n            }\n\n            _factoryThunk = () => controllerFactory;\n        }\n\n        public void SetControllerFactory(Type controllerFactoryType)\n        {\n            if (controllerFactoryType == null)\n            {\n                throw new ArgumentNullException(\"controllerFactoryType\");\n            }\n            if (!typeof(IControllerFactory).IsAssignableFrom(controllerFactoryType))\n            {\n                throw new ArgumentException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.ControllerBuilder_MissingIControllerFactory,\n                        controllerFactoryType),\n                    \"controllerFactoryType\");\n            }\n\n            _factoryThunk = delegate\n            {\n                try\n                {\n                    return (IControllerFactory)Activator.CreateInstance(controllerFactoryType);\n                }\n                catch (Exception ex)\n                {\n                    throw new InvalidOperationException(\n                        String.Format(\n                            CultureInfo.CurrentCulture,\n                            MvcResources.ControllerBuilder_ErrorCreatingControllerFactory,\n                            controllerFactoryType),\n                        ex);\n                }\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ControllerContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Routing;\nusing System.Web.WebPages;\n\nnamespace System.Web.Mvc\n{\n    // Though many of the properties on ControllerContext and its subclassed types are virtual, there are still sealed\n    // properties (like ControllerContext.RequestContext, ActionExecutingContext.Result, etc.). If these properties\n    // were virtual, a mocking framework might override them with incorrect behavior (property getters would return\n    // null, property setters would be no-ops). By sealing these properties, we are forcing them to have the default\n    // \"get or store a value\" semantics that they were intended to have.\n\n    public class ControllerContext\n    {\n        internal const string ParentActionViewContextToken = \"ParentActionViewContext\";\n        private HttpContextBase _httpContext;\n        private RequestContext _requestContext;\n        private RouteData _routeData;\n\n        // parameterless constructor used for mocking\n        public ControllerContext()\n        {\n        }\n\n        // copy constructor - allows for subclassed types to take an existing ControllerContext as a parameter\n        // and we'll automatically set the appropriate properties\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2214:DoNotCallOverridableMethodsInConstructors\", Justification = \"The virtual property setters are only to support mocking frameworks, in which case this constructor shouldn't be called anyway.\")]\n        protected ControllerContext(ControllerContext controllerContext)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n\n            Controller = controllerContext.Controller;\n            RequestContext = controllerContext.RequestContext;\n        }\n\n        public ControllerContext(HttpContextBase httpContext, RouteData routeData, ControllerBase controller)\n            : this(new RequestContext(httpContext, routeData), controller)\n        {\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2214:DoNotCallOverridableMethodsInConstructors\", Justification = \"The virtual property setters are only to support mocking frameworks, in which case this constructor shouldn't be called anyway.\")]\n        public ControllerContext(RequestContext requestContext, ControllerBase controller)\n        {\n            if (requestContext == null)\n            {\n                throw new ArgumentNullException(\"requestContext\");\n            }\n            if (controller == null)\n            {\n                throw new ArgumentNullException(\"controller\");\n            }\n\n            RequestContext = requestContext;\n            Controller = controller;\n        }\n\n        public virtual ControllerBase Controller { get; set; }\n\n        public IDisplayMode DisplayMode\n        {\n            get { return DisplayModeProvider.GetDisplayMode(HttpContext); }\n            set { DisplayModeProvider.SetDisplayMode(HttpContext, value); }\n        }\n\n        public virtual HttpContextBase HttpContext\n        {\n            get\n            {\n                if (_httpContext == null)\n                {\n                    _httpContext = (_requestContext != null) ? _requestContext.HttpContext : new EmptyHttpContext();\n                }\n                return _httpContext;\n            }\n            set { _httpContext = value; }\n        }\n\n        public virtual bool IsChildAction\n        {\n            get\n            {\n                RouteData routeData = RouteData;\n                if (routeData == null)\n                {\n                    return false;\n                }\n                return routeData.DataTokens.ContainsKey(ParentActionViewContextToken);\n            }\n        }\n\n        public ViewContext ParentActionViewContext\n        {\n            get { return RouteData.DataTokens[ParentActionViewContextToken] as ViewContext; }\n        }\n\n        public RequestContext RequestContext\n        {\n            get\n            {\n                if (_requestContext == null)\n                {\n                    // still need explicit calls to constructors since the property getters are virtual and might return null\n                    HttpContextBase httpContext = HttpContext ?? new EmptyHttpContext();\n                    RouteData routeData = RouteData ?? new RouteData();\n\n                    _requestContext = new RequestContext(httpContext, routeData);\n                }\n                return _requestContext;\n            }\n            set { _requestContext = value; }\n        }\n\n        public virtual RouteData RouteData\n        {\n            get\n            {\n                if (_routeData == null)\n                {\n                    _routeData = (_requestContext != null) ? _requestContext.RouteData : new RouteData();\n                }\n                return _routeData;\n            }\n            set { _routeData = value; }\n        }\n\n        private sealed class EmptyHttpContext : HttpContextBase\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ControllerDescriptor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Reflection;\n\nnamespace System.Web.Mvc\n{\n    public abstract class ControllerDescriptor : ICustomAttributeProvider, IUniquelyIdentifiable\n    {\n        private readonly Lazy<string> _uniqueId;\n\n        protected ControllerDescriptor()\n        {\n            _uniqueId = new Lazy<string>(CreateUniqueId);\n        }\n\n        public virtual string ControllerName\n        {\n            get\n            {\n                string typeName = ControllerType.Name;\n                if (typeName.EndsWith(\"Controller\", StringComparison.OrdinalIgnoreCase))\n                {\n                    return typeName.Substring(0, typeName.Length - \"Controller\".Length);\n                }\n\n                return typeName;\n            }\n        }\n\n        public abstract Type ControllerType { get; }\n\n        [SuppressMessage(\"Microsoft.Security\", \"CA2119:SealMethodsThatSatisfyPrivateInterfaces\", Justification = \"This is overridden elsewhere in System.Web.Mvc\")]\n        public virtual string UniqueId\n        {\n            get { return _uniqueId.Value; }\n        }\n\n        private string CreateUniqueId()\n        {\n            return DescriptorUtil.CreateUniqueId(GetType(), ControllerName, ControllerType);\n        }\n\n        public abstract ActionDescriptor FindAction(ControllerContext controllerContext, string actionName);\n\n        public abstract ActionDescriptor[] GetCanonicalActions();\n\n        public virtual object[] GetCustomAttributes(bool inherit)\n        {\n            return GetCustomAttributes(typeof(object), inherit);\n        }\n\n        public virtual object[] GetCustomAttributes(Type attributeType, bool inherit)\n        {\n            if (attributeType == null)\n            {\n                throw new ArgumentNullException(\"attributeType\");\n            }\n\n            return (object[])Array.CreateInstance(attributeType, 0);\n        }\n\n        public virtual IEnumerable<FilterAttribute> GetFilterAttributes(bool useCache)\n        {\n            return GetCustomAttributes(typeof(FilterAttribute), inherit: true).Cast<FilterAttribute>();\n        }\n\n        public virtual bool IsDefined(Type attributeType, bool inherit)\n        {\n            if (attributeType == null)\n            {\n                throw new ArgumentNullException(\"attributeType\");\n            }\n\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ControllerDescriptorCache.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    internal sealed class ControllerDescriptorCache : ReaderWriterCache<Type, ControllerDescriptor>\n    {\n        public ControllerDescriptorCache()\n        {\n        }\n\n        public ControllerDescriptor GetDescriptor(Type controllerType, Func<ControllerDescriptor> creator)\n        {\n            return FetchOrCreateItem(controllerType, creator);\n        }\n\n        internal ControllerDescriptor GetDescriptor<TArgument>(Type controllerType, Func<TArgument, ControllerDescriptor> creator, TArgument state)\n        {\n            return FetchOrCreateItem(controllerType, creator, state);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ControllerDescriptorExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Reflection;\nusing System.Web.Mvc.Properties;\nusing System.Web.Mvc.Routing;\n\nnamespace System.Web.Mvc\n{\n    internal static class ControllerDescriptorExtensions\n    {\n        public static string GetAreaName(this ControllerDescriptor controllerDescriptor, RouteAreaAttribute area)\n        {\n            if (area == null)\n            {\n                return null;\n            }\n\n            if (area.AreaName != null)\n            {\n                return area.AreaName;\n            }\n            if (controllerDescriptor.ControllerType.Namespace != null)\n            {\n                return controllerDescriptor.ControllerType.Namespace.Split('.').Last();\n            }\n\n            throw Error.InvalidOperation(MvcResources.AttributeRouting_CouldNotInferAreaNameFromMissingNamespace, controllerDescriptor.ControllerName);\n        }\n\n        public static RouteAreaAttribute GetAreaFrom(this ControllerDescriptor controllerDescriptor)\n        {\n            RouteAreaAttribute areaAttribute =\n                controllerDescriptor.GetCustomAttributes(typeof(RouteAreaAttribute), inherit: true)\n                                    .Cast<RouteAreaAttribute>()\n                                    .FirstOrDefault();\n            return areaAttribute;\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Mvc/ControllerInstanceFilterProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Mvc\n{\n    public class ControllerInstanceFilterProvider : IFilterProvider\n    {\n        public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)\n        {\n            if (controllerContext.Controller != null)\n            {\n                // Use FilterScope.First and Order of Int32.MinValue to ensure controller instance methods always run first\n                yield return new Filter(controllerContext.Controller, FilterScope.First, Int32.MinValue);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ControllerTypeCache.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\n\nnamespace System.Web.Mvc\n{\n    internal sealed class ControllerTypeCache\n    {\n        private const string TypeCacheName = \"MVC-ControllerTypeCache.xml\";\n\n        private volatile Dictionary<string, ILookup<string, Type>> _cache;\n        private object _lockObj = new object();\n\n        internal int Count\n        {\n            get\n            {\n                int count = 0;\n                foreach (var lookup in _cache.Values)\n                {\n                    foreach (var grouping in lookup)\n                    {\n                        count += grouping.Count();\n                    }\n                }\n                return count;\n            }\n        }\n\n        internal IReadOnlyList<Type> GetControllerTypes()\n        {\n            return new ReadOnlyCollection<Type>(_cache.Values.SelectMany(lookup => lookup.SelectMany(t => t)).ToList());\n        }\n\n        public void EnsureInitialized(IBuildManager buildManager)\n        {\n            if (_cache == null)\n            {\n                lock (_lockObj)\n                {\n                    if (_cache == null)\n                    {\n                        List<Type> controllerTypes = TypeCacheUtil.GetFilteredTypesFromAssemblies(TypeCacheName, IsControllerType, buildManager);\n                        var groupedByName = controllerTypes.GroupBy(\n                            t => t.Name.Substring(0, t.Name.Length - \"Controller\".Length),\n                            StringComparer.OrdinalIgnoreCase);\n                        _cache = groupedByName.ToDictionary(\n                            g => g.Key,\n                            g => g.ToLookup(t => t.Namespace ?? String.Empty, StringComparer.OrdinalIgnoreCase),\n                            StringComparer.OrdinalIgnoreCase);\n                    }\n                }\n            }\n        }\n\n        public ICollection<Type> GetControllerTypes(string controllerName, HashSet<string> namespaces)\n        {\n            HashSet<Type> matchingTypes = new HashSet<Type>();\n\n            ILookup<string, Type> namespaceLookup;\n            if (_cache.TryGetValue(controllerName, out namespaceLookup))\n            {\n                // this friendly name was located in the cache, now cycle through namespaces\n                if (namespaces != null)\n                {\n                    foreach (string requestedNamespace in namespaces)\n                    {\n                        foreach (var targetNamespaceGrouping in namespaceLookup)\n                        {\n                            if (IsNamespaceMatch(requestedNamespace, targetNamespaceGrouping.Key))\n                            {\n                                matchingTypes.UnionWith(targetNamespaceGrouping);\n                            }\n                        }\n                    }\n                }\n                else\n                {\n                    // if the namespaces parameter is null, search *every* namespace\n                    foreach (var namespaceGroup in namespaceLookup)\n                    {\n                        matchingTypes.UnionWith(namespaceGroup);\n                    }\n                }\n            }\n\n            return matchingTypes;\n        }\n\n        internal static bool IsControllerType(Type t)\n        {\n            return\n                t != null &&\n                t.IsPublic &&\n                t.Name.EndsWith(\"Controller\", StringComparison.OrdinalIgnoreCase) &&\n                !t.IsAbstract &&\n                typeof(IController).IsAssignableFrom(t);\n        }\n\n        internal static bool IsNamespaceMatch(string requestedNamespace, string targetNamespace)\n        {\n            // degenerate cases\n            if (requestedNamespace == null)\n            {\n                return false;\n            }\n            else if (requestedNamespace.Length == 0)\n            {\n                return true;\n            }\n\n            if (!requestedNamespace.EndsWith(\".*\", StringComparison.OrdinalIgnoreCase))\n            {\n                // looking for exact namespace match\n                return String.Equals(requestedNamespace, targetNamespace, StringComparison.OrdinalIgnoreCase);\n            }\n            else\n            {\n                // looking for exact or sub-namespace match\n                requestedNamespace = requestedNamespace.Substring(0, requestedNamespace.Length - \".*\".Length);\n                if (!targetNamespace.StartsWith(requestedNamespace, StringComparison.OrdinalIgnoreCase))\n                {\n                    return false;\n                }\n\n                if (requestedNamespace.Length == targetNamespace.Length)\n                {\n                    // exact match\n                    return true;\n                }\n                else if (targetNamespace[requestedNamespace.Length] == '.')\n                {\n                    // good prefix match, e.g. requestedNamespace = \"Foo.Bar\" and targetNamespace = \"Foo.Bar.Baz\"\n                    return true;\n                }\n                else\n                {\n                    // bad prefix match, e.g. requestedNamespace = \"Foo.Bar\" and targetNamespace = \"Foo.Bar2\"\n                    return false;\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/CopyOnWriteDictionary.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\n\nnamespace System.Web.Mvc\n{\n    /// <summary>\n    /// A <see cref=\"IDictionary{TKey, TValue}\"/> that defers creating a shallow copy of the source dictionary until\n    /// a mutative operation has been performed on it.\n    /// </summary>\n    internal class CopyOnWriteDictionary<TKey, TValue> : IDictionary<TKey, TValue>\n    {\n        private readonly IDictionary<TKey, TValue> _sourceDictionary;\n        private readonly IEqualityComparer<TKey> _comparer;\n        private IDictionary<TKey, TValue> _innerDictionary;\n\n        public CopyOnWriteDictionary(IDictionary<TKey, TValue> sourceDictionary,\n                                     IEqualityComparer<TKey> comparer)\n        {\n            Contract.Assert(sourceDictionary != null);\n            Contract.Assert(comparer != null);\n\n            _sourceDictionary = sourceDictionary;\n            _comparer = comparer;\n        }\n\n        private IDictionary<TKey, TValue> ReadDictionary\n        {\n            get\n            {\n                return _innerDictionary ?? _sourceDictionary;\n            }\n        }\n\n        private IDictionary<TKey, TValue> WriteDictionary\n        {\n            get\n            {\n                if (_innerDictionary == null)\n                {\n                    _innerDictionary = new Dictionary<TKey, TValue>(_sourceDictionary,\n                                                                    _comparer);\n                }\n\n                return _innerDictionary;\n            }\n        }\n\n        public virtual ICollection<TKey> Keys\n        {\n            get\n            {\n                return ReadDictionary.Keys;\n            }\n        }\n\n        public virtual ICollection<TValue> Values\n        {\n            get\n            {\n                return ReadDictionary.Values;\n            }\n        }\n\n        public virtual int Count\n        {\n            get\n            {\n                return ReadDictionary.Count;\n            }\n        }\n\n        public virtual bool IsReadOnly\n        {\n            get\n            {\n                return false;\n            }\n        }\n\n        public virtual TValue this[TKey key]\n        {\n            get\n            {\n                return ReadDictionary[key];\n            }\n            set\n            {\n                WriteDictionary[key] = value;\n            }\n        }\n\n        public virtual bool ContainsKey(TKey key)\n        {\n            return ReadDictionary.ContainsKey(key);\n        }\n\n        public virtual void Add(TKey key, TValue value)\n        {\n            WriteDictionary.Add(key, value);\n        }\n\n        public virtual bool Remove(TKey key)\n        {\n            return WriteDictionary.Remove(key);\n        }\n\n        public virtual bool TryGetValue(TKey key, out TValue value)\n        {\n            return ReadDictionary.TryGetValue(key, out value);\n        }\n\n        public virtual void Add(KeyValuePair<TKey, TValue> item)\n        {\n            WriteDictionary.Add(item);\n        }\n\n        public virtual void Clear()\n        {\n            WriteDictionary.Clear();\n        }\n\n        public virtual bool Contains(KeyValuePair<TKey, TValue> item)\n        {\n            return ReadDictionary.Contains(item);\n        }\n\n        public virtual void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)\n        {\n            ReadDictionary.CopyTo(array, arrayIndex);\n        }\n\n        public bool Remove(KeyValuePair<TKey, TValue> item)\n        {\n            return WriteDictionary.Remove(item);\n        }\n\n        public virtual IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()\n        {\n            return ReadDictionary.GetEnumerator();\n        }\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return GetEnumerator();\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Mvc/CustomModelBinderAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.Mvc\n{\n    [AttributeUsage(ValidTargets, AllowMultiple = false, Inherited = false)]\n    public abstract class CustomModelBinderAttribute : Attribute\n    {\n        internal const AttributeTargets ValidTargets = AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Struct;\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Justification = \"This method can potentially perform a non-trivial amount of work.\")]\n        public abstract IModelBinder GetBinder();\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/DataAnnotationsModelMetadata.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel.DataAnnotations;\nusing System.Globalization;\nusing System.Reflection;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    public class DataAnnotationsModelMetadata : ModelMetadata\n    {\n        private DisplayColumnAttribute _displayColumnAttribute;\n\n        public DataAnnotationsModelMetadata(DataAnnotationsModelMetadataProvider provider, Type containerType,\n                                            Func<object> modelAccessor, Type modelType, string propertyName,\n                                            DisplayColumnAttribute displayColumnAttribute)\n            : base(provider, containerType, modelAccessor, modelType, propertyName)\n        {\n            _displayColumnAttribute = displayColumnAttribute;\n        }\n\n        protected override string GetSimpleDisplayText()\n        {\n            if (Model != null)\n            {\n                if (_displayColumnAttribute != null && !String.IsNullOrEmpty(_displayColumnAttribute.DisplayColumn))\n                {\n                    PropertyInfo displayColumnProperty = ModelType.GetProperty(_displayColumnAttribute.DisplayColumn, BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance);\n                    ValidateDisplayColumnAttribute(_displayColumnAttribute, displayColumnProperty, ModelType);\n\n                    object simpleDisplayTextValue = displayColumnProperty.GetValue(Model, new object[0]);\n                    if (simpleDisplayTextValue != null)\n                    {\n                        return simpleDisplayTextValue.ToString();\n                    }\n                }\n            }\n\n            return base.GetSimpleDisplayText();\n        }\n\n        private static void ValidateDisplayColumnAttribute(DisplayColumnAttribute displayColumnAttribute, PropertyInfo displayColumnProperty, Type modelType)\n        {\n            if (displayColumnProperty == null)\n            {\n                throw new InvalidOperationException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.DataAnnotationsModelMetadataProvider_UnknownProperty,\n                        modelType.FullName, displayColumnAttribute.DisplayColumn));\n            }\n            if (displayColumnProperty.GetGetMethod() == null)\n            {\n                throw new InvalidOperationException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.DataAnnotationsModelMetadataProvider_UnreadableProperty,\n                        modelType.FullName, displayColumnAttribute.DisplayColumn));\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/DataAnnotationsModelMetadataProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\n\nnamespace System.Web.Mvc\n{\n    public class DataAnnotationsModelMetadataProvider : AssociatedMetadataProvider\n    {\n        protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)\n        {\n            List<Attribute> attributeList = new List<Attribute>(attributes);\n            DisplayColumnAttribute displayColumnAttribute = attributeList.OfType<DisplayColumnAttribute>().FirstOrDefault();\n            DataAnnotationsModelMetadata result = new DataAnnotationsModelMetadata(this, containerType, modelAccessor, modelType, propertyName, displayColumnAttribute);\n\n            // Do [HiddenInput] before [UIHint], so you can override the template hint\n            HiddenInputAttribute hiddenInputAttribute = attributeList.OfType<HiddenInputAttribute>().FirstOrDefault();\n            if (hiddenInputAttribute != null)\n            {\n                result.TemplateHint = \"HiddenInput\";\n                result.HideSurroundingHtml = !hiddenInputAttribute.DisplayValue;\n            }\n\n            // We prefer [UIHint(\"...\", PresentationLayer = \"MVC\")] but will fall back to [UIHint(\"...\")]\n            IEnumerable<UIHintAttribute> uiHintAttributes = attributeList.OfType<UIHintAttribute>();\n            UIHintAttribute uiHintAttribute = uiHintAttributes.FirstOrDefault(a => String.Equals(a.PresentationLayer, \"MVC\", StringComparison.OrdinalIgnoreCase))\n                                              ?? uiHintAttributes.FirstOrDefault(a => String.IsNullOrEmpty(a.PresentationLayer));\n            if (uiHintAttribute != null)\n            {\n                result.TemplateHint = uiHintAttribute.UIHint;\n            }\n\n            EditableAttribute editable = attributes.OfType<EditableAttribute>().FirstOrDefault();\n            if (editable != null)\n            {\n                result.IsReadOnly = !editable.AllowEdit;\n            }\n            else\n            {\n                ReadOnlyAttribute readOnlyAttribute = attributeList.OfType<ReadOnlyAttribute>().FirstOrDefault();\n                if (readOnlyAttribute != null)\n                {\n                    result.IsReadOnly = readOnlyAttribute.IsReadOnly;\n                }\n            }\n\n            DataTypeAttribute dataTypeAttribute = attributeList.OfType<DataTypeAttribute>().FirstOrDefault();\n            DisplayFormatAttribute displayFormatAttribute = attributeList.OfType<DisplayFormatAttribute>().FirstOrDefault();\n            SetFromDataTypeAndDisplayAttributes(result, dataTypeAttribute, displayFormatAttribute);\n\n            ScaffoldColumnAttribute scaffoldColumnAttribute = attributeList.OfType<ScaffoldColumnAttribute>().FirstOrDefault();\n            if (scaffoldColumnAttribute != null)\n            {\n                result.ShowForDisplay = result.ShowForEdit = scaffoldColumnAttribute.Scaffold;\n            }\n\n            DisplayAttribute display = attributes.OfType<DisplayAttribute>().FirstOrDefault();\n            string name = null;\n            if (display != null)\n            {\n                result.Description = display.GetDescription();\n                result.ShortDisplayName = display.GetShortName();\n                result.Watermark = display.GetPrompt();\n                result.Order = display.GetOrder() ?? ModelMetadata.DefaultOrder;\n\n                name = display.GetName();\n            }\n\n            if (name != null)\n            {\n                result.DisplayName = name;\n            }\n            else\n            {\n                DisplayNameAttribute displayNameAttribute = attributeList.OfType<DisplayNameAttribute>().FirstOrDefault();\n                if (displayNameAttribute != null)\n                {\n                    result.DisplayName = displayNameAttribute.DisplayName;\n                }\n            }\n\n            RequiredAttribute requiredAttribute = attributeList.OfType<RequiredAttribute>().FirstOrDefault();\n            if (requiredAttribute != null)\n            {\n                result.IsRequired = true;\n            }\n\n            return result;\n        }\n\n        private static void SetFromDataTypeAndDisplayAttributes(DataAnnotationsModelMetadata result,\n            DataTypeAttribute dataTypeAttribute, DisplayFormatAttribute displayFormatAttribute)\n        {\n            if (dataTypeAttribute != null)\n            {\n                result.DataTypeName = dataTypeAttribute.ToDataTypeName();\n            }\n\n            if (displayFormatAttribute == null && dataTypeAttribute != null)\n            {\n                displayFormatAttribute = dataTypeAttribute.DisplayFormat;\n\n                // If DisplayFormat value was non-null and this [DataType] is of a subclass, assume the [DataType]\n                // constructor used the protected DisplayFormat setter to override its default. Note deriving from\n                // [DataType] but preserving DataFormatString and ApplyFormatInEditMode results in\n                // HasNonDefaultEditFormat==true.\n                if (displayFormatAttribute != null && dataTypeAttribute.GetType() != typeof(DataTypeAttribute))\n                {\n                    result.HasNonDefaultEditFormat = true;\n                }\n            }\n            else if (displayFormatAttribute != null)\n            {\n                result.HasNonDefaultEditFormat = true;\n            }\n\n            if (displayFormatAttribute != null)\n            {\n                result.NullDisplayText = displayFormatAttribute.NullDisplayText;\n                result.DisplayFormatString = displayFormatAttribute.DataFormatString;\n                result.ConvertEmptyStringToNull = displayFormatAttribute.ConvertEmptyStringToNull;\n                result.HtmlEncode = displayFormatAttribute.HtmlEncode;\n\n                if (displayFormatAttribute.ApplyFormatInEditMode)\n                {\n                    result.EditFormatString = displayFormatAttribute.DataFormatString;\n                }\n\n                if (!displayFormatAttribute.HtmlEncode && String.IsNullOrWhiteSpace(result.DataTypeName))\n                {\n                    result.DataTypeName = DataTypeUtil.HtmlTypeName;\n                }\n\n                // Regardless of HasNonDefaultEditFormat calculation above, treat missing EditFormatString as the\n                // default.  Note the corner case of a [DataType] subclass overriding a non-empty default to apply a\n                // [DisplayFormat] lacking DataFormatString or with ApplyFormatInEditMode==false results in\n                // HasNonDefaultEditFormat==false.\n                if (String.IsNullOrEmpty(result.EditFormatString))\n                {\n                    result.HasNonDefaultEditFormat = false;\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/DataAnnotationsModelValidator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\n\nnamespace System.Web.Mvc\n{\n    public class DataAnnotationsModelValidator : ModelValidator\n    {\n        public DataAnnotationsModelValidator(ModelMetadata metadata, ControllerContext context, ValidationAttribute attribute)\n            : base(metadata, context)\n        {\n            if (attribute == null)\n            {\n                throw new ArgumentNullException(\"attribute\");\n            }\n\n            Attribute = attribute;\n        }\n\n        protected internal ValidationAttribute Attribute { get; private set; }\n\n        protected internal string ErrorMessage\n        {\n            get { return Attribute.FormatErrorMessage(Metadata.GetDisplayName()); }\n        }\n\n        public override bool IsRequired\n        {\n            get { return Attribute is RequiredAttribute; }\n        }\n\n        internal static ModelValidator Create(ModelMetadata metadata, ControllerContext context, ValidationAttribute attribute)\n        {\n            return new DataAnnotationsModelValidator(metadata, context, attribute);\n        }\n\n        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()\n        {\n            IEnumerable<ModelClientValidationRule> results = base.GetClientValidationRules();\n\n            IClientValidatable clientValidatable = Attribute as IClientValidatable;\n            if (clientValidatable != null)\n            {\n                results = results.Concat(clientValidatable.GetClientValidationRules(Metadata, ControllerContext));\n            }\n\n            return results;\n        }\n\n        public override IEnumerable<ModelValidationResult> Validate(object container)\n        {\n            // Per the WCF RIA Services team, instance can never be null (if you have\n            // no parent, you pass yourself for the \"instance\" parameter).\n            string memberName = Metadata.PropertyName ?? Metadata.ModelType.Name;\n            ValidationContext context = new ValidationContext(container ?? Metadata.Model)\n            {\n                DisplayName = Metadata.GetDisplayName(),\n                MemberName = memberName\n            };\n\n            ValidationResult result = Attribute.GetValidationResult(Metadata.Model, context);\n            if (result != ValidationResult.Success)\n            {\n                // ModelValidationResult.MemberName is used by invoking validators (such as ModelValidator) to \n                // construct the ModelKey for ModelStateDictionary. When validating at type level we want to append the \n                // returned MemberNames if specified (e.g. person.Address.FirstName). For property validation, the \n                // ModelKey can be constructed using the ModelMetadata and we should ignore MemberName (we don't want \n                // (person.Name.Name). However the invoking validator does not have a way to distinguish between these two \n                // cases. Consequently we'll only set MemberName if this validation returns a MemberName that is different\n                // from the property being validated.\n\n                string errorMemberName = result.MemberNames.FirstOrDefault();\n                if (String.Equals(errorMemberName, memberName, StringComparison.Ordinal))\n                {\n                    errorMemberName = null;\n                }\n\n                var validationResult = new ModelValidationResult\n                {\n                    Message = result.ErrorMessage,\n                    MemberName = errorMemberName\n                };\n\n                return new ModelValidationResult[] { validationResult };\n            }\n\n            return Enumerable.Empty<ModelValidationResult>();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/DataAnnotationsModelValidatorOfTAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel.DataAnnotations;\n\nnamespace System.Web.Mvc\n{\n    public class DataAnnotationsModelValidator<TAttribute> : DataAnnotationsModelValidator\n        where TAttribute : ValidationAttribute\n    {\n        public DataAnnotationsModelValidator(ModelMetadata metadata, ControllerContext context, TAttribute attribute)\n            : base(metadata, context, attribute)\n        {\n        }\n\n        protected new TAttribute Attribute\n        {\n            get { return (TAttribute)base.Attribute; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/DataAnnotationsModelValidatorProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Linq;\nusing System.Reflection;\nusing System.Threading;\nusing System.Web.Mvc.Properties;\nusing System.Web.Security;\nusing DataAnnotationsCompareAttribute = System.ComponentModel.DataAnnotations.CompareAttribute;\n\nnamespace System.Web.Mvc\n{\n    // A factory for validators based on ValidationAttribute\n    public delegate ModelValidator DataAnnotationsModelValidationFactory(ModelMetadata metadata, ControllerContext context, ValidationAttribute attribute);\n\n    // A factory for validators based on IValidatableObject\n    public delegate ModelValidator DataAnnotationsValidatableObjectAdapterFactory(ModelMetadata metadata, ControllerContext context);\n\n    /// <summary>\n    /// An implementation of <see cref=\"ModelValidatorProvider\"/> which providers validators\n    /// for attributes which derive from <see cref=\"ValidationAttribute\"/>. It also provides\n    /// a validator for types which implement <see cref=\"IValidatableObject\"/>. To support\n    /// client side validation, you can either register adapters through the static methods\n    /// on this class, or by having your validation attributes implement\n    /// <see cref=\"IClientValidatable\"/>. The logic to support IClientValidatable\n    /// is implemented in <see cref=\"DataAnnotationsModelValidator\"/>.\n    /// </summary>\n    public class DataAnnotationsModelValidatorProvider : AssociatedValidatorProvider\n    {\n        private static bool _addImplicitRequiredAttributeForValueTypes = true;\n        private static ReaderWriterLockSlim _adaptersLock = new ReaderWriterLockSlim();\n\n        // Factories for validation attributes\n\n        internal static DataAnnotationsModelValidationFactory DefaultAttributeFactory =\n            (metadata, context, attribute) => new DataAnnotationsModelValidator(metadata, context, attribute);\n\n        internal static Dictionary<Type, DataAnnotationsModelValidationFactory> AttributeFactories = BuildAttributeFactoriesDictionary();\n\n        // Factories for IValidatableObject models\n\n        internal static DataAnnotationsValidatableObjectAdapterFactory DefaultValidatableFactory =\n            (metadata, context) => new ValidatableObjectAdapter(metadata, context);\n\n        internal static Dictionary<Type, DataAnnotationsValidatableObjectAdapterFactory> ValidatableFactories = new Dictionary<Type, DataAnnotationsValidatableObjectAdapterFactory>();\n\n        public static bool AddImplicitRequiredAttributeForValueTypes\n        {\n            get { return _addImplicitRequiredAttributeForValueTypes; }\n            set { _addImplicitRequiredAttributeForValueTypes = value; }\n        }\n\n        protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)\n        {\n            _adaptersLock.EnterReadLock();\n\n            try\n            {\n                List<ModelValidator> results = new List<ModelValidator>();\n\n                // Add an implied [Required] attribute for any non-nullable value type,\n                // unless they've configured us not to do that.\n                if (AddImplicitRequiredAttributeForValueTypes &&\n                    metadata.IsRequired &&\n                    !attributes.Any(a => a is RequiredAttribute))\n                {\n                    attributes = attributes.Concat(new[] { new RequiredAttribute() });\n                }\n\n                // Produce a validator for each validation attribute we find\n                foreach (ValidationAttribute attribute in attributes.OfType<ValidationAttribute>())\n                {\n                    DataAnnotationsModelValidationFactory factory;\n                    if (!AttributeFactories.TryGetValue(attribute.GetType(), out factory))\n                    {\n                        factory = DefaultAttributeFactory;\n                    }\n                    results.Add(factory(metadata, context, attribute));\n                }\n\n                // Produce a validator if the type supports IValidatableObject\n                if (typeof(IValidatableObject).IsAssignableFrom(metadata.ModelType))\n                {\n                    DataAnnotationsValidatableObjectAdapterFactory factory;\n                    if (!ValidatableFactories.TryGetValue(metadata.ModelType, out factory))\n                    {\n                        factory = DefaultValidatableFactory;\n                    }\n                    results.Add(factory(metadata, context));\n                }\n\n                return results;\n            }\n            finally\n            {\n                _adaptersLock.ExitReadLock();\n            }\n        }\n\n        #region Validation attribute adapter registration\n\n        public static void RegisterAdapter(Type attributeType, Type adapterType)\n        {\n            ValidateAttributeType(attributeType);\n            ValidateAttributeAdapterType(adapterType);\n            ConstructorInfo constructor = GetAttributeAdapterConstructor(attributeType, adapterType);\n\n            _adaptersLock.EnterWriteLock();\n\n            try\n            {\n                AttributeFactories[attributeType] = (metadata, context, attribute) => (ModelValidator)constructor.Invoke(new object[] { metadata, context, attribute });\n            }\n            finally\n            {\n                _adaptersLock.ExitWriteLock();\n            }\n        }\n\n        public static void RegisterAdapterFactory(Type attributeType, DataAnnotationsModelValidationFactory factory)\n        {\n            ValidateAttributeType(attributeType);\n            ValidateAttributeFactory(factory);\n\n            _adaptersLock.EnterWriteLock();\n\n            try\n            {\n                AttributeFactories[attributeType] = factory;\n            }\n            finally\n            {\n                _adaptersLock.ExitWriteLock();\n            }\n        }\n\n        public static void RegisterDefaultAdapter(Type adapterType)\n        {\n            ValidateAttributeAdapterType(adapterType);\n            ConstructorInfo constructor = GetAttributeAdapterConstructor(typeof(ValidationAttribute), adapterType);\n\n            DefaultAttributeFactory = (metadata, context, attribute) => (ModelValidator)constructor.Invoke(new object[] { metadata, context, attribute });\n        }\n\n        public static void RegisterDefaultAdapterFactory(DataAnnotationsModelValidationFactory factory)\n        {\n            ValidateAttributeFactory(factory);\n\n            DefaultAttributeFactory = factory;\n        }\n\n        // Helpers \n\n        private static ConstructorInfo GetAttributeAdapterConstructor(Type attributeType, Type adapterType)\n        {\n            ConstructorInfo constructor = adapterType.GetConstructor(new[] { typeof(ModelMetadata), typeof(ControllerContext), attributeType });\n            if (constructor == null)\n            {\n                throw new ArgumentException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.DataAnnotationsModelValidatorProvider_ConstructorRequirements,\n                        adapterType.FullName,\n                        typeof(ModelMetadata).FullName,\n                        typeof(ControllerContext).FullName,\n                        attributeType.FullName),\n                    \"adapterType\");\n            }\n\n            return constructor;\n        }\n\n        private static void ValidateAttributeAdapterType(Type adapterType)\n        {\n            if (adapterType == null)\n            {\n                throw new ArgumentNullException(\"adapterType\");\n            }\n            if (!typeof(ModelValidator).IsAssignableFrom(adapterType))\n            {\n                throw new ArgumentException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.Common_TypeMustDriveFromType,\n                        adapterType.FullName,\n                        typeof(ModelValidator).FullName),\n                    \"adapterType\");\n            }\n        }\n\n        private static void ValidateAttributeType(Type attributeType)\n        {\n            if (attributeType == null)\n            {\n                throw new ArgumentNullException(\"attributeType\");\n            }\n            if (!typeof(ValidationAttribute).IsAssignableFrom(attributeType))\n            {\n                throw new ArgumentException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.Common_TypeMustDriveFromType,\n                        attributeType.FullName,\n                        typeof(ValidationAttribute).FullName),\n                    \"attributeType\");\n            }\n        }\n\n        private static void ValidateAttributeFactory(DataAnnotationsModelValidationFactory factory)\n        {\n            if (factory == null)\n            {\n                throw new ArgumentNullException(\"factory\");\n            }\n        }\n\n        #endregion\n\n        #region IValidatableObject adapter registration\n\n        /// <summary>\n        /// Registers an adapter type for the given <paramref name=\"modelType\"/>, which must\n        /// implement <see cref=\"IValidatableObject\"/>. The adapter type must derive from\n        /// <see cref=\"ModelValidator\"/> and it must contain a public constructor\n        /// which takes two parameters of types <see cref=\"ModelMetadata\"/> and\n        /// <see cref=\"ControllerContext\"/>.\n        /// </summary>\n        public static void RegisterValidatableObjectAdapter(Type modelType, Type adapterType)\n        {\n            ValidateValidatableModelType(modelType);\n            ValidateValidatableAdapterType(adapterType);\n            ConstructorInfo constructor = GetValidatableAdapterConstructor(adapterType);\n\n            _adaptersLock.EnterWriteLock();\n\n            try\n            {\n                ValidatableFactories[modelType] = (metadata, context) => (ModelValidator)constructor.Invoke(new object[] { metadata, context });\n            }\n            finally\n            {\n                _adaptersLock.ExitWriteLock();\n            }\n        }\n\n        /// <summary>\n        /// Registers an adapter factory for the given <paramref name=\"modelType\"/>, which must\n        /// implement <see cref=\"IValidatableObject\"/>.\n        /// </summary>\n        public static void RegisterValidatableObjectAdapterFactory(Type modelType, DataAnnotationsValidatableObjectAdapterFactory factory)\n        {\n            ValidateValidatableModelType(modelType);\n            ValidateValidatableFactory(factory);\n\n            _adaptersLock.EnterWriteLock();\n\n            try\n            {\n                ValidatableFactories[modelType] = factory;\n            }\n            finally\n            {\n                _adaptersLock.ExitWriteLock();\n            }\n        }\n\n        /// <summary>\n        /// Registers the default adapter type for objects which implement\n        /// <see cref=\"IValidatableObject\"/>. The adapter type must derive from\n        /// <see cref=\"ModelValidator\"/> and it must contain a public constructor\n        /// which takes two parameters of types <see cref=\"ModelMetadata\"/> and\n        /// <see cref=\"ControllerContext\"/>.\n        /// </summary>\n        public static void RegisterDefaultValidatableObjectAdapter(Type adapterType)\n        {\n            ValidateValidatableAdapterType(adapterType);\n            ConstructorInfo constructor = GetValidatableAdapterConstructor(adapterType);\n\n            DefaultValidatableFactory = (metadata, context) => (ModelValidator)constructor.Invoke(new object[] { metadata, context });\n        }\n\n        /// <summary>\n        /// Registers the default adapter factory for objects which implement\n        /// <see cref=\"IValidatableObject\"/>.\n        /// </summary>\n        public static void RegisterDefaultValidatableObjectAdapterFactory(DataAnnotationsValidatableObjectAdapterFactory factory)\n        {\n            ValidateValidatableFactory(factory);\n\n            DefaultValidatableFactory = factory;\n        }\n\n        // Helpers \n\n        private static ConstructorInfo GetValidatableAdapterConstructor(Type adapterType)\n        {\n            ConstructorInfo constructor = adapterType.GetConstructor(new[] { typeof(ModelMetadata), typeof(ControllerContext) });\n            if (constructor == null)\n            {\n                throw new ArgumentException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.DataAnnotationsModelValidatorProvider_ValidatableConstructorRequirements,\n                        adapterType.FullName,\n                        typeof(ModelMetadata).FullName,\n                        typeof(ControllerContext).FullName),\n                    \"adapterType\");\n            }\n\n            return constructor;\n        }\n\n        private static void ValidateValidatableAdapterType(Type adapterType)\n        {\n            if (adapterType == null)\n            {\n                throw new ArgumentNullException(\"adapterType\");\n            }\n            if (!typeof(ModelValidator).IsAssignableFrom(adapterType))\n            {\n                throw new ArgumentException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.Common_TypeMustDriveFromType,\n                        adapterType.FullName,\n                        typeof(ModelValidator).FullName),\n                    \"adapterType\");\n            }\n        }\n\n        private static void ValidateValidatableModelType(Type modelType)\n        {\n            if (modelType == null)\n            {\n                throw new ArgumentNullException(\"modelType\");\n            }\n            if (!typeof(IValidatableObject).IsAssignableFrom(modelType))\n            {\n                throw new ArgumentException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.Common_TypeMustDriveFromType,\n                        modelType.FullName,\n                        typeof(IValidatableObject).FullName),\n                    \"modelType\");\n            }\n        }\n\n        private static void ValidateValidatableFactory(DataAnnotationsValidatableObjectAdapterFactory factory)\n        {\n            if (factory == null)\n            {\n                throw new ArgumentNullException(\"factory\");\n            }\n        }\n\n        #endregion\n\n        private static Dictionary<Type, DataAnnotationsModelValidationFactory> BuildAttributeFactoriesDictionary()\n        {\n            var dict = new Dictionary<Type, DataAnnotationsModelValidationFactory>();\n\n            AddValidationAttributeAdapter(dict, typeof(RangeAttribute),\n                (metadata, context, attribute) => new RangeAttributeAdapter(metadata, context, (RangeAttribute)attribute));\n\n            AddValidationAttributeAdapter(dict, typeof(RegularExpressionAttribute),\n                (metadata, context, attribute) => new RegularExpressionAttributeAdapter(metadata, context, (RegularExpressionAttribute)attribute));\n\n            AddValidationAttributeAdapter(dict, typeof(RequiredAttribute),\n                (metadata, context, attribute) => new RequiredAttributeAdapter(metadata, context, (RequiredAttribute)attribute));\n\n            AddValidationAttributeAdapter(dict, typeof(StringLengthAttribute),\n                (metadata, context, attribute) => new StringLengthAttributeAdapter(metadata, context, (StringLengthAttribute)attribute));\n\n            AddValidationAttributeAdapter(dict, typeof(MaxLengthAttribute),\n                (metadata, context, attribute) => new MaxLengthAttributeAdapter(metadata, context, (MaxLengthAttribute)attribute));\n\n            AddValidationAttributeAdapter(dict, typeof(MinLengthAttribute),\n                (metadata, context, attribute) => new MinLengthAttributeAdapter(metadata, context, (MinLengthAttribute)attribute));\n\n            AddValidationAttributeAdapter(dict, typeof(MembershipPasswordAttribute),\n                    (metadata, context, attribute) => new MembershipPasswordAttributeAdapter(metadata, context, (MembershipPasswordAttribute)attribute));\n\n            AddValidationAttributeAdapter(dict, typeof(DataAnnotationsCompareAttribute),\n                    (metadata, context, attribute) => new CompareAttributeAdapter(metadata, context, (DataAnnotationsCompareAttribute)attribute));\n\n            AddValidationAttributeAdapter(dict, typeof(FileExtensionsAttribute),\n                   (metadata, context, attribute) => new FileExtensionsAttributeAdapter(metadata, context, (FileExtensionsAttribute)attribute));\n\n            AddDataTypeAttributeAdapter(dict, typeof(CreditCardAttribute), \"creditcard\");\n            AddDataTypeAttributeAdapter(dict, typeof(EmailAddressAttribute), \"email\");\n            AddDataTypeAttributeAdapter(dict, typeof(PhoneAttribute), \"phone\");\n            AddDataTypeAttributeAdapter(dict, typeof(UrlAttribute), \"url\");\n\n            return dict;\n        }\n\n        private static void AddValidationAttributeAdapter(Dictionary<Type, DataAnnotationsModelValidationFactory> dictionary, Type validataionAttributeType, DataAnnotationsModelValidationFactory factory)\n        {\n            Contract.Assert(dictionary != null);\n            if (validataionAttributeType != null)\n            {\n                dictionary.Add(validataionAttributeType, factory);\n            }\n        }\n\n        private static void AddDataTypeAttributeAdapter(Dictionary<Type, DataAnnotationsModelValidationFactory> dictionary, Type attributeType, string ruleName)\n        {\n            AddValidationAttributeAdapter(\n                dictionary,\n                attributeType,\n                (metadata, context, attribute) => new DataTypeAttributeAdapter(metadata, context, (DataTypeAttribute)attribute, ruleName));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/DataErrorInfoModelValidatorProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Linq;\n\nnamespace System.Web.Mvc\n{\n    public class DataErrorInfoModelValidatorProvider : ModelValidatorProvider\n    {\n        public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context)\n        {\n            if (metadata == null)\n            {\n                throw new ArgumentNullException(\"metadata\");\n            }\n            if (context == null)\n            {\n                throw new ArgumentNullException(\"context\");\n            }\n\n            return GetValidatorsImpl(metadata, context);\n        }\n\n        private static IEnumerable<ModelValidator> GetValidatorsImpl(ModelMetadata metadata, ControllerContext context)\n        {\n            // If the metadata describes a model that implements IDataErrorInfo, we should call its\n            // Error property at the appropriate time.\n            if (TypeImplementsIDataErrorInfo(metadata.ModelType))\n            {\n                yield return new DataErrorInfoClassModelValidator(metadata, context);\n            }\n\n            // If the metadata describes a property of a container that implements IDataErrorInfo,\n            // we should call its Item indexer at the appropriate time.\n            if (TypeImplementsIDataErrorInfo(metadata.ContainerType))\n            {\n                yield return new DataErrorInfoPropertyModelValidator(metadata, context);\n            }\n        }\n\n        private static bool TypeImplementsIDataErrorInfo(Type type)\n        {\n            return typeof(IDataErrorInfo).IsAssignableFrom(type);\n        }\n\n        internal sealed class DataErrorInfoClassModelValidator : ModelValidator\n        {\n            public DataErrorInfoClassModelValidator(ModelMetadata metadata, ControllerContext controllerContext)\n                : base(metadata, controllerContext)\n            {\n            }\n\n            public override IEnumerable<ModelValidationResult> Validate(object container)\n            {\n                IDataErrorInfo castModel = Metadata.Model as IDataErrorInfo;\n                if (castModel != null)\n                {\n                    string errorMessage = castModel.Error;\n                    if (!String.IsNullOrEmpty(errorMessage))\n                    {\n                        return new ModelValidationResult[]\n                        {\n                            new ModelValidationResult() { Message = errorMessage }\n                        };\n                    }\n                }\n                return Enumerable.Empty<ModelValidationResult>();\n            }\n        }\n\n        internal sealed class DataErrorInfoPropertyModelValidator : ModelValidator\n        {\n            public DataErrorInfoPropertyModelValidator(ModelMetadata metadata, ControllerContext controllerContext)\n                : base(metadata, controllerContext)\n            {\n            }\n\n            public override IEnumerable<ModelValidationResult> Validate(object container)\n            {\n                IDataErrorInfo castContainer = container as IDataErrorInfo;\n                if (castContainer != null && !String.Equals(Metadata.PropertyName, \"error\", StringComparison.OrdinalIgnoreCase))\n                {\n                    string errorMessage = castContainer[Metadata.PropertyName];\n                    if (!String.IsNullOrEmpty(errorMessage))\n                    {\n                        return new ModelValidationResult[]\n                        {\n                            new ModelValidationResult() { Message = errorMessage }\n                        };\n                    }\n                }\n                return Enumerable.Empty<ModelValidationResult>();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/DataTypeAttributeAdapter.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    /// <summary>\n    /// A validation adapter that is used to map <see cref=\"DataTypeAttribute\"/>'s to a single client side validation rule.\n    /// </summary>\n    internal class DataTypeAttributeAdapter : DataAnnotationsModelValidator\n    {\n        public DataTypeAttributeAdapter(ModelMetadata metadata, ControllerContext context, DataTypeAttribute attribute, string ruleName)\n            : base(metadata, context, attribute)\n        {\n            if (String.IsNullOrEmpty(ruleName))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"ruleName\");\n            }\n            RuleName = ruleName;\n        }\n\n        public string RuleName { get; set; }\n\n        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()\n        {\n            yield return new ModelClientValidationRule\n            {\n                ValidationType = RuleName,\n                ErrorMessage = ErrorMessage\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/DataTypeUtil.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\n\nnamespace System.Web.Mvc\n{\n    internal static class DataTypeUtil\n    {\n        private static readonly string CreditCardTypeName = DataType.CreditCard.ToString();\n        private static readonly string CurrencyTypeName = DataType.Currency.ToString();\n        private static readonly string DateTypeName = DataType.Date.ToString();\n        private static readonly string DateTimeTypeName = DataType.DateTime.ToString();\n        private static readonly string DurationTypeName = DataType.Duration.ToString();\n        private static readonly string EmailAddressTypeName = DataType.EmailAddress.ToString();\n        internal static readonly string HtmlTypeName = DataType.Html.ToString();\n        private static readonly string ImageUrlTypeName = DataType.ImageUrl.ToString();\n        private static readonly string MultiLineTextTypeName = DataType.MultilineText.ToString();\n        private static readonly string PasswordTypeName = DataType.Password.ToString();\n        private static readonly string PhoneNumberTypeName = DataType.PhoneNumber.ToString();\n        private static readonly string PostalCodeTypeName = DataType.PostalCode.ToString();\n        private static readonly string TextTypeName = DataType.Text.ToString();\n        private static readonly string TimeTypeName = DataType.Time.ToString();\n        private static readonly string UploadTypeName = DataType.Upload.ToString();\n        private static readonly string UrlTypeName = DataType.Url.ToString();\n\n        private static readonly Lazy<Dictionary<object, string>> _dataTypeToName = new Lazy<Dictionary<object, string>>(CreateDataTypeToName, isThreadSafe: true);\n\n        // This is a faster version of GetDataTypeName(). It internally calls ToString() on the enum\n        // value, which can be quite slow because of value verification.\n        internal static string ToDataTypeName(this DataTypeAttribute attribute, Func<DataTypeAttribute, Boolean> isDataType = null)\n        {\n            if (isDataType == null)\n            {\n                isDataType = t => t.GetType().Equals(typeof(DataTypeAttribute));\n            }\n\n            // GetDataTypeName is virtual, so this is only safe if they haven't derived from DataTypeAttribute.\n            // However, if they derive from DataTypeAttribute, they can help their own perf by overriding GetDataTypeName\n            // and returning an appropriate string without invoking the ToString() on the enum.\n            if (isDataType(attribute))\n            {\n                // Statically known dataTypes are handled separately for performance\n                string name = KnownDataTypeToString(attribute.DataType);\n                if (name == null)\n                {\n                    // Unknown types fallback to a dictionary lookup.\n                    // Code running on .NET 4.5 will not enter this code for statically known data types.\n                    // Versions of .NET greater than 4.5 will enter this code for any new data types added to those frameworks\n                    _dataTypeToName.Value.TryGetValue(attribute.DataType, out name);\n                }\n\n                if (name != null)\n                {\n                    return name;\n                }\n            }\n\n            return attribute.GetDataTypeName();\n        }\n\n        private static string KnownDataTypeToString(DataType dataType)\n        {\n            switch (dataType)\n            {\n                case DataType.CreditCard:\n                    return CreditCardTypeName;\n                case DataType.Currency:\n                    return CurrencyTypeName;\n                case DataType.Date:\n                    return DateTypeName;\n                case DataType.DateTime:\n                    return DateTimeTypeName;\n                case DataType.Duration:\n                    return DurationTypeName;\n                case DataType.EmailAddress:\n                    return EmailAddressTypeName;\n                case DataType.Html:\n                    return HtmlTypeName;\n                case DataType.ImageUrl:\n                    return ImageUrlTypeName;\n                case DataType.MultilineText:\n                    return MultiLineTextTypeName;\n                case DataType.Password:\n                    return PasswordTypeName;\n                case DataType.PhoneNumber:\n                    return PhoneNumberTypeName;\n                case DataType.PostalCode:\n                    return PostalCodeTypeName;\n                case DataType.Text:\n                    return TextTypeName;\n                case DataType.Time:\n                    return TimeTypeName;\n                case DataType.Upload:\n                    return UploadTypeName;\n                case DataType.Url:\n                    return UrlTypeName;\n            }\n\n            return null;\n        }\n\n        private static Dictionary<object, string> CreateDataTypeToName()\n        {\n            Dictionary<object, string> dataTypeToName = new Dictionary<object, string>();\n            foreach (DataType dataTypeValue in Enum.GetValues(typeof(DataType)))\n            {\n                // Don't add to the dictionary any of the statically known types.\n                // This is a workingset size optimization.\n                if (dataTypeValue != DataType.Custom && KnownDataTypeToString(dataTypeValue) == null)\n                {\n                    string name = Enum.GetName(typeof(DataType), dataTypeValue);\n                    dataTypeToName[dataTypeValue] = name;\n                }\n            }\n\n            return dataTypeToName;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/DefaultControllerFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Linq;\nusing System.Reflection;\nusing System.Text;\nusing System.Web.Mvc.Properties;\nusing System.Web.Mvc.Routing;\nusing System.Web.Routing;\nusing System.Web.SessionState;\n\nnamespace System.Web.Mvc\n{\n    public class DefaultControllerFactory : IControllerFactory\n    {\n        private static readonly ConcurrentDictionary<Type, SessionStateBehavior> _sessionStateCache = new ConcurrentDictionary<Type, SessionStateBehavior>();\n        private static ControllerTypeCache _staticControllerTypeCache = new ControllerTypeCache();\n        private IBuildManager _buildManager;\n        private IResolver<IControllerActivator> _activatorResolver;\n        private IControllerActivator _controllerActivator;\n        private ControllerBuilder _controllerBuilder;\n        private ControllerTypeCache _instanceControllerTypeCache;\n\n        public DefaultControllerFactory()\n            : this(null, null, null)\n        {\n        }\n\n        public DefaultControllerFactory(IControllerActivator controllerActivator)\n            : this(controllerActivator, null, null)\n        {\n        }\n\n        internal DefaultControllerFactory(IControllerActivator controllerActivator, IResolver<IControllerActivator> activatorResolver, IDependencyResolver dependencyResolver)\n        {\n            if (controllerActivator != null)\n            {\n                _controllerActivator = controllerActivator;\n            }\n            else\n            {\n                _activatorResolver = activatorResolver ?? new SingleServiceResolver<IControllerActivator>(\n                                                              () => null,\n                                                              new DefaultControllerActivator(dependencyResolver),\n                                                              \"DefaultControllerFactory constructor\");\n            }\n        }\n\n        private IControllerActivator ControllerActivator\n        {\n            get\n            {\n                if (_controllerActivator != null)\n                {\n                    return _controllerActivator;\n                }\n                _controllerActivator = _activatorResolver.Current;\n                return _controllerActivator;\n            }\n        }\n\n        internal IBuildManager BuildManager\n        {\n            get\n            {\n                if (_buildManager == null)\n                {\n                    _buildManager = new BuildManagerWrapper();\n                }\n                return _buildManager;\n            }\n            set { _buildManager = value; }\n        }\n\n        internal ControllerBuilder ControllerBuilder\n        {\n            get { return _controllerBuilder ?? ControllerBuilder.Current; }\n            set { _controllerBuilder = value; }\n        }\n\n        internal ControllerTypeCache ControllerTypeCache\n        {\n            get { return _instanceControllerTypeCache ?? _staticControllerTypeCache; }\n            set { _instanceControllerTypeCache = value; }\n        }\n\n        internal static InvalidOperationException CreateAmbiguousControllerException(RouteBase route, string controllerName, ICollection<Type> matchingTypes)\n        {\n            // we need to generate an exception containing all the controller types\n            StringBuilder typeList = new StringBuilder();\n            foreach (Type matchedType in matchingTypes)\n            {\n                typeList.AppendLine();\n                typeList.Append(matchedType.FullName);\n            }\n\n            string errorText;\n            Route castRoute = route as Route;\n            if (castRoute != null)\n            {\n                errorText = String.Format(CultureInfo.CurrentCulture, MvcResources.DefaultControllerFactory_ControllerNameAmbiguous_WithRouteUrl,\n                                          controllerName, castRoute.Url, typeList, Environment.NewLine);\n            }\n            else\n            {\n                errorText = String.Format(CultureInfo.CurrentCulture, MvcResources.DefaultControllerFactory_ControllerNameAmbiguous_WithoutRouteUrl,\n                                          controllerName, typeList, Environment.NewLine);\n            }\n\n            return new InvalidOperationException(errorText);\n        }\n\n        private static InvalidOperationException CreateDirectRouteAmbiguousControllerException(ICollection<Type> matchingTypes)\n        {\n            // we need to generate an exception containing all the controller types\n            StringBuilder typeList = new StringBuilder();\n            foreach (Type matchedType in matchingTypes)\n            {\n                typeList.AppendLine();\n                typeList.Append(matchedType.FullName);\n            }\n\n            string errorText = String.Format(\n                CultureInfo.CurrentCulture,\n                MvcResources.DefaultControllerFactory_DirectRouteAmbiguous,\n                typeList,\n                Environment.NewLine);\n\n            return new InvalidOperationException(errorText);\n        }\n\n        public virtual IController CreateController(RequestContext requestContext, string controllerName)\n        {\n            if (requestContext == null)\n            {\n                throw new ArgumentNullException(\"requestContext\");\n            }\n\n            if (String.IsNullOrEmpty(controllerName) &&\n                (requestContext.RouteData == null || !requestContext.RouteData.HasDirectRouteMatch()))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"controllerName\");\n            }\n\n            Type controllerType = GetControllerType(requestContext, controllerName);\n            IController controller = GetControllerInstance(requestContext, controllerType);\n            return controller;\n        }\n\n        protected internal virtual IController GetControllerInstance(RequestContext requestContext, Type controllerType)\n        {\n            if (requestContext == null)\n            {\n                throw new ArgumentNullException(\"requestContext\");\n            }\n            if (controllerType == null)\n            {\n                throw new HttpException(404,\n                                        String.Format(\n                                            CultureInfo.CurrentCulture,\n                                            MvcResources.DefaultControllerFactory_NoControllerFound,\n                                            requestContext.HttpContext.Request.Path));\n            }\n            if (!typeof(IController).IsAssignableFrom(controllerType))\n            {\n                throw new ArgumentException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.DefaultControllerFactory_TypeDoesNotSubclassControllerBase,\n                        controllerType),\n                    \"controllerType\");\n            }\n\n            return ControllerActivator.Create(requestContext, controllerType);\n        }\n\n        protected internal virtual SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, Type controllerType)\n        {\n            if (controllerType == null)\n            {\n                return SessionStateBehavior.Default;\n            }\n\n            return _sessionStateCache.GetOrAdd(\n                controllerType,\n                type =>\n                {\n                    var attr = type.GetCustomAttributes(typeof(SessionStateAttribute), inherit: true)\n                        .OfType<SessionStateAttribute>()\n                        .FirstOrDefault();\n\n                    return (attr != null) ? attr.Behavior : SessionStateBehavior.Default;\n                });\n        }\n\n        protected internal virtual Type GetControllerType(RequestContext requestContext, string controllerName)\n        {\n            if (requestContext == null)\n            {\n                throw new ArgumentNullException(\"requestContext\");\n            }\n\n            if (String.IsNullOrEmpty(controllerName) &&\n                (requestContext.RouteData == null || !requestContext.RouteData.HasDirectRouteMatch()))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"controllerName\");\n            }\n\n            RouteData routeData = requestContext.RouteData;\n            if (routeData != null && routeData.HasDirectRouteMatch())\n            {\n                return GetControllerTypeFromDirectRoute(routeData);\n            }\n\n            // first search in the current route's namespace collection\n            object routeNamespacesObj;\n            Type match;\n            if (routeData != null && routeData.DataTokens.TryGetValue(RouteDataTokenKeys.Namespaces, out routeNamespacesObj))\n            {\n                IEnumerable<string> routeNamespaces = routeNamespacesObj as IEnumerable<string>;\n                if (routeNamespaces != null && routeNamespaces.Any())\n                {\n                    HashSet<string> namespaceHash = new HashSet<string>(routeNamespaces, StringComparer.OrdinalIgnoreCase);\n                    match = GetControllerTypeWithinNamespaces(routeData.Route, controllerName, namespaceHash);\n\n                    // the UseNamespaceFallback key might not exist, in which case its value is implicitly \"true\"\n                    if (match != null || false.Equals(routeData.DataTokens[RouteDataTokenKeys.UseNamespaceFallback]))\n                    {\n                        // got a match or the route requested we stop looking\n                        return match;\n                    }\n                }\n            }\n\n            // then search in the application's default namespace collection\n            RouteBase route = routeData == null ? null : routeData.Route;\n            if (ControllerBuilder.DefaultNamespaces.Count > 0)\n            {\n                HashSet<string> namespaceDefaults = new HashSet<string>(ControllerBuilder.DefaultNamespaces, StringComparer.OrdinalIgnoreCase);\n                match = GetControllerTypeWithinNamespaces(route, controllerName, namespaceDefaults);\n                if (match != null)\n                {\n                    return match;\n                }\n            }\n\n            // if all else fails, search every namespace\n            return GetControllerTypeWithinNamespaces(route, controllerName, null /* namespaces */);\n        }\n\n        private static Type GetControllerTypeFromDirectRoute(RouteData routeData)\n        {\n            Contract.Assert(routeData != null);\n\n            var matchingRouteDatas = routeData.GetDirectRouteMatches();\n\n            List<Type> controllerTypes = new List<Type>();\n            foreach (var directRouteData in matchingRouteDatas)\n            {\n                if (directRouteData != null)\n                {\n                    Type controllerType = directRouteData.GetTargetControllerType();\n                    if (controllerType == null)\n                    {\n                        // We don't expect this to happen, but it could happen if some code messes with the \n                        // route data tokens and removes the key we're looking for. \n                        throw new InvalidOperationException(MvcResources.DirectRoute_MissingControllerType);\n                    }\n\n                    if (!controllerTypes.Contains(controllerType))\n                    {\n                        controllerTypes.Add(controllerType);\n                    }\n                }\n            }\n\n            // We only want to handle the case where all matched direct routes refer to the same controller.\n            // Handling the multiple-controllers case would put attribute routing down a totally different\n            // path than traditional routing.\n            if (controllerTypes.Count == 0)\n            {\n                return null;\n            }\n            else if (controllerTypes.Count == 1)\n            {\n                return controllerTypes[0];\n            }\n            else\n            {\n                throw CreateDirectRouteAmbiguousControllerException(controllerTypes);\n            }\n        }\n\n        private Type GetControllerTypeWithinNamespaces(RouteBase route, string controllerName, HashSet<string> namespaces)\n        {\n            // Once the master list of controllers has been created we can quickly index into it\n            ControllerTypeCache.EnsureInitialized(BuildManager);\n\n            ICollection<Type> matchingTypes = ControllerTypeCache.GetControllerTypes(controllerName, namespaces);\n            switch (matchingTypes.Count)\n            {\n                case 0:\n                    // no matching types\n                    return null;\n\n                case 1:\n                    // single matching type\n                    return matchingTypes.First();\n\n                default:\n                    // multiple matching types\n                    throw CreateAmbiguousControllerException(route, controllerName, matchingTypes);\n            }\n        }\n\n        public virtual void ReleaseController(IController controller)\n        {\n            IDisposable disposable = controller as IDisposable;\n            if (disposable != null)\n            {\n                disposable.Dispose();\n            }\n        }\n\n        internal IReadOnlyList<Type> GetControllerTypes()\n        {\n            ControllerTypeCache.EnsureInitialized(BuildManager);\n            return ControllerTypeCache.GetControllerTypes();\n        }\n\n        SessionStateBehavior IControllerFactory.GetControllerSessionBehavior(RequestContext requestContext, string controllerName)\n        {\n            if (requestContext == null)\n            {\n                throw new ArgumentNullException(\"requestContext\");\n            }\n            if (String.IsNullOrEmpty(controllerName))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"controllerName\");\n            }\n\n            Type controllerType = GetControllerType(requestContext, controllerName);\n            return GetControllerSessionBehavior(requestContext, controllerType);\n        }\n\n        private class DefaultControllerActivator : IControllerActivator\n        {\n            private Func<IDependencyResolver> _resolverThunk;\n\n            public DefaultControllerActivator()\n                : this(null)\n            {\n            }\n\n            public DefaultControllerActivator(IDependencyResolver resolver)\n            {\n                if (resolver == null)\n                {\n                    _resolverThunk = () => DependencyResolver.Current;\n                }\n                else\n                {\n                    _resolverThunk = () => resolver;\n                }\n            }\n\n            public IController Create(RequestContext requestContext, Type controllerType)\n            {\n                try\n                {\n                    return (IController)(_resolverThunk().GetService(controllerType) ?? Activator.CreateInstance(controllerType));\n                }\n                catch (Exception ex)\n                {\n                    throw new InvalidOperationException(\n                        String.Format(\n                            CultureInfo.CurrentCulture,\n                            MvcResources.DefaultControllerFactory_ErrorCreatingController,\n                            controllerType),\n                        ex);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/DefaultModelBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq;\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    public class DefaultModelBinder : IModelBinder\n    {\n        private static string _resourceClassKey;\n        private ModelBinderDictionary _binders;\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"Property is settable so that the dictionary can be provided for unit testing purposes.\")]\n        protected internal ModelBinderDictionary Binders\n        {\n            get\n            {\n                if (_binders == null)\n                {\n                    _binders = ModelBinders.Binders;\n                }\n                return _binders;\n            }\n            set { _binders = value; }\n        }\n\n        public static string ResourceClassKey\n        {\n            get { return _resourceClassKey ?? String.Empty; }\n            set { _resourceClassKey = value; }\n        }\n\n        private static void AddValueRequiredMessageToModelState(ControllerContext controllerContext, ModelStateDictionary modelState, string modelStateKey, Type elementType, object value)\n        {\n            if (value == null && !TypeHelpers.TypeAllowsNullValue(elementType) && modelState.IsValidField(modelStateKey))\n            {\n                modelState.AddModelError(modelStateKey, GetValueRequiredResource(controllerContext));\n            }\n        }\n\n        internal void BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, object model)\n        {\n            // need to replace the property filter + model object and create an inner binding context\n            ModelBindingContext newBindingContext = CreateComplexElementalModelBindingContext(controllerContext, bindingContext, model);\n\n            // validation\n            if (OnModelUpdating(controllerContext, newBindingContext))\n            {\n                BindProperties(controllerContext, newBindingContext);\n                OnModelUpdated(controllerContext, newBindingContext);\n            }\n        }\n\n        internal object BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext)\n        {\n            object model = bindingContext.Model;\n            Type modelType = bindingContext.ModelType;\n\n            // if we're being asked to create an array, create a list instead, then coerce to an array after the list is created\n            if (model == null && modelType.IsArray)\n            {\n                Type elementType = modelType.GetElementType();\n                Type listType = typeof(List<>).MakeGenericType(elementType);\n                object collection = CreateModel(controllerContext, bindingContext, listType);\n\n                ModelBindingContext arrayBindingContext = new ModelBindingContext()\n                {\n                    ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => collection, listType),\n                    ModelName = bindingContext.ModelName,\n                    ModelState = bindingContext.ModelState,\n                    PropertyFilter = bindingContext.PropertyFilter,\n                    ValueProvider = bindingContext.ValueProvider\n                };\n                IList list = (IList)UpdateCollection(controllerContext, arrayBindingContext, elementType);\n\n                if (list == null)\n                {\n                    return null;\n                }\n\n                Array array = Array.CreateInstance(elementType, list.Count);\n                list.CopyTo(array, 0);\n                return array;\n            }\n\n            if (model == null)\n            {\n                model = CreateModel(controllerContext, bindingContext, modelType);\n            }\n\n            // special-case IDictionary<,> and ICollection<>\n            Type dictionaryType = TypeHelpers.ExtractGenericInterface(modelType, typeof(IDictionary<,>));\n            if (dictionaryType != null)\n            {\n                Type[] genericArguments = dictionaryType.GetGenericArguments();\n                Type keyType = genericArguments[0];\n                Type valueType = genericArguments[1];\n\n                ModelBindingContext dictionaryBindingContext = new ModelBindingContext()\n                {\n                    ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, modelType),\n                    ModelName = bindingContext.ModelName,\n                    ModelState = bindingContext.ModelState,\n                    PropertyFilter = bindingContext.PropertyFilter,\n                    ValueProvider = bindingContext.ValueProvider\n                };\n                object dictionary = UpdateDictionary(controllerContext, dictionaryBindingContext, keyType, valueType);\n                return dictionary;\n            }\n\n            Type enumerableType = TypeHelpers.ExtractGenericInterface(modelType, typeof(IEnumerable<>));\n            if (enumerableType != null)\n            {\n                Type elementType = enumerableType.GetGenericArguments()[0];\n\n                Type collectionType = typeof(ICollection<>).MakeGenericType(elementType);\n                if (collectionType.IsInstanceOfType(model))\n                {\n                    ModelBindingContext collectionBindingContext = new ModelBindingContext()\n                    {\n                        ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, modelType),\n                        ModelName = bindingContext.ModelName,\n                        ModelState = bindingContext.ModelState,\n                        PropertyFilter = bindingContext.PropertyFilter,\n                        ValueProvider = bindingContext.ValueProvider\n                    };\n                    object collection = UpdateCollection(controllerContext, collectionBindingContext, elementType);\n                    return collection;\n                }\n            }\n\n            // otherwise, just update the properties on the complex type\n            BindComplexElementalModel(controllerContext, bindingContext, model);\n            return model;\n        }\n\n        public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)\n        {\n            RuntimeHelpers.EnsureSufficientExecutionStack();\n\n            if (bindingContext == null)\n            {\n                throw new ArgumentNullException(\"bindingContext\");\n            }\n\n            bool performedFallback = false;\n\n            if (!String.IsNullOrEmpty(bindingContext.ModelName) && !bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName))\n            {\n                // We couldn't find any entry that began with the prefix. If this is the top-level element, fall back\n                // to the empty prefix.\n                if (bindingContext.FallbackToEmptyPrefix)\n                {\n                    bindingContext = new ModelBindingContext()\n                    {\n                        ModelMetadata = bindingContext.ModelMetadata,\n                        ModelState = bindingContext.ModelState,\n                        PropertyFilter = bindingContext.PropertyFilter,\n                        ValueProvider = bindingContext.ValueProvider\n                    };\n                    performedFallback = true;\n                }\n                else\n                {\n                    return null;\n                }\n            }\n\n            // Simple model = int, string, etc.; determined by calling TypeConverter.CanConvertFrom(typeof(string))\n            // or by seeing if a value in the request exactly matches the name of the model we're binding.\n            // Complex type = everything else.\n            if (!performedFallback)\n            {\n                bool performRequestValidation = ShouldPerformRequestValidation(controllerContext, bindingContext);\n                ValueProviderResult valueProviderResult = bindingContext.UnvalidatedValueProvider.GetValue(bindingContext.ModelName, skipValidation: !performRequestValidation);\n                if (valueProviderResult != null)\n                {\n                    return BindSimpleModel(controllerContext, bindingContext, valueProviderResult);\n                }\n            }\n            if (!bindingContext.ModelMetadata.IsComplexType)\n            {\n                return null;\n            }\n\n            return BindComplexModel(controllerContext, bindingContext);\n        }\n\n        private void BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext)\n        {\n            PropertyDescriptorCollection properties = GetModelProperties(controllerContext, bindingContext);\n            Predicate<string> propertyFilter = bindingContext.PropertyFilter;\n\n            // Loop is a performance sensitive codepath so avoid using enumerators.\n            for (int i = 0; i < properties.Count; i++)\n            {\n                PropertyDescriptor property = properties[i];\n                if (ShouldUpdateProperty(property, propertyFilter))\n                {\n                    BindProperty(controllerContext, bindingContext, property);\n                }\n            }\n        }\n\n        protected virtual void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)\n        {\n            // need to skip properties that aren't part of the request, else we might hit a StackOverflowException\n            string fullPropertyKey = CreateSubPropertyName(bindingContext.ModelName, propertyDescriptor.Name);\n            if (!bindingContext.ValueProvider.ContainsPrefix(fullPropertyKey))\n            {\n                return;\n            }\n\n            // call into the property's model binder\n            IModelBinder propertyBinder = Binders.GetBinder(propertyDescriptor.PropertyType);\n            object originalPropertyValue = propertyDescriptor.GetValue(bindingContext.Model);\n            ModelMetadata propertyMetadata = bindingContext.PropertyMetadata[propertyDescriptor.Name];\n            propertyMetadata.Model = originalPropertyValue;\n            ModelBindingContext innerBindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = propertyMetadata,\n                ModelName = fullPropertyKey,\n                ModelState = bindingContext.ModelState,\n                ValueProvider = bindingContext.ValueProvider\n            };\n            object newPropertyValue = GetPropertyValue(controllerContext, innerBindingContext, propertyDescriptor, propertyBinder);\n            propertyMetadata.Model = newPropertyValue;\n\n            // validation\n            ModelState modelState = bindingContext.ModelState[fullPropertyKey];\n            if (modelState == null || modelState.Errors.Count == 0)\n            {\n                if (OnPropertyValidating(controllerContext, bindingContext, propertyDescriptor, newPropertyValue))\n                {\n                    SetProperty(controllerContext, bindingContext, propertyDescriptor, newPropertyValue);\n                    OnPropertyValidated(controllerContext, bindingContext, propertyDescriptor, newPropertyValue);\n                }\n            }\n            else\n            {\n                SetProperty(controllerContext, bindingContext, propertyDescriptor, newPropertyValue);\n\n                // Convert FormatExceptions (type conversion failures) into InvalidValue messages\n                foreach (ModelError error in modelState.Errors.Where(err => String.IsNullOrEmpty(err.ErrorMessage) && err.Exception != null).ToList())\n                {\n                    for (Exception exception = error.Exception; exception != null; exception = exception.InnerException)\n                    {\n                        // We only consider \"known\" type of exception and do not make too aggressive changes here\n                        if (exception is FormatException || exception is OverflowException)\n                        {\n                            string displayName = propertyMetadata.GetDisplayName();\n                            string errorMessageTemplate = GetValueInvalidResource(controllerContext);\n                            string errorMessage = String.Format(CultureInfo.CurrentCulture, errorMessageTemplate, modelState.Value.AttemptedValue, displayName);\n                            modelState.Errors.Remove(error);\n                            modelState.Errors.Add(errorMessage);\n                            break;\n                        }\n                    }\n                }\n            }\n        }\n\n        internal object BindSimpleModel(ControllerContext controllerContext, ModelBindingContext bindingContext, ValueProviderResult valueProviderResult)\n        {\n            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);\n\n            // if the value provider returns an instance of the requested data type, we can just short-circuit\n            // the evaluation and return that instance\n            if (bindingContext.ModelType.IsInstanceOfType(valueProviderResult.RawValue))\n            {\n                return valueProviderResult.RawValue;\n            }\n\n            // since a string is an IEnumerable<char>, we want it to skip the two checks immediately following\n            if (bindingContext.ModelType != typeof(string))\n            {\n                // conversion results in 3 cases, as below\n                if (bindingContext.ModelType.IsArray)\n                {\n                    // case 1: user asked for an array\n                    // ValueProviderResult.ConvertTo() understands array types, so pass in the array type directly\n                    object modelArray = ConvertProviderResult(bindingContext.ModelState, bindingContext.ModelName, valueProviderResult, bindingContext.ModelType);\n                    return modelArray;\n                }\n\n                Type enumerableType = TypeHelpers.ExtractGenericInterface(bindingContext.ModelType, typeof(IEnumerable<>));\n                if (enumerableType != null)\n                {\n                    // case 2: user asked for a collection rather than an array\n                    // need to call ConvertTo() on the array type, then copy the array to the collection\n                    object modelCollection = CreateModel(controllerContext, bindingContext, bindingContext.ModelType);\n                    Type elementType = enumerableType.GetGenericArguments()[0];\n                    Type arrayType = elementType.MakeArrayType();\n                    object modelArray = ConvertProviderResult(bindingContext.ModelState, bindingContext.ModelName, valueProviderResult, arrayType);\n\n                    Type collectionType = typeof(ICollection<>).MakeGenericType(elementType);\n                    if (collectionType.IsInstanceOfType(modelCollection))\n                    {\n                        CollectionHelpers.ReplaceCollection(elementType, modelCollection, modelArray);\n                    }\n                    return modelCollection;\n                }\n            }\n\n            // case 3: user asked for an individual element\n            object model = ConvertProviderResult(bindingContext.ModelState, bindingContext.ModelName, valueProviderResult, bindingContext.ModelType);\n            return model;\n        }\n\n        private static bool CanUpdateReadonlyTypedReference(Type type)\n        {\n            // value types aren't strictly immutable, but because they have copy-by-value semantics\n            // we can't update a value type that is marked readonly\n            if (type.IsValueType)\n            {\n                return false;\n            }\n\n            // arrays are mutable, but because we can't change their length we shouldn't try\n            // to update an array that is referenced readonly\n            if (type.IsArray)\n            {\n                return false;\n            }\n\n            // special-case known common immutable types\n            if (type == typeof(string))\n            {\n                return false;\n            }\n\n            return true;\n        }\n\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1304:SpecifyCultureInfo\", MessageId = \"System.Web.Mvc.ValueProviderResult.ConvertTo(System.Type)\", Justification = \"The target object should make the correct culture determination, not this method.\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We're recording this exception so that we can act on it later.\")]\n        private static object ConvertProviderResult(ModelStateDictionary modelState, string modelStateKey, ValueProviderResult valueProviderResult, Type destinationType)\n        {\n            try\n            {\n                object convertedValue = valueProviderResult.ConvertTo(destinationType);\n                return convertedValue;\n            }\n            catch (Exception ex)\n            {\n                modelState.AddModelError(modelStateKey, ex);\n                return null;\n            }\n        }\n\n        internal ModelBindingContext CreateComplexElementalModelBindingContext(ControllerContext controllerContext, ModelBindingContext bindingContext, object model)\n        {\n            BindAttribute bindAttr = (BindAttribute)GetTypeDescriptor(controllerContext, bindingContext).GetAttributes()[typeof(BindAttribute)];\n            Predicate<string> newPropertyFilter = (bindAttr != null)\n                                                      ? propertyName => bindAttr.IsPropertyAllowed(propertyName) && bindingContext.PropertyFilter(propertyName)\n                                                      : bindingContext.PropertyFilter;\n\n            ModelBindingContext newBindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, bindingContext.ModelType),\n                ModelName = bindingContext.ModelName,\n                ModelState = bindingContext.ModelState,\n                PropertyFilter = newPropertyFilter,\n                ValueProvider = bindingContext.ValueProvider\n            };\n\n            return newBindingContext;\n        }\n\n        protected virtual object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)\n        {\n            // fallback to the type's default constructor\n            Type typeToCreate = modelType;\n\n            // we can understand some collection interfaces, e.g. IList<>, IDictionary<,>\n            if (modelType.IsGenericType)\n            {\n                Type genericTypeDefinition = modelType.GetGenericTypeDefinition();\n                if (genericTypeDefinition == typeof(IDictionary<,>))\n                {\n                    typeToCreate = typeof(Dictionary<,>).MakeGenericType(modelType.GetGenericArguments());\n                }\n                else if (genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>) || genericTypeDefinition == typeof(IList<>))\n                {\n                    typeToCreate = typeof(List<>).MakeGenericType(modelType.GetGenericArguments());\n                }\n            }\n\n            try\n            {\n                return Activator.CreateInstance(typeToCreate);\n            }\n            catch (MissingMethodException exception)\n            {\n                // Ensure thrown exception contains the type name.  Might be down a few levels.\n                MissingMethodException replacementException =\n                    TypeHelpers.EnsureDebuggableException(exception, typeToCreate.FullName);\n                if (replacementException != null)\n                {\n                    throw replacementException;\n                }\n\n                throw;\n            }\n        }\n\n        protected static string CreateSubIndexName(string prefix, int index)\n        {\n            return String.Format(CultureInfo.InvariantCulture, \"{0}[{1}]\", prefix, index);\n        }\n\n        protected static string CreateSubIndexName(string prefix, string index)\n        {\n            return String.Format(CultureInfo.InvariantCulture, \"{0}[{1}]\", prefix, index);\n        }\n\n        protected internal static string CreateSubPropertyName(string prefix, string propertyName)\n        {\n            if (String.IsNullOrEmpty(prefix))\n            {\n                return propertyName;\n            }\n            else if (String.IsNullOrEmpty(propertyName))\n            {\n                return prefix;\n            }\n            else\n            {\n                return prefix + \".\" + propertyName;\n            }\n        }\n\n        protected IEnumerable<PropertyDescriptor> GetFilteredModelProperties(ControllerContext controllerContext, ModelBindingContext bindingContext)\n        {\n            // Performance note: Retain for compatibility only. Faster version inlined\n            PropertyDescriptorCollection properties = GetModelProperties(controllerContext, bindingContext);\n            Predicate<string> propertyFilter = bindingContext.PropertyFilter;\n\n            return from PropertyDescriptor property in properties\n                   where ShouldUpdateProperty(property, propertyFilter)\n                   select property;\n        }\n\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1304:SpecifyCultureInfo\", MessageId = \"System.Web.Mvc.ValueProviderResult.ConvertTo(System.Type)\", Justification = \"ValueProviderResult already handles culture conversion appropriately.\")]\n        private static void GetIndexes(ModelBindingContext bindingContext, out bool stopOnIndexNotFound, out IEnumerable<string> indexes)\n        {\n            string indexKey = CreateSubPropertyName(bindingContext.ModelName, \"index\");\n            ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(indexKey);\n\n            if (valueProviderResult != null)\n            {\n                string[] indexesArray = valueProviderResult.ConvertTo(typeof(string[])) as string[];\n                if (indexesArray != null)\n                {\n                    stopOnIndexNotFound = false;\n                    indexes = indexesArray;\n                    return;\n                }\n            }\n\n            // just use a simple zero-based system\n            stopOnIndexNotFound = true;\n            indexes = GetZeroBasedIndexes();\n        }\n\n        protected virtual PropertyDescriptorCollection GetModelProperties(ControllerContext controllerContext, ModelBindingContext bindingContext)\n        {\n            return GetTypeDescriptor(controllerContext, bindingContext).GetProperties();\n        }\n\n        protected virtual object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)\n        {\n            object value = propertyBinder.BindModel(controllerContext, bindingContext);\n\n            if (bindingContext.ModelMetadata.ConvertEmptyStringToNull && Equals(value, String.Empty))\n            {\n                return null;\n            }\n\n            return value;\n        }\n\n        protected virtual ICustomTypeDescriptor GetTypeDescriptor(ControllerContext controllerContext, ModelBindingContext bindingContext)\n        {\n            return TypeDescriptorHelper.Get(bindingContext.ModelType);\n        }\n\n        // If the user specified a ResourceClassKey try to load the resource they specified.\n        // If the class key is invalid, an exception will be thrown.\n        // If the class key is valid but the resource is not found, it returns null, in which\n        // case it will fall back to the MVC default error message.\n        private static string GetUserResourceString(ControllerContext controllerContext, string resourceName)\n        {\n            string result = null;\n\n            if (!String.IsNullOrEmpty(ResourceClassKey) && (controllerContext != null) && (controllerContext.HttpContext != null))\n            {\n                result = controllerContext.HttpContext.GetGlobalResourceObject(ResourceClassKey, resourceName, CultureInfo.CurrentUICulture) as string;\n            }\n\n            return result;\n        }\n\n        private static string GetValueInvalidResource(ControllerContext controllerContext)\n        {\n            return GetUserResourceString(controllerContext, \"PropertyValueInvalid\") ?? MvcResources.DefaultModelBinder_ValueInvalid;\n        }\n\n        private static string GetValueRequiredResource(ControllerContext controllerContext)\n        {\n            return GetUserResourceString(controllerContext, \"PropertyValueRequired\") ?? MvcResources.DefaultModelBinder_ValueRequired;\n        }\n\n        private static IEnumerable<string> GetZeroBasedIndexes()\n        {\n            int i = 0;\n            while (true)\n            {\n                yield return i.ToString(CultureInfo.InvariantCulture);\n                i++;\n            }\n        }\n\n        protected static bool IsModelValid(ModelBindingContext bindingContext)\n        {\n            if (bindingContext == null)\n            {\n                throw new ArgumentNullException(\"bindingContext\");\n            }\n            if (String.IsNullOrEmpty(bindingContext.ModelName))\n            {\n                return bindingContext.ModelState.IsValid;\n            }\n            return bindingContext.ModelState.IsValidField(bindingContext.ModelName);\n        }\n\n        protected virtual void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)\n        {\n            Dictionary<string, bool> startedValid = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);\n\n            foreach (ModelValidationResult validationResult in ModelValidator.GetModelValidator(bindingContext.ModelMetadata, controllerContext).Validate(null))\n            {\n                string subPropertyName = CreateSubPropertyName(bindingContext.ModelName, validationResult.MemberName);\n\n                if (!startedValid.ContainsKey(subPropertyName))\n                {\n                    startedValid[subPropertyName] = bindingContext.ModelState.IsValidField(subPropertyName);\n                }\n\n                if (startedValid[subPropertyName])\n                {\n                    bindingContext.ModelState.AddModelError(subPropertyName, validationResult.Message);\n                }\n            }\n        }\n\n        protected virtual bool OnModelUpdating(ControllerContext controllerContext, ModelBindingContext bindingContext)\n        {\n            // default implementation does nothing\n            return true;\n        }\n\n        protected virtual void OnPropertyValidated(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)\n        {\n            // default implementation does nothing\n        }\n\n        protected virtual bool OnPropertyValidating(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)\n        {\n            // default implementation does nothing\n            return true;\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We're recording this exception so that we can act on it later.\")]\n        protected virtual void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)\n        {\n            ModelMetadata propertyMetadata = bindingContext.PropertyMetadata[propertyDescriptor.Name];\n            propertyMetadata.Model = value;\n            string modelStateKey = CreateSubPropertyName(bindingContext.ModelName, propertyMetadata.PropertyName);\n\n            // If the value is null, and the validation system can find a Required validator for\n            // us, we'd prefer to run it before we attempt to set the value; otherwise, property\n            // setters which throw on null (f.e., Entity Framework properties which are backed by\n            // non-nullable strings in the DB) will get their error message in ahead of us.\n            //\n            // We are effectively using the special validator -- Required -- as a helper to the\n            // binding system, which is why this code is here instead of in the Validating/Validated\n            // methods, which are really the old-school validation hooks.\n            if (value == null && bindingContext.ModelState.IsValidField(modelStateKey))\n            {\n                ModelValidator requiredValidator = ModelValidatorProviders.Providers.GetValidators(propertyMetadata, controllerContext).Where(v => v.IsRequired).FirstOrDefault();\n                if (requiredValidator != null)\n                {\n                    foreach (ModelValidationResult validationResult in requiredValidator.Validate(bindingContext.Model))\n                    {\n                        bindingContext.ModelState.AddModelError(modelStateKey, validationResult.Message);\n                    }\n                }\n            }\n\n            bool isNullValueOnNonNullableType =\n                value == null &&\n                !TypeHelpers.TypeAllowsNullValue(propertyDescriptor.PropertyType);\n\n            // Try to set a value into the property unless we know it will fail (read-only\n            // properties and null values with non-nullable types)\n            if (!propertyDescriptor.IsReadOnly && !isNullValueOnNonNullableType)\n            {\n                try\n                {\n                    propertyDescriptor.SetValue(bindingContext.Model, value);\n                }\n                catch (Exception ex)\n                {\n                    // Only add if we're not already invalid\n                    if (bindingContext.ModelState.IsValidField(modelStateKey))\n                    {\n                        bindingContext.ModelState.AddModelError(modelStateKey, ex);\n                    }\n                }\n            }\n\n            // Last chance for an error on null values with non-nullable types, we'll use\n            // the default \"A value is required.\" message.\n            if (isNullValueOnNonNullableType && bindingContext.ModelState.IsValidField(modelStateKey))\n            {\n                bindingContext.ModelState.AddModelError(modelStateKey, GetValueRequiredResource(controllerContext));\n            }\n        }\n\n        private static bool ShouldPerformRequestValidation(ControllerContext controllerContext, ModelBindingContext bindingContext)\n        {\n            if (controllerContext == null || controllerContext.Controller == null || bindingContext == null || bindingContext.ModelMetadata == null)\n            {\n                // To make unit testing easier, if the caller hasn't specified enough contextual information we just default\n                // to always pulling the data from a collection that goes through request validation.\n                return true;\n            }\n\n            // We should perform request validation only if both the controller and the model ask for it. This is the\n            // default behavior for both. If either the controller (via [ValidateInput(false)]) or the model (via [AllowHtml])\n            // opts out, we don't validate.\n            return (controllerContext.Controller.ValidateRequest && bindingContext.ModelMetadata.RequestValidationEnabled);\n        }\n\n        private static bool ShouldUpdateProperty(PropertyDescriptor property, Predicate<string> propertyFilter)\n        {\n            if (property.IsReadOnly && !CanUpdateReadonlyTypedReference(property.PropertyType))\n            {\n                return false;\n            }\n\n            // if this property is rejected by the filter, move on\n            if (!propertyFilter(property.Name))\n            {\n                return false;\n            }\n\n            // otherwise, allow\n            return true;\n        }\n\n        internal object UpdateCollection(ControllerContext controllerContext, ModelBindingContext bindingContext, Type elementType)\n        {\n            bool stopOnIndexNotFound;\n            IEnumerable<string> indexes;\n            GetIndexes(bindingContext, out stopOnIndexNotFound, out indexes);\n            IModelBinder elementBinder = Binders.GetBinder(elementType);\n\n            // build up a list of items from the request\n            List<object> modelList = new List<object>();\n            foreach (string currentIndex in indexes)\n            {\n                string subIndexKey = CreateSubIndexName(bindingContext.ModelName, currentIndex);\n                if (!bindingContext.ValueProvider.ContainsPrefix(subIndexKey))\n                {\n                    if (stopOnIndexNotFound)\n                    {\n                        // we ran out of elements to pull\n                        break;\n                    }\n                    else\n                    {\n                        continue;\n                    }\n                }\n\n                ModelBindingContext innerContext = new ModelBindingContext()\n                {\n                    ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, elementType),\n                    ModelName = subIndexKey,\n                    ModelState = bindingContext.ModelState,\n                    PropertyFilter = bindingContext.PropertyFilter,\n                    ValueProvider = bindingContext.ValueProvider\n                };\n                object thisElement = elementBinder.BindModel(controllerContext, innerContext);\n\n                // we need to merge model errors up\n                AddValueRequiredMessageToModelState(controllerContext, bindingContext.ModelState, subIndexKey, elementType, thisElement);\n                modelList.Add(thisElement);\n            }\n\n            // if there weren't any elements at all in the request, just return\n            if (modelList.Count == 0)\n            {\n                return null;\n            }\n\n            // replace the original collection\n            object collection = bindingContext.Model;\n            CollectionHelpers.ReplaceCollection(elementType, collection, modelList);\n            return collection;\n        }\n\n        internal object UpdateDictionary(ControllerContext controllerContext, ModelBindingContext bindingContext, Type keyType, Type valueType)\n        {\n            bool stopOnIndexNotFound;\n            IEnumerable<string> indexes;\n            GetIndexes(bindingContext, out stopOnIndexNotFound, out indexes);\n\n            IModelBinder keyBinder = Binders.GetBinder(keyType);\n            IModelBinder valueBinder = Binders.GetBinder(valueType);\n\n            // build up a list of items from the request\n            List<KeyValuePair<object, object>> modelList = new List<KeyValuePair<object, object>>();\n            foreach (string currentIndex in indexes)\n            {\n                string subIndexKey = CreateSubIndexName(bindingContext.ModelName, currentIndex);\n                string keyFieldKey = CreateSubPropertyName(subIndexKey, \"key\");\n                string valueFieldKey = CreateSubPropertyName(subIndexKey, \"value\");\n\n                if (!(bindingContext.ValueProvider.ContainsPrefix(keyFieldKey) && bindingContext.ValueProvider.ContainsPrefix(valueFieldKey)))\n                {\n                    if (stopOnIndexNotFound)\n                    {\n                        // we ran out of elements to pull\n                        break;\n                    }\n                    else\n                    {\n                        continue;\n                    }\n                }\n\n                // bind the key\n                ModelBindingContext keyBindingContext = new ModelBindingContext()\n                {\n                    ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, keyType),\n                    ModelName = keyFieldKey,\n                    ModelState = bindingContext.ModelState,\n                    ValueProvider = bindingContext.ValueProvider\n                };\n                object thisKey = keyBinder.BindModel(controllerContext, keyBindingContext);\n\n                // we need to merge model errors up\n                AddValueRequiredMessageToModelState(controllerContext, bindingContext.ModelState, keyFieldKey, keyType, thisKey);\n                if (!keyType.IsInstanceOfType(thisKey))\n                {\n                    // we can't add an invalid key, so just move on\n                    continue;\n                }\n\n                // bind the value\n                modelList.Add(CreateEntryForModel(controllerContext, bindingContext, valueType, valueBinder, valueFieldKey, thisKey));\n            }\n\n            // Let's try another method\n            if (modelList.Count == 0)\n            {\n                IEnumerableValueProvider enumerableValueProvider = bindingContext.ValueProvider as IEnumerableValueProvider;\n                if (enumerableValueProvider != null)\n                {\n                    IDictionary<string, string> keys = enumerableValueProvider.GetKeysFromPrefix(bindingContext.ModelName);\n                    foreach (var thisKey in keys)\n                    {\n                        modelList.Add(CreateEntryForModel(controllerContext, bindingContext, valueType, valueBinder, thisKey.Value, thisKey.Key));\n                    }\n                }\n            }\n\n            // replace the original collection\n            object dictionary = bindingContext.Model;\n            CollectionHelpers.ReplaceDictionary(keyType, valueType, dictionary, modelList);\n            return dictionary;\n        }\n\n        private static KeyValuePair<object, object> CreateEntryForModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type valueType, IModelBinder valueBinder, string modelName, object modelKey)\n        {\n            ModelBindingContext valueBindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, valueType),\n                ModelName = modelName,\n                ModelState = bindingContext.ModelState,\n                PropertyFilter = bindingContext.PropertyFilter,\n                ValueProvider = bindingContext.ValueProvider\n            };\n            object thisValue = valueBinder.BindModel(controllerContext, valueBindingContext);\n            AddValueRequiredMessageToModelState(controllerContext, bindingContext.ModelState, modelName, valueType, thisValue);\n            return new KeyValuePair<object, object>(modelKey, thisValue);\n        }\n\n        // This helper type is used because we're working with strongly-typed collections, but we don't know the Ts\n        // ahead of time. By using the generic methods below, we can consolidate the collection-specific code in a\n        // single helper type rather than having reflection-based calls spread throughout the DefaultModelBinder type.\n        // There is a single point of entry to each of the methods below, so they're fairly simple to maintain.\n\n        private static class CollectionHelpers\n        {\n            private static readonly MethodInfo _replaceCollectionMethod = typeof(CollectionHelpers).GetMethod(\"ReplaceCollectionImpl\", BindingFlags.Static | BindingFlags.NonPublic);\n            private static readonly MethodInfo _replaceDictionaryMethod = typeof(CollectionHelpers).GetMethod(\"ReplaceDictionaryImpl\", BindingFlags.Static | BindingFlags.NonPublic);\n\n            [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]\n            public static void ReplaceCollection(Type collectionType, object collection, object newContents)\n            {\n                MethodInfo targetMethod = _replaceCollectionMethod.MakeGenericMethod(collectionType);\n                targetMethod.Invoke(null, new object[] { collection, newContents });\n            }\n\n            private static void ReplaceCollectionImpl<T>(ICollection<T> collection, IEnumerable newContents)\n            {\n                collection.Clear();\n                if (newContents != null)\n                {\n                    foreach (object item in newContents)\n                    {\n                        // if the item was not a T, some conversion failed. the error message will be propagated,\n                        // but in the meanwhile we need to make a placeholder element in the array.\n                        T castItem = (item is T) ? (T)item : default(T);\n                        collection.Add(castItem);\n                    }\n                }\n            }\n\n            [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]\n            public static void ReplaceDictionary(Type keyType, Type valueType, object dictionary, object newContents)\n            {\n                MethodInfo targetMethod = _replaceDictionaryMethod.MakeGenericMethod(keyType, valueType);\n                targetMethod.Invoke(null, new object[] { dictionary, newContents });\n            }\n\n            private static void ReplaceDictionaryImpl<TKey, TValue>(IDictionary<TKey, TValue> dictionary, IEnumerable<KeyValuePair<object, object>> newContents)\n            {\n                dictionary.Clear();\n                foreach (KeyValuePair<object, object> item in newContents)\n                {\n                    if (item.Key is TKey)\n                    {\n                        // if the item was not a T, some conversion failed. the error message will be propagated,\n                        // but in the meanwhile we need to make a placeholder element in the dictionary.\n                        TKey castKey = (TKey)item.Key; // this cast shouldn't fail\n                        TValue castValue = (item.Value is TValue) ? (TValue)item.Value : default(TValue);\n                        dictionary[castKey] = castValue;\n                    }\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/DefaultViewLocationCache.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Caching;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    public class DefaultViewLocationCache : IViewLocationCache\n    {\n        private static readonly TimeSpan _defaultTimeSpan = new TimeSpan(0, 15, 0);\n\n        [SuppressMessage(\"Microsoft.Security\", \"CA2104:DoNotDeclareReadOnlyMutableReferenceTypes\", Justification = \"The reference type is immutable. \")]\n        public static readonly IViewLocationCache Null = new NullViewLocationCache();\n\n        public DefaultViewLocationCache()\n            : this(_defaultTimeSpan)\n        {\n        }\n\n        public DefaultViewLocationCache(TimeSpan timeSpan)\n        {\n            if (timeSpan.Ticks < 0)\n            {\n                throw new InvalidOperationException(MvcResources.DefaultViewLocationCache_NegativeTimeSpan);\n            }\n            TimeSpan = timeSpan;\n        }\n\n        public TimeSpan TimeSpan { get; private set; }\n\n        #region IViewLocationCache Members\n\n        public string GetViewLocation(HttpContextBase httpContext, string key)\n        {\n            if (httpContext == null)\n            {\n                throw new ArgumentNullException(\"httpContext\");\n            }\n            return (string)httpContext.Cache[key];\n        }\n\n        public void InsertViewLocation(HttpContextBase httpContext, string key, string virtualPath)\n        {\n            if (httpContext == null)\n            {\n                throw new ArgumentNullException(\"httpContext\");\n            }\n            httpContext.Cache.Insert(key, virtualPath, null /* dependencies */, Cache.NoAbsoluteExpiration, TimeSpan);\n        }\n\n        #endregion\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/DependencyResolver.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq;\nusing System.Reflection;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    public class DependencyResolver\n    {\n        private static DependencyResolver _instance = new DependencyResolver();\n\n        private IDependencyResolver _current;\n\n        /// <summary>\n        /// Cache should always be a new CacheDependencyResolver(_current).\n        /// </summary>\n        private CacheDependencyResolver _currentCache;\n\n        public DependencyResolver()\n        {\n            InnerSetResolver(new DefaultDependencyResolver());\n        }\n\n        public static IDependencyResolver Current\n        {\n            get { return _instance.InnerCurrent; }\n        }\n\n        internal static IDependencyResolver CurrentCache\n        {\n            get { return _instance.InnerCurrentCache; }\n        }\n\n        public IDependencyResolver InnerCurrent\n        {\n            get { return _current; }\n        }\n\n        /// <summary>\n        /// Provides caching over results returned by Current.\n        /// </summary>\n        internal IDependencyResolver InnerCurrentCache\n        {\n            get { return _currentCache; }\n        }\n\n        public static void SetResolver(IDependencyResolver resolver)\n        {\n            _instance.InnerSetResolver(resolver);\n        }\n\n        public static void SetResolver(object commonServiceLocator)\n        {\n            _instance.InnerSetResolver(commonServiceLocator);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types.\")]\n        public static void SetResolver(Func<Type, object> getService, Func<Type, IEnumerable<object>> getServices)\n        {\n            _instance.InnerSetResolver(getService, getServices);\n        }\n\n        public void InnerSetResolver(IDependencyResolver resolver)\n        {\n            if (resolver == null)\n            {\n                throw new ArgumentNullException(\"resolver\");\n            }\n\n            _current = resolver;\n            _currentCache = new CacheDependencyResolver(_current);\n        }\n\n        public void InnerSetResolver(object commonServiceLocator)\n        {\n            if (commonServiceLocator == null)\n            {\n                throw new ArgumentNullException(\"commonServiceLocator\");\n            }\n\n            Type locatorType = commonServiceLocator.GetType();\n            MethodInfo getInstance = locatorType.GetMethod(\"GetInstance\", new[] { typeof(Type) });\n            MethodInfo getInstances = locatorType.GetMethod(\"GetAllInstances\", new[] { typeof(Type) });\n\n            if (getInstance == null ||\n                getInstance.ReturnType != typeof(object) ||\n                getInstances == null ||\n                getInstances.ReturnType != typeof(IEnumerable<object>))\n            {\n                throw new ArgumentException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.DependencyResolver_DoesNotImplementICommonServiceLocator,\n                        locatorType.FullName),\n                    \"commonServiceLocator\");\n            }\n\n            var getService = (Func<Type, object>)Delegate.CreateDelegate(typeof(Func<Type, object>), commonServiceLocator, getInstance);\n            var getServices = (Func<Type, IEnumerable<object>>)Delegate.CreateDelegate(typeof(Func<Type, IEnumerable<object>>), commonServiceLocator, getInstances);\n\n            InnerSetResolver(new DelegateBasedDependencyResolver(getService, getServices));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types.\")]\n        public void InnerSetResolver(Func<Type, object> getService, Func<Type, IEnumerable<object>> getServices)\n        {\n            if (getService == null)\n            {\n                throw new ArgumentNullException(\"getService\");\n            }\n            if (getServices == null)\n            {\n                throw new ArgumentNullException(\"getServices\");\n            }\n\n            InnerSetResolver(new DelegateBasedDependencyResolver(getService, getServices));\n        }\n\n        /// <summary>\n        /// Wraps an IDependencyResolver and ensures single instance per-type.\n        /// </summary>\n        /// <remarks>\n        /// Note it's possible for multiple threads to race and call the _resolver service multiple times.\n        /// We'll pick one winner and ignore the others and still guarantee a unique instance.\n        /// </remarks>\n        private sealed class CacheDependencyResolver : IDependencyResolver\n        {\n            private readonly ConcurrentDictionary<Type, object> _cache = new ConcurrentDictionary<Type, object>();\n            private readonly ConcurrentDictionary<Type, IEnumerable<object>> _cacheMultiple = new ConcurrentDictionary<Type, IEnumerable<object>>();\n            private readonly Func<Type, object> _getServiceDelegate;\n            private readonly Func<Type, IEnumerable<object>> _getServicesDelegate;\n\n            private readonly IDependencyResolver _resolver;\n\n            public CacheDependencyResolver(IDependencyResolver resolver)\n            {\n                _resolver = resolver;\n                _getServiceDelegate = _resolver.GetService;\n                _getServicesDelegate = _resolver.GetServices;\n            }\n\n            public object GetService(Type serviceType)\n            {\n                // Use a saved delegate to prevent per-call delegate allocation\n                return _cache.GetOrAdd(serviceType, _getServiceDelegate);\n            }\n\n            public IEnumerable<object> GetServices(Type serviceType)\n            {\n                // Use a saved delegate to prevent per-call delegate allocation\n                return _cacheMultiple.GetOrAdd(serviceType, _getServicesDelegate);\n            }\n        }\n\n        private class DefaultDependencyResolver : IDependencyResolver\n        {\n            [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"This method might throw exceptions whose type we cannot strongly link against; namely, ActivationException from common service locator\")]\n            public object GetService(Type serviceType)\n            {\n                // Since attempting to create an instance of an interface or an abstract type results in an exception, immediately return null\n                // to improve performance and the debugging experience with first-chance exceptions enabled.\n                if (serviceType.IsInterface || serviceType.IsAbstract)\n                {\n                    return null;\n                }\n\n                try\n                {\n                    return Activator.CreateInstance(serviceType);\n                }\n                catch\n                {\n                    return null;\n                }\n            }\n\n            public IEnumerable<object> GetServices(Type serviceType)\n            {\n                return Enumerable.Empty<object>();\n            }\n        }\n\n        private class DelegateBasedDependencyResolver : IDependencyResolver\n        {\n            private Func<Type, object> _getService;\n            private Func<Type, IEnumerable<object>> _getServices;\n\n            public DelegateBasedDependencyResolver(Func<Type, object> getService, Func<Type, IEnumerable<object>> getServices)\n            {\n                _getService = getService;\n                _getServices = getServices;\n            }\n\n            [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"This method might throw exceptions whose type we cannot strongly link against; namely, ActivationException from common service locator\")]\n            public object GetService(Type type)\n            {\n                try\n                {\n                    return _getService.Invoke(type);\n                }\n                catch\n                {\n                    return null;\n                }\n            }\n\n            public IEnumerable<object> GetServices(Type type)\n            {\n                return _getServices(type);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/DependencyResolverExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace System.Web.Mvc\n{\n    public static class DependencyResolverExtensions\n    {\n        public static TService GetService<TService>(this IDependencyResolver resolver)\n        {\n            return (TService)resolver.GetService(typeof(TService));\n        }\n\n        public static IEnumerable<TService> GetServices<TService>(this IDependencyResolver resolver)\n        {\n            return resolver.GetServices(typeof(TService)).Cast<TService>();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/DescriptorUtil.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Reflection;\nusing System.Text;\nusing System.Threading;\n\nnamespace System.Web.Mvc\n{\n    internal static class DescriptorUtil\n    {\n        private static void AppendPartToUniqueIdBuilder(StringBuilder builder, object part)\n        {\n            if (part == null)\n            {\n                builder.Append(\"[-1]\");\n            }\n            else\n            {\n                string partString = Convert.ToString(part, CultureInfo.InvariantCulture);\n                builder.AppendFormat(\"[{0}]{1}\", partString.Length, partString);\n            }\n        }\n\n        public static void AppendUniqueId(StringBuilder builder, object part)\n        {\n            // We can special-case certain part types\n            MemberInfo memberInfo = part as MemberInfo;\n            if (memberInfo != null)\n            {\n                AppendPartToUniqueIdBuilder(builder, memberInfo.Module.ModuleVersionId);\n                AppendPartToUniqueIdBuilder(builder, memberInfo.MetadataToken);\n                return;\n            }\n\n            IUniquelyIdentifiable uniquelyIdentifiable = part as IUniquelyIdentifiable;\n            if (uniquelyIdentifiable != null)\n            {\n                AppendPartToUniqueIdBuilder(builder, uniquelyIdentifiable.UniqueId);\n                return;\n            }\n\n            AppendPartToUniqueIdBuilder(builder, part);\n        }\n\n        public static string CreateUniqueId(object part0, object part1)\n        {\n            StringBuilder builder = new StringBuilder();\n            AppendUniqueId(builder, part0);\n            AppendUniqueId(builder, part1);\n            return builder.ToString();\n        }\n\n        public static string CreateUniqueId(object part0, object part1, object part2)\n        {\n            StringBuilder builder = new StringBuilder();\n            AppendUniqueId(builder, part0);\n            AppendUniqueId(builder, part1);\n            AppendUniqueId(builder, part2);\n            return builder.ToString();\n        }\n\n        public static TDescriptor[] LazilyFetchOrCreateDescriptors<TReflection, TDescriptor, TArgument>(\n            ref TDescriptor[] cacheLocation,\n            Func<TArgument, TReflection[]> initializer,\n            Func<TReflection, TArgument, TDescriptor> converter,\n            TArgument state)\n        {\n            // did we already calculate this once?\n            TDescriptor[] existingCache = Interlocked.CompareExchange(ref cacheLocation, null, null);\n            if (existingCache != null)\n            {\n                return existingCache;\n            }\n\n            // Note: since this code operates on arrays it is more efficient to call simple array operations\n            // instead of LINQ-y extension methods such as Select and Where. DO NOT attempt to simplify this\n            // without testing the performance impact.\n            TReflection[] memberInfos = initializer(state);\n            List<TDescriptor> descriptorsList = new List<TDescriptor>(memberInfos.Length);\n            for (int i = 0; i < memberInfos.Length; i++)\n            {\n                TDescriptor descriptor = converter(memberInfos[i], state);\n                if (descriptor != null)\n                {\n                    descriptorsList.Add(descriptor);\n                }\n            }\n            TDescriptor[] descriptors = descriptorsList.ToArray();\n\n            TDescriptor[] updatedCache = Interlocked.CompareExchange(ref cacheLocation, descriptors, null);\n            return updatedCache ?? descriptors;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/DictionaryHelpers.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace System.Web.Mvc\n{\n    internal static class DictionaryHelpers\n    {\n        public static IEnumerable<KeyValuePair<string, TValue>> FindKeysWithPrefix<TValue>(IDictionary<string, TValue> dictionary, string prefix)\n        {\n            TValue exactMatchValue;\n            if (dictionary.TryGetValue(prefix, out exactMatchValue))\n            {\n                yield return new KeyValuePair<string, TValue>(prefix, exactMatchValue);\n            }\n\n            foreach (var entry in dictionary)\n            {\n                string key = entry.Key;\n\n                if (key.Length <= prefix.Length)\n                {\n                    continue;\n                }\n\n                if (!key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))\n                {\n                    continue;\n                }\n\n                char charAfterPrefix = key[prefix.Length];\n                switch (charAfterPrefix)\n                {\n                    case '[':\n                    case '.':\n                        yield return entry;\n                        break;\n                }\n            }\n        }\n\n        public static bool DoesAnyKeyHavePrefix<TValue>(IDictionary<string, TValue> dictionary, string prefix)\n        {\n            return FindKeysWithPrefix(dictionary, prefix).Any();\n        }\n\n        public static TValue GetOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, TValue @default)\n        {\n            TValue value;\n            if (dict.TryGetValue(key, out value))\n            {\n                return value;\n            }\n            return @default;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/DictionaryValueProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\n\nnamespace System.Web.Mvc\n{\n    public class DictionaryValueProvider<TValue> : IValueProvider, IEnumerableValueProvider\n    {\n        private PrefixContainer _prefixContainer;\n        private readonly Dictionary<string, ValueProviderResult> _values = new Dictionary<string, ValueProviderResult>(StringComparer.OrdinalIgnoreCase);\n\n        public DictionaryValueProvider(IDictionary<string, TValue> dictionary, CultureInfo culture)\n        {\n            if (dictionary == null)\n            {\n                throw new ArgumentNullException(\"dictionary\");\n            }\n\n            foreach (KeyValuePair<string, TValue> entry in dictionary)\n            {\n                object rawValue = entry.Value;\n                string attemptedValue = Convert.ToString(rawValue, culture);\n                _values[entry.Key] = new ValueProviderResult(rawValue, attemptedValue, culture);\n            }\n        }\n\n        private PrefixContainer PrefixContainer\n        {\n            get\n            {\n                if (_prefixContainer == null)\n                {\n                    // Race condition on initialization has no side effects\n                    _prefixContainer = new PrefixContainer(_values.Keys);\n                }\n                return _prefixContainer;\n            }\n        }\n\n        public virtual bool ContainsPrefix(string prefix)\n        {\n            return PrefixContainer.ContainsPrefix(prefix);\n        }\n\n        public virtual ValueProviderResult GetValue(string key)\n        {\n            if (key == null)\n            {\n                throw new ArgumentNullException(\"key\");\n            }\n\n            ValueProviderResult valueProviderResult;\n            _values.TryGetValue(key, out valueProviderResult);\n            return valueProviderResult;\n        }\n\n        public virtual IDictionary<string, string> GetKeysFromPrefix(string prefix)\n        {\n            return PrefixContainer.GetKeysFromPrefix(prefix);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/DynamicViewDataDictionary.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Dynamic;\n\nnamespace System.Web.Mvc\n{\n    internal sealed class DynamicViewDataDictionary : DynamicObject\n    {\n        private readonly Func<ViewDataDictionary> _viewDataThunk;\n\n        public DynamicViewDataDictionary(Func<ViewDataDictionary> viewDataThunk)\n        {\n            _viewDataThunk = viewDataThunk;\n        }\n\n        private ViewDataDictionary ViewData\n        {\n            get\n            {\n                ViewDataDictionary viewData = _viewDataThunk();\n                Debug.Assert(viewData != null);\n                return viewData;\n            }\n        }\n\n        // Implementing this function improves the debugging experience as it provides the debugger with the list of all\n        // the properties currently defined on the object\n        public override IEnumerable<string> GetDynamicMemberNames()\n        {\n            return ViewData.Keys;\n        }\n\n        public override bool TryGetMember(GetMemberBinder binder, out object result)\n        {\n            result = ViewData[binder.Name];\n            // since ViewDataDictionary always returns a result even if the key does not exist, always return true\n            return true;\n        }\n\n        public override bool TrySetMember(SetMemberBinder binder, object value)\n        {\n            ViewData[binder.Name] = value;\n            // you can always set a key in the dictionary so return true\n            return true;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/EmptyModelMetadataProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Mvc\n{\n    public class EmptyModelMetadataProvider : AssociatedMetadataProvider\n    {\n        protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)\n        {\n            return new ModelMetadata(this, containerType, modelAccessor, modelType, propertyName);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/EmptyModelValidatorProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace System.Web.Mvc\n{\n    public class EmptyModelValidatorProvider : ModelValidatorProvider\n    {\n        public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context)\n        {\n            return Enumerable.Empty<ModelValidator>();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/EmptyResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    // represents a result that doesn't do anything, like a controller action returning null\n    public class EmptyResult : ActionResult\n    {\n        private static readonly EmptyResult _singleton = new EmptyResult();\n\n        internal static EmptyResult Instance\n        {\n            get { return _singleton; }\n        }\n\n        public override void ExecuteResult(ControllerContext context)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Error.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Web.Mvc.Async;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    internal static class Error\n    {\n        public static InvalidOperationException AsyncActionMethodSelector_CouldNotFindMethod(string methodName, Type controllerType)\n        {\n            string message = String.Format(CultureInfo.CurrentCulture, MvcResources.AsyncActionMethodSelector_CouldNotFindMethod,\n                                           methodName, controllerType);\n            return new InvalidOperationException(message);\n        }\n\n        public static InvalidOperationException AsyncCommon_AsyncResultAlreadyConsumed()\n        {\n            return new InvalidOperationException(MvcResources.AsyncCommon_AsyncResultAlreadyConsumed);\n        }\n\n        public static InvalidOperationException AsyncCommon_ControllerMustImplementIAsyncManagerContainer(Type actualControllerType)\n        {\n            string message = String.Format(CultureInfo.CurrentCulture, MvcResources.AsyncCommon_ControllerMustImplementIAsyncManagerContainer,\n                                           actualControllerType);\n            return new InvalidOperationException(message);\n        }\n\n        public static ArgumentException AsyncCommon_InvalidAsyncResult(string parameterName)\n        {\n            return new ArgumentException(MvcResources.AsyncCommon_InvalidAsyncResult, parameterName);\n        }\n\n        public static ArgumentOutOfRangeException AsyncCommon_InvalidTimeout(string parameterName)\n        {\n            return new ArgumentOutOfRangeException(parameterName, MvcResources.AsyncCommon_InvalidTimeout);\n        }\n\n        public static InvalidOperationException ChildActionOnlyAttribute_MustBeInChildRequest(ActionDescriptor actionDescriptor)\n        {\n            string message = String.Format(CultureInfo.CurrentCulture, MvcResources.ChildActionOnlyAttribute_MustBeInChildRequest,\n                                           actionDescriptor.ActionName);\n            return new InvalidOperationException(message);\n        }\n\n        public static ArgumentException ParameterCannotBeNullOrEmpty(string parameterName)\n        {\n            return new ArgumentException(MvcResources.Common_NullOrEmpty, parameterName);\n        }\n\n        public static InvalidOperationException PropertyCannotBeNullOrEmpty(string propertyName)\n        {\n            string message = String.Format(CultureInfo.CurrentCulture, MvcResources.Common_PropertyCannotBeNullOrEmpty,\n                                           propertyName);\n            return new InvalidOperationException(message);\n        }\n\n        public static SynchronousOperationException SynchronizationContextUtil_ExceptionThrown(Exception innerException)\n        {\n            return new SynchronousOperationException(MvcResources.SynchronizationContextUtil_ExceptionThrown, innerException);\n        }\n\n        public static InvalidOperationException ViewDataDictionary_WrongTModelType(Type valueType, Type modelType)\n        {\n            string message = String.Format(CultureInfo.CurrentCulture, MvcResources.ViewDataDictionary_WrongTModelType,\n                                           valueType, modelType);\n            return new InvalidOperationException(message);\n        }\n\n        public static InvalidOperationException ViewDataDictionary_ModelCannotBeNull(Type modelType)\n        {\n            string message = String.Format(CultureInfo.CurrentCulture, MvcResources.ViewDataDictionary_ModelCannotBeNull,\n                                           modelType);\n            return new InvalidOperationException(message);\n        }\n\n        public static ArgumentOutOfRangeException ArgumentMustBeGreaterThanOrEqualTo(string parameterName, int actualValue, int minValue)\n        {\n            string message = String.Format(CultureInfo.CurrentCulture, MvcResources.ArgumentMustBeGreaterThanOrEqualTo,\n                                           minValue);\n            return new ArgumentOutOfRangeException(parameterName, actualValue, message);\n        }\n\n        public static Exception ArgumentNull(string parameterName)\n        {\n            return new ArgumentNullException(parameterName);\n        }\n\n        public static InvalidOperationException InvalidOperation(string messageFormat, params object[] args)\n        {\n            string message = String.Format(CultureInfo.CurrentCulture, messageFormat, args);\n            return new InvalidOperationException(message);\n        }\n\n        internal static string Format(string format, params object[] args)\n        {\n            return String.Format(CultureInfo.CurrentCulture, format, args);\n        }\n\n        internal static ArgumentException Argument(string parameterName, string messageFormat, params object[] messageArgs)\n        {\n            return new ArgumentException(Error.Format(messageFormat, messageArgs), parameterName);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ExceptionContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.Mvc\n{\n    public class ExceptionContext : ControllerContext\n    {\n        private ActionResult _result;\n\n        // parameterless constructor used for mocking\n        public ExceptionContext()\n        {\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2214:DoNotCallOverridableMethodsInConstructors\", Justification = \"The virtual property setters are only to support mocking frameworks, in which case this constructor shouldn't be called anyway.\")]\n        public ExceptionContext(ControllerContext controllerContext, Exception exception)\n            : base(controllerContext)\n        {\n            if (exception == null)\n            {\n                throw new ArgumentNullException(\"exception\");\n            }\n\n            Exception = exception;\n        }\n\n        public virtual Exception Exception { get; set; }\n\n        public bool ExceptionHandled { get; set; }\n\n        public ActionResult Result\n        {\n            get { return _result ?? EmptyResult.Instance; }\n            set { _result = value; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ExpressionHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Linq.Expressions;\nusing System.Reflection;\nusing System.Web.Mvc.ExpressionUtil;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    public static class ExpressionHelper\n    {\n        public static string GetExpressionText(string expression)\n        {\n            return\n                String.Equals(expression, \"model\", StringComparison.OrdinalIgnoreCase)\n                    ? String.Empty // If it's exactly \"model\", then give them an empty string, to replicate the lambda behavior\n                    : expression;\n        }\n\n        public static string GetExpressionText(LambdaExpression expression)\n        {\n            // Split apart the expression string for property/field accessors to create its name\n            Stack<string> nameParts = new Stack<string>();\n            Expression part = expression.Body;\n\n            while (part != null)\n            {\n                if (part.NodeType == ExpressionType.Call)\n                {\n                    MethodCallExpression methodExpression = (MethodCallExpression)part;\n\n                    if (!IsSingleArgumentIndexer(methodExpression))\n                    {\n                        // Unsupported\n                        break;\n                    }\n\n                    nameParts.Push(\n                        GetIndexerInvocation(\n                            methodExpression.Arguments.Single(),\n                            expression.Parameters.ToArray()));\n\n                    part = methodExpression.Object;\n                }\n                else if (part.NodeType == ExpressionType.ArrayIndex)\n                {\n                    BinaryExpression binaryExpression = (BinaryExpression)part;\n\n                    nameParts.Push(\n                        GetIndexerInvocation(\n                            binaryExpression.Right,\n                            expression.Parameters.ToArray()));\n\n                    part = binaryExpression.Left;\n                }\n                else if (part.NodeType == ExpressionType.MemberAccess)\n                {\n                    MemberExpression memberExpressionPart = (MemberExpression)part;\n                    var name = memberExpressionPart.Member.Name;\n\n                    // If identifier contains \"__\", it is \"reserved for use by the implementation\" and likely compiler-\n                    // or Razor-generated e.g. the name of a field in a delegate's generated class.\n                    if (name.Contains(\"__\"))\n                    {\n                        // Exit loop. Should have the entire name because previous MemberAccess has same name as the\n                        // leftmost expression node (a variable).\n                        break;\n                    }\n\n                    nameParts.Push(\".\" + name);\n                    part = memberExpressionPart.Expression;\n                }\n                else if (part.NodeType == ExpressionType.Parameter)\n                {\n                    // Dev10 Bug #907611\n                    // When the expression is parameter based (m => m.Something...), we'll push an empty\n                    // string onto the stack and stop evaluating. The extra empty string makes sure that\n                    // we don't accidentally cut off too much of m => m.Model.\n                    nameParts.Push(String.Empty);\n\n                    // Exit loop. Have the entire name because the parameter cannot be used as an indexer; always the\n                    // leftmost expression node.\n                    break;\n                }\n                else\n                {\n                    // Unsupported\n                    break;\n                }\n            }\n\n            // If parts start with \"model\", then strip that part away.\n            if (nameParts.Count > 0 && String.Equals(nameParts.Peek(), \".model\", StringComparison.OrdinalIgnoreCase))\n            {\n                nameParts.Pop();\n            }\n\n            if (nameParts.Count > 0)\n            {\n                return nameParts.Aggregate((left, right) => left + right).TrimStart('.');\n            }\n\n            return String.Empty;\n        }\n\n        private static string GetIndexerInvocation(Expression expression, ParameterExpression[] parameters)\n        {\n            Expression converted = Expression.Convert(expression, typeof(object));\n            ParameterExpression fakeParameter = Expression.Parameter(typeof(object), null);\n            Expression<Func<object, object>> lambda = Expression.Lambda<Func<object, object>>(converted, fakeParameter);\n            Func<object, object> func;\n\n            try\n            {\n                func = CachedExpressionCompiler.Process(lambda);\n            }\n            catch (InvalidOperationException ex)\n            {\n                throw new InvalidOperationException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.ExpressionHelper_InvalidIndexerExpression,\n                        expression,\n                        parameters[0].Name),\n                    ex);\n            }\n\n            return \"[\" + Convert.ToString(func(null), CultureInfo.InvariantCulture) + \"]\";\n        }\n\n        internal static bool IsSingleArgumentIndexer(Expression expression)\n        {\n            MethodCallExpression methodExpression = expression as MethodCallExpression;\n            if (methodExpression == null || methodExpression.Arguments.Count != 1)\n            {\n                return false;\n            }\n\n            return methodExpression.Method\n                .DeclaringType\n                .GetDefaultMembers()\n                .OfType<PropertyInfo>()\n                .Any(p => p.GetGetMethod() == methodExpression.Method);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ExpressionUtil/BinaryExpressionFingerprint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\nusing System.Reflection;\n\n#pragma warning disable 659 // overrides AddToHashCodeCombiner instead\n\nnamespace System.Web.Mvc.ExpressionUtil\n{\n    // BinaryExpression fingerprint class\n    // Useful for things like array[index]\n\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2218:OverrideGetHashCodeOnOverridingEquals\", Justification = \"Overrides AddToHashCodeCombiner() instead.\")]\n    internal sealed class BinaryExpressionFingerprint : ExpressionFingerprint\n    {\n        public BinaryExpressionFingerprint(ExpressionType nodeType, Type type, MethodInfo method)\n            : base(nodeType, type)\n        {\n            // Other properties on BinaryExpression (like IsLifted / IsLiftedToNull) are simply derived\n            // from Type and NodeType, so they're not necessary for inclusion in the fingerprint.\n\n            Method = method;\n        }\n\n        // http://msdn.microsoft.com/en-us/library/system.linq.expressions.binaryexpression.method.aspx\n        public MethodInfo Method { get; private set; }\n\n        public override bool Equals(object obj)\n        {\n            BinaryExpressionFingerprint other = obj as BinaryExpressionFingerprint;\n            return (other != null)\n                   && Equals(this.Method, other.Method)\n                   && this.Equals(other);\n        }\n\n        internal override void AddToHashCodeCombiner(HashCodeCombiner combiner)\n        {\n            combiner.AddObject(Method);\n            base.AddToHashCodeCombiner(combiner);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ExpressionUtil/CachedExpressionCompiler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Linq.Expressions;\nusing System.Reflection;\n\nnamespace System.Web.Mvc.ExpressionUtil\n{\n    internal static class CachedExpressionCompiler\n    {\n        // This is the entry point to the cached expression compilation system. The system\n        // will try to turn the expression into an actual delegate as quickly as possible,\n        // relying on cache lookups and other techniques to save time if appropriate.\n        // If the provided expression is particularly obscure and the system doesn't know\n        // how to handle it, we'll just compile the expression as normal.\n        public static Func<TModel, TValue> Process<TModel, TValue>(Expression<Func<TModel, TValue>> lambdaExpression)\n        {\n            return Compiler<TModel, TValue>.Compile(lambdaExpression);\n        }\n\n        private static class Compiler<TIn, TOut>\n        {\n            private static Func<TIn, TOut> _identityFunc;\n\n            private static readonly ConcurrentDictionary<MemberInfo, Func<TIn, TOut>> _simpleMemberAccessDict =\n                new ConcurrentDictionary<MemberInfo, Func<TIn, TOut>>();\n\n            private static readonly ConcurrentDictionary<MemberInfo, Func<object, TOut>> _constMemberAccessDict =\n                new ConcurrentDictionary<MemberInfo, Func<object, TOut>>();\n\n            private static readonly ConcurrentDictionary<ExpressionFingerprintChain, Hoisted<TIn, TOut>> _fingerprintedCache =\n                new ConcurrentDictionary<ExpressionFingerprintChain, Hoisted<TIn, TOut>>();\n\n            public static Func<TIn, TOut> Compile(Expression<Func<TIn, TOut>> expr)\n            {\n                return CompileFromIdentityFunc(expr)\n                       ?? CompileFromConstLookup(expr)\n                       ?? CompileFromMemberAccess(expr)\n                       ?? CompileFromFingerprint(expr)\n                       ?? CompileSlow(expr);\n            }\n\n            private static Func<TIn, TOut> CompileFromConstLookup(Expression<Func<TIn, TOut>> expr)\n            {\n                ConstantExpression constExpr = expr.Body as ConstantExpression;\n                if (constExpr != null)\n                {\n                    // model => {const}\n\n                    TOut constantValue = (TOut)constExpr.Value;\n                    return _ => constantValue;\n                }\n\n                return null;\n            }\n\n            private static Func<TIn, TOut> CompileFromIdentityFunc(Expression<Func<TIn, TOut>> expr)\n            {\n                if (expr.Body == expr.Parameters[0])\n                {\n                    // model => model\n\n                    // don't need to lock, as all identity funcs are identical\n                    if (_identityFunc == null)\n                    {\n                        _identityFunc = expr.Compile();\n                    }\n\n                    return _identityFunc;\n                }\n\n                return null;\n            }\n\n            private static Func<TIn, TOut> CompileFromFingerprint(Expression<Func<TIn, TOut>> expr)\n            {\n                List<object> capturedConstants;\n                ExpressionFingerprintChain fingerprint = FingerprintingExpressionVisitor.GetFingerprintChain(expr, out capturedConstants);\n\n                if (fingerprint != null)\n                {\n                    var del = _fingerprintedCache.GetOrAdd(fingerprint, _ =>\n                    {\n                        // Fingerprinting succeeded, but there was a cache miss. Rewrite the expression\n                        // and add the rewritten expression to the cache.\n\n                        var hoistedExpr = HoistingExpressionVisitor<TIn, TOut>.Hoist(expr);\n                        return hoistedExpr.Compile();\n                    });\n                    return model => del(model, capturedConstants);\n                }\n\n                // couldn't be fingerprinted\n                return null;\n            }\n\n            private static Func<TIn, TOut> CompileFromMemberAccess(Expression<Func<TIn, TOut>> expr)\n            {\n                // Performance tests show that on the x64 platform, special-casing static member and\n                // captured local variable accesses is faster than letting the fingerprinting system\n                // handle them. On the x86 platform, the fingerprinting system is faster, but only\n                // by around one microsecond, so it's not worth it to complicate the logic here with\n                // an architecture check.\n\n                MemberExpression memberExpr = expr.Body as MemberExpression;\n                if (memberExpr != null)\n                {\n                    if (memberExpr.Expression == expr.Parameters[0] || memberExpr.Expression == null)\n                    {\n                        // model => model.Member or model => StaticMember\n                        return _simpleMemberAccessDict.GetOrAdd(memberExpr.Member, _ => expr.Compile());\n                    }\n\n                    ConstantExpression constExpr = memberExpr.Expression as ConstantExpression;\n                    if (constExpr != null)\n                    {\n                        // model => {const}.Member (captured local variable)\n                        var del = _constMemberAccessDict.GetOrAdd(memberExpr.Member, _ =>\n                        {\n                            // rewrite as capturedLocal => ((TDeclaringType)capturedLocal).Member\n                            var constParamExpr = Expression.Parameter(typeof(object), \"capturedLocal\");\n                            var constCastExpr = Expression.Convert(constParamExpr, memberExpr.Member.DeclaringType);\n                            var newMemberAccessExpr = memberExpr.Update(constCastExpr);\n                            var newLambdaExpr = Expression.Lambda<Func<object, TOut>>(newMemberAccessExpr, constParamExpr);\n                            return newLambdaExpr.Compile();\n                        });\n\n                        object capturedLocal = constExpr.Value;\n                        return _ => del(capturedLocal);\n                    }\n                }\n\n                return null;\n            }\n\n            private static Func<TIn, TOut> CompileSlow(Expression<Func<TIn, TOut>> expr)\n            {\n                // fallback compilation system - just compile the expression directly\n                return expr.Compile();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ExpressionUtil/ConditionalExpressionFingerprint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\n\n#pragma warning disable 659 // overrides AddToHashCodeCombiner instead\n\nnamespace System.Web.Mvc.ExpressionUtil\n{\n    // ConditionalExpression fingerprint class\n    // Expression of form (test) ? ifTrue : ifFalse\n\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2218:OverrideGetHashCodeOnOverridingEquals\", Justification = \"Overrides AddToHashCodeCombiner() instead.\")]\n    internal sealed class ConditionalExpressionFingerprint : ExpressionFingerprint\n    {\n        public ConditionalExpressionFingerprint(ExpressionType nodeType, Type type)\n            : base(nodeType, type)\n        {\n            // There are no properties on ConditionalExpression that are worth including in\n            // the fingerprint.\n        }\n\n        public override bool Equals(object obj)\n        {\n            ConditionalExpressionFingerprint other = obj as ConditionalExpressionFingerprint;\n            return (other != null)\n                   && this.Equals(other);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ExpressionUtil/ConstantExpressionFingerprint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\n\n#pragma warning disable 659 // overrides AddToHashCodeCombiner instead\n\nnamespace System.Web.Mvc.ExpressionUtil\n{\n    // ConstantExpression fingerprint class\n    //\n    // A ConstantExpression might represent a captured local variable, so we can't compile\n    // the value directly into the cached function. Instead, a placeholder is generated\n    // and the value is hoisted into a local variables array. This placeholder can then\n    // be compiled and cached, and the array lookup happens at runtime.\n\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2218:OverrideGetHashCodeOnOverridingEquals\", Justification = \"Overrides AddToHashCodeCombiner() instead.\")]\n    internal sealed class ConstantExpressionFingerprint : ExpressionFingerprint\n    {\n        public ConstantExpressionFingerprint(ExpressionType nodeType, Type type)\n            : base(nodeType, type)\n        {\n            // There are no properties on ConstantExpression that are worth including in\n            // the fingerprint.\n        }\n\n        public override bool Equals(object obj)\n        {\n            ConstantExpressionFingerprint other = obj as ConstantExpressionFingerprint;\n            return (other != null)\n                   && this.Equals(other);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ExpressionUtil/DefaultExpressionFingerprint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\n\n#pragma warning disable 659 // overrides AddToHashCodeCombiner instead\n\nnamespace System.Web.Mvc.ExpressionUtil\n{\n    // DefaultExpression fingerprint class\n    // Expression of form default(T)\n\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2218:OverrideGetHashCodeOnOverridingEquals\", Justification = \"Overrides AddToHashCodeCombiner() instead.\")]\n    internal sealed class DefaultExpressionFingerprint : ExpressionFingerprint\n    {\n        public DefaultExpressionFingerprint(ExpressionType nodeType, Type type)\n            : base(nodeType, type)\n        {\n            // There are no properties on DefaultExpression that are worth including in\n            // the fingerprint.\n        }\n\n        public override bool Equals(object obj)\n        {\n            DefaultExpressionFingerprint other = obj as DefaultExpressionFingerprint;\n            return (other != null)\n                   && this.Equals(other);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ExpressionUtil/ExpressionFingerprint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq.Expressions;\n\nnamespace System.Web.Mvc.ExpressionUtil\n{\n    // Serves as the base class for all expression fingerprints. Provides a default implementation\n    // of GetHashCode().\n\n    internal abstract class ExpressionFingerprint\n    {\n        protected ExpressionFingerprint(ExpressionType nodeType, Type type)\n        {\n            NodeType = nodeType;\n            Type = type;\n        }\n\n        // the type of expression node, e.g. OP_ADD, MEMBER_ACCESS, etc.\n        public ExpressionType NodeType { get; private set; }\n\n        // the CLR type resulting from this expression, e.g. int, string, etc.\n        public Type Type { get; private set; }\n\n        internal virtual void AddToHashCodeCombiner(HashCodeCombiner combiner)\n        {\n            combiner.AddInt32((int)NodeType);\n            combiner.AddObject(Type);\n        }\n\n        protected bool Equals(ExpressionFingerprint other)\n        {\n            return (other != null)\n                   && (this.NodeType == other.NodeType)\n                   && Equals(this.Type, other.Type);\n        }\n\n        public override bool Equals(object obj)\n        {\n            return Equals(obj as ExpressionFingerprint);\n        }\n\n        public override int GetHashCode()\n        {\n            HashCodeCombiner combiner = new HashCodeCombiner();\n            AddToHashCodeCombiner(combiner);\n            return combiner.CombinedHash;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ExpressionUtil/ExpressionFingerprintChain.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Mvc.ExpressionUtil\n{\n    // Expression fingerprint chain class\n    // Contains information used for generalizing, comparing, and recreating Expression instances\n    //\n    // Since Expression objects are immutable and are recreated for every invocation of an expression\n    // helper method, they can't be compared directly. Fingerprinting Expression objects allows\n    // information about them to be abstracted away, and the fingerprints can be directly compared.\n    // Consider the process of fingerprinting that all values (parameters, constants, etc.) are hoisted\n    // and replaced with dummies. What remains can be decomposed into a sequence of operations on specific\n    // types and specific inputs.\n    //\n    // Some sample fingerprints chains:\n    //\n    // 2 + 4 -> OP_ADD, CONST:int, NULL, CONST:int\n    // 2 + 8 -> OP_ADD, CONST:int, NULL, CONST:int\n    // 2.0 + 4.0 -> OP_ADD, CONST:double, NULL, CONST:double\n    //\n    // 2 + 4 and 2 + 8 have the same fingerprint, but 2.0 + 4.0 has a different fingerprint since its\n    // underlying types differ. Note that this looks a bit like prefix notation and is a side effect\n    // of how the ExpressionVisitor class recurses into expressions. (Occasionally there will be a NULL\n    // in the fingerprint chain, which depending on context can denote a static member, a null Conversion\n    // in a BinaryExpression, and so forth.)\n    //\n    // \"Hello \" + \"world\" -> OP_ADD, CONST:string, NULL, CONST:string\n    // \"Hello \" + {model} -> OP_ADD, CONST:string, NULL, PARAM_0:string\n    //\n    // These string concatenations have different fingerprints since the inputs are provided differently:\n    // one is a constant, the other is a parameter.\n    //\n    // ({model} ?? \"sample\").Length -> MEMBER_ACCESS(String.Length), OP_COALESCE, PARAM_0:string, NULL, CONST:string\n    // ({model} ?? \"other sample\").Length -> MEMBER_ACCESS(String.Length), OP_COALESCE, PARAM_0:string, NULL, CONST:string\n    //\n    // These expressions have the same fingerprint since all constants of the same underlying type are\n    // treated equally.\n    //\n    // It's also important that the fingerprints don't reference the actual Expression objects that were\n    // used to generate them, as the fingerprints will be cached, and caching a fingerprint that references\n    // an Expression will root the Expression (and any objects it references).\n\n    internal sealed class ExpressionFingerprintChain : IEquatable<ExpressionFingerprintChain>\n    {\n        public readonly List<ExpressionFingerprint> Elements = new List<ExpressionFingerprint>();\n\n        public bool Equals(ExpressionFingerprintChain other)\n        {\n            // Two chains are considered equal if two elements appearing in the same index in\n            // each chain are equal (value equality, not referential equality).\n\n            if (other == null)\n            {\n                return false;\n            }\n\n            if (this.Elements.Count != other.Elements.Count)\n            {\n                return false;\n            }\n\n            for (int i = 0; i < this.Elements.Count; i++)\n            {\n                if (!Equals(this.Elements[i], other.Elements[i]))\n                {\n                    return false;\n                }\n            }\n\n            return true;\n        }\n\n        public override bool Equals(object obj)\n        {\n            return Equals(obj as ExpressionFingerprintChain);\n        }\n\n        public override int GetHashCode()\n        {\n            HashCodeCombiner combiner = new HashCodeCombiner();\n            Elements.ForEach(combiner.AddFingerprint);\n            return combiner.CombinedHash;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ExpressionUtil/FingerprintingExpressionVisitor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq.Expressions;\n\nnamespace System.Web.Mvc.ExpressionUtil\n{\n    // This is a visitor which produces a fingerprint of an expression. It doesn't\n    // rewrite the expression in a form which can be compiled and cached.\n\n    internal sealed class FingerprintingExpressionVisitor : ExpressionVisitor\n    {\n        private readonly List<object> _seenConstants = new List<object>();\n        private readonly List<ParameterExpression> _seenParameters = new List<ParameterExpression>();\n        private readonly ExpressionFingerprintChain _currentChain = new ExpressionFingerprintChain();\n        private bool _gaveUp;\n\n        private FingerprintingExpressionVisitor()\n        {\n        }\n\n        private T GiveUp<T>(T node)\n        {\n            // We don't understand this node, so just quit.\n\n            _gaveUp = true;\n            return node;\n        }\n\n        // Returns the fingerprint chain + captured constants list for this expression, or null\n        // if the expression couldn't be fingerprinted.\n        public static ExpressionFingerprintChain GetFingerprintChain(Expression expr, out List<object> capturedConstants)\n        {\n            FingerprintingExpressionVisitor visitor = new FingerprintingExpressionVisitor();\n            visitor.Visit(expr);\n\n            if (visitor._gaveUp)\n            {\n                capturedConstants = null;\n                return null;\n            }\n            else\n            {\n                capturedConstants = visitor._seenConstants;\n                return visitor._currentChain;\n            }\n        }\n\n        public override Expression Visit(Expression node)\n        {\n            if (node == null)\n            {\n                _currentChain.Elements.Add(null);\n                return null;\n            }\n            else\n            {\n                return base.Visit(node);\n            }\n        }\n\n        protected override Expression VisitBinary(BinaryExpression node)\n        {\n            if (_gaveUp)\n            {\n                return node;\n            }\n            _currentChain.Elements.Add(new BinaryExpressionFingerprint(node.NodeType, node.Type, node.Method));\n            return base.VisitBinary(node);\n        }\n\n        protected override Expression VisitBlock(BlockExpression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override CatchBlock VisitCatchBlock(CatchBlock node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitConditional(ConditionalExpression node)\n        {\n            if (_gaveUp)\n            {\n                return node;\n            }\n            _currentChain.Elements.Add(new ConditionalExpressionFingerprint(node.NodeType, node.Type));\n            return base.VisitConditional(node);\n        }\n\n        protected override Expression VisitConstant(ConstantExpression node)\n        {\n            if (_gaveUp)\n            {\n                return node;\n            }\n\n            _seenConstants.Add(node.Value);\n            _currentChain.Elements.Add(new ConstantExpressionFingerprint(node.NodeType, node.Type));\n            return base.VisitConstant(node);\n        }\n\n        protected override Expression VisitDebugInfo(DebugInfoExpression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitDefault(DefaultExpression node)\n        {\n            if (_gaveUp)\n            {\n                return node;\n            }\n            _currentChain.Elements.Add(new DefaultExpressionFingerprint(node.NodeType, node.Type));\n            return base.VisitDefault(node);\n        }\n\n        protected override Expression VisitDynamic(DynamicExpression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override ElementInit VisitElementInit(ElementInit node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitExtension(Expression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitGoto(GotoExpression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitIndex(IndexExpression node)\n        {\n            if (_gaveUp)\n            {\n                return node;\n            }\n            _currentChain.Elements.Add(new IndexExpressionFingerprint(node.NodeType, node.Type, node.Indexer));\n            return base.VisitIndex(node);\n        }\n\n        protected override Expression VisitInvocation(InvocationExpression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitLabel(LabelExpression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override LabelTarget VisitLabelTarget(LabelTarget node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitLambda<T>(Expression<T> node)\n        {\n            if (_gaveUp)\n            {\n                return node;\n            }\n            _currentChain.Elements.Add(new LambdaExpressionFingerprint(node.NodeType, node.Type));\n            return base.VisitLambda<T>(node);\n        }\n\n        protected override Expression VisitListInit(ListInitExpression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitLoop(LoopExpression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitMember(MemberExpression node)\n        {\n            if (_gaveUp)\n            {\n                return node;\n            }\n            _currentChain.Elements.Add(new MemberExpressionFingerprint(node.NodeType, node.Type, node.Member));\n            return base.VisitMember(node);\n        }\n\n        protected override MemberAssignment VisitMemberAssignment(MemberAssignment node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override MemberBinding VisitMemberBinding(MemberBinding node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitMemberInit(MemberInitExpression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override MemberListBinding VisitMemberListBinding(MemberListBinding node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitMethodCall(MethodCallExpression node)\n        {\n            if (_gaveUp)\n            {\n                return node;\n            }\n            _currentChain.Elements.Add(new MethodCallExpressionFingerprint(node.NodeType, node.Type, node.Method));\n            return base.VisitMethodCall(node);\n        }\n\n        protected override Expression VisitNew(NewExpression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitNewArray(NewArrayExpression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitParameter(ParameterExpression node)\n        {\n            if (_gaveUp)\n            {\n                return node;\n            }\n\n            int parameterIndex = _seenParameters.IndexOf(node);\n            if (parameterIndex < 0)\n            {\n                // first time seeing this parameter\n                parameterIndex = _seenParameters.Count;\n                _seenParameters.Add(node);\n            }\n\n            _currentChain.Elements.Add(new ParameterExpressionFingerprint(node.NodeType, node.Type, parameterIndex));\n            return base.VisitParameter(node);\n        }\n\n        protected override Expression VisitRuntimeVariables(RuntimeVariablesExpression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitSwitch(SwitchExpression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override SwitchCase VisitSwitchCase(SwitchCase node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitTry(TryExpression node)\n        {\n            return GiveUp(node);\n        }\n\n        protected override Expression VisitTypeBinary(TypeBinaryExpression node)\n        {\n            if (_gaveUp)\n            {\n                return node;\n            }\n            _currentChain.Elements.Add(new TypeBinaryExpressionFingerprint(node.NodeType, node.Type, node.TypeOperand));\n            return base.VisitTypeBinary(node);\n        }\n\n        protected override Expression VisitUnary(UnaryExpression node)\n        {\n            if (_gaveUp)\n            {\n                return node;\n            }\n            _currentChain.Elements.Add(new UnaryExpressionFingerprint(node.NodeType, node.Type, node.Method));\n            return base.VisitUnary(node);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ExpressionUtil/HashCodeCombiner.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\n\nnamespace System.Web.Mvc.ExpressionUtil\n{\n    // based on System.Web.Util.HashCodeCombiner\n    internal class HashCodeCombiner\n    {\n        private long _combinedHash64 = 0x1505L;\n\n        public int CombinedHash\n        {\n            get { return _combinedHash64.GetHashCode(); }\n        }\n\n        public void AddFingerprint(ExpressionFingerprint fingerprint)\n        {\n            if (fingerprint != null)\n            {\n                fingerprint.AddToHashCodeCombiner(this);\n            }\n            else\n            {\n                AddInt32(0);\n            }\n        }\n\n        public void AddEnumerable(IEnumerable e)\n        {\n            if (e == null)\n            {\n                AddInt32(0);\n            }\n            else\n            {\n                int count = 0;\n                foreach (object o in e)\n                {\n                    AddObject(o);\n                    count++;\n                }\n                AddInt32(count);\n            }\n        }\n\n        public void AddInt32(int i)\n        {\n            _combinedHash64 = ((_combinedHash64 << 5) + _combinedHash64) ^ i;\n        }\n\n        public void AddObject(object o)\n        {\n            int hashCode = (o != null) ? o.GetHashCode() : 0;\n            AddInt32(hashCode);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ExpressionUtil/Hoisted.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Mvc.ExpressionUtil\n{\n    internal delegate TValue Hoisted<TModel, TValue>(TModel model, List<object> capturedConstants);\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ExpressionUtil/HoistingExpressionVisitor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq.Expressions;\n\nnamespace System.Web.Mvc.ExpressionUtil\n{\n    // This is a visitor which rewrites constant expressions as parameter lookups. It's meant\n    // to produce an expression which can be cached safely.\n\n    internal sealed class HoistingExpressionVisitor<TIn, TOut> : ExpressionVisitor\n    {\n        private static readonly ParameterExpression _hoistedConstantsParamExpr = Expression.Parameter(typeof(List<object>), \"hoistedConstants\");\n        private int _numConstantsProcessed;\n\n        // factory will create instance\n        private HoistingExpressionVisitor()\n        {\n        }\n\n        public static Expression<Hoisted<TIn, TOut>> Hoist(Expression<Func<TIn, TOut>> expr)\n        {\n            // rewrite Expression<Func<TIn, TOut>> as Expression<Hoisted<TIn, TOut>>\n\n            var visitor = new HoistingExpressionVisitor<TIn, TOut>();\n            var rewrittenBodyExpr = visitor.Visit(expr.Body);\n            var rewrittenLambdaExpr = Expression.Lambda<Hoisted<TIn, TOut>>(rewrittenBodyExpr, expr.Parameters[0], _hoistedConstantsParamExpr);\n            return rewrittenLambdaExpr;\n        }\n\n        protected override Expression VisitConstant(ConstantExpression node)\n        {\n            // rewrite the constant expression as (TConst)hoistedConstants[i];\n            return Expression.Convert(Expression.Property(_hoistedConstantsParamExpr, \"Item\", Expression.Constant(_numConstantsProcessed++)), node.Type);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ExpressionUtil/IndexExpressionFingerprint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\nusing System.Reflection;\n\n#pragma warning disable 659 // overrides AddToHashCodeCombiner instead\n\nnamespace System.Web.Mvc.ExpressionUtil\n{\n    // IndexExpression fingerprint class\n    // Represents certain forms of array access or indexer property access\n\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2218:OverrideGetHashCodeOnOverridingEquals\", Justification = \"Overrides AddToHashCodeCombiner() instead.\")]\n    internal sealed class IndexExpressionFingerprint : ExpressionFingerprint\n    {\n        public IndexExpressionFingerprint(ExpressionType nodeType, Type type, PropertyInfo indexer)\n            : base(nodeType, type)\n        {\n            // Other properties on IndexExpression (like the argument count) are simply derived\n            // from Type and Indexer, so they're not necessary for inclusion in the fingerprint.\n\n            Indexer = indexer;\n        }\n\n        // http://msdn.microsoft.com/en-us/library/system.linq.expressions.indexexpression.indexer.aspx\n        public PropertyInfo Indexer { get; private set; }\n\n        public override bool Equals(object obj)\n        {\n            IndexExpressionFingerprint other = obj as IndexExpressionFingerprint;\n            return (other != null)\n                   && Equals(this.Indexer, other.Indexer)\n                   && this.Equals(other);\n        }\n\n        internal override void AddToHashCodeCombiner(HashCodeCombiner combiner)\n        {\n            combiner.AddObject(Indexer);\n            base.AddToHashCodeCombiner(combiner);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ExpressionUtil/LambdaExpressionFingerprint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\n\n#pragma warning disable 659 // overrides AddToHashCodeCombiner instead\n\nnamespace System.Web.Mvc.ExpressionUtil\n{\n    // LambdaExpression fingerprint class\n    // Represents a lambda expression (root element in Expression<T>)\n\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2218:OverrideGetHashCodeOnOverridingEquals\", Justification = \"Overrides AddToHashCodeCombiner() instead.\")]\n    internal sealed class LambdaExpressionFingerprint : ExpressionFingerprint\n    {\n        public LambdaExpressionFingerprint(ExpressionType nodeType, Type type)\n            : base(nodeType, type)\n        {\n            // There are no properties on LambdaExpression that are worth including in\n            // the fingerprint.\n        }\n\n        public override bool Equals(object obj)\n        {\n            LambdaExpressionFingerprint other = obj as LambdaExpressionFingerprint;\n            return (other != null)\n                   && this.Equals(other);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ExpressionUtil/MemberExpressionFingerprint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\nusing System.Reflection;\n\n#pragma warning disable 659 // overrides AddToHashCodeCombiner instead\n\nnamespace System.Web.Mvc.ExpressionUtil\n{\n    // MemberExpression fingerprint class\n    // Expression of form xxx.FieldOrProperty\n\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2218:OverrideGetHashCodeOnOverridingEquals\", Justification = \"Overrides AddToHashCodeCombiner() instead.\")]\n    internal sealed class MemberExpressionFingerprint : ExpressionFingerprint\n    {\n        public MemberExpressionFingerprint(ExpressionType nodeType, Type type, MemberInfo member)\n            : base(nodeType, type)\n        {\n            Member = member;\n        }\n\n        // http://msdn.microsoft.com/en-us/library/system.linq.expressions.memberexpression.member.aspx\n        public MemberInfo Member { get; private set; }\n\n        public override bool Equals(object obj)\n        {\n            MemberExpressionFingerprint other = obj as MemberExpressionFingerprint;\n            return (other != null)\n                   && Equals(this.Member, other.Member)\n                   && this.Equals(other);\n        }\n\n        internal override void AddToHashCodeCombiner(HashCodeCombiner combiner)\n        {\n            combiner.AddObject(Member);\n            base.AddToHashCodeCombiner(combiner);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ExpressionUtil/MethodCallExpressionFingerprint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\nusing System.Reflection;\n\n#pragma warning disable 659 // overrides AddToHashCodeCombiner instead\n\nnamespace System.Web.Mvc.ExpressionUtil\n{\n    // MethodCallExpression fingerprint class\n    // Expression of form xxx.Foo(...), xxx[...] (get_Item()), etc.\n\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2218:OverrideGetHashCodeOnOverridingEquals\", Justification = \"Overrides AddToHashCodeCombiner() instead.\")]\n    internal sealed class MethodCallExpressionFingerprint : ExpressionFingerprint\n    {\n        public MethodCallExpressionFingerprint(ExpressionType nodeType, Type type, MethodInfo method)\n            : base(nodeType, type)\n        {\n            // Other properties on MethodCallExpression (like the argument count) are simply derived\n            // from Type and Indexer, so they're not necessary for inclusion in the fingerprint.\n\n            Method = method;\n        }\n\n        // http://msdn.microsoft.com/en-us/library/system.linq.expressions.methodcallexpression.method.aspx\n        public MethodInfo Method { get; private set; }\n\n        public override bool Equals(object obj)\n        {\n            MethodCallExpressionFingerprint other = obj as MethodCallExpressionFingerprint;\n            return (other != null)\n                   && Equals(this.Method, other.Method)\n                   && this.Equals(other);\n        }\n\n        internal override void AddToHashCodeCombiner(HashCodeCombiner combiner)\n        {\n            combiner.AddObject(Method);\n            base.AddToHashCodeCombiner(combiner);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ExpressionUtil/ParameterExpressionFingerprint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\n\n#pragma warning disable 659 // overrides AddToHashCodeCombiner instead\n\nnamespace System.Web.Mvc.ExpressionUtil\n{\n    // ParameterExpression fingerprint class\n    // Can represent the model parameter or an inner parameter in an open lambda expression\n\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2218:OverrideGetHashCodeOnOverridingEquals\", Justification = \"Overrides AddToHashCodeCombiner() instead.\")]\n    internal sealed class ParameterExpressionFingerprint : ExpressionFingerprint\n    {\n        public ParameterExpressionFingerprint(ExpressionType nodeType, Type type, int parameterIndex)\n            : base(nodeType, type)\n        {\n            ParameterIndex = parameterIndex;\n        }\n\n        // Parameter position within the overall expression, used to maintain alpha equivalence.\n        public int ParameterIndex { get; private set; }\n\n        public override bool Equals(object obj)\n        {\n            ParameterExpressionFingerprint other = obj as ParameterExpressionFingerprint;\n            return (other != null)\n                   && (this.ParameterIndex == other.ParameterIndex)\n                   && this.Equals(other);\n        }\n\n        internal override void AddToHashCodeCombiner(HashCodeCombiner combiner)\n        {\n            combiner.AddInt32(ParameterIndex);\n            base.AddToHashCodeCombiner(combiner);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ExpressionUtil/TypeBinaryExpressionFingerprint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\n\n#pragma warning disable 659 // overrides AddToHashCodeCombiner instead\n\nnamespace System.Web.Mvc.ExpressionUtil\n{\n    // TypeBinary fingerprint class\n    // Expression of form \"obj is T\"\n\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2218:OverrideGetHashCodeOnOverridingEquals\", Justification = \"Overrides AddToHashCodeCombiner() instead.\")]\n    internal sealed class TypeBinaryExpressionFingerprint : ExpressionFingerprint\n    {\n        public TypeBinaryExpressionFingerprint(ExpressionType nodeType, Type type, Type typeOperand)\n            : base(nodeType, type)\n        {\n            TypeOperand = typeOperand;\n        }\n\n        // http://msdn.microsoft.com/en-us/library/system.linq.expressions.typebinaryexpression.typeoperand.aspx\n        public Type TypeOperand { get; private set; }\n\n        public override bool Equals(object obj)\n        {\n            TypeBinaryExpressionFingerprint other = obj as TypeBinaryExpressionFingerprint;\n            return (other != null)\n                   && Equals(this.TypeOperand, other.TypeOperand)\n                   && this.Equals(other);\n        }\n\n        internal override void AddToHashCodeCombiner(HashCodeCombiner combiner)\n        {\n            combiner.AddObject(TypeOperand);\n            base.AddToHashCodeCombiner(combiner);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ExpressionUtil/UnaryExpressionFingerprint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\nusing System.Reflection;\n\n#pragma warning disable 659 // overrides AddToHashCodeCombiner instead\n\nnamespace System.Web.Mvc.ExpressionUtil\n{\n    // UnaryExpression fingerprint class\n    // The most common appearance of a UnaryExpression is a cast or other conversion operator\n\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2218:OverrideGetHashCodeOnOverridingEquals\", Justification = \"Overrides AddToHashCodeCombiner() instead.\")]\n    internal sealed class UnaryExpressionFingerprint : ExpressionFingerprint\n    {\n        public UnaryExpressionFingerprint(ExpressionType nodeType, Type type, MethodInfo method)\n            : base(nodeType, type)\n        {\n            // Other properties on UnaryExpression (like IsLifted / IsLiftedToNull) are simply derived\n            // from Type and NodeType, so they're not necessary for inclusion in the fingerprint.\n\n            Method = method;\n        }\n\n        // http://msdn.microsoft.com/en-us/library/system.linq.expressions.unaryexpression.method.aspx\n        public MethodInfo Method { get; private set; }\n\n        public override bool Equals(object obj)\n        {\n            UnaryExpressionFingerprint other = obj as UnaryExpressionFingerprint;\n            return (other != null)\n                   && Equals(this.Method, other.Method)\n                   && this.Equals(other);\n        }\n\n        internal override void AddToHashCodeCombiner(HashCodeCombiner combiner)\n        {\n            combiner.AddObject(Method);\n            base.AddToHashCodeCombiner(combiner);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/FieldValidationMetadata.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\n\nnamespace System.Web.Mvc\n{\n    public class FieldValidationMetadata\n    {\n        private readonly Collection<ModelClientValidationRule> _validationRules = new Collection<ModelClientValidationRule>();\n        private string _fieldName;\n\n        public string FieldName\n        {\n            get { return _fieldName ?? String.Empty; }\n            set { _fieldName = value; }\n        }\n\n        public bool ReplaceValidationMessageContents { get; set; }\n\n        public string ValidationMessageId { get; set; }\n\n        public ICollection<ModelClientValidationRule> ValidationRules\n        {\n            get { return _validationRules; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/FileContentResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.Mvc\n{\n    public class FileContentResult : FileResult\n    {\n        public FileContentResult(byte[] fileContents, string contentType)\n            : base(contentType)\n        {\n            if (fileContents == null)\n            {\n                throw new ArgumentNullException(\"fileContents\");\n            }\n\n            FileContents = fileContents;\n        }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1819:PropertiesShouldNotReturnArrays\", Justification = \"There's no reason to tamper-proof this array since it's supplied to the type's constructor.\")]\n        public byte[] FileContents { get; private set; }\n\n        protected override void WriteFile(HttpResponseBase response)\n        {\n            response.OutputStream.Write(FileContents, 0, FileContents.Length);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/FileExtensionsAttributeAdapter.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\n\nnamespace System.Web.Mvc\n{\n    internal class FileExtensionsAttributeAdapter : DataAnnotationsModelValidator<FileExtensionsAttribute>\n    {\n        public FileExtensionsAttributeAdapter(ModelMetadata metadata, ControllerContext context, FileExtensionsAttribute attribute)\n            : base(metadata, context, attribute)\n        {\n        }\n\n        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()\n        {\n            var rule = new ModelClientValidationRule\n            {\n                ValidationType = \"extension\",\n                ErrorMessage = ErrorMessage\n            };\n            rule.ValidationParameters[\"extension\"] = Attribute.Extensions;\n            yield return rule;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/FilePathResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    public class FilePathResult : FileResult\n    {\n        public FilePathResult(string fileName, string contentType)\n            : base(contentType)\n        {\n            if (String.IsNullOrEmpty(fileName))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"fileName\");\n            }\n\n            FileName = fileName;\n        }\n\n        public string FileName { get; private set; }\n\n        protected override void WriteFile(HttpResponseBase response)\n        {\n            response.TransmitFile(FileName);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/FileResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Mime;\nusing System.Text;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    public abstract class FileResult : ActionResult\n    {\n        private string _fileDownloadName;\n\n        protected FileResult(string contentType)\n        {\n            if (String.IsNullOrEmpty(contentType))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"contentType\");\n            }\n\n            ContentType = contentType;\n        }\n\n        public string ContentType { get; private set; }\n\n        public string FileDownloadName\n        {\n            get { return _fileDownloadName ?? String.Empty; }\n            set { _fileDownloadName = value; }\n        }\n\n        public override void ExecuteResult(ControllerContext context)\n        {\n            if (context == null)\n            {\n                throw new ArgumentNullException(\"context\");\n            }\n\n            HttpResponseBase response = context.HttpContext.Response;\n            response.ContentType = ContentType;\n\n            if (!String.IsNullOrEmpty(FileDownloadName))\n            {\n                // From RFC 2183, Sec. 2.3:\n                // The sender may want to suggest a filename to be used if the entity is\n                // detached and stored in a separate file. If the receiving MUA writes\n                // the entity to a file, the suggested filename should be used as a\n                // basis for the actual filename, where possible.\n                string headerValue = ContentDispositionUtil.GetHeaderValue(FileDownloadName);\n                context.HttpContext.Response.AddHeader(\"Content-Disposition\", headerValue);\n            }\n\n            WriteFile(response);\n        }\n\n        protected abstract void WriteFile(HttpResponseBase response);\n\n        internal static class ContentDispositionUtil\n        {\n            private const string HexDigits = \"0123456789ABCDEF\";\n\n            private static void AddByteToStringBuilder(byte b, StringBuilder builder)\n            {\n                builder.Append('%');\n\n                int i = b;\n                AddHexDigitToStringBuilder(i >> 4, builder);\n                AddHexDigitToStringBuilder(i % 16, builder);\n            }\n\n            private static void AddHexDigitToStringBuilder(int digit, StringBuilder builder)\n            {\n                builder.Append(HexDigits[digit]);\n            }\n\n            private static string CreateRfc2231HeaderValue(string filename)\n            {\n                StringBuilder builder = new StringBuilder(\"attachment; filename*=UTF-8''\");\n\n                byte[] filenameBytes = Encoding.UTF8.GetBytes(filename);\n                foreach (byte b in filenameBytes)\n                {\n                    if (IsByteValidHeaderValueCharacter(b))\n                    {\n                        builder.Append((char)b);\n                    }\n                    else\n                    {\n                        AddByteToStringBuilder(b, builder);\n                    }\n                }\n\n                return builder.ToString();\n            }\n\n            public static string GetHeaderValue(string fileName)\n            {\n                // If fileName contains any Unicode characters, encode according\n                // to RFC 2231 (with clarifications from RFC 5987)\n                foreach (char c in fileName)\n                {\n                    if ((int)c > 127)\n                    {\n                        return CreateRfc2231HeaderValue(fileName);\n                    }\n                }\n\n                // Knowing there are no Unicode characters in this fileName, rely on\n                // ContentDisposition.ToString() to encode properly.\n                // In .Net 4.0, ContentDisposition.ToString() throws FormatException if\n                // the file name contains Unicode characters.\n                // In .Net 4.5, ContentDisposition.ToString() no longer throws FormatException\n                // if it contains Unicode, and it will not encode Unicode as we require here.\n                // The Unicode test above is identical to the 4.0 FormatException test,\n                // allowing this helper to give the same results in 4.0 and 4.5.         \n                ContentDisposition disposition = new ContentDisposition() { FileName = fileName };\n                return disposition.ToString();\n            }\n\n            // Application of RFC 2231 Encoding to Hypertext Transfer Protocol (HTTP) Header Fields, sec. 3.2\n            // http://greenbytes.de/tech/webdav/draft-reschke-rfc2231-in-http-latest.html\n            private static bool IsByteValidHeaderValueCharacter(byte b)\n            {\n                if ((byte)'0' <= b && b <= (byte)'9')\n                {\n                    return true; // is digit\n                }\n                if ((byte)'a' <= b && b <= (byte)'z')\n                {\n                    return true; // lowercase letter\n                }\n                if ((byte)'A' <= b && b <= (byte)'Z')\n                {\n                    return true; // uppercase letter\n                }\n\n                switch (b)\n                {\n                    case (byte)'-':\n                    case (byte)'.':\n                    case (byte)'_':\n                    case (byte)'~':\n                    case (byte)':':\n                    case (byte)'!':\n                    case (byte)'$':\n                    case (byte)'&':\n                    case (byte)'+':\n                        return true;\n                }\n\n                return false;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/FileStreamResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\n\nnamespace System.Web.Mvc\n{\n    public class FileStreamResult : FileResult\n    {\n        // default buffer size as defined in BufferedStream type\n        private const int BufferSize = 0x1000;\n\n        public FileStreamResult(Stream fileStream, string contentType)\n            : base(contentType)\n        {\n            if (fileStream == null)\n            {\n                throw new ArgumentNullException(\"fileStream\");\n            }\n\n            FileStream = fileStream;\n        }\n\n        public Stream FileStream { get; private set; }\n\n        protected override void WriteFile(HttpResponseBase response)\n        {\n            // grab chunks of data and write to the output stream\n            Stream outputStream = response.OutputStream;\n            using (FileStream)\n            {\n                byte[] buffer = new byte[BufferSize];\n\n                while (true)\n                {\n                    int bytesRead = FileStream.Read(buffer, 0, BufferSize);\n                    if (bytesRead == 0)\n                    {\n                        // no more data\n                        break;\n                    }\n\n                    outputStream.Write(buffer, 0, bytesRead);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Filter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public class Filter\n    {\n        public const int DefaultOrder = -1;\n\n        public Filter(object instance, FilterScope scope, int? order)\n        {\n            if (instance == null)\n            {\n                throw new ArgumentNullException(\"instance\");\n            }\n\n            if (order == null)\n            {\n                IMvcFilter mvcFilter = instance as IMvcFilter;\n                if (mvcFilter != null)\n                {\n                    order = mvcFilter.Order;\n                }\n            }\n\n            Instance = instance;\n            Order = order ?? DefaultOrder;\n            Scope = scope;\n        }\n\n        public object Instance { get; protected set; }\n\n        public int Order { get; protected set; }\n\n        public FilterScope Scope { get; protected set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/FilterAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Linq;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\n    public abstract class FilterAttribute : Attribute, IMvcFilter\n    {\n        private static readonly ConcurrentDictionary<Type, bool> _multiuseAttributeCache = new ConcurrentDictionary<Type, bool>();\n        private int _order = Filter.DefaultOrder;\n\n        public bool AllowMultiple\n        {\n            get { return AllowsMultiple(GetType()); }\n        }\n\n        public int Order\n        {\n            get { return _order; }\n            set\n            {\n                if (value < Filter.DefaultOrder)\n                {\n                    throw new ArgumentOutOfRangeException(\"value\", MvcResources.FilterAttribute_OrderOutOfRange);\n                }\n                _order = value;\n            }\n        }\n\n        private static bool AllowsMultiple(Type attributeType)\n        {\n            return _multiuseAttributeCache.GetOrAdd(\n                attributeType,\n                type => type.GetCustomAttributes(typeof(AttributeUsageAttribute), true)\n                            .Cast<AttributeUsageAttribute>()\n                            .First()\n                            .AllowMultiple);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/FilterAttributeFilterProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace System.Web.Mvc\n{\n    public class FilterAttributeFilterProvider : IFilterProvider\n    {\n        private readonly bool _cacheAttributeInstances;\n\n        public FilterAttributeFilterProvider()\n            : this(true)\n        {\n        }\n\n        public FilterAttributeFilterProvider(bool cacheAttributeInstances)\n        {\n            _cacheAttributeInstances = cacheAttributeInstances;\n        }\n\n        protected virtual IEnumerable<FilterAttribute> GetActionAttributes(ControllerContext controllerContext, ActionDescriptor actionDescriptor)\n        {\n            return actionDescriptor.GetFilterAttributes(_cacheAttributeInstances);\n        }\n\n        protected virtual IEnumerable<FilterAttribute> GetControllerAttributes(ControllerContext controllerContext, ActionDescriptor actionDescriptor)\n        {\n            return actionDescriptor.ControllerDescriptor.GetFilterAttributes(_cacheAttributeInstances);\n        }\n\n        public virtual IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)\n        {\n            // Results are low in number in the common case so use yield return to avoid creating intermediate collections or nested enumerables\n            if (controllerContext.Controller != null)\n            {\n                foreach (FilterAttribute attr in GetControllerAttributes(controllerContext, actionDescriptor))\n                {\n                    yield return new Filter(attr, FilterScope.Controller, order: null);\n                }\n                foreach (FilterAttribute attr in GetActionAttributes(controllerContext, actionDescriptor))\n                {\n                    yield return new Filter(attr, FilterScope.Action, order: null);\n                }\n            }             \n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/FilterInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Web.Mvc.Filters;\n\nnamespace System.Web.Mvc\n{\n    public class FilterInfo\n    {\n        private readonly List<IActionFilter> _actionFilters = new List<IActionFilter>();\n        private readonly List<IAuthenticationFilter> _authenticationFilters = new List<IAuthenticationFilter>();\n        private readonly List<IAuthorizationFilter> _authorizationFilters = new List<IAuthorizationFilter>();\n        private readonly List<IExceptionFilter> _exceptionFilters = new List<IExceptionFilter>();\n        private readonly List<IResultFilter> _resultFilters = new List<IResultFilter>();\n\n        public FilterInfo()\n        {\n        }\n\n        public FilterInfo(IEnumerable<Filter> filters)\n        {\n            // Determine the override scope for each filter type and cache the filters list.\n            OverrideFilterInfo processed = ProcessOverrideFilters(filters);\n            // Split the cached filters list based on filter type and override scope.\n            SplitFilters(processed);\n        }\n\n        public IList<IActionFilter> ActionFilters\n        {\n            get { return _actionFilters; }\n        }\n\n        public IList<IAuthenticationFilter> AuthenticationFilters\n        {\n            get { return _authenticationFilters; }\n        }\n\n        public IList<IAuthorizationFilter> AuthorizationFilters\n        {\n            get { return _authorizationFilters; }\n        }\n\n        public IList<IExceptionFilter> ExceptionFilters\n        {\n            get { return _exceptionFilters; }\n        }\n\n        public IList<IResultFilter> ResultFilters\n        {\n            get { return _resultFilters; }\n        }\n\n        private static OverrideFilterInfo ProcessOverrideFilters(IEnumerable<Filter> filters)\n        {\n            OverrideFilterInfo result = new OverrideFilterInfo\n            {\n                ActionOverrideScope = FilterScope.First,\n                AuthenticationOverrideScope = FilterScope.First,\n                AuthorizationOverrideScope = FilterScope.First,\n                ExceptionOverrideScope = FilterScope.First,\n                ResultOverrideScope = FilterScope.First,\n                Filters = new List<Filter>()\n            };\n\n            // Evaluate the 'filters' enumerable only once since the operation can be quite expensive.\n            foreach (Filter filter in filters)\n            {\n                if (filter == null)\n                {\n                    continue;\n                }\n                IOverrideFilter overrideFilter = filter.Instance as IOverrideFilter;\n\n                if (overrideFilter != null)\n                {\n                    if (overrideFilter.FiltersToOverride == typeof(IActionFilter)\n                        && filter.Scope >= result.ActionOverrideScope)\n                    {\n                        result.ActionOverrideScope = filter.Scope;\n                    }\n                    else if (overrideFilter.FiltersToOverride == typeof(IAuthenticationFilter)\n                        && filter.Scope >= result.AuthenticationOverrideScope)\n                    {\n                        result.AuthenticationOverrideScope = filter.Scope;\n                    }\n                    else if (overrideFilter.FiltersToOverride == typeof(IAuthorizationFilter)\n                        && filter.Scope >= result.AuthorizationOverrideScope)\n                    {\n                        result.AuthorizationOverrideScope = filter.Scope;\n                    }\n                    else if (overrideFilter.FiltersToOverride == typeof(IExceptionFilter)\n                        && filter.Scope >= result.ExceptionOverrideScope)\n                    {\n                        result.ExceptionOverrideScope = filter.Scope;\n                    }\n                    else if (overrideFilter.FiltersToOverride == typeof(IResultFilter)\n                        && filter.Scope >= result.ResultOverrideScope)\n                    {\n                        result.ResultOverrideScope = filter.Scope;\n                    }\n                }\n\n                // Cache filters to avoid having to enumerate it again (expensive). Do so here to avoid an extra loop.\n                result.Filters.Add(filter);\n            }\n\n            return result;\n        }\n\n        private void SplitFilters(OverrideFilterInfo info)\n        {\n            Contract.Assert(info.Filters != null);\n\n            foreach (Filter filter in info.Filters)\n            {\n                Contract.Assert(filter != null);\n\n                IActionFilter actionFilter = filter.Instance as IActionFilter;\n\n                if (actionFilter != null && filter.Scope >= info.ActionOverrideScope)\n                {\n                    _actionFilters.Add(actionFilter);\n                }\n\n                IAuthenticationFilter authenticationFilter = filter.Instance as IAuthenticationFilter;\n\n                if (authenticationFilter != null && filter.Scope >= info.AuthenticationOverrideScope)\n                {\n                    _authenticationFilters.Add(authenticationFilter);\n                }\n\n                IAuthorizationFilter authorizationFilter = filter.Instance as IAuthorizationFilter;\n\n                if (authorizationFilter != null && filter.Scope >= info.AuthorizationOverrideScope)\n                {\n                    _authorizationFilters.Add(authorizationFilter);\n                }\n\n                IExceptionFilter exceptionFilter = filter.Instance as IExceptionFilter;\n\n                if (exceptionFilter != null && filter.Scope >= info.ExceptionOverrideScope)\n                {\n                    _exceptionFilters.Add(exceptionFilter);\n                }\n\n                IResultFilter resultFilter = filter.Instance as IResultFilter;\n\n                if (resultFilter != null && filter.Scope >= info.ResultOverrideScope)\n                {\n                    _resultFilters.Add(resultFilter);\n                }\n            }\n        }\n\n        private struct OverrideFilterInfo\n        {\n            public FilterScope ActionOverrideScope;\n            public FilterScope AuthenticationOverrideScope;\n            public FilterScope AuthorizationOverrideScope;\n            public FilterScope ExceptionOverrideScope;\n            public FilterScope ResultOverrideScope;\n\n            public List<Filter> Filters;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/FilterProviderCollection.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\n\nnamespace System.Web.Mvc\n{\n    public class FilterProviderCollection : Collection<IFilterProvider>\n    {\n        private static FilterComparer _filterComparer = new FilterComparer();\n        private IFilterProvider[] _combinedItems;\n        private IDependencyResolver _dependencyResolver;\n\n        public FilterProviderCollection()\n        {\n        }\n\n        public FilterProviderCollection(IList<IFilterProvider> providers)\n            : base(providers)\n        {\n        }\n\n        internal FilterProviderCollection(IList<IFilterProvider> list, IDependencyResolver dependencyResolver)\n            : base(list)\n        {\n            _dependencyResolver = dependencyResolver;\n        }\n\n        internal IFilterProvider[] CombinedItems\n        {\n            get\n            {\n                IFilterProvider[] combinedItems = _combinedItems;\n                if (combinedItems == null)\n                {\n                    combinedItems = MultiServiceResolver.GetCombined<IFilterProvider>(Items, _dependencyResolver);\n                    _combinedItems = combinedItems;\n                }\n                return combinedItems;\n            }\n        }\n\n        private static bool AllowMultiple(object filterInstance)\n        {\n            IMvcFilter mvcFilter = filterInstance as IMvcFilter;\n            if (mvcFilter == null)\n            {\n                return true;\n            }\n\n            return mvcFilter.AllowMultiple;\n        }\n\n        public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n            if (actionDescriptor == null)\n            {\n                throw new ArgumentNullException(\"actionDescriptor\");\n            }\n\n            IFilterProvider[] providers = CombinedItems;\n            List<Filter> filters = new List<Filter>();\n            for (int i = 0; i < providers.Length; i++)\n            {\n                IFilterProvider provider = providers[i];\n                foreach (Filter filter in provider.GetFilters(controllerContext, actionDescriptor))\n                {\n                    filters.Add(filter);\n                }\n            }\n\n            filters.Sort(_filterComparer);\n\n            if (filters.Count > 1)\n            {\n                RemoveDuplicates(filters);\n            }\n            return filters;\n        }\n\n        private static void RemoveDuplicates(List<Filter> filters)\n        {\n            HashSet<Type> visitedTypes = new HashSet<Type>();\n\n            // Remove duplicates from the back forward\n            for (int i = filters.Count - 1; i >= 0; i--)\n            {\n                Filter filter = filters[i];\n                object filterInstance = filter.Instance;\n                Type filterInstanceType = filterInstance.GetType();\n\n                if (!visitedTypes.Contains(filterInstanceType) || AllowMultiple(filterInstance))\n                {\n                    visitedTypes.Add(filterInstanceType);\n                }\n                else\n                {\n                    filters.RemoveAt(i);                        \n                }\n            }\n        }\n\n        protected override void ClearItems()\n        {\n            _combinedItems = null;\n            base.ClearItems();\n        }\n\n        protected override void InsertItem(int index, IFilterProvider item)\n        {\n            _combinedItems = null;\n            base.InsertItem(index, item);\n        }\n\n        protected override void RemoveItem(int index)\n        {\n            _combinedItems = null;\n            base.RemoveItem(index);\n        }\n\n        protected override void SetItem(int index, IFilterProvider item)\n        {\n            _combinedItems = null;\n            base.SetItem(index, item);\n        }\n\n        private class FilterComparer : IComparer<Filter>\n        {\n            public int Compare(Filter x, Filter y)\n            {\n                // Nulls always have to be less than non-nulls\n                if (x == null && y == null)\n                {\n                    return 0;\n                }\n                if (x == null)\n                {\n                    return -1;\n                }\n                if (y == null)\n                {\n                    return 1;\n                }\n\n                // Sort first by order...\n\n                if (x.Order < y.Order)\n                {\n                    return -1;\n                }\n                if (x.Order > y.Order)\n                {\n                    return 1;\n                }\n\n                // ...then by scope\n\n                if (x.Scope < y.Scope)\n                {\n                    return -1;\n                }\n                if (x.Scope > y.Scope)\n                {\n                    return 1;\n                }\n\n                return 0;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/FilterProviders.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public static class FilterProviders\n    {\n        static FilterProviders()\n        {\n            Providers = new FilterProviderCollection();\n            Providers.Add(GlobalFilters.Filters);\n            Providers.Add(new FilterAttributeFilterProvider());\n            Providers.Add(new ControllerInstanceFilterProvider());\n        }\n\n        public static FilterProviderCollection Providers { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/FilterScope.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public enum FilterScope\n    {\n        First = 0,\n        Global = 10,\n        Controller = 20,\n        Action = 30,\n        Last = 100,\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Filters/AuthenticationChallengeContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc.Filters\n{\n    /// <summary>\n    /// Represents an authentication challenge context containing information for executing an authentication\n    /// challenge.\n    /// </summary>\n    public class AuthenticationChallengeContext : ControllerContext\n    {\n        private ActionDescriptor _actionDescriptor;\n        private ActionResult _result;\n\n        /// <summary>Initializes a new instance of the <see cref=\"AuthenticationChallengeContext\"/> class.</summary>\n        /// <remarks>This constructor should only be used for unit testing purposes.</remarks>\n        public AuthenticationChallengeContext()\n        {\n        }\n\n        /// <summary>Initializes a new instance of the <see cref=\"AuthenticationChallengeContext\"/> class.</summary>\n        /// <param name=\"controllerContext\">The controller context.</param>\n        /// <param name=\"actionDescriptor\">The action descriptor.</param>\n        /// <param name=\"result\">The current action result.</param>\n        public AuthenticationChallengeContext(ControllerContext controllerContext, ActionDescriptor actionDescriptor,\n            ActionResult result)\n            : base(controllerContext)\n        {\n            if (actionDescriptor == null)\n            {\n                throw new ArgumentNullException(\"actionDescriptor\");\n            }\n\n            if (result == null)\n            {\n                throw new ArgumentNullException(\"result\");\n            }\n\n            _actionDescriptor = actionDescriptor;\n            _result = result;\n        }\n\n        /// <summary>Gets or sets the action descriptor.</summary>\n        public ActionDescriptor ActionDescriptor\n        {\n            get\n            {\n                return _actionDescriptor;\n            }\n            set\n            {\n                _actionDescriptor = value;\n            }\n        }\n\n        /// <summary>Gets or sets the action result to execute.</summary>\n        /// <remarks>\n        /// Authentication filters wishing to add an authentication challenge will often chain the result (set the\n        /// value to an action result that executes the previous value and then does something additional, such as add\n        /// a WWW-Authenticate header).\n        /// </remarks>\n        public ActionResult Result\n        {\n            get\n            {\n                return _result;\n            }\n            set\n            {\n                _result = value;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Filters/AuthenticationContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Security.Principal;\n\nnamespace System.Web.Mvc.Filters\n{\n    /// <summary>Represents an authentication context containing information for performing authentication.</summary>\n    public class AuthenticationContext : ControllerContext\n    {\n        /// <summary>Initializes a new instance of the <see cref=\"AuthenticationContext\"/> class.</summary>\n        /// <remarks>This constructor should only be used for unit testing purposes.</remarks>\n        public AuthenticationContext()\n        {\n        }\n\n        /// <summary>Initializes a new instance of the <see cref=\"AuthenticationContext\"/> class.</summary>\n        /// <param name=\"controllerContext\">The controller context.</param>\n        /// <param name=\"actionDescriptor\">The action descriptor.</param>\n        /// <param name=\"principal\">The current principal.</param>\n        public AuthenticationContext(ControllerContext controllerContext, ActionDescriptor actionDescriptor,\n            IPrincipal principal)\n            : base(controllerContext)\n        {\n            if (actionDescriptor == null)\n            {\n                throw new ArgumentNullException(\"actionDescriptor\");\n            }\n\n            ActionDescriptor = actionDescriptor;\n            Principal = principal;\n        }\n\n        /// <summary>Gets or sets the action descriptor.</summary>\n        public ActionDescriptor ActionDescriptor { get; set; }\n\n        /// <summary>Gets or sets the currently authenticated principal.</summary>\n        public IPrincipal Principal { get; set; }\n\n        /// <summary>\n        /// Gets or sets the error result, which indicates that authentication was attempted and failed.\n        /// </summary>\n        public ActionResult Result { get; set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Filters/IAuthenticationFilter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc.Filters\n{\n    /// <summary>Defines a filter that performs authentication.</summary>\n    public interface IAuthenticationFilter\n    {\n        /// <summary>Authenticates the request.</summary>\n        /// <param name=\"filterContext\">The context to use for authentication.</param>\n        void OnAuthentication(AuthenticationContext filterContext);\n\n        /// <summary>Adds an authentication challenge to the current <see cref=\"ActionResult\"/>.</summary>\n        /// <param name=\"filterContext\">The context to use for the authentication challenge.</param>\n        void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Filters/IOverrideFilter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc.Filters\n{\n    /// <summary>Defines a filter that overrides other filters.</summary>\n    public interface IOverrideFilter\n    {\n        /// <summary>Gets the type of filters to override.</summary>\n        /// <remarks>\n        /// The following types of filters may be overridden:\n        /// <list type=\"bullet\">\n        /// <item><description><see cref=\"IActionFilter\"/></description></item>\n        /// <item><description><see cref=\"IAuthenticationFilter\"/></description></item>\n        /// <item><description><see cref=\"IAuthorizationFilter\"/></description></item>\n        /// <item><description><see cref=\"IExceptionFilter\"/></description></item>\n        /// <item><description><see cref=\"IResultFilter\"/></description></item>\n        /// </list>\n        /// </remarks>\n        Type FiltersToOverride { get; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/FormCollection.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Web.Helpers;\n\nnamespace System.Web.Mvc\n{\n    [SuppressMessage(\"Microsoft.Usage\", \"CA2237:MarkISerializableTypesWithSerializable\", Justification = \"It is not anticipated that users will need to serialize this type.\")]\n    [SuppressMessage(\"Microsoft.Design\", \"CA1035:ICollectionImplementationsHaveStronglyTypedMembers\", Justification = \"It is not anticipated that users will call FormCollection.CopyTo().\")]\n    [FormCollectionBinder]\n    public sealed class FormCollection : NameValueCollection, IValueProvider\n    {\n        public FormCollection()\n        {\n        }\n\n        public FormCollection(NameValueCollection collection)\n        {\n            if (collection == null)\n            {\n                throw new ArgumentNullException(\"collection\");\n            }\n\n            Add(collection);\n        }\n\n        internal FormCollection(ControllerBase controller, Func<NameValueCollection> validatedValuesThunk, Func<NameValueCollection> unvalidatedValuesThunk)\n        {\n            Add(controller == null || controller.ValidateRequest ? validatedValuesThunk() : unvalidatedValuesThunk());\n        }\n\n        public ValueProviderResult GetValue(string name)\n        {\n            if (name == null)\n            {\n                throw new ArgumentNullException(\"name\");\n            }\n\n            string[] rawValue = GetValues(name);\n            if (rawValue == null)\n            {\n                return null;\n            }\n\n            string attemptedValue = this[name];\n            return new ValueProviderResult(rawValue, attemptedValue, CultureInfo.CurrentCulture);\n        }\n\n        public IValueProvider ToValueProvider()\n        {\n            return this;\n        }\n\n        #region IValueProvider Members\n\n        bool IValueProvider.ContainsPrefix(string prefix)\n        {\n            return ValueProviderUtil.CollectionContainsPrefix(AllKeys, prefix);\n        }\n\n        ValueProviderResult IValueProvider.GetValue(string key)\n        {\n            return GetValue(key);\n        }\n\n        #endregion\n\n        private sealed class FormCollectionBinderAttribute : CustomModelBinderAttribute\n        {\n            // since the FormCollectionModelBinder.BindModel() method is thread-safe, we only need to keep\n            // a single instance of the binder around\n            private static readonly FormCollectionModelBinder _binder = new FormCollectionModelBinder();\n\n            public override IModelBinder GetBinder()\n            {\n                return _binder;\n            }\n\n            // this class is used for generating a FormCollection object\n            private sealed class FormCollectionModelBinder : IModelBinder\n            {\n                public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)\n                {\n                    if (controllerContext == null)\n                    {\n                        throw new ArgumentNullException(\"controllerContext\");\n                    }\n\n                    return new FormCollection(controllerContext.Controller,\n                                              () => controllerContext.HttpContext.Request.Form,\n                                              () => controllerContext.HttpContext.Request.Unvalidated.Form);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/FormContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Script.Serialization;\n\nnamespace System.Web.Mvc\n{\n    public class FormContext\n    {\n        private readonly Dictionary<string, FieldValidationMetadata> _fieldValidators = new Dictionary<string, FieldValidationMetadata>();\n        private readonly Dictionary<string, bool> _renderedFields = new Dictionary<string, bool>();\n\n        public IDictionary<string, FieldValidationMetadata> FieldValidators\n        {\n            get { return _fieldValidators; }\n        }\n\n        public string FormId { get; set; }\n\n        public bool ReplaceValidationSummary { get; set; }\n\n        public string ValidationSummaryId { get; set; }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Justification = \"Performs a potentially time-consuming conversion.\")]\n        public string GetJsonValidationMetadata()\n        {\n            JavaScriptSerializer serializer = new JavaScriptSerializer();\n\n            SortedDictionary<string, object> dict = new SortedDictionary<string, object>()\n            {\n                { \"Fields\", FieldValidators.Values },\n                { \"FormId\", FormId }\n            };\n            if (!String.IsNullOrEmpty(ValidationSummaryId))\n            {\n                dict[\"ValidationSummaryId\"] = ValidationSummaryId;\n            }\n            dict[\"ReplaceValidationSummary\"] = ReplaceValidationSummary;\n\n            return serializer.Serialize(dict);\n        }\n\n        public FieldValidationMetadata GetValidationMetadataForField(string fieldName)\n        {\n            return GetValidationMetadataForField(fieldName, false /* createIfNotFound */);\n        }\n\n        public FieldValidationMetadata GetValidationMetadataForField(string fieldName, bool createIfNotFound)\n        {\n            if (String.IsNullOrEmpty(fieldName))\n            {\n                throw Error.ParameterCannotBeNullOrEmpty(\"fieldName\");\n            }\n\n            FieldValidationMetadata metadata;\n            if (!FieldValidators.TryGetValue(fieldName, out metadata))\n            {\n                if (createIfNotFound)\n                {\n                    metadata = new FieldValidationMetadata()\n                    {\n                        FieldName = fieldName\n                    };\n                    FieldValidators[fieldName] = metadata;\n                }\n            }\n            return metadata;\n        }\n\n        public bool RenderedField(string fieldName)\n        {\n            bool result;\n            _renderedFields.TryGetValue(fieldName, out result);\n            return result;\n        }\n\n        public void RenderedField(string fieldName, bool value)\n        {\n            _renderedFields[fieldName] = value;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/FormMethod.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public enum FormMethod\n    {\n        Get,\n        Post\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/FormValueProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Web.Helpers;\n\nnamespace System.Web.Mvc\n{\n    public sealed class FormValueProvider : NameValueCollectionValueProvider\n    {\n        public FormValueProvider(ControllerContext controllerContext)\n            : this(controllerContext, new UnvalidatedRequestValuesWrapper(controllerContext.HttpContext.Request.Unvalidated))\n        {\n        }\n\n        // For unit testing\n        internal FormValueProvider(ControllerContext controllerContext, IUnvalidatedRequestValues unvalidatedValues)\n            : base(controllerContext.HttpContext.Request.Form, unvalidatedValues.Form, CultureInfo.CurrentCulture)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/FormValueProviderFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Helpers;\n\nnamespace System.Web.Mvc\n{\n    public sealed class FormValueProviderFactory : ValueProviderFactory\n    {\n        private readonly UnvalidatedRequestValuesAccessor _unvalidatedValuesAccessor;\n\n        public FormValueProviderFactory()\n            : this(null)\n        {\n        }\n\n        // For unit testing\n        internal FormValueProviderFactory(UnvalidatedRequestValuesAccessor unvalidatedValuesAccessor)\n        {\n            _unvalidatedValuesAccessor = unvalidatedValuesAccessor ?? (cc => new UnvalidatedRequestValuesWrapper(cc.HttpContext.Request.Unvalidated));\n        }\n\n        public override IValueProvider GetValueProvider(ControllerContext controllerContext)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n\n            return new FormValueProvider(controllerContext, _unvalidatedValuesAccessor(controllerContext));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/GlobalFilterCollection.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Mvc.Filters;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    public sealed class GlobalFilterCollection : IEnumerable<Filter>, IFilterProvider\n    {\n        private List<Filter> _filters = new List<Filter>();\n\n        public int Count\n        {\n            get { return _filters.Count; }\n        }\n\n        public void Add(object filter)\n        {\n            AddInternal(filter, order: null);\n        }\n\n        public void Add(object filter, int order)\n        {\n            AddInternal(filter, order);\n        }\n\n        private void AddInternal(object filter, int? order)\n        {\n            ValidateFilterInstance(filter);\n            _filters.Add(new Filter(filter, FilterScope.Global, order));\n        }\n\n        public void Clear()\n        {\n            _filters.Clear();\n        }\n\n        public bool Contains(object filter)\n        {\n            return _filters.Any(f => f.Instance == filter);\n        }\n\n        public IEnumerator<Filter> GetEnumerator()\n        {\n            return _filters.GetEnumerator();\n        }\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return _filters.GetEnumerator();\n        }\n\n        IEnumerable<Filter> IFilterProvider.GetFilters(ControllerContext controllerContext,\n            ActionDescriptor actionDescriptor)\n        {\n            return this;\n        }\n\n        public void Remove(object filter)\n        {\n            _filters.RemoveAll(f => f.Instance == filter);\n        }\n\n        private static void ValidateFilterInstance(object instance)\n        {\n            if (instance != null && !(\n                instance is IActionFilter ||\n                instance is IAuthorizationFilter ||\n                instance is IExceptionFilter ||\n                instance is IResultFilter ||\n                instance is IAuthenticationFilter))\n            {\n                throw Error.InvalidOperation(MvcResources.GlobalFilterCollection_UnsupportedFilterInstance,\n                    typeof(IAuthorizationFilter).FullName,\n                    typeof(IActionFilter).FullName,\n                    typeof(IResultFilter).FullName,\n                    typeof(IExceptionFilter).FullName,\n                    typeof(IAuthenticationFilter).FullName);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/GlobalFilters.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public static class GlobalFilters\n    {\n        static GlobalFilters()\n        {\n            Filters = new GlobalFilterCollection();\n        }\n\n        public static GlobalFilterCollection Filters { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/GlobalSuppressions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n// This file is used by Code Analysis to maintain SuppressMessage \n// attributes that are applied to this project. \n// Project-level suppressions either have no target or are given \n// a specific target and scoped to a namespace, type, member, etc. \n//\n// To add a suppression to this file, right-click the message in the \n// Error List, point to \"Suppress Message(s)\", and click \n// \"In Project Suppression File\". \n// You do not need to add suppressions to this file manually. \n\nusing System.Diagnostics.CodeAnalysis;\n\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA2210:AssembliesShouldHaveValidStrongNames\", Justification = \"Assembly is delay-signed.\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"System.Web.Mvc.Ajax\", Justification = \"Helpers reside within a separate namespace to support alternate helper classes.\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1033:InterfaceMethodsShouldBeCallableByChildTypes\", Scope = \"member\", Target = \"System.Web.Mvc.TempDataDictionary.#System.Collections.Generic.ICollection`1<System.Collections.Generic.KeyValuePair`2<System.String,System.Object>>.Contains(System.Collections.Generic.KeyValuePair`2<System.String,System.Object>)\", Justification = \"There are no defined scenarios for wanting to derive from this class, but we don't want to prevent it either.\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1033:InterfaceMethodsShouldBeCallableByChildTypes\", Scope = \"member\", Target = \"System.Web.Mvc.TempDataDictionary.#System.Collections.Generic.ICollection`1<System.Collections.Generic.KeyValuePair`2<System.String,System.Object>>.CopyTo(System.Collections.Generic.KeyValuePair`2<System.String,System.Object>[],System.Int32)\", Justification = \"There are no defined scenarios for wanting to derive from this class, but we don't want to prevent it either.\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1033:InterfaceMethodsShouldBeCallableByChildTypes\", Scope = \"member\", Target = \"System.Web.Mvc.TempDataDictionary.#System.Collections.Generic.ICollection`1<System.Collections.Generic.KeyValuePair`2<System.String,System.Object>>.IsReadOnly\", Justification = \"There are no defined scenarios for wanting to derive from this class, but we don't want to prevent it either.\")]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1703:ResourceStringsShouldBeSpelledCorrectly\", MessageId = \"Param\", Scope = \"resource\", Target = \"System.Web.Mvc.Properties.MvcResources.resources\", Justification = \"This is the name that matches ASP.NET\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"System.Web.Mvc.Razor\", Justification = \"This is a grouping of functionally similar components, thus a namespace is a valid way to group them.\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"System.Web.Mvc.Filters\", Justification = \"Starting to move away from one big namespace. We have to start (small) somewhere.\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"System.Web.Mvc.Routing\", Justification = \"Starting to move away from one big namespace. We have to start (small) somewhere.\")]"
  },
  {
    "path": "src/System.Web.Mvc/HandleErrorAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    [SuppressMessage(\"Microsoft.Performance\", \"CA1813:AvoidUnsealedAttributes\", Justification = \"This attribute is AllowMultiple = true and users might want to override behavior.\")]\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]\n    public class HandleErrorAttribute : FilterAttribute, IExceptionFilter\n    {\n        private const string DefaultView = \"Error\";\n\n        private readonly object _typeId = new object();\n\n        private Type _exceptionType = typeof(Exception);\n        private string _master;\n        private string _view;\n\n        public Type ExceptionType\n        {\n            get { return _exceptionType; }\n            set\n            {\n                if (value == null)\n                {\n                    throw new ArgumentNullException(\"value\");\n                }\n                if (!typeof(Exception).IsAssignableFrom(value))\n                {\n                    throw new ArgumentException(String.Format(CultureInfo.CurrentCulture,\n                                                              MvcResources.ExceptionViewAttribute_NonExceptionType, value.FullName));\n                }\n\n                _exceptionType = value;\n            }\n        }\n\n        public string Master\n        {\n            get { return _master ?? String.Empty; }\n            set { _master = value; }\n        }\n\n        public override object TypeId\n        {\n            get { return _typeId; }\n        }\n\n        public string View\n        {\n            get { return (!String.IsNullOrEmpty(_view)) ? _view : DefaultView; }\n            set { _view = value; }\n        }\n\n        public virtual void OnException(ExceptionContext filterContext)\n        {\n            if (filterContext == null)\n            {\n                throw new ArgumentNullException(\"filterContext\");\n            }\n            if (filterContext.IsChildAction)\n            {\n                return;\n            }\n\n            // If custom errors are disabled, we need to let the normal ASP.NET exception handler\n            // execute so that the user can see useful debugging information.\n            if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)\n            {\n                return;\n            }\n\n            Exception exception = filterContext.Exception;\n\n            // If this is not an HTTP 500 (for example, if somebody throws an HTTP 404 from an action method),\n            // ignore it.\n            if (new HttpException(null, exception).GetHttpCode() != 500)\n            {\n                return;\n            }\n\n            if (!ExceptionType.IsInstanceOfType(exception))\n            {\n                return;\n            }\n\n            string controllerName = (string)filterContext.RouteData.Values[\"controller\"];\n            string actionName = (string)filterContext.RouteData.Values[\"action\"];\n            HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);\n            filterContext.Result = new ViewResult\n            {\n                ViewName = View,\n                MasterName = Master,\n                ViewData = new ViewDataDictionary<HandleErrorInfo>(model),\n                TempData = filterContext.Controller.TempData\n            };\n            filterContext.ExceptionHandled = true;\n            filterContext.HttpContext.Response.Clear();\n            filterContext.HttpContext.Response.StatusCode = 500;\n\n            // Certain versions of IIS will sometimes use their own error page when\n            // they detect a server error. Setting this property indicates that we\n            // want it to try to render ASP.NET MVC's error page instead.\n            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/HandleErrorInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    public class HandleErrorInfo\n    {\n        public HandleErrorInfo(Exception exception, string controllerName, string actionName)\n        {\n            if (exception == null)\n            {\n                throw new ArgumentNullException(\"exception\");\n            }\n            if (String.IsNullOrEmpty(controllerName))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"controllerName\");\n            }\n            if (String.IsNullOrEmpty(actionName))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"actionName\");\n            }\n\n            Exception = exception;\n            ControllerName = controllerName;\n            ActionName = actionName;\n        }\n\n        public string ActionName { get; private set; }\n\n        public string ControllerName { get; private set; }\n\n        public Exception Exception { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/HiddenInputAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]\n    public sealed class HiddenInputAttribute : Attribute\n    {\n        public HiddenInputAttribute()\n        {\n            DisplayValue = true;\n        }\n\n        public bool DisplayValue { get; set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Html/ChildActionExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Web.Mvc.Properties;\nusing System.Web.Mvc.Routing;\nusing System.Web.Routing;\nusing System.Web.WebPages;\n\nnamespace System.Web.Mvc.Html\n{\n    public static class ChildActionExtensions\n    {\n        // Action\n\n        public static MvcHtmlString Action(this HtmlHelper htmlHelper, string actionName)\n        {\n            return Action(htmlHelper, actionName, null /* controllerName */, null /* routeValues */);\n        }\n\n        public static MvcHtmlString Action(this HtmlHelper htmlHelper, string actionName, object routeValues)\n        {\n            return Action(htmlHelper, actionName, null /* controllerName */, TypeHelper.ObjectToDictionary(routeValues));\n        }\n\n        public static MvcHtmlString Action(this HtmlHelper htmlHelper, string actionName, RouteValueDictionary routeValues)\n        {\n            return Action(htmlHelper, actionName, null /* controllerName */, routeValues);\n        }\n\n        public static MvcHtmlString Action(this HtmlHelper htmlHelper, string actionName, string controllerName)\n        {\n            return Action(htmlHelper, actionName, controllerName, null /* routeValues */);\n        }\n\n        public static MvcHtmlString Action(this HtmlHelper htmlHelper, string actionName, string controllerName, object routeValues)\n        {\n            return Action(htmlHelper, actionName, controllerName, TypeHelper.ObjectToDictionary(routeValues));\n        }\n\n        public static MvcHtmlString Action(this HtmlHelper htmlHelper, string actionName, string controllerName, RouteValueDictionary routeValues)\n        {\n            using (StringWriter writer = new StringWriter(CultureInfo.CurrentCulture))\n            {\n                ActionHelper(htmlHelper, actionName, controllerName, routeValues, writer);\n                return MvcHtmlString.Create(writer.ToString());\n            }\n        }\n\n        // RenderAction\n\n        public static void RenderAction(this HtmlHelper htmlHelper, string actionName)\n        {\n            RenderAction(htmlHelper, actionName, null /* controllerName */, null /* routeValues */);\n        }\n\n        public static void RenderAction(this HtmlHelper htmlHelper, string actionName, object routeValues)\n        {\n            RenderAction(htmlHelper, actionName, null /* controllerName */, TypeHelper.ObjectToDictionary(routeValues));\n        }\n\n        public static void RenderAction(this HtmlHelper htmlHelper, string actionName, RouteValueDictionary routeValues)\n        {\n            RenderAction(htmlHelper, actionName, null /* controllerName */, routeValues);\n        }\n\n        public static void RenderAction(this HtmlHelper htmlHelper, string actionName, string controllerName)\n        {\n            RenderAction(htmlHelper, actionName, controllerName, null /* routeValues */);\n        }\n\n        public static void RenderAction(this HtmlHelper htmlHelper, string actionName, string controllerName, object routeValues)\n        {\n            RenderAction(htmlHelper, actionName, controllerName, TypeHelper.ObjectToDictionary(routeValues));\n        }\n\n        public static void RenderAction(this HtmlHelper htmlHelper, string actionName, string controllerName, RouteValueDictionary routeValues)\n        {\n            ActionHelper(htmlHelper, actionName, controllerName, routeValues, htmlHelper.ViewContext.Writer);\n        }\n\n        // Helpers\n\n        internal static void ActionHelper(HtmlHelper htmlHelper, string actionName, string controllerName, RouteValueDictionary routeValues, TextWriter textWriter)\n        {\n            if (htmlHelper == null)\n            {\n                throw new ArgumentNullException(\"htmlHelper\");\n            }\n            if (String.IsNullOrEmpty(actionName))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"actionName\");\n            }\n\n            RouteValueDictionary additionalRouteValues = routeValues;\n            routeValues = MergeDictionaries(routeValues, htmlHelper.ViewContext.RouteData.Values);\n\n            routeValues[\"action\"] = actionName;\n            if (!String.IsNullOrEmpty(controllerName))\n            {\n                routeValues[\"controller\"] = controllerName;\n            }\n\n            bool usingAreas;\n            VirtualPathData vpd = htmlHelper.RouteCollection.GetVirtualPathForArea(htmlHelper.ViewContext.RequestContext, null /* name */, routeValues, out usingAreas);\n            if (vpd == null)\n            {\n                throw new InvalidOperationException(MvcResources.Common_NoRouteMatched);\n            }\n\n            if (usingAreas)\n            {\n                routeValues.Remove(\"area\");\n                if (additionalRouteValues != null)\n                {\n                    additionalRouteValues.Remove(\"area\");\n                }\n            }\n\n            if (additionalRouteValues != null)\n            {\n                routeValues[ChildActionValueProvider.ChildActionValuesKey] = new DictionaryValueProvider<object>(additionalRouteValues, CultureInfo.InvariantCulture);\n            }\n\n            RouteData routeData = CreateRouteData(vpd.Route, routeValues, vpd.DataTokens, htmlHelper.ViewContext);\n            HttpContextBase httpContext = htmlHelper.ViewContext.HttpContext;\n            RequestContext requestContext = new RequestContext(httpContext, routeData);\n            ChildActionMvcHandler handler = new ChildActionMvcHandler(requestContext);\n            httpContext.Server.Execute(HttpHandlerUtil.WrapForServerExecute(handler), textWriter, true /* preserveForm */);\n        }\n\n        private static RouteData CreateRouteData(RouteBase route, RouteValueDictionary routeValues, RouteValueDictionary dataTokens, ViewContext parentViewContext)\n        {\n            RouteData routeData = new RouteData();\n\n            foreach (KeyValuePair<string, object> kvp in routeValues)\n            {\n                routeData.Values.Add(kvp.Key, kvp.Value);\n            }\n\n            foreach (KeyValuePair<string, object> kvp in dataTokens)\n            {\n                routeData.DataTokens.Add(kvp.Key, kvp.Value);\n            }\n\n            routeData.Route = route;\n            routeData.DataTokens[ControllerContext.ParentActionViewContextToken] = parentViewContext;\n\n            // It's possible that the outgoing route is a direct route - in which case it's not possible to reach using\n            // the action name and controller name. We need to check for that case to determine if we need to create a \n            // 'direct route' routedata to reach it.\n            if (route.IsDirectRoute())\n            {\n                // Codeplex-2136 - ControllerContext.IsChildAction returns false inside Controller.Initialize()\n                //\n                // We're constructing a 'temp' route data to wrap the route data for the match we're invoking via\n                // an attribute route. The ControllerContext will look at datatokens to see if it's being invoked\n                // as a child action. \n                //\n                // By sticking the view context on both route data ControllerContext will do the right thing\n                // at all parts of the pipeline.\n                var directRouteData = RouteCollectionRoute.CreateDirectRouteMatch(route, new List<RouteData>() { routeData });\n                directRouteData.DataTokens[ControllerContext.ParentActionViewContextToken] = parentViewContext;\n                return directRouteData;\n            }\n            else\n            {\n                return routeData;\n            }\n        }\n\n        private static RouteValueDictionary MergeDictionaries(params RouteValueDictionary[] dictionaries)\n        {\n            // Merge existing route values with the user provided values\n            var result = new RouteValueDictionary();\n\n            foreach (RouteValueDictionary dictionary in dictionaries.Where(d => d != null))\n            {\n                foreach (KeyValuePair<string, object> kvp in dictionary)\n                {\n                    if (!result.ContainsKey(kvp.Key))\n                    {\n                        result.Add(kvp.Key, kvp.Value);\n                    }\n                }\n            }\n\n            return result;\n        }\n\n        internal class ChildActionMvcHandler : MvcHandler\n        {\n            public ChildActionMvcHandler(RequestContext context)\n                : base(context)\n            {\n            }\n\n            protected internal override void AddVersionHeader(HttpContextBase httpContext)\n            {\n                // No version header for child actions\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Html/DefaultDisplayTemplates.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Data;\nusing System.Globalization;\nusing System.Linq;\nusing System.Text;\nusing System.Web.Mvc.Properties;\nusing System.Web.UI.WebControls;\n\nnamespace System.Web.Mvc.Html\n{\n    internal static class DefaultDisplayTemplates\n    {\n        internal static string BooleanTemplate(HtmlHelper html)\n        {\n            bool? value = null;\n            if (html.ViewContext.ViewData.Model != null)\n            {\n                value = Convert.ToBoolean(html.ViewContext.ViewData.Model, CultureInfo.InvariantCulture);\n            }\n\n            return html.ViewContext.ViewData.ModelMetadata.IsNullableValueType\n                       ? BooleanTemplateDropDownList(value)\n                       : BooleanTemplateCheckbox(value ?? false);\n        }\n\n        private static string BooleanTemplateCheckbox(bool value)\n        {\n            TagBuilder inputTag = new TagBuilder(\"input\");\n            inputTag.AddCssClass(\"check-box\");\n            inputTag.Attributes[\"disabled\"] = \"disabled\";\n            inputTag.Attributes[\"type\"] = \"checkbox\";\n            if (value)\n            {\n                inputTag.Attributes[\"checked\"] = \"checked\";\n            }\n\n            return inputTag.ToString(TagRenderMode.SelfClosing);\n        }\n\n        private static string BooleanTemplateDropDownList(bool? value)\n        {\n            StringBuilder builder = new StringBuilder();\n\n            TagBuilder selectTag = new TagBuilder(\"select\");\n            selectTag.AddCssClass(\"list-box\");\n            selectTag.AddCssClass(\"tri-state\");\n            selectTag.Attributes[\"disabled\"] = \"disabled\";\n            builder.Append(selectTag.ToString(TagRenderMode.StartTag));\n\n            foreach (SelectListItem item in DefaultEditorTemplates.TriStateValues(value))\n            {\n                builder.Append(SelectExtensions.ListItemToOption(item));\n            }\n\n            builder.Append(selectTag.ToString(TagRenderMode.EndTag));\n            return builder.ToString();\n        }\n\n        internal static string CollectionTemplate(HtmlHelper html)\n        {\n            return CollectionTemplate(html, TemplateHelpers.TemplateHelper);\n        }\n\n        internal static string CollectionTemplate(HtmlHelper html, TemplateHelpers.TemplateHelperDelegate templateHelper)\n        {\n            object model = html.ViewContext.ViewData.ModelMetadata.Model;\n            if (model == null)\n            {\n                return String.Empty;\n            }\n\n            IEnumerable collection = model as IEnumerable;\n            if (collection == null)\n            {\n                throw new InvalidOperationException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.Templates_TypeMustImplementIEnumerable,\n                        model.GetType().FullName));\n            }\n\n            Type typeInCollection = typeof(string);\n            Type genericEnumerableType = TypeHelpers.ExtractGenericInterface(collection.GetType(), typeof(IEnumerable<>));\n            if (genericEnumerableType != null)\n            {\n                typeInCollection = genericEnumerableType.GetGenericArguments()[0];\n            }\n            bool typeInCollectionIsNullableValueType = TypeHelpers.IsNullableValueType(typeInCollection);\n\n            string oldPrefix = html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix;\n\n            try\n            {\n                html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = String.Empty;\n\n                string fieldNameBase = oldPrefix;\n                StringBuilder result = new StringBuilder();\n                int index = 0;\n\n                foreach (object item in collection)\n                {\n                    Type itemType = typeInCollection;\n                    if (item != null && !typeInCollectionIsNullableValueType)\n                    {\n                        itemType = item.GetType();\n                    }\n                    ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(() => item, itemType);\n                    string fieldName = String.Format(CultureInfo.InvariantCulture, \"{0}[{1}]\", fieldNameBase, index++);\n                    string output = templateHelper(html, metadata, fieldName, null /* templateName */, DataBoundControlMode.ReadOnly, null /* additionalViewData */);\n                    result.Append(output);\n                }\n\n                return result.ToString();\n            }\n            finally\n            {\n                html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = oldPrefix;\n            }\n        }\n\n        internal static string DecimalTemplate(HtmlHelper html)\n        {\n            if (html.ViewContext.ViewData.TemplateInfo.FormattedModelValue == html.ViewContext.ViewData.ModelMetadata.Model)\n            {\n                html.ViewContext.ViewData.TemplateInfo.FormattedModelValue = String.Format(CultureInfo.CurrentCulture, \"{0:0.00}\", html.ViewContext.ViewData.ModelMetadata.Model);\n            }\n\n            return StringTemplate(html);\n        }\n\n        internal static string EmailAddressTemplate(HtmlHelper html)\n        {\n            return String.Format(CultureInfo.InvariantCulture,\n                                 \"<a href=\\\"mailto:{0}\\\">{1}</a>\",\n                                 html.AttributeEncode(html.ViewContext.ViewData.Model),\n                                 html.Encode(html.ViewContext.ViewData.TemplateInfo.FormattedModelValue));\n        }\n\n        internal static string HiddenInputTemplate(HtmlHelper html)\n        {\n            if (html.ViewContext.ViewData.ModelMetadata.HideSurroundingHtml)\n            {\n                return String.Empty;\n            }\n            return StringTemplate(html);\n        }\n\n        internal static string HtmlTemplate(HtmlHelper html)\n        {\n            return html.ViewContext.ViewData.TemplateInfo.FormattedModelValue.ToString();\n        }\n\n        internal static string ObjectTemplate(HtmlHelper html)\n        {\n            return ObjectTemplate(html, TemplateHelpers.TemplateHelper);\n        }\n\n        internal static string ObjectTemplate(HtmlHelper html, TemplateHelpers.TemplateHelperDelegate templateHelper)\n        {\n            ViewDataDictionary viewData = html.ViewContext.ViewData;\n            TemplateInfo templateInfo = viewData.TemplateInfo;\n            ModelMetadata modelMetadata = viewData.ModelMetadata;\n            StringBuilder builder = new StringBuilder();\n\n            if (modelMetadata.Model == null)\n            {\n                // DDB #225237\n                return modelMetadata.NullDisplayText;\n            }\n\n            if (templateInfo.TemplateDepth > 1)\n            {\n                // DDB #224751\n                string text = modelMetadata.SimpleDisplayText;\n                if (modelMetadata.HtmlEncode)\n                {\n                    text = html.Encode(text);\n                }\n\n                return text;\n            }\n\n            foreach (ModelMetadata propertyMetadata in modelMetadata.Properties.Where(pm => ShouldShow(pm, templateInfo)))\n            {\n                if (!propertyMetadata.HideSurroundingHtml)\n                {\n                    string label = propertyMetadata.GetDisplayName();\n                    if (!String.IsNullOrEmpty(label))\n                    {\n                        builder.AppendFormat(CultureInfo.InvariantCulture, \"<div class=\\\"display-label\\\">{0}</div>\", label);\n                        builder.AppendLine();\n                    }\n\n                    builder.Append(\"<div class=\\\"display-field\\\">\");\n                }\n\n                builder.Append(templateHelper(html, propertyMetadata, propertyMetadata.PropertyName, null /* templateName */, DataBoundControlMode.ReadOnly, null /* additionalViewData */));\n\n                if (!propertyMetadata.HideSurroundingHtml)\n                {\n                    builder.AppendLine(\"</div>\");\n                }\n            }\n\n            return builder.ToString();\n        }\n\n        private static bool ShouldShow(ModelMetadata metadata, TemplateInfo templateInfo)\n        {\n            return\n                metadata.ShowForDisplay\n                && metadata.ModelType != typeof(EntityState)\n                && !metadata.IsComplexType\n                && !templateInfo.Visited(metadata);\n        }\n\n        internal static string StringTemplate(HtmlHelper html)\n        {\n            return html.Encode(html.ViewContext.ViewData.TemplateInfo.FormattedModelValue);\n        }\n\n        internal static string UrlTemplate(HtmlHelper html)\n        {\n            return String.Format(CultureInfo.InvariantCulture,\n                                 \"<a href=\\\"{0}\\\">{1}</a>\",\n                                 html.AttributeEncode(html.ViewContext.ViewData.Model),\n                                 html.Encode(html.ViewContext.ViewData.TemplateInfo.FormattedModelValue));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Html/DefaultEditorTemplates.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Data;\nusing System.Data.Linq;\nusing System.Drawing;\nusing System.Globalization;\nusing System.Linq;\nusing System.Text;\nusing System.Web.Configuration;\nusing System.Web.Mvc.Properties;\nusing System.Web.Routing;\nusing System.Web.UI.WebControls;\n\nnamespace System.Web.Mvc.Html\n{\n    internal static class DefaultEditorTemplates\n    {\n        private const string HtmlAttributeKey = \"htmlAttributes\";\n        private const string UsePasswordValue = \"Switch.System.Web.Mvc.UsePasswordValue\";\n\n        internal static string BooleanTemplate(HtmlHelper html)\n        {\n            bool? value = null;\n            if (html.ViewContext.ViewData.Model != null)\n            {\n                value = Convert.ToBoolean(html.ViewContext.ViewData.Model, CultureInfo.InvariantCulture);\n            }\n\n            return html.ViewContext.ViewData.ModelMetadata.IsNullableValueType\n                       ? BooleanTemplateDropDownList(html, value)\n                       : BooleanTemplateCheckbox(html, value ?? false);\n        }\n\n        private static string BooleanTemplateCheckbox(HtmlHelper html, bool value)\n        {\n            return html.CheckBox(String.Empty, value, CreateHtmlAttributes(html, \"check-box\")).ToHtmlString();\n        }\n\n        private static string BooleanTemplateDropDownList(HtmlHelper html, bool? value)\n        {\n            return html.DropDownList(String.Empty, TriStateValues(value), CreateHtmlAttributes(html, \"list-box tri-state\")).ToHtmlString();\n        }\n\n        internal static string CollectionTemplate(HtmlHelper html)\n        {\n            return CollectionTemplate(html, TemplateHelpers.TemplateHelper);\n        }\n\n        internal static string CollectionTemplate(HtmlHelper html, TemplateHelpers.TemplateHelperDelegate templateHelper)\n        {\n            ViewDataDictionary viewData = html.ViewContext.ViewData;\n            object model = viewData.ModelMetadata.Model;\n            if (model == null)\n            {\n                return String.Empty;\n            }\n\n            IEnumerable collection = model as IEnumerable;\n            if (collection == null)\n            {\n                throw new InvalidOperationException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.Templates_TypeMustImplementIEnumerable,\n                        model.GetType().FullName));\n            }\n\n            Type typeInCollection = typeof(string);\n            Type genericEnumerableType = TypeHelpers.ExtractGenericInterface(collection.GetType(), typeof(IEnumerable<>));\n            if (genericEnumerableType != null)\n            {\n                typeInCollection = genericEnumerableType.GetGenericArguments()[0];\n            }\n            bool typeInCollectionIsNullableValueType = TypeHelpers.IsNullableValueType(typeInCollection);\n\n            string oldPrefix = viewData.TemplateInfo.HtmlFieldPrefix;\n\n            try\n            {\n                viewData.TemplateInfo.HtmlFieldPrefix = String.Empty;\n\n                string fieldNameBase = oldPrefix;\n                StringBuilder result = new StringBuilder();\n                int index = 0;\n\n                foreach (object item in collection)\n                {\n                    Type itemType = typeInCollection;\n                    if (item != null && !typeInCollectionIsNullableValueType)\n                    {\n                        itemType = item.GetType();\n                    }\n                    ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(() => item, itemType);\n                    string fieldName = String.Format(CultureInfo.InvariantCulture, \"{0}[{1}]\", fieldNameBase, index++);\n                    string output = templateHelper(html, metadata, fieldName, null /* templateName */, DataBoundControlMode.Edit, null /* additionalViewData */);\n                    result.Append(output);\n                }\n\n                return result.ToString();\n            }\n            finally\n            {\n                viewData.TemplateInfo.HtmlFieldPrefix = oldPrefix;\n            }\n        }\n\n        internal static string DecimalTemplate(HtmlHelper html)\n        {\n            if (html.ViewContext.ViewData.TemplateInfo.FormattedModelValue == html.ViewContext.ViewData.ModelMetadata.Model)\n            {\n                html.ViewContext.ViewData.TemplateInfo.FormattedModelValue = String.Format(CultureInfo.CurrentCulture, \"{0:0.00}\", html.ViewContext.ViewData.ModelMetadata.Model);\n            }\n\n            return StringTemplate(html);\n        }\n\n        internal static string HiddenInputTemplate(HtmlHelper html)\n        {\n            string result;\n            ViewDataDictionary viewData = html.ViewContext.ViewData;\n            if (viewData.ModelMetadata.HideSurroundingHtml)\n            {\n                result = String.Empty;\n            }\n            else\n            {\n                result = DefaultDisplayTemplates.StringTemplate(html);\n            }\n\n            object model = viewData.Model;\n\n            Binary modelAsBinary = model as Binary;\n            if (modelAsBinary != null)\n            {\n                model = Convert.ToBase64String(modelAsBinary.ToArray());\n            }\n            else\n            {\n                byte[] modelAsByteArray = model as byte[];\n                if (modelAsByteArray != null)\n                {\n                    model = Convert.ToBase64String(modelAsByteArray);\n                }\n            }\n\n            object htmlAttributesObject = viewData[HtmlAttributeKey];\n            IDictionary<string, object> htmlAttributesDict = htmlAttributesObject as IDictionary<string, object>;\n\n            MvcHtmlString hiddenResult;\n\n            if (htmlAttributesDict != null)\n            {\n                hiddenResult = html.Hidden(String.Empty, model, htmlAttributesDict);\n            }\n            else\n            {\n                hiddenResult = html.Hidden(String.Empty, model, htmlAttributesObject);\n            }\n\n            result += hiddenResult.ToHtmlString();\n\n            return result;\n        }\n\n        internal static string MultilineTextTemplate(HtmlHelper html)\n        {\n            return html.TextArea(String.Empty,\n                                 html.ViewContext.ViewData.TemplateInfo.FormattedModelValue.ToString(),\n                                 0 /* rows */, 0 /* columns */,\n                                 CreateHtmlAttributes(html, \"text-box multi-line\")).ToHtmlString();\n        }\n\n        private static IDictionary<string, object> CreateHtmlAttributes(HtmlHelper html, string className, string inputType = null)\n        {\n            object htmlAttributesObject = html.ViewContext.ViewData[HtmlAttributeKey];\n            if (htmlAttributesObject != null)\n            {\n                return MergeHtmlAttributes(htmlAttributesObject, className, inputType);\n            }\n\n            var htmlAttributes = new Dictionary<string, object>()\n            {\n                { \"class\", className }\n            };\n            if (inputType != null)\n            {\n                htmlAttributes.Add(\"type\", inputType);\n            }\n            return htmlAttributes;\n        }\n\n        private static IDictionary<string, object> MergeHtmlAttributes(object htmlAttributesObject, string className, string inputType)\n        {\n            IDictionary<string, object> htmlAttributesDict = htmlAttributesObject as IDictionary<string, object>;\n\n            RouteValueDictionary htmlAttributes = (htmlAttributesDict != null) ? new RouteValueDictionary(htmlAttributesDict)\n                : HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributesObject);\n\n            string htmlClassName;\n            if (htmlAttributes.TryGetValue(\"class\", out htmlClassName))\n            {\n                htmlClassName += \" \" + className;\n                htmlAttributes[\"class\"] = htmlClassName;\n            }\n            else\n            {\n                htmlAttributes.Add(\"class\", className);\n            }\n\n            // The input type from the provided htmlAttributes overrides the inputType parameter.\n            if (inputType != null && !htmlAttributes.ContainsKey(\"type\"))\n            {\n                htmlAttributes.Add(\"type\", inputType);\n            }\n\n            return htmlAttributes;\n        }\n\n        internal static string ObjectTemplate(HtmlHelper html)\n        {\n            return ObjectTemplate(html, TemplateHelpers.TemplateHelper);\n        }\n\n        internal static string ObjectTemplate(HtmlHelper html, TemplateHelpers.TemplateHelperDelegate templateHelper)\n        {\n            ViewDataDictionary viewData = html.ViewContext.ViewData;\n            TemplateInfo templateInfo = viewData.TemplateInfo;\n            ModelMetadata modelMetadata = viewData.ModelMetadata;\n            StringBuilder builder = new StringBuilder();\n\n            if (templateInfo.TemplateDepth > 1)\n            {\n                if (modelMetadata.Model == null)\n                {\n                    return modelMetadata.NullDisplayText;\n                }\n\n                // DDB #224751\n                string text = modelMetadata.SimpleDisplayText;\n                if (modelMetadata.HtmlEncode)\n                {\n                    text = html.Encode(text);\n                }\n\n                return text;\n            }\n\n            foreach (ModelMetadata propertyMetadata in modelMetadata.Properties.Where(pm => ShouldShow(pm, templateInfo)))\n            {\n                if (!propertyMetadata.HideSurroundingHtml)\n                {\n                    string label = LabelExtensions.LabelHelper(html, propertyMetadata, propertyMetadata.PropertyName).ToHtmlString();\n                    if (!String.IsNullOrEmpty(label))\n                    {\n                        builder.AppendFormat(CultureInfo.InvariantCulture, \"<div class=\\\"editor-label\\\">{0}</div>\\r\\n\", label);\n                    }\n\n                    builder.Append(\"<div class=\\\"editor-field\\\">\");\n                }\n\n                builder.Append(templateHelper(html, propertyMetadata, propertyMetadata.PropertyName, null /* templateName */, DataBoundControlMode.Edit, null /* additionalViewData */));\n\n                if (!propertyMetadata.HideSurroundingHtml)\n                {\n                    builder.Append(\" \");\n                    builder.Append(html.ValidationMessage(propertyMetadata.PropertyName));\n                    builder.Append(\"</div>\\r\\n\");\n                }\n            }\n\n            return builder.ToString();\n        }\n\n        internal static string PasswordTemplate(HtmlHelper html)\n        {\n            object value = null;\n            var usePasswordStrings = WebConfigurationManager.AppSettings.GetValues(UsePasswordValue);\n            bool usePasswordValue;\n            if (usePasswordStrings != null &&\n                usePasswordStrings.Length > 0 &&\n                bool.TryParse(usePasswordStrings[0], out usePasswordValue) &&\n                usePasswordValue)\n            {\n                value = html.ViewContext.ViewData.TemplateInfo.FormattedModelValue;\n            }\n\n            return html.Password(\n                name: String.Empty,\n                value: value,\n                htmlAttributes: CreateHtmlAttributes(html, \"text-box single-line password\")).ToHtmlString();\n        }\n\n        private static bool ShouldShow(ModelMetadata metadata, TemplateInfo templateInfo)\n        {\n            return\n                metadata.ShowForEdit\n                && metadata.ModelType != typeof(EntityState)\n                && !metadata.IsComplexType\n                && !templateInfo.Visited(metadata);\n        }\n\n        internal static string StringTemplate(HtmlHelper html)\n        {\n            return HtmlInputTemplateHelper(html);\n        }\n\n        internal static string PhoneNumberInputTemplate(HtmlHelper html)\n        {\n            return HtmlInputTemplateHelper(html, inputType: \"tel\");\n        }\n\n        internal static string UrlInputTemplate(HtmlHelper html)\n        {\n            return HtmlInputTemplateHelper(html, inputType: \"url\");\n        }\n\n        internal static string EmailAddressInputTemplate(HtmlHelper html)\n        {\n            return HtmlInputTemplateHelper(html, inputType: \"email\");\n        }\n\n        internal static string DateTimeInputTemplate(HtmlHelper html)\n        {\n            ApplyRfc3339DateFormattingIfNeeded(html, \"{0:yyyy-MM-ddTHH:mm:ss.fffK}\");\n            return HtmlInputTemplateHelper(html, inputType: \"datetime\");\n        }\n\n        internal static string DateTimeLocalInputTemplate(HtmlHelper html)\n        {\n            ApplyRfc3339DateFormattingIfNeeded(html, \"{0:yyyy-MM-ddTHH:mm:ss.fff}\");\n            return HtmlInputTemplateHelper(html, inputType: \"datetime-local\");\n        }\n\n        internal static string DateInputTemplate(HtmlHelper html)\n        {\n            ApplyRfc3339DateFormattingIfNeeded(html, \"{0:yyyy-MM-dd}\");\n            return HtmlInputTemplateHelper(html, inputType: \"date\");\n        }\n\n        internal static string TimeInputTemplate(HtmlHelper html)\n        {\n            ApplyRfc3339DateFormattingIfNeeded(html, \"{0:HH:mm:ss.fff}\");\n            return HtmlInputTemplateHelper(html, inputType: \"time\");\n        }\n\n        internal static string NumberInputTemplate(HtmlHelper html)\n        {\n            return HtmlInputTemplateHelper(html, inputType: \"number\");\n        }\n\n        internal static string ColorInputTemplate(HtmlHelper html)\n        {\n            string value = null;\n            if (html.ViewContext.ViewData.Model != null)\n            {\n                if (html.ViewContext.ViewData.Model is Color)\n                {\n                    Color color = (Color)html.ViewContext.ViewData.Model;\n                    value = String.Format(CultureInfo.InvariantCulture, \"#{0:X2}{1:X2}{2:X2}\", color.R, color.G, color.B);\n                }\n                else\n                {\n                    value = html.ViewContext.ViewData.Model.ToString();\n                }\n            }\n\n            return HtmlInputTemplateHelper(html, \"color\", value);\n        }\n\n        private static void ApplyRfc3339DateFormattingIfNeeded(HtmlHelper html, string format)\n        {\n            if (html.Html5DateRenderingMode != Html5DateRenderingMode.Rfc3339)\n            {\n                return;\n            }\n\n            ModelMetadata metadata = html.ViewContext.ViewData.ModelMetadata;\n            object value = metadata.Model;\n            if (html.ViewContext.ViewData.TemplateInfo.FormattedModelValue != value && metadata.HasNonDefaultEditFormat)\n            {\n                return;\n            }\n\n            if (value is DateTime || value is DateTimeOffset)\n            {\n                html.ViewContext.ViewData.TemplateInfo.FormattedModelValue = String.Format(CultureInfo.InvariantCulture, format, value);\n            }\n        }\n\n        private static string HtmlInputTemplateHelper(HtmlHelper html, string inputType = null)\n        {\n            return HtmlInputTemplateHelper(html, inputType, html.ViewContext.ViewData.TemplateInfo.FormattedModelValue);\n        }\n\n        private static string HtmlInputTemplateHelper(HtmlHelper html, string inputType, object value)\n        {\n            return html.TextBox(\n                    name: String.Empty,\n                    value: value,\n                    htmlAttributes: CreateHtmlAttributes(html, className: \"text-box single-line\", inputType: inputType))\n                .ToHtmlString();\n        }\n\n        internal static List<SelectListItem> TriStateValues(bool? value)\n        {\n            return new List<SelectListItem>\n            {\n                new SelectListItem { Text = MvcResources.Common_TriState_NotSet, Value = String.Empty, Selected = !value.HasValue },\n                new SelectListItem { Text = MvcResources.Common_TriState_True, Value = \"true\", Selected = value.HasValue && value.Value },\n                new SelectListItem { Text = MvcResources.Common_TriState_False, Value = \"false\", Selected = value.HasValue && !value.Value },\n            };\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Mvc/Html/DisplayExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\nusing System.Web.UI.WebControls;\n\nnamespace System.Web.Mvc.Html\n{\n    public static class DisplayExtensions\n    {\n        public static MvcHtmlString Display(this HtmlHelper html, string expression)\n        {\n            return TemplateHelpers.Template(html, expression, null /* templateName */, null /* htmlFieldName */, DataBoundControlMode.ReadOnly, null /* additionalViewData */);\n        }\n\n        public static MvcHtmlString Display(this HtmlHelper html, string expression, object additionalViewData)\n        {\n            return TemplateHelpers.Template(html, expression, null /* templateName */, null /* htmlFieldName */, DataBoundControlMode.ReadOnly, additionalViewData);\n        }\n\n        public static MvcHtmlString Display(this HtmlHelper html, string expression, string templateName)\n        {\n            return TemplateHelpers.Template(html, expression, templateName, null /* htmlFieldName */, DataBoundControlMode.ReadOnly, null /* additionalViewData */);\n        }\n\n        public static MvcHtmlString Display(this HtmlHelper html, string expression, string templateName, object additionalViewData)\n        {\n            return TemplateHelpers.Template(html, expression, templateName, null /* htmlFieldName */, DataBoundControlMode.ReadOnly, additionalViewData);\n        }\n\n        public static MvcHtmlString Display(this HtmlHelper html, string expression, string templateName, string htmlFieldName)\n        {\n            return TemplateHelpers.Template(html, expression, templateName, htmlFieldName, DataBoundControlMode.ReadOnly, null /* additionalViewData */);\n        }\n\n        public static MvcHtmlString Display(this HtmlHelper html, string expression, string templateName, string htmlFieldName, object additionalViewData)\n        {\n            return TemplateHelpers.Template(html, expression, templateName, htmlFieldName, DataBoundControlMode.ReadOnly, additionalViewData);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString DisplayFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)\n        {\n            return TemplateHelpers.TemplateFor(html, expression, null /* templateName */, null /* htmlFieldName */, DataBoundControlMode.ReadOnly, null /* additionalViewData */);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString DisplayFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object additionalViewData)\n        {\n            return TemplateHelpers.TemplateFor(html, expression, null /* templateName */, null /* htmlFieldName */, DataBoundControlMode.ReadOnly, additionalViewData);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString DisplayFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string templateName)\n        {\n            return TemplateHelpers.TemplateFor(html, expression, templateName, null /* htmlFieldName */, DataBoundControlMode.ReadOnly, null /* additionalViewData */);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString DisplayFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string templateName, object additionalViewData)\n        {\n            return TemplateHelpers.TemplateFor(html, expression, templateName, null /* htmlFieldName */, DataBoundControlMode.ReadOnly, additionalViewData);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString DisplayFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string templateName, string htmlFieldName)\n        {\n            return TemplateHelpers.TemplateFor(html, expression, templateName, htmlFieldName, DataBoundControlMode.ReadOnly, null /* additionalViewData */);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString DisplayFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string templateName, string htmlFieldName, object additionalViewData)\n        {\n            return TemplateHelpers.TemplateFor(html, expression, templateName, htmlFieldName, DataBoundControlMode.ReadOnly, additionalViewData);\n        }\n\n        public static MvcHtmlString DisplayForModel(this HtmlHelper html)\n        {\n            return MvcHtmlString.Create(TemplateHelpers.TemplateHelper(html, html.ViewData.ModelMetadata, String.Empty, null /* templateName */, DataBoundControlMode.ReadOnly, null /* additionalViewData */));\n        }\n\n        public static MvcHtmlString DisplayForModel(this HtmlHelper html, object additionalViewData)\n        {\n            return MvcHtmlString.Create(TemplateHelpers.TemplateHelper(html, html.ViewData.ModelMetadata, String.Empty, null /* templateName */, DataBoundControlMode.ReadOnly, additionalViewData));\n        }\n\n        public static MvcHtmlString DisplayForModel(this HtmlHelper html, string templateName)\n        {\n            return MvcHtmlString.Create(TemplateHelpers.TemplateHelper(html, html.ViewData.ModelMetadata, String.Empty, templateName, DataBoundControlMode.ReadOnly, null /* additionalViewData */));\n        }\n\n        public static MvcHtmlString DisplayForModel(this HtmlHelper html, string templateName, object additionalViewData)\n        {\n            return MvcHtmlString.Create(TemplateHelpers.TemplateHelper(html, html.ViewData.ModelMetadata, String.Empty, templateName, DataBoundControlMode.ReadOnly, additionalViewData));\n        }\n\n        public static MvcHtmlString DisplayForModel(this HtmlHelper html, string templateName, string htmlFieldName)\n        {\n            return MvcHtmlString.Create(TemplateHelpers.TemplateHelper(html, html.ViewData.ModelMetadata, htmlFieldName, templateName, DataBoundControlMode.ReadOnly, null /* additionalViewData */));\n        }\n\n        public static MvcHtmlString DisplayForModel(this HtmlHelper html, string templateName, string htmlFieldName, object additionalViewData)\n        {\n            return MvcHtmlString.Create(TemplateHelpers.TemplateHelper(html, html.ViewData.ModelMetadata, htmlFieldName, templateName, DataBoundControlMode.ReadOnly, additionalViewData));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Html/DisplayNameExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Linq.Expressions;\n\nnamespace System.Web.Mvc.Html\n{\n    public static class DisplayNameExtensions\n    {\n        public static MvcHtmlString DisplayName(this HtmlHelper html, string expression)\n        {\n            return DisplayNameInternal(html, expression, metadataProvider: null);\n        }\n\n        internal static MvcHtmlString DisplayNameInternal(this HtmlHelper html, string expression, ModelMetadataProvider metadataProvider)\n        {\n            return DisplayNameHelper(ModelMetadata.FromStringExpression(expression, html.ViewData, metadataProvider),\n                                     expression);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString DisplayNameFor<TModel, TValue>(this HtmlHelper<IEnumerable<TModel>> html, Expression<Func<TModel, TValue>> expression)\n        {\n            return DisplayNameForInternal(html, expression, metadataProvider: null);\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA1801:ReviewUnusedParameters\", Justification = \"This is an extension method\")]\n        internal static MvcHtmlString DisplayNameForInternal<TModel, TValue>(this HtmlHelper<IEnumerable<TModel>> html, Expression<Func<TModel, TValue>> expression, ModelMetadataProvider metadataProvider)\n        {\n            return DisplayNameHelper(ModelMetadata.FromLambdaExpression(expression, new ViewDataDictionary<TModel>(), metadataProvider),\n                                     ExpressionHelper.GetExpressionText(expression));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString DisplayNameFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)\n        {\n            return DisplayNameForInternal(html, expression, metadataProvider: null);\n        }\n\n        internal static MvcHtmlString DisplayNameForInternal<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, ModelMetadataProvider metadataProvider)\n        {\n            return DisplayNameHelper(ModelMetadata.FromLambdaExpression(expression, html.ViewData, metadataProvider),\n                                     ExpressionHelper.GetExpressionText(expression));\n        }\n\n        public static MvcHtmlString DisplayNameForModel(this HtmlHelper html)\n        {\n            return DisplayNameHelper(html.ViewData.ModelMetadata, String.Empty);\n        }\n\n        internal static MvcHtmlString DisplayNameHelper(ModelMetadata metadata, string htmlFieldName)\n        {\n            // We don't call ModelMetadata.GetDisplayName here because we want to fall back to the field name rather than the ModelType.\n            // This is similar to how the LabelHelpers get the text of a label.\n            string resolvedDisplayName = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();\n\n            return new MvcHtmlString(HttpUtility.HtmlEncode(resolvedDisplayName));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Html/DisplayTextExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\n\nnamespace System.Web.Mvc.Html\n{\n    public static class DisplayTextExtensions\n    {\n        public static MvcHtmlString DisplayText(this HtmlHelper html, string name)\n        {\n            return DisplayTextHelper(html, ModelMetadata.FromStringExpression(name, html.ViewContext.ViewData));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString DisplayTextFor<TModel, TResult>(this HtmlHelper<TModel> html, Expression<Func<TModel, TResult>> expression)\n        {\n            return DisplayTextHelper(html, ModelMetadata.FromLambdaExpression(expression, html.ViewData));\n        }\n\n        private static MvcHtmlString DisplayTextHelper(HtmlHelper html, ModelMetadata metadata)\n        {\n            string text = metadata.SimpleDisplayText;\n            if (metadata.HtmlEncode)\n            {\n                text = html.Encode(text);\n            }\n\n            return MvcHtmlString.Create(text);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Html/EditorExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\nusing System.Web.UI.WebControls;\n\nnamespace System.Web.Mvc.Html\n{\n    public static class EditorExtensions\n    {\n        public static MvcHtmlString Editor(this HtmlHelper html, string expression)\n        {\n            return TemplateHelpers.Template(html, expression, null /* templateName */, null /* htmlFieldName */, DataBoundControlMode.Edit, null /* additionalViewData */);\n        }\n\n        public static MvcHtmlString Editor(this HtmlHelper html, string expression, object additionalViewData)\n        {\n            return TemplateHelpers.Template(html, expression, null /* templateName */, null /* htmlFieldName */, DataBoundControlMode.Edit, additionalViewData);\n        }\n\n        public static MvcHtmlString Editor(this HtmlHelper html, string expression, string templateName)\n        {\n            return TemplateHelpers.Template(html, expression, templateName, null /* htmlFieldName */, DataBoundControlMode.Edit, null /* additionalViewData */);\n        }\n\n        public static MvcHtmlString Editor(this HtmlHelper html, string expression, string templateName, object additionalViewData)\n        {\n            return TemplateHelpers.Template(html, expression, templateName, null /* htmlFieldName */, DataBoundControlMode.Edit, additionalViewData);\n        }\n\n        public static MvcHtmlString Editor(this HtmlHelper html, string expression, string templateName, string htmlFieldName)\n        {\n            return TemplateHelpers.Template(html, expression, templateName, htmlFieldName, DataBoundControlMode.Edit, null /* additionalViewData */);\n        }\n\n        public static MvcHtmlString Editor(this HtmlHelper html, string expression, string templateName, string htmlFieldName, object additionalViewData)\n        {\n            return TemplateHelpers.Template(html, expression, templateName, htmlFieldName, DataBoundControlMode.Edit, additionalViewData);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString EditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)\n        {\n            return TemplateHelpers.TemplateFor(html, expression, null /* templateName */, null /* htmlFieldName */, DataBoundControlMode.Edit, null /* additionalViewData */);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString EditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object additionalViewData)\n        {\n            return TemplateHelpers.TemplateFor(html, expression, null /* templateName */, null /* htmlFieldName */, DataBoundControlMode.Edit, additionalViewData);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString EditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string templateName)\n        {\n            return TemplateHelpers.TemplateFor(html, expression, templateName, null /* htmlFieldName */, DataBoundControlMode.Edit, null /* additionalViewData */);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString EditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string templateName, object additionalViewData)\n        {\n            return TemplateHelpers.TemplateFor(html, expression, templateName, null /* htmlFieldName */, DataBoundControlMode.Edit, additionalViewData);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString EditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string templateName, string htmlFieldName)\n        {\n            return TemplateHelpers.TemplateFor(html, expression, templateName, htmlFieldName, DataBoundControlMode.Edit, null /* additionalViewData */);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString EditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string templateName, string htmlFieldName, object additionalViewData)\n        {\n            return TemplateHelpers.TemplateFor(html, expression, templateName, htmlFieldName, DataBoundControlMode.Edit, additionalViewData);\n        }\n\n        public static MvcHtmlString EditorForModel(this HtmlHelper html)\n        {\n            return MvcHtmlString.Create(TemplateHelpers.TemplateHelper(html, html.ViewData.ModelMetadata, String.Empty, null /* templateName */, DataBoundControlMode.Edit, null /* additionalViewData */));\n        }\n\n        public static MvcHtmlString EditorForModel(this HtmlHelper html, object additionalViewData)\n        {\n            return MvcHtmlString.Create(TemplateHelpers.TemplateHelper(html, html.ViewData.ModelMetadata, String.Empty, null /* templateName */, DataBoundControlMode.Edit, additionalViewData));\n        }\n\n        public static MvcHtmlString EditorForModel(this HtmlHelper html, string templateName)\n        {\n            return MvcHtmlString.Create(TemplateHelpers.TemplateHelper(html, html.ViewData.ModelMetadata, String.Empty, templateName, DataBoundControlMode.Edit, null /* additionalViewData */));\n        }\n\n        public static MvcHtmlString EditorForModel(this HtmlHelper html, string templateName, object additionalViewData)\n        {\n            return MvcHtmlString.Create(TemplateHelpers.TemplateHelper(html, html.ViewData.ModelMetadata, String.Empty, templateName, DataBoundControlMode.Edit, additionalViewData));\n        }\n\n        public static MvcHtmlString EditorForModel(this HtmlHelper html, string templateName, string htmlFieldName)\n        {\n            return MvcHtmlString.Create(TemplateHelpers.TemplateHelper(html, html.ViewData.ModelMetadata, htmlFieldName, templateName, DataBoundControlMode.Edit, null /* additionalViewData */));\n        }\n\n        public static MvcHtmlString EditorForModel(this HtmlHelper html, string templateName, string htmlFieldName, object additionalViewData)\n        {\n            return MvcHtmlString.Create(TemplateHelpers.TemplateHelper(html, html.ViewData.ModelMetadata, htmlFieldName, templateName, DataBoundControlMode.Edit, additionalViewData));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Html/EnumHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Diagnostics.Contracts;\nusing System.Linq.Expressions;\nusing System.Reflection;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc.Html\n{\n    public static class EnumHelper\n    {\n        /// <summary>\n        /// Gets a value indicating whether the given <paramref name=\"type\"/> or an expression of this\n        /// <see cref=\"Type\"/> is suitable for use in <see cref=\"GetSelectList(Type)\"/> and <see\n        /// cref=\"SelectExtensions.EnumDropDownListFor{TModel,TEnum}(HtmlHelper{TModel}, Expression{Func{TModel, TEnum}})\"/>\n        /// calls.\n        /// </summary>\n        /// <param name=\"type\">The <see cref=\"Type\"/> to check.</param>\n        /// <returns>\n        /// <see langword=\"true\"/> if <see cref=\"GetSelectList(Type)\"/> will not throw when passed given\n        /// <see cref=\"Type\"/> and <see\n        /// cref=\"SelectExtensions.EnumDropDownListFor{TModel,TEnum}(HtmlHelper{TModel}, Expression{Func{TModel, TEnum}})\"/>\n        /// will not throw when passed an expression of this <see cref=\"Type\"/>; <see langword=\"false\"/> otherwise.\n        /// </returns>\n        /// <remarks>\n        /// Currently returns <see langref=\"true\"/> if the <paramref name=\"type\"/> parameter is\n        /// non-<see langref=\"null\"/>, is an <see langref=\"enum\"/> type, and does not have a\n        /// <see cref=\"FlagsAttribute\"/> attribute.\n        /// </remarks>\n        public static bool IsValidForEnumHelper(Type type)\n        {\n            bool isValid = false;\n            if (type != null)\n            {\n                // Type.IsEnum is false for Nullable<T> even if T is an enum.  Check underlying type (if any).\n                // Do not support Enum type itself -- IsEnum property is false for that class.\n                Type checkedType = Nullable.GetUnderlyingType(type) ?? type;\n                if (checkedType.IsEnum)\n                {\n                    isValid = !HasFlagsInternal(checkedType);\n                }\n            }\n\n            return isValid;\n        }\n\n        /// <summary>\n        /// Gets a value indicating whether the given <paramref name=\"metadata\"/> or associated expression is suitable\n        /// for use in <see cref=\"GetSelectList(ModelMetadata)\"/> and <see\n        /// cref=\"SelectExtensions.EnumDropDownListFor{TModel,TEnum}(HtmlHelper{TModel}, Expression{Func{TModel, TEnum}})\"/>\n        /// calls.\n        /// </summary>\n        /// <param name=\"metadata\">The <see cref=\"ModelMetadata\"/> to check.</param>\n        /// <returns>\n        /// <see langword=\"true\"/> if <see cref=\"GetSelectList(ModelMetadata)\"/> will return not throw when passed\n        /// given <see cref=\"ModelMetadata\"/> and <see\n        /// cref=\"SelectExtensions.EnumDropDownListFor{TModel,TEnum}(HtmlHelper{TModel}, Expression{Func{TModel, TEnum}})\"/>\n        /// will not throw when passed associated expression; <see langword=\"false\"/> otherwise.\n        /// </returns>\n        /// <remarks>\n        /// Currently returns <see langref=\"true\"/> if the <paramref name=\"metadata\"/> parameter is\n        /// non-<see langref=\"null\"/> and <see cref=\"IsValidForEnumHelper(Type)\"/> returns <see langref=\"true\"/> for\n        /// <c>metadata.ModelType</c>.\n        /// </remarks>\n        public static bool IsValidForEnumHelper(ModelMetadata metadata)\n        {\n            return metadata != null && IsValidForEnumHelper(metadata.ModelType);\n        }\n\n        /// <summary>\n        /// Gets a list of <see cref=\"SelectListItem\"/> objects corresponding to enum constants defined in the given\n        /// <paramref name=\"type\"/>.\n        /// </summary>\n        /// <param name=\"type\">The <see cref=\"Type\"/> to evaluate.</param>\n        /// <returns> An <see cref=\"IList{SelectListItem}\"/> for the given <paramref name=\"type\"/>.</returns>\n        /// <remarks>\n        /// Throws if <see cref=\"IsValidForEnumHelper(Type)\"/> returns <see langref=\"false\"/> for the given\n        /// <paramref name=\"type\"/>.\n        /// </remarks>\n        public static IList<SelectListItem> GetSelectList(Type type)\n        {\n            if (type == null)\n            {\n                throw Error.ArgumentNull(\"type\");\n            }\n\n            if (!IsValidForEnumHelper(type))\n            {\n                throw Error.Argument(\"type\", MvcResources.EnumHelper_InvalidParameterType, type.FullName);\n            }\n\n            IList<SelectListItem> selectList = new List<SelectListItem>();\n\n            // According to HTML5: \"The first child option element of a select element with a required attribute and\n            // without a multiple attribute, and whose size is \"1\", must have either an empty value attribute, or must\n            // have no text content.\"  SelectExtensions.DropDownList[For]() methods often generate a matching\n            // <select/>.  Empty value for Nullable<T>, empty text for round-tripping an unrecognized value, or option\n            // label serves in some cases.  But otherwise, ignoring this does not cause problems in either IE or Chrome.\n            Type checkedType = Nullable.GetUnderlyingType(type) ?? type;\n            if (checkedType != type)\n            {\n                // Underlying type was non-null so handle Nullable<T>; ensure returned list has a spot for null\n                selectList.Add(new SelectListItem { Text = String.Empty, Value = String.Empty, });\n            }\n\n            // Populate the list\n            const BindingFlags BindingFlags =\n                BindingFlags.DeclaredOnly | BindingFlags.GetField | BindingFlags.Public | BindingFlags.Static;\n            foreach (FieldInfo field in checkedType.GetFields(BindingFlags))\n            {\n                // fieldValue will be an numeric type (byte, ...)\n                object fieldValue = field.GetRawConstantValue();\n\n                selectList.Add(new SelectListItem { Text = GetDisplayName(field), Value = fieldValue.ToString(), });\n            }\n\n            return selectList;\n        }\n\n        /// <summary>\n        /// Gets a list of <see cref=\"SelectListItem\"/> objects corresponding to enum constants defined in the given\n        /// <paramref name=\"metadata\"/>.\n        /// </summary>\n        /// <param name=\"metadata\">The <see cref=\"ModelMetadata\"/> to evaluate.</param>\n        /// <returns> An <see cref=\"IList{SelectListItem}\"/> for the given <paramref name=\"metadata\"/>.</returns>\n        /// <remarks>\n        /// Throws if <see cref=\"IsValidForEnumHelper(ModelMetadata)\"/> returns <see langref=\"false\"/> for the given\n        /// <paramref name=\"metadata\"/>.\n        /// </remarks>\n        public static IList<SelectListItem> GetSelectList(ModelMetadata metadata)\n        {\n            if (metadata == null)\n            {\n                throw Error.ArgumentNull(\"metadata\");\n            }\n\n            if (metadata.ModelType == null)\n            {\n                throw Error.Argument(\"metadata\", MvcResources.EnumHelper_InvalidMetadataParameter);\n            }\n\n            if (!IsValidForEnumHelper(metadata))\n            {\n                throw Error.Argument(\"metadata\", MvcResources.EnumHelper_InvalidParameterType,\n                    metadata.ModelType.FullName);\n            }\n\n            return GetSelectList(metadata.ModelType);\n        }\n\n        /// <summary>\n        /// Gets a list of <see cref=\"SelectListItem\"/> objects corresponding to enum constants defined in the given\n        /// <paramref name=\"type\"/>.  Also ensures the <paramref name=\"value\"/> will round-trip even if it does not\n        /// match a defined constant and sets the <c>Selected</c> property to <see langref=\"true\"/> for one element in\n        /// the returned list -- matching the <paramref name=\"value\"/>.\n        /// </summary>\n        /// <param name=\"type\">The <see cref=\"Type\"/> to evaluate.</param>\n        /// <param name=\"value\">Value from <see cref=\"Type\"/> <paramref name=\"type\"/> to select.</param>\n        /// <returns>\n        /// An <see cref=\"IList{SelectListItem}\"/> for the given <paramref name=\"type\"/>, possibly extended to\n        /// include an unrecognized <paramref name=\"value\"/>.\n        /// </returns>\n        /// <remarks>\n        /// Throws if <see cref=\"IsValidForEnumHelper(Type)\"/> returns <see langref=\"false\"/> for the given\n        /// <paramref name=\"type\"/> or if a non-null <paramref name=\"value\"/> has a different <see cref=\"Type\"/> than\n        /// <paramref name=\"type\"/>.\n        /// </remarks>\n        public static IList<SelectListItem> GetSelectList(Type type, Enum value)\n        {\n            IList<SelectListItem> selectList = GetSelectList(type);\n\n            Type valueType = (value == null) ? null : value.GetType();\n            if (valueType != null && valueType != type && valueType != Nullable.GetUnderlyingType(type))\n            {\n                throw Error.Argument(\"value\", MvcResources.EnumHelper_InvalidValueParameter, valueType.FullName,\n                    type.FullName);\n            }\n\n            if (value == null && selectList.Count != 0 && String.IsNullOrEmpty(selectList[0].Value))\n            {\n                // Type is Nullable<T>; use existing entry to round trip null value\n                selectList[0].Selected = true;\n            }\n            else\n            {\n                // If null, use default for this (non-Nullable<T>) enum -- always has 0 integral value\n                string valueString = (value == null) ? \"0\" : value.ToString(\"d\");\n\n                // Select the last matching item, imitating what at least IE and Chrome highlight when multiple\n                // elements in a <select/> element have a selected attribute.\n                bool foundSelected = false;\n                for (int i = selectList.Count - 1; !foundSelected && i >= 0; --i)\n                {\n                    SelectListItem item = selectList[i];\n                    item.Selected = (valueString == item.Value);\n                    foundSelected |= item.Selected;\n                }\n\n                // Round trip the current value\n                if (!foundSelected)\n                {\n                    if (selectList.Count != 0 && String.IsNullOrEmpty(selectList[0].Value))\n                    {\n                        // Type is Nullable<T>; use existing entry for round trip\n                        selectList[0].Selected = true;\n                        selectList[0].Value = valueString;\n                    }\n                    else\n                    {\n                        // Add new entry which does not display value to user\n                        selectList.Insert(0,\n                            new SelectListItem { Selected = true, Text = String.Empty, Value = valueString, });\n                    }\n                }\n            }\n\n            return selectList;\n        }\n\n        /// <summary>\n        /// Gets a list of <see cref=\"SelectListItem\"/> objects corresponding to enum constants defined in the given\n        /// <paramref name=\"metadata\"/>.  Also ensures the <paramref name=\"value\"/> will round-trip even if it does not\n        /// match a defined constant and sets the <c>Selected</c> property to <see langref=\"true\"/> for one element in\n        /// the returned list -- matching the <paramref name=\"value\"/>.\n        /// </summary>\n        /// <param name=\"metadata\">The <see cref=\"ModelMetadata\"/> to evaluate.</param>\n        /// <param name=\"value\">Value from <see cref=\"Type\"/> of <paramref name=\"metadata\"/> to select.</param>\n        /// <returns>\n        /// An <see cref=\"IList{SelectListItem}\"/> for the given <paramref name=\"metadata\"/>, possibly extended to\n        /// include an unrecognized <paramref name=\"value\"/>.\n        /// </returns>\n        /// <remarks>\n        /// Throws if <see cref=\"IsValidForEnumHelper(ModelMetadata)\"/> returns <see langref=\"false\"/> for the given\n        /// <paramref name=\"metadata\"/> or if a non-null <paramref name=\"value\"/> has a different <see cref=\"Type\"/>\n        /// than <c>metadata.ModelType</c>.\n        /// </remarks>\n        public static IList<SelectListItem> GetSelectList(ModelMetadata metadata, Enum value)\n        {\n            if (metadata == null)\n            {\n                throw Error.ArgumentNull(\"metadata\");\n            }\n\n            if (metadata.ModelType == null)\n            {\n                throw Error.Argument(\"metadata\", MvcResources.EnumHelper_InvalidMetadataParameter);\n            }\n\n            if (!IsValidForEnumHelper(metadata))\n            {\n                throw Error.Argument(\"metadata\", MvcResources.EnumHelper_InvalidParameterType,\n                    metadata.ModelType.FullName);\n            }\n\n            return GetSelectList(metadata.ModelType, value);\n        }\n\n        internal static bool HasFlags(Type type)\n        {\n            Contract.Assert(type != null);\n\n            Type checkedType = Nullable.GetUnderlyingType(type) ?? type;\n            return HasFlagsInternal(checkedType);\n        }\n\n        private static bool HasFlagsInternal(Type type)\n        {\n            Contract.Assert(type != null);\n\n            FlagsAttribute attribute = type.GetCustomAttribute<FlagsAttribute>(inherit: false);\n            return attribute != null;\n        }\n\n        // Return non-empty name specified in a [Display] attribute for the given field, if any; field's name otherwise\n        private static string GetDisplayName(FieldInfo field)\n        {\n            DisplayAttribute display = field.GetCustomAttribute<DisplayAttribute>(inherit: false);\n            if (display != null)\n            {\n                string name = display.GetName();\n                if (!String.IsNullOrEmpty(name))\n                {\n                    return name;\n                }\n            }\n\n            return field.Name;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Html/FormExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Routing;\nusing System.Web.WebPages;\n\nnamespace System.Web.Mvc.Html\n{\n    public static class FormExtensions\n    {\n        public static MvcForm BeginForm(this HtmlHelper htmlHelper)\n        {\n            // generates <form action=\"{current url}\" method=\"post\">...</form>\n            string formAction = htmlHelper.ViewContext.HttpContext.Request.RawUrl;\n            return FormHelper(htmlHelper, formAction, FormMethod.Post, new RouteValueDictionary());\n        }\n\n        public static MvcForm BeginForm(this HtmlHelper htmlHelper, object routeValues)\n        {\n            return BeginForm(htmlHelper, null, null, TypeHelper.ObjectToDictionary(routeValues), FormMethod.Post, new RouteValueDictionary());\n        }\n\n        public static MvcForm BeginForm(this HtmlHelper htmlHelper, RouteValueDictionary routeValues)\n        {\n            return BeginForm(htmlHelper, null, null, routeValues, FormMethod.Post, new RouteValueDictionary());\n        }\n\n        public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName)\n        {\n            return BeginForm(htmlHelper, actionName, controllerName, new RouteValueDictionary(), FormMethod.Post, new RouteValueDictionary());\n        }\n\n        public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, object routeValues)\n        {\n            return BeginForm(htmlHelper, actionName, controllerName, TypeHelper.ObjectToDictionary(routeValues), FormMethod.Post, new RouteValueDictionary());\n        }\n\n        public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, RouteValueDictionary routeValues)\n        {\n            return BeginForm(htmlHelper, actionName, controllerName, routeValues, FormMethod.Post, new RouteValueDictionary());\n        }\n\n        public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, FormMethod method)\n        {\n            return BeginForm(htmlHelper, actionName, controllerName, new RouteValueDictionary(), method, new RouteValueDictionary());\n        }\n\n        public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, object routeValues, FormMethod method)\n        {\n            return BeginForm(htmlHelper, actionName, controllerName, TypeHelper.ObjectToDictionary(routeValues), method, new RouteValueDictionary());\n        }\n\n        public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, RouteValueDictionary routeValues, FormMethod method)\n        {\n            return BeginForm(htmlHelper, actionName, controllerName, routeValues, method, new RouteValueDictionary());\n        }\n\n        public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, FormMethod method, object htmlAttributes)\n        {\n            return BeginForm(htmlHelper, actionName, controllerName, new RouteValueDictionary(), method, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, FormMethod method, IDictionary<string, object> htmlAttributes)\n        {\n            return BeginForm(htmlHelper, actionName, controllerName, new RouteValueDictionary(), method, htmlAttributes);\n        }\n\n        public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, object routeValues, FormMethod method, object htmlAttributes)\n        {\n            return BeginForm(htmlHelper, actionName, controllerName, TypeHelper.ObjectToDictionary(routeValues), method, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, RouteValueDictionary routeValues, FormMethod method, IDictionary<string, object> htmlAttributes)\n        {\n            string formAction = UrlHelper.GenerateUrl(null /* routeName */, actionName, controllerName, routeValues, htmlHelper.RouteCollection, htmlHelper.ViewContext.RequestContext, true /* includeImplicitMvcValues */);\n            return FormHelper(htmlHelper, formAction, method, htmlAttributes);\n        }\n\n        public static MvcForm BeginRouteForm(this HtmlHelper htmlHelper, object routeValues)\n        {\n            return BeginRouteForm(htmlHelper, null /* routeName */, TypeHelper.ObjectToDictionary(routeValues), FormMethod.Post, new RouteValueDictionary());\n        }\n\n        public static MvcForm BeginRouteForm(this HtmlHelper htmlHelper, RouteValueDictionary routeValues)\n        {\n            return BeginRouteForm(htmlHelper, null /* routeName */, routeValues, FormMethod.Post, new RouteValueDictionary());\n        }\n\n        public static MvcForm BeginRouteForm(this HtmlHelper htmlHelper, string routeName)\n        {\n            return BeginRouteForm(htmlHelper, routeName, new RouteValueDictionary(), FormMethod.Post, new RouteValueDictionary());\n        }\n\n        public static MvcForm BeginRouteForm(this HtmlHelper htmlHelper, string routeName, object routeValues)\n        {\n            return BeginRouteForm(htmlHelper, routeName, TypeHelper.ObjectToDictionary(routeValues), FormMethod.Post, new RouteValueDictionary());\n        }\n\n        public static MvcForm BeginRouteForm(this HtmlHelper htmlHelper, string routeName, RouteValueDictionary routeValues)\n        {\n            return BeginRouteForm(htmlHelper, routeName, routeValues, FormMethod.Post, new RouteValueDictionary());\n        }\n\n        public static MvcForm BeginRouteForm(this HtmlHelper htmlHelper, string routeName, FormMethod method)\n        {\n            return BeginRouteForm(htmlHelper, routeName, new RouteValueDictionary(), method, new RouteValueDictionary());\n        }\n\n        public static MvcForm BeginRouteForm(this HtmlHelper htmlHelper, string routeName, object routeValues, FormMethod method)\n        {\n            return BeginRouteForm(htmlHelper, routeName, TypeHelper.ObjectToDictionary(routeValues), method, new RouteValueDictionary());\n        }\n\n        public static MvcForm BeginRouteForm(this HtmlHelper htmlHelper, string routeName, RouteValueDictionary routeValues, FormMethod method)\n        {\n            return BeginRouteForm(htmlHelper, routeName, routeValues, method, new RouteValueDictionary());\n        }\n\n        public static MvcForm BeginRouteForm(this HtmlHelper htmlHelper, string routeName, FormMethod method, object htmlAttributes)\n        {\n            return BeginRouteForm(htmlHelper, routeName, new RouteValueDictionary(), method, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcForm BeginRouteForm(this HtmlHelper htmlHelper, string routeName, FormMethod method, IDictionary<string, object> htmlAttributes)\n        {\n            return BeginRouteForm(htmlHelper, routeName, new RouteValueDictionary(), method, htmlAttributes);\n        }\n\n        public static MvcForm BeginRouteForm(this HtmlHelper htmlHelper, string routeName, object routeValues, FormMethod method, object htmlAttributes)\n        {\n            return BeginRouteForm(htmlHelper, routeName, TypeHelper.ObjectToDictionary(routeValues), method, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcForm BeginRouteForm(this HtmlHelper htmlHelper, string routeName, RouteValueDictionary routeValues, FormMethod method, IDictionary<string, object> htmlAttributes)\n        {\n            string formAction = UrlHelper.GenerateUrl(routeName, null, null, routeValues, htmlHelper.RouteCollection, htmlHelper.ViewContext.RequestContext, false /* includeImplicitMvcValues */);\n            return FormHelper(htmlHelper, formAction, method, htmlAttributes);\n        }\n\n        public static void EndForm(this HtmlHelper htmlHelper)\n        {\n            EndForm(htmlHelper.ViewContext);\n        }\n\n        internal static void EndForm(ViewContext viewContext)\n        {\n            viewContext.Writer.Write(\"</form>\");\n            viewContext.OutputClientValidation();\n            viewContext.FormContext = null;\n        }\n\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"Because disposing the object would write to the response stream, you don't want to prematurely dispose of this object.\")]\n        private static MvcForm FormHelper(this HtmlHelper htmlHelper, string formAction, FormMethod method, IDictionary<string, object> htmlAttributes)\n        {\n            TagBuilder tagBuilder = new TagBuilder(\"form\");\n            tagBuilder.MergeAttributes(htmlAttributes);\n            // action is implicitly generated, so htmlAttributes take precedence.\n            tagBuilder.MergeAttribute(\"action\", formAction);\n            // method is an explicit parameter, so it takes precedence over the htmlAttributes.\n            tagBuilder.MergeAttribute(\"method\", HtmlHelper.GetFormMethodString(method), true);\n\n            bool traditionalJavascriptEnabled = htmlHelper.ViewContext.ClientValidationEnabled\n                                                && !htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled;\n\n            if (traditionalJavascriptEnabled)\n            {\n                // forms must have an ID for client validation\n                tagBuilder.GenerateId(htmlHelper.ViewContext.FormIdGenerator());\n            }\n\n            htmlHelper.ViewContext.Writer.Write(tagBuilder.ToString(TagRenderMode.StartTag));\n            MvcForm theForm = new MvcForm(htmlHelper.ViewContext);\n\n            if (traditionalJavascriptEnabled)\n            {\n                htmlHelper.ViewContext.FormContext.FormId = tagBuilder.Attributes[\"id\"];\n            }\n\n            return theForm;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Html/InputExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Data.Linq;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq.Expressions;\nusing System.Text;\nusing System.Web.Mvc.Properties;\nusing System.Web.Routing;\n\nnamespace System.Web.Mvc.Html\n{\n    public static class InputExtensions\n    {\n        // CheckBox\n\n        public static MvcHtmlString CheckBox(this HtmlHelper htmlHelper, string name)\n        {\n            return CheckBox(htmlHelper, name, htmlAttributes: (object)null);\n        }\n\n        public static MvcHtmlString CheckBox(this HtmlHelper htmlHelper, string name, bool isChecked)\n        {\n            return CheckBox(htmlHelper, name, isChecked, htmlAttributes: (object)null);\n        }\n\n        public static MvcHtmlString CheckBox(this HtmlHelper htmlHelper, string name, bool isChecked, object htmlAttributes)\n        {\n            return CheckBox(htmlHelper, name, isChecked, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcHtmlString CheckBox(this HtmlHelper htmlHelper, string name, object htmlAttributes)\n        {\n            return CheckBox(htmlHelper, name, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcHtmlString CheckBox(this HtmlHelper htmlHelper, string name, IDictionary<string, object> htmlAttributes)\n        {\n            return CheckBoxHelper(htmlHelper, metadata: null, name: name, isChecked: null, htmlAttributes: htmlAttributes);\n        }\n\n        public static MvcHtmlString CheckBox(this HtmlHelper htmlHelper, string name, bool isChecked, IDictionary<string, object> htmlAttributes)\n        {\n            return CheckBoxHelper(htmlHelper, metadata: null, name: name, isChecked: isChecked, htmlAttributes: htmlAttributes);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString CheckBoxFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool>> expression)\n        {\n            return CheckBoxFor(htmlHelper, expression, htmlAttributes: null);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString CheckBoxFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool>> expression, object htmlAttributes)\n        {\n            return CheckBoxFor(htmlHelper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString CheckBoxFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool>> expression, IDictionary<string, object> htmlAttributes)\n        {\n            if (expression == null)\n            {\n                throw new ArgumentNullException(\"expression\");\n            }\n\n            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);\n            bool? isChecked = null;\n            if (metadata.Model != null)\n            {\n                bool modelChecked;\n                if (Boolean.TryParse(metadata.Model.ToString(), out modelChecked))\n                {\n                    isChecked = modelChecked;\n                }\n            }\n\n            return CheckBoxHelper(htmlHelper, metadata, ExpressionHelper.GetExpressionText(expression), isChecked, htmlAttributes);\n        }\n\n        private static MvcHtmlString CheckBoxHelper(HtmlHelper htmlHelper, ModelMetadata metadata, string name, bool? isChecked, IDictionary<string, object> htmlAttributes)\n        {\n            RouteValueDictionary attributes = ToRouteValueDictionary(htmlAttributes);\n\n            bool explicitValue = isChecked.HasValue;\n            if (explicitValue)\n            {\n                attributes.Remove(\"checked\"); // Explicit value must override dictionary\n            }\n\n            return InputHelper(htmlHelper,\n                               InputType.CheckBox,\n                               metadata,\n                               name,\n                               value: \"true\",\n                               useViewData: !explicitValue,\n                               isChecked: isChecked ?? false,\n                               setId: true,\n                               isExplicitValue: false,\n                               format: null,\n                               htmlAttributes: attributes);\n        }\n\n        // Hidden\n\n        public static MvcHtmlString Hidden(this HtmlHelper htmlHelper, string name)\n        {\n            return Hidden(htmlHelper, name, value: null, htmlAttributes: null);\n        }\n\n        public static MvcHtmlString Hidden(this HtmlHelper htmlHelper, string name, object value)\n        {\n            return Hidden(htmlHelper, name, value, htmlAttributes: null);\n        }\n\n        public static MvcHtmlString Hidden(this HtmlHelper htmlHelper, string name, object value, object htmlAttributes)\n        {\n            return Hidden(htmlHelper, name, value, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcHtmlString Hidden(this HtmlHelper htmlHelper, string name, object value, IDictionary<string, object> htmlAttributes)\n        {\n            return HiddenHelper(htmlHelper,\n                                metadata: null,\n                                value: value,\n                                useViewData: value == null,\n                                expression: name,\n                                htmlAttributes: htmlAttributes);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString HiddenFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)\n        {\n            return HiddenFor(htmlHelper, expression, (IDictionary<string, object>)null);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString HiddenFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)\n        {\n            return HiddenFor(htmlHelper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString HiddenFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)\n        {\n            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);\n            return HiddenHelper(htmlHelper,\n                                metadata,\n                                metadata.Model,\n                                false,\n                                ExpressionHelper.GetExpressionText(expression),\n                                htmlAttributes);\n        }\n\n        private static MvcHtmlString HiddenHelper(HtmlHelper htmlHelper, ModelMetadata metadata, object value, bool useViewData, string expression, IDictionary<string, object> htmlAttributes)\n        {\n            Binary binaryValue = value as Binary;\n            if (binaryValue != null)\n            {\n                value = binaryValue.ToArray();\n            }\n\n            byte[] byteArrayValue = value as byte[];\n            if (byteArrayValue != null)\n            {\n                value = Convert.ToBase64String(byteArrayValue);\n            }\n\n            return InputHelper(htmlHelper,\n                               InputType.Hidden,\n                               metadata,\n                               expression,\n                               value,\n                               useViewData,\n                               isChecked: false,\n                               setId: true,\n                               isExplicitValue: true,\n                               format: null,\n                               htmlAttributes: htmlAttributes);\n        }\n\n        // Password\n\n        public static MvcHtmlString Password(this HtmlHelper htmlHelper, string name)\n        {\n            return Password(htmlHelper, name, value: null);\n        }\n\n        public static MvcHtmlString Password(this HtmlHelper htmlHelper, string name, object value)\n        {\n            return Password(htmlHelper, name, value, htmlAttributes: null);\n        }\n\n        public static MvcHtmlString Password(this HtmlHelper htmlHelper, string name, object value, object htmlAttributes)\n        {\n            return Password(htmlHelper, name, value, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcHtmlString Password(this HtmlHelper htmlHelper, string name, object value, IDictionary<string, object> htmlAttributes)\n        {\n            return PasswordHelper(htmlHelper, metadata: null, name: name, value: value, htmlAttributes: htmlAttributes);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString PasswordFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)\n        {\n            return PasswordFor(htmlHelper, expression, htmlAttributes: null);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString PasswordFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)\n        {\n            return PasswordFor(htmlHelper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1011:ConsiderPassingBaseTypesAsParameters\", Justification = \"Users cannot use anonymous methods with the LambdaExpression type\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString PasswordFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)\n        {\n            if (expression == null)\n            {\n                throw new ArgumentNullException(\"expression\");\n            }\n\n            return PasswordHelper(htmlHelper,\n                                  ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData),\n                                  ExpressionHelper.GetExpressionText(expression),\n                                  value: null,\n                                  htmlAttributes: htmlAttributes);\n        }\n\n        private static MvcHtmlString PasswordHelper(HtmlHelper htmlHelper, ModelMetadata metadata, string name, object value, IDictionary<string, object> htmlAttributes)\n        {\n            return InputHelper(htmlHelper,\n                               InputType.Password,\n                               metadata,\n                               name,\n                               value,\n                               useViewData: false,\n                               isChecked: false,\n                               setId: true,\n                               isExplicitValue: true,\n                               format: null,\n                               htmlAttributes: htmlAttributes);\n        }\n\n        // RadioButton\n\n        public static MvcHtmlString RadioButton(this HtmlHelper htmlHelper, string name, object value)\n        {\n            return RadioButton(htmlHelper, name, value, htmlAttributes: (object)null);\n        }\n\n        public static MvcHtmlString RadioButton(this HtmlHelper htmlHelper, string name, object value, object htmlAttributes)\n        {\n            return RadioButton(htmlHelper, name, value, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcHtmlString RadioButton(this HtmlHelper htmlHelper, string name, object value, IDictionary<string, object> htmlAttributes)\n        {\n            // Determine whether or not to render the checked attribute based on the contents of ViewData.\n            string valueString = Convert.ToString(value, CultureInfo.CurrentCulture);\n            bool isChecked = (!String.IsNullOrEmpty(name)) && (String.Equals(htmlHelper.EvalString(name), valueString, StringComparison.OrdinalIgnoreCase));\n            // checked attributes is implicit, so we need to ensure that the dictionary takes precedence.\n            RouteValueDictionary attributes = ToRouteValueDictionary(htmlAttributes);\n            if (attributes.ContainsKey(\"checked\"))\n            {\n                return InputHelper(htmlHelper,\n                                   InputType.Radio,\n                                   metadata: null,\n                                   name: name,\n                                   value: value,\n                                   useViewData: false,\n                                   isChecked: false,\n                                   setId: true,\n                                   isExplicitValue: true,\n                                   format: null,\n                                   htmlAttributes: attributes);\n            }\n\n            return RadioButton(htmlHelper, name, value, isChecked, htmlAttributes);\n        }\n\n        public static MvcHtmlString RadioButton(this HtmlHelper htmlHelper, string name, object value, bool isChecked)\n        {\n            return RadioButton(htmlHelper, name, value, isChecked, htmlAttributes: (object)null);\n        }\n\n        public static MvcHtmlString RadioButton(this HtmlHelper htmlHelper, string name, object value, bool isChecked, object htmlAttributes)\n        {\n            return RadioButton(htmlHelper, name, value, isChecked, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcHtmlString RadioButton(this HtmlHelper htmlHelper, string name, object value, bool isChecked, IDictionary<string, object> htmlAttributes)\n        {\n            if (value == null)\n            {\n                throw new ArgumentNullException(\"value\");\n            }\n            // checked attribute is an explicit parameter so it takes precedence.\n            RouteValueDictionary attributes = ToRouteValueDictionary(htmlAttributes);\n            attributes.Remove(\"checked\");\n            return InputHelper(htmlHelper,\n                               InputType.Radio,\n                               metadata: null,\n                               name: name,\n                               value: value,\n                               useViewData: false,\n                               isChecked: isChecked,\n                               setId: true,\n                               isExplicitValue: true,\n                               format: null,\n                               htmlAttributes: attributes);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString RadioButtonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value)\n        {\n            return RadioButtonFor(htmlHelper, expression, value, htmlAttributes: null);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString RadioButtonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, object htmlAttributes)\n        {\n            return RadioButtonFor(htmlHelper, expression, value, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString RadioButtonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, IDictionary<string, object> htmlAttributes)\n        {\n            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);\n            return RadioButtonHelper(htmlHelper,\n                                     metadata,\n                                     metadata.Model,\n                                     ExpressionHelper.GetExpressionText(expression),\n                                     value,\n                                     null /* isChecked */,\n                                     htmlAttributes);\n        }\n\n        private static MvcHtmlString RadioButtonHelper(HtmlHelper htmlHelper, ModelMetadata metadata, object model, string name, object value, bool? isChecked, IDictionary<string, object> htmlAttributes)\n        {\n            if (value == null)\n            {\n                throw new ArgumentNullException(\"value\");\n            }\n\n            RouteValueDictionary attributes = ToRouteValueDictionary(htmlAttributes);\n\n            bool explicitValue = isChecked.HasValue;\n            if (explicitValue)\n            {\n                attributes.Remove(\"checked\"); // Explicit value must override dictionary\n            }\n            else\n            {\n                string valueString = Convert.ToString(value, CultureInfo.CurrentCulture);\n                isChecked = model != null &&\n                            !String.IsNullOrEmpty(htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name)) &&\n                            String.Equals(model.ToString(), valueString, StringComparison.OrdinalIgnoreCase);\n            }\n\n            return InputHelper(htmlHelper,\n                               InputType.Radio,\n                               metadata,\n                               name,\n                               value,\n                               useViewData: false,\n                               isChecked: isChecked ?? false,\n                               setId: true,\n                               isExplicitValue: true,\n                               format: null,\n                               htmlAttributes: attributes);\n        }\n\n        // TextBox\n\n        public static MvcHtmlString TextBox(this HtmlHelper htmlHelper, string name)\n        {\n            return TextBox(htmlHelper, name, value: null);\n        }\n\n        public static MvcHtmlString TextBox(this HtmlHelper htmlHelper, string name, object value)\n        {\n            return TextBox(htmlHelper, name, value, format: null);\n        }\n\n        public static MvcHtmlString TextBox(this HtmlHelper htmlHelper, string name, object value, string format)\n        {\n            return TextBox(htmlHelper, name, value, format, htmlAttributes: (object)null);\n        }\n\n        public static MvcHtmlString TextBox(this HtmlHelper htmlHelper, string name, object value, object htmlAttributes)\n        {\n            return TextBox(htmlHelper, name, value, format: null, htmlAttributes: htmlAttributes);\n        }\n\n        public static MvcHtmlString TextBox(this HtmlHelper htmlHelper, string name, object value, string format, object htmlAttributes)\n        {\n            return TextBox(htmlHelper, name, value, format, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcHtmlString TextBox(this HtmlHelper htmlHelper, string name, object value, IDictionary<string, object> htmlAttributes)\n        {\n            return TextBox(htmlHelper, name, value, format: null, htmlAttributes: htmlAttributes);\n        }\n\n        public static MvcHtmlString TextBox(this HtmlHelper htmlHelper, string name, object value, string format, IDictionary<string, object> htmlAttributes)\n        {\n            return InputHelper(htmlHelper,\n                               InputType.Text,\n                               metadata: null,\n                               name: name,\n                               value: value,\n                               useViewData: (value == null),\n                               isChecked: false,\n                               setId: true,\n                               isExplicitValue: true,\n                               format: format,\n                               htmlAttributes: htmlAttributes);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)\n        {\n            return htmlHelper.TextBoxFor(expression, format: null);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string format)\n        {\n            return htmlHelper.TextBoxFor(expression, format, (IDictionary<string, object>)null);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)\n        {\n            return htmlHelper.TextBoxFor(expression, format: null, htmlAttributes: htmlAttributes);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string format, object htmlAttributes)\n        {\n            return htmlHelper.TextBoxFor(expression, format: format, htmlAttributes: HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)\n        {\n            return htmlHelper.TextBoxFor(expression, format: null, htmlAttributes: htmlAttributes);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string format, IDictionary<string, object> htmlAttributes)\n        {\n            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);\n            return TextBoxHelper(htmlHelper,\n                                 metadata,\n                                 metadata.Model,\n                                 ExpressionHelper.GetExpressionText(expression),\n                                 format,\n                                 htmlAttributes);\n        }\n\n        private static MvcHtmlString TextBoxHelper(this HtmlHelper htmlHelper, ModelMetadata metadata, object model, string expression, string format, IDictionary<string, object> htmlAttributes)\n        {\n            return InputHelper(htmlHelper,\n                               InputType.Text,\n                               metadata,\n                               expression,\n                               model,\n                               useViewData: false,\n                               isChecked: false,\n                               setId: true,\n                               isExplicitValue: true,\n                               format: format,\n                               htmlAttributes: htmlAttributes);\n        }\n\n        // Helper methods\n\n        private static MvcHtmlString InputHelper(HtmlHelper htmlHelper, InputType inputType, ModelMetadata metadata, string name, object value, bool useViewData, bool isChecked, bool setId, bool isExplicitValue, string format, IDictionary<string, object> htmlAttributes)\n        {\n            string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);\n            if (String.IsNullOrEmpty(fullName))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"name\");\n            }\n\n            TagBuilder tagBuilder = new TagBuilder(\"input\");\n            tagBuilder.MergeAttributes(htmlAttributes);\n            tagBuilder.MergeAttribute(\"type\", HtmlHelper.GetInputTypeString(inputType));\n            tagBuilder.MergeAttribute(\"name\", fullName, true);\n\n            string valueParameter = htmlHelper.FormatValue(value, format);\n            bool usedModelState = false;\n\n            switch (inputType)\n            {\n                case InputType.CheckBox:\n                    bool? modelStateWasChecked = htmlHelper.GetModelStateValue(fullName, typeof(bool)) as bool?;\n                    if (modelStateWasChecked.HasValue)\n                    {\n                        isChecked = modelStateWasChecked.Value;\n                        usedModelState = true;\n                    }\n                    goto case InputType.Radio;\n                case InputType.Radio:\n                    if (!usedModelState)\n                    {\n                        string modelStateValue = htmlHelper.GetModelStateValue(fullName, typeof(string)) as string;\n                        if (modelStateValue != null)\n                        {\n                            isChecked = String.Equals(modelStateValue, valueParameter, StringComparison.Ordinal);\n                            usedModelState = true;\n                        }\n                    }\n                    if (!usedModelState && useViewData)\n                    {\n                        isChecked = htmlHelper.EvalBoolean(fullName);\n                    }\n                    if (isChecked)\n                    {\n                        tagBuilder.MergeAttribute(\"checked\", \"checked\");\n                    }\n                    tagBuilder.MergeAttribute(\"value\", valueParameter, isExplicitValue);\n                    break;\n                case InputType.Password:\n                    if (value != null)\n                    {\n                        tagBuilder.MergeAttribute(\"value\", valueParameter, isExplicitValue);\n                    }\n                    break;\n                default:\n                    string attemptedValue = (string)htmlHelper.GetModelStateValue(fullName, typeof(string));\n                    tagBuilder.MergeAttribute(\"value\", attemptedValue ?? ((useViewData) ? htmlHelper.EvalString(fullName, format) : valueParameter), isExplicitValue);\n                    break;\n            }\n\n            if (setId)\n            {\n                tagBuilder.GenerateId(fullName);\n            }\n\n            // If there are any errors for a named field, we add the css attribute.\n            ModelState modelState;\n            if (htmlHelper.ViewData.ModelState.TryGetValue(fullName, out modelState))\n            {\n                if (modelState.Errors.Count > 0)\n                {\n                    tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);\n                }\n            }\n\n            tagBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(name, metadata));\n\n            if (inputType == InputType.CheckBox)\n            {\n                // Render an additional <input type=\"hidden\".../> for checkboxes. This\n                // addresses scenarios where unchecked checkboxes are not sent in the request.\n                // Sending a hidden input makes it possible to know that the checkbox was present\n                // on the page when the request was submitted.\n                StringBuilder inputItemBuilder = new StringBuilder();\n                inputItemBuilder.Append(tagBuilder.ToString(TagRenderMode.SelfClosing));\n\n                TagBuilder hiddenInput = new TagBuilder(\"input\");\n                hiddenInput.MergeAttribute(\"type\", HtmlHelper.GetInputTypeString(InputType.Hidden));\n                hiddenInput.MergeAttribute(\"name\", fullName);\n                hiddenInput.MergeAttribute(\"value\", \"false\");\n                inputItemBuilder.Append(hiddenInput.ToString(TagRenderMode.SelfClosing));\n                return MvcHtmlString.Create(inputItemBuilder.ToString());\n            }\n\n            return tagBuilder.ToMvcHtmlString(TagRenderMode.SelfClosing);\n        }\n\n        private static RouteValueDictionary ToRouteValueDictionary(IDictionary<string, object> dictionary)\n        {\n            return dictionary == null ? new RouteValueDictionary() : new RouteValueDictionary(dictionary);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Html/LabelExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Linq.Expressions;\n\nnamespace System.Web.Mvc.Html\n{\n    public static class LabelExtensions\n    {\n        public static MvcHtmlString Label(this HtmlHelper html, string expression)\n        {\n            return Label(html,\n                         expression,\n                         labelText: null);\n        }\n\n        public static MvcHtmlString Label(this HtmlHelper html, string expression, string labelText)\n        {\n            return Label(html, expression, labelText, htmlAttributes: null, metadataProvider: null);\n        }\n\n        public static MvcHtmlString Label(this HtmlHelper html, string expression, object htmlAttributes)\n        {\n            return Label(html, expression, labelText: null, htmlAttributes: htmlAttributes, metadataProvider: null);\n        }\n\n        public static MvcHtmlString Label(this HtmlHelper html, string expression, IDictionary<string, object> htmlAttributes)\n        {\n            return Label(html, expression, labelText: null, htmlAttributes: htmlAttributes, metadataProvider: null);\n        }\n\n        public static MvcHtmlString Label(this HtmlHelper html, string expression, string labelText, object htmlAttributes)\n        {\n            return Label(html, expression, labelText, htmlAttributes, metadataProvider: null);\n        }\n\n        public static MvcHtmlString Label(this HtmlHelper html, string expression, string labelText, IDictionary<string, object> htmlAttributes)\n        {\n            return Label(html, expression, labelText, htmlAttributes, metadataProvider: null);\n        }\n\n        internal static MvcHtmlString Label(this HtmlHelper html, string expression, string labelText, object htmlAttributes, ModelMetadataProvider metadataProvider)\n        {\n            return Label(html,\n                         expression,\n                         labelText,\n                         HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes),\n                         metadataProvider);\n        }\n\n        internal static MvcHtmlString Label(this HtmlHelper html, string expression, string labelText, IDictionary<string, object> htmlAttributes, ModelMetadataProvider metadataProvider)\n        {\n            return LabelHelper(html,\n                               ModelMetadata.FromStringExpression(expression, html.ViewData, metadataProvider),\n                               expression,\n                               labelText,\n                               htmlAttributes);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)\n        {\n            return LabelFor<TModel, TValue>(html, expression, labelText: null);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string labelText)\n        {\n            return LabelFor(html, expression, labelText, htmlAttributes: null, metadataProvider: null);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes)\n        {\n            return LabelFor(html, expression, labelText: null, htmlAttributes: htmlAttributes, metadataProvider: null);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, IDictionary<string, object> htmlAttributes)\n        {\n            return LabelFor(html, expression, labelText: null, htmlAttributes: htmlAttributes, metadataProvider: null);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string labelText, object htmlAttributes)\n        {\n            return LabelFor(html, expression, labelText, htmlAttributes, metadataProvider: null);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string labelText, IDictionary<string, object> htmlAttributes)\n        {\n            return LabelFor(html, expression, labelText, htmlAttributes, metadataProvider: null);\n        }\n\n        internal static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string labelText, object htmlAttributes, ModelMetadataProvider metadataProvider)\n        {\n            return LabelFor(html,\n                            expression,\n                            labelText,\n                            HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes),\n                            metadataProvider);\n        }\n\n        internal static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string labelText, IDictionary<string, object> htmlAttributes, ModelMetadataProvider metadataProvider)\n        {\n            return LabelHelper(html,\n                               ModelMetadata.FromLambdaExpression(expression, html.ViewData, metadataProvider),\n                               ExpressionHelper.GetExpressionText(expression),\n                               labelText,\n                               htmlAttributes);\n        }\n\n        public static MvcHtmlString LabelForModel(this HtmlHelper html)\n        {\n            return LabelForModel(html, labelText: null);\n        }\n\n        public static MvcHtmlString LabelForModel(this HtmlHelper html, string labelText)\n        {\n            return LabelHelper(html, html.ViewData.ModelMetadata, String.Empty, labelText);\n        }\n\n        public static MvcHtmlString LabelForModel(this HtmlHelper html, object htmlAttributes)\n        {\n            return LabelHelper(html, html.ViewData.ModelMetadata, String.Empty, labelText: null, htmlAttributes: HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcHtmlString LabelForModel(this HtmlHelper html, IDictionary<string, object> htmlAttributes)\n        {\n            return LabelHelper(html, html.ViewData.ModelMetadata, String.Empty, labelText: null, htmlAttributes: htmlAttributes);\n        }\n\n        public static MvcHtmlString LabelForModel(this HtmlHelper html, string labelText, object htmlAttributes)\n        {\n            return LabelHelper(html, html.ViewData.ModelMetadata, String.Empty, labelText, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcHtmlString LabelForModel(this HtmlHelper html, string labelText, IDictionary<string, object> htmlAttributes)\n        {\n            return LabelHelper(html, html.ViewData.ModelMetadata, String.Empty, labelText, htmlAttributes);\n        }\n\n        internal static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string labelText = null, IDictionary<string, object> htmlAttributes = null)\n        {\n            string resolvedLabelText = labelText ?? metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();\n            if (String.IsNullOrEmpty(resolvedLabelText))\n            {\n                return MvcHtmlString.Empty;\n            }\n\n            TagBuilder tag = new TagBuilder(\"label\");\n            tag.Attributes.Add(\"for\", TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)));\n            tag.SetInnerText(resolvedLabelText);\n            tag.MergeAttributes(htmlAttributes, replaceExisting: true);\n            return tag.ToMvcHtmlString(TagRenderMode.Normal);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Html/LinkExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Mvc.Properties;\nusing System.Web.Routing;\nusing System.Web.WebPages;\n\nnamespace System.Web.Mvc.Html\n{\n    public static class LinkExtensions\n    {\n        public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName)\n        {\n            return ActionLink(htmlHelper, linkText, actionName, null /* controllerName */, new RouteValueDictionary(), new RouteValueDictionary());\n        }\n\n        public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues)\n        {\n            return ActionLink(htmlHelper, linkText, actionName, null /* controllerName */, TypeHelper.ObjectToDictionary(routeValues), new RouteValueDictionary());\n        }\n\n        public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues, object htmlAttributes)\n        {\n            return ActionLink(htmlHelper, linkText, actionName, null /* controllerName */, TypeHelper.ObjectToDictionary(routeValues), HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, RouteValueDictionary routeValues)\n        {\n            return ActionLink(htmlHelper, linkText, actionName, null /* controllerName */, routeValues, new RouteValueDictionary());\n        }\n\n        public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes)\n        {\n            return ActionLink(htmlHelper, linkText, actionName, null /* controllerName */, routeValues, htmlAttributes);\n        }\n\n        public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName)\n        {\n            return ActionLink(htmlHelper, linkText, actionName, controllerName, new RouteValueDictionary(), new RouteValueDictionary());\n        }\n\n        public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes)\n        {\n            return ActionLink(htmlHelper, linkText, actionName, controllerName, TypeHelper.ObjectToDictionary(routeValues), HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes)\n        {\n            if (String.IsNullOrEmpty(linkText))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"linkText\");\n            }\n            return MvcHtmlString.Create(HtmlHelper.GenerateLink(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection, linkText, null /* routeName */, actionName, controllerName, routeValues, htmlAttributes));\n        }\n\n        public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, string protocol, string hostName, string fragment, object routeValues, object htmlAttributes)\n        {\n            return ActionLink(htmlHelper, linkText, actionName, controllerName, protocol, hostName, fragment, TypeHelper.ObjectToDictionary(routeValues), HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, string protocol, string hostName, string fragment, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes)\n        {\n            if (String.IsNullOrEmpty(linkText))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"linkText\");\n            }\n            return MvcHtmlString.Create(HtmlHelper.GenerateLink(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection, linkText, null /* routeName */, actionName, controllerName, protocol, hostName, fragment, routeValues, htmlAttributes));\n        }\n\n        public static MvcHtmlString RouteLink(this HtmlHelper htmlHelper, string linkText, object routeValues)\n        {\n            return RouteLink(htmlHelper, linkText, TypeHelper.ObjectToDictionary(routeValues));\n        }\n\n        public static MvcHtmlString RouteLink(this HtmlHelper htmlHelper, string linkText, RouteValueDictionary routeValues)\n        {\n            return RouteLink(htmlHelper, linkText, routeValues, new RouteValueDictionary());\n        }\n\n        public static MvcHtmlString RouteLink(this HtmlHelper htmlHelper, string linkText, string routeName)\n        {\n            return RouteLink(htmlHelper, linkText, routeName, (object)null /* routeValues */);\n        }\n\n        public static MvcHtmlString RouteLink(this HtmlHelper htmlHelper, string linkText, string routeName, object routeValues)\n        {\n            return RouteLink(htmlHelper, linkText, routeName, TypeHelper.ObjectToDictionary(routeValues));\n        }\n\n        public static MvcHtmlString RouteLink(this HtmlHelper htmlHelper, string linkText, string routeName, RouteValueDictionary routeValues)\n        {\n            return RouteLink(htmlHelper, linkText, routeName, routeValues, new RouteValueDictionary());\n        }\n\n        public static MvcHtmlString RouteLink(this HtmlHelper htmlHelper, string linkText, object routeValues, object htmlAttributes)\n        {\n            return RouteLink(htmlHelper, linkText, TypeHelper.ObjectToDictionary(routeValues), HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcHtmlString RouteLink(this HtmlHelper htmlHelper, string linkText, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes)\n        {\n            return RouteLink(htmlHelper, linkText, null /* routeName */, routeValues, htmlAttributes);\n        }\n\n        public static MvcHtmlString RouteLink(this HtmlHelper htmlHelper, string linkText, string routeName, object routeValues, object htmlAttributes)\n        {\n            return RouteLink(htmlHelper, linkText, routeName, TypeHelper.ObjectToDictionary(routeValues), HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcHtmlString RouteLink(this HtmlHelper htmlHelper, string linkText, string routeName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes)\n        {\n            if (String.IsNullOrEmpty(linkText))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"linkText\");\n            }\n            return MvcHtmlString.Create(HtmlHelper.GenerateRouteLink(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection, linkText, routeName, routeValues, htmlAttributes));\n        }\n\n        public static MvcHtmlString RouteLink(this HtmlHelper htmlHelper, string linkText, string routeName, string protocol, string hostName, string fragment, object routeValues, object htmlAttributes)\n        {\n            return RouteLink(htmlHelper, linkText, routeName, protocol, hostName, fragment, TypeHelper.ObjectToDictionary(routeValues), HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcHtmlString RouteLink(this HtmlHelper htmlHelper, string linkText, string routeName, string protocol, string hostName, string fragment, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes)\n        {\n            if (String.IsNullOrEmpty(linkText))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"linkText\");\n            }\n            return MvcHtmlString.Create(HtmlHelper.GenerateRouteLink(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection, linkText, routeName, protocol, hostName, fragment, routeValues, htmlAttributes));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Html/MvcForm.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc.Html\n{\n    public class MvcForm : IDisposable\n    {\n        private readonly ViewContext _viewContext;\n        private bool _disposed;\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA1801:ReviewUnusedParameters\", MessageId = \"httpResponse\", Justification = \"This method existed in MVC 1.0 and has been deprecated.\")]\n        [Obsolete(\"This constructor is obsolete, because its functionality has been moved to MvcForm(ViewContext) now.\", true /* error */)]\n        public MvcForm(HttpResponseBase httpResponse)\n        {\n            throw new InvalidOperationException(MvcResources.MvcForm_ConstructorObsolete);\n        }\n\n        public MvcForm(ViewContext viewContext)\n        {\n            if (viewContext == null)\n            {\n                throw new ArgumentNullException(\"viewContext\");\n            }\n\n            _viewContext = viewContext;\n\n            // push the new FormContext\n            _viewContext.FormContext = new FormContext();\n        }\n\n        public void Dispose()\n        {\n            Dispose(true /* disposing */);\n            GC.SuppressFinalize(this);\n        }\n\n        protected virtual void Dispose(bool disposing)\n        {\n            if (!_disposed)\n            {\n                _disposed = true;\n                FormExtensions.EndForm(_viewContext);\n            }\n        }\n\n        public void EndForm()\n        {\n            Dispose(true);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Html/NameExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\n\nnamespace System.Web.Mvc.Html\n{\n    public static class NameExtensions\n    {\n        public static MvcHtmlString Id(this HtmlHelper html, string name)\n        {\n            return MvcHtmlString.Create(html.AttributeEncode(html.ViewData.TemplateInfo.GetFullHtmlFieldId(name)));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1011:ConsiderPassingBaseTypesAsParameters\", Justification = \"Users cannot use anonymous methods with the LambdaExpression type\")]\n        public static MvcHtmlString IdFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression)\n        {\n            return Id(html, ExpressionHelper.GetExpressionText(expression));\n        }\n\n        public static MvcHtmlString IdForModel(this HtmlHelper html)\n        {\n            return Id(html, String.Empty);\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1719:ParameterNamesShouldNotMatchMemberNames\", MessageId = \"1#\", Justification = \"This is a shipped API.\")]\n        public static MvcHtmlString Name(this HtmlHelper html, string name)\n        {\n            return MvcHtmlString.Create(html.AttributeEncode(html.ViewData.TemplateInfo.GetFullHtmlFieldName(name)));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1011:ConsiderPassingBaseTypesAsParameters\", Justification = \"Users cannot use anonymous methods with the LambdaExpression type\")]\n        public static MvcHtmlString NameFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression)\n        {\n            return Name(html, ExpressionHelper.GetExpressionText(expression));\n        }\n\n        public static MvcHtmlString NameForModel(this HtmlHelper html)\n        {\n            return Name(html, String.Empty);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Html/PartialExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.IO;\n\nnamespace System.Web.Mvc.Html\n{\n    public static class PartialExtensions\n    {\n        public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName)\n        {\n            return Partial(htmlHelper, partialViewName, null /* model */, htmlHelper.ViewData);\n        }\n\n        public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName, ViewDataDictionary viewData)\n        {\n            return Partial(htmlHelper, partialViewName, null /* model */, viewData);\n        }\n\n        public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName, object model)\n        {\n            return Partial(htmlHelper, partialViewName, model, htmlHelper.ViewData);\n        }\n\n        public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName, object model, ViewDataDictionary viewData)\n        {\n            using (StringWriter writer = new StringWriter(CultureInfo.CurrentCulture))\n            {\n                htmlHelper.RenderPartialInternal(partialViewName, viewData, model, writer, ViewEngines.Engines);\n                return MvcHtmlString.Create(writer.ToString());\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Html/RenderPartialExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc.Html\n{\n    public static class RenderPartialExtensions\n    {\n        // Renders the partial view with the parent's view data and model\n        public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName)\n        {\n            htmlHelper.RenderPartialInternal(partialViewName, htmlHelper.ViewData, null /* model */, htmlHelper.ViewContext.Writer, ViewEngines.Engines);\n        }\n\n        // Renders the partial view with the given view data and, implicitly, the given view data's model\n        public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName, ViewDataDictionary viewData)\n        {\n            htmlHelper.RenderPartialInternal(partialViewName, viewData, null /* model */, htmlHelper.ViewContext.Writer, ViewEngines.Engines);\n        }\n\n        // Renders the partial view with an empty view data and the given model\n        public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName, object model)\n        {\n            htmlHelper.RenderPartialInternal(partialViewName, htmlHelper.ViewData, model, htmlHelper.ViewContext.Writer, ViewEngines.Engines);\n        }\n\n        // Renders the partial view with a copy of the given view data plus the given model\n        public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName, object model, ViewDataDictionary viewData)\n        {\n            htmlHelper.RenderPartialInternal(partialViewName, viewData, model, htmlHelper.ViewContext.Writer, ViewEngines.Engines);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Html/SelectExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq;\nusing System.Linq.Expressions;\nusing System.Text;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc.Html\n{\n    public static class SelectExtensions\n    {\n        // DropDownList\n\n        public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name)\n        {\n            return DropDownList(htmlHelper, name, null /* selectList */, null /* optionLabel */, null /* htmlAttributes */);\n        }\n\n        public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, string optionLabel)\n        {\n            return DropDownList(htmlHelper, name, null /* selectList */, optionLabel, null /* htmlAttributes */);\n        }\n\n        public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList)\n        {\n            return DropDownList(htmlHelper, name, selectList, null /* optionLabel */, null /* htmlAttributes */);\n        }\n\n        public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, object htmlAttributes)\n        {\n            return DropDownList(htmlHelper, name, selectList, null /* optionLabel */, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, IDictionary<string, object> htmlAttributes)\n        {\n            return DropDownList(htmlHelper, name, selectList, null /* optionLabel */, htmlAttributes);\n        }\n\n        public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, string optionLabel)\n        {\n            return DropDownList(htmlHelper, name, selectList, optionLabel, null /* htmlAttributes */);\n        }\n\n        public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, string optionLabel, object htmlAttributes)\n        {\n            return DropDownList(htmlHelper, name, selectList, optionLabel, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, string optionLabel, IDictionary<string, object> htmlAttributes)\n        {\n            return DropDownListHelper(htmlHelper, metadata: null, expression: name, selectList: selectList, optionLabel: optionLabel, htmlAttributes: htmlAttributes);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList)\n        {\n            return DropDownListFor(htmlHelper, expression, selectList, null /* optionLabel */, null /* htmlAttributes */);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, object htmlAttributes)\n        {\n            return DropDownListFor(htmlHelper, expression, selectList, null /* optionLabel */, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, IDictionary<string, object> htmlAttributes)\n        {\n            return DropDownListFor(htmlHelper, expression, selectList, null /* optionLabel */, htmlAttributes);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel)\n        {\n            return DropDownListFor(htmlHelper, expression, selectList, optionLabel, null /* htmlAttributes */);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, object htmlAttributes)\n        {\n            return DropDownListFor(htmlHelper, expression, selectList, optionLabel, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1011:ConsiderPassingBaseTypesAsParameters\", Justification = \"Users cannot use anonymous methods with the LambdaExpression type\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, IDictionary<string, object> htmlAttributes)\n        {\n            if (expression == null)\n            {\n                throw new ArgumentNullException(\"expression\");\n            }\n\n            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);\n\n            return DropDownListHelper(htmlHelper, metadata, ExpressionHelper.GetExpressionText(expression), selectList, optionLabel, htmlAttributes);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\",\n            Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper,\n            Expression<Func<TModel, TEnum>> expression)\n        {\n            return EnumDropDownListFor(htmlHelper, expression, optionLabel: null);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\",\n            Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper,\n            Expression<Func<TModel, TEnum>> expression, object htmlAttributes)\n        {\n            return EnumDropDownListFor(htmlHelper, expression, optionLabel: null, htmlAttributes: htmlAttributes);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\",\n            Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper,\n            Expression<Func<TModel, TEnum>> expression, IDictionary<string, object> htmlAttributes)\n        {\n            return EnumDropDownListFor(htmlHelper, expression, optionLabel: null, htmlAttributes: htmlAttributes);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\",\n            Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper,\n            Expression<Func<TModel, TEnum>> expression, string optionLabel)\n        {\n            return EnumDropDownListFor(htmlHelper, expression, optionLabel, (IDictionary<string, object>)null);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\",\n            Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper,\n            Expression<Func<TModel, TEnum>> expression, string optionLabel, object htmlAttributes)\n        {\n            return EnumDropDownListFor(htmlHelper, expression, optionLabel,\n                HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        // Unable to constrain TEnum.  Cannot include IComparable, IConvertible, IFormattable because Nullable<T> does\n        // not implement those interfaces (and Int32 does).  Enum alone is not compatible with expression restrictions\n        // because that requires a cast from all enum types.  And the struct generic constraint disallows passing a\n        // Nullable<T> expression.\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\",\n            Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper,\n            Expression<Func<TModel, TEnum>> expression, string optionLabel, IDictionary<string, object> htmlAttributes)\n        {\n            if (expression == null)\n            {\n                throw Error.ArgumentNull(\"expression\");\n            }\n\n            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);\n            if (metadata == null)\n            {\n                throw Error.Argument(\"expression\", MvcResources.SelectExtensions_InvalidExpressionParameterNoMetadata,\n                    expression.ToString());\n            }\n\n            if (metadata.ModelType == null)\n            {\n                throw Error.Argument(\"expression\", MvcResources.SelectExtensions_InvalidExpressionParameterNoModelType,\n                    expression.ToString());\n            }\n\n            if (!EnumHelper.IsValidForEnumHelper(metadata.ModelType))\n            {\n                string formatString;\n                if (EnumHelper.HasFlags(metadata.ModelType))\n                {\n                    formatString = MvcResources.SelectExtensions_InvalidExpressionParameterTypeHasFlags;\n                }\n                else\n                {\n                    formatString = MvcResources.SelectExtensions_InvalidExpressionParameterType;\n                }\n\n                throw Error.Argument(\"expression\", formatString, metadata.ModelType.FullName, \"Flags\");\n            }\n\n            // Run through same processing as SelectInternal() to determine selected value and ensure it is included\n            // in the select list.\n            string expressionName = ExpressionHelper.GetExpressionText(expression);\n            string expressionFullName =\n                htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expressionName);\n            Enum currentValue = null;\n            if (!String.IsNullOrEmpty(expressionFullName))\n            {\n                currentValue = htmlHelper.GetModelStateValue(expressionFullName, metadata.ModelType) as Enum;\n            }\n\n            if (currentValue == null && !String.IsNullOrEmpty(expressionName))\n            {\n                // Ignore any select list (enumerable with this name) in the view data\n                currentValue = htmlHelper.ViewData.Eval(expressionName) as Enum;\n            }\n\n            if (currentValue == null)\n            {\n                currentValue = metadata.Model as Enum;\n            }\n\n            IList<SelectListItem> selectList = EnumHelper.GetSelectList(metadata.ModelType, currentValue);\n            if (!String.IsNullOrEmpty(optionLabel) && selectList.Count != 0 && String.IsNullOrEmpty(selectList[0].Text))\n            {\n                // Were given an optionLabel and the select list has a blank initial slot.  Combine.\n                selectList[0].Text = optionLabel;\n\n                // Use the option label just once; don't pass it down the lower-level helpers.\n                optionLabel = null;\n            }\n\n            return DropDownListHelper(htmlHelper, metadata, expressionName, selectList, optionLabel, htmlAttributes);\n        }\n\n        private static MvcHtmlString DropDownListHelper(HtmlHelper htmlHelper, ModelMetadata metadata, string expression, IEnumerable<SelectListItem> selectList, string optionLabel, IDictionary<string, object> htmlAttributes)\n        {\n            return SelectInternal(htmlHelper, metadata, optionLabel, expression, selectList, allowMultiple: false, htmlAttributes: htmlAttributes);\n        }\n\n        // ListBox\n\n        public static MvcHtmlString ListBox(this HtmlHelper htmlHelper, string name)\n        {\n            return ListBox(htmlHelper, name, null /* selectList */, null /* htmlAttributes */);\n        }\n\n        public static MvcHtmlString ListBox(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList)\n        {\n            return ListBox(htmlHelper, name, selectList, (IDictionary<string, object>)null);\n        }\n\n        public static MvcHtmlString ListBox(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, object htmlAttributes)\n        {\n            return ListBox(htmlHelper, name, selectList, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcHtmlString ListBox(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList, IDictionary<string, object> htmlAttributes)\n        {\n            return ListBoxHelper(htmlHelper, metadata: null, name: name, selectList: selectList, htmlAttributes: htmlAttributes);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString ListBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList)\n        {\n            return ListBoxFor(htmlHelper, expression, selectList, null /* htmlAttributes */);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString ListBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, object htmlAttributes)\n        {\n            return ListBoxFor(htmlHelper, expression, selectList, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1011:ConsiderPassingBaseTypesAsParameters\", Justification = \"Users cannot use anonymous methods with the LambdaExpression type\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString ListBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, IDictionary<string, object> htmlAttributes)\n        {\n            if (expression == null)\n            {\n                throw new ArgumentNullException(\"expression\");\n            }\n\n            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);\n\n            return ListBoxHelper(htmlHelper,\n                                 metadata,\n                                 ExpressionHelper.GetExpressionText(expression),\n                                 selectList,\n                                 htmlAttributes);\n        }\n\n        private static MvcHtmlString ListBoxHelper(HtmlHelper htmlHelper, ModelMetadata metadata, string name, IEnumerable<SelectListItem> selectList, IDictionary<string, object> htmlAttributes)\n        {\n            return SelectInternal(htmlHelper, metadata, optionLabel: null, name: name, selectList: selectList, allowMultiple: true, htmlAttributes: htmlAttributes);\n        }\n\n        // Helper methods\n\n        private static IEnumerable<SelectListItem> GetSelectData(this HtmlHelper htmlHelper, string name)\n        {\n            object o = null;\n            if (htmlHelper.ViewData != null && !String.IsNullOrEmpty(name))\n            {\n                o = htmlHelper.ViewData.Eval(name);\n            }\n            if (o == null)\n            {\n                throw new InvalidOperationException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.HtmlHelper_MissingSelectData,\n                        name,\n                        \"IEnumerable<SelectListItem>\"));\n            }\n            IEnumerable<SelectListItem> selectList = o as IEnumerable<SelectListItem>;\n            if (selectList == null)\n            {\n                throw new InvalidOperationException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.HtmlHelper_WrongSelectDataType,\n                        name,\n                        o.GetType().FullName,\n                        \"IEnumerable<SelectListItem>\"));\n            }\n            return selectList;\n        }\n\n        internal static string ListItemToOption(SelectListItem item)\n        {\n            TagBuilder builder = new TagBuilder(\"option\")\n            {\n                InnerHtml = HttpUtility.HtmlEncode(item.Text)\n            };\n            if (item.Value != null)\n            {\n                builder.Attributes[\"value\"] = item.Value;\n            }\n            if (item.Selected)\n            {\n                builder.Attributes[\"selected\"] = \"selected\";\n            }\n            if (item.Disabled)\n            {\n                builder.Attributes[\"disabled\"] = \"disabled\";\n            }\n            return builder.ToString(TagRenderMode.Normal);\n        }\n\n        private static IEnumerable<SelectListItem> GetSelectListWithDefaultValue(IEnumerable<SelectListItem> selectList, object defaultValue, bool allowMultiple)\n        {\n            IEnumerable defaultValues;\n\n            if (allowMultiple)\n            {\n                defaultValues = defaultValue as IEnumerable;\n                if (defaultValues == null || defaultValues is string)\n                {\n                    throw new InvalidOperationException(\n                        String.Format(\n                            CultureInfo.CurrentCulture,\n                            MvcResources.HtmlHelper_SelectExpressionNotEnumerable,\n                            \"expression\"));\n                }\n            }\n            else\n            {\n                defaultValues = new[] { defaultValue };\n            }\n\n            IEnumerable<string> values = from object value in defaultValues\n                                         select Convert.ToString(value, CultureInfo.CurrentCulture);\n\n            // ToString() by default returns an enum value's name.  But selectList may use numeric values.\n            IEnumerable<string> enumValues = from Enum value in defaultValues.OfType<Enum>()\n                                             select value.ToString(\"d\");\n            values = values.Concat(enumValues);\n\n            HashSet<string> selectedValues = new HashSet<string>(values, StringComparer.OrdinalIgnoreCase);\n            List<SelectListItem> newSelectList = new List<SelectListItem>();\n\n            foreach (SelectListItem item in selectList)\n            {\n                item.Selected = (item.Value != null) ? selectedValues.Contains(item.Value) : selectedValues.Contains(item.Text);\n                newSelectList.Add(item);\n            }\n            return newSelectList;\n        }\n\n        private static MvcHtmlString SelectInternal(this HtmlHelper htmlHelper, ModelMetadata metadata,\n            string optionLabel, string name, IEnumerable<SelectListItem> selectList, bool allowMultiple,\n            IDictionary<string, object> htmlAttributes)\n        {\n            string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);\n            if (String.IsNullOrEmpty(fullName))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"name\");\n            }\n\n            bool usedViewData = false;\n\n            // If we got a null selectList, try to use ViewData to get the list of items.\n            if (selectList == null)\n            {\n                selectList = htmlHelper.GetSelectData(name);\n                usedViewData = true;\n            }\n\n            object defaultValue = (allowMultiple) ? htmlHelper.GetModelStateValue(fullName, typeof(string[])) : htmlHelper.GetModelStateValue(fullName, typeof(string));\n\n            // If we haven't already used ViewData to get the entire list of items then we need to\n            // use the ViewData-supplied value before using the parameter-supplied value.\n            if (defaultValue == null)\n            {\n                if (!usedViewData && !String.IsNullOrEmpty(name))\n                {\n                    defaultValue = htmlHelper.ViewData.Eval(name);\n                }\n                else if (metadata != null)\n                {\n                    defaultValue = metadata.Model;\n                }\n            }\n\n            if (defaultValue != null)\n            {\n                selectList = GetSelectListWithDefaultValue(selectList, defaultValue, allowMultiple);\n            }\n\n            // Convert each ListItem to an <option> tag and wrap them with <optgroup> if requested.\n            StringBuilder listItemBuilder = BuildItems(optionLabel, selectList);\n\n            TagBuilder tagBuilder = new TagBuilder(\"select\")\n            {\n                InnerHtml = listItemBuilder.ToString()\n            };\n            tagBuilder.MergeAttributes(htmlAttributes);\n            tagBuilder.MergeAttribute(\"name\", fullName, true /* replaceExisting */);\n            tagBuilder.GenerateId(fullName);\n            if (allowMultiple)\n            {\n                tagBuilder.MergeAttribute(\"multiple\", \"multiple\");\n            }\n\n            // If there are any errors for a named field, we add the css attribute.\n            ModelState modelState;\n            if (htmlHelper.ViewData.ModelState.TryGetValue(fullName, out modelState))\n            {\n                if (modelState.Errors.Count > 0)\n                {\n                    tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);\n                }\n            }\n\n            tagBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(name, metadata));\n\n            return tagBuilder.ToMvcHtmlString(TagRenderMode.Normal);\n        }\n\n        private static StringBuilder BuildItems(string optionLabel, IEnumerable<SelectListItem> selectList)\n        {\n            StringBuilder listItemBuilder = new StringBuilder();\n\n            // Make optionLabel the first item that gets rendered.\n            if (optionLabel != null)\n            {\n                listItemBuilder.AppendLine(ListItemToOption(new SelectListItem()\n                {\n                    Text = optionLabel,\n                    Value = String.Empty,\n                    Selected = false\n                }));\n            }\n\n            // Group items in the SelectList if requested.\n            // Treat each item with Group == null as a member of a unique group\n            // so they are added according to the original order.\n            IEnumerable<IGrouping<int, SelectListItem>> groupedSelectList = selectList.GroupBy<SelectListItem, int>(\n                i => (i.Group == null) ? i.GetHashCode() : i.Group.GetHashCode());\n            foreach (IGrouping<int, SelectListItem> group in groupedSelectList)\n            {\n                SelectListGroup optGroup = group.First().Group;\n\n                // Wrap if requested.\n                TagBuilder groupBuilder = null;\n                if (optGroup != null)\n                {\n                    groupBuilder = new TagBuilder(\"optgroup\");\n                    if (optGroup.Name != null)\n                    {\n                        groupBuilder.MergeAttribute(\"label\", optGroup.Name);\n                    }\n                    if (optGroup.Disabled)\n                    {\n                        groupBuilder.MergeAttribute(\"disabled\", \"disabled\");\n                    }\n                    listItemBuilder.AppendLine(groupBuilder.ToString(TagRenderMode.StartTag));\n                }\n\n                foreach (SelectListItem item in group)\n                {\n                    listItemBuilder.AppendLine(ListItemToOption(item));\n                }\n\n                if (optGroup != null)\n                {\n                    listItemBuilder.AppendLine(groupBuilder.ToString(TagRenderMode.EndTag));\n                }\n            }\n\n            return listItemBuilder;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Html/TemplateHelpers.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Linq.Expressions;\nusing System.Web.Mvc.Properties;\nusing System.Web.Routing;\nusing System.Web.UI.WebControls;\nusing System.Web.WebPages;\n\nnamespace System.Web.Mvc.Html\n{\n    internal static class TemplateHelpers\n    {\n        private static readonly Dictionary<DataBoundControlMode, string> _modeViewPaths =\n            new Dictionary<DataBoundControlMode, string>\n            {\n                { DataBoundControlMode.ReadOnly, \"DisplayTemplates\" },\n                { DataBoundControlMode.Edit, \"EditorTemplates\" }\n            };\n\n        private static readonly Dictionary<string, Func<HtmlHelper, string>> _defaultDisplayActions =\n            new Dictionary<string, Func<HtmlHelper, string>>(StringComparer.OrdinalIgnoreCase)\n            {\n                { \"EmailAddress\", DefaultDisplayTemplates.EmailAddressTemplate },\n                { \"HiddenInput\", DefaultDisplayTemplates.HiddenInputTemplate },\n                { \"Html\", DefaultDisplayTemplates.HtmlTemplate },\n                { \"Text\", DefaultDisplayTemplates.StringTemplate },\n                { \"Url\", DefaultDisplayTemplates.UrlTemplate },\n                { \"Collection\", DefaultDisplayTemplates.CollectionTemplate },\n                { typeof(bool).Name, DefaultDisplayTemplates.BooleanTemplate },\n                { typeof(decimal).Name, DefaultDisplayTemplates.DecimalTemplate },\n                { typeof(string).Name, DefaultDisplayTemplates.StringTemplate },\n                { typeof(object).Name, DefaultDisplayTemplates.ObjectTemplate },\n            };\n\n        private static readonly Dictionary<string, Func<HtmlHelper, string>> _defaultEditorActions =\n            new Dictionary<string, Func<HtmlHelper, string>>(StringComparer.OrdinalIgnoreCase)\n            {\n                { \"HiddenInput\", DefaultEditorTemplates.HiddenInputTemplate },\n                { \"MultilineText\", DefaultEditorTemplates.MultilineTextTemplate },\n                { \"Password\", DefaultEditorTemplates.PasswordTemplate },\n                { \"Text\", DefaultEditorTemplates.StringTemplate },\n                { \"Collection\", DefaultEditorTemplates.CollectionTemplate },\n                { \"PhoneNumber\", DefaultEditorTemplates.PhoneNumberInputTemplate },\n                { \"Url\", DefaultEditorTemplates.UrlInputTemplate },\n                { \"EmailAddress\", DefaultEditorTemplates.EmailAddressInputTemplate },\n                { \"DateTime\", DefaultEditorTemplates.DateTimeInputTemplate },\n                { \"DateTime-local\", DefaultEditorTemplates.DateTimeLocalInputTemplate },\n                { \"Date\", DefaultEditorTemplates.DateInputTemplate },\n                { \"Time\", DefaultEditorTemplates.TimeInputTemplate },\n                { typeof(Color).Name, DefaultEditorTemplates.ColorInputTemplate },\n                { typeof(byte).Name, DefaultEditorTemplates.NumberInputTemplate },\n                { typeof(sbyte).Name, DefaultEditorTemplates.NumberInputTemplate },\n                { typeof(int).Name, DefaultEditorTemplates.NumberInputTemplate },\n                { typeof(uint).Name, DefaultEditorTemplates.NumberInputTemplate },\n                { typeof(long).Name, DefaultEditorTemplates.NumberInputTemplate },\n                { typeof(ulong).Name, DefaultEditorTemplates.NumberInputTemplate },\n                { typeof(bool).Name, DefaultEditorTemplates.BooleanTemplate },\n                { typeof(decimal).Name, DefaultEditorTemplates.DecimalTemplate },\n                { typeof(string).Name, DefaultEditorTemplates.StringTemplate },\n                { typeof(object).Name, DefaultEditorTemplates.ObjectTemplate },\n            };\n\n        internal static string CacheItemId = Guid.NewGuid().ToString();\n\n        internal delegate string ExecuteTemplateDelegate(HtmlHelper html, ViewDataDictionary viewData, string templateName,\n                                                         DataBoundControlMode mode, GetViewNamesDelegate getViewNames,\n                                                         GetDefaultActionsDelegate getDefaultActions);\n\n        internal delegate Dictionary<string, Func<HtmlHelper, string>> GetDefaultActionsDelegate(DataBoundControlMode mode);\n\n        internal delegate IEnumerable<string> GetViewNamesDelegate(ModelMetadata metadata, params string[] templateHints);\n\n        internal delegate string TemplateHelperDelegate(HtmlHelper html, ModelMetadata metadata, string htmlFieldName,\n                                                        string templateName, DataBoundControlMode mode, object additionalViewData);\n\n        internal static string ExecuteTemplate(HtmlHelper html, ViewDataDictionary viewData, string templateName, DataBoundControlMode mode, GetViewNamesDelegate getViewNames, GetDefaultActionsDelegate getDefaultActions)\n        {\n            Dictionary<string, ActionCacheItem> actionCache = GetActionCache(html);\n            Dictionary<string, Func<HtmlHelper, string>> defaultActions = getDefaultActions(mode);\n            string modeViewPath = _modeViewPaths[mode];\n\n            foreach (string viewName in getViewNames(viewData.ModelMetadata, templateName, viewData.ModelMetadata.TemplateHint, viewData.ModelMetadata.DataTypeName))\n            {\n                string fullViewName = modeViewPath + \"/\" + viewName;\n                ActionCacheItem cacheItem;\n\n                if (actionCache.TryGetValue(fullViewName, out cacheItem))\n                {\n                    if (cacheItem != null)\n                    {\n                        return cacheItem.Execute(html, viewData);\n                    }\n                }\n                else\n                {\n                    ViewEngineResult viewEngineResult = ViewEngines.Engines.FindPartialView(html.ViewContext, fullViewName);\n                    if (viewEngineResult.View != null)\n                    {\n                        actionCache[fullViewName] = new ActionCacheViewItem { ViewName = fullViewName };\n\n                        using (StringWriter writer = new StringWriter(CultureInfo.InvariantCulture))\n                        {\n                            viewEngineResult.View.Render(new ViewContext(html.ViewContext, viewEngineResult.View, viewData, html.ViewContext.TempData, writer), writer);\n                            return writer.ToString();\n                        }\n                    }\n\n                    Func<HtmlHelper, string> defaultAction;\n                    if (defaultActions.TryGetValue(viewName, out defaultAction))\n                    {\n                        actionCache[fullViewName] = new ActionCacheCodeItem { Action = defaultAction };\n                        return defaultAction(MakeHtmlHelper(html, viewData));\n                    }\n\n                    actionCache[fullViewName] = null;\n                }\n            }\n\n            throw new InvalidOperationException(\n                String.Format(\n                    CultureInfo.CurrentCulture,\n                    MvcResources.TemplateHelpers_NoTemplate,\n                    viewData.ModelMetadata.RealModelType.FullName));\n        }\n\n        internal static Dictionary<string, ActionCacheItem> GetActionCache(HtmlHelper html)\n        {\n            HttpContextBase context = html.ViewContext.HttpContext;\n            Dictionary<string, ActionCacheItem> result;\n\n            if (!context.Items.Contains(CacheItemId))\n            {\n                result = new Dictionary<string, ActionCacheItem>();\n                context.Items[CacheItemId] = result;\n            }\n            else\n            {\n                result = (Dictionary<string, ActionCacheItem>)context.Items[CacheItemId];\n            }\n\n            return result;\n        }\n\n        internal static Dictionary<string, Func<HtmlHelper, string>> GetDefaultActions(DataBoundControlMode mode)\n        {\n            return mode == DataBoundControlMode.ReadOnly ? _defaultDisplayActions : _defaultEditorActions;\n        }\n\n        internal static IEnumerable<string> GetViewNames(ModelMetadata metadata, params string[] templateHints)\n        {\n            foreach (string templateHint in templateHints.Where(s => !String.IsNullOrEmpty(s)))\n            {\n                yield return templateHint;\n            }\n\n            // We don't want to search for Nullable<T>, we want to search for T (which should handle both T and Nullable<T>)\n            Type fieldType = Nullable.GetUnderlyingType(metadata.RealModelType) ?? metadata.RealModelType;\n\n            // TODO: Make better string names for generic types\n            yield return fieldType.Name;\n\n            if (fieldType == typeof(string))\n            {\n                // Nothing more to provide\n                yield break;\n            }\n            else if (!metadata.IsComplexType)\n            {\n                // IsEnum is false for the Enum class itself\n                if (fieldType.IsEnum)\n                {\n                    // Same as fieldType.BaseType.Name in this case\n                    yield return \"Enum\";\n                }\n                else if (fieldType == typeof(DateTimeOffset))\n                {\n                    yield return \"DateTime\";\n                }\n\n                yield return \"String\";\n            }\n            else if (fieldType.IsInterface)\n            {\n                if (typeof(IEnumerable).IsAssignableFrom(fieldType))\n                {\n                    yield return \"Collection\";\n                }\n\n                yield return \"Object\";\n            }\n            else\n            {\n                bool isEnumerable = typeof(IEnumerable).IsAssignableFrom(fieldType);\n\n                while (true)\n                {\n                    fieldType = fieldType.BaseType;\n                    if (fieldType == null)\n                    {\n                        break;\n                    }\n\n                    if (isEnumerable && fieldType == typeof(Object))\n                    {\n                        yield return \"Collection\";\n                    }\n\n                    yield return fieldType.Name;\n                }\n            }\n        }\n\n        internal static MvcHtmlString Template(HtmlHelper html, string expression, string templateName, string htmlFieldName, DataBoundControlMode mode, object additionalViewData)\n        {\n            return MvcHtmlString.Create(Template(html, expression, templateName, htmlFieldName, mode, additionalViewData, TemplateHelper));\n        }\n\n        // Unit testing version\n        internal static string Template(HtmlHelper html, string expression, string templateName, string htmlFieldName,\n                                        DataBoundControlMode mode, object additionalViewData, TemplateHelperDelegate templateHelper)\n        {\n            return templateHelper(html,\n                                  ModelMetadata.FromStringExpression(expression, html.ViewData),\n                                  htmlFieldName ?? ExpressionHelper.GetExpressionText(expression),\n                                  templateName,\n                                  mode,\n                                  additionalViewData);\n        }\n\n        internal static MvcHtmlString TemplateFor<TContainer, TValue>(this HtmlHelper<TContainer> html, Expression<Func<TContainer, TValue>> expression,\n                                                                      string templateName, string htmlFieldName, DataBoundControlMode mode,\n                                                                      object additionalViewData)\n        {\n            return MvcHtmlString.Create(TemplateFor(html, expression, templateName, htmlFieldName, mode, additionalViewData, TemplateHelper));\n        }\n\n        // Unit testing version\n        internal static string TemplateFor<TContainer, TValue>(this HtmlHelper<TContainer> html, Expression<Func<TContainer, TValue>> expression,\n                                                               string templateName, string htmlFieldName, DataBoundControlMode mode,\n                                                               object additionalViewData, TemplateHelperDelegate templateHelper)\n        {\n            return templateHelper(html,\n                                  ModelMetadata.FromLambdaExpression(expression, html.ViewData),\n                                  htmlFieldName ?? ExpressionHelper.GetExpressionText(expression),\n                                  templateName,\n                                  mode,\n                                  additionalViewData);\n        }\n\n        internal static string TemplateHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string templateName, DataBoundControlMode mode, object additionalViewData)\n        {\n            return TemplateHelper(html, metadata, htmlFieldName, templateName, mode, additionalViewData, ExecuteTemplate);\n        }\n\n        internal static string TemplateHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string templateName, DataBoundControlMode mode, object additionalViewData, ExecuteTemplateDelegate executeTemplate)\n        {\n            // TODO: Convert Editor into Display if model.IsReadOnly is true? Need to be careful about this because\n            // the Model property on the ViewPage/ViewUserControl is get-only, so the type descriptor automatically\n            // decorates it with a [ReadOnly] attribute...\n\n            if (metadata.ConvertEmptyStringToNull && String.Empty.Equals(metadata.Model))\n            {\n                metadata.Model = null;\n            }\n\n            object formattedModelValue = metadata.Model;\n            if (metadata.Model == null && mode == DataBoundControlMode.ReadOnly)\n            {\n                formattedModelValue = metadata.NullDisplayText;\n            }\n\n            string formatString = mode == DataBoundControlMode.ReadOnly ? metadata.DisplayFormatString : metadata.EditFormatString;\n            if (metadata.Model != null && !String.IsNullOrEmpty(formatString))\n            {\n                formattedModelValue = String.Format(CultureInfo.CurrentCulture, formatString, metadata.Model);\n            }\n\n            // Normally this shouldn't happen, unless someone writes their own custom Object templates which\n            // don't check to make sure that the object hasn't already been displayed\n            object visitedObjectsKey = metadata.Model ?? metadata.RealModelType;\n            if (html.ViewDataContainer.ViewData.TemplateInfo.VisitedObjects.Contains(visitedObjectsKey))\n            {\n                // DDB #224750\n                return String.Empty;\n            }\n\n            ViewDataDictionary viewData = new ViewDataDictionary(html.ViewDataContainer.ViewData)\n            {\n                Model = metadata.Model,\n                ModelMetadata = metadata,\n                TemplateInfo = new TemplateInfo\n                {\n                    FormattedModelValue = formattedModelValue,\n                    HtmlFieldPrefix = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName),\n                    VisitedObjects = new HashSet<object>(html.ViewContext.ViewData.TemplateInfo.VisitedObjects), // DDB #224750\n                }\n            };\n\n            if (additionalViewData != null)\n            {\n                foreach (KeyValuePair<string, object> kvp in TypeHelper.ObjectToDictionary(additionalViewData))\n                {\n                    viewData[kvp.Key] = kvp.Value;\n                }\n            }\n\n            viewData.TemplateInfo.VisitedObjects.Add(visitedObjectsKey); // DDB #224750\n\n            return executeTemplate(html, viewData, templateName, mode, GetViewNames, GetDefaultActions);\n        }\n\n        // Helpers\n\n        private static HtmlHelper MakeHtmlHelper(HtmlHelper html, ViewDataDictionary viewData)\n        {\n            var newHelper = new HtmlHelper(\n                new ViewContext(html.ViewContext, html.ViewContext.View, viewData, html.ViewContext.TempData, html.ViewContext.Writer),\n                new ViewDataContainer(viewData));\n            newHelper.Html5DateRenderingMode = html.Html5DateRenderingMode;\n            return newHelper;\n        }\n\n        internal class ActionCacheCodeItem : ActionCacheItem\n        {\n            public Func<HtmlHelper, string> Action { get; set; }\n\n            public override string Execute(HtmlHelper html, ViewDataDictionary viewData)\n            {\n                return Action(MakeHtmlHelper(html, viewData));\n            }\n        }\n\n        internal abstract class ActionCacheItem\n        {\n            public abstract string Execute(HtmlHelper html, ViewDataDictionary viewData);\n        }\n\n        internal class ActionCacheViewItem : ActionCacheItem\n        {\n            public string ViewName { get; set; }\n\n            public override string Execute(HtmlHelper html, ViewDataDictionary viewData)\n            {\n                ViewEngineResult viewEngineResult = ViewEngines.Engines.FindPartialView(html.ViewContext, ViewName);\n                using (StringWriter writer = new StringWriter(CultureInfo.InvariantCulture))\n                {\n                    viewEngineResult.View.Render(new ViewContext(html.ViewContext, viewEngineResult.View, viewData, html.ViewContext.TempData, writer), writer);\n                    return writer.ToString();\n                }\n            }\n        }\n\n        private class ViewDataContainer : IViewDataContainer\n        {\n            public ViewDataContainer(ViewDataDictionary viewData)\n            {\n                ViewData = viewData;\n            }\n\n            public ViewDataDictionary ViewData { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Html/TextAreaExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq.Expressions;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc.Html\n{\n    public static class TextAreaExtensions\n    {\n        // These values are similar to the defaults used by WebForms\n        // when using <asp:TextBox TextMode=\"MultiLine\"> without specifying\n        // the Rows and Columns attributes.\n        private const int TextAreaRows = 2;\n        private const int TextAreaColumns = 20;\n\n        private static Dictionary<string, object> implicitRowsAndColumns = new Dictionary<string, object>\n        {\n            { \"rows\", TextAreaRows.ToString(CultureInfo.InvariantCulture) },\n            { \"cols\", TextAreaColumns.ToString(CultureInfo.InvariantCulture) },\n        };\n\n        private static Dictionary<string, object> GetRowsAndColumnsDictionary(int rows, int columns)\n        {\n            if (rows < 0)\n            {\n                throw new ArgumentOutOfRangeException(\"rows\", MvcResources.HtmlHelper_TextAreaParameterOutOfRange);\n            }\n            if (columns < 0)\n            {\n                throw new ArgumentOutOfRangeException(\"columns\", MvcResources.HtmlHelper_TextAreaParameterOutOfRange);\n            }\n\n            Dictionary<string, object> result = new Dictionary<string, object>();\n            if (rows > 0)\n            {\n                result.Add(\"rows\", rows.ToString(CultureInfo.InvariantCulture));\n            }\n            if (columns > 0)\n            {\n                result.Add(\"cols\", columns.ToString(CultureInfo.InvariantCulture));\n            }\n\n            return result;\n        }\n\n        public static MvcHtmlString TextArea(this HtmlHelper htmlHelper, string name)\n        {\n            return TextArea(htmlHelper, name, null /* value */, null /* htmlAttributes */);\n        }\n\n        public static MvcHtmlString TextArea(this HtmlHelper htmlHelper, string name, object htmlAttributes)\n        {\n            return TextArea(htmlHelper, name, null /* value */, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcHtmlString TextArea(this HtmlHelper htmlHelper, string name, IDictionary<string, object> htmlAttributes)\n        {\n            return TextArea(htmlHelper, name, null /* value */, htmlAttributes);\n        }\n\n        public static MvcHtmlString TextArea(this HtmlHelper htmlHelper, string name, string value)\n        {\n            return TextArea(htmlHelper, name, value, null /* htmlAttributes */);\n        }\n\n        public static MvcHtmlString TextArea(this HtmlHelper htmlHelper, string name, string value, object htmlAttributes)\n        {\n            return TextArea(htmlHelper, name, value, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcHtmlString TextArea(this HtmlHelper htmlHelper, string name, string value, IDictionary<string, object> htmlAttributes)\n        {\n            ModelMetadata metadata = ModelMetadata.FromStringExpression(name, htmlHelper.ViewContext.ViewData);\n            if (value != null)\n            {\n                metadata.Model = value;\n            }\n\n            return TextAreaHelper(htmlHelper, metadata, name, implicitRowsAndColumns, htmlAttributes);\n        }\n\n        public static MvcHtmlString TextArea(this HtmlHelper htmlHelper, string name, string value, int rows, int columns, object htmlAttributes)\n        {\n            return TextArea(htmlHelper, name, value, rows, columns, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public static MvcHtmlString TextArea(this HtmlHelper htmlHelper, string name, string value, int rows, int columns, IDictionary<string, object> htmlAttributes)\n        {\n            ModelMetadata metadata = ModelMetadata.FromStringExpression(name, htmlHelper.ViewContext.ViewData);\n            if (value != null)\n            {\n                metadata.Model = value;\n            }\n\n            return TextAreaHelper(htmlHelper, metadata, name, GetRowsAndColumnsDictionary(rows, columns), htmlAttributes);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString TextAreaFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)\n        {\n            return TextAreaFor(htmlHelper, expression, (IDictionary<string, object>)null);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString TextAreaFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)\n        {\n            return TextAreaFor(htmlHelper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString TextAreaFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)\n        {\n            if (expression == null)\n            {\n                throw new ArgumentNullException(\"expression\");\n            }\n\n            return TextAreaHelper(htmlHelper,\n                                  ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData),\n                                  ExpressionHelper.GetExpressionText(expression),\n                                  implicitRowsAndColumns,\n                                  htmlAttributes);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString TextAreaFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, int rows, int columns, object htmlAttributes)\n        {\n            return TextAreaFor(htmlHelper, expression, rows, columns, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString TextAreaFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, int rows, int columns, IDictionary<string, object> htmlAttributes)\n        {\n            if (expression == null)\n            {\n                throw new ArgumentNullException(\"expression\");\n            }\n\n            return TextAreaHelper(htmlHelper,\n                                  ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData),\n                                  ExpressionHelper.GetExpressionText(expression),\n                                  GetRowsAndColumnsDictionary(rows, columns),\n                                  htmlAttributes);\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2208:InstantiateArgumentExceptionsCorrectly\", Justification = \"If this fails, it is because the string-based version had an empty 'name' parameter\")]\n        internal static MvcHtmlString TextAreaHelper(HtmlHelper htmlHelper, ModelMetadata modelMetadata, string name, IDictionary<string, object> rowsAndColumns, IDictionary<string, object> htmlAttributes, string innerHtmlPrefix = null)\n        {\n            string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);\n            if (String.IsNullOrEmpty(fullName))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"name\");\n            }\n\n            TagBuilder tagBuilder = new TagBuilder(\"textarea\");\n            tagBuilder.GenerateId(fullName);\n            tagBuilder.MergeAttributes(htmlAttributes, true);\n            tagBuilder.MergeAttributes(rowsAndColumns, rowsAndColumns != implicitRowsAndColumns); // Only force explicit rows/cols\n            tagBuilder.MergeAttribute(\"name\", fullName, true);\n\n            // If there are any errors for a named field, we add the CSS attribute.\n            ModelState modelState;\n            if (htmlHelper.ViewData.ModelState.TryGetValue(fullName, out modelState) && modelState.Errors.Count > 0)\n            {\n                tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);\n            }\n\n            tagBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(name, modelMetadata));\n\n            string value;\n            if (modelState != null && modelState.Value != null)\n            {\n                value = modelState.Value.AttemptedValue;\n            }\n            else if (modelMetadata.Model != null)\n            {\n                value = modelMetadata.Model.ToString();\n            }\n            else\n            {\n                value = String.Empty;\n            }\n\n            // The first newline is always trimmed when a TextArea is rendered, so we add an extra one\n            // in case the value being rendered is something like \"\\r\\nHello\".\n            tagBuilder.InnerHtml = (innerHtmlPrefix ?? Environment.NewLine) + HttpUtility.HtmlEncode(value);\n\n            return tagBuilder.ToMvcHtmlString(TagRenderMode.Normal);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Html/ValidationExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq;\nusing System.Linq.Expressions;\nusing System.Text;\nusing System.Web.Mvc.Properties;\nusing System.Web.Routing;\n\nnamespace System.Web.Mvc.Html\n{\n    public static class ValidationExtensions\n    {\n        private const string HiddenListItem = @\"<li style=\"\"display:none\"\"></li>\";\n        private static string _resourceClassKey;\n\n        public static string ResourceClassKey\n        {\n            get { return _resourceClassKey ?? String.Empty; }\n            set { _resourceClassKey = value; }\n        }\n\n        private static FieldValidationMetadata ApplyFieldValidationMetadata(HtmlHelper htmlHelper, ModelMetadata modelMetadata, string modelName)\n        {\n            FormContext formContext = htmlHelper.ViewContext.FormContext;\n            FieldValidationMetadata fieldMetadata = formContext.GetValidationMetadataForField(modelName, true /* createIfNotFound */);\n\n            // write rules to context object\n            IEnumerable<ModelValidator> validators = ModelValidatorProviders.Providers.GetValidators(modelMetadata, htmlHelper.ViewContext);\n            foreach (ModelClientValidationRule rule in validators.SelectMany(v => v.GetClientValidationRules()))\n            {\n                fieldMetadata.ValidationRules.Add(rule);\n            }\n\n            return fieldMetadata;\n        }\n\n        private static string GetInvalidPropertyValueResource(HttpContextBase httpContext)\n        {\n            string resourceValue = null;\n            if (!String.IsNullOrEmpty(ResourceClassKey) && (httpContext != null))\n            {\n                // If the user specified a ResourceClassKey try to load the resource they specified.\n                // If the class key is invalid, an exception will be thrown.\n                // If the class key is valid but the resource is not found, it returns null, in which\n                // case it will fall back to the MVC default error message.\n                resourceValue = httpContext.GetGlobalResourceObject(ResourceClassKey, \"InvalidPropertyValue\", CultureInfo.CurrentUICulture) as string;\n            }\n            return resourceValue ?? MvcResources.Common_ValueNotValidForProperty;\n        }\n\n        private static string GetUserErrorMessageOrDefault(HttpContextBase httpContext, ModelError error, ModelState modelState)\n        {\n            if (!String.IsNullOrEmpty(error.ErrorMessage))\n            {\n                return error.ErrorMessage;\n            }\n            if (modelState == null)\n            {\n                return null;\n            }\n\n            string attemptedValue = (modelState.Value != null) ? modelState.Value.AttemptedValue : null;\n            return String.Format(CultureInfo.CurrentCulture, GetInvalidPropertyValueResource(httpContext), attemptedValue);\n        }\n\n        // Validate\n\n        public static void Validate(this HtmlHelper htmlHelper, string modelName)\n        {\n            if (modelName == null)\n            {\n                throw new ArgumentNullException(\"modelName\");\n            }\n\n            ValidateHelper(htmlHelper,\n                           ModelMetadata.FromStringExpression(modelName, htmlHelper.ViewContext.ViewData),\n                           modelName);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static void ValidateFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)\n        {\n            ValidateHelper(htmlHelper,\n                           ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData),\n                           ExpressionHelper.GetExpressionText(expression));\n        }\n\n        private static void ValidateHelper(HtmlHelper htmlHelper, ModelMetadata modelMetadata, string expression)\n        {\n            FormContext formContext = htmlHelper.ViewContext.GetFormContextForClientValidation();\n            if (formContext == null || htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled)\n            {\n                return; // nothing to do\n            }\n\n            string modelName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expression);\n            ApplyFieldValidationMetadata(htmlHelper, modelMetadata, modelName);\n        }\n\n        // ValidationMessage\n\n        public static MvcHtmlString ValidationMessage(this HtmlHelper htmlHelper, string modelName)\n        {\n            return ValidationMessage(htmlHelper, modelName, validationMessage: null, htmlAttributes: new RouteValueDictionary());\n        }\n\n        public static MvcHtmlString ValidationMessage(this HtmlHelper htmlHelper, string modelName, object htmlAttributes)\n        {\n            return ValidationMessage(htmlHelper, modelName, validationMessage: null, htmlAttributes: HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        /// <summary>\n        /// Displays a validation message if an error exists for the specified entry in the\n        /// <see cref=\"ModelStateDictionary\"/> object.\n        /// </summary>\n        /// <param name=\"htmlHelper\">The HTML helper instance that this method operates on.</param>\n        /// <param name=\"modelName\">The name of the entry being validated.</param>\n        /// <param name=\"htmlAttributes\">An object that contains the HTML attributes for the element.</param>\n        /// <param name=\"tag\">The tag to be set for the wrapping HTML element of the validation message.</param>\n        /// <returns>null if the entry is valid and client-side validation is disabled.\n        /// Otherwise, a <paramref name=\"tag\"/> element that contains an error message.</returns>\n        public static MvcHtmlString ValidationMessage(this HtmlHelper htmlHelper,\n                                                      string modelName,\n                                                      object htmlAttributes,\n                                                      string tag)\n        {\n            return ValidationMessage(htmlHelper,\n                                     modelName,\n                                     validationMessage: null,\n                                     htmlAttributes: HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes),\n                                     tag: tag);\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1719:ParameterNamesShouldNotMatchMemberNames\", Justification = \"'validationMessage' refers to the message that will be rendered by the ValidationMessage helper.\")]\n        public static MvcHtmlString ValidationMessage(this HtmlHelper htmlHelper, string modelName, string validationMessage)\n        {\n            return ValidationMessage(htmlHelper, modelName, validationMessage, new RouteValueDictionary());\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1719:ParameterNamesShouldNotMatchMemberNames\", Justification = \"'validationMessage' refers to the message that will be rendered by the ValidationMessage helper.\")]\n        public static MvcHtmlString ValidationMessage(this HtmlHelper htmlHelper, string modelName, string validationMessage, object htmlAttributes)\n        {\n            return ValidationMessage(htmlHelper, modelName, validationMessage, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        /// <summary>\n        /// Displays a validation message if an error exists for the specified entry in the\n        /// <see cref=\"ModelStateDictionary\"/> object.\n        /// </summary>\n        /// <param name=\"htmlHelper\">The HTML helper instance that this method operates on.</param>\n        /// <param name=\"modelName\">The name of the entry being validated.</param>\n        /// <param name=\"validationMessage\">The message to display if the specified entry contains an error.</param>\n        /// <param name=\"htmlAttributes\">An object that contains the HTML attributes for the element.</param>\n        /// <param name=\"tag\">The tag to be set for the wrapping HTML element of the validation message.</param>\n        /// <returns>null if the entry is valid and client-side validation is disabled.\n        /// Otherwise, a <paramref name=\"tag\"/> element that contains an error message.</returns>\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1719:ParameterNamesShouldNotMatchMemberNames\", Justification =\n            \"'validationMessage' refers to the message that will be rendered by the ValidationMessage helper.\")]\n        public static MvcHtmlString ValidationMessage(this HtmlHelper htmlHelper,\n                                                      string modelName,\n                                                      string validationMessage,\n                                                      object htmlAttributes,\n                                                      string tag)\n        {\n            return ValidationMessage(htmlHelper,\n                                     modelName,\n                                     validationMessage,\n                                     HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes),\n                                     tag);\n        }\n\n        /// <summary>\n        /// Displays a validation message if an error exists for the specified entry in the\n        /// <see cref=\"ModelStateDictionary\"/> object.\n        /// </summary>\n        /// <param name=\"htmlHelper\">The HTML helper instance that this method operates on.</param>\n        /// <param name=\"modelName\">The name of the entry being validated.</param>\n        /// <param name=\"validationMessage\">The message to display if the specified entry contains an error.</param>\n        /// <param name=\"tag\">The tag to be set for the wrapping HTML element of the validation message.</param>\n        /// <returns>null if the entry is valid and client-side validation is disabled.\n        /// Otherwise, a <paramref name=\"tag\"/> element that contains an error message.</returns>\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1719:ParameterNamesShouldNotMatchMemberNames\", Justification =\n            \"'validationMessage' refers to the message that will be rendered by the ValidationMessage helper.\")]\n        public static MvcHtmlString ValidationMessage(this HtmlHelper htmlHelper,\n                                                      string modelName,\n                                                      string validationMessage,\n                                                      string tag)\n        {\n            return ValidationMessage(htmlHelper,\n                                     modelName,\n                                     validationMessage,\n                                     htmlAttributes: new RouteValueDictionary(),\n                                     tag: tag);\n        }\n\n        public static MvcHtmlString ValidationMessage(this HtmlHelper htmlHelper, string modelName, IDictionary<string, object> htmlAttributes)\n        {\n            return ValidationMessage(htmlHelper, modelName, validationMessage: null, htmlAttributes: htmlAttributes);\n        }\n\n        /// <summary>\n        /// Displays a validation message if an error exists for the specified entry in the\n        /// <see cref=\"ModelStateDictionary\"/> object.\n        /// </summary>\n        /// <param name=\"htmlHelper\">The HTML helper instance that this method operates on.</param>\n        /// <param name=\"modelName\">The name of the entry being validated.</param>\n        /// <param name=\"htmlAttributes\">An <see cref=\"IDictionary{TKey,TValue}\"/> that contains the HTML attributes\n        /// for the element.</param>\n        /// <param name=\"tag\">The tag to be set for the wrapping HTML element of the validation message.</param>\n        /// <returns>null if the entry is valid and client-side validation is disabled.\n        /// Otherwise, a <paramref name=\"tag\"/> element that contains an error message.</returns>\n        public static MvcHtmlString ValidationMessage(this HtmlHelper htmlHelper,\n                                                      string modelName,\n                                                      IDictionary<string, object> htmlAttributes,\n                                                      string tag)\n        {\n            return ValidationMessage(htmlHelper,\n                                     modelName,\n                                     validationMessage: null,\n                                     htmlAttributes: htmlAttributes,\n                                     tag: tag);\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1719:ParameterNamesShouldNotMatchMemberNames\", Justification = \"'validationMessage' refers to the message that will be rendered by the ValidationMessage helper.\")]\n        public static MvcHtmlString ValidationMessage(this HtmlHelper htmlHelper, string modelName, string validationMessage, IDictionary<string, object> htmlAttributes)\n        {\n            return ValidationMessage(htmlHelper, modelName, validationMessage, htmlAttributes, tag: null);\n        }\n\n        /// <summary>\n        /// Displays a validation message if an error exists for the specified entry in the\n        /// <see cref=\"ModelStateDictionary\"/> object.\n        /// </summary>\n        /// <param name=\"htmlHelper\">The HTML helper instance that this method operates on.</param>\n        /// <param name=\"modelName\">The name of the model object being validated.</param>\n        /// <param name=\"validationMessage\">The message to display if the specified entry contains an error.</param>\n        /// <param name=\"htmlAttributes\">An <see cref=\"IDictionary{TKey,TValue}\"/> that contains the HTML attributes\n        /// for the element.</param>\n        /// <param name=\"tag\">The tag to be set for the wrapping HTML element of the validation message.</param>\n        /// <returns>null if the model object is valid and client-side validation is disabled.\n        /// Otherwise, a <paramref name=\"tag\"/> element that contains an error message.</returns>\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1719:ParameterNamesShouldNotMatchMemberNames\", Justification =\n            \"'validationMessage' refers to the message that will be rendered by the ValidationMessage helper.\")]\n        public static MvcHtmlString ValidationMessage(this HtmlHelper htmlHelper,\n                                                      string modelName,\n                                                      string validationMessage,\n                                                      IDictionary<string, object> htmlAttributes,\n                                                      string tag)\n        {\n            if (modelName == null)\n            {\n                throw new ArgumentNullException(\"modelName\");\n            }\n\n            return ValidationMessageHelper(htmlHelper,\n                                           ModelMetadata.FromStringExpression(modelName, htmlHelper.ViewContext.ViewData),\n                                           modelName,\n                                           validationMessage,\n                                           htmlAttributes,\n                                           tag);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString ValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)\n        {\n            return ValidationMessageFor(htmlHelper, expression, validationMessage: null, htmlAttributes: new RouteValueDictionary());\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString ValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string validationMessage)\n        {\n            return ValidationMessageFor(htmlHelper, expression, validationMessage, new RouteValueDictionary());\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString ValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string validationMessage, object htmlAttributes)\n        {\n            return ValidationMessageFor(htmlHelper, expression, validationMessage, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString ValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string validationMessage, IDictionary<string, object> htmlAttributes)\n        {\n            return ValidationMessageFor(htmlHelper,\n                                        expression,\n                                        validationMessage,\n                                        htmlAttributes,\n                                        tag: null);\n        }\n\n        /// <summary>\n        /// Returns the HTML markup for a validation-error message for the specified expression.\n        /// </summary>\n        /// <typeparam name=\"TModel\">The type of the model.</typeparam>\n        /// <typeparam name=\"TProperty\">The type of the property.</typeparam>\n        /// <param name=\"htmlHelper\">The HTML helper instance that this method operates on.</param>\n        /// <param name=\"expression\">An expression that identifies the object that contains the properties to render.\n        /// </param>\n        /// <param name=\"validationMessage\">The message to display if a validation error occurs.</param>\n        /// <param name=\"tag\">The tag to be set for the wrapping HTML element of the validation message.</param>\n        /// <returns>null if the model object is valid and client-side validation is disabled.\n        /// Otherwise, a <paramref name=\"tag\"/> element that contains an error message.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification =\n            \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString ValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,\n                                                                            Expression<Func<TModel, TProperty>> expression,\n                                                                            string validationMessage,\n                                                                            string tag)\n        {\n            return ValidationMessageFor(htmlHelper,\n                                        expression,\n                                        validationMessage,\n                                        htmlAttributes: null,\n                                        tag: tag);\n        }\n\n        /// <summary>\n        /// Returns the HTML markup for a validation-error message for the specified expression.\n        /// </summary>\n        /// <typeparam name=\"TModel\">The type of the model.</typeparam>\n        /// <typeparam name=\"TProperty\">The type of the property.</typeparam>\n        /// <param name=\"htmlHelper\">The HTML helper instance that this method operates on.</param>\n        /// <param name=\"expression\">An expression that identifies the object that contains the properties to render.\n        /// </param>\n        /// <param name=\"validationMessage\">The message to display if a validation error occurs.</param>\n        /// <param name=\"htmlAttributes\">An object that contains the HTML attributes for the element.</param>\n        /// <param name=\"tag\">The tag to be set for the wrapping HTML element of the validation message.</param>\n        /// <returns>null if the model object is valid and client-side validation is disabled.\n        /// Otherwise, a <paramref name=\"tag\"/> element that contains an error message.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification =\n            \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString ValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,\n                                                                            Expression<Func<TModel, TProperty>> expression,\n                                                                            string validationMessage,\n                                                                            object htmlAttributes,\n                                                                            string tag)\n        {\n            return ValidationMessageFor(htmlHelper,\n                                        expression,\n                                        validationMessage,\n                                        HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes),\n                                        tag);\n        }\n\n        /// <summary>\n        /// Returns the HTML markup for a validation-error message for the specified expression.\n        /// </summary>\n        /// <typeparam name=\"TModel\">The type of the model.</typeparam>\n        /// <typeparam name=\"TProperty\">The type of the property.</typeparam>\n        /// <param name=\"htmlHelper\">The HTML helper instance that this method operates on.</param>\n        /// <param name=\"expression\">An expression that identifies the object that contains the properties to render.\n        /// </param>\n        /// <param name=\"validationMessage\">The message to display if a validation error occurs.</param>\n        /// <param name=\"htmlAttributes\">An <see cref=\"IDictionary{TKey,TValue}\"/> that contains the HTML attributes\n        /// for the element.</param>\n        /// <param name=\"tag\">The tag to be set for the wrapping HTML element of the validation message.</param>\n        /// <returns>null if the model object is valid and client-side validation is disabled.\n        /// Otherwise, a <paramref name=\"tag\"/> element that contains an error message.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification =\n            \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString ValidationMessageFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,\n                                                                            Expression<Func<TModel, TProperty>> expression,\n                                                                            string validationMessage,\n                                                                            IDictionary<string, object> htmlAttributes,\n                                                                            string tag)\n        {\n            return ValidationMessageHelper(htmlHelper,\n                                           ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData),\n                                           ExpressionHelper.GetExpressionText(expression),\n                                           validationMessage,\n                                           htmlAttributes,\n                                           tag);\n        }\n\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1308:NormalizeStringsToUppercase\", Justification = \"Normalization to lowercase is a common requirement for JavaScript and HTML values\")]\n        private static MvcHtmlString ValidationMessageHelper(this HtmlHelper htmlHelper, ModelMetadata modelMetadata, string expression, string validationMessage, IDictionary<string, object> htmlAttributes, string tag)\n        {\n            string modelName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expression);\n            FormContext formContext = htmlHelper.ViewContext.GetFormContextForClientValidation();\n\n            if (!htmlHelper.ViewData.ModelState.ContainsKey(modelName) && formContext == null)\n            {\n                return null;\n            }\n\n            ModelState modelState = htmlHelper.ViewData.ModelState[modelName];\n            ModelErrorCollection modelErrors = (modelState == null) ? null : modelState.Errors;\n            ModelError modelError = (((modelErrors == null) || (modelErrors.Count == 0)) ? null : modelErrors.FirstOrDefault(m => !String.IsNullOrEmpty(m.ErrorMessage)) ?? modelErrors[0]);\n\n            if (modelError == null && formContext == null)\n            {\n                return null;\n            }\n\n            if (String.IsNullOrEmpty(tag))\n            {\n                tag = htmlHelper.ViewContext.ValidationMessageElement;\n            }\n\n            TagBuilder builder = new TagBuilder(tag);\n            builder.MergeAttributes(htmlAttributes);\n            builder.AddCssClass((modelError != null) ? HtmlHelper.ValidationMessageCssClassName : HtmlHelper.ValidationMessageValidCssClassName);\n\n            if (!String.IsNullOrEmpty(validationMessage))\n            {\n                builder.SetInnerText(validationMessage);\n            }\n            else if (modelError != null)\n            {\n                builder.SetInnerText(GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, modelError, modelState));\n            }\n\n            if (formContext != null)\n            {\n                bool replaceValidationMessageContents = String.IsNullOrEmpty(validationMessage);\n\n                if (htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled)\n                {\n                    builder.MergeAttribute(\"data-valmsg-for\", modelName);\n                    builder.MergeAttribute(\"data-valmsg-replace\", replaceValidationMessageContents.ToString().ToLowerInvariant());\n                }\n                else\n                {\n                    FieldValidationMetadata fieldMetadata = ApplyFieldValidationMetadata(htmlHelper, modelMetadata, modelName);\n                    // rules will already have been written to the metadata object\n                    fieldMetadata.ReplaceValidationMessageContents = replaceValidationMessageContents; // only replace contents if no explicit message was specified\n\n                    // client validation always requires an ID\n                    builder.GenerateId(modelName + \"_validationMessage\");\n                    fieldMetadata.ValidationMessageId = builder.Attributes[\"id\"];\n                }\n            }\n\n            return builder.ToMvcHtmlString(TagRenderMode.Normal);\n        }\n\n        // ValidationSummary\n\n        public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper)\n        {\n            return ValidationSummary(htmlHelper, excludePropertyErrors: false);\n        }\n\n        public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, bool excludePropertyErrors)\n        {\n            return ValidationSummary(htmlHelper, excludePropertyErrors, message: null);\n        }\n\n        public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, string message)\n        {\n            return ValidationSummary(htmlHelper, excludePropertyErrors: false, message: message, htmlAttributes: (object)null, headingTag: null);\n        }\n\n        public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, string message, string headingTag)\n        {\n            return ValidationSummary(htmlHelper, excludePropertyErrors: false, message: message, htmlAttributes: (object)null, headingTag: headingTag);\n        }\n\n        public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, bool excludePropertyErrors, string message)\n        {\n            return ValidationSummary(htmlHelper, excludePropertyErrors, message, htmlAttributes: (object)null, headingTag: null);\n        }\n\n        public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, bool excludePropertyErrors, string message, string headingTag)\n        {\n            return ValidationSummary(htmlHelper, excludePropertyErrors, message, htmlAttributes: (object)null, headingTag: headingTag);\n        }\n\n        public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, string message, object htmlAttributes)\n        {\n            return ValidationSummary(htmlHelper, excludePropertyErrors: false, message: message, htmlAttributes: HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes), headingTag: null);\n        }\n\n        public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, string message, object htmlAttributes, string headingTag)\n        {\n            return ValidationSummary(htmlHelper, excludePropertyErrors: false, message: message, htmlAttributes: HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes), headingTag: headingTag);\n        }\n\n        public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, bool excludePropertyErrors, string message, object htmlAttributes)\n        {\n            return ValidationSummary(htmlHelper, excludePropertyErrors, message, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes), null);\n        }\n\n        public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, bool excludePropertyErrors, string message, object htmlAttributes, string headingTag)\n        {\n            return ValidationSummary(htmlHelper, excludePropertyErrors, message, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes), headingTag);\n        }\n\n        public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, string message, IDictionary<string, object> htmlAttributes)\n        {\n            return ValidationSummary(htmlHelper, excludePropertyErrors: false, message: message, htmlAttributes: htmlAttributes, headingTag: null);\n        }\n\n        public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, string message, IDictionary<string, object> htmlAttributes, string headingTag)\n        {\n            return ValidationSummary(htmlHelper, excludePropertyErrors: false, message: message, htmlAttributes: htmlAttributes, headingTag: headingTag);\n        }\n\n        public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, bool excludePropertyErrors, string message, IDictionary<string, object> htmlAttributes)\n        {\n            return ValidationSummary(htmlHelper, excludePropertyErrors, message, htmlAttributes, null);\n        }\n\n        public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, bool excludePropertyErrors, string message, IDictionary<string, object> htmlAttributes, string headingTag)\n        {\n            if (htmlHelper == null)\n            {\n                throw new ArgumentNullException(\"htmlHelper\");\n            }\n\n            FormContext formContext = htmlHelper.ViewContext.GetFormContextForClientValidation();\n            if (htmlHelper.ViewData.ModelState.IsValid)\n            {\n                if (formContext == null)\n                {\n                    // No client side validation\n                    return null;\n                }\n                // TODO: This isn't really about unobtrusive; can we fix up non-unobtrusive to get rid of this, too?\n                if (htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled && excludePropertyErrors)\n                {\n                    // No client-side updates\n                    return null;\n                }\n            }\n\n            string messageSpan;\n            if (!String.IsNullOrEmpty(message))\n            {\n                if (String.IsNullOrEmpty(headingTag))\n                {\n                    headingTag = htmlHelper.ViewContext.ValidationSummaryMessageElement;\n                }\n\n                TagBuilder spanTag = new TagBuilder(headingTag);\n                spanTag.SetInnerText(message);\n                messageSpan = spanTag.ToString(TagRenderMode.Normal) + Environment.NewLine;\n            }\n            else\n            {\n                messageSpan = null;\n            }\n\n            StringBuilder htmlSummary = new StringBuilder();\n            TagBuilder unorderedList = new TagBuilder(\"ul\");\n\n            IEnumerable<ModelState> modelStates = GetModelStateList(htmlHelper, excludePropertyErrors);\n\n            foreach (ModelState modelState in modelStates)\n            {\n                foreach (ModelError modelError in modelState.Errors)\n                {\n                    string errorText = GetUserErrorMessageOrDefault(htmlHelper.ViewContext.HttpContext, modelError, null /* modelState */);\n                    if (!String.IsNullOrEmpty(errorText))\n                    {\n                        TagBuilder listItem = new TagBuilder(\"li\");\n                        listItem.SetInnerText(errorText);\n                        htmlSummary.AppendLine(listItem.ToString(TagRenderMode.Normal));\n                    }\n                }\n            }\n\n            if (htmlSummary.Length == 0)\n            {\n                htmlSummary.AppendLine(HiddenListItem);\n            }\n\n            unorderedList.InnerHtml = htmlSummary.ToString();\n\n            TagBuilder divBuilder = new TagBuilder(\"div\");\n            divBuilder.MergeAttributes(htmlAttributes);\n            divBuilder.AddCssClass((htmlHelper.ViewData.ModelState.IsValid) ? HtmlHelper.ValidationSummaryValidCssClassName : HtmlHelper.ValidationSummaryCssClassName);\n            divBuilder.InnerHtml = messageSpan + unorderedList.ToString(TagRenderMode.Normal);\n\n            if (formContext != null)\n            {\n                if (htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled)\n                {\n                    if (!excludePropertyErrors)\n                    {\n                        // Only put errors in the validation summary if they're supposed to be included there\n                        divBuilder.MergeAttribute(\"data-valmsg-summary\", \"true\");\n                    }\n                }\n                else\n                {\n                    // client val summaries need an ID\n                    divBuilder.GenerateId(\"validationSummary\");\n                    formContext.ValidationSummaryId = divBuilder.Attributes[\"id\"];\n                    formContext.ReplaceValidationSummary = !excludePropertyErrors;\n                }\n            }\n            return divBuilder.ToMvcHtmlString(TagRenderMode.Normal);\n        }\n\n        // Returns non-null list of model states, which caller will render in order provided.\n        private static IEnumerable<ModelState> GetModelStateList(HtmlHelper htmlHelper, bool excludePropertyErrors)\n        {\n            if (excludePropertyErrors)\n            {\n                ModelState ms;\n                htmlHelper.ViewData.ModelState.TryGetValue(htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix, out ms);\n                if (ms != null)\n                {\n                    return new ModelState[] { ms };\n                }\n\n                return new ModelState[0];\n            }\n            else\n            {\n                // Sort modelStates to respect the ordering in the metadata.                 \n                // ModelState doesn't refer to ModelMetadata, but we can correlate via the property name.\n                Dictionary<string, int> ordering = new Dictionary<string, int>();\n\n                var metadata = htmlHelper.ViewData.ModelMetadata;\n                if (metadata != null)\n                {\n                    foreach (ModelMetadata m in metadata.Properties)\n                    {\n                        ordering[m.PropertyName] = m.Order;\n                    }\n                }\n\n                return from kv in htmlHelper.ViewData.ModelState\n                       let name = kv.Key\n                       orderby ordering.GetOrDefault(name, ModelMetadata.DefaultOrder)\n                       select kv.Value;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Html/ValueExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq.Expressions;\n\nnamespace System.Web.Mvc.Html\n{\n    public static class ValueExtensions\n    {\n        public static MvcHtmlString Value(this HtmlHelper html, string name)\n        {\n            return Value(html, name, format: null);\n        }\n\n        public static MvcHtmlString Value(this HtmlHelper html, string name, string format)\n        {\n            if (name == null)\n            {\n                throw new ArgumentNullException(\"name\");\n            }\n\n            return ValueForHelper(html, name, value: null, format: format, useViewData: true);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString ValueFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression)\n        {\n            return ValueFor(html, expression, format: null);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static MvcHtmlString ValueFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, string format)\n        {\n            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);\n            return ValueForHelper(html, ExpressionHelper.GetExpressionText(expression), metadata.Model, format, useViewData: false);\n        }\n\n        public static MvcHtmlString ValueForModel(this HtmlHelper html)\n        {\n            return ValueForModel(html, format: null);\n        }\n\n        public static MvcHtmlString ValueForModel(this HtmlHelper html, string format)\n        {\n            return Value(html, String.Empty, format);\n        }\n\n        internal static MvcHtmlString ValueForHelper(HtmlHelper html, string name, object value, string format, bool useViewData)\n        {\n            string fullName = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);\n            string attemptedValue = (string)html.GetModelStateValue(fullName, typeof(string));\n            string resolvedValue;\n\n            if (attemptedValue != null)\n            {\n                // case 1: if ModelState has a value then it's already formatted so ignore format string\n                resolvedValue = attemptedValue;\n            }\n            else if (useViewData)\n            {\n                if (name.Length == 0)\n                {\n                    // case 2(a): format the value from ModelMetadata for the current model\n                    ModelMetadata metadata = ModelMetadata.FromStringExpression(String.Empty, html.ViewContext.ViewData);\n                    resolvedValue = html.FormatValue(metadata.Model, format);\n                }\n                else\n                {\n                    // case 2(b): format the value from ViewData\n                    resolvedValue = html.EvalString(name, format);\n                }\n            }\n            else\n            {\n                // case 3: format the explicit value from ModelMetadata\n                resolvedValue = html.FormatValue(value, format);\n            }\n\n            return MvcHtmlString.Create(html.AttributeEncode(resolvedValue));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Html5DateRenderingMode.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    /// <summary>\n    /// Controls the value-rendering method For HTML5 input elements of types such as date, time, datetime and datetime-local.\n    /// </summary>\n    public enum Html5DateRenderingMode\n    {\n        /// <summary>\n        /// Render date and time values according to the current culture's ToString behavior.\n        /// </summary>\n        CurrentCulture = 0,\n\n        /// <summary>\n        /// Render date and time values as Rfc3339 compliant strings to support HTML5 date and time types of input elements.\n        /// </summary>\n        Rfc3339,\n    }\n}"
  },
  {
    "path": "src/System.Web.Mvc/HtmlHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Web.Helpers;\nusing System.Web.Mvc.Html;\nusing System.Web.Mvc.Properties;\nusing System.Web.Routing;\nusing System.Web.WebPages;\nusing System.Web.WebPages.Scope;\n\nnamespace System.Web.Mvc\n{\n    public class HtmlHelper\n    {\n        public static readonly string ValidationInputCssClassName = \"input-validation-error\";\n        public static readonly string ValidationInputValidCssClassName = \"input-validation-valid\";\n        public static readonly string ValidationMessageCssClassName = \"field-validation-error\";\n        public static readonly string ValidationMessageValidCssClassName = \"field-validation-valid\";\n        public static readonly string ValidationSummaryCssClassName = \"validation-summary-errors\";\n        public static readonly string ValidationSummaryValidCssClassName = \"validation-summary-valid\";\n\n        private static readonly object _html5InputsModeKey = new object();\n\n        private DynamicViewDataDictionary _dynamicViewDataDictionary;\n\n        public HtmlHelper(ViewContext viewContext, IViewDataContainer viewDataContainer)\n            : this(viewContext, viewDataContainer, RouteTable.Routes)\n        {\n        }\n\n        public HtmlHelper(ViewContext viewContext, IViewDataContainer viewDataContainer, RouteCollection routeCollection)\n        {\n            if (viewContext == null)\n            {\n                throw new ArgumentNullException(\"viewContext\");\n            }\n            if (viewDataContainer == null)\n            {\n                throw new ArgumentNullException(\"viewDataContainer\");\n            }\n            if (routeCollection == null)\n            {\n                throw new ArgumentNullException(\"routeCollection\");\n            }\n\n            ViewContext = viewContext;\n            ViewDataContainer = viewDataContainer;\n            RouteCollection = routeCollection;\n            ClientValidationRuleFactory = (name, metadata) => ModelValidatorProviders.Providers.GetValidators(metadata ?? ModelMetadata.FromStringExpression(name, ViewData), ViewContext).SelectMany(v => v.GetClientValidationRules());\n        }\n\n        public static bool ClientValidationEnabled\n        {\n            get { return ViewContext.GetClientValidationEnabled(); }\n            set { ViewContext.SetClientValidationEnabled(value); }\n        }\n\n        public static string IdAttributeDotReplacement\n        {\n            get { return WebPages.Html.HtmlHelper.IdAttributeDotReplacement; }\n            set { WebPages.Html.HtmlHelper.IdAttributeDotReplacement = value; }\n        }\n\n        internal Func<string, ModelMetadata, IEnumerable<ModelClientValidationRule>> ClientValidationRuleFactory { get; set; }\n\n        public RouteCollection RouteCollection { get; private set; }\n\n        public static bool UnobtrusiveJavaScriptEnabled\n        {\n            get { return ViewContext.GetUnobtrusiveJavaScriptEnabled(); }\n            set { ViewContext.SetUnobtrusiveJavaScriptEnabled(value); }\n        }\n\n        /// <summary>\n        /// Element name used to wrap a top-level message in\n        /// <see cref=\"ValidationExtensions.ValidationSummary(HtmlHelper)\"/> and other overloads.\n        /// </summary>\n        public static string ValidationSummaryMessageElement\n        {\n            get { return ViewContext.GetValidationSummaryMessageElement(); }\n            set\n            {\n                if (String.IsNullOrEmpty(value))\n                {\n                    throw Error.ParameterCannotBeNullOrEmpty(\"value\");\n                }\n\n                ViewContext.SetValidationSummaryMessageElement(value);\n            }\n        }\n\n        /// <summary>\n        /// Element name used to wrap the validation message generated by\n        /// <see cref=\"ValidationExtensions.ValidationMessage(HtmlHelper, String)\"/> and other overloads.\n        /// </summary>\n        public static string ValidationMessageElement\n        {\n            get { return ViewContext.GetValidationMessageElement(); }\n            set\n            {\n                if (String.IsNullOrEmpty(value))\n                {\n                    throw Error.ParameterCannotBeNullOrEmpty(\"value\");\n                }\n\n                ViewContext.SetValidationMessageElement(value);\n            }\n        }\n\n        public dynamic ViewBag\n        {\n            get\n            {\n                if (_dynamicViewDataDictionary == null)\n                {\n                    _dynamicViewDataDictionary = new DynamicViewDataDictionary(() => ViewData);\n                }\n                return _dynamicViewDataDictionary;\n            }\n        }\n\n        public ViewContext ViewContext { get; private set; }\n\n        public ViewDataDictionary ViewData\n        {\n            get { return ViewDataContainer.ViewData; }\n        }\n\n        public IViewDataContainer ViewDataContainer { get; internal set; }\n\n        /// <summary>\n        /// Creates a dictionary of HTML attributes from the input object, \n        /// translating underscores to dashes.\n        /// </summary>\n        /// <example>\n        /// <c>new { data_name=\"value\" }</c> will translate to the entry <c>{ \"data-name\" , \"value\" }</c>\n        /// in the resulting dictionary.\n        /// </example>\n        /// <param name=\"htmlAttributes\">Anonymous object describing HTML attributes.</param>\n        /// <returns>A dictionary that represents HTML attributes.</returns>\n        public static RouteValueDictionary AnonymousObjectToHtmlAttributes(object htmlAttributes)\n        {\n            return System.Web.WebPages.Html.HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);\n        }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"For consistency, all helpers are instance methods.\")]\n        public MvcHtmlString AntiForgeryToken()\n        {\n            return new MvcHtmlString(AntiForgery.GetHtml().ToString());\n        }\n\n        /// <summary>\n        /// Set this property to <see cref=\"Mvc.Html5DateRenderingMode.Rfc3339\"/> to have templated helpers such as Html.EditorFor render date and time\n        /// values as Rfc3339 compliant strings.\n        /// </summary>\n        /// <remarks>\n        /// The scope of this setting is for the current view alone. Sub views and parent views\n        /// will default to <see cref=\"Mvc.Html5DateRenderingMode.CurrentCulture\"/> unless explicitly set otherwise.\n        /// </remarks>\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"The usage of the property is as an instance property of the helper.\")]\n        public Html5DateRenderingMode Html5DateRenderingMode\n        {\n            get\n            {\n                object value;\n                if (ScopeStorage.CurrentScope.TryGetValue(_html5InputsModeKey, out value))\n                {\n                    return (Html5DateRenderingMode)value;\n                }\n                return default(Html5DateRenderingMode);\n            }\n            set\n            {\n                ScopeStorage.CurrentScope[_html5InputsModeKey] = value;\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA2204:Literals should be spelled correctly\", MessageId = \"AdditionalDataProvider\", Justification = \"API name.\")]\n        [SuppressMessage(\"Microsoft.Naming\", \"CA2204:Literals should be spelled correctly\", MessageId = \"AntiForgeryConfig\", Justification = \"API name.\")]\n        [SuppressMessage(\"Microsoft.Naming\", \"CA2204:Literals should be spelled correctly\", MessageId = \"AntiForgeryToken\", Justification = \"API name.\")]\n        [SuppressMessage(\"Microsoft.Naming\", \"CA2204:Literals should be spelled correctly\", MessageId = \"httpCookies\", Justification = \"API name.\")]\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"Method is obsolete.\")]\n        [Obsolete(\"This method is deprecated. Use the AntiForgeryToken() method instead. To specify custom data to be embedded within the token, use the static AntiForgeryConfig.AdditionalDataProvider property.\", error: true)]\n        [EditorBrowsable(EditorBrowsableState.Never)]\n        public MvcHtmlString AntiForgeryToken(string salt)\n        {\n            if (!String.IsNullOrEmpty(salt))\n            {\n                throw new NotSupportedException(\"This method is deprecated. Use the AntiForgeryToken() method instead. To specify custom data to be embedded within the token, use the static AntiForgeryConfig.AdditionalDataProvider property.\");\n            }\n\n            return AntiForgeryToken();\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA2204:Literals should be spelled correctly\", MessageId = \"AdditionalDataProvider\", Justification = \"API name.\")]\n        [SuppressMessage(\"Microsoft.Naming\", \"CA2204:Literals should be spelled correctly\", MessageId = \"AntiForgeryConfig\", Justification = \"API name.\")]\n        [SuppressMessage(\"Microsoft.Naming\", \"CA2204:Literals should be spelled correctly\", MessageId = \"AntiForgeryToken\", Justification = \"API name.\")]\n        [SuppressMessage(\"Microsoft.Naming\", \"CA2204:Literals should be spelled correctly\", MessageId = \"httpCookies\", Justification = \"API name.\")]\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"Method is obsolete.\")]\n        [Obsolete(\"This method is deprecated. Use the AntiForgeryToken() method instead. To specify a custom domain for the generated cookie, use the <httpCookies> configuration element. To specify custom data to be embedded within the token, use the static AntiForgeryConfig.AdditionalDataProvider property.\", error: true)]\n        [EditorBrowsable(EditorBrowsableState.Never)]\n        public MvcHtmlString AntiForgeryToken(string salt, string domain, string path)\n        {\n            if (!String.IsNullOrEmpty(salt) || !String.IsNullOrEmpty(domain) || !String.IsNullOrEmpty(path))\n            {\n                throw new NotSupportedException(\"This method is deprecated. Use the AntiForgeryToken() method instead. To specify a custom domain for the generated cookie, use the <httpCookies> configuration element. To specify custom data to be embedded within the token, use the static AntiForgeryConfig.AdditionalDataProvider property.\");\n            }\n\n            return AntiForgeryToken();\n        }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"For consistency, all helpers are instance methods.\")]\n        public string AttributeEncode(string value)\n        {\n            return (!String.IsNullOrEmpty(value)) ? HttpUtility.HtmlAttributeEncode(value) : String.Empty;\n        }\n\n        public string AttributeEncode(object value)\n        {\n            return AttributeEncode(Convert.ToString(value, CultureInfo.InvariantCulture));\n        }\n\n        public void EnableClientValidation()\n        {\n            EnableClientValidation(enabled: true);\n        }\n\n        public void EnableClientValidation(bool enabled)\n        {\n            ViewContext.ClientValidationEnabled = enabled;\n        }\n\n        public void EnableUnobtrusiveJavaScript()\n        {\n            EnableUnobtrusiveJavaScript(enabled: true);\n        }\n\n        public void EnableUnobtrusiveJavaScript(bool enabled)\n        {\n            ViewContext.UnobtrusiveJavaScriptEnabled = enabled;\n        }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"For consistency, all helpers are instance methods.\")]\n        public string Encode(string value)\n        {\n            return (!String.IsNullOrEmpty(value)) ? HttpUtility.HtmlEncode(value) : String.Empty;\n        }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"For consistency, all helpers are instance methods.\")]\n        public string Encode(object value)\n        {\n            return value != null ? HttpUtility.HtmlEncode(value) : String.Empty;\n        }\n\n        internal string EvalString(string key)\n        {\n            return Convert.ToString(ViewData.Eval(key), CultureInfo.CurrentCulture);\n        }\n\n        internal string EvalString(string key, string format)\n        {\n            return Convert.ToString(ViewData.Eval(key, format), CultureInfo.CurrentCulture);\n        }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"For consistency, all helpers are instance methods.\")]\n        public string FormatValue(object value, string format)\n        {\n            return ViewDataDictionary.FormatValueInternal(value, format);\n        }\n\n        internal bool EvalBoolean(string key)\n        {\n            return Convert.ToBoolean(ViewData.Eval(key), CultureInfo.InvariantCulture);\n        }\n\n        internal static IView FindPartialView(ViewContext viewContext, string partialViewName, ViewEngineCollection viewEngineCollection)\n        {\n            ViewEngineResult result = viewEngineCollection.FindPartialView(viewContext, partialViewName);\n            if (result.View != null)\n            {\n                return result.View;\n            }\n\n            StringBuilder locationsText = new StringBuilder();\n            foreach (string location in result.SearchedLocations)\n            {\n                locationsText.AppendLine();\n                locationsText.Append(location);\n            }\n\n            throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,\n                                                              MvcResources.Common_PartialViewNotFound, partialViewName, locationsText));\n        }\n\n        public static string GenerateIdFromName(string name)\n        {\n            return GenerateIdFromName(name, IdAttributeDotReplacement);\n        }\n\n        public static string GenerateIdFromName(string name, string idAttributeDotReplacement)\n        {\n            if (name == null)\n            {\n                throw new ArgumentNullException(\"name\");\n            }\n\n            if (idAttributeDotReplacement == null)\n            {\n                throw new ArgumentNullException(\"idAttributeDotReplacement\");\n            }\n\n            // TagBuilder.CreateSanitizedId returns null for empty strings, return String.Empty instead to avoid breaking change\n            if (name.Length == 0)\n            {\n                return String.Empty;\n            }\n\n            return TagBuilder.CreateSanitizedId(name, idAttributeDotReplacement);\n        }\n\n        public static string GenerateLink(RequestContext requestContext, RouteCollection routeCollection, string linkText, string routeName, string actionName, string controllerName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes)\n        {\n            return GenerateLink(requestContext, routeCollection, linkText, routeName, actionName, controllerName, null /* protocol */, null /* hostName */, null /* fragment */, routeValues, htmlAttributes);\n        }\n\n        public static string GenerateLink(RequestContext requestContext, RouteCollection routeCollection, string linkText, string routeName, string actionName, string controllerName, string protocol, string hostName, string fragment, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes)\n        {\n            return GenerateLinkInternal(requestContext, routeCollection, linkText, routeName, actionName, controllerName, protocol, hostName, fragment, routeValues, htmlAttributes, true /* includeImplicitMvcValues */);\n        }\n\n        private static string GenerateLinkInternal(RequestContext requestContext, RouteCollection routeCollection, string linkText, string routeName, string actionName, string controllerName, string protocol, string hostName, string fragment, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes, bool includeImplicitMvcValues)\n        {\n            string url = UrlHelper.GenerateUrl(routeName, actionName, controllerName, protocol, hostName, fragment, routeValues, routeCollection, requestContext, includeImplicitMvcValues);\n            TagBuilder tagBuilder = new TagBuilder(\"a\")\n            {\n                InnerHtml = (!String.IsNullOrEmpty(linkText)) ? HttpUtility.HtmlEncode(linkText) : String.Empty\n            };\n            tagBuilder.MergeAttributes(htmlAttributes);\n            tagBuilder.MergeAttribute(\"href\", url);\n            return tagBuilder.ToString(TagRenderMode.Normal);\n        }\n\n        public static string GenerateRouteLink(RequestContext requestContext, RouteCollection routeCollection, string linkText, string routeName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes)\n        {\n            return GenerateRouteLink(requestContext, routeCollection, linkText, routeName, null /* protocol */, null /* hostName */, null /* fragment */, routeValues, htmlAttributes);\n        }\n\n        public static string GenerateRouteLink(RequestContext requestContext, RouteCollection routeCollection, string linkText, string routeName, string protocol, string hostName, string fragment, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes)\n        {\n            return GenerateLinkInternal(requestContext, routeCollection, linkText, routeName, null /* actionName */, null /* controllerName */, protocol, hostName, fragment, routeValues, htmlAttributes, false /* includeImplicitMvcValues */);\n        }\n\n        public static string GetFormMethodString(FormMethod method)\n        {\n            switch (method)\n            {\n                case FormMethod.Get:\n                    return \"get\";\n                case FormMethod.Post:\n                    return \"post\";\n                default:\n                    return \"post\";\n            }\n        }\n\n        public static string GetInputTypeString(InputType inputType)\n        {\n            switch (inputType)\n            {\n                case InputType.CheckBox:\n                    return \"checkbox\";\n                case InputType.Hidden:\n                    return \"hidden\";\n                case InputType.Password:\n                    return \"password\";\n                case InputType.Radio:\n                    return \"radio\";\n                case InputType.Text:\n                    return \"text\";\n                default:\n                    return \"text\";\n            }\n        }\n\n        internal object GetModelStateValue(string key, Type destinationType)\n        {\n            ModelState modelState;\n            if (ViewData.ModelState.TryGetValue(key, out modelState))\n            {\n                if (modelState.Value != null)\n                {\n                    return modelState.Value.ConvertTo(destinationType, null /* culture */);\n                }\n            }\n            return null;\n        }\n\n        public IDictionary<string, object> GetUnobtrusiveValidationAttributes(string name)\n        {\n            return GetUnobtrusiveValidationAttributes(name, metadata: null);\n        }\n\n        // Only render attributes if unobtrusive client-side validation is enabled, and then only if we've\n        // never rendered validation for a field with this name in this form. Also, if there's no form context,\n        // then we can't render the attributes (we'd have no <form> to attach them to).\n        public IDictionary<string, object> GetUnobtrusiveValidationAttributes(string name, ModelMetadata metadata)\n        {\n            Dictionary<string, object> results = new Dictionary<string, object>();\n\n            // The ordering of these 3 checks (and the early exits) is for performance reasons.\n            if (!ViewContext.UnobtrusiveJavaScriptEnabled)\n            {\n                return results;\n            }\n\n            FormContext formContext = ViewContext.GetFormContextForClientValidation();\n            if (formContext == null)\n            {\n                return results;\n            }\n\n            string fullName = ViewData.TemplateInfo.GetFullHtmlFieldName(name);\n            if (formContext.RenderedField(fullName))\n            {\n                return results;\n            }\n\n            formContext.RenderedField(fullName, true);\n\n            IEnumerable<ModelClientValidationRule> clientRules = ClientValidationRuleFactory(name, metadata);\n            UnobtrusiveValidationAttributesGenerator.GetValidationAttributes(clientRules, results);\n\n            return results;\n        }\n\n        public MvcHtmlString HttpMethodOverride(HttpVerbs httpVerb)\n        {\n            string httpMethod;\n            switch (httpVerb)\n            {\n                case HttpVerbs.Delete:\n                    httpMethod = \"DELETE\";\n                    break;\n                case HttpVerbs.Head:\n                    httpMethod = \"HEAD\";\n                    break;\n                case HttpVerbs.Put:\n                    httpMethod = \"PUT\";\n                    break;\n                case HttpVerbs.Patch:\n                    httpMethod = \"PATCH\";\n                    break;\n                case HttpVerbs.Options:\n                    httpMethod = \"OPTIONS\";\n                    break;\n                default:\n                    throw new ArgumentException(MvcResources.HtmlHelper_InvalidHttpVerb, \"httpVerb\");\n            }\n\n            return HttpMethodOverride(httpMethod);\n        }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"For consistency, all helpers are instance methods.\")]\n        public MvcHtmlString HttpMethodOverride(string httpMethod)\n        {\n            if (String.IsNullOrEmpty(httpMethod))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"httpMethod\");\n            }\n            if (String.Equals(httpMethod, \"GET\", StringComparison.OrdinalIgnoreCase) ||\n                String.Equals(httpMethod, \"POST\", StringComparison.OrdinalIgnoreCase))\n            {\n                throw new ArgumentException(MvcResources.HtmlHelper_InvalidHttpMethod, \"httpMethod\");\n            }\n\n            TagBuilder tagBuilder = new TagBuilder(\"input\");\n            tagBuilder.Attributes[\"type\"] = \"hidden\";\n            tagBuilder.Attributes[\"name\"] = HttpRequestExtensions.XHttpMethodOverrideKey;\n            tagBuilder.Attributes[\"value\"] = httpMethod;\n\n            return tagBuilder.ToMvcHtmlString(TagRenderMode.SelfClosing);\n        }\n\n        /// <summary>\n        /// Wraps HTML markup in an IHtmlString, which will enable HTML markup to be\n        /// rendered to the output without getting HTML encoded.\n        /// </summary>\n        /// <param name=\"value\">HTML markup string.</param>\n        /// <returns>An IHtmlString that represents HTML markup.</returns>\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"For consistency, all helpers are instance methods.\")]\n        public IHtmlString Raw(string value)\n        {\n            return new HtmlString(value);\n        }\n\n        /// <summary>\n        /// Wraps HTML markup from the string representation of an object in an IHtmlString,\n        /// which will enable HTML markup to be rendered to the output without getting HTML encoded.\n        /// </summary>\n        /// <param name=\"value\">object with string representation as HTML markup</param>\n        /// <returns>An IHtmlString that represents HTML markup.</returns>\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"For consistency, all helpers are instance methods.\")]\n        public IHtmlString Raw(object value)\n        {\n            return new HtmlString(value == null ? null : value.ToString());\n        }\n\n        internal virtual void RenderPartialInternal(string partialViewName, ViewDataDictionary viewData, object model, TextWriter writer, ViewEngineCollection viewEngineCollection)\n        {\n            if (String.IsNullOrEmpty(partialViewName))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"partialViewName\");\n            }\n\n            ViewDataDictionary newViewData = null;\n\n            if (model == null)\n            {\n                if (viewData == null)\n                {\n                    newViewData = new ViewDataDictionary(ViewData);\n                }\n                else\n                {\n                    newViewData = new ViewDataDictionary(viewData);\n                }\n            }\n            else\n            {\n                if (viewData == null)\n                {\n                    newViewData = new ViewDataDictionary(model);\n                }\n                else\n                {\n                    newViewData = new ViewDataDictionary(viewData) { Model = model };\n                }\n            }\n\n            ViewContext newViewContext = new ViewContext(ViewContext, ViewContext.View, newViewData, ViewContext.TempData, writer);\n            IView view = FindPartialView(newViewContext, partialViewName, viewEngineCollection);\n            view.Render(newViewContext, writer);\n        }\n\n        /// <summary>\n        /// Set element name used to wrap a top-level message in\n        /// <see cref=\"ValidationExtensions.ValidationSummary(HtmlHelper)\"/> and other overloads.\n        /// </summary>\n        public void SetValidationSummaryMessageElement(string elementName)\n        {\n            if (String.IsNullOrEmpty(elementName))\n            {\n                throw Error.ParameterCannotBeNullOrEmpty(\"elementName\");\n            }\n\n            ViewContext.ValidationSummaryMessageElement = elementName;\n        }\n\n        /// <summary>\n        /// Set element name used to wrap the validation message generated by\n        /// <see cref=\"ValidationExtensions.ValidationMessage(HtmlHelper, String)\"/> and other overloads.\n        /// </summary>\n        public void SetValidationMessageElement(string elementName)\n        {\n            if (String.IsNullOrEmpty(elementName))\n            {\n                throw Error.ParameterCannotBeNullOrEmpty(\"elementName\");\n            }\n\n            ViewContext.ValidationMessageElement = elementName;\n        }\n\n        /// <summary>\n        /// Creates a dictionary from an object, by adding each public instance property as a key with its associated \n        /// value to the dictionary. It will expose public properties from derived types as well. This is typically used\n        /// with objects of an anonymous type.\n        /// </summary>\n        /// <example>\n        /// <c>new { property_name = \"value\" }</c> will translate to the entry <c>{ \"property_name\" , \"value\" }</c>\n        /// in the resulting dictionary.\n        /// </example>\n        /// <param name=\"value\">The object to be converted.</param>\n        /// <returns>The created dictionary of property names and property values.</returns>\n        public static IDictionary<string, object> ObjectToDictionary(object value)\n        {\n            return TypeHelper.ObjectToDictionary(value);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/HtmlHelperOfTModel.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Routing;\n\nnamespace System.Web.Mvc\n{\n    public class HtmlHelper<TModel> : HtmlHelper\n    {\n        private DynamicViewDataDictionary _dynamicViewDataDictionary;\n        private ViewDataDictionary<TModel> _viewData;\n\n        public HtmlHelper(ViewContext viewContext, IViewDataContainer viewDataContainer)\n            : this(viewContext, viewDataContainer, RouteTable.Routes)\n        {\n        }\n\n        public HtmlHelper(ViewContext viewContext, IViewDataContainer viewDataContainer, RouteCollection routeCollection)\n            : base(viewContext, viewDataContainer, routeCollection)\n        {\n            _viewData = new ViewDataDictionary<TModel>(viewDataContainer.ViewData);\n        }\n\n        public new dynamic ViewBag\n        {\n            get\n            {\n                if (_dynamicViewDataDictionary == null)\n                {\n                    _dynamicViewDataDictionary = new DynamicViewDataDictionary(() => ViewData);\n                }\n\n                return _dynamicViewDataDictionary;\n            }\n        }\n\n        public new ViewDataDictionary<TModel> ViewData\n        {\n            get { return _viewData; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/HttpDeleteAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\n\nnamespace System.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\n    public sealed class HttpDeleteAttribute : ActionMethodSelectorAttribute\n    {\n        private static readonly AcceptVerbsAttribute _innerAttribute = new AcceptVerbsAttribute(HttpVerbs.Delete);\n\n        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)\n        {\n            return _innerAttribute.IsValidForRequest(controllerContext, methodInfo);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/HttpFileCollectionValueProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\n\nnamespace System.Web.Mvc\n{\n    public sealed class HttpFileCollectionValueProvider : DictionaryValueProvider<HttpPostedFileBase[]>\n    {\n        private static readonly Dictionary<string, HttpPostedFileBase[]> _emptyDictionary = new Dictionary<string, HttpPostedFileBase[]>();\n\n        public HttpFileCollectionValueProvider(ControllerContext controllerContext)\n            : base(GetHttpPostedFileDictionary(controllerContext), CultureInfo.InvariantCulture)\n        {\n        }\n\n        private static Dictionary<string, HttpPostedFileBase[]> GetHttpPostedFileDictionary(ControllerContext controllerContext)\n        {\n            HttpFileCollectionBase files = controllerContext.HttpContext.Request.Files;\n\n            // fast-track common case of no files\n            if (files.Count == 0)\n            {\n                return _emptyDictionary;\n            }\n\n            // build up the 1:many file mapping\n            List<KeyValuePair<string, HttpPostedFileBase>> mapping = new List<KeyValuePair<string, HttpPostedFileBase>>();\n            string[] allKeys = files.AllKeys;\n            for (int i = 0; i < files.Count; i++)\n            {\n                string key = allKeys[i];\n                if (key != null)\n                {\n                    HttpPostedFileBase file = HttpPostedFileBaseModelBinder.ChooseFileOrNull(files[i]);\n                    mapping.Add(new KeyValuePair<string, HttpPostedFileBase>(key, file));\n                }\n            }\n\n            // turn the mapping into a 1:many dictionary\n            var grouped = mapping.GroupBy(el => el.Key, el => el.Value, StringComparer.OrdinalIgnoreCase);\n            return grouped.ToDictionary(g => g.Key, g => g.ToArray(), StringComparer.OrdinalIgnoreCase);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/HttpFileCollectionValueProviderFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public sealed class HttpFileCollectionValueProviderFactory : ValueProviderFactory\n    {\n        public override IValueProvider GetValueProvider(ControllerContext controllerContext)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n\n            return new HttpFileCollectionValueProvider(controllerContext);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/HttpGetAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\n\nnamespace System.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\n    public sealed class HttpGetAttribute : ActionMethodSelectorAttribute\n    {\n        private static readonly AcceptVerbsAttribute _innerAttribute = new AcceptVerbsAttribute(HttpVerbs.Get);\n\n        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)\n        {\n            return _innerAttribute.IsValidForRequest(controllerContext, methodInfo);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/HttpHandlerUtil.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Mvc.Properties;\nusing System.Web.UI;\n\nnamespace System.Web.Mvc\n{\n    internal static class HttpHandlerUtil\n    {\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"The Dispose on Page doesn't do anything by default, and we control both of these internal types.\")]\n        public static IHttpHandler WrapForServerExecute(IHttpHandler httpHandler)\n        {\n            // Since Server.Execute() doesn't propagate HttpExceptions where the status code is\n            // anything other than 500, we need to wrap these exceptions ourselves.\n            IHttpAsyncHandler asyncHandler = httpHandler as IHttpAsyncHandler;\n            return (asyncHandler != null) ? new ServerExecuteHttpHandlerAsyncWrapper(asyncHandler) : new ServerExecuteHttpHandlerWrapper(httpHandler);\n        }\n\n        private sealed class ServerExecuteHttpHandlerAsyncWrapper : ServerExecuteHttpHandlerWrapper, IHttpAsyncHandler\n        {\n            private readonly IHttpAsyncHandler _httpHandler;\n\n            public ServerExecuteHttpHandlerAsyncWrapper(IHttpAsyncHandler httpHandler)\n                : base(httpHandler)\n            {\n                _httpHandler = httpHandler;\n            }\n\n            public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)\n            {\n                return Wrap(() => _httpHandler.BeginProcessRequest(context, cb, extraData));\n            }\n\n            public void EndProcessRequest(IAsyncResult result)\n            {\n                Wrap(() => _httpHandler.EndProcessRequest(result));\n            }\n        }\n\n        /// <remarks>\n        /// Server.Execute() requires that the provided IHttpHandler subclass Page.\n        /// </remarks>\n        internal class ServerExecuteHttpHandlerWrapper : Page\n        {\n            private readonly IHttpHandler _httpHandler;\n\n            public ServerExecuteHttpHandlerWrapper(IHttpHandler httpHandler)\n            {\n                _httpHandler = httpHandler;\n            }\n\n            internal IHttpHandler InnerHandler\n            {\n                get { return _httpHandler; }\n            }\n\n            public override void ProcessRequest(HttpContext context)\n            {\n                Wrap(() => _httpHandler.ProcessRequest(context));\n            }\n\n            protected static void Wrap(Action action)\n            {\n                Wrap(delegate\n                {\n                    action();\n                    return (object)null;\n                });\n            }\n\n            protected static TResult Wrap<TResult>(Func<TResult> func)\n            {\n                try\n                {\n                    return func();\n                }\n                catch (HttpException he)\n                {\n                    if (he.GetHttpCode() == 500)\n                    {\n                        throw; // doesn't need to be wrapped\n                    }\n                    else\n                    {\n                        HttpException newHe = new HttpException(500, MvcResources.ViewPageHttpHandlerWrapper_ExceptionOccurred, he);\n                        throw newHe;\n                    }\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/HttpHeadAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\n\nnamespace System.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\n    public sealed class HttpHeadAttribute : ActionMethodSelectorAttribute\n    {\n        private static readonly AcceptVerbsAttribute _innerAttribute = new AcceptVerbsAttribute(HttpVerbs.Head);\n\n        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)\n        {\n            return _innerAttribute.IsValidForRequest(controllerContext, methodInfo);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/HttpNotFoundResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\n\nnamespace System.Web.Mvc\n{\n    public class HttpNotFoundResult : HttpStatusCodeResult\n    {\n        public HttpNotFoundResult()\n            : this(null)\n        {\n        }\n\n        // NotFound is equivalent to HTTP status 404.\n        public HttpNotFoundResult(string statusDescription)\n            : base(HttpStatusCode.NotFound, statusDescription)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/HttpOptionsAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\n\nnamespace System.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\n    public sealed class HttpOptionsAttribute : ActionMethodSelectorAttribute\n    {\n        private static readonly AcceptVerbsAttribute _innerAttribute = new AcceptVerbsAttribute(HttpVerbs.Options);\n\n        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)\n        {\n            return _innerAttribute.IsValidForRequest(controllerContext, methodInfo);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/HttpPatchAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\n\nnamespace System.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\n    public sealed class HttpPatchAttribute : ActionMethodSelectorAttribute\n    {\n        private static readonly AcceptVerbsAttribute _innerAttribute = new AcceptVerbsAttribute(HttpVerbs.Patch);\n\n        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)\n        {\n            return _innerAttribute.IsValidForRequest(controllerContext, methodInfo);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/HttpPostAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\n\nnamespace System.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\n    public sealed class HttpPostAttribute : ActionMethodSelectorAttribute\n    {\n        private static readonly AcceptVerbsAttribute _innerAttribute = new AcceptVerbsAttribute(HttpVerbs.Post);\n\n        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)\n        {\n            return _innerAttribute.IsValidForRequest(controllerContext, methodInfo);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/HttpPostedFileBaseModelBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public class HttpPostedFileBaseModelBinder : IModelBinder\n    {\n        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n            if (bindingContext == null)\n            {\n                throw new ArgumentNullException(\"bindingContext\");\n            }\n\n            HttpPostedFileBase theFile = controllerContext.HttpContext.Request.Files[bindingContext.ModelName];\n            return ChooseFileOrNull(theFile);\n        }\n\n        // helper that returns the original file if there was content uploaded, null if empty\n        internal static HttpPostedFileBase ChooseFileOrNull(HttpPostedFileBase rawFile)\n        {\n            // case 1: there was no <input type=\"file\" ... /> element in the post\n            if (rawFile == null)\n            {\n                return null;\n            }\n\n            // case 2: there was an <input type=\"file\" ... /> element in the post, but it was left blank\n            if (rawFile.ContentLength == 0 && String.IsNullOrEmpty(rawFile.FileName))\n            {\n                return null;\n            }\n\n            // case 3: the file was posted\n            return rawFile;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/HttpPutAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\n\nnamespace System.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\n    public sealed class HttpPutAttribute : ActionMethodSelectorAttribute\n    {\n        private static readonly AcceptVerbsAttribute _innerAttribute = new AcceptVerbsAttribute(HttpVerbs.Put);\n\n        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)\n        {\n            return _innerAttribute.IsValidForRequest(controllerContext, methodInfo);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/HttpRequestExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public static class HttpRequestExtensions\n    {\n        internal const string XHttpMethodOverrideKey = \"X-HTTP-Method-Override\";\n\n        public static string GetHttpMethodOverride(this HttpRequestBase request)\n        {\n            if (request == null)\n            {\n                throw new ArgumentNullException(\"request\");\n            }\n\n            string incomingVerb = request.HttpMethod;\n\n            if (!String.Equals(incomingVerb, \"POST\", StringComparison.OrdinalIgnoreCase))\n            {\n                return incomingVerb;\n            }\n\n            string verbOverride = null;\n            string headerOverrideValue = request.Headers[XHttpMethodOverrideKey];\n            if (!String.IsNullOrEmpty(headerOverrideValue))\n            {\n                verbOverride = headerOverrideValue;\n            }\n            else\n            {\n                string formOverrideValue = request.Form[XHttpMethodOverrideKey];\n                if (!String.IsNullOrEmpty(formOverrideValue))\n                {\n                    verbOverride = formOverrideValue;\n                }\n                else\n                {\n                    string queryStringOverrideValue = request.QueryString[XHttpMethodOverrideKey];\n                    if (!String.IsNullOrEmpty(queryStringOverrideValue))\n                    {\n                        verbOverride = queryStringOverrideValue;\n                    }\n                }\n            }\n            if (verbOverride != null)\n            {\n                if (!String.Equals(verbOverride, \"GET\", StringComparison.OrdinalIgnoreCase) &&\n                    !String.Equals(verbOverride, \"POST\", StringComparison.OrdinalIgnoreCase))\n                {\n                    incomingVerb = verbOverride;\n                }\n            }\n            return incomingVerb;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/HttpStatusCodeResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\n\nnamespace System.Web.Mvc\n{\n    public class HttpStatusCodeResult : ActionResult\n    {\n        public HttpStatusCodeResult(int statusCode)\n            : this(statusCode, null)\n        {\n        }\n\n        public HttpStatusCodeResult(HttpStatusCode statusCode)\n            : this(statusCode, null)\n        {\n        }\n\n        public HttpStatusCodeResult(HttpStatusCode statusCode, string statusDescription)\n            : this((int)statusCode, statusDescription)\n        {\n        }\n\n        public HttpStatusCodeResult(int statusCode, string statusDescription)\n        {\n            StatusCode = statusCode;\n            StatusDescription = statusDescription;\n        }\n\n        public int StatusCode { get; private set; }\n\n        public string StatusDescription { get; private set; }\n\n        public override void ExecuteResult(ControllerContext context)\n        {\n            if (context == null)\n            {\n                throw new ArgumentNullException(\"context\");\n            }\n\n            context.HttpContext.Response.StatusCode = StatusCode;\n            if (StatusDescription != null)\n            {\n                context.HttpContext.Response.StatusDescription = StatusDescription;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/HttpUnauthorizedResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\n\nnamespace System.Web.Mvc\n{\n    public class HttpUnauthorizedResult : HttpStatusCodeResult\n    {\n        public HttpUnauthorizedResult()\n            : this(null)\n        {\n        }\n\n        // Unauthorized is equivalent to HTTP status 401, the status code for unauthorized\n        // access. Other code might intercept this and perform some special logic. For\n        // example, the FormsAuthenticationModule looks for 401 responses and instead\n        // redirects the user to the login page.\n        public HttpUnauthorizedResult(string statusDescription)\n            : base(HttpStatusCode.Unauthorized, statusDescription)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/HttpVerbs.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    [Flags]\n    public enum HttpVerbs\n    {\n        Get = 1 << 0,\n        Post = 1 << 1,\n        Put = 1 << 2,\n        Delete = 1 << 3,\n        Head = 1 << 4,\n        Patch = 1 << 5,\n        Options = 1 << 6,\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IActionFilter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public interface IActionFilter\n    {\n        void OnActionExecuting(ActionExecutingContext filterContext);\n        void OnActionExecuted(ActionExecutedContext filterContext);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IActionInvoker.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public interface IActionInvoker\n    {\n        bool InvokeAction(ControllerContext controllerContext, string actionName);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IActionInvokerFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    /// <summary>\n    /// Used to create an <see cref=\"IActionInvoker\"/> instance for the current request.\n    /// </summary>\n    public interface IActionInvokerFactory\n    {\n        /// <summary>\n        /// Creates an instance of action invoker for the current request.\n        /// </summary>\n        /// <returns>The created <see cref=\"IActionInvoker\"/>.</returns>\n        IActionInvoker CreateInstance();\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IAuthorizationFilter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public interface IAuthorizationFilter\n    {\n        void OnAuthorization(AuthorizationContext filterContext);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IBuildManager.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.IO;\n\nnamespace System.Web.Mvc\n{\n    internal interface IBuildManager\n    {\n        bool FileExists(string virtualPath);\n        Type GetCompiledType(string virtualPath);\n        ICollection GetReferencedAssemblies();\n        Stream ReadCachedFile(string fileName);\n        Stream CreateCachedFile(string fileName);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IClientValidatable.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Mvc\n{\n    // The purpose of this interface is to make something as supporting client-side\n    // validation, which could be discovered at runtime by whatever validation\n    // framework you're using. Because this interface is designed to be independent\n    // of underlying implementation details, where you apply this interface will\n    // depend on your specific validation framework.\n    //\n    // For DataAnnotations, you'll apply this interface to your validation attribute\n    // (the class which derives from ValidationAttribute). When you've implemented\n    // this interface, it will alleviate the need of writing a validator and registering\n    // it with the DataAnnotationsModelValidatorProvider.\n    public interface IClientValidatable\n    {\n        IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Routing;\n\nnamespace System.Web.Mvc\n{\n    public interface IController\n    {\n        void Execute(RequestContext requestContext);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IControllerActivator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Routing;\n\nnamespace System.Web.Mvc\n{\n    public interface IControllerActivator\n    {\n        IController Create(RequestContext requestContext, Type controllerType);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IControllerFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Routing;\nusing System.Web.SessionState;\n\nnamespace System.Web.Mvc\n{\n    public interface IControllerFactory\n    {\n        IController CreateController(RequestContext requestContext, string controllerName);\n        SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName);\n        void ReleaseController(IController controller);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IDependencyResolver.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Mvc\n{\n    public interface IDependencyResolver\n    {\n        object GetService(Type serviceType);\n        IEnumerable<object> GetServices(Type serviceType);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IEnumerableValueProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Mvc\n{\n    // Represents a special IValueProvider that has the ability to be enumerable.\n    public interface IEnumerableValueProvider : IValueProvider\n    {\n        IDictionary<string, string> GetKeysFromPrefix(string prefix);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IExceptionFilter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public interface IExceptionFilter\n    {\n        void OnException(ExceptionContext filterContext);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IFilterProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Mvc\n{\n    public interface IFilterProvider\n    {\n        IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IMetadataAware.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    // This interface is implemented by attributes which wish to contribute to the\n    // ModelMetadata creation process without needing to write a custom metadata\n    // provider. It is consumed by AssociatedMetadataProvider, so this behavior is\n    // automatically inherited by all classes which derive from it (notably, the\n    // DataAnnotationsModelMetadataProvider).\n    public interface IMetadataAware\n    {\n        void OnMetadataCreated(ModelMetadata metadata);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IMethodInfoActionDescriptor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\n\nnamespace System.Web.Mvc\n{\n    /// <summary>\n    /// An optional interface for <see cref=\"ActionDescriptor\" /> types which provide a <see cref=\"MethodInfo\" />.\n    /// </summary>\n    public interface IMethodInfoActionDescriptor\n    {\n        /// <summary>\n        /// Gets the MethodInfo\n        /// </summary>\n        MethodInfo MethodInfo\n        {\n            get;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IModelBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public interface IModelBinder\n    {\n        object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IModelBinderProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public interface IModelBinderProvider\n    {\n        IModelBinder GetBinder(Type modelType);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IMvcControlBuilder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    internal interface IMvcControlBuilder\n    {\n        string Inherits { set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IMvcFilter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public interface IMvcFilter\n    {\n        bool AllowMultiple { get; }\n        int Order { get; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IResolver.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    internal interface IResolver<T>\n    {\n        T Current { get; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IResultFilter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public interface IResultFilter\n    {\n        void OnResultExecuting(ResultExecutingContext filterContext);\n        void OnResultExecuted(ResultExecutedContext filterContext);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IRouteWithArea.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public interface IRouteWithArea\n    {\n        string Area { get; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ITempDataProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Mvc\n{\n    public interface ITempDataProvider\n    {\n        IDictionary<string, object> LoadTempData(ControllerContext controllerContext);\n        void SaveTempData(ControllerContext controllerContext, IDictionary<string, object> values);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ITempDataProviderFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    /// <summary>\n    /// Used to create an <see cref=\"ITempDataProvider\"/> instance for the controller.\n    /// </summary>\n    public interface ITempDataProviderFactory\n    {\n        /// <summary>\n        /// Creates an instance of <see cref=\"ITempDataProvider\"/> for the controller.\n        /// </summary>\n        /// <returns>The created <see cref=\"ITempDataProvider\"/>.</returns>\n        ITempDataProvider CreateInstance();\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IUniquelyIdentifiable.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    internal interface IUniquelyIdentifiable\n    {\n        string UniqueId { get; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IUnvalidatedRequestValues.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\n\nnamespace System.Web.Mvc\n{\n    // Used for mocking the UnvalidatedRequestValues type in System.Web.WebPages\n\n    internal interface IUnvalidatedRequestValues\n    {\n        NameValueCollection Form { get; }\n        NameValueCollection QueryString { get; }\n        string this[string key] { get; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IUnvalidatedValueProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    // Represents a special IValueProvider that has the ability to skip request validation.\n    public interface IUnvalidatedValueProvider : IValueProvider\n    {\n        ValueProviderResult GetValue(string key, bool skipValidation);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IValueProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    /// <summary>\n    /// Defines the methods that are required for a value provider in ASP.NET MVC.\n    /// </summary>\n    public interface IValueProvider\n    {\n        /// <summary>\n        /// Determines whether the collection contains the specified prefix.\n        /// </summary>\n        /// <param name=\"prefix\">The prefix to search for.</param>\n        /// <returns>true if the collection contains the specified prefix; otherwise, false.</returns>\n        bool ContainsPrefix(string prefix);\n\n        /// <summary>\n        /// Retrieves a value object using the specified key.\n        /// </summary>\n        /// <param name=\"key\">The key of the value object to retrieve.</param>\n        /// <returns>The value object for the specified key. If the exact key is not found, null.</returns>\n        ValueProviderResult GetValue(string key);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IView.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\n\nnamespace System.Web.Mvc\n{\n    public interface IView\n    {\n        void Render(ViewContext viewContext, TextWriter writer);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IViewDataContainer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.Mvc\n{\n    public interface IViewDataContainer\n    {\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"This is the mechanism by which the ViewPage / ViewUserControl get their ViewDataDictionary objects.\")]\n        ViewDataDictionary ViewData { get; set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IViewEngine.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public interface IViewEngine\n    {\n        ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache);\n        ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache);\n        void ReleaseView(ControllerContext controllerContext, IView view);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IViewLocationCache.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public interface IViewLocationCache\n    {\n        string GetViewLocation(HttpContextBase httpContext, string key);\n        void InsertViewLocation(HttpContextBase httpContext, string key, string virtualPath);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IViewPageActivator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public interface IViewPageActivator\n    {\n        object Create(ControllerContext controllerContext, Type type);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/IViewStartPageChild.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    internal interface IViewStartPageChild\n    {\n        HtmlHelper<object> Html { get; }\n        UrlHelper Url { get; }\n        ViewContext ViewContext { get; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/InputType.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public enum InputType\n    {\n        CheckBox,\n        Hidden,\n        Password,\n        Radio,\n        Text\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/JQueryFormValueProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\n\nnamespace System.Web.Mvc\n{\n    /// <summary>\n    /// The JQuery Form Value provider is used to handle JQuery formatted data in\n    /// request Forms.\n    /// </summary>\n    public class JQueryFormValueProvider : NameValueCollectionValueProvider\n    {\n        /// <summary>\n        /// Constructs a new instance of the JQuery form ValueProvider\n        /// </summary>\n        /// <param name=\"controllerContext\">The context on which the ValueProvider operates.</param>\n        public JQueryFormValueProvider(\n                    ControllerContext controllerContext)\n                : this(controllerContext,\n                        new UnvalidatedRequestValuesWrapper(\n                                controllerContext.HttpContext.Request.Unvalidated))\n        {\n        }\n\n        // For unit testing\n        internal JQueryFormValueProvider(\n                        ControllerContext controllerContext,\n                        IUnvalidatedRequestValues unvalidatedValues)\n            : base(controllerContext.HttpContext.Request.Form, \n                        unvalidatedValues.Form,\n                        CultureInfo.CurrentCulture,\n                        jQueryToMvcRequestNormalizationRequired: true)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/JQueryFormValueProviderFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    /// <summary>\n    /// Provides the necessary ValueProvider to handle JQuery Form data.\n    /// </summary>\n    public sealed class JQueryFormValueProviderFactory : ValueProviderFactory\n    {\n        private readonly UnvalidatedRequestValuesAccessor _unvalidatedValuesAccessor;\n\n        /// <summary>\n        /// Constructs a new instance of the factory which provides JQuery form ValueProviders.\n        /// </summary>\n        public JQueryFormValueProviderFactory()\n            : this(unvalidatedValuesAccessor: null)\n        {\n        }\n\n        // For unit testing\n        internal JQueryFormValueProviderFactory(UnvalidatedRequestValuesAccessor unvalidatedValuesAccessor)\n        {\n            _unvalidatedValuesAccessor = unvalidatedValuesAccessor ??\n                                       (cc => new UnvalidatedRequestValuesWrapper(cc.HttpContext.Request.Unvalidated));\n        }\n\n        /// <summary>\n        /// Returns the suitable ValueProvider.\n        /// </summary>\n        /// <param name=\"controllerContext\">The context on which the ValueProvider should operate.</param>\n        /// <returns></returns>\n        public override IValueProvider GetValueProvider(ControllerContext controllerContext)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n\n            return new JQueryFormValueProvider(controllerContext, _unvalidatedValuesAccessor(controllerContext));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/JavaScript/jquery.unobtrusive-ajax.js",
    "content": "/*!\n** Unobtrusive Ajax support library for jQuery\n** Copyright (C) Microsoft Corporation. All rights reserved.\n*/\n\n/*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: false */\n/*global window: false, jQuery: false */\n\n(function ($) {\n    var data_click = \"unobtrusiveAjaxClick\",\n        data_target = \"unobtrusiveAjaxClickTarget\",\n        data_validation = \"unobtrusiveValidation\";\n\n    function getFunction(code, argNames) {\n        var fn = window, parts = (code || \"\").split(\".\");\n        while (fn && parts.length) {\n            fn = fn[parts.shift()];\n        }\n        if (typeof (fn) === \"function\") {\n            return fn;\n        }\n        argNames.push(code);\n        return Function.constructor.apply(null, argNames);\n    }\n\n    function isMethodProxySafe(method) {\n        return method === \"GET\" || method === \"POST\";\n    }\n\n    function asyncOnBeforeSend(xhr, method) {\n        if (!isMethodProxySafe(method)) {\n            xhr.setRequestHeader(\"X-HTTP-Method-Override\", method);\n        }\n    }\n\n    function asyncOnSuccess(element, data, contentType) {\n        var mode;\n\n        if (contentType.indexOf(\"application/x-javascript\") !== -1) {  // jQuery already executes JavaScript for us\n            return;\n        }\n\n        mode = (element.getAttribute(\"data-ajax-mode\") || \"\").toUpperCase();\n        $(element.getAttribute(\"data-ajax-update\")).each(function (i, update) {\n            switch (mode) {\n            case \"BEFORE\":\n                $(update).prepend(data);\n                break;\n            case \"AFTER\":\n                $(update).append(data);\n                break;\n            case \"REPLACE-WITH\":\n                $(update).replaceWith(data);\n                break;\n            default:\n                $(update).html(data);\n                break;\n            }\n        });\n    }\n\n    function asyncRequest(element, options) {\n        var confirm, loading, method, duration;\n\n        confirm = element.getAttribute(\"data-ajax-confirm\");\n        if (confirm && !window.confirm(confirm)) {\n            return;\n        }\n\n        loading = $(element.getAttribute(\"data-ajax-loading\"));\n        duration = parseInt(element.getAttribute(\"data-ajax-loading-duration\"), 10) || 0;\n\n        $.extend(options, {\n            type: element.getAttribute(\"data-ajax-method\") || undefined,\n            url: element.getAttribute(\"data-ajax-url\") || undefined,\n            cache: !!element.getAttribute(\"data-ajax-cache\"),\n            beforeSend: function (xhr) {\n                var result;\n                asyncOnBeforeSend(xhr, method);\n                result = getFunction(element.getAttribute(\"data-ajax-begin\"), [\"xhr\"]).apply(element, arguments);\n                if (result !== false) {\n                    loading.show(duration);\n                }\n                return result;\n            },\n            complete: function () {\n                loading.hide(duration);\n                getFunction(element.getAttribute(\"data-ajax-complete\"), [\"xhr\", \"status\"]).apply(element, arguments);\n            },\n            success: function (data, status, xhr) {\n                asyncOnSuccess(element, data, xhr.getResponseHeader(\"Content-Type\") || \"text/html\");\n                getFunction(element.getAttribute(\"data-ajax-success\"), [\"data\", \"status\", \"xhr\"]).apply(element, arguments);\n            },\n            error: function () {\n                getFunction(element.getAttribute(\"data-ajax-failure\"), [\"xhr\", \"status\", \"error\"]).apply(element, arguments);\n            }\n        });\n\n        options.data.push({ name: \"X-Requested-With\", value: \"XMLHttpRequest\" });\n\n        method = options.type.toUpperCase();\n        if (!isMethodProxySafe(method)) {\n            options.type = \"POST\";\n            options.data.push({ name: \"X-HTTP-Method-Override\", value: method });\n        }\n\n        $.ajax(options);\n    }\n\n    function validate(form) {\n        var validationInfo = $(form).data(data_validation);\n        return !validationInfo || !validationInfo.validate || validationInfo.validate();\n    }\n\n    $(document).on(\"click\", \"a[data-ajax=true]\", function (evt) {\n        evt.preventDefault();\n        asyncRequest(this, {\n            url: this.href,\n            type: \"GET\",\n            data: []\n        });\n    });\n\n    $(document).on(\"click\", \"form[data-ajax=true] input[type=image]\", function (evt) {\n        var name = evt.target.name,\n            target = $(evt.target),\n            form = $(target.parents(\"form\")[0]),\n            offset = target.offset();\n\n        form.data(data_click, [\n            { name: name + \".x\", value: Math.round(evt.pageX - offset.left) },\n            { name: name + \".y\", value: Math.round(evt.pageY - offset.top) }\n        ]);\n\n        setTimeout(function () {\n            form.removeData(data_click);\n        }, 0);\n    });\n\n    $(document).on(\"click\", \"form[data-ajax=true] :submit\", function (evt) {\n        var name = evt.currentTarget.name,\n            target = $(evt.target),\n            form = $(target.parents(\"form\")[0]);\n\n        form.data(data_click, name ? [{ name: name, value: evt.currentTarget.value }] : []);\n        form.data(data_target, target);\n\n        setTimeout(function () {\n            form.removeData(data_click);\n            form.removeData(data_target);\n        }, 0);\n    });\n\n    $(document).on(\"submit\", \"form[data-ajax=true]\", function (evt) {\n        var clickInfo = $(this).data(data_click) || [],\n            clickTarget = $(this).data(data_target),\n            isCancel = clickTarget && clickTarget.hasClass(\"cancel\");\n        evt.preventDefault();\n        if (!isCancel && !validate(this)) {\n            return;\n        }\n        asyncRequest(this, {\n            url: this.action,\n            type: this.method || \"GET\",\n            data: clickInfo.concat($(this).serializeArray())\n        });\n    });\n}(jQuery));"
  },
  {
    "path": "src/System.Web.Mvc/JavaScript/jquery.validate.unobtrusive.js",
    "content": "﻿/*!\n** Unobtrusive validation support library for jQuery and jQuery Validate\n** Copyright (C) Microsoft Corporation. All rights reserved.\n*/\n\n/*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: false */\n/*global document: false, jQuery: false */\n\n(function ($) {\n    var $jQval = $.validator,\n        adapters,\n        data_validation = \"unobtrusiveValidation\";\n\n    function setValidationValues(options, ruleName, value) {\n        options.rules[ruleName] = value;\n        if (options.message) {\n            options.messages[ruleName] = options.message;\n        }\n    }\n\n    function splitAndTrim(value) {\n        return value.replace(/^\\s+|\\s+$/g, \"\").split(/\\s*,\\s*/g);\n    }\n\n    function escapeAttributeValue(value) {\n        // As mentioned on http://api.jquery.com/category/selectors/\n        return value.replace(/([!\"#$%&'()*+,./:;<=>?@\\[\\\\\\]^`{|}~])/g, \"\\\\$1\");\n    }\n\n    function getModelPrefix(fieldName) {\n        return fieldName.substr(0, fieldName.lastIndexOf(\".\") + 1);\n    }\n\n    function appendModelPrefix(value, prefix) {\n        if (value.indexOf(\"*.\") === 0) {\n            value = value.replace(\"*.\", prefix);\n        }\n        return value;\n    }\n\n    function onError(error, inputElement) {  // 'this' is the form element\n        var container = $(this).find(\"[data-valmsg-for='\" + escapeAttributeValue(inputElement[0].name) + \"']\"),\n            replaceAttrValue = container.attr(\"data-valmsg-replace\"),\n            replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) !== false : null;\n\n        container.removeClass(\"field-validation-valid\").addClass(\"field-validation-error\");\n        error.data(\"unobtrusiveContainer\", container);\n\n        if (replace) {\n            container.empty();\n            error.removeClass(\"input-validation-error\").appendTo(container);\n        }\n        else {\n            error.hide();\n        }\n    }\n\n    function onErrors(event, validator) {  // 'this' is the form element\n        var container = $(this).find(\"[data-valmsg-summary=true]\"),\n            list = container.find(\"ul\");\n\n        if (list && list.length && validator.errorList.length) {\n            list.empty();\n            container.addClass(\"validation-summary-errors\").removeClass(\"validation-summary-valid\");\n\n            $.each(validator.errorList, function () {\n                $(\"<li />\").html(this.message).appendTo(list);\n            });\n        }\n    }\n\n    function onSuccess(error) {  // 'this' is the form element\n        var container = error.data(\"unobtrusiveContainer\"),\n            replaceAttrValue = container.attr(\"data-valmsg-replace\"),\n            replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) : null;\n\n        if (container) {\n            container.addClass(\"field-validation-valid\").removeClass(\"field-validation-error\");\n            error.removeData(\"unobtrusiveContainer\");\n\n            if (replace) {\n                container.empty();\n            }\n        }\n    }\n\n    function onReset(event) {  // 'this' is the form element\n        var $form = $(this),\n            key = '__jquery_unobtrusive_validation_form_reset';\n        if ($form.data(key)) {\n            return;\n        }\n        // Set a flag that indicates we're currently resetting the form.\n        $form.data(key, true);\n        try {\n            $form.data(\"validator\").resetForm();\n        } finally {\n            $form.removeData(key);\n        }\n\n        $form.find(\".validation-summary-errors\")\n            .addClass(\"validation-summary-valid\")\n            .removeClass(\"validation-summary-errors\");\n        $form.find(\".field-validation-error\")\n            .addClass(\"field-validation-valid\")\n            .removeClass(\"field-validation-error\")\n            .removeData(\"unobtrusiveContainer\")\n            .find(\">*\")  // If we were using valmsg-replace, get the underlying error\n                .removeData(\"unobtrusiveContainer\");\n    }\n\n    function validationInfo(form) {\n        var $form = $(form),\n            result = $form.data(data_validation),\n            onResetProxy = $.proxy(onReset, form),\n            defaultOptions = $jQval.unobtrusive.options || {},\n            execInContext = function (name, args) {\n                var func = defaultOptions[name];\n                func && $.isFunction(func) && func.apply(form, args);\n            }\n\n        if (!result) {\n            result = {\n                options: {  // options structure passed to jQuery Validate's validate() method\n                    errorClass: defaultOptions.errorClass || \"input-validation-error\",\n                    errorElement: defaultOptions.errorElement || \"span\",\n                    errorPlacement: function () {\n                        onError.apply(form, arguments);\n                        execInContext(\"errorPlacement\", arguments);\n                    },\n                    invalidHandler: function () {\n                        onErrors.apply(form, arguments);\n                        execInContext(\"invalidHandler\", arguments);\n                    },\n                    messages: {},\n                    rules: {},\n                    success: function () {\n                        onSuccess.apply(form, arguments);\n                        execInContext(\"success\", arguments);\n                    }\n                },\n                attachValidation: function () {\n                    $form\n                        .off(\"reset.\" + data_validation, onResetProxy)\n                        .on(\"reset.\" + data_validation, onResetProxy)\n                        .validate(this.options);\n                },\n                validate: function () {  // a validation function that is called by unobtrusive Ajax\n                    $form.validate();\n                    return $form.valid();\n                }\n            };\n            $form.data(data_validation, result);\n        }\n\n        return result;\n    }\n\n    $jQval.unobtrusive = {\n        adapters: [],\n\n        parseElement: function (element, skipAttach) {\n            /// <summary>\n            /// Parses a single HTML element for unobtrusive validation attributes.\n            /// </summary>\n            /// <param name=\"element\" domElement=\"true\">The HTML element to be parsed.</param>\n            /// <param name=\"skipAttach\" type=\"Boolean\">[Optional] true to skip attaching the\n            /// validation to the form. If parsing just this single element, you should specify true.\n            /// If parsing several elements, you should specify false, and manually attach the validation\n            /// to the form when you are finished. The default is false.</param>\n            var $element = $(element),\n                form = $element.parents(\"form\")[0],\n                valInfo, rules, messages;\n\n            if (!form) {  // Cannot do client-side validation without a form\n                return;\n            }\n\n            valInfo = validationInfo(form);\n            valInfo.options.rules[element.name] = rules = {};\n            valInfo.options.messages[element.name] = messages = {};\n\n            $.each(this.adapters, function () {\n                var prefix = \"data-val-\" + this.name,\n                    message = $element.attr(prefix),\n                    paramValues = {};\n\n                if (message !== undefined) {  // Compare against undefined, because an empty message is legal (and falsy)\n                    prefix += \"-\";\n\n                    $.each(this.params, function () {\n                        paramValues[this] = $element.attr(prefix + this);\n                    });\n\n                    this.adapt({\n                        element: element,\n                        form: form,\n                        message: message,\n                        params: paramValues,\n                        rules: rules,\n                        messages: messages\n                    });\n                }\n            });\n\n            $.extend(rules, { \"__dummy__\": true });\n\n            if (!skipAttach) {\n                valInfo.attachValidation();\n            }\n        },\n\n        parse: function (selector) {\n            /// <summary>\n            /// Parses all the HTML elements in the specified selector. It looks for input elements decorated\n            /// with the [data-val=true] attribute value and enables validation according to the data-val-*\n            /// attribute values.\n            /// </summary>\n            /// <param name=\"selector\" type=\"String\">Any valid jQuery selector.</param>\n\n            // $forms includes all forms in selector's DOM hierarchy (parent, children and self) that have at least one\n            // element with data-val=true\n            var $selector = $(selector),\n                $forms = $selector.parents()\n                                  .addBack()\n                                  .filter(\"form\")\n                                  .add($selector.find(\"form\"))\n                                  .has(\"[data-val=true]\");\n\n            $selector.find(\"[data-val=true]\").each(function () {\n                $jQval.unobtrusive.parseElement(this, true);\n            });\n\n            $forms.each(function () {\n                var info = validationInfo(this);\n                if (info) {\n                    info.attachValidation();\n                }\n            });\n        }\n    };\n\n    adapters = $jQval.unobtrusive.adapters;\n\n    adapters.add = function (adapterName, params, fn) {\n        /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation.</summary>\n        /// <param name=\"adapterName\" type=\"String\">The name of the adapter to be added. This matches the name used\n        /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>\n        /// <param name=\"params\" type=\"Array\" optional=\"true\">[Optional] An array of parameter names (strings) that will\n        /// be extracted from the data-val-nnnn-mmmm HTML attributes (where nnnn is the adapter name, and\n        /// mmmm is the parameter name).</param>\n        /// <param name=\"fn\" type=\"Function\">The function to call, which adapts the values from the HTML\n        /// attributes into jQuery Validate rules and/or messages.</param>\n        /// <returns type=\"jQuery.validator.unobtrusive.adapters\" />\n        if (!fn) {  // Called with no params, just a function\n            fn = params;\n            params = [];\n        }\n        this.push({ name: adapterName, params: params, adapt: fn });\n        return this;\n    };\n\n    adapters.addBool = function (adapterName, ruleName) {\n        /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where\n        /// the jQuery Validate validation rule has no parameter values.</summary>\n        /// <param name=\"adapterName\" type=\"String\">The name of the adapter to be added. This matches the name used\n        /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>\n        /// <param name=\"ruleName\" type=\"String\" optional=\"true\">[Optional] The name of the jQuery Validate rule. If not provided, the value\n        /// of adapterName will be used instead.</param>\n        /// <returns type=\"jQuery.validator.unobtrusive.adapters\" />\n        return this.add(adapterName, function (options) {\n            setValidationValues(options, ruleName || adapterName, true);\n        });\n    };\n\n    adapters.addMinMax = function (adapterName, minRuleName, maxRuleName, minMaxRuleName, minAttribute, maxAttribute) {\n        /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where\n        /// the jQuery Validate validation has three potential rules (one for min-only, one for max-only, and\n        /// one for min-and-max). The HTML parameters are expected to be named -min and -max.</summary>\n        /// <param name=\"adapterName\" type=\"String\">The name of the adapter to be added. This matches the name used\n        /// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>\n        /// <param name=\"minRuleName\" type=\"String\">The name of the jQuery Validate rule to be used when you only\n        /// have a minimum value.</param>\n        /// <param name=\"maxRuleName\" type=\"String\">The name of the jQuery Validate rule to be used when you only\n        /// have a maximum value.</param>\n        /// <param name=\"minMaxRuleName\" type=\"String\">The name of the jQuery Validate rule to be used when you\n        /// have both a minimum and maximum value.</param>\n        /// <param name=\"minAttribute\" type=\"String\" optional=\"true\">[Optional] The name of the HTML attribute that\n        /// contains the minimum value. The default is \"min\".</param>\n        /// <param name=\"maxAttribute\" type=\"String\" optional=\"true\">[Optional] The name of the HTML attribute that\n        /// contains the maximum value. The default is \"max\".</param>\n        /// <returns type=\"jQuery.validator.unobtrusive.adapters\" />\n        return this.add(adapterName, [minAttribute || \"min\", maxAttribute || \"max\"], function (options) {\n            var min = options.params.min,\n                max = options.params.max;\n\n            if (min && max) {\n                setValidationValues(options, minMaxRuleName, [min, max]);\n            }\n            else if (min) {\n                setValidationValues(options, minRuleName, min);\n            }\n            else if (max) {\n                setValidationValues(options, maxRuleName, max);\n            }\n        });\n    };\n\n    adapters.addSingleVal = function (adapterName, attribute, ruleName) {\n        /// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where\n        /// the jQuery Validate validation rule has a single value.</summary>\n        /// <param name=\"adapterName\" type=\"String\">The name of the adapter to be added. This matches the name used\n        /// in the data-val-nnnn HTML attribute(where nnnn is the adapter name).</param>\n        /// <param name=\"attribute\" type=\"String\">[Optional] The name of the HTML attribute that contains the value.\n        /// The default is \"val\".</param>\n        /// <param name=\"ruleName\" type=\"String\" optional=\"true\">[Optional] The name of the jQuery Validate rule. If not provided, the value\n        /// of adapterName will be used instead.</param>\n        /// <returns type=\"jQuery.validator.unobtrusive.adapters\" />\n        return this.add(adapterName, [attribute || \"val\"], function (options) {\n            setValidationValues(options, ruleName || adapterName, options.params[attribute]);\n        });\n    };\n\n    $jQval.addMethod(\"__dummy__\", function (value, element, params) {\n        return true;\n    });\n\n    $jQval.addMethod(\"regex\", function (value, element, params) {\n        var match;\n        if (this.optional(element)) {\n            return true;\n        }\n\n        match = new RegExp(params).exec(value);\n        return (match && (match.index === 0) && (match[0].length === value.length));\n    });\n\n    $jQval.addMethod(\"nonalphamin\", function (value, element, nonalphamin) {\n        var match;\n        if (nonalphamin) {\n            match = value.match(/\\W/g);\n            match = match && match.length >= nonalphamin;\n        }\n        return match;\n    });\n\n    if ($jQval.methods.extension) {\n        adapters.addSingleVal(\"accept\", \"mimtype\");\n        adapters.addSingleVal(\"extension\", \"extension\");\n    } else {\n        // for backward compatibility, when the 'extension' validation method does not exist, such as with versions\n        // of JQuery Validation plugin prior to 1.10, we should use the 'accept' method for\n        // validating the extension, and ignore mime-type validations as they are not supported.\n        adapters.addSingleVal(\"extension\", \"extension\", \"accept\");\n    }\n\n    adapters.addSingleVal(\"regex\", \"pattern\");\n    adapters.addBool(\"creditcard\").addBool(\"date\").addBool(\"digits\").addBool(\"email\").addBool(\"number\").addBool(\"url\");\n    adapters.addMinMax(\"length\", \"minlength\", \"maxlength\", \"rangelength\").addMinMax(\"range\", \"min\", \"max\", \"range\");\n    adapters.addMinMax(\"minlength\", \"minlength\").addMinMax(\"maxlength\", \"minlength\", \"maxlength\");\n    adapters.add(\"equalto\", [\"other\"], function (options) {\n        var prefix = getModelPrefix(options.element.name),\n            other = options.params.other,\n            fullOtherName = appendModelPrefix(other, prefix),\n            element = $(options.form).find(\":input\").filter(\"[name='\" + escapeAttributeValue(fullOtherName) + \"']\")[0];\n\n        setValidationValues(options, \"equalTo\", element);\n    });\n    adapters.add(\"required\", function (options) {\n        // jQuery Validate equates \"required\" with \"mandatory\" for checkbox elements\n        if (options.element.tagName.toUpperCase() !== \"INPUT\" || options.element.type.toUpperCase() !== \"CHECKBOX\") {\n            setValidationValues(options, \"required\", true);\n        }\n    });\n    adapters.add(\"remote\", [\"url\", \"type\", \"additionalfields\"], function (options) {\n        var value = {\n            url: options.params.url,\n            type: options.params.type || \"GET\",\n            data: {}\n        },\n            prefix = getModelPrefix(options.element.name);\n\n        $.each(splitAndTrim(options.params.additionalfields || options.element.name), function (i, fieldName) {\n            var paramName = appendModelPrefix(fieldName, prefix);\n            value.data[paramName] = function () {\n                var field = $(options.form).find(\":input\").filter(\"[name='\" + escapeAttributeValue(paramName) + \"']\");\n                // For checkboxes and radio buttons, only pick up values from checked fields.\n                if (field.is(\":checkbox\")) {\n                    return field.filter(\":checked\").val() || field.filter(\":hidden\").val() || '';\n                }\n                else if (field.is(\":radio\")) {\n                    return field.filter(\":checked\").val() || '';\n                }\n                return field.val();\n            };\n        });\n\n        setValidationValues(options, \"remote\", value);\n    });\n    adapters.add(\"password\", [\"min\", \"nonalphamin\", \"regex\"], function (options) {\n        if (options.params.min) {\n            setValidationValues(options, \"minlength\", options.params.min);\n        }\n        if (options.params.nonalphamin) {\n            setValidationValues(options, \"nonalphamin\", options.params.nonalphamin);\n        }\n        if (options.params.regex) {\n            setValidationValues(options, \"regex\", options.params.regex);\n        }\n    });\n\n    $(function () {\n        $jQval.unobtrusive.parse(document);\n    });\n}(jQuery));"
  },
  {
    "path": "src/System.Web.Mvc/JavaScriptResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public class JavaScriptResult : ActionResult\n    {\n        public string Script { get; set; }\n\n        public override void ExecuteResult(ControllerContext context)\n        {\n            if (context == null)\n            {\n                throw new ArgumentNullException(\"context\");\n            }\n\n            HttpResponseBase response = context.HttpContext.Response;\n            response.ContentType = \"application/x-javascript\";\n\n            if (Script != null)\n            {\n                response.Write(Script);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/JsonRequestBehavior.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public enum JsonRequestBehavior\n    {\n        AllowGet,\n        DenyGet,\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/JsonResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Text;\nusing System.Web.Mvc.Properties;\nusing System.Web.Script.Serialization;\n\nnamespace System.Web.Mvc\n{\n    public class JsonResult : ActionResult\n    {\n        public JsonResult()\n        {\n            JsonRequestBehavior = JsonRequestBehavior.DenyGet;\n        }\n\n        public Encoding ContentEncoding { get; set; }\n\n        public string ContentType { get; set; }\n\n        public object Data { get; set; }\n\n        public JsonRequestBehavior JsonRequestBehavior { get; set; }\n\n        /// <summary>\n        /// When set MaxJsonLength passed to the JavaScriptSerializer.\n        /// </summary>\n        public int? MaxJsonLength { get; set; }\n\n        /// <summary>\n        /// When set RecursionLimit passed to the JavaScriptSerializer.\n        /// </summary>\n        public int? RecursionLimit { get; set; }\n\n        public override void ExecuteResult(ControllerContext context)\n        {\n            if (context == null)\n            {\n                throw new ArgumentNullException(\"context\");\n            }\n            if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&\n                String.Equals(context.HttpContext.Request.HttpMethod, \"GET\", StringComparison.OrdinalIgnoreCase))\n            {\n                throw new InvalidOperationException(MvcResources.JsonRequest_GetNotAllowed);\n            }\n\n            HttpResponseBase response = context.HttpContext.Response;\n\n            if (!String.IsNullOrEmpty(ContentType))\n            {\n                response.ContentType = ContentType;\n            }\n            else\n            {\n                response.ContentType = \"application/json\";\n            }\n            if (ContentEncoding != null)\n            {\n                response.ContentEncoding = ContentEncoding;\n            }\n            if (Data != null)\n            {\n                JavaScriptSerializer serializer = new JavaScriptSerializer();\n                if (MaxJsonLength.HasValue)\n                {\n                    serializer.MaxJsonLength = MaxJsonLength.Value;\n                }\n                if (RecursionLimit.HasValue)\n                {\n                    serializer.RecursionLimit = RecursionLimit.Value;\n                }\n                response.Write(serializer.Serialize(Data));\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/JsonValueProviderFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Configuration;\nusing System.Globalization;\nusing System.IO;\nusing System.Web.Mvc.Properties;\nusing System.Web.Script.Serialization;\n\nnamespace System.Web.Mvc\n{\n    public sealed class JsonValueProviderFactory : ValueProviderFactory\n    {\n        private static void AddToBackingStore(EntryLimitedDictionary backingStore, string prefix, object value)\n        {\n            IDictionary<string, object> d = value as IDictionary<string, object>;\n            if (d != null)\n            {\n                foreach (KeyValuePair<string, object> entry in d)\n                {\n                    AddToBackingStore(backingStore, MakePropertyKey(prefix, entry.Key), entry.Value);\n                }\n                return;\n            }\n\n            IList l = value as IList;\n            if (l != null)\n            {\n                for (int i = 0; i < l.Count; i++)\n                {\n                    AddToBackingStore(backingStore, MakeArrayKey(prefix, i), l[i]);\n                }\n                return;\n            }\n\n            // primitive\n            backingStore.Add(prefix, value);\n        }\n\n        private static object GetDeserializedObject(ControllerContext controllerContext)\n        {\n            if (!controllerContext.HttpContext.Request.ContentType.StartsWith(\"application/json\", StringComparison.OrdinalIgnoreCase))\n            {\n                // not JSON request\n                return null;\n            }\n\n            StreamReader reader = new StreamReader(controllerContext.HttpContext.Request.InputStream);\n            string bodyText = reader.ReadToEnd();\n            if (String.IsNullOrEmpty(bodyText))\n            {\n                // no JSON data\n                return null;\n            }\n\n            JavaScriptSerializer serializer = new JavaScriptSerializer();\n            object jsonData = serializer.DeserializeObject(bodyText);\n            return jsonData;\n        }\n\n        public override IValueProvider GetValueProvider(ControllerContext controllerContext)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n\n            object jsonData = GetDeserializedObject(controllerContext);\n            if (jsonData == null)\n            {\n                return null;\n            }\n\n            Dictionary<string, object> backingStore = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);\n            EntryLimitedDictionary backingStoreWrapper = new EntryLimitedDictionary(backingStore);\n            AddToBackingStore(backingStoreWrapper, String.Empty, jsonData);\n            return new DictionaryValueProvider<object>(backingStore, CultureInfo.CurrentCulture);\n        }\n\n        private static string MakeArrayKey(string prefix, int index)\n        {\n            return prefix + \"[\" + index.ToString(CultureInfo.InvariantCulture) + \"]\";\n        }\n\n        private static string MakePropertyKey(string prefix, string propertyName)\n        {\n            return (String.IsNullOrEmpty(prefix)) ? propertyName : prefix + \".\" + propertyName;\n        }\n\n        private class EntryLimitedDictionary\n        {\n            private static int _maximumDepth = GetMaximumDepth();\n            private readonly IDictionary<string, object> _innerDictionary;\n            private int _itemCount = 0;\n\n            public EntryLimitedDictionary(IDictionary<string, object> innerDictionary)\n            {\n                _innerDictionary = innerDictionary;\n            }\n\n            public void Add(string key, object value)\n            {\n                if (++_itemCount > _maximumDepth)\n                {\n                    throw new InvalidOperationException(MvcResources.JsonValueProviderFactory_RequestTooLarge);\n                }\n\n                _innerDictionary.Add(key, value);\n            }\n\n            private static int GetMaximumDepth()\n            {\n                NameValueCollection appSettings = ConfigurationManager.AppSettings;\n                if (appSettings != null)\n                {\n                    string[] valueArray = appSettings.GetValues(\"aspnet:MaxJsonDeserializerMembers\");\n                    if (valueArray != null && valueArray.Length > 0)\n                    {\n                        int result;\n                        if (Int32.TryParse(valueArray[0], out result))\n                        {\n                            return result;\n                        }\n                    }\n                }\n\n                return 1000; // Fallback default\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/LinqBinaryModelBinder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Data.Linq;\n\nnamespace System.Web.Mvc\n{\n    public class LinqBinaryModelBinder : ByteArrayModelBinder\n    {\n        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)\n        {\n            byte[] byteValue = (byte[])base.BindModel(controllerContext, bindingContext);\n            if (byteValue == null)\n            {\n                return null;\n            }\n\n            return new Binary(byteValue);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/MaxLengthAttributeAdapter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\n\nnamespace System.Web.Mvc\n{\n    public class MaxLengthAttributeAdapter : DataAnnotationsModelValidator<MaxLengthAttribute>\n    {\n        public MaxLengthAttributeAdapter(ModelMetadata metadata, ControllerContext context, MaxLengthAttribute attribute)\n            : base(metadata, context, attribute)\n        {\n        }\n\n        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()\n        {\n            return new[] { new ModelClientValidationMaxLengthRule(ErrorMessage, Attribute.Length) };\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/MembershipPasswordAttributeAdapter.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Security;\n\nnamespace System.Web.Mvc\n{\n    internal class MembershipPasswordAttributeAdapter : DataAnnotationsModelValidator<MembershipPasswordAttribute>\n    {\n        public MembershipPasswordAttributeAdapter(ModelMetadata metadata, ControllerContext context, MembershipPasswordAttribute attribute)\n            : base(metadata, context, attribute)\n        {\n        }\n\n        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()\n        {\n            yield return new ModelClientValidationMembershipPasswordRule(ErrorMessage, Attribute.MinRequiredPasswordLength, Attribute.MinRequiredNonAlphanumericCharacters, Attribute.PasswordStrengthRegularExpression);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/MinLengthAttributeAdapter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\n\nnamespace System.Web.Mvc\n{\n    public class MinLengthAttributeAdapter : DataAnnotationsModelValidator<MinLengthAttribute>\n    {\n        public MinLengthAttributeAdapter(ModelMetadata metadata, ControllerContext context, MinLengthAttribute attribute)\n            : base(metadata, context, attribute)\n        {\n        }\n\n        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()\n        {\n            return new[] { new ModelClientValidationMinLengthRule(ErrorMessage, Attribute.Length) };\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ModelBinderAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    [AttributeUsage(ValidTargets, AllowMultiple = false, Inherited = false)]\n    public sealed class ModelBinderAttribute : CustomModelBinderAttribute\n    {\n        public ModelBinderAttribute(Type binderType)\n        {\n            if (binderType == null)\n            {\n                throw new ArgumentNullException(\"binderType\");\n            }\n            if (!typeof(IModelBinder).IsAssignableFrom(binderType))\n            {\n                string message = String.Format(CultureInfo.CurrentCulture,\n                                               MvcResources.ModelBinderAttribute_TypeNotIModelBinder, binderType.FullName);\n                throw new ArgumentException(message, \"binderType\");\n            }\n\n            BinderType = binderType;\n        }\n\n        public Type BinderType { get; private set; }\n\n        public override IModelBinder GetBinder()\n        {\n            try\n            {\n                return (IModelBinder)Activator.CreateInstance(BinderType);\n            }\n            catch (Exception ex)\n            {\n                throw new InvalidOperationException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.ModelBinderAttribute_ErrorCreatingModelBinder,\n                        BinderType.FullName),\n                    ex);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ModelBinderDictionary.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    public class ModelBinderDictionary : IDictionary<Type, IModelBinder>\n    {\n        private readonly Dictionary<Type, IModelBinder> _innerDictionary = new Dictionary<Type, IModelBinder>();\n        private IModelBinder _defaultBinder;\n        private ModelBinderProviderCollection _modelBinderProviders;\n\n        public ModelBinderDictionary()\n            : this(ModelBinderProviders.BinderProviders)\n        {\n        }\n\n        internal ModelBinderDictionary(ModelBinderProviderCollection modelBinderProviders)\n        {\n            _modelBinderProviders = modelBinderProviders;\n        }\n\n        public int Count\n        {\n            get { return _innerDictionary.Count; }\n        }\n\n        public IModelBinder DefaultBinder\n        {\n            get\n            {\n                if (_defaultBinder == null)\n                {\n                    _defaultBinder = new DefaultModelBinder();\n                }\n                return _defaultBinder;\n            }\n            set { _defaultBinder = value; }\n        }\n\n        public bool IsReadOnly\n        {\n            get { return ((IDictionary<Type, IModelBinder>)_innerDictionary).IsReadOnly; }\n        }\n\n        public ICollection<Type> Keys\n        {\n            get { return _innerDictionary.Keys; }\n        }\n\n        public ICollection<IModelBinder> Values\n        {\n            get { return _innerDictionary.Values; }\n        }\n\n        public IModelBinder this[Type key]\n        {\n            get\n            {\n                IModelBinder binder;\n                _innerDictionary.TryGetValue(key, out binder);\n                return binder;\n            }\n            set { _innerDictionary[key] = value; }\n        }\n\n        public void Add(KeyValuePair<Type, IModelBinder> item)\n        {\n            ((IDictionary<Type, IModelBinder>)_innerDictionary).Add(item);\n        }\n\n        public void Add(Type key, IModelBinder value)\n        {\n            _innerDictionary.Add(key, value);\n        }\n\n        public void Clear()\n        {\n            _innerDictionary.Clear();\n        }\n\n        public bool Contains(KeyValuePair<Type, IModelBinder> item)\n        {\n            return ((IDictionary<Type, IModelBinder>)_innerDictionary).Contains(item);\n        }\n\n        public bool ContainsKey(Type key)\n        {\n            return _innerDictionary.ContainsKey(key);\n        }\n\n        public void CopyTo(KeyValuePair<Type, IModelBinder>[] array, int arrayIndex)\n        {\n            ((IDictionary<Type, IModelBinder>)_innerDictionary).CopyTo(array, arrayIndex);\n        }\n\n        public IModelBinder GetBinder(Type modelType)\n        {\n            return GetBinder(modelType, true /* fallbackToDefault */);\n        }\n\n        public virtual IModelBinder GetBinder(Type modelType, bool fallbackToDefault)\n        {\n            if (modelType == null)\n            {\n                throw new ArgumentNullException(\"modelType\");\n            }\n\n            return GetBinder(modelType, (fallbackToDefault) ? DefaultBinder : null);\n        }\n\n        private IModelBinder GetBinder(Type modelType, IModelBinder fallbackBinder)\n        {\n            // Try to look up a binder for this type. We use this order of precedence:\n            // 1. Binder returned from provider\n            // 2. Binder registered in the global table\n            // 3. Binder attribute defined on the type\n            // 4. Supplied fallback binder\n\n            IModelBinder binder = _modelBinderProviders.GetBinder(modelType);\n            if (binder != null)\n            {\n                return binder;\n            }\n\n            if (_innerDictionary.TryGetValue(modelType, out binder))\n            {\n                return binder;\n            }\n\n            // Function is called frequently, so ensure the error delegate is stateless\n            binder = ModelBinders.GetBinderFromAttributes(modelType, (Type errorModel) =>\n                {\n                    throw new InvalidOperationException(\n                        String.Format(CultureInfo.CurrentCulture, MvcResources.ModelBinderDictionary_MultipleAttributes, errorModel.FullName));\n                });\n\n            return binder ?? fallbackBinder;\n        }\n\n        public IEnumerator<KeyValuePair<Type, IModelBinder>> GetEnumerator()\n        {\n            return _innerDictionary.GetEnumerator();\n        }\n\n        public bool Remove(KeyValuePair<Type, IModelBinder> item)\n        {\n            return ((IDictionary<Type, IModelBinder>)_innerDictionary).Remove(item);\n        }\n\n        public bool Remove(Type key)\n        {\n            return _innerDictionary.Remove(key);\n        }\n\n        public bool TryGetValue(Type key, out IModelBinder value)\n        {\n            return _innerDictionary.TryGetValue(key, out value);\n        }\n\n        #region IEnumerable Members\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return ((IEnumerable)_innerDictionary).GetEnumerator();\n        }\n\n        #endregion\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ModelBinderProviderCollection.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\n\nnamespace System.Web.Mvc\n{\n    public class ModelBinderProviderCollection : Collection<IModelBinderProvider>\n    {\n        private IModelBinderProvider[] _combinedItems;\n        private IDependencyResolver _dependencyResolver;\n\n        public ModelBinderProviderCollection()\n        {\n        }\n\n        public ModelBinderProviderCollection(IList<IModelBinderProvider> list)\n            : base(list)\n        {\n        }\n\n        internal ModelBinderProviderCollection(IList<IModelBinderProvider> list, IDependencyResolver dependencyResolver)\n            : base(list)\n        {\n            _dependencyResolver = dependencyResolver;\n        }\n\n        internal IModelBinderProvider[] CombinedItems\n        {\n            get\n            {\n                IModelBinderProvider[] combinedItems = _combinedItems;\n                if (combinedItems == null)\n                {\n                    combinedItems = MultiServiceResolver.GetCombined<IModelBinderProvider>(Items, _dependencyResolver);\n                    _combinedItems = combinedItems;\n                }\n                return combinedItems;\n            }\n        }\n\n        protected override void ClearItems()\n        {\n            _combinedItems = null;\n            base.ClearItems();\n        }\n\n        protected override void InsertItem(int index, IModelBinderProvider item)\n        {\n            if (item == null)\n            {\n                throw new ArgumentNullException(\"item\");\n            }\n            _combinedItems = null;\n            base.InsertItem(index, item);\n        }\n\n        protected override void RemoveItem(int index)\n        {\n            _combinedItems = null;\n            base.RemoveItem(index);\n        }\n\n        protected override void SetItem(int index, IModelBinderProvider item)\n        {\n            if (item == null)\n            {\n                throw new ArgumentNullException(\"item\");\n            }\n            _combinedItems = null;\n            base.SetItem(index, item);\n        }\n\n        public IModelBinder GetBinder(Type modelType)\n        {\n            if (modelType == null)\n            {\n                throw new ArgumentNullException(\"modelType\");\n            }\n\n            // Performance sensitive.\n            IModelBinderProvider[] providers = CombinedItems;\n            for (int i = 0; i < providers.Length; i++)\n            {\n                IModelBinder binder = providers[i].GetBinder(modelType);\n                if (binder != null)\n                {\n                    return binder;\n                }\n            }\n            return null;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ModelBinderProviders.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public static class ModelBinderProviders\n    {\n        private static readonly ModelBinderProviderCollection _binderProviders = new ModelBinderProviderCollection\n        {\n        };\n\n        public static ModelBinderProviderCollection BinderProviders\n        {\n            get { return _binderProviders; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ModelBinders.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data.Linq;\nusing System.Linq;\nusing System.Reflection;\nusing System.Threading;\n\nnamespace System.Web.Mvc\n{\n    public static class ModelBinders\n    {\n        private static readonly ModelBinderDictionary _binders = CreateDefaultBinderDictionary();\n\n        public static ModelBinderDictionary Binders\n        {\n            get { return _binders; }\n        }\n\n        internal static IModelBinder GetBinderFromAttributes(Type type, Action<Type> errorAction)\n        {\n            AttributeList allAttrs = new AttributeList(TypeDescriptorHelper.Get(type).GetAttributes());\n            CustomModelBinderAttribute binder = allAttrs.SingleOfTypeDefaultOrError<Attribute, CustomModelBinderAttribute, Type>(errorAction, type);\n            return binder == null ? null : binder.GetBinder();\n        }\n\n        internal static IModelBinder GetBinderFromAttributes(ICustomAttributeProvider element, Action<ICustomAttributeProvider> errorAction)\n        {\n            CustomModelBinderAttribute[] attrs = (CustomModelBinderAttribute[])element.GetCustomAttributes(typeof(CustomModelBinderAttribute), true /* inherit */);\n            // For compatibility, return null if no attributes.\n            if (attrs == null)\n            {                \n                return null;\n            }\n            CustomModelBinderAttribute binder = attrs.SingleDefaultOrError(errorAction, element);\n            return binder == null ? null : binder.GetBinder();\n        }\n\n        private static ModelBinderDictionary CreateDefaultBinderDictionary()\n        {\n            // We can't add a binder to the HttpPostedFileBase type as an attribute, so we'll just\n            // prepopulate the dictionary as a convenience to users.\n\n            ModelBinderDictionary binders = new ModelBinderDictionary()\n            {\n                { typeof(HttpPostedFileBase), new HttpPostedFileBaseModelBinder() },\n                { typeof(byte[]), new ByteArrayModelBinder() },\n                { typeof(Binary), new LinqBinaryModelBinder() },\n                { typeof(CancellationToken), new CancellationTokenModelBinder() }\n            };\n            return binders;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ModelBindingContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    public class ModelBindingContext\n    {\n        private static readonly Predicate<string> _defaultPropertyFilter = _ => true;\n\n        private string _modelName = String.Empty;\n        private ModelStateDictionary _modelState;\n        private Predicate<string> _propertyFilter;\n        private Dictionary<string, ModelMetadata> _propertyMetadata;\n\n        public ModelBindingContext()\n            : this(null)\n        {\n        }\n\n        // copies certain values that won't change between parent and child objects,\n        // e.g. ValueProvider, ModelState\n        public ModelBindingContext(ModelBindingContext bindingContext)\n        {\n            if (bindingContext != null)\n            {\n                ModelState = bindingContext.ModelState;\n                ValueProvider = bindingContext.ValueProvider;\n            }\n        }\n\n        public bool FallbackToEmptyPrefix { get; set; }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA1801:ReviewUnusedParameters\", MessageId = \"value\", Justification = \"Cannot remove setter as that's a breaking change\")]\n        public object Model\n        {\n            get { return ModelMetadata.Model; }\n            set { throw new InvalidOperationException(MvcResources.ModelMetadata_PropertyNotSettable); }\n        }\n\n        public ModelMetadata ModelMetadata { get; set; }\n\n        public string ModelName\n        {\n            get\n            {\n                return _modelName;\n            }\n            set \n            {\n                _modelName = value ?? String.Empty;\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"The containing type is mutable.\")]\n        public ModelStateDictionary ModelState\n        {\n            get\n            {\n                if (_modelState == null)\n                {\n                    _modelState = new ModelStateDictionary();\n                }\n                return _modelState;\n            }\n            set { _modelState = value; }\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA1801:ReviewUnusedParameters\", MessageId = \"value\", Justification = \"Cannot remove setter as that's a breaking change\")]\n        public Type ModelType\n        {\n            get { return ModelMetadata.ModelType; }\n            set { throw new InvalidOperationException(MvcResources.ModelMetadata_PropertyNotSettable); }\n        }\n\n        public Predicate<string> PropertyFilter\n        {\n            get\n            {\n                if (_propertyFilter == null)\n                {\n                    _propertyFilter = _defaultPropertyFilter;\n                }\n                return _propertyFilter;\n            }\n            set { _propertyFilter = value; }\n        }\n\n        public IDictionary<string, ModelMetadata> PropertyMetadata\n        {\n            get\n            {\n                if (_propertyMetadata == null)\n                {\n                    _propertyMetadata = ModelMetadata.PropertiesAsArray.ToDictionaryFast(m => m.PropertyName, StringComparer.OrdinalIgnoreCase);\n                }\n\n                return _propertyMetadata;\n            }\n        }\n\n        public IValueProvider ValueProvider { get; set; }\n\n        internal IUnvalidatedValueProvider UnvalidatedValueProvider\n        {\n            get { return (ValueProvider as IUnvalidatedValueProvider) ?? new UnvalidatedValueProviderWrapper(ValueProvider); }\n        }\n\n        // Used to wrap an IValueProvider in an IUnvalidatedValueProvider\n        private sealed class UnvalidatedValueProviderWrapper : IValueProvider, IUnvalidatedValueProvider\n        {\n            private readonly IValueProvider _backingProvider;\n\n            public UnvalidatedValueProviderWrapper(IValueProvider backingProvider)\n            {\n                _backingProvider = backingProvider;\n            }\n\n            public ValueProviderResult GetValue(string key, bool skipValidation)\n            {\n                // 'skipValidation' isn't understood by the backing provider and can be ignored\n                return GetValue(key);\n            }\n\n            public bool ContainsPrefix(string prefix)\n            {\n                return _backingProvider.ContainsPrefix(prefix);\n            }\n\n            public ValueProviderResult GetValue(string key)\n            {\n                return _backingProvider.GetValue(key);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ModelError.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    [Serializable]\n    public class ModelError\n    {\n        public ModelError(Exception exception)\n            : this(exception, null /* errorMessage */)\n        {\n        }\n\n        public ModelError(Exception exception, string errorMessage)\n            : this(errorMessage)\n        {\n            if (exception == null)\n            {\n                throw new ArgumentNullException(\"exception\");\n            }\n\n            Exception = exception;\n        }\n\n        public ModelError(string errorMessage)\n        {\n            ErrorMessage = errorMessage ?? String.Empty;\n        }\n\n        public Exception Exception { get; private set; }\n\n        public string ErrorMessage { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ModelErrorCollection.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\n\nnamespace System.Web.Mvc\n{\n    [Serializable]\n    public class ModelErrorCollection : Collection<ModelError>\n    {\n        public void Add(Exception exception)\n        {\n            Add(new ModelError(exception));\n        }\n\n        public void Add(string errorMessage)\n        {\n            Add(new ModelError(errorMessage));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ModelMetadata.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Linq;\nusing System.Linq.Expressions;\nusing System.Reflection;\nusing System.Web.Mvc.ExpressionUtil;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    public class ModelMetadata\n    {\n        public const int DefaultOrder = 10000;\n\n        private readonly Type _containerType;\n        private readonly Type _modelType;\n        private readonly string _propertyName;\n\n        /// <summary>\n        /// Explicit backing store for the things we want initialized by default, so don't have to call\n        /// the protected virtual setters of an auto-generated property\n        /// </summary>\n        private Dictionary<string, object> _additionalValues = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);\n        private bool _convertEmptyStringToNull = true;\n        private bool _htmlEncode = true;\n        private bool _isRequired;\n        private object _model;\n        private Func<object> _modelAccessor;\n        private int _order = DefaultOrder;\n        private IEnumerable<ModelMetadata> _properties;\n        private ModelMetadata[] _propertiesInternal;\n        private Type _realModelType;\n        private bool _requestValidationEnabled = true;\n        private bool _showForDisplay = true;\n        private bool _showForEdit = true;\n        private string _simpleDisplayText;\n\n        public ModelMetadata(ModelMetadataProvider provider, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)\n        {\n            if (provider == null)\n            {\n                throw new ArgumentNullException(\"provider\");\n            }\n            if (modelType == null)\n            {\n                throw new ArgumentNullException(\"modelType\");\n            }\n\n            Provider = provider;\n\n            _containerType = containerType;\n            _isRequired = !TypeHelpers.TypeAllowsNullValue(modelType);\n            _modelAccessor = modelAccessor;\n            _modelType = modelType;\n            _propertyName = propertyName;\n        }\n\n        public virtual Dictionary<string, object> AdditionalValues\n        {\n            get { return _additionalValues; }\n        }\n\n        /// <summary>\n        /// A reference to the model's container object. Will be non-null if the model represents a property.\n        /// </summary>\n        public object Container { get; set; }\n\n        public Type ContainerType\n        {\n            get { return _containerType; }\n        }\n\n        public virtual bool ConvertEmptyStringToNull\n        {\n            get { return _convertEmptyStringToNull; }\n            set { _convertEmptyStringToNull = value; }\n        }\n\n        public virtual string DataTypeName { get; set; }\n\n        public virtual string Description { get; set; }\n\n        public virtual string DisplayFormatString { get; set; }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1721:PropertyNamesShouldNotMatchGetMethods\", Justification = \"The method is a delegating helper to choose among multiple property values\")]\n        public virtual string DisplayName { get; set; }\n\n        public virtual string EditFormatString { get; set; }\n\n        internal virtual bool HasNonDefaultEditFormat { get; set; }\n\n        public virtual bool HideSurroundingHtml { get; set; }\n\n        public virtual bool HtmlEncode\n        {\n            get { return _htmlEncode; }\n            set { _htmlEncode = value; }\n        }\n\n        public virtual bool IsComplexType\n        {\n            get { return !(TypeDescriptor.GetConverter(ModelType).CanConvertFrom(typeof(string))); }\n        }\n\n        public bool IsNullableValueType\n        {\n            get { return TypeHelpers.IsNullableValueType(ModelType); }\n        }\n\n        public virtual bool IsReadOnly { get; set; }\n\n        public virtual bool IsRequired\n        {\n            get { return _isRequired; }\n            set { _isRequired = value; }\n        }\n\n        public object Model\n        {\n            get\n            {\n                if (_modelAccessor != null)\n                {\n                    _model = _modelAccessor();\n                    _modelAccessor = null;\n                }\n                return _model;\n            }\n            set\n            {\n                _model = value;\n                _modelAccessor = null;\n                _properties = null;\n                _realModelType = null;\n            }\n        }\n\n        public Type ModelType\n        {\n            get { return _modelType; }\n        }\n\n        public virtual string NullDisplayText { get; set; }\n\n        public virtual int Order\n        {\n            get { return _order; }\n            set { _order = value; }\n        }\n\n        public virtual IEnumerable<ModelMetadata> Properties\n        {\n            get\n            {\n                if (_properties == null)\n                {\n                    IEnumerable<ModelMetadata> originalProperties = Provider.GetMetadataForProperties(Model, RealModelType);\n                    // This will be returned as a copied out array in the common case, so reuse the returned array for performance.\n                    _propertiesInternal = SortProperties(originalProperties.AsArray());\n                    _properties = new ReadOnlyCollection<ModelMetadata>(_propertiesInternal);\n                }\n                return _properties;\n            }\n        }\n\n        internal ModelMetadata[] PropertiesAsArray \n        {\n            get\n            {\n                IEnumerable<ModelMetadata> virtualProperties = Properties;\n                if (Object.ReferenceEquals(virtualProperties, _properties))\n                {\n                    Contract.Assert(_propertiesInternal != null);\n                    return _propertiesInternal;\n                }\n                return virtualProperties.AsArray();\n            }\n        }\n\n        public string PropertyName\n        {\n            get { return _propertyName; }\n        }\n\n        protected ModelMetadataProvider Provider { get; set; }\n\n        internal Type RealModelType\n        {\n            get\n            {\n                if (_realModelType == null)\n                {\n                    _realModelType = ModelType;\n\n                    // Don't call GetType() if the model is Nullable<T>, because it will\n                    // turn Nullable<T> into T for non-null values\n                    if (Model != null && !TypeHelpers.IsNullableValueType(ModelType))\n                    {\n                        _realModelType = Model.GetType();\n                    }\n                }\n\n                return _realModelType;\n            }\n        }\n\n        public virtual bool RequestValidationEnabled\n        {\n            get { return _requestValidationEnabled; }\n            set { _requestValidationEnabled = value; }\n        }\n\n        public virtual string ShortDisplayName { get; set; }\n\n        public virtual bool ShowForDisplay\n        {\n            get { return _showForDisplay; }\n            set { _showForDisplay = value; }\n        }\n\n        public virtual bool ShowForEdit\n        {\n            get { return _showForEdit; }\n            set { _showForEdit = value; }\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1721:PropertyNamesShouldNotMatchGetMethods\", Justification = \"This property delegates to the method when the user has not yet set a simple display text value.\")]\n        public virtual string SimpleDisplayText\n        {\n            get\n            {\n                if (_simpleDisplayText == null)\n                {\n                    _simpleDisplayText = GetSimpleDisplayText();\n                }\n                return _simpleDisplayText;\n            }\n            set { _simpleDisplayText = value; }\n        }\n\n        public virtual string TemplateHint { get; set; }\n\n        public virtual string Watermark { get; set; }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This is an appropriate nesting of generic types\")]\n        public static ModelMetadata FromLambdaExpression<TParameter, TValue>(Expression<Func<TParameter, TValue>> expression,\n                                                                             ViewDataDictionary<TParameter> viewData)\n        {\n            return FromLambdaExpression(expression, viewData, metadataProvider: null);\n        }\n\n        internal static ModelMetadata FromLambdaExpression<TParameter, TValue>(Expression<Func<TParameter, TValue>> expression,\n                                                                               ViewDataDictionary<TParameter> viewData,\n                                                                               ModelMetadataProvider metadataProvider)\n        {\n            if (expression == null)\n            {\n                throw new ArgumentNullException(\"expression\");\n            }\n            if (viewData == null)\n            {\n                throw new ArgumentNullException(\"viewData\");\n            }\n\n            string propertyName = null;\n            Type containerType = null;\n            bool legalExpression = false;\n\n            // Need to verify the expression is valid; it needs to at least end in something\n            // that we can convert to a meaningful string for model binding purposes\n\n            switch (expression.Body.NodeType)\n            {\n                case ExpressionType.ArrayIndex:\n                    // ArrayIndex always means a single-dimensional indexer; multi-dimensional indexer is a method call to Get()\n                    legalExpression = true;\n                    break;\n\n                case ExpressionType.Call:\n                    // Only legal method call is a single argument indexer/DefaultMember call\n                    legalExpression = ExpressionHelper.IsSingleArgumentIndexer(expression.Body);\n                    break;\n\n                case ExpressionType.MemberAccess:\n                    // Property/field access is always legal\n                    MemberExpression memberExpression = (MemberExpression)expression.Body;\n                    propertyName = memberExpression.Member is PropertyInfo ? memberExpression.Member.Name : null;\n                    containerType = memberExpression.Expression.Type;\n                    legalExpression = true;\n                    break;\n\n                case ExpressionType.Parameter:\n                    // Parameter expression means \"model => model\", so we delegate to FromModel\n                    return FromModel(viewData, metadataProvider);\n            }\n\n            if (!legalExpression)\n            {\n                throw new InvalidOperationException(MvcResources.TemplateHelpers_TemplateLimitations);\n            }\n\n            TParameter container = viewData.Model;\n            Func<object> modelAccessor = () =>\n            {\n                try\n                {\n                    return CachedExpressionCompiler.Process(expression)(container);\n                }\n                catch (NullReferenceException)\n                {\n                    return null;\n                }\n            };\n\n            return GetMetadataFromProvider(modelAccessor, typeof(TValue), propertyName, container, containerType, metadataProvider);\n        }\n\n        private static ModelMetadata FromModel(ViewDataDictionary viewData, ModelMetadataProvider metadataProvider)\n        {\n            return viewData.ModelMetadata ?? GetMetadataFromProvider(null, typeof(string), null, null, null, metadataProvider);\n        }\n\n        public static ModelMetadata FromStringExpression(string expression, ViewDataDictionary viewData)\n        {\n            return FromStringExpression(expression, viewData, metadataProvider: null);\n        }\n\n        internal static ModelMetadata FromStringExpression(string expression, ViewDataDictionary viewData, ModelMetadataProvider metadataProvider)\n        {\n            if (expression == null)\n            {\n                throw new ArgumentNullException(\"expression\");\n            }\n            if (viewData == null)\n            {\n                throw new ArgumentNullException(\"viewData\");\n            }\n            if (expression.Length == 0)\n            {\n                // Empty string really means \"model metadata for the current model\"\n                return FromModel(viewData, metadataProvider);\n            }\n\n            ViewDataInfo vdi = viewData.GetViewDataInfo(expression);\n            object container = null;\n            Type containerType = null;\n            Type modelType = null;\n            Func<object> modelAccessor = null;\n            string propertyName = null;\n\n            if (vdi != null)\n            {\n                if (vdi.Container != null)\n                {\n                    container = vdi.Container;\n                    containerType = vdi.Container.GetType();\n                }\n\n                modelAccessor = () => vdi.Value;\n\n                if (vdi.PropertyDescriptor != null)\n                {\n                    propertyName = vdi.PropertyDescriptor.Name;\n                    modelType = vdi.PropertyDescriptor.PropertyType;\n                }\n                else if (vdi.Value != null)\n                {\n                    // We only need to delay accessing properties (for LINQ to SQL)\n                    modelType = vdi.Value.GetType();\n                }\n            }\n            else if (viewData.ModelMetadata != null)\n            {\n                //  Try getting a property from ModelMetadata if we couldn't find an answer in ViewData\n                ModelMetadata propertyMetadata = viewData.ModelMetadata.Properties.Where(p => p.PropertyName == expression).FirstOrDefault();\n                if (propertyMetadata != null)\n                {\n                    return propertyMetadata;\n                }\n            }\n\n            return GetMetadataFromProvider(modelAccessor, modelType ?? typeof(string), propertyName, container, containerType, metadataProvider);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Justification = \"The method is a delegating helper to choose among multiple property values\")]\n        public string GetDisplayName()\n        {\n            return DisplayName ?? PropertyName ?? ModelType.Name;\n        }\n\n        private static ModelMetadata GetMetadataFromProvider(Func<object> modelAccessor, Type modelType, string propertyName, object container, Type containerType, ModelMetadataProvider metadataProvider)\n        {\n            metadataProvider = metadataProvider ?? ModelMetadataProviders.Current;\n            if (containerType != null && !String.IsNullOrEmpty(propertyName))\n            {\n                ModelMetadata metadata = metadataProvider.GetMetadataForProperty(modelAccessor, containerType, propertyName);\n                if (metadata != null)\n                {\n                    metadata.Container = container;\n                }\n                return metadata;\n            }\n            return metadataProvider.GetMetadataForType(modelAccessor, modelType);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Justification = \"This method is used to resolve the simple display text when it was not explicitly set through other means.\")]\n        protected virtual string GetSimpleDisplayText()\n        {\n            if (Model == null)\n            {\n                return NullDisplayText;\n            }\n\n            string toStringResult = Convert.ToString(Model, CultureInfo.CurrentCulture);\n            if (toStringResult == null)\n            {\n                return String.Empty;\n            }\n\n            if (!toStringResult.Equals(Model.GetType().FullName, StringComparison.Ordinal))\n            {\n                return toStringResult;\n            }\n\n            ModelMetadata firstProperty = Properties.FirstOrDefault();\n            if (firstProperty == null)\n            {\n                return String.Empty;\n            }\n\n            if (firstProperty.Model == null)\n            {\n                return firstProperty.NullDisplayText;\n            }\n\n            return Convert.ToString(firstProperty.Model, CultureInfo.CurrentCulture);\n        }\n\n        public virtual IEnumerable<ModelValidator> GetValidators(ControllerContext context)\n        {\n            return ModelValidatorProviders.Providers.GetValidators(this, context);\n        }\n\n        private static ModelMetadata[] SortProperties(ModelMetadata[] properties)\n        {\n            // Performance-senstive\n            // Common case is that properties do not need sorting\n            int? previousOrder = null;\n            bool needSort = false;\n            for (int i = 0; i < properties.Length; i++)\n            {\n                ModelMetadata metadata = properties[i];\n                if (previousOrder != null && previousOrder > metadata.Order)\n                {\n                    needSort = true;\n                    break;\n                }\n                previousOrder = metadata.Order;\n            }\n            if (!needSort)\n            {\n                return properties;\n            }\n            // For compatibility the sort must be stable so use OrderBy rather than Array.Sort\n            return properties.OrderBy(m => m.Order).ToArray();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ModelMetadataProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Mvc\n{\n    public abstract class ModelMetadataProvider\n    {\n        public abstract IEnumerable<ModelMetadata> GetMetadataForProperties(object container, Type containerType);\n\n        public abstract ModelMetadata GetMetadataForProperty(Func<object> modelAccessor, Type containerType, string propertyName);\n\n        public abstract ModelMetadata GetMetadataForType(Func<object> modelAccessor, Type modelType);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ModelMetadataProviders.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public class ModelMetadataProviders\n    {\n        private static ModelMetadataProviders _instance = new ModelMetadataProviders();\n        private ModelMetadataProvider _currentProvider;\n        private IResolver<ModelMetadataProvider> _resolver;\n\n        internal ModelMetadataProviders(IResolver<ModelMetadataProvider> resolver = null)\n        {\n            _resolver = resolver ?? new SingleServiceResolver<ModelMetadataProvider>(\n                                        () => _currentProvider,\n                                        new CachedDataAnnotationsModelMetadataProvider(),\n                                        \"ModelMetadataProviders.Current\");\n        }\n\n        public static ModelMetadataProvider Current\n        {\n            get { return _instance.CurrentInternal; }\n            set { _instance.CurrentInternal = value; }\n        }\n\n        internal ModelMetadataProvider CurrentInternal\n        {\n            get { return _resolver.Current; }\n            set { _currentProvider = value ?? new EmptyModelMetadataProvider(); }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ModelState.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    [Serializable]\n    public class ModelState\n    {\n        private ModelErrorCollection _errors = new ModelErrorCollection();\n\n        public ValueProviderResult Value { get; set; }\n\n        public ModelErrorCollection Errors\n        {\n            get { return _errors; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ModelStateDictionary.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace System.Web.Mvc\n{\n    [Serializable]\n    public class ModelStateDictionary : IDictionary<string, ModelState>\n    {\n        private readonly IDictionary<string, ModelState> _innerDictionary;\n\n        public ModelStateDictionary()\n        {\n            _innerDictionary = new Dictionary<string, ModelState>(StringComparer.OrdinalIgnoreCase);\n        }\n\n        public ModelStateDictionary(ModelStateDictionary dictionary)\n        {\n            if (dictionary == null)\n            {\n                throw new ArgumentNullException(\"dictionary\");\n            }\n\n            _innerDictionary = new CopyOnWriteDictionary<string, ModelState>(dictionary,\n                                                                             StringComparer.OrdinalIgnoreCase);\n        }\n\n        public int Count\n        {\n            get { return _innerDictionary.Count; }\n        }\n\n        public bool IsReadOnly\n        {\n            get { return _innerDictionary.IsReadOnly; }\n        }\n\n        public bool IsValid\n        {\n            get { return Values.All(modelState => modelState.Errors.Count == 0); }\n        }\n\n        public ICollection<string> Keys\n        {\n            get { return _innerDictionary.Keys; }\n        }\n\n        public ICollection<ModelState> Values\n        {\n            get { return _innerDictionary.Values; }\n        }\n\n        public ModelState this[string key]\n        {\n            get\n            {\n                ModelState value;\n                _innerDictionary.TryGetValue(key, out value);\n                return value;\n            }\n            set { _innerDictionary[key] = value; }\n        }\n\n        // For unit testing\n        internal IDictionary<string, ModelState> InnerDictionary\n        {\n            get { return _innerDictionary; }\n        }\n\n        public void Add(KeyValuePair<string, ModelState> item)\n        {\n            _innerDictionary.Add(item);\n        }\n\n        public void Add(string key, ModelState value)\n        {\n            _innerDictionary.Add(key, value);\n        }\n\n        public void AddModelError(string key, Exception exception)\n        {\n            GetModelStateForKey(key).Errors.Add(exception);\n        }\n\n        public void AddModelError(string key, string errorMessage)\n        {\n            GetModelStateForKey(key).Errors.Add(errorMessage);\n        }\n\n        public void Clear()\n        {\n            _innerDictionary.Clear();\n        }\n\n        public bool Contains(KeyValuePair<string, ModelState> item)\n        {\n            return _innerDictionary.Contains(item);\n        }\n\n        public bool ContainsKey(string key)\n        {\n            return _innerDictionary.ContainsKey(key);\n        }\n\n        public void CopyTo(KeyValuePair<string, ModelState>[] array, int arrayIndex)\n        {\n            _innerDictionary.CopyTo(array, arrayIndex);\n        }\n\n        public IEnumerator<KeyValuePair<string, ModelState>> GetEnumerator()\n        {\n            return _innerDictionary.GetEnumerator();\n        }\n\n        private ModelState GetModelStateForKey(string key)\n        {\n            if (key == null)\n            {\n                throw new ArgumentNullException(\"key\");\n            }\n\n            ModelState modelState;\n            if (!TryGetValue(key, out modelState))\n            {\n                modelState = new ModelState();\n                this[key] = modelState;\n            }\n\n            return modelState;\n        }\n\n        public bool IsValidField(string key)\n        {\n            if (key == null)\n            {\n                throw new ArgumentNullException(\"key\");\n            }\n\n            // if the key is not found in the dictionary, we just say that it's valid (since there are no errors)\n            return DictionaryHelpers.FindKeysWithPrefix(this, key).All(entry => entry.Value.Errors.Count == 0);\n        }\n\n        public void Merge(ModelStateDictionary dictionary)\n        {\n            if (dictionary == null)\n            {\n                return;\n            }\n\n            foreach (var entry in dictionary)\n            {\n                this[entry.Key] = entry.Value;\n            }\n        }\n\n        public bool Remove(KeyValuePair<string, ModelState> item)\n        {\n            return _innerDictionary.Remove(item);\n        }\n\n        public bool Remove(string key)\n        {\n            return _innerDictionary.Remove(key);\n        }\n\n        public void SetModelValue(string key, ValueProviderResult value)\n        {\n            GetModelStateForKey(key).Value = value;\n        }\n\n        public bool TryGetValue(string key, out ModelState value)\n        {\n            return _innerDictionary.TryGetValue(key, out value);\n        }\n\n        #region IEnumerable Members\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return GetEnumerator();\n        }\n\n        #endregion\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ModelValidationResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public class ModelValidationResult\n    {\n        private string _memberName;\n        private string _message;\n\n        public string MemberName\n        {\n            get { return _memberName ?? String.Empty; }\n            set { _memberName = value; }\n        }\n\n        public string Message\n        {\n            get { return _message ?? String.Empty; }\n            set { _message = value; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ModelValidator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\n\nnamespace System.Web.Mvc\n{\n    public abstract class ModelValidator\n    {\n        protected ModelValidator(ModelMetadata metadata, ControllerContext controllerContext)\n        {\n            if (metadata == null)\n            {\n                throw new ArgumentNullException(\"metadata\");\n            }\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n\n            Metadata = metadata;\n            ControllerContext = controllerContext;\n        }\n\n        protected internal ControllerContext ControllerContext { get; private set; }\n\n        public virtual bool IsRequired\n        {\n            get { return false; }\n        }\n\n        protected internal ModelMetadata Metadata { get; private set; }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Justification = \"This method may perform non-trivial work.\")]\n        public virtual IEnumerable<ModelClientValidationRule> GetClientValidationRules()\n        {\n            return Enumerable.Empty<ModelClientValidationRule>();\n        }\n\n        public static ModelValidator GetModelValidator(ModelMetadata metadata, ControllerContext context)\n        {\n            return new CompositeModelValidator(metadata, context);\n        }\n\n        public abstract IEnumerable<ModelValidationResult> Validate(object container);\n\n        private class CompositeModelValidator : ModelValidator\n        {\n            public CompositeModelValidator(ModelMetadata metadata, ControllerContext controllerContext)\n                : base(metadata, controllerContext)\n            {\n            }\n\n            private static ModelValidationResult CreateSubPropertyResult(ModelMetadata propertyMetadata, ModelValidationResult propertyResult)\n            {\n                return new ModelValidationResult\n                {\n                    MemberName = DefaultModelBinder.CreateSubPropertyName(propertyMetadata.PropertyName, propertyResult.MemberName),\n                    Message = propertyResult.Message\n                };\n            }\n\n            public override IEnumerable<ModelValidationResult> Validate(object container)\n            {\n                bool propertiesValid = true;\n\n                ModelMetadata[] properties = Metadata.PropertiesAsArray;\n\n                // Performance sensitive loops\n                for (int propertyIndex = 0; propertyIndex < properties.Length; propertyIndex++)\n                {\n                    ModelMetadata propertyMetadata = properties[propertyIndex];\n                    foreach (ModelValidator propertyValidator in propertyMetadata.GetValidators(ControllerContext))\n                    {\n                        foreach (ModelValidationResult propertyResult in propertyValidator.Validate(Metadata.Model))\n                        {\n                            propertiesValid = false;\n                            yield return CreateSubPropertyResult(propertyMetadata, propertyResult);\n                        }\n                    }\n                }\n\n                if (propertiesValid)\n                {\n                    foreach (ModelValidator typeValidator in Metadata.GetValidators(ControllerContext))\n                    {\n                        foreach (ModelValidationResult typeResult in typeValidator.Validate(container))\n                        {\n                            yield return typeResult;\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ModelValidatorProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Mvc\n{\n    public abstract class ModelValidatorProvider\n    {\n        public abstract IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ModelValidatorProviderCollection.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\n\nnamespace System.Web.Mvc\n{\n    public class ModelValidatorProviderCollection : Collection<ModelValidatorProvider>\n    {\n        private ModelValidatorProvider[] _combinedItems;\n        private IDependencyResolver _dependencyResolver;\n\n        public ModelValidatorProviderCollection()\n        {\n        }\n\n        public ModelValidatorProviderCollection(IList<ModelValidatorProvider> list)\n            : base(list)\n        {\n        }\n\n        internal ModelValidatorProviderCollection(IList<ModelValidatorProvider> list, IDependencyResolver dependencyResolver)\n            : base(list)\n        {\n            _dependencyResolver = dependencyResolver;\n        }\n\n        internal ModelValidatorProvider[] CombinedItems\n        {\n            get \n            {\n                ModelValidatorProvider[] combinedItems = _combinedItems;\n                if (combinedItems == null)\n                {\n                    combinedItems = MultiServiceResolver.GetCombined<ModelValidatorProvider>(Items, _dependencyResolver);\n                    _combinedItems = combinedItems;\n                }\n                return combinedItems;\n            }\n        }\n\n        protected override void ClearItems()\n        {\n            _combinedItems = null;\n            base.ClearItems();\n        }\n\n        protected override void InsertItem(int index, ModelValidatorProvider item)\n        {\n            if (item == null)\n            {\n                throw new ArgumentNullException(\"item\");\n            }\n            _combinedItems = null;\n            base.InsertItem(index, item);\n        }\n\n        protected override void RemoveItem(int index)\n        {\n            _combinedItems = null;\n            base.RemoveItem(index);\n        }\n\n        protected override void SetItem(int index, ModelValidatorProvider item)\n        {\n            if (item == null)\n            {\n                throw new ArgumentNullException(\"item\");\n            }\n            _combinedItems = null;\n            base.SetItem(index, item);\n        }\n\n        public IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context)\n        {\n            ModelValidatorProvider[] combined = CombinedItems;\n            for (int i = 0; i < combined.Length; i++)\n            {\n                ModelValidatorProvider provider = combined[i];\n                foreach (ModelValidator validator in provider.GetValidators(metadata, context))\n                {\n                    yield return validator;\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ModelValidatorProviders.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public static class ModelValidatorProviders\n    {\n        private static readonly ModelValidatorProviderCollection _providers = new ModelValidatorProviderCollection()\n        {\n            new DataAnnotationsModelValidatorProvider(),\n            new DataErrorInfoModelValidatorProvider(),\n            new ClientDataTypeModelValidatorProvider()\n        };\n\n        public static ModelValidatorProviderCollection Providers\n        {\n            get { return _providers; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/MultiSelectList.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq;\nusing System.Linq.Expressions;\nusing System.Web.UI;\n\nnamespace System.Web.Mvc\n{\n    [SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"Multi\", Justification = \"FxCop won't accept this in the custom dictionary, so we're suppressing it in source\")]\n    [SuppressMessage(\"Microsoft.Naming\", \"CA1710:IdentifiersShouldHaveCorrectSuffix\", Justification = \"This is a shipped API\")]\n    public class MultiSelectList : IEnumerable<SelectListItem>\n    {\n        private IList<SelectListGroup> _groups;\n\n        public MultiSelectList(IEnumerable items)\n            : this(items, selectedValues: null)\n        {\n        }\n\n        public MultiSelectList(IEnumerable items, IEnumerable selectedValues)\n            : this(items, dataValueField: null, dataTextField: null, selectedValues: selectedValues)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the MultiSelectList class by using the items to include in the list, \n        /// the selected values, the disabled values.\n        /// </summary>\n        /// <param name=\"items\">The items used to build each <see cref=\"SelectListItem\"/> of the list.</param>\n        /// <param name=\"selectedValues\">The selected values field. Used to match the Selected property of the \n        /// corresponding <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"disabledValues\">The disabled values. Used to match the Disabled property of the corresponding\n        /// <see cref=\"SelectListItem\"/>.</param>>\n        public MultiSelectList(IEnumerable items, IEnumerable selectedValues, IEnumerable disabledValues)\n            : this(items,\n                   dataValueField: null,\n                   dataTextField: null,\n                   selectedValues: selectedValues,\n                   disabledValues: disabledValues)\n        {\n        }\n\n        public MultiSelectList(IEnumerable items, string dataValueField, string dataTextField)\n            : this(items, dataValueField, dataTextField, selectedValues: null)\n        {\n        }\n\n        public MultiSelectList(IEnumerable items, string dataValueField, string dataTextField, IEnumerable selectedValues)\n            : this(items, dataValueField, dataTextField, dataGroupField: null, selectedValues: selectedValues)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the MultiSelectList class by using the items to include in the list, \n        /// the data value field, the data text field, and the data group field.\n        /// </summary>\n        /// <param name=\"items\">The items used to build each <see cref=\"SelectListItem\"/> of the list.</param>\n        /// <param name=\"dataValueField\">The data value field. Used to match the Value property of the corresponding \n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"dataTextField\">The data text field. Used to match the Text property of the corresponding \n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"dataGroupField\">The data group field. Used to match the Group property of the corresponding \n        /// <see cref=\"SelectListItem\"/>.</param>\n        public MultiSelectList(IEnumerable items, string dataValueField, string dataTextField, string dataGroupField)\n            : this(items, dataValueField, dataTextField, dataGroupField: dataGroupField, selectedValues: null)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the MultiSelectList class by using the items to include in the list, \n        /// the data value field, the data text field, the selected values, and the disabled values.\n        /// </summary>\n        /// <param name=\"items\">The items used to build each <see cref=\"SelectListItem\"/> of the list.</param>\n        /// <param name=\"dataValueField\">The data value field. Used to match the Value property of the corresponding \n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"dataTextField\">The data text field. Used to match the Text property of the corresponding \n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"selectedValues\">The selected values field. Used to match the Selected property of the \n        /// corresponding <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"disabledValues\">The disabled values. Used to match the Disabled property of the corresponding\n        /// <see cref=\"SelectListItem\"/>.</param>>\n        public MultiSelectList(IEnumerable items,\n                               string dataValueField,\n                               string dataTextField,\n                               IEnumerable selectedValues,\n                               IEnumerable disabledValues)\n            : this(items,\n                   dataValueField,\n                   dataTextField,\n                   dataGroupField: null,\n                   selectedValues: selectedValues,\n                   disabledValues: disabledValues)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the MultiSelectList class by using the items to include in the list, \n        /// the data value field, the data text field, the data group field, and the selected values.\n        /// </summary>\n        /// <param name=\"items\">The items used to build each <see cref=\"SelectListItem\"/> of the list.</param>\n        /// <param name=\"dataValueField\">The data value field. Used to match the Value property of the corresponding \n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"dataTextField\">The data text field. Used to match the Text property of the corresponding \n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"dataGroupField\">The data group field. Used to match the Group property of the corresponding \n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"selectedValues\">The selected values field. Used to match the Selected property of the \n        /// corresponding <see cref=\"SelectListItem\"/>.</param>\n        public MultiSelectList(IEnumerable items,\n                               string dataValueField,\n                               string dataTextField,\n                               string dataGroupField,\n                               IEnumerable selectedValues)\n            : this(items, dataValueField, dataTextField, dataGroupField, selectedValues, disabledValues: null)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the MultiSelectList class by using the items to include in the list,\n        /// the data value field, the data text field, the data group field, the selected values, and the disabled\n        /// values.\n        /// </summary>\n        /// <param name=\"items\">The items used to build each <see cref=\"SelectListItem\"/> of the list.</param>\n        /// <param name=\"dataValueField\">The data value field. Used to match the Value property of the corresponding \n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"dataTextField\">The data text field. Used to match the Text property of the corresponding \n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"dataGroupField\">The data group field. Used to match the Group property of the corresponding \n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"selectedValues\">The selected values field. Used to match the Selected property of the \n        /// corresponding <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"disabledValues\">The disabled values. Used to match the Disabled property of the corresponding\n        /// <see cref=\"SelectListItem\"/>.</param>\n        public MultiSelectList(IEnumerable items,\n                               string dataValueField,\n                               string dataTextField,\n                               string dataGroupField,\n                               IEnumerable selectedValues,\n                               IEnumerable disabledValues)\n            : this(items,\n                   dataValueField,\n                   dataTextField,\n                   dataGroupField,\n                   selectedValues,\n                   disabledValues,\n                   disabledGroups: null)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the MultiSelectList class by using the items to include in the list, \n        /// the data value field, the data text field, the data group field, the selected values, the disabled values,\n        /// and the disabled groups.\n        /// </summary>\n        /// <param name=\"items\">The items used to build each <see cref=\"SelectListItem\"/> of the list.</param>\n        /// <param name=\"dataValueField\">The data value field. Used to match the Value property of the corresponding \n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"dataTextField\">The data text field. Used to match the Text property of the corresponding \n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"dataGroupField\">The data group field. Used to match the Group property of the corresponding \n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"selectedValues\">The selected values field. Used to match the Selected property of the \n        /// corresponding <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"disabledValues\">The disabled values. Used to match the Disabled property of the corresponding\n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"disabledGroups\">The disabled groups. Used to match the Disabled property of the corresponding\n        /// <see cref=\"SelectListGroup\"/>.</param>\n        public MultiSelectList(IEnumerable items,\n                               string dataValueField,\n                               string dataTextField,\n                               string dataGroupField,\n                               IEnumerable selectedValues,\n                               IEnumerable disabledValues,\n                               IEnumerable disabledGroups)\n        {\n            if (items == null)\n            {\n                throw new ArgumentNullException(\"items\");\n            }\n\n            Items = items;\n            DataValueField = dataValueField;\n            DataTextField = dataTextField;\n            SelectedValues = selectedValues;\n            DataGroupField = dataGroupField;\n            DisabledValues = disabledValues;\n            DisabledGroups = disabledGroups;\n\n            if (DataGroupField != null)\n            {\n                _groups = new List<SelectListGroup>();\n            }\n        }\n\n        /// <summary>\n        /// Gets the data group field.\n        /// </summary>\n        public string DataGroupField { get; private set; }\n\n        public string DataTextField { get; private set; }\n\n        public string DataValueField { get; private set; }\n\n        /// <summary>\n        /// Gets the disabled groups.\n        /// </summary>\n        public IEnumerable DisabledGroups { get; private set; }\n\n        /// <summary>\n        /// Gets the disabled values.\n        /// </summary>\n        public IEnumerable DisabledValues { get; private set; }\n\n        public IEnumerable Items { get; private set; }\n\n        public IEnumerable SelectedValues { get; private set; }\n\n        public virtual IEnumerator<SelectListItem> GetEnumerator()\n        {\n            return GetListItems().GetEnumerator();\n        }\n\n        internal IList<SelectListItem> GetListItems()\n        {\n            return (!String.IsNullOrEmpty(DataValueField))\n                       ? GetListItemsWithValueField()\n                       : GetListItemsWithoutValueField();\n        }\n\n        private IList<SelectListItem> GetListItemsWithValueField()\n        {\n            HashSet<string> selectedValues = GetStringHashSet(SelectedValues);\n            HashSet<string> disabledValues = GetStringHashSet(DisabledValues);\n            HashSet<string> disabledGroups = GetStringHashSet(DisabledGroups);\n\n            IEnumerable<SelectListItem> listItems = Items.Cast<object>().Select(item =>\n            {\n                string value = Eval(item, DataValueField);\n                return new SelectListItem\n                {\n                    Group = GetGroup(item, disabledGroups),\n                    Value = value,\n                    Text = Eval(item, DataTextField),\n                    Selected = selectedValues.Contains(value),\n                    Disabled = disabledValues.Contains(value),\n                };\n            });\n\n            return listItems.ToList();\n        }\n\n        private IList<SelectListItem> GetListItemsWithoutValueField()\n        {\n            HashSet<object> selectedValues = GetObjectHashSet(SelectedValues);\n            HashSet<object> disabledValues = GetObjectHashSet(DisabledValues);\n            HashSet<string> disabledGroups = GetStringHashSet(DisabledGroups);\n\n            IEnumerable<SelectListItem> listItems = Items.Cast<object>().Select(item =>\n            {\n                return new SelectListItem\n                {\n                    Group = GetGroup(item, disabledGroups),\n                    Text = Eval(item, DataTextField),\n                    Selected = selectedValues.Contains(item),\n                    Disabled = disabledValues.Contains(item),\n                };\n            });\n\n            return listItems.ToList();\n        }\n\n        private static string Eval(object container, string expression)\n        {\n            object value = container;\n            if (!String.IsNullOrEmpty(expression))\n            {\n                value = DataBinder.Eval(container, expression);\n            }\n            return Convert.ToString(value, CultureInfo.CurrentCulture);\n        }\n\n        private SelectListGroup GetGroup(object container, HashSet<string> disabledGroups)\n        {\n            if (_groups == null)\n            {\n                return null;\n            }\n\n            string groupName = Eval(container, DataGroupField);\n            if (String.IsNullOrEmpty(groupName))\n            {\n                return null;\n            }\n\n            // We use StringComparison.CurrentCulture because the group name is used to display as the value of \n            // optgroup HTML tag's label attribute.\n            SelectListGroup group = _groups.FirstOrDefault(\n                g => String.Equals(g.Name, groupName, StringComparison.CurrentCulture));\n            if (group == null)\n            {\n                group = new SelectListGroup() { Name = groupName, Disabled = disabledGroups.Contains(groupName) };\n                _groups.Add(group);\n            }\n\n            return group;\n        }\n\n        private static HashSet<string> GetStringHashSet(IEnumerable values)\n        {\n            HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);\n            if (values != null)\n            {\n                hashSet.UnionWith(\n                    values.Cast<object>().Select(value => Convert.ToString(value, CultureInfo.CurrentCulture)));\n            }\n            return hashSet;\n        }\n\n        private static HashSet<object> GetObjectHashSet(IEnumerable values)\n        {\n            HashSet<object> hashSet = new HashSet<object>();\n            if (values != null)\n            {\n                hashSet.UnionWith(values.Cast<object>());\n            }\n            return hashSet;\n        }\n\n        #region IEnumerable Members\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return GetEnumerator();\n        }\n\n        #endregion\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/MultiServiceResolver.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace System.Web.Mvc\n{\n    internal static class MultiServiceResolver        \n    {\n        internal static TService[] GetCombined<TService>(IList<TService> items, IDependencyResolver resolver = null) where TService : class\n        {           \n            if (resolver == null)\n            {\n                resolver = DependencyResolver.Current;\n            }\n            IEnumerable<TService> services = resolver.GetServices<TService>();\n            return services.Concat(items).ToArray();\n        } \n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/MvcFilter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public abstract class MvcFilter : IMvcFilter\n    {\n        protected MvcFilter()\n        {\n        }\n\n        protected MvcFilter(bool allowMultiple, int order)\n        {\n            AllowMultiple = allowMultiple;\n            Order = order;\n        }\n\n        public bool AllowMultiple { get; private set; }\n\n        public int Order { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/MvcHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Reflection;\nusing System.Threading;\nusing System.Web.Mvc.Async;\nusing System.Web.Mvc.Properties;\nusing System.Web.Routing;\nusing System.Web.SessionState;\nusing Microsoft.Web.Infrastructure.DynamicValidationHelper;\n\nnamespace System.Web.Mvc\n{\n    public class MvcHandler : IHttpAsyncHandler, IHttpHandler, IRequiresSessionState\n    {\n        private static readonly object _processRequestTag = new object();\n\n        internal static readonly string MvcVersion = GetMvcVersionString();\n        public static readonly string MvcVersionHeaderName = \"X-AspNetMvc-Version\";\n        private ControllerBuilder _controllerBuilder;\n\n        public MvcHandler(RequestContext requestContext)\n        {\n            if (requestContext == null)\n            {\n                throw new ArgumentNullException(\"requestContext\");\n            }\n\n            RequestContext = requestContext;\n        }\n\n        internal ControllerBuilder ControllerBuilder\n        {\n            get\n            {\n                if (_controllerBuilder == null)\n                {\n                    _controllerBuilder = ControllerBuilder.Current;\n                }\n                return _controllerBuilder;\n            }\n            set { _controllerBuilder = value; }\n        }\n\n        public static bool DisableMvcResponseHeader { get; set; }\n\n        protected virtual bool IsReusable\n        {\n            get { return false; }\n        }\n\n        public RequestContext RequestContext { get; private set; }\n\n        protected internal virtual void AddVersionHeader(HttpContextBase httpContext)\n        {\n            if (!DisableMvcResponseHeader)\n            {\n                httpContext.Response.AppendHeader(MvcVersionHeaderName, MvcVersion);\n            }\n        }\n\n        protected virtual IAsyncResult BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, object state)\n        {\n            HttpContextBase httpContextBase = new HttpContextWrapper(httpContext);\n            return BeginProcessRequest(httpContextBase, callback, state);\n        }\n\n        protected internal virtual IAsyncResult BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, object state)\n        {\n            IController controller;\n            IControllerFactory factory;\n            ProcessRequestInit(httpContext, out controller, out factory);\n\n            IAsyncController asyncController = controller as IAsyncController;\n            if (asyncController != null)\n            {\n                // asynchronous controller\n\n                // Ensure delegates continue to use the C# Compiler static delegate caching optimization.\n                BeginInvokeDelegate<ProcessRequestState> beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState, ProcessRequestState innerState)\n                {\n                    try\n                    {\n                        return innerState.AsyncController.BeginExecute(innerState.RequestContext, asyncCallback, asyncState);\n                    }\n                    catch\n                    {\n                        innerState.ReleaseController();\n                        throw;\n                    }\n                };\n\n                EndInvokeVoidDelegate<ProcessRequestState> endDelegate = delegate(IAsyncResult asyncResult, ProcessRequestState innerState)\n                {\n                    try\n                    {\n                        innerState.AsyncController.EndExecute(asyncResult);\n                    }\n                    finally\n                    {\n                        innerState.ReleaseController();\n                    }\n                };\n                ProcessRequestState outerState = new ProcessRequestState() \n                {\n                    AsyncController = asyncController, Factory = factory, RequestContext = RequestContext\n                };\n                \n                SynchronizationContext callbackSyncContext = SynchronizationContextUtil.GetSynchronizationContext();\n                return AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, outerState, _processRequestTag, callbackSyncContext: callbackSyncContext);\n            }\n            else\n            {\n                // synchronous controller\n                Action action = delegate\n                {\n                    try\n                    {\n                        controller.Execute(RequestContext);\n                    }\n                    finally\n                    {\n                        factory.ReleaseController(controller);\n                    }\n                };\n\n                return AsyncResultWrapper.BeginSynchronous(callback, state, action, _processRequestTag);\n            }\n        }\n\n        protected internal virtual void EndProcessRequest(IAsyncResult asyncResult)\n        {\n            AsyncResultWrapper.End(asyncResult, _processRequestTag);\n        }\n\n        private static string GetMvcVersionString()\n        {\n            // DevDiv 216459:\n            // This code originally used Assembly.GetName(), but that requires FileIOPermission, which isn't granted in\n            // medium trust. However, Assembly.FullName *is* accessible in medium trust.\n            return new AssemblyName(typeof(MvcHandler).Assembly.FullName).Version.ToString(2);\n        }\n\n        protected virtual void ProcessRequest(HttpContext httpContext)\n        {\n            HttpContextBase httpContextBase = new HttpContextWrapper(httpContext);\n            ProcessRequest(httpContextBase);\n        }\n\n        protected internal virtual void ProcessRequest(HttpContextBase httpContext)\n        {\n            IController controller;\n            IControllerFactory factory;\n            ProcessRequestInit(httpContext, out controller, out factory);\n\n            try\n            {\n                controller.Execute(RequestContext);\n            }\n            finally\n            {\n                factory.ReleaseController(controller);\n            }\n        }\n\n        private void ProcessRequestInit(HttpContextBase httpContext, out IController controller, out IControllerFactory factory)\n        {\n            // If request validation has already been enabled, make it lazy. This allows attributes like [HttpPost] (which looks\n            // at Request.Form) to work correctly without triggering full validation.\n            // Tolerate null HttpContext for testing.\n            HttpContext currentContext = HttpContext.Current;\n            if (currentContext != null)\n            {\n                bool? isRequestValidationEnabled = ValidationUtility.IsValidationEnabled(currentContext);\n                if (isRequestValidationEnabled == true)\n                {\n                    ValidationUtility.EnableDynamicValidation(currentContext);\n                }\n            }\n\n            AddVersionHeader(httpContext);\n            RemoveOptionalRoutingParameters();\n\n            // Get the controller type\n            string controllerName = RequestContext.RouteData.GetRequiredString(\"controller\");\n\n            // Instantiate the controller and call Execute\n            factory = ControllerBuilder.GetControllerFactory();\n            controller = factory.CreateController(RequestContext, controllerName);\n            if (controller == null)\n            {\n                throw new InvalidOperationException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.ControllerBuilder_FactoryReturnedNull,\n                        factory.GetType(),\n                        controllerName));\n            }\n        }\n\n        private void RemoveOptionalRoutingParameters()\n        {\n            RouteValueDictionary rvd = RequestContext.RouteData.Values;\n\n            // Ensure delegate is stateless\n            rvd.RemoveFromDictionary((entry) => entry.Value == UrlParameter.Optional);\n        }\n\n        #region IHttpHandler Members\n\n        bool IHttpHandler.IsReusable\n        {\n            get { return IsReusable; }\n        }\n\n        void IHttpHandler.ProcessRequest(HttpContext httpContext)\n        {\n            ProcessRequest(httpContext);\n        }\n\n        #endregion\n\n        #region IHttpAsyncHandler Members\n\n        IAsyncResult IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)\n        {\n            return BeginProcessRequest(context, cb, extraData);\n        }\n\n        void IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)\n        {\n            EndProcessRequest(result);\n        }\n\n        #endregion\n\n        // Keep as value type to avoid allocating\n        private struct ProcessRequestState\n        {\n            internal IAsyncController AsyncController;\n            internal IControllerFactory Factory;\n            internal RequestContext RequestContext;\n\n            internal void ReleaseController()\n            {\n                Factory.ReleaseController(AsyncController);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/MvcHtmlString.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.Mvc\n{\n    public sealed class MvcHtmlString : HtmlString\n    {\n        [SuppressMessage(\"Microsoft.Security\", \"CA2104:DoNotDeclareReadOnlyMutableReferenceTypes\", Justification = \"MvcHtmlString is immutable\")]\n        public static readonly MvcHtmlString Empty = Create(String.Empty);\n\n        private readonly string _value;\n\n        public MvcHtmlString(string value)\n            : base(value ?? String.Empty)\n        {\n            _value = value ?? String.Empty;\n        }\n\n        public static MvcHtmlString Create(string value)\n        {\n            return new MvcHtmlString(value);\n        }\n\n        public static bool IsNullOrEmpty(MvcHtmlString value)\n        {\n            return (value == null || value._value.Length == 0);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/MvcHttpHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc.Async;\nusing System.Web.Routing;\nusing System.Web.SessionState;\n\nnamespace System.Web.Mvc\n{\n    public class MvcHttpHandler : UrlRoutingHandler, IHttpAsyncHandler, IRequiresSessionState\n    {\n        private static readonly object _processRequestTag = new object();\n\n        protected virtual IAsyncResult BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, object state)\n        {\n            HttpContextBase httpContextBase = new HttpContextWrapper(httpContext);\n            return BeginProcessRequest(httpContextBase, callback, state);\n        }\n\n        protected internal virtual IAsyncResult BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, object state)\n        {\n            IHttpHandler httpHandler = GetHttpHandler(httpContext);\n            IHttpAsyncHandler httpAsyncHandler = httpHandler as IHttpAsyncHandler;\n\n            if (httpAsyncHandler != null)\n            {\n                // asynchronous handler\n\n                // Ensure delegates continue to use the C# Compiler static delegate caching optimization.\n                BeginInvokeDelegate<IHttpAsyncHandler> beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState, IHttpAsyncHandler innerHandler)\n                {\n                    return innerHandler.BeginProcessRequest(HttpContext.Current, asyncCallback, asyncState);\n                };\n                EndInvokeVoidDelegate<IHttpAsyncHandler> endDelegate = delegate(IAsyncResult asyncResult, IHttpAsyncHandler innerHandler)\n                {\n                    innerHandler.EndProcessRequest(asyncResult);\n                };\n                return AsyncResultWrapper.Begin(callback, state, beginDelegate, endDelegate, httpAsyncHandler, _processRequestTag);\n            }\n            else\n            {\n                // synchronous handler\n                Action action = delegate\n                {\n                    httpHandler.ProcessRequest(HttpContext.Current);\n                };\n                return AsyncResultWrapper.BeginSynchronous(callback, state, action, _processRequestTag);\n            }\n        }\n\n        protected internal virtual void EndProcessRequest(IAsyncResult asyncResult)\n        {\n            AsyncResultWrapper.End(asyncResult, _processRequestTag);\n        }\n\n        private static IHttpHandler GetHttpHandler(HttpContextBase httpContext)\n        {\n            DummyHttpHandler dummyHandler = new DummyHttpHandler();\n            dummyHandler.PublicProcessRequest(httpContext);\n            return dummyHandler.HttpHandler;\n        }\n\n        // synchronous code\n        protected override void VerifyAndProcessRequest(IHttpHandler httpHandler, HttpContextBase httpContext)\n        {\n            if (httpHandler == null)\n            {\n                throw new ArgumentNullException(\"httpHandler\");\n            }\n\n            httpHandler.ProcessRequest(HttpContext.Current);\n        }\n\n        #region IHttpAsyncHandler Members\n\n        IAsyncResult IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)\n        {\n            return BeginProcessRequest(context, cb, extraData);\n        }\n\n        void IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)\n        {\n            EndProcessRequest(result);\n        }\n\n        #endregion\n\n        // Since UrlRoutingHandler.ProcessRequest() does the heavy lifting of looking at the RouteCollection for\n        // a matching route, we need to call into it. However, that method is also responsible for kicking off\n        // the synchronous request, and we can't allow it to do that. The purpose of this dummy class is to run\n        // only the lookup portion of UrlRoutingHandler.ProcessRequest(), then intercept the handler it returns\n        // and execute it asynchronously.\n\n        private sealed class DummyHttpHandler : UrlRoutingHandler\n        {\n            public IHttpHandler HttpHandler;\n\n            public void PublicProcessRequest(HttpContextBase httpContext)\n            {\n                ProcessRequest(httpContext);\n            }\n\n            protected override void VerifyAndProcessRequest(IHttpHandler httpHandler, HttpContextBase httpContext)\n            {\n                // don't process the request, just store a reference to it\n                HttpHandler = httpHandler;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/MvcRouteHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc.Properties;\nusing System.Web.Routing;\nusing System.Web.SessionState;\n\nnamespace System.Web.Mvc\n{\n    public class MvcRouteHandler : IRouteHandler\n    {\n        private IControllerFactory _controllerFactory;\n\n        public MvcRouteHandler()\n        {\n        }\n\n        public MvcRouteHandler(IControllerFactory controllerFactory)\n        {\n            _controllerFactory = controllerFactory;\n        }\n\n        protected virtual IHttpHandler GetHttpHandler(RequestContext requestContext)\n        {\n            requestContext.HttpContext.SetSessionStateBehavior(GetSessionStateBehavior(requestContext));\n            return new MvcHandler(requestContext);\n        }\n\n        protected virtual SessionStateBehavior GetSessionStateBehavior(RequestContext requestContext)\n        {\n            string controllerName = (string)requestContext.RouteData.Values[\"controller\"];\n            if (String.IsNullOrWhiteSpace(controllerName))\n            {\n                throw new InvalidOperationException(MvcResources.MvcRouteHandler_RouteValuesHasNoController);\n            }\n\n            IControllerFactory controllerFactory = _controllerFactory ?? ControllerBuilder.Current.GetControllerFactory();\n            return controllerFactory.GetControllerSessionBehavior(requestContext, controllerName);\n        }\n\n        #region IRouteHandler Members\n\n        IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)\n        {\n            return GetHttpHandler(requestContext);\n        }\n\n        #endregion\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/MvcWebRazorHostFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc.Razor;\nusing System.Web.WebPages.Razor;\n\nnamespace System.Web.Mvc\n{\n    public class MvcWebRazorHostFactory : WebRazorHostFactory\n    {\n        public override WebPageRazorHost CreateHost(string virtualPath, string physicalPath)\n        {\n            WebPageRazorHost host = base.CreateHost(virtualPath, physicalPath);\n\n            if (!host.IsSpecialPage)\n            {\n                return new MvcWebPageRazorHost(virtualPath, physicalPath);\n            }\n\n            return host;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/NameValueCollectionExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\n\nnamespace System.Web.Mvc\n{\n    public static class NameValueCollectionExtensions\n    {\n        public static void CopyTo(this NameValueCollection collection, IDictionary<string, object> destination)\n        {\n            CopyTo(collection, destination, false /* replaceEntries */);\n        }\n\n        public static void CopyTo(this NameValueCollection collection, IDictionary<string, object> destination, bool replaceEntries)\n        {\n            if (collection == null)\n            {\n                throw new ArgumentNullException(\"collection\");\n            }\n            if (destination == null)\n            {\n                throw new ArgumentNullException(\"destination\");\n            }\n\n            foreach (string key in collection.Keys)\n            {\n                if (replaceEntries || !destination.ContainsKey(key))\n                {\n                    destination[key] = collection[key];\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/NameValueCollectionValueProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Text;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    [SuppressMessage(\"StyleCop.CSharp.NamingRules\",\n                            \"SA1305:FieldNamesMustNotUseHungarianNotation\",\n                            Target = \"jQueryToMvcRequestNormalizationRequired\",\n                            Justification = \"jQuery is usually spelled like this. Hence suppressing this message.\")]\n    public class NameValueCollectionValueProvider : IValueProvider, IUnvalidatedValueProvider, IEnumerableValueProvider\n    {\n        private PrefixContainer _prefixContainer;\n        private NameValueCollection _collection;\n        private NameValueCollection _unvalidatedCollection;\n        private CultureInfo _culture;\n        private bool _jQueryToMvcRequestNormalizationRequired;\n\n        private Dictionary<string, ValueProviderResultPlaceholder> _values = null;\n                \n        public NameValueCollectionValueProvider(NameValueCollection collection, CultureInfo culture)\n            : this(collection, unvalidatedCollection: null, culture: culture)\n        {\n        }\n\n        public NameValueCollectionValueProvider(\n                        NameValueCollection collection, NameValueCollection unvalidatedCollection, CultureInfo culture)\n            : this(collection, unvalidatedCollection, culture, jQueryToMvcRequestNormalizationRequired: false)\n        {\n        }\n\n        /// <summary>\n        /// Initializes Name Value collection provider.\n        /// </summary>\n        /// <param name=\"collection\">Key value collection from request.</param>\n        /// <param name=\"unvalidatedCollection\">Unvalidated key value collection from the request.</param>\n        /// <param name=\"culture\">Culture with which the values are to be used.</param>\n        /// <param name=\"jQueryToMvcRequestNormalizationRequired\">jQuery POST when sending complex Javascript \n        /// objects to server does not encode in the way understandable by MVC. This flag should be set\n        /// if the request should be normalized to MVC form - https://aspnetwebstack.codeplex.com/workitem/1564. </param>\n        [SuppressMessage(\"Microsoft.Naming\",\n                            \"CA1704:IdentifiersShouldBeSpelledCorrectly\",\n                            MessageId = \"j\",\n                            Justification = \"jQuery is not accepted as a valid variable name in this class\")]\n        public NameValueCollectionValueProvider(\n                            NameValueCollection collection, \n                            NameValueCollection unvalidatedCollection, \n                            CultureInfo culture, \n                            bool jQueryToMvcRequestNormalizationRequired)\n        {\n            if (collection == null)\n            {\n                throw new ArgumentNullException(\"collection\");\n            }\n\n            _unvalidatedCollection = unvalidatedCollection ?? collection;\n            _collection = collection;\n            _culture = culture;\n            _jQueryToMvcRequestNormalizationRequired = jQueryToMvcRequestNormalizationRequired;\n        }\n\n        private Dictionary<string, ValueProviderResultPlaceholder> Values\n        {\n            get\n            {\n                if (_values == null)\n                {\n                    _values = InitializeCollectionValues();\n                }\n\n                return _values;\n            }\n        }\n        \n        private PrefixContainer PrefixContainer\n        {\n            get\n            {\n                if (_prefixContainer == null)\n                {\n                    // Race condition on initialization has no side effects\n                    _prefixContainer = new PrefixContainer(Values.Keys);\n                }\n                return _prefixContainer;\n            }\n        }\n\n        public virtual bool ContainsPrefix(string prefix)\n        {\n            return PrefixContainer.ContainsPrefix(prefix);\n        }\n\n        public virtual ValueProviderResult GetValue(string key)\n        {\n            return GetValue(key, skipValidation: false);\n        }\n\n        public virtual ValueProviderResult GetValue(string key, bool skipValidation)\n        {\n            if (key == null)\n            {\n                throw new ArgumentNullException(\"key\");\n            }\n\n            ValueProviderResultPlaceholder placeholder;\n            Values.TryGetValue(key, out placeholder);\n            if (placeholder == null)\n            {\n                return null;\n            }\n            else\n            {\n                return (skipValidation) ? placeholder.UnvalidatedResult : placeholder.ValidatedResult;\n            }\n        }\n\n        public virtual IDictionary<string, string> GetKeysFromPrefix(string prefix)\n        {\n            return PrefixContainer.GetKeysFromPrefix(prefix);\n        }\n\n        private Dictionary<string, ValueProviderResultPlaceholder> InitializeCollectionValues()\n        {\n            Dictionary<string, ValueProviderResultPlaceholder> tempValues =\n                            new Dictionary<string, ValueProviderResultPlaceholder>(StringComparer.OrdinalIgnoreCase);\n\n            // Need to read keys from the unvalidated collection, as M.W.I's granular request validation is a bit touchy\n            // and validated entries at the time the key or value is looked at. For example, GetKey() will throw if the\n            // value fails request validation, even though the value's not being looked at (M.W.I can't tell the difference).\n\n            foreach (string key in _unvalidatedCollection)\n            {\n                if (key != null)\n                {\n                    string normalizedKey = key;\n                    if (_jQueryToMvcRequestNormalizationRequired)\n                    {\n                        normalizedKey = NormalizeJQueryToMvc(key);\n                    }\n\n                    // need to look up values lazily, as eagerly looking at the collection might trigger validation\n                    tempValues[normalizedKey] =\n                        new ValueProviderResultPlaceholder(key, _collection, _unvalidatedCollection, _culture);\n                }\n            }\n\n            return tempValues;\n        }\n\n        // This code is borrowed from WebAPI FormDataCollectionExtensions.cs \n        // This is a helper method to use Model Binding over a JQuery syntax. \n        // Normalize from JQuery to MVC keys. The model binding infrastructure uses MVC keys\n        // x[] --> x\n        // [] --> \"\"\n        // x[12] --> x[12]\n        // x[field]  --> x.field, where field is not a number\n        private static string NormalizeJQueryToMvc(string key)\n        {\n            if (key == null)\n            {\n                return String.Empty;\n            }\n\n            StringBuilder sb = null;\n            int i = 0;\n            while (true)\n            {\n                int indexOpen = key.IndexOf('[', i);\n                if (indexOpen < 0)\n                {\n                    // Fast path, no normalization needed.\n                    // This skips the string conversion and allocating the string builder.\n                    if (i == 0)\n                    {\n                        return key;\n                    }\n\n                    sb = sb ?? new StringBuilder();\n                    sb.Append(key, i, key.Length - i);\n                    break; // no more brackets\n                }\n\n                sb = sb ?? new StringBuilder();\n                sb.Append(key, i, indexOpen - i); // everything up to \"[\"\n\n                // Find closing bracket.\n                int indexClose = key.IndexOf(']', indexOpen);\n                if (indexClose == -1)\n                {\n                    throw Error.Argument(\"key\", MvcResources.JQuerySyntaxMissingClosingBracket);\n                }\n\n                if (indexClose == indexOpen + 1)\n                {\n                    // Empty bracket. Signifies array. Just remove. \n                }\n                else\n                {\n                    if (Char.IsDigit(key[indexOpen + 1]))\n                    {\n                        // array index. Leave unchanged. \n                        sb.Append(key, indexOpen, indexClose - indexOpen + 1);\n                    }\n                    else\n                    {\n                        // Field name.  Convert to dot notation. \n                        sb.Append('.');\n                        sb.Append(key, indexOpen + 1, indexClose - indexOpen - 1);\n                    }\n                }\n\n                i = indexClose + 1;\n                if (i >= key.Length)\n                {\n                    break; // end of string\n                }\n            }\n            return sb.ToString();\n        }\n\n        // Placeholder that can store a validated (in relation to request validation) or unvalidated\n        // ValueProviderResult for a given key.\n        private sealed class ValueProviderResultPlaceholder\n        {\n            private ValueProviderResult _validatedResult;\n            private ValueProviderResult _unvalidatedResult;\n            private string _key;\n            private NameValueCollection _validatedCollection;\n            private NameValueCollection _unvalidatedCollection;\n            private CultureInfo _culture;\n\n            public ValueProviderResultPlaceholder(string key, NameValueCollection validatedCollection, NameValueCollection unvalidatedCollection, CultureInfo culture)\n            {\n                _key = key;\n                _validatedCollection = validatedCollection;\n                _unvalidatedCollection = unvalidatedCollection;\n                _culture = culture;\n            }\n\n            public ValueProviderResult ValidatedResult\n            {\n                get \n                {\n                    if (_validatedResult == null)\n                    {\n                        _validatedResult = GetResultFromCollection(_key, _validatedCollection, _culture);\n                    }\n                    return _validatedResult;\n                }\n            }\n\n            public ValueProviderResult UnvalidatedResult\n            {\n                get \n                {\n                    if (_unvalidatedResult == null)\n                    {\n                        _unvalidatedResult = GetResultFromCollection(_key, _unvalidatedCollection, _culture);\n                    }\n                    return _unvalidatedResult;\n                }\n            }\n\n            private static ValueProviderResult GetResultFromCollection(string key, NameValueCollection collection, CultureInfo culture)\n            {\n                string[] rawValue = collection.GetValues(key);\n                string attemptedValue = collection[key];\n                return new ValueProviderResult(rawValue, attemptedValue, culture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/NoAsyncTimeoutAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\n\nnamespace System.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\n    public sealed class NoAsyncTimeoutAttribute : AsyncTimeoutAttribute\n    {\n        public NoAsyncTimeoutAttribute()\n            : base(Timeout.Infinite)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/NonActionAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\n\nnamespace System.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\n    public sealed class NonActionAttribute : ActionMethodSelectorAttribute\n    {\n        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)\n        {\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/NullViewLocationCache.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    internal sealed class NullViewLocationCache : IViewLocationCache\n    {\n        #region IViewLocationCache Members\n\n        public string GetViewLocation(HttpContextBase httpContext, string key)\n        {\n            return null;\n        }\n\n        public void InsertViewLocation(HttpContextBase httpContext, string key, string virtualPath)\n        {\n        }\n\n        #endregion\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/OutputCacheAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.Caching;\nusing System.Security.Cryptography;\nusing System.Text;\nusing System.Threading;\nusing System.Web.Mvc.Properties;\nusing System.Web.UI;\n\nnamespace System.Web.Mvc\n{\n    [SuppressMessage(\"Microsoft.Performance\", \"CA1813:AvoidUnsealedAttributes\", Justification = \"Unsealed so that subclassed types can set properties in the default constructor.\")]\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\n    public class OutputCacheAttribute : ActionFilterAttribute, IExceptionFilter\n    {\n        private const string CacheKeyPrefix = \"_MvcChildActionCache_\";\n        private static readonly char[] _splitParameter = new[] { ';' };\n        private static ObjectCache _childActionCache;\n        private static object _childActionFilterFinishCallbackKey = new object();\n        private readonly Func<string[]> _splitVaryByParamThunk;\n        private OutputCacheParameters _cacheSettings = new OutputCacheParameters { VaryByParam = \"*\" };\n        private Func<ObjectCache> _childActionCacheThunk = () => ChildActionCache;\n        private bool _locationWasSet;\n        private bool _noStoreWasSet;\n        private string[] _tokenizedVaryByParams;\n\n        public OutputCacheAttribute()\n        {\n            _splitVaryByParamThunk = () => GetTokenizedVaryByParam(VaryByParam);\n        }\n\n        internal OutputCacheAttribute(ObjectCache childActionCache)\n            : this()\n        {\n            _childActionCacheThunk = () => childActionCache;\n        }\n\n        public string CacheProfile\n        {\n            get { return _cacheSettings.CacheProfile ?? String.Empty; }\n            set { _cacheSettings.CacheProfile = value; }\n        }\n\n        internal OutputCacheParameters CacheSettings\n        {\n            get { return _cacheSettings; }\n        }\n\n        public static ObjectCache ChildActionCache\n        {\n            get { return _childActionCache ?? MemoryCache.Default; }\n            set { _childActionCache = value; }\n        }\n\n        private ObjectCache ChildActionCacheInternal\n        {\n            get { return _childActionCacheThunk(); }\n        }\n\n        public int Duration\n        {\n            get { return _cacheSettings.Duration; }\n            set { _cacheSettings.Duration = value; }\n        }\n\n        public OutputCacheLocation Location\n        {\n            get { return _cacheSettings.Location; }\n            set\n            {\n                _cacheSettings.Location = value;\n                _locationWasSet = true;\n            }\n        }\n\n        public bool NoStore\n        {\n            get { return _cacheSettings.NoStore; }\n            set\n            {\n                _cacheSettings.NoStore = value;\n                _noStoreWasSet = true;\n            }\n        }\n\n        public string SqlDependency\n        {\n            get { return _cacheSettings.SqlDependency ?? String.Empty; }\n            set { _cacheSettings.SqlDependency = value; }\n        }\n\n        public string VaryByContentEncoding\n        {\n            get { return _cacheSettings.VaryByContentEncoding ?? String.Empty; }\n            set { _cacheSettings.VaryByContentEncoding = value; }\n        }\n\n        public string VaryByCustom\n        {\n            get { return _cacheSettings.VaryByCustom ?? String.Empty; }\n            set { _cacheSettings.VaryByCustom = value; }\n        }\n\n        public string VaryByHeader\n        {\n            get { return _cacheSettings.VaryByHeader ?? String.Empty; }\n            set { _cacheSettings.VaryByHeader = value; }\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"Param\", Justification = \"Matches the @ OutputCache page directive. Suppressed in source because this is a special case suppression.\")]\n        public string VaryByParam\n        {\n            get { return _cacheSettings.VaryByParam ?? String.Empty; }\n            set\n            {\n                // Reset the tokenized values if the property gets modified.\n                _tokenizedVaryByParams = null;\n                _cacheSettings.VaryByParam = value;\n            }\n        }\n\n        private static void ClearChildActionFilterFinishCallback(ControllerContext controllerContext)\n        {\n            controllerContext.HttpContext.Items.Remove(_childActionFilterFinishCallbackKey);\n        }\n\n        private static void CompleteChildAction(ControllerContext filterContext, bool wasException)\n        {\n            Action<bool> callback = GetChildActionFilterFinishCallback(filterContext);\n\n            if (callback != null)\n            {\n                ClearChildActionFilterFinishCallback(filterContext);\n                callback(wasException);\n            }\n        }\n\n        private static Action<bool> GetChildActionFilterFinishCallback(ControllerContext controllerContext)\n        {\n            return controllerContext.HttpContext.Items[_childActionFilterFinishCallbackKey] as Action<bool>;\n        }\n\n        internal string GetChildActionUniqueId(ActionExecutingContext filterContext)\n        {\n            StringBuilder uniqueIdBuilder = new StringBuilder();\n\n            // Start with a prefix, presuming that we share the cache with other users\n            uniqueIdBuilder.Append(CacheKeyPrefix);\n\n            // Unique ID of the action description\n            uniqueIdBuilder.Append(filterContext.ActionDescriptor.UniqueId);\n\n            // Unique ID from the VaryByCustom settings, if any\n            DescriptorUtil.AppendUniqueId(uniqueIdBuilder, VaryByCustom);\n            if (!String.IsNullOrEmpty(VaryByCustom))\n            {\n                string varyByCustomResult = filterContext.HttpContext.ApplicationInstance.GetVaryByCustomString(HttpContext.Current, VaryByCustom);\n                uniqueIdBuilder.Append(varyByCustomResult);\n            }\n\n            // Unique ID from the VaryByParam settings, if any\n            BuildUniqueIdFromActionParameters(uniqueIdBuilder, filterContext);\n\n            // The key is typically too long to be useful, so we use a cryptographic hash\n            // as the actual key (better randomization and key distribution, so small vary\n            // values will generate dramtically different keys).\n            using (SHA256Cng sha = new SHA256Cng())\n            {\n                return Convert.ToBase64String(sha.ComputeHash(Encoding.UTF8.GetBytes(uniqueIdBuilder.ToString())));\n            }\n        }\n\n        internal void BuildUniqueIdFromActionParameters(\n            StringBuilder builder,\n            ActionExecutingContext filterContext)\n        {\n            if (String.Equals(VaryByParam, \"none\", StringComparison.OrdinalIgnoreCase))\n            {\n                // nothing to do\n                return;\n            }\n\n            if (String.Equals(VaryByParam, \"*\", StringComparison.Ordinal))\n            {\n                // use all available key/value pairs. Keys need to be sorted so we end up with a stable identifier.\n                IEnumerable<KeyValuePair<string, object>> orderedParameters = filterContext\n                                                                .ActionParameters\n                                                                .OrderBy(k => k.Key, StringComparer.OrdinalIgnoreCase);\n\n                foreach (KeyValuePair<string, object> item in orderedParameters)\n                {\n                    DescriptorUtil.AppendUniqueId(builder, item.Key.ToUpperInvariant());\n                    DescriptorUtil.AppendUniqueId(builder, item.Value);\n                }\n\n                return;\n            }\n\n            LazyInitializer.EnsureInitialized(ref _tokenizedVaryByParams,\n                                              _splitVaryByParamThunk);\n\n            // By default, filterContext.ActionParameter is a case insensitive (StringComparer.OrdinalIgnoreCase)\n            // dictionary. If the user has replaced it with a dictionary that uses a different comparer, we'll\n            // wrap it in a Dictionary<string, object>(StringComparer.OrdinalIgnoreCase)\n            // This allows us to lookup values for action parameters when the VaryByParam token key differs in case.\n            Dictionary<string, object> keyValues = GetCaseInsensitiveActionParametersDictionary(\n                                                        filterContext.ActionParameters);\n            for (int i = 0; i < _tokenizedVaryByParams.Length; i++)\n            {\n                string key = _tokenizedVaryByParams[i];\n                DescriptorUtil.AppendUniqueId(builder, key);\n\n                object value;\n                keyValues.TryGetValue(key, out value);\n                DescriptorUtil.AppendUniqueId(builder, value);\n            }\n        }\n\n        public static bool IsChildActionCacheActive(ControllerContext controllerContext)\n        {\n            return GetChildActionFilterFinishCallback(controllerContext) != null;\n        }\n\n        public override void OnActionExecuted(ActionExecutedContext filterContext)\n        {\n            if (filterContext == null)\n            {\n                throw new ArgumentNullException(\"filterContext\");\n            }\n\n            // Complete the request if the child action threw an exception\n            if (filterContext.IsChildAction && filterContext.Exception != null)\n            {\n                CompleteChildAction(filterContext, wasException: true);\n            }\n        }\n\n        public override void OnActionExecuting(ActionExecutingContext filterContext)\n        {\n            if (filterContext == null)\n            {\n                throw new ArgumentNullException(\"filterContext\");\n            }\n\n            if (filterContext.IsChildAction)\n            {\n                // Skip validation and caching if there's no caching on the server for this action. It's ok to \n                // explicitly disable caching for a child action, but it will be ignored if the parent action\n                // is using caching.\n                if (IsServerSideCacheDisabled())\n                {\n                    return;\n                }\n\n                ValidateChildActionConfiguration();\n\n                // Already actively being captured? (i.e., cached child action inside of cached child action)\n                // Realistically, this needs write substitution to do properly (including things like authentication)\n                if (GetChildActionFilterFinishCallback(filterContext) != null)\n                {\n                    throw new InvalidOperationException(MvcResources.OutputCacheAttribute_CannotNestChildCache);\n                }\n\n                // Already cached?\n                string uniqueId = GetChildActionUniqueId(filterContext);\n                string cachedValue = ChildActionCacheInternal.Get(uniqueId) as string;\n                if (cachedValue != null)\n                {\n                    filterContext.Result = new ContentResult() { Content = cachedValue };\n                    return;\n                }\n\n                // Swap in a new TextWriter so we can capture the output\n                StringWriter cachingWriter = new StringWriter(CultureInfo.InvariantCulture);\n                TextWriter originalWriter = filterContext.HttpContext.Response.Output;\n                filterContext.HttpContext.Response.Output = cachingWriter;\n\n                // Set a finish callback to clean up\n                SetChildActionFilterFinishCallback(filterContext, wasException =>\n                {\n                    // Restore original writer\n                    filterContext.HttpContext.Response.Output = originalWriter;\n\n                    // Grab output and write it\n                    string capturedText = cachingWriter.ToString();\n                    filterContext.HttpContext.Response.Write(capturedText);\n\n                    // Only cache output if this wasn't an error\n                    if (!wasException)\n                    {\n                        ChildActionCacheInternal.Add(uniqueId, capturedText, DateTimeOffset.UtcNow.AddSeconds(Duration));\n                    }\n                });\n            }\n        }\n\n        public void OnException(ExceptionContext filterContext)\n        {\n            if (filterContext == null)\n            {\n                throw new ArgumentNullException(\"filterContext\");\n            }\n\n            if (filterContext.IsChildAction)\n            {\n                CompleteChildAction(filterContext, wasException: true);\n            }\n        }\n\n        public override void OnResultExecuting(ResultExecutingContext filterContext)\n        {\n            if (filterContext == null)\n            {\n                throw new ArgumentNullException(\"filterContext\");\n            }\n\n            if (!filterContext.IsChildAction)\n            {\n                // we need to call ProcessRequest() since there's no other way to set the Page.Response intrinsic\n                using (OutputCachedPage page = new OutputCachedPage(_cacheSettings))\n                {\n                    page.ProcessRequest(HttpContext.Current);\n                }\n            }\n        }\n\n        public override void OnResultExecuted(ResultExecutedContext filterContext)\n        {\n            if (filterContext == null)\n            {\n                throw new ArgumentNullException(\"filterContext\");\n            }\n\n            if (filterContext.IsChildAction)\n            {\n                CompleteChildAction(filterContext, wasException: filterContext.Exception != null);\n            }\n        }\n\n        private static void SetChildActionFilterFinishCallback(ControllerContext controllerContext, Action<bool> callback)\n        {\n            controllerContext.HttpContext.Items[_childActionFilterFinishCallbackKey] = callback;\n        }\n\n        private void ValidateChildActionConfiguration()\n        {\n            if (!String.IsNullOrWhiteSpace(CacheProfile) ||\n                !String.IsNullOrWhiteSpace(SqlDependency) ||\n                !String.IsNullOrWhiteSpace(VaryByContentEncoding) ||\n                !String.IsNullOrWhiteSpace(VaryByHeader) ||\n                _locationWasSet || _noStoreWasSet)\n            {\n                throw new InvalidOperationException(MvcResources.OutputCacheAttribute_ChildAction_UnsupportedSetting);\n            }\n\n            if (Duration <= 0)\n            {\n                throw new InvalidOperationException(MvcResources.OutputCacheAttribute_InvalidDuration);\n            }\n\n            if (String.IsNullOrWhiteSpace(VaryByParam))\n            {\n                throw new InvalidOperationException(MvcResources.OutputCacheAttribute_InvalidVaryByParam);\n            }\n        }\n\n        private bool IsServerSideCacheDisabled()\n        {\n            switch (Location)\n            {\n                case OutputCacheLocation.None:\n                case OutputCacheLocation.Client:\n                case OutputCacheLocation.Downstream:\n                    return true;\n\n                default:\n                    return false;\n            }\n        }\n\n        private static string[] GetTokenizedVaryByParam(string varyByParam)\n        {\n            // Vary by specific parameters\n            IEnumerable<string> splitTokens = from part in varyByParam.Split(_splitParameter)\n                                              let trimmed = part.Trim()\n                                              where !String.IsNullOrEmpty(trimmed)\n                                              select trimmed.ToUpperInvariant();\n            return splitTokens.ToArray();\n        }\n\n        private static Dictionary<string, object> GetCaseInsensitiveActionParametersDictionary(\n            IDictionary<string, object> actionParameters)\n        {\n            // The ControllerActionInvoker starts off with a Dictionary<string, object> with\n            // StringComparer.OrdinalIgnoreCase. Check if we are working with this type to start with.\n            // If not produce a new dictionary from the existing one.\n\n            var dictionary = actionParameters as Dictionary<string, object>;\n            if (dictionary != null && dictionary.Comparer == StringComparer.OrdinalIgnoreCase)\n            {\n                return dictionary;\n            }\n\n            return new Dictionary<string, object>(actionParameters, StringComparer.OrdinalIgnoreCase);\n        }\n\n        [SuppressMessage(\"ASP.NET.Security\", \"CA5328:ValidateRequestShouldBeEnabled\", Justification = \"Instances of this type are not created in response to direct user input.\")]\n        private sealed class OutputCachedPage : Page\n        {\n            private OutputCacheParameters _cacheSettings;\n\n            public OutputCachedPage(OutputCacheParameters cacheSettings)\n            {\n                // Tracing requires Page IDs to be unique.\n                ID = Guid.NewGuid().ToString();\n                _cacheSettings = cacheSettings;\n            }\n\n            protected override void FrameworkInitialize()\n            {\n                // when you put the <%@ OutputCache %> directive on a page, the generated code calls InitOutputCache() from here\n                base.FrameworkInitialize();\n                InitOutputCache(_cacheSettings);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/OverrideActionFiltersAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc.Filters;\n\nnamespace System.Web.Mvc\n{\n    /// <summary>Represents a filter attribute that overrides action filters defined at a higher level.</summary>\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\n    public sealed class OverrideActionFiltersAttribute : FilterAttribute, IOverrideFilter\n    {\n        /// <inheritdoc />\n        public Type FiltersToOverride\n        {\n            get { return typeof(IActionFilter); }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/OverrideAuthenticationAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc.Filters;\n\nnamespace System.Web.Mvc\n{\n    /// <summary>\n    /// Represents a filter attribute that overrides authentication filters defined at a higher level.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\n    public sealed class OverrideAuthenticationAttribute : FilterAttribute, IOverrideFilter\n    {\n        /// <inheritdoc />\n        public Type FiltersToOverride\n        {\n            get { return typeof(IAuthenticationFilter); }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/OverrideAuthorizationAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc.Filters;\n\nnamespace System.Web.Mvc\n{\n    /// <summary>\n    /// Represents a filter attribute that overrides authorization filters defined at a higher level.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\n    public sealed class OverrideAuthorizationAttribute : FilterAttribute, IOverrideFilter\n    {\n        /// <inheritdoc />\n        public Type FiltersToOverride\n        {\n            get { return typeof(IAuthorizationFilter); }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/OverrideExceptionFiltersAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc.Filters;\n\nnamespace System.Web.Mvc\n{\n    /// <summary>Represents a filter attribute that overrides exception filters defined at a higher level.</summary>\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\n    public sealed class OverrideExceptionFiltersAttribute : FilterAttribute, IOverrideFilter\n    {\n        /// <inheritdoc />\n        public Type FiltersToOverride\n        {\n            get { return typeof(IExceptionFilter); }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/OverrideResultFiltersAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc.Filters;\n\nnamespace System.Web.Mvc\n{\n    /// <summary>Represents a filter attribute that overrides result filters defined at a higher level.</summary>\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\n    public sealed class OverrideResultFiltersAttribute : FilterAttribute, IOverrideFilter\n    {\n        /// <inheritdoc />\n        public Type FiltersToOverride\n        {\n            get { return typeof(IResultFilter); }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ParameterBindingInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Mvc\n{\n    public abstract class ParameterBindingInfo\n    {\n        public virtual IModelBinder Binder\n        {\n            get { return null; }\n        }\n\n        public virtual ICollection<string> Exclude\n        {\n            get { return new string[0]; }\n        }\n\n        public virtual ICollection<string> Include\n        {\n            get { return new string[0]; }\n        }\n\n        public virtual string Prefix\n        {\n            get { return null; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ParameterDescriptor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\n\nnamespace System.Web.Mvc\n{\n    public abstract class ParameterDescriptor : ICustomAttributeProvider\n    {\n        private static readonly EmptyParameterBindingInfo _emptyBindingInfo = new EmptyParameterBindingInfo();\n\n        public abstract ActionDescriptor ActionDescriptor { get; }\n\n        public virtual ParameterBindingInfo BindingInfo\n        {\n            get { return _emptyBindingInfo; }\n        }\n\n        public virtual object DefaultValue\n        {\n            get { return null; }\n        }\n\n        public abstract string ParameterName { get; }\n\n        public abstract Type ParameterType { get; }\n\n        public virtual object[] GetCustomAttributes(bool inherit)\n        {\n            return GetCustomAttributes(typeof(object), inherit);\n        }\n\n        public virtual object[] GetCustomAttributes(Type attributeType, bool inherit)\n        {\n            if (attributeType == null)\n            {\n                throw new ArgumentNullException(\"attributeType\");\n            }\n\n            return (object[])Array.CreateInstance(attributeType, 0);\n        }\n\n        public virtual bool IsDefined(Type attributeType, bool inherit)\n        {\n            if (attributeType == null)\n            {\n                throw new ArgumentNullException(\"attributeType\");\n            }\n\n            return false;\n        }\n\n        private sealed class EmptyParameterBindingInfo : ParameterBindingInfo\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ParameterInfoUtil.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Reflection;\n\nnamespace System.Web.Mvc\n{\n    internal static class ParameterInfoUtil\n    {\n        public static bool TryGetDefaultValue(ParameterInfo parameterInfo, out object value)\n        {\n            // this will get the default value as seen by the VB / C# compilers\n            // if no value was baked in, RawDefaultValue returns DBNull.Value\n            object defaultValue = parameterInfo.DefaultValue;\n            if (defaultValue != DBNull.Value)\n            {\n                value = defaultValue;\n                return true;\n            }\n\n            // if the compiler did not bake in a default value, check the [DefaultValue] attribute\n            DefaultValueAttribute[] attrs = (DefaultValueAttribute[])parameterInfo.GetCustomAttributes(typeof(DefaultValueAttribute), false);\n            if (attrs == null || attrs.Length == 0)\n            {\n                value = default(object);\n                return false;\n            }\n            else\n            {\n                value = attrs[0].Value;\n                return true;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/PartialViewResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Text;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    public class PartialViewResult : ViewResultBase\n    {\n        protected override ViewEngineResult FindView(ControllerContext context)\n        {\n            ViewEngineResult result = ViewEngineCollection.FindPartialView(context, ViewName);\n            if (result.View != null)\n            {\n                return result;\n            }\n\n            // we need to generate an exception containing all the locations we searched\n            StringBuilder locationsText = new StringBuilder();\n            foreach (string location in result.SearchedLocations)\n            {\n                locationsText.AppendLine();\n                locationsText.Append(location);\n            }\n            throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,\n                                                              MvcResources.Common_PartialViewNotFound, ViewName, locationsText));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/PreApplicationStartCode.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Web.WebPages.Scope;\n\nnamespace System.Web.Mvc\n{\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class PreApplicationStartCode\n    {\n        private static bool _startWasCalled;\n\n        public static void Start()\n        {\n            // Guard against multiple calls. All Start calls are made on same thread, so no lock needed here\n            if (_startWasCalled)\n            {\n                return;\n            }\n            _startWasCalled = true;\n\n            WebPages.Razor.PreApplicationStartCode.Start();\n            WebPages.PreApplicationStartCode.Start();\n\n            ViewContext.GlobalScopeThunk = () => ScopeStorage.CurrentScope;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Properties/AssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\nusing System.Web;\nusing System.Web.Mvc;\n\n[assembly: AssemblyTitle(\"System.Web.Mvc.dll\")]\n[assembly: AssemblyDescription(\"System.Web.Mvc.dll\")]\n[assembly: Guid(\"4b5f4208-c6b0-4c37-9a41-63325ffa52ad\")]\n\n[assembly: InternalsVisibleTo(\"DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7\")]\n[assembly: InternalsVisibleTo(\"System.Web.Mvc.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n[assembly: PreApplicationStartMethod(typeof(PreApplicationStartCode), \"Start\")]\n[assembly: TypeForwardedTo(typeof(TagBuilder))]\n[assembly: TypeForwardedTo(typeof(TagRenderMode))]\n[assembly: TypeForwardedTo(typeof(HttpAntiForgeryException))]\n[assembly: TypeForwardedTo(typeof(ModelClientValidationEqualToRule))]\n[assembly: TypeForwardedTo(typeof(ModelClientValidationRangeRule))]\n[assembly: TypeForwardedTo(typeof(ModelClientValidationRegexRule))]\n[assembly: TypeForwardedTo(typeof(ModelClientValidationRemoteRule))]\n[assembly: TypeForwardedTo(typeof(ModelClientValidationRequiredRule))]\n[assembly: TypeForwardedTo(typeof(ModelClientValidationRule))]\n[assembly: TypeForwardedTo(typeof(ModelClientValidationStringLengthRule))]\n"
  },
  {
    "path": "src/System.Web.Mvc/Properties/MvcResources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.34003\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace System.Web.Mvc.Properties {\n    using System;\n    \n    \n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class MvcResources {\n        \n        private static global::System.Resources.ResourceManager resourceMan;\n        \n        private static global::System.Globalization.CultureInfo resourceCulture;\n        \n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal MvcResources() {\n        }\n        \n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"System.Web.Mvc.Properties.MvcResources\", typeof(MvcResources).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n        \n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The current request for action &apos;{0}&apos; on controller type &apos;{1}&apos; is ambiguous between the following action methods:{2}.\n        /// </summary>\n        internal static string ActionMethodSelector_AmbiguousMatch {\n            get {\n                return ResourceManager.GetString(\"ActionMethodSelector_AmbiguousMatch\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to {0} on type {1}.\n        /// </summary>\n        internal static string ActionMethodSelector_AmbiguousMatchType {\n            get {\n                return ResourceManager.GetString(\"ActionMethodSelector_AmbiguousMatchType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Value must be greater than or equal to {0}..\n        /// </summary>\n        internal static string ArgumentMustBeGreaterThanOrEqualTo {\n            get {\n                return ResourceManager.GetString(\"ArgumentMustBeGreaterThanOrEqualTo\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The asynchronous action method &apos;{0}&apos; cannot be executed synchronously..\n        /// </summary>\n        internal static string AsyncActionDescriptor_CannotExecuteSynchronously {\n            get {\n                return ResourceManager.GetString(\"AsyncActionDescriptor_CannotExecuteSynchronously\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Lookup for method &apos;{0}&apos; on controller type &apos;{1}&apos; failed because of an ambiguity between the following methods:{2}.\n        /// </summary>\n        internal static string AsyncActionMethodSelector_AmbiguousMethodMatch {\n            get {\n                return ResourceManager.GetString(\"AsyncActionMethodSelector_AmbiguousMethodMatch\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Could not locate a method named &apos;{0}&apos; on controller type {1}..\n        /// </summary>\n        internal static string AsyncActionMethodSelector_CouldNotFindMethod {\n            get {\n                return ResourceManager.GetString(\"AsyncActionMethodSelector_CouldNotFindMethod\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The provided IAsyncResult has already been consumed..\n        /// </summary>\n        internal static string AsyncCommon_AsyncResultAlreadyConsumed {\n            get {\n                return ResourceManager.GetString(\"AsyncCommon_AsyncResultAlreadyConsumed\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The controller of type &apos;{0}&apos; must subclass AsyncController or implement the IAsyncManagerContainer interface..\n        /// </summary>\n        internal static string AsyncCommon_ControllerMustImplementIAsyncManagerContainer {\n            get {\n                return ResourceManager.GetString(\"AsyncCommon_ControllerMustImplementIAsyncManagerContainer\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The provided IAsyncResult is not valid for this method..\n        /// </summary>\n        internal static string AsyncCommon_InvalidAsyncResult {\n            get {\n                return ResourceManager.GetString(\"AsyncCommon_InvalidAsyncResult\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The timeout value must be non-negative or Timeout.Infinite..\n        /// </summary>\n        internal static string AsyncCommon_InvalidTimeout {\n            get {\n                return ResourceManager.GetString(\"AsyncCommon_InvalidTimeout\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Could not infer area name for the controller &apos;{0}&apos; because it does not have a namespace..\n        /// </summary>\n        internal static string AttributeRouting_CouldNotInferAreaNameFromMissingNamespace {\n            get {\n                return ResourceManager.GetString(\"AttributeRouting_CouldNotInferAreaNameFromMissingNamespace\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to AuthorizeAttribute cannot be used within a child action caching block..\n        /// </summary>\n        internal static string AuthorizeAttribute_CannotUseWithinChildActionCache {\n            get {\n                return ResourceManager.GetString(\"AuthorizeAttribute_CannotUseWithinChildActionCache\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The action &apos;{0}&apos; is accessible only by a child request..\n        /// </summary>\n        internal static string ChildActionOnlyAttribute_MustBeInChildRequest {\n            get {\n                return ResourceManager.GetString(\"ChildActionOnlyAttribute_MustBeInChildRequest\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The field {0} must be a date..\n        /// </summary>\n        internal static string ClientDataTypeModelValidatorProvider_FieldMustBeDate {\n            get {\n                return ResourceManager.GetString(\"ClientDataTypeModelValidatorProvider_FieldMustBeDate\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The field {0} must be a number..\n        /// </summary>\n        internal static string ClientDataTypeModelValidatorProvider_FieldMustBeNumeric {\n            get {\n                return ResourceManager.GetString(\"ClientDataTypeModelValidatorProvider_FieldMustBeNumeric\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to No route in the route table matches the supplied values..\n        /// </summary>\n        internal static string Common_NoRouteMatched {\n            get {\n                return ResourceManager.GetString(\"Common_NoRouteMatched\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Value cannot be null or empty..\n        /// </summary>\n        internal static string Common_NullOrEmpty {\n            get {\n                return ResourceManager.GetString(\"Common_NullOrEmpty\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The partial view &apos;{0}&apos; was not found or no view engine supports the searched locations. The following locations were searched:{1}.\n        /// </summary>\n        internal static string Common_PartialViewNotFound {\n            get {\n                return ResourceManager.GetString(\"Common_PartialViewNotFound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The property &apos;{0}&apos; cannot be null or empty..\n        /// </summary>\n        internal static string Common_PropertyCannotBeNullOrEmpty {\n            get {\n                return ResourceManager.GetString(\"Common_PropertyCannotBeNullOrEmpty\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The property {0}.{1} could not be found..\n        /// </summary>\n        internal static string Common_PropertyNotFound {\n            get {\n                return ResourceManager.GetString(\"Common_PropertyNotFound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to False.\n        /// </summary>\n        internal static string Common_TriState_False {\n            get {\n                return ResourceManager.GetString(\"Common_TriState_False\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Not Set.\n        /// </summary>\n        internal static string Common_TriState_NotSet {\n            get {\n                return ResourceManager.GetString(\"Common_TriState_NotSet\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to True.\n        /// </summary>\n        internal static string Common_TriState_True {\n            get {\n                return ResourceManager.GetString(\"Common_TriState_True\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The type {0} must derive from {1}.\n        /// </summary>\n        internal static string Common_TypeMustDriveFromType {\n            get {\n                return ResourceManager.GetString(\"Common_TypeMustDriveFromType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The value &apos;{0}&apos; is invalid..\n        /// </summary>\n        internal static string Common_ValueNotValidForProperty {\n            get {\n                return ResourceManager.GetString(\"Common_ValueNotValidForProperty\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The view &apos;{0}&apos; or its master was not found or no view engine supports the searched locations. The following locations were searched:{1}.\n        /// </summary>\n        internal static string Common_ViewNotFound {\n            get {\n                return ResourceManager.GetString(\"Common_ViewNotFound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &apos;{0}&apos; and &apos;{1}&apos; do not match..\n        /// </summary>\n        internal static string CompareAttribute_MustMatch {\n            get {\n                return ResourceManager.GetString(\"CompareAttribute_MustMatch\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Could not find a property named {0}..\n        /// </summary>\n        internal static string CompareAttribute_UnknownProperty {\n            get {\n                return ResourceManager.GetString(\"CompareAttribute_UnknownProperty\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A public action method &apos;{0}&apos; was not found on controller &apos;{1}&apos;..\n        /// </summary>\n        internal static string Controller_UnknownAction {\n            get {\n                return ResourceManager.GetString(\"Controller_UnknownAction\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to No matching action was found on controller &apos;{0}&apos;. This can happen when a controller uses RouteAttribute for routing, but no action on that controller matches the request..\n        /// </summary>\n        internal static string Controller_UnknownAction_NoActionName {\n            get {\n                return ResourceManager.GetString(\"Controller_UnknownAction_NoActionName\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The model of type &apos;{0}&apos; could not be updated..\n        /// </summary>\n        internal static string Controller_UpdateModel_UpdateUnsuccessful {\n            get {\n                return ResourceManager.GetString(\"Controller_UpdateModel_UpdateUnsuccessful\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The model of type &apos;{0}&apos; is not valid..\n        /// </summary>\n        internal static string Controller_Validate_ValidationFailed {\n            get {\n                return ResourceManager.GetString(\"Controller_Validate_ValidationFailed\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Cannot execute Controller with a null HttpContext..\n        /// </summary>\n        internal static string ControllerBase_CannotExecuteWithNullHttpContext {\n            get {\n                return ResourceManager.GetString(\"ControllerBase_CannotExecuteWithNullHttpContext\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A single instance of controller &apos;{0}&apos; cannot be used to handle multiple requests. If a custom controller factory is in use, make sure that it creates a new instance of the controller for each request..\n        /// </summary>\n        internal static string ControllerBase_CannotHandleMultipleRequests {\n            get {\n                return ResourceManager.GetString(\"ControllerBase_CannotHandleMultipleRequests\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to An error occurred when trying to create the IControllerFactory &apos;{0}&apos;. Make sure that the controller factory has a public parameterless constructor..\n        /// </summary>\n        internal static string ControllerBuilder_ErrorCreatingControllerFactory {\n            get {\n                return ResourceManager.GetString(\"ControllerBuilder_ErrorCreatingControllerFactory\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The IControllerFactory &apos;{0}&apos; did not return a controller for the name &apos;{1}&apos;..\n        /// </summary>\n        internal static string ControllerBuilder_FactoryReturnedNull {\n            get {\n                return ResourceManager.GetString(\"ControllerBuilder_FactoryReturnedNull\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The controller factory type &apos;{0}&apos; must implement the IControllerFactory interface..\n        /// </summary>\n        internal static string ControllerBuilder_MissingIControllerFactory {\n            get {\n                return ResourceManager.GetString(\"ControllerBuilder_MissingIControllerFactory\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The view found at &apos;{0}&apos; was not created..\n        /// </summary>\n        internal static string CshtmlView_ViewCouldNotBeCreated {\n            get {\n                return ResourceManager.GetString(\"CshtmlView_ViewCouldNotBeCreated\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The view at &apos;{0}&apos; must derive from WebViewPage, or WebViewPage&lt;TModel&gt;..\n        /// </summary>\n        internal static string CshtmlView_WrongViewBase {\n            get {\n                return ResourceManager.GetString(\"CshtmlView_WrongViewBase\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to {0} has a DisplayColumn attribute for {1}, but property {1} does not exist..\n        /// </summary>\n        internal static string DataAnnotationsModelMetadataProvider_UnknownProperty {\n            get {\n                return ResourceManager.GetString(\"DataAnnotationsModelMetadataProvider_UnknownProperty\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to {0} has a DisplayColumn attribute for {1}, but property {1} does not have a public getter..\n        /// </summary>\n        internal static string DataAnnotationsModelMetadataProvider_UnreadableProperty {\n            get {\n                return ResourceManager.GetString(\"DataAnnotationsModelMetadataProvider_UnreadableProperty\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The type {0} must have a public constructor which accepts three parameters of types {1}, {2}, and {3}.\n        /// </summary>\n        internal static string DataAnnotationsModelValidatorProvider_ConstructorRequirements {\n            get {\n                return ResourceManager.GetString(\"DataAnnotationsModelValidatorProvider_ConstructorRequirements\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The type {0} must have a public constructor which accepts two parameters of types {1} and {2}..\n        /// </summary>\n        internal static string DataAnnotationsModelValidatorProvider_ValidatableConstructorRequirements {\n            get {\n                return ResourceManager.GetString(\"DataAnnotationsModelValidatorProvider_ValidatableConstructorRequirements\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Multiple types were found that match the controller named &apos;{0}&apos;. This can happen if the route that services this request does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the &apos;MapRoute&apos; method that takes a &apos;namespaces&apos; parameter.{2}{2}The request for &apos;{0}&apos; has found the following matching controllers:{1}.\n        /// </summary>\n        internal static string DefaultControllerFactory_ControllerNameAmbiguous_WithoutRouteUrl {\n            get {\n                return ResourceManager.GetString(\"DefaultControllerFactory_ControllerNameAmbiguous_WithoutRouteUrl\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Multiple types were found that match the controller named &apos;{0}&apos;. This can happen if the route that services this request (&apos;{1}&apos;) does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the &apos;MapRoute&apos; method that takes a &apos;namespaces&apos; parameter.{3}{3}The request for &apos;{0}&apos; has found the following matching controllers:{2}.\n        /// </summary>\n        internal static string DefaultControllerFactory_ControllerNameAmbiguous_WithRouteUrl {\n            get {\n                return ResourceManager.GetString(\"DefaultControllerFactory_ControllerNameAmbiguous_WithRouteUrl\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Multiple controller types were found that match the URL. This can happen if attribute routes on multiple controllers match the requested URL.{1}{1}The request has found the following matching controller types: {0}.\n        /// </summary>\n        internal static string DefaultControllerFactory_DirectRouteAmbiguous {\n            get {\n                return ResourceManager.GetString(\"DefaultControllerFactory_DirectRouteAmbiguous\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to An error occurred when trying to create a controller of type &apos;{0}&apos;. Make sure that the controller has a parameterless public constructor..\n        /// </summary>\n        internal static string DefaultControllerFactory_ErrorCreatingController {\n            get {\n                return ResourceManager.GetString(\"DefaultControllerFactory_ErrorCreatingController\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The controller for path &apos;{0}&apos; was not found or does not implement IController..\n        /// </summary>\n        internal static string DefaultControllerFactory_NoControllerFound {\n            get {\n                return ResourceManager.GetString(\"DefaultControllerFactory_NoControllerFound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The controller type &apos;{0}&apos; must implement IController..\n        /// </summary>\n        internal static string DefaultControllerFactory_TypeDoesNotSubclassControllerBase {\n            get {\n                return ResourceManager.GetString(\"DefaultControllerFactory_TypeDoesNotSubclassControllerBase\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The constructor to use for activating the constraint type &apos;{0}&apos; is ambiguous. Multiple constructors were found with the following number of parameters: {1}..\n        /// </summary>\n        internal static string DefaultInlineConstraintResolver_AmbiguousCtors {\n            get {\n                return ResourceManager.GetString(\"DefaultInlineConstraintResolver_AmbiguousCtors\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Could not find a constructor for constraint type &apos;{0}&apos; with the following number of parameters: {1}..\n        /// </summary>\n        internal static string DefaultInlineConstraintResolver_CouldNotFindCtor {\n            get {\n                return ResourceManager.GetString(\"DefaultInlineConstraintResolver_CouldNotFindCtor\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The constraint type &apos;{0}&apos; which is mapped to constraint key &apos;{1}&apos; must implement the IRouteConstraint interface..\n        /// </summary>\n        internal static string DefaultInlineConstraintResolver_TypeNotConstraint {\n            get {\n                return ResourceManager.GetString(\"DefaultInlineConstraintResolver_TypeNotConstraint\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The value &apos;{0}&apos; is not valid for {1}..\n        /// </summary>\n        internal static string DefaultModelBinder_ValueInvalid {\n            get {\n                return ResourceManager.GetString(\"DefaultModelBinder_ValueInvalid\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A value is required..\n        /// </summary>\n        internal static string DefaultModelBinder_ValueRequired {\n            get {\n                return ResourceManager.GetString(\"DefaultModelBinder_ValueRequired\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The number of ticks for the TimeSpan value must be greater than or equal to 0..\n        /// </summary>\n        internal static string DefaultViewLocationCache_NegativeTimeSpan {\n            get {\n                return ResourceManager.GetString(\"DefaultViewLocationCache_NegativeTimeSpan\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The type {0} does not appear to implement Microsoft.Practices.ServiceLocation.IServiceLocator..\n        /// </summary>\n        internal static string DependencyResolver_DoesNotImplementICommonServiceLocator {\n            get {\n                return ResourceManager.GetString(\"DependencyResolver_DoesNotImplementICommonServiceLocator\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The current request is ambiguous between the following action methods:{0}.\n        /// </summary>\n        internal static string DirectRoute_AmbiguousMatch {\n            get {\n                return ResourceManager.GetString(\"DirectRoute_AmbiguousMatch\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A direct route for an action method cannot use the parameter &apos;action&apos;. Specify a literal path in place of this parameter to create a route to the action..\n        /// </summary>\n        internal static string DirectRoute_InvalidParameter_Action {\n            get {\n                return ResourceManager.GetString(\"DirectRoute_InvalidParameter_Action\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A direct route cannot use the parameter &apos;controller&apos;. Specify a literal path in place of this parameter to create a route to a controller..\n        /// </summary>\n        internal static string DirectRoute_InvalidParameter_Controller {\n            get {\n                return ResourceManager.GetString(\"DirectRoute_InvalidParameter_Controller\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The route does not have any associated action descriptors. Routing requires that each direct route map to a non-empty set of actions..\n        /// </summary>\n        internal static string DirectRoute_MissingActionDescriptors {\n            get {\n                return ResourceManager.GetString(\"DirectRoute_MissingActionDescriptors\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The route does not have an associated controller descriptor. Routing requires that each direct route map to a single controller..\n        /// </summary>\n        internal static string DirectRoute_MissingControllerDescriptor {\n            get {\n                return ResourceManager.GetString(\"DirectRoute_MissingControllerDescriptor\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The route does not have an associated controller type. Routing requires that each direct route map to a single controller type..\n        /// </summary>\n        internal static string DirectRoute_MissingControllerType {\n            get {\n                return ResourceManager.GetString(\"DirectRoute_MissingControllerType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Direct routing does not support per-route route handlers..\n        /// </summary>\n        internal static string DirectRoute_RouteHandlerNotSupported {\n            get {\n                return ResourceManager.GetString(\"DirectRoute_RouteHandlerNotSupported\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to ModelType property must not be null..\n        /// </summary>\n        internal static string EnumHelper_InvalidMetadataParameter {\n            get {\n                return ResourceManager.GetString(\"EnumHelper_InvalidMetadataParameter\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Type &apos;{0}&apos; is not supported..\n        /// </summary>\n        internal static string EnumHelper_InvalidParameterType {\n            get {\n                return ResourceManager.GetString(\"EnumHelper_InvalidParameterType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Invalid value parameter type &apos;{0}&apos;. Must match type parameter &apos;{1}&apos;..\n        /// </summary>\n        internal static string EnumHelper_InvalidValueParameter {\n            get {\n                return ResourceManager.GetString(\"EnumHelper_InvalidValueParameter\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The type &apos;{0}&apos; does not inherit from Exception..\n        /// </summary>\n        internal static string ExceptionViewAttribute_NonExceptionType {\n            get {\n                return ResourceManager.GetString(\"ExceptionViewAttribute_NonExceptionType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The expression compiler was unable to evaluate the indexer expression &apos;{0}&apos; because it references the model parameter &apos;{1}&apos; which is unavailable..\n        /// </summary>\n        internal static string ExpressionHelper_InvalidIndexerExpression {\n            get {\n                return ResourceManager.GetString(\"ExpressionHelper_InvalidIndexerExpression\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Order must be greater than or equal to -1..\n        /// </summary>\n        internal static string FilterAttribute_OrderOutOfRange {\n            get {\n                return ResourceManager.GetString(\"FilterAttribute_OrderOutOfRange\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The given filter instance must implement one or more of the following filter interfaces: {0}, {1}, {2}, {3}, {4}..\n        /// </summary>\n        internal static string GlobalFilterCollection_UnsupportedFilterInstance {\n            get {\n                return ResourceManager.GetString(\"GlobalFilterCollection_UnsupportedFilterInstance\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The GET and POST HTTP methods are not supported..\n        /// </summary>\n        internal static string HtmlHelper_InvalidHttpMethod {\n            get {\n                return ResourceManager.GetString(\"HtmlHelper_InvalidHttpMethod\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The specified HttpVerbs value is not supported. The supported values are Delete, Head, Put, Options, and Patch..\n        /// </summary>\n        internal static string HtmlHelper_InvalidHttpVerb {\n            get {\n                return ResourceManager.GetString(\"HtmlHelper_InvalidHttpVerb\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to There is no ViewData item of type &apos;{1}&apos; that has the key &apos;{0}&apos;..\n        /// </summary>\n        internal static string HtmlHelper_MissingSelectData {\n            get {\n                return ResourceManager.GetString(\"HtmlHelper_MissingSelectData\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The parameter &apos;{0}&apos; must evaluate to an IEnumerable when multiple selection is allowed..\n        /// </summary>\n        internal static string HtmlHelper_SelectExpressionNotEnumerable {\n            get {\n                return ResourceManager.GetString(\"HtmlHelper_SelectExpressionNotEnumerable\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The value must be greater than or equal to zero..\n        /// </summary>\n        internal static string HtmlHelper_TextAreaParameterOutOfRange {\n            get {\n                return ResourceManager.GetString(\"HtmlHelper_TextAreaParameterOutOfRange\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The ViewData item that has the key &apos;{0}&apos; is of type &apos;{1}&apos; but must be of type &apos;{2}&apos;..\n        /// </summary>\n        internal static string HtmlHelper_WrongSelectDataType {\n            get {\n                return ResourceManager.GetString(\"HtmlHelper_WrongSelectDataType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The inline constraint resolver of type &apos;{0}&apos; was unable to resolve the following inline constraint: &apos;{1}&apos;..\n        /// </summary>\n        internal static string HttpRouteBuilder_CouldNotResolveConstraint {\n            get {\n                return ResourceManager.GetString(\"HttpRouteBuilder_CouldNotResolveConstraint\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The key is invalid JQuery syntax because it is missing a closing bracket..\n        /// </summary>\n        internal static string JQuerySyntaxMissingClosingBracket {\n            get {\n                return ResourceManager.GetString(\"JQuerySyntaxMissingClosingBracket\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet..\n        /// </summary>\n        internal static string JsonRequest_GetNotAllowed {\n            get {\n                return ResourceManager.GetString(\"JsonRequest_GetNotAllowed\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The JSON request was too large to be deserialized..\n        /// </summary>\n        internal static string JsonValueProviderFactory_RequestTooLarge {\n            get {\n                return ResourceManager.GetString(\"JsonValueProviderFactory_RequestTooLarge\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to An error occurred when trying to create the IModelBinder &apos;{0}&apos;. Make sure that the binder has a public parameterless constructor..\n        /// </summary>\n        internal static string ModelBinderAttribute_ErrorCreatingModelBinder {\n            get {\n                return ResourceManager.GetString(\"ModelBinderAttribute_ErrorCreatingModelBinder\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The type &apos;{0}&apos; does not implement the IModelBinder interface..\n        /// </summary>\n        internal static string ModelBinderAttribute_TypeNotIModelBinder {\n            get {\n                return ResourceManager.GetString(\"ModelBinderAttribute_TypeNotIModelBinder\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The type &apos;{0}&apos; contains multiple attributes that inherit from CustomModelBinderAttribute..\n        /// </summary>\n        internal static string ModelBinderDictionary_MultipleAttributes {\n            get {\n                return ResourceManager.GetString(\"ModelBinderDictionary_MultipleAttributes\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to This property setter is obsolete, because its value is derived from ModelMetadata.Model now..\n        /// </summary>\n        internal static string ModelMetadata_PropertyNotSettable {\n            get {\n                return ResourceManager.GetString(\"ModelMetadata_PropertyNotSettable\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to This constructor is obsolete, because its functionality has been moved to MvcForm(ViewContext) now..\n        /// </summary>\n        internal static string MvcForm_ConstructorObsolete {\n            get {\n                return ResourceManager.GetString(\"MvcForm_ConstructorObsolete\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &apos;inherits&apos; keyword is not allowed when a &apos;{0}&apos; keyword is used..\n        /// </summary>\n        internal static string MvcRazorCodeParser_CannotHaveModelAndInheritsKeyword {\n            get {\n                return ResourceManager.GetString(\"MvcRazorCodeParser_CannotHaveModelAndInheritsKeyword\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &apos;{0}&apos; keyword must be followed by a type name on the same line..\n        /// </summary>\n        internal static string MvcRazorCodeParser_ModelKeywordMustBeFollowedByTypeName {\n            get {\n                return ResourceManager.GetString(\"MvcRazorCodeParser_ModelKeywordMustBeFollowedByTypeName\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Only one &apos;{0}&apos; statement is allowed in a file..\n        /// </summary>\n        internal static string MvcRazorCodeParser_OnlyOneModelStatementIsAllowed {\n            get {\n                return ResourceManager.GetString(\"MvcRazorCodeParser_OnlyOneModelStatementIsAllowed\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The matched route does not include a &apos;controller&apos; route value, which is required..\n        /// </summary>\n        internal static string MvcRouteHandler_RouteValuesHasNoController {\n            get {\n                return ResourceManager.GetString(\"MvcRouteHandler_RouteValuesHasNoController\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to OutputCacheAttribute is not allowed on child actions which are children of an already cached child action..\n        /// </summary>\n        internal static string OutputCacheAttribute_CannotNestChildCache {\n            get {\n                return ResourceManager.GetString(\"OutputCacheAttribute_CannotNestChildCache\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to OutputCacheAttribute for child actions only supports Duration, VaryByCustom, and VaryByParam values. Please do not set CacheProfile, Location, NoStore, SqlDependency, VaryByContentEncoding, or VaryByHeader values for child actions..\n        /// </summary>\n        internal static string OutputCacheAttribute_ChildAction_UnsupportedSetting {\n            get {\n                return ResourceManager.GetString(\"OutputCacheAttribute_ChildAction_UnsupportedSetting\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Duration must be a positive number..\n        /// </summary>\n        internal static string OutputCacheAttribute_InvalidDuration {\n            get {\n                return ResourceManager.GetString(\"OutputCacheAttribute_InvalidDuration\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to VaryByParam must be &apos;*&apos;, &apos;none&apos;, or a semicolon-delimited list of keys..\n        /// </summary>\n        internal static string OutputCacheAttribute_InvalidVaryByParam {\n            get {\n                return ResourceManager.GetString(\"OutputCacheAttribute_InvalidVaryByParam\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Child actions are not allowed to perform redirect actions..\n        /// </summary>\n        internal static string RedirectAction_CannotRedirectInChildAction {\n            get {\n                return ResourceManager.GetString(\"RedirectAction_CannotRedirectInChildAction\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Cannot create a descriptor for instance method &apos;{0}&apos; on type &apos;{1}&apos; because the type does not derive from ControllerBase..\n        /// </summary>\n        internal static string ReflectedActionDescriptor_CannotCallInstanceMethodOnNonControllerType {\n            get {\n                return ResourceManager.GetString(\"ReflectedActionDescriptor_CannotCallInstanceMethodOnNonControllerType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Cannot call action method &apos;{0}&apos; on controller &apos;{1}&apos; because the parameter &apos;{2}&apos; is passed by reference..\n        /// </summary>\n        internal static string ReflectedActionDescriptor_CannotCallMethodsWithOutOrRefParameters {\n            get {\n                return ResourceManager.GetString(\"ReflectedActionDescriptor_CannotCallMethodsWithOutOrRefParameters\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Cannot call action method &apos;{0}&apos; on controller &apos;{1}&apos; because the action method is a generic method..\n        /// </summary>\n        internal static string ReflectedActionDescriptor_CannotCallOpenGenericMethods {\n            get {\n                return ResourceManager.GetString(\"ReflectedActionDescriptor_CannotCallOpenGenericMethods\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Cannot call action method &apos;{0}&apos; on controller &apos;{1}&apos; because the action method is a static method..\n        /// </summary>\n        internal static string ReflectedActionDescriptor_CannotCallStaticMethod {\n            get {\n                return ResourceManager.GetString(\"ReflectedActionDescriptor_CannotCallStaticMethod\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The parameters dictionary contains a null entry for parameter &apos;{0}&apos; of non-nullable type &apos;{1}&apos; for method &apos;{2}&apos; in &apos;{3}&apos;. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter..\n        /// </summary>\n        internal static string ReflectedActionDescriptor_ParameterCannotBeNull {\n            get {\n                return ResourceManager.GetString(\"ReflectedActionDescriptor_ParameterCannotBeNull\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The parameters dictionary does not contain an entry for parameter &apos;{0}&apos; of type &apos;{1}&apos; for method &apos;{2}&apos; in &apos;{3}&apos;. The dictionary must contain an entry for each parameter, including parameters that have null values..\n        /// </summary>\n        internal static string ReflectedActionDescriptor_ParameterNotInDictionary {\n            get {\n                return ResourceManager.GetString(\"ReflectedActionDescriptor_ParameterNotInDictionary\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The parameters dictionary contains an invalid entry for parameter &apos;{0}&apos; for method &apos;{1}&apos; in &apos;{2}&apos;. The dictionary contains a value of type &apos;{3}&apos;, but the parameter requires a value of type &apos;{4}&apos;..\n        /// </summary>\n        internal static string ReflectedActionDescriptor_ParameterValueHasWrongType {\n            get {\n                return ResourceManager.GetString(\"ReflectedActionDescriptor_ParameterValueHasWrongType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The parameter &apos;{0}&apos; on method &apos;{1}&apos; contains multiple attributes that inherit from CustomModelBinderAttribute..\n        /// </summary>\n        internal static string ReflectedParameterBindingInfo_MultipleConverterAttributes {\n            get {\n                return ResourceManager.GetString(\"ReflectedParameterBindingInfo_MultipleConverterAttributes\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to No url for remote validation could be found..\n        /// </summary>\n        internal static string RemoteAttribute_NoUrlFound {\n            get {\n                return ResourceManager.GetString(\"RemoteAttribute_NoUrlFound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &apos;{0}&apos; is invalid..\n        /// </summary>\n        internal static string RemoteAttribute_RemoteValidationFailed {\n            get {\n                return ResourceManager.GetString(\"RemoteAttribute_RemoteValidationFailed\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The requested resource can only be accessed via SSL..\n        /// </summary>\n        internal static string RequireHttpsAttribute_MustUseSsl {\n            get {\n                return ResourceManager.GetString(\"RequireHttpsAttribute_MustUseSsl\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A path segment that contains more than one section, such as a literal section or a parameter, cannot contain a catch-all parameter..\n        /// </summary>\n        internal static string Route_CannotHaveCatchAllInMultiSegment {\n            get {\n                return ResourceManager.GetString(\"Route_CannotHaveCatchAllInMultiSegment\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A path segment cannot contain two consecutive parameters. They must be separated by a &apos;/&apos; or by a literal string..\n        /// </summary>\n        internal static string Route_CannotHaveConsecutiveParameters {\n            get {\n                return ResourceManager.GetString(\"Route_CannotHaveConsecutiveParameters\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The route template separator character &apos;/&apos; cannot appear consecutively. It must be separated by either a parameter or a literal value..\n        /// </summary>\n        internal static string Route_CannotHaveConsecutiveSeparators {\n            get {\n                return ResourceManager.GetString(\"Route_CannotHaveConsecutiveSeparators\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A catch-all parameter can only appear as the last segment of the route template..\n        /// </summary>\n        internal static string Route_CatchAllMustBeLast {\n            get {\n                return ResourceManager.GetString(\"Route_CatchAllMustBeLast\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The constraint entry &apos;{0}&apos; on the route with route template &apos;{1}&apos; must have a string value or be of a type which implements &apos;{2}&apos;..\n        /// </summary>\n        internal static string Route_InvalidConstraint {\n            get {\n                return ResourceManager.GetString(\"Route_InvalidConstraint\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The route parameter name &apos;{0}&apos; is invalid. Route parameter names must be non-empty and cannot contain these characters: &quot;{{&quot;, &quot;}}&quot;, &quot;/&quot;, &quot;?&quot;.\n        /// </summary>\n        internal static string Route_InvalidParameterName {\n            get {\n                return ResourceManager.GetString(\"Route_InvalidParameterName\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The route template cannot start with a &apos;/&apos; or &apos;~&apos; character and it cannot contain a &apos;?&apos; character..\n        /// </summary>\n        internal static string Route_InvalidRouteTemplate {\n            get {\n                return ResourceManager.GetString(\"Route_InvalidRouteTemplate\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to There is an incomplete parameter in this path segment: &apos;{0}&apos;. Check that each &apos;{{&apos; character has a matching &apos;}}&apos; character..\n        /// </summary>\n        internal static string Route_MismatchedParameter {\n            get {\n                return ResourceManager.GetString(\"Route_MismatchedParameter\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The route parameter name &apos;{0}&apos; appears more than one time in the route template..\n        /// </summary>\n        internal static string Route_RepeatedParameter {\n            get {\n                return ResourceManager.GetString(\"Route_RepeatedParameter\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The prefix &apos;{0}&apos; of the route area named &apos;{1}&apos; on the controller named &apos;{2}&apos; cannot end with a forward slash..\n        /// </summary>\n        internal static string RouteAreaPrefix_CannotEnd_WithForwardSlash {\n            get {\n                return ResourceManager.GetString(\"RouteAreaPrefix_CannotEnd_WithForwardSlash\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The route prefix &apos;{0}&apos; on the controller named &apos;{1}&apos; cannot begin or end with a forward slash..\n        /// </summary>\n        internal static string RoutePrefix_CannotStartOrEnd_WithForwardSlash {\n            get {\n                return ResourceManager.GetString(\"RoutePrefix_CannotStartOrEnd_WithForwardSlash\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Only one route prefix attribute is supported. Remove extra attributes from the controller of type &apos;{0}&apos;..\n        /// </summary>\n        internal static string RoutePrefix_CannotSupportMultiRoutePrefix {\n            get {\n                return ResourceManager.GetString(\"RoutePrefix_CannotSupportMultiRoutePrefix\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The property &apos;prefix&apos; from route prefix attribute on controller of type &apos;{0}&apos; cannot be null..\n        /// </summary>\n        internal static string RoutePrefix_PrefixCannotBeNull {\n            get {\n                return ResourceManager.GetString(\"RoutePrefix_PrefixCannotBeNull\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The route template &apos;{0}&apos; on the action named &apos;{1}&apos; on the controller named &apos;{2}&apos; cannot begin with a forward slash..\n        /// </summary>\n        internal static string RouteTemplate_CannotStart_WithForwardSlash {\n            get {\n                return ResourceManager.GetString(\"RouteTemplate_CannotStart_WithForwardSlash\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Unable to determine ModelMetadata for expression &apos;{0}&apos;..\n        /// </summary>\n        internal static string SelectExtensions_InvalidExpressionParameterNoMetadata {\n            get {\n                return ResourceManager.GetString(\"SelectExtensions_InvalidExpressionParameterNoMetadata\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Unable to determine type of expression &apos;{0}&apos;..\n        /// </summary>\n        internal static string SelectExtensions_InvalidExpressionParameterNoModelType {\n            get {\n                return ResourceManager.GetString(\"SelectExtensions_InvalidExpressionParameterNoModelType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Return type &apos;{0}&apos; is not supported..\n        /// </summary>\n        internal static string SelectExtensions_InvalidExpressionParameterType {\n            get {\n                return ResourceManager.GetString(\"SelectExtensions_InvalidExpressionParameterType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Return type &apos;{0}&apos; is not supported. Type must not have a &apos;{1}&apos; attribute..\n        /// </summary>\n        internal static string SelectExtensions_InvalidExpressionParameterTypeHasFlags {\n            get {\n                return ResourceManager.GetString(\"SelectExtensions_InvalidExpressionParameterTypeHasFlags\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The SessionStateTempDataProvider class requires session state to be enabled..\n        /// </summary>\n        internal static string SessionStateTempDataProvider_SessionStateDisabled {\n            get {\n                return ResourceManager.GetString(\"SessionStateTempDataProvider_SessionStateDisabled\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to An instance of {0} was found in the resolver as well as a custom registered provider in {1}. Please set only one or the other..\n        /// </summary>\n        internal static string SingleServiceResolver_CannotRegisterTwoInstances {\n            get {\n                return ResourceManager.GetString(\"SingleServiceResolver_CannotRegisterTwoInstances\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A route named &apos;{0}&apos; is already in the route collection. Route names must be unique.\n        ///\n        ///Duplicates:\n        ///{1}\n        ///{2}.\n        /// </summary>\n        internal static string SubRouteCollection_DuplicateRouteName {\n            get {\n                return ResourceManager.GetString(\"SubRouteCollection_DuplicateRouteName\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to An operation that crossed a synchronization context failed. See the inner exception for more information..\n        /// </summary>\n        internal static string SynchronizationContextUtil_ExceptionThrown {\n            get {\n                return ResourceManager.GetString(\"SynchronizationContextUtil_ExceptionThrown\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The asynchronous action method &apos;{0}&apos; returns a Task, which cannot be executed synchronously..\n        /// </summary>\n        internal static string TaskAsyncActionDescriptor_CannotExecuteSynchronously {\n            get {\n                return ResourceManager.GetString(\"TaskAsyncActionDescriptor_CannotExecuteSynchronously\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Unable to locate an appropriate template for type {0}..\n        /// </summary>\n        internal static string TemplateHelpers_NoTemplate {\n            get {\n                return ResourceManager.GetString(\"TemplateHelpers_NoTemplate\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions..\n        /// </summary>\n        internal static string TemplateHelpers_TemplateLimitations {\n            get {\n                return ResourceManager.GetString(\"TemplateHelpers_TemplateLimitations\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The Collection template was used with an object of type &apos;{0}&apos;, which does not implement System.IEnumerable..\n        /// </summary>\n        internal static string Templates_TypeMustImplementIEnumerable {\n            get {\n                return ResourceManager.GetString(\"Templates_TypeMustImplementIEnumerable\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to This file is automatically generated. Please do not modify the contents of this file..\n        /// </summary>\n        internal static string TypeCache_DoNotModify {\n            get {\n                return ResourceManager.GetString(\"TypeCache_DoNotModify\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to {0} Object type &apos;{1}&apos;..\n        /// </summary>\n        internal static string TypeHelpers_CannotCreateInstance {\n            get {\n                return ResourceManager.GetString(\"TypeHelpers_CannotCreateInstance\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to {0}.{1} must not return null..\n        /// </summary>\n        internal static string TypeMethodMustNotReturnNull {\n            get {\n                return ResourceManager.GetString(\"TypeMethodMustNotReturnNull\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The model object inside the metadata claimed to be compatible with {0}, but was actually {1}..\n        /// </summary>\n        internal static string ValidatableObjectAdapter_IncompatibleType {\n            get {\n                return ResourceManager.GetString(\"ValidatableObjectAdapter_IncompatibleType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The parameter conversion from type &apos;{0}&apos; to type &apos;{1}&apos; failed. See the inner exception for more information..\n        /// </summary>\n        internal static string ValueProviderResult_ConversionThrew {\n            get {\n                return ResourceManager.GetString(\"ValueProviderResult_ConversionThrew\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The parameter conversion from type &apos;{0}&apos; to type &apos;{1}&apos; failed because no type converter can convert between these types..\n        /// </summary>\n        internal static string ValueProviderResult_NoConverterExists {\n            get {\n                return ResourceManager.GetString(\"ValueProviderResult_NoConverterExists\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type &apos;{0}&apos;..\n        /// </summary>\n        internal static string ViewDataDictionary_ModelCannotBeNull {\n            get {\n                return ResourceManager.GetString(\"ViewDataDictionary_ModelCannotBeNull\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The model item passed into the dictionary is of type &apos;{0}&apos;, but this dictionary requires a model item of type &apos;{1}&apos;..\n        /// </summary>\n        internal static string ViewDataDictionary_WrongTModelType {\n            get {\n                return ResourceManager.GetString(\"ViewDataDictionary_WrongTModelType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A ViewMasterPage can be used only with content pages that derive from ViewPage or ViewPage&lt;TModel&gt;..\n        /// </summary>\n        internal static string ViewMasterPage_RequiresViewPage {\n            get {\n                return ResourceManager.GetString(\"ViewMasterPage_RequiresViewPage\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Execution of the child request failed. Please examine the InnerException for more information..\n        /// </summary>\n        internal static string ViewPageHttpHandlerWrapper_ExceptionOccurred {\n            get {\n                return ResourceManager.GetString(\"ViewPageHttpHandlerWrapper_ExceptionOccurred\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A ViewStartPage can be used only with with a page that derives from WebViewPage or another ViewStartPage..\n        /// </summary>\n        internal static string ViewStartPage_RequiresMvcRazorView {\n            get {\n                return ResourceManager.GetString(\"ViewStartPage_RequiresMvcRazorView\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The ViewUserControl &apos;{0}&apos; cannot find an IViewDataContainer object. The ViewUserControl must be inside a ViewPage, a ViewMasterPage, or another ViewUserControl..\n        /// </summary>\n        internal static string ViewUserControl_RequiresViewDataProvider {\n            get {\n                return ResourceManager.GetString(\"ViewUserControl_RequiresViewDataProvider\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A ViewUserControl can be used only in pages that derive from ViewPage or ViewPage&lt;TModel&gt;..\n        /// </summary>\n        internal static string ViewUserControl_RequiresViewPage {\n            get {\n                return ResourceManager.GetString(\"ViewUserControl_RequiresViewPage\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A master name cannot be specified when the view is a ViewUserControl..\n        /// </summary>\n        internal static string WebFormViewEngine_UserControlCannotHaveMaster {\n            get {\n                return ResourceManager.GetString(\"WebFormViewEngine_UserControlCannotHaveMaster\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The view at &apos;{0}&apos; must derive from ViewPage, ViewPage&lt;TModel&gt;, ViewUserControl, or ViewUserControl&lt;TModel&gt;..\n        /// </summary>\n        internal static string WebFormViewEngine_WrongViewBase {\n            get {\n                return ResourceManager.GetString(\"WebFormViewEngine_WrongViewBase\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Properties/MvcResources.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"ActionMethodSelector_AmbiguousMatch\" xml:space=\"preserve\">\n    <value>The current request for action '{0}' on controller type '{1}' is ambiguous between the following action methods:{2}</value>\n  </data>\n  <data name=\"Common_NoRouteMatched\" xml:space=\"preserve\">\n    <value>No route in the route table matches the supplied values.</value>\n  </data>\n  <data name=\"Common_NullOrEmpty\" xml:space=\"preserve\">\n    <value>Value cannot be null or empty.</value>\n  </data>\n  <data name=\"Common_PartialViewNotFound\" xml:space=\"preserve\">\n    <value>The partial view '{0}' was not found or no view engine supports the searched locations. The following locations were searched:{1}</value>\n  </data>\n  <data name=\"Common_PropertyCannotBeNullOrEmpty\" xml:space=\"preserve\">\n    <value>The property '{0}' cannot be null or empty.</value>\n  </data>\n  <data name=\"Common_ViewNotFound\" xml:space=\"preserve\">\n    <value>The view '{0}' or its master was not found or no view engine supports the searched locations. The following locations were searched:{1}</value>\n  </data>\n  <data name=\"ControllerBuilder_ErrorCreatingControllerFactory\" xml:space=\"preserve\">\n    <value>An error occurred when trying to create the IControllerFactory '{0}'. Make sure that the controller factory has a public parameterless constructor.</value>\n  </data>\n  <data name=\"ControllerBuilder_FactoryReturnedNull\" xml:space=\"preserve\">\n    <value>The IControllerFactory '{0}' did not return a controller for the name '{1}'.</value>\n  </data>\n  <data name=\"ControllerBuilder_MissingIControllerFactory\" xml:space=\"preserve\">\n    <value>The controller factory type '{0}' must implement the IControllerFactory interface.</value>\n  </data>\n  <data name=\"Controller_UnknownAction\" xml:space=\"preserve\">\n    <value>A public action method '{0}' was not found on controller '{1}'.</value>\n  </data>\n  <data name=\"DefaultControllerFactory_ErrorCreatingController\" xml:space=\"preserve\">\n    <value>An error occurred when trying to create a controller of type '{0}'. Make sure that the controller has a parameterless public constructor.</value>\n  </data>\n  <data name=\"DefaultControllerFactory_NoControllerFound\" xml:space=\"preserve\">\n    <value>The controller for path '{0}' was not found or does not implement IController.</value>\n  </data>\n  <data name=\"DefaultControllerFactory_TypeDoesNotSubclassControllerBase\" xml:space=\"preserve\">\n    <value>The controller type '{0}' must implement IController.</value>\n  </data>\n  <data name=\"ValueProviderResult_ConversionThrew\" xml:space=\"preserve\">\n    <value>The parameter conversion from type '{0}' to type '{1}' failed. See the inner exception for more information.</value>\n  </data>\n  <data name=\"ValueProviderResult_NoConverterExists\" xml:space=\"preserve\">\n    <value>The parameter conversion from type '{0}' to type '{1}' failed because no type converter can convert between these types.</value>\n  </data>\n  <data name=\"ExceptionViewAttribute_NonExceptionType\" xml:space=\"preserve\">\n    <value>The type '{0}' does not inherit from Exception.</value>\n  </data>\n  <data name=\"FilterAttribute_OrderOutOfRange\" xml:space=\"preserve\">\n    <value>Order must be greater than or equal to -1.</value>\n  </data>\n  <data name=\"HtmlHelper_MissingSelectData\" xml:space=\"preserve\">\n    <value>There is no ViewData item of type '{1}' that has the key '{0}'.</value>\n  </data>\n  <data name=\"HtmlHelper_TextAreaParameterOutOfRange\" xml:space=\"preserve\">\n    <value>The value must be greater than or equal to zero.</value>\n  </data>\n  <data name=\"HtmlHelper_WrongSelectDataType\" xml:space=\"preserve\">\n    <value>The ViewData item that has the key '{0}' is of type '{1}' but must be of type '{2}'.</value>\n  </data>\n  <data name=\"ModelBinderAttribute_ErrorCreatingModelBinder\" xml:space=\"preserve\">\n    <value>An error occurred when trying to create the IModelBinder '{0}'. Make sure that the binder has a public parameterless constructor.</value>\n  </data>\n  <data name=\"ModelBinderAttribute_TypeNotIModelBinder\" xml:space=\"preserve\">\n    <value>The type '{0}' does not implement the IModelBinder interface.</value>\n  </data>\n  <data name=\"ModelBinderDictionary_MultipleAttributes\" xml:space=\"preserve\">\n    <value>The type '{0}' contains multiple attributes that inherit from CustomModelBinderAttribute.</value>\n  </data>\n  <data name=\"SessionStateTempDataProvider_SessionStateDisabled\" xml:space=\"preserve\">\n    <value>The SessionStateTempDataProvider class requires session state to be enabled.</value>\n  </data>\n  <data name=\"ViewDataDictionary_WrongTModelType\" xml:space=\"preserve\">\n    <value>The model item passed into the dictionary is of type '{0}', but this dictionary requires a model item of type '{1}'.</value>\n  </data>\n  <data name=\"ViewMasterPage_RequiresViewPage\" xml:space=\"preserve\">\n    <value>A ViewMasterPage can be used only with content pages that derive from ViewPage or ViewPage&lt;TModel&gt;.</value>\n  </data>\n  <data name=\"ViewUserControl_RequiresViewDataProvider\" xml:space=\"preserve\">\n    <value>The ViewUserControl '{0}' cannot find an IViewDataContainer object. The ViewUserControl must be inside a ViewPage, a ViewMasterPage, or another ViewUserControl.</value>\n  </data>\n  <data name=\"ViewUserControl_RequiresViewPage\" xml:space=\"preserve\">\n    <value>A ViewUserControl can be used only in pages that derive from ViewPage or ViewPage&lt;TModel&gt;.</value>\n  </data>\n  <data name=\"WebFormViewEngine_UserControlCannotHaveMaster\" xml:space=\"preserve\">\n    <value>A master name cannot be specified when the view is a ViewUserControl.</value>\n  </data>\n  <data name=\"WebFormViewEngine_WrongViewBase\" xml:space=\"preserve\">\n    <value>The view at '{0}' must derive from ViewPage, ViewPage&lt;TModel&gt;, ViewUserControl, or ViewUserControl&lt;TModel&gt;.</value>\n  </data>\n  <data name=\"Common_ValueNotValidForProperty\" xml:space=\"preserve\">\n    <value>The value '{0}' is invalid.</value>\n  </data>\n  <data name=\"ActionMethodSelector_AmbiguousMatchType\" xml:space=\"preserve\">\n    <value>{0} on type {1}</value>\n  </data>\n  <data name=\"Controller_UpdateModel_UpdateUnsuccessful\" xml:space=\"preserve\">\n    <value>The model of type '{0}' could not be updated.</value>\n  </data>\n  <data name=\"DefaultModelBinder_ValueRequired\" xml:space=\"preserve\">\n    <value>A value is required.</value>\n  </data>\n  <data name=\"ReflectedActionDescriptor_ParameterCannotBeNull\" xml:space=\"preserve\">\n    <value>The parameters dictionary contains a null entry for parameter '{0}' of non-nullable type '{1}' for method '{2}' in '{3}'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.</value>\n  </data>\n  <data name=\"ReflectedActionDescriptor_ParameterNotInDictionary\" xml:space=\"preserve\">\n    <value>The parameters dictionary does not contain an entry for parameter '{0}' of type '{1}' for method '{2}' in '{3}'. The dictionary must contain an entry for each parameter, including parameters that have null values.</value>\n  </data>\n  <data name=\"ReflectedActionDescriptor_ParameterValueHasWrongType\" xml:space=\"preserve\">\n    <value>The parameters dictionary contains an invalid entry for parameter '{0}' for method '{1}' in '{2}'. The dictionary contains a value of type '{3}', but the parameter requires a value of type '{4}'.</value>\n  </data>\n  <data name=\"ReflectedParameterBindingInfo_MultipleConverterAttributes\" xml:space=\"preserve\">\n    <value>The parameter '{0}' on method '{1}' contains multiple attributes that inherit from CustomModelBinderAttribute.</value>\n  </data>\n  <data name=\"ReflectedActionDescriptor_CannotCallInstanceMethodOnNonControllerType\" xml:space=\"preserve\">\n    <value>Cannot create a descriptor for instance method '{0}' on type '{1}' because the type does not derive from ControllerBase.</value>\n  </data>\n  <data name=\"ReflectedActionDescriptor_CannotCallMethodsWithOutOrRefParameters\" xml:space=\"preserve\">\n    <value>Cannot call action method '{0}' on controller '{1}' because the parameter '{2}' is passed by reference.</value>\n  </data>\n  <data name=\"ReflectedActionDescriptor_CannotCallOpenGenericMethods\" xml:space=\"preserve\">\n    <value>Cannot call action method '{0}' on controller '{1}' because the action method is a generic method.</value>\n  </data>\n  <data name=\"Route_CannotHaveCatchAllInMultiSegment\" xml:space=\"preserve\">\n    <value>A path segment that contains more than one section, such as a literal section or a parameter, cannot contain a catch-all parameter.</value>\n  </data>\n  <data name=\"Route_CannotHaveConsecutiveParameters\" xml:space=\"preserve\">\n    <value>A path segment cannot contain two consecutive parameters. They must be separated by a '/' or by a literal string.</value>\n  </data>\n  <data name=\"Route_CannotHaveConsecutiveSeparators\" xml:space=\"preserve\">\n    <value>The route template separator character '/' cannot appear consecutively. It must be separated by either a parameter or a literal value.</value>\n  </data>\n  <data name=\"Route_CatchAllMustBeLast\" xml:space=\"preserve\">\n    <value>A catch-all parameter can only appear as the last segment of the route template.</value>\n  </data>\n  <data name=\"Route_InvalidParameterName\" xml:space=\"preserve\">\n    <value>The route parameter name '{0}' is invalid. Route parameter names must be non-empty and cannot contain these characters: \"{{\", \"}}\", \"/\", \"?\"</value>\n  </data>\n  <data name=\"Route_InvalidRouteTemplate\" xml:space=\"preserve\">\n    <value>The route template cannot start with a '/' or '~' character and it cannot contain a '?' character.</value>\n  </data>\n  <data name=\"Route_MismatchedParameter\" xml:space=\"preserve\">\n    <value>There is an incomplete parameter in this path segment: '{0}'. Check that each '{{' character has a matching '}}' character.</value>\n  </data>\n  <data name=\"Route_RepeatedParameter\" xml:space=\"preserve\">\n    <value>The route parameter name '{0}' appears more than one time in the route template.</value>\n  </data>\n  <data name=\"DefaultViewLocationCache_NegativeTimeSpan\" xml:space=\"preserve\">\n    <value>The number of ticks for the TimeSpan value must be greater than or equal to 0.</value>\n  </data>\n  <data name=\"DefaultModelBinder_ValueInvalid\" xml:space=\"preserve\">\n    <value>The value '{0}' is not valid for {1}.</value>\n  </data>\n  <data name=\"TemplateHelpers_TemplateLimitations\" xml:space=\"preserve\">\n    <value>Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.</value>\n  </data>\n  <data name=\"Common_TriState_False\" xml:space=\"preserve\">\n    <value>False</value>\n  </data>\n  <data name=\"Common_TriState_NotSet\" xml:space=\"preserve\">\n    <value>Not Set</value>\n  </data>\n  <data name=\"Common_TriState_True\" xml:space=\"preserve\">\n    <value>True</value>\n  </data>\n  <data name=\"ControllerBase_CannotHandleMultipleRequests\" xml:space=\"preserve\">\n    <value>A single instance of controller '{0}' cannot be used to handle multiple requests. If a custom controller factory is in use, make sure that it creates a new instance of the controller for each request.</value>\n  </data>\n  <data name=\"Common_PropertyNotFound\" xml:space=\"preserve\">\n    <value>The property {0}.{1} could not be found.</value>\n  </data>\n  <data name=\"DataAnnotationsModelMetadataProvider_UnknownProperty\" xml:space=\"preserve\">\n    <value>{0} has a DisplayColumn attribute for {1}, but property {1} does not exist.</value>\n  </data>\n  <data name=\"DataAnnotationsModelMetadataProvider_UnreadableProperty\" xml:space=\"preserve\">\n    <value>{0} has a DisplayColumn attribute for {1}, but property {1} does not have a public getter.</value>\n  </data>\n  <data name=\"TemplateHelpers_NoTemplate\" xml:space=\"preserve\">\n    <value>Unable to locate an appropriate template for type {0}.</value>\n  </data>\n  <data name=\"RequireHttpsAttribute_MustUseSsl\" xml:space=\"preserve\">\n    <value>The requested resource can only be accessed via SSL.</value>\n  </data>\n  <data name=\"HtmlHelper_InvalidHttpVerb\" xml:space=\"preserve\">\n    <value>The specified HttpVerbs value is not supported. The supported values are Delete, Head, Put, Options, and Patch.</value>\n  </data>\n  <data name=\"HtmlHelper_InvalidHttpMethod\" xml:space=\"preserve\">\n    <value>The GET and POST HTTP methods are not supported.</value>\n  </data>\n  <data name=\"JsonRequest_GetNotAllowed\" xml:space=\"preserve\">\n    <value>This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.</value>\n  </data>\n  <data name=\"ModelMetadata_PropertyNotSettable\" xml:space=\"preserve\">\n    <value>This property setter is obsolete, because its value is derived from ModelMetadata.Model now.</value>\n  </data>\n  <data name=\"ViewDataDictionary_ModelCannotBeNull\" xml:space=\"preserve\">\n    <value>The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type '{0}'.</value>\n  </data>\n  <data name=\"Common_TypeMustDriveFromType\" xml:space=\"preserve\">\n    <value>The type {0} must derive from {1}</value>\n  </data>\n  <data name=\"DataAnnotationsModelValidatorProvider_ConstructorRequirements\" xml:space=\"preserve\">\n    <value>The type {0} must have a public constructor which accepts three parameters of types {1}, {2}, and {3}</value>\n  </data>\n  <data name=\"ViewPageHttpHandlerWrapper_ExceptionOccurred\" xml:space=\"preserve\">\n    <value>Execution of the child request failed. Please examine the InnerException for more information.</value>\n  </data>\n  <data name=\"RedirectAction_CannotRedirectInChildAction\" xml:space=\"preserve\">\n    <value>Child actions are not allowed to perform redirect actions.</value>\n  </data>\n  <data name=\"AsyncCommon_AsyncResultAlreadyConsumed\" xml:space=\"preserve\">\n    <value>The provided IAsyncResult has already been consumed.</value>\n  </data>\n  <data name=\"AsyncCommon_InvalidAsyncResult\" xml:space=\"preserve\">\n    <value>The provided IAsyncResult is not valid for this method.</value>\n  </data>\n  <data name=\"SynchronizationContextUtil_ExceptionThrown\" xml:space=\"preserve\">\n    <value>An operation that crossed a synchronization context failed. See the inner exception for more information.</value>\n  </data>\n  <data name=\"AsyncCommon_ControllerMustImplementIAsyncManagerContainer\" xml:space=\"preserve\">\n    <value>The controller of type '{0}' must subclass AsyncController or implement the IAsyncManagerContainer interface.</value>\n  </data>\n  <data name=\"AsyncCommon_InvalidTimeout\" xml:space=\"preserve\">\n    <value>The timeout value must be non-negative or Timeout.Infinite.</value>\n  </data>\n  <data name=\"AsyncActionMethodSelector_AmbiguousMethodMatch\" xml:space=\"preserve\">\n    <value>Lookup for method '{0}' on controller type '{1}' failed because of an ambiguity between the following methods:{2}</value>\n  </data>\n  <data name=\"AsyncActionMethodSelector_CouldNotFindMethod\" xml:space=\"preserve\">\n    <value>Could not locate a method named '{0}' on controller type {1}.</value>\n  </data>\n  <data name=\"ChildActionOnlyAttribute_MustBeInChildRequest\" xml:space=\"preserve\">\n    <value>The action '{0}' is accessible only by a child request.</value>\n  </data>\n  <data name=\"Templates_TypeMustImplementIEnumerable\" xml:space=\"preserve\">\n    <value>The Collection template was used with an object of type '{0}', which does not implement System.IEnumerable.</value>\n  </data>\n  <data name=\"TypeCache_DoNotModify\" xml:space=\"preserve\">\n    <value>This file is automatically generated. Please do not modify the contents of this file.</value>\n  </data>\n  <data name=\"ClientDataTypeModelValidatorProvider_FieldMustBeNumeric\" xml:space=\"preserve\">\n    <value>The field {0} must be a number.</value>\n  </data>\n  <data name=\"ExpressionHelper_InvalidIndexerExpression\" xml:space=\"preserve\">\n    <value>The expression compiler was unable to evaluate the indexer expression '{0}' because it references the model parameter '{1}' which is unavailable.</value>\n  </data>\n  <data name=\"Controller_Validate_ValidationFailed\" xml:space=\"preserve\">\n    <value>The model of type '{0}' is not valid.</value>\n  </data>\n  <data name=\"DefaultControllerFactory_ControllerNameAmbiguous_WithoutRouteUrl\" xml:space=\"preserve\">\n    <value>Multiple types were found that match the controller named '{0}'. This can happen if the route that services this request does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces' parameter.{2}{2}The request for '{0}' has found the following matching controllers:{1}</value>\n  </data>\n  <data name=\"DefaultControllerFactory_ControllerNameAmbiguous_WithRouteUrl\" xml:space=\"preserve\">\n    <value>Multiple types were found that match the controller named '{0}'. This can happen if the route that services this request ('{1}') does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces' parameter.{3}{3}The request for '{0}' has found the following matching controllers:{2}</value>\n  </data>\n  <data name=\"DataAnnotationsModelValidatorProvider_ValidatableConstructorRequirements\" xml:space=\"preserve\">\n    <value>The type {0} must have a public constructor which accepts two parameters of types {1} and {2}.</value>\n  </data>\n  <data name=\"ValidatableObjectAdapter_IncompatibleType\" xml:space=\"preserve\">\n    <value>The model object inside the metadata claimed to be compatible with {0}, but was actually {1}.</value>\n  </data>\n  <data name=\"CshtmlView_ViewCouldNotBeCreated\" xml:space=\"preserve\">\n    <value>The view found at '{0}' was not created.</value>\n  </data>\n  <data name=\"CshtmlView_WrongViewBase\" xml:space=\"preserve\">\n    <value>The view at '{0}' must derive from WebViewPage, or WebViewPage&lt;TModel&gt;.</value>\n  </data>\n  <data name=\"ReflectedActionDescriptor_CannotCallStaticMethod\" xml:space=\"preserve\">\n    <value>Cannot call action method '{0}' on controller '{1}' because the action method is a static method.</value>\n  </data>\n  <data name=\"MvcRazorCodeParser_ModelKeywordMustBeFollowedByTypeName\" xml:space=\"preserve\">\n    <value>The '{0}' keyword must be followed by a type name on the same line.</value>\n  </data>\n  <data name=\"MvcRazorCodeParser_CannotHaveModelAndInheritsKeyword\" xml:space=\"preserve\">\n    <value>The 'inherits' keyword is not allowed when a '{0}' keyword is used.</value>\n  </data>\n  <data name=\"MvcRazorCodeParser_OnlyOneModelStatementIsAllowed\" xml:space=\"preserve\">\n    <value>Only one '{0}' statement is allowed in a file.</value>\n  </data>\n  <data name=\"SingleServiceResolver_CannotRegisterTwoInstances\" xml:space=\"preserve\">\n    <value>An instance of {0} was found in the resolver as well as a custom registered provider in {1}. Please set only one or the other.</value>\n  </data>\n  <data name=\"DependencyResolver_DoesNotImplementICommonServiceLocator\" xml:space=\"preserve\">\n    <value>The type {0} does not appear to implement Microsoft.Practices.ServiceLocation.IServiceLocator.</value>\n  </data>\n  <data name=\"ViewStartPage_RequiresMvcRazorView\" xml:space=\"preserve\">\n    <value>A ViewStartPage can be used only with with a page that derives from WebViewPage or another ViewStartPage.</value>\n  </data>\n  <data name=\"ControllerBase_CannotExecuteWithNullHttpContext\" xml:space=\"preserve\">\n    <value>Cannot execute Controller with a null HttpContext.</value>\n  </data>\n  <data name=\"CompareAttribute_MustMatch\" xml:space=\"preserve\">\n    <value>'{0}' and '{1}' do not match.</value>\n  </data>\n  <data name=\"RemoteAttribute_RemoteValidationFailed\" xml:space=\"preserve\">\n    <value>'{0}' is invalid.</value>\n  </data>\n  <data name=\"RemoteAttribute_NoUrlFound\" xml:space=\"preserve\">\n    <value>No url for remote validation could be found.</value>\n  </data>\n  <data name=\"AuthorizeAttribute_CannotUseWithinChildActionCache\" xml:space=\"preserve\">\n    <value>AuthorizeAttribute cannot be used within a child action caching block.</value>\n  </data>\n  <data name=\"OutputCacheAttribute_InvalidDuration\" xml:space=\"preserve\">\n    <value>Duration must be a positive number.</value>\n  </data>\n  <data name=\"OutputCacheAttribute_InvalidVaryByParam\" xml:space=\"preserve\">\n    <value>VaryByParam must be '*', 'none', or a semicolon-delimited list of keys.</value>\n  </data>\n  <data name=\"OutputCacheAttribute_ChildAction_UnsupportedSetting\" xml:space=\"preserve\">\n    <value>OutputCacheAttribute for child actions only supports Duration, VaryByCustom, and VaryByParam values. Please do not set CacheProfile, Location, NoStore, SqlDependency, VaryByContentEncoding, or VaryByHeader values for child actions.</value>\n  </data>\n  <data name=\"OutputCacheAttribute_CannotNestChildCache\" xml:space=\"preserve\">\n    <value>OutputCacheAttribute is not allowed on child actions which are children of an already cached child action.</value>\n  </data>\n  <data name=\"CompareAttribute_UnknownProperty\" xml:space=\"preserve\">\n    <value>Could not find a property named {0}.</value>\n  </data>\n  <data name=\"HtmlHelper_SelectExpressionNotEnumerable\" xml:space=\"preserve\">\n    <value>The parameter '{0}' must evaluate to an IEnumerable when multiple selection is allowed.</value>\n  </data>\n  <data name=\"MvcRouteHandler_RouteValuesHasNoController\" xml:space=\"preserve\">\n    <value>The matched route does not include a 'controller' route value, which is required.</value>\n  </data>\n  <data name=\"ClientDataTypeModelValidatorProvider_FieldMustBeDate\" xml:space=\"preserve\">\n    <value>The field {0} must be a date.</value>\n  </data>\n  <data name=\"TaskAsyncActionDescriptor_CannotExecuteSynchronously\" xml:space=\"preserve\">\n    <value>The asynchronous action method '{0}' returns a Task, which cannot be executed synchronously.</value>\n  </data>\n  <data name=\"AsyncActionDescriptor_CannotExecuteSynchronously\" xml:space=\"preserve\">\n    <value>The asynchronous action method '{0}' cannot be executed synchronously.</value>\n  </data>\n  <data name=\"MvcForm_ConstructorObsolete\" xml:space=\"preserve\">\n    <value>This constructor is obsolete, because its functionality has been moved to MvcForm(ViewContext) now.</value>\n  </data>\n  <data name=\"JsonValueProviderFactory_RequestTooLarge\" xml:space=\"preserve\">\n    <value>The JSON request was too large to be deserialized.</value>\n  </data>\n  <data name=\"GlobalFilterCollection_UnsupportedFilterInstance\" xml:space=\"preserve\">\n    <value>The given filter instance must implement one or more of the following filter interfaces: {0}, {1}, {2}, {3}, {4}.</value>\n  </data>\n  <data name=\"ArgumentMustBeGreaterThanOrEqualTo\" xml:space=\"preserve\">\n    <value>Value must be greater than or equal to {0}.</value>\n  </data>\n  <data name=\"DefaultInlineConstraintResolver_AmbiguousCtors\" xml:space=\"preserve\">\n    <value>The constructor to use for activating the constraint type '{0}' is ambiguous. Multiple constructors were found with the following number of parameters: {1}.</value>\n  </data>\n  <data name=\"DefaultInlineConstraintResolver_CouldNotFindCtor\" xml:space=\"preserve\">\n    <value>Could not find a constructor for constraint type '{0}' with the following number of parameters: {1}.</value>\n  </data>\n  <data name=\"DefaultInlineConstraintResolver_TypeNotConstraint\" xml:space=\"preserve\">\n    <value>The constraint type '{0}' which is mapped to constraint key '{1}' must implement the IRouteConstraint interface.</value>\n  </data>\n  <data name=\"HttpRouteBuilder_CouldNotResolveConstraint\" xml:space=\"preserve\">\n    <value>The inline constraint resolver of type '{0}' was unable to resolve the following inline constraint: '{1}'.</value>\n  </data>\n  <data name=\"RouteTemplate_CannotStart_WithForwardSlash\" xml:space=\"preserve\">\n    <value>The route template '{0}' on the action named '{1}' on the controller named '{2}' cannot begin with a forward slash.</value>\n  </data>\n  <data name=\"AttributeRouting_CouldNotInferAreaNameFromMissingNamespace\" xml:space=\"preserve\">\n    <value>Could not infer area name for the controller '{0}' because it does not have a namespace.</value>\n  </data>\n  <data name=\"RouteAreaPrefix_CannotEnd_WithForwardSlash\" xml:space=\"preserve\">\n    <value>The prefix '{0}' of the route area named '{1}' on the controller named '{2}' cannot end with a forward slash.</value>\n  </data>\n  <data name=\"RoutePrefix_CannotStartOrEnd_WithForwardSlash\" xml:space=\"preserve\">\n    <value>The route prefix '{0}' on the controller named '{1}' cannot begin or end with a forward slash.</value>\n  </data>\n  <data name=\"TypeHelpers_CannotCreateInstance\" xml:space=\"preserve\">\n    <value>{0} Object type '{1}'.</value>\n  </data>\n  <data name=\"EnumHelper_InvalidMetadataParameter\" xml:space=\"preserve\">\n    <value>ModelType property must not be null.</value>\n  </data>\n  <data name=\"EnumHelper_InvalidValueParameter\" xml:space=\"preserve\">\n    <value>Invalid value parameter type '{0}'. Must match type parameter '{1}'.</value>\n  </data>\n  <data name=\"EnumHelper_InvalidParameterType\" xml:space=\"preserve\">\n    <value>Type '{0}' is not supported.</value>\n  </data>\n  <data name=\"SelectExtensions_InvalidExpressionParameterNoMetadata\" xml:space=\"preserve\">\n    <value>Unable to determine ModelMetadata for expression '{0}'.</value>\n  </data>\n  <data name=\"SelectExtensions_InvalidExpressionParameterNoModelType\" xml:space=\"preserve\">\n    <value>Unable to determine type of expression '{0}'.</value>\n  </data>\n  <data name=\"SelectExtensions_InvalidExpressionParameterType\" xml:space=\"preserve\">\n    <value>Return type '{0}' is not supported.</value>\n  </data>\n  <data name=\"SelectExtensions_InvalidExpressionParameterTypeHasFlags\" xml:space=\"preserve\">\n    <value>Return type '{0}' is not supported. Type must not have a '{1}' attribute.</value>\n  </data>\n  <data name=\"DefaultControllerFactory_DirectRouteAmbiguous\" xml:space=\"preserve\">\n    <value>Multiple controller types were found that match the URL. This can happen if attribute routes on multiple controllers match the requested URL.{1}{1}The request has found the following matching controller types: {0}</value>\n  </data>\n  <data name=\"DirectRoute_AmbiguousMatch\" xml:space=\"preserve\">\n    <value>The current request is ambiguous between the following action methods:{0}</value>\n  </data>\n  <data name=\"Controller_UnknownAction_NoActionName\" xml:space=\"preserve\">\n    <value>No matching action was found on controller '{0}'. This can happen when a controller uses RouteAttribute for routing, but no action on that controller matches the request.</value>\n  </data>\n  <data name=\"DirectRoute_MissingControllerType\" xml:space=\"preserve\">\n    <value>The route does not have an associated controller type. Routing requires that each direct route map to a single controller type.</value>\n  </data>\n  <data name=\"DirectRoute_MissingActionDescriptors\" xml:space=\"preserve\">\n    <value>The route does not have any associated action descriptors. Routing requires that each direct route map to a non-empty set of actions.</value>\n  </data>\n  <data name=\"DirectRoute_MissingControllerDescriptor\" xml:space=\"preserve\">\n    <value>The route does not have an associated controller descriptor. Routing requires that each direct route map to a single controller.</value>\n  </data>\n  <data name=\"SubRouteCollection_DuplicateRouteName\" xml:space=\"preserve\">\n    <value>A route named '{0}' is already in the route collection. Route names must be unique.\n\nDuplicates:\n{1}\n{2}</value>\n  </data>\n  <data name=\"TypeMethodMustNotReturnNull\" xml:space=\"preserve\">\n    <value>{0}.{1} must not return null.</value>\n  </data>\n  <data name=\"RoutePrefix_CannotSupportMultiRoutePrefix\" xml:space=\"preserve\">\n    <value>Only one route prefix attribute is supported. Remove extra attributes from the controller of type '{0}'.</value>\n  </data>\n  <data name=\"RoutePrefix_PrefixCannotBeNull\" xml:space=\"preserve\">\n    <value>The property 'prefix' from route prefix attribute on controller of type '{0}' cannot be null.</value>\n  </data>\n  <data name=\"Route_InvalidConstraint\" xml:space=\"preserve\">\n    <value>The constraint entry '{0}' on the route with route template '{1}' must have a string value or be of a type which implements '{2}'.</value>\n  </data>\n  <data name=\"DirectRoute_RouteHandlerNotSupported\" xml:space=\"preserve\">\n    <value>Direct routing does not support per-route route handlers.</value>\n  </data>\n  <data name=\"DirectRoute_InvalidParameter_Action\" xml:space=\"preserve\">\n    <value>A direct route for an action method cannot use the parameter 'action'. Specify a literal path in place of this parameter to create a route to the action.</value>\n  </data>\n  <data name=\"DirectRoute_InvalidParameter_Controller\" xml:space=\"preserve\">\n    <value>A direct route cannot use the parameter 'controller'. Specify a literal path in place of this parameter to create a route to a controller.</value>\n  </data>\n  <data name=\"JQuerySyntaxMissingClosingBracket\" xml:space=\"preserve\">\n    <value>The key is invalid JQuery syntax because it is missing a closing bracket.</value>\n  </data>\n</root>"
  },
  {
    "path": "src/System.Web.Mvc/QueryStringValueProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Web.Helpers;\n\nnamespace System.Web.Mvc\n{\n    public sealed class QueryStringValueProvider : NameValueCollectionValueProvider\n    {\n        // QueryString should use the invariant culture since it's part of the URL, and the URL should be\n        // interpreted in a uniform fashion regardless of the origin of a particular request.\n        public QueryStringValueProvider(ControllerContext controllerContext)\n            : this(controllerContext, new UnvalidatedRequestValuesWrapper(controllerContext.HttpContext.Request.Unvalidated))\n        {\n        }\n\n        // For unit testing\n        internal QueryStringValueProvider(ControllerContext controllerContext, IUnvalidatedRequestValues unvalidatedValues)\n            : base(controllerContext.HttpContext.Request.QueryString, unvalidatedValues.QueryString, CultureInfo.InvariantCulture)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/QueryStringValueProviderFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Helpers;\n\nnamespace System.Web.Mvc\n{\n    public sealed class QueryStringValueProviderFactory : ValueProviderFactory\n    {\n        private readonly UnvalidatedRequestValuesAccessor _unvalidatedValuesAccessor;\n\n        public QueryStringValueProviderFactory()\n            : this(null)\n        {\n        }\n\n        // For unit testing\n        internal QueryStringValueProviderFactory(UnvalidatedRequestValuesAccessor unvalidatedValuesAccessor)\n        {\n            _unvalidatedValuesAccessor = unvalidatedValuesAccessor ?? (cc => new UnvalidatedRequestValuesWrapper(cc.HttpContext.Request.Unvalidated));\n        }\n\n        public override IValueProvider GetValueProvider(ControllerContext controllerContext)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n\n            return new QueryStringValueProvider(controllerContext, _unvalidatedValuesAccessor(controllerContext));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/RangeAttributeAdapter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\n\nnamespace System.Web.Mvc\n{\n    public class RangeAttributeAdapter : DataAnnotationsModelValidator<RangeAttribute>\n    {\n        public RangeAttributeAdapter(ModelMetadata metadata, ControllerContext context, RangeAttribute attribute)\n            : base(metadata, context, attribute)\n        {\n        }\n\n        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()\n        {\n            string errorMessage = ErrorMessage; // Per Dev10 Bug #923283, need to make sure ErrorMessage is called before Minimum/Maximum\n            return new[] { new ModelClientValidationRangeRule(errorMessage, Attribute.Minimum, Attribute.Maximum) };\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Razor/MvcCSharpRazorCodeGenerator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.Web.Razor;\nusing System.Web.Razor.Generator;\n\nnamespace System.Web.Mvc.Razor\n{\n    internal class MvcCSharpRazorCodeGenerator : CSharpRazorCodeGenerator\n    {\n        private const string DefaultModelTypeName = \"dynamic\";\n\n        public MvcCSharpRazorCodeGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host)\n            : base(className, rootNamespaceName, sourceFileName, host)\n        {\n            var mvcHost = host as MvcWebPageRazorHost;\n            if (mvcHost != null && !mvcHost.IsSpecialPage)\n            {\n                // set the default model type to \"dynamic\" (Dev10 bug 935656)\n                // don't set it for \"special\" pages (such as \"_viewStart.cshtml\")\n                SetBaseType(DefaultModelTypeName);\n            }\n        }\n\n        private void SetBaseType(string modelTypeName)\n        {\n            var baseType = new CodeTypeReference(Context.Host.DefaultBaseClass + \"<\" + modelTypeName + \">\");\n            Context.GeneratedClass.BaseTypes.Clear();\n            Context.GeneratedClass.BaseTypes.Add(baseType);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Razor/MvcCSharpRazorCodeParser.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Web.Mvc.Properties;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Text;\n\nnamespace System.Web.Mvc.Razor\n{\n    public class MvcCSharpRazorCodeParser : CSharpCodeParser\n    {\n        private const string ModelKeyword = \"model\";\n        private const string GenericTypeFormatString = \"{0}<{1}>\";\n        private SourceLocation? _endInheritsLocation;\n        private bool _modelStatementFound;\n\n        public MvcCSharpRazorCodeParser()\n        {\n            MapDirectives(ModelDirective, ModelKeyword);\n        }\n\n        protected override void InheritsDirective()\n        {\n            // Verify we're on the right keyword and accept\n            AssertDirective(SyntaxConstants.CSharp.InheritsKeyword);\n            AcceptAndMoveNext();\n            _endInheritsLocation = CurrentLocation;\n\n            InheritsDirectiveCore();\n            CheckForInheritsAndModelStatements();\n        }\n\n        private void CheckForInheritsAndModelStatements()\n        {\n            if (_modelStatementFound && _endInheritsLocation.HasValue)\n            {\n                Context.OnError(_endInheritsLocation.Value, String.Format(CultureInfo.CurrentCulture, MvcResources.MvcRazorCodeParser_CannotHaveModelAndInheritsKeyword, ModelKeyword));\n            }\n        }\n\n        protected virtual void ModelDirective()\n        {\n            // Verify we're on the right keyword and accept\n            AssertDirective(ModelKeyword);\n            AcceptAndMoveNext();\n\n            SourceLocation endModelLocation = CurrentLocation;\n\n            BaseTypeDirective(\n                String.Format(CultureInfo.CurrentCulture,\n                              MvcResources.MvcRazorCodeParser_ModelKeywordMustBeFollowedByTypeName, ModelKeyword),\n                CreateModelCodeGenerator);\n\n            if (_modelStatementFound)\n            {\n                Context.OnError(endModelLocation, String.Format(CultureInfo.CurrentCulture, MvcResources.MvcRazorCodeParser_OnlyOneModelStatementIsAllowed, ModelKeyword));\n            }\n\n            _modelStatementFound = true;\n\n            CheckForInheritsAndModelStatements();\n        }\n\n        private SpanCodeGenerator CreateModelCodeGenerator(string model)\n        {\n            return new SetModelTypeCodeGenerator(model, GenericTypeFormatString);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Razor/MvcVBRazorCodeParser.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Linq;\nusing System.Web.Mvc.Properties;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Mvc.Razor\n{\n    public class MvcVBRazorCodeParser : VBCodeParser\n    {\n        internal const string ModelTypeKeyword = \"ModelType\";\n        private const string GenericTypeFormatString = \"{0}(Of {1})\";\n        private SourceLocation? _endInheritsLocation;\n        private bool _modelStatementFound;\n\n        public MvcVBRazorCodeParser()\n        {\n            MapDirective(ModelTypeKeyword, ModelTypeDirective);\n        }\n\n        protected override bool InheritsStatement()\n        {\n            // Verify we're on the right keyword and accept\n            Assert(VBKeyword.Inherits);\n            VBSymbol inherits = CurrentSymbol;\n            NextToken();\n            _endInheritsLocation = CurrentLocation;\n            PutCurrentBack();\n            PutBack(inherits);\n            EnsureCurrent();\n\n            bool result = base.InheritsStatement();\n            CheckForInheritsAndModelStatements();\n            return result;\n        }\n\n        private void CheckForInheritsAndModelStatements()\n        {\n            if (_modelStatementFound && _endInheritsLocation.HasValue)\n            {\n                Context.OnError(_endInheritsLocation.Value, String.Format(CultureInfo.CurrentCulture, MvcResources.MvcRazorCodeParser_CannotHaveModelAndInheritsKeyword, ModelTypeKeyword));\n            }\n        }\n\n        protected virtual bool ModelTypeDirective()\n        {\n            AssertDirective(ModelTypeKeyword);\n\n            Span.CodeGenerator = SpanCodeGenerator.Null;\n            Context.CurrentBlock.Type = BlockType.Directive;\n\n            AcceptAndMoveNext();\n            SourceLocation endModelLocation = CurrentLocation;\n\n            if (At(VBSymbolType.WhiteSpace))\n            {\n                Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n            }\n\n            AcceptWhile(VBSymbolType.WhiteSpace);\n            Output(SpanKind.MetaCode);\n\n            if (_modelStatementFound)\n            {\n                Context.OnError(endModelLocation, String.Format(CultureInfo.CurrentCulture, MvcResources.MvcRazorCodeParser_OnlyOneModelStatementIsAllowed, ModelTypeKeyword));\n            }\n            _modelStatementFound = true;\n\n            if (EndOfFile || At(VBSymbolType.WhiteSpace) || At(VBSymbolType.NewLine))\n            {\n                Context.OnError(endModelLocation, MvcResources.MvcRazorCodeParser_ModelKeywordMustBeFollowedByTypeName, ModelTypeKeyword);\n            }\n\n            // Just accept to a newline\n            AcceptUntil(VBSymbolType.NewLine);\n            if (!Context.DesignTimeMode)\n            {\n                // We want the newline to be treated as code, but it causes issues at design-time.\n                Optional(VBSymbolType.NewLine);\n            }\n\n            string baseType = String.Concat(Span.Symbols.Select(s => s.Content)).Trim();\n            Span.CodeGenerator = new SetModelTypeCodeGenerator(baseType, GenericTypeFormatString);\n\n            CheckForInheritsAndModelStatements();\n            Output(SpanKind.Code);\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Razor/MvcWebPageRazorHost.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.WebPages.Razor;\n\nnamespace System.Web.Mvc.Razor\n{\n    [SuppressMessage(\"Microsoft.Naming\", \"CA1702:CompoundWordsShouldBeCasedCorrectly\", MessageId = \"WebPage\", Justification = \"The class name is derived from the name of the base type\")]\n    public class MvcWebPageRazorHost : WebPageRazorHost\n    {\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2214:DoNotCallOverridableMethodsInConstructors\", Justification = \"The NamespaceImports property should not be virtual. This is a temporary fix.\")]\n        public MvcWebPageRazorHost(string virtualPath, string physicalPath)\n            : base(virtualPath, physicalPath)\n        {\n            RegisterSpecialFile(RazorViewEngine.ViewStartFileName, typeof(ViewStartPage));\n\n            DefaultPageBaseClass = typeof(WebViewPage).FullName;\n\n            // REVIEW get rid of the namespace import to not force additional references in default MVC projects\n            GetRidOfNamespace(\"System.Web.WebPages.Html\");\n        }\n\n        public override RazorCodeGenerator DecorateCodeGenerator(RazorCodeGenerator incomingCodeGenerator)\n        {\n            if (incomingCodeGenerator is CSharpRazorCodeGenerator)\n            {\n                return new MvcCSharpRazorCodeGenerator(incomingCodeGenerator.ClassName,\n                                                       incomingCodeGenerator.RootNamespaceName,\n                                                       incomingCodeGenerator.SourceFileName,\n                                                       incomingCodeGenerator.Host);\n            }\n            else\n            {\n                return base.DecorateCodeGenerator(incomingCodeGenerator);\n            }\n        }\n\n        public override ParserBase DecorateCodeParser(ParserBase incomingCodeParser)\n        {\n            if (incomingCodeParser is CSharpCodeParser)\n            {\n                return new MvcCSharpRazorCodeParser();\n            }\n            else if (incomingCodeParser is VBCodeParser)\n            {\n                return new MvcVBRazorCodeParser();\n            }\n            else\n            {\n                return base.DecorateCodeParser(incomingCodeParser);\n            }\n        }\n\n        private void GetRidOfNamespace(string ns)\n        {\n            Debug.Assert(NamespaceImports.Contains(ns), ns + \" is not a default namespace anymore\");\n            if (NamespaceImports.Contains(ns))\n            {\n                NamespaceImports.Remove(ns);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Razor/SetModelTypeCodeGenerator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Web.Mvc.ExpressionUtil;\nusing System.Web.Razor.Generator;\n\nnamespace System.Web.Mvc.Razor\n{\n    internal class SetModelTypeCodeGenerator : SetBaseTypeCodeGenerator\n    {\n        private string _genericTypeFormat;\n\n        public SetModelTypeCodeGenerator(string modelType, string genericTypeFormat)\n            : base(modelType)\n        {\n            _genericTypeFormat = genericTypeFormat;\n        }\n\n        protected override string ResolveType(CodeGeneratorContext context, string baseType)\n        {\n            return String.Format(\n                CultureInfo.InvariantCulture,\n                _genericTypeFormat,\n                context.Host.DefaultBaseClass,\n                baseType);\n        }\n\n        public override bool Equals(object obj)\n        {\n            SetModelTypeCodeGenerator other = obj as SetModelTypeCodeGenerator;\n            return other != null &&\n                   base.Equals(obj) &&\n                   String.Equals(_genericTypeFormat, other._genericTypeFormat, StringComparison.Ordinal);\n        }\n\n        public override int GetHashCode()\n        {\n            var combiner = new HashCodeCombiner();\n            combiner.AddInt32(base.GetHashCode());\n            combiner.AddObject(_genericTypeFormat);\n            return combiner.CombinedHash;\n        }\n\n        public override string ToString()\n        {\n            return \"Model:\" + BaseType;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Razor/StartPageLookupDelegate.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.WebPages;\n\nnamespace System.Web.Mvc.Razor\n{\n    internal delegate WebPageRenderingBase StartPageLookupDelegate(WebPageRenderingBase page, string fileName, IEnumerable<string> supportedExtensions);\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/RazorView.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Web.Mvc.Properties;\nusing System.Web.Mvc.Razor;\nusing System.Web.WebPages;\n\nnamespace System.Web.Mvc\n{\n    public class RazorView : BuildManagerCompiledView\n    {\n        public RazorView(ControllerContext controllerContext, string viewPath, string layoutPath, bool runViewStartPages, IEnumerable<string> viewStartFileExtensions)\n            : this(controllerContext, viewPath, layoutPath, runViewStartPages, viewStartFileExtensions, null)\n        {\n        }\n\n        public RazorView(ControllerContext controllerContext, string viewPath, string layoutPath, bool runViewStartPages, IEnumerable<string> viewStartFileExtensions, IViewPageActivator viewPageActivator)\n            : base(controllerContext, viewPath, viewPageActivator)\n        {\n            LayoutPath = layoutPath ?? String.Empty;\n            RunViewStartPages = runViewStartPages;\n            StartPageLookup = StartPage.GetStartPage;\n            ViewStartFileExtensions = viewStartFileExtensions ?? Enumerable.Empty<string>();\n        }\n\n        public string LayoutPath { get; private set; }\n\n        public bool RunViewStartPages { get; private set; }\n\n        internal StartPageLookupDelegate StartPageLookup { get; set; }\n\n        internal IVirtualPathFactory VirtualPathFactory { get; set; }\n\n        internal DisplayModeProvider DisplayModeProvider { get; set; }\n\n        public IEnumerable<string> ViewStartFileExtensions { get; private set; }\n\n        protected override void RenderView(ViewContext viewContext, TextWriter writer, object instance)\n        {\n            if (writer == null)\n            {\n                throw new ArgumentNullException(\"writer\");\n            }\n\n            WebViewPage webViewPage = instance as WebViewPage;\n            if (webViewPage == null)\n            {\n                throw new InvalidOperationException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.CshtmlView_WrongViewBase,\n                        ViewPath));\n            }\n\n            // An overriden master layout might have been specified when the ViewActionResult got returned.\n            // We need to hold on to it so that we can set it on the inner page once it has executed.\n            webViewPage.OverridenLayoutPath = LayoutPath;\n            webViewPage.VirtualPath = ViewPath;\n            webViewPage.ViewContext = viewContext;\n            webViewPage.ViewData = viewContext.ViewData;\n\n            webViewPage.InitHelpers();\n\n            if (VirtualPathFactory != null)\n            {\n                webViewPage.VirtualPathFactory = VirtualPathFactory;\n            }\n            if (DisplayModeProvider != null)\n            {\n                webViewPage.DisplayModeProvider = DisplayModeProvider;\n            }\n\n            WebPageRenderingBase startPage = null;\n            if (RunViewStartPages)\n            {\n                startPage = StartPageLookup(webViewPage, RazorViewEngine.ViewStartFileName, ViewStartFileExtensions);\n            }\n            webViewPage.ExecutePageHierarchy(new WebPageContext(context: viewContext.HttpContext, page: null, model: null), writer, startPage);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/RazorViewEngine.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public class RazorViewEngine : BuildManagerViewEngine\n    {\n        internal static readonly string ViewStartFileName = \"_ViewStart\";\n\n        public RazorViewEngine()\n            : this(null)\n        {\n        }\n\n        public RazorViewEngine(IViewPageActivator viewPageActivator)\n            : base(viewPageActivator)\n        {\n            AreaViewLocationFormats = new[]\n            {\n                \"~/Areas/{2}/Views/{1}/{0}.cshtml\",\n                \"~/Areas/{2}/Views/{1}/{0}.vbhtml\",\n                \"~/Areas/{2}/Views/Shared/{0}.cshtml\",\n                \"~/Areas/{2}/Views/Shared/{0}.vbhtml\"\n            };\n            AreaMasterLocationFormats = new[]\n            {\n                \"~/Areas/{2}/Views/{1}/{0}.cshtml\",\n                \"~/Areas/{2}/Views/{1}/{0}.vbhtml\",\n                \"~/Areas/{2}/Views/Shared/{0}.cshtml\",\n                \"~/Areas/{2}/Views/Shared/{0}.vbhtml\"\n            };\n            AreaPartialViewLocationFormats = new[]\n            {\n                \"~/Areas/{2}/Views/{1}/{0}.cshtml\",\n                \"~/Areas/{2}/Views/{1}/{0}.vbhtml\",\n                \"~/Areas/{2}/Views/Shared/{0}.cshtml\",\n                \"~/Areas/{2}/Views/Shared/{0}.vbhtml\"\n            };\n\n            ViewLocationFormats = new[]\n            {\n                \"~/Views/{1}/{0}.cshtml\",\n                \"~/Views/{1}/{0}.vbhtml\",\n                \"~/Views/Shared/{0}.cshtml\",\n                \"~/Views/Shared/{0}.vbhtml\"\n            };\n            MasterLocationFormats = new[]\n            {\n                \"~/Views/{1}/{0}.cshtml\",\n                \"~/Views/{1}/{0}.vbhtml\",\n                \"~/Views/Shared/{0}.cshtml\",\n                \"~/Views/Shared/{0}.vbhtml\"\n            };\n            PartialViewLocationFormats = new[]\n            {\n                \"~/Views/{1}/{0}.cshtml\",\n                \"~/Views/{1}/{0}.vbhtml\",\n                \"~/Views/Shared/{0}.cshtml\",\n                \"~/Views/Shared/{0}.vbhtml\"\n            };\n\n            FileExtensions = new[]\n            {\n                \"cshtml\",\n                \"vbhtml\",\n            };\n        }\n\n        protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)\n        {\n            return new RazorView(controllerContext, partialPath,\n                                 layoutPath: null, runViewStartPages: false, viewStartFileExtensions: FileExtensions, viewPageActivator: ViewPageActivator)\n            {\n                DisplayModeProvider = DisplayModeProvider\n            };\n        }\n\n        protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)\n        {\n            var view = new RazorView(controllerContext, viewPath,\n                                     layoutPath: masterPath, runViewStartPages: true, viewStartFileExtensions: FileExtensions, viewPageActivator: ViewPageActivator)\n            {\n                DisplayModeProvider = DisplayModeProvider\n            };\n            return view;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ReaderWriterCache.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Threading;\n\nnamespace System.Web.Mvc\n{\n    [SuppressMessage(\"Microsoft.Design\", \"CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable\", Justification = \"Instances of this type are meant to be singletons.\")]\n    internal abstract class ReaderWriterCache<TKey, TValue>\n    {\n        private readonly Dictionary<TKey, TValue> _cache;\n        private readonly ReaderWriterLockSlim _readerWriterLock = new ReaderWriterLockSlim();\n\n        protected ReaderWriterCache()\n            : this(null)\n        {\n        }\n\n        protected ReaderWriterCache(IEqualityComparer<TKey> comparer)\n        {\n            _cache = new Dictionary<TKey, TValue>(comparer);\n        }\n\n        protected Dictionary<TKey, TValue> Cache\n        {\n            get { return _cache; }\n        }\n\n        protected TValue FetchOrCreateItem(TKey key, Func<TValue> creator)\n        {\n            // Passing the delegate as an argument allows the inline delegate to be static\n            return FetchOrCreateItem(key, (Func<TValue> innerCreator) => innerCreator(), creator);\n        }\n\n        protected TValue FetchOrCreateItem<TArgument>(TKey key, Func<TArgument, TValue> creator, TArgument state)\n        {\n            // first, see if the item already exists in the cache\n            _readerWriterLock.EnterReadLock();\n            try\n            {\n                TValue existingEntry;\n                if (_cache.TryGetValue(key, out existingEntry))\n                {\n                    return existingEntry;\n                }\n            }\n            finally\n            {\n                _readerWriterLock.ExitReadLock();\n            }\n\n            // insert the new item into the cache\n            TValue newEntry = creator(state);\n            _readerWriterLock.EnterWriteLock();\n            try\n            {\n                TValue existingEntry;\n                if (_cache.TryGetValue(key, out existingEntry))\n                {\n                    // another thread already inserted an item, so use that one\n                    return existingEntry;\n                }\n\n                _cache[key] = newEntry;\n                return newEntry;\n            }\n            finally\n            {\n                _readerWriterLock.ExitWriteLock();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/RedirectResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    // represents a result that performs a redirection given some URI\n    public class RedirectResult : ActionResult\n    {\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"0#\", Justification = \"Response.Redirect() takes its URI as a string parameter.\")]\n        public RedirectResult(string url)\n            : this(url, permanent: false)\n        {\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"0#\", Justification = \"Response.Redirect() takes its URI as a string parameter.\")]\n        public RedirectResult(string url, bool permanent)\n        {\n            if (String.IsNullOrEmpty(url))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"url\");\n            }\n\n            Permanent = permanent;\n            Url = url;\n        }\n\n        public bool Permanent { get; private set; }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1056:UriPropertiesShouldNotBeStrings\", Justification = \"Response.Redirect() takes its URI as a string parameter.\")]\n        public string Url { get; private set; }\n\n        public override void ExecuteResult(ControllerContext context)\n        {\n            if (context == null)\n            {\n                throw new ArgumentNullException(\"context\");\n            }\n            if (context.IsChildAction)\n            {\n                throw new InvalidOperationException(MvcResources.RedirectAction_CannotRedirectInChildAction);\n            }\n\n            string destinationUrl = UrlHelper.GenerateContentUrl(Url, context.HttpContext);\n            context.Controller.TempData.Keep();\n\n            if (Permanent)\n            {\n                context.HttpContext.Response.RedirectPermanent(destinationUrl, endResponse: false);\n            }\n            else\n            {\n                context.HttpContext.Response.Redirect(destinationUrl, endResponse: false);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/RedirectToRouteResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc.Properties;\nusing System.Web.Routing;\n\nnamespace System.Web.Mvc\n{\n    // represents a result that performs a redirection given some values dictionary\n    public class RedirectToRouteResult : ActionResult\n    {\n        private RouteCollection _routes;\n\n        public RedirectToRouteResult(RouteValueDictionary routeValues)\n            :\n                this(null, routeValues)\n        {\n        }\n\n        public RedirectToRouteResult(string routeName, RouteValueDictionary routeValues)\n            : this(routeName, routeValues, permanent: false)\n        {\n        }\n\n        public RedirectToRouteResult(string routeName, RouteValueDictionary routeValues, bool permanent)\n        {\n            Permanent = permanent;\n            RouteName = routeName ?? String.Empty;\n            RouteValues = routeValues ?? new RouteValueDictionary();\n        }\n\n        public bool Permanent { get; private set; }\n\n        public string RouteName { get; private set; }\n\n        public RouteValueDictionary RouteValues { get; private set; }\n\n        internal RouteCollection Routes\n        {\n            get\n            {\n                if (_routes == null)\n                {\n                    _routes = RouteTable.Routes;\n                }\n                return _routes;\n            }\n            set { _routes = value; }\n        }\n\n        public override void ExecuteResult(ControllerContext context)\n        {\n            if (context == null)\n            {\n                throw new ArgumentNullException(\"context\");\n            }\n            if (context.IsChildAction)\n            {\n                throw new InvalidOperationException(MvcResources.RedirectAction_CannotRedirectInChildAction);\n            }\n\n            string destinationUrl = UrlHelper.GenerateUrl(RouteName, null /* actionName */, null /* controllerName */, RouteValues, Routes, context.RequestContext, false /* includeImplicitMvcValues */);\n            if (String.IsNullOrEmpty(destinationUrl))\n            {\n                throw new InvalidOperationException(MvcResources.Common_NoRouteMatched);\n            }\n\n            context.Controller.TempData.Keep();\n\n            if (Permanent)\n            {\n                context.HttpContext.Response.RedirectPermanent(destinationUrl, endResponse: false);\n            }\n            else\n            {\n                context.HttpContext.Response.Redirect(destinationUrl, endResponse: false);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ReflectedActionDescriptor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Text;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    public class ReflectedActionDescriptor : ActionDescriptor, IMethodInfoActionDescriptor\n    {\n        private readonly string _actionName;\n        private readonly ControllerDescriptor _controllerDescriptor;\n        private string _uniqueId;\n        private ParameterDescriptor[] _parametersCache;\n\n        public ReflectedActionDescriptor(MethodInfo methodInfo, string actionName, ControllerDescriptor controllerDescriptor)\n            : this(methodInfo, actionName, controllerDescriptor, true /* validateMethod */)\n        {\n        }\n\n        internal ReflectedActionDescriptor(MethodInfo methodInfo, string actionName, ControllerDescriptor controllerDescriptor, bool validateMethod)\n        {\n            if (methodInfo == null)\n            {\n                throw new ArgumentNullException(\"methodInfo\");\n            }\n            if (String.IsNullOrEmpty(actionName))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"actionName\");\n            }\n            if (controllerDescriptor == null)\n            {\n                throw new ArgumentNullException(\"controllerDescriptor\");\n            }\n\n            if (validateMethod)\n            {\n                string failedMessage = VerifyActionMethodIsCallable(methodInfo);\n                if (failedMessage != null)\n                {\n                    throw new ArgumentException(failedMessage, \"methodInfo\");\n                }\n            }\n\n            MethodInfo = methodInfo;\n            _actionName = actionName;\n            _controllerDescriptor = controllerDescriptor;\n        }\n\n        public override string ActionName\n        {\n            get { return _actionName; }\n        }\n\n        public override ControllerDescriptor ControllerDescriptor\n        {\n            get { return _controllerDescriptor; }\n        }\n\n        public MethodInfo MethodInfo { get; private set; }\n\n        public override string UniqueId\n        {\n            get \n            {\n                if (_uniqueId == null)\n                {\n                    _uniqueId = CreateUniqueId();\n                }\n                return _uniqueId; \n            }\n        }\n\n        private string CreateUniqueId()\n        {\n            var builder = new StringBuilder(base.UniqueId);\n            DescriptorUtil.AppendUniqueId(builder, MethodInfo);\n            return builder.ToString();\n        }\n\n        public override object Execute(ControllerContext controllerContext, IDictionary<string, object> parameters)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n            if (parameters == null)\n            {\n                throw new ArgumentNullException(\"parameters\");\n            }\n\n            // Performance sensitive so avoid Linq or delegates.\n            ParameterInfo[] parameterInfos = MethodInfo.GetParameters();\n            object[] parametersArray = new object[parameterInfos.Length];\n            for (int i = 0; i < parameterInfos.Length; i++)\n            {\n                ParameterInfo parameterInfo = parameterInfos[i];\n                object parameter = ExtractParameterFromDictionary(parameterInfo, parameters, MethodInfo);\n                parametersArray[i] = parameter;\n            }\n\n            ActionMethodDispatcher dispatcher = DispatcherCache.GetDispatcher(MethodInfo);\n            object actionReturnValue = dispatcher.Execute(controllerContext.Controller, parametersArray);\n            return actionReturnValue;\n        }\n\n        public override object[] GetCustomAttributes(bool inherit)\n        {\n            return ActionDescriptorHelper.GetCustomAttributes(MethodInfo, inherit);\n        }\n\n        public override object[] GetCustomAttributes(Type attributeType, bool inherit)\n        {\n            return ActionDescriptorHelper.GetCustomAttributes(MethodInfo, attributeType, inherit);\n        }\n\n        public override IEnumerable<FilterAttribute> GetFilterAttributes(bool useCache)\n        {\n            if (useCache && GetType() == typeof(ReflectedActionDescriptor))\n            {\n                // Do not look at cache in types derived from this type because they might incorrectly implement GetCustomAttributes\n                return ReflectedAttributeCache.GetMethodFilterAttributes(MethodInfo);\n            }\n            return base.GetFilterAttributes(useCache);\n        }\n\n        public override ParameterDescriptor[] GetParameters()\n        {\n            return ActionDescriptorHelper.GetParameters(this, MethodInfo, ref _parametersCache);\n        }\n\n        public override ICollection<ActionSelector> GetSelectors()\n        {\n            return ActionDescriptorHelper.GetSelectors(MethodInfo);\n        }\n\n        internal override ICollection<ActionNameSelector> GetNameSelectors()\n        {\n            return ActionDescriptorHelper.GetNameSelectors(MethodInfo);\n        }\n\n        public override bool IsDefined(Type attributeType, bool inherit)\n        {\n            return ActionDescriptorHelper.IsDefined(MethodInfo, attributeType, inherit);\n        }\n\n        internal static ReflectedActionDescriptor TryCreateDescriptor(MethodInfo methodInfo, string name, ControllerDescriptor controllerDescriptor)\n        {\n            ReflectedActionDescriptor descriptor = new ReflectedActionDescriptor(methodInfo, name, controllerDescriptor, false /* validateMethod */);\n            string failedMessage = VerifyActionMethodIsCallable(methodInfo);\n            return (failedMessage == null) ? descriptor : null;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ReflectedAttributeCache.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Diagnostics;\nusing System.Reflection;\n\nnamespace System.Web.Mvc\n{\n    internal static class ReflectedAttributeCache\n    {\n        private static readonly ConcurrentDictionary<MethodInfo, ReadOnlyCollection<ActionMethodSelectorAttribute>> _actionMethodSelectorAttributeCache = new ConcurrentDictionary<MethodInfo, ReadOnlyCollection<ActionMethodSelectorAttribute>>();\n        private static readonly ConcurrentDictionary<MethodInfo, ReadOnlyCollection<ActionNameSelectorAttribute>> _actionNameSelectorAttributeCache = new ConcurrentDictionary<MethodInfo, ReadOnlyCollection<ActionNameSelectorAttribute>>();\n        private static readonly ConcurrentDictionary<MethodInfo, ReadOnlyCollection<FilterAttribute>> _methodFilterAttributeCache = new ConcurrentDictionary<MethodInfo, ReadOnlyCollection<FilterAttribute>>();\n\n        private static readonly ConcurrentDictionary<Type, ReadOnlyCollection<FilterAttribute>> _typeFilterAttributeCache = new ConcurrentDictionary<Type, ReadOnlyCollection<FilterAttribute>>();\n\n        public static ReadOnlyCollection<FilterAttribute> GetTypeFilterAttributes(Type type)\n        {\n            return GetAttributes(_typeFilterAttributeCache, type);\n        }\n\n        public static ReadOnlyCollection<FilterAttribute> GetMethodFilterAttributes(MethodInfo methodInfo)\n        {\n            return GetAttributes(_methodFilterAttributeCache, methodInfo);\n        }\n\n        public static ReadOnlyCollection<ActionMethodSelectorAttribute> GetActionMethodSelectorAttributesCollection(MethodInfo methodInfo)\n        {\n            return GetAttributes(_actionMethodSelectorAttributeCache, methodInfo);\n        }\n\n        public static ReadOnlyCollection<ActionNameSelectorAttribute> GetActionNameSelectorAttributes(MethodInfo methodInfo)\n        {\n            return GetAttributes(_actionNameSelectorAttributeCache, methodInfo);\n        }\n\n        private static ReadOnlyCollection<TAttribute> GetAttributes<TMemberInfo, TAttribute>(ConcurrentDictionary<TMemberInfo, ReadOnlyCollection<TAttribute>> lookup, TMemberInfo memberInfo)\n            where TAttribute : Attribute\n            where TMemberInfo : MemberInfo\n        {\n            Debug.Assert(memberInfo != null);\n            Debug.Assert(lookup != null);\n            // Frequently called, so use a static delegate\n            // An inline delegate cannot be used because the C# compiler does not cache inline delegates that reference generic method arguments\n            return lookup.GetOrAdd(\n                memberInfo,\n                CachedDelegates<TMemberInfo, TAttribute>.GetCustomAttributes);\n        }\n\n        private static class CachedDelegates<TMemberInfo, TAttribute>\n            where TAttribute : Attribute\n            where TMemberInfo : MemberInfo\n        {\n            internal static Func<TMemberInfo, ReadOnlyCollection<TAttribute>> GetCustomAttributes = (TMemberInfo memberInfo) =>\n            {\n                return new ReadOnlyCollection<TAttribute>((TAttribute[])memberInfo.GetCustomAttributes(typeof(TAttribute), inherit: true));\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ReflectedControllerDescriptor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    public class ReflectedControllerDescriptor : ControllerDescriptor\n    {\n        private readonly Type _controllerType;\n        private readonly ActionMethodSelector _selector;\n        private ActionDescriptor[] _canonicalActionsCache;\n\n        public ReflectedControllerDescriptor(Type controllerType)\n        {\n            if (controllerType == null)\n            {\n                throw new ArgumentNullException(\"controllerType\");\n            }\n\n            _controllerType = controllerType;\n            _selector = new ActionMethodSelector(_controllerType);\n        }\n\n        public sealed override Type ControllerType\n        {\n            get { return _controllerType; }\n        }\n\n        public override ActionDescriptor FindAction(ControllerContext controllerContext, string actionName)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n            if (String.IsNullOrEmpty(actionName))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"actionName\");\n            }\n\n            MethodInfo matched = _selector.FindActionMethod(controllerContext, actionName);\n            if (matched == null)\n            {\n                return null;\n            }\n\n            return new ReflectedActionDescriptor(matched, actionName, this);\n        }\n\n        private MethodInfo[] GetAllActionMethodsFromSelector()\n        {\n            return _selector.StandardRouteMethods.ToArray();\n        }\n\n        public override ActionDescriptor[] GetCanonicalActions()\n        {\n            ActionDescriptor[] actions = LazilyFetchCanonicalActionsCollection();\n\n            // need to clone array so that user modifications aren't accidentally stored\n            return (ActionDescriptor[])actions.Clone();\n        }\n\n        public override object[] GetCustomAttributes(bool inherit)\n        {\n            return ControllerType.GetCustomAttributes(inherit);\n        }\n\n        public override object[] GetCustomAttributes(Type attributeType, bool inherit)\n        {\n            return ControllerType.GetCustomAttributes(attributeType, inherit);\n        }\n\n        public override IEnumerable<FilterAttribute> GetFilterAttributes(bool useCache)\n        {\n            if (useCache && GetType() == typeof(ReflectedControllerDescriptor))\n            {\n                // Do not look at cache in types derived from this type because they might incorrectly implement GetCustomAttributes\n                return ReflectedAttributeCache.GetTypeFilterAttributes(ControllerType);\n            }\n            return base.GetFilterAttributes(useCache);\n        }\n\n        public override bool IsDefined(Type attributeType, bool inherit)\n        {\n            return ControllerType.IsDefined(attributeType, inherit);\n        }\n\n        private ActionDescriptor[] LazilyFetchCanonicalActionsCollection()\n        {\n            return DescriptorUtil.LazilyFetchOrCreateDescriptors(\n                cacheLocation: ref _canonicalActionsCache,\n                initializer: (ReflectedControllerDescriptor state) => state.GetAllActionMethodsFromSelector(),\n                converter: (MethodInfo methodInfo, ReflectedControllerDescriptor state) => ReflectedActionDescriptor.TryCreateDescriptor(methodInfo, methodInfo.Name, state),\n                state: this);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ReflectedParameterBindingInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Globalization;\nusing System.Reflection;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    internal class ReflectedParameterBindingInfo : ParameterBindingInfo\n    {\n        private readonly ParameterInfo _parameterInfo;\n        private ICollection<string> _exclude = new string[0];\n        private ICollection<string> _include = new string[0];\n        private string _prefix;\n\n        public ReflectedParameterBindingInfo(ParameterInfo parameterInfo)\n        {\n            _parameterInfo = parameterInfo;\n            ReadSettingsFromBindAttribute();\n        }\n\n        public override IModelBinder Binder\n        {\n            get\n            {\n                IModelBinder binder = ModelBinders.GetBinderFromAttributes(\n                    _parameterInfo,\n                    (ICustomAttributeProvider errorArg) =>\n                    {\n                        ParameterInfo parameterInfo = (ParameterInfo)errorArg;\n                        throw new InvalidOperationException(\n                            String.Format(\n                                CultureInfo.CurrentCulture,\n                                MvcResources.ReflectedParameterBindingInfo_MultipleConverterAttributes,\n                                parameterInfo.Name,\n                                parameterInfo.Member));\n                    });\n\n                return binder;\n            }\n        }\n\n        public override ICollection<string> Exclude\n        {\n            get { return _exclude; }\n        }\n\n        public override ICollection<string> Include\n        {\n            get { return _include; }\n        }\n\n        public override string Prefix\n        {\n            get { return _prefix; }\n        }\n\n        private void ReadSettingsFromBindAttribute()\n        {\n            BindAttribute attr = (BindAttribute)Attribute.GetCustomAttribute(_parameterInfo, typeof(BindAttribute));\n            if (attr == null)\n            {\n                return;\n            }\n\n            _exclude = new ReadOnlyCollection<string>(AuthorizeAttribute.SplitString(attr.Exclude));\n            _include = new ReadOnlyCollection<string>(AuthorizeAttribute.SplitString(attr.Include));\n            _prefix = attr.Prefix;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ReflectedParameterDescriptor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\n\nnamespace System.Web.Mvc\n{\n    public class ReflectedParameterDescriptor : ParameterDescriptor\n    {\n        private readonly ActionDescriptor _actionDescriptor;\n        private readonly ReflectedParameterBindingInfo _bindingInfo;\n\n        public ReflectedParameterDescriptor(ParameterInfo parameterInfo, ActionDescriptor actionDescriptor)\n        {\n            if (parameterInfo == null)\n            {\n                throw new ArgumentNullException(\"parameterInfo\");\n            }\n            if (actionDescriptor == null)\n            {\n                throw new ArgumentNullException(\"actionDescriptor\");\n            }\n\n            ParameterInfo = parameterInfo;\n            _actionDescriptor = actionDescriptor;\n            _bindingInfo = new ReflectedParameterBindingInfo(parameterInfo);\n        }\n\n        public override ActionDescriptor ActionDescriptor\n        {\n            get { return _actionDescriptor; }\n        }\n\n        public override ParameterBindingInfo BindingInfo\n        {\n            get { return _bindingInfo; }\n        }\n\n        public override object DefaultValue\n        {\n            get\n            {\n                object value;\n                if (ParameterInfoUtil.TryGetDefaultValue(ParameterInfo, out value))\n                {\n                    return value;\n                }\n                else\n                {\n                    return base.DefaultValue;\n                }\n            }\n        }\n\n        public ParameterInfo ParameterInfo { get; private set; }\n\n        public override string ParameterName\n        {\n            get { return ParameterInfo.Name; }\n        }\n\n        public override Type ParameterType\n        {\n            get { return ParameterInfo.ParameterType; }\n        }\n\n        public override object[] GetCustomAttributes(bool inherit)\n        {\n            return ParameterInfo.GetCustomAttributes(inherit);\n        }\n\n        public override object[] GetCustomAttributes(Type attributeType, bool inherit)\n        {\n            return ParameterInfo.GetCustomAttributes(attributeType, inherit);\n        }\n\n        public override bool IsDefined(Type attributeType, bool inherit)\n        {\n            return ParameterInfo.IsDefined(attributeType, inherit);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/RegularExpressionAttributeAdapter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\n\nnamespace System.Web.Mvc\n{\n    public class RegularExpressionAttributeAdapter : DataAnnotationsModelValidator<RegularExpressionAttribute>\n    {\n        public RegularExpressionAttributeAdapter(ModelMetadata metadata, ControllerContext context, RegularExpressionAttribute attribute)\n            : base(metadata, context, attribute)\n        {\n        }\n\n        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()\n        {\n            return new[] { new ModelClientValidationRegexRule(ErrorMessage, Attribute.Pattern) };\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/RemoteAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Web.Mvc.Properties;\nusing System.Web.Routing;\n\nnamespace System.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Property)]\n    [SuppressMessage(\"Microsoft.Design\", \"CA1019:DefineAccessorsForAttributeArguments\", Justification = \"The constructor parameters are used to feed RouteData, which is public.\")]\n    [SuppressMessage(\"Microsoft.Performance\", \"CA1813:AvoidUnsealedAttributes\", Justification = \"This attribute is designed to be a base class for other attributes.\")]\n    public class RemoteAttribute : ValidationAttribute, IClientValidatable\n    {\n        private string _additionalFields;\n        private string[] _additonalFieldsSplit = new string[0];\n\n        protected RemoteAttribute()\n            : base(MvcResources.RemoteAttribute_RemoteValidationFailed)\n        {\n            RouteData = new RouteValueDictionary();\n        }\n\n        public RemoteAttribute(string routeName)\n            : this()\n        {\n            if (String.IsNullOrWhiteSpace(routeName))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"routeName\");\n            }\n\n            RouteName = routeName;\n        }\n\n        public RemoteAttribute(string action, string controller)\n            :\n                this(action, controller, null /* areaName */)\n        {\n        }\n\n        public RemoteAttribute(string action, string controller, string areaName)\n            : this()\n        {\n            if (String.IsNullOrWhiteSpace(action))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"action\");\n            }\n            if (String.IsNullOrWhiteSpace(controller))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"controller\");\n            }\n\n            RouteData[\"controller\"] = controller;\n            RouteData[\"action\"] = action;\n\n            if (!String.IsNullOrWhiteSpace(areaName))\n            {\n                RouteData[\"area\"] = areaName;\n            }\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"RemoteAttribute\"/> class.\n        /// </summary>\n        /// <param name=\"action\">The route name.</param>\n        /// <param name=\"controller\">The name of the controller.</param>\n        /// <param name=\"areaReference\">\n        /// Find the controller in the root if <see cref=\"AreaReference.UseRoot\"/>. Otherwise look in the current area.\n        /// </param>\n        public RemoteAttribute(string action, string controller, AreaReference areaReference)\n            : this(action, controller)\n        {\n            if (areaReference == AreaReference.UseRoot)\n            {\n                RouteData[\"area\"] = null;\n            }\n        }\n\n        public string HttpMethod { get; set; }\n\n        public string AdditionalFields\n        {\n            get { return _additionalFields ?? String.Empty; }\n            set\n            {\n                _additionalFields = value;\n                _additonalFieldsSplit = AuthorizeAttribute.SplitString(value);\n            }\n        }\n\n        protected RouteValueDictionary RouteData { get; private set; }\n\n        protected string RouteName { get; set; }\n\n        protected virtual RouteCollection Routes\n        {\n            get { return RouteTable.Routes; }\n        }\n\n        public string FormatAdditionalFieldsForClientValidation(string property)\n        {\n            if (String.IsNullOrEmpty(property))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"property\");\n            }\n\n            string delimitedAdditionalFields = FormatPropertyForClientValidation(property);\n\n            foreach (string field in _additonalFieldsSplit)\n            {\n                delimitedAdditionalFields += \",\" + FormatPropertyForClientValidation(field);\n            }\n\n            return delimitedAdditionalFields;\n        }\n\n        public static string FormatPropertyForClientValidation(string property)\n        {\n            if (String.IsNullOrEmpty(property))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"property\");\n            }\n            return \"*.\" + property;\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1055:UriReturnValuesShouldNotBeStrings\", Justification = \"The value is a not a regular URL since it may contain ~/ ASP.NET-specific characters\")]\n        protected virtual string GetUrl(ControllerContext controllerContext)\n        {\n            var pathData = Routes.GetVirtualPathForArea(controllerContext.RequestContext,\n                                                        RouteName,\n                                                        RouteData);\n\n            if (pathData == null)\n            {\n                throw new InvalidOperationException(MvcResources.RemoteAttribute_NoUrlFound);\n            }\n\n            return pathData.VirtualPath;\n        }\n\n        public override string FormatErrorMessage(string name)\n        {\n            return String.Format(CultureInfo.CurrentCulture, ErrorMessageString, name);\n        }\n\n        public override bool IsValid(object value)\n        {\n            return true;\n        }\n\n        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)\n        {\n            yield return new ModelClientValidationRemoteRule(FormatErrorMessage(metadata.GetDisplayName()), GetUrl(context), HttpMethod, FormatAdditionalFieldsForClientValidation(metadata.PropertyName));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/RequireHttpsAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    [SuppressMessage(\"Microsoft.Performance\", \"CA1813:AvoidUnsealedAttributes\", Justification = \"Unsealed because type contains virtual extensibility points.\")]\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\n    public class RequireHttpsAttribute : FilterAttribute, IAuthorizationFilter\n    {\n        public RequireHttpsAttribute()\n            : this(permanent: false)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"RequireHttpsAttribute\"/> class.\n        /// </summary>\n        /// <param name=\"permanent\">Whether the redirect to HTTPS should be a permanent redirect.</param>\n        public RequireHttpsAttribute(bool permanent)\n        {\n            this.Permanent = permanent;\n        }\n\n        /// <summary>\n        /// Gets a value indicating whether the redirect to HTTPS should be a permanent redirect.\n        /// </summary>\n        public bool Permanent { get; private set; }\n\n        public virtual void OnAuthorization(AuthorizationContext filterContext)\n        {\n            if (filterContext == null)\n            {\n                throw new ArgumentNullException(\"filterContext\");\n            }\n\n            if (!filterContext.HttpContext.Request.IsSecureConnection)\n            {\n                HandleNonHttpsRequest(filterContext);\n            }\n        }\n\n        protected virtual void HandleNonHttpsRequest(AuthorizationContext filterContext)\n        {\n            // only redirect for GET requests, otherwise the browser might not propagate the verb and request\n            // body correctly.\n\n            if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, \"GET\", StringComparison.OrdinalIgnoreCase))\n            {\n                throw new InvalidOperationException(MvcResources.RequireHttpsAttribute_MustUseSsl);\n            }\n\n            // redirect to HTTPS version of page\n            string url = \"https://\" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;\n            filterContext.Result = new RedirectResult(url, this.Permanent);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/RequiredAttributeAdapter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\n\nnamespace System.Web.Mvc\n{\n    public class RequiredAttributeAdapter : DataAnnotationsModelValidator<RequiredAttribute>\n    {\n        public RequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)\n            : base(metadata, context, attribute)\n        {\n        }\n\n        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()\n        {\n            return new[] { new ModelClientValidationRequiredRule(ErrorMessage) };\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ResultExecutedContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.Mvc\n{\n    public class ResultExecutedContext : ControllerContext\n    {\n        // parameterless constructor used for mocking\n        public ResultExecutedContext()\n        {\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2214:DoNotCallOverridableMethodsInConstructors\", Justification = \"The virtual property setters are only to support mocking frameworks, in which case this constructor shouldn't be called anyway.\")]\n        public ResultExecutedContext(ControllerContext controllerContext, ActionResult result, bool canceled, Exception exception)\n            : base(controllerContext)\n        {\n            if (result == null)\n            {\n                throw new ArgumentNullException(\"result\");\n            }\n\n            Result = result;\n            Canceled = canceled;\n            Exception = exception;\n        }\n\n        public virtual bool Canceled { get; set; }\n\n        public virtual Exception Exception { get; set; }\n\n        public bool ExceptionHandled { get; set; }\n\n        public virtual ActionResult Result { get; set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ResultExecutingContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.Mvc\n{\n    public class ResultExecutingContext : ControllerContext\n    {\n        // parameterless constructor used for mocking\n        public ResultExecutingContext()\n        {\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2214:DoNotCallOverridableMethodsInConstructors\", Justification = \"The virtual property setters are only to support mocking frameworks, in which case this constructor shouldn't be called anyway.\")]\n        public ResultExecutingContext(ControllerContext controllerContext, ActionResult result)\n            : base(controllerContext)\n        {\n            if (result == null)\n            {\n                throw new ArgumentNullException(\"result\");\n            }\n\n            Result = result;\n        }\n\n        public bool Cancel { get; set; }\n\n        public virtual ActionResult Result { get; set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/RouteAreaAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc.Routing;\n\nnamespace System.Web.Mvc\n{\n    /// <summary>\n    /// Defines the area to set for all the routes defined in this controller.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]\n    public sealed class RouteAreaAttribute : Attribute\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"RouteAreaAttribute\" /> class.\n        /// </summary>\n        /// <remarks>An attempt will be made to infer the area name from the target controller's namespace.</remarks>\n        public RouteAreaAttribute()\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"RouteAreaAttribute\" /> class.\n        /// </summary>\n        /// <param name=\"areaName\">The name of the area. \n        /// If the value is null, an attempt will be made to infer the area name from the target controller's namespace.\n        /// </param>\n        public RouteAreaAttribute(string areaName)\n        {\n            AreaName = areaName;\n        }\n\n        /// <summary>\n        /// The area name to set for all the routes defined in the controller.\n        /// If the value is null, an attempt will be made to infer the area name from the target controller's namespace.\n        /// </summary>\n        public string AreaName { get; private set; }\n\n        /// <summary>\n        /// The URL prefix to apply to the routes of this area. Defaults to the area's name.\n        /// </summary>\n        public string AreaPrefix { get; set; }\n    }\n}"
  },
  {
    "path": "src/System.Web.Mvc/RouteAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Web.Mvc.Routing;\n\nnamespace System.Web.Mvc\n{\n    /// <summary>\n    /// Place on a controller or action to expose it directly via a route. \n    /// When placed on a controller, it applies to actions that do not have any <see cref=\"RouteAttribute\"/>s on them.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = false, AllowMultiple = true)]\n    public sealed class RouteAttribute : Attribute, IDirectRouteFactory, IRouteInfoProvider\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"RouteAttribute\" /> class.\n        /// </summary>\n        public RouteAttribute() : this(String.Empty)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"RouteAttribute\" /> class.\n        /// </summary>\n        /// <param name=\"template\">The route template describing the URI pattern to match against.</param>\n        public RouteAttribute(string template)\n        {\n            if (template == null)\n            {\n                throw Error.ArgumentNull(\"template\");\n            }\n            Template = template;\n        }\n\n        /// <inheritdoc />\n        public string Name { get; set; }\n\n        /// <inheritdoc />\n        public int Order { get; set; }\n        \n        /// <inheritdoc />\n        public string Template { get; private set; }\n\n        RouteEntry IDirectRouteFactory.CreateRoute(DirectRouteFactoryContext context)\n        {\n            Contract.Assert(context != null);\n\n            IDirectRouteBuilder builder = context.CreateBuilder(Template);\n            Contract.Assert(builder != null);\n\n            builder.Name = Name;\n            builder.Order = Order;\n            return builder.Build();\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Mvc/RouteCollectionExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Web.Mvc.Properties;\nusing System.Web.Mvc.Routing;\nusing System.Web.Routing;\nusing System.Web.WebPages;\n\nnamespace System.Web.Mvc\n{\n    public static class RouteCollectionExtensions\n    {\n        // This method returns a new RouteCollection containing only routes that matched a particular area.\n        // The Boolean out parameter is just a flag specifying whether any registered routes were area-aware.\n        private static RouteCollection FilterRouteCollectionByArea(RouteCollection routes, string areaName, out bool usingAreas)\n        {\n            if (areaName == null)\n            {\n                areaName = String.Empty;\n            }\n\n            usingAreas = false;\n\n            // Ensure that we continue using the same settings as the previous route collection\n            // if we are using areas and the route collection is exchanged\n            RouteCollection filteredRoutes = new RouteCollection()\n            {\n                AppendTrailingSlash = routes.AppendTrailingSlash,\n                LowercaseUrls = routes.LowercaseUrls,\n                RouteExistingFiles = routes.RouteExistingFiles\n            };\n\n            using (routes.GetReadLock())\n            {\n                foreach (RouteBase route in routes)\n                {\n                    string thisAreaName = AreaHelpers.GetAreaName(route) ?? String.Empty;\n                    usingAreas |= (thisAreaName.Length > 0);\n                    if (String.Equals(thisAreaName, areaName, StringComparison.OrdinalIgnoreCase))\n                    {\n                        filteredRoutes.Add(route);\n                    }\n                }\n            }\n\n            // if areas are not in use, the filtered route collection might be incorrect\n            return (usingAreas) ? filteredRoutes : routes;\n        }\n\n        public static VirtualPathData GetVirtualPathForArea(this RouteCollection routes, RequestContext requestContext, RouteValueDictionary values)\n        {\n            return GetVirtualPathForArea(routes, requestContext, null /* name */, values);\n        }\n\n        public static VirtualPathData GetVirtualPathForArea(this RouteCollection routes, RequestContext requestContext, string name, RouteValueDictionary values)\n        {\n            bool usingAreas; // don't care about this value\n            return GetVirtualPathForArea(routes, requestContext, name, values, out usingAreas);\n        }\n\n        internal static VirtualPathData GetVirtualPathForArea(this RouteCollection routes, RequestContext requestContext, string name, RouteValueDictionary values, out bool usingAreas)\n        {\n            if (routes == null)\n            {\n                throw new ArgumentNullException(\"routes\");\n            }\n\n            if (!String.IsNullOrEmpty(name))\n            {\n                // the route name is a stronger qualifier than the area name, so just pipe it through\n                usingAreas = false;\n                return routes.GetVirtualPath(requestContext, name, values);\n            }\n\n            string targetArea = null;\n            if (values != null)\n            {\n                object targetAreaRawValue;\n                if (values.TryGetValue(\"area\", out targetAreaRawValue))\n                {\n                    targetArea = targetAreaRawValue as string;\n                }\n                else\n                {\n                    // set target area to current area\n                    if (requestContext != null)\n                    {\n                        targetArea = AreaHelpers.GetAreaName(requestContext.RouteData);\n                    }\n                }\n            }\n\n            // need to apply a correction to the RVD if areas are in use\n            RouteValueDictionary correctedValues = values;\n            RouteCollection filteredRoutes = FilterRouteCollectionByArea(routes, targetArea, out usingAreas);\n            if (usingAreas)\n            {\n                correctedValues = new RouteValueDictionary(values);\n                correctedValues.Remove(\"area\");\n            }\n\n            VirtualPathData vpd = filteredRoutes.GetVirtualPath(requestContext, correctedValues);\n            return vpd;\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"This is not a regular URL as it may contain special routing characters.\")]\n        public static void IgnoreRoute(this RouteCollection routes, string url)\n        {\n            IgnoreRoute(routes, url, null /* constraints */);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"This is not a regular URL as it may contain special routing characters.\")]\n        public static void IgnoreRoute(this RouteCollection routes, string url, object constraints)\n        {\n            if (routes == null)\n            {\n                throw new ArgumentNullException(\"routes\");\n            }\n            if (url == null)\n            {\n                throw new ArgumentNullException(\"url\");\n            }\n\n            IgnoreRouteInternal route = new IgnoreRouteInternal(url)\n            {\n                Constraints = CreateRouteValueDictionaryUncached(constraints)\n            };\n\n            ConstraintValidation.Validate(route);\n\n            routes.Add(route);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"2#\", Justification = \"This is not a regular URL as it may contain special routing characters.\")]\n        public static Route MapRoute(this RouteCollection routes, string name, string url)\n        {\n            return MapRoute(routes, name, url, null /* defaults */, (object)null /* constraints */);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"2#\", Justification = \"This is not a regular URL as it may contain special routing characters.\")]\n        public static Route MapRoute(this RouteCollection routes, string name, string url, object defaults)\n        {\n            return MapRoute(routes, name, url, defaults, (object)null /* constraints */);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"2#\", Justification = \"This is not a regular URL as it may contain special routing characters.\")]\n        public static Route MapRoute(this RouteCollection routes, string name, string url, object defaults, object constraints)\n        {\n            return MapRoute(routes, name, url, defaults, constraints, null /* namespaces */);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"2#\", Justification = \"This is not a regular URL as it may contain special routing characters.\")]\n        public static Route MapRoute(this RouteCollection routes, string name, string url, string[] namespaces)\n        {\n            return MapRoute(routes, name, url, null /* defaults */, null /* constraints */, namespaces);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"2#\", Justification = \"This is not a regular URL as it may contain special routing characters.\")]\n        public static Route MapRoute(this RouteCollection routes, string name, string url, object defaults, string[] namespaces)\n        {\n            return MapRoute(routes, name, url, defaults, null /* constraints */, namespaces);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"2#\", Justification = \"This is not a regular URL as it may contain special routing characters.\")]\n        public static Route MapRoute(this RouteCollection routes, string name, string url, object defaults, object constraints, string[] namespaces)\n        {\n            if (routes == null)\n            {\n                throw new ArgumentNullException(\"routes\");\n            }\n            if (url == null)\n            {\n                throw new ArgumentNullException(\"url\");\n            }\n\n            Route route = new Route(url, new MvcRouteHandler())\n            {\n                Defaults = CreateRouteValueDictionaryUncached(defaults),\n                Constraints = CreateRouteValueDictionaryUncached(constraints),\n                DataTokens = new RouteValueDictionary()\n            };\n\n            ConstraintValidation.Validate(route);\n\n            if ((namespaces != null) && (namespaces.Length > 0))\n            {\n                route.DataTokens[RouteDataTokenKeys.Namespaces] = namespaces;\n            }\n\n            routes.Add(name, route);\n\n            return route;\n        }\n\n        /// <summary>\n        /// The callers to this method are used at startup only, thus it's a bit better to use\n        /// the uncached method because it will run faster for the first few times, and will not\n        /// consume memory long term.\n        /// </summary>\n        private static RouteValueDictionary CreateRouteValueDictionaryUncached(object values)\n        {\n            var dictionary = values as IDictionary<string, object>;\n            if (dictionary != null)\n            {\n                return new RouteValueDictionary(dictionary);\n            }\n\n            return TypeHelper.ObjectToDictionaryUncached(values);\n        }\n\n        private sealed class IgnoreRouteInternal : Route\n        {\n            public IgnoreRouteInternal(string url)\n                : base(url, new StopRoutingHandler())\n            {\n            }\n\n            public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary routeValues)\n            {\n                // Never match during route generation. This avoids the scenario where an IgnoreRoute with\n                // fairly relaxed constraints ends up eagerly matching all generated URLs.\n                return null;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/RouteDataValueProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\n\nnamespace System.Web.Mvc\n{\n    public sealed class RouteDataValueProvider : DictionaryValueProvider<object>\n    {\n        // RouteData should use the invariant culture since it's part of the URL, and the URL should be\n        // interpreted in a uniform fashion regardless of the origin of a particular request.\n        public RouteDataValueProvider(ControllerContext controllerContext)\n            : base(controllerContext.RouteData.Values, CultureInfo.InvariantCulture)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/RouteDataValueProviderFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public sealed class RouteDataValueProviderFactory : ValueProviderFactory\n    {\n        public override IValueProvider GetValueProvider(ControllerContext controllerContext)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n\n            return new RouteDataValueProvider(controllerContext);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/RoutePrefixAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Mvc.Routing;\n\nnamespace System.Web.Mvc\n{\n    /// <summary>\n    /// Annotates a controller with a route prefix that applies to all actions within the controller.\n    /// </summary>\n    [SuppressMessage(\"Microsoft.Performance\", \"CA1813:AvoidUnsealedAttributes\", Justification = \"This attribute is intended to be extended by the user.\")]\n    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]\n    public class RoutePrefixAttribute : Attribute, IRoutePrefix\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"RoutePrefixAttribute\" /> class without specifying any parameters.\n        /// </summary>\n        protected RoutePrefixAttribute()\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"RoutePrefixAttribute\" /> class.\n        /// </summary>\n        /// <param name=\"prefix\">The route prefix for the controller.</param>\n        public RoutePrefixAttribute(string prefix)\n        {\n            if (prefix == null)\n            {\n                throw new ArgumentNullException(\"prefix\");\n            }\n\n            Prefix = prefix;\n        }\n\n        /// <summary>\n        /// Gets the route prefix.\n        /// </summary>\n        public virtual string Prefix { get; private set; }\n    }\n}"
  },
  {
    "path": "src/System.Web.Mvc/RouteValuesHelpers.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Routing;\n\nnamespace System.Web.Mvc\n{\n    internal static class RouteValuesHelpers\n    {\n        public static RouteValueDictionary GetRouteValues(RouteValueDictionary routeValues)\n        {\n            return (routeValues != null) ? new RouteValueDictionary(routeValues) : new RouteValueDictionary();\n        }\n\n        public static RouteValueDictionary MergeRouteValues(string actionName, string controllerName, RouteValueDictionary implicitRouteValues, RouteValueDictionary routeValues, bool includeImplicitMvcValues)\n        {\n            // Create a new dictionary containing implicit and auto-generated values\n            RouteValueDictionary mergedRouteValues = new RouteValueDictionary();\n\n            if (includeImplicitMvcValues)\n            {\n                // We only include MVC-specific values like 'controller' and 'action' if we are generating an action link.\n                // If we are generating a route link [as to MapRoute(\"Foo\", \"any/url\", new { controller = ... })], including\n                // the current controller name will cause the route match to fail if the current controller is not the same\n                // as the destination controller.\n\n                object implicitValue;\n                if (implicitRouteValues != null && implicitRouteValues.TryGetValue(\"action\", out implicitValue))\n                {\n                    mergedRouteValues[\"action\"] = implicitValue;\n                }\n\n                if (implicitRouteValues != null && implicitRouteValues.TryGetValue(\"controller\", out implicitValue))\n                {\n                    mergedRouteValues[\"controller\"] = implicitValue;\n                }\n            }\n\n            // Merge values from the user's dictionary/object\n            if (routeValues != null)\n            {\n                foreach (KeyValuePair<string, object> routeElement in GetRouteValues(routeValues))\n                {\n                    mergedRouteValues[routeElement.Key] = routeElement.Value;\n                }\n            }\n\n            // Merge explicit parameters when not null\n            if (actionName != null)\n            {\n                mergedRouteValues[\"action\"] = actionName;\n            }\n\n            if (controllerName != null)\n            {\n                mergedRouteValues[\"controller\"] = controllerName;\n            }\n\n            return mergedRouteValues;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Routing/AttributeRoutingMapper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing System.Reflection;\nusing System.Text;\nusing System.Web.Mvc.Async;\nusing System.Web.Mvc.Properties;\nusing System.Web.Routing;\n\nnamespace System.Web.Mvc.Routing\n{\n    /// <remarks>\n    /// Corresponds to the Web API implementation of attribute routing in\n    /// System.Web.Http.Routing.AttributeRoutingMapper.\n    /// </remarks>\n    internal static class AttributeRoutingMapper\n    {\n        /// <summary>\n        /// Maps the attribute-defined routes for the application.\n        /// </summary>\n        /// <param name=\"routes\">The route collection.</param>\n        /// <param name=\"constraintResolver\">\n        /// The <see cref=\"IInlineConstraintResolver\"/> to use for resolving inline constraints in route templates.\n        /// </param>\n        public static void MapAttributeRoutes(RouteCollection routes, IInlineConstraintResolver constraintResolver)\n        {\n            if (routes == null)\n            {\n                throw new ArgumentNullException(\"routes\");\n            }\n\n            if (constraintResolver == null)\n            {\n                throw new ArgumentNullException(\"constraintResolver\");\n            }\n\n            MapAttributeRoutes(routes, constraintResolver, new DefaultDirectRouteProvider());\n        }\n\n        /// <summary>\n        /// Maps the attribute-defined routes for the application.\n        /// </summary>\n        /// <param name=\"routes\">The route collection.</param>\n        /// <param name=\"constraintResolver\">\n        /// The <see cref=\"IInlineConstraintResolver\"/> to use for resolving inline constraints in route templates.\n        /// </param>\n        /// <param name=\"directRouteProvider\">\n        /// The <see cref=\"IDirectRouteProvider\"/> to use for mapping routes from controller types.\n        /// </param>\n        public static void MapAttributeRoutes(\n            RouteCollection routes, \n            IInlineConstraintResolver constraintResolver, \n            IDirectRouteProvider directRouteProvider)\n        {\n            if (routes == null)\n            {\n                throw new ArgumentNullException(\"routes\");\n            }\n\n            if (constraintResolver == null)\n            {\n                throw new ArgumentNullException(\"constraintResolver\");\n            }\n\n            if (directRouteProvider == null)\n            {\n                throw new ArgumentNullException(\"directRouteProvider\");\n            }\n\n            DefaultControllerFactory typesLocator =\n                DependencyResolver.Current.GetService<IControllerFactory>() as DefaultControllerFactory\n                ?? ControllerBuilder.Current.GetControllerFactory() as DefaultControllerFactory\n                ?? new DefaultControllerFactory();\n\n            IReadOnlyList<Type> controllerTypes = typesLocator.GetControllerTypes();\n\n            MapAttributeRoutes(routes, controllerTypes, constraintResolver, directRouteProvider);\n        }\n\n        /// <summary>\n        /// Maps the attribute-defined routes for the application.\n        /// </summary>\n        /// <param name=\"routes\">The route collection.</param>\n        /// <param name=\"controllerTypes\">The controller types to scan.</param>\n        public static void MapAttributeRoutes(RouteCollection routes, IEnumerable<Type> controllerTypes)\n        {\n            MapAttributeRoutes(routes, controllerTypes, new DefaultInlineConstraintResolver());\n        }\n\n        /// <summary>\n        /// Maps the attribute-defined routes for the application.\n        /// </summary>\n        /// <param name=\"routes\">The route collection.</param>\n        /// <param name=\"controllerTypes\">The controller types to scan.</param>\n        /// <param name=\"constraintResolver\">\n        /// The <see cref=\"IInlineConstraintResolver\"/> to use for resolving inline constraints in route templates.\n        /// </param>\n        public static void MapAttributeRoutes(RouteCollection routes, IEnumerable<Type> controllerTypes,\n            IInlineConstraintResolver constraintResolver)\n        {\n            MapAttributeRoutes(routes, controllerTypes, constraintResolver, new DefaultDirectRouteProvider());\n        }\n\n        /// <summary>\n        /// Maps the attribute-defined routes for the application.\n        /// </summary>\n        /// <param name=\"routes\">The route collection.</param>\n        /// <param name=\"controllerTypes\">The controller types to scan.</param>\n        /// <param name=\"constraintResolver\">\n        /// The <see cref=\"IInlineConstraintResolver\"/> to use for resolving inline constraints in route templates.\n        /// </param>\n        /// <param name=\"directRouteProvider\">\n        /// The <see cref=\"IDirectRouteProvider\"/> to use for mapping routes from controller types.\n        /// </param>\n        public static void MapAttributeRoutes(RouteCollection routes, IEnumerable<Type> controllerTypes,\n            IInlineConstraintResolver constraintResolver, IDirectRouteProvider directRouteProvider)\n        {\n            if (routes == null)\n            {\n                throw new ArgumentNullException(\"routes\");\n            }\n\n            if (controllerTypes == null)\n            {\n                throw new ArgumentNullException(\"controllerTypes\");\n            }\n\n            if (constraintResolver == null)\n            {\n                throw new ArgumentNullException(\"constraintResolver\");\n            }\n\n            if (directRouteProvider == null)\n            {\n                throw new ArgumentNullException(\"directRouteProvider\");\n            }\n\n            SubRouteCollection subRoutes = new SubRouteCollection();\n            AddRouteEntries(subRoutes, controllerTypes, constraintResolver, directRouteProvider);\n            IReadOnlyCollection<RouteEntry> entries = subRoutes.Entries;\n\n            if (entries.Count > 0)\n            {\n                RouteCollectionRoute aggregrateRoute = new RouteCollectionRoute(subRoutes);\n                routes.Add(aggregrateRoute);\n\n                // This sort is here to enforce a static ordering for link generation using these routes. \n                // We don't apply dynamic criteria like ActionSelectors on link generation, but we can use the static\n                // ones.\n                //\n                // Routes to actions are placed first because they are considered more specific. A route to an action\n                // will only match for link generation if the action name was supplied, so this is essential for\n                // correctness. Without this a controller-level route could be 'greedy' and generate a link when\n                // the action-level route was intended.\n                RouteEntry[] sorted = entries\n                    .OrderBy(r => r.Route.GetOrder())\n                    .ThenBy(r => r.Route.GetTargetIsAction() ? 0 : 1)\n                    .ThenBy(r => r.Route.GetPrecedence())\n                    .ToArray();\n\n                AddGenerationHooksForSubRoutes(routes, sorted);\n            }\n        }\n\n        // just for testing\n        internal static IReadOnlyCollection<RouteEntry> GetAttributeRoutes(Type controllerType)\n        {\n            SubRouteCollection collector = new SubRouteCollection();\n            AddRouteEntries(\n                collector, \n                new Type[] { controllerType }, \n                new DefaultInlineConstraintResolver(), \n                new DefaultDirectRouteProvider());\n\n            return collector.Entries;\n        }\n\n        // Add generation hooks for the Attribute-routing subroutes. \n        // This lets us generate urls for routes supplied by attr-based routing.\n        private static void AddGenerationHooksForSubRoutes(RouteCollection routeTable, IList<RouteEntry> entries)\n        {\n            Contract.Assert(entries != null);\n\n            foreach (RouteEntry entry in entries)\n            {\n                Contract.Assert(entry != null);\n                Route route = entry.Route;\n                Contract.Assert(route != null);\n                RouteBase linkGenerationRoute = new LinkGenerationRoute(route);\n                string name = entry.Name;\n\n                if (name == null)\n                {\n                    routeTable.Add(linkGenerationRoute);\n                }\n                else\n                {\n                    routeTable.Add(name, linkGenerationRoute);\n                }\n            }\n        }\n\n        internal static void AddRouteEntries(SubRouteCollection collector, IEnumerable<Type> controllerTypes,\n            IInlineConstraintResolver constraintResolver, IDirectRouteProvider directRouteProvider)\n        {\n            IEnumerable<ReflectedAsyncControllerDescriptor> controllers = GetControllerDescriptors(controllerTypes);\n\n            foreach (ReflectedAsyncControllerDescriptor controller in controllers)\n            {\n                List<ActionDescriptor> actions = GetActionDescriptors(controller);\n\n                IReadOnlyCollection<RouteEntry> entries = directRouteProvider.GetDirectRoutes(controller, actions, constraintResolver);\n                if (entries == null)\n                {\n                    throw Error.InvalidOperation(\n                        MvcResources.TypeMethodMustNotReturnNull,\n                        typeof(IDirectRouteProvider).Name, \n                        \"GetDirectRoutes\");\n                }\n\n                foreach (RouteEntry entry in entries)\n                {\n                    if (entry == null)\n                    {\n                        throw Error.InvalidOperation(\n                            MvcResources.TypeMethodMustNotReturnNull,\n                            typeof(IDirectRouteProvider).Name, \n                            \"GetDirectRoutes\");\n                    }\n\n                    DirectRouteBuilder.ValidateRouteEntry(entry);\n\n                    // This marks the action/controller as unreachable via traditional routing.\n                    if (entry.Route.GetTargetIsAction())\n                    {\n                        var actionDescriptors = entry.Route.GetTargetActionDescriptors();\n                        Contract.Assert(actionDescriptors != null && actionDescriptors.Any());\n\n                        foreach (var actionDescriptor in actionDescriptors.OfType<IMethodInfoActionDescriptor>())\n                        {\n                            var methodInfo = actionDescriptor.MethodInfo;\n                            if (methodInfo != null)\n                            {\n                                controller.Selector.StandardRouteMethods.Remove(methodInfo);\n                            }\n                        }\n                    }\n                    else\n                    {\n                        // This is a controller-level route - no actions in this controller are reachable via\n                        // traditional routes.\n                        controller.Selector.StandardRouteMethods.Clear();\n                    }\n                }\n\n                collector.AddRange(entries);\n            }\n        }\n\n        private static IEnumerable<ReflectedAsyncControllerDescriptor> GetControllerDescriptors(IEnumerable<Type> controllerTypes)\n        {\n            Contract.Assert(controllerTypes != null);\n\n            Func<Type, ControllerDescriptor> descriptorFactory = ReflectedAsyncControllerDescriptor.DefaultDescriptorFactory;\n            ControllerDescriptorCache descriptorsCache = new AsyncControllerActionInvoker().DescriptorCache;\n\n            return \n                controllerTypes\n                .Select(type => descriptorsCache.GetDescriptor(type, descriptorFactory, type))\n                .Cast<ReflectedAsyncControllerDescriptor>();\n        }\n\n        private static List<ActionDescriptor> GetActionDescriptors(ReflectedAsyncControllerDescriptor controller)\n        {\n            Contract.Assert(controller != null);\n\n            AsyncActionMethodSelector actionSelector = controller.Selector;\n\n            var actions = new List<ActionDescriptor>();\n            foreach (MethodInfo method in actionSelector.ActionMethods)\n            {\n                string actionName = actionSelector.GetActionName(method);\n                ActionDescriptorCreator creator = actionSelector.GetActionDescriptorDelegate(method);\n                Debug.Assert(creator != null);\n\n                ActionDescriptor action = creator(actionName, controller);\n                actions.Add(action);\n            }\n\n            return actions;\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Mvc/Routing/ConstraintValidation.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Web.Mvc.Properties;\nusing System.Web.Routing;\n\nnamespace System.Web.Mvc.Routing\n{\n    /// <summary>\n    /// Validates that the constraints on a Route are of a type that can be processed by <see cref=\"System.Web.Routing.Route\" />.\n    /// </summary>\n    /// <remarks>\n    /// This validation is only applicable when the <see cref=\"System.Web.Routing.Route\" /> is one that we created. A user-defined\n    /// type that is derived from <see cref=\"System.Web.Routing.RouteBase\" /> may have different semantics.\n    /// \n    /// The logic here is duplicated from System.Web, but we need it to validate correctness of routes on startup. Since we can't \n    /// change System.Web, this just lives in a static class for MVC.\n    /// </remarks>\n    internal static class ConstraintValidation\n    {\n        public static void Validate(Route route)\n        {\n            Contract.Assert(route != null);\n            Contract.Assert(route.Url != null);\n\n            if (route.Constraints == null)\n            {\n                return;\n            }\n\n            foreach (var kvp in route.Constraints)\n            {\n                if (kvp.Value is string)\n                {\n                    continue;\n                }\n\n                if (kvp.Value is IRouteConstraint)\n                {\n                    continue;\n                }\n\n                throw Error.InvalidOperation(\n                    MvcResources.Route_InvalidConstraint,\n                    kvp.Key,\n                    route.Url,\n                    typeof(IRouteConstraint).FullName);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Routing/DefaultDirectRouteProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing System.Reflection;\nusing System.Web.Mvc.Properties;\nusing System.Web.Routing;\n\nnamespace System.Web.Mvc.Routing\n{\n    public class DefaultDirectRouteProvider : IDirectRouteProvider\n    {\n        /// <summary>\n        /// Gets direct routes for the given controller descriptor and action descriptors based on \n        /// <see cref=\"IDirectRouteFactory\"/> attributes.\n        /// </summary>\n        /// <param name=\"controllerDescriptor\">The controller descriptor.</param>\n        /// <param name=\"actionDescriptors\">The action descriptors for all actions.</param>\n        /// <param name=\"constraintResolver\">The constraint resolver.</param>\n        /// <returns>A set of route entries.</returns>\n        /// <remarks>\n        /// The implementation returns route entries for the given controller and actions. \n        /// \n        /// Any actions that have associated <see cref=\"IDirectRouteFactory\"/> instances will produce route\n        /// entries that route direct to those actions.\n        /// \n        /// Any actions that do not have an associated <see cref=\"IDirectRouteFactory\"/> instances will be\n        /// associated with the controller. If the controller has any associated <see cref=\"IDirectRouteProvider\"/>\n        /// instances, then route entries will be created for the controller and associated actions.\n        /// </remarks>\n        public virtual IReadOnlyList<RouteEntry> GetDirectRoutes(\n            ControllerDescriptor controllerDescriptor,\n            IReadOnlyList<ActionDescriptor> actionDescriptors,\n            IInlineConstraintResolver constraintResolver)\n        {\n            List<RouteEntry> entries = new List<RouteEntry>();\n\n            List<ActionDescriptor> actionsWithoutRoutes = new List<ActionDescriptor>();\n\n            foreach (ActionDescriptor action in actionDescriptors)\n            {\n                IReadOnlyList<IDirectRouteFactory> factories = GetActionRouteFactories(action);\n\n                if (factories != null && factories.Count > 0)\n                {\n                    IReadOnlyCollection<RouteEntry> actionEntries = GetActionDirectRoutes(action, factories, constraintResolver);\n                    if (actionEntries != null)\n                    {\n                        entries.AddRange(actionEntries);\n                    }\n                }\n                else\n                {\n                    // IF there are no routes on the specific action, attach it to the controller routes (if any).\n                    actionsWithoutRoutes.Add(action);\n                }\n            }\n\n            if (actionsWithoutRoutes.Count > 0)\n            {\n                IReadOnlyList<IDirectRouteFactory> controllerFactories = GetControllerRouteFactories(controllerDescriptor);\n                if (controllerFactories != null && controllerFactories.Count > 0)\n                {\n                    IReadOnlyCollection<RouteEntry> controllerEntries = GetControllerDirectRoutes(\n                        controllerDescriptor,\n                        actionsWithoutRoutes,\n                        controllerFactories,\n                        constraintResolver);\n\n                    if (controllerEntries != null)\n                    {\n                        entries.AddRange(controllerEntries);\n                    }\n                }\n            }\n\n            return entries;\n        }\n\n        /// <summary>\n        /// Gets route factories for the given controller descriptor.\n        /// </summary>\n        /// <param name=\"controllerDescriptor\">The controller descriptor.</param>\n        /// <returns>A set of route factories.</returns>\n        /// <remarks>\n        /// The implementation returns <see cref=\"IDirectRouteFactory\"/> instances based on attributes on the controller.\n        /// </remarks>\n        protected virtual IReadOnlyList<IDirectRouteFactory> GetControllerRouteFactories(ControllerDescriptor controllerDescriptor)\n        {\n            object[] attributes = controllerDescriptor.GetCustomAttributes(inherit: false);\n            IEnumerable<IDirectRouteFactory> newFactories = attributes.OfType<IDirectRouteFactory>();\n            IEnumerable<IRouteInfoProvider> oldProviders = attributes.OfType<IRouteInfoProvider>();\n\n            List<IDirectRouteFactory> combined = new List<IDirectRouteFactory>();\n            combined.AddRange(newFactories);\n\n            foreach (IRouteInfoProvider oldProvider in oldProviders)\n            {\n                if (oldProvider is IDirectRouteFactory)\n                {\n                    continue;\n                }\n\n                combined.Add(new RouteInfoDirectRouteFactory(oldProvider));\n            }\n\n            return combined;\n        }\n\n        /// <summary>\n        /// Gets a set of route factories for the given action descriptor.\n        /// </summary>\n        /// <param name=\"actionDescriptor\">The action descriptor.</param>\n        /// <returns>A set of route factories.</returns>\n        /// <remarks>\n        /// The implementation returns <see cref=\"IDirectRouteFactory\"/> instances based on attributes on the action. Returns\n        /// null if the action was defined on a base class of this controller.\n        /// </remarks>\n        protected virtual IReadOnlyList<IDirectRouteFactory> GetActionRouteFactories(ActionDescriptor actionDescriptor)\n        {\n            // Skip Route attributes on inherited actions.\n            IMethodInfoActionDescriptor methodInfoActionDescriptor = actionDescriptor as IMethodInfoActionDescriptor;\n            if (methodInfoActionDescriptor != null &&\n                methodInfoActionDescriptor.MethodInfo != null &&\n                actionDescriptor.ControllerDescriptor != null &&\n                methodInfoActionDescriptor.MethodInfo.DeclaringType != actionDescriptor.ControllerDescriptor.ControllerType)\n            {\n                return null;\n            }\n\n            object[] attributes = actionDescriptor.GetCustomAttributes(inherit: false);\n            IEnumerable<IDirectRouteFactory> newFactories = attributes.OfType<IDirectRouteFactory>();\n            IEnumerable<IRouteInfoProvider> oldProviders = attributes.OfType<IRouteInfoProvider>();\n\n            List<IDirectRouteFactory> combined = new List<IDirectRouteFactory>();\n            combined.AddRange(newFactories);\n\n            foreach (IRouteInfoProvider oldProvider in oldProviders)\n            {\n                if (oldProvider is IDirectRouteFactory)\n                {\n                    continue;\n                }\n\n                combined.Add(new RouteInfoDirectRouteFactory(oldProvider));\n            }\n\n            return combined;\n        }\n\n        /// <summary>\n        /// Creates <see cref=\"RouteEntry\"/> instances based on the provided factories, controller and actions. The route\n        /// entries provided direct routing to the provided controller and can reach the set of provided actions.\n        /// </summary>\n        /// <param name=\"controllerDescriptor\">The controller descriptor.</param>\n        /// <param name=\"actionDescriptors\">The action descriptors.</param>\n        /// <param name=\"factories\">The direct route factories.</param>\n        /// <param name=\"constraintResolver\">The constraint resolver.</param>\n        /// <returns>A set of route entries.</returns>\n        protected virtual IReadOnlyList<RouteEntry> GetControllerDirectRoutes(\n            ControllerDescriptor controllerDescriptor,\n            IReadOnlyList<ActionDescriptor> actionDescriptors,\n            IReadOnlyList<IDirectRouteFactory> factories,\n            IInlineConstraintResolver constraintResolver)\n        {\n            return CreateRouteEntries(\n                GetAreaPrefix(controllerDescriptor),\n                GetRoutePrefix(controllerDescriptor),\n                factories,\n                actionDescriptors,\n                constraintResolver,\n                targetIsAction: false);\n        }\n\n        /// <summary>\n        /// Creates <see cref=\"RouteEntry\"/> instances based on the provided factories and action. The route entries\n        /// provide direct routing to the provided action.\n        /// </summary>\n        /// <param name=\"actionDescriptor\">The action descriptor.</param>\n        /// <param name=\"factories\">The direct route factories.</param>\n        /// <param name=\"constraintResolver\">The constraint resolver.</param>\n        /// <returns>A set of route entries.</returns>\n        protected virtual IReadOnlyList<RouteEntry> GetActionDirectRoutes(\n            ActionDescriptor actionDescriptor,\n            IReadOnlyList<IDirectRouteFactory> factories,\n            IInlineConstraintResolver constraintResolver)\n        {\n            return CreateRouteEntries(\n                GetAreaPrefix(actionDescriptor.ControllerDescriptor),\n                GetRoutePrefix(actionDescriptor.ControllerDescriptor),\n                factories,\n                new ActionDescriptor[] { actionDescriptor },\n                constraintResolver,\n                targetIsAction: true);\n        }\n\n        /// <summary>\n        /// Gets the route prefix from the provided controller.\n        /// </summary>\n        /// <param name=\"controllerDescriptor\">The controller descriptor.</param>\n        /// <returns>The route prefix or null.</returns>\n        protected virtual string GetRoutePrefix(ControllerDescriptor controllerDescriptor)\n        {\n            IRoutePrefix[] attributes = controllerDescriptor.GetCustomAttributes(inherit: false).OfType<IRoutePrefix>().ToArray();\n\n            if (attributes == null)\n            {\n                return null;\n            }\n\n            if (attributes.Length > 1)\n            {\n                string errorMessage = Error.Format(\n                    MvcResources.RoutePrefix_CannotSupportMultiRoutePrefix,\n                    controllerDescriptor.ControllerType.FullName);\n                throw new InvalidOperationException(errorMessage);\n            }\n\n            if (attributes.Length == 1)\n            {\n                IRoutePrefix attribute = attributes[0];\n\n                if (attribute != null)\n                {\n                    string prefix = attribute.Prefix;\n                    if (prefix == null)\n                    {\n                        string errorMessage = Error.Format(\n                            MvcResources.RoutePrefix_PrefixCannotBeNull,\n                            controllerDescriptor.ControllerType.FullName);\n                        throw new InvalidOperationException(errorMessage);\n                    }\n\n                    if (prefix.StartsWith(\"/\", StringComparison.Ordinal)\n                        || prefix.EndsWith(\"/\", StringComparison.Ordinal))\n                    {\n                        string errorMessage = Error.Format(\n                            MvcResources.RoutePrefix_CannotStartOrEnd_WithForwardSlash, prefix,\n                            controllerDescriptor.ControllerName);\n                        throw new InvalidOperationException(errorMessage);\n                    }\n\n                    return prefix;\n                }\n            }\n\n            return null;\n        }\n\n        /// <summary>\n        /// Gets the area prefix from the provided controller.\n        /// </summary>\n        /// <param name=\"controllerDescriptor\">The controller descriptor.</param>\n        /// <returns>The area prefix or null.</returns>\n        protected virtual string GetAreaPrefix(ControllerDescriptor controllerDescriptor)\n        {\n            RouteAreaAttribute area = controllerDescriptor.GetAreaFrom();\n            string areaName = controllerDescriptor.GetAreaName(area);\n            string areaPrefix = area != null ? area.AreaPrefix ?? area.AreaName : null;\n\n            ValidateAreaPrefixTemplate(areaPrefix, areaName, controllerDescriptor);\n\n            return areaPrefix;\n        }\n\n        private static IReadOnlyList<RouteEntry> CreateRouteEntries(\n            string areaPrefix,\n            string controllerPrefix,\n            IReadOnlyCollection<IDirectRouteFactory> factories,\n            IReadOnlyCollection<ActionDescriptor> actions,\n            IInlineConstraintResolver constraintResolver,\n            bool targetIsAction)\n        {\n            List<RouteEntry> entries = new List<RouteEntry>();\n            foreach (IDirectRouteFactory factory in factories)\n            {\n                RouteEntry entry = CreateRouteEntry(areaPrefix, controllerPrefix, factory, actions, constraintResolver, targetIsAction);\n                entries.Add(entry);\n            }\n\n            return entries;\n        }\n\n        // Internal for testing\n        internal static RouteEntry CreateRouteEntry(\n            string areaPrefix,\n            string controllerPrefix,\n            IDirectRouteFactory factory,\n            IReadOnlyCollection<ActionDescriptor> actions,\n            IInlineConstraintResolver constraintResolver,\n            bool targetIsAction)\n        {\n            Contract.Assert(factory != null);\n\n            DirectRouteFactoryContext context = new DirectRouteFactoryContext(\n                areaPrefix, \n                controllerPrefix, \n                actions, \n                constraintResolver, \n                targetIsAction);\n\n            RouteEntry entry = factory.CreateRoute(context);\n\n            if (entry == null)\n            {\n                throw Error.InvalidOperation(\n                    MvcResources.TypeMethodMustNotReturnNull,\n                    typeof(IDirectRouteFactory).Name, \n                    \"CreateRoute\");\n            }\n\n            DirectRouteBuilder.ValidateRouteEntry(entry);\n\n            return entry;\n        }\n\n        private static void ValidateAreaPrefixTemplate(string areaPrefix, string areaName, ControllerDescriptor controllerDescriptor)\n        {\n            if (areaPrefix != null && areaPrefix.EndsWith(\"/\", StringComparison.Ordinal))\n            {\n                string errorMessage = Error.Format(MvcResources.RouteAreaPrefix_CannotEnd_WithForwardSlash,\n                                                   areaPrefix, areaName, controllerDescriptor.ControllerName);\n                throw new InvalidOperationException(errorMessage);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Routing/DirectRouteCandidate.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.Linq;\nusing System.Reflection;\nusing System.Text;\nusing System.Web.Mvc.Async;\nusing System.Web.Mvc.Properties;\nusing System.Web.Routing;\n\nnamespace System.Web.Mvc.Routing\n{\n    /// <summary>\n    /// Represents a candidate action found via a direct route.\n    /// </summary>\n    /// <remarks>\n    /// Members are get/set for testability of the 'best-match' algorithm.\n    /// </remarks>\n    internal class DirectRouteCandidate\n    {\n        public ActionDescriptor ActionDescriptor\n        {\n            get;\n            set;\n        }\n\n        public IEnumerable<ActionNameSelector> ActionNameSelectors\n        {\n            get;\n            set;\n        }\n\n        public IEnumerable<ActionSelector> ActionSelectors\n        {\n            get;\n            set;\n        }\n\n        public ControllerDescriptor ControllerDescriptor\n        {\n            get;\n            set;\n        }\n\n        public bool HasActionNameSelectors\n        {\n            get\n            {\n                return ActionNameSelectors != null && ActionNameSelectors.Any();\n            }\n        }\n\n        public bool HasActionSelectors\n        {\n            get\n            {\n                return ActionSelectors != null && ActionSelectors.Any();\n            }\n        }\n\n        public int Order\n        {\n            get;\n            set;\n        }\n\n        public decimal Precedence\n        {\n            get;\n            set;\n        }\n\n        public RouteData RouteData\n        {\n            get;\n            set;\n        }\n\n        public static DirectRouteCandidate SelectBestCandidate(List<DirectRouteCandidate> candidates, ControllerContext controllerContext)\n        {\n            Debug.Assert(controllerContext != null);\n            Debug.Assert(candidates != null);\n\n            // These filters will allow actions to opt-out of execution via the provided public extensibility points.\n            List<DirectRouteCandidate> filteredByActionName = ApplyActionNameFilters(candidates, controllerContext);\n            List<DirectRouteCandidate> applicableCandidates = ApplyActionSelectors(filteredByActionName, controllerContext);\n\n            // At this point all of the remaining actions are applicable - now we're just trying to find the\n            // most specific match.\n            //\n            // Order is first, because it's the 'override' to our algorithm\n            List<DirectRouteCandidate> filteredByOrder = FilterByOrder(applicableCandidates);\n            List<DirectRouteCandidate> filteredByPrecedence = FilterByPrecedence(filteredByOrder);\n\n            if (filteredByPrecedence.Count == 0)\n            {\n                return null;\n            }\n            else if (filteredByPrecedence.Count == 1)\n            {\n                return filteredByPrecedence[0];\n            }\n            else\n            {\n                throw CreateAmbiguiousMatchException(candidates);\n            }\n        }\n\n        private static AmbiguousMatchException CreateAmbiguiousMatchException(List<DirectRouteCandidate> candidates)\n        {\n            string ambiguityList = CreateAmbiguousMatchList(candidates);\n            string message = String.Format(\n                CultureInfo.CurrentCulture,\n                MvcResources.DirectRoute_AmbiguousMatch,\n                ambiguityList);\n\n            return new AmbiguousMatchException(message);\n        }\n\n        protected static string CreateAmbiguousMatchList(IEnumerable<DirectRouteCandidate> candidates)\n        {\n            StringBuilder exceptionMessageBuilder = new StringBuilder();\n            foreach (DirectRouteCandidate candidate in candidates)\n            {\n                MethodInfo method = null;\n\n                ReflectedActionDescriptor reflectedActionDescriptor = candidate.ActionDescriptor as ReflectedActionDescriptor;\n                if (reflectedActionDescriptor == null)\n                {\n                    ReflectedAsyncActionDescriptor reflectedAsyncActionDescriptor = candidate.ActionDescriptor as ReflectedAsyncActionDescriptor;\n                    if (reflectedAsyncActionDescriptor != null)\n                    {\n                        method = reflectedAsyncActionDescriptor.AsyncMethodInfo;\n                    }\n                }\n                else\n                {\n                    method = reflectedActionDescriptor.MethodInfo;\n                }\n\n                string controllerAction = method == null ? candidate.ActionDescriptor.ActionName : Convert.ToString(method, CultureInfo.CurrentCulture);\n                string controllerType = method.DeclaringType.FullName;\n\n                exceptionMessageBuilder.AppendLine();\n                exceptionMessageBuilder.AppendFormat(CultureInfo.CurrentCulture, MvcResources.ActionMethodSelector_AmbiguousMatchType, controllerAction, controllerType);\n            }\n\n            return exceptionMessageBuilder.ToString();\n        }\n\n        private static List<DirectRouteCandidate> ApplyActionNameFilters(List<DirectRouteCandidate> candidates, ControllerContext controllerContext)\n        {\n            List<DirectRouteCandidate> filtered = new List<DirectRouteCandidate>();\n            foreach (DirectRouteCandidate candidate in candidates)\n            {\n                string actionName;\n                candidate.RouteData.Values.TryGetValue<string>(\"action\", out actionName);\n\n                if (candidate.HasActionNameSelectors)\n                {\n                    // For the sake of consistency - we still want to call the action name selectors even if\n                    // this route was matched without providing an action name.\n                    actionName = actionName ?? candidate.ActionDescriptor.ActionName;\n\n                    if (candidate.ActionNameSelectors.All(selector => selector(controllerContext, actionName)))\n                    {\n                        filtered.Add(candidate);\n                    }\n                }\n                else if (actionName != null)\n                {\n                    if (String.Equals(actionName, candidate.ActionDescriptor.ActionName, StringComparison.OrdinalIgnoreCase))\n                    {\n                        filtered.Add(candidate);\n                    }\n                }\n                else\n                {\n                    // No name-based filtering applies for this route.\n                    filtered.Add(candidate);\n                }\n            }\n\n            return filtered;\n        }\n\n        private static List<DirectRouteCandidate> ApplyActionSelectors(List<DirectRouteCandidate> candidates, ControllerContext controllerContext)\n        {\n            List<DirectRouteCandidate> matchesWithActionSelectors = new List<DirectRouteCandidate>();\n            List<DirectRouteCandidate> matchesWithoutActionSelectors = new List<DirectRouteCandidate>();\n\n            foreach (DirectRouteCandidate candidate in candidates)\n            {\n                if (candidate.HasActionSelectors)\n                {\n                    if (candidate.ActionSelectors.All(selector => selector(controllerContext)))\n                    {\n                        matchesWithActionSelectors.Add(candidate);\n                    }\n                }\n                else\n                {\n                    matchesWithoutActionSelectors.Add(candidate);\n                }\n            }\n\n            return matchesWithActionSelectors.Any() ? matchesWithActionSelectors : matchesWithoutActionSelectors;\n        }\n\n        private static List<DirectRouteCandidate> FilterByOrder(List<DirectRouteCandidate> candidates)\n        {\n            if (!candidates.Any())\n            {\n                return candidates;\n            }\n\n            int minimum = candidates.Min(c => c.Order);\n            return candidates.Where(c => c.Order == minimum).AsList();\n        }\n\n        private static List<DirectRouteCandidate> FilterByPrecedence(List<DirectRouteCandidate> candidates)\n        {\n            if (!candidates.Any())\n            {\n                return candidates;\n            }\n\n            decimal minimum = candidates.Min(c => c.Precedence);\n            return candidates.Where(c => c.Precedence == minimum).AsList();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Routing/DirectRouteExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Reflection;\nusing System.Web.Routing;\n\nnamespace System.Web.Mvc.Routing\n{\n    internal static class DirectRouteExtensions\n    {\n        /// <summary>\n        /// Gets the precedence or this route.\n        /// </summary>\n        public static decimal GetPrecedence(this RouteData routeData)\n        {\n            return GetRouteDataTokenValue<decimal>(routeData, RouteDataTokenKeys.Precedence);\n        }\n\n        /// <summary>\n        /// Gets the precedence or this route.\n        /// </summary>\n        public static decimal GetPrecedence(this Route route)\n        {\n            return GetRouteDataTokenValue<decimal>(route, RouteDataTokenKeys.Precedence);\n        }\n\n        /// <summary>\n        /// Sets the precedence of this Route.\n        /// </summary>\n        public static void SetPrecedence(this Route route, decimal precedence)\n        {\n            SetRouteDataTokenValue(route, RouteDataTokenKeys.Precedence, precedence);\n        }\n\n        /// <summary>\n        /// Gets the order or this route.\n        /// </summary>\n        public static int GetOrder(this RouteData routeData)\n        {\n            return GetRouteDataTokenValue<int>(routeData, RouteDataTokenKeys.Order);\n        }\n\n        /// <summary>\n        /// Gets the order or this route.\n        /// </summary>\n        public static int GetOrder(this Route route)\n        {\n            return GetRouteDataTokenValue<int>(route, RouteDataTokenKeys.Order);\n        }\n\n        /// <summary>\n        /// Sets the order of this Route.\n        /// </summary>\n        public static void SetOrder(this Route route, int order)\n        {\n            SetRouteDataTokenValue(route, RouteDataTokenKeys.Order, order);\n        }\n\n        /// <summary>\n        /// Gets a value indicating whether or not the route is a direct route to an action.\n        /// </summary>\n        public static bool GetTargetIsAction(this RouteData routeData)\n        {\n            return GetRouteDataTokenValue<bool>(routeData, RouteDataTokenKeys.TargetIsAction);\n        }\n\n        /// <summary>\n        /// Gets a value indicating whether or not the route is a direct route to an action.\n        /// </summary>\n        public static bool GetTargetIsAction(this Route route)\n        {\n            return GetRouteDataTokenValue<bool>(route, RouteDataTokenKeys.TargetIsAction);\n        }\n\n        /// <summary>\n        /// Sets a value indicating whether or not the route is a direct route to an action.\n        /// </summary>\n        public static void SetTargetIsAction(this Route route, bool targetIsAction)\n        {\n            SetRouteDataTokenValue(route, RouteDataTokenKeys.TargetIsAction, targetIsAction);\n        }\n\n        /// <summary>\n        /// Gets the ControllerDescriptor that matches this Route.\n        /// </summary>\n        public static ControllerDescriptor GetTargetControllerDescriptor(this Route route)\n        {\n            var actions = GetTargetActionDescriptors(route);\n            ControllerDescriptor controller = null;\n\n            foreach (var action in actions)\n            {\n                if (controller == null)\n                {\n                    controller = action.ControllerDescriptor;\n                }\n                else if (controller != action.ControllerDescriptor)\n                {\n                    // Don't provide a single controller descriptor if multiple controllers match.\n                    return null;\n                }\n            }\n\n            return controller;\n        }\n\n        /// <summary>\n        /// Gets the ControllerDescriptor that matches this Route.\n        /// </summary>\n        public static ControllerDescriptor GetTargetControllerDescriptor(this RouteData routeData)\n        {\n            var actions = GetTargetActionDescriptors(routeData);\n            ControllerDescriptor controller = null;\n\n            foreach (var action in actions)\n            {\n                if (controller == null)\n                {\n                    controller = action.ControllerDescriptor;\n                }\n                else if (controller != action.ControllerDescriptor)\n                {\n                    // Don't provide a single controller descriptor if multiple controllers match.\n                    return null;\n                }\n            }\n\n            return controller;\n        }\n\n        public static Type GetTargetControllerType(this RouteData routeData)\n        {\n            ControllerDescriptor controllerDescriptor = routeData.GetTargetControllerDescriptor();\n            return controllerDescriptor == null ? null : controllerDescriptor.ControllerType;\n        }\n\n        /// <summary>\n        /// Gets the target actions that can be matched if this route is matched.\n        /// </summary>\n        public static ActionDescriptor[] GetTargetActionDescriptors(this RouteData routeData)\n        {\n            return GetRouteDataTokenValue<ActionDescriptor[]>(routeData, RouteDataTokenKeys.Actions);\n        }\n\n        /// <summary>\n        /// Gets the target actions that can be matched if this route is matched.\n        /// </summary>\n        public static ActionDescriptor[] GetTargetActionDescriptors(this Route route)\n        {\n            return GetRouteDataTokenValue<ActionDescriptor[]>(route, RouteDataTokenKeys.Actions);\n        }\n\n        /// <summary>\n        /// Sets the target actions that can be matched if this route is matched.\n        /// </summary>\n        public static void SetTargetActionDescriptors(this Route route, ActionDescriptor[] actionDescriptors)\n        {\n            if (actionDescriptors == null || actionDescriptors.Length == 0)\n            {\n                throw Error.ParameterCannotBeNullOrEmpty(\"actionDescriptors\");\n            }\n\n            SetRouteDataTokenValue(route, RouteDataTokenKeys.Actions, actionDescriptors);\n        }\n\n        public static bool HasDirectRouteMatch(this RouteData routeData)\n        {\n            if (routeData == null)\n            {\n                throw Error.ArgumentNull(\"routeData\");\n            }\n\n            return routeData.Values.ContainsKey(RouteDataTokenKeys.DirectRouteMatches);\n        }\n\n        public static IEnumerable<RouteData> GetDirectRouteMatches(this RouteData routeData)\n        {\n            return GetRouteDataValue<IEnumerable<RouteData>>(routeData, RouteDataTokenKeys.DirectRouteMatches) ?? Enumerable.Empty<RouteData>();\n        }\n\n        public static void SetDirectRouteMatches(this RouteData routeData, IEnumerable<RouteData> matches)\n        {\n            if (matches == null || !matches.Any())\n            {\n                throw Error.ParameterCannotBeNullOrEmpty(\"matches\");\n            }\n\n            SetRouteDataValue(routeData, RouteDataTokenKeys.DirectRouteMatches, matches);\n        }\n\n        public static bool IsDirectRoute(this RouteBase routeBase)\n        {\n            Route route = routeBase as Route;\n            if (route == null)\n            {\n                return false;\n            }\n            else\n            {\n                // All direct routes need to have actions associated.\n                return route.GetTargetActionDescriptors() != null;\n            }\n        }\n\n        private static T GetRouteDataTokenValue<T>(this Route route, string key)\n        {\n            if (route == null)\n            {\n                throw Error.ArgumentNull(\"route\");\n            }\n\n            if (key == null)\n            {\n                throw Error.ArgumentNull(\"key\");\n            }\n\n            T value;\n            if (route.DataTokens != null && route.DataTokens.TryGetValue(key, out value))\n            {\n                return value;\n            }\n            else\n            {\n                return default(T);\n            }\n        }\n\n        private static T GetRouteDataTokenValue<T>(this RouteData routeData, string key)\n        {\n            if (routeData == null)\n            {\n                throw Error.ArgumentNull(\"route\");\n            }\n\n            if (key == null)\n            {\n                throw Error.ArgumentNull(\"key\");\n            }\n\n            return GetRouteDataTokenValue<T>(routeData.Route as Route, key);\n        }\n\n        private static void SetRouteDataTokenValue<T>(this Route route, string key, T value)\n        {\n            if (route == null)\n            {\n                throw Error.ArgumentNull(\"route\");\n            }\n\n            if (key == null)\n            {\n                throw Error.ArgumentNull(\"key\");\n            }\n\n            if (route.DataTokens == null)\n            {\n                route.DataTokens = new RouteValueDictionary();\n            }\n\n            route.DataTokens[key] = value;\n        }\n\n        private static T GetRouteDataValue<T>(this RouteData routeData, string key)\n        {\n            if (routeData == null)\n            {\n                throw Error.ArgumentNull(\"routeData\");\n            }\n\n            if (key == null)\n            {\n                throw Error.ArgumentNull(\"key\");\n            }\n\n            T value;\n            if (routeData.Values.TryGetValue(key, out value))\n            {\n                return value;\n            }\n            else\n            {\n                return default(T);\n            }\n        }\n\n        private static void SetRouteDataValue<T>(this RouteData routeData, string key, T value)\n        {\n            if (routeData == null)\n            {\n                throw Error.ArgumentNull(\"routeData\");\n            }\n\n            if (key == null)\n            {\n                throw Error.ArgumentNull(\"key\");\n            }\n\n            routeData.Values[key] = value;\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Mvc/Routing/IDirectRouteProvider.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n#if ASPNETWEBAPI\nusing System.Web.Http.Controllers;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing\n#else\nnamespace System.Web.Mvc.Routing\n#endif\n{\n    /// <summary>\n    /// Defines a provider for routes that directly target action descriptors (attribute routes).\n    /// </summary>\n    public interface IDirectRouteProvider\n    {\n        /// <summary>Gets the direct routes for a controller.</summary>\n        /// <param name=\"controllerDescriptor\">The controller descriptor.</param>\n        /// <param name=\"actionDescriptors\">The action descriptors.</param>\n        /// <param name=\"constraintResolver\">The inline constraint resolver.</param>\n        /// <returns>A set of route entries for the controller.</returns>\n#if ASPNETWEBAPI\n        IReadOnlyList<RouteEntry> GetDirectRoutes(\n            HttpControllerDescriptor controllerDescriptor, \n            IReadOnlyList<HttpActionDescriptor> actionDescriptors,\n            IInlineConstraintResolver constraintResolver);\n#else\n        IReadOnlyList<RouteEntry> GetDirectRoutes(\n            ControllerDescriptor controllerDescriptor,\n            IReadOnlyList<ActionDescriptor> actionDescriptors,\n            IInlineConstraintResolver constraintResolver);\n#endif\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Routing/IRouteInfoProvider.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Routing;\n\nnamespace System.Web.Mvc.Routing\n{\n    /// <summary>\n    /// Provides information for building a <see cref=\"Route\"/>.\n    /// </summary>\n    public interface IRouteInfoProvider\n    {\n        /// <summary>\n        /// Gets the name of the route to generate.\n        /// </summary>\n        string Name { get; }\n\n        /// <summary>\n        /// Gets the route template describing the URI pattern to match against.\n        /// </summary>\n        string Template { get; }    \n    }\n}"
  },
  {
    "path": "src/System.Web.Mvc/Routing/LinkGenerationRoute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Routing;\n\nnamespace System.Web.Mvc.Routing\n{\n    /// <summary>\n    /// Adapts a named direct route into a top-level entry in the route table that can only be used\n    /// for generating a link (GetVirtualPath). We use these because the subroutes produced by direct\n    /// routing, don't go into the main collection and so can't be matched by name.\n    /// </summary>\n    /// <remarks>\n    /// Parallel to the Web API implementation of attribute routing in System.Web.Http.Routing.LinkGenerationRoute.\n    /// </remarks>\n    internal class LinkGenerationRoute : Route\n    {\n        private readonly Route _innerRoute;\n\n        public LinkGenerationRoute(Route innerRoute)\n            : base(innerRoute.Url, innerRoute.Defaults, innerRoute.Constraints, innerRoute.DataTokens,\n            innerRoute.RouteHandler)\n        {\n            if (innerRoute == null)\n            {\n                throw Error.ArgumentNull(\"innerRoute\");\n            }\n\n            _innerRoute = innerRoute;\n        }\n\n        public override RouteData GetRouteData(HttpContextBase httpContext)\n        {\n            // Claims no routes\n            return null;\n        }\n\n        public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)\n        {\n            return _innerRoute.GetVirtualPath(requestContext, values);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Routing/ParsedRoute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\n\nnamespace System.Web.Mvc.Routing\n{\n    internal class ParsedRoute\n    {\n        public ParsedRoute(IList<PathSegment> pathSegments)\n        {\n            {\n                Contract.Assert(pathSegments != null);\n                PathSegments = pathSegments;\n            }\n        }\n\n        public IList<PathSegment> PathSegments { get; private set; }\n    }\n}"
  },
  {
    "path": "src/System.Web.Mvc/Routing/RouteBuilder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing System.Web.Routing;\n\nnamespace System.Web.Mvc.Routing\n{\n    /// <summary>\n    /// Obsolete, use <see cref=\"System.Web.Mvc.Routing.RouteFactoryAttribute\"/> to customize generated attribute\n    /// routes.\n    /// </summary>\n    [Obsolete(\n        \"Obsolete, do not use. To create custom Routes with attribute routing, use \" +\n        \"System.Web.Mvc.Routing.RouteFactoryAttribute\")]\n    public class RouteBuilder\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"RouteBuilder\" /> class using the default inline constraint resolver.\n        /// </summary>\n        public RouteBuilder()\n            : this(new DefaultInlineConstraintResolver())\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"RouteBuilder\" /> class.\n        /// </summary>\n        /// <param name=\"constraintResolver\">The <see cref=\"IInlineConstraintResolver\"/> to use for resolving inline constraints.</param>\n        public RouteBuilder(IInlineConstraintResolver constraintResolver)\n        {\n            if (constraintResolver == null)\n            {\n                throw Error.ArgumentNull(\"constraintResolver\");\n            }\n\n            ConstraintResolver = constraintResolver;\n        }\n\n        public IInlineConstraintResolver ConstraintResolver { get; private set; }\n\n        /// <summary>\n        /// Builds an <see cref=\"Route\"/> for a particular controller.\n        /// </summary>\n        /// <param name=\"routeTemplate\">The tokenized route template for the route.</param>\n        /// <param name=\"controllerDescriptor\">The controller the route attribute has been applied on.</param>\n        /// <returns>The generated <see cref=\"Route\"/>.</returns>\n        public Route BuildDirectRoute(string routeTemplate, ControllerDescriptor controllerDescriptor)\n        {\n            if (routeTemplate == null)\n            {\n                throw Error.ArgumentNull(\"routeTemplate\");\n            }\n\n            if (controllerDescriptor == null)\n            {\n                throw Error.ArgumentNull(\"controllerDescriptor\");\n            }\n                        \n            string controllerName = controllerDescriptor.ControllerName;\n                        \n            RouteAreaAttribute area = controllerDescriptor.GetAreaFrom();\n            string areaName = controllerDescriptor.GetAreaName(area);\n\n            RouteValueDictionary defaults = new RouteValueDictionary\n            {\n                { \"controller\", controllerName }\n            };\n\n            Type controllerType = controllerDescriptor.ControllerType;\n\n            RouteValueDictionary dataTokens = new RouteValueDictionary();\n            if (areaName != null)\n            {\n                dataTokens.Add(RouteDataTokenKeys.Area, areaName);\n                dataTokens.Add(RouteDataTokenKeys.UseNamespaceFallback, value: false);\n                if (controllerType != null)\n                {\n                    dataTokens.Add(RouteDataTokenKeys.Namespaces, new[] { controllerType.Namespace });\n                }\n            }\n\n            RouteValueDictionary constraints = new RouteValueDictionary();\n            string detokenizedRouteTemplate = InlineRouteTemplateParser.ParseRouteTemplate(routeTemplate, defaults, constraints, ConstraintResolver);\n\n            Route route = new Route(detokenizedRouteTemplate, new MvcRouteHandler())\n            {\n                Defaults = defaults,\n                Constraints = constraints,\n                DataTokens = dataTokens\n            };\n\n            return route;\n        }\n\n        /// <summary>\n        /// Builds an <see cref=\"Route\"/> for a particular action.\n        /// </summary>\n        /// <param name=\"routeTemplate\">The tokenized route template for the route.</param>\n        /// <param name=\"allowedMethods\">The HTTP methods supported by the route. A null value specify that all possible methods are supported.</param>\n        /// <param name=\"controllerName\">The name of the associated controller.</param>\n        /// <param name=\"actionName\">The name of the associated action.</param>\n        /// <param name=\"targetMethod\">The method that the route attribute has been applied on.</param>\n        /// <param name=\"areaName\"></param>\n        /// <returns>The generated <see cref=\"Route\"/>.</returns>\n        public Route BuildDirectRoute(string routeTemplate, IEnumerable<string> allowedMethods, string controllerName, string actionName, MethodInfo targetMethod, string areaName)\n        {\n            if (routeTemplate == null)\n            {\n                throw Error.ArgumentNull(\"routeTemplate\");\n            }\n\n            if (controllerName == null)\n            {\n                throw Error.ArgumentNull(\"controllerName\");\n            }\n\n            if (actionName == null)\n            {\n                throw Error.ArgumentNull(\"actionName\");\n            }\n\n            RouteValueDictionary defaults = new RouteValueDictionary\n            {\n                { \"controller\", controllerName },\n                { \"action\", actionName }\n            };\n\n            RouteValueDictionary constraints = new RouteValueDictionary();\n            if (allowedMethods != null)\n            {\n                string[] array = allowedMethods.ToArray();\n                if (array.Length > 0)\n                {\n                    // Current method constraint implementation is inefficient since it matches before running the constraint.\n                    // Consider checking the HTTP method first in a custom route as a performance optimization.\n                    constraints.Add(\"httpMethod\", new HttpMethodConstraint(array));\n                }\n            }\n\n            RouteValueDictionary dataTokens = new RouteValueDictionary();\n            if (areaName != null)\n            {\n                dataTokens.Add(RouteDataTokenKeys.Area, areaName);\n                dataTokens.Add(RouteDataTokenKeys.UseNamespaceFallback, value: false);\n                if (targetMethod.DeclaringType != null)\n                {\n                    dataTokens.Add(RouteDataTokenKeys.Namespaces, new[] { targetMethod.DeclaringType.Namespace });\n                }\n            }\n\n            string detokenizedRouteTemplate = InlineRouteTemplateParser.ParseRouteTemplate(routeTemplate, defaults, constraints, ConstraintResolver);\n\n            return BuildDirectRoute(defaults, constraints, dataTokens, detokenizedRouteTemplate, targetMethod);\n        }\n\n        /// <summary>\n        /// Builds an <see cref=\"Route\"/>.\n        /// </summary>\n        /// <param name=\"defaults\">The route defaults.</param>\n        /// <param name=\"constraints\">The route constraints.</param>\n        /// <param name=\"dataTokens\"></param>\n        /// <param name=\"routeTemplate\">The detokenized route template.</param>\n        /// <param name=\"targetMethod\">The method that the route attribute has been applied on.</param>\n        /// <returns>The generated <see cref=\"Route\"/>.</returns>\n        public virtual Route BuildDirectRoute(RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens, string routeTemplate, MethodInfo targetMethod)\n        {\n            Route route = new Route(routeTemplate, new MvcRouteHandler())\n            {\n                Defaults = defaults,\n                Constraints = constraints,\n                DataTokens = dataTokens\n            };\n\n            return route;\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Mvc/Routing/RouteCollectionAttributeRoutingExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc.Routing;\nusing System.Web.Routing;\n\nnamespace System.Web.Mvc\n{\n    // Corresponds to the Web API implementation of attribute routing in System.Web.Http.HttpConfigurationExtensions.\n    public static class RouteCollectionAttributeRoutingExtensions\n    {\n        /// <summary>\n        /// Maps the attribute-defined routes for the application.\n        /// </summary>\n        /// <param name=\"routes\"></param>\n        public static void MapMvcAttributeRoutes(this RouteCollection routes)\n        {\n            if (routes == null)\n            {\n                throw new ArgumentNullException(\"routes\");\n            }\n\n            AttributeRoutingMapper.MapAttributeRoutes(routes, new DefaultInlineConstraintResolver());\n        }\n\n        /// <summary>\n        /// Maps the attribute-defined routes for the application.\n        /// </summary>\n        /// <param name=\"routes\"></param>\n        /// <param name=\"constraintResolver\">\n        /// The <see cref=\"IInlineConstraintResolver\"/> to use for resolving inline constraints in route templates.\n        /// </param>\n        public static void MapMvcAttributeRoutes(this RouteCollection routes,\n            IInlineConstraintResolver constraintResolver)\n        {\n            if (routes == null)\n            {\n                throw new ArgumentNullException(\"routes\");\n            }\n\n            if (constraintResolver == null)\n            {\n                throw new ArgumentNullException(\"constraintResolver\");\n            }\n\n            AttributeRoutingMapper.MapAttributeRoutes(routes, constraintResolver);\n        }\n\n        /// <summary>\n        /// Maps the attribute-defined routes for the application.\n        /// </summary>\n        /// <param name=\"routes\"></param>\n        /// <param name=\"directRouteProvider\">\n        /// The <see cref=\"IDirectRouteProvider\"/> to use for mapping routes.\n        /// </param>\n        public static void MapMvcAttributeRoutes(\n            this RouteCollection routes,\n            IDirectRouteProvider directRouteProvider)\n        {\n            if (routes == null)\n            {\n                throw new ArgumentNullException(\"routes\");\n            }\n\n            if (directRouteProvider == null)\n            {\n                throw new ArgumentNullException(\"directRouteProvider\");\n            }\n\n            AttributeRoutingMapper.MapAttributeRoutes(routes, new DefaultInlineConstraintResolver(), directRouteProvider);\n        }\n\n        /// <summary>\n        /// Maps the attribute-defined routes for the application.\n        /// </summary>\n        /// <param name=\"routes\"></param>\n        /// <param name=\"constraintResolver\">\n        /// The <see cref=\"IInlineConstraintResolver\"/> to use for resolving inline constraints in route templates.\n        /// </param>\n        /// <param name=\"directRouteProvider\">\n        /// The <see cref=\"IDirectRouteProvider\"/> to use for mapping routes.\n        /// </param>\n        public static void MapMvcAttributeRoutes(\n            this RouteCollection routes,\n            IInlineConstraintResolver constraintResolver,\n            IDirectRouteProvider directRouteProvider)\n        {\n            if (routes == null)\n            {\n                throw new ArgumentNullException(\"routes\");\n            }\n\n            if (constraintResolver == null)\n            {\n                throw new ArgumentNullException(\"constraintResolver\");\n            }\n\n            if (directRouteProvider == null)\n            {\n                throw new ArgumentNullException(\"directRouteProvider\");\n            }\n\n            AttributeRoutingMapper.MapAttributeRoutes(routes, constraintResolver, directRouteProvider);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/Routing/RouteCollectionRoute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Web.Routing;\n\nnamespace System.Web.Mvc.Routing\n{\n    /// <summary>\n    /// A single route that is the composite of multiple \"sub routes\".  \n    /// </summary>\n    /// <remarks>\n    /// Corresponds to the Web API implementation of attribute routing in System.Web.Http.Routing.RouteCollectionRoute.\n    /// </remarks>\n    internal class RouteCollectionRoute : RouteBase, IReadOnlyCollection<RouteBase>\n    {\n        private readonly IReadOnlyCollection<RouteBase> _subRoutes;\n\n        public RouteCollectionRoute(IReadOnlyCollection<RouteBase> subRoutes)\n        {\n            if (subRoutes == null)\n            {\n                throw new ArgumentNullException(\"subRoutes\");\n            }\n\n            _subRoutes = subRoutes;\n        }\n\n        public override RouteData GetRouteData(HttpContextBase httpContext)\n        {\n            List<RouteData> matches = new List<RouteData>();\n            foreach (RouteBase route in _subRoutes)\n            {\n                var match = route.GetRouteData(httpContext);\n                if (match != null)\n                {\n                    matches.Add(match);\n                }\n            }\n\n            return CreateDirectRouteMatch(this, matches);\n        }\n\n        public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)\n        {\n            // Link generation is not supported via the RouteCollectionRoute - see LinkGenerationRoute.\n            return null;\n        }\n\n        public int Count\n        {\n            get { return _subRoutes.Count; }\n        }\n\n        public IEnumerator<RouteBase> GetEnumerator()\n        {\n            return _subRoutes.GetEnumerator();\n        }\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return _subRoutes.GetEnumerator();\n        }\n\n        public static RouteData CreateDirectRouteMatch(RouteBase route, List<RouteData> matches)\n        {\n            if (matches.Count == 0)\n            {\n                return null;\n            }\n            else\n            {\n                var routeData = new RouteData();\n                routeData.Route = route;\n                routeData.RouteHandler = new MvcRouteHandler();\n                routeData.SetDirectRouteMatches(matches);\n\n                // At a few points in the code (MvcRouteHandler, MvcHandler) we need to look up the controller\n                // by name. For the purposes of error handling/debugging, it's helpful if we can have a name\n                // in this code to pass through.\n                //\n                // Inside the DefaultControllerFactory we'll double check the route data and throw if we have\n                // multiple controller matches, but for now let's just use the controller of the first match.\n                ControllerDescriptor controllerDescriptor = matches[0].GetTargetControllerDescriptor();\n                if (controllerDescriptor != null)\n                {\n                    routeData.Values[RouteDataTokenKeys.Controller] = controllerDescriptor.ControllerName;\n                }\n\n                return routeData;\n            }\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.Mvc/Routing/RouteDataTokenKeys.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc.Routing\n{\n    internal class RouteDataTokenKeys\n    {\n        public const string UseNamespaceFallback = \"UseNamespaceFallback\";\n        public const string Namespaces = \"Namespaces\";\n        public const string Area = \"area\";\n        public const string Controller = \"controller\";\n\n        // Used to provide the action descriptors to consider for attribute routing\n        public const string Actions = \"MS_DirectRouteActions\";\n\n        // Used to allow customer-provided disambiguation between multiple matching attribute routes\n        public const string Order = \"MS_DirectRouteOrder\";\n\n        // Used to prioritize routes to actions for link generation\n        public const string TargetIsAction = \"MS_DirectRouteTargetIsAction\";\n\n        // Used to allow URI constraint-based disambiguation between multiple matching attribute routes\n        public const string Precedence = \"MS_DirectRoutePrecedence\";\n\n        public const string DirectRouteMatches = \"MS_DirectRouteMatches\";\n    }\n}"
  },
  {
    "path": "src/System.Web.Mvc/SelectList.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.Mvc\n{\n    [SuppressMessage(\"Microsoft.Naming\", \"CA1710:IdentifiersShouldHaveCorrectSuffix\", Justification = \"This is a shipped API\")]\n    public class SelectList : MultiSelectList\n    {\n        public SelectList(IEnumerable items)\n            : this(items, selectedValue: null)\n        {\n        }\n\n        public SelectList(IEnumerable items, object selectedValue)\n            : this(items, dataValueField: null, dataTextField: null, selectedValue: selectedValue)\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the SelectList class by using the specified items for the list,\n        /// the selected value, and the disabled values.\n        /// </summary>\n        /// <param name=\"items\">The items used to build each <see cref=\"SelectListItem\"/> of the list.</param>\n        /// <param name=\"selectedValue\">The selected value. Used to match the Selected property of the corresponding\n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"disabledValues\">The disabled values. Used to match the Disabled property of the corresponding\n        /// <see cref=\"SelectListItem\"/>.</param>\n        public SelectList(IEnumerable items, object selectedValue, IEnumerable disabledValues)\n            : this(items,\n                   dataValueField: null,\n                   dataTextField: null,\n                   selectedValue: selectedValue,\n                   disabledValues: disabledValues)\n        {\n        }\n\n        public SelectList(IEnumerable items, string dataValueField, string dataTextField)\n            : this(items, dataValueField, dataTextField, selectedValue: null)\n        {\n        }\n\n        public SelectList(IEnumerable items, string dataValueField, string dataTextField, object selectedValue)\n            : base(items, dataValueField, dataTextField, ToEnumerable(selectedValue))\n        {\n            SelectedValue = selectedValue;\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the SelectList class by using the specified items for the list,\n        /// the data value field, the data text field, the data group field, and the selected value.\n        /// </summary>\n        /// <param name=\"items\">The items used to build each <see cref=\"SelectListItem\"/> of the list.</param>\n        /// <param name=\"dataValueField\">The data value field. Used to match the Value property of the corresponding\n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"dataTextField\">The data text field. Used to match the Text property of the corresponding\n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"dataGroupField\">The data group field. Used to match the Group property of the corresponding\n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"selectedValue\">The selected value. Used to match the Selected property of the corresponding\n        /// <see cref=\"SelectListItem\"/>.</param>\n        public SelectList(IEnumerable items,\n                          string dataValueField,\n                          string dataTextField,\n                          string dataGroupField,\n                          object selectedValue)\n            : base(items, dataValueField, dataTextField, dataGroupField, ToEnumerable(selectedValue))\n        {\n            SelectedValue = selectedValue;\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the SelectList class by using the specified items for the list,\n        /// the data value field, the data text field, the selected value, and the disabled values.\n        /// </summary>\n        /// <param name=\"items\">The items used to build each <see cref=\"SelectListItem\"/> of the list.</param>\n        /// <param name=\"dataValueField\">The data value field. Used to match the Value property of the corresponding\n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"dataTextField\">The data text field. Used to match the Text property of the corresponding\n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"selectedValue\">The selected value. Used to match the Selected property of the corresponding\n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"disabledValues\">The disabled values. Used to match the Disabled property of the corresponding\n        /// <see cref=\"SelectListItem\"/>.</param>\n        public SelectList(IEnumerable items,\n                          string dataValueField,\n                          string dataTextField,\n                          object selectedValue,\n                          IEnumerable disabledValues)\n            : base(items, dataValueField, dataTextField, ToEnumerable(selectedValue), disabledValues)\n        {\n            SelectedValue = selectedValue;\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the SelectList class by using the specified items for the list,\n        /// the data value field, the data text field, the data group field, the selected value, and the disabled\n        /// values.\n        /// </summary>\n        /// <param name=\"items\">The items used to build each <see cref=\"SelectListItem\"/> of the list.</param>\n        /// <param name=\"dataValueField\">The data value field. Used to match the Value property of the corresponding\n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"dataTextField\">The data text field. Used to match the Text property of the corresponding\n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"dataGroupField\">The data group field. Used to match the Group property of the corresponding\n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"selectedValue\">The selected value. Used to match the Selected property of the corresponding\n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"disabledValues\">The disabled values. Used to match the Disabled property of the corresponding\n        /// <see cref=\"SelectListItem\"/>.</param>\n        public SelectList(IEnumerable items,\n                          string dataValueField,\n                          string dataTextField,\n                          string dataGroupField,\n                          object selectedValue,\n                          IEnumerable disabledValues)\n            : base(items, dataValueField, dataTextField, dataGroupField, ToEnumerable(selectedValue), disabledValues)\n        {\n            SelectedValue = selectedValue;\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the SelectList class by using the specified items for the list,\n        /// the data value field, the data text field, the data group field. the selected value, the disabled values,\n        /// and the disabled groups.\n        /// </summary>\n        /// <param name=\"items\">The items used to build each <see cref=\"SelectListItem\"/> of the list.</param>\n        /// <param name=\"dataValueField\">The data value field. Used to match the Value property of the corresponding\n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"dataTextField\">The data text field. Used to match the Text property of the corresponding\n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"dataGroupField\">The data group field. Used to match the Group property of the corresponding\n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"selectedValue\">The selected value. Used to match the Selected property of the corresponding\n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"disabledValues\">The disabled values. Used to match the Disabled property of the corresponding\n        /// <see cref=\"SelectListItem\"/>.</param>\n        /// <param name=\"disabledGroups\">The disabled groups. Used to match the Disabled property of the corresponding\n        /// <see cref=\"SelectListGroup\"/>.</param>\n        public SelectList(IEnumerable items,\n                          string dataValueField,\n                          string dataTextField,\n                          string dataGroupField,\n                          object selectedValue,\n                          IEnumerable disabledValues,\n                          IEnumerable disabledGroups)\n            : base(items,\n                   dataValueField,\n                   dataTextField,\n                   dataGroupField,\n                   ToEnumerable(selectedValue),\n                   disabledValues,\n                   disabledGroups)\n        {\n            SelectedValue = selectedValue;\n        }\n\n        public object SelectedValue { get; private set; }\n\n        private static IEnumerable ToEnumerable(object selectedValue)\n        {\n            return (selectedValue != null) ? new object[] { selectedValue } : null;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/SelectListGroup.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    /// <summary>\n    /// Represents the optgroup HTML element and its attributes.\n    /// In a select list, multiple groups with the same name are supported.\n    /// They are compared with reference equality.\n    /// </summary>\n    public class SelectListGroup\n    {\n        /// <summary>\n        /// Gets or sets a value that indicates whether this <see cref=\"SelectListGroup\"/> is disabled. \n        /// </summary>\n        public bool Disabled { get; set; }\n\n        /// <summary>\n        /// Represents the value of the optgroup's label.\n        /// </summary>\n        public string Name { get; set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/SelectListItem.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public class SelectListItem\n    {\n        /// <summary>\n        /// Gets or sets a value that indicates whether this <see cref=\"SelectListItem\"/> is disabled.\n        /// </summary>\n        public bool Disabled { get; set; }\n\n        /// <summary>\n        /// Represents the optgroup HTML element this item is wrapped into.\n        /// In a select list, multiple groups with the same name are supported.\n        /// They are compared with reference equality.\n        /// </summary>\n        public SelectListGroup Group { get; set; }\n\n        public bool Selected { get; set; }\n\n        public string Text { get; set; }\n\n        public string Value { get; set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/SessionStateAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.SessionState;\n\nnamespace System.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]\n    public sealed class SessionStateAttribute : Attribute\n    {\n        public SessionStateAttribute(SessionStateBehavior behavior)\n        {\n            Behavior = behavior;\n        }\n\n        public SessionStateBehavior Behavior { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/SessionStateTempDataProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    public class SessionStateTempDataProvider : ITempDataProvider\n    {\n        internal const string TempDataSessionStateKey = \"__ControllerTempData\";\n\n        public virtual IDictionary<string, object> LoadTempData(ControllerContext controllerContext)\n        {\n            HttpSessionStateBase session = controllerContext.HttpContext.Session;\n\n            if (session != null)\n            {\n                Dictionary<string, object> tempDataDictionary = session[TempDataSessionStateKey] as Dictionary<string, object>;\n\n                if (tempDataDictionary != null)\n                {\n                    // If we got it from Session, remove it so that no other request gets it\n                    session.Remove(TempDataSessionStateKey);\n                    return tempDataDictionary;\n                }\n            }\n\n            return new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);\n        }\n\n        public virtual void SaveTempData(ControllerContext controllerContext, IDictionary<string, object> values)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n\n            HttpSessionStateBase session = controllerContext.HttpContext.Session;\n            bool isDirty = (values != null && values.Count > 0);\n\n            if (session == null)\n            {\n                if (isDirty)\n                {\n                    throw new InvalidOperationException(MvcResources.SessionStateTempDataProvider_SessionStateDisabled);\n                }\n            }\n            else\n            {\n                if (isDirty)\n                {\n                    session[TempDataSessionStateKey] = values;\n                }\n                else\n                {\n                    // Since the default implementation of Remove() (from SessionStateItemCollection) dirties the\n                    // collection, we shouldn't call it unless we really do need to remove the existing key.\n                    if (session[TempDataSessionStateKey] != null)\n                    {\n                        session.Remove(TempDataSessionStateKey);\n                    }\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/SingleServiceResolver.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    internal class SingleServiceResolver<TService> : IResolver<TService>\n        where TService : class\n    {\n        private Lazy<TService> _currentValueFromResolver;\n        private Func<TService> _currentValueThunk;\n        private TService _defaultValue;\n        private Func<IDependencyResolver> _resolverThunk;\n        private string _callerMethodName;\n\n        public SingleServiceResolver(Func<TService> currentValueThunk, TService defaultValue, string callerMethodName)\n        {\n            if (currentValueThunk == null)\n            {\n                throw new ArgumentNullException(\"currentValueThunk\");\n            }\n            if (defaultValue == null)\n            {\n                throw new ArgumentNullException(\"defaultValue\");\n            }\n\n            _resolverThunk = () => DependencyResolver.Current;\n            _currentValueFromResolver = new Lazy<TService>(GetValueFromResolver);\n            _currentValueThunk = currentValueThunk;\n            _defaultValue = defaultValue;\n            _callerMethodName = callerMethodName;\n        }\n\n        internal SingleServiceResolver(Func<TService> staticAccessor, TService defaultValue, IDependencyResolver resolver, string callerMethodName)\n            : this(staticAccessor, defaultValue, callerMethodName)\n        {\n            if (resolver != null)\n            {\n                _resolverThunk = () => resolver;\n            }\n        }\n\n        public TService Current\n        {\n            get { return _currentValueFromResolver.Value ?? _currentValueThunk() ?? _defaultValue; }\n        }\n\n        private TService GetValueFromResolver()\n        {\n            TService result = _resolverThunk().GetService<TService>();\n\n            if (result != null && _currentValueThunk() != null)\n            {\n                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, MvcResources.SingleServiceResolver_CannotRegisterTwoInstances, typeof(TService).Name.ToString(), _callerMethodName));\n            }\n\n            return result;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/StringLengthAttributeAdapter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\n\nnamespace System.Web.Mvc\n{\n    public class StringLengthAttributeAdapter : DataAnnotationsModelValidator<StringLengthAttribute>\n    {\n        public StringLengthAttributeAdapter(ModelMetadata metadata, ControllerContext context, StringLengthAttribute attribute)\n            : base(metadata, context, attribute)\n        {\n        }\n\n        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()\n        {\n            return new[] { new ModelClientValidationStringLengthRule(ErrorMessage, Attribute.MinimumLength, Attribute.MaximumLength) };\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/System.Web.Mvc.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{3D3FFD8A-624D-4E9B-954B-E1C105507975}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>System.Web.Mvc</RootNamespace>\n    <AssemblyName>System.Web.Mvc</AssemblyName>\n    <DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>\n    <RunCodeAnalysis>$(CodeAnalysis)</RunCodeAnalysis>\n    <CodeAnalysisRuleSet>..\\Strict.ruleset</CodeAnalysisRuleSet>\n    <DefineConstants>$(DefineConstants);ASPNETMVC</DefineConstants>\n    <NoWarn>1591</NoWarn>\n    <BaseAddress>1609891840</BaseAddress>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL\">\n      <Private>True</Private>\n      <HintPath>..\\..\\packages\\Microsoft.Web.Infrastructure.1.0.0.0\\lib\\net40\\Microsoft.Web.Infrastructure.dll</HintPath>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.ComponentModel.DataAnnotations\" />\n    <Reference Include=\"System.configuration\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Data.Entity\" />\n    <Reference Include=\"System.Data.Linq\" />\n    <Reference Include=\"System.Drawing\" />\n    <Reference Include=\"System.Runtime.Caching\" />\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"System.Data\" />\n    <Reference Include=\"System.Web.Abstractions\" />\n    <Reference Include=\"System.Web.Extensions\" />\n    <Reference Include=\"System.Web.Routing\" />\n    <Reference Include=\"System.Xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\CommonAssemblyInfo.cs\">\n      <Link>Properties\\CommonAssemblyInfo.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\AttributeList.cs\">\n      <Link>Common\\AttributeList.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\DictionaryExtensions.cs\">\n      <Link>Common\\DictionaryExtensions.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\ListWrapperCollection.cs\">\n      <Link>Common\\ListWrapperCollection.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\PrefixContainer.cs\">\n      <Link>Common\\PrefixContainer.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\DirectRouteBuilder.cs\">\n      <Link>Routing\\DirectRouteBuilder.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\DirectRouteFactoryContext.cs\">\n      <Link>Routing\\DirectRouteFactoryContext.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\IDirectRouteBuilder.cs\">\n      <Link>Routing\\IDirectRouteBuilder.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\IDirectRouteFactory.cs\">\n      <Link>Routing\\IDirectRouteFactory.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\IInlineConstraintResolver.cs\">\n      <Link>Routing\\IInlineConstraintResolver.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\RouteEntry.cs\">\n      <Link>Routing\\RouteEntry.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\RouteFactoryAttribute.cs\">\n      <Link>Routing\\RouteFactoryAttribute.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\RouteInfoDirectRouteFactory.cs\">\n      <Link>Routing\\RouteInfoDirectRouteFactory.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\RouteParser.cs\">\n      <Link>Routing\\RouteParser.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\RoutePrecedence.cs\">\n      <Link>Routing\\RoutePrecedence.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\TaskHelpers.cs\">\n      <Link>Common\\TaskHelpers.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\TaskHelpersExtensions.cs\">\n      <Link>Common\\TaskHelpersExtensions.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\AlphaRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\AlphaRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\BoolRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\BoolRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\CompoundRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\CompoundRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\DateTimeRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\DateTimeRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\DecimalRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\DecimalRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\DoubleRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\DoubleRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\FloatRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\FloatRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\GuidRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\GuidRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\IntRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\IntRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\LengthRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\LengthRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\LongRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\LongRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\MaxLengthRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\MaxLengthRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\MaxRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\MaxRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\MinLengthRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\MinLengthRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\MinRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\MinRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\RangeRouteConstraintBase.cs\">\n      <Link>Routing\\Constraints\\RangeRouteConstraintBase.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\RegexRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\RegexRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\Constraints\\OptionalRouteConstraint.cs\">\n      <Link>Routing\\Constraints\\OptionalRouteConstraint.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\DefaultInlineConstraintResolver.cs\">\n      <Link>Routing\\DefaultInlineConstraintResolver.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\InlineRouteTemplateParser.cs\">\n      <Link>Routing\\InlineRouteTemplateParser.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\SubRouteCollection.cs\">\n      <Link>Routing\\SubRouteCollection.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\IRoutePrefix.cs\">\n      <Link>Routing\\IRoutePrefix.cs</Link>\n    </Compile>\n    <Compile Include=\"ActionMethodSelectorBase.cs\" />\n    <Compile Include=\"ActionNameSelector.cs\" />\n    <Compile Include=\"AreaReference.cs\" />\n    <Compile Include=\"ControllerDescriptorExtensions.cs\" />\n    <Compile Include=\"Async\\IAsyncActionInvokerFactory.cs\" />\n    <Compile Include=\"CopyOnWriteDictionary.cs\" />\n    <Compile Include=\"IActionInvokerFactory.cs\" />\n    <Compile Include=\"IMethodInfoActionDescriptor.cs\" />\n    <Compile Include=\"ITempDataProviderFactory.cs\" />\n    <Compile Include=\"JQueryFormValueProvider.cs\" />\n    <Compile Include=\"JQueryFormValueProviderFactory.cs\" />\n    <Compile Include=\"Routing\\DefaultDirectRouteProvider.cs\" />\n    <Compile Include=\"Routing\\IDirectRouteProvider.cs\" />\n    <Compile Include=\"SelectListGroup.cs\" />\n    <Compile Include=\"Html\\EnumHelper.cs\" />\n    <Compile Include=\"MaxLengthAttributeAdapter.cs\" />\n    <Compile Include=\"MinLengthAttributeAdapter.cs\" />\n    <Compile Include=\"Properties\\MvcResources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>MvcResources.resx</DependentUpon>\n    </Compile>\n    <Compile Include=\"Routing\\ConstraintValidation.cs\" />\n    <Compile Include=\"Routing\\DirectRouteCandidate.cs\" />\n    <Compile Include=\"Routing\\LinkGenerationRoute.cs\" />\n    <Compile Include=\"Routing\\RouteCollectionRoute.cs\" />\n    <Compile Include=\"Routing\\ParsedRoute.cs\" />\n    <Compile Include=\"..\\Common\\Routing\\PathContentSegment.cs\">\n      <Link>Routing\\PathContentSegment.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\PathLiteralSubsegment.cs\">\n      <Link>Routing\\PathLiteralSubsegment.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\PathParameterSubsegment.cs\">\n      <Link>Routing\\PathParameterSubsegment.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\PathSegment.cs\">\n      <Link>Routing\\PathSegment.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\PathSeparatorSegment.cs\">\n      <Link>Routing\\PathSeparatorSegment.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\PathSubsegment.cs\">\n      <Link>Routing\\PathSubsegment.cs</Link>\n    </Compile>\n    <Compile Include=\"AdditionalMetaDataAttribute.cs\" />\n    <Compile Include=\"AllowAnonymousAttribute.cs\" />\n    <Compile Include=\"ActionDescriptorHelper.cs\" />\n    <Compile Include=\"Async\\BeginInvokeDelegateOfTState.cs\" />\n    <Compile Include=\"Async\\TaskAsyncActionDescriptor.cs\" />\n    <Compile Include=\"Async\\TaskWrapperAsyncResult.cs\" />\n    <Compile Include=\"Filters\\AuthenticationChallengeContext.cs\" />\n    <Compile Include=\"Filters\\AuthenticationContext.cs\" />\n    <Compile Include=\"BuildManagerCompiledView.cs\" />\n    <Compile Include=\"BuildManagerViewEngine.cs\" />\n    <Compile Include=\"CachedAssociatedMetadataProvider.cs\" />\n    <Compile Include=\"CachedDataAnnotationsMetadataAttributes.cs\" />\n    <Compile Include=\"CachedDataAnnotationsModelMetadata.cs\" />\n    <Compile Include=\"CachedDataAnnotationsModelMetadataProvider.cs\" />\n    <Compile Include=\"CachedModelMetadata.cs\" />\n    <Compile Include=\"CancellationTokenModelBinder.cs\" />\n    <Compile Include=\"CompareAttributeAdapter.cs\" />\n    <Compile Include=\"DataTypeAttributeAdapter.cs\" />\n    <Compile Include=\"Async\\EndInvokeDelegateOfTResultTState.cs\" />\n    <Compile Include=\"Async\\EndInvokeVoidDelegate.cs\" />\n    <Compile Include=\"FileExtensionsAttributeAdapter.cs\" />\n    <Compile Include=\"Filters\\IAuthenticationFilter.cs\" />\n    <Compile Include=\"Filters\\IOverrideFilter.cs\" />\n    <Compile Include=\"Html5DateRenderingMode.cs\" />\n    <Compile Include=\"RouteAttribute.cs\" />\n    <Compile Include=\"MembershipPasswordAttributeAdapter.cs\" />\n    <Compile Include=\"CompareAttribute.cs\" />\n    <Compile Include=\"ChildActionValueProvider.cs\" />\n    <Compile Include=\"ChildActionValueProviderFactory.cs\" />\n    <Compile Include=\"HttpHeadAttribute.cs\" />\n    <Compile Include=\"HttpOptionsAttribute.cs\" />\n    <Compile Include=\"HttpPatchAttribute.cs\" />\n    <Compile Include=\"IEnumerableValueProvider.cs\" />\n    <Compile Include=\"DataTypeUtil.cs\" />\n    <Compile Include=\"Html\\DisplayNameExtensions.cs\" />\n    <Compile Include=\"Html\\NameExtensions.cs\" />\n    <Compile Include=\"Html\\ValueExtensions.cs\" />\n    <Compile Include=\"OverrideActionFiltersAttribute.cs\" />\n    <Compile Include=\"OverrideAuthenticationAttribute.cs\" />\n    <Compile Include=\"OverrideAuthorizationAttribute.cs\" />\n    <Compile Include=\"OverrideExceptionFiltersAttribute.cs\" />\n    <Compile Include=\"OverrideResultFiltersAttribute.cs\" />\n    <Compile Include=\"Razor\\MvcCSharpRazorCodeGenerator.cs\" />\n    <Compile Include=\"Razor\\SetModelTypeCodeGenerator.cs\" />\n    <Compile Include=\"ReflectedAttributeCache.cs\" />\n    <Compile Include=\"RouteAreaAttribute.cs\" />\n    <Compile Include=\"Routing\\AttributeRoutingMapper.cs\" />\n    <Compile Include=\"Routing\\DirectRouteExtensions.cs\" />\n    <Compile Include=\"Routing\\IRouteInfoProvider.cs\" />\n    <Compile Include=\"Routing\\RouteBuilder.cs\" />\n    <Compile Include=\"Routing\\RouteCollectionAttributeRoutingExtensions.cs\" />\n    <Compile Include=\"RoutePrefixAttribute.cs\" />\n    <Compile Include=\"Routing\\RouteDataTokenKeys.cs\" />\n    <Compile Include=\"SessionStateAttribute.cs\" />\n    <Compile Include=\"AllowHtmlAttribute.cs\" />\n    <Compile Include=\"UnvalidatedRequestValuesAccessor.cs\" />\n    <Compile Include=\"UnvalidatedRequestValuesWrapper.cs\" />\n    <Compile Include=\"IUnvalidatedRequestValues.cs\" />\n    <Compile Include=\"IUnvalidatedValueProvider.cs\" />\n    <Compile Include=\"DependencyResolverExtensions.cs\" />\n    <Compile Include=\"ExpressionUtil\\BinaryExpressionFingerprint.cs\" />\n    <Compile Include=\"ExpressionUtil\\CachedExpressionCompiler.cs\" />\n    <Compile Include=\"ExpressionUtil\\ConditionalExpressionFingerprint.cs\" />\n    <Compile Include=\"ExpressionUtil\\ConstantExpressionFingerprint.cs\" />\n    <Compile Include=\"ExpressionUtil\\DefaultExpressionFingerprint.cs\" />\n    <Compile Include=\"ExpressionUtil\\ExpressionFingerprint.cs\" />\n    <Compile Include=\"ExpressionUtil\\ExpressionFingerprintChain.cs\" />\n    <Compile Include=\"ExpressionUtil\\FingerprintingExpressionVisitor.cs\" />\n    <Compile Include=\"ExpressionUtil\\HashCodeCombiner.cs\" />\n    <Compile Include=\"ExpressionUtil\\Hoisted.cs\" />\n    <Compile Include=\"ExpressionUtil\\HoistingExpressionVisitor.cs\" />\n    <Compile Include=\"ExpressionUtil\\IndexExpressionFingerprint.cs\" />\n    <Compile Include=\"ExpressionUtil\\LambdaExpressionFingerprint.cs\" />\n    <Compile Include=\"ExpressionUtil\\MemberExpressionFingerprint.cs\" />\n    <Compile Include=\"ExpressionUtil\\MethodCallExpressionFingerprint.cs\" />\n    <Compile Include=\"ExpressionUtil\\ParameterExpressionFingerprint.cs\" />\n    <Compile Include=\"ExpressionUtil\\TypeBinaryExpressionFingerprint.cs\" />\n    <Compile Include=\"ExpressionUtil\\UnaryExpressionFingerprint.cs\" />\n    <Compile Include=\"IControllerActivator.cs\" />\n    <Compile Include=\"IModelBinderProvider.cs\" />\n    <Compile Include=\"IUniquelyIdentifiable.cs\" />\n    <Compile Include=\"IViewStartPageChild.cs\" />\n    <Compile Include=\"IResolver.cs\" />\n    <Compile Include=\"ControllerInstanceFilterProvider.cs\" />\n    <Compile Include=\"RazorView.cs\" />\n    <Compile Include=\"RazorViewEngine.cs\" />\n    <Compile Include=\"DynamicViewDataDictionary.cs\" />\n    <Compile Include=\"Filter.cs\" />\n    <Compile Include=\"FilterAttributeFilterProvider.cs\" />\n    <Compile Include=\"FilterProviderCollection.cs\" />\n    <Compile Include=\"FilterProviders.cs\" />\n    <Compile Include=\"FilterScope.cs\" />\n    <Compile Include=\"GlobalFilterCollection.cs\" />\n    <Compile Include=\"GlobalFilters.cs\" />\n    <Compile Include=\"IFilterProvider.cs\" />\n    <Compile Include=\"IMvcFilter.cs\" />\n    <Compile Include=\"IViewPageActivator.cs\" />\n    <Compile Include=\"ModelBinderProviderCollection.cs\" />\n    <Compile Include=\"ModelBinderProviders.cs\" />\n    <Compile Include=\"MultiServiceResolver.cs\" />\n    <Compile Include=\"Razor\\MvcCSharpRazorCodeParser.cs\" />\n    <Compile Include=\"MvcFilter.cs\" />\n    <Compile Include=\"Razor\\MvcVBRazorCodeParser.cs\" />\n    <Compile Include=\"Razor\\MvcWebPageRazorHost.cs\" />\n    <Compile Include=\"MvcWebRazorHostFactory.cs\" />\n    <Compile Include=\"PreApplicationStartCode.cs\" />\n    <Compile Include=\"RemoteAttribute.cs\" />\n    <Compile Include=\"SingleServiceResolver.cs\" />\n    <Compile Include=\"Razor\\StartPageLookupDelegate.cs\" />\n    <Compile Include=\"TagBuilderExtensions.cs\" />\n    <Compile Include=\"ViewStartPage.cs\" />\n    <Compile Include=\"WebViewPage.cs\" />\n    <Compile Include=\"WebViewPageOfTModel.cs\" />\n    <Compile Include=\"HttpNotFoundResult.cs\" />\n    <Compile Include=\"HttpStatusCodeResult.cs\" />\n    <Compile Include=\"IMvcControlBuilder.cs\" />\n    <Compile Include=\"AssociatedMetadataProvider.cs\" />\n    <Compile Include=\"ActionExecutedContext.cs\" />\n    <Compile Include=\"ActionExecutingContext.cs\" />\n    <Compile Include=\"ClientDataTypeModelValidatorProvider.cs\" />\n    <Compile Include=\"AssociatedValidatorProvider.cs\" />\n    <Compile Include=\"Async\\ActionDescriptorCreator.cs\" />\n    <Compile Include=\"Async\\AsyncActionDescriptor.cs\" />\n    <Compile Include=\"Async\\AsyncActionMethodSelector.cs\" />\n    <Compile Include=\"Async\\AsyncControllerActionInvoker.cs\" />\n    <Compile Include=\"Async\\SynchronousOperationException.cs\" />\n    <Compile Include=\"Async\\AsyncManager.cs\" />\n    <Compile Include=\"AsyncTimeoutAttribute.cs\" />\n    <Compile Include=\"Async\\BeginInvokeDelegate.cs\" />\n    <Compile Include=\"Async\\AsyncResultWrapper.cs\" />\n    <Compile Include=\"Async\\AsyncVoid.cs\" />\n    <Compile Include=\"AsyncController.cs\" />\n    <Compile Include=\"Async\\IAsyncController.cs\" />\n    <Compile Include=\"Async\\IAsyncActionInvoker.cs\" />\n    <Compile Include=\"Async\\IAsyncManagerContainer.cs\" />\n    <Compile Include=\"IClientValidatable.cs\" />\n    <Compile Include=\"IMetadataAware.cs\" />\n    <Compile Include=\"IDependencyResolver.cs\" />\n    <Compile Include=\"JsonValueProviderFactory.cs\" />\n    <Compile Include=\"DependencyResolver.cs\" />\n    <Compile Include=\"UrlParameter.cs\" />\n    <Compile Include=\"FormValueProvider.cs\" />\n    <Compile Include=\"FormValueProviderFactory.cs\" />\n    <Compile Include=\"HttpFileCollectionValueProvider.cs\" />\n    <Compile Include=\"HttpFileCollectionValueProviderFactory.cs\" />\n    <Compile Include=\"QueryStringValueProvider.cs\" />\n    <Compile Include=\"QueryStringValueProviderFactory.cs\" />\n    <Compile Include=\"RangeAttributeAdapter.cs\" />\n    <Compile Include=\"RegularExpressionAttributeAdapter.cs\" />\n    <Compile Include=\"RequiredAttributeAdapter.cs\" />\n    <Compile Include=\"RouteDataValueProvider.cs\" />\n    <Compile Include=\"RouteDataValueProviderFactory.cs\" />\n    <Compile Include=\"StringLengthAttributeAdapter.cs\" />\n    <Compile Include=\"TypeCacheUtil.cs\" />\n    <Compile Include=\"TypeCacheSerializer.cs\" />\n    <Compile Include=\"Html\\DisplayTextExtensions.cs\" />\n    <Compile Include=\"NoAsyncTimeoutAttribute.cs\" />\n    <Compile Include=\"Async\\OperationCounter.cs\" />\n    <Compile Include=\"Async\\ReflectedAsyncActionDescriptor.cs\" />\n    <Compile Include=\"Async\\ReflectedAsyncControllerDescriptor.cs\" />\n    <Compile Include=\"Async\\Trigger.cs\" />\n    <Compile Include=\"Async\\TriggerListener.cs\" />\n    <Compile Include=\"Async\\SimpleAsyncResult.cs\" />\n    <Compile Include=\"Async\\EndInvokeDelegateOfTResult.cs\" />\n    <Compile Include=\"Async\\SynchronizationContextUtil.cs\" />\n    <Compile Include=\"AuthorizationContext.cs\" />\n    <Compile Include=\"ByteArrayModelBinder.cs\" />\n    <Compile Include=\"ControllerContext.cs\" />\n    <Compile Include=\"Html\\ChildActionExtensions.cs\" />\n    <Compile Include=\"ParameterInfoUtil.cs\" />\n    <Compile Include=\"HttpHandlerUtil.cs\" />\n    <Compile Include=\"ChildActionOnlyAttribute.cs\" />\n    <Compile Include=\"TypeDescriptorHelper.cs\" />\n    <Compile Include=\"ValidatableObjectAdapter.cs\" />\n    <Compile Include=\"ValueProviderFactories.cs\" />\n    <Compile Include=\"ValueProviderFactory.cs\" />\n    <Compile Include=\"ValueProviderFactoryCollection.cs\" />\n    <Compile Include=\"ValueProviderCollection.cs\" />\n    <Compile Include=\"DictionaryValueProvider.cs\" />\n    <Compile Include=\"NameValueCollectionValueProvider.cs\" />\n    <Compile Include=\"ValueProviderUtil.cs\" />\n    <Compile Include=\"IValueProvider.cs\" />\n    <Compile Include=\"DataErrorInfoModelValidatorProvider.cs\" />\n    <Compile Include=\"ModelValidatorProviderCollection.cs\" />\n    <Compile Include=\"DataAnnotationsModelMetadata.cs\" />\n    <Compile Include=\"HiddenInputAttribute.cs\" />\n    <Compile Include=\"HttpGetAttribute.cs\" />\n    <Compile Include=\"HttpPutAttribute.cs\" />\n    <Compile Include=\"HttpDeleteAttribute.cs\" />\n    <Compile Include=\"MvcHtmlString.cs\" />\n    <Compile Include=\"DataAnnotationsModelValidator.cs\" />\n    <Compile Include=\"DataAnnotationsModelValidatorProvider.cs\" />\n    <Compile Include=\"DataAnnotationsModelValidatorOfTAttribute.cs\" />\n    <Compile Include=\"EmptyModelValidatorProvider.cs\" />\n    <Compile Include=\"ExpressionHelper.cs\" />\n    <Compile Include=\"FieldValidationMetadata.cs\" />\n    <Compile Include=\"FormContext.cs\" />\n    <Compile Include=\"JsonRequestBehavior.cs\" />\n    <Compile Include=\"ModelValidationResult.cs\" />\n    <Compile Include=\"ModelValidator.cs\" />\n    <Compile Include=\"ModelValidatorProvider.cs\" />\n    <Compile Include=\"ModelValidatorProviders.cs\" />\n    <Compile Include=\"RequireHttpsAttribute.cs\" />\n    <Compile Include=\"HttpRequestExtensions.cs\" />\n    <Compile Include=\"DataAnnotationsModelMetadataProvider.cs\" />\n    <Compile Include=\"EmptyModelMetadataProvider.cs\" />\n    <Compile Include=\"ModelMetadata.cs\" />\n    <Compile Include=\"ModelMetadataProvider.cs\" />\n    <Compile Include=\"ModelMetadataProviders.cs\" />\n    <Compile Include=\"AreaHelpers.cs\" />\n    <Compile Include=\"AreaRegistration.cs\" />\n    <Compile Include=\"AreaRegistrationContext.cs\" />\n    <Compile Include=\"Error.cs\" />\n    <Compile Include=\"IRouteWithArea.cs\" />\n    <Compile Include=\"Async\\SingleEntryGate.cs\" />\n    <Compile Include=\"Html\\PartialExtensions.cs\" />\n    <Compile Include=\"LinqBinaryModelBinder.cs\" />\n    <Compile Include=\"TryGetValueDelegate.cs\" />\n    <Compile Include=\"ViewDataInfo.cs\" />\n    <Compile Include=\"Html\\DefaultDisplayTemplates.cs\" />\n    <Compile Include=\"Html\\DefaultEditorTemplates.cs\" />\n    <Compile Include=\"Html\\DisplayExtensions.cs\" />\n    <Compile Include=\"Html\\EditorExtensions.cs\" />\n    <Compile Include=\"Html\\LabelExtensions.cs\" />\n    <Compile Include=\"Html\\TemplateHelpers.cs\" />\n    <Compile Include=\"HttpPostAttribute.cs\" />\n    <Compile Include=\"ExceptionContext.cs\" />\n    <Compile Include=\"ResultExecutedContext.cs\" />\n    <Compile Include=\"ResultExecutingContext.cs\" />\n    <Compile Include=\"TemplateInfo.cs\" />\n    <Compile Include=\"ValidateAntiForgeryTokenAttribute.cs\" />\n    <Compile Include=\"JavaScriptResult.cs\" />\n    <Compile Include=\"ActionDescriptor.cs\" />\n    <Compile Include=\"ActionMethodDispatcher.cs\" />\n    <Compile Include=\"ActionMethodSelector.cs\" />\n    <Compile Include=\"ActionMethodSelectorAttribute.cs\" />\n    <Compile Include=\"ActionNameSelectorAttribute.cs\" />\n    <Compile Include=\"AuthorizeAttribute.cs\" />\n    <Compile Include=\"Ajax\\AjaxOptions.cs\" />\n    <Compile Include=\"Ajax\\AjaxExtensions.cs\" />\n    <Compile Include=\"ActionMethodDispatcherCache.cs\" />\n    <Compile Include=\"BindAttribute.cs\" />\n    <Compile Include=\"ControllerBase.cs\" />\n    <Compile Include=\"ActionNameAttribute.cs\" />\n    <Compile Include=\"AcceptVerbsAttribute.cs\" />\n    <Compile Include=\"AjaxHelperOfTModel.cs\" />\n    <Compile Include=\"HtmlHelperOfTModel.cs\" />\n    <Compile Include=\"DictionaryHelpers.cs\" />\n    <Compile Include=\"AjaxRequestExtensions.cs\" />\n    <Compile Include=\"ModelBinderDictionary.cs\" />\n    <Compile Include=\"ValueProviderDictionary.cs\" />\n    <Compile Include=\"ViewContext.cs\" />\n    <Compile Include=\"ViewMasterPageControlBuilder.cs\" />\n    <Compile Include=\"ViewTemplateUserControl.cs\">\n      <SubType>ASPXCodeBehind</SubType>\n    </Compile>\n    <Compile Include=\"ViewTemplateUserControlOfTModel.cs\">\n      <SubType>ASPXCodeBehind</SubType>\n    </Compile>\n    <Compile Include=\"ViewType.cs\" />\n    <Compile Include=\"ViewTypeControlBuilder.cs\" />\n    <Compile Include=\"ViewUserControlControlBuilder.cs\" />\n    <Compile Include=\"ViewPageControlBuilder.cs\" />\n    <Compile Include=\"ViewTypeParserFilter.cs\" />\n    <Compile Include=\"DefaultViewLocationCache.cs\" />\n    <Compile Include=\"FormCollection.cs\" />\n    <Compile Include=\"HttpPostedFileBaseModelBinder.cs\" />\n    <Compile Include=\"NullViewLocationCache.cs\" />\n    <Compile Include=\"ValidateInputAttribute.cs\" />\n    <Compile Include=\"FileContentResult.cs\" />\n    <Compile Include=\"FilePathResult.cs\" />\n    <Compile Include=\"FileResult.cs\" />\n    <Compile Include=\"FileStreamResult.cs\" />\n    <Compile Include=\"InputType.cs\" />\n    <Compile Include=\"ControllerDescriptorCache.cs\" />\n    <Compile Include=\"ReflectedParameterBindingInfo.cs\" />\n    <Compile Include=\"ParameterBindingInfo.cs\" />\n    <Compile Include=\"ReaderWriterCache.cs\" />\n    <Compile Include=\"DescriptorUtil.cs\" />\n    <Compile Include=\"ReflectedControllerDescriptor.cs\" />\n    <Compile Include=\"ControllerDescriptor.cs\" />\n    <Compile Include=\"ActionSelector.cs\" />\n    <Compile Include=\"ReflectedActionDescriptor.cs\" />\n    <Compile Include=\"Html\\MvcForm.cs\" />\n    <Compile Include=\"HttpVerbs.cs\" />\n    <Compile Include=\"DefaultModelBinder.cs\" />\n    <Compile Include=\"ModelBindingContext.cs\" />\n    <Compile Include=\"ParameterDescriptor.cs\" />\n    <Compile Include=\"RouteValuesHelpers.cs\" />\n    <Compile Include=\"SelectListItem.cs\" />\n    <Compile Include=\"ReflectedParameterDescriptor.cs\" />\n    <Compile Include=\"ValueProviderResult.cs\" />\n    <Compile Include=\"CustomModelBinderAttribute.cs\" />\n    <Compile Include=\"FormMethod.cs\" />\n    <Compile Include=\"Html\\FormExtensions.cs\" />\n    <Compile Include=\"Html\\InputExtensions.cs\" />\n    <Compile Include=\"Html\\RenderPartialExtensions.cs\" />\n    <Compile Include=\"Html\\SelectExtensions.cs\" />\n    <Compile Include=\"Html\\TextAreaExtensions.cs\" />\n    <Compile Include=\"Html\\ValidationExtensions.cs\" />\n    <Compile Include=\"IModelBinder.cs\" />\n    <Compile Include=\"Html\\LinkExtensions.cs\" />\n    <Compile Include=\"ModelBinderAttribute.cs\" />\n    <Compile Include=\"ModelBinders.cs\" />\n    <Compile Include=\"ModelStateDictionary.cs\" />\n    <Compile Include=\"ModelState.cs\" />\n    <Compile Include=\"ModelErrorCollection.cs\" />\n    <Compile Include=\"ModelError.cs\" />\n    <Compile Include=\"Ajax\\InsertionMode.cs\" />\n    <Compile Include=\"HandleErrorAttribute.cs\" />\n    <Compile Include=\"HandleErrorInfo.cs\" />\n    <Compile Include=\"HttpUnauthorizedResult.cs\" />\n    <Compile Include=\"IActionInvoker.cs\" />\n    <Compile Include=\"IView.cs\" />\n    <Compile Include=\"IViewLocationCache.cs\" />\n    <Compile Include=\"MvcHttpHandler.cs\" />\n    <Compile Include=\"PartialViewResult.cs\" />\n    <Compile Include=\"SessionStateTempDataProvider.cs\" />\n    <Compile Include=\"ITempDataProvider.cs\" />\n    <Compile Include=\"OutputCacheAttribute.cs\" />\n    <Compile Include=\"FilterInfo.cs\" />\n    <Compile Include=\"GlobalSuppressions.cs\" />\n    <Compile Include=\"ActionFilterAttribute.cs\" />\n    <Compile Include=\"ActionResult.cs\" />\n    <Compile Include=\"AjaxHelper.cs\" />\n    <Compile Include=\"BuildManagerWrapper.cs\" />\n    <Compile Include=\"Controller.cs\" />\n    <Compile Include=\"ControllerActionInvoker.cs\" />\n    <Compile Include=\"ControllerBuilder.cs\" />\n    <Compile Include=\"ControllerTypeCache.cs\" />\n    <Compile Include=\"ContentResult.cs\" />\n    <Compile Include=\"FilterAttribute.cs\" />\n    <Compile Include=\"IResultFilter.cs\" />\n    <Compile Include=\"IExceptionFilter.cs\" />\n    <Compile Include=\"IAuthorizationFilter.cs\" />\n    <Compile Include=\"JsonResult.cs\" />\n    <Compile Include=\"NameValueCollectionExtensions.cs\" />\n    <Compile Include=\"ViewDataDictionaryOfTModel.cs\" />\n    <Compile Include=\"EmptyResult.cs\" />\n    <Compile Include=\"MultiSelectList.cs\" />\n    <Compile Include=\"RedirectResult.cs\" />\n    <Compile Include=\"RedirectToRouteResult.cs\" />\n    <Compile Include=\"DefaultControllerFactory.cs\" />\n    <Compile Include=\"HtmlHelper.cs\" />\n    <Compile Include=\"IActionFilter.cs\" />\n    <Compile Include=\"IBuildManager.cs\" />\n    <Compile Include=\"IController.cs\" />\n    <Compile Include=\"IControllerFactory.cs\" />\n    <Compile Include=\"IViewDataContainer.cs\" />\n    <Compile Include=\"IViewEngine.cs\" />\n    <Compile Include=\"MvcHandler.cs\" />\n    <Compile Include=\"MvcRouteHandler.cs\" />\n    <Compile Include=\"NonActionAttribute.cs\" />\n    <Compile Include=\"RouteCollectionExtensions.cs\" />\n    <Compile Include=\"SelectList.cs\" />\n    <Compile Include=\"TempDataDictionary.cs\" />\n    <Compile Include=\"TypeHelpers.cs\" />\n    <Compile Include=\"UrlHelper.cs\" />\n    <Compile Include=\"ViewDataDictionary.cs\" />\n    <Compile Include=\"ViewEngineCollection.cs\" />\n    <Compile Include=\"ViewEngineResult.cs\" />\n    <Compile Include=\"ViewEngines.cs\" />\n    <Compile Include=\"ViewMasterPage.cs\">\n      <SubType>ASPXCodeBehind</SubType>\n    </Compile>\n    <Compile Include=\"ViewMasterPageOfTModel.cs\">\n      <SubType>ASPXCodeBehind</SubType>\n    </Compile>\n    <Compile Include=\"ViewPage.cs\">\n      <SubType>ASPXCodeBehind</SubType>\n    </Compile>\n    <Compile Include=\"ViewPageOfTModel.cs\">\n      <SubType>ASPXCodeBehind</SubType>\n    </Compile>\n    <Compile Include=\"ViewResult.cs\" />\n    <Compile Include=\"ViewResultBase.cs\" />\n    <Compile Include=\"ViewUserControl.cs\">\n      <SubType>ASPXCodeBehind</SubType>\n    </Compile>\n    <Compile Include=\"ViewUserControlOfTModel.cs\">\n      <SubType>ASPXCodeBehind</SubType>\n    </Compile>\n    <Compile Include=\"VirtualPathProviderViewEngine.cs\" />\n    <Compile Include=\"WebFormView.cs\" />\n    <Compile Include=\"WebFormViewEngine.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"Properties\\MvcResources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <SubType>Designer</SubType>\n      <LastGenOutput>MvcResources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n  </ItemGroup>\n  <ItemGroup>\n    <CodeAnalysisDictionary Include=\"..\\CodeAnalysisDictionary.xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\System.Web.Razor\\System.Web.Razor.csproj\">\n      <Project>{8F18041B-9410-4C36-A9C5-067813DF5F31}</Project>\n      <Name>System.Web.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.WebPages.Razor\\System.Web.WebPages.Razor.csproj\">\n      <Project>{0939B11A-FE4E-4BA1-8AD6-D97741EE314F}</Project>\n      <Name>System.Web.WebPages.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.WebPages\\System.Web.WebPages.csproj\">\n      <Project>{76EFA9C5-8D7E-4FDF-B710-E20F8B6B00D2}</Project>\n      <Name>System.Web.WebPages</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"JavaScript\\jquery.unobtrusive-ajax.js\" />\n    <None Include=\"JavaScript\\jquery.validate.unobtrusive.js\" />\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <ItemGroup />\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  <Target Name=\"AfterBuild\">\n    <ItemGroup>\n      <ScriptFiles Include=\"JavaScript\\*.js\" />\n    </ItemGroup>\n    <Copy SourceFiles=\"@(ScriptFiles)\" DestinationFolder=\"$(OutputPath)\" SkipUnchangedFiles=\"true\" />\n  </Target>\n</Project>"
  },
  {
    "path": "src/System.Web.Mvc/TagBuilderExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics;\n\nnamespace System.Web.Mvc\n{\n    internal static class TagBuilderExtensions\n    {\n        internal static MvcHtmlString ToMvcHtmlString(this TagBuilder tagBuilder, TagRenderMode renderMode)\n        {\n            Debug.Assert(tagBuilder != null);\n            return new MvcHtmlString(tagBuilder.ToString(renderMode));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/TempDataDictionary.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace System.Web.Mvc\n{\n    public class TempDataDictionary : IDictionary<string, object>\n    {\n        internal const string TempDataSerializationKey = \"__tempData\";\n\n        private Dictionary<string, object> _data;\n        private HashSet<string> _initialKeys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);\n        private HashSet<string> _retainedKeys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);\n\n        public TempDataDictionary()\n        {\n            _data = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);\n        }\n\n        public int Count\n        {\n            get { return _data.Count; }\n        }\n\n        public ICollection<string> Keys\n        {\n            get { return _data.Keys; }\n        }\n\n        public ICollection<object> Values\n        {\n            get { return _data.Values; }\n        }\n\n        bool ICollection<KeyValuePair<string, object>>.IsReadOnly\n        {\n            get { return ((ICollection<KeyValuePair<string, object>>)_data).IsReadOnly; }\n        }\n\n        public object this[string key]\n        {\n            get\n            {\n                object value;\n                if (TryGetValue(key, out value))\n                {\n                    _initialKeys.Remove(key);\n                    return value;\n                }\n                return null;\n            }\n            set\n            {\n                _data[key] = value;\n                _initialKeys.Add(key);\n            }\n        }\n\n        public void Keep()\n        {\n            _retainedKeys.Clear();\n            _retainedKeys.UnionWith(_data.Keys);\n        }\n\n        public void Keep(string key)\n        {\n            _retainedKeys.Add(key);\n        }\n\n        public void Load(ControllerContext controllerContext, ITempDataProvider tempDataProvider)\n        {\n            IDictionary<string, object> providerDictionary = tempDataProvider.LoadTempData(controllerContext);\n            _data = (providerDictionary != null)\n                ? new Dictionary<string, object>(providerDictionary, StringComparer.OrdinalIgnoreCase)\n                : new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);\n            _initialKeys = new HashSet<string>(_data.Keys, StringComparer.OrdinalIgnoreCase);\n            _retainedKeys.Clear();\n        }\n\n        public object Peek(string key)\n        {\n            object value;\n            _data.TryGetValue(key, out value);\n            return value;\n        }\n\n        public void Save(ControllerContext controllerContext, ITempDataProvider tempDataProvider)\n        {\n            // Frequently called so ensure delegate is stateless\n            _data.RemoveFromDictionary((KeyValuePair<string, object> entry, TempDataDictionary tempData) =>\n                {\n                    string key = entry.Key;\n                    return !tempData._initialKeys.Contains(key) \n                        && !tempData._retainedKeys.Contains(key);\n                }, this);\n\n            tempDataProvider.SaveTempData(controllerContext, _data);\n        }\n\n        public void Add(string key, object value)\n        {\n            _data.Add(key, value);\n            _initialKeys.Add(key);\n        }\n\n        public void Clear()\n        {\n            _data.Clear();\n            _retainedKeys.Clear();\n            _initialKeys.Clear();\n        }\n\n        public bool ContainsKey(string key)\n        {\n            return _data.ContainsKey(key);\n        }\n\n        public bool ContainsValue(object value)\n        {\n            return _data.ContainsValue(value);\n        }\n\n        public IEnumerator<KeyValuePair<string, object>> GetEnumerator()\n        {\n            return new TempDataDictionaryEnumerator(this);\n        }\n\n        public bool Remove(string key)\n        {\n            _retainedKeys.Remove(key);\n            _initialKeys.Remove(key);\n            return _data.Remove(key);\n        }\n\n        public bool TryGetValue(string key, out object value)\n        {\n            _initialKeys.Remove(key);\n            return _data.TryGetValue(key, out value);\n        }\n\n        void ICollection<KeyValuePair<string, object>>.CopyTo(KeyValuePair<string, object>[] array, int index)\n        {\n            ((ICollection<KeyValuePair<string, object>>)_data).CopyTo(array, index);\n        }\n\n        void ICollection<KeyValuePair<string, object>>.Add(KeyValuePair<string, object> keyValuePair)\n        {\n            _initialKeys.Add(keyValuePair.Key);\n            ((ICollection<KeyValuePair<string, object>>)_data).Add(keyValuePair);\n        }\n\n        bool ICollection<KeyValuePair<string, object>>.Contains(KeyValuePair<string, object> keyValuePair)\n        {\n            return ((ICollection<KeyValuePair<string, object>>)_data).Contains(keyValuePair);\n        }\n\n        bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> keyValuePair)\n        {\n            _initialKeys.Remove(keyValuePair.Key);\n            return ((ICollection<KeyValuePair<string, object>>)_data).Remove(keyValuePair);\n        }\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return new TempDataDictionaryEnumerator(this);\n        }\n\n        private sealed class TempDataDictionaryEnumerator : IEnumerator<KeyValuePair<string, object>>\n        {\n            private IEnumerator<KeyValuePair<string, object>> _enumerator;\n            private TempDataDictionary _tempData;\n\n            public TempDataDictionaryEnumerator(TempDataDictionary tempData)\n            {\n                _tempData = tempData;\n                _enumerator = _tempData._data.GetEnumerator();\n            }\n\n            public KeyValuePair<string, object> Current\n            {\n                get\n                {\n                    KeyValuePair<string, object> kvp = _enumerator.Current;\n                    _tempData._initialKeys.Remove(kvp.Key);\n                    return kvp;\n                }\n            }\n\n            object IEnumerator.Current\n            {\n                get { return Current; }\n            }\n\n            public bool MoveNext()\n            {\n                return _enumerator.MoveNext();\n            }\n\n            public void Reset()\n            {\n                _enumerator.Reset();\n            }\n\n            void IDisposable.Dispose()\n            {\n                _enumerator.Dispose();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/TemplateInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Mvc\n{\n    public class TemplateInfo\n    {\n        private string _htmlFieldPrefix;\n        private object _formattedModelValue;\n        private HashSet<object> _visitedObjects;\n\n        public object FormattedModelValue\n        {\n            get { return _formattedModelValue ?? String.Empty; }\n            set { _formattedModelValue = value; }\n        }\n\n        public string HtmlFieldPrefix\n        {\n            get { return _htmlFieldPrefix ?? String.Empty; }\n            set { _htmlFieldPrefix = value; }\n        }\n\n        public int TemplateDepth\n        {\n            get { return VisitedObjects.Count; }\n        }\n\n        // DDB #224750 - Keep a collection of visited objects to prevent infinite recursion\n        internal HashSet<object> VisitedObjects\n        {\n            get\n            {\n                if (_visitedObjects == null)\n                {\n                    _visitedObjects = new HashSet<object>();\n                }\n                return _visitedObjects;\n            }\n            set { _visitedObjects = value; }\n        }\n\n        public string GetFullHtmlFieldId(string partialFieldName)\n        {\n            return HtmlHelper.GenerateIdFromName(GetFullHtmlFieldName(partialFieldName));\n        }\n\n        public string GetFullHtmlFieldName(string partialFieldName)\n        {\n            if (partialFieldName != null && partialFieldName.StartsWith(\"[\", StringComparison.Ordinal))\n            {\n                // See Codeplex #544 - the partialFieldName might represent an indexer access, in which case combining\n                // with a 'dot' would be invalid.\n                return HtmlFieldPrefix + partialFieldName;\n            }\n            else\n            {\n                // This uses \"combine and trim\" because either or both of these values might be empty\n                return (HtmlFieldPrefix + \".\" + (partialFieldName ?? String.Empty)).Trim('.');\n            }\n        }\n\n        public bool Visited(ModelMetadata metadata)\n        {\n            return VisitedObjects.Contains(metadata.Model ?? metadata.ModelType);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/TryGetValueDelegate.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    internal delegate bool TryGetValueDelegate(object dictionary, string key, out object value);\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/TypeCacheSerializer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\nusing System.Web.Mvc.Properties;\nusing System.Xml;\n\nnamespace System.Web.Mvc\n{\n    // Processes files with this format:\n    //\n    // <typeCache lastModified=... mvcVersionId=...>\n    //   <assembly name=...>\n    //     <module versionId=...>\n    //       <type>...</type>\n    //     </module>\n    //   </assembly>\n    // </typeCache>\n    //\n    // This is used to store caches of files between AppDomain resets, leading to improved cold boot time\n    // and more efficient use of memory.\n\n    internal sealed class TypeCacheSerializer\n    {\n        private static readonly Guid _mvcVersionId = typeof(TypeCacheSerializer).Module.ModuleVersionId;\n\n        // used for unit testing\n\n        private DateTime CurrentDate\n        {\n            get { return CurrentDateOverride ?? DateTime.Now; }\n        }\n\n        internal DateTime? CurrentDateOverride { get; set; }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"This is an instance method for consistency with the SerializeTypes() method.\")]\n        public List<Type> DeserializeTypes(TextReader input)\n        {\n            XmlDocument doc = new XmlDocument();\n            doc.Load(input);\n            XmlElement rootElement = doc.DocumentElement;\n\n            Guid readMvcVersionId = new Guid(rootElement.Attributes[\"mvcVersionId\"].Value);\n            if (readMvcVersionId != _mvcVersionId)\n            {\n                // The cache is outdated because the cache file was produced by a different version\n                // of MVC.\n                return null;\n            }\n\n            List<Type> deserializedTypes = new List<Type>();\n            foreach (XmlNode assemblyNode in rootElement.ChildNodes)\n            {\n                string assemblyName = assemblyNode.Attributes[\"name\"].Value;\n                Assembly assembly = Assembly.Load(assemblyName);\n\n                foreach (XmlNode moduleNode in assemblyNode.ChildNodes)\n                {\n                    Guid moduleVersionId = new Guid(moduleNode.Attributes[\"versionId\"].Value);\n\n                    foreach (XmlNode typeNode in moduleNode.ChildNodes)\n                    {\n                        string typeName = typeNode.InnerText;\n                        Type type = assembly.GetType(typeName);\n                        if (type == null || type.Module.ModuleVersionId != moduleVersionId)\n                        {\n                            // The cache is outdated because we couldn't find a previously recorded\n                            // type or the type's containing module was modified.\n                            return null;\n                        }\n                        else\n                        {\n                            deserializedTypes.Add(type);\n                        }\n                    }\n                }\n            }\n\n            return deserializedTypes;\n        }\n\n        public void SerializeTypes(IEnumerable<Type> types, TextWriter output)\n        {\n            var groupedByAssembly = from type in types\n                                    group type by type.Module\n                                        into groupedByModule\n                                        group groupedByModule by groupedByModule.Key.Assembly;\n\n            XmlDocument doc = new XmlDocument();\n            doc.AppendChild(doc.CreateComment(MvcResources.TypeCache_DoNotModify));\n\n            XmlElement typeCacheElement = doc.CreateElement(\"typeCache\");\n            doc.AppendChild(typeCacheElement);\n            typeCacheElement.SetAttribute(\"lastModified\", CurrentDate.ToString(CultureInfo.InvariantCulture));\n            typeCacheElement.SetAttribute(\"mvcVersionId\", _mvcVersionId.ToString());\n\n            foreach (var assemblyGroup in groupedByAssembly)\n            {\n                XmlElement assemblyElement = doc.CreateElement(\"assembly\");\n                typeCacheElement.AppendChild(assemblyElement);\n                assemblyElement.SetAttribute(\"name\", assemblyGroup.Key.FullName);\n\n                foreach (var moduleGroup in assemblyGroup)\n                {\n                    XmlElement moduleElement = doc.CreateElement(\"module\");\n                    assemblyElement.AppendChild(moduleElement);\n                    moduleElement.SetAttribute(\"versionId\", moduleGroup.Key.ModuleVersionId.ToString());\n\n                    foreach (Type type in moduleGroup)\n                    {\n                        XmlElement typeElement = doc.CreateElement(\"type\");\n                        moduleElement.AppendChild(typeElement);\n                        typeElement.AppendChild(doc.CreateTextNode(type.FullName));\n                    }\n                }\n            }\n\n            doc.Save(output);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/TypeCacheUtil.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\n\nnamespace System.Web.Mvc\n{\n    internal static class TypeCacheUtil\n    {\n        private static IEnumerable<Type> FilterTypesInAssemblies(IBuildManager buildManager, Predicate<Type> predicate)\n        {\n            // Go through all assemblies referenced by the application and search for types matching a predicate\n            IEnumerable<Type> typesSoFar = Type.EmptyTypes;\n\n            ICollection assemblies = buildManager.GetReferencedAssemblies();\n            foreach (Assembly assembly in assemblies)\n            {\n                Type[] typesInAsm;\n                try\n                {\n                    typesInAsm = assembly.GetTypes();\n                }\n                catch (ReflectionTypeLoadException ex)\n                {\n                    typesInAsm = ex.Types;\n                }\n                typesSoFar = typesSoFar.Concat(typesInAsm);\n            }\n            return typesSoFar.Where(type => TypeIsPublicClass(type) && predicate(type));\n        }\n\n        public static List<Type> GetFilteredTypesFromAssemblies(string cacheName, Predicate<Type> predicate, IBuildManager buildManager)\n        {\n            TypeCacheSerializer serializer = new TypeCacheSerializer();\n\n            // first, try reading from the cache on disk\n            List<Type> matchingTypes = ReadTypesFromCache(cacheName, predicate, buildManager, serializer);\n            if (matchingTypes != null)\n            {\n                return matchingTypes;\n            }\n\n            // if reading from the cache failed, enumerate over every assembly looking for a matching type\n            matchingTypes = FilterTypesInAssemblies(buildManager, predicate).ToList();\n\n            // finally, save the cache back to disk\n            SaveTypesToCache(cacheName, matchingTypes, buildManager, serializer);\n\n            return matchingTypes;\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Cache failures are not fatal, and the code should continue executing normally.\")]\n        internal static List<Type> ReadTypesFromCache(string cacheName, Predicate<Type> predicate, IBuildManager buildManager, TypeCacheSerializer serializer)\n        {\n            try\n            {\n                Stream stream = buildManager.ReadCachedFile(cacheName);\n                if (stream != null)\n                {\n                    using (StreamReader reader = new StreamReader(stream))\n                    {\n                        List<Type> deserializedTypes = serializer.DeserializeTypes(reader);\n                        if (deserializedTypes != null && deserializedTypes.All(type => TypeIsPublicClass(type) && predicate(type)))\n                        {\n                            // If all read types still match the predicate, success!\n                            return deserializedTypes;\n                        }\n                    }\n                }\n            }\n            catch\n            {\n            }\n\n            return null;\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Cache failures are not fatal, and the code should continue executing normally.\")]\n        internal static void SaveTypesToCache(string cacheName, IList<Type> matchingTypes, IBuildManager buildManager, TypeCacheSerializer serializer)\n        {\n            try\n            {\n                Stream stream = buildManager.CreateCachedFile(cacheName);\n                if (stream != null)\n                {\n                    using (StreamWriter writer = new StreamWriter(stream))\n                    {\n                        serializer.SerializeTypes(matchingTypes, writer);\n                    }\n                }\n            }\n            catch\n            {\n            }\n        }\n\n        private static bool TypeIsPublicClass(Type type)\n        {\n            return (type != null && type.IsPublic && type.IsClass && !type.IsAbstract);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/TypeDescriptorHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.ComponentModel.DataAnnotations;\n\nnamespace System.Web.Mvc\n{\n    internal static class TypeDescriptorHelper\n    {\n        public static ICustomTypeDescriptor Get(Type type)\n        {\n            return new AssociatedMetadataTypeTypeDescriptionProvider(type).GetTypeDescriptor(type);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/TypeHelpers.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Reflection;\nusing System.Threading;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    internal static class TypeHelpers\n    {\n        private static readonly Dictionary<Type, TryGetValueDelegate> _tryGetValueDelegateCache = new Dictionary<Type, TryGetValueDelegate>();\n        private static readonly ReaderWriterLockSlim _tryGetValueDelegateCacheLock = new ReaderWriterLockSlim();\n\n        private static readonly MethodInfo _strongTryGetValueImplInfo = typeof(TypeHelpers).GetMethod(\"StrongTryGetValueImpl\", BindingFlags.NonPublic | BindingFlags.Static);\n\n        public static readonly Assembly MsCorLibAssembly = typeof(string).Assembly;\n        public static readonly Assembly MvcAssembly = typeof(Controller).Assembly;\n        public static readonly Assembly SystemWebAssembly = typeof(HttpContext).Assembly;\n\n        // method is used primarily for lighting up new .NET Framework features even if MVC targets the previous version\n        // thisParameter is the 'this' parameter if target method is instance method, should be null for static method\n        public static TDelegate CreateDelegate<TDelegate>(Assembly assembly, string typeName, string methodName, object thisParameter) where TDelegate : class\n        {\n            // ensure target type exists\n            Type targetType = assembly.GetType(typeName, false /* throwOnError */);\n            if (targetType == null)\n            {\n                return null;\n            }\n\n            return CreateDelegate<TDelegate>(targetType, methodName, thisParameter);\n        }\n\n        public static TDelegate CreateDelegate<TDelegate>(Type targetType, string methodName, object thisParameter) where TDelegate : class\n        {\n            // ensure target method exists\n            ParameterInfo[] delegateParameters = typeof(TDelegate).GetMethod(\"Invoke\").GetParameters();\n            Type[] argumentTypes = Array.ConvertAll(delegateParameters, pInfo => pInfo.ParameterType);\n            MethodInfo targetMethod = targetType.GetMethod(methodName, argumentTypes);\n            if (targetMethod == null)\n            {\n                return null;\n            }\n\n            TDelegate d = Delegate.CreateDelegate(typeof(TDelegate), thisParameter, targetMethod, false /* throwOnBindFailure */) as TDelegate;\n            return d;\n        }\n\n        public static TryGetValueDelegate CreateTryGetValueDelegate(Type targetType)\n        {\n            TryGetValueDelegate result;\n\n            _tryGetValueDelegateCacheLock.EnterReadLock();\n            try\n            {\n                if (_tryGetValueDelegateCache.TryGetValue(targetType, out result))\n                {\n                    return result;\n                }\n            }\n            finally\n            {\n                _tryGetValueDelegateCacheLock.ExitReadLock();\n            }\n\n            Type dictionaryType = ExtractGenericInterface(targetType, typeof(IDictionary<,>));\n\n            // just wrap a call to the underlying IDictionary<TKey, TValue>.TryGetValue() where string can be cast to TKey\n            if (dictionaryType != null)\n            {\n                Type[] typeArguments = dictionaryType.GetGenericArguments();\n                Type keyType = typeArguments[0];\n                Type returnType = typeArguments[1];\n\n                if (keyType.IsAssignableFrom(typeof(string)))\n                {\n                    MethodInfo strongImplInfo = _strongTryGetValueImplInfo.MakeGenericMethod(keyType, returnType);\n                    result = (TryGetValueDelegate)Delegate.CreateDelegate(typeof(TryGetValueDelegate), strongImplInfo);\n                }\n            }\n\n            // wrap a call to the underlying IDictionary.Item()\n            if (result == null && typeof(IDictionary).IsAssignableFrom(targetType))\n            {\n                result = TryGetValueFromNonGenericDictionary;\n            }\n\n            _tryGetValueDelegateCacheLock.EnterWriteLock();\n            try\n            {\n                _tryGetValueDelegateCache[targetType] = result;\n            }\n            finally\n            {\n                _tryGetValueDelegateCacheLock.ExitWriteLock();\n            }\n\n            return result;\n        }\n\n        public static Type ExtractGenericInterface(Type queryType, Type interfaceType)\n        {\n            if (MatchesGenericType(queryType, interfaceType))\n            {\n                return queryType;\n            }\n            Type[] queryTypeInterfaces = queryType.GetInterfaces();\n            return MatchGenericTypeFirstOrDefault(queryTypeInterfaces, interfaceType);\n        }\n\n        public static object GetDefaultValue(Type type)\n        {\n            return (TypeAllowsNullValue(type)) ? null : Activator.CreateInstance(type);\n        }\n\n        public static bool IsCompatibleObject<T>(object value)\n        {\n            return (value is T || (value == null && TypeAllowsNullValue(typeof(T))));\n        }\n\n        public static bool IsNullableValueType(Type type)\n        {\n            return Nullable.GetUnderlyingType(type) != null;\n        }\n\n        /// <summary>\n        /// Provide a new <see cref=\"MissingMethodException\"/> if original Message does not contain given full Type name.\n        /// </summary>\n        /// <param name=\"originalException\"><see cref=\"MissingMethodException\"/> to check.</param>\n        /// <param name=\"fullTypeName\">Full Type name which Message should contain.</param>\n        /// <returns>New <see cref=\"MissingMethodException\"/> if an update is required; null otherwise.</returns>\n        public static MissingMethodException EnsureDebuggableException(\n            MissingMethodException originalException,\n            string fullTypeName)\n        {\n            MissingMethodException replacementException = null;\n            if (!originalException.Message.Contains(fullTypeName))\n            {\n                string message = String.Format(\n                    CultureInfo.CurrentCulture,\n                    MvcResources.TypeHelpers_CannotCreateInstance,\n                    originalException.Message,\n                    fullTypeName);\n                replacementException = new MissingMethodException(message, originalException);\n            }\n\n            return replacementException;\n        }\n\n        private static bool MatchesGenericType(Type type, Type matchType)\n        {\n            return type.IsGenericType && type.GetGenericTypeDefinition() == matchType;\n        }\n\n        private static Type MatchGenericTypeFirstOrDefault(Type[] types, Type matchType)\n        {\n            for (int i = 0; i < types.Length; i++)\n            {\n                Type type = types[i];\n                if (MatchesGenericType(type, matchType))\n                {\n                    return type;\n                }\n            }\n            return null;\n        }\n\n        private static bool StrongTryGetValueImpl<TKey, TValue>(object dictionary, string key, out object value)\n        {\n            IDictionary<TKey, TValue> strongDict = (IDictionary<TKey, TValue>)dictionary;\n\n            TValue strongValue;\n            bool retVal = strongDict.TryGetValue((TKey)(object)key, out strongValue);\n            value = strongValue;\n            return retVal;\n        }\n\n        private static bool TryGetValueFromNonGenericDictionary(object dictionary, string key, out object value)\n        {\n            IDictionary weakDict = (IDictionary)dictionary;\n\n            bool containsKey = weakDict.Contains(key);\n            value = (containsKey) ? weakDict[key] : null;\n            return containsKey;\n        }\n\n        public static bool TypeAllowsNullValue(Type type)\n        {\n            return (!type.IsValueType || IsNullableValueType(type));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/UnvalidatedRequestValuesAccessor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    internal delegate IUnvalidatedRequestValues UnvalidatedRequestValuesAccessor(ControllerContext controllerContext);\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/UnvalidatedRequestValuesWrapper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\n\nnamespace System.Web.Mvc\n{\n    // Concrete implementation for the IUnvalidatedRequestValues helper interface\n\n    internal sealed class UnvalidatedRequestValuesWrapper : IUnvalidatedRequestValues\n    {\n        private readonly UnvalidatedRequestValuesBase _unvalidatedValues;\n\n        public UnvalidatedRequestValuesWrapper(UnvalidatedRequestValuesBase unvalidatedValues)\n        {\n            _unvalidatedValues = unvalidatedValues;\n        }\n\n        public NameValueCollection Form\n        {\n            get { return _unvalidatedValues.Form; }\n        }\n\n        public NameValueCollection QueryString\n        {\n            get { return _unvalidatedValues.QueryString; }\n        }\n\n        public string this[string key]\n        {\n            get { return _unvalidatedValues[key]; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/UrlHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Web.Mvc.Properties;\nusing System.Web.Routing;\nusing System.Web.WebPages;\n\nnamespace System.Web.Mvc\n{\n    public class UrlHelper\n    {\n        /// <summary>\n        /// Key used to signify that a route URL generation request should include HTTP routes (e.g. Web API).\n        /// If this key is not specified then no HTTP routes will match.\n        /// </summary>\n        private const string HttpRouteKey = \"httproute\";\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"UrlHelper\"/> class.\n        /// </summary>\n        /// <remarks>The default constructor is intended for use by unit testing only.</remarks>\n        public UrlHelper()\n        {\n        }\n\n        public UrlHelper(RequestContext requestContext)\n            : this(requestContext, RouteTable.Routes)\n        {\n        }\n\n        public UrlHelper(RequestContext requestContext, RouteCollection routeCollection)\n        {\n            if (requestContext == null)\n            {\n                throw new ArgumentNullException(\"requestContext\");\n            }\n            if (routeCollection == null)\n            {\n                throw new ArgumentNullException(\"routeCollection\");\n            }\n            RequestContext = requestContext;\n            RouteCollection = routeCollection;\n        }\n\n        public RequestContext RequestContext { get; private set; }\n\n        public RouteCollection RouteCollection { get; private set; }\n\n        public virtual string Action()\n        {\n            return RequestContext.HttpContext.Request.RawUrl;\n        }\n\n        public virtual string Action(string actionName)\n        {\n            return GenerateUrl(null /* routeName */, actionName, null, (RouteValueDictionary)null /* routeValues */);\n        }\n\n        public virtual string Action(string actionName, object routeValues)\n        {\n            return GenerateUrl(null /* routeName */, actionName, null /* controllerName */, TypeHelper.ObjectToDictionary(routeValues));\n        }\n\n        public virtual string Action(string actionName, RouteValueDictionary routeValues)\n        {\n            return GenerateUrl(null /* routeName */, actionName, null /* controllerName */, routeValues);\n        }\n\n        public virtual string Action(string actionName, string controllerName)\n        {\n            return GenerateUrl(null /* routeName */, actionName, controllerName, (RouteValueDictionary)null /* routeValues */);\n        }\n\n        public virtual string Action(string actionName, string controllerName, object routeValues)\n        {\n            return GenerateUrl(null /* routeName */, actionName, controllerName, TypeHelper.ObjectToDictionary(routeValues));\n        }\n\n        public virtual string Action(string actionName, string controllerName, RouteValueDictionary routeValues)\n        {\n            return GenerateUrl(null /* routeName */, actionName, controllerName, routeValues);\n        }\n\n        public virtual string Action(string actionName, string controllerName, RouteValueDictionary routeValues, string protocol)\n        {\n            return GenerateUrl(null /* routeName */, actionName, controllerName, protocol, null /* hostName */, null /* fragment */, routeValues, RouteCollection, RequestContext, true /* includeImplicitMvcValues */);\n        }\n\n        public virtual string Action(string actionName, string controllerName, object routeValues, string protocol)\n        {\n            return GenerateUrl(null /* routeName */, actionName, controllerName, protocol, null /* hostName */, null /* fragment */, TypeHelper.ObjectToDictionary(routeValues), RouteCollection, RequestContext, true /* includeImplicitMvcValues */);\n        }\n\n        public virtual string Action(string actionName, string controllerName, RouteValueDictionary routeValues, string protocol, string hostName)\n        {\n            return GenerateUrl(null /* routeName */, actionName, controllerName, protocol, hostName, null /* fragment */, routeValues, RouteCollection, RequestContext, true /* includeImplicitMvcValues */);\n        }\n\n        public virtual string Content(string contentPath)\n        {\n            return GenerateContentUrl(contentPath, RequestContext.HttpContext);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1055:UriReturnValuesShouldNotBeStrings\", Justification = \"As the return value will used only for rendering, string return value is more appropriate.\")]\n        public static string GenerateContentUrl(string contentPath, HttpContextBase httpContext)\n        {\n            if (String.IsNullOrEmpty(contentPath))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"contentPath\");\n            }\n\n            if (httpContext == null)\n            {\n                throw new ArgumentNullException(\"httpContext\");\n            }\n\n            if (contentPath[0] == '~')\n            {\n                return UrlUtil.GenerateClientUrl(httpContext, contentPath);\n            }\n            else\n            {\n                return contentPath;\n            }\n        }\n\n        //REVIEW: Should we have an overload that takes Uri?\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", Justification = \"Needs to take same parameters as HttpUtility.UrlEncode()\")]\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"For consistency, all helpers are instance methods.\")]\n        public virtual string Encode(string url)\n        {\n            return HttpUtility.UrlEncode(url);\n        }\n\n        private string GenerateUrl(string routeName, string actionName, string controllerName, RouteValueDictionary routeValues)\n        {\n            return GenerateUrl(routeName, actionName, controllerName, routeValues, RouteCollection, RequestContext, true /* includeImplicitMvcValues */);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1055:UriReturnValuesShouldNotBeStrings\", Justification = \"As the return value will used only for rendering, string return value is more appropriate.\")]\n        public static string GenerateUrl(string routeName, string actionName, string controllerName, string protocol, string hostName, string fragment, RouteValueDictionary routeValues, RouteCollection routeCollection, RequestContext requestContext, bool includeImplicitMvcValues)\n        {\n            string url = GenerateUrl(routeName, actionName, controllerName, routeValues, routeCollection, requestContext, includeImplicitMvcValues);\n\n            if (url != null)\n            {\n                if (!String.IsNullOrEmpty(fragment))\n                {\n                    url = url + \"#\" + fragment;\n                }\n\n                if (!String.IsNullOrEmpty(protocol) || !String.IsNullOrEmpty(hostName))\n                {\n                    Uri requestUrl = requestContext.HttpContext.Request.Url;\n                    protocol = (!String.IsNullOrEmpty(protocol)) ? protocol : Uri.UriSchemeHttp;\n                    hostName = (!String.IsNullOrEmpty(hostName)) ? hostName : requestUrl.Host;\n\n                    string port = String.Empty;\n                    string requestProtocol = requestUrl.Scheme;\n\n                    if (String.Equals(protocol, requestProtocol, StringComparison.OrdinalIgnoreCase))\n                    {\n                        port = requestUrl.IsDefaultPort ? String.Empty : (\":\" + Convert.ToString(requestUrl.Port, CultureInfo.InvariantCulture));\n                    }\n\n                    url = protocol + Uri.SchemeDelimiter + hostName + port + url;\n                }\n            }\n\n            return url;\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1055:UriReturnValuesShouldNotBeStrings\", Justification = \"As the return value will used only for rendering, string return value is more appropriate.\")]\n        public static string GenerateUrl(string routeName, string actionName, string controllerName, RouteValueDictionary routeValues, RouteCollection routeCollection, RequestContext requestContext, bool includeImplicitMvcValues)\n        {\n            if (routeCollection == null)\n            {\n                throw new ArgumentNullException(\"routeCollection\");\n            }\n\n            if (requestContext == null)\n            {\n                throw new ArgumentNullException(\"requestContext\");\n            }\n\n            RouteValueDictionary mergedRouteValues = RouteValuesHelpers.MergeRouteValues(actionName, controllerName, requestContext.RouteData.Values, routeValues, includeImplicitMvcValues);\n\n            VirtualPathData vpd = routeCollection.GetVirtualPathForArea(requestContext, routeName, mergedRouteValues);\n            if (vpd == null)\n            {\n                return null;\n            }\n\n            string modifiedUrl = UrlUtil.GenerateClientUrl(requestContext.HttpContext, vpd.VirtualPath);\n            return modifiedUrl;\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"0#\", Justification = \"Response.Redirect() takes its URI as a string parameter.\")]\n        public virtual bool IsLocalUrl(string url)\n        {\n            // TODO this should call the System.Web.dll API once it gets added to the framework and MVC takes a dependency on it.\n            return RequestExtensions.IsUrlLocalToHost(RequestContext.HttpContext.Request, url);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1055:UriReturnValuesShouldNotBeStrings\", Justification = \"As the return value will used only for rendering, string return value is more appropriate.\")]\n        public virtual string RouteUrl(object routeValues)\n        {\n            return RouteUrl(null /* routeName */, routeValues);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1055:UriReturnValuesShouldNotBeStrings\", Justification = \"As the return value will used only for rendering, string return value is more appropriate.\")]\n        public virtual string RouteUrl(RouteValueDictionary routeValues)\n        {\n            return RouteUrl(null /* routeName */, routeValues);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1055:UriReturnValuesShouldNotBeStrings\", Justification = \"As the return value will used only for rendering, string return value is more appropriate.\")]\n        public virtual string RouteUrl(string routeName)\n        {\n            return RouteUrl(routeName, (object)null /* routeValues */);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1055:UriReturnValuesShouldNotBeStrings\", Justification = \"As the return value will used only for rendering, string return value is more appropriate.\")]\n        public virtual string RouteUrl(string routeName, object routeValues)\n        {\n            return RouteUrl(routeName, routeValues, null /* protocol */);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1055:UriReturnValuesShouldNotBeStrings\", Justification = \"As the return value will used only for rendering, string return value is more appropriate.\")]\n        public virtual string RouteUrl(string routeName, RouteValueDictionary routeValues)\n        {\n            return RouteUrl(routeName, routeValues, null /* protocol */, null /* hostName */);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1055:UriReturnValuesShouldNotBeStrings\", Justification = \"As the return value will used only for rendering, string return value is more appropriate.\")]\n        public virtual string RouteUrl(string routeName, object routeValues, string protocol)\n        {\n            return GenerateUrl(routeName, null /* actionName */, null /* controllerName */, protocol, null /* hostName */, null /* fragment */, TypeHelper.ObjectToDictionary(routeValues), RouteCollection, RequestContext, false /* includeImplicitMvcValues */);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1055:UriReturnValuesShouldNotBeStrings\", Justification = \"As the return value will used only for rendering, string return value is more appropriate.\")]\n        public virtual string RouteUrl(string routeName, RouteValueDictionary routeValues, string protocol, string hostName)\n        {\n            return GenerateUrl(routeName, null /* actionName */, null /* controllerName */, protocol, hostName, null /* fragment */, routeValues, RouteCollection, RequestContext, false /* includeImplicitMvcValues */);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1055:UriReturnValuesShouldNotBeStrings\", Justification = \"As the return value will used only for rendering, string return value is more appropriate.\")]\n        public virtual string HttpRouteUrl(string routeName, object routeValues)\n        {\n            return HttpRouteUrl(routeName, TypeHelper.ObjectToDictionary(routeValues));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1055:UriReturnValuesShouldNotBeStrings\", Justification = \"As the return value will used only for rendering, string return value is more appropriate.\")]\n        public virtual string HttpRouteUrl(string routeName, RouteValueDictionary routeValues)\n        {\n            if (routeValues == null)\n            {\n                // If no route values were passed in at all we have to create a new dictionary\n                // so that we can add the extra \"httproute\" key.\n                routeValues = new RouteValueDictionary();\n                routeValues.Add(HttpRouteKey, true);\n            }\n            else\n            {\n                // Copy the dictionary to add the extra \"httproute\" key used by all Web API routes to\n                // disambiguate them from other MVC routes.\n                routeValues = new RouteValueDictionary(routeValues);\n                if (!routeValues.ContainsKey(HttpRouteKey))\n                {\n                    routeValues.Add(HttpRouteKey, true);\n                }\n            }\n\n            return GenerateUrl(routeName,\n                actionName: null,\n                controllerName: null,\n                protocol: null,\n                hostName: null,\n                fragment: null,\n                routeValues: routeValues,\n                routeCollection: RouteCollection,\n                requestContext: RequestContext,\n                includeImplicitMvcValues: false);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/UrlParameter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.Mvc\n{\n    public sealed class UrlParameter\n    {\n        [SuppressMessage(\"Microsoft.Security\", \"CA2104:DoNotDeclareReadOnlyMutableReferenceTypes\", Justification = \"This type is immutable.\")]\n        public static readonly UrlParameter Optional = new UrlParameter();\n\n        // singleton constructor\n        private UrlParameter()\n        {\n        }\n\n        public override string ToString()\n        {\n            return String.Empty;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ValidatableObjectAdapter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Globalization;\nusing System.Linq;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    public class ValidatableObjectAdapter : ModelValidator\n    {\n        public ValidatableObjectAdapter(ModelMetadata metadata, ControllerContext context)\n            : base(metadata, context)\n        {\n        }\n\n        public override IEnumerable<ModelValidationResult> Validate(object container)\n        {\n            // NOTE: Container is never used here, because IValidatableObject doesn't give you\n            // any way to get access to your container.\n\n            object model = Metadata.Model;\n            if (model == null)\n            {\n                return Enumerable.Empty<ModelValidationResult>();\n            }\n\n            IValidatableObject validatable = model as IValidatableObject;\n            if (validatable == null)\n            {\n                throw new InvalidOperationException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.ValidatableObjectAdapter_IncompatibleType,\n                        typeof(IValidatableObject).FullName,\n                        model.GetType().FullName));\n            }\n\n            ValidationContext validationContext = new ValidationContext(validatable, null, null);\n            return ConvertResults(validatable.Validate(validationContext));\n        }\n\n        private static IEnumerable<ModelValidationResult> ConvertResults(IEnumerable<ValidationResult> results)\n        {\n            foreach (ValidationResult result in results)\n            {\n                if (result != ValidationResult.Success)\n                {\n                    if (result.MemberNames == null || !result.MemberNames.Any())\n                    {\n                        yield return new ModelValidationResult { Message = result.ErrorMessage };\n                    }\n                    else\n                    {\n                        foreach (string memberName in result.MemberNames)\n                        {\n                            yield return new ModelValidationResult { Message = result.ErrorMessage, MemberName = memberName };\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ValidateAntiForgeryTokenAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Helpers;\n\nnamespace System.Web.Mvc\n{\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]\n    public sealed class ValidateAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter\n    {\n        private string _salt;\n\n        public ValidateAntiForgeryTokenAttribute()\n            : this(AntiForgery.Validate)\n        {\n        }\n\n        internal ValidateAntiForgeryTokenAttribute(Action validateAction)\n        {\n            Debug.Assert(validateAction != null);\n            ValidateAction = validateAction;\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA2204:Literals should be spelled correctly\", MessageId = \"AdditionalDataProvider\", Justification = \"API name.\")]\n        [SuppressMessage(\"Microsoft.Naming\", \"CA2204:Literals should be spelled correctly\", MessageId = \"AntiForgeryConfig\", Justification = \"API name.\")]\n        [Obsolete(\"The 'Salt' property is deprecated. To specify custom data to be embedded within the token, use the static AntiForgeryConfig.AdditionalDataProvider property.\", error: true)]\n        [EditorBrowsable(EditorBrowsableState.Never)]\n        public string Salt\n        {\n            get { return _salt; }\n            set\n            {\n                if (!String.IsNullOrEmpty(value))\n                {\n                    throw new NotSupportedException(\"The 'Salt' property is deprecated. To specify custom data to be embedded within the token, use the static AntiForgeryConfig.AdditionalDataProvider property.\");\n                }\n                _salt = value;\n            }\n        }\n\n        internal Action ValidateAction { get; private set; }\n\n        public void OnAuthorization(AuthorizationContext filterContext)\n        {\n            if (filterContext == null)\n            {\n                throw new ArgumentNullException(\"filterContext\");\n            }\n\n            ValidateAction();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ValidateInputAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.Mvc\n{\n    [SuppressMessage(\"Microsoft.Performance\", \"CA1813:AvoidUnsealedAttributes\", Justification = \"No compelling performance reason to seal this type.\")]\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\n    public class ValidateInputAttribute : FilterAttribute, IAuthorizationFilter\n    {\n        public ValidateInputAttribute(bool enableValidation)\n        {\n            EnableValidation = enableValidation;\n        }\n\n        public bool EnableValidation { get; private set; }\n\n        public virtual void OnAuthorization(AuthorizationContext filterContext)\n        {\n            if (filterContext == null)\n            {\n                throw new ArgumentNullException(\"filterContext\");\n            }\n\n            filterContext.Controller.ValidateRequest = EnableValidation;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ValueProviderCollection.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\n\nnamespace System.Web.Mvc\n{\n    public class ValueProviderCollection : Collection<IValueProvider>, IValueProvider, IUnvalidatedValueProvider, IEnumerableValueProvider\n    {\n        public ValueProviderCollection()\n        {\n        }\n\n        public ValueProviderCollection(IList<IValueProvider> list)\n            : base(list)\n        {\n        }\n\n        public virtual bool ContainsPrefix(string prefix)\n        {\n            // Performance sensitive, so avoid Linq and delegates\n            // Saving Count is faster for looping over Collection<T>\n            int itemCount = Count;\n            for (int i = 0; i < itemCount; i++)\n            {\n                if (this[i].ContainsPrefix(prefix))\n                {\n                    return true;\n                }\n            }\n            return false;\n        }\n\n        public virtual ValueProviderResult GetValue(string key)\n        {\n            return GetValue(key, skipValidation: false);\n        }\n\n        public virtual ValueProviderResult GetValue(string key, bool skipValidation)\n        {\n            // Performance sensitive.\n            // Caching the count is faster for Collection<T>\n            int providerCount = Count;\n            for (int i = 0; i < providerCount; i++)\n            {\n                ValueProviderResult result = GetValueFromProvider(this[i], key, skipValidation);\n                if (result != null)\n                {\n                    return result;\n                }\n            }\n            return null;\n        }\n\n        public virtual IDictionary<string, string> GetKeysFromPrefix(string prefix)\n        {\n            return (from provider in this\n                    let result = GetKeysFromPrefixFromProvider(provider, prefix)\n                    where result != null && result.Any()\n                    select result).FirstOrDefault() ?? new Dictionary<string, string>();\n        }\n\n        internal static ValueProviderResult GetValueFromProvider(IValueProvider provider, string key, bool skipValidation)\n        {\n            // Since IUnvalidatedValueProvider is a superset of IValueProvider, it's always OK to use the\n            // IUnvalidatedValueProvider-supplied members if they're present. Otherwise just call the\n            // normal IValueProvider members.\n\n            IUnvalidatedValueProvider unvalidatedProvider = provider as IUnvalidatedValueProvider;\n            return (unvalidatedProvider != null) ? unvalidatedProvider.GetValue(key, skipValidation) : provider.GetValue(key);\n        }\n\n        internal static IDictionary<string, string> GetKeysFromPrefixFromProvider(IValueProvider provider, string prefix)\n        {\n            IEnumerableValueProvider enumeratedProvider = provider as IEnumerableValueProvider;\n            return (enumeratedProvider != null) ? enumeratedProvider.GetKeysFromPrefix(prefix) : null;\n        }\n\n        protected override void InsertItem(int index, IValueProvider item)\n        {\n            if (item == null)\n            {\n                throw new ArgumentNullException(\"item\");\n            }\n            base.InsertItem(index, item);\n        }\n\n        protected override void SetItem(int index, IValueProvider item)\n        {\n            if (item == null)\n            {\n                throw new ArgumentNullException(\"item\");\n            }\n            base.SetItem(index, item);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ValueProviderDictionary.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Web.Routing;\n\nnamespace System.Web.Mvc\n{\n    [Obsolete(\"The recommended alternative is to use one of the specific ValueProvider types, such as FormValueProvider.\")]\n    public class ValueProviderDictionary : IDictionary<string, ValueProviderResult>, IValueProvider\n    {\n        private readonly Dictionary<string, ValueProviderResult> _dictionary = new Dictionary<string, ValueProviderResult>(StringComparer.OrdinalIgnoreCase);\n\n        public ValueProviderDictionary(ControllerContext controllerContext)\n        {\n            ControllerContext = controllerContext;\n            if (controllerContext != null)\n            {\n                PopulateDictionary();\n            }\n        }\n\n        public ControllerContext ControllerContext { get; private set; }\n\n        public int Count\n        {\n            get { return ((ICollection<KeyValuePair<string, ValueProviderResult>>)Dictionary).Count; }\n        }\n\n        internal Dictionary<string, ValueProviderResult> Dictionary\n        {\n            get { return _dictionary; }\n        }\n\n        public bool IsReadOnly\n        {\n            get { return ((ICollection<KeyValuePair<string, ValueProviderResult>>)Dictionary).IsReadOnly; }\n        }\n\n        public ICollection<string> Keys\n        {\n            get { return Dictionary.Keys; }\n        }\n\n        public ValueProviderResult this[string key]\n        {\n            get\n            {\n                ValueProviderResult result;\n                Dictionary.TryGetValue(key, out result);\n                return result;\n            }\n            set { Dictionary[key] = value; }\n        }\n\n        public ICollection<ValueProviderResult> Values\n        {\n            get { return Dictionary.Values; }\n        }\n\n        public void Add(KeyValuePair<string, ValueProviderResult> item)\n        {\n            ((ICollection<KeyValuePair<string, ValueProviderResult>>)Dictionary).Add(item);\n        }\n\n        public void Add(string key, object value)\n        {\n            string attemptedValue = Convert.ToString(value, CultureInfo.InvariantCulture);\n            ValueProviderResult valueProviderResult = new ValueProviderResult(value, attemptedValue, CultureInfo.InvariantCulture);\n            Add(key, valueProviderResult);\n        }\n\n        public void Add(string key, ValueProviderResult value)\n        {\n            Dictionary.Add(key, value);\n        }\n\n        private void AddToDictionaryIfNotPresent(string key, ValueProviderResult result)\n        {\n            if (!String.IsNullOrEmpty(key))\n            {\n                if (!Dictionary.ContainsKey(key))\n                {\n                    Dictionary.Add(key, result);\n                }\n            }\n        }\n\n        public void Clear()\n        {\n            ((ICollection<KeyValuePair<string, ValueProviderResult>>)Dictionary).Clear();\n        }\n\n        public bool Contains(KeyValuePair<string, ValueProviderResult> item)\n        {\n            return ((ICollection<KeyValuePair<string, ValueProviderResult>>)Dictionary).Contains(item);\n        }\n\n        public bool ContainsKey(string key)\n        {\n            return Dictionary.ContainsKey(key);\n        }\n\n        public void CopyTo(KeyValuePair<string, ValueProviderResult>[] array, int arrayIndex)\n        {\n            ((ICollection<KeyValuePair<string, ValueProviderResult>>)Dictionary).CopyTo(array, arrayIndex);\n        }\n\n        public IEnumerator<KeyValuePair<string, ValueProviderResult>> GetEnumerator()\n        {\n            return ((IEnumerable<KeyValuePair<string, ValueProviderResult>>)Dictionary).GetEnumerator();\n        }\n\n        private void PopulateDictionary()\n        {\n            CultureInfo currentCulture = CultureInfo.CurrentCulture;\n            CultureInfo invariantCulture = CultureInfo.InvariantCulture;\n\n            // We use this order of precedence to populate the dictionary:\n            // 1. Request form submission (should be culture-aware)\n            // 2. Values from the RouteData (could be from the typed-in URL or from the route's default values)\n            // 3. URI query string\n\n            NameValueCollection form = ControllerContext.HttpContext.Request.Form;\n            if (form != null)\n            {\n                string[] keys = form.AllKeys;\n                foreach (string key in keys)\n                {\n                    string[] rawValue = form.GetValues(key);\n                    string attemptedValue = form[key];\n                    ValueProviderResult result = new ValueProviderResult(rawValue, attemptedValue, currentCulture);\n                    AddToDictionaryIfNotPresent(key, result);\n                }\n            }\n\n            RouteValueDictionary routeValues = ControllerContext.RouteData.Values;\n            if (routeValues != null)\n            {\n                foreach (var kvp in routeValues)\n                {\n                    string key = kvp.Key;\n                    object rawValue = kvp.Value;\n                    string attemptedValue = Convert.ToString(rawValue, invariantCulture);\n                    ValueProviderResult result = new ValueProviderResult(rawValue, attemptedValue, invariantCulture);\n                    AddToDictionaryIfNotPresent(key, result);\n                }\n            }\n\n            NameValueCollection queryString = ControllerContext.HttpContext.Request.QueryString;\n            if (queryString != null)\n            {\n                string[] keys = queryString.AllKeys;\n                foreach (string key in keys)\n                {\n                    string[] rawValue = queryString.GetValues(key);\n                    string attemptedValue = queryString[key];\n                    ValueProviderResult result = new ValueProviderResult(rawValue, attemptedValue, invariantCulture);\n                    AddToDictionaryIfNotPresent(key, result);\n                }\n            }\n        }\n\n        public bool Remove(KeyValuePair<string, ValueProviderResult> item)\n        {\n            return ((ICollection<KeyValuePair<string, ValueProviderResult>>)Dictionary).Remove(item);\n        }\n\n        public bool Remove(string key)\n        {\n            return Dictionary.Remove(key);\n        }\n\n        public bool TryGetValue(string key, out ValueProviderResult value)\n        {\n            return Dictionary.TryGetValue(key, out value);\n        }\n\n        #region IEnumerable Members\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return ((IEnumerable)Dictionary).GetEnumerator();\n        }\n\n        #endregion\n\n        #region IValueProvider Members\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1033:InterfaceMethodsShouldBeCallableByChildTypes\", Justification = \"The declaring type is obsolete, so there is little benefit to exposing this as a virtual method.\")]\n        bool IValueProvider.ContainsPrefix(string prefix)\n        {\n            if (prefix == null)\n            {\n                throw new ArgumentNullException(\"prefix\");\n            }\n\n            return ValueProviderUtil.CollectionContainsPrefix(Keys, prefix);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1033:InterfaceMethodsShouldBeCallableByChildTypes\", Justification = \"The declaring type is obsolete, so there is little benefit to exposing this as a virtual method.\")]\n        ValueProviderResult IValueProvider.GetValue(string key)\n        {\n            if (key == null)\n            {\n                throw new ArgumentNullException(\"key\");\n            }\n\n            ValueProviderResult valueProviderResult;\n            TryGetValue(key, out valueProviderResult);\n            return valueProviderResult;\n        }\n\n        #endregion\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ValueProviderFactories.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public static class ValueProviderFactories\n    {\n        private static readonly ValueProviderFactoryCollection _factories = new ValueProviderFactoryCollection()\n        {\n            new ChildActionValueProviderFactory(),\n            new FormValueProviderFactory(),\n            new JsonValueProviderFactory(),\n            new RouteDataValueProviderFactory(),\n            new QueryStringValueProviderFactory(),\n            new HttpFileCollectionValueProviderFactory(),\n            new JQueryFormValueProviderFactory()\n        };\n\n        public static ValueProviderFactoryCollection Factories\n        {\n            get { return _factories; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ValueProviderFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public abstract class ValueProviderFactory\n    {\n        public abstract IValueProvider GetValueProvider(ControllerContext controllerContext);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ValueProviderFactoryCollection.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\n\nnamespace System.Web.Mvc\n{\n    public class ValueProviderFactoryCollection : Collection<ValueProviderFactory>\n    {\n        private ValueProviderFactory[] _combinedItems;\n        private IDependencyResolver _dependencyResolver;\n\n        public ValueProviderFactoryCollection()\n        {\n        }\n\n        public ValueProviderFactoryCollection(IList<ValueProviderFactory> list)\n            : base(list)\n        {\n        }\n\n        internal ValueProviderFactoryCollection(IList<ValueProviderFactory> list, IDependencyResolver dependencyResolver)\n            : base(list)\n        {\n            _dependencyResolver = dependencyResolver;\n        }\n\n        internal ValueProviderFactory[] CombinedItems\n        {\n            get\n            {\n                ValueProviderFactory[] combinedItems = _combinedItems;\n                if (combinedItems == null)\n                {\n                    combinedItems = MultiServiceResolver.GetCombined<ValueProviderFactory>(Items, _dependencyResolver);\n                    _combinedItems = combinedItems;\n                }\n                return combinedItems;\n            }\n        }\n\n        public IValueProvider GetValueProvider(ControllerContext controllerContext)\n        {\n            ValueProviderFactory[] current = CombinedItems;\n            List<IValueProvider> providers = new List<IValueProvider>(current.Length);\n            for (int i = 0; i < current.Length; i++)\n            {\n                ValueProviderFactory factory = current[i];\n                IValueProvider provider = factory.GetValueProvider(controllerContext);\n                if (provider != null)\n                {\n                    providers.Add(provider);\n                }\n            }\n            return new ValueProviderCollection(providers);\n        }\n\n        protected override void ClearItems()\n        {\n            _combinedItems = null;\n            base.ClearItems();\n        }\n\n        protected override void InsertItem(int index, ValueProviderFactory item)\n        {\n            if (item == null)\n            {\n                throw new ArgumentNullException(\"item\");\n            }\n            _combinedItems = null;\n            base.InsertItem(index, item);\n        }\n\n        protected override void RemoveItem(int index)\n        {\n            _combinedItems = null;\n            base.RemoveItem(index);\n        }\n\n        protected override void SetItem(int index, ValueProviderFactory item)\n        {\n            if (item == null)\n            {\n                throw new ArgumentNullException(\"item\");\n            }\n            _combinedItems = null;\n            base.SetItem(index, item);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ValueProviderResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    [Serializable]\n    public class ValueProviderResult\n    {\n        private static readonly CultureInfo _staticCulture = CultureInfo.InvariantCulture;\n        private CultureInfo _instanceCulture;\n\n        // default constructor so that subclassed types can set the properties themselves\n        protected ValueProviderResult()\n        {\n        }\n\n        public ValueProviderResult(object rawValue, string attemptedValue, CultureInfo culture)\n        {\n            RawValue = rawValue;\n            AttemptedValue = attemptedValue;\n            Culture = culture;\n        }\n\n        public string AttemptedValue { get; protected set; }\n\n        public CultureInfo Culture\n        {\n            get\n            {\n                if (_instanceCulture == null)\n                {\n                    _instanceCulture = _staticCulture;\n                }\n                return _instanceCulture;\n            }\n            protected set { _instanceCulture = value; }\n        }\n\n        public object RawValue { get; protected set; }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Conversion failure is not fatal\")]\n        private static object ConvertSimpleType(CultureInfo culture, object value, Type destinationType)\n        {\n            if (value == null || destinationType.IsInstanceOfType(value))\n            {\n                return value;\n            }\n\n            // if this is a user-input value but the user didn't type anything, return no value\n            string valueAsString = value as string;\n            if (valueAsString != null && String.IsNullOrWhiteSpace(valueAsString))\n            {\n                return null;\n            }\n\n            // In case of a Nullable object, we extract the underlying type and try to convert it.\n            Type underlyingType = Nullable.GetUnderlyingType(destinationType);\n\n            if (underlyingType != null)\n            {\n                destinationType = underlyingType;\n            }\n\n            // String doesn't provide convertibles to interesting types, and thus it will typically throw rather than succeed.\n            if (valueAsString == null)\n            {\n                // If the source type implements IConvertible, try that first\n                IConvertible convertible = value as IConvertible;\n                if (convertible != null)\n                {\n                    try\n                    {\n                        return convertible.ToType(destinationType, culture);\n                    }\n                    catch\n                    {\n                    }\n                }\n            }\n\n            // Last resort, look for a type converter\n            TypeConverter converter = TypeDescriptor.GetConverter(destinationType);\n            bool canConvertFrom = converter.CanConvertFrom(value.GetType());\n            if (!canConvertFrom)\n            {\n                converter = TypeDescriptor.GetConverter(value.GetType());\n            }\n            if (!(canConvertFrom || converter.CanConvertTo(destinationType)))\n            {\n                // EnumConverter cannot convert integer, so we verify manually\n                if (destinationType.IsEnum && value is int)\n                {\n                    return Enum.ToObject(destinationType, (int)value);\n                }\n\n                string message = String.Format(CultureInfo.CurrentCulture, MvcResources.ValueProviderResult_NoConverterExists,\n                                               value.GetType().FullName, destinationType.FullName);\n                throw new InvalidOperationException(message);\n            }\n\n            try\n            {\n                object convertedValue = (canConvertFrom)\n                                            ? converter.ConvertFrom(null /* context */, culture, value)\n                                            : converter.ConvertTo(null /* context */, culture, value, destinationType);\n                return convertedValue;\n            }\n            catch (Exception ex)\n            {\n                string message = String.Format(CultureInfo.CurrentCulture, MvcResources.ValueProviderResult_ConversionThrew,\n                                               value.GetType().FullName, destinationType.FullName);\n                throw new InvalidOperationException(message, ex);\n            }\n        }\n\n        public object ConvertTo(Type type)\n        {\n            return ConvertTo(type, null /* culture */);\n        }\n\n        public virtual object ConvertTo(Type type, CultureInfo culture)\n        {\n            if (type == null)\n            {\n                throw new ArgumentNullException(\"type\");\n            }\n\n            CultureInfo cultureToUse = culture ?? Culture;\n            return UnwrapPossibleArrayType(cultureToUse, RawValue, type);\n        }\n\n        private static object UnwrapPossibleArrayType(CultureInfo culture, object value, Type destinationType)\n        {\n            if (value == null || destinationType.IsInstanceOfType(value))\n            {\n                return value;\n            }\n\n            // array conversion results in four cases, as below\n            Array valueAsArray = value as Array;\n            if (destinationType.IsArray)\n            {\n                Type destinationElementType = destinationType.GetElementType();\n                if (valueAsArray != null)\n                {\n                    // case 1: both destination + source type are arrays, so convert each element\n                    IList converted = Array.CreateInstance(destinationElementType, valueAsArray.Length);\n                    for (int i = 0; i < valueAsArray.Length; i++)\n                    {\n                        converted[i] = ConvertSimpleType(culture, valueAsArray.GetValue(i), destinationElementType);\n                    }\n                    return converted;\n                }\n                else\n                {\n                    // case 2: destination type is array but source is single element, so wrap element in array + convert\n                    object element = ConvertSimpleType(culture, value, destinationElementType);\n                    IList converted = Array.CreateInstance(destinationElementType, 1);\n                    converted[0] = element;\n                    return converted;\n                }\n            }\n            else if (valueAsArray != null)\n            {\n                // case 3: destination type is single element but source is array, so extract first element + convert\n                if (valueAsArray.Length > 0)\n                {\n                    value = valueAsArray.GetValue(0);\n                    return ConvertSimpleType(culture, value, destinationType);\n                }\n                else\n                {\n                    // case 3(a): source is empty array, so can't perform conversion\n                    return null;\n                }\n            }\n            // case 4: both destination + source type are single elements, so convert\n            return ConvertSimpleType(culture, value, destinationType);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ValueProviderUtil.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Mvc\n{\n    internal static class ValueProviderUtil\n    {\n        public static bool CollectionContainsPrefix(IEnumerable<string> collection, string prefix)\n        {\n            foreach (string key in collection)\n            {\n                if (key != null)\n                {\n                    if (prefix.Length == 0)\n                    {\n                        return true; // shortcut - non-null key matches empty prefix\n                    }\n\n                    if (key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))\n                    {\n                        if (key.Length == prefix.Length)\n                        {\n                            return true; // exact match\n                        }\n                        else\n                        {\n                            switch (key[prefix.Length])\n                            {\n                                case '.': // known separator characters\n                                case '[':\n                                    return true;\n                            }\n                        }\n                    }\n                }\n            }\n\n            return false; // nothing found\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ViewContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.IO;\nusing System.Web.Mvc.Html;\nusing System.Web.WebPages.Scope;\n\nnamespace System.Web.Mvc\n{\n    public class ViewContext : ControllerContext\n    {\n        private const string ClientValidationScript = @\"<script type=\"\"text/javascript\"\">\n//<![CDATA[\nif (!window.mvcClientValidationMetadata) {{ window.mvcClientValidationMetadata = []; }}\nwindow.mvcClientValidationMetadata.push({0});\n//]]>\n</script>\";\n\n        internal static readonly string ClientValidationKeyName = \"ClientValidationEnabled\";\n        internal static readonly string UnobtrusiveJavaScriptKeyName = \"UnobtrusiveJavaScriptEnabled\";\n        internal static readonly string ValidationSummaryMessageElementKeyName = \"ValidationSummaryMessageElement\";\n        internal static readonly string ValidationMessageElementKeyName = \"ValidationMessageElement\";\n\n        // Some values have to be stored in HttpContext.Items in order to be propagated between calls\n        // to RenderPartial(), RenderAction(), etc.\n        private static readonly object _formContextKey = new object();\n        private static readonly object _lastFormNumKey = new object();\n\n        private Func<IDictionary<object, object>> _scopeThunk;\n        private IDictionary<object, object> _transientScope;\n\n        private DynamicViewDataDictionary _dynamicViewDataDictionary;\n        private Func<string> _formIdGenerator;\n\n        // We need a default FormContext if the user uses html <form> instead of an MvcForm\n        private FormContext _defaultFormContext = new FormContext();\n\n        // parameterless constructor used for mocking\n        public ViewContext()\n        {\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2214:DoNotCallOverridableMethodsInConstructors\", Justification = \"The virtual property setters are only to support mocking frameworks, in which case this constructor shouldn't be called anyway.\")]\n        public ViewContext(ControllerContext controllerContext, IView view, ViewDataDictionary viewData, TempDataDictionary tempData, TextWriter writer)\n            : base(controllerContext)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n            if (view == null)\n            {\n                throw new ArgumentNullException(\"view\");\n            }\n            if (viewData == null)\n            {\n                throw new ArgumentNullException(\"viewData\");\n            }\n            if (tempData == null)\n            {\n                throw new ArgumentNullException(\"tempData\");\n            }\n            if (writer == null)\n            {\n                throw new ArgumentNullException(\"writer\");\n            }\n\n            View = view;\n            ViewData = viewData;\n            Writer = writer;\n            TempData = tempData;\n        }\n\n        public virtual bool ClientValidationEnabled\n        {\n            get { return GetClientValidationEnabled(Scope, HttpContext); }\n            set { SetClientValidationEnabled(value, Scope, HttpContext); }\n        }\n\n        public virtual FormContext FormContext\n        {\n            get\n            {\n                // Never return a null form context, this is important for validation purposes\n                return HttpContext.Items[_formContextKey] as FormContext ?? _defaultFormContext;\n            }\n            set { HttpContext.Items[_formContextKey] = value; }\n        }\n\n        internal Func<string> FormIdGenerator\n        {\n            get\n            {\n                if (_formIdGenerator == null)\n                {\n                    _formIdGenerator = DefaultFormIdGenerator;\n                }\n                return _formIdGenerator;\n            }\n            set { _formIdGenerator = value; }\n        }\n\n        internal static Func<IDictionary<object, object>> GlobalScopeThunk { get; set; }\n\n        private IDictionary<object, object> Scope\n        {\n            get\n            {\n                if (ScopeThunk != null)\n                {\n                    return ScopeThunk();\n                }\n                if (_transientScope == null)\n                {\n                    _transientScope = new Dictionary<object, object>();\n                }\n                return _transientScope;\n            }\n        }\n\n        internal Func<IDictionary<object, object>> ScopeThunk\n        {\n            get { return _scopeThunk ?? GlobalScopeThunk; }\n            set { _scopeThunk = value; }\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"The property setter is only here to support mocking this type and should not be called at runtime.\")]\n        public virtual TempDataDictionary TempData { get; set; }\n\n        public virtual bool UnobtrusiveJavaScriptEnabled\n        {\n            get { return GetUnobtrusiveJavaScriptEnabled(Scope, HttpContext); }\n            set { SetUnobtrusiveJavaScriptEnabled(value, Scope, HttpContext); }\n        }\n\n        /// <summary>\n        /// Element name used to wrap a top-level message generated by\n        /// <see cref=\"ValidationExtensions.ValidationSummary(HtmlHelper)\"/> and other overloads.\n        /// </summary>\n        public virtual string ValidationSummaryMessageElement\n        {\n            get { return GetValidationSummaryMessageElement(Scope, HttpContext); }\n            set\n            {\n                if (String.IsNullOrEmpty(value))\n                {\n                    throw Error.ParameterCannotBeNullOrEmpty(\"value\");\n                }\n\n                SetValidationSummaryMessageElement(value, Scope, HttpContext);\n            }\n        }\n\n        /// <summary>\n        /// Element name used to wrap a top-level message generated by\n        /// <see cref=\"ValidationExtensions.ValidationMessage(HtmlHelper, String)\"/> and other overloads.\n        /// </summary>\n        public virtual string ValidationMessageElement\n        {\n            get { return GetValidationMessageElement(Scope, HttpContext); }\n            set\n            {\n                if (String.IsNullOrEmpty(value))\n                {\n                    throw Error.ParameterCannotBeNullOrEmpty(\"value\");\n                }\n\n                SetValidationMessageElement(value, Scope, HttpContext);\n            }\n        }\n\n        public virtual IView View { get; set; }\n\n        public dynamic ViewBag\n        {\n            get\n            {\n                if (_dynamicViewDataDictionary == null)\n                {\n                    _dynamicViewDataDictionary = new DynamicViewDataDictionary(() => ViewData);\n                }\n                return _dynamicViewDataDictionary;\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"The property setter is only here to support mocking this type and should not be called at runtime.\")]\n        public virtual ViewDataDictionary ViewData { get; set; }\n\n        public virtual TextWriter Writer { get; set; }\n\n        private string DefaultFormIdGenerator()\n        {\n            int formNum = IncrementFormCount(HttpContext.Items);\n            return String.Format(CultureInfo.InvariantCulture, \"form{0}\", formNum);\n        }\n\n        internal static bool GetClientValidationEnabled(IDictionary<object, object> scope = null, HttpContextBase httpContext = null)\n        {\n            return ScopeCache.Get(scope, httpContext).ClientValidationEnabled;\n        }\n\n        internal FormContext GetFormContextForClientValidation()\n        {\n            return (ClientValidationEnabled) ? FormContext : null;\n        }\n\n        internal static bool GetUnobtrusiveJavaScriptEnabled(IDictionary<object, object> scope = null, HttpContextBase httpContext = null)\n        {\n            return ScopeCache.Get(scope, httpContext).UnobtrusiveJavaScriptEnabled;\n        }\n\n        internal static string GetValidationSummaryMessageElement(\n            IDictionary<object, object> scope = null,\n            HttpContextBase httpContext = null)\n        {\n            return ScopeCache.Get(scope, httpContext).ValidationSummaryMessageElement;\n        }\n\n        internal static string GetValidationMessageElement(\n            IDictionary<object, object> scope = null,\n            HttpContextBase httpContext = null)\n        {\n            return ScopeCache.Get(scope, httpContext).ValidationMessageElement;\n        }\n\n        private static int IncrementFormCount(IDictionary items)\n        {\n            object lastFormNum = items[_lastFormNumKey];\n            int newFormNum = (lastFormNum != null) ? ((int)lastFormNum) + 1 : 0;\n            items[_lastFormNumKey] = newFormNum;\n            return newFormNum;\n        }\n\n        public void OutputClientValidation()\n        {\n            FormContext formContext = GetFormContextForClientValidation();\n            if (formContext == null || UnobtrusiveJavaScriptEnabled)\n            {\n                return; // do nothing\n            }\n\n            string scriptWithCorrectNewLines = ClientValidationScript.Replace(\"\\r\\n\", Environment.NewLine);\n            string validationJson = formContext.GetJsonValidationMetadata();\n            string formatted = String.Format(CultureInfo.InvariantCulture, scriptWithCorrectNewLines, validationJson);\n\n            Writer.Write(formatted);\n        }\n\n        internal static void SetClientValidationEnabled(bool enabled, IDictionary<object, object> scope = null, HttpContextBase httpContext = null)\n        {\n            ScopeCache.Get(scope, httpContext).ClientValidationEnabled = enabled;\n        }\n\n        internal static void SetUnobtrusiveJavaScriptEnabled(bool enabled, IDictionary<object, object> scope = null, HttpContextBase httpContext = null)\n        {\n            ScopeCache.Get(scope, httpContext).UnobtrusiveJavaScriptEnabled = enabled;\n        }\n\n        internal static void SetValidationSummaryMessageElement(\n            string elementName,\n            IDictionary<object, object> scope = null,\n            HttpContextBase httpContext = null)\n        {\n            ScopeCache.Get(scope, httpContext).ValidationSummaryMessageElement = elementName;\n        }\n\n        internal static void SetValidationMessageElement(\n            string elementName,\n            IDictionary<object, object> scope = null,\n            HttpContextBase httpContext = null)\n        {\n            ScopeCache.Get(scope, httpContext).ValidationMessageElement = elementName;\n        }\n\n        private static TValue ScopeGet<TValue>(IDictionary<object, object> scope, string name, TValue defaultValue = default(TValue))\n        {\n            object result;\n            if (scope.TryGetValue(name, out result))\n            {\n                return (TValue)Convert.ChangeType(result, typeof(TValue), CultureInfo.InvariantCulture);\n            }\n            return defaultValue;\n        }\n\n        private sealed class ScopeCache\n        {\n            private static readonly object _cacheKey = new object();\n            private bool _clientValidationEnabled;\n            private IDictionary<object, object> _scope;\n            private bool _unobtrusiveJavaScriptEnabled;\n            private string _validationSummaryMessageElement;\n            private string _validationMessageElement;\n\n            private ScopeCache(IDictionary<object, object> scope)\n            {\n                _scope = scope;\n\n                _clientValidationEnabled = ScopeGet(scope, ClientValidationKeyName, false);\n                _unobtrusiveJavaScriptEnabled = ScopeGet(scope, UnobtrusiveJavaScriptKeyName, false);\n                _validationSummaryMessageElement = ScopeGet(scope, ValidationSummaryMessageElementKeyName, \"span\");\n                _validationMessageElement = ScopeGet(scope, ValidationMessageElementKeyName, \"span\");\n            }\n\n            public bool ClientValidationEnabled\n            {\n                get { return _clientValidationEnabled; }\n                set\n                {\n                    _clientValidationEnabled = value;\n                    _scope[ClientValidationKeyName] = value;\n                }\n            }\n\n            public bool UnobtrusiveJavaScriptEnabled\n            {\n                get { return _unobtrusiveJavaScriptEnabled; }\n                set\n                {\n                    _unobtrusiveJavaScriptEnabled = value;\n                    _scope[UnobtrusiveJavaScriptKeyName] = value;\n                }\n            }\n\n            public string ValidationSummaryMessageElement\n            {\n                get { return _validationSummaryMessageElement; }\n                set\n                {\n                    _validationSummaryMessageElement = value;\n                    _scope[ValidationSummaryMessageElementKeyName] = value;\n                }\n            }\n\n            public string ValidationMessageElement\n            {\n                get { return _validationMessageElement; }\n                set\n                {\n                    _validationMessageElement = value;\n                    _scope[ValidationMessageElementKeyName] = value;\n                }\n            }\n\n            public static ScopeCache Get(IDictionary<object, object> scope, HttpContextBase httpContext)\n            {\n                if (httpContext == null && Web.HttpContext.Current != null)\n                {\n                    httpContext = new HttpContextWrapper(Web.HttpContext.Current);\n                }\n\n                ScopeCache result = null;\n                scope = scope ?? ScopeStorage.CurrentScope;\n\n                if (httpContext != null)\n                {\n                    result = httpContext.Items[_cacheKey] as ScopeCache;\n                }\n\n                if (result == null || result._scope != scope)\n                {\n                    result = new ScopeCache(scope);\n\n                    if (httpContext != null)\n                    {\n                        httpContext.Items[_cacheKey] = result;\n                    }\n                }\n\n                return result;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ViewDataDictionary.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    // TODO: Unit test ModelState interaction with VDD\n\n    public class ViewDataDictionary : IDictionary<string, object>\n    {\n        private readonly IDictionary<string, object> _innerDictionary;\n        private readonly ModelStateDictionary _modelState;\n        private object _model;\n        private ModelMetadata _modelMetadata;\n        private TemplateInfo _templateMetadata;\n\n        public ViewDataDictionary()\n            : this((object)null)\n        {\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2214:DoNotCallOverridableMethodsInConstructors\", Justification = \"See note on SetModel() method.\")]\n        public ViewDataDictionary(object model)\n        {\n            Model = model;\n            _innerDictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);\n            _modelState = new ModelStateDictionary();\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2214:DoNotCallOverridableMethodsInConstructors\", Justification = \"See note on SetModel() method.\")]\n        public ViewDataDictionary(ViewDataDictionary dictionary)\n        {\n            if (dictionary == null)\n            {\n                throw new ArgumentNullException(\"dictionary\");\n            }\n\n            _innerDictionary = new CopyOnWriteDictionary<string, object>(dictionary, StringComparer.OrdinalIgnoreCase);\n            _modelState = new ModelStateDictionary(dictionary.ModelState);\n\n            Model = dictionary.Model;\n            TemplateInfo = dictionary.TemplateInfo;\n\n            // PERF: Don't unnecessarily instantiate the model metadata\n            _modelMetadata = dictionary._modelMetadata;\n        }\n\n        public int Count\n        {\n            get { return _innerDictionary.Count; }\n        }\n\n        public bool IsReadOnly\n        {\n            get { return _innerDictionary.IsReadOnly; }\n        }\n\n        public ICollection<string> Keys\n        {\n            get { return _innerDictionary.Keys; }\n        }\n\n        public object Model\n        {\n            get { return _model; }\n            set\n            {\n                _modelMetadata = null;\n                SetModel(value);\n            }\n        }\n\n        public virtual ModelMetadata ModelMetadata\n        {\n            get\n            {\n                if (_modelMetadata == null && _model != null)\n                {\n                    _modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => _model, _model.GetType());\n                }\n                return _modelMetadata;\n            }\n            set { _modelMetadata = value; }\n        }\n\n        public ModelStateDictionary ModelState\n        {\n            get { return _modelState; }\n        }\n\n        public TemplateInfo TemplateInfo\n        {\n            get\n            {\n                if (_templateMetadata == null)\n                {\n                    _templateMetadata = new TemplateInfo();\n                }\n                return _templateMetadata;\n            }\n            set { _templateMetadata = value; }\n        }\n\n        public ICollection<object> Values\n        {\n            get { return _innerDictionary.Values; }\n        }\n\n        public object this[string key]\n        {\n            get\n            {\n                object value;\n                _innerDictionary.TryGetValue(key, out value);\n                return value;\n            }\n            set { _innerDictionary[key] = value; }\n        }\n\n        // For unit testing\n        internal IDictionary<string, object> InnerDictionary\n        {\n            get { return _innerDictionary; }\n        }\n\n        public void Add(KeyValuePair<string, object> item)\n        {\n            _innerDictionary.Add(item);\n        }\n\n        public void Add(string key, object value)\n        {\n            _innerDictionary.Add(key, value);\n        }\n\n        public void Clear()\n        {\n            _innerDictionary.Clear();\n        }\n\n        public bool Contains(KeyValuePair<string, object> item)\n        {\n            return _innerDictionary.Contains(item);\n        }\n\n        public bool ContainsKey(string key)\n        {\n            return _innerDictionary.ContainsKey(key);\n        }\n\n        public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)\n        {\n            _innerDictionary.CopyTo(array, arrayIndex);\n        }\n\n        public object Eval(string expression)\n        {\n            ViewDataInfo info = GetViewDataInfo(expression);\n            return (info != null) ? info.Value : null;\n        }\n\n        public string Eval(string expression, string format)\n        {\n            object value = Eval(expression);\n            return FormatValueInternal(value, format);\n        }\n\n        internal static string FormatValueInternal(object value, string format)\n        {\n            if (value == null)\n            {\n                return String.Empty;\n            }\n\n            if (String.IsNullOrEmpty(format))\n            {\n                return Convert.ToString(value, CultureInfo.CurrentCulture);\n            }\n            else\n            {\n                return String.Format(CultureInfo.CurrentCulture, format, value);\n            }\n        }\n\n        public IEnumerator<KeyValuePair<string, object>> GetEnumerator()\n        {\n            return _innerDictionary.GetEnumerator();\n        }\n\n        public ViewDataInfo GetViewDataInfo(string expression)\n        {\n            if (String.IsNullOrEmpty(expression))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"expression\");\n            }\n\n            return ViewDataEvaluator.Eval(this, expression);\n        }\n\n        public bool Remove(KeyValuePair<string, object> item)\n        {\n            return _innerDictionary.Remove(item);\n        }\n\n        public bool Remove(string key)\n        {\n            return _innerDictionary.Remove(key);\n        }\n\n        // This method will execute before the derived type's instance constructor executes. Derived types must\n        // be aware of this and should plan accordingly. For example, the logic in SetModel() should be simple\n        // enough so as not to depend on the \"this\" pointer referencing a fully constructed object.\n        protected virtual void SetModel(object value)\n        {\n            _model = value;\n        }\n\n        public bool TryGetValue(string key, out object value)\n        {\n            return _innerDictionary.TryGetValue(key, out value);\n        }\n\n        internal static class ViewDataEvaluator\n        {\n            public static ViewDataInfo Eval(ViewDataDictionary vdd, string expression)\n            {\n                //Given an expression \"foo.bar.baz\" we look up the following (pseudocode):\n                //  this[\"foo.bar.baz.quux\"]\n                //  this[\"foo.bar.baz\"][\"quux\"]\n                //  this[\"foo.bar\"][\"baz.quux]\n                //  this[\"foo.bar\"][\"baz\"][\"quux\"]\n                //  this[\"foo\"][\"bar.baz.quux\"]\n                //  this[\"foo\"][\"bar.baz\"][\"quux\"]\n                //  this[\"foo\"][\"bar\"][\"baz.quux\"]\n                //  this[\"foo\"][\"bar\"][\"baz\"][\"quux\"]\n\n                ViewDataInfo evaluated = EvalComplexExpression(vdd, expression);\n                return evaluated;\n            }\n\n            private static ViewDataInfo EvalComplexExpression(object indexableObject, string expression)\n            {\n                foreach (ExpressionPair expressionPair in GetRightToLeftExpressions(expression))\n                {\n                    string subExpression = expressionPair.Left;\n                    string postExpression = expressionPair.Right;\n\n                    ViewDataInfo subTargetInfo = GetPropertyValue(indexableObject, subExpression);\n                    if (subTargetInfo != null)\n                    {\n                        if (String.IsNullOrEmpty(postExpression))\n                        {\n                            return subTargetInfo;\n                        }\n\n                        if (subTargetInfo.Value != null)\n                        {\n                            ViewDataInfo potential = EvalComplexExpression(subTargetInfo.Value, postExpression);\n                            if (potential != null)\n                            {\n                                return potential;\n                            }\n                        }\n                    }\n                }\n                return null;\n            }\n\n            private static IEnumerable<ExpressionPair> GetRightToLeftExpressions(string expression)\n            {\n                // Produces an enumeration of all the combinations of complex property names\n                // given a complex expression. See the list above for an example of the result\n                // of the enumeration.\n\n                yield return new ExpressionPair(expression, String.Empty);\n\n                int lastDot = expression.LastIndexOf('.');\n\n                string subExpression = expression;\n                string postExpression = String.Empty;\n\n                while (lastDot > -1)\n                {\n                    subExpression = expression.Substring(0, lastDot);\n                    postExpression = expression.Substring(lastDot + 1);\n                    yield return new ExpressionPair(subExpression, postExpression);\n\n                    lastDot = subExpression.LastIndexOf('.');\n                }\n            }\n\n            private static ViewDataInfo GetIndexedPropertyValue(object indexableObject, string key)\n            {\n                IDictionary<string, object> dict = indexableObject as IDictionary<string, object>;\n                object value = null;\n                bool success = false;\n\n                if (dict != null)\n                {\n                    success = dict.TryGetValue(key, out value);\n                }\n                else\n                {\n                    TryGetValueDelegate tgvDel = TypeHelpers.CreateTryGetValueDelegate(indexableObject.GetType());\n                    if (tgvDel != null)\n                    {\n                        success = tgvDel(indexableObject, key, out value);\n                    }\n                }\n\n                if (success)\n                {\n                    return new ViewDataInfo()\n                    {\n                        Container = indexableObject,\n                        Value = value\n                    };\n                }\n\n                return null;\n            }\n\n            private static ViewDataInfo GetPropertyValue(object container, string propertyName)\n            {\n                // This method handles one \"segment\" of a complex property expression\n\n                // First, we try to evaluate the property based on its indexer\n                ViewDataInfo value = GetIndexedPropertyValue(container, propertyName);\n                if (value != null)\n                {\n                    return value;\n                }\n\n                // If the indexer didn't return anything useful, continue...\n\n                // If the container is a ViewDataDictionary then treat its Model property\n                // as the container instead of the ViewDataDictionary itself.\n                ViewDataDictionary vdd = container as ViewDataDictionary;\n                if (vdd != null)\n                {\n                    container = vdd.Model;\n                }\n\n                // If the container is null, we're out of options\n                if (container == null)\n                {\n                    return null;\n                }\n\n                // Second, we try to use PropertyDescriptors and treat the expression as a property name\n                PropertyDescriptor descriptor = TypeDescriptor.GetProperties(container).Find(propertyName, true);\n                if (descriptor == null)\n                {\n                    return null;\n                }\n\n                return new ViewDataInfo(() => descriptor.GetValue(container))\n                {\n                    Container = container,\n                    PropertyDescriptor = descriptor\n                };\n            }\n\n            private struct ExpressionPair\n            {\n                public readonly string Left;\n                public readonly string Right;\n\n                public ExpressionPair(string left, string right)\n                {\n                    Left = left;\n                    Right = right;\n                }\n            }\n        }\n\n        #region IEnumerable Members\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return _innerDictionary.GetEnumerator();\n        }\n\n        #endregion\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ViewDataDictionaryOfTModel.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public class ViewDataDictionary<TModel> : ViewDataDictionary\n    {\n        public ViewDataDictionary()\n            :\n                base(default(TModel))\n        {\n        }\n\n        public ViewDataDictionary(TModel model)\n            :\n                base(model)\n        {\n        }\n\n        public ViewDataDictionary(ViewDataDictionary viewDataDictionary)\n            :\n                base(viewDataDictionary)\n        {\n        }\n\n        public new TModel Model\n        {\n            get { return (TModel)base.Model; }\n            set { SetModel(value); }\n        }\n\n        public override ModelMetadata ModelMetadata\n        {\n            get\n            {\n                ModelMetadata result = base.ModelMetadata;\n                if (result == null)\n                {\n                    result = base.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(TModel));\n                }\n                return result;\n            }\n            set { base.ModelMetadata = value; }\n        }\n\n        protected override void SetModel(object value)\n        {\n            bool castWillSucceed = TypeHelpers.IsCompatibleObject<TModel>(value);\n\n            if (castWillSucceed)\n            {\n                base.SetModel((TModel)value);\n            }\n            else\n            {\n                InvalidOperationException exception = (value != null)\n                                                          ? Error.ViewDataDictionary_WrongTModelType(value.GetType(), typeof(TModel))\n                                                          : Error.ViewDataDictionary_ModelCannotBeNull(typeof(TModel));\n                throw exception;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ViewDataInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\n\nnamespace System.Web.Mvc\n{\n    public class ViewDataInfo\n    {\n        private object _value;\n        private Func<object> _valueAccessor;\n\n        public ViewDataInfo()\n        {\n        }\n\n        public ViewDataInfo(Func<object> valueAccessor)\n        {\n            _valueAccessor = valueAccessor;\n        }\n\n        public object Container { get; set; }\n\n        public PropertyDescriptor PropertyDescriptor { get; set; }\n\n        public object Value\n        {\n            get\n            {\n                if (_valueAccessor != null)\n                {\n                    _value = _valueAccessor();\n                    _valueAccessor = null;\n                }\n\n                return _value;\n            }\n            set\n            {\n                _value = value;\n                _valueAccessor = null;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ViewEngineCollection.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    public class ViewEngineCollection : Collection<IViewEngine>\n    {\n        private IViewEngine[] _combinedItems;\n        private IDependencyResolver _dependencyResolver;\n\n        public ViewEngineCollection()\n        {\n        }\n\n        public ViewEngineCollection(IList<IViewEngine> list)\n            : base(list)\n        {\n        }\n\n        internal ViewEngineCollection(IList<IViewEngine> list, IDependencyResolver dependencyResolver)\n            : base(list)\n        {\n            _dependencyResolver = dependencyResolver;\n        }\n\n        internal IViewEngine[] CombinedItems\n        {\n            get\n            {\n                IViewEngine[] combinedItems = _combinedItems;\n                if (combinedItems == null)\n                {\n                    combinedItems = MultiServiceResolver.GetCombined<IViewEngine>(Items, _dependencyResolver);\n                    _combinedItems = combinedItems;\n                }\n                return combinedItems;\n            }\n        }\n\n        protected override void ClearItems()\n        {\n            _combinedItems = null;\n            base.ClearItems();\n        }\n\n        protected override void InsertItem(int index, IViewEngine item)\n        {\n            if (item == null)\n            {\n                throw new ArgumentNullException(\"item\");\n            }\n            _combinedItems = null;\n            base.InsertItem(index, item);\n        }\n\n        protected override void RemoveItem(int index)\n        {\n            _combinedItems = null;\n            base.RemoveItem(index);\n        }\n\n        protected override void SetItem(int index, IViewEngine item)\n        {\n            if (item == null)\n            {\n                throw new ArgumentNullException(\"item\");\n            }\n            _combinedItems = null;\n            base.SetItem(index, item);\n        }\n\n        private ViewEngineResult Find(Func<IViewEngine, ViewEngineResult> cacheLocator, Func<IViewEngine, ViewEngineResult> locator)\n        {\n            // First, look up using the cacheLocator and do not track the searched paths in non-matching view engines\n            // Then, look up using the normal locator and track the searched paths so that an error view engine can be returned\n            return Find(cacheLocator, trackSearchedPaths: false)\n                   ?? Find(locator, trackSearchedPaths: true);\n        }\n\n        private ViewEngineResult Find(Func<IViewEngine, ViewEngineResult> lookup, bool trackSearchedPaths)\n        {\n            // Returns\n            //    1st result\n            // OR list of searched paths (if trackSearchedPaths == true)\n            // OR null\n            ViewEngineResult result;\n\n            List<string> searched = null;\n            if (trackSearchedPaths)\n            {\n                searched = new List<string>();\n            }\n\n            foreach (IViewEngine engine in CombinedItems)\n            {\n                if (engine != null)\n                {\n                    result = lookup(engine);\n\n                    if (result.View != null)\n                    {\n                        return result;\n                    }\n\n                    if (trackSearchedPaths)\n                    {\n                        searched.AddRange(result.SearchedLocations);\n                    }\n                }\n            }\n\n            if (trackSearchedPaths)\n            {\n                // Remove duplicate search paths since multiple view engines could have potentially looked at the same path\n                return new ViewEngineResult(searched.Distinct().ToList());\n            }\n            else\n            {\n                return null;\n            }\n        }\n\n        public virtual ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n            if (String.IsNullOrEmpty(partialViewName))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"partialViewName\");\n            }\n\n            return Find(e => e.FindPartialView(controllerContext, partialViewName, true),\n                        e => e.FindPartialView(controllerContext, partialViewName, false));\n        }\n\n        public virtual ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n            if (String.IsNullOrEmpty(viewName))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"viewName\");\n            }\n\n            return Find(e => e.FindView(controllerContext, viewName, masterName, true),\n                        e => e.FindView(controllerContext, viewName, masterName, false));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ViewEngineResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Mvc\n{\n    public class ViewEngineResult\n    {\n        public ViewEngineResult(IEnumerable<string> searchedLocations)\n        {\n            if (searchedLocations == null)\n            {\n                throw new ArgumentNullException(\"searchedLocations\");\n            }\n\n            SearchedLocations = searchedLocations;\n        }\n\n        public ViewEngineResult(IView view, IViewEngine viewEngine)\n        {\n            if (view == null)\n            {\n                throw new ArgumentNullException(\"view\");\n            }\n            if (viewEngine == null)\n            {\n                throw new ArgumentNullException(\"viewEngine\");\n            }\n\n            View = view;\n            ViewEngine = viewEngine;\n        }\n\n        public IEnumerable<string> SearchedLocations { get; private set; }\n\n        public IView View { get; private set; }\n\n        public IViewEngine ViewEngine { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ViewEngines.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public static class ViewEngines\n    {\n        private static readonly ViewEngineCollection _engines = new ViewEngineCollection\n        {\n            new WebFormViewEngine(),\n            new RazorViewEngine(),\n        };\n\n        public static ViewEngineCollection Engines\n        {\n            get { return _engines; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ViewMasterPage.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Web.Mvc.Properties;\nusing System.Web.UI;\n\nnamespace System.Web.Mvc\n{\n    [FileLevelControlBuilder(typeof(ViewMasterPageControlBuilder))]\n    public class ViewMasterPage : MasterPage\n    {\n        public AjaxHelper<object> Ajax\n        {\n            get { return ViewPage.Ajax; }\n        }\n\n        public HtmlHelper<object> Html\n        {\n            get { return ViewPage.Html; }\n        }\n\n        public object Model\n        {\n            get { return ViewData.Model; }\n        }\n\n        public TempDataDictionary TempData\n        {\n            get { return ViewPage.TempData; }\n        }\n\n        public UrlHelper Url\n        {\n            get { return ViewPage.Url; }\n        }\n\n        public dynamic ViewBag\n        {\n            get { return ViewPage.ViewBag; }\n        }\n\n        public ViewContext ViewContext\n        {\n            get { return ViewPage.ViewContext; }\n        }\n\n        public ViewDataDictionary ViewData\n        {\n            get { return ViewPage.ViewData; }\n        }\n\n        internal ViewPage ViewPage\n        {\n            get\n            {\n                ViewPage viewPage = Page as ViewPage;\n                if (viewPage == null)\n                {\n                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, MvcResources.ViewMasterPage_RequiresViewPage));\n                }\n                return viewPage;\n            }\n        }\n\n        public HtmlTextWriter Writer\n        {\n            get { return ViewPage.Writer; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ViewMasterPageControlBuilder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.Web.UI;\n\nnamespace System.Web.Mvc\n{\n    internal sealed class ViewMasterPageControlBuilder : FileLevelMasterPageControlBuilder, IMvcControlBuilder\n    {\n        public string Inherits { get; set; }\n\n        public override void ProcessGeneratedCode(CodeCompileUnit codeCompileUnit, CodeTypeDeclaration baseType, CodeTypeDeclaration derivedType, CodeMemberMethod buildMethod, CodeMemberMethod dataBindingMethod)\n        {\n            if (!String.IsNullOrWhiteSpace(Inherits))\n            {\n                derivedType.BaseTypes[0] = new CodeTypeReference(Inherits);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ViewMasterPageOfTModel.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public class ViewMasterPage<TModel> : ViewMasterPage\n    {\n        private AjaxHelper<TModel> _ajaxHelper;\n        private HtmlHelper<TModel> _htmlHelper;\n        private ViewDataDictionary<TModel> _viewData;\n\n        public new AjaxHelper<TModel> Ajax\n        {\n            get\n            {\n                if (_ajaxHelper == null)\n                {\n                    _ajaxHelper = new AjaxHelper<TModel>(ViewContext, ViewPage);\n                }\n                return _ajaxHelper;\n            }\n        }\n\n        public new HtmlHelper<TModel> Html\n        {\n            get\n            {\n                if (_htmlHelper == null)\n                {\n                    _htmlHelper = new HtmlHelper<TModel>(ViewContext, ViewPage);\n                }\n                return _htmlHelper;\n            }\n        }\n\n        public new TModel Model\n        {\n            get { return ViewData.Model; }\n        }\n\n        public new ViewDataDictionary<TModel> ViewData\n        {\n            get\n            {\n                if (_viewData == null)\n                {\n                    _viewData = new ViewDataDictionary<TModel>(ViewPage.ViewData);\n                }\n                return _viewData;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ViewPage.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.IO;\nusing System.Text;\nusing System.Web.UI;\n\nnamespace System.Web.Mvc\n{\n    [FileLevelControlBuilder(typeof(ViewPageControlBuilder))]\n    public class ViewPage : Page, IViewDataContainer\n    {\n        [ThreadStatic]\n        private static int _nextId;\n\n        private DynamicViewDataDictionary _dynamicViewData;\n        private string _masterLocation;\n\n        private ViewDataDictionary _viewData;\n\n        public AjaxHelper<object> Ajax { get; set; }\n\n        public HtmlHelper<object> Html { get; set; }\n\n        public string MasterLocation\n        {\n            get { return _masterLocation ?? String.Empty; }\n            set { _masterLocation = value; }\n        }\n\n        public object Model\n        {\n            get { return ViewData.Model; }\n        }\n\n        public TempDataDictionary TempData\n        {\n            get { return ViewContext.TempData; }\n        }\n\n        public UrlHelper Url { get; set; }\n\n        public dynamic ViewBag\n        {\n            get\n            {\n                if (_dynamicViewData == null)\n                {\n                    _dynamicViewData = new DynamicViewDataDictionary(() => ViewData);\n                }\n                return _dynamicViewData;\n            }\n        }\n\n        public ViewContext ViewContext { get; set; }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"This is the mechanism by which the ViewPage gets its ViewDataDictionary object.\")]\n        public ViewDataDictionary ViewData\n        {\n            get\n            {\n                if (_viewData == null)\n                {\n                    SetViewData(new ViewDataDictionary());\n                }\n                return _viewData;\n            }\n            set { SetViewData(value); }\n        }\n\n        public HtmlTextWriter Writer { get; private set; }\n\n        public virtual void InitHelpers()\n        {\n            Ajax = new AjaxHelper<object>(ViewContext, this);\n            Html = new HtmlHelper<object>(ViewContext, this);\n            Url = new UrlHelper(ViewContext.RequestContext);\n        }\n\n        internal static string NextId()\n        {\n            return (++_nextId).ToString(CultureInfo.InvariantCulture);\n        }\n\n        protected override void OnPreInit(EventArgs e)\n        {\n            base.OnPreInit(e);\n\n            if (!String.IsNullOrEmpty(MasterLocation))\n            {\n                MasterPageFile = MasterLocation;\n            }\n        }\n\n        public override void ProcessRequest(HttpContext context)\n        {\n            // Tracing requires IDs to be unique.\n            ID = NextId();\n\n            base.ProcessRequest(context);\n        }\n\n        protected override void Render(HtmlTextWriter writer)\n        {\n            Writer = writer;\n            try\n            {\n                base.Render(writer);\n            }\n            finally\n            {\n                Writer = null;\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"The object is disposed in the finally block of the method\")]\n        public virtual void RenderView(ViewContext viewContext)\n        {\n            ViewContext = viewContext;\n            InitHelpers();\n\n            bool createdSwitchWriter = false;\n            SwitchWriter switchWriter = viewContext.HttpContext.Response.Output as SwitchWriter;\n\n            try\n            {\n                if (switchWriter == null)\n                {\n                    switchWriter = new SwitchWriter();\n                    createdSwitchWriter = true;\n                }\n\n                using (switchWriter.Scope(viewContext.Writer))\n                {\n                    if (createdSwitchWriter)\n                    {\n                        // It's safe to reset the _nextId within a Server.Execute() since it pushes a new TraceContext onto\n                        // the stack, so there won't be an ID conflict.\n                        int originalNextId = _nextId;\n                        try\n                        {\n                            _nextId = 0;\n                            viewContext.HttpContext.Server.Execute(HttpHandlerUtil.WrapForServerExecute(this), switchWriter, true /* preserveForm */);\n                        }\n                        finally\n                        {\n                            // Restore the original _nextId in case this isn't actually the outermost view, since resetting\n                            // the _nextId may now cause trace ID conflicts in the outer view.\n                            _nextId = originalNextId;\n                        }\n                    }\n                    else\n                    {\n                        ProcessRequest(HttpContext.Current);\n                    }\n                }\n            }\n            finally\n            {\n                if (createdSwitchWriter)\n                {\n                    switchWriter.Dispose();\n                }\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA1801:ReviewUnusedParameters\", MessageId = \"textWriter\", Justification = \"This method existed in MVC 1.0 and has been deprecated.\")]\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"This method existed in MVC 1.0 and has been deprecated.\")]\n        [Obsolete(\"The TextWriter is now provided by the ViewContext object passed to the RenderView method.\", true /* error */)]\n        public void SetTextWriter(TextWriter textWriter)\n        {\n            // this is now a no-op\n        }\n\n        protected virtual void SetViewData(ViewDataDictionary viewData)\n        {\n            _viewData = viewData;\n        }\n\n        internal class SwitchWriter : TextWriter\n        {\n            public SwitchWriter()\n                : base(CultureInfo.CurrentCulture)\n            {\n            }\n\n            public override Encoding Encoding\n            {\n                get { return InnerWriter.Encoding; }\n            }\n\n            public override IFormatProvider FormatProvider\n            {\n                get { return InnerWriter.FormatProvider; }\n            }\n\n            internal TextWriter InnerWriter { get; set; }\n\n            public override string NewLine\n            {\n                get { return InnerWriter.NewLine; }\n                set { InnerWriter.NewLine = value; }\n            }\n\n            public override void Close()\n            {\n                InnerWriter.Close();\n            }\n\n            public override void Flush()\n            {\n                InnerWriter.Flush();\n            }\n\n            public IDisposable Scope(TextWriter writer)\n            {\n                WriterScope scope = new WriterScope(this, InnerWriter);\n\n                try\n                {\n                    if (writer != this)\n                    {\n                        InnerWriter = writer;\n                    }\n\n                    return scope;\n                }\n                catch\n                {\n                    scope.Dispose();\n                    throw;\n                }\n            }\n\n            public override void Write(bool value)\n            {\n                InnerWriter.Write(value);\n            }\n\n            public override void Write(char value)\n            {\n                InnerWriter.Write(value);\n            }\n\n            public override void Write(char[] buffer)\n            {\n                InnerWriter.Write(buffer);\n            }\n\n            public override void Write(char[] buffer, int index, int count)\n            {\n                InnerWriter.Write(buffer, index, count);\n            }\n\n            public override void Write(decimal value)\n            {\n                InnerWriter.Write(value);\n            }\n\n            public override void Write(double value)\n            {\n                InnerWriter.Write(value);\n            }\n\n            public override void Write(float value)\n            {\n                InnerWriter.Write(value);\n            }\n\n            public override void Write(int value)\n            {\n                InnerWriter.Write(value);\n            }\n\n            public override void Write(long value)\n            {\n                InnerWriter.Write(value);\n            }\n\n            public override void Write(object value)\n            {\n                InnerWriter.Write(value);\n            }\n\n            public override void Write(string format, object arg0)\n            {\n                InnerWriter.Write(format, arg0);\n            }\n\n            public override void Write(string format, object arg0, object arg1)\n            {\n                InnerWriter.Write(format, arg0, arg1);\n            }\n\n            public override void Write(string format, object arg0, object arg1, object arg2)\n            {\n                InnerWriter.Write(format, arg0, arg1, arg2);\n            }\n\n            public override void Write(string format, params object[] arg)\n            {\n                InnerWriter.Write(format, arg);\n            }\n\n            public override void Write(string value)\n            {\n                InnerWriter.Write(value);\n            }\n\n            public override void Write(uint value)\n            {\n                InnerWriter.Write(value);\n            }\n\n            public override void Write(ulong value)\n            {\n                InnerWriter.Write(value);\n            }\n\n            public override void WriteLine()\n            {\n                InnerWriter.WriteLine();\n            }\n\n            public override void WriteLine(bool value)\n            {\n                InnerWriter.WriteLine(value);\n            }\n\n            public override void WriteLine(char value)\n            {\n                InnerWriter.WriteLine(value);\n            }\n\n            public override void WriteLine(char[] buffer)\n            {\n                InnerWriter.WriteLine(buffer);\n            }\n\n            public override void WriteLine(char[] buffer, int index, int count)\n            {\n                InnerWriter.WriteLine(buffer, index, count);\n            }\n\n            public override void WriteLine(decimal value)\n            {\n                InnerWriter.WriteLine(value);\n            }\n\n            public override void WriteLine(double value)\n            {\n                InnerWriter.WriteLine(value);\n            }\n\n            public override void WriteLine(float value)\n            {\n                InnerWriter.WriteLine(value);\n            }\n\n            public override void WriteLine(int value)\n            {\n                InnerWriter.WriteLine(value);\n            }\n\n            public override void WriteLine(long value)\n            {\n                InnerWriter.WriteLine(value);\n            }\n\n            public override void WriteLine(object value)\n            {\n                InnerWriter.WriteLine(value);\n            }\n\n            public override void WriteLine(string format, object arg0)\n            {\n                InnerWriter.WriteLine(format, arg0);\n            }\n\n            public override void WriteLine(string format, object arg0, object arg1)\n            {\n                InnerWriter.WriteLine(format, arg0, arg1);\n            }\n\n            public override void WriteLine(string format, object arg0, object arg1, object arg2)\n            {\n                InnerWriter.WriteLine(format, arg0, arg1, arg2);\n            }\n\n            public override void WriteLine(string format, params object[] arg)\n            {\n                InnerWriter.WriteLine(format, arg);\n            }\n\n            public override void WriteLine(string value)\n            {\n                InnerWriter.WriteLine(value);\n            }\n\n            public override void WriteLine(uint value)\n            {\n                InnerWriter.WriteLine(value);\n            }\n\n            public override void WriteLine(ulong value)\n            {\n                InnerWriter.WriteLine(value);\n            }\n\n            private sealed class WriterScope : IDisposable\n            {\n                private SwitchWriter _switchWriter;\n                private TextWriter _writerToRestore;\n\n                public WriterScope(SwitchWriter switchWriter, TextWriter writerToRestore)\n                {\n                    _switchWriter = switchWriter;\n                    _writerToRestore = writerToRestore;\n                }\n\n                public void Dispose()\n                {\n                    _switchWriter.InnerWriter = _writerToRestore;\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ViewPageControlBuilder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.Web.UI;\n\nnamespace System.Web.Mvc\n{\n    internal sealed class ViewPageControlBuilder : FileLevelPageControlBuilder, IMvcControlBuilder\n    {\n        public string Inherits { get; set; }\n\n        public override void ProcessGeneratedCode(CodeCompileUnit codeCompileUnit, CodeTypeDeclaration baseType, CodeTypeDeclaration derivedType, CodeMemberMethod buildMethod, CodeMemberMethod dataBindingMethod)\n        {\n            if (!String.IsNullOrWhiteSpace(Inherits))\n            {\n                derivedType.BaseTypes[0] = new CodeTypeReference(Inherits);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ViewPageOfTModel.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.Mvc\n{\n    public class ViewPage<TModel> : ViewPage\n    {\n        private ViewDataDictionary<TModel> _viewData;\n\n        public new AjaxHelper<TModel> Ajax { get; set; }\n\n        public new HtmlHelper<TModel> Html { get; set; }\n\n        public new TModel Model\n        {\n            get { return ViewData.Model; }\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"This is settable for unit testing purposes\")]\n        public new ViewDataDictionary<TModel> ViewData\n        {\n            get\n            {\n                if (_viewData == null)\n                {\n                    SetViewData(new ViewDataDictionary<TModel>());\n                }\n                return _viewData;\n            }\n            set { SetViewData(value); }\n        }\n\n        public override void InitHelpers()\n        {\n            base.InitHelpers();\n\n            Ajax = new AjaxHelper<TModel>(ViewContext, this);\n            Html = new HtmlHelper<TModel>(ViewContext, this);\n        }\n\n        protected override void SetViewData(ViewDataDictionary viewData)\n        {\n            _viewData = new ViewDataDictionary<TModel>(viewData);\n\n            base.SetViewData(_viewData);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ViewResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Text;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    public class ViewResult : ViewResultBase\n    {\n        private string _masterName;\n\n        public string MasterName\n        {\n            get { return _masterName ?? String.Empty; }\n            set { _masterName = value; }\n        }\n\n        protected override ViewEngineResult FindView(ControllerContext context)\n        {\n            ViewEngineResult result = ViewEngineCollection.FindView(context, ViewName, MasterName);\n            if (result.View != null)\n            {\n                return result;\n            }\n\n            // we need to generate an exception containing all the locations we searched\n            StringBuilder locationsText = new StringBuilder();\n            foreach (string location in result.SearchedLocations)\n            {\n                locationsText.AppendLine();\n                locationsText.Append(location);\n            }\n            throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,\n                                                              MvcResources.Common_ViewNotFound, ViewName, locationsText));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ViewResultBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.IO;\n\nnamespace System.Web.Mvc\n{\n    public abstract class ViewResultBase : ActionResult\n    {\n        private DynamicViewDataDictionary _dynamicViewData;\n        private TempDataDictionary _tempData;\n        private ViewDataDictionary _viewData;\n        private ViewEngineCollection _viewEngineCollection;\n        private string _viewName;\n\n        public object Model\n        {\n            get { return ViewData.Model; }\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"This entire type is meant to be mutable.\")]\n        public TempDataDictionary TempData\n        {\n            get\n            {\n                if (_tempData == null)\n                {\n                    _tempData = new TempDataDictionary();\n                }\n                return _tempData;\n            }\n            set { _tempData = value; }\n        }\n\n        public IView View { get; set; }\n\n        public dynamic ViewBag\n        {\n            get\n            {\n                if (_dynamicViewData == null)\n                {\n                    _dynamicViewData = new DynamicViewDataDictionary(() => ViewData);\n                }\n                return _dynamicViewData;\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"This entire type is meant to be mutable.\")]\n        public ViewDataDictionary ViewData\n        {\n            get\n            {\n                if (_viewData == null)\n                {\n                    _viewData = new ViewDataDictionary();\n                }\n                return _viewData;\n            }\n            set { _viewData = value; }\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"This entire type is meant to be mutable.\")]\n        public ViewEngineCollection ViewEngineCollection\n        {\n            get { return _viewEngineCollection ?? ViewEngines.Engines; }\n            set { _viewEngineCollection = value; }\n        }\n\n        public string ViewName\n        {\n            get { return _viewName ?? String.Empty; }\n            set { _viewName = value; }\n        }\n\n        public override void ExecuteResult(ControllerContext context)\n        {\n            if (context == null)\n            {\n                throw new ArgumentNullException(\"context\");\n            }\n            if (String.IsNullOrEmpty(ViewName))\n            {\n                ViewName = context.RouteData.GetRequiredString(\"action\");\n            }\n\n            ViewEngineResult result = null;\n\n            if (View == null)\n            {\n                result = FindView(context);\n                View = result.View;\n            }\n\n            TextWriter writer = context.HttpContext.Response.Output;\n            ViewContext viewContext = new ViewContext(context, View, ViewData, TempData, writer);\n            View.Render(viewContext, writer);\n\n            if (result != null)\n            {\n                result.ViewEngine.ReleaseView(context, View);\n            }\n        }\n\n        protected abstract ViewEngineResult FindView(ControllerContext context);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ViewStartPage.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc.Properties;\nusing System.Web.WebPages;\n\nnamespace System.Web.Mvc\n{\n    public abstract class ViewStartPage : StartPage, IViewStartPageChild\n    {\n        private IViewStartPageChild _viewStartPageChild;\n\n        public HtmlHelper<object> Html\n        {\n            get { return ViewStartPageChild.Html; }\n        }\n\n        public UrlHelper Url\n        {\n            get { return ViewStartPageChild.Url; }\n        }\n\n        public ViewContext ViewContext\n        {\n            get { return ViewStartPageChild.ViewContext; }\n        }\n\n        internal IViewStartPageChild ViewStartPageChild\n        {\n            get\n            {\n                if (_viewStartPageChild == null)\n                {\n                    IViewStartPageChild child = ChildPage as IViewStartPageChild;\n                    if (child == null)\n                    {\n                        throw new InvalidOperationException(MvcResources.ViewStartPage_RequiresMvcRazorView);\n                    }\n                    _viewStartPageChild = child;\n                }\n\n                return _viewStartPageChild;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ViewTemplateUserControl.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public class ViewTemplateUserControl : ViewTemplateUserControl<object>\n    {\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ViewTemplateUserControlOfTModel.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public class ViewTemplateUserControl<TModel> : ViewUserControl<TModel>\n    {\n        protected string FormattedModelValue\n        {\n            get { return ViewData.TemplateInfo.FormattedModelValue.ToString(); }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ViewType.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Web.UI;\n\nnamespace System.Web.Mvc\n{\n    [ControlBuilder(typeof(ViewTypeControlBuilder))]\n    [NonVisualControl]\n    public class ViewType : Control\n    {\n        private string _typeName;\n\n        [DefaultValue(\"\")]\n        public string TypeName\n        {\n            get { return _typeName ?? String.Empty; }\n            set { _typeName = value; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ViewTypeControlBuilder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.Collections;\nusing System.Web.UI;\n\nnamespace System.Web.Mvc\n{\n    internal sealed class ViewTypeControlBuilder : ControlBuilder\n    {\n        private string _typeName;\n\n        public override void Init(TemplateParser parser, ControlBuilder parentBuilder, Type type, string tagName, string id, IDictionary attribs)\n        {\n            base.Init(parser, parentBuilder, type, tagName, id, attribs);\n\n            _typeName = (string)attribs[\"typename\"];\n        }\n\n        public override void ProcessGeneratedCode(\n            CodeCompileUnit codeCompileUnit,\n            CodeTypeDeclaration baseType,\n            CodeTypeDeclaration derivedType,\n            CodeMemberMethod buildMethod,\n            CodeMemberMethod dataBindingMethod)\n        {\n            // Override the view's base type with the explicit base type\n            derivedType.BaseTypes[0] = new CodeTypeReference(_typeName);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ViewTypeParserFilter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.UI;\n\nnamespace System.Web.Mvc\n{\n    // This class is referenced dynamically by the web.config built by project templates.\n    // Do not delete this class based on it not being statically referenced by product code.\n\n    internal class ViewTypeParserFilter : PageParserFilter\n    {\n        private static Dictionary<string, Type> _directiveBaseTypeMappings = new Dictionary<string, Type>\n        {\n            { \"page\", typeof(ViewPage) },\n            { \"control\", typeof(ViewUserControl) },\n            { \"master\", typeof(ViewMasterPage) },\n        };\n\n        private string _inherits;\n\n        public ViewTypeParserFilter()\n        {\n        }\n\n        public override bool AllowCode\n        {\n            get { return true; }\n        }\n\n        public override int NumberOfControlsAllowed\n        {\n            get { return -1; }\n        }\n\n        public override int NumberOfDirectDependenciesAllowed\n        {\n            get { return -1; }\n        }\n\n        public override int TotalNumberOfDependenciesAllowed\n        {\n            get { return -1; }\n        }\n\n        public override void PreprocessDirective(string directiveName, IDictionary attributes)\n        {\n            base.PreprocessDirective(directiveName, attributes);\n\n            Type baseType;\n            if (_directiveBaseTypeMappings.TryGetValue(directiveName, out baseType))\n            {\n                string inheritsAttribute = attributes[\"inherits\"] as string;\n\n                // Since the ASP.NET page parser doesn't understand native generic syntax, we\n                // need to swap out whatever the user provided with the default base type for\n                // the given directive (page vs. control vs. master). We stash the old value\n                // and swap it back in inside the control builder. Our \"is this generic?\"\n                // check here really only works for C# and VB.NET, since we're checking for\n                // < or ( in the type name.\n                //\n                // We only change generic directives, because doing so breaks back-compat\n                // for property setters on @Page, @Control, and @Master directives. The user\n                // can work around this breaking behavior by using a non-generic inherits\n                // directive, or by using the CLR syntax for generic type names.\n\n                if (inheritsAttribute != null && inheritsAttribute.IndexOfAny(new[] { '<', '(' }) > 0)\n                {\n                    attributes[\"inherits\"] = baseType.FullName;\n                    _inherits = inheritsAttribute;\n                }\n            }\n        }\n\n        public override void ParseComplete(ControlBuilder rootBuilder)\n        {\n            base.ParseComplete(rootBuilder);\n\n            IMvcControlBuilder builder = rootBuilder as IMvcControlBuilder;\n            if (builder != null)\n            {\n                builder.Inherits = _inherits;\n            }\n        }\n\n        // Everything else in this class is unrelated to our 'inherits' handling.\n        // Since PageParserFilter blocks everything by default, we need to unblock it\n\n        public override bool AllowBaseType(Type baseType)\n        {\n            return true;\n        }\n\n        public override bool AllowControl(Type controlType, ControlBuilder builder)\n        {\n            return true;\n        }\n\n        public override bool AllowVirtualReference(string referenceVirtualPath, VirtualReferenceType referenceType)\n        {\n            return true;\n        }\n\n        public override bool AllowServerSideInclude(string includeVirtualPath)\n        {\n            return true;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ViewUserControl.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.IO;\nusing System.Web.Mvc.Properties;\nusing System.Web.UI;\n\nnamespace System.Web.Mvc\n{\n    [FileLevelControlBuilder(typeof(ViewUserControlControlBuilder))]\n    public class ViewUserControl : UserControl, IViewDataContainer\n    {\n        private AjaxHelper<object> _ajaxHelper;\n        private DynamicViewDataDictionary _dynamicViewData;\n        private HtmlHelper<object> _htmlHelper;\n        private ViewContext _viewContext;\n        private ViewDataDictionary _viewData;\n        private string _viewDataKey;\n\n        public AjaxHelper<object> Ajax\n        {\n            get\n            {\n                if (_ajaxHelper == null)\n                {\n                    _ajaxHelper = new AjaxHelper<object>(ViewContext, this);\n                }\n                return _ajaxHelper;\n            }\n        }\n\n        public HtmlHelper<object> Html\n        {\n            get\n            {\n                if (_htmlHelper == null)\n                {\n                    _htmlHelper = new HtmlHelper<object>(ViewContext, this);\n                }\n                return _htmlHelper;\n            }\n        }\n\n        public object Model\n        {\n            get { return ViewData.Model; }\n        }\n\n        public TempDataDictionary TempData\n        {\n            get { return ViewPage.TempData; }\n        }\n\n        public UrlHelper Url\n        {\n            get { return ViewPage.Url; }\n        }\n\n        public dynamic ViewBag\n        {\n            get\n            {\n                if (_dynamicViewData == null)\n                {\n                    _dynamicViewData = new DynamicViewDataDictionary(() => ViewData);\n                }\n                return _dynamicViewData;\n            }\n        }\n\n        [Browsable(false)]\n        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\n        public ViewContext ViewContext\n        {\n            get { return _viewContext ?? ViewPage.ViewContext; }\n            set { _viewContext = value; }\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"This is the mechanism by which the ViewUserControl gets its ViewDataDictionary object.\")]\n        [Browsable(false)]\n        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\n        public ViewDataDictionary ViewData\n        {\n            get\n            {\n                EnsureViewData();\n                return _viewData;\n            }\n            set { SetViewData(value); }\n        }\n\n        [DefaultValue(\"\")]\n        public string ViewDataKey\n        {\n            get { return _viewDataKey ?? String.Empty; }\n            set { _viewDataKey = value; }\n        }\n\n        internal ViewPage ViewPage\n        {\n            get\n            {\n                ViewPage viewPage = Page as ViewPage;\n                if (viewPage == null)\n                {\n                    throw new InvalidOperationException(MvcResources.ViewUserControl_RequiresViewPage);\n                }\n                return viewPage;\n            }\n        }\n\n        public HtmlTextWriter Writer\n        {\n            get { return ViewPage.Writer; }\n        }\n\n        protected virtual void SetViewData(ViewDataDictionary viewData)\n        {\n            _viewData = viewData;\n        }\n\n        protected void EnsureViewData()\n        {\n            if (_viewData != null)\n            {\n                return;\n            }\n\n            // Get the ViewData for this ViewUserControl, optionally using the specified ViewDataKey\n            IViewDataContainer vdc = GetViewDataContainer(this);\n            if (vdc == null)\n            {\n                throw new InvalidOperationException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        MvcResources.ViewUserControl_RequiresViewDataProvider,\n                        AppRelativeVirtualPath));\n            }\n\n            ViewDataDictionary myViewData = vdc.ViewData;\n\n            // If we have a ViewDataKey, try to extract the ViewData from the dictionary, otherwise\n            // return the container's ViewData.\n            if (!String.IsNullOrEmpty(ViewDataKey))\n            {\n                object target = myViewData.Eval(ViewDataKey);\n                myViewData = target as ViewDataDictionary ?? new ViewDataDictionary(myViewData) { Model = target };\n            }\n\n            SetViewData(myViewData);\n        }\n\n        private static IViewDataContainer GetViewDataContainer(Control control)\n        {\n            // Walk up the control hierarchy until we find someone that implements IViewDataContainer\n            while (control != null)\n            {\n                control = control.Parent;\n                IViewDataContainer vdc = control as IViewDataContainer;\n                if (vdc != null)\n                {\n                    return vdc;\n                }\n            }\n            return null;\n        }\n\n        public virtual void RenderView(ViewContext viewContext)\n        {\n            using (ViewUserControlContainerPage containerPage = new ViewUserControlContainerPage(this))\n            {\n                RenderViewAndRestoreContentType(containerPage, viewContext);\n            }\n        }\n\n        internal static void RenderViewAndRestoreContentType(ViewPage containerPage, ViewContext viewContext)\n        {\n            // We need to restore the Content-Type since Page.SetIntrinsics() will reset it. It's not possible\n            // to work around the call to SetIntrinsics() since the control's render method requires the\n            // containing page's Response property to be non-null, and SetIntrinsics() is the only way to set\n            // this.\n            string savedContentType = viewContext.HttpContext.Response.ContentType;\n            containerPage.RenderView(viewContext);\n            viewContext.HttpContext.Response.ContentType = savedContentType;\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA1801:ReviewUnusedParameters\", MessageId = \"textWriter\", Justification = \"This method existed in MVC 1.0 and has been deprecated.\")]\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"This method existed in MVC 1.0 and has been deprecated.\")]\n        [Obsolete(\"The TextWriter is now provided by the ViewContext object passed to the RenderView method.\", true /* error */)]\n        public void SetTextWriter(TextWriter textWriter)\n        {\n            // this is now a no-op\n        }\n\n        private sealed class ViewUserControlContainerPage : ViewPage\n        {\n            private readonly ViewUserControl _userControl;\n\n            public ViewUserControlContainerPage(ViewUserControl userControl)\n            {\n                _userControl = userControl;\n            }\n\n            public override void ProcessRequest(HttpContext context)\n            {\n                _userControl.ID = NextId();\n                Controls.Add(_userControl);\n\n                base.ProcessRequest(context);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ViewUserControlControlBuilder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.Web.UI;\n\nnamespace System.Web.Mvc\n{\n    internal sealed class ViewUserControlControlBuilder : FileLevelUserControlBuilder, IMvcControlBuilder\n    {\n        public string Inherits { get; set; }\n\n        public override void ProcessGeneratedCode(CodeCompileUnit codeCompileUnit, CodeTypeDeclaration baseType, CodeTypeDeclaration derivedType, CodeMemberMethod buildMethod, CodeMemberMethod dataBindingMethod)\n        {\n            if (!String.IsNullOrWhiteSpace(Inherits))\n            {\n                derivedType.BaseTypes[0] = new CodeTypeReference(Inherits);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/ViewUserControlOfTModel.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.Mvc\n{\n    public class ViewUserControl<TModel> : ViewUserControl\n    {\n        private AjaxHelper<TModel> _ajaxHelper;\n        private HtmlHelper<TModel> _htmlHelper;\n        private ViewDataDictionary<TModel> _viewData;\n\n        public new AjaxHelper<TModel> Ajax\n        {\n            get\n            {\n                if (_ajaxHelper == null)\n                {\n                    _ajaxHelper = new AjaxHelper<TModel>(ViewContext, this);\n                }\n                return _ajaxHelper;\n            }\n        }\n\n        public new HtmlHelper<TModel> Html\n        {\n            get\n            {\n                if (_htmlHelper == null)\n                {\n                    _htmlHelper = new HtmlHelper<TModel>(ViewContext, this);\n                }\n                return _htmlHelper;\n            }\n        }\n\n        public new TModel Model\n        {\n            get { return ViewData.Model; }\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"This is settable for unit testing purposes\")]\n        public new ViewDataDictionary<TModel> ViewData\n        {\n            get\n            {\n                EnsureViewData();\n                return _viewData;\n            }\n            set { SetViewData(value); }\n        }\n\n        protected override void SetViewData(ViewDataDictionary viewData)\n        {\n            _viewData = new ViewDataDictionary<TModel>(viewData);\n\n            base.SetViewData(_viewData);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/VirtualPathProviderViewEngine.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq;\nusing System.Web.Hosting;\nusing System.Web.Mvc.Properties;\nusing System.Web.WebPages;\n\nnamespace System.Web.Mvc\n{\n    public abstract class VirtualPathProviderViewEngine : IViewEngine\n    {\n        // format is \":ViewCacheEntry:{cacheType}:{prefix}:{name}:{controllerName}:{areaName}:\"\n        private const string CacheKeyFormat = \":ViewCacheEntry:{0}:{1}:{2}:{3}:{4}:\";\n        private const string CacheKeyPrefixMaster = \"Master\";\n        private const string CacheKeyPrefixPartial = \"Partial\";\n        private const string CacheKeyPrefixView = \"View\";\n        private static readonly string[] _emptyLocations = new string[0];\n        private DisplayModeProvider _displayModeProvider;\n\n        private Func<VirtualPathProvider> _vppFunc = () => HostingEnvironment.VirtualPathProvider;\n        internal Func<string, string> GetExtensionThunk = VirtualPathUtility.GetExtension;\n        private IViewLocationCache _viewLocationCache;\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1819:PropertiesShouldNotReturnArrays\", Justification = \"This is a shipped API\")]\n        public string[] AreaMasterLocationFormats { get; set; }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1819:PropertiesShouldNotReturnArrays\", Justification = \"This is a shipped API\")]\n        public string[] AreaPartialViewLocationFormats { get; set; }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1819:PropertiesShouldNotReturnArrays\", Justification = \"This is a shipped API\")]\n        public string[] AreaViewLocationFormats { get; set; }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1819:PropertiesShouldNotReturnArrays\", Justification = \"This is a shipped API\")]\n        public string[] FileExtensions { get; set; }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1819:PropertiesShouldNotReturnArrays\", Justification = \"This is a shipped API\")]\n        public string[] MasterLocationFormats { get; set; }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1819:PropertiesShouldNotReturnArrays\", Justification = \"This is a shipped API\")]\n        public string[] PartialViewLocationFormats { get; set; }\n\n        // Neither DefaultViewLocationCache.Null nor a DefaultViewLocationCache instance maintain internal state. Fine\n        // if multiple threads race to initialize _viewLocationCache.\n        public IViewLocationCache ViewLocationCache\n        {\n            get\n            {\n                if (_viewLocationCache == null)\n                {\n                    if (HttpContext.Current == null || HttpContext.Current.IsDebuggingEnabled)\n                    {\n                        _viewLocationCache = DefaultViewLocationCache.Null;\n                    }\n                    else\n                    {\n                        _viewLocationCache = new DefaultViewLocationCache();\n                    }\n                }\n\n                return _viewLocationCache;\n            }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.ArgumentNull(\"value\");\n                }\n\n                _viewLocationCache = value;\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1819:PropertiesShouldNotReturnArrays\", Justification = \"This is a shipped API\")]\n        public string[] ViewLocationFormats { get; set; }\n\n        // Likely exists for testing only\n        protected VirtualPathProvider VirtualPathProvider\n        {\n            get { return _vppFunc(); }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.ArgumentNull(\"value\");\n                }\n\n                _vppFunc = () => value;\n            }\n        }\n\n        // Provided for testing only; setter used in BuildManagerViewEngine but only for test scenarios\n        internal Func<VirtualPathProvider> VirtualPathProviderFunc\n        {\n            get { return _vppFunc; }\n            set\n            {\n                if (value == null)\n                {\n                    throw Error.ArgumentNull(\"value\");\n                }\n\n                _vppFunc = value;\n            }\n        }\n\n        protected internal DisplayModeProvider DisplayModeProvider\n        {\n            get { return _displayModeProvider ?? DisplayModeProvider.Instance; }\n            set { _displayModeProvider = value; }\n        }\n\n        internal virtual string CreateCacheKey(string prefix, string name, string controllerName, string areaName)\n        {\n            return String.Format(CultureInfo.InvariantCulture, CacheKeyFormat,\n                                 GetType().AssemblyQualifiedName, prefix, name, controllerName, areaName);\n        }\n\n        internal static string AppendDisplayModeToCacheKey(string cacheKey, string displayMode)\n        {\n            // key format is \":ViewCacheEntry:{cacheType}:{prefix}:{name}:{controllerName}:{areaName}:\"\n            // so append \"{displayMode}:\" to the key\n            return cacheKey + displayMode + \":\";\n        }\n\n        protected abstract IView CreatePartialView(ControllerContext controllerContext, string partialPath);\n\n        protected abstract IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath);\n\n        protected virtual bool FileExists(ControllerContext controllerContext, string virtualPath)\n        {\n            return VirtualPathProvider.FileExists(virtualPath);\n        }\n\n        public virtual ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n            if (String.IsNullOrEmpty(partialViewName))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"partialViewName\");\n            }\n\n            string[] searched;\n            string controllerName = controllerContext.RouteData.GetRequiredString(\"controller\");\n            string partialPath = GetPath(controllerContext, PartialViewLocationFormats, AreaPartialViewLocationFormats, \"PartialViewLocationFormats\", partialViewName, controllerName, CacheKeyPrefixPartial, useCache, out searched);\n\n            if (String.IsNullOrEmpty(partialPath))\n            {\n                return new ViewEngineResult(searched);\n            }\n\n            return new ViewEngineResult(CreatePartialView(controllerContext, partialPath), this);\n        }\n\n        public virtual ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)\n        {\n            if (controllerContext == null)\n            {\n                throw new ArgumentNullException(\"controllerContext\");\n            }\n            if (String.IsNullOrEmpty(viewName))\n            {\n                throw new ArgumentException(MvcResources.Common_NullOrEmpty, \"viewName\");\n            }\n\n            string[] viewLocationsSearched;\n            string[] masterLocationsSearched;\n\n            string controllerName = controllerContext.RouteData.GetRequiredString(\"controller\");\n            string viewPath = GetPath(controllerContext, ViewLocationFormats, AreaViewLocationFormats, \"ViewLocationFormats\", viewName, controllerName, CacheKeyPrefixView, useCache, out viewLocationsSearched);\n            string masterPath = GetPath(controllerContext, MasterLocationFormats, AreaMasterLocationFormats, \"MasterLocationFormats\", masterName, controllerName, CacheKeyPrefixMaster, useCache, out masterLocationsSearched);\n\n            if (String.IsNullOrEmpty(viewPath) || (String.IsNullOrEmpty(masterPath) && !String.IsNullOrEmpty(masterName)))\n            {\n                return new ViewEngineResult(viewLocationsSearched.Union(masterLocationsSearched));\n            }\n\n            return new ViewEngineResult(CreateView(controllerContext, viewPath, masterPath), this);\n        }\n\n        private string GetPath(ControllerContext controllerContext, string[] locations, string[] areaLocations, string locationsPropertyName, string name, string controllerName, string cacheKeyPrefix, bool useCache, out string[] searchedLocations)\n        {\n            searchedLocations = _emptyLocations;\n\n            if (String.IsNullOrEmpty(name))\n            {\n                return String.Empty;\n            }\n\n            string areaName = AreaHelpers.GetAreaName(controllerContext.RouteData);\n            bool usingAreas = !String.IsNullOrEmpty(areaName);\n            List<ViewLocation> viewLocations = GetViewLocations(locations, (usingAreas) ? areaLocations : null);\n\n            if (viewLocations.Count == 0)\n            {\n                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,\n                                                                  MvcResources.Common_PropertyCannotBeNullOrEmpty, locationsPropertyName));\n            }\n\n            bool nameRepresentsPath = IsSpecificPath(name);\n            string cacheKey = CreateCacheKey(cacheKeyPrefix, name, (nameRepresentsPath) ? String.Empty : controllerName, areaName);\n\n            if (useCache)\n            {\n                // Only look at cached display modes that can handle the context.\n                IEnumerable<IDisplayMode> possibleDisplayModes = DisplayModeProvider.GetAvailableDisplayModesForContext(controllerContext.HttpContext, controllerContext.DisplayMode);\n                foreach (IDisplayMode displayMode in possibleDisplayModes)\n                {\n                    string cachedLocation = ViewLocationCache.GetViewLocation(controllerContext.HttpContext, AppendDisplayModeToCacheKey(cacheKey, displayMode.DisplayModeId));\n\n                    if (cachedLocation == null)\n                    {\n                        // If any matching display mode location is not in the cache, fall back to the uncached behavior, which will repopulate all of our caches.\n                        return null;\n                    }\n\n                    // A non-empty cachedLocation indicates that we have a matching file on disk. Return that result.\n                    if (cachedLocation.Length > 0)\n                    {\n                        if (controllerContext.DisplayMode == null)\n                        {\n                            controllerContext.DisplayMode = displayMode;\n                        }\n\n                        return cachedLocation;\n                    }\n                    // An empty cachedLocation value indicates that we don't have a matching file on disk. Keep going down the list of possible display modes.\n                }\n\n                // GetPath is called again without using the cache.\n                return null;\n            }\n            else\n            {\n                return nameRepresentsPath\n                    ? GetPathFromSpecificName(controllerContext, name, cacheKey, ref searchedLocations)\n                    : GetPathFromGeneralName(controllerContext, viewLocations, name, controllerName, areaName, cacheKey, ref searchedLocations);\n            }\n        }\n\n        private string GetPathFromGeneralName(ControllerContext controllerContext, List<ViewLocation> locations, string name, string controllerName, string areaName, string cacheKey, ref string[] searchedLocations)\n        {\n            string result = String.Empty;\n            searchedLocations = new string[locations.Count];\n\n            for (int i = 0; i < locations.Count; i++)\n            {\n                ViewLocation location = locations[i];\n                string virtualPath = location.Format(name, controllerName, areaName);\n                DisplayInfo virtualPathDisplayInfo = DisplayModeProvider.GetDisplayInfoForVirtualPath(virtualPath, controllerContext.HttpContext, path => FileExists(controllerContext, path), controllerContext.DisplayMode);\n\n                if (virtualPathDisplayInfo != null)\n                {\n                    string resolvedVirtualPath = virtualPathDisplayInfo.FilePath;\n\n                    searchedLocations = _emptyLocations;\n                    result = resolvedVirtualPath;\n                    ViewLocationCache.InsertViewLocation(controllerContext.HttpContext, AppendDisplayModeToCacheKey(cacheKey, virtualPathDisplayInfo.DisplayMode.DisplayModeId), result);\n\n                    if (controllerContext.DisplayMode == null)\n                    {\n                        controllerContext.DisplayMode = virtualPathDisplayInfo.DisplayMode;\n                    }\n\n                    // Populate the cache for all other display modes. We want to cache both file system hits and misses so that we can distinguish\n                    // in future requests whether a file's status was evicted from the cache (null value) or if the file doesn't exist (empty string).\n                    IEnumerable<IDisplayMode> allDisplayModes = DisplayModeProvider.Modes;\n                    foreach (IDisplayMode displayMode in allDisplayModes)\n                    {\n                        if (displayMode.DisplayModeId != virtualPathDisplayInfo.DisplayMode.DisplayModeId)\n                        {\n                            DisplayInfo displayInfoToCache = displayMode.GetDisplayInfo(controllerContext.HttpContext, virtualPath, virtualPathExists: path => FileExists(controllerContext, path));\n\n                            string cacheValue = String.Empty;\n                            if (displayInfoToCache != null && displayInfoToCache.FilePath != null)\n                            {\n                                cacheValue = displayInfoToCache.FilePath;\n                            }\n                            ViewLocationCache.InsertViewLocation(controllerContext.HttpContext, AppendDisplayModeToCacheKey(cacheKey, displayMode.DisplayModeId), cacheValue);\n                        }\n                    }\n                    break;\n                }\n\n                searchedLocations[i] = virtualPath;\n            }\n\n            return result;\n        }\n\n        private string GetPathFromSpecificName(ControllerContext controllerContext, string name, string cacheKey, ref string[] searchedLocations)\n        {\n            string result = name;\n\n            if (!(FilePathIsSupported(name) && FileExists(controllerContext, name)))\n            {\n                result = String.Empty;\n                searchedLocations = new[] { name };\n            }\n\n            ViewLocationCache.InsertViewLocation(controllerContext.HttpContext, cacheKey, result);\n            return result;\n        }\n\n        private bool FilePathIsSupported(string virtualPath)\n        {\n            if (FileExtensions == null)\n            {\n                // legacy behavior for custom ViewEngine that might not set the FileExtensions property\n                return true;\n            }\n            else\n            {\n                // get rid of the '.' because the FileExtensions property expects extensions withouth a dot.\n                string extension = GetExtensionThunk(virtualPath).TrimStart('.');\n                return FileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase);\n            }\n        }\n\n        private static List<ViewLocation> GetViewLocations(string[] viewLocationFormats, string[] areaViewLocationFormats)\n        {\n            List<ViewLocation> allLocations = new List<ViewLocation>();\n\n            if (areaViewLocationFormats != null)\n            {\n                foreach (string areaViewLocationFormat in areaViewLocationFormats)\n                {\n                    allLocations.Add(new AreaAwareViewLocation(areaViewLocationFormat));\n                }\n            }\n\n            if (viewLocationFormats != null)\n            {\n                foreach (string viewLocationFormat in viewLocationFormats)\n                {\n                    allLocations.Add(new ViewLocation(viewLocationFormat));\n                }\n            }\n\n            return allLocations;\n        }\n\n        private static bool IsSpecificPath(string name)\n        {\n            char c = name[0];\n            return (c == '~' || c == '/');\n        }\n\n        public virtual void ReleaseView(ControllerContext controllerContext, IView view)\n        {\n            IDisposable disposable = view as IDisposable;\n            if (disposable != null)\n            {\n                disposable.Dispose();\n            }\n        }\n\n        private class AreaAwareViewLocation : ViewLocation\n        {\n            public AreaAwareViewLocation(string virtualPathFormatString)\n                : base(virtualPathFormatString)\n            {\n            }\n\n            public override string Format(string viewName, string controllerName, string areaName)\n            {\n                return String.Format(CultureInfo.InvariantCulture, _virtualPathFormatString, viewName, controllerName, areaName);\n            }\n        }\n\n        private class ViewLocation\n        {\n            protected string _virtualPathFormatString;\n\n            public ViewLocation(string virtualPathFormatString)\n            {\n                _virtualPathFormatString = virtualPathFormatString;\n            }\n\n            public virtual string Format(string viewName, string controllerName, string areaName)\n            {\n                return String.Format(CultureInfo.InvariantCulture, _virtualPathFormatString, viewName, controllerName);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/WebFormView.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.IO;\nusing System.Web.Mvc.Properties;\n\nnamespace System.Web.Mvc\n{\n    public class WebFormView : BuildManagerCompiledView\n    {\n        public WebFormView(ControllerContext controllerContext, string viewPath)\n            : this(controllerContext, viewPath, null, null)\n        {\n        }\n\n        public WebFormView(ControllerContext controllerContext, string viewPath, string masterPath)\n            : this(controllerContext, viewPath, masterPath, null)\n        {\n        }\n\n        public WebFormView(ControllerContext controllerContext, string viewPath, string masterPath, IViewPageActivator viewPageActivator)\n            : base(controllerContext, viewPath, viewPageActivator)\n        {\n            MasterPath = masterPath ?? String.Empty;\n        }\n\n        public string MasterPath { get; private set; }\n\n        protected override void RenderView(ViewContext viewContext, TextWriter writer, object instance)\n        {\n            ViewPage viewPage = instance as ViewPage;\n            if (viewPage != null)\n            {\n                RenderViewPage(viewContext, viewPage);\n                return;\n            }\n\n            ViewUserControl viewUserControl = instance as ViewUserControl;\n            if (viewUserControl != null)\n            {\n                RenderViewUserControl(viewContext, viewUserControl);\n                return;\n            }\n\n            throw new InvalidOperationException(\n                String.Format(\n                    CultureInfo.CurrentCulture,\n                    MvcResources.WebFormViewEngine_WrongViewBase,\n                    ViewPath));\n        }\n\n        private void RenderViewPage(ViewContext context, ViewPage page)\n        {\n            if (!String.IsNullOrEmpty(MasterPath))\n            {\n                page.MasterLocation = MasterPath;\n            }\n\n            page.ViewData = context.ViewData;\n            page.RenderView(context);\n        }\n\n        private void RenderViewUserControl(ViewContext context, ViewUserControl control)\n        {\n            if (!String.IsNullOrEmpty(MasterPath))\n            {\n                throw new InvalidOperationException(MvcResources.WebFormViewEngine_UserControlCannotHaveMaster);\n            }\n\n            control.ViewData = context.ViewData;\n            control.RenderView(context);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/WebFormViewEngine.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public class WebFormViewEngine : BuildManagerViewEngine\n    {\n        public WebFormViewEngine()\n            : this(null)\n        {\n        }\n\n        public WebFormViewEngine(IViewPageActivator viewPageActivator)\n            : base(viewPageActivator)\n        {\n            MasterLocationFormats = new[]\n            {\n                \"~/Views/{1}/{0}.master\",\n                \"~/Views/Shared/{0}.master\"\n            };\n\n            AreaMasterLocationFormats = new[]\n            {\n                \"~/Areas/{2}/Views/{1}/{0}.master\",\n                \"~/Areas/{2}/Views/Shared/{0}.master\",\n            };\n\n            ViewLocationFormats = new[]\n            {\n                \"~/Views/{1}/{0}.aspx\",\n                \"~/Views/{1}/{0}.ascx\",\n                \"~/Views/Shared/{0}.aspx\",\n                \"~/Views/Shared/{0}.ascx\"\n            };\n\n            AreaViewLocationFormats = new[]\n            {\n                \"~/Areas/{2}/Views/{1}/{0}.aspx\",\n                \"~/Areas/{2}/Views/{1}/{0}.ascx\",\n                \"~/Areas/{2}/Views/Shared/{0}.aspx\",\n                \"~/Areas/{2}/Views/Shared/{0}.ascx\",\n            };\n\n            PartialViewLocationFormats = ViewLocationFormats;\n            AreaPartialViewLocationFormats = AreaViewLocationFormats;\n\n            FileExtensions = new[]\n            {\n                \"aspx\",\n                \"ascx\",\n                \"master\",\n            };\n        }\n\n        protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)\n        {\n            return new WebFormView(controllerContext, partialPath, null, ViewPageActivator);\n        }\n\n        protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)\n        {\n            return new WebFormView(controllerContext, viewPath, masterPath, ViewPageActivator);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/WebViewPage.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.IO;\nusing System.Web.Mvc.Properties;\nusing System.Web.WebPages;\n\nnamespace System.Web.Mvc\n{\n    public abstract class WebViewPage : WebPageBase, IViewDataContainer, IViewStartPageChild\n    {\n        private ViewDataDictionary _viewData;\n        private DynamicViewDataDictionary _dynamicViewData;\n        private HttpContextBase _context;\n        private HtmlHelper<object> _html;\n        private AjaxHelper<object> _ajax;\n\n        public override HttpContextBase Context\n        {\n            // REVIEW why are we forced to override this?\n            get { return _context ?? ViewContext.HttpContext; }\n            set { _context = value; }\n        }\n\n        public HtmlHelper<object> Html\n        {\n            get\n            {\n                if (_html == null && ViewContext != null)\n                {\n                    _html = new HtmlHelper<object>(ViewContext, this);\n                }\n                return _html;\n            }\n            set\n            {\n                _html = value;\n            }\n        }\n\n        public AjaxHelper<object> Ajax\n        {\n            get\n            {\n                if (_ajax == null && ViewContext != null)\n                {\n                    _ajax = new AjaxHelper<object>(ViewContext, this);\n                }\n                return _ajax;\n            }\n            set\n            {\n                _ajax = value;\n            }\n        }\n\n        public object Model\n        {\n            get { return ViewData.Model; }\n        }\n\n        internal string OverridenLayoutPath { get; set; }\n\n        public TempDataDictionary TempData\n        {\n            get { return ViewContext.TempData; }\n        }\n\n        public UrlHelper Url { get; set; }\n\n        public dynamic ViewBag\n        {\n            get\n            {\n                if (_dynamicViewData == null)\n                {\n                    _dynamicViewData = new DynamicViewDataDictionary(() => ViewData);\n                }\n                return _dynamicViewData;\n            }\n        }\n\n        public ViewContext ViewContext { get; set; }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"This is the mechanism by which the ViewPage gets its ViewDataDictionary object.\")]\n        public ViewDataDictionary ViewData\n        {\n            get\n            {\n                if (_viewData == null)\n                {\n                    SetViewData(new ViewDataDictionary());\n                }\n                return _viewData;\n            }\n            set { SetViewData(value); }\n        }\n\n        protected override void ConfigurePage(WebPageBase parentPage)\n        {\n            var baseViewPage = parentPage as WebViewPage;\n            if (baseViewPage == null)\n            {\n                // TODO : review if this check is even necessary.\n                // When this method is called by the framework parentPage should already be an instance of WebViewPage\n                // Need to review what happens if this method gets called in Plan9 pointing at an MVC view\n                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, MvcResources.CshtmlView_WrongViewBase, parentPage.VirtualPath));\n            }\n\n            // Set ViewContext and ViewData here so that the layout page inherits ViewData from the main page\n            ViewContext = baseViewPage.ViewContext;\n            ViewData = baseViewPage.ViewData;\n            InitHelpers();\n        }\n\n        public override void ExecutePageHierarchy()\n        {\n            // Change the Writer so that things like Html.BeginForm work correctly\n            TextWriter oldWriter = ViewContext.Writer;\n            ViewContext.Writer = Output;\n\n            base.ExecutePageHierarchy();\n\n            // Overwrite LayoutPage so that returning a view with a custom master page works.\n            if (!String.IsNullOrEmpty(OverridenLayoutPath))\n            {\n                Layout = OverridenLayoutPath;\n            }\n\n            // Restore the old View Context Writer\n            ViewContext.Writer = oldWriter;\n        }\n\n        public virtual void InitHelpers()\n        {\n            // Html and Ajax helpers are lazily initialized since they are not directly visible to a Razor page.\n            // In order to ensure back-compat, in the event that this instance gets re-used, we'll reset these\n            // properties so they get reinitialized the very next time they get accessed.\n            Html = null;\n            Ajax = null;\n            Url = new UrlHelper(ViewContext.RequestContext);\n        }\n\n        protected virtual void SetViewData(ViewDataDictionary viewData)\n        {\n            _viewData = viewData;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/WebViewPageOfTModel.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.Mvc\n{\n    public abstract class WebViewPage<TModel> : WebViewPage\n    {\n        private ViewDataDictionary<TModel> _viewData;\n\n        public new AjaxHelper<TModel> Ajax { get; set; }\n\n        public new HtmlHelper<TModel> Html { get; set; }\n\n        public new TModel Model\n        {\n            get { return ViewData.Model; }\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"This is the mechanism by which the ViewPage gets its ViewDataDictionary object.\")]\n        public new ViewDataDictionary<TModel> ViewData\n        {\n            get\n            {\n                if (_viewData == null)\n                {\n                    SetViewData(new ViewDataDictionary<TModel>());\n                }\n                return _viewData;\n            }\n            set { SetViewData(value); }\n        }\n\n        public override void InitHelpers()\n        {\n            base.InitHelpers();\n\n            Ajax = new AjaxHelper<TModel>(ViewContext, this);\n            Html = new HtmlHelper<TModel>(ViewContext, this);\n        }\n\n        protected override void SetViewData(ViewDataDictionary viewData)\n        {\n            _viewData = new ViewDataDictionary<TModel>(viewData);\n\n            base.SetViewData(_viewData);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Mvc/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Microsoft.Web.Infrastructure\" version=\"1.0.0.0\" targetFramework=\"net45\" />\n</packages>"
  },
  {
    "path": "src/System.Web.Razor/CSharpRazorCodeLanguage.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing Microsoft.CSharp;\n\nnamespace System.Web.Razor\n{\n    /// <summary>\n    /// Defines the C# Code Language for Razor\n    /// </summary>\n    public class CSharpRazorCodeLanguage : RazorCodeLanguage\n    {\n        private const string CSharpLanguageName = \"csharp\";\n\n        /// <summary>\n        /// Returns the name of the language: \"csharp\"\n        /// </summary>\n        public override string LanguageName\n        {\n            get { return CSharpLanguageName; }\n        }\n\n        /// <summary>\n        /// Returns the type of the CodeDOM provider for this language\n        /// </summary>\n        public override Type CodeDomProviderType\n        {\n            get { return typeof(CSharpCodeProvider); }\n        }\n\n        /// <summary>\n        /// Constructs a new instance of the code parser for this language\n        /// </summary>\n        public override ParserBase CreateCodeParser()\n        {\n            return new CSharpCodeParser();\n        }\n\n        /// <summary>\n        /// Constructs a new instance of the code generator for this language with the specified settings\n        /// </summary>\n        public override RazorCodeGenerator CreateCodeGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host)\n        {\n            return new CSharpRazorCodeGenerator(className, rootNamespaceName, sourceFileName, host);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/DocumentParseCompleteEventArgs.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Text;\n\nnamespace System.Web.Razor\n{\n    /// <summary>\n    /// Arguments for the DocumentParseComplete event in RazorEditorParser\n    /// </summary>\n    public class DocumentParseCompleteEventArgs : EventArgs\n    {\n        /// <summary>\n        /// Indicates if the tree structure has actually changed since the previous reparse.\n        /// </summary>\n        public bool TreeStructureChanged { get; set; }\n\n        /// <summary>\n        /// The results of the code generation and parsing\n        /// </summary>\n        public GeneratorResults GeneratorResults { get; set; }\n\n        /// <summary>\n        /// The TextChange which triggered the reparse\n        /// </summary>\n        public TextChange SourceChange { get; set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Editor/AutoCompleteEditHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Razor.Editor;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Razor.Parser.SyntaxTree\n{\n    public class AutoCompleteEditHandler : SpanEditHandler\n    {\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"Func<T> is the recommended delegate type and requires this level of nesting.\")]\n        public AutoCompleteEditHandler(Func<string, IEnumerable<ISymbol>> tokenizer)\n            : base(tokenizer)\n        {\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"Func<T> is the recommended delegate type and requires this level of nesting.\")]\n        public AutoCompleteEditHandler(Func<string, IEnumerable<ISymbol>> tokenizer, AcceptedCharacters accepted)\n            : base(tokenizer, accepted)\n        {\n        }\n\n        public bool AutoCompleteAtEndOfSpan { get; set; }\n        public string AutoCompleteString { get; set; }\n\n        protected override PartialParseResult CanAcceptChange(Span target, TextChange normalizedChange)\n        {\n            if (((AutoCompleteAtEndOfSpan && IsAtEndOfSpan(target, normalizedChange)) || IsAtEndOfFirstLine(target, normalizedChange)) &&\n                normalizedChange.IsInsert &&\n                ParserHelpers.IsNewLine(normalizedChange.NewText) &&\n                AutoCompleteString != null)\n            {\n                return PartialParseResult.Rejected | PartialParseResult.AutoCompleteBlock;\n            }\n            return PartialParseResult.Rejected;\n        }\n\n        public override string ToString()\n        {\n            return base.ToString() + \",AutoComplete:[\" + (AutoCompleteString ?? \"<null>\") + \"]\" + (AutoCompleteAtEndOfSpan ? \";AtEnd\" : \";AtEOL\");\n        }\n\n        public override bool Equals(object obj)\n        {\n            AutoCompleteEditHandler other = obj as AutoCompleteEditHandler;\n            return base.Equals(obj) &&\n                   other != null &&\n                   String.Equals(other.AutoCompleteString, AutoCompleteString, StringComparison.Ordinal) &&\n                   AutoCompleteAtEndOfSpan == other.AutoCompleteAtEndOfSpan;\n        }\n\n        public override int GetHashCode()\n        {\n            return HashCodeCombiner.Start()\n                .Add(base.GetHashCode())\n                .Add(AutoCompleteString)\n                .CombinedHash;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Editor/BackgroundParser.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Utils;\n\nnamespace System.Web.Razor.Editor\n{\n    internal class BackgroundParser : IDisposable\n    {\n        private MainThreadState _main;\n        private BackgroundThread _bg;\n\n        public BackgroundParser(RazorEngineHost host, string fileName)\n        {\n            _main = new MainThreadState(fileName);\n            _bg = new BackgroundThread(_main, host, fileName);\n\n            _main.ResultsReady += (sender, args) => OnResultsReady(args);\n        }\n\n        /// <summary>\n        /// Fired on the main thread.\n        /// </summary>\n        public event EventHandler<DocumentParseCompleteEventArgs> ResultsReady;\n\n        public bool IsIdle\n        {\n            get { return _main.IsIdle; }\n        }\n\n        public void Start()\n        {\n            _bg.Start();\n        }\n\n        public void Cancel()\n        {\n            _main.Cancel();\n        }\n\n        public void QueueChange(TextChange change)\n        {\n            _main.QueueChange(change);\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2213:DisposableFieldsShouldBeDisposed\", MessageId = \"_main\", Justification = \"MainThreadState is disposed when the background thread shuts down\")]\n        public void Dispose()\n        {\n            _main.Cancel();\n        }\n\n        public IDisposable SynchronizeMainThreadState()\n        {\n            return _main.Lock();\n        }\n\n        protected virtual void OnResultsReady(DocumentParseCompleteEventArgs args)\n        {\n            var handler = ResultsReady;\n            if (handler != null)\n            {\n                handler(this, args);\n            }\n        }\n\n        internal static bool TreesAreDifferent(Block leftTree, Block rightTree, IEnumerable<TextChange> changes)\n        {\n            return TreesAreDifferent(leftTree, rightTree, changes, CancellationToken.None);\n        }\n\n        internal static bool TreesAreDifferent(Block leftTree, Block rightTree, IEnumerable<TextChange> changes, CancellationToken cancelToken)\n        {\n            // Apply all the pending changes to the original tree\n            // PERF: If this becomes a bottleneck, we can probably do it the other way around,\n            //  i.e. visit the tree and find applicable changes for each node.\n            foreach (TextChange change in changes)\n            {\n                cancelToken.ThrowIfCancellationRequested();\n                Span changeOwner = leftTree.LocateOwner(change);\n\n                // Apply the change to the tree\n                if (changeOwner == null)\n                {\n                    return true;\n                }\n                EditResult result = changeOwner.EditHandler.ApplyChange(changeOwner, change, force: true);\n                changeOwner.ReplaceWith(result.EditedSpan);\n            }\n\n            // Now compare the trees\n            bool treesDifferent = !leftTree.EquivalentTo(rightTree);\n            return treesDifferent;\n        }\n\n        private abstract class ThreadStateBase\n        {\n#if DEBUG\n            private int _id = -1;\n#endif\n            protected ThreadStateBase()\n            {\n            }\n\n            [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"This method is only empty in Release builds. In Debug builds it contains references to instance variables\")]\n            [Conditional(\"DEBUG\")]\n            protected void SetThreadId(int id)\n            {\n#if DEBUG\n                _id = id;\n#endif\n            }\n\n            [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"This method is only empty in Release builds. In Debug builds it contains references to instance variables\")]\n            [Conditional(\"DEBUG\")]\n            protected void EnsureOnThread()\n            {\n#if DEBUG\n                Debug.Assert(_id != -1, \"SetThreadId was never called!\");\n                Debug.Assert(Thread.CurrentThread.ManagedThreadId == _id, \"Called from an unexpected thread!\");\n#endif\n            }\n\n            [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"This method is only empty in Release builds. In Debug builds it contains references to instance variables\")]\n            [Conditional(\"DEBUG\")]\n            protected void EnsureNotOnThread()\n            {\n#if DEBUG\n                Debug.Assert(_id != -1, \"SetThreadId was never called!\");\n                Debug.Assert(Thread.CurrentThread.ManagedThreadId != _id, \"Called from an unexpected thread!\");\n#endif\n            }\n        }\n\n        private class MainThreadState : ThreadStateBase, IDisposable\n        {\n            private CancellationTokenSource _cancelSource = new CancellationTokenSource();\n            private ManualResetEventSlim _hasParcel = new ManualResetEventSlim(false);\n            private CancellationTokenSource _currentParcelCancelSource;\n\n            [SuppressMessage(\"Microsoft.Performance\", \"CA1823:AvoidUnusedPrivateFields\", Justification = \"Field is used in debug code and may be used later\")]\n            private string _fileName;\n            private object _stateLock = new object();\n            private IList<TextChange> _changes = new List<TextChange>();\n\n            public MainThreadState(string fileName)\n            {\n                _fileName = fileName;\n\n                SetThreadId(Thread.CurrentThread.ManagedThreadId);\n            }\n\n            public event EventHandler<DocumentParseCompleteEventArgs> ResultsReady;\n\n            public CancellationToken CancelToken\n            {\n                get { return _cancelSource.Token; }\n            }\n\n            public bool IsIdle\n            {\n                get\n                {\n                    lock (_stateLock)\n                    {\n                        return _currentParcelCancelSource == null;\n                    }\n                }\n            }\n\n            public void Cancel()\n            {\n                EnsureOnThread();\n                _cancelSource.Cancel();\n            }\n\n            public IDisposable Lock()\n            {\n                Monitor.Enter(_stateLock);\n                return new DisposableAction(() => Monitor.Exit(_stateLock));\n            }\n\n            public void QueueChange(TextChange change)\n            {\n                RazorEditorTrace.TraceLine(RazorResources.Trace_QueuingParse, Path.GetFileName(_fileName), change);\n                EnsureOnThread();\n                lock (_stateLock)\n                {\n                    // CurrentParcel token source is not null ==> There's a parse underway\n                    if (_currentParcelCancelSource != null)\n                    {\n                        _currentParcelCancelSource.Cancel();\n                    }\n\n                    _changes.Add(change);\n                    _hasParcel.Set();\n                }\n            }\n\n            public WorkParcel GetParcel()\n            {\n                EnsureNotOnThread(); // Only the background thread can get a parcel\n                _hasParcel.Wait(_cancelSource.Token);\n                _hasParcel.Reset();\n                lock (_stateLock)\n                {\n                    // Create a cancellation source for this parcel\n                    _currentParcelCancelSource = new CancellationTokenSource();\n\n                    var changes = _changes;\n                    _changes = new List<TextChange>();\n                    return new WorkParcel(changes, _currentParcelCancelSource.Token);\n                }\n            }\n\n            public void ReturnParcel(DocumentParseCompleteEventArgs args)\n            {\n                lock (_stateLock)\n                {\n                    // Clear the current parcel cancellation source\n                    if (_currentParcelCancelSource != null)\n                    {\n                        _currentParcelCancelSource.Dispose();\n                        _currentParcelCancelSource = null;\n                    }\n\n                    // If there are things waiting to be parsed, just don't fire the event because we're already out of date\n                    if (_changes.Any())\n                    {\n                        return;\n                    }\n                }\n                var handler = ResultsReady;\n                if (handler != null)\n                {\n                    handler(this, args);\n                }\n            }\n\n            public void Dispose()\n            {\n                Dispose(true);\n                GC.SuppressFinalize(this);\n            }\n\n            protected virtual void Dispose(bool disposing)\n            {\n                if (disposing)\n                {\n                    if (_currentParcelCancelSource != null)\n                    {\n                        _currentParcelCancelSource.Dispose();\n                        _currentParcelCancelSource = null;\n                    }\n                    _cancelSource.Dispose();\n                    _hasParcel.Dispose();\n                }\n            }\n        }\n\n        private class BackgroundThread : ThreadStateBase\n        {\n            private MainThreadState _main;\n            private Thread _backgroundThread;\n            private CancellationToken _shutdownToken;\n            private RazorEngineHost _host;\n            private string _fileName;\n            private Block _currentParseTree;\n            private IList<TextChange> _previouslyDiscarded = new List<TextChange>();\n\n            public BackgroundThread(MainThreadState main, RazorEngineHost host, string fileName)\n            {\n                // Run on MAIN thread!\n                _main = main;\n                _backgroundThread = new Thread(WorkerLoop);\n                _shutdownToken = _main.CancelToken;\n                _host = host;\n                _fileName = fileName;\n\n                SetThreadId(_backgroundThread.ManagedThreadId);\n            }\n\n            // **** ANY THREAD ****\n            public void Start()\n            {\n                _backgroundThread.Start();\n            }\n\n            // **** BACKGROUND THREAD ****\n            private void WorkerLoop()\n            {\n                long? elapsedMs = null;\n                string fileNameOnly = Path.GetFileName(_fileName);\n#if EDITOR_TRACING\n                Stopwatch sw = new Stopwatch();\n#endif\n\n                try\n                {\n                    RazorEditorTrace.TraceLine(RazorResources.Trace_BackgroundThreadStart, fileNameOnly);\n                    EnsureOnThread();\n                    while (!_shutdownToken.IsCancellationRequested)\n                    {\n                        // Grab the parcel of work to do\n                        WorkParcel parcel = _main.GetParcel();\n                        if (parcel.Changes.Any())\n                        {\n                            RazorEditorTrace.TraceLine(RazorResources.Trace_ChangesArrived, fileNameOnly, parcel.Changes.Count);\n                            try\n                            {\n                                DocumentParseCompleteEventArgs args = null;\n                                using (var linkedCancel = CancellationTokenSource.CreateLinkedTokenSource(_shutdownToken, parcel.CancelToken))\n                                {\n                                    if (!linkedCancel.IsCancellationRequested)\n                                    {\n                                        // Collect ALL changes\n#if EDITOR_TRACING\n                                        if (_previouslyDiscarded != null && _previouslyDiscarded.Any())\n                                        {\n                                            RazorEditorTrace.TraceLine(RazorResources.Trace_CollectedDiscardedChanges, fileNameOnly, _previouslyDiscarded.Count);\n                                        }\n#endif\n                                        List<TextChange> allChanges;\n\n                                        if (_previouslyDiscarded != null)\n                                        {\n                                            allChanges = Enumerable.Concat(_previouslyDiscarded, parcel.Changes).ToList();\n                                        }\n                                        else\n                                        {\n                                            allChanges = parcel.Changes.ToList();\n                                        }\n\n                                        TextChange finalChange = allChanges.Last();\n#if EDITOR_TRACING\n                                        sw.Start();\n#endif\n                                        GeneratorResults results = ParseChange(finalChange.NewBuffer, linkedCancel.Token);\n#if EDITOR_TRACING\n                                        sw.Stop();\n                                        elapsedMs = sw.ElapsedMilliseconds;\n                                        sw.Reset();\n#endif\n                                        RazorEditorTrace.TraceLine(\n                                            RazorResources.Trace_ParseComplete,\n                                            fileNameOnly,\n                                            elapsedMs.HasValue ? elapsedMs.Value.ToString(CultureInfo.InvariantCulture) : \"?\");\n\n                                        if (results != null && !linkedCancel.IsCancellationRequested)\n                                        {\n                                            // Clear discarded changes list\n                                            _previouslyDiscarded = null;\n\n                                            // Take the current tree and check for differences\n#if EDITOR_TRACING\n                                            sw.Start();\n#endif\n                                            bool treeStructureChanged = _currentParseTree == null || TreesAreDifferent(_currentParseTree, results.Document, allChanges, parcel.CancelToken);\n#if EDITOR_TRACING\n                                            sw.Stop();\n                                            elapsedMs = sw.ElapsedMilliseconds;\n                                            sw.Reset();\n#endif\n                                            _currentParseTree = results.Document;\n                                            RazorEditorTrace.TraceLine(RazorResources.Trace_TreesCompared,\n                                                fileNameOnly,\n                                                elapsedMs.HasValue ? elapsedMs.Value.ToString(CultureInfo.InvariantCulture) : \"?\",\n                                                treeStructureChanged);\n\n                                            // Build Arguments\n                                            args = new DocumentParseCompleteEventArgs()\n                                            {\n                                                GeneratorResults = results,\n                                                SourceChange = finalChange,\n                                                TreeStructureChanged = treeStructureChanged\n                                            };\n                                        }\n                                        else\n                                        {\n                                            // Parse completed but we were cancelled in the mean time. Add these to the discarded changes set\n                                            RazorEditorTrace.TraceLine(RazorResources.Trace_ChangesDiscarded, fileNameOnly, allChanges.Count);\n                                            _previouslyDiscarded = allChanges;\n                                        }\n\n#if CHECK_TREE\n                                            if (args != null)\n                                            {\n                                                // Rewind the buffer and sanity check the line mappings\n                                                finalChange.NewBuffer.Position = 0;\n                                                int lineCount = finalChange.NewBuffer.ReadToEnd().Split(new string[] { Environment.NewLine, \"\\r\", \"\\n\" }, StringSplitOptions.None).Count();\n                                                Debug.Assert(\n                                                    !args.GeneratorResults.DesignTimeLineMappings.Any(pair => pair.Value.StartLine > lineCount),\n                                                    \"Found a design-time line mapping referring to a line outside the source file!\");\n                                                Debug.Assert(\n                                                    !args.GeneratorResults.Document.Flatten().Any(span => span.Start.LineIndex > lineCount),\n                                                    \"Found a span with a line number outside the source file\");\n                                                Debug.Assert(\n                                                    !args.GeneratorResults.Document.Flatten().Any(span => span.Start.AbsoluteIndex > parcel.NewBuffer.Length),\n                                                    \"Found a span with an absolute offset outside the source file\");\n                                            }\n#endif\n                                    }\n                                }\n                                if (args != null)\n                                {\n                                    _main.ReturnParcel(args);\n                                }\n                            }\n                            catch (OperationCanceledException)\n                            {\n                            }\n                        }\n                        else\n                        {\n                            RazorEditorTrace.TraceLine(RazorResources.Trace_NoChangesArrived, fileNameOnly, parcel.Changes.Count);\n                            Thread.Yield();\n                        }\n                    }\n                }\n                catch (OperationCanceledException)\n                {\n                    // Do nothing. Just shut down.\n                }\n                finally\n                {\n                    RazorEditorTrace.TraceLine(RazorResources.Trace_BackgroundThreadShutdown, fileNameOnly);\n\n                    // Clean up main thread resources\n                    _main.Dispose();\n                }\n            }\n\n            private GeneratorResults ParseChange(ITextBuffer buffer, CancellationToken token)\n            {\n                EnsureOnThread();\n\n                // Create a template engine\n                RazorTemplateEngine engine = new RazorTemplateEngine(_host);\n\n                // Seek the buffer to the beginning\n                buffer.Position = 0;\n\n                try\n                {\n                    return engine.GenerateCode(\n                        input: buffer,\n                        className: null,\n                        rootNamespace: null,\n                        sourceFileName: _fileName,\n                        cancelToken: token);\n                }\n                catch (OperationCanceledException)\n                {\n                    return null;\n                }\n            }\n        }\n\n        private class WorkParcel\n        {\n            public WorkParcel(IList<TextChange> changes, CancellationToken cancelToken)\n            {\n                Changes = changes;\n                CancelToken = cancelToken;\n            }\n\n            public CancellationToken CancelToken { get; private set; }\n            public IList<TextChange> Changes { get; private set; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Editor/EditResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.Razor.Editor\n{\n    public class EditResult\n    {\n        public EditResult(PartialParseResult result, SpanBuilder editedSpan)\n        {\n            Result = result;\n            EditedSpan = editedSpan;\n        }\n\n        public PartialParseResult Result { get; set; }\n        public SpanBuilder EditedSpan { get; set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Editor/EditorHints.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Razor.Editor\n{\n    /// <summary>\n    /// Used within <see cref=\"F:SpanEditHandler.EditorHints\"/>.\n    /// </summary>\n    [Flags]\n    public enum EditorHints\n    {\n        /// <summary>\n        /// The default (Markup or Code) editor behavior for Statement completion should be used.\n        /// Editors can always use the default behavior, even if the span is labeled with a different CompletionType.\n        /// </summary>\n        None = 0, // 0000 0000\n\n        /// <summary>\n        /// Indicates that Virtual Path completion should be used for this span if the editor supports it.\n        /// Editors need not support this mode of completion, and will use the default (<see cref=\"F:EditorHints.None\"/>) behavior\n        /// if they do not support it.\n        /// </summary>\n        VirtualPath = 1, // 0000 0001\n\n        /// <summary>\n        /// Indicates that this span's content contains the path to the layout page for this document.\n        /// </summary>\n        LayoutPage = 2, // 0000 0010\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Editor/ImplicitExpressionEditHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Razor.Editor\n{\n    public class ImplicitExpressionEditHandler : SpanEditHandler\n    {\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"Func<T> is the recommended delegate type and requires this level of nesting.\")]\n        public ImplicitExpressionEditHandler(Func<string, IEnumerable<ISymbol>> tokenizer, ISet<string> keywords, bool acceptTrailingDot)\n            : base(tokenizer)\n        {\n            Initialize(keywords, acceptTrailingDot);\n        }\n\n        public bool AcceptTrailingDot { get; private set; }\n        public ISet<string> Keywords { get; private set; }\n\n        public override string ToString()\n        {\n            return String.Format(CultureInfo.InvariantCulture, \"{0};ImplicitExpression[{1}];K{2}\", base.ToString(), AcceptTrailingDot ? \"ATD\" : \"RTD\", Keywords.Count);\n        }\n\n        public override bool Equals(object obj)\n        {\n            ImplicitExpressionEditHandler other = obj as ImplicitExpressionEditHandler;\n            return other != null &&\n                   base.Equals(other) &&\n                   Keywords.SetEquals(other.Keywords) &&\n                   AcceptTrailingDot == other.AcceptTrailingDot;\n        }\n\n        public override int GetHashCode()\n        {\n            return HashCodeCombiner.Start()\n                .Add(base.GetHashCode())\n                .Add(AcceptTrailingDot)\n                .Add(Keywords)\n                .CombinedHash;\n        }\n\n        protected override PartialParseResult CanAcceptChange(Span target, TextChange normalizedChange)\n        {\n            if (AcceptedCharacters == AcceptedCharacters.Any)\n            {\n                return PartialParseResult.Rejected;\n            }\n\n            // In some editors intellisense insertions are handled as \"dotless commits\".  If an intellisense selection is confirmed \n            // via something like '.' a dotless commit will append a '.' and then insert the remaining intellisense selection prior \n            // to the appended '.'.  This 'if' statement attempts to accept the intermediate steps of a dotless commit via \n            // intellisense.  It will accept two cases:\n            //     1. '@foo.' -> '@foobaz.'.\n            //     2. '@foobaz..' -> '@foobaz.bar.'. Includes Sub-cases '@foobaz()..' -> '@foobaz().bar.' etc.\n            // The key distinction being the double '.' in the second case.\n            if (IsDotlessCommitInsertion(target, normalizedChange))\n            {\n                return HandleDotlessCommitInsertion(target);\n            }\n\n            if (IsAcceptableIdentifierReplacement(target, normalizedChange))\n            {\n                return TryAcceptChange(target, normalizedChange);\n            }\n\n            if (IsAcceptableReplace(target, normalizedChange))\n            {\n                return HandleReplacement(target, normalizedChange);\n            }\n            int changeRelativePosition = normalizedChange.OldPosition - target.Start.AbsoluteIndex;\n\n            // Get the edit context\n            char? lastChar = null;\n            if (changeRelativePosition > 0 && target.Content.Length > 0)\n            {\n                lastChar = target.Content[changeRelativePosition - 1];\n            }\n\n            // Don't support 0->1 length edits\n            if (lastChar == null)\n            {\n                return PartialParseResult.Rejected;\n            }\n\n            // Accepts cases when insertions are made at the end of a span or '.' is inserted within a span.\n            if (IsAcceptableInsertion(target, normalizedChange))\n            {\n                // Handle the insertion\n                return HandleInsertion(target, lastChar.Value, normalizedChange);\n            }\n\n            if (IsAcceptableDeletion(target, normalizedChange))\n            {\n                return HandleDeletion(target, lastChar.Value, normalizedChange);\n            }\n\n            return PartialParseResult.Rejected;\n        }\n\n        private void Initialize(ISet<string> keywords, bool acceptTrailingDot)\n        {\n            Keywords = keywords ?? new HashSet<string>();\n            AcceptTrailingDot = acceptTrailingDot;\n        }\n\n        // A dotless commit is the process of inserting a '.' with an intellisense selection.\n        private static bool IsDotlessCommitInsertion(Span target, TextChange change)\n        {\n            return IsNewDotlessCommitInsertion(target, change) || IsSecondaryDotlessCommitInsertion(target, change);\n        }\n\n        // Completing 'DateTime' in intellisense with a '.' could result in: '@DateT' -> '@DateT.' -> '@DateTime.' which is accepted.\n        private static bool IsNewDotlessCommitInsertion(Span target, TextChange change)\n        {\n            return !IsAtEndOfSpan(target, change) &&\n                   change.NewPosition > 0 &&\n                   change.NewLength > 0 &&\n                   target.Content.Last() == '.' &&\n                   ParserHelpers.IsIdentifier(change.NewText, requireIdentifierStart: false) &&\n                   (change.OldLength == 0 || ParserHelpers.IsIdentifier(change.OldText, requireIdentifierStart: false));\n        }\n\n        // Once a dotless commit has been performed you then have something like '@DateTime.'.  This scenario is used to detect the\n        // situation when you try to perform another dotless commit resulting in a textchange with '..'.  Completing 'DateTime.Now' \n        // in intellisense with a '.' could result in: '@DateTime.' -> '@DateTime..' -> '@DateTime.Now.' which is accepted.\n        private static bool IsSecondaryDotlessCommitInsertion(Span target, TextChange change)\n        {\n            // Do not need to worry about other punctuation, just looking for double '.' (after change)\n            return change.NewLength == 1 &&\n                   !String.IsNullOrEmpty(target.Content) &&\n                   target.Content.Last() == '.' &&\n                   change.NewText == \".\" &&\n                   change.OldLength == 0;\n        }\n\n        private bool IsAcceptableIdentifierReplacement(Span target, TextChange change)\n        {\n            if (!change.IsReplace)\n            {\n                return false;\n            }\n\n            foreach (ISymbol isymbol in target.Symbols)\n            {\n                CSharpSymbol symbol = isymbol as CSharpSymbol;\n\n                if (symbol == null)\n                {\n                    break;\n                }\n\n                int symbolStartIndex = target.Start.AbsoluteIndex + symbol.Start.AbsoluteIndex;\n                int symbolEndIndex = symbolStartIndex + symbol.Content.Length;\n\n                // We're looking for the first symbol that contains the TextChange.\n                if (symbolEndIndex > change.OldPosition)\n                {\n                    if (symbolEndIndex >= change.OldPosition + change.OldLength && symbol.Type == CSharpSymbolType.Identifier)\n                    {\n                        // The symbol we're changing happens to be an identifier. Need to check if its transformed state is also one.\n                        // We do this transformation logic to capture the case that the new text change happens to not be an identifier;\n                        // i.e. \"5\". Alone, it's numeric, within an identifier it's classified as identifier.\n                        string transformedContent = change.ApplyChange(symbol.Content, symbolStartIndex);\n                        IEnumerable<ISymbol> newSymbols = Tokenizer(transformedContent);\n\n                        if (newSymbols.Count() != 1)\n                        {\n                            // The transformed content resulted in more than one symbol; we can only replace a single identifier with\n                            // another single identifier.\n                            break;\n                        }\n\n                        CSharpSymbol newSymbol = (CSharpSymbol)newSymbols.First();\n                        if (newSymbol.Type == CSharpSymbolType.Identifier)\n                        {\n                            return true;\n                        }\n                    }\n\n                    // Change is touching a non-identifier symbol or spans multiple symbols.\n\n                    break;\n                }\n            }\n\n            return false;\n        }\n\n        private static bool IsAcceptableReplace(Span target, TextChange change)\n        {\n            return IsEndReplace(target, change) ||\n                   (change.IsReplace && RemainingIsWhitespace(target, change));\n        }\n\n        private static bool IsAcceptableDeletion(Span target, TextChange change)\n        {\n            return IsEndDeletion(target, change) ||\n                   (change.IsDelete && RemainingIsWhitespace(target, change));\n        }\n\n        // Acceptable insertions can occur at the end of a span or when a '.' is inserted within a span.\n        private static bool IsAcceptableInsertion(Span target, TextChange change)\n        {\n            return change.IsInsert &&\n                   (IsAcceptableEndInsertion(target, change) ||\n                   IsAcceptableInnerInsertion(target, change));\n        }\n\n        // Accepts character insertions at the end of spans.  AKA: '@foo' -> '@fooo' or '@foo' -> '@foo   ' etc.\n        private static bool IsAcceptableEndInsertion(Span target, TextChange change)\n        {\n            Debug.Assert(change.IsInsert);\n\n            return IsAtEndOfSpan(target, change) ||\n                   RemainingIsWhitespace(target, change);\n        }\n\n        // Accepts '.' insertions in the middle of spans. Ex: '@foo.baz.bar' -> '@foo..baz.bar'\n        // This is meant to allow intellisense when editing a span.\n        [SuppressMessage(\"Microsoft.Usage\", \"CA1801:ReviewUnusedParameters\", MessageId = \"target\", Justification = \"The 'target' parameter is used in Debug to validate that the function is called in the correct context.\")]\n        private static bool IsAcceptableInnerInsertion(Span target, TextChange change)\n        {\n            Debug.Assert(change.IsInsert);\n\n            // Ensure that we're actually inserting in the middle of a span and not at the end.\n            // This case will fail if the IsAcceptableEndInsertion does not capture an end insertion correctly.\n            Debug.Assert(!IsAtEndOfSpan(target, change));\n\n            return change.NewPosition > 0 &&\n                   change.NewText == \".\";\n        }\n\n        private static bool RemainingIsWhitespace(Span target, TextChange change)\n        {\n            int offset = (change.OldPosition - target.Start.AbsoluteIndex) + change.OldLength;\n            return String.IsNullOrWhiteSpace(target.Content.Substring(offset));\n        }\n\n        private PartialParseResult HandleDotlessCommitInsertion(Span target)\n        {\n            PartialParseResult result = PartialParseResult.Accepted;\n            if (!AcceptTrailingDot && target.Content.LastOrDefault() == '.')\n            {\n                result |= PartialParseResult.Provisional;\n            }\n            return result;\n        }\n\n        private PartialParseResult HandleReplacement(Span target, TextChange change)\n        {\n            // Special Case for IntelliSense commits.\n            //  When IntelliSense commits, we get two changes (for example user typed \"Date\", then committed \"DateTime\" by pressing \".\")\n            //  1. Insert \".\" at the end of this span\n            //  2. Replace the \"Date.\" at the end of the span with \"DateTime.\"\n            //  We need partial parsing to accept case #2.\n            string oldText = GetOldText(target, change);\n\n            PartialParseResult result = PartialParseResult.Rejected;\n            if (EndsWithDot(oldText) && EndsWithDot(change.NewText))\n            {\n                result = PartialParseResult.Accepted;\n                if (!AcceptTrailingDot)\n                {\n                    result |= PartialParseResult.Provisional;\n                }\n            }\n            return result;\n        }\n\n        private PartialParseResult HandleDeletion(Span target, char previousChar, TextChange change)\n        {\n            // What's left after deleting?\n            if (previousChar == '.')\n            {\n                return TryAcceptChange(target, change, PartialParseResult.Accepted | PartialParseResult.Provisional);\n            }\n            else if (ParserHelpers.IsIdentifierPart(previousChar))\n            {\n                return TryAcceptChange(target, change);\n            }\n            else\n            {\n                return PartialParseResult.Rejected;\n            }\n        }\n\n        private PartialParseResult HandleInsertion(Span target, char previousChar, TextChange change)\n        {\n            // What are we inserting after?\n            if (previousChar == '.')\n            {\n                return HandleInsertionAfterDot(target, change);\n            }\n            else if (ParserHelpers.IsIdentifierPart(previousChar) || previousChar == ')' || previousChar == ']')\n            {\n                return HandleInsertionAfterIdPart(target, change);\n            }\n            else\n            {\n                return PartialParseResult.Rejected;\n            }\n        }\n\n        private PartialParseResult HandleInsertionAfterIdPart(Span target, TextChange change)\n        {\n            // If the insertion is a full identifier part, accept it\n            if (ParserHelpers.IsIdentifier(change.NewText, requireIdentifierStart: false))\n            {\n                return TryAcceptChange(target, change);\n            }\n            else if (EndsWithDot(change.NewText))\n            {\n                // Accept it, possibly provisionally\n                PartialParseResult result = PartialParseResult.Accepted;\n                if (!AcceptTrailingDot)\n                {\n                    result |= PartialParseResult.Provisional;\n                }\n                return TryAcceptChange(target, change, result);\n            }\n            else\n            {\n                return PartialParseResult.Rejected;\n            }\n        }\n\n        private static bool EndsWithDot(string content)\n        {\n            return (content.Length == 1 && content[0] == '.') ||\n                   (content[content.Length - 1] == '.' &&\n                    content.Take(content.Length - 1).All(ParserHelpers.IsIdentifierPart));\n        }\n\n        private PartialParseResult HandleInsertionAfterDot(Span target, TextChange change)\n        {\n            // If the insertion is a full identifier or another dot, accept it\n            if (ParserHelpers.IsIdentifier(change.NewText) || change.NewText == \".\")\n            {\n                return TryAcceptChange(target, change);\n            }\n            return PartialParseResult.Rejected;\n        }\n\n        private PartialParseResult TryAcceptChange(Span target, TextChange change, PartialParseResult acceptResult = PartialParseResult.Accepted)\n        {\n            string content = change.ApplyChange(target);\n            if (StartsWithKeyword(content))\n            {\n                return PartialParseResult.Rejected | PartialParseResult.SpanContextChanged;\n            }\n\n            return acceptResult;\n        }\n\n        private bool StartsWithKeyword(string newContent)\n        {\n            using (StringReader reader = new StringReader(newContent))\n            {\n                return Keywords.Contains(reader.ReadWhile(ParserHelpers.IsIdentifierPart));\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Editor/RazorEditorTrace.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Text;\n\nnamespace System.Web.Razor.Editor\n{\n    internal static class RazorEditorTrace\n    {\n        private static bool? _enabled;\n\n        private static bool IsEnabled()\n        {\n            if (_enabled == null)\n            {\n                bool enabled;\n                if (Boolean.TryParse(Environment.GetEnvironmentVariable(\"RAZOR_EDITOR_TRACE\"), out enabled))\n                {\n                    Trace.WriteLine(String.Format(\n                        CultureInfo.CurrentCulture,\n                        RazorResources.Trace_Startup,\n                        enabled ? RazorResources.Trace_Enabled : RazorResources.Trace_Disabled));\n                    _enabled = enabled;\n                }\n                else\n                {\n                    _enabled = false;\n                }\n            }\n            return _enabled.Value;\n        }\n\n        [Conditional(\"EDITOR_TRACING\")]\n        public static void TraceLine(string format, params object[] args)\n        {\n            if (IsEnabled())\n            {\n                Trace.WriteLine(String.Format(\n                    CultureInfo.CurrentCulture,\n                    RazorResources.Trace_Format,\n                    String.Format(CultureInfo.CurrentCulture, format, args)));\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Editor/SingleLineMarkupEditHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Editor\n{\n    public class SingleLineMarkupEditHandler : SpanEditHandler\n    {\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"Func<T> is the recommended delegate type and requires this level of nesting.\")]\n        public SingleLineMarkupEditHandler(Func<string, IEnumerable<ISymbol>> tokenizer)\n            : base(tokenizer)\n        {\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"Func<T> is the recommended delegate type and requires this level of nesting.\")]\n        public SingleLineMarkupEditHandler(Func<string, IEnumerable<ISymbol>> tokenizer, AcceptedCharacters accepted)\n            : base(tokenizer, accepted)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Editor/SpanEditHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Razor.Editor\n{\n    // Manages edits to a span\n    public class SpanEditHandler\n    {\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"Func<T> is the recommended delegate type and requires this level of nesting.\")]\n        public SpanEditHandler(Func<string, IEnumerable<ISymbol>> tokenizer)\n            : this(tokenizer, AcceptedCharacters.Any)\n        {\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"Func<T> is the recommended delegate type and requires this level of nesting.\")]\n        public SpanEditHandler(Func<string, IEnumerable<ISymbol>> tokenizer, AcceptedCharacters accepted)\n        {\n            AcceptedCharacters = accepted;\n            Tokenizer = tokenizer;\n        }\n\n        public AcceptedCharacters AcceptedCharacters { get; set; }\n\n        /// <summary>\n        /// Provides a set of hints to editors which may be manipulating the document in which this span is located.\n        /// </summary>\n        public EditorHints EditorHints { get; set; }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"Func<T> is the recommended delegate type and requires this level of nesting.\")]\n        public Func<string, IEnumerable<ISymbol>> Tokenizer { get; set; }\n\n        public static SpanEditHandler CreateDefault()\n        {\n            return CreateDefault(s => Enumerable.Empty<ISymbol>());\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"Func<T> is the recommended delegate type and requires this level of nesting.\")]\n        public static SpanEditHandler CreateDefault(Func<string, IEnumerable<ISymbol>> tokenizer)\n        {\n            return new SpanEditHandler(tokenizer);\n        }\n\n        public virtual EditResult ApplyChange(Span target, TextChange change)\n        {\n            return ApplyChange(target, change, force: false);\n        }\n\n        public virtual EditResult ApplyChange(Span target, TextChange change, bool force)\n        {\n            PartialParseResult result = PartialParseResult.Accepted;\n            TextChange normalized = change.Normalize();\n            if (!force)\n            {\n                result = CanAcceptChange(target, normalized);\n            }\n\n            // If the change is accepted then apply the change\n            if (result.HasFlag(PartialParseResult.Accepted))\n            {\n                return new EditResult(result, UpdateSpan(target, normalized));\n            }\n            return new EditResult(result, new SpanBuilder(target));\n        }\n\n        public virtual bool OwnsChange(Span target, TextChange change)\n        {\n            int end = target.Start.AbsoluteIndex + target.Length;\n            int changeOldEnd = change.OldPosition + change.OldLength;\n            return change.OldPosition >= target.Start.AbsoluteIndex &&\n                   (changeOldEnd < end || (changeOldEnd == end && AcceptedCharacters != AcceptedCharacters.None));\n        }\n\n        protected virtual PartialParseResult CanAcceptChange(Span target, TextChange normalizedChange)\n        {\n            return PartialParseResult.Rejected;\n        }\n\n        protected virtual SpanBuilder UpdateSpan(Span target, TextChange normalizedChange)\n        {\n            string newContent = normalizedChange.ApplyChange(target);\n            SpanBuilder newSpan = new SpanBuilder(target);\n            newSpan.ClearSymbols();\n            foreach (ISymbol sym in Tokenizer(newContent))\n            {\n                sym.OffsetStart(target.Start);\n                newSpan.Accept(sym);\n            }\n            if (target.Next != null)\n            {\n                SourceLocation newEnd = SourceLocationTracker.CalculateNewLocation(target.Start, newContent);\n                target.Next.ChangeStart(newEnd);\n            }\n            return newSpan;\n        }\n\n        protected internal static bool IsAtEndOfFirstLine(Span target, TextChange change)\n        {\n            int endOfFirstLine = target.Content.IndexOfAny(new char[] { (char)0x000d, (char)0x000a, (char)0x2028, (char)0x2029 });\n            return (endOfFirstLine == -1 || (change.OldPosition - target.Start.AbsoluteIndex) <= endOfFirstLine);\n        }\n\n        /// <summary>\n        /// Returns true if the specified change is an insertion of text at the end of this span.\n        /// </summary>\n        protected internal static bool IsEndInsertion(Span target, TextChange change)\n        {\n            return change.IsInsert && IsAtEndOfSpan(target, change);\n        }\n\n        /// <summary>\n        /// Returns true if the specified change is an insertion of text at the end of this span.\n        /// </summary>\n        protected internal static bool IsEndDeletion(Span target, TextChange change)\n        {\n            return change.IsDelete && IsAtEndOfSpan(target, change);\n        }\n\n        /// <summary>\n        /// Returns true if the specified change is a replacement of text at the end of this span.\n        /// </summary>\n        protected internal static bool IsEndReplace(Span target, TextChange change)\n        {\n            return change.IsReplace && IsAtEndOfSpan(target, change);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1011:ConsiderPassingBaseTypesAsParameters\", Justification = \"This method should only be used on Spans\")]\n        protected internal static bool IsAtEndOfSpan(Span target, TextChange change)\n        {\n            return (change.OldPosition + change.OldLength) == (target.Start.AbsoluteIndex + target.Length);\n        }\n\n        /// <summary>\n        /// Returns the old text referenced by the change.\n        /// </summary>\n        /// <remarks>\n        /// If the content has already been updated by applying the change, this data will be _invalid_\n        /// </remarks>\n        protected internal static string GetOldText(Span target, TextChange change)\n        {\n            return target.Content.Substring(change.OldPosition - target.Start.AbsoluteIndex, change.OldLength);\n        }\n\n        // Is the specified span to the right of this span and immediately adjacent?\n        internal static bool IsAdjacentOnRight(Span target, Span other)\n        {\n            return target.Start.AbsoluteIndex < other.Start.AbsoluteIndex && target.Start.AbsoluteIndex + target.Length == other.Start.AbsoluteIndex;\n        }\n\n        // Is the specified span to the left of this span and immediately adjacent?\n        internal static bool IsAdjacentOnLeft(Span target, Span other)\n        {\n            return other.Start.AbsoluteIndex < target.Start.AbsoluteIndex && other.Start.AbsoluteIndex + other.Length == target.Start.AbsoluteIndex;\n        }\n\n        public override string ToString()\n        {\n            return GetType().Name + \";Accepts:\" + AcceptedCharacters + ((EditorHints == EditorHints.None) ? String.Empty : (\";Hints: \" + EditorHints.ToString()));\n        }\n\n        public override bool Equals(object obj)\n        {\n            SpanEditHandler other = obj as SpanEditHandler;\n            return other != null &&\n                   AcceptedCharacters == other.AcceptedCharacters &&\n                   EditorHints == other.EditorHints;\n        }\n\n        public override int GetHashCode()\n        {\n            return HashCodeCombiner.Start()\n                .Add(AcceptedCharacters)\n                .Add(EditorHints)\n                .CombinedHash;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/AddImportCodeGenerator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.Linq;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Razor.Generator\n{\n    public class AddImportCodeGenerator : SpanCodeGenerator\n    {\n        public AddImportCodeGenerator(string ns, int namespaceKeywordLength)\n        {\n            Namespace = ns;\n            NamespaceKeywordLength = namespaceKeywordLength;\n        }\n\n        public string Namespace { get; private set; }\n        public int NamespaceKeywordLength { get; set; }\n\n        public override void GenerateCode(Span target, CodeGeneratorContext context)\n        {\n            // Try to find the namespace in the existing imports\n            string ns = Namespace;\n            if (!String.IsNullOrEmpty(ns) && Char.IsWhiteSpace(ns[0]))\n            {\n                ns = ns.Substring(1);\n            }\n\n            CodeNamespaceImport import = context.Namespace\n                .Imports\n                .OfType<CodeNamespaceImport>()\n                .Where(i => String.Equals(i.Namespace, ns.Trim(), StringComparison.Ordinal))\n                .FirstOrDefault();\n\n            if (import == null)\n            {\n                // It doesn't exist, create it\n                import = new CodeNamespaceImport(ns);\n                context.Namespace.Imports.Add(import);\n            }\n\n            // Attach our info to the existing/new import.\n            import.LinePragma = context.GenerateLinePragma(target);\n        }\n\n        public override string ToString()\n        {\n            return \"Import:\" + Namespace + \";KwdLen:\" + NamespaceKeywordLength;\n        }\n\n        public override bool Equals(object obj)\n        {\n            AddImportCodeGenerator other = obj as AddImportCodeGenerator;\n            return other != null &&\n                   String.Equals(Namespace, other.Namespace, StringComparison.Ordinal) &&\n                   NamespaceKeywordLength == other.NamespaceKeywordLength;\n        }\n\n        public override int GetHashCode()\n        {\n            return HashCodeCombiner.Start()\n                .Add(Namespace)\n                .Add(NamespaceKeywordLength)\n                .CombinedHash;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/AttributeBlockCodeGenerator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Text;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Razor.Generator\n{\n    public class AttributeBlockCodeGenerator : BlockCodeGenerator\n    {\n        public AttributeBlockCodeGenerator(string name, LocationTagged<string> prefix, LocationTagged<string> suffix)\n        {\n            Name = name;\n            Prefix = prefix;\n            Suffix = suffix;\n        }\n\n        public string Name { get; private set; }\n        public LocationTagged<string> Prefix { get; private set; }\n        public LocationTagged<string> Suffix { get; private set; }\n\n        public override void GenerateStartBlockCode(Block target, CodeGeneratorContext context)\n        {\n            if (context.Host.DesignTimeMode)\n            {\n                return; // Don't generate anything!\n            }\n            context.FlushBufferedStatement();\n            context.AddStatement(context.BuildCodeString(cw =>\n            {\n                if (!String.IsNullOrEmpty(context.TargetWriterName))\n                {\n                    cw.WriteStartMethodInvoke(context.Host.GeneratedClassContext.WriteAttributeToMethodName);\n                    cw.WriteSnippet(context.TargetWriterName);\n                    cw.WriteParameterSeparator();\n                }\n                else\n                {\n                    cw.WriteStartMethodInvoke(context.Host.GeneratedClassContext.WriteAttributeMethodName);\n                }\n                cw.WriteStringLiteral(Name);\n                cw.WriteParameterSeparator();\n                cw.WriteLocationTaggedString(Prefix);\n                cw.WriteParameterSeparator();\n                cw.WriteLocationTaggedString(Suffix);\n\n                // In VB, we need a line continuation\n                cw.WriteLineContinuation();\n            }));\n        }\n\n        public override void GenerateEndBlockCode(Block target, CodeGeneratorContext context)\n        {\n            if (context.Host.DesignTimeMode)\n            {\n                return; // Don't generate anything!\n            }\n            context.FlushBufferedStatement();\n            context.AddStatement(context.BuildCodeString(cw =>\n            {\n                cw.WriteEndMethodInvoke();\n                cw.WriteEndStatement();\n            }));\n        }\n\n        public override string ToString()\n        {\n            return String.Format(CultureInfo.CurrentCulture, \"Attr:{0},{1:F},{2:F}\", Name, Prefix, Suffix);\n        }\n\n        public override bool Equals(object obj)\n        {\n            AttributeBlockCodeGenerator other = obj as AttributeBlockCodeGenerator;\n            return other != null &&\n                   String.Equals(other.Name, Name, StringComparison.Ordinal) &&\n                   Equals(other.Prefix, Prefix) &&\n                   Equals(other.Suffix, Suffix);\n        }\n\n        public override int GetHashCode()\n        {\n            return HashCodeCombiner.Start()\n                .Add(Name)\n                .Add(Prefix)\n                .Add(Suffix)\n                .CombinedHash;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/BaseCodeWriter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Razor.Generator\n{\n    internal abstract class BaseCodeWriter : CodeWriter\n    {\n        public override void WriteSnippet(string snippet)\n        {\n            InnerWriter.Write(snippet);\n        }\n\n        protected internal override void EmitStartMethodInvoke(string methodName)\n        {\n            EmitStartMethodInvoke(methodName, new string[0]);\n        }\n\n        protected internal override void EmitStartMethodInvoke(string methodName, params string[] genericArguments)\n        {\n            InnerWriter.Write(methodName);\n            if (genericArguments != null && genericArguments.Length > 0)\n            {\n                WriteStartGenerics();\n                for (int i = 0; i < genericArguments.Length; i++)\n                {\n                    if (i > 0)\n                    {\n                        WriteParameterSeparator();\n                    }\n                    WriteSnippet(genericArguments[i]);\n                }\n                WriteEndGenerics();\n            }\n\n            InnerWriter.Write(\"(\");\n        }\n\n        protected internal override void EmitEndMethodInvoke()\n        {\n            InnerWriter.Write(\")\");\n        }\n\n        protected internal override void EmitEndConstructor()\n        {\n            InnerWriter.Write(\")\");\n        }\n\n        protected internal override void EmitEndLambdaExpression()\n        {\n        }\n\n        public override void WriteParameterSeparator()\n        {\n            InnerWriter.Write(\", \");\n        }\n\n        protected internal void WriteCommaSeparatedList<T>(T[] items, Action<T> writeItemAction)\n        {\n            for (int i = 0; i < items.Length; i++)\n            {\n                if (i > 0)\n                {\n                    InnerWriter.Write(\", \");\n                }\n                writeItemAction(items[i]);\n            }\n        }\n\n        protected internal virtual void WriteStartGenerics()\n        {\n        }\n\n        protected internal virtual void WriteEndGenerics()\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/BlockCodeGenerator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.Razor.Generator\n{\n    public abstract class BlockCodeGenerator : IBlockCodeGenerator\n    {\n        [SuppressMessage(\"Microsoft.Security\", \"CA2104:DoNotDeclareReadOnlyMutableReferenceTypes\", Justification = \"This class has no instance state\")]\n        public static readonly IBlockCodeGenerator Null = new NullBlockCodeGenerator();\n\n        public virtual void GenerateStartBlockCode(Block target, CodeGeneratorContext context)\n        {\n        }\n\n        public virtual void GenerateEndBlockCode(Block target, CodeGeneratorContext context)\n        {\n        }\n\n        public override bool Equals(object obj)\n        {\n            return (obj as IBlockCodeGenerator) != null;\n        }\n\n        public override int GetHashCode()\n        {\n            return base.GetHashCode();\n        }\n\n        private class NullBlockCodeGenerator : IBlockCodeGenerator\n        {\n            public void GenerateStartBlockCode(Block target, CodeGeneratorContext context)\n            {\n            }\n\n            public void GenerateEndBlockCode(Block target, CodeGeneratorContext context)\n            {\n            }\n\n            public override string ToString()\n            {\n                return \"None\";\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/CSharpCodeWriter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\n\nnamespace System.Web.Razor.Generator\n{\n    internal class CSharpCodeWriter : BaseCodeWriter\n    {\n        protected internal override void WriteStartGenerics()\n        {\n            InnerWriter.Write(\"<\");\n        }\n\n        protected internal override void WriteEndGenerics()\n        {\n            InnerWriter.Write(\">\");\n        }\n\n        public override int WriteVariableDeclaration(string type, string name, string value)\n        {\n            InnerWriter.Write(type);\n            InnerWriter.Write(\" \");\n            InnerWriter.Write(name);\n            if (!String.IsNullOrEmpty(value))\n            {\n                InnerWriter.Write(\" = \");\n                InnerWriter.Write(value);\n            }\n            else\n            {\n                InnerWriter.Write(\" = null\");\n            }\n            return 0;\n        }\n\n        public override void WriteDisableUnusedFieldWarningPragma()\n        {\n            InnerWriter.Write(\"#pragma warning disable 219\");\n        }\n\n        public override void WriteRestoreUnusedFieldWarningPragma()\n        {\n            InnerWriter.Write(\"#pragma warning restore 219\");\n        }\n\n        public override void WriteStringLiteral(string literal)\n        {\n            if (literal == null)\n            {\n                throw new ArgumentNullException(\"literal\");\n            }\n\n            // From CSharpCodeProvider in CodeDOM\n            //  If the string is short, use C style quoting (e.g \"\\r\\n\")\n            //  Also do it if it is too long to fit in one line\n            //  If the string contains '\\0', verbatim style won't work.\n            if (literal.Length >= 256 && literal.Length <= 1500 && literal.IndexOf('\\0') == -1)\n            {\n                WriteVerbatimStringLiteral(literal);\n            }\n            else\n            {\n                WriteCStyleStringLiteral(literal);\n            }\n        }\n\n        private void WriteVerbatimStringLiteral(string literal)\n        {\n            // From CSharpCodeGenerator.QuoteSnippetStringVerbatim in CodeDOM\n            InnerWriter.Write(\"@\\\"\");\n            for (int i = 0; i < literal.Length; i++)\n            {\n                if (literal[i] == '\\\"')\n                {\n                    InnerWriter.Write(\"\\\"\\\"\");\n                }\n                else\n                {\n                    InnerWriter.Write(literal[i]);\n                }\n            }\n            InnerWriter.Write(\"\\\"\");\n        }\n\n        private void WriteCStyleStringLiteral(string literal)\n        {\n            // From CSharpCodeGenerator.QuoteSnippetStringCStyle in CodeDOM\n            InnerWriter.Write(\"\\\"\");\n            for (int i = 0; i < literal.Length; i++)\n            {\n                switch (literal[i])\n                {\n                    case '\\r':\n                        InnerWriter.Write(\"\\\\r\");\n                        break;\n                    case '\\t':\n                        InnerWriter.Write(\"\\\\t\");\n                        break;\n                    case '\\\"':\n                        InnerWriter.Write(\"\\\\\\\"\");\n                        break;\n                    case '\\'':\n                        InnerWriter.Write(\"\\\\\\'\");\n                        break;\n                    case '\\\\':\n                        InnerWriter.Write(\"\\\\\\\\\");\n                        break;\n                    case '\\0':\n                        InnerWriter.Write(\"\\\\\\0\");\n                        break;\n                    case '\\n':\n                        InnerWriter.Write(\"\\\\n\");\n                        break;\n                    case '\\u2028':\n                    case '\\u2029':\n                        // Inlined CSharpCodeGenerator.AppendEscapedChar\n                        InnerWriter.Write(\"\\\\u\");\n                        InnerWriter.Write(((int)literal[i]).ToString(\"X4\", CultureInfo.InvariantCulture));\n                        break;\n                    default:\n                        InnerWriter.Write(literal[i]);\n                        break;\n                }\n                if (i > 0 && i % 80 == 0)\n                {\n                    // If current character is a high surrogate and the following \n                    // character is a low surrogate, don't break them. \n                    // Otherwise when we write the string to a file, we might lose \n                    // the characters.\n                    if (Char.IsHighSurrogate(literal[i])\n                        && (i < literal.Length - 1)\n                        && Char.IsLowSurrogate(literal[i + 1]))\n                    {\n                        InnerWriter.Write(literal[++i]);\n                    }\n\n                    InnerWriter.Write(\"\\\" +\");\n                    InnerWriter.Write(Environment.NewLine);\n                    InnerWriter.Write('\\\"');\n                }\n            }\n            InnerWriter.Write(\"\\\"\");\n        }\n\n        public override void WriteEndStatement()\n        {\n            InnerWriter.WriteLine(\";\");\n        }\n\n        public override void WriteIdentifier(string identifier)\n        {\n            InnerWriter.Write(\"@\" + identifier);\n        }\n\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1308:NormalizeStringsToUppercase\", Justification = \"Lowercase is intended here. C# boolean literals are all lowercase\")]\n        public override void WriteBooleanLiteral(bool value)\n        {\n            WriteSnippet(value.ToString().ToLowerInvariant());\n        }\n\n        protected internal override void EmitStartLambdaExpression(string[] parameterNames)\n        {\n            if (parameterNames == null)\n            {\n                throw new ArgumentNullException(\"parameterNames\");\n            }\n\n            if (parameterNames.Length == 0 || parameterNames.Length > 1)\n            {\n                InnerWriter.Write(\"(\");\n            }\n            WriteCommaSeparatedList(parameterNames, InnerWriter.Write);\n            if (parameterNames.Length == 0 || parameterNames.Length > 1)\n            {\n                InnerWriter.Write(\")\");\n            }\n            InnerWriter.Write(\" => \");\n        }\n\n        protected internal override void EmitStartLambdaDelegate(string[] parameterNames)\n        {\n            if (parameterNames == null)\n            {\n                throw new ArgumentNullException(\"parameterNames\");\n            }\n\n            EmitStartLambdaExpression(parameterNames);\n            InnerWriter.WriteLine(\"{\");\n        }\n\n        protected internal override void EmitEndLambdaDelegate()\n        {\n            InnerWriter.Write(\"}\");\n        }\n\n        protected internal override void EmitStartConstructor(string typeName)\n        {\n            if (typeName == null)\n            {\n                throw new ArgumentNullException(\"typeName\");\n            }\n\n            InnerWriter.Write(\"new \");\n            InnerWriter.Write(typeName);\n            InnerWriter.Write(\"(\");\n        }\n\n        public override void WriteReturn()\n        {\n            InnerWriter.Write(\"return \");\n        }\n\n        public override void WriteLinePragma(int? lineNumber, string fileName)\n        {\n            InnerWriter.WriteLine();\n            if (lineNumber != null)\n            {\n                InnerWriter.Write(\"#line \");\n                InnerWriter.Write(lineNumber);\n                InnerWriter.Write(\" \\\"\");\n                InnerWriter.Write(fileName);\n                InnerWriter.Write(\"\\\"\");\n                InnerWriter.WriteLine();\n            }\n            else\n            {\n                InnerWriter.WriteLine(\"#line default\");\n                InnerWriter.WriteLine(\"#line hidden\");\n            }\n        }\n\n        public override void WriteHiddenLinePragma()\n        {\n            InnerWriter.WriteLine(\"#line hidden\");\n        }\n\n        public override void WriteHelperHeaderPrefix(string templateTypeName, bool isStatic)\n        {\n            InnerWriter.Write(\"public \");\n            if (isStatic)\n            {\n                InnerWriter.Write(\"static \");\n            }\n            InnerWriter.Write(templateTypeName);\n            InnerWriter.Write(\" \");\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/CSharpRazorCodeGenerator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.Razor.Generator\n{\n    public class CSharpRazorCodeGenerator : RazorCodeGenerator\n    {\n        private const string HiddenLinePragma = \"#line hidden\";\n\n        public CSharpRazorCodeGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host)\n            : base(className, rootNamespaceName, sourceFileName, host)\n        {\n        }\n\n        internal override Func<CodeWriter> CodeWriterFactory\n        {\n            get { return () => new CSharpCodeWriter(); }\n        }\n\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1303:Do not pass literals as localized parameters\", MessageId = \"System.CodeDom.CodeSnippetTypeMember.#ctor(System.String)\", Justification = \"Value is never to be localized\")]\n        protected override void Initialize(CodeGeneratorContext context)\n        {\n            base.Initialize(context);\n\n            context.GeneratedClass.Members.Insert(0, new CodeSnippetTypeMember(HiddenLinePragma));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/CodeGenerationCompleteEventArgs.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Razor.Generator\n{\n    public class CodeGenerationCompleteEventArgs : EventArgs\n    {\n        public CodeGenerationCompleteEventArgs(string virtualPath, string physicalPath, CodeCompileUnit generatedCode)\n        {\n            if (String.IsNullOrEmpty(virtualPath))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"virtualPath\");\n            }\n            if (generatedCode == null)\n            {\n                throw new ArgumentNullException(\"generatedCode\");\n            }\n            VirtualPath = virtualPath;\n            PhysicalPath = physicalPath;\n            GeneratedCode = generatedCode;\n        }\n\n        public CodeCompileUnit GeneratedCode { get; private set; }\n        public string VirtualPath { get; private set; }\n        public string PhysicalPath { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/CodeGeneratorContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq;\nusing System.Text;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Utils;\n\nnamespace System.Web.Razor.Generator\n{\n    public class CodeGeneratorContext\n    {\n        private const string DesignTimeHelperMethodName = \"__RazorDesignTimeHelpers__\";\n\n        private int _nextDesignTimePragmaId = 1;\n        private bool _expressionHelperVariableWriten;\n        private CodeMemberMethod _designTimeHelperMethod;\n        private StatementBuffer _currentBuffer = new StatementBuffer();\n\n        private CodeGeneratorContext()\n        {\n            ExpressionRenderingMode = ExpressionRenderingMode.WriteToOutput;\n        }\n\n        // Internal/Private state. Technically consumers might want to use some of these but they can implement them independently if necessary.\n        // It's way safer to make them internal for now, especially with the code generator stuff in a bit of flux.\n        internal ExpressionRenderingMode ExpressionRenderingMode { get; set; }\n        private Action<string, CodeLinePragma> StatementCollector { get; set; }\n        private Func<CodeWriter> CodeWriterFactory { get; set; }\n\n        public string SourceFile { get; internal set; }\n        public CodeCompileUnit CompileUnit { get; internal set; }\n        public CodeNamespace Namespace { get; internal set; }\n        public CodeTypeDeclaration GeneratedClass { get; internal set; }\n        public RazorEngineHost Host { get; private set; }\n        public IDictionary<int, GeneratedCodeMapping> CodeMappings { get; private set; }\n        public string TargetWriterName { get; set; }\n        public CodeMemberMethod TargetMethod { get; set; }\n\n        public string CurrentBufferedStatement\n        {\n            get { return _currentBuffer == null ? String.Empty : _currentBuffer.Builder.ToString(); }\n        }\n\n        public static CodeGeneratorContext Create(RazorEngineHost host, string className, string rootNamespace, string sourceFile, bool shouldGenerateLinePragmas)\n        {\n            return Create(host, null, className, rootNamespace, sourceFile, shouldGenerateLinePragmas);\n        }\n\n        internal static CodeGeneratorContext Create(RazorEngineHost host, Func<CodeWriter> writerFactory, string className, string rootNamespace, string sourceFile, bool shouldGenerateLinePragmas)\n        {\n            CodeGeneratorContext context = new CodeGeneratorContext()\n            {\n                Host = host,\n                CodeWriterFactory = writerFactory,\n                SourceFile = shouldGenerateLinePragmas ? sourceFile : null,\n                CompileUnit = new CodeCompileUnit(),\n                Namespace = new CodeNamespace(rootNamespace),\n                GeneratedClass = new CodeTypeDeclaration(className)\n                {\n                    IsClass = true\n                },\n                TargetMethod = new CodeMemberMethod()\n                {\n                    Name = host.GeneratedClassContext.ExecuteMethodName,\n                    Attributes = MemberAttributes.Override | MemberAttributes.Public\n                },\n                CodeMappings = new Dictionary<int, GeneratedCodeMapping>()\n            };\n            context.CompileUnit.Namespaces.Add(context.Namespace);\n            context.Namespace.Types.Add(context.GeneratedClass);\n            context.GeneratedClass.Members.Add(context.TargetMethod);\n\n            context.Namespace.Imports.AddRange(host.NamespaceImports\n                                                   .Select(s => new CodeNamespaceImport(s))\n                                                   .ToArray());\n\n            return context;\n        }\n\n        public void AddDesignTimeHelperStatement(CodeSnippetStatement statement)\n        {\n            if (_designTimeHelperMethod == null)\n            {\n                _designTimeHelperMethod = new CodeMemberMethod()\n                {\n                    Name = DesignTimeHelperMethodName,\n                    Attributes = MemberAttributes.Private\n                };\n                _designTimeHelperMethod.Statements.Add(\n                    new CodeSnippetStatement(BuildCodeString(cw => cw.WriteDisableUnusedFieldWarningPragma())));\n                _designTimeHelperMethod.Statements.Add(\n                    new CodeSnippetStatement(BuildCodeString(cw => cw.WriteRestoreUnusedFieldWarningPragma())));\n                GeneratedClass.Members.Insert(0, _designTimeHelperMethod);\n            }\n            _designTimeHelperMethod.Statements.Insert(_designTimeHelperMethod.Statements.Count - 1, statement);\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2233:OperationsShouldNotOverflow\", MessageId = \"generatedCodeStart+1\", Justification = \"There is no risk of overflow in this case\")]\n        public int AddCodeMapping(SourceLocation sourceLocation, int generatedCodeStart, int generatedCodeLength)\n        {\n            if (generatedCodeStart == Int32.MaxValue)\n            {\n                throw new ArgumentOutOfRangeException(\"generatedCodeStart\");\n            }\n\n            GeneratedCodeMapping mapping = new GeneratedCodeMapping(\n                startOffset: sourceLocation.AbsoluteIndex,\n                startLine: sourceLocation.LineIndex + 1,\n                startColumn: sourceLocation.CharacterIndex + 1,\n                startGeneratedColumn: generatedCodeStart + 1,\n                codeLength: generatedCodeLength);\n\n            int id = _nextDesignTimePragmaId++;\n            CodeMappings[id] = mapping;\n            return id;\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1011:ConsiderPassingBaseTypesAsParameters\", Justification = \"This method requires that a Span be provided\")]\n        public CodeLinePragma GenerateLinePragma(Span target)\n        {\n            return GenerateLinePragma(target, 0);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1011:ConsiderPassingBaseTypesAsParameters\", Justification = \"This method requires that a Span be provided\")]\n        public CodeLinePragma GenerateLinePragma(Span target, int generatedCodeStart)\n        {\n            return GenerateLinePragma(target, generatedCodeStart, target.Content.Length);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1011:ConsiderPassingBaseTypesAsParameters\", Justification = \"This method requires that a Span be provided\")]\n        public CodeLinePragma GenerateLinePragma(Span target, int generatedCodeStart, int codeLength)\n        {\n            return GenerateLinePragma(target.Start, generatedCodeStart, codeLength);\n        }\n\n        public CodeLinePragma GenerateLinePragma(SourceLocation start, int generatedCodeStart, int codeLength)\n        {\n            if (!String.IsNullOrEmpty(SourceFile))\n            {\n                if (Host.DesignTimeMode)\n                {\n                    int mappingId = AddCodeMapping(start, generatedCodeStart, codeLength);\n                    return new CodeLinePragma(SourceFile, mappingId);\n                }\n                return new CodeLinePragma(SourceFile, start.LineIndex + 1);\n            }\n            return null;\n        }\n\n        public void BufferStatementFragment(Span sourceSpan)\n        {\n            BufferStatementFragment(sourceSpan.Content, sourceSpan);\n        }\n\n        public void BufferStatementFragment(string fragment)\n        {\n            BufferStatementFragment(fragment, null);\n        }\n\n        public void BufferStatementFragment(string fragment, Span sourceSpan)\n        {\n            if (sourceSpan != null && _currentBuffer.LinePragmaSpan == null)\n            {\n                _currentBuffer.LinePragmaSpan = sourceSpan;\n\n                // Pad the output as necessary\n                int start = _currentBuffer.Builder.Length;\n                if (_currentBuffer.GeneratedCodeStart != null)\n                {\n                    start = _currentBuffer.GeneratedCodeStart.Value;\n                }\n\n                int paddingLength; // unused, in this case there is enough context in the original code to calculate the right padding length\n                                   // (padded.Length - _currentBuffer.Builder.Length)\n\n                string padded = CodeGeneratorPaddingHelper.Pad(Host, _currentBuffer.Builder.ToString(), sourceSpan, start, out paddingLength);\n                _currentBuffer.GeneratedCodeStart = start + (padded.Length - _currentBuffer.Builder.Length);\n                _currentBuffer.Builder.Clear();\n                _currentBuffer.Builder.Append(padded);\n            }\n            _currentBuffer.Builder.Append(fragment);\n        }\n\n        public void MarkStartOfGeneratedCode()\n        {\n            _currentBuffer.MarkStart();\n        }\n\n        public void MarkEndOfGeneratedCode()\n        {\n            _currentBuffer.MarkEnd();\n        }\n\n        public void FlushBufferedStatement()\n        {\n            if (_currentBuffer.Builder.Length > 0)\n            {\n                CodeLinePragma pragma = null;\n                if (_currentBuffer.LinePragmaSpan != null)\n                {\n                    int start = _currentBuffer.Builder.Length;\n                    if (_currentBuffer.GeneratedCodeStart != null)\n                    {\n                        start = _currentBuffer.GeneratedCodeStart.Value;\n                    }\n                    int len = _currentBuffer.Builder.Length - start;\n                    if (_currentBuffer.CodeLength != null)\n                    {\n                        len = _currentBuffer.CodeLength.Value;\n                    }\n                    pragma = GenerateLinePragma(_currentBuffer.LinePragmaSpan, start, len);\n                }\n                AddStatement(_currentBuffer.Builder.ToString(), pragma);\n                _currentBuffer.Reset();\n            }\n        }\n\n        public void AddStatement(string generatedCode)\n        {\n            AddStatement(generatedCode, null);\n        }\n\n        public void AddStatement(string body, CodeLinePragma pragma)\n        {\n            if (StatementCollector == null)\n            {\n                TargetMethod.Statements.Add(new CodeSnippetStatement(body) { LinePragma = pragma });\n            }\n            else\n            {\n                StatementCollector(body, pragma);\n            }\n        }\n\n        public void EnsureExpressionHelperVariable()\n        {\n            if (!_expressionHelperVariableWriten)\n            {\n                GeneratedClass.Members.Insert(0,\n                                              new CodeMemberField(typeof(object), \"__o\")\n                                              {\n                                                  Attributes = MemberAttributes.Private | MemberAttributes.Static\n                                              });\n                _expressionHelperVariableWriten = true;\n            }\n        }\n\n        public IDisposable ChangeStatementCollector(Action<string, CodeLinePragma> collector)\n        {\n            Action<string, CodeLinePragma> oldCollector = StatementCollector;\n            StatementCollector = collector;\n            return new DisposableAction(() =>\n            {\n                StatementCollector = oldCollector;\n            });\n        }\n\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1308:NormalizeStringsToUppercase\", Justification = \"We explicitly want the lower-case string here\")]\n        public void AddContextCall(Span contentSpan, string methodName, bool isLiteral)\n        {\n            AddStatement(BuildCodeString(cw =>\n            {\n                cw.WriteStartMethodInvoke(methodName);\n                if (!String.IsNullOrEmpty(TargetWriterName))\n                {\n                    cw.WriteSnippet(TargetWriterName);\n                    cw.WriteParameterSeparator();\n                }\n                cw.WriteStringLiteral(Host.InstrumentedSourceFilePath);\n                cw.WriteParameterSeparator();\n                cw.WriteSnippet(contentSpan.Start.AbsoluteIndex.ToString(CultureInfo.InvariantCulture));\n                cw.WriteParameterSeparator();\n                cw.WriteSnippet(contentSpan.Content.Length.ToString(CultureInfo.InvariantCulture));\n                cw.WriteParameterSeparator();\n                cw.WriteSnippet(isLiteral.ToString().ToLowerInvariant());\n                cw.WriteEndMethodInvoke();\n                cw.WriteEndStatement();\n            }));\n        }\n\n        internal CodeWriter CreateCodeWriter()\n        {\n            Debug.Assert(CodeWriterFactory != null);\n            if (CodeWriterFactory == null)\n            {\n                throw new InvalidOperationException(RazorResources.CreateCodeWriter_NoCodeWriter);\n            }\n            return CodeWriterFactory();\n        }\n\n        internal string BuildCodeString(Action<CodeWriter> action)\n        {\n            using (CodeWriter cw = CodeWriterFactory())\n            {\n                action(cw);\n                return cw.Content;\n            }\n        }\n\n        private class StatementBuffer\n        {\n            public StringBuilder Builder = new StringBuilder();\n            public int? GeneratedCodeStart;\n            public int? CodeLength;\n            public Span LinePragmaSpan;\n\n            public void Reset()\n            {\n                Builder.Clear();\n                GeneratedCodeStart = null;\n                CodeLength = null;\n                LinePragmaSpan = null;\n            }\n\n            public void MarkStart()\n            {\n                GeneratedCodeStart = Builder.Length;\n            }\n\n            public void MarkEnd()\n            {\n                CodeLength = Builder.Length - GeneratedCodeStart;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/CodeGeneratorPaddingHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.Razor.Generator\n{\n    internal static class CodeGeneratorPaddingHelper\n    {\n        private static readonly char[] _newLineChars = { '\\r', '\\n' };\n\n        // there is some duplicity of code here, but its very simple and since this is a host path, I'd rather not create another class to encapsulate the data.\n        public static int PaddingCharCount(RazorEngineHost host, Span target, int generatedStart)\n        {\n            int padding = CalculatePadding(host, target, generatedStart);\n\n            if (host.DesignTimeMode && host.IsIndentingWithTabs)\n            {\n                int spaces;\n                int tabs = Math.DivRem(padding, host.TabSize, out spaces);\n\n                return tabs + spaces;\n            }\n            else\n            {\n                return padding;\n            }\n        }\n\n        // Special case for statement padding to account for brace positioning in the editor.\n        public static string PadStatement(RazorEngineHost host, string code, Span target, ref int startGeneratedCode, out int paddingCharCount)\n        {\n            if (host == null)\n            {\n                throw new ArgumentNullException(\"host\");\n            }\n\n            if (target == null)\n            {\n                throw new ArgumentNullException(\"target\");\n            }\n\n            // We are passing 0 rather than startgeneratedcode intentionally (keeping v2 behavior).\n            int padding = CalculatePadding(host, target, 0);\n\n            // We treat statement padding specially so for brace positioning, so that in the following example:\n            //   @if (foo > 0)\n            //   {\n            //   }\n            //\n            // the braces shows up under the @ rather than under the if.\n            if (host.DesignTimeMode &&\n                padding > 0 &&\n                target.Previous.Kind == SpanKind.Transition && // target.Previous is guaranteed to be none null if you got any padding.\n                String.Equals(target.Previous.Content, SyntaxConstants.TransitionString))\n            {\n                padding--;\n                startGeneratedCode--;\n            }\n\n            string generatedCode = PadInternal(host, code, padding, out paddingCharCount);\n\n            return generatedCode;\n        }\n\n        public static string Pad(RazorEngineHost host, string code, Span target, out int paddingCharCount)\n        {\n            int padding = CalculatePadding(host, target, 0);\n\n            return PadInternal(host, code, padding, out paddingCharCount);\n        }\n\n        public static string Pad(RazorEngineHost host, string code, Span target, int generatedStart, out int paddingCharCount)\n        {\n            int padding = CalculatePadding(host, target, generatedStart);\n\n            return PadInternal(host, code, padding, out paddingCharCount);\n        }\n\n        // internal for unit testing only, not intended to be used directly in code\n        internal static int CalculatePadding(RazorEngineHost host, Span target, int generatedStart)\n        {\n            if (host == null)\n            {\n                throw new ArgumentNullException(\"host\");\n            }\n\n            if (target == null)\n            {\n                throw new ArgumentNullException(\"target\");\n            }\n\n            int padding;\n\n            padding = CollectSpacesAndTabs(target, host.TabSize) - generatedStart;\n\n            // if we add generated text that is longer than the padding we wanted to insert we have no recourse and we have to skip padding\n            // example:\n            // Razor code at column zero: @somecode()\n            // Generated code will be:\n            // In design time: __o = somecode();\n            // In Run time: Write(somecode());\n            //\n            // In both cases the padding would have been 1 space to remote the space the @ symbol takes, which will be smaller than the 6 chars the hidden generated code takes.\n            if (padding < 0)\n            {\n                padding = 0;\n            }\n\n            return padding;\n        }\n\n        private static string PadInternal(RazorEngineHost host, string code, int padding, out int paddingCharCount)\n        {\n            if (host.DesignTimeMode && host.IsIndentingWithTabs)\n            {\n                int spaces;\n                int tabs = Math.DivRem(padding, host.TabSize, out spaces);\n\n                paddingCharCount = tabs + spaces;\n\n                return new string('\\t', tabs) + new string(' ', spaces) + code;\n            }\n            else\n            {\n                paddingCharCount = padding;\n                return code.PadLeft(padding + code.Length, ' ');\n            }\n        }\n\n        private static int CollectSpacesAndTabs(Span target, int tabSize)\n        {\n            Span firstSpanInLine = target;\n\n            string currentContent = null;\n\n            while (firstSpanInLine.Previous != null)\n            {\n                // When scanning previous spans we need to be break down the spans with spaces.\n                // Because the parser doesn't so for example a span looking like \\n\\n\\t needs to be broken down, and we should just grab the \\t.\n                String previousContent = firstSpanInLine.Previous.Content ?? String.Empty;\n\n                int lastNewLineIndex = previousContent.LastIndexOfAny(_newLineChars);\n\n                if (lastNewLineIndex < 0)\n                {\n                    firstSpanInLine = firstSpanInLine.Previous;\n                }\n                else\n                {\n                    if (lastNewLineIndex != previousContent.Length - 1)\n                    {\n                        firstSpanInLine = firstSpanInLine.Previous;\n                        currentContent = previousContent.Substring(lastNewLineIndex + 1);\n                    }\n\n                    break;\n                }\n            }\n\n            // We need to walk from the beginning of the line, because space + tab(tabSize) = tabSize columns, but tab(tabSize) + space = tabSize+1 columns.\n            Span currentSpanInLine = firstSpanInLine;\n\n            if (currentContent == null)\n            {\n                currentContent = currentSpanInLine.Content;\n            }\n\n            int padding = 0;\n            while (currentSpanInLine != target)\n            {\n                if (currentContent != null)\n                {\n                    for (int i = 0; i < currentContent.Length; i++)\n                    {\n                        if (currentContent[i] == '\\t')\n                        {\n                            // Example:\n                            // <space><space><tab><tab>:\n                            // iter 1) 1\n                            // iter 2) 2\n                            // iter 3) 4 = 2 + (4 - 2)\n                            // iter 4) 8 = 4 + (4 - 0)\n                            padding = padding + (tabSize - (padding % tabSize));\n                        }\n                        else\n                        {\n                            padding++;\n                        }\n                    }\n                }\n\n                currentSpanInLine = currentSpanInLine.Next;\n                currentContent = currentSpanInLine.Content;\n            }\n\n            return padding;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/CodeWriter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.Globalization;\nusing System.IO;\n\nnamespace System.Web.Razor.Generator\n{\n    // Utility class which helps write code snippets\n    internal abstract class CodeWriter : IDisposable\n    {\n        private StringWriter _writer;\n\n        protected CodeWriter()\n        {\n        }\n\n        private enum WriterMode\n        {\n            Constructor,\n            MethodCall,\n            LambdaDelegate,\n            LambdaExpression\n        }\n\n        public string Content\n        {\n            get { return InnerWriter.ToString(); }\n        }\n\n        public StringWriter InnerWriter\n        {\n            get\n            {\n                if (_writer == null)\n                {\n                    _writer = new StringWriter(CultureInfo.InvariantCulture);\n                }\n                return _writer;\n            }\n        }\n\n        public virtual bool SupportsMidStatementLinePragmas\n        {\n            get { return true; }\n        }\n\n        public abstract void WriteParameterSeparator();\n        public abstract void WriteReturn();\n        public abstract void WriteLinePragma(int? lineNumber, string fileName);\n        public abstract void WriteHelperHeaderPrefix(string templateTypeName, bool isStatic);\n        public abstract void WriteSnippet(string snippet);\n        public abstract void WriteStringLiteral(string literal);\n        public abstract int WriteVariableDeclaration(string type, string name, string value);\n\n        public virtual void WriteLinePragma()\n        {\n            WriteLinePragma(null);\n        }\n\n        public virtual void WriteLinePragma(CodeLinePragma pragma)\n        {\n            if (pragma == null)\n            {\n                WriteLinePragma(null, null);\n            }\n            else\n            {\n                WriteLinePragma(pragma.LineNumber, pragma.FileName);\n            }\n        }\n\n        public virtual void WriteHiddenLinePragma()\n        {\n        }\n\n        public virtual void WriteDisableUnusedFieldWarningPragma()\n        {\n        }\n\n        public virtual void WriteRestoreUnusedFieldWarningPragma()\n        {\n        }\n\n        public virtual void WriteIdentifier(string identifier)\n        {\n            InnerWriter.Write(identifier);\n        }\n\n        public virtual void WriteHelperHeaderSuffix(string templateTypeName)\n        {\n        }\n\n        public virtual void WriteHelperTrailer()\n        {\n        }\n\n        public void WriteStartMethodInvoke(string methodName)\n        {\n            EmitStartMethodInvoke(methodName);\n        }\n\n        public void WriteStartMethodInvoke(string methodName, params string[] genericArguments)\n        {\n            EmitStartMethodInvoke(methodName, genericArguments);\n        }\n\n        public void WriteEndMethodInvoke()\n        {\n            EmitEndMethodInvoke();\n        }\n\n        public virtual void WriteEndStatement()\n        {\n        }\n\n        public virtual void WriteStartAssignment(string variableName)\n        {\n            InnerWriter.Write(variableName);\n            InnerWriter.Write(\" = \");\n        }\n\n        public void WriteStartLambdaExpression(params string[] parameterNames)\n        {\n            EmitStartLambdaExpression(parameterNames);\n        }\n\n        public void WriteStartConstructor(string typeName)\n        {\n            EmitStartConstructor(typeName);\n        }\n\n        public void WriteStartLambdaDelegate(params string[] parameterNames)\n        {\n            EmitStartLambdaDelegate(parameterNames);\n        }\n\n        public void WriteEndLambdaExpression()\n        {\n            EmitEndLambdaExpression();\n        }\n\n        public void WriteEndConstructor()\n        {\n            EmitEndConstructor();\n        }\n\n        public void WriteEndLambdaDelegate()\n        {\n            EmitEndLambdaDelegate();\n        }\n\n        public virtual void WriteLineContinuation()\n        {\n        }\n\n        public virtual void WriteBooleanLiteral(bool value)\n        {\n            WriteSnippet(value.ToString(CultureInfo.InvariantCulture));\n        }\n\n        public void Dispose()\n        {\n            Dispose(true);\n            GC.SuppressFinalize(this);\n        }\n\n        public void Clear()\n        {\n            if (InnerWriter != null)\n            {\n                InnerWriter.GetStringBuilder().Clear();\n            }\n        }\n\n        public CodeSnippetStatement ToStatement()\n        {\n            return new CodeSnippetStatement(Content);\n        }\n\n        public CodeSnippetTypeMember ToTypeMember()\n        {\n            return new CodeSnippetTypeMember(Content);\n        }\n\n        protected internal abstract void EmitStartLambdaDelegate(string[] parameterNames);\n        protected internal abstract void EmitStartLambdaExpression(string[] parameterNames);\n        protected internal abstract void EmitStartConstructor(string typeName);\n        protected internal abstract void EmitStartMethodInvoke(string methodName);\n\n        protected internal virtual void EmitStartMethodInvoke(string methodName, params string[] genericArguments)\n        {\n            EmitStartMethodInvoke(methodName);\n        }\n\n        protected internal abstract void EmitEndLambdaDelegate();\n        protected internal abstract void EmitEndLambdaExpression();\n        protected internal abstract void EmitEndConstructor();\n        protected internal abstract void EmitEndMethodInvoke();\n\n        protected virtual void Dispose(bool disposing)\n        {\n            if (disposing && _writer != null)\n            {\n                _writer.Dispose();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/CodeWriterExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Web.Razor.Text;\n\nnamespace System.Web.Razor.Generator\n{\n    internal static class CodeWriterExtensions\n    {\n        public static void WriteLocationTaggedString(this CodeWriter writer, LocationTagged<string> value)\n        {\n            writer.WriteStartMethodInvoke(\"Tuple.Create\");\n            writer.WriteStringLiteral(value.Value);\n            writer.WriteParameterSeparator();\n            writer.WriteSnippet(value.Location.AbsoluteIndex.ToString(CultureInfo.CurrentCulture));\n            writer.WriteEndMethodInvoke();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/DynamicAttributeBlockCodeGenerator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Linq;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Text;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Razor.Generator\n{\n    public class DynamicAttributeBlockCodeGenerator : BlockCodeGenerator\n    {\n        private const string ValueWriterName = \"__razor_attribute_value_writer\";\n        private string _oldTargetWriter;\n        private bool _isExpression;\n        private ExpressionRenderingMode _oldRenderingMode;\n\n        public DynamicAttributeBlockCodeGenerator(LocationTagged<string> prefix, int offset, int line, int col)\n            : this(prefix, new SourceLocation(offset, line, col))\n        {\n        }\n\n        public DynamicAttributeBlockCodeGenerator(LocationTagged<string> prefix, SourceLocation valueStart)\n        {\n            Prefix = prefix;\n            ValueStart = valueStart;\n        }\n\n        public LocationTagged<string> Prefix { get; private set; }\n        public SourceLocation ValueStart { get; private set; }\n\n        public override void GenerateStartBlockCode(Block target, CodeGeneratorContext context)\n        {\n            if (context.Host.DesignTimeMode)\n            {\n                return; // Don't generate anything!\n            }\n\n            // What kind of block is nested within\n            string generatedCode;\n            Block child = target.Children.Where(n => n.IsBlock).Cast<Block>().FirstOrDefault();\n            if (child != null && child.Type == BlockType.Expression)\n            {\n                _isExpression = true;\n                generatedCode = context.BuildCodeString(cw =>\n                {\n                    cw.WriteParameterSeparator();\n                    cw.WriteStartMethodInvoke(\"Tuple.Create\");\n                    cw.WriteLocationTaggedString(Prefix);\n                    cw.WriteParameterSeparator();\n                    cw.WriteStartMethodInvoke(\"Tuple.Create\", \"System.Object\", \"System.Int32\");\n                });\n\n                _oldRenderingMode = context.ExpressionRenderingMode;\n                context.ExpressionRenderingMode = ExpressionRenderingMode.InjectCode;\n            }\n            else\n            {\n                generatedCode = context.BuildCodeString(cw =>\n                {\n                    cw.WriteParameterSeparator();\n                    cw.WriteStartMethodInvoke(\"Tuple.Create\");\n                    cw.WriteLocationTaggedString(Prefix);\n                    cw.WriteParameterSeparator();\n                    cw.WriteStartMethodInvoke(\"Tuple.Create\", \"System.Object\", \"System.Int32\");\n                    cw.WriteStartConstructor(context.Host.GeneratedClassContext.TemplateTypeName);\n                    cw.WriteStartLambdaDelegate(ValueWriterName);\n                });\n            }\n\n            context.MarkEndOfGeneratedCode();\n            context.BufferStatementFragment(generatedCode);\n\n            _oldTargetWriter = context.TargetWriterName;\n            context.TargetWriterName = ValueWriterName;\n        }\n\n        public override void GenerateEndBlockCode(Block target, CodeGeneratorContext context)\n        {\n            if (context.Host.DesignTimeMode)\n            {\n                return; // Don't generate anything!\n            }\n\n            string generatedCode;\n            if (_isExpression)\n            {\n                generatedCode = context.BuildCodeString(cw =>\n                {\n                    cw.WriteParameterSeparator();\n                    cw.WriteSnippet(ValueStart.AbsoluteIndex.ToString(CultureInfo.CurrentCulture));\n                    cw.WriteEndMethodInvoke();\n                    cw.WriteParameterSeparator();\n                    // literal: false - This attribute value is not a literal value, it is dynamically generated\n                    cw.WriteBooleanLiteral(false);\n                    cw.WriteEndMethodInvoke();\n                    cw.WriteLineContinuation();\n                });\n                context.ExpressionRenderingMode = _oldRenderingMode;\n            }\n            else\n            {\n                generatedCode = context.BuildCodeString(cw =>\n                {\n                    cw.WriteEndLambdaDelegate();\n                    cw.WriteEndConstructor();\n                    cw.WriteParameterSeparator();\n                    cw.WriteSnippet(ValueStart.AbsoluteIndex.ToString(CultureInfo.CurrentCulture));\n                    cw.WriteEndMethodInvoke();\n                    cw.WriteParameterSeparator();\n                    // literal: false - This attribute value is not a literal value, it is dynamically generated\n                    cw.WriteBooleanLiteral(false);\n                    cw.WriteEndMethodInvoke();\n                    cw.WriteLineContinuation();\n                });\n            }\n\n            context.AddStatement(generatedCode);\n            context.TargetWriterName = _oldTargetWriter;\n        }\n\n        public override string ToString()\n        {\n            return String.Format(CultureInfo.CurrentCulture, \"DynAttr:{0:F}\", Prefix);\n        }\n\n        public override bool Equals(object obj)\n        {\n            DynamicAttributeBlockCodeGenerator other = obj as DynamicAttributeBlockCodeGenerator;\n            return other != null &&\n                   Equals(other.Prefix, Prefix);\n        }\n\n        public override int GetHashCode()\n        {\n            return HashCodeCombiner.Start()\n                .Add(Prefix)\n                .CombinedHash;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/ExpressionCodeGenerator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.Razor.Generator\n{\n    public class ExpressionCodeGenerator : HybridCodeGenerator\n    {\n        public override void GenerateStartBlockCode(Block target, CodeGeneratorContext context)\n        {\n            if (context.Host.EnableInstrumentation && context.ExpressionRenderingMode == ExpressionRenderingMode.WriteToOutput)\n            {\n                Span contentSpan = target.Children\n                    .OfType<Span>()\n                    .Where(s => s.Kind == SpanKind.Code || s.Kind == SpanKind.Markup)\n                    .FirstOrDefault();\n\n                if (contentSpan != null)\n                {\n                    context.AddContextCall(contentSpan, context.Host.GeneratedClassContext.BeginContextMethodName, false);\n                }\n            }\n\n            string writeInvocation = context.BuildCodeString(cw =>\n            {\n                if (context.Host.DesignTimeMode)\n                {\n                    context.EnsureExpressionHelperVariable();\n                    cw.WriteStartAssignment(\"__o\");\n                }\n                else if (context.ExpressionRenderingMode == ExpressionRenderingMode.WriteToOutput)\n                {\n                    if (!String.IsNullOrEmpty(context.TargetWriterName))\n                    {\n                        cw.WriteStartMethodInvoke(context.Host.GeneratedClassContext.WriteToMethodName);\n                        cw.WriteSnippet(context.TargetWriterName);\n                        cw.WriteParameterSeparator();\n                    }\n                    else\n                    {\n                        cw.WriteStartMethodInvoke(context.Host.GeneratedClassContext.WriteMethodName);\n                    }\n                }\n            });\n\n            context.BufferStatementFragment(writeInvocation);\n            context.MarkStartOfGeneratedCode();\n        }\n\n        public override void GenerateEndBlockCode(Block target, CodeGeneratorContext context)\n        {\n            string endBlock = context.BuildCodeString(cw =>\n            {\n                if (context.ExpressionRenderingMode == ExpressionRenderingMode.WriteToOutput)\n                {\n                    if (!context.Host.DesignTimeMode)\n                    {\n                        cw.WriteEndMethodInvoke();\n                    }\n                    cw.WriteEndStatement();\n                }\n                else\n                {\n                    cw.WriteLineContinuation();\n                }\n            });\n\n            context.MarkEndOfGeneratedCode();\n            context.BufferStatementFragment(endBlock);\n            context.FlushBufferedStatement();\n\n            if (context.Host.EnableInstrumentation && context.ExpressionRenderingMode == ExpressionRenderingMode.WriteToOutput)\n            {\n                Span contentSpan = target.Children\n                    .OfType<Span>()\n                    .Where(s => s.Kind == SpanKind.Code || s.Kind == SpanKind.Markup)\n                    .FirstOrDefault();\n\n                if (contentSpan != null)\n                {\n                    context.AddContextCall(contentSpan, context.Host.GeneratedClassContext.EndContextMethodName, false);\n                }\n            }\n        }\n\n        public override void GenerateCode(Span target, CodeGeneratorContext context)\n        {\n            Span sourceSpan = null;\n            if (context.CreateCodeWriter().SupportsMidStatementLinePragmas || context.ExpressionRenderingMode == ExpressionRenderingMode.WriteToOutput)\n            {\n                sourceSpan = target;\n            }\n            context.BufferStatementFragment(target.Content, sourceSpan);\n        }\n\n        public override string ToString()\n        {\n            return \"Expr\";\n        }\n\n        public override bool Equals(object obj)\n        {\n            return obj is ExpressionCodeGenerator;\n        }\n\n        public override int GetHashCode()\n        {\n            return base.GetHashCode();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/ExpressionRenderingMode.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Razor.Generator\n{\n    public enum ExpressionRenderingMode\n    {\n        /// <summary>\n        /// Indicates that expressions should be written to the output stream\n        /// </summary>\n        /// <example>\n        /// If @foo is rendered with WriteToOutput, the code generator would output the following code:\n        /// \n        /// Write(foo);\n        /// </example>\n        WriteToOutput,\n\n        /// <summary>\n        /// Indicates that expressions should simply be placed as-is in the code, and the context in which\n        /// the code exists will be used to render it\n        /// </summary>\n        /// <example>\n        /// If @foo is rendered with InjectCode, the code generator would output the following code:\n        /// \n        /// foo\n        /// </example>\n        InjectCode\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/GeneratedClassContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Razor.Generator\n{\n    public struct GeneratedClassContext\n    {\n        public static readonly string DefaultWriteMethodName = \"Write\";\n        public static readonly string DefaultWriteLiteralMethodName = \"WriteLiteral\";\n        public static readonly string DefaultExecuteMethodName = \"Execute\";\n        public static readonly string DefaultLayoutPropertyName = \"Layout\";\n        public static readonly string DefaultWriteAttributeMethodName = \"WriteAttribute\";\n        public static readonly string DefaultWriteAttributeToMethodName = \"WriteAttributeTo\";\n\n        public static readonly GeneratedClassContext Default = new GeneratedClassContext(DefaultExecuteMethodName,\n                                                                                         DefaultWriteMethodName,\n                                                                                         DefaultWriteLiteralMethodName);\n\n        public GeneratedClassContext(string executeMethodName, string writeMethodName, string writeLiteralMethodName)\n            : this()\n        {\n            if (String.IsNullOrEmpty(executeMethodName))\n            {\n                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture,\n                                                          CommonResources.Argument_Cannot_Be_Null_Or_Empty,\n                                                          \"executeMethodName\"),\n                                            \"executeMethodName\");\n            }\n            if (String.IsNullOrEmpty(writeMethodName))\n            {\n                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture,\n                                                          CommonResources.Argument_Cannot_Be_Null_Or_Empty,\n                                                          \"writeMethodName\"),\n                                            \"writeMethodName\");\n            }\n            if (String.IsNullOrEmpty(writeLiteralMethodName))\n            {\n                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture,\n                                                          CommonResources.Argument_Cannot_Be_Null_Or_Empty,\n                                                          \"writeLiteralMethodName\"),\n                                            \"writeLiteralMethodName\");\n            }\n\n            WriteMethodName = writeMethodName;\n            WriteLiteralMethodName = writeLiteralMethodName;\n            ExecuteMethodName = executeMethodName;\n\n            WriteToMethodName = null;\n            WriteLiteralToMethodName = null;\n            TemplateTypeName = null;\n            DefineSectionMethodName = null;\n\n            LayoutPropertyName = DefaultLayoutPropertyName;\n            WriteAttributeMethodName = DefaultWriteAttributeMethodName;\n            WriteAttributeToMethodName = DefaultWriteAttributeToMethodName;\n        }\n\n        public GeneratedClassContext(string executeMethodName,\n                                     string writeMethodName,\n                                     string writeLiteralMethodName,\n                                     string writeToMethodName,\n                                     string writeLiteralToMethodName,\n                                     string templateTypeName)\n            : this(executeMethodName, writeMethodName, writeLiteralMethodName)\n        {\n            WriteToMethodName = writeToMethodName;\n            WriteLiteralToMethodName = writeLiteralToMethodName;\n            TemplateTypeName = templateTypeName;\n        }\n\n        public GeneratedClassContext(string executeMethodName,\n                                     string writeMethodName,\n                                     string writeLiteralMethodName,\n                                     string writeToMethodName,\n                                     string writeLiteralToMethodName,\n                                     string templateTypeName,\n                                     string defineSectionMethodName)\n            : this(executeMethodName, writeMethodName, writeLiteralMethodName, writeToMethodName, writeLiteralToMethodName, templateTypeName)\n        {\n            DefineSectionMethodName = defineSectionMethodName;\n        }\n\n        public GeneratedClassContext(string executeMethodName,\n                                     string writeMethodName,\n                                     string writeLiteralMethodName,\n                                     string writeToMethodName,\n                                     string writeLiteralToMethodName,\n                                     string templateTypeName,\n                                     string defineSectionMethodName,\n                                     string beginContextMethodName,\n                                     string endContextMethodName)\n            : this(executeMethodName, writeMethodName, writeLiteralMethodName, writeToMethodName, writeLiteralToMethodName, templateTypeName, defineSectionMethodName)\n        {\n            BeginContextMethodName = beginContextMethodName;\n            EndContextMethodName = endContextMethodName;\n        }\n\n        public string WriteMethodName { get; private set; }\n        public string WriteLiteralMethodName { get; private set; }\n        public string WriteToMethodName { get; private set; }\n        public string WriteLiteralToMethodName { get; private set; }\n        public string ExecuteMethodName { get; private set; }\n\n        // Optional Items\n        public string BeginContextMethodName { get; set; }\n        public string EndContextMethodName { get; set; }\n        public string LayoutPropertyName { get; set; }\n        public string DefineSectionMethodName { get; set; }\n        public string TemplateTypeName { get; set; }\n        public string WriteAttributeMethodName { get; set; }\n        public string WriteAttributeToMethodName { get; set; }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1056:UriPropertiesShouldNotBeStrings\", Justification = \"Property is not a URL property\")]\n        public string ResolveUrlMethodName { get; set; }\n\n        public bool AllowSections\n        {\n            get { return !String.IsNullOrEmpty(DefineSectionMethodName); }\n        }\n\n        public bool AllowTemplates\n        {\n            get { return !String.IsNullOrEmpty(TemplateTypeName); }\n        }\n\n        public bool SupportsInstrumentation\n        {\n            get { return !String.IsNullOrEmpty(BeginContextMethodName) && !String.IsNullOrEmpty(EndContextMethodName); }\n        }\n\n        public override bool Equals(object obj)\n        {\n            if (!(obj is GeneratedClassContext))\n            {\n                return false;\n            }\n            GeneratedClassContext other = (GeneratedClassContext)obj;\n            return String.Equals(DefineSectionMethodName, other.DefineSectionMethodName, StringComparison.Ordinal) &&\n                   String.Equals(WriteMethodName, other.WriteMethodName, StringComparison.Ordinal) &&\n                   String.Equals(WriteLiteralMethodName, other.WriteLiteralMethodName, StringComparison.Ordinal) &&\n                   String.Equals(WriteToMethodName, other.WriteToMethodName, StringComparison.Ordinal) &&\n                   String.Equals(WriteLiteralToMethodName, other.WriteLiteralToMethodName, StringComparison.Ordinal) &&\n                   String.Equals(ExecuteMethodName, other.ExecuteMethodName, StringComparison.Ordinal) &&\n                   String.Equals(TemplateTypeName, other.TemplateTypeName, StringComparison.Ordinal) &&\n                   String.Equals(BeginContextMethodName, other.BeginContextMethodName, StringComparison.Ordinal) &&\n                   String.Equals(EndContextMethodName, other.EndContextMethodName, StringComparison.Ordinal);\n        }\n\n        public override int GetHashCode()\n        {\n            // TODO: Use HashCodeCombiner\n            return DefineSectionMethodName.GetHashCode() ^\n                   WriteMethodName.GetHashCode() ^\n                   WriteLiteralMethodName.GetHashCode() ^\n                   WriteToMethodName.GetHashCode() ^\n                   WriteLiteralToMethodName.GetHashCode() ^\n                   ExecuteMethodName.GetHashCode() ^\n                   TemplateTypeName.GetHashCode() ^\n                   BeginContextMethodName.GetHashCode() ^\n                   EndContextMethodName.GetHashCode();\n        }\n\n        public static bool operator ==(GeneratedClassContext left, GeneratedClassContext right)\n        {\n            return left.Equals(right);\n        }\n\n        public static bool operator !=(GeneratedClassContext left, GeneratedClassContext right)\n        {\n            return !left.Equals(right);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/GeneratedCodeMapping.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Razor.Generator\n{\n    public struct GeneratedCodeMapping\n    {\n        public GeneratedCodeMapping(int startLine, int startColumn, int startGeneratedColumn, int codeLength)\n            : this(null, startLine, startColumn, startGeneratedColumn, codeLength)\n        {\n        }\n\n        public GeneratedCodeMapping(int startOffset, int startLine, int startColumn, int startGeneratedColumn, int codeLength)\n            : this((int?)startOffset, startLine, startColumn, startGeneratedColumn, codeLength)\n        {\n        }\n\n        private GeneratedCodeMapping(int? startOffset, int startLine, int startColumn, int startGeneratedColumn, int codeLength)\n            : this()\n        {\n            if (startLine < 0)\n            {\n                throw new ArgumentOutOfRangeException(\"startLine\", String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, \"startLine\", \"0\"));\n            }\n            if (startColumn < 0)\n            {\n                throw new ArgumentOutOfRangeException(\"startColumn\", String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, \"startColumn\", \"0\"));\n            }\n            if (startGeneratedColumn < 0)\n            {\n                throw new ArgumentOutOfRangeException(\"startGeneratedColumn\", String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, \"startGeneratedColumn\", \"0\"));\n            }\n            if (codeLength < 0)\n            {\n                throw new ArgumentOutOfRangeException(\"codeLength\", String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, \"codeLength\", \"0\"));\n            }\n\n            StartOffset = startOffset;\n            StartLine = startLine;\n            StartColumn = startColumn;\n            StartGeneratedColumn = startGeneratedColumn;\n            CodeLength = codeLength;\n        }\n\n        public int? StartOffset { get; set; }\n        public int CodeLength { get; set; }\n        public int StartColumn { get; set; }\n        public int StartGeneratedColumn { get; set; }\n        public int StartLine { get; set; }\n\n        public override bool Equals(object obj)\n        {\n            if (!(obj is GeneratedCodeMapping))\n            {\n                return false;\n            }\n            GeneratedCodeMapping other = (GeneratedCodeMapping)obj;\n            return CodeLength == other.CodeLength &&\n                   StartColumn == other.StartColumn &&\n                   StartGeneratedColumn == other.StartGeneratedColumn &&\n                   StartLine == other.StartLine &&\n                   // Null means it matches the other no matter what.\n                   (StartOffset == null || other.StartOffset == null || StartOffset.Equals(other.StartOffset));\n        }\n\n        public override string ToString()\n        {\n            return String.Format(\n                CultureInfo.CurrentCulture,\n                \"({0}, {1}, {2}) -> (?, {3}) [{4}]\",\n                StartOffset == null ? \"?\" : StartOffset.Value.ToString(CultureInfo.CurrentCulture),\n                StartLine,\n                StartColumn,\n                StartGeneratedColumn,\n                CodeLength);\n        }\n\n        public override int GetHashCode()\n        {\n            return HashCodeCombiner.Start()\n                .Add(CodeLength)\n                .Add(StartColumn)\n                .Add(StartGeneratedColumn)\n                .Add(StartLine)\n                .Add(StartOffset)\n                .CombinedHash;\n        }\n\n        public static bool operator ==(GeneratedCodeMapping left, GeneratedCodeMapping right)\n        {\n            return left.Equals(right);\n        }\n\n        public static bool operator !=(GeneratedCodeMapping left, GeneratedCodeMapping right)\n        {\n            return !left.Equals(right);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/HelperCodeGenerator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.Globalization;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Text;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Razor.Generator\n{\n    public class HelperCodeGenerator : BlockCodeGenerator\n    {\n        private const string HelperWriterName = \"__razor_helper_writer\";\n\n        private CodeWriter _writer;\n        private string _oldWriter;\n        private IDisposable _statementCollectorToken;\n\n        public HelperCodeGenerator(LocationTagged<string> signature, bool headerComplete)\n        {\n            Signature = signature;\n            HeaderComplete = headerComplete;\n        }\n\n        public LocationTagged<string> Signature { get; private set; }\n        public LocationTagged<string> Footer { get; set; }\n        public bool HeaderComplete { get; private set; }\n\n        public override void GenerateStartBlockCode(Block target, CodeGeneratorContext context)\n        {\n            _writer = context.CreateCodeWriter();\n\n            string prefix = context.BuildCodeString(\n                cw => cw.WriteHelperHeaderPrefix(context.Host.GeneratedClassContext.TemplateTypeName, context.Host.StaticHelpers));\n\n            _writer.WriteLinePragma(\n                context.GenerateLinePragma(Signature.Location, prefix.Length, Signature.Value.Length));\n            _writer.WriteSnippet(prefix);\n            _writer.WriteSnippet(Signature);\n            if (HeaderComplete)\n            {\n                _writer.WriteHelperHeaderSuffix(context.Host.GeneratedClassContext.TemplateTypeName);\n            }\n            _writer.WriteLinePragma(null);\n            if (HeaderComplete)\n            {\n                _writer.WriteReturn();\n                _writer.WriteStartConstructor(context.Host.GeneratedClassContext.TemplateTypeName);\n                _writer.WriteStartLambdaDelegate(HelperWriterName);\n            }\n\n            _statementCollectorToken = context.ChangeStatementCollector(AddStatementToHelper);\n            _oldWriter = context.TargetWriterName;\n            context.TargetWriterName = HelperWriterName;\n        }\n\n        public override void GenerateEndBlockCode(Block target, CodeGeneratorContext context)\n        {\n            _statementCollectorToken.Dispose();\n            if (HeaderComplete)\n            {\n                _writer.WriteEndLambdaDelegate();\n                _writer.WriteEndConstructor();\n                _writer.WriteEndStatement();\n            }\n            if (Footer != null && !String.IsNullOrEmpty(Footer.Value))\n            {\n                _writer.WriteLinePragma(\n                    context.GenerateLinePragma(Footer.Location, 0, Footer.Value.Length));\n                _writer.WriteSnippet(Footer);\n                _writer.WriteLinePragma();\n            }\n            _writer.WriteHelperTrailer();\n\n            context.GeneratedClass.Members.Add(new CodeSnippetTypeMember(_writer.Content));\n            context.TargetWriterName = _oldWriter;\n        }\n\n        public override bool Equals(object obj)\n        {\n            HelperCodeGenerator other = obj as HelperCodeGenerator;\n            return other != null &&\n                   base.Equals(other) &&\n                   HeaderComplete == other.HeaderComplete &&\n                   Equals(Signature, other.Signature);\n        }\n\n        public override int GetHashCode()\n        {\n            return HashCodeCombiner.Start()\n                .Add(base.GetHashCode())\n                .Add(Signature)\n                .CombinedHash;\n        }\n\n        public override string ToString()\n        {\n            return \"Helper:\" + Signature.ToString(\"F\", CultureInfo.CurrentCulture) + \";\" + (HeaderComplete ? \"C\" : \"I\");\n        }\n\n        private void AddStatementToHelper(string statement, CodeLinePragma pragma)\n        {\n            if (pragma != null)\n            {\n                _writer.WriteLinePragma(pragma);\n            }\n            _writer.WriteSnippet(statement);\n            _writer.InnerWriter.WriteLine(); // CodeDOM normally inserts an extra line so we need to do so here.\n            if (pragma != null)\n            {\n                _writer.WriteLinePragma();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/HybridCodeGenerator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.Razor.Generator\n{\n    public abstract class HybridCodeGenerator : ISpanCodeGenerator, IBlockCodeGenerator\n    {\n        public virtual void GenerateStartBlockCode(Block target, CodeGeneratorContext context)\n        {\n        }\n\n        public virtual void GenerateEndBlockCode(Block target, CodeGeneratorContext context)\n        {\n        }\n\n        public virtual void GenerateCode(Span target, CodeGeneratorContext context)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/IBlockCodeGenerator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.Razor.Generator\n{\n    public interface IBlockCodeGenerator\n    {\n        void GenerateStartBlockCode(Block target, CodeGeneratorContext context);\n        void GenerateEndBlockCode(Block target, CodeGeneratorContext context);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/ISpanCodeGenerator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.Razor.Generator\n{\n    public interface ISpanCodeGenerator\n    {\n        void GenerateCode(Span target, CodeGeneratorContext context);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/LiteralAttributeCodeGenerator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Text;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Razor.Generator\n{\n    public class LiteralAttributeCodeGenerator : SpanCodeGenerator\n    {\n        public LiteralAttributeCodeGenerator(LocationTagged<string> prefix, LocationTagged<SpanCodeGenerator> valueGenerator)\n        {\n            Prefix = prefix;\n            ValueGenerator = valueGenerator;\n        }\n\n        public LiteralAttributeCodeGenerator(LocationTagged<string> prefix, LocationTagged<string> value)\n        {\n            Prefix = prefix;\n            Value = value;\n        }\n\n        public LocationTagged<string> Prefix { get; private set; }\n        public LocationTagged<string> Value { get; private set; }\n        public LocationTagged<SpanCodeGenerator> ValueGenerator { get; private set; }\n\n        public override void GenerateCode(Span target, CodeGeneratorContext context)\n        {\n            if (context.Host.DesignTimeMode)\n            {\n                return;\n            }\n            ExpressionRenderingMode oldMode = context.ExpressionRenderingMode;\n            context.BufferStatementFragment(context.BuildCodeString(cw =>\n            {\n                cw.WriteParameterSeparator();\n                cw.WriteStartMethodInvoke(\"Tuple.Create\");\n                cw.WriteLocationTaggedString(Prefix);\n                cw.WriteParameterSeparator();\n                if (ValueGenerator != null)\n                {\n                    cw.WriteStartMethodInvoke(\"Tuple.Create\", \"System.Object\", \"System.Int32\");\n                    context.ExpressionRenderingMode = ExpressionRenderingMode.InjectCode;\n                }\n                else\n                {\n                    cw.WriteLocationTaggedString(Value);\n                    cw.WriteParameterSeparator();\n                    // literal: true - This attribute value is a literal value\n                    cw.WriteBooleanLiteral(true);\n                    cw.WriteEndMethodInvoke();\n\n                    // In VB, we need a line continuation\n                    cw.WriteLineContinuation();\n                }\n            }));\n            if (ValueGenerator != null)\n            {\n                ValueGenerator.Value.GenerateCode(target, context);\n                context.FlushBufferedStatement();\n                context.ExpressionRenderingMode = oldMode;\n                context.AddStatement(context.BuildCodeString(cw =>\n                {\n                    cw.WriteParameterSeparator();\n                    cw.WriteSnippet(ValueGenerator.Location.AbsoluteIndex.ToString(CultureInfo.CurrentCulture));\n                    cw.WriteEndMethodInvoke();\n                    cw.WriteParameterSeparator();\n                    // literal: false - This attribute value is not a literal value, it is dynamically generated\n                    cw.WriteBooleanLiteral(false);\n                    cw.WriteEndMethodInvoke();\n\n                    // In VB, we need a line continuation\n                    cw.WriteLineContinuation();\n                }));\n            }\n            else\n            {\n                context.FlushBufferedStatement();\n            }\n        }\n\n        public override string ToString()\n        {\n            if (ValueGenerator == null)\n            {\n                return String.Format(CultureInfo.CurrentCulture, \"LitAttr:{0:F},{1:F}\", Prefix, Value);\n            }\n            else\n            {\n                return String.Format(CultureInfo.CurrentCulture, \"LitAttr:{0:F},<Sub:{1:F}>\", Prefix, ValueGenerator);\n            }\n        }\n\n        public override bool Equals(object obj)\n        {\n            LiteralAttributeCodeGenerator other = obj as LiteralAttributeCodeGenerator;\n            return other != null &&\n                   Equals(other.Prefix, Prefix) &&\n                   Equals(other.Value, Value) &&\n                   Equals(other.ValueGenerator, ValueGenerator);\n        }\n\n        public override int GetHashCode()\n        {\n            return HashCodeCombiner.Start()\n                .Add(Prefix)\n                .Add(Value)\n                .Add(ValueGenerator)\n                .CombinedHash;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/MarkupCodeGenerator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.Razor.Generator\n{\n    public class MarkupCodeGenerator : SpanCodeGenerator\n    {\n        public override void GenerateCode(Span target, CodeGeneratorContext context)\n        {\n            if (!context.Host.DesignTimeMode && String.IsNullOrEmpty(target.Content))\n            {\n                return;\n            }\n\n            if (context.Host.EnableInstrumentation)\n            {\n                context.AddContextCall(target, context.Host.GeneratedClassContext.BeginContextMethodName, isLiteral: true);\n            }\n\n            if (!String.IsNullOrEmpty(target.Content) && !context.Host.DesignTimeMode)\n            {\n                string code = context.BuildCodeString(cw =>\n                {\n                    if (!String.IsNullOrEmpty(context.TargetWriterName))\n                    {\n                        cw.WriteStartMethodInvoke(context.Host.GeneratedClassContext.WriteLiteralToMethodName);\n                        cw.WriteSnippet(context.TargetWriterName);\n                        cw.WriteParameterSeparator();\n                    }\n                    else\n                    {\n                        cw.WriteStartMethodInvoke(context.Host.GeneratedClassContext.WriteLiteralMethodName);\n                    }\n                    cw.WriteStringLiteral(target.Content);\n                    cw.WriteEndMethodInvoke();\n                    cw.WriteEndStatement();\n                });\n                context.AddStatement(code);\n            }\n\n            if (context.Host.EnableInstrumentation)\n            {\n                context.AddContextCall(target, context.Host.GeneratedClassContext.EndContextMethodName, isLiteral: true);\n            }\n        }\n\n        public override string ToString()\n        {\n            return \"Markup\";\n        }\n\n        public override bool Equals(object obj)\n        {\n            return obj is MarkupCodeGenerator;\n        }\n\n        public override int GetHashCode()\n        {\n            return base.GetHashCode();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/RazorCodeGenerator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.Linq;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Razor.Generator\n{\n    public abstract class RazorCodeGenerator : ParserVisitor\n    {\n        private CodeGeneratorContext _context;\n\n        protected RazorCodeGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host)\n        {\n            if (String.IsNullOrEmpty(className))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"className\");\n            }\n            if (rootNamespaceName == null)\n            {\n                throw new ArgumentNullException(\"rootNamespaceName\");\n            }\n            if (host == null)\n            {\n                throw new ArgumentNullException(\"host\");\n            }\n\n            ClassName = className;\n            RootNamespaceName = rootNamespaceName;\n            SourceFileName = sourceFileName;\n            GenerateLinePragmas = String.IsNullOrEmpty(SourceFileName) ? false : true;\n            Host = host;\n        }\n\n        // Data pulled from constructor\n        public string ClassName { get; private set; }\n        public string RootNamespaceName { get; private set; }\n        public string SourceFileName { get; private set; }\n        public RazorEngineHost Host { get; private set; }\n\n        // Generation settings\n        public bool GenerateLinePragmas { get; set; }\n        public bool DesignTimeMode { get; set; }\n\n        public CodeGeneratorContext Context\n        {\n            get\n            {\n                EnsureContextInitialized();\n                return _context;\n            }\n        }\n\n        internal virtual Func<CodeWriter> CodeWriterFactory\n        {\n            get { return null; }\n        }\n\n        public override void VisitStartBlock(Block block)\n        {\n            block.CodeGenerator.GenerateStartBlockCode(block, Context);\n        }\n\n        public override void VisitEndBlock(Block block)\n        {\n            block.CodeGenerator.GenerateEndBlockCode(block, Context);\n        }\n\n        public override void VisitSpan(Span span)\n        {\n            span.CodeGenerator.GenerateCode(span, Context);\n        }\n\n        public override void OnComplete()\n        {\n            Context.FlushBufferedStatement();\n        }\n\n        private void EnsureContextInitialized()\n        {\n            if (_context == null)\n            {\n                _context = CodeGeneratorContext.Create(Host, CodeWriterFactory, ClassName, RootNamespaceName, SourceFileName, GenerateLinePragmas);\n                Initialize(_context);\n            }\n        }\n\n        protected virtual void Initialize(CodeGeneratorContext context)\n        {\n            context.Namespace.Imports.AddRange(Host.NamespaceImports.Select(s => new CodeNamespaceImport(s)).ToArray());\n\n            if (!String.IsNullOrEmpty(Host.DefaultBaseClass))\n            {\n                context.GeneratedClass.BaseTypes.Add(new CodeTypeReference(Host.DefaultBaseClass));\n            }\n\n            // Dev10 Bug 937438: Generate explicit Parameter-less constructor on Razor generated class\n            context.GeneratedClass.Members.Add(new CodeConstructor() { Attributes = MemberAttributes.Public });\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/RazorCommentCodeGenerator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.Razor.Generator\n{\n    public class RazorCommentCodeGenerator : BlockCodeGenerator\n    {\n        public override void GenerateStartBlockCode(Block target, CodeGeneratorContext context)\n        {\n            // Flush the buffered statement since we're interrupting it with a comment.\n            if (!String.IsNullOrEmpty(context.CurrentBufferedStatement))\n            {\n                context.MarkEndOfGeneratedCode();\n                context.BufferStatementFragment(context.BuildCodeString(cw => cw.WriteLineContinuation()));\n            }\n            context.FlushBufferedStatement();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/RazorDirectiveAttributeCodeGenerator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Razor.Generator\n{\n    public class RazorDirectiveAttributeCodeGenerator : SpanCodeGenerator\n    {\n        public RazorDirectiveAttributeCodeGenerator(string name, string value)\n        {\n            if (String.IsNullOrEmpty(name))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"name\");\n            }\n            Name = name;\n            Value = value ?? String.Empty; // Coerce to empty string if it was null.\n        }\n\n        public string Name { get; private set; }\n\n        public string Value { get; private set; }\n\n        public override void GenerateCode(Span target, CodeGeneratorContext context)\n        {\n            var attributeType = new CodeTypeReference(typeof(RazorDirectiveAttribute));\n            var attributeDeclaration = new CodeAttributeDeclaration(\n                attributeType,\n                new CodeAttributeArgument(new CodePrimitiveExpression(Name)),\n                new CodeAttributeArgument(new CodePrimitiveExpression(Value)));\n            context.GeneratedClass.CustomAttributes.Add(attributeDeclaration);\n        }\n\n        public override string ToString()\n        {\n            return \"Directive: \" + Name + \", Value: \" + Value;\n        }\n\n        public override bool Equals(object obj)\n        {\n            RazorDirectiveAttributeCodeGenerator other = obj as RazorDirectiveAttributeCodeGenerator;\n            return other != null &&\n                   Name.Equals(other.Name, StringComparison.OrdinalIgnoreCase) &&\n                   Value.Equals(other.Value, StringComparison.OrdinalIgnoreCase);\n        }\n\n        public override int GetHashCode()\n        {\n            return Tuple.Create(Name.ToUpperInvariant(), Value.ToUpperInvariant())\n                .GetHashCode();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/ResolveUrlCodeGenerator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.Razor.Generator\n{\n    public class ResolveUrlCodeGenerator : SpanCodeGenerator\n    {\n        public override void GenerateCode(Span target, CodeGeneratorContext context)\n        {\n            // Check if the host supports it\n            if (String.IsNullOrEmpty(context.Host.GeneratedClassContext.ResolveUrlMethodName))\n            {\n                // Nope, just use the default MarkupCodeGenerator behavior\n                new MarkupCodeGenerator().GenerateCode(target, context);\n                return;\n            }\n\n            if (!context.Host.DesignTimeMode && String.IsNullOrEmpty(target.Content))\n            {\n                return;\n            }\n\n            if (context.Host.EnableInstrumentation && context.ExpressionRenderingMode == ExpressionRenderingMode.WriteToOutput)\n            {\n                // Add a non-literal context call (non-literal because the expanded URL will not match the source character-by-character)\n                context.AddContextCall(target, context.Host.GeneratedClassContext.BeginContextMethodName, isLiteral: false);\n            }\n\n            if (!String.IsNullOrEmpty(target.Content) && !context.Host.DesignTimeMode)\n            {\n                string code = context.BuildCodeString(cw =>\n                {\n                    if (context.ExpressionRenderingMode == ExpressionRenderingMode.WriteToOutput)\n                    {\n                        if (!String.IsNullOrEmpty(context.TargetWriterName))\n                        {\n                            cw.WriteStartMethodInvoke(context.Host.GeneratedClassContext.WriteLiteralToMethodName);\n                            cw.WriteSnippet(context.TargetWriterName);\n                            cw.WriteParameterSeparator();\n                        }\n                        else\n                        {\n                            cw.WriteStartMethodInvoke(context.Host.GeneratedClassContext.WriteLiteralMethodName);\n                        }\n                    }\n                    cw.WriteStartMethodInvoke(context.Host.GeneratedClassContext.ResolveUrlMethodName);\n                    cw.WriteStringLiteral(target.Content);\n                    cw.WriteEndMethodInvoke();\n\n                    if (context.ExpressionRenderingMode == ExpressionRenderingMode.WriteToOutput)\n                    {\n                        cw.WriteEndMethodInvoke();\n                        cw.WriteEndStatement();\n                    }\n                    else\n                    {\n                        cw.WriteLineContinuation();\n                    }\n                });\n                if (context.ExpressionRenderingMode == ExpressionRenderingMode.WriteToOutput)\n                {\n                    context.AddStatement(code);\n                }\n                else\n                {\n                    context.BufferStatementFragment(code);\n                }\n            }\n\n            if (context.Host.EnableInstrumentation && context.ExpressionRenderingMode == ExpressionRenderingMode.WriteToOutput)\n            {\n                context.AddContextCall(target, context.Host.GeneratedClassContext.EndContextMethodName, isLiteral: false);\n            }\n        }\n\n        public override string ToString()\n        {\n            return \"VirtualPath\";\n        }\n\n        public override bool Equals(object obj)\n        {\n            return obj is ResolveUrlCodeGenerator;\n        }\n\n        public override int GetHashCode()\n        {\n            return base.GetHashCode();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/SectionCodeGenerator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser.SyntaxTree;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Razor.Generator\n{\n    public class SectionCodeGenerator : BlockCodeGenerator\n    {\n        public SectionCodeGenerator(string sectionName)\n        {\n            SectionName = sectionName;\n        }\n\n        public string SectionName { get; private set; }\n\n        public override void GenerateStartBlockCode(Block target, CodeGeneratorContext context)\n        {\n            string startBlock = context.BuildCodeString(cw =>\n            {\n                cw.WriteStartMethodInvoke(context.Host.GeneratedClassContext.DefineSectionMethodName);\n                cw.WriteStringLiteral(SectionName);\n                cw.WriteParameterSeparator();\n                cw.WriteStartLambdaDelegate();\n            });\n            context.AddStatement(startBlock);\n        }\n\n        public override void GenerateEndBlockCode(Block target, CodeGeneratorContext context)\n        {\n            string startBlock = context.BuildCodeString(cw =>\n            {\n                cw.WriteEndLambdaDelegate();\n                cw.WriteEndMethodInvoke();\n                cw.WriteEndStatement();\n            });\n            context.AddStatement(startBlock);\n        }\n\n        public override bool Equals(object obj)\n        {\n            SectionCodeGenerator other = obj as SectionCodeGenerator;\n            return other != null &&\n                   base.Equals(other) &&\n                   String.Equals(SectionName, other.SectionName, StringComparison.Ordinal);\n        }\n\n        public override int GetHashCode()\n        {\n            return HashCodeCombiner.Start()\n                .Add(base.GetHashCode())\n                .Add(SectionName)\n                .CombinedHash;\n        }\n\n        public override string ToString()\n        {\n            return \"Section:\" + SectionName;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/SetBaseTypeCodeGenerator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.Razor.Generator\n{\n    public class SetBaseTypeCodeGenerator : SpanCodeGenerator\n    {\n        public SetBaseTypeCodeGenerator(string baseType)\n        {\n            BaseType = baseType;\n        }\n\n        public string BaseType { get; private set; }\n\n        public override void GenerateCode(Span target, CodeGeneratorContext context)\n        {\n            context.GeneratedClass.BaseTypes.Clear();\n            context.GeneratedClass.BaseTypes.Add(new CodeTypeReference(ResolveType(context, BaseType.Trim())));\n\n            if (context.Host.DesignTimeMode)\n            {\n                int generatedCodeStart = 0;\n                string code = context.BuildCodeString(cw =>\n                {\n                    generatedCodeStart = cw.WriteVariableDeclaration(target.Content, \"__inheritsHelper\", null);\n                    cw.WriteEndStatement();\n                });\n\n                int paddingCharCount;\n\n                CodeSnippetStatement stmt = new CodeSnippetStatement(\n                    CodeGeneratorPaddingHelper.Pad(context.Host, code, target, generatedCodeStart, out paddingCharCount))\n                {\n                    LinePragma = context.GenerateLinePragma(target, generatedCodeStart + paddingCharCount)\n                };\n                context.AddDesignTimeHelperStatement(stmt);\n            }\n        }\n\n        protected virtual string ResolveType(CodeGeneratorContext context, string baseType)\n        {\n            return baseType;\n        }\n\n        public override string ToString()\n        {\n            return \"Base:\" + BaseType;\n        }\n\n        public override bool Equals(object obj)\n        {\n            SetBaseTypeCodeGenerator other = obj as SetBaseTypeCodeGenerator;\n            return other != null &&\n                   String.Equals(BaseType, other.BaseType, StringComparison.Ordinal);\n        }\n\n        public override int GetHashCode()\n        {\n            return BaseType.GetHashCode();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/SetLayoutCodeGenerator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.Razor.Generator\n{\n    public class SetLayoutCodeGenerator : SpanCodeGenerator\n    {\n        public SetLayoutCodeGenerator(string layoutPath)\n        {\n            LayoutPath = layoutPath;\n        }\n\n        public string LayoutPath { get; set; }\n\n        public override void GenerateCode(Span target, CodeGeneratorContext context)\n        {\n            if (!context.Host.DesignTimeMode && !String.IsNullOrEmpty(context.Host.GeneratedClassContext.LayoutPropertyName))\n            {\n                context.TargetMethod.Statements.Add(\n                    new CodeAssignStatement(\n                        new CodePropertyReferenceExpression(null, context.Host.GeneratedClassContext.LayoutPropertyName),\n                        new CodePrimitiveExpression(LayoutPath)));\n            }\n        }\n\n        public override string ToString()\n        {\n            return \"Layout: \" + LayoutPath;\n        }\n\n        public override bool Equals(object obj)\n        {\n            SetLayoutCodeGenerator other = obj as SetLayoutCodeGenerator;\n            return other != null && String.Equals(other.LayoutPath, LayoutPath, StringComparison.Ordinal);\n        }\n\n        public override int GetHashCode()\n        {\n            return LayoutPath.GetHashCode();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/SetVBOptionCodeGenerator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.Razor.Generator\n{\n    public class SetVBOptionCodeGenerator : SpanCodeGenerator\n    {\n        public static readonly string StrictCodeDomOptionName = \"AllowLateBound\";\n        public static readonly string ExplicitCodeDomOptionName = \"RequireVariableDeclaration\";\n\n        public SetVBOptionCodeGenerator(string optionName, bool value)\n        {\n            OptionName = optionName;\n            Value = value;\n        }\n\n        // CodeDOM Option Name, which is NOT the same as the VB Option Name\n        public string OptionName { get; private set; }\n        public bool Value { get; private set; }\n\n        public static SetVBOptionCodeGenerator Strict(bool onOffValue)\n        {\n            // Strict On = AllowLateBound Off\n            return new SetVBOptionCodeGenerator(StrictCodeDomOptionName, !onOffValue);\n        }\n\n        public static SetVBOptionCodeGenerator Explicit(bool onOffValue)\n        {\n            return new SetVBOptionCodeGenerator(ExplicitCodeDomOptionName, onOffValue);\n        }\n\n        public override void GenerateCode(Span target, CodeGeneratorContext context)\n        {\n            context.CompileUnit.UserData[OptionName] = Value;\n        }\n\n        public override string ToString()\n        {\n            return \"Option:\" + OptionName + \"=\" + Value;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/SpanCodeGenerator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.Razor.Generator\n{\n    public abstract class SpanCodeGenerator : ISpanCodeGenerator\n    {\n        [SuppressMessage(\"Microsoft.Security\", \"CA2104:DoNotDeclareReadOnlyMutableReferenceTypes\", Justification = \"This class has no instance state\")]\n        public static readonly ISpanCodeGenerator Null = new NullSpanCodeGenerator();\n\n        public virtual void GenerateCode(Span target, CodeGeneratorContext context)\n        {\n        }\n\n        public override bool Equals(object obj)\n        {\n            return (obj as ISpanCodeGenerator) != null;\n        }\n\n        public override int GetHashCode()\n        {\n            return base.GetHashCode();\n        }\n\n        private class NullSpanCodeGenerator : ISpanCodeGenerator\n        {\n            public void GenerateCode(Span target, CodeGeneratorContext context)\n            {\n            }\n\n            public override string ToString()\n            {\n                return \"None\";\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/StatementCodeGenerator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.Razor.Generator\n{\n    public class StatementCodeGenerator : SpanCodeGenerator\n    {\n        public override void GenerateCode(Span target, CodeGeneratorContext context)\n        {\n            context.FlushBufferedStatement();\n\n            string generatedCode = context.BuildCodeString(cw =>\n            {\n                cw.WriteSnippet(target.Content);\n            });\n\n            int startGeneratedCode = target.Start.CharacterIndex;\n            int paddingCharCount;\n            generatedCode = CodeGeneratorPaddingHelper.PadStatement(context.Host, generatedCode, target, ref startGeneratedCode, out paddingCharCount);\n\n            context.AddStatement(\n                generatedCode,\n                context.GenerateLinePragma(target, paddingCharCount));\n        }\n\n        public override string ToString()\n        {\n            return \"Stmt\";\n        }\n\n        public override bool Equals(object obj)\n        {\n            return obj is StatementCodeGenerator;\n        }\n\n        public override int GetHashCode()\n        {\n            return base.GetHashCode();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/TemplateBlockCodeGenerator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.Razor.Generator\n{\n    public class TemplateBlockCodeGenerator : BlockCodeGenerator\n    {\n        private const string TemplateWriterName = \"__razor_template_writer\";\n        private const string ItemParameterName = \"item\";\n\n        private string _oldTargetWriter;\n\n        public override void GenerateStartBlockCode(Block target, CodeGeneratorContext context)\n        {\n            string generatedCode = context.BuildCodeString(cw =>\n            {\n                cw.WriteStartLambdaExpression(ItemParameterName);\n                cw.WriteStartConstructor(context.Host.GeneratedClassContext.TemplateTypeName);\n                cw.WriteStartLambdaDelegate(TemplateWriterName);\n            });\n\n            context.MarkEndOfGeneratedCode();\n            context.BufferStatementFragment(generatedCode);\n            context.FlushBufferedStatement();\n\n            _oldTargetWriter = context.TargetWriterName;\n            context.TargetWriterName = TemplateWriterName;\n        }\n\n        public override void GenerateEndBlockCode(Block target, CodeGeneratorContext context)\n        {\n            string generatedCode = context.BuildCodeString(cw =>\n            {\n                cw.WriteEndLambdaDelegate();\n                cw.WriteEndConstructor();\n                cw.WriteEndLambdaExpression();\n            });\n\n            context.BufferStatementFragment(generatedCode);\n            context.TargetWriterName = _oldTargetWriter;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/TypeMemberCodeGenerator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.Diagnostics.Contracts;\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.Razor.Generator\n{\n    public class TypeMemberCodeGenerator : SpanCodeGenerator\n    {\n        public override void GenerateCode(Span target, CodeGeneratorContext context)\n        {\n            string generatedCode = context.BuildCodeString(cw =>\n            {\n                cw.WriteSnippet(target.Content);\n            });\n\n            int paddingCharCount;\n            string paddedCode = CodeGeneratorPaddingHelper.Pad(context.Host, generatedCode, target, out paddingCharCount);\n\n            Contract.Assert(paddingCharCount > 0);\n\n            context.GeneratedClass.Members.Add(\n                new CodeSnippetTypeMember(paddedCode)\n                {\n                    LinePragma = context.GenerateLinePragma(target, paddingCharCount)\n                });\n        }\n\n        public override string ToString()\n        {\n            return \"TypeMember\";\n        }\n\n        public override bool Equals(object obj)\n        {\n            return obj is TypeMemberCodeGenerator;\n        }\n\n        // C# complains at us if we don't provide an implementation, even one like this\n        public override int GetHashCode()\n        {\n            return base.GetHashCode();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/VBCodeWriter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Razor.Generator\n{\n    internal class VBCodeWriter : BaseCodeWriter\n    {\n        public override bool SupportsMidStatementLinePragmas\n        {\n            get { return false; }\n        }\n\n        protected internal override void WriteStartGenerics()\n        {\n            InnerWriter.Write(\"(Of \");\n        }\n\n        protected internal override void WriteEndGenerics()\n        {\n            InnerWriter.Write(\")\");\n        }\n\n        public override void WriteLineContinuation()\n        {\n            InnerWriter.Write(\" _\");\n        }\n\n        public override int WriteVariableDeclaration(string type, string name, string value)\n        {\n            InnerWriter.Write(\"Dim \");\n            InnerWriter.Write(name);\n            InnerWriter.Write(\" As \");\n            int typePos = InnerWriter.GetStringBuilder().Length;\n            InnerWriter.Write(type);\n            if (!String.IsNullOrEmpty(value))\n            {\n                InnerWriter.Write(\" = \");\n                InnerWriter.Write(value);\n            }\n            else\n            {\n                InnerWriter.Write(\" = Nothing\");\n            }\n            return typePos;\n        }\n\n        public override void WriteStringLiteral(string literal)\n        {\n            bool inQuotes = true;\n            InnerWriter.Write(\"\\\"\");\n            for (int i = 0; i < literal.Length; i++)\n            {\n                switch (literal[i])\n                {\n                    case '\\t':\n                    case '\\n':\n                    case '\\r':\n                    case '\\0':\n                    case '\\u2028':\n                    case '\\u2029':\n                        // Exit quotes\n                        EnsureOutOfQuotes(ref inQuotes);\n\n                        // Write concat character\n                        InnerWriter.Write(\"&\");\n\n                        // Write character literal\n                        WriteCharLiteral(literal[i]);\n                        break;\n                    case '\"':\n                    case '“':\n                    case '”':\n                    case (char)0xff02:\n                        EnsureInQuotes(ref inQuotes);\n                        InnerWriter.Write(literal[i]);\n                        InnerWriter.Write(literal[i]);\n                        break;\n                    default:\n                        EnsureInQuotes(ref inQuotes);\n                        InnerWriter.Write(literal[i]);\n                        break;\n                }\n                if (i > 0 && (i % 80) == 0)\n                {\n                    if ((Char.IsHighSurrogate(literal[i]) && (i < (literal.Length - 1))) && Char.IsLowSurrogate(literal[i + 1]))\n                    {\n                        InnerWriter.Write(literal[++i]);\n                    }\n                    if (inQuotes)\n                    {\n                        InnerWriter.Write(\"\\\"\");\n                    }\n                    inQuotes = true;\n                    InnerWriter.Write(\"& _ \");\n                    InnerWriter.Write(Environment.NewLine);\n                    InnerWriter.Write('\"');\n                }\n            }\n            EnsureOutOfQuotes(ref inQuotes);\n        }\n\n        protected internal override void EmitStartLambdaExpression(string[] parameterNames)\n        {\n            InnerWriter.Write(\"Function (\");\n            WriteCommaSeparatedList(parameterNames, InnerWriter.Write);\n            InnerWriter.Write(\") \");\n        }\n\n        protected internal override void EmitStartConstructor(string typeName)\n        {\n            InnerWriter.Write(\"New \");\n            InnerWriter.Write(typeName);\n            InnerWriter.Write(\"(\");\n        }\n\n        protected internal override void EmitStartLambdaDelegate(string[] parameterNames)\n        {\n            InnerWriter.Write(\"Sub (\");\n            WriteCommaSeparatedList(parameterNames, InnerWriter.Write);\n            InnerWriter.WriteLine(\")\");\n        }\n\n        protected internal override void EmitEndLambdaDelegate()\n        {\n            InnerWriter.Write(\"End Sub\");\n        }\n\n        private void WriteCharLiteral(char literal)\n        {\n            InnerWriter.Write(\"Global.Microsoft.VisualBasic.ChrW(\");\n            InnerWriter.Write((int)literal);\n            InnerWriter.Write(\")\");\n        }\n\n        private void EnsureInQuotes(ref bool inQuotes)\n        {\n            if (!inQuotes)\n            {\n                InnerWriter.Write(\"&\\\"\");\n                inQuotes = true;\n            }\n        }\n\n        private void EnsureOutOfQuotes(ref bool inQuotes)\n        {\n            if (inQuotes)\n            {\n                InnerWriter.Write(\"\\\"\");\n                inQuotes = false;\n            }\n        }\n\n        public override void WriteReturn()\n        {\n            InnerWriter.Write(\"Return \");\n        }\n\n        public override void WriteLinePragma(int? lineNumber, string fileName)\n        {\n            InnerWriter.WriteLine();\n            if (lineNumber != null)\n            {\n                InnerWriter.Write(\"#ExternalSource(\\\"\");\n                InnerWriter.Write(fileName);\n                InnerWriter.Write(\"\\\", \");\n                InnerWriter.Write(lineNumber);\n                InnerWriter.WriteLine(\")\");\n            }\n            else\n            {\n                InnerWriter.WriteLine(\"#End ExternalSource\");\n            }\n        }\n\n        public override void WriteHelperHeaderPrefix(string templateTypeName, bool isStatic)\n        {\n            InnerWriter.Write(\"Public \");\n            if (isStatic)\n            {\n                InnerWriter.Write(\"Shared \");\n            }\n            InnerWriter.Write(\"Function \");\n        }\n\n        public override void WriteHelperHeaderSuffix(string templateTypeName)\n        {\n            InnerWriter.Write(\" As \");\n            InnerWriter.WriteLine(templateTypeName);\n        }\n\n        public override void WriteHelperTrailer()\n        {\n            InnerWriter.WriteLine(\"End Function\");\n        }\n\n        public override void WriteEndStatement()\n        {\n            InnerWriter.WriteLine();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Generator/VBRazorCodeGenerator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Razor.Generator\n{\n    public class VBRazorCodeGenerator : RazorCodeGenerator\n    {\n        public VBRazorCodeGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host)\n            : base(className, rootNamespaceName, sourceFileName, host)\n        {\n        }\n\n        internal override Func<CodeWriter> CodeWriterFactory\n        {\n            get { return () => new VBCodeWriter(); }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/GeneratorResults.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.Collections.Generic;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.Razor\n{\n    /// <summary>\n    /// Represents results from code generation (and parsing, since that is a pre-requisite of code generation)\n    /// </summary>\n    /// <remarks>\n    /// Since this inherits from ParserResults, it has all the data from ParserResults, and simply adds code generation data\n    /// </remarks>\n    public class GeneratorResults : ParserResults\n    {\n        public GeneratorResults(ParserResults parserResults,\n                                CodeCompileUnit generatedCode,\n                                IDictionary<int, GeneratedCodeMapping> designTimeLineMappings)\n            : this(parserResults.Document, parserResults.ParserErrors, generatedCode, designTimeLineMappings)\n        {\n        }\n\n        public GeneratorResults(Block document,\n                                IList<RazorError> parserErrors,\n                                CodeCompileUnit generatedCode,\n                                IDictionary<int, GeneratedCodeMapping> designTimeLineMappings)\n            : this(parserErrors.Count == 0, document, parserErrors, generatedCode, designTimeLineMappings)\n        {\n        }\n\n        protected GeneratorResults(bool success,\n                                   Block document,\n                                   IList<RazorError> parserErrors,\n                                   CodeCompileUnit generatedCode,\n                                   IDictionary<int, GeneratedCodeMapping> designTimeLineMappings)\n            : base(success, document, parserErrors)\n        {\n            GeneratedCode = generatedCode;\n            DesignTimeLineMappings = designTimeLineMappings;\n        }\n\n        /// <summary>\n        /// The generated code\n        /// </summary>\n        public CodeCompileUnit GeneratedCode { get; private set; }\n\n        /// <summary>\n        /// If design-time mode was used in the Code Generator, this will contain the dictionary\n        /// of design-time generated code mappings\n        /// </summary>\n        public IDictionary<int, GeneratedCodeMapping> DesignTimeLineMappings { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/GlobalSuppressions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n// This file is used by Code Analysis to maintain SuppressMessage \n// attributes that are applied to this project. \n// Project-level suppressions either have no target or are given \n// a specific target and scoped to a namespace, type, member, etc. \n//\n// To add a suppression to this file, right-click the message in the \n// Error List, point to \"Suppress Message(s)\", and click \n// \"In Project Suppression File\". \n// You do not need to add suppressions to this file manually. \n\nusing System.Diagnostics.CodeAnalysis;\n\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1703:ResourceStringsShouldBeSpelledCorrectly\", MessageId = \"br\", Scope = \"resource\", Target = \"System.Web.Razor.Resources.RazorResources.resources\", Justification = \"Resource is referencing html tag\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"System.Web.Razor.Tokenizer.Symbols\", Justification = \"These namespaces are design to group classes by function. They will be reviewed to ensure they remain relevant.\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"System.Web.Razor.Tokenizer\", Justification = \"These namespaces are design to group classes by function. They will be reviewed to ensure they remain relevant.\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"System.Web.Razor.Text\", Justification = \"These namespaces are design to group classes by function. They will be reviewed to ensure they remain relevant.\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"System.Web.Razor.Parser\", Justification = \"These namespaces are design to group classes by function. They will be reviewed to ensure they remain relevant.\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"System.Web.Razor.Editor\", Justification = \"These namespaces are design to group classes by function. They will be reviewed to ensure they remain relevant.\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"System.Web.Razor\", Justification = \"These namespaces are design to group classes by function. They will be reviewed to ensure they remain relevant.\")]\n[assembly: SuppressMessage(\"Microsoft.Web.FxCop\", \"MW1000:UnusedResourceUsageRule\", Justification = \"There are numerous unused resources due to VB being disabled. This rule will be re-run after VB is restored\")]\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/BalancingModes.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Razor.Parser\n{\n    [Flags]\n    public enum BalancingModes\n    {\n        None = 0,\n        BacktrackOnFailure = 1,\n        NoErrorOnFailure = 2,\n        AllowCommentsAndTemplates = 4,\n        AllowEmbeddedTransitions = 8\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/CSharpCodeParser.Directives.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq;\nusing System.Web.Razor.Editor;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Parser\n{\n    public partial class CSharpCodeParser\n    {\n        private void SetupDirectives()\n        {\n            MapDirectives(InheritsDirective, SyntaxConstants.CSharp.InheritsKeyword);\n            MapDirectives(FunctionsDirective, SyntaxConstants.CSharp.FunctionsKeyword);\n            MapDirectives(SectionDirective, SyntaxConstants.CSharp.SectionKeyword);\n            MapDirectives(HelperDirective, SyntaxConstants.CSharp.HelperKeyword);\n            MapDirectives(LayoutDirective, SyntaxConstants.CSharp.LayoutKeyword);\n            MapDirectives(SessionStateDirective, SyntaxConstants.CSharp.SessionStateKeyword);\n        }\n\n        protected virtual void LayoutDirective()\n        {\n            AssertDirective(SyntaxConstants.CSharp.LayoutKeyword);\n            AcceptAndMoveNext();\n            Context.CurrentBlock.Type = BlockType.Directive;\n\n            // Accept spaces, but not newlines\n            bool foundSomeWhitespace = At(CSharpSymbolType.WhiteSpace);\n            AcceptWhile(CSharpSymbolType.WhiteSpace);\n            Output(SpanKind.MetaCode, foundSomeWhitespace ? AcceptedCharacters.None : AcceptedCharacters.Any);\n\n            // First non-whitespace character starts the Layout Page, then newline ends it\n            AcceptUntil(CSharpSymbolType.NewLine);\n            Span.CodeGenerator = new SetLayoutCodeGenerator(Span.GetContent());\n            Span.EditHandler.EditorHints = EditorHints.LayoutPage | EditorHints.VirtualPath;\n            bool foundNewline = Optional(CSharpSymbolType.NewLine);\n            AddMarkerSymbolIfNecessary();\n            Output(SpanKind.MetaCode, foundNewline ? AcceptedCharacters.None : AcceptedCharacters.Any);\n        }\n\n        protected virtual void SessionStateDirective()\n        {\n            AssertDirective(SyntaxConstants.CSharp.SessionStateKeyword);\n            AcceptAndMoveNext();\n\n            SessionStateDirectiveCore();\n        }\n\n        protected void SessionStateDirectiveCore()\n        {\n            SessionStateTypeDirective(RazorResources.ParserEror_SessionDirectiveMissingValue, (key, value) => new RazorDirectiveAttributeCodeGenerator(key, value));\n        }\n\n        protected void SessionStateTypeDirective(string noValueError, Func<string, string, SpanCodeGenerator> createCodeGenerator)\n        {\n            // Set the block type\n            Context.CurrentBlock.Type = BlockType.Directive;\n\n            // Accept whitespace\n            CSharpSymbol remainingWs = AcceptSingleWhiteSpaceCharacter();\n\n            if (Span.Symbols.Count > 1)\n            {\n                Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n            }\n\n            Output(SpanKind.MetaCode);\n\n            if (remainingWs != null)\n            {\n                Accept(remainingWs);\n            }\n            AcceptWhile(IsSpacingToken(includeNewLines: false, includeComments: true));\n\n            // Parse a Type Name\n            if (!ValidSessionStateValue())\n            {\n                Context.OnError(CurrentLocation, noValueError);\n            }\n\n            // Pull out the type name\n            string sessionStateValue = String.Concat(\n                Span.Symbols\n                    .Cast<CSharpSymbol>()\n                    .Select(sym => sym.Content)).Trim();\n\n            // Set up code generation\n            Span.CodeGenerator = createCodeGenerator(SyntaxConstants.CSharp.SessionStateKeyword, sessionStateValue);\n\n            // Output the span and finish the block\n            CompleteBlock();\n            Output(SpanKind.Code);\n        }\n\n        protected virtual bool ValidSessionStateValue()\n        {\n            return Optional(CSharpSymbolType.Identifier);\n        }\n\n        [SuppressMessage(\"Microsoft.Maintainability\", \"CA1506:AvoidExcessiveClassCoupling\", Justification = \"Coupling will be reviewed at a later date\")]\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1308:NormalizeStringsToUppercase\", Justification = \"C# Keywords are always lower-case\")]\n        protected virtual void HelperDirective()\n        {\n            bool nested = Context.IsWithin(BlockType.Helper);\n\n            // Set the block and span type\n            Context.CurrentBlock.Type = BlockType.Helper;\n\n            // Verify we're on \"helper\" and accept\n            AssertDirective(SyntaxConstants.CSharp.HelperKeyword);\n            Block block = new Block(CurrentSymbol.Content.ToString().ToLowerInvariant(), CurrentLocation);\n            AcceptAndMoveNext();\n\n            if (nested)\n            {\n                Context.OnError(CurrentLocation, RazorResources.ParseError_Helpers_Cannot_Be_Nested);\n            }\n\n            // Accept a single whitespace character if present, if not, we should stop now\n            if (!At(CSharpSymbolType.WhiteSpace))\n            {\n                string error;\n                if (At(CSharpSymbolType.NewLine))\n                {\n                    error = RazorResources.ErrorComponent_Newline;\n                }\n                else if (EndOfFile)\n                {\n                    error = RazorResources.ErrorComponent_EndOfFile;\n                }\n                else\n                {\n                    error = String.Format(CultureInfo.CurrentCulture, RazorResources.ErrorComponent_Character, CurrentSymbol.Content);\n                }\n\n                Context.OnError(\n                    CurrentLocation,\n                    RazorResources.ParseError_Unexpected_Character_At_Helper_Name_Start,\n                    error);\n                PutCurrentBack();\n                Output(SpanKind.MetaCode);\n                return;\n            }\n\n            CSharpSymbol remainingWs = AcceptSingleWhiteSpaceCharacter();\n\n            // Output metacode and continue\n            Output(SpanKind.MetaCode);\n            if (remainingWs != null)\n            {\n                Accept(remainingWs);\n            }\n            AcceptWhile(IsSpacingToken(includeNewLines: false, includeComments: true)); // Don't accept newlines.\n\n            // Expecting an identifier (helper name)\n            bool errorReported = !Required(CSharpSymbolType.Identifier, errorIfNotFound: true, errorBase: RazorResources.ParseError_Unexpected_Character_At_Helper_Name_Start);\n            if (!errorReported)\n            {\n                Assert(CSharpSymbolType.Identifier);\n                AcceptAndMoveNext();\n            }\n\n            AcceptWhile(IsSpacingToken(includeNewLines: false, includeComments: true));\n\n            // Expecting parameter list start: \"(\"\n            SourceLocation bracketErrorPos = CurrentLocation;\n            if (!Optional(CSharpSymbolType.LeftParenthesis))\n            {\n                if (!errorReported)\n                {\n                    errorReported = true;\n                    Context.OnError(\n                        CurrentLocation,\n                        RazorResources.ParseError_MissingCharAfterHelperName,\n                        \"(\");\n                }\n            }\n            else\n            {\n                SourceLocation bracketStart = CurrentLocation;\n                if (!Balance(BalancingModes.NoErrorOnFailure,\n                             CSharpSymbolType.LeftParenthesis,\n                             CSharpSymbolType.RightParenthesis,\n                             bracketStart))\n                {\n                    errorReported = true;\n                    Context.OnError(\n                        bracketErrorPos,\n                        RazorResources.ParseError_UnterminatedHelperParameterList);\n                }\n                Optional(CSharpSymbolType.RightParenthesis);\n            }\n\n            int bookmark = CurrentLocation.AbsoluteIndex;\n            IEnumerable<CSharpSymbol> ws = ReadWhile(IsSpacingToken(includeNewLines: true, includeComments: true));\n\n            // Expecting a \"{\"\n            SourceLocation errorLocation = CurrentLocation;\n            bool headerComplete = At(CSharpSymbolType.LeftBrace);\n            if (headerComplete)\n            {\n                Accept(ws);\n                AcceptAndMoveNext();\n            }\n            else\n            {\n                Context.Source.Position = bookmark;\n                NextToken();\n                AcceptWhile(IsSpacingToken(includeNewLines: false, includeComments: true));\n                if (!errorReported)\n                {\n                    Context.OnError(\n                        errorLocation,\n                        RazorResources.ParseError_MissingCharAfterHelperParameters,\n                        Language.GetSample(CSharpSymbolType.LeftBrace));\n                }\n            }\n\n            // Grab the signature and build the code generator\n            AddMarkerSymbolIfNecessary();\n            LocationTagged<string> signature = Span.GetContent();\n            HelperCodeGenerator blockGen = new HelperCodeGenerator(signature, headerComplete);\n            Context.CurrentBlock.CodeGenerator = blockGen;\n\n            // The block will generate appropriate code, \n            Span.CodeGenerator = SpanCodeGenerator.Null;\n\n            if (!headerComplete)\n            {\n                CompleteBlock();\n                Output(SpanKind.Code);\n                return;\n            }\n            else\n            {\n                Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n                Output(SpanKind.Code);\n            }\n\n            // We're valid, so parse the nested block\n            AutoCompleteEditHandler bodyEditHandler = new AutoCompleteEditHandler(Language.TokenizeString);\n            using (PushSpanConfig(DefaultSpanConfig))\n            {\n                using (Context.StartBlock(BlockType.Statement))\n                {\n                    Span.EditHandler = bodyEditHandler;\n                    CodeBlock(false, block);\n                    CompleteBlock(insertMarkerIfNecessary: true);\n                    Output(SpanKind.Code);\n                }\n            }\n            Initialize(Span);\n\n            EnsureCurrent();\n\n            Span.CodeGenerator = SpanCodeGenerator.Null; // The block will generate the footer code.\n            if (!Optional(CSharpSymbolType.RightBrace))\n            {\n                // The } is missing, so set the initial signature span to use it as an autocomplete string\n                bodyEditHandler.AutoCompleteString = \"}\";\n\n                // Need to be able to accept anything to properly handle the autocomplete\n                bodyEditHandler.AcceptedCharacters = AcceptedCharacters.Any;\n            }\n            else\n            {\n                blockGen.Footer = Span.GetContent();\n                Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n            }\n            CompleteBlock();\n            Output(SpanKind.Code);\n        }\n\n        protected virtual void SectionDirective()\n        {\n            bool nested = Context.IsWithin(BlockType.Section);\n            bool errorReported = false;\n\n            // Set the block and span type\n            Context.CurrentBlock.Type = BlockType.Section;\n\n            // Verify we're on \"section\" and accept\n            AssertDirective(SyntaxConstants.CSharp.SectionKeyword);\n            AcceptAndMoveNext();\n\n            if (nested)\n            {\n                Context.OnError(CurrentLocation, String.Format(CultureInfo.CurrentCulture, RazorResources.ParseError_Sections_Cannot_Be_Nested, RazorResources.SectionExample_CS));\n                errorReported = true;\n            }\n\n            IEnumerable<CSharpSymbol> ws = ReadWhile(IsSpacingToken(includeNewLines: true, includeComments: false));\n\n            // Get the section name\n            string sectionName = String.Empty;\n            if (!Required(CSharpSymbolType.Identifier,\n                          errorIfNotFound: true,\n                          errorBase: RazorResources.ParseError_Unexpected_Character_At_Section_Name_Start))\n            {\n                if (!errorReported)\n                {\n                    errorReported = true;\n                }\n\n                PutCurrentBack();\n                PutBack(ws);\n                AcceptWhile(IsSpacingToken(includeNewLines: false, includeComments: false));\n            }\n            else\n            {\n                Accept(ws);\n                sectionName = CurrentSymbol.Content;\n                AcceptAndMoveNext();\n            }\n            Context.CurrentBlock.CodeGenerator = new SectionCodeGenerator(sectionName);\n\n            SourceLocation errorLocation = CurrentLocation;\n            ws = ReadWhile(IsSpacingToken(includeNewLines: true, includeComments: false));\n\n            // Get the starting brace\n            bool sawStartingBrace = At(CSharpSymbolType.LeftBrace);\n            if (!sawStartingBrace)\n            {\n                if (!errorReported)\n                {\n                    errorReported = true;\n                    Context.OnError(errorLocation, RazorResources.ParseError_MissingOpenBraceAfterSection);\n                }\n\n                PutCurrentBack();\n                PutBack(ws);\n                AcceptWhile(IsSpacingToken(includeNewLines: false, includeComments: false));\n                Optional(CSharpSymbolType.NewLine);\n                Output(SpanKind.MetaCode);\n                CompleteBlock();\n                return;\n            }\n            else\n            {\n                Accept(ws);\n            }\n\n            // Set up edit handler\n            AutoCompleteEditHandler editHandler = new AutoCompleteEditHandler(Language.TokenizeString) { AutoCompleteAtEndOfSpan = true };\n\n            Span.EditHandler = editHandler;\n            Span.Accept(CurrentSymbol);\n\n            // Output Metacode then switch to section parser\n            Output(SpanKind.MetaCode);\n            SectionBlock(\"{\", \"}\", caseSensitive: true);\n\n            Span.CodeGenerator = SpanCodeGenerator.Null;\n            // Check for the terminating \"}\"\n            if (!Optional(CSharpSymbolType.RightBrace))\n            {\n                editHandler.AutoCompleteString = \"}\";\n                Context.OnError(CurrentLocation,\n                                RazorResources.ParseError_Expected_X,\n                                Language.GetSample(CSharpSymbolType.RightBrace));\n            }\n            else\n            {\n                Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n            }\n            CompleteBlock(insertMarkerIfNecessary: false, captureWhitespaceToEndOfLine: true);\n            Output(SpanKind.MetaCode);\n            return;\n        }\n\n        protected virtual void FunctionsDirective()\n        {\n            // Set the block type\n            Context.CurrentBlock.Type = BlockType.Functions;\n\n            // Verify we're on \"functions\" and accept\n            AssertDirective(SyntaxConstants.CSharp.FunctionsKeyword);\n            Block block = new Block(CurrentSymbol);\n            AcceptAndMoveNext();\n\n            AcceptWhile(IsSpacingToken(includeNewLines: true, includeComments: false));\n\n            if (!At(CSharpSymbolType.LeftBrace))\n            {\n                Context.OnError(CurrentLocation,\n                                RazorResources.ParseError_Expected_X,\n                                Language.GetSample(CSharpSymbolType.LeftBrace));\n                CompleteBlock();\n                Output(SpanKind.MetaCode);\n                return;\n            }\n            else\n            {\n                Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n            }\n\n            // Capture start point and continue\n            SourceLocation blockStart = CurrentLocation;\n            AcceptAndMoveNext();\n\n            // Output what we've seen and continue\n            Output(SpanKind.MetaCode);\n\n            AutoCompleteEditHandler editHandler = new AutoCompleteEditHandler(Language.TokenizeString);\n            Span.EditHandler = editHandler;\n\n            Balance(BalancingModes.NoErrorOnFailure, CSharpSymbolType.LeftBrace, CSharpSymbolType.RightBrace, blockStart);\n            Span.CodeGenerator = new TypeMemberCodeGenerator();\n            if (!At(CSharpSymbolType.RightBrace))\n            {\n                editHandler.AutoCompleteString = \"}\";\n                Context.OnError(block.Start, RazorResources.ParseError_Expected_EndOfBlock_Before_EOF, block.Name, \"}\", \"{\");\n                CompleteBlock();\n                Output(SpanKind.Code);\n            }\n            else\n            {\n                Output(SpanKind.Code);\n                Assert(CSharpSymbolType.RightBrace);\n                Span.CodeGenerator = SpanCodeGenerator.Null;\n                Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n                AcceptAndMoveNext();\n                CompleteBlock();\n                Output(SpanKind.MetaCode);\n            }\n        }\n\n        protected virtual void InheritsDirective()\n        {\n            // Verify we're on the right keyword and accept\n            AssertDirective(SyntaxConstants.CSharp.InheritsKeyword);\n            AcceptAndMoveNext();\n\n            InheritsDirectiveCore();\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA1801:ReviewUnusedParameters\", MessageId = \"directive\", Justification = \"This only occurs in Release builds, where this method is empty by design\")]\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"This only occurs in Release builds, where this method is empty by design\")]\n        [Conditional(\"DEBUG\")]\n        protected void AssertDirective(string directive)\n        {\n            Assert(CSharpSymbolType.Identifier);\n            Debug.Assert(String.Equals(CurrentSymbol.Content, directive, StringComparison.Ordinal));\n        }\n\n        protected void InheritsDirectiveCore()\n        {\n            BaseTypeDirective(RazorResources.ParseError_InheritsKeyword_Must_Be_Followed_By_TypeName, baseType => new SetBaseTypeCodeGenerator(baseType));\n        }\n\n        protected void BaseTypeDirective(string noTypeNameError, Func<string, SpanCodeGenerator> createCodeGenerator)\n        {\n            // Set the block type\n            Context.CurrentBlock.Type = BlockType.Directive;\n\n            // Accept whitespace\n            CSharpSymbol remainingWs = AcceptSingleWhiteSpaceCharacter();\n\n            if (Span.Symbols.Count > 1)\n            {\n                Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n            }\n\n            Output(SpanKind.MetaCode);\n\n            if (remainingWs != null)\n            {\n                Accept(remainingWs);\n            }\n            AcceptWhile(IsSpacingToken(includeNewLines: false, includeComments: true));\n\n            if (EndOfFile || At(CSharpSymbolType.WhiteSpace) || At(CSharpSymbolType.NewLine))\n            {\n                Context.OnError(CurrentLocation, noTypeNameError);\n            }\n\n            // Parse to the end of the line\n            AcceptUntil(CSharpSymbolType.NewLine);\n            if (!Context.DesignTimeMode)\n            {\n                // We want the newline to be treated as code, but it causes issues at design-time.\n                Optional(CSharpSymbolType.NewLine);\n            }\n\n            // Pull out the type name\n            string baseType = Span.GetContent();\n\n            // Set up code generation\n            Span.CodeGenerator = createCodeGenerator(baseType.Trim());\n\n            // Output the span and finish the block\n            CompleteBlock();\n            Output(SpanKind.Code);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/CSharpCodeParser.Statements.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.Linq;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Parser\n{\n    public partial class CSharpCodeParser\n    {\n        private void SetUpKeywords()\n        {\n            MapKeywords(ConditionalBlock, CSharpKeyword.For, CSharpKeyword.Foreach, CSharpKeyword.While, CSharpKeyword.Switch, CSharpKeyword.Lock);\n            MapKeywords(CaseStatement, false, CSharpKeyword.Case, CSharpKeyword.Default);\n            MapKeywords(IfStatement, CSharpKeyword.If);\n            MapKeywords(TryStatement, CSharpKeyword.Try);\n            MapKeywords(UsingKeyword, CSharpKeyword.Using);\n            MapKeywords(DoStatement, CSharpKeyword.Do);\n            MapKeywords(ReservedDirective, CSharpKeyword.Namespace, CSharpKeyword.Class);\n        }\n\n        protected virtual void ReservedDirective(bool topLevel)\n        {\n            Context.OnError(CurrentLocation, String.Format(CultureInfo.CurrentCulture, RazorResources.ParseError_ReservedWord, CurrentSymbol.Content));\n            AcceptAndMoveNext();\n            Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n            Span.CodeGenerator = SpanCodeGenerator.Null;\n            Context.CurrentBlock.Type = BlockType.Directive;\n            CompleteBlock();\n            Output(SpanKind.MetaCode);\n        }\n\n        private void KeywordBlock(bool topLevel)\n        {\n            HandleKeyword(topLevel, () =>\n            {\n                Context.CurrentBlock.Type = BlockType.Expression;\n                Context.CurrentBlock.CodeGenerator = new ExpressionCodeGenerator();\n                ImplicitExpression();\n            });\n        }\n\n        private void CaseStatement(bool topLevel)\n        {\n            Assert(CSharpSymbolType.Keyword);\n            Debug.Assert(CurrentSymbol.Keyword != null &&\n                         (CurrentSymbol.Keyword.Value == CSharpKeyword.Case ||\n                          CurrentSymbol.Keyword.Value == CSharpKeyword.Default));\n            AcceptUntil(CSharpSymbolType.Colon);\n            Optional(CSharpSymbolType.Colon);\n        }\n\n        private void DoStatement(bool topLevel)\n        {\n            Assert(CSharpKeyword.Do);\n            UnconditionalBlock();\n            WhileClause();\n            if (topLevel)\n            {\n                CompleteBlock();\n            }\n        }\n\n        private void WhileClause()\n        {\n            Span.EditHandler.AcceptedCharacters = AcceptedCharacters.Any;\n            IEnumerable<CSharpSymbol> ws = SkipToNextImportantToken();\n\n            if (At(CSharpKeyword.While))\n            {\n                Accept(ws);\n                Assert(CSharpKeyword.While);\n                AcceptAndMoveNext();\n                AcceptWhile(IsSpacingToken(includeNewLines: true, includeComments: true));\n                if (AcceptCondition() && Optional(CSharpSymbolType.Semicolon))\n                {\n                    Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n                }\n            }\n            else\n            {\n                PutCurrentBack();\n                PutBack(ws);\n            }\n        }\n\n        private void UsingKeyword(bool topLevel)\n        {\n            Assert(CSharpKeyword.Using);\n            Block block = new Block(CurrentSymbol);\n            AcceptAndMoveNext();\n            AcceptWhile(IsSpacingToken(includeNewLines: false, includeComments: true));\n\n            if (At(CSharpSymbolType.LeftParenthesis))\n            {\n                // using ( ==> Using Statement\n                UsingStatement(block);\n            }\n            else if (At(CSharpSymbolType.Identifier))\n            {\n                // using Identifier ==> Using Declaration\n                if (!topLevel)\n                {\n                    Context.OnError(block.Start, RazorResources.ParseError_NamespaceImportAndTypeAlias_Cannot_Exist_Within_CodeBlock);\n                    StandardStatement();\n                }\n                else\n                {\n                    UsingDeclaration();\n                }\n            }\n\n            if (topLevel)\n            {\n                CompleteBlock();\n            }\n        }\n\n        private void UsingDeclaration()\n        {\n            // Set block type to directive\n            Context.CurrentBlock.Type = BlockType.Directive;\n\n            // Parse a type name\n            Assert(CSharpSymbolType.Identifier);\n            NamespaceOrTypeName();\n            IEnumerable<CSharpSymbol> ws = ReadWhile(IsSpacingToken(includeNewLines: true, includeComments: true));\n            if (At(CSharpSymbolType.Assign))\n            {\n                // Alias\n                Accept(ws);\n                Assert(CSharpSymbolType.Assign);\n                AcceptAndMoveNext();\n\n                AcceptWhile(IsSpacingToken(includeNewLines: true, includeComments: true));\n\n                // One more namespace or type name\n                NamespaceOrTypeName();\n            }\n            else\n            {\n                PutCurrentBack();\n                PutBack(ws);\n            }\n\n            Span.EditHandler.AcceptedCharacters = AcceptedCharacters.AnyExceptNewline;\n            Span.CodeGenerator = new AddImportCodeGenerator(\n                Span.GetContent(syms => syms.Skip(1)), // Skip \"using\"\n                SyntaxConstants.CSharp.UsingKeywordLength);\n\n            // Optional \";\"\n            if (EnsureCurrent())\n            {\n                Optional(CSharpSymbolType.Semicolon);\n            }\n        }\n\n        private bool NamespaceOrTypeName()\n        {\n            if (Optional(CSharpSymbolType.Identifier) || Optional(CSharpSymbolType.Keyword))\n            {\n                Optional(CSharpSymbolType.QuestionMark); // Nullable\n                if (Optional(CSharpSymbolType.DoubleColon))\n                {\n                    if (!Optional(CSharpSymbolType.Identifier))\n                    {\n                        Optional(CSharpSymbolType.Keyword);\n                    }\n                }\n                if (At(CSharpSymbolType.LessThan))\n                {\n                    TypeArgumentList();\n                }\n                if (Optional(CSharpSymbolType.Dot))\n                {\n                    NamespaceOrTypeName();\n                }\n                while (At(CSharpSymbolType.LeftBracket))\n                {\n                    Balance(BalancingModes.None);\n                    Optional(CSharpSymbolType.RightBracket);\n                }\n                return true;\n            }\n            else\n            {\n                return false;\n            }\n        }\n\n        private void TypeArgumentList()\n        {\n            Assert(CSharpSymbolType.LessThan);\n            Balance(BalancingModes.None);\n            Optional(CSharpSymbolType.GreaterThan);\n        }\n\n        private void UsingStatement(Block block)\n        {\n            Assert(CSharpSymbolType.LeftParenthesis);\n\n            // Parse condition\n            if (AcceptCondition())\n            {\n                AcceptWhile(IsSpacingToken(includeNewLines: true, includeComments: true));\n\n                // Parse code block\n                ExpectCodeBlock(block);\n            }\n        }\n\n        private void TryStatement(bool topLevel)\n        {\n            Assert(CSharpKeyword.Try);\n            UnconditionalBlock();\n            AfterTryClause();\n            if (topLevel)\n            {\n                CompleteBlock();\n            }\n        }\n\n        private void IfStatement(bool topLevel)\n        {\n            Assert(CSharpKeyword.If);\n            ConditionalBlock(topLevel: false);\n            AfterIfClause();\n            if (topLevel)\n            {\n                CompleteBlock();\n            }\n        }\n\n        private void AfterTryClause()\n        {\n            // Grab whitespace\n            IEnumerable<CSharpSymbol> ws = SkipToNextImportantToken();\n\n            // Check for a catch or finally part\n            if (At(CSharpKeyword.Catch))\n            {\n                Accept(ws);\n                Assert(CSharpKeyword.Catch);\n                ConditionalBlock(topLevel: false);\n                AfterTryClause();\n            }\n            else if (At(CSharpKeyword.Finally))\n            {\n                Accept(ws);\n                Assert(CSharpKeyword.Finally);\n                UnconditionalBlock();\n            }\n            else\n            {\n                // Return whitespace and end the block\n                PutCurrentBack();\n                PutBack(ws);\n                Span.EditHandler.AcceptedCharacters = AcceptedCharacters.Any;\n            }\n        }\n\n        private void AfterIfClause()\n        {\n            // Grab whitespace and razor comments\n            IEnumerable<CSharpSymbol> ws = SkipToNextImportantToken();\n\n            // Check for an else part\n            if (At(CSharpKeyword.Else))\n            {\n                Accept(ws);\n                Assert(CSharpKeyword.Else);\n                ElseClause();\n            }\n            else\n            {\n                // No else, return whitespace\n                PutCurrentBack();\n                PutBack(ws);\n                Span.EditHandler.AcceptedCharacters = AcceptedCharacters.Any;\n            }\n        }\n\n        private void ElseClause()\n        {\n            if (!At(CSharpKeyword.Else))\n            {\n                return;\n            }\n            Block block = new Block(CurrentSymbol);\n\n            AcceptAndMoveNext();\n            AcceptWhile(IsSpacingToken(includeNewLines: true, includeComments: true));\n            if (At(CSharpKeyword.If))\n            {\n                // ElseIf\n                block.Name = SyntaxConstants.CSharp.ElseIfKeyword;\n                ConditionalBlock(block);\n                AfterIfClause();\n            }\n            else if (!EndOfFile)\n            {\n                // Else\n                ExpectCodeBlock(block);\n            }\n        }\n\n        private void ExpectCodeBlock(Block block)\n        {\n            if (!EndOfFile)\n            {\n                // Check for \"{\" to make sure we're at a block\n                if (!At(CSharpSymbolType.LeftBrace))\n                {\n                    Context.OnError(CurrentLocation,\n                                    RazorResources.ParseError_SingleLine_ControlFlowStatements_Not_Allowed,\n                                    Language.GetSample(CSharpSymbolType.LeftBrace),\n                                    CurrentSymbol.Content);\n                }\n\n                // Parse the statement and then we're done\n                Statement(block);\n            }\n        }\n\n        private void UnconditionalBlock()\n        {\n            Assert(CSharpSymbolType.Keyword);\n            Block block = new Block(CurrentSymbol);\n            AcceptAndMoveNext();\n            AcceptWhile(IsSpacingToken(includeNewLines: true, includeComments: true));\n            ExpectCodeBlock(block);\n        }\n\n        private void ConditionalBlock(bool topLevel)\n        {\n            Assert(CSharpSymbolType.Keyword);\n            Block block = new Block(CurrentSymbol);\n            ConditionalBlock(block);\n            if (topLevel)\n            {\n                CompleteBlock();\n            }\n        }\n\n        private void ConditionalBlock(Block block)\n        {\n            AcceptAndMoveNext();\n            AcceptWhile(IsSpacingToken(includeNewLines: true, includeComments: true));\n\n            // Parse the condition, if present (if not present, we'll let the C# compiler complain)\n            if (AcceptCondition())\n            {\n                AcceptWhile(IsSpacingToken(includeNewLines: true, includeComments: true));\n                ExpectCodeBlock(block);\n            }\n        }\n\n        private bool AcceptCondition()\n        {\n            if (At(CSharpSymbolType.LeftParenthesis))\n            {\n                bool complete = Balance(BalancingModes.BacktrackOnFailure | BalancingModes.AllowCommentsAndTemplates);\n                if (!complete)\n                {\n                    AcceptUntil(CSharpSymbolType.NewLine);\n                }\n                else\n                {\n                    Optional(CSharpSymbolType.RightParenthesis);\n                }\n                return complete;\n            }\n            return true;\n        }\n\n        private void Statement()\n        {\n            Statement(null);\n        }\n\n        private void Statement(Block block)\n        {\n            Span.EditHandler.AcceptedCharacters = AcceptedCharacters.Any;\n\n            // Accept whitespace but always keep the last whitespace node so we can put it back if necessary\n            CSharpSymbol lastWs = AcceptWhiteSpaceInLines();\n            Debug.Assert(lastWs == null || (lastWs.Start.AbsoluteIndex + lastWs.Content.Length == CurrentLocation.AbsoluteIndex));\n\n            if (EndOfFile)\n            {\n                if (lastWs != null)\n                {\n                    Accept(lastWs);\n                }\n                return;\n            }\n\n            CSharpSymbolType type = CurrentSymbol.Type;\n            SourceLocation loc = CurrentLocation;\n\n            bool isSingleLineMarkup = type == CSharpSymbolType.Transition && NextIs(CSharpSymbolType.Colon);\n            bool isMarkup = isSingleLineMarkup ||\n                            type == CSharpSymbolType.LessThan ||\n                            (type == CSharpSymbolType.Transition && NextIs(CSharpSymbolType.LessThan));\n\n            if (Context.DesignTimeMode || !isMarkup)\n            {\n                // CODE owns whitespace, MARKUP owns it ONLY in DesignTimeMode.\n                if (lastWs != null)\n                {\n                    Accept(lastWs);\n                }\n            }\n            else\n            {\n                // MARKUP owns whitespace EXCEPT in DesignTimeMode.\n                PutCurrentBack();\n                PutBack(lastWs);\n            }\n\n            if (isMarkup)\n            {\n                if (type == CSharpSymbolType.Transition && !isSingleLineMarkup)\n                {\n                    Context.OnError(loc, RazorResources.ParseError_AtInCode_Must_Be_Followed_By_Colon_Paren_Or_Identifier_Start);\n                }\n\n                // Markup block\n                Output(SpanKind.Code);\n                if (Context.DesignTimeMode && CurrentSymbol != null && (CurrentSymbol.Type == CSharpSymbolType.LessThan || CurrentSymbol.Type == CSharpSymbolType.Transition))\n                {\n                    PutCurrentBack();\n                }\n                OtherParserBlock();\n            }\n            else\n            {\n                // What kind of statement is this?\n                HandleStatement(block, type);\n            }\n        }\n\n        private void HandleStatement(Block block, CSharpSymbolType type)\n        {\n            switch (type)\n            {\n                case CSharpSymbolType.RazorCommentTransition:\n                    Output(SpanKind.Code);\n                    RazorComment();\n                    Statement(block);\n                    break;\n                case CSharpSymbolType.LeftBrace:\n                    // Verbatim Block\n                    block = block ?? new Block(RazorResources.BlockName_Code, CurrentLocation);\n                    AcceptAndMoveNext();\n                    CodeBlock(block);\n                    break;\n                case CSharpSymbolType.Keyword:\n                    // Keyword block\n                    HandleKeyword(false, StandardStatement);\n                    break;\n                case CSharpSymbolType.Transition:\n                    // Embedded Expression block\n                    EmbeddedExpression();\n                    break;\n                case CSharpSymbolType.RightBrace:\n                    // Possible end of Code Block, just run the continuation\n                    break;\n                case CSharpSymbolType.Comment:\n                    AcceptAndMoveNext();\n                    break;\n                default:\n                    // Other statement\n                    StandardStatement();\n                    break;\n            }\n        }\n\n        private void EmbeddedExpression()\n        {\n            // First, verify the type of the block\n            Assert(CSharpSymbolType.Transition);\n            CSharpSymbol transition = CurrentSymbol;\n            NextToken();\n\n            if (At(CSharpSymbolType.Transition))\n            {\n                // Escaped \"@\"\n                Output(SpanKind.Code);\n\n                // Output \"@\" as hidden span\n                Accept(transition);\n                Span.CodeGenerator = SpanCodeGenerator.Null;\n                Output(SpanKind.Code);\n\n                Assert(CSharpSymbolType.Transition);\n                AcceptAndMoveNext();\n                StandardStatement();\n            }\n            else\n            {\n                // Throw errors as necessary, but continue parsing\n                if (At(CSharpSymbolType.Keyword))\n                {\n                    Context.OnError(CurrentLocation,\n                                    RazorResources.ParseError_Unexpected_Keyword_After_At,\n                                    CSharpLanguageCharacteristics.GetKeyword(CurrentSymbol.Keyword.Value));\n                }\n                else if (At(CSharpSymbolType.LeftBrace))\n                {\n                    Context.OnError(CurrentLocation, RazorResources.ParseError_Unexpected_Nested_CodeBlock);\n                }\n\n                // @( or @foo - Nested expression, parse a child block\n                PutCurrentBack();\n                PutBack(transition);\n\n                // Before exiting, add a marker span if necessary\n                AddMarkerSymbolIfNecessary();\n\n                NestedBlock();\n            }\n        }\n\n        private void StandardStatement()\n        {\n            while (!EndOfFile)\n            {\n                int bookmark = CurrentLocation.AbsoluteIndex;\n                IEnumerable<CSharpSymbol> read = ReadWhile(sym => sym.Type != CSharpSymbolType.Semicolon &&\n                                                                  sym.Type != CSharpSymbolType.RazorCommentTransition &&\n                                                                  sym.Type != CSharpSymbolType.Transition &&\n                                                                  sym.Type != CSharpSymbolType.LeftBrace &&\n                                                                  sym.Type != CSharpSymbolType.LeftParenthesis &&\n                                                                  sym.Type != CSharpSymbolType.LeftBracket &&\n                                                                  sym.Type != CSharpSymbolType.RightBrace);\n                if (At(CSharpSymbolType.LeftBrace) || At(CSharpSymbolType.LeftParenthesis) || At(CSharpSymbolType.LeftBracket))\n                {\n                    Accept(read);\n                    if (Balance(BalancingModes.AllowCommentsAndTemplates | BalancingModes.BacktrackOnFailure))\n                    {\n                        Optional(CSharpSymbolType.RightBrace);\n                    }\n                    else\n                    {\n                        // Recovery\n                        AcceptUntil(CSharpSymbolType.LessThan, CSharpSymbolType.RightBrace);\n                        return;\n                    }\n                }\n                else if (At(CSharpSymbolType.Transition) && (NextIs(CSharpSymbolType.LessThan, CSharpSymbolType.Colon)))\n                {\n                    Accept(read);\n                    Output(SpanKind.Code);\n                    Template();\n                }\n                else if (At(CSharpSymbolType.RazorCommentTransition))\n                {\n                    Accept(read);\n                    RazorComment();\n                }\n                else if (At(CSharpSymbolType.Semicolon))\n                {\n                    Accept(read);\n                    AcceptAndMoveNext();\n                    return;\n                }\n                else if (At(CSharpSymbolType.RightBrace))\n                {\n                    Accept(read);\n                    return;\n                }\n                else\n                {\n                    Context.Source.Position = bookmark;\n                    NextToken();\n                    AcceptUntil(CSharpSymbolType.LessThan, CSharpSymbolType.RightBrace);\n                    return;\n                }\n            }\n        }\n\n        private void CodeBlock(Block block)\n        {\n            CodeBlock(true, block);\n        }\n\n        private void CodeBlock(bool acceptTerminatingBrace, Block block)\n        {\n            EnsureCurrent();\n            while (!EndOfFile && !At(CSharpSymbolType.RightBrace))\n            {\n                // Parse a statement, then return here\n                Statement();\n                EnsureCurrent();\n            }\n\n            if (EndOfFile)\n            {\n                Context.OnError(block.Start, RazorResources.ParseError_Expected_EndOfBlock_Before_EOF, block.Name, '}', '{');\n            }\n            else if (acceptTerminatingBrace)\n            {\n                Assert(CSharpSymbolType.RightBrace);\n                Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n                AcceptAndMoveNext();\n            }\n        }\n\n        private void HandleKeyword(bool topLevel, Action fallback)\n        {\n            Debug.Assert(CurrentSymbol.Type == CSharpSymbolType.Keyword && CurrentSymbol.Keyword != null);\n            Action<bool> handler;\n            if (_keywordParsers.TryGetValue(CurrentSymbol.Keyword.Value, out handler))\n            {\n                handler(topLevel);\n            }\n            else\n            {\n                fallback();\n            }\n        }\n\n        private IEnumerable<CSharpSymbol> SkipToNextImportantToken()\n        {\n            while (!EndOfFile)\n            {\n                IEnumerable<CSharpSymbol> ws = ReadWhile(IsSpacingToken(includeNewLines: true, includeComments: true));\n                if (At(CSharpSymbolType.RazorCommentTransition))\n                {\n                    Accept(ws);\n                    Span.EditHandler.AcceptedCharacters = AcceptedCharacters.Any;\n                    RazorComment();\n                }\n                else\n                {\n                    return ws;\n                }\n            }\n            return Enumerable.Empty<CSharpSymbol>();\n        }\n\n        // Common code for Parsers, but FxCop REALLY doesn't like it in the base class.. moving it here for now.\n        protected override void OutputSpanBeforeRazorComment()\n        {\n            AddMarkerSymbolIfNecessary();\n            Output(SpanKind.Code);\n        }\n\n        protected class Block\n        {\n            public Block(string name, SourceLocation start)\n            {\n                Name = name;\n                Start = start;\n            }\n\n            public Block(CSharpSymbol symbol)\n                : this(GetName(symbol), symbol.Start)\n            {\n            }\n\n            public string Name { get; set; }\n            public SourceLocation Start { get; set; }\n\n            private static string GetName(CSharpSymbol sym)\n            {\n                if (sym.Type == CSharpSymbolType.Keyword)\n                {\n                    return CSharpLanguageCharacteristics.GetKeyword(sym.Keyword.Value);\n                }\n                return sym.Content;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/CSharpCodeParser.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Razor.Editor;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Tokenizer;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Parser\n{\n    public partial class CSharpCodeParser : TokenizerBackedParser<CSharpTokenizer, CSharpSymbol, CSharpSymbolType>\n    {\n        internal static readonly int UsingKeywordLength = 5; // using\n\n        internal static ISet<string> DefaultKeywords = new HashSet<string>()\n        {\n            \"if\",\n            \"do\",\n            \"try\",\n            \"for\",\n            \"foreach\",\n            \"while\",\n            \"switch\",\n            \"lock\",\n            \"using\",\n            \"section\",\n            \"inherits\",\n            \"helper\",\n            \"functions\",\n            \"namespace\",\n            \"class\",\n            \"layout\",\n            \"sessionstate\"\n        };\n\n        private Dictionary<string, Action> _directiveParsers = new Dictionary<string, Action>();\n        private Dictionary<CSharpKeyword, Action<bool>> _keywordParsers = new Dictionary<CSharpKeyword, Action<bool>>();\n\n        public CSharpCodeParser()\n        {\n            Keywords = new HashSet<string>();\n            SetUpKeywords();\n            SetupDirectives();\n        }\n\n        protected internal ISet<string> Keywords { get; private set; }\n\n        public bool IsNested { get; set; }\n\n        protected override ParserBase OtherParser\n        {\n            get { return Context.MarkupParser; }\n        }\n\n        protected override LanguageCharacteristics<CSharpTokenizer, CSharpSymbol, CSharpSymbolType> Language\n        {\n            get { return CSharpLanguageCharacteristics.Instance; }\n        }\n\n        protected void MapDirectives(Action handler, params string[] directives)\n        {\n            foreach (string directive in directives)\n            {\n                _directiveParsers.Add(directive, handler);\n                Keywords.Add(directive);\n            }\n        }\n\n        protected bool TryGetDirectiveHandler(string directive, out Action handler)\n        {\n            return _directiveParsers.TryGetValue(directive, out handler);\n        }\n\n        private void MapKeywords(Action<bool> handler, params CSharpKeyword[] keywords)\n        {\n            MapKeywords(handler, topLevel: true, keywords: keywords);\n        }\n\n        private void MapKeywords(Action<bool> handler, bool topLevel, params CSharpKeyword[] keywords)\n        {\n            foreach (CSharpKeyword keyword in keywords)\n            {\n                _keywordParsers.Add(keyword, handler);\n                if (topLevel)\n                {\n                    Keywords.Add(CSharpLanguageCharacteristics.GetKeyword(keyword));\n                }\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"This only occurs in Release builds, where this method is empty by design\")]\n        [Conditional(\"DEBUG\")]\n        internal void Assert(CSharpKeyword expectedKeyword)\n        {\n            Debug.Assert(CurrentSymbol.Type == CSharpSymbolType.Keyword && CurrentSymbol.Keyword.HasValue && CurrentSymbol.Keyword.Value == expectedKeyword);\n        }\n\n        protected internal bool At(CSharpKeyword keyword)\n        {\n            return At(CSharpSymbolType.Keyword) && CurrentSymbol.Keyword.HasValue && CurrentSymbol.Keyword.Value == keyword;\n        }\n\n        protected internal bool AcceptIf(CSharpKeyword keyword)\n        {\n            if (At(keyword))\n            {\n                AcceptAndMoveNext();\n                return true;\n            }\n            return false;\n        }\n\n        protected static Func<CSharpSymbol, bool> IsSpacingToken(bool includeNewLines, bool includeComments)\n        {\n            return sym => sym.Type == CSharpSymbolType.WhiteSpace ||\n                          (includeNewLines && sym.Type == CSharpSymbolType.NewLine) ||\n                          (includeComments && sym.Type == CSharpSymbolType.Comment);\n        }\n\n        public override void ParseBlock()\n        {\n            using (PushSpanConfig(DefaultSpanConfig))\n            {\n                if (Context == null)\n                {\n                    throw new InvalidOperationException(RazorResources.Parser_Context_Not_Set);\n                }\n\n                // Unless changed, the block is a statement block\n                using (Context.StartBlock(BlockType.Statement))\n                {\n                    NextToken();\n\n                    AcceptWhile(IsSpacingToken(includeNewLines: true, includeComments: true));\n\n                    CSharpSymbol current = CurrentSymbol;\n                    if (At(CSharpSymbolType.StringLiteral) && CurrentSymbol.Content.Length > 0 && CurrentSymbol.Content[0] == SyntaxConstants.TransitionCharacter)\n                    {\n                        Tuple<CSharpSymbol, CSharpSymbol> split = Language.SplitSymbol(CurrentSymbol, 1, CSharpSymbolType.Transition);\n                        current = split.Item1;\n                        Context.Source.Position = split.Item2.Start.AbsoluteIndex;\n                        NextToken();\n                    }\n                    else if (At(CSharpSymbolType.Transition))\n                    {\n                        NextToken();\n                    }\n\n                    // Accept \"@\" if we see it, but if we don't, that's OK. We assume we were started for a good reason\n                    if (current.Type == CSharpSymbolType.Transition)\n                    {\n                        if (Span.Symbols.Count > 0)\n                        {\n                            Output(SpanKind.Code);\n                        }\n                        AtTransition(current);\n                    }\n                    else\n                    {\n                        // No \"@\" => Jump straight to AfterTransition\n                        AfterTransition();\n                    }\n                    Output(SpanKind.Code);\n                }\n            }\n        }\n\n        private void DefaultSpanConfig(SpanBuilder span)\n        {\n            span.EditHandler = SpanEditHandler.CreateDefault(Language.TokenizeString);\n            span.CodeGenerator = new StatementCodeGenerator();\n        }\n\n        private void AtTransition(CSharpSymbol current)\n        {\n            Debug.Assert(current.Type == CSharpSymbolType.Transition);\n            Accept(current);\n            Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n            Span.CodeGenerator = SpanCodeGenerator.Null;\n\n            // Output the \"@\" span and continue here\n            Output(SpanKind.Transition);\n            AfterTransition();\n        }\n\n        private void AfterTransition()\n        {\n            using (PushSpanConfig(DefaultSpanConfig))\n            {\n                EnsureCurrent();\n                try\n                {\n                    // What type of block is this?\n                    if (!EndOfFile)\n                    {\n                        if (CurrentSymbol.Type == CSharpSymbolType.LeftParenthesis)\n                        {\n                            Context.CurrentBlock.Type = BlockType.Expression;\n                            Context.CurrentBlock.CodeGenerator = new ExpressionCodeGenerator();\n                            ExplicitExpression();\n                            return;\n                        }\n                        else if (CurrentSymbol.Type == CSharpSymbolType.Identifier)\n                        {\n                            Action handler;\n                            if (TryGetDirectiveHandler(CurrentSymbol.Content, out handler))\n                            {\n                                Span.CodeGenerator = SpanCodeGenerator.Null;\n                                handler();\n                                return;\n                            }\n                            else\n                            {\n                                Context.CurrentBlock.Type = BlockType.Expression;\n                                Context.CurrentBlock.CodeGenerator = new ExpressionCodeGenerator();\n                                ImplicitExpression();\n                                return;\n                            }\n                        }\n                        else if (CurrentSymbol.Type == CSharpSymbolType.Keyword)\n                        {\n                            KeywordBlock(topLevel: true);\n                            return;\n                        }\n                        else if (CurrentSymbol.Type == CSharpSymbolType.LeftBrace)\n                        {\n                            VerbatimBlock();\n                            return;\n                        }\n                    }\n\n                    // Invalid character\n                    Context.CurrentBlock.Type = BlockType.Expression;\n                    Context.CurrentBlock.CodeGenerator = new ExpressionCodeGenerator();\n                    AddMarkerSymbolIfNecessary();\n                    Span.CodeGenerator = new ExpressionCodeGenerator();\n                    Span.EditHandler = new ImplicitExpressionEditHandler(\n                        Language.TokenizeString,\n                        DefaultKeywords,\n                        acceptTrailingDot: IsNested)\n                        {\n                            AcceptedCharacters = AcceptedCharacters.NonWhiteSpace\n                        };\n                    if (At(CSharpSymbolType.WhiteSpace) || At(CSharpSymbolType.NewLine))\n                    {\n                        Context.OnError(CurrentLocation, RazorResources.ParseError_Unexpected_WhiteSpace_At_Start_Of_CodeBlock_CS);\n                    }\n                    else if (EndOfFile)\n                    {\n                        Context.OnError(CurrentLocation, RazorResources.ParseError_Unexpected_EndOfFile_At_Start_Of_CodeBlock);\n                    }\n                    else\n                    {\n                        Context.OnError(CurrentLocation, RazorResources.ParseError_Unexpected_Character_At_Start_Of_CodeBlock_CS, CurrentSymbol.Content);\n                    }\n                }\n                finally\n                {\n                    // Always put current character back in the buffer for the next parser.\n                    PutCurrentBack();\n                }\n            }\n        }\n\n        private void VerbatimBlock()\n        {\n            Assert(CSharpSymbolType.LeftBrace);\n            Block block = new Block(RazorResources.BlockName_Code, CurrentLocation);\n            AcceptAndMoveNext();\n\n            // Set up the \"{\" span and output\n            Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n            Span.CodeGenerator = SpanCodeGenerator.Null;\n            Output(SpanKind.MetaCode);\n\n            // Set up auto-complete and parse the code block\n            AutoCompleteEditHandler editHandler = new AutoCompleteEditHandler(Language.TokenizeString);\n            Span.EditHandler = editHandler;\n            CodeBlock(false, block);\n\n            Span.CodeGenerator = new StatementCodeGenerator();\n            AddMarkerSymbolIfNecessary();\n            if (!At(CSharpSymbolType.RightBrace))\n            {\n                editHandler.AutoCompleteString = \"}\";\n            }\n            Output(SpanKind.Code);\n\n            if (Optional(CSharpSymbolType.RightBrace))\n            {\n                // Set up the \"}\" span\n                Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n                Span.CodeGenerator = SpanCodeGenerator.Null;\n            }\n\n            if (!At(CSharpSymbolType.WhiteSpace) && !At(CSharpSymbolType.NewLine))\n            {\n                PutCurrentBack();\n            }\n\n            CompleteBlock(insertMarkerIfNecessary: false);\n            Output(SpanKind.MetaCode);\n        }\n\n        private void ImplicitExpression()\n        {\n            Context.CurrentBlock.Type = BlockType.Expression;\n            Context.CurrentBlock.CodeGenerator = new ExpressionCodeGenerator();\n\n            using (PushSpanConfig(span =>\n            {\n                span.EditHandler = new ImplicitExpressionEditHandler(Language.TokenizeString, Keywords, acceptTrailingDot: IsNested);\n                span.EditHandler.AcceptedCharacters = AcceptedCharacters.NonWhiteSpace;\n                span.CodeGenerator = new ExpressionCodeGenerator();\n            }))\n            {\n                do\n                {\n                    if (AtIdentifier(allowKeywords: true))\n                    {\n                        AcceptAndMoveNext();\n                    }\n                }\n                while (MethodCallOrArrayIndex());\n\n                PutCurrentBack();\n                Output(SpanKind.Code);\n            }\n        }\n\n        private bool MethodCallOrArrayIndex()\n        {\n            if (!EndOfFile)\n            {\n                if (CurrentSymbol.Type == CSharpSymbolType.LeftParenthesis || CurrentSymbol.Type == CSharpSymbolType.LeftBracket)\n                {\n                    // If we end within \"(\", whitespace is fine\n                    Span.EditHandler.AcceptedCharacters = AcceptedCharacters.Any;\n\n                    CSharpSymbolType right;\n                    bool success;\n\n                    using (PushSpanConfig((span, prev) =>\n                    {\n                        prev(span);\n                        span.EditHandler.AcceptedCharacters = AcceptedCharacters.Any;\n                    }))\n                    {\n                        right = Language.FlipBracket(CurrentSymbol.Type);\n                        success = Balance(BalancingModes.BacktrackOnFailure | BalancingModes.AllowCommentsAndTemplates);\n                    }\n\n                    if (!success)\n                    {\n                        AcceptUntil(CSharpSymbolType.LessThan);\n                    }\n                    if (At(right))\n                    {\n                        AcceptAndMoveNext();\n                        Span.EditHandler.AcceptedCharacters = AcceptedCharacters.NonWhiteSpace;\n                    }\n                    return MethodCallOrArrayIndex();\n                }\n                if (CurrentSymbol.Type == CSharpSymbolType.Dot)\n                {\n                    CSharpSymbol dot = CurrentSymbol;\n                    if (NextToken())\n                    {\n                        if (At(CSharpSymbolType.Identifier) || At(CSharpSymbolType.Keyword))\n                        {\n                            // Accept the dot and return to the start\n                            Accept(dot);\n                            return true; // continue\n                        }\n                        else\n                        {\n                            // Put the symbol back\n                            PutCurrentBack();\n                        }\n                    }\n                    if (!IsNested)\n                    {\n                        // Put the \".\" back\n                        PutBack(dot);\n                    }\n                    else\n                    {\n                        Accept(dot);\n                    }\n                }\n                else if (!At(CSharpSymbolType.WhiteSpace) && !At(CSharpSymbolType.NewLine))\n                {\n                    PutCurrentBack();\n                }\n            }\n\n            // Implicit Expression is complete\n            return false;\n        }\n\n        private void CompleteBlock()\n        {\n            CompleteBlock(insertMarkerIfNecessary: true);\n        }\n\n        private void CompleteBlock(bool insertMarkerIfNecessary)\n        {\n            CompleteBlock(insertMarkerIfNecessary, captureWhitespaceToEndOfLine: insertMarkerIfNecessary);\n        }\n\n        private void CompleteBlock(bool insertMarkerIfNecessary, bool captureWhitespaceToEndOfLine)\n        {\n            if (insertMarkerIfNecessary && Context.LastAcceptedCharacters != AcceptedCharacters.Any)\n            {\n                AddMarkerSymbolIfNecessary();\n            }\n\n            EnsureCurrent();\n\n            // Read whitespace, but not newlines\n            // If we're not inserting a marker span, we don't need to capture whitespace\n            if (!Context.WhiteSpaceIsSignificantToAncestorBlock &&\n                Context.CurrentBlock.Type != BlockType.Expression &&\n                captureWhitespaceToEndOfLine &&\n                !Context.DesignTimeMode &&\n                !IsNested)\n            {\n                CaptureWhitespaceAtEndOfCodeOnlyLine();\n            }\n            else\n            {\n                PutCurrentBack();\n            }\n        }\n\n        private void CaptureWhitespaceAtEndOfCodeOnlyLine()\n        {\n            IEnumerable<CSharpSymbol> ws = ReadWhile(sym => sym.Type == CSharpSymbolType.WhiteSpace);\n            if (At(CSharpSymbolType.NewLine))\n            {\n                Accept(ws);\n                AcceptAndMoveNext();\n                PutCurrentBack();\n            }\n            else\n            {\n                PutCurrentBack();\n                PutBack(ws);\n            }\n        }\n\n        private void ConfigureExplicitExpressionSpan(SpanBuilder sb)\n        {\n            sb.EditHandler = SpanEditHandler.CreateDefault(Language.TokenizeString);\n            sb.CodeGenerator = new ExpressionCodeGenerator();\n        }\n\n        private void ExplicitExpression()\n        {\n            Block block = new Block(RazorResources.BlockName_ExplicitExpression, CurrentLocation);\n            Assert(CSharpSymbolType.LeftParenthesis);\n            AcceptAndMoveNext();\n            Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n            Span.CodeGenerator = SpanCodeGenerator.Null;\n            Output(SpanKind.MetaCode);\n            using (PushSpanConfig(ConfigureExplicitExpressionSpan))\n            {\n                bool success = Balance(\n                    BalancingModes.BacktrackOnFailure | BalancingModes.NoErrorOnFailure | BalancingModes.AllowCommentsAndTemplates,\n                    CSharpSymbolType.LeftParenthesis,\n                    CSharpSymbolType.RightParenthesis,\n                    block.Start);\n\n                if (!success)\n                {\n                    AcceptUntil(CSharpSymbolType.LessThan);\n                    Context.OnError(block.Start, RazorResources.ParseError_Expected_EndOfBlock_Before_EOF, block.Name, \")\", \"(\");\n                }\n\n                // If necessary, put an empty-content marker symbol here\n                if (Span.Symbols.Count == 0)\n                {\n                    Accept(new CSharpSymbol(CurrentLocation, String.Empty, CSharpSymbolType.Unknown));\n                }\n\n                // Output the content span and then capture the \")\"\n                Output(SpanKind.Code);\n            }\n            Optional(CSharpSymbolType.RightParenthesis);\n            if (!EndOfFile)\n            {\n                PutCurrentBack();\n            }\n            Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n            Span.CodeGenerator = SpanCodeGenerator.Null;\n            CompleteBlock(insertMarkerIfNecessary: false);\n            Output(SpanKind.MetaCode);\n        }\n\n        private void Template()\n        {\n            if (Context.IsWithin(BlockType.Template))\n            {\n                Context.OnError(CurrentLocation, RazorResources.ParseError_InlineMarkup_Blocks_Cannot_Be_Nested);\n            }\n            Output(SpanKind.Code);\n            using (Context.StartBlock(BlockType.Template))\n            {\n                Context.CurrentBlock.CodeGenerator = new TemplateBlockCodeGenerator();\n                PutCurrentBack();\n                OtherParserBlock();\n            }\n        }\n\n        private void OtherParserBlock()\n        {\n            ParseWithOtherParser(p => p.ParseBlock());\n        }\n\n        private void SectionBlock(string left, string right, bool caseSensitive)\n        {\n            ParseWithOtherParser(p => p.ParseSection(Tuple.Create(left, right), caseSensitive));\n        }\n\n        private void NestedBlock()\n        {\n            Output(SpanKind.Code);\n            bool wasNested = IsNested;\n            IsNested = true;\n            using (PushSpanConfig())\n            {\n                ParseBlock();\n            }\n            Initialize(Span);\n            IsNested = wasNested;\n            NextToken();\n        }\n\n        protected override bool IsAtEmbeddedTransition(bool allowTemplatesAndComments, bool allowTransitions)\n        {\n            // No embedded transitions in C#, so ignore that param\n            return allowTemplatesAndComments\n                   && ((Language.IsTransition(CurrentSymbol)\n                        && NextIs(CSharpSymbolType.LessThan, CSharpSymbolType.Colon))\n                       || Language.IsCommentStart(CurrentSymbol));\n        }\n\n        protected override void HandleEmbeddedTransition()\n        {\n            if (Language.IsTransition(CurrentSymbol))\n            {\n                PutCurrentBack();\n                Template();\n            }\n            else if (Language.IsCommentStart(CurrentSymbol))\n            {\n                RazorComment();\n            }\n        }\n\n        private void ParseWithOtherParser(Action<ParserBase> parseAction)\n        {\n            using (PushSpanConfig())\n            {\n                Context.SwitchActiveParser();\n                parseAction(Context.MarkupParser);\n                Context.SwitchActiveParser();\n            }\n            Initialize(Span);\n            NextToken();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/CSharpLanguageCharacteristics.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Parser\n{\n    public class CSharpLanguageCharacteristics : LanguageCharacteristics<CSharpTokenizer, CSharpSymbol, CSharpSymbolType>\n    {\n        private static readonly CSharpLanguageCharacteristics _instance = new CSharpLanguageCharacteristics();\n\n        private static Dictionary<CSharpSymbolType, string> _symbolSamples = new Dictionary<CSharpSymbolType, string>()\n        {\n            { CSharpSymbolType.Arrow, \"->\" },\n            { CSharpSymbolType.Minus, \"-\" },\n            { CSharpSymbolType.Decrement, \"--\" },\n            { CSharpSymbolType.MinusAssign, \"-=\" },\n            { CSharpSymbolType.NotEqual, \"!=\" },\n            { CSharpSymbolType.Not, \"!\" },\n            { CSharpSymbolType.Modulo, \"%\" },\n            { CSharpSymbolType.ModuloAssign, \"%=\" },\n            { CSharpSymbolType.AndAssign, \"&=\" },\n            { CSharpSymbolType.And, \"&\" },\n            { CSharpSymbolType.DoubleAnd, \"&&\" },\n            { CSharpSymbolType.LeftParenthesis, \"(\" },\n            { CSharpSymbolType.RightParenthesis, \")\" },\n            { CSharpSymbolType.Star, \"*\" },\n            { CSharpSymbolType.MultiplyAssign, \"*=\" },\n            { CSharpSymbolType.Comma, \",\" },\n            { CSharpSymbolType.Dot, \".\" },\n            { CSharpSymbolType.Slash, \"/\" },\n            { CSharpSymbolType.DivideAssign, \"/=\" },\n            { CSharpSymbolType.DoubleColon, \"::\" },\n            { CSharpSymbolType.Colon, \":\" },\n            { CSharpSymbolType.Semicolon, \";\" },\n            { CSharpSymbolType.QuestionMark, \"?\" },\n            { CSharpSymbolType.NullCoalesce, \"??\" },\n            { CSharpSymbolType.RightBracket, \"]\" },\n            { CSharpSymbolType.LeftBracket, \"[\" },\n            { CSharpSymbolType.XorAssign, \"^=\" },\n            { CSharpSymbolType.Xor, \"^\" },\n            { CSharpSymbolType.LeftBrace, \"{\" },\n            { CSharpSymbolType.OrAssign, \"|=\" },\n            { CSharpSymbolType.DoubleOr, \"||\" },\n            { CSharpSymbolType.Or, \"|\" },\n            { CSharpSymbolType.RightBrace, \"}\" },\n            { CSharpSymbolType.Tilde, \"~\" },\n            { CSharpSymbolType.Plus, \"+\" },\n            { CSharpSymbolType.PlusAssign, \"+=\" },\n            { CSharpSymbolType.Increment, \"++\" },\n            { CSharpSymbolType.LessThan, \"<\" },\n            { CSharpSymbolType.LessThanEqual, \"<=\" },\n            { CSharpSymbolType.LeftShift, \"<<\" },\n            { CSharpSymbolType.LeftShiftAssign, \"<<=\" },\n            { CSharpSymbolType.Assign, \"=\" },\n            { CSharpSymbolType.Equals, \"==\" },\n            { CSharpSymbolType.GreaterThan, \">\" },\n            { CSharpSymbolType.GreaterThanEqual, \">=\" },\n            { CSharpSymbolType.RightShift, \">>\" },\n            { CSharpSymbolType.RightShiftAssign, \">>>\" },\n            { CSharpSymbolType.Hash, \"#\" },\n            { CSharpSymbolType.Transition, \"@\" },\n        };\n\n        private CSharpLanguageCharacteristics()\n        {\n        }\n\n        public static CSharpLanguageCharacteristics Instance\n        {\n            get { return _instance; }\n        }\n\n        public override CSharpTokenizer CreateTokenizer(ITextDocument source)\n        {\n            return new CSharpTokenizer(source);\n        }\n\n        protected override CSharpSymbol CreateSymbol(SourceLocation location, string content, CSharpSymbolType type, IEnumerable<RazorError> errors)\n        {\n            return new CSharpSymbol(location, content, type, errors);\n        }\n\n        public override string GetSample(CSharpSymbolType type)\n        {\n            return GetSymbolSample(type);\n        }\n\n        public override CSharpSymbol CreateMarkerSymbol(SourceLocation location)\n        {\n            return new CSharpSymbol(location, String.Empty, CSharpSymbolType.Unknown);\n        }\n\n        public override CSharpSymbolType GetKnownSymbolType(KnownSymbolType type)\n        {\n            switch (type)\n            {\n                case KnownSymbolType.Identifier:\n                    return CSharpSymbolType.Identifier;\n                case KnownSymbolType.Keyword:\n                    return CSharpSymbolType.Keyword;\n                case KnownSymbolType.NewLine:\n                    return CSharpSymbolType.NewLine;\n                case KnownSymbolType.WhiteSpace:\n                    return CSharpSymbolType.WhiteSpace;\n                case KnownSymbolType.Transition:\n                    return CSharpSymbolType.Transition;\n                case KnownSymbolType.CommentStart:\n                    return CSharpSymbolType.RazorCommentTransition;\n                case KnownSymbolType.CommentStar:\n                    return CSharpSymbolType.RazorCommentStar;\n                case KnownSymbolType.CommentBody:\n                    return CSharpSymbolType.RazorComment;\n                default:\n                    return CSharpSymbolType.Unknown;\n            }\n        }\n\n        public override CSharpSymbolType FlipBracket(CSharpSymbolType bracket)\n        {\n            switch (bracket)\n            {\n                case CSharpSymbolType.LeftBrace:\n                    return CSharpSymbolType.RightBrace;\n                case CSharpSymbolType.LeftBracket:\n                    return CSharpSymbolType.RightBracket;\n                case CSharpSymbolType.LeftParenthesis:\n                    return CSharpSymbolType.RightParenthesis;\n                case CSharpSymbolType.LessThan:\n                    return CSharpSymbolType.GreaterThan;\n                case CSharpSymbolType.RightBrace:\n                    return CSharpSymbolType.LeftBrace;\n                case CSharpSymbolType.RightBracket:\n                    return CSharpSymbolType.LeftBracket;\n                case CSharpSymbolType.RightParenthesis:\n                    return CSharpSymbolType.LeftParenthesis;\n                case CSharpSymbolType.GreaterThan:\n                    return CSharpSymbolType.LessThan;\n                default:\n                    Debug.Fail(\"FlipBracket must be called with a bracket character\");\n                    return CSharpSymbolType.Unknown;\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1308:NormalizeStringsToUppercase\", Justification = \"C# Keywords are lower-case\")]\n        public static string GetKeyword(CSharpKeyword keyword)\n        {\n            return keyword.ToString().ToLowerInvariant();\n        }\n\n        public static string GetSymbolSample(CSharpSymbolType type)\n        {\n            string sample;\n            if (!_symbolSamples.TryGetValue(type, out sample))\n            {\n                switch (type)\n                {\n                    case CSharpSymbolType.Identifier:\n                        return RazorResources.CSharpSymbol_Identifier;\n                    case CSharpSymbolType.Keyword:\n                        return RazorResources.CSharpSymbol_Keyword;\n                    case CSharpSymbolType.IntegerLiteral:\n                        return RazorResources.CSharpSymbol_IntegerLiteral;\n                    case CSharpSymbolType.NewLine:\n                        return RazorResources.CSharpSymbol_Newline;\n                    case CSharpSymbolType.WhiteSpace:\n                        return RazorResources.CSharpSymbol_Whitespace;\n                    case CSharpSymbolType.Comment:\n                        return RazorResources.CSharpSymbol_Comment;\n                    case CSharpSymbolType.RealLiteral:\n                        return RazorResources.CSharpSymbol_RealLiteral;\n                    case CSharpSymbolType.CharacterLiteral:\n                        return RazorResources.CSharpSymbol_CharacterLiteral;\n                    case CSharpSymbolType.StringLiteral:\n                        return RazorResources.CSharpSymbol_StringLiteral;\n                    default:\n                        return RazorResources.Symbol_Unknown;\n                }\n            }\n            return sample;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/CallbackVisitor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.Razor.Parser\n{\n    public class CallbackVisitor : ParserVisitor\n    {\n        private Action<Span> _spanCallback;\n        private Action<RazorError> _errorCallback;\n        private Action<BlockType> _endBlockCallback;\n        private Action<BlockType> _startBlockCallback;\n        private Action _completeCallback;\n\n        public CallbackVisitor(Action<Span> spanCallback)\n            : this(spanCallback, _ =>\n            {\n            })\n        {\n        }\n\n        public CallbackVisitor(Action<Span> spanCallback, Action<RazorError> errorCallback)\n            : this(spanCallback, errorCallback, _ =>\n            {\n            }, _ =>\n            {\n            })\n        {\n        }\n\n        public CallbackVisitor(Action<Span> spanCallback, Action<RazorError> errorCallback, Action<BlockType> startBlockCallback, Action<BlockType> endBlockCallback)\n            : this(spanCallback, errorCallback, startBlockCallback, endBlockCallback, () =>\n            {\n            })\n        {\n        }\n\n        public CallbackVisitor(Action<Span> spanCallback, Action<RazorError> errorCallback, Action<BlockType> startBlockCallback, Action<BlockType> endBlockCallback, Action completeCallback)\n        {\n            _spanCallback = spanCallback;\n            _errorCallback = errorCallback;\n            _startBlockCallback = startBlockCallback;\n            _endBlockCallback = endBlockCallback;\n            _completeCallback = completeCallback;\n        }\n\n        public SynchronizationContext SynchronizationContext { get; set; }\n\n        public override void VisitStartBlock(Block block)\n        {\n            base.VisitStartBlock(block);\n            RaiseCallback(SynchronizationContext, block.Type, _startBlockCallback);\n        }\n\n        public override void VisitSpan(Span span)\n        {\n            base.VisitSpan(span);\n            RaiseCallback(SynchronizationContext, span, _spanCallback);\n        }\n\n        public override void VisitEndBlock(Block block)\n        {\n            base.VisitEndBlock(block);\n            RaiseCallback(SynchronizationContext, block.Type, _endBlockCallback);\n        }\n\n        public override void VisitError(RazorError err)\n        {\n            base.VisitError(err);\n            RaiseCallback(SynchronizationContext, err, _errorCallback);\n        }\n\n        public override void OnComplete()\n        {\n            base.OnComplete();\n            RaiseCallback<object>(SynchronizationContext, null, _ => _completeCallback());\n        }\n\n        private static void RaiseCallback<T>(SynchronizationContext syncContext, T param, Action<T> callback)\n        {\n            if (callback != null)\n            {\n                if (syncContext != null)\n                {\n                    syncContext.Post(state => callback((T)state), param);\n                }\n                else\n                {\n                    callback(param);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/ConditionalAttributeCollapser.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Web.Razor.Editor;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer;\n\nnamespace System.Web.Razor.Parser\n{\n    internal class ConditionalAttributeCollapser : MarkupRewriter\n    {\n        public ConditionalAttributeCollapser(Action<SpanBuilder, SourceLocation, string> markupSpanFactory) : base(markupSpanFactory)\n        {\n        }\n\n        protected override bool CanRewrite(Block block)\n        {\n            AttributeBlockCodeGenerator gen = block.CodeGenerator as AttributeBlockCodeGenerator;\n            return gen != null && block.Children.Any() && block.Children.All(IsLiteralAttributeValue);\n        }\n\n        protected override SyntaxTreeNode RewriteBlock(BlockBuilder parent, Block block)\n        {\n            // Collect the content of this node\n            string content = String.Concat(block.Children.Cast<Span>().Select(s => s.Content));\n\n            // Create a new span containing this content\n            SpanBuilder span = new SpanBuilder();\n            span.EditHandler = new SpanEditHandler(HtmlTokenizer.Tokenize);\n            FillSpan(span, block.Children.Cast<Span>().First().Start, content);\n            return span.Build();\n        }\n\n        private bool IsLiteralAttributeValue(SyntaxTreeNode node)\n        {\n            if (node.IsBlock)\n            {\n                return false;\n            }\n            Span span = node as Span;\n            Debug.Assert(span != null);\n\n            LiteralAttributeCodeGenerator litGen = span.CodeGenerator as LiteralAttributeCodeGenerator;\n\n            return span != null &&\n                   ((litGen != null && litGen.ValueGenerator == null) ||\n                    span.CodeGenerator == SpanCodeGenerator.Null ||\n                    span.CodeGenerator is MarkupCodeGenerator);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/HtmlLanguageCharacteristics.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Parser\n{\n    public class HtmlLanguageCharacteristics : LanguageCharacteristics<HtmlTokenizer, HtmlSymbol, HtmlSymbolType>\n    {\n        private static readonly HtmlLanguageCharacteristics _instance = new HtmlLanguageCharacteristics();\n\n        private HtmlLanguageCharacteristics()\n        {\n        }\n\n        public static HtmlLanguageCharacteristics Instance\n        {\n            get { return _instance; }\n        }\n\n        public override string GetSample(HtmlSymbolType type)\n        {\n            switch (type)\n            {\n                case HtmlSymbolType.Text:\n                    return RazorResources.HtmlSymbol_Text;\n                case HtmlSymbolType.WhiteSpace:\n                    return RazorResources.HtmlSymbol_WhiteSpace;\n                case HtmlSymbolType.NewLine:\n                    return RazorResources.HtmlSymbol_NewLine;\n                case HtmlSymbolType.OpenAngle:\n                    return \"<\";\n                case HtmlSymbolType.Bang:\n                    return \"!\";\n                case HtmlSymbolType.Solidus:\n                    return \"/\";\n                case HtmlSymbolType.QuestionMark:\n                    return \"?\";\n                case HtmlSymbolType.DoubleHyphen:\n                    return \"--\";\n                case HtmlSymbolType.LeftBracket:\n                    return \"[\";\n                case HtmlSymbolType.CloseAngle:\n                    return \">\";\n                case HtmlSymbolType.RightBracket:\n                    return \"]\";\n                case HtmlSymbolType.Equals:\n                    return \"=\";\n                case HtmlSymbolType.DoubleQuote:\n                    return \"\\\"\";\n                case HtmlSymbolType.SingleQuote:\n                    return \"'\";\n                case HtmlSymbolType.Transition:\n                    return \"@\";\n                case HtmlSymbolType.Colon:\n                    return \":\";\n                case HtmlSymbolType.RazorComment:\n                    return RazorResources.HtmlSymbol_RazorComment;\n                case HtmlSymbolType.RazorCommentStar:\n                    return \"*\";\n                case HtmlSymbolType.RazorCommentTransition:\n                    return \"@\";\n                default:\n                    return RazorResources.Symbol_Unknown;\n            }\n        }\n\n        public override HtmlTokenizer CreateTokenizer(ITextDocument source)\n        {\n            return new HtmlTokenizer(source);\n        }\n\n        public override HtmlSymbolType FlipBracket(HtmlSymbolType bracket)\n        {\n            switch (bracket)\n            {\n                case HtmlSymbolType.LeftBracket:\n                    return HtmlSymbolType.RightBracket;\n                case HtmlSymbolType.OpenAngle:\n                    return HtmlSymbolType.CloseAngle;\n                case HtmlSymbolType.RightBracket:\n                    return HtmlSymbolType.LeftBracket;\n                case HtmlSymbolType.CloseAngle:\n                    return HtmlSymbolType.OpenAngle;\n                default:\n                    Debug.Fail(\"FlipBracket must be called with a bracket character\");\n                    return HtmlSymbolType.Unknown;\n            }\n        }\n\n        public override HtmlSymbol CreateMarkerSymbol(SourceLocation location)\n        {\n            return new HtmlSymbol(location, String.Empty, HtmlSymbolType.Unknown);\n        }\n\n        public override HtmlSymbolType GetKnownSymbolType(KnownSymbolType type)\n        {\n            switch (type)\n            {\n                case KnownSymbolType.CommentStart:\n                    return HtmlSymbolType.RazorCommentTransition;\n                case KnownSymbolType.CommentStar:\n                    return HtmlSymbolType.RazorCommentStar;\n                case KnownSymbolType.CommentBody:\n                    return HtmlSymbolType.RazorComment;\n                case KnownSymbolType.Identifier:\n                    return HtmlSymbolType.Text;\n                case KnownSymbolType.Keyword:\n                    return HtmlSymbolType.Text;\n                case KnownSymbolType.NewLine:\n                    return HtmlSymbolType.NewLine;\n                case KnownSymbolType.Transition:\n                    return HtmlSymbolType.Transition;\n                case KnownSymbolType.WhiteSpace:\n                    return HtmlSymbolType.WhiteSpace;\n                default:\n                    return HtmlSymbolType.Unknown;\n            }\n        }\n\n        protected override HtmlSymbol CreateSymbol(SourceLocation location, string content, HtmlSymbolType type, IEnumerable<RazorError> errors)\n        {\n            return new HtmlSymbol(location, content, type, errors);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/HtmlMarkupParser.Block.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Web.Razor.Editor;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Parser\n{\n    public partial class HtmlMarkupParser\n    {\n        private SourceLocation _lastTagStart = SourceLocation.Zero;\n        private HtmlSymbol _bufferedOpenAngle;\n\n        public override void ParseBlock()\n        {\n            if (Context == null)\n            {\n                throw new InvalidOperationException(RazorResources.Parser_Context_Not_Set);\n            }\n\n            using (PushSpanConfig(DefaultMarkupSpan))\n            {\n                using (Context.StartBlock(BlockType.Markup))\n                {\n                    if (!NextToken())\n                    {\n                        return;\n                    }\n\n                    AcceptWhile(IsSpacingToken(includeNewLines: true));\n\n                    if (CurrentSymbol.Type == HtmlSymbolType.OpenAngle)\n                    {\n                        // \"<\" => Implicit Tag Block\n                        TagBlock(new Stack<Tuple<HtmlSymbol, SourceLocation>>());\n                    }\n                    else if (CurrentSymbol.Type == HtmlSymbolType.Transition)\n                    {\n                        // \"@\" => Explicit Tag/Single Line Block OR Template\n                        Output(SpanKind.Markup);\n\n                        // Definitely have a transition span\n                        Assert(HtmlSymbolType.Transition);\n                        AcceptAndMoveNext();\n                        Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n                        Span.CodeGenerator = SpanCodeGenerator.Null;\n                        Output(SpanKind.Transition);\n                        if (At(HtmlSymbolType.Transition))\n                        {\n                            Span.CodeGenerator = SpanCodeGenerator.Null;\n                            AcceptAndMoveNext();\n                            Output(SpanKind.MetaCode);\n                        }\n                        AfterTransition();\n                    }\n                    else\n                    {\n                        Context.OnError(CurrentSymbol.Start, RazorResources.ParseError_MarkupBlock_Must_Start_With_Tag);\n                    }\n                    Output(SpanKind.Markup);\n                }\n            }\n        }\n\n        private void DefaultMarkupSpan(SpanBuilder span)\n        {\n            span.CodeGenerator = new MarkupCodeGenerator();\n            span.EditHandler = new SpanEditHandler(Language.TokenizeString, AcceptedCharacters.Any);\n        }\n\n        private void AfterTransition()\n        {\n            // \"@:\" => Explicit Single Line Block\n            if (CurrentSymbol.Type == HtmlSymbolType.Text && CurrentSymbol.Content.Length > 0 && CurrentSymbol.Content[0] == ':')\n            {\n                // Split the token\n                Tuple<HtmlSymbol, HtmlSymbol> split = Language.SplitSymbol(CurrentSymbol, 1, HtmlSymbolType.Colon);\n\n                // The first part (left) is added to this span and we return a MetaCode span\n                Accept(split.Item1);\n                Span.CodeGenerator = SpanCodeGenerator.Null;\n                Output(SpanKind.MetaCode);\n                if (split.Item2 != null)\n                {\n                    Accept(split.Item2);\n                }\n                NextToken();\n                SingleLineMarkup();\n            }\n            else if (CurrentSymbol.Type == HtmlSymbolType.OpenAngle)\n            {\n                TagBlock(new Stack<Tuple<HtmlSymbol, SourceLocation>>());\n            }\n        }\n\n        private void SingleLineMarkup()\n        {\n            // Parse until a newline, it's that simple!\n            // First, signal to code parser that whitespace is significant to us.\n            bool old = Context.WhiteSpaceIsSignificantToAncestorBlock;\n            Context.WhiteSpaceIsSignificantToAncestorBlock = true;\n            Span.EditHandler = new SingleLineMarkupEditHandler(Language.TokenizeString);\n            SkipToAndParseCode(HtmlSymbolType.NewLine);\n            if (!EndOfFile && CurrentSymbol.Type == HtmlSymbolType.NewLine)\n            {\n                AcceptAndMoveNext();\n                Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n            }\n            PutCurrentBack();\n            Context.WhiteSpaceIsSignificantToAncestorBlock = old;\n            Output(SpanKind.Markup);\n        }\n\n        private void TagBlock(Stack<Tuple<HtmlSymbol, SourceLocation>> tags)\n        {\n            // Skip Whitespace and Text\n            bool complete = false;\n            do\n            {\n                SkipToAndParseCode(HtmlSymbolType.OpenAngle);\n                if (EndOfFile)\n                {\n                    EndTagBlock(tags, complete: true);\n                }\n                else\n                {\n                    _bufferedOpenAngle = null;\n                    _lastTagStart = CurrentLocation;\n                    Assert(HtmlSymbolType.OpenAngle);\n                    _bufferedOpenAngle = CurrentSymbol;\n                    SourceLocation tagStart = CurrentLocation;\n                    if (!NextToken())\n                    {\n                        Accept(_bufferedOpenAngle);\n                        EndTagBlock(tags, complete: false);\n                    }\n                    else\n                    {\n                        complete = AfterTagStart(tagStart, tags);\n                    }\n                }\n            }\n            while (tags.Count > 0);\n\n            EndTagBlock(tags, complete);\n        }\n\n        private bool AfterTagStart(SourceLocation tagStart, Stack<Tuple<HtmlSymbol, SourceLocation>> tags)\n        {\n            if (!EndOfFile)\n            {\n                switch (CurrentSymbol.Type)\n                {\n                    case HtmlSymbolType.Solidus:\n                        // End Tag\n                        return EndTag(tagStart, tags);\n                    case HtmlSymbolType.Bang:\n                        // Comment\n                        Accept(_bufferedOpenAngle);\n                        return BangTag();\n                    case HtmlSymbolType.QuestionMark:\n                        // XML PI\n                        Accept(_bufferedOpenAngle);\n                        return XmlPI();\n                    default:\n                        // Start Tag\n                        return StartTag(tags);\n                }\n            }\n            if (tags.Count == 0)\n            {\n                Context.OnError(CurrentLocation, RazorResources.ParseError_OuterTagMissingName);\n            }\n            return false;\n        }\n\n        private bool XmlPI()\n        {\n            // Accept \"?\"\n            Assert(HtmlSymbolType.QuestionMark);\n            AcceptAndMoveNext();\n            return AcceptUntilAll(HtmlSymbolType.QuestionMark, HtmlSymbolType.CloseAngle);\n        }\n\n        private bool BangTag()\n        {\n            // Accept \"!\"\n            Assert(HtmlSymbolType.Bang);\n\n            if (AcceptAndMoveNext())\n            {\n                if (CurrentSymbol.Type == HtmlSymbolType.DoubleHyphen)\n                {\n                    AcceptAndMoveNext();\n                    return AcceptUntilAll(HtmlSymbolType.DoubleHyphen, HtmlSymbolType.CloseAngle);\n                }\n                else if (CurrentSymbol.Type == HtmlSymbolType.LeftBracket)\n                {\n                    if (AcceptAndMoveNext())\n                    {\n                        return CData();\n                    }\n                }\n                else\n                {\n                    AcceptAndMoveNext();\n                    return AcceptUntilAll(HtmlSymbolType.CloseAngle);\n                }\n            }\n\n            return false;\n        }\n\n        private bool CData()\n        {\n            if (CurrentSymbol.Type == HtmlSymbolType.Text && String.Equals(CurrentSymbol.Content, \"cdata\", StringComparison.OrdinalIgnoreCase))\n            {\n                if (AcceptAndMoveNext())\n                {\n                    if (CurrentSymbol.Type == HtmlSymbolType.LeftBracket)\n                    {\n                        return AcceptUntilAll(HtmlSymbolType.RightBracket, HtmlSymbolType.RightBracket, HtmlSymbolType.CloseAngle);\n                    }\n                }\n            }\n\n            return false;\n        }\n\n        private bool EndTag(SourceLocation tagStart, Stack<Tuple<HtmlSymbol, SourceLocation>> tags)\n        {\n            // Accept \"/\" and move next\n            Assert(HtmlSymbolType.Solidus);\n            HtmlSymbol solidus = CurrentSymbol;\n            if (!NextToken())\n            {\n                Accept(_bufferedOpenAngle);\n                Accept(solidus);\n                return false;\n            }\n            else\n            {\n                string tagName = String.Empty;\n                if (At(HtmlSymbolType.Text))\n                {\n                    tagName = CurrentSymbol.Content;\n                }\n                bool matched = RemoveTag(tags, tagName, tagStart);\n\n                if (tags.Count == 0 &&\n                    String.Equals(tagName, SyntaxConstants.TextTagName, StringComparison.OrdinalIgnoreCase) &&\n                    matched)\n                {\n                    Output(SpanKind.Markup);\n                    return EndTextTag(solidus);\n                }\n                Accept(_bufferedOpenAngle);\n                Accept(solidus);\n\n                AcceptUntil(HtmlSymbolType.CloseAngle);\n\n                // Accept the \">\"\n                return Optional(HtmlSymbolType.CloseAngle);\n            }\n        }\n\n        private bool EndTextTag(HtmlSymbol solidus)\n        {\n            SourceLocation start = _bufferedOpenAngle.Start;\n\n            Accept(_bufferedOpenAngle);\n            Accept(solidus);\n\n            Assert(HtmlSymbolType.Text);\n            AcceptAndMoveNext();\n\n            bool seenCloseAngle = Optional(HtmlSymbolType.CloseAngle);\n\n            if (!seenCloseAngle)\n            {\n                Context.OnError(start, RazorResources.ParseError_TextTagCannotContainAttributes);\n            }\n            else\n            {\n                Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n            }\n\n            Span.CodeGenerator = SpanCodeGenerator.Null;\n            Output(SpanKind.Transition);\n            return seenCloseAngle;\n        }\n\n        private bool IsTagRecoveryStopPoint(HtmlSymbol sym)\n        {\n            return sym.Type == HtmlSymbolType.CloseAngle ||\n                   sym.Type == HtmlSymbolType.Solidus ||\n                   sym.Type == HtmlSymbolType.OpenAngle ||\n                   sym.Type == HtmlSymbolType.SingleQuote ||\n                   sym.Type == HtmlSymbolType.DoubleQuote;\n        }\n\n        private void TagContent()\n        {\n            if (!At(HtmlSymbolType.WhiteSpace))\n            {\n                // We should be right after the tag name, so if there's no whitespace, something is wrong\n                RecoverToEndOfTag();\n            }\n            else\n            {\n                // We are here ($): <tag$ foo=\"bar\" biz=\"~/Baz\" />\n                while (!EndOfFile && !IsEndOfTag())\n                {\n                    BeforeAttribute();\n                }\n            }\n        }\n\n        private bool IsEndOfTag()\n        {\n            if (At(HtmlSymbolType.Solidus))\n            {\n                if (NextIs(HtmlSymbolType.CloseAngle))\n                {\n                    return true;\n                }\n                else\n                {\n                    AcceptAndMoveNext();\n                }\n            }\n            return At(HtmlSymbolType.CloseAngle) || At(HtmlSymbolType.OpenAngle);\n        }\n\n        private void BeforeAttribute()\n        {\n            // http://dev.w3.org/html5/spec/tokenization.html#before-attribute-name-state\n            // Capture whitespace\n            var whitespace = ReadWhile(sym => sym.Type == HtmlSymbolType.WhiteSpace || sym.Type == HtmlSymbolType.NewLine);\n\n            if (At(HtmlSymbolType.Transition))\n            {\n                // Transition outside of attribute value => Switch to recovery mode\n                Accept(whitespace);\n                RecoverToEndOfTag();\n                return;\n            }\n\n            // http://dev.w3.org/html5/spec/tokenization.html#attribute-name-state\n            // Read the 'name' (i.e. read until the '=' or whitespace/newline)\n            var name = Enumerable.Empty<HtmlSymbol>();\n            if (At(HtmlSymbolType.Text))\n            {\n                name = ReadWhile(sym =>\n                                 sym.Type != HtmlSymbolType.WhiteSpace &&\n                                 sym.Type != HtmlSymbolType.NewLine &&\n                                 sym.Type != HtmlSymbolType.Equals &&\n                                 sym.Type != HtmlSymbolType.CloseAngle &&\n                                 sym.Type != HtmlSymbolType.OpenAngle &&\n                                 (sym.Type != HtmlSymbolType.Solidus || !NextIs(HtmlSymbolType.CloseAngle)));\n            }\n            else\n            {\n                // Unexpected character in tag, enter recovery\n                Accept(whitespace);\n                RecoverToEndOfTag();\n                return;\n            }\n\n            if (!At(HtmlSymbolType.Equals))\n            {\n                // Saw a space or newline after the name, so just skip this attribute and continue around the loop\n                Accept(whitespace);\n                Accept(name);\n                return;\n            }\n\n            Output(SpanKind.Markup);\n\n            // Start a new markup block for the attribute\n            using (Context.StartBlock(BlockType.Markup))\n            {\n                AttributePrefix(whitespace, name);\n            }\n        }\n\n        private void AttributePrefix(IEnumerable<HtmlSymbol> whitespace, IEnumerable<HtmlSymbol> nameSymbols)\n        {\n            // First, determine if this is a 'data-' attribute (since those can't use conditional attributes)\n            LocationTagged<string> name = nameSymbols.GetContent(Span.Start);\n            bool attributeCanBeConditional = !name.Value.StartsWith(\"data-\", StringComparison.OrdinalIgnoreCase);\n\n            // Accept the whitespace and name\n            Accept(whitespace);\n            Accept(nameSymbols);\n            Assert(HtmlSymbolType.Equals); // We should be at \"=\"\n            AcceptAndMoveNext();\n            HtmlSymbolType quote = HtmlSymbolType.Unknown;\n            if (At(HtmlSymbolType.SingleQuote) || At(HtmlSymbolType.DoubleQuote))\n            {\n                quote = CurrentSymbol.Type;\n                AcceptAndMoveNext();\n            }\n\n            // We now have the prefix: (i.e. '      foo=\"')\n            LocationTagged<string> prefix = Span.GetContent();\n\n            if (attributeCanBeConditional)\n            {\n                Span.CodeGenerator = SpanCodeGenerator.Null; // The block code generator will render the prefix\n                Output(SpanKind.Markup);\n\n                // Read the values\n                while (!EndOfFile && !IsEndOfAttributeValue(quote, CurrentSymbol))\n                {\n                    AttributeValue(quote);\n                }\n\n                // Capture the suffix\n                LocationTagged<string> suffix = new LocationTagged<string>(String.Empty, CurrentLocation);\n                if (quote != HtmlSymbolType.Unknown && At(quote))\n                {\n                    suffix = CurrentSymbol.GetContent();\n                    AcceptAndMoveNext();\n                }\n\n                if (Span.Symbols.Count > 0)\n                {\n                    Span.CodeGenerator = SpanCodeGenerator.Null; // Again, block code generator will render the suffix\n                    Output(SpanKind.Markup);\n                }\n\n                // Create the block code generator\n                Context.CurrentBlock.CodeGenerator = new AttributeBlockCodeGenerator(\n                    name, prefix, suffix);\n            }\n            else\n            {\n                // Not a \"conditional\" attribute, so just read the value\n                SkipToAndParseCode(sym => IsEndOfAttributeValue(quote, sym));\n                if (quote != HtmlSymbolType.Unknown)\n                {\n                    Optional(quote);\n                }\n                Output(SpanKind.Markup);\n            }\n        }\n\n        private void AttributeValue(HtmlSymbolType quote)\n        {\n            SourceLocation prefixStart = CurrentLocation;\n            var prefix = ReadWhile(sym => sym.Type == HtmlSymbolType.WhiteSpace || sym.Type == HtmlSymbolType.NewLine);\n            Accept(prefix);\n\n            if (At(HtmlSymbolType.Transition))\n            {\n                SourceLocation valueStart = CurrentLocation;\n                PutCurrentBack();\n\n                // Output the prefix but as a null-span. DynamicAttributeBlockCodeGenerator will render it\n                Span.CodeGenerator = SpanCodeGenerator.Null;\n\n                // Dynamic value, start a new block and set the code generator\n                using (Context.StartBlock(BlockType.Markup))\n                {\n                    Context.CurrentBlock.CodeGenerator = new DynamicAttributeBlockCodeGenerator(prefix.GetContent(prefixStart), valueStart);\n\n                    OtherParserBlock();\n                }\n            }\n            else if (At(HtmlSymbolType.Text) && CurrentSymbol.Content.Length > 0 && CurrentSymbol.Content[0] == '~' && NextIs(HtmlSymbolType.Solidus))\n            {\n                // Virtual Path value\n                SourceLocation valueStart = CurrentLocation;\n                VirtualPath();\n                Span.CodeGenerator = new LiteralAttributeCodeGenerator(\n                    prefix.GetContent(prefixStart),\n                    new LocationTagged<SpanCodeGenerator>(new ResolveUrlCodeGenerator(), valueStart));\n            }\n            else\n            {\n                // Literal value\n                // 'quote' should be \"Unknown\" if not quoted and symbols coming from the tokenizer should never have \"Unknown\" type.\n                var value = ReadWhile(sym =>\n                    // These three conditions find separators which break the attribute value into portions\n                                      sym.Type != HtmlSymbolType.WhiteSpace &&\n                                      sym.Type != HtmlSymbolType.NewLine &&\n                                      sym.Type != HtmlSymbolType.Transition &&\n                                          // This condition checks for the end of the attribute value (it repeats some of the checks above but for now that's ok)\n                                      !IsEndOfAttributeValue(quote, sym));\n                Accept(value);\n                Span.CodeGenerator = new LiteralAttributeCodeGenerator(prefix.GetContent(prefixStart), value.GetContent(prefixStart));\n            }\n            Output(SpanKind.Markup);\n        }\n\n        private bool IsEndOfAttributeValue(HtmlSymbolType quote, HtmlSymbol sym)\n        {\n            return EndOfFile || sym == null ||\n                   (quote != HtmlSymbolType.Unknown\n                        ? sym.Type == quote // If quoted, just wait for the quote\n                        : IsUnquotedEndOfAttributeValue(sym));\n        }\n\n        private bool IsUnquotedEndOfAttributeValue(HtmlSymbol sym)\n        {\n            // If unquoted, we have a larger set of terminating characters: \n            // http://dev.w3.org/html5/spec/tokenization.html#attribute-value-unquoted-state\n            // Also we need to detect \"/\" and \">\"\n            return sym.Type == HtmlSymbolType.DoubleQuote ||\n                   sym.Type == HtmlSymbolType.SingleQuote ||\n                   sym.Type == HtmlSymbolType.OpenAngle ||\n                   sym.Type == HtmlSymbolType.Equals ||\n                   (sym.Type == HtmlSymbolType.Solidus && NextIs(HtmlSymbolType.CloseAngle)) ||\n                   sym.Type == HtmlSymbolType.CloseAngle ||\n                   sym.Type == HtmlSymbolType.WhiteSpace ||\n                   sym.Type == HtmlSymbolType.NewLine;\n        }\n\n        private void VirtualPath()\n        {\n            Assert(HtmlSymbolType.Text);\n            Debug.Assert(CurrentSymbol.Content.Length > 0 && CurrentSymbol.Content[0] == '~');\n\n            // Parse until a transition symbol, whitespace, newline or quote. We support only a fairly minimal subset of Virtual Paths\n            AcceptUntil(HtmlSymbolType.Transition, HtmlSymbolType.WhiteSpace, HtmlSymbolType.NewLine, HtmlSymbolType.SingleQuote, HtmlSymbolType.DoubleQuote);\n\n            // Output a Virtual Path span\n            Span.EditHandler.EditorHints = EditorHints.VirtualPath;\n        }\n\n        private void RecoverToEndOfTag()\n        {\n            // Accept until \">\", \"/\" or \"<\", but parse code\n            while (!EndOfFile)\n            {\n                SkipToAndParseCode(IsTagRecoveryStopPoint);\n                if (!EndOfFile)\n                {\n                    EnsureCurrent();\n                    switch (CurrentSymbol.Type)\n                    {\n                        case HtmlSymbolType.SingleQuote:\n                        case HtmlSymbolType.DoubleQuote:\n                            ParseQuoted();\n                            break;\n                        case HtmlSymbolType.OpenAngle:\n                        // Another \"<\" means this tag is invalid.\n                        case HtmlSymbolType.Solidus:\n                        // Empty tag\n                        case HtmlSymbolType.CloseAngle:\n                            // End of tag\n                            return;\n                        default:\n                            AcceptAndMoveNext();\n                            break;\n                    }\n                }\n            }\n        }\n\n        private void ParseQuoted()\n        {\n            HtmlSymbolType type = CurrentSymbol.Type;\n            AcceptAndMoveNext();\n            ParseQuoted(type);\n        }\n\n        private void ParseQuoted(HtmlSymbolType type)\n        {\n            SkipToAndParseCode(type);\n            if (!EndOfFile)\n            {\n                Assert(type);\n                AcceptAndMoveNext();\n            }\n        }\n\n        private bool StartTag(Stack<Tuple<HtmlSymbol, SourceLocation>> tags)\n        {\n            // If we're at text, it's the name, otherwise the name is \"\"\n            HtmlSymbol tagName;\n            if (At(HtmlSymbolType.Text))\n            {\n                tagName = CurrentSymbol;\n            }\n            else\n            {\n                tagName = new HtmlSymbol(CurrentLocation, String.Empty, HtmlSymbolType.Unknown);\n            }\n\n            Tuple<HtmlSymbol, SourceLocation> tag = Tuple.Create(tagName, _lastTagStart);\n\n            if (tags.Count == 0 && String.Equals(tag.Item1.Content, SyntaxConstants.TextTagName, StringComparison.OrdinalIgnoreCase))\n            {\n                Output(SpanKind.Markup);\n                Span.CodeGenerator = SpanCodeGenerator.Null;\n\n                Accept(_bufferedOpenAngle);\n                Assert(HtmlSymbolType.Text);\n\n                AcceptAndMoveNext();\n\n                int bookmark = CurrentLocation.AbsoluteIndex;\n                IEnumerable<HtmlSymbol> tokens = ReadWhile(IsSpacingToken(includeNewLines: true));\n                bool empty = At(HtmlSymbolType.Solidus);\n                if (empty)\n                {\n                    Accept(tokens);\n                    Assert(HtmlSymbolType.Solidus);\n                    AcceptAndMoveNext();\n                    bookmark = CurrentLocation.AbsoluteIndex;\n                    tokens = ReadWhile(IsSpacingToken(includeNewLines: true));\n                }\n\n                if (!Optional(HtmlSymbolType.CloseAngle))\n                {\n                    Context.Source.Position = bookmark;\n                    NextToken();\n                    Context.OnError(tag.Item2, RazorResources.ParseError_TextTagCannotContainAttributes);\n                }\n                else\n                {\n                    Accept(tokens);\n                    Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n                }\n\n                if (!empty)\n                {\n                    tags.Push(tag);\n                }\n                Output(SpanKind.Transition);\n                return true;\n            }\n            Accept(_bufferedOpenAngle);\n            Optional(HtmlSymbolType.Text);\n            return RestOfTag(tag, tags);\n        }\n\n        private bool RestOfTag(Tuple<HtmlSymbol, SourceLocation> tag, Stack<Tuple<HtmlSymbol, SourceLocation>> tags)\n        {\n            TagContent();\n\n            // We are now at a possible end of the tag\n            // Found '<', so we just abort this tag.\n            if (At(HtmlSymbolType.OpenAngle))\n            {\n                return false;\n            }\n\n            bool isEmpty = At(HtmlSymbolType.Solidus);\n            // Found a solidus, so don't accept it but DON'T push the tag to the stack\n            if (isEmpty)\n            {\n                AcceptAndMoveNext();\n            }\n\n            // Check for the '>' to determine if the tag is finished\n            bool seenClose = Optional(HtmlSymbolType.CloseAngle);\n            if (!seenClose)\n            {\n                Context.OnError(tag.Item2, RazorResources.ParseError_UnfinishedTag, tag.Item1.Content);\n            }\n            else\n            {\n                if (!isEmpty)\n                {\n                    // Is this a void element?\n                    string tagName = tag.Item1.Content.Trim();\n                    if (VoidElements.Contains(tagName))\n                    {\n                        // Technically, void elements like \"meta\" are not allowed to have end tags. Just in case they do,\n                        // we need to look ahead at the next set of tokens. If we see \"<\", \"/\", tag name, accept it and the \">\" following it\n                        // Place a bookmark\n                        int bookmark = CurrentLocation.AbsoluteIndex;\n\n                        // Skip whitespace\n                        IEnumerable<HtmlSymbol> ws = ReadWhile(IsSpacingToken(includeNewLines: true));\n\n                        // Open Angle\n                        if (At(HtmlSymbolType.OpenAngle) && NextIs(HtmlSymbolType.Solidus))\n                        {\n                            HtmlSymbol openAngle = CurrentSymbol;\n                            NextToken();\n                            Assert(HtmlSymbolType.Solidus);\n                            HtmlSymbol solidus = CurrentSymbol;\n                            NextToken();\n                            if (At(HtmlSymbolType.Text) && String.Equals(CurrentSymbol.Content, tagName, StringComparison.OrdinalIgnoreCase))\n                            {\n                                // Accept up to here\n                                Accept(ws);\n                                Accept(openAngle);\n                                Accept(solidus);\n                                AcceptAndMoveNext();\n\n                                // Accept to '>', '<' or EOF\n                                AcceptUntil(HtmlSymbolType.CloseAngle, HtmlSymbolType.OpenAngle);\n                                // Accept the '>' if we saw it. And if we do see it, we're complete\n                                return Optional(HtmlSymbolType.CloseAngle);\n                            } // At(HtmlSymbolType.Text) && String.Equals(CurrentSymbol.Content, tagName, StringComparison.OrdinalIgnoreCase)\n                        } // At(HtmlSymbolType.OpenAngle) && NextIs(HtmlSymbolType.Solidus)\n\n                        // Go back to the bookmark and just finish this tag at the close angle\n                        Context.Source.Position = bookmark;\n                        NextToken();\n                    }\n                    else if (String.Equals(tagName, \"script\", StringComparison.OrdinalIgnoreCase))\n                    {\n                        SkipToEndScriptAndParseCode();\n                    }\n                    else\n                    {\n                        // Push the tag on to the stack\n                        tags.Push(tag);\n                    }\n                }\n            }\n            return seenClose;\n        }\n\n        private void SkipToEndScriptAndParseCode()\n        {\n            // Special case for <script>: Skip to end of script tag and parse code\n            bool seenEndScript = false;\n            while (!seenEndScript && !EndOfFile)\n            {\n                SkipToAndParseCode(HtmlSymbolType.OpenAngle);\n                SourceLocation tagStart = CurrentLocation;\n                AcceptAndMoveNext();\n                AcceptWhile(HtmlSymbolType.WhiteSpace);\n                if (Optional(HtmlSymbolType.Solidus))\n                {\n                    AcceptWhile(HtmlSymbolType.WhiteSpace);\n                    if (At(HtmlSymbolType.Text) && String.Equals(CurrentSymbol.Content, \"script\", StringComparison.OrdinalIgnoreCase))\n                    {\n                        // </script!\n                        SkipToAndParseCode(HtmlSymbolType.CloseAngle);\n                        if (!Optional(HtmlSymbolType.CloseAngle))\n                        {\n                            Context.OnError(tagStart, RazorResources.ParseError_UnfinishedTag, \"script\");\n                        }\n                        seenEndScript = true;\n                    }\n                }\n            }\n        }\n\n        private bool AcceptUntilAll(params HtmlSymbolType[] endSequence)\n        {\n            while (!EndOfFile)\n            {\n                SkipToAndParseCode(endSequence[0]);\n                if (AcceptAll(endSequence))\n                {\n                    return true;\n                }\n            }\n            Debug.Assert(EndOfFile);\n            Span.EditHandler.AcceptedCharacters = AcceptedCharacters.Any;\n            return false;\n        }\n\n        private bool RemoveTag(Stack<Tuple<HtmlSymbol, SourceLocation>> tags, string tagName, SourceLocation tagStart)\n        {\n            Tuple<HtmlSymbol, SourceLocation> currentTag = null;\n            while (tags.Count > 0)\n            {\n                currentTag = tags.Pop();\n                if (String.Equals(tagName, currentTag.Item1.Content, StringComparison.OrdinalIgnoreCase))\n                {\n                    // Matched the tag\n                    return true;\n                }\n            }\n            if (currentTag != null)\n            {\n                Context.OnError(currentTag.Item2, RazorResources.ParseError_MissingEndTag, currentTag.Item1.Content);\n            }\n            else\n            {\n                Context.OnError(tagStart, RazorResources.ParseError_UnexpectedEndTag, tagName);\n            }\n            return false;\n        }\n\n        private void EndTagBlock(Stack<Tuple<HtmlSymbol, SourceLocation>> tags, bool complete)\n        {\n            if (tags.Count > 0)\n            {\n                // Ended because of EOF, not matching close tag.  Throw error for last tag\n                while (tags.Count > 1)\n                {\n                    tags.Pop();\n                }\n                Tuple<HtmlSymbol, SourceLocation> tag = tags.Pop();\n                Context.OnError(tag.Item2, RazorResources.ParseError_MissingEndTag, tag.Item1.Content);\n            }\n            else if (complete)\n            {\n                Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n            }\n            tags.Clear();\n            if (!Context.DesignTimeMode)\n            {\n                AcceptWhile(HtmlSymbolType.WhiteSpace);\n                if (!EndOfFile && CurrentSymbol.Type == HtmlSymbolType.NewLine)\n                {\n                    AcceptAndMoveNext();\n                }\n            }\n            else if (Span.EditHandler.AcceptedCharacters == AcceptedCharacters.Any)\n            {\n                AcceptWhile(HtmlSymbolType.WhiteSpace);\n                Optional(HtmlSymbolType.NewLine);\n            }\n            PutCurrentBack();\n\n            if (!complete)\n            {\n                AddMarkerSymbolIfNecessary();\n            }\n            Output(SpanKind.Markup);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/HtmlMarkupParser.Document.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Parser\n{\n    public partial class HtmlMarkupParser\n    {\n        public override void ParseDocument()\n        {\n            if (Context == null)\n            {\n                throw new InvalidOperationException(RazorResources.Parser_Context_Not_Set);\n            }\n\n            using (PushSpanConfig(DefaultMarkupSpan))\n            {\n                using (Context.StartBlock(BlockType.Markup))\n                {\n                    NextToken();\n                    while (!EndOfFile)\n                    {\n                        SkipToAndParseCode(HtmlSymbolType.OpenAngle);\n                        ScanTagInDocumentContext();\n                    }\n                    AddMarkerSymbolIfNecessary();\n                    Output(SpanKind.Markup);\n                }\n            }\n        }\n\n        /// <summary>\n        /// Reads the content of a tag (if present) in the MarkupDocument (or MarkupSection) context,\n        /// where we don't care about maintaining a stack of tags.\n        /// </summary>\n        /// <returns>A boolean indicating if we scanned at least one tag.</returns>\n        private bool ScanTagInDocumentContext()\n        {\n            if (Optional(HtmlSymbolType.OpenAngle))\n            {\n                if (At(HtmlSymbolType.Bang))\n                {\n                    BangTag();\n                    return true;\n                }\n                else if (At(HtmlSymbolType.QuestionMark))\n                {\n                    XmlPI();\n                    return true;\n                }\n                else if (!At(HtmlSymbolType.Solidus))\n                {\n                    bool scriptTag = At(HtmlSymbolType.Text) &&\n                                     String.Equals(CurrentSymbol.Content, \"script\", StringComparison.OrdinalIgnoreCase);\n                    Optional(HtmlSymbolType.Text);\n                    TagContent(); // Parse the tag, don't care about the content\n                    Optional(HtmlSymbolType.Solidus);\n                    Optional(HtmlSymbolType.CloseAngle);\n                    if (scriptTag)\n                    {\n                        SkipToEndScriptAndParseCode();\n                    }\n                    return true;\n                }\n            }\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/HtmlMarkupParser.Section.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Parser\n{\n    public partial class HtmlMarkupParser\n    {\n        private bool CaseSensitive { get; set; }\n\n        private StringComparison Comparison\n        {\n            get { return CaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; }\n        }\n\n        public override void ParseSection(Tuple<string, string> nestingSequences, bool caseSensitive)\n        {\n            if (Context == null)\n            {\n                throw new InvalidOperationException(RazorResources.Parser_Context_Not_Set);\n            }\n\n            using (PushSpanConfig(DefaultMarkupSpan))\n            {\n                using (Context.StartBlock(BlockType.Markup))\n                {\n                    NextToken();\n                    CaseSensitive = caseSensitive;\n                    if (nestingSequences.Item1 == null)\n                    {\n                        NonNestingSection(nestingSequences.Item2.Split());\n                    }\n                    else\n                    {\n                        NestingSection(nestingSequences);\n                    }\n                    AddMarkerSymbolIfNecessary();\n                    Output(SpanKind.Markup);\n                }\n            }\n        }\n\n        private void NonNestingSection(string[] nestingSequenceComponents)\n        {\n            do\n            {\n                SkipToAndParseCode(sym => sym.Type == HtmlSymbolType.OpenAngle || AtEnd(nestingSequenceComponents));\n                ScanTagInDocumentContext();\n                if (!EndOfFile && AtEnd(nestingSequenceComponents))\n                {\n                    break;\n                }\n            }\n            while (!EndOfFile);\n\n            PutCurrentBack();\n        }\n\n        private void NestingSection(Tuple<string, string> nestingSequences)\n        {\n            int nesting = 1;\n            while (nesting > 0 && !EndOfFile)\n            {\n                SkipToAndParseCode(sym =>\n                    sym.Type == HtmlSymbolType.Text ||\n                    sym.Type == HtmlSymbolType.OpenAngle);\n                if (At(HtmlSymbolType.Text))\n                {\n                    nesting += ProcessTextToken(nestingSequences, nesting);\n                    if (CurrentSymbol != null)\n                    {\n                        AcceptAndMoveNext();\n                    }\n                    else if (nesting > 0)\n                    {\n                        NextToken();\n                    }\n                }\n                else\n                {\n                    ScanTagInDocumentContext();\n                }\n            }\n        }\n\n        private bool AtEnd(string[] nestingSequenceComponents)\n        {\n            EnsureCurrent();\n            if (String.Equals(CurrentSymbol.Content, nestingSequenceComponents[0], Comparison))\n            {\n                int bookmark = CurrentSymbol.Start.AbsoluteIndex;\n                try\n                {\n                    foreach (string component in nestingSequenceComponents)\n                    {\n                        if (!EndOfFile && !String.Equals(CurrentSymbol.Content, component, Comparison))\n                        {\n                            return false;\n                        }\n                        NextToken();\n                        while (!EndOfFile && IsSpacingToken(includeNewLines: true)(CurrentSymbol))\n                        {\n                            NextToken();\n                        }\n                    }\n                    return true;\n                }\n                finally\n                {\n                    Context.Source.Position = bookmark;\n                    NextToken();\n                }\n            }\n            return false;\n        }\n\n        private int ProcessTextToken(Tuple<string, string> nestingSequences, int currentNesting)\n        {\n            for (int i = 0; i < CurrentSymbol.Content.Length; i++)\n            {\n                int nestingDelta = HandleNestingSequence(nestingSequences.Item1, i, currentNesting, 1);\n                if (nestingDelta == 0)\n                {\n                    nestingDelta = HandleNestingSequence(nestingSequences.Item2, i, currentNesting, -1);\n                }\n\n                if (nestingDelta != 0)\n                {\n                    return nestingDelta;\n                }\n            }\n            return 0;\n        }\n\n        private int HandleNestingSequence(string sequence, int position, int currentNesting, int retIfMatched)\n        {\n            if (sequence != null &&\n                CurrentSymbol.Content[position] == sequence[0] &&\n                position + sequence.Length <= CurrentSymbol.Content.Length)\n            {\n                string possibleStart = CurrentSymbol.Content.Substring(position, sequence.Length);\n                if (String.Equals(possibleStart, sequence, Comparison))\n                {\n                    // Capture the current symbol and \"put it back\" (really we just want to clear CurrentSymbol)\n                    int bookmark = Context.Source.Position;\n                    HtmlSymbol sym = CurrentSymbol;\n                    PutCurrentBack();\n\n                    // Carve up the symbol\n                    Tuple<HtmlSymbol, HtmlSymbol> pair = Language.SplitSymbol(sym, position, HtmlSymbolType.Text);\n                    HtmlSymbol preSequence = pair.Item1;\n                    Debug.Assert(pair.Item2 != null);\n                    pair = Language.SplitSymbol(pair.Item2, sequence.Length, HtmlSymbolType.Text);\n                    HtmlSymbol sequenceToken = pair.Item1;\n                    HtmlSymbol postSequence = pair.Item2;\n\n                    // Accept the first chunk (up to the nesting sequence we just saw)\n                    if (!String.IsNullOrEmpty(preSequence.Content))\n                    {\n                        Accept(preSequence);\n                    }\n\n                    if (currentNesting + retIfMatched == 0)\n                    {\n                        // This is 'popping' the final entry on the stack of nesting sequences\n                        // A caller higher in the parsing stack will accept the sequence token, so advance\n                        // to it\n                        Context.Source.Position = sequenceToken.Start.AbsoluteIndex;\n                    }\n                    else\n                    {\n                        // This isn't the end of the last nesting sequence, accept the token and keep going\n                        Accept(sequenceToken);\n\n                        // Position at the start of the postSequence symbol\n                        if (postSequence != null)\n                        {\n                            Context.Source.Position = postSequence.Start.AbsoluteIndex;\n                        }\n                        else\n                        {\n                            Context.Source.Position = bookmark;\n                        }\n                    }\n\n                    // Return the value we were asked to return if matched, since we found a nesting sequence\n                    return retIfMatched;\n                }\n            }\n            return 0;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/HtmlMarkupParser.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Parser\n{\n    public partial class HtmlMarkupParser : TokenizerBackedParser<HtmlTokenizer, HtmlSymbol, HtmlSymbolType>\n    {\n        //From http://dev.w3.org/html5/spec/Overview.html#elements-0\n        private ISet<string> _voidElements = new HashSet<string>(StringComparer.OrdinalIgnoreCase)\n        {\n            \"area\",\n            \"base\",\n            \"br\",\n            \"col\",\n            \"command\",\n            \"embed\",\n            \"hr\",\n            \"img\",\n            \"input\",\n            \"keygen\",\n            \"link\",\n            \"meta\",\n            \"param\",\n            \"source\",\n            \"track\",\n            \"wbr\"\n        };\n\n        public ISet<string> VoidElements\n        {\n            get { return _voidElements; }\n        }\n\n        protected override ParserBase OtherParser\n        {\n            get { return Context.CodeParser; }\n        }\n\n        protected override LanguageCharacteristics<HtmlTokenizer, HtmlSymbol, HtmlSymbolType> Language\n        {\n            get { return HtmlLanguageCharacteristics.Instance; }\n        }\n\n        public override void BuildSpan(SpanBuilder span, SourceLocation start, string content)\n        {\n            span.Kind = SpanKind.Markup;\n            span.CodeGenerator = new MarkupCodeGenerator();\n            base.BuildSpan(span, start, content);\n        }\n\n        protected override void OutputSpanBeforeRazorComment()\n        {\n            Output(SpanKind.Markup);\n        }\n\n        protected void SkipToAndParseCode(HtmlSymbolType type)\n        {\n            SkipToAndParseCode(sym => sym.Type == type);\n        }\n\n        protected void SkipToAndParseCode(Func<HtmlSymbol, bool> condition)\n        {\n            HtmlSymbol last = null;\n            bool startOfLine = false;\n            while (!EndOfFile && !condition(CurrentSymbol))\n            {\n                if (At(HtmlSymbolType.NewLine))\n                {\n                    if (last != null)\n                    {\n                        Accept(last);\n                    }\n\n                    // Mark the start of a new line\n                    startOfLine = true;\n                    last = null;\n                    AcceptAndMoveNext();\n                }\n                else if (At(HtmlSymbolType.Transition))\n                {\n                    HtmlSymbol transition = CurrentSymbol;\n                    NextToken();\n                    if (At(HtmlSymbolType.Transition))\n                    {\n                        if (last != null)\n                        {\n                            Accept(last);\n                            last = null;\n                        }\n                        Output(SpanKind.Markup);\n                        Accept(transition);\n                        Span.CodeGenerator = SpanCodeGenerator.Null;\n                        Output(SpanKind.Markup);\n                        AcceptAndMoveNext();\n                        continue; // while\n                    }\n                    else\n                    {\n                        if (!EndOfFile)\n                        {\n                            PutCurrentBack();\n                        }\n                        PutBack(transition);\n                    }\n\n                    // Handle whitespace rewriting\n                    if (last != null)\n                    {\n                        if (!Context.DesignTimeMode && last.Type == HtmlSymbolType.WhiteSpace && startOfLine)\n                        {\n                            // Put the whitespace back too\n                            startOfLine = false;\n                            PutBack(last);\n                            last = null;\n                        }\n                        else\n                        {\n                            // Accept last\n                            Accept(last);\n                            last = null;\n                        }\n                    }\n\n                    OtherParserBlock();\n                }\n                else if (At(HtmlSymbolType.RazorCommentTransition))\n                {\n                    if (last != null)\n                    {\n                        Accept(last);\n                        last = null;\n                    }\n                    AddMarkerSymbolIfNecessary();\n                    Output(SpanKind.Markup);\n                    RazorComment();\n                }\n                else\n                {\n                    // As long as we see whitespace, we're still at the \"start\" of the line\n                    startOfLine &= At(HtmlSymbolType.WhiteSpace);\n\n                    // If there's a last token, accept it\n                    if (last != null)\n                    {\n                        Accept(last);\n                        last = null;\n                    }\n\n                    // Advance\n                    last = CurrentSymbol;\n                    NextToken();\n                }\n            }\n\n            if (last != null)\n            {\n                Accept(last);\n            }\n        }\n\n        protected static Func<HtmlSymbol, bool> IsSpacingToken(bool includeNewLines)\n        {\n            return sym => sym.Type == HtmlSymbolType.WhiteSpace || (includeNewLines && sym.Type == HtmlSymbolType.NewLine);\n        }\n\n        private void OtherParserBlock()\n        {\n            AddMarkerSymbolIfNecessary();\n            Output(SpanKind.Markup);\n            using (PushSpanConfig())\n            {\n                Context.SwitchActiveParser();\n                Context.CodeParser.ParseBlock();\n                Context.SwitchActiveParser();\n            }\n            Initialize(Span);\n            NextToken();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/ISyntaxTreeRewriter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.Razor.Parser\n{\n    internal interface ISyntaxTreeRewriter\n    {\n        Block Rewrite(Block input);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/LanguageCharacteristics.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Parser\n{\n    [SuppressMessage(\"Microsoft.Design\", \"CA1005:AvoidExcessiveParametersOnGenericTypes\", Justification = \"All generic type parameters are required\")]\n    public abstract class LanguageCharacteristics<TTokenizer, TSymbol, TSymbolType>\n        where TTokenizer : Tokenizer<TSymbol, TSymbolType>\n        where TSymbol : SymbolBase<TSymbolType>\n    {\n        public abstract string GetSample(TSymbolType type);\n        public abstract TTokenizer CreateTokenizer(ITextDocument source);\n        public abstract TSymbolType FlipBracket(TSymbolType bracket);\n        public abstract TSymbol CreateMarkerSymbol(SourceLocation location);\n\n        public virtual IEnumerable<TSymbol> TokenizeString(string content)\n        {\n            return TokenizeString(SourceLocation.Zero, content);\n        }\n\n        public virtual IEnumerable<TSymbol> TokenizeString(SourceLocation start, string input)\n        {\n            using (SeekableTextReader reader = new SeekableTextReader(input))\n            {\n                TTokenizer tok = CreateTokenizer(reader);\n                TSymbol sym;\n                while ((sym = tok.NextSymbol()) != null)\n                {\n                    sym.OffsetStart(start);\n                    yield return sym;\n                }\n            }\n        }\n\n        public virtual bool IsWhiteSpace(TSymbol symbol)\n        {\n            return IsKnownSymbolType(symbol, KnownSymbolType.WhiteSpace);\n        }\n\n        public virtual bool IsNewLine(TSymbol symbol)\n        {\n            return IsKnownSymbolType(symbol, KnownSymbolType.NewLine);\n        }\n\n        public virtual bool IsIdentifier(TSymbol symbol)\n        {\n            return IsKnownSymbolType(symbol, KnownSymbolType.Identifier);\n        }\n\n        public virtual bool IsKeyword(TSymbol symbol)\n        {\n            return IsKnownSymbolType(symbol, KnownSymbolType.Keyword);\n        }\n\n        public virtual bool IsTransition(TSymbol symbol)\n        {\n            return IsKnownSymbolType(symbol, KnownSymbolType.Transition);\n        }\n\n        public virtual bool IsCommentStart(TSymbol symbol)\n        {\n            return IsKnownSymbolType(symbol, KnownSymbolType.CommentStart);\n        }\n\n        public virtual bool IsCommentStar(TSymbol symbol)\n        {\n            return IsKnownSymbolType(symbol, KnownSymbolType.CommentStar);\n        }\n\n        public virtual bool IsCommentBody(TSymbol symbol)\n        {\n            return IsKnownSymbolType(symbol, KnownSymbolType.CommentBody);\n        }\n\n        public virtual bool IsUnknown(TSymbol symbol)\n        {\n            return IsKnownSymbolType(symbol, KnownSymbolType.Unknown);\n        }\n\n        public virtual bool IsKnownSymbolType(TSymbol symbol, KnownSymbolType type)\n        {\n            return symbol != null && Equals(symbol.Type, GetKnownSymbolType(type));\n        }\n\n        public virtual Tuple<TSymbol, TSymbol> SplitSymbol(TSymbol symbol, int splitAt, TSymbolType leftType)\n        {\n            TSymbol left = CreateSymbol(symbol.Start, symbol.Content.Substring(0, splitAt), leftType, Enumerable.Empty<RazorError>());\n            TSymbol right = null;\n            if (splitAt < symbol.Content.Length)\n            {\n                right = CreateSymbol(SourceLocationTracker.CalculateNewLocation(symbol.Start, left.Content), symbol.Content.Substring(splitAt), symbol.Type, symbol.Errors);\n            }\n            return Tuple.Create(left, right);\n        }\n\n        public abstract TSymbolType GetKnownSymbolType(KnownSymbolType type);\n\n        public virtual bool KnowsSymbolType(KnownSymbolType type)\n        {\n            return type == KnownSymbolType.Unknown || !Equals(GetKnownSymbolType(type), GetKnownSymbolType(KnownSymbolType.Unknown));\n        }\n\n        protected abstract TSymbol CreateSymbol(SourceLocation location, string content, TSymbolType type, IEnumerable<RazorError> errors);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/MarkupCollapser.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Text;\n\nnamespace System.Web.Razor.Parser\n{\n    internal class MarkupCollapser : MarkupRewriter\n    {\n        public MarkupCollapser(Action<SpanBuilder, SourceLocation, string> markupSpanFactory) : base(markupSpanFactory)\n        {\n        }\n\n        protected override bool CanRewrite(Span span)\n        {\n            return span.Kind == SpanKind.Markup && span.CodeGenerator is MarkupCodeGenerator;\n        }\n\n        protected override SyntaxTreeNode RewriteSpan(BlockBuilder parent, Span span)\n        {\n            // Only rewrite if we have a previous that is also markup (CanRewrite does this check for us!)\n            Span previous = parent.Children.LastOrDefault() as Span;\n            if (previous == null || !CanRewrite(previous))\n            {\n                return span;\n            }\n\n            // Merge spans\n            parent.Children.Remove(previous);\n            SpanBuilder merged = new SpanBuilder();\n            FillSpan(merged, previous.Start, previous.Content + span.Content);\n            return merged.Build();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/MarkupRewriter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Text;\n\nnamespace System.Web.Razor.Parser\n{\n    internal abstract class MarkupRewriter : ParserVisitor, ISyntaxTreeRewriter\n    {\n        private Stack<BlockBuilder> _blocks = new Stack<BlockBuilder>();\n        private Action<SpanBuilder, SourceLocation, string> _markupSpanFactory;\n\n        protected MarkupRewriter(Action<SpanBuilder, SourceLocation, string> markupSpanFactory)\n        {\n            if (markupSpanFactory == null)\n            {\n                throw new ArgumentNullException(\"markupSpanFactory\");\n            }\n            _markupSpanFactory = markupSpanFactory;\n        }\n\n        protected BlockBuilder Parent\n        {\n            get { return _blocks.Count > 0 ? _blocks.Peek() : null; }\n        }\n\n        public virtual Block Rewrite(Block input)\n        {\n            input.Accept(this);\n            Debug.Assert(_blocks.Count == 1);\n            return _blocks.Pop().Build();\n        }\n\n        public override void VisitBlock(Block block)\n        {\n            if (CanRewrite(block))\n            {\n                SyntaxTreeNode newNode = RewriteBlock(_blocks.Peek(), block);\n                if (newNode != null)\n                {\n                    _blocks.Peek().Children.Add(newNode);\n                }\n            }\n            else\n            {\n                // Not rewritable.\n                BlockBuilder builder = new BlockBuilder(block);\n                builder.Children.Clear();\n                _blocks.Push(builder);\n                base.VisitBlock(block);\n                Debug.Assert(ReferenceEquals(builder, _blocks.Peek()));\n\n                if (_blocks.Count > 1)\n                {\n                    _blocks.Pop();\n                    _blocks.Peek().Children.Add(builder.Build());\n                }\n            }\n        }\n\n        public override void VisitSpan(Span span)\n        {\n            if (CanRewrite(span))\n            {\n                SyntaxTreeNode newNode = RewriteSpan(_blocks.Peek(), span);\n                if (newNode != null)\n                {\n                    _blocks.Peek().Children.Add(newNode);\n                }\n            }\n            else\n            {\n                _blocks.Peek().Children.Add(span);\n            }\n        }\n\n        protected virtual bool CanRewrite(Block block)\n        {\n            return false;\n        }\n\n        protected virtual bool CanRewrite(Span span)\n        {\n            return false;\n        }\n\n        protected virtual SyntaxTreeNode RewriteBlock(BlockBuilder parent, Block block)\n        {\n            throw new NotImplementedException();\n        }\n\n        protected virtual SyntaxTreeNode RewriteSpan(BlockBuilder parent, Span span)\n        {\n            throw new NotImplementedException();\n        }\n\n        protected void FillSpan(SpanBuilder builder, SourceLocation start, string content)\n        {\n            _markupSpanFactory(builder, start, content);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/ParserBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Text;\n\nnamespace System.Web.Razor.Parser\n{\n    public abstract class ParserBase\n    {\n        private ParserContext _context;\n\n        public virtual ParserContext Context\n        {\n            get { return _context; }\n            set\n            {\n                Debug.Assert(_context == null, \"Context has already been set for this parser!\");\n                _context = value;\n                _context.AssertOnOwnerTask();\n            }\n        }\n\n        public virtual bool IsMarkupParser\n        {\n            get { return false; }\n        }\n\n        protected abstract ParserBase OtherParser { get; }\n\n        public abstract void BuildSpan(SpanBuilder span, SourceLocation start, string content);\n\n        public abstract void ParseBlock();\n\n        // Markup Parsers need the ParseDocument and ParseSection methods since the markup parser is the first parser to hit the document \n        // and the logic may be different than the ParseBlock method.\n        public virtual void ParseDocument()\n        {\n            Debug.Assert(IsMarkupParser);\n            throw new NotSupportedException(RazorResources.ParserIsNotAMarkupParser);\n        }\n\n        public virtual void ParseSection(Tuple<string, string> nestingSequences, bool caseSensitive)\n        {\n            Debug.Assert(IsMarkupParser);\n            throw new NotSupportedException(RazorResources.ParserIsNotAMarkupParser);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/ParserContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Utils;\n\nnamespace System.Web.Razor.Parser\n{\n    public partial class ParserContext\n    {\n        private int? _ownerTaskId;\n\n        private bool _terminated = false;\n\n        private Stack<BlockBuilder> _blockStack = new Stack<BlockBuilder>();\n\n        public ParserContext(ITextDocument source, ParserBase codeParser, ParserBase markupParser, ParserBase activeParser)\n        {\n            if (source == null)\n            {\n                throw new ArgumentNullException(\"source\");\n            }\n            if (codeParser == null)\n            {\n                throw new ArgumentNullException(\"codeParser\");\n            }\n            if (markupParser == null)\n            {\n                throw new ArgumentNullException(\"markupParser\");\n            }\n            if (activeParser == null)\n            {\n                throw new ArgumentNullException(\"activeParser\");\n            }\n            if (activeParser != codeParser && activeParser != markupParser)\n            {\n                throw new ArgumentException(RazorResources.ActiveParser_Must_Be_Code_Or_Markup_Parser, \"activeParser\");\n            }\n\n            CaptureOwnerTask();\n\n            Source = new TextDocumentReader(source);\n            CodeParser = codeParser;\n            MarkupParser = markupParser;\n            ActiveParser = activeParser;\n            Errors = new List<RazorError>();\n        }\n\n        public IList<RazorError> Errors { get; private set; }\n        public TextDocumentReader Source { get; set; }\n        public ParserBase CodeParser { get; private set; }\n        public ParserBase MarkupParser { get; private set; }\n        public ParserBase ActiveParser { get; private set; }\n        public bool DesignTimeMode { get; set; }\n\n        public BlockBuilder CurrentBlock\n        {\n            get { return _blockStack.Peek(); }\n        }\n\n        public Span LastSpan { get; private set; }\n        public bool WhiteSpaceIsSignificantToAncestorBlock { get; set; }\n\n        public AcceptedCharacters LastAcceptedCharacters\n        {\n            get\n            {\n                if (LastSpan == null)\n                {\n                    return AcceptedCharacters.None;\n                }\n                return LastSpan.EditHandler.AcceptedCharacters;\n            }\n        }\n\n        internal Stack<BlockBuilder> BlockStack\n        {\n            get { return _blockStack; }\n        }\n\n        public char CurrentCharacter\n        {\n            get\n            {\n                if (_terminated)\n                {\n                    return '\\0';\n                }\n#if DEBUG\n                if (CheckInfiniteLoop())\n                {\n                    return '\\0';\n                }\n#endif\n                int ch = Source.Peek();\n                if (ch == -1)\n                {\n                    return '\\0';\n                }\n                return (char)ch;\n            }\n        }\n\n        public bool EndOfFile\n        {\n            get { return _terminated || Source.Peek() == -1; }\n        }\n\n        public void AddSpan(Span span)\n        {\n            EnusreNotTerminated();\n            if (_blockStack.Count == 0)\n            {\n                throw new InvalidOperationException(RazorResources.ParserContext_NoCurrentBlock);\n            }\n            _blockStack.Peek().Children.Add(span);\n            LastSpan = span;\n        }\n\n        /// <summary>\n        /// Starts a block of the specified type\n        /// </summary>\n        /// <param name=\"blockType\">The type of the block to start</param>\n        public IDisposable StartBlock(BlockType blockType)\n        {\n            EnusreNotTerminated();\n            AssertOnOwnerTask();\n            _blockStack.Push(new BlockBuilder() { Type = blockType });\n            return new DisposableAction(EndBlock);\n        }\n\n        /// <summary>\n        /// Starts a block\n        /// </summary>\n        public IDisposable StartBlock()\n        {\n            EnusreNotTerminated();\n            AssertOnOwnerTask();\n            _blockStack.Push(new BlockBuilder());\n            return new DisposableAction(EndBlock);\n        }\n\n        /// <summary>\n        /// Ends the current block\n        /// </summary>\n        public void EndBlock()\n        {\n            EnusreNotTerminated();\n            AssertOnOwnerTask();\n\n            if (_blockStack.Count == 0)\n            {\n                throw new InvalidOperationException(RazorResources.EndBlock_Called_Without_Matching_StartBlock);\n            }\n            if (_blockStack.Count > 1)\n            {\n                BlockBuilder block = _blockStack.Pop();\n                _blockStack.Peek().Children.Add(block.Build());\n            }\n            else\n            {\n                // If we're at 1, terminate the parser\n                _terminated = true;\n            }\n        }\n\n        /// <summary>\n        /// Gets a boolean indicating if any of the ancestors of the current block is of the specified type\n        /// </summary>\n        public bool IsWithin(BlockType type)\n        {\n            return _blockStack.Any(b => b.Type == type);\n        }\n\n        public void SwitchActiveParser()\n        {\n            EnusreNotTerminated();\n            AssertOnOwnerTask();\n            if (ReferenceEquals(ActiveParser, CodeParser))\n            {\n                ActiveParser = MarkupParser;\n            }\n            else\n            {\n                ActiveParser = CodeParser;\n            }\n        }\n\n        public void OnError(SourceLocation location, string message)\n        {\n            EnusreNotTerminated();\n            AssertOnOwnerTask();\n            Errors.Add(new RazorError(message, location));\n        }\n\n        public void OnError(SourceLocation location, string message, params object[] args)\n        {\n            EnusreNotTerminated();\n            AssertOnOwnerTask();\n            OnError(location, String.Format(CultureInfo.CurrentCulture, message, args));\n        }\n\n        public ParserResults CompleteParse()\n        {\n            if (_blockStack.Count == 0)\n            {\n                throw new InvalidOperationException(RazorResources.ParserContext_CannotCompleteTree_NoRootBlock);\n            }\n            if (_blockStack.Count != 1)\n            {\n                throw new InvalidOperationException(RazorResources.ParserContext_CannotCompleteTree_OutstandingBlocks);\n            }\n            return new ParserResults(_blockStack.Pop().Build(), Errors);\n        }\n\n        [Conditional(\"DEBUG\")]\n        internal void CaptureOwnerTask()\n        {\n            if (Task.CurrentId != null)\n            {\n                _ownerTaskId = Task.CurrentId;\n            }\n        }\n\n        [Conditional(\"DEBUG\")]\n        internal void AssertOnOwnerTask()\n        {\n            if (_ownerTaskId != null)\n            {\n                Debug.Assert(_ownerTaskId == Task.CurrentId);\n            }\n        }\n\n        [Conditional(\"DEBUG\")]\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"The method body is empty in Release builds\")]\n        internal void AssertCurrent(char expected)\n        {\n            Debug.Assert(CurrentCharacter == expected);\n        }\n\n        private void EnusreNotTerminated()\n        {\n            if (_terminated)\n            {\n                throw new InvalidOperationException(RazorResources.ParserContext_ParseComplete);\n            }\n        }\n    }\n\n    // Debug Helpers\n\n#if DEBUG\n    [DebuggerDisplay(\"{Unparsed}\")]\n    public partial class ParserContext\n    {\n        private const int InfiniteLoopCountThreshold = 1000;\n        private int _infiniteLoopGuardCount = 0;\n        private SourceLocation? _infiniteLoopGuardLocation = null;\n\n        internal string Unparsed\n        {\n            get\n            {\n                string remaining = Source.ReadToEnd();\n                Source.Position -= remaining.Length;\n                return remaining;\n            }\n        }\n\n        private bool CheckInfiniteLoop()\n        {\n            // Infinite loop guard\n            //  Basically, if this property is accessed 1000 times in a row without having advanced the source reader to the next position, we\n            //  cause a parser error\n            if (_infiniteLoopGuardLocation != null)\n            {\n                if (Source.Location == _infiniteLoopGuardLocation.Value)\n                {\n                    _infiniteLoopGuardCount++;\n                    if (_infiniteLoopGuardCount > InfiniteLoopCountThreshold)\n                    {\n                        Debug.Fail(\"An internal parser error is causing an infinite loop at this location.\");\n                        _terminated = true;\n                        return true;\n                    }\n                }\n                else\n                {\n                    _infiniteLoopGuardCount = 0;\n                }\n            }\n            _infiniteLoopGuardLocation = Source.Location;\n            return false;\n        }\n    }\n#endif\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/ParserHelpers.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq;\n\nnamespace System.Web.Razor.Parser\n{\n    public static class ParserHelpers\n    {\n        public static bool IsNewLine(char value)\n        {\n            return value == '\\r' // Carriage return\n                   || value == '\\n' // Linefeed\n                   || value == '\\u0085' // Next Line\n                   || value == '\\u2028' // Line separator\n                   || value == '\\u2029'; // Paragraph separator\n        }\n\n        public static bool IsNewLine(string value)\n        {\n            return (value.Length == 1 && (IsNewLine(value[0]))) ||\n                   (String.Equals(value, \"\\r\\n\", StringComparison.Ordinal));\n        }\n\n        // Returns true if the character is Whitespace and NOT a newline\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1702:CompoundWordsShouldBeCasedCorrectly\", MessageId = \"Whitespace\", Justification = \"This would be a breaking change in a shipping API\")]\n        public static bool IsWhitespace(char value)\n        {\n            return value == ' ' ||\n                   value == '\\f' ||\n                   value == '\\t' ||\n                   value == '\\u000B' || // Vertical Tab\n                   Char.GetUnicodeCategory(value) == UnicodeCategory.SpaceSeparator;\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1702:CompoundWordsShouldBeCasedCorrectly\", MessageId = \"Whitespace\", Justification = \"This would be a breaking change in a shipping API\")]\n        public static bool IsWhitespaceOrNewLine(char value)\n        {\n            return IsWhitespace(value) || IsNewLine(value);\n        }\n\n        public static bool IsIdentifier(string value)\n        {\n            return IsIdentifier(value, requireIdentifierStart: true);\n        }\n\n        public static bool IsIdentifier(string value, bool requireIdentifierStart)\n        {\n            IEnumerable<char> identifierPart = value;\n            if (requireIdentifierStart)\n            {\n                identifierPart = identifierPart.Skip(1);\n            }\n            return (!requireIdentifierStart || IsIdentifierStart(value[0])) && identifierPart.All(IsIdentifierPart);\n        }\n\n        public static bool IsHexDigit(char value)\n        {\n            return (value >= '0' && value <= '9') || (value >= 'A' && value <= 'F') || (value >= 'a' && value <= 'f');\n        }\n\n        public static bool IsIdentifierStart(char value)\n        {\n            return value == '_' || IsLetter(value);\n        }\n\n        public static bool IsIdentifierPart(char value)\n        {\n            return IsLetter(value)\n                   || IsDecimalDigit(value)\n                   || IsConnecting(value)\n                   || IsCombining(value)\n                   || IsFormatting(value);\n        }\n\n        public static bool IsTerminatingCharToken(char value)\n        {\n            return IsNewLine(value) || value == '\\'';\n        }\n\n        public static bool IsTerminatingQuotedStringToken(char value)\n        {\n            return IsNewLine(value) || value == '\"';\n        }\n\n        public static bool IsDecimalDigit(char value)\n        {\n            return Char.GetUnicodeCategory(value) == UnicodeCategory.DecimalDigitNumber;\n        }\n\n        public static bool IsLetterOrDecimalDigit(char value)\n        {\n            return IsLetter(value) || IsDecimalDigit(value);\n        }\n\n        public static bool IsLetter(char value)\n        {\n            var cat = Char.GetUnicodeCategory(value);\n            return cat == UnicodeCategory.UppercaseLetter\n                   || cat == UnicodeCategory.LowercaseLetter\n                   || cat == UnicodeCategory.TitlecaseLetter\n                   || cat == UnicodeCategory.ModifierLetter\n                   || cat == UnicodeCategory.OtherLetter\n                   || cat == UnicodeCategory.LetterNumber;\n        }\n\n        public static bool IsFormatting(char value)\n        {\n            return Char.GetUnicodeCategory(value) == UnicodeCategory.Format;\n        }\n\n        public static bool IsCombining(char value)\n        {\n            var cat = Char.GetUnicodeCategory(value);\n            return cat == UnicodeCategory.SpacingCombiningMark || cat == UnicodeCategory.NonSpacingMark;\n        }\n\n        public static bool IsConnecting(char value)\n        {\n            return Char.GetUnicodeCategory(value) == UnicodeCategory.ConnectorPunctuation;\n        }\n\n        public static string SanitizeClassName(string inputName)\n        {\n            if (!IsIdentifierStart(inputName[0]) && IsIdentifierPart(inputName[0]))\n            {\n                inputName = \"_\" + inputName;\n            }\n\n            return new String((from value in inputName\n                               select IsIdentifierPart(value) ? value : '_')\n                                  .ToArray());\n        }\n\n        public static bool IsEmailPart(char character)\n        {\n            // Source: http://tools.ietf.org/html/rfc5322#section-3.4.1\n            // We restrict the allowed characters to alpha-numerics and '_' in order to ensure we cover most of the cases where an\n            // email address is intended without restricting the usage of code within JavaScript, CSS, and other contexts.\n            return Char.IsLetter(character) || Char.IsDigit(character) || character == '_';\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/ParserVisitor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.Razor.Parser\n{\n    public abstract class ParserVisitor\n    {\n        public CancellationToken? CancelToken { get; set; }\n\n        public virtual void VisitBlock(Block block)\n        {\n            VisitStartBlock(block);\n            foreach (SyntaxTreeNode node in block.Children)\n            {\n                node.Accept(this);\n            }\n            VisitEndBlock(block);\n        }\n\n        public virtual void VisitStartBlock(Block block)\n        {\n            ThrowIfCanceled();\n        }\n\n        public virtual void VisitSpan(Span span)\n        {\n            ThrowIfCanceled();\n        }\n\n        public virtual void VisitEndBlock(Block block)\n        {\n            ThrowIfCanceled();\n        }\n\n        public virtual void VisitError(RazorError err)\n        {\n            ThrowIfCanceled();\n        }\n\n        public virtual void OnComplete()\n        {\n            ThrowIfCanceled();\n        }\n\n        public virtual void ThrowIfCanceled()\n        {\n            if (CancelToken != null && CancelToken.Value.IsCancellationRequested)\n            {\n                throw new OperationCanceledException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/ParserVisitorExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.Razor.Parser\n{\n    public static class ParserVisitorExtensions\n    {\n        public static void Visit(this ParserVisitor self, ParserResults result)\n        {\n            if (self == null)\n            {\n                throw new ArgumentNullException(\"self\");\n            }\n            if (result == null)\n            {\n                throw new ArgumentNullException(\"result\");\n            }\n\n            result.Document.Accept(self);\n            foreach (RazorError error in result.ParserErrors)\n            {\n                self.VisitError(error);\n            }\n            self.OnComplete();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/RazorParser.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.IO;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Text;\n\nnamespace System.Web.Razor.Parser\n{\n    public class RazorParser\n    {\n        public RazorParser(ParserBase codeParser, ParserBase markupParser)\n        {\n            if (codeParser == null)\n            {\n                throw new ArgumentNullException(\"codeParser\");\n            }\n            if (markupParser == null)\n            {\n                throw new ArgumentNullException(\"markupParser\");\n            }\n\n            MarkupParser = markupParser;\n            CodeParser = codeParser;\n\n            Optimizers = new List<ISyntaxTreeRewriter>()\n            {\n                // Move whitespace from start of expression block to markup\n                new WhiteSpaceRewriter(MarkupParser.BuildSpan),\n                // Collapse conditional attributes where the entire value is literal\n                new ConditionalAttributeCollapser(MarkupParser.BuildSpan),\n            };\n        }\n\n        internal ParserBase CodeParser { get; private set; }\n        internal ParserBase MarkupParser { get; private set; }\n        internal IList<ISyntaxTreeRewriter> Optimizers { get; private set; }\n\n        public bool DesignTimeMode { get; set; }\n\n        public virtual void Parse(TextReader input, ParserVisitor visitor)\n        {\n            ParserResults results = ParseCore(new SeekableTextReader(input));\n\n            // Replay the results on the visitor\n            visitor.Visit(results);\n        }\n\n        public virtual ParserResults Parse(TextReader input)\n        {\n            return ParseCore(new SeekableTextReader(input));\n        }\n\n        public virtual ParserResults Parse(ITextDocument input)\n        {\n            return ParseCore(input);\n        }\n\n#pragma warning disable 0618\n        [Obsolete(\"Lookahead-based readers have been deprecated, use overrides which accept a TextReader or ITextDocument instead\")]\n        public virtual void Parse(LookaheadTextReader input, ParserVisitor visitor)\n        {\n            ParserResults results = ParseCore(new SeekableTextReader(input));\n\n            // Replay the results on the visitor\n            visitor.Visit(results);\n        }\n\n        [Obsolete(\"Lookahead-based readers have been deprecated, use overrides which accept a TextReader or ITextDocument instead\")]\n        public virtual ParserResults Parse(LookaheadTextReader input)\n        {\n            return ParseCore(new SeekableTextReader(input));\n        }\n#pragma warning restore 0618\n\n        public virtual Task CreateParseTask(TextReader input, Action<Span> spanCallback, Action<RazorError> errorCallback)\n        {\n            return CreateParseTask(input, new CallbackVisitor(spanCallback, errorCallback));\n        }\n\n        public virtual Task CreateParseTask(TextReader input, Action<Span> spanCallback, Action<RazorError> errorCallback, SynchronizationContext context)\n        {\n            return CreateParseTask(input, new CallbackVisitor(spanCallback, errorCallback) { SynchronizationContext = context });\n        }\n\n        public virtual Task CreateParseTask(TextReader input, Action<Span> spanCallback, Action<RazorError> errorCallback, CancellationToken cancelToken)\n        {\n            return CreateParseTask(input, new CallbackVisitor(spanCallback, errorCallback) { CancelToken = cancelToken });\n        }\n\n        public virtual Task CreateParseTask(TextReader input, Action<Span> spanCallback, Action<RazorError> errorCallback, SynchronizationContext context, CancellationToken cancelToken)\n        {\n            return CreateParseTask(input, new CallbackVisitor(spanCallback, errorCallback)\n            {\n                SynchronizationContext = context,\n                CancelToken = cancelToken\n            });\n        }\n\n        [SuppressMessage(\"Microsoft.Web.FxCop\", \"MW1200:DoNotConstructTaskInstances\", Justification = \"This rule is not applicable to this assembly.\")]\n        public virtual Task CreateParseTask(TextReader input,\n                                            ParserVisitor consumer)\n        {\n            return new Task(() =>\n            {\n                try\n                {\n                    Parse(input, consumer);\n                }\n                catch (OperationCanceledException)\n                {\n                    return; // Just return if we're cancelled.\n                }\n            });\n        }\n\n        private ParserResults ParseCore(ITextDocument input)\n        {\n            // Setup the parser context\n            ParserContext context = new ParserContext(input, CodeParser, MarkupParser, MarkupParser)\n            {\n                DesignTimeMode = DesignTimeMode\n            };\n\n            MarkupParser.Context = context;\n            CodeParser.Context = context;\n\n            // Execute the parse\n            MarkupParser.ParseDocument();\n\n            // Get the result\n            ParserResults results = context.CompleteParse();\n\n            // Rewrite whitespace if supported\n            Block current = results.Document;\n            foreach (ISyntaxTreeRewriter rewriter in Optimizers)\n            {\n                current = rewriter.Rewrite(current);\n            }\n\n            // Link the leaf nodes into a chain\n            Span prev = null;\n            foreach (Span node in current.Flatten())\n            {\n                node.Previous = prev;\n                if (prev != null)\n                {\n                    prev.Next = node;\n                }\n                prev = node;\n            }\n\n            // Return the new result\n            return new ParserResults(current, results.ParserErrors);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/SyntaxConstants.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.Razor.Parser\n{\n    public static class SyntaxConstants\n    {\n        public static readonly string TextTagName = \"text\";\n        public static readonly char TransitionCharacter = '@';\n        public static readonly string TransitionString = \"@\";\n        public static readonly string StartCommentSequence = \"@*\";\n        public static readonly string EndCommentSequence = \"*@\";\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1034:NestedTypesShouldNotBeVisible\", Justification = \"Class is nested to provide better organization\")]\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1724:TypeNamesShouldNotMatchNamespaces\", Justification = \"This type name should not cause a conflict\")]\n        public static class CSharp\n        {\n            public static readonly int UsingKeywordLength = 5;\n            public static readonly string InheritsKeyword = \"inherits\";\n            public static readonly string FunctionsKeyword = \"functions\";\n            public static readonly string SectionKeyword = \"section\";\n            public static readonly string HelperKeyword = \"helper\";\n            public static readonly string ElseIfKeyword = \"else if\";\n            public static readonly string NamespaceKeyword = \"namespace\";\n            public static readonly string ClassKeyword = \"class\";\n            public static readonly string LayoutKeyword = \"layout\";\n            public static readonly string SessionStateKeyword = \"sessionstate\";\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1034:NestedTypesShouldNotBeVisible\", Justification = \"Class is nested to provide better organization\")]\n        public static class VB\n        {\n            public static readonly int ImportsKeywordLength = 7;\n            public static readonly string EndKeyword = \"End\";\n            public static readonly string CodeKeyword = \"Code\";\n            public static readonly string FunctionsKeyword = \"Functions\";\n            public static readonly string SectionKeyword = \"Section\";\n            public static readonly string StrictKeyword = \"Strict\";\n            public static readonly string ExplicitKeyword = \"Explicit\";\n            public static readonly string OffKeyword = \"Off\";\n            public static readonly string HelperKeyword = \"Helper\";\n            public static readonly string SelectCaseKeyword = \"Select Case\";\n            public static readonly string LayoutKeyword = \"Layout\";\n            public static readonly string EndCodeKeyword = \"End Code\";\n            public static readonly string EndHelperKeyword = \"End Helper\";\n            public static readonly string EndFunctionsKeyword = \"End Functions\";\n            public static readonly string EndSectionKeyword = \"End Section\";\n            public static readonly string SessionStateKeyword = \"SessionState\";\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/SyntaxTree/AcceptedCharacters.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.Razor.Parser.SyntaxTree\n{\n    [Flags]\n    public enum AcceptedCharacters\n    {\n        None = 0,\n        NewLine = 1,\n        WhiteSpace = 2,\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1702:CompoundWordsShouldBeCasedCorrectly\", MessageId = \"NonWhite\", Justification = \"This is not a compound word, it is two words\")]\n        NonWhiteSpace = 4,\n\n        AllWhiteSpace = NewLine | WhiteSpace,\n        Any = AllWhiteSpace | NonWhiteSpace,\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1702:CompoundWordsShouldBeCasedCorrectly\", MessageId = \"Newline\", Justification = \"This would be a breaking change to a previous released API\")]\n        AnyExceptNewline = NonWhiteSpace | WhiteSpace\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/SyntaxTree/Block.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Text;\n\nnamespace System.Web.Razor.Parser.SyntaxTree\n{\n    public class Block : SyntaxTreeNode\n    {\n        public Block(BlockBuilder source)\n        {\n            if (source.Type == null)\n            {\n                throw new InvalidOperationException(RazorResources.Block_Type_Not_Specified);\n            }\n            Type = source.Type.Value;\n            Children = source.Children;\n            Name = source.Name;\n            CodeGenerator = source.CodeGenerator;\n            source.Reset();\n\n            foreach (SyntaxTreeNode node in Children)\n            {\n                node.Parent = this;\n            }\n        }\n\n        internal Block(BlockType type, IEnumerable<SyntaxTreeNode> contents, IBlockCodeGenerator generator)\n        {\n            Type = type;\n            CodeGenerator = generator;\n            Children = contents;\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1721:PropertyNamesShouldNotMatchGetMethods\", Justification = \"Type is the most appropriate name for this property and there is little chance of confusion with GetType\")]\n        public BlockType Type { get; private set; }\n\n        public IEnumerable<SyntaxTreeNode> Children { get; private set; }\n        public string Name { get; private set; }\n        public IBlockCodeGenerator CodeGenerator { get; private set; }\n\n        public override bool IsBlock\n        {\n            get { return true; }\n        }\n\n        public override SourceLocation Start\n        {\n            get\n            {\n                SyntaxTreeNode child = Children.FirstOrDefault();\n                if (child == null)\n                {\n                    return SourceLocation.Zero;\n                }\n                else\n                {\n                    return child.Start;\n                }\n            }\n        }\n\n        public override int Length\n        {\n            get { return Children.Sum(child => child.Length); }\n        }\n\n        public Span FindFirstDescendentSpan()\n        {\n            SyntaxTreeNode current = this;\n            while (current != null && current.IsBlock)\n            {\n                current = ((Block)current).Children.FirstOrDefault();\n            }\n            return current as Span;\n        }\n\n        public Span FindLastDescendentSpan()\n        {\n            SyntaxTreeNode current = this;\n            while (current != null && current.IsBlock)\n            {\n                current = ((Block)current).Children.LastOrDefault();\n            }\n            return current as Span;\n        }\n\n        public override void Accept(ParserVisitor visitor)\n        {\n            visitor.VisitBlock(this);\n        }\n\n        public override string ToString()\n        {\n            return String.Format(CultureInfo.CurrentCulture, \"{0} Block at {1}::{2} (Gen:{3})\", Type, Start, Length, CodeGenerator);\n        }\n\n        public override bool Equals(object obj)\n        {\n            Block other = obj as Block;\n            return other != null &&\n                   Type == other.Type &&\n                   Equals(CodeGenerator, other.CodeGenerator) &&\n                   ChildrenEqual(Children, other.Children);\n        }\n\n        public override int GetHashCode()\n        {\n            return (int)Type;\n        }\n\n        public IEnumerable<Span> Flatten()\n        {\n            // Create an enumerable that flattens the tree for use by syntax highlighters, etc.\n            foreach (SyntaxTreeNode element in Children)\n            {\n                Span span = element as Span;\n                if (span != null)\n                {\n                    yield return span;\n                }\n                else\n                {\n                    Block block = element as Block;\n                    foreach (Span childSpan in block.Flatten())\n                    {\n                        yield return childSpan;\n                    }\n                }\n            }\n        }\n\n        public Span LocateOwner(TextChange change)\n        {\n            // Ask each child recursively\n            Span owner = null;\n            foreach (SyntaxTreeNode element in Children)\n            {\n                Span span = element as Span;\n                if (span == null)\n                {\n                    owner = ((Block)element).LocateOwner(change);\n                }\n                else\n                {\n                    if (change.OldPosition < span.Start.AbsoluteIndex)\n                    {\n                        // Early escape for cases where changes overlap multiple spans\n                        // In those cases, the span will return false, and we don't want to search the whole tree\n                        // So if the current span starts after the change, we know we've searched as far as we need to\n                        break;\n                    }\n                    owner = span.EditHandler.OwnsChange(span, change) ? span : owner;\n                }\n\n                if (owner != null)\n                {\n                    break;\n                }\n            }\n            return owner;\n        }\n\n        private static bool ChildrenEqual(IEnumerable<SyntaxTreeNode> left, IEnumerable<SyntaxTreeNode> right)\n        {\n            IEnumerator<SyntaxTreeNode> leftEnum = left.GetEnumerator();\n            IEnumerator<SyntaxTreeNode> rightEnum = right.GetEnumerator();\n            while (leftEnum.MoveNext())\n            {\n                if (!rightEnum.MoveNext() || // More items in left than in right\n                    !Equals(leftEnum.Current, rightEnum.Current))\n                {\n                    // Nodes are not equal\n                    return false;\n                }\n            }\n            if (rightEnum.MoveNext())\n            {\n                // More items in right than left\n                return false;\n            }\n            return true;\n        }\n\n        public override bool EquivalentTo(SyntaxTreeNode node)\n        {\n            Block other = node as Block;\n            if (other == null || other.Type != Type)\n            {\n                return false;\n            }\n            return Enumerable.SequenceEqual(Children, other.Children, new EquivalenceComparer());\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/SyntaxTree/BlockBuilder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Razor.Generator;\n\nnamespace System.Web.Razor.Parser.SyntaxTree\n{\n    public class BlockBuilder\n    {\n        public BlockBuilder()\n        {\n            Reset();\n        }\n\n        public BlockBuilder(Block original)\n        {\n            Type = original.Type;\n            Children = new List<SyntaxTreeNode>(original.Children);\n            Name = original.Name;\n            CodeGenerator = original.CodeGenerator;\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1721:PropertyNamesShouldNotMatchGetMethods\", Justification = \"Type is the most appropriate name for this property and there is little chance of confusion with GetType\")]\n        public BlockType? Type { get; set; }\n\n        public IList<SyntaxTreeNode> Children { get; private set; }\n        public string Name { get; set; }\n        public IBlockCodeGenerator CodeGenerator { get; set; }\n\n        public Block Build()\n        {\n            return new Block(this);\n        }\n\n        public void Reset()\n        {\n            Type = null;\n            Name = null;\n            Children = new List<SyntaxTreeNode>();\n            CodeGenerator = BlockCodeGenerator.Null;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/SyntaxTree/BlockType.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Razor.Parser.SyntaxTree\n{\n    public enum BlockType\n    {\n        // Code\n        Statement,\n        Directive,\n        Functions,\n        Expression,\n        Helper,\n\n        // Markup\n        Markup,\n        Section,\n        Template,\n\n        // Special\n        Comment\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/SyntaxTree/EquivalenceComparer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Razor.Parser.SyntaxTree\n{\n    internal class EquivalenceComparer : IEqualityComparer<SyntaxTreeNode>\n    {\n        public bool Equals(SyntaxTreeNode x, SyntaxTreeNode y)\n        {\n            return x.EquivalentTo(y);\n        }\n\n        public int GetHashCode(SyntaxTreeNode obj)\n        {\n            return obj.GetHashCode();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/SyntaxTree/RazorError.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Web.Razor.Text;\n\nnamespace System.Web.Razor.Parser.SyntaxTree\n{\n    public class RazorError : IEquatable<RazorError>\n    {\n        public RazorError(string message, SourceLocation location)\n            : this(message, location, 1)\n        {\n        }\n\n        public RazorError(string message, int absoluteIndex, int lineIndex, int columnIndex)\n            : this(message, new SourceLocation(absoluteIndex, lineIndex, columnIndex))\n        {\n        }\n\n        public RazorError(string message, SourceLocation location, int length)\n        {\n            Message = message;\n            Location = location;\n            Length = length;\n        }\n\n        public RazorError(string message, int absoluteIndex, int lineIndex, int columnIndex, int length)\n            : this(message, new SourceLocation(absoluteIndex, lineIndex, columnIndex), length)\n        {\n        }\n\n        public string Message { get; private set; }\n        public SourceLocation Location { get; private set; }\n        public int Length { get; private set; }\n\n        public override string ToString()\n        {\n            return String.Format(CultureInfo.CurrentCulture, \"Error @ {0}({2}) - [{1}]\", Location, Message, Length);\n        }\n\n        public override bool Equals(object obj)\n        {\n            RazorError err = obj as RazorError;\n            return (err != null) && (Equals(err));\n        }\n\n        public override int GetHashCode()\n        {\n            return base.GetHashCode();\n        }\n\n        public bool Equals(RazorError other)\n        {\n            return String.Equals(other.Message, Message, StringComparison.Ordinal) &&\n                   Location.Equals(other.Location);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/SyntaxTree/Span.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Text;\nusing System.Web.Razor.Editor;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Razor.Parser.SyntaxTree\n{\n    public class Span : SyntaxTreeNode\n    {\n        private SourceLocation _start;\n\n        public Span(SpanBuilder builder)\n        {\n            ReplaceWith(builder);\n        }\n\n        public SpanKind Kind { get; protected set; }\n        public IEnumerable<ISymbol> Symbols { get; protected set; }\n\n        // Allow test code to re-link spans\n        public Span Previous { get; protected internal set; }\n        public Span Next { get; protected internal set; }\n\n        public SpanEditHandler EditHandler { get; protected set; }\n        public ISpanCodeGenerator CodeGenerator { get; protected set; }\n\n        public override bool IsBlock\n        {\n            get { return false; }\n        }\n\n        public override int Length\n        {\n            get { return Content.Length; }\n        }\n\n        public override SourceLocation Start\n        {\n            get { return _start; }\n        }\n\n        public string Content { get; private set; }\n\n        public void Change(Action<SpanBuilder> changes)\n        {\n            SpanBuilder builder = new SpanBuilder(this);\n            changes(builder);\n            ReplaceWith(builder);\n        }\n\n        public void ReplaceWith(SpanBuilder builder)\n        {\n            Debug.Assert(!builder.Symbols.Any() || builder.Symbols.All(s => s != null));\n\n            Kind = builder.Kind;\n            Symbols = builder.Symbols;\n            EditHandler = builder.EditHandler;\n            CodeGenerator = builder.CodeGenerator ?? SpanCodeGenerator.Null;\n            _start = builder.Start;\n\n            // Since we took references to the values in SpanBuilder, clear its references out\n            builder.Reset();\n\n            // Calculate other properties\n            Content = Symbols.Aggregate(new StringBuilder(), (sb, sym) => sb.Append(sym.Content), sb => sb.ToString());\n        }\n\n        /// <summary>\n        /// Accepts the specified visitor\n        /// </summary>\n        /// <remarks>\n        /// Calls the VisitSpan method on the specified visitor, passing in this\n        /// </remarks>\n        public override void Accept(ParserVisitor visitor)\n        {\n            visitor.VisitSpan(this);\n        }\n\n        public override string ToString()\n        {\n            StringBuilder builder = new StringBuilder();\n            builder.Append(Kind);\n            builder.AppendFormat(\" Span at {0}::{1} - [{2}]\", Start, Length, Content);\n            builder.Append(\" Edit: <\");\n            builder.Append(EditHandler.ToString());\n            builder.Append(\">\");\n            builder.Append(\" Gen: <\");\n            builder.Append(CodeGenerator.ToString());\n            builder.Append(\"> {\");\n            builder.Append(String.Join(\";\", Symbols.GroupBy(sym => sym.GetType()).Select(grp => String.Concat(grp.Key.Name, \":\", grp.Count()))));\n            builder.Append(\"}\");\n            return builder.ToString();\n        }\n\n        public void ChangeStart(SourceLocation newStart)\n        {\n            _start = newStart;\n            Span current = this;\n            SourceLocationTracker tracker = new SourceLocationTracker(newStart);\n            tracker.UpdateLocation(Content);\n            while ((current = current.Next) != null)\n            {\n                current._start = tracker.CurrentLocation;\n                tracker.UpdateLocation(current.Content);\n            }\n        }\n\n        internal void SetStart(SourceLocation newStart)\n        {\n            _start = newStart;\n        }\n\n        /// <summary>\n        /// Checks that the specified span is equivalent to the other in that it has the same start point and content.\n        /// </summary>\n        public override bool EquivalentTo(SyntaxTreeNode node)\n        {\n            Span other = node as Span;\n            return other != null &&\n                   Kind.Equals(other.Kind) &&\n                   Start.Equals(other.Start) &&\n                   EditHandler.Equals(other.EditHandler) &&\n                   String.Equals(other.Content, Content, StringComparison.Ordinal);\n        }\n\n        public override bool Equals(object obj)\n        {\n            Span other = obj as Span;\n            return other != null &&\n                   Kind.Equals(other.Kind) &&\n                   EditHandler.Equals(other.EditHandler) &&\n                   CodeGenerator.Equals(other.CodeGenerator) &&\n                   Symbols.SequenceEqual(other.Symbols);\n        }\n\n        public override int GetHashCode()\n        {\n            return HashCodeCombiner.Start()\n                .Add((int)Kind)\n                .Add(Start)\n                .Add(Content)\n                .CombinedHash;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/SyntaxTree/SpanBuilder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Web.Razor.Editor;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Parser.SyntaxTree\n{\n    public class SpanBuilder\n    {\n        private IList<ISymbol> _symbols = new List<ISymbol>();\n        private SourceLocationTracker _tracker = new SourceLocationTracker();\n\n        public SpanBuilder(Span original)\n        {\n            Kind = original.Kind;\n            _symbols = new List<ISymbol>(original.Symbols);\n            EditHandler = original.EditHandler;\n            CodeGenerator = original.CodeGenerator;\n            Start = original.Start;\n        }\n\n        public SpanBuilder()\n        {\n            Reset();\n        }\n\n        public SourceLocation Start { get; set; }\n        public SpanKind Kind { get; set; }\n\n        public ReadOnlyCollection<ISymbol> Symbols\n        {\n            get { return new ReadOnlyCollection<ISymbol>(_symbols); }\n        }\n\n        public SpanEditHandler EditHandler { get; set; }\n        public ISpanCodeGenerator CodeGenerator { get; set; }\n\n        public void Reset()\n        {\n            _symbols = new List<ISymbol>();\n            EditHandler = SpanEditHandler.CreateDefault(s => Enumerable.Empty<ISymbol>());\n            CodeGenerator = SpanCodeGenerator.Null;\n            Start = SourceLocation.Zero;\n        }\n\n        public Span Build()\n        {\n            return new Span(this);\n        }\n\n        public void ClearSymbols()\n        {\n            _symbols.Clear();\n        }\n\n        // Short-cut method for adding a symbol\n        public void Accept(ISymbol symbol)\n        {\n            if (symbol == null)\n            {\n                return;\n            }\n\n            if (_symbols.Count == 0)\n            {\n                Start = symbol.Start;\n                symbol.ChangeStart(SourceLocation.Zero);\n                _tracker.CurrentLocation = SourceLocation.Zero;\n            }\n            else\n            {\n                symbol.ChangeStart(_tracker.CurrentLocation);\n            }\n\n            _symbols.Add(symbol);\n            _tracker.UpdateLocation(symbol.Content);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/SyntaxTree/SpanKind.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Razor.Parser.SyntaxTree\n{\n    public enum SpanKind\n    {\n        Transition,\n        MetaCode,\n        Comment,\n        Code,\n        Markup\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/SyntaxTree/SyntaxTreeNode.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Text;\n\nnamespace System.Web.Razor.Parser.SyntaxTree\n{\n    public abstract class SyntaxTreeNode\n    {\n        public Block Parent { get; internal set; }\n\n        /// <summary>\n        /// Returns true if this element is a block (to avoid casting)\n        /// </summary>\n        public abstract bool IsBlock { get; }\n\n        /// <summary>\n        /// The length of all the content contained in this node\n        /// </summary>\n        public abstract int Length { get; }\n\n        /// <summary>\n        /// The start point of this node\n        /// </summary>\n        public abstract SourceLocation Start { get; }\n\n        /// <summary>\n        /// Accepts a parser visitor, calling the appropriate visit method and passing in this instance\n        /// </summary>\n        /// <param name=\"visitor\">The visitor to accept</param>\n        public abstract void Accept(ParserVisitor visitor);\n\n        /// <summary>\n        /// Determines if the specified node is equivalent to this node\n        /// </summary>\n        /// <param name=\"node\">The node to compare this node with</param>\n        /// <returns>\n        /// true if the provided node has all the same content and metadata, though the specific quantity and type of symbols may be different.\n        /// </returns>\n        public abstract bool EquivalentTo(SyntaxTreeNode node);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/TextReaderExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Linq;\nusing System.Text;\n\nnamespace System.Web.Razor.Parser\n{\n    internal static class TextReaderExtensions\n    {\n        public static string ReadUntil(this TextReader reader, char terminator)\n        {\n            return ReadUntil(reader, terminator, inclusive: false);\n        }\n\n        public static string ReadUntil(this TextReader reader, char terminator, bool inclusive)\n        {\n            if (reader == null)\n            {\n                throw new ArgumentNullException(\"reader\");\n            }\n\n            // Rather not allocate an array to use ReadUntil(TextReader, params char[]) so we'll just call the predicate version directly\n            return reader.ReadUntil(c => c == terminator, inclusive);\n        }\n\n        public static string ReadUntil(this TextReader reader, params char[] terminators)\n        {\n            // NOTE: Using named parameters would be difficult here, hence the inline comment\n            return reader.ReadUntil(inclusive: false, terminators: terminators);\n        }\n\n        public static string ReadUntil(this TextReader reader, bool inclusive, params char[] terminators)\n        {\n            if (reader == null)\n            {\n                throw new ArgumentNullException(\"reader\");\n            }\n            if (terminators == null)\n            {\n                throw new ArgumentNullException(\"terminators\");\n            }\n\n            return reader.ReadUntil(c => terminators.Any(tc => tc == c), inclusive: inclusive);\n        }\n\n        public static string ReadUntil(this TextReader reader, Predicate<char> condition)\n        {\n            return reader.ReadUntil(condition, inclusive: false);\n        }\n\n        public static string ReadUntil(this TextReader reader, Predicate<char> condition, bool inclusive)\n        {\n            if (reader == null)\n            {\n                throw new ArgumentNullException(\"reader\");\n            }\n            if (condition == null)\n            {\n                throw new ArgumentNullException(\"condition\");\n            }\n\n            StringBuilder builder = new StringBuilder();\n            int ch = -1;\n            while ((ch = reader.Peek()) != -1 && !condition((char)ch))\n            {\n                reader.Read(); // Advance the reader\n                builder.Append((char)ch);\n            }\n\n            if (inclusive && reader.Peek() != -1)\n            {\n                builder.Append((char)reader.Read());\n            }\n\n            return builder.ToString();\n        }\n\n        public static string ReadWhile(this TextReader reader, Predicate<char> condition)\n        {\n            return reader.ReadWhile(condition, inclusive: false);\n        }\n\n        public static string ReadWhile(this TextReader reader, Predicate<char> condition, bool inclusive)\n        {\n            if (reader == null)\n            {\n                throw new ArgumentNullException(\"reader\");\n            }\n            if (condition == null)\n            {\n                throw new ArgumentNullException(\"condition\");\n            }\n\n            return reader.ReadUntil(ch => !condition(ch), inclusive);\n        }\n\n        public static string ReadWhiteSpace(this TextReader reader)\n        {\n            return reader.ReadWhile(c => Char.IsWhiteSpace(c));\n        }\n\n        public static string ReadUntilWhiteSpace(this TextReader reader)\n        {\n            return reader.ReadUntil(c => Char.IsWhiteSpace(c));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/TokenizerBackedParser.Helpers.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq;\nusing System.Web.Razor.Editor;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer;\nusing System.Web.Razor.Tokenizer.Symbols;\nusing System.Web.Razor.Utils;\n\nnamespace System.Web.Razor.Parser\n{\n    public abstract partial class TokenizerBackedParser<TTokenizer, TSymbol, TSymbolType> : ParserBase\n        where TTokenizer : Tokenizer<TSymbol, TSymbolType>\n        where TSymbol : SymbolBase<TSymbolType>\n    {\n        // Helpers\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"This only occurs in Release builds, where this method is empty by design\")]\n        [Conditional(\"DEBUG\")]\n        internal void Assert(TSymbolType expectedType)\n        {\n            Debug.Assert(!EndOfFile && Equals(CurrentSymbol.Type, expectedType));\n        }\n\n        protected internal void PutBack(TSymbol symbol)\n        {\n            if (symbol != null)\n            {\n                Tokenizer.PutBack(symbol);\n            }\n        }\n\n        /// <summary>\n        /// Put the specified symbols back in the input stream. The provided list MUST be in the ORDER THE SYMBOLS WERE READ. The\n        /// list WILL be reversed and the Putback(TSymbol) will be called on each item.\n        /// </summary>\n        /// <remarks>\n        /// If a document contains symbols: a, b, c, d, e, f\n        /// and AcceptWhile or AcceptUntil is used to collect until d\n        /// the list returned by AcceptWhile/Until will contain: a, b, c IN THAT ORDER\n        /// that is the correct format for providing to this method. The caller of this method would,\n        /// in that case, want to put c, b and a back into the stream, so \"a, b, c\" is the CORRECT order\n        /// </remarks>\n        protected internal void PutBack(IEnumerable<TSymbol> symbols)\n        {\n            foreach (TSymbol symbol in symbols.Reverse())\n            {\n                PutBack(symbol);\n            }\n        }\n\n        protected internal void PutCurrentBack()\n        {\n            if (!EndOfFile && CurrentSymbol != null)\n            {\n                PutBack(CurrentSymbol);\n            }\n        }\n\n        protected internal bool Balance(BalancingModes mode)\n        {\n            TSymbolType left = CurrentSymbol.Type;\n            TSymbolType right = Language.FlipBracket(left);\n            SourceLocation start = CurrentLocation;\n            AcceptAndMoveNext();\n            if (EndOfFile && !mode.HasFlag(BalancingModes.NoErrorOnFailure))\n            {\n                Context.OnError(start,\n                                RazorResources.ParseError_Expected_CloseBracket_Before_EOF,\n                                Language.GetSample(left),\n                                Language.GetSample(right));\n            }\n\n            return Balance(mode, left, right, start);\n        }\n\n        protected internal bool Balance(BalancingModes mode, TSymbolType left, TSymbolType right, SourceLocation start)\n        {\n            int startPosition = CurrentLocation.AbsoluteIndex;\n            int nesting = 1;\n            if (!EndOfFile)\n            {\n                IList<TSymbol> syms = new List<TSymbol>();\n                do\n                {\n                    if (IsAtEmbeddedTransition(\n                        mode.HasFlag(BalancingModes.AllowCommentsAndTemplates),\n                        mode.HasFlag(BalancingModes.AllowEmbeddedTransitions)))\n                    {\n                        Accept(syms);\n                        syms.Clear();\n                        HandleEmbeddedTransition();\n\n                        // Reset backtracking since we've already outputted some spans.\n                        startPosition = CurrentLocation.AbsoluteIndex;\n                    }\n                    if (At(left))\n                    {\n                        nesting++;\n                    }\n                    else if (At(right))\n                    {\n                        nesting--;\n                    }\n                    if (nesting > 0)\n                    {\n                        syms.Add(CurrentSymbol);\n                    }\n                }\n                while (nesting > 0 && NextToken());\n\n                if (nesting > 0)\n                {\n                    if (!mode.HasFlag(BalancingModes.NoErrorOnFailure))\n                    {\n                        Context.OnError(start,\n                                        RazorResources.ParseError_Expected_CloseBracket_Before_EOF,\n                                        Language.GetSample(left),\n                                        Language.GetSample(right));\n                    }\n                    if (mode.HasFlag(BalancingModes.BacktrackOnFailure))\n                    {\n                        Context.Source.Position = startPosition;\n                        NextToken();\n                    }\n                    else\n                    {\n                        Accept(syms);\n                    }\n                }\n                else\n                {\n                    // Accept all the symbols we saw\n                    Accept(syms);\n                }\n            }\n            return nesting == 0;\n        }\n\n        protected internal bool NextIs(TSymbolType type)\n        {\n            return NextIs(sym => sym != null && Equals(type, sym.Type));\n        }\n\n        protected internal bool NextIs(params TSymbolType[] types)\n        {\n            return NextIs(sym => sym != null && types.Any(t => Equals(t, sym.Type)));\n        }\n\n        protected internal bool NextIs(Func<TSymbol, bool> condition)\n        {\n            TSymbol cur = CurrentSymbol;\n            NextToken();\n            bool result = condition(CurrentSymbol);\n            PutCurrentBack();\n            PutBack(cur);\n            EnsureCurrent();\n            return result;\n        }\n\n        protected internal bool Was(TSymbolType type)\n        {\n            return PreviousSymbol != null && Equals(PreviousSymbol.Type, type);\n        }\n\n        protected internal bool At(TSymbolType type)\n        {\n            return !EndOfFile && CurrentSymbol != null && Equals(CurrentSymbol.Type, type);\n        }\n\n        protected internal bool AcceptAndMoveNext()\n        {\n            Accept(CurrentSymbol);\n            return NextToken();\n        }\n\n        protected TSymbol AcceptSingleWhiteSpaceCharacter()\n        {\n            if (Language.IsWhiteSpace(CurrentSymbol))\n            {\n                Tuple<TSymbol, TSymbol> pair = Language.SplitSymbol(CurrentSymbol, 1, Language.GetKnownSymbolType(KnownSymbolType.WhiteSpace));\n                Accept(pair.Item1);\n                Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n                NextToken();\n                return pair.Item2;\n            }\n            return null;\n        }\n\n        protected internal void Accept(IEnumerable<TSymbol> symbols)\n        {\n            foreach (TSymbol symbol in symbols)\n            {\n                Accept(symbol);\n            }\n        }\n\n        protected internal void Accept(TSymbol symbol)\n        {\n            if (symbol != null)\n            {\n                foreach (RazorError error in symbol.Errors)\n                {\n                    Context.Errors.Add(error);\n                }\n                Span.Accept(symbol);\n            }\n        }\n\n        protected internal bool AcceptAll(params TSymbolType[] types)\n        {\n            foreach (TSymbolType type in types)\n            {\n                if (CurrentSymbol == null || !Equals(CurrentSymbol.Type, type))\n                {\n                    return false;\n                }\n                AcceptAndMoveNext();\n            }\n            return true;\n        }\n\n        protected internal void AddMarkerSymbolIfNecessary()\n        {\n            AddMarkerSymbolIfNecessary(CurrentLocation);\n        }\n\n        protected internal void AddMarkerSymbolIfNecessary(SourceLocation location)\n        {\n            if (Span.Symbols.Count == 0 && Context.LastAcceptedCharacters != AcceptedCharacters.Any)\n            {\n                Accept(Language.CreateMarkerSymbol(location));\n            }\n        }\n\n        protected internal void Output(SpanKind kind)\n        {\n            Configure(kind, null);\n            Output();\n        }\n\n        protected internal void Output(SpanKind kind, AcceptedCharacters accepts)\n        {\n            Configure(kind, accepts);\n            Output();\n        }\n\n        protected internal void Output(AcceptedCharacters accepts)\n        {\n            Configure(null, accepts);\n            Output();\n        }\n\n        private void Output()\n        {\n            if (Span.Symbols.Count > 0)\n            {\n                Context.AddSpan(Span.Build());\n                Initialize(Span);\n            }\n        }\n\n        protected IDisposable PushSpanConfig()\n        {\n            return PushSpanConfig(newConfig: (Action<SpanBuilder, Action<SpanBuilder>>)null);\n        }\n\n        protected IDisposable PushSpanConfig(Action<SpanBuilder> newConfig)\n        {\n            return PushSpanConfig(newConfig == null ? (Action<SpanBuilder, Action<SpanBuilder>>)null : (span, _) => newConfig(span));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"The Action<T> parameters are preferred over custom delegates\")]\n        protected IDisposable PushSpanConfig(Action<SpanBuilder, Action<SpanBuilder>> newConfig)\n        {\n            Action<SpanBuilder> old = SpanConfig;\n            ConfigureSpan(newConfig);\n            return new DisposableAction(() => SpanConfig = old);\n        }\n\n        protected void ConfigureSpan(Action<SpanBuilder> config)\n        {\n            SpanConfig = config;\n            Initialize(Span);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"The Action<T> parameters are preferred over custom delegates\")]\n        protected void ConfigureSpan(Action<SpanBuilder, Action<SpanBuilder>> config)\n        {\n            Action<SpanBuilder> prev = SpanConfig;\n            if (config == null)\n            {\n                SpanConfig = null;\n            }\n            else\n            {\n                SpanConfig = span => config(span, prev);\n            }\n            Initialize(Span);\n        }\n\n        protected internal void Expected(KnownSymbolType type)\n        {\n            Expected(Language.GetKnownSymbolType(type));\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA1801:ReviewUnusedParameters\", MessageId = \"types\", Justification = \"It is used in debug builds\")]\n        protected internal void Expected(params TSymbolType[] types)\n        {\n            Debug.Assert(!EndOfFile && CurrentSymbol != null && types.Contains(CurrentSymbol.Type));\n            AcceptAndMoveNext();\n        }\n\n        protected internal bool Optional(KnownSymbolType type)\n        {\n            return Optional(Language.GetKnownSymbolType(type));\n        }\n\n        protected internal bool Optional(TSymbolType type)\n        {\n            if (At(type))\n            {\n                AcceptAndMoveNext();\n                return true;\n            }\n            return false;\n        }\n\n        protected internal bool Required(TSymbolType expected, bool errorIfNotFound, string errorBase)\n        {\n            bool found = At(expected);\n            if (!found && errorIfNotFound)\n            {\n                string error;\n                if (Language.IsNewLine(CurrentSymbol))\n                {\n                    error = RazorResources.ErrorComponent_Newline;\n                }\n                else if (Language.IsWhiteSpace(CurrentSymbol))\n                {\n                    error = RazorResources.ErrorComponent_Whitespace;\n                }\n                else if (EndOfFile)\n                {\n                    error = RazorResources.ErrorComponent_EndOfFile;\n                }\n                else\n                {\n                    error = String.Format(CultureInfo.CurrentCulture, RazorResources.ErrorComponent_Character, CurrentSymbol.Content);\n                }\n\n                Context.OnError(\n                    CurrentLocation,\n                    errorBase,\n                    error);\n            }\n            return found;\n        }\n\n        protected bool EnsureCurrent()\n        {\n            if (CurrentSymbol == null)\n            {\n                return NextToken();\n            }\n            return true;\n        }\n\n        protected internal void AcceptWhile(TSymbolType type)\n        {\n            AcceptWhile(sym => Equals(type, sym.Type));\n        }\n\n        // We want to avoid array allocations and enumeration where possible, so we use the same technique as String.Format\n        protected internal void AcceptWhile(TSymbolType type1, TSymbolType type2)\n        {\n            AcceptWhile(sym => Equals(type1, sym.Type) || Equals(type2, sym.Type));\n        }\n\n        protected internal void AcceptWhile(TSymbolType type1, TSymbolType type2, TSymbolType type3)\n        {\n            AcceptWhile(sym => Equals(type1, sym.Type) || Equals(type2, sym.Type) || Equals(type3, sym.Type));\n        }\n\n        protected internal void AcceptWhile(params TSymbolType[] types)\n        {\n            AcceptWhile(sym => types.Any(expected => Equals(expected, sym.Type)));\n        }\n\n        protected internal void AcceptUntil(TSymbolType type)\n        {\n            AcceptWhile(sym => !Equals(type, sym.Type));\n        }\n\n        // We want to avoid array allocations and enumeration where possible, so we use the same technique as String.Format\n        protected internal void AcceptUntil(TSymbolType type1, TSymbolType type2)\n        {\n            AcceptWhile(sym => !Equals(type1, sym.Type) && !Equals(type2, sym.Type));\n        }\n\n        protected internal void AcceptUntil(TSymbolType type1, TSymbolType type2, TSymbolType type3)\n        {\n            AcceptWhile(sym => !Equals(type1, sym.Type) && !Equals(type2, sym.Type) && !Equals(type3, sym.Type));\n        }\n\n        protected internal void AcceptUntil(params TSymbolType[] types)\n        {\n            AcceptWhile(sym => types.All(expected => !Equals(expected, sym.Type)));\n        }\n\n        protected internal void AcceptWhile(Func<TSymbol, bool> condition)\n        {\n            Accept(ReadWhileLazy(condition));\n        }\n\n        protected internal IEnumerable<TSymbol> ReadWhile(Func<TSymbol, bool> condition)\n        {\n            return ReadWhileLazy(condition).ToList();\n        }\n\n        protected TSymbol AcceptWhiteSpaceInLines()\n        {\n            TSymbol lastWs = null;\n            while (Language.IsWhiteSpace(CurrentSymbol) || Language.IsNewLine(CurrentSymbol))\n            {\n                // Capture the previous whitespace node\n                if (lastWs != null)\n                {\n                    Accept(lastWs);\n                }\n\n                if (Language.IsWhiteSpace(CurrentSymbol))\n                {\n                    lastWs = CurrentSymbol;\n                }\n                else if (Language.IsNewLine(CurrentSymbol))\n                {\n                    // Accept newline and reset last whitespace tracker\n                    Accept(CurrentSymbol);\n                    lastWs = null;\n                }\n\n                Tokenizer.Next();\n            }\n            return lastWs;\n        }\n\n        protected bool AtIdentifier(bool allowKeywords)\n        {\n            return CurrentSymbol != null &&\n                   (Language.IsIdentifier(CurrentSymbol) ||\n                    (allowKeywords && Language.IsKeyword(CurrentSymbol)));\n        }\n\n        // Don't open this to sub classes because it's lazy but it looks eager.\n        // You have to advance the Enumerable to read the next characters.\n        internal IEnumerable<TSymbol> ReadWhileLazy(Func<TSymbol, bool> condition)\n        {\n            while (EnsureCurrent() && condition(CurrentSymbol))\n            {\n                yield return CurrentSymbol;\n                NextToken();\n            }\n        }\n\n        private void Configure(SpanKind? kind, AcceptedCharacters? accepts)\n        {\n            if (kind != null)\n            {\n                Span.Kind = kind.Value;\n            }\n            if (accepts != null)\n            {\n                Span.EditHandler.AcceptedCharacters = accepts.Value;\n            }\n        }\n\n        protected virtual void OutputSpanBeforeRazorComment()\n        {\n            throw new InvalidOperationException(RazorResources.Language_Does_Not_Support_RazorComment);\n        }\n\n        private void CommentSpanConfig(SpanBuilder span)\n        {\n            span.CodeGenerator = SpanCodeGenerator.Null;\n            span.EditHandler = SpanEditHandler.CreateDefault(Language.TokenizeString);\n        }\n\n        protected void RazorComment()\n        {\n            if (!Language.KnowsSymbolType(KnownSymbolType.CommentStart) ||\n                !Language.KnowsSymbolType(KnownSymbolType.CommentStar) ||\n                !Language.KnowsSymbolType(KnownSymbolType.CommentBody))\n            {\n                throw new InvalidOperationException(RazorResources.Language_Does_Not_Support_RazorComment);\n            }\n            OutputSpanBeforeRazorComment();\n            using (PushSpanConfig(CommentSpanConfig))\n            {\n                using (Context.StartBlock(BlockType.Comment))\n                {\n                    Context.CurrentBlock.CodeGenerator = new RazorCommentCodeGenerator();\n                    SourceLocation start = CurrentLocation;\n\n                    Expected(KnownSymbolType.CommentStart);\n                    Output(SpanKind.Transition, AcceptedCharacters.None);\n\n                    Expected(KnownSymbolType.CommentStar);\n                    Output(SpanKind.MetaCode, AcceptedCharacters.None);\n\n                    Optional(KnownSymbolType.CommentBody);\n                    AddMarkerSymbolIfNecessary();\n                    Output(SpanKind.Comment);\n\n                    bool errorReported = false;\n                    if (!Optional(KnownSymbolType.CommentStar))\n                    {\n                        errorReported = true;\n                        Context.OnError(start, RazorResources.ParseError_RazorComment_Not_Terminated);\n                    }\n                    else\n                    {\n                        Output(SpanKind.MetaCode, AcceptedCharacters.None);\n                    }\n\n                    if (!Optional(KnownSymbolType.CommentStart))\n                    {\n                        if (!errorReported)\n                        {\n                            errorReported = true;\n                            Context.OnError(start, RazorResources.ParseError_RazorComment_Not_Terminated);\n                        }\n                    }\n                    else\n                    {\n                        Output(SpanKind.Transition, AcceptedCharacters.None);\n                    }\n                }\n            }\n            Initialize(Span);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/TokenizerBackedParser.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Parser\n{\n    [SuppressMessage(\"Microsoft.Design\", \"CA1005:AvoidExcessiveParametersOnGenericTypes\", Justification = \"All generic type parameters are required\")]\n    public abstract partial class TokenizerBackedParser<TTokenizer, TSymbol, TSymbolType> : ParserBase\n        where TTokenizer : Tokenizer<TSymbol, TSymbolType>\n        where TSymbol : SymbolBase<TSymbolType>\n    {\n        private TokenizerView<TTokenizer, TSymbol, TSymbolType> _tokenizer;\n\n        protected TokenizerBackedParser()\n        {\n            Span = new SpanBuilder();\n        }\n\n        protected SpanBuilder Span { get; set; }\n\n        protected TokenizerView<TTokenizer, TSymbol, TSymbolType> Tokenizer\n        {\n            get { return _tokenizer ?? InitTokenizer(); }\n        }\n\n        protected Action<SpanBuilder> SpanConfig { get; set; }\n\n        protected TSymbol CurrentSymbol\n        {\n            get { return Tokenizer.Current; }\n        }\n\n        protected TSymbol PreviousSymbol { get; private set; }\n\n        protected SourceLocation CurrentLocation\n        {\n            get { return (EndOfFile || CurrentSymbol == null) ? Context.Source.Location : CurrentSymbol.Start; }\n        }\n\n        protected bool EndOfFile\n        {\n            get { return Tokenizer.EndOfFile; }\n        }\n\n        protected abstract LanguageCharacteristics<TTokenizer, TSymbol, TSymbolType> Language { get; }\n\n        protected virtual void HandleEmbeddedTransition()\n        {\n        }\n\n        protected virtual bool IsAtEmbeddedTransition(bool allowTemplatesAndComments, bool allowTransitions)\n        {\n            return false;\n        }\n\n        public override void BuildSpan(SpanBuilder span, SourceLocation start, string content)\n        {\n            foreach (ISymbol sym in Language.TokenizeString(start, content))\n            {\n                span.Accept(sym);\n            }\n        }\n\n        protected void Initialize(SpanBuilder span)\n        {\n            if (SpanConfig != null)\n            {\n                SpanConfig(span);\n            }\n        }\n\n        protected internal bool NextToken()\n        {\n            PreviousSymbol = CurrentSymbol;\n            return Tokenizer.Next();\n        }\n\n        private TokenizerView<TTokenizer, TSymbol, TSymbolType> InitTokenizer()\n        {\n            return _tokenizer = new TokenizerView<TTokenizer, TSymbol, TSymbolType>(Language.CreateTokenizer(Context.Source));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/VBCodeParser.Directives.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq;\nusing System.Web.Razor.Editor;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Parser\n{\n    public partial class VBCodeParser : TokenizerBackedParser<VBTokenizer, VBSymbol, VBSymbolType>\n    {\n        private void SetUpDirectives()\n        {\n            MapDirective(SyntaxConstants.VB.CodeKeyword, EndTerminatedDirective(SyntaxConstants.VB.CodeKeyword,\n                                                                                BlockType.Statement,\n                                                                                new StatementCodeGenerator(),\n                                                                                allowMarkup: true));\n            MapDirective(SyntaxConstants.VB.FunctionsKeyword, EndTerminatedDirective(SyntaxConstants.VB.FunctionsKeyword,\n                                                                                     BlockType.Functions,\n                                                                                     new TypeMemberCodeGenerator(),\n                                                                                     allowMarkup: false));\n            MapDirective(SyntaxConstants.VB.SectionKeyword, SectionDirective);\n            MapDirective(SyntaxConstants.VB.HelperKeyword, HelperDirective);\n\n            MapDirective(SyntaxConstants.VB.LayoutKeyword, LayoutDirective);\n            MapDirective(SyntaxConstants.VB.SessionStateKeyword, SessionStateDirective);\n        }\n\n        protected virtual bool LayoutDirective()\n        {\n            AssertDirective(SyntaxConstants.VB.LayoutKeyword);\n            AcceptAndMoveNext();\n            Context.CurrentBlock.Type = BlockType.Directive;\n\n            // Accept spaces, but not newlines\n            bool foundSomeWhitespace = At(VBSymbolType.WhiteSpace);\n            AcceptWhile(VBSymbolType.WhiteSpace);\n            Output(SpanKind.MetaCode, foundSomeWhitespace ? AcceptedCharacters.None : AcceptedCharacters.Any);\n\n            // First non-whitespace character starts the Layout Page, then newline ends it\n            AcceptUntil(VBSymbolType.NewLine);\n            Span.CodeGenerator = new SetLayoutCodeGenerator(Span.GetContent());\n            Span.EditHandler.EditorHints = EditorHints.LayoutPage | EditorHints.VirtualPath;\n            bool foundNewline = Optional(VBSymbolType.NewLine);\n            AddMarkerSymbolIfNecessary();\n            Output(SpanKind.MetaCode, foundNewline ? AcceptedCharacters.None : AcceptedCharacters.Any);\n            return true;\n        }\n\n        protected virtual bool SessionStateDirective()\n        {\n            AssertDirective(SyntaxConstants.VB.SessionStateKeyword);\n            AcceptAndMoveNext();\n            Context.CurrentBlock.Type = BlockType.Directive;\n\n            // Accept spaces, but not newlines\n            bool foundSomeWhitespace = At(VBSymbolType.WhiteSpace);\n            AcceptWhile(VBSymbolType.WhiteSpace);\n            Output(SpanKind.MetaCode, foundSomeWhitespace ? AcceptedCharacters.None : AcceptedCharacters.Any);\n\n            // First non-whitespace character starts the session state directive, then newline ends it\n            AcceptUntil(VBSymbolType.NewLine);\n            var value = String.Concat(Span.Symbols.Select(sym => sym.Content));\n            Span.CodeGenerator = new RazorDirectiveAttributeCodeGenerator(SyntaxConstants.VB.SessionStateKeyword, value);\n            bool foundNewline = Optional(VBSymbolType.NewLine);\n            AddMarkerSymbolIfNecessary();\n            Output(SpanKind.MetaCode, foundNewline ? AcceptedCharacters.None : AcceptedCharacters.Any);\n            return true;\n        }\n\n        protected virtual bool HelperDirective()\n        {\n            if (Context.IsWithin(BlockType.Helper))\n            {\n                Context.OnError(CurrentLocation, RazorResources.ParseError_Helpers_Cannot_Be_Nested);\n            }\n\n            Context.CurrentBlock.Type = BlockType.Helper;\n            SourceLocation blockStart = CurrentLocation;\n\n            AssertDirective(SyntaxConstants.VB.HelperKeyword);\n            AcceptAndMoveNext();\n\n            VBSymbolType firstAfterKeyword = VBSymbolType.Unknown;\n            if (CurrentSymbol != null)\n            {\n                firstAfterKeyword = CurrentSymbol.Type;\n            }\n\n            VBSymbol remainingWs = null;\n            if (At(VBSymbolType.NewLine))\n            {\n                // Accept a _single_ new line, we'll be aborting later.\n                AcceptAndMoveNext();\n            }\n            else\n            {\n                remainingWs = AcceptSingleWhiteSpaceCharacter();\n            }\n            if (firstAfterKeyword == VBSymbolType.WhiteSpace || firstAfterKeyword == VBSymbolType.NewLine)\n            {\n                Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n            }\n            Output(SpanKind.MetaCode);\n            if (firstAfterKeyword != VBSymbolType.WhiteSpace)\n            {\n                string error;\n                if (At(VBSymbolType.NewLine))\n                {\n                    error = RazorResources.ErrorComponent_Newline;\n                }\n                else if (EndOfFile)\n                {\n                    error = RazorResources.ErrorComponent_EndOfFile;\n                }\n                else\n                {\n                    error = String.Format(CultureInfo.CurrentCulture, RazorResources.ErrorComponent_Character, CurrentSymbol.Content);\n                }\n\n                Context.OnError(\n                    CurrentLocation,\n                    RazorResources.ParseError_Unexpected_Character_At_Helper_Name_Start,\n                    error);\n\n                // Bail out.\n                PutCurrentBack();\n                Output(SpanKind.Code);\n                return false;\n            }\n\n            if (remainingWs != null)\n            {\n                Accept(remainingWs);\n            }\n\n            bool errorReported = !Required(VBSymbolType.Identifier, RazorResources.ParseError_Unexpected_Character_At_Helper_Name_Start);\n\n            AcceptWhile(VBSymbolType.WhiteSpace);\n\n            SourceLocation parensStart = CurrentLocation;\n            bool headerComplete = false;\n            if (!Optional(VBSymbolType.LeftParenthesis))\n            {\n                if (!errorReported)\n                {\n                    errorReported = true;\n                    Context.OnError(CurrentLocation,\n                                    RazorResources.ParseError_MissingCharAfterHelperName,\n                                    VBSymbol.GetSample(VBSymbolType.LeftParenthesis));\n                }\n            }\n            else if (!Balance(BalancingModes.NoErrorOnFailure, VBSymbolType.LeftParenthesis, VBSymbolType.RightParenthesis, parensStart))\n            {\n                Context.OnError(parensStart, RazorResources.ParseError_UnterminatedHelperParameterList);\n            }\n            else\n            {\n                Expected(VBSymbolType.RightParenthesis);\n                headerComplete = true;\n            }\n\n            AddMarkerSymbolIfNecessary();\n            Context.CurrentBlock.CodeGenerator = new HelperCodeGenerator(\n                Span.GetContent(),\n                headerComplete);\n            AutoCompleteEditHandler editHandler = new AutoCompleteEditHandler(Language.TokenizeString);\n            Span.EditHandler = editHandler;\n            Output(SpanKind.Code);\n\n            if (headerComplete)\n            {\n                bool old = IsNested;\n                IsNested = true;\n                using (Context.StartBlock(BlockType.Statement))\n                {\n                    using (PushSpanConfig(StatementBlockSpanConfiguration(new StatementCodeGenerator())))\n                    {\n                        try\n                        {\n                            if (!EndTerminatedDirectiveBody(SyntaxConstants.VB.HelperKeyword, blockStart, allowAllTransitions: true))\n                            {\n                                if (Context.LastAcceptedCharacters != AcceptedCharacters.Any)\n                                {\n                                    AddMarkerSymbolIfNecessary();\n                                }\n\n                                editHandler.AutoCompleteString = SyntaxConstants.VB.EndHelperKeyword;\n                                return false;\n                            }\n                            else\n                            {\n                                return true;\n                            }\n                        }\n                        finally\n                        {\n                            Output(SpanKind.Code);\n                            IsNested = old;\n                        }\n                    }\n                }\n            }\n            else\n            {\n                Output(SpanKind.Code);\n            }\n            PutCurrentBack();\n            return false;\n        }\n\n        protected virtual bool SectionDirective()\n        {\n            SourceLocation start = CurrentLocation;\n            AssertDirective(SyntaxConstants.VB.SectionKeyword);\n            AcceptAndMoveNext();\n\n            if (Context.IsWithin(BlockType.Section))\n            {\n                Context.OnError(CurrentLocation, RazorResources.ParseError_Sections_Cannot_Be_Nested, RazorResources.SectionExample_VB);\n            }\n\n            if (At(VBSymbolType.NewLine))\n            {\n                AcceptAndMoveNext();\n            }\n            else\n            {\n                AcceptVBSpaces();\n            }\n            string sectionName = null;\n            if (!At(VBSymbolType.Identifier))\n            {\n                Context.OnError(CurrentLocation,\n                                RazorResources.ParseError_Unexpected_Character_At_Section_Name_Start,\n                                GetCurrentSymbolDisplay());\n            }\n            else\n            {\n                sectionName = CurrentSymbol.Content;\n                AcceptAndMoveNext();\n            }\n            Context.CurrentBlock.Type = BlockType.Section;\n            Context.CurrentBlock.CodeGenerator = new SectionCodeGenerator(sectionName ?? String.Empty);\n\n            AutoCompleteEditHandler editHandler = new AutoCompleteEditHandler(Language.TokenizeString);\n            Span.EditHandler = editHandler;\n\n            PutCurrentBack();\n\n            Output(SpanKind.MetaCode);\n\n            // Parse the section\n            OtherParserBlock(null, SyntaxConstants.VB.EndSectionKeyword);\n\n            Span.CodeGenerator = SpanCodeGenerator.Null;\n            bool complete = false;\n            if (!At(VBKeyword.End))\n            {\n                Context.OnError(start,\n                                RazorResources.ParseError_BlockNotTerminated,\n                                SyntaxConstants.VB.SectionKeyword,\n                                SyntaxConstants.VB.EndSectionKeyword);\n                editHandler.AutoCompleteString = SyntaxConstants.VB.EndSectionKeyword;\n            }\n            else\n            {\n                AcceptAndMoveNext();\n                AcceptWhile(VBSymbolType.WhiteSpace);\n                if (!At(SyntaxConstants.VB.SectionKeyword))\n                {\n                    Context.OnError(start,\n                                    RazorResources.ParseError_BlockNotTerminated,\n                                    SyntaxConstants.VB.SectionKeyword,\n                                    SyntaxConstants.VB.EndSectionKeyword);\n                }\n                else\n                {\n                    AcceptAndMoveNext();\n                    Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n                    complete = true;\n                }\n            }\n            PutCurrentBack();\n            Output(SpanKind.MetaCode);\n            return complete;\n        }\n\n        protected virtual Func<bool> EndTerminatedDirective(string directive, BlockType blockType, SpanCodeGenerator codeGenerator, bool allowMarkup)\n        {\n            return () =>\n            {\n                SourceLocation blockStart = CurrentLocation;\n                Context.CurrentBlock.Type = blockType;\n                AssertDirective(directive);\n                AcceptAndMoveNext();\n\n                Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n                Span.CodeGenerator = SpanCodeGenerator.Null;\n                Output(SpanKind.MetaCode);\n\n                using (PushSpanConfig(StatementBlockSpanConfiguration(codeGenerator)))\n                {\n                    AutoCompleteEditHandler editHandler = new AutoCompleteEditHandler(Language.TokenizeString);\n                    Span.EditHandler = editHandler;\n\n                    if (!EndTerminatedDirectiveBody(directive, blockStart, allowMarkup))\n                    {\n                        editHandler.AutoCompleteString = String.Concat(SyntaxConstants.VB.EndKeyword, \" \", directive);\n                        return false;\n                    }\n                    return true;\n                }\n            };\n        }\n\n        protected virtual bool EndTerminatedDirectiveBody(string directive, SourceLocation blockStart, bool allowAllTransitions)\n        {\n            while (!EndOfFile)\n            {\n                VBSymbol lastWhitespace = AcceptWhiteSpaceInLines();\n                if (IsAtEmbeddedTransition(allowTemplatesAndComments: allowAllTransitions, allowTransitions: allowAllTransitions))\n                {\n                    HandleEmbeddedTransition(lastWhitespace);\n                }\n                else\n                {\n                    if (At(VBKeyword.End))\n                    {\n                        Accept(lastWhitespace);\n                        VBSymbol end = CurrentSymbol;\n                        NextToken();\n                        IEnumerable<VBSymbol> ws = ReadVBSpaces();\n                        if (At(directive))\n                        {\n                            if (Context.LastAcceptedCharacters != AcceptedCharacters.Any)\n                            {\n                                AddMarkerSymbolIfNecessary(end.Start);\n                            }\n                            Output(SpanKind.Code);\n                            Accept(end);\n                            Accept(ws);\n                            AcceptAndMoveNext();\n                            Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n                            Span.CodeGenerator = SpanCodeGenerator.Null;\n                            Output(SpanKind.MetaCode);\n                            return true;\n                        }\n                        else\n                        {\n                            Accept(end);\n                            Accept(ws);\n                            AcceptAndMoveNext();\n                        }\n                    }\n                    else\n                    {\n                        Accept(lastWhitespace);\n                        AcceptAndMoveNext();\n                    }\n                }\n            }\n\n            // This is a language keyword, so it does not need to be localized\n            Context.OnError(blockStart, RazorResources.ParseError_BlockNotTerminated, directive, String.Concat(SyntaxConstants.VB.EndKeyword, \" \", directive));\n            return false;\n        }\n\n        protected bool At(string directive)\n        {\n            return At(VBSymbolType.Identifier) && String.Equals(CurrentSymbol.Content, directive, StringComparison.OrdinalIgnoreCase);\n        }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"'this' is used in DEBUG builds\")]\n        [Conditional(\"DEBUG\")]\n        protected void AssertDirective(string directive)\n        {\n            Assert(VBSymbolType.Identifier);\n            Debug.Assert(String.Equals(directive, CurrentSymbol.Content, StringComparison.OrdinalIgnoreCase));\n        }\n\n        private string GetCurrentSymbolDisplay()\n        {\n            if (EndOfFile)\n            {\n                return RazorResources.ErrorComponent_EndOfFile;\n            }\n            else if (At(VBSymbolType.NewLine))\n            {\n                return RazorResources.ErrorComponent_Newline;\n            }\n            else if (At(VBSymbolType.WhiteSpace))\n            {\n                return RazorResources.ErrorComponent_Whitespace;\n            }\n            else\n            {\n                return String.Format(CultureInfo.CurrentCulture, RazorResources.ErrorComponent_Character, CurrentSymbol.Content);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/VBCodeParser.Statements.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.Linq;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Parser\n{\n    public partial class VBCodeParser : TokenizerBackedParser<VBTokenizer, VBSymbol, VBSymbolType>\n    {\n        private void SetUpKeywords()\n        {\n            MapKeyword(VBKeyword.Using, EndTerminatedStatement(VBKeyword.Using, supportsExit: false, supportsContinue: false)); // http://msdn.microsoft.com/en-us/library/htd05whh.aspx\n            MapKeyword(VBKeyword.While, EndTerminatedStatement(VBKeyword.While, supportsExit: true, supportsContinue: true)); // http://msdn.microsoft.com/en-us/library/zh1f56zs.aspx\n            MapKeyword(VBKeyword.If, EndTerminatedStatement(VBKeyword.If, supportsExit: false, supportsContinue: false)); // http://msdn.microsoft.com/en-us/library/752y8abs.aspx\n            MapKeyword(VBKeyword.Select, EndTerminatedStatement(VBKeyword.Select, supportsExit: true, supportsContinue: false, blockName: SyntaxConstants.VB.SelectCaseKeyword)); // http://msdn.microsoft.com/en-us/library/cy37t14y.aspx\n            MapKeyword(VBKeyword.Try, EndTerminatedStatement(VBKeyword.Try, supportsExit: true, supportsContinue: false)); // http://msdn.microsoft.com/en-us/library/fk6t46tz.aspx\n            MapKeyword(VBKeyword.With, EndTerminatedStatement(VBKeyword.With, supportsExit: false, supportsContinue: false)); // http://msdn.microsoft.com/en-us/library/wc500chb.aspx\n            MapKeyword(VBKeyword.SyncLock, EndTerminatedStatement(VBKeyword.SyncLock, supportsExit: false, supportsContinue: false)); // http://msdn.microsoft.com/en-us/library/3a86s51t.aspx\n\n            // http://msdn.microsoft.com/en-us/library/5z06z1kb.aspx\n            // http://msdn.microsoft.com/en-us/library/5ebk1751.aspx\n            MapKeyword(VBKeyword.For, KeywordTerminatedStatement(VBKeyword.For, VBKeyword.Next, supportsExit: true, supportsContinue: true));\n            MapKeyword(VBKeyword.Do, KeywordTerminatedStatement(VBKeyword.Do, VBKeyword.Loop, supportsExit: true, supportsContinue: true)); // http://msdn.microsoft.com/en-us/library/eked04a7.aspx\n\n            MapKeyword(VBKeyword.Imports, ImportsStatement);\n            MapKeyword(VBKeyword.Option, OptionStatement);\n            MapKeyword(VBKeyword.Inherits, InheritsStatement);\n\n            MapKeyword(VBKeyword.Class, ReservedWord);\n            MapKeyword(VBKeyword.Namespace, ReservedWord);\n        }\n\n        protected virtual bool InheritsStatement()\n        {\n            Assert(VBKeyword.Inherits);\n\n            Span.CodeGenerator = SpanCodeGenerator.Null;\n            Context.CurrentBlock.Type = BlockType.Directive;\n\n            AcceptAndMoveNext();\n            SourceLocation endInherits = CurrentLocation;\n\n            if (At(VBSymbolType.WhiteSpace))\n            {\n                Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n            }\n\n            AcceptWhile(VBSymbolType.WhiteSpace);\n            Output(SpanKind.MetaCode);\n\n            if (EndOfFile || At(VBSymbolType.WhiteSpace) || At(VBSymbolType.NewLine))\n            {\n                Context.OnError(endInherits, RazorResources.ParseError_InheritsKeyword_Must_Be_Followed_By_TypeName);\n            }\n\n            // Just accept to a newline\n            AcceptUntil(VBSymbolType.NewLine);\n            if (!Context.DesignTimeMode)\n            {\n                // We want the newline to be treated as code, but it causes issues at design-time.\n                Optional(VBSymbolType.NewLine);\n            }\n\n            string baseType = Span.GetContent();\n            Span.CodeGenerator = new SetBaseTypeCodeGenerator(baseType.Trim());\n\n            Output(SpanKind.Code);\n            return false;\n        }\n\n        protected virtual bool OptionStatement()\n        {\n            try\n            {\n                Context.CurrentBlock.Type = BlockType.Directive;\n\n                Assert(VBKeyword.Option);\n                AcceptAndMoveNext();\n                AcceptWhile(VBSymbolType.WhiteSpace);\n                if (!At(VBSymbolType.Identifier))\n                {\n                    if (CurrentSymbol != null)\n                    {\n                        Context.OnError(CurrentLocation, String.Format(CultureInfo.CurrentCulture,\n                                                                       RazorResources.ParseError_Unexpected,\n                                                                       CurrentSymbol.Content));\n                    }\n                    return false;\n                }\n                SourceLocation optionLoc = CurrentLocation;\n                string option = CurrentSymbol.Content;\n                AcceptAndMoveNext();\n\n                AcceptWhile(VBSymbolType.WhiteSpace);\n                bool boolVal;\n                if (At(VBKeyword.On))\n                {\n                    AcceptAndMoveNext();\n                    boolVal = true;\n                }\n                else if (At(VBSymbolType.Identifier))\n                {\n                    if (String.Equals(CurrentSymbol.Content, SyntaxConstants.VB.OffKeyword, StringComparison.OrdinalIgnoreCase))\n                    {\n                        AcceptAndMoveNext();\n                        boolVal = false;\n                    }\n                    else\n                    {\n                        Context.OnError(CurrentLocation, String.Format(CultureInfo.CurrentCulture,\n                                                                       RazorResources.ParseError_InvalidOptionValue,\n                                                                       option,\n                                                                       CurrentSymbol.Content));\n                        AcceptAndMoveNext();\n                        return false;\n                    }\n                }\n                else\n                {\n                    if (!EndOfFile)\n                    {\n                        Context.OnError(CurrentLocation, String.Format(CultureInfo.CurrentCulture,\n                                                                       RazorResources.ParseError_Unexpected,\n                                                                       CurrentSymbol.Content));\n                        AcceptAndMoveNext();\n                    }\n                    return false;\n                }\n\n                if (String.Equals(option, SyntaxConstants.VB.StrictKeyword, StringComparison.OrdinalIgnoreCase))\n                {\n                    Span.CodeGenerator = SetVBOptionCodeGenerator.Strict(boolVal);\n                }\n                else if (String.Equals(option, SyntaxConstants.VB.ExplicitKeyword, StringComparison.OrdinalIgnoreCase))\n                {\n                    Span.CodeGenerator = SetVBOptionCodeGenerator.Explicit(boolVal);\n                }\n                else\n                {\n                    Span.CodeGenerator = new SetVBOptionCodeGenerator(option, boolVal);\n                    Context.OnError(optionLoc, RazorResources.ParseError_UnknownOption, option);\n                }\n            }\n            finally\n            {\n                if (Span.Symbols.Count > 0)\n                {\n                    Output(SpanKind.MetaCode);\n                }\n            }\n            return true;\n        }\n\n        protected virtual bool ImportsStatement()\n        {\n            Context.CurrentBlock.Type = BlockType.Directive;\n            Assert(VBKeyword.Imports);\n            AcceptAndMoveNext();\n\n            AcceptVBSpaces();\n            if (At(VBSymbolType.WhiteSpace) || At(VBSymbolType.NewLine))\n            {\n                Context.OnError(CurrentLocation, RazorResources.ParseError_NamespaceOrTypeAliasExpected);\n            }\n\n            // Just accept to a newline\n            AcceptUntil(VBSymbolType.NewLine);\n            Optional(VBSymbolType.NewLine);\n\n            string ns = String.Concat(Span.Symbols.Skip(1).Select(s => s.Content));\n            Span.CodeGenerator = new AddImportCodeGenerator(ns, SyntaxConstants.VB.ImportsKeywordLength);\n\n            Output(SpanKind.MetaCode);\n            return false;\n        }\n\n        protected virtual Func<bool> EndTerminatedStatement(VBKeyword keyword, bool supportsExit, bool supportsContinue)\n        {\n            return EndTerminatedStatement(keyword, supportsExit, supportsContinue, blockName: keyword.ToString());\n        }\n\n        protected virtual Func<bool> EndTerminatedStatement(VBKeyword keyword, bool supportsExit, bool supportsContinue, string blockName)\n        {\n            return () =>\n            {\n                using (PushSpanConfig(StatementBlockSpanConfiguration(new StatementCodeGenerator())))\n                {\n                    SourceLocation blockStart = CurrentLocation;\n                    Assert(keyword);\n                    AcceptAndMoveNext();\n\n                    while (!EndOfFile)\n                    {\n                        VBSymbol lastWhitespace = AcceptWhiteSpaceInLines();\n                        if (IsAtEmbeddedTransition(allowTemplatesAndComments: true, allowTransitions: true))\n                        {\n                            HandleEmbeddedTransition(lastWhitespace);\n                        }\n                        else\n                        {\n                            Accept(lastWhitespace);\n\n                            if ((supportsExit && At(VBKeyword.Exit)) || (supportsContinue && At(VBKeyword.Continue)))\n                            {\n                                HandleExitOrContinue(keyword);\n                            }\n                            else if (At(VBKeyword.End))\n                            {\n                                AcceptAndMoveNext();\n                                AcceptVBSpaces();\n                                if (At(keyword))\n                                {\n                                    AcceptAndMoveNext();\n                                    if (!Context.DesignTimeMode)\n                                    {\n                                        Optional(VBSymbolType.NewLine);\n                                    }\n                                    Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n                                    return false;\n                                }\n                            }\n                            else if (At(keyword))\n                            {\n                                // Parse nested statement\n                                EndTerminatedStatement(keyword, supportsExit, supportsContinue)();\n                            }\n                            else if (!EndOfFile)\n                            {\n                                AcceptAndMoveNext();\n                            }\n                        }\n                    }\n\n                    Context.OnError(blockStart,\n                                    RazorResources.ParseError_BlockNotTerminated,\n                                    blockName,\n                                    // This is a language keyword, so it does not need to be localized\n                                    String.Concat(VBKeyword.End, \" \", keyword));\n                    return false;\n                }\n            };\n        }\n\n        protected virtual Func<bool> KeywordTerminatedStatement(VBKeyword start, VBKeyword terminator, bool supportsExit, bool supportsContinue)\n        {\n            return () =>\n            {\n                using (PushSpanConfig(StatementBlockSpanConfiguration(new StatementCodeGenerator())))\n                {\n                    SourceLocation blockStart = CurrentLocation;\n                    Assert(start);\n                    AcceptAndMoveNext();\n                    while (!EndOfFile)\n                    {\n                        VBSymbol lastWhitespace = AcceptWhiteSpaceInLines();\n                        if (IsAtEmbeddedTransition(allowTemplatesAndComments: true, allowTransitions: true))\n                        {\n                            HandleEmbeddedTransition(lastWhitespace);\n                        }\n                        else\n                        {\n                            Accept(lastWhitespace);\n                            if ((supportsExit && At(VBKeyword.Exit)) || (supportsContinue && At(VBKeyword.Continue)))\n                            {\n                                HandleExitOrContinue(start);\n                            }\n                            else if (At(start))\n                            {\n                                // Parse nested statement\n                                KeywordTerminatedStatement(start, terminator, supportsExit, supportsContinue)();\n                            }\n                            else if (At(terminator))\n                            {\n                                AcceptUntil(VBSymbolType.NewLine);\n                                Optional(VBSymbolType.NewLine);\n                                Span.EditHandler.AcceptedCharacters = AcceptedCharacters.AnyExceptNewline;\n                                return false;\n                            }\n                            else if (!EndOfFile)\n                            {\n                                AcceptAndMoveNext();\n                            }\n                        }\n                    }\n\n                    Context.OnError(blockStart,\n                                    RazorResources.ParseError_BlockNotTerminated,\n                                    start, terminator);\n                    return false;\n                }\n            };\n        }\n\n        protected void HandleExitOrContinue(VBKeyword keyword)\n        {\n            Assert(VBSymbolType.Keyword);\n            Debug.Assert(CurrentSymbol.Keyword == VBKeyword.Continue || CurrentSymbol.Keyword == VBKeyword.Exit);\n\n            // Accept, read whitespace and look for the next keyword\n            AcceptAndMoveNext();\n            AcceptWhile(VBSymbolType.WhiteSpace);\n\n            // If this is the start keyword, skip it and continue (to avoid starting a nested statement block)\n            Optional(keyword);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/VBCodeParser.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Web.Razor.Editor;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Parser\n{\n    public partial class VBCodeParser : TokenizerBackedParser<VBTokenizer, VBSymbol, VBSymbolType>\n    {\n        internal static ISet<string> DefaultKeywords = new HashSet<string>(StringComparer.OrdinalIgnoreCase)\n        {\n            \"functions\",\n            \"code\",\n            \"section\",\n            \"do\",\n            \"while\",\n            \"if\",\n            \"select\",\n            \"for\",\n            \"try\",\n            \"with\",\n            \"synclock\",\n            \"using\",\n            \"imports\",\n            \"inherits\",\n            \"option\",\n            \"helper\",\n            \"namespace\",\n            \"class\",\n            \"layout\",\n            \"sessionstate\"\n        };\n\n        private Dictionary<VBKeyword, Func<bool>> _keywordHandlers = new Dictionary<VBKeyword, Func<bool>>();\n        private Dictionary<string, Func<bool>> _directiveHandlers = new Dictionary<string, Func<bool>>(StringComparer.OrdinalIgnoreCase);\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2214:DoNotCallOverridableMethodsInConstructors\", Justification = \"Necessary state is initialized before calling virtual methods\")]\n        public VBCodeParser()\n        {\n            DirectParentIsCode = false;\n            Keywords = new HashSet<string>(StringComparer.OrdinalIgnoreCase);\n            SetUpKeywords();\n            SetUpDirectives();\n        }\n\n        protected internal ISet<string> Keywords { get; private set; }\n\n        protected override LanguageCharacteristics<VBTokenizer, VBSymbol, VBSymbolType> Language\n        {\n            get { return VBLanguageCharacteristics.Instance; }\n        }\n\n        protected override ParserBase OtherParser\n        {\n            get { return Context.MarkupParser; }\n        }\n\n        private bool IsNested { get; set; }\n        private bool DirectParentIsCode { get; set; }\n\n        protected override bool IsAtEmbeddedTransition(bool allowTemplatesAndComments, bool allowTransitions)\n        {\n            return (allowTransitions && Language.IsTransition(CurrentSymbol) && !Was(VBSymbolType.Dot)) ||\n                   (allowTemplatesAndComments && Language.IsCommentStart(CurrentSymbol)) ||\n                   (Language.IsTransition(CurrentSymbol) && NextIs(VBSymbolType.Transition));\n        }\n\n        protected override void HandleEmbeddedTransition()\n        {\n            HandleEmbeddedTransition(null);\n        }\n\n        protected void HandleEmbeddedTransition(VBSymbol lastWhiteSpace)\n        {\n            if (At(VBSymbolType.RazorCommentTransition))\n            {\n                Accept(lastWhiteSpace);\n                RazorComment();\n            }\n            else if ((At(VBSymbolType.Transition) && !Was(VBSymbolType.Dot)))\n            {\n                HandleTransition(lastWhiteSpace);\n            }\n        }\n\n        public override void ParseBlock()\n        {\n            if (Context == null)\n            {\n                throw new InvalidOperationException(RazorResources.Parser_Context_Not_Set);\n            }\n            using (PushSpanConfig())\n            {\n                if (Context == null)\n                {\n                    throw new InvalidOperationException(RazorResources.Parser_Context_Not_Set);\n                }\n\n                Initialize(Span);\n                NextToken();\n                using (Context.StartBlock())\n                {\n                    IEnumerable<VBSymbol> syms = ReadWhile(sym => sym.Type == VBSymbolType.WhiteSpace);\n                    if (At(VBSymbolType.Transition))\n                    {\n                        Accept(syms);\n                        Span.CodeGenerator = new StatementCodeGenerator();\n                        Output(SpanKind.Code);\n                    }\n                    else\n                    {\n                        PutBack(syms);\n                        EnsureCurrent();\n                    }\n\n                    // Allow a transition span, but don't require it\n                    if (Optional(VBSymbolType.Transition))\n                    {\n                        Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n                        Span.CodeGenerator = SpanCodeGenerator.Null;\n                        Output(SpanKind.Transition);\n                    }\n\n                    Context.CurrentBlock.Type = BlockType.Expression;\n                    Context.CurrentBlock.CodeGenerator = new ExpressionCodeGenerator();\n\n                    // Determine the type of the block\n                    bool isComplete = false;\n                    Action<SpanBuilder> config = null;\n                    if (!EndOfFile)\n                    {\n                        switch (CurrentSymbol.Type)\n                        {\n                            case VBSymbolType.Identifier:\n                                if (!TryDirectiveBlock(ref isComplete))\n                                {\n                                    ImplicitExpression();\n                                }\n                                break;\n                            case VBSymbolType.LeftParenthesis:\n                                isComplete = ExplicitExpression();\n                                break;\n                            case VBSymbolType.Keyword:\n                                Context.CurrentBlock.Type = BlockType.Statement;\n                                Context.CurrentBlock.CodeGenerator = BlockCodeGenerator.Null;\n                                isComplete = KeywordBlock();\n                                break;\n                            case VBSymbolType.WhiteSpace:\n                            case VBSymbolType.NewLine:\n                                config = ImplictExpressionSpanConfig;\n                                Context.OnError(CurrentLocation,\n                                                RazorResources.ParseError_Unexpected_WhiteSpace_At_Start_Of_CodeBlock_VB);\n                                break;\n                            default:\n                                config = ImplictExpressionSpanConfig;\n                                Context.OnError(CurrentLocation,\n                                                RazorResources.ParseError_Unexpected_Character_At_Start_Of_CodeBlock_VB,\n                                                CurrentSymbol.Content);\n                                break;\n                        }\n                    }\n                    else\n                    {\n                        config = ImplictExpressionSpanConfig;\n                        Context.OnError(CurrentLocation,\n                                        RazorResources.ParseError_Unexpected_EndOfFile_At_Start_Of_CodeBlock);\n                    }\n                    using (PushSpanConfig(config))\n                    {\n                        if (!isComplete && Span.Symbols.Count == 0 && Context.LastAcceptedCharacters != AcceptedCharacters.Any)\n                        {\n                            AddMarkerSymbolIfNecessary();\n                        }\n                        Output(SpanKind.Code);\n                        PutCurrentBack();\n                    }\n                }\n            }\n        }\n\n        private void ImplictExpressionSpanConfig(SpanBuilder span)\n        {\n            span.CodeGenerator = new ExpressionCodeGenerator();\n            span.EditHandler = new ImplicitExpressionEditHandler(\n                Language.TokenizeString,\n                Keywords,\n                acceptTrailingDot: DirectParentIsCode)\n            {\n                AcceptedCharacters = AcceptedCharacters.NonWhiteSpace\n            };\n        }\n\n        private Action<SpanBuilder> StatementBlockSpanConfiguration(SpanCodeGenerator codeGenerator)\n        {\n            return span =>\n            {\n                span.Kind = SpanKind.Code;\n                span.CodeGenerator = codeGenerator;\n                span.EditHandler = SpanEditHandler.CreateDefault(Language.TokenizeString);\n            };\n        }\n\n        // Pass \"complete\" flag by ref, not out because some paths may not change it.\n        private bool TryDirectiveBlock(ref bool complete)\n        {\n            Assert(VBSymbolType.Identifier);\n            Func<bool> handler;\n            if (_directiveHandlers.TryGetValue(CurrentSymbol.Content, out handler))\n            {\n                Context.CurrentBlock.CodeGenerator = BlockCodeGenerator.Null;\n                complete = handler();\n                return true;\n            }\n            return false;\n        }\n\n        private bool KeywordBlock()\n        {\n            Assert(VBSymbolType.Keyword);\n            Func<bool> handler;\n            if (_keywordHandlers.TryGetValue(CurrentSymbol.Keyword.Value, out handler))\n            {\n                Span.CodeGenerator = new StatementCodeGenerator();\n                Context.CurrentBlock.Type = BlockType.Statement;\n                return handler();\n            }\n            else\n            {\n                ImplicitExpression();\n                return false;\n            }\n        }\n\n        private bool ExplicitExpression()\n        {\n            Context.CurrentBlock.Type = BlockType.Expression;\n            Context.CurrentBlock.CodeGenerator = new ExpressionCodeGenerator();\n            SourceLocation start = CurrentLocation;\n            Expected(VBSymbolType.LeftParenthesis);\n            Span.CodeGenerator = SpanCodeGenerator.Null;\n            Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n            Output(SpanKind.MetaCode);\n\n            Span.CodeGenerator = new ExpressionCodeGenerator();\n            using (PushSpanConfig(span => span.CodeGenerator = new ExpressionCodeGenerator()))\n            {\n                if (!Balance(BalancingModes.NoErrorOnFailure |\n                             BalancingModes.BacktrackOnFailure |\n                             BalancingModes.AllowCommentsAndTemplates,\n                             VBSymbolType.LeftParenthesis,\n                             VBSymbolType.RightParenthesis,\n                             start))\n                {\n                    Context.OnError(start,\n                                    RazorResources.ParseError_Expected_EndOfBlock_Before_EOF,\n                                    RazorResources.BlockName_ExplicitExpression,\n                                    VBSymbol.GetSample(VBSymbolType.RightParenthesis),\n                                    VBSymbol.GetSample(VBSymbolType.LeftParenthesis));\n                    AcceptUntil(VBSymbolType.NewLine);\n                    AddMarkerSymbolIfNecessary();\n                    Output(SpanKind.Code);\n                    PutCurrentBack();\n                    return false;\n                }\n                else\n                {\n                    AddMarkerSymbolIfNecessary();\n                    Output(SpanKind.Code);\n                    Expected(VBSymbolType.RightParenthesis);\n                    Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;\n                    Span.CodeGenerator = SpanCodeGenerator.Null;\n                    Output(SpanKind.MetaCode);\n                    PutCurrentBack();\n                    return true;\n                }\n            }\n        }\n\n        private void ImplicitExpression()\n        {\n            Context.CurrentBlock.Type = BlockType.Expression;\n            Context.CurrentBlock.CodeGenerator = new ExpressionCodeGenerator();\n            using (PushSpanConfig(ImplictExpressionSpanConfig))\n            {\n                Expected(VBSymbolType.Identifier, VBSymbolType.Keyword);\n                Span.CodeGenerator = new ExpressionCodeGenerator();\n                while (!EndOfFile)\n                {\n                    switch (CurrentSymbol.Type)\n                    {\n                        case VBSymbolType.LeftParenthesis:\n                            SourceLocation start = CurrentLocation;\n                            AcceptAndMoveNext();\n\n                            Action<SpanBuilder> oldConfig = SpanConfig;\n                            using (PushSpanConfig())\n                            {\n                                ConfigureSpan(span =>\n                                {\n                                    oldConfig(span);\n                                    span.EditHandler.AcceptedCharacters = AcceptedCharacters.Any;\n                                });\n                                Balance(BalancingModes.AllowCommentsAndTemplates,\n                                        VBSymbolType.LeftParenthesis,\n                                        VBSymbolType.RightParenthesis,\n                                        start);\n                            }\n                            if (Optional(VBSymbolType.RightParenthesis))\n                            {\n                                Span.EditHandler.AcceptedCharacters = AcceptedCharacters.NonWhiteSpace;\n                            }\n                            break;\n                        case VBSymbolType.Dot:\n                            VBSymbol dot = CurrentSymbol;\n                            NextToken();\n                            if (At(VBSymbolType.Identifier) || At(VBSymbolType.Keyword))\n                            {\n                                Accept(dot);\n                                AcceptAndMoveNext();\n                            }\n                            else if (At(VBSymbolType.Transition))\n                            {\n                                VBSymbol at = CurrentSymbol;\n                                NextToken();\n                                if (At(VBSymbolType.Identifier) || At(VBSymbolType.Keyword))\n                                {\n                                    Accept(dot);\n                                    Accept(at);\n                                    AcceptAndMoveNext();\n                                }\n                                else\n                                {\n                                    PutBack(at);\n                                    PutBack(dot);\n                                }\n                            }\n                            else\n                            {\n                                PutCurrentBack();\n                                if (IsNested)\n                                {\n                                    Accept(dot);\n                                }\n                                else\n                                {\n                                    PutBack(dot);\n                                }\n                                return;\n                            }\n                            break;\n                        default:\n                            PutCurrentBack();\n                            return;\n                    }\n                }\n            }\n        }\n\n        protected void MapKeyword(VBKeyword keyword, Func<bool> action)\n        {\n            _keywordHandlers[keyword] = action;\n            Keywords.Add(keyword.ToString());\n        }\n\n        protected void MapDirective(string directive, Func<bool> action)\n        {\n            _directiveHandlers[directive] = action;\n            Keywords.Add(directive);\n        }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"This only occurs in Release builds, where this method is empty by design\")]\n        [Conditional(\"DEBUG\")]\n        protected void Assert(VBKeyword keyword)\n        {\n            Debug.Assert(CurrentSymbol.Type == VBSymbolType.Keyword && CurrentSymbol.Keyword == keyword);\n        }\n\n        protected bool At(VBKeyword keyword)\n        {\n            return At(VBSymbolType.Keyword) && CurrentSymbol.Keyword == keyword;\n        }\n\n        protected void OtherParserBlock()\n        {\n            OtherParserBlock(null, null);\n        }\n\n        protected void OtherParserBlock(string startSequence, string endSequence)\n        {\n            using (PushSpanConfig())\n            {\n                if (Span.Symbols.Count > 0)\n                {\n                    Output(SpanKind.Code);\n                }\n\n                Context.SwitchActiveParser();\n\n                bool old = DirectParentIsCode;\n                DirectParentIsCode = false;\n\n                Debug.Assert(ReferenceEquals(Context.ActiveParser, Context.MarkupParser));\n                if (!String.IsNullOrEmpty(startSequence) || !String.IsNullOrEmpty(endSequence))\n                {\n                    Context.MarkupParser.ParseSection(Tuple.Create(startSequence, endSequence), false);\n                }\n                else\n                {\n                    Context.MarkupParser.ParseBlock();\n                }\n\n                DirectParentIsCode = old;\n\n                Context.SwitchActiveParser();\n                EnsureCurrent();\n            }\n            Initialize(Span);\n        }\n\n        protected void HandleTransition(VBSymbol lastWhiteSpace)\n        {\n            if (At(VBSymbolType.RazorCommentTransition))\n            {\n                Accept(lastWhiteSpace);\n                RazorComment();\n                return;\n            }\n\n            // Check the next character\n            VBSymbol transition = CurrentSymbol;\n            NextToken();\n            if (At(VBSymbolType.LessThan) || At(VBSymbolType.Colon))\n            {\n                // Put the transition back\n                PutCurrentBack();\n                PutBack(transition);\n\n                // If we're in design-time mode, accept the whitespace, otherwise put it back\n                if (Context.DesignTimeMode)\n                {\n                    Accept(lastWhiteSpace);\n                }\n                else\n                {\n                    PutBack(lastWhiteSpace);\n                }\n\n                // Switch to markup\n                OtherParserBlock();\n            }\n            else if (At(VBSymbolType.Transition))\n            {\n                if (Context.IsWithin(BlockType.Template))\n                {\n                    Context.OnError(transition.Start, RazorResources.ParseError_InlineMarkup_Blocks_Cannot_Be_Nested);\n                }\n                Accept(lastWhiteSpace);\n                VBSymbol transition2 = CurrentSymbol;\n                NextToken();\n                if (At(VBSymbolType.LessThan) || At(VBSymbolType.Colon))\n                {\n                    PutCurrentBack();\n                    PutBack(transition2);\n                    PutBack(transition);\n                    Output(SpanKind.Code);\n\n                    // Start a template block and switch to Markup\n                    using (Context.StartBlock(BlockType.Template))\n                    {\n                        Context.CurrentBlock.CodeGenerator = new TemplateBlockCodeGenerator();\n                        OtherParserBlock();\n                        Initialize(Span);\n                    }\n                }\n                else\n                {\n                    Accept(transition);\n                    Accept(transition2);\n                }\n            }\n            else\n            {\n                Accept(lastWhiteSpace);\n\n                PutCurrentBack();\n                PutBack(transition);\n\n                bool old = IsNested;\n                IsNested = true;\n                NestedBlock();\n                IsNested = old;\n            }\n        }\n\n        protected override void OutputSpanBeforeRazorComment()\n        {\n            Output(SpanKind.Code);\n        }\n\n        protected bool ReservedWord()\n        {\n            Context.CurrentBlock.Type = BlockType.Directive;\n            Context.OnError(CurrentLocation, RazorResources.ParseError_ReservedWord, CurrentSymbol.Content);\n            Span.CodeGenerator = SpanCodeGenerator.Null;\n            AcceptAndMoveNext();\n            Output(SpanKind.MetaCode, AcceptedCharacters.None);\n            return true;\n        }\n\n        protected void NestedBlock()\n        {\n            using (PushSpanConfig())\n            {\n                Output(SpanKind.Code);\n\n                bool old = DirectParentIsCode;\n                DirectParentIsCode = true;\n\n                ParseBlock();\n\n                DirectParentIsCode = old;\n            }\n            Initialize(Span);\n        }\n\n        protected bool Required(VBSymbolType expected, string errorBase)\n        {\n            if (!Optional(expected))\n            {\n                Context.OnError(CurrentLocation, errorBase, GetCurrentSymbolDisplay());\n                return false;\n            }\n            return true;\n        }\n\n        protected bool Optional(VBKeyword keyword)\n        {\n            if (At(keyword))\n            {\n                AcceptAndMoveNext();\n                return true;\n            }\n            return false;\n        }\n\n        protected void AcceptVBSpaces()\n        {\n            Accept(ReadVBSpacesLazy());\n        }\n\n        protected IEnumerable<VBSymbol> ReadVBSpaces()\n        {\n            return ReadVBSpacesLazy().ToList();\n        }\n\n        public bool IsDirectiveDefined(string directive)\n        {\n            return _directiveHandlers.ContainsKey(directive);\n        }\n\n        private IEnumerable<VBSymbol> ReadVBSpacesLazy()\n        {\n            foreach (var symbol in ReadWhileLazy(sym => sym.Type == VBSymbolType.WhiteSpace))\n            {\n                yield return symbol;\n            }\n            while (At(VBSymbolType.LineContinuation))\n            {\n                int bookmark = CurrentLocation.AbsoluteIndex;\n                VBSymbol under = CurrentSymbol;\n                NextToken();\n                if (At(VBSymbolType.NewLine))\n                {\n                    yield return under;\n                    yield return CurrentSymbol;\n                    NextToken();\n                    foreach (var symbol in ReadVBSpaces())\n                    {\n                        yield return symbol;\n                    }\n                }\n                else\n                {\n                    Context.Source.Position = bookmark;\n                    NextToken();\n                    yield break;\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/VBLanguageCharacteristics.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Parser\n{\n    public class VBLanguageCharacteristics : LanguageCharacteristics<VBTokenizer, VBSymbol, VBSymbolType>\n    {\n        private static readonly VBLanguageCharacteristics _instance = new VBLanguageCharacteristics();\n\n        private VBLanguageCharacteristics()\n        {\n        }\n\n        public static VBLanguageCharacteristics Instance\n        {\n            get { return _instance; }\n        }\n\n        public override VBTokenizer CreateTokenizer(ITextDocument source)\n        {\n            return new VBTokenizer(source);\n        }\n\n        public override string GetSample(VBSymbolType type)\n        {\n            return VBSymbol.GetSample(type);\n        }\n\n        public override VBSymbolType FlipBracket(VBSymbolType bracket)\n        {\n            switch (bracket)\n            {\n                case VBSymbolType.LeftBrace:\n                    return VBSymbolType.RightBrace;\n                case VBSymbolType.LeftBracket:\n                    return VBSymbolType.RightBracket;\n                case VBSymbolType.LeftParenthesis:\n                    return VBSymbolType.RightParenthesis;\n                case VBSymbolType.RightBrace:\n                    return VBSymbolType.LeftBrace;\n                case VBSymbolType.RightBracket:\n                    return VBSymbolType.LeftBracket;\n                case VBSymbolType.RightParenthesis:\n                    return VBSymbolType.LeftParenthesis;\n                default:\n                    return VBSymbolType.Unknown;\n            }\n        }\n\n        public override VBSymbol CreateMarkerSymbol(SourceLocation location)\n        {\n            return new VBSymbol(location, String.Empty, VBSymbolType.Unknown);\n        }\n\n        public override VBSymbolType GetKnownSymbolType(KnownSymbolType type)\n        {\n            switch (type)\n            {\n                case KnownSymbolType.CommentStart:\n                    return VBSymbolType.RazorCommentTransition;\n                case KnownSymbolType.CommentStar:\n                    return VBSymbolType.RazorCommentStar;\n                case KnownSymbolType.CommentBody:\n                    return VBSymbolType.RazorComment;\n                case KnownSymbolType.Identifier:\n                    return VBSymbolType.Identifier;\n                case KnownSymbolType.Keyword:\n                    return VBSymbolType.Keyword;\n                case KnownSymbolType.NewLine:\n                    return VBSymbolType.NewLine;\n                case KnownSymbolType.Transition:\n                    return VBSymbolType.Transition;\n                case KnownSymbolType.WhiteSpace:\n                    return VBSymbolType.WhiteSpace;\n                default:\n                    return VBSymbolType.Unknown;\n            }\n        }\n\n        protected override VBSymbol CreateSymbol(SourceLocation location, string content, VBSymbolType type, IEnumerable<RazorError> errors)\n        {\n            return new VBSymbol(location, content, type, errors);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Parser/WhitespaceRewriter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Text;\n\nnamespace System.Web.Razor.Parser\n{\n    internal class WhiteSpaceRewriter : MarkupRewriter\n    {\n        public WhiteSpaceRewriter(Action<SpanBuilder, SourceLocation, string> markupSpanFactory) : base(markupSpanFactory)\n        {\n        }\n\n        protected override bool CanRewrite(Block block)\n        {\n            return block.Type == BlockType.Expression && Parent != null;\n        }\n\n        //public override void VisitBlock(Block block)\n        //{\n        //    BlockBuilder parent = null;\n        //    if (_blocks.Count > 0)\n        //    {\n        //        parent = _blocks.Peek();\n        //    }\n        //    BlockBuilder newBlock = new BlockBuilder(block);\n        //    newBlock.Children.Clear();\n        //    _blocks.Push(newBlock);\n        //    if (block.Type == BlockType.Expression && parent != null)\n        //    {\n        //        VisitExpressionBlock(block, parent);\n        //    }\n        //    else\n        //    {\n        //        base.VisitBlock(block);\n        //    }\n        //    if (_blocks.Count > 1)\n        //    {\n        //        parent.Children.Add(_blocks.Pop().Build());\n        //    }\n        //}\n\n        //public override void VisitSpan(Span span)\n        //{\n        //    Debug.Assert(_blocks.Count > 0);\n        //    _blocks.Peek().Children.Add(span);\n        //}\n\n        protected override SyntaxTreeNode RewriteBlock(BlockBuilder parent, Block block)\n        {\n            BlockBuilder newBlock = new BlockBuilder(block);\n            newBlock.Children.Clear();\n            Span ws = block.Children.FirstOrDefault() as Span;\n            IEnumerable<SyntaxTreeNode> newNodes = block.Children;\n            if (ws.Content.All(Char.IsWhiteSpace))\n            {\n                // Add this node to the parent\n                SpanBuilder builder = new SpanBuilder(ws);\n                builder.ClearSymbols();\n                FillSpan(builder, ws.Start, ws.Content);\n                parent.Children.Add(builder.Build());\n\n                // Remove the old whitespace node\n                newNodes = block.Children.Skip(1);\n            }\n\n            foreach (SyntaxTreeNode node in newNodes)\n            {\n                newBlock.Children.Add(node);\n            }\n            return newBlock.Build();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/ParserResults.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.Razor\n{\n    /// <summary>\n    /// Represents the results of parsing a Razor document\n    /// </summary>\n    public class ParserResults\n    {\n        public ParserResults(Block document, IList<RazorError> parserErrors)\n            : this(parserErrors == null || parserErrors.Count == 0, document, parserErrors)\n        {\n        }\n\n        protected ParserResults(bool success, Block document, IList<RazorError> errors)\n        {\n            Success = success;\n            Document = document;\n            ParserErrors = errors ?? new List<RazorError>();\n        }\n\n        /// <summary>\n        /// Indicates if parsing was successful (no errors)\n        /// </summary>\n        public bool Success { get; private set; }\n\n        /// <summary>\n        /// The root node in the document's syntax tree\n        /// </summary>\n        public Block Document { get; private set; }\n\n        /// <summary>\n        /// The list of errors which occurred during parsing.\n        /// </summary>\n        public IList<RazorError> ParserErrors { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/PartialParseResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.Razor\n{\n    // Flags:\n    //  Provisional, ContextChanged, Accepted, Rejected\n    //  000001 1  - Rejected,\n    //  000010 2  - Accepted\n    //  000100 4  - Provisional\n    //  001000 8  - Context Changed\n    //  010000 16 - Auto Complete Block\n\n    /// <summary>\n    /// The result of attempting an incremental parse\n    /// </summary>\n    /// <remarks>\n    /// Either the Accepted or Rejected flag is ALWAYS set.  \n    /// Additionally, Provisional may be set with Accepted and SpanContextChanged may be set with Rejected.\n    /// Provisional may NOT be set with Rejected and SpanContextChanged may NOT be set with Accepted.\n    /// </remarks>\n    [Flags]\n    [SuppressMessage(\"Microsoft.Naming\", \"CA1714:FlagsEnumsShouldHavePluralNames\", Justification = \"The singular name is more appropriate here\")]\n    public enum PartialParseResult\n    {\n        /// <summary>\n        /// Indicates that the edit could not be accepted and that a reparse is underway.\n        /// </summary>\n        Rejected = 1,\n\n        /// <summary>\n        /// Indicates that the edit was accepted and has been added to the parse tree\n        /// </summary>\n        Accepted = 2,\n\n        /// <summary>\n        /// Indicates that the edit was accepted, but that a reparse should be forced when idle time is available\n        /// since the edit may be misclassified\n        /// </summary>\n        /// <remarks>\n        /// This generally occurs when a \".\" is typed in an Implicit Expression, since editors require that this\n        /// be assigned to Code in order to properly support features like IntelliSense.  However, if no further edits\n        /// occur following the \".\", it should be treated as Markup.\n        /// </remarks>\n        Provisional = 4,\n\n        /// <summary>\n        /// Indicates that the edit caused a change in the span's context and that if any statement completions were active prior to starting this\n        /// partial parse, they should be reinitialized.\n        /// </summary>\n        SpanContextChanged = 8,\n\n        /// <summary>\n        /// Indicates that the edit requires an auto completion to occur\n        /// </summary>\n        AutoCompleteBlock = 16\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Properties/AssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\n\n// General Information about an assembly is controlled through the following \n// set of attributes. Change these attribute values to modify the information\n// associated with an assembly.\n\n[assembly: AssemblyTitle(\"System.Web.Razor\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: InternalsVisibleTo(\"System.Web.Razor.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n[assembly: InternalsVisibleTo(\"System.Web.WebPages.Razor.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n[assembly: InternalsVisibleTo(\"Microsoft.WebPages.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n"
  },
  {
    "path": "src/System.Web.Razor/RazorCodeLanguage.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\n\nnamespace System.Web.Razor\n{\n    /// <summary>\n    /// Represents a code language in Razor.\n    /// </summary>\n    public abstract class RazorCodeLanguage\n    {\n        private static IDictionary<string, RazorCodeLanguage> _services = new Dictionary<string, RazorCodeLanguage>(StringComparer.OrdinalIgnoreCase)\n        {\n            { \"cshtml\", new CSharpRazorCodeLanguage() },\n            { \"vbhtml\", new VBRazorCodeLanguage() }\n        };\n\n        /// <summary>\n        /// Gets the list of registered languages mapped to file extensions (without a \".\")\n        /// </summary>\n        public static IDictionary<string, RazorCodeLanguage> Languages\n        {\n            get { return _services; }\n        }\n\n        /// <summary>\n        /// The name of the language (for use in System.Web.Compilation.BuildProvider.GetDefaultCompilerTypeForLanguage)\n        /// </summary>\n        public abstract string LanguageName { get; }\n\n        /// <summary>\n        /// The type of the CodeDOM provider for this language\n        /// </summary>\n        public abstract Type CodeDomProviderType { get; }\n\n        /// <summary>\n        /// Gets the RazorCodeLanguage registered for the specified file extension\n        /// </summary>\n        /// <param name=\"fileExtension\">The extension, with or without a \".\"</param>\n        /// <returns>The language registered for that extension</returns>\n        public static RazorCodeLanguage GetLanguageByExtension(string fileExtension)\n        {\n            RazorCodeLanguage service = null;\n            Languages.TryGetValue(fileExtension.TrimStart('.'), out service);\n            return service;\n        }\n\n        /// <summary>\n        /// Constructs the code parser.  Must return a new instance on EVERY call to ensure thread-safety\n        /// </summary>\n        public abstract ParserBase CreateCodeParser();\n\n        /// <summary>\n        /// Constructs the code generator.  Must return a new instance on EVERY call to ensure thread-safety\n        /// </summary>\n        public abstract RazorCodeGenerator CreateCodeGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/RazorDebugHelpers.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n#if DEBUG\n\nusing System.CodeDom;\nusing System.CodeDom.Compiler;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.IO;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Text;\n\nnamespace System.Web.Razor\n{\n    internal static class RazorDebugHelpers\n    {\n        private static bool _outputDebuggingEnabled = IsDebuggingEnabled();\n\n        private static readonly Dictionary<char, string> _printableEscapeChars = new Dictionary<char, string>\n        {\n            { '\\0', \"\\\\0\" },\n            { '\\\\', \"\\\\\\\\\" },\n            { '\\'', \"'\" },\n            { '\\\"', \"\\\\\\\"\" },\n            { '\\a', \"\\\\a\" },\n            { '\\b', \"\\\\b\" },\n            { '\\f', \"\\\\f\" },\n            { '\\n', \"\\\\n\" },\n            { '\\r', \"\\\\r\" },\n            { '\\t', \"\\\\t\" },\n            { '\\v', \"\\\\v\" },\n        };\n\n        internal static bool OutputDebuggingEnabled\n        {\n            get { return _outputDebuggingEnabled; }\n        }\n\n        [SuppressMessage(\"Microsoft.Security\", \"CA2141:TransparentMethodsMustNotSatisfyLinkDemandsFxCopRule\", Justification = \"This is debug only\")]\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"This is debug only\")]\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1305:SpecifyIFormatProvider\", MessageId = \"System.IO.StringWriter.#ctor\", Justification = \"This is debug only\")]\n        internal static void WriteGeneratedCode(string sourceFile, CodeCompileUnit codeCompileUnit)\n        {\n            if (!OutputDebuggingEnabled)\n            {\n                return;\n            }\n\n            RunTask(() =>\n            {\n                string extension = Path.GetExtension(sourceFile);\n                RazorCodeLanguage language = RazorCodeLanguage.GetLanguageByExtension(extension);\n                CodeDomProvider provider = CodeDomProvider.CreateProvider(language.LanguageName);\n\n                using (var writer = new StringWriter())\n                {\n                    // Trim the html part of cshtml or vbhtml\n                    string outputExtension = extension.Substring(0, 3);\n                    string outputFileName = Normalize(sourceFile) + \"_generated\" + outputExtension;\n                    string outputPath = Path.Combine(Path.GetDirectoryName(sourceFile), outputFileName);\n\n                    // REVIEW: Do these options need to be tweaked?\n                    provider.GenerateCodeFromCompileUnit(codeCompileUnit, writer, new CodeGeneratorOptions());\n                    File.WriteAllText(outputPath, writer.ToString());\n                }\n            });\n        }\n\n        internal static void WriteDebugTree(string sourceFile, Block document, PartialParseResult result, TextChange change, RazorEditorParser parser, bool treeStructureChanged)\n        {\n            if (!OutputDebuggingEnabled)\n            {\n                return;\n            }\n\n            RunTask(() =>\n            {\n                string outputFileName = Normalize(sourceFile) + \"_tree\";\n                string outputPath = Path.Combine(Path.GetDirectoryName(sourceFile), outputFileName);\n\n                var treeBuilder = new StringBuilder();\n                WriteTree(document, treeBuilder);\n                treeBuilder.AppendLine();\n                treeBuilder.AppendFormat(CultureInfo.CurrentCulture, \"Last Change: {0}\", change);\n                treeBuilder.AppendLine();\n                treeBuilder.AppendFormat(CultureInfo.CurrentCulture, \"Normalized To: {0}\", change.Normalize());\n                treeBuilder.AppendLine();\n                treeBuilder.AppendFormat(CultureInfo.CurrentCulture, \"Partial Parse Result: {0}\", result);\n                treeBuilder.AppendLine();\n                if (result.HasFlag(PartialParseResult.Rejected))\n                {\n                    treeBuilder.AppendFormat(CultureInfo.CurrentCulture, \"Tree Structure Changed: {0}\", treeStructureChanged);\n                    treeBuilder.AppendLine();\n                }\n                if (result.HasFlag(PartialParseResult.AutoCompleteBlock))\n                {\n                    treeBuilder.AppendFormat(CultureInfo.CurrentCulture, \"Auto Complete Insert String: \\\"{0}\\\"\", parser.GetAutoCompleteString());\n                    treeBuilder.AppendLine();\n                }\n                File.WriteAllText(outputPath, treeBuilder.ToString());\n            });\n        }\n\n        private static void WriteTree(SyntaxTreeNode node, StringBuilder treeBuilder, int depth = 0)\n        {\n            if (node == null)\n            {\n                return;\n            }\n            if (depth > 1)\n            {\n                WriteIndent(treeBuilder, depth);\n            }\n\n            if (depth > 0)\n            {\n                treeBuilder.Append(\"|-- \");\n            }\n\n            treeBuilder.AppendLine(ConvertEscapseSequences(node.ToString()));\n            if (node.IsBlock)\n            {\n                foreach (SyntaxTreeNode child in ((Block)node).Children)\n                {\n                    WriteTree(child, treeBuilder, depth + 1);\n                }\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"This is debug only\")]\n        [SuppressMessage(\"Microsoft.Web.FxCop\", \"MW1202:DoNotUseProblematicTaskTypes\", Justification = \"This rule is not applicable to this assembly.\")]\n        [SuppressMessage(\"Microsoft.Web.FxCop\", \"MW1201:DoNotCallProblematicMethodsOnTask\", Justification = \"This rule is not applicable to this assembly.\")]\n        private static void RunTask(Action action)\n        {\n            Task.Factory.StartNew(() =>\n            {\n                try\n                {\n                    action();\n                }\n                catch\n                {\n                    // Catch all errors since this is just a debug helper\n                }\n            });\n        }\n\n        private static void WriteIndent(StringBuilder sb, int depth)\n        {\n            for (int i = 0; i < (depth - 1) * 4; ++i)\n            {\n                if (i % 4 == 0)\n                {\n                    sb.Append(\"|\");\n                }\n                else\n                {\n                    sb.Append(\" \");\n                }\n            }\n        }\n\n        private static string Normalize(string path)\n        {\n            return Path.GetFileName(path).Replace('.', '_');\n        }\n\n        private static string ConvertEscapseSequences(string value)\n        {\n            StringBuilder sb = new StringBuilder();\n            foreach (var ch in value)\n            {\n                sb.Append(GetCharValue(ch));\n            }\n            return sb.ToString();\n        }\n\n        private static string GetCharValue(char ch)\n        {\n            string value;\n            if (_printableEscapeChars.TryGetValue(ch, out value))\n            {\n                return value;\n            }\n            return ch.ToString();\n        }\n\n        private static bool IsDebuggingEnabled()\n        {\n            bool enabled;\n            return Boolean.TryParse(Environment.GetEnvironmentVariable(\"RAZOR_DEBUG\"), out enabled) && enabled;\n        }\n    }\n}\n\n#endif\n"
  },
  {
    "path": "src/System.Web.Razor/RazorDirectiveAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Razor\n{\n    /// <summary>\n    /// Specifies a Razor directive that is rendered as an attribute on the generated class. \n    /// </summary>\n    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]\n    public sealed class RazorDirectiveAttribute : Attribute\n    {\n        private readonly object _typeId = new object();\n\n        public RazorDirectiveAttribute(string name, string value)\n        {\n            if (String.IsNullOrEmpty(name))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"name\");\n            }\n\n            Name = name;\n            Value = value;\n        }\n\n        public override object TypeId\n        {\n            get { return _typeId; }\n        }\n\n        public string Name { get; private set; }\n\n        public string Value { get; private set; }\n\n        public override bool Equals(object obj)\n        {\n            RazorDirectiveAttribute attribute = obj as RazorDirectiveAttribute;\n            return attribute != null &&\n                   Name.Equals(attribute.Name, StringComparison.OrdinalIgnoreCase) &&\n                   StringComparer.OrdinalIgnoreCase.Equals(Value, attribute.Value);\n        }\n\n        public override int GetHashCode()\n        {\n            return (StringComparer.OrdinalIgnoreCase.GetHashCode(Name) * 31) +\n                   (Value == null ? 0 : StringComparer.OrdinalIgnoreCase.GetHashCode(Value));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/RazorEditorParser.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Threading;\nusing System.Web.Razor.Editor;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Text;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Razor\n{\n    /// <summary>\n    /// Parser used by editors to avoid reparsing the entire document on each text change\n    /// </summary>\n    /// <remarks>\n    /// This parser is designed to allow editors to avoid having to worry about incremental parsing.\n    /// The CheckForStructureChanges method can be called with every change made by a user in an editor and\n    /// the parser will provide a result indicating if it was able to incrementally reparse the document.\n    /// \n    /// The general workflow for editors with this parser is:\n    /// 0. User edits document\n    /// 1. Editor builds TextChange structure describing the edit and providing a reference to the _updated_ text buffer\n    /// 2. Editor calls CheckForStructureChanges passing in that change.\n    /// 3. Parser determines if the change can be simply applied to an existing parse tree node\n    ///   a.  If it can, the Parser updates its parse tree and returns PartialParseResult.Accepted\n    ///   b.  If it can not, the Parser starts a background parse task and return PartialParseResult.Rejected\n    /// NOTE: Additional flags can be applied to the PartialParseResult, see that enum for more details.  However,\n    ///       the Accepted or Rejected flags will ALWAYS be present\n    /// \n    /// A change can only be incrementally parsed if a single, unique, Span (see System.Web.Razor.Parser.SyntaxTree) in the syntax tree can\n    /// be identified as owning the entire change.  For example, if a change overlaps with multiple spans, the change cannot be\n    /// parsed incrementally and a full reparse is necessary.  A Span \"owns\" a change if the change occurs either a) entirely\n    /// within it's boundaries or b) it is a pure insertion (see TextChange) at the end of a Span whose CanGrow flag (see Span) is\n    /// true.\n    /// \n    /// Even if a single unique Span owner can be identified, it's possible the edit will cause the Span to split or merge with other\n    /// Spans, in which case, a full reparse is necessary to identify the extent of the changes to the tree.\n    /// \n    /// When the RazorEditorParser returns Accepted, it updates CurrentParseTree immediately.  However, the editor is expected to\n    /// update it's own data structures independently.  It can use CurrentParseTree to do this, as soon as the editor returns from\n    /// CheckForStructureChanges, but it should (ideally) have logic for doing so without needing the new tree.\n    /// \n    /// When Rejected is returned by CheckForStructureChanges, a background parse task has _already_ been started.  When that task\n    /// finishes, the DocumentStructureChanged event will be fired containing the new generated code, parse tree and a reference to\n    /// the original TextChange that caused the reparse, to allow the editor to resolve the new tree against any changes made since \n    /// calling CheckForStructureChanges.\n    /// \n    /// If a call to CheckForStructureChanges occurs while a reparse is already in-progress, the reparse is cancelled IMMEDIATELY\n    /// and Rejected is returned without attempting to reparse.  This means that if a conusmer calls CheckForStructureChanges, which\n    /// returns Rejected, then calls it again before DocumentParseComplete is fired, it will only recieve one DocumentParseComplete\n    /// event, for the second change.\n    /// </remarks>\n    public class RazorEditorParser : IDisposable\n    {\n        // Lock for this document\n        private Span _lastChangeOwner;\n        private Span _lastAutoCompleteSpan;\n        private BackgroundParser _parser;\n        private Block _currentParseTree;\n\n        /// <summary>\n        /// Constructs the editor parser.  One instance should be used per active editor.  This\n        /// instance _can_ be shared among reparses, but should _never_ be shared between documents.\n        /// </summary>\n        /// <param name=\"host\">The <see cref=\"RazorEngineHost\"/> which defines the environment in which the generated code will live.  <see cref=\"F:RazorEngineHost.DesignTimeMode\"/> should be set if design-time code mappings are desired</param>\n        /// <param name=\"sourceFileName\">The physical path to use in line pragmas</param>\n        public RazorEditorParser(RazorEngineHost host, string sourceFileName)\n        {\n            if (host == null)\n            {\n                throw new ArgumentNullException(\"host\");\n            }\n            if (String.IsNullOrEmpty(sourceFileName))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"sourceFileName\");\n            }\n\n            Host = host;\n            FileName = sourceFileName;\n            _parser = new BackgroundParser(host, sourceFileName);\n            _parser.ResultsReady += (sender, args) => OnDocumentParseComplete(args);\n            _parser.Start();\n        }\n\n        /// <summary>\n        /// Event fired when a full reparse of the document completes\n        /// </summary>\n        public event EventHandler<DocumentParseCompleteEventArgs> DocumentParseComplete;\n\n        public RazorEngineHost Host { get; private set; }\n        public string FileName { get; private set; }\n        public bool LastResultProvisional { get; private set; }\n        public Block CurrentParseTree\n        {\n            get { return _currentParseTree; }\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Justification = \"Since this method is heavily affected by side-effects, particularly calls to CheckForStructureChanges, it should not be made into a property\")]\n        public virtual string GetAutoCompleteString()\n        {\n            if (_lastAutoCompleteSpan != null)\n            {\n                AutoCompleteEditHandler editHandler = _lastAutoCompleteSpan.EditHandler as AutoCompleteEditHandler;\n                if (editHandler != null)\n                {\n                    return editHandler.AutoCompleteString;\n                }\n            }\n            return null;\n        }\n\n        /// <summary>\n        /// Determines if a change will cause a structural change to the document and if not, applies it to the existing tree.\n        /// If a structural change would occur, automatically starts a reparse\n        /// </summary>\n        /// <remarks>\n        /// NOTE: The initial incremental parsing check and actual incremental parsing (if possible) occurs\n        /// on the callers thread.  However, if a full reparse is needed, this occurs on a background thread.\n        /// </remarks>\n        /// <param name=\"change\">The change to apply to the parse tree</param>\n        /// <returns>A PartialParseResult value indicating the result of the incremental parse</returns>\n        public virtual PartialParseResult CheckForStructureChanges(TextChange change)\n        {\n            // Validate the change\n            long? elapsedMs = null;\n#if EDITOR_TRACING\n            Stopwatch sw = new Stopwatch();\n            sw.Start();\n#endif\n            RazorEditorTrace.TraceLine(RazorResources.Trace_EditorReceivedChange, Path.GetFileName(FileName), change);\n            if (change.NewBuffer == null)\n            {\n                throw new ArgumentException(String.Format(CultureInfo.CurrentUICulture,\n                                                          RazorResources.Structure_Member_CannotBeNull,\n                                                          \"Buffer\",\n                                                          \"TextChange\"), \"change\");\n            }\n\n            PartialParseResult result = PartialParseResult.Rejected;\n\n            // If there isn't already a parse underway, try partial-parsing\n            string changeString = String.Empty;\n            using (_parser.SynchronizeMainThreadState())\n            {\n                // Capture the string value of the change while we're synchronized\n                changeString = change.ToString();\n\n                // Check if we can partial-parse\n                if (CurrentParseTree != null && _parser.IsIdle)\n                {\n                    result = TryPartialParse(change);\n                }\n            }\n\n            // If partial parsing failed or there were outstanding parser tasks, start a full reparse\n            if (result.HasFlag(PartialParseResult.Rejected))\n            {\n                _parser.QueueChange(change);\n            }\n\n            // Otherwise, remember if this was provisionally accepted for next partial parse\n            LastResultProvisional = result.HasFlag(PartialParseResult.Provisional);\n            VerifyFlagsAreValid(result);\n\n#if EDITOR_TRACING\n            sw.Stop();\n            elapsedMs = sw.ElapsedMilliseconds;\n            sw.Reset();\n#endif\n            RazorEditorTrace.TraceLine(RazorResources.Trace_EditorProcessedChange, Path.GetFileName(FileName), changeString, elapsedMs.HasValue ? elapsedMs.Value.ToString(CultureInfo.InvariantCulture) : \"?\", result.ToString());\n            return result;\n        }\n\n        /// <summary>\n        /// Disposes of this parser.  Should be called when the editor window is closed and the document is unloaded.\n        /// </summary>\n        public void Dispose()\n        {\n            Dispose(true);\n            GC.SuppressFinalize(this);\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2213:DisposableFieldsShouldBeDisposed\", MessageId = \"_cancelTokenSource\", Justification = \"The cancellation token is owned by the worker thread, so it is disposed there\")]\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2213:DisposableFieldsShouldBeDisposed\", MessageId = \"_changeReceived\", Justification = \"The change received event is owned by the worker thread, so it is disposed there\")]\n        protected virtual void Dispose(bool disposing)\n        {\n            if (disposing)\n            {\n                _parser.Dispose();\n            }\n        }\n\n        private PartialParseResult TryPartialParse(TextChange change)\n        {\n            PartialParseResult result = PartialParseResult.Rejected;\n\n            // Try the last change owner\n            if (_lastChangeOwner != null && _lastChangeOwner.EditHandler.OwnsChange(_lastChangeOwner, change))\n            {\n                EditResult editResult = _lastChangeOwner.EditHandler.ApplyChange(_lastChangeOwner, change);\n                result = editResult.Result;\n                if (!editResult.Result.HasFlag(PartialParseResult.Rejected))\n                {\n                    _lastChangeOwner.ReplaceWith(editResult.EditedSpan);\n                }\n\n                return result;\n            }\n\n            // Locate the span responsible for this change\n            _lastChangeOwner = CurrentParseTree.LocateOwner(change);\n\n            if (LastResultProvisional)\n            {\n                // Last change owner couldn't accept this, so we must do a full reparse\n                result = PartialParseResult.Rejected;\n            }\n            else if (_lastChangeOwner != null)\n            {\n                EditResult editRes = _lastChangeOwner.EditHandler.ApplyChange(_lastChangeOwner, change);\n                result = editRes.Result;\n                if (!editRes.Result.HasFlag(PartialParseResult.Rejected))\n                {\n                    _lastChangeOwner.ReplaceWith(editRes.EditedSpan);\n                }\n                if (result.HasFlag(PartialParseResult.AutoCompleteBlock))\n                {\n                    _lastAutoCompleteSpan = _lastChangeOwner;\n                }\n                else\n                {\n                    _lastAutoCompleteSpan = null;\n                }\n            }\n            return result;\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Exceptions are being caught here intentionally\")]\n        private void OnDocumentParseComplete(DocumentParseCompleteEventArgs args)\n        {\n            using (_parser.SynchronizeMainThreadState())\n            {\n                _currentParseTree = args.GeneratorResults.Document;\n                _lastChangeOwner = null;\n            }\n\n            Debug.Assert(args != null, \"Event arguments cannot be null\");\n            EventHandler<DocumentParseCompleteEventArgs> handler = DocumentParseComplete;\n            if (handler != null)\n            {\n                try\n                {\n                    handler(this, args);\n                }\n                catch (Exception ex)\n                {\n                    Debug.WriteLine(\"[RzEd] Document Parse Complete Handler Threw: \" + ex.ToString());\n                }\n            }\n        }\n\n        [Conditional(\"DEBUG\")]\n        private static void VerifyFlagsAreValid(PartialParseResult result)\n        {\n            Debug.Assert(result.HasFlag(PartialParseResult.Accepted) ||\n                         result.HasFlag(PartialParseResult.Rejected),\n                         \"Partial Parse result does not have either of Accepted or Rejected flags set\");\n            Debug.Assert(result.HasFlag(PartialParseResult.Rejected) ||\n                         !result.HasFlag(PartialParseResult.SpanContextChanged),\n                         \"Partial Parse result was Accepted AND had SpanContextChanged flag set\");\n            Debug.Assert(result.HasFlag(PartialParseResult.Rejected) ||\n                         !result.HasFlag(PartialParseResult.AutoCompleteBlock),\n                         \"Partial Parse result was Accepted AND had AutoCompleteBlock flag set\");\n            Debug.Assert(result.HasFlag(PartialParseResult.Accepted) ||\n                         !result.HasFlag(PartialParseResult.Provisional),\n                         \"Partial Parse result was Rejected AND had Provisional flag set\");\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/RazorEngineHost.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\n\nnamespace System.Web.Razor\n{\n    /// <summary>\n    /// Defines the environment in which a Razor template will live\n    /// </summary>\n    /// <remarks>\n    /// The host defines the following things:\n    /// * What method names will be used for rendering markup, expressions etc.  For example \"Write\", \"WriteLiteral\"\n    /// * The namespace imports to be added to every page generated via this host\n    /// * The default Base Class to inherit the generated class from\n    /// * The default Class Name and Namespace for the generated class (can be overridden by parameters in RazorTemplateEngine.GeneratedCode)\n    /// * The language of the code in a Razor page\n    /// * The markup, code parsers and code generators to use (the system will select defaults, but a Host gets a change to augment them)\n    ///     ** See DecorateNNN methods\n    /// * Additional code to add to the generated code (see PostProcessGeneratedCode)\n    /// </remarks>\n    public class RazorEngineHost\n    {\n        internal const string InternalDefaultClassName = \"__CompiledTemplate\";\n        internal const string InternalDefaultNamespace = \"Razor\";\n\n        private bool _instrumentationActive = false;\n        private Func<ParserBase> _markupParserFactory;\n\n        private int _tabSize = 4;\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2214:DoNotCallOverridableMethodsInConstructors\", Justification = \"The code path is safe, it is a property setter and not dependent on other state\")]\n        protected RazorEngineHost()\n        {\n            GeneratedClassContext = GeneratedClassContext.Default;\n            NamespaceImports = new HashSet<string>();\n            DesignTimeMode = false;\n            DefaultNamespace = InternalDefaultNamespace;\n            DefaultClassName = InternalDefaultClassName;\n            EnableInstrumentation = false;\n        }\n\n        /// <summary>\n        /// Creates a host which uses the specified code language and the HTML markup language\n        /// </summary>\n        /// <param name=\"codeLanguage\">The code language to use</param>\n        public RazorEngineHost(RazorCodeLanguage codeLanguage)\n            : this(codeLanguage, () => new HtmlMarkupParser())\n        {\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2214:DoNotCallOverridableMethodsInConstructors\", Justification = \"The code path is safe, it is a property setter and not dependent on other state\")]\n        public RazorEngineHost(RazorCodeLanguage codeLanguage, Func<ParserBase> markupParserFactory)\n            : this()\n        {\n            if (codeLanguage == null)\n            {\n                throw new ArgumentNullException(\"codeLanguage\");\n            }\n            if (markupParserFactory == null)\n            {\n                throw new ArgumentNullException(\"markupParserFactory\");\n            }\n\n            CodeLanguage = codeLanguage;\n            _markupParserFactory = markupParserFactory;\n        }\n\n        /// <summary>\n        /// Details about the methods and types that should be used to generate code for Razor constructs\n        /// </summary>\n        public virtual GeneratedClassContext GeneratedClassContext { get; set; }\n\n        /// <summary>\n        /// A list of namespaces to import in the generated file\n        /// </summary>\n        public virtual ISet<string> NamespaceImports { get; private set; }\n\n        /// <summary>\n        /// The base-class of the generated class\n        /// </summary>\n        public virtual string DefaultBaseClass { get; set; }\n\n        /// <summary>\n        /// Indiciates if the parser and code generator should run in design-time mode\n        /// </summary>\n        public virtual bool DesignTimeMode { get; set; }\n\n        /// <summary>\n        /// The name of the generated class\n        /// </summary>\n        public virtual string DefaultClassName { get; set; }\n\n        /// <summary>\n        /// The namespace which will contain the generated class\n        /// </summary>\n        public virtual string DefaultNamespace { get; set; }\n\n        /// <summary>\n        /// Boolean indicating if helper methods should be instance methods or static methods\n        /// </summary>\n        public virtual bool StaticHelpers { get; set; }\n\n        /// <summary>\n        /// The language of the code within the Razor template.\n        /// </summary>\n        public virtual RazorCodeLanguage CodeLanguage { get; protected set; }\n\n        /// <summary>\n        /// Boolean indicating if instrumentation code should be injected into the output page\n        /// </summary>\n        public virtual bool EnableInstrumentation\n        {\n            // Always disable instrumentation in DesignTimeMode.\n            get { return !DesignTimeMode && _instrumentationActive; }\n            set { _instrumentationActive = value; }\n        }\n\n        /// <summary>\n        /// Gets or sets whether the design time editor is using tabs or spaces for indentation.\n        /// </summary>\n        public virtual bool IsIndentingWithTabs { get; set; }\n\n        /// <summary>\n        /// Tab size used by the hosting editor, when indenting with tabs.\n        /// </summary>\n        public virtual int TabSize\n        {\n            get\n            {\n                return _tabSize;\n            }\n\n            set\n            {\n                _tabSize = Math.Max(value, 1);\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets the path to use for this document when generating Instrumentation calls\n        /// </summary>\n        public virtual string InstrumentedSourceFilePath { get; set; }\n\n        /// <summary>\n        /// Constructs the markup parser.  Must return a new instance on EVERY call to ensure thread-safety\n        /// </summary>\n        public virtual ParserBase CreateMarkupParser()\n        {\n            if (_markupParserFactory != null)\n            {\n                return _markupParserFactory();\n            }\n            return null;\n        }\n\n        /// <summary>\n        /// Gets an instance of the code parser and is provided an opportunity to decorate or replace it\n        /// </summary>\n        /// <param name=\"incomingCodeParser\">The code parser</param>\n        /// <returns>Either the same code parser, after modifications, or a different code parser</returns>\n        public virtual ParserBase DecorateCodeParser(ParserBase incomingCodeParser)\n        {\n            if (incomingCodeParser == null)\n            {\n                throw new ArgumentNullException(\"incomingCodeParser\");\n            }\n            return incomingCodeParser;\n        }\n\n        /// <summary>\n        /// Gets an instance of the markup parser and is provided an opportunity to decorate or replace it\n        /// </summary>\n        /// <param name=\"incomingMarkupParser\">The markup parser</param>\n        /// <returns>Either the same markup parser, after modifications, or a different markup parser</returns>\n        public virtual ParserBase DecorateMarkupParser(ParserBase incomingMarkupParser)\n        {\n            if (incomingMarkupParser == null)\n            {\n                throw new ArgumentNullException(\"incomingMarkupParser\");\n            }\n            return incomingMarkupParser;\n        }\n\n        /// <summary>\n        /// Gets an instance of the code generator and is provided an opportunity to decorate or replace it\n        /// </summary>\n        /// <param name=\"incomingCodeGenerator\">The code generator</param>\n        /// <returns>Either the same code generator, after modifications, or a different code generator</returns>\n        public virtual RazorCodeGenerator DecorateCodeGenerator(RazorCodeGenerator incomingCodeGenerator)\n        {\n            if (incomingCodeGenerator == null)\n            {\n                throw new ArgumentNullException(\"incomingCodeGenerator\");\n            }\n            return incomingCodeGenerator;\n        }\n\n        /// <summary>\n        /// Gets the important CodeDOM nodes generated by the code generator and has a chance to add to them.\n        /// </summary>\n        /// <remarks>\n        /// All the other parameter values can be located by traversing tree in the codeCompileUnit node, they\n        /// are simply provided for convenience\n        /// </remarks>\n        /// <param name=\"context\">The current <see cref=\"CodeGeneratorContext\"/>.</param>\n        public virtual void PostProcessGeneratedCode(CodeGeneratorContext context)\n        {\n#pragma warning disable 0618\n            PostProcessGeneratedCode(context.CompileUnit, context.Namespace, context.GeneratedClass, context.TargetMethod);\n#pragma warning restore 0618\n        }\n\n        [Obsolete(\"This method is obsolete, use the override which takes a CodeGeneratorContext instead\")]\n        public virtual void PostProcessGeneratedCode(CodeCompileUnit codeCompileUnit, CodeNamespace generatedNamespace, CodeTypeDeclaration generatedClass, CodeMemberMethod executeMethod)\n        {\n            if (codeCompileUnit == null)\n            {\n                throw new ArgumentNullException(\"codeCompileUnit\");\n            }\n            if (generatedNamespace == null)\n            {\n                throw new ArgumentNullException(\"generatedNamespace\");\n            }\n            if (generatedClass == null)\n            {\n                throw new ArgumentNullException(\"generatedClass\");\n            }\n            if (executeMethod == null)\n            {\n                throw new ArgumentNullException(\"executeMethod\");\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/RazorTemplateEngine.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.IO;\nusing System.Threading;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Text;\n\nnamespace System.Web.Razor\n{\n    /// <summary>\n    /// Entry-point to the Razor Template Engine\n    /// </summary>\n    public class RazorTemplateEngine\n    {\n        public static readonly string DefaultClassName = \"Template\";\n        public static readonly string DefaultNamespace = String.Empty;\n\n        /// <summary>\n        /// Constructs a new RazorTemplateEngine with the specified host\n        /// </summary>\n        /// <param name=\"host\">The host which defines the environment in which the generated template code will live</param>\n        public RazorTemplateEngine(RazorEngineHost host)\n        {\n            if (host == null)\n            {\n                throw new ArgumentNullException(\"host\");\n            }\n\n            Host = host;\n        }\n\n        /// <summary>\n        /// The RazorEngineHost which defines the environment in which the generated template code will live\n        /// </summary>\n        public RazorEngineHost Host { get; private set; }\n\n        public ParserResults ParseTemplate(ITextBuffer input)\n        {\n            return ParseTemplate(input, null);\n        }\n\n        /// <summary>\n        /// Parses the template specified by the TextBuffer and returns it's result\n        /// </summary>\n        /// <remarks>\n        /// IMPORTANT: This does NOT need to be called before GeneratedCode! GenerateCode will automatically\n        /// parse the document first.\n        /// \n        /// The cancel token provided can be used to cancel the parse.  However, please note\n        /// that the parse occurs _synchronously_, on the callers thread.  This parameter is \n        /// provided so that if the caller is in a background thread with a CancellationToken, \n        /// it can pass it along to the parser.\n        /// </remarks>\n        /// <param name=\"input\">The input text to parse</param>\n        /// <param name=\"cancelToken\">A token used to cancel the parser</param>\n        /// <returns>The resulting parse tree</returns>\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"Input object would be disposed if we dispose the wrapper.  We don't own the input so we don't want to dispose it\")]\n        public ParserResults ParseTemplate(ITextBuffer input, CancellationToken? cancelToken)\n        {\n            return ParseTemplateCore(input.ToDocument(), cancelToken);\n        }\n\n        // See ParseTemplate(ITextBuffer, CancellationToken?), \n        // this overload simply wraps a TextReader in a TextBuffer (see ITextBuffer and BufferingTextReader)\n        public ParserResults ParseTemplate(TextReader input)\n        {\n            return ParseTemplate(input, null);\n        }\n\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"Input object would be disposed if we dispose the wrapper.  We don't own the input so we don't want to dispose it\")]\n        public ParserResults ParseTemplate(TextReader input, CancellationToken? cancelToken)\n        {\n            return ParseTemplateCore(new SeekableTextReader(input), cancelToken);\n        }\n\n        protected internal virtual ParserResults ParseTemplateCore(ITextDocument input, CancellationToken? cancelToken)\n        {\n            // Construct the parser\n            RazorParser parser = CreateParser();\n            Debug.Assert(parser != null);\n            return parser.Parse(input);\n        }\n\n        public GeneratorResults GenerateCode(ITextBuffer input)\n        {\n            return GenerateCode(input, null, null, null, null);\n        }\n\n        public GeneratorResults GenerateCode(ITextBuffer input, CancellationToken? cancelToken)\n        {\n            return GenerateCode(input, null, null, null, cancelToken);\n        }\n\n        public GeneratorResults GenerateCode(ITextBuffer input, string className, string rootNamespace, string sourceFileName)\n        {\n            return GenerateCode(input, className, rootNamespace, sourceFileName, null);\n        }\n\n        /// <summary>\n        /// Parses the template specified by the TextBuffer, generates code for it, and returns the constructed CodeDOM tree\n        /// </summary>\n        /// <remarks>\n        /// The cancel token provided can be used to cancel the parse.  However, please note\n        /// that the parse occurs _synchronously_, on the callers thread.  This parameter is \n        /// provided so that if the caller is in a background thread with a CancellationToken, \n        /// it can pass it along to the parser.\n        /// \n        /// The className, rootNamespace and sourceFileName parameters are optional and override the default\n        /// specified by the Host.  For example, the WebPageRazorHost in System.Web.WebPages.Razor configures the\n        /// Class Name, Root Namespace and Source File Name based on the virtual path of the page being compiled.\n        /// However, the built-in RazorEngineHost class uses constant defaults, so the caller will likely want to \n        /// change them using these parameters\n        /// </remarks>\n        /// <param name=\"input\">The input text to parse</param>\n        /// <param name=\"cancelToken\">A token used to cancel the parser</param>\n        /// <param name=\"className\">The name of the generated class, overriding whatever is specified in the Host.  The default value (defined in the Host) can be used by providing null for this argument</param>\n        /// <param name=\"rootNamespace\">The namespace in which the generated class will reside, overriding whatever is specified in the Host.  The default value (defined in the Host) can be used by providing null for this argument</param>\n        /// <param name=\"sourceFileName\">The file name to use in line pragmas, usually the original Razor file, overriding whatever is specified in the Host.  The default value (defined in the Host) can be used by providing null for this argument</param>\n        /// <returns>The resulting parse tree AND generated Code DOM tree</returns>\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"Input object would be disposed if we dispose the wrapper.  We don't own the input so we don't want to dispose it\")]\n        public GeneratorResults GenerateCode(ITextBuffer input, string className, string rootNamespace, string sourceFileName, CancellationToken? cancelToken)\n        {\n            return GenerateCodeCore(input.ToDocument(), className, rootNamespace, sourceFileName, cancelToken);\n        }\n\n        // See GenerateCode override which takes ITextBuffer, and BufferingTextReader for details.\n        public GeneratorResults GenerateCode(TextReader input)\n        {\n            return GenerateCode(input, null, null, null, null);\n        }\n\n        public GeneratorResults GenerateCode(TextReader input, CancellationToken? cancelToken)\n        {\n            return GenerateCode(input, null, null, null, cancelToken);\n        }\n\n        public GeneratorResults GenerateCode(TextReader input, string className, string rootNamespace, string sourceFileName)\n        {\n            return GenerateCode(input, className, rootNamespace, sourceFileName, null);\n        }\n\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"Input object would be disposed if we dispose the wrapper.  We don't own the input so we don't want to dispose it\")]\n        public GeneratorResults GenerateCode(TextReader input, string className, string rootNamespace, string sourceFileName, CancellationToken? cancelToken)\n        {\n            return GenerateCodeCore(new SeekableTextReader(input), className, rootNamespace, sourceFileName, cancelToken);\n        }\n\n        protected internal virtual GeneratorResults GenerateCodeCore(ITextDocument input, string className, string rootNamespace, string sourceFileName, CancellationToken? cancelToken)\n        {\n            className = (className ?? Host.DefaultClassName) ?? DefaultClassName;\n            rootNamespace = (rootNamespace ?? Host.DefaultNamespace) ?? DefaultNamespace;\n\n            // Run the parser\n            RazorParser parser = CreateParser();\n            Debug.Assert(parser != null);\n            ParserResults results = parser.Parse(input);\n\n            // Generate code\n            RazorCodeGenerator generator = CreateCodeGenerator(className, rootNamespace, sourceFileName);\n            generator.DesignTimeMode = Host.DesignTimeMode;\n            generator.Visit(results);\n\n            // Post process code\n            Host.PostProcessGeneratedCode(generator.Context);\n\n            // Extract design-time mappings\n            IDictionary<int, GeneratedCodeMapping> designTimeLineMappings = null;\n            if (Host.DesignTimeMode)\n            {\n                designTimeLineMappings = generator.Context.CodeMappings;\n            }\n\n            // Collect results and return\n            return new GeneratorResults(results, generator.Context.CompileUnit, designTimeLineMappings);\n        }\n\n        protected internal virtual RazorCodeGenerator CreateCodeGenerator(string className, string rootNamespace, string sourceFileName)\n        {\n            return Host.DecorateCodeGenerator(\n                Host.CodeLanguage.CreateCodeGenerator(className, rootNamespace, sourceFileName, Host));\n        }\n\n        protected internal virtual RazorParser CreateParser()\n        {\n            ParserBase codeParser = Host.CodeLanguage.CreateCodeParser();\n            ParserBase markupParser = Host.CreateMarkupParser();\n\n            return new RazorParser(Host.DecorateCodeParser(codeParser),\n                                   Host.DecorateMarkupParser(markupParser))\n            {\n                DesignTimeMode = Host.DesignTimeMode\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Resources/RazorResources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.34011\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace System.Web.Razor.Resources {\n    using System;\n    \n    \n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class RazorResources {\n        \n        private static global::System.Resources.ResourceManager resourceMan;\n        \n        private static global::System.Globalization.CultureInfo resourceCulture;\n        \n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal RazorResources() {\n        }\n        \n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"System.Web.Razor.Resources.RazorResources\", typeof(RazorResources).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n        \n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The active parser must the same as either the markup or code parser..\n        /// </summary>\n        internal static string ActiveParser_Must_Be_Code_Or_Markup_Parser {\n            get {\n                return ResourceManager.GetString(\"ActiveParser_Must_Be_Code_Or_Markup_Parser\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Block cannot be built because a Type has not been specified in the BlockBuilder.\n        /// </summary>\n        internal static string Block_Type_Not_Specified {\n            get {\n                return ResourceManager.GetString(\"Block_Type_Not_Specified\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to code.\n        /// </summary>\n        internal static string BlockName_Code {\n            get {\n                return ResourceManager.GetString(\"BlockName_Code\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to explicit expression.\n        /// </summary>\n        internal static string BlockName_ExplicitExpression {\n            get {\n                return ResourceManager.GetString(\"BlockName_ExplicitExpression\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &quot;CancelBacktrack&quot; method can be called only while in a look-ahead process started with the &quot;BeginLookahead&quot; method..\n        /// </summary>\n        internal static string CancelBacktrack_Must_Be_Called_Within_Lookahead {\n            get {\n                return ResourceManager.GetString(\"CancelBacktrack_Must_Be_Called_Within_Lookahead\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Cannot call CreateCodeWriter, a CodeWriter was not provided to the Create method.\n        /// </summary>\n        internal static string CreateCodeWriter_NoCodeWriter {\n            get {\n                return ResourceManager.GetString(\"CreateCodeWriter_NoCodeWriter\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;&lt;character literal&gt;&gt;.\n        /// </summary>\n        internal static string CSharpSymbol_CharacterLiteral {\n            get {\n                return ResourceManager.GetString(\"CSharpSymbol_CharacterLiteral\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;&lt;comment&gt;&gt;.\n        /// </summary>\n        internal static string CSharpSymbol_Comment {\n            get {\n                return ResourceManager.GetString(\"CSharpSymbol_Comment\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;&lt;identifier&gt;&gt;.\n        /// </summary>\n        internal static string CSharpSymbol_Identifier {\n            get {\n                return ResourceManager.GetString(\"CSharpSymbol_Identifier\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;&lt;integer literal&gt;&gt;.\n        /// </summary>\n        internal static string CSharpSymbol_IntegerLiteral {\n            get {\n                return ResourceManager.GetString(\"CSharpSymbol_IntegerLiteral\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;&lt;keyword&gt;&gt;.\n        /// </summary>\n        internal static string CSharpSymbol_Keyword {\n            get {\n                return ResourceManager.GetString(\"CSharpSymbol_Keyword\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;&lt;newline sequence&gt;&gt;.\n        /// </summary>\n        internal static string CSharpSymbol_Newline {\n            get {\n                return ResourceManager.GetString(\"CSharpSymbol_Newline\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;&lt;real literal&gt;&gt;.\n        /// </summary>\n        internal static string CSharpSymbol_RealLiteral {\n            get {\n                return ResourceManager.GetString(\"CSharpSymbol_RealLiteral\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;&lt;string literal&gt;&gt;.\n        /// </summary>\n        internal static string CSharpSymbol_StringLiteral {\n            get {\n                return ResourceManager.GetString(\"CSharpSymbol_StringLiteral\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;&lt;white space&gt;&gt;.\n        /// </summary>\n        internal static string CSharpSymbol_Whitespace {\n            get {\n                return ResourceManager.GetString(\"CSharpSymbol_Whitespace\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &quot;EndBlock&quot; was called without a matching call to &quot;StartBlock&quot;..\n        /// </summary>\n        internal static string EndBlock_Called_Without_Matching_StartBlock {\n            get {\n                return ResourceManager.GetString(\"EndBlock_Called_Without_Matching_StartBlock\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &quot;{0}&quot; character.\n        /// </summary>\n        internal static string ErrorComponent_Character {\n            get {\n                return ResourceManager.GetString(\"ErrorComponent_Character\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to end of file.\n        /// </summary>\n        internal static string ErrorComponent_EndOfFile {\n            get {\n                return ResourceManager.GetString(\"ErrorComponent_EndOfFile\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to line break.\n        /// </summary>\n        internal static string ErrorComponent_Newline {\n            get {\n                return ResourceManager.GetString(\"ErrorComponent_Newline\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to space or line break.\n        /// </summary>\n        internal static string ErrorComponent_Whitespace {\n            get {\n                return ResourceManager.GetString(\"ErrorComponent_Whitespace\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;&lt;newline sequence&gt;&gt;.\n        /// </summary>\n        internal static string HtmlSymbol_NewLine {\n            get {\n                return ResourceManager.GetString(\"HtmlSymbol_NewLine\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;&lt;razor comment&gt;&gt;.\n        /// </summary>\n        internal static string HtmlSymbol_RazorComment {\n            get {\n                return ResourceManager.GetString(\"HtmlSymbol_RazorComment\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;&lt;text&gt;&gt;.\n        /// </summary>\n        internal static string HtmlSymbol_Text {\n            get {\n                return ResourceManager.GetString(\"HtmlSymbol_Text\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;&lt;white space&gt;&gt;.\n        /// </summary>\n        internal static string HtmlSymbol_WhiteSpace {\n            get {\n                return ResourceManager.GetString(\"HtmlSymbol_WhiteSpace\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Cannot use built-in RazorComment handler, language characteristics does not define the CommentStart, CommentStar and CommentBody known symbol types or parser does not override TokenizerBackedParser.OutputSpanBeforeRazorComment.\n        /// </summary>\n        internal static string Language_Does_Not_Support_RazorComment {\n            get {\n                return ResourceManager.GetString(\"Language_Does_Not_Support_RazorComment\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &quot;@&quot; character must be followed by a &quot;:&quot;, &quot;(&quot;, or a C# identifier.  If you intended to switch to markup, use an HTML start tag, for example:\n        ///\n        ///@if(isLoggedIn) {\n        ///    &lt;p&gt;Hello, @user!&lt;/p&gt;\n        ///}.\n        /// </summary>\n        internal static string ParseError_AtInCode_Must_Be_Followed_By_Colon_Paren_Or_Identifier_Start {\n            get {\n                return ResourceManager.GetString(\"ParseError_AtInCode_Must_Be_Followed_By_Colon_Paren_Or_Identifier_Start\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to End of file was reached before the end of the block comment.  All comments started with &quot;/*&quot; sequence must be terminated with a matching &quot;*/&quot; sequence..\n        /// </summary>\n        internal static string ParseError_BlockComment_Not_Terminated {\n            get {\n                return ResourceManager.GetString(\"ParseError_BlockComment_Not_Terminated\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &quot;{0}&quot; block was not terminated.  All &quot;{0}&quot; statements must be terminated with a matching &quot;{1}&quot;..\n        /// </summary>\n        internal static string ParseError_BlockNotTerminated {\n            get {\n                return ResourceManager.GetString(\"ParseError_BlockNotTerminated\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to An opening &quot;{0}&quot; is missing the corresponding closing &quot;{1}&quot;..\n        /// </summary>\n        internal static string ParseError_Expected_CloseBracket_Before_EOF {\n            get {\n                return ResourceManager.GetString(\"ParseError_Expected_CloseBracket_Before_EOF\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The {0} block is missing a closing &quot;{1}&quot; character.  Make sure you have a matching &quot;{1}&quot; character for all the &quot;{2}&quot; characters within this block, and that none of the &quot;{1}&quot; characters are being interpreted as markup..\n        /// </summary>\n        internal static string ParseError_Expected_EndOfBlock_Before_EOF {\n            get {\n                return ResourceManager.GetString(\"ParseError_Expected_EndOfBlock_Before_EOF\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Expected &quot;{0}&quot;..\n        /// </summary>\n        internal static string ParseError_Expected_X {\n            get {\n                return ResourceManager.GetString(\"ParseError_Expected_X\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Helper blocks cannot be nested within each other..\n        /// </summary>\n        internal static string ParseError_Helpers_Cannot_Be_Nested {\n            get {\n                return ResourceManager.GetString(\"ParseError_Helpers_Cannot_Be_Nested\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &apos;inherits&apos; keyword must be followed by a type name on the same line..\n        /// </summary>\n        internal static string ParseError_InheritsKeyword_Must_Be_Followed_By_TypeName {\n            get {\n                return ResourceManager.GetString(\"ParseError_InheritsKeyword_Must_Be_Followed_By_TypeName\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Inline markup blocks (@&lt;p&gt;Content&lt;/p&gt;) cannot be nested.  Only one level of inline markup is allowed..\n        /// </summary>\n        internal static string ParseError_InlineMarkup_Blocks_Cannot_Be_Nested {\n            get {\n                return ResourceManager.GetString(\"ParseError_InlineMarkup_Blocks_Cannot_Be_Nested\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &quot;{1}&quot; is not a valid value for the &quot;{0}&quot; option. The &quot;Option {0}&quot; statement must be followed by either &quot;On&quot; or &quot;Off&quot;. .\n        /// </summary>\n        internal static string ParseError_InvalidOptionValue {\n            get {\n                return ResourceManager.GetString(\"ParseError_InvalidOptionValue\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Markup in a code block must start with a tag and all start tags must be matched with end tags.  Do not use unclosed tags like &quot;&lt;br&gt;&quot;.  Instead use self-closing tags like &quot;&lt;br/&gt;&quot;..\n        /// </summary>\n        internal static string ParseError_MarkupBlock_Must_Start_With_Tag {\n            get {\n                return ResourceManager.GetString(\"ParseError_MarkupBlock_Must_Start_With_Tag\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Expected a &quot;{0}&quot; after the helper name..\n        /// </summary>\n        internal static string ParseError_MissingCharAfterHelperName {\n            get {\n                return ResourceManager.GetString(\"ParseError_MissingCharAfterHelperName\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Expected a &quot;{0}&quot; after the helper parameters..\n        /// </summary>\n        internal static string ParseError_MissingCharAfterHelperParameters {\n            get {\n                return ResourceManager.GetString(\"ParseError_MissingCharAfterHelperParameters\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &quot;{0}&quot; element was not closed.  All elements must be either self-closing or have a matching end tag..\n        /// </summary>\n        internal static string ParseError_MissingEndTag {\n            get {\n                return ResourceManager.GetString(\"ParseError_MissingEndTag\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Sections cannot be empty.  The &quot;@section&quot; keyword must be followed by a block of markup surrounded by &quot;{}&quot;.  For example:\n        ///\n        ///@section Sidebar {\n        ///   &lt;!-- Markup and text goes here --&gt;\n        ///}.\n        /// </summary>\n        internal static string ParseError_MissingOpenBraceAfterSection {\n            get {\n                return ResourceManager.GetString(\"ParseError_MissingOpenBraceAfterSection\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Namespace imports and type aliases cannot be placed within code blocks.  They must immediately follow an &quot;@&quot; character in markup.  It is recommended that you put them at the top of the page, as in the following example:\n        ///\n        ///@using System.Drawing;\n        ///@{\n        ///    // OK here to use types from System.Drawing in the page.\n        ///}.\n        /// </summary>\n        internal static string ParseError_NamespaceImportAndTypeAlias_Cannot_Exist_Within_CodeBlock {\n            get {\n                return ResourceManager.GetString(\"ParseError_NamespaceImportAndTypeAlias_Cannot_Exist_Within_CodeBlock\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &quot;Imports&quot; keyword must be followed by a namespace or a type alias on the same line..\n        /// </summary>\n        internal static string ParseError_NamespaceOrTypeAliasExpected {\n            get {\n                return ResourceManager.GetString(\"ParseError_NamespaceOrTypeAliasExpected\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Outer tag is missing a name. The first character of a markup block must be an HTML tag with a valid name..\n        /// </summary>\n        internal static string ParseError_OuterTagMissingName {\n            get {\n                return ResourceManager.GetString(\"ParseError_OuterTagMissingName\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to End of file was reached before the end of the block comment.  All comments that start with the &quot;@*&quot; sequence must be terminated with a matching &quot;*@&quot; sequence..\n        /// </summary>\n        internal static string ParseError_RazorComment_Not_Terminated {\n            get {\n                return ResourceManager.GetString(\"ParseError_RazorComment_Not_Terminated\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &quot;{0}&quot; is a reserved word and cannot be used in implicit expressions.  An explicit expression (&quot;@()&quot;) must be used..\n        /// </summary>\n        internal static string ParseError_ReservedWord {\n            get {\n                return ResourceManager.GetString(\"ParseError_ReservedWord\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Section blocks (&quot;{0}&quot;) cannot be nested.  Only one level of section blocks are allowed..\n        /// </summary>\n        internal static string ParseError_Sections_Cannot_Be_Nested {\n            get {\n                return ResourceManager.GetString(\"ParseError_Sections_Cannot_Be_Nested\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Expected a &quot;{0}&quot; but found a &quot;{1}&quot;.  Block statements must be enclosed in &quot;{{&quot; and &quot;}}&quot;.  You cannot use single-statement control-flow statements in CSHTML pages. For example, the following is not allowed:\n        ///\n        ///@if(isLoggedIn)\n        ///    &lt;p&gt;Hello, @user&lt;/p&gt;\n        ///\n        ///Instead, wrap the contents of the block in &quot;{{}}&quot;:\n        ///\n        ///@if(isLoggedIn) {{\n        ///    &lt;p&gt;Hello, @user&lt;/p&gt;\n        ///}}.\n        /// </summary>\n        internal static string ParseError_SingleLine_ControlFlowStatements_Not_Allowed {\n            get {\n                return ResourceManager.GetString(\"ParseError_SingleLine_ControlFlowStatements_Not_Allowed\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &quot;&lt;text&gt;&quot; and &quot;&lt;/text&gt;&quot; tags cannot contain attributes..\n        /// </summary>\n        internal static string ParseError_TextTagCannotContainAttributes {\n            get {\n                return ResourceManager.GetString(\"ParseError_TextTagCannotContainAttributes\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Unexpected &quot;{0}&quot;.\n        /// </summary>\n        internal static string ParseError_Unexpected {\n            get {\n                return ResourceManager.GetString(\"ParseError_Unexpected\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Unexpected {0} after helper keyword.  All helpers must have a name which starts with an &quot;_&quot; or alphabetic character. The remaining characters must be either &quot;_&quot; or alphanumeric..\n        /// </summary>\n        internal static string ParseError_Unexpected_Character_At_Helper_Name_Start {\n            get {\n                return ResourceManager.GetString(\"ParseError_Unexpected_Character_At_Helper_Name_Start\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Unexpected {0} after section keyword.  Section names must start with an &quot;_&quot; or alphabetic character, and the remaining characters must be either &quot;_&quot; or alphanumeric..\n        /// </summary>\n        internal static string ParseError_Unexpected_Character_At_Section_Name_Start {\n            get {\n                return ResourceManager.GetString(\"ParseError_Unexpected_Character_At_Section_Name_Start\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &quot;{0}&quot; is not valid at the start of a code block.  Only identifiers, keywords, comments, &quot;(&quot; and &quot;{{&quot; are valid..\n        /// </summary>\n        internal static string ParseError_Unexpected_Character_At_Start_Of_CodeBlock_CS {\n            get {\n                return ResourceManager.GetString(\"ParseError_Unexpected_Character_At_Start_Of_CodeBlock_CS\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &quot;{0}&quot; is not valid at the start of a code block.  Only identifiers, keywords, comments, and &quot;(&quot; are valid..\n        /// </summary>\n        internal static string ParseError_Unexpected_Character_At_Start_Of_CodeBlock_VB {\n            get {\n                return ResourceManager.GetString(\"ParseError_Unexpected_Character_At_Start_Of_CodeBlock_VB\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to End-of-file was found after the &quot;@&quot; character.  &quot;@&quot; must be followed by a valid code block.  If you want to output an &quot;@&quot;, escape it using the sequence: &quot;@@&quot;.\n        /// </summary>\n        internal static string ParseError_Unexpected_EndOfFile_At_Start_Of_CodeBlock {\n            get {\n                return ResourceManager.GetString(\"ParseError_Unexpected_EndOfFile_At_Start_Of_CodeBlock\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Unexpected &quot;{0}&quot; keyword after &quot;@&quot; character.  Once inside code, you do not need to prefix constructs like &quot;{0}&quot; with &quot;@&quot;..\n        /// </summary>\n        internal static string ParseError_Unexpected_Keyword_After_At {\n            get {\n                return ResourceManager.GetString(\"ParseError_Unexpected_Keyword_After_At\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Unexpected &quot;{&quot; after &quot;@&quot; character. Once inside the body of a code block (@if {}, @{}, etc.) you do not need to use &quot;@{&quot; to switch to code..\n        /// </summary>\n        internal static string ParseError_Unexpected_Nested_CodeBlock {\n            get {\n                return ResourceManager.GetString(\"ParseError_Unexpected_Nested_CodeBlock\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A space or line break was encountered after the &quot;@&quot; character.  Only valid identifiers, keywords, comments, &quot;(&quot; and &quot;{&quot; are valid at the start of a code block and they must occur immediately following &quot;@&quot; with no space in between..\n        /// </summary>\n        internal static string ParseError_Unexpected_WhiteSpace_At_Start_Of_CodeBlock_CS {\n            get {\n                return ResourceManager.GetString(\"ParseError_Unexpected_WhiteSpace_At_Start_Of_CodeBlock_CS\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A space or line break was encountered after the &quot;@&quot; character.  Only valid identifiers, keywords, comments, and &quot;(&quot; are valid at the start of a code block and they must occur immediately following &quot;@&quot; with no space in between..\n        /// </summary>\n        internal static string ParseError_Unexpected_WhiteSpace_At_Start_Of_CodeBlock_VB {\n            get {\n                return ResourceManager.GetString(\"ParseError_Unexpected_WhiteSpace_At_Start_Of_CodeBlock_VB\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Encountered end tag &quot;{0}&quot; with no matching start tag.  Are your start/end tags properly balanced?.\n        /// </summary>\n        internal static string ParseError_UnexpectedEndTag {\n            get {\n                return ResourceManager.GetString(\"ParseError_UnexpectedEndTag\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to End of file or an unexpected character was reached before the &quot;{0}&quot; tag could be parsed.  Elements inside markup blocks must be complete. They must either be self-closing (&quot;&lt;br /&gt;&quot;) or have matching end tags (&quot;&lt;p&gt;Hello&lt;/p&gt;&quot;).  If you intended to display a &quot;&lt;&quot; character, use the &quot;&amp;lt;&quot; HTML entity..\n        /// </summary>\n        internal static string ParseError_UnfinishedTag {\n            get {\n                return ResourceManager.GetString(\"ParseError_UnfinishedTag\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Unknown option: &quot;{0}&quot;..\n        /// </summary>\n        internal static string ParseError_UnknownOption {\n            get {\n                return ResourceManager.GetString(\"ParseError_UnknownOption\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Unterminated string literal. Strings that start with a quotation mark (&quot;) must be terminated before the end of the line.  However, strings that start with @ and a quotation mark (@&quot;) can span multiple lines. Closing HTML tags within a string literal may trigger this error message..\n        /// </summary>\n        internal static string ParseError_Unterminated_String_Literal {\n            get {\n                return ResourceManager.GetString(\"ParseError_Unterminated_String_Literal\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Helper parameter list is missing a closing &quot;)&quot;..\n        /// </summary>\n        internal static string ParseError_UnterminatedHelperParameterList {\n            get {\n                return ResourceManager.GetString(\"ParseError_UnterminatedHelperParameterList\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Parser was started with a null Context property.  The Context property must be set BEFORE calling any methods on the parser..\n        /// </summary>\n        internal static string Parser_Context_Not_Set {\n            get {\n                return ResourceManager.GetString(\"Parser_Context_Not_Set\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Cannot complete the tree, StartBlock must be called at least once..\n        /// </summary>\n        internal static string ParserContext_CannotCompleteTree_NoRootBlock {\n            get {\n                return ResourceManager.GetString(\"ParserContext_CannotCompleteTree_NoRootBlock\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Cannot complete the tree, there are still open blocks..\n        /// </summary>\n        internal static string ParserContext_CannotCompleteTree_OutstandingBlocks {\n            get {\n                return ResourceManager.GetString(\"ParserContext_CannotCompleteTree_OutstandingBlocks\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Cannot finish span, there is no current block. Call StartBlock at least once before finishing a span.\n        /// </summary>\n        internal static string ParserContext_NoCurrentBlock {\n            get {\n                return ResourceManager.GetString(\"ParserContext_NoCurrentBlock\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Cannot complete action, the parser has finished. Only CompleteParse can be called to extract the final parser results after the parser has finished.\n        /// </summary>\n        internal static string ParserContext_ParseComplete {\n            get {\n                return ResourceManager.GetString(\"ParserContext_ParseComplete\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Missing value for session state directive..\n        /// </summary>\n        internal static string ParserEror_SessionDirectiveMissingValue {\n            get {\n                return ResourceManager.GetString(\"ParserEror_SessionDirectiveMissingValue\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The parser provided to the ParserContext was not a Markup Parser..\n        /// </summary>\n        internal static string ParserIsNotAMarkupParser {\n            get {\n                return ResourceManager.GetString(\"ParserIsNotAMarkupParser\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to @section Header { ... }.\n        /// </summary>\n        internal static string SectionExample_CS {\n            get {\n                return ResourceManager.GetString(\"SectionExample_CS\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to @Section Header ... End Section.\n        /// </summary>\n        internal static string SectionExample_VB {\n            get {\n                return ResourceManager.GetString(\"SectionExample_VB\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The {0} property of the {1} structure cannot be null..\n        /// </summary>\n        internal static string Structure_Member_CannotBeNull {\n            get {\n                return ResourceManager.GetString(\"Structure_Member_CannotBeNull\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;&lt;unknown&gt;&gt;.\n        /// </summary>\n        internal static string Symbol_Unknown {\n            get {\n                return ResourceManager.GetString(\"Symbol_Unknown\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Cannot resume this symbol. Only the symbol immediately preceding the current one can be resumed..\n        /// </summary>\n        internal static string Tokenizer_CannotResumeSymbolUnlessIsPrevious {\n            get {\n                return ResourceManager.GetString(\"Tokenizer_CannotResumeSymbolUnlessIsPrevious\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to In order to put a symbol back, it must have been the symbol which ended at the current position. The specified symbol ends at {0}, but the current position is {1}.\n        /// </summary>\n        internal static string TokenizerView_CannotPutBack {\n            get {\n                return ResourceManager.GetString(\"TokenizerView_CannotPutBack\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to [BG][{0}] Shutdown.\n        /// </summary>\n        internal static string Trace_BackgroundThreadShutdown {\n            get {\n                return ResourceManager.GetString(\"Trace_BackgroundThreadShutdown\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to [BG][{0}] Startup.\n        /// </summary>\n        internal static string Trace_BackgroundThreadStart {\n            get {\n                return ResourceManager.GetString(\"Trace_BackgroundThreadStart\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to [BG][{0}] {1} changes arrived.\n        /// </summary>\n        internal static string Trace_ChangesArrived {\n            get {\n                return ResourceManager.GetString(\"Trace_ChangesArrived\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to [BG][{0}] Discarded {1} changes.\n        /// </summary>\n        internal static string Trace_ChangesDiscarded {\n            get {\n                return ResourceManager.GetString(\"Trace_ChangesDiscarded\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to [BG][{0}] Collecting {1} discarded changes.\n        /// </summary>\n        internal static string Trace_CollectedDiscardedChanges {\n            get {\n                return ResourceManager.GetString(\"Trace_CollectedDiscardedChanges\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Disabled.\n        /// </summary>\n        internal static string Trace_Disabled {\n            get {\n                return ResourceManager.GetString(\"Trace_Disabled\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to [P][{0}] {3} Change in {2} milliseconds: {1}.\n        /// </summary>\n        internal static string Trace_EditorProcessedChange {\n            get {\n                return ResourceManager.GetString(\"Trace_EditorProcessedChange\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to [P][{0}] Received Change: {1}.\n        /// </summary>\n        internal static string Trace_EditorReceivedChange {\n            get {\n                return ResourceManager.GetString(\"Trace_EditorReceivedChange\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Enabled.\n        /// </summary>\n        internal static string Trace_Enabled {\n            get {\n                return ResourceManager.GetString(\"Trace_Enabled\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to [Razor] {0}.\n        /// </summary>\n        internal static string Trace_Format {\n            get {\n                return ResourceManager.GetString(\"Trace_Format\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to [BG][{0}] no changes arrived?.\n        /// </summary>\n        internal static string Trace_NoChangesArrived {\n            get {\n                return ResourceManager.GetString(\"Trace_NoChangesArrived\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to [BG][{0}] Parse Complete in {1} milliseconds.\n        /// </summary>\n        internal static string Trace_ParseComplete {\n            get {\n                return ResourceManager.GetString(\"Trace_ParseComplete\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to [M][{0}] Queuing Parse for: {1}.\n        /// </summary>\n        internal static string Trace_QueuingParse {\n            get {\n                return ResourceManager.GetString(\"Trace_QueuingParse\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to [Razor] Editor Tracing {0}.\n        /// </summary>\n        internal static string Trace_Startup {\n            get {\n                return ResourceManager.GetString(\"Trace_Startup\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to [BG][{0}] Trees Compared in {1} milliseconds. Different = {2}.\n        /// </summary>\n        internal static string Trace_TreesCompared {\n            get {\n                return ResourceManager.GetString(\"Trace_TreesCompared\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;&lt;character literal&gt;&gt;.\n        /// </summary>\n        internal static string VBSymbol_CharacterLiteral {\n            get {\n                return ResourceManager.GetString(\"VBSymbol_CharacterLiteral\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;&lt;comment&gt;&gt;.\n        /// </summary>\n        internal static string VBSymbol_Comment {\n            get {\n                return ResourceManager.GetString(\"VBSymbol_Comment\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;&lt;date literal&gt;&gt;.\n        /// </summary>\n        internal static string VBSymbol_DateLiteral {\n            get {\n                return ResourceManager.GetString(\"VBSymbol_DateLiteral\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;&lt;floating point literal&gt;&gt;.\n        /// </summary>\n        internal static string VBSymbol_FloatingPointLiteral {\n            get {\n                return ResourceManager.GetString(\"VBSymbol_FloatingPointLiteral\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;&lt;identifier&gt;&gt;.\n        /// </summary>\n        internal static string VBSymbol_Identifier {\n            get {\n                return ResourceManager.GetString(\"VBSymbol_Identifier\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;&lt;integer literal&gt;&gt;.\n        /// </summary>\n        internal static string VBSymbol_IntegerLiteral {\n            get {\n                return ResourceManager.GetString(\"VBSymbol_IntegerLiteral\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;&lt;keyword&gt;&gt;.\n        /// </summary>\n        internal static string VBSymbol_Keyword {\n            get {\n                return ResourceManager.GetString(\"VBSymbol_Keyword\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;&lt;newline sequence&gt;&gt;.\n        /// </summary>\n        internal static string VBSymbol_NewLine {\n            get {\n                return ResourceManager.GetString(\"VBSymbol_NewLine\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;&lt;razor comment&gt;&gt;.\n        /// </summary>\n        internal static string VBSymbol_RazorComment {\n            get {\n                return ResourceManager.GetString(\"VBSymbol_RazorComment\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;&lt;string literal&gt;&gt;.\n        /// </summary>\n        internal static string VBSymbol_StringLiteral {\n            get {\n                return ResourceManager.GetString(\"VBSymbol_StringLiteral\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;&lt;white space&gt;&gt;.\n        /// </summary>\n        internal static string VBSymbol_WhiteSpace {\n            get {\n                return ResourceManager.GetString(\"VBSymbol_WhiteSpace\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Resources/RazorResources.resx",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"ActiveParser_Must_Be_Code_Or_Markup_Parser\" xml:space=\"preserve\">\n    <value>The active parser must the same as either the markup or code parser.</value>\n  </data>\n  <data name=\"BlockName_Code\" xml:space=\"preserve\">\n    <value>code</value>\n    <comment>This is a literal used when composing ParserError_* messages. Most blocks are named by the keyword that starts them, for example \"if\".  However, for those without keywords, a (localizable) name must be used.  This literal is ALWAYS used mid-sentence, thus should not be capitalized.</comment>\n  </data>\n  <data name=\"BlockName_ExplicitExpression\" xml:space=\"preserve\">\n    <value>explicit expression</value>\n    <comment>This is a literal used when composing ParserError_* messages. Most blocks are named by the keyword that starts them, for example \"if\".  However, for those without keywords, a (localizable) name must be used.  This literal is ALWAYS used mid-sentence, thus should not be capitalized.</comment>\n  </data>\n  <data name=\"CancelBacktrack_Must_Be_Called_Within_Lookahead\" xml:space=\"preserve\">\n    <value>The \"CancelBacktrack\" method can be called only while in a look-ahead process started with the \"BeginLookahead\" method.</value>\n  </data>\n  <data name=\"EndBlock_Called_Without_Matching_StartBlock\" xml:space=\"preserve\">\n    <value>\"EndBlock\" was called without a matching call to \"StartBlock\".</value>\n  </data>\n  <data name=\"ParseError_AtInCode_Must_Be_Followed_By_Colon_Paren_Or_Identifier_Start\" xml:space=\"preserve\">\n    <value>The \"@\" character must be followed by a \":\", \"(\", or a C# identifier.  If you intended to switch to markup, use an HTML start tag, for example:\n\n@if(isLoggedIn) {\n    &lt;p&gt;Hello, @user!&lt;/p&gt;\n}</value>\n  </data>\n  <data name=\"ParseError_BlockComment_Not_Terminated\" xml:space=\"preserve\">\n    <value>End of file was reached before the end of the block comment.  All comments started with \"/*\" sequence must be terminated with a matching \"*/\" sequence.</value>\n  </data>\n  <data name=\"ParseError_Expected_CloseBracket_Before_EOF\" xml:space=\"preserve\">\n    <value>An opening \"{0}\" is missing the corresponding closing \"{1}\".</value>\n  </data>\n  <data name=\"ParseError_Expected_EndOfBlock_Before_EOF\" xml:space=\"preserve\">\n    <value>The {0} block is missing a closing \"{1}\" character.  Make sure you have a matching \"{1}\" character for all the \"{2}\" characters within this block, and that none of the \"{1}\" characters are being interpreted as markup.</value>\n  </data>\n  <data name=\"ParseError_Expected_X\" xml:space=\"preserve\">\n    <value>Expected \"{0}\".</value>\n  </data>\n  <data name=\"ParseError_InlineMarkup_Blocks_Cannot_Be_Nested\" xml:space=\"preserve\">\n    <value>Inline markup blocks (@&lt;p&gt;Content&lt;/p&gt;) cannot be nested.  Only one level of inline markup is allowed.</value>\n  </data>\n  <data name=\"ParseError_MarkupBlock_Must_Start_With_Tag\" xml:space=\"preserve\">\n    <value>Markup in a code block must start with a tag and all start tags must be matched with end tags.  Do not use unclosed tags like \"&lt;br&gt;\".  Instead use self-closing tags like \"&lt;br/&gt;\".</value>\n  </data>\n  <data name=\"ParseError_MissingEndTag\" xml:space=\"preserve\">\n    <value>The \"{0}\" element was not closed.  All elements must be either self-closing or have a matching end tag.</value>\n  </data>\n  <data name=\"ParseError_MissingOpenBraceAfterSection\" xml:space=\"preserve\">\n    <value>Sections cannot be empty.  The \"@section\" keyword must be followed by a block of markup surrounded by \"{}\".  For example:\n\n@section Sidebar {\n   &lt;!-- Markup and text goes here --&gt;\n}</value>\n  </data>\n  <data name=\"ParseError_NamespaceImportAndTypeAlias_Cannot_Exist_Within_CodeBlock\" xml:space=\"preserve\">\n    <value>Namespace imports and type aliases cannot be placed within code blocks.  They must immediately follow an \"@\" character in markup.  It is recommended that you put them at the top of the page, as in the following example:\n\n@using System.Drawing;\n@{\n    // OK here to use types from System.Drawing in the page.\n}</value>\n  </data>\n  <data name=\"ParseError_Sections_Cannot_Be_Nested\" xml:space=\"preserve\">\n    <value>Section blocks (\"{0}\") cannot be nested.  Only one level of section blocks are allowed.</value>\n    <comment>{0} is one of SectionExample_VB or SectionExample_CS based on the language.</comment>\n  </data>\n  <data name=\"ParseError_SingleLine_ControlFlowStatements_Not_Allowed\" xml:space=\"preserve\">\n    <value>Expected a \"{0}\" but found a \"{1}\".  Block statements must be enclosed in \"{{\" and \"}}\".  You cannot use single-statement control-flow statements in CSHTML pages. For example, the following is not allowed:\n\n@if(isLoggedIn)\n    &lt;p&gt;Hello, @user&lt;/p&gt;\n\nInstead, wrap the contents of the block in \"{{}}\":\n\n@if(isLoggedIn) {{\n    &lt;p&gt;Hello, @user&lt;/p&gt;\n}}</value>\n    <comment>{0} is only ever a single character</comment>\n  </data>\n  <data name=\"ParseError_UnexpectedEndTag\" xml:space=\"preserve\">\n    <value>Encountered end tag \"{0}\" with no matching start tag.  Are your start/end tags properly balanced?</value>\n  </data>\n  <data name=\"ParseError_Unexpected_Character_At_Section_Name_Start\" xml:space=\"preserve\">\n    <value>Unexpected {0} after section keyword.  Section names must start with an \"_\" or alphabetic character, and the remaining characters must be either \"_\" or alphanumeric.</value>\n  </data>\n  <data name=\"ParseError_Unexpected_Character_At_Start_Of_CodeBlock_CS\" xml:space=\"preserve\">\n    <value>\"{0}\" is not valid at the start of a code block.  Only identifiers, keywords, comments, \"(\" and \"{{\" are valid.</value>\n    <comment>\"{{\" is an escape sequence for String.Format, when outputted to the user it will be displayed as \"{\"</comment>\n  </data>\n  <data name=\"ParseError_UnfinishedTag\" xml:space=\"preserve\">\n    <value>End of file or an unexpected character was reached before the \"{0}\" tag could be parsed.  Elements inside markup blocks must be complete. They must either be self-closing (\"&lt;br /&gt;\") or have matching end tags (\"&lt;p&gt;Hello&lt;/p&gt;\").  If you intended to display a \"&lt;\" character, use the \"&amp;lt;\" HTML entity.</value>\n  </data>\n  <data name=\"ParseError_Unterminated_String_Literal\" xml:space=\"preserve\">\n    <value>Unterminated string literal. Strings that start with a quotation mark (\") must be terminated before the end of the line.  However, strings that start with @ and a quotation mark (@\") can span multiple lines. Closing HTML tags within a string literal may trigger this error message.</value>\n  </data>\n  <data name=\"ParseError_InvalidOptionValue\" xml:space=\"preserve\">\n    <value>\"{1}\" is not a valid value for the \"{0}\" option. The \"Option {0}\" statement must be followed by either \"On\" or \"Off\". </value>\n    <comment>{0} is either Strict or Explicit and represent VB's \"Option Strict\" and \"Option Explicit\" keywords</comment>\n  </data>\n  <data name=\"ParseError_UnknownOption\" xml:space=\"preserve\">\n    <value>Unknown option: \"{0}\".</value>\n  </data>\n  <data name=\"ParseError_BlockNotTerminated\" xml:space=\"preserve\">\n    <value>The \"{0}\" block was not terminated.  All \"{0}\" statements must be terminated with a matching \"{1}\".</value>\n  </data>\n  <data name=\"SectionExample_CS\" xml:space=\"preserve\">\n    <value>@section Header { ... }</value>\n    <comment>In CSHTML, the @section keyword is case-sensitive and lowercase (as with all C# keywords)</comment>\n  </data>\n  <data name=\"ParseError_TextTagCannotContainAttributes\" xml:space=\"preserve\">\n    <value>\"&lt;text&gt;\" and \"&lt;/text&gt;\" tags cannot contain attributes.</value>\n  </data>\n  <data name=\"ParseError_NamespaceOrTypeAliasExpected\" xml:space=\"preserve\">\n    <value>The \"Imports\" keyword must be followed by a namespace or a type alias on the same line.</value>\n  </data>\n  <data name=\"ParseError_Unexpected_WhiteSpace_At_Start_Of_CodeBlock_CS\" xml:space=\"preserve\">\n    <value>A space or line break was encountered after the \"@\" character.  Only valid identifiers, keywords, comments, \"(\" and \"{\" are valid at the start of a code block and they must occur immediately following \"@\" with no space in between.</value>\n  </data>\n  <data name=\"ParseError_InheritsKeyword_Must_Be_Followed_By_TypeName\" xml:space=\"preserve\">\n    <value>The 'inherits' keyword must be followed by a type name on the same line.</value>\n  </data>\n  <data name=\"ParseError_OuterTagMissingName\" xml:space=\"preserve\">\n    <value>Outer tag is missing a name. The first character of a markup block must be an HTML tag with a valid name.</value>\n  </data>\n  <data name=\"ParseError_RazorComment_Not_Terminated\" xml:space=\"preserve\">\n    <value>End of file was reached before the end of the block comment.  All comments that start with the \"@*\" sequence must be terminated with a matching \"*@\" sequence.</value>\n  </data>\n  <data name=\"ErrorComponent_Character\" xml:space=\"preserve\">\n    <value>\"{0}\" character</value>\n  </data>\n  <data name=\"ErrorComponent_EndOfFile\" xml:space=\"preserve\">\n    <value>end of file</value>\n  </data>\n  <data name=\"ErrorComponent_Whitespace\" xml:space=\"preserve\">\n    <value>space or line break</value>\n  </data>\n  <data name=\"ParseError_Unexpected_Character_At_Start_Of_CodeBlock_VB\" xml:space=\"preserve\">\n    <value>\"{0}\" is not valid at the start of a code block.  Only identifiers, keywords, comments, and \"(\" are valid.</value>\n  </data>\n  <data name=\"ParseError_Unexpected_EndOfFile_At_Start_Of_CodeBlock\" xml:space=\"preserve\">\n    <value>End-of-file was found after the \"@\" character.  \"@\" must be followed by a valid code block.  If you want to output an \"@\", escape it using the sequence: \"@@\"</value>\n  </data>\n  <data name=\"ParseError_Unexpected_WhiteSpace_At_Start_Of_CodeBlock_VB\" xml:space=\"preserve\">\n    <value>A space or line break was encountered after the \"@\" character.  Only valid identifiers, keywords, comments, and \"(\" are valid at the start of a code block and they must occur immediately following \"@\" with no space in between.</value>\n  </data>\n  <data name=\"Structure_Member_CannotBeNull\" xml:space=\"preserve\">\n    <value>The {0} property of the {1} structure cannot be null.</value>\n  </data>\n  <data name=\"ParseError_MissingCharAfterHelperParameters\" xml:space=\"preserve\">\n    <value>Expected a \"{0}\" after the helper parameters.</value>\n  </data>\n  <data name=\"ParseError_MissingCharAfterHelperName\" xml:space=\"preserve\">\n    <value>Expected a \"{0}\" after the helper name.</value>\n  </data>\n  <data name=\"ParseError_UnterminatedHelperParameterList\" xml:space=\"preserve\">\n    <value>Helper parameter list is missing a closing \")\".</value>\n  </data>\n  <data name=\"ParseError_Helpers_Cannot_Be_Nested\" xml:space=\"preserve\">\n    <value>Helper blocks cannot be nested within each other.</value>\n  </data>\n  <data name=\"Parser_Context_Not_Set\" xml:space=\"preserve\">\n    <value>Parser was started with a null Context property.  The Context property must be set BEFORE calling any methods on the parser.</value>\n  </data>\n  <data name=\"ParseError_Unexpected_Keyword_After_At\" xml:space=\"preserve\">\n    <value>Unexpected \"{0}\" keyword after \"@\" character.  Once inside code, you do not need to prefix constructs like \"{0}\" with \"@\".</value>\n  </data>\n  <data name=\"ParseError_ReservedWord\" xml:space=\"preserve\">\n    <value>\"{0}\" is a reserved word and cannot be used in implicit expressions.  An explicit expression (\"@()\") must be used.</value>\n  </data>\n  <data name=\"ParseError_Unexpected_Character_At_Helper_Name_Start\" xml:space=\"preserve\">\n    <value>Unexpected {0} after helper keyword.  All helpers must have a name which starts with an \"_\" or alphabetic character. The remaining characters must be either \"_\" or alphanumeric.</value>\n  </data>\n  <data name=\"Tokenizer_CannotResumeSymbolUnlessIsPrevious\" xml:space=\"preserve\">\n    <value>Cannot resume this symbol. Only the symbol immediately preceding the current one can be resumed.</value>\n  </data>\n  <data name=\"ParserContext_NoCurrentBlock\" xml:space=\"preserve\">\n    <value>Cannot finish span, there is no current block. Call StartBlock at least once before finishing a span</value>\n  </data>\n  <data name=\"ParserContext_CannotCompleteTree_OutstandingBlocks\" xml:space=\"preserve\">\n    <value>Cannot complete the tree, there are still open blocks.</value>\n  </data>\n  <data name=\"ParserContext_CannotCompleteTree_NoRootBlock\" xml:space=\"preserve\">\n    <value>Cannot complete the tree, StartBlock must be called at least once.</value>\n  </data>\n  <data name=\"ParserContext_ParseComplete\" xml:space=\"preserve\">\n    <value>Cannot complete action, the parser has finished. Only CompleteParse can be called to extract the final parser results after the parser has finished</value>\n  </data>\n  <data name=\"Block_Type_Not_Specified\" xml:space=\"preserve\">\n    <value>Block cannot be built because a Type has not been specified in the BlockBuilder</value>\n  </data>\n  <data name=\"CSharpSymbol_CharacterLiteral\" xml:space=\"preserve\">\n    <value>&lt;&lt;character literal&gt;&gt;</value>\n  </data>\n  <data name=\"CSharpSymbol_Comment\" xml:space=\"preserve\">\n    <value>&lt;&lt;comment&gt;&gt;</value>\n  </data>\n  <data name=\"CSharpSymbol_Identifier\" xml:space=\"preserve\">\n    <value>&lt;&lt;identifier&gt;&gt;</value>\n  </data>\n  <data name=\"CSharpSymbol_IntegerLiteral\" xml:space=\"preserve\">\n    <value>&lt;&lt;integer literal&gt;&gt;</value>\n  </data>\n  <data name=\"CSharpSymbol_Keyword\" xml:space=\"preserve\">\n    <value>&lt;&lt;keyword&gt;&gt;</value>\n  </data>\n  <data name=\"CSharpSymbol_Newline\" xml:space=\"preserve\">\n    <value>&lt;&lt;newline sequence&gt;&gt;</value>\n  </data>\n  <data name=\"CSharpSymbol_RealLiteral\" xml:space=\"preserve\">\n    <value>&lt;&lt;real literal&gt;&gt;</value>\n  </data>\n  <data name=\"CSharpSymbol_StringLiteral\" xml:space=\"preserve\">\n    <value>&lt;&lt;string literal&gt;&gt;</value>\n  </data>\n  <data name=\"CSharpSymbol_Whitespace\" xml:space=\"preserve\">\n    <value>&lt;&lt;white space&gt;&gt;</value>\n  </data>\n  <data name=\"Symbol_Unknown\" xml:space=\"preserve\">\n    <value>&lt;&lt;unknown&gt;&gt;</value>\n  </data>\n  <data name=\"TokenizerView_CannotPutBack\" xml:space=\"preserve\">\n    <value>In order to put a symbol back, it must have been the symbol which ended at the current position. The specified symbol ends at {0}, but the current position is {1}</value>\n  </data>\n  <data name=\"ParseError_Unexpected\" xml:space=\"preserve\">\n    <value>Unexpected \"{0}\"</value>\n  </data>\n  <data name=\"ParseError_Unexpected_Nested_CodeBlock\" xml:space=\"preserve\">\n    <value>Unexpected \"{\" after \"@\" character. Once inside the body of a code block (@if {}, @{}, etc.) you do not need to use \"@{\" to switch to code.</value>\n  </data>\n  <data name=\"ErrorComponent_Newline\" xml:space=\"preserve\">\n    <value>line break</value>\n  </data>\n  <data name=\"SectionExample_VB\" xml:space=\"preserve\">\n    <value>@Section Header ... End Section</value>\n    <comment>In VBHTML, the @Section keyword is case-insensitive (as with all VB keywords), but the standard practice is to Title Case it</comment>\n  </data>\n  <data name=\"VBSymbol_CharacterLiteral\" xml:space=\"preserve\">\n    <value>&lt;&lt;character literal&gt;&gt;</value>\n  </data>\n  <data name=\"VBSymbol_Comment\" xml:space=\"preserve\">\n    <value>&lt;&lt;comment&gt;&gt;</value>\n  </data>\n  <data name=\"VBSymbol_DateLiteral\" xml:space=\"preserve\">\n    <value>&lt;&lt;date literal&gt;&gt;</value>\n  </data>\n  <data name=\"VBSymbol_FloatingPointLiteral\" xml:space=\"preserve\">\n    <value>&lt;&lt;floating point literal&gt;&gt;</value>\n  </data>\n  <data name=\"VBSymbol_Identifier\" xml:space=\"preserve\">\n    <value>&lt;&lt;identifier&gt;&gt;</value>\n  </data>\n  <data name=\"VBSymbol_IntegerLiteral\" xml:space=\"preserve\">\n    <value>&lt;&lt;integer literal&gt;&gt;</value>\n  </data>\n  <data name=\"VBSymbol_Keyword\" xml:space=\"preserve\">\n    <value>&lt;&lt;keyword&gt;&gt;</value>\n  </data>\n  <data name=\"VBSymbol_NewLine\" xml:space=\"preserve\">\n    <value>&lt;&lt;newline sequence&gt;&gt;</value>\n  </data>\n  <data name=\"VBSymbol_RazorComment\" xml:space=\"preserve\">\n    <value>&lt;&lt;razor comment&gt;&gt;</value>\n  </data>\n  <data name=\"VBSymbol_StringLiteral\" xml:space=\"preserve\">\n    <value>&lt;&lt;string literal&gt;&gt;</value>\n  </data>\n  <data name=\"VBSymbol_WhiteSpace\" xml:space=\"preserve\">\n    <value>&lt;&lt;white space&gt;&gt;</value>\n  </data>\n  <data name=\"HtmlSymbol_NewLine\" xml:space=\"preserve\">\n    <value>&lt;&lt;newline sequence&gt;&gt;</value>\n  </data>\n  <data name=\"HtmlSymbol_RazorComment\" xml:space=\"preserve\">\n    <value>&lt;&lt;razor comment&gt;&gt;</value>\n  </data>\n  <data name=\"HtmlSymbol_Text\" xml:space=\"preserve\">\n    <value>&lt;&lt;text&gt;&gt;</value>\n  </data>\n  <data name=\"HtmlSymbol_WhiteSpace\" xml:space=\"preserve\">\n    <value>&lt;&lt;white space&gt;&gt;</value>\n  </data>\n  <data name=\"ParserIsNotAMarkupParser\" xml:space=\"preserve\">\n    <value>The parser provided to the ParserContext was not a Markup Parser.</value>\n  </data>\n  <data name=\"Language_Does_Not_Support_RazorComment\" xml:space=\"preserve\">\n    <value>Cannot use built-in RazorComment handler, language characteristics does not define the CommentStart, CommentStar and CommentBody known symbol types or parser does not override TokenizerBackedParser.OutputSpanBeforeRazorComment</value>\n  </data>\n  <data name=\"ParserEror_SessionDirectiveMissingValue\" xml:space=\"preserve\">\n    <value>Missing value for session state directive.</value>\n  </data>\n  <data name=\"CreateCodeWriter_NoCodeWriter\" xml:space=\"preserve\">\n    <value>Cannot call CreateCodeWriter, a CodeWriter was not provided to the Create method</value>\n    <comment>This error should not be seen by users, it should only appear to internal developers, but I'm putting it in resources just in case</comment>\n  </data>\n  <data name=\"Trace_BackgroundThreadShutdown\" xml:space=\"preserve\">\n    <value>[BG][{0}] Shutdown</value>\n  </data>\n  <data name=\"Trace_BackgroundThreadStart\" xml:space=\"preserve\">\n    <value>[BG][{0}] Startup</value>\n  </data>\n  <data name=\"Trace_ChangesArrived\" xml:space=\"preserve\">\n    <value>[BG][{0}] {1} changes arrived</value>\n  </data>\n  <data name=\"Trace_ChangesDiscarded\" xml:space=\"preserve\">\n    <value>[BG][{0}] Discarded {1} changes</value>\n  </data>\n  <data name=\"Trace_CollectedDiscardedChanges\" xml:space=\"preserve\">\n    <value>[BG][{0}] Collecting {1} discarded changes</value>\n  </data>\n  <data name=\"Trace_Disabled\" xml:space=\"preserve\">\n    <value>Disabled</value>\n  </data>\n  <data name=\"Trace_EditorProcessedChange\" xml:space=\"preserve\">\n    <value>[P][{0}] {3} Change in {2} milliseconds: {1}</value>\n  </data>\n  <data name=\"Trace_EditorReceivedChange\" xml:space=\"preserve\">\n    <value>[P][{0}] Received Change: {1}</value>\n  </data>\n  <data name=\"Trace_Enabled\" xml:space=\"preserve\">\n    <value>Enabled</value>\n  </data>\n  <data name=\"Trace_Format\" xml:space=\"preserve\">\n    <value>[Razor] {0}</value>\n  </data>\n  <data name=\"Trace_NoChangesArrived\" xml:space=\"preserve\">\n    <value>[BG][{0}] no changes arrived?</value>\n  </data>\n  <data name=\"Trace_ParseComplete\" xml:space=\"preserve\">\n    <value>[BG][{0}] Parse Complete in {1} milliseconds</value>\n  </data>\n  <data name=\"Trace_QueuingParse\" xml:space=\"preserve\">\n    <value>[M][{0}] Queuing Parse for: {1}</value>\n  </data>\n  <data name=\"Trace_Startup\" xml:space=\"preserve\">\n    <value>[Razor] Editor Tracing {0}</value>\n  </data>\n  <data name=\"Trace_TreesCompared\" xml:space=\"preserve\">\n    <value>[BG][{0}] Trees Compared in {1} milliseconds. Different = {2}</value>\n  </data>\n</root>"
  },
  {
    "path": "src/System.Web.Razor/StateMachine.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Razor\n{\n    public abstract class StateMachine<TReturn>\n    {\n        protected delegate StateResult State();\n\n        protected abstract State StartState { get; }\n\n        protected State CurrentState { get; set; }\n\n        protected virtual TReturn Turn()\n        {\n            if (CurrentState != null)\n            {\n                StateResult result;\n                do\n                {\n                    // Keep running until we get a null result or output\n                    result = CurrentState();\n                    CurrentState = result.Next;\n                }\n                while (result != null && !result.HasOutput);\n\n                if (result == null)\n                {\n                    return default(TReturn); // Terminated\n                }\n                return result.Output;\n            }\n            return default(TReturn);\n        }\n\n        /// <summary>\n        /// Returns a result indicating that the machine should stop executing and return null output.\n        /// </summary>\n        protected StateResult Stop()\n        {\n            return null;\n        }\n\n        /// <summary>\n        /// Returns a result indicating that this state has no output and the machine should immediately invoke the specified state\n        /// </summary>\n        /// <remarks>\n        /// By returning no output, the state machine will invoke the next state immediately, before returning\n        /// controller to the caller of <see cref=\"Turn\"/>\n        /// </remarks>\n        protected StateResult Transition(State newState)\n        {\n            return new StateResult(newState);\n        }\n\n        /// <summary>\n        /// Returns a result containing the specified output and indicating that the next call to\n        /// <see cref=\"Turn\"/> should invoke the provided state.\n        /// </summary>\n        protected StateResult Transition(TReturn output, State newState)\n        {\n            return new StateResult(output, newState);\n        }\n\n        /// <summary>\n        /// Returns a result indicating that this state has no output and the machine should remain in this state\n        /// </summary>\n        /// <remarks>\n        /// By returning no output, the state machine will re-invoke the current state again before returning\n        /// controller to the caller of <see cref=\"Turn\"/>\n        /// </remarks>\n        protected StateResult Stay()\n        {\n            return new StateResult(CurrentState);\n        }\n\n        /// <summary>\n        /// Returns a result containing the specified output and indicating that the next call to\n        /// <see cref=\"Turn\"/> should re-invoke the current state.\n        /// </summary>\n        protected StateResult Stay(TReturn output)\n        {\n            return new StateResult(output, CurrentState);\n        }\n\n        protected class StateResult\n        {\n            public StateResult(State next)\n            {\n                HasOutput = false;\n                Next = next;\n            }\n\n            public StateResult(TReturn output, State next)\n            {\n                HasOutput = true;\n                Output = output;\n                Next = next;\n            }\n\n            public bool HasOutput { get; set; }\n            public TReturn Output { get; set; }\n            public State Next { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/System.Web.Razor.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{8F18041B-9410-4C36-A9C5-067813DF5F31}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <RootNamespace>System.Web.Razor</RootNamespace>\n    <AssemblyName>System.Web.Razor</AssemblyName>\n    <DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>\n    <RunCodeAnalysis>$(CodeAnalysis)</RunCodeAnalysis>\n    <CodeAnalysisRuleSet>..\\Strict.ruleset</CodeAnalysisRuleSet>\n    <DefineConstants>$(DefineConstants);ASPNETWEBPAGES</DefineConstants>\n    <NoWarn>1591</NoWarn>\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\n    <DefineConstants>$(DefineConstants);EDITOR_TRACING</DefineConstants>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"System\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\CommonAssemblyInfo.cs\">\n      <Link>Properties\\CommonAssemblyInfo.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\CommonResources.Designer.cs\">\n      <Link>Common\\CommonResources.Designer.cs</Link>\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>CommonResources.resx</DependentUpon>\n    </Compile>\n    <Compile Include=\"..\\Common\\HashCodeCombiner.cs\">\n      <Link>Common\\HashCodeCombiner.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\GlobalSuppressions.cs\">\n      <Link>Common\\GlobalSuppressions.cs</Link>\n    </Compile>\n    <Compile Include=\"DocumentParseCompleteEventArgs.cs\" />\n    <Compile Include=\"Editor\\AutoCompleteEditHandler.cs\" />\n    <Compile Include=\"Editor\\BackgroundParser.cs\" />\n    <Compile Include=\"Editor\\RazorEditorTrace.cs\" />\n    <Compile Include=\"Generator\\AttributeBlockCodeGenerator.cs\" />\n    <Compile Include=\"Generator\\CodeWriterExtensions.cs\" />\n    <Compile Include=\"Generator\\DynamicAttributeBlockCodeGenerator.cs\" />\n    <Compile Include=\"Generator\\ExpressionRenderingMode.cs\" />\n    <Compile Include=\"Generator\\LiteralAttributeCodeGenerator.cs\" />\n    <Compile Include=\"Generator\\RazorCommentCodeGenerator.cs\" />\n    <Compile Include=\"Generator\\SetLayoutCodeGenerator.cs\" />\n    <Compile Include=\"Editor\\SingleLineMarkupEditHandler.cs\" />\n    <Compile Include=\"Editor\\SpanEditHandler.cs\" />\n    <Compile Include=\"Editor\\EditResult.cs\" />\n    <Compile Include=\"Editor\\ImplicitExpressionEditHandler.cs\" />\n    <Compile Include=\"Editor\\EditorHints.cs\" />\n    <Compile Include=\"Generator\\AddImportCodeGenerator.cs\" />\n    <Compile Include=\"Generator\\BlockCodeGenerator.cs\" />\n    <Compile Include=\"Generator\\CodeGeneratorPaddingHelper.cs\" />\n    <Compile Include=\"Generator\\CodeGeneratorContext.cs\" />\n    <Compile Include=\"Generator\\CodeWriter.cs\" />\n    <Compile Include=\"Generator\\BaseCodeWriter.cs\" />\n    <Compile Include=\"Generator\\RazorDirectiveAttributeCodeGenerator.cs\" />\n    <Compile Include=\"Generator\\CSharpCodeWriter.cs\" />\n    <Compile Include=\"Generator\\ExpressionCodeGenerator.cs\" />\n    <Compile Include=\"Generator\\GeneratedClassContext.cs\" />\n    <Compile Include=\"Generator\\HybridCodeGenerator.cs\" />\n    <Compile Include=\"Generator\\IBlockCodeGenerator.cs\" />\n    <Compile Include=\"Generator\\ISpanCodeGenerator.cs\" />\n    <Compile Include=\"Generator\\MarkupCodeGenerator.cs\" />\n    <Compile Include=\"Generator\\ResolveUrlCodeGenerator.cs\" />\n    <Compile Include=\"Generator\\SetBaseTypeCodeGenerator.cs\" />\n    <Compile Include=\"Generator\\HelperCodeGenerator.cs\" />\n    <Compile Include=\"Generator\\SectionCodeGenerator.cs\" />\n    <Compile Include=\"Generator\\SetVBOptionCodeGenerator.cs\" />\n    <Compile Include=\"Generator\\SpanCodeGenerator.cs\" />\n    <Compile Include=\"Generator\\StatementCodeGenerator.cs\" />\n    <Compile Include=\"Generator\\TemplateBlockCodeGenerator.cs\" />\n    <Compile Include=\"Generator\\TypeMemberCodeGenerator.cs\" />\n    <Compile Include=\"Generator\\VBCodeWriter.cs\" />\n    <Compile Include=\"Parser\\BalancingModes.cs\" />\n    <Compile Include=\"Parser\\CallbackVisitor.cs\" />\n    <Compile Include=\"Parser\\ConditionalAttributeCollapser.cs\" />\n    <Compile Include=\"Parser\\CSharpCodeParser.Directives.cs\" />\n    <Compile Include=\"Parser\\CSharpCodeParser.Statements.cs\" />\n    <Compile Include=\"Parser\\CSharpCodeParser.cs\" />\n    <Compile Include=\"Parser\\CSharpLanguageCharacteristics.cs\" />\n    <Compile Include=\"Parser\\HtmlLanguageCharacteristics.cs\" />\n    <Compile Include=\"Parser\\HtmlMarkupParser.Block.cs\" />\n    <Compile Include=\"Parser\\HtmlMarkupParser.Document.cs\" />\n    <Compile Include=\"Parser\\HtmlMarkupParser.cs\" />\n    <Compile Include=\"Parser\\HtmlMarkupParser.Section.cs\" />\n    <Compile Include=\"Parser\\ISyntaxTreeRewriter.cs\" />\n    <Compile Include=\"Parser\\LanguageCharacteristics.cs\" />\n    <Compile Include=\"Parser\\MarkupCollapser.cs\" />\n    <Compile Include=\"Parser\\MarkupRewriter.cs\" />\n    <Compile Include=\"Parser\\ParserHelpers.cs\" />\n    <Compile Include=\"Parser\\ParserVisitor.cs\" />\n    <Compile Include=\"Parser\\ParserVisitorExtensions.cs\" />\n    <Compile Include=\"Parser\\SyntaxConstants.cs\" />\n    <Compile Include=\"Parser\\SyntaxTree\\AcceptedCharacters.cs\" />\n    <Compile Include=\"Parser\\SyntaxTree\\BlockBuilder.cs\" />\n    <Compile Include=\"Parser\\SyntaxTree\\EquivalenceComparer.cs\" />\n    <Compile Include=\"Parser\\SyntaxTree\\SpanBuilder.cs\" />\n    <Compile Include=\"Parser\\TextReaderExtensions.cs\" />\n    <Compile Include=\"Parser\\TokenizerBackedParser.cs\" />\n    <Compile Include=\"Parser\\TokenizerBackedParser.Helpers.cs\" />\n    <Compile Include=\"Parser\\VBCodeParser.cs\" />\n    <Compile Include=\"Parser\\VBCodeParser.Directives.cs\" />\n    <Compile Include=\"Parser\\VBLanguageCharacteristics.cs\" />\n    <Compile Include=\"Parser\\WhitespaceRewriter.cs\" />\n    <Compile Include=\"PartialParseResult.cs\" />\n    <Compile Include=\"RazorDebugHelpers.cs\" />\n    <Compile Include=\"RazorDirectiveAttribute.cs\" />\n    <Compile Include=\"RazorEditorParser.cs\" />\n    <Compile Include=\"Generator\\CodeGenerationCompleteEventArgs.cs\" />\n    <Compile Include=\"Generator\\GeneratedCodeMapping.cs\" />\n    <Compile Include=\"Generator\\RazorCodeGenerator.cs\" />\n    <Compile Include=\"GeneratorResults.cs\" />\n    <Compile Include=\"RazorEngineHost.cs\" />\n    <Compile Include=\"RazorTemplateEngine.cs\" />\n    <Compile Include=\"StateMachine.cs\" />\n    <Compile Include=\"Text\\BufferingTextReader.cs\" />\n    <Compile Include=\"Text\\LookaheadToken.cs\" />\n    <Compile Include=\"Text\\LocationTagged.cs\" />\n    <Compile Include=\"Text\\SeekableTextReader.cs\" />\n    <Compile Include=\"Text\\LineTrackingStringBuffer.cs\" />\n    <Compile Include=\"Text\\LookaheadTextReader.cs\" />\n    <Compile Include=\"Text\\TextExtensions.cs\" />\n    <Compile Include=\"Text\\TextBufferReader.cs\" />\n    <Compile Include=\"Text\\TextDocumentReader.cs\" />\n    <Compile Include=\"Tokenizer\\ITokenizer.cs\" />\n    <Compile Include=\"Tokenizer\\Symbols\\ISymbol.cs\" />\n    <Compile Include=\"Tokenizer\\Symbols\\KnownSymbolType.cs\" />\n    <Compile Include=\"Tokenizer\\Symbols\\SymbolExtensions.cs\" />\n    <Compile Include=\"Tokenizer\\Symbols\\SymbolTypeSuppressions.cs\" />\n    <Compile Include=\"Tokenizer\\TokenizerView.cs\" />\n    <Compile Include=\"Tokenizer\\VBKeywordDetector.cs\" />\n    <Compile Include=\"Tokenizer\\VBHelpers.cs\" />\n    <Compile Include=\"Tokenizer\\CSharpHelpers.cs\" />\n    <Compile Include=\"Tokenizer\\CSharpKeywordDetector.cs\" />\n    <Compile Include=\"Tokenizer\\CSharpTokenizer.cs\" />\n    <Compile Include=\"Tokenizer\\HtmlTokenizer.cs\" />\n    <Compile Include=\"Tokenizer\\Symbols\\VBKeyword.cs\" />\n    <Compile Include=\"Tokenizer\\Symbols\\VBSymbol.cs\" />\n    <Compile Include=\"Tokenizer\\Symbols\\VBSymbolType.cs\" />\n    <Compile Include=\"Tokenizer\\Symbols\\CSharpKeyword.cs\" />\n    <Compile Include=\"Tokenizer\\Symbols\\CSharpSymbol.cs\" />\n    <Compile Include=\"Tokenizer\\Symbols\\CSharpSymbolType.cs\" />\n    <Compile Include=\"Tokenizer\\Symbols\\HtmlSymbol.cs\" />\n    <Compile Include=\"Tokenizer\\Symbols\\HtmlSymbolType.cs\" />\n    <Compile Include=\"Tokenizer\\Symbols\\SymbolBase.cs\" />\n    <Compile Include=\"Tokenizer\\Tokenizer.cs\" />\n    <Compile Include=\"Tokenizer\\VBTokenizer.cs\" />\n    <Compile Include=\"Tokenizer\\XmlHelpers.cs\" />\n    <Compile Include=\"Utils\\CharUtils.cs\" />\n    <Compile Include=\"VBRazorCodeLanguage.cs\" />\n    <Compile Include=\"Generator\\CSharpRazorCodeGenerator.cs\" />\n    <Compile Include=\"Parser\\SyntaxTree\\BlockType.cs\" />\n    <Compile Include=\"Parser\\SyntaxTree\\Block.cs\" />\n    <Compile Include=\"Parser\\SyntaxTree\\RazorError.cs\" />\n    <Compile Include=\"ParserResults.cs\" />\n    <Compile Include=\"Parser\\SyntaxTree\\SyntaxTreeNode.cs\" />\n    <Compile Include=\"Parser\\SyntaxTree\\SpanKind.cs\" />\n    <Compile Include=\"Parser\\ParserContext.cs\" />\n    <Compile Include=\"Parser\\RazorParser.cs\" />\n    <Compile Include=\"Text\\ITextBuffer.cs\" />\n    <Compile Include=\"Text\\SourceLocationTracker.cs\" />\n    <Compile Include=\"RazorCodeLanguage.cs\" />\n    <Compile Include=\"CSharpRazorCodeLanguage.cs\" />\n    <Compile Include=\"Utils\\DisposableAction.cs\" />\n    <Compile Include=\"Utils\\EnumUtil.cs\" />\n    <Compile Include=\"Utils\\EnumeratorExtensions.cs\" />\n    <Compile Include=\"GlobalSuppressions.cs\" />\n    <Compile Include=\"Parser\\ParserBase.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"Resources\\RazorResources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>RazorResources.resx</DependentUpon>\n    </Compile>\n    <Compile Include=\"Text\\SourceLocation.cs\" />\n    <Compile Include=\"Text\\TextChange.cs\" />\n    <Compile Include=\"Text\\TextChangeType.cs\" />\n    <Compile Include=\"Parser\\SyntaxTree\\Span.cs\" />\n    <Compile Include=\"Generator\\VBRazorCodeGenerator.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"..\\CommonResources.resx\">\n      <Link>Common\\CommonResources.resx</Link>\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>CommonResources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n    <EmbeddedResource Include=\"Resources\\RazorResources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>RazorResources.Designer.cs</LastGenOutput>\n      <SubType>Designer</SubType>\n    </EmbeddedResource>\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"Parser\\VBCodeParser.Statements.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <CodeAnalysisDictionary Include=\"..\\CodeAnalysisDictionary.xml\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n</Project>"
  },
  {
    "path": "src/System.Web.Razor/Text/BufferingTextReader.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Utils;\n\nnamespace System.Web.Razor.Text\n{\n    public class BufferingTextReader : LookaheadTextReader\n    {\n        private Stack<BacktrackContext> _backtrackStack = new Stack<BacktrackContext>();\n        private int _currentBufferPosition;\n\n        private int _currentCharacter;\n        private SourceLocationTracker _locationTracker;\n\n        public BufferingTextReader(TextReader source)\n        {\n            if (source == null)\n            {\n                throw new ArgumentNullException(\"source\");\n            }\n\n            InnerReader = source;\n            _locationTracker = new SourceLocationTracker();\n\n            UpdateCurrentCharacter();\n        }\n\n        internal StringBuilder Buffer { get; set; }\n        internal bool Buffering { get; set; }\n        internal TextReader InnerReader { get; private set; }\n\n        public override SourceLocation CurrentLocation\n        {\n            get { return _locationTracker.CurrentLocation; }\n        }\n\n        protected virtual int CurrentCharacter\n        {\n            get { return _currentCharacter; }\n        }\n\n        public override int Read()\n        {\n            int ch = CurrentCharacter;\n            NextCharacter();\n            return ch;\n        }\n\n        // TODO: Optimize Read(char[],int,int) to copy direct from the buffer where possible\n\n        public override int Peek()\n        {\n            return CurrentCharacter;\n        }\n\n        protected override void Dispose(bool disposing)\n        {\n            if (disposing)\n            {\n                InnerReader.Dispose();\n            }\n            base.Dispose(disposing);\n        }\n\n        public override IDisposable BeginLookahead()\n        {\n            // Is this our first lookahead?\n            if (Buffer == null)\n            {\n                // Yes, setup the backtrack buffer\n                Buffer = new StringBuilder();\n            }\n\n            if (!Buffering)\n            {\n                // We're not already buffering, so we need to expand the buffer to hold the first character\n                ExpandBuffer();\n                Buffering = true;\n            }\n\n            // Mark the position to return to when we backtrack\n            // Use the closures and the \"using\" statement rather than an explicit stack\n            BacktrackContext context = new BacktrackContext()\n            {\n                BufferIndex = _currentBufferPosition,\n                Location = CurrentLocation\n            };\n            _backtrackStack.Push(context);\n            return new DisposableAction(() =>\n            {\n                EndLookahead(context);\n            });\n        }\n\n        // REVIEW: This really doesn't sound like the best name for this...\n        public override void CancelBacktrack()\n        {\n            if (_backtrackStack.Count == 0)\n            {\n                throw new InvalidOperationException(RazorResources.CancelBacktrack_Must_Be_Called_Within_Lookahead);\n            }\n            // Just pop the current backtrack context so that when the lookahead ends, it won't be backtracked\n            _backtrackStack.Pop();\n        }\n\n        private void EndLookahead(BacktrackContext context)\n        {\n            // If the specified context is not the one on the stack, it was popped by a call to DoNotBacktrack\n            if (_backtrackStack.Count > 0 && ReferenceEquals(_backtrackStack.Peek(), context))\n            {\n                _backtrackStack.Pop();\n                _currentBufferPosition = context.BufferIndex;\n                _locationTracker.CurrentLocation = context.Location;\n\n                UpdateCurrentCharacter();\n            }\n        }\n\n        protected virtual void NextCharacter()\n        {\n            int prevChar = CurrentCharacter;\n            if (prevChar == -1)\n            {\n                return; // We're at the end of the source\n            }\n\n            if (Buffering)\n            {\n                if (_currentBufferPosition >= Buffer.Length - 1)\n                {\n                    // If there are no more lookaheads (thus no need to continue with the buffer) we can just clean up the buffer\n                    if (_backtrackStack.Count == 0)\n                    {\n                        // Reset the buffer\n                        Buffer.Length = 0;\n                        _currentBufferPosition = 0;\n                        Buffering = false;\n                    }\n                    else if (!ExpandBuffer())\n                    {\n                        // Failed to expand the buffer, because we're at the end of the source\n                        _currentBufferPosition = Buffer.Length; // Force the position past the end of the buffer\n                    }\n                }\n                else\n                {\n                    // Not at the end yet, just advance the buffer pointer\n                    _currentBufferPosition++;\n                }\n            }\n            else\n            {\n                // Just act like normal\n                InnerReader.Read(); // Don't care about the return value, Peek() is used to get characters from the source\n            }\n\n            UpdateCurrentCharacter();\n            _locationTracker.UpdateLocation((char)prevChar, (char)CurrentCharacter);\n        }\n\n        protected bool ExpandBuffer()\n        {\n            // Pull another character into the buffer and update the position\n            int ch = InnerReader.Read();\n\n            // Only append the character to the buffer if there actually is one\n            if (ch != -1)\n            {\n                Buffer.Append((char)ch);\n                _currentBufferPosition = Buffer.Length - 1;\n                return true;\n            }\n            return false;\n        }\n\n        private void UpdateCurrentCharacter()\n        {\n            if (Buffering && _currentBufferPosition < Buffer.Length)\n            {\n                // Read from the buffer\n                _currentCharacter = (int)Buffer[_currentBufferPosition];\n            }\n            else\n            {\n                // No buffer? Peek from the source\n                _currentCharacter = InnerReader.Peek();\n            }\n        }\n\n        private class BacktrackContext\n        {\n            public int BufferIndex { get; set; }\n            public SourceLocation Location { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Text/ITextBuffer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Razor.Text\n{\n    public interface ITextBuffer\n    {\n        int Length { get; }\n        int Position { get; set; }\n        int Read();\n        int Peek();\n    }\n\n    // TextBuffer with Location tracking\n    public interface ITextDocument : ITextBuffer\n    {\n        SourceLocation Location { get; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Text/LineTrackingStringBuffer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Text;\nusing System.Web.Razor.Parser;\n\nnamespace System.Web.Razor.Text\n{\n    internal class LineTrackingStringBuffer\n    {\n        private TextLine _currentLine;\n        private TextLine _endLine;\n        private IList<TextLine> _lines;\n\n        public LineTrackingStringBuffer()\n        {\n            _endLine = new TextLine(0, 0);\n            _lines = new List<TextLine>() { _endLine };\n        }\n\n        public int Length\n        {\n            get { return _endLine.End; }\n        }\n\n        public SourceLocation EndLocation\n        {\n            get { return new SourceLocation(Length, _lines.Count - 1, _lines[_lines.Count - 1].Length); }\n        }\n\n        public void Append(string content)\n        {\n            for (int i = 0; i < content.Length; i++)\n            {\n                AppendCore(content[i]);\n\n                // \\r on it's own: Start a new line, otherwise wait for \\n\n                // Other Newline: Start a new line\n                if ((content[i] == '\\r' && (i + 1 == content.Length || content[i + 1] != '\\n')) || (content[i] != '\\r' && ParserHelpers.IsNewLine(content[i])))\n                {\n                    PushNewLine();\n                }\n            }\n        }\n\n        public CharacterReference CharAt(int absoluteIndex)\n        {\n            TextLine line = FindLine(absoluteIndex);\n            if (line == null)\n            {\n                throw new ArgumentOutOfRangeException(\"absoluteIndex\");\n            }\n            int idx = absoluteIndex - line.Start;\n            return new CharacterReference(line.Content[idx], new SourceLocation(absoluteIndex, line.Index, idx));\n        }\n\n        private void PushNewLine()\n        {\n            _endLine = new TextLine(_endLine.End, _endLine.Index + 1);\n            _lines.Add(_endLine);\n        }\n\n        private void AppendCore(char chr)\n        {\n            Debug.Assert(_lines.Count > 0);\n            _lines[_lines.Count - 1].Content.Append(chr);\n        }\n\n        private TextLine FindLine(int absoluteIndex)\n        {\n            TextLine selected = null;\n\n            if (_currentLine != null)\n            {\n                if (_currentLine.Contains(absoluteIndex))\n                {\n                    // This index is on the last read line\n                    selected = _currentLine;\n                }\n                else if (absoluteIndex > _currentLine.Index && _currentLine.Index + 1 < _lines.Count)\n                {\n                    // This index is ahead of the last read line\n                    selected = ScanLines(absoluteIndex, _currentLine.Index);\n                }\n            }\n\n            // Have we found a line yet?\n            if (selected == null)\n            {\n                // Scan from line 0\n                selected = ScanLines(absoluteIndex, 0);\n            }\n\n            Debug.Assert(selected == null || selected.Contains(absoluteIndex));\n            _currentLine = selected;\n            return selected;\n        }\n\n        private TextLine ScanLines(int absoluteIndex, int startPos)\n        {\n            for (int i = 0; i < _lines.Count; i++)\n            {\n                int idx = (i + startPos) % _lines.Count;\n                Debug.Assert(idx >= 0 && idx < _lines.Count);\n\n                if (_lines[idx].Contains(absoluteIndex))\n                {\n                    return _lines[idx];\n                }\n            }\n            return null;\n        }\n\n        internal class CharacterReference\n        {\n            public CharacterReference(char character, SourceLocation location)\n            {\n                Character = character;\n                Location = location;\n            }\n\n            public char Character { get; private set; }\n            public SourceLocation Location { get; private set; }\n        }\n\n        private class TextLine\n        {\n            private StringBuilder _content = new StringBuilder();\n\n            public TextLine(int start, int index)\n            {\n                Start = start;\n                Index = index;\n            }\n\n            public StringBuilder Content\n            {\n                get { return _content; }\n            }\n\n            public int Length\n            {\n                get { return Content.Length; }\n            }\n\n            public int Start { get; set; }\n            public int Index { get; set; }\n\n            public int End\n            {\n                get { return Start + Length; }\n            }\n\n            public bool Contains(int index)\n            {\n                return index < End && index >= Start;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Text/LocationTagged.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics;\nusing System.Globalization;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Razor.Text\n{\n    [DebuggerDisplay(\"({Location})\\\"{Value}\\\"\")]\n    public class LocationTagged<T> : IFormattable\n    {\n        private LocationTagged()\n        {\n            Location = SourceLocation.Undefined;\n            Value = default(T);\n        }\n\n        public LocationTagged(T value, int offset, int line, int col)\n            : this(value, new SourceLocation(offset, line, col))\n        {\n        }\n\n        public LocationTagged(T value, SourceLocation location)\n        {\n            if (value == null)\n            {\n                throw new ArgumentNullException(\"value\");\n            }\n\n            Location = location;\n            Value = value;\n        }\n\n        public SourceLocation Location { get; private set; }\n        public T Value { get; private set; }\n\n        public override bool Equals(object obj)\n        {\n            LocationTagged<T> other = obj as LocationTagged<T>;\n            return other != null &&\n                   Equals(other.Location, Location) &&\n                   Equals(other.Value, Value);\n        }\n\n        public override int GetHashCode()\n        {\n            return HashCodeCombiner.Start()\n                .Add(Location)\n                .Add(Value)\n                .CombinedHash;\n        }\n\n        public override string ToString()\n        {\n            return Value.ToString();\n        }\n\n        public string ToString(string format, IFormatProvider formatProvider)\n        {\n            if (String.IsNullOrEmpty(format))\n            {\n                format = \"P\";\n            }\n            if (formatProvider == null)\n            {\n                formatProvider = CultureInfo.CurrentCulture;\n            }\n            switch (format.ToUpperInvariant())\n            {\n                case \"F\":\n                    return String.Format(formatProvider, \"{0}@{1}\", Value, Location);\n                default:\n                    return Value.ToString();\n            }\n        }\n\n        public static implicit operator T(LocationTagged<T> value)\n        {\n            return value.Value;\n        }\n\n        public static bool operator ==(LocationTagged<T> left, LocationTagged<T> right)\n        {\n            return Equals(left, right);\n        }\n\n        public static bool operator !=(LocationTagged<T> left, LocationTagged<T> right)\n        {\n            return !Equals(left, right);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Text/LookaheadTextReader.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\n\nnamespace System.Web.Razor.Text\n{\n    public abstract class LookaheadTextReader : TextReader\n    {\n        public abstract SourceLocation CurrentLocation { get; }\n        public abstract IDisposable BeginLookahead();\n        public abstract void CancelBacktrack();\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Text/LookaheadToken.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Razor.Text\n{\n    public class LookaheadToken : IDisposable\n    {\n        private Action _cancelAction;\n        private bool _accepted;\n\n        public LookaheadToken(Action cancelAction)\n        {\n            _cancelAction = cancelAction;\n        }\n\n        public void Accept()\n        {\n            _accepted = true;\n        }\n\n        public void Dispose()\n        {\n            Dispose(true);\n            GC.SuppressFinalize(this);\n        }\n\n        protected virtual void Dispose(bool disposing)\n        {\n            if (!_accepted)\n            {\n                _cancelAction();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Text/SeekableTextReader.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\n\nnamespace System.Web.Razor.Text\n{\n    public class SeekableTextReader : TextReader, ITextDocument\n    {\n        private int _position = 0;\n        private LineTrackingStringBuffer _buffer = new LineTrackingStringBuffer();\n        private SourceLocation _location = SourceLocation.Zero;\n        private char? _current;\n\n        public SeekableTextReader(string content)\n        {\n            _buffer.Append(content);\n            UpdateState();\n        }\n\n        public SeekableTextReader(TextReader source)\n            : this(source.ReadToEnd())\n        {\n        }\n\n        public SeekableTextReader(ITextBuffer buffer)\n            : this(buffer.ReadToEnd())\n        {\n        }\n\n        public SourceLocation Location\n        {\n            get { return _location; }\n        }\n\n        public int Length\n        {\n            get { return _buffer.Length; }\n        }\n\n        public int Position\n        {\n            get { return _position; }\n            set\n            {\n                if (_position != value)\n                {\n                    _position = value;\n                    UpdateState();\n                }\n            }\n        }\n\n        internal LineTrackingStringBuffer Buffer\n        {\n            get { return _buffer; }\n        }\n\n        public override int Read()\n        {\n            if (_current == null)\n            {\n                return -1;\n            }\n            char chr = _current.Value;\n            _position++;\n            UpdateState();\n            return chr;\n        }\n\n        public override int Peek()\n        {\n            if (_current == null)\n            {\n                return -1;\n            }\n            return _current.Value;\n        }\n\n        private void UpdateState()\n        {\n            if (_position < _buffer.Length)\n            {\n                LineTrackingStringBuffer.CharacterReference chr = _buffer.CharAt(_position);\n                _current = chr.Character;\n                _location = chr.Location;\n            }\n            else if (_buffer.Length == 0)\n            {\n                _current = null;\n                _location = SourceLocation.Zero;\n            }\n            else\n            {\n                _current = null;\n                _location = _buffer.EndLocation;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Text/SourceLocation.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\n\nnamespace System.Web.Razor.Text\n{\n    [Serializable]\n    public struct SourceLocation : IEquatable<SourceLocation>, IComparable<SourceLocation>\n    {\n        public static readonly SourceLocation Undefined = CreateUndefined();\n        public static readonly SourceLocation Zero = new SourceLocation(0, 0, 0);\n\n        private int _absoluteIndex;\n        private int _lineIndex;\n        private int _characterIndex;\n\n        public SourceLocation(int absoluteIndex, int lineIndex, int characterIndex)\n        {\n            _absoluteIndex = absoluteIndex;\n            _lineIndex = lineIndex;\n            _characterIndex = characterIndex;\n        }\n\n        public int AbsoluteIndex\n        {\n            get { return _absoluteIndex; }\n        }\n\n        /// <summary>\n        /// Gets the 1-based index of the line referred to by this Source Location.\n        /// </summary>\n        public int LineIndex\n        {\n            get { return _lineIndex; }\n        }\n\n        public int CharacterIndex\n        {\n            get { return _characterIndex; }\n        }\n\n        public override string ToString()\n        {\n            return String.Format(CultureInfo.CurrentCulture, \"({0}:{1},{2})\", AbsoluteIndex, LineIndex, CharacterIndex);\n        }\n\n        public override bool Equals(object obj)\n        {\n            return (obj is SourceLocation) && Equals((SourceLocation)obj);\n        }\n\n        public override int GetHashCode()\n        {\n            // LineIndex and CharacterIndex can be calculated from AbsoluteIndex and the document content.\n            return AbsoluteIndex;\n        }\n\n        public bool Equals(SourceLocation other)\n        {\n            return AbsoluteIndex == other.AbsoluteIndex &&\n                   LineIndex == other.LineIndex &&\n                   CharacterIndex == other.CharacterIndex;\n        }\n\n        public int CompareTo(SourceLocation other)\n        {\n            return AbsoluteIndex.CompareTo(other.AbsoluteIndex);\n        }\n\n        public static SourceLocation Advance(SourceLocation left, string text)\n        {\n            SourceLocationTracker tracker = new SourceLocationTracker(left);\n            tracker.UpdateLocation(text);\n            return tracker.CurrentLocation;\n        }\n\n        public static SourceLocation Add(SourceLocation left, SourceLocation right)\n        {\n            if (right.LineIndex > 0)\n            {\n                // Column index doesn't matter\n                return new SourceLocation(left.AbsoluteIndex + right.AbsoluteIndex, left.LineIndex + right.LineIndex, right.CharacterIndex);\n            }\n            else\n            {\n                return new SourceLocation(left.AbsoluteIndex + right.AbsoluteIndex, left.LineIndex + right.LineIndex, left.CharacterIndex + right.CharacterIndex);\n            }\n        }\n\n        public static SourceLocation Subtract(SourceLocation left, SourceLocation right)\n        {\n            return new SourceLocation(left.AbsoluteIndex - right.AbsoluteIndex,\n                                      left.LineIndex - right.LineIndex,\n                                      left.LineIndex != right.LineIndex ? left.CharacterIndex : left.CharacterIndex - right.CharacterIndex);\n        }\n\n        private static SourceLocation CreateUndefined()\n        {\n            SourceLocation sl = new SourceLocation();\n            sl._absoluteIndex = -1;\n            sl._lineIndex = -1;\n            sl._characterIndex = -1;\n            return sl;\n        }\n\n        public static bool operator <(SourceLocation left, SourceLocation right)\n        {\n            return left.CompareTo(right) < 0;\n        }\n\n        public static bool operator >(SourceLocation left, SourceLocation right)\n        {\n            return left.CompareTo(right) > 0;\n        }\n\n        public static bool operator ==(SourceLocation left, SourceLocation right)\n        {\n            return left.Equals(right);\n        }\n\n        public static bool operator !=(SourceLocation left, SourceLocation right)\n        {\n            return !left.Equals(right);\n        }\n\n        public static SourceLocation operator +(SourceLocation left, SourceLocation right)\n        {\n            return Add(left, right);\n        }\n\n        public static SourceLocation operator -(SourceLocation left, SourceLocation right)\n        {\n            return Subtract(left, right);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Text/SourceLocationTracker.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser;\n\nnamespace System.Web.Razor.Text\n{\n    public class SourceLocationTracker\n    {\n        private int _absoluteIndex = 0;\n        private int _characterIndex = 0;\n        private int _lineIndex = 0;\n        private SourceLocation _currentLocation;\n\n        public SourceLocationTracker()\n            : this(SourceLocation.Zero)\n        {\n        }\n\n        public SourceLocationTracker(SourceLocation currentLocation)\n        {\n            CurrentLocation = currentLocation;\n\n            UpdateInternalState();\n        }\n\n        public SourceLocation CurrentLocation\n        {\n            get\n            {\n                return _currentLocation;\n            }\n            set\n            {\n                if (_currentLocation != value)\n                {\n                    _currentLocation = value;\n                    UpdateInternalState();\n                }\n            }\n        }\n\n        public void UpdateLocation(char characterRead, char nextCharacter)\n        {\n            UpdateCharacterCore(characterRead, nextCharacter);\n            RecalculateSourceLocation();\n        }\n\n        public SourceLocationTracker UpdateLocation(string content)\n        {\n            for (int i = 0; i < content.Length; i++)\n            {\n                char nextCharacter = '\\0';\n                if (i < content.Length - 1)\n                {\n                    nextCharacter = content[i + 1];\n                }\n                UpdateCharacterCore(content[i], nextCharacter);\n            }\n            RecalculateSourceLocation();\n            return this;\n        }\n\n        private void UpdateCharacterCore(char characterRead, char nextCharacter)\n        {\n            _absoluteIndex++;\n\n            if (ParserHelpers.IsNewLine(characterRead) && (characterRead != '\\r' || nextCharacter != '\\n'))\n            {\n                _lineIndex++;\n                _characterIndex = 0;\n            }\n            else\n            {\n                _characterIndex++;\n            }\n        }\n\n        private void UpdateInternalState()\n        {\n            _absoluteIndex = CurrentLocation.AbsoluteIndex;\n            _characterIndex = CurrentLocation.CharacterIndex;\n            _lineIndex = CurrentLocation.LineIndex;\n        }\n\n        private void RecalculateSourceLocation()\n        {\n            _currentLocation = new SourceLocation(_absoluteIndex, _lineIndex, _characterIndex);\n        }\n\n        public static SourceLocation CalculateNewLocation(SourceLocation lastPosition, string newContent)\n        {\n            return new SourceLocationTracker(lastPosition).UpdateLocation(newContent).CurrentLocation;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Text/TextBufferReader.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Utils;\n\nnamespace System.Web.Razor.Text\n{\n    public class TextBufferReader : LookaheadTextReader\n    {\n        private Stack<BacktrackContext> _bookmarks = new Stack<BacktrackContext>();\n        private SourceLocationTracker _tracker = new SourceLocationTracker();\n\n        public TextBufferReader(ITextBuffer buffer)\n        {\n            if (buffer == null)\n            {\n                throw new ArgumentNullException(\"buffer\");\n            }\n\n            InnerBuffer = buffer;\n        }\n\n        internal ITextBuffer InnerBuffer { get; private set; }\n\n        public override SourceLocation CurrentLocation\n        {\n            get { return _tracker.CurrentLocation; }\n        }\n\n        public override int Peek()\n        {\n            return InnerBuffer.Peek();\n        }\n\n        public override int Read()\n        {\n            int read = InnerBuffer.Read();\n            if (read != -1)\n            {\n                char nextChar = '\\0';\n                int next = Peek();\n                if (next != -1)\n                {\n                    nextChar = (char)next;\n                }\n                _tracker.UpdateLocation((char)read, nextChar);\n            }\n            return read;\n        }\n\n        protected override void Dispose(bool disposing)\n        {\n            if (disposing)\n            {\n                IDisposable disposable = InnerBuffer as IDisposable;\n                if (disposable != null)\n                {\n                    disposable.Dispose();\n                }\n            }\n            base.Dispose(disposing);\n        }\n\n        public override IDisposable BeginLookahead()\n        {\n            BacktrackContext context = new BacktrackContext() { Location = CurrentLocation };\n            _bookmarks.Push(context);\n            return new DisposableAction(() =>\n            {\n                EndLookahead(context);\n            });\n        }\n\n        public override void CancelBacktrack()\n        {\n            if (_bookmarks.Count == 0)\n            {\n                throw new InvalidOperationException(RazorResources.CancelBacktrack_Must_Be_Called_Within_Lookahead);\n            }\n            _bookmarks.Pop();\n        }\n\n        private void EndLookahead(BacktrackContext context)\n        {\n            if (_bookmarks.Count > 0 && ReferenceEquals(_bookmarks.Peek(), context))\n            {\n                // Backtrack wasn't cancelled, so pop it\n                _bookmarks.Pop();\n\n                // Set the new current location\n                _tracker.CurrentLocation = context.Location;\n                InnerBuffer.Position = context.Location.AbsoluteIndex;\n            }\n        }\n\n        /// <summary>\n        /// Need a class for reference equality to support cancelling backtrack.\n        /// </summary>\n        private class BacktrackContext\n        {\n            public SourceLocation Location { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Text/TextChange.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.Text;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Razor.Text\n{\n    public struct TextChange\n    {\n        private string _newText;\n        private string _oldText;\n\n        /// <summary>\n        /// Constructor for changes where the position hasn't moved (primarily for tests)\n        /// </summary>\n        internal TextChange(int position, int oldLength, ITextBuffer oldBuffer, int newLength, ITextBuffer newBuffer)\n            : this(position, oldLength, oldBuffer, position, newLength, newBuffer)\n        {\n        }\n\n        public TextChange(int oldPosition, int oldLength, ITextBuffer oldBuffer, int newPosition, int newLength, ITextBuffer newBuffer)\n            : this()\n        {\n            if (oldPosition < 0)\n            {\n                throw new ArgumentOutOfRangeException(\"oldPosition\", String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, \"0\"));\n            }\n            if (newPosition < 0)\n            {\n                throw new ArgumentOutOfRangeException(\"newPosition\", String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, \"0\"));\n            }\n            if (oldLength < 0)\n            {\n                throw new ArgumentOutOfRangeException(\"oldLength\", String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, \"0\"));\n            }\n            if (newLength < 0)\n            {\n                throw new ArgumentOutOfRangeException(\"newLength\", String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, \"0\"));\n            }\n            if (oldBuffer == null)\n            {\n                throw new ArgumentNullException(\"oldBuffer\");\n            }\n            if (newBuffer == null)\n            {\n                throw new ArgumentNullException(\"newBuffer\");\n            }\n\n            OldPosition = oldPosition;\n            NewPosition = newPosition;\n            OldLength = oldLength;\n            NewLength = newLength;\n            NewBuffer = newBuffer;\n            OldBuffer = oldBuffer;\n        }\n\n        public int OldPosition { get; private set; }\n        public int NewPosition { get; private set; }\n        public int OldLength { get; private set; }\n        public int NewLength { get; private set; }\n        public ITextBuffer NewBuffer { get; private set; }\n        public ITextBuffer OldBuffer { get; private set; }\n\n        /// <remark>\n        /// Note: This property is not thread safe, and will move position on the textbuffer while being read.\n        /// https://aspnetwebstack.codeplex.com/workitem/1317, tracks making this immutable and improving the access\n        /// to ITextBuffer to be thread safe.\n        /// </remark>\n        public string OldText\n        {\n            get\n            {\n                if (_oldText == null && OldBuffer != null)\n                {\n                    _oldText = GetText(OldBuffer, OldPosition, OldLength);\n                }\n                return _oldText;\n            }\n        }\n\n        /// <remark>\n        /// Note: This property is not thread safe, and will move position on the textbuffer while being read.\n        /// https://aspnetwebstack.codeplex.com/workitem/1317, tracks making this immutable and improving the access\n        /// to ITextBuffer to be thread safe.\n        /// </remark>\n        public string NewText\n        {\n            get\n            {\n                if (_newText == null)\n                {\n                    _newText = GetText(NewBuffer, NewPosition, NewLength);\n                }\n                return _newText;\n            }\n        }\n\n        public bool IsInsert\n        {\n            get { return OldLength == 0 && NewLength > 0; }\n        }\n\n        public bool IsDelete\n        {\n            get { return OldLength > 0 && NewLength == 0; }\n        }\n\n        public bool IsReplace\n        {\n            get { return OldLength > 0 && NewLength > 0; }\n        }\n\n        public override bool Equals(object obj)\n        {\n            if (!(obj is TextChange))\n            {\n                return false;\n            }\n            TextChange change = (TextChange)obj;\n            return (change.OldPosition == OldPosition) &&\n                   (change.NewPosition == NewPosition) &&\n                   (change.OldLength == OldLength) &&\n                   (change.NewLength == NewLength) &&\n                   OldBuffer.Equals(change.OldBuffer) &&\n                   NewBuffer.Equals(change.NewBuffer);\n        }\n\n        public string ApplyChange(string content, int changeOffset)\n        {\n            int changeRelativePosition = OldPosition - changeOffset;\n\n            Debug.Assert(changeRelativePosition >= 0);\n            return content.Remove(changeRelativePosition, OldLength)\n                .Insert(changeRelativePosition, NewText);\n        }\n\n        /// <summary>\n        /// Applies the text change to the content of the span and returns the new content.\n        /// This method doesn't update the span content.\n        /// </summary>\n        public string ApplyChange(Span span)\n        {\n            return ApplyChange(span.Content, span.Start.AbsoluteIndex);\n        }\n\n        public override int GetHashCode()\n        {\n            return OldPosition ^ NewPosition ^ OldLength ^ NewLength ^ NewBuffer.GetHashCode() ^ OldBuffer.GetHashCode();\n        }\n\n        public override string ToString()\n        {\n            return String.Format(CultureInfo.CurrentCulture, \"({0}:{1}) \\\"{3}\\\" -> ({0}:{2}) \\\"{4}\\\"\", OldPosition, OldLength, NewLength, OldText, NewText);\n        }\n\n        /// <summary>\n        /// Removes a common prefix from the edit to turn IntelliSense replacements into insertions where possible\n        /// </summary>\n        /// <returns>A normalized text change</returns>\n        public TextChange Normalize()\n        {\n            if (OldBuffer != null && IsReplace && NewLength > OldLength && NewText.StartsWith(OldText, StringComparison.Ordinal) && NewPosition == OldPosition)\n            {\n                // Normalize the change into an insertion of the uncommon suffix (i.e. strip out the common prefix)\n                return new TextChange(oldPosition: OldPosition + OldLength,\n                                      oldLength: 0,\n                                      oldBuffer: OldBuffer,\n                                      newPosition: OldPosition + OldLength,\n                                      newLength: NewLength - OldLength,\n                                      newBuffer: NewBuffer);\n            }\n            return this;\n        }\n\n        private static string GetText(ITextBuffer buffer, int position, int length)\n        {\n            // Optimization for the common case of one char inserts, in this case we don't even need to seek the buffer.\n            if (length == 0)\n            {\n                return String.Empty;\n            }\n\n            int oldPosition = buffer.Position;\n            try\n            {\n                buffer.Position = position;\n\n                // Optimization for the common case of one char inserts, in this case we seek the buffer.\n                if (length == 1)\n                {\n                    return ((char)buffer.Read()).ToString();\n                }\n                else\n                {\n                    var builder = new StringBuilder();\n                    for (int i = 0; i < length; i++)\n                    {\n                        char c = (char)buffer.Read();\n                        builder.Append(c);\n\n                        // This check is probably not necessary, will revisit when fixing https://aspnetwebstack.codeplex.com/workitem/1317\n                        if (Char.IsHighSurrogate(c))\n                        {\n                            builder.Append((char)buffer.Read());\n                        }\n                    }\n                    return builder.ToString();\n                }\n            }\n            finally\n            {\n                buffer.Position = oldPosition;\n            }\n        }\n\n        public static bool operator ==(TextChange left, TextChange right)\n        {\n            return left.Equals(right);\n        }\n\n        public static bool operator !=(TextChange left, TextChange right)\n        {\n            return !left.Equals(right);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Text/TextChangeType.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Razor.Text\n{\n    public enum TextChangeType\n    {\n        Insert,\n        Remove\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Text/TextDocumentReader.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\n\nnamespace System.Web.Razor.Text\n{\n    public class TextDocumentReader : TextReader, ITextDocument\n    {\n        public TextDocumentReader(ITextDocument source)\n        {\n            Document = source;\n        }\n\n        internal ITextDocument Document { get; private set; }\n\n        public SourceLocation Location\n        {\n            get { return Document.Location; }\n        }\n\n        public int Length\n        {\n            get { return Document.Length; }\n        }\n\n        public int Position\n        {\n            get { return Document.Position; }\n            set { Document.Position = value; }\n        }\n\n        public override int Read()\n        {\n            return Document.Read();\n        }\n\n        public override int Peek()\n        {\n            return Document.Peek();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Text/TextExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Text;\n\nnamespace System.Web.Razor.Text\n{\n    internal static class TextExtensions\n    {\n        public static void Seek(this ITextBuffer self, int characters)\n        {\n            self.Position += characters;\n        }\n\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"The consumer is expected to dispose this object\")]\n        public static ITextDocument ToDocument(this ITextBuffer self)\n        {\n            ITextDocument ret = self as ITextDocument;\n            if (ret == null)\n            {\n                ret = new SeekableTextReader(self);\n            }\n            return ret;\n        }\n\n        public static LookaheadToken BeginLookahead(this ITextBuffer self)\n        {\n            int start = self.Position;\n            return new LookaheadToken(() =>\n            {\n                self.Position = start;\n            });\n        }\n\n        public static string ReadToEnd(this ITextBuffer self)\n        {\n            StringBuilder builder = new StringBuilder();\n            int read;\n            while ((read = self.Read()) != -1)\n            {\n                builder.Append((char)read);\n            }\n            return builder.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Tokenizer/CSharpHelpers.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\n\nnamespace System.Web.Razor.Tokenizer\n{\n    public static class CSharpHelpers\n    {\n        // CSharp Spec §2.4.2\n        public static bool IsIdentifierStart(char character)\n        {\n            return Char.IsLetter(character) ||\n                   character == '_' ||\n                   Char.GetUnicodeCategory(character) == UnicodeCategory.LetterNumber; // Ln\n        }\n\n        public static bool IsIdentifierPart(char character)\n        {\n            return Char.IsDigit(character) ||\n                   IsIdentifierStart(character) ||\n                   IsIdentifierPartByUnicodeCategory(character);\n        }\n\n        public static bool IsRealLiteralSuffix(char character)\n        {\n            return character == 'F' ||\n                   character == 'f' ||\n                   character == 'D' ||\n                   character == 'd' ||\n                   character == 'M' ||\n                   character == 'm';\n        }\n\n        private static bool IsIdentifierPartByUnicodeCategory(char character)\n        {\n            UnicodeCategory category = Char.GetUnicodeCategory(character);\n            return category == UnicodeCategory.NonSpacingMark || // Mn\n                   category == UnicodeCategory.SpacingCombiningMark || // Mc\n                   category == UnicodeCategory.ConnectorPunctuation || // Pc\n                   category == UnicodeCategory.Format; // Cf\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Tokenizer/CSharpKeywordDetector.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Tokenizer\n{\n    internal static class CSharpKeywordDetector\n    {\n        private static readonly Dictionary<string, CSharpKeyword> _keywords = new Dictionary<string, CSharpKeyword>(StringComparer.Ordinal)\n        {\n            { \"abstract\", CSharpKeyword.Abstract },\n            { \"byte\", CSharpKeyword.Byte },\n            { \"class\", CSharpKeyword.Class },\n            { \"delegate\", CSharpKeyword.Delegate },\n            { \"event\", CSharpKeyword.Event },\n            { \"fixed\", CSharpKeyword.Fixed },\n            { \"if\", CSharpKeyword.If },\n            { \"internal\", CSharpKeyword.Internal },\n            { \"new\", CSharpKeyword.New },\n            { \"override\", CSharpKeyword.Override },\n            { \"readonly\", CSharpKeyword.Readonly },\n            { \"short\", CSharpKeyword.Short },\n            { \"struct\", CSharpKeyword.Struct },\n            { \"try\", CSharpKeyword.Try },\n            { \"unsafe\", CSharpKeyword.Unsafe },\n            { \"volatile\", CSharpKeyword.Volatile },\n            { \"as\", CSharpKeyword.As },\n            { \"do\", CSharpKeyword.Do },\n            { \"is\", CSharpKeyword.Is },\n            { \"params\", CSharpKeyword.Params },\n            { \"ref\", CSharpKeyword.Ref },\n            { \"switch\", CSharpKeyword.Switch },\n            { \"ushort\", CSharpKeyword.Ushort },\n            { \"while\", CSharpKeyword.While },\n            { \"case\", CSharpKeyword.Case },\n            { \"const\", CSharpKeyword.Const },\n            { \"explicit\", CSharpKeyword.Explicit },\n            { \"float\", CSharpKeyword.Float },\n            { \"null\", CSharpKeyword.Null },\n            { \"sizeof\", CSharpKeyword.Sizeof },\n            { \"typeof\", CSharpKeyword.Typeof },\n            { \"implicit\", CSharpKeyword.Implicit },\n            { \"private\", CSharpKeyword.Private },\n            { \"this\", CSharpKeyword.This },\n            { \"using\", CSharpKeyword.Using },\n            { \"extern\", CSharpKeyword.Extern },\n            { \"return\", CSharpKeyword.Return },\n            { \"stackalloc\", CSharpKeyword.Stackalloc },\n            { \"uint\", CSharpKeyword.Uint },\n            { \"base\", CSharpKeyword.Base },\n            { \"catch\", CSharpKeyword.Catch },\n            { \"continue\", CSharpKeyword.Continue },\n            { \"double\", CSharpKeyword.Double },\n            { \"for\", CSharpKeyword.For },\n            { \"in\", CSharpKeyword.In },\n            { \"lock\", CSharpKeyword.Lock },\n            { \"object\", CSharpKeyword.Object },\n            { \"protected\", CSharpKeyword.Protected },\n            { \"static\", CSharpKeyword.Static },\n            { \"false\", CSharpKeyword.False },\n            { \"public\", CSharpKeyword.Public },\n            { \"sbyte\", CSharpKeyword.Sbyte },\n            { \"throw\", CSharpKeyword.Throw },\n            { \"virtual\", CSharpKeyword.Virtual },\n            { \"decimal\", CSharpKeyword.Decimal },\n            { \"else\", CSharpKeyword.Else },\n            { \"operator\", CSharpKeyword.Operator },\n            { \"string\", CSharpKeyword.String },\n            { \"ulong\", CSharpKeyword.Ulong },\n            { \"bool\", CSharpKeyword.Bool },\n            { \"char\", CSharpKeyword.Char },\n            { \"default\", CSharpKeyword.Default },\n            { \"foreach\", CSharpKeyword.Foreach },\n            { \"long\", CSharpKeyword.Long },\n            { \"void\", CSharpKeyword.Void },\n            { \"enum\", CSharpKeyword.Enum },\n            { \"finally\", CSharpKeyword.Finally },\n            { \"int\", CSharpKeyword.Int },\n            { \"out\", CSharpKeyword.Out },\n            { \"sealed\", CSharpKeyword.Sealed },\n            { \"true\", CSharpKeyword.True },\n            { \"goto\", CSharpKeyword.Goto },\n            { \"unchecked\", CSharpKeyword.Unchecked },\n            { \"interface\", CSharpKeyword.Interface },\n            { \"break\", CSharpKeyword.Break },\n            { \"checked\", CSharpKeyword.Checked },\n            { \"namespace\", CSharpKeyword.Namespace }\n        };\n\n        public static CSharpKeyword? SymbolTypeForIdentifier(string id)\n        {\n            CSharpKeyword type;\n            if (!_keywords.TryGetValue(id, out type))\n            {\n                return null;\n            }\n            return type;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Tokenizer/CSharpTokenizer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Tokenizer\n{\n    public class CSharpTokenizer : Tokenizer<CSharpSymbol, CSharpSymbolType>\n    {\n        private Dictionary<char, Func<CSharpSymbolType>> _operatorHandlers;\n\n        public CSharpTokenizer(ITextDocument source)\n            : base(source)\n        {\n            CurrentState = Data;\n\n            _operatorHandlers = new Dictionary<char, Func<CSharpSymbolType>>()\n            {\n                { '-', MinusOperator },\n                { '<', LessThanOperator },\n                { '>', GreaterThanOperator },\n                { '&', CreateTwoCharOperatorHandler(CSharpSymbolType.And, '=', CSharpSymbolType.AndAssign, '&', CSharpSymbolType.DoubleAnd) },\n                { '|', CreateTwoCharOperatorHandler(CSharpSymbolType.Or, '=', CSharpSymbolType.OrAssign, '|', CSharpSymbolType.DoubleOr) },\n                { '+', CreateTwoCharOperatorHandler(CSharpSymbolType.Plus, '=', CSharpSymbolType.PlusAssign, '+', CSharpSymbolType.Increment) },\n                { '=', CreateTwoCharOperatorHandler(CSharpSymbolType.Assign, '=', CSharpSymbolType.Equals, '>', CSharpSymbolType.GreaterThanEqual) },\n                { '!', CreateTwoCharOperatorHandler(CSharpSymbolType.Not, '=', CSharpSymbolType.NotEqual) },\n                { '%', CreateTwoCharOperatorHandler(CSharpSymbolType.Modulo, '=', CSharpSymbolType.ModuloAssign) },\n                { '*', CreateTwoCharOperatorHandler(CSharpSymbolType.Star, '=', CSharpSymbolType.MultiplyAssign) },\n                { ':', CreateTwoCharOperatorHandler(CSharpSymbolType.Colon, ':', CSharpSymbolType.DoubleColon) },\n                { '?', CreateTwoCharOperatorHandler(CSharpSymbolType.QuestionMark, '?', CSharpSymbolType.NullCoalesce) },\n                { '^', CreateTwoCharOperatorHandler(CSharpSymbolType.Xor, '=', CSharpSymbolType.XorAssign) },\n                { '(', () => CSharpSymbolType.LeftParenthesis },\n                { ')', () => CSharpSymbolType.RightParenthesis },\n                { '{', () => CSharpSymbolType.LeftBrace },\n                { '}', () => CSharpSymbolType.RightBrace },\n                { '[', () => CSharpSymbolType.LeftBracket },\n                { ']', () => CSharpSymbolType.RightBracket },\n                { ',', () => CSharpSymbolType.Comma },\n                { ';', () => CSharpSymbolType.Semicolon },\n                { '~', () => CSharpSymbolType.Tilde },\n                { '#', () => CSharpSymbolType.Hash }\n            };\n        }\n\n        protected override State StartState\n        {\n            get { return Data; }\n        }\n\n        public override CSharpSymbolType RazorCommentType\n        {\n            get { return CSharpSymbolType.RazorComment; }\n        }\n\n        public override CSharpSymbolType RazorCommentTransitionType\n        {\n            get { return CSharpSymbolType.RazorCommentTransition; }\n        }\n\n        public override CSharpSymbolType RazorCommentStarType\n        {\n            get { return CSharpSymbolType.RazorCommentStar; }\n        }\n\n        protected override CSharpSymbol CreateSymbol(SourceLocation start, string content, CSharpSymbolType type, IEnumerable<RazorError> errors)\n        {\n            return new CSharpSymbol(start, content, type, errors);\n        }\n\n        private StateResult Data()\n        {\n            if (ParserHelpers.IsNewLine(CurrentCharacter))\n            {\n                // CSharp Spec §2.3.1\n                bool checkTwoCharNewline = CurrentCharacter == '\\r';\n                TakeCurrent();\n                if (checkTwoCharNewline && CurrentCharacter == '\\n')\n                {\n                    TakeCurrent();\n                }\n                return Stay(EndSymbol(CSharpSymbolType.NewLine));\n            }\n            else if (ParserHelpers.IsWhitespace(CurrentCharacter))\n            {\n                // CSharp Spec §2.3.3\n                TakeUntil(c => !ParserHelpers.IsWhitespace(c));\n                return Stay(EndSymbol(CSharpSymbolType.WhiteSpace));\n            }\n            else if (CSharpHelpers.IsIdentifierStart(CurrentCharacter))\n            {\n                return Identifier();\n            }\n            else if (Char.IsDigit(CurrentCharacter))\n            {\n                return NumericLiteral();\n            }\n            switch (CurrentCharacter)\n            {\n                case '@':\n                    return AtSymbol();\n                case '\\'':\n                    TakeCurrent();\n                    return Transition(() => QuotedLiteral('\\'', CSharpSymbolType.CharacterLiteral));\n                case '\"':\n                    TakeCurrent();\n                    return Transition(() => QuotedLiteral('\"', CSharpSymbolType.StringLiteral));\n                case '.':\n                    if (Char.IsDigit(Peek()))\n                    {\n                        return RealLiteral();\n                    }\n                    return Stay(Single(CSharpSymbolType.Dot));\n                case '/':\n                    TakeCurrent();\n                    if (CurrentCharacter == '/')\n                    {\n                        TakeCurrent();\n                        return SingleLineComment();\n                    }\n                    else if (CurrentCharacter == '*')\n                    {\n                        TakeCurrent();\n                        return Transition(BlockComment);\n                    }\n                    else if (CurrentCharacter == '=')\n                    {\n                        TakeCurrent();\n                        return Stay(EndSymbol(CSharpSymbolType.DivideAssign));\n                    }\n                    else\n                    {\n                        return Stay(EndSymbol(CSharpSymbolType.Slash));\n                    }\n                default:\n                    return Stay(EndSymbol(Operator()));\n            }\n        }\n\n        private StateResult AtSymbol()\n        {\n            TakeCurrent();\n            if (CurrentCharacter == '\"')\n            {\n                TakeCurrent();\n                return Transition(VerbatimStringLiteral);\n            }\n            else if (CurrentCharacter == '*')\n            {\n                return Transition(EndSymbol(CSharpSymbolType.RazorCommentTransition), AfterRazorCommentTransition);\n            }\n            else if (CurrentCharacter == '@')\n            {\n                // Could be escaped comment transition\n                return Transition(EndSymbol(CSharpSymbolType.Transition), () =>\n                {\n                    TakeCurrent();\n                    return Transition(EndSymbol(CSharpSymbolType.Transition), Data);\n                });\n            }\n            return Stay(EndSymbol(CSharpSymbolType.Transition));\n        }\n\n        private CSharpSymbolType Operator()\n        {\n            char first = CurrentCharacter;\n            TakeCurrent();\n            Func<CSharpSymbolType> handler;\n            if (_operatorHandlers.TryGetValue(first, out handler))\n            {\n                return handler();\n            }\n            return CSharpSymbolType.Unknown;\n        }\n\n        private CSharpSymbolType LessThanOperator()\n        {\n            if (CurrentCharacter == '=')\n            {\n                TakeCurrent();\n                return CSharpSymbolType.LessThanEqual;\n            }\n            return CSharpSymbolType.LessThan;\n        }\n\n        private CSharpSymbolType GreaterThanOperator()\n        {\n            if (CurrentCharacter == '=')\n            {\n                TakeCurrent();\n                return CSharpSymbolType.GreaterThanEqual;\n            }\n            return CSharpSymbolType.GreaterThan;\n        }\n\n        private CSharpSymbolType MinusOperator()\n        {\n            if (CurrentCharacter == '>')\n            {\n                TakeCurrent();\n                return CSharpSymbolType.Arrow;\n            }\n            else if (CurrentCharacter == '-')\n            {\n                TakeCurrent();\n                return CSharpSymbolType.Decrement;\n            }\n            else if (CurrentCharacter == '=')\n            {\n                TakeCurrent();\n                return CSharpSymbolType.MinusAssign;\n            }\n            return CSharpSymbolType.Minus;\n        }\n\n        private Func<CSharpSymbolType> CreateTwoCharOperatorHandler(CSharpSymbolType typeIfOnlyFirst, char second, CSharpSymbolType typeIfBoth)\n        {\n            return () =>\n            {\n                if (CurrentCharacter == second)\n                {\n                    TakeCurrent();\n                    return typeIfBoth;\n                }\n                return typeIfOnlyFirst;\n            };\n        }\n\n        private Func<CSharpSymbolType> CreateTwoCharOperatorHandler(CSharpSymbolType typeIfOnlyFirst, char option1, CSharpSymbolType typeIfOption1, char option2, CSharpSymbolType typeIfOption2)\n        {\n            return () =>\n            {\n                if (CurrentCharacter == option1)\n                {\n                    TakeCurrent();\n                    return typeIfOption1;\n                }\n                else if (CurrentCharacter == option2)\n                {\n                    TakeCurrent();\n                    return typeIfOption2;\n                }\n                return typeIfOnlyFirst;\n            };\n        }\n\n        private StateResult VerbatimStringLiteral()\n        {\n            TakeUntil(c => c == '\"');\n            if (CurrentCharacter == '\"')\n            {\n                TakeCurrent();\n                if (CurrentCharacter == '\"')\n                {\n                    TakeCurrent();\n                    // Stay in the literal, this is an escaped \"\n                    return Stay();\n                }\n            }\n            else if (EndOfFile)\n            {\n                CurrentErrors.Add(new RazorError(RazorResources.ParseError_Unterminated_String_Literal, CurrentStart));\n            }\n            return Transition(EndSymbol(CSharpSymbolType.StringLiteral), Data);\n        }\n\n        private StateResult QuotedLiteral(char quote, CSharpSymbolType literalType)\n        {\n            TakeUntil(c => c == '\\\\' || c == quote || ParserHelpers.IsNewLine(c));\n            if (CurrentCharacter == '\\\\')\n            {\n                TakeCurrent(); // Take the '\\'\n                \n                // If the next char is the same quote that started this\n                if (CurrentCharacter == quote || CurrentCharacter == '\\\\')\n                {\n                    TakeCurrent(); // Take it so that we don't prematurely end the literal.\n                }\n                return Stay();\n            }\n            else if (EndOfFile || ParserHelpers.IsNewLine(CurrentCharacter))\n            {\n                CurrentErrors.Add(new RazorError(RazorResources.ParseError_Unterminated_String_Literal, CurrentStart));\n            }\n            else\n            {\n                TakeCurrent(); // No-op if at EOF\n            }\n            return Transition(EndSymbol(literalType), Data);\n        }\n\n        // CSharp Spec §2.3.2\n        private StateResult BlockComment()\n        {\n            TakeUntil(c => c == '*');\n            if (EndOfFile)\n            {\n                CurrentErrors.Add(new RazorError(RazorResources.ParseError_BlockComment_Not_Terminated, CurrentStart));\n                return Transition(EndSymbol(CSharpSymbolType.Comment), Data);\n            }\n            if (CurrentCharacter == '*')\n            {\n                TakeCurrent();\n                if (CurrentCharacter == '/')\n                {\n                    TakeCurrent();\n                    return Transition(EndSymbol(CSharpSymbolType.Comment), Data);\n                }\n            }\n            return Stay();\n        }\n\n        // CSharp Spec §2.3.2\n        private StateResult SingleLineComment()\n        {\n            TakeUntil(c => ParserHelpers.IsNewLine(c));\n            return Stay(EndSymbol(CSharpSymbolType.Comment));\n        }\n\n        // CSharp Spec §2.4.4\n        private StateResult NumericLiteral()\n        {\n            if (TakeAll(\"0x\", caseSensitive: true))\n            {\n                return HexLiteral();\n            }\n            else\n            {\n                return DecimalLiteral();\n            }\n        }\n\n        private StateResult HexLiteral()\n        {\n            TakeUntil(c => !ParserHelpers.IsHexDigit(c));\n            TakeIntegerSuffix();\n            return Stay(EndSymbol(CSharpSymbolType.IntegerLiteral));\n        }\n\n        private StateResult DecimalLiteral()\n        {\n            TakeUntil(c => !Char.IsDigit(c));\n            if (CurrentCharacter == '.' && Char.IsDigit(Peek()))\n            {\n                return RealLiteral();\n            }\n            else if (CSharpHelpers.IsRealLiteralSuffix(CurrentCharacter) ||\n                     CurrentCharacter == 'E' || CurrentCharacter == 'e')\n            {\n                return RealLiteralExponentPart();\n            }\n            else\n            {\n                TakeIntegerSuffix();\n                return Stay(EndSymbol(CSharpSymbolType.IntegerLiteral));\n            }\n        }\n\n        private StateResult RealLiteralExponentPart()\n        {\n            if (CurrentCharacter == 'E' || CurrentCharacter == 'e')\n            {\n                TakeCurrent();\n                if (CurrentCharacter == '+' || CurrentCharacter == '-')\n                {\n                    TakeCurrent();\n                }\n                TakeUntil(c => !Char.IsDigit(c));\n            }\n            if (CSharpHelpers.IsRealLiteralSuffix(CurrentCharacter))\n            {\n                TakeCurrent();\n            }\n            return Stay(EndSymbol(CSharpSymbolType.RealLiteral));\n        }\n\n        // CSharp Spec §2.4.4.3\n        private StateResult RealLiteral()\n        {\n            AssertCurrent('.');\n            TakeCurrent();\n            Debug.Assert(Char.IsDigit(CurrentCharacter));\n            TakeUntil(c => !Char.IsDigit(c));\n            return RealLiteralExponentPart();\n        }\n\n        private void TakeIntegerSuffix()\n        {\n            if (Char.ToLowerInvariant(CurrentCharacter) == 'u')\n            {\n                TakeCurrent();\n                if (Char.ToLowerInvariant(CurrentCharacter) == 'l')\n                {\n                    TakeCurrent();\n                }\n            }\n            else if (Char.ToLowerInvariant(CurrentCharacter) == 'l')\n            {\n                TakeCurrent();\n                if (Char.ToLowerInvariant(CurrentCharacter) == 'u')\n                {\n                    TakeCurrent();\n                }\n            }\n        }\n\n        // CSharp Spec §2.4.2\n        private StateResult Identifier()\n        {\n            Debug.Assert(CSharpHelpers.IsIdentifierStart(CurrentCharacter));\n            TakeCurrent();\n            TakeUntil(c => !CSharpHelpers.IsIdentifierPart(c));\n            CSharpSymbol sym = null;\n            if (HaveContent)\n            {\n                CSharpKeyword? kwd = CSharpKeywordDetector.SymbolTypeForIdentifier(Buffer.ToString());\n                CSharpSymbolType type = CSharpSymbolType.Identifier;\n                if (kwd != null)\n                {\n                    type = CSharpSymbolType.Keyword;\n                }\n                sym = new CSharpSymbol(CurrentStart, Buffer.ToString(), type) { Keyword = kwd };\n            }\n            StartSymbol();\n            return Stay(sym);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Tokenizer/HtmlTokenizer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Tokenizer\n{\n    // Tokenizer _loosely_ based on http://dev.w3.org/html5/spec/Overview.html#tokenization\n    public class HtmlTokenizer : Tokenizer<HtmlSymbol, HtmlSymbolType>\n    {\n        private const char TransitionChar = '@';\n\n        public HtmlTokenizer(ITextDocument source)\n            : base(source)\n        {\n            CurrentState = Data;\n        }\n\n        protected override State StartState\n        {\n            get { return Data; }\n        }\n\n        public override HtmlSymbolType RazorCommentType\n        {\n            get { return HtmlSymbolType.RazorComment; }\n        }\n\n        public override HtmlSymbolType RazorCommentTransitionType\n        {\n            get { return HtmlSymbolType.RazorCommentTransition; }\n        }\n\n        public override HtmlSymbolType RazorCommentStarType\n        {\n            get { return HtmlSymbolType.RazorCommentStar; }\n        }\n\n        internal static IEnumerable<HtmlSymbol> Tokenize(string content)\n        {\n            using (SeekableTextReader reader = new SeekableTextReader(content))\n            {\n                HtmlTokenizer tok = new HtmlTokenizer(reader);\n                HtmlSymbol sym;\n                while ((sym = tok.NextSymbol()) != null)\n                {\n                    yield return sym;\n                }\n            }\n        }\n\n        protected override HtmlSymbol CreateSymbol(SourceLocation start, string content, HtmlSymbolType type, IEnumerable<RazorError> errors)\n        {\n            return new HtmlSymbol(start, content, type, errors);\n        }\n\n        // http://dev.w3.org/html5/spec/Overview.html#data-state\n        private StateResult Data()\n        {\n            if (ParserHelpers.IsWhitespace(CurrentCharacter))\n            {\n                return Stay(Whitespace());\n            }\n            else if (ParserHelpers.IsNewLine(CurrentCharacter))\n            {\n                return Stay(Newline());\n            }\n            else if (CurrentCharacter == '@')\n            {\n                TakeCurrent();\n                if (CurrentCharacter == '*')\n                {\n                    return Transition(EndSymbol(HtmlSymbolType.RazorCommentTransition), AfterRazorCommentTransition);\n                }\n                else if (CurrentCharacter == '@')\n                {\n                    // Could be escaped comment transition\n                    return Transition(EndSymbol(HtmlSymbolType.Transition), () =>\n                    {\n                        TakeCurrent();\n                        return Transition(EndSymbol(HtmlSymbolType.Transition), Data);\n                    });\n                }\n                return Stay(EndSymbol(HtmlSymbolType.Transition));\n            }\n            else if (AtSymbol())\n            {\n                return Stay(Symbol());\n            }\n            else\n            {\n                return Transition(Text);\n            }\n        }\n\n        private StateResult Text()\n        {\n            char prev = '\\0';\n            while (!EndOfFile && !ParserHelpers.IsWhitespaceOrNewLine(CurrentCharacter) && !AtSymbol())\n            {\n                prev = CurrentCharacter;\n                TakeCurrent();\n            }\n\n            if (CurrentCharacter == '@')\n            {\n                char next = Peek();\n                if (ParserHelpers.IsLetterOrDecimalDigit(prev) && ParserHelpers.IsLetterOrDecimalDigit(next))\n                {\n                    TakeCurrent(); // Take the \"@\"\n                    return Stay(); // Stay in the Text state\n                }\n            }\n\n            // Output the Text token and return to the Data state to tokenize the next character (if there is one)\n            return Transition(EndSymbol(HtmlSymbolType.Text), Data);\n        }\n\n        private HtmlSymbol Symbol()\n        {\n            Debug.Assert(AtSymbol());\n            char sym = CurrentCharacter;\n            TakeCurrent();\n            switch (sym)\n            {\n                case '<':\n                    return EndSymbol(HtmlSymbolType.OpenAngle);\n                case '!':\n                    return EndSymbol(HtmlSymbolType.Bang);\n                case '/':\n                    return EndSymbol(HtmlSymbolType.Solidus);\n                case '?':\n                    return EndSymbol(HtmlSymbolType.QuestionMark);\n                case '[':\n                    return EndSymbol(HtmlSymbolType.LeftBracket);\n                case '>':\n                    return EndSymbol(HtmlSymbolType.CloseAngle);\n                case ']':\n                    return EndSymbol(HtmlSymbolType.RightBracket);\n                case '=':\n                    return EndSymbol(HtmlSymbolType.Equals);\n                case '\"':\n                    return EndSymbol(HtmlSymbolType.DoubleQuote);\n                case '\\'':\n                    return EndSymbol(HtmlSymbolType.SingleQuote);\n                case '-':\n                    Debug.Assert(CurrentCharacter == '-');\n                    TakeCurrent();\n                    return EndSymbol(HtmlSymbolType.DoubleHyphen);\n                default:\n                    Debug.Fail(\"Unexpected symbol!\");\n                    return EndSymbol(HtmlSymbolType.Unknown);\n            }\n        }\n\n        private HtmlSymbol Whitespace()\n        {\n            while (ParserHelpers.IsWhitespace(CurrentCharacter))\n            {\n                TakeCurrent();\n            }\n            return EndSymbol(HtmlSymbolType.WhiteSpace);\n        }\n\n        private HtmlSymbol Newline()\n        {\n            Debug.Assert(ParserHelpers.IsNewLine(CurrentCharacter));\n            // CSharp Spec §2.3.1\n            bool checkTwoCharNewline = CurrentCharacter == '\\r';\n            TakeCurrent();\n            if (checkTwoCharNewline && CurrentCharacter == '\\n')\n            {\n                TakeCurrent();\n            }\n            return EndSymbol(HtmlSymbolType.NewLine);\n        }\n\n        private bool AtSymbol()\n        {\n            return CurrentCharacter == '<' ||\n                   CurrentCharacter == '<' ||\n                   CurrentCharacter == '!' ||\n                   CurrentCharacter == '/' ||\n                   CurrentCharacter == '?' ||\n                   CurrentCharacter == '[' ||\n                   CurrentCharacter == '>' ||\n                   CurrentCharacter == ']' ||\n                   CurrentCharacter == '=' ||\n                   CurrentCharacter == '\"' ||\n                   CurrentCharacter == '\\'' ||\n                   CurrentCharacter == '@' ||\n                   (CurrentCharacter == '-' && Peek() == '-');\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Tokenizer/ITokenizer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Tokenizer\n{\n    public interface ITokenizer\n    {\n        ISymbol NextSymbol();\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Tokenizer/Symbols/CSharpKeyword.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Razor.Tokenizer.Symbols\n{\n    public enum CSharpKeyword\n    {\n        Abstract,\n        Byte,\n        Class,\n        Delegate,\n        Event,\n        Fixed,\n        If,\n        Internal,\n        New,\n        Override,\n        Readonly,\n        Short,\n        Struct,\n        Try,\n        Unsafe,\n        Volatile,\n        As,\n        Do,\n        Is,\n        Params,\n        Ref,\n        Switch,\n        Ushort,\n        While,\n        Case,\n        Const,\n        Explicit,\n        Float,\n        Null,\n        Sizeof,\n        Typeof,\n        Implicit,\n        Private,\n        This,\n        Using,\n        Extern,\n        Return,\n        Stackalloc,\n        Uint,\n        Base,\n        Catch,\n        Continue,\n        Double,\n        For,\n        In,\n        Lock,\n        Object,\n        Protected,\n        Static,\n        False,\n        Public,\n        Sbyte,\n        Throw,\n        Virtual,\n        Decimal,\n        Else,\n        Operator,\n        String,\n        Ulong,\n        Bool,\n        Char,\n        Default,\n        Foreach,\n        Long,\n        Void,\n        Enum,\n        Finally,\n        Int,\n        Out,\n        Sealed,\n        True,\n        Goto,\n        Unchecked,\n        Interface,\n        Break,\n        Checked,\n        Namespace\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Tokenizer/Symbols/CSharpSymbol.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Text;\n\nnamespace System.Web.Razor.Tokenizer.Symbols\n{\n    public class CSharpSymbol : SymbolBase<CSharpSymbolType>\n    {\n        // Helper constructor\n        public CSharpSymbol(int offset, int line, int column, string content, CSharpSymbolType type)\n            : this(new SourceLocation(offset, line, column), content, type, Enumerable.Empty<RazorError>())\n        {\n        }\n\n        public CSharpSymbol(SourceLocation start, string content, CSharpSymbolType type)\n            : this(start, content, type, Enumerable.Empty<RazorError>())\n        {\n        }\n\n        public CSharpSymbol(int offset, int line, int column, string content, CSharpSymbolType type, IEnumerable<RazorError> errors)\n            : base(new SourceLocation(offset, line, column), content, type, errors)\n        {\n        }\n\n        public CSharpSymbol(SourceLocation start, string content, CSharpSymbolType type, IEnumerable<RazorError> errors)\n            : base(start, content, type, errors)\n        {\n        }\n\n        public bool? EscapedIdentifier { get; set; }\n        public CSharpKeyword? Keyword { get; set; }\n\n        public override bool Equals(object obj)\n        {\n            CSharpSymbol other = obj as CSharpSymbol;\n            return base.Equals(obj) && other.Keyword == Keyword;\n        }\n\n        public override int GetHashCode()\n        {\n            return base.GetHashCode() ^ Keyword.GetHashCode();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Tokenizer/Symbols/CSharpSymbolType.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Razor.Tokenizer.Symbols\n{\n    public enum CSharpSymbolType\n    {\n        Unknown,\n        Identifier,\n        Keyword,\n        IntegerLiteral,\n        NewLine,\n        WhiteSpace,\n        Comment,\n        RealLiteral,\n        CharacterLiteral,\n        StringLiteral,\n\n        // Operators\n        Arrow,\n        Minus,\n        Decrement,\n        MinusAssign,\n        NotEqual,\n        Not,\n        Modulo,\n        ModuloAssign,\n        AndAssign,\n        And,\n        DoubleAnd,\n        LeftParenthesis,\n        RightParenthesis,\n        Star,\n        MultiplyAssign,\n        Comma,\n        Dot,\n        Slash,\n        DivideAssign,\n        DoubleColon,\n        Colon,\n        Semicolon,\n        QuestionMark,\n        NullCoalesce,\n        RightBracket,\n        LeftBracket,\n        XorAssign,\n        Xor,\n        LeftBrace,\n        OrAssign,\n        DoubleOr,\n        Or,\n        RightBrace,\n        Tilde,\n        Plus,\n        PlusAssign,\n        Increment,\n        LessThan,\n        LessThanEqual,\n        LeftShift,\n        LeftShiftAssign,\n        Assign,\n        Equals,\n        GreaterThan,\n        GreaterThanEqual,\n        RightShift,\n        RightShiftAssign,\n        Hash,\n        Transition,\n\n        // Razor specific\n        RazorCommentTransition,\n        RazorCommentStar,\n        RazorComment\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Tokenizer/Symbols/HtmlSymbol.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Text;\n\nnamespace System.Web.Razor.Tokenizer.Symbols\n{\n    public class HtmlSymbol : SymbolBase<HtmlSymbolType>\n    {\n        // Helper constructor\n        public HtmlSymbol(int offset, int line, int column, string content, HtmlSymbolType type)\n            : this(new SourceLocation(offset, line, column), content, type, Enumerable.Empty<RazorError>())\n        {\n        }\n\n        public HtmlSymbol(SourceLocation start, string content, HtmlSymbolType type)\n            : base(start, content, type, Enumerable.Empty<RazorError>())\n        {\n        }\n\n        public HtmlSymbol(int offset, int line, int column, string content, HtmlSymbolType type, IEnumerable<RazorError> errors)\n            : base(new SourceLocation(offset, line, column), content, type, errors)\n        {\n        }\n\n        public HtmlSymbol(SourceLocation start, string content, HtmlSymbolType type, IEnumerable<RazorError> errors)\n            : base(start, content, type, errors)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Tokenizer/Symbols/HtmlSymbolType.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Razor.Tokenizer.Symbols\n{\n    public enum HtmlSymbolType\n    {\n        Unknown,\n        Text, // Text which isn't one of the below\n        WhiteSpace, // Non-newline Whitespace\n        NewLine, // Newline\n        OpenAngle, // <\n        Bang, // !\n        Solidus, // /\n        QuestionMark, // ?\n        DoubleHyphen, // --\n        LeftBracket, // [\n        CloseAngle, // >\n        RightBracket, // ]\n        Equals, // =\n        DoubleQuote, // \"\n        SingleQuote, // '\n        Transition, // @\n        Colon,\n        RazorComment,\n        RazorCommentStar,\n        RazorCommentTransition\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Tokenizer/Symbols/ISymbol.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Text;\n\nnamespace System.Web.Razor.Tokenizer.Symbols\n{\n    public interface ISymbol\n    {\n        SourceLocation Start { get; }\n        string Content { get; }\n\n        void OffsetStart(SourceLocation documentStart);\n        void ChangeStart(SourceLocation newStart);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Tokenizer/Symbols/KnownSymbolType.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Razor.Tokenizer.Symbols\n{\n    public enum KnownSymbolType\n    {\n        WhiteSpace,\n        NewLine,\n        Identifier,\n        Keyword,\n        Transition,\n        Unknown,\n        CommentStart,\n        CommentStar,\n        CommentBody\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Tokenizer/Symbols/SymbolBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Text;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Razor.Tokenizer.Symbols\n{\n    public abstract class SymbolBase<TType> : ISymbol\n    {\n        protected SymbolBase(SourceLocation start, string content, TType type, IEnumerable<RazorError> errors)\n        {\n            if (content == null)\n            {\n                throw new ArgumentNullException(\"content\");\n            }\n            if (type == null)\n            {\n                throw new ArgumentNullException(\"type\");\n            }\n\n            Start = start;\n            Content = content;\n            Type = type;\n            Errors = errors;\n        }\n\n        public SourceLocation Start { get; private set; }\n        public string Content { get; private set; }\n        public IEnumerable<RazorError> Errors { get; private set; }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1721:PropertyNamesShouldNotMatchGetMethods\", Justification = \"This is the most appropriate name for this property and conflicts are unlikely\")]\n        public TType Type { get; private set; }\n\n        public override bool Equals(object obj)\n        {\n            SymbolBase<TType> other = obj as SymbolBase<TType>;\n            return other != null &&\n                   Start.Equals(other.Start) &&\n                   String.Equals(Content, other.Content, StringComparison.Ordinal) &&\n                   Type.Equals(other.Type);\n        }\n\n        public override int GetHashCode()\n        {\n            return HashCodeCombiner.Start()\n                .Add(Start)\n                .Add(Content)\n                .Add(Type)\n                .CombinedHash;\n        }\n\n        public override string ToString()\n        {\n            return String.Format(CultureInfo.InvariantCulture, \"{0} {1} - [{2}]\", Start, Type, Content);\n        }\n\n        public void OffsetStart(SourceLocation documentStart)\n        {\n            Start = documentStart + Start;\n        }\n\n        public void ChangeStart(SourceLocation newStart)\n        {\n            Start = newStart;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Tokenizer/Symbols/SymbolExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Text;\n\nnamespace System.Web.Razor.Tokenizer.Symbols\n{\n    public static class SymbolExtensions\n    {\n        public static LocationTagged<string> GetContent(this SpanBuilder span)\n        {\n            return GetContent(span, e => e);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"Func<T> is the recommended type for generic delegates and requires this level of nesting\")]\n        public static LocationTagged<string> GetContent(this SpanBuilder span, Func<IEnumerable<ISymbol>, IEnumerable<ISymbol>> filter)\n        {\n            return GetContent(filter(span.Symbols), span.Start);\n        }\n\n        public static LocationTagged<string> GetContent(this IEnumerable<ISymbol> symbols, SourceLocation spanStart)\n        {\n            if (symbols.Any())\n            {\n                return new LocationTagged<string>(String.Concat(symbols.Select(s => s.Content)), spanStart + symbols.First().Start);\n            }\n            else\n            {\n                return new LocationTagged<string>(String.Empty, spanStart);\n            }\n        }\n\n        public static LocationTagged<string> GetContent(this ISymbol symbol)\n        {\n            return new LocationTagged<string>(symbol.Content, symbol.Start);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Tokenizer/Symbols/SymbolTypeSuppressions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n// Centralized all the supressions for the CSharpSymbolType and VBSymbolType enum members here for clarity. They are\n// not in the CodeAnalysisDictionary because they are special case exclusions\n\nusing System.Diagnostics.CodeAnalysis;\n\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"Foreach\", Scope = \"member\", Target = \"System.Web.Razor.Tokenizer.Symbols.CSharpKeyword.#Foreach\", Justification = Justifications.SymbolTypeNames)]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1702:CompoundWordsShouldBeCasedCorrectly\", MessageId = \"Readonly\", Scope = \"member\", Target = \"System.Web.Razor.Tokenizer.Symbols.CSharpKeyword.#Readonly\", Justification = Justifications.SymbolTypeNames)]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"Sbyte\", Scope = \"member\", Target = \"System.Web.Razor.Tokenizer.Symbols.CSharpKeyword.#Sbyte\", Justification = Justifications.SymbolTypeNames)]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"Sizeof\", Scope = \"member\", Target = \"System.Web.Razor.Tokenizer.Symbols.CSharpKeyword.#Sizeof\", Justification = Justifications.SymbolTypeNames)]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"Stackalloc\", Scope = \"member\", Target = \"System.Web.Razor.Tokenizer.Symbols.CSharpKeyword.#Stackalloc\", Justification = Justifications.SymbolTypeNames)]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"Typeof\", Scope = \"member\", Target = \"System.Web.Razor.Tokenizer.Symbols.CSharpKeyword.#Typeof\", Justification = Justifications.SymbolTypeNames)]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"Uint\", Scope = \"member\", Target = \"System.Web.Razor.Tokenizer.Symbols.CSharpKeyword.#Uint\", Justification = Justifications.SymbolTypeNames)]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"Ulong\", Scope = \"member\", Target = \"System.Web.Razor.Tokenizer.Symbols.CSharpKeyword.#Ulong\", Justification = Justifications.SymbolTypeNames)]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"Ushort\", Scope = \"member\", Target = \"System.Web.Razor.Tokenizer.Symbols.CSharpKeyword.#Ushort\", Justification = Justifications.SymbolTypeNames)]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"Val\", Scope = \"member\", Target = \"System.Web.Razor.Tokenizer.Symbols.VBKeyword.#ByVal\", Justification = Justifications.SymbolTypeNames)]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"Sng\", Scope = \"member\", Target = \"System.Web.Razor.Tokenizer.Symbols.VBKeyword.#CSng\", Justification = Justifications.SymbolTypeNames)]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1702:CompoundWordsShouldBeCasedCorrectly\", MessageId = \"ReDim\", Scope = \"member\", Target = \"System.Web.Razor.Tokenizer.Symbols.VBKeyword.#ReDim\", Justification = Justifications.SymbolTypeNames)]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1709:IdentifiersShouldBeCasedCorrectly\", MessageId = \"Re\", Scope = \"member\", Target = \"System.Web.Razor.Tokenizer.Symbols.VBKeyword.#ReDim\", Justification = Justifications.SymbolTypeNames)]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"Str\", Scope = \"member\", Target = \"System.Web.Razor.Tokenizer.Symbols.VBKeyword.#CStr\", Justification = Justifications.SymbolTypeNames)]\n\ninternal static partial class Justifications\n{\n    internal const string SymbolTypeNames = \"Symbol Type Names are spelled according to the language keyword or token they represent\";\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Tokenizer/Symbols/VBKeyword.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.Razor.Tokenizer.Symbols\n{\n    public enum VBKeyword\n    {\n        AddHandler,\n        AndAlso,\n        Byte,\n        Catch,\n        CDate,\n        CInt,\n        Const,\n        CSng,\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"Lng\", Justification = \"This is a VB Keyword. Note: Excluded here because it is a specific case\")]\n        CULng,\n        Declare,\n        DirectCast,\n        Else,\n        Enum,\n        Exit,\n        Friend,\n        GetXmlNamespace,\n        Handles,\n        In,\n        Is,\n        Like,\n        Mod,\n        MyBase,\n        New,\n        AddressOf,\n        As,\n        ByVal,\n        CBool,\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"Dbl\", Justification = \"This is a VB Keyword. Note: Excluded here because it is a specific case\")]\n        CDbl,\n        Class,\n        Continue,\n        CStr,\n        CUShort,\n        Default,\n        Do,\n        ElseIf,\n        Erase,\n        False,\n        Function,\n        Global,\n        If,\n        Inherits,\n        IsNot,\n        Long,\n        Module,\n        MyClass,\n        Next,\n        Alias,\n        Boolean,\n        Call,\n        CByte,\n        CDec,\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1704:IdentifiersShouldBeSpelledCorrectly\", MessageId = \"Lng\", Justification = \"This is a VB Keyword. Note: Excluded here because it is a specific case\")]\n        CLng,\n        CSByte,\n        CType,\n        Date,\n        Delegate,\n        Double,\n        End,\n        Error,\n        Finally,\n        Get,\n        GoSub,\n        Implements,\n        Integer,\n        Let,\n        Loop,\n        MustInherit,\n        Namespace,\n        Not,\n        And,\n        ByRef,\n        Case,\n        CChar,\n        Char,\n        CObj,\n        CShort,\n        CUInt,\n        Decimal,\n        Dim,\n        Each,\n        EndIf,\n        Event,\n        For,\n        GetType,\n        GoTo,\n        Imports,\n        Interface,\n        Lib,\n        Me,\n        MustOverride,\n        Narrowing,\n        Nothing,\n        NotInheritable,\n        On,\n        Or,\n        Overrides,\n        Property,\n        ReadOnly,\n        Resume,\n        Set,\n        Single,\n        String,\n        Then,\n        Try,\n        ULong,\n        Wend,\n        With,\n        NotOverridable,\n        Operator,\n        OrElse,\n        ParamArray,\n        Protected,\n        ReDim,\n        Return,\n        Shadows,\n        Static,\n        Structure,\n        Throw,\n        TryCast,\n        UShort,\n        When,\n        WithEvents,\n        Object,\n        Option,\n        Overloads,\n        Partial,\n        Public,\n        Rem,\n        SByte,\n        Shared,\n        Step,\n        Sub,\n        To,\n        TypeOf,\n        Using,\n        While,\n        WriteOnly,\n        Of,\n        Optional,\n        Overridable,\n        Private,\n        RaiseEvent,\n        RemoveHandler,\n        Select,\n        Short,\n        Stop,\n        SyncLock,\n        True,\n        UInteger,\n        Variant,\n        Widening,\n        Xor\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Tokenizer/Symbols/VBSymbol.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Text;\n\nnamespace System.Web.Razor.Tokenizer.Symbols\n{\n    public class VBSymbol : SymbolBase<VBSymbolType>\n    {\n        // Helper constructor\n        private static Dictionary<VBSymbolType, string> _symbolSamples = new Dictionary<VBSymbolType, string>()\n        {\n            { VBSymbolType.LineContinuation, \"_\" },\n            { VBSymbolType.LeftParenthesis, \"(\" },\n            { VBSymbolType.RightParenthesis, \")\" },\n            { VBSymbolType.LeftBracket, \"[\" },\n            { VBSymbolType.RightBracket, \"]\" },\n            { VBSymbolType.LeftBrace, \"{\" },\n            { VBSymbolType.RightBrace, \"}\" },\n            { VBSymbolType.Bang, \"!\" },\n            { VBSymbolType.Hash, \"#\" },\n            { VBSymbolType.Comma, \",\" },\n            { VBSymbolType.Dot, \".\" },\n            { VBSymbolType.Colon, \":\" },\n            { VBSymbolType.QuestionMark, \"?\" },\n            { VBSymbolType.Concatenation, \"&\" },\n            { VBSymbolType.Multiply, \"*\" },\n            { VBSymbolType.Add, \"+\" },\n            { VBSymbolType.Subtract, \"-\" },\n            { VBSymbolType.Divide, \"/\" },\n            { VBSymbolType.IntegerDivide, \"\\\\\" },\n            { VBSymbolType.Exponentiation, \"^\" },\n            { VBSymbolType.Equal, \"=\" },\n            { VBSymbolType.LessThan, \"<\" },\n            { VBSymbolType.GreaterThan, \">\" },\n            { VBSymbolType.Dollar, \"$\" },\n            { VBSymbolType.Transition, \"@\" },\n            { VBSymbolType.RazorCommentTransition, \"@\" },\n            { VBSymbolType.RazorCommentStar, \"*\" }\n        };\n\n        public VBSymbol(int offset, int line, int column, string content, VBSymbolType type)\n            : this(new SourceLocation(offset, line, column), content, type, Enumerable.Empty<RazorError>())\n        {\n        }\n\n        public VBSymbol(SourceLocation start, string content, VBSymbolType type)\n            : this(start, content, type, Enumerable.Empty<RazorError>())\n        {\n        }\n\n        public VBSymbol(int offset, int line, int column, string content, VBSymbolType type, IEnumerable<RazorError> errors)\n            : base(new SourceLocation(offset, line, column), content, type, errors)\n        {\n        }\n\n        public VBSymbol(SourceLocation start, string content, VBSymbolType type, IEnumerable<RazorError> errors)\n            : base(start, content, type, errors)\n        {\n        }\n\n        public VBKeyword? Keyword { get; set; }\n\n        public override bool Equals(object obj)\n        {\n            VBSymbol other = obj as VBSymbol;\n            return base.Equals(obj) && other.Keyword == Keyword;\n        }\n\n        public override int GetHashCode()\n        {\n            return base.GetHashCode() ^ Keyword.GetHashCode();\n        }\n\n        public static string GetSample(VBSymbolType type)\n        {\n            string sample;\n            if (!_symbolSamples.TryGetValue(type, out sample))\n            {\n                switch (type)\n                {\n                    case VBSymbolType.WhiteSpace:\n                        return RazorResources.VBSymbol_WhiteSpace;\n                    case VBSymbolType.NewLine:\n                        return RazorResources.VBSymbol_NewLine;\n                    case VBSymbolType.Comment:\n                        return RazorResources.VBSymbol_Comment;\n                    case VBSymbolType.Identifier:\n                        return RazorResources.VBSymbol_Identifier;\n                    case VBSymbolType.Keyword:\n                        return RazorResources.VBSymbol_Keyword;\n                    case VBSymbolType.IntegerLiteral:\n                        return RazorResources.VBSymbol_IntegerLiteral;\n                    case VBSymbolType.FloatingPointLiteral:\n                        return RazorResources.VBSymbol_FloatingPointLiteral;\n                    case VBSymbolType.StringLiteral:\n                        return RazorResources.VBSymbol_StringLiteral;\n                    case VBSymbolType.CharacterLiteral:\n                        return RazorResources.VBSymbol_CharacterLiteral;\n                    case VBSymbolType.DateLiteral:\n                        return RazorResources.VBSymbol_DateLiteral;\n                    case VBSymbolType.RazorComment:\n                        return RazorResources.VBSymbol_RazorComment;\n                    default:\n                        return RazorResources.Symbol_Unknown;\n                }\n            }\n            return sample;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Tokenizer/Symbols/VBSymbolType.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Razor.Tokenizer.Symbols\n{\n    public enum VBSymbolType\n    {\n        Unknown,\n        WhiteSpace,\n        NewLine,\n        LineContinuation,\n        Comment,\n        Identifier,\n        Keyword,\n        IntegerLiteral,\n        FloatingPointLiteral,\n        StringLiteral,\n        CharacterLiteral,\n        DateLiteral,\n        LeftParenthesis,\n        RightBrace,\n        LeftBrace,\n        RightParenthesis,\n        Hash,\n        Bang,\n        Comma,\n        Dot,\n        Colon,\n        Concatenation,\n        QuestionMark,\n        Subtract,\n        Multiply,\n        Add,\n        Divide,\n        IntegerDivide,\n        Exponentiation,\n        LessThan,\n        GreaterThan,\n        Equal,\n        RightBracket,\n        LeftBracket,\n        Dollar,\n        Transition,\n\n        RazorCommentTransition,\n        RazorCommentStar,\n        RazorComment\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Tokenizer/Tokenizer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq;\nusing System.Text;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Tokenizer\n{\n    public abstract partial class Tokenizer<TSymbol, TSymbolType> : StateMachine<TSymbol>, ITokenizer\n        where TSymbol : SymbolBase<TSymbolType>\n    {\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"TextDocumentReader does not require disposal\")]\n        protected Tokenizer(ITextDocument source)\n        {\n            if (source == null)\n            {\n                throw new ArgumentNullException(\"source\");\n            }\n            Source = new TextDocumentReader(source);\n            Buffer = new StringBuilder();\n            CurrentErrors = new List<RazorError>();\n            StartSymbol();\n        }\n\n        public TextDocumentReader Source { get; private set; }\n\n        protected StringBuilder Buffer { get; private set; }\n\n        protected bool EndOfFile\n        {\n            get { return Source.Peek() == -1; }\n        }\n\n        protected IList<RazorError> CurrentErrors { get; private set; }\n\n        public abstract TSymbolType RazorCommentStarType { get; }\n        public abstract TSymbolType RazorCommentType { get; }\n        public abstract TSymbolType RazorCommentTransitionType { get; }\n\n        protected bool HaveContent\n        {\n            get { return Buffer.Length > 0; }\n        }\n\n        protected char CurrentCharacter\n        {\n            get\n            {\n                int peek = Source.Peek();\n                return peek == -1 ? '\\0' : (char)peek;\n            }\n        }\n\n        protected SourceLocation CurrentLocation\n        {\n            get { return Source.Location; }\n        }\n\n        protected SourceLocation CurrentStart { get; private set; }\n\n        public virtual TSymbol NextSymbol()\n        {\n            // Post-Condition: Buffer should be empty at the start of Next()\n            Debug.Assert(Buffer.Length == 0);\n            StartSymbol();\n\n            if (EndOfFile)\n            {\n                return null;\n            }\n            TSymbol sym = Turn();\n\n            // Post-Condition: Buffer should be empty at the end of Next()\n            Debug.Assert(Buffer.Length == 0);\n\n            return sym;\n        }\n\n        public void Reset()\n        {\n            CurrentState = StartState;\n        }\n\n        protected abstract TSymbol CreateSymbol(SourceLocation start, string content, TSymbolType type, IEnumerable<RazorError> errors);\n\n        protected TSymbol Single(TSymbolType type)\n        {\n            TakeCurrent();\n            return EndSymbol(type);\n        }\n\n        protected bool TakeString(string input, bool caseSensitive)\n        {\n            int position = 0;\n            Func<char, char> charFilter = c => c;\n            if (caseSensitive)\n            {\n                charFilter = Char.ToLower;\n            }\n            while (!EndOfFile && position < input.Length && charFilter(CurrentCharacter) == charFilter(input[position++]))\n            {\n                TakeCurrent();\n            }\n            return position == input.Length;\n        }\n\n        protected void StartSymbol()\n        {\n            Buffer.Clear();\n            CurrentStart = CurrentLocation;\n            CurrentErrors.Clear();\n        }\n\n        protected TSymbol EndSymbol(TSymbolType type)\n        {\n            return EndSymbol(CurrentStart, type);\n        }\n\n        protected TSymbol EndSymbol(SourceLocation start, TSymbolType type)\n        {\n            TSymbol sym = null;\n            if (HaveContent)\n            {\n                sym = CreateSymbol(start, Buffer.ToString(), type, CurrentErrors.ToArray());\n            }\n            StartSymbol();\n            return sym;\n        }\n\n        protected void ResumeSymbol(TSymbol previous)\n        {\n            // Verify the symbol can be resumed\n            if (previous.Start.AbsoluteIndex + previous.Content.Length != CurrentStart.AbsoluteIndex)\n            {\n                throw new InvalidOperationException(RazorResources.Tokenizer_CannotResumeSymbolUnlessIsPrevious);\n            }\n\n            // Reset the start point\n            CurrentStart = previous.Start;\n\n            // Capture the current buffer content\n            string newContent = Buffer.ToString();\n\n            // Clear the buffer, then put the old content back and add the new content to the end\n            Buffer.Clear();\n            Buffer.Append(previous.Content);\n            Buffer.Append(newContent);\n        }\n\n        protected bool TakeUntil(Func<char, bool> predicate)\n        {\n            // Take all the characters up to the end character\n            while (!EndOfFile && !predicate(CurrentCharacter))\n            {\n                TakeCurrent();\n            }\n\n            // Why did we end?\n            return !EndOfFile;\n        }\n\n        protected Func<char, bool> CharOrWhiteSpace(char character)\n        {\n            return c => c == character || ParserHelpers.IsWhitespace(c) || ParserHelpers.IsNewLine(c);\n        }\n\n        protected void TakeCurrent()\n        {\n            if (EndOfFile)\n            {\n                return;\n            } // No-op\n            Buffer.Append(CurrentCharacter);\n            MoveNext();\n        }\n\n        protected void MoveNext()\n        {\n#if DEBUG\n            _read.Append(CurrentCharacter);\n#endif\n            Source.Read();\n        }\n\n        protected bool TakeAll(string expected, bool caseSensitive)\n        {\n            return Lookahead(expected, takeIfMatch: true, caseSensitive: caseSensitive);\n        }\n\n        protected bool At(string expected, bool caseSensitive)\n        {\n            return Lookahead(expected, takeIfMatch: false, caseSensitive: caseSensitive);\n        }\n\n        protected char Peek()\n        {\n            using (LookaheadToken lookahead = Source.BeginLookahead())\n            {\n                MoveNext();\n                return CurrentCharacter;\n            }\n        }\n\n        protected StateResult AfterRazorCommentTransition()\n        {\n            if (CurrentCharacter != '*')\n            {\n                // We've been moved since last time we were asked for a symbol... reset the state\n                return Transition(StartState);\n            }\n            AssertCurrent('*');\n            TakeCurrent();\n            return Transition(EndSymbol(RazorCommentStarType), RazorCommentBody);\n        }\n\n        protected StateResult RazorCommentBody()\n        {\n            TakeUntil(c => c == '*');\n            if (CurrentCharacter == '*')\n            {\n                char star = CurrentCharacter;\n                SourceLocation start = CurrentLocation;\n                MoveNext();\n                if (!EndOfFile && CurrentCharacter == '@')\n                {\n                    State next = () =>\n                    {\n                        Buffer.Append(star);\n                        return Transition(EndSymbol(start, RazorCommentStarType), () =>\n                        {\n                            if (CurrentCharacter != '@')\n                            {\n                                // We've been moved since last time we were asked for a symbol... reset the state\n                                return Transition(StartState);\n                            }\n                            TakeCurrent();\n                            return Transition(EndSymbol(RazorCommentTransitionType), StartState);\n                        });\n                    };\n\n                    if (HaveContent)\n                    {\n                        return Transition(EndSymbol(RazorCommentType), next);\n                    }\n                    else\n                    {\n                        return Transition(next);\n                    }\n                }\n                else\n                {\n                    Buffer.Append(star);\n                    return Stay();\n                }\n            }\n            return Transition(EndSymbol(RazorCommentType), StartState);\n        }\n\n        private bool Lookahead(string expected, bool takeIfMatch, bool caseSensitive)\n        {\n            Func<char, char> filter = c => c;\n            if (!caseSensitive)\n            {\n                filter = Char.ToLowerInvariant;\n            }\n\n            if (expected.Length == 0 || filter(CurrentCharacter) != filter(expected[0]))\n            {\n                return false;\n            }\n\n            // Capture the current buffer content in case we have to backtrack\n            string oldBuffer = null;\n            if (takeIfMatch)\n            {\n                Buffer.ToString();\n            }\n\n            using (LookaheadToken lookahead = Source.BeginLookahead())\n            {\n                for (int i = 0; i < expected.Length; i++)\n                {\n                    if (filter(CurrentCharacter) != filter(expected[i]))\n                    {\n                        if (takeIfMatch)\n                        {\n                            // Clear the buffer and put the old buffer text back\n                            Buffer.Clear();\n                            Buffer.Append(oldBuffer);\n                        }\n                        // Return without accepting lookahead (thus rejecting it)\n                        return false;\n                    }\n                    if (takeIfMatch)\n                    {\n                        TakeCurrent();\n                    }\n                    else\n                    {\n                        MoveNext();\n                    }\n                }\n                if (takeIfMatch)\n                {\n                    lookahead.Accept();\n                }\n            }\n            return true;\n        }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"This only occurs in Release builds, where this method is empty by design\")]\n        [Conditional(\"DEBUG\")]\n        internal void AssertCurrent(char current)\n        {\n            Debug.Assert(CurrentCharacter == current, \"CurrentCharacter Assumption violated\", \"Assumed that the current character would be {0}, but it is actually {1}\", current, CurrentCharacter);\n        }\n\n        ISymbol ITokenizer.NextSymbol()\n        {\n            return (ISymbol)NextSymbol();\n        }\n    }\n\n#if DEBUG\n    [DebuggerDisplay(\"{DebugDisplay}\")]\n    public partial class Tokenizer<TSymbol, TSymbolType>\n    {\n        private StringBuilder _read = new StringBuilder();\n\n        public string DebugDisplay\n        {\n            get { return String.Format(CultureInfo.InvariantCulture, \"[{0}] [{1}] [{2}]\", _read.ToString(), CurrentCharacter, Remaining); }\n        }\n\n        public string Remaining\n        {\n            get\n            {\n                string remaining = Source.ReadToEnd();\n                Source.Seek(-remaining.Length);\n                return remaining;\n            }\n        }\n    }\n#endif\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Tokenizer/TokenizerView.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Tokenizer\n{\n    [SuppressMessage(\"Microsoft.Design\", \"CA1005:AvoidExcessiveParametersOnGenericTypes\", Justification = \"All generic parameters are required\")]\n    public class TokenizerView<TTokenizer, TSymbol, TSymbolType>\n        where TTokenizer : Tokenizer<TSymbol, TSymbolType>\n        where TSymbol : SymbolBase<TSymbolType>\n    {\n        public TokenizerView(TTokenizer tokenizer)\n        {\n            Tokenizer = tokenizer;\n        }\n\n        public TTokenizer Tokenizer { get; private set; }\n        public bool EndOfFile { get; private set; }\n        public TSymbol Current { get; private set; }\n\n        public ITextDocument Source\n        {\n            get { return Tokenizer.Source; }\n        }\n\n        public bool Next()\n        {\n            Current = Tokenizer.NextSymbol();\n            EndOfFile = (Current == null);\n            return !EndOfFile;\n        }\n\n        public void PutBack(TSymbol symbol)\n        {\n            Debug.Assert(Source.Position == symbol.Start.AbsoluteIndex + symbol.Content.Length);\n            if (Source.Position != symbol.Start.AbsoluteIndex + symbol.Content.Length)\n            {\n                // We've already passed this symbol\n                throw new InvalidOperationException(\n                    String.Format(CultureInfo.CurrentCulture,\n                                  RazorResources.TokenizerView_CannotPutBack,\n                                  symbol.Start.AbsoluteIndex + symbol.Content.Length,\n                                  Source.Position));\n            }\n            Source.Position -= symbol.Content.Length;\n            Current = null;\n            EndOfFile = Source.Position >= Source.Length;\n            Tokenizer.Reset();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Tokenizer/VBHelpers.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Razor.Tokenizer\n{\n    public static class VBHelpers\n    {\n        public static bool IsSingleQuote(char character)\n        {\n            return character == '\\'' || character == '‘' || character == '’';\n        }\n\n        public static bool IsDoubleQuote(char character)\n        {\n            return character == '\"' || character == '“' || character == '”';\n        }\n\n        public static bool IsOctalDigit(char character)\n        {\n            return character >= '0' && character <= '7';\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Tokenizer/VBKeywordDetector.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Tokenizer\n{\n    internal static class VBKeywordDetector\n    {\n        private static readonly Dictionary<string, VBKeyword> _keywords = new Dictionary<string, VBKeyword>(StringComparer.OrdinalIgnoreCase)\n        {\n            { \"addhandler\", VBKeyword.AddHandler },\n            { \"andalso\", VBKeyword.AndAlso },\n            { \"byte\", VBKeyword.Byte },\n            { \"catch\", VBKeyword.Catch },\n            { \"cdate\", VBKeyword.CDate },\n            { \"cint\", VBKeyword.CInt },\n            { \"const\", VBKeyword.Const },\n            { \"csng\", VBKeyword.CSng },\n            { \"culng\", VBKeyword.CULng },\n            { \"declare\", VBKeyword.Declare },\n            { \"directcast\", VBKeyword.DirectCast },\n            { \"else\", VBKeyword.Else },\n            { \"enum\", VBKeyword.Enum },\n            { \"exit\", VBKeyword.Exit },\n            { \"friend\", VBKeyword.Friend },\n            { \"getxmlnamespace\", VBKeyword.GetXmlNamespace },\n            { \"handles\", VBKeyword.Handles },\n            { \"in\", VBKeyword.In },\n            { \"is\", VBKeyword.Is },\n            { \"like\", VBKeyword.Like },\n            { \"mod\", VBKeyword.Mod },\n            { \"mybase\", VBKeyword.MyBase },\n            { \"new\", VBKeyword.New },\n            { \"addressof\", VBKeyword.AddressOf },\n            { \"as\", VBKeyword.As },\n            { \"byval\", VBKeyword.ByVal },\n            { \"cbool\", VBKeyword.CBool },\n            { \"cdbl\", VBKeyword.CDbl },\n            { \"class\", VBKeyword.Class },\n            { \"continue\", VBKeyword.Continue },\n            { \"cstr\", VBKeyword.CStr },\n            { \"cushort\", VBKeyword.CUShort },\n            { \"default\", VBKeyword.Default },\n            { \"do\", VBKeyword.Do },\n            { \"elseif\", VBKeyword.ElseIf },\n            { \"erase\", VBKeyword.Erase },\n            { \"false\", VBKeyword.False },\n            { \"function\", VBKeyword.Function },\n            { \"global\", VBKeyword.Global },\n            { \"if\", VBKeyword.If },\n            { \"inherits\", VBKeyword.Inherits },\n            { \"isnot\", VBKeyword.IsNot },\n            { \"long\", VBKeyword.Long },\n            { \"module\", VBKeyword.Module },\n            { \"myclass\", VBKeyword.MyClass },\n            { \"next\", VBKeyword.Next },\n            { \"alias\", VBKeyword.Alias },\n            { \"boolean\", VBKeyword.Boolean },\n            { \"call\", VBKeyword.Call },\n            { \"cbyte\", VBKeyword.CByte },\n            { \"cdec\", VBKeyword.CDec },\n            { \"clng\", VBKeyword.CLng },\n            { \"csbyte\", VBKeyword.CSByte },\n            { \"ctype\", VBKeyword.CType },\n            { \"date\", VBKeyword.Date },\n            { \"delegate\", VBKeyword.Delegate },\n            { \"double\", VBKeyword.Double },\n            { \"end\", VBKeyword.End },\n            { \"error\", VBKeyword.Error },\n            { \"finally\", VBKeyword.Finally },\n            { \"get\", VBKeyword.Get },\n            { \"gosub\", VBKeyword.GoSub },\n            { \"implements\", VBKeyword.Implements },\n            { \"integer\", VBKeyword.Integer },\n            { \"let\", VBKeyword.Let },\n            { \"loop\", VBKeyword.Loop },\n            { \"mustinherit\", VBKeyword.MustInherit },\n            { \"namespace\", VBKeyword.Namespace },\n            { \"not\", VBKeyword.Not },\n            { \"and\", VBKeyword.And },\n            { \"byref\", VBKeyword.ByRef },\n            { \"case\", VBKeyword.Case },\n            { \"cchar\", VBKeyword.CChar },\n            { \"char\", VBKeyword.Char },\n            { \"cobj\", VBKeyword.CObj },\n            { \"cshort\", VBKeyword.CShort },\n            { \"cuint\", VBKeyword.CUInt },\n            { \"decimal\", VBKeyword.Decimal },\n            { \"dim\", VBKeyword.Dim },\n            { \"each\", VBKeyword.Each },\n            { \"endif\", VBKeyword.EndIf },\n            { \"event\", VBKeyword.Event },\n            { \"for\", VBKeyword.For },\n            { \"gettype\", VBKeyword.GetType },\n            { \"goto\", VBKeyword.GoTo },\n            { \"imports\", VBKeyword.Imports },\n            { \"interface\", VBKeyword.Interface },\n            { \"lib\", VBKeyword.Lib },\n            { \"me\", VBKeyword.Me },\n            { \"mustoverride\", VBKeyword.MustOverride },\n            { \"narrowing\", VBKeyword.Narrowing },\n            { \"nothing\", VBKeyword.Nothing },\n            { \"notinheritable\", VBKeyword.NotInheritable },\n            { \"on\", VBKeyword.On },\n            { \"or\", VBKeyword.Or },\n            { \"overrides\", VBKeyword.Overrides },\n            { \"property\", VBKeyword.Property },\n            { \"rem\", VBKeyword.Rem },\n            { \"readonly\", VBKeyword.ReadOnly },\n            { \"resume\", VBKeyword.Resume },\n            { \"set\", VBKeyword.Set },\n            { \"single\", VBKeyword.Single },\n            { \"string\", VBKeyword.String },\n            { \"then\", VBKeyword.Then },\n            { \"try\", VBKeyword.Try },\n            { \"ulong\", VBKeyword.ULong },\n            { \"wend\", VBKeyword.Wend },\n            { \"with\", VBKeyword.With },\n            { \"notoverridable\", VBKeyword.NotOverridable },\n            { \"operator\", VBKeyword.Operator },\n            { \"orelse\", VBKeyword.OrElse },\n            { \"paramarray\", VBKeyword.ParamArray },\n            { \"protected\", VBKeyword.Protected },\n            { \"redim\", VBKeyword.ReDim },\n            { \"return\", VBKeyword.Return },\n            { \"shadows\", VBKeyword.Shadows },\n            { \"static\", VBKeyword.Static },\n            { \"structure\", VBKeyword.Structure },\n            { \"throw\", VBKeyword.Throw },\n            { \"trycast\", VBKeyword.TryCast },\n            { \"ushort\", VBKeyword.UShort },\n            { \"when\", VBKeyword.When },\n            { \"withevents\", VBKeyword.WithEvents },\n            { \"object\", VBKeyword.Object },\n            { \"option\", VBKeyword.Option },\n            { \"overloads\", VBKeyword.Overloads },\n            { \"partial\", VBKeyword.Partial },\n            { \"public\", VBKeyword.Public },\n            { \"sbyte\", VBKeyword.SByte },\n            { \"shared\", VBKeyword.Shared },\n            { \"step\", VBKeyword.Step },\n            { \"sub\", VBKeyword.Sub },\n            { \"to\", VBKeyword.To },\n            { \"typeof\", VBKeyword.TypeOf },\n            { \"using\", VBKeyword.Using },\n            { \"while\", VBKeyword.While },\n            { \"writeonly\", VBKeyword.WriteOnly },\n            { \"of\", VBKeyword.Of },\n            { \"optional\", VBKeyword.Optional },\n            { \"overridable\", VBKeyword.Overridable },\n            { \"private\", VBKeyword.Private },\n            { \"raiseevent\", VBKeyword.RaiseEvent },\n            { \"removehandler\", VBKeyword.RemoveHandler },\n            { \"select\", VBKeyword.Select },\n            { \"short\", VBKeyword.Short },\n            { \"stop\", VBKeyword.Stop },\n            { \"synclock\", VBKeyword.SyncLock },\n            { \"true\", VBKeyword.True },\n            { \"uinteger\", VBKeyword.UInteger },\n            { \"variant\", VBKeyword.Variant },\n            { \"widening\", VBKeyword.Widening },\n            { \"xor\", VBKeyword.Xor }\n        };\n\n        public static VBKeyword? GetKeyword(string id)\n        {\n            VBKeyword type;\n            if (!_keywords.TryGetValue(id, out type))\n            {\n                return null;\n            }\n            return type;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Tokenizer/VBTokenizer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Tokenizer\n{\n    public class VBTokenizer : Tokenizer<VBSymbol, VBSymbolType>\n    {\n        private static Dictionary<char, VBSymbolType> _operatorTable = new Dictionary<char, VBSymbolType>()\n        {\n            { '_', VBSymbolType.LineContinuation },\n            { '(', VBSymbolType.LeftParenthesis },\n            { ')', VBSymbolType.RightParenthesis },\n            { '[', VBSymbolType.LeftBracket },\n            { ']', VBSymbolType.RightBracket },\n            { '{', VBSymbolType.LeftBrace },\n            { '}', VBSymbolType.RightBrace },\n            { '!', VBSymbolType.Bang },\n            { '#', VBSymbolType.Hash },\n            { ',', VBSymbolType.Comma },\n            { '.', VBSymbolType.Dot },\n            { ':', VBSymbolType.Colon },\n            { '?', VBSymbolType.QuestionMark },\n            { '&', VBSymbolType.Concatenation },\n            { '*', VBSymbolType.Multiply },\n            { '+', VBSymbolType.Add },\n            { '-', VBSymbolType.Subtract },\n            { '/', VBSymbolType.Divide },\n            { '\\\\', VBSymbolType.IntegerDivide },\n            { '^', VBSymbolType.Exponentiation },\n            { '=', VBSymbolType.Equal },\n            { '<', VBSymbolType.LessThan },\n            { '>', VBSymbolType.GreaterThan },\n            { '$', VBSymbolType.Dollar },\n        };\n\n        public VBTokenizer(ITextDocument source)\n            : base(source)\n        {\n            CurrentState = Data;\n        }\n\n        protected override State StartState\n        {\n            get { return Data; }\n        }\n\n        public override VBSymbolType RazorCommentType\n        {\n            get { return VBSymbolType.RazorComment; }\n        }\n\n        public override VBSymbolType RazorCommentTransitionType\n        {\n            get { return VBSymbolType.RazorCommentTransition; }\n        }\n\n        public override VBSymbolType RazorCommentStarType\n        {\n            get { return VBSymbolType.RazorCommentStar; }\n        }\n\n        internal static IEnumerable<VBSymbol> Tokenize(string content)\n        {\n            using (SeekableTextReader reader = new SeekableTextReader(content))\n            {\n                VBTokenizer tok = new VBTokenizer(reader);\n                VBSymbol sym;\n                while ((sym = tok.NextSymbol()) != null)\n                {\n                    yield return sym;\n                }\n            }\n        }\n\n        protected override VBSymbol CreateSymbol(SourceLocation start, string content, VBSymbolType type, IEnumerable<RazorError> errors)\n        {\n            return new VBSymbol(start, content, type, errors);\n        }\n\n        private StateResult Data()\n        {\n            // We are accepting more characters and whitespace/newlines then the VB Spec defines, to simplify things\n            // Since the code must still be compiled by a VB compiler, this will not cause adverse effects.\n            if (ParserHelpers.IsNewLine(CurrentCharacter))\n            {\n                // VB Spec §2.1.1\n                bool checkTwoCharNewline = CurrentCharacter == '\\r';\n                TakeCurrent();\n                if (checkTwoCharNewline && CurrentCharacter == '\\n')\n                {\n                    TakeCurrent();\n                }\n                return Stay(EndSymbol(VBSymbolType.NewLine));\n            }\n            else if (ParserHelpers.IsWhitespace(CurrentCharacter))\n            {\n                // CSharp Spec §2.1.3\n                TakeUntil(c => !ParserHelpers.IsWhitespace(c));\n                return Stay(EndSymbol(VBSymbolType.WhiteSpace));\n            }\n            else if (VBHelpers.IsSingleQuote(CurrentCharacter))\n            {\n                TakeCurrent();\n                return CommentBody();\n            }\n            else if (IsIdentifierStart())\n            {\n                return Identifier();\n            }\n            else if (Char.IsDigit(CurrentCharacter))\n            {\n                return DecimalLiteral();\n            }\n            else if (CurrentCharacter == '&')\n            {\n                char next = Char.ToLower(Peek(), CultureInfo.InvariantCulture);\n                if (next == 'h')\n                {\n                    return HexLiteral();\n                }\n                else if (next == 'o')\n                {\n                    return OctLiteral();\n                }\n            }\n            else if (CurrentCharacter == '.' && Char.IsDigit(Peek()))\n            {\n                return FloatingPointLiteralEnd();\n            }\n            else if (VBHelpers.IsDoubleQuote(CurrentCharacter))\n            {\n                TakeCurrent();\n                return Transition(QuotedLiteral);\n            }\n            else if (AtDateLiteral())\n            {\n                return DateLiteral();\n            }\n            else if (CurrentCharacter == '@')\n            {\n                TakeCurrent();\n                if (CurrentCharacter == '*')\n                {\n                    return Transition(EndSymbol(VBSymbolType.RazorCommentTransition), AfterRazorCommentTransition);\n                }\n                else if (CurrentCharacter == '@')\n                {\n                    // Could be escaped comment transition\n                    return Transition(EndSymbol(VBSymbolType.Transition), () =>\n                    {\n                        TakeCurrent();\n                        return Transition(EndSymbol(VBSymbolType.Transition), Data);\n                    });\n                }\n                else\n                {\n                    return Stay(EndSymbol(VBSymbolType.Transition));\n                }\n            }\n            return Stay(EndSymbol(Operator()));\n        }\n\n        private StateResult DateLiteral()\n        {\n            AssertCurrent('#');\n            TakeCurrent();\n            TakeUntil(c => c == '#' || ParserHelpers.IsNewLine(c));\n            if (CurrentCharacter == '#')\n            {\n                TakeCurrent();\n            }\n            return Stay(EndSymbol(VBSymbolType.DateLiteral));\n        }\n\n        private bool AtDateLiteral()\n        {\n            if (CurrentCharacter != '#')\n            {\n                return false;\n            }\n            int start = Source.Position;\n            try\n            {\n                MoveNext();\n                while (ParserHelpers.IsWhitespace(CurrentCharacter))\n                {\n                    MoveNext();\n                }\n                return Char.IsDigit(CurrentCharacter);\n            }\n            finally\n            {\n                Source.Position = start;\n            }\n        }\n\n        private StateResult QuotedLiteral()\n        {\n            TakeUntil(c => VBHelpers.IsDoubleQuote(c) || ParserHelpers.IsNewLine(c));\n            if (VBHelpers.IsDoubleQuote(CurrentCharacter))\n            {\n                TakeCurrent();\n                if (VBHelpers.IsDoubleQuote(CurrentCharacter))\n                {\n                    // Escape sequence, remain in the string\n                    TakeCurrent();\n                    return Stay();\n                }\n            }\n\n            VBSymbolType type = VBSymbolType.StringLiteral;\n            if (Char.ToLowerInvariant(CurrentCharacter) == 'c')\n            {\n                TakeCurrent();\n                type = VBSymbolType.CharacterLiteral;\n            }\n            return Transition(EndSymbol(type), Data);\n        }\n\n        private StateResult DecimalLiteral()\n        {\n            TakeUntil(c => !Char.IsDigit(c));\n            char lower = Char.ToLowerInvariant(CurrentCharacter);\n            if (IsFloatTypeSuffix(lower) || lower == '.' || lower == 'e')\n            {\n                return FloatingPointLiteralEnd();\n            }\n            else\n            {\n                TakeIntTypeSuffix();\n                return Stay(EndSymbol(VBSymbolType.IntegerLiteral));\n            }\n        }\n\n        private static bool IsFloatTypeSuffix(char chr)\n        {\n            chr = Char.ToLowerInvariant(chr);\n            return chr == 'f' || chr == 'r' || chr == 'd';\n        }\n\n        private StateResult FloatingPointLiteralEnd()\n        {\n            if (CurrentCharacter == '.')\n            {\n                TakeCurrent();\n                TakeUntil(c => !Char.IsDigit(c));\n            }\n            if (Char.ToLowerInvariant(CurrentCharacter) == 'e')\n            {\n                TakeCurrent();\n                if (CurrentCharacter == '+' || CurrentCharacter == '-')\n                {\n                    TakeCurrent();\n                }\n                TakeUntil(c => !Char.IsDigit(c));\n            }\n            if (IsFloatTypeSuffix(CurrentCharacter))\n            {\n                TakeCurrent();\n            }\n            return Stay(EndSymbol(VBSymbolType.FloatingPointLiteral));\n        }\n\n        private StateResult HexLiteral()\n        {\n            AssertCurrent('&');\n            TakeCurrent();\n            Debug.Assert(Char.ToLowerInvariant(CurrentCharacter) == 'h');\n            TakeCurrent();\n            TakeUntil(c => !ParserHelpers.IsHexDigit(c));\n            TakeIntTypeSuffix();\n            return Stay(EndSymbol(VBSymbolType.IntegerLiteral));\n        }\n\n        private StateResult OctLiteral()\n        {\n            AssertCurrent('&');\n            TakeCurrent();\n            Debug.Assert(Char.ToLowerInvariant(CurrentCharacter) == 'o');\n            TakeCurrent();\n            TakeUntil(c => !VBHelpers.IsOctalDigit(c));\n            TakeIntTypeSuffix();\n            return Stay(EndSymbol(VBSymbolType.IntegerLiteral));\n        }\n\n        private VBSymbolType Operator()\n        {\n            char op = CurrentCharacter;\n            TakeCurrent();\n            VBSymbolType ret;\n            if (_operatorTable.TryGetValue(op, out ret))\n            {\n                return ret;\n            }\n            return VBSymbolType.Unknown;\n        }\n\n        private void TakeIntTypeSuffix()\n        {\n            // Take the \"U\" in US, UI, UL\n            if (Char.ToLowerInvariant(CurrentCharacter) == 'u')\n            {\n                TakeCurrent(); // Unsigned Prefix\n            }\n\n            // Take the S, I or L integer suffix\n            if (IsIntegerSuffix(CurrentCharacter))\n            {\n                TakeCurrent();\n            }\n        }\n\n        private static bool IsIntegerSuffix(char chr)\n        {\n            chr = Char.ToLowerInvariant(chr);\n            return chr == 's' || chr == 'i' || chr == 'l';\n        }\n\n        private StateResult CommentBody()\n        {\n            TakeUntil(ParserHelpers.IsNewLine);\n            return Stay(EndSymbol(VBSymbolType.Comment));\n        }\n\n        private StateResult Identifier()\n        {\n            bool isEscaped = false;\n            if (CurrentCharacter == '[')\n            {\n                TakeCurrent();\n                isEscaped = true;\n            }\n            TakeUntil(c => !ParserHelpers.IsIdentifierPart(c));\n\n            // If we're escaped, take the ']'\n            if (isEscaped)\n            {\n                if (CurrentCharacter == ']')\n                {\n                    TakeCurrent();\n                }\n            }\n\n            // Check for Keywords and build the symbol\n            VBKeyword? keyword = VBKeywordDetector.GetKeyword(Buffer.ToString());\n            if (keyword == VBKeyword.Rem)\n            {\n                return CommentBody();\n            }\n\n            VBSymbol sym = new VBSymbol(CurrentStart, Buffer.ToString(), keyword == null ? VBSymbolType.Identifier : VBSymbolType.Keyword)\n            {\n                Keyword = keyword\n            };\n\n            StartSymbol();\n\n            return Stay(sym);\n        }\n\n        private bool IsIdentifierStart()\n        {\n            if (CurrentCharacter == '_')\n            {\n                // VB Spec §2.2:\n                //  If an identifier begins with an underscore, it must contain at least one other valid identifier character to disambiguate it from a line continuation.\n                return ParserHelpers.IsIdentifierPart(Peek());\n            }\n            if (CurrentCharacter == '[')\n            {\n                return ParserHelpers.IsIdentifierPart(Peek());\n            }\n            return ParserHelpers.IsIdentifierStart(CurrentCharacter);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Tokenizer/XmlHelpers.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Razor.Tokenizer\n{\n    internal static class XmlHelpers\n    {\n        public static bool IsXmlNameStartChar(char chr)\n        {\n            // [4] NameStartChar    ::= \":\" | [A-Z] | \"_\" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | \n            //                          [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | \n            //                          [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]\n            // http://www.w3.org/TR/REC-xml/#NT-Name\n\n            return Char.IsLetter(chr) ||\n                   chr == ':' ||\n                   chr == '_' ||\n                   IsInRange(chr, 0xC0, 0xD6) ||\n                   IsInRange(chr, 0xD8, 0xF6) ||\n                   IsInRange(chr, 0xF8, 0x2FF) ||\n                   IsInRange(chr, 0x370, 0x37D) ||\n                   IsInRange(chr, 0x37F, 0x1FFF) ||\n                   IsInRange(chr, 0x200C, 0x200D) ||\n                   IsInRange(chr, 0x2070, 0x218F) ||\n                   IsInRange(chr, 0x2C00, 0x2FEF) ||\n                   IsInRange(chr, 0x3001, 0xD7FF) ||\n                   IsInRange(chr, 0xF900, 0xFDCF) ||\n                   IsInRange(chr, 0xFDF0, 0xFFFD) ||\n                   IsInRange(chr, 0x10000, 0xEFFFF);\n        }\n\n        public static bool IsXmlNameChar(char chr)\n        {\n            // [4a] NameChar     ::= NameStartChar | \"-\" | \".\" | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]\n            // http://www.w3.org/TR/REC-xml/#NT-Name\n            return Char.IsDigit(chr) ||\n                   IsXmlNameStartChar(chr) ||\n                   chr == '-' ||\n                   chr == '.' ||\n                   chr == '·' || // (U+00B7 is middle dot: ·)\n                   IsInRange(chr, 0x0300, 0x036F) ||\n                   IsInRange(chr, 0x203F, 0x2040);\n        }\n\n        public static bool IsInRange(char chr, int low, int high)\n        {\n            return ((int)chr >= low) && ((int)chr <= high);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Utils/CharUtils.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Razor.Utils\n{\n    internal static class CharUtils\n    {\n        internal static bool IsNonNewLineWhitespace(char c)\n        {\n            return Char.IsWhiteSpace(c) && !IsNewLine(c);\n        }\n\n        internal static bool IsNewLine(char c)\n        {\n            return c == 0x000d // Carriage return\n                   || c == 0x000a // Linefeed\n                   || c == 0x2028 // Line separator\n                   || c == 0x2029; // Paragraph separator\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Utils/DisposableAction.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Razor.Utils\n{\n    internal class DisposableAction : IDisposable\n    {\n        private Action _action;\n\n        public DisposableAction(Action action)\n        {\n            if (action == null)\n            {\n                throw new ArgumentNullException(\"action\");\n            }\n            _action = action;\n        }\n\n        public void Dispose()\n        {\n            Dispose(true);\n            GC.SuppressFinalize(this);\n        }\n\n        protected virtual void Dispose(bool disposing)\n        {\n            // If we were disposed by the finalizer it's because the user didn't use a \"using\" block, so don't do anything!\n            if (disposing)\n            {\n                _action();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Utils/EnumUtil.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Razor.Utils\n{\n    internal static class EnumUtil\n    {\n        public static IEnumerable<T> Single<T>(T item)\n        {\n            yield return item;\n        }\n\n        public static IEnumerable<T> Prepend<T>(T item, IEnumerable<T> enumerable)\n        {\n            yield return item;\n            foreach (T t in enumerable)\n            {\n                yield return t;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/Utils/EnumeratorExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace System.Web.Razor.Utils\n{\n    internal static class EnumeratorExtensions\n    {\n        public static IEnumerable<T> Flatten<T>(this IEnumerable<IEnumerable<T>> source)\n        {\n            return source.SelectMany(e => e);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.Razor/VBRazorCodeLanguage.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing Microsoft.VisualBasic;\n\nnamespace System.Web.Razor\n{\n    /// <summary>\n    /// Defines the Visual Basic Code Language for Razor\n    /// </summary>\n    public class VBRazorCodeLanguage : RazorCodeLanguage\n    {\n        private const string VBLanguageName = \"vb\";\n\n        /// <summary>\n        /// Returns the name of the language: \"vb\"\n        /// </summary>\n        public override string LanguageName\n        {\n            get { return VBLanguageName; }\n        }\n\n        /// <summary>\n        /// Returns the type of the CodeDOM provider for this language\n        /// </summary>\n        public override Type CodeDomProviderType\n        {\n            get { return typeof(VBCodeProvider); }\n        }\n\n        /// <summary>\n        /// Constructs a new instance of the code parser for this language\n        /// </summary>\n        public override ParserBase CreateCodeParser()\n        {\n            return new VBCodeParser();\n        }\n\n        /// <summary>\n        /// Constructs a new instance of the code generator for this language with the specified settings\n        /// </summary>\n        public override RazorCodeGenerator CreateCodeGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host)\n        {\n            return new VBRazorCodeGenerator(className, rootNamespaceName, sourceFileName, host);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/ApplicationPart.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\nusing System.Web.Routing;\nusing System.Web.WebPages.ApplicationParts;\nusing System.Web.WebPages.Resources;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.WebPages\n{\n    public class ApplicationPart\n    {\n        private const string ModuleRootSyntax = \"@/\";\n        private const string ResourceVirtualPathRoot = \"~/r.ashx/\";\n        private const string ResourceRoute = \"r.ashx/{module}/{*path}\";\n        private static readonly LazyAction _initApplicationPart = new LazyAction(InitApplicationParts);\n        private static ApplicationPartRegistry _partRegistry;\n        private readonly Lazy<IDictionary<string, string>> _applicationPartResources;\n        private readonly Lazy<string> _applicationPartName;\n\n        public ApplicationPart(Assembly assembly, string rootVirtualPath)\n            : this(new ResourceAssembly(assembly), rootVirtualPath)\n        {\n        }\n\n        internal ApplicationPart(IResourceAssembly assembly, string rootVirtualPath)\n        {\n            if (String.IsNullOrEmpty(rootVirtualPath))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"rootVirtualPath\");\n            }\n\n            // Make sure the root path ends with a slash\n            if (!rootVirtualPath.EndsWith(\"/\", StringComparison.Ordinal))\n            {\n                rootVirtualPath += \"/\";\n            }\n\n            Assembly = assembly;\n            RootVirtualPath = rootVirtualPath;\n            _applicationPartResources = new Lazy<IDictionary<string, string>>(() => Assembly.GetManifestResourceNames().ToDictionary(key => key, key => key, StringComparer.OrdinalIgnoreCase));\n            _applicationPartName = new Lazy<string>(() => Assembly.Name);\n        }\n\n        internal IResourceAssembly Assembly { get; private set; }\n\n        internal string RootVirtualPath { get; private set; }\n\n        internal string Name\n        {\n            get { return _applicationPartName.Value; }\n        }\n\n        internal IDictionary<string, string> ApplicationPartResources\n        {\n            get { return _applicationPartResources.Value; }\n        }\n\n        // REVIEW: Do we need an Unregister?\n        // Register an assembly as an application module, which makes its compiled web pages\n        // and embedded resources available\n        public static void Register(ApplicationPart applicationPart)\n        {\n            // Ensure the registry is ready and the route handlers are set up\n            _initApplicationPart.EnsurePerformed();\n            Debug.Assert(_partRegistry != null, \"Part registry should be initialized\");\n\n            _partRegistry.Register(applicationPart);\n        }\n\n        public static string ProcessVirtualPath(Assembly assembly, string baseVirtualPath, string virtualPath)\n        {\n            if (_partRegistry == null)\n            {\n                // This was called without registering a part.\n                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, WebPageResources.ApplicationPart_ModuleNotRegistered, assembly));\n            }\n\n            ApplicationPart applicationPart = _partRegistry[new ResourceAssembly(assembly)];\n            if (applicationPart == null)\n            {\n                throw new InvalidOperationException(\n                    String.Format(CultureInfo.CurrentCulture,\n                                  WebPageResources.ApplicationPart_ModuleNotRegistered,\n                                  assembly));\n            }\n\n            return applicationPart.ProcessVirtualPath(baseVirtualPath, virtualPath);\n        }\n\n        internal static IEnumerable<ApplicationPart> GetRegisteredParts()\n        {\n            _initApplicationPart.EnsurePerformed();\n            return _partRegistry.RegisteredParts;\n        }\n\n        private string ProcessVirtualPath(string baseVirtualPath, string virtualPath)\n        {\n            virtualPath = ResolveVirtualPath(RootVirtualPath, baseVirtualPath, virtualPath);\n            if (!virtualPath.StartsWith(RootVirtualPath, StringComparison.OrdinalIgnoreCase))\n            {\n                return virtualPath;\n            }\n\n            // Remove the root package path from the path, since the resource name doesn't use it\n            // e.g. ~/admin/Debugger/Sub Folder/foo.jpg ==> ~/Sub Folder/foo.jpg\n            string packageVirtualPath = \"~/\" + virtualPath.Substring(RootVirtualPath.Length);\n\n            string resourceName = GetResourceNameFromVirtualPath(packageVirtualPath);\n\n            // If the assembly doesn't contains that resource, don't change the path\n            if (!ApplicationPartResources.ContainsKey(resourceName))\n            {\n                return virtualPath;\n            }\n\n            // The resource exists, so return a special path that will be handled by the resource handler\n            return GetResourceVirtualPath(virtualPath);\n        }\n\n        /// <summary>\n        /// Expands a virtual path by replacing a leading \"@\" with the application part root\n        /// or combining it with the specified baseVirtualPath\n        /// </summary>\n        internal static string ResolveVirtualPath(string applicationRoot, string baseVirtualPath, string virtualPath)\n        {\n            // If it starts with @/, replace that with the package root\n            // e.g. @/Sub Folder/foo.jpg ==> ~/admin/Debugger/Sub Folder/foo.jpg\n            if (virtualPath.StartsWith(ModuleRootSyntax, StringComparison.OrdinalIgnoreCase))\n            {\n                return applicationRoot + virtualPath.Substring(ModuleRootSyntax.Length);\n            }\n            else\n            {\n                // Resolve if relative to the base\n                return VirtualPathUtility.Combine(baseVirtualPath, virtualPath);\n            }\n        }\n\n        internal Stream GetResourceStream(string virtualPath)\n        {\n            string resourceName = GetResourceNameFromVirtualPath(virtualPath);\n            string normalizedResourceName;\n            if (ApplicationPartResources.TryGetValue(resourceName, out normalizedResourceName))\n            {\n                // Return the resource stream\n                return Assembly.GetManifestResourceStream(normalizedResourceName);\n            }\n            return null;\n        }\n\n        // Get the name of an embedded resource based on a virtual path\n        private string GetResourceNameFromVirtualPath(string virtualPath)\n        {\n            return GetResourceNameFromVirtualPath(Name, virtualPath);\n        }\n\n        internal static string GetResourceNameFromVirtualPath(string moduleName, string virtualPath)\n        {\n            // Make sure path starts with ~/\n            if (!virtualPath.StartsWith(\"~/\", StringComparison.Ordinal))\n            {\n                virtualPath = \"~/\" + virtualPath;\n            }\n\n            // Get the directory part of the path\n            // e.g. ~/Sub Folder/foo.jpg ==> ~/Sub Folder/\n            string dir = VirtualPathUtility.GetDirectory(virtualPath);\n\n            // Get rid of the starting ~/\n            // e.g. ~/Sub Folder/ ==> Sub Folder/\n            if (dir.Length >= 2)\n            {\n                dir = dir.Substring(2);\n            }\n\n            // Replace / with . and spaces with _\n            // TODO: other special chars need to be replaced by _ as well\n            // e.g. Sub Folder/ ==> Sub_Folder.\n            dir = dir.Replace('/', '.');\n            dir = dir.Replace(' ', '_');\n\n            // Get the file name part.  That part of the resource names is the same as in the virtual path,\n            // so no replacements are needed\n            // e.g. ~/Sub Folder/foo.jpg ==> foo.jpg\n            string fileName = Path.GetFileName(virtualPath);\n\n            // Put them back together, and prepend the assembly name\n            // e.g. DebuggerAssembly.Sub_Folder.foo.jpg\n            return moduleName + \".\" + dir + fileName;\n        }\n\n        // Get a virtual path that uses the resource handler from a regular virtual path\n        private string GetResourceVirtualPath(string virtualPath)\n        {\n            return GetResourceVirtualPath(Name, RootVirtualPath, virtualPath);\n        }\n\n        internal static string GetResourceVirtualPath(string moduleName, string moduleRoot, string virtualPath)\n        {\n            // The path should always start with the root of the module. Skip it.\n            Debug.Assert(virtualPath.StartsWith(moduleRoot, StringComparison.OrdinalIgnoreCase));\n            virtualPath = virtualPath.Substring(moduleRoot.Length).TrimStart('/');\n\n            // Make a path to the resource through our resource route, e.g. ~/r.ashx/sub/foo.jpg\n            // e.g. ~/admin/Debugger/Sub Folder/foo.jpg ==> ~/r.ashx/DebuggerPackageName/Sub Folder/foo.jpg\n            return ResourceVirtualPathRoot + HttpUtility.UrlPathEncode(moduleName) + \"/\" + virtualPath;\n        }\n\n        private static void InitApplicationParts()\n        {\n            // Register the virtual path factory\n            var virtualPathFactory = new DictionaryBasedVirtualPathFactory();\n            VirtualPathFactoryManager.RegisterVirtualPathFactory(virtualPathFactory);\n\n            // Intantiate the part registry\n            _partRegistry = new ApplicationPartRegistry(virtualPathFactory);\n\n            // Register the resource route\n            RouteTable.Routes.Add(new Route(ResourceRoute, new ResourceRouteHandler(_partRegistry)));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/ApplicationParts/ApplicationPartRegistry.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Linq.Expressions;\nusing System.Web.WebPages.Resources;\n\nnamespace System.Web.WebPages.ApplicationParts\n{\n    internal class ApplicationPartRegistry\n    {\n        // Page types that we could serve\n        private static readonly Type _webPageType = typeof(WebPageRenderingBase);\n        private readonly DictionaryBasedVirtualPathFactory _virtualPathFactory;\n        private readonly ConcurrentDictionary<string, bool> _registeredVirtualPaths;\n        private readonly ConcurrentDictionary<IResourceAssembly, ApplicationPart> _applicationParts;\n\n        public ApplicationPartRegistry(DictionaryBasedVirtualPathFactory pathFactory)\n        {\n            _applicationParts = new ConcurrentDictionary<IResourceAssembly, ApplicationPart>();\n            _registeredVirtualPaths = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);\n            _virtualPathFactory = pathFactory;\n        }\n\n        public IEnumerable<ApplicationPart> RegisteredParts\n        {\n            get { return _applicationParts.Values; }\n        }\n\n        public ApplicationPart this[string name]\n        {\n            get { return _applicationParts.Values.FirstOrDefault(appPart => appPart.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); }\n        }\n\n        public ApplicationPart this[IResourceAssembly assembly]\n        {\n            get\n            {\n                ApplicationPart part;\n                if (!_applicationParts.TryGetValue(assembly, out part))\n                {\n                    part = null;\n                }\n                return part;\n            }\n        }\n\n        // Register an assembly as an application module, which makes its compiled web pages\n        // and embedded resources available\n        public void Register(ApplicationPart applicationPart)\n        {\n            Register(applicationPart, registerPageAction: null); // Use default action which creates a new page\n        }\n\n        // Register an assembly as an application module, which makes its compiled web pages\n        // and embedded resources available\n        internal void Register(ApplicationPart applicationPart, Func<object> registerPageAction)\n        {\n            // Throw if this assembly has been registered\n            if (_applicationParts.ContainsKey(applicationPart.Assembly))\n            {\n                throw new InvalidOperationException(\n                    String.Format(CultureInfo.CurrentCulture,\n                                  WebPageResources.ApplicationPart_ModuleAlreadyRegistered, applicationPart.Assembly));\n            }\n\n            // Throw if the virtual path is already in use\n            if (_registeredVirtualPaths.ContainsKey(applicationPart.RootVirtualPath))\n            {\n                throw new InvalidOperationException(\n                    String.Format(CultureInfo.CurrentCulture,\n                                  WebPageResources.ApplicationPart_ModuleAlreadyRegisteredForVirtualPath, applicationPart.RootVirtualPath));\n            }\n\n            // REVIEW: Should we register the app-part after we scan the assembly for webpages?\n            // Add the part to the list\n            if (_applicationParts.TryAdd(applicationPart.Assembly, applicationPart))\n            {\n                // We don't really care about the value\n                _registeredVirtualPaths.TryAdd(applicationPart.RootVirtualPath, true);\n\n                // Get all of the web page types\n                var webPageTypes = from type in applicationPart.Assembly.GetTypes()\n                                   where type.IsSubclassOf(_webPageType)\n                                   select type;\n\n                // Register each of page with the plan9\n                foreach (Type webPageType in webPageTypes)\n                {\n                    RegisterWebPage(applicationPart, webPageType, registerPageAction);\n                }\n            }\n        }\n\n        private void RegisterWebPage(ApplicationPart module, Type webPageType, Func<object> registerPageAction)\n        {\n            var virtualPathAttribute = webPageType.GetCustomAttributes(typeof(PageVirtualPathAttribute), false)\n                .Cast<PageVirtualPathAttribute>()\n                .SingleOrDefault();\n\n            // Ignore it if it doesn't have a PageVirtualPathAttribute\n            if (virtualPathAttribute == null)\n            {\n                return;\n            }\n\n            // Get the path of the page relative to the module root\n            string virtualPath = GetRootRelativeVirtualPath(module.RootVirtualPath, virtualPathAttribute.VirtualPath);\n\n            // Create a factory for the page type\n            Func<object> pageFactory = registerPageAction ?? NewTypeInstance(webPageType);\n\n            // Register a page factory for it\n            _virtualPathFactory.RegisterPath(virtualPath, pageFactory);\n        }\n\n        private static Func<object> NewTypeInstance(Type type)\n        {\n            return Expression.Lambda<Func<object>>(Expression.New(type)).Compile();\n        }\n\n        internal static string GetRootRelativeVirtualPath(string rootVirtualPath, string pageVirtualPath)\n        {\n            string virtualPath = pageVirtualPath;\n\n            // Trim the ~/ prefix, since we want it to be relative to the module base path\n            if (virtualPath.StartsWith(\"~/\", StringComparison.Ordinal))\n            {\n                virtualPath = virtualPath.Substring(2);\n            }\n\n            if (!rootVirtualPath.EndsWith(\"/\", StringComparison.OrdinalIgnoreCase))\n            {\n                rootVirtualPath += \"/\";\n            }\n\n            // Combine it with the root\n            virtualPath = VirtualPathUtility.Combine(rootVirtualPath, virtualPath);\n            return virtualPath;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/ApplicationParts/DictionaryBasedVirtualPathFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\n\nnamespace System.Web.WebPages.ApplicationParts\n{\n    // IVirtualPathFactory that keeps track of a mapping from virtual paths to handler factories\n    internal class DictionaryBasedVirtualPathFactory : IVirtualPathFactory\n    {\n        private Dictionary<string, Func<object>> _factories = new Dictionary<string, Func<object>>(StringComparer.OrdinalIgnoreCase);\n\n        internal void RegisterPath(string virtualPath, Func<object> factory)\n        {\n            _factories[virtualPath] = factory;\n        }\n\n        public bool Exists(string virtualPath)\n        {\n            return _factories.ContainsKey(virtualPath);\n        }\n\n        public object CreateInstance(string virtualPath)\n        {\n            // Instantiate an object for the path\n            // Note that this fails if it doesn't exist.  PathExists is assumed to have been called first\n            Debug.Assert(Exists(virtualPath));\n            return _factories[virtualPath]();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/ApplicationParts/IResourceAssembly.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\n\nnamespace System.Web.WebPages.ApplicationParts\n{\n    // For unit testing purpose since Assembly is not Moqable\n    internal interface IResourceAssembly\n    {\n        string Name { get; }\n        Stream GetManifestResourceStream(string name);\n        IEnumerable<string> GetManifestResourceNames();\n        IEnumerable<Type> GetTypes();\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/ApplicationParts/LazyAction.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics;\n\nnamespace System.Web.WebPages.ApplicationParts\n{\n    internal class LazyAction\n    {\n        private Lazy<object> _lazyAction;\n\n        public LazyAction(Action action)\n        {\n            Debug.Assert(action != null, \"action should not be null\");\n            // Setup the lazy object to run our action and just return null \n            // since we don't care about the value\n            _lazyAction = new Lazy<object>(() =>\n            {\n                action();\n                return null;\n            });\n        }\n\n        public object EnsurePerformed()\n        {\n            // REVIEW: This isn't used we're just exploiting the use of Lazy<T> to execute \n            // our action once in a thread safe way\n            // It would be nice if the framework had Unit (i.e a better void type so we could type Func<Unit> -> Action) \n            return _lazyAction.Value;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/ApplicationParts/ResourceAssembly.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Reflection;\n\nnamespace System.Web.WebPages.ApplicationParts\n{\n    // Implementation of IResourceAssembly over a standard assembly\n    internal class ResourceAssembly : IResourceAssembly\n    {\n        private readonly Assembly _assembly;\n\n        public ResourceAssembly(Assembly assembly)\n        {\n            if (assembly == null)\n            {\n                throw new ArgumentNullException(\"assembly\");\n            }\n            _assembly = assembly;\n        }\n\n        public string Name\n        {\n            get\n            {\n                // Need this for medium trust\n                AssemblyName assemblyName = new AssemblyName(_assembly.FullName);\n                Debug.Assert(assemblyName != null, \"Assembly name should not be null\");\n                // Use the assembly short name\n                return assemblyName.Name;\n            }\n        }\n\n        public Stream GetManifestResourceStream(string name)\n        {\n            return _assembly.GetManifestResourceStream(name);\n        }\n\n        public IEnumerable<string> GetManifestResourceNames()\n        {\n            return _assembly.GetManifestResourceNames();\n        }\n\n        public IEnumerable<Type> GetTypes()\n        {\n            return _assembly.GetExportedTypes();\n        }\n\n        public override bool Equals(object obj)\n        {\n            var otherAssembly = obj as ResourceAssembly;\n            return otherAssembly != null && otherAssembly._assembly.Equals(_assembly);\n        }\n\n        public override int GetHashCode()\n        {\n            return _assembly.GetHashCode();\n        }\n\n        public override String ToString()\n        {\n            return _assembly.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/ApplicationParts/ResourceHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Web.WebPages.Resources;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.WebPages.ApplicationParts\n{\n    // Used to serve static resource files (e.g. .jpg, .css, .js) that live inside appliaction modules\n    internal class ResourceHandler : IHttpHandler\n    {\n        private readonly string _path;\n        private readonly ApplicationPart _applicationPart;\n\n        public ResourceHandler(ApplicationPart applicationPart, string path)\n        {\n            if (applicationPart == null)\n            {\n                throw new ArgumentNullException(\"applicationPart\");\n            }\n\n            if (String.IsNullOrEmpty(path))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"path\");\n            }\n\n            _applicationPart = applicationPart;\n            _path = path;\n        }\n\n        public bool IsReusable\n        {\n            get { return true; }\n        }\n\n        public void ProcessRequest(HttpContext context)\n        {\n            ProcessRequest(new HttpResponseWrapper(context.Response));\n        }\n\n        internal void ProcessRequest(HttpResponseBase response)\n        {\n            string virtualPath = _path;\n\n            // Make sure it starts with ~/\n            if (!virtualPath.StartsWith(\"~/\", StringComparison.Ordinal))\n            {\n                virtualPath = \"~/\" + virtualPath;\n            }\n\n            // Get the resource stream for this virtual path\n            using (var stream = _applicationPart.GetResourceStream(virtualPath))\n            {\n                if (stream == null)\n                {\n                    throw new HttpException(404, String.Format(\n                        CultureInfo.CurrentCulture,\n                        WebPageResources.ApplicationPart_ResourceNotFound, _path));\n                }\n\n                // Set the mime type based on the file extension\n                response.ContentType = MimeMapping.GetMimeMapping(virtualPath);\n\n                // Copy it to the response\n                stream.CopyTo(response.OutputStream);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/ApplicationParts/ResourceRouteHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Web.Routing;\nusing System.Web.WebPages.Resources;\n\nnamespace System.Web.WebPages.ApplicationParts\n{\n    internal class ResourceRouteHandler : IRouteHandler\n    {\n        private ApplicationPartRegistry _partRegistry;\n\n        public ResourceRouteHandler(ApplicationPartRegistry partRegistry)\n        {\n            _partRegistry = partRegistry;\n        }\n\n        public IHttpHandler GetHttpHandler(RequestContext requestContext)\n        {\n            // Get the package name and static resource path from the route\n            string partName = (string)requestContext.RouteData.GetRequiredString(\"module\");\n\n            // Try to find an application module by this name\n            ApplicationPart module = _partRegistry[partName];\n\n            // Throw an exception if we can't find the module by name\n            if (module == null)\n            {\n                throw new InvalidOperationException(\n                    String.Format(CultureInfo.CurrentCulture,\n                                  WebPageResources.ApplicationPart_ModuleCannotBeFound, partName));\n            }\n\n            // Get the resource path\n            string path = (string)requestContext.RouteData.GetRequiredString(\"path\");\n\n            // Return the resource handler for this module and path\n            return new ResourceHandler(module, path);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/ApplicationStartPage.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.IO;\nusing System.Reflection;\nusing System.Threading;\nusing System.Web.Caching;\nusing System.Web.Hosting;\nusing Microsoft.Web.Infrastructure;\n\nnamespace System.Web.WebPages\n{\n    public abstract class ApplicationStartPage : WebPageExecutingBase\n    {\n        private static readonly Action<Action> _safeExecuteStartPageThunk = GetSafeExecuteStartPageThunk();\n        public static readonly string StartPageVirtualPath = \"~/_appstart.\";\n        public static readonly string CacheKeyPrefix = \"__AppStartPage__\";\n\n        public HttpApplication Application { get; internal set; }\n\n        public override HttpContextBase Context\n        {\n            get { return new HttpContextWrapper(Application.Context); }\n        }\n\n        public static HtmlString Markup { get; private set; }\n\n        internal static Exception Exception { get; private set; }\n\n        public TextWriter Output { get; internal set; }\n\n        public override string VirtualPath\n        {\n            get { return StartPageVirtualPath; }\n            set\n            {\n                // The virtual path for the start page is fixed for now.\n                throw new NotSupportedException();\n            }\n        }\n\n        internal void ExecuteInternal()\n        {\n            // See comments in GetSafeExecuteStartPageThunk().\n            _safeExecuteStartPageThunk(() =>\n            {\n                Output = new StringWriter(CultureInfo.InvariantCulture);\n                Execute();\n                Markup = new HtmlString(Output.ToString());\n            });\n        }\n\n        internal static void ExecuteStartPage(HttpApplication application)\n        {\n            ExecuteStartPage(application,\n                             vpath => MonitorFile(vpath),\n                             VirtualPathFactoryManager.Instance,\n                             WebPageHttpHandler.GetRegisteredExtensions());\n        }\n\n        internal static void ExecuteStartPage(HttpApplication application, Action<string> monitorFile, IVirtualPathFactory virtualPathFactory, IEnumerable<string> supportedExtensions)\n        {\n            try\n            {\n                ExecuteStartPageInternal(application, monitorFile, virtualPathFactory, supportedExtensions);\n            }\n            catch (Exception e)\n            {\n                // Throw it as a HttpException so as to\n                // display the original stack trace information.\n                Exception = e;\n                throw new HttpException(null, e);\n            }\n        }\n\n        internal static void ExecuteStartPageInternal(HttpApplication application, Action<string> monitorFile, IVirtualPathFactory virtualPathFactory, IEnumerable<string> supportedExtensions)\n        {\n            ApplicationStartPage startPage = null;\n\n            foreach (var extension in supportedExtensions)\n            {\n                var vpath = StartPageVirtualPath + extension;\n\n                // We need to monitor regardless of existence because the user could add/remove the\n                // file at any time.\n                monitorFile(vpath);\n                if (!virtualPathFactory.Exists(vpath))\n                {\n                    continue;\n                }\n\n                if (startPage == null)\n                {\n                    startPage = virtualPathFactory.CreateInstance<ApplicationStartPage>(vpath);\n                    startPage.Application = application;\n                    startPage.VirtualPathFactory = virtualPathFactory;\n                    startPage.ExecuteInternal();\n                }\n            }\n        }\n\n        private static Action<Action> GetSafeExecuteStartPageThunk()\n        {\n            // Programmatically detect if this version of System.Web.dll suffers from a bug in\n            // which HttpUtility.HtmlEncode can't be called from Application_Start, and if so\n            // set the current HttpContext to null to work around it.\n            //\n            // See Dev10 #906296 and Dev10 #898600 for more information.\n\n            if (typeof(HttpResponse).GetProperty(\"DisableCustomHttpEncoder\", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly) != null)\n            {\n                // this version suffers from the bug\n                return HttpContextHelper.ExecuteInNullContext;\n            }\n            else\n            {\n                // this version does not suffer from the bug\n                return action => action();\n            }\n        }\n\n        private static void InitiateShutdown(string key, object value, CacheItemRemovedReason reason)\n        {\n            // Only handle case when the dependency has changed.\n            if (reason != CacheItemRemovedReason.DependencyChanged)\n            {\n                return;\n            }\n\n            ThreadPool.QueueUserWorkItem(new WaitCallback(ShutdownCallBack));\n        }\n\n        private static void MonitorFile(string virtualPath)\n        {\n            var virtualPathDependencies = new List<string>();\n            virtualPathDependencies.Add(virtualPath);\n            CacheDependency cacheDependency = HostingEnvironment.VirtualPathProvider.GetCacheDependency(\n                virtualPath, virtualPathDependencies, DateTime.UtcNow);\n            var key = CacheKeyPrefix + virtualPath;\n\n            HttpRuntime.Cache.Insert(key, virtualPath, cacheDependency,\n                                     Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,\n                                     CacheItemPriority.NotRemovable, new CacheItemRemovedCallback(InitiateShutdown));\n        }\n\n        private static void ShutdownCallBack(object state)\n        {\n            InfrastructureHelper.UnloadAppDomain();\n        }\n\n        public override void Write(HelperResult result)\n        {\n            if (result != null)\n            {\n                result.WriteTo(Output);\n            }\n        }\n\n        public override void WriteLiteral(object value)\n        {\n            Output.Write(value);\n        }\n\n        public override void Write(object value)\n        {\n            Output.Write(HttpUtility.HtmlEncode(value));\n        }\n\n        protected internal override TextWriter GetOutputWriter()\n        {\n            return Output;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/AttributeValue.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.WebPages.Instrumentation;\n\nnamespace System.Web.WebPages\n{\n    public class AttributeValue\n    {\n        public AttributeValue(PositionTagged<string> prefix, PositionTagged<object> value, bool literal)\n        {\n            Prefix = prefix;\n            Value = value;\n            Literal = literal;\n        }\n\n        public PositionTagged<string> Prefix { get; private set; }\n        public PositionTagged<object> Value { get; private set; }\n        public bool Literal { get; private set; }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"We are using tuples here to avoid dependencies from Razor to WebPages\")]\n        public static AttributeValue FromTuple(Tuple<Tuple<string, int>, Tuple<object, int>, bool> value)\n        {\n            return new AttributeValue(value.Item1, value.Item2, value.Item3);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"We are using tuples here to avoid dependencies from Razor to WebPages\")]\n        public static AttributeValue FromTuple(Tuple<Tuple<string, int>, Tuple<string, int>, bool> value)\n        {\n            return new AttributeValue(value.Item1, new PositionTagged<object>(value.Item2.Item1, value.Item2.Item2), value.Item3);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"We are using tuples here to avoid dependencies from Razor to WebPages\")]\n        public static implicit operator AttributeValue(Tuple<Tuple<string, int>, Tuple<object, int>, bool> value)\n        {\n            return FromTuple(value);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"We are using tuples here to avoid dependencies from Razor to WebPages\")]\n        public static implicit operator AttributeValue(Tuple<Tuple<string, int>, Tuple<string, int>, bool> value)\n        {\n            return FromTuple(value);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/BrowserHelpers.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Hosting;\n\nnamespace System.Web.WebPages\n{\n    /// <summary>\n    /// Extension methods used to determine what browser a visitor wants to be seen as using.\n    /// </summary>\n    public static class BrowserHelpers\n    {\n        /// <summary>\n        /// Stock IE6 user agent string\n        /// </summary>\n        private const string DesktopUserAgent = \"Mozilla/4.0 (compatible; MSIE 6.1; Windows XP)\";\n\n        /// <summary>\n        /// Stock Windows Mobile 6.0 user agent string\n        /// </summary>\n        private const string MobileUserAgent = \"Mozilla/4.0 (compatible; MSIE 6.0; Windows CE; IEMobile 8.12; MSIEMobile 6.0)\";\n\n        private static readonly object _browserOverrideKey = new object();\n        private static readonly object _userAgentKey = new object();\n\n        /// <summary>\n        /// Clears the set browser for the request. After clearing the browser the overridden browser will be the browser for the request.\n        /// </summary>\n        public static void ClearOverriddenBrowser(this HttpContextBase httpContext)\n        {\n            SetOverriddenBrowser(httpContext, userAgent: null);\n        }\n\n        // Default implementation to generate an HttpBrowserCapabilities object using the current HttpCapabilitiesProvider\n        private static HttpBrowserCapabilitiesBase CreateOverriddenBrowser(string userAgent)\n        {\n            HttpBrowserCapabilities overriddenBrowser = new HttpContext(new UserAgentWorkerRequest(userAgent)).Request.Browser;\n            return new HttpBrowserCapabilitiesWrapper(overriddenBrowser);\n        }\n\n        /// <summary>\n        /// Gets the overridden browser for the request based on the overridden user agent.\n        /// If no overridden user agent is set, returns the browser for the request.\n        /// </summary>\n        public static HttpBrowserCapabilitiesBase GetOverriddenBrowser(this HttpContextBase httpContext)\n        {\n            return GetOverriddenBrowser(httpContext, createBrowser: null);\n        }\n\n        /// <summary>\n        /// Internal GetOverriddenBrowser overload to allow the browser creation function to changed. Defaults to CreateOverridenBrowser if createBrowser is null.\n        /// </summary>\n        internal static HttpBrowserCapabilitiesBase GetOverriddenBrowser(this HttpContextBase httpContext, Func<string, HttpBrowserCapabilitiesBase> createBrowser)\n        {\n            HttpBrowserCapabilitiesBase overriddenBrowser = (HttpBrowserCapabilitiesBase)httpContext.Items[_browserOverrideKey];\n\n            if (overriddenBrowser == null)\n            {\n                string overriddenUserAgent = GetOverriddenUserAgent(httpContext);\n\n                if (!String.Equals(overriddenUserAgent, httpContext.Request.UserAgent, StringComparison.OrdinalIgnoreCase))\n                {\n                    if (createBrowser != null)\n                    {\n                        overriddenBrowser = createBrowser(overriddenUserAgent);\n                    }\n                    else\n                    {\n                        overriddenBrowser = CreateOverriddenBrowser(overriddenUserAgent);\n                    }\n                }\n                else\n                {\n                    overriddenBrowser = httpContext.Request.Browser;\n                }\n\n                httpContext.Items[_browserOverrideKey] = overriddenBrowser;\n            }\n\n            return overriddenBrowser;\n        }\n\n        /// <summary>\n        /// Gets the overridden user agent for the request. If no overridden user agent is set, returns the user agent for the request.\n        /// </summary>\n        public static string GetOverriddenUserAgent(this HttpContextBase httpContext)\n        {\n            return (string)httpContext.Items[_userAgentKey] ??\n                   BrowserOverrideStores.Current.GetOverriddenUserAgent(httpContext) ??\n                   httpContext.Request.UserAgent;\n        }\n\n        /// <summary>\n        /// Gets a string that varies based upon the type of the browser. Can be used to override\n        /// System.Web.HttpApplication.GetVaryByCustomString to differentiate cache keys based on\n        /// the overridden browser.\n        /// </summary>\n        public static string GetVaryByCustomStringForOverriddenBrowser(this HttpContext httpContext)\n        {\n            return GetVaryByCustomStringForOverriddenBrowser(new HttpContextWrapper(httpContext));\n        }\n\n        /// <summary>\n        /// Gets a string that varies based upon the type of the browser. Can be used to override\n        /// System.Web.HttpApplication.GetVaryByCustomString to differentiate cache keys based on\n        /// the overridden browser.\n        /// </summary>\n        public static string GetVaryByCustomStringForOverriddenBrowser(this HttpContextBase httpContext)\n        {\n            return GetOverriddenBrowser(httpContext, createBrowser: null).Type;\n        }\n\n        /// <summary>\n        /// Sets the overridden user agent for the request using a BrowserOverride.\n        /// </summary>\n        public static void SetOverriddenBrowser(this HttpContextBase httpContext, BrowserOverride browserOverride)\n        {\n            string userAgent = null;\n\n            switch (browserOverride)\n            {\n                case BrowserOverride.Desktop:\n                    // bug:262389 override only if the request was not made from a browser or the browser is not of a desktop device\n                    if (httpContext.Request.Browser == null || httpContext.Request.Browser.IsMobileDevice)\n                    {\n                        userAgent = DesktopUserAgent;\n                    }\n                    break;\n                case BrowserOverride.Mobile:\n                    if (httpContext.Request.Browser == null || !httpContext.Request.Browser.IsMobileDevice)\n                    {\n                        userAgent = MobileUserAgent;\n                    }\n                    break;\n            }\n\n            if (userAgent != null)\n            {\n                SetOverriddenBrowser(httpContext, userAgent);\n            }\n            else\n            {\n                ClearOverriddenBrowser(httpContext);\n            }\n        }\n\n        /// <summary>\n        /// Sets the overridden user agent for the request using a string\n        /// </summary>\n        public static void SetOverriddenBrowser(this HttpContextBase httpContext, string userAgent)\n        {\n            // Set the overridden user agent and clear the overridden browser\n            // so that it can be generated from the new overridden user agent.\n            httpContext.Items[_userAgentKey] = userAgent;\n            httpContext.Items[_browserOverrideKey] = null;\n\n            BrowserOverrideStores.Current.SetOverriddenUserAgent(httpContext, userAgent);\n        }\n\n        private sealed class UserAgentWorkerRequest : SimpleWorkerRequest\n        {\n            private readonly string _userAgent;\n\n            public UserAgentWorkerRequest(string userAgent)\n                : base(String.Empty, String.Empty, output: null)\n            {\n                _userAgent = userAgent;\n            }\n\n            public override string GetKnownRequestHeader(int index)\n            {\n                return index == HeaderUserAgent ? _userAgent : null;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/BrowserOverride.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.WebPages\n{\n    /// <summary>\n    /// BrowserOverrides can be used by BrowserHelpers to override the browser for a particular request.\n    /// </summary>\n    public enum BrowserOverride\n    {\n        Desktop,\n        Mobile\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/BrowserOverrideStore.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.WebPages\n{\n    /// <summary>\n    /// The current BrowserOverrideStore is used to get and set the user agent of a request.\n    /// For an example see CookieBasedBrowserOverrideStore.\n    /// </summary>\n    public abstract class BrowserOverrideStore\n    {\n        public abstract string GetOverriddenUserAgent(HttpContextBase httpContext);\n        public abstract void SetOverriddenUserAgent(HttpContextBase httpContext, string userAgent);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/BrowserOverrideStores.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.WebPages\n{\n    public class BrowserOverrideStores\n    {\n        private static BrowserOverrideStores _instance = new BrowserOverrideStores();\n        private BrowserOverrideStore _currentOverrideStore = new CookieBrowserOverrideStore();\n\n        /// <summary>\n        /// The current BrowserOverrideStore\n        /// </summary>\n        public static BrowserOverrideStore Current\n        {\n            get { return _instance.CurrentInternal; }\n            set { _instance.CurrentInternal = value; }\n        }\n\n        internal BrowserOverrideStore CurrentInternal\n        {\n            get { return _currentOverrideStore; }\n            set { _currentOverrideStore = value ?? new RequestBrowserOverrideStore(); }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/BuildManagerWrapper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.IO;\nusing System.Linq;\nusing System.Web.Caching;\nusing System.Web.Compilation;\nusing System.Web.Hosting;\nusing System.Web.Util;\nusing System.Xml.Linq;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.WebPages\n{\n    /// <summary>\n    /// Wraps the caching and instantiation of paths of the BuildManager. \n    /// In case of precompiled non-updateable sites, the only way to verify if a file exists is to call BuildManager.GetObjectFactory. However this method is less performant than\n    /// VirtualPathProvider.FileExists which is used for all other scenarios. In this class, we optimize for the first scenario by storing the results of GetObjectFactory for a \n    /// long duration.\n    /// </summary>\n    internal sealed class BuildManagerWrapper : IVirtualPathFactory\n    {\n        internal static readonly Guid KeyGuid = Guid.NewGuid();\n        private static readonly TimeSpan _objectFactoryCacheDuration = TimeSpan.FromMinutes(1);\n        private readonly IVirtualPathUtility _virtualPathUtility;\n        private readonly Func<VirtualPathProvider> _vppFunc;\n        private readonly bool _isPrecompiled;\n        private readonly FileExistenceCache _vppCache;\n        private IEnumerable<string> _supportedExtensions;\n\n        public BuildManagerWrapper()\n            : this(() => HostingEnvironment.VirtualPathProvider, new VirtualPathUtilityWrapper())\n        {\n        }\n\n        public BuildManagerWrapper(VirtualPathProvider vpp, IVirtualPathUtility virtualPathUtility)\n            : this(() => vpp, virtualPathUtility)\n        {\n            Contract.Assert(vpp != null);\n        }\n\n        public BuildManagerWrapper(Func<VirtualPathProvider> vppFunc, IVirtualPathUtility virtualPathUtility)\n        {\n            Contract.Assert(vppFunc != null);\n            Contract.Assert(virtualPathUtility != null);\n\n            _vppFunc = vppFunc;\n            _virtualPathUtility = virtualPathUtility;\n            _isPrecompiled = IsNonUpdatablePrecompiledApp();\n            if (!_isPrecompiled)\n            {\n                _vppCache = new FileExistenceCache(vppFunc);\n            }\n        }\n\n        public IEnumerable<string> SupportedExtensions\n        {\n            get { return _supportedExtensions ?? WebPageHttpHandler.GetRegisteredExtensions(); }\n            set { _supportedExtensions = value; }\n        }\n\n        /// <summary>\n        /// Determines if a page exists in the website. \n        /// This method switches between a long duration cache or a short duration FileExistenceCache depending on whether the site is precompiled. \n        /// This is an optimization because BuildManager.GetObjectFactory is comparably slower than performing VirtualPathFactory.Exists\n        /// </summary>\n        public bool Exists(string virtualPath)\n        {\n            if (_isPrecompiled)\n            {\n                return ExistsInPrecompiledSite(virtualPath);\n            }\n            return ExistsInVpp(virtualPath);\n        }\n\n        internal bool IsNonUpdatablePrecompiledApp()\n        {\n            VirtualPathProvider vpp = _vppFunc();\n            // VirtualPathProvider currently null in some test scenarios e.g. PreApplicationStartCodeTest.StartTest\n            if (vpp == null)\n            {\n                return false;\n            }\n            return IsNonUpdateablePrecompiledApp(vpp, _virtualPathUtility);\n        }\n\n        /// <summary>\n        /// An app's is precompiled for our purposes if \n        /// (a) it has a PreCompiledApp.config file in the site root, \n        /// (b) The PreCompiledApp.config says that the app is not Updatable.\n        /// </summary>\n        /// <remarks>\n        /// This code is based on System.Web.DynamicData.Misc.IsNonUpdatablePrecompiledAppNoCache (DynamicData)\n        /// </remarks>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\",\n            Justification = \"We want to replicate the behavior of BuildManager which catches all exceptions.\")]\n        internal static bool IsNonUpdateablePrecompiledApp(VirtualPathProvider vpp, IVirtualPathUtility virtualPathUtility)\n        {\n            var virtualPath = virtualPathUtility.ToAbsolute(\"~/PrecompiledApp.config\");\n            if (!vpp.FileExists(virtualPath))\n            {\n                return false;\n            }\n\n            XDocument document;\n            using (Stream stream = vpp.GetFile(virtualPath).Open())\n            {\n                try\n                {\n                    document = XDocument.Load(stream);\n                }\n                catch\n                {\n                    // If we are unable to load the file, ignore it. The BuildManager behaves identically.\n                    return false;\n                }\n            }\n\n            if (document.Root == null || !document.Root.Name.LocalName.Equals(\"precompiledApp\", StringComparison.OrdinalIgnoreCase))\n            {\n                return false;\n            }\n            var updatableAttribute = document.Root.Attribute(\"updatable\");\n            if (updatableAttribute != null)\n            {\n                bool result;\n                return Boolean.TryParse(updatableAttribute.Value, out result) && (result == false);\n            }\n            return false;\n        }\n\n        private bool ExistsInPrecompiledSite(string virtualPath)\n        {\n            var key = GetKeyFromVirtualPath(virtualPath);\n\n            // We assume that the key is unique enough to avoid collisions.\n            var buildManagerResult = (BuildManagerResult)HttpRuntime.Cache.Get(key);\n            if (buildManagerResult == null)\n            {\n                // For precompiled apps, we cache the ObjectFactory and use it in the CreateInstance method. \n                var objectFactory = GetObjectFactory(virtualPath);\n                buildManagerResult = new BuildManagerResult { ObjectFactory = objectFactory, Exists = objectFactory != null };\n                // Cache the result with a sliding expiration for a long duration. \n                HttpRuntime.Cache.Add(key, buildManagerResult, null, Cache.NoAbsoluteExpiration, _objectFactoryCacheDuration, CacheItemPriority.Low, null);\n            }\n            return buildManagerResult.Exists;\n        }\n\n        /// <summary>\n        /// Determines if a site exists in the VirtualPathProvider.\n        /// Results of hits are cached for a very short amount of time in the FileExistenceCache.\n        /// </summary>\n        private bool ExistsInVpp(string virtualPath)\n        {\n            Debug.Assert(_vppCache != null);\n            return _vppCache.FileExists(virtualPath);\n        }\n\n        /// <summary>\n        /// Determines if an ObjectFactory exists for the virtualPath. \n        /// The BuildManager complains if we pass in extensions that aren't registered for compilation. So we ensure that the virtual path is not \n        /// extensionless and that it is one of the extension\n        /// </summary>\n        private IWebObjectFactory GetObjectFactory(string virtualPath)\n        {\n            if (IsPathExtensionSupported(virtualPath))\n            {\n                return BuildManager.GetObjectFactory(virtualPath, throwIfNotFound: false);\n            }\n            return null;\n        }\n\n        public object CreateInstance(string virtualPath)\n        {\n            return CreateInstanceOfType<object>(virtualPath);\n        }\n\n        public T CreateInstanceOfType<T>(string virtualPath) where T : class\n        {\n            if (_isPrecompiled)\n            {\n                var buildManagerResult = (BuildManagerResult)HttpRuntime.Cache.Get(GetKeyFromVirtualPath(virtualPath));\n                // The cache could have evicted our results. In this case, we'll simply fall through to CreateInstanceFromVirtualPath\n                if (buildManagerResult != null)\n                {\n                    Debug.Assert(buildManagerResult.Exists && buildManagerResult.ObjectFactory != null, \"This method must only be called if the file exists.\");\n                    return buildManagerResult.ObjectFactory.CreateInstance() as T;\n                }\n            }\n\n            return (T)BuildManager.CreateInstanceFromVirtualPath(virtualPath, typeof(T));\n        }\n\n        /// <summary>\n        /// Determines if the extension is one of the extensions registered with WebPageHttpHandler. \n        /// </summary>\n        public bool IsPathExtensionSupported(string virtualPath)\n        {\n            string extension = PathUtil.GetExtension(virtualPath);\n            return !String.IsNullOrEmpty(extension)\n                   && SupportedExtensions.Contains(extension.Substring(1), StringComparer.OrdinalIgnoreCase);\n        }\n\n        /// <summary>\n        /// Creates a reasonably unique key for a given virtual path by concatenating it with a Guid.\n        /// </summary>\n        private static string GetKeyFromVirtualPath(string virtualPath)\n        {\n            return KeyGuid.ToString() + \"_\" + virtualPath;\n        }\n\n        private class BuildManagerResult\n        {\n            public bool Exists { get; set; }\n\n            public IWebObjectFactory ObjectFactory { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Common/DisposableAction.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.WebPages\n{\n    internal class DisposableAction : IDisposable\n    {\n        private Action _action;\n        private bool _hasDisposed;\n\n        public DisposableAction(Action action)\n        {\n            if (action == null)\n            {\n                throw new ArgumentNullException(\"action\");\n            }\n            _action = action;\n        }\n\n        public void Dispose()\n        {\n            Dispose(true);\n            GC.SuppressFinalize(this);\n        }\n\n        protected virtual void Dispose(bool disposing)\n        {\n            // If we were disposed by the finalizer it's because the user didn't use a \"using\" block, so don't do anything!\n            if (disposing)\n            {\n                lock (this)\n                {\n                    if (!_hasDisposed)\n                    {\n                        _hasDisposed = true;\n                        _action();\n                    }\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/CookieBrowserOverrideStore.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.WebPages\n{\n    /// <summary>\n    /// The default BrowserOverrideStore. Gets overridden user agent for a request from a cookie.\n    /// Creates a cookie to set the overridden user agent.\n    /// </summary>\n    public class CookieBrowserOverrideStore : BrowserOverrideStore\n    {\n        internal static readonly string BrowserOverrideCookieName = \".ASPXBrowserOverride\";\n        private readonly int _daysToExpire;\n\n        /// <summary>\n        /// Creates the BrowserOverrideStore setting any browser override cookie to expire in 7 days.\n        /// </summary>\n        public CookieBrowserOverrideStore()\n            : this(daysToExpire: 7)\n        {\n        }\n\n        /// <summary>\n        /// Constructor to control the expiration of the browser override cookie.\n        /// </summary>\n        public CookieBrowserOverrideStore(int daysToExpire)\n        {\n            _daysToExpire = daysToExpire;\n        }\n\n        /// <summary>\n        /// Looks for a user agent by searching for the browser override cookie. If no cookie is found\n        /// returns null.\n        /// </summary>\n        public override string GetOverriddenUserAgent(HttpContextBase httpContext)\n        {\n            // Check the response to see if the cookie has been set somewhere in the current request.\n            HttpCookieCollection responseCookies = httpContext.Response.Cookies;\n            // NOTE: Only look for the key (via AllKeys) so a new cookie is not automatically created.\n            string[] cookieNames = responseCookies.AllKeys;\n            // NOTE: use a simple for loop since it performs an order of magnitude faster than .Contains()\n            // and this is a hot path that gets executed for every request.\n            for (int i = 0; i < cookieNames.Length; i++)\n            {\n                // HttpCookieCollection uses OrdinalIgnoreCase comparison for its keys\n                if (String.Equals(cookieNames[i], BrowserOverrideCookieName, StringComparison.OrdinalIgnoreCase))\n                {\n                    HttpCookie currentOverriddenBrowserCookie = responseCookies[BrowserOverrideCookieName];\n\n                    if (currentOverriddenBrowserCookie.Value != null)\n                    {\n                        return currentOverriddenBrowserCookie.Value;\n                    }\n                    else\n                    {\n                        // The cookie has no value. It was cleared on the current request so return null.\n                        return null;\n                    }\n                }\n            }\n\n            // If there was no cookie found in the response check the request.\n            var requestOverrideCookie = httpContext.Request.Cookies[BrowserOverrideCookieName];\n            if (requestOverrideCookie != null)\n            {\n                return requestOverrideCookie.Value;\n            }\n\n            return null;\n        }\n\n        /// <summary>\n        /// Adds a browser override cookie with the set user agent to the response of the current request.\n        /// If the user agent is null the browser override cookie is set to expire, otherwise its expiration is set\n        /// to daysToExpire, specified when CookieBasedOverrideStore is created.\n        /// </summary>\n        public override void SetOverriddenUserAgent(HttpContextBase httpContext, string userAgent)\n        {\n            HttpCookie browserOverrideCookie = new HttpCookie(BrowserOverrideCookieName, HttpUtility.UrlEncode(userAgent));\n\n            if (userAgent == null)\n            {\n                browserOverrideCookie.Expires = DateTime.Now.AddDays(-1);\n            }\n            else\n            {\n                // Only set expiration if the cookie should live longer than the current session\n                if (_daysToExpire > 0)\n                {\n                    browserOverrideCookie.Expires = DateTime.Now.AddDays(_daysToExpire);\n                }\n            }\n\n            httpContext.Response.Cookies.Remove(BrowserOverrideCookieName);\n            httpContext.Response.Cookies.Add(browserOverrideCookie);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/DefaultDisplayMode.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\n\nnamespace System.Web.WebPages\n{\n    /// <summary>\n    /// The <see cref=\"DefaultDisplayMode\"/> can take any suffix and determine if there is a corresponding\n    /// file that exists given a path and request by transforming the path to contain the suffix.\n    /// Add a new DefaultDisplayMode to the Modes collection to handle a new suffix or inherit from\n    /// DefaultDisplayMode to provide custom logic to transform paths with a suffix.\n    /// </summary>\n    public class DefaultDisplayMode : IDisplayMode\n    {\n        private readonly string _suffix;\n\n        public DefaultDisplayMode()\n            : this(DisplayModeProvider.DefaultDisplayModeId)\n        {\n        }\n\n        public DefaultDisplayMode(string suffix)\n        {\n            _suffix = suffix ?? String.Empty;\n        }\n\n        /// <summary>\n        /// When set, the <see cref=\"DefaultDisplayMode\"/> will only be available to return Display Info for a request\n        /// if the ContextCondition evaluates to true.\n        /// </summary>\n        public Func<HttpContextBase, bool> ContextCondition { get; set; }\n\n        public virtual string DisplayModeId\n        {\n            get { return _suffix; }\n        }\n\n        public bool CanHandleContext(HttpContextBase httpContext)\n        {\n            return ContextCondition == null || ContextCondition(httpContext);\n        }\n\n        /// <summary>\n        /// Returns DisplayInfo with the transformed path if it exists.\n        /// </summary>\n        public virtual DisplayInfo GetDisplayInfo(HttpContextBase httpContext, string virtualPath, Func<string, bool> virtualPathExists)\n        {\n            string transformedFilename = TransformPath(virtualPath, _suffix);\n            if (transformedFilename != null && virtualPathExists(transformedFilename))\n            {\n                return new DisplayInfo(transformedFilename, this);\n            }\n\n            return null;\n        }\n\n        /// <summary>\n        /// Transforms paths according to the following rules:\n        /// \\some\\path.blah\\file.txt.zip -> \\some\\path.blah\\file.txt.suffix.zip\n        /// \\some\\path.blah\\file -> \\some\\path.blah\\file.suffix\n        /// </summary>\n        protected virtual string TransformPath(string virtualPath, string suffix)\n        {\n            if (String.IsNullOrEmpty(suffix))\n            {\n                return virtualPath;\n            }\n\n            string extension = Path.GetExtension(virtualPath);\n            return Path.ChangeExtension(virtualPath, suffix + extension);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/DisplayInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.WebPages\n{\n    /// <summary>\n    /// DisplayInfo wraps the resolved file path and IDisplayMode for a request and path.\n    /// The returned IDisplayMode can be used to resolve other page elements for the request.\n    /// </summary>\n    public class DisplayInfo\n    {\n        public DisplayInfo(string filePath, IDisplayMode displayMode)\n        {\n            if (filePath == null)\n            {\n                throw new ArgumentNullException(\"filePath\");\n            }\n\n            if (displayMode == null)\n            {\n                throw new ArgumentNullException(\"displayMode\");\n            }\n\n            FilePath = filePath;\n            DisplayMode = displayMode;\n        }\n\n        /// <summary>\n        /// The Display Mode used to resolve a virtual path.\n        /// </summary>\n        public IDisplayMode DisplayMode { get; private set; }\n\n        /// <summary>\n        /// Resolved path of a file that exists.\n        /// </summary>\n        public string FilePath { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/DisplayModeProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace System.Web.WebPages\n{\n    public sealed class DisplayModeProvider\n    {\n        public static readonly string MobileDisplayModeId = \"Mobile\";\n        public static readonly string DefaultDisplayModeId = String.Empty;\n        private static readonly object _displayModeKey = new object();\n        private static readonly DisplayModeProvider _instance = new DisplayModeProvider();\n\n        private readonly List<IDisplayMode> _displayModes = new List<IDisplayMode>\n        {\n            new DefaultDisplayMode(MobileDisplayModeId)\n            {\n                ContextCondition = context => context.GetOverriddenBrowser().IsMobileDevice\n            },\n            new DefaultDisplayMode()\n        };\n\n        internal DisplayModeProvider()\n        {\n            // The type is a psuedo-singleton. A user would gain nothing from constructing it since we won't use anything but DisplayModeProvider.Instance internally.\n        }\n\n        /// <summary>\n        /// Restricts the search for Display Info to Display Modes either equal to or following the current\n        /// Display Mode in Modes. For example, a page being rendered in the Default Display Mode will not\n        /// display Mobile partial views in order to achieve a consistent look and feel.\n        /// </summary>\n        public bool RequireConsistentDisplayMode { get; set; }\n\n        public static DisplayModeProvider Instance\n        {\n            get { return _instance; }\n        }\n\n        /// <summary>\n        /// All Display Modes that are available to handle a request.\n        /// </summary>\n        public IList<IDisplayMode> Modes\n        {\n            get { return _displayModes; }\n        }\n\n        private int FindFirstAvailableDisplayMode(IDisplayMode currentDisplayMode, bool requireConsistentDisplayMode)\n        {\n            if (requireConsistentDisplayMode && currentDisplayMode != null)\n            {\n                int first = _displayModes.IndexOf(currentDisplayMode);\n                return (first >= 0) ? first : _displayModes.Count;\n            }\n            return 0;\n        }\n\n        /// <summary>\n        /// Returns any IDisplayMode that can handle the given request.\n        /// </summary>\n        public IEnumerable<IDisplayMode> GetAvailableDisplayModesForContext(HttpContextBase httpContext, IDisplayMode currentDisplayMode)\n        {\n            return GetAvailableDisplayModesForContext(httpContext, currentDisplayMode, RequireConsistentDisplayMode);\n        }\n\n        internal IEnumerable<IDisplayMode> GetAvailableDisplayModesForContext(HttpContextBase httpContext, IDisplayMode currentDisplayMode, bool requireConsistentDisplayMode)\n        {\n            int first = FindFirstAvailableDisplayMode(currentDisplayMode, requireConsistentDisplayMode);\n            for (int i = first; i < _displayModes.Count; i++)\n            {\n                IDisplayMode mode = _displayModes[i];\n                if (mode.CanHandleContext(httpContext))\n                {\n                    yield return mode;\n                }\n            }\n        }\n\n        /// <summary>\n        /// Returns DisplayInfo from the first IDisplayMode in Modes that can handle the given request and locate the virtual path.\n        /// If currentDisplayMode is not null and RequireConsistentDisplayMode is set to true the search for DisplayInfo will only\n        /// start with the currentDisplayMode.\n        /// </summary>\n        public DisplayInfo GetDisplayInfoForVirtualPath(string virtualPath, HttpContextBase httpContext, Func<string, bool> virtualPathExists, IDisplayMode currentDisplayMode)\n        {\n            return GetDisplayInfoForVirtualPath(virtualPath, httpContext, virtualPathExists, currentDisplayMode, RequireConsistentDisplayMode);\n        }\n\n        internal DisplayInfo GetDisplayInfoForVirtualPath(string virtualPath, HttpContextBase httpContext, Func<string, bool> virtualPathExists, IDisplayMode currentDisplayMode,\n                                                          bool requireConsistentDisplayMode)\n        {\n            // Performance sensitive\n            int first = FindFirstAvailableDisplayMode(currentDisplayMode, requireConsistentDisplayMode);\n            for (int i = first; i < _displayModes.Count; i++)\n            {\n                IDisplayMode mode = _displayModes[i];\n                if (mode.CanHandleContext(httpContext))\n                {\n                    DisplayInfo info = mode.GetDisplayInfo(httpContext, virtualPath, virtualPathExists);\n                    if (info != null)\n                    {\n                        return info;\n                    }\n                }\n            }\n            return null;\n        }\n\n        internal static IDisplayMode GetDisplayMode(HttpContextBase context)\n        {\n            return context != null ? context.Items[_displayModeKey] as IDisplayMode : null;\n        }\n\n        internal static void SetDisplayMode(HttpContextBase context, IDisplayMode displayMode)\n        {\n            if (context != null)\n            {\n                context.Items[_displayModeKey] = displayMode;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/DynamicHttpApplicationState.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Dynamic;\nusing System.Web.WebPages.Resources;\n\nnamespace System.Web.WebPages\n{\n    internal class DynamicHttpApplicationState : DynamicObject\n    {\n        private HttpApplicationStateBase _state;\n\n        public DynamicHttpApplicationState(HttpApplicationStateBase state)\n        {\n            _state = state;\n        }\n\n        public override bool TryGetMember(GetMemberBinder binder, out object result)\n        {\n            result = _state[binder.Name];\n            // We return true here because HttpApplicationState returns null if the key is not\n            // in the dictionary, so we simply pass on the returned value.\n            return true;\n        }\n\n        public override bool TrySetMember(SetMemberBinder binder, object value)\n        {\n            _state[binder.Name] = value;\n            return true;\n        }\n\n        public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)\n        {\n            if (indexes == null || indexes.Length != 1)\n            {\n                throw new ArgumentException(WebPageResources.DynamicDictionary_InvalidNumberOfIndexes);\n            }\n\n            result = null;\n            string key = indexes[0] as string;\n            if (key != null)\n            {\n                result = _state[key];\n            }\n            else if (indexes[0] is int)\n            {\n                result = _state[(int)indexes[0]];\n            }\n            else\n            {\n                // HttpApplicationState only supports keys of type string and int when getting values, so any attempt \n                // to use other types will result in an error. We throw an exception here to explain to the user what is wrong.\n                // Returning false will instead cause a runtime binder exception which might be confusing to the user.\n                throw new ArgumentException(WebPageResources.DynamicHttpApplicationState_UseOnlyStringOrIntToGet);\n            }\n            return true;\n        }\n\n        public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)\n        {\n            if (indexes == null || indexes.Length != 1)\n            {\n                throw new ArgumentException(WebPageResources.DynamicDictionary_InvalidNumberOfIndexes);\n            }\n\n            string key = indexes[0] as string;\n            if (key != null)\n            {\n                _state[key] = value;\n                return true;\n            }\n            else\n            {\n                // HttpApplicationState only supports keys of type string when setting values, so any attempt \n                // to use other types will result in an error. We throw an exception here to explain to the user what is wrong.\n                // Returning false will instead cause a runtime binder error which might be confusing to the user.\n                throw new ArgumentException(WebPageResources.DynamicHttpApplicationState_UseOnlyStringToSet);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/DynamicPageDataDictionary.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Dynamic;\nusing System.Web.WebPages.Resources;\n\nnamespace System.Web.WebPages\n{\n    /// <summary>\n    /// This is a wrapper around PageDataDictionary[[dynamic]] which allows dynamic\n    /// access (e.g. dict.Foo). Like PageDataDictionary, it returns null if the key is not found, \n    /// instead of throwing an exception.\n    /// This class is intended to be used as DynamicPageDataDictionary[[dynamic]]\n    /// </summary>\n    // This is a generic type because C# does not allow implementing an interface \n    // involving dynamic types (implementing IDictionary<object, dynamic> causes\n    // a compile error \n    // http://blogs.msdn.com/cburrows/archive/2009/02/04/c-dynamic-part-vii.aspx).\n    internal class DynamicPageDataDictionary<TValue> : DynamicObject, IDictionary<object, TValue>\n    {\n        private PageDataDictionary<TValue> _data;\n\n        public DynamicPageDataDictionary(PageDataDictionary<TValue> dictionary)\n        {\n            _data = dictionary;\n        }\n\n        public ICollection<object> Keys\n        {\n            get { return _data.Keys; }\n        }\n\n        public ICollection<TValue> Values\n        {\n            get { return _data.Values; }\n        }\n\n        public int Count\n        {\n            get { return _data.Count; }\n        }\n\n        public bool IsReadOnly\n        {\n            get { return _data.IsReadOnly; }\n        }\n\n        public TValue this[object key]\n        {\n            get { return _data[key]; }\n            set { _data[key] = value; }\n        }\n\n        public override bool TryGetMember(GetMemberBinder binder, out object result)\n        {\n            result = _data[binder.Name];\n            // We return true here because PageDataDictionary returns null if the key is not\n            // in the dictionary, so we simply pass on the returned value.\n            return true;\n        }\n\n        public override bool TrySetMember(SetMemberBinder binder, object value)\n        {\n            // This cast should always succeed assuming TValue is dynamic.\n            TValue v = (TValue)value;\n            _data[binder.Name] = v;\n            return true;\n        }\n\n        public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)\n        {\n            if (indexes == null || indexes.Length != 1)\n            {\n                throw new ArgumentException(WebPageResources.DynamicDictionary_InvalidNumberOfIndexes);\n            }\n\n            result = _data[indexes[0]];\n            // We return true here because PageDataDictionary returns null if the key is not\n            // in the dictionary, so we simply pass on the returned value.\n            return true;\n        }\n\n        public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)\n        {\n            if (indexes == null || indexes.Length != 1)\n            {\n                throw new ArgumentException(WebPageResources.DynamicDictionary_InvalidNumberOfIndexes);\n            }\n\n            // This cast should always succeed assuming TValue is dynamic.\n            _data[indexes[0]] = (TValue)value;\n            return true;\n        }\n\n        public void Add(object key, TValue value)\n        {\n            _data.Add(key, value);\n        }\n\n        public bool ContainsKey(object key)\n        {\n            return _data.ContainsKey(key);\n        }\n\n        public bool Remove(object key)\n        {\n            return _data.Remove(key);\n        }\n\n        public bool TryGetValue(object key, out TValue value)\n        {\n            return _data.TryGetValue(key, out value);\n        }\n\n        public void Add(KeyValuePair<object, TValue> item)\n        {\n            _data.Add(item);\n        }\n\n        public void Clear()\n        {\n            _data.Clear();\n        }\n\n        public bool Contains(KeyValuePair<object, TValue> item)\n        {\n            return _data.Contains(item);\n        }\n\n        public void CopyTo(KeyValuePair<object, TValue>[] array, int arrayIndex)\n        {\n            _data.CopyTo(array, arrayIndex);\n        }\n\n        public bool Remove(KeyValuePair<object, TValue> item)\n        {\n            return _data.Remove(item.Key);\n        }\n\n        public IEnumerator<KeyValuePair<object, TValue>> GetEnumerator()\n        {\n            return _data.GetEnumerator();\n        }\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return _data.GetEnumerator();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/FileExistenceCache.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Threading;\nusing System.Web.Hosting;\n\nnamespace System.Web.WebPages\n{\n    /// <summary>\n    /// This class caches the result of VirtualPathProvider.FileExists for a short\n    /// period of time, and recomputes it if necessary.\n    /// \n    /// The default VPP MapPathBasedVirtualPathProvider caches the result of\n    /// the FileExists call with the appropriate dependencies, so it is less\n    /// expensive on subsequent calls, but it still needs to do MapPath which can \n    /// take quite some time.\n    /// </summary>\n    internal class FileExistenceCache\n    {\n        private const int TicksPerMillisecond = 10000;\n        private readonly Func<VirtualPathProvider> _virtualPathProviderFunc;\n        private readonly Func<string, bool> _virtualPathFileExists;\n        private ConcurrentDictionary<string, bool> _cache;\n        private long _creationTick;\n        private int _ticksBeforeReset;\n\n        // Overload used mainly for testing\n        public FileExistenceCache(VirtualPathProvider virtualPathProvider, int milliSecondsBeforeReset = 1000)\n            : this(() => virtualPathProvider, milliSecondsBeforeReset)\n        {\n            Contract.Assert(virtualPathProvider != null);\n        }\n\n        public FileExistenceCache(Func<VirtualPathProvider> virtualPathProviderFunc, int milliSecondsBeforeReset = 1000)\n        {\n            Contract.Assert(virtualPathProviderFunc != null);\n\n            _virtualPathProviderFunc = virtualPathProviderFunc;\n            _virtualPathFileExists = path => _virtualPathProviderFunc().FileExists(path);\n            _ticksBeforeReset = milliSecondsBeforeReset * TicksPerMillisecond;\n            Reset();\n        }\n\n        // Use the VPP returned by the HostingEnvironment unless a custom vpp is passed in (mainly for testing purposes)\n        public VirtualPathProvider VirtualPathProvider\n        {\n            get { return _virtualPathProviderFunc(); }\n        }\n\n        public int MilliSecondsBeforeReset\n        {\n            get { return _ticksBeforeReset / TicksPerMillisecond; }\n            internal set { _ticksBeforeReset = value * TicksPerMillisecond; }\n        }\n\n        internal IDictionary<string, bool> CacheInternal\n        {\n            get { return _cache; }\n        }\n\n        public bool TimeExceeded\n        {\n            get { return (DateTime.UtcNow.Ticks - Interlocked.Read(ref _creationTick)) > _ticksBeforeReset; }\n        }\n\n        public void Reset()\n        {\n            _cache = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);\n\n            DateTime now = DateTime.UtcNow;\n            long tick = now.Ticks;\n\n            Interlocked.Exchange(ref _creationTick, tick);\n        }\n\n        public bool FileExists(string virtualPath)\n        {\n            if (TimeExceeded)\n            {\n                Reset();\n            }\n\n            return _cache.GetOrAdd(virtualPath, _virtualPathFileExists);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/GlobalSuppressions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n// This file is used by Code Analysis to maintain SuppressMessage \n// attributes that are applied to this project.\n// Project-level suppressions either have no target or are given \n// a specific target and scoped to a namespace, type, member, etc.\n//\n// To add a suppression to this file, right-click the message in the \n// Error List, point to \"Suppress Message(s)\", and click \n// \"In Project Suppression File\".\n// You do not need to add suppressions to this file manually.\n\nusing System.Diagnostics.CodeAnalysis;\n\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"System.Web.WebPages.Html\", Justification = \"The namespace contains types specific to Razor. It allows a way for MVC Razor host to identify and remove the namespace\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"System.Web.Mvc\", Justification = \"This namespace contains TagBuilder and other types forwarded from System.Web.Mvc. The namespace must stay the way it is for type forwarding to work\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"System.Web.WebPages.Instrumentation\", Justification = \"This namespace contains Instrumentation types and represents an isolated set of functionality.\")]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1703:ResourceStringsShouldBeSpelledCorrectly\", MessageId = \"accesscontrolservice\", Scope = \"resource\", Target = \"System.Web.WebPages.Resources.WebPageResources.resources\", Justification = \"This is part of a URL.\")]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1703:ResourceStringsShouldBeSpelledCorrectly\", MessageId = \"identityprovider\", Scope = \"resource\", Target = \"System.Web.WebPages.Resources.WebPageResources.resources\", Justification = \"This is part of a URL.\")]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1703:ResourceStringsShouldBeSpelledCorrectly\", MessageId = \"nameidentifier\", Scope = \"resource\", Target = \"System.Web.WebPages.Resources.WebPageResources.resources\", Justification = \"This is part of a URL.\")]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1703:ResourceStringsShouldBeSpelledCorrectly\", MessageId = \"xmlsoap\", Scope = \"resource\", Target = \"System.Web.WebPages.Resources.WebPageResources.resources\", Justification = \"This is part of a URL.\")]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1724:TypeNamesShouldNotMatchNamespaces\", Scope = \"type\", Target = \"System.Web.Helpers.Validation\")]\n"
  },
  {
    "path": "src/System.Web.WebPages/HelperPage.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.IO;\nusing System.Security.Principal;\nusing System.Web.Caching;\nusing System.Web.WebPages.Html;\nusing System.Web.WebPages.Instrumentation;\n\nnamespace System.Web.WebPages\n{\n    [SuppressMessage(\"Microsoft.Design\", \"CA1053:StaticHolderTypesShouldNotHaveConstructors\", Justification = \"Even though this is essentially a static class, we need helper classes to inherit from it to get their static methods\")]\n    public class HelperPage\n    {\n        private static WebPageContext _pageContext;\n        private static InstrumentationService _instrumentationService = null;\n\n        private static InstrumentationService InstrumentationService\n        {\n            get\n            {\n                if (_instrumentationService == null)\n                {\n                    _instrumentationService = new InstrumentationService();\n                }\n                return _instrumentationService;\n            }\n        }\n\n        public static HttpContextBase Context\n        {\n            get { return new HttpContextWrapper(HttpContext.Current); }\n        }\n\n        public static WebPageRenderingBase CurrentPage\n        {\n            get { return PageContext.Page; }\n        }\n\n        public static dynamic Page\n        {\n            get { return CurrentPage.Page; }\n        }\n\n        public static dynamic Model\n        {\n            get\n            {\n                WebPage currentWebPage = CurrentPage as WebPage;\n                if (currentWebPage == null)\n                {\n                    return null;\n                }\n                return currentWebPage.Model;\n            }\n        }\n\n        public static ModelStateDictionary ModelState\n        {\n            get\n            {\n                WebPage currentWebPage = CurrentPage as WebPage;\n                if (currentWebPage == null)\n                {\n                    return null;\n                }\n                return currentWebPage.ModelState;\n            }\n        }\n\n        public static HtmlHelper Html\n        {\n            get\n            {\n                WebPage currentWebPage = CurrentPage as WebPage;\n                if (currentWebPage == null)\n                {\n                    return null;\n                }\n                return currentWebPage.Html;\n            }\n        }\n\n        public static WebPageContext PageContext\n        {\n            get { return _pageContext ?? WebPageContext.Current; }\n            set { _pageContext = value; }\n        }\n\n        public static HttpApplicationStateBase AppState\n        {\n            get\n            {\n                if (Context != null)\n                {\n                    return Context.Application;\n                }\n                return null;\n            }\n        }\n\n        public static dynamic App\n        {\n            get { return CurrentPage.App; }\n        }\n\n        public static string VirtualPath\n        {\n            get { return PageContext.Page.VirtualPath; }\n        }\n\n        public static Cache Cache\n        {\n            get\n            {\n                if (Context != null)\n                {\n                    return Context.Cache;\n                }\n                return null;\n            }\n        }\n\n        public static HttpRequestBase Request\n        {\n            get\n            {\n                if (Context != null)\n                {\n                    return Context.Request;\n                }\n                return null;\n            }\n        }\n\n        public static HttpResponseBase Response\n        {\n            get\n            {\n                if (Context != null)\n                {\n                    return Context.Response;\n                }\n                return null;\n            }\n        }\n\n        public static HttpServerUtilityBase Server\n        {\n            get\n            {\n                if (Context != null)\n                {\n                    return Context.Server;\n                }\n                return null;\n            }\n        }\n\n        public static HttpSessionStateBase Session\n        {\n            get\n            {\n                if (Context != null)\n                {\n                    return Context.Session;\n                }\n                return null;\n            }\n        }\n\n        public static IList<string> UrlData\n        {\n            get { return CurrentPage.UrlData; }\n        }\n\n        public static IPrincipal User\n        {\n            get { return CurrentPage.User; }\n        }\n\n        public static bool IsPost\n        {\n            get { return CurrentPage.IsPost; }\n        }\n\n        public static bool IsAjax\n        {\n            get { return CurrentPage.IsAjax; }\n        }\n\n        public static IDictionary<object, dynamic> PageData\n        {\n            get { return PageContext.PageData; }\n        }\n\n        protected static string HelperVirtualPath { get; set; }\n\n        public static string Href(string path, params object[] pathParts)\n        {\n            return CurrentPage.Href(path, pathParts);\n        }\n\n        public static void WriteTo(TextWriter writer, object value)\n        {\n            WebPageBase.WriteTo(writer, value);\n        }\n\n        public static void WriteLiteralTo(TextWriter writer, object value)\n        {\n            WebPageBase.WriteLiteralTo(writer, value);\n        }\n\n        public static void WriteTo(TextWriter writer, HelperResult value)\n        {\n            WebPageBase.WriteTo(writer, value);\n        }\n\n        public static void WriteLiteralTo(TextWriter writer, HelperResult value)\n        {\n            WebPageBase.WriteLiteralTo(writer, value);\n        }\n\n        public static void WriteAttributeTo(TextWriter writer, string name, PositionTagged<string> prefix, PositionTagged<string> suffix, params AttributeValue[] values)\n        {\n            CurrentPage.WriteAttributeTo(VirtualPath, writer, name, prefix, suffix, values);\n        }\n\n        public static void BeginContext(string virtualPath, int startPosition, int length, bool isLiteral)\n        {\n            BeginContext(PageContext.Page.GetOutputWriter(), virtualPath, startPosition, length, isLiteral);\n        }\n\n        public static void BeginContext(TextWriter writer, string virtualPath, int startPosition, int length, bool isLiteral)\n        {\n            // Double check that the instrumentation service is active because WriteAttribute always calls this\n            if (InstrumentationService.IsAvailable)\n            {\n                InstrumentationService.BeginContext(Context,\n                                                    virtualPath,\n                                                    writer,\n                                                    startPosition,\n                                                    length,\n                                                    isLiteral);\n            }\n        }\n\n        public static void EndContext(string virtualPath, int startPosition, int length, bool isLiteral)\n        {\n            EndContext(PageContext.Page.GetOutputWriter(), virtualPath, startPosition, length, isLiteral);\n        }\n\n        public static void EndContext(TextWriter writer, string virtualPath, int startPosition, int length, bool isLiteral)\n        {\n            // Double check that the instrumentation service is active because WriteAttribute always calls this\n            if (InstrumentationService.IsAvailable)\n            {\n                InstrumentationService.EndContext(Context,\n                                                  virtualPath,\n                                                  writer,\n                                                  startPosition,\n                                                  length,\n                                                  isLiteral);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/HelperResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.IO;\n\nnamespace System.Web.WebPages\n{\n    public class HelperResult : IHtmlString\n    {\n        private readonly Action<TextWriter> _action;\n\n        public HelperResult(Action<TextWriter> action)\n        {\n            if (action == null)\n            {\n                throw new ArgumentNullException(\"action\");\n            }\n            _action = action;\n        }\n\n        public string ToHtmlString()\n        {\n            return ToString();\n        }\n\n        public override string ToString()\n        {\n            using (var writer = new StringWriter(CultureInfo.InvariantCulture))\n            {\n                _action(writer);\n                return writer.ToString();\n            }\n        }\n\n        public void WriteTo(TextWriter writer)\n        {\n            _action(writer);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Helpers/AntiForgery.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Helpers.AntiXsrf;\nusing System.Web.Helpers.Claims;\nusing System.Web.Mvc;\nusing System.Web.WebPages.Resources;\n\nnamespace System.Web.Helpers\n{\n    /// <summary>\n    /// Provides access to the anti-forgery system, which provides protection against\n    /// Cross-site Request Forgery (XSRF, also called CSRF) attacks.\n    /// </summary>\n    public static class AntiForgery\n    {\n        private static readonly AntiForgeryWorker _worker = CreateSingletonAntiForgeryWorker();\n\n        private static AntiForgeryWorker CreateSingletonAntiForgeryWorker()\n        {\n            // initialize the dependency chain\n\n            IAntiForgeryConfig config = new AntiForgeryConfigWrapper();\n            IAntiForgeryTokenSerializer serializer = new AntiForgeryTokenSerializer(MachineKey45CryptoSystem.Instance);\n            ITokenStore tokenStore = new AntiForgeryTokenStore(config, serializer);\n            IClaimUidExtractor claimUidExtractor = new ClaimUidExtractor(config, ClaimsIdentityConverter.Default);\n            ITokenValidator tokenValidator = new TokenValidator(config, claimUidExtractor);\n\n            return new AntiForgeryWorker(serializer, config, tokenStore, tokenValidator);\n        }\n\n        /// <summary>\n        /// Generates an anti-forgery token for this request. This token can\n        /// be validated by calling the Validate() method.\n        /// </summary>\n        /// <returns>An HTML string corresponding to an &lt;input type=\"hidden\"&gt;\n        /// element. This element should be put inside a &lt;form&gt;.</returns>\n        /// <remarks>\n        /// This method has a side effect: it may set a response cookie.\n        /// </remarks>\n        public static HtmlString GetHtml()\n        {\n            if (HttpContext.Current == null)\n            {\n                throw new ArgumentException(WebPageResources.HttpContextUnavailable);\n            }\n\n            TagBuilder retVal = _worker.GetFormInputElement(new HttpContextWrapper(HttpContext.Current));\n            return retVal.ToHtmlString(TagRenderMode.SelfClosing);\n        }\n\n        /// <summary>\n        /// Generates an anti-forgery token pair (cookie and form token) for this request.\n        /// This method is similar to GetHtml(), but this method gives the caller control\n        /// over how to persist the returned values. To validate these tokens, call the\n        /// appropriate overload of Validate.\n        /// </summary>\n        /// <param name=\"oldCookieToken\">The anti-forgery token - if any - that already existed\n        /// for this request. May be null. The anti-forgery system will try to reuse this cookie\n        /// value when generating a matching form token.</param>\n        /// <param name=\"newCookieToken\">Will contain a new cookie value if the old cookie token\n        /// was null or invalid. If this value is non-null when the method completes, the caller\n        /// must persist this value in the form of a response cookie, and the existing cookie value\n        /// should be discarded. If this value is null when the method completes, the existing\n        /// cookie value was valid and needn't be modified.</param>\n        /// <param name=\"formToken\">The value that should be stored in the &lt;form&gt;. The caller\n        /// should take care not to accidentally swap the cookie and form tokens.</param>\n        /// <remarks>\n        /// Unlike the GetHtml() method, this method has no side effect. The caller\n        /// is responsible for setting the response cookie and injecting the returned\n        /// form token as appropriate.\n        /// </remarks>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1021:AvoidOutParameters\", MessageId = \"1#\", Justification = \"Method is intended for advanced audiences.\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1021:AvoidOutParameters\", MessageId = \"2#\", Justification = \"Method is intended for advanced audiences.\")]\n        [EditorBrowsable(EditorBrowsableState.Advanced)]\n        public static void GetTokens(string oldCookieToken, out string newCookieToken, out string formToken)\n        {\n            if (HttpContext.Current == null)\n            {\n                throw new ArgumentException(WebPageResources.HttpContextUnavailable);\n            }\n\n            _worker.GetTokens(new HttpContextWrapper(HttpContext.Current), oldCookieToken, out newCookieToken, out formToken);\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA2204:Literals should be spelled correctly\", MessageId = \"AdditionalDataProvider\", Justification = \"API name.\")]\n        [SuppressMessage(\"Microsoft.Naming\", \"CA2204:Literals should be spelled correctly\", MessageId = \"AntiForgeryConfig\", Justification = \"API name.\")]\n        [SuppressMessage(\"Microsoft.Naming\", \"CA2204:Literals should be spelled correctly\", MessageId = \"GetHtml\", Justification = \"API name.\")]\n        [SuppressMessage(\"Microsoft.Naming\", \"CA2204:Literals should be spelled correctly\", MessageId = \"httpCookies\", Justification = \"API name.\")]\n        [Obsolete(\"This method is deprecated. Use the GetHtml() method instead. To specify a custom domain for the generated cookie, use the <httpCookies> configuration element. To specify custom data to be embedded within the token, use the static AntiForgeryConfig.AdditionalDataProvider property.\", error: true)]\n        [EditorBrowsable(EditorBrowsableState.Never)]\n        public static HtmlString GetHtml(HttpContextBase httpContext, string salt, string domain, string path)\n        {\n            if (httpContext == null)\n            {\n                throw new ArgumentNullException(\"httpContext\");\n            }\n\n            if (!String.IsNullOrEmpty(salt) || !String.IsNullOrEmpty(domain) || !String.IsNullOrEmpty(path))\n            {\n                throw new NotSupportedException(\"This method is deprecated. Use the GetHtml() method instead. To specify a custom domain for the generated cookie, use the <httpCookies> configuration element. To specify custom data to be embedded within the token, use the static AntiForgeryConfig.AdditionalDataProvider property.\");\n            }\n\n            TagBuilder retVal = _worker.GetFormInputElement(httpContext);\n            return retVal.ToHtmlString(TagRenderMode.SelfClosing);\n        }\n\n        /// <summary>\n        /// Validates an anti-forgery token that was supplied for this request.\n        /// The anti-forgery token may be generated by calling GetHtml().\n        /// </summary>\n        /// <remarks>\n        /// Throws an HttpAntiForgeryException if validation fails.\n        /// </remarks>\n        public static void Validate()\n        {\n            if (HttpContext.Current == null)\n            {\n                throw new ArgumentException(WebPageResources.HttpContextUnavailable);\n            }\n\n            _worker.Validate(new HttpContextWrapper(HttpContext.Current));\n        }\n\n        /// <summary>\n        /// Validates an anti-forgery token pair that was generated by the GetTokens method.\n        /// </summary>\n        /// <param name=\"cookieToken\">The token that was supplied in the request cookie.</param>\n        /// <param name=\"formToken\">The token that was supplied in the request form body.</param>\n        /// <remarks>\n        /// Throws an HttpAntiForgeryException if validation fails.\n        /// </remarks>\n        [EditorBrowsable(EditorBrowsableState.Advanced)]\n        public static void Validate(string cookieToken, string formToken)\n        {\n            if (HttpContext.Current == null)\n            {\n                throw new ArgumentException(WebPageResources.HttpContextUnavailable);\n            }\n\n            _worker.Validate(new HttpContextWrapper(HttpContext.Current), cookieToken, formToken);\n        }\n\n        [Obsolete(\"This method is deprecated. Use the Validate() method instead.\", error: true)]\n        [EditorBrowsable(EditorBrowsableState.Never)]\n        public static void Validate(HttpContextBase httpContext, string salt)\n        {\n            if (httpContext == null)\n            {\n                throw new ArgumentNullException(\"httpContext\");\n            }\n\n            if (!String.IsNullOrEmpty(salt))\n            {\n                throw new NotSupportedException(\"This method is deprecated. Use the Validate() method instead.\");\n            }\n\n            _worker.Validate(httpContext);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Helpers/AntiForgeryConfig.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Text;\n\nnamespace System.Web.Helpers\n{\n    /// <summary>\n    /// Provides programmatic configuration for the anti-forgery token system.\n    /// </summary>\n    public static class AntiForgeryConfig\n    {\n        internal const string AntiForgeryTokenFieldName = \"__RequestVerificationToken\";\n\n        private static string _cookieName;\n        private static string _uniqueClaimTypeIdentifier;\n\n        /// <summary>\n        /// Specifies an object that can provide additional data to put into all\n        /// generated tokens and that can validate additional data in incoming\n        /// tokens.\n        /// </summary>\n        public static IAntiForgeryAdditionalDataProvider AdditionalDataProvider\n        {\n            get;\n            set;\n        }\n\n        /// <summary>\n        /// Specifies the name of the cookie that is used by the anti-forgery\n        /// system.\n        /// </summary>\n        /// <remarks>\n        /// If an explicit name is not provided, the system will automatically\n        /// generate a name.\n        /// </remarks>\n        public static string CookieName\n        {\n            get\n            {\n                if (_cookieName == null)\n                {\n                    _cookieName = GetAntiForgeryCookieName();\n                }\n                return _cookieName;\n            }\n            set\n            {\n                _cookieName = value;\n            }\n        }\n\n        /// <summary>\n        /// Specifies whether SSL is required for the anti-forgery system\n        /// to operate. If this setting is 'true' and a non-SSL request\n        /// comes into the system, all anti-forgery APIs will fail.\n        /// </summary>\n        public static bool RequireSsl\n        {\n            get;\n            set;\n        }\n\n        /// <summary>\n        /// Specifies whether to suppress the generation of X-Frame-Options header\n        /// which is used to prevent ClickJacking. By default, the X-Frame-Options\n        /// header is generated with the value SAMEORIGIN. If this setting is 'true', \n        /// the X-Frame-Options header will not be generated for the response.\n        /// </summary>\n        public static bool SuppressXFrameOptionsHeader\n        {\n            get;\n            set;\n        }\n\n        /// <summary>\n        /// Specifies whether the anti-forgery system should skip checking\n        /// for conditions that might indicate misuse of the system. Please\n        /// use caution when setting this switch, as improper use could open\n        /// security holes in the application.\n        /// </summary>\n        /// <remarks>\n        /// Setting this switch will disable several checks, including:\n        /// - Identity.IsAuthenticated = true without Identity.Name being set\n        /// - special-casing claims-based identities\n        /// </remarks>\n        [EditorBrowsable(EditorBrowsableState.Never)]\n        public static bool SuppressIdentityHeuristicChecks\n        {\n            get;\n            set;\n        }\n\n        /// <summary>\n        /// If claims-based authorization is in use, specifies the claim\n        /// type from the identity that is used to uniquely identify the\n        /// user. If this property is set, all claims-based identities\n        /// <em>must</em> return unique values for this claim type.\n        /// </summary>\n        /// <remarks>\n        /// If claims-based authorization is in use and this property has\n        /// not been set, the anti-forgery system will automatically look\n        /// for claim types \"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier\"\n        /// and \"http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider\".\n        /// </remarks>\n        public static string UniqueClaimTypeIdentifier\n        {\n            get\n            {\n                return _uniqueClaimTypeIdentifier ?? String.Empty;\n            }\n            set\n            {\n                _uniqueClaimTypeIdentifier = value;\n            }\n        }\n\n        private static string GetAntiForgeryCookieName()\n        {\n            return GetAntiForgeryCookieName(HttpRuntime.AppDomainAppVirtualPath);\n        }\n\n        // If the app path is provided, we're generating a cookie name rather than a field name, and the cookie names should\n        // be unique so that a development server cookie and an IIS cookie - both running on localhost - don't stomp on\n        // each other.\n        internal static string GetAntiForgeryCookieName(string appPath)\n        {\n            if (String.IsNullOrEmpty(appPath) || appPath == \"/\")\n            {\n                return AntiForgeryTokenFieldName;\n            }\n            else\n            {\n                return AntiForgeryTokenFieldName + \"_\" + HttpServerUtility.UrlTokenEncode(Encoding.UTF8.GetBytes(appPath));\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Helpers/AntiXsrf/AntiForgeryConfigWrapper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Helpers.AntiXsrf\n{\n    internal sealed class AntiForgeryConfigWrapper : IAntiForgeryConfig\n    {\n        public IAntiForgeryAdditionalDataProvider AdditionalDataProvider\n        {\n            get\n            {\n                return AntiForgeryConfig.AdditionalDataProvider;\n            }\n        }\n\n        public string CookieName\n        {\n            get { return AntiForgeryConfig.CookieName; }\n        }\n\n        public string FormFieldName\n        {\n            get { return AntiForgeryConfig.AntiForgeryTokenFieldName; }\n        }\n\n        public bool RequireSSL\n        {\n            get { return AntiForgeryConfig.RequireSsl; }\n        }\n\n        public bool SuppressIdentityHeuristicChecks\n        {\n            get { return AntiForgeryConfig.SuppressIdentityHeuristicChecks; }\n        }\n\n        public string UniqueClaimTypeIdentifier\n        {\n            get { return AntiForgeryConfig.UniqueClaimTypeIdentifier; }\n        }\n\n        public bool SuppressXFrameOptionsHeader\n        {\n            get { return AntiForgeryConfig.SuppressXFrameOptionsHeader; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Helpers/AntiXsrf/AntiForgeryToken.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Helpers.AntiXsrf\n{\n    // Represents the security token for the Anti-XSRF system.\n    // The token is a random 128-bit value that correlates the session with the request body.\n    internal sealed class AntiForgeryToken\n    {\n        internal const int SecurityTokenBitLength = 128;\n        internal const int ClaimUidBitLength = 256;\n\n        private string _additionalData;\n        private BinaryBlob _securityToken;\n        private string _username;\n\n        public string AdditionalData\n        {\n            get\n            {\n                return _additionalData ?? String.Empty;\n            }\n            set\n            {\n                _additionalData = value;\n            }\n        }\n\n        public BinaryBlob ClaimUid { get; set; }\n\n        public bool IsSessionToken { get; set; }\n\n        public BinaryBlob SecurityToken\n        {\n            get\n            {\n                if (_securityToken == null)\n                {\n                    _securityToken = new BinaryBlob(SecurityTokenBitLength);\n                }\n                return _securityToken;\n            }\n            set\n            {\n                _securityToken = value;\n            }\n        }\n\n        public string Username\n        {\n            get\n            {\n                return _username ?? String.Empty;\n            }\n            set\n            {\n                _username = value;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Helpers/AntiXsrf/AntiForgeryTokenSerializer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.IO;\nusing System.Web.Mvc;\n\nnamespace System.Web.Helpers.AntiXsrf\n{\n    internal sealed class AntiForgeryTokenSerializer : IAntiForgeryTokenSerializer\n    {\n        private const byte TokenVersion = 0x01;\n        private readonly ICryptoSystem _cryptoSystem;\n\n        internal AntiForgeryTokenSerializer(ICryptoSystem cryptoSystem)\n        {\n            _cryptoSystem = cryptoSystem;\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Failures are homogenized; caller handles appropriately.\")]\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2202:Do not dispose objects multiple times\", Justification = \"MemoryStream is safe for multi-dispose.\")]\n        public AntiForgeryToken Deserialize(string serializedToken)\n        {\n            try\n            {\n                using (MemoryStream stream = new MemoryStream(_cryptoSystem.Unprotect(serializedToken)))\n                {\n                    using (BinaryReader reader = new BinaryReader(stream))\n                    {\n                        AntiForgeryToken token = DeserializeImpl(reader);\n                        if (token != null)\n                        {\n                            return token;\n                        }\n                    }\n                }\n            }\n            catch\n            {\n                // swallow all exceptions - homogenize error if something went wrong\n            }\n\n            // if we reached this point, something went wrong deserializing\n            throw HttpAntiForgeryException.CreateDeserializationFailedException();\n        }\n\n        /* The serialized format of the anti-XSRF token is as follows:\n         * Version: 1 byte integer\n         * SecurityToken: 16 byte binary blob\n         * IsSessionToken: 1 byte Boolean\n         * [if IsSessionToken = true]\n         *   +- IsClaimsBased: 1 byte Boolean\n         *   |  [if IsClaimsBased = true]\n         *   |    `- ClaimUid: 32 byte binary blob\n         *   |  [if IsClaimsBased = false]\n         *   |    `- Username: UTF-8 string with 7-bit integer length prefix\n         *   `- AdditionalData: UTF-8 string with 7-bit integer length prefix\n         */\n        private static AntiForgeryToken DeserializeImpl(BinaryReader reader)\n        {\n            // we can only consume tokens of the same serialized version that we generate\n            byte embeddedVersion = reader.ReadByte();\n            if (embeddedVersion != TokenVersion)\n            {\n                return null;\n            }\n\n            AntiForgeryToken deserializedToken = new AntiForgeryToken();\n            byte[] securityTokenBytes = reader.ReadBytes(AntiForgeryToken.SecurityTokenBitLength / 8);\n            deserializedToken.SecurityToken = new BinaryBlob(AntiForgeryToken.SecurityTokenBitLength, securityTokenBytes);\n            deserializedToken.IsSessionToken = reader.ReadBoolean();\n\n            if (!deserializedToken.IsSessionToken)\n            {\n                bool isClaimsBased = reader.ReadBoolean();\n                if (isClaimsBased)\n                {\n                    byte[] claimUidBytes = reader.ReadBytes(AntiForgeryToken.ClaimUidBitLength / 8);\n                    deserializedToken.ClaimUid = new BinaryBlob(AntiForgeryToken.ClaimUidBitLength, claimUidBytes);\n                }\n                else\n                {\n                    deserializedToken.Username = reader.ReadString();\n                }\n\n                deserializedToken.AdditionalData = reader.ReadString();\n            }\n\n            // if there's still unconsumed data in the stream, fail\n            if (reader.BaseStream.ReadByte() != -1)\n            {\n                return null;\n            }\n\n            // success\n            return deserializedToken;\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2202:Do not dispose objects multiple times\", Justification = \"MemoryStream is safe for multi-dispose.\")]\n        public string Serialize(AntiForgeryToken token)\n        {\n            Contract.Assert(token != null);\n\n            using (MemoryStream stream = new MemoryStream())\n            {\n                using (BinaryWriter writer = new BinaryWriter(stream))\n                {\n                    writer.Write(TokenVersion);\n                    writer.Write(token.SecurityToken.GetData());\n                    writer.Write(token.IsSessionToken);\n\n                    if (!token.IsSessionToken)\n                    {\n                        if (token.ClaimUid != null)\n                        {\n                            writer.Write(true /* isClaimsBased */);\n                            writer.Write(token.ClaimUid.GetData());\n                        }\n                        else\n                        {\n                            writer.Write(false /* isClaimsBased */);\n                            writer.Write(token.Username);\n                        }\n\n                        writer.Write(token.AdditionalData);\n                    }\n\n                    writer.Flush();\n                    return _cryptoSystem.Protect(stream.ToArray());\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Helpers/AntiXsrf/AntiForgeryTokenStore.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Web.Mvc;\n\nnamespace System.Web.Helpers.AntiXsrf\n{\n    // Saves anti-XSRF tokens split between HttpRequest.Cookies and HttpRequest.Form\n    internal sealed class AntiForgeryTokenStore : ITokenStore\n    {\n        private readonly IAntiForgeryConfig _config;\n        private readonly IAntiForgeryTokenSerializer _serializer;\n\n        internal AntiForgeryTokenStore(IAntiForgeryConfig config, IAntiForgeryTokenSerializer serializer)\n        {\n            _config = config;\n            _serializer = serializer;\n        }\n\n        public AntiForgeryToken GetCookieToken(HttpContextBase httpContext)\n        {\n            HttpCookie cookie = httpContext.Request.Cookies[_config.CookieName];\n            if (cookie == null || String.IsNullOrEmpty(cookie.Value))\n            {\n                // did not exist\n                return null;\n            }\n\n            return _serializer.Deserialize(cookie.Value);\n        }\n\n        public AntiForgeryToken GetFormToken(HttpContextBase httpContext)\n        {\n            string value = httpContext.Request.Form[_config.FormFieldName];\n            if (String.IsNullOrEmpty(value))\n            {\n                // did not exist\n                return null;\n            }\n\n            return _serializer.Deserialize(value);\n        }\n\n        public void SaveCookieToken(HttpContextBase httpContext, AntiForgeryToken token)\n        {\n            string serializedToken = _serializer.Serialize(token);\n            HttpCookie newCookie = new HttpCookie(_config.CookieName, serializedToken)\n            {\n                HttpOnly = true\n            };\n\n            // Note: don't use \"newCookie.Secure = _config.RequireSSL;\" since the default\n            // value of newCookie.Secure is automatically populated from the <httpCookies>\n            // config element.\n            if (_config.RequireSSL)\n            {\n                newCookie.Secure = true;\n            }\n\n            httpContext.Response.Cookies.Set(newCookie);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Helpers/AntiXsrf/AntiForgeryWorker.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Security.Principal;\nusing System.Web.Mvc;\nusing System.Web.WebPages.Resources;\n\nnamespace System.Web.Helpers.AntiXsrf\n{\n    internal sealed class AntiForgeryWorker\n    {\n        private readonly IAntiForgeryConfig _config;\n        private readonly IAntiForgeryTokenSerializer _serializer;\n        private readonly ITokenStore _tokenStore;\n        private readonly ITokenValidator _validator;\n\n        internal AntiForgeryWorker(IAntiForgeryTokenSerializer serializer, IAntiForgeryConfig config, ITokenStore tokenStore, ITokenValidator validator)\n        {\n            _serializer = serializer;\n            _config = config;\n            _tokenStore = tokenStore;\n            _validator = validator;\n        }\n\n        private void CheckSSLConfig(HttpContextBase httpContext)\n        {\n            if (_config.RequireSSL && !httpContext.Request.IsSecureConnection)\n            {\n                throw new InvalidOperationException(WebPageResources.AntiForgeryWorker_RequireSSL);\n            }\n        }\n\n        private AntiForgeryToken DeserializeToken(string serializedToken)\n        {\n            return (!String.IsNullOrEmpty(serializedToken))\n                ? _serializer.Deserialize(serializedToken)\n                : null;\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Caller will just regenerate token in case of failure.\")]\n        private AntiForgeryToken DeserializeTokenNoThrow(string serializedToken)\n        {\n            try\n            {\n                return DeserializeToken(serializedToken);\n            }\n            catch\n            {\n                // ignore failures since we'll just generate a new token\n                return null;\n            }\n        }\n\n        private static IIdentity ExtractIdentity(HttpContextBase httpContext)\n        {\n            if (httpContext != null)\n            {\n                IPrincipal user = httpContext.User;\n                if (user != null)\n                {\n                    return user.Identity;\n                }\n            }\n            return null;\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Caller will just regenerate token in case of failure.\")]\n        private AntiForgeryToken GetCookieTokenNoThrow(HttpContextBase httpContext)\n        {\n            try\n            {\n                return _tokenStore.GetCookieToken(httpContext);\n            }\n            catch\n            {\n                // ignore failures since we'll just generate a new token\n                return null;\n            }\n        }\n\n        // [ ENTRY POINT ]\n        // Generates an anti-XSRF token pair for the current user. The return\n        // value is the hidden input form element that should be rendered in\n        // the <form>. This method has a side effect: it may set a response\n        // cookie.\n        public TagBuilder GetFormInputElement(HttpContextBase httpContext)\n        {\n            CheckSSLConfig(httpContext);\n\n            AntiForgeryToken oldCookieToken = GetCookieTokenNoThrow(httpContext);\n            AntiForgeryToken newCookieToken, formToken;\n            GetTokens(httpContext, oldCookieToken, out newCookieToken, out formToken);\n\n            if (newCookieToken != null)\n            {\n                // If a new cookie was generated, persist it.\n                _tokenStore.SaveCookieToken(httpContext, newCookieToken);\n            }\n\n            if (!_config.SuppressXFrameOptionsHeader)\n            {\n                // Adding X-Frame-Options header to prevent ClickJacking. See\n                // http://tools.ietf.org/html/draft-ietf-websec-x-frame-options-10\n                // for more information.\n                const string FrameHeaderName = \"X-Frame-Options\";\n                if (httpContext.Response.Headers[FrameHeaderName] == null)\n                {\n                    httpContext.Response.AddHeader(FrameHeaderName, \"SAMEORIGIN\");\n                }\n            }\n\n            // <input type=\"hidden\" name=\"__AntiForgeryToken\" value=\"...\" />\n            TagBuilder retVal = new TagBuilder(\"input\");\n            retVal.Attributes[\"type\"] = \"hidden\";\n            retVal.Attributes[\"name\"] = _config.FormFieldName;\n            retVal.Attributes[\"value\"] = _serializer.Serialize(formToken);\n            return retVal;\n        }\n\n        // [ ENTRY POINT ]\n        // Generates a (cookie, form) serialized token pair for the current user.\n        // The caller may specify an existing cookie value if one exists. If the\n        // 'new cookie value' out param is non-null, the caller *must* persist\n        // the new value to cookie storage since the original value was null or\n        // invalid. This method is side-effect free.\n        public void GetTokens(HttpContextBase httpContext, string serializedOldCookieToken, out string serializedNewCookieToken, out string serializedFormToken)\n        {\n            CheckSSLConfig(httpContext);\n\n            AntiForgeryToken oldCookieToken = DeserializeTokenNoThrow(serializedOldCookieToken);\n            AntiForgeryToken newCookieToken, formToken;\n            GetTokens(httpContext, oldCookieToken, out newCookieToken, out formToken);\n\n            serializedNewCookieToken = Serialize(newCookieToken);\n            serializedFormToken = Serialize(formToken);\n        }\n\n        private void GetTokens(HttpContextBase httpContext, AntiForgeryToken oldCookieToken, out AntiForgeryToken newCookieToken, out AntiForgeryToken formToken)\n        {\n            newCookieToken = null;\n            if (!_validator.IsCookieTokenValid(oldCookieToken))\n            {\n                // Need to make sure we're always operating with a good cookie token.\n                oldCookieToken = newCookieToken = _validator.GenerateCookieToken();\n            }\n\n            Contract.Assert(_validator.IsCookieTokenValid(oldCookieToken));\n            formToken = _validator.GenerateFormToken(httpContext, ExtractIdentity(httpContext), oldCookieToken);\n        }\n\n        private string Serialize(AntiForgeryToken token)\n        {\n            return (token != null) ? _serializer.Serialize(token) : null;\n        }\n\n        // [ ENTRY POINT ]\n        // Given an HttpContext, validates that the anti-XSRF tokens contained\n        // in the cookies & form are OK for this request.\n        public void Validate(HttpContextBase httpContext)\n        {\n            CheckSSLConfig(httpContext);\n\n            // Extract cookie & form tokens\n            AntiForgeryToken cookieToken = _tokenStore.GetCookieToken(httpContext);\n            AntiForgeryToken formToken = _tokenStore.GetFormToken(httpContext);\n\n            // Validate\n            _validator.ValidateTokens(httpContext, ExtractIdentity(httpContext), cookieToken, formToken);\n        }\n\n        // [ ENTRY POINT ]\n        // Given the serialized string representations of a cookie & form token,\n        // validates that the pair is OK for this request.\n        public void Validate(HttpContextBase httpContext, string cookieToken, string formToken)\n        {\n            CheckSSLConfig(httpContext);\n\n            // Extract cookie & form tokens\n            AntiForgeryToken deserializedCookieToken = DeserializeToken(cookieToken);\n            AntiForgeryToken deserializedFormToken = DeserializeToken(formToken);\n\n            // Validate\n            _validator.ValidateTokens(httpContext, ExtractIdentity(httpContext), deserializedCookieToken, deserializedFormToken);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Helpers/AntiXsrf/BinaryBlob.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Security.Cryptography;\nusing System.Text;\n\nnamespace System.Web.Helpers.AntiXsrf\n{\n    // Represents a binary blob (token) that contains random data.\n    // Useful for binary data inside a serialized stream.\n    [DebuggerDisplay(\"{DebuggerString}\")]\n    internal sealed class BinaryBlob : IEquatable<BinaryBlob>\n    {\n        private static readonly RNGCryptoServiceProvider _prng = new RNGCryptoServiceProvider();\n\n        private readonly byte[] _data;\n\n        // Generates a new token using a specified bit length.\n        public BinaryBlob(int bitLength)\n            : this(bitLength, GenerateNewToken(bitLength))\n        {\n        }\n\n        // Generates a token using an existing binary value.\n        public BinaryBlob(int bitLength, byte[] data)\n        {\n            if (bitLength < 32 || bitLength % 8 != 0)\n            {\n                throw new ArgumentOutOfRangeException(\"bitLength\");\n            }\n            if (data == null || data.Length != bitLength / 8)\n            {\n                throw new ArgumentOutOfRangeException(\"data\");\n            }\n\n            _data = data;\n        }\n\n        public int BitLength\n        {\n            get\n            {\n                return checked(_data.Length * 8);\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\", Justification = \"Called by debugger.\")]\n        private string DebuggerString\n        {\n            get\n            {\n                StringBuilder sb = new StringBuilder(\"0x\", 2 + (_data.Length * 2));\n                for (int i = 0; i < _data.Length; i++)\n                {\n                    sb.AppendFormat(CultureInfo.InvariantCulture, \"{0:x2}\", _data[i]);\n                }\n                return sb.ToString();\n            }\n        }\n\n        public override bool Equals(object obj)\n        {\n            return Equals(obj as BinaryBlob);\n        }\n\n        public bool Equals(BinaryBlob other)\n        {\n            if (other == null)\n            {\n                return false;\n            }\n\n            Contract.Assert(this._data.Length == other._data.Length);\n            return CryptoUtil.AreByteArraysEqual(this._data, other._data);\n        }\n\n        public byte[] GetData()\n        {\n            return _data;\n        }\n\n        public override int GetHashCode()\n        {\n            // Since data should contain uniformly-distributed entropy, the\n            // first 32 bits can serve as the hash code.\n            Contract.Assert(_data != null && _data.Length >= (32 / 8));\n            return BitConverter.ToInt32(_data, 0);\n        }\n\n        private static byte[] GenerateNewToken(int bitLength)\n        {\n            byte[] data = new byte[bitLength / 8];\n            _prng.GetBytes(data);\n            return data;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Helpers/AntiXsrf/ClaimUidExtractor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Linq;\nusing System.Security.Principal;\nusing System.Web.Helpers.Claims;\nusing System.Web.WebPages.Resources;\n\nnamespace System.Web.Helpers.AntiXsrf\n{\n    internal sealed class ClaimUidExtractor : IClaimUidExtractor\n    {\n        internal const string NameIdentifierClaimType = \"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier\";\n        internal const string IdentityProviderClaimType = \"http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider\";\n\n        private readonly ClaimsIdentityConverter _claimsIdentityConverter;\n        private readonly IAntiForgeryConfig _config;\n\n        internal ClaimUidExtractor(IAntiForgeryConfig config, ClaimsIdentityConverter claimsIdentityConverter)\n        {\n            _config = config;\n            _claimsIdentityConverter = claimsIdentityConverter;\n        }\n\n        public BinaryBlob ExtractClaimUid(IIdentity identity)\n        {\n            if (identity == null || !identity.IsAuthenticated || _config.SuppressIdentityHeuristicChecks)\n            {\n                // Skip anonymous users\n                // Skip when claims-based checks are disabled\n                return null;\n            }\n\n            ClaimsIdentity claimsIdentity = _claimsIdentityConverter.TryConvert(identity);\n            if (claimsIdentity == null)\n            {\n                // not a claims-based identity\n                return null;\n            }\n\n            string[] uniqueIdentifierParameters = GetUniqueIdentifierParameters(claimsIdentity, _config.UniqueClaimTypeIdentifier);\n            byte[] claimUidBytes = CryptoUtil.ComputeSHA256(uniqueIdentifierParameters);\n            return new BinaryBlob(256, claimUidBytes);\n        }\n\n        internal static string[] GetUniqueIdentifierParameters(ClaimsIdentity claimsIdentity, string uniqueClaimTypeIdentifier)\n        {\n            var claims = claimsIdentity.GetClaims();\n\n            // The application developer might not want to use our default behavior\n            // and instead might want us to use a claim he knows is unique within\n            // the security realm of his application. (Perhaps he has crafted this\n            // claim himself.)\n            if (!String.IsNullOrEmpty(uniqueClaimTypeIdentifier))\n            {\n                Claim matchingClaim = claims.SingleOrDefault(claim => String.Equals(uniqueClaimTypeIdentifier, claim.ClaimType, StringComparison.Ordinal));\n                if (matchingClaim == null || String.IsNullOrEmpty(matchingClaim.Value))\n                {\n                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, WebPageResources.ClaimUidExtractor_ClaimNotPresent, uniqueClaimTypeIdentifier));\n                }\n\n                return new string[]\n                {\n                    uniqueClaimTypeIdentifier,\n                    matchingClaim.Value\n                };\n            }\n\n            // By default, we look for 'nameIdentifier' and 'identityProvider' claims.\n            // For a correctly configured ACS consumer, this tuple will uniquely\n            // identify a user of the application. We assume that a well-behaved\n            // identity provider will never assign the same name identifier to multiple\n            // users within its security realm, and we assume that ACS has been\n            // configured so that each identity provider has a unique 'identityProvider'\n            // claim.\n            Claim nameIdentifierClaim = claims.SingleOrDefault(claim => String.Equals(NameIdentifierClaimType, claim.ClaimType, StringComparison.Ordinal));\n            Claim identityProviderClaim = claims.SingleOrDefault(claim => String.Equals(IdentityProviderClaimType, claim.ClaimType, StringComparison.Ordinal));\n            if (nameIdentifierClaim == null || String.IsNullOrEmpty(nameIdentifierClaim.Value)\n                || identityProviderClaim == null || String.IsNullOrEmpty(identityProviderClaim.Value))\n            {\n                throw new InvalidOperationException(WebPageResources.ClaimUidExtractor_DefaultClaimsNotPresent);\n            }\n\n            return new string[]\n            {\n                NameIdentifierClaimType,\n                nameIdentifierClaim.Value,\n                IdentityProviderClaimType,\n                identityProviderClaim.Value\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Helpers/AntiXsrf/IAntiForgeryConfig.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Helpers.AntiXsrf\n{\n    // Provides configuration information about the anti-forgery system.\n    internal interface IAntiForgeryConfig\n    {\n        // Provides additional data to go into the tokens.\n        IAntiForgeryAdditionalDataProvider AdditionalDataProvider { get; }\n\n        // Name of the cookie to use.\n        string CookieName { get; }\n\n        // Name of the form field to use.\n        string FormFieldName { get; }\n\n        // Whether SSL is mandatory for this request.\n        bool RequireSSL { get; }\n\n        // Skip ClaimsIdentity & related logic.\n        bool SuppressIdentityHeuristicChecks { get; }\n\n        // ClaimType to use for ClaimsIdentity.\n        string UniqueClaimTypeIdentifier { get; }\n\n        // Skip X-FRAME-OPTIONS header.\n        bool SuppressXFrameOptionsHeader { get; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Helpers/AntiXsrf/IAntiForgeryTokenSerializer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Helpers.AntiXsrf\n{\n    // Abstracts out the serialization process for an anti-forgery token\n    internal interface IAntiForgeryTokenSerializer\n    {\n        AntiForgeryToken Deserialize(string serializedToken);\n        string Serialize(AntiForgeryToken token);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Helpers/AntiXsrf/IClaimUidExtractor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Security.Principal;\n\nnamespace System.Web.Helpers.AntiXsrf\n{\n    // Can extract unique identifers for a claims-based identity\n    internal interface IClaimUidExtractor\n    {\n        BinaryBlob ExtractClaimUid(IIdentity identity);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Helpers/AntiXsrf/ICryptoSystem.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Helpers.AntiXsrf\n{\n    // Provides an abstraction around the cryptographic subsystem for the anti-XSRF helpers.\n    internal interface ICryptoSystem\n    {\n        string Protect(byte[] data);\n        byte[] Unprotect(string protectedData);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Helpers/AntiXsrf/ITokenStore.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Helpers.AntiXsrf\n{\n    // Provides an abstraction around how tokens are persisted and retrieved for a request\n    internal interface ITokenStore\n    {\n        AntiForgeryToken GetCookieToken(HttpContextBase httpContext);\n        AntiForgeryToken GetFormToken(HttpContextBase httpContext);\n        void SaveCookieToken(HttpContextBase httpContext, AntiForgeryToken token);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Helpers/AntiXsrf/ITokenValidator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Security.Principal;\n\nnamespace System.Web.Helpers.AntiXsrf\n{\n    // Provides an abstraction around something that can validate anti-XSRF tokens\n    internal interface ITokenValidator\n    {\n        // Generates a new random cookie token.\n        AntiForgeryToken GenerateCookieToken();\n\n        // Given a cookie token, generates a corresponding form token.\n        // The incoming cookie token must be valid.\n        AntiForgeryToken GenerateFormToken(HttpContextBase httpContext, IIdentity identity, AntiForgeryToken cookieToken);\n\n        // Determines whether an existing cookie token is valid (well-formed).\n        // If it is not, the caller must call GenerateCookieToken() before calling GenerateFormToken().\n        bool IsCookieTokenValid(AntiForgeryToken cookieToken);\n\n        // Validates a (cookie, form) token pair.\n        void ValidateTokens(HttpContextBase httpContext, IIdentity identity, AntiForgeryToken cookieToken, AntiForgeryToken formToken);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Helpers/AntiXsrf/MachineKey45CryptoSystem.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing System.Web.Security;\n\nnamespace System.Web.Helpers.AntiXsrf\n{\n    // Interfaces with the System.Web.MachineKey static class using the 4.5 Protect / Unprotect methods.\n    internal sealed class MachineKey45CryptoSystem : ICryptoSystem\n    {\n        private static readonly string[] _purposes = new string[] { \"System.Web.Helpers.AntiXsrf.AntiForgeryToken.v1\" };\n        private static readonly MachineKey45CryptoSystem _singletonInstance = GetSingletonInstance();\n\n        public static MachineKey45CryptoSystem Instance\n        {\n            get\n            {\n                return _singletonInstance;\n            }\n        }\n\n        private static MachineKey45CryptoSystem GetSingletonInstance()\n        {\n            return new MachineKey45CryptoSystem();\n        }\n\n        public string Protect(byte[] data)\n        {\n            byte[] rawProtectedBytes = MachineKey.Protect(data, _purposes);\n            return HttpServerUtility.UrlTokenEncode(rawProtectedBytes);\n        }\n\n        public byte[] Unprotect(string protectedData)\n        {\n            byte[] rawProtectedBytes = HttpServerUtility.UrlTokenDecode(protectedData);\n            return MachineKey.Unprotect(rawProtectedBytes, _purposes);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Helpers/AntiXsrf/TokenValidator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.Globalization;\nusing System.Security.Principal;\nusing System.Web.Mvc;\nusing System.Web.WebPages.Resources;\n\nnamespace System.Web.Helpers.AntiXsrf\n{\n    internal sealed class TokenValidator : ITokenValidator\n    {\n        private readonly IClaimUidExtractor _claimUidExtractor;\n        private readonly IAntiForgeryConfig _config;\n\n        internal TokenValidator(IAntiForgeryConfig config, IClaimUidExtractor claimUidExtractor)\n        {\n            _config = config;\n            _claimUidExtractor = claimUidExtractor;\n        }\n\n        public AntiForgeryToken GenerateCookieToken()\n        {\n            return new AntiForgeryToken()\n            {\n                // SecurityToken will be populated automatically.\n                IsSessionToken = true\n            };\n        }\n\n        public AntiForgeryToken GenerateFormToken(HttpContextBase httpContext, IIdentity identity, AntiForgeryToken cookieToken)\n        {\n            Contract.Assert(IsCookieTokenValid(cookieToken));\n\n            AntiForgeryToken formToken = new AntiForgeryToken()\n            {\n                SecurityToken = cookieToken.SecurityToken,\n                IsSessionToken = false\n            };\n\n            bool requireAuthenticatedUserHeuristicChecks = false;\n            // populate Username and ClaimUid\n            if (identity != null && identity.IsAuthenticated)\n            {\n                if (!_config.SuppressIdentityHeuristicChecks)\n                {\n                    // If the user is authenticated and heuristic checks are not suppressed,\n                    // then Username, ClaimUid, or AdditionalData must be set.\n                    requireAuthenticatedUserHeuristicChecks = true;\n                }\n\n                formToken.ClaimUid = _claimUidExtractor.ExtractClaimUid(identity);\n                if (formToken.ClaimUid == null)\n                {\n                    formToken.Username = identity.Name;\n                }\n            }\n\n            // populate AdditionalData\n            if (_config.AdditionalDataProvider != null)\n            {\n                formToken.AdditionalData = _config.AdditionalDataProvider.GetAdditionalData(httpContext);\n            }\n\n            if (requireAuthenticatedUserHeuristicChecks\n                && String.IsNullOrEmpty(formToken.Username)\n                && formToken.ClaimUid == null\n                && String.IsNullOrEmpty(formToken.AdditionalData))\n            {\n                // Application says user is authenticated, but we have no identifier for the user.\n                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,\n                    WebPageResources.TokenValidator_AuthenticatedUserWithoutUsername, identity.GetType()));\n            }\n\n            return formToken;\n        }\n\n        public bool IsCookieTokenValid(AntiForgeryToken cookieToken)\n        {\n            return (cookieToken != null && cookieToken.IsSessionToken);\n        }\n\n        public void ValidateTokens(HttpContextBase httpContext, IIdentity identity, AntiForgeryToken sessionToken, AntiForgeryToken fieldToken)\n        {\n            // Were the tokens even present at all?\n            if (sessionToken == null)\n            {\n                throw HttpAntiForgeryException.CreateCookieMissingException(_config.CookieName);\n            }\n            if (fieldToken == null)\n            {\n                throw HttpAntiForgeryException.CreateFormFieldMissingException(_config.FormFieldName);\n            }\n\n            // Do the tokens have the correct format?\n            if (!sessionToken.IsSessionToken || fieldToken.IsSessionToken)\n            {\n                throw HttpAntiForgeryException.CreateTokensSwappedException(_config.CookieName, _config.FormFieldName);\n            }\n\n            // Are the security tokens embedded in each incoming token identical?\n            if (!Equals(sessionToken.SecurityToken, fieldToken.SecurityToken))\n            {\n                throw HttpAntiForgeryException.CreateSecurityTokenMismatchException();\n            }\n\n            // Is the incoming token meant for the current user?\n            string currentUsername = String.Empty;\n            BinaryBlob currentClaimUid = null;\n\n            if (identity != null && identity.IsAuthenticated)\n            {\n                currentClaimUid = _claimUidExtractor.ExtractClaimUid(identity);\n                if (currentClaimUid == null)\n                {\n                    currentUsername = identity.Name ?? String.Empty;\n                }\n            }\n\n            // OpenID and other similar authentication schemes use URIs for the username.\n            // These should be treated as case-sensitive.\n            bool useCaseSensitiveUsernameComparison = currentUsername.StartsWith(\"http://\", StringComparison.OrdinalIgnoreCase)\n                || currentUsername.StartsWith(\"https://\", StringComparison.OrdinalIgnoreCase);\n\n            if (!String.Equals(fieldToken.Username, currentUsername, (useCaseSensitiveUsernameComparison) ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase))\n            {\n                throw HttpAntiForgeryException.CreateUsernameMismatchException(fieldToken.Username, currentUsername);\n            }\n            if (!Equals(fieldToken.ClaimUid, currentClaimUid))\n            {\n                throw HttpAntiForgeryException.CreateClaimUidMismatchException();\n            }\n\n            // Is the AdditionalData valid?\n            if (_config.AdditionalDataProvider != null && !_config.AdditionalDataProvider.ValidateAdditionalData(httpContext, fieldToken.AdditionalData))\n            {\n                throw HttpAntiForgeryException.CreateAdditionalDataCheckFailedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Helpers/Claims/Claim.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\n\nnamespace System.Web.Helpers.Claims\n{\n    // Represents a Claim; serves as an abstraction around the WIF SDK and 4.5 Claim types since\n    // we can't compile directly against them.\n    internal sealed class Claim\n    {\n        public Claim(string claimType, string value)\n        {\n            ClaimType = claimType;\n            Value = value;\n        }\n\n        public string ClaimType { get; private set; }\n\n        public string Value { get; private set; }\n\n        // Creates a Claim from a TClaim object (duck typing).\n        //\n        // The TClaim must have the following shape:\n        // class TClaim {\n        //   string ClaimType { get; } // or just 'Type'\n        //   string Value { get; }\n        // }\n        internal static Claim Create<TClaim>(TClaim claim)\n        {\n            return ClaimFactory<TClaim>.Create(claim);\n        }\n\n        private static class ClaimFactory<TClaim>\n        {\n            private static readonly Func<TClaim, string> _claimTypeGetter = CreateClaimTypeGetter();\n            private static readonly Func<TClaim, string> _valueGetter = CreateValueGetter();\n\n            public static Claim Create(TClaim claim)\n            {\n                return new Claim(_claimTypeGetter(claim), _valueGetter(claim));\n            }\n\n            private static Func<TClaim, string> CreateClaimTypeGetter()\n            {\n                // the claim type might go by one of two different property names\n                return CreateGeneralPropertyGetter(\"ClaimType\") ?? CreateGeneralPropertyGetter(\"Type\");\n            }\n\n            private static Func<TClaim, string> CreateGeneralPropertyGetter(string propertyName)\n            {\n                PropertyInfo propInfo = typeof(TClaim).GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance, null, typeof(string), Type.EmptyTypes, null);\n                if (propInfo == null)\n                {\n                    return null;\n                }\n\n                MethodInfo propGetter = propInfo.GetGetMethod();\n\n                // For improved perf, instance methods can be treated as static methods by leaving\n                // the 'this' parameter unbound. Virtual dispatch for the property getter will\n                // still take place as expected.\n                return (Func<TClaim, string>)Delegate.CreateDelegate(typeof(Func<TClaim, string>), propGetter);\n            }\n\n            private static Func<TClaim, string> CreateValueGetter()\n            {\n                return CreateGeneralPropertyGetter(\"Value\");\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Helpers/Claims/ClaimsIdentity.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing System.Security.Principal;\n\nnamespace System.Web.Helpers.Claims\n{\n    // Represents a ClaimsIdentity; serves as an abstraction around the WIF SDK and 4.5\n    // ClaimIdentity types since we can't compile directly against them.\n    internal abstract class ClaimsIdentity\n    {\n        public abstract IEnumerable<Claim> GetClaims();\n\n        // Attempts to convert an IIdentity into a ClaimsIdentity;\n        // returns null if the conversion fails (duck typing).\n        //\n        // The TClaimsIdentity must have the following shape:\n        // class TClaimsIdentity : IIdentity {\n        //   TClaimsCollection Claims { get; }\n        // }\n        // where TClaimsCollection is assignable to IEnumerable<TClaim>,\n        // and where TClaim is valid for Claim.Create<TClaim>.\n        internal static ClaimsIdentity TryConvert<TClaimsIdentity, TClaim>(IIdentity identity)\n            where TClaimsIdentity : class, IIdentity\n        {\n            TClaimsIdentity castClaimsIdentity = identity as TClaimsIdentity;\n            return (castClaimsIdentity != null)\n                ? new ClaimsIdentityImpl<TClaimsIdentity, TClaim>(castClaimsIdentity)\n                : null;\n        }\n\n        private sealed class ClaimsIdentityImpl<TClaimsIdentity, TClaim> : ClaimsIdentity\n            where TClaimsIdentity : class, IIdentity\n        {\n            private static readonly Func<TClaimsIdentity, IEnumerable<TClaim>> _claimsGetter = CreateClaimsGetter();\n\n            private readonly TClaimsIdentity _claimsIdentity;\n\n            public ClaimsIdentityImpl(TClaimsIdentity claimsIdentity)\n            {\n                _claimsIdentity = claimsIdentity;\n            }\n\n            private static Func<TClaimsIdentity, IEnumerable<TClaim>> CreateClaimsGetter()\n            {\n                PropertyInfo propInfo = typeof(TClaimsIdentity).GetProperty(\"Claims\", BindingFlags.Public | BindingFlags.Instance);\n                MethodInfo propGetter = propInfo.GetGetMethod();\n\n                // For improved perf, instance methods can be treated as static methods by leaving\n                // the 'this' parameter unbound. Virtual dispatch for the property getter will\n                // still take place as expected.\n                return (Func<TClaimsIdentity, IEnumerable<TClaim>>)Delegate.CreateDelegate(typeof(Func<TClaimsIdentity, IEnumerable<TClaim>>), propGetter);\n            }\n\n            public override IEnumerable<Claim> GetClaims()\n            {\n                return _claimsGetter(_claimsIdentity).Select(Claim.Create);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Helpers/Claims/ClaimsIdentityConverter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Security.Principal;\nusing System.Web.Security;\n\nnamespace System.Web.Helpers.Claims\n{\n    // Can convert IIdentity instances into our ClaimsIdentity wrapper.\n    internal sealed class ClaimsIdentityConverter\n    {\n        private static readonly MethodInfo _claimsIdentityTryConvertOpenMethod = typeof(ClaimsIdentity).GetMethod(\"TryConvert\", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);\n        private static readonly ClaimsIdentityConverter _default = new ClaimsIdentityConverter(GetDefaultConverters());\n\n        private readonly Func<IIdentity, ClaimsIdentity>[] _converters;\n\n        // Internal for unit testing; nobody should ever be calling this in production.\n        internal ClaimsIdentityConverter(Func<IIdentity, ClaimsIdentity>[] converters)\n        {\n            _converters = converters;\n        }\n\n        // By default, we understand the ClaimsIdentity / Claim types included\n        // with the WIF SDK and FX 4.5.\n        public static ClaimsIdentityConverter Default\n        {\n            get\n            {\n                return _default;\n            }\n        }\n\n        private static bool IsGrandfatheredIdentityType(IIdentity claimsIdentity)\n        {\n            // These specific types might also be claims-based types depending on\n            // the version of the framework we're running, but we don't want to\n            // treat them as claims-based types since we know their Name property\n            // will suffice as a unique identifier within the security realm of the\n            // current application.\n            return claimsIdentity is FormsIdentity\n                || claimsIdentity is WindowsIdentity\n                || claimsIdentity is GenericIdentity;\n        }\n\n        public ClaimsIdentity TryConvert(IIdentity identity)\n        {\n            if (IsGrandfatheredIdentityType(identity))\n            {\n                return null;\n            }\n\n            // loop through all registered converters until one matches\n            for (int i = 0; i < _converters.Length; i++)\n            {\n                ClaimsIdentity retVal = _converters[i](identity);\n                if (retVal != null)\n                {\n                    return retVal;\n                }\n            }\n\n            return null;\n        }\n\n        private static void AddToList(IList<Func<IIdentity, ClaimsIdentity>> converters, Type claimsIdentityType, Type claimType)\n        {\n            if (claimsIdentityType != null && claimType != null)\n            {\n                MethodInfo tryConvertClosedMethod = _claimsIdentityTryConvertOpenMethod.MakeGenericMethod(claimsIdentityType, claimType);\n                Func<IIdentity, ClaimsIdentity> converter = (Func<IIdentity, ClaimsIdentity>)Delegate.CreateDelegate(typeof(Func<IIdentity, ClaimsIdentity>), tryConvertClosedMethod);\n                converters.Add(converter);\n            }\n        }\n\n        private static Func<IIdentity, ClaimsIdentity>[] GetDefaultConverters()\n        {\n            List<Func<IIdentity, ClaimsIdentity>> converters = new List<Func<IIdentity, ClaimsIdentity>>();\n\n            // WIF SDK is only available in full trust scenarios\n            if (AppDomain.CurrentDomain.IsHomogenous && AppDomain.CurrentDomain.IsFullyTrusted)\n            {\n                Type claimsIdentityType = Type.GetType(\"Microsoft.IdentityModel.Claims.IClaimsIdentity, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\");\n                Type claimType = Type.GetType(\"Microsoft.IdentityModel.Claims.Claim, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\");\n                AddToList(converters, claimsIdentityType, claimType);\n            }\n\n            // 4.5 ClaimsIdentity type\n            {\n                Module mscorlibModule = typeof(object).Module;\n                Type claimsIdentityType = mscorlibModule.GetType(\"System.Security.Claims.ClaimsIdentity\");\n                Type claimType = mscorlibModule.GetType(\"System.Security.Claims.Claim\");\n                AddToList(converters, claimsIdentityType, claimType);\n            }\n\n            return converters.ToArray();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Helpers/CryptoUtil.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.IO;\nusing System.Security.Cryptography;\n\nnamespace System.Web.Helpers\n{\n    internal static class CryptoUtil\n    {\n        // This method is specially written to take the same amount of time\n        // regardless of where 'a' and 'b' differ. Please do not optimize it.\n        public static bool AreByteArraysEqual(byte[] a, byte[] b)\n        {\n            if (a == null || b == null || a.Length != b.Length)\n            {\n                return false;\n            }\n\n            bool areEqual = true;\n            for (int i = 0; i < a.Length; i++)\n            {\n                areEqual &= (a[i] == b[i]);\n            }\n            return areEqual;\n        }\n\n        // Computes a SHA256 hash over all of the input parameters.\n        // Each parameter is UTF8 encoded and preceded by a 7-bit encoded\n        // integer describing the encoded byte length of the string.\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2202:Do not dispose objects multiple times\", Justification = \"MemoryStream is resilient to double-Dispose\")]\n        public static byte[] ComputeSHA256(IList<string> parameters)\n        {\n            using (MemoryStream ms = new MemoryStream())\n            {\n                using (BinaryWriter bw = new BinaryWriter(ms))\n                {\n                    foreach (string parameter in parameters)\n                    {\n                        bw.Write(parameter); // also writes the length as a prefix; unambiguous\n                    }\n                    bw.Flush();\n\n                    using (SHA256Cng sha256 = new SHA256Cng())\n                    {\n                        byte[] retVal = sha256.ComputeHash(ms.GetBuffer(), 0, checked((int)ms.Length));\n                        return retVal;\n                    }\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Helpers/IAntiForgeryAdditionalDataProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Helpers\n{\n    /// <summary>\n    /// Allows providing or validating additional custom data for anti-forgery tokens.\n    /// For example, the developer could use this to supply a nonce when the token is\n    /// generated, then he could validate the nonce when the token is validated.\n    /// </summary>\n    /// <remarks>\n    /// The anti-forgery system already embeds the client's username within the\n    /// generated tokens. This interface provides and consumes <em>supplemental</em>\n    /// data. If an incoming anti-forgery token contains supplemental data but no\n    /// additional data provider is configured, the supplemental data will not be\n    /// validated.\n    /// </remarks>\n    public interface IAntiForgeryAdditionalDataProvider\n    {\n        /// <summary>\n        /// Provides additional data to be stored for the anti-forgery tokens generated\n        /// during this request.\n        /// </summary>\n        /// <param name=\"context\">Information about the current request.</param>\n        /// <returns>Supplemental data to embed within the anti-forgery token.</returns>\n        string GetAdditionalData(HttpContextBase context);\n\n        /// <summary>\n        /// Validates additional data that was embedded inside an incoming anti-forgery\n        /// token.\n        /// </summary>\n        /// <param name=\"context\">Information about the current request.</param>\n        /// <param name=\"additionalData\">Supplemental data that was embedded within the token.</param>\n        /// <returns>True if the data is valid; false if the data is invalid.</returns>\n        bool ValidateAdditionalData(HttpContextBase context, string additionalData);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Helpers/UnvalidatedRequestValues.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\n\nnamespace System.Web.Helpers\n{\n    // Provides access to Request.* collections, except that these have not gone through request validation.\n    [Obsolete(\"Use System.Web.HttpRequest.Unvalidated instead.\")]\n    public sealed class UnvalidatedRequestValues\n    {\n        private readonly HttpRequestBase _request;\n\n        internal UnvalidatedRequestValues(HttpRequestBase request)\n        {\n            _request = request;\n        }\n\n        public NameValueCollection Form\n        {\n            get { return _request.Unvalidated.Form; }\n        }\n\n        public NameValueCollection QueryString\n        {\n            get { return _request.Unvalidated.QueryString; }\n        }\n\n        public string this[string key]\n        {\n            get\n            {\n                return _request.Unvalidated[key];\n            }\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.WebPages/Helpers/Validation.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.Helpers\n{\n    [Obsolete(\"Use System.Web.HttpRequest.Unvalidated instead.\")]\n    public static class Validation\n    {\n        [SuppressMessage(\"Microsoft.Usage\", \"CA1801:ReviewUnusedParameters\", MessageId = \"request\",\n            Justification = \"Parameter is only meant for making this show up as 'Request.Unvalidated()', which closely resembles FX45 syntax.\")]\n#pragma warning disable 0618 // Obsolete System.Web.Helpers.UnvalidatedRequestValues\n        public static UnvalidatedRequestValues Unvalidated(this HttpRequestBase request)\n#pragma warning restore\n        {\n            return Unvalidated((HttpRequest)null);\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA1801:ReviewUnusedParameters\", MessageId = \"request\",\n            Justification = \"Parameter is only meant for making this show up as 'Request.Unvalidated()', which closely resembles FX45 syntax.\")]\n#pragma warning disable 0618 // Obsolete System.Web.Helpers.UnvalidatedRequestValues\n        public static UnvalidatedRequestValues Unvalidated(this HttpRequest request)\n#pragma warning restore\n        {\n            // We don't actually need the request object; we'll get HttpContext.Current directly.\n            HttpContext context = HttpContext.Current;\n#pragma warning disable 0618 // Obsolete System.Web.Helpers.UnvalidatedRequestValues\n            return new UnvalidatedRequestValues(new HttpRequestWrapper(context.Request));\n#pragma warning restore\n        }\n\n        public static string Unvalidated(this HttpRequestBase request, string key)\n        {\n            return Unvalidated(request)[key];\n        }\n\n        public static string Unvalidated(this HttpRequest request, string key)\n        {\n            return Unvalidated(request)[key];\n        }\n    }\n}"
  },
  {
    "path": "src/System.Web.WebPages/Html/HtmlHelper.Checkbox.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Mvc;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.WebPages.Html\n{\n    public partial class HtmlHelper\n    {\n        public IHtmlString CheckBox(string name)\n        {\n            return CheckBox(name, htmlAttributes: (IDictionary<string, object>)null);\n        }\n\n        public IHtmlString CheckBox(string name, object htmlAttributes)\n        {\n            return CheckBox(name, AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public IHtmlString CheckBox(string name, IDictionary<string, object> htmlAttributes)\n        {\n            if (String.IsNullOrEmpty(name))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"name\");\n            }\n\n            return BuildCheckBox(name, null, htmlAttributes);\n        }\n\n        public IHtmlString CheckBox(string name, bool isChecked)\n        {\n            return CheckBox(name, isChecked, (IDictionary<string, object>)null);\n        }\n\n        public IHtmlString CheckBox(string name, bool isChecked, object htmlAttributes)\n        {\n            return CheckBox(name, isChecked, AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public IHtmlString CheckBox(string name, bool isChecked, IDictionary<string, object> htmlAttributes)\n        {\n            if (String.IsNullOrEmpty(name))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"name\");\n            }\n            return BuildCheckBox(name, isChecked, htmlAttributes);\n        }\n\n        private IHtmlString BuildCheckBox(string name, bool? isChecked, IDictionary<string, object> attributes)\n        {\n            TagBuilder builder = new TagBuilder(\"input\");\n            builder.MergeAttribute(\"type\", \"checkbox\", replaceExisting: true);\n            builder.GenerateId(name);\n            builder.MergeAttributes(attributes, replaceExisting: true);\n            builder.MergeAttribute(\"name\", name, replaceExisting: true);\n\n            if (UnobtrusiveJavaScriptEnabled)\n            {\n                var validationAttributes = _validationHelper.GetUnobtrusiveValidationAttributes(name);\n                builder.MergeAttributes(validationAttributes, replaceExisting: false);\n            }\n\n            var model = ModelState[name];\n            if (model != null && model.Value != null)\n            {\n                bool modelValue = (bool)ConvertTo(model.Value, typeof(bool));\n                isChecked = isChecked ?? modelValue;\n            }\n            if (isChecked.HasValue)\n            {\n                if (isChecked.Value == true)\n                {\n                    builder.MergeAttribute(\"checked\", \"checked\", replaceExisting: true);\n                }\n                else\n                {\n                    builder.Attributes.Remove(\"checked\");\n                }\n            }\n\n            AddErrorClass(builder, name);\n            return builder.ToHtmlString(TagRenderMode.SelfClosing);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Html/HtmlHelper.Input.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Data.Linq;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Mvc;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.WebPages.Html\n{\n    public partial class HtmlHelper\n    {\n        private enum InputType\n        {\n            Text,\n            Password,\n            Hidden\n        }\n\n        public IHtmlString TextBox(string name)\n        {\n            if (String.IsNullOrEmpty(name))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"name\");\n            }\n\n            return BuildInputField(name, InputType.Text, value: null, isExplicitValue: false,\n                                   attributes: (IDictionary<string, object>)null);\n        }\n\n        public IHtmlString TextBox(string name, object value)\n        {\n            return TextBox(name, value, htmlAttributes: (IDictionary<string, object>)null);\n        }\n\n        public IHtmlString TextBox(string name, object value, object htmlAttributes)\n        {\n            return TextBox(name, value, AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public IHtmlString TextBox(string name, object value, IDictionary<string, object> htmlAttributes)\n        {\n            if (String.IsNullOrEmpty(name))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"name\");\n            }\n\n            return BuildInputField(name, InputType.Text, value, isExplicitValue: true, attributes: htmlAttributes);\n        }\n\n        public IHtmlString Hidden(string name)\n        {\n            if (String.IsNullOrEmpty(name))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"name\");\n            }\n\n            return BuildInputField(name, InputType.Hidden, value: null, isExplicitValue: false,\n                                   attributes: (IDictionary<string, object>)null);\n        }\n\n        public IHtmlString Hidden(string name, object value)\n        {\n            return Hidden(name, value, htmlAttributes: (IDictionary<string, object>)null);\n        }\n\n        public IHtmlString Hidden(string name, object value, object htmlAttributes)\n        {\n            return Hidden(name, value, AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public IHtmlString Hidden(string name, object value, IDictionary<string, object> htmlAttributes)\n        {\n            if (String.IsNullOrEmpty(name))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"name\");\n            }\n\n            return BuildInputField(name, InputType.Hidden, GetHiddenFieldValue(value), isExplicitValue: true,\n                                   attributes: htmlAttributes);\n        }\n\n        private static object GetHiddenFieldValue(object value)\n        {\n            Binary binaryValue = value as Binary;\n            if (binaryValue != null)\n            {\n                value = binaryValue.ToArray();\n            }\n\n            byte[] byteArrayValue = value as byte[];\n            if (byteArrayValue != null)\n            {\n                value = Convert.ToBase64String(byteArrayValue);\n            }\n\n            return value;\n        }\n\n        public IHtmlString Password(string name)\n        {\n            if (String.IsNullOrEmpty(name))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"name\");\n            }\n\n            return BuildInputField(name, InputType.Password, null, isExplicitValue: false,\n                                   attributes: (IDictionary<string, object>)null);\n        }\n\n        public IHtmlString Password(string name, object value)\n        {\n            return Password(name, value, htmlAttributes: (IDictionary<string, object>)null);\n        }\n\n        public IHtmlString Password(string name, object value, object htmlAttributes)\n        {\n            return Password(name, value, AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public IHtmlString Password(string name, object value, IDictionary<string, object> htmlAttributes)\n        {\n            if (String.IsNullOrEmpty(name))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"name\");\n            }\n\n            return BuildInputField(name, InputType.Password, value, isExplicitValue: true, attributes: htmlAttributes);\n        }\n\n        private IHtmlString BuildInputField(string name, InputType type, object value, bool isExplicitValue,\n                                            IDictionary<string, object> attributes)\n        {\n            TagBuilder tagBuilder = new TagBuilder(\"input\");\n            // Implicit parameters\n            tagBuilder.MergeAttribute(\"type\", GetInputTypeString(type));\n            tagBuilder.GenerateId(name);\n\n            // Overwrite implicit\n            tagBuilder.MergeAttributes(attributes, replaceExisting: true);\n\n            if (UnobtrusiveJavaScriptEnabled)\n            {\n                // Add validation attributes\n                var validationAttributes = _validationHelper.GetUnobtrusiveValidationAttributes(name);\n                tagBuilder.MergeAttributes(validationAttributes, replaceExisting: false);\n            }\n\n            // Function arguments\n            tagBuilder.MergeAttribute(\"name\", name, replaceExisting: true);\n            var modelState = ModelState[name];\n            if ((type != InputType.Password) && modelState != null)\n            {\n                // Don't use model values for passwords\n                value = value ?? modelState.Value ?? String.Empty;\n            }\n\n            if ((type != InputType.Password) || ((type == InputType.Password) && (value != null)))\n            {\n                // Review: Do we really need to be this pedantic about sticking to mvc?\n                tagBuilder.MergeAttribute(\"value\", (string)ConvertTo(value, typeof(string)), replaceExisting: isExplicitValue);\n            }\n\n            AddErrorClass(tagBuilder, name);\n            return tagBuilder.ToHtmlString(TagRenderMode.SelfClosing);\n        }\n\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1308:NormalizeStringsToUppercase\", Justification = \"Input types are specified in lower case\")]\n        private static string GetInputTypeString(InputType inputType)\n        {\n            if (!Enum.IsDefined(typeof(InputType), inputType))\n            {\n                inputType = InputType.Text;\n            }\n            return inputType.ToString().ToLowerInvariant();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Html/HtmlHelper.Internal.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.Web.Mvc;\nusing System.Web.WebPages.Resources;\n\nnamespace System.Web.WebPages.Html\n{\n    public partial class HtmlHelper\n    {\n        private void AddErrorClass(TagBuilder tagBuilder, string name)\n        {\n            if (!ModelState.IsValidField(name))\n            {\n                tagBuilder.AddCssClass(ValidationInputCssClassName);\n            }\n        }\n\n        private static object ConvertTo(object value, Type type)\n        {\n            Debug.Assert(type != null);\n            return UnwrapPossibleArrayType(value, type, CultureInfo.InvariantCulture);\n        }\n\n        private static object UnwrapPossibleArrayType(object value, Type destinationType, CultureInfo culture)\n        {\n            if (value == null || destinationType.IsInstanceOfType(value))\n            {\n                return value;\n            }\n\n            // array conversion results in four cases, as below\n            Array valueAsArray = value as Array;\n            if (destinationType.IsArray)\n            {\n                Type destinationElementType = destinationType.GetElementType();\n                if (valueAsArray != null)\n                {\n                    // case 1: both destination + source type are arrays, so convert each element\n                    IList converted = Array.CreateInstance(destinationElementType, valueAsArray.Length);\n                    for (int i = 0; i < valueAsArray.Length; i++)\n                    {\n                        converted[i] = ConvertSimpleType(valueAsArray.GetValue(i), destinationElementType, culture);\n                    }\n                    return converted;\n                }\n                else\n                {\n                    // case 2: destination type is array but source is single element, so wrap element in array + convert\n                    object element = ConvertSimpleType(value, destinationElementType, culture);\n                    IList converted = Array.CreateInstance(destinationElementType, 1);\n                    converted[0] = element;\n                    return converted;\n                }\n            }\n            else if (valueAsArray != null)\n            {\n                // case 3: destination type is single element but source is array, so extract first element + convert\n                if (valueAsArray.Length > 0)\n                {\n                    value = valueAsArray.GetValue(0);\n                    return ConvertSimpleType(value, destinationType, culture);\n                }\n                else\n                {\n                    // case 3(a): source is empty array, so can't perform conversion\n                    return null;\n                }\n            }\n            // case 4: both destination + source type are single elements, so convert\n            return ConvertSimpleType(value, destinationType, culture);\n        }\n\n        private static object ConvertSimpleType(object value, Type destinationType, CultureInfo culture)\n        {\n            if (value == null || destinationType.IsInstanceOfType(value))\n            {\n                return value;\n            }\n\n            // if this is a user-input value but the user didn't type anything, return no value\n            string valueAsString = value as string;\n            if (valueAsString != null && valueAsString.Trim().Length == 0)\n            {\n                return null;\n            }\n\n            TypeConverter converter = TypeDescriptor.GetConverter(destinationType);\n            bool canConvertFrom = converter.CanConvertFrom(value.GetType());\n            if (!canConvertFrom)\n            {\n                converter = TypeDescriptor.GetConverter(value.GetType());\n            }\n            if (!(canConvertFrom || converter.CanConvertTo(destinationType)))\n            {\n                string message = String.Format(CultureInfo.CurrentCulture, WebPageResources.HtmlHelper_NoConverterExists,\n                                               value.GetType().FullName, destinationType.FullName);\n                throw new InvalidOperationException(message);\n            }\n\n            try\n            {\n                object convertedValue = (canConvertFrom)\n                                            ? converter.ConvertFrom(context: null, culture: culture, value: value)\n                                            : converter.ConvertTo(context: null, culture: culture, value: value, destinationType: destinationType);\n                return convertedValue;\n            }\n            catch (Exception ex)\n            {\n                string message = String.Format(CultureInfo.CurrentUICulture, WebPageResources.HtmlHelper_ConversionThrew,\n                                               value.GetType().FullName, destinationType.FullName);\n                throw new InvalidOperationException(message, ex);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Html/HtmlHelper.Label.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Mvc;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.WebPages.Html\n{\n    public partial class HtmlHelper\n    {\n        public IHtmlString Label(string labelText)\n        {\n            return Label(labelText, null, (IDictionary<string, object>)null);\n        }\n\n        public IHtmlString Label(string labelText, string labelFor)\n        {\n            return Label(labelText, labelFor, (IDictionary<string, object>)null);\n        }\n\n        public IHtmlString Label(string labelText, object attributes)\n        {\n            return Label(labelText, null, AnonymousObjectToHtmlAttributes(attributes));\n        }\n\n        public IHtmlString Label(string labelText, string labelFor, object attributes)\n        {\n            return Label(labelText, labelFor, AnonymousObjectToHtmlAttributes(attributes));\n        }\n\n        public IHtmlString Label(string labelText, string labelFor, IDictionary<string, object> attributes)\n        {\n            if (String.IsNullOrEmpty(labelText))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"labelText\");\n            }\n\n            labelFor = labelFor ?? labelText;\n\n            TagBuilder tag = new TagBuilder(\"label\") { InnerHtml = Encode(labelText) };\n\n            if (!String.IsNullOrEmpty(labelFor))\n            {\n                tag.MergeAttribute(\"for\", labelFor);\n            }\n            tag.MergeAttributes(attributes, false);\n\n            return tag.ToHtmlString(TagRenderMode.Normal);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Html/HtmlHelper.Radio.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Mvc;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.WebPages.Html\n{\n    public partial class HtmlHelper\n    {\n        public IHtmlString RadioButton(string name, object value)\n        {\n            return RadioButton(name, value, htmlAttributes: (IDictionary<string, object>)null);\n        }\n\n        public IHtmlString RadioButton(string name, object value, object htmlAttributes)\n        {\n            return RadioButton(name, value, AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public IHtmlString RadioButton(string name, object value, IDictionary<string, object> htmlAttributes)\n        {\n            if (String.IsNullOrEmpty(name))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"name\");\n            }\n\n            return BuildRadioButton(name, value, isChecked: null, attributes: htmlAttributes);\n        }\n\n        public IHtmlString RadioButton(string name, object value, bool isChecked)\n        {\n            return RadioButton(name, value, isChecked, htmlAttributes: (IDictionary<string, object>)null);\n        }\n\n        public IHtmlString RadioButton(string name, object value, bool isChecked, object htmlAttributes)\n        {\n            return RadioButton(name, value, isChecked, AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public IHtmlString RadioButton(string name, object value, bool isChecked, IDictionary<string, object> htmlAttributes)\n        {\n            if (name == null)\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"name\");\n            }\n            return BuildRadioButton(name, value, isChecked, htmlAttributes);\n        }\n\n        private IHtmlString BuildRadioButton(string name, object value, bool? isChecked, IDictionary<string, object> attributes)\n        {\n            string valueString = ConvertTo(value, typeof(string)) as string;\n\n            TagBuilder builder = new TagBuilder(\"input\");\n            builder.MergeAttribute(\"type\", \"radio\", true);\n            builder.GenerateId(name);\n            builder.MergeAttributes(attributes, replaceExisting: true);\n\n            builder.MergeAttribute(\"value\", valueString, replaceExisting: true);\n            builder.MergeAttribute(\"name\", name, replaceExisting: true);\n\n            if (UnobtrusiveJavaScriptEnabled)\n            {\n                // Add validation attributes\n                var validationAttributes = _validationHelper.GetUnobtrusiveValidationAttributes(name);\n                builder.MergeAttributes(validationAttributes, replaceExisting: false);\n            }\n\n            var modelState = ModelState[name];\n            string modelValue = null;\n            if (modelState != null)\n            {\n                modelValue = ConvertTo(modelState.Value, typeof(string)) as string;\n                isChecked = isChecked ?? String.Equals(modelValue, valueString, StringComparison.OrdinalIgnoreCase);\n            }\n\n            if (isChecked.HasValue)\n            {\n                // Overrides attribute values\n                if (isChecked.Value)\n                {\n                    builder.MergeAttribute(\"checked\", \"checked\", true);\n                }\n                else\n                {\n                    builder.Attributes.Remove(\"checked\");\n                }\n            }\n\n            AddErrorClass(builder, name);\n\n            return builder.ToHtmlString(TagRenderMode.SelfClosing);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Html/HtmlHelper.Select.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Text;\nusing System.Web.Mvc;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.WebPages.Html\n{\n    public partial class HtmlHelper\n    {\n        public IHtmlString ListBox(string name, IEnumerable<SelectListItem> selectList)\n        {\n            return ListBox(name, defaultOption: null, selectList: selectList, htmlAttributes: (IDictionary<string, object>)null);\n        }\n\n        public IHtmlString ListBox(string name, string defaultOption, IEnumerable<SelectListItem> selectList)\n        {\n            return ListBox(name, defaultOption: defaultOption, selectList: selectList, selectedValues: null,\n                           htmlAttributes: (IDictionary<string, object>)null);\n        }\n\n        public IHtmlString ListBox(string name, IEnumerable<SelectListItem> selectList, object htmlAttributes)\n        {\n            return ListBox(name, defaultOption: null, selectList: selectList, selectedValues: null, htmlAttributes: htmlAttributes);\n        }\n\n        public IHtmlString ListBox(string name, IEnumerable<SelectListItem> selectList, IDictionary<string, object> htmlAttributes)\n        {\n            return ListBox(name, defaultOption: null, selectList: selectList, selectedValues: null, htmlAttributes: htmlAttributes);\n        }\n\n        public IHtmlString ListBox(string name, string defaultOption, IEnumerable<SelectListItem> selectList,\n                                   IDictionary<string, object> htmlAttributes)\n        {\n            return ListBox(name, defaultOption, selectList, selectedValues: null, htmlAttributes: htmlAttributes);\n        }\n\n        public IHtmlString ListBox(string name, string defaultOption, IEnumerable<SelectListItem> selectList, object htmlAttributes)\n        {\n            return ListBox(name, defaultOption: defaultOption, selectList: selectList, selectedValues: null, htmlAttributes: htmlAttributes);\n        }\n\n        public IHtmlString ListBox(string name, string defaultOption, IEnumerable<SelectListItem> selectList, object selectedValues,\n                                   IDictionary<string, object> htmlAttributes)\n        {\n            if (String.IsNullOrEmpty(name))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"name\");\n            }\n            return BuildListBox(name, defaultOption: defaultOption, selectList: selectList,\n                                selectedValues: selectedValues, size: null, allowMultiple: false, htmlAttributes: htmlAttributes);\n        }\n\n        public IHtmlString ListBox(string name, string defaultOption, IEnumerable<SelectListItem> selectList, object selectedValues,\n                                   object htmlAttributes)\n        {\n            return ListBox(name, defaultOption: defaultOption, selectList: selectList,\n                           selectedValues: selectedValues, htmlAttributes: AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public IHtmlString ListBox(string name, IEnumerable<SelectListItem> selectList,\n                                   object selectedValues, int size, bool allowMultiple)\n        {\n            return ListBox(name, defaultOption: null, selectList: selectList, selectedValues: selectedValues, size: size,\n                           allowMultiple: allowMultiple, htmlAttributes: (IDictionary<string, object>)null);\n        }\n\n        public IHtmlString ListBox(string name, string defaultOption, IEnumerable<SelectListItem> selectList,\n                                   object selectedValues, int size, bool allowMultiple)\n        {\n            return ListBox(name, defaultOption: defaultOption, selectList: selectList, selectedValues: selectedValues,\n                           size: size, allowMultiple: allowMultiple, htmlAttributes: (IDictionary<string, object>)null);\n        }\n\n        public IHtmlString ListBox(string name, string defaultOption, IEnumerable<SelectListItem> selectList,\n                                   object selectedValues, int size, bool allowMultiple, IDictionary<string, object> htmlAttributes)\n        {\n            if (String.IsNullOrEmpty(name))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"name\");\n            }\n\n            return BuildListBox(name, defaultOption, selectList, selectedValues, size, allowMultiple, htmlAttributes);\n        }\n\n        public IHtmlString ListBox(string name, string defaultOption, IEnumerable<SelectListItem> selectList,\n                                   object selectedValues, int size, bool allowMultiple, object htmlAttributes)\n        {\n            return ListBox(name, defaultOption, selectList, selectedValues, size, allowMultiple, AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        private IHtmlString BuildListBox(string name, string defaultOption, IEnumerable<SelectListItem> selectList,\n                                         object selectedValues, int? size, bool allowMultiple, IDictionary<string, object> htmlAttributes)\n        {\n            var modelState = ModelState[name];\n            if (modelState != null)\n            {\n                selectedValues = selectedValues ?? ModelState[name].Value;\n            }\n\n            if (selectedValues != null)\n            {\n                IEnumerable values = (allowMultiple) ? ConvertTo(selectedValues, typeof(string[])) as string[]\n                                         : new[] { ConvertTo(selectedValues, typeof(string)) };\n\n                HashSet<string> selectedValueSet = new HashSet<string>(from object value in values\n                                                                       select Convert.ToString(value, CultureInfo.CurrentCulture),\n                                                                       StringComparer.OrdinalIgnoreCase);\n                List<SelectListItem> newSelectList = new List<SelectListItem>();\n\n                bool previousSelected = false;\n                foreach (SelectListItem item in selectList)\n                {\n                    bool selected = false;\n                    // If the user's specified allowed multiple to be false\n                    // only pick up the first item that was selected.\n                    if (allowMultiple || !previousSelected)\n                    {\n                        selected = item.Selected || selectedValueSet.Contains(item.Value ?? item.Text);\n                    }\n                    previousSelected = previousSelected | selected;\n\n                    newSelectList.Add(new SelectListItem(item) { Selected = selected });\n                }\n                selectList = newSelectList;\n            }\n\n            TagBuilder tagBuilder = new TagBuilder(\"select\")\n            {\n                InnerHtml = BuildListOptions(selectList, defaultOption)\n            };\n\n            if (UnobtrusiveJavaScriptEnabled)\n            {\n                // Add validation attributes\n                var validationAttributes = _validationHelper.GetUnobtrusiveValidationAttributes(name);\n                tagBuilder.MergeAttributes(validationAttributes, replaceExisting: false);\n            }\n\n            tagBuilder.GenerateId(name);\n            tagBuilder.MergeAttributes(htmlAttributes);\n\n            tagBuilder.MergeAttribute(\"name\", name, replaceExisting: true);\n            if (size.HasValue)\n            {\n                tagBuilder.MergeAttribute(\"size\", size.ToString(), true);\n            }\n            if (allowMultiple)\n            {\n                tagBuilder.MergeAttribute(\"multiple\", \"multiple\");\n            }\n            else if (tagBuilder.Attributes.ContainsKey(\"multiple\"))\n            {\n                tagBuilder.Attributes.Remove(\"multiple\");\n            }\n\n            // If there are any errors for a named field, we add the css attribute.\n            AddErrorClass(tagBuilder, name);\n\n            return tagBuilder.ToHtmlString(TagRenderMode.Normal);\n        }\n\n        public IHtmlString DropDownList(string name, IEnumerable<SelectListItem> selectList)\n        {\n            return DropDownList(name, defaultOption: null, selectList: selectList, htmlAttributes: (IDictionary<string, object>)null);\n        }\n\n        public IHtmlString DropDownList(string name, IEnumerable<SelectListItem> selectList, object htmlAttributes)\n        {\n            return DropDownList(name, defaultOption: null, selectList: selectList, selectedValue: null, htmlAttributes: htmlAttributes);\n        }\n\n        public IHtmlString DropDownList(string name, IEnumerable<SelectListItem> selectList, IDictionary<string, object> htmlAttributes)\n        {\n            return DropDownList(name, defaultOption: null, selectList: selectList, selectedValue: null, htmlAttributes: htmlAttributes);\n        }\n\n        public IHtmlString DropDownList(string name, string defaultOption, IEnumerable<SelectListItem> selectList)\n        {\n            return DropDownList(name, defaultOption, selectList, selectedValue: null, htmlAttributes: (IDictionary<string, object>)null);\n        }\n\n        public IHtmlString DropDownList(string name, string defaultOption, IEnumerable<SelectListItem> selectList,\n                                        IDictionary<string, object> htmlAttributes)\n        {\n            return DropDownList(name, defaultOption, selectList, selectedValue: null, htmlAttributes: htmlAttributes);\n        }\n\n        public IHtmlString DropDownList(string name, string defaultOption, IEnumerable<SelectListItem> selectList, object htmlAttributes)\n        {\n            return DropDownList(name, defaultOption: defaultOption, selectList: selectList, selectedValue: null, htmlAttributes: htmlAttributes);\n        }\n\n        public IHtmlString DropDownList(string name, string defaultOption, IEnumerable<SelectListItem> selectList, object selectedValue,\n                                        IDictionary<string, object> htmlAttributes)\n        {\n            if (String.IsNullOrEmpty(name))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"name\");\n            }\n            return BuildDropDownList(name, defaultOption, selectList, selectedValue, htmlAttributes: htmlAttributes);\n        }\n\n        public IHtmlString DropDownList(string name, string defaultOption, IEnumerable<SelectListItem> selectList, object selectedValue,\n                                        object htmlAttributes)\n        {\n            return DropDownList(name, defaultOption, selectList, selectedValue, AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        private IHtmlString BuildDropDownList(string name, string defaultOption, IEnumerable<SelectListItem> selectList,\n                                              object selectedValue, IDictionary<string, object> htmlAttributes)\n        {\n            var modelState = ModelState[name];\n            if (modelState != null)\n            {\n                selectedValue = selectedValue ?? ModelState[name].Value;\n            }\n            selectedValue = ConvertTo(selectedValue, typeof(string));\n\n            if (selectedValue != null)\n            {\n                var newSelectList = new List<SelectListItem>(from item in selectList\n                                                             select new SelectListItem(item));\n                var comparer = StringComparer.InvariantCultureIgnoreCase;\n                var selectedItem = newSelectList.FirstOrDefault(item => item.Selected || comparer.Equals(item.Value ?? item.Text, selectedValue));\n                if (selectedItem != default(SelectListItem))\n                {\n                    selectedItem.Selected = true;\n                    selectList = newSelectList;\n                }\n            }\n\n            TagBuilder tagBuilder = new TagBuilder(\"select\")\n            {\n                InnerHtml = BuildListOptions(selectList, defaultOption)\n            };\n            tagBuilder.MergeAttributes(htmlAttributes);\n            tagBuilder.MergeAttribute(\"name\", name, replaceExisting: true);\n            tagBuilder.GenerateId(name);\n            if (UnobtrusiveJavaScriptEnabled)\n            {\n                var validationAttributes = _validationHelper.GetUnobtrusiveValidationAttributes(name);\n                tagBuilder.MergeAttributes(validationAttributes, replaceExisting: false);\n            }\n\n            // If there are any errors for a named field, we add the css attribute.\n            AddErrorClass(tagBuilder, name);\n\n            return tagBuilder.ToHtmlString(TagRenderMode.Normal);\n        }\n\n        private static string BuildListOptions(IEnumerable<SelectListItem> selectList, string optionText)\n        {\n            StringBuilder builder = new StringBuilder().AppendLine();\n            if (optionText != null)\n            {\n                builder.AppendLine(ListItemToOption(new SelectListItem { Text = optionText, Value = String.Empty }));\n            }\n            if (selectList != null)\n            {\n                foreach (var item in selectList)\n                {\n                    builder.AppendLine(ListItemToOption(item));\n                }\n            }\n            return builder.ToString();\n        }\n\n        private static string ListItemToOption(SelectListItem item)\n        {\n            TagBuilder builder = new TagBuilder(\"option\")\n            {\n                InnerHtml = HttpUtility.HtmlEncode(item.Text)\n            };\n            if (item.Value != null)\n            {\n                builder.Attributes[\"value\"] = item.Value;\n            }\n            if (item.Selected)\n            {\n                builder.Attributes[\"selected\"] = \"selected\";\n            }\n            return builder.ToString(TagRenderMode.Normal);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Html/HtmlHelper.TextArea.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Web.Mvc;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.WebPages.Html\n{\n    public partial class HtmlHelper\n    {\n        // Values from mvc\n        private const int TextAreaRows = 2;\n        private const int TextAreaColumns = 20;\n\n        private static readonly IDictionary<string, object> _implicitRowsAndColumns = new Dictionary<string, object>\n        {\n            { \"rows\", TextAreaRows.ToString(CultureInfo.InvariantCulture) },\n            { \"cols\", TextAreaColumns.ToString(CultureInfo.InvariantCulture) },\n        };\n\n        private static IDictionary<string, object> GetRowsAndColumnsDictionary(int rows, int columns)\n        {\n            Dictionary<string, object> result = new Dictionary<string, object>();\n            if (rows > 0)\n            {\n                result.Add(\"rows\", rows.ToString(CultureInfo.InvariantCulture));\n            }\n            if (columns > 0)\n            {\n                result.Add(\"cols\", columns.ToString(CultureInfo.InvariantCulture));\n            }\n            return result;\n        }\n\n        public IHtmlString TextArea(string name)\n        {\n            return TextArea(name, value: null, htmlAttributes: (IDictionary<string, object>)null);\n        }\n\n        public IHtmlString TextArea(string name, object htmlAttributes)\n        {\n            return TextArea(name, value: null, htmlAttributes: AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public IHtmlString TextArea(string name, IDictionary<string, object> htmlAttributes)\n        {\n            return TextArea(name, value: null, htmlAttributes: htmlAttributes);\n        }\n\n        public IHtmlString TextArea(string name, string value)\n        {\n            return TextArea(name, value, (IDictionary<string, object>)null);\n        }\n\n        public IHtmlString TextArea(string name, string value, object htmlAttributes)\n        {\n            return TextArea(name, value, AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public IHtmlString TextArea(string name, string value, IDictionary<string, object> htmlAttributes)\n        {\n            if (String.IsNullOrEmpty(name))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"name\");\n            }\n\n            return BuildTextArea(name, value, _implicitRowsAndColumns, htmlAttributes);\n        }\n\n        public IHtmlString TextArea(string name, string value, int rows, int columns,\n                                    object htmlAttributes)\n        {\n            return TextArea(name, value, rows, columns, AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public IHtmlString TextArea(string name, string value, int rows, int columns,\n                                    IDictionary<string, object> htmlAttributes)\n        {\n            if (String.IsNullOrEmpty(name))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"name\");\n            }\n            return BuildTextArea(name, value, GetRowsAndColumnsDictionary(rows, columns), htmlAttributes);\n        }\n\n        private IHtmlString BuildTextArea(string name, string value, IDictionary<string, object> rowsAndColumnsDictionary,\n                                          IDictionary<string, object> htmlAttributes)\n        {\n            TagBuilder tagBuilder = new TagBuilder(\"textarea\");\n\n            if (UnobtrusiveJavaScriptEnabled)\n            {\n                // Add validation attributes\n                var validationAttributes = _validationHelper.GetUnobtrusiveValidationAttributes(name);\n                tagBuilder.MergeAttributes(validationAttributes, replaceExisting: false);\n            }\n\n            // Add user specified htmlAttributes\n            tagBuilder.MergeAttributes(htmlAttributes);\n\n            tagBuilder.MergeAttributes(rowsAndColumnsDictionary, rowsAndColumnsDictionary != _implicitRowsAndColumns);\n\n            // Value becomes the inner html of the textarea element\n            var modelState = ModelState[name];\n            if (modelState != null)\n            {\n                value = value ?? Convert.ToString(ModelState[name].Value, CultureInfo.CurrentCulture);\n            }\n            tagBuilder.InnerHtml = Encode(value);\n\n            //Assign name and id\n            tagBuilder.MergeAttribute(\"name\", name);\n            tagBuilder.GenerateId(name);\n\n            AddErrorClass(tagBuilder, name);\n\n            return tagBuilder.ToHtmlString(TagRenderMode.Normal);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Html/HtmlHelper.Validation.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Text;\nusing System.Web.Mvc;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.WebPages.Html\n{\n    public partial class HtmlHelper\n    {\n        public IHtmlString ValidationMessage(string name)\n        {\n            return ValidationMessage(name, null, null);\n        }\n\n        public IHtmlString ValidationMessage(string name, string message)\n        {\n            return ValidationMessage(name, message, (IDictionary<string, object>)null);\n        }\n\n        public IHtmlString ValidationMessage(string name, object htmlAttributes)\n        {\n            return ValidationMessage(name, null, AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public IHtmlString ValidationMessage(string name, IDictionary<string, object> htmlAttributes)\n        {\n            return ValidationMessage(name, null, htmlAttributes);\n        }\n\n        public IHtmlString ValidationMessage(string name, string message, object htmlAttributes)\n        {\n            return ValidationMessage(name, message, AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public IHtmlString ValidationMessage(string name, string message, IDictionary<string, object> htmlAttributes)\n        {\n            if (String.IsNullOrEmpty(name))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"name\");\n            }\n            return BuildValidationMessage(name, message, htmlAttributes);\n        }\n\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1308:NormalizeStringsToUppercase\",\n            Justification = \"Normalization to lowercase is a common requirement for JavaScript and HTML values\")]\n        private IHtmlString BuildValidationMessage(string name, string message, IDictionary<string, object> htmlAttributes)\n        {\n            var modelState = ModelState[name];\n            IEnumerable<string> errors = null;\n            if (modelState != null)\n            {\n                errors = modelState.Errors;\n            }\n            bool hasError = errors != null && errors.Any();\n            if (!hasError && !UnobtrusiveJavaScriptEnabled)\n            {\n                // If unobtrusive validation is enabled, we need to generate an empty span with the \"val-for\" attribute\"\n                return null;\n            }\n            else\n            {\n                string error = null;\n                if (hasError)\n                {\n                    error = message ?? errors.First();\n                }\n\n                TagBuilder tagBuilder = new TagBuilder(\"span\") { InnerHtml = Encode(error) };\n                tagBuilder.MergeAttributes(htmlAttributes);\n                if (UnobtrusiveJavaScriptEnabled)\n                {\n                    bool replaceValidationMessageContents = String.IsNullOrEmpty(message);\n                    tagBuilder.MergeAttribute(\"data-valmsg-for\", name);\n                    tagBuilder.MergeAttribute(\"data-valmsg-replace\", replaceValidationMessageContents.ToString().ToLowerInvariant());\n                }\n                tagBuilder.AddCssClass(hasError ? ValidationMessageCssClassName : ValidationMessageValidCssClassName);\n                return tagBuilder.ToHtmlString(TagRenderMode.Normal);\n            }\n        }\n\n        public IHtmlString ValidationSummary()\n        {\n            return BuildValidationSummary(message: null, excludeFieldErrors: false, htmlAttributes: (IDictionary<string, object>)null);\n        }\n\n        public IHtmlString ValidationSummary(string message)\n        {\n            return BuildValidationSummary(message: message, excludeFieldErrors: false, htmlAttributes: (IDictionary<string, object>)null);\n        }\n\n        public IHtmlString ValidationSummary(bool excludeFieldErrors)\n        {\n            return ValidationSummary(message: null, excludeFieldErrors: excludeFieldErrors, htmlAttributes: (IDictionary<string, object>)null);\n        }\n\n        public IHtmlString ValidationSummary(object htmlAttributes)\n        {\n            return ValidationSummary(message: null, excludeFieldErrors: false, htmlAttributes: htmlAttributes);\n        }\n\n        public IHtmlString ValidationSummary(IDictionary<string, object> htmlAttributes)\n        {\n            return ValidationSummary(message: null, excludeFieldErrors: false, htmlAttributes: htmlAttributes);\n        }\n\n        public IHtmlString ValidationSummary(string message, object htmlAttributes)\n        {\n            return ValidationSummary(message, excludeFieldErrors: false, htmlAttributes: htmlAttributes);\n        }\n\n        public IHtmlString ValidationSummary(string message, IDictionary<string, object> htmlAttributes)\n        {\n            return ValidationSummary(message, excludeFieldErrors: false, htmlAttributes: htmlAttributes);\n        }\n\n        public IHtmlString ValidationSummary(string message, bool excludeFieldErrors, object htmlAttributes)\n        {\n            return ValidationSummary(message, excludeFieldErrors, AnonymousObjectToHtmlAttributes(htmlAttributes));\n        }\n\n        public IHtmlString ValidationSummary(string message, bool excludeFieldErrors, IDictionary<string, object> htmlAttributes)\n        {\n            return BuildValidationSummary(message, excludeFieldErrors, htmlAttributes);\n        }\n\n        private IHtmlString BuildValidationSummary(string message, bool excludeFieldErrors, IDictionary<string, object> htmlAttributes)\n        {\n            IEnumerable<string> errors = null;\n            if (excludeFieldErrors)\n            {\n                // Review: Is there a better way to share the form field name between this and ModelStateDictionary?\n                var formModelState = ModelState[ModelStateDictionary.FormFieldKey];\n                if (formModelState != null)\n                {\n                    errors = formModelState.Errors;\n                }\n            }\n            else\n            {\n                errors = ModelState.SelectMany(c => c.Value.Errors);\n            }\n\n            bool hasErrors = errors != null && errors.Any();\n            if (!hasErrors && (!UnobtrusiveJavaScriptEnabled || excludeFieldErrors))\n            {\n                // If no errors are found and we do not have unobtrusive validation enabled or if the summary is not meant to display field errors, don't generate the summary.\n                return null;\n            }\n            else\n            {\n                TagBuilder tagBuilder = new TagBuilder(\"div\");\n                tagBuilder.MergeAttributes(htmlAttributes);\n                tagBuilder.AddCssClass(hasErrors ? ValidationSummaryClass : ValidationSummaryValidClass);\n                if (UnobtrusiveJavaScriptEnabled && !excludeFieldErrors)\n                {\n                    tagBuilder.MergeAttribute(\"data-valmsg-summary\", \"true\");\n                }\n\n                StringBuilder builder = new StringBuilder();\n                if (message != null)\n                {\n                    builder.Append(\"<span>\");\n                    builder.Append(Encode(message));\n                    builder.AppendLine(\"</span>\");\n                }\n                builder.AppendLine(\"<ul>\");\n                foreach (var error in errors)\n                {\n                    builder.Append(\"<li>\");\n                    builder.Append(Encode(error));\n                    builder.AppendLine(\"</li>\");\n                }\n                builder.Append(\"</ul>\");\n\n                tagBuilder.InnerHtml = builder.ToString();\n                return tagBuilder.ToHtmlString(TagRenderMode.Normal);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Html/HtmlHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Web.Routing;\nusing System.Web.WebPages.Scope;\n\nnamespace System.Web.WebPages.Html\n{\n    public partial class HtmlHelper\n    {\n        internal const string DefaultValidationInputErrorCssClass = \"input-validation-error\";\n        private const string DefaultValidationInputValidCssClass = \"input-validation-valid\";\n        private const string DefaultValidationMessageErrorCssClass = \"field-validation-error\";\n        private const string DefaultValidationMessageValidCssClass = \"field-validation-valid\";\n        private const string DefaultValidationSummaryErrorCssClass = \"validation-summary-errors\";\n        private const string DefaultValidationSummaryValidCssClassName = \"validation-summary-valid\";\n        private static readonly object _validationMesssageErrorClassKey = new object();\n        private static readonly object _validationMessageValidClassKey = new object();\n        private static readonly object _validationInputErrorClassKey = new object();\n        private static readonly object _validationInputValidClassKey = new object();\n        private static readonly object _validationSummaryClassKey = new object();\n        private static readonly object _validationSummaryValidClassKey = new object();\n        private static readonly object _unobtrusiveValidationKey = new object();\n        private static string _idAttributeDotReplacement;\n        private readonly ValidationHelper _validationHelper;\n\n        internal HtmlHelper(ModelStateDictionary modelState, ValidationHelper validationHelper)\n        {\n            ModelState = modelState;\n            _validationHelper = validationHelper;\n        }\n\n        // This property got copied from MVC's HtmlHelper along with TagBuilder.\n        // It was a global property in MVC so it should not have scoped semantics here either.\n        public static string IdAttributeDotReplacement\n        {\n            get\n            {\n                if (String.IsNullOrEmpty(_idAttributeDotReplacement))\n                {\n                    _idAttributeDotReplacement = \"_\";\n                }\n                return _idAttributeDotReplacement;\n            }\n            set { _idAttributeDotReplacement = value; }\n        }\n\n        public static string ValidationInputValidCssClassName\n        {\n            get { return ScopeStorage.CurrentScope[_validationInputValidClassKey] as string ?? DefaultValidationInputValidCssClass; }\n            set\n            {\n                if (value == null)\n                {\n                    throw new ArgumentNullException(\"value\");\n                }\n                ScopeStorage.CurrentScope[_validationInputValidClassKey] = value;\n            }\n        }\n\n        public static string ValidationInputCssClassName\n        {\n            get { return ScopeStorage.CurrentScope[_validationInputErrorClassKey] as string ?? DefaultValidationInputErrorCssClass; }\n            set\n            {\n                if (value == null)\n                {\n                    throw new ArgumentNullException(\"value\");\n                }\n                ScopeStorage.CurrentScope[_validationInputErrorClassKey] = value;\n            }\n        }\n\n        public static string ValidationMessageValidCssClassName\n        {\n            get { return ScopeStorage.CurrentScope[_validationMessageValidClassKey] as string ?? DefaultValidationMessageValidCssClass; }\n            set\n            {\n                if (value == null)\n                {\n                    throw new ArgumentNullException(\"value\");\n                }\n                ScopeStorage.CurrentScope[_validationMessageValidClassKey] = value;\n            }\n        }\n\n        public static string ValidationMessageCssClassName\n        {\n            get { return ScopeStorage.CurrentScope[_validationMesssageErrorClassKey] as string ?? DefaultValidationMessageErrorCssClass; }\n            set\n            {\n                if (value == null)\n                {\n                    throw new ArgumentNullException(\"value\");\n                }\n                ScopeStorage.CurrentScope[_validationMesssageErrorClassKey] = value;\n            }\n        }\n\n        public static string ValidationSummaryClass\n        {\n            get { return ScopeStorage.CurrentScope[_validationSummaryClassKey] as string ?? DefaultValidationSummaryErrorCssClass; }\n            set\n            {\n                if (value == null)\n                {\n                    throw new ArgumentNullException(\"value\");\n                }\n                ScopeStorage.CurrentScope[_validationSummaryClassKey] = value;\n            }\n        }\n\n        public static string ValidationSummaryValidClass\n        {\n            get { return ScopeStorage.CurrentScope[_validationSummaryValidClassKey] as string ?? DefaultValidationSummaryValidCssClassName; }\n            set\n            {\n                if (value == null)\n                {\n                    throw new ArgumentNullException(\"value\");\n                }\n                ScopeStorage.CurrentScope[_validationSummaryValidClassKey] = value;\n            }\n        }\n\n        public static bool UnobtrusiveJavaScriptEnabled\n        {\n            get\n            {\n                bool? value = (bool?)ScopeStorage.CurrentScope[_unobtrusiveValidationKey];\n                return value ?? true;\n            }\n            set { ScopeStorage.CurrentScope[_unobtrusiveValidationKey] = value; }\n        }\n\n        private ModelStateDictionary ModelState { get; set; }\n\n        public string AttributeEncode(object value)\n        {\n            return AttributeEncode(Convert.ToString(value, CultureInfo.InvariantCulture));\n        }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\",\n            Justification = \"For consistency, all helpers are instance methods.\")]\n        public string AttributeEncode(string value)\n        {\n            if (String.IsNullOrEmpty(value))\n            {\n                return String.Empty;\n            }\n            else\n            {\n                return HttpUtility.HtmlAttributeEncode(value);\n            }\n        }\n\n        public string Encode(object value)\n        {\n            return Encode(Convert.ToString(value, CultureInfo.InvariantCulture));\n        }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\",\n            Justification = \"For consistency, all helpers are instance methods.\")]\n        public string Encode(string value)\n        {\n            if (String.IsNullOrEmpty(value))\n            {\n                return String.Empty;\n            }\n            else\n            {\n                return HttpUtility.HtmlEncode(value);\n            }\n        }\n\n        /// <summary>\n        /// Wraps HTML markup in an IHtmlString, which will enable HTML markup to be\n        /// rendered to the output without getting HTML encoded.\n        /// </summary>\n        /// <param name=\"value\">HTML markup string.</param>\n        /// <returns>An IHtmlString that represents HTML markup.</returns>\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\",\n            Justification = \"For consistency, all helpers are instance methods.\")]\n        public IHtmlString Raw(string value)\n        {\n            return new HtmlString(value);\n        }\n\n        /// <summary>\n        /// Wraps HTML markup from the string representation of an object in an IHtmlString,\n        /// which will enable HTML markup to be rendered to the output without getting HTML encoded.\n        /// </summary>\n        /// <param name=\"value\">object with string representation as HTML markup</param>\n        /// <returns>An IHtmlString that represents HTML markup.</returns>\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\",\n            Justification = \"For consistency, all helpers are instance methods.\")]\n        public IHtmlString Raw(object value)\n        {\n            return new HtmlString(value == null ? null : value.ToString());\n        }\n\n        /// <summary>\n        /// Creates a dictionary of HTML attributes from the input object, \n        /// translating underscores to dashes.\n        /// </summary>\n        /// <example>\n        /// new <c>{ data_name=\"value\" }</c> will translate to the entry <c>{ \"data-name\" , \"value\" }</c>\n        /// in the resulting dictionary.\n        /// </example>\n        /// <param name=\"htmlAttributes\">Anonymous object describing HTML attributes.</param>\n        /// <returns>A dictionary that represents HTML attributes.</returns>\n        public static RouteValueDictionary AnonymousObjectToHtmlAttributes(object htmlAttributes)\n        {\n            RouteValueDictionary result = new RouteValueDictionary();\n\n            if (htmlAttributes != null)\n            {\n                foreach (PropertyHelper property in HtmlAttributePropertyHelper.GetProperties(htmlAttributes))\n                {\n                    result.Add(property.Name, property.GetValue(htmlAttributes));\n                }\n            }\n\n            return result;\n        }\n\n        /// <summary>\n        /// Creates a dictionary from an object, by adding each public instance property as a key with its associated \n        /// value to the dictionary. It will expose public properties from derived types as well. This is typically used\n        /// with objects of an anonymous type.\n        /// </summary>\n        /// <example>\n        /// <c>new { property_name = \"value\" }</c> will translate to the entry <c>{ \"property_name\" , \"value\" }</c>\n        /// in the resulting dictionary.\n        /// </example>\n        /// <param name=\"value\">The object to be converted.</param>\n        /// <returns>The created dictionary of property names and property values.</returns>\n        public static IDictionary<string, object> ObjectToDictionary(object value)\n        {\n            return TypeHelper.ObjectToDictionary(value);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Html/ModelState.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.WebPages.Html\n{\n    public class ModelState\n    {\n        private List<string> _errors = new List<string>();\n\n        public IList<string> Errors\n        {\n            get { return _errors; }\n        }\n\n        public object Value { get; set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Html/ModelStateDictionary.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace System.Web.WebPages.Html\n{\n    // Most of the code for this class is copied from MVC 2.0\n    public class ModelStateDictionary : IDictionary<string, ModelState>\n    {\n        internal const string FormFieldKey = \"_FORM\";\n        private readonly Dictionary<string, ModelState> _innerDictionary = new Dictionary<string, ModelState>(StringComparer.OrdinalIgnoreCase);\n\n        public ModelStateDictionary()\n        {\n        }\n\n        public ModelStateDictionary(ModelStateDictionary dictionary)\n        {\n            if (dictionary == null)\n            {\n                throw new ArgumentNullException(\"dictionary\");\n            }\n\n            foreach (var entry in dictionary)\n            {\n                _innerDictionary.Add(entry.Key, entry.Value);\n            }\n        }\n\n        public int Count\n        {\n            get { return _innerDictionary.Count; }\n        }\n\n        public bool IsReadOnly\n        {\n            get { return ((IDictionary<string, ModelState>)_innerDictionary).IsReadOnly; }\n        }\n\n        public bool IsValid\n        {\n            get { return !Values.SelectMany(modelState => modelState.Errors).Any(); }\n        }\n\n        public ICollection<string> Keys\n        {\n            get { return _innerDictionary.Keys; }\n        }\n\n        public ICollection<ModelState> Values\n        {\n            get { return _innerDictionary.Values; }\n        }\n\n        public ModelState this[string key]\n        {\n            get\n            {\n                ModelState value;\n                _innerDictionary.TryGetValue(key, out value);\n                return value;\n            }\n            set { _innerDictionary[key] = value; }\n        }\n\n        public void Add(KeyValuePair<string, ModelState> item)\n        {\n            ((IDictionary<string, ModelState>)_innerDictionary).Add(item);\n        }\n\n        public void Add(string key, ModelState value)\n        {\n            _innerDictionary.Add(key, value);\n        }\n\n        public void AddError(string key, string errorMessage)\n        {\n            GetModelStateForKey(key).Errors.Add(errorMessage);\n        }\n\n        public void AddFormError(string errorMessage)\n        {\n            GetModelStateForKey(FormFieldKey).Errors.Add(errorMessage);\n        }\n\n        public void Clear()\n        {\n            _innerDictionary.Clear();\n        }\n\n        public bool Contains(KeyValuePair<string, ModelState> item)\n        {\n            return ((IDictionary<string, ModelState>)_innerDictionary).Contains(item);\n        }\n\n        public bool ContainsKey(string key)\n        {\n            return _innerDictionary.ContainsKey(key);\n        }\n\n        public void CopyTo(KeyValuePair<string, ModelState>[] array, int arrayIndex)\n        {\n            ((IDictionary<string, ModelState>)_innerDictionary).CopyTo(array, arrayIndex);\n        }\n\n        public IEnumerator<KeyValuePair<string, ModelState>> GetEnumerator()\n        {\n            return _innerDictionary.GetEnumerator();\n        }\n\n        private ModelState GetModelStateForKey(string key)\n        {\n            if (key == null)\n            {\n                throw new ArgumentNullException(\"key\");\n            }\n\n            ModelState modelState;\n            if (!TryGetValue(key, out modelState))\n            {\n                modelState = new ModelState();\n                _innerDictionary[key] = modelState;\n            }\n\n            return modelState;\n        }\n\n        public bool IsValidField(string key)\n        {\n            if (key == null)\n            {\n                throw new ArgumentNullException(\"key\");\n            }\n\n            // if the key is not found in the dictionary, we just say that it's valid (since there are no errors)\n            ModelState modelState = this[key];\n            return (modelState == null) || !modelState.Errors.Any();\n        }\n\n        public void Merge(ModelStateDictionary dictionary)\n        {\n            if (dictionary == null)\n            {\n                return;\n            }\n\n            foreach (var entry in dictionary)\n            {\n                this[entry.Key] = entry.Value;\n            }\n        }\n\n        public bool Remove(KeyValuePair<string, ModelState> item)\n        {\n            return ((IDictionary<string, ModelState>)_innerDictionary).Remove(item);\n        }\n\n        public bool Remove(string key)\n        {\n            return _innerDictionary.Remove(key);\n        }\n\n        public bool TryGetValue(string key, out ModelState value)\n        {\n            return _innerDictionary.TryGetValue(key, out value);\n        }\n\n        public void SetModelValue(string key, object value)\n        {\n            ModelState state = GetModelStateForKey(key);\n            state.Value = value;\n        }\n\n        #region IEnumerable Members\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return ((IEnumerable)_innerDictionary).GetEnumerator();\n        }\n\n        #endregion\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Html/SelectListItem.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.WebPages.Html\n{\n    public class SelectListItem\n    {\n        public SelectListItem()\n        {\n        }\n\n        public SelectListItem(SelectListItem item)\n        {\n            Text = item.Text;\n            Value = item.Value;\n            Selected = item.Selected;\n        }\n\n        public string Text { get; set; }\n\n        public string Value { get; set; }\n\n        public bool Selected { get; set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/HttpContextExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.WebPages\n{\n    public static class HttpContextExtensions\n    {\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"Response.Redirect() takes its URI as a string parameter.\")]\n        public static void RedirectLocal(this HttpContextBase context, string url)\n        {\n            if (context.Request.IsUrlLocalToHost(url))\n            {\n                context.Response.Redirect(url);\n            }\n            else\n            {\n                context.Response.Redirect(\"~/\");\n            }\n        }\n\n        public static void RegisterForDispose(this HttpContextBase context, IDisposable resource)\n        {\n            if (context == null)\n            {\n                throw new ArgumentNullException(\"context\");\n            }\n            RequestResourceTracker.RegisterForDispose(context, resource);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/IDisplayMode.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.WebPages\n{\n    /// <summary>\n    /// An interface that provides DisplayInfo for a virtual path and request. An IDisplayMode may modify the virtual path before checking\n    /// if it exists. CanHandleContext is called to determine if the Display Mode is available to return display info for the request.\n    /// GetDisplayInfo should return null if the virtual path does not exist. For an example implementation, see DefaultDisplayMode.\n    /// DisplayModeId is used to cache the non-null result of a call to GetDisplayInfo and should be unique for each Display Mode. See\n    /// DisplayModes for the built-in Display Modes and their ids.\n    /// </summary>\n    public interface IDisplayMode\n    {\n        string DisplayModeId { get; }\n        bool CanHandleContext(HttpContextBase httpContext);\n        DisplayInfo GetDisplayInfo(HttpContextBase httpContext, string virtualPath, Func<string, bool> virtualPathExists);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/ITemplateFile.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.WebPages\n{\n    /// <summary>\n    /// An interface that provides information about the current executing file.\n    /// WebPageRenderingBase implements this type so that all pages excluding AppStart pages could be queried to identify the \n    /// current executing file.\n    /// </summary>\n    public interface ITemplateFile\n    {\n        TemplateFileInfo TemplateInfo { get; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/IVirtualPathFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.WebPages\n{\n    // Implemented by classes that can create object instances from virtual path.\n    // Those implementations can completely bypass the BuildManager (e.g. for dynamic language pages)\n    public interface IVirtualPathFactory\n    {\n        bool Exists(string virtualPath);\n        object CreateInstance(string virtualPath);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/IVirtualPathUtility.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.Internal.Web.Utils\n{\n    internal interface IVirtualPathUtility\n    {\n        string Combine(string basePath, string relativePath);\n\n        string ToAbsolute(string virtualPath);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/IWebPageRequestExecutor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.WebPages\n{\n    // An executor is a class that can take over the execution of a WebPage. This can be used to\n    // implement features like AJAX callback methods on the page (like WebForms Page Methods)\n    public interface IWebPageRequestExecutor\n    {\n        bool Execute(WebPage page);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Instrumentation/HttpContextAdapter.Availability.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\n\nnamespace System.Web.WebPages.Instrumentation\n{\n    internal partial class HttpContextAdapter\n    {\n        private static readonly bool _isInstrumentationAvailable = typeof(HttpContext).GetProperty(\"PageInstrumentation\", BindingFlags.Instance | BindingFlags.Public) != null;\n\n        internal static bool IsInstrumentationAvailable\n        {\n            get { return _isInstrumentationAvailable; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Instrumentation/HttpContextAdapter.generated.cs",
    "content": "﻿using System.CodeDom.Compiler;\n\nnamespace System.Web.WebPages.Instrumentation\n{\n    [GeneratedCode(\"Microsoft.Web.CodeGen.DynamicCallerGenerator\", \"1.0.0.0\")]\n    internal partial class HttpContextAdapter\n    {\n        internal PageInstrumentationServiceAdapter PageInstrumentation\n        {\n            get { return new PageInstrumentationServiceAdapter((object)Adaptee.PageInstrumentation); }\n        }\n\n        // BEGIN Adaptor Infrastructure Code\n        private static readonly Type _TargetType = typeof(HttpContext);\n        internal dynamic Adaptee { get; private set; }\n\n        internal HttpContextAdapter(object existing)\n        {\n            Adaptee = existing;\n        }\n\n        // END Adaptor Infrastructure Code\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Instrumentation/HttpContextAdapter.tt",
    "content": "﻿<#@ template debug=\"false\" hostspecific=\"true\" language=\"C#\" inherits=\"Microsoft.Web.CodeGen.DynamicCallerGenerator\" #>\n<#@ import namespace=\"System.Reflection\" #>\n<#@ assembly name=\"$(SolutionDir)\\tools\\Microsoft.Web.CodeGen\\Microsoft.Web.CodeGen.dll\" #>\n<#@ output extension=\".cs\" #>\n<#\nTargetNamespace = \"System.Web.WebPages.Instrumentation\";\n\nInclude(MemberTypes.Property, \"PageInstrumentation\");\n\nMap(\n\t\"System.Web.Instrumentation.PageInstrumentationService\",\n\t\"System.Web.WebPages.Instrumentation.PageInstrumentationServiceAdapter\",\n\ts => {#><#=s#>.Adaptee<#},\n\ts => {#>new PageInstrumentationServiceAdapter(<#=s#>)<#}\n);\n\nWriteAdaptor(\n\t\"System.Web.HttpContext\", \n\tHost.ResolvePath(@\"..\\..\\..\\ReferenceAssemblies\\NetFx\\Dev11\\System.Web.dll\")\n); \n#>"
  },
  {
    "path": "src/System.Web.WebPages/Instrumentation/InstrumentationService.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.IO;\n\nnamespace System.Web.WebPages.Instrumentation\n{\n    public class InstrumentationService\n    {\n        private static readonly bool _isAvailable = HttpContextAdapter.IsInstrumentationAvailable;\n        private bool _localIsAvailable = _isAvailable && PageInstrumentationServiceAdapter.IsEnabled;\n\n        private PageInstrumentationServiceAdapter _instrumentationServiceAdapter;\n        private bool _isInstrumentationServiceAdapterInitialized;\n\n        public InstrumentationService()\n        {\n            ExtractInstrumentationService = GetInstrumentationServiceUncached;\n            CreateContext = CreateSystemWebContext;\n        }\n\n        public bool IsAvailable\n        {\n            get { return _localIsAvailable; }\n            internal set { _localIsAvailable = value; }\n        }\n\n        internal Func<HttpContextBase, PageInstrumentationServiceAdapter> ExtractInstrumentationService { get; set; }\n        internal Func<string, TextWriter, int, int, bool, PageExecutionContextAdapter> CreateContext { get; set; }\n\n        public void BeginContext(HttpContextBase context, string virtualPath, TextWriter writer, int startPosition, int length, bool isLiteral)\n        {\n            if (IsAvailable)\n            {\n                PageInstrumentationServiceAdapter instrumentationService = GetInstrumentationService(context);\n                if (instrumentationService != null && instrumentationService.ExecutionListeners.Count > 0)\n                {\n                    var instrumentationContext = CreateContext(virtualPath, writer, startPosition, length, isLiteral);\n                    foreach (PageExecutionListenerAdapter listener in instrumentationService.ExecutionListeners)\n                    {\n                        listener.BeginContext(instrumentationContext);\n                    }\n                }\n            }\n        }\n\n        public void EndContext(HttpContextBase context, string virtualPath, TextWriter writer, int startPosition, int length, bool isLiteral)\n        {\n            if (IsAvailable)\n            {\n                PageInstrumentationServiceAdapter instrumentationService = GetInstrumentationService(context);\n                if (instrumentationService != null && instrumentationService.ExecutionListeners.Count > 0)\n                {\n                    var instrumentationContext = CreateContext(virtualPath, writer, startPosition, length, isLiteral);\n                    foreach (PageExecutionListenerAdapter listener in instrumentationService.ExecutionListeners)\n                    {\n                        listener.EndContext(instrumentationContext);\n                    }\n                }\n            }\n        }\n\n        private static PageExecutionContextAdapter CreateSystemWebContext(string virtualPath, TextWriter writer, int startPosition, int length, bool isLiteral)\n        {\n            return new PageExecutionContextAdapter()\n            {\n                VirtualPath = virtualPath,\n                TextWriter = writer,\n                StartPosition = startPosition,\n                Length = length,\n                IsLiteral = isLiteral\n            };\n        }\n\n        private PageInstrumentationServiceAdapter GetInstrumentationService(HttpContextBase context)\n        {\n            // There seems to be the potential for the adapter to be null.\n            if (!_isInstrumentationServiceAdapterInitialized)\n            {\n                _instrumentationServiceAdapter = ExtractInstrumentationService(context);\n\n                _isInstrumentationServiceAdapterInitialized = true;\n            }\n\n            return _instrumentationServiceAdapter;\n        }\n\n        private PageInstrumentationServiceAdapter GetInstrumentationServiceUncached(HttpContextBase context)\n        {\n            HttpContextAdapter ctx = new HttpContextAdapter(context);\n            return ctx.PageInstrumentation;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Instrumentation/PageExecutionContextAdapter.generated.cs",
    "content": "﻿using System.CodeDom.Compiler;\nusing System.IO;\nusing System.Linq.Expressions;\n\nnamespace System.Web.WebPages.Instrumentation\n{\n    [GeneratedCode(\"Microsoft.Web.CodeGen.DynamicCallerGenerator\", \"1.0.0.0\")]\n    internal partial class PageExecutionContextAdapter\n    {\n        internal bool IsLiteral\n        {\n            get { return Adaptee.IsLiteral; }\n            set { Adaptee.IsLiteral = value; }\n        }\n\n        internal int Length\n        {\n            get { return Adaptee.Length; }\n            set { Adaptee.Length = value; }\n        }\n\n        internal int StartPosition\n        {\n            get { return Adaptee.StartPosition; }\n            set { Adaptee.StartPosition = value; }\n        }\n\n        internal TextWriter TextWriter\n        {\n            get { return Adaptee.TextWriter; }\n            set { Adaptee.TextWriter = value; }\n        }\n\n        internal string VirtualPath\n        {\n            get { return Adaptee.VirtualPath; }\n            set { Adaptee.VirtualPath = value; }\n        }\n\n        private static class _CallSite_ctor_1\n        {\n            public static Func<object> Site;\n\n            static _CallSite_ctor_1()\n            {\n                Site = Expression.Lambda<Func<object>>(\n                    Expression.New(_TargetType.GetConstructor(new Type[] { })))\n                    .Compile();\n            }\n        }\n\n        internal PageExecutionContextAdapter()\n        {\n            Adaptee = _CallSite_ctor_1.Site();\n        }\n\n        // BEGIN Adaptor Infrastructure Code\n        private static readonly Type _TargetType = typeof(HttpContext).Assembly.GetType(\"System.Web.Instrumentation.PageExecutionContext\");\n        internal dynamic Adaptee { get; private set; }\n\n        internal PageExecutionContextAdapter(object existing)\n        {\n            Adaptee = existing;\n        }\n\n        // END Adaptor Infrastructure Code\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Instrumentation/PageExecutionContextAdapter.tt",
    "content": "﻿<#@ template debug=\"false\" hostspecific=\"true\" language=\"C#\" inherits=\"Microsoft.Web.CodeGen.DynamicCallerGenerator\" #>\n<#@ assembly name=\"$(SolutionDir)\\tools\\Microsoft.Web.CodeGen\\Microsoft.Web.CodeGen.dll\" #>\n<#@ output extension=\".cs\" #>\n<# \nTargetNamespace = \"System.Web.WebPages.Instrumentation\";\nWriteAdaptor(\n\t\"System.Web.Instrumentation.PageExecutionContext\", \n\tHost.ResolvePath(@\"..\\..\\..\\ReferenceAssemblies\\NetFx\\Dev11\\System.Web.dll\")\n); #>"
  },
  {
    "path": "src/System.Web.WebPages/Instrumentation/PageExecutionListenerAdapter.generated.cs",
    "content": "﻿using System.CodeDom.Compiler;\n\nnamespace System.Web.WebPages.Instrumentation\n{\n    [GeneratedCode(\"Microsoft.Web.CodeGen.DynamicCallerGenerator\", \"1.0.0.0\")]\n    internal partial class PageExecutionListenerAdapter\n    {\n        internal void BeginContext(PageExecutionContextAdapter context)\n        {\n            Adaptee.BeginContext(context.Adaptee);\n        }\n\n        internal void EndContext(PageExecutionContextAdapter context)\n        {\n            Adaptee.EndContext(context.Adaptee);\n        }\n\n        // BEGIN Adaptor Infrastructure Code\n        private static readonly Type _TargetType = typeof(HttpContext).Assembly.GetType(\"System.Web.Instrumentation.PageExecutionListener\");\n        internal dynamic Adaptee { get; private set; }\n\n        internal PageExecutionListenerAdapter(object existing)\n        {\n            Adaptee = existing;\n        }\n\n        // END Adaptor Infrastructure Code\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Instrumentation/PageExecutionListenerAdapter.tt",
    "content": "﻿<#@ template debug=\"false\" hostspecific=\"true\" language=\"C#\" inherits=\"Microsoft.Web.CodeGen.DynamicCallerGenerator\" #>\n<#@ assembly name=\"$(SolutionDir)\\tools\\Microsoft.Web.CodeGen\\Microsoft.Web.CodeGen.dll\" #>\n<#@ output extension=\".cs\" #>\n<# \nTargetNamespace = \"System.Web.WebPages.Instrumentation\";\nMap(\n\t\"System.Web.Instrumentation.PageExecutionContext\", \n\t\"System.Web.WebPages.Instrumentation.PageExecutionContextAdapter\", \n\ts => {#><#=s#>.Adaptee<#}\n);\nWriteAdaptor(\n\t\"System.Web.Instrumentation.PageExecutionListener\", \n\tHost.ResolvePath(@\"..\\..\\..\\ReferenceAssemblies\\NetFx\\Dev11\\System.Web.dll\")\n); #>"
  },
  {
    "path": "src/System.Web.WebPages/Instrumentation/PageInstrumentationServiceAdapter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Linq.Expressions;\nusing System.Reflection;\n\nnamespace System.Web.WebPages.Instrumentation\n{\n    internal partial class PageInstrumentationServiceAdapter\n    {\n        private static readonly Type _targetType = typeof(HttpContext).Assembly.GetType(\"System.Web.Instrumentation.PageInstrumentationService\");\n        private IReadOnlyList<PageExecutionListenerAdapter> _listenerAdapters;\n\n        internal PageInstrumentationServiceAdapter()\n        {\n            Adaptee = _CallSite_ctor_2.Site();\n        }\n\n        internal PageInstrumentationServiceAdapter(object existing)\n        {\n            Adaptee = existing;\n        }\n\n        internal IReadOnlyList<PageExecutionListenerAdapter> ExecutionListeners\n        {\n            get\n            {\n                if (_listenerAdapters == null)\n                {\n                    IEnumerable<dynamic> inner = Adaptee.ExecutionListeners;\n                    // Bug 235916: If we pass the type as an object, the callsite is limited to wherever the object is assigned to \n                    // dynamic which avoids private reflection issues in partial trust.\n                    _listenerAdapters = inner.Select(listener => new PageExecutionListenerAdapter((object)listener)).ToList();\n                }\n\n                return _listenerAdapters;\n            }\n        }\n\n        internal static bool IsEnabled\n        {\n            get { return _CallSite_IsEnabled_1.Getter(); }\n            set { _CallSite_IsEnabled_1.Setter(value); }\n        }\n\n        internal dynamic Adaptee { get; private set; }\n\n        private static class _CallSite_IsEnabled_1\n        {\n            public static Func<bool> Getter;\n            public static Action<bool> Setter;\n\n            [SuppressMessage(\"Microsoft.Performance\", \"CA1810:InitializeReferenceTypeStaticFieldsInline\", Justification = \"Fields cannot be initialized at declaration\")]\n            static _CallSite_IsEnabled_1()\n            {\n                PropertyInfo prop = null;\n                if (_targetType != null)\n                {\n                    prop = _targetType.GetProperty(\"IsEnabled\", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder, typeof(bool), Type.EmptyTypes, new ParameterModifier[0]);\n                }\n                if (prop != null)\n                {\n                    Getter = Expression.Lambda<Func<bool>>(Expression.Property(null, prop)).Compile();\n                    ParameterExpression value = Expression.Parameter(typeof(bool));\n                    Setter = Expression.Lambda<Action<bool>>(\n                        Expression.Assign(Expression.Property(null, prop), value), value).Compile();\n                }\n                else\n                {\n                    Getter = () => false;\n                    Setter = _ =>\n                    {\n                    };\n                }\n            }\n        }\n\n        private static class _CallSite_ctor_2\n        {\n            public static Func<object> Site;\n\n            [SuppressMessage(\"Microsoft.Performance\", \"CA1810:InitializeReferenceTypeStaticFieldsInline\", Justification = \"Fields cannot be initialized at declaration\")]\n            static _CallSite_ctor_2()\n            {\n                if (_targetType != null)\n                {\n                    Site = Expression.Lambda<Func<object>>(\n                        Expression.New(\n                            _targetType.GetConstructor(new Type[] { })))\n                        .Compile();\n                }\n                else\n                {\n                    Site = () => null;\n                }\n            }\n        }\n\n        // END Adaptor Infrastructure Code\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Instrumentation/PositionTagged.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.WebPages.Instrumentation\n{\n    [DebuggerDisplay(\"({Position})\\\"{Value}\\\"\")]\n    public class PositionTagged<T>\n    {\n        private PositionTagged()\n        {\n            Position = 0;\n            Value = default(T);\n        }\n\n        public PositionTagged(T value, int offset)\n        {\n            Position = offset;\n            Value = value;\n        }\n\n        public int Position { get; private set; }\n        public T Value { get; private set; }\n\n        public override bool Equals(object obj)\n        {\n            PositionTagged<T> other = obj as PositionTagged<T>;\n            return other != null &&\n                   other.Position == Position &&\n                   Equals(other.Value, Value);\n        }\n\n        public override int GetHashCode()\n        {\n            return HashCodeCombiner.Start()\n                .Add(Position)\n                .Add(Value)\n                .CombinedHash;\n        }\n\n        public override string ToString()\n        {\n            return Value.ToString();\n        }\n\n        public static implicit operator T(PositionTagged<T> value)\n        {\n            return value.Value;\n        }\n\n        public static implicit operator PositionTagged<T>(Tuple<T, int> value)\n        {\n            return new PositionTagged<T>(value.Item1, value.Item2);\n        }\n\n        public static bool operator ==(PositionTagged<T> left, PositionTagged<T> right)\n        {\n            return Equals(left, right);\n        }\n\n        public static bool operator !=(PositionTagged<T> left, PositionTagged<T> right)\n        {\n            return !Equals(left, right);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/MimeMapping.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\n\nnamespace Microsoft.Internal.Web.Utils\n{\n    internal static class MimeMapping\n    {\n        private static readonly IDictionary<string, string> _mimeMappings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)\n        {\n            { \".*\", \"application/octet-stream\" },\n            { \".323\", \"text/h323\" },\n            { \".aaf\", \"application/octet-stream\" },\n            { \".aca\", \"application/octet-stream\" },\n            { \".accdb\", \"application/msaccess\" },\n            { \".accde\", \"application/msaccess\" },\n            { \".accdt\", \"application/msaccess\" },\n            { \".acx\", \"application/internet-property-stream\" },\n            { \".afm\", \"application/octet-stream\" },\n            { \".ai\", \"application/postscript\" },\n            { \".aif\", \"audio/x-aiff\" },\n            { \".aifc\", \"audio/aiff\" },\n            { \".aiff\", \"audio/aiff\" },\n            { \".application\", \"application/x-ms-application\" },\n            { \".art\", \"image/x-jg\" },\n            { \".asd\", \"application/octet-stream\" },\n            { \".asf\", \"video/x-ms-asf\" },\n            { \".asi\", \"application/octet-stream\" },\n            { \".asm\", \"text/plain\" },\n            { \".asr\", \"video/x-ms-asf\" },\n            { \".asx\", \"video/x-ms-asf\" },\n            { \".atom\", \"application/atom+xml\" },\n            { \".au\", \"audio/basic\" },\n            { \".avi\", \"video/x-msvideo\" },\n            { \".axs\", \"application/olescript\" },\n            { \".bas\", \"text/plain\" },\n            { \".bcpio\", \"application/x-bcpio\" },\n            { \".bin\", \"application/octet-stream\" },\n            { \".bmp\", \"image/bmp\" },\n            { \".c\", \"text/plain\" },\n            { \".cab\", \"application/octet-stream\" },\n            { \".calx\", \"application/vnd.ms-office.calx\" },\n            { \".cat\", \"application/vnd.ms-pki.seccat\" },\n            { \".cdf\", \"application/x-cdf\" },\n            { \".chm\", \"application/octet-stream\" },\n            { \".class\", \"application/x-java-applet\" },\n            { \".clp\", \"application/x-msclip\" },\n            { \".cmx\", \"image/x-cmx\" },\n            { \".cnf\", \"text/plain\" },\n            { \".cod\", \"image/cis-cod\" },\n            { \".cpio\", \"application/x-cpio\" },\n            { \".cpp\", \"text/plain\" },\n            { \".crd\", \"application/x-mscardfile\" },\n            { \".crl\", \"application/pkix-crl\" },\n            { \".crt\", \"application/x-x509-ca-cert\" },\n            { \".csh\", \"application/x-csh\" },\n            { \".css\", \"text/css\" },\n            { \".csv\", \"application/octet-stream\" },\n            { \".cur\", \"application/octet-stream\" },\n            { \".dcr\", \"application/x-director\" },\n            { \".deploy\", \"application/octet-stream\" },\n            { \".der\", \"application/x-x509-ca-cert\" },\n            { \".dib\", \"image/bmp\" },\n            { \".dir\", \"application/x-director\" },\n            { \".disco\", \"text/xml\" },\n            { \".dll\", \"application/x-msdownload\" },\n            { \".dll.config\", \"text/xml\" },\n            { \".dlm\", \"text/dlm\" },\n            { \".doc\", \"application/msword\" },\n            { \".docm\", \"application/vnd.ms-word.document.macroEnabled.12\" },\n            { \".docx\", \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\" },\n            { \".dot\", \"application/msword\" },\n            { \".dotm\", \"application/vnd.ms-word.template.macroEnabled.12\" },\n            { \".dotx\", \"application/vnd.openxmlformats-officedocument.wordprocessingml.template\" },\n            { \".dsp\", \"application/octet-stream\" },\n            { \".dtd\", \"text/xml\" },\n            { \".dvi\", \"application/x-dvi\" },\n            { \".dwf\", \"drawing/x-dwf\" },\n            { \".dwp\", \"application/octet-stream\" },\n            { \".dxr\", \"application/x-director\" },\n            { \".eml\", \"message/rfc822\" },\n            { \".emz\", \"application/octet-stream\" },\n            { \".eot\", \"application/octet-stream\" },\n            { \".eps\", \"application/postscript\" },\n            { \".etx\", \"text/x-setext\" },\n            { \".evy\", \"application/envoy\" },\n            { \".exe\", \"application/octet-stream\" },\n            { \".exe.config\", \"text/xml\" },\n            { \".fdf\", \"application/vnd.fdf\" },\n            { \".fif\", \"application/fractals\" },\n            { \".fla\", \"application/octet-stream\" },\n            { \".flr\", \"x-world/x-vrml\" },\n            { \".flv\", \"video/x-flv\" },\n            { \".gif\", \"image/gif\" },\n            { \".gtar\", \"application/x-gtar\" },\n            { \".gz\", \"application/x-gzip\" },\n            { \".h\", \"text/plain\" },\n            { \".hdf\", \"application/x-hdf\" },\n            { \".hdml\", \"text/x-hdml\" },\n            { \".hhc\", \"application/x-oleobject\" },\n            { \".hhk\", \"application/octet-stream\" },\n            { \".hhp\", \"application/octet-stream\" },\n            { \".hlp\", \"application/winhlp\" },\n            { \".hqx\", \"application/mac-binhex40\" },\n            { \".hta\", \"application/hta\" },\n            { \".htc\", \"text/x-component\" },\n            { \".htm\", \"text/html\" },\n            { \".html\", \"text/html\" },\n            { \".htt\", \"text/webviewhtml\" },\n            { \".hxt\", \"text/html\" },\n            { \".ico\", \"image/x-icon\" },\n            { \".ics\", \"application/octet-stream\" },\n            { \".ief\", \"image/ief\" },\n            { \".iii\", \"application/x-iphone\" },\n            { \".inf\", \"application/octet-stream\" },\n            { \".ins\", \"application/x-internet-signup\" },\n            { \".isp\", \"application/x-internet-signup\" },\n            { \".IVF\", \"video/x-ivf\" },\n            { \".jar\", \"application/java-archive\" },\n            { \".java\", \"application/octet-stream\" },\n            { \".jck\", \"application/liquidmotion\" },\n            { \".jcz\", \"application/liquidmotion\" },\n            { \".jfif\", \"image/pjpeg\" },\n            { \".jpb\", \"application/octet-stream\" },\n            { \".jpe\", \"image/jpeg\" },\n            { \".jpeg\", \"image/jpeg\" },\n            { \".jpg\", \"image/jpeg\" },\n            { \".js\", \"application/x-javascript\" },\n            { \".jsx\", \"text/jscript\" },\n            { \".latex\", \"application/x-latex\" },\n            { \".lit\", \"application/x-ms-reader\" },\n            { \".lpk\", \"application/octet-stream\" },\n            { \".lsf\", \"video/x-la-asf\" },\n            { \".lsx\", \"video/x-la-asf\" },\n            { \".lzh\", \"application/octet-stream\" },\n            { \".m13\", \"application/x-msmediaview\" },\n            { \".m14\", \"application/x-msmediaview\" },\n            { \".m1v\", \"video/mpeg\" },\n            { \".m3u\", \"audio/x-mpegurl\" },\n            { \".man\", \"application/x-troff-man\" },\n            { \".manifest\", \"application/x-ms-manifest\" },\n            { \".map\", \"text/plain\" },\n            { \".mdb\", \"application/x-msaccess\" },\n            { \".mdp\", \"application/octet-stream\" },\n            { \".me\", \"application/x-troff-me\" },\n            { \".mht\", \"message/rfc822\" },\n            { \".mhtml\", \"message/rfc822\" },\n            { \".mid\", \"audio/mid\" },\n            { \".midi\", \"audio/mid\" },\n            { \".mix\", \"application/octet-stream\" },\n            { \".mmf\", \"application/x-smaf\" },\n            { \".mno\", \"text/xml\" },\n            { \".mny\", \"application/x-msmoney\" },\n            { \".mov\", \"video/quicktime\" },\n            { \".movie\", \"video/x-sgi-movie\" },\n            { \".mp2\", \"video/mpeg\" },\n            { \".mp3\", \"audio/mpeg\" },\n            { \".mpa\", \"video/mpeg\" },\n            { \".mpe\", \"video/mpeg\" },\n            { \".mpeg\", \"video/mpeg\" },\n            { \".mpg\", \"video/mpeg\" },\n            { \".mpp\", \"application/vnd.ms-project\" },\n            { \".mpv2\", \"video/mpeg\" },\n            { \".ms\", \"application/x-troff-ms\" },\n            { \".msi\", \"application/octet-stream\" },\n            { \".mso\", \"application/octet-stream\" },\n            { \".mvb\", \"application/x-msmediaview\" },\n            { \".mvc\", \"application/x-miva-compiled\" },\n            { \".nc\", \"application/x-netcdf\" },\n            { \".nsc\", \"video/x-ms-asf\" },\n            { \".nws\", \"message/rfc822\" },\n            { \".ocx\", \"application/octet-stream\" },\n            { \".oda\", \"application/oda\" },\n            { \".odc\", \"text/x-ms-odc\" },\n            { \".ods\", \"application/oleobject\" },\n            { \".one\", \"application/onenote\" },\n            { \".onea\", \"application/onenote\" },\n            { \".onetoc\", \"application/onenote\" },\n            { \".onetoc2\", \"application/onenote\" },\n            { \".onetmp\", \"application/onenote\" },\n            { \".onepkg\", \"application/onenote\" },\n            { \".osdx\", \"application/opensearchdescription+xml\" },\n            { \".p10\", \"application/pkcs10\" },\n            { \".p12\", \"application/x-pkcs12\" },\n            { \".p7b\", \"application/x-pkcs7-certificates\" },\n            { \".p7c\", \"application/pkcs7-mime\" },\n            { \".p7m\", \"application/pkcs7-mime\" },\n            { \".p7r\", \"application/x-pkcs7-certreqresp\" },\n            { \".p7s\", \"application/pkcs7-signature\" },\n            { \".pbm\", \"image/x-portable-bitmap\" },\n            { \".pcx\", \"application/octet-stream\" },\n            { \".pcz\", \"application/octet-stream\" },\n            { \".pdf\", \"application/pdf\" },\n            { \".pfb\", \"application/octet-stream\" },\n            { \".pfm\", \"application/octet-stream\" },\n            { \".pfx\", \"application/x-pkcs12\" },\n            { \".pgm\", \"image/x-portable-graymap\" },\n            { \".pko\", \"application/vnd.ms-pki.pko\" },\n            { \".pma\", \"application/x-perfmon\" },\n            { \".pmc\", \"application/x-perfmon\" },\n            { \".pml\", \"application/x-perfmon\" },\n            { \".pmr\", \"application/x-perfmon\" },\n            { \".pmw\", \"application/x-perfmon\" },\n            { \".png\", \"image/png\" },\n            { \".pnm\", \"image/x-portable-anymap\" },\n            { \".pnz\", \"image/png\" },\n            { \".pot\", \"application/vnd.ms-powerpoint\" },\n            { \".potm\", \"application/vnd.ms-powerpoint.template.macroEnabled.12\" },\n            { \".potx\", \"application/vnd.openxmlformats-officedocument.presentationml.template\" },\n            { \".ppam\", \"application/vnd.ms-powerpoint.addin.macroEnabled.12\" },\n            { \".ppm\", \"image/x-portable-pixmap\" },\n            { \".pps\", \"application/vnd.ms-powerpoint\" },\n            { \".ppsm\", \"application/vnd.ms-powerpoint.slideshow.macroEnabled.12\" },\n            { \".ppsx\", \"application/vnd.openxmlformats-officedocument.presentationml.slideshow\" },\n            { \".ppt\", \"application/vnd.ms-powerpoint\" },\n            { \".pptm\", \"application/vnd.ms-powerpoint.presentation.macroEnabled.12\" },\n            { \".pptx\", \"application/vnd.openxmlformats-officedocument.presentationml.presentation\" },\n            { \".prf\", \"application/pics-rules\" },\n            { \".prm\", \"application/octet-stream\" },\n            { \".prx\", \"application/octet-stream\" },\n            { \".ps\", \"application/postscript\" },\n            { \".psd\", \"application/octet-stream\" },\n            { \".psm\", \"application/octet-stream\" },\n            { \".psp\", \"application/octet-stream\" },\n            { \".pub\", \"application/x-mspublisher\" },\n            { \".qt\", \"video/quicktime\" },\n            { \".qtl\", \"application/x-quicktimeplayer\" },\n            { \".qxd\", \"application/octet-stream\" },\n            { \".ra\", \"audio/x-pn-realaudio\" },\n            { \".ram\", \"audio/x-pn-realaudio\" },\n            { \".rar\", \"application/octet-stream\" },\n            { \".ras\", \"image/x-cmu-raster\" },\n            { \".rf\", \"image/vnd.rn-realflash\" },\n            { \".rgb\", \"image/x-rgb\" },\n            { \".rm\", \"application/vnd.rn-realmedia\" },\n            { \".rmi\", \"audio/mid\" },\n            { \".roff\", \"application/x-troff\" },\n            { \".rpm\", \"audio/x-pn-realaudio-plugin\" },\n            { \".rtf\", \"application/rtf\" },\n            { \".rtx\", \"text/richtext\" },\n            { \".scd\", \"application/x-msschedule\" },\n            { \".sct\", \"text/scriptlet\" },\n            { \".sea\", \"application/octet-stream\" },\n            { \".setpay\", \"application/set-payment-initiation\" },\n            { \".setreg\", \"application/set-registration-initiation\" },\n            { \".sgml\", \"text/sgml\" },\n            { \".sh\", \"application/x-sh\" },\n            { \".shar\", \"application/x-shar\" },\n            { \".sit\", \"application/x-stuffit\" },\n            { \".sldm\", \"application/vnd.ms-powerpoint.slide.macroEnabled.12\" },\n            { \".sldx\", \"application/vnd.openxmlformats-officedocument.presentationml.slide\" },\n            { \".smd\", \"audio/x-smd\" },\n            { \".smi\", \"application/octet-stream\" },\n            { \".smx\", \"audio/x-smd\" },\n            { \".smz\", \"audio/x-smd\" },\n            { \".snd\", \"audio/basic\" },\n            { \".snp\", \"application/octet-stream\" },\n            { \".spc\", \"application/x-pkcs7-certificates\" },\n            { \".spl\", \"application/futuresplash\" },\n            { \".src\", \"application/x-wais-source\" },\n            { \".ssm\", \"application/streamingmedia\" },\n            { \".sst\", \"application/vnd.ms-pki.certstore\" },\n            { \".stl\", \"application/vnd.ms-pki.stl\" },\n            { \".sv4cpio\", \"application/x-sv4cpio\" },\n            { \".sv4crc\", \"application/x-sv4crc\" },\n            { \".swf\", \"application/x-shockwave-flash\" },\n            { \".t\", \"application/x-troff\" },\n            { \".tar\", \"application/x-tar\" },\n            { \".tcl\", \"application/x-tcl\" },\n            { \".tex\", \"application/x-tex\" },\n            { \".texi\", \"application/x-texinfo\" },\n            { \".texinfo\", \"application/x-texinfo\" },\n            { \".tgz\", \"application/x-compressed\" },\n            { \".thmx\", \"application/vnd.ms-officetheme\" },\n            { \".thn\", \"application/octet-stream\" },\n            { \".tif\", \"image/tiff\" },\n            { \".tiff\", \"image/tiff\" },\n            { \".toc\", \"application/octet-stream\" },\n            { \".tr\", \"application/x-troff\" },\n            { \".trm\", \"application/x-msterminal\" },\n            { \".tsv\", \"text/tab-separated-values\" },\n            { \".ttf\", \"application/octet-stream\" },\n            { \".txt\", \"text/plain\" },\n            { \".u32\", \"application/octet-stream\" },\n            { \".uls\", \"text/iuls\" },\n            { \".ustar\", \"application/x-ustar\" },\n            { \".vbs\", \"text/vbscript\" },\n            { \".vcf\", \"text/x-vcard\" },\n            { \".vcs\", \"text/plain\" },\n            { \".vdx\", \"application/vnd.ms-visio.viewer\" },\n            { \".vml\", \"text/xml\" },\n            { \".vsd\", \"application/vnd.visio\" },\n            { \".vss\", \"application/vnd.visio\" },\n            { \".vst\", \"application/vnd.visio\" },\n            { \".vsto\", \"application/x-ms-vsto\" },\n            { \".vsw\", \"application/vnd.visio\" },\n            { \".vsx\", \"application/vnd.visio\" },\n            { \".vtx\", \"application/vnd.visio\" },\n            { \".wav\", \"audio/wav\" },\n            { \".wax\", \"audio/x-ms-wax\" },\n            { \".wbmp\", \"image/vnd.wap.wbmp\" },\n            { \".wcm\", \"application/vnd.ms-works\" },\n            { \".wdb\", \"application/vnd.ms-works\" },\n            { \".wks\", \"application/vnd.ms-works\" },\n            { \".wm\", \"video/x-ms-wm\" },\n            { \".wma\", \"audio/x-ms-wma\" },\n            { \".wmd\", \"application/x-ms-wmd\" },\n            { \".wmf\", \"application/x-msmetafile\" },\n            { \".wml\", \"text/vnd.wap.wml\" },\n            { \".wmlc\", \"application/vnd.wap.wmlc\" },\n            { \".wmls\", \"text/vnd.wap.wmlscript\" },\n            { \".wmlsc\", \"application/vnd.wap.wmlscriptc\" },\n            { \".wmp\", \"video/x-ms-wmp\" },\n            { \".wmv\", \"video/x-ms-wmv\" },\n            { \".wmx\", \"video/x-ms-wmx\" },\n            { \".wmz\", \"application/x-ms-wmz\" },\n            { \".wps\", \"application/vnd.ms-works\" },\n            { \".wri\", \"application/x-mswrite\" },\n            { \".wrl\", \"x-world/x-vrml\" },\n            { \".wrz\", \"x-world/x-vrml\" },\n            { \".wsdl\", \"text/xml\" },\n            { \".wvx\", \"video/x-ms-wvx\" },\n            { \".x\", \"application/directx\" },\n            { \".xaf\", \"x-world/x-vrml\" },\n            { \".xaml\", \"application/xaml+xml\" },\n            { \".xap\", \"application/x-silverlight-app\" },\n            { \".xbap\", \"application/x-ms-xbap\" },\n            { \".xbm\", \"image/x-xbitmap\" },\n            { \".xdr\", \"text/plain\" },\n            { \".xla\", \"application/vnd.ms-excel\" },\n            { \".xlam\", \"application/vnd.ms-excel.addin.macroEnabled.12\" },\n            { \".xlc\", \"application/vnd.ms-excel\" },\n            { \".xlm\", \"application/vnd.ms-excel\" },\n            { \".xls\", \"application/vnd.ms-excel\" },\n            { \".xlsb\", \"application/vnd.ms-excel.sheet.binary.macroEnabled.12\" },\n            { \".xlsm\", \"application/vnd.ms-excel.sheet.macroEnabled.12\" },\n            { \".xlsx\", \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\" },\n            { \".xlt\", \"application/vnd.ms-excel\" },\n            { \".xltm\", \"application/vnd.ms-excel.template.macroEnabled.12\" },\n            { \".xltx\", \"application/vnd.openxmlformats-officedocument.spreadsheetml.template\" },\n            { \".xlw\", \"application/vnd.ms-excel\" },\n            { \".xml\", \"text/xml\" },\n            { \".xof\", \"x-world/x-vrml\" },\n            { \".xpm\", \"image/x-xpixmap\" },\n            { \".xps\", \"application/vnd.ms-xpsdocument\" },\n            { \".xsd\", \"text/xml\" },\n            { \".xsf\", \"text/xml\" },\n            { \".xsl\", \"text/xml\" },\n            { \".xslt\", \"text/xml\" },\n            { \".xsn\", \"application/octet-stream\" },\n            { \".xtp\", \"application/octet-stream\" },\n            { \".xwd\", \"image/x-xwindowdump\" },\n            { \".z\", \"application/x-compress\" },\n            { \".zip\", \"application/x-zip-compressed\" }\n        };\n\n        internal static string GetMimeMapping(string fileName)\n        {\n            if (fileName == null)\n            {\n                throw new ArgumentNullException(\"fileName\");\n            }\n\n            string contentType = null;\n            string extension = Path.GetExtension(fileName);\n            if (_mimeMappings.TryGetValue(extension, out contentType))\n            {\n                return contentType;\n            }\n            return _mimeMappings[\".*\"];\n        }\n\n        internal static void AddMimeMapping(string extension, string mimeType)\n        {\n            _mimeMappings.Add(extension, mimeType);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Mvc/HttpAntiForgeryException.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.Serialization;\nusing System.Web.WebPages.Resources;\n\nnamespace System.Web.Mvc\n{\n    [Serializable]\n    [TypeForwardedFrom(\"System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\")]\n    public sealed class HttpAntiForgeryException : HttpException\n    {\n        public HttpAntiForgeryException()\n        {\n        }\n\n        private HttpAntiForgeryException(SerializationInfo info, StreamingContext context)\n            : base(info, context)\n        {\n        }\n\n        public HttpAntiForgeryException(string message)\n            : base(message)\n        {\n        }\n\n        private HttpAntiForgeryException(string message, params object[] args)\n            : this(String.Format(CultureInfo.CurrentCulture, message, args))\n        {\n        }\n\n        public HttpAntiForgeryException(string message, Exception innerException)\n            : base(message, innerException)\n        {\n        }\n\n        internal static HttpAntiForgeryException CreateAdditionalDataCheckFailedException()\n        {\n            return new HttpAntiForgeryException(WebPageResources.AntiForgeryToken_AdditionalDataCheckFailed);\n        }\n\n        internal static HttpAntiForgeryException CreateClaimUidMismatchException()\n        {\n            return new HttpAntiForgeryException(WebPageResources.AntiForgeryToken_ClaimUidMismatch);\n        }\n\n        internal static HttpAntiForgeryException CreateCookieMissingException(string cookieName)\n        {\n            return new HttpAntiForgeryException(WebPageResources.AntiForgeryToken_CookieMissing, cookieName);\n        }\n\n        internal static HttpAntiForgeryException CreateDeserializationFailedException()\n        {\n            return new HttpAntiForgeryException(WebPageResources.AntiForgeryToken_DeserializationFailed);\n        }\n\n        internal static HttpAntiForgeryException CreateFormFieldMissingException(string formFieldName)\n        {\n            return new HttpAntiForgeryException(WebPageResources.AntiForgeryToken_FormFieldMissing, formFieldName);\n        }\n\n        internal static HttpAntiForgeryException CreateSecurityTokenMismatchException()\n        {\n            return new HttpAntiForgeryException(WebPageResources.AntiForgeryToken_SecurityTokenMismatch);\n        }\n\n        internal static HttpAntiForgeryException CreateTokensSwappedException(string cookieName, string formFieldName)\n        {\n            return new HttpAntiForgeryException(WebPageResources.AntiForgeryToken_TokensSwapped, cookieName, formFieldName);\n        }\n\n        internal static HttpAntiForgeryException CreateUsernameMismatchException(string usernameInToken, string currentUsername)\n        {\n            return new HttpAntiForgeryException(WebPageResources.AntiForgeryToken_UsernameMismatch, usernameInToken, currentUsername);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Mvc/ModelClientValidationEqualToRule.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Runtime.CompilerServices;\n\nnamespace System.Web.Mvc\n{\n    [TypeForwardedFrom(\"System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\")]\n    public class ModelClientValidationEqualToRule : ModelClientValidationRule\n    {\n        public ModelClientValidationEqualToRule(string errorMessage, object other)\n        {\n            ErrorMessage = errorMessage;\n            ValidationType = \"equalto\";\n            ValidationParameters[\"other\"] = other;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Mvc/ModelClientValidationMaxLengthRule.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public class ModelClientValidationMaxLengthRule : ModelClientValidationRule\n    {\n        public ModelClientValidationMaxLengthRule(string errorMessage, int maximumLength)\n        {\n            ErrorMessage = errorMessage;\n            ValidationType = \"maxlength\";\n            ValidationParameters[\"max\"] = maximumLength;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Mvc/ModelClientValidationMembershipPasswordRule.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    internal class ModelClientValidationMembershipPasswordRule : ModelClientValidationRule\n    {\n        public ModelClientValidationMembershipPasswordRule(string errorMessage, int minRequiredPasswordLength, int minRequiredNonAlphanumericCharacters, string passwordStrengthRegularExpression)\n        {\n            ErrorMessage = errorMessage;\n            ValidationType = \"password\";\n\n            if (minRequiredPasswordLength != 0)\n            {\n                ValidationParameters[\"min\"] = minRequiredPasswordLength;\n            }\n\n            if (minRequiredNonAlphanumericCharacters != 0)\n            {\n                ValidationParameters[\"nonalphamin\"] = minRequiredNonAlphanumericCharacters;\n            }\n\n            if (!String.IsNullOrEmpty(passwordStrengthRegularExpression))\n            {\n                ValidationParameters[\"regex\"] = passwordStrengthRegularExpression;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Mvc/ModelClientValidationMinLengthRule.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc\n{\n    public class ModelClientValidationMinLengthRule : ModelClientValidationRule\n    {\n        public ModelClientValidationMinLengthRule(string errorMessage, int minimumLength)\n        {\n            ErrorMessage = errorMessage;\n            ValidationType = \"minlength\";\n            ValidationParameters[\"min\"] = minimumLength;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Mvc/ModelClientValidationRangeRule.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Runtime.CompilerServices;\n\nnamespace System.Web.Mvc\n{\n    [TypeForwardedFrom(\"System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\")]\n    public class ModelClientValidationRangeRule : ModelClientValidationRule\n    {\n        public ModelClientValidationRangeRule(string errorMessage, object minValue, object maxValue)\n        {\n            ErrorMessage = errorMessage;\n            ValidationType = \"range\";\n            ValidationParameters[\"min\"] = minValue;\n            ValidationParameters[\"max\"] = maxValue;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Mvc/ModelClientValidationRegexRule.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Runtime.CompilerServices;\n\nnamespace System.Web.Mvc\n{\n    [TypeForwardedFrom(\"System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\")]\n    public class ModelClientValidationRegexRule : ModelClientValidationRule\n    {\n        public ModelClientValidationRegexRule(string errorMessage, string pattern)\n        {\n            ErrorMessage = errorMessage;\n            ValidationType = \"regex\";\n            ValidationParameters.Add(\"pattern\", pattern);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Mvc/ModelClientValidationRemoteRule.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Runtime.CompilerServices;\n\nnamespace System.Web.Mvc\n{\n    [TypeForwardedFrom(\"System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\")]\n    public class ModelClientValidationRemoteRule : ModelClientValidationRule\n    {\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", Justification = \"The value is a not a regular URL since it may contain ~/ ASP.NET-specific characters\")]\n        public ModelClientValidationRemoteRule(string errorMessage, string url, string httpMethod, string additionalFields)\n        {\n            ErrorMessage = errorMessage;\n            ValidationType = \"remote\";\n            ValidationParameters[\"url\"] = url;\n\n            if (!String.IsNullOrEmpty(httpMethod))\n            {\n                ValidationParameters[\"type\"] = httpMethod;\n            }\n\n            ValidationParameters[\"additionalfields\"] = additionalFields;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Mvc/ModelClientValidationRequiredRule.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Runtime.CompilerServices;\n\nnamespace System.Web.Mvc\n{\n    [TypeForwardedFrom(\"System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\")]\n    public class ModelClientValidationRequiredRule : ModelClientValidationRule\n    {\n        public ModelClientValidationRequiredRule(string errorMessage)\n        {\n            ErrorMessage = errorMessage;\n            ValidationType = \"required\";\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Mvc/ModelClientValidationRule.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Runtime.CompilerServices;\n\nnamespace System.Web.Mvc\n{\n    [TypeForwardedFrom(\"System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\")]\n    public class ModelClientValidationRule\n    {\n        private readonly Dictionary<string, object> _validationParameters = new Dictionary<string, object>();\n        private string _validationType;\n\n        public string ErrorMessage { get; set; }\n\n        public IDictionary<string, object> ValidationParameters\n        {\n            get { return _validationParameters; }\n        }\n\n        public string ValidationType\n        {\n            get { return _validationType ?? String.Empty; }\n            set { _validationType = value; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Mvc/ModelClientValidationStringLengthRule.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Runtime.CompilerServices;\n\nnamespace System.Web.Mvc\n{\n    [TypeForwardedFrom(\"System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\")]\n    public class ModelClientValidationStringLengthRule : ModelClientValidationRule\n    {\n        public ModelClientValidationStringLengthRule(string errorMessage, int minimumLength, int maximumLength)\n        {\n            ErrorMessage = errorMessage;\n            ValidationType = \"length\";\n\n            if (minimumLength != 0)\n            {\n                ValidationParameters[\"min\"] = minimumLength;\n            }\n\n            if (maximumLength != Int32.MaxValue)\n            {\n                ValidationParameters[\"max\"] = maximumLength;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Mvc/TagBuilder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Runtime.CompilerServices;\nusing System.Text;\nusing System.Web.WebPages.Html;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Mvc\n{\n    [TypeForwardedFrom(\"System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\")]\n    public class TagBuilder\n    {\n        private string _idAttributeDotReplacement;\n\n        private string _innerHtml;\n\n        public TagBuilder(string tagName)\n        {\n            if (String.IsNullOrEmpty(tagName))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"tagName\");\n            }\n\n            TagName = tagName;\n            Attributes = new SortedDictionary<string, string>(StringComparer.Ordinal);\n        }\n\n        public IDictionary<string, string> Attributes { get; private set; }\n\n        public string IdAttributeDotReplacement\n        {\n            get\n            {\n                if (String.IsNullOrEmpty(_idAttributeDotReplacement))\n                {\n                    _idAttributeDotReplacement = HtmlHelper.IdAttributeDotReplacement;\n                }\n                return _idAttributeDotReplacement;\n            }\n            set { _idAttributeDotReplacement = value; }\n        }\n\n        public string InnerHtml\n        {\n            get { return _innerHtml ?? String.Empty; }\n            set { _innerHtml = value; }\n        }\n\n        public string TagName { get; private set; }\n\n        public void AddCssClass(string value)\n        {\n            string currentValue;\n\n            if (Attributes.TryGetValue(\"class\", out currentValue))\n            {\n                Attributes[\"class\"] = value + \" \" + currentValue;\n            }\n            else\n            {\n                Attributes[\"class\"] = value;\n            }\n        }\n\n        public static string CreateSanitizedId(string originalId)\n        {\n            return CreateSanitizedId(originalId, HtmlHelper.IdAttributeDotReplacement);\n        }\n\n        public static string CreateSanitizedId(string originalId, string invalidCharReplacement)\n        {\n            if (String.IsNullOrEmpty(originalId))\n            {\n                return null;\n            }\n\n            if (invalidCharReplacement == null)\n            {\n                throw new ArgumentNullException(\"invalidCharReplacement\");\n            }\n\n            char firstChar = originalId[0];\n            if (!Html401IdUtil.IsLetter(firstChar))\n            {\n                // the first character must be a letter\n                return null;\n            }\n\n            StringBuilder sb = new StringBuilder(originalId.Length);\n            sb.Append(firstChar);\n\n            for (int i = 1; i < originalId.Length; i++)\n            {\n                char thisChar = originalId[i];\n                if (Html401IdUtil.IsValidIdCharacter(thisChar))\n                {\n                    sb.Append(thisChar);\n                }\n                else\n                {\n                    sb.Append(invalidCharReplacement);\n                }\n            }\n\n            return sb.ToString();\n        }\n\n        public void GenerateId(string name)\n        {\n            if (!Attributes.ContainsKey(\"id\"))\n            {\n                string sanitizedId = CreateSanitizedId(name, IdAttributeDotReplacement);\n                if (!String.IsNullOrEmpty(sanitizedId))\n                {\n                    Attributes[\"id\"] = sanitizedId;\n                }\n            }\n        }\n\n        private void AppendAttributes(StringBuilder sb)\n        {\n            foreach (var attribute in Attributes)\n            {\n                string key = attribute.Key;\n                if (String.Equals(key, \"id\", StringComparison.Ordinal /* case-sensitive */) && String.IsNullOrEmpty(attribute.Value))\n                {\n                    continue; // DevDiv Bugs #227595: don't output empty IDs\n                }\n                string value = HttpUtility.HtmlAttributeEncode(attribute.Value);\n                sb.Append(' ')\n                    .Append(key)\n                    .Append(\"=\\\"\")\n                    .Append(value)\n                    .Append('\"');\n            }\n        }\n\n        public void MergeAttribute(string key, string value)\n        {\n            MergeAttribute(key, value, replaceExisting: false);\n        }\n\n        public void MergeAttribute(string key, string value, bool replaceExisting)\n        {\n            if (String.IsNullOrEmpty(key))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"key\");\n            }\n\n            if (replaceExisting || !Attributes.ContainsKey(key))\n            {\n                Attributes[key] = value;\n            }\n        }\n\n        public void MergeAttributes<TKey, TValue>(IDictionary<TKey, TValue> attributes)\n        {\n            MergeAttributes(attributes, replaceExisting: false);\n        }\n\n        public void MergeAttributes<TKey, TValue>(IDictionary<TKey, TValue> attributes, bool replaceExisting)\n        {\n            if (attributes != null)\n            {\n                foreach (var entry in attributes)\n                {\n                    string key = Convert.ToString(entry.Key, CultureInfo.InvariantCulture);\n                    string value = Convert.ToString(entry.Value, CultureInfo.InvariantCulture);\n                    MergeAttribute(key, value, replaceExisting);\n                }\n            }\n        }\n\n        public void SetInnerText(string innerText)\n        {\n            InnerHtml = HttpUtility.HtmlEncode(innerText);\n        }\n\n        internal HtmlString ToHtmlString(TagRenderMode renderMode)\n        {\n            return new HtmlString(ToString(renderMode));\n        }\n\n        public override string ToString()\n        {\n            return ToString(TagRenderMode.Normal);\n        }\n\n        public string ToString(TagRenderMode renderMode)\n        {\n            StringBuilder sb = new StringBuilder();\n            switch (renderMode)\n            {\n                case TagRenderMode.StartTag:\n                    sb.Append('<')\n                        .Append(TagName);\n                    AppendAttributes(sb);\n                    sb.Append('>');\n                    break;\n                case TagRenderMode.EndTag:\n                    sb.Append(\"</\")\n                        .Append(TagName)\n                        .Append('>');\n                    break;\n                case TagRenderMode.SelfClosing:\n                    sb.Append('<')\n                        .Append(TagName);\n                    AppendAttributes(sb);\n                    sb.Append(\" />\");\n                    break;\n                default:\n                    sb.Append('<')\n                        .Append(TagName);\n                    AppendAttributes(sb);\n                    sb.Append('>')\n                        .Append(InnerHtml)\n                        .Append(\"</\")\n                        .Append(TagName)\n                        .Append('>');\n                    break;\n            }\n            return sb.ToString();\n        }\n\n        // Valid IDs are defined in http://www.w3.org/TR/html401/types.html#type-id\n        private static class Html401IdUtil\n        {\n            private static bool IsAllowableSpecialCharacter(char c)\n            {\n                switch (c)\n                {\n                    case '-':\n                    case '_':\n                    case ':':\n                        // note that we're specifically excluding the '.' character\n                        return true;\n\n                    default:\n                        return false;\n                }\n            }\n\n            private static bool IsDigit(char c)\n            {\n                return ('0' <= c && c <= '9');\n            }\n\n            public static bool IsLetter(char c)\n            {\n                return (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z'));\n            }\n\n            public static bool IsValidIdCharacter(char c)\n            {\n                return (IsLetter(c) || IsDigit(c) || IsAllowableSpecialCharacter(c));\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Mvc/TagRenderMode.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Runtime.CompilerServices;\n\nnamespace System.Web.Mvc\n{\n    [TypeForwardedFrom(\"System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\")]\n    public enum TagRenderMode\n    {\n        Normal,\n        StartTag,\n        EndTag,\n        SelfClosing\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Mvc/UnobtrusiveValidationAttributesGenerator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Web.WebPages.Resources;\n\nnamespace System.Web.Mvc\n{\n    public static class UnobtrusiveValidationAttributesGenerator\n    {\n        public static void GetValidationAttributes(IEnumerable<ModelClientValidationRule> clientRules, IDictionary<string, object> results)\n        {\n            if (clientRules == null)\n            {\n                throw new ArgumentNullException(\"clientRules\");\n            }\n            if (results == null)\n            {\n                throw new ArgumentNullException(\"results\");\n            }\n\n            bool renderedRules = false;\n\n            foreach (ModelClientValidationRule rule in clientRules)\n            {\n                renderedRules = true;\n                string ruleName = \"data-val-\" + rule.ValidationType;\n\n                ValidateUnobtrusiveValidationRule(rule, results, ruleName);\n\n                results.Add(ruleName, rule.ErrorMessage ?? String.Empty);\n                ruleName += \"-\";\n\n                foreach (var kvp in rule.ValidationParameters)\n                {\n                    results.Add(ruleName + kvp.Key, kvp.Value ?? String.Empty);\n                }\n            }\n\n            if (renderedRules)\n            {\n                results.Add(\"data-val\", \"true\");\n            }\n        }\n\n        private static void ValidateUnobtrusiveValidationRule(ModelClientValidationRule rule, IDictionary<string, object> resultsDictionary, string dictionaryKey)\n        {\n            if (String.IsNullOrWhiteSpace(rule.ValidationType))\n            {\n                throw new InvalidOperationException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        WebPageResources.UnobtrusiveJavascript_ValidationTypeCannotBeEmpty,\n                        rule.GetType().FullName));\n            }\n\n            if (resultsDictionary.ContainsKey(dictionaryKey))\n            {\n                throw new InvalidOperationException(\n                    String.Format(\n                        CultureInfo.CurrentCulture,\n                        WebPageResources.UnobtrusiveJavascript_ValidationTypeMustBeUnique,\n                        rule.ValidationType));\n            }\n\n            if (rule.ValidationType.Any(c => !Char.IsLower(c)))\n            {\n                throw new InvalidOperationException(\n                    String.Format(CultureInfo.CurrentCulture, WebPageResources.UnobtrusiveJavascript_ValidationTypeMustBeLegal,\n                                  rule.ValidationType,\n                                  rule.GetType().FullName));\n            }\n\n            foreach (var key in rule.ValidationParameters.Keys)\n            {\n                if (String.IsNullOrWhiteSpace(key))\n                {\n                    throw new InvalidOperationException(\n                        String.Format(\n                            CultureInfo.CurrentCulture,\n                            WebPageResources.UnobtrusiveJavascript_ValidationParameterCannotBeEmpty,\n                            rule.GetType().FullName));\n                }\n\n                if (!Char.IsLower(key.First()) || key.Any(c => !Char.IsLower(c) && !Char.IsDigit(c)))\n                {\n                    throw new InvalidOperationException(\n                        String.Format(\n                            CultureInfo.CurrentCulture,\n                            WebPageResources.UnobtrusiveJavascript_ValidationParameterMustBeLegal,\n                            key,\n                            rule.GetType().FullName));\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/PageDataDictionary.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\n\nnamespace System.Web.WebPages\n{\n    /// <summary>\n    /// This is a wrapper around Dictionary so that using PageData[key] returns null\n    /// if the key is not found, instead of throwing an exception.\n    /// </summary>\n    // This is a generic type because C# does not allow implementing an interface \n    // involving dynamic types (implementing IDictionary<object, dynamic> causes\n    // a compile error \n    // http://blogs.msdn.com/cburrows/archive/2009/02/04/c-dynamic-part-vii.aspx).\n    internal class PageDataDictionary<TValue> : IDictionary<object, TValue>\n    {\n        private IDictionary<object, TValue> _data = new Dictionary<object, TValue>(new PageDataComparer());\n\n        private IDictionary<string, TValue> _stringDictionary = new Dictionary<string, TValue>(StringComparer.OrdinalIgnoreCase);\n\n        private IList<TValue> _indexedValues = new List<TValue>();\n\n        internal IDictionary<object, TValue> Data\n        {\n            get { return _data; }\n        }\n\n        internal IDictionary<string, TValue> StringDictionary\n        {\n            get { return _stringDictionary; }\n        }\n\n        internal IList<TValue> IndexedValues\n        {\n            get { return _indexedValues; }\n        }\n\n        public ICollection<object> Keys\n        {\n            get\n            {\n                List<object> keys = new List<object>();\n                keys.AddRange(_stringDictionary.Keys);\n                for (int i = 0; i < _indexedValues.Count; i++)\n                {\n                    keys.Add(i);\n                }\n                foreach (var key in _data.Keys)\n                {\n                    if (!ContainsIndex(key) && !ContainsStringKey(key))\n                    {\n                        keys.Add(key);\n                    }\n                }\n                return keys;\n            }\n        }\n\n        public ICollection<TValue> Values\n        {\n            get\n            {\n                List<TValue> values = new List<TValue>();\n                foreach (var key in Keys)\n                {\n                    values.Add(this[key]);\n                }\n                return values;\n            }\n        }\n\n        internal ICollection<KeyValuePair<object, TValue>> Items\n        {\n            get\n            {\n                var items = new List<KeyValuePair<object, TValue>>();\n                foreach (var key in Keys)\n                {\n                    var value = this[key];\n                    var kvp = new KeyValuePair<object, TValue>(key, value);\n                    items.Add(kvp);\n                }\n                return items;\n            }\n        }\n\n        public int Count\n        {\n            get { return Items.Count; }\n        }\n\n        public bool IsReadOnly\n        {\n            get { return false; }\n        }\n\n        public TValue this[object key]\n        {\n            get\n            {\n                TValue v = default(TValue);\n                TryGetValue(key, out v);\n                return v;\n            }\n\n            // Note that this affects and updates the string dictionary and indexed list\n            // only for existing keys found in these collections. \n            // Otherwise, the key/value goes into the _data dictionary.\n            set\n            {\n                if (ContainsStringKey(key))\n                {\n                    _stringDictionary[(string)key] = value;\n                }\n                else if (ContainsIndex(key))\n                {\n                    _indexedValues[(int)key] = value;\n                }\n                else\n                {\n                    _data[key] = value;\n                }\n            }\n        }\n\n        public void Add(object key, TValue value)\n        {\n            _data.Add(key, value);\n        }\n\n        internal bool ContainsIndex(object o)\n        {\n            if (o is int)\n            {\n                return ContainsIndex((int)o);\n            }\n            else\n            {\n                return false;\n            }\n        }\n\n        internal bool ContainsIndex(int index)\n        {\n            return _indexedValues.Count > index && index >= 0;\n        }\n\n        internal bool ContainsStringKey(object o)\n        {\n            string s = o as string;\n            if (s != null)\n            {\n                return ContainsStringKey(s);\n            }\n            else\n            {\n                return false;\n            }\n        }\n\n        internal bool ContainsStringKey(string key)\n        {\n            return _stringDictionary.ContainsKey(key);\n        }\n\n        public bool ContainsKey(object key)\n        {\n            if (ContainsIndex(key))\n            {\n                return true;\n            }\n            else if (ContainsStringKey(key))\n            {\n                return true;\n            }\n            else if (_data.ContainsKey(key))\n            {\n                return true;\n            }\n            else\n            {\n                return false;\n            }\n        }\n\n        // Note that if the key exists in more than one place, then only\n        // the string dictionary and the indexed list will be updated.\n        public bool Remove(object key)\n        {\n            if (ContainsStringKey(key))\n            {\n                return _stringDictionary.Remove((string)key);\n            }\n            else if (ContainsIndex(key))\n            {\n                return _indexedValues.Remove(_indexedValues[(int)key]);\n            }\n            else\n            {\n                return _data.Remove(key);\n            }\n        }\n\n        public bool TryGetValue(object key, out TValue value)\n        {\n            if (ContainsStringKey(key))\n            {\n                return _stringDictionary.TryGetValue((string)key, out value);\n            }\n            else if (ContainsIndex(key))\n            {\n                value = _indexedValues[(int)key];\n                return true;\n            }\n            else\n            {\n                return _data.TryGetValue(key, out value);\n            }\n        }\n\n        public void Add(KeyValuePair<object, TValue> item)\n        {\n            this[item.Key] = item.Value;\n        }\n\n        public void Clear()\n        {\n            _stringDictionary.Clear();\n            _indexedValues.Clear();\n            _data.Clear();\n        }\n\n        public bool Contains(KeyValuePair<object, TValue> item)\n        {\n            return ContainsKey(item.Key) && Values.Contains(item.Value);\n        }\n\n        public void CopyTo(KeyValuePair<object, TValue>[] array, int arrayIndex)\n        {\n            Items.CopyTo(array, arrayIndex);\n        }\n\n        public bool Remove(KeyValuePair<object, TValue> item)\n        {\n            if (Contains(item))\n            {\n                return Remove((object)item.Key);\n            }\n            return false;\n        }\n\n        public IEnumerator<KeyValuePair<object, TValue>> GetEnumerator()\n        {\n            return Items.GetEnumerator();\n        }\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return Items.GetEnumerator();\n        }\n\n        // Creates a new PageData dictionary using only the original items from the pageData (excluding the string dictionary and indexed list),\n        // and adding the parameters.\n        internal static IDictionary<object, dynamic> CreatePageDataFromParameters(IDictionary<object, dynamic> previousPageData, params object[] data)\n        {\n            var oldPageData = previousPageData as PageDataDictionary<dynamic>;\n\n            // Add the original items\n            var pageData = new PageDataDictionary<dynamic>();\n            foreach (var kvp in oldPageData.Data)\n            {\n                pageData.Data.Add(kvp);\n            }\n\n            if (data != null && data.Length > 0)\n            {\n                // Add items to the indexed list\n                for (int i = 0; i < data.Length; i++)\n                {\n                    pageData.IndexedValues.Add(data[i]);\n                }\n\n                // Check for anonymous types, and add to the string dictionary\n                object first = data[0];\n                Type type = first.GetType();\n                if (TypeHelper.IsAnonymousType(type))\n                {\n                    // Anonymous type\n                    TypeHelper.AddAnonymousObjectToDictionary(pageData.StringDictionary, first);\n                }\n\n                // Check if the first element is of type IDictionary<string, object>\n                if (typeof(IDictionary<string, object>).IsAssignableFrom(type))\n                {\n                    // Dictionary\n                    var stringDictionary = first as IDictionary<string, object>;\n                    foreach (var kvp in stringDictionary)\n                    {\n                        pageData.StringDictionary.Add(kvp);\n                    }\n                }\n            }\n\n            return pageData;\n        }\n\n        // This comparer treats only strings as case-insensitive, but still handles objects\n        // of other types as well.\n        private sealed class PageDataComparer : IEqualityComparer<object>\n        {\n            bool IEqualityComparer<object>.Equals(object x, object y)\n            {\n                var s1 = x as string;\n                var s2 = y as string;\n                if (s1 != null && s2 != null)\n                {\n                    return String.Equals(s1, s2, StringComparison.OrdinalIgnoreCase);\n                }\n                return Equals(x, y);\n            }\n\n            int IEqualityComparer<object>.GetHashCode(object obj)\n            {\n                var s = obj as string;\n                if (s != null)\n                {\n                    return s.ToUpperInvariant().GetHashCode();\n                }\n                return obj.GetHashCode();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/PageVirtualPathAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.WebPages\n{\n    // Attribute placed on a WebPage derived class that indicates the virtual path that it's associated with\n    // This is used to support scenarios where pages are compiled ahead of time in external class libraries\n    // Specifically, this is used by the RazorSingleFileGenerator.\n    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]\n    public sealed class PageVirtualPathAttribute : Attribute\n    {\n        public PageVirtualPathAttribute(string virtualPath)\n        {\n            VirtualPath = virtualPath;\n        }\n\n        public string VirtualPath { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/PreApplicationStartCode.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Web.UI;\nusing System.Web.WebPages.Scope;\nusing Microsoft.Web.Infrastructure.DynamicModuleHelper;\n\nnamespace System.Web.WebPages\n{\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class PreApplicationStartCode\n    {\n        // NOTE: Do not add public fields, methods, or other members to this class.\n        // This class does not show up in Intellisense so members on it will not be\n        // discoverable by users. Place new members on more appropriate classes that\n        // relate to the public API (for example, a LoginUrl property should go on a\n        // membership-related class).\n\n        private static bool _startWasCalled;\n\n        public static void Start()\n        {\n            // Even though ASP.NET will only call each PreAppStart once, we sometimes internally call one PreAppStart from \n            // another PreAppStart to ensure that things get initialized in the right order. ASP.NET does not guarantee the \n            // order so we have to guard against multiple calls.\n            // All Start calls are made on same thread, so no lock needed here.\n\n            if (_startWasCalled)\n            {\n                return;\n            }\n            _startWasCalled = true;\n\n            WebPageHttpHandler.RegisterExtension(\"cshtml\");\n            WebPageHttpHandler.RegisterExtension(\"vbhtml\");\n\n            // Turn off the string resource behavior which would not work in our simple base page\n            PageParser.EnableLongStringsAsResources = false;\n\n            DynamicModuleUtility.RegisterModule(typeof(WebPageHttpModule));\n\n            ScopeStorage.CurrentProvider = new AspNetRequestScopeStorageProvider();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Properties/AssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Web;\nusing System.Web.WebPages;\n\n// General Information about an assembly is controlled through the following \n// set of attributes. Change these attribute values to modify the information\n// associated with an assembly.\n\n[assembly: AssemblyTitle(\"System.Web.WebPages\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: InternalsVisibleTo(\"System.Web.Mvc, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n[assembly: InternalsVisibleTo(\"System.Web.Helpers, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n[assembly: InternalsVisibleTo(\"System.Web.WebPages.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n[assembly: InternalsVisibleTo(\"System.Web.Helpers.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n[assembly: InternalsVisibleTo(\"System.Web.WebPages.Administration.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n[assembly: PreApplicationStartMethod(typeof(PreApplicationStartCode), \"Start\")]\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"System.Web.Helpers\", Justification = \"Namespace has more types in System.Web.Helpers.dll.\")]\n"
  },
  {
    "path": "src/System.Web.WebPages/ReflectionDynamicObject.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Dynamic;\nusing System.Globalization;\nusing System.Reflection;\n\nnamespace System.Web.WebPages\n{\n    // Allows dynamic access over a CLR object via private reflection\n    internal sealed class ReflectionDynamicObject : DynamicObject\n    {\n        private object RealObject { get; set; }\n\n        public static object WrapObjectIfInternal(object o)\n        {\n            // If it's null, don't try to wrap it\n            if (o == null)\n            {\n                return null;\n            }\n\n            // If it's public, leave it alone since the standard dynamic binder will work. Well, it won't work for\n            // internal properties, but we're mostly concerned about supporting anonymous objects, which are never public\n            if (o.GetType().IsPublic)\n            {\n                return o;\n            }\n\n            return new ReflectionDynamicObject() { RealObject = o };\n        }\n\n        // Called when a property is accessed\n        public override bool TryGetMember(GetMemberBinder binder, out object result)\n        {\n            // Get the property info\n            PropertyInfo propInfo = RealObject.GetType().GetProperty(\n                binder.Name,\n                BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public);\n\n            if (propInfo == null)\n            {\n                // If there is no such property, return null instead of failing. This allows optional parameters\n                result = null;\n            }\n            else\n            {\n                // Get the property value\n                result = propInfo.GetValue(RealObject, null);\n\n                // Wrap the sub object if necessary. This allows nested anonymous objects to work.\n                result = WrapObjectIfInternal(result);\n            }\n\n            return true;\n        }\n\n        // Called when a method is called\n        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)\n        {\n            result = RealObject.GetType().InvokeMember(\n                binder.Name,\n                BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,\n                null,\n                RealObject,\n                args,\n                CultureInfo.InvariantCulture);\n\n            return true;\n        }\n\n        // Called when the dynamic object needs to be converted to a non dynamic object\n        public override bool TryConvert(ConvertBinder binder, out object result)\n        {\n            result = RealObject;\n            return true;\n        }\n\n        public override string ToString()\n        {\n            // Just return the original object's display string\n            return RealObject.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/RequestBrowserOverrideStore.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.WebPages\n{\n    /// <summary>\n    /// RequestBrowserOverrideStore simply returns the user agent of the current request.\n    /// </summary>\n    internal sealed class RequestBrowserOverrideStore : BrowserOverrideStore\n    {\n        public override string GetOverriddenUserAgent(HttpContextBase httpContext)\n        {\n            return httpContext.Request.UserAgent;\n        }\n\n        public override void SetOverriddenUserAgent(HttpContextBase httpContext, string userAgent)\n        {\n            return;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/RequestExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.WebPages\n{\n    public static class RequestExtensions\n    {\n        [SuppressMessage(\"Microsoft.Usage\", \"CA1801:ReviewUnusedParameters\", MessageId = \"request\", Justification = \"The request parameter is no longer being used but we do not want to break legacy callers.\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1054:UriParametersShouldNotBeStrings\", MessageId = \"1#\", Justification = \"Response.Redirect() takes its URI as a string parameter.\")]\n        public static bool IsUrlLocalToHost(this HttpRequestBase request, string url)\n        {\n            return !url.IsEmpty() &&\n                   ((url[0] == '/' && (url.Length == 1 || (url[1] != '/' && url[1] != '\\\\'))) || // \"/\" or \"/foo\" but not \"//\" or \"/\\\"\n                    (url.Length > 1 && url[0] == '~' && url[1] == '/')); // \"~/\" or \"~/foo\"\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/RequestResourceTracker.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.WebPages\n{\n    internal static class RequestResourceTracker\n    {\n        private static readonly object _resourcesKey = new object();\n\n        private static List<SecureWeakReference> GetResources(HttpContextBase context)\n        {\n            var resources = (List<SecureWeakReference>)context.Items[_resourcesKey];\n            if (resources == null)\n            {\n                resources = new List<SecureWeakReference>();\n                context.Items[_resourcesKey] = resources;\n            }\n\n            return resources;\n        }\n\n        internal static void DisposeResources(HttpContextBase context)\n        {\n            var resources = GetResources(context);\n            if (resources != null)\n            {\n                resources.ForEach(resource => resource.Dispose());\n                resources.Clear();\n            }\n        }\n\n        internal static void RegisterForDispose(HttpContextBase context, IDisposable resource)\n        {\n            var resources = GetResources(context);\n            if (resources != null)\n            {\n                resources.Add(new SecureWeakReference(resource));\n            }\n        }\n\n        internal static void RegisterForDispose(IDisposable resource)\n        {\n            var context = HttpContext.Current;\n            if (context != null)\n            {\n                RegisterForDispose(new HttpContextWrapper(context), resource);\n            }\n        }\n\n        private sealed class SecureWeakReference\n        {\n            private readonly WeakReference _reference;\n\n            public SecureWeakReference(IDisposable reference)\n            {\n                _reference = new WeakReference(reference);\n            }\n\n            internal void Dispose()\n            {\n                var disposable = (IDisposable)_reference.Target;\n                if (disposable != null)\n                {\n                    disposable.Dispose();\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Resources/WebPageResources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.261\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace System.Web.WebPages.Resources {\n    using System;\n    \n    \n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class WebPageResources {\n        \n        private static global::System.Resources.ResourceManager resourceMan;\n        \n        private static global::System.Globalization.CultureInfo resourceCulture;\n        \n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal WebPageResources() {\n        }\n        \n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"System.Web.WebPages.Resources.WebPageResources\", typeof(WebPageResources).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n        \n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The provided anti-forgery token failed a custom data check..\n        /// </summary>\n        internal static string AntiForgeryToken_AdditionalDataCheckFailed {\n            get {\n                return ResourceManager.GetString(\"AntiForgeryToken_AdditionalDataCheckFailed\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The provided anti-forgery token was meant for a different claims-based user than the current user..\n        /// </summary>\n        internal static string AntiForgeryToken_ClaimUidMismatch {\n            get {\n                return ResourceManager.GetString(\"AntiForgeryToken_ClaimUidMismatch\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The required anti-forgery cookie &quot;{0}&quot; is not present..\n        /// </summary>\n        internal static string AntiForgeryToken_CookieMissing {\n            get {\n                return ResourceManager.GetString(\"AntiForgeryToken_CookieMissing\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The anti-forgery token could not be decrypted. If this application is hosted by a Web Farm or cluster, ensure that all machines are running the same version of ASP.NET Web Pages and that the &lt;machineKey&gt; configuration specifies explicit encryption and validation keys. AutoGenerate cannot be used in a cluster..\n        /// </summary>\n        internal static string AntiForgeryToken_DeserializationFailed {\n            get {\n                return ResourceManager.GetString(\"AntiForgeryToken_DeserializationFailed\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The required anti-forgery form field &quot;{0}&quot; is not present..\n        /// </summary>\n        internal static string AntiForgeryToken_FormFieldMissing {\n            get {\n                return ResourceManager.GetString(\"AntiForgeryToken_FormFieldMissing\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The anti-forgery cookie token and form field token do not match..\n        /// </summary>\n        internal static string AntiForgeryToken_SecurityTokenMismatch {\n            get {\n                return ResourceManager.GetString(\"AntiForgeryToken_SecurityTokenMismatch\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Validation of the provided anti-forgery token failed. The cookie &quot;{0}&quot; and the form field &quot;{1}&quot; were swapped..\n        /// </summary>\n        internal static string AntiForgeryToken_TokensSwapped {\n            get {\n                return ResourceManager.GetString(\"AntiForgeryToken_TokensSwapped\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The provided anti-forgery token was meant for user &quot;{0}&quot;, but the current user is &quot;{1}&quot;..\n        /// </summary>\n        internal static string AntiForgeryToken_UsernameMismatch {\n            get {\n                return ResourceManager.GetString(\"AntiForgeryToken_UsernameMismatch\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The anti-forgery system has the configuration value AntiForgeryConfig.RequireSsl = true, but the current request is not an SSL request..\n        /// </summary>\n        internal static string AntiForgeryWorker_RequireSSL {\n            get {\n                return ResourceManager.GetString(\"AntiForgeryWorker_RequireSSL\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The assembly &quot;{0}&quot; is already registered..\n        /// </summary>\n        internal static string ApplicationPart_ModuleAlreadyRegistered {\n            get {\n                return ResourceManager.GetString(\"ApplicationPart_ModuleAlreadyRegistered\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to An application module is already registered for virtual path &quot;{0}&quot;..\n        /// </summary>\n        internal static string ApplicationPart_ModuleAlreadyRegisteredForVirtualPath {\n            get {\n                return ResourceManager.GetString(\"ApplicationPart_ModuleAlreadyRegisteredForVirtualPath\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Unable to find an application module with the name &quot;{0}&quot;..\n        /// </summary>\n        internal static string ApplicationPart_ModuleCannotBeFound {\n            get {\n                return ResourceManager.GetString(\"ApplicationPart_ModuleCannotBeFound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The assembly &quot;{0}&quot; is not a registered application module..\n        /// </summary>\n        internal static string ApplicationPart_ModuleNotRegistered {\n            get {\n                return ResourceManager.GetString(\"ApplicationPart_ModuleNotRegistered\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The resource file &quot;{0}&quot; could not be found..\n        /// </summary>\n        internal static string ApplicationPart_ResourceNotFound {\n            get {\n                return ResourceManager.GetString(\"ApplicationPart_ResourceNotFound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A claim of type &apos;{0}&apos; was not present on the provided ClaimsIdentity..\n        /// </summary>\n        internal static string ClaimUidExtractor_ClaimNotPresent {\n            get {\n                return ResourceManager.GetString(\"ClaimUidExtractor_ClaimNotPresent\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A claim of type &apos;http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier&apos; or &apos;http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider&apos; was not present on the provided ClaimsIdentity. To enable anti-forgery token support with claims-based authentication, please verify that the configured claims provider is providing both of these claims on the ClaimsIdentity instances it generates. If the configured claims provider instead uses a different claim type as a unique identif [rest of string was truncated]&quot;;.\n        /// </summary>\n        internal static string ClaimUidExtractor_DefaultClaimsNotPresent {\n            get {\n                return ResourceManager.GetString(\"ClaimUidExtractor_DefaultClaimsNotPresent\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Index length must be exactly one..\n        /// </summary>\n        internal static string DynamicDictionary_InvalidNumberOfIndexes {\n            get {\n                return ResourceManager.GetString(\"DynamicDictionary_InvalidNumberOfIndexes\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Index must be of type string or int when getting a value..\n        /// </summary>\n        internal static string DynamicHttpApplicationState_UseOnlyStringOrIntToGet {\n            get {\n                return ResourceManager.GetString(\"DynamicHttpApplicationState_UseOnlyStringOrIntToGet\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Index must be of type string when setting a value..\n        /// </summary>\n        internal static string DynamicHttpApplicationState_UseOnlyStringToSet {\n            get {\n                return ResourceManager.GetString(\"DynamicHttpApplicationState_UseOnlyStringToSet\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The parameter conversion from type &quot;{0}&quot; to type &quot;{1}&quot; failed. See the inner exception for more information..\n        /// </summary>\n        internal static string HtmlHelper_ConversionThrew {\n            get {\n                return ResourceManager.GetString(\"HtmlHelper_ConversionThrew\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The parameter conversion from type &quot;{0}&quot; to type &quot;{1}&quot; failed because no type converter can convert between these types..\n        /// </summary>\n        internal static string HtmlHelper_NoConverterExists {\n            get {\n                return ResourceManager.GetString(\"HtmlHelper_NoConverterExists\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to An HttpContext is required to perform this operation. Check that this operation is being performed during a web request..\n        /// </summary>\n        internal static string HttpContextUnavailable {\n            get {\n                return ResourceManager.GetString(\"HttpContextUnavailable\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Value &quot;{0}&quot; specified in &quot;{1}&quot; is an invalid value for the SessionState directive. Possible values are: &quot;{2}&quot;..\n        /// </summary>\n        internal static string SessionState_InvalidValue {\n            get {\n                return ResourceManager.GetString(\"SessionState_InvalidValue\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to At most one SessionState value can be declared per page..\n        /// </summary>\n        internal static string SessionState_TooManyValues {\n            get {\n                return ResourceManager.GetString(\"SessionState_TooManyValues\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to RequestScope cannot be created when _AppStart is executing..\n        /// </summary>\n        internal static string StateStorage_RequestScopeNotAvailable {\n            get {\n                return ResourceManager.GetString(\"StateStorage_RequestScopeNotAvailable\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Storage scope is read only..\n        /// </summary>\n        internal static string StateStorage_ScopeIsReadOnly {\n            get {\n                return ResourceManager.GetString(\"StateStorage_ScopeIsReadOnly\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Storage scopes cannot be created when _AppStart is executing..\n        /// </summary>\n        internal static string StateStorage_StorageScopesCannotBeCreated {\n            get {\n                return ResourceManager.GetString(\"StateStorage_StorageScopesCannotBeCreated\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The provided identity of type &apos;{0}&apos; is marked IsAuthenticated = true but does not have a value for Name. By default, the anti-forgery system requires that all authenticated identities have a unique Name. If it is not possible to provide a unique Name for this identity, consider setting the static property AntiForgeryConfig.AdditionalDataProvider to an instance of a type that can provide some form of unique identifier for the current user..\n        /// </summary>\n        internal static string TokenValidator_AuthenticatedUserWithoutUsername {\n            get {\n                return ResourceManager.GetString(\"TokenValidator_AuthenticatedUserWithoutUsername\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Validation parameter names in unobtrusive client validation rules cannot be empty. Client rule type: {0}.\n        /// </summary>\n        internal static string UnobtrusiveJavascript_ValidationParameterCannotBeEmpty {\n            get {\n                return ResourceManager.GetString(\"UnobtrusiveJavascript_ValidationParameterCannotBeEmpty\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Validation parameter names in unobtrusive client validation rules must start with a lowercase letter and consist of only lowercase letters or digits. Validation parameter name: {0}, client rule type: {1}.\n        /// </summary>\n        internal static string UnobtrusiveJavascript_ValidationParameterMustBeLegal {\n            get {\n                return ResourceManager.GetString(\"UnobtrusiveJavascript_ValidationParameterMustBeLegal\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Validation type names in unobtrusive client validation rules cannot be empty. Client rule type: {0}.\n        /// </summary>\n        internal static string UnobtrusiveJavascript_ValidationTypeCannotBeEmpty {\n            get {\n                return ResourceManager.GetString(\"UnobtrusiveJavascript_ValidationTypeCannotBeEmpty\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Validation type names in unobtrusive client validation rules must consist of only lowercase letters. Invalid name: &quot;{0}&quot;, client rule type: {1}.\n        /// </summary>\n        internal static string UnobtrusiveJavascript_ValidationTypeMustBeLegal {\n            get {\n                return ResourceManager.GetString(\"UnobtrusiveJavascript_ValidationTypeMustBeLegal\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Validation type names in unobtrusive client validation rules must be unique. The following validation type was seen more than once: {0}.\n        /// </summary>\n        internal static string UnobtrusiveJavascript_ValidationTypeMustBeUnique {\n            get {\n                return ResourceManager.GetString(\"UnobtrusiveJavascript_ValidationTypeMustBeUnique\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The UrlData collection is read-only..\n        /// </summary>\n        internal static string UrlData_ReadOnly {\n            get {\n                return ResourceManager.GetString(\"UrlData_ReadOnly\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Input format is invalid..\n        /// </summary>\n        internal static string ValidationDefault_DataType {\n            get {\n                return ResourceManager.GetString(\"ValidationDefault_DataType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Values do not match..\n        /// </summary>\n        internal static string ValidationDefault_EqualsTo {\n            get {\n                return ResourceManager.GetString(\"ValidationDefault_EqualsTo\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Value must be a decimal between {0} and {1}..\n        /// </summary>\n        internal static string ValidationDefault_FloatRange {\n            get {\n                return ResourceManager.GetString(\"ValidationDefault_FloatRange\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Value must be an integer between {0} and {1}..\n        /// </summary>\n        internal static string ValidationDefault_IntegerRange {\n            get {\n                return ResourceManager.GetString(\"ValidationDefault_IntegerRange\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Value is invalid..\n        /// </summary>\n        internal static string ValidationDefault_Regex {\n            get {\n                return ResourceManager.GetString(\"ValidationDefault_Regex\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to This field is required..\n        /// </summary>\n        internal static string ValidationDefault_Required {\n            get {\n                return ResourceManager.GetString(\"ValidationDefault_Required\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Max length: {0}..\n        /// </summary>\n        internal static string ValidationDefault_StringLength {\n            get {\n                return ResourceManager.GetString(\"ValidationDefault_StringLength\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to String must be between {0} and {1} characters..\n        /// </summary>\n        internal static string ValidationDefault_StringLengthRange {\n            get {\n                return ResourceManager.GetString(\"ValidationDefault_StringLengthRange\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The file &quot;{0}&quot; cannot be requested directly because it calls the &quot;{1}&quot; method..\n        /// </summary>\n        internal static string WebPage_CannotRequestDirectly {\n            get {\n                return ResourceManager.GetString(\"WebPage_CannotRequestDirectly\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The following file could not be rendered because its extension &quot;{0}&quot; might not be supported: &quot;{1}&quot;..\n        /// </summary>\n        internal static string WebPage_FileNotSupported {\n            get {\n                return ResourceManager.GetString(\"WebPage_FileNotSupported\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The file &quot;{0}&quot; could not be rendered, because it does not exist or is not a valid page..\n        /// </summary>\n        internal static string WebPage_InvalidPageType {\n            get {\n                return ResourceManager.GetString(\"WebPage_InvalidPageType\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The layout page &quot;{0}&quot; could not be found at the following path: &quot;{1}&quot;..\n        /// </summary>\n        internal static string WebPage_LayoutPageNotFound {\n            get {\n                return ResourceManager.GetString(\"WebPage_LayoutPageNotFound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &quot;RenderBody&quot; method has already been called..\n        /// </summary>\n        internal static string WebPage_RenderBodyAlreadyCalled {\n            get {\n                return ResourceManager.GetString(\"WebPage_RenderBodyAlreadyCalled\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &quot;RenderBody&quot; method has not been called for layout page &quot;{0}&quot;..\n        /// </summary>\n        internal static string WebPage_RenderBodyNotCalled {\n            get {\n                return ResourceManager.GetString(\"WebPage_RenderBodyNotCalled\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Section already defined: &quot;{0}&quot;..\n        /// </summary>\n        internal static string WebPage_SectionAleadyDefined {\n            get {\n                return ResourceManager.GetString(\"WebPage_SectionAleadyDefined\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &quot;RenderSection&quot; method has already been called for the section named &quot;{0}&quot;..\n        /// </summary>\n        internal static string WebPage_SectionAleadyRendered {\n            get {\n                return ResourceManager.GetString(\"WebPage_SectionAleadyRendered\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Section not defined: &quot;{0}&quot;..\n        /// </summary>\n        internal static string WebPage_SectionNotDefined {\n            get {\n                return ResourceManager.GetString(\"WebPage_SectionNotDefined\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The following sections have been defined but have not been rendered for the layout page &quot;{0}&quot;: &quot;{1}&quot;..\n        /// </summary>\n        internal static string WebPage_SectionsNotRendered {\n            get {\n                return ResourceManager.GetString(\"WebPage_SectionsNotRendered\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Files with leading underscores (&quot;_&quot;) cannot be served..\n        /// </summary>\n        internal static string WebPageRoute_UnderscoreBlocked {\n            get {\n                return ResourceManager.GetString(\"WebPageRoute_UnderscoreBlocked\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Resources/WebPageResources.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"AntiForgeryToken_AdditionalDataCheckFailed\" xml:space=\"preserve\">\n    <value>The provided anti-forgery token failed a custom data check.</value>\n  </data>\n  <data name=\"AntiForgeryToken_ClaimUidMismatch\" xml:space=\"preserve\">\n    <value>The provided anti-forgery token was meant for a different claims-based user than the current user.</value>\n  </data>\n  <data name=\"AntiForgeryToken_CookieMissing\" xml:space=\"preserve\">\n    <value>The required anti-forgery cookie \"{0}\" is not present.</value>\n  </data>\n  <data name=\"AntiForgeryToken_DeserializationFailed\" xml:space=\"preserve\">\n    <value>The anti-forgery token could not be decrypted. If this application is hosted by a Web Farm or cluster, ensure that all machines are running the same version of ASP.NET Web Pages and that the &lt;machineKey&gt; configuration specifies explicit encryption and validation keys. AutoGenerate cannot be used in a cluster.</value>\n  </data>\n  <data name=\"AntiForgeryToken_FormFieldMissing\" xml:space=\"preserve\">\n    <value>The required anti-forgery form field \"{0}\" is not present.</value>\n  </data>\n  <data name=\"AntiForgeryToken_SecurityTokenMismatch\" xml:space=\"preserve\">\n    <value>The anti-forgery cookie token and form field token do not match.</value>\n  </data>\n  <data name=\"AntiForgeryToken_TokensSwapped\" xml:space=\"preserve\">\n    <value>Validation of the provided anti-forgery token failed. The cookie \"{0}\" and the form field \"{1}\" were swapped.</value>\n  </data>\n  <data name=\"AntiForgeryToken_UsernameMismatch\" xml:space=\"preserve\">\n    <value>The provided anti-forgery token was meant for user \"{0}\", but the current user is \"{1}\".</value>\n  </data>\n  <data name=\"AntiForgeryWorker_RequireSSL\" xml:space=\"preserve\">\n    <value>The anti-forgery system has the configuration value AntiForgeryConfig.RequireSsl = true, but the current request is not an SSL request.</value>\n  </data>\n  <data name=\"ApplicationPart_ModuleAlreadyRegistered\" xml:space=\"preserve\">\n    <value>The assembly \"{0}\" is already registered.</value>\n  </data>\n  <data name=\"ApplicationPart_ModuleAlreadyRegisteredForVirtualPath\" xml:space=\"preserve\">\n    <value>An application module is already registered for virtual path \"{0}\".</value>\n  </data>\n  <data name=\"ApplicationPart_ModuleCannotBeFound\" xml:space=\"preserve\">\n    <value>Unable to find an application module with the name \"{0}\".</value>\n  </data>\n  <data name=\"ApplicationPart_ModuleNotRegistered\" xml:space=\"preserve\">\n    <value>The assembly \"{0}\" is not a registered application module.</value>\n  </data>\n  <data name=\"ApplicationPart_ResourceNotFound\" xml:space=\"preserve\">\n    <value>The resource file \"{0}\" could not be found.</value>\n  </data>\n  <data name=\"ClaimUidExtractor_ClaimNotPresent\" xml:space=\"preserve\">\n    <value>A claim of type '{0}' was not present on the provided ClaimsIdentity.</value>\n  </data>\n  <data name=\"ClaimUidExtractor_DefaultClaimsNotPresent\" xml:space=\"preserve\">\n    <value>A claim of type 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier' or 'http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider' was not present on the provided ClaimsIdentity. To enable anti-forgery token support with claims-based authentication, please verify that the configured claims provider is providing both of these claims on the ClaimsIdentity instances it generates. If the configured claims provider instead uses a different claim type as a unique identifier, it can be configured by setting the static property AntiForgeryConfig.UniqueClaimTypeIdentifier.</value>\n  </data>\n  <data name=\"DynamicDictionary_InvalidNumberOfIndexes\" xml:space=\"preserve\">\n    <value>Index length must be exactly one.</value>\n  </data>\n  <data name=\"DynamicHttpApplicationState_UseOnlyStringOrIntToGet\" xml:space=\"preserve\">\n    <value>Index must be of type string or int when getting a value.</value>\n  </data>\n  <data name=\"DynamicHttpApplicationState_UseOnlyStringToSet\" xml:space=\"preserve\">\n    <value>Index must be of type string when setting a value.</value>\n  </data>\n  <data name=\"HtmlHelper_ConversionThrew\" xml:space=\"preserve\">\n    <value>The parameter conversion from type \"{0}\" to type \"{1}\" failed. See the inner exception for more information.</value>\n  </data>\n  <data name=\"HtmlHelper_NoConverterExists\" xml:space=\"preserve\">\n    <value>The parameter conversion from type \"{0}\" to type \"{1}\" failed because no type converter can convert between these types.</value>\n  </data>\n  <data name=\"HttpContextUnavailable\" xml:space=\"preserve\">\n    <value>An HttpContext is required to perform this operation. Check that this operation is being performed during a web request.</value>\n  </data>\n  <data name=\"SessionState_InvalidValue\" xml:space=\"preserve\">\n    <value>Value \"{0}\" specified in \"{1}\" is an invalid value for the SessionState directive. Possible values are: \"{2}\".</value>\n  </data>\n  <data name=\"SessionState_TooManyValues\" xml:space=\"preserve\">\n    <value>At most one SessionState value can be declared per page.</value>\n  </data>\n  <data name=\"StateStorage_RequestScopeNotAvailable\" xml:space=\"preserve\">\n    <value>RequestScope cannot be created when _AppStart is executing.</value>\n  </data>\n  <data name=\"StateStorage_ScopeIsReadOnly\" xml:space=\"preserve\">\n    <value>Storage scope is read only.</value>\n  </data>\n  <data name=\"StateStorage_StorageScopesCannotBeCreated\" xml:space=\"preserve\">\n    <value>Storage scopes cannot be created when _AppStart is executing.</value>\n  </data>\n  <data name=\"TokenValidator_AuthenticatedUserWithoutUsername\" xml:space=\"preserve\">\n    <value>The provided identity of type '{0}' is marked IsAuthenticated = true but does not have a value for Name. By default, the anti-forgery system requires that all authenticated identities have a unique Name. If it is not possible to provide a unique Name for this identity, consider setting the static property AntiForgeryConfig.AdditionalDataProvider to an instance of a type that can provide some form of unique identifier for the current user.</value>\n  </data>\n  <data name=\"UnobtrusiveJavascript_ValidationParameterCannotBeEmpty\" xml:space=\"preserve\">\n    <value>Validation parameter names in unobtrusive client validation rules cannot be empty. Client rule type: {0}</value>\n  </data>\n  <data name=\"UnobtrusiveJavascript_ValidationParameterMustBeLegal\" xml:space=\"preserve\">\n    <value>Validation parameter names in unobtrusive client validation rules must start with a lowercase letter and consist of only lowercase letters or digits. Validation parameter name: {0}, client rule type: {1}</value>\n  </data>\n  <data name=\"UnobtrusiveJavascript_ValidationTypeCannotBeEmpty\" xml:space=\"preserve\">\n    <value>Validation type names in unobtrusive client validation rules cannot be empty. Client rule type: {0}</value>\n  </data>\n  <data name=\"UnobtrusiveJavascript_ValidationTypeMustBeLegal\" xml:space=\"preserve\">\n    <value>Validation type names in unobtrusive client validation rules must consist of only lowercase letters. Invalid name: \"{0}\", client rule type: {1}</value>\n  </data>\n  <data name=\"UnobtrusiveJavascript_ValidationTypeMustBeUnique\" xml:space=\"preserve\">\n    <value>Validation type names in unobtrusive client validation rules must be unique. The following validation type was seen more than once: {0}</value>\n  </data>\n  <data name=\"UrlData_ReadOnly\" xml:space=\"preserve\">\n    <value>The UrlData collection is read-only.</value>\n  </data>\n  <data name=\"ValidationDefault_DataType\" xml:space=\"preserve\">\n    <value>Input format is invalid.</value>\n  </data>\n  <data name=\"ValidationDefault_EqualsTo\" xml:space=\"preserve\">\n    <value>Values do not match.</value>\n  </data>\n  <data name=\"ValidationDefault_FloatRange\" xml:space=\"preserve\">\n    <value>Value must be a decimal between {0} and {1}.</value>\n  </data>\n  <data name=\"ValidationDefault_IntegerRange\" xml:space=\"preserve\">\n    <value>Value must be an integer between {0} and {1}.</value>\n  </data>\n  <data name=\"ValidationDefault_Regex\" xml:space=\"preserve\">\n    <value>Value is invalid.</value>\n  </data>\n  <data name=\"ValidationDefault_Required\" xml:space=\"preserve\">\n    <value>This field is required.</value>\n  </data>\n  <data name=\"ValidationDefault_StringLength\" xml:space=\"preserve\">\n    <value>Max length: {0}.</value>\n  </data>\n  <data name=\"ValidationDefault_StringLengthRange\" xml:space=\"preserve\">\n    <value>String must be between {0} and {1} characters.</value>\n  </data>\n  <data name=\"WebPageRoute_UnderscoreBlocked\" xml:space=\"preserve\">\n    <value>Files with leading underscores (\"_\") cannot be served.</value>\n  </data>\n  <data name=\"WebPage_CannotRequestDirectly\" xml:space=\"preserve\">\n    <value>The file \"{0}\" cannot be requested directly because it calls the \"{1}\" method.</value>\n  </data>\n  <data name=\"WebPage_FileNotSupported\" xml:space=\"preserve\">\n    <value>The following file could not be rendered because its extension \"{0}\" might not be supported: \"{1}\".</value>\n  </data>\n  <data name=\"WebPage_InvalidPageType\" xml:space=\"preserve\">\n    <value>The file \"{0}\" could not be rendered, because it does not exist or is not a valid page.</value>\n  </data>\n  <data name=\"WebPage_LayoutPageNotFound\" xml:space=\"preserve\">\n    <value>The layout page \"{0}\" could not be found at the following path: \"{1}\".</value>\n  </data>\n  <data name=\"WebPage_RenderBodyAlreadyCalled\" xml:space=\"preserve\">\n    <value>The \"RenderBody\" method has already been called.</value>\n  </data>\n  <data name=\"WebPage_RenderBodyNotCalled\" xml:space=\"preserve\">\n    <value>The \"RenderBody\" method has not been called for layout page \"{0}\".</value>\n  </data>\n  <data name=\"WebPage_SectionAleadyDefined\" xml:space=\"preserve\">\n    <value>Section already defined: \"{0}\".</value>\n  </data>\n  <data name=\"WebPage_SectionAleadyRendered\" xml:space=\"preserve\">\n    <value>The \"RenderSection\" method has already been called for the section named \"{0}\".</value>\n  </data>\n  <data name=\"WebPage_SectionNotDefined\" xml:space=\"preserve\">\n    <value>Section not defined: \"{0}\".</value>\n  </data>\n  <data name=\"WebPage_SectionsNotRendered\" xml:space=\"preserve\">\n    <value>The following sections have been defined but have not been rendered for the layout page \"{0}\": \"{1}\".</value>\n  </data>\n</root>"
  },
  {
    "path": "src/System.Web.WebPages/ResponseExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Net;\n\nnamespace System.Web.WebPages\n{\n    public static class ResponseExtensions\n    {\n        public static void SetStatus(this HttpResponseBase response, HttpStatusCode httpStatusCode)\n        {\n            SetStatus(response, (int)httpStatusCode);\n        }\n\n        public static void SetStatus(this HttpResponseBase response, int httpStatusCode)\n        {\n            response.StatusCode = httpStatusCode;\n            response.End();\n        }\n\n        public static void WriteBinary(this HttpResponseBase response, byte[] data, string mimeType)\n        {\n            response.ContentType = mimeType;\n            WriteBinary(response, data);\n        }\n\n        public static void WriteBinary(this HttpResponseBase response, byte[] data)\n        {\n            response.OutputStream.Write(data, 0, data.Length);\n        }\n\n        // REVIEW: See what this is actually calling that's needed\n        // Configure output caching for the request\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"We are not removing optional parameters from helpers\")]\n        public static void OutputCache(this HttpResponseBase response,\n                                       int numberOfSeconds,\n                                       bool sliding = false,\n                                       IEnumerable<string> varyByParams = null,\n                                       IEnumerable<string> varyByHeaders = null,\n                                       IEnumerable<string> varyByContentEncodings = null,\n                                       HttpCacheability cacheability = HttpCacheability.Public)\n        {\n            OutputCache(new HttpContextWrapper(HttpContext.Current), response.Cache, numberOfSeconds, sliding, varyByParams, varyByHeaders, varyByContentEncodings,\n                        cacheability);\n        }\n\n        internal static void OutputCache(HttpContextBase httpContext,\n                                         HttpCachePolicyBase cache,\n                                         int numberOfSeconds,\n                                         bool sliding,\n                                         IEnumerable<string> varyByParams,\n                                         IEnumerable<string> varyByHeaders,\n                                         IEnumerable<string> varyByContentEncodings,\n                                         HttpCacheability cacheability)\n        {\n            cache.SetCacheability(cacheability);\n            cache.SetExpires(httpContext.Timestamp.AddSeconds(numberOfSeconds));\n            cache.SetMaxAge(new TimeSpan(0, 0, numberOfSeconds));\n            cache.SetValidUntilExpires(true);\n            cache.SetLastModified(httpContext.Timestamp);\n            cache.SetSlidingExpiration(sliding);\n\n            if (varyByParams != null)\n            {\n                foreach (var p in varyByParams)\n                {\n                    cache.VaryByParams[p] = true;\n                }\n            }\n\n            if (varyByHeaders != null)\n            {\n                foreach (var headerName in varyByHeaders)\n                {\n                    cache.VaryByHeaders[headerName] = true;\n                }\n            }\n\n            if (varyByContentEncodings != null)\n            {\n                foreach (var contentEncoding in varyByContentEncodings)\n                {\n                    cache.VaryByContentEncodings[contentEncoding] = true;\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Scope/ApplicationScopeStorageDictionary.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\n\nnamespace System.Web.WebPages.Scope\n{\n    /// <summary>\n    /// The application level storage context that uses a static dictionary as a backing store.\n    /// </summary>\n    internal class ApplicationScopeStorageDictionary : ScopeStorageDictionary\n    {\n        private static readonly IDictionary<object, object> _innerDictionary =\n            new ConcurrentDictionary<object, object>(ScopeStorageComparer.Instance);\n\n        public ApplicationScopeStorageDictionary()\n            : this(new WebConfigScopeDictionary())\n        {\n        }\n\n        public ApplicationScopeStorageDictionary(WebConfigScopeDictionary webConfigState)\n            : base(baseScope: webConfigState, backingStore: _innerDictionary)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Scope/AspNetRequestScopeStorageProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.WebPages.Resources;\n\nnamespace System.Web.WebPages.Scope\n{\n    public class AspNetRequestScopeStorageProvider : IScopeStorageProvider\n    {\n        private static readonly object _pageScopeKey = new object();\n        private static readonly object _requestScopeKey = new object();\n        private readonly HttpContextBase _httpContext;\n        private readonly Func<bool> _appStartExecuted;\n\n        public AspNetRequestScopeStorageProvider()\n            : this(httpContext: null, appStartExecuted: () => WebPageHttpModule.AppStartExecuteCompleted)\n        {\n        }\n\n        internal AspNetRequestScopeStorageProvider(HttpContextBase httpContext, Func<bool> appStartExecuted)\n        {\n            _httpContext = httpContext;\n            _appStartExecuted = appStartExecuted;\n            ApplicationScope = new ApplicationScopeStorageDictionary();\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"The state storage API is designed to allow contexts to be set\")]\n        public IDictionary<object, object> CurrentScope\n        {\n            get { return PageScope ?? RequestScopeInternal ?? ApplicationScope; }\n            set\n            {\n                if (!_appStartExecuted())\n                {\n                    // Disallow creating new contexts before the start page is executed. \n                    // This makes sense because our provider is scoped to a request.\n                    throw new InvalidOperationException(WebPageResources.StateStorage_StorageScopesCannotBeCreated);\n                }\n                PageScope = value;\n            }\n        }\n\n        public IDictionary<object, object> GlobalScope\n        {\n            get { return ApplicationScope; }\n        }\n\n        public IDictionary<object, object> ApplicationScope { get; private set; }\n\n        public IDictionary<object, object> RequestScope\n        {\n            get\n            {\n                var requestContext = RequestScopeInternal;\n                if (requestContext == null)\n                {\n                    throw new InvalidOperationException(WebPageResources.StateStorage_RequestScopeNotAvailable);\n                }\n                return requestContext;\n            }\n        }\n\n        private HttpContextBase HttpContext\n        {\n            get\n            {\n                // If a http context is specifically provided, use that. Else return the value from System.Web.HttpContext.Current if its available.\n                var currentHttpContext = Web.HttpContext.Current;\n                return _httpContext ?? (currentHttpContext == null ? null : new HttpContextWrapper(currentHttpContext));\n            }\n        }\n\n        private IDictionary<object, object> RequestScopeInternal\n        {\n            get\n            {\n                if (_appStartExecuted())\n                {\n                    var requestContext = (IDictionary<object, object>)HttpContext.Items[_requestScopeKey];\n                    if (requestContext == null)\n                    {\n                        HttpContext.Items[_requestScopeKey] = requestContext = new ScopeStorageDictionary(ApplicationScope);\n                    }\n                    return requestContext;\n                }\n                return null;\n            }\n        }\n\n        private IDictionary<object, object> PageScope\n        {\n            get\n            {\n                if (HttpContext == null)\n                {\n                    return null;\n                }\n                return (IDictionary<object, object>)HttpContext.Items[_pageScopeKey];\n            }\n            set\n            {\n                // This call would be guarded by the CurrentContext setter.\n                Debug.Assert(HttpContext != null);\n                HttpContext.Items[_pageScopeKey] = value;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Scope/IScopeStorageProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.WebPages.Scope\n{\n    public interface IScopeStorageProvider\n    {\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"The state storage API is designed to allow contexts to be set\")]\n        IDictionary<object, object> CurrentScope { get; set; }\n\n        IDictionary<object, object> GlobalScope { get; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Scope/ScopeStorage.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.WebPages.Scope\n{\n    public static class ScopeStorage\n    {\n        private static readonly IScopeStorageProvider _defaultStorageProvider = new StaticScopeStorageProvider();\n        private static IScopeStorageProvider _stateStorageProvider;\n\n        public static IScopeStorageProvider CurrentProvider\n        {\n            get { return _stateStorageProvider ?? _defaultStorageProvider; }\n            set { _stateStorageProvider = value; }\n        }\n\n        public static IDictionary<object, object> CurrentScope\n        {\n            get { return CurrentProvider.CurrentScope; }\n        }\n\n        public static IDictionary<object, object> GlobalScope\n        {\n            get { return CurrentProvider.GlobalScope; }\n        }\n\n        public static IDisposable CreateTransientScope(IDictionary<object, object> context)\n        {\n            var currentContext = CurrentScope;\n            CurrentProvider.CurrentScope = context;\n            return new DisposableAction(() => CurrentProvider.CurrentScope = currentContext); // Return an IDisposable that pops the item back off\n        }\n\n        public static IDisposable CreateTransientScope()\n        {\n            return CreateTransientScope(new ScopeStorageDictionary(baseScope: CurrentScope));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Scope/ScopeStorageComparer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.WebPages.Scope\n{\n    /// <summary>\n    /// Custom comparer for the context dictionaries\n    /// The comparer treats strings as a special case, performing case insesitive comparison. \n    /// This guaratees that we remain consistent throughout the chain of contexts since PageData dictionary \n    /// behaves in this manner.\n    /// </summary>\n    internal class ScopeStorageComparer : IEqualityComparer<object>\n    {\n        private static IEqualityComparer<object> _instance;\n        private readonly IEqualityComparer<object> _defaultComparer = EqualityComparer<object>.Default;\n        private readonly IEqualityComparer<string> _stringComparer = StringComparer.OrdinalIgnoreCase;\n\n        private ScopeStorageComparer()\n        {\n        }\n\n        public static IEqualityComparer<object> Instance\n        {\n            get\n            {\n                if (_instance == null)\n                {\n                    _instance = new ScopeStorageComparer();\n                }\n                return _instance;\n            }\n        }\n\n        [SuppressMessage(\"StyleCop.CSharp.NamingRules\", \"SA1305:FieldNamesMustNotUseHungarianNotation\", Target = \"xString, yString\",\n           Justification = \"These names make most sense.\")]\n        public new bool Equals(object x, object y)\n        {\n            string xString = x as string;\n            string yString = y as string;\n\n            if ((xString != null) && (yString != null))\n            {\n                return _stringComparer.Equals(xString, yString);\n            }\n\n            return _defaultComparer.Equals(x, y);\n        }\n\n        public int GetHashCode(object obj)\n        {\n            string objString = obj as string;\n            if (objString != null)\n            {\n                return _stringComparer.GetHashCode(objString);\n            }\n\n            return _defaultComparer.GetHashCode(obj);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Scope/ScopeStorageDictionary.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\n\nnamespace System.Web.WebPages.Scope\n{\n    public class ScopeStorageDictionary : IDictionary<object, object>\n    {\n        private static readonly StateStorageKeyValueComparer _keyValueComparer = new StateStorageKeyValueComparer();\n        private readonly IDictionary<object, object> _baseScope;\n        private readonly IDictionary<object, object> _backingStore;\n\n        public ScopeStorageDictionary()\n            : this(baseScope: null)\n        {\n        }\n\n        public ScopeStorageDictionary(IDictionary<object, object> baseScope)\n            : this(baseScope: baseScope, backingStore: new Dictionary<object, object>(ScopeStorageComparer.Instance))\n        {\n        }\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"ScopeStorageDictionary\"/> class.\n        /// </summary>\n        /// <param name=\"baseScope\">The base scope.</param>\n        /// <param name=\"backingStore\">\n        /// The dictionary to use as a storage. Since the dictionary would be used as-is, we expect the implementer to \n        /// use the same key-value comparison logic as we do here.\n        /// </param>\n        internal ScopeStorageDictionary(IDictionary<object, object> baseScope, IDictionary<object, object> backingStore)\n        {\n            _baseScope = baseScope;\n            _backingStore = backingStore;\n        }\n\n        protected IDictionary<object, object> BackingStore\n        {\n            get { return _backingStore; }\n        }\n\n        protected IDictionary<object, object> BaseScope\n        {\n            get { return _baseScope; }\n        }\n\n        public virtual ICollection<object> Keys\n        {\n            get { return GetItems().Select(item => item.Key).ToList(); }\n        }\n\n        public virtual ICollection<object> Values\n        {\n            get { return GetItems().Select(item => item.Value).ToList(); }\n        }\n\n        public virtual int Count\n        {\n            get { return GetItems().Count(); }\n        }\n\n        public virtual bool IsReadOnly\n        {\n            get { return false; }\n        }\n\n        public object this[object key]\n        {\n            get\n            {\n                object value;\n                TryGetValue(key, out value);\n                return value;\n            }\n            set { SetValue(key, value); }\n        }\n\n        public virtual void SetValue(object key, object value)\n        {\n            _backingStore[key] = value;\n        }\n\n        public virtual bool TryGetValue(object key, out object value)\n        {\n            return _backingStore.TryGetValue(key, out value) || (_baseScope != null && _baseScope.TryGetValue(key, out value));\n        }\n\n        public virtual bool Remove(object key)\n        {\n            return _backingStore.Remove(key);\n        }\n\n        public virtual IEnumerator<KeyValuePair<object, object>> GetEnumerator()\n        {\n            return GetItems().GetEnumerator();\n        }\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return GetEnumerator();\n        }\n\n        public virtual void Add(object key, object value)\n        {\n            SetValue(key, value);\n        }\n\n        public virtual bool ContainsKey(object key)\n        {\n            return _backingStore.ContainsKey(key) || (_baseScope != null && _baseScope.ContainsKey(key));\n        }\n\n        public virtual void Add(KeyValuePair<object, object> item)\n        {\n            SetValue(item.Key, item.Value);\n        }\n\n        public virtual void Clear()\n        {\n            _backingStore.Clear();\n        }\n\n        public virtual bool Contains(KeyValuePair<object, object> item)\n        {\n            return _backingStore.Contains(item) || (_baseScope != null && _baseScope.Contains(item));\n        }\n\n        public virtual void CopyTo(KeyValuePair<object, object>[] array, int arrayIndex)\n        {\n            GetItems().ToList().CopyTo(array, arrayIndex);\n        }\n\n        public virtual bool Remove(KeyValuePair<object, object> item)\n        {\n            return _backingStore.Remove(item);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Justification = \"This call might be expensive depending on how long the chain of contexts is\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\", Justification = \"This method is implementation specific and is not meant to be exposed as a public API.\")]\n        protected virtual IEnumerable<KeyValuePair<object, object>> GetItems()\n        {\n            if (_baseScope == null)\n            {\n                return _backingStore;\n            }\n            return Enumerable.Concat(_backingStore, _baseScope).Distinct(_keyValueComparer);\n        }\n\n        private class StateStorageKeyValueComparer : IEqualityComparer<KeyValuePair<object, object>>\n        {\n            private IEqualityComparer<object> _stateStorageComparer = ScopeStorageComparer.Instance;\n\n            public bool Equals(KeyValuePair<object, object> x, KeyValuePair<object, object> y)\n            {\n                return _stateStorageComparer.Equals(x.Key, y.Key);\n            }\n\n            public int GetHashCode(KeyValuePair<object, object> obj)\n            {\n                return _stateStorageComparer.GetHashCode(obj.Key);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Scope/StaticScopeStorageProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace System.Web.WebPages.Scope\n{\n    public class StaticScopeStorageProvider : IScopeStorageProvider\n    {\n        private static readonly IDictionary<object, object> _defaultContext =\n            new ScopeStorageDictionary(null, new ConcurrentDictionary<object, object>(ScopeStorageComparer.Instance));\n\n        private IDictionary<object, object> _currentContext;\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"The state storage API is designed to allow contexts to be set\")]\n        public IDictionary<object, object> CurrentScope\n        {\n            get { return _currentContext ?? _defaultContext; }\n            set { _currentContext = value; }\n        }\n\n        public IDictionary<object, object> GlobalScope\n        {\n            get { return _defaultContext; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Scope/WebConfigScopeStorageDictionary.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Linq;\nusing System.Web.Configuration;\nusing System.Web.WebPages.Resources;\n\nnamespace System.Web.WebPages.Scope\n{\n    internal class WebConfigScopeDictionary : IDictionary<object, object>\n    {\n        private readonly Lazy<Dictionary<object, object>> _items;\n\n        public WebConfigScopeDictionary()\n            : this(WebConfigurationManager.AppSettings)\n        {\n        }\n\n        public WebConfigScopeDictionary(NameValueCollection appSettings)\n        {\n            _items = new Lazy<Dictionary<object, object>>(() =>\n                {\n                    Dictionary<object, object> items = new Dictionary<object, object>(ScopeStorageComparer.Instance);\n                    foreach (string key in appSettings.AllKeys)\n                    {\n                        items[key] = appSettings[key];\n                    }\n                    return items;\n                });\n        }\n\n        private IDictionary<object, object> Items\n        {\n            get { return _items.Value; }\n        }\n\n        public ICollection<object> Keys\n        {\n            get { return Items.Keys; }\n        }\n\n        public ICollection<object> Values\n        {\n            get { return Items.Values; }\n        }\n\n        public int Count\n        {\n            get { return Items.Count; }\n        }\n\n        public bool IsReadOnly\n        {\n            get { return true; }\n        }\n\n        public object this[object key]\n        {\n            get\n            {\n                object value;\n                TryGetValue(key, out value);\n                return value;\n            }\n            set { throw new NotSupportedException(WebPageResources.StateStorage_ScopeIsReadOnly); }\n        }\n\n        public bool TryGetValue(object key, out object value)\n        {\n            return Items.TryGetValue(key, out value);\n        }\n\n        public IEnumerator<KeyValuePair<object, object>> GetEnumerator()\n        {\n            return Items.GetEnumerator();\n        }\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return GetEnumerator();\n        }\n\n        public void Add(object key, object value)\n        {\n            throw new NotSupportedException(WebPageResources.StateStorage_ScopeIsReadOnly);\n        }\n\n        public bool ContainsKey(object key)\n        {\n            return Items.ContainsKey(key);\n        }\n\n        public bool Remove(object key)\n        {\n            throw new NotSupportedException(WebPageResources.StateStorage_ScopeIsReadOnly);\n        }\n\n        public void Add(KeyValuePair<object, object> item)\n        {\n            throw new NotSupportedException(WebPageResources.StateStorage_ScopeIsReadOnly);\n        }\n\n        public void Clear()\n        {\n            throw new NotSupportedException(WebPageResources.StateStorage_ScopeIsReadOnly);\n        }\n\n        public bool Contains(KeyValuePair<object, object> item)\n        {\n            return Items.Contains(item);\n        }\n\n        public void CopyTo(KeyValuePair<object, object>[] array, int arrayIndex)\n        {\n            Items.CopyTo(array, arrayIndex);\n        }\n\n        public bool Remove(KeyValuePair<object, object> item)\n        {\n            throw new NotSupportedException(WebPageResources.StateStorage_ScopeIsReadOnly);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/SectionWriter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.WebPages\n{\n    public delegate void SectionWriter();\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/StartPage.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.IO;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.WebPages\n{\n    /// <summary>\n    /// Wrapper class to be used by _pagestart.cshtml files to call into\n    /// the actual page.\n    /// Most of the properties and methods just delegate the call to ChildPage.XXX\n    /// </summary>\n    public abstract class StartPage : WebPageRenderingBase\n    {\n        public WebPageRenderingBase ChildPage { get; set; }\n\n        public override HttpContextBase Context\n        {\n            get { return ChildPage.Context; }\n            set { ChildPage.Context = value; }\n        }\n\n        public override string Layout\n        {\n            get { return ChildPage.Layout; }\n            set\n            {\n                if (value == null)\n                {\n                    ChildPage.Layout = null;\n                }\n                else\n                {\n                    ChildPage.Layout = NormalizeLayoutPagePath(value);\n                }\n            }\n        }\n\n        public override IDictionary<object, dynamic> PageData\n        {\n            get { return ChildPage.PageData; }\n        }\n\n        public override dynamic Page\n        {\n            get { return ChildPage.Page; }\n        }\n\n        internal bool RunPageCalled { get; set; }\n\n        public override void ExecutePageHierarchy()\n        {\n            // Push the current pagestart on the stack. \n            TemplateStack.Push(Context, this);\n            try\n            {\n                // Execute the developer-written code of the InitPage\n                Execute();\n\n                // If the child page wasn't explicitly run by the developer of the InitPage, then run it now.\n                // The child page is either the next InitPage, or the final WebPage.\n                if (!RunPageCalled)\n                {\n                    RunPage();\n                }\n            }\n            finally\n            {\n                TemplateStack.Pop(Context);\n            }\n        }\n\n        /// <summary>\n        /// Returns either the root-most init page, or the provided page itself if no init page is found\n        /// </summary>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1011:ConsiderPassingBaseTypesAsParameters\",\n            Justification = \"Start Pages are instances of WebPageRenderingBase. It might be possible to have WebPageExecuting bases that are not in the same inheritance tree as StartPages\")]\n        public static WebPageRenderingBase GetStartPage(WebPageRenderingBase page, string fileName, IEnumerable<string> supportedExtensions)\n        {\n            if (page == null)\n            {\n                throw new ArgumentNullException(\"page\");\n            }\n            if (String.IsNullOrEmpty(fileName))\n            {\n                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"fileName\"), \"fileName\");\n            }\n            if (supportedExtensions == null)\n            {\n                throw new ArgumentNullException(\"supportedExtensions\");\n            }\n\n            // Use the page's VirtualPathFactory if available\n            return GetStartPage(page, page.VirtualPathFactory ?? VirtualPathFactoryManager.Instance,\n                                HttpRuntime.AppDomainAppVirtualPath, fileName, supportedExtensions);\n        }\n\n        internal static WebPageRenderingBase GetStartPage(WebPageRenderingBase page, IVirtualPathFactory virtualPathFactory, string appDomainAppVirtualPath,\n                                                          string fileName, IEnumerable<string> supportedExtensions)\n        {\n            // Build up a list of pages to execute, such as one of the following:\n            // ~/somepage.cshtml\n            // ~/_pageStart.cshtml --> ~/somepage.cshtml\n            // ~/_pageStart.cshtml --> ~/sub/_pageStart.cshtml --> ~/sub/somepage.cshtml\n            WebPageRenderingBase currentPage = page;\n            var pageDirectory = VirtualPathUtility.GetDirectory(page.VirtualPath);\n\n            // Start with the requested page's directory, find the init page,\n            // and then traverse up the hierarchy to find init pages all the\n            // way up to the root of the app.\n            while (!String.IsNullOrEmpty(pageDirectory) && pageDirectory != \"/\" && PathUtil.IsWithinAppRoot(appDomainAppVirtualPath, pageDirectory))\n            {\n                // Go through the list of supported extensions\n                foreach (var extension in supportedExtensions)\n                {\n                    var virtualPath = VirtualPathUtility.Combine(pageDirectory, fileName + \".\" + extension);\n\n                    // Can we build a file from the current path?\n                    if (virtualPathFactory.Exists(virtualPath))\n                    {\n                        var parentStartPage = virtualPathFactory.CreateInstance<StartPage>(virtualPath);\n                        parentStartPage.VirtualPath = virtualPath;\n                        parentStartPage.ChildPage = currentPage;\n                        parentStartPage.VirtualPathFactory = virtualPathFactory;\n                        currentPage = parentStartPage;\n\n                        break;\n                    }\n                }\n\n                pageDirectory = currentPage.GetDirectory(pageDirectory);\n            }\n\n            // At this point 'currentPage' is the root-most StartPage (if there were\n            // any StartPages at all) or it is the requested page itself.\n            return currentPage;\n        }\n\n        public override HelperResult RenderPage(string path, params object[] data)\n        {\n            return ChildPage.RenderPage(NormalizePath(path), data);\n        }\n\n        public void RunPage()\n        {\n            RunPageCalled = true;\n            //ChildPage.PageContext = PageContext;\n            ChildPage.ExecutePageHierarchy();\n        }\n\n        public override void Write(HelperResult result)\n        {\n            ChildPage.Write(result);\n        }\n\n        public override void WriteLiteral(object value)\n        {\n            ChildPage.WriteLiteral(value);\n        }\n\n        public override void Write(object value)\n        {\n            ChildPage.Write(value);\n        }\n\n        protected internal override TextWriter GetOutputWriter()\n        {\n            return ChildPage.GetOutputWriter();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/StringExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\n\nnamespace System.Web.WebPages\n{\n    public static class StringExtensions\n    {\n        public static bool IsEmpty(this string value)\n        {\n            return String.IsNullOrEmpty(value);\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1720:IdentifiersShouldNotContainTypeNames\", MessageId = \"int\", Justification = \"We specificaly want type names\")]\n        public static int AsInt(this string value)\n        {\n            return AsInt(value, 0);\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1720:IdentifiersShouldNotContainTypeNames\", MessageId = \"int\", Justification = \"We specificaly want type names\")]\n        public static int AsInt(this string value, int defaultValue)\n        {\n            int result;\n            return Int32.TryParse(value, out result) ? result : defaultValue;\n        }\n\n        public static decimal AsDecimal(this string value)\n        {\n            // Decimal.TryParse does not work consistently for some locales. For instance for lt-LT, it accepts but ignores decimal values so \"12.12\" is parsed as 1212.\n            return As<Decimal>(value);\n        }\n\n        public static decimal AsDecimal(this string value, decimal defaultValue)\n        {\n            return As<Decimal>(value, defaultValue);\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1720:IdentifiersShouldNotContainTypeNames\", MessageId = \"float\", Justification = \"We specificaly want type names\")]\n        public static float AsFloat(this string value)\n        {\n            return AsFloat(value, default(float));\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1720:IdentifiersShouldNotContainTypeNames\", MessageId = \"float\", Justification = \"We specificaly want type names\")]\n        public static float AsFloat(this string value, float defaultValue)\n        {\n            float result;\n            return Single.TryParse(value, out result) ? result : defaultValue;\n        }\n\n        public static DateTime AsDateTime(this string value)\n        {\n            return AsDateTime(value, default(DateTime));\n        }\n\n        public static DateTime AsDateTime(this string value, DateTime defaultValue)\n        {\n            DateTime result;\n            return DateTime.TryParse(value, out result) ? result : defaultValue;\n        }\n\n        public static TValue As<TValue>(this string value)\n        {\n            return As<TValue>(value, default(TValue));\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1720:IdentifiersShouldNotContainTypeNames\", MessageId = \"bool\", Justification = \"We specificaly want type names\")]\n        public static bool AsBool(this string value)\n        {\n            return AsBool(value, default(bool));\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1720:IdentifiersShouldNotContainTypeNames\", MessageId = \"bool\", Justification = \"We specificaly want type names\")]\n        public static bool AsBool(this string value, bool defaultValue)\n        {\n            bool result;\n            return Boolean.TryParse(value, out result) ? result : defaultValue;\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We want to make this user friendly and return the default value on all failures\")]\n        public static TValue As<TValue>(this string value, TValue defaultValue)\n        {\n            try\n            {\n                TypeConverter converter = TypeDescriptor.GetConverter(typeof(TValue));\n                if (converter.CanConvertFrom(typeof(string)))\n                {\n                    return (TValue)converter.ConvertFrom(value);\n                }\n                // try the other direction\n                converter = TypeDescriptor.GetConverter(typeof(string));\n                if (converter.CanConvertTo(typeof(TValue)))\n                {\n                    return (TValue)converter.ConvertTo(value, typeof(TValue));\n                }\n            }\n            catch\n            {\n                // eat all exceptions and return the defaultValue, assumption is that its always a parse/format exception\n            }\n            return defaultValue;\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1720:IdentifiersShouldNotContainTypeNames\", MessageId = \"bool\", Justification = \"We specificaly want type names\")]\n        public static bool IsBool(this string value)\n        {\n            bool result;\n            return Boolean.TryParse(value, out result);\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1720:IdentifiersShouldNotContainTypeNames\", MessageId = \"int\", Justification = \"We specificaly want type names\")]\n        public static bool IsInt(this string value)\n        {\n            int result;\n            return Int32.TryParse(value, out result);\n        }\n\n        public static bool IsDecimal(this string value)\n        {\n            // For some reason, Decimal.TryParse incorrectly parses floating point values as decimal value for some cultures.\n            // For example, 12.5 is parsed as 125 in lt-LT.\n            return Is<Decimal>(value);\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1720:IdentifiersShouldNotContainTypeNames\", MessageId = \"float\", Justification = \"We specificaly want type names\")]\n        public static bool IsFloat(this string value)\n        {\n            float result;\n            return Single.TryParse(value, out result);\n        }\n\n        public static bool IsDateTime(this string value)\n        {\n            DateTime result;\n            return DateTime.TryParse(value, out result);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"This is the identical to the way it is done in TypeConverter.IsValid\"),\n         SuppressMessage(\"Microsoft.Design\", \"CA1004:GenericMethodsShouldProvideTypeParameter\", Justification = \"This is the signature we want\")]\n        public static bool Is<TValue>(this string value)\n        {\n            TypeConverter converter = TypeDescriptor.GetConverter(typeof(TValue));\n            if (converter != null)\n            {\n                try\n                {\n                    if ((value == null) || converter.CanConvertFrom(null, value.GetType()))\n                    {\n                        // TypeConverter.IsValid essentially does this - a try catch - but uses InvariantCulture to convert. \n                        converter.ConvertFrom(null, CultureInfo.CurrentCulture, value);\n                        return true;\n                    }\n                }\n                catch\n                {\n                }\n            }\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/StringWriterExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Text;\n\nnamespace System.Web.WebPages\n{\n    internal static class StringWriterExtensions\n    {\n        public const int BufferSize = 1024;\n\n        // Used to copy data from a string writer to avoid allocating the full string\n        // which can end up on LOH (and cause memory fragmentation).\n        public static void CopyTo(this StringWriter input, TextWriter output)\n        {\n            StringBuilder builder = input.GetStringBuilder();\n\n            int remainingChars = builder.Length;\n            int bufferSize = Math.Min(builder.Length, BufferSize);\n\n            char[] buffer = new char[bufferSize];\n            int currentPosition = 0;\n\n            while (remainingChars > 0)\n            {\n                int copyLen = Math.Min(bufferSize, remainingChars);\n\n                builder.CopyTo(currentPosition, buffer, 0, copyLen);\n\n                output.Write(buffer, 0, copyLen);\n\n                currentPosition += copyLen;\n                remainingChars -= copyLen;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/System.Web.WebPages.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{76EFA9C5-8D7E-4FDF-B710-E20F8B6B00D2}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>System.Web.WebPages</RootNamespace>\n    <AssemblyName>System.Web.WebPages</AssemblyName>\n    <DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>\n    <RunCodeAnalysis>$(CodeAnalysis)</RunCodeAnalysis>\n    <CodeAnalysisRuleSet>..\\Strict.ruleset</CodeAnalysisRuleSet>\n    <DefineConstants>$(DefineConstants);ASPNETWEBPAGES</DefineConstants>\n    <NoWarn>1591</NoWarn>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Microsoft.Web.Infrastructure.1.0.0.0\\lib\\net40\\Microsoft.Web.Infrastructure.dll</HintPath>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.ComponentModel.DataAnnotations\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Data.Linq\" />\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"System.XML\" />\n    <Reference Include=\"System.Xml.Linq\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\CommonAssemblyInfo.cs\">\n      <Link>Properties\\CommonAssemblyInfo.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\CommonResources.Designer.cs\">\n      <Link>Common\\CommonResources.Designer.cs</Link>\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>CommonResources.resx</DependentUpon>\n    </Compile>\n    <Compile Include=\"..\\Common\\CollectionExtensions.cs\">\n      <Link>Common\\CollectionExtensions.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Empty.cs\">\n      <Link>Common\\Empty.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\HashCodeCombiner.cs\">\n      <Link>Common\\HashCodeCombiner.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\ListWrapperCollection.cs\">\n      <Link>Common\\ListWrapperCollection.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\PathHelpers.cs\">\n      <Link>Common\\PathHelpers.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\GlobalSuppressions.cs\">\n      <Link>Common\\GlobalSuppressions.cs</Link>\n    </Compile>\n    <Compile Include=\"ApplicationPart.cs\" />\n    <Compile Include=\"ApplicationParts\\ApplicationPartRegistry.cs\" />\n    <Compile Include=\"ApplicationParts\\DictionaryBasedVirtualPathFactory.cs\" />\n    <Compile Include=\"ApplicationParts\\IResourceAssembly.cs\" />\n    <Compile Include=\"ApplicationParts\\LazyAction.cs\" />\n    <Compile Include=\"ApplicationParts\\ResourceAssembly.cs\" />\n    <Compile Include=\"ApplicationParts\\ResourceHandler.cs\" />\n    <Compile Include=\"ApplicationParts\\ResourceRouteHandler.cs\" />\n    <Compile Include=\"ApplicationStartPage.cs\" />\n    <Compile Include=\"AttributeValue.cs\" />\n    <Compile Include=\"BrowserOverrideStore.cs\" />\n    <Compile Include=\"BrowserOverrideStores.cs\" />\n    <Compile Include=\"BrowserOverride.cs\" />\n    <Compile Include=\"BuildManagerWrapper.cs\" />\n    <Compile Include=\"CookieBrowserOverrideStore.cs\" />\n    <Compile Include=\"DisplayInfo.cs\" />\n    <Compile Include=\"DisplayModeProvider.cs\" />\n    <Compile Include=\"BrowserHelpers.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\ClaimUidExtractor.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\AntiForgeryTokenStore.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\MachineKey45CryptoSystem.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\ITokenStore.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\TokenValidator.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\ITokenValidator.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\IClaimUidExtractor.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\ICryptoSystem.cs\" />\n    <Compile Include=\"Helpers\\Claims\\Claim.cs\" />\n    <Compile Include=\"Helpers\\Claims\\ClaimsIdentity.cs\" />\n    <Compile Include=\"Helpers\\Claims\\ClaimsIdentityConverter.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\AntiForgeryConfigWrapper.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\AntiForgeryWorker.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\IAntiForgeryTokenSerializer.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\IAntiForgeryConfig.cs\" />\n    <Compile Include=\"Helpers\\CryptoUtil.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\AntiForgeryToken.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\BinaryBlob.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\AntiForgeryTokenSerializer.cs\" />\n    <Compile Include=\"Helpers\\AntiForgeryConfig.cs\" />\n    <Compile Include=\"Helpers\\IAntiForgeryAdditionalDataProvider.cs\" />\n    <Compile Include=\"IDisplayMode.cs\" />\n    <Compile Include=\"DefaultDisplayMode.cs\" />\n    <Compile Include=\"FileExistenceCache.cs\" />\n    <Compile Include=\"Helpers\\AntiForgery.cs\" />\n    <Compile Include=\"HttpContextExtensions.cs\" />\n    <Compile Include=\"Instrumentation\\HttpContextAdapter.Availability.cs\" />\n    <Compile Include=\"Instrumentation\\HttpContextAdapter.generated.cs\">\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>HttpContextAdapter.tt</DependentUpon>\n    </Compile>\n    <Compile Include=\"Instrumentation\\InstrumentationService.cs\" />\n    <Compile Include=\"Instrumentation\\PageExecutionContextAdapter.generated.cs\">\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>PageExecutionContextAdapter.tt</DependentUpon>\n    </Compile>\n    <Compile Include=\"Instrumentation\\PageExecutionListenerAdapter.generated.cs\">\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>PageExecutionListenerAdapter.tt</DependentUpon>\n    </Compile>\n    <Compile Include=\"Instrumentation\\PageInstrumentationServiceAdapter.cs\" />\n    <Compile Include=\"Instrumentation\\PositionTagged.cs\" />\n    <Compile Include=\"IVirtualPathUtility.cs\" />\n    <Compile Include=\"MimeMapping.cs\" />\n    <Compile Include=\"Mvc\\ModelClientValidationEqualToRule.cs\" />\n    <Compile Include=\"Mvc\\ModelClientValidationMinLengthRule.cs\" />\n    <Compile Include=\"Mvc\\ModelClientValidationMembershipPasswordRule.cs\" />\n    <Compile Include=\"Mvc\\ModelClientValidationRangeRule.cs\" />\n    <Compile Include=\"Mvc\\ModelClientValidationRegexRule.cs\" />\n    <Compile Include=\"Mvc\\ModelClientValidationRemoteRule.cs\" />\n    <Compile Include=\"Mvc\\ModelClientValidationRequiredRule.cs\" />\n    <Compile Include=\"Mvc\\ModelClientValidationRule.cs\" />\n    <Compile Include=\"Mvc\\ModelClientValidationMaxLengthRule.cs\" />\n    <Compile Include=\"Mvc\\ModelClientValidationStringLengthRule.cs\" />\n    <Compile Include=\"Mvc\\UnobtrusiveValidationAttributesGenerator.cs\" />\n    <Compile Include=\"RequestBrowserOverrideStore.cs\" />\n    <Compile Include=\"StringWriterExtensions.cs\" />\n    <Compile Include=\"Utils\\HtmlAttributePropertyHelper.cs\" />\n    <Compile Include=\"..\\Common\\PropertyHelper.cs\" />\n    <Compile Include=\"Utils\\SessionStateUtil.cs\" />\n    <Compile Include=\"Utils\\TypeHelper.cs\" />\n    <Compile Include=\"Utils\\UrlRewriterHelper.cs\" />\n    <Compile Include=\"Utils\\UrlUtil.cs\" />\n    <Compile Include=\"Validation\\CompareValidator.cs\" />\n    <Compile Include=\"Validation\\DataTypeValidator.cs\" />\n    <Compile Include=\"Validation\\IValidator.cs\" />\n    <Compile Include=\"Validation\\RequestFieldValidatorBase.cs\" />\n    <Compile Include=\"Validation\\ValidationAttributeAdapter.cs\" />\n    <Compile Include=\"Validation\\ValidationHelper.cs\" />\n    <Compile Include=\"Validation\\Validator.cs\" />\n    <Compile Include=\"VirtualPathFactoryExtensions.cs\" />\n    <Compile Include=\"Mvc\\HttpAntiForgeryException.cs\" />\n    <Compile Include=\"RequestExtensions.cs\" />\n    <Compile Include=\"Helpers\\UnvalidatedRequestValues.cs\" />\n    <Compile Include=\"Helpers\\Validation.cs\" />\n    <Compile Include=\"ITemplateFile.cs\" />\n    <Compile Include=\"Mvc\\TagBuilder.cs\" />\n    <Compile Include=\"Mvc\\TagRenderMode.cs\" />\n    <Compile Include=\"StartPage.cs\" />\n    <Compile Include=\"RequestResourceTracker.cs\" />\n    <Compile Include=\"DynamicHttpApplicationState.cs\" />\n    <Compile Include=\"DynamicPageDataDictionary.cs\" />\n    <Compile Include=\"Html\\HtmlHelper.Checkbox.cs\" />\n    <Compile Include=\"Html\\HtmlHelper.cs\" />\n    <Compile Include=\"Html\\HtmlHelper.Input.cs\" />\n    <Compile Include=\"Html\\HtmlHelper.Internal.cs\" />\n    <Compile Include=\"Html\\HtmlHelper.Label.cs\" />\n    <Compile Include=\"Html\\HtmlHelper.Radio.cs\" />\n    <Compile Include=\"Html\\HtmlHelper.Select.cs\" />\n    <Compile Include=\"Html\\HtmlHelper.TextArea.cs\" />\n    <Compile Include=\"Html\\HtmlHelper.Validation.cs\" />\n    <Compile Include=\"Html\\SelectListItem.cs\" />\n    <Compile Include=\"IVirtualPathFactory.cs\" />\n    <Compile Include=\"Scope\\ApplicationScopeStorageDictionary.cs\" />\n    <Compile Include=\"Scope\\AspNetRequestScopeStorageProvider.cs\" />\n    <Compile Include=\"Common\\DisposableAction.cs\" />\n    <Compile Include=\"Scope\\IScopeStorageProvider.cs\" />\n    <Compile Include=\"Scope\\ScopeStorage.cs\" />\n    <Compile Include=\"Scope\\ScopeStorageComparer.cs\" />\n    <Compile Include=\"Scope\\ScopeStorageDictionary.cs\" />\n    <Compile Include=\"Scope\\StaticScopeStorageProvider.cs\" />\n    <Compile Include=\"Scope\\WebConfigScopeStorageDictionary.cs\" />\n    <Compile Include=\"TemplateFileInfo.cs\" />\n    <Compile Include=\"TemplateStack.cs\" />\n    <Compile Include=\"Utils\\CultureUtil.cs\" />\n    <Compile Include=\"Utils\\PathUtil.cs\" />\n    <Compile Include=\"VirtualPathUtilityWrapper.cs\" />\n    <Compile Include=\"WebPageHttpModule.cs\" />\n    <Compile Include=\"HelperPage.cs\" />\n    <Compile Include=\"HelperResult.cs\" />\n    <Compile Include=\"IWebPageRequestExecutor.cs\" />\n    <Compile Include=\"Html\\ModelState.cs\" />\n    <Compile Include=\"Html\\ModelStateDictionary.cs\" />\n    <Compile Include=\"WebPageRoute.cs\" />\n    <Compile Include=\"WebPageContext.cs\" />\n    <Compile Include=\"SectionWriter.cs\" />\n    <Compile Include=\"WebPageExecutingBase.cs\" />\n    <Compile Include=\"WebPageRenderingBase.cs\" />\n    <Compile Include=\"ReflectionDynamicObject.cs\" />\n    <Compile Include=\"ResponseExtensions.cs\" />\n    <Compile Include=\"PageDataDictionary.cs\" />\n    <Compile Include=\"PageVirtualPathAttribute.cs\" />\n    <Compile Include=\"UrlDataList.cs\" />\n    <Compile Include=\"StringExtensions.cs\" />\n    <Compile Include=\"GlobalSuppressions.cs\" />\n    <Compile Include=\"Resources\\WebPageResources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>WebPageResources.resx</DependentUpon>\n    </Compile>\n    <Compile Include=\"WebPageMatch.cs\" />\n    <Compile Include=\"VirtualPathFactoryManager.cs\" />\n    <Compile Include=\"WebPageBase.cs\" />\n    <Compile Include=\"WebPageHttpHandler.cs\" />\n    <Compile Include=\"PreApplicationStartCode.cs\" />\n    <Compile Include=\"Utils\\BuildManagerExceptionUtil.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"WebPage.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Service Include=\"{508349B6-6B84-4DF5-91F0-309BEEBAD82D}\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"..\\CommonResources.resx\">\n      <Link>Common\\CommonResources.resx</Link>\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>CommonResources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n    <EmbeddedResource Include=\"Resources\\WebPageResources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>WebPageResources.Designer.cs</LastGenOutput>\n      <SubType>Designer</SubType>\n    </EmbeddedResource>\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\System.Web.Razor\\System.Web.Razor.csproj\">\n      <Project>{8F18041B-9410-4C36-A9C5-067813DF5F31}</Project>\n      <Name>System.Web.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.WebPages.Deployment\\System.Web.WebPages.Deployment.csproj\">\n      <Project>{22BABB60-8F02-4027-AFFC-ACF069954536}</Project>\n      <Name>System.Web.WebPages.Deployment</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"Instrumentation\\HttpContextAdapter.tt\">\n      <Generator>TextTemplatingFileGenerator</Generator>\n      <LastGenOutput>HttpContextAdapter.generated.cs</LastGenOutput>\n    </None>\n    <None Include=\"Instrumentation\\PageExecutionContextAdapter.tt\">\n      <Generator>TextTemplatingFileGenerator</Generator>\n      <LastGenOutput>PageExecutionContextAdapter.generated.cs</LastGenOutput>\n    </None>\n    <None Include=\"Instrumentation\\PageExecutionListenerAdapter.tt\">\n      <Generator>TextTemplatingFileGenerator</Generator>\n      <LastGenOutput>PageExecutionListenerAdapter.generated.cs</LastGenOutput>\n    </None>\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <ItemGroup>\n    <CodeAnalysisDictionary Include=\"..\\CodeAnalysisDictionary.xml\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n</Project>"
  },
  {
    "path": "src/System.Web.WebPages/TemplateFileInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.WebPages\n{\n    /// <summary>\n    /// TemplateFileInfo specifies properties of a template such as VirtualPath. \n    /// This type allows us to modify the behavior of ITemplateFile between releases without changing the interface.\n    /// </summary>\n    public class TemplateFileInfo\n    {\n        private readonly string _virtualPath;\n\n        public TemplateFileInfo(string virtualPath)\n        {\n            _virtualPath = virtualPath;\n        }\n\n        public string VirtualPath\n        {\n            get { return _virtualPath; }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/TemplateStack.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\n\nnamespace System.Web.WebPages\n{\n    /// <summary>\n    /// Template stacks store a stack of template files. WebPageExecutingBase implements this type, so when executing Plan9 or Mvc WebViewPage,\n    /// the stack would contain instances of the page. \n    /// The stack can be queried to identify properties of the current executing file such as the virtual path of the file.\n    /// </summary>\n    [SuppressMessage(\"Microsoft.Naming\", \"CA1711:IdentifiersShouldNotHaveIncorrectSuffix\", Justification = \"TemplateStack is a stack\")]\n    public static class TemplateStack\n    {\n        private static readonly object _contextKey = new object();\n\n        public static ITemplateFile GetCurrentTemplate(HttpContextBase httpContext)\n        {\n            if (httpContext == null)\n            {\n                throw new ArgumentNullException(\"httpContext\");\n            }\n            return GetStack(httpContext).FirstOrDefault();\n        }\n\n        public static ITemplateFile Pop(HttpContextBase httpContext)\n        {\n            if (httpContext == null)\n            {\n                throw new ArgumentNullException(\"httpContext\");\n            }\n            return GetStack(httpContext).Pop();\n        }\n\n        public static void Push(HttpContextBase httpContext, ITemplateFile templateFile)\n        {\n            if (templateFile == null)\n            {\n                throw new ArgumentNullException(\"templateFile\");\n            }\n            if (httpContext == null)\n            {\n                throw new ArgumentNullException(\"httpContext\");\n            }\n            GetStack(httpContext).Push(templateFile);\n        }\n\n        private static Stack<ITemplateFile> GetStack(HttpContextBase httpContext)\n        {\n            var stack = httpContext.Items[_contextKey] as Stack<ITemplateFile>;\n            if (stack == null)\n            {\n                stack = new Stack<ITemplateFile>();\n                httpContext.Items[_contextKey] = stack;\n            }\n            return stack;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/UrlDataList.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.WebPages.Resources;\n\nnamespace System.Web.WebPages\n{\n    // Wrapper for list that lets us return empty string for non existant pieces of the Url\n    internal class UrlDataList : IList<string>\n    {\n        private List<string> _urlData;\n\n        public UrlDataList(string pathInfo)\n        {\n            if (String.IsNullOrEmpty(pathInfo))\n            {\n                _urlData = new List<string>();\n            }\n            else\n            {\n                _urlData = pathInfo.Split(new char[] { '/' }).ToList();\n            }\n        }\n\n        public int Count\n        {\n            get { return _urlData.Count; }\n        }\n\n        public bool IsReadOnly\n        {\n            get { return true; }\n        }\n\n        public string this[int index]\n        {\n            get\n            {\n                // REVIEW: what about index < 0\n                if (index >= _urlData.Count)\n                {\n                    return String.Empty;\n                }\n                return _urlData[index];\n            }\n            set { throw new NotSupportedException(WebPageResources.UrlData_ReadOnly); }\n        }\n\n        public int IndexOf(string item)\n        {\n            return _urlData.IndexOf(item);\n        }\n\n        public void Insert(int index, string item)\n        {\n            throw new NotSupportedException(WebPageResources.UrlData_ReadOnly);\n        }\n\n        public void RemoveAt(int index)\n        {\n            throw new NotSupportedException(WebPageResources.UrlData_ReadOnly);\n        }\n\n        public void Add(string item)\n        {\n            throw new NotSupportedException(WebPageResources.UrlData_ReadOnly);\n        }\n\n        public void Clear()\n        {\n            throw new NotSupportedException(WebPageResources.UrlData_ReadOnly);\n        }\n\n        public bool Contains(string item)\n        {\n            return _urlData.Contains(item);\n        }\n\n        public void CopyTo(string[] array, int arrayIndex)\n        {\n            _urlData.CopyTo(array, arrayIndex);\n        }\n\n        public bool Remove(string item)\n        {\n            throw new NotSupportedException(WebPageResources.UrlData_ReadOnly);\n        }\n\n        public IEnumerator<string> GetEnumerator()\n        {\n            return _urlData.GetEnumerator();\n        }\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return _urlData.GetEnumerator();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Utils/BuildManagerExceptionUtil.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.IO;\nusing System.Web.WebPages.Resources;\nusing Microsoft.Web.Infrastructure;\n\nnamespace System.Web.WebPages\n{\n    internal static class BuildManagerExceptionUtil\n    {\n        // Checks the exception to see if it is from CompilationUtil.GetBuildProviderTypeFromExtension, which will throw\n        // an exception about an unsupported extension. \n        // Actual error format: There is no build provider registered for the extension '.txt'. You can register one in the <compilation><buildProviders> section in machine.config or web.config. Make sure is has a BuildProviderAppliesToAttribute attribute which includes the value 'Web' or 'All'. \n        internal static bool IsUnsupportedExtensionError(HttpException e)\n        {\n            Exception exception = e;\n\n            // Go through the layers of exceptions to find if any of them is from GetBuildProviderTypeFromExtension\n            while (exception != null)\n            {\n                var site = exception.TargetSite;\n                if (site != null && site.Name == \"GetBuildProviderTypeFromExtension\" && site.DeclaringType != null && site.DeclaringType.Name == \"CompilationUtil\")\n                {\n                    return true;\n                }\n                exception = exception.InnerException;\n            }\n            return false;\n        }\n\n        internal static void ThrowIfUnsupportedExtension(string virtualPath, HttpException e)\n        {\n            if (IsUnsupportedExtensionError(e))\n            {\n                var extension = Path.GetExtension(virtualPath);\n                throw new HttpException(String.Format(CultureInfo.CurrentCulture, WebPageResources.WebPage_FileNotSupported, extension, virtualPath));\n            }\n        }\n\n        internal static void ThrowIfCodeDomDefinedExtension(string virtualPath, HttpException e)\n        {\n            if (e is HttpCompileException)\n            {\n                var extension = Path.GetExtension(virtualPath);\n                if (InfrastructureHelper.IsCodeDomDefinedExtension(extension))\n                {\n                    throw new HttpException(String.Format(CultureInfo.CurrentCulture, WebPageResources.WebPage_FileNotSupported, extension, virtualPath));\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Utils/CultureUtil.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.Linq;\nusing System.Threading;\n\nnamespace System.Web.WebPages\n{\n    internal static class CultureUtil\n    {\n        internal static void SetCulture(Thread thread, HttpContextBase context, string cultureName)\n        {\n            Debug.Assert(!String.IsNullOrEmpty(cultureName));\n            CultureInfo cultureInfo = GetCulture(context, cultureName);\n            if (cultureInfo != null)\n            {\n                thread.CurrentCulture = cultureInfo;\n            }\n        }\n\n        internal static void SetUICulture(Thread thread, HttpContextBase context, string cultureName)\n        {\n            Debug.Assert(!String.IsNullOrEmpty(cultureName));\n            CultureInfo cultureInfo = GetCulture(context, cultureName);\n            if (cultureInfo != null)\n            {\n                thread.CurrentUICulture = cultureInfo;\n            }\n        }\n\n        private static CultureInfo GetCulture(HttpContextBase context, string cultureName)\n        {\n            if (cultureName.Equals(\"auto\", StringComparison.OrdinalIgnoreCase))\n            {\n                return DetermineAutoCulture(context);\n            }\n            else\n            {\n                return CultureInfo.GetCultureInfo(cultureName);\n            }\n        }\n\n        private static CultureInfo DetermineAutoCulture(HttpContextBase context)\n        {\n            HttpRequestBase request = context.Request;\n            Debug.Assert(request != null); //This call is made from a WebPageExecutingBase. Request can never be null when inside a page.\n            CultureInfo culture = null;\n\n            if (request.UserLanguages != null)\n            {\n                string userLanguageEntry = request.UserLanguages.FirstOrDefault();\n                if (!String.IsNullOrWhiteSpace(userLanguageEntry))\n                {\n                    // Check if user language has q parameter. E.g. something like this: \"as-IN;q=0.3\"\n                    int index = userLanguageEntry.IndexOf(';');\n                    if (index != -1)\n                    {\n                        userLanguageEntry = userLanguageEntry.Substring(0, index);\n                    }\n\n                    try\n                    {\n                        culture = new CultureInfo(userLanguageEntry);\n                    }\n                    catch (CultureNotFoundException)\n                    {\n                        // There is no easy way to ask if a given culture is invalid so we have to handle exception.  \n                    }\n                }\n            }\n            return culture;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Utils/HtmlAttributePropertyHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Reflection;\n\nnamespace System.Web.WebPages\n{\n    internal class HtmlAttributePropertyHelper : PropertyHelper\n    {\n        private static ConcurrentDictionary<Type, PropertyHelper[]> _reflectionCache = new ConcurrentDictionary<Type, PropertyHelper[]>();\n\n        public static new PropertyHelper[] GetProperties(object instance)\n        {\n            return GetProperties(instance, CreateInstance, _reflectionCache);\n        }\n\n        private static PropertyHelper CreateInstance(PropertyInfo property)\n        {\n            return new HtmlAttributePropertyHelper(property);\n        }\n\n        public HtmlAttributePropertyHelper(PropertyInfo property)\n            : base(property)\n        {\n        }\n\n        public override string Name\n        {\n            get\n            {\n                return base.Name;\n            }\n\n            protected set\n            {\n                base.Name = value == null ? null : value.Replace('_', '-');\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Utils/PathUtil.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\n\nnamespace System.Web.WebPages\n{\n    internal static class PathUtil\n    {\n        /// <summary>\n        /// Path.GetExtension performs a CheckInvalidPathChars(path) which blows up for paths that do not translate to valid physical paths but are valid paths in ASP.NET\n        /// This method is a near clone of Path.GetExtension without a call to CheckInvalidPathChars(path);\n        /// </summary>\n        internal static string GetExtension(string path)\n        {\n            if (String.IsNullOrEmpty(path))\n            {\n                return path;\n            }\n            int current = path.Length;\n            while (--current >= 0)\n            {\n                char ch = path[current];\n                if (ch == '.')\n                {\n                    if (current == path.Length - 1)\n                    {\n                        break;\n                    }\n                    return path.Substring(current);\n                }\n                if (ch == Path.DirectorySeparatorChar || ch == Path.AltDirectorySeparatorChar)\n                {\n                    break;\n                }\n            }\n            return String.Empty;\n        }\n\n        internal static bool IsWithinAppRoot(string appDomainAppVirtualPath, string virtualPath)\n        {\n            if (appDomainAppVirtualPath == null)\n            {\n                // If the runtime has not been initialized, just return true.\n                return true;\n            }\n\n            var absPath = virtualPath;\n            if (!VirtualPathUtility.IsAbsolute(absPath))\n            {\n                absPath = VirtualPathUtility.ToAbsolute(absPath);\n            }\n            // We need to call this overload because it returns null if the path is not within the application root.\n            // The overload calls into MakeVirtualPathAppRelative(string virtualPath, string applicationPath, bool nullIfNotInApp), with \n            // nullIfNotInApp set to true.\n            return VirtualPathUtility.ToAppRelative(absPath, appDomainAppVirtualPath) != null;\n        }\n\n        /// <summary>\n        /// Determines true if the path is simply \"MyPath\", and not app-relative \"~/MyPath\" or absolute \"/MyApp/MyPath\" or relative \"../Test/MyPath\"\n        /// </summary>\n        /// <returns>True if it is a not app-relative, absolute or relative.</returns>\n        internal static bool IsSimpleName(string path)\n        {\n            if (VirtualPathUtility.IsAbsolute(path) || VirtualPathUtility.IsAppRelative(path))\n            {\n                return false;\n            }\n            if (path.StartsWith(\".\", StringComparison.OrdinalIgnoreCase))\n            {\n                return false;\n            }\n            return true;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Utils/SessionStateUtil.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.Linq;\nusing System.Web.Razor;\nusing System.Web.SessionState;\nusing System.Web.WebPages.Resources;\n\nnamespace System.Web.WebPages\n{\n    internal static class SessionStateUtil\n    {\n        private static readonly ConcurrentDictionary<Type, SessionStateBehavior?> _sessionStateBehaviorCache = new ConcurrentDictionary<Type, SessionStateBehavior?>();\n\n        internal static void SetUpSessionState(HttpContextBase context, IHttpHandler handler)\n        {\n            SetUpSessionState(context, handler, _sessionStateBehaviorCache);\n        }\n\n        internal static void SetUpSessionState(HttpContextBase context, IHttpHandler handler, ConcurrentDictionary<Type, SessionStateBehavior?> cache)\n        {\n            WebPageHttpHandler webPageHandler = handler as WebPageHttpHandler;\n            Debug.Assert(handler != null);\n            SessionStateBehavior? sessionState = GetSessionStateBehavior(webPageHandler.RequestedPage, cache);\n\n            if (sessionState != null)\n            {\n                // If the page explicitly specifies a session state value, return since it has the most priority.\n                context.SetSessionStateBehavior(sessionState.Value);\n                return;\n            }\n\n            WebPageRenderingBase page = webPageHandler.StartPage;\n            StartPage startPage = null;\n            do\n            {\n                // Drill down _AppStart and _PageStart.\n                startPage = page as StartPage;\n                if (startPage != null)\n                {\n                    sessionState = GetSessionStateBehavior(page, cache);\n                    page = startPage.ChildPage;\n                }\n            }\n            while (startPage != null);\n\n            if (sessionState != null)\n            {\n                context.SetSessionStateBehavior(sessionState.Value);\n            }\n        }\n\n        private static SessionStateBehavior? GetSessionStateBehavior(WebPageExecutingBase page, ConcurrentDictionary<Type, SessionStateBehavior?> cache)\n        {\n            return cache.GetOrAdd(page.GetType(), type =>\n            {\n                SessionStateBehavior sessionStateBehavior = SessionStateBehavior.Default;\n                var attributes = (RazorDirectiveAttribute[])type.GetCustomAttributes(typeof(RazorDirectiveAttribute), inherit: false);\n                var directiveAttributes = attributes.Where(attr => StringComparer.OrdinalIgnoreCase.Equals(\"sessionstate\", attr.Name))\n                    .ToList();\n\n                if (!directiveAttributes.Any())\n                {\n                    return null;\n                }\n                if (directiveAttributes.Count > 1)\n                {\n                    throw new InvalidOperationException(WebPageResources.SessionState_TooManyValues);\n                }\n                var directiveAttribute = directiveAttributes[0];\n                if (!Enum.TryParse<SessionStateBehavior>(directiveAttribute.Value, ignoreCase: true, result: out sessionStateBehavior))\n                {\n                    var values = Enum.GetValues(typeof(SessionStateBehavior)).Cast<SessionStateBehavior>().Select(s => s.ToString());\n                    throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, WebPageResources.SessionState_InvalidValue,\n                                                              directiveAttribute.Value, page.VirtualPath, String.Join(\", \", values)));\n                }\n                return sessionStateBehavior;\n            });\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Utils/TypeHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Web.Routing;\n\nnamespace System.Web.WebPages\n{\n    internal static class TypeHelper\n    {\n        /// <summary>\n        /// Given an object of anonymous type, add each property as a key and associated with its value to a dictionary.\n        ///\n        /// This helper will cache accessors and types, and is intended when the anonymous object is accessed multiple\n        /// times throughout the lifetime of the web application.\n        /// </summary>\n        public static RouteValueDictionary ObjectToDictionary(object value)\n        {\n            RouteValueDictionary dictionary = new RouteValueDictionary();\n\n            if (value != null)\n            {\n                foreach (PropertyHelper helper in PropertyHelper.GetProperties(value))\n                {\n                    dictionary.Add(helper.Name, helper.GetValue(value));\n                }\n            }\n\n            return dictionary;\n        }\n\n        /// <summary>\n        /// Given an object of anonymous type, add each property as a key and associated with its value to a dictionary.\n        ///\n        /// This helper will not cache accessors and types, and is intended when the anonymous object is accessed once\n        /// or very few times throughout the lifetime of the web application.\n        /// </summary>\n        public static RouteValueDictionary ObjectToDictionaryUncached(object value)\n        {\n            RouteValueDictionary dictionary = new RouteValueDictionary();\n\n            if (value != null)\n            {\n                foreach (PropertyHelper helper in PropertyHelper.GetProperties(value))\n                {\n                    dictionary.Add(helper.Name, helper.GetValue(value));\n                }\n            }\n\n            return dictionary;\n        }\n\n        /// <summary>\n        /// Given an object of anonymous type, add each property as a key and associated with its value to the given dictionary.\n        /// </summary>\n        public static void AddAnonymousObjectToDictionary(IDictionary<string, object> dictionary, object value)\n        {\n            var values = ObjectToDictionary(value);\n            foreach (var item in values)\n            {\n                dictionary.Add(item);\n            }\n        }\n\n        /// <remarks>This code is copied from http://www.liensberger.it/web/blog/?p=191 </remarks>\n        public static bool IsAnonymousType(Type type)\n        {\n            if (type == null)\n            {\n                throw new ArgumentNullException(\"type\");\n            }\n\n            // TODO: The only way to detect anonymous types right now.\n            return Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false)\n                   && type.IsGenericType && type.Name.Contains(\"AnonymousType\")\n                   && (type.Name.StartsWith(\"<>\", StringComparison.OrdinalIgnoreCase) || type.Name.StartsWith(\"VB$\", StringComparison.OrdinalIgnoreCase))\n                   && (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Utils/UrlRewriterHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\n\nnamespace System.Web.WebPages\n{\n    internal class UrlRewriterHelper\n    {\n        // internal for tests\n        internal const string UrlWasRewrittenServerVar = \"IIS_WasUrlRewritten\";\n        internal const string UrlRewriterEnabledServerVar = \"IIS_UrlRewriteModule\";\n\n        internal const string UrlWasRequestRewrittenTrueValue = \"true\";\n        internal const string UrlWasRequestRewrittenFalseValue = \"false\";\n\n        private object _lockObject = new object();\n        private bool _urlRewriterIsTurnedOnValue;\n        private volatile bool _urlRewriterIsTurnedOnCalculated = false;\n\n        private static bool WasThisRequestRewritten(HttpContextBase httpContext)\n        {\n            if (httpContext.Items.Contains(UrlWasRewrittenServerVar))\n            {\n                return Object.Equals(httpContext.Items[UrlWasRewrittenServerVar], UrlWasRequestRewrittenTrueValue);\n            }\n            else\n            {\n                HttpWorkerRequest httpWorkerRequest = (HttpWorkerRequest)httpContext.GetService(typeof(HttpWorkerRequest));\n                bool requestWasRewritten = (httpWorkerRequest != null && httpWorkerRequest.GetServerVariable(UrlWasRewrittenServerVar) != null);\n\n                if (requestWasRewritten)\n                {\n                    httpContext.Items.Add(UrlWasRewrittenServerVar, UrlWasRequestRewrittenTrueValue);\n                }\n                else\n                {\n                    httpContext.Items.Add(UrlWasRewrittenServerVar, UrlWasRequestRewrittenFalseValue);\n                }\n\n                return requestWasRewritten;\n            }\n        }\n\n        private bool IsUrlRewriterTurnedOn(HttpContextBase httpContext)\n        {\n            // Need to do double-check locking because a single instance of this class is shared in the entire app domain (see PathHelpers)\n            if (!_urlRewriterIsTurnedOnCalculated)\n            {\n                lock (_lockObject)\n                {\n                    if (!_urlRewriterIsTurnedOnCalculated)\n                    {\n                        HttpWorkerRequest httpWorkerRequest = (HttpWorkerRequest)httpContext.GetService(typeof(HttpWorkerRequest));\n                        bool urlRewriterIsEnabled = (httpWorkerRequest != null && httpWorkerRequest.GetServerVariable(UrlRewriterEnabledServerVar) != null);\n                        _urlRewriterIsTurnedOnValue = urlRewriterIsEnabled;\n                        _urlRewriterIsTurnedOnCalculated = true;\n                    }\n                }\n            }\n            return _urlRewriterIsTurnedOnValue;\n        }\n\n        public virtual bool WasRequestRewritten(HttpContextBase httpContext)\n        {\n            return IsUrlRewriterTurnedOn(httpContext) && WasThisRequestRewritten(httpContext);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Utils/UrlUtil.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Text;\nusing System.Web.Routing;\n\nnamespace System.Web.WebPages\n{\n    internal static class UrlUtil\n    {\n        private static UrlRewriterHelper _urlRewriterHelper = new UrlRewriterHelper();\n\n        // this method can accept an app-relative path or an absolute path for contentPath\n        public static string GenerateClientUrl(HttpContextBase httpContext, string contentPath)\n        {\n            if (String.IsNullOrEmpty(contentPath))\n            {\n                return contentPath;\n            }\n\n            // many of the methods we call internally can't handle query strings properly, so just strip it out for\n            // the time being\n            string query;\n            contentPath = StripQuery(contentPath, out query);\n\n            // many of the methods we call internally can't handle query strings properly, so tack it on after processing\n            // the virtual app path and url rewrites\n            if (String.IsNullOrEmpty(query))\n            {\n                return GenerateClientUrlInternal(httpContext, contentPath);\n            }\n            else\n            {\n                return GenerateClientUrlInternal(httpContext, contentPath) + query;\n            }\n        }\n\n        public static string GenerateClientUrl(HttpContextBase httpContext, string basePath, string path, params object[] pathParts)\n        {\n            if (String.IsNullOrEmpty(path))\n            {\n                return path;\n            }\n\n            if (pathParts != null)\n            {\n                for (int i = 0; i < pathParts.Length; i++)\n                {\n                    if (pathParts[i] == null)\n                    {\n                        throw new ArgumentNullException(\"pathParts\");\n                    }\n                }\n            }\n\n            if (basePath != null)\n            {\n                path = VirtualPathUtility.Combine(basePath, path);\n            }\n\n            string query;\n            string processedPath = BuildUrl(path, out query, pathParts);\n\n            // many of the methods we call internally can't handle query strings properly, so tack it on after processing\n            // the virtual app path and url rewrites\n            if (String.IsNullOrEmpty(query))\n            {\n                return GenerateClientUrlInternal(httpContext, processedPath);\n            }\n            else\n            {\n                return GenerateClientUrlInternal(httpContext, processedPath) + query;\n            }\n        }\n\n        private static string GenerateClientUrlInternal(HttpContextBase httpContext, string contentPath)\n        {\n            if (String.IsNullOrEmpty(contentPath))\n            {\n                return contentPath;\n            }\n\n            // can't call VirtualPathUtility.IsAppRelative since it throws on some inputs\n            bool isAppRelative = contentPath[0] == '~';\n            if (isAppRelative)\n            {\n                string absoluteContentPath = VirtualPathUtility.ToAbsolute(contentPath, httpContext.Request.ApplicationPath);\n                return GenerateClientUrlInternal(httpContext, absoluteContentPath);\n            }\n\n            // we only want to manipulate the path if URL rewriting is active for this request, else we risk breaking the generated URL\n            bool wasRequestRewritten = _urlRewriterHelper.WasRequestRewritten(httpContext);\n            if (!wasRequestRewritten)\n            {\n                return contentPath;\n            }\n\n            // Since the rawUrl represents what the user sees in his browser, it is what we want to use as the base\n            // of our absolute paths. For example, consider mysite.example.com/foo, which is internally\n            // rewritten to content.example.com/mysite/foo. When we want to generate a link to ~/bar, we want to\n            // base it from / instead of /foo, otherwise the user ends up seeing mysite.example.com/foo/bar,\n            // which is incorrect.\n            string relativeUrlToDestination = MakeRelative(httpContext.Request.Path, contentPath);\n            string absoluteUrlToDestination = MakeAbsolute(httpContext.Request.RawUrl, relativeUrlToDestination);\n            return absoluteUrlToDestination;\n        }\n\n        public static string MakeAbsolute(string basePath, string relativePath)\n        {\n            // The Combine() method can't handle query strings on the base path, so we trim it off.\n            string query;\n            basePath = StripQuery(basePath, out query);\n            return VirtualPathUtility.Combine(basePath, relativePath);\n        }\n\n        public static string MakeRelative(string fromPath, string toPath)\n        {\n            string relativeUrl = VirtualPathUtility.MakeRelative(fromPath, toPath);\n            if (String.IsNullOrEmpty(relativeUrl) || relativeUrl[0] == '?')\n            {\n                // Sometimes VirtualPathUtility.MakeRelative() will return an empty string when it meant to return '.',\n                // but links to {empty string} are browser dependent. We replace it with an explicit path to force\n                // consistency across browsers.\n                relativeUrl = \"./\" + relativeUrl;\n            }\n            return relativeUrl;\n        }\n\n        private static string StripQuery(string path, out string query)\n        {\n            int queryIndex = path.IndexOf('?');\n            if (queryIndex >= 0)\n            {\n                query = path.Substring(queryIndex);\n                return path.Substring(0, queryIndex);\n            }\n            else\n            {\n                query = null;\n                return path;\n            }\n        }\n\n        internal static void ResetUrlRewriterHelper()\n        {\n            _urlRewriterHelper = new UrlRewriterHelper();\n        }\n\n        internal static string BuildUrl(string path, out string query, params object[] pathParts)\n        {\n            // Performance senstive \n            // \n            // This code branches on the number of path-parts to either favor string.Concat or StringBuilder \n            // for performance. The most common case (for WebPages) will provide a single int value as a \n            // path-part - string.Concat can be more efficient when we know the number of strings to join.\n            if (pathParts == null || pathParts.Length == 0)\n            {\n                query = String.Empty;\n                return HttpUtility.UrlPathEncode(path);\n            }\n            else if (pathParts.Length == 1)\n            {\n                object pathPart = pathParts[0];\n                if (IsDisplayableType(pathPart.GetType()))\n                {\n                    string displayablePath = Convert.ToString(pathPart, CultureInfo.InvariantCulture);\n                    path = path + \"/\" + displayablePath;\n                    query = String.Empty;\n                    return HttpUtility.UrlPathEncode(path);\n                }\n                else\n                {\n                    StringBuilder queryBuilder = new StringBuilder();\n                    AppendToQueryString(queryBuilder, pathPart);\n\n                    query = queryBuilder.ToString();\n                    return HttpUtility.UrlPathEncode(path);\n                }\n            }\n            else\n            {\n                StringBuilder pathBuilder = new StringBuilder(path);\n                StringBuilder queryBuilder = new StringBuilder();\n\n                for (int i = 0; i < pathParts.Length; i++)\n                {\n                    object pathPart = pathParts[i];\n                    if (IsDisplayableType(pathPart.GetType()))\n                    {\n                        var displayablePath = Convert.ToString(pathPart, CultureInfo.InvariantCulture);\n                        pathBuilder.Append('/');\n                        pathBuilder.Append(displayablePath);\n                    }\n                    else\n                    {\n                        AppendToQueryString(queryBuilder, pathPart);\n                    }\n                }\n\n                query = queryBuilder.ToString();\n                return HttpUtility.UrlPathEncode(pathBuilder.ToString());\n            }\n        }\n\n        private static void AppendToQueryString(StringBuilder queryString, object obj)\n        {\n            // If this method is called, then obj isn't a type that we can put in the path, instead\n            // we want to format it as key-value pairs for the query string. The mostly likely \n            // user scenario for this is an anonymous type.\n            IDictionary<string, object> dictionary = TypeHelper.ObjectToDictionary(obj);\n\n            foreach (var item in dictionary)\n            {\n                if (queryString.Length == 0)\n                {\n                    queryString.Append('?');\n                }\n                else\n                {\n                    queryString.Append('&');\n                }\n\n                string stringValue = Convert.ToString(item.Value, CultureInfo.InvariantCulture);\n\n                queryString.Append(HttpUtility.UrlEncode(item.Key))\n                    .Append('=')\n                    .Append(HttpUtility.UrlEncode(stringValue));\n            }\n        }\n\n        /// <summary>\n        /// Determines if a type is displayable as part of a Url path.\n        /// </summary>\n        /// <remarks>\n        /// If a type is a displayable type, then we format values of that type as part of the Url Path. If not, then\n        /// we attempt to create a RouteValueDictionary, and encode the value as key-value pairs in the query string.\n        /// \n        /// We determine if a type is displayable by whether or not it implements any interfaces. The built-in simple\n        /// types like Int32 implement IFormattable, which will be used to convert it to a string. \n        /// \n        /// Primarily we do this check to allow anonymous types to represent key-value pairs (anonymous types don't \n        /// implement any interfaces). \n        /// </remarks>\n        private static bool IsDisplayableType(Type t)\n        {\n            return t.GetInterfaces().Length > 0;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Validation/CompareValidator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics;\nusing System.Web.Mvc;\n\nnamespace System.Web.WebPages\n{\n    internal class CompareValidator : RequestFieldValidatorBase\n    {\n        private readonly string _otherField;\n        private readonly ModelClientValidationEqualToRule _clientValidationRule;\n\n        public CompareValidator(string otherField, string errorMessage)\n            : base(errorMessage)\n        {\n            Debug.Assert(!String.IsNullOrEmpty(otherField));\n            _otherField = otherField;\n            _clientValidationRule = new ModelClientValidationEqualToRule(errorMessage, otherField);\n        }\n\n        public override ModelClientValidationRule ClientValidationRule\n        {\n            get { return _clientValidationRule; }\n        }\n\n        protected override bool IsValid(HttpContextBase httpContext, string value)\n        {\n            string otherValue = GetRequestValue(httpContext.Request, _otherField);\n            return String.Equals(value, otherValue, StringComparison.CurrentCulture);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Validation/DataTypeValidator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.WebPages\n{\n    internal class DataTypeValidator : RequestFieldValidatorBase\n    {\n        private readonly SupportedValidationDataType _dataType;\n\n        public DataTypeValidator(SupportedValidationDataType type, string errorMessage = null)\n            : base(errorMessage)\n        {\n            _dataType = type;\n        }\n\n        public enum SupportedValidationDataType\n        {\n            DateTime,\n            Decimal,\n            Url,\n            Integer,\n            Float\n        }\n\n        protected override bool IsValid(HttpContextBase httpContext, string value)\n        {\n            if (String.IsNullOrEmpty(value))\n            {\n                return true;\n            }\n\n            switch (_dataType)\n            {\n                case SupportedValidationDataType.DateTime:\n                    return value.IsDateTime();\n                case SupportedValidationDataType.Float:\n                    return value.IsFloat();\n                case SupportedValidationDataType.Decimal:\n                    return value.IsDecimal();\n                case SupportedValidationDataType.Integer:\n                    return value.IsInt();\n                case SupportedValidationDataType.Url:\n                    return Uri.IsWellFormedUriString(value, UriKind.Absolute);\n            }\n            return true;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Validation/IValidator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel.DataAnnotations;\nusing System.Web.Mvc;\n\nnamespace System.Web.WebPages\n{\n    public interface IValidator\n    {\n        ModelClientValidationRule ClientValidationRule { get; }\n        ValidationResult Validate(ValidationContext validationContext);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Validation/RequestFieldValidatorBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel.DataAnnotations;\nusing System.Diagnostics;\nusing System.Web.Helpers;\nusing System.Web.Mvc;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.WebPages\n{\n    public abstract class RequestFieldValidatorBase : IValidator\n    {\n        private readonly string _errorMessage;\n        private readonly bool _useUnvalidatedValues;\n\n        protected RequestFieldValidatorBase(string errorMessage)\n            : this(errorMessage, useUnvalidatedValues: false)\n        {\n        }\n\n        protected RequestFieldValidatorBase(string errorMessage, bool useUnvalidatedValues)\n        {\n            if (String.IsNullOrEmpty(errorMessage))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"errorMessage\");\n            }\n\n            _errorMessage = errorMessage;\n            _useUnvalidatedValues = useUnvalidatedValues;\n        }\n\n        public virtual ModelClientValidationRule ClientValidationRule\n        {\n            get { return null; }\n        }\n\n        /// <summary>\n        /// Meant for unit tests that causes RequestFieldValidatorBase to basically ignore the unvalidated field requirement.\n        /// </summary>\n        internal static bool IgnoreUseUnvalidatedValues { get; set; }\n\n        protected abstract bool IsValid(HttpContextBase httpContext, string value);\n\n        public virtual ValidationResult Validate(ValidationContext validationContext)\n        {\n            var httpContext = GetHttpContext(validationContext);\n            var field = validationContext.MemberName;\n            var fieldValue = GetRequestValue(httpContext.Request, field);\n\n            if (IsValid(httpContext, fieldValue))\n            {\n                return ValidationResult.Success;\n            }\n            return new ValidationResult(_errorMessage, memberNames: new[] { field });\n        }\n\n        protected static HttpContextBase GetHttpContext(ValidationContext validationContext)\n        {\n            Debug.Assert(validationContext.ObjectInstance is HttpContextBase, \"For our validation context, ObjectInstance must be an HttpContextBase instance.\");\n            return (HttpContextBase)validationContext.ObjectInstance;\n        }\n\n        protected string GetRequestValue(HttpRequestBase request, string field)\n        {\n            if (IgnoreUseUnvalidatedValues)\n            {\n                // Make sure we do not set this when we are hosted since this is only meant for unit test scenarios.\n                Debug.Assert(HttpContext.Current == null, \"This flag should not be set when we are hosted.\");\n                return request.Form[field];\n            }\n            return _useUnvalidatedValues ? request.Unvalidated[field] : request.Form[field];\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Validation/ValidationAttributeAdapter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel.DataAnnotations;\nusing System.Web.Mvc;\n\nnamespace System.Web.WebPages\n{\n    internal class ValidationAttributeAdapter : RequestFieldValidatorBase\n    {\n        private readonly ValidationAttribute _attribute;\n        private readonly ModelClientValidationRule _clientValidationRule;\n\n        public ValidationAttributeAdapter(ValidationAttribute attribute, string errorMessage, ModelClientValidationRule clientValidationRule)\n            :\n                this(attribute, errorMessage, clientValidationRule, useUnvalidatedValues: false)\n        {\n        }\n\n        public ValidationAttributeAdapter(ValidationAttribute attribute, string errorMessage, ModelClientValidationRule clientValidationRule, bool useUnvalidatedValues)\n            : base(errorMessage, useUnvalidatedValues)\n        {\n            _attribute = attribute;\n            _clientValidationRule = clientValidationRule;\n        }\n\n        public ValidationAttribute Attribute\n        {\n            get { return _attribute; }\n        }\n\n        public override ModelClientValidationRule ClientValidationRule\n        {\n            get { return _clientValidationRule; }\n        }\n\n        protected override bool IsValid(HttpContextBase httpContext, string value)\n        {\n            return _attribute.IsValid(value);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Validation/ValidationHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq;\nusing System.Text;\nusing System.Web.Mvc;\nusing System.Web.WebPages.Html;\nusing System.Web.WebPages.Scope;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.WebPages\n{\n    public sealed class ValidationHelper\n    {\n        private static readonly object _invalidCssClassKey = new object();\n        private static readonly object _validCssClassKey = new object();\n        private static IDictionary<object, object> _scopeOverride;\n\n        private readonly Dictionary<string, List<IValidator>> _validators = new Dictionary<string, List<IValidator>>(StringComparer.OrdinalIgnoreCase);\n        private readonly HttpContextBase _httpContext;\n        private readonly ModelStateDictionary _modelStateDictionary;\n\n        internal ValidationHelper(HttpContextBase httpContext, ModelStateDictionary modelStateDictionary)\n        {\n            Debug.Assert(httpContext != null);\n            Debug.Assert(modelStateDictionary != null);\n\n            _httpContext = httpContext;\n            _modelStateDictionary = modelStateDictionary;\n        }\n\n        public static string ValidCssClass\n        {\n            get\n            {\n                object value;\n                if (!Scope.TryGetValue(_validCssClassKey, out value))\n                {\n                    return null;\n                }\n                return value as string;\n            }\n            set { Scope[_validCssClassKey] = value; }\n        }\n\n        public static string InvalidCssClass\n        {\n            get\n            {\n                object value;\n                if (!Scope.TryGetValue(_invalidCssClassKey, out value))\n                {\n                    return HtmlHelper.DefaultValidationInputErrorCssClass;\n                }\n                return value as string;\n            }\n            set { Scope[_invalidCssClassKey] = value; }\n        }\n\n        [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"This makes it easier for a user to read this value without knowing of this type.\")]\n        public string FormField\n        {\n            get { return ModelStateDictionary.FormFieldKey; }\n        }\n\n        internal static IDictionary<object, object> Scope\n        {\n            get { return _scopeOverride ?? ScopeStorage.CurrentScope; }\n        }\n\n        public void RequireField(string field)\n        {\n            RequireField(field, errorMessage: null);\n        }\n\n        public void RequireField(string field, string errorMessage)\n        {\n            if (String.IsNullOrEmpty(field))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"field\");\n            }\n            Add(field, Validator.Required(errorMessage: errorMessage));\n        }\n\n        public void RequireFields(params string[] fields)\n        {\n            if (fields == null)\n            {\n                throw new ArgumentNullException(\"fields\");\n            }\n            foreach (var field in fields)\n            {\n                RequireField(field);\n            }\n        }\n\n        public void Add(string field, params IValidator[] validators)\n        {\n            if (String.IsNullOrEmpty(field))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"field\");\n            }\n            if ((validators == null) || validators.Any(v => v == null))\n            {\n                throw new ArgumentNullException(\"validators\");\n            }\n\n            AddFieldValidators(field, validators);\n        }\n\n        public void Add(IEnumerable<string> fields, params IValidator[] validators)\n        {\n            if (fields == null)\n            {\n                throw new ArgumentNullException(\"fields\");\n            }\n            if (validators == null)\n            {\n                throw new ArgumentNullException(\"validators\");\n            }\n            foreach (var field in fields)\n            {\n                Add(field, validators);\n            }\n        }\n\n        public void AddFormError(string errorMessage)\n        {\n            _modelStateDictionary.AddFormError(errorMessage);\n        }\n\n        public bool IsValid(params string[] fields)\n        {\n            // Don't need to validate fields as we treat empty fields as all in Validate.\n            return !Validate(fields).Any();\n        }\n\n        public IEnumerable<ValidationResult> Validate(params string[] fields)\n        {\n            IEnumerable<string> keys = fields;\n            if (fields == null || !fields.Any())\n            {\n                // If no fields are present, validate all of them.\n                keys = _validators.Keys.Concat(new[] { FormField });\n            }\n            return ValidateFieldsAndUpdateModelState(keys);\n        }\n\n        public IEnumerable<string> GetErrors(params string[] fields)\n        {\n            // Don't need to validate fields as we treat empty fields as all in Validate.\n            return Validate(fields).Select(r => r.ErrorMessage);\n        }\n\n        public HtmlString For(string field)\n        {\n            if (String.IsNullOrEmpty(field))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"field\");\n            }\n\n            var clientRules = GetClientValidationRules(field);\n            return GenerateHtmlFromClientValidationRules(clientRules);\n        }\n\n        public HtmlString ClassFor(string field)\n        {\n            if (_httpContext != null && String.Equals(\"POST\", _httpContext.Request.HttpMethod, StringComparison.OrdinalIgnoreCase))\n            {\n                string cssClass = IsValid(field) ? ValidationHelper.ValidCssClass : ValidationHelper.InvalidCssClass;\n                return cssClass == null ? null : new HtmlString(cssClass);\n            }\n            return null;\n        }\n\n        internal static IDisposable OverrideScope()\n        {\n            _scopeOverride = new Dictionary<object, object>();\n            return new DisposableAction(() => _scopeOverride = null);\n        }\n\n        internal IDictionary<string, object> GetUnobtrusiveValidationAttributes(string field)\n        {\n            var clientRules = GetClientValidationRules(field);\n            var attributes = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);\n            UnobtrusiveValidationAttributesGenerator.GetValidationAttributes(clientRules, attributes);\n            return attributes;\n        }\n\n        private IEnumerable<ValidationResult> ValidateFieldsAndUpdateModelState(IEnumerable<string> fields)\n        {\n            var validationContext = new ValidationContext(_httpContext, serviceProvider: null, items: null);\n            var validationResults = new List<ValidationResult>();\n            foreach (var field in fields)\n            {\n                IEnumerable<ValidationResult> fieldResults = ValidateField(field, validationContext);\n                IEnumerable<string> errors = fieldResults.Select(c => c.ErrorMessage);\n                ModelState modelState = _modelStateDictionary[field];\n                if (modelState != null && modelState.Errors.Any())\n                {\n                    errors = errors.Except(modelState.Errors, StringComparer.OrdinalIgnoreCase);\n\n                    // If there were other validation errors that were added via ModelState, add them to the collection.\n                    fieldResults = fieldResults.Concat(modelState.Errors.Select(e => new ValidationResult(e, new[] { field })));\n                }\n\n                foreach (var errorMessage in errors)\n                {\n                    // Only add errors that haven't been encountered before. This is to prevent from the same error message being duplicated \n                    // if a call is made multiple times\n                    _modelStateDictionary.AddError(field, errorMessage);\n                }\n\n                validationResults.AddRange(fieldResults);\n            }\n            return validationResults;\n        }\n\n        private void AddFieldValidators(string field, params IValidator[] validators)\n        {\n            List<IValidator> fieldValidators = null;\n            if (!_validators.TryGetValue(field, out fieldValidators))\n            {\n                fieldValidators = new List<IValidator>();\n                _validators[field] = fieldValidators;\n            }\n            foreach (var validator in validators)\n            {\n                fieldValidators.Add(validator);\n            }\n        }\n\n        private IEnumerable<ValidationResult> ValidateField(string field, ValidationContext context)\n        {\n            List<IValidator> fieldValidators;\n            if (!_validators.TryGetValue(field, out fieldValidators))\n            {\n                return Enumerable.Empty<ValidationResult>();\n            }\n            context.MemberName = field;\n            return fieldValidators.Select(f => f.Validate(context))\n                .Where(result => result != ValidationResult.Success);\n        }\n\n        private IEnumerable<ModelClientValidationRule> GetClientValidationRules(string field)\n        {\n            List<IValidator> fieldValidators = null;\n            if (!_validators.TryGetValue(field, out fieldValidators))\n            {\n                return Enumerable.Empty<ModelClientValidationRule>();\n            }\n\n            return from item in fieldValidators\n                   let clientRule = item.ClientValidationRule\n                   where clientRule != null\n                   select clientRule;\n        }\n\n        internal static HtmlString GenerateHtmlFromClientValidationRules(IEnumerable<ModelClientValidationRule> clientRules)\n        {\n            if (!clientRules.Any())\n            {\n                return null;\n            }\n\n            var attributes = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);\n            UnobtrusiveValidationAttributesGenerator.GetValidationAttributes(clientRules, attributes);\n\n            var stringBuilder = new StringBuilder();\n            foreach (var attribute in attributes)\n            {\n                string key = attribute.Key;\n                string value = HttpUtility.HtmlEncode(Convert.ToString(attribute.Value, CultureInfo.InvariantCulture));\n                stringBuilder.Append(key)\n                    .Append(\"=\\\"\")\n                    .Append(value)\n                    .Append('\"')\n                    .Append(' ');\n            }\n\n            // Trim trailing whitespace\n            if (stringBuilder.Length > 0)\n            {\n                stringBuilder.Length--;\n            }\n\n            return new HtmlString(stringBuilder.ToString());\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/Validation/Validator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel.DataAnnotations;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Web.Mvc;\nusing System.Web.WebPages.Resources;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.WebPages\n{\n    public abstract class Validator\n    {\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"We are ok using default parameters for helpers\")]\n        public static IValidator Required(string errorMessage = null)\n        {\n            errorMessage = DefaultIfEmpty(errorMessage, WebPageResources.ValidationDefault_Required);\n            var clientAttributes = new ModelClientValidationRequiredRule(errorMessage);\n            // We don't care if the value is unsafe when verifying that it is required.\n            return new ValidationAttributeAdapter(new RequiredAttribute(), errorMessage, clientAttributes, useUnvalidatedValues: true);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"We are ok using default parameters for helpers\")]\n        public static IValidator Range(int minValue, int maxValue, string errorMessage = null)\n        {\n            errorMessage = String.Format(CultureInfo.CurrentCulture, DefaultIfEmpty(errorMessage, WebPageResources.ValidationDefault_IntegerRange), minValue, maxValue);\n            var clientAttributes = new ModelClientValidationRangeRule(errorMessage, minValue, maxValue);\n            return new ValidationAttributeAdapter(new RangeAttribute(minValue, maxValue), errorMessage, clientAttributes);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"We are ok using default parameters for helpers\")]\n        public static IValidator Range(double minValue, double maxValue, string errorMessage = null)\n        {\n            errorMessage = String.Format(CultureInfo.CurrentCulture, DefaultIfEmpty(errorMessage, WebPageResources.ValidationDefault_FloatRange), minValue, maxValue);\n            var clientAttributes = new ModelClientValidationRangeRule(errorMessage, minValue, maxValue);\n            return new ValidationAttributeAdapter(new RangeAttribute(minValue, maxValue), errorMessage, clientAttributes);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"We are ok using default parameters for helpers\")]\n        public static IValidator StringLength(int maxLength, int minLength = 0, string errorMessage = null)\n        {\n            if (minLength == 0)\n            {\n                errorMessage = String.Format(CultureInfo.CurrentCulture, DefaultIfEmpty(errorMessage, WebPageResources.ValidationDefault_StringLength), maxLength);\n            }\n            else\n            {\n                errorMessage = DefaultIfEmpty(errorMessage, WebPageResources.ValidationDefault_StringLengthRange);\n                errorMessage = String.Format(CultureInfo.CurrentCulture, errorMessage, minLength, maxLength);\n            }\n            var clientAttributes = new ModelClientValidationStringLengthRule(errorMessage, minLength, maxLength);\n\n            // We don't care if the value is unsafe when checking the length of the request field passed to us.\n            return new ValidationAttributeAdapter(new StringLengthAttribute(maxLength) { MinimumLength = minLength }, errorMessage, clientAttributes,\n                                                  useUnvalidatedValues: true);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"We are ok using default parameters for helpers\")]\n        public static IValidator Regex(string pattern, string errorMessage = null)\n        {\n            if (String.IsNullOrEmpty(pattern))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"pattern\");\n            }\n\n            errorMessage = DefaultIfEmpty(errorMessage, WebPageResources.ValidationDefault_Regex);\n            var clientAttributes = new ModelClientValidationRegexRule(errorMessage, pattern);\n            return new ValidationAttributeAdapter(new RegularExpressionAttribute(pattern), errorMessage, clientAttributes);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"We are ok using default parameters for helpers\")]\n        public static IValidator EqualsTo(string otherFieldName, string errorMessage = null)\n        {\n            if (String.IsNullOrEmpty(otherFieldName))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"otherFieldName\");\n            }\n\n            errorMessage = DefaultIfEmpty(errorMessage, WebPageResources.ValidationDefault_EqualsTo);\n            return new CompareValidator(otherFieldName, errorMessage);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"We are ok using default parameters for helpers\")]\n        public static IValidator DateTime(string errorMessage = null)\n        {\n            errorMessage = DefaultIfEmpty(errorMessage, WebPageResources.ValidationDefault_DataType);\n            return new DataTypeValidator(DataTypeValidator.SupportedValidationDataType.DateTime, errorMessage);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"We are ok using default parameters for helpers\")]\n        public static IValidator Decimal(string errorMessage = null)\n        {\n            errorMessage = DefaultIfEmpty(errorMessage, WebPageResources.ValidationDefault_DataType);\n            return new DataTypeValidator(DataTypeValidator.SupportedValidationDataType.Decimal, errorMessage);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"We are ok using default parameters for helpers\")]\n        public static IValidator Integer(string errorMessage = null)\n        {\n            errorMessage = DefaultIfEmpty(errorMessage, WebPageResources.ValidationDefault_DataType);\n            return new DataTypeValidator(DataTypeValidator.SupportedValidationDataType.Integer, errorMessage);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"We are ok using default parameters for helpers\")]\n        public static IValidator Url(string errorMessage = null)\n        {\n            errorMessage = DefaultIfEmpty(errorMessage, WebPageResources.ValidationDefault_DataType);\n            return new DataTypeValidator(DataTypeValidator.SupportedValidationDataType.Url, errorMessage);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"We are ok using default parameters for helpers\")]\n        public static IValidator Float(string errorMessage = null)\n        {\n            errorMessage = DefaultIfEmpty(errorMessage, WebPageResources.ValidationDefault_DataType);\n            return new DataTypeValidator(DataTypeValidator.SupportedValidationDataType.Float, errorMessage);\n        }\n\n        private static string DefaultIfEmpty(string errorMessage, string defaultErrorMessage)\n        {\n            if (String.IsNullOrEmpty(errorMessage))\n            {\n                return defaultErrorMessage;\n            }\n            return errorMessage;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/VirtualPathFactoryExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.WebPages\n{\n    internal static class VirtualPathFactoryExtensions\n    {\n        public static T CreateInstance<T>(this IVirtualPathFactory factory, string virtualPath) where T : class\n        {\n            var virtualPathFactoryManager = factory as VirtualPathFactoryManager;\n            if (virtualPathFactoryManager != null)\n            {\n                return virtualPathFactoryManager.CreateInstanceOfType<T>(virtualPath);\n            }\n            var buildManagerFactory = factory as BuildManagerWrapper;\n            if (buildManagerFactory != null)\n            {\n                return buildManagerFactory.CreateInstanceOfType<T>(virtualPath);\n            }\n\n            return factory.CreateInstance(virtualPath) as T;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/VirtualPathFactoryManager.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace System.Web.WebPages\n{\n    // This class encapsulates the creation of objects from virtual paths.  The creation is either performed via BuildBanager API's, or\n    // by using explicitly registered factories (which happens through ApplicationPart.Register).\n    public class VirtualPathFactoryManager : IVirtualPathFactory\n    {\n        private static readonly Lazy<VirtualPathFactoryManager> _instance = new Lazy<VirtualPathFactoryManager>(() => new VirtualPathFactoryManager(new BuildManagerWrapper()));\n        private static Func<string, bool> _instancePathExists;\n        private readonly LinkedList<IVirtualPathFactory> _virtualPathFactories = new LinkedList<IVirtualPathFactory>();\n\n        internal VirtualPathFactoryManager(IVirtualPathFactory defaultFactory)\n        {\n            _virtualPathFactories.AddFirst(defaultFactory);\n        }\n\n        // Get the VirtualPathFactoryManager singleton instance\n        internal static VirtualPathFactoryManager Instance\n        {\n            get { return _instance.Value; }\n        }\n\n        internal static Func<string, bool> InstancePathExists\n        {\n            get \n            {\n                if (_instancePathExists == null)\n                {\n                    _instancePathExists = Instance.Exists;\n                }\n                return _instancePathExists;\n            }\n        }\n\n        internal IEnumerable<IVirtualPathFactory> RegisteredFactories\n        {\n            get { return _virtualPathFactories; }\n        }\n\n        public static void RegisterVirtualPathFactory(IVirtualPathFactory virtualPathFactory)\n        {\n            Instance.RegisterVirtualPathFactoryInternal(virtualPathFactory);\n        }\n\n        internal void RegisterVirtualPathFactoryInternal(IVirtualPathFactory virtualPathFactory)\n        {\n            _virtualPathFactories.AddBefore(_virtualPathFactories.Last, virtualPathFactory);\n        }\n\n        public bool Exists(string virtualPath)\n        {\n            // Performance sensitive so avoid Linq and delegates\n            foreach (IVirtualPathFactory factory in _virtualPathFactories)\n            {\n                if (factory.Exists(virtualPath))\n                {\n                    return true;\n                }\n            }\n            return false;\n        }\n\n        public object CreateInstance(string virtualPath)\n        {\n            return CreateInstanceOfType<object>(virtualPath);\n        }\n\n        internal T CreateInstanceOfType<T>(string virtualPath) where T : class\n        {\n            var virtualPathFactory = _virtualPathFactories.FirstOrDefault(f => f.Exists(virtualPath));\n            if (virtualPathFactory != null)\n            {\n                return virtualPathFactory.CreateInstance<T>(virtualPath);\n            }\n            return null;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/VirtualPathUtilityWrapper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web;\n\nnamespace Microsoft.Internal.Web.Utils\n{\n    internal sealed class VirtualPathUtilityWrapper : IVirtualPathUtility\n    {\n        public string Combine(string basePath, string relativePath)\n        {\n            return VirtualPathUtility.Combine(basePath, relativePath);\n        }\n\n        public string ToAbsolute(string virtualPath)\n        {\n            return VirtualPathUtility.ToAbsolute(virtualPath);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/WebPage.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Web.WebPages.Html;\nusing System.Web.WebPages.Scope;\n\nnamespace System.Web.WebPages\n{\n    [SuppressMessage(\"Microsoft.Maintainability\", \"CA1506:AvoidExcessiveClassCoupling\", Justification = \"This is a core class which needs to have references to many other classes\")]\n    public abstract class WebPage : WebPageBase\n    {\n        private static readonly List<IWebPageRequestExecutor> _executors = new List<IWebPageRequestExecutor>();\n\n        private HttpContextBase _context;\n        // Expose the model as dynamic\n        private dynamic _model;\n\n        // True if this is a 'top level' page (URL addressable), vs a 'satellite' page like a user control or master\n        internal bool TopLevelPage { get; set; }\n\n        public override HttpContextBase Context\n        {\n            get\n            {\n                if (_context == null)\n                {\n                    return PageContext.HttpContext;\n                }\n                return _context;\n            }\n            set { _context = value; }\n        }\n\n        public HtmlHelper Html { get; private set; }\n\n        public ValidationHelper Validation\n        {\n            get { return PageContext.Validation; }\n        }\n\n        public dynamic Model\n        {\n            get\n            {\n                if (_model == null)\n                {\n                    // Instead of directly returning the model, we wrap it in our own custom DynamicObject.\n                    // This allows it to perform private reflection, which would normally fail. This is useful\n                    // when dealing with anonymous objects, which are always internal\n                    _model = ReflectionDynamicObject.WrapObjectIfInternal(PageContext.Model);\n                }\n                return _model;\n            }\n        }\n\n        public ModelStateDictionary ModelState\n        {\n            get { return PageContext.ModelState; }\n        }\n\n        public static void RegisterPageExecutor(IWebPageRequestExecutor executor)\n        {\n            _executors.Add(executor);\n        }\n\n        public override void ExecutePageHierarchy()\n        {\n            using (ScopeStorage.CreateTransientScope(new ScopeStorageDictionary(ScopeStorage.CurrentScope, PageData)))\n            {\n                ExecutePageHierarchy(_executors);\n            }\n        }\n\n        internal void ExecutePageHierarchy(IEnumerable<IWebPageRequestExecutor> executors)\n        {\n            // Call all the executors until we find one that wants to handle it. This is used to implement features\n            // such as AJAX Page methods without having to bake them into the framework.\n            // Note that we only do this for 'top level' pages, as these are request-level executors that should not run for each user control/master\n            if (!TopLevelPage || !executors.Any(executor => executor.Execute(this)))\n            {\n                // No executor handled the request, so use normal processing\n                base.ExecutePageHierarchy();\n            }\n        }\n\n        public override HelperResult RenderPage(string path, params object[] data)\n        {\n            return base.RenderPage(path, data);\n        }\n\n        protected override void InitializePage()\n        {\n            base.InitializePage();\n\n            Html = new HtmlHelper(ModelState, Validation);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/WebPageBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.IO;\nusing System.Text;\nusing System.Web.WebPages.Resources;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.WebPages\n{\n    [SuppressMessage(\"Microsoft.Design\", \"CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable\", Justification = \"This is temporary (elipton)\")]\n    public abstract class WebPageBase : WebPageRenderingBase\n    {\n        // Keep track of which sections RenderSection has already been called on\n        private readonly HashSet<string> _renderedSections = new HashSet<string>(StringComparer.OrdinalIgnoreCase);\n        // Keep track of whether RenderBody has been called\n        private bool _renderedBody = false;\n        // Action for rendering the body within a layout page\n        private Action<TextWriter> _body;\n\n        private StringWriter _tempWriter;\n        private TextWriter _currentWriter;\n\n        private DynamicPageDataDictionary<dynamic> _dynamicPageData;\n\n        public override string Layout { get; set; }\n\n        public TextWriter Output\n        {\n            get { return OutputStack.Peek(); }\n        }\n\n        public Stack<TextWriter> OutputStack\n        {\n            get { return PageContext.OutputStack; }\n        }\n\n        public override IDictionary<object, dynamic> PageData\n        {\n            get { return PageContext.PageData; }\n        }\n\n        public override dynamic Page\n        {\n            get\n            {\n                if (_dynamicPageData == null)\n                {\n                    _dynamicPageData = new DynamicPageDataDictionary<dynamic>((PageDataDictionary<dynamic>)PageData);\n                }\n                return _dynamicPageData;\n            }\n        }\n\n        // Retrieves the sections defined in the calling page. If this is null, that means\n        // this page has been requested directly.\n        private Dictionary<string, SectionWriter> PreviousSectionWriters\n        {\n            get\n            {\n                var top = SectionWritersStack.Pop();\n                var previous = SectionWritersStack.Count > 0 ? SectionWritersStack.Peek() : null;\n                SectionWritersStack.Push(top);\n                return previous;\n            }\n        }\n\n        // Retrieves the current Dictionary of sectionWriters on the stack without poping it.\n        // There should be at least one on the stack which is added when the Render(ViewData,TextWriter)\n        // is called.\n        private Dictionary<string, SectionWriter> SectionWriters\n        {\n            get { return SectionWritersStack.Peek(); }\n        }\n\n        private Stack<Dictionary<string, SectionWriter>> SectionWritersStack\n        {\n            get { return PageContext.SectionWritersStack; }\n        }\n\n        protected virtual void ConfigurePage(WebPageBase parentPage)\n        {\n        }\n\n        public static WebPageBase CreateInstanceFromVirtualPath(string virtualPath)\n        {\n            return CreateInstanceFromVirtualPath(virtualPath, VirtualPathFactoryManager.Instance);\n        }\n\n        internal static WebPageBase CreateInstanceFromVirtualPath(string virtualPath, IVirtualPathFactory virtualPathFactory)\n        {\n            // Get the compiled object\n            try\n            {\n                WebPageBase webPage = virtualPathFactory.CreateInstance<WebPageBase>(virtualPath);\n\n                // Give it its virtual path\n                webPage.VirtualPath = virtualPath;\n\n                // Assign it the VirtualPathFactory\n                webPage.VirtualPathFactory = virtualPathFactory;\n\n                return webPage;\n            }\n            catch (HttpException e)\n            {\n                BuildManagerExceptionUtil.ThrowIfUnsupportedExtension(virtualPath, e);\n                throw;\n            }\n        }\n\n        /// <summary>\n        /// Attempts to create a WebPageBase instance from a virtualPath and wraps complex compiler exceptions with simpler messages\n        /// </summary>\n        protected virtual WebPageBase CreatePageFromVirtualPath(string virtualPath, HttpContextBase httpContext, Func<string, bool> virtualPathExists, DisplayModeProvider displayModeProvider, IDisplayMode displayMode)\n        {\n            try\n            {\n                DisplayInfo resolvedDisplayInfo = displayModeProvider.GetDisplayInfoForVirtualPath(virtualPath, httpContext, virtualPathExists, displayMode);\n\n                if (resolvedDisplayInfo != null)\n                {\n                    var webPage = VirtualPathFactory.CreateInstance<WebPageBase>(resolvedDisplayInfo.FilePath);\n\n                    if (webPage != null)\n                    {\n                        // Give it its virtual path\n                        webPage.VirtualPath = virtualPath;\n                        webPage.VirtualPathFactory = VirtualPathFactory;\n                        webPage.DisplayModeProvider = DisplayModeProvider;\n\n                        return webPage;\n                    }\n                }\n            }\n            catch (HttpException e)\n            {\n                // If the path uses an unregistered extension, such as Foo.txt,\n                // then an error regarding build providers will be thrown.\n                // Check if this is the case and throw a simpler error.\n                BuildManagerExceptionUtil.ThrowIfUnsupportedExtension(virtualPath, e);\n\n                // If the path uses an extension registered with codedom, such as Foo.js,\n                // then an unfriendly compilation error might get thrown by the underlying compiler.\n                // Check if this is the case and throw a simpler error.\n                BuildManagerExceptionUtil.ThrowIfCodeDomDefinedExtension(virtualPath, e);\n\n                // Rethrow any errors\n                throw;\n            }\n            // The page is missing, could not be compiled or is of an invalid type.\n            throw new HttpException(String.Format(CultureInfo.CurrentCulture, WebPageResources.WebPage_InvalidPageType, virtualPath));\n        }\n\n        private WebPageContext CreatePageContextFromParameters(bool isLayoutPage, params object[] data)\n        {\n            object first = null;\n            if (data != null && data.Length > 0)\n            {\n                first = data[0];\n            }\n\n            var pageData = PageDataDictionary<dynamic>.CreatePageDataFromParameters(PageData, data);\n\n            return WebPageContext.CreateNestedPageContext(PageContext, pageData, first, isLayoutPage);\n        }\n\n        public void DefineSection(string name, SectionWriter action)\n        {\n            if (SectionWriters.ContainsKey(name))\n            {\n                throw new HttpException(String.Format(CultureInfo.InvariantCulture, WebPageResources.WebPage_SectionAleadyDefined, name));\n            }\n            SectionWriters[name] = action;\n        }\n\n        internal void EnsurePageCanBeRequestedDirectly(string methodName)\n        {\n            if (PreviousSectionWriters == null)\n            {\n                throw new HttpException(String.Format(CultureInfo.CurrentCulture, WebPageResources.WebPage_CannotRequestDirectly, VirtualPath, methodName));\n            }\n        }\n\n        public void ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer)\n        {\n            ExecutePageHierarchy(pageContext, writer, startPage: null);\n        }\n\n        // This method is only used by WebPageBase to allow passing in the view context and writer.\n        public void ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)\n        {\n            PushContext(pageContext, writer);\n\n            if (startPage != null)\n            {\n                if (startPage != this)\n                {\n                    var startPageContext = WebPageContext.CreateNestedPageContext<object>(parentContext: pageContext, pageData: null, model: null, isLayoutPage: false);\n                    startPageContext.Page = startPage;\n                    startPage.PageContext = startPageContext;\n                }\n                startPage.ExecutePageHierarchy();\n            }\n            else\n            {\n                ExecutePageHierarchy();\n            }\n            PopContext();\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We really don't care if SourceHeader fails, and we don't want it to fail any real requests ever\")]\n        public override void ExecutePageHierarchy()\n        {\n            // Unlike InitPages, for a WebPage there is no hierarchy - it is always\n            // the last file to execute in the chain. There can still be layout pages\n            // and partial pages, but they are never part of the hierarchy.\n\n            // (add server header for falcon debugging)\n            // call to MapPath() is expensive. If we are not emiting source files to header, \n            // don't bother to populate the SourceFiles collection. This saves perf significantly.\n            if (WebPageHttpHandler.ShouldGenerateSourceHeader(Context))\n            {\n                try\n                {\n                    string vp = VirtualPath;\n                    if (vp != null)\n                    {\n                        string path = Context.Request.MapPath(vp);\n                        if (!path.IsEmpty())\n                        {\n                            PageContext.SourceFiles.Add(path);\n                        }\n                    }\n                }\n                catch\n                {\n                    // we really don't care if this ever fails, so we swallow all exceptions\n                }\n            }\n\n            TemplateStack.Push(Context, this);\n            try\n            {\n                // Execute the developer-written code of the WebPage\n                Execute();\n            }\n            finally\n            {\n                TemplateStack.Pop(Context);\n            }\n        }\n\n        protected virtual void InitializePage()\n        {\n        }\n\n        public bool IsSectionDefined(string name)\n        {\n            EnsurePageCanBeRequestedDirectly(\"IsSectionDefined\");\n            return PreviousSectionWriters.ContainsKey(name);\n        }\n\n        public void PopContext()\n        {\n            // Using the CopyTo extension method on the _tempWriter instead of .ToString()\n            // to avoid allocating large strings that then end up on the Large object heap.\n            OutputStack.Pop();\n\n            if (!String.IsNullOrEmpty(Layout))\n            {\n                string layoutPagePath = NormalizeLayoutPagePath(Layout);\n\n                // If a layout file was specified, render it passing our page content.\n                OutputStack.Push(_currentWriter);\n                RenderSurrounding(\n                    layoutPagePath,\n                    _tempWriter.CopyTo);\n                OutputStack.Pop();\n            }\n            else\n            {\n                // Otherwise, just render the page.\n                _tempWriter.CopyTo(_currentWriter);\n            }\n\n            VerifyRenderedBodyOrSections();\n            SectionWritersStack.Pop();\n        }\n\n        public void PushContext(WebPageContext pageContext, TextWriter writer)\n        {\n            _currentWriter = writer;\n            PageContext = pageContext;\n            pageContext.Page = this;\n\n            InitializePage();\n\n            // Create a temporary writer\n            _tempWriter = new StringWriter(CultureInfo.InvariantCulture);\n\n            // Render the page into it\n            OutputStack.Push(_tempWriter);\n            SectionWritersStack.Push(new Dictionary<string, SectionWriter>(StringComparer.OrdinalIgnoreCase));\n\n            // If the body is defined in the ViewData, remove it and store it on the instance\n            // so that it won't affect rendering of partial pages when they call VerifyRenderedBodyOrSections\n            if (PageContext.BodyAction != null)\n            {\n                _body = PageContext.BodyAction;\n                PageContext.BodyAction = null;\n            }\n        }\n\n        public HelperResult RenderBody()\n        {\n            EnsurePageCanBeRequestedDirectly(\"RenderBody\");\n\n            if (_renderedBody)\n            {\n                throw new HttpException(WebPageResources.WebPage_RenderBodyAlreadyCalled);\n            }\n            _renderedBody = true;\n\n            // _body should have previously been set in Render(ViewContext,TextWriter) if it\n            // was available in the ViewData.\n            if (_body != null)\n            {\n                return new HelperResult(tw => _body(tw));\n            }\n            else\n            {\n                throw new HttpException(String.Format(CultureInfo.CurrentCulture, WebPageResources.WebPage_CannotRequestDirectly, VirtualPath, \"RenderBody\"));\n            }\n        }\n\n        public override HelperResult RenderPage(string path, params object[] data)\n        {\n            return RenderPageCore(path, isLayoutPage: false, data: data);\n        }\n\n        private HelperResult RenderPageCore(string path, bool isLayoutPage, object[] data)\n        {\n            if (String.IsNullOrEmpty(path))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"path\");\n            }\n\n            return new HelperResult(writer =>\n            {\n                path = NormalizePath(path);\n                WebPageBase subPage = CreatePageFromVirtualPath(path, Context, VirtualPathFactory.Exists, DisplayModeProvider, DisplayMode);\n                var pageContext = CreatePageContextFromParameters(isLayoutPage, data);\n\n                subPage.ConfigurePage(this);\n                subPage.ExecutePageHierarchy(pageContext, writer);\n            });\n        }\n\n        public HelperResult RenderSection(string name)\n        {\n            return RenderSection(name, required: true);\n        }\n\n        public HelperResult RenderSection(string name, bool required)\n        {\n            EnsurePageCanBeRequestedDirectly(\"RenderSection\");\n\n            if (PreviousSectionWriters.ContainsKey(name))\n            {\n                var result = new HelperResult(tw =>\n                {\n                    if (_renderedSections.Contains(name))\n                    {\n                        throw new HttpException(String.Format(CultureInfo.InvariantCulture, WebPageResources.WebPage_SectionAleadyRendered, name));\n                    }\n                    var body = PreviousSectionWriters[name];\n                    // Since the body can also call RenderSection, we need to temporarily remove\n                    // the current sections from the stack.\n                    var top = SectionWritersStack.Pop();\n\n                    bool pushed = false;\n                    try\n                    {\n                        if (Output != tw)\n                        {\n                            OutputStack.Push(tw);\n                            pushed = true;\n                        }\n\n                        body();\n                    }\n                    finally\n                    {\n                        if (pushed)\n                        {\n                            OutputStack.Pop();\n                        }\n                    }\n                    SectionWritersStack.Push(top);\n                    _renderedSections.Add(name);\n                });\n                return result;\n            }\n            else if (required)\n            {\n                // If the section is not found, and it is not optional, throw an error.\n                throw new HttpException(String.Format(CultureInfo.InvariantCulture, WebPageResources.WebPage_SectionNotDefined, name));\n            }\n            else\n            {\n                // If the section is optional and not found, then don't do anything.\n                return null;\n            }\n        }\n\n        private void RenderSurrounding(string partialViewName, Action<TextWriter> body)\n        {\n            // Save the previous body action and set ours instead.\n            // This value will be retrieved by the sub-page being rendered when it runs\n            // Render(ViewData, TextWriter).\n            var priorValue = PageContext.BodyAction;\n            PageContext.BodyAction = body;\n\n            // Render the layout file\n            Write(RenderPageCore(partialViewName, isLayoutPage: true, data: new object[0]));\n\n            // Restore the state\n            PageContext.BodyAction = priorValue;\n        }\n\n        // Verifies that RenderBody is called, or that RenderSection is called for all sections\n        private void VerifyRenderedBodyOrSections()\n        {\n            // The _body will be set within a layout page because PageContext.BodyAction was set by RenderSurrounding, \n            // which is only called in the case of rendering layout pages.\n            // Using RenderPage will not result in a _body being set in a partial page, thus the following checks for\n            // sections should not apply when RenderPage is called.\n            // Dev10 bug 928341 \n            if (_body != null)\n            {\n                if (SectionWritersStack.Count > 1 && PreviousSectionWriters != null && PreviousSectionWriters.Count > 0)\n                {\n                    // There are sections defined. Check that all sections have been rendered.\n                    StringBuilder sectionsNotRendered = new StringBuilder();\n                    foreach (var name in PreviousSectionWriters.Keys)\n                    {\n                        if (!_renderedSections.Contains(name))\n                        {\n                            if (sectionsNotRendered.Length > 0)\n                            {\n                                sectionsNotRendered.Append(\"; \");\n                            }\n                            sectionsNotRendered.Append(name);\n                        }\n                    }\n                    if (sectionsNotRendered.Length > 0)\n                    {\n                        throw new HttpException(String.Format(CultureInfo.CurrentCulture, WebPageResources.WebPage_SectionsNotRendered, VirtualPath, sectionsNotRendered.ToString()));\n                    }\n                }\n                else if (!_renderedBody)\n                {\n                    // There are no sections defined, but RenderBody was NOT called.\n                    // If a body was defined, then RenderBody should have been called.\n                    throw new HttpException(String.Format(CultureInfo.CurrentCulture, WebPageResources.WebPage_RenderBodyNotCalled, VirtualPath));\n                }\n            }\n        }\n\n        public override void Write(HelperResult result)\n        {\n            WriteTo(Output, result);\n        }\n\n        public override void Write(object value)\n        {\n            WriteTo(Output, value);\n        }\n\n        public override void WriteLiteral(object value)\n        {\n            Output.Write(value);\n        }\n\n        protected internal override TextWriter GetOutputWriter()\n        {\n            return Output;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/WebPageContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Web.WebPages.Html;\n\nnamespace System.Web.WebPages\n{\n    // Class for containing various pieces of data required by a WebPage\n    public class WebPageContext\n    {\n        private static readonly object _sourceFileKey = new object();\n        private Stack<TextWriter> _outputStack;\n        private Stack<Dictionary<string, SectionWriter>> _sectionWritersStack;\n        private IDictionary<object, dynamic> _pageData;\n        private ValidationHelper _validation;\n        private ModelStateDictionary _modelStateDictionary;\n\n        public WebPageContext()\n            : this(context: null, page: null, model: null)\n        {\n        }\n\n        public WebPageContext(HttpContextBase context, WebPageRenderingBase page, object model)\n        {\n            HttpContext = context;\n            Page = page;\n            Model = model;\n        }\n\n        public static WebPageContext Current\n        {\n            get\n            {\n                // The TemplateStack stores instances of WebPageRenderingBase. \n                // Retrieve the top-most item from the stack and cast it to WebPageBase. \n                var httpContext = Web.HttpContext.Current;\n                if (httpContext != null)\n                {\n                    var contextWrapper = new HttpContextWrapper(httpContext);\n                    var currentTemplate = TemplateStack.GetCurrentTemplate(contextWrapper);\n                    var currentPage = (currentTemplate as WebPageRenderingBase);\n\n                    return (currentPage == null) ? null : currentPage.PageContext;\n                }\n                return null;\n            }\n        }\n\n        internal HttpContextBase HttpContext { get; set; }\n\n        public object Model { get; internal set; }\n\n        internal ModelStateDictionary ModelState\n        {\n            get\n            {\n                if (_modelStateDictionary == null)\n                {\n                    _modelStateDictionary = new ModelStateDictionary();\n                }\n                return _modelStateDictionary;\n            }\n            private set { _modelStateDictionary = value; }\n        }\n\n        internal ValidationHelper Validation\n        {\n            get\n            {\n                if (_validation == null)\n                {\n                    Debug.Assert(HttpContext != null, \"HttpContext must be initalized for Validation to work.\");\n                    _validation = new ValidationHelper(HttpContext, ModelState);\n                }\n                return _validation;\n            }\n            private set { _validation = value; }\n        }\n\n        internal Action<TextWriter> BodyAction { get; set; }\n\n        internal Stack<TextWriter> OutputStack\n        {\n            get\n            {\n                if (_outputStack == null)\n                {\n                    _outputStack = new Stack<TextWriter>();\n                }\n                return _outputStack;\n            }\n            set { _outputStack = value; }\n        }\n\n        public WebPageRenderingBase Page { get; internal set; }\n\n        public IDictionary<object, dynamic> PageData\n        {\n            get\n            {\n                if (_pageData == null)\n                {\n                    _pageData = new PageDataDictionary<dynamic>();\n                }\n                return _pageData;\n            }\n            internal set { _pageData = value; }\n        }\n\n        internal Stack<Dictionary<string, SectionWriter>> SectionWritersStack\n        {\n            get\n            {\n                if (_sectionWritersStack == null)\n                {\n                    _sectionWritersStack = new Stack<Dictionary<string, SectionWriter>>();\n                }\n                return _sectionWritersStack;\n            }\n            set { _sectionWritersStack = value; }\n        }\n\n        // NOTE: We use a hashset because order doesn't matter and we want to eliminate duplicates\n        internal HashSet<string> SourceFiles\n        {\n            get\n            {\n                HashSet<string> sourceFiles = HttpContext.Items[_sourceFileKey] as HashSet<string>;\n                if (sourceFiles == null)\n                {\n                    sourceFiles = new HashSet<string>();\n                    HttpContext.Items[_sourceFileKey] = sourceFiles;\n                }\n                return sourceFiles;\n            }\n        }\n\n        internal static WebPageContext CreateNestedPageContext<TModel>(WebPageContext parentContext, IDictionary<object, dynamic> pageData, TModel model, bool isLayoutPage)\n        {\n            var nestedContext = new WebPageContext\n            {\n                HttpContext = parentContext.HttpContext,\n                OutputStack = parentContext.OutputStack,\n                Validation = parentContext.Validation,\n                PageData = pageData,\n                Model = model,\n                ModelState = parentContext.ModelState,\n            };\n\n            if (isLayoutPage)\n            {\n                nestedContext.BodyAction = parentContext.BodyAction;\n                nestedContext.SectionWritersStack = parentContext.SectionWritersStack;\n            }\n            return nestedContext;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/WebPageExecutingBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.IO;\nusing System.Web.WebPages.Instrumentation;\nusing System.Web.WebPages.Resources;\n\n/*\nWebPage class hierarchy\n\nWebPageExecutingBase                        The base class for all Plan9 files (_pagestart, _appstart, and regular pages)\n    ApplicationStartPage                    Used for _appstart.cshtml\n    WebPageRenderingBase\n        StartPage                           Used for _pagestart.cshtml\n        WebPageBase\n            WebPage                         Plan9Pages\n            ViewWebPage?                    MVC Views\nHelperPage                                  Base class for Web Pages in App_Code.\n*/\n\nnamespace System.Web.WebPages\n{\n    // The base class for all CSHTML files (_pagestart, _appstart, and regular pages)\n    public abstract class WebPageExecutingBase\n    {\n        private IVirtualPathFactory _virtualPathFactory;\n        private DynamicHttpApplicationState _dynamicAppState;\n        private InstrumentationService _instrumentationService = null;\n\n        internal InstrumentationService InstrumentationService\n        {\n            get\n            {\n                if (_instrumentationService == null)\n                {\n                    _instrumentationService = new InstrumentationService();\n                }\n                return _instrumentationService;\n            }\n            set { _instrumentationService = value; }\n        }\n\n        public virtual HttpApplicationStateBase AppState\n        {\n            get\n            {\n                if (Context != null)\n                {\n                    return Context.Application;\n                }\n                return null;\n            }\n        }\n\n        public virtual dynamic App\n        {\n            get\n            {\n                if (_dynamicAppState == null && AppState != null)\n                {\n                    _dynamicAppState = new DynamicHttpApplicationState(AppState);\n                }\n                return _dynamicAppState;\n            }\n        }\n\n        public virtual HttpContextBase Context { get; set; }\n\n        public virtual string VirtualPath { get; set; }\n\n        [EditorBrowsable(EditorBrowsableState.Never)]\n        public virtual IVirtualPathFactory VirtualPathFactory\n        {\n            get { return _virtualPathFactory ?? VirtualPathFactoryManager.Instance; }\n            set { _virtualPathFactory = value; }\n        }\n\n        [EditorBrowsable(EditorBrowsableState.Never)]\n        public abstract void Execute();\n\n        public virtual string Href(string path, params object[] pathParts)\n        {\n            return UrlUtil.GenerateClientUrl(Context, VirtualPath, path, pathParts);\n        }\n\n        protected internal void BeginContext(int startPosition, int length, bool isLiteral)\n        {\n            BeginContext(GetOutputWriter(), VirtualPath, startPosition, length, isLiteral);\n        }\n\n        protected internal void BeginContext(string virtualPath, int startPosition, int length, bool isLiteral)\n        {\n            BeginContext(GetOutputWriter(), virtualPath, startPosition, length, isLiteral);\n        }\n\n        protected internal void BeginContext(TextWriter writer, int startPosition, int length, bool isLiteral)\n        {\n            BeginContext(writer, VirtualPath, startPosition, length, isLiteral);\n        }\n\n        protected internal void BeginContext(TextWriter writer, string virtualPath, int startPosition, int length, bool isLiteral)\n        {\n            // Double check that the instrumentation service is active because WriteAttribute always calls this\n            if (InstrumentationService.IsAvailable)\n            {\n                InstrumentationService.BeginContext(Context,\n                                                    virtualPath,\n                                                    writer,\n                                                    startPosition,\n                                                    length,\n                                                    isLiteral);\n            }\n        }\n\n        protected internal void EndContext(int startPosition, int length, bool isLiteral)\n        {\n            EndContext(GetOutputWriter(), VirtualPath, startPosition, length, isLiteral);\n        }\n\n        protected internal void EndContext(string virtualPath, int startPosition, int length, bool isLiteral)\n        {\n            EndContext(GetOutputWriter(), virtualPath, startPosition, length, isLiteral);\n        }\n\n        protected internal void EndContext(TextWriter writer, int startPosition, int length, bool isLiteral)\n        {\n            EndContext(writer, VirtualPath, startPosition, length, isLiteral);\n        }\n\n        protected internal void EndContext(TextWriter writer, string virtualPath, int startPosition, int length, bool isLiteral)\n        {\n            // Double check that the instrumentation service is active because WriteAttribute always calls this\n            if (InstrumentationService.IsAvailable)\n            {\n                InstrumentationService.EndContext(Context,\n                                                  virtualPath,\n                                                  writer,\n                                                  startPosition,\n                                                  length,\n                                                  isLiteral);\n            }\n        }\n\n        internal virtual string GetDirectory(string virtualPath)\n        {\n            return VirtualPathUtility.GetDirectory(virtualPath);\n        }\n\n        /// <summary>\n        /// Normalizes path relative to the current virtual path and throws if a file does not exist at the location.\n        /// </summary>\n        protected internal virtual string NormalizeLayoutPagePath(string layoutPagePath)\n        {\n            var virtualPath = NormalizePath(layoutPagePath);\n            // Look for it as specified, either absolute, relative or same folder\n            if (VirtualPathFactory.Exists(virtualPath))\n            {\n                return virtualPath;\n            }\n            throw new HttpException(String.Format(CultureInfo.CurrentCulture, WebPageResources.WebPage_LayoutPageNotFound, layoutPagePath, virtualPath));\n        }\n\n        public virtual string NormalizePath(string path)\n        {\n            // If it's relative, resolve it\n            return VirtualPathUtility.Combine(VirtualPath, path);\n        }\n\n        public abstract void Write(HelperResult result);\n\n        public abstract void Write(object value);\n\n        public abstract void WriteLiteral(object value);\n\n        public virtual void WriteAttribute(string name, PositionTagged<string> prefix, PositionTagged<string> suffix, params AttributeValue[] values)\n        {\n            WriteAttributeTo(GetOutputWriter(), name, prefix, suffix, values);\n        }\n\n        public virtual void WriteAttributeTo(TextWriter writer, string name, PositionTagged<string> prefix, PositionTagged<string> suffix, params AttributeValue[] values)\n        {\n            WriteAttributeTo(VirtualPath, writer, name, prefix, suffix, values);\n        }\n\n        protected internal virtual void WriteAttributeTo(string pageVirtualPath, TextWriter writer, string name, PositionTagged<string> prefix, PositionTagged<string> suffix, params AttributeValue[] values)\n        {\n            bool first = true;\n            bool wroteSomething = false;\n            if (values.Length == 0)\n            {\n                // Explicitly empty attribute, so write the prefix and suffix\n                WritePositionTaggedLiteral(writer, pageVirtualPath, prefix);\n                WritePositionTaggedLiteral(writer, pageVirtualPath, suffix);\n            }\n            else\n            {\n                for (int i = 0; i < values.Length; i++)\n                {\n                    AttributeValue attrVal = values[i];\n                    PositionTagged<object> val = attrVal.Value;\n                    PositionTagged<string> next = i == values.Length - 1 ?\n                        suffix : // End of the list, grab the suffix\n                        values[i + 1].Prefix; // Still in the list, grab the next prefix\n\n                    if (val.Value == null)\n                    {\n                        // Nothing to write\n                        continue;\n                    }\n\n                    // The special cases here are that the value we're writing might already be a string, or that the \n                    // value might be a bool. If the value is the bool 'true' we want to write the attribute name instead\n                    // of the string 'true'. If the value is the bool 'false' we don't want to write anything.\n                    //\n                    // Otherwise the value is another object (perhaps an IHtmlString), and we'll ask it to format itself.\n                    string stringValue;\n\n                    // Intentionally using is+cast here for performance reasons. This is more performant than as+bool? \n                    // because of boxing.\n                    if (val.Value is bool)\n                    {\n                        if ((bool)val.Value)\n                        {\n                            stringValue = name;\n                        }\n                        else\n                        {\n                            continue;\n                        }\n                    }\n                    else\n                    {\n                        stringValue = val.Value as string;\n                    }\n\n                    if (first)\n                    {\n                        WritePositionTaggedLiteral(writer, pageVirtualPath, prefix);\n                        first = false;\n                    }\n                    else\n                    {\n                        WritePositionTaggedLiteral(writer, pageVirtualPath, attrVal.Prefix);\n                    }\n\n                    // Calculate length of the source span by the position of the next value (or suffix)\n                    int sourceLength = next.Position - attrVal.Value.Position;\n\n                    BeginContext(writer, pageVirtualPath, attrVal.Value.Position, sourceLength, isLiteral: attrVal.Literal);\n\n                    // The extra branching here is to ensure that we call the Write*To(string) overload when\n                    // possible.\n                    if (attrVal.Literal && stringValue != null)\n                    {\n                        WriteLiteralTo(writer, stringValue);\n                    }\n                    else if (attrVal.Literal)\n                    {\n                        WriteLiteralTo(writer, val.Value);\n                    }\n                    else if (stringValue != null)\n                    {\n                        WriteTo(writer, stringValue);\n                    }\n                    else\n                    {\n                        WriteTo(writer, val.Value);\n                    }\n\n                    EndContext(writer, pageVirtualPath, attrVal.Value.Position, sourceLength, isLiteral: attrVal.Literal);\n                    wroteSomething = true;\n                }\n                if (wroteSomething)\n                {\n                    WritePositionTaggedLiteral(writer, pageVirtualPath, suffix);\n                }\n            }\n        }\n\n        private void WritePositionTaggedLiteral(TextWriter writer, string pageVirtualPath, string value, int position)\n        {\n            BeginContext(writer, pageVirtualPath, position, value.Length, isLiteral: true);\n            WriteLiteralTo(writer, value);\n            EndContext(writer, pageVirtualPath, position, value.Length, isLiteral: true);\n        }\n\n        private void WritePositionTaggedLiteral(TextWriter writer, string pageVirtualPath, PositionTagged<string> value)\n        {\n            WritePositionTaggedLiteral(writer, pageVirtualPath, value.Value, value.Position);\n        }\n\n        // This method is called by generated code and needs to stay in sync with the parser\n        public static void WriteTo(TextWriter writer, HelperResult content)\n        {\n            if (content != null)\n            {\n                content.WriteTo(writer);\n            }\n        }\n\n        // This method is called by generated code and needs to stay in sync with the parser\n        public static void WriteTo(TextWriter writer, object content)\n        {\n            writer.Write(HttpUtility.HtmlEncode(content));\n        }\n\n        // Perf optimization to avoid calling string.ToString when we already know the type is a string.\n        private static void WriteTo(TextWriter writer, string content)\n        {\n            writer.Write(HttpUtility.HtmlEncode(content));\n        }\n\n        // This method is called by generated code and needs to stay in sync with the parser\n        public static void WriteLiteralTo(TextWriter writer, object content)\n        {\n            writer.Write(content);\n        }\n\n        // Perf optimization to avoid calling string.ToString when we already know the type is a string.\n        private static void WriteLiteralTo(TextWriter writer, string content)\n        {\n            writer.Write(content);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Justification = \"A method is more appropriate in this case since a property likely already exists to hold this value\")]\n        protected internal virtual TextWriter GetOutputWriter()\n        {\n            return TextWriter.Null;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/WebPageHttpHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Reflection;\nusing System.Security;\nusing System.Text;\nusing System.Web.SessionState;\nusing Microsoft.Web.Infrastructure.DynamicValidationHelper;\n\nnamespace System.Web.WebPages\n{\n    public class WebPageHttpHandler : IHttpHandler, IRequiresSessionState\n    {\n        internal const string StartPageFileName = \"_PageStart\";\n        public static readonly string WebPagesVersionHeaderName = \"X-AspNetWebPages-Version\";\n        private static string[] _supportedExtensions = Empty<string>.Array;\n        internal static readonly string WebPagesVersion = GetVersionString();\n        private readonly WebPage _webPage;\n        private readonly Lazy<WebPageRenderingBase> _startPage;\n\n        public WebPageHttpHandler(WebPage webPage)\n            : this(webPage, new Lazy<WebPageRenderingBase>(() => System.Web.WebPages.StartPage.GetStartPage(webPage, StartPageFileName, GetRegisteredExtensions())))\n        {\n        }\n\n        internal WebPageHttpHandler(WebPage webPage, Lazy<WebPageRenderingBase> startPage)\n        {\n            if (webPage == null)\n            {\n                throw new ArgumentNullException(\"webPage\");\n            }\n            _webPage = webPage;\n            _startPage = startPage;\n        }\n\n        public static bool DisableWebPagesResponseHeader { get; set; }\n\n        public virtual bool IsReusable\n        {\n            get { return false; }\n        }\n\n        internal WebPage RequestedPage\n        {\n            get { return _webPage; }\n        }\n\n        internal WebPageRenderingBase StartPage\n        {\n            get { return _startPage.Value; }\n        }\n\n        internal static string[] SupportedExtensions\n        {\n            get { return _supportedExtensions; }\n        }\n\n        internal static void AddVersionHeader(HttpContextBase httpContext)\n        {\n            if (!DisableWebPagesResponseHeader)\n            {\n                httpContext.Response.AppendHeader(WebPagesVersionHeaderName, WebPagesVersion);\n            }\n        }\n\n        public static IHttpHandler CreateFromVirtualPath(string virtualPath)\n        {\n            return CreateFromVirtualPath(virtualPath, VirtualPathFactoryManager.Instance);\n        }\n\n        internal static IHttpHandler CreateFromVirtualPath(string virtualPath, IVirtualPathFactory virtualPathFactory)\n        {\n            // We will try to create a WebPage from our factory. If this fails, we assume that the virtual path maps to an IHttpHandler.\n            // Instantiate the page from the virtual path\n            WebPage page = virtualPathFactory.CreateInstance<WebPage>(virtualPath);\n\n            // If it's not a page, assume it's a regular handler\n            if (page == null)\n            {\n                return virtualPathFactory.CreateInstance<IHttpHandler>(virtualPath);\n            }\n\n            // Mark it as a 'top level' page (as opposed to a user control or master)\n            page.TopLevelPage = true;\n\n            // Give it its virtual path\n            page.VirtualPath = virtualPath;\n\n            // Assign it the object factory\n            page.VirtualPathFactory = virtualPathFactory;\n\n            // Return a handler over it\n            return new WebPageHttpHandler(page);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Justification = \"We don't want a property\")]\n        public static ReadOnlyCollection<string> GetRegisteredExtensions()\n        {\n            return new ReadOnlyCollection<string>(_supportedExtensions);\n        }\n\n        private static string GetVersionString()\n        {\n            // DevDiv 216459:\n            // This code originally used Assembly.GetName(), but that requires FileIOPermission, which isn't granted in\n            // medium trust. However, Assembly.FullName *is* accessible in medium trust.\n            return new AssemblyName(typeof(WebPageHttpHandler).Assembly.FullName).Version.ToString(2);\n        }\n\n        private static bool HandleError(Exception e)\n        {\n            // This method is similar to System.Web.UI.Page.HandleError\n\n            // Don't touch security exception\n            if (e is SecurityException)\n            {\n                return false;\n            }\n\n            throw new HttpUnhandledException(null, e);\n        }\n\n        internal static void GenerateSourceFilesHeader(WebPageContext context)\n        {\n            if (context.SourceFiles.Any())\n            {\n                var files = String.Join(\"|\", context.SourceFiles);\n                // Since the characters in the value are files that may include characters outside of the ASCII set, header encoding as specified in RFC2047. \n                // =?<charset>?<encoding>?...?= \n                // In the following case, UTF8 is used with base64 encoding \n                var encodedText = \"=?UTF-8?B?\" + Convert.ToBase64String(Encoding.UTF8.GetBytes(files)) + \"?=\";\n                context.HttpContext.Response.AddHeader(\"X-SourceFiles\", encodedText);\n            }\n        }\n\n        public virtual void ProcessRequest(HttpContext context)\n        {\n            ProcessRequestInternal(context);\n        }\n\n        internal void ProcessRequestInternal(HttpContext context)\n        {\n            // enable dynamic validation for this request\n            ValidationUtility.EnableDynamicValidation(context);\n            context.Request.ValidateInput();\n\n            HttpContextBase contextBase = new HttpContextWrapper(context);\n            ProcessRequestInternal(contextBase);\n        }\n\n        internal void ProcessRequestInternal(HttpContextBase httpContext)\n        {\n            try\n            {\n                //WebSecurity.Context = contextBase;\n                AddVersionHeader(httpContext);\n\n                // This is also the point where a Plan9 request truly begins execution\n\n                // We call ExecutePageHierarchy on the requested page, passing in the possible initPage, so that\n                // the requested page can take care of the necessary push/pop context and trigger the call to\n                // the initPage.\n                _webPage.ExecutePageHierarchy(new WebPageContext { HttpContext = httpContext }, httpContext.Response.Output, StartPage);\n\n                if (ShouldGenerateSourceHeader(httpContext))\n                {\n                    GenerateSourceFilesHeader(_webPage.PageContext);\n                }\n            }\n            catch (Exception e)\n            {\n                if (!HandleError(e))\n                {\n                    throw;\n                }\n            }\n        }\n\n        public static void RegisterExtension(string extension)\n        {\n            // Note: we don't lock or check for duplicates because we only expect this method to be called during PreAppStart\n            // Long lived data with few writes and many reads, so reallocate the array each time.\n            _supportedExtensions = _supportedExtensions.AppendAndReallocate(extension);\n        }\n\n        internal static bool ShouldGenerateSourceHeader(HttpContextBase context)\n        {\n            return context.Request.IsLocal;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/WebPageHttpModule.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.WebPages\n{\n    internal class WebPageHttpModule : IHttpModule\n    {\n        internal static EventHandler Initialize;\n        internal static EventHandler ApplicationStart;\n        internal static EventHandler BeginRequest;\n        internal static EventHandler EndRequest;\n        private static bool _appStartExecuted = false;\n        private static readonly object _appStartExecutedLock = new object();\n        private static readonly object _hasBeenRegisteredKey = new object();\n\n        internal static bool AppStartExecuteCompleted { get; set; }\n\n        public void Dispose()\n        {\n        }\n\n        public void Init(HttpApplication application)\n        {\n            if (application.Context.Items[_hasBeenRegisteredKey] != null)\n            {\n                // registration for this module has already run for this HttpApplication instance\n                return;\n            }\n\n            application.Context.Items[_hasBeenRegisteredKey] = true;\n\n            InitApplication(application);\n        }\n\n        internal static void InitApplication(HttpApplication application)\n        {\n            // We need to run StartApplication first, so that any exception thrown during execution of the StartPage gets\n            // recorded on StartPage.Exception\n            StartApplication(application);\n            InitializeApplication(application);\n        }\n\n        internal static void InitializeApplication(HttpApplication application)\n        {\n            InitializeApplication(application, OnApplicationPostResolveRequestCache, Initialize);\n        }\n\n        internal static void InitializeApplication(HttpApplication application, EventHandler onApplicationPostResolveRequestCache, EventHandler initialize)\n        {\n            if (initialize != null)\n            {\n                initialize(application, EventArgs.Empty);\n            }\n            application.PostResolveRequestCache += onApplicationPostResolveRequestCache;\n            if (ApplicationStartPage.Exception != null || BeginRequest != null)\n            {\n                application.BeginRequest += OnBeginRequest;\n            }\n\n            application.EndRequest += OnEndRequest;\n        }\n\n        internal static void StartApplication(HttpApplication application)\n        {\n            StartApplication(application, ApplicationStartPage.ExecuteStartPage, ApplicationStart);\n        }\n\n        internal static void StartApplication(HttpApplication application, Action<HttpApplication> executeStartPage, EventHandler applicationStart)\n        {\n            // Application start events should happen only once per application life time.\n            lock (_appStartExecutedLock)\n            {\n                if (!_appStartExecuted)\n                {\n                    _appStartExecuted = true;\n\n                    executeStartPage(application);\n                    AppStartExecuteCompleted = true;\n                    if (applicationStart != null)\n                    {\n                        applicationStart(application, EventArgs.Empty);\n                    }\n                }\n            }\n        }\n\n        internal static void OnApplicationPostResolveRequestCache(object sender, EventArgs e)\n        {\n            HttpContextBase context = new HttpContextWrapper(((HttpApplication)sender).Context);\n            new WebPageRoute().DoPostResolveRequestCache(context);\n        }\n\n        internal static void OnBeginRequest(object sender, EventArgs e)\n        {\n            if (ApplicationStartPage.Exception != null)\n            {\n                // Throw it as a HttpException so as to\n                // display the original stack trace information.\n                throw new HttpException(null, ApplicationStartPage.Exception);\n            }\n            if (BeginRequest != null)\n            {\n                BeginRequest(sender, e);\n            }\n        }\n\n        internal static void OnEndRequest(object sender, EventArgs e)\n        {\n            if (EndRequest != null)\n            {\n                EndRequest(sender, e);\n            }\n\n            var app = (HttpApplication)sender;\n            RequestResourceTracker.DisposeResources(new HttpContextWrapper(app.Context));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/WebPageMatch.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.WebPages\n{\n    internal sealed class WebPageMatch\n    {\n        public WebPageMatch(string matchedPath, string pathInfo)\n        {\n            MatchedPath = matchedPath;\n            PathInfo = pathInfo;\n        }\n\n        public string MatchedPath { get; private set; }\n\n        public string PathInfo { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/WebPageRenderingBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Web.Caching;\nusing System.Web.Profile;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.WebPages\n{\n    public abstract class WebPageRenderingBase : WebPageExecutingBase, ITemplateFile\n    {\n        private IPrincipal _user;\n        private UrlDataList _urlData;\n        private TemplateFileInfo _templateFileInfo;\n        private DisplayModeProvider _displayModeProvider;\n\n        public virtual Cache Cache\n        {\n            get\n            {\n                if (Context != null)\n                {\n                    return Context.Cache;\n                }\n                return null;\n            }\n        }\n\n        internal DisplayModeProvider DisplayModeProvider\n        {\n            get { return _displayModeProvider ?? DisplayModeProvider.Instance; }\n\n            set { _displayModeProvider = value; }\n        }\n\n        protected internal IDisplayMode DisplayMode\n        {\n            get { return DisplayModeProvider.GetDisplayMode(Context); }\n        }\n\n        public abstract string Layout { get; set; }\n\n        public abstract IDictionary<object, dynamic> PageData { get; }\n\n        public abstract dynamic Page { get; }\n\n        public WebPageContext PageContext { get; internal set; }\n\n        public ProfileBase Profile\n        {\n            get\n            {\n                if (Context != null)\n                {\n                    return Context.Profile;\n                }\n                return null;\n            }\n        }\n\n        public virtual HttpRequestBase Request\n        {\n            get\n            {\n                if (Context != null)\n                {\n                    return Context.Request;\n                }\n                return null;\n            }\n        }\n\n        public virtual HttpResponseBase Response\n        {\n            get\n            {\n                if (Context != null)\n                {\n                    return Context.Response;\n                }\n                return null;\n            }\n        }\n\n        public virtual HttpServerUtilityBase Server\n        {\n            get\n            {\n                if (Context != null)\n                {\n                    return Context.Server;\n                }\n                return null;\n            }\n        }\n\n        public virtual HttpSessionStateBase Session\n        {\n            get\n            {\n                if (Context != null)\n                {\n                    return Context.Session;\n                }\n                return null;\n            }\n        }\n\n        public virtual IList<string> UrlData\n        {\n            get\n            {\n                if (_urlData == null)\n                {\n                    WebPageMatch match = WebPageRoute.GetWebPageMatch(Context);\n                    if (match != null)\n                    {\n                        _urlData = new UrlDataList(match.PathInfo);\n                    }\n                    else\n                    {\n                        // REVIEW: Can there ever be no route match?\n                        _urlData = new UrlDataList(null);\n                    }\n                }\n                return _urlData;\n            }\n        }\n\n        public virtual IPrincipal User\n        {\n            get\n            {\n                if (_user == null)\n                {\n                    return Context.User;\n                }\n                return _user;\n            }\n            internal set { _user = value; }\n        }\n\n        public virtual TemplateFileInfo TemplateInfo\n        {\n            get\n            {\n                if (_templateFileInfo == null)\n                {\n                    _templateFileInfo = new TemplateFileInfo(VirtualPath);\n                }\n                return _templateFileInfo;\n            }\n        }\n\n        public virtual bool IsPost\n        {\n            get { return Request.HttpMethod == \"POST\"; }\n        }\n\n        public virtual bool IsAjax\n        {\n            get\n            {\n                var request = Request;\n                if (request == null)\n                {\n                    return false;\n                }\n                return (request[\"X-Requested-With\"] == \"XMLHttpRequest\") || ((request.Headers != null) && (request.Headers[\"X-Requested-With\"] == \"XMLHttpRequest\"));\n            }\n        }\n\n        public string Culture\n        {\n            get { return Thread.CurrentThread.CurrentCulture.Name; }\n            set\n            {\n                if (String.IsNullOrEmpty(value))\n                {\n                    // GetCultureInfo accepts empty strings but throws for null strings. To maintain consistency in our string handling behavior, throw\n                    throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"value\");\n                }\n                CultureUtil.SetCulture(Thread.CurrentThread, Context, value);\n            }\n        }\n\n        public string UICulture\n        {\n            get { return Thread.CurrentThread.CurrentUICulture.Name; }\n            set\n            {\n                if (String.IsNullOrEmpty(value))\n                {\n                    // GetCultureInfo accepts empty strings but throws for null strings. To maintain consistency in our string handling behavior, throw\n                    throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"value\");\n                }\n                CultureUtil.SetUICulture(Thread.CurrentThread, Context, value);\n            }\n        }\n\n        // Calls the Execute() method, and calls RunPage() if the page is an InitPage but\n        // did not call RunPage().\n        public abstract void ExecutePageHierarchy();\n\n        public abstract HelperResult RenderPage(string path, params object[] data);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/WebPageRoute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Web.WebPages.Deployment;\nusing System.Web.WebPages.Resources;\n\nnamespace System.Web.WebPages\n{\n    internal sealed class WebPageRoute\n    {\n        private static readonly Lazy<bool> _isRootExplicitlyDisabled = new Lazy<bool>(() => WebPagesDeployment.IsExplicitlyDisabled(\"~/\"));\n        private bool? _isExplicitlyDisabled;\n\n        internal bool IsExplicitlyDisabled\n        {\n            get { return _isExplicitlyDisabled ?? _isRootExplicitlyDisabled.Value; }\n            set { _isExplicitlyDisabled = value; }\n        }\n\n        internal void DoPostResolveRequestCache(HttpContextBase context)\n        {\n            if (IsExplicitlyDisabled)\n            {\n                // If the root config is explicitly disabled, do not process the request.\n                return;\n            }\n\n            // Parse incoming URL (we trim off the first two chars since they're always \"~/\")\n            string requestPath = context.Request.AppRelativeCurrentExecutionFilePath.Substring(2) + context.Request.PathInfo;\n            string[] registeredExtensions = WebPageHttpHandler.SupportedExtensions;\n\n            // Check if this request matches a file in the app\n            WebPageMatch webpageRouteMatch = MatchRequest(requestPath, registeredExtensions, VirtualPathFactoryManager.InstancePathExists, context, DisplayModeProvider.Instance);\n            if (webpageRouteMatch != null)\n            {\n                // If it matches then save some data for the WebPage's UrlData\n                context.Items[typeof(WebPageMatch)] = webpageRouteMatch;\n\n                string virtualPath = \"~/\" + webpageRouteMatch.MatchedPath;\n\n                // Verify that this path is enabled before remapping\n                if (!WebPagesDeployment.IsExplicitlyDisabled(virtualPath))\n                {\n                    IHttpHandler handler = WebPageHttpHandler.CreateFromVirtualPath(virtualPath);\n                    if (handler != null)\n                    {\n                        SessionStateUtil.SetUpSessionState(context, handler);\n                        // Remap to our handler\n                        context.RemapHandler(handler);\n                    }\n                }\n            }\n            else\n            {\n                // Bug:904704 If its not a match, but to a supported extension, we want to return a 404 instead of a 403\n                string extension = PathUtil.GetExtension(requestPath);\n                foreach (string supportedExt in registeredExtensions)\n                {\n                    if (String.Equals(\".\" + supportedExt, extension, StringComparison.OrdinalIgnoreCase))\n                    {\n                        throw new HttpException(404, null);\n                    }\n                }\n            }\n        }\n\n        private static bool FileExists(string virtualPath, Func<string, bool> virtualPathExists)\n        {\n            var path = \"~/\" + virtualPath;\n            return virtualPathExists(path);\n        }\n\n        internal static WebPageMatch GetWebPageMatch(HttpContextBase context)\n        {\n            WebPageMatch webPageMatch = (WebPageMatch)context.Items[typeof(WebPageMatch)];\n            return webPageMatch;\n        }\n\n        private static string GetRouteLevelMatch(string pathValue, string[] supportedExtensions, Func<string, bool> virtualPathExists, HttpContextBase context, DisplayModeProvider displayModeProvider)\n        {\n            for (int i = 0; i < supportedExtensions.Length; i++)\n            {\n                string supportedExtension = supportedExtensions[i];\n\n                // For performance, avoid multiple calls to String.Concat\n                string virtualPath;\n                // Only add the extension if it's not already there\n                if (!PathHelpers.EndsWithExtension(pathValue, supportedExtension))\n                {\n                    virtualPath = \"~/\" + pathValue + \".\" + supportedExtension;\n                }\n                else\n                {\n                    virtualPath = \"~/\" + pathValue;\n                }\n                DisplayInfo virtualPathDisplayInfo = displayModeProvider.GetDisplayInfoForVirtualPath(virtualPath, context, virtualPathExists, currentDisplayMode: null);\n\n                if (virtualPathDisplayInfo != null)\n                {\n                    // If there's an exact match on disk, return it unless it starts with an underscore\n                    if (Path.GetFileName(virtualPathDisplayInfo.FilePath).StartsWith(\"_\", StringComparison.OrdinalIgnoreCase))\n                    {\n                        throw new HttpException(404, WebPageResources.WebPageRoute_UnderscoreBlocked);\n                    }\n\n                    string resolvedVirtualPath = virtualPathDisplayInfo.FilePath;\n\n                    // Matches are not expected to be virtual paths so remove the ~/ from the match\n                    if (resolvedVirtualPath.StartsWith(\"~/\", StringComparison.OrdinalIgnoreCase))\n                    {\n                        resolvedVirtualPath = resolvedVirtualPath.Remove(0, 2);\n                    }\n\n                    DisplayModeProvider.SetDisplayMode(context, virtualPathDisplayInfo.DisplayMode);\n\n                    return resolvedVirtualPath;\n                }\n            }\n\n            return null;\n        }\n\n        internal static WebPageMatch MatchRequest(string pathValue, string[] supportedExtensions, Func<string, bool> virtualPathExists, HttpContextBase context, DisplayModeProvider displayModes)\n        {\n            string currentLevel = String.Empty;\n            string currentPathInfo = pathValue;\n\n            // We can skip the file exists check and normal lookup for empty paths, but we still need to look for default pages\n            if (!String.IsNullOrEmpty(pathValue))\n            {\n                // If the file exists and its not a supported extension, let the request go through\n                if (FileExists(pathValue, virtualPathExists))\n                {\n                    // TODO: Look into switching to RawURL to eliminate the need for this issue\n                    bool foundSupportedExtension = false;\n                    for (int i = 0; i < supportedExtensions.Length; i++)\n                    {\n                        string supportedExtension = supportedExtensions[i];\n                        if (PathHelpers.EndsWithExtension(pathValue, supportedExtension))\n                        {\n                            foundSupportedExtension = true;\n                            break;\n                        }\n                    }\n\n                    if (!foundSupportedExtension)\n                    {\n                        return null;\n                    }\n                }\n\n                // For each trimmed part of the path try to add a known extension and\n                // check if it matches a file in the application.\n                currentLevel = pathValue;\n                currentPathInfo = String.Empty;\n                while (true)\n                {\n                    // Does the current route level patch any supported extension?\n                    string routeLevelMatch = GetRouteLevelMatch(currentLevel, supportedExtensions, virtualPathExists, context, displayModes);\n                    if (routeLevelMatch != null)\n                    {\n                        return new WebPageMatch(routeLevelMatch, currentPathInfo);\n                    }\n\n                    // Try to remove the last path segment (e.g. go from /foo/bar to /foo)\n                    int indexOfLastSlash = currentLevel.LastIndexOf('/');\n                    if (indexOfLastSlash == -1)\n                    {\n                        // If there are no more slashes, we're done\n                        break;\n                    }\n                    else\n                    {\n                        // Chop off the last path segment to get to the next one\n                        currentLevel = currentLevel.Substring(0, indexOfLastSlash);\n\n                        // And save the path info in case there is a match\n                        currentPathInfo = pathValue.Substring(indexOfLastSlash + 1);\n                    }\n                }\n            }\n\n            return MatchDefaultFiles(pathValue, supportedExtensions, virtualPathExists, context, displayModes, currentLevel);\n        }\n\n        private static WebPageMatch MatchDefaultFiles(string pathValue, string[] supportedExtensions, Func<string, bool> virtualPathExists, HttpContextBase context, DisplayModeProvider displayModes, string currentLevel)\n        {\n            // If we haven't found anything yet, now try looking for default.* or index.* at the current url\n            currentLevel = pathValue;\n            string currentLevelDefault;\n            string currentLevelIndex;\n            if (String.IsNullOrEmpty(currentLevel))\n            {\n                currentLevelDefault = \"default\";\n                currentLevelIndex = \"index\";\n            }\n            else\n            {\n                if (currentLevel[currentLevel.Length - 1] != '/')\n                {\n                    currentLevel += \"/\";\n                }\n                currentLevelDefault = currentLevel + \"default\";\n                currentLevelIndex = currentLevel + \"index\";\n            }\n\n            // Does the current route level match any supported extension?\n            string defaultMatch = GetRouteLevelMatch(currentLevelDefault, supportedExtensions, virtualPathExists, context, displayModes);\n            if (defaultMatch != null)\n            {\n                return new WebPageMatch(defaultMatch, String.Empty);\n            }\n\n            string indexMatch = GetRouteLevelMatch(currentLevelIndex, supportedExtensions, virtualPathExists, context, displayModes);\n            if (indexMatch != null)\n            {\n                return new WebPageMatch(indexMatch, String.Empty);\n            }\n\n            return null;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Microsoft.Web.Infrastructure\" version=\"1.0.0.0\" targetFramework=\"net45\" />\n</packages>"
  },
  {
    "path": "src/System.Web.WebPages.Administration/Default.cshtml",
    "content": "﻿@* Generator: WebPage *@\n\n@using System.Web.WebPages.Administration.PackageManager;\n@{    \n    Page.Title = AdminResources.Modules;\n    var adminModules = from p in SiteAdmin.Modules\n                       where !p.StartPageVirtualPath.Equals(SiteAdmin.AdminVirtualPath, StringComparison.OrdinalIgnoreCase)\n                       orderby p.DisplayName\n                       select p;\n}\n\n@if (!adminModules.Any() && !PackageManagerModule.Available) {\n    <h3>@AdminResources.NoAdminModulesInstalled</h3>\n}\nelse if (PackageManagerModule.Available && !adminModules.Any()) {\n    // If no other module is available, take the user directly to the package manager\n    Response.Redirect(Href(\"packages\"));\n    return;\n}\nelse {\n    <ul class=\"modules\">\n    @if (PackageManagerModule.Available) {\n        <li>    \n            <a href=\"@Href(\"packages\")\" title=\"@PackageManagerModule.ModuleName\"><strong>@PackageManagerModule.ModuleName</strong></a>\n            <div class=\"description\">@PackageManagerModule.ModuleDescription</div>\n        </li>\n    }\n    @if (adminModules.Any()) {\n        foreach (var module in adminModules) {\n            <li>\n                <a href=\"@Href(module.StartPageVirtualPath)\"><strong>@module.DisplayName</strong></a>\n                <div class=\"description\">\n                    @module.Description\n                </div>\n            </li>\n        }\n    }\n    </ul>\n}"
  },
  {
    "path": "src/System.Web.WebPages.Administration/EnableInstructions.cshtml",
    "content": "﻿@* Generator: WebPage *@\n\n@using System.Globalization;\n\n@{\n    Page.Title = AdminResources.SecurityTitle;\n\n    if(AdminSecurity.HasAdminPassword()) {\n        SiteAdmin.RedirectToHome(Response);\n        return;\n    }\n\n    string url = SiteAdmin.GetRedirectUrl(SiteAdmin.AdminVirtualPath);\n}   \n\n@Html.Raw(AdminResources.EnableInstructions)\n<br />\n<p>\n    @Html.Raw(String.Format(CultureInfo.CurrentCulture, AdminResources.ContinueAfterEnableText, Html.Encode(Href(url))))\n</p>\n\n"
  },
  {
    "path": "src/System.Web.WebPages.Administration/Framework/AdminSecurity.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.IO;\nusing System.Web.Helpers;\nusing System.Web.Hosting;\nusing System.Web.Security;\n\nnamespace System.Web.WebPages.Administration\n{\n    internal static class AdminSecurity\n    {\n        private const string AuthCookieName = \".ASPXADMINAUTH\";\n        private const string AdminUserNameToken = \"ADMIN\";\n\n        // Bug941370: Renamed the file to .config to prevent IIS6 from serving this files.\n        internal static readonly string AdminPasswordFile = VirtualPathUtility.Combine(SiteAdmin.AdminSettingsFolder, \"Password.config\");\n        internal static readonly string TemporaryPasswordFile = VirtualPathUtility.Combine(SiteAdmin.AdminSettingsFolder, \"_Password.config\");\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We catch all exceptions to prevent any decryption failure results from being exposed.\")]\n        internal static bool IsAuthenticated(HttpRequestBase request)\n        {\n            HttpCookie authCookie = request.Cookies[AuthCookieName];\n\n            // Not authenticated if there is no cookie\n            if (authCookie == null)\n            {\n                return false;\n            }\n\n            try\n            {\n                return IsValidAuthCookie(authCookie);\n            }\n            catch\n            {\n                // If decryption fails, it may be a bad cookie\n                return false;\n            }\n        }\n\n        private static bool IsValidAuthCookie(HttpCookie authCookie)\n        {\n            // Decrypt the cookie and check the expired flag\n            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);\n\n            // Ensure that the ticket hasn't expired and that the custom UserData string is our AdminUserNameToken\n            return !ticket.Expired && ticket.UserData != null && ticket.UserData.Equals(AdminUserNameToken);\n        }\n\n        internal static void SetAuthCookie(HttpResponseBase response)\n        {\n            // Get an auth admin cookie\n            HttpCookie cookie = GetAuthCookie();\n\n            // Set the name to our auth cookie name\n            cookie.Name = AuthCookieName;\n\n            // Add it to the response\n            response.Cookies.Add(cookie);\n        }\n\n        internal static HttpCookie GetAuthCookie()\n        {\n            // Create a new forms auth ticket for the admin section\n            // Add the admin user name as user data so that we distinguish between a regular\n            // ticket issued by ASP.NET's auth system versus our own            \n            var ticket = new FormsAuthenticationTicket(2,\n                                                       AdminUserNameToken,\n                                                       DateTime.Now,\n                                                       DateTime.Now.Add(FormsAuthentication.Timeout),\n                                                       false,\n                                                       AdminUserNameToken,\n                                                       FormsAuthentication.FormsCookiePath);\n\n            // Encrypt the ticket and create the cookie\n            string encryptedValue = FormsAuthentication.Encrypt(ticket);\n            var cookie = new HttpCookie(AuthCookieName, encryptedValue);\n            cookie.HttpOnly = true;\n            cookie.Path = ticket.CookiePath;\n\n            return cookie;\n        }\n\n        internal static void DeleteAuthCookie(HttpResponseBase response)\n        {\n            // Expire the cookie\n            var cookie = new HttpCookie(AuthCookieName);\n            cookie.Expires = DateTime.Now.AddDays(-1);\n            response.Cookies.Add(cookie);\n        }\n\n        internal static bool HasAdminPassword()\n        {\n            return HasAdminPassword(HostingEnvironment.VirtualPathProvider);\n        }\n\n        internal static bool HasAdminPassword(VirtualPathProvider vpp)\n        {\n            // REVIEW: Do we need to check for content as well?\n            return vpp.FileExists(AdminPasswordFile);\n        }\n\n        internal static bool HasTemporaryPassword()\n        {\n            return HasTemporaryPassword(HostingEnvironment.VirtualPathProvider);\n        }\n\n        internal static bool HasTemporaryPassword(VirtualPathProvider vpp)\n        {\n            // REVIEW: Do we need to check for content as well?\n            return vpp.FileExists(TemporaryPasswordFile);\n        }\n\n        internal static bool SaveTemporaryPassword(string password)\n        {\n            // When saving the admin password we store it in a dummy file so that we don't enable to the admin UI by default\n            return SaveTemporaryPassword(password, GetTemporaryPasswordFileStream);\n        }\n\n        private static Stream GetTemporaryPasswordFileStream()\n        {\n            // Get the password directory and file name\n            string passwordFilePath = HostingEnvironment.MapPath(TemporaryPasswordFile);\n            string passwordFileDir = Path.GetDirectoryName(passwordFilePath);\n\n            // Ensure password directory exists\n            Directory.CreateDirectory(passwordFileDir);\n\n            // Return the stream\n            return File.OpenWrite(passwordFilePath);\n        }\n\n        internal static bool SaveTemporaryPassword(string password, Func<Stream> getPasswordFileStream)\n        {\n            Stream stream = null;\n            try\n            {\n                // Get the password file stream\n                stream = getPasswordFileStream();\n            }\n            catch (UnauthorizedAccessException)\n            {\n                // The user doesn't have write access to App_Data or the site root\n                return false;\n            }\n\n            using (var writer = new StreamWriter(stream))\n            {\n                // Write the salty password\n                writer.WriteLine(Crypto.HashPassword(password));\n            }\n\n            return true;\n        }\n\n        internal static bool CheckPassword(string password)\n        {\n            return CheckPassword(password, () =>\n            {\n                VirtualFile passwordFile = HostingEnvironment.VirtualPathProvider.GetFile(AdminPasswordFile);\n                Debug.Assert(passwordFile != null, \"password file should not be null\");\n                return passwordFile.Open();\n            });\n        }\n\n        internal static bool CheckPassword(string password, Func<Stream> getPasswordFileStream)\n        {\n            string saltyPassword = null;\n\n            Stream stream = getPasswordFileStream();\n            using (StreamReader reader = new StreamReader(stream))\n            {\n                // Read the salted password\n                saltyPassword = reader.ReadLine();\n            }\n\n            return Crypto.VerifyHashedPassword(saltyPassword, password);\n        }\n\n        /// <summary>\n        /// Ensure that the current request is authorized. \n        /// If the request is authenticated, then we skip all other checks.\n        /// </summary>\n        internal static void Authorize(StartPage page)\n        {\n            Authorize(page, HostingEnvironment.VirtualPathProvider, VirtualPathUtility.ToAppRelative);\n        }\n\n        internal static void Authorize(StartPage page, VirtualPathProvider vpp, Func<string, string> makeAppRelative)\n        {\n            if (!IsAuthenticated(page.Request))\n            {\n                if (HasAdminPassword(vpp))\n                {\n                    // If there is a password file (Password.config) then we redirect to the login page\n                    RedirectSafe(page, SiteAdmin.LoginVirtualPath, makeAppRelative);\n                }\n                else if (HasTemporaryPassword(vpp))\n                {\n                    // Dev 10 941521: Admin: Pass through returnurl into page that tells the user to rename _password.config\n                    // If there is a disabled password file (_Password.config) then we redirect to the instructions page\n                    RedirectSafe(page, SiteAdmin.EnableInstructionsVirtualPath, makeAppRelative);\n                }\n                else\n                {\n                    // The user hasn't done anything so redirect to the register page.\n                    RedirectSafe(page, SiteAdmin.RegisterVirtualPath, makeAppRelative);\n                }\n            }\n        }\n\n        /// <summary>\n        /// Doesn't do a redirect if the requesting page is itself the same as the virtual path.\n        /// We need to do this since it is called from the _pagestart.cshtml which always runs.\n        /// </summary>\n        private static void RedirectSafe(StartPage page, string virtualPath, Func<string, string> makeAppRelative)\n        {\n            // Make sure we get the virtual path\n            virtualPath = SiteAdmin.GetVirtualPath(virtualPath);\n\n            if (!IsRequestingPage(page, virtualPath))\n            {\n                // Append the redirect url querystring\n                virtualPath = SiteAdmin.GetRedirectUrl(page.Request, virtualPath, makeAppRelative);\n\n                page.Context.Response.Redirect(virtualPath);\n            }\n        }\n\n        /// <summary>\n        /// Determines if the specified virtualPath is being requested. We do this by walking the page hierarchy\n        /// and comparing the virtualPath with the child page's VirtualPath property (which in the case of ApplicationParts are compiled into the assembly\n        /// using the PageVirtualPath attribute).\n        /// </summary>\n        internal static bool IsRequestingPage(this StartPage page, string virtualPath)\n        {\n            WebPageRenderingBase webPage = GetRootPage(page);\n\n            return webPage.VirtualPath.Equals(virtualPath, StringComparison.OrdinalIgnoreCase);\n        }\n\n        /// <summary>\n        /// Walks the page hierarcy to find the requested page.\n        /// </summary>\n        private static WebPageRenderingBase GetRootPage(StartPage page)\n        {\n            WebPageRenderingBase currentPage = null;\n            while (page != null)\n            {\n                currentPage = page.ChildPage;\n                page = currentPage as StartPage;\n            }\n\n            Debug.Assert(currentPage != null, \"Should never be null\");\n            return currentPage;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages.Administration/Framework/PreApplicationStartCode.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\n\nnamespace System.Web.WebPages.Administration\n{\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class PreApplicationStartCode\n    {\n        // NOTE: Do not add public fields, methods, or other members to this class.\n        // This class does not show up in Intellisense so members on it will not be\n        // discoverable by users. Place new members on more appropriate classes that\n        // relate to the public API (for example, a LoginUrl property should go on a\n        // membership-related class).\n\n        private static bool _startWasCalled;\n\n        public static void Start()\n        {\n            // Even though ASP.NET will only call each PreAppStart once, we sometimes internally call one PreAppStart from \n            // another PreAppStart to ensure that things get initialized in the right order. ASP.NET does not guarantee the \n            // order so we have to guard against multiple calls.\n            // All Start calls are made on same thread, so no lock needed here.\n            if (_startWasCalled)\n            {\n                return;\n            }\n            _startWasCalled = true;\n\n            // Register the admin module\n            SiteAdmin.RegisterAdminModule();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages.Administration/Framework/SiteAdmin.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Configuration;\nusing System.Diagnostics;\nusing System.Globalization;\n\nnamespace System.Web.WebPages.Administration\n{\n    public class SiteAdmin\n    {\n        internal const string DefaultAdminVirtualPath = \"~/_Admin/\";\n        internal const string AdminSettingsFolder = \"~/App_Data/Admin/\";\n\n        // Configuration settings\n        private const string AdminVirtualPathAppSettingsKey = \"asp:AdminFolderVirtualPath\";\n        private const string AdminEnabledAppSettingsKey = \"asp:AdminManagerEnabled\";\n\n        private const string ReturnUrlQueryString = \"ReturnUrl\";\n\n        // Virtual paths excluded from security. These urls are the same as the ones in the PageVirtulPath attribute.\n        internal const string LoginVirtualPath = \"~/Login.cshtml\";\n        internal const string LogoutVirtualPath = \"~/Logout.cshtml\";\n        internal const string RegisterVirtualPath = \"~/Register.cshtml\";\n        internal const string EnableInstructionsVirtualPath = \"~/EnableInstructions.cshtml\";\n\n        private static ConcurrentDictionary<string, SiteAdmin> _adminModules = new ConcurrentDictionary<string, SiteAdmin>();\n\n        // These only needs to be computed once per app domain\n        private static readonly Lazy<bool?> _adminEnabled = new Lazy<bool?>(GetAdminEnabledSetting);\n        private static readonly Lazy<string> _adminVirtualPath = new Lazy<string>(GetDefaultVirtualPath);\n\n        private SiteAdmin(string startPageVirtualPath, string displayName, string description)\n        {\n            Debug.Assert(startPageVirtualPath != null, \"startPageVirtualPath can't be null\");\n            Debug.Assert(displayName != null, \"displayName can't be null\");\n\n            StartPageVirtualPath = startPageVirtualPath;\n            DisplayName = displayName;\n            Description = description;\n        }\n\n        public static string AdminVirtualPath\n        {\n            get { return _adminVirtualPath.Value; }\n        }\n\n        public string StartPageVirtualPath { get; private set; }\n\n        public string DisplayName { get; private set; }\n\n        public string Description { get; private set; }\n\n        internal static bool Available\n        {\n            get\n            {\n                HttpContext context = HttpContext.Current;\n                if (context != null && context.Request.IsLocal)\n                {\n                    // Check the configuration setting if there is any\n                    if (_adminEnabled.Value != null)\n                    {\n                        return _adminEnabled.Value.Value;\n                    }\n\n                    // There was no setting so localhost is enough to verify availability\n                    return true;\n                }\n                // If we're not on localhost then nothing is available\n                return false;\n            }\n        }\n\n        public static IEnumerable<SiteAdmin> Modules\n        {\n            get { return _adminModules.Values; }\n        }\n\n        internal static void RegisterAdminModule()\n        {\n            // Add a admin module as an application module (precompiled)\n            ApplicationPart.Register(new ApplicationPart(typeof(SiteAdmin).Assembly, AdminVirtualPath));\n        }\n\n        private static bool? GetAdminEnabledSetting()\n        {\n            bool enabled;\n            if (Boolean.TryParse(ConfigurationManager.AppSettings[AdminEnabledAppSettingsKey], out enabled))\n            {\n                return enabled;\n            }\n\n            return null;\n        }\n\n        public static string GetVirtualPath(string virtualPath)\n        {\n            if (virtualPath == null)\n            {\n                throw new ArgumentNullException(\"virtualPath\");\n            }\n\n            // Don't add the virtual path more than once\n            if (virtualPath.StartsWith(AdminVirtualPath, StringComparison.OrdinalIgnoreCase))\n            {\n                return virtualPath;\n            }\n\n            if (virtualPath.StartsWith(\"~/\", StringComparison.OrdinalIgnoreCase))\n            {\n                virtualPath = virtualPath.Substring(2);\n            }\n\n            if (virtualPath.StartsWith(\"/\", StringComparison.OrdinalIgnoreCase))\n            {\n                virtualPath = virtualPath.Substring(1);\n            }\n            return VirtualPathUtility.Combine(AdminVirtualPath, virtualPath);\n        }\n\n        public static void Register(string startPageVirtualPath, string displayName, string description)\n        {\n            if (startPageVirtualPath == null)\n            {\n                throw new ArgumentNullException(\"startPageVirtualPath\");\n            }\n\n            if (displayName == null)\n            {\n                throw new ArgumentNullException(\"displayName\");\n            }\n\n            // Get the virtual path relative to the admin virtual path\n            string virtualPath = GetVirtualPath(startPageVirtualPath);\n\n            // Register that under the admin root\n            Register(new SiteAdmin(virtualPath, displayName, description));\n        }\n\n        private static string GetDefaultVirtualPath()\n        {\n            string virtualPath = ConfigurationManager.AppSettings[AdminVirtualPathAppSettingsKey];\n            if (String.IsNullOrEmpty(virtualPath))\n            {\n                virtualPath = DefaultAdminVirtualPath;\n            }\n\n            if (!virtualPath.EndsWith(\"/\", StringComparison.OrdinalIgnoreCase))\n            {\n                virtualPath += \"/\";\n            }\n            return virtualPath;\n        }\n\n        internal static void RedirectToLogin(HttpResponseBase response)\n        {\n            response.Redirect(GetVirtualPath(LoginVirtualPath));\n        }\n\n        internal static void RedirectToRegister(HttpResponseBase response)\n        {\n            response.Redirect(GetVirtualPath(RegisterVirtualPath));\n        }\n\n        internal static void RedirectToHome(HttpResponseBase response)\n        {\n            response.Redirect(AdminVirtualPath);\n        }\n\n        internal static void Register(SiteAdmin module)\n        {\n            if (_adminModules.ContainsKey(module.StartPageVirtualPath))\n            {\n                throw new InvalidOperationException(\n                    String.Format(CultureInfo.CurrentCulture,\n                                  AdminResources.ModuleAlreadyRegistered, module.StartPageVirtualPath));\n            }\n\n            // Add to the list of registered modules\n            _adminModules.TryAdd(module.StartPageVirtualPath, module);\n        }\n\n        internal static string GetReturnUrl(HttpRequestBase request)\n        {\n            // REVIEW: FormsAuthentication.GetReturlUrl also checks the form for the return url\n            // do we need that?\n            string returnUrl = request.QueryString[ReturnUrlQueryString];\n\n            // If the return url query string doesn't exist or is empty\n            // return the admin root virtual path\n            if (String.IsNullOrEmpty(returnUrl))\n            {\n                return null;\n            }\n\n            // REVIEW: FormsAuthentication.GetReturnUrl checks if the url is dangerous\n            // i.e it uses an internal helper in System.Web CrossSiteScriptingValidation.IsDangerousUrl.\n            // Should we copy that behavior?\n\n            if (!VirtualPathUtility.IsAppRelative(returnUrl))\n            {\n                // We only put app relative return urls in the query string (i.e starts with ~/)\n                throw new InvalidOperationException(AdminResources.InvalidReturnUrl);\n            }\n\n            return returnUrl;\n        }\n\n        internal static string GetRedirectUrl(string redirectUrl)\n        {\n            var request = new HttpRequestWrapper(HttpContext.Current.Request);\n            return GetRedirectUrl(request, redirectUrl, VirtualPathUtility.ToAppRelative);\n        }\n\n        internal static string GetRedirectUrl(HttpRequestBase request, string redirectUrl, Func<string, string> makeAppRelative)\n        {\n            // If there's already a return url then use it, otherwise the app relative url of the \n            // current request to redirect to after signing in\n            string returnUrl = GetReturnUrl(request) ?? makeAppRelative(request.RawUrl);\n\n            // Get the app relative path to the redirect url\n            redirectUrl = GetVirtualPath(redirectUrl);\n\n            // Get the current page with return url\n            redirectUrl += \"?\" + ReturnUrlQueryString + \"=\" + HttpUtility.UrlEncode(returnUrl);\n\n            return redirectUrl;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages.Administration/Login.cshtml",
    "content": "﻿@* Generator: WebPage *@\n\n@using System.Globalization;\n@{\n    Page.Title = AdminResources.LoginTitle;\n\n    // No admin password has been registered so redirect\n    if(!AdminSecurity.HasAdminPassword()) {\n        SiteAdmin.RedirectToRegister(Response);\n        return;\n    }\n\n    if (IsPost) {\n        AntiForgery.Validate();\n        var password = Request.Form[\"password\"];\n\n        if (AdminSecurity.CheckPassword(password)) {\n            // Get the return url\n            var returnUrl = SiteAdmin.GetReturnUrl(Request) ?? SiteAdmin.AdminVirtualPath;\n\n            // Set the admin auth cookie\n            AdminSecurity.SetAuthCookie(Response);\n\n            // Redirect to the return url\n            Response.Redirect(returnUrl);\n        }\n        else {\n            ModelState.AddError(\"password\", AdminResources.Validation_PasswordIncorrect);\n        }\n    }\n}\n\n@section Head{\n    <script type=\"text/javascript\">\n    function showForgotPasswordInfo(){\n        document.getElementById('forgotPasswordInfo').style.display = '';\n    }\n    </script>\n}\n\n@Html.ValidationSummary()\n<br />\n\n<form method=\"post\" action=\"\">\n    @AntiForgery.GetHtml()\n    <fieldset>\n    <ol>\n        <li class=\"password\">\n            <label for=\"password\">@AdminResources.Password:</label>\n            @Html.Password(\"password\") @Html.ValidationMessage(\"password\", \"*\")\n    </ol>\n    <p class=\"form-actions\">\n        <input type=\"submit\" value=\"@AdminResources.Login\" />\n    </p>\n    </fieldset>\n    <p>\n        <a href=\"#\" onclick=\"showForgotPasswordInfo(); return false;\">@AdminResources.ForgotPassword</a>\n    </p>\n</form>\n<br />\n@{ \n    var passwordFileLocation = AdminSecurity.AdminPasswordFile.TrimStart('~', '/');\n    var forgotPasswordHelp = String.Format(CultureInfo.CurrentCulture, AdminResources.AdminPasswordChangeInstructions, Html.Encode(passwordFileLocation));\n}\n<span id=\"forgotPasswordInfo\" style=\"display: none\">@Html.Raw(forgotPasswordHelp)</span>"
  },
  {
    "path": "src/System.Web.WebPages.Administration/Logout.cshtml",
    "content": "﻿@* Generator: WebPage *@\n\n@{    \n    // Delete the admin auth cookie\n    AdminSecurity.DeleteAuthCookie(Response);\n\n    // Redirect home\n    SiteAdmin.RedirectToHome(Response);\n}\n"
  },
  {
    "path": "src/System.Web.WebPages.Administration/Properties/AssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Web;\nusing System.Web.WebPages.Administration;\n\n// General Information about an assembly is controlled through the following \n// set of attributes. Change these attribute values to modify the information\n// associated with an assembly.\n\n[assembly: AssemblyTitle(\"System.Web.WebPages.Administration\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: PreApplicationStartMethod(typeof(PreApplicationStartCode), \"Start\")]\n[assembly: InternalsVisibleTo(\"System.Web.WebPages.Administration.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n"
  },
  {
    "path": "src/System.Web.WebPages.Administration/Register.cshtml",
    "content": "﻿@* Generator: WebPage *@\n\n@using System.Globalization;\n@{\n    Page.Title = AdminResources.RegisterTitle;\n    var adminPath = SiteAdmin.AdminVirtualPath.TrimStart('~');\n    Page.Desc = String.Format(CultureInfo.CurrentCulture, AdminResources.RegisterDesc, Html.Encode(adminPath));\n\n    // If the password is already set the redirect to login\n    if(AdminSecurity.HasAdminPassword()) {\n        SiteAdmin.RedirectToLogin(Response);\n        return;\n    }\n\n    if (IsPost) {\n        AntiForgery.Validate();\n\n        var password = Request.Form[\"password\"];\n        var reenteredPassword = Request.Form[\"repassword\"];\n        if (password.IsEmpty()) {\n            ModelState.AddError(\"password\", AdminResources.Validation_PasswordRequired); \n        }\n        else if (password != reenteredPassword) {\n            ModelState.AddError(\"repassword\", AdminResources.Validation_PasswordsDoNotMatch);\n        }\n\n        if (ModelState.IsValid) {\n            // Save the admin password\n            if(AdminSecurity.SaveTemporaryPassword(password)) {\n                // Get the return url\n                var returnUrl = SiteAdmin.GetReturnUrl(Request) ?? SiteAdmin.AdminVirtualPath;\n\n                // Redirect to the return url\n                Response.Redirect(returnUrl);\n            }\n            else {\n                // Add a validation error since creating the password.txt failed\n                ModelState.AddFormError(AdminResources.AdminModuleRequiresAccessToAppData);\n            }\n            \n        }\n    }\n}\n\n<br/>\n\n@Html.ValidationSummary()\n\n<form method=\"post\" action=\"\">\n@AntiForgery.GetHtml()\n<fieldset>\n    <ol>\n        <li class=\"password\">\n            <label for=\"password\">@AdminResources.EnterPassword</label>\n            @Html.Password(\"password\") @Html.ValidationMessage(\"password\", \"*\")\n        </li>\n        <li class=\"password\">\n            <label>@AdminResources.ReenterPassword</label>\n            @Html.Password(\"repassword\") @Html.ValidationMessage(\"repassword\", \"*\")\n        </li>\n    </ol>\n    <p class=\"form-actions\">\n        <input type=\"submit\" value=\"@AdminResources.CreatePassword\" class=\"long-input\" />\n    </p>\n</fieldset>\n</form>\n"
  },
  {
    "path": "src/System.Web.WebPages.Administration/Resources/AdminResources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.214\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace System.Web.WebPages.Administration {\n    using System;\n    \n    \n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class AdminResources {\n        \n        private static global::System.Resources.ResourceManager resourceMan;\n        \n        private static global::System.Globalization.CultureInfo resourceCulture;\n        \n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal AdminResources() {\n        }\n        \n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"System.Web.WebPages.Administration.Resources.AdminResources\", typeof(AdminResources).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n        \n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Home.\n        /// </summary>\n        internal static string AdminHome {\n            get {\n                return ResourceManager.GetString(\"AdminHome\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Web Pages Administration.\n        /// </summary>\n        internal static string AdminModuleDisplayTitle {\n            get {\n                return ResourceManager.GetString(\"AdminModuleDisplayTitle\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The Admin Module requires write access to ~/App_Data.\n        /// </summary>\n        internal static string AdminModuleRequiresAccessToAppData {\n            get {\n                return ResourceManager.GetString(\"AdminModuleRequiresAccessToAppData\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to ASP.NET Web Pages Administration.\n        /// </summary>\n        internal static string AdminModuleTitle {\n            get {\n                return ResourceManager.GetString(\"AdminModuleTitle\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to To reset the password, delete the &lt;strong&gt;{0}&lt;/strong&gt; file and revisit this page..\n        /// </summary>\n        internal static string AdminPasswordChangeInstructions {\n            get {\n                return ResourceManager.GetString(\"AdminPasswordChangeInstructions\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to &lt;a href=&quot;{0}&quot;&gt;Click here&lt;/a&gt; to continue and verify your password after you have renamed the file to Password.config..\n        /// </summary>\n        internal static string ContinueAfterEnableText {\n            get {\n                return ResourceManager.GetString(\"ContinueAfterEnableText\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Create Password.\n        /// </summary>\n        internal static string CreatePassword {\n            get {\n                return ResourceManager.GetString(\"CreatePassword\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to For security reasons your password hash is saved in a file named _Password.config in the /App_Data/Admin/ folder of your website. To fully enable site administration, rename the file to Password.config by removing the underscore (_) character from the file name. If this is the first time you are seeing these instructions and you have not yet created a password, then remove the /App_Data/Admin/_Password.config file. This will remove a previously created password and allow you to create your own password.\n        /// </summary>\n        internal static string EnableInstructions {\n            get {\n                return ResourceManager.GetString(\"EnableInstructions\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Enter Password.\n        /// </summary>\n        internal static string EnterPassword {\n            get {\n                return ResourceManager.GetString(\"EnterPassword\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Forgot Password?.\n        /// </summary>\n        internal static string ForgotPassword {\n            get {\n                return ResourceManager.GetString(\"ForgotPassword\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The return URL specified for request redirection is invalid..\n        /// </summary>\n        internal static string InvalidReturnUrl {\n            get {\n                return ResourceManager.GetString(\"InvalidReturnUrl\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Login.\n        /// </summary>\n        internal static string Login {\n            get {\n                return ResourceManager.GetString(\"Login\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Login to ASP.NET Web Pages Administration.\n        /// </summary>\n        internal static string LoginTitle {\n            get {\n                return ResourceManager.GetString(\"LoginTitle\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Logo.\n        /// </summary>\n        internal static string LogoLabel {\n            get {\n                return ResourceManager.GetString(\"LogoLabel\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Logout.\n        /// </summary>\n        internal static string Logout {\n            get {\n                return ResourceManager.GetString(\"Logout\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Module already registered for virtual path &apos;{0}&apos;.\n        /// </summary>\n        internal static string ModuleAlreadyRegistered {\n            get {\n                return ResourceManager.GetString(\"ModuleAlreadyRegistered\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Modules.\n        /// </summary>\n        internal static string Modules {\n            get {\n                return ResourceManager.GetString(\"Modules\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to No modules are currently installed..\n        /// </summary>\n        internal static string NoAdminModulesInstalled {\n            get {\n                return ResourceManager.GetString(\"NoAdminModulesInstalled\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Password.\n        /// </summary>\n        internal static string Password {\n            get {\n                return ResourceManager.GetString(\"Password\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Confirm Password.\n        /// </summary>\n        internal static string ReenterPassword {\n            get {\n                return ResourceManager.GetString(\"ReenterPassword\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Accessing pages in ASP.NET Web Pages Package Administration requires a password. You create the password the first time you visit a page in this directory..\n        /// </summary>\n        internal static string RegisterDesc {\n            get {\n                return ResourceManager.GetString(\"RegisterDesc\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Create a password.\n        /// </summary>\n        internal static string RegisterTitle {\n            get {\n                return ResourceManager.GetString(\"RegisterTitle\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to ASP.NET Web Pages Administration Security Check.\n        /// </summary>\n        internal static string SecurityTitle {\n            get {\n                return ResourceManager.GetString(\"SecurityTitle\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The password in incorrect.\n        /// </summary>\n        internal static string Validation_PasswordIncorrect {\n            get {\n                return ResourceManager.GetString(\"Validation_PasswordIncorrect\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A password is required..\n        /// </summary>\n        internal static string Validation_PasswordRequired {\n            get {\n                return ResourceManager.GetString(\"Validation_PasswordRequired\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Confirm password does not match password.\n        /// </summary>\n        internal static string Validation_PasswordsDoNotMatch {\n            get {\n                return ResourceManager.GetString(\"Validation_PasswordsDoNotMatch\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages.Administration/Resources/AdminResources.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"AdminModuleTitle\" xml:space=\"preserve\">\n    <value>ASP.NET Web Pages Administration</value>\n  </data>\n  <data name=\"LoginTitle\" xml:space=\"preserve\">\n    <value>Login to ASP.NET Web Pages Administration</value>\n  </data>\n  <data name=\"RegisterTitle\" xml:space=\"preserve\">\n    <value>Create a password</value>\n  </data>\n  <data name=\"ModuleAlreadyRegistered\" xml:space=\"preserve\">\n    <value>Module already registered for virtual path '{0}'</value>\n  </data>\n  <data name=\"NoAdminModulesInstalled\" xml:space=\"preserve\">\n    <value>No modules are currently installed.</value>\n  </data>\n  <data name=\"Validation_PasswordIncorrect\" xml:space=\"preserve\">\n    <value>The password in incorrect</value>\n  </data>\n  <data name=\"Validation_PasswordRequired\" xml:space=\"preserve\">\n    <value>A password is required.</value>\n  </data>\n  <data name=\"Logout\" xml:space=\"preserve\">\n    <value>Logout</value>\n  </data>\n  <data name=\"Login\" xml:space=\"preserve\">\n    <value>Login</value>\n  </data>\n  <data name=\"Password\" xml:space=\"preserve\">\n    <value>Password</value>\n  </data>\n  <data name=\"AdminModuleRequiresAccessToAppData\" xml:space=\"preserve\">\n    <value>The Admin Module requires write access to ~/App_Data</value>\n  </data>\n  <data name=\"CreatePassword\" xml:space=\"preserve\">\n    <value>Create Password</value>\n  </data>\n  <data name=\"InvalidReturnUrl\" xml:space=\"preserve\">\n    <value>The return URL specified for request redirection is invalid.</value>\n  </data>\n  <data name=\"EnterPassword\" xml:space=\"preserve\">\n    <value>Enter Password</value>\n  </data>\n  <data name=\"ReenterPassword\" xml:space=\"preserve\">\n    <value>Confirm Password</value>\n  </data>\n  <data name=\"Validation_PasswordsDoNotMatch\" xml:space=\"preserve\">\n    <value>Confirm password does not match password</value>\n  </data>\n  <data name=\"EnableInstructions\" xml:space=\"preserve\">\n    <value>For security reasons your password hash is saved in a file named _Password.config in the /App_Data/Admin/ folder of your website. To fully enable site administration, rename the file to Password.config by removing the underscore (_) character from the file name. If this is the first time you are seeing these instructions and you have not yet created a password, then remove the /App_Data/Admin/_Password.config file. This will remove a previously created password and allow you to create your own password</value>\n    <comment>This resource string will be printed without html encoding. Ensure parameters are html encoded.</comment>\n  </data>\n  <data name=\"AdminPasswordChangeInstructions\" xml:space=\"preserve\">\n    <value>To reset the password, delete the &lt;strong&gt;{0}&lt;/strong&gt; file and revisit this page.</value>\n    <comment>This resource string will be printed without html encoding. Ensure parameters are html encoded.</comment>\n  </data>\n  <data name=\"ForgotPassword\" xml:space=\"preserve\">\n    <value>Forgot Password?</value>\n  </data>\n  <data name=\"Modules\" xml:space=\"preserve\">\n    <value>Modules</value>\n  </data>\n  <data name=\"RegisterDesc\" xml:space=\"preserve\">\n    <value>Accessing pages in ASP.NET Web Pages Package Administration requires a password. You create the password the first time you visit a page in this directory.</value>\n  </data>\n  <data name=\"AdminHome\" xml:space=\"preserve\">\n    <value>Home</value>\n  </data>\n  <data name=\"AdminModuleDisplayTitle\" xml:space=\"preserve\">\n    <value>Web Pages Administration</value>\n  </data>\n  <data name=\"LogoLabel\" xml:space=\"preserve\">\n    <value>Logo</value>\n  </data>\n  <data name=\"ContinueAfterEnableText\" xml:space=\"preserve\">\n    <value>&lt;a href=\"{0}\"&gt;Click here&lt;/a&gt; to continue and verify your password after you have renamed the file to Password.config.</value>\n    <comment>This resource string will be printed without html encoding. Ensure parameters are html encoded.</comment>\n  </data>\n  <data name=\"SecurityTitle\" xml:space=\"preserve\">\n    <value>ASP.NET Web Pages Administration Security Check</value>\n  </data>\n</root>"
  },
  {
    "path": "src/System.Web.WebPages.Administration/Resources/PackageManagerResources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.488\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace System.Web.WebPages.Administration.PackageManager {\n    using System;\n    \n    \n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class PackageManagerResources {\n        \n        private static global::System.Resources.ResourceManager resourceMan;\n        \n        private static global::System.Globalization.CultureInfo resourceCulture;\n        \n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal PackageManagerResources() {\n        }\n        \n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"System.Web.WebPages.Administration.Resources.PackageManagerResources\", typeof(PackageManagerResources).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n        \n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Add Package Source.\n        /// </summary>\n        internal static string AddPackageSourceLabel {\n            get {\n                return ResourceManager.GetString(\"AddPackageSourceLabel\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Are you sure you want to uninstall &lt;strong&gt;{0}&lt;/strong&gt;?.\n        /// </summary>\n        internal static string AreYouSureUninstall {\n            get {\n                return ResourceManager.GetString(\"AreYouSureUninstall\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Author.\n        /// </summary>\n        internal static string AuthorsLabel {\n            get {\n                return ResourceManager.GetString(\"AuthorsLabel\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Bad Request.\n        /// </summary>\n        internal static string BadRequest {\n            get {\n                return ResourceManager.GetString(\"BadRequest\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Cancel.\n        /// </summary>\n        internal static string Cancel {\n            get {\n                return ResourceManager.GetString(\"Cancel\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Clear.\n        /// </summary>\n        internal static string ClearLabel {\n            get {\n                return ResourceManager.GetString(\"ClearLabel\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Default.\n        /// </summary>\n        internal static string DefaultPackageSourceName {\n            get {\n                return ResourceManager.GetString(\"DefaultPackageSourceName\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Delete.\n        /// </summary>\n        internal static string DeleteLabel {\n            get {\n                return ResourceManager.GetString(\"DeleteLabel\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to By clicking &quot;Install&quot; you agree to the license terms for the package(s) above. If you do not agree to the license terms, click &quot;Cancel.&quot; Each package is licensed to you by its owner. Microsoft is not responsible for, nor does it grant any licenses to, third-party packages..\n        /// </summary>\n        internal static string Disclaimer {\n            get {\n                return ResourceManager.GetString(\"Disclaimer\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Installed.\n        /// </summary>\n        internal static string InstalledLabel {\n            get {\n                return ResourceManager.GetString(\"InstalledLabel\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Install.\n        /// </summary>\n        internal static string InstallPackage {\n            get {\n                return ResourceManager.GetString(\"InstallPackage\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Installing package {0}..\n        /// </summary>\n        internal static string InstallPackageDesc {\n            get {\n                return ResourceManager.GetString(\"InstallPackageDesc\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Package &lt;strong&gt;{0}&lt;/strong&gt; was successfully installed..\n        /// </summary>\n        internal static string InstallSuccess {\n            get {\n                return ResourceManager.GetString(\"InstallSuccess\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to JavaScript is required to correctly view this page..\n        /// </summary>\n        internal static string JavascriptRequired {\n            get {\n                return ResourceManager.GetString(\"JavascriptRequired\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Use this page to manage your package sources..\n        /// </summary>\n        internal static string ManageSourcesDesc {\n            get {\n                return ResourceManager.GetString(\"ManageSourcesDesc\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Manage Package Sources.\n        /// </summary>\n        internal static string ManageSourcesTitle {\n            get {\n                return ResourceManager.GetString(\"ManageSourcesTitle\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to A collection of tools to automate the process of installing, upgrading, configuring, and removing packages from an ASP.NET application..\n        /// </summary>\n        internal static string ModuleDesc {\n            get {\n                return ResourceManager.GetString(\"ModuleDesc\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Package Manager.\n        /// </summary>\n        internal static string ModuleTitle {\n            get {\n                return ResourceManager.GetString(\"ModuleTitle\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Next.\n        /// </summary>\n        internal static string NextText {\n            get {\n                return ResourceManager.GetString(\"NextText\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to No packages found..\n        /// </summary>\n        internal static string NoPackagesFound {\n            get {\n                return ResourceManager.GetString(\"NoPackagesFound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to No packages installed. &lt;p&gt;&lt;a href=&quot;{0}&quot;&gt;Install packages from an online feed&lt;/a&gt;&lt;/p&gt;.\n        /// </summary>\n        internal static string NoPackagesInstalled {\n            get {\n                return ResourceManager.GetString(\"NoPackagesInstalled\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Default (All).\n        /// </summary>\n        internal static string NuGetFeed {\n            get {\n                return ResourceManager.GetString(\"NuGetFeed\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Online.\n        /// </summary>\n        internal static string OnlineLabel {\n            get {\n                return ResourceManager.GetString(\"OnlineLabel\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Error installing package &quot;{0}&quot;:.\n        /// </summary>\n        internal static string PackageInstallationError {\n            get {\n                return ResourceManager.GetString(\"PackageInstallationError\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Unable to read package source file. Ensure that the file &quot;{0}&quot; is writeable and the contents of the file have not been modified externally..\n        /// </summary>\n        internal static string PackageSourceFileInstructions {\n            get {\n                return ResourceManager.GetString(\"PackageSourceFileInstructions\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Source.\n        /// </summary>\n        internal static string PackageSourceLabel {\n            get {\n                return ResourceManager.GetString(\"PackageSourceLabel\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Error occurred uninstalling package &quot;{0}&quot;:.\n        /// </summary>\n        internal static string PackageUninstallationError {\n            get {\n                return ResourceManager.GetString(\"PackageUninstallationError\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Error occurred updating package &quot;{0}&quot;:.\n        /// </summary>\n        internal static string PackageUpdateError {\n            get {\n                return ResourceManager.GetString(\"PackageUpdateError\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Page.\n        /// </summary>\n        internal static string PageLabel {\n            get {\n                return ResourceManager.GetString(\"PageLabel\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Previous.\n        /// </summary>\n        internal static string PreviousText {\n            get {\n                return ResourceManager.GetString(\"PreviousText\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Privacy Statement.\n        /// </summary>\n        internal static string PrivacyStatement {\n            get {\n                return ResourceManager.GetString(\"PrivacyStatement\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Remove Dependencies?.\n        /// </summary>\n        internal static string RemoveDependencies {\n            get {\n                return ResourceManager.GetString(\"RemoveDependencies\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Restore Default .\n        /// </summary>\n        internal static string RestoreDefaultSources {\n            get {\n                return ResourceManager.GetString(\"RestoreDefaultSources\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Search.\n        /// </summary>\n        internal static string SearchLabel {\n            get {\n                return ResourceManager.GetString(\"SearchLabel\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Packages.\n        /// </summary>\n        internal static string SectionTitle {\n            get {\n                return ResourceManager.GetString(\"SectionTitle\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Show.\n        /// </summary>\n        internal static string ShowLabel {\n            get {\n                return ResourceManager.GetString(\"ShowLabel\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Name.\n        /// </summary>\n        internal static string SourceNameLabel {\n            get {\n                return ResourceManager.GetString(\"SourceNameLabel\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Source.\n        /// </summary>\n        internal static string SourceUrlLabel {\n            get {\n                return ResourceManager.GetString(\"SourceUrlLabel\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Uninstall.\n        /// </summary>\n        internal static string UninstallPackage {\n            get {\n                return ResourceManager.GetString(\"UninstallPackage\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Uninstalling package {0}..\n        /// </summary>\n        internal static string UninstallPackageDesc {\n            get {\n                return ResourceManager.GetString(\"UninstallPackageDesc\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Package &lt;strong&gt;{0}&lt;/strong&gt; was successfully uninstalled..\n        /// </summary>\n        internal static string UninstallSuccess {\n            get {\n                return ResourceManager.GetString(\"UninstallSuccess\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Unknown framework assembly: &quot;{0}&quot;.\n        /// </summary>\n        internal static string UnknownFrameworkReference {\n            get {\n                return ResourceManager.GetString(\"UnknownFrameworkReference\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Update.\n        /// </summary>\n        internal static string UpdatePackage {\n            get {\n                return ResourceManager.GetString(\"UpdatePackage\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Updating package {0} to version {1}..\n        /// </summary>\n        internal static string UpdatePackageDesc {\n            get {\n                return ResourceManager.GetString(\"UpdatePackageDesc\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Updates.\n        /// </summary>\n        internal static string UpdatesLabel {\n            get {\n                return ResourceManager.GetString(\"UpdatesLabel\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Package &lt;strong&gt;{0}&lt;/strong&gt; was successfully updated..\n        /// </summary>\n        internal static string UpdateSuccess {\n            get {\n                return ResourceManager.GetString(\"UpdateSuccess\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Invalid source url..\n        /// </summary>\n        internal static string Validation_InvalidPackageSourceUrl {\n            get {\n                return ResourceManager.GetString(\"Validation_InvalidPackageSourceUrl\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Specified package source already exists..\n        /// </summary>\n        internal static string Validation_PackageSourceAlreadyExists {\n            get {\n                return ResourceManager.GetString(\"Validation_PackageSourceAlreadyExists\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to View License Terms.\n        /// </summary>\n        internal static string ViewLicenseTerms {\n            get {\n                return ResourceManager.GetString(\"ViewLicenseTerms\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to , .\n        /// </summary>\n        internal static string WordSeparator {\n            get {\n                return ResourceManager.GetString(\"WordSeparator\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages.Administration/Resources/PackageManagerResources.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"PackageSourceLabel\" xml:space=\"preserve\">\n    <value>Source</value>\n  </data>\n  <data name=\"PageLabel\" xml:space=\"preserve\">\n    <value>Page</value>\n  </data>\n  <data name=\"InstallPackage\" xml:space=\"preserve\">\n    <value>Install</value>\n  </data>\n  <data name=\"DefaultPackageSourceName\" xml:space=\"preserve\">\n    <value>Default</value>\n  </data>\n  <data name=\"NoPackagesFound\" xml:space=\"preserve\">\n    <value>No packages found.</value>\n  </data>\n  <data name=\"PackageInstallationError\" xml:space=\"preserve\">\n    <value>Error installing package \"{0}\":</value>\n  </data>\n  <data name=\"PackageUninstallationError\" xml:space=\"preserve\">\n    <value>Error occurred uninstalling package \"{0}\":</value>\n  </data>\n  <data name=\"SearchLabel\" xml:space=\"preserve\">\n    <value>Search</value>\n  </data>\n  <data name=\"UninstallPackage\" xml:space=\"preserve\">\n    <value>Uninstall</value>\n  </data>\n  <data name=\"BadRequest\" xml:space=\"preserve\">\n    <value>Bad Request</value>\n  </data>\n  <data name=\"ModuleDesc\" xml:space=\"preserve\">\n    <value>A collection of tools to automate the process of installing, upgrading, configuring, and removing packages from an ASP.NET application.</value>\n  </data>\n  <data name=\"ModuleTitle\" xml:space=\"preserve\">\n    <value>Package Manager</value>\n  </data>\n  <data name=\"NoPackagesInstalled\" xml:space=\"preserve\">\n    <value>No packages installed. &lt;p&gt;&lt;a href=\"{0}\"&gt;Install packages from an online feed&lt;/a&gt;&lt;/p&gt;</value>\n    <comment>Not HTML encoding the text. Ensure params are encoded</comment>\n  </data>\n  <data name=\"AuthorsLabel\" xml:space=\"preserve\">\n    <value>Author</value>\n  </data>\n  <data name=\"WordSeparator\" xml:space=\"preserve\">\n    <value>, </value>\n    <comment>String used as glue to join multiple words into a single comma separated string </comment>\n  </data>\n  <data name=\"Disclaimer\" xml:space=\"preserve\">\n    <value>By clicking \"Install\" you agree to the license terms for the package(s) above. If you do not agree to the license terms, click \"Cancel.\" Each package is licensed to you by its owner. Microsoft is not responsible for, nor does it grant any licenses to, third-party packages.</value>\n  </data>\n  <data name=\"InstallPackageDesc\" xml:space=\"preserve\">\n    <value>Installing package {0}.</value>\n  </data>\n  <data name=\"UninstallPackageDesc\" xml:space=\"preserve\">\n    <value>Uninstalling package {0}.</value>\n  </data>\n  <data name=\"AreYouSureUninstall\" xml:space=\"preserve\">\n    <value>Are you sure you want to uninstall &lt;strong&gt;{0}&lt;/strong&gt;?</value>\n    <comment>Not HTML encoding the text. Ensure params are encoded </comment>\n  </data>\n  <data name=\"Cancel\" xml:space=\"preserve\">\n    <value>Cancel</value>\n  </data>\n  <data name=\"UninstallSuccess\" xml:space=\"preserve\">\n    <value>Package &lt;strong&gt;{0}&lt;/strong&gt; was successfully uninstalled.</value>\n    <comment>Not HTML encoding the text. Ensure params are encoded</comment>\n  </data>\n  <data name=\"UpdatePackage\" xml:space=\"preserve\">\n    <value>Update</value>\n  </data>\n  <data name=\"JavascriptRequired\" xml:space=\"preserve\">\n    <value>JavaScript is required to correctly view this page.</value>\n  </data>\n  <data name=\"ViewLicenseTerms\" xml:space=\"preserve\">\n    <value>View License Terms</value>\n  </data>\n  <data name=\"InstallSuccess\" xml:space=\"preserve\">\n    <value>Package &lt;strong&gt;{0}&lt;/strong&gt; was successfully installed.</value>\n    <comment>Not HTML encoding the text. Ensure params are encoded</comment>\n  </data>\n  <data name=\"UpdatePackageDesc\" xml:space=\"preserve\">\n    <value>Updating package {0} to version {1}.</value>\n    <comment>Updating Foo 1.1 to version 1.3.</comment>\n  </data>\n  <data name=\"UpdateSuccess\" xml:space=\"preserve\">\n    <value>Package &lt;strong&gt;{0}&lt;/strong&gt; was successfully updated.</value>\n    <comment>Not HTML encoding the text. Ensure params are encoded</comment>\n  </data>\n  <data name=\"ClearLabel\" xml:space=\"preserve\">\n    <value>Clear</value>\n  </data>\n  <data name=\"ManageSourcesDesc\" xml:space=\"preserve\">\n    <value>Use this page to manage your package sources.</value>\n  </data>\n  <data name=\"AddPackageSourceLabel\" xml:space=\"preserve\">\n    <value>Add Package Source</value>\n  </data>\n  <data name=\"DeleteLabel\" xml:space=\"preserve\">\n    <value>Delete</value>\n  </data>\n  <data name=\"SourceNameLabel\" xml:space=\"preserve\">\n    <value>Name</value>\n  </data>\n  <data name=\"SourceUrlLabel\" xml:space=\"preserve\">\n    <value>Source</value>\n  </data>\n  <data name=\"ManageSourcesTitle\" xml:space=\"preserve\">\n    <value>Manage Package Sources</value>\n  </data>\n  <data name=\"Validation_InvalidPackageSourceUrl\" xml:space=\"preserve\">\n    <value>Invalid source url.</value>\n  </data>\n  <data name=\"PackageSourceFileInstructions\" xml:space=\"preserve\">\n    <value>Unable to read package source file. Ensure that the file \"{0}\" is writeable and the contents of the file have not been modified externally.</value>\n  </data>\n  <data name=\"RestoreDefaultSources\" xml:space=\"preserve\">\n    <value>Restore Default </value>\n  </data>\n  <data name=\"PackageUpdateError\" xml:space=\"preserve\">\n    <value>Error occurred updating package \"{0}\":</value>\n  </data>\n  <data name=\"RemoveDependencies\" xml:space=\"preserve\">\n    <value>Remove Dependencies?</value>\n  </data>\n  <data name=\"SectionTitle\" xml:space=\"preserve\">\n    <value>Packages</value>\n  </data>\n  <data name=\"Validation_PackageSourceAlreadyExists\" xml:space=\"preserve\">\n    <value>Specified package source already exists.</value>\n  </data>\n  <data name=\"ShowLabel\" xml:space=\"preserve\">\n    <value>Show</value>\n  </data>\n  <data name=\"InstalledLabel\" xml:space=\"preserve\">\n    <value>Installed</value>\n  </data>\n  <data name=\"OnlineLabel\" xml:space=\"preserve\">\n    <value>Online</value>\n  </data>\n  <data name=\"UpdatesLabel\" xml:space=\"preserve\">\n    <value>Updates</value>\n  </data>\n  <data name=\"NuGetFeed\" xml:space=\"preserve\">\n    <value>Default (All)</value>\n  </data>\n  <data name=\"PrivacyStatement\" xml:space=\"preserve\">\n    <value>Privacy Statement</value>\n  </data>\n  <data name=\"UnknownFrameworkReference\" xml:space=\"preserve\">\n    <value>Unknown framework assembly: \"{0}\"</value>\n  </data>\n  <data name=\"NextText\" xml:space=\"preserve\">\n    <value>Next</value>\n  </data>\n  <data name=\"PreviousText\" xml:space=\"preserve\">\n    <value>Previous</value>\n  </data>\n</root>"
  },
  {
    "path": "src/System.Web.WebPages.Administration/Site.css",
    "content": "/* Reset\n***************************************************************/\n\nhtml, body, div, span, applet, object, iframe,\nh1, h2, h3, h4, h5, h6, p, blockquote, pre,\na, abbr, acronym, address, big, cite, code,\ndel, dfn, em, font, img, ins, kbd, q, s, samp,\nsmall, strike, strong, sub, sup, tt, var,\ndl, dt, dd, ol, ul, li,\nfieldset, form, label, legend,\ntable, caption, tbody, tfoot, thead, tr, th, td {\n\tmargin: 0;\n\tpadding: 0;\n\tborder: 0;\n\toutline: 0;\n\tfont-weight: inherit;\n\tfont-style: inherit;\n\tfont-size: 100%;\n\tfont-family: inherit;\n\tvertical-align: baseline;\n}\n\n/* Remember focus styles! */\n:focus { outline: 0; }\n\nbody { line-height: 1.4em; color: black; background: white; }\nol, ul { list-style: none; }\n\n/* Tables still need 'cellspacing=\"0\"' in the markup */\ntable { border-collapse: separate; border-spacing: 0; }\ncaption, td { text-align: left;  }\n\nthead th \n{\n    font-weight: bold;\n    text-align: center;\n}\n\nblockquote:before, blockquote:after,\nq:before, q:after { content: \"\"; }\nblockquote, q { quotes: \"\" \"\"; }\n\n/* HTML 5 elements as block */  \nheader, footer, aside, nav, article { display: block; }\n\n/* Clearing Floats\n***************************************************************/\n\n.group:after \n{\n\tcontent: \".\";\n\tdisplay: block;\n\theight: 0;\n\tclear: both;\n\tvisibility: hidden;\n}\n\n/* General\n***************************************************************/\n\n/* Default font settings. \nThe font-size 81.3% sets the base font to 13px \n\nPixels \tEMs \t    Percent Points\n6px \t0.462em \t46.2% \t5pt\n7px \t0.538em \t53.8% \t5pt\n8px \t0.615em \t61.5% \t6pt\n9px \t0.692em \t69.2% \t7pt\n10px \t0.769em \t76.9% \t8pt\n11px \t0.846em \t84.6% \t8pt\n12px \t0.923em \t92.3% \t9pt\n13px \t1em \t    100% \t10pt\n14px \t1.077em \t107.7% \t11pt\n15px \t1.154em \t115.4% \t11pt\n16px \t1.231em \t123.1% \t12pt\n17px \t1.308em \t130.8% \t13pt\n18px \t1.385em \t138.5% \t14pt\n19px \t1.462em \t146.2% \t14pt\n20px \t1.538em \t153.8% \t15pt\n21px \t1.615em \t161.5% \t16pt\n22px \t1.692em \t169.2% \t17pt\n23px \t1.769em \t176.9% \t17pt\n24px \t1.846em \t184.6% \t18pt\n26px\t2em\t\t\t200%\t20pt\n*/\n\nbody {\n    background-color: #ececec;\t\n  \tfont-size: 81.3%;\n    font-family: Segoe UI,Trebuchet,\"Helvetica Neue\", Arial, Helvetica, sans-serif; color:#333;\n    margin: 0;\n    padding: 0;\n    \n/*CSS3 properties*/\n    filter:progid:DXImageTransform.Microsoft.Gradient(GradientType=0, startColorstr='#ffffff',  endColorstr='#ececec');\n\tbackground: -webkit-gradient(linear, 0 0, 0 100%, from(#fff), to(#ececec)) fixed;\n\tbackground: -moz-linear-gradient(top, #fff, #ececec) fixed;  \n}\n\na:link {\n    color: #034af3;\n    text-decoration: underline;\n}\n\na:visited {\n    color: #505abc;\n}\n\na:hover {\n    color: #1d60ff;\n    text-decoration: none;\n}\n\na:active {\n    color: #12eb87;\n}\n\n/* Headings and Text Elements   \n***************************************************************/\n\n/* Headings */\nh1, h2, h3, h4, h5, h6 { color: #385366; }\n\nh1 { font-size: 184.6%; } /*24px*/\nh2 { font-size: 176.9%; } /*23px*/\nh3 { font-size: 153.8%; } /*20px*/\nh4 { font-size: 138.5%; } /*18px*/\nh5 { font-size: 123.1%; } /*16px*/\nh6 { font-size: 107.7%; } /*14px*/\n\n/* Text elements */\np  \n{\n    line-height: 18px; \n    margin-top: 10px;\n}\n\n.text-small { font-size: 84.6%; /*11px*/ }\n\nstrong \n{\n    font-weight: bold;\n}\n\ncode \n{\n    display: block;\n    margin: 5px 0px 5px 5px;\n}\n\nem \n{\n    font-style: italic;\n}\n\n/* Layout   \n***************************************************************/\n\n#page {\n    width: 90%;\n    margin-left: auto;\n    margin-right: auto;\n}\n\n#header {\n    position: relative;\n    margin-bottom: 0;\n    color: #000;\n    padding: 26px 26px 26px 0;\n}\n\n#main {\n    padding: 30px 30px 15px 30px;\n    background-color: #fff;\n    margin: 0 0 30px 0;\n    border: 1px solid #a6a6a6;\n     \n    /*CSS3 properties*/\n    border-radius: 3px;\n    -webkit-border-radius: 3px;\n    -moz-border-radius: 3px;\n\t-webkit-box-shadow: 0px 0px 4px rgba(102, 102, 102, 0.3); \n\t-moz-box-shadow: 0px 0px 4px rgba(102, 102, 102, 0.3);\n\tbox-shadow: 0px 0px 4px rgba(102, 102, 102, 0.3);\n\tbackground: -webkit-gradient(linear, 0 0, 0 100%, from(#fff), to(#f3f3f3)) fixed;\n\tbackground: -moz-linear-gradient(top, #fff, #f3f3f3) fixed;\n    filter:progid:DXImageTransform.Microsoft.Gradient(GradientType=0, startColorstr='#ffffff',  endColorstr='#f3f3f3');\n}\n\n#footer {\n    padding: 10px 0;\n    text-align: center;\n    line-height: normal;\n    margin: 0;\n}\n\n/* Site Title \n***************************************************************/\n\n#header .site-title {\n    float: left;\n\tcolor: #385366;\n    padding: 5px;\n    margin: 0;\n    border: none;\n}\n    \n    \n#header .site-title span.aspnet {\n\tcolor:#3c89c8;\n}\n\n/* Login Display  \n***************************************************************/\n\n#settings {\n    float: right;\n    font-size: 123.1%; /*16px*/\n    display: block;\n    text-align: right;\n    margin: 14px 0 0 0;\n}\n\n    #settings li {\n        margin: 0;\n        display: inline;\n        list-style: none;\n        padding: 0 0 0 5px;\n    }\n    \n    \n    #settings a:before \n    {\n        margin-right: 10px;\n        content: \"[\"\n    }\n    \n    #settings a:after \n    {\n        margin-left: 10px;\n        content: \"]\"\n    }\n    \n    #settings a:link, #settings a:visited \n    {\n        text-decoration: none;\n        margin: 0 0 0 10px;        \n        color:#034AF3;\n    }\n\n    #settings a:hover\n    {\n        text-decoration: underline;\n    }\n\n/* Tab Menu   \n***************************************************************/\n\n.nav li { font-size: 123.1%; } /*16px*/\n\nul#menu {\n    clear: both;\n    border-bottom: 1px #5c87b2 solid;\n    padding: 0 0 2px 0;\n    position: relative;\n    text-align: right;\n}\n\n    ul#menu li {\n        display: inline;\n        list-style: none;\n\n    }\n\n        ul#menu li a {\n            padding: 10px 20px 0 0;\n            font-weight: bold;\n            text-decoration: none;\n            line-height: 2.8em;\n            background-color: #e8eef4;\n            color: #034af3;\n            \n            /*CSS3 properties*/\n            border-radius: 4px 4px 0 0;\n            -webkit-border-radius: 4px 4px 0 0;\n            -moz-border-radius: 4px 4px 0 0;\n        }\n\n        ul#menu li a:hover {\n            background-color: #fff;\n            text-decoration: none;\n        }\n\n        ul#menu li a:active {\n            background-color: #a6e2a6;\n            text-decoration: none;\n        }\n\n        ul#menu li.selected a {\n            background-color: #fff;\n            color: #000;\n        }\n        \n/* Page Title   \n***************************************************************/\n\n\t.page-title {\n\tborder-bottom: 1px solid #e8e6e6;\n\tmargin: 0 0 26px 0;\n\t}\n        \n/* Forms   \n***************************************************************/\nfieldset {\n    margin: 10px 0;\n    padding: 10px;\n    border: 1px solid #ccc;\n}\n\n    fieldset legend {\n    \tfont-size: 123.1%; /*16px*/\n        font-weight: 600;\n        padding: 2px 4px 8px 4px;\n    }\n    \n    fieldset ol {\n        padding: 0;\n        list-style: none;\n    }\n    \n    fieldset ol li {\n       \tpadding: 0 0 5px 0;\n        }\n    \n    fieldset label {\n        display: block;\n        font-weight: bold;\n    }\n    \n    fieldset label.checkbox {\n        display: inline;\n    }\n    \n     select, fieldset  input[type=\"text\"], input[type=\"password\"] {\n        border: 1px solid #c4c4c4;\n        color: #444;\n        width: 300px;\n\t\tpadding: 3px;\n   \n     \t/*CSS3 properties*/\n        border-radius: 3px;\n  \t\t-webkit-border-radius: 3px;\n    \t-moz-border-radius: 3px;\n    }\n\n\tselect {\n\twidth: auto;\n}\n\ninput[type=\"submit\"],\ninput[type=\"reset\"],\ninput[type=\"button\"]\n{\n        font-size: 107.7%; /*14px*/\n  \t\tcolor:#333;\n\t\tbackground:#F5F5F5;\n\t\tborder:1px solid #999;\n\t\tcursor:pointer;\n\t\twidth:80px;\n\t\tpadding: 1px;\n\t\ttext-align:center;\n\t\t\n\t\t/*CSS3 properties*/\n\t\tfilter:progid:DXImageTransform.Microsoft.Gradient(GradientType=0, startColorstr='#f5f5f5',  endColorstr='#cbcbcb');\n\t\tbackground: -webkit-gradient(linear, 0 0, 0 100%, from(#f5f5f5), to(#cbcbcb));\n\t\tbackground: -moz-linear-gradient(top, #f5f5f5, #cbcbcb);\n\t\t\n\t\tbox-shadow: inset 0px 0px 1px rgba(255, 255, 255, 1.0), 1px 1px 1px rgba(102, 102, 102, 0.3);\n\t\t-webkit-box-shadow: inset 0px 0px 1px rgba(255, 255, 255, 1.0), 1px 1px 1px rgba(102, 102, 102, 0.3); \n\t\t-moz-box-shadow: inset 0px 0px 1px rgba(255, 255, 255, 1.0), 1px 1px 1px rgba(102, 102, 102, 0.3);\n\t\tborder-radius: 3px;\n\t\t-webkit-border-radius: 3px;\n\t\t-moz-border-radius: 3px;\n    }\n    \n\ninput[type=\"submit\"]:hover,\ninput[type=\"reset\"]:hover,\ninput[type=\"button\"]:hover,\nbutton:hover {\n\ttext-decoration:none; \n\tbackground: #62a9e2;\n\tcolor:#fff;\n\tborder:1px solid #2e76b1;\n\t\n\t/*CSS3 properties*/\t\n\tfilter:progid:DXImageTransform.Microsoft.Gradient(GradientType=0, startColorstr='#62a9e2',  endColorstr='#3c89c8');\n\tbackground: -webkit-gradient(linear, 0 0, 0 100%, from(#62a9e2), to(#3c89c8));\n\tbackground: -moz-linear-gradient(top, #62a9e2, #3c89c8);\n}\n\ninput[type=\"submit\"]:active,\ninput[type=\"reset\"]:active,\ninput[type=\"button\"]:active,\nbutton:active {\n\ttext-decoration:none; \n\tbackground: #62a9e2;\n\tcolor:#fff;\n \tborder:1px solid #093253;\n \n \t/*CSS3 properties*/\t\n \tfilter:progid:DXImageTransform.Microsoft.Gradient(GradientType=0, startColorstr='#72b8f2',  endColorstr='#3078b3');\n \tbackground: -webkit-gradient(linear, 0 0, 0 100%, from(#72b8f2), to(#3078b3));\n\tbackground: -moz-linear-gradient(top, #72b8f2, #3078b3);\n\tbox-shadow: inset 0px 0px 1px rgba(0, 0, 0, 1.0), 1px 1px 1px rgba(102, 102, 102, 0.3);\n\t-moz-box-shadow: inset 0px 0px 1px rgba(0, 0, 0, 1.0), 1px 1px 1px rgba(102, 102, 102, 0.3);\n\t-webkit-box-shadow: inset 0px 0px 1px rgba(0, 0, 0, 1.0), 1px 1px 1px rgba(102, 102, 102, 0.3);\n}\n\ninput[type=\"submit\"].long-input,\ninput[type=\"reset\"].long-input,\ninput[type=\"button\"].long-input,\nbutton.long-input {\n    width: 140px;\n}\n\ninput[type=\"submit\"]:focus::-moz-focus-inner, button:focus::-moz-focus-inner {\n  border: 1px dotted transparent;\n}\n\n    \n /* Information and errors  \n----------------------------------------------------------*/  \n.message {\n    clear: both;\n    border: 1px solid;\n    margin: 10px 0px;\n    padding: 15px;\n    font-weight: bold;\n    \n    /*CSS3 properties*/\n    border-radius: 3px;\n    -moz-border-radius: 3px;\n    -webkit-border-radius: 3px;\n\n\t-moz-box-shadow: inset 0px 0px 1px rgba(0, 0, 0, 1.0), 1px 1px 1px rgba(102, 102, 102, 0.3);\n\t-webkit-box-shadow: inset 0px 0px 1px rgba(0, 0, 0, 1.0), 1px 1px 1px rgba(102, 102, 102, 0.3);\n\tbox-shadow: inset 0px 0px 1px rgba(0, 0, 0, 1.0), 1px 1px 1px rgba(102, 102, 102, 0.3);\n}\n\n.info {\n    background: #dddddd;\n    color: #00529b;\n}\n\n.error {\n    background: #ffe4e4;\n    color: #d63301;\n}\n\n.success {\n    background: #dff2bf;\n    color: #43750E;\n}\n\ninput[type=\"text\"].validation-error, input[type=\"password\"].validation-error { \n    border: solid 1px #d63301; \n    background-color: #ffccba;\n    font-weight: inherit;\n    font-size: inherit;\n    color: inherit;\n}\n\n.validation-error {\n    display: inline;\n    color: #be3e16;\n    font-weight: 600;\n    font-size: 123.1%; /*16px*/\n}\n\n.page-title > h1\n{\n    margin-top: 0;\n}\n\n.page-title > span \n{\n    font-style: italic;\n}\n.modules\n{\n    list-style-type: none;\n    margin: 0 0 0 -15px;\n}\n\n\n.modules > li\n{\n    background: url(images/package.png) no-repeat 0 10%;\n    padding: 0 0 0 30px;\n}\n\n.modules > li > a\n{\n    font-size: 123.1%; /*16px*/\n\n}\n\n#breadcrumbs\n{\n    font-size: 123.1%; /*16px*/\n    margin:0 auto;\n    display: block;\n    height: 44px;\n}\n\n#breadcrumbs ul, #breadcrumbs  li \n{\n    float:left;\n    margin:0 8px;\n    height: 100%;\n}\n\n#breadcrumbs ul \n{\n    line-height: 20px;\n    list-style: none outside none;\n    padding: 0;\n}\n\n\n#breadcrumbs li.selected\n{\n    background:url(\"images/tabOn.gif\") no-repeat scroll 45% bottom transparent;\n    bottom: -1px;\n    position: relative;\n}\n\n#breadcrumbs a, #breadcrumbs a:visited, #breadcrumbs a:active\n{\n    text-decoration: none;\n    color:#034AF3;\n}\n\n.error ul \n{\n    padding: 0;\n    margin: 0;\n}\n\n.error ul li \n{\n    list-style-type: none;\n\n}\n\n.page-settings \n{\n    float: right;\n    width: 5%;   \n    text-transform: lowercase;\n}\n\nhr \n{\n    border-top: none;\n    border-left: none;\n    border-right: none;\n    border-bottom: 1px solid #E8E6E6;\n}\n\n/* Misc\n***************************************************************/\n\n.clear { clear: both; }\n\n.left { float: left; }\n\n.centered { text-align: center; }\n\n.right { float: right; }\n\nimg.inline \n{\n    vertical-align: text-bottom;\n}\n\n\n\n"
  },
  {
    "path": "src/System.Web.WebPages.Administration/System.Web.WebPages.Administration.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{C23F02FC-4538-43F5-ABBA-38BA069AEA8F}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>System.Web.WebPages.Administration</RootNamespace>\n    <AssemblyName>System.Web.WebPages.Administration</AssemblyName>\n    <DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>\n    <RunCodeAnalysis>$(CodeAnalysis)</RunCodeAnalysis>\n    <CodeAnalysisRuleSet>..\\Strict.ruleset</CodeAnalysisRuleSet>\n    <DefineConstants>$(DefineConstants);ASPNETWEBPAGES</DefineConstants>\n    <NoWarn>1591</NoWarn>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"NuGet.Core, Version=1.6.30117.9648, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL\">\n      <Private>True</Private>\n      <HintPath>..\\..\\packages\\Nuget.Core.1.6.2\\lib\\net40\\NuGet.Core.dll</HintPath>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"System.Xml.Linq\" />\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"System.Xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\CommonResources.Designer.cs\">\n      <Link>Common\\CommonResources.Designer.cs</Link>\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>CommonResources.resx</DependentUpon>\n    </Compile>\n    <Compile Include=\"..\\GlobalSuppressions.cs\">\n      <Link>Common\\GlobalSuppressions.cs</Link>\n    </Compile>\n    <Compile Include=\"Framework\\packages\\RemoteAssembly.cs\" />\n    <Compile Include=\"Framework\\packages\\IPackagesSourceFile.cs\" />\n    <Compile Include=\"Framework\\packages\\IWebProjectManager.cs\" />\n    <Compile Include=\"Framework\\packages\\PackageSourceFile.cs\" />\n    <Compile Include=\"Framework\\packages\\WebProjectManager.cs\" />\n    <Compile Include=\"Framework\\packages\\WebProjectSystem.cs\" />\n    <Compile Include=\"Framework\\SiteAdmin.cs\" />\n    <Compile Include=\"Framework\\packages\\WebPackageSource.cs\" />\n    <Compile Include=\"Framework\\packages\\PackageManagerModule.cs\" />\n    <Compile Include=\"Framework\\packages\\PageUtils.cs\" />\n    <Compile Include=\"Resources\\PackageManagerResources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>PackageManagerResources.resx</DependentUpon>\n    </Compile>\n    <Compile Include=\"Resources\\AdminResources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>AdminResources.resx</DependentUpon>\n    </Compile>\n    <Compile Include=\"Framework\\AdminSecurity.cs\" />\n    <Compile Include=\"Framework\\PreApplicationStartCode.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"..\\CommonAssemblyInfo.cs\">\n      <Link>Properties\\CommonAssemblyInfo.cs</Link>\n    </Compile>\n    <Compile Include=\"Framework\\packages\\PackageExtensions.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\" />\n    <RazorSrcFiles Include=\"_Layout.cshtml\" />\n    <RazorSrcFiles Include=\"Logout.cshtml\" />\n    <RazorSrcFiles Include=\"Register.cshtml\" />\n    <RazorSrcFiles Include=\"Login.cshtml\" />\n    <RazorSrcFiles Include=\"_pagestart.cshtml\" />\n    <RazorSrcFiles Include=\"Default.cshtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"..\\CommonResources.resx\">\n      <Link>Common\\CommonResources.resx</Link>\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>CommonResources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n    <EmbeddedResource Include=\"Resources\\AdminResources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>AdminResources.Designer.cs</LastGenOutput>\n      <CustomToolNamespace>System.Web.WebPages.Administration</CustomToolNamespace>\n    </EmbeddedResource>\n    <EmbeddedResource Include=\"Resources\\PackageManagerResources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>PackageManagerResources.Designer.cs</LastGenOutput>\n      <CustomToolNamespace>System.Web.WebPages.Administration.PackageManager</CustomToolNamespace>\n    </EmbeddedResource>\n    <EmbeddedResource Include=\"Site.css\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"images\\error.png\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"images\\package.png\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\System.Web.WebPages.Deployment\\System.Web.WebPages.Deployment.csproj\">\n      <Project>{22BABB60-8F02-4027-AFFC-ACF069954536}</Project>\n      <Name>System.Web.WebPages.Deployment</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\WebMatrix.Data\\WebMatrix.Data.csproj\">\n      <Project>{4D39BAAF-8A96-473E-AB79-C8A341885137}</Project>\n      <Name>WebMatrix.Data</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.Helpers\\System.Web.Helpers.csproj\">\n      <Project>{9B7E3740-6161-4548-833C-4BBCA43B970E}</Project>\n      <Name>System.Web.Helpers</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.WebPages\\System.Web.WebPages.csproj\">\n      <Project>{76EFA9C5-8D7E-4FDF-B710-E20F8B6B00D2}</Project>\n      <Name>System.Web.WebPages</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\WebMatrix.WebData\\WebMatrix.WebData.csproj\">\n      <Project>{55A15F40-1435-4248-A7F2-2A146BB83586}</Project>\n      <Name>WebMatrix.WebData</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"images\\aspLogo.gif\" />\n    <EmbeddedResource Include=\"images\\tabon.gif\" />\n    <EmbeddedResource Include=\"images\\ok.png\" />\n    <EmbeddedResource Include=\"packages\\scripts\\PackageAction.js\" />\n    <EmbeddedResource Include=\"packages\\scripts\\Default.js\" />\n    <RazorSrcFiles Include=\"EnableInstructions.cshtml\">\n      <CustomToolNamespace>System.Web.WebPages.Administration.PackageManager</CustomToolNamespace>\n    </RazorSrcFiles>\n    <RazorSrcFiles Include=\"packages\\SourceFileInstructions.cshtml\">\n      <CustomToolNamespace>System.Web.WebPages.Administration.PackageManager</CustomToolNamespace>\n    </RazorSrcFiles>\n    <RazorSrcFiles Include=\"packages\\PackageSources.cshtml\">\n      <CustomToolNamespace>System.Web.WebPages.Administration.PackageManager</CustomToolNamespace>\n    </RazorSrcFiles>\n    <RazorSrcFiles Include=\"packages\\Install.cshtml\">\n      <CustomToolNamespace>System.Web.WebPages.Administration.PackageManager</CustomToolNamespace>\n    </RazorSrcFiles>\n    <RazorSrcFiles Include=\"packages\\Update.cshtml\">\n      <CustomToolNamespace>System.Web.WebPages.Administration.PackageManager</CustomToolNamespace>\n    </RazorSrcFiles>\n    <RazorSrcFiles Include=\"packages\\_Package.cshtml\">\n      <CustomToolNamespace>System.Web.WebPages.Administration.PackageManager</CustomToolNamespace>\n    </RazorSrcFiles>\n    <RazorSrcFiles Include=\"packages\\Default.cshtml\">\n      <CustomToolNamespace>System.Web.WebPages.Administration.PackageManager</CustomToolNamespace>\n    </RazorSrcFiles>\n    <EmbeddedResource Include=\"packages\\images\\error.png\" />\n    <EmbeddedResource Include=\"packages\\images\\package.png\" />\n    <EmbeddedResource Include=\"packages\\Site.css\" />\n    <RazorSrcFiles Include=\"packages\\Uninstall.cshtml\">\n      <CustomToolNamespace>System.Web.WebPages.Administration.PackageManager</CustomToolNamespace>\n    </RazorSrcFiles>\n    <RazorSrcFiles Include=\"packages\\_PackageDetails.cshtml\">\n      <CustomToolNamespace>System.Web.WebPages.Administration.PackageManager</CustomToolNamespace>\n    </RazorSrcFiles>\n    <RazorSrcFiles Include=\"packages\\_pagestart.cshtml\">\n      <CustomToolNamespace>System.Web.WebPages.Administration.PackageManager</CustomToolNamespace>\n    </RazorSrcFiles>\n    <RazorSrcFiles Include=\"packages\\_Layout.cshtml\">\n      <CustomToolNamespace>System.Web.WebPages.Administration.PackageManager</CustomToolNamespace>\n    </RazorSrcFiles>\n  </ItemGroup>\n  <ItemGroup>\n    <Folder Include=\"packages\\Resources\\\" />\n  </ItemGroup>\n  <ItemGroup>\n    <CodeAnalysisDictionary Include=\"..\\CodeAnalysisDictionary.xml\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  \n  <!-- Note: RazorGenerator.MsBuild uses Razor 3.0 \\ Mvc 5.0 for generating views. In the event we update the Mvc parser, we'll need to ensure this package references the updated Mvc build -->\n  <Import Project=\"..\\..\\packages\\RazorGenerator.MsBuild.2.2.0\\build\\RazorGenerator.MsBuild.targets\" Condition=\"Exists('..\\..\\packages\\RazorGenerator.MsBuild.2.2.0\\build\\RazorGenerator.MsBuild.targets')\" />\n</Project>"
  },
  {
    "path": "src/System.Web.WebPages.Administration/_Layout.cshtml",
    "content": "﻿@* Generator: WebPage *@\n\n@{\n    string title = Page.Title;\n}\n\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n   <head>\n      <title>@AdminResources.AdminModuleTitle@if (!title.IsEmpty()) { <text>- @title </text> }</title>\n      <link href=\"@Href(\"Site.css\")\" rel=\"stylesheet\" type=\"text/css\" />\n      @RenderSection(\"Head\", required: false)\n   </head>\n   <body>\n      <div id=\"page\">\n         <div id=\"header\" class=\"group\">\n            <h1 class=\"site-title\">\n                <img src=\"@Href(\"images/aspLogo.gif\")\" alt=\"@AdminResources.LogoLabel\" />\n                <span class=\"aspnet\">ASP.NET</span>&nbsp;@AdminResources.AdminModuleDisplayTitle\n            </h1>\n             <div id=\"settings\">\n                <span>\n                    @RenderSection(\"PageSettings\", required: false)\n                    &nbsp;\n                    @if (AdminSecurity.IsAuthenticated(Request)) {\n                        <a href=\"@Href(\"Logout\")\">@AdminResources.Logout</a>\n                    }\n                </span>\n             </div>\n           </div>\n           <div class=\"clear\"></div>\n           <div id=\"breadcrumbs\" class=\"group\">\n           <ul>\n           @{\n                var firstCrumb = true;\n                int current = 0;\n            }\n            @foreach(var item in Page.BreadCrumbs){\n                current++;\n                if(firstCrumb) {\n                    firstCrumb = false;\n                }\n                else {\n                    <li><span>&gt;</span></li>\n                }\n                <li @((current == Page.BreadCrumbs.Count) ? @Html.Raw(\"class=\\\"selected\\\"\") : null)>\n                <a href=\"@item.Item2\" title=\"@item.Item1\">@item.Item1</a>\n                </li>\n           }\n           </ul>\n\n        </div>\n        <div id=\"main\">\n            @{\n                string sectionTitle = Page.SectionTitle ?? title;\n            }\n            @if (!sectionTitle.IsEmpty()) {\n                <div class=\"page-title\">\n                    <h1>@sectionTitle</h1>\n                    @if (!String.IsNullOrEmpty(Page.Desc)) {\n                        <span>@Page.Desc</span>\n                    }\n                </div>\n            }          \n            @RenderBody()\n            <p />\n        </div>\n        <div id=\"footer\">\n            @RenderSection(\"Footer\", required: false)\n        </div>\n      </div>\n   </body>\n</html>"
  },
  {
    "path": "src/System.Web.WebPages.Administration/_pagestart.cshtml",
    "content": "﻿@* Generator: WebPage *@\n\n@{\n    // 404 if the admin page isn't available\n    if (!SiteAdmin.Available) {\n        Response.SetStatus(HttpStatusCode.NotFound);\n        return;\n    }\n       \n    AdminSecurity.Authorize(this);    \n}\n\n@{\n    // Set up layout values\n    var breadCrumbs = new List<Tuple<string, string>>();\n    if (SiteAdmin.Modules.Any()) {\n        breadCrumbs.Add(Tuple.Create(AdminResources.AdminHome, Href(SiteAdmin.AdminVirtualPath)));\n    }\n    PageData[\"BreadCrumbs\"] = breadCrumbs;\n    Layout = \"_Layout.cshtml\";  \n\n    \n    HtmlHelper.ValidationSummaryClass = \"message error\";\n    HtmlHelper.ValidationInputCssClassName = \"validation-error\";\n\n    // Force IE9 standards mode rendering\n    Response.AddHeader(\"X-UA-Compatible\", \"IE=Edge\");\n}\n\n\n"
  },
  {
    "path": "src/System.Web.WebPages.Administration/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Nuget.Core\" version=\"1.6.2\" targetFramework=\"net45\" />\n  <package id=\"RazorGenerator.MsBuild\" version=\"2.2.0\" targetFramework=\"net45\" />\n</packages>"
  },
  {
    "path": "src/System.Web.WebPages.Deployment/AppDomainHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\n\nnamespace System.Web.WebPages.Deployment\n{\n    internal static class AppDomainHelper\n    {\n        public static IDictionary<string, IEnumerable<string>> GetBinAssemblyReferences(string appPath, string configPath)\n        {\n            string binDirectory = Path.Combine(appPath, \"bin\");\n            if (!Directory.Exists(binDirectory))\n            {\n                return null;\n            }\n\n            AppDomain appDomain = null;\n            try\n            {\n                var appDomainSetup = new AppDomainSetup\n                {\n                    ApplicationBase = appPath,\n                    ConfigurationFile = configPath,\n                    PrivateBinPath = binDirectory,\n                };\n                appDomain = AppDomain.CreateDomain(typeof(AppDomainHelper).Namespace, AppDomain.CurrentDomain.Evidence, appDomainSetup);\n\n                var type = typeof(RemoteAssemblyLoader);\n                var instance = (RemoteAssemblyLoader)appDomain.CreateInstanceAndUnwrap(type.Assembly.FullName, type.FullName);\n\n                return Directory.EnumerateFiles(binDirectory, \"*.dll\")\n                    .ToDictionary(assemblyPath => assemblyPath,\n                                  assemblyPath => instance.GetReferences(assemblyPath));\n            }\n            finally\n            {\n                if (appDomain != null)\n                {\n                    AppDomain.Unload(appDomain);\n                }\n            }\n        }\n\n        private sealed class RemoteAssemblyLoader : MarshalByRefObject\n        {\n            [SuppressMessage(\"Microsoft.Performance\", \"CA1822:MarkMembersAsStatic\", Justification = \"Method needs to be instance level for cross domain invocation\"),\n             SuppressMessage(\"Microsoft.Reliability\", \"CA2001:AvoidCallingProblematicMethods\", MessageId = \"System.Reflection.Assembly.LoadFrom\",\n                 Justification = \"We want to load this specific assembly.\")]\n            public IEnumerable<string> GetReferences(string assemblyPath)\n            {\n                var assembly = Assembly.LoadFrom(assemblyPath);\n                return assembly.GetReferencedAssemblies()\n                    .Select(asmName => Assembly.Load(asmName.FullName).FullName)\n                    .Concat(new[] { assembly.FullName })\n                    .ToArray();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages.Deployment/AssemblyUtils.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\nusing System.Security;\nusing Microsoft.Internal.Web.Utils;\nusing Microsoft.Web.Infrastructure;\n\nnamespace System.Web.WebPages.Deployment\n{\n    internal static class AssemblyUtils\n    {\n        // Copied from AssemblyRefs.cs\n        private const string SharedLibPublicKey = \"31bf3856ad364e35\";\n\n        internal static readonly AssemblyName ThisAssemblyName = new AssemblyName(typeof(AssemblyUtils).Assembly.FullName);\n        internal static readonly Version WebPagesV1Version = new Version(1, 0, 0, 0);\n        private static readonly string _binFileName = Path.GetFileName(ThisAssemblyName.Name) + \".dll\";\n\n        // Special case MWI because it does not share the same assembly version as the rest of WebPages.\n        private static readonly Version _mwiVersion = new AssemblyName(typeof(InfrastructureHelper).Assembly.FullName).Version;\n\n        private static readonly AssemblyName _mwiAssemblyName = GetFullName(\"Microsoft.Web.Infrastructure\", _mwiVersion);\n\n        private static readonly AssemblyName[] _version1AssemblyList = new[]\n        {\n            _mwiAssemblyName,\n            GetFullName(\"System.Web.Razor\", WebPagesV1Version),\n            GetFullName(\"System.Web.Helpers\", WebPagesV1Version),\n            GetFullName(\"System.Web.WebPages\", WebPagesV1Version),\n            GetFullName(\"System.Web.WebPages.Administration\", WebPagesV1Version),\n            GetFullName(\"System.Web.WebPages.Razor\", WebPagesV1Version),\n            GetFullName(\"WebMatrix.Data\", WebPagesV1Version),\n            GetFullName(\"WebMatrix.WebData\", WebPagesV1Version)\n        };\n\n        private static readonly AssemblyName[] _versionCurrentAssemblyList = new[]\n        {\n            _mwiAssemblyName,\n            GetFullName(\"System.Web.Razor\", ThisAssemblyName.Version),\n            GetFullName(\"System.Web.Helpers\", ThisAssemblyName.Version),\n            GetFullName(\"System.Web.WebPages\", ThisAssemblyName.Version),\n            GetFullName(\"System.Web.WebPages.Administration\", ThisAssemblyName.Version),\n            GetFullName(\"System.Web.WebPages.Razor\", ThisAssemblyName.Version),\n            GetFullName(\"WebMatrix.Data\", ThisAssemblyName.Version),\n            GetFullName(\"WebMatrix.WebData\", ThisAssemblyName.Version)\n        };\n\n        internal static Version GetMaxWebPagesVersion()\n        {\n            return GetMaxWebPagesVersion(GetLoadedAssemblies());\n        }\n\n        internal static Version GetMaxWebPagesVersion(IEnumerable<AssemblyName> loadedAssemblies)\n        {\n            return GetWebPagesAssemblies(loadedAssemblies).Max(c => c.Version);\n        }\n\n        internal static bool IsVersionAvailable(Version version)\n        {\n            return IsVersionAvailable(GetLoadedAssemblies(), version);\n        }\n\n        internal static bool IsVersionAvailable(IEnumerable<AssemblyName> loadedAssemblies, Version version)\n        {\n            return GetWebPagesAssemblies(loadedAssemblies).Any(c => c.Version == version);\n        }\n\n        private static IEnumerable<AssemblyName> GetWebPagesAssemblies(IEnumerable<AssemblyName> loadedAssemblies)\n        {\n            return (from otherName in loadedAssemblies\n                    where NamesMatch(ThisAssemblyName, otherName, matchVersion: false)\n                    select otherName);\n        }\n\n        /// <summary>\n        /// Returns the version of a System.Web.WebPages.Deployment.dll if it is present in the bin and matches the name and \n        /// public key token of the current assembly.\n        /// </summary>\n        /// <returns>Version from bin if present, null otherwise.</returns>\n        internal static Version GetVersionFromBin(string binDirectory, IFileSystem fileSystem, Func<string, AssemblyName> getAssemblyNameThunk = null)\n        {\n            // If a version of the assembly is present both in the bin and the GAC, the GAC would win.\n            // To work around this, we'll look for a physical file on disk with the same name as the current assembly and load it to determine the version.\n            // Determine if the Deployment assembly is present in the bin\n            var assemblyInBin = Path.Combine(binDirectory, _binFileName);\n            if (fileSystem.FileExists(assemblyInBin))\n            {\n                try\n                {\n                    getAssemblyNameThunk = getAssemblyNameThunk ?? AssemblyName.GetAssemblyName;\n                    AssemblyName assemblyName = getAssemblyNameThunk(assemblyInBin);\n                    if (NamesMatch(ThisAssemblyName, assemblyName, matchVersion: false))\n                    {\n                        return assemblyName.Version;\n                    }\n                }\n                catch (BadImageFormatException)\n                {\n                    // Do nothing. \n                }\n                catch (SecurityException)\n                {\n                    // Do nothing\n                }\n                catch (FileLoadException)\n                {\n                    // Do nothing.\n                }\n            }\n            return null;\n        }\n\n        internal static bool NamesMatch(AssemblyName left, AssemblyName right, bool matchVersion)\n        {\n            return Equals(left.Name, right.Name) &&\n                   Equals(left.CultureInfo, right.CultureInfo) &&\n                   Enumerable.SequenceEqual(left.GetPublicKeyToken(), right.GetPublicKeyToken()) &&\n                   (!matchVersion || Equals(left.Version, right.Version));\n        }\n\n        internal static IEnumerable<AssemblyName> GetLoadedAssemblies()\n        {\n            return AppDomain.CurrentDomain.GetAssemblies()\n                .Select(GetAssemblyName)\n                .ToList();\n        }\n\n        internal static IEnumerable<AssemblyName> GetAssembliesForVersion(Version version)\n        {\n            if (version == WebPagesV1Version)\n            {\n                return _version1AssemblyList;\n            }\n            return _versionCurrentAssemblyList;\n        }\n\n        private static AssemblyName GetAssemblyName(Assembly assembly)\n        {\n            return new AssemblyName(assembly.FullName);\n        }\n\n        private static AssemblyName GetFullName(string name, Version version, string publicKeyToken)\n        {\n            return new AssemblyName(String.Format(CultureInfo.InvariantCulture,\n                                                  \"{0}, Version={1}, Culture=neutral, PublicKeyToken={2}\",\n                                                  name, version, publicKeyToken));\n        }\n\n        internal static AssemblyName GetFullName(string name, Version version)\n        {\n            return GetFullName(name, version, SharedLibPublicKey);\n        }\n\n        public static IDictionary<string, Version> GetAssembliesMatchingOtherVersions(IDictionary<string, IEnumerable<string>> references)\n        {\n            var webPagesAssemblies = AssemblyUtils.GetAssembliesForVersion(AssemblyUtils.ThisAssemblyName.Version);\n            if (references == null || webPagesAssemblies == null || !webPagesAssemblies.Any())\n            {\n                return new Dictionary<string, Version>(0);\n            }\n\n            var matchingVersions = from item in references\n                                   let matchedVersion = GetMatchingVersion(webPagesAssemblies, item.Value)\n                                   where matchedVersion != null\n                                   select new KeyValuePair<string, Version>(item.Key, matchedVersion);\n            return matchingVersions.ToDictionary(k => k.Key, k => k.Value);\n        }\n\n        private static Version GetMatchingVersion(IEnumerable<AssemblyName> webPagesAssemblies, IEnumerable<string> references)\n        {\n            // Return assemblies that match in name but not in version.\n            var matchingVersions = from webPagesAssembly in webPagesAssemblies\n                                   from referenceName in references\n                                   let referencedAssembly = new AssemblyName(referenceName)\n                                   where AssemblyUtils.NamesMatch(webPagesAssembly, referencedAssembly, matchVersion: false) && webPagesAssembly.Version != referencedAssembly.Version\n                                   select referencedAssembly.Version;\n            return matchingVersions.FirstOrDefault();\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages.Deployment/BuildManagerWrapper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Web.Compilation;\n\nnamespace System.Web.WebPages.Deployment\n{\n    internal sealed class BuildManagerWrapper : IBuildManager\n    {\n        /// <summary>\n        /// Reads a special cached file from %WindDir%\\Microsoft.NET\\Framework\\vx.x\\ASP.NET Temporary Files\\&lt;x&gt;\\&lt;y&gt;\\UserCache that is \n        /// available across AppDomain recycles.\n        /// </summary>\n        public Stream ReadCachedFile(string path)\n        {\n            return BuildManager.ReadCachedFile(path);\n        }\n\n        /// <summary>\n        /// Creates or opens a special cached file that is created under  %WindDir%\\Microsoft.NET\\Framework\\vx.x\\ASP.NET Temporary Files\\&lt;x&gt;\\&lt;y&gt;\\UserCache that is \n        /// available across AppDomain recycles.\n        /// </summary>\n        public Stream CreateCachedFile(string path)\n        {\n            return BuildManager.CreateCachedFile(path);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages.Deployment/Common/IFileSystem.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\n\nnamespace Microsoft.Internal.Web.Utils\n{\n    internal interface IFileSystem\n    {\n        bool FileExists(string path);\n\n        Stream ReadFile(string path);\n\n        Stream OpenFile(string path);\n\n        IEnumerable<string> EnumerateFiles(string root);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages.Deployment/Common/PhysicalFileSystem.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\n\nnamespace Microsoft.Internal.Web.Utils\n{\n    internal sealed class PhysicalFileSystem : IFileSystem\n    {\n        public bool FileExists(string path)\n        {\n            return File.Exists(path);\n        }\n\n        public Stream ReadFile(string path)\n        {\n            return File.OpenRead(path);\n        }\n\n        public Stream OpenFile(string path)\n        {\n            string directory = Path.GetDirectoryName(path);\n            EnsureDirectory(directory);\n            return File.OpenWrite(path);\n        }\n\n        public IEnumerable<string> EnumerateFiles(string path)\n        {\n            return Directory.EnumerateFiles(path);\n        }\n\n        private static void EnsureDirectory(string path)\n        {\n            if (!Directory.Exists(path))\n            {\n                Directory.CreateDirectory(path);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages.Deployment/GlobalSuppressions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n// This file is used by Code Analysis to maintain SuppressMessage \n// attributes that are applied to this project.\n// Project-level suppressions either have no target or are given \n// a specific target and scoped to a namespace, type, member, etc.\n//\n// To add a suppression to this file, right-click the message in the \n// Error List, point to \"Suppress Message(s)\", and click \n// \"In Project Suppression File\".\n// You do not need to add suppressions to this file manually.\n\nusing System.Diagnostics.CodeAnalysis;\n\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"System.Web.WebPages.Deployment\", Justification = \"Namespace is present to match assembly name\")]\n"
  },
  {
    "path": "src/System.Web.WebPages.Deployment/IBuildManager.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\n\nnamespace System.Web.WebPages.Deployment\n{\n    internal interface IBuildManager\n    {\n        Stream CreateCachedFile(string fileName);\n\n        Stream ReadCachedFile(string fileName);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages.Deployment/PreApplicationStartCode.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq;\nusing System.Reflection;\nusing System.Web.Caching;\nusing System.Web.Compilation;\nusing System.Web.Configuration;\nusing System.Web.WebPages.Deployment.Resources;\nusing Microsoft.Internal.Web.Utils;\nusing Microsoft.Web.Infrastructure;\n\nnamespace System.Web.WebPages.Deployment\n{\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class PreApplicationStartCode\n    {\n        /// <summary>\n        /// Key used to indicate to tooling that the compile exception we throw to refresh the app domain originated from us so that they can deal with it correctly. \n        /// </summary>\n        private const string ToolingIndicatorKey = \"WebPages.VersionChange\";\n\n        // NOTE: Do not add public fields, methods, or other members to this class.\n        // This class does not show up in Intellisense so members on it will not be\n        // discoverable by users. Place new members on more appropriate classes that\n        // relate to the public API (for example, a LoginUrl property should go on a\n        // membership-related class).\n        private static readonly IFileSystem _physicalFileSystem = new PhysicalFileSystem();\n\n        private static bool _startWasCalled;\n\n        public static void Start()\n        {\n            // Even though ASP.NET will only call each PreAppStart once, we sometimes internally call one PreAppStart from \n            // another PreAppStart to ensure that things get initialized in the right order. ASP.NET does not guarantee the \n            // order so we have to guard against multiple calls.\n            // All Start calls are made on same thread, so no lock needed here.\n\n            if (_startWasCalled)\n            {\n                return;\n            }\n            _startWasCalled = true;\n\n            StartCore();\n        }\n\n        internal static bool StartCore()\n        {\n            var buildManager = new BuildManagerWrapper();\n            NameValueCollection appSettings = WebConfigurationManager.AppSettings;\n            Action<Version> loadWebPages = LoadWebPages;\n            Action registerForChangeNotification = RegisterForChangeNotifications;\n            IEnumerable<AssemblyName> loadedAssemblies = AssemblyUtils.GetLoadedAssemblies();\n\n            return StartCore(_physicalFileSystem, HttpRuntime.AppDomainAppPath, HttpRuntime.BinDirectory, appSettings, loadedAssemblies,\n                             buildManager, loadWebPages, registerForChangeNotification);\n        }\n\n        // Adds Parameter for unit tests\n        internal static bool StartCore(IFileSystem fileSystem, string appDomainAppPath, string binDirectory, NameValueCollection appSettings, IEnumerable<AssemblyName> loadedAssemblies,\n                                       IBuildManager buildManager, Action<Version> loadWebPages, Action registerForChangeNotification, Func<string, AssemblyName> getAssemblyNameThunk = null)\n        {\n            if (WebPagesDeployment.IsExplicitlyDisabled(appSettings))\n            {\n                // If WebPages is explicitly disabled, exit.\n                Debug.WriteLine(\"WebPages Bootstrapper v{0}: not loading WebPages since it is disabled\", AssemblyUtils.ThisAssemblyName.Version);\n                return false;\n            }\n\n            Version maxWebPagesVersion = AssemblyUtils.GetMaxWebPagesVersion(loadedAssemblies);\n            Debug.Assert(maxWebPagesVersion != null, \"Function must return some max value.\");\n            if (AssemblyUtils.ThisAssemblyName.Version != maxWebPagesVersion)\n            {\n                // Always let the highest version determine what needs to be done. This would make future proofing simpler.\n                Debug.WriteLine(\"WebPages Bootstrapper v{0}: Higher version v{1} is available.\", AssemblyUtils.ThisAssemblyName.Version, maxWebPagesVersion);\n                return false;\n            }\n\n            var webPagesEnabled = WebPagesDeployment.IsEnabled(fileSystem, appDomainAppPath, appSettings);\n            Version binVersion = AssemblyUtils.GetVersionFromBin(binDirectory, fileSystem, getAssemblyNameThunk);\n            Version configVersion = WebPagesDeployment.GetVersionFromConfig(appSettings);\n            Version version = configVersion ?? binVersion ?? AssemblyUtils.WebPagesV1Version;\n\n            // Asserts to ensure unit tests are set up correctly. So essentially, we're unit testing the unit tests. \n            Debug.Assert(version != null, \"GetVersion always returns a version\");\n            Debug.Assert(binVersion == null || binVersion <= maxWebPagesVersion, \"binVersion cannot be higher than max version\");\n\n            if ((binVersion != null) && (binVersion != version))\n            {\n                // Determine if there's a version conflict. A conflict could occur if there's a version specified in the bin which is different from the version specified in the \n                // config that is different.\n                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, ConfigurationResources.WebPagesVersionConflict, version, binVersion));\n            }\n            else if (binVersion != null)\n            {\n                // The rest of the code is only meant to be executed if we are executing from the GAC.\n                // If a version is bin deployed, we don't need to do anything special to bootstrap.\n                return false;\n            }\n            else if (!webPagesEnabled)\n            {\n                Debug.WriteLine(\"WebPages Bootstrapper v{0}: WebPages not enabled, registering for change notifications\", AssemblyUtils.ThisAssemblyName.Version);\n                // Register for change notifications under the application root\n                registerForChangeNotification();\n                return false;\n            }\n            else if (!AssemblyUtils.IsVersionAvailable(loadedAssemblies, version))\n            {\n                if (version == AssemblyUtils.WebPagesV1Version && configVersion == null && binVersion == null)\n                {\n                    // No version was specified. We're implicitly assuming that the site is a v1 site. However, the user does not have V1 binaries available. \n                    throw new InvalidOperationException(ConfigurationResources.WebPagesImplicitVersionFailure);\n                }\n                else \n                {\n                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, ConfigurationResources.WebPagesVersionNotFound, version, AssemblyUtils.ThisAssemblyName.Version));\n                }\n            }\n\n            Debug.WriteLine(\"WebPages Bootstrapper v{0}: loading version {1}, loading WebPages\", AssemblyUtils.ThisAssemblyName.Version, version);\n            // If the version the application was compiled earlier was different, invalidate compilation results by adding a file to the bin.\n            InvalidateCompilationResultsIfVersionChanged(buildManager, fileSystem, binDirectory, version);\n            loadWebPages(version);\n            return true;\n        }\n\n        /// <summary>\n        /// WebPages stores the version to be compiled against in AppSettings as &gt;add key=\"webpages:version\" value=\"1.0\" /&lt;. \n        /// Changing values AppSettings does not cause recompilation therefore we could run into a state where we have files compiled against v1 but the application is \n        /// currently v2.\n        /// </summary>\n        private static void InvalidateCompilationResultsIfVersionChanged(IBuildManager buildManager, IFileSystem fileSystem, string binDirectory, Version currentVersion)\n        {\n            Version previousVersion = WebPagesDeployment.GetPreviousRuntimeVersion(buildManager);\n\n            // Persist the current version number in BuildManager's cached file\n            WebPagesDeployment.PersistRuntimeVersion(buildManager, currentVersion);\n\n            if (previousVersion == null)\n            {\n                // Do nothing.\n            }\n            else if (previousVersion != currentVersion)\n            {\n                // If the previous runtime version is different, perturb the bin directory so that it forces recompilation.\n                WebPagesDeployment.ForceRecompile(fileSystem, binDirectory);\n                var httpCompileException = new HttpCompileException(ConfigurationResources.WebPagesVersionChanges);\n                // Indicator for tooling\n                httpCompileException.Data[ToolingIndicatorKey] = true;\n                throw httpCompileException;\n            }\n        }\n\n        // Copied from xsp\\System\\Web\\Compilation\\BuildManager.cs\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Copied from System.Web.dll\")]\n        internal static ICollection<MethodInfo> GetPreStartInitMethodsFromAssemblyCollection(IEnumerable<Assembly> assemblies)\n        {\n            List<MethodInfo> methods = new List<MethodInfo>();\n            foreach (Assembly assembly in assemblies)\n            {\n                PreApplicationStartMethodAttribute[] attributes = null;\n                try\n                {\n                    attributes = (PreApplicationStartMethodAttribute[])assembly.GetCustomAttributes(typeof(PreApplicationStartMethodAttribute), inherit: true);\n                }\n                catch\n                {\n                    // GetCustomAttributes invokes the constructors of the attributes, so it is possible that they might throw unexpected exceptions.\n                    // (Dev10 bug 831981)\n                }\n\n                if (attributes != null && attributes.Length != 0)\n                {\n                    Debug.Assert(attributes.Length == 1);\n                    PreApplicationStartMethodAttribute attribute = attributes[0];\n                    Debug.Assert(attribute != null);\n\n                    MethodInfo method = null;\n                    // Ensure the Type on the attribute is in the same assembly as the attribute itself\n                    if (attribute.Type != null && !String.IsNullOrEmpty(attribute.MethodName) && attribute.Type.Assembly == assembly)\n                    {\n                        method = FindPreStartInitMethod(attribute.Type, attribute.MethodName);\n                    }\n\n                    if (method != null)\n                    {\n                        methods.Add(method);\n                    }\n\n                    // No-op if the attribute is invalid\n                    /*\n                    else {\n                        throw new HttpException(SR.GetString(SR.Invalid_PreApplicationStartMethodAttribute_value,\n                            assembly.FullName,\n                            (attribute.Type != null ? attribute.Type.FullName : String.Empty),\n                            attribute.MethodName));\n                    }\n                    */\n                }\n            }\n            return methods;\n        }\n\n        // Copied from xsp\\System\\Web\\Compilation\\BuildManager.cs\n        internal static MethodInfo FindPreStartInitMethod(Type type, string methodName)\n        {\n            Debug.Assert(type != null);\n            Debug.Assert(!String.IsNullOrEmpty(methodName));\n            MethodInfo method = null;\n            if (type.IsPublic)\n            {\n                // Verify that type is public to avoid allowing internal code execution. This implementation will not match\n                // nested public types.\n                method = type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,\n                                        binder: null,\n                                        types: Type.EmptyTypes,\n                                        modifiers: null);\n            }\n            return method;\n        }\n\n        [SuppressMessage(\"Microsoft.Reliability\", \"CA2000:Dispose objects before losing scope\", Justification = \"The cache disposes of the dependency\")]\n        private static void RegisterForChangeNotifications()\n        {\n            string physicalPath = HttpRuntime.AppDomainAppPath;\n\n            CacheDependency cacheDependency = new CacheDependency(physicalPath, DateTime.UtcNow);\n            var key = WebPagesDeployment.CacheKeyPrefix + physicalPath;\n\n            HttpRuntime.Cache.Insert(key, physicalPath, cacheDependency,\n                                     Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,\n                                     CacheItemPriority.NotRemovable, new CacheItemRemovedCallback(OnChanged));\n        }\n\n        private static void OnChanged(string key, object value, CacheItemRemovedReason reason)\n        {\n            // Only handle case when the dependency has changed.\n            if (reason != CacheItemRemovedReason.DependencyChanged)\n            {\n                return;\n            }\n\n            // Scan the app root for a webpages file\n            if (WebPagesDeployment.AppRootContainsWebPagesFile(_physicalFileSystem, HttpRuntime.AppDomainAppPath))\n            {\n                // Unload the app domain so we register plan9 when the app restarts\n                InfrastructureHelper.UnloadAppDomain();\n            }\n            else\n            {\n                // We need to re-register since the item was removed from the cache\n                RegisterForChangeNotifications();\n            }\n        }\n\n        private static void LoadWebPages(Version version)\n        {\n            IEnumerable<AssemblyName> assemblyList = AssemblyUtils.GetAssembliesForVersion(version);\n            var assemblies = assemblyList.Select(LoadAssembly);\n\n            foreach (var asm in assemblies)\n            {\n                BuildManager.AddReferencedAssembly(asm);\n            }\n\n            foreach (var m in GetPreStartInitMethodsFromAssemblyCollection(assemblies))\n            {\n                m.Invoke(null, null);\n            }\n        }\n\n        private static Assembly LoadAssembly(AssemblyName name)\n        {\n            return Assembly.Load(name);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages.Deployment/Properties/AssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Web;\nusing System.Web.WebPages.Deployment;\n\n// General Information about an assembly is controlled through the following \n// set of attributes. Change these attribute values to modify the information\n// associated with an assembly.\n\n[assembly: AssemblyTitle(\"System.Web.WebPages.Deployment\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: InternalsVisibleTo(\"System.Web.WebPages.Deployment.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n[assembly: PreApplicationStartMethod(typeof(PreApplicationStartCode), \"Start\")]\n"
  },
  {
    "path": "src/System.Web.WebPages.Deployment/Resources/ConfigurationResources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.269\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace System.Web.WebPages.Deployment.Resources {\n    using System;\n    \n    \n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class ConfigurationResources {\n        \n        private static global::System.Resources.ResourceManager resourceMan;\n        \n        private static global::System.Globalization.CultureInfo resourceCulture;\n        \n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal ConfigurationResources() {\n        }\n        \n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"System.Web.WebPages.Deployment.Resources.ConfigurationResources\", typeof(ConfigurationResources).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n        \n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &quot;InstallPath&quot; name was not found in the Web Pages registry key &quot;{0}&quot;..\n        /// </summary>\n        internal static string InstallPathNotFound {\n            get {\n                return ResourceManager.GetString(\"InstallPathNotFound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Could not determine which version of ASP.NET Web Pages to use.\n        ///\n        ///In order to use this site, specify a version in the site’s web.config file. For more information, see the following article on the Microsoft support site: http://go.microsoft.com/fwlink/?LinkId=254126.\n        /// </summary>\n        internal static string WebPagesImplicitVersionFailure {\n            get {\n                return ResourceManager.GetString(\"WebPagesImplicitVersionFailure\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The Web Pages registry key &quot;{0}&quot; does not exist..\n        /// </summary>\n        internal static string WebPagesRegistryKeyDoesNotExist {\n            get {\n                return ResourceManager.GetString(\"WebPagesRegistryKeyDoesNotExist\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Changes were detected in the Web Pages runtime version that require your application to be recompiled. Refresh your browser window to continue..\n        /// </summary>\n        internal static string WebPagesVersionChanges {\n            get {\n                return ResourceManager.GetString(\"WebPagesVersionChanges\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Conflicting versions of ASP.NET Web Pages detected: specified version is &quot;{0}&quot;, but the version in bin is &quot;{1}&quot;. To continue, remove files from the application&apos;s bin directory or remove the version specification in web.config..\n        /// </summary>\n        internal static string WebPagesVersionConflict {\n            get {\n                return ResourceManager.GetString(\"WebPagesVersionConflict\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Specified Web Pages version &quot;{0}&quot; could not be found. Update your web.config to specify a different version. Current version: &quot;{1}&quot;..\n        /// </summary>\n        internal static string WebPagesVersionNotFound {\n            get {\n                return ResourceManager.GetString(\"WebPagesVersionNotFound\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages.Deployment/Resources/ConfigurationResources.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"InstallPathNotFound\" xml:space=\"preserve\">\n    <value>The \"InstallPath\" name was not found in the Web Pages registry key \"{0}\".</value>\n  </data>\n  <data name=\"WebPagesImplicitVersionFailure\" xml:space=\"preserve\">\n    <value>Could not determine which version of ASP.NET Web Pages to use.\n\nIn order to use this site, specify a version in the site’s web.config file. For more information, see the following article on the Microsoft support site: http://go.microsoft.com/fwlink/?LinkId=254126</value>\n  </data>\n  <data name=\"WebPagesRegistryKeyDoesNotExist\" xml:space=\"preserve\">\n    <value>The Web Pages registry key \"{0}\" does not exist.</value>\n  </data>\n  <data name=\"WebPagesVersionChanges\" xml:space=\"preserve\">\n    <value>Changes were detected in the Web Pages runtime version that require your application to be recompiled. Refresh your browser window to continue.</value>\n  </data>\n  <data name=\"WebPagesVersionConflict\" xml:space=\"preserve\">\n    <value>Conflicting versions of ASP.NET Web Pages detected: specified version is \"{0}\", but the version in bin is \"{1}\". To continue, remove files from the application's bin directory or remove the version specification in web.config.</value>\n  </data>\n  <data name=\"WebPagesVersionNotFound\" xml:space=\"preserve\">\n    <value>Specified Web Pages version \"{0}\" could not be found. Update your web.config to specify a different version. Current version: \"{1}\".</value>\n  </data>\n</root>"
  },
  {
    "path": "src/System.Web.WebPages.Deployment/System.Web.WebPages.Deployment.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{22BABB60-8F02-4027-AFFC-ACF069954536}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <RootNamespace>System.Web.WebPages.Deployment</RootNamespace>\n    <AssemblyName>System.Web.WebPages.Deployment</AssemblyName>\n    <DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>\n    <RunCodeAnalysis>$(CodeAnalysis)</RunCodeAnalysis>\n    <CodeAnalysisRuleSet>..\\Strict.ruleset</CodeAnalysisRuleSet>\n    <DefineConstants>$(DefineConstants);ASPNETWEBPAGES</DefineConstants>\n    <NoWarn>1591</NoWarn>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Microsoft.Web.Infrastructure.1.0.0.0\\lib\\net40\\Microsoft.Web.Infrastructure.dll</HintPath>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.configuration\" />\n    <Reference Include=\"System.Web\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\CommonAssemblyInfo.cs\">\n      <Link>Properties\\CommonAssemblyInfo.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\CommonResources.Designer.cs\">\n      <Link>Common\\CommonResources.Designer.cs</Link>\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>CommonResources.resx</DependentUpon>\n    </Compile>\n    <Compile Include=\"..\\GlobalSuppressions.cs\">\n      <Link>Common\\GlobalSuppressions.cs</Link>\n    </Compile>\n    <Compile Include=\"AppDomainHelper.cs\" />\n    <Compile Include=\"AssemblyUtils.cs\" />\n    <Compile Include=\"BuildManagerWrapper.cs\" />\n    <Compile Include=\"Common\\IFileSystem.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"Common\\PhysicalFileSystem.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"GlobalSuppressions.cs\" />\n    <Compile Include=\"IBuildManager.cs\" />\n    <Compile Include=\"Resources\\ConfigurationResources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>ConfigurationResources.resx</DependentUpon>\n    </Compile>\n    <Compile Include=\"WebPagesDeployment.cs\" />\n    <Compile Include=\"PreApplicationStartCode.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"..\\CommonResources.resx\">\n      <Link>Common\\CommonResources.resx</Link>\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>CommonResources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n    <EmbeddedResource Include=\"Resources\\ConfigurationResources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>ConfigurationResources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n  </ItemGroup>\n  <ItemGroup>\n    <CodeAnalysisDictionary Include=\"..\\CodeAnalysisDictionary.xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n</Project>"
  },
  {
    "path": "src/System.Web.WebPages.Deployment/WebPagesDeployment.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.ComponentModel;\nusing System.Configuration;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\nusing System.Web.Configuration;\nusing System.Web.Hosting;\nusing System.Web.WebPages.Deployment.Resources;\nusing Microsoft.Internal.Web.Utils;\nusing Microsoft.Win32;\n\nnamespace System.Web.WebPages.Deployment\n{\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class WebPagesDeployment\n    {\n        private const string AppSettingsVersionKey = \"webpages:Version\";\n        private const string AppSettingsEnabledKey = \"webpages:Enabled\";\n\n        /// <summary>\n        /// File name for a temporary file that we drop in bin to force recompilation.\n        /// </summary>\n        private const string ForceRecompilationFile = \"WebPagesRecompilation.deleteme\";\n\n        private const string WebPagesRegistryKey = @\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\ASP.NET Web Pages\\v{0}.{1}\";\n        internal static readonly string CacheKeyPrefix = \"__System.Web.WebPages.Deployment__\";\n        private static readonly string[] _webPagesExtensions = new[] { \".cshtml\", \".vbhtml\" };\n        private static readonly object _installPathNotFound = new object();\n        private static readonly IFileSystem _fileSystem = new PhysicalFileSystem();\n\n        /// <param name=\"path\">Physical or virtual path to a directory where we need to determine the version of WebPages to be used.</param>\n        /// <remarks>\n        /// In a non-hosted scenario, this method would only look at a web.config that is present at the current path. Any config settings at an\n        /// ancestor directory would not be considered.\n        /// If we are unable to determine a version, we would assume that this is a v1 app.\n        /// </remarks>\n        public static Version GetVersionWithoutEnabledCheck(string path)\n        {\n            return GetVersionWithoutEnabledCheckInternal(path, AssemblyUtils.WebPagesV1Version);\n        }\n\n        public static Version GetExplicitWebPagesVersion(string path)\n        {\n            return GetVersionWithoutEnabledCheckInternal(path, defaultVersion: null);\n        }\n\n        [Obsolete(\"This method is obsolete and is meant for legacy code. Use GetVersionWithoutEnabled instead.\")]\n        public static Version GetVersion(string path)\n        {\n            return GetObsoleteVersionInternal(path, GetAppSettings(path), new PhysicalFileSystem());\n        }\n\n        /// <remarks>\n        /// This is meant to test an obsolete method. Don't use this!\n        /// </remarks>\n        internal static Version GetObsoleteVersionInternal(string path, NameValueCollection configuration, IFileSystem fileSystem)\n        {\n            if (String.IsNullOrEmpty(path))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"path\");\n            }\n\n            var binDirectory = GetBinDirectory(path);\n            var binVersion = AssemblyUtils.GetVersionFromBin(binDirectory, _fileSystem);\n            var version = GetVersionInternal(configuration, binVersion, defaultVersion: null);\n\n            if (version != null)\n            {\n                // If a webpages version is available in config or bin, return it.\n                return version;\n            }\n            else if (AppRootContainsWebPagesFile(fileSystem, path))\n            {\n                // If the path points to a WebPages site, return v1 as a fixed version.\n                return AssemblyUtils.WebPagesV1Version;\n            }\n            return null;\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Justification = \"This operation might be expensive since it has to reflect over Assembly names.\")]\n        public static Version GetMaxVersion()\n        {\n            return AssemblyUtils.GetMaxWebPagesVersion();\n        }\n\n        /// <summary>\n        /// Determines if Asp.Net Web Pages is enabled.\n        /// Web Pages is enabled if there's a webPages:Enabled key in AppSettings is set to \"true\" or if there's a cshtml file in the current path\n        /// and the key is not present.\n        /// </summary>\n        /// <param name=\"path\">The path at which to determine if web pages is enabled.</param>\n        /// <remarks>\n        /// In a non-hosted scenario, this method would only look at a web.config that is present at the current path. Any config settings at an\n        /// ancestor directory would not be considered.\n        /// </remarks>\n        public static bool IsEnabled(string path)\n        {\n            if (String.IsNullOrEmpty(path))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"path\");\n            }\n\n            return IsEnabled(_fileSystem, path, GetAppSettings(path));\n        }\n\n        /// <remarks>\n        /// In a non-hosted scenario, this method would only look at a web.config that is present at the current path. Any config settings at an\n        /// ancestor directory would not be considered.\n        /// </remarks>\n        public static bool IsExplicitlyDisabled(string path)\n        {\n            if (String.IsNullOrEmpty(path))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"path\");\n            }\n            return IsExplicitlyDisabled(GetAppSettings(path));\n        }\n\n        [EditorBrowsable(EditorBrowsableState.Never)]\n        public static IDictionary<string, Version> GetIncompatibleDependencies(string appPath)\n        {\n            if (String.IsNullOrEmpty(appPath))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"appPath\");\n            }\n            var configFilePath = Path.Combine(appPath, \"web.config\");\n\n            var assemblyReferences = AppDomainHelper.GetBinAssemblyReferences(appPath, configFilePath);\n            return AssemblyUtils.GetAssembliesMatchingOtherVersions(assemblyReferences);\n        }\n\n        internal static bool IsExplicitlyDisabled(NameValueCollection appSettings)\n        {\n            bool? enabled = GetEnabled(appSettings);\n            return enabled.HasValue && enabled.Value == false;\n        }\n\n        internal static bool IsEnabled(IFileSystem fileSystem, string path, NameValueCollection appSettings)\n        {\n            bool? enabled = GetEnabled(appSettings);\n            if (!enabled.HasValue)\n            {\n                return AppRootContainsWebPagesFile(fileSystem, path);\n            }\n            return enabled.Value;\n        }\n\n        /// <summary>\n        /// Returns the value for webPages:Enabled AppSetting value in web.config.\n        /// </summary>\n        private static bool? GetEnabled(NameValueCollection appSettings)\n        {\n            string enabledSetting = appSettings.Get(AppSettingsEnabledKey);\n            if (String.IsNullOrEmpty(enabledSetting))\n            {\n                return null;\n            }\n            else\n            {\n                return Boolean.Parse(enabledSetting);\n            }\n        }\n\n        /// <summary>\n        /// Returns the version of WebPages to be used for a specified path.\n        /// </summary>\n        /// <remarks>\n        /// This method would always returns a value regardless of web pages is explicitly disabled (via config) or implicitly disabled (by virtue of not having a cshtml file) at \n        /// the specified path.\n        /// </remarks>\n        internal static Version GetVersionInternal(NameValueCollection appSettings, Version binVersion, Version defaultVersion)\n        {\n            // Return version values with the following precedence: \n            // 1) Version in config\n            // 2) Version in bin\n            // 3) defaultVersion.\n            return GetVersionFromConfig(appSettings) ?? binVersion ?? defaultVersion;\n        }\n\n        private static Version GetVersionWithoutEnabledCheckInternal(string path, Version defaultVersion)\n        {\n            if (String.IsNullOrEmpty(path))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"path\");\n            }\n\n            var binDirectory = GetBinDirectory(path);\n            var binVersion = AssemblyUtils.GetVersionFromBin(binDirectory, _fileSystem);\n\n            return GetVersionInternal(GetAppSettings(path), binVersion, defaultVersion);\n        }\n\n        /// <summary>\n        /// Gets full path to a folder that contains ASP.NET WebPages assemblies for a given version. Used by\n        /// WebMatrix and Visual Studio so they know what to copy to an app's Bin folder or deploy to a hoster. \n        /// </summary>\n        public static string GetAssemblyPath(Version version)\n        {\n            if (version == null)\n            {\n                throw new ArgumentNullException(\"version\");\n            }\n\n            string webPagesRegistryKey = String.Format(CultureInfo.InvariantCulture, WebPagesRegistryKey, version.Major, version.Minor);\n\n            object installPath = Registry.GetValue(webPagesRegistryKey, \"InstallPath\", _installPathNotFound);\n\n            if (installPath == null)\n            {\n                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,\n                                                                  ConfigurationResources.WebPagesRegistryKeyDoesNotExist, webPagesRegistryKey));\n            }\n            else if (installPath == _installPathNotFound)\n            {\n                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,\n                                                                  ConfigurationResources.InstallPathNotFound, webPagesRegistryKey));\n            }\n\n            return Path.Combine((string)installPath, \"Assemblies\");\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Justification = \"This operation might be expensive since it has to reflect over Assembly names.\")]\n        public static IEnumerable<AssemblyName> GetWebPagesAssemblies()\n        {\n            return AssemblyUtils.GetAssembliesForVersion(AssemblyUtils.ThisAssemblyName.Version);\n        }\n\n        private static NameValueCollection GetAppSettings(string path)\n        {\n            if (path.StartsWith(\"~/\", StringComparison.Ordinal))\n            {\n                // Path is virtual, assume we're hosted\n                return (NameValueCollection)WebConfigurationManager.GetSection(\"appSettings\", path);\n            }\n            else\n            {\n                // Path is physical, map it to an application\n                WebConfigurationFileMap fileMap = new WebConfigurationFileMap();\n                fileMap.VirtualDirectories.Add(\"/\", new VirtualDirectoryMapping(path, true));\n                var config = WebConfigurationManager.OpenMappedWebConfiguration(fileMap, \"/\");\n\n                var appSettingsSection = config.AppSettings;\n                var appSettings = new NameValueCollection();\n\n                foreach (KeyValueConfigurationElement element in appSettingsSection.Settings)\n                {\n                    appSettings.Add(element.Key, element.Value);\n                }\n                return appSettings;\n            }\n        }\n\n        internal static Version GetVersionFromConfig(NameValueCollection appSettings)\n        {\n            string version = appSettings.Get(AppSettingsVersionKey);\n            // Version will be null if the config section is registered but not present in app web.config.\n            if (!String.IsNullOrEmpty(version))\n            {\n                // Build and Revision are optional in config but required by Fusion, so we set them to 0 if unspecified in config.\n                // Valid in config: \"1.0\", \"1.0.0\", \"1.0.0.0\"\n                var fullVersion = new Version(version);\n                if (fullVersion.Build == -1 || fullVersion.Revision == -1)\n                {\n                    fullVersion = new Version(fullVersion.Major, fullVersion.Minor,\n                                              fullVersion.Build == -1 ? 0 : fullVersion.Build,\n                                              fullVersion.Revision == -1 ? 0 : fullVersion.Revision);\n                }\n                return fullVersion;\n            }\n            return null;\n        }\n\n        internal static bool AppRootContainsWebPagesFile(IFileSystem fileSystem, string path)\n        {\n            var files = fileSystem.EnumerateFiles(path);\n            return files.Any(IsWebPagesFile);\n        }\n\n        private static bool IsWebPagesFile(string file)\n        {\n            var extension = Path.GetExtension(file);\n            return _webPagesExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase);\n        }\n\n        /// <summary>\n        /// HttpRuntime.BinDirectory is unavailable in design time and throws if we try to access it. To workaround this, if we aren't hosted,\n        /// we will assume that the path that was passed to us is the application root.\n        /// </summary>\n        /// <param name=\"path\"></param>\n        /// <returns></returns>\n        private static string GetBinDirectory(string path)\n        {\n            if (HostingEnvironment.IsHosted)\n            {\n                return HttpRuntime.BinDirectory;\n            }\n            return Path.Combine(path, \"bin\");\n        }\n\n        /// <summary>\n        /// Reads a previously persisted version number from build manager's cached directory.\n        /// </summary>\n        /// <returns>Null if a previous version number does not exist or is not a valid version number, read version number otherwise.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We never want to throw an exception from this method.\")]\n        internal static Version GetPreviousRuntimeVersion(IBuildManager buildManagerFileSystem)\n        {\n            string fileName = GetCachedFileName();\n            try\n            {\n                Stream stream = buildManagerFileSystem.ReadCachedFile(fileName);\n                if (stream == null)\n                {\n                    return null;\n                }\n\n                using (StreamReader reader = new StreamReader(stream))\n                {\n                    string text = reader.ReadLine();\n                    Version version;\n                    if (Version.TryParse(text, out version))\n                    {\n                        return version;\n                    }\n                }\n            }\n            catch\n            {\n            }\n            return null;\n        }\n\n        /// <summary>\n        /// Persists the version number in a file under the build manager's cached directory.\n        /// </summary>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We never want to throw an exception from this method.\")]\n        internal static void PersistRuntimeVersion(IBuildManager buildManager, Version version)\n        {\n            string fileName = GetCachedFileName();\n            try\n            {\n                Stream stream = buildManager.CreateCachedFile(fileName);\n                using (var writer = new StreamWriter(stream))\n                {\n                    writer.WriteLine(version.ToString());\n                }\n            }\n            catch\n            {\n            }\n        }\n\n        /// <summary>\n        /// Forces recompilation of the application by dropping a file under bin.\n        /// </summary>\n        /// <param name=\"fileSystem\">File system instance used to write a file to bin directory.</param>\n        /// <param name=\"binDirectory\">Path to bin directory of the application</param>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"We never want to throw an exception from this method.\")]\n        internal static void ForceRecompile(IFileSystem fileSystem, string binDirectory)\n        {\n            var fileToWrite = Path.Combine(binDirectory, ForceRecompilationFile);\n            try\n            {\n                // Note: We should use BuildManager::ForceRecompile once that method makes it into System.Web.\n                using (var writer = new StreamWriter(fileSystem.OpenFile(fileToWrite)))\n                {\n                    writer.WriteLine();\n                }\n            }\n            catch\n            {\n            }\n        }\n\n        /// <summary>\n        /// Name of the the temporary file used by BuildManager.CreateCachedFile / BuildManager.ReadCachedFile where we cache WebPages's version number. \n        /// </summary>\n        /// <returns></returns>\n        private static string GetCachedFileName()\n        {\n            return typeof(WebPagesDeployment).Namespace;\n        }\n\n        private static string RemoveTrailingSlash(string path)\n        {\n            if (!String.IsNullOrEmpty(path))\n            {\n                path = path.TrimEnd(Path.DirectorySeparatorChar);\n            }\n            return path;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages.Deployment/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Microsoft.Web.Infrastructure\" version=\"1.0.0.0\" targetFramework=\"net45\" />\n</packages>"
  },
  {
    "path": "src/System.Web.WebPages.Razor/AssemblyBuilderWrapper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.Web.Compilation;\n\nnamespace System.Web.WebPages.Razor\n{\n    internal sealed class AssemblyBuilderWrapper : IAssemblyBuilder\n    {\n        public AssemblyBuilderWrapper(AssemblyBuilder builder)\n        {\n            if (builder == null)\n            {\n                throw new ArgumentNullException(\"builder\");\n            }\n\n            InnerBuilder = builder;\n        }\n\n        internal AssemblyBuilder InnerBuilder { get; set; }\n\n        public void AddCodeCompileUnit(BuildProvider buildProvider, CodeCompileUnit compileUnit)\n        {\n            InnerBuilder.AddCodeCompileUnit(buildProvider, compileUnit);\n        }\n\n        public void GenerateTypeFactory(string typeName)\n        {\n            InnerBuilder.GenerateTypeFactory(typeName);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages.Razor/CompilingPathEventArgs.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.WebPages.Razor\n{\n    public class CompilingPathEventArgs : EventArgs\n    {\n        public CompilingPathEventArgs(string virtualPath, WebPageRazorHost host)\n        {\n            VirtualPath = virtualPath;\n            Host = host;\n        }\n\n        public string VirtualPath { get; private set; }\n        public WebPageRazorHost Host { get; set; }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages.Razor/Configuration/HostSection.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Configuration;\n\nnamespace System.Web.WebPages.Razor.Configuration\n{\n    public class HostSection : ConfigurationSection\n    {\n        public static readonly string SectionName = RazorWebSectionGroup.GroupName + \"/host\";\n\n        private static readonly ConfigurationProperty _typeProperty =\n            new ConfigurationProperty(\"factoryType\",\n                                      typeof(string),\n                                      null,\n                                      ConfigurationPropertyOptions.IsRequired);\n\n        private bool _factoryTypeSet = false;\n        private string _factoryType;\n\n        [ConfigurationProperty(\"factoryType\", IsRequired = true, DefaultValue = null)]\n        public string FactoryType\n        {\n            get { return _factoryTypeSet ? _factoryType : (string)this[_typeProperty]; }\n            set\n            {\n                _factoryType = value;\n                _factoryTypeSet = true;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages.Razor/Configuration/RazorPagesSection.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Configuration;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Web.Configuration;\n\nnamespace System.Web.WebPages.Razor.Configuration\n{\n    public class RazorPagesSection : ConfigurationSection\n    {\n        public static readonly string SectionName = RazorWebSectionGroup.GroupName + \"/pages\";\n\n        private static readonly ConfigurationProperty _pageBaseTypeProperty =\n            new ConfigurationProperty(\"pageBaseType\",\n                                      typeof(string),\n                                      null,\n                                      ConfigurationPropertyOptions.IsRequired);\n\n        private static readonly ConfigurationProperty _namespacesProperty =\n            new ConfigurationProperty(\"namespaces\",\n                                      typeof(NamespaceCollection),\n                                      null,\n                                      ConfigurationPropertyOptions.IsRequired);\n\n        private bool _pageBaseTypeSet = false;\n        private bool _namespacesSet = false;\n\n        private string _pageBaseType;\n        private NamespaceCollection _namespaces;\n\n        [ConfigurationProperty(\"pageBaseType\", IsRequired = true)]\n        public string PageBaseType\n        {\n            get { return _pageBaseTypeSet ? _pageBaseType : (string)this[_pageBaseTypeProperty]; }\n            set\n            {\n                _pageBaseType = value;\n                _pageBaseTypeSet = true;\n            }\n        }\n\n        [ConfigurationProperty(\"namespaces\", IsRequired = true)]\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\", Justification = \"Being able to set this property is extremely useful for third-parties who are testing components which interact with the Razor configuration system\")]\n        public NamespaceCollection Namespaces\n        {\n            get { return _namespacesSet ? _namespaces : (NamespaceCollection)this[_namespacesProperty]; }\n            set\n            {\n                _namespaces = value;\n                _namespacesSet = true;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages.Razor/Configuration/RazorWebSectionGroup.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Configuration;\n\nnamespace System.Web.WebPages.Razor.Configuration\n{\n    public class RazorWebSectionGroup : ConfigurationSectionGroup\n    {\n        public static readonly string GroupName = \"system.web.webPages.razor\";\n\n        // Use flags instead of null values since tests may want to set the property to null\n        private bool _hostSet = false;\n        private bool _pagesSet = false;\n\n        private HostSection _host;\n        private RazorPagesSection _pages;\n\n        [ConfigurationProperty(\"host\", IsRequired = false)]\n        public HostSection Host\n        {\n            get { return _hostSet ? _host : (HostSection)Sections[\"host\"]; }\n            set\n            {\n                _host = value;\n                _hostSet = true;\n            }\n        }\n\n        [ConfigurationProperty(\"pages\", IsRequired = false)]\n        public RazorPagesSection Pages\n        {\n            get { return _pagesSet ? _pages : (RazorPagesSection)Sections[\"pages\"]; }\n            set\n            {\n                _pages = value;\n                _pagesSet = true;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages.Razor/GlobalSuppressions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n// This file is used by Code Analysis to maintain SuppressMessage \n// attributes that are applied to this project.\n// Project-level suppressions either have no target or are given \n// a specific target and scoped to a namespace, type, member, etc.\n//\n// To add a suppression to this file, right-click the message in the \n// Error List, point to \"Suppress Message(s)\", and click \n// \"In Project Suppression File\".\n// You do not need to add suppressions to this file manually.\n"
  },
  {
    "path": "src/System.Web.WebPages.Razor/HostingEnvironmentWrapper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Hosting;\n\nnamespace System.Web.WebPages.Razor\n{\n    internal sealed class HostingEnvironmentWrapper : IHostingEnvironment\n    {\n        public string MapPath(string virtualPath)\n        {\n            return HostingEnvironment.MapPath(virtualPath);\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages.Razor/IAssemblyBuilder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.Web.Compilation;\n\nnamespace System.Web.WebPages.Razor\n{\n    internal interface IAssemblyBuilder\n    {\n        void AddCodeCompileUnit(BuildProvider buildProvider, CodeCompileUnit compileUnit);\n        void GenerateTypeFactory(string typeName);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages.Razor/IHostingEnvironment.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.WebPages.Razor\n{\n    internal interface IHostingEnvironment\n    {\n        string MapPath(string virtualPath);\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages.Razor/PreApplicationStartCode.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Web.Compilation;\n\nnamespace System.Web.WebPages.Razor\n{\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class PreApplicationStartCode\n    {\n        // NOTE: Do not add public fields, methods, or other members to this class.\n        // This class does not show up in Intellisense so members on it will not be\n        // discoverable by users. Place new members on more appropriate classes that\n        // relate to the public API (for example, a LoginUrl property should go on a\n        // membership-related class).\n\n        private static bool _startWasCalled;\n\n        public static void Start()\n        {\n            // Even though ASP.NET will only call each PreAppStart once, we sometimes internally call one PreAppStart from \n            // another PreAppStart to ensure that things get initialized in the right order. ASP.NET does not guarantee the \n            // order so we have to guard against multiple calls.\n            // All Start calls are made on same thread, so no lock needed here.\n\n            if (_startWasCalled)\n            {\n                return;\n            }\n            _startWasCalled = true;\n\n            BuildProvider.RegisterBuildProvider(\".cshtml\", typeof(RazorBuildProvider));\n            BuildProvider.RegisterBuildProvider(\".vbhtml\", typeof(RazorBuildProvider));\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages.Razor/Properties/AssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Web;\nusing System.Web.WebPages.Razor;\n\n// General Information about an assembly is controlled through the following \n// set of attributes. Change these attribute values to modify the information\n// associated with an assembly.\n\n[assembly: AssemblyTitle(\"System.Web.WebPages.Razor\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: InternalsVisibleTo(\"System.Web.WebPages.Razor.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n[assembly: PreApplicationStartMethod(typeof(PreApplicationStartCode), \"Start\")]\n"
  },
  {
    "path": "src/System.Web.WebPages.Razor/RazorBuildProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.CodeDom.Compiler;\nusing System.Collections;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Security;\nusing System.Web.Compilation;\nusing System.Web.Razor;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.WebPages.Razor\n{\n    [BuildProviderAppliesTo(BuildProviderAppliesTo.Web | BuildProviderAppliesTo.Code)]\n    public class RazorBuildProvider : BuildProvider\n    {\n        private static bool? _isFullTrust;\n        private CodeCompileUnit _generatedCode = null;\n        private WebPageRazorHost _host = null;\n        private IList _virtualPathDependencies;\n        private IAssemblyBuilder _assemblyBuilder;\n        public static event EventHandler<CodeGenerationCompleteEventArgs> CodeGenerationCompleted;\n\n        internal event EventHandler<CodeGenerationCompleteEventArgs> CodeGenerationCompletedInternal\n        {\n            add { _codeGenerationCompletedInternal += value; }\n            remove { _codeGenerationCompletedInternal -= value; }\n        }\n\n        public static event EventHandler CodeGenerationStarted;\n\n        /// <summary>\n        /// For unit testing.\n        /// </summary>\n        internal event EventHandler CodeGenerationStartedInternal\n        {\n            add { _codeGenerationStartedInternal += value; }\n            remove { _codeGenerationStartedInternal -= value; }\n        }\n\n        public static event EventHandler<CompilingPathEventArgs> CompilingPath;\n\n        /// <summary>\n        /// For unit testing\n        /// </summary>\n        private event EventHandler<CodeGenerationCompleteEventArgs> _codeGenerationCompletedInternal;\n        private event EventHandler _codeGenerationStartedInternal;\n\n        internal WebPageRazorHost Host\n        {\n            get\n            {\n                if (_host == null)\n                {\n                    _host = CreateHost();\n                }\n                return _host;\n            }\n            set { _host = value; }\n        }\n\n        // Returns the base dependencies and any dependencies added via AddVirtualPathDependencies\n        public override ICollection VirtualPathDependencies\n        {\n            get\n            {\n                if (_virtualPathDependencies != null)\n                {\n                    // Return a readonly wrapper so as to prevent users from modifying the collection directly.\n                    return ArrayList.ReadOnly(_virtualPathDependencies);\n                }\n                else\n                {\n                    return base.VirtualPathDependencies;\n                }\n            }\n        }\n\n        public new string VirtualPath\n        {\n            get { return base.VirtualPath; }\n        }\n\n        public AssemblyBuilder AssemblyBuilder\n        {\n            get\n            {\n                var wrapper = _assemblyBuilder as AssemblyBuilderWrapper;\n                if (wrapper != null)\n                {\n                    return wrapper.InnerBuilder;\n                }\n                else\n                {\n                    return null;\n                }\n            }\n        }\n\n        // For unit testing\n        internal IAssemblyBuilder AssemblyBuilderInternal\n        {\n            get { return _assemblyBuilder; }\n        }\n\n        internal CodeCompileUnit GeneratedCode\n        {\n            get\n            {\n                EnsureGeneratedCode();\n                return _generatedCode;\n            }\n            set { _generatedCode = value; }\n        }\n\n        public override CompilerType CodeCompilerType\n        {\n            get\n            {\n                EnsureGeneratedCode();\n                CompilerType compilerType = GetDefaultCompilerTypeForLanguage(Host.CodeLanguage.LanguageName);\n                if (_isFullTrust != false && Host.DefaultDebugCompilation)\n                {\n                    try\n                    {\n                        SetIncludeDebugInfoFlag(compilerType);\n                        _isFullTrust = true;\n                    }\n                    catch (SecurityException)\n                    {\n                        _isFullTrust = false;\n                    }\n                }\n                return compilerType;\n            }\n        }\n\n        public void AddVirtualPathDependency(string dependency)\n        {\n            if (_virtualPathDependencies == null)\n            {\n                // Initialize the collection containing the base dependencies\n                _virtualPathDependencies = new ArrayList(base.VirtualPathDependencies);\n            }\n\n            _virtualPathDependencies.Add(dependency);\n        }\n\n        public override Type GetGeneratedType(CompilerResults results)\n        {\n            return results.CompiledAssembly.GetType(String.Format(CultureInfo.CurrentCulture, \"{0}.{1}\", Host.DefaultNamespace, Host.DefaultClassName));\n        }\n\n        public override void GenerateCode(AssemblyBuilder assemblyBuilder)\n        {\n            GenerateCodeCore(new AssemblyBuilderWrapper(assemblyBuilder));\n        }\n\n        internal virtual void GenerateCodeCore(IAssemblyBuilder assemblyBuilder)\n        {\n            OnCodeGenerationStarted(assemblyBuilder);\n            assemblyBuilder.AddCodeCompileUnit(this, GeneratedCode);\n            assemblyBuilder.GenerateTypeFactory(String.Format(CultureInfo.InvariantCulture, \"{0}.{1}\", Host.DefaultNamespace, Host.DefaultClassName));\n        }\n\n        protected internal virtual TextReader InternalOpenReader()\n        {\n            return OpenReader();\n        }\n\n        protected internal virtual WebPageRazorHost CreateHost()\n        {\n            // Get the host from config\n            WebPageRazorHost configuredHost = GetHostFromConfig();\n\n            // Fire the event\n            CompilingPathEventArgs args = new CompilingPathEventArgs(VirtualPath, configuredHost);\n            OnBeforeCompilePath(args);\n\n            // Return the host provided in the args, which may have been changed by the handler\n            return args.Host;\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Justification = \"This method performs significant work and a property would not be appropriate\")]\n        protected internal virtual WebPageRazorHost GetHostFromConfig()\n        {\n            return WebRazorHostFactory.CreateHostFromConfig(VirtualPath);\n        }\n\n        protected virtual void OnBeforeCompilePath(CompilingPathEventArgs args)\n        {\n            EventHandler<CompilingPathEventArgs> handler = CompilingPath;\n            if (handler != null)\n            {\n                handler(this, args);\n            }\n        }\n\n        private void OnCodeGenerationStarted(IAssemblyBuilder assemblyBuilder)\n        {\n            _assemblyBuilder = assemblyBuilder;\n            EventHandler handler = _codeGenerationStartedInternal ?? CodeGenerationStarted;\n            if (handler != null)\n            {\n                handler(this, null);\n            }\n        }\n\n        private void OnCodeGenerationCompleted(CodeCompileUnit generatedCode)\n        {\n            EventHandler<CodeGenerationCompleteEventArgs> handler = _codeGenerationCompletedInternal ?? CodeGenerationCompleted;\n            if (handler != null)\n            {\n                handler(this, new CodeGenerationCompleteEventArgs(Host.VirtualPath, Host.PhysicalPath, generatedCode));\n            }\n        }\n\n        private void EnsureGeneratedCode()\n        {\n            if (_generatedCode == null)\n            {\n                RazorTemplateEngine engine = new RazorTemplateEngine(Host);\n                GeneratorResults results = null;\n                using (TextReader reader = InternalOpenReader())\n                {\n                    results = engine.GenerateCode(reader, className: null, rootNamespace: null, sourceFileName: Host.PhysicalPath);\n                }\n                if (!results.Success)\n                {\n                    throw CreateExceptionFromParserError(results.ParserErrors.Last(), VirtualPath);\n                }\n                _generatedCode = results.GeneratedCode;\n\n                // Run the code gen complete event\n                OnCodeGenerationCompleted(_generatedCode);\n            }\n        }\n\n        private static HttpParseException CreateExceptionFromParserError(RazorError error, string virtualPath)\n        {\n            return new HttpParseException(error.Message + Environment.NewLine, null, virtualPath, null, error.Location.LineIndex + 1);\n        }\n\n        [SuppressMessage(\"Microsoft.Security\", \"CA2141:TransparentMethodsMustNotSatisfyLinkDemandsFxCopRule\", Justification = \"We are catching the SecurityException to detect medium trust\")]\n        private static void SetIncludeDebugInfoFlag(CompilerType compilerType)\n        {\n            compilerType.CompilerParameters.IncludeDebugInformation = true;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages.Razor/Resources/RazorWebResources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.1\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace System.Web.WebPages.Razor.Resources {\n    using System;\n    \n    \n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class RazorWebResources {\n        \n        private static global::System.Resources.ResourceManager resourceMan;\n        \n        private static global::System.Globalization.CultureInfo resourceCulture;\n        \n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal RazorWebResources() {\n        }\n        \n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"System.Web.WebPages.Razor.Resources.RazorWebResources\", typeof(RazorWebResources).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n        \n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Could not determine the code language for &quot;{0}&quot;..\n        /// </summary>\n        internal static string BuildProvider_No_CodeLanguageService_For_Path {\n            get {\n                return ResourceManager.GetString(\"BuildProvider_No_CodeLanguageService_For_Path\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Could not locate Razor Host Factory type: {0}.\n        /// </summary>\n        internal static string Could_Not_Locate_FactoryType {\n            get {\n                return ResourceManager.GetString(\"Could_Not_Locate_FactoryType\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages.Razor/Resources/RazorWebResources.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"BuildProvider_No_CodeLanguageService_For_Path\" xml:space=\"preserve\">\n    <value>Could not determine the code language for \"{0}\".</value>\n  </data>\n  <data name=\"Could_Not_Locate_FactoryType\" xml:space=\"preserve\">\n    <value>Could not locate Razor Host Factory type: {0}</value>\n  </data>\n</root>"
  },
  {
    "path": "src/System.Web.WebPages.Razor/System.Web.WebPages.Razor.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{0939B11A-FE4E-4BA1-8AD6-D97741EE314F}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <RootNamespace>System.Web.WebPages.Razor</RootNamespace>\n    <AssemblyName>System.Web.WebPages.Razor</AssemblyName>\n    <DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>\n    <RunCodeAnalysis>$(CodeAnalysis)</RunCodeAnalysis>\n    <CodeAnalysisRuleSet>..\\Strict.ruleset</CodeAnalysisRuleSet>\n    <DefineConstants>$(DefineConstants);ASPNETWEBPAGES</DefineConstants>\n    <NoWarn>1591</NoWarn>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Web\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\CommonAssemblyInfo.cs\">\n      <Link>Properties\\CommonAssemblyInfo.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\CommonResources.Designer.cs\">\n      <Link>Common\\CommonResources.Designer.cs</Link>\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>CommonResources.resx</DependentUpon>\n    </Compile>\n    <Compile Include=\"..\\GlobalSuppressions.cs\">\n      <Link>Common\\GlobalSuppressions.cs</Link>\n    </Compile>\n    <Compile Include=\"AssemblyBuilderWrapper.cs\" />\n    <Compile Include=\"CompilingPathEventArgs.cs\" />\n    <Compile Include=\"Configuration\\HostSection.cs\" />\n    <Compile Include=\"Configuration\\RazorPagesSection.cs\" />\n    <Compile Include=\"Configuration\\RazorWebSectionGroup.cs\" />\n    <Compile Include=\"GlobalSuppressions.cs\" />\n    <Compile Include=\"HostingEnvironmentWrapper.cs\" />\n    <Compile Include=\"IAssemblyBuilder.cs\" />\n    <Compile Include=\"IHostingEnvironment.cs\" />\n    <Compile Include=\"PreApplicationStartCode.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"RazorBuildProvider.cs\" />\n    <Compile Include=\"WebRazorHostFactory.cs\" />\n    <Compile Include=\"WebCodeRazorHost.cs\" />\n    <Compile Include=\"WebPageRazorHost.cs\" />\n    <Compile Include=\"Resources\\RazorWebResources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>RazorWebResources.resx</DependentUpon>\n    </Compile>\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\System.Web.WebPages\\System.Web.WebPages.csproj\">\n      <Project>{76EFA9C5-8D7E-4FDF-B710-E20F8B6B00D2}</Project>\n      <Name>System.Web.WebPages</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.Razor\\System.Web.Razor.csproj\">\n      <Project>{8F18041B-9410-4C36-A9C5-067813DF5F31}</Project>\n      <Name>System.Web.Razor</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"..\\CommonResources.resx\">\n      <Link>Common\\CommonResources.resx</Link>\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>CommonResources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n    <EmbeddedResource Include=\"Resources\\RazorWebResources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>RazorWebResources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n  </ItemGroup>\n  <ItemGroup>\n    <CodeAnalysisDictionary Include=\"..\\CodeAnalysisDictionary.xml\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n</Project>"
  },
  {
    "path": "src/System.Web.WebPages.Razor/WebCodeRazorHost.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.IO;\nusing System.Linq;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\n\nnamespace System.Web.WebPages.Razor\n{\n    public class WebCodeRazorHost : WebPageRazorHost\n    {\n        private const string AppCodeDir = \"App_Code\";\n        private const string HttpContextAccessorName = \"Context\";\n        private static readonly string _helperPageBaseType = typeof(HelperPage).FullName;\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2214:DoNotCallOverridableMethodsInConstructors\", Justification = \"The code path is safe, it is a property setter and not dependent on other state\")]\n        public WebCodeRazorHost(string virtualPath)\n            : base(virtualPath)\n        {\n            DefaultBaseClass = _helperPageBaseType;\n            DefaultNamespace = DetermineNamespace(virtualPath);\n            DefaultDebugCompilation = false;\n            StaticHelpers = true;\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2214:DoNotCallOverridableMethodsInConstructors\", Justification = \"The code path is safe, it is a property setter and not dependent on other state\")]\n        public WebCodeRazorHost(string virtualPath, string physicalPath)\n            : base(virtualPath, physicalPath)\n        {\n            DefaultBaseClass = _helperPageBaseType;\n            DefaultNamespace = DetermineNamespace(virtualPath);\n            DefaultDebugCompilation = false;\n            StaticHelpers = true;\n        }\n\n        public override void PostProcessGeneratedCode(CodeGeneratorContext context)\n        {\n            base.PostProcessGeneratedCode(context);\n\n            // Yank out the execute method (ignored in Razor Web Code pages)\n            context.GeneratedClass.Members.Remove(context.TargetMethod);\n\n            // Make ApplicationInstance static\n            CodeMemberProperty appInstanceProperty =\n                context.GeneratedClass.Members\n                    .OfType<CodeMemberProperty>()\n                    .Where(p => ApplicationInstancePropertyName\n                                    .Equals(p.Name))\n                    .SingleOrDefault();\n\n            if (appInstanceProperty != null)\n            {\n                appInstanceProperty.Attributes |= MemberAttributes.Static;\n            }\n        }\n\n        protected override string GetClassName(string virtualPath)\n        {\n            return ParserHelpers.SanitizeClassName(Path.GetFileNameWithoutExtension(virtualPath));\n        }\n\n        private static string DetermineNamespace(string virtualPath)\n        {\n            // Normailzize the virtual path\n            virtualPath = virtualPath.Replace(Path.DirectorySeparatorChar, '/');\n\n            // Get the directory\n            virtualPath = GetDirectory(virtualPath);\n\n            // Skip the App_Code segment if any\n            int appCodeIndex = virtualPath.IndexOf(AppCodeDir, StringComparison.OrdinalIgnoreCase);\n            if (appCodeIndex != -1)\n            {\n                virtualPath = virtualPath.Substring(appCodeIndex + AppCodeDir.Length);\n            }\n\n            // Get the segments removing any empty entries\n            IEnumerable<string> segments = virtualPath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);\n\n            if (!segments.Any())\n            {\n                return WebDefaultNamespace;\n            }\n\n            return WebDefaultNamespace + \".\" + String.Join(\".\", segments);\n        }\n\n        private static string GetDirectory(string virtualPath)\n        {\n            int lastSlash = virtualPath.LastIndexOf('/');\n            if (lastSlash != -1)\n            {\n                return virtualPath.Substring(0, lastSlash);\n            }\n            return String.Empty;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages.Razor/WebPageRazorHost.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Web.Compilation;\nusing System.Web.Hosting;\nusing System.Web.Razor;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.WebPages.Instrumentation;\nusing System.Web.WebPages.Razor.Resources;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.WebPages.Razor\n{\n    public class WebPageRazorHost : RazorEngineHost\n    {\n        // DevDiv Bug 941404 - Add a prefix and folder name to class names\n        internal const string PageClassNamePrefix = \"_Page_\";\n        internal const string ApplicationInstancePropertyName = \"ApplicationInstance\";\n        internal const string ContextPropertyName = \"Context\";\n        internal const string DefineSectionMethodName = \"DefineSection\";\n        internal const string WebDefaultNamespace = \"ASP\";\n        internal const string WriteToMethodName = \"WriteTo\";\n        internal const string WriteLiteralToMethodName = \"WriteLiteralTo\";\n        internal const string BeginContextMethodName = \"BeginContext\";\n        internal const string EndContextMethodName = \"EndContext\";\n        internal const string ResolveUrlMethodName = \"Href\";\n\n        private const string ApplicationStartFileName = \"_AppStart\";\n        private const string PageStartFileName = \"_PageStart\";\n\n        internal static readonly string FallbackApplicationTypeName = typeof(HttpApplication).FullName;\n        internal static readonly string PageBaseClass = typeof(WebPage).FullName;\n        internal static readonly string TemplateTypeName = typeof(HelperResult).FullName;\n\n        private static ConcurrentDictionary<string, object> _importedNamespaces = new ConcurrentDictionary<string, object>();\n        private readonly Dictionary<string, string> _specialFileBaseTypes = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);\n\n        private string _className;\n        private RazorCodeLanguage _codeLanguage;\n        private string _globalAsaxTypeName;\n        private bool? _isSpecialPage;\n        private string _physicalPath = null;\n        private string _specialFileBaseClass;\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2214:DoNotCallOverridableMethodsInConstructors\", Justification = \"The code path is safe, it is a property setter and not dependent on other state\")]\n        private WebPageRazorHost()\n        {\n            NamespaceImports.Add(\"System\");\n            NamespaceImports.Add(\"System.Collections.Generic\");\n            NamespaceImports.Add(\"System.IO\");\n            NamespaceImports.Add(\"System.Linq\");\n            NamespaceImports.Add(\"System.Net\");\n            NamespaceImports.Add(\"System.Web\");\n            NamespaceImports.Add(\"System.Web.Helpers\");\n            NamespaceImports.Add(\"System.Web.Security\");\n            NamespaceImports.Add(\"System.Web.UI\");\n            NamespaceImports.Add(\"System.Web.WebPages\");\n            NamespaceImports.Add(\"System.Web.WebPages.Html\");\n\n            RegisterSpecialFile(ApplicationStartFileName, typeof(ApplicationStartPage));\n            RegisterSpecialFile(PageStartFileName, typeof(StartPage));\n            DefaultNamespace = WebDefaultNamespace;\n            GeneratedClassContext = new GeneratedClassContext(GeneratedClassContext.DefaultExecuteMethodName,\n                                                              GeneratedClassContext.DefaultWriteMethodName,\n                                                              GeneratedClassContext.DefaultWriteLiteralMethodName,\n                                                              WriteToMethodName,\n                                                              WriteLiteralToMethodName,\n                                                              TemplateTypeName,\n                                                              DefineSectionMethodName,\n                                                              BeginContextMethodName,\n                                                              EndContextMethodName)\n            {\n                ResolveUrlMethodName = ResolveUrlMethodName\n            };\n            DefaultPageBaseClass = PageBaseClass;\n            DefaultDebugCompilation = true;\n            EnableInstrumentation = false;\n        }\n\n        public WebPageRazorHost(string virtualPath)\n            : this(virtualPath, null)\n        {\n        }\n\n        [SuppressMessage(\"Microsoft.Usage\", \"CA2214:DoNotCallOverridableMethodsInConstructors\", Justification = \"The code path is safe, it is a property setter and not dependent on other state\")]\n        public WebPageRazorHost(string virtualPath, string physicalPath)\n            : this()\n        {\n            if (String.IsNullOrEmpty(virtualPath))\n            {\n                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"virtualPath\"), \"virtualPath\");\n            }\n\n            VirtualPath = virtualPath;\n\n            PhysicalPath = physicalPath;\n            DefaultClassName = GetClassName(VirtualPath);\n            CodeLanguage = GetCodeLanguage();\n            EnableInstrumentation = new InstrumentationService().IsAvailable;\n        }\n\n        public override RazorCodeLanguage CodeLanguage\n        {\n            get\n            {\n                if (_codeLanguage == null)\n                {\n                    _codeLanguage = GetCodeLanguage();\n                }\n                return _codeLanguage;\n            }\n            protected set { _codeLanguage = value; }\n        }\n\n        public override string DefaultBaseClass\n        {\n            get\n            {\n                if (base.DefaultBaseClass != null)\n                {\n                    return base.DefaultBaseClass;\n                }\n                if (IsSpecialPage)\n                {\n                    return SpecialPageBaseClass;\n                }\n                else\n                {\n                    return DefaultPageBaseClass;\n                }\n            }\n            set { base.DefaultBaseClass = value; }\n        }\n\n        public override string DefaultClassName\n        {\n            get\n            {\n                if (_className == null)\n                {\n                    _className = GetClassName(VirtualPath);\n                }\n                return _className;\n            }\n            set { _className = value; }\n        }\n\n        public bool DefaultDebugCompilation { get; set; }\n\n        public string DefaultPageBaseClass { get; set; }\n\n        internal string GlobalAsaxTypeName\n        {\n            get { return _globalAsaxTypeName ?? (HostingEnvironment.IsHosted ? BuildManager.GetGlobalAsaxType().FullName : FallbackApplicationTypeName); }\n            set { _globalAsaxTypeName = value; }\n        }\n\n        public bool IsSpecialPage\n        {\n            get\n            {\n                CheckForSpecialPage();\n                return _isSpecialPage.Value;\n            }\n        }\n\n        public string PhysicalPath\n        {\n            get\n            {\n                MapPhysicalPath();\n                return _physicalPath;\n            }\n            set { _physicalPath = value; }\n        }\n\n        public override string InstrumentedSourceFilePath\n        {\n            get { return VirtualPath; }\n            set { VirtualPath = value; }\n        }\n\n        private string SpecialPageBaseClass\n        {\n            get\n            {\n                CheckForSpecialPage();\n                return _specialFileBaseClass;\n            }\n        }\n\n        public string VirtualPath { get; private set; }\n\n        /// <summary>\n        /// Adds a namespace to the global imports list for this AppDomain\n        /// </summary>\n        /// <remarks>\n        /// IMPORTANT: ALL uses of WebPageRazorHost (and derived classes) within the same AppDomain will share this list.\n        /// Therefore this method should only be used in runtime scenarios, not in design-time scenarios where the Razor\n        /// data structures for multiple files and projects may be shared within a single AppDomain.\n        /// </remarks>\n        /// <param name=\"ns\">The namespace to add to the global imports list.</param>\n        public static void AddGlobalImport(string ns)\n        {\n            if (String.IsNullOrEmpty(ns))\n            {\n                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"ns\"), \"ns\");\n            }\n\n            _importedNamespaces.TryAdd(ns, null);\n        }\n\n        private void CheckForSpecialPage()\n        {\n            if (!_isSpecialPage.HasValue)\n            {\n                string fileName = Path.GetFileNameWithoutExtension(VirtualPath);\n                string baseType;\n                if (_specialFileBaseTypes.TryGetValue(fileName, out baseType))\n                {\n                    _isSpecialPage = true;\n                    _specialFileBaseClass = baseType;\n                }\n                else\n                {\n                    _isSpecialPage = false;\n                }\n            }\n        }\n\n        public override ParserBase CreateMarkupParser()\n        {\n            return new HtmlMarkupParser();\n        }\n\n        private static RazorCodeLanguage DetermineCodeLanguage(string fileName)\n        {\n            string extension = Path.GetExtension(fileName);\n\n            // Use an if rather than else-if just in case Path.GetExtension returns null for some reason\n            if (String.IsNullOrEmpty(extension))\n            {\n                return null;\n            }\n            if (extension[0] == '.')\n            {\n                extension = extension.Substring(1); // Trim off the dot\n            }\n\n            // Look up the language\n            // At the moment this only deals with code languages: cs, vb, etc., but in theory we could have MarkupLanguageServices which allow for\n            // interesting combinations like: vbcss, csxml, etc.\n            RazorCodeLanguage language = GetLanguageByExtension(extension);\n            return language;\n        }\n\n        protected virtual string GetClassName(string virtualPath)\n        {\n            // Remove \"~/\" and run through our santizer\n            // For example, for ~/Foo/Bar/Baz.cshtml, the class name is _Page_Foo_Bar_Baz_cshtml\n            return ParserHelpers.SanitizeClassName(PageClassNamePrefix + virtualPath.TrimStart('~', '/'));\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Justification = \"Method involves significant processing and should not be a property\")]\n        protected virtual RazorCodeLanguage GetCodeLanguage()\n        {\n            RazorCodeLanguage language = DetermineCodeLanguage(VirtualPath);\n            if (language == null && !String.IsNullOrEmpty(PhysicalPath))\n            {\n                language = DetermineCodeLanguage(PhysicalPath);\n            }\n\n            if (language == null)\n            {\n                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, RazorWebResources.BuildProvider_No_CodeLanguageService_For_Path, VirtualPath));\n            }\n\n            return language;\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Justification = \"This method involves copying memory, so a property is not appropriate\")]\n        public static IEnumerable<string> GetGlobalImports()\n        {\n            return _importedNamespaces.ToArray().Select(pair => pair.Key);\n        }\n\n        private static RazorCodeLanguage GetLanguageByExtension(string extension)\n        {\n            return RazorCodeLanguage.GetLanguageByExtension(extension);\n        }\n\n        private void MapPhysicalPath()\n        {\n            if (_physicalPath == null && HostingEnvironment.IsHosted)\n            {\n                string path = HostingEnvironment.MapPath(VirtualPath);\n                if (!String.IsNullOrEmpty(path) && File.Exists(path))\n                {\n                    _physicalPath = path;\n                }\n            }\n        }\n\n        public override void PostProcessGeneratedCode(CodeGeneratorContext context)\n        {\n            base.PostProcessGeneratedCode(context);\n\n            // Add additional global imports\n            context.Namespace.Imports.AddRange(GetGlobalImports().Select(s => new CodeNamespaceImport(s)).ToArray());\n\n            // Create ApplicationInstance property\n            CodeMemberProperty prop = new CodeMemberProperty()\n            {\n                Name = ApplicationInstancePropertyName,\n                Type = new CodeTypeReference(GlobalAsaxTypeName),\n                HasGet = true,\n                HasSet = false,\n                Attributes = MemberAttributes.Family | MemberAttributes.Final\n            };\n            prop.GetStatements.Add(\n                new CodeMethodReturnStatement(\n                    new CodeCastExpression(\n                        new CodeTypeReference(GlobalAsaxTypeName),\n                        new CodePropertyReferenceExpression(\n                            new CodePropertyReferenceExpression(\n                                null,\n                                ContextPropertyName),\n                            ApplicationInstancePropertyName))));\n            context.GeneratedClass.Members.Insert(0, prop);\n        }\n\n        protected void RegisterSpecialFile(string fileName, Type baseType)\n        {\n            if (baseType == null)\n            {\n                throw new ArgumentNullException(\"baseType\");\n            }\n            RegisterSpecialFile(fileName, baseType.FullName);\n        }\n\n        protected void RegisterSpecialFile(string fileName, string baseTypeName)\n        {\n            if (String.IsNullOrEmpty(fileName))\n            {\n                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"fileName\"), \"fileName\");\n            }\n            if (String.IsNullOrEmpty(baseTypeName))\n            {\n                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"baseTypeName\"), \"baseTypeName\");\n            }\n\n            _specialFileBaseTypes[fileName] = baseTypeName;\n        }\n    }\n}\n"
  },
  {
    "path": "src/System.Web.WebPages.Razor/WebRazorHostFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.Linq;\nusing System.Linq.Expressions;\nusing System.Web.Compilation;\nusing System.Web.Configuration;\nusing System.Web.Hosting;\nusing System.Web.WebPages.Razor.Configuration;\nusing System.Web.WebPages.Razor.Resources;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.WebPages.Razor\n{\n    public class WebRazorHostFactory\n    {\n        private static ConcurrentDictionary<string, Func<WebRazorHostFactory>> _factories =\n            new ConcurrentDictionary<string, Func<WebRazorHostFactory>>(StringComparer.OrdinalIgnoreCase);\n\n        internal static Func<string, Type> TypeFactory = DefaultTypeFactory;\n\n        public static WebPageRazorHost CreateDefaultHost(string virtualPath)\n        {\n            return CreateDefaultHost(virtualPath, null);\n        }\n\n        public static WebPageRazorHost CreateDefaultHost(string virtualPath, string physicalPath)\n        {\n            return CreateHostFromConfigCore(null, virtualPath, physicalPath);\n        }\n\n        public static WebPageRazorHost CreateHostFromConfig(string virtualPath)\n        {\n            return CreateHostFromConfig(virtualPath, null);\n        }\n\n        public static WebPageRazorHost CreateHostFromConfig(string virtualPath, string physicalPath)\n        {\n            if (String.IsNullOrEmpty(virtualPath))\n            {\n                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"virtualPath\"), \"virtualPath\");\n            }\n\n            return CreateHostFromConfigCore(GetRazorSection(virtualPath), virtualPath, physicalPath);\n        }\n\n        public static WebPageRazorHost CreateHostFromConfig(RazorWebSectionGroup config, string virtualPath)\n        {\n            return CreateHostFromConfig(config, virtualPath, null);\n        }\n\n        public static WebPageRazorHost CreateHostFromConfig(RazorWebSectionGroup config, string virtualPath, string physicalPath)\n        {\n            if (config == null)\n            {\n                throw new ArgumentNullException(\"config\");\n            }\n            if (String.IsNullOrEmpty(virtualPath))\n            {\n                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"virtualPath\"), \"virtualPath\");\n            }\n\n            return CreateHostFromConfigCore(config, virtualPath, physicalPath);\n        }\n\n        internal static WebPageRazorHost CreateHostFromConfigCore(RazorWebSectionGroup config, string virtualPath, string physicalPath)\n        {\n            // Use the virtual path to select a host environment for the generated code\n            // Do this check here because the App_Code host can't be overridden.\n\n            // Make the path app relative\n            virtualPath = EnsureAppRelative(virtualPath);\n\n            WebPageRazorHost host;\n            if (virtualPath.StartsWith(\"~/App_Code\", StringComparison.OrdinalIgnoreCase))\n            {\n                // Under App_Code => It's a Web Code file\n                host = new WebCodeRazorHost(virtualPath, physicalPath);\n            }\n            else\n            {\n                WebRazorHostFactory factory = null;\n                if (config != null && config.Host != null && !String.IsNullOrEmpty(config.Host.FactoryType))\n                {\n                    Func<WebRazorHostFactory> factoryCreator = _factories.GetOrAdd(config.Host.FactoryType, CreateFactory);\n                    Debug.Assert(factoryCreator != null); // CreateFactory should throw if there's an error creating the factory\n                    factory = factoryCreator();\n                }\n\n                host = (factory ?? new WebRazorHostFactory()).CreateHost(virtualPath, physicalPath);\n\n                if (config != null && config.Pages != null)\n                {\n                    ApplyConfigurationToHost(config.Pages, host);\n                }\n            }\n\n            return host;\n        }\n\n        private static Func<WebRazorHostFactory> CreateFactory(string typeName)\n        {\n            Type factoryType = TypeFactory(typeName);\n            if (factoryType == null)\n            {\n                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,\n                                                                  RazorWebResources.Could_Not_Locate_FactoryType,\n                                                                  typeName));\n            }\n            return Expression.Lambda<Func<WebRazorHostFactory>>(Expression.New(factoryType))\n                .Compile();\n        }\n\n        public static void ApplyConfigurationToHost(RazorPagesSection config, WebPageRazorHost host)\n        {\n            host.DefaultPageBaseClass = config.PageBaseType;\n\n            // Add imports\n            foreach (string import in config.Namespaces.OfType<NamespaceInfo>().Select(ns => ns.Namespace))\n            {\n                host.NamespaceImports.Add(import);\n            }\n        }\n\n        public virtual WebPageRazorHost CreateHost(string virtualPath, string physicalPath)\n        {\n            return new WebPageRazorHost(virtualPath, physicalPath);\n        }\n\n        internal static RazorWebSectionGroup GetRazorSection(string virtualPath)\n        {\n            // Get the individual sections (we can only use GetSection in medium trust) and then reconstruct the section group\n            return new RazorWebSectionGroup()\n            {\n                Host = (HostSection)WebConfigurationManager.GetSection(HostSection.SectionName, virtualPath),\n                Pages = (RazorPagesSection)WebConfigurationManager.GetSection(RazorPagesSection.SectionName, virtualPath)\n            };\n        }\n\n#if CODE_COVERAGE\n        [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]\n        // JUSTIFICATION: VirtualPathUtility.ToAppRelative is only available in ASP.Net environment\n#endif\n\n        private static string EnsureAppRelative(string virtualPath)\n        {\n            if (HostingEnvironment.IsHosted)\n            {\n                virtualPath = VirtualPathUtility.ToAppRelative(virtualPath);\n            }\n            else\n            {\n                if (virtualPath.StartsWith(\"/\", StringComparison.Ordinal))\n                {\n                    virtualPath = \"~\" + virtualPath;\n                }\n                else if (!virtualPath.StartsWith(\"~/\", StringComparison.Ordinal))\n                {\n                    virtualPath = \"~/\" + virtualPath;\n                }\n            }\n            return virtualPath;\n        }\n\n#if CODE_COVERAGE\n        [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]\n        // JUSTIFICATION: BuildManager.GetType is only available in ASP.Net environment\n#endif\n\n        private static Type DefaultTypeFactory(string typeName)\n        {\n            return BuildManager.GetType(typeName, false, false);\n        }\n    }\n}\n"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/ApiDescriptionExtensions.cs",
    "content": "﻿using System;\nusing System.Text;\nusing System.Web;\nusing System.Web.Http.Description;\n\nnamespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage\n{\n    public static class ApiDescriptionExtensions\n    {\n        /// <summary>\n        /// Generates an URI-friendly ID for the <see cref=\"ApiDescription\"/>. E.g. \"Get-Values-id_name\" instead of \"GetValues/{id}?name={name}\"\n        /// </summary>\n        /// <param name=\"description\">The <see cref=\"ApiDescription\"/>.</param>\n        /// <returns>The ID as a string.</returns>\n        public static string GetFriendlyId(this ApiDescription description)\n        {\n            string path = description.RelativePath;\n            string[] urlParts = path.Split('?');\n            string localPath = urlParts[0];\n            string queryKeyString = null;\n            if (urlParts.Length > 1)\n            {\n                string query = urlParts[1];\n                string[] queryKeys = HttpUtility.ParseQueryString(query).AllKeys;\n                queryKeyString = String.Join(\"_\", queryKeys);\n            }\n\n            StringBuilder friendlyPath = new StringBuilder();\n            friendlyPath.AppendFormat(\"{0}-{1}\",\n                description.HttpMethod.Method,\n                localPath.Replace(\"/\", \"-\").Replace(\"{\", String.Empty).Replace(\"}\", String.Empty));\n            if (queryKeyString != null)\n            {\n                friendlyPath.AppendFormat(\"_{0}\", queryKeyString.Replace('.', '-'));\n            }\n            return friendlyPath.ToString();\n        }\n    }\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/App_Start/HelpPageConfig.cs",
    "content": "﻿// Uncomment the following to provide samples for PageResult<T>. Must also add the Microsoft.AspNet.WebApi.OData\n// package to your project.\n////#define Handle_PageResultOfT\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing System.Net.Http.Headers;\nusing System.Reflection;\nusing System.Web;\nusing System.Web.Http;\n#if Handle_PageResultOfT\nusing System.Web.Http.OData;\n#endif\n\nnamespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage\n{\n    /// <summary>\n    /// Use this class to customize the Help Page.\n    /// For example you can set a custom <see cref=\"System.Web.Http.Description.IDocumentationProvider\"/> to supply the documentation\n    /// or you can provide the samples for the requests/responses.\n    /// </summary>\n    public static class HelpPageConfig\n    {\n        [SuppressMessage(\"Microsoft.Globalization\", \"CA1303:Do not pass literals as localized parameters\",\n            MessageId = \"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.TextSample.#ctor(System.String)\",\n            Justification = \"End users may choose to merge this string with existing localized resources.\")]\n        [SuppressMessage(\"Microsoft.Naming\", \"CA2204:Literals should be spelled correctly\",\n            MessageId = \"bsonspec\",\n            Justification = \"Part of a URI.\")]\n        public static void Register(HttpConfiguration config)\n        {\n            //// Uncomment the following to use the documentation from XML documentation file.\n            //config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath(\"~/App_Data/XmlDocument.xml\")));\n\n            //// Uncomment the following to use \"sample string\" as the sample for all actions that have string as the body parameter or return type.\n            //// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type \n            //// formats by the available formatters.\n            //config.SetSampleObjects(new Dictionary<Type, object>\n            //{\n            //    {typeof(string), \"sample string\"},\n            //    {typeof(IEnumerable<string>), new string[]{\"sample 1\", \"sample 2\"}}\n            //});\n\n            // Extend the following to provide factories for types not handled automatically (those lacking parameterless\n            // constructors) or for which you prefer to use non-default property values. Line below provides a fallback\n            // since automatic handling will fail and GeneratePageResult handles only a single type.\n#if Handle_PageResultOfT\n            config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult);\n#endif\n\n            // Extend the following to use a preset object directly as the sample for all actions that support a media\n            // type, regardless of the body parameter or return type. The lines below avoid display of binary content.\n            // The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object.\n            config.SetSampleForMediaType(\n                new TextSample(\"Binary JSON content. See http://bsonspec.org for details.\"),\n                new MediaTypeHeaderValue(\"application/bson\"));\n\n            //// Uncomment the following to use \"[0]=foo&[1]=bar\" directly as the sample for all actions that support form URL encoded format\n            //// and have IEnumerable<string> as the body parameter or return type.\n            //config.SetSampleForType(\"[0]=foo&[1]=bar\", new MediaTypeHeaderValue(\"application/x-www-form-urlencoded\"), typeof(IEnumerable<string>));\n\n            //// Uncomment the following to use \"1234\" directly as the request sample for media type \"text/plain\" on the controller named \"Values\"\n            //// and action named \"Put\".\n            //config.SetSampleRequest(\"1234\", new MediaTypeHeaderValue(\"text/plain\"), \"Values\", \"Put\");\n\n            //// Uncomment the following to use the image on \"../images/aspNetHome.png\" directly as the response sample for media type \"image/png\"\n            //// on the controller named \"Values\" and action named \"Get\" with parameter \"id\".\n            //config.SetSampleResponse(new ImageSample(\"../images/aspNetHome.png\"), new MediaTypeHeaderValue(\"image/png\"), \"Values\", \"Get\", \"id\");\n\n            //// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>.\n            //// The sample will be generated as if the controller named \"Values\" and action named \"Get\" were having string as the body parameter.\n            //config.SetActualRequestType(typeof(string), \"Values\", \"Get\");\n\n            //// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>.\n            //// The sample will be generated as if the controller named \"Values\" and action named \"Post\" were returning a string.\n            //config.SetActualResponseType(typeof(string), \"Values\", \"Post\");\n        }\n\n#if Handle_PageResultOfT\n        private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type)\n        {\n            if (type.IsGenericType)\n            {\n                Type openGenericType = type.GetGenericTypeDefinition();\n                if (openGenericType == typeof(PageResult<>))\n                {\n                    // Get the T in PageResult<T>\n                    Type[] typeParameters = type.GetGenericArguments();\n                    Debug.Assert(typeParameters.Length == 1);\n\n                    // Create an enumeration to pass as the first parameter to the PageResult<T> constuctor\n                    Type itemsType = typeof(List<>).MakeGenericType(typeParameters);\n                    object items = sampleGenerator.GetSampleObject(itemsType);\n\n                    // Fill in the other information needed to invoke the PageResult<T> constuctor\n                    Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), };\n                    object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, };\n\n                    // Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor\n                    ConstructorInfo constructor = type.GetConstructor(parameterTypes);\n                    return constructor.Invoke(parameters);\n                }\n            }\n\n            return null;\n        }\n#endif\n    }\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/Controllers/HelpController.cs",
    "content": "﻿using System;\nusing System.Web.Http;\nusing System.Web.Mvc;\nusing ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions;\nusing ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Models;\n\nnamespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Controllers\n{\n    /// <summary>\n    /// The controller that will handle requests for the help page.\n    /// </summary>\n    public class HelpController : Controller\n    {\n        private const string ErrorViewName = \"Error\";\n\n        public HelpController()\n            : this(GlobalConfiguration.Configuration)\n        {\n        }\n\n        public HelpController(HttpConfiguration config)\n        {\n            Configuration = config;\n        }\n\n        public HttpConfiguration Configuration { get; private set; }\n\n        public ActionResult Index()\n        {\n            ViewBag.DocumentationProvider = Configuration.Services.GetDocumentationProvider();\n            return View(Configuration.Services.GetApiExplorer().ApiDescriptions);\n        }\n\n        public ActionResult Api(string apiId)\n        {\n            if (!String.IsNullOrEmpty(apiId))\n            {\n                HelpPageApiModel apiModel = Configuration.GetHelpPageApiModel(apiId);\n                if (apiModel != null)\n                {\n                    return View(apiModel);\n                }\n            }\n\n            return View(ErrorViewName);\n        }\n\n        public ActionResult ResourceModel(string modelName)\n        {\n            if (!String.IsNullOrEmpty(modelName))\n            {\n                ModelDescriptionGenerator modelDescriptionGenerator = Configuration.GetModelDescriptionGenerator();\n                ModelDescription modelDescription;\n                if (modelDescriptionGenerator.GeneratedModels.TryGetValue(modelName, out modelDescription))\n                {\n                    return View(modelDescription);\n                }\n            }\n\n            return View(ErrorViewName);\n        }\n    }\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/HelpPage.css",
    "content": "﻿.help-page h1,\n.help-page .h1,\n.help-page h2,\n.help-page .h2,\n.help-page h3,\n.help-page .h3,\n#body.help-page,\n.help-page-table th,\n.help-page-table pre,\n.help-page-table p {\n    font-family: \"Segoe UI Light\", Frutiger, \"Frutiger Linotype\", \"Dejavu Sans\", \"Helvetica Neue\", Arial, sans-serif;\n}\n\n.help-page pre.wrapped {\n    white-space: -moz-pre-wrap;\n    white-space: -pre-wrap;\n    white-space: -o-pre-wrap;\n    white-space: pre-wrap;\n}\n\n.help-page .warning-message-container {\n    margin-top: 20px;\n    padding: 0 10px;\n    color: #525252;\n    background: #EFDCA9; \n    border: 1px solid #CCCCCC;\n}\n\n.help-page-table {\n    width: 100%;\n    border-collapse: collapse;\n    text-align: left;\n    margin: 0px 0px 20px 0px;\n    border-top: 1px solid #D4D4D4;\n}\n\n.help-page-table th {\n    text-align: left;\n    font-weight: bold;\n    border-bottom: 1px solid #D4D4D4;\n    padding: 5px 6px 5px 6px;\n}\n\n.help-page-table td {\n    border-bottom: 1px solid #D4D4D4;\n    padding: 10px 8px 10px 8px;\n    vertical-align: top;\n}\n\n.help-page-table pre,\n.help-page-table p {\n    margin: 0px;\n    padding: 0px;\n    font-family: inherit;\n    font-size: 100%;\n}\n\n.help-page-table tbody tr:hover td {\n    background-color: #F3F3F3;\n}\n\n.help-page a:hover {\n    background-color: transparent;\n}\n\n.help-page .sample-header {\n    border: 2px solid #D4D4D4;\n    background: #00497E;\n    color: #FFFFFF;\n    padding: 8px 15px;\n    border-bottom: none;\n    display: inline-block;\n    margin: 10px 0px 0px 0px;\n}\n\n.help-page .sample-content {\n    display: block;\n    border-width: 0;\n    padding: 15px 20px;\n    background: #FFFFFF;\n    border: 2px solid #D4D4D4;\n    margin: 0px 0px 10px 0px;\n}\n\n.help-page .api-name {\n    width: 40%;\n}\n\n.help-page .api-documentation {\n    width: 60%;\n}\n\n.help-page .parameter-name {\n    width: 20%;\n}\n\n.help-page .parameter-documentation {\n    width: 40%;\n}\n\n.help-page .parameter-type {\n    width: 20%;\n}\n\n.help-page .parameter-annotations {\n    width: 20%;\n}\n\n.help-page h1,\n.help-page .h1 {\n    font-size: 36px;\n    line-height: normal;\n}\n\n.help-page h2,\n.help-page .h2 {\n    font-size: 24px;\n}\n\n.help-page h3,\n.help-page .h3 {\n    font-size: 20px;\n}\n\n#body.help-page {\n    font-size: 14px;\n    line-height: 143%;\n    color: #333;\n}\n\n.help-page a {\n    color: #0000EE;\n    text-decoration: none;\n}\n"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/HelpPageAreaRegistration.cs",
    "content": "﻿using System.Web.Http;\nusing System.Web.Mvc;\n\nnamespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage\n{\n    public class HelpPageAreaRegistration : AreaRegistration\n    {\n        public override string AreaName\n        {\n            get\n            {\n                return \"HelpPage\";\n            }\n        }\n\n        public override void RegisterArea(AreaRegistrationContext context)\n        {\n            context.MapRoute(\n                \"HelpPage_Default\",\n                \"Help/{action}/{apiId}\",\n                new { controller = \"Help\", action = \"Index\", apiId = UrlParameter.Optional });\n\n            HelpPageConfig.Register(GlobalConfiguration.Configuration);\n        }\n    }\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/HelpPageConfigurationExtensions.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Net.Http.Headers;\nusing System.Web.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Description;\nusing ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions;\nusing ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Models;\n\nnamespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage\n{\n    public static class HelpPageConfigurationExtensions\n    {\n        private const string ApiModelPrefix = \"MS_HelpPageApiModel_\";\n\n        /// <summary>\n        /// Sets the documentation provider for help page.\n        /// </summary>\n        /// <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        /// <param name=\"documentationProvider\">The documentation provider.</param>\n        public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)\n        {\n            config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);\n        }\n\n        /// <summary>\n        /// Sets the objects that will be used by the formatters to produce sample requests/responses.\n        /// </summary>\n        /// <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        /// <param name=\"sampleObjects\">The sample objects.</param>\n        public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)\n        {\n            config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;\n        }\n\n        /// <summary>\n        /// Sets the sample request directly for the specified media type and action.\n        /// </summary>\n        /// <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        /// <param name=\"sample\">The sample request.</param>\n        /// <param name=\"mediaType\">The media type.</param>\n        /// <param name=\"controllerName\">Name of the controller.</param>\n        /// <param name=\"actionName\">Name of the action.</param>\n        public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)\n        {\n            config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { \"*\" }), sample);\n        }\n\n        /// <summary>\n        /// Sets the sample request directly for the specified media type and action with parameters.\n        /// </summary>\n        /// <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        /// <param name=\"sample\">The sample request.</param>\n        /// <param name=\"mediaType\">The media type.</param>\n        /// <param name=\"controllerName\">Name of the controller.</param>\n        /// <param name=\"actionName\">Name of the action.</param>\n        /// <param name=\"parameterNames\">The parameter names.</param>\n        public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)\n        {\n            config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);\n        }\n\n        /// <summary>\n        /// Sets the sample request directly for the specified media type of the action.\n        /// </summary>\n        /// <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        /// <param name=\"sample\">The sample response.</param>\n        /// <param name=\"mediaType\">The media type.</param>\n        /// <param name=\"controllerName\">Name of the controller.</param>\n        /// <param name=\"actionName\">Name of the action.</param>\n        public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)\n        {\n            config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { \"*\" }), sample);\n        }\n\n        /// <summary>\n        /// Sets the sample response directly for the specified media type of the action with specific parameters.\n        /// </summary>\n        /// <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        /// <param name=\"sample\">The sample response.</param>\n        /// <param name=\"mediaType\">The media type.</param>\n        /// <param name=\"controllerName\">Name of the controller.</param>\n        /// <param name=\"actionName\">Name of the action.</param>\n        /// <param name=\"parameterNames\">The parameter names.</param>\n        public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)\n        {\n            config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);\n        }\n\n        /// <summary>\n        /// Sets the sample directly for all actions with the specified media type.\n        /// </summary>\n        /// <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        /// <param name=\"sample\">The sample.</param>\n        /// <param name=\"mediaType\">The media type.</param>\n        public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)\n        {\n            config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);\n        }\n\n        /// <summary>\n        /// Sets the sample directly for all actions with the specified type and media type.\n        /// </summary>\n        /// <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        /// <param name=\"sample\">The sample.</param>\n        /// <param name=\"mediaType\">The media type.</param>\n        /// <param name=\"type\">The parameter type or return type of an action.</param>\n        public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)\n        {\n            config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);\n        }\n\n        /// <summary>\n        /// Specifies the actual type of <see cref=\"System.Net.Http.ObjectContent{T}\"/> passed to the <see cref=\"System.Net.Http.HttpRequestMessage\"/> in an action.\n        /// The help page will use this information to produce more accurate request samples.\n        /// </summary>\n        /// <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        /// <param name=\"type\">The type.</param>\n        /// <param name=\"controllerName\">Name of the controller.</param>\n        /// <param name=\"actionName\">Name of the action.</param>\n        public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)\n        {\n            config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { \"*\" }), type);\n        }\n\n        /// <summary>\n        /// Specifies the actual type of <see cref=\"System.Net.Http.ObjectContent{T}\"/> passed to the <see cref=\"System.Net.Http.HttpRequestMessage\"/> in an action.\n        /// The help page will use this information to produce more accurate request samples.\n        /// </summary>\n        /// <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        /// <param name=\"type\">The type.</param>\n        /// <param name=\"controllerName\">Name of the controller.</param>\n        /// <param name=\"actionName\">Name of the action.</param>\n        /// <param name=\"parameterNames\">The parameter names.</param>\n        public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)\n        {\n            config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);\n        }\n\n        /// <summary>\n        /// Specifies the actual type of <see cref=\"System.Net.Http.ObjectContent{T}\"/> returned as part of the <see cref=\"System.Net.Http.HttpRequestMessage\"/> in an action.\n        /// The help page will use this information to produce more accurate response samples.\n        /// </summary>\n        /// <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        /// <param name=\"type\">The type.</param>\n        /// <param name=\"controllerName\">Name of the controller.</param>\n        /// <param name=\"actionName\">Name of the action.</param>\n        public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)\n        {\n            config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { \"*\" }), type);\n        }\n\n        /// <summary>\n        /// Specifies the actual type of <see cref=\"System.Net.Http.ObjectContent{T}\"/> returned as part of the <see cref=\"System.Net.Http.HttpRequestMessage\"/> in an action.\n        /// The help page will use this information to produce more accurate response samples.\n        /// </summary>\n        /// <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        /// <param name=\"type\">The type.</param>\n        /// <param name=\"controllerName\">Name of the controller.</param>\n        /// <param name=\"actionName\">Name of the action.</param>\n        /// <param name=\"parameterNames\">The parameter names.</param>\n        public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)\n        {\n            config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);\n        }\n\n        /// <summary>\n        /// Gets the help page sample generator.\n        /// </summary>\n        /// <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        /// <returns>The help page sample generator.</returns>\n        public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)\n        {\n            return (HelpPageSampleGenerator)config.Properties.GetOrAdd(\n                typeof(HelpPageSampleGenerator),\n                k => new HelpPageSampleGenerator());\n        }\n\n        /// <summary>\n        /// Sets the help page sample generator.\n        /// </summary>\n        /// <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        /// <param name=\"sampleGenerator\">The help page sample generator.</param>\n        public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)\n        {\n            config.Properties.AddOrUpdate(\n                typeof(HelpPageSampleGenerator),\n                k => sampleGenerator,\n                (k, o) => sampleGenerator);\n        }\n\n        /// <summary>\n        /// Gets the model description generator.\n        /// </summary>\n        /// <param name=\"config\">The configuration.</param>\n        /// <returns>The <see cref=\"ModelDescriptionGenerator\"/></returns>\n        public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)\n        {\n            return (ModelDescriptionGenerator)config.Properties.GetOrAdd(\n                typeof(ModelDescriptionGenerator),\n                k => InitializeModelDescriptionGenerator(config));\n        }\n\n        /// <summary>\n        /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.\n        /// </summary>\n        /// <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        /// <param name=\"apiDescriptionId\">The <see cref=\"ApiDescription\"/> ID.</param>\n        /// <returns>\n        /// An <see cref=\"HelpPageApiModel\"/>\n        /// </returns>\n        public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)\n        {\n            object model;\n            string modelId = ApiModelPrefix + apiDescriptionId;\n            if (!config.Properties.TryGetValue(modelId, out model))\n            {\n                Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;\n                ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));\n                if (apiDescription != null)\n                {\n                    model = GenerateApiModel(apiDescription, config);\n                    config.Properties.TryAdd(modelId, model);\n                }\n            }\n\n            return (HelpPageApiModel)model;\n        }\n\n        private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)\n        {\n            HelpPageApiModel apiModel = new HelpPageApiModel()\n            {\n                ApiDescription = apiDescription,\n            };\n\n            ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();\n            HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();\n            GenerateUriParameters(apiModel, modelGenerator);\n            GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);\n            GenerateResourceDescription(apiModel, modelGenerator);\n            GenerateSamples(apiModel, sampleGenerator);\n\n            return apiModel;\n        }\n\n        private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)\n        {\n            ApiDescription apiDescription = apiModel.ApiDescription;\n            foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)\n            {\n                if (apiParameter.Source == ApiParameterSource.FromUri)\n                {\n                    HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;\n                    Type parameterType = null;\n                    ModelDescription typeDescription = null;\n                    ComplexTypeModelDescription complexTypeDescription = null;\n                    if (parameterDescriptor != null)\n                    {\n                        parameterType = parameterDescriptor.ParameterType;\n                        typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);\n                        complexTypeDescription = typeDescription as ComplexTypeModelDescription;\n                    }\n\n                    // Example:\n                    // [TypeConverter(typeof(PointConverter))]\n                    // public class Point\n                    // {\n                    //     public Point(int x, int y)\n                    //     {\n                    //         X = x;\n                    //         Y = y;\n                    //     }\n                    //     public int X { get; set; }\n                    //     public int Y { get; set; }\n                    // }\n                    // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.\n                    // \n                    // public class Point\n                    // {\n                    //     public int X { get; set; }\n                    //     public int Y { get; set; }\n                    // }\n                    // Regular complex class Point will have properties X and Y added to UriParameters collection.\n                    if (complexTypeDescription != null\n                        && !IsBindableWithTypeConverter(parameterType))\n                    {\n                        foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)\n                        {\n                            apiModel.UriParameters.Add(uriParameter);\n                        }\n                    }\n                    else if (parameterDescriptor != null)\n                    {\n                        ParameterDescription uriParameter =\n                            AddParameterDescription(apiModel, apiParameter, typeDescription);\n\n                        if (!parameterDescriptor.IsOptional)\n                        {\n                            uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = \"Required\" });\n                        }\n\n                        object defaultValue = parameterDescriptor.DefaultValue;\n                        if (defaultValue != null)\n                        {\n                            uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = \"Default value is \" + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });\n                        }\n                    }\n                    else\n                    {\n                        Debug.Assert(parameterDescriptor == null);\n\n                        // If parameterDescriptor is null, this is an undeclared route parameter which only occurs\n                        // when source is FromUri. Ignored in request model and among resource parameters but listed\n                        // as a simple string here.\n                        ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));\n                        AddParameterDescription(apiModel, apiParameter, modelDescription);\n                    }\n                }\n            }\n        }\n\n        private static bool IsBindableWithTypeConverter(Type parameterType)\n        {\n            if (parameterType == null)\n            {\n                return false;\n            }\n\n            return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));\n        }\n\n        private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,\n            ApiParameterDescription apiParameter, ModelDescription typeDescription)\n        {\n            ParameterDescription parameterDescription = new ParameterDescription\n            {\n                Name = apiParameter.Name,\n                Documentation = apiParameter.Documentation,\n                TypeDescription = typeDescription,\n            };\n\n            apiModel.UriParameters.Add(parameterDescription);\n            return parameterDescription;\n        }\n\n        private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)\n        {\n            ApiDescription apiDescription = apiModel.ApiDescription;\n            foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)\n            {\n                if (apiParameter.Source == ApiParameterSource.FromBody)\n                {\n                    Type parameterType = apiParameter.ParameterDescriptor.ParameterType;\n                    apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);\n                    apiModel.RequestDocumentation = apiParameter.Documentation;\n                }\n                else if (apiParameter.ParameterDescriptor != null &&\n                    apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))\n                {\n                    Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);\n\n                    if (parameterType != null)\n                    {\n                        apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);\n                    }\n                }\n            }\n        }\n\n        private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)\n        {\n            ResponseDescription response = apiModel.ApiDescription.ResponseDescription;\n            Type responseType = response.ResponseType ?? response.DeclaredType;\n            if (responseType != null && responseType != typeof(void))\n            {\n                apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"The exception is recorded as ErrorMessages.\")]\n        private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)\n        {\n            try\n            {\n                foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))\n                {\n                    apiModel.SampleRequests.Add(item.Key, item.Value);\n                    LogInvalidSampleAsError(apiModel, item.Value);\n                }\n\n                foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))\n                {\n                    apiModel.SampleResponses.Add(item.Key, item.Value);\n                    LogInvalidSampleAsError(apiModel, item.Value);\n                }\n            }\n            catch (Exception e)\n            {\n                apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,\n                    \"An exception has occurred while generating the sample. Exception message: {0}\",\n                    HelpPageSampleGenerator.UnwrapException(e).Message));\n            }\n        }\n\n        private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)\n        {\n            parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(\n                p => p.Source == ApiParameterSource.FromBody ||\n                    (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));\n\n            if (parameterDescription == null)\n            {\n                resourceType = null;\n                return false;\n            }\n\n            resourceType = parameterDescription.ParameterDescriptor.ParameterType;\n\n            if (resourceType == typeof(HttpRequestMessage))\n            {\n                HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();\n                resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);\n            }\n\n            if (resourceType == null)\n            {\n                parameterDescription = null;\n                return false;\n            }\n\n            return true;\n        }\n\n        private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)\n        {\n            ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);\n            Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;\n            foreach (ApiDescription api in apis)\n            {\n                ApiParameterDescription parameterDescription;\n                Type parameterType;\n                if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))\n                {\n                    modelGenerator.GetOrCreateModelDescription(parameterType);\n                }\n            }\n            return modelGenerator;\n        }\n\n        private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)\n        {\n            InvalidSample invalidSample = sample as InvalidSample;\n            if (invalidSample != null)\n            {\n                apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/ModelDescriptions/CollectionModelDescription.cs",
    "content": "﻿namespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n{\n    public class CollectionModelDescription : ModelDescription\n    {\n        public ModelDescription ElementDescription { get; set; }\n    }\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/ModelDescriptions/ComplexTypeModelDescription.cs",
    "content": "﻿using System.Collections.ObjectModel;\n\nnamespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n{\n    public class ComplexTypeModelDescription : ModelDescription\n    {\n        public ComplexTypeModelDescription()\n        {\n            Properties = new Collection<ParameterDescription>();\n        }\n\n        public Collection<ParameterDescription> Properties { get; private set; }\n    }\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/ModelDescriptions/DictionaryModelDescription.cs",
    "content": "﻿namespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n{\n    public class DictionaryModelDescription : KeyValuePairModelDescription\n    {\n    }\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/ModelDescriptions/EnumTypeModelDescription.cs",
    "content": "﻿using System.Collections.Generic;\nusing System.Collections.ObjectModel;\n\nnamespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n{\n    public class EnumTypeModelDescription : ModelDescription\n    {\n        public EnumTypeModelDescription()\n        {\n            Values = new Collection<EnumValueDescription>();\n        }\n\n        public Collection<EnumValueDescription> Values { get; private set; }\n    }\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/ModelDescriptions/EnumValueDescription.cs",
    "content": "﻿namespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n{\n    public class EnumValueDescription\n    {\n        public string Documentation { get; set; }\n\n        public string Name { get; set; }\n\n        public string Value { get; set; }\n    }\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/ModelDescriptions/IModelDocumentationProvider.cs",
    "content": "using System;\nusing System.Reflection;\n\nnamespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n{\n    public interface IModelDocumentationProvider\n    {\n        string GetDocumentation(MemberInfo member);\n\n        string GetDocumentation(Type type);\n    }\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/ModelDescriptions/KeyValuePairModelDescription.cs",
    "content": "﻿namespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n{\n    public class KeyValuePairModelDescription : ModelDescription\n    {\n        public ModelDescription KeyModelDescription { get; set; }\n\n        public ModelDescription ValueModelDescription { get; set; }\n    }\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/ModelDescriptions/ModelDescription.cs",
    "content": "﻿using System;\n\nnamespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n{\n    /// <summary>\n    /// Describes a type model.\n    /// </summary>\n    public abstract class ModelDescription\n    {\n        public string Documentation { get; set; }\n\n        public Type ModelType { get; set; }\n\n        public string Name { get; set; }\n    }\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/ModelDescriptions/ModelDescriptionGenerator.cs",
    "content": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.ComponentModel.DataAnnotations;\nusing System.Globalization;\nusing System.Reflection;\nusing System.Runtime.Serialization;\nusing System.Web.Http;\nusing System.Web.Http.Description;\nusing System.Xml.Serialization;\nusing Newtonsoft.Json;\n\nnamespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n{\n    /// <summary>\n    /// Generates model descriptions for given types.\n    /// </summary>\n    public class ModelDescriptionGenerator\n    {\n        // Modify this to support more data annotation attributes.\n        private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>\n        {\n            { typeof(RequiredAttribute), a => \"Required\" },\n            { typeof(RangeAttribute), a =>\n                {\n                    RangeAttribute range = (RangeAttribute)a;\n                    return String.Format(CultureInfo.CurrentCulture, \"Range: inclusive between {0} and {1}\", range.Minimum, range.Maximum);\n                }\n            },\n            { typeof(MaxLengthAttribute), a =>\n                {\n                    MaxLengthAttribute maxLength = (MaxLengthAttribute)a;\n                    return String.Format(CultureInfo.CurrentCulture, \"Max length: {0}\", maxLength.Length);\n                }\n            },\n            { typeof(MinLengthAttribute), a =>\n                {\n                    MinLengthAttribute minLength = (MinLengthAttribute)a;\n                    return String.Format(CultureInfo.CurrentCulture, \"Min length: {0}\", minLength.Length);\n                }\n            },\n            { typeof(StringLengthAttribute), a =>\n                {\n                    StringLengthAttribute strLength = (StringLengthAttribute)a;\n                    return String.Format(CultureInfo.CurrentCulture, \"String length: inclusive between {0} and {1}\", strLength.MinimumLength, strLength.MaximumLength);\n                }\n            },\n            { typeof(DataTypeAttribute), a =>\n                {\n                    DataTypeAttribute dataType = (DataTypeAttribute)a;\n                    return String.Format(CultureInfo.CurrentCulture, \"Data type: {0}\", dataType.CustomDataType ?? dataType.DataType.ToString());\n                }\n            },\n            { typeof(RegularExpressionAttribute), a =>\n                {\n                    RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;\n                    return String.Format(CultureInfo.CurrentCulture, \"Matching regular expression pattern: {0}\", regularExpression.Pattern);\n                }\n            },\n        };\n\n        // Modify this to add more default documentations.\n        private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>\n        {\n            { typeof(Int16), \"integer\" },\n            { typeof(Int32), \"integer\" },\n            { typeof(Int64), \"integer\" },\n            { typeof(UInt16), \"unsigned integer\" },\n            { typeof(UInt32), \"unsigned integer\" },\n            { typeof(UInt64), \"unsigned integer\" },\n            { typeof(Byte), \"byte\" },\n            { typeof(Char), \"character\" },\n            { typeof(SByte), \"signed byte\" },\n            { typeof(Uri), \"URI\" },\n            { typeof(Single), \"decimal number\" },\n            { typeof(Double), \"decimal number\" },\n            { typeof(Decimal), \"decimal number\" },\n            { typeof(String), \"string\" },\n            { typeof(Guid), \"globally unique identifier\" },\n            { typeof(TimeSpan), \"time interval\" },\n            { typeof(DateTime), \"date\" },\n            { typeof(DateTimeOffset), \"date\" },\n            { typeof(Boolean), \"boolean\" },\n        };\n\n        private Lazy<IModelDocumentationProvider> _documentationProvider;\n\n        public ModelDescriptionGenerator(HttpConfiguration config)\n        {\n            if (config == null)\n            {\n                throw new ArgumentNullException(\"config\");\n            }\n\n            _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);\n            GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);\n        }\n\n        public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }\n\n        private IModelDocumentationProvider DocumentationProvider\n        {\n            get\n            {\n                return _documentationProvider.Value;\n            }\n        }\n\n        public ModelDescription GetOrCreateModelDescription(Type modelType)\n        {\n            if (modelType == null)\n            {\n                throw new ArgumentNullException(\"modelType\");\n            }\n\n            Type underlyingType = Nullable.GetUnderlyingType(modelType);\n            if (underlyingType != null)\n            {\n                modelType = underlyingType;\n            }\n\n            ModelDescription modelDescription;\n            string modelName = ModelNameHelper.GetModelName(modelType);\n            if (GeneratedModels.TryGetValue(modelName, out modelDescription))\n            {\n                if (modelType != modelDescription.ModelType)\n                {\n                    throw new InvalidOperationException(\n                        String.Format(\n                            CultureInfo.CurrentCulture,\n                            \"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. \" +\n                            \"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.\",\n                            modelName,\n                            modelDescription.ModelType.FullName,\n                            modelType.FullName));\n                }\n\n                return modelDescription;\n            }\n\n            if (DefaultTypeDocumentation.ContainsKey(modelType))\n            {\n                return GenerateSimpleTypeModelDescription(modelType);\n            }\n\n            if (modelType.IsEnum)\n            {\n                return GenerateEnumTypeModelDescription(modelType);\n            }\n\n            if (modelType.IsGenericType)\n            {\n                Type[] genericArguments = modelType.GetGenericArguments();\n\n                if (genericArguments.Length == 1)\n                {\n                    Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);\n                    if (enumerableType.IsAssignableFrom(modelType))\n                    {\n                        return GenerateCollectionModelDescription(modelType, genericArguments[0]);\n                    }\n                }\n                if (genericArguments.Length == 2)\n                {\n                    Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);\n                    if (dictionaryType.IsAssignableFrom(modelType))\n                    {\n                        return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);\n                    }\n\n                    Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);\n                    if (keyValuePairType.IsAssignableFrom(modelType))\n                    {\n                        return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);\n                    }\n                }\n            }\n\n            if (modelType.IsArray)\n            {\n                Type elementType = modelType.GetElementType();\n                return GenerateCollectionModelDescription(modelType, elementType);\n            }\n\n            if (modelType == typeof(NameValueCollection))\n            {\n                return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));\n            }\n\n            if (typeof(IDictionary).IsAssignableFrom(modelType))\n            {\n                return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));\n            }\n\n            if (typeof(IEnumerable).IsAssignableFrom(modelType))\n            {\n                return GenerateCollectionModelDescription(modelType, typeof(object));\n            }\n\n            return GenerateComplexTypeModelDescription(modelType);\n        }\n\n        // Change this to provide different name for the member.\n        private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)\n        {\n            JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();\n            if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))\n            {\n                return jsonProperty.PropertyName;\n            }\n\n            if (hasDataContractAttribute)\n            {\n                DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();\n                if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))\n                {\n                    return dataMember.Name;\n                }\n            }\n\n            return member.Name;\n        }\n\n        private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)\n        {\n            JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();\n            XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();\n            IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();\n            NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();\n            ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();\n\n            bool hasMemberAttribute = member.DeclaringType.IsEnum ?\n                member.GetCustomAttribute<EnumMemberAttribute>() != null :\n                member.GetCustomAttribute<DataMemberAttribute>() != null;\n\n            // Display member only if all the followings are true:\n            // no JsonIgnoreAttribute\n            // no XmlIgnoreAttribute\n            // no IgnoreDataMemberAttribute\n            // no NonSerializedAttribute\n            // no ApiExplorerSettingsAttribute with IgnoreApi set to true\n            // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute\n            return jsonIgnore == null &&\n                xmlIgnore == null &&\n                ignoreDataMember == null &&\n                nonSerialized == null &&\n                (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&\n                (!hasDataContractAttribute || hasMemberAttribute);\n        }\n\n        private string CreateDefaultDocumentation(Type type)\n        {\n            string documentation;\n            if (DefaultTypeDocumentation.TryGetValue(type, out documentation))\n            {\n                return documentation;\n            }\n            if (DocumentationProvider != null)\n            {\n                documentation = DocumentationProvider.GetDocumentation(type);\n            }\n\n            return documentation;\n        }\n\n        private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)\n        {\n            List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();\n\n            IEnumerable<Attribute> attributes = property.GetCustomAttributes();\n            foreach (Attribute attribute in attributes)\n            {\n                Func<object, string> textGenerator;\n                if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))\n                {\n                    annotations.Add(\n                        new ParameterAnnotation\n                        {\n                            AnnotationAttribute = attribute,\n                            Documentation = textGenerator(attribute)\n                        });\n                }\n            }\n\n            // Rearrange the annotations\n            annotations.Sort((x, y) =>\n            {\n                // Special-case RequiredAttribute so that it shows up on top\n                if (x.AnnotationAttribute is RequiredAttribute)\n                {\n                    return -1;\n                }\n                if (y.AnnotationAttribute is RequiredAttribute)\n                {\n                    return 1;\n                }\n\n                // Sort the rest based on alphabetic order of the documentation\n                return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);\n            });\n\n            foreach (ParameterAnnotation annotation in annotations)\n            {\n                propertyModel.Annotations.Add(annotation);\n            }\n        }\n\n        private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)\n        {\n            ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);\n            if (collectionModelDescription != null)\n            {\n                return new CollectionModelDescription\n                {\n                    Name = ModelNameHelper.GetModelName(modelType),\n                    ModelType = modelType,\n                    ElementDescription = collectionModelDescription\n                };\n            }\n\n            return null;\n        }\n\n        private ModelDescription GenerateComplexTypeModelDescription(Type modelType)\n        {\n            ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription\n            {\n                Name = ModelNameHelper.GetModelName(modelType),\n                ModelType = modelType,\n                Documentation = CreateDefaultDocumentation(modelType)\n            };\n\n            GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);\n            bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;\n            PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);\n            foreach (PropertyInfo property in properties)\n            {\n                if (ShouldDisplayMember(property, hasDataContractAttribute))\n                {\n                    ParameterDescription propertyModel = new ParameterDescription\n                    {\n                        Name = GetMemberName(property, hasDataContractAttribute)\n                    };\n\n                    if (DocumentationProvider != null)\n                    {\n                        propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);\n                    }\n\n                    GenerateAnnotations(property, propertyModel);\n                    complexModelDescription.Properties.Add(propertyModel);\n                    propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);\n                }\n            }\n\n            FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);\n            foreach (FieldInfo field in fields)\n            {\n                if (ShouldDisplayMember(field, hasDataContractAttribute))\n                {\n                    ParameterDescription propertyModel = new ParameterDescription\n                    {\n                        Name = GetMemberName(field, hasDataContractAttribute)\n                    };\n\n                    if (DocumentationProvider != null)\n                    {\n                        propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);\n                    }\n\n                    complexModelDescription.Properties.Add(propertyModel);\n                    propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);\n                }\n            }\n\n            return complexModelDescription;\n        }\n\n        private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)\n        {\n            ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);\n            ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);\n\n            return new DictionaryModelDescription\n            {\n                Name = ModelNameHelper.GetModelName(modelType),\n                ModelType = modelType,\n                KeyModelDescription = keyModelDescription,\n                ValueModelDescription = valueModelDescription\n            };\n        }\n\n        private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)\n        {\n            EnumTypeModelDescription enumDescription = new EnumTypeModelDescription\n            {\n                Name = ModelNameHelper.GetModelName(modelType),\n                ModelType = modelType,\n                Documentation = CreateDefaultDocumentation(modelType)\n            };\n            bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;\n            foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))\n            {\n                if (ShouldDisplayMember(field, hasDataContractAttribute))\n                {\n                    EnumValueDescription enumValue = new EnumValueDescription\n                    {\n                        Name = field.Name,\n                        Value = field.GetRawConstantValue().ToString()\n                    };\n                    if (DocumentationProvider != null)\n                    {\n                        enumValue.Documentation = DocumentationProvider.GetDocumentation(field);\n                    }\n                    enumDescription.Values.Add(enumValue);\n                }\n            }\n            GeneratedModels.Add(enumDescription.Name, enumDescription);\n\n            return enumDescription;\n        }\n\n        private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)\n        {\n            ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);\n            ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);\n\n            return new KeyValuePairModelDescription\n            {\n                Name = ModelNameHelper.GetModelName(modelType),\n                ModelType = modelType,\n                KeyModelDescription = keyModelDescription,\n                ValueModelDescription = valueModelDescription\n            };\n        }\n\n        private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)\n        {\n            SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription\n            {\n                Name = ModelNameHelper.GetModelName(modelType),\n                ModelType = modelType,\n                Documentation = CreateDefaultDocumentation(modelType)\n            };\n            GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);\n\n            return simpleModelDescription;\n        }\n    }\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/ModelDescriptions/ModelNameAttribute.cs",
    "content": "﻿using System;\n\nnamespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n{\n    /// <summary>\n    /// Use this attribute to change the name of the <see cref=\"ModelDescription\"/> generated for a type.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum, AllowMultiple = false, Inherited = false)]\n    public sealed class ModelNameAttribute : Attribute\n    {\n        public ModelNameAttribute(string name)\n        {\n            Name = name;\n        }\n\n        public string Name { get; private set; }\n    }\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/ModelDescriptions/ModelNameHelper.cs",
    "content": "﻿using System;\nusing System.Globalization;\nusing System.Linq;\nusing System.Reflection;\n\nnamespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n{\n    internal static class ModelNameHelper\n    {\n        // Modify this to provide custom model name mapping.\n        public static string GetModelName(Type type)\n        {\n            ModelNameAttribute modelNameAttribute = type.GetCustomAttribute<ModelNameAttribute>();\n            if (modelNameAttribute != null && !String.IsNullOrEmpty(modelNameAttribute.Name))\n            {\n                return modelNameAttribute.Name;\n            }\n\n            string modelName = type.Name;\n            if (type.IsGenericType)\n            {\n                // Format the generic type name to something like: GenericOfAgurment1AndArgument2\n                Type genericType = type.GetGenericTypeDefinition();\n                Type[] genericArguments = type.GetGenericArguments();\n                string genericTypeName = genericType.Name;\n\n                // Trim the generic parameter counts from the name\n                genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`'));\n                string[] argumentTypeNames = genericArguments.Select(t => GetModelName(t)).ToArray();\n                modelName = String.Format(CultureInfo.InvariantCulture, \"{0}Of{1}\", genericTypeName, String.Join(\"And\", argumentTypeNames));\n            }\n\n            return modelName;\n        }\n    }\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/ModelDescriptions/ParameterAnnotation.cs",
    "content": "﻿using System;\n\nnamespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n{\n    public class ParameterAnnotation\n    {\n        public Attribute AnnotationAttribute { get; set; }\n\n        public string Documentation { get; set; }\n    }\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/ModelDescriptions/ParameterDescription.cs",
    "content": "﻿using System.Collections.Generic;\nusing System.Collections.ObjectModel;\n\nnamespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n{\n    public class ParameterDescription\n    {\n        public ParameterDescription()\n        {\n            Annotations = new Collection<ParameterAnnotation>();\n        }\n\n        public Collection<ParameterAnnotation> Annotations { get; private set; }\n\n        public string Documentation { get; set; }\n\n        public string Name { get; set; }\n\n        public ModelDescription TypeDescription { get; set; }\n    }\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/ModelDescriptions/SimpleTypeModelDescription.cs",
    "content": "﻿namespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n{\n    public class SimpleTypeModelDescription : ModelDescription\n    {\n    }\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/Models/HelpPageApiModel.cs",
    "content": "﻿using System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Net.Http.Headers;\nusing System.Web.Http.Description;\nusing ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions;\n\nnamespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Models\n{\n    /// <summary>\n    /// The model that represents an API displayed on the help page.\n    /// </summary>\n    public class HelpPageApiModel\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HelpPageApiModel\"/> class.\n        /// </summary>\n        public HelpPageApiModel()\n        {\n            UriParameters = new Collection<ParameterDescription>();\n            SampleRequests = new Dictionary<MediaTypeHeaderValue, object>();\n            SampleResponses = new Dictionary<MediaTypeHeaderValue, object>();\n            ErrorMessages = new Collection<string>();\n        }\n\n        /// <summary>\n        /// Gets or sets the <see cref=\"ApiDescription\"/> that describes the API.\n        /// </summary>\n        public ApiDescription ApiDescription { get; set; }\n\n        /// <summary>\n        /// Gets or sets the <see cref=\"ParameterDescription\"/> collection that describes the URI parameters for the API.\n        /// </summary>\n        public Collection<ParameterDescription> UriParameters { get; private set; }\n\n        /// <summary>\n        /// Gets or sets the documentation for the request.\n        /// </summary>\n        public string RequestDocumentation { get; set; }\n\n        /// <summary>\n        /// Gets or sets the <see cref=\"ModelDescription\"/> that describes the request body.\n        /// </summary>\n        public ModelDescription RequestModelDescription { get; set; }\n\n        /// <summary>\n        /// Gets the request body parameter descriptions.\n        /// </summary>\n        public IList<ParameterDescription> RequestBodyParameters\n        {\n            get\n            {\n                return GetParameterDescriptions(RequestModelDescription);\n            }\n        }\n\n        /// <summary>\n        /// Gets or sets the <see cref=\"ModelDescription\"/> that describes the resource.\n        /// </summary>\n        public ModelDescription ResourceDescription { get; set; }\n\n        /// <summary>\n        /// Gets the resource property descriptions.\n        /// </summary>\n        public IList<ParameterDescription> ResourceProperties\n        {\n            get\n            {\n                return GetParameterDescriptions(ResourceDescription);\n            }\n        }\n\n        /// <summary>\n        /// Gets the sample requests associated with the API.\n        /// </summary>\n        public IDictionary<MediaTypeHeaderValue, object> SampleRequests { get; private set; }\n\n        /// <summary>\n        /// Gets the sample responses associated with the API.\n        /// </summary>\n        public IDictionary<MediaTypeHeaderValue, object> SampleResponses { get; private set; }\n\n        /// <summary>\n        /// Gets the error messages associated with this model.\n        /// </summary>\n        public Collection<string> ErrorMessages { get; private set; }\n\n        private static IList<ParameterDescription> GetParameterDescriptions(ModelDescription modelDescription)\n        {\n            ComplexTypeModelDescription complexTypeModelDescription = modelDescription as ComplexTypeModelDescription;\n            if (complexTypeModelDescription != null)\n            {\n                return complexTypeModelDescription.Properties;\n            }\n\n            CollectionModelDescription collectionModelDescription = modelDescription as CollectionModelDescription;\n            if (collectionModelDescription != null)\n            {\n                complexTypeModelDescription = collectionModelDescription.ElementDescription as ComplexTypeModelDescription;\n                if (complexTypeModelDescription != null)\n                {\n                    return complexTypeModelDescription.Properties;\n                }\n            }\n\n            return null;\n        }\n    }\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/SampleGeneration/HelpPageSampleGenerator.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Web.Http.Description;\nusing System.Xml.Linq;\nusing Newtonsoft.Json;\n\nnamespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage\n{\n    /// <summary>\n    /// This class will generate the samples for the help page.\n    /// </summary>\n    public class HelpPageSampleGenerator\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"HelpPageSampleGenerator\"/> class.\n        /// </summary>\n        public HelpPageSampleGenerator()\n        {\n            ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();\n            ActionSamples = new Dictionary<HelpPageSampleKey, object>();\n            SampleObjects = new Dictionary<Type, object>();\n            SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>\n            {\n                DefaultSampleObjectFactory,\n            };\n        }\n\n        /// <summary>\n        /// Gets CLR types that are used as the content of <see cref=\"HttpRequestMessage\"/> or <see cref=\"HttpResponseMessage\"/>.\n        /// </summary>\n        public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }\n\n        /// <summary>\n        /// Gets the objects that are used directly as samples for certain actions.\n        /// </summary>\n        public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }\n\n        /// <summary>\n        /// Gets the objects that are serialized as samples by the supported formatters.\n        /// </summary>\n        public IDictionary<Type, object> SampleObjects { get; internal set; }\n\n        /// <summary>\n        /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,\n        /// stopping when the factory successfully returns a non-<see langref=\"null\"/> object.\n        /// </summary>\n        /// <remarks>\n        /// Collection includes just <see cref=\"ObjectGenerator.GenerateObject(Type)\"/> initially. Use\n        /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and\n        /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\",\n            Justification = \"This is an appropriate nesting of generic types\")]\n        public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }\n\n        /// <summary>\n        /// Gets the request body samples for a given <see cref=\"ApiDescription\"/>.\n        /// </summary>\n        /// <param name=\"api\">The <see cref=\"ApiDescription\"/>.</param>\n        /// <returns>The samples keyed by media type.</returns>\n        public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)\n        {\n            return GetSample(api, SampleDirection.Request);\n        }\n\n        /// <summary>\n        /// Gets the response body samples for a given <see cref=\"ApiDescription\"/>.\n        /// </summary>\n        /// <param name=\"api\">The <see cref=\"ApiDescription\"/>.</param>\n        /// <returns>The samples keyed by media type.</returns>\n        public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)\n        {\n            return GetSample(api, SampleDirection.Response);\n        }\n\n        /// <summary>\n        /// Gets the request or response body samples.\n        /// </summary>\n        /// <param name=\"api\">The <see cref=\"ApiDescription\"/>.</param>\n        /// <param name=\"sampleDirection\">The value indicating whether the sample is for a request or for a response.</param>\n        /// <returns>The samples keyed by media type.</returns>\n        public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)\n        {\n            if (api == null)\n            {\n                throw new ArgumentNullException(\"api\");\n            }\n            string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;\n            string actionName = api.ActionDescriptor.ActionName;\n            IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);\n            Collection<MediaTypeFormatter> formatters;\n            Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);\n            var samples = new Dictionary<MediaTypeHeaderValue, object>();\n\n            // Use the samples provided directly for actions\n            var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);\n            foreach (var actionSample in actionSamples)\n            {\n                samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));\n            }\n\n            // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.\n            // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.\n            if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))\n            {\n                object sampleObject = GetSampleObject(type);\n                foreach (var formatter in formatters)\n                {\n                    foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)\n                    {\n                        if (!samples.ContainsKey(mediaType))\n                        {\n                            object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);\n\n                            // If no sample found, try generate sample using formatter and sample object\n                            if (sample == null && sampleObject != null)\n                            {\n                                sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);\n                            }\n\n                            samples.Add(mediaType, WrapSampleIfString(sample));\n                        }\n                    }\n                }\n            }\n\n            return samples;\n        }\n\n        /// <summary>\n        /// Search for samples that are provided directly through <see cref=\"ActionSamples\"/>.\n        /// </summary>\n        /// <param name=\"controllerName\">Name of the controller.</param>\n        /// <param name=\"actionName\">Name of the action.</param>\n        /// <param name=\"parameterNames\">The parameter names.</param>\n        /// <param name=\"type\">The CLR type.</param>\n        /// <param name=\"formatter\">The formatter.</param>\n        /// <param name=\"mediaType\">The media type.</param>\n        /// <param name=\"sampleDirection\">The value indicating whether the sample is for a request or for a response.</param>\n        /// <returns>The sample that matches the parameters.</returns>\n        public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)\n        {\n            object sample;\n\n            // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.\n            // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.\n            // If still not found, try to get the sample provided for the specified mediaType and type.\n            // Finally, try to get the sample provided for the specified mediaType.\n            if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||\n                ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { \"*\" }), out sample) ||\n                ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||\n                ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))\n            {\n                return sample;\n            }\n\n            return null;\n        }\n\n        /// <summary>\n        /// Gets the sample object that will be serialized by the formatters. \n        /// First, it will look at the <see cref=\"SampleObjects\"/>. If no sample object is found, it will try to create\n        /// one using <see cref=\"DefaultSampleObjectFactory\"/> (which wraps an <see cref=\"ObjectGenerator\"/>) and other\n        /// factories in <see cref=\"SampleObjectFactories\"/>.\n        /// </summary>\n        /// <param name=\"type\">The type.</param>\n        /// <returns>The sample object.</returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\",\n            Justification = \"Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.\")]\n        public virtual object GetSampleObject(Type type)\n        {\n            object sampleObject;\n\n            if (!SampleObjects.TryGetValue(type, out sampleObject))\n            {\n                // No specific object available, try our factories.\n                foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)\n                {\n                    if (factory == null)\n                    {\n                        continue;\n                    }\n\n                    try\n                    {\n                        sampleObject = factory(this, type);\n                        if (sampleObject != null)\n                        {\n                            break;\n                        }\n                    }\n                    catch\n                    {\n                        // Ignore any problems encountered in the factory; go on to the next one (if any).\n                    }\n                }\n            }\n\n            return sampleObject;\n        }\n\n        /// <summary>\n        /// Resolves the actual type of <see cref=\"System.Net.Http.ObjectContent{T}\"/> passed to the <see cref=\"System.Net.Http.HttpRequestMessage\"/> in an action.\n        /// </summary>\n        /// <param name=\"api\">The <see cref=\"ApiDescription\"/>.</param>\n        /// <returns>The type.</returns>\n        public virtual Type ResolveHttpRequestMessageType(ApiDescription api)\n        {\n            string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;\n            string actionName = api.ActionDescriptor.ActionName;\n            IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);\n            Collection<MediaTypeFormatter> formatters;\n            return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);\n        }\n\n        /// <summary>\n        /// Resolves the type of the action parameter or return value when <see cref=\"HttpRequestMessage\"/> or <see cref=\"HttpResponseMessage\"/> is used.\n        /// </summary>\n        /// <param name=\"api\">The <see cref=\"ApiDescription\"/>.</param>\n        /// <param name=\"controllerName\">Name of the controller.</param>\n        /// <param name=\"actionName\">Name of the action.</param>\n        /// <param name=\"parameterNames\">The parameter names.</param>\n        /// <param name=\"sampleDirection\">The value indicating whether the sample is for a request or a response.</param>\n        /// <param name=\"formatters\">The formatters.</param>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1021:AvoidOutParameters\", Justification = \"This is only used in advanced scenarios.\")]\n        public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)\n        {\n            if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))\n            {\n                throw new InvalidEnumArgumentException(\"sampleDirection\", (int)sampleDirection, typeof(SampleDirection));\n            }\n            if (api == null)\n            {\n                throw new ArgumentNullException(\"api\");\n            }\n            Type type;\n            if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||\n                ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { \"*\" }), out type))\n            {\n                // Re-compute the supported formatters based on type\n                Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();\n                foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)\n                {\n                    if (IsFormatSupported(sampleDirection, formatter, type))\n                    {\n                        newFormatters.Add(formatter);\n                    }\n                }\n                formatters = newFormatters;\n            }\n            else\n            {\n                switch (sampleDirection)\n                {\n                    case SampleDirection.Request:\n                        ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);\n                        type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;\n                        formatters = api.SupportedRequestBodyFormatters;\n                        break;\n                    case SampleDirection.Response:\n                    default:\n                        type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;\n                        formatters = api.SupportedResponseFormatters;\n                        break;\n                }\n            }\n\n            return type;\n        }\n\n        /// <summary>\n        /// Writes the sample object using formatter.\n        /// </summary>\n        /// <param name=\"formatter\">The formatter.</param>\n        /// <param name=\"value\">The value.</param>\n        /// <param name=\"type\">The type.</param>\n        /// <param name=\"mediaType\">Type of the media.</param>\n        /// <returns></returns>\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"The exception is recorded as InvalidSample.\")]\n        public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)\n        {\n            if (formatter == null)\n            {\n                throw new ArgumentNullException(\"formatter\");\n            }\n            if (mediaType == null)\n            {\n                throw new ArgumentNullException(\"mediaType\");\n            }\n\n            object sample = String.Empty;\n            MemoryStream ms = null;\n            HttpContent content = null;\n            try\n            {\n                if (formatter.CanWriteType(type))\n                {\n                    ms = new MemoryStream();\n                    content = new ObjectContent(type, value, formatter, mediaType);\n                    formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();\n                    ms.Position = 0;\n                    StreamReader reader = new StreamReader(ms);\n                    string serializedSampleString = reader.ReadToEnd();\n                    if (mediaType.MediaType.ToUpperInvariant().Contains(\"XML\"))\n                    {\n                        serializedSampleString = TryFormatXml(serializedSampleString);\n                    }\n                    else if (mediaType.MediaType.ToUpperInvariant().Contains(\"JSON\"))\n                    {\n                        serializedSampleString = TryFormatJson(serializedSampleString);\n                    }\n\n                    sample = new TextSample(serializedSampleString);\n                }\n                else\n                {\n                    sample = new InvalidSample(String.Format(\n                        CultureInfo.CurrentCulture,\n                        \"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.\",\n                        mediaType,\n                        formatter.GetType().Name,\n                        type.Name));\n                }\n            }\n            catch (Exception e)\n            {\n                sample = new InvalidSample(String.Format(\n                    CultureInfo.CurrentCulture,\n                    \"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}\",\n                    formatter.GetType().Name,\n                    mediaType.MediaType,\n                    UnwrapException(e).Message));\n            }\n            finally\n            {\n                if (ms != null)\n                {\n                    ms.Dispose();\n                }\n                if (content != null)\n                {\n                    content.Dispose();\n                }\n            }\n\n            return sample;\n        }\n\n        internal static Exception UnwrapException(Exception exception)\n        {\n            AggregateException aggregateException = exception as AggregateException;\n            if (aggregateException != null)\n            {\n                return aggregateException.Flatten().InnerException;\n            }\n            return exception;\n        }\n\n        // Default factory for sample objects\n        private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)\n        {\n            // Try to create a default sample object\n            ObjectGenerator objectGenerator = new ObjectGenerator();\n            return objectGenerator.GenerateObject(type);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Handling the failure by returning the original string.\")]\n        private static string TryFormatJson(string str)\n        {\n            try\n            {\n                object parsedJson = JsonConvert.DeserializeObject(str);\n                return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);\n            }\n            catch\n            {\n                // can't parse JSON, return the original string\n                return str;\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Handling the failure by returning the original string.\")]\n        private static string TryFormatXml(string str)\n        {\n            try\n            {\n                XDocument xml = XDocument.Parse(str);\n                return xml.ToString();\n            }\n            catch\n            {\n                // can't parse XML, return the original string\n                return str;\n            }\n        }\n\n        private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)\n        {\n            switch (sampleDirection)\n            {\n                case SampleDirection.Request:\n                    return formatter.CanReadType(type);\n                case SampleDirection.Response:\n                    return formatter.CanWriteType(type);\n            }\n            return false;\n        }\n\n        private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)\n        {\n            HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);\n            foreach (var sample in ActionSamples)\n            {\n                HelpPageSampleKey sampleKey = sample.Key;\n                if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&\n                    String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&\n                    (sampleKey.ParameterNames.SetEquals(new[] { \"*\" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&\n                    sampleDirection == sampleKey.SampleDirection)\n                {\n                    yield return sample;\n                }\n            }\n        }\n\n        private static object WrapSampleIfString(object sample)\n        {\n            string stringSample = sample as string;\n            if (stringSample != null)\n            {\n                return new TextSample(stringSample);\n            }\n\n            return sample;\n        }\n    }\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/SampleGeneration/HelpPageSampleKey.cs",
    "content": "﻿using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Net.Http.Headers;\n\nnamespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage\n{\n    /// <summary>\n    /// This is used to identify the place where the sample should be applied.\n    /// </summary>\n    public class HelpPageSampleKey\n    {\n        /// <summary>\n        /// Creates a new <see cref=\"HelpPageSampleKey\"/> based on media type.\n        /// </summary>\n        /// <param name=\"mediaType\">The media type.</param>\n        public HelpPageSampleKey(MediaTypeHeaderValue mediaType)\n        {\n            if (mediaType == null)\n            {\n                throw new ArgumentNullException(\"mediaType\");\n            }\n\n            ActionName = String.Empty;\n            ControllerName = String.Empty;\n            MediaType = mediaType;\n            ParameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);\n        }\n\n        /// <summary>\n        /// Creates a new <see cref=\"HelpPageSampleKey\"/> based on media type and CLR type.\n        /// </summary>\n        /// <param name=\"mediaType\">The media type.</param>\n        /// <param name=\"type\">The CLR type.</param>\n        public HelpPageSampleKey(MediaTypeHeaderValue mediaType, Type type)\n            : this(mediaType)\n        {\n            if (type == null)\n            {\n                throw new ArgumentNullException(\"type\");\n            }\n\n            ParameterType = type;\n        }\n\n        /// <summary>\n        /// Creates a new <see cref=\"HelpPageSampleKey\"/> based on <see cref=\"SampleDirection\"/>, controller name, action name and parameter names.\n        /// </summary>\n        /// <param name=\"sampleDirection\">The <see cref=\"SampleDirection\"/>.</param>\n        /// <param name=\"controllerName\">Name of the controller.</param>\n        /// <param name=\"actionName\">Name of the action.</param>\n        /// <param name=\"parameterNames\">The parameter names.</param>\n        public HelpPageSampleKey(SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames)\n        {\n            if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))\n            {\n                throw new InvalidEnumArgumentException(\"sampleDirection\", (int)sampleDirection, typeof(SampleDirection));\n            }\n            if (controllerName == null)\n            {\n                throw new ArgumentNullException(\"controllerName\");\n            }\n            if (actionName == null)\n            {\n                throw new ArgumentNullException(\"actionName\");\n            }\n            if (parameterNames == null)\n            {\n                throw new ArgumentNullException(\"parameterNames\");\n            }\n\n            ControllerName = controllerName;\n            ActionName = actionName;\n            ParameterNames = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);\n            SampleDirection = sampleDirection;\n        }\n\n        /// <summary>\n        /// Creates a new <see cref=\"HelpPageSampleKey\"/> based on media type, <see cref=\"SampleDirection\"/>, controller name, action name and parameter names.\n        /// </summary>\n        /// <param name=\"mediaType\">The media type.</param>\n        /// <param name=\"sampleDirection\">The <see cref=\"SampleDirection\"/>.</param>\n        /// <param name=\"controllerName\">Name of the controller.</param>\n        /// <param name=\"actionName\">Name of the action.</param>\n        /// <param name=\"parameterNames\">The parameter names.</param>\n        public HelpPageSampleKey(MediaTypeHeaderValue mediaType, SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames)\n            : this(sampleDirection, controllerName, actionName, parameterNames)\n        {\n            if (mediaType == null)\n            {\n                throw new ArgumentNullException(\"mediaType\");\n            }\n\n            MediaType = mediaType;\n        }\n\n        /// <summary>\n        /// Gets the name of the controller.\n        /// </summary>\n        /// <value>\n        /// The name of the controller.\n        /// </value>\n        public string ControllerName { get; private set; }\n\n        /// <summary>\n        /// Gets the name of the action.\n        /// </summary>\n        /// <value>\n        /// The name of the action.\n        /// </value>\n        public string ActionName { get; private set; }\n\n        /// <summary>\n        /// Gets the media type.\n        /// </summary>\n        /// <value>\n        /// The media type.\n        /// </value>\n        public MediaTypeHeaderValue MediaType { get; private set; }\n\n        /// <summary>\n        /// Gets the parameter names.\n        /// </summary>\n        public HashSet<string> ParameterNames { get; private set; }\n\n        public Type ParameterType { get; private set; }\n\n        /// <summary>\n        /// Gets the <see cref=\"SampleDirection\"/>.\n        /// </summary>\n        public SampleDirection? SampleDirection { get; private set; }\n\n        public override bool Equals(object obj)\n        {\n            HelpPageSampleKey otherKey = obj as HelpPageSampleKey;\n            if (otherKey == null)\n            {\n                return false;\n            }\n\n            return String.Equals(ControllerName, otherKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&\n                String.Equals(ActionName, otherKey.ActionName, StringComparison.OrdinalIgnoreCase) &&\n                (MediaType == otherKey.MediaType || (MediaType != null && MediaType.Equals(otherKey.MediaType))) &&\n                ParameterType == otherKey.ParameterType &&\n                SampleDirection == otherKey.SampleDirection &&\n                ParameterNames.SetEquals(otherKey.ParameterNames);\n        }\n\n        public override int GetHashCode()\n        {\n            int hashCode = ControllerName.ToUpperInvariant().GetHashCode() ^ ActionName.ToUpperInvariant().GetHashCode();\n            if (MediaType != null)\n            {\n                hashCode ^= MediaType.GetHashCode();\n            }\n            if (SampleDirection != null)\n            {\n                hashCode ^= SampleDirection.GetHashCode();\n            }\n            if (ParameterType != null)\n            {\n                hashCode ^= ParameterType.GetHashCode();\n            }\n            foreach (string parameterName in ParameterNames)\n            {\n                hashCode ^= parameterName.ToUpperInvariant().GetHashCode();\n            }\n\n            return hashCode;\n        }\n    }\n}\n"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/SampleGeneration/ImageSample.cs",
    "content": "﻿using System;\n\nnamespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage\n{\n    /// <summary>\n    /// This represents an image sample on the help page. There's a display template named ImageSample associated with this class.\n    /// </summary>\n    public class ImageSample\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"ImageSample\"/> class.\n        /// </summary>\n        /// <param name=\"src\">The URL of an image.</param>\n        public ImageSample(string src)\n        {\n            if (src == null)\n            {\n                throw new ArgumentNullException(\"src\");\n            }\n            Src = src;\n        }\n\n        public string Src { get; private set; }\n\n        public override bool Equals(object obj)\n        {\n            ImageSample other = obj as ImageSample;\n            return other != null && Src == other.Src;\n        }\n\n        public override int GetHashCode()\n        {\n            return Src.GetHashCode();\n        }\n\n        public override string ToString()\n        {\n            return Src;\n        }\n    }\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/SampleGeneration/InvalidSample.cs",
    "content": "﻿using System;\n\nnamespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage\n{\n    /// <summary>\n    /// This represents an invalid sample on the help page. There's a display template named InvalidSample associated with this class.\n    /// </summary>\n    public class InvalidSample\n    {\n        public InvalidSample(string errorMessage)\n        {\n            if (errorMessage == null)\n            {\n                throw new ArgumentNullException(\"errorMessage\");\n            }\n            ErrorMessage = errorMessage;\n        }\n\n        public string ErrorMessage { get; private set; }\n\n        public override bool Equals(object obj)\n        {\n            InvalidSample other = obj as InvalidSample;\n            return other != null && ErrorMessage == other.ErrorMessage;\n        }\n\n        public override int GetHashCode()\n        {\n            return ErrorMessage.GetHashCode();\n        }\n\n        public override string ToString()\n        {\n            return ErrorMessage;\n        }\n    }\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/SampleGeneration/ObjectGenerator.cs",
    "content": "using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Linq;\nusing System.Reflection;\n\nnamespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage\n{\n    /// <summary>\n    /// This class will create an object of a given type and populate it with sample data.\n    /// </summary>\n    public class ObjectGenerator\n    {\n        internal const int DefaultCollectionSize = 2;\n        private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();\n\n        /// <summary>\n        /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:\n        /// Simple types: <see cref=\"int\"/>, <see cref=\"string\"/>, <see cref=\"Enum\"/>, <see cref=\"DateTime\"/>, <see cref=\"Uri\"/>, etc.\n        /// Complex types: POCO types.\n        /// Nullables: <see cref=\"Nullable{T}\"/>.\n        /// Arrays: arrays of simple types or complex types.\n        /// Key value pairs: <see cref=\"KeyValuePair{TKey,TValue}\"/>\n        /// Tuples: <see cref=\"Tuple{T1}\"/>, <see cref=\"Tuple{T1,T2}\"/>, etc\n        /// Dictionaries: <see cref=\"IDictionary{TKey,TValue}\"/> or anything deriving from <see cref=\"IDictionary{TKey,TValue}\"/>.\n        /// Collections: <see cref=\"IList{T}\"/>, <see cref=\"IEnumerable{T}\"/>, <see cref=\"ICollection{T}\"/>, <see cref=\"IList\"/>, <see cref=\"IEnumerable\"/>, <see cref=\"ICollection\"/> or anything deriving from <see cref=\"ICollection{T}\"/> or <see cref=\"IList\"/>.\n        /// Queryables: <see cref=\"IQueryable\"/>, <see cref=\"IQueryable{T}\"/>.\n        /// </summary>\n        /// <param name=\"type\">The type.</param>\n        /// <returns>An object of the given type.</returns>\n        public object GenerateObject(Type type)\n        {\n            return GenerateObject(type, new Dictionary<Type, object>());\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification = \"Here we just want to return null if anything goes wrong.\")]\n        private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)\n        {\n            try\n            {\n                if (SimpleTypeObjectGenerator.CanGenerateObject(type))\n                {\n                    return SimpleObjectGenerator.GenerateObject(type);\n                }\n\n                if (type.IsArray)\n                {\n                    return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);\n                }\n\n                if (type.IsGenericType)\n                {\n                    return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);\n                }\n\n                if (type == typeof(IDictionary))\n                {\n                    return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);\n                }\n\n                if (typeof(IDictionary).IsAssignableFrom(type))\n                {\n                    return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);\n                }\n\n                if (type == typeof(IList) ||\n                    type == typeof(IEnumerable) ||\n                    type == typeof(ICollection))\n                {\n                    return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);\n                }\n\n                if (typeof(IList).IsAssignableFrom(type))\n                {\n                    return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);\n                }\n\n                if (type == typeof(IQueryable))\n                {\n                    return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);\n                }\n\n                if (type.IsEnum)\n                {\n                    return GenerateEnum(type);\n                }\n\n                if (type.IsPublic || type.IsNestedPublic)\n                {\n                    return GenerateComplexObject(type, createdObjectReferences);\n                }\n            }\n            catch\n            {\n                // Returns null if anything fails\n                return null;\n            }\n\n            return null;\n        }\n\n        private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)\n        {\n            Type genericTypeDefinition = type.GetGenericTypeDefinition();\n            if (genericTypeDefinition == typeof(Nullable<>))\n            {\n                return GenerateNullable(type, createdObjectReferences);\n            }\n\n            if (genericTypeDefinition == typeof(KeyValuePair<,>))\n            {\n                return GenerateKeyValuePair(type, createdObjectReferences);\n            }\n\n            if (IsTuple(genericTypeDefinition))\n            {\n                return GenerateTuple(type, createdObjectReferences);\n            }\n\n            Type[] genericArguments = type.GetGenericArguments();\n            if (genericArguments.Length == 1)\n            {\n                if (genericTypeDefinition == typeof(IList<>) ||\n                    genericTypeDefinition == typeof(IEnumerable<>) ||\n                    genericTypeDefinition == typeof(ICollection<>))\n                {\n                    Type collectionType = typeof(List<>).MakeGenericType(genericArguments);\n                    return GenerateCollection(collectionType, collectionSize, createdObjectReferences);\n                }\n\n                if (genericTypeDefinition == typeof(IQueryable<>))\n                {\n                    return GenerateQueryable(type, collectionSize, createdObjectReferences);\n                }\n\n                Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);\n                if (closedCollectionType.IsAssignableFrom(type))\n                {\n                    return GenerateCollection(type, collectionSize, createdObjectReferences);\n                }\n            }\n\n            if (genericArguments.Length == 2)\n            {\n                if (genericTypeDefinition == typeof(IDictionary<,>))\n                {\n                    Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);\n                    return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);\n                }\n\n                Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);\n                if (closedDictionaryType.IsAssignableFrom(type))\n                {\n                    return GenerateDictionary(type, collectionSize, createdObjectReferences);\n                }\n            }\n\n            if (type.IsPublic || type.IsNestedPublic)\n            {\n                return GenerateComplexObject(type, createdObjectReferences);\n            }\n\n            return null;\n        }\n\n        private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)\n        {\n            Type[] genericArgs = type.GetGenericArguments();\n            object[] parameterValues = new object[genericArgs.Length];\n            bool failedToCreateTuple = true;\n            ObjectGenerator objectGenerator = new ObjectGenerator();\n            for (int i = 0; i < genericArgs.Length; i++)\n            {\n                parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);\n                failedToCreateTuple &= parameterValues[i] == null;\n            }\n            if (failedToCreateTuple)\n            {\n                return null;\n            }\n            object result = Activator.CreateInstance(type, parameterValues);\n            return result;\n        }\n\n        private static bool IsTuple(Type genericTypeDefinition)\n        {\n            return genericTypeDefinition == typeof(Tuple<>) ||\n                genericTypeDefinition == typeof(Tuple<,>) ||\n                genericTypeDefinition == typeof(Tuple<,,>) ||\n                genericTypeDefinition == typeof(Tuple<,,,>) ||\n                genericTypeDefinition == typeof(Tuple<,,,,>) ||\n                genericTypeDefinition == typeof(Tuple<,,,,,>) ||\n                genericTypeDefinition == typeof(Tuple<,,,,,,>) ||\n                genericTypeDefinition == typeof(Tuple<,,,,,,,>);\n        }\n\n        private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)\n        {\n            Type[] genericArgs = keyValuePairType.GetGenericArguments();\n            Type typeK = genericArgs[0];\n            Type typeV = genericArgs[1];\n            ObjectGenerator objectGenerator = new ObjectGenerator();\n            object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);\n            object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);\n            if (keyObject == null && valueObject == null)\n            {\n                // Failed to create key and values\n                return null;\n            }\n            object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);\n            return result;\n        }\n\n        private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)\n        {\n            Type type = arrayType.GetElementType();\n            Array result = Array.CreateInstance(type, size);\n            bool areAllElementsNull = true;\n            ObjectGenerator objectGenerator = new ObjectGenerator();\n            for (int i = 0; i < size; i++)\n            {\n                object element = objectGenerator.GenerateObject(type, createdObjectReferences);\n                result.SetValue(element, i);\n                areAllElementsNull &= element == null;\n            }\n\n            if (areAllElementsNull)\n            {\n                return null;\n            }\n\n            return result;\n        }\n\n        private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)\n        {\n            Type typeK = typeof(object);\n            Type typeV = typeof(object);\n            if (dictionaryType.IsGenericType)\n            {\n                Type[] genericArgs = dictionaryType.GetGenericArguments();\n                typeK = genericArgs[0];\n                typeV = genericArgs[1];\n            }\n\n            object result = Activator.CreateInstance(dictionaryType);\n            MethodInfo addMethod = dictionaryType.GetMethod(\"Add\") ?? dictionaryType.GetMethod(\"TryAdd\");\n            MethodInfo containsMethod = dictionaryType.GetMethod(\"Contains\") ?? dictionaryType.GetMethod(\"ContainsKey\");\n            ObjectGenerator objectGenerator = new ObjectGenerator();\n            for (int i = 0; i < size; i++)\n            {\n                object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);\n                if (newKey == null)\n                {\n                    // Cannot generate a valid key\n                    return null;\n                }\n\n                bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });\n                if (!containsKey)\n                {\n                    object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);\n                    addMethod.Invoke(result, new object[] { newKey, newValue });\n                }\n            }\n\n            return result;\n        }\n\n        private static object GenerateEnum(Type enumType)\n        {\n            Array possibleValues = Enum.GetValues(enumType);\n            if (possibleValues.Length > 0)\n            {\n                return possibleValues.GetValue(0);\n            }\n            return null;\n        }\n\n        private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)\n        {\n            bool isGeneric = queryableType.IsGenericType;\n            object list;\n            if (isGeneric)\n            {\n                Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());\n                list = GenerateCollection(listType, size, createdObjectReferences);\n            }\n            else\n            {\n                list = GenerateArray(typeof(object[]), size, createdObjectReferences);\n            }\n            if (list == null)\n            {\n                return null;\n            }\n            if (isGeneric)\n            {\n                Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());\n                MethodInfo asQueryableMethod = typeof(Queryable).GetMethod(\"AsQueryable\", new[] { argumentType });\n                return asQueryableMethod.Invoke(null, new[] { list });\n            }\n\n            return Queryable.AsQueryable((IEnumerable)list);\n        }\n\n        private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)\n        {\n            Type type = collectionType.IsGenericType ?\n                collectionType.GetGenericArguments()[0] :\n                typeof(object);\n            object result = Activator.CreateInstance(collectionType);\n            MethodInfo addMethod = collectionType.GetMethod(\"Add\");\n            bool areAllElementsNull = true;\n            ObjectGenerator objectGenerator = new ObjectGenerator();\n            for (int i = 0; i < size; i++)\n            {\n                object element = objectGenerator.GenerateObject(type, createdObjectReferences);\n                addMethod.Invoke(result, new object[] { element });\n                areAllElementsNull &= element == null;\n            }\n\n            if (areAllElementsNull)\n            {\n                return null;\n            }\n\n            return result;\n        }\n\n        private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)\n        {\n            Type type = nullableType.GetGenericArguments()[0];\n            ObjectGenerator objectGenerator = new ObjectGenerator();\n            return objectGenerator.GenerateObject(type, createdObjectReferences);\n        }\n\n        private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)\n        {\n            object result = null;\n\n            if (createdObjectReferences.TryGetValue(type, out result))\n            {\n                // The object has been created already, just return it. This will handle the circular reference case.\n                return result;\n            }\n\n            if (type.IsValueType)\n            {\n                result = Activator.CreateInstance(type);\n            }\n            else\n            {\n                ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);\n                if (defaultCtor == null)\n                {\n                    // Cannot instantiate the type because it doesn't have a default constructor\n                    return null;\n                }\n\n                result = defaultCtor.Invoke(new object[0]);\n            }\n            createdObjectReferences.Add(type, result);\n            SetPublicProperties(type, result, createdObjectReferences);\n            SetPublicFields(type, result, createdObjectReferences);\n            return result;\n        }\n\n        private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)\n        {\n            PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);\n            ObjectGenerator objectGenerator = new ObjectGenerator();\n            foreach (PropertyInfo property in properties)\n            {\n                if (property.CanWrite)\n                {\n                    object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);\n                    property.SetValue(obj, propertyValue, null);\n                }\n            }\n        }\n\n        private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)\n        {\n            FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);\n            ObjectGenerator objectGenerator = new ObjectGenerator();\n            foreach (FieldInfo field in fields)\n            {\n                object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);\n                field.SetValue(obj, fieldValue);\n            }\n        }\n\n        private class SimpleTypeObjectGenerator\n        {\n            private long _index = 0;\n            private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();\n\n            [SuppressMessage(\"Microsoft.Maintainability\", \"CA1502:AvoidExcessiveComplexity\", Justification = \"These are simple type factories and cannot be split up.\")]\n            private static Dictionary<Type, Func<long, object>> InitializeGenerators()\n            {\n                return new Dictionary<Type, Func<long, object>>\n                {\n                    { typeof(Boolean), index => true },\n                    { typeof(Byte), index => (Byte)64 },\n                    { typeof(Char), index => (Char)65 },\n                    { typeof(DateTime), index => DateTime.Now },\n                    { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },\n                    { typeof(DBNull), index => DBNull.Value },\n                    { typeof(Decimal), index => (Decimal)index },\n                    { typeof(Double), index => (Double)(index + 0.1) },\n                    { typeof(Guid), index => Guid.NewGuid() },\n                    { typeof(Int16), index => (Int16)(index % Int16.MaxValue) },\n                    { typeof(Int32), index => (Int32)(index % Int32.MaxValue) },\n                    { typeof(Int64), index => (Int64)index },\n                    { typeof(Object), index => new object() },\n                    { typeof(SByte), index => (SByte)64 },\n                    { typeof(Single), index => (Single)(index + 0.1) },\n                    { \n                        typeof(String), index =>\n                        {\n                            return String.Format(CultureInfo.CurrentCulture, \"sample string {0}\", index);\n                        }\n                    },\n                    { \n                        typeof(TimeSpan), index =>\n                        {\n                            return TimeSpan.FromTicks(1234567);\n                        }\n                    },\n                    { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },\n                    { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },\n                    { typeof(UInt64), index => (UInt64)index },\n                    { \n                        typeof(Uri), index =>\n                        {\n                            return new Uri(String.Format(CultureInfo.CurrentCulture, \"http://webapihelppage{0}.com\", index));\n                        }\n                    },\n                };\n            }\n\n            public static bool CanGenerateObject(Type type)\n            {\n                return DefaultGenerators.ContainsKey(type);\n            }\n\n            public object GenerateObject(Type type)\n            {\n                return DefaultGenerators[type](++_index);\n            }\n        }\n    }\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/SampleGeneration/SampleDirection.cs",
    "content": "﻿namespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage\n{\n    /// <summary>\n    /// Indicates whether the sample is used for request or response\n    /// </summary>\n    public enum SampleDirection\n    {\n        Request = 0,\n        Response\n    }\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/SampleGeneration/TextSample.cs",
    "content": "﻿using System;\n\nnamespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage\n{\n    /// <summary>\n    /// This represents a preformatted text sample on the help page. There's a display template named TextSample associated with this class.\n    /// </summary>\n    public class TextSample\n    {\n        public TextSample(string text)\n        {\n            if (text == null)\n            {\n                throw new ArgumentNullException(\"text\");\n            }\n            Text = text;\n        }\n\n        public string Text { get; private set; }\n\n        public override bool Equals(object obj)\n        {\n            TextSample other = obj as TextSample;\n            return other != null && Text == other.Text;\n        }\n\n        public override int GetHashCode()\n        {\n            return Text.GetHashCode();\n        }\n\n        public override string ToString()\n        {\n            return Text;\n        }\n    }\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/Views/Help/Api.cshtml",
    "content": "﻿@using System.Web.Http\n@using ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Models\n@model HelpPageApiModel\n\n@{\n    var description = Model.ApiDescription;\n    ViewBag.Title = description.HttpMethod.Method + \" \" + description.RelativePath;\n}\n\n<link type=\"text/css\" href=\"~/Areas/HelpPage/HelpPage.css\" rel=\"stylesheet\" />\n<div id=\"body\" class=\"help-page\">\n    <section class=\"featured\">\n        <div class=\"content-wrapper\">\n            <p>\n                @Html.ActionLink(\"Help Page Home\", \"Index\")\n            </p>\n        </div>\n    </section>\n    <section class=\"content-wrapper main-content clear-fix\">\n        @Html.DisplayForModel()\n    </section>\n</div>\n"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/Views/Help/DisplayTemplates/ApiGroup.cshtml",
    "content": "﻿@using System.Web.Http\n@using System.Web.Http.Controllers\n@using System.Web.Http.Description\n@using ROOT_PROJECT_NAMESPACE.Areas.HelpPage\n@using ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Models\n@model IGrouping<HttpControllerDescriptor, ApiDescription>\n\n@{\n    var controllerDocumentation = ViewBag.DocumentationProvider != null ? \n        ViewBag.DocumentationProvider.GetDocumentation(Model.Key) : \n        null;\n}\n\n<h2 id=\"@Model.Key.ControllerName\">@Model.Key.ControllerName</h2>\n@if (!String.IsNullOrEmpty(controllerDocumentation))\n{\n    <p>@controllerDocumentation</p>\n}\n<table class=\"help-page-table\">\n    <thead>\n        <tr><th>API</th><th>Description</th></tr>\n    </thead>\n    <tbody>\n    @foreach (var api in Model)\n    {\n        <tr>\n            <td class=\"api-name\"><a href=\"@Url.Action(\"Api\", \"Help\", new { apiId = api.GetFriendlyId() })\">@api.HttpMethod.Method @api.RelativePath</a></td>\n            <td class=\"api-documentation\">\n            @if (api.Documentation != null)\n            {\n                <p>@api.Documentation</p>\n            }\n            else\n            {\n                <p>No documentation available.</p>\n            }\n            </td>\n        </tr>\n    }\n    </tbody>\n</table>"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/Views/Help/DisplayTemplates/CollectionModelDescription.cshtml",
    "content": "@using ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n@model CollectionModelDescription\n@if (Model.ElementDescription is ComplexTypeModelDescription)\n{\n    @Html.DisplayFor(m => m.ElementDescription)\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/Views/Help/DisplayTemplates/ComplexTypeModelDescription.cshtml",
    "content": "@using ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n@model ComplexTypeModelDescription\n@Html.DisplayFor(m => m.Properties, \"Parameters\")"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/Views/Help/DisplayTemplates/DictionaryModelDescription.cshtml",
    "content": "@using ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n@model DictionaryModelDescription\nDictionary of @Html.DisplayFor(m => Model.KeyModelDescription.ModelType, \"ModelDescriptionLink\", new { modelDescription = Model.KeyModelDescription }) [key]\nand @Html.DisplayFor(m => Model.ValueModelDescription.ModelType, \"ModelDescriptionLink\", new { modelDescription = Model.ValueModelDescription }) [value]"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/Views/Help/DisplayTemplates/EnumTypeModelDescription.cshtml",
    "content": "@using ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n@model EnumTypeModelDescription\n\n<p>Possible enumeration values:</p>\n\n<table class=\"help-page-table\">\n    <thead>\n        <tr><th>Name</th><th>Value</th><th>Description</th></tr>\n    </thead>\n    <tbody>\n        @foreach (EnumValueDescription value in Model.Values)\n        {\n            <tr>\n                <td class=\"enum-name\"><b>@value.Name</b></td>\n                <td class=\"enum-value\">\n                    <p>@value.Value</p>\n                </td>\n                <td class=\"enum-description\">\n                    <p>@value.Documentation</p>\n                </td>\n            </tr>\n        }\n    </tbody>\n</table>"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/Views/Help/DisplayTemplates/HelpPageApiModel.cshtml",
    "content": "﻿@using System.Web.Http\n@using System.Web.Http.Description\n@using ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Models\n@using ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n@model HelpPageApiModel\n\n@{\n    ApiDescription description = Model.ApiDescription;\n}\n<h1>@description.HttpMethod.Method @description.RelativePath</h1>\n<div>\n    <p>@description.Documentation</p>\n\n    <h2>Request Information</h2>\n\n    <h3>URI Parameters</h3>\n    @Html.DisplayFor(m => m.UriParameters, \"Parameters\")\n\n    <h3>Body Parameters</h3>\n\n    <p>@Model.RequestDocumentation</p>\n\n    @if (Model.RequestModelDescription != null)\n    {\n        @Html.DisplayFor(m => m.RequestModelDescription.ModelType, \"ModelDescriptionLink\", new { modelDescription = Model.RequestModelDescription })\n        if (Model.RequestBodyParameters != null)\n        {\n            @Html.DisplayFor(m => m.RequestBodyParameters, \"Parameters\")\n        }\n    }\n    else\n    {\n        <p>None.</p>\n    }\n\n    @if (Model.SampleRequests.Count > 0)\n    {\n        <h3>Request Formats</h3>\n        @Html.DisplayFor(m => m.SampleRequests, \"Samples\")\n    }\n\n    <h2>Response Information</h2>\n\n    <h3>Resource Description</h3>\n\n    <p>@description.ResponseDescription.Documentation</p>\n\n    @if (Model.ResourceDescription != null)\n    {\n        @Html.DisplayFor(m => m.ResourceDescription.ModelType, \"ModelDescriptionLink\", new { modelDescription = Model.ResourceDescription })\n        if (Model.ResourceProperties != null)\n        {\n            @Html.DisplayFor(m => m.ResourceProperties, \"Parameters\")\n        }\n    }\n    else\n    {\n        <p>None.</p>\n    }\n\n    @if (Model.SampleResponses.Count > 0)\n    {\n        <h3>Response Formats</h3>\n        @Html.DisplayFor(m => m.SampleResponses, \"Samples\")\n    }\n\n</div>"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/Views/Help/DisplayTemplates/ImageSample.cshtml",
    "content": "﻿@using ROOT_PROJECT_NAMESPACE.Areas.HelpPage\n@model ImageSample\n\n<img src=\"@Model.Src\" />"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/Views/Help/DisplayTemplates/InvalidSample.cshtml",
    "content": "﻿@using ROOT_PROJECT_NAMESPACE.Areas.HelpPage\n@model InvalidSample\n\n@if (HttpContext.Current.IsDebuggingEnabled)\n{\n    <div class=\"warning-message-container\">\n        <p>@Model.ErrorMessage</p>\n    </div>\n}\nelse\n{\n    <p>Sample not available.</p>\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/Views/Help/DisplayTemplates/KeyValuePairModelDescription.cshtml",
    "content": "@using ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n@model KeyValuePairModelDescription\nPair of @Html.DisplayFor(m => Model.KeyModelDescription.ModelType, \"ModelDescriptionLink\", new { modelDescription = Model.KeyModelDescription }) [key]\nand @Html.DisplayFor(m => Model.ValueModelDescription.ModelType, \"ModelDescriptionLink\", new { modelDescription = Model.ValueModelDescription }) [value]"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/Views/Help/DisplayTemplates/ModelDescriptionLink.cshtml",
    "content": "@using ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n@model Type\n@{\n    ModelDescription modelDescription = ViewBag.modelDescription;\n    if (modelDescription is ComplexTypeModelDescription || modelDescription is EnumTypeModelDescription)\n    {\n        if (Model == typeof(Object))\n        {\n            @:Object\n        }\n        else\n        {\n            @Html.ActionLink(modelDescription.Name, \"ResourceModel\", \"Help\", new { modelName = modelDescription.Name }, null)\n        }\n    }\n    else if (modelDescription is CollectionModelDescription)\n    {\n        var collectionDescription = modelDescription as CollectionModelDescription;\n        var elementDescription = collectionDescription.ElementDescription;\n        @:Collection of @Html.DisplayFor(m => elementDescription.ModelType, \"ModelDescriptionLink\", new { modelDescription = elementDescription })\n    }\n    else\n    {\n        @Html.DisplayFor(m => modelDescription)\n    }\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/Views/Help/DisplayTemplates/Parameters.cshtml",
    "content": "﻿@using System.Collections.Generic\n@using System.Collections.ObjectModel\n@using System.Web.Http.Description\n@using System.Threading\n@using ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n@model IList<ParameterDescription>\n\n@if (Model.Count > 0)\n{\n    <table class=\"help-page-table\">\n        <thead>\n            <tr><th>Name</th><th>Description</th><th>Type</th><th>Additional information</th></tr>\n        </thead>\n        <tbody>\n            @foreach (ParameterDescription parameter in Model)\n            {\n                ModelDescription modelDescription = parameter.TypeDescription;\n                <tr>\n                    <td class=\"parameter-name\">@parameter.Name</td>\n                    <td class=\"parameter-documentation\">\n                        <p>@parameter.Documentation</p>\n                    </td>\n                    <td class=\"parameter-type\">\n                        @Html.DisplayFor(m => modelDescription.ModelType, \"ModelDescriptionLink\", new { modelDescription = modelDescription })\n                    </td>\n                    <td class=\"parameter-annotations\">\n                        @if (parameter.Annotations.Count > 0)\n                        {\n                            foreach (var annotation in parameter.Annotations)\n                            {\n                                <p>@annotation.Documentation</p>\n                            }\n                        }\n                        else\n                        {\n                            <p>None.</p>\n                        }\n                    </td>\n                </tr>\n            }\n        </tbody>\n    </table>\n}\nelse\n{\n    <p>None.</p>\n}\n\n"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/Views/Help/DisplayTemplates/Samples.cshtml",
    "content": "﻿@using System.Net.Http.Headers\n@model Dictionary<MediaTypeHeaderValue, object>\n\n@{\n    // Group the samples into a single tab if they are the same.\n    Dictionary<string, object> samples = Model.GroupBy(pair => pair.Value).ToDictionary(\n        pair => String.Join(\", \", pair.Select(m => m.Key.ToString()).ToArray()), \n        pair => pair.Key);\n    var mediaTypes = samples.Keys;\n}\n<div>\n    @foreach (var mediaType in mediaTypes)\n    {\n        <h4 class=\"sample-header\">@mediaType</h4>\n        <div class=\"sample-content\">\n            <span><b>Sample:</b></span>\n            @{\n                var sample = samples[mediaType];\n                if (sample == null)\n                {\n                    <p>Sample not available.</p>\n                }\n                else\n                {\n                    @Html.DisplayFor(s => sample);\n                }\n            }\n        </div>\n    }\n</div>"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/Views/Help/DisplayTemplates/SimpleTypeModelDescription.cshtml",
    "content": "@using ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n@model SimpleTypeModelDescription\n@Model.Documentation"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/Views/Help/DisplayTemplates/TextSample.cshtml",
    "content": "﻿@using ROOT_PROJECT_NAMESPACE.Areas.HelpPage\n@model TextSample\n\n<pre class=\"wrapped\">\n@Model.Text\n</pre>"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/Views/Help/Index.cshtml",
    "content": "﻿@using System.Web.Http\n@using System.Web.Http.Controllers\n@using System.Web.Http.Description\n@using System.Collections.ObjectModel\n@using ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Models\n@model Collection<ApiDescription>\n\n@{\n    ViewBag.Title = \"ASP.NET Web API Help Page\";\n\n    // Group APIs by controller\n    ILookup<HttpControllerDescriptor, ApiDescription> apiGroups = Model.ToLookup(api => api.ActionDescriptor.ControllerDescriptor);\n}\n\n<link type=\"text/css\" href=\"~/Areas/HelpPage/HelpPage.css\" rel=\"stylesheet\" />\n<header class=\"help-page\">\n    <div class=\"content-wrapper\">\n        <div class=\"float-left\">\n            <h1>@ViewBag.Title</h1>\n        </div>\n    </div>\n</header>\n<div id=\"body\" class=\"help-page\">\n    <section class=\"featured\">\n        <div class=\"content-wrapper\">\n            <h2>Introduction</h2>\n            <p>\n                Provide a general description of your APIs here.\n            </p>\n        </div>\n    </section>\n    <section class=\"content-wrapper main-content clear-fix\">\n        @foreach (var group in apiGroups)\n        {\n            @Html.DisplayFor(m => group, \"ApiGroup\")\n        }\n    </section>\n</div>\n"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/Views/Help/ResourceModel.cshtml",
    "content": "@using System.Web.Http\n@using ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n@model ModelDescription\n\n<link type=\"text/css\" href=\"~/Areas/HelpPage/HelpPage.css\" rel=\"stylesheet\" />\n<div id=\"body\" class=\"help-page\">\n    <section class=\"featured\">\n        <div class=\"content-wrapper\">\n            <p>\n                @Html.ActionLink(\"Help Page Home\", \"Index\")\n            </p>\n        </div>\n    </section>\n    <h1>@Model.Name</h1>\n    <p>@Model.Documentation</p>\n    <section class=\"content-wrapper main-content clear-fix\">\n        @Html.DisplayFor(m => Model)\n    </section>\n</div>\n"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/Views/Shared/_Layout.cshtml",
    "content": "﻿<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"utf-8\" />\n    <meta name=\"viewport\" content=\"width=device-width\" />\n    <title>@ViewBag.Title</title>\n    @RenderSection(\"scripts\", required: false)\n</head>\n<body>\n    @RenderBody()\n</body>\n</html>"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/Views/Web.config",
    "content": "﻿<?xml version=\"1.0\"?>\n\n<configuration>\n  <configSections>\n    <sectionGroup name=\"system.web.webPages.razor\" type=\"System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\">\n      <section name=\"host\" type=\"System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\" requirePermission=\"false\" />\n      <section name=\"pages\" type=\"System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\" requirePermission=\"false\" />\n    </sectionGroup>\n  </configSections>\n\n  <system.web.webPages.razor>\n    <host factoryType=\"System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.3.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\" />\n    <pages pageBaseType=\"System.Web.Mvc.WebViewPage\">\n      <namespaces>\n        <add namespace=\"System.Web.Mvc\" />\n        <add namespace=\"System.Web.Mvc.Ajax\" />\n        <add namespace=\"System.Web.Mvc.Html\" />\n        <add namespace=\"System.Web.Routing\" />\n      </namespaces>\n    </pages>\n  </system.web.webPages.razor>\n\n  <appSettings>\n    <add key=\"webpages:Enabled\" value=\"false\" />\n  </appSettings>\n\n  <system.web>\n    <compilation debug=\"true\">\n      <assemblies>\n        <add assembly=\"System.Net.Http, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" />\n      </assemblies>\n    </compilation>\n  </system.web>\n\n  <system.webServer>\n    <handlers>\n      <remove name=\"BlockViewHandler\"/>\n      <add name=\"BlockViewHandler\" path=\"*\" verb=\"*\" preCondition=\"integratedMode\" type=\"System.Web.HttpNotFoundHandler\" />\n    </handlers>\n  </system.webServer>\n</configuration>\n"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/Views/_ViewStart.cshtml",
    "content": "﻿@{\n    // Change the Layout path below to blend the look and feel of the help page with your existing web pages.\n    Layout = \"~/Areas/HelpPage/Views/Shared/_Layout.cshtml\";\n}"
  },
  {
    "path": "src/WebApiHelpPage/Areas/HelpPage/XmlDocumentationProvider.cs",
    "content": "﻿using System;\nusing System.Globalization;\nusing System.Linq;\nusing System.Reflection;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Description;\nusing System.Xml.XPath;\nusing ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions;\n\nnamespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage\n{\n    /// <summary>\n    /// A custom <see cref=\"IDocumentationProvider\"/> that reads the API documentation from an XML documentation file.\n    /// </summary>\n    public class XmlDocumentationProvider : IDocumentationProvider, IModelDocumentationProvider\n    {\n        private XPathNavigator _documentNavigator;\n        private const string TypeExpression = \"/doc/members/member[@name='T:{0}']\";\n        private const string MethodExpression = \"/doc/members/member[@name='M:{0}']\";\n        private const string PropertyExpression = \"/doc/members/member[@name='P:{0}']\";\n        private const string FieldExpression = \"/doc/members/member[@name='F:{0}']\";\n        private const string ParameterExpression = \"param[@name='{0}']\";\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"XmlDocumentationProvider\"/> class.\n        /// </summary>\n        /// <param name=\"documentPath\">The physical path to XML document.</param>\n        public XmlDocumentationProvider(string documentPath)\n        {\n            if (documentPath == null)\n            {\n                throw new ArgumentNullException(\"documentPath\");\n            }\n            XPathDocument xpath = new XPathDocument(documentPath);\n            _documentNavigator = xpath.CreateNavigator();\n        }\n\n        public string GetDocumentation(HttpControllerDescriptor controllerDescriptor)\n        {\n            XPathNavigator typeNode = GetTypeNode(controllerDescriptor.ControllerType);\n            return GetTagValue(typeNode, \"summary\");\n        }\n\n        public virtual string GetDocumentation(HttpActionDescriptor actionDescriptor)\n        {\n            XPathNavigator methodNode = GetMethodNode(actionDescriptor);\n            return GetTagValue(methodNode, \"summary\");\n        }\n\n        public virtual string GetDocumentation(HttpParameterDescriptor parameterDescriptor)\n        {\n            ReflectedHttpParameterDescriptor reflectedParameterDescriptor = parameterDescriptor as ReflectedHttpParameterDescriptor;\n            if (reflectedParameterDescriptor != null)\n            {\n                XPathNavigator methodNode = GetMethodNode(reflectedParameterDescriptor.ActionDescriptor);\n                if (methodNode != null)\n                {\n                    string parameterName = reflectedParameterDescriptor.ParameterInfo.Name;\n                    XPathNavigator parameterNode = methodNode.SelectSingleNode(String.Format(CultureInfo.InvariantCulture, ParameterExpression, parameterName));\n                    if (parameterNode != null)\n                    {\n                        return parameterNode.Value.Trim();\n                    }\n                }\n            }\n\n            return null;\n        }\n\n        public string GetResponseDocumentation(HttpActionDescriptor actionDescriptor)\n        {\n            XPathNavigator methodNode = GetMethodNode(actionDescriptor);\n            return GetTagValue(methodNode, \"returns\");\n        }\n\n        public string GetDocumentation(MemberInfo member)\n        {\n            string memberName = String.Format(CultureInfo.InvariantCulture, \"{0}.{1}\", GetTypeName(member.DeclaringType), member.Name);\n            string expression = member.MemberType == MemberTypes.Field ? FieldExpression : PropertyExpression;\n            string selectExpression = String.Format(CultureInfo.InvariantCulture, expression, memberName);\n            XPathNavigator propertyNode = _documentNavigator.SelectSingleNode(selectExpression);\n            return GetTagValue(propertyNode, \"summary\");\n        }\n\n        public string GetDocumentation(Type type)\n        {\n            XPathNavigator typeNode = GetTypeNode(type);\n            return GetTagValue(typeNode, \"summary\");\n        }\n\n        private XPathNavigator GetMethodNode(HttpActionDescriptor actionDescriptor)\n        {\n            ReflectedHttpActionDescriptor reflectedActionDescriptor = actionDescriptor as ReflectedHttpActionDescriptor;\n            if (reflectedActionDescriptor != null)\n            {\n                string selectExpression = String.Format(CultureInfo.InvariantCulture, MethodExpression, GetMemberName(reflectedActionDescriptor.MethodInfo));\n                return _documentNavigator.SelectSingleNode(selectExpression);\n            }\n\n            return null;\n        }\n\n        private static string GetMemberName(MethodInfo method)\n        {\n            string name = String.Format(CultureInfo.InvariantCulture, \"{0}.{1}\", GetTypeName(method.DeclaringType), method.Name);\n            ParameterInfo[] parameters = method.GetParameters();\n            if (parameters.Length != 0)\n            {\n                string[] parameterTypeNames = parameters.Select(param => GetTypeName(param.ParameterType)).ToArray();\n                name += String.Format(CultureInfo.InvariantCulture, \"({0})\", String.Join(\",\", parameterTypeNames));\n            }\n\n            return name;\n        }\n\n        private static string GetTagValue(XPathNavigator parentNode, string tagName)\n        {\n            if (parentNode != null)\n            {\n                XPathNavigator node = parentNode.SelectSingleNode(tagName);\n                if (node != null)\n                {\n                    return node.Value.Trim();\n                }\n            }\n\n            return null;\n        }\n\n        private XPathNavigator GetTypeNode(Type type)\n        {\n            string controllerTypeName = GetTypeName(type);\n            string selectExpression = String.Format(CultureInfo.InvariantCulture, TypeExpression, controllerTypeName);\n            return _documentNavigator.SelectSingleNode(selectExpression);\n        }\n\n        private static string GetTypeName(Type type)\n        {\n            string name = type.FullName;\n            if (type.IsGenericType)\n            {\n                // Format the generic type name to something like: Generic{System.Int32,System.String}\n                Type genericType = type.GetGenericTypeDefinition();\n                Type[] genericArguments = type.GetGenericArguments();\n                string genericTypeName = genericType.FullName;\n\n                // Trim the generic parameter counts from the name\n                genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`'));\n                string[] argumentTypeNames = genericArguments.Select(t => GetTypeName(t)).ToArray();\n                name = String.Format(CultureInfo.InvariantCulture, \"{0}{{{1}}}\", genericTypeName, String.Join(\",\", argumentTypeNames));\n            }\n            if (type.IsNested)\n            {\n                // Changing the nested type name from OuterType+InnerType to OuterType.InnerType to match the XML documentation syntax.\n                name = name.Replace(\"+\", \".\");\n            }\n\n            return name;\n        }\n    }\n}\n"
  },
  {
    "path": "src/WebApiHelpPage/GlobalSuppressions.cs",
    "content": "﻿// This file is used by Code Analysis to maintain SuppressMessage \n// attributes that are applied to this project.\n// Project-level suppressions either have no target or are given \n// a specific target and scoped to a namespace, type, member, etc.\n//\n// To add a suppression to this file, right-click the message in the \n// Error List, point to \"Suppress Message(s)\", and click \n// \"In Project Suppression File\".\n// You do not need to add suppressions to this file manually.\n\n[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1707:IdentifiersShouldNotContainUnderscores\", Scope = \"namespace\", Target = \"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Controllers\", Justification = \"This namespace will be replaced with the project namespace when the help page is installed.\")]\n[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1707:IdentifiersShouldNotContainUnderscores\", Scope = \"namespace\", Target = \"ROOT_PROJECT_NAMESPACE.Areas.HelpPage\", Justification = \"This namespace will be replaced with the project namespace when the help page is installed.\")]\n[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1707:IdentifiersShouldNotContainUnderscores\", Scope = \"namespace\", Target = \"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Models\", Justification = \"This namespace will be replaced with the project namespace when the help page is installed.\")]\n[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1709:IdentifiersShouldBeCasedCorrectly\", MessageId = \"NAMESPACE\", Scope = \"namespace\", Target = \"ROOT_PROJECT_NAMESPACE.Areas.HelpPage\", Justification = \"This namespace will be replaced with the project namespace when the help page is installed.\")]\n[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1709:IdentifiersShouldBeCasedCorrectly\", MessageId = \"NAMESPACE\", Scope = \"namespace\", Target = \"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Controllers\", Justification = \"This namespace will be replaced with the project namespace when the help page is installed.\")]\n[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1709:IdentifiersShouldBeCasedCorrectly\", MessageId = \"NAMESPACE\", Scope = \"namespace\", Target = \"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Models\", Justification = \"This namespace will be replaced with the project namespace when the help page is installed.\")]\n[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1709:IdentifiersShouldBeCasedCorrectly\", MessageId = \"PROJECT\", Scope = \"namespace\", Target = \"ROOT_PROJECT_NAMESPACE.Areas.HelpPage\", Justification = \"This namespace will be replaced with the project namespace when the help page is installed.\")]\n[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1709:IdentifiersShouldBeCasedCorrectly\", MessageId = \"PROJECT\", Scope = \"namespace\", Target = \"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Controllers\", Justification = \"This namespace will be replaced with the project namespace when the help page is installed.\")]\n[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1709:IdentifiersShouldBeCasedCorrectly\", MessageId = \"PROJECT\", Scope = \"namespace\", Target = \"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Models\", Justification = \"This namespace will be replaced with the project namespace when the help page is installed.\")]\n[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1709:IdentifiersShouldBeCasedCorrectly\", MessageId = \"ROOT\", Scope = \"namespace\", Target = \"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Controllers\", Justification = \"This namespace will be replaced with the project namespace when the help page is installed.\")]\n[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1709:IdentifiersShouldBeCasedCorrectly\", MessageId = \"ROOT\", Scope = \"namespace\", Target = \"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Models\", Justification = \"This namespace will be replaced with the project namespace when the help page is installed.\")]\n[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1709:IdentifiersShouldBeCasedCorrectly\", MessageId = \"ROOT\", Scope = \"namespace\", Target = \"ROOT_PROJECT_NAMESPACE.Areas.HelpPage\", Justification = \"This namespace will be replaced with the project namespace when the help page is installed.\")]\n[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Controllers\", Justification = \"This namespace will be replaced with the project namespace when the help page is installed.\")]\n[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Models\", Justification = \"This namespace will be replaced with the project namespace when the help page is installed.\")]\n[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Usage\", \"CA1801:ReviewUnusedParameters\", MessageId = \"config\", Scope = \"member\", Target = \"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.HelpPageConfig.#Register(System.Web.Http.HttpConfiguration)\", Justification = \"This parameter is part of the template and could be used later.\")]\n[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Design\", \"CA2210:AssembliesShouldHaveValidStrongNames\", Justification = \"The assembly will not be deployed because we distribute the source code.\")]\n[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Web.FxCop\", \"MW1201:DoNotCallProblematicMethodsOnTaskRule\", Scope = \"member\", Target = \"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.HelpPageSampleGenerator.#WriteSampleObjectUsingFormatter(System.Net.Http.Formatting.MediaTypeFormatter,System.Object,System.Type,System.Net.Http.Headers.MediaTypeHeaderValue)\", Justification = \"This is an internal FxCop rule and we ship the source file.\")]\n[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1709:IdentifiersShouldBeCasedCorrectly\", MessageId = \"ROOT\", Scope = \"namespace\", Target = \"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\", Justification = \"This namespace will be replaced with the project namespace when the help page is installed.\")]\n[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1707:IdentifiersShouldNotContainUnderscores\", Scope = \"namespace\", Target = \"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\", Justification = \"This namespace will be replaced with the project namespace when the help page is installed.\")]\n[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1709:IdentifiersShouldBeCasedCorrectly\", MessageId = \"PROJECT\", Scope = \"namespace\", Target = \"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\", Justification = \"This namespace will be replaced with the project namespace when the help page is installed.\")]\n[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1709:IdentifiersShouldBeCasedCorrectly\", MessageId = \"NAMESPACE\", Scope = \"namespace\", Target = \"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\", Justification = \"This namespace will be replaced with the project namespace when the help page is installed.\")]\n"
  },
  {
    "path": "src/WebApiHelpPage/Properties/AssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\n\n[assembly: AssemblyTitle(\"WebApiHelpPage\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: Guid(\"aa22bcbc-83b3-466d-a421-9c561e3625b7\")]"
  },
  {
    "path": "src/WebApiHelpPage/Settings.StyleCop",
    "content": "<StyleCopSettings Version=\"105\">\n  <Analyzers>\n    <Analyzer AnalyzerId=\"Microsoft.Web.StyleCop.Rules\">\n      <Rules>\n        <Rule Name=\"FileMustHaveHeader\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n      </Rules>\n      <AnalyzerSettings />\n    </Analyzer>\n  </Analyzers>\n</StyleCopSettings>"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/ApiDescriptionExtensions.vb",
    "content": "Imports System\nImports System.Runtime.CompilerServices\nImports System.Text\nImports System.Web\nImports System.Web.Http.Description\n\nNamespace Areas.HelpPage\n    Public Module ApiDescriptionExtensions\n        '''<summary>\n        '''Generates an URI-friendly ID for the <see cref=\"ApiDescription\"/>. E.g. \"Get-Values-id_name\" instead of \"GetValues/{id}?name={name}\"\n        '''</summary>\n        '''<param name=\"description\">The <see cref=\"ApiDescription\"/>.</param>\n        '''<returns>The ID as a string.</returns>\n        <Extension()>\n        Public Function GetFriendlyId(ByVal description As ApiDescription) As String\n            Dim path As String = description.RelativePath\n            Dim urlParts() As String = path.Split(\"?\"c)\n            Dim localPath As String = urlParts(0)\n\n            Dim queryKeyString As String = Nothing\n\n            If (urlParts.Length > 1) Then\n                Dim query As String = urlParts(1)\n                Dim queryKeys() As String = HttpUtility.ParseQueryString(query).AllKeys\n                queryKeyString = String.Join(\"_\", queryKeys)\n            End If\n\n            Dim friendlyPath As New StringBuilder\n\n            friendlyPath.AppendFormat(\"{0}-{1}\",\n                description.HttpMethod.Method,\n                localPath.Replace(\"/\", \"-\").Replace(\"{\", String.Empty).Replace(\"}\", String.Empty))\n\n            If (Not queryKeyString Is Nothing) Then\n                friendlyPath.AppendFormat(\"_{0}\", queryKeyString.Replace(\".\", \"-\"))\n            End If\n\n            GetFriendlyId = friendlyPath.ToString()\n        End Function\n    End Module\nEnd Namespace"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/App_Start/HelpPageConfig.vb",
    "content": "' Uncomment the following to provide samples for PageResult(Of T). Must also add the Microsoft.AspNet.WebApi.OData\n' package to your project.\n''#Const Handle_PageResultOfT = 1\n\nImports System\nImports System.Collections\nImports System.Collections.Generic\nImports System.Diagnostics\nImports System.Diagnostics.CodeAnalysis\nImports System.Linq\nImports System.Net.Http.Headers\nImports System.Reflection\nImports System.Web\nImports System.Web.Http\n#If Handle_PageResultOfT Then\nImports System.Web.Http.OData\n#End If\n\nNamespace Areas.HelpPage\n    ''' <summary>\n    ''' Use this class to customize the Help Page.\n    ''' For example you can set a custom <see cref=\"System.Web.Http.Description.IDocumentationProvider\"/> to supply the documentation\n    ''' or you can provide the samples for the requests/responses.\n    ''' </summary>\n    Public Module HelpPageConfig\n        <SuppressMessage(\"Microsoft.Globalization\", \"CA1303:Do not pass literals as localized parameters\",\n            MessageId:=\"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.TextSample.#ctor(System.String)\",\n            Justification:=\"End users may choose to merge this string with existing localized resources.\")>\n        <SuppressMessage(\"Microsoft.Naming\", \"CA2204:Literals should be spelled correctly\",\n            MessageId:=\"bsonspec\",\n            Justification:=\"Part of a URI.\")>\n        Public Sub Register(config As HttpConfiguration)\n            '' Uncomment the following to use the documentation from XML documentation file.\n            'config.SetDocumentationProvider(New XmlDocumentationProvider(HttpContext.Current.Server.MapPath(\"~/App_Data/XmlDocument.xml\")))\n\n            '' Uncomment the following to use \"sample string\" as the sample for all actions that have string as the body parameter or return type.\n            '' Also, the string arrays will be used for IEnumerable(Of String). The sample objects will be serialized into different media type \n            '' formats by the available formatters.\n            'config.SetSampleObjects(New Dictionary(Of Type, Object) From\n            '{\n            '     {GetType(String), \"sample string\"},\n            '     {GetType(IEnumerable(Of String)), New String() {\"sample 1\", \"sample 2\"}}\n            '})\n\n            ' Extend the following to provide factories for types not handled automatically (those lacking parameterless\n            ' constructors) or for which you prefer to use non-default property values. Line below provides a fallback\n            ' since automatic handling will fail and GeneratePageResult handles only a single type.\n#If Handle_PageResultOfT Then\n            config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(AddressOf GeneratePageResult)\n#End If\n\n            ' Extend the following to use a preset object directly as the sample for all actions that support a media\n            ' type, regardless of the body parameter or return type. The lines below avoid display of binary content.\n            ' The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object.\n            config.SetSampleForMediaType(\n                New TextSample(\"Binary JSON content. See http://bsonspec.org for details.\"),\n                New MediaTypeHeaderValue(\"application/bson\"))\n\n            '' Uncomment the following to use \"[0]=foo&[1]=bar\" directly as the sample for all actions that support form URL encoded format\n            '' and have IEnumerable(Of String) as the body parameter or return type.\n            'config.SetSampleForType(\"[0]=foo&[1]=bar\", New MediaTypeHeaderValue(\"application/x-www-form-urlencoded\"), GetType(IEnumerable(Of String)))\n\n            '' Uncomment the following to use \"1234\" directly as the request sample for media type \"text/plain\" on the controller named \"Values\"\n            '' and action named \"Put\".\n            'config.SetSampleRequest(\"1234\", New MediaTypeHeaderValue(\"text/plain\"), \"Values\", \"Put\")\n\n            '' Uncomment the following to use the image on \"../images/aspNetHome.png\" directly as the response sample for media type \"image/png\"\n            '' on the controller named \"Values\" and action named \"Get\" with parameter \"id\".\n            'config.SetSampleResponse(New ImageSample(\"../images/aspNetHome.png\"), New MediaTypeHeaderValue(\"image/png\"), \"Values\", \"Get\", \"id\")\n\n            '' Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent(Of string).\n            '' The sample will be generated as if the controller named \"Values\" and action named \"Get\" were having String as the body parameter.\n            'config.SetActualRequestType(GetType(String), \"Values\", \"Get\")\n\n            '' Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent(Of String).\n            '' The sample will be generated as if the controller named \"Values\" and action named \"Post\" were returning a String.\n            'config.SetActualResponseType(GetType(String), \"Values\", \"Post\")\n        End Sub\n\n#If Handle_PageResultOfT Then\n        Private Function GeneratePageResult(sampleGenerator As HelpPageSampleGenerator, type As Type) As Object\n            If type.IsGenericType Then\n                Dim openGenericType As Type = type.GetGenericTypeDefinition()\n                If openGenericType = GetType(PageResult(Of )) Then\n                    ' Get the T in PageResult(Of T)\n                    Dim typeParameters() As Type = type.GetGenericArguments()\n                    Debug.Assert(typeParameters.Length = 1)\n\n                    ' Create an enumeration to pass as the first parameter to the PageResult(Of T) constuctor\n                    Dim itemsType As Type = GetType(List(Of )).MakeGenericType(typeParameters)\n                    Dim items As Object = sampleGenerator.GetSampleObject(itemsType)\n\n                    ' Fill in the other information needed to invoke the PageResult(Of T) constuctor\n                    Dim parameterTypes() As Type = New Type() {itemsType, GetType(Uri), GetType(Long?)}\n                    Dim parameters() As Object = New Object() {items, Nothing, CLng(ObjectGenerator.DefaultCollectionSize)}\n\n                    ' Call PageResult(items As IEnumerable(Of T), nextPageLink As Uri, count As Long?) constructor\n                    Dim constructor As ConstructorInfo = type.GetConstructor(parameterTypes)\n                    Return constructor.Invoke(parameters)\n                End If\n            End If\n\n            Return Nothing\n        End Function\n#End If\n    End Module\nEnd Namespace"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/Controllers/HelpController.vb",
    "content": "Imports System\nImports System.Web.Http\nImports System.Web.Mvc\nImports ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Models\nImports ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n\nNamespace Areas.HelpPage.Controllers\n    ''' <summary>\n    ''' The controller that will handle requests for the help page.\n    ''' </summary>\n    Public Class HelpController\n        Inherits Controller\n\n        Private Const ErrorViewName As String = \"Error\"\n        Private httpConfiguration As HttpConfiguration\n\n        Public Sub New()\n            Me.New(GlobalConfiguration.Configuration)\n        End Sub\n\n        Public Sub New(config As HttpConfiguration)\n            Configuration = config\n        End Sub\n\n        Public Property Configuration As HttpConfiguration\n            Get\n                Return httpConfiguration\n            End Get\n            Private Set(value As HttpConfiguration)\n                httpConfiguration = value\n            End Set\n        End Property\n\n        Public Function Index() As ActionResult\n            ViewData(\"DocumentationProvider\") = Configuration.Services.GetDocumentationProvider()\n            Return View(Configuration.Services.GetApiExplorer().ApiDescriptions)\n        End Function\n\n        Public Function Api(apiId As String) As ActionResult\n            If (Not String.IsNullOrEmpty(apiId)) Then\n                Dim apiModel As HelpPageApiModel = Configuration.GetHelpPageApiModel(apiId)\n                If (Not apiModel Is Nothing) Then\n                    Return View(apiModel)\n                End If\n            End If\n            Return View(ErrorViewName)\n        End Function\n\n        Public Function ResourceModel(modelName As String) As ActionResult\n            If Not [String].IsNullOrEmpty(modelName) Then\n                Dim modelDescriptionGenerator As ModelDescriptionGenerator = Configuration.GetModelDescriptionGenerator()\n                Dim modelDescription As ModelDescription = Nothing\n                If modelDescriptionGenerator.GeneratedModels.TryGetValue(modelName, modelDescription) Then\n                    Return View(modelDescription)\n                End If\n            End If\n\n            Return View(ErrorViewName)\n        End Function\n    End Class\nEnd Namespace\n"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/HelpPage.css",
    "content": "﻿.help-page h1,\n.help-page .h1,\n.help-page h2,\n.help-page .h2,\n.help-page h3,\n.help-page .h3,\n#body.help-page,\n.help-page-table th,\n.help-page-table pre,\n.help-page-table p {\n    font-family: \"Segoe UI Light\", Frutiger, \"Frutiger Linotype\", \"Dejavu Sans\", \"Helvetica Neue\", Arial, sans-serif;\n}\n\n.help-page pre.wrapped {\n    white-space: -moz-pre-wrap;\n    white-space: -pre-wrap;\n    white-space: -o-pre-wrap;\n    white-space: pre-wrap;\n}\n\n.help-page .warning-message-container {\n    margin-top: 20px;\n    padding: 0 10px;\n    color: #525252;\n    background: #EFDCA9; \n    border: 1px solid #CCCCCC;\n}\n\n.help-page-table {\n    width: 100%;\n    border-collapse: collapse;\n    text-align: left;\n    margin: 0px 0px 20px 0px;\n    border-top: 1px solid #D4D4D4;\n}\n\n.help-page-table th {\n    text-align: left;\n    font-weight: bold;\n    border-bottom: 1px solid #D4D4D4;\n    padding: 5px 6px 5px 6px;\n}\n\n.help-page-table td {\n    border-bottom: 1px solid #D4D4D4;\n    padding: 10px 8px 10px 8px;\n    vertical-align: top;\n}\n\n.help-page-table pre,\n.help-page-table p {\n    margin: 0px;\n    padding: 0px;\n    font-family: inherit;\n    font-size: 100%;\n}\n\n.help-page-table tbody tr:hover td {\n    background-color: #F3F3F3;\n}\n\n.help-page a:hover {\n    background-color: transparent;\n}\n\n.help-page .sample-header {\n    border: 2px solid #D4D4D4;\n    background: #00497E;\n    color: #FFFFFF;\n    padding: 8px 15px;\n    border-bottom: none;\n    display: inline-block;\n    margin: 10px 0px 0px 0px;\n}\n\n.help-page .sample-content {\n    display: block;\n    border-width: 0;\n    padding: 15px 20px;\n    background: #FFFFFF;\n    border: 2px solid #D4D4D4;\n    margin: 0px 0px 10px 0px;\n}\n\n.help-page .api-name {\n    width: 40%;\n}\n\n.help-page .api-documentation {\n    width: 60%;\n}\n\n.help-page .parameter-name {\n    width: 20%;\n}\n\n.help-page .parameter-documentation {\n    width: 40%;\n}\n\n.help-page .parameter-type {\n    width: 20%;\n}\n\n.help-page .parameter-annotations {\n    width: 20%;\n}\n\n.help-page h1,\n.help-page .h1 {\n    font-size: 36px;\n    line-height: normal;\n}\n\n.help-page h2,\n.help-page .h2 {\n    font-size: 24px;\n}\n\n.help-page h3,\n.help-page .h3 {\n    font-size: 20px;\n}\n\n#body.help-page {\n    font-size: 14px;\n    line-height: 143%;\n    color: #333;\n}\n\n.help-page a {\n    color: #0000EE;\n    text-decoration: none;\n}\n"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/HelpPageAreaRegistration.vb",
    "content": "Imports System.Web.Http\nImports System.Web.Mvc\n\nNamespace Areas.HelpPage\n    Public Class HelpPageAreaRegistration\n        Inherits AreaRegistration\n\n        Public Overrides ReadOnly Property AreaName As String\n            Get\n                Return \"HelpPage\"\n            End Get\n        End Property\n\n        Public Overrides Sub RegisterArea(context As AreaRegistrationContext)\n            context.MapRoute(\n                \"HelpPage_Default\",\n                \"Help/{action}/{apiId}\",\n                New With {.Controller = \"Help\", .action = \"Index\", .apiId = UrlParameter.Optional})\n            HelpPageConfig.Register(GlobalConfiguration.Configuration)\n        End Sub\n    End Class\nEnd Namespace"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/HelpPageConfigurationExtensions.vb",
    "content": "Imports System\nImports System.Collections.Generic\nImports System.Collections.ObjectModel\nImports System.ComponentModel\nImports System.Diagnostics\nImports System.Diagnostics.CodeAnalysis\nImports System.Globalization\nImports System.Linq\nImports System.Net.Http\nImports System.Net.Http.Headers\nImports System.Runtime.CompilerServices\nImports System.Web.Http\nImports System.Web.Http.Controllers\nImports System.Web.Http.Description\nImports ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Models\nImports ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n\nNamespace Areas.HelpPage\n    Public Module HelpPageConfigurationExtensions\n        Private Const ApiModelPrefix As String = \"MS_HelpPageApiModel_\"\n\n        ''' <summary>\n        ''' Sets the documentation provider for help page.\n        ''' </summary>\n        ''' <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        ''' <param name=\"documentationProvider\">The documentation provider.</param>\n        <Extension()>\n        Public Sub SetDocumentationProvider(ByVal config As HttpConfiguration, documentationProvider As IDocumentationProvider)\n            config.Services.Replace(GetType(IDocumentationProvider), documentationProvider)\n        End Sub\n\n        ''' <summary>\n        ''' Sets the objects that will be used by the formatters to produce sample requests/responses.\n        ''' </summary>\n        ''' <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        ''' <param name=\"sampleObjects\">The sample objects.</param>\n        <Extension()>\n        Public Sub SetSampleObjects(ByVal config As HttpConfiguration, sampleObjects As IDictionary(Of Type, Object))\n            config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects\n        End Sub\n\n        ''' <summary>\n        ''' Sets the sample request directly for the specified media type and action.\n        ''' </summary>\n        ''' <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        ''' <param name=\"sample\">The sample request.</param>\n        ''' <param name=\"mediaType\">The media type.</param>\n        ''' <param name=\"controllerName\">Name of the controller.</param>\n        ''' <param name=\"actionName\">Name of the action.</param>\n        <Extension()>\n        Public Sub SetSampleRequest(ByVal config As HttpConfiguration, sample As Object, mediaType As MediaTypeHeaderValue, controllerName As String, actionName As String)\n            config.GetHelpPageSampleGenerator().ActionSamples.Add(New HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, New String() {\"*\"}), sample)\n        End Sub\n\n        ''' <summary>\n        ''' Sets the sample request directly for the specified media type and action with parameters.\n        ''' </summary>\n        ''' <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        ''' <param name=\"sample\">The sample request.</param>\n        ''' <param name=\"mediaType\">The media type.</param>\n        ''' <param name=\"controllerName\">Name of the controller.</param>\n        ''' <param name=\"actionName\">Name of the action.</param>\n        ''' <param name=\"parameterNames\">The parameter names.</param>\n        <Extension()>\n        Public Sub SetSampleRequest(ByVal config As HttpConfiguration, sample As Object, mediaType As MediaTypeHeaderValue, controllerName As String, actionName As String, ByVal ParamArray parameterNames() As String)\n            config.GetHelpPageSampleGenerator().ActionSamples.Add(New HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample)\n        End Sub\n\n        ''' <summary>\n        ''' Sets the sample request directly for the specified media type of the action.\n        ''' </summary>\n        ''' <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        ''' <param name=\"sample\">The sample response.</param>\n        ''' <param name=\"mediaType\">The media type.</param>\n        ''' <param name=\"controllerName\">Name of the controller.</param>\n        ''' <param name=\"actionName\">Name of the action.</param>\n        <Extension()>\n        Public Sub SetSampleResponse(ByVal config As HttpConfiguration, sample As Object, mediaType As MediaTypeHeaderValue, controllerName As String, actionName As String)\n            config.GetHelpPageSampleGenerator().ActionSamples.Add(New HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, New String() {\"*\"}), sample)\n        End Sub\n\n        ''' <summary>\n        ''' Sets the sample response directly for the specified media type of the action with specific parameters.\n        ''' </summary>\n        ''' <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        ''' <param name=\"sample\">The sample response.</param>\n        ''' <param name=\"mediaType\">The media type.</param>\n        ''' <param name=\"controllerName\">Name of the controller.</param>\n        ''' <param name=\"actionName\">Name of the action.</param>\n        ''' <param name=\"parameterNames\">The parameter names.</param>\n        <Extension()>\n        Public Sub SetSampleResponse(ByVal config As HttpConfiguration, sample As Object, mediaType As MediaTypeHeaderValue, controllerName As String, actionName As String, ByVal ParamArray parameterNames() As String)\n            config.GetHelpPageSampleGenerator().ActionSamples.Add(New HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample)\n        End Sub\n\n        ''' <summary>\n        ''' Sets the sample directly for all actions with the specified type.\n        ''' </summary>\n        ''' <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        ''' <param name=\"sample\">The sample.</param>\n        ''' <param name=\"mediaType\">The media type.</param>\n        <Extension()>\n        Public Sub SetSampleForMediaType(ByVal config As HttpConfiguration, sample As Object, mediaType As MediaTypeHeaderValue)\n            config.GetHelpPageSampleGenerator().ActionSamples.Add(New HelpPageSampleKey(mediaType), sample)\n        End Sub\n\n        ''' <summary>\n        ''' Sets the sample directly for all actions with the specified type and media type.\n        ''' </summary>\n        ''' <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        ''' <param name=\"sample\">The sample.</param>\n        ''' <param name=\"mediaType\">The media type.</param>\n        ''' <param name=\"type\">The parameter type or return type of an action.</param>\n        <Extension()>\n        Public Sub SetSampleForType(ByVal config As HttpConfiguration, sample As Object, mediaType As MediaTypeHeaderValue, type As Type)\n            config.GetHelpPageSampleGenerator().ActionSamples.Add(New HelpPageSampleKey(mediaType, type), sample)\n        End Sub\n\n        ''' <summary>\n        ''' Specifies the actual type of <see cref=\"System.Net.Http.ObjectContent(Of T)\"/> passed to the <see cref=\"System.Net.Http.HttpRequestMessage\"/> in an action. \n        ''' The help page will use this information to produce more accurate request samples.\n        ''' </summary>\n        ''' <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        ''' <param name=\"type\">The type.</param>\n        ''' <param name=\"controllerName\">Name of the controller.</param>\n        ''' <param name=\"actionName\">Name of the action.</param>\n        <Extension()>\n        Public Sub SetActualRequestType(ByVal config As HttpConfiguration, type As Type, controllerName As String, actionName As String)\n            config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(New HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, New String() {\"*\"}), type)\n        End Sub\n\n        ''' <summary>\n        ''' Specifies the actual type of <see cref=\"System.Net.Http.ObjectContent(Of T)\"/> passed to the <see cref=\"System.Net.Http.HttpRequestMessage\"/> in an action. \n        ''' The help page will use this information to produce more accurate request samples.\n        ''' </summary>\n        ''' <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        ''' <param name=\"type\">The type.</param>\n        ''' <param name=\"controllerName\">Name of the controller.</param>\n        ''' <param name=\"actionName\">Name of the action.</param>\n        ''' <param name=\"parameterNames\">The parameter names.</param>\n        <Extension()>\n        Public Sub SetActualRequestType(ByVal config As HttpConfiguration, type As Type, controllerName As String, actionName As String, ByVal ParamArray parameterNames() As String)\n            config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(New HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type)\n        End Sub\n\n        ''' <summary>\n        ''' Specifies the actual type of <see cref=\"System.Net.Http.ObjectContent(Of T)\"/> returned as part of the <see cref=\"System.Net.Http.HttpRequestMessage\"/> in an action. \n        ''' The help page will use this information to produce more accurate response samples.\n        ''' </summary>\n        ''' <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        ''' <param name=\"type\">The type.</param>\n        ''' <param name=\"controllerName\">Name of the controller.</param>\n        ''' <param name=\"actionName\">Name of the action.</param>\n        <Extension()>\n        Public Sub SetActualResponseType(ByVal config As HttpConfiguration, type As Type, controllerName As String, actionName As String)\n            config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(New HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, New String() {\"*\"}), type)\n        End Sub\n\n        ''' <summary>\n        ''' Specifies the actual type of <see cref=\"System.Net.Http.ObjectContent(Of T)\"/> returned as part of the <see cref=\"System.Net.Http.HttpRequestMessage\"/> in an action. \n        ''' The help page will use this information to produce more accurate response samples.\n        ''' </summary>\n        ''' <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        ''' <param name=\"type\">The type.</param>\n        ''' <param name=\"controllerName\">Name of the controller.</param>\n        ''' <param name=\"actionName\">Name of the action.</param>\n        ''' <param name=\"parameterNames\">The parameter names.</param>\n        <Extension()>\n        Public Sub SetActualResponseType(ByVal config As HttpConfiguration, type As Type, controllerName As String, actionName As String, ByVal ParamArray parameterNames() As String)\n            config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(New HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type)\n        End Sub\n\n        ''' <summary>\n        ''' Gets the help page sample generator.\n        ''' </summary>\n        ''' <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        ''' <returns>The help page sample generator.</returns>\n        <Extension()>\n        Public Function GetHelpPageSampleGenerator(ByVal config As HttpConfiguration) As HelpPageSampleGenerator\n            Return DirectCast(config.Properties.GetOrAdd(\n                GetType(HelpPageSampleGenerator),\n                Function(k) New HelpPageSampleGenerator()), HelpPageSampleGenerator)\n        End Function\n\n        ''' <summary>\n        ''' Gets the model description generator.\n        ''' </summary>\n        ''' <param name=\"config\">The configuration.</param>\n        ''' <returns>The <see cref=\"ModelDescriptionGenerator\"/></returns>\n        <Extension()>\n        Public Function GetModelDescriptionGenerator(config As HttpConfiguration) As ModelDescriptionGenerator\n            Return DirectCast(config.Properties.GetOrAdd(GetType(ModelDescriptionGenerator), Function(k) InitializeModelDescriptionGenerator(config)), ModelDescriptionGenerator)\n        End Function\n\n        ''' <summary>\n        ''' Sets the help page sample generator.\n        ''' </summary>\n        ''' <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        ''' <param name=\"sampleGenerator\">The help page sample generator.</param>\n        <Extension()>\n        Public Sub SetHelpPageSampleGenerator(ByVal config As HttpConfiguration, sampleGenerator As HelpPageSampleGenerator)\n            config.Properties.AddOrUpdate(\n                GetType(HelpPageSampleGenerator),\n                Function(k) sampleGenerator,\n                Function(k, o) sampleGenerator)\n        End Sub\n\n        ''' <summary>\n        ''' Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.\n        ''' </summary>\n        ''' <param name=\"config\">The <see cref=\"HttpConfiguration\"/>.</param>\n        ''' <param name=\"apiDescriptionId\">The <see cref=\"ApiDescription\"/> ID.</param>\n        ''' <returns>\n        ''' An <see cref=\"HelpPageApiModel\"/>\n        ''' </returns>\n\n        <Extension()>\n        Public Function GetHelpPageApiModel(ByVal config As HttpConfiguration, apiDescriptionId As String) As HelpPageApiModel\n            Dim model As New Object\n\n            Dim modelId As String = ApiModelPrefix + apiDescriptionId\n            If (Not config.Properties.TryGetValue(modelId, model)) Then\n                Dim apiDescriptions As Collection(Of ApiDescription) = config.Services.GetApiExplorer().ApiDescriptions\n                Dim ApiDescription As ApiDescription = apiDescriptions.FirstOrDefault(Function(api) String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase))\n                If (Not ApiDescription Is Nothing) Then\n                    model = GenerateApiModel(ApiDescription, config)\n                    config.Properties.TryAdd(modelId, model)\n                End If\n            End If\n            Return DirectCast(model, HelpPageApiModel)\n        End Function\n\n        Public Function GenerateApiModel(apiDescription As ApiDescription, config As HttpConfiguration) As HelpPageApiModel\n            Dim apiModel As New HelpPageApiModel() With {\n                .ApiDescription = apiDescription\n            }\n\n            Dim sampleGenerator As HelpPageSampleGenerator = config.GetHelpPageSampleGenerator()\n            Dim modelGenerator As ModelDescriptionGenerator = config.GetModelDescriptionGenerator()\n            GenerateUriParameters(apiModel, modelGenerator)\n            GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator)\n            GenerateResourceDescription(apiModel, modelGenerator)\n            GenerateSamples(apiModel, sampleGenerator)\n\n            Return apiModel\n        End Function\n\n        Private Sub GenerateUriParameters(apiModel As HelpPageApiModel, modelGenerator As ModelDescriptionGenerator)\n            Dim apiDescription As ApiDescription = apiModel.ApiDescription\n            For Each apiParameter As ApiParameterDescription In apiDescription.ParameterDescriptions\n                If apiParameter.Source = ApiParameterSource.FromUri Then\n                    Dim parameterDescriptor As HttpParameterDescriptor = apiParameter.ParameterDescriptor\n                    Dim parameterType As Type = Nothing\n                    Dim typeDescription As ModelDescription = Nothing\n                    Dim complexTypeDescription As ComplexTypeModelDescription = Nothing\n                    If parameterDescriptor IsNot Nothing Then\n                        parameterType = parameterDescriptor.ParameterType\n                        typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType)\n                        complexTypeDescription = TryCast(typeDescription, ComplexTypeModelDescription)\n                    End If\n\n                    '' Example:\n                    '' <TypeConverter(GetType(PointConverter))>\n                    '' Public Class Point\n                    ''     Public Sub New(x As Integer, y As Integer)\n                    ''         x = x\n                    ''         y = y\n                    ''     End Sub\n                    ''     Public X As Integer\n                    ''     Public Y As Integer\n                    '' End Class\n                    '' Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.\n                    ''\n                    '' Public Class Point\n                    ''     Public X As Integer\n                    ''     Public Y As Integer\n                    '' End Class\n                    '' Regular complex class Point will have properties X and Y added to UriParameters collection.\n                    If complexTypeDescription IsNot Nothing AndAlso Not IsBindableWithTypeConverter(parameterType) Then\n                        For Each uriParameter As ParameterDescription In complexTypeDescription.Properties\n                            apiModel.UriParameters.Add(uriParameter)\n                        Next\n                    ElseIf parameterDescriptor IsNot Nothing Then\n                        Dim uriParameter As ParameterDescription =\n                            AddParameterDescription(apiModel, apiParameter, typeDescription)\n\n                        If Not parameterDescriptor.IsOptional Then\n                            uriParameter.Annotations.Add(New ParameterAnnotation() With {\n                                .Documentation = \"Required\"\n                            })\n                        End If\n\n                        Dim defaultValue As Object = parameterDescriptor.DefaultValue\n                        If defaultValue IsNot Nothing Then\n                            uriParameter.Annotations.Add(New ParameterAnnotation() With {\n                                .Documentation = \"Default value is \" & Convert.ToString(defaultValue, CultureInfo.InvariantCulture)\n                            })\n                        End If\n                    Else\n                        Debug.Assert(parameterDescriptor Is Nothing)\n\n                        '' If parameterDescriptor is Nothing, this is an undeclared route parameter which only occurs\n                        '' when source is FromUri. Ignored in request model and among resource parameters but listed\n                        '' as a simple string here.\n                        Dim modelDescription As ModelDescription =\n                            modelGenerator.GetOrCreateModelDescription(GetType(String))\n                        AddParameterDescription(apiModel, apiParameter, modelDescription)\n                    End If\n                End If\n            Next\n        End Sub\n\n        Private Function IsBindableWithTypeConverter(type As Type) As Boolean\n            If type Is Nothing Then\n                Return False\n            End If\n\n            Return TypeDescriptor.GetConverter(type).CanConvertFrom(GetType(String))\n        End Function\n\n        Private Function AddParameterDescription(apiModel As HelpPageApiModel, apiParameter As ApiParameterDescription,\n                                                 typeDescription As ModelDescription) As ParameterDescription\n            Dim parameterDescription As New ParameterDescription() With\n            {\n                .Name = apiParameter.Name,\n                .Documentation = apiParameter.Documentation,\n                .TypeDescription = typeDescription\n            }\n\n            apiModel.UriParameters.Add(parameterDescription)\n            Return parameterDescription\n        End Function\n\n        Private Sub GenerateRequestModelDescription(apiModel As HelpPageApiModel, modelGenerator As ModelDescriptionGenerator, sampleGenerator As HelpPageSampleGenerator)\n            Dim apiDescription As ApiDescription = apiModel.ApiDescription\n            For Each apiParameter As ApiParameterDescription In apiDescription.ParameterDescriptions\n                If apiParameter.Source = ApiParameterSource.FromBody Then\n                    Dim parameterType As Type = apiParameter.ParameterDescriptor.ParameterType\n                    apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType)\n                    apiModel.RequestDocumentation = apiParameter.Documentation\n                ElseIf apiParameter.ParameterDescriptor IsNot Nothing AndAlso\n                    apiParameter.ParameterDescriptor.ParameterType = GetType(HttpRequestMessage) Then\n                    Dim parameterType As Type = sampleGenerator.ResolveHttpRequestMessageType(apiDescription)\n\n                    If parameterType IsNot Nothing Then\n                        apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType)\n                    End If\n                End If\n            Next\n        End Sub\n\n        Private Sub GenerateResourceDescription(apiModel As HelpPageApiModel, modelGenerator As ModelDescriptionGenerator)\n            Dim response As ResponseDescription = apiModel.ApiDescription.ResponseDescription\n            Dim responseType As Type = If(response.ResponseType, response.DeclaredType)\n            If responseType IsNot Nothing AndAlso responseType <> GetType(System.Void) Then\n                apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType)\n            End If\n        End Sub\n\n        <SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification:=\"The exception is recorded as ErrorMessages.\")>\n        Private Sub GenerateSamples(apiModel As HelpPageApiModel, sampleGenerator As HelpPageSampleGenerator)\n            Try\n                For Each item In sampleGenerator.GetSampleRequests(apiModel.ApiDescription)\n                    apiModel.SampleRequests.Add(item.Key, item.Value)\n                    LogInvalidSampleAsError(apiModel, item.Value)\n                Next\n\n                For Each item In sampleGenerator.GetSampleResponses(apiModel.ApiDescription)\n                    apiModel.SampleResponses.Add(item.Key, item.Value)\n                    LogInvalidSampleAsError(apiModel, item.Value)\n                Next\n            Catch e As Exception\n                apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,\n                                                         \"An exception has occurred while generating the sample. Exception message: {0}\",\n                                                         HelpPageSampleGenerator.UnwrapException(e).Message))\n            End Try\n        End Sub\n\n        Private Function TryGetResourceParameter(apiDescription As ApiDescription, config As HttpConfiguration, ByRef parameterDescription As ApiParameterDescription, ByRef resourceType As Type) As Boolean\n            parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(\n                Function(p) p.Source = ApiParameterSource.FromBody OrElse\n                    (p.ParameterDescriptor IsNot Nothing AndAlso p.ParameterDescriptor.ParameterType = GetType(HttpRequestMessage)))\n\n            If parameterDescription Is Nothing Then\n                resourceType = Nothing\n                Return False\n            End If\n\n            resourceType = parameterDescription.ParameterDescriptor.ParameterType\n\n            If resourceType = GetType(HttpRequestMessage) Then\n                Dim sampleGenerator As HelpPageSampleGenerator = config.GetHelpPageSampleGenerator()\n                resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription)\n            End If\n\n            If resourceType Is Nothing Then\n                parameterDescription = Nothing\n                Return False\n            End If\n\n            Return True\n        End Function\n\n        Private Function InitializeModelDescriptionGenerator(config As HttpConfiguration) As ModelDescriptionGenerator\n            Dim modelGenerator As New ModelDescriptionGenerator(config)\n            Dim apis As Collection(Of ApiDescription) = config.Services.GetApiExplorer().ApiDescriptions\n            For Each api As ApiDescription In apis\n                Dim parameterDescription As ApiParameterDescription = Nothing\n                Dim parameterType As Type = Nothing\n                If TryGetResourceParameter(api, config, parameterDescription, parameterType) Then\n                    modelGenerator.GetOrCreateModelDescription(parameterType)\n                End If\n            Next\n            Return modelGenerator\n        End Function\n\n        Private Sub LogInvalidSampleAsError(apiModel As HelpPageApiModel, sample As Object)\n            Dim invalidSample As InvalidSample = TryCast(sample, InvalidSample)\n            If (Not invalidSample Is Nothing) Then\n                apiModel.ErrorMessages.Add(invalidSample.ErrorMessage)\n            End If\n        End Sub\n    End Module\nEnd Namespace"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/ModelDescriptions/CollectionModelDescription.vb",
    "content": "﻿Namespace Areas.HelpPage.ModelDescriptions\n    Public Class CollectionModelDescription\n        Inherits ModelDescription\n        Private _elementDescription As ModelDescription\n\n        Public Property ElementDescription() As ModelDescription\n            Get\n                Return _elementDescription\n            End Get\n            Set(value As ModelDescription)\n                _elementDescription = value\n            End Set\n        End Property\n    End Class\nEnd Namespace"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/ModelDescriptions/ComplexTypeModelDescription.vb",
    "content": "﻿Imports System.Collections.ObjectModel\n\nNamespace Areas.HelpPage.ModelDescriptions\n    Public Class ComplexTypeModelDescription\n        Inherits ModelDescription\n        Private _properties As Collection(Of ParameterDescription)\n\n        Public Sub New()\n            Properties = New Collection(Of ParameterDescription)()\n        End Sub\n\n        Public Property Properties() As Collection(Of ParameterDescription)\n            Get\n                Return _properties\n            End Get\n            Private Set(value As Collection(Of ParameterDescription))\n                _properties = value\n            End Set\n        End Property\n    End Class\nEnd Namespace"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/ModelDescriptions/DictionaryModelDescription.vb",
    "content": "﻿Namespace Areas.HelpPage.ModelDescriptions\n    Public Class DictionaryModelDescription\n        Inherits KeyValuePairModelDescription\n    End Class\nEnd Namespace"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/ModelDescriptions/EnumTypeModelDescription.vb",
    "content": "﻿Imports System.Collections.Generic\nImports System.Collections.ObjectModel\n\nNamespace Areas.HelpPage.ModelDescriptions\n    Public Class EnumTypeModelDescription\n        Inherits ModelDescription\n        Private _values As Collection(Of EnumValueDescription)\n\n        Public Sub New()\n            Values = New Collection(Of EnumValueDescription)()\n        End Sub\n\n        Public Property Values() As Collection(Of EnumValueDescription)\n            Get\n                Return _values\n            End Get\n            Private Set(value As Collection(Of EnumValueDescription))\n                _values = value\n            End Set\n        End Property\n    End Class\nEnd Namespace"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/ModelDescriptions/EnumValueDescription.vb",
    "content": "﻿Namespace Areas.HelpPage.ModelDescriptions\n    Public Class EnumValueDescription\n        Private _documentation As String\n        Private _value As String\n        Private _name As String\n\n        Public Property Documentation() As String\n            Get\n                Return _documentation\n            End Get\n            Set(value As String)\n                _documentation = value\n            End Set\n        End Property\n\n        Public Property Name() As String\n            Get\n                Return _name\n            End Get\n            Set(value As String)\n                _name = value\n            End Set\n        End Property\n\n        Public Property Value() As String\n            Get\n                Return _value\n            End Get\n            Set(value As String)\n                _value = value\n            End Set\n        End Property\n    End Class\nEnd Namespace"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/ModelDescriptions/IModelDocumentationProvider.vb",
    "content": "Imports System\nImports System.Reflection\n\nNamespace Areas.HelpPage.ModelDescriptions\n    Public Interface IModelDocumentationProvider\n        Function GetDocumentation(member As MemberInfo) As String\n        Function GetDocumentation(type As Type) As String\n    End Interface\nEnd Namespace"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/ModelDescriptions/KeyValuePairModelDescription.vb",
    "content": "﻿Namespace Areas.HelpPage.ModelDescriptions\n    Public Class KeyValuePairModelDescription\n        Inherits ModelDescription\n        Private _keyModelDescription As ModelDescription\n        Private _valueModelDescription As ModelDescription\n\n        Public Property KeyModelDescription() As ModelDescription\n            Get\n                Return _keyModelDescription\n            End Get\n            Set(value As ModelDescription)\n                _keyModelDescription = value\n            End Set\n        End Property\n\n        Public Property ValueModelDescription() As ModelDescription\n            Get\n                Return _valueModelDescription\n            End Get\n            Set(value As ModelDescription)\n                _valueModelDescription = value\n            End Set\n        End Property\n    End Class\nEnd Namespace"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/ModelDescriptions/ModelDescription.vb",
    "content": "﻿Imports System\n\nNamespace Areas.HelpPage.ModelDescriptions\n    ''' <summary>\n    ''' Describes a type model.\n    ''' </summary>\n    Public MustInherit Class ModelDescription\n        Private _name As String\n        Private _documentation As String\n        Private _modelType As Type\n\n        Public Property Documentation() As String\n            Get\n                Return _documentation\n            End Get\n            Set(value As String)\n                _documentation = value\n            End Set\n        End Property\n\n        Public Property ModelType() As Type\n            Get\n                Return _modelType\n            End Get\n            Set(value As Type)\n                _modelType = value\n            End Set\n        End Property\n\n        Public Property Name() As String\n            Get\n                Return _name\n            End Get\n            Set(value As String)\n                _name = value\n            End Set\n        End Property\n    End Class\nEnd Namespace"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/ModelDescriptions/ModelDescriptionGenerator.vb",
    "content": "Imports System\nImports System.Collections\nImports System.Collections.Generic\nImports System.Collections.Specialized\nImports System.ComponentModel.DataAnnotations\nImports System.Globalization\nImports System.Reflection\nImports System.Runtime.Serialization\nImports System.Web.Http\nImports System.Web.Http.Description\nImports System.Xml.Serialization\nImports Newtonsoft.Json\n\nNamespace Areas.HelpPage.ModelDescriptions\n    ''' <summary>\n    ''' Generates model descriptions for given types.\n    ''' </summary>\n    Public Class ModelDescriptionGenerator\n        ' Modify this to support more data annotation attributes.\n        Private ReadOnly AnnotationTextGenerator As IDictionary(Of Type, Func(Of Object, String)) = New Dictionary(Of Type, Func(Of Object, String))() From { _\n            {GetType(RequiredAttribute),\n             Function(a) \"Required\"},\n            {GetType(RangeAttribute),\n             Function(a)\n                 Dim range As RangeAttribute = DirectCast(a, RangeAttribute)\n                 Return [String].Format(CultureInfo.CurrentCulture, \"Range: inclusive between {0} and {1}\", range.Minimum, range.Maximum)\n             End Function},\n            {GetType(MaxLengthAttribute),\n             Function(a)\n                 Dim maxLength As MaxLengthAttribute = DirectCast(a, MaxLengthAttribute)\n                 Return [String].Format(CultureInfo.CurrentCulture, \"Max length: {0}\", maxLength.Length)\n             End Function},\n            {GetType(MinLengthAttribute),\n             Function(a)\n                 Dim minLength As MinLengthAttribute = DirectCast(a, MinLengthAttribute)\n                 Return [String].Format(CultureInfo.CurrentCulture, \"Min length: {0}\", minLength.Length)\n             End Function},\n            {GetType(StringLengthAttribute),\n             Function(a)\n                 Dim strLength As StringLengthAttribute = DirectCast(a, StringLengthAttribute)\n                 Return [String].Format(CultureInfo.CurrentCulture, \"String length: inclusive between {0} and {1}\", strLength.MinimumLength, strLength.MaximumLength)\n             End Function},\n            {GetType(DataTypeAttribute),\n             Function(a)\n                 Dim dataType As DataTypeAttribute = DirectCast(a, DataTypeAttribute)\n                 Return [String].Format(CultureInfo.CurrentCulture, \"Data type: {0}\", If(dataType.CustomDataType, dataType.DataType.ToString()))\n             End Function},\n            {GetType(RegularExpressionAttribute),\n             Function(a)\n                 Dim regularExpression As RegularExpressionAttribute = DirectCast(a, RegularExpressionAttribute)\n                 Return [String].Format(CultureInfo.CurrentCulture, \"Matching regular expression pattern: {0}\", regularExpression.Pattern)\n             End Function}\n        }\n\n        ' Modify this to add more default documentations.\n        Private ReadOnly DefaultTypeDocumentation As IDictionary(Of Type, String) = New Dictionary(Of Type, String)() From { _\n            {GetType(Int16), \"integer\"},\n            {GetType(Int32), \"integer\"},\n            {GetType(Int64), \"integer\"},\n            {GetType(UInt16), \"unsigned integer\"},\n            {GetType(UInt32), \"unsigned integer\"},\n            {GetType(UInt64), \"unsigned integer\"},\n            {GetType([Byte]), \"byte\"},\n            {GetType([Char]), \"character\"},\n            {GetType([SByte]), \"signed byte\"},\n            {GetType(Uri), \"URI\"},\n            {GetType([Single]), \"decimal number\"},\n            {GetType([Double]), \"decimal number\"},\n            {GetType([Decimal]), \"decimal number\"},\n            {GetType([String]), \"string\"},\n            {GetType(Guid), \"globally unique identifier\"},\n            {GetType(TimeSpan), \"time interval\"},\n            {GetType(DateTime), \"date\"},\n            {GetType(DateTimeOffset), \"date\"},\n            {GetType([Boolean]), \"boolean\"}\n        }\n\n        Private _documentationProvider As Lazy(Of IModelDocumentationProvider)\n\n        Public Sub New(config As HttpConfiguration)\n            If config Is Nothing Then\n                Throw New ArgumentNullException(\"config\")\n            End If\n\n            _documentationProvider = New Lazy(Of IModelDocumentationProvider)(Function() TryCast(config.Services.GetDocumentationProvider(), IModelDocumentationProvider))\n            GeneratedModels = New Dictionary(Of String, ModelDescription)(StringComparer.OrdinalIgnoreCase)\n        End Sub\n\n        Public Property GeneratedModels() As Dictionary(Of String, ModelDescription)\n            Get\n                Return m_GeneratedModels\n            End Get\n            Private Set(value As Dictionary(Of String, ModelDescription))\n                m_GeneratedModels = value\n            End Set\n        End Property\n        Private m_GeneratedModels As Dictionary(Of String, ModelDescription)\n\n        Private ReadOnly Property DocumentationProvider() As IModelDocumentationProvider\n            Get\n                Return _documentationProvider.Value\n            End Get\n        End Property\n\n        Public Function GetOrCreateModelDescription(modelType As Type) As ModelDescription\n            If modelType Is Nothing Then\n                Throw New ArgumentNullException(\"modelType\")\n            End If\n\n            Dim underlyingType As Type = Nullable.GetUnderlyingType(modelType)\n            If underlyingType IsNot Nothing Then\n                modelType = underlyingType\n            End If\n\n            Dim modelDescription As ModelDescription = Nothing\n            Dim modelName As String = ModelNameHelper.GetModelName(modelType)\n            If GeneratedModels.TryGetValue(modelName, modelDescription) Then\n                If modelType <> modelDescription.ModelType Then\n                    Throw New InvalidOperationException([String].Format(CultureInfo.CurrentCulture, \"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. \" & \"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.\", modelName, modelDescription.ModelType.FullName, modelType.FullName))\n                End If\n\n                Return modelDescription\n            End If\n\n            If DefaultTypeDocumentation.ContainsKey(modelType) Then\n                Return GenerateSimpleTypeModelDescription(modelType)\n            End If\n\n            If modelType.IsEnum Then\n                Return GenerateEnumTypeModelDescription(modelType)\n            End If\n\n            If modelType.IsGenericType Then\n                Dim genericArguments As Type() = modelType.GetGenericArguments()\n\n                If genericArguments.Length = 1 Then\n                    Dim enumerableType As Type = GetType(IEnumerable(Of )).MakeGenericType(genericArguments)\n                    If enumerableType.IsAssignableFrom(modelType) Then\n                        Return GenerateCollectionModelDescription(modelType, genericArguments(0))\n                    End If\n                End If\n                If genericArguments.Length = 2 Then\n                    Dim dictionaryType As Type = GetType(IDictionary(Of ,)).MakeGenericType(genericArguments)\n                    If dictionaryType.IsAssignableFrom(modelType) Then\n                        Return GenerateDictionaryModelDescription(modelType, genericArguments(0), genericArguments(1))\n                    End If\n\n                    Dim keyValuePairType As Type = GetType(KeyValuePair(Of ,)).MakeGenericType(genericArguments)\n                    If keyValuePairType.IsAssignableFrom(modelType) Then\n                        Return GenerateKeyValuePairModelDescription(modelType, genericArguments(0), genericArguments(1))\n                    End If\n                End If\n            End If\n\n            If modelType.IsArray Then\n                Dim elementType As Type = modelType.GetElementType()\n                Return GenerateCollectionModelDescription(modelType, elementType)\n            End If\n\n            If modelType Is GetType(NameValueCollection) Then\n                Return GenerateDictionaryModelDescription(modelType, GetType(String), GetType(String))\n            End If\n\n            If GetType(IDictionary).IsAssignableFrom(modelType) Then\n                Return GenerateDictionaryModelDescription(modelType, GetType(Object), GetType(Object))\n            End If\n\n            If GetType(IEnumerable).IsAssignableFrom(modelType) Then\n                Return GenerateCollectionModelDescription(modelType, GetType(Object))\n            End If\n\n            Return GenerateComplexTypeModelDescription(modelType)\n        End Function\n\n        ' Change this to provide different name for the member.\n        Private Shared Function GetMemberName(member As MemberInfo, hasDataContractAttribute As Boolean) As String\n            Dim jsonProperty As JsonPropertyAttribute = member.GetCustomAttribute(Of JsonPropertyAttribute)()\n            If jsonProperty IsNot Nothing AndAlso Not [String].IsNullOrEmpty(jsonProperty.PropertyName) Then\n                Return jsonProperty.PropertyName\n            End If\n\n            If hasDataContractAttribute Then\n                Dim dataMember As DataMemberAttribute = member.GetCustomAttribute(Of DataMemberAttribute)()\n                If dataMember IsNot Nothing AndAlso Not [String].IsNullOrEmpty(dataMember.Name) Then\n                    Return dataMember.Name\n                End If\n            End If\n\n            Return member.Name\n        End Function\n\n        Private Shared Function ShouldDisplayMember(member As MemberInfo, hasDataContractAttribute As Boolean) As Boolean\n            Dim jsonIgnore As JsonIgnoreAttribute = member.GetCustomAttribute(Of JsonIgnoreAttribute)()\n            Dim xmlIgnore As XmlIgnoreAttribute = member.GetCustomAttribute(Of XmlIgnoreAttribute)()\n            Dim ignoreDataMember As IgnoreDataMemberAttribute = member.GetCustomAttribute(Of IgnoreDataMemberAttribute)()\n            Dim nonSerialized As NonSerializedAttribute = member.GetCustomAttribute(Of NonSerializedAttribute)()\n            Dim apiExplorerSetting As ApiExplorerSettingsAttribute = member.GetCustomAttribute(Of ApiExplorerSettingsAttribute)()\n\n            Dim hasMemberAttribute As Boolean = If(member.DeclaringType.IsEnum, member.GetCustomAttribute(Of EnumMemberAttribute)() IsNot Nothing, member.GetCustomAttribute(Of DataMemberAttribute)() IsNot Nothing)\n\n            ' Display member only if all the followings are true:\n            ' no JsonIgnoreAttribute\n            ' no XmlIgnoreAttribute\n            ' no IgnoreDataMemberAttribute\n            ' no NonSerializedAttribute\n            ' no ApiExplorerSettingsAttribute with IgnoreApi set to true\n            ' no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute\n            Return jsonIgnore Is Nothing AndAlso xmlIgnore Is Nothing AndAlso ignoreDataMember Is Nothing AndAlso nonSerialized Is Nothing AndAlso (apiExplorerSetting Is Nothing OrElse Not apiExplorerSetting.IgnoreApi) AndAlso (Not hasDataContractAttribute OrElse hasMemberAttribute)\n        End Function\n\n        Private Function CreateDefaultDocumentation(type As Type) As String\n            Dim documentation As String = Nothing\n            If DefaultTypeDocumentation.TryGetValue(type, documentation) Then\n                Return documentation\n            End If\n            If DocumentationProvider IsNot Nothing Then\n                documentation = DocumentationProvider.GetDocumentation(type)\n            End If\n\n            Return documentation\n        End Function\n\n        Private Sub GenerateAnnotations([property] As MemberInfo, propertyModel As ParameterDescription)\n            Dim annotations As New List(Of ParameterAnnotation)()\n\n            Dim attributes As IEnumerable(Of Attribute) = [property].GetCustomAttributes()\n            For Each attribute As Attribute In attributes\n                Dim textGenerator As Func(Of Object, String) = Nothing\n                If AnnotationTextGenerator.TryGetValue(attribute.[GetType](), textGenerator) Then\n                    annotations.Add(\n                        New ParameterAnnotation() With {\n                            .AnnotationAttribute = attribute,\n                            .Documentation = textGenerator(attribute)\n                        })\n                End If\n            Next\n\n            ' Rearrange the annotations\n            annotations.Sort(\n                Function(x, y)\n                    ' Special-case RequiredAttribute so that it shows up on top\n                    If TypeOf x.AnnotationAttribute Is RequiredAttribute Then\n                        Return -1\n                    End If\n                    If TypeOf y.AnnotationAttribute Is RequiredAttribute Then\n                        Return 1\n                    End If\n\n                    ' Sort the rest based on alphabetic order of the documentation\n                    Return [String].Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase)\n\n                End Function)\n\n            For Each annotation As ParameterAnnotation In annotations\n                propertyModel.Annotations.Add(annotation)\n            Next\n        End Sub\n\n        Private Function GenerateCollectionModelDescription(modelType As Type, elementType As Type) As CollectionModelDescription\n            Dim collectionModelDescription As ModelDescription = GetOrCreateModelDescription(elementType)\n            If collectionModelDescription IsNot Nothing Then\n                Return New CollectionModelDescription() With {\n                    .Name = ModelNameHelper.GetModelName(modelType),\n                    .ModelType = modelType,\n                    .ElementDescription = collectionModelDescription\n                }\n            End If\n\n            Return Nothing\n        End Function\n\n        Private Function GenerateComplexTypeModelDescription(modelType As Type) As ModelDescription\n            Dim complexModelDescription As New ComplexTypeModelDescription() With {\n                .Name = ModelNameHelper.GetModelName(modelType),\n                .ModelType = modelType,\n                .Documentation = CreateDefaultDocumentation(modelType)\n            }\n\n            GeneratedModels.Add(complexModelDescription.Name, complexModelDescription)\n            Dim hasDataContractAttribute As Boolean = modelType.GetCustomAttribute(Of DataContractAttribute)() IsNot Nothing\n            Dim properties As PropertyInfo() = modelType.GetProperties(BindingFlags.[Public] Or BindingFlags.Instance)\n            For Each [property] As PropertyInfo In properties\n                If ShouldDisplayMember([property], hasDataContractAttribute) Then\n                    Dim propertyModel As New ParameterDescription() With {\n                        .Name = GetMemberName([property], hasDataContractAttribute)\n                    }\n\n                    If DocumentationProvider IsNot Nothing Then\n                        propertyModel.Documentation = DocumentationProvider.GetDocumentation([property])\n                    End If\n\n                    GenerateAnnotations([property], propertyModel)\n                    complexModelDescription.Properties.Add(propertyModel)\n                    propertyModel.TypeDescription = GetOrCreateModelDescription([property].PropertyType)\n                End If\n            Next\n\n            Dim fields As FieldInfo() = modelType.GetFields(BindingFlags.[Public] Or BindingFlags.Instance)\n            For Each field As FieldInfo In fields\n                If ShouldDisplayMember(field, hasDataContractAttribute) Then\n                    Dim propertyModel As New ParameterDescription() With {\n                        .Name = GetMemberName(field, hasDataContractAttribute)\n                    }\n\n                    If DocumentationProvider IsNot Nothing Then\n                        propertyModel.Documentation = DocumentationProvider.GetDocumentation(field)\n                    End If\n\n                    complexModelDescription.Properties.Add(propertyModel)\n                    propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType)\n                End If\n            Next\n\n            Return complexModelDescription\n        End Function\n\n        Private Function GenerateDictionaryModelDescription(modelType As Type, keyType As Type, valueType As Type) As DictionaryModelDescription\n            Dim keyModelDescription As ModelDescription = GetOrCreateModelDescription(keyType)\n            Dim valueModelDescription As ModelDescription = GetOrCreateModelDescription(valueType)\n\n            Return New DictionaryModelDescription() With {\n                .Name = ModelNameHelper.GetModelName(modelType),\n                .ModelType = modelType,\n                .KeyModelDescription = keyModelDescription,\n                .ValueModelDescription = valueModelDescription\n            }\n        End Function\n\n        Private Function GenerateEnumTypeModelDescription(modelType As Type) As EnumTypeModelDescription\n            Dim enumDescription As New EnumTypeModelDescription() With {\n                .Name = ModelNameHelper.GetModelName(modelType),\n                .ModelType = modelType,\n                .Documentation = CreateDefaultDocumentation(modelType)\n            }\n            Dim hasDataContractAttribute As Boolean = modelType.GetCustomAttribute(Of DataContractAttribute)() IsNot Nothing\n            For Each field As FieldInfo In modelType.GetFields(BindingFlags.[Public] Or BindingFlags.[Static])\n                If ShouldDisplayMember(field, hasDataContractAttribute) Then\n                    Dim enumValue As New EnumValueDescription() With {\n                        .Name = field.Name,\n                        .Value = field.GetRawConstantValue().ToString()\n                    }\n                    If DocumentationProvider IsNot Nothing Then\n                        enumValue.Documentation = DocumentationProvider.GetDocumentation(field)\n                    End If\n                    enumDescription.Values.Add(enumValue)\n                End If\n            Next\n            GeneratedModels.Add(enumDescription.Name, enumDescription)\n\n            Return enumDescription\n        End Function\n\n        Private Function GenerateKeyValuePairModelDescription(modelType As Type, keyType As Type, valueType As Type) As KeyValuePairModelDescription\n            Dim keyModelDescription As ModelDescription = GetOrCreateModelDescription(keyType)\n            Dim valueModelDescription As ModelDescription = GetOrCreateModelDescription(valueType)\n\n            Return New KeyValuePairModelDescription() With {\n                .Name = ModelNameHelper.GetModelName(modelType),\n                .ModelType = modelType,\n                .KeyModelDescription = keyModelDescription,\n                .ValueModelDescription = valueModelDescription\n            }\n        End Function\n\n        Private Function GenerateSimpleTypeModelDescription(modelType As Type) As ModelDescription\n            Dim simpleModelDescription As New SimpleTypeModelDescription() With {\n                .Name = ModelNameHelper.GetModelName(modelType),\n                .ModelType = modelType,\n                .Documentation = CreateDefaultDocumentation(modelType)\n            }\n            GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription)\n\n            Return simpleModelDescription\n        End Function\n    End Class\nEnd Namespace"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/ModelDescriptions/ModelNameAttribute.vb",
    "content": "﻿Imports System\n\nNamespace Areas.HelpPage.ModelDescriptions\n    ''' <summary>\n    ''' Use this attribute to change the name of the <see cref=\"ModelDescription\"/> generated for a type.\n    ''' </summary>\n    <AttributeUsage(AttributeTargets.[Class] Or AttributeTargets.Struct Or AttributeTargets.[Enum], AllowMultiple:=False, Inherited:=False)> _\n    Public NotInheritable Class ModelNameAttribute\n        Inherits Attribute\n        Private _name As String\n\n        Public Sub New(name As String)\n            _name = name\n        End Sub\n\n        Public Property Name() As String\n            Get\n                Return _name\n            End Get\n            Private Set(value As String)\n                _name = value\n            End Set\n        End Property\n    End Class\nEnd Namespace"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/ModelDescriptions/ModelNameHelper.vb",
    "content": "﻿Imports System\nImports System.Globalization\nImports System.Linq\nImports System.Reflection\n\nNamespace Areas.HelpPage.ModelDescriptions\n    Friend NotInheritable Class ModelNameHelper\n        Private Sub New()\n        End Sub\n\n        ' Modify this to provide custom model name mapping.\n        Public Shared Function GetModelName(type As Type) As String\n            Dim modelNameAttribute As ModelNameAttribute = type.GetCustomAttribute(Of ModelNameAttribute)()\n            If modelNameAttribute IsNot Nothing AndAlso Not [String].IsNullOrEmpty(modelNameAttribute.Name) Then\n                Return modelNameAttribute.Name\n            End If\n\n            Dim modelName As String = type.Name\n            If type.IsGenericType Then\n                ' Format the generic type name to something like: GenericOfAgurment1AndArgument2\n                Dim genericType As Type = type.GetGenericTypeDefinition()\n                Dim genericArguments As Type() = type.GetGenericArguments()\n                Dim genericTypeName As String = genericType.Name\n\n                ' Trim the generic parameter counts from the name\n                genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf(\"`\"c))\n                Dim argumentTypeNames As String() = genericArguments.[Select](Function(t) GetModelName(t)).ToArray()\n                modelName = [String].Format(CultureInfo.InvariantCulture, \"{0}Of{1}\", genericTypeName, [String].Join(\"And\", argumentTypeNames))\n            End If\n\n            Return modelName\n        End Function\n    End Class\nEnd Namespace"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/ModelDescriptions/ParameterAnnotation.vb",
    "content": "﻿Imports System\n\nNamespace Areas.HelpPage.ModelDescriptions\n    Public Class ParameterAnnotation\n        Private _annotationAttribute As Attribute\n        Private _documentation As String\n\n        Public Property AnnotationAttribute() As Attribute\n            Get\n                Return _annotationAttribute\n            End Get\n            Set(value As Attribute)\n                _annotationAttribute = value\n            End Set\n        End Property\n\n        Public Property Documentation() As String\n            Get\n                Return _documentation\n            End Get\n            Set(value As String)\n                _documentation = value\n            End Set\n        End Property\n    End Class\nEnd Namespace"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/ModelDescriptions/ParameterDescription.vb",
    "content": "﻿Imports System.Collections.Generic\nImports System.Collections.ObjectModel\n\nNamespace Areas.HelpPage.ModelDescriptions\n    Public Class ParameterDescription\n        Private _annotations As Collection(Of ParameterAnnotation)\n        Private _documentation As String\n        Private _name As String\n        Private _typeDescription As ModelDescription\n\n        Public Sub New()\n            Annotations = New Collection(Of ParameterAnnotation)()\n        End Sub\n\n        Public Property Annotations() As Collection(Of ParameterAnnotation)\n            Get\n                Return _annotations\n            End Get\n            Private Set(value As Collection(Of ParameterAnnotation))\n                _annotations = value\n            End Set\n        End Property\n\n        Public Property Documentation() As String\n            Get\n                Return _documentation\n            End Get\n            Set(value As String)\n                _documentation = value\n            End Set\n        End Property\n\n        Public Property Name() As String\n            Get\n                Return _name\n            End Get\n            Set(value As String)\n                _name = value\n            End Set\n        End Property\n\n        Public Property TypeDescription() As ModelDescription\n            Get\n                Return _typeDescription\n            End Get\n            Set(value As ModelDescription)\n                _typeDescription = value\n            End Set\n        End Property\n    End Class\nEnd Namespace"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/ModelDescriptions/SimpleTypeModelDescription.vb",
    "content": "﻿Namespace Areas.HelpPage.ModelDescriptions\n    Public Class SimpleTypeModelDescription\n        Inherits ModelDescription\n    End Class\nEnd Namespace"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/Models/HelpPageApiModel.vb",
    "content": "Imports System.Collections.Generic\nImports System.Collections.ObjectModel\nImports System.Net.Http.Headers\nImports System.Web.Http.Description\nImports ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n\nNamespace Areas.HelpPage.Models\n    ''' <summary>\n    ''' The model that represents an API displayed on the help page.\n    ''' </summary>\n    Public Class HelpPageApiModel\n        Private _sampleRequests As IDictionary(Of MediaTypeHeaderValue, Object)\n        Private _sampleResponses As IDictionary(Of MediaTypeHeaderValue, Object)\n        Private _errorMessages As Collection(Of String)\n        Private _apiDescription As ApiDescription\n        Private _uriParameters As Collection(Of ParameterDescription)\n        Private _requestModelDescription As ModelDescription\n        Private _resourceDescription As ModelDescription\n        Private _requestDocumentation As String\n\n        '''<summary>\n        ''' Initializes a new instance of the <see cref=\"HelpPageApiModel\"/> class.\n        ''' </summary>\n        Public Sub New()\n            UriParameters = New Collection(Of ParameterDescription)\n            SampleRequests = New Dictionary(Of MediaTypeHeaderValue, Object)\n            SampleResponses = New Dictionary(Of MediaTypeHeaderValue, Object)\n            ErrorMessages = New Collection(Of String)\n        End Sub\n\n        ''' <summary>\n        ''' Gets or sets the <see cref=\"ApiDescription\"/> that describes the API.\n        ''' </summary>\n        Public Property ApiDescription As ApiDescription\n            Get\n                Return _apiDescription\n            End Get\n            Set(value As ApiDescription)\n                _apiDescription = value\n            End Set\n        End Property\n\n\n        ''' <summary>\n        ''' Gets or sets the <see cref=\"ParameterDescription\"/> collection that describes the URI parameters for the API.\n        ''' </summary>\n        Public Property UriParameters() As Collection(Of ParameterDescription)\n            Get\n                Return _uriParameters\n            End Get\n            Private Set(value As Collection(Of ParameterDescription))\n                _uriParameters = value\n            End Set\n        End Property\n\n        ''' <summary>\n        ''' Gets or sets the documentation for the request.\n        ''' </summary>\n        Public Property RequestDocumentation() As String\n            Get\n                Return _requestDocumentation\n            End Get\n            Set(value As String)\n                _requestDocumentation = value\n            End Set\n        End Property\n\n        ''' <summary>\n        ''' Gets or sets the model description of the request body.\n        ''' </summary>\n        Public Property RequestModelDescription() As ModelDescription\n            Get\n                Return _requestModelDescription\n            End Get\n            Set(value As ModelDescription)\n                _requestModelDescription = value\n            End Set\n        End Property\n\n        ''' <summary>\n        ''' Gets the request body parameter descriptions.\n        ''' </summary>\n        Public ReadOnly Property RequestBodyParameters() As IList(Of ParameterDescription)\n            Get\n                Return GetParameterDescriptions(RequestModelDescription)\n            End Get\n        End Property\n\n        ''' <summary>\n        ''' Gets or sets the <see cref=\"ModelDescription\"/> that describes the resource.\n        ''' </summary>\n        Public Property ResourceDescription() As ModelDescription\n            Get\n                Return _resourceDescription\n            End Get\n            Set(value As ModelDescription)\n                _resourceDescription = value\n            End Set\n        End Property\n\n        ''' <summary>\n        ''' Gets the resource property descriptions.\n        ''' </summary>\n        Public ReadOnly Property ResourceProperties() As IList(Of ParameterDescription)\n            Get\n                Return GetParameterDescriptions(ResourceDescription)\n            End Get\n        End Property\n\n        ''' <summary>\n        ''' Gets the sample requests associated with the API.\n        ''' </summary>\n        Public Property SampleRequests As IDictionary(Of MediaTypeHeaderValue, Object)\n            Get\n                Return _sampleRequests\n            End Get\n            Private Set(value As IDictionary(Of MediaTypeHeaderValue, Object))\n                _sampleRequests = value\n            End Set\n        End Property\n\n        ''' <summary>\n        ''' Gets the sample responses associated with the API.\n        ''' </summary>\n        Public Property SampleResponses As IDictionary(Of MediaTypeHeaderValue, Object)\n            Get\n                Return _sampleResponses\n            End Get\n            Private Set(value As IDictionary(Of MediaTypeHeaderValue, Object))\n                _sampleResponses = value\n            End Set\n        End Property\n\n        ''' <summary>\n        ''' Gets the error messages associated with this model.\n        ''' </summary>\n        Public Property ErrorMessages As Collection(Of String)\n            Get\n                Return _errorMessages\n            End Get\n            Private Set(value As Collection(Of String))\n                _errorMessages = value\n            End Set\n        End Property\n\n        Private Shared Function GetParameterDescriptions(modelDescription As ModelDescription) As IList(Of ParameterDescription)\n            Dim complexTypeModelDescription As ComplexTypeModelDescription = TryCast(modelDescription, ComplexTypeModelDescription)\n            If complexTypeModelDescription IsNot Nothing Then\n                Return complexTypeModelDescription.Properties\n            End If\n\n            Dim collectionModelDescription As CollectionModelDescription = TryCast(modelDescription, CollectionModelDescription)\n            If collectionModelDescription IsNot Nothing Then\n                complexTypeModelDescription = TryCast(collectionModelDescription.ElementDescription, ComplexTypeModelDescription)\n                If complexTypeModelDescription IsNot Nothing Then\n                    Return complexTypeModelDescription.Properties\n                End If\n            End If\n\n            Return Nothing\n        End Function\n    End Class\nEnd Namespace"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/SampleGeneration/HelpPageSampleGenerator.vb",
    "content": "Imports System\nImports System.Collections.Generic\nImports System.Collections.ObjectModel\nImports System.ComponentModel\nImports System.Diagnostics.CodeAnalysis\nImports System.Globalization\nImports System.IO\nImports System.Linq\nImports System.Net.Http\nImports System.Net.Http.Formatting\nImports System.Net.Http.Headers\nImports System.Runtime.InteropServices\nImports System.Web.Http.Description\nImports System.Xml.Linq\nImports Newtonsoft.Json\n\nNamespace Areas.HelpPage\n    ''' <summary>\n    ''' This class will generate the samples for the help page.\n    ''' </summary>\n    Public Class HelpPageSampleGenerator\n        Private _actualHttpMessageTypes As IDictionary(Of HelpPageSampleKey, Type)\n        Private _actionSamples As IDictionary(Of HelpPageSampleKey, Object)\n        Private _sampleObjects As IDictionary(Of Type, Object)\n        Private _sampleObjectFactories As IList(Of Func(Of HelpPageSampleGenerator, Type, Object))\n\n        ''' <summary>\n        ''' Initializes a new instance of the <see cref=\"HelpPageSampleGenerator\"/> class.\n        ''' </summary>\n        Public Sub New()\n            ActualHttpMessageTypes = New Dictionary(Of HelpPageSampleKey, Type)\n            ActionSamples = New Dictionary(Of HelpPageSampleKey, Object)\n            SampleObjects = New Dictionary(Of Type, Object)\n            SampleObjectFactories = New List(Of Func(Of HelpPageSampleGenerator, Type, Object))\n            SampleObjectFactories.Add(AddressOf DefaultSampleObjectFactory)\n        End Sub\n\n        ''' <summary>\n        ''' Gets CLR types that are used as the content of <see cref=\"HttpRequestMessage\"/> or <see cref=\"HttpResponseMessage\"/>.\n        ''' </summary>\n        Public Property ActualHttpMessageTypes As IDictionary(Of HelpPageSampleKey, Type)\n            Get\n                Return _actualHttpMessageTypes\n            End Get\n            Friend Set(value As IDictionary(Of HelpPageSampleKey, Type))\n                _actualHttpMessageTypes = value\n            End Set\n        End Property\n\n        ''' <summary>\n        ''' Gets the objects that are used directly as samples for certain actions.\n        ''' </summary>\n        Public Property ActionSamples As IDictionary(Of HelpPageSampleKey, Object)\n            Get\n                Return _actionSamples\n            End Get\n            Friend Set(value As IDictionary(Of HelpPageSampleKey, Object))\n                _actionSamples = value\n            End Set\n        End Property\n\n        ''' <summary>\n        ''' Gets the objects that are serialized as samples by the supported formatters.\n        ''' </summary>\n        Public Property SampleObjects As IDictionary(Of Type, Object)\n            Get\n                Return _sampleObjects\n            End Get\n            Friend Set(value As IDictionary(Of Type, Object))\n                _sampleObjects = value\n            End Set\n        End Property\n\n        ''' <summary>\n        ''' Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,\n        ''' stopping when the factory successfully returns a non-<see langref=\"null\"/> object.\n        ''' </summary>\n        ''' <remarks>\n        ''' Collection includes just <see cref=\"ObjectGenerator.GenerateObject\"/> initially. Use\n        ''' <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and\n        ''' <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>\n        <SuppressMessage(\"Microsoft.Design\", \"CA1006:DoNotNestGenericTypesInMemberSignatures\",\n            Justification:=\"This is an appropriate nesting of generic types\")>\n        Public Property SampleObjectFactories As IList(Of Func(Of HelpPageSampleGenerator, Type, Object))\n            Get\n                Return _sampleObjectFactories\n            End Get\n            Private Set(value As IList(Of Func(Of HelpPageSampleGenerator, Type, Object)))\n                _sampleObjectFactories = value\n            End Set\n        End Property\n\n        ''' <summary>\n        ''' Gets the request body samples for a given <see cref=\"ApiDescription\"/>.\n        ''' </summary>\n        ''' <param name=\"api\">The <see cref=\"ApiDescription\"/>.</param>\n        ''' <returns>The samples keyed by media type.</returns>\n        Public Function GetSampleRequests(api As ApiDescription) As IDictionary(Of MediaTypeHeaderValue, Object)\n            Return GetSample(api, SampleDirection.Request)\n        End Function\n\n        ''' <summary>\n        ''' Gets the response body samples for a given <see cref=\"ApiDescription\"/>.\n        ''' </summary>\n        ''' <param name=\"api\">The <see cref=\"ApiDescription\"/>.</param>\n        ''' <returns>The samples keyed by media type.</returns>\n        Public Function GetSampleResponses(api As ApiDescription) As IDictionary(Of MediaTypeHeaderValue, Object)\n            Return GetSample(api, SampleDirection.Response)\n        End Function\n\n        ''' <summary>\n        ''' Gets the request or response body samples.\n        ''' </summary>\n        ''' <param name=\"api\">The <see cref=\"ApiDescription\"/>.</param>\n        ''' <param name=\"sampleDirection\">The value indicating whether the sample is for a request or for a response.</param>\n        ''' <returns>The samples keyed by media type.</returns>\n        Public Overridable Function GetSample(api As ApiDescription, sampleDirection As SampleDirection) As IDictionary(Of MediaTypeHeaderValue, Object)\n            If (api Is Nothing) Then\n                Throw New ArgumentNullException(\"api\")\n            End If\n\n            Dim controllerName As String = api.ActionDescriptor.ControllerDescriptor.ControllerName\n            Dim actionName As String = api.ActionDescriptor.ActionName\n            Dim parameterNames As IEnumerable(Of String) = api.ParameterDescriptions.Select(Function(p) p.Name)\n            Dim formatters As New Collection(Of MediaTypeFormatter)\n            Dim type As Type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, formatters)\n            Dim samples As New Dictionary(Of MediaTypeHeaderValue, Object)\n\n            ' Use the samples provided directly for actions\n            Dim actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection)\n            For Each actionSample In actionSamples\n                samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value))\n            Next\n\n            ' Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.\n            ' Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.\n            If (Not type Is Nothing AndAlso Not GetType(HttpResponseMessage).IsAssignableFrom(type)) Then\n                Dim sampleObject As Object = GetSampleObject(type)\n                For Each formatter In formatters\n                    For Each mediaType As MediaTypeHeaderValue In formatter.SupportedMediaTypes\n                        If (Not samples.ContainsKey(mediaType)) Then\n                            Dim sample As Object = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection)\n                            ' If no sample found, try generate sample using formatter and sample object\n                            If (sample Is Nothing And Not sampleObject Is Nothing) Then\n                                sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType)\n                            End If\n\n                            samples.Add(mediaType, WrapSampleIfString(sample))\n                        End If\n                    Next\n                Next\n            End If\n            Return samples\n        End Function\n\n        ''' <summary>\n        ''' Search for samples that are provided directly through <see cref=\"ActionSamples\"/>.\n        ''' </summary>\n        ''' <param name=\"controllerName\">Name of the controller.</param>\n        ''' <param name=\"actionName\">Name of the action.</param>\n        ''' <param name=\"parameterNames\">The parameter names.</param>\n        ''' <param name=\"type\">The CLR type.</param>\n        ''' <param name=\"formatter\">The formatter.</param>\n        ''' <param name=\"mediaType\">The media type.</param>\n        ''' <param name=\"sampleDirection\">The value indicating whether the sample is for a request or for a response.</param>\n        ''' <returns>The sample that matches the parameters.</returns>\n        Public Overridable Function GetActionSample(controllerName As String, actionName As String, parameterNames As IEnumerable(Of String), type As Type, formatter As MediaTypeFormatter, mediaType As MediaTypeHeaderValue, sampleDirection As SampleDirection) As Object\n            Dim sample As New Object\n\n            ' First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.\n            ' If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.\n            ' If still not found, try to get the sample provided for the specified mediaType and type.\n            ' Finally, try to get the sample provided for the specified mediaType.\n            If (ActionSamples.TryGetValue(New HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), sample) OrElse\n                ActionSamples.TryGetValue(New HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, New String() {\"*\"}), sample) OrElse\n                ActionSamples.TryGetValue(New HelpPageSampleKey(mediaType, type), sample) OrElse\n                ActionSamples.TryGetValue(New HelpPageSampleKey(mediaType), sample)) Then\n                Return sample\n            End If\n            Return Nothing\n        End Function\n\n        ''' <summary>\n        ''' Gets the sample object that will be serialized by the formatters. \n        ''' First, it will look at the <see cref=\"SampleObjects\"/>. If no sample object is found, it will try to create\n        ''' one using <see cref=\"DefaultSampleObjectFactory\"/> (which wraps an <see cref=\"ObjectGenerator\"/>) and other\n        ''' factories in <see cref=\"SampleObjectFactories\"/>.\n        ''' </summary>\n        ''' <param name=\"type\">The type.</param>\n        ''' <returns>The sample object.</returns>\n        <SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\",\n            Justification:=\"Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.\")>\n        Public Overridable Function GetSampleObject(type As Type) As Object\n            Dim sampleObject As New Object\n\n            If (Not SampleObjects.TryGetValue(type, sampleObject)) Then\n                ' No specific object available, try our factories.\n                For Each factory As Func(Of HelpPageSampleGenerator, Type, Object) In SampleObjectFactories\n                    If factory Is Nothing Then\n                        Continue For\n                    End If\n\n                    Try\n                        sampleObject = factory(Me, type)\n                        If sampleObject IsNot Nothing Then\n                            Exit For\n                        End If\n                    Catch\n                        ' Ignore any problems encountered in the factory; go on to the next one (if any).\n                    End Try\n                Next\n            End If\n\n            Return sampleObject\n        End Function\n\n        ''' <summary>\n        ''' Resolves the actual type of <see cref=\"System.Net.Http.ObjectContent(Of T)\"/> passed to the <see cref=\"System.Net.Http.HttpRequestMessage\"/> in an action.\n        ''' </summary>\n        ''' <param name=\"api\">The <see cref=\"ApiDescription\"/>.</param>\n        ''' <returns>The type.</returns>\n        Public Overridable Function ResolveHttpRequestMessageType(api As ApiDescription) As Type\n            Dim controllerName As String = api.ActionDescriptor.ControllerDescriptor.ControllerName\n            Dim actionName As String = api.ActionDescriptor.ActionName\n            Dim parameterNames As IEnumerable(Of String) = api.ParameterDescriptions.[Select](Function(p) p.Name)\n            Dim formatters As Collection(Of MediaTypeFormatter) = Nothing\n            Return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, formatters)\n        End Function\n\n        ''' <summary>\n        ''' Resolves the type of the action parameter or return value when <see cref=\"HttpRequestMessage\"/> or <see cref=\"HttpResponseMessage\"/> is used.\n        ''' </summary>\n        ''' <param name=\"api\">The <see cref=\"ApiDescription\"/>.</param>\n        ''' <param name=\"controllerName\">Name of the controller.</param>\n        ''' <param name=\"actionName\">Name of the action.</param>\n        ''' <param name=\"parameterNames\">The parameter names.</param>\n        ''' <param name=\"sampleDirection\">The value indicating whether the sample is for a request or a response.</param>\n        ''' <param name=\"formatters\">The formatters.</param>\n        <SuppressMessage(\"Microsoft.Design\", \"CA1021:AvoidOutParameters\", Justification:=\"This is only used in advanced scenarios.\")>\n        Public Overridable Function ResolveType(api As ApiDescription, controllerName As String, actionName As String, parameterNames As IEnumerable(Of String), sampleDirection As SampleDirection, <Out()> ByRef formatters As Collection(Of MediaTypeFormatter)) As Type\n            If (Not [Enum].IsDefined(GetType(SampleDirection), sampleDirection)) Then\n                Throw New InvalidEnumArgumentException(\"sampleDirection\", CInt(sampleDirection), GetType(SampleDirection))\n            End If\n            If (api Is Nothing) Then\n                Throw New ArgumentNullException(\"api\")\n            End If\n            Dim type As Type = GetType(Object)\n\n            If (ActualHttpMessageTypes.TryGetValue(New HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), type) OrElse\n                ActualHttpMessageTypes.TryGetValue(New HelpPageSampleKey(sampleDirection, controllerName, actionName, New String() {\"*\"}), type)) Then\n                ' Re-compute the supported formatters based on type\n                Dim newFormatters As New Collection(Of MediaTypeFormatter)\n                For Each formatter In api.ActionDescriptor.Configuration.Formatters\n                    If (IsFormatSupported(sampleDirection, formatter, type)) Then\n                        newFormatters.Add(formatter)\n                    End If\n                Next\n\n                formatters = newFormatters\n            Else\n                Select Case sampleDirection\n                    Case sampleDirection.Request\n                        Dim requestBodyParameter As ApiParameterDescription = api.ParameterDescriptions.FirstOrDefault(Function(p) p.Source = ApiParameterSource.FromBody)\n                        type = If(requestBodyParameter Is Nothing, Nothing, requestBodyParameter.ParameterDescriptor.ParameterType)\n                        formatters = api.SupportedRequestBodyFormatters\n                    Case Else\n                        'Case sampleDirection.Response\n                        type = If(api.ResponseDescription.ResponseType, api.ResponseDescription.DeclaredType)\n                        formatters = api.SupportedResponseFormatters\n                End Select\n            End If\n            Return type\n        End Function\n\n        ''' <summary>\n        ''' Writes the sample object using formatter.\n        ''' </summary>\n        ''' <param name=\"formatter\">The formatter.</param>\n        ''' <param name=\"value\">The value.</param>\n        ''' <param name=\"type\">The type.</param>\n        ''' <param name=\"mediaType\">Type of the media.</param>\n        ''' <returns></returns>\n        <SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification:=\"The exception is recorded as InvalidSample.\")>\n        Public Overridable Function WriteSampleObjectUsingFormatter(formatter As MediaTypeFormatter, value As Object, type As Type, mediaType As MediaTypeHeaderValue) As Object\n            If (formatter Is Nothing) Then\n                Throw New ArgumentNullException(\"formatter\")\n            End If\n            If (mediaType Is Nothing) Then\n                Throw New ArgumentNullException(\"mediaType\")\n            End If\n\n            Dim sample As Object = String.Empty\n            Dim MS As MemoryStream = Nothing\n            Dim content As HttpContent = Nothing\n            Try\n                If (formatter.CanWriteType(type)) Then\n                    MS = New MemoryStream()\n                    content = New ObjectContent(type, value, formatter, mediaType)\n                    formatter.WriteToStreamAsync(type, value, MS, content, Nothing).Wait()\n                    MS.Position = 0\n                    Dim reader As New StreamReader(MS)\n                    Dim serializedSampleString As String = reader.ReadToEnd()\n                    If (mediaType.MediaType.ToUpperInvariant().Contains(\"XML\")) Then\n                        serializedSampleString = TryFormatXml(serializedSampleString)\n                    ElseIf (mediaType.MediaType.ToUpperInvariant().Contains(\"JSON\")) Then\n                        serializedSampleString = TryFormatJson(serializedSampleString)\n                    End If\n\n                    sample = New TextSample(serializedSampleString)\n                Else\n                    sample = New InvalidSample(String.Format(\n                        CultureInfo.CurrentCulture,\n                        \"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.\",\n                        mediaType,\n                        formatter.GetType().Name,\n                        type.Name))\n                End If\n            Catch e As Exception\n                sample = New InvalidSample(String.Format(\n                    CultureInfo.CurrentCulture,\n                    \"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}\",\n                    formatter.GetType().Name,\n                    mediaType.MediaType,\n                    UnwrapException(e).Message))\n            Finally\n                If (Not MS Is Nothing) Then\n                    MS.Dispose()\n                End If\n                If (Not content Is Nothing) Then\n                    content.Dispose()\n                End If\n            End Try\n            Return sample\n        End Function\n\n        Friend Shared Function UnwrapException(exception As Exception) As Exception\n            Dim aggregateException As AggregateException = TryCast(exception, AggregateException)\n            If aggregateException IsNot Nothing Then\n                Return aggregateException.Flatten().InnerException\n            End If\n            Return exception\n        End Function\n\n        Private Shared Function DefaultSampleObjectFactory(sampleGenerator As HelpPageSampleGenerator, type As Type) As Object\n            ' Try create a default sample object\n            Dim objectGenerator As New ObjectGenerator()\n            Return objectGenerator.GenerateObject(type)\n        End Function\n\n        <SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification:=\"Handling the failure by returning the original string.\")>\n        Private Shared Function TryFormatJson(str As String) As String\n            Try\n                Dim parsedJson As Object = JsonConvert.DeserializeObject(str)\n                Return JsonConvert.SerializeObject(parsedJson, Formatting.Indented)\n            Catch\n                ' can't parse JSON, return the original string\n                Return str\n            End Try\n        End Function\n\n        <SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification:=\"Handling the failure by returning the original string.\")>\n        Private Shared Function TryFormatXml(str As String) As String\n            Try\n                Dim Xml As XDocument = XDocument.Parse(str)\n                Return Xml.ToString()\n            Catch\n                ' can't parse XML, return the original string\n                Return str\n            End Try\n        End Function\n\n        Private Shared Function IsFormatSupported(sampleDirection As SampleDirection, formatter As MediaTypeFormatter, type As Type) As Boolean\n            Select Case sampleDirection\n                Case sampleDirection.Request\n                    Return formatter.CanReadType(type)\n                Case sampleDirection.Response\n                    Return formatter.CanWriteType(type)\n            End Select\n            Return False\n        End Function\n\n        Private Iterator Function GetAllActionSamples(controllerName As String, actionName As String, parameterNames As IEnumerable(Of String), sampleDirection As SampleDirection) As IEnumerable(Of KeyValuePair(Of HelpPageSampleKey, Object))\n            Dim parameterNamesSet As New HashSet(Of String)(parameterNames, StringComparer.OrdinalIgnoreCase)\n            For Each sample In ActionSamples\n                Dim sampleKey As HelpPageSampleKey = sample.Key\n                If (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) And\n                        String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) And\n                        (sampleKey.ParameterNames.SetEquals(New String() {\"*\"}) Or parameterNamesSet.SetEquals(sampleKey.ParameterNames)) And\n                        sampleDirection = sampleKey.SampleDirection) Then\n                    Yield sample\n                End If\n            Next\n        End Function\n\n        Private Shared Function WrapSampleIfString(sample As Object) As Object\n            Dim stringSample As String = TryCast(sample, String)\n            If (Not stringSample Is Nothing) Then\n                Return New TextSample(stringSample)\n            End If\n            Return sample\n        End Function\n    End Class\nEnd Namespace"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/SampleGeneration/HelpPageSampleKey.vb",
    "content": "Imports System\nImports System.Collections.Generic\nImports System.ComponentModel\nImports System.Net.Http.Headers\n\nNamespace Areas.HelpPage\n    ''' <summary>\n    ''' This is used to identify the place where the sample should be applied.\n    ''' </summary>\n    Public Class HelpPageSampleKey\n        Private _actionName As String\n        Private _controllerName As String\n        Private _mediaType As MediaTypeHeaderValue\n        Private _parameterNames As HashSet(Of String)\n        Private _parameterType As Type\n        Private _sampleDirection As Nullable(Of SampleDirection)\n\n        ''' <summary>\n        ''' Creates a new <see cref=\"HelpPageSampleKey\"/> based on media type.\n        ''' </summary>\n        ''' <param name=\"mediaType\">The media type.</param>\n        Public Sub New(mediaType As MediaTypeHeaderValue)\n            If (mediaType Is Nothing) Then\n                Throw New ArgumentNullException(\"mediaType\")\n            End If\n\n            _actionName = String.Empty\n            _controllerName = String.Empty\n            _parameterNames = New HashSet(Of String)(StringComparer.OrdinalIgnoreCase)\n            _mediaType = mediaType\n        End Sub\n\n        ''' <summary>\n        ''' Creates a new <see cref=\"HelpPageSampleKey\"/> based on media type and CLR type.\n        ''' </summary>\n        ''' <param name=\"mediaType\">The media type.</param>\n        ''' <param name=\"type\">The CLR type.</param>\n        Public Sub New(mediaType As MediaTypeHeaderValue, type As Type)\n            MyClass.New(mediaType)\n\n            If (type Is Nothing) Then\n                Throw New ArgumentNullException(\"type\")\n            End If\n\n            _parameterType = type\n        End Sub\n\n        ''' <summary>\n        ''' Creates a new <see cref=\"HelpPageSampleKey\"/> based on <see cref=\"SampleDirection\"/>, controller name, action name and parameter names.\n        ''' </summary>\n        ''' <param name=\"sampleDirection\">The <see cref=\"SampleDirection\"/>.</param>\n        ''' <param name=\"controllerName\">Name of the controller.</param>\n        ''' <param name=\"actionName\">Name of the action.</param>\n        ''' <param name=\"parameterNames\">The parameter names.</param>\n        Public Sub New(sampleDirection As SampleDirection, controllerName As String, actionName As String, parameterNames As IEnumerable(Of String))\n            If (Not [Enum].IsDefined(GetType(SampleDirection), sampleDirection)) Then\n                Throw New InvalidEnumArgumentException(\"sampleDirection\", CInt(sampleDirection), GetType(SampleDirection))\n            End If\n            If (controllerName Is Nothing) Then\n                Throw New ArgumentNullException(\"controllerName\")\n            End If\n            If (actionName Is Nothing) Then\n                Throw New ArgumentNullException(\"actionName\")\n            End If\n            If (parameterNames Is Nothing) Then\n                Throw New ArgumentNullException(\"parameterNames\")\n            End If\n\n            _controllerName = controllerName\n            _actionName = actionName\n            _parameterNames = New HashSet(Of String)(parameterNames, StringComparer.OrdinalIgnoreCase)\n            _sampleDirection = sampleDirection\n        End Sub\n\n        ''' <summary>\n        ''' Creates a new <see cref=\"HelpPageSampleKey\"/> based on media type, <see cref=\"SampleDirection\"/>, controller name, action name and parameter names.\n        ''' </summary>\n        ''' <param name=\"mediaType\">The media type.</param>\n        ''' <param name=\"sampleDirection\">The <see cref=\"SampleDirection\"/>.</param>\n        ''' <param name=\"controllerName\">Name of the controller.</param>\n        ''' <param name=\"actionName\">Name of the action.</param>\n        ''' <param name=\"parameterNames\">The parameter names.</param>\n        Public Sub New(mediaType As MediaTypeHeaderValue, sampleDirection As SampleDirection, controllerName As String, actionName As String, parameterNames As IEnumerable(Of String))\n            MyClass.New(sampleDirection, controllerName, actionName, parameterNames)\n\n            If (mediaType Is Nothing) Then\n                Throw New ArgumentNullException(\"mediaType\")\n            End If\n\n            _mediaType = mediaType\n        End Sub\n\n        ''' <summary>\n        ''' Gets the name of the controller.\n        ''' </summary>\n        ''' <value>\n        ''' The name of the controller.\n        ''' </value>\n        Public ReadOnly Property ControllerName As String\n            Get\n                Return _controllerName\n            End Get\n        End Property\n\n        ''' <summary>\n        ''' Gets the name of the action.\n        ''' </summary>\n        ''' <value>\n        ''' The name of the action.\n        ''' </value>\n        Public ReadOnly Property ActionName As String\n            Get\n                Return _actionName\n            End Get\n        End Property\n\n        ''' <summary>\n        ''' Gets the media type.\n        ''' </summary>\n        ''' <value>\n        ''' The media type.\n        ''' </value>\n        Public ReadOnly Property MediaType As MediaTypeHeaderValue\n            Get\n                Return _mediaType\n            End Get\n        End Property\n\n        ''' <summary>\n        ''' Gets the parameter names.\n        ''' </summary>\n        Public ReadOnly Property ParameterNames As HashSet(Of String)\n            Get\n                Return _parameterNames\n            End Get\n        End Property\n\n        Public ReadOnly Property ParameterType As Type\n            Get\n                Return _parameterType\n            End Get\n        End Property\n\n        ''' <summary>\n        ''' Gets the <see cref=\"SampleDirection\"/>.\n        ''' </summary>\n        Public ReadOnly Property SampleDirection As Nullable(Of SampleDirection)\n            Get\n                Return _sampleDirection\n            End Get\n        End Property\n\n        Public Overrides Function Equals(obj As Object) As Boolean\n            Dim otherKey As HelpPageSampleKey = TryCast(obj, HelpPageSampleKey)\n            If (otherKey Is Nothing) Then\n                Return False\n            End If\n\n            Return String.Equals(ControllerName, otherKey.ControllerName, StringComparison.OrdinalIgnoreCase) And\n                String.Equals(ActionName, otherKey.ActionName, StringComparison.OrdinalIgnoreCase) And\n                (MediaType Is otherKey.MediaType Or (Not MediaType Is Nothing AndAlso MediaType.Equals(otherKey.MediaType))) And\n                ParameterType = otherKey.ParameterType And\n                SampleDirection.Equals(otherKey.SampleDirection) And\n                ParameterNames.SetEquals(otherKey.ParameterNames)\n        End Function\n\n        Public Overrides Function GetHashCode() As Integer\n            Dim hashCode As Integer = ControllerName.ToUpperInvariant().GetHashCode() Xor ActionName.ToUpperInvariant().GetHashCode()\n            If (Not MediaType Is Nothing) Then\n                hashCode = hashCode Xor MediaType.GetHashCode()\n            End If\n            If (SampleDirection.HasValue) Then\n                hashCode = hashCode Xor SampleDirection.GetHashCode()\n            End If\n            If (Not ParameterType Is Nothing) Then\n                hashCode = hashCode Xor ParameterType.GetHashCode()\n            End If\n            For Each parameterName As String In ParameterNames\n                hashCode = hashCode Xor parameterName.ToUpperInvariant().GetHashCode()\n            Next\n            Return hashCode\n        End Function\n    End Class\nEnd Namespace"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/SampleGeneration/ImageSample.vb",
    "content": "Imports System\n\nNamespace Areas.HelpPage\n    ''' <summary>\n    ''' This represents an image sample on the help page. There's a display template named ImageSample associated with this class.\n    ''' </summary>\n    Public Class ImageSample\n        Private _src As String\n\n        ''' <summary>\n        ''' Initializes a new instance of the <see cref=\"ImageSample\"/> class.\n        ''' </summary>\n        ''' <param name=\"src\">The URL of an image.</param>\n        Public Sub New(src As String)\n            If (src Is Nothing) Then\n                Throw New ArgumentNullException(\"src\")\n            End If\n            Me.Src = src\n        End Sub\n\n        Public Property Src As String\n            Get\n                Return _src\n            End Get\n            Private Set(value As String)\n                _src = value\n            End Set\n        End Property\n\n        Public Overrides Function Equals(obj As Object) As Boolean\n            Dim other As ImageSample = TryCast(obj, ImageSample)\n\n            Return Not other Is Nothing AndAlso Src = other.Src\n        End Function\n\n        Public Overrides Function GetHashCode() As Integer\n            Return Src.GetHashCode()\n        End Function\n\n        Public Overrides Function ToString() As String\n            Return Src\n        End Function\n    End Class\nEnd Namespace"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/SampleGeneration/InvalidSample.vb",
    "content": "Imports System\n\nNamespace Areas.HelpPage\n    ''' <summary>\n    ''' This represents an invalid sample on the help page. There's a display template named InvalidSample associated with this class.\n    ''' </summary>\n    Public Class InvalidSample\n        Private _errorMessage As String\n\n        Public Sub New(errorMessage As String)\n            If (errorMessage Is Nothing) Then\n                Throw New ArgumentNullException(\"errorMessage\")\n            End If\n\n            Me.ErrorMessage = errorMessage\n        End Sub\n\n        Public Property ErrorMessage As String\n            Get\n                Return _errorMessage\n            End Get\n            Private Set(value As String)\n                _errorMessage = value\n            End Set\n        End Property\n\n        Public Overrides Function Equals(obj As Object) As Boolean\n            Dim other As InvalidSample = TryCast(obj, InvalidSample)\n            Return Not other Is Nothing AndAlso ErrorMessage = other.ErrorMessage\n        End Function\n\n        Public Overrides Function GetHashCode() As Integer\n            Return ErrorMessage.GetHashCode()\n        End Function\n\n        Public Overrides Function ToString() As String\n            Return ErrorMessage\n        End Function\n    End Class\nEnd Namespace"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/SampleGeneration/ObjectGenerator.vb",
    "content": "Imports System\nImports System.Collections\nImports System.Collections.Generic\nImports System.Diagnostics.CodeAnalysis\nImports System.Globalization\nImports System.Linq\nImports System.Reflection\nImports Microsoft.VisualBasic\n\nNamespace Areas.HelpPage\n    ''' <summary>\n    ''' This class will create an object of a given type and populate it with sample data.\n    ''' </summary>\n    Public Class ObjectGenerator\n        Friend Const DefaultCollectionSize As Integer = 2\n        Private ReadOnly SimpleObjectGenerator As New SimpleTypeObjectGenerator()\n\n        ''' <summary>\n        ''' Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:\n        ''' Simple types: <see cref=\"int\"/>, <see cref=\"string\"/>, <see cref=\"[Enum]\"/>, <see cref=\"DateTime\"/>, <see cref=\"Uri\"/>, etc.\n        ''' Complex types: POCO types.\n        ''' Nullables: <see cref=\"Nullable(Of T)\"/>.\n        ''' Arrays: arrays of simple types or complex types.\n        ''' Key value pairs: <see cref=\"KeyValuePair(Of TKey,TValue)\"/>\n        ''' Tuples: <see cref=\"Tuple(Of T1)\"/>, <see cref=\"Tuple(Of T1,T2)\"/>, etc\n        ''' Dictionaries: <see cref=\"IDictionary(Of TKey,TValue)\"/> or anything deriving from <see cref=\"IDictionary(Of TKey,TValue)\"/>.\n        ''' Collections: <see cref=\"IList(Of T)\"/>, <see cref=\"IEnumerable(Of T)\"/>, <see cref=\"ICollection(Of T)\"/>, <see cref=\"IList\"/>, <see cref=\"IEnumerable\"/>, <see cref=\"ICollection\"/> or anything deriving from <see cref=\"ICollection(Of T)\"/> or <see cref=\"IList\"/>.\n        ''' Queryables: <see cref=\"System.Linq.IQueryable\"/>, <see cref=\"IQueryable(Of T)\"/>.\n        ''' </summary>\n        ''' <param name=\"type\">The type.</param>\n        ''' <returns>An object of the given type.</returns>\n        Public Function GenerateObject(type As Type) As Object\n            GenerateObject = GenerateObject(type, New Dictionary(Of Type, Object)())\n        End Function\n\n        <SuppressMessage(\"Microsoft.Design\", \"CA1031:DoNotCatchGeneralExceptionTypes\", Justification:=\"Here we just want to return null if anything goes wrong.\")>\n        Private Function GenerateObject(type As Type, createdObjectReferences As Dictionary(Of Type, Object)) As Object\n            Try\n                If (SimpleTypeObjectGenerator.CanGenerateObject(type)) Then\n                    Return SimpleObjectGenerator.GenerateObject(type)\n                End If\n\n                If (type.IsArray) Then\n                    Return GenerateArray(type, DefaultCollectionSize, createdObjectReferences)\n                End If\n\n                If (type.IsGenericType) Then\n                    Return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences)\n                End If\n\n                If (type Is GetType(IDictionary)) Then\n                    Return GenerateDictionary(GetType(Hashtable), DefaultCollectionSize, createdObjectReferences)\n                End If\n\n                If (GetType(IDictionary).IsAssignableFrom(type)) Then\n                    Return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences)\n                End If\n\n                If (type Is GetType(IList) Or\n                        type Is GetType(IEnumerable) Or\n                        type Is GetType(ICollection)) Then\n                    Return GenerateCollection(GetType(ArrayList), DefaultCollectionSize, createdObjectReferences)\n                End If\n\n                If (GetType(IList).IsAssignableFrom(type)) Then\n                    Return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences)\n                End If\n\n                If (type Is GetType(IQueryable)) Then\n                    Return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences)\n                End If\n\n                If (type.IsEnum) Then\n                    Return GenerateEnum(type)\n                End If\n\n                If (type.IsPublic Or type.IsNestedPublic) Then\n                    Return GenerateComplexObject(type, createdObjectReferences)\n                End If\n            Catch\n                ' Returns Nothing if anything fails\n                Return Nothing\n            End Try\n\n            Return Nothing\n        End Function\n\n        Private Shared Function GenerateGenericType(type As Type, collectionSize As Integer, createdObjectReferences As Dictionary(Of Type, Object)) As Object\n            Dim genericTypeDefinition As Type = type.GetGenericTypeDefinition()\n\n            If (genericTypeDefinition Is GetType(Nullable()) Or genericTypeDefinition Is GetType(Nullable(Of ))) Then\n                Return GenerateNullable(type, createdObjectReferences)\n            End If\n\n            If (genericTypeDefinition Is GetType(KeyValuePair(Of ,))) Then\n                Return GenerateKeyValuePair(type, createdObjectReferences)\n            End If\n\n            If (IsTuple(genericTypeDefinition)) Then\n                Return GenerateTuple(type, createdObjectReferences)\n            End If\n\n            Dim genericArguments() As Type = type.GetGenericArguments()\n\n            If (genericArguments.Length = 1) Then\n                If (genericTypeDefinition Is GetType(IList(Of )) Or\n                    genericTypeDefinition Is GetType(IEnumerable(Of )) Or\n                    genericTypeDefinition Is GetType(ICollection(Of ))) Then\n\n                    Dim collectionType As Type = GetType(List(Of )).MakeGenericType(genericArguments)\n                    Return GenerateCollection(collectionType, collectionSize, createdObjectReferences)\n                End If\n\n                If (genericTypeDefinition Is GetType(IQueryable(Of ))) Then\n                    Return GenerateQueryable(type, collectionSize, createdObjectReferences)\n                End If\n\n                Dim closedCollectionType As Type = GetType(ICollection(Of )).MakeGenericType(genericArguments(0))\n                If (closedCollectionType.IsAssignableFrom(type)) Then\n                    Return GenerateCollection(type, collectionSize, createdObjectReferences)\n                End If\n            End If\n\n            If (genericArguments.Length = 2) Then\n                If (genericTypeDefinition Is GetType(IDictionary(Of ,))) Then\n                    Dim dictionaryType As Type = GetType(Dictionary(Of ,)).MakeGenericType(genericArguments)\n                    Return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences)\n                End If\n\n                Dim closedDictionaryType As Type = GetType(IDictionary(Of ,)).MakeGenericType(genericArguments(0), genericArguments(1))\n                If (closedDictionaryType.IsAssignableFrom(type)) Then\n                    Return GenerateDictionary(type, collectionSize, createdObjectReferences)\n                End If\n            End If\n\n            If (type.IsPublic Or type.IsNestedPublic) Then\n                Return GenerateComplexObject(type, createdObjectReferences)\n            End If\n\n            Return Nothing\n        End Function\n\n        Private Shared Function GenerateTuple(type As Type, createdObjectReferences As Dictionary(Of Type, Object)) As Object\n            Dim genericArgs() As Type = type.GetGenericArguments()\n            Dim parameterValues(genericArgs.Length - 1) As Object\n            Dim failedToCreateTuple As Boolean = True\n\n            Dim objectGenerator As New ObjectGenerator()\n            For i As Integer = 0 To genericArgs.Length - 1\n                parameterValues(i) = objectGenerator.GenerateObject(genericArgs(i), createdObjectReferences)\n                failedToCreateTuple = failedToCreateTuple And (parameterValues(i) Is Nothing)\n            Next\n\n            If (failedToCreateTuple) Then\n                Return Nothing\n            End If\n\n            Return Activator.CreateInstance(type, parameterValues)\n        End Function\n\n        Private Shared Function IsTuple(genericTypeDefinition As Type) As Boolean\n            Return (genericTypeDefinition Is GetType(Tuple(Of )) Or\n                genericTypeDefinition Is GetType(Tuple(Of ,)) Or\n                genericTypeDefinition Is GetType(Tuple(Of ,,)) Or\n                genericTypeDefinition Is GetType(Tuple(Of ,,,)) Or\n                genericTypeDefinition Is GetType(Tuple(Of ,,,,)) Or\n                genericTypeDefinition Is GetType(Tuple(Of ,,,,,)) Or\n                genericTypeDefinition Is GetType(Tuple(Of ,,,,,,)) Or\n                genericTypeDefinition Is GetType(Tuple(Of ,,,,,,,)))\n        End Function\n\n        Private Shared Function GenerateKeyValuePair(keyValuePairType As Type, createdObjectReferences As Dictionary(Of Type, Object)) As Object\n            Dim genericArgs() As Type = keyValuePairType.GetGenericArguments()\n            Dim typeK As Type = genericArgs(0)\n            Dim typeV As Type = genericArgs(1)\n\n            Dim objectGenerator As New ObjectGenerator()\n\n            Dim keyObject As Object = objectGenerator.GenerateObject(typeK, createdObjectReferences)\n            Dim valueObject As Object = objectGenerator.GenerateObject(typeV, createdObjectReferences)\n            If (keyObject Is Nothing And valueObject Is Nothing) Then\n                ' Failed to create key and values\n                Return Nothing\n            End If\n\n            Return Activator.CreateInstance(keyValuePairType, keyObject, valueObject)\n        End Function\n\n        Private Shared Function GenerateArray(arrayType As Type, size As Integer, createdObjectReferences As Dictionary(Of Type, Object)) As Object\n            Dim type As Type = arrayType.GetElementType()\n            Dim result As Array = Array.CreateInstance(type, size)\n            Dim areAllElementsNothing As Boolean = True\n\n            Dim objectGenerator As New ObjectGenerator()\n\n            For i As Integer = 0 To size - 1\n                Dim element As Object = objectGenerator.GenerateObject(type, createdObjectReferences)\n                result.SetValue(element, i)\n                areAllElementsNothing = areAllElementsNothing And (element Is Nothing)\n            Next\n\n            If (areAllElementsNothing) Then\n                Return Nothing\n            End If\n\n            Return result\n        End Function\n\n        Private Shared Function GenerateDictionary(dictionaryType As Type, size As Integer, createdObjectReferences As Dictionary(Of Type, Object)) As Object\n            Dim typeK As Type = GetType(Object)\n            Dim typeV As Type = GetType(Object)\n            If (dictionaryType.IsGenericType) Then\n                Dim genericArgs() As Type = dictionaryType.GetGenericArguments()\n                typeK = genericArgs(0)\n                typeV = genericArgs(1)\n            End If\n\n            Dim result As Object = Activator.CreateInstance(dictionaryType)\n            Dim addMethod As MethodInfo = If(dictionaryType.GetMethod(\"Add\"), dictionaryType.GetMethod(\"TryAdd\"))\n            Dim containsMethod As MethodInfo = If(dictionaryType.GetMethod(\"Contains\"), dictionaryType.GetMethod(\"ContainsKey\"))\n\n            Dim objectGenerator As New ObjectGenerator()\n\n            For i As Integer = 0 To size - 1\n                Dim newKey As Object = objectGenerator.GenerateObject(typeK, createdObjectReferences)\n                If (newKey Is Nothing) Then\n                    ' Cannot generate a valid key\n                    Return Nothing\n                End If\n\n                Dim containsKey As Boolean = DirectCast(containsMethod.Invoke(result, New Object() {newKey}), Boolean)\n\n                If Not containsKey Then\n                    Dim newValue As Object = objectGenerator.GenerateObject(typeV, createdObjectReferences)\n                    addMethod.Invoke(result, New Object() {newKey, newValue})\n                End If\n            Next\n\n            Return result\n        End Function\n\n        Private Shared Function GenerateEnum(enumType As Type) As Object\n            Dim possibleValues As Array = [Enum].GetValues(enumType)\n            If possibleValues.Length > 0 Then\n                Return possibleValues.GetValue(0)\n            End If\n            Return Nothing\n        End Function\n\n        Private Shared Function GenerateQueryable(queryableType As Type, size As Integer, createdObjectReferences As Dictionary(Of Type, Object)) As Object\n            Dim isGeneric As Boolean = queryableType.IsGenericType\n            Dim list As Object = Nothing\n            If (isGeneric) Then\n                Dim listType As Type = GetType(List(Of )).MakeGenericType(queryableType.GetGenericArguments())\n                list = GenerateCollection(listType, size, createdObjectReferences)\n            Else\n                list = GenerateArray(GetType(Object()), size, createdObjectReferences)\n            End If\n\n            If (list Is Nothing) Then\n                Return Nothing\n            End If\n\n            If (isGeneric) Then\n                Dim argumentType As Type = GetType(IEnumerable(Of )).MakeGenericType(queryableType.GetGenericArguments())\n                Dim asQueryableMethod As MethodInfo = GetType(Queryable).GetMethod(\"AsQueryable\", New Type() {argumentType})\n                Return asQueryableMethod.Invoke(Nothing, New Object() {list})\n            End If\n\n            Return Queryable.AsQueryable(DirectCast(list, IEnumerable))\n        End Function\n\n        Private Shared Function GenerateCollection(collectionType As Type, size As Integer, createdObjectReferences As Dictionary(Of Type, Object)) As Object\n            Dim type As Type = If(collectionType.IsGenericType, collectionType.GetGenericArguments()(0), GetType(Object))\n\n            Dim result As Object = Activator.CreateInstance(collectionType)\n            Dim addMethod As MethodInfo = collectionType.GetMethod(\"Add\")\n            Dim areAllElementsNothing As Boolean = True\n            Dim objectGenerator As New ObjectGenerator()\n\n            For i As Integer = 0 To size - 1\n                Dim element As Object = objectGenerator.GenerateObject(type, createdObjectReferences)\n                addMethod.Invoke(result, New Object() {element})\n                areAllElementsNothing = areAllElementsNothing And (element Is Nothing)\n            Next\n\n            If (areAllElementsNothing) Then\n                Return Nothing\n            End If\n\n            Return result\n        End Function\n\n        Private Shared Function GenerateNullable(nullableType As Type, createdObjectReferences As Dictionary(Of Type, Object)) As Object\n            Dim type As Type = nullableType.GetGenericArguments()(0)\n            Dim objectGenerator As New ObjectGenerator()\n            Return objectGenerator.GenerateObject(type, createdObjectReferences)\n        End Function\n\n        Private Shared Function GenerateComplexObject(type As Type, createdObjectReferences As Dictionary(Of Type, Object)) As Object\n            Dim result As Object = Nothing\n\n            If (createdObjectReferences.TryGetValue(type, result)) Then\n                ' The object has been created already, just return it. This will handle the circular reference case.\n                Return result\n            End If\n\n            If (type.IsValueType) Then\n                result = Activator.CreateInstance(type)\n            Else\n                Dim defaultCtor As ConstructorInfo = type.GetConstructor(type.EmptyTypes)\n                If (defaultCtor Is Nothing) Then\n                    ' Cannot instantiate the type because it doesn't have a default constructor\n                    Return Nothing\n                End If\n\n                result = defaultCtor.Invoke(New Object() {})\n            End If\n\n            createdObjectReferences.Add(type, result)\n            SetPublicProperties(type, result, createdObjectReferences)\n            SetPublicFields(type, result, createdObjectReferences)\n            Return result\n        End Function\n\n        Private Shared Sub SetPublicProperties(type As Type, obj As Object, createdObjectReferences As Dictionary(Of Type, Object))\n            Dim properties() As PropertyInfo = type.GetProperties(BindingFlags.Public Or BindingFlags.Instance)\n            Dim objectGenerator As New ObjectGenerator()\n            For Each prop As PropertyInfo In properties\n                If (prop.CanWrite) Then\n                    Dim propertyValue As Object = objectGenerator.GenerateObject(prop.PropertyType, createdObjectReferences)\n                    prop.SetValue(obj, propertyValue, Nothing)\n                End If\n            Next\n        End Sub\n\n        Private Shared Sub SetPublicFields(type As Type, obj As Object, createdObjectReferences As Dictionary(Of Type, Object))\n            Dim fields() As FieldInfo = type.GetFields(BindingFlags.Public Or BindingFlags.Instance)\n            Dim objectGenerator As New ObjectGenerator()\n            For Each field As FieldInfo In fields\n                Dim fieldValue As Object = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences)\n                field.SetValue(obj, fieldValue)\n            Next\n        End Sub\n\n        Private Class SimpleTypeObjectGenerator\n            Private _index As Long = 0\n\n            Private Shared ReadOnly DefaultGenerators As Dictionary(Of Type, Func(Of Long, Object)) = InitializeGenerators()\n\n            <SuppressMessage(\"Microsoft.Maintainability\", \"CA1502:AvoidExcessiveComplexity\", Justification:=\"These are simple type factories and cannot be split up.\")>\n            Private Shared Function InitializeGenerators() As Dictionary(Of Type, Func(Of Long, Object))\n                Return New Dictionary(Of Type, Func(Of Long, Object)) From\n                {\n                    {GetType(Boolean), Function(index As Long) True},\n                    {GetType(Byte), Function(index As Long) CByte(64)},\n                    {GetType(Char), Function(index As Long) ChrW(65)},\n                    {GetType(DateTime), Function(index As Long) DateTime.Now},\n                    {GetType(DateTimeOffset), Function(index As Long) New DateTimeOffset(DateTime.Now)},\n                    {GetType(DBNull), Function(index As Long) DBNull.Value},\n                    {GetType(Decimal), Function(index As Long) CDec(index)},\n                    {GetType(Double), Function(index As Long) CDbl(index) + 0.1},\n                    {GetType(Guid), Function(index As Long) Guid.NewGuid()},\n                    {GetType(Int16), Function(index As Long) CType(index Mod Int16.MaxValue, Int16)},\n                    {GetType(Int32), Function(index As Long) CType(index Mod Int32.MaxValue, Int32)},\n                    {GetType(Int64), Function(index As Long) CType(index, Int64)},\n                    {GetType(Object), Function(index As Long) New Object},\n                    {GetType(SByte), Function(index As Long) CSByte(64)},\n                    {GetType(Single), Function(index As Long) CSng(index + 0.1)},\n                    {GetType(String), Function(index As Long) String.Format(CultureInfo.CurrentCulture, \"sample string {0}\", index)},\n                    {GetType(TimeSpan), Function(index As Long) TimeSpan.FromTicks(1234567)},\n                    {GetType(UInt16), Function(index As Long) CType(index Mod UInt16.MaxValue, UInt16)},\n                    {GetType(UInt32), Function(index As Long) CType(index Mod UInt32.MaxValue, UInt32)},\n                    {GetType(UInt64), Function(index As Long) CType(index, UInt64)},\n                    {GetType(Uri), Function(index As Long) New Uri(String.Format(CultureInfo.CurrentCulture, \"http://webapihelppage{0}.com\", index))}\n                }\n            End Function\n\n            Public Shared Function CanGenerateObject(type As Type) As Boolean\n                Return DefaultGenerators.ContainsKey(type)\n            End Function\n\n            Public Function GenerateObject(type As Type) As Object\n                _index += 1\n                Return DefaultGenerators(type)(_index)\n            End Function\n        End Class\n    End Class\nEnd Namespace"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/SampleGeneration/SampleDirection.vb",
    "content": "Namespace Areas.HelpPage\n    ''' <summary>\n    ''' Indicates whether the sample is used for request or response\n    ''' </summary>\n    Public Enum SampleDirection\n        Request = 0\n        Response\n    End Enum\nEnd Namespace"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/SampleGeneration/TextSample.vb",
    "content": "Imports System\n\nNamespace Areas.HelpPage\n    ''' <summary>\n    ''' This represents a preformatted text sample on the help page. There's a display template named TextSample associated with this class.\n    ''' </summary>\n    Public Class TextSample\n        Private _text As String\n\n        Public Sub New(text As String)\n            If (text Is Nothing) Then\n                Throw New ArgumentNullException(\"text\")\n            End If\n            Me.Text = text\n        End Sub\n\n        Public Property Text As String\n            Get\n                Return _text\n            End Get\n            Private Set(value As String)\n                _text = value\n            End Set\n        End Property\n\n        Public Overrides Function Equals(obj As Object) As Boolean\n            Equals = False\n            Dim other As TextSample = TryCast(obj, TextSample)\n            If Not (other Is Nothing) Then\n                Equals = (Text = other.Text)\n            End If\n        End Function\n\n        Public Overrides Function GetHashCode() As Integer\n            Return Text.GetHashCode()\n        End Function\n\n        Public Overrides Function ToString() As String\n            Return Text\n        End Function\n    End Class\nEnd Namespace"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/Views/Help/Api.vbhtml",
    "content": "@Imports System.Web.Http\n@Imports System.Web.Http.Description\n@Imports ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Models\n@ModelType HelpPageApiModel\n\n@Code\n    Dim description As ApiDescription = Model.ApiDescription\n    ViewData(\"Title\") = description.HttpMethod.Method + \" \" + description.RelativePath\nEnd Code\n\n<link type=\"text/css\" href=\"~/Areas/HelpPage/HelpPage.css\" rel=\"stylesheet\" />\n<div id=\"body\" class=\"help-page\">\n    <section class=\"featured\">\n        <div class=\"content-wrapper\">\n            <p>\n                @Html.ActionLink(\"Help Page Home\", \"Index\")\n            </p>\n        </div>\n    </section>\n    <section class=\"content-wrapper main-content clear-fix\">\n        @Html.DisplayForModel()\n    </section>\n</div>\n"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/Views/Help/DisplayTemplates/ApiGroup.vbhtml",
    "content": "@Imports System.Web.Http\n@Imports System.Web.Http.Controllers\n@Imports System.Web.Http.Description\n@Imports ROOT_PROJECT_NAMESPACE.Areas.HelpPage\n@ModelType IGrouping(Of HttpControllerDescriptor, ApiDescription)\n\n@Code\n    Dim controllerDocumentation As String = If(Not ViewData(\"DocumentationProvider\") Is Nothing,\n        ViewData(\"DocumentationProvider\").GetDocumentation(Model.Key),\n        Nothing)\nEnd Code\n\n<h2 id=\"@Model.Key.ControllerName\">@Model.Key.ControllerName</h2>\n@If Not controllerDocumentation Is Nothing Then\n    @<p>@controllerDocumentation</p>\nEnd If\n<table class=\"help-page-table\">\n    <thead>\n        <tr><th>API</th><th>Description</th></tr>\n    </thead>\n    <tbody>\n    @For Each api As ApiDescription In Model\n        @<tr>\n            <td class=\"api-name\"><a href=\"@Url.Action(\"Api\", \"Help\", routeValues:=New With {.apiId = api.GetFriendlyId()})\">@api.HttpMethod.Method @api.RelativePath</a></td>\n            <td class=\"api-documentation\">\n            @If Not api.Documentation Is Nothing Then\n                @<p>@api.Documentation</p>\n            Else\n                @<p>No documentation available.</p>\n            End If\n            </td>\n        </tr>\n    Next\n    </tbody>\n</table>"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/Views/Help/DisplayTemplates/CollectionModelDescription.vbhtml",
    "content": "@Imports ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n@ModelType CollectionModelDescription\n@If TypeOf Model.ElementDescription Is ComplexTypeModelDescription Then\n    @Html.DisplayFor(Function(m) m.ElementDescription)\nEnd If"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/Views/Help/DisplayTemplates/ComplexTypeModelDescription.vbhtml",
    "content": "@Imports ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n@ModelType ComplexTypeModelDescription\n@Html.DisplayFor(Function(m) Model.Properties, \"Parameters\")\n"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/Views/Help/DisplayTemplates/DictionaryModelDescription.vbhtml",
    "content": "@Imports ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n@ModelType DictionaryModelDescription\nDictionary of @Html.DisplayFor(Function(m) Model.KeyModelDescription.ModelType, \"ModelDescriptionLink\", New With { .modelDescription = Model.KeyModelDescription }) [key]\nand @Html.DisplayFor(Function(m) Model.ValueModelDescription.ModelType, \"ModelDescriptionLink\", New With { .modelDescription = Model.ValueModelDescription }) [value]"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/Views/Help/DisplayTemplates/EnumTypeModelDescription.vbhtml",
    "content": "@Imports ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n@ModelType EnumTypeModelDescription\n\n<p>Possible enumeration values:</p>\n\n<table class=\"help-page-table\">\n    <thead>\n        <tr><th>Name</th><th>Value</th><th>Description</th></tr>\n    </thead>\n    <tbody>\n        @For Each value As EnumValueDescription In Model.Values        \n            @<tr>\n                <td class=\"enum-name\"><b>@value.Name</b></td>\n                <td class=\"enum-value\">\n                    <p>@value.Value</p>\n                </td>\n                <td class=\"enum-description\">\n                    <p>@value.Documentation</p>\n                </td>\n            </tr>\n        Next\n    </tbody>\n</table>"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/Views/Help/DisplayTemplates/HelpPageApiModel.vbhtml",
    "content": "@Imports System.Web.Http\n@Imports System.Web.Http.Description\n@Imports ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Models\n@Imports ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n@ModelType HelpPageApiModel\n\n@Code\n    Dim description As ApiDescription = Model.ApiDescription\nEnd Code\n\n<h1>@description.HttpMethod.Method @description.RelativePath</h1>\n<div>\n    <p>@description.Documentation</p>\n\n    <h2>Request Information</h2>\n\n    <h3>URI Parameters</h3>\n    @Html.DisplayFor(Function(m) m.UriParameters, \"Parameters\")\n\n    <h3>Body Parameters</h3>\n\n    <p>@Model.RequestDocumentation</p>\n\n    @If Model.RequestModelDescription IsNot Nothing Then\n        @Html.DisplayFor(Function(m) m.RequestModelDescription.ModelType, \"ModelDescriptionLink\", New With {.modelDescription = Model.RequestModelDescription})\n        If Model.RequestBodyParameters IsNot Nothing Then\n            @Html.DisplayFor(Function(m) m.RequestBodyParameters, \"Parameters\")\n        End If \n    Else\n        @<p>None.</p>\n    End If\n\n    @If Model.SampleRequests.Count > 0 Then\n        @<h3>Request Formats</h3>\n        @Html.DisplayFor(Function(m) m.SampleRequests, \"Samples\")\n    End If \n\n    <h2>Response Information</h2>\n\n    <h3>Resource Description</h3>\n\n    <p>@description.ResponseDescription.Documentation</p>\n\n    @If Model.ResourceDescription IsNot Nothing Then\n        @Html.DisplayFor(Function(m) m.ResourceDescription.ModelType, \"ModelDescriptionLink\", New With {.modelDescription = Model.ResourceDescription})\n        If Model.ResourceProperties IsNot Nothing Then\n            @Html.DisplayFor(Function(m) m.ResourceProperties, \"Parameters\")\n        End If\n    Else\n        @<p>None.</p>\n    End If\n\n\n    @If Model.SampleResponses.Count > 0 Then\n        @<h3>Response Formats</h3>\n        @Html.DisplayFor(Function(m) m.SampleResponses, \"Samples\")\n    End If\n</div>\n"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/Views/Help/DisplayTemplates/ImageSample.vbhtml",
    "content": "@Imports ROOT_PROJECT_NAMESPACE.Areas.HelpPage\n@ModelType ImageSample\n\n<img src=\"@Model.Src\" />"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/Views/Help/DisplayTemplates/InvalidSample.vbhtml",
    "content": "@Imports ROOT_PROJECT_NAMESPACE.Areas.HelpPage\n@ModelType InvalidSample\n\n@If HttpContext.Current.IsDebuggingEnabled Then\n    @<div class=\"warning-message-container\">\n        <p>@Model.ErrorMessage</p>\n    </div>\nElse\n    @<p>Sample not available.</p>\nEnd If"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/Views/Help/DisplayTemplates/KeyValuePairModelDescription.vbhtml",
    "content": "@Imports ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n@ModelType KeyValuePairModelDescription\nPair of @Html.DisplayFor(Function(m) Model.KeyModelDescription.ModelType, \"ModelDescriptionLink\", New With { .modelDescription = Model.KeyModelDescription }) [key]\nand @Html.DisplayFor(Function(m) Model.ValueModelDescription.ModelType, \"ModelDescriptionLink\", New With { .modelDescription = Model.ValueModelDescription }) [value]"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/Views/Help/DisplayTemplates/ModelDescriptionLink.vbhtml",
    "content": "@Imports ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n@ModelType Type\n@Code\n    Dim modelDescription As ModelDescription = ViewBag.modelDescription\n    If TypeOf modelDescription Is ComplexTypeModelDescription Or TypeOf modelDescription Is EnumTypeModelDescription Then\n        If Model Is GetType(Object) Then\n            @:Object\n        Else\n            @Html.ActionLink(modelDescription.Name, \"ResourceModel\", \"Help\", New With {.modelName = modelDescription.Name}, Nothing)\n        End If\n    ElseIf TypeOf modelDescription Is CollectionModelDescription Then\n        Dim collectionDescription As CollectionModelDescription = DirectCast(modelDescription, CollectionModelDescription)\n        Dim elementDescription As ModelDescription = collectionDescription.ElementDescription\n        @:Collection of @Html.DisplayFor(Function(m) elementDescription.ModelType, \"ModelDescriptionLink\", New With {.modelDescription = elementDescription})\n    Else\n        @Html.DisplayFor(Function(m) modelDescription)\n    End If\nEnd Code\n"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/Views/Help/DisplayTemplates/Parameters.vbhtml",
    "content": "@Imports System.Collections.ObjectModel\n@Imports System.Web.Http.Description\n@Imports System.Threading\n@Imports ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n@ModelType IList(Of ParameterDescription)\n\n@If Model.Count > 0 Then\n    @<table class=\"help-page-table\">\n        <thead>\n            <tr><th>Name</th><th>Description</th><th>Type</th><th>Additional information</th></tr>\n        </thead>\n        <tbody>\n            @For Each parameter As ParameterDescription In Model\n                Dim modelDescription As ModelDescription = parameter.TypeDescription\n                @<tr>\n                    <td class=\"parameter-name\">@parameter.Name</td>\n                    <td class=\"parameter-documentation\">\n                        <p>@parameter.Documentation</p>\n                    </td>\n                    <td class=\"parameter-type\">\n                        @Html.DisplayFor(Function(m) modelDescription.ModelType, \"ModelDescriptionLink\", New With {.modelDescription = modelDescription})\n                    </td>\n                    <td class=\"parameter-annotations\">\n                        @If parameter.Annotations.Count > 0 Then\n                            @For Each annotation As ParameterAnnotation In parameter.Annotations\n                                @<p>@annotation.Documentation</p>\n                            Next\n                        else\n                            @<p>None.</p>\n                        End If \n                    </td>\n                </tr>\n            Next\n        </tbody>\n    </table>\nElse\n    @<p>None.</p>\nEnd If\n\n"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/Views/Help/DisplayTemplates/Samples.vbhtml",
    "content": "@Imports System.Net.Http.Headers\n@ModelType Dictionary(Of MediaTypeHeaderValue, Object)\n\n@Code\n    'Group the samples into a single tab if they are the same.\n    Dim samples As Dictionary(Of String, Object) = Model.GroupBy(Function(pair) pair.Value).ToDictionary(\n        Function(pair) String.Join(\", \", pair.Select(Function(m) m.Key.ToString()).ToArray()),\n        Function(pair) pair.Key)\n    Dim mediaTypes As Dictionary(Of String, Object).KeyCollection = samples.Keys\nEnd Code\n<div>\n    @For Each mediaType As String In mediaTypes\n        @<h4 class=\"sample-header\">@mediaType</h4>\n        @<div class=\"sample-content\">\n            <span><b>Sample:</b></span>\n            @Code\n            Dim sample As Object = samples(mediaType)\n            If sample Is Nothing Then\n                @<p>Sample not available.</p>\n            Else\n                @Html.DisplayFor(Function(s) sample)\n            End If\n            End code\n        </div>\n    Next\n</div>"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/Views/Help/DisplayTemplates/SimpleTypeModelDescription.vbhtml",
    "content": "@Imports ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n@ModelType SimpleTypeModelDescription\n@Model.Documentation"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/Views/Help/DisplayTemplates/TextSample.vbhtml",
    "content": "@Imports ROOT_PROJECT_NAMESPACE.Areas.HelpPage\n@ModelType TextSample\n\n<pre class=\"wrapped\">\n@Model.Text\n</pre>"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/Views/Help/Index.vbhtml",
    "content": "@Imports System.Web.Http\n@Imports System.Web.Http.Controllers\n@Imports System.Web.Http.Description\n@Imports System.Collections.ObjectModel\n@Imports ROOT_PROJECT_NAMESPACE.Areas.HelpPage\n@ModelType Collection(Of ApiDescription)\n\n@Code\n    ViewData(\"Title\") = \"ASP.NET Web API Help Page\"\n    \n    ' Group APIs by controller\n    Dim apiGroups As ILookup(Of HttpControllerDescriptor, ApiDescription) = Model.ToLookup(Function(api) api.ActionDescriptor.ControllerDescriptor)\nEnd Code\n\n<link type=\"text/css\" href=\"~/Areas/HelpPage/HelpPage.css\" rel=\"stylesheet\" />\n<header class=\"help-page\">\n    <div class=\"content-wrapper\">\n        <div class=\"float-left\">\n            <h1>@ViewData(\"Title\")</h1>\n        </div>\n    </div>\n</header>\n<div id=\"body\" class=\"help-page\">\n    <section class=\"featured\">\n        <div class=\"content-wrapper\">\n            <h2>Introduction</h2>\n            <p>\n                Provide a general description of your APIs here.\n            </p>\n        </div>\n    </section>\n    <section class=\"content-wrapper main-content clear-fix\">\n        @For Each group As IGrouping(Of HttpControllerDescriptor, ApiDescription) In apiGroups\n            @Html.DisplayFor(Function(m) group, \"ApiGroup\")\n        Next\n    </section>\n</div>\n"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/Views/Help/ResourceModel.vbhtml",
    "content": "@Imports System.Web.Http\n@Imports ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n@ModelType ModelDescription\n\n<link type=\"text/css\" href=\"~/Areas/HelpPage/HelpPage.css\" rel=\"stylesheet\" />\n<div id=\"body\" class=\"help-page\">\n    <section class=\"featured\">\n        <div class=\"content-wrapper\">\n            <p>\n                @Html.ActionLink(\"Help Page Home\", \"Index\")\n            </p>\n        </div>\n    </section>\n    <h1>@Model.Name</h1>\n    <p>@Model.Documentation</p>\n    <section class=\"content-wrapper main-content clear-fix\">\n        @Html.DisplayFor(Function(m) Model)\n    </section>\n</div>\n"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/Views/Shared/_Layout.vbhtml",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"utf-8\" />\n    <meta name=\"viewport\" content=\"width=device-width\" />\n    <title>@ViewData(\"Title\")</title>\n    @RenderSection(\"scripts\", required:=False)\n</head>\n<body>\n    @RenderBody()\n</body>\n</html>"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/Views/Web.config",
    "content": "<?xml version=\"1.0\"?>\n\n<configuration>\n  <configSections>\n    <sectionGroup name=\"system.web.webPages.razor\" type=\"System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\">\n      <section name=\"host\" type=\"System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\" requirePermission=\"false\" />\n      <section name=\"pages\" type=\"System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\" requirePermission=\"false\" />\n    </sectionGroup>\n  </configSections>\n\n  <system.web.webPages.razor>\n    <host factoryType=\"System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.3.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\" />\n    <pages pageBaseType=\"System.Web.Mvc.WebViewPage\">\n      <namespaces>\n        <add namespace=\"System.Web.Mvc\" />\n        <add namespace=\"System.Web.Mvc.Ajax\" />\n        <add namespace=\"System.Web.Mvc.Html\" />\n        <add namespace=\"System.Web.Routing\" />\n      </namespaces>\n    </pages>\n  </system.web.webPages.razor>\n\n  <appSettings>\n    <add key=\"webpages:Enabled\" value=\"false\" />\n  </appSettings>\n\n  <system.web>\n    <compilation debug=\"true\">\n      <assemblies>\n        <add assembly=\"System.Net.Http, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" />\n      </assemblies>\n    </compilation>\n  </system.web>\n\n  <system.webServer>\n    <handlers>\n      <remove name=\"BlockViewHandler\"/>\n      <add name=\"BlockViewHandler\" path=\"*\" verb=\"*\" preCondition=\"integratedMode\" type=\"System.Web.HttpNotFoundHandler\" />\n    </handlers>\n  </system.webServer>\n</configuration>\n"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/Views/_ViewStart.vbhtml",
    "content": "@Code\n    'Change the Layout path below to blend the look and feel of the help page with your existing web pages.\n    Layout = \"~/Areas/HelpPage/Views/Shared/_Layout.vbhtml\"\nEnd Code"
  },
  {
    "path": "src/WebApiHelpPage/VB/Areas/HelpPage/XmlDocumentationProvider.vb",
    "content": "Imports System\nImports System.Globalization\nImports System.Linq\nImports System.Reflection\nImports System.Web.Http.Controllers\nImports System.Web.Http.Description\nImports System.Xml.XPath\nImports ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\n\nNamespace Areas.HelpPage\n    ''' <summary>\n    ''' A custom <see cref=\"IDocumentationProvider\"/> that reads the API documentation from an XML documentation file.\n    ''' </summary>\n    Public Class XmlDocumentationProvider\n        Implements IDocumentationProvider\n        Implements IModelDocumentationProvider\n\n        Private _documentNavigator As XPathNavigator\n        Private Const TypeExpression As String = \"/doc/members/member[@name='T:{0}']\"\n        Private Const MethodExpression As String = \"/doc/members/member[@name='M:{0}']\"\n        Private Const PropertyExpression As String = \"/doc/members/member[@name='P:{0}']\"\n        Private Const FieldExpression As String = \"/doc/members/member[@name='F:{0}']\"\n        Private Const ParameterExpression As String = \"param[@name='{0}']\"\n\n        ''' <summary>\n        ''' Initializes a new instance of the <see cref=\"XmlDocumentationProvider\"/> class.\n        ''' </summary>\n        ''' <param name=\"documentPath\">The physical path to XML document.</param>\n        Public Sub New(documentPath As String)\n            If (documentPath Is Nothing) Then\n                Throw New ArgumentNullException(\"documentPath\")\n            End If\n            Dim xpath As New XPathDocument(documentPath)\n            _documentNavigator = xpath.CreateNavigator()\n        End Sub\n\n        Public Function GetDocumentation(controllerDescriptor As HttpControllerDescriptor) As String Implements IDocumentationProvider.GetDocumentation\n            Dim typeNode As XPathNavigator = GetTypeNode(controllerDescriptor.ControllerType)\n            Return GetTagValue(typeNode, \"summary\")\n        End Function\n\n        Public Function GetDocumentation(actionDescriptor As HttpActionDescriptor) As String Implements IDocumentationProvider.GetDocumentation\n            Dim methodNode As XPathNavigator = GetMethodNode(actionDescriptor)\n            Return GetTagValue(methodNode, \"summary\")\n        End Function\n\n        Public Function GetDocumentation(parameterDescriptor As HttpParameterDescriptor) As String Implements IDocumentationProvider.GetDocumentation\n            Dim reflectedParameterDescriptor As ReflectedHttpParameterDescriptor = TryCast(parameterDescriptor, ReflectedHttpParameterDescriptor)\n            If (Not reflectedParameterDescriptor Is Nothing) Then\n                Dim methodNode As XPathNavigator = GetMethodNode(reflectedParameterDescriptor.ActionDescriptor)\n                If (Not methodNode Is Nothing) Then\n                    Dim parameterName As String = reflectedParameterDescriptor.ParameterInfo.Name\n                    Dim parameterNode As XPathNavigator = methodNode.SelectSingleNode(String.Format(CultureInfo.InvariantCulture, ParameterExpression, parameterName))\n                    If (Not parameterNode Is Nothing) Then\n                        Return parameterNode.Value.Trim()\n                    End If\n                End If\n            End If\n\n            Return Nothing\n        End Function\n\n        Public Function GetResponseDocumentation(actionDescriptor As HttpActionDescriptor) As String Implements IDocumentationProvider.GetResponseDocumentation\n            Dim methodNode As XPathNavigator = GetMethodNode(actionDescriptor)\n            Return GetTagValue(methodNode, \"returns\")\n        End Function\n\n        Public Function GetDocumentation(member As MemberInfo) As String Implements IModelDocumentationProvider.GetDocumentation\n            Dim memberName As String = [String].Format(CultureInfo.InvariantCulture, \"{0}.{1}\", GetTypeName(member.DeclaringType), member.Name)\n            Dim expression As String = If(member.MemberType = MemberTypes.Field, FieldExpression, PropertyExpression)\n            Dim selectExpression As String = [String].Format(CultureInfo.InvariantCulture, expression, memberName)\n            Dim propertyNode As XPathNavigator = _documentNavigator.SelectSingleNode(selectExpression)\n            Return GetTagValue(propertyNode, \"summary\")\n        End Function\n\n        Public Function GetDocumentation(type As Type) As String Implements IModelDocumentationProvider.GetDocumentation\n            Dim typeNode As XPathNavigator = GetTypeNode(type)\n            Return GetTagValue(typeNode, \"summary\")\n        End Function\n\n        Private Function GetMethodNode(actionDescriptor As HttpActionDescriptor) As XPathNavigator\n            Dim reflectedActionDescriptor As ReflectedHttpActionDescriptor = TryCast(actionDescriptor, ReflectedHttpActionDescriptor)\n            If (Not reflectedActionDescriptor Is Nothing) Then\n                Dim selectExpression As String = String.Format(CultureInfo.InvariantCulture, MethodExpression, GetMemberName(reflectedActionDescriptor.MethodInfo))\n                Return _documentNavigator.SelectSingleNode(selectExpression)\n            End If\n\n            Return Nothing\n        End Function\n\n        Private Shared Function GetMemberName(method As MethodInfo) As String\n            Dim name As String = String.Format(CultureInfo.InvariantCulture, \"{0}.{1}\", method.DeclaringType.FullName, method.Name)\n            Dim parameters() As ParameterInfo = method.GetParameters()\n            If (parameters.Length <> 0) Then\n                Dim parameterTypeNames() As String = parameters.Select(Function(param) GetTypeName(param.ParameterType)).ToArray()\n                name += String.Format(CultureInfo.InvariantCulture, \"({0})\", String.Join(\",\", parameterTypeNames))\n            End If\n\n            Return name\n        End Function\n\n        Private Shared Function GetTagValue(parentNode As XPathNavigator, tagName As String) As String\n            If (Not parentNode Is Nothing) Then\n                Dim node As XPathNavigator = parentNode.SelectSingleNode(tagName)\n                If (Not node Is Nothing) Then\n                    Return node.Value.Trim()\n                End If\n            End If\n\n            Return Nothing\n        End Function\n\n        Private Function GetTypeNode(type As Type) As XPathNavigator\n            Dim controllerTypeName As String = GetTypeName(type)\n            Dim selectExpression As String = [String].Format(CultureInfo.InvariantCulture, TypeExpression, controllerTypeName)\n            Return _documentNavigator.SelectSingleNode(selectExpression)\n        End Function\n\n        Private Shared Function GetTypeName(type As Type) As String\n            Dim name As String = type.FullName\n            If type.IsGenericType Then\n                ' Format the generic type name to something like: Generic{System.Int32,System.String}\n                Dim genericType As Type = type.GetGenericTypeDefinition()\n                Dim genericArguments As Type() = type.GetGenericArguments()\n                Dim genericTypeName As String = genericType.FullName\n\n                ' Trim the generic parameter counts from the name\n                genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf(\"`\"c))\n                Dim argumentTypeNames As String() = genericArguments.[Select](Function(t) GetTypeName(t)).ToArray()\n                name = [String].Format(CultureInfo.InvariantCulture, \"{0}{{{1}}}\", genericTypeName, [String].Join(\",\", argumentTypeNames))\n            End If\n            If type.IsNested Then\n                ' Changing the nested type name from OuterType+InnerType to OuterType.InnerType to match the XML documentation syntax.\n                name = name.Replace(\"+\", \".\")\n            End If\n\n            Return name\n        End Function\n    End Class\nEnd Namespace"
  },
  {
    "path": "src/WebApiHelpPage/VB/GlobalSuppressions.vb",
    "content": "﻿'\n'\n' This file is used by Code Analysis to maintain SuppressMessage \n' attributes that are applied to this project.\n' Project-level suppressions either have no target or are given \n' a specific target and scoped to a namespace, type, member, etc.\n'\n' To add a suppression to this file, right-click the message in the \n' Code Analysis results, point to \"Suppress Message\", and click \n' \"In Suppression File\".\n' You do not need to add suppressions to this file manually.\n\n<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1707:IdentifiersShouldNotContainUnderscores\", Scope:=\"namespace\", Target:=\"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Controllers\", Justification:=\"This namespace will be replaced with the project namespace when the help page is installed.\")> \n<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1707:IdentifiersShouldNotContainUnderscores\", Scope:=\"namespace\", Target:=\"ROOT_PROJECT_NAMESPACE.Areas.HelpPage\", Justification:=\"This namespace will be replaced with the project namespace when the help page is installed.\")> \n<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1707:IdentifiersShouldNotContainUnderscores\", Scope:=\"namespace\", Target:=\"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Models\", Justification:=\"This namespace will be replaced with the project namespace when the help page is installed.\")> \n<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1709:IdentifiersShouldBeCasedCorrectly\", MessageId:=\"NAMESPACE\", Scope:=\"namespace\", Target:=\"ROOT_PROJECT_NAMESPACE.Areas.HelpPage\", Justification:=\"This namespace will be replaced with the project namespace when the help page is installed.\")> \n<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1709:IdentifiersShouldBeCasedCorrectly\", MessageId:=\"NAMESPACE\", Scope:=\"namespace\", Target:=\"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Controllers\", Justification:=\"This namespace will be replaced with the project namespace when the help page is installed.\")> \n<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1709:IdentifiersShouldBeCasedCorrectly\", MessageId:=\"NAMESPACE\", Scope:=\"namespace\", Target:=\"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Models\", Justification:=\"This namespace will be replaced with the project namespace when the help page is installed.\")> \n<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1709:IdentifiersShouldBeCasedCorrectly\", MessageId:=\"PROJECT\", Scope:=\"namespace\", Target:=\"ROOT_PROJECT_NAMESPACE.Areas.HelpPage\", Justification:=\"This namespace will be replaced with the project namespace when the help page is installed.\")> \n<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1709:IdentifiersShouldBeCasedCorrectly\", MessageId:=\"PROJECT\", Scope:=\"namespace\", Target:=\"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Controllers\", Justification:=\"This namespace will be replaced with the project namespace when the help page is installed.\")> \n<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1709:IdentifiersShouldBeCasedCorrectly\", MessageId:=\"PROJECT\", Scope:=\"namespace\", Target:=\"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Models\", Justification:=\"This namespace will be replaced with the project namespace when the help page is installed.\")> \n<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1709:IdentifiersShouldBeCasedCorrectly\", MessageId:=\"ROOT\", Scope:=\"namespace\", Target:=\"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Controllers\", Justification:=\"This namespace will be replaced with the project namespace when the help page is installed.\")> \n<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1709:IdentifiersShouldBeCasedCorrectly\", MessageId:=\"ROOT\", Scope:=\"namespace\", Target:=\"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Models\", Justification:=\"This namespace will be replaced with the project namespace when the help page is installed.\")> \n<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1709:IdentifiersShouldBeCasedCorrectly\", MessageId:=\"ROOT\", Scope:=\"namespace\", Target:=\"ROOT_PROJECT_NAMESPACE.Areas.HelpPage\", Justification:=\"This namespace will be replaced with the project namespace when the help page is installed.\")> \n<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope:=\"namespace\", Target:=\"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Controllers\", Justification:=\"This namespace will be replaced with the project namespace when the help page is installed.\")> \n<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope:=\"namespace\", Target:=\"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Models\", Justification:=\"This namespace will be replaced with the project namespace when the help page is installed.\")> \n<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Usage\", \"CA1801:ReviewUnusedParameters\", MessageId:=\"config\", Scope:=\"member\", Target:=\"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.HelpPageConfig.#Register(System.Web.Http.HttpConfiguration)\", Justification:=\"This parameter is part of the template and could be used later.\")> \n<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Design\", \"CA2210:AssembliesShouldHaveValidStrongNames\", Justification:=\"The assembly will not be deployed because we distribute the source code.\")> \n<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Web.FxCop\", \"MW1201:DoNotCallProblematicMethodsOnTaskRule\", Scope:=\"member\", Target:=\"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.HelpPageSampleGenerator.#WriteSampleObjectUsingFormatter(System.Net.Http.Formatting.MediaTypeFormatter,System.Object,System.Type,System.Net.Http.Headers.MediaTypeHeaderValue)\", Justification:=\"This is an internal FxCop rule and we ship the source file.\")> \n<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1709:IdentifiersShouldBeCasedCorrectly\", MessageId:=\"ROOT\", Scope:=\"namespace\", Target:=\"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\", Justification:=\"This namespace will be replaced with the project namespace when the help page is installed.\")> \n<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1707:IdentifiersShouldNotContainUnderscores\", Scope:=\"namespace\", Target:=\"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\", Justification:=\"This namespace will be replaced with the project namespace when the help page is installed.\")> \n<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1709:IdentifiersShouldBeCasedCorrectly\", MessageId:=\"PROJECT\", Scope:=\"namespace\", Target:=\"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\", Justification:=\"This namespace will be replaced with the project namespace when the help page is installed.\")> \n<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Naming\", \"CA1709:IdentifiersShouldBeCasedCorrectly\", MessageId:=\"NAMESPACE\", Scope:=\"namespace\", Target:=\"ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions\", Justification:=\"This namespace will be replaced with the project namespace when the help page is installed.\")> "
  },
  {
    "path": "src/WebApiHelpPage/VB/Properties/AssemblyInfo.vb",
    "content": "﻿' Copyright (c) .NET Foundation. All rights reserved.\n' Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nImports System\nImports System.Reflection\nImports System.Runtime.InteropServices\n\n<Assembly: AssemblyTitle(\"WebApiHelpPageVB\")>\n<Assembly: AssemblyDescription(\"\")>\n<Assembly: Guid(\"aa22bcbc-83b3-466d-a421-9c561e3625b7\")>"
  },
  {
    "path": "src/WebApiHelpPage/VB/Settings.StyleCop",
    "content": "<StyleCopSettings Version=\"105\">\n  <Analyzers>\n    <Analyzer AnalyzerId=\"Microsoft.Web.StyleCop.Rules\">\n      <Rules>\n        <Rule Name=\"FileMustHaveHeader\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n      </Rules>\n      <AnalyzerSettings />\n    </Analyzer>\n  </Analyzers>\n</StyleCopSettings>"
  },
  {
    "path": "src/WebApiHelpPage/VB/WebApiHelpPage.VB.nuspec",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<package>\n  <metadata>\n    <id>Microsoft.AspNet.WebApi.HelpPage.VB</id>\n    <version>5.1.0-alpha-0</version>\n    <title>Microsoft ASP.NET Web API Help Page (VB)</title>\n    <authors>Microsoft</authors>\n    <owners>Microsoft</owners>\n    <projectUrl>http://www.asp.net/web-api</projectUrl>\n    <repository type=\"git\" url=\"https://github.com/aspnet/AspNetWebStack\"/>\n    <description>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.</description>\n    <summary>The ASP.NET Web API Help Page automatically generates help page content for the web APIs on your site.</summary>\n    <dependencies>\n      <dependency id=\"Microsoft.AspNet.WebApi.WebHost\" version=\"[5.1.0-rc1, 5.1.65535.65535)\" />\n      <dependency id=\"Microsoft.AspNet.Mvc\" version=\"[5.1.0-rc1, 5.1.65535.65535)\" />\n      <dependency id=\"Microsoft.AspNet.Razor\" version=\"[3.1.0-rc1, 3.1.65535.65535)\" />\n    </dependencies>\n    <frameworkAssemblies>\n      <frameworkAssembly assemblyName=\"System.Runtime.Serialization\" />\n      <frameworkAssembly assemblyName=\"System.ComponentModel.DataAnnotations\"  />\n    </frameworkAssemblies>\n    <language>en-US</language>\n    <tags>Microsoft AspNet WebApi AspNetWebApi HelpPage VB VisualBasic</tags>\n  </metadata>\n  <files>\n    <file src=\"Areas\\HelpPage\\App_Start\\HelpPageConfig.vb.pp\" target=\"content\\Areas\\HelpPage\\App_Start\\HelpPageConfig.vb.pp\" />\n    <file src=\"Areas\\HelpPage\\Controllers\\HelpController.vb.pp\" target=\"content\\Areas\\HelpPage\\Controllers\\HelpController.vb.pp\" />\n    <file src=\"Areas\\HelpPage\\ModelDescriptions\\CollectionModelDescription.vb.pp\" target=\"content\\Areas\\HelpPage\\ModelDescriptions\\CollectionModelDescription.vb.pp\" />\n    <file src=\"Areas\\HelpPage\\ModelDescriptions\\ComplexTypeModelDescription.vb.pp\" target=\"content\\Areas\\HelpPage\\ModelDescriptions\\ComplexTypeModelDescription.vb.pp\" />\n    <file src=\"Areas\\HelpPage\\ModelDescriptions\\DictionaryModelDescription.vb.pp\" target=\"content\\Areas\\HelpPage\\ModelDescriptions\\DictionaryModelDescription.vb.pp\" />\n    <file src=\"Areas\\HelpPage\\ModelDescriptions\\EnumTypeModelDescription.vb.pp\" target=\"content\\Areas\\HelpPage\\ModelDescriptions\\EnumTypeModelDescription.vb.pp\" />\n    <file src=\"Areas\\HelpPage\\ModelDescriptions\\EnumValueDescription.vb.pp\" target=\"content\\Areas\\HelpPage\\ModelDescriptions\\EnumValueDescription.vb.pp\" />\n    <file src=\"Areas\\HelpPage\\ModelDescriptions\\IModelDocumentationProvider.vb.pp\" target=\"content\\Areas\\HelpPage\\ModelDescriptions\\IModelDocumentationProvider.vb.pp\" />\n    <file src=\"Areas\\HelpPage\\ModelDescriptions\\KeyValuePairModelDescription.vb.pp\" target=\"content\\Areas\\HelpPage\\ModelDescriptions\\KeyValuePairModelDescription.vb.pp\" />\n    <file src=\"Areas\\HelpPage\\ModelDescriptions\\ModelDescription.vb.pp\" target=\"content\\Areas\\HelpPage\\ModelDescriptions\\ModelDescription.vb.pp\" />\n    <file src=\"Areas\\HelpPage\\ModelDescriptions\\ModelNameAttribute.vb.pp\" target=\"content\\Areas\\HelpPage\\ModelDescriptions\\ModelNameAttribute.vb.pp\" />\n    <file src=\"Areas\\HelpPage\\ModelDescriptions\\ModelNameHelper.vb.pp\" target=\"content\\Areas\\HelpPage\\ModelDescriptions\\ModelNameHelper.vb.pp\" />\n    <file src=\"Areas\\HelpPage\\ModelDescriptions\\ModelDescriptionGenerator.vb.pp\" target=\"content\\Areas\\HelpPage\\ModelDescriptions\\ModelDescriptionGenerator.vb.pp\" />\n    <file src=\"Areas\\HelpPage\\ModelDescriptions\\ParameterDescription.vb.pp\" target=\"content\\Areas\\HelpPage\\ModelDescriptions\\ParameterDescription.vb.pp\" />\n    <file src=\"Areas\\HelpPage\\ModelDescriptions\\ParameterAnnotation.vb.pp\" target=\"content\\Areas\\HelpPage\\ModelDescriptions\\ParameterAnnotation.vb.pp\" />\n    <file src=\"Areas\\HelpPage\\ModelDescriptions\\SimpleTypeModelDescription.vb.pp\" target=\"content\\Areas\\HelpPage\\ModelDescriptions\\SimpleTypeModelDescription.vb.pp\" />\n    <file src=\"Areas\\HelpPage\\Models\\HelpPageApiModel.vb.pp\" target=\"content\\Areas\\HelpPage\\Models\\HelpPageApiModel.vb.pp\" />\n    <file src=\"Areas\\HelpPage\\SampleGeneration\\HelpPageSampleGenerator.vb.pp\" target=\"content\\Areas\\HelpPage\\SampleGeneration\\HelpPageSampleGenerator.vb.pp\" />\n    <file src=\"Areas\\HelpPage\\SampleGeneration\\HelpPageSampleKey.vb.pp\" target=\"content\\Areas\\HelpPage\\SampleGeneration\\HelpPageSampleKey.vb.pp\" />\n    <file src=\"Areas\\HelpPage\\SampleGeneration\\ImageSample.vb.pp\" target=\"content\\Areas\\HelpPage\\SampleGeneration\\ImageSample.vb.pp\" />\n    <file src=\"Areas\\HelpPage\\SampleGeneration\\InvalidSample.vb.pp\" target=\"content\\Areas\\HelpPage\\SampleGeneration\\InvalidSample.vb.pp\" />\n    <file src=\"Areas\\HelpPage\\SampleGeneration\\ObjectGenerator.vb.pp\" target=\"content\\Areas\\HelpPage\\SampleGeneration\\ObjectGenerator.vb.pp\" />\n    <file src=\"Areas\\HelpPage\\SampleGeneration\\SampleDirection.vb.pp\" target=\"content\\Areas\\HelpPage\\SampleGeneration\\SampleDirection.vb.pp\" />\n    <file src=\"Areas\\HelpPage\\SampleGeneration\\TextSample.vb.pp\" target=\"content\\Areas\\HelpPage\\SampleGeneration\\TextSample.vb.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\ApiGroup.vbhtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\ApiGroup.vbhtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\CollectionModelDescription.vbhtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\CollectionModelDescription.vbhtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\ComplexTypeModelDescription.vbhtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\ComplexTypeModelDescription.vbhtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\DictionaryModelDescription.vbhtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\DictionaryModelDescription.vbhtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\EnumTypeModelDescription.vbhtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\EnumTypeModelDescription.vbhtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\HelpPageApiModel.vbhtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\HelpPageApiModel.vbhtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\ImageSample.vbhtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\ImageSample.vbhtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\InvalidSample.vbhtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\InvalidSample.vbhtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\KeyValuePairModelDescription.vbhtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\KeyValuePairModelDescription.vbhtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\ModelDescriptionLink.vbhtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\ModelDescriptionLink.vbhtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\Parameters.vbhtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\Parameters.vbhtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\Samples.vbhtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\Samples.vbhtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\SimpleTypeModelDescription.vbhtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\SimpleTypeModelDescription.vbhtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\TextSample.vbhtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\TextSample.vbhtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\Api.vbhtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\Api.vbhtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\Index.vbhtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\Index.vbhtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\ResourceModel.vbhtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\ResourceModel.vbhtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Shared\\_Layout.vbhtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Shared\\_Layout.vbhtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Web.config\" target=\"content\\Areas\\HelpPage\\Views\\Web.config\" />\n    <file src=\"Areas\\HelpPage\\Views\\_ViewStart.vbhtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\_ViewStart.vbhtml.pp\" />\n    <file src=\"Areas\\HelpPage\\ApiDescriptionExtensions.vb.pp\" target=\"content\\Areas\\HelpPage\\ApiDescriptionExtensions.vb.pp\" />\n    <file src=\"Areas\\HelpPage\\HelpPage.css.pp\" target=\"content\\Areas\\HelpPage\\HelpPage.css.pp\" />\n    <file src=\"Areas\\HelpPage\\HelpPageAreaRegistration.vb.pp\" target=\"content\\Areas\\HelpPage\\HelpPageAreaRegistration.vb.pp\" />\n    <file src=\"Areas\\HelpPage\\HelpPageConfigurationExtensions.vb.pp\" target=\"content\\Areas\\HelpPage\\HelpPageConfigurationExtensions.vb.pp\" />\n    <file src=\"Areas\\HelpPage\\XmlDocumentationProvider.vb.pp\" target=\"content\\Areas\\HelpPage\\XmlDocumentationProvider.vb.pp\" />\n  </files>\n</package>"
  },
  {
    "path": "src/WebApiHelpPage/VB/WebApiHelpPageVB.vbproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <Import Project=\"..\\WebApiHelpPageMsBuildTasks.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{22075D5A-E9A1-4E2D-ABA7-8E7CBF2A049E}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <RootNamespace>ROOT_PROJECT_NAMESPACE</RootNamespace>\n    <AssemblyName>WebApiHelpPageVB</AssemblyName>\n    <DocumentationFile>$(AssemblyName).xml</DocumentationFile>\n    <RunCodeAnalysis>$(CodeAnalysis)</RunCodeAnalysis>\n    <CodeAnalysisRuleSet>..\\..\\Strict.ruleset</CodeAnalysisRuleSet>\n    <MyType>Windows</MyType>\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\n    <DefineDebug>true</DefineDebug>\n    <DefineTrace>true</DefineTrace>\n    <DefineConstants>\n    </DefineConstants>\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\n    <DefineDebug>false</DefineDebug>\n    <DefineTrace>true</DefineTrace>\n    <DefineConstants>\n    </DefineConstants>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)' == 'CodeAnalysis|AnyCPU'\">\n    <DefineDebug>false</DefineDebug>\n    <DefineTrace>true</DefineTrace>\n    <DefineConstants>CodeAnalysis</DefineConstants>\n  </PropertyGroup>\n  <PropertyGroup>\n    <OptionExplicit>On</OptionExplicit>\n  </PropertyGroup>\n  <PropertyGroup>\n    <OptionCompare>Binary</OptionCompare>\n  </PropertyGroup>\n  <PropertyGroup>\n    <OptionStrict>Off</OptionStrict>\n  </PropertyGroup>\n  <PropertyGroup>\n    <OptionInfer>On</OptionInfer>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\..\\packages\\Newtonsoft.Json.13.0.1\\lib\\net45\\Newtonsoft.Json.dll</HintPath>\n      <SpecificVersion>False</SpecificVersion>\n      <Private>False</Private>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.ComponentModel.DataAnnotations\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Net.Http\" />\n    <Reference Include=\"System.Net.Http.WebRequest\" />\n    <Reference Include=\"System.Runtime.Serialization\" />\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"System.Xml.Linq\" />\n    <Reference Include=\"System.Data.DataSetExtensions\" />\n    <Reference Include=\"Microsoft.VisualBasic\" />\n    <Reference Include=\"System.Data\" />\n    <Reference Include=\"System.Xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"Areas\\HelpPage\\Controllers\\HelpController.vb\" />\n    <Compile Include=\"Areas\\HelpPage\\App_Start\\HelpPageConfig.vb\" />\n    <Compile Include=\"Areas\\HelpPage\\HelpPageAreaRegistration.vb\" />\n    <Compile Include=\"Areas\\HelpPage\\ApiDescriptionExtensions.vb\" />\n    <Compile Include=\"Areas\\HelpPage\\HelpPageConfigurationExtensions.vb\" />\n    <Compile Include=\"Areas\\HelpPage\\SampleGeneration\\ObjectGenerator.vb\" />\n    <Compile Include=\"Areas\\HelpPage\\SampleGeneration\\SampleDirection.vb\" />\n    <Compile Include=\"Areas\\HelpPage\\SampleGeneration\\InvalidSample.vb\" />\n    <Compile Include=\"Areas\\HelpPage\\SampleGeneration\\HelpPageSampleKey.vb\" />\n    <Compile Include=\"Areas\\HelpPage\\XmlDocumentationProvider.vb\" />\n    <Compile Include=\"Areas\\HelpPage\\Models\\HelpPageApiModel.vb\" />\n    <Compile Include=\"Areas\\HelpPage\\SampleGeneration\\TextSample.vb\" />\n    <Compile Include=\"Areas\\HelpPage\\SampleGeneration\\HelpPageSampleGenerator.vb\" />\n    <Compile Include=\"Areas\\HelpPage\\SampleGeneration\\ImageSample.vb\" />\n    <Compile Include=\"GlobalSuppressions.vb\" />\n    <Compile Include=\"Properties\\AssemblyInfo.vb\" />\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\Api.vbhtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\ApiGroup.vbhtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\CollectionModelDescription.vbhtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\ComplexTypeModelDescription.vbhtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\DictionaryModelDescription.vbhtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\EnumTypeModelDescription.vbhtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\HelpPageApiModel.vbhtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\InvalidSample.vbhtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\ImageSample.vbhtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\KeyValuePairModelDescription.vbhtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\ModelDescriptionLink.vbhtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\Parameters.vbhtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\Samples.vbhtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\SimpleTypeModelDescription.vbhtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\TextSample.vbhtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\Index.vbhtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\ResourceModel.vbhtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Web.config\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Shared\\_Layout.vbhtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\_ViewStart.vbhtml\" />\n    <None Include=\"packages.config\">\n      <SubType>Designer</SubType>\n    </None>\n  </ItemGroup>\n  <ItemGroup>\n    <CodeAnalysisDictionary Include=\"..\\..\\CodeAnalysisDictionary.xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Content Include=\"Areas\\HelpPage\\HelpPage.css\" />\n    <Compile Include=\"Areas\\HelpPage\\ModelDescriptions\\CollectionModelDescription.vb\" />\n    <Compile Include=\"Areas\\HelpPage\\ModelDescriptions\\ComplexTypeModelDescription.vb\" />\n    <Compile Include=\"Areas\\HelpPage\\ModelDescriptions\\DictionaryModelDescription.vb\" />\n    <Compile Include=\"Areas\\HelpPage\\ModelDescriptions\\EnumTypeModelDescription.vb\" />\n    <Compile Include=\"Areas\\HelpPage\\ModelDescriptions\\EnumValueDescription.vb\" />\n    <Compile Include=\"Areas\\HelpPage\\ModelDescriptions\\IModelDocumentationProvider.vb\" />\n    <Compile Include=\"Areas\\HelpPage\\ModelDescriptions\\KeyValuePairModelDescription.vb\" />\n    <Compile Include=\"Areas\\HelpPage\\ModelDescriptions\\ModelDescription.vb\" />\n    <Compile Include=\"Areas\\HelpPage\\ModelDescriptions\\ModelDescriptionGenerator.vb\" />\n    <Compile Include=\"Areas\\HelpPage\\ModelDescriptions\\ModelNameAttribute.vb\" />\n    <Compile Include=\"Areas\\HelpPage\\ModelDescriptions\\ModelNameHelper.vb\" />\n    <Compile Include=\"Areas\\HelpPage\\ModelDescriptions\\ParameterAnnotation.vb\" />\n    <Compile Include=\"Areas\\HelpPage\\ModelDescriptions\\ParameterDescription.vb\" />\n    <Compile Include=\"Areas\\HelpPage\\ModelDescriptions\\SimpleTypeModelDescription.vb\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\..\\CommonAssemblyInfo.vb\">\n      <Link>Properties\\CommonAssemblyInfo.cs</Link>\n    </Compile>\n  </ItemGroup>\n  <ItemGroup>\n    <Folder Include=\"My Project\\\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\..\\System.Net.Http.Formatting\\System.Net.Http.Formatting.csproj\">\n      <Project>{668e9021-ce84-49d9-98fb-df125a9fcdb0}</Project>\n      <Name>System.Net.Http.Formatting</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\System.Web.Helpers\\System.Web.Helpers.csproj\">\n      <Project>{9b7e3740-6161-4548-833c-4bbca43b970e}</Project>\n      <Name>System.Web.Helpers</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\System.Web.Http.WebHost\\System.Web.Http.WebHost.csproj\">\n      <Project>{a0187bc2-8325-4bb2-8697-7f955cf4173e}</Project>\n      <Name>System.Web.Http.WebHost</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\System.Web.Http\\System.Web.Http.csproj\">\n      <Project>{ddc1ce0c-486e-4e35-bb3b-eab61f8f9440}</Project>\n      <Name>System.Web.Http</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\System.Web.Mvc\\System.Web.Mvc.csproj\">\n      <Project>{3d3ffd8a-624d-4e9b-954b-e1c105507975}</Project>\n      <Name>System.Web.Mvc</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\System.Web.Razor\\System.Web.Razor.csproj\">\n      <Project>{8f18041b-9410-4c36-a9c5-067813df5f31}</Project>\n      <Name>System.Web.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\System.Web.WebPages.Deployment\\System.Web.WebPages.Deployment.csproj\">\n      <Project>{22babb60-8f02-4027-affc-acf069954536}</Project>\n      <Name>System.Web.WebPages.Deployment</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\System.Web.WebPages.Razor\\System.Web.WebPages.Razor.csproj\">\n      <Project>{0939b11a-fe4e-4ba1-8ad6-d97741ee314f}</Project>\n      <Name>System.Web.WebPages.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\System.Web.WebPages\\System.Web.WebPages.csproj\">\n      <Project>{76efa9c5-8d7e-4fdf-b710-e20f8b6b00d2}</Project>\n      <Name>System.Web.WebPages</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.VisualBasic.targets\" />\n  <Target Name=\"AfterBuild\">\n    <!--Build the NuGet package for help page-->\n    <ItemGroup>\n      <SourceFiles Include=\"Areas/**/*.*\" />\n    </ItemGroup>\n    <MakeDir Directories=\"$(OutputPath)\\NuGet\" />\n    <ConvertToNuGetTransformationFiles SourceFiles=\"@(SourceFiles)\" OutputPath=\"$(OutputPath)VB\\\" OriginalNamespaceToken=\"ROOT_PROJECT_NAMESPACE\" ReplacementNamespaceToken=\"$rootnamespace$\" />\n    <NuGetPack NuGetExe=\"..\\..\\..\\.nuget\\NuGet.exe\" Source=\"$(ProjectDir)WebApiHelpPage.VB.nuspec\" BasePath=\"$(OutputPath)VB\" OutputDirectory=\"$(OutputPath)NuGet\" />\n  </Target>\n</Project>"
  },
  {
    "path": "src/WebApiHelpPage/VB/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Microsoft.Web.Infrastructure\" version=\"1.0.0.0\" targetFramework=\"net40\" />\n  <package id=\"Newtonsoft.Json\" version=\"13.0.1\" targetFramework=\"net45\" />\n</packages>"
  },
  {
    "path": "src/WebApiHelpPage/WebApiHelpPage.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <Import Project=\"WebApiHelpPageMsBuildTasks.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{FEDFE6CA-8282-4C5B-A756-E97189690982}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>WebApiHelpPage</RootNamespace>\n    <AssemblyName>WebApiHelpPage</AssemblyName>\n    <DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>\n    <RunCodeAnalysis>$(CodeAnalysis)</RunCodeAnalysis>\n    <CodeAnalysisRuleSet>..\\Strict.ruleset</CodeAnalysisRuleSet>\n    <DefineConstants>$(DefineConstants);ASPNETMVC</DefineConstants>\n    <NoWarn>1591</NoWarn>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Newtonsoft.Json.13.0.1\\lib\\net45\\Newtonsoft.Json.dll</HintPath>\n      <SpecificVersion>False</SpecificVersion>\n      <Private>False</Private>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.ComponentModel.DataAnnotations\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Net.Http\" />\n    <Reference Include=\"System.Net.Http.WebRequest\" />\n    <Reference Include=\"System.Runtime.Serialization\" />\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"System.Xml.Linq\" />\n    <Reference Include=\"System.Data.DataSetExtensions\" />\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"System.Data\" />\n    <Reference Include=\"System.Xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"Areas\\HelpPage\\Controllers\\HelpController.cs\" />\n    <Compile Include=\"Areas\\HelpPage\\App_Start\\HelpPageConfig.cs\" />\n    <Compile Include=\"Areas\\HelpPage\\HelpPageAreaRegistration.cs\" />\n    <Compile Include=\"Areas\\HelpPage\\ApiDescriptionExtensions.cs\" />\n    <Compile Include=\"Areas\\HelpPage\\HelpPageConfigurationExtensions.cs\" />\n    <Compile Include=\"Areas\\HelpPage\\ModelDescriptions\\CollectionModelDescription.cs\" />\n    <Compile Include=\"Areas\\HelpPage\\ModelDescriptions\\ComplexTypeModelDescription.cs\" />\n    <Compile Include=\"Areas\\HelpPage\\ModelDescriptions\\ParameterAnnotation.cs\" />\n    <Compile Include=\"Areas\\HelpPage\\ModelDescriptions\\DictionaryModelDescription.cs\" />\n    <Compile Include=\"Areas\\HelpPage\\ModelDescriptions\\EnumTypeModelDescription.cs\" />\n    <Compile Include=\"Areas\\HelpPage\\ModelDescriptions\\EnumValueDescription.cs\" />\n    <Compile Include=\"Areas\\HelpPage\\ModelDescriptions\\IModelDocumentationProvider.cs\" />\n    <Compile Include=\"Areas\\HelpPage\\ModelDescriptions\\KeyValuePairModelDescription.cs\" />\n    <Compile Include=\"Areas\\HelpPage\\ModelDescriptions\\ModelDescription.cs\" />\n    <Compile Include=\"Areas\\HelpPage\\ModelDescriptions\\ModelDescriptionGenerator.cs\" />\n    <Compile Include=\"Areas\\HelpPage\\ModelDescriptions\\ModelNameAttribute.cs\" />\n    <Compile Include=\"Areas\\HelpPage\\ModelDescriptions\\ModelNameHelper.cs\" />\n    <Compile Include=\"Areas\\HelpPage\\ModelDescriptions\\ParameterDescription.cs\" />\n    <Compile Include=\"Areas\\HelpPage\\ModelDescriptions\\SimpleTypeModelDescription.cs\" />\n    <Compile Include=\"Areas\\HelpPage\\SampleGeneration\\ObjectGenerator.cs\" />\n    <Compile Include=\"Areas\\HelpPage\\SampleGeneration\\SampleDirection.cs\" />\n    <Compile Include=\"Areas\\HelpPage\\SampleGeneration\\InvalidSample.cs\" />\n    <Compile Include=\"Areas\\HelpPage\\SampleGeneration\\HelpPageSampleKey.cs\" />\n    <Compile Include=\"Areas\\HelpPage\\XmlDocumentationProvider.cs\" />\n    <Compile Include=\"Areas\\HelpPage\\Models\\HelpPageApiModel.cs\" />\n    <Compile Include=\"Areas\\HelpPage\\SampleGeneration\\TextSample.cs\" />\n    <Compile Include=\"Areas\\HelpPage\\SampleGeneration\\HelpPageSampleGenerator.cs\" />\n    <Compile Include=\"Areas\\HelpPage\\SampleGeneration\\ImageSample.cs\" />\n    <Compile Include=\"GlobalSuppressions.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\Api.cshtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\ApiGroup.cshtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\CollectionModelDescription.cshtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\ComplexTypeModelDescription.cshtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\DictionaryModelDescription.cshtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\EnumTypeModelDescription.cshtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\HelpPageApiModel.cshtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\InvalidSample.cshtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\ImageSample.cshtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\KeyValuePairModelDescription.cshtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\ModelDescriptionLink.cshtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\Parameters.cshtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\Samples.cshtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\SimpleTypeModelDescription.cshtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\TextSample.cshtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\Index.cshtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Help\\ResourceModel.cshtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Web.config\" />\n    <None Include=\"Areas\\HelpPage\\Views\\Shared\\_Layout.cshtml\" />\n    <None Include=\"Areas\\HelpPage\\Views\\_ViewStart.cshtml\" />\n    <None Include=\"packages.config\">\n      <SubType>Designer</SubType>\n    </None>\n  </ItemGroup>\n  <ItemGroup>\n    <CodeAnalysisDictionary Include=\"..\\CodeAnalysisDictionary.xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Content Include=\"Areas\\HelpPage\\HelpPage.css\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\CommonAssemblyInfo.cs\">\n      <Link>Properties\\CommonAssemblyInfo.cs</Link>\n    </Compile>\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\System.Net.Http.Formatting\\System.Net.Http.Formatting.csproj\">\n      <Project>{668e9021-ce84-49d9-98fb-df125a9fcdb0}</Project>\n      <Name>System.Net.Http.Formatting</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.Helpers\\System.Web.Helpers.csproj\">\n      <Project>{9b7e3740-6161-4548-833c-4bbca43b970e}</Project>\n      <Name>System.Web.Helpers</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.Http.WebHost\\System.Web.Http.WebHost.csproj\">\n      <Project>{a0187bc2-8325-4bb2-8697-7f955cf4173e}</Project>\n      <Name>System.Web.Http.WebHost</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.Http\\System.Web.Http.csproj\">\n      <Project>{ddc1ce0c-486e-4e35-bb3b-eab61f8f9440}</Project>\n      <Name>System.Web.Http</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.Mvc\\System.Web.Mvc.csproj\">\n      <Project>{3d3ffd8a-624d-4e9b-954b-e1c105507975}</Project>\n      <Name>System.Web.Mvc</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.Razor\\System.Web.Razor.csproj\">\n      <Project>{8f18041b-9410-4c36-a9c5-067813df5f31}</Project>\n      <Name>System.Web.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.WebPages.Deployment\\System.Web.WebPages.Deployment.csproj\">\n      <Project>{22babb60-8f02-4027-affc-acf069954536}</Project>\n      <Name>System.Web.WebPages.Deployment</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.WebPages.Razor\\System.Web.WebPages.Razor.csproj\">\n      <Project>{0939b11a-fe4e-4ba1-8ad6-d97741ee314f}</Project>\n      <Name>System.Web.WebPages.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.WebPages\\System.Web.WebPages.csproj\">\n      <Project>{76efa9c5-8d7e-4fdf-b710-e20f8b6b00d2}</Project>\n      <Name>System.Web.WebPages</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  <Target Name=\"AfterBuild\">\n    <!--Build the NuGet package for help page-->\n    <ItemGroup>\n      <SourceFiles Include=\"Areas/**/*.*\" />\n    </ItemGroup>\n    <MakeDir Directories=\"$(OutputPath)\\NuGet\" />\n    <ConvertToNuGetTransformationFiles SourceFiles=\"@(SourceFiles)\" OutputPath=\"$(OutputPath)\" OriginalNamespaceToken=\"ROOT_PROJECT_NAMESPACE\" ReplacementNamespaceToken=\"$rootnamespace$\" />\n    <NuGetPack NuGetExe=\"..\\..\\.nuget\\NuGet.exe\" Source=\"$(ProjectDir)WebApiHelpPage.nuspec\" BasePath=\"$(OutputPath).\" OutputDirectory=\"$(OutputPath)NuGet\" />\n  </Target>\n</Project>"
  },
  {
    "path": "src/WebApiHelpPage/WebApiHelpPage.nuspec",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<package>\n  <metadata>\n    <id>Microsoft.AspNet.WebApi.HelpPage</id>\n    <version>5.1.0-alpha-0</version>\n    <title>Microsoft ASP.NET Web API Help Page</title>\n    <authors>Microsoft</authors>\n    <owners>Microsoft</owners>\n    <projectUrl>http://www.asp.net/web-api</projectUrl>\n    <repository type=\"git\" url=\"https://github.com/aspnet/AspNetWebStack\"/>\n    <description>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.</description>\n    <summary>The ASP.NET Web API Help Page automatically generates help page content for the web APIs on your site.</summary>\n    <dependencies>\n      <dependency id=\"Microsoft.AspNet.WebApi.WebHost\" version=\"[5.1.0-rc1, 5.1.65535.65535)\" />\n      <dependency id=\"Microsoft.AspNet.Mvc\" version=\"[5.1.0-rc1, 5.1.65535.65535)\" />\n      <dependency id=\"Microsoft.AspNet.Razor\" version=\"[3.1.0-rc1, 3.1.65535.65535)\" />\n    </dependencies>\n    <frameworkAssemblies>\n      <frameworkAssembly assemblyName=\"System.Runtime.Serialization\" />\n      <frameworkAssembly assemblyName=\"System.ComponentModel.DataAnnotations\"  />\n    </frameworkAssemblies>\n    <language>en-US</language>\n    <tags>Microsoft AspNet WebApi AspNetWebApi HelpPage</tags>\n  </metadata>\n  <files>\n    <file src=\"Areas\\HelpPage\\App_Start\\HelpPageConfig.cs.pp\" target=\"content\\Areas\\HelpPage\\App_Start\\HelpPageConfig.cs.pp\" />\n    <file src=\"Areas\\HelpPage\\Controllers\\HelpController.cs.pp\" target=\"content\\Areas\\HelpPage\\Controllers\\HelpController.cs.pp\" />\n    <file src=\"Areas\\HelpPage\\ModelDescriptions\\CollectionModelDescription.cs.pp\" target=\"content\\Areas\\HelpPage\\ModelDescriptions\\CollectionModelDescription.cs.pp\" />\n    <file src=\"Areas\\HelpPage\\ModelDescriptions\\ComplexTypeModelDescription.cs.pp\" target=\"content\\Areas\\HelpPage\\ModelDescriptions\\ComplexTypeModelDescription.cs.pp\" />\n    <file src=\"Areas\\HelpPage\\ModelDescriptions\\DictionaryModelDescription.cs.pp\" target=\"content\\Areas\\HelpPage\\ModelDescriptions\\DictionaryModelDescription.cs.pp\" />\n    <file src=\"Areas\\HelpPage\\ModelDescriptions\\EnumTypeModelDescription.cs.pp\" target=\"content\\Areas\\HelpPage\\ModelDescriptions\\EnumTypeModelDescription.cs.pp\" />\n    <file src=\"Areas\\HelpPage\\ModelDescriptions\\EnumValueDescription.cs.pp\" target=\"content\\Areas\\HelpPage\\ModelDescriptions\\EnumValueDescription.cs.pp\" />\n    <file src=\"Areas\\HelpPage\\ModelDescriptions\\IModelDocumentationProvider.cs.pp\" target=\"content\\Areas\\HelpPage\\ModelDescriptions\\IModelDocumentationProvider.cs.pp\" />\n    <file src=\"Areas\\HelpPage\\ModelDescriptions\\KeyValuePairModelDescription.cs.pp\" target=\"content\\Areas\\HelpPage\\ModelDescriptions\\KeyValuePairModelDescription.cs.pp\" />\n    <file src=\"Areas\\HelpPage\\ModelDescriptions\\ModelDescription.cs.pp\" target=\"content\\Areas\\HelpPage\\ModelDescriptions\\ModelDescription.cs.pp\" />\n    <file src=\"Areas\\HelpPage\\ModelDescriptions\\ModelNameAttribute.cs.pp\" target=\"content\\Areas\\HelpPage\\ModelDescriptions\\ModelNameAttribute.cs.pp\" />\n    <file src=\"Areas\\HelpPage\\ModelDescriptions\\ModelNameHelper.cs.pp\" target=\"content\\Areas\\HelpPage\\ModelDescriptions\\ModelNameHelper.cs.pp\" />\n    <file src=\"Areas\\HelpPage\\ModelDescriptions\\ModelDescriptionGenerator.cs.pp\" target=\"content\\Areas\\HelpPage\\ModelDescriptions\\ModelDescriptionGenerator.cs.pp\" />\n    <file src=\"Areas\\HelpPage\\ModelDescriptions\\ParameterDescription.cs.pp\" target=\"content\\Areas\\HelpPage\\ModelDescriptions\\ParameterDescription.cs.pp\" />\n    <file src=\"Areas\\HelpPage\\ModelDescriptions\\ParameterAnnotation.cs.pp\" target=\"content\\Areas\\HelpPage\\ModelDescriptions\\ParameterAnnotation.cs.pp\" />\n    <file src=\"Areas\\HelpPage\\ModelDescriptions\\SimpleTypeModelDescription.cs.pp\" target=\"content\\Areas\\HelpPage\\ModelDescriptions\\SimpleTypeModelDescription.cs.pp\" />\n    <file src=\"Areas\\HelpPage\\Models\\HelpPageApiModel.cs.pp\" target=\"content\\Areas\\HelpPage\\Models\\HelpPageApiModel.cs.pp\" />\n    <file src=\"Areas\\HelpPage\\SampleGeneration\\HelpPageSampleGenerator.cs.pp\" target=\"content\\Areas\\HelpPage\\SampleGeneration\\HelpPageSampleGenerator.cs.pp\" />\n    <file src=\"Areas\\HelpPage\\SampleGeneration\\HelpPageSampleKey.cs.pp\" target=\"content\\Areas\\HelpPage\\SampleGeneration\\HelpPageSampleKey.cs.pp\" />\n    <file src=\"Areas\\HelpPage\\SampleGeneration\\ImageSample.cs.pp\" target=\"content\\Areas\\HelpPage\\SampleGeneration\\ImageSample.cs.pp\" />\n    <file src=\"Areas\\HelpPage\\SampleGeneration\\InvalidSample.cs.pp\" target=\"content\\Areas\\HelpPage\\SampleGeneration\\InvalidSample.cs.pp\" />\n    <file src=\"Areas\\HelpPage\\SampleGeneration\\ObjectGenerator.cs.pp\" target=\"content\\Areas\\HelpPage\\SampleGeneration\\ObjectGenerator.cs.pp\" />\n    <file src=\"Areas\\HelpPage\\SampleGeneration\\SampleDirection.cs.pp\" target=\"content\\Areas\\HelpPage\\SampleGeneration\\SampleDirection.cs.pp\" />\n    <file src=\"Areas\\HelpPage\\SampleGeneration\\TextSample.cs.pp\" target=\"content\\Areas\\HelpPage\\SampleGeneration\\TextSample.cs.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\ApiGroup.cshtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\ApiGroup.cshtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\CollectionModelDescription.cshtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\CollectionModelDescription.cshtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\ComplexTypeModelDescription.cshtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\ComplexTypeModelDescription.cshtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\DictionaryModelDescription.cshtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\DictionaryModelDescription.cshtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\EnumTypeModelDescription.cshtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\EnumTypeModelDescription.cshtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\HelpPageApiModel.cshtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\HelpPageApiModel.cshtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\ImageSample.cshtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\ImageSample.cshtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\InvalidSample.cshtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\InvalidSample.cshtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\KeyValuePairModelDescription.cshtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\KeyValuePairModelDescription.cshtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\ModelDescriptionLink.cshtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\ModelDescriptionLink.cshtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\Parameters.cshtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\Parameters.cshtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\Samples.cshtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\Samples.cshtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\SimpleTypeModelDescription.cshtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\SimpleTypeModelDescription.cshtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\TextSample.cshtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\DisplayTemplates\\TextSample.cshtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\Api.cshtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\Api.cshtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\Index.cshtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\Index.cshtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Help\\ResourceModel.cshtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Help\\ResourceModel.cshtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Shared\\_Layout.cshtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\Shared\\_Layout.cshtml.pp\" />\n    <file src=\"Areas\\HelpPage\\Views\\Web.config\" target=\"content\\Areas\\HelpPage\\Views\\Web.config\" />\n    <file src=\"Areas\\HelpPage\\Views\\_ViewStart.cshtml.pp\" target=\"content\\Areas\\HelpPage\\Views\\_ViewStart.cshtml.pp\" />\n    <file src=\"Areas\\HelpPage\\ApiDescriptionExtensions.cs.pp\" target=\"content\\Areas\\HelpPage\\ApiDescriptionExtensions.cs.pp\" />\n    <file src=\"Areas\\HelpPage\\HelpPage.css.pp\" target=\"content\\Areas\\HelpPage\\HelpPage.css.pp\" />\n    <file src=\"Areas\\HelpPage\\HelpPageAreaRegistration.cs.pp\" target=\"content\\Areas\\HelpPage\\HelpPageAreaRegistration.cs.pp\" />\n    <file src=\"Areas\\HelpPage\\HelpPageConfigurationExtensions.cs.pp\" target=\"content\\Areas\\HelpPage\\HelpPageConfigurationExtensions.cs.pp\" />\n    <file src=\"Areas\\HelpPage\\XmlDocumentationProvider.cs.pp\" target=\"content\\Areas\\HelpPage\\XmlDocumentationProvider.cs.pp\" />\n  </files>\n</package>"
  },
  {
    "path": "src/WebApiHelpPage/WebApiHelpPageMsBuildTasks.targets",
    "content": "<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"..\\..\\tools\\WebStack.tasks.targets\"/>\n  <UsingTask TaskName=\"NuGetPack\" TaskFactory=\"CodeTaskFactory\" AssemblyFile=\"$(CodeTaskFactoryAssemblyFile)\">\n    <ParameterGroup>\n      <NuGetExe ParameterType=\"System.String\" Required=\"true\" />\n      <Source ParameterType=\"System.String\" Required=\"true\" />\n      <OutputDirectory ParameterType=\"System.String\" Required=\"true\" />\n      <BasePath ParameterType=\"System.String\" Required=\"true\" />\n    </ParameterGroup>\n    <Task>\n      <Reference Include=\"$(BuildTaskAssemblyReference)\" />\n      <Using Namespace=\"System.Net\" />\n      <Using Namespace=\"Microsoft.Build.Tasks\" />\n      <Code Type=\"Fragment\" Language=\"cs\">\n        <![CDATA[\n          try\n          {\n            NuGetExe = Path.GetFullPath(NuGetExe);\n\n            if (!File.Exists(NuGetExe))\n            {\n              string tempFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());\n\n              try\n              {\n                Log.LogMessage(\"Downloading latest version of NuGet.exe...\");\n                WebClient webClient = new WebClient();\n                webClient.DownloadFile(\"https://nuget.org/nuget.exe\", tempFile);\n\n                if (!File.Exists(NuGetExe))\n                {\n                  try\n                  {\n                    File.Move(tempFile, NuGetExe);\n                  }\n                  catch (IOException)\n                  {\n                    // Another project downloaded and moved the file before us. That's OK; just delete this duplicate\n                    // temp copy and continue.\n                  }\n                }\n              }\n              finally\n              {\n                File.Delete(tempFile);\n              }\n            }\n          }\n          catch (Exception ex)\n          {\n              Log.LogErrorFromException(ex);\n              return false;\n          }\n\n          Exec execTask = new Exec();\n          execTask.BuildEngine = BuildEngine;\n          execTask.HostObject = HostObject;\n\n          execTask.Command = String.Format(@\"\"\"{0}\"\" pack \"\"{1}\"\" -OutputDirectory \"\"{2}\"\" -BasePath \"\"{3}\"\"\",\n            NuGetExe, Path.GetFullPath(Source), Path.GetFullPath(OutputDirectory), Path.GetFullPath(BasePath));\n\n          return execTask.Execute();\n        ]]>\n      </Code>\n    </Task>\n  </UsingTask>\n  <UsingTask TaskName=\"ConvertToNuGetTransformationFiles\" TaskFactory=\"CodeTaskFactory\" AssemblyFile=\"$(CodeTaskFactoryAssemblyFile)\">\n    <ParameterGroup>\n      <OutputPath ParameterType=\"System.String\" Required=\"true\" />\n      <OriginalNamespaceToken ParameterType=\"System.String\" Required=\"true\" />\n      <ReplacementNamespaceToken ParameterType=\"System.String\" Required=\"true\" />\n      <SourceFiles ParameterType=\"Microsoft.Build.Framework.ITaskItem[]\" Required=\"true\" />\n    </ParameterGroup>\n    <Task>\n      <Code Type=\"Fragment\" Language=\"cs\">\n        <![CDATA[\n          foreach (var sourceFile in SourceFiles)\n          {\n            string sourceFilePath = sourceFile.GetMetadata(\"FullPath\");\n            string relativeDirectory = sourceFile.GetMetadata(\"RelativeDir\");\n            string fileName = sourceFile.GetMetadata(\"Filename\");\n            string extension = sourceFile.GetMetadata(\"Extension\");\n            string destinationDirectory = Path.Combine(OutputPath, relativeDirectory);\n            string destinationFilePath = Path.Combine(destinationDirectory, fileName + extension);\n\n            DirectoryInfo dir = new DirectoryInfo(destinationDirectory);\n            if (!dir.Exists)\n            {\n                dir.Create();\n            }\n\n            string content = File.ReadAllText(sourceFilePath);\n\n            // Do the transformation for source code only\n            if (extension.StartsWith(\".cs\") || extension.StartsWith(\".vb\"))\n            {\n              destinationFilePath += \".pp\";\n              content = content.Replace(OriginalNamespaceToken, ReplacementNamespaceToken);\n            }\n\n            File.WriteAllText(destinationFilePath, content, Encoding.UTF8); // Always write the file using UTF8 encoding with BOM.\n          }\n          return true;\n        ]]>\n      </Code>\n    </Task>\n  </UsingTask>\n</Project>"
  },
  {
    "path": "src/WebApiHelpPage/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Microsoft.Web.Infrastructure\" version=\"1.0.0.0\" targetFramework=\"net45\" />\n  <package id=\"Newtonsoft.Json\" version=\"13.0.1\" targetFramework=\"net45\" />\n</packages>"
  },
  {
    "path": "src/WebHelpers.ruleset",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RuleSet Name=\"FxCop rules for Web Helpers\"  ToolsVersion=\"10.0\">\n    <Include Path=\"strict.ruleset\" Action=\"Default\" />\n    <Rules AnalyzerId=\"Microsoft.Analyzers.ManagedCodeAnalysis\" RuleNamespace=\"Microsoft.Rules.Managed\">\n        <Rule Id=\"CA1026\" Action=\"None\" />\n    </Rules>\n</RuleSet>"
  },
  {
    "path": "src/WebMatrix.Data/ConfigurationManagerWrapper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Configuration;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\n\nnamespace WebMatrix.Data\n{\n    internal class ConfigurationManagerWrapper : IConfigurationManager\n    {\n        private readonly string _dataDirectory = null;\n        private IDictionary<string, string> _appSettings;\n        private IDictionary<string, IDbFileHandler> _handlers;\n\n        public ConfigurationManagerWrapper(IDictionary<string, IDbFileHandler> handlers, string dataDirectory = null)\n        {\n            Debug.Assert(handlers != null, \"handlers should not be null\");\n            _dataDirectory = dataDirectory ?? Database.DataDirectory;\n            _handlers = handlers;\n        }\n\n        public IDictionary<string, string> AppSettings\n        {\n            get\n            {\n                if (_appSettings == null)\n                {\n                    _appSettings = (from string key in ConfigurationManager.AppSettings\n                                    select key).ToDictionary(key => key, key => ConfigurationManager.AppSettings[key]);\n                }\n                return _appSettings;\n            }\n        }\n\n        private static IConnectionConfiguration GetConnectionConfigurationFromConfig(string name)\n        {\n            ConnectionStringSettings setting = ConfigurationManager.ConnectionStrings[name];\n            if (setting != null)\n            {\n                return new ConnectionConfiguration(setting.ProviderName, setting.ConnectionString);\n            }\n            return null;\n        }\n\n        public IConnectionConfiguration GetConnection(string name)\n        {\n            return GetConnection(name, GetConnectionConfigurationFromConfig, File.Exists);\n        }\n\n        // For unit testing\n        internal IConnectionConfiguration GetConnection(string name, Func<string, IConnectionConfiguration> getConfigConnection, Func<string, bool> fileExists)\n        {\n            // First try config\n            IConnectionConfiguration configuraitonConfig = getConfigConnection(name);\n            if (configuraitonConfig != null)\n            {\n                return configuraitonConfig;\n            }\n\n            // Then try files under the |DataDirectory| with the supported extensions\n            // REVIEW: We sort because we want to process mdf before sdf (we only have 2 entries)\n            foreach (var handler in _handlers.OrderBy(h => h.Key))\n            {\n                string fileName = Path.Combine(_dataDirectory, name + handler.Key);\n                if (fileExists(fileName))\n                {\n                    return handler.Value.GetConnectionConfiguration(fileName);\n                }\n            }\n\n            return null;\n        }\n    }\n}\n"
  },
  {
    "path": "src/WebMatrix.Data/ConnectionConfiguration.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics;\n\nnamespace WebMatrix.Data\n{\n    internal class ConnectionConfiguration : IConnectionConfiguration\n    {\n        internal ConnectionConfiguration(string providerName, string connectionString)\n            : this(new DbProviderFactoryWrapper(providerName), connectionString)\n        {\n        }\n\n        internal ConnectionConfiguration(IDbProviderFactory providerFactory, string connectionString)\n        {\n            Debug.Assert(!String.IsNullOrEmpty(connectionString), \"connectionString should not be null\");\n\n            ProviderFactory = providerFactory;\n            ConnectionString = connectionString;\n        }\n\n        public IDbProviderFactory ProviderFactory { get; private set; }\n\n        public string ConnectionString { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/WebMatrix.Data/ConnectionEventArgs.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Data.Common;\n\nnamespace WebMatrix.Data\n{\n    public class ConnectionEventArgs : EventArgs\n    {\n        public ConnectionEventArgs(DbConnection connection)\n        {\n            Connection = connection;\n        }\n\n        public DbConnection Connection { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/WebMatrix.Data/Database.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Data;\nusing System.Data.Common;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing Microsoft.Internal.Web.Utils;\nusing WebMatrix.Data.Resources;\n\nnamespace WebMatrix.Data\n{\n    public class Database : IDisposable\n    {\n        internal const string SqlCeProviderName = \"System.Data.SqlServerCe.4.0\";\n        internal const string SqlServerProviderName = \"System.Data.SqlClient\";\n\n        private const string DefaultDataProviderAppSetting = \"systemData:defaultProvider\";\n        internal static string DataDirectory = (string)AppDomain.CurrentDomain.GetData(\"DataDirectory\") ?? Directory.GetCurrentDirectory();\n\n        private static readonly IDictionary<string, IDbFileHandler> _databaseFileHandlers = new Dictionary<string, IDbFileHandler>(StringComparer.OrdinalIgnoreCase)\n        {\n            { \".sdf\", new SqlCeDbFileHandler() },\n            { \".mdf\", new SqlServerDbFileHandler() }\n        };\n\n        private static readonly IConfigurationManager _configurationManager = new ConfigurationManagerWrapper(_databaseFileHandlers);\n        private Func<DbConnection> _connectionFactory;\n        private DbConnection _connection;\n\n        internal Database(Func<DbConnection> connectionFactory)\n        {\n            _connectionFactory = connectionFactory;\n        }\n\n        public static event EventHandler<ConnectionEventArgs> ConnectionOpened\n        {\n            add { _connectionOpened += value; }\n            remove { _connectionOpened -= value; }\n        }\n\n        private static event EventHandler<ConnectionEventArgs> _connectionOpened;\n\n        public DbConnection Connection\n        {\n            get\n            {\n                if (_connection == null)\n                {\n                    _connection = _connectionFactory();\n                }\n                return _connection;\n            }\n        }\n\n        public void Close()\n        {\n            Dispose();\n        }\n\n        public void Dispose()\n        {\n            Dispose(true);\n            GC.SuppressFinalize(this);\n        }\n\n        protected virtual void Dispose(bool disposing)\n        {\n            if (disposing)\n            {\n                if (_connection != null)\n                {\n                    _connection.Close();\n                    _connection = null;\n                }\n            }\n        }\n\n        public dynamic QuerySingle(string commandText, params object[] args)\n        {\n            if (String.IsNullOrEmpty(commandText))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"commandText\");\n            }\n\n            return QueryInternal(commandText, args).FirstOrDefault();\n        }\n\n        public IEnumerable<dynamic> Query(string commandText, params object[] parameters)\n        {\n            if (String.IsNullOrEmpty(commandText))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"commandText\");\n            }\n            // Return a readonly collection\n            return QueryInternal(commandText, parameters).ToList().AsReadOnly();\n        }\n\n        [SuppressMessage(\"Microsoft.Security\", \"CA2100:Review SQL queries for security vulnerabilities\", Justification = \"Users are responsible for ensuring the inputs to this method are SQL Injection sanitized\")]\n        private IEnumerable<dynamic> QueryInternal(string commandText, params object[] parameters)\n        {\n            EnsureConnectionOpen();\n\n            DbCommand command = Connection.CreateCommand();\n            command.CommandText = commandText;\n\n            AddParameters(command, parameters);\n            using (command)\n            {\n                IEnumerable<string> columnNames = null;\n                using (DbDataReader reader = command.ExecuteReader())\n                {\n                    foreach (DbDataRecord record in reader)\n                    {\n                        if (columnNames == null)\n                        {\n                            columnNames = GetColumnNames(record);\n                        }\n                        yield return new DynamicRecord(columnNames, record);\n                    }\n                }\n            }\n        }\n\n        private static IEnumerable<string> GetColumnNames(DbDataRecord record)\n        {\n            // Get all of the column names for this query\n            for (int i = 0; i < record.FieldCount; i++)\n            {\n                yield return record.GetName(i);\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Security\", \"CA2100:Review SQL queries for security vulnerabilities\", Justification = \"Users are responsible for ensuring the inputs to this method are SQL Injection sanitized\")]\n        public int Execute(string commandText, params object[] args)\n        {\n            if (String.IsNullOrEmpty(commandText))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"commandText\");\n            }\n\n            EnsureConnectionOpen();\n\n            DbCommand command = Connection.CreateCommand();\n            command.CommandText = commandText;\n\n            AddParameters(command, args);\n            using (command)\n            {\n                return command.ExecuteNonQuery();\n            }\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\", Justification = \"This makes a database request\")]\n        public dynamic GetLastInsertId()\n        {\n            // This method only support sql ce and sql server for now\n            return QueryValue(\"SELECT @@Identity\");\n        }\n\n        [SuppressMessage(\"Microsoft.Security\", \"CA2100:Review SQL queries for security vulnerabilities\", Justification = \"Users are responsible for ensuring the inputs to this method are SQL Injection sanitized\")]\n        public dynamic QueryValue(string commandText, params object[] args)\n        {\n            if (String.IsNullOrEmpty(commandText))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"commandText\");\n            }\n\n            EnsureConnectionOpen();\n\n            DbCommand command = Connection.CreateCommand();\n            command.CommandText = commandText;\n\n            AddParameters(command, args);\n            using (command)\n            {\n                return command.ExecuteScalar();\n            }\n        }\n\n        private void EnsureConnectionOpen()\n        {\n            // If the connection isn't open then open it\n            if (Connection.State != ConnectionState.Open)\n            {\n                Connection.Open();\n\n                // Raise the connection opened event\n                OnConnectionOpened();\n            }\n        }\n\n        private void OnConnectionOpened()\n        {\n            if (_connectionOpened != null)\n            {\n                _connectionOpened(this, new ConnectionEventArgs(Connection));\n            }\n        }\n\n        private static void AddParameters(DbCommand command, object[] args)\n        {\n            if (args == null)\n            {\n                return;\n            }\n\n            // Create numbered parameters\n            IEnumerable<DbParameter> parameters = args.Select((o, index) =>\n            {\n                var parameter = command.CreateParameter();\n                parameter.ParameterName = index.ToString(CultureInfo.InvariantCulture);\n                parameter.Value = o ?? DBNull.Value;\n                return parameter;\n            });\n\n            foreach (var p in parameters)\n            {\n                command.Parameters.Add(p);\n            }\n        }\n\n        public static Database OpenConnectionString(string connectionString)\n        {\n            return OpenConnectionString(connectionString, providerName: null);\n        }\n\n        public static Database OpenConnectionString(string connectionString, string providerName)\n        {\n            if (String.IsNullOrEmpty(connectionString))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"connectionString\");\n            }\n\n            return OpenConnectionStringInternal(providerName, connectionString);\n        }\n\n        public static Database Open(string name)\n        {\n            if (String.IsNullOrEmpty(name))\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"name\");\n            }\n            return OpenNamedConnection(name, _configurationManager);\n        }\n\n        internal static IConnectionConfiguration GetConnectionConfiguration(string fileName, IDictionary<string, IDbFileHandler> handlers)\n        {\n            string extension = Path.GetExtension(fileName);\n            IDbFileHandler handler;\n            if (handlers.TryGetValue(extension, out handler))\n            {\n                return handler.GetConnectionConfiguration(fileName);\n            }\n\n            throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,\n                                                              DataResources.UnableToDetermineDatabase, fileName));\n        }\n\n        private static Database OpenConnectionStringInternal(string providerName, string connectionString)\n        {\n            return OpenConnectionStringInternal(new DbProviderFactoryWrapper(providerName), connectionString);\n        }\n\n        private static Database OpenConnectionInternal(IConnectionConfiguration connectionConfig)\n        {\n            return OpenConnectionStringInternal(connectionConfig.ProviderFactory, connectionConfig.ConnectionString);\n        }\n\n        internal static Database OpenConnectionStringInternal(IDbProviderFactory providerFactory, string connectionString)\n        {\n            return new Database(() => providerFactory.CreateConnection(connectionString));\n        }\n\n        internal static Database OpenNamedConnection(string name, IConfigurationManager configurationManager)\n        {\n            // Opens a connection using the connection string setting with the specified name\n            IConnectionConfiguration configuration = configurationManager.GetConnection(name);\n            if (configuration != null)\n            {\n                // We've found one in the connection string setting in config so use it\n                return OpenConnectionInternal(configuration);\n            }\n\n            throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,\n                                                              DataResources.ConnectionStringNotFound, name));\n        }\n\n        internal static string GetDefaultProviderName()\n        {\n            string providerName;\n            // Get the default provider name from config if there is any\n            if (!_configurationManager.AppSettings.TryGetValue(DefaultDataProviderAppSetting, out providerName))\n            {\n                providerName = SqlCeProviderName;\n            }\n\n            return providerName;\n        }\n    }\n}\n"
  },
  {
    "path": "src/WebMatrix.Data/DbProviderFactoryWrapper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Data.Common;\n\nnamespace WebMatrix.Data\n{\n    internal class DbProviderFactoryWrapper : IDbProviderFactory\n    {\n        private string _providerName;\n        private DbProviderFactory _providerFactory;\n\n        public DbProviderFactoryWrapper(string providerName)\n        {\n            _providerName = providerName;\n        }\n\n        public DbConnection CreateConnection(string connectionString)\n        {\n            if (String.IsNullOrEmpty(_providerName))\n            {\n                // If the provider name is null or empty then use the default\n                _providerName = Database.GetDefaultProviderName();\n            }\n\n            if (_providerFactory == null)\n            {\n                _providerFactory = DbProviderFactories.GetFactory(_providerName);\n            }\n\n            DbConnection connection = _providerFactory.CreateConnection();\n            connection.ConnectionString = connectionString;\n            return connection;\n        }\n    }\n}\n"
  },
  {
    "path": "src/WebMatrix.Data/DynamicRecord.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Diagnostics;\nusing System.Dynamic;\nusing System.Globalization;\nusing System.Linq;\nusing WebMatrix.Data.Resources;\n\nnamespace WebMatrix.Data\n{\n    public sealed class DynamicRecord : DynamicObject, ICustomTypeDescriptor\n    {\n        internal DynamicRecord(IEnumerable<string> columnNames, IDataRecord record)\n        {\n            Debug.Assert(record != null, \"record should not be null\");\n            Debug.Assert(columnNames != null, \"columnNames should not be null\");\n\n            Columns = columnNames.ToList();\n            Record = record;\n        }\n\n        public IList<string> Columns { get; private set; }\n\n        private IDataRecord Record { get; set; }\n\n        public object this[string name]\n        {\n            get\n            {\n                VerifyColumn(name);\n                return GetValue(Record[name]);\n            }\n        }\n\n        public object this[int index]\n        {\n            get { return GetValue(Record[index]); }\n        }\n\n        public override bool TryGetMember(GetMemberBinder binder, out object result)\n        {\n            result = this[binder.Name];\n            return true;\n        }\n\n        private static object GetValue(object value)\n        {\n            return DBNull.Value == value ? null : value;\n        }\n\n        public override IEnumerable<string> GetDynamicMemberNames()\n        {\n            return Columns;\n        }\n\n        private void VerifyColumn(string name)\n        {\n            // REVIEW: Perf\n            if (!Columns.Contains(name, StringComparer.OrdinalIgnoreCase))\n            {\n                throw new InvalidOperationException(\n                    String.Format(CultureInfo.CurrentCulture,\n                                  DataResources.InvalidColumnName, name));\n            }\n        }\n\n        AttributeCollection ICustomTypeDescriptor.GetAttributes()\n        {\n            return AttributeCollection.Empty;\n        }\n\n        string ICustomTypeDescriptor.GetClassName()\n        {\n            return null;\n        }\n\n        string ICustomTypeDescriptor.GetComponentName()\n        {\n            return null;\n        }\n\n        TypeConverter ICustomTypeDescriptor.GetConverter()\n        {\n            return null;\n        }\n\n        EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()\n        {\n            return null;\n        }\n\n        PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()\n        {\n            return null;\n        }\n\n        object ICustomTypeDescriptor.GetEditor(Type editorBaseType)\n        {\n            return null;\n        }\n\n        EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)\n        {\n            return EventDescriptorCollection.Empty;\n        }\n\n        EventDescriptorCollection ICustomTypeDescriptor.GetEvents()\n        {\n            return EventDescriptorCollection.Empty;\n        }\n\n        PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)\n        {\n            return ((ICustomTypeDescriptor)this).GetProperties();\n        }\n\n        PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()\n        {\n            // Get the name and type for each column name\n            var properties = from columnName in Columns\n                             let columnIndex = Record.GetOrdinal(columnName)\n                             let type = Record.GetFieldType(columnIndex)\n                             select new DynamicPropertyDescriptor(columnName, type);\n\n            return new PropertyDescriptorCollection(properties.ToArray(), readOnly: true);\n        }\n\n        object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)\n        {\n            return this;\n        }\n\n        private class DynamicPropertyDescriptor : PropertyDescriptor\n        {\n            private static readonly Attribute[] _empty = new Attribute[0];\n            private readonly Type _type;\n\n            public DynamicPropertyDescriptor(string name, Type type)\n                : base(name, _empty)\n            {\n                _type = type;\n            }\n\n            public override Type ComponentType\n            {\n                get { return typeof(DynamicRecord); }\n            }\n\n            public override bool IsReadOnly\n            {\n                get { return true; }\n            }\n\n            public override Type PropertyType\n            {\n                get { return _type; }\n            }\n\n            public override bool CanResetValue(object component)\n            {\n                return false;\n            }\n\n            public override object GetValue(object component)\n            {\n                DynamicRecord record = component as DynamicRecord;\n                // REVIEW: Should we throw if the wrong object was passed in?\n                if (record != null)\n                {\n                    return record[Name];\n                }\n                return null;\n            }\n\n            public override void ResetValue(object component)\n            {\n                throw new InvalidOperationException(\n                    String.Format(CultureInfo.CurrentCulture,\n                                  DataResources.RecordIsReadOnly, Name));\n            }\n\n            public override void SetValue(object component, object value)\n            {\n                throw new InvalidOperationException(\n                    String.Format(CultureInfo.CurrentCulture,\n                                  DataResources.RecordIsReadOnly, Name));\n            }\n\n            public override bool ShouldSerializeValue(object component)\n            {\n                return false;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/WebMatrix.Data/GlobalSuppressions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n// This file is used by Code Analysis to maintain SuppressMessage \n// attributes that are applied to this project.\n// Project-level suppressions either have no target or are given \n// a specific target and scoped to a namespace, type, member, etc.\n//\n// To add a suppression to this file, right-click the message in the \n// Error List, point to \"Suppress Message(s)\", and click \n// \"In Project Suppression File\".\n// You do not need to add suppressions to this file manually.\n\nusing System.Diagnostics.CodeAnalysis;\n\n[assembly: SuppressMessage(\"Microsoft.Design\", \"CA1020:AvoidNamespacesWithFewTypes\", Scope = \"namespace\", Target = \"WebMatrix.Data\", Justification = \"WebMatrix.Data is a logical grouping of data-related helpers, and thus it belongs in its own namespace\")]\n"
  },
  {
    "path": "src/WebMatrix.Data/IConfigurationManager.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace WebMatrix.Data\n{\n    internal interface IConfigurationManager\n    {\n        IDictionary<string, string> AppSettings { get; }\n        IConnectionConfiguration GetConnection(string name);\n    }\n}\n"
  },
  {
    "path": "src/WebMatrix.Data/IConnectionConfiguration.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace WebMatrix.Data\n{\n    internal interface IConnectionConfiguration\n    {\n        string ConnectionString { get; }\n        IDbProviderFactory ProviderFactory { get; }\n    }\n}\n"
  },
  {
    "path": "src/WebMatrix.Data/IDbFileHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace WebMatrix.Data\n{\n    internal interface IDbFileHandler\n    {\n        IConnectionConfiguration GetConnectionConfiguration(string fileName);\n    }\n}\n"
  },
  {
    "path": "src/WebMatrix.Data/IDbProviderFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Data.Common;\n\nnamespace WebMatrix.Data\n{\n    internal interface IDbProviderFactory\n    {\n        DbConnection CreateConnection(string connectionString);\n    }\n}\n"
  },
  {
    "path": "src/WebMatrix.Data/Properties/AssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\n\n// General Information about an assembly is controlled through the following \n// set of attributes. Change these attribute values to modify the information\n// associated with an assembly.\n\n[assembly: AssemblyTitle(\"WebMatrix.Data\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: InternalsVisibleTo(\"WebMatrix.Data.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n[assembly: InternalsVisibleTo(\"WebMatrix.WebData.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n"
  },
  {
    "path": "src/WebMatrix.Data/Resources/DataResources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.1\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace WebMatrix.Data.Resources {\n    using System;\n    \n    \n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class DataResources {\n        \n        private static global::System.Resources.ResourceManager resourceMan;\n        \n        private static global::System.Globalization.CultureInfo resourceCulture;\n        \n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal DataResources() {\n        }\n        \n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"WebMatrix.Data.Resources.DataResources\", typeof(DataResources).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n        \n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Connection string &quot;{0}&quot; was not found..\n        /// </summary>\n        internal static string ConnectionStringNotFound {\n            get {\n                return ResourceManager.GetString(\"ConnectionStringNotFound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Invalid column name &quot;{0}&quot;..\n        /// </summary>\n        internal static string InvalidColumnName {\n            get {\n                return ResourceManager.GetString(\"InvalidColumnName\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Unable to modify the value of column &quot;{0}&quot; because the record is read only..\n        /// </summary>\n        internal static string RecordIsReadOnly {\n            get {\n                return ResourceManager.GetString(\"RecordIsReadOnly\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Unable to determine the provider for the database file &quot;{0}&quot;..\n        /// </summary>\n        internal static string UnableToDetermineDatabase {\n            get {\n                return ResourceManager.GetString(\"UnableToDetermineDatabase\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/WebMatrix.Data/Resources/DataResources.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"ConnectionStringNotFound\" xml:space=\"preserve\">\n    <value>Connection string \"{0}\" was not found.</value>\n  </data>\n  <data name=\"InvalidColumnName\" xml:space=\"preserve\">\n    <value>Invalid column name \"{0}\".</value>\n  </data>\n  <data name=\"RecordIsReadOnly\" xml:space=\"preserve\">\n    <value>Unable to modify the value of column \"{0}\" because the record is read only.</value>\n  </data>\n  <data name=\"UnableToDetermineDatabase\" xml:space=\"preserve\">\n    <value>Unable to determine the provider for the database file \"{0}\".</value>\n  </data>\n</root>"
  },
  {
    "path": "src/WebMatrix.Data/SqlCeDbFileHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.IO;\n\nnamespace WebMatrix.Data\n{\n    internal class SqlCeDbFileHandler : IDbFileHandler\n    {\n        private const string SqlCeConnectionStringFormat = @\"Data Source={0};File Access Retry Timeout=10\";\n\n        public IConnectionConfiguration GetConnectionConfiguration(string fileName)\n        {\n            // Get the default provider name\n            string providerName = Database.GetDefaultProviderName();\n            Debug.Assert(!String.IsNullOrEmpty(providerName), \"Provider name should not be null or empty\");\n\n            string connectionString = GetConnectionString(fileName);\n            return new ConnectionConfiguration(providerName, connectionString);\n        }\n\n        public static string GetConnectionString(string fileName)\n        {\n            if (Path.IsPathRooted(fileName))\n            {\n                return String.Format(CultureInfo.InvariantCulture, SqlCeConnectionStringFormat, fileName);\n            }\n\n            // Use |DataDirectory| if the path isn't rooted\n            string dataSource = @\"|DataDirectory|\\\" + Path.GetFileName(fileName);\n            return String.Format(CultureInfo.InvariantCulture, SqlCeConnectionStringFormat, dataSource);\n        }\n    }\n}\n"
  },
  {
    "path": "src/WebMatrix.Data/SqlServerDbFileHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Globalization;\nusing System.IO;\n\nnamespace WebMatrix.Data\n{\n    internal class SqlServerDbFileHandler : IDbFileHandler\n    {\n        private const string SqlServerConnectionStringFormat = @\"Data Source=.\\SQLEXPRESS;AttachDbFilename={0};Initial Catalog={1};Integrated Security=True;User Instance=True;MultipleActiveResultSets=True\";\n        private const string SqlServerProviderName = \"System.Data.SqlClient\";\n\n        public IConnectionConfiguration GetConnectionConfiguration(string fileName)\n        {\n            return new ConnectionConfiguration(SqlServerProviderName, GetConnectionString(fileName, Database.DataDirectory));\n        }\n\n        internal static string GetConnectionString(string fileName, string dataDirectory)\n        {\n            if (Path.IsPathRooted(fileName))\n            {\n                // Attach the db as the file name if it is rooted\n                return String.Format(CultureInfo.InvariantCulture, SqlServerConnectionStringFormat, fileName, fileName);\n            }\n\n            // Use |DataDirectory| if the path isn't rooted\n            string dataSource = @\"|DataDirectory|\\\" + Path.GetFileName(fileName);\n            // Set the full path for the initial catalog so we attach as that\n            string initialCatalog = Path.Combine(dataDirectory, Path.GetFileName(fileName));\n            return String.Format(CultureInfo.InvariantCulture, SqlServerConnectionStringFormat, dataSource, initialCatalog);\n        }\n    }\n}\n"
  },
  {
    "path": "src/WebMatrix.Data/WebMatrix.Data.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{4D39BAAF-8A96-473E-AB79-C8A341885137}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <RootNamespace>WebMatrix.Data</RootNamespace>\n    <AssemblyName>WebMatrix.Data</AssemblyName>\n    <DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>\n    <RunCodeAnalysis>$(CodeAnalysis)</RunCodeAnalysis>\n    <CodeAnalysisRuleSet>..\\Strict.ruleset</CodeAnalysisRuleSet>\n    <DefineConstants>$(DefineConstants);ASPNETWEBPAGES</DefineConstants>\n    <NoWarn>1591</NoWarn>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.configuration\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"System.Data\" />\n    <Reference Include=\"System.Xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\CommonAssemblyInfo.cs\">\n      <Link>Properties\\CommonAssemblyInfo.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\CommonResources.Designer.cs\">\n      <Link>Common\\CommonResources.Designer.cs</Link>\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>CommonResources.resx</DependentUpon>\n    </Compile>\n    <Compile Include=\"..\\GlobalSuppressions.cs\">\n      <Link>Common\\GlobalSuppressions.cs</Link>\n    </Compile>\n    <Compile Include=\"ConfigurationManagerWrapper.cs\" />\n    <Compile Include=\"ConnectionConfiguration.cs\" />\n    <Compile Include=\"ConnectionEventArgs.cs\" />\n    <Compile Include=\"Database.cs\" />\n    <Compile Include=\"DbProviderFactoryWrapper.cs\" />\n    <Compile Include=\"DynamicRecord.cs\" />\n    <Compile Include=\"GlobalSuppressions.cs\" />\n    <Compile Include=\"IConfigurationManager.cs\" />\n    <Compile Include=\"IConnectionConfiguration.cs\" />\n    <Compile Include=\"IDbFileHandler.cs\" />\n    <Compile Include=\"IDbProviderFactory.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"Resources\\DataResources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>DataResources.resx</DependentUpon>\n    </Compile>\n    <Compile Include=\"SqlCeDbFileHandler.cs\" />\n    <Compile Include=\"SqlServerDbFileHandler.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"..\\CommonResources.resx\">\n      <Link>Common\\CommonResources.resx</Link>\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>CommonResources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n    <EmbeddedResource Include=\"Resources\\DataResources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>DataResources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n  </ItemGroup>\n  <ItemGroup>\n    <CodeAnalysisDictionary Include=\"..\\CodeAnalysisDictionary.xml\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n</Project>"
  },
  {
    "path": "src/WebMatrix.WebData/ConfigUtil.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Configuration;\n\nnamespace WebMatrix.WebData\n{\n    internal static class ConfigUtil\n    {\n        private static bool _simpleMembershipEnabled = IsSimpleMembershipEnabled();\n\n        public static bool SimpleMembershipEnabled\n        {\n            get { return _simpleMembershipEnabled; }\n        }\n\n        private static bool IsSimpleMembershipEnabled()\n        {\n            string settingValue = ConfigurationManager.AppSettings[WebSecurity.EnableSimpleMembershipKey];\n            bool enabled;\n            if (!String.IsNullOrEmpty(settingValue) && Boolean.TryParse(settingValue, out enabled))\n            {\n                return enabled;\n            }\n            // Simple Membership is enabled by default, but attempts to delegate to the current provider if not initialized.\n            return true;\n        }\n\n        internal static bool ShouldPreserveLoginUrl()\n        {\n            string settingValue = ConfigurationManager.AppSettings[FormsAuthenticationSettings.PreserveLoginUrlKey];\n            bool preserveLoginUrl;\n            if (!String.IsNullOrEmpty(settingValue) && Boolean.TryParse(settingValue, out preserveLoginUrl))\n            {\n                return preserveLoginUrl;\n            }\n\n            // For backwards compatible with WebPages 1.0, we override the loginUrl value if \n            // the PreserveLoginUrl key is not present.\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "src/WebMatrix.WebData/DatabaseConnectionInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing WebMatrix.Data;\n\nnamespace WebMatrix.WebData\n{\n    internal class DatabaseConnectionInfo\n    {\n        private string _connectionStringName;\n        private string _connectionString;\n\n        private enum ConnectionType\n        {\n            ConnectionStringName = 0,\n            ConnectionString = 1\n        }\n\n        public string ConnectionString\n        {\n            get { return _connectionString; }\n            set\n            {\n                _connectionString = value;\n                Type = ConnectionType.ConnectionString;\n            }\n        }\n\n        public string ConnectionStringName\n        {\n            get { return _connectionStringName; }\n            set\n            {\n                _connectionStringName = value;\n                Type = ConnectionType.ConnectionStringName;\n            }\n        }\n\n        public string ProviderName { get; set; }\n\n        private ConnectionType Type { get; set; }\n\n        public Database Connect()\n        {\n            switch (Type)\n            {\n                case ConnectionType.ConnectionString:\n                    return Database.OpenConnectionString(ConnectionString, ProviderName);\n                case ConnectionType.ConnectionStringName:\n                    return Database.Open(ConnectionStringName);\n                default:\n                    return null;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/WebMatrix.WebData/DatabaseWrapper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing WebMatrix.Data;\n\nnamespace WebMatrix.WebData\n{\n    internal class DatabaseWrapper : IDatabase\n    {\n        private readonly Database _database;\n\n        public DatabaseWrapper(Database database)\n        {\n            _database = database;\n        }\n\n        public dynamic QuerySingle(string commandText, params object[] parameters)\n        {\n            return _database.QuerySingle(commandText, parameters);\n        }\n\n        public IEnumerable<dynamic> Query(string commandText, params object[] parameters)\n        {\n            return _database.Query(commandText, parameters);\n        }\n\n        public dynamic QueryValue(string commandText, params object[] parameters)\n        {\n            return _database.QueryValue(commandText, parameters);\n        }\n\n        public int Execute(string commandText, params object[] parameters)\n        {\n            return _database.Execute(commandText, parameters);\n        }\n\n        public void Dispose()\n        {\n            _database.Dispose();\n        }\n    }\n}\n"
  },
  {
    "path": "src/WebMatrix.WebData/ExtendedMembershipProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Web.Security;\n\nnamespace WebMatrix.WebData\n{\n    public abstract class ExtendedMembershipProvider : MembershipProvider\n    {\n        private const int OneDayInMinutes = 24 * 60;\n\n        /// <summary>\n        /// Deletes the OAuth and OpenID account with the specified provider name and provider user id.\n        /// </summary>\n        /// <param name=\"provider\">The provider.</param>\n        /// <param name=\"providerUserId\">The provider user id.</param>\n        public virtual void DeleteOAuthAccount(string provider, string providerUserId)\n        {\n            throw new NotImplementedException();\n        }\n\n        /// <summary>\n        /// Creates a new OAuth account with the specified data or update an existing one if it already exists.\n        /// </summary>\n        /// <param name=\"provider\">The provider.</param>\n        /// <param name=\"providerUserId\">The provider userid.</param>\n        /// <param name=\"userName\">The username.</param>\n        public virtual void CreateOrUpdateOAuthAccount(string provider, string providerUserId, string userName)\n        {\n            throw new NotImplementedException();\n        }\n\n        /// <summary>\n        /// Gets the id of the user with the specified provider name and provider user id.\n        /// </summary>\n        /// <param name=\"provider\">The provider.</param>\n        /// <param name=\"providerUserId\">The provider user id.</param>\n        /// <returns></returns>\n        public virtual int GetUserIdFromOAuth(string provider, string providerUserId)\n        {\n            throw new NotImplementedException();\n        }\n\n        /// <summary>\n        /// Gets the username of a user with the given id\n        /// </summary>\n        /// <param name=\"userId\">The user id.</param>\n        /// <returns></returns>\n        public virtual string GetUserNameFromId(int userId)\n        {\n            throw new NotImplementedException();\n        }\n\n        /// <summary>\n        /// Determines whether there exists a local account (as opposed to OAuth account) with the specified userId.\n        /// </summary>\n        /// <param name=\"userId\">The user id to check for local account.</param>\n        /// <returns>\n        ///   <c>true</c> if there is a local account with the specified user id]; otherwise, <c>false</c>.\n        /// </returns>\n        public virtual bool HasLocalAccount(int userId)\n        {\n            throw new NotImplementedException();\n        }\n\n        /// <summary>\n        /// Gets the OAuth token secret from the specified OAuth token.\n        /// </summary>\n        /// <param name=\"token\">The token from which to retrieve secret.</param>\n        /// <returns>The token secret of the specified token</returns>\n        public virtual string GetOAuthTokenSecret(string token)\n        {\n            throw new NotImplementedException();\n        }\n\n        /// <summary>\n        /// Stores the specified token and secret into database.\n        /// </summary>\n        /// <param name=\"requestToken\">The token.</param>\n        /// <param name=\"requestTokenSecret\">The secret.</param>\n        public virtual void StoreOAuthRequestToken(string requestToken, string requestTokenSecret)\n        {\n            throw new NotImplementedException();\n        }\n\n        /// <summary>\n        /// Replaces the request token with access token and secret in the database.\n        /// </summary>\n        /// <param name=\"requestToken\">The request token.</param>\n        /// <param name=\"accessToken\">The access token.</param>\n        /// <param name=\"accessTokenSecret\">The access token secret.</param>\n        public virtual void ReplaceOAuthRequestTokenWithAccessToken(string requestToken, string accessToken, string accessTokenSecret)\n        {\n            throw new NotImplementedException();\n        }\n\n        /// <summary>\n        /// Deletes the OAuth token from the backing store from the database.\n        /// </summary>\n        /// <param name=\"token\">The token to be deleted.</param>\n        public virtual void DeleteOAuthToken(string token)\n        {\n            throw new NotImplementedException();\n        }\n\n        /// <summary>\n        /// Gets all OAuth accounts associated with the specified username\n        /// </summary>\n        /// <param name=\"userName\">Name of the user.</param>\n        /// <returns></returns>\n        public abstract ICollection<OAuthAccountData> GetAccountsForUser(string userName);\n\n        public virtual string CreateUserAndAccount(string userName, string password)\n        {\n            return CreateUserAndAccount(userName, password, requireConfirmation: false, values: null);\n        }\n\n        public virtual string CreateUserAndAccount(string userName, string password, bool requireConfirmation)\n        {\n            return CreateUserAndAccount(userName, password, requireConfirmation, values: null);\n        }\n\n        public virtual string CreateUserAndAccount(string userName, string password, IDictionary<string, object> values)\n        {\n            return CreateUserAndAccount(userName, password, requireConfirmation: false, values: values);\n        }\n\n        public abstract string CreateUserAndAccount(string userName, string password, bool requireConfirmation, IDictionary<string, object> values);\n\n        public virtual string CreateAccount(string userName, string password)\n        {\n            return CreateAccount(userName, password, requireConfirmationToken: false);\n        }\n\n        public abstract string CreateAccount(string userName, string password, bool requireConfirmationToken);\n        public abstract bool ConfirmAccount(string userName, string accountConfirmationToken);\n        public abstract bool ConfirmAccount(string accountConfirmationToken);\n        public abstract bool DeleteAccount(string userName);\n\n        public virtual string GeneratePasswordResetToken(string userName)\n        {\n            return GeneratePasswordResetToken(userName, tokenExpirationInMinutesFromNow: OneDayInMinutes);\n        }\n\n        public abstract string GeneratePasswordResetToken(string userName, int tokenExpirationInMinutesFromNow);\n        public abstract int GetUserIdFromPasswordResetToken(string token);\n        public abstract bool IsConfirmed(string userName);\n        public abstract bool ResetPasswordWithToken(string token, string newPassword);\n        public abstract int GetPasswordFailuresSinceLastSuccess(string userName);\n        public abstract DateTime GetCreateDate(string userName);\n        public abstract DateTime GetPasswordChangedDate(string userName);\n        public abstract DateTime GetLastPasswordFailureDate(string userName);\n\n        internal virtual void VerifyInitialized()\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "src/WebMatrix.WebData/FormsAuthenticationSettings.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace WebMatrix.WebData\n{\n    /// <summary>\n    /// Defines key names for use in a web.config &lt;appSettings&gt; section to override default settings.\n    /// </summary>\n    public static class FormsAuthenticationSettings\n    {\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1726:UsePreferredTerms\", MessageId = \"Login\", Justification = \"The term Login is used more frequently in ASP.Net\")]\n        public static readonly string LoginUrlKey = \"loginUrl\";\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1726:UsePreferredTerms\", MessageId = \"Login\", Justification = \"The term Login is used more frequently in ASP.Net\")]\n        public static readonly string DefaultLoginUrl = \"~/Account/Login\";\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1726:UsePreferredTerms\", MessageId = \"Login\", Justification = \"The term Login is used more frequently in ASP.Net\")]\n        public static readonly string PreserveLoginUrlKey = \"PreserveLoginUrl\";\n    }\n}\n"
  },
  {
    "path": "src/WebMatrix.WebData/GlobalSuppressions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n// This file is used by Code Analysis to maintain SuppressMessage \n// attributes that are applied to this project.\n// Project-level suppressions either have no target or are given \n// a specific target and scoped to a namespace, type, member, etc.\n//\n// To add a suppression to this file, right-click the message in the \n// Error List, point to \"Suppress Message(s)\", and click \n// \"In Project Suppression File\".\n// You do not need to add suppressions to this file manually.\n\nusing System.Diagnostics.CodeAnalysis;\n\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1702:CompoundWordsShouldBeCasedCorrectly\", MessageId = \"Username\", Scope = \"member\", Target = \"WebMatrix.WebData.ExtendedMembershipProvider.#GetUsernameFromId(System.Int32)\", Justification = \"Username is one word.\")]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1702:CompoundWordsShouldBeCasedCorrectly\", MessageId = \"username\", Scope = \"member\", Target = \"WebMatrix.WebData.ExtendedMembershipProvider.#GetAccountsForUser(System.String)\", Justification = \"Username is one word.\")]\n[assembly: SuppressMessage(\"Microsoft.Naming\", \"CA1702:CompoundWordsShouldBeCasedCorrectly\", MessageId = \"username\", Scope = \"member\", Target = \"WebMatrix.WebData.ExtendedMembershipProvider.#CreateOrUpdateOAuthAccount(System.String,System.String,System.String)\", Justification = \"Username is one word.\")]\n"
  },
  {
    "path": "src/WebMatrix.WebData/IDatabase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\n\nnamespace WebMatrix.WebData\n{\n    internal interface IDatabase : IDisposable\n    {\n        dynamic QuerySingle(string commandText, params object[] args);\n\n        IEnumerable<dynamic> Query(string commandText, params object[] parameters);\n\n        dynamic QueryValue(string commandText, params object[] parameters);\n\n        int Execute(string commandText, params object[] args);\n    }\n}\n"
  },
  {
    "path": "src/WebMatrix.WebData/OAuthAccountData.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Globalization;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace WebMatrix.WebData\n{\n    /// <summary>\n    /// Represents an OpenAuth and OpenID account.\n    /// </summary>\n    public class OAuthAccountData\n    {\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"OAuthAccountData\"/> class.\n        /// </summary>\n        /// <param name=\"provider\">The provider.</param>\n        /// <param name=\"providerUserId\">The provider user id.</param>\n        public OAuthAccountData(string provider, string providerUserId)\n        {\n            if (String.IsNullOrEmpty(provider))\n            {\n                throw new ArgumentException(\n                    String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"provider\"),\n                    \"provider\");\n            }\n\n            if (String.IsNullOrEmpty(providerUserId))\n            {\n                throw new ArgumentException(\n                    String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"providerUserId\"),\n                    \"providerUserId\");\n            }\n\n            Provider = provider;\n            ProviderUserId = providerUserId;\n        }\n\n        /// <summary>\n        /// Gets the provider name.\n        /// </summary>\n        public string Provider { get; private set; }\n\n        /// <summary>\n        /// Gets the provider user id.\n        /// </summary>\n        public string ProviderUserId { get; private set; }\n    }\n}\n"
  },
  {
    "path": "src/WebMatrix.WebData/PreApplicationStartCode.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing System.ComponentModel;\nusing System.Configuration;\nusing System.Web;\nusing System.Web.Security;\nusing System.Web.WebPages;\nusing System.Web.WebPages.Razor;\nusing WebMatrix.Data;\n\nnamespace WebMatrix.WebData\n{\n    [EditorBrowsable(EditorBrowsableState.Never)]\n    public static class PreApplicationStartCode\n    {\n        // NOTE: Do not add public fields, methods, or other members to this class.\n        // This class does not show up in Intellisense so members on it will not be\n        // discoverable by users. Place new members on more appropriate classes that\n        // relate to the public API (for example, a LoginUrl property should go on a\n        // membership-related class).\n\n        private const string LoginUrlKey = \"loginUrl\";\n\n        private static bool _startWasCalled;\n\n        public static void Start()\n        {\n            // Even though ASP.NET will only call each PreAppStart once, we sometimes internally call one PreAppStart from \n            // another PreAppStart to ensure that things get initialized in the right order. ASP.NET does not guarantee the \n            // order so we have to guard against multiple calls.\n            // All Start calls are made on same thread, so no lock needed here.\n\n            if (_startWasCalled)\n            {\n                return;\n            }\n            _startWasCalled = true;\n\n            // Summary of Simple Membership startup behavior:\n            //  1. If the appSetting enabledSimpleMembership is present and equal to \"false\", NEITHER SimpleMembership NOR AutoFormsAuth are activated\n            //  2. If the appSetting is true, a non-boolean string or not present, BOTH may be activated\n            //    a. SimpleMembership ONLY replaces the AspNetSqlMemberhipProvider, but it does replace it even if it isn't the default.  This\n            //       means that anything accessing this provider by name will get Simple Membership, but if this provider is no longer the default\n            //       then SimpleMembership does not affect the default\n            //    b. SimpleMembership delegates to the previous default provider UNLESS WebSecurity.InitializeDatabaseConnection is called.\n\n            // Initialize membership provider\n            WebSecurity.PreAppStartInit();\n\n            // Initialize Forms Authentication default configuration\n            SetUpFormsAuthentication();\n\n            // Wire up WebMatrix.Data's Database object to the ASP.NET Web Pages resource tracker\n            Database.ConnectionOpened += OnConnectionOpened;\n\n            // Auto import the WebMatrix.Data and WebMatrix.WebData namespaces to all apps that are executing.\n            WebPageRazorHost.AddGlobalImport(\"WebMatrix.Data\");\n            WebPageRazorHost.AddGlobalImport(\"WebMatrix.WebData\");\n        }\n\n        private static void OnConnectionOpened(object sender, ConnectionEventArgs e)\n        {\n            // Register all open connections for disposing at the end of the request\n            HttpContext httpContext = HttpContext.Current;\n            if (httpContext != null)\n            {\n                HttpContextWrapper httpContextWrapper = new HttpContextWrapper(httpContext);\n                httpContextWrapper.RegisterForDispose(e.Connection);\n            }\n        }\n\n        private static void SetUpFormsAuthentication()\n        {\n            if (ConfigUtil.SimpleMembershipEnabled)\n            {\n                NameValueCollection configurationData = new NameValueCollection();\n\n                string appSettingsLoginUrl = ConfigurationManager.AppSettings[FormsAuthenticationSettings.LoginUrlKey];\n                if (appSettingsLoginUrl != null)\n                {\n                    // Allow use of <add key=\"loginUrl\" value=\"~/MyPath/LogOn\" /> as a shortcut to specify\n                    // a custom log in url\n                    configurationData[LoginUrlKey] = appSettingsLoginUrl;\n                }\n                else if (!ConfigUtil.ShouldPreserveLoginUrl())\n                {\n                    // Otherwise, use the default login url, but only if PreserveLoginUrl != true\n                    // If PreserveLoginUrl == true, we do not want to override FormsAuthentication's default\n                    // behavior because trying to evaluate FormsAuthentication.LoginUrl at this point in a\n                    // PreAppStart method would cause app-relative URLs to be evaluated incorrectly.\n                    configurationData[LoginUrlKey] = FormsAuthenticationSettings.DefaultLoginUrl;\n                }\n\n                FormsAuthentication.EnableFormsAuthentication(configurationData);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/WebMatrix.WebData/Properties/AssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\nusing System.Web;\nusing WebMatrix.WebData;\n\n// General Information about an assembly is controlled through the following \n// set of attributes. Change these attribute values to modify the information\n// associated with an assembly.\n\n[assembly: AssemblyTitle(\"WebMatrix.WebData\")]\n[assembly: AssemblyDescription(\"\")]\n[assembly: InternalsVisibleTo(\"WebPages.Functional.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n[assembly: InternalsVisibleTo(\"WebMatrix.WebData.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9\")]\n[assembly: PreApplicationStartMethod(typeof(PreApplicationStartCode), \"Start\")]\n"
  },
  {
    "path": "src/WebMatrix.WebData/Resources/WebDataResources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.488\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace WebMatrix.WebData.Resources {\n    using System;\n    \n    \n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class WebDataResources {\n        \n        private static global::System.Resources.ResourceManager resourceMan;\n        \n        private static global::System.Globalization.CultureInfo resourceCulture;\n        \n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal WebDataResources() {\n        }\n        \n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"WebMatrix.WebData.Resources.WebDataResources\", typeof(WebDataResources).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n        \n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Database operation failed..\n        /// </summary>\n        internal static string Security_DbFailure {\n            get {\n                return ResourceManager.GetString(\"Security_DbFailure\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to No user table found that has the name &quot;{0}&quot;..\n        /// </summary>\n        internal static string Security_FailedToFindUserTable {\n            get {\n                return ResourceManager.GetString(\"Security_FailedToFindUserTable\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The &quot;WebSecurity.InitializeDatabaseConnection&quot; method can be called only once..\n        /// </summary>\n        internal static string Security_InitializeAlreadyCalled {\n            get {\n                return ResourceManager.GetString(\"Security_InitializeAlreadyCalled\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to You must call the &quot;WebSecurity.InitializeDatabaseConnection&quot; method before you call any other method of the &quot;WebSecurity&quot; class. This call should be placed in an _AppStart.cshtml file in the root of your site..\n        /// </summary>\n        internal static string Security_InitializeMustBeCalledFirst {\n            get {\n                return ResourceManager.GetString(\"Security_InitializeMustBeCalledFirst\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to No account exists for &quot;{0}&quot;..\n        /// </summary>\n        internal static string Security_NoAccountFound {\n            get {\n                return ResourceManager.GetString(\"Security_NoAccountFound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to To call this method, the &quot;Membership.Provider&quot; property must be an instance of &quot;ExtendedMembershipProvider&quot;..\n        /// </summary>\n        internal static string Security_NoExtendedMembershipProvider {\n            get {\n                return ResourceManager.GetString(\"Security_NoExtendedMembershipProvider\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to No user found was found that has the name &quot;{0}&quot;..\n        /// </summary>\n        internal static string Security_NoUserFound {\n            get {\n                return ResourceManager.GetString(\"Security_NoUserFound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Failed to store OAuth token to database..\n        /// </summary>\n        internal static string SimpleMembership_FailToStoreOAuthToken {\n            get {\n                return ResourceManager.GetString(\"SimpleMembership_FailToStoreOAuthToken\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The membership password is too long. (Maximum length is 128 characters)..\n        /// </summary>\n        internal static string SimpleMembership_PasswordTooLong {\n            get {\n                return ResourceManager.GetString(\"SimpleMembership_PasswordTooLong\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Provider unrecognized attribute: &quot;{0}&quot;..\n        /// </summary>\n        internal static string SimpleMembership_ProviderUnrecognizedAttribute {\n            get {\n                return ResourceManager.GetString(\"SimpleMembership_ProviderUnrecognizedAttribute\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to The role &quot;{0}&quot; cannot be deleted because there are still users in the role..\n        /// </summary>\n        internal static string SimpleRoleProvder_RolePopulated {\n            get {\n                return ResourceManager.GetString(\"SimpleRoleProvder_RolePopulated\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to User &quot;{0}&quot; is already in role &quot;{1}&quot;..\n        /// </summary>\n        internal static string SimpleRoleProvder_UserAlreadyInRole {\n            get {\n                return ResourceManager.GetString(\"SimpleRoleProvder_UserAlreadyInRole\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to User &quot;{0}&quot; is not in role &quot;{1}&quot;..\n        /// </summary>\n        internal static string SimpleRoleProvder_UserNotInRole {\n            get {\n                return ResourceManager.GetString(\"SimpleRoleProvder_UserNotInRole\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to No role found that has the name &quot;{0}&quot;..\n        /// </summary>\n        internal static string SimpleRoleProvider_NoRoleFound {\n            get {\n                return ResourceManager.GetString(\"SimpleRoleProvider_NoRoleFound\", resourceCulture);\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Role &quot;{0}&quot; already exists..\n        /// </summary>\n        internal static string SimpleRoleProvider_RoleExists {\n            get {\n                return ResourceManager.GetString(\"SimpleRoleProvider_RoleExists\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/WebMatrix.WebData/Resources/WebDataResources.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"Security_DbFailure\" xml:space=\"preserve\">\n    <value>Database operation failed.</value>\n  </data>\n  <data name=\"Security_FailedToFindUserTable\" xml:space=\"preserve\">\n    <value>No user table found that has the name \"{0}\".</value>\n  </data>\n  <data name=\"Security_InitializeAlreadyCalled\" xml:space=\"preserve\">\n    <value>The \"WebSecurity.InitializeDatabaseConnection\" method can be called only once.</value>\n  </data>\n  <data name=\"Security_InitializeMustBeCalledFirst\" xml:space=\"preserve\">\n    <value>You must call the \"WebSecurity.InitializeDatabaseConnection\" method before you call any other method of the \"WebSecurity\" class. This call should be placed in an _AppStart.cshtml file in the root of your site.</value>\n  </data>\n  <data name=\"Security_NoAccountFound\" xml:space=\"preserve\">\n    <value>No account exists for \"{0}\".</value>\n  </data>\n  <data name=\"Security_NoExtendedMembershipProvider\" xml:space=\"preserve\">\n    <value>To call this method, the \"Membership.Provider\" property must be an instance of \"ExtendedMembershipProvider\".</value>\n  </data>\n  <data name=\"Security_NoUserFound\" xml:space=\"preserve\">\n    <value>No user found was found that has the name \"{0}\".</value>\n  </data>\n  <data name=\"SimpleMembership_FailToStoreOAuthToken\" xml:space=\"preserve\">\n    <value>Failed to store OAuth token to database.</value>\n  </data>\n  <data name=\"SimpleMembership_PasswordTooLong\" xml:space=\"preserve\">\n    <value>The membership password is too long. (Maximum length is 128 characters).</value>\n  </data>\n  <data name=\"SimpleMembership_ProviderUnrecognizedAttribute\" xml:space=\"preserve\">\n    <value>Provider unrecognized attribute: \"{0}\".</value>\n  </data>\n  <data name=\"SimpleRoleProvder_RolePopulated\" xml:space=\"preserve\">\n    <value>The role \"{0}\" cannot be deleted because there are still users in the role.</value>\n  </data>\n  <data name=\"SimpleRoleProvder_UserAlreadyInRole\" xml:space=\"preserve\">\n    <value>User \"{0}\" is already in role \"{1}\".</value>\n  </data>\n  <data name=\"SimpleRoleProvder_UserNotInRole\" xml:space=\"preserve\">\n    <value>User \"{0}\" is not in role \"{1}\".</value>\n  </data>\n  <data name=\"SimpleRoleProvider_NoRoleFound\" xml:space=\"preserve\">\n    <value>No role found that has the name \"{0}\".</value>\n  </data>\n  <data name=\"SimpleRoleProvider_RoleExists\" xml:space=\"preserve\">\n    <value>Role \"{0}\" already exists.</value>\n  </data>\n</root>"
  },
  {
    "path": "src/WebMatrix.WebData/SimpleMembershipProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.ComponentModel;\nusing System.Configuration.Provider;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.Linq;\nusing System.Security.Cryptography;\nusing System.Text;\nusing System.Web;\nusing System.Web.Helpers;\nusing System.Web.Security;\nusing System.Web.WebPages;\nusing Microsoft.Internal.Web.Utils;\nusing WebMatrix.Data;\nusing WebMatrix.WebData.Resources;\n\nnamespace WebMatrix.WebData\n{\n    public class SimpleMembershipProvider : ExtendedMembershipProvider\n    {\n        private const int TokenSizeInBytes = 16;\n        private readonly MembershipProvider _previousProvider;\n        private SimpleMembershipProviderCasingBehavior _casingBehavior;\n\n        public SimpleMembershipProvider()\n            : this(null)\n        {\n        }\n\n        public SimpleMembershipProvider(MembershipProvider previousProvider)\n        {\n            _previousProvider = previousProvider;\n            if (_previousProvider != null)\n            {\n                _previousProvider.ValidatingPassword += (sender, args) =>\n                {\n                    if (!InitializeCalled)\n                    {\n                        OnValidatingPassword(args);\n                    }\n                };\n            }\n        }\n\n        private MembershipProvider PreviousProvider\n        {\n            get\n            {\n                if (_previousProvider == null)\n                {\n                    throw new InvalidOperationException(WebDataResources.Security_InitializeMustBeCalledFirst);\n                }\n                else\n                {\n                    return _previousProvider;\n                }\n            }\n        }\n\n        // Public properties\n        // Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override bool EnablePasswordRetrieval\n        {\n            get { return InitializeCalled ? false : PreviousProvider.EnablePasswordRetrieval; }\n        }\n\n        // Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override bool EnablePasswordReset\n        {\n            get { return InitializeCalled ? false : PreviousProvider.EnablePasswordReset; }\n        }\n\n        // Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override bool RequiresQuestionAndAnswer\n        {\n            get { return InitializeCalled ? false : PreviousProvider.RequiresQuestionAndAnswer; }\n        }\n\n        // Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override bool RequiresUniqueEmail\n        {\n            get { return InitializeCalled ? false : PreviousProvider.RequiresUniqueEmail; }\n        }\n\n        // Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override MembershipPasswordFormat PasswordFormat\n        {\n            get { return InitializeCalled ? MembershipPasswordFormat.Hashed : PreviousProvider.PasswordFormat; }\n        }\n\n        // Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override int MaxInvalidPasswordAttempts\n        {\n            get { return InitializeCalled ? Int32.MaxValue : PreviousProvider.MaxInvalidPasswordAttempts; }\n        }\n\n        // Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override int PasswordAttemptWindow\n        {\n            get { return InitializeCalled ? Int32.MaxValue : PreviousProvider.PasswordAttemptWindow; }\n        }\n\n        // Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override int MinRequiredPasswordLength\n        {\n            get { return InitializeCalled ? 0 : PreviousProvider.MinRequiredPasswordLength; }\n        }\n\n        // Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override int MinRequiredNonAlphanumericCharacters\n        {\n            get { return InitializeCalled ? 0 : PreviousProvider.MinRequiredNonAlphanumericCharacters; }\n        }\n\n        // Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override string PasswordStrengthRegularExpression\n        {\n            get { return InitializeCalled ? String.Empty : PreviousProvider.PasswordStrengthRegularExpression; }\n        }\n\n        // Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override string ApplicationName\n        {\n            get\n            {\n                if (InitializeCalled)\n                {\n                    throw new NotSupportedException();\n                }\n                else\n                {\n                    return PreviousProvider.ApplicationName;\n                }\n            }\n            set\n            {\n                if (InitializeCalled)\n                {\n                    throw new NotSupportedException();\n                }\n                else\n                {\n                    PreviousProvider.ApplicationName = value;\n                }\n            }\n        }\n\n        internal static string MembershipTableName\n        {\n            get { return \"webpages_Membership\"; }\n        }\n\n        internal static string OAuthMembershipTableName\n        {\n            get { return \"webpages_OAuthMembership\"; }\n        }\n\n        internal static string OAuthTokenTableName\n        {\n            get { return \"webpages_OAuthToken\"; }\n        }\n\n        private string SafeUserTableName\n        {\n            get { return \"[\" + UserTableName + \"]\"; }\n        }\n\n        private string SafeUserIdColumn\n        {\n            get { return \"[\" + UserIdColumn + \"]\"; }\n        }\n\n        private string SafeUserNameColumn\n        {\n            get { return \"[\" + UserNameColumn + \"]\"; }\n        }\n\n        // represents the User table for the app\n        public string UserTableName { get; set; }\n\n        // represents the User created UserName column, i.e. Email\n        public string UserNameColumn { get; set; }\n\n        // Represents the User created id column, i.e. ID;\n        // REVIEW: we could get this from the primary key of UserTable in the future\n        public string UserIdColumn { get; set; }\n\n        /// <summary>\n        /// Gets or sets the <see cref=\"WebMatrix.WebData.SimpleMembershipProviderCasingBehavior\"/> for this provider.\n        /// </summary>\n        /// <remarks>\n        /// This value configures whether or not queries for user names normalize the user name to uppercase. See\n        /// <see cref=\"WebMatrix.WebData.SimpleMembershipProviderCasingBehavior\"/> for a full description.\n        /// </remarks>\n        public SimpleMembershipProviderCasingBehavior CasingBehavior\n        {\n            get\n            {\n                return _casingBehavior;\n            }\n            set\n            {\n                if (value < SimpleMembershipProviderCasingBehavior.NormalizeCasing || value > SimpleMembershipProviderCasingBehavior.RelyOnDatabaseCollation)\n                {\n                    throw new InvalidEnumArgumentException(\"value\", (int)value, typeof(SimpleMembershipProviderCasingBehavior));\n                }\n\n                _casingBehavior = value;\n            }\n        }\n\n        internal DatabaseConnectionInfo ConnectionInfo { get; set; }\n        internal bool InitializeCalled { get; set; }\n\n        internal override void VerifyInitialized()\n        {\n            if (!InitializeCalled)\n            {\n                throw new InvalidOperationException(WebDataResources.Security_InitializeMustBeCalledFirst);\n            }\n        }\n\n        // Inherited from ProviderBase - The \"previous provider\" we get has already been initialized by the Config system,\n        // so we shouldn't forward this call\n        public override void Initialize(string name, NameValueCollection config)\n        {\n            if (config == null)\n            {\n                throw new ArgumentNullException(\"config\");\n            }\n            if (String.IsNullOrEmpty(name))\n            {\n                name = \"SimpleMembershipProvider\";\n            }\n            if (String.IsNullOrEmpty(config[\"description\"]))\n            {\n                config.Remove(\"description\");\n                config.Add(\"description\", \"Simple Membership Provider\");\n            }\n            base.Initialize(name, config);\n\n            config.Remove(\"connectionStringName\");\n            config.Remove(\"enablePasswordRetrieval\");\n            config.Remove(\"enablePasswordReset\");\n            config.Remove(\"requiresQuestionAndAnswer\");\n            config.Remove(\"applicationName\");\n            config.Remove(\"requiresUniqueEmail\");\n            config.Remove(\"maxInvalidPasswordAttempts\");\n            config.Remove(\"passwordAttemptWindow\");\n            config.Remove(\"passwordFormat\");\n            config.Remove(\"name\");\n            config.Remove(\"description\");\n            config.Remove(\"minRequiredPasswordLength\");\n            config.Remove(\"minRequiredNonalphanumericCharacters\");\n            config.Remove(\"passwordStrengthRegularExpression\");\n            config.Remove(\"hashAlgorithmType\");\n\n            if (config.Count > 0)\n            {\n                string attribUnrecognized = config.GetKey(0);\n                if (!String.IsNullOrEmpty(attribUnrecognized))\n                {\n                    throw new ProviderException(String.Format(CultureInfo.CurrentCulture, WebDataResources.SimpleMembership_ProviderUnrecognizedAttribute, attribUnrecognized));\n                }\n            }\n        }\n\n        internal static bool CheckTableExists(IDatabase db, string tableName)\n        {\n            var query = db.QuerySingle(@\"SELECT * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = @0\", tableName);\n            return query != null;\n        }\n\n        internal void CreateTablesIfNeeded()\n        {\n            using (var db = ConnectToDatabase())\n            {\n                if (!CheckTableExists(db, UserTableName))\n                {\n                    db.Execute(@\"CREATE TABLE \" + SafeUserTableName + \"(\" + SafeUserIdColumn + \" int NOT NULL PRIMARY KEY IDENTITY, \" + SafeUserNameColumn + \" nvarchar(56) NOT NULL UNIQUE)\");\n                }\n\n                if (!CheckTableExists(db, OAuthMembershipTableName))\n                {\n                    db.Execute(@\"CREATE TABLE \" + OAuthMembershipTableName + \" (Provider nvarchar(30) NOT NULL, ProviderUserId nvarchar(100) NOT NULL, UserId int NOT NULL, PRIMARY KEY (Provider, ProviderUserId))\");\n                }\n\n                if (!CheckTableExists(db, MembershipTableName))\n                {\n                    db.Execute(@\"CREATE TABLE \" + MembershipTableName + @\" (\n                        UserId                                  int                 NOT NULL PRIMARY KEY,\n                        CreateDate                              datetime            ,\n                        ConfirmationToken                       nvarchar(128)       ,\n                        IsConfirmed                             bit                 DEFAULT 0,\n                        LastPasswordFailureDate                 datetime            ,\n                        PasswordFailuresSinceLastSuccess         int                 NOT NULL DEFAULT 0,\n                        Password                                nvarchar(128)       NOT NULL,\n                        PasswordChangedDate                     datetime            ,\n                        PasswordSalt                            nvarchar(128)       NOT NULL,\n                        PasswordVerificationToken               nvarchar(128)       ,\n                        PasswordVerificationTokenExpirationDate datetime)\");\n                    // TODO: Do we want to add FK constraint to user table too?\n                    //                        CONSTRAINT fk_UserId FOREIGN KEY (UserId) REFERENCES \"+UserTableName+\"(\"+UserIdColumn+\"))\");\n                }\n            }\n        }\n\n        private static void CreateOAuthTokenTableIfNeeded(IDatabase db)\n        {\n            if (!CheckTableExists(db, OAuthTokenTableName))\n            {\n                db.Execute(@\"CREATE TABLE \" + OAuthTokenTableName + \" (Token nvarchar(100) NOT NULL, Secret nvarchar(100) NOT NULL, PRIMARY KEY (Token))\");\n            }\n        }\n\n        // Not an override ==> Simple Membership MUST be enabled to use this method\n        public int GetUserId(string userName)\n        {\n            VerifyInitialized();\n            using (var db = ConnectToDatabase())\n            {\n                return GetUserId(db, userName);\n            }\n        }\n\n        private int GetUserId(IDatabase db, string userName)\n        {\n            return GetUserId(db, SafeUserTableName, SafeUserNameColumn, SafeUserIdColumn, CasingBehavior, userName);\n        }\n\n        internal static int GetUserId(\n            IDatabase db,\n            string userTableName,\n            string userNameColumn,\n            string userIdColumn,\n            SimpleMembershipProviderCasingBehavior casingBehavior,\n            string userName)\n        {\n            dynamic result;\n            if (casingBehavior == SimpleMembershipProviderCasingBehavior.NormalizeCasing)\n            {\n                // Casing is normalized in Sql to allow the database to normalize username according to its collation. The common issue \n                // that can occur here is the 'Turkish i problem', where the uppercase of 'i' is not 'I' in Turkish.\n                result = db.QueryValue(@\"SELECT \" + userIdColumn + \" FROM \" + userTableName + \" WHERE (UPPER(\" + userNameColumn + \") = UPPER(@0))\", userName);\n            }\n            else if (casingBehavior == SimpleMembershipProviderCasingBehavior.RelyOnDatabaseCollation)\n            {\n                // When this option is supplied we assume the database has been configured with an appropriate casing, and don't normalize \n                // the user name. This is performant but requires appropriate configuration on the database.\n                result = db.QueryValue(@\"SELECT \" + userIdColumn + \" FROM \" + userTableName + \" WHERE (\" + userNameColumn + \" = @0)\", userName);\n            }\n            else\n            {\n                Debug.Fail(\"Unexpected enum value\");\n                return -1;\n            }\n\n            if (result != null)\n            {\n                return (int)result;\n            }\n            return -1;\n        }\n\n        // Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method\n        public override int GetUserIdFromPasswordResetToken(string token)\n        {\n            VerifyInitialized();\n            using (var db = ConnectToDatabase())\n            {\n                var result = db.QuerySingle(@\"SELECT UserId FROM \" + MembershipTableName + \" WHERE (PasswordVerificationToken = @0)\", token);\n                if (result != null && result[0] != null)\n                {\n                    return (int)result[0];\n                }\n                return -1;\n            }\n        }\n\n        // Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)\n        {\n            if (!InitializeCalled)\n            {\n                return PreviousProvider.ChangePasswordQuestionAndAnswer(username, password, newPasswordQuestion, newPasswordAnswer);\n            }\n            throw new NotSupportedException();\n        }\n\n        /// <summary>\n        /// Sets the confirmed flag for the username if it is correct.\n        /// </summary>\n        /// <returns>True if the account could be successfully confirmed. False if the username was not found or the confirmation token is invalid.</returns>\n        /// <remarks>Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method</remarks>\n        public override bool ConfirmAccount(string userName, string accountConfirmationToken)\n        {\n            VerifyInitialized();\n            using (var db = ConnectToDatabase())\n            {\n                // We need to compare the token using a case insensitive comparison however it seems tricky to do this uniformly across databases when representing the token as a string. \n                // Therefore verify the case on the client\n                var row = db.QuerySingle(\"SELECT m.[UserId], m.[ConfirmationToken] FROM \" + MembershipTableName + \" m JOIN \" + SafeUserTableName + \" u\"\n                                         + \" ON m.[UserId] = u.\" + SafeUserIdColumn\n                                         + \" WHERE m.[ConfirmationToken] = @0 AND\"\n                                         + \" u.\" + SafeUserNameColumn + \" = @1\", accountConfirmationToken, userName);\n                if (row == null)\n                {\n                    return false;\n                }\n                int userId = row[0];\n                string expectedToken = row[1];\n\n                if (String.Equals(accountConfirmationToken, expectedToken, StringComparison.Ordinal))\n                {\n                    int affectedRows = db.Execute(\"UPDATE \" + MembershipTableName + \" SET [IsConfirmed] = 1 WHERE [UserId] = @0\", userId);\n                    return affectedRows > 0;\n                }\n                return false;\n            }\n        }\n\n        /// <summary>\n        /// Sets the confirmed flag for the username if it is correct.\n        /// </summary>\n        /// <returns>True if the account could be successfully confirmed. False if the username was not found or the confirmation token is invalid.</returns>\n        /// <remarks>Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method.\n        /// There is a tiny possibility where this method fails to work correctly. Two or more users could be assigned the same token but specified using different cases.\n        /// A workaround for this would be to use the overload that accepts both the user name and confirmation token.\n        /// </remarks>\n        public override bool ConfirmAccount(string accountConfirmationToken)\n        {\n            VerifyInitialized();\n            using (var db = ConnectToDatabase())\n            {\n                // We need to compare the token using a case insensitive comparison however it seems tricky to do this uniformly across databases when representing the token as a string. \n                // Therefore verify the case on the client\n                var rows = db.Query(\"SELECT [UserId], [ConfirmationToken] FROM \" + MembershipTableName + \" WHERE [ConfirmationToken] = @0\", accountConfirmationToken)\n                    .Where(r => ((string)r[1]).Equals(accountConfirmationToken, StringComparison.Ordinal))\n                    .ToList();\n                Debug.Assert(rows.Count < 2, \"By virtue of the fact that the ConfirmationToken is random and unique, we can never have two tokens that are identical.\");\n                if (!rows.Any())\n                {\n                    return false;\n                }\n                var row = rows.First();\n                int userId = row[0];\n                int affectedRows = db.Execute(\"UPDATE \" + MembershipTableName + \" SET [IsConfirmed] = 1 WHERE [UserId] = @0\", userId);\n                return affectedRows > 0;\n            }\n        }\n\n        internal virtual IDatabase ConnectToDatabase()\n        {\n            return new DatabaseWrapper(ConnectionInfo.Connect());\n        }\n\n        // Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method\n        public override string CreateAccount(string userName, string password, bool requireConfirmationToken)\n        {\n            VerifyInitialized();\n\n            if (password.IsEmpty())\n            {\n                throw new MembershipCreateUserException(MembershipCreateStatus.InvalidPassword);\n            }\n\n            string hashedPassword = Crypto.HashPassword(password);\n            if (hashedPassword.Length > 128)\n            {\n                throw new MembershipCreateUserException(MembershipCreateStatus.InvalidPassword);\n            }\n\n            if (userName.IsEmpty())\n            {\n                throw new MembershipCreateUserException(MembershipCreateStatus.InvalidUserName);\n            }\n\n            using (var db = ConnectToDatabase())\n            {\n                // Step 1: Check if the user exists in the Users table\n                int uid = GetUserId(db, SafeUserTableName, SafeUserNameColumn, SafeUserIdColumn, CasingBehavior, userName);\n                if (uid == -1)\n                {\n                    // User not found\n                    throw new MembershipCreateUserException(MembershipCreateStatus.ProviderError);\n                }\n\n                // Step 2: Check if the user exists in the Membership table: Error if yes.\n                var result = db.QuerySingle(@\"SELECT COUNT(*) FROM [\" + MembershipTableName + \"] WHERE UserId = @0\", uid);\n                if (result[0] > 0)\n                {\n                    throw new MembershipCreateUserException(MembershipCreateStatus.DuplicateUserName);\n                }\n\n                // Step 3: Create user in Membership table\n                string token = null;\n                object dbtoken = DBNull.Value;\n                if (requireConfirmationToken)\n                {\n                    token = GenerateToken();\n                    dbtoken = token;\n                }\n                int defaultNumPasswordFailures = 0;\n\n                int insert = db.Execute(@\"INSERT INTO [\" + MembershipTableName + \"] (UserId, [Password], PasswordSalt, IsConfirmed, ConfirmationToken, CreateDate, PasswordChangedDate, PasswordFailuresSinceLastSuccess)\"\n                                        + \" VALUES (@0, @1, @2, @3, @4, @5, @5, @6)\", uid, hashedPassword, String.Empty /* salt column is unused */, !requireConfirmationToken, dbtoken, DateTime.UtcNow, defaultNumPasswordFailures);\n                if (insert != 1)\n                {\n                    throw new MembershipCreateUserException(MembershipCreateStatus.ProviderError);\n                }\n                return token;\n            }\n        }\n\n        // Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)\n        {\n            if (!InitializeCalled)\n            {\n                return PreviousProvider.CreateUser(username, password, email, passwordQuestion, passwordAnswer, isApproved, providerUserKey, out status);\n            }\n            throw new NotSupportedException();\n        }\n\n        private void CreateUserRow(IDatabase db, string userName, IDictionary<string, object> values)\n        {\n            // Make sure user doesn't exist\n            int userId = GetUserId(db, userName);\n            if (userId != -1)\n            {\n                throw new MembershipCreateUserException(MembershipCreateStatus.DuplicateUserName);\n            }\n\n            StringBuilder columnString = new StringBuilder();\n            columnString.Append(SafeUserNameColumn);\n            StringBuilder argsString = new StringBuilder();\n            argsString.Append(\"@0\");\n            List<object> argsArray = new List<object>();\n            argsArray.Add(userName);\n            if (values != null)\n            {\n                int index = 1;\n                foreach (string key in values.Keys)\n                {\n                    // Skip the user name column since we always generate that\n                    if (String.Equals(UserNameColumn, key, StringComparison.OrdinalIgnoreCase))\n                    {\n                        continue;\n                    }\n                    columnString.Append(\",\").Append(key);\n                    argsString.Append(\",@\").Append(index++);\n                    object value = values[key];\n                    if (value == null)\n                    {\n                        value = DBNull.Value;\n                    }\n                    argsArray.Add(value);\n                }\n            }\n\n            int rows = db.Execute(\"INSERT INTO \" + SafeUserTableName + \" (\" + columnString.ToString() + \") VALUES (\" + argsString.ToString() + \")\", argsArray.ToArray());\n            if (rows != 1)\n            {\n                throw new MembershipCreateUserException(MembershipCreateStatus.ProviderError);\n            }\n        }\n\n        // Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method\n        public override string CreateUserAndAccount(string userName, string password, bool requireConfirmation, IDictionary<string, object> values)\n        {\n            VerifyInitialized();\n\n            using (var db = ConnectToDatabase())\n            {\n                CreateUserRow(db, userName, values);\n                return CreateAccount(userName, password, requireConfirmation);\n            }\n        }\n\n        // Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override string GetPassword(string username, string answer)\n        {\n            if (!InitializeCalled)\n            {\n                return PreviousProvider.GetPassword(username, answer);\n            }\n            throw new NotSupportedException();\n        }\n\n        private static bool SetPassword(IDatabase db, int userId, string newPassword)\n        {\n            string hashedPassword = Crypto.HashPassword(newPassword);\n            if (hashedPassword.Length > 128)\n            {\n                throw new ArgumentException(WebDataResources.SimpleMembership_PasswordTooLong);\n            }\n\n            // Update new password\n            int result = db.Execute(@\"UPDATE \" + MembershipTableName + \" SET Password=@0, PasswordSalt=@1, PasswordChangedDate=@2 WHERE UserId = @3\", hashedPassword, String.Empty /* salt column is unused */, DateTime.UtcNow, userId);\n            return result > 0;\n        }\n\n        // Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override bool ChangePassword(string username, string oldPassword, string newPassword)\n        {\n            if (!InitializeCalled)\n            {\n                return PreviousProvider.ChangePassword(username, oldPassword, newPassword);\n            }\n\n            // REVIEW: are commas special in the password?\n            if (username.IsEmpty())\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"username\");\n            }\n            if (oldPassword.IsEmpty())\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"oldPassword\");\n            }\n            if (newPassword.IsEmpty())\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"newPassword\");\n            }\n\n            using (var db = ConnectToDatabase())\n            {\n                int userId = GetUserId(db, username);\n                if (userId == -1)\n                {\n                    return false; // User not found\n                }\n\n                // First check that the old credentials match\n                if (!CheckPassword(db, userId, oldPassword))\n                {\n                    return false;\n                }\n\n                return SetPassword(db, userId, newPassword);\n            }\n        }\n\n        // Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override string ResetPassword(string username, string answer)\n        {\n            if (!InitializeCalled)\n            {\n                return PreviousProvider.ResetPassword(username, answer);\n            }\n            throw new NotSupportedException();\n        }\n\n        // Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)\n        {\n            if (!InitializeCalled)\n            {\n                return PreviousProvider.GetUser(providerUserKey, userIsOnline);\n            }\n            throw new NotSupportedException();\n        }\n\n        // Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override MembershipUser GetUser(string username, bool userIsOnline)\n        {\n            if (!InitializeCalled)\n            {\n                return PreviousProvider.GetUser(username, userIsOnline);\n            }\n\n            // Due to a bug in v1, GetUser allows passing null / empty values.\n            using (var db = ConnectToDatabase())\n            {\n                int userId = GetUserId(db, username);\n                if (userId == -1)\n                {\n                    return null; // User not found\n                }\n\n                return new MembershipUser(Membership.Provider.Name, username, userId, null, null, null, true, false, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue);\n            }\n        }\n\n        // Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override string GetUserNameByEmail(string email)\n        {\n            if (!InitializeCalled)\n            {\n                return PreviousProvider.GetUserNameByEmail(email);\n            }\n            throw new NotSupportedException();\n        }\n\n        // Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method\n        public override bool DeleteAccount(string userName)\n        {\n            VerifyInitialized();\n\n            using (var db = ConnectToDatabase())\n            {\n                int userId = GetUserId(db, userName);\n                if (userId == -1)\n                {\n                    return false; // User not found\n                }\n\n                int deleted = db.Execute(@\"DELETE FROM \" + MembershipTableName + \" WHERE UserId = @0\", userId);\n                return (deleted == 1);\n            }\n        }\n\n        // Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override bool DeleteUser(string username, bool deleteAllRelatedData)\n        {\n            if (!InitializeCalled)\n            {\n                return PreviousProvider.DeleteUser(username, deleteAllRelatedData);\n            }\n\n            using (var db = ConnectToDatabase())\n            {\n                int userId = GetUserId(db, username);\n                if (userId == -1)\n                {\n                    return false; // User not found\n                }\n\n                int deleted = db.Execute(@\"DELETE FROM \" + SafeUserTableName + \" WHERE \" + SafeUserIdColumn + \" = @0\", userId);\n                bool returnValue = (deleted == 1);\n\n                //if (deleteAllRelatedData) {\n                // REVIEW: do we really want to delete from the user table?\n                //}\n                return returnValue;\n            }\n        }\n\n        internal bool DeleteUserAndAccountInternal(string userName)\n        {\n            return (DeleteAccount(userName) && DeleteUser(userName, false));\n        }\n\n        // Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)\n        {\n            if (!InitializeCalled)\n            {\n                return PreviousProvider.GetAllUsers(pageIndex, pageSize, out totalRecords);\n            }\n            throw new NotSupportedException();\n        }\n\n        // Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override int GetNumberOfUsersOnline()\n        {\n            if (!InitializeCalled)\n            {\n                return PreviousProvider.GetNumberOfUsersOnline();\n            }\n            throw new NotSupportedException();\n        }\n\n        // Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)\n        {\n            if (!InitializeCalled)\n            {\n                return PreviousProvider.FindUsersByName(usernameToMatch, pageIndex, pageSize, out totalRecords);\n            }\n            throw new NotSupportedException();\n        }\n\n        // Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)\n        {\n            if (!InitializeCalled)\n            {\n                return PreviousProvider.FindUsersByEmail(emailToMatch, pageIndex, pageSize, out totalRecords);\n            }\n            throw new NotSupportedException();\n        }\n\n        private static int GetPasswordFailuresSinceLastSuccess(IDatabase db, int userId)\n        {\n            var failure = db.QueryValue(@\"SELECT PasswordFailuresSinceLastSuccess FROM \" + MembershipTableName + \" WHERE (UserId = @0)\", userId);\n            if (failure != null)\n            {\n                return failure;\n            }\n            return -1;\n        }\n\n        // Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method\n        public override int GetPasswordFailuresSinceLastSuccess(string userName)\n        {\n            using (var db = ConnectToDatabase())\n            {\n                int userId = GetUserId(db, userName);\n                if (userId == -1)\n                {\n                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, WebDataResources.Security_NoUserFound, userName));\n                }\n\n                return GetPasswordFailuresSinceLastSuccess(db, userId);\n            }\n        }\n\n        // Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method\n        public override DateTime GetCreateDate(string userName)\n        {\n            using (var db = ConnectToDatabase())\n            {\n                int userId = GetUserId(db, userName);\n                if (userId == -1)\n                {\n                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, WebDataResources.Security_NoUserFound, userName));\n                }\n\n                var createDate = db.QueryValue(@\"SELECT CreateDate FROM \" + MembershipTableName + \" WHERE (UserId = @0)\", userId);\n                if (createDate != null)\n                {\n                    return createDate;\n                }\n                return DateTime.MinValue;\n            }\n        }\n\n        // Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method\n        public override DateTime GetPasswordChangedDate(string userName)\n        {\n            using (var db = ConnectToDatabase())\n            {\n                int userId = GetUserId(db, userName);\n                if (userId == -1)\n                {\n                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, WebDataResources.Security_NoUserFound, userName));\n                }\n\n                var pwdChangeDate = db.QuerySingle(@\"SELECT PasswordChangedDate FROM \" + MembershipTableName + \" WHERE (UserId = @0)\", userId);\n                if (pwdChangeDate != null && pwdChangeDate[0] != null)\n                {\n                    return (DateTime)pwdChangeDate[0];\n                }\n                return DateTime.MinValue;\n            }\n        }\n\n        // Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method\n        public override DateTime GetLastPasswordFailureDate(string userName)\n        {\n            using (var db = ConnectToDatabase())\n            {\n                int userId = GetUserId(db, userName);\n                if (userId == -1)\n                {\n                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, WebDataResources.Security_NoUserFound, userName));\n                }\n\n                var failureDate = db.QuerySingle(@\"SELECT LastPasswordFailureDate FROM \" + MembershipTableName + \" WHERE (UserId = @0)\", userId);\n                if (failureDate != null && failureDate[0] != null)\n                {\n                    return (DateTime)failureDate[0];\n                }\n                return DateTime.MinValue;\n            }\n        }\n\n        private bool CheckPassword(IDatabase db, int userId, string password)\n        {\n            string hashedPassword = GetHashedPassword(db, userId);\n            bool verificationSucceeded = (hashedPassword != null && Crypto.VerifyHashedPassword(hashedPassword, password));\n            if (verificationSucceeded)\n            {\n                // Reset password failure count on successful credential check\n                db.Execute(@\"UPDATE \" + MembershipTableName + \" SET PasswordFailuresSinceLastSuccess = 0 WHERE (UserId = @0)\", userId);\n            }\n            else\n            {\n                int failures = GetPasswordFailuresSinceLastSuccess(db, userId);\n                if (failures != -1)\n                {\n                    db.Execute(@\"UPDATE \" + MembershipTableName + \" SET PasswordFailuresSinceLastSuccess = @1, LastPasswordFailureDate = @2 WHERE (UserId = @0)\", userId, failures + 1, DateTime.UtcNow);\n                }\n            }\n            return verificationSucceeded;\n        }\n\n        private string GetHashedPassword(IDatabase db, int userId)\n        {\n            var pwdQuery = db.Query(@\"SELECT m.[Password] \" +\n                                    @\"FROM \" + MembershipTableName + \" m, \" + SafeUserTableName + \" u \" +\n                                    @\"WHERE m.UserId = \" + userId + \" AND m.UserId = u.\" + SafeUserIdColumn).ToList();\n            // REVIEW: Should get exactly one match, should we throw if we get > 1?\n            if (pwdQuery.Count != 1)\n            {\n                return null;\n            }\n            return pwdQuery[0].Password;\n        }\n\n        // Ensures the user exists in the accounts table\n        private int VerifyUserNameHasConfirmedAccount(IDatabase db, string username, bool throwException)\n        {\n            int userId = GetUserId(db, username);\n            if (userId == -1)\n            {\n                if (throwException)\n                {\n                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, WebDataResources.Security_NoUserFound, username));\n                }\n                else\n                {\n                    return -1;\n                }\n            }\n\n            int result = db.QueryValue(@\"SELECT COUNT(*) FROM \" + MembershipTableName + \" WHERE (UserId = @0 AND IsConfirmed = 1)\", userId);\n            if (result == 0)\n            {\n                if (throwException)\n                {\n                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, WebDataResources.Security_NoAccountFound, username));\n                }\n                else\n                {\n                    return -1;\n                }\n            }\n            return userId;\n        }\n\n        private static string GenerateToken()\n        {\n            using (var prng = new RNGCryptoServiceProvider())\n            {\n                return GenerateToken(prng);\n            }\n        }\n\n        internal static string GenerateToken(RandomNumberGenerator generator)\n        {\n            byte[] tokenBytes = new byte[TokenSizeInBytes];\n            generator.GetBytes(tokenBytes);\n            return HttpServerUtility.UrlTokenEncode(tokenBytes);\n        }\n\n        // Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method\n        public override string GeneratePasswordResetToken(string userName, int tokenExpirationInMinutesFromNow)\n        {\n            VerifyInitialized();\n            if (userName.IsEmpty())\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"userName\");\n            }\n            using (var db = ConnectToDatabase())\n            {\n                int userId = VerifyUserNameHasConfirmedAccount(db, userName, throwException: true);\n\n                string token = db.QueryValue(@\"SELECT PasswordVerificationToken FROM \" + MembershipTableName + \" WHERE (UserId = @0 AND PasswordVerificationTokenExpirationDate > @1)\", userId, DateTime.UtcNow);\n                if (token == null)\n                {\n                    token = GenerateToken();\n\n                    int rows = db.Execute(@\"UPDATE \" + MembershipTableName + \" SET PasswordVerificationToken = @0, PasswordVerificationTokenExpirationDate = @1 WHERE (UserId = @2)\", token, DateTime.UtcNow.AddMinutes(tokenExpirationInMinutesFromNow), userId);\n                    if (rows != 1)\n                    {\n                        throw new ProviderException(WebDataResources.Security_DbFailure);\n                    }\n                }\n                else\n                {\n                    // TODO: should we update expiry again?\n                }\n                return token;\n            }\n        }\n\n        // Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method\n        public override bool IsConfirmed(string userName)\n        {\n            VerifyInitialized();\n            if (userName.IsEmpty())\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"userName\");\n            }\n\n            using (var db = ConnectToDatabase())\n            {\n                int userId = VerifyUserNameHasConfirmedAccount(db, userName, throwException: false);\n                return (userId != -1);\n            }\n        }\n\n        // Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method\n        public override bool ResetPasswordWithToken(string token, string newPassword)\n        {\n            VerifyInitialized();\n            if (newPassword.IsEmpty())\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"newPassword\");\n            }\n            using (var db = ConnectToDatabase())\n            {\n                int? userId = db.QueryValue(@\"SELECT UserId FROM \" + MembershipTableName + \" WHERE (PasswordVerificationToken = @0 AND PasswordVerificationTokenExpirationDate > @1)\", token, DateTime.UtcNow);\n                if (userId != null)\n                {\n                    bool success = SetPassword(db, userId.Value, newPassword);\n                    if (success)\n                    {\n                        // Clear the Token on success\n                        int rows = db.Execute(@\"UPDATE \" + MembershipTableName + \" SET PasswordVerificationToken = NULL, PasswordVerificationTokenExpirationDate = NULL WHERE (UserId = @0)\", userId);\n                        if (rows != 1)\n                        {\n                            throw new ProviderException(WebDataResources.Security_DbFailure);\n                        }\n                    }\n                    return success;\n                }\n                else\n                {\n                    return false;\n                }\n            }\n        }\n\n        // Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override void UpdateUser(MembershipUser user)\n        {\n            if (!InitializeCalled)\n            {\n                PreviousProvider.UpdateUser(user);\n            }\n            else\n            {\n                throw new NotSupportedException();\n            }\n        }\n\n        // Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override bool UnlockUser(string userName)\n        {\n            if (!InitializeCalled)\n            {\n                return PreviousProvider.UnlockUser(userName);\n            }\n            throw new NotSupportedException();\n        }\n\n        internal void ValidateUserTable()\n        {\n            using (var db = ConnectToDatabase())\n            {\n                // GetUser will fail with an exception if the user table isn't set up properly\n                try\n                {\n                    GetUserId(db, \"z\");\n                }\n                catch (Exception e)\n                {\n                    throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, WebDataResources.Security_FailedToFindUserTable, UserTableName), e);\n                }\n            }\n        }\n\n        // Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override bool ValidateUser(string username, string password)\n        {\n            if (!InitializeCalled)\n            {\n                return PreviousProvider.ValidateUser(username, password);\n            }\n            if (username.IsEmpty())\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"username\");\n            }\n            if (password.IsEmpty())\n            {\n                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, \"password\");\n            }\n\n            using (var db = ConnectToDatabase())\n            {\n                int userId = VerifyUserNameHasConfirmedAccount(db, username, throwException: false);\n                if (userId == -1)\n                {\n                    return false;\n                }\n                else\n                {\n                    return CheckPassword(db, userId, password);\n                }\n            }\n        }\n\n        public override string GetUserNameFromId(int userId)\n        {\n            VerifyInitialized();\n\n            using (var db = ConnectToDatabase())\n            {\n                dynamic username = db.QueryValue(\"SELECT \" + SafeUserNameColumn + \" FROM \" + SafeUserTableName + \" WHERE (\" + SafeUserIdColumn + \"=@0)\", userId);\n                return (string)username;\n            }\n        }\n\n        public override void CreateOrUpdateOAuthAccount(string provider, string providerUserId, string userName)\n        {\n            VerifyInitialized();\n\n            if (userName.IsEmpty())\n            {\n                throw new MembershipCreateUserException(MembershipCreateStatus.ProviderError);\n            }\n\n            int userId = GetUserId(userName);\n            if (userId == -1)\n            {\n                throw new MembershipCreateUserException(MembershipCreateStatus.InvalidUserName);\n            }\n\n            var oldUserId = GetUserIdFromOAuth(provider, providerUserId);\n            using (var db = ConnectToDatabase())\n            {\n                if (oldUserId == -1)\n                {\n                    // account doesn't exist. create a new one.\n                    int insert = db.Execute(@\"INSERT INTO [\" + OAuthMembershipTableName + \"] (Provider, ProviderUserId, UserId) VALUES (@0, @1, @2)\", provider, providerUserId, userId);\n                    if (insert != 1)\n                    {\n                        throw new MembershipCreateUserException(MembershipCreateStatus.ProviderError);\n                    }\n                }\n                else\n                {\n                    // account already exist. update it\n                    int insert = db.Execute(@\"UPDATE [\" + OAuthMembershipTableName + \"] SET UserId = @2 WHERE UPPER(Provider)=@0 AND UPPER(ProviderUserId)=@1\", provider, providerUserId, userId);\n                    if (insert != 1)\n                    {\n                        throw new MembershipCreateUserException(MembershipCreateStatus.ProviderError);\n                    }\n                }\n            }\n        }\n\n        public override void DeleteOAuthAccount(string provider, string providerUserId)\n        {\n            VerifyInitialized();\n\n            using (var db = ConnectToDatabase())\n            {\n                // account doesn't exist. create a new one.\n                int insert = db.Execute(@\"DELETE FROM [\" + OAuthMembershipTableName + \"] WHERE UPPER(Provider)=@0 AND UPPER(ProviderUserId)=@1\", provider, providerUserId);\n                if (insert != 1)\n                {\n                    throw new MembershipCreateUserException(MembershipCreateStatus.ProviderError);\n                }\n            }\n        }\n\n        public override int GetUserIdFromOAuth(string provider, string providerUserId)\n        {\n            VerifyInitialized();\n\n            using (var db = ConnectToDatabase())\n            {\n                dynamic id = db.QueryValue(@\"SELECT UserId FROM [\" + OAuthMembershipTableName + \"] WHERE UPPER(Provider)=@0 AND UPPER(ProviderUserId)=@1\", provider.ToUpperInvariant(), providerUserId.ToUpperInvariant());\n                if (id != null)\n                {\n                    return (int)id;\n                }\n\n                return -1;\n            }\n        }\n\n        public override string GetOAuthTokenSecret(string token)\n        {\n            VerifyInitialized();\n\n            using (var db = ConnectToDatabase())\n            {\n                CreateOAuthTokenTableIfNeeded(db);\n\n                // Note that token is case-sensitive\n                dynamic secret = db.QueryValue(@\"SELECT Secret FROM [\" + OAuthTokenTableName + \"] WHERE Token=@0\", token);\n                return (string)secret;\n            }\n        }\n\n        public override void StoreOAuthRequestToken(string requestToken, string requestTokenSecret)\n        {\n            VerifyInitialized();\n\n            string existingSecret = GetOAuthTokenSecret(requestToken);\n            if (existingSecret != null)\n            {\n                if (existingSecret == requestTokenSecret)\n                {\n                    // the record already exists\n                    return;\n                }\n\n                using (var db = ConnectToDatabase())\n                {\n                    CreateOAuthTokenTableIfNeeded(db);\n\n                    // the token exists with old secret, update it to new secret\n                    db.Execute(@\"UPDATE [\" + OAuthTokenTableName + \"] SET Secret = @1 WHERE Token = @0\", requestToken, requestTokenSecret);\n                }\n            }\n            else\n            {\n                using (var db = ConnectToDatabase())\n                {\n                    CreateOAuthTokenTableIfNeeded(db);\n\n                    // insert new record\n                    int insert = db.Execute(@\"INSERT INTO [\" + OAuthTokenTableName + \"] (Token, Secret) VALUES(@0, @1)\", requestToken, requestTokenSecret);\n                    if (insert != 1)\n                    {\n                        throw new ProviderException(WebDataResources.SimpleMembership_FailToStoreOAuthToken);\n                    }\n                }\n            }\n        }\n\n        /// <summary>\n        /// Replaces the request token with access token and secret.\n        /// </summary>\n        /// <param name=\"requestToken\">The request token.</param>\n        /// <param name=\"accessToken\">The access token.</param>\n        /// <param name=\"accessTokenSecret\">The access token secret.</param>\n        public override void ReplaceOAuthRequestTokenWithAccessToken(string requestToken, string accessToken, string accessTokenSecret)\n        {\n            VerifyInitialized();\n\n            using (var db = ConnectToDatabase())\n            {\n                CreateOAuthTokenTableIfNeeded(db);\n\n                // insert new record\n                db.Execute(@\"DELETE FROM [\" + OAuthTokenTableName + \"] WHERE Token = @0\", requestToken);\n\n                // Although there are two different types of tokens, request token and access token,\n                // we treat them the same in database records.\n                StoreOAuthRequestToken(accessToken, accessTokenSecret);\n            }\n        }\n\n        /// <summary>\n        /// Deletes the OAuth token from the backing store from the database.\n        /// </summary>\n        /// <param name=\"token\">The token to be deleted.</param>\n        public override void DeleteOAuthToken(string token)\n        {\n            VerifyInitialized();\n\n            using (var db = ConnectToDatabase())\n            {\n                CreateOAuthTokenTableIfNeeded(db);\n\n                // Note that token is case-sensitive\n                db.Execute(@\"DELETE FROM [\" + OAuthTokenTableName + \"] WHERE Token=@0\", token);\n            }\n        }\n\n        public override ICollection<OAuthAccountData> GetAccountsForUser(string userName)\n        {\n            VerifyInitialized();\n\n            int userId = GetUserId(userName);\n            if (userId != -1)\n            {\n                using (var db = ConnectToDatabase())\n                {\n                    IEnumerable<dynamic> records = db.Query(@\"SELECT Provider, ProviderUserId FROM [\" + OAuthMembershipTableName + \"] WHERE UserId=@0\", userId);\n                    if (records != null)\n                    {\n                        var accounts = new List<OAuthAccountData>();\n                        foreach (DynamicRecord row in records)\n                        {\n                            accounts.Add(new OAuthAccountData((string)row[\"Provider\"], (string)row[\"ProviderUserId\"]));\n                        }\n                        return accounts;\n                    }\n                }\n            }\n\n            return new OAuthAccountData[0];\n        }\n\n        /// <summary>\n        /// Determines whether there exists a local account (as opposed to OAuth account) with the specified userId.\n        /// </summary>\n        /// <param name=\"userId\">The user id to check for local account.</param>\n        /// <returns>\n        ///   <c>true</c> if there is a local account with the specified user id]; otherwise, <c>false</c>.\n        /// </returns>\n        public override bool HasLocalAccount(int userId)\n        {\n            VerifyInitialized();\n\n            using (var db = ConnectToDatabase())\n            {\n                dynamic id = db.QueryValue(@\"SELECT UserId FROM [\" + MembershipTableName + \"] WHERE UserId=@0\", userId);\n                return id != null;\n            }\n        }\n    }\n}"
  },
  {
    "path": "src/WebMatrix.WebData/SimpleMembershipProviderCasingBehavior.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace WebMatrix.WebData\n{\n    /// <summary>\n    /// Configures the behavior of SimpleMembershipProvider for the casing of user name queries.\n    /// </summary>\n    public enum SimpleMembershipProviderCasingBehavior\n    {\n        /// <summary>\n        /// Uses the SQL Upper function to normalize the casing of user names for a case-insensitive comparison. \n        /// This is the default value.\n        /// </summary>\n        /// <remarks>\n        /// This option uses the SQL Upper function to perform case-normalization. This guarantees that the \n        /// the user name is searched case-insensitively, but can have a performance impact when a large number\n        /// of users exist.\n        /// </remarks>\n        NormalizeCasing,\n\n        /// <summary>\n        /// Relies on the database's configured collation to normalize casing for the comparison of user names. User\n        /// names are provided to the database exactly as entered by the user.\n        /// </summary>\n        /// <remarks>\n        /// This option relies on the configured collection of database table for user names to perform a correct comparison.\n        /// This is guaranteed to be correct for the chosen collation and performant. Only choose this option if the table storing\n        /// user names is configured with the desired collation.\n        /// </remarks>\n        RelyOnDatabaseCollation,\n    }\n}\n"
  },
  {
    "path": "src/WebMatrix.WebData/SimpleRoleProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Configuration.Provider;\nusing System.Globalization;\nusing System.Linq;\nusing System.Web.Security;\nusing WebMatrix.WebData.Resources;\n\nnamespace WebMatrix.WebData\n{\n    public class SimpleRoleProvider : RoleProvider\n    {\n        private RoleProvider _previousProvider;\n        private SimpleMembershipProviderCasingBehavior _casingBehavior;\n\n        public SimpleRoleProvider()\n            : this(null)\n        {\n        }\n\n        public SimpleRoleProvider(RoleProvider previousProvider)\n        {\n            _previousProvider = previousProvider;\n        }\n\n        private RoleProvider PreviousProvider\n        {\n            get\n            {\n                if (_previousProvider == null)\n                {\n                    throw new InvalidOperationException(WebDataResources.Security_InitializeMustBeCalledFirst);\n                }\n                else\n                {\n                    return _previousProvider;\n                }\n            }\n        }\n\n        private string SafeUserTableName\n        {\n            get { return \"[\" + UserTableName + \"]\"; }\n        }\n\n        private string SafeUserNameColumn\n        {\n            get { return \"[\" + UserNameColumn + \"]\"; }\n        }\n\n        private string SafeUserIdColumn\n        {\n            get { return \"[\" + UserIdColumn + \"]\"; }\n        }\n\n        internal static string RoleTableName\n        {\n            get { return \"webpages_Roles\"; }\n        }\n\n        internal static string UsersInRoleTableName\n        {\n            get { return \"webpages_UsersInRoles\"; }\n        }\n\n        // represents the User table for the app\n        public string UserTableName { get; set; }\n\n        // represents the User created UserName column, i.e. Email\n        public string UserNameColumn { get; set; }\n\n        // Represents the User created id column, i.e. ID;\n        // REVIEW: we could get this from the primary key of UserTable in the future\n        public string UserIdColumn { get; set; }\n\n        /// <summary>\n        /// Gets or sets the <see cref=\"WebMatrix.WebData.SimpleMembershipProviderCasingBehavior\"/> for this provider.\n        /// </summary>\n        /// <remarks>\n        /// This value configures whether or not queries for user names normalize the user name to uppercase. See\n        /// <see cref=\"WebMatrix.WebData.SimpleMembershipProviderCasingBehavior\"/> for a full description.\n        /// </remarks>\n        public SimpleMembershipProviderCasingBehavior CasingBehavior\n        {\n            get\n            {\n                return _casingBehavior;\n            }\n            set\n            {\n                if (value < SimpleMembershipProviderCasingBehavior.NormalizeCasing || value > SimpleMembershipProviderCasingBehavior.RelyOnDatabaseCollation)\n                {\n                    throw new InvalidEnumArgumentException(\"value\", (int)value, typeof(SimpleMembershipProviderCasingBehavior));\n                }\n\n                _casingBehavior = value;\n            }\n        }\n\n        internal DatabaseConnectionInfo ConnectionInfo { get; set; }\n        internal bool InitializeCalled { get; set; }\n\n        // Inherited from RoleProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override string ApplicationName\n        {\n            get\n            {\n                if (InitializeCalled)\n                {\n                    throw new NotSupportedException();\n                }\n                else\n                {\n                    return PreviousProvider.ApplicationName;\n                }\n            }\n            set\n            {\n                if (InitializeCalled)\n                {\n                    throw new NotSupportedException();\n                }\n                else\n                {\n                    PreviousProvider.ApplicationName = value;\n                }\n            }\n        }\n\n        private void VerifyInitialized()\n        {\n            if (!InitializeCalled)\n            {\n                throw new InvalidOperationException(WebDataResources.Security_InitializeMustBeCalledFirst);\n            }\n        }\n\n        private IDatabase ConnectToDatabase()\n        {\n            return new DatabaseWrapper(ConnectionInfo.Connect());\n        }\n\n        internal void CreateTablesIfNeeded()\n        {\n            using (var db = ConnectToDatabase())\n            {\n                if (!SimpleMembershipProvider.CheckTableExists(db, RoleTableName))\n                {\n                    db.Execute(@\"CREATE TABLE \" + RoleTableName + @\" (\n                        RoleId                                  int                 NOT NULL PRIMARY KEY IDENTITY,\n                        RoleName                                nvarchar(256)       NOT NULL UNIQUE)\");\n\n                    db.Execute(@\"CREATE TABLE \" + UsersInRoleTableName + @\" (\n                        UserId                                  int                 NOT NULL,\n                        RoleId                                  int                 NOT NULL,\n                        PRIMARY KEY (UserId, RoleId),\n                        CONSTRAINT fk_UserId FOREIGN KEY (UserId) REFERENCES \" + SafeUserTableName + \"(\" + SafeUserIdColumn + @\"),\n                        CONSTRAINT fk_RoleId FOREIGN KEY (RoleId) REFERENCES \" + RoleTableName + \"(RoleId) )\");\n                }\n            }\n        }\n\n        private List<int> GetUserIdsFromNames(IDatabase db, string[] usernames)\n        {\n            List<int> userIds = new List<int>(usernames.Length);\n            foreach (string username in usernames)\n            {\n                int id = SimpleMembershipProvider.GetUserId(db, SafeUserTableName, SafeUserNameColumn, SafeUserIdColumn, CasingBehavior, username);\n                if (id == -1)\n                {\n                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, WebDataResources.Security_NoUserFound, username));\n                }\n                userIds.Add(id);\n            }\n            return userIds;\n        }\n\n        private static List<int> GetRoleIdsFromNames(IDatabase db, string[] roleNames)\n        {\n            List<int> roleIds = new List<int>(roleNames.Length);\n            foreach (string role in roleNames)\n            {\n                int id = FindRoleId(db, role);\n                if (id == -1)\n                {\n                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, WebDataResources.SimpleRoleProvider_NoRoleFound, role));\n                }\n                roleIds.Add(id);\n            }\n            return roleIds;\n        }\n\n        // Inherited from RoleProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override void AddUsersToRoles(string[] usernames, string[] roleNames)\n        {\n            if (!InitializeCalled)\n            {\n                PreviousProvider.AddUsersToRoles(usernames, roleNames);\n            }\n            else\n            {\n                using (var db = ConnectToDatabase())\n                {\n                    int userCount = usernames.Length;\n                    int roleCount = roleNames.Length;\n                    List<int> userIds = GetUserIdsFromNames(db, usernames);\n                    List<int> roleIds = GetRoleIdsFromNames(db, roleNames);\n\n                    // Generate a INSERT INTO for each userid/rowid combination, where userIds are the first params, and roleIds follow\n                    for (int uId = 0; uId < userCount; uId++)\n                    {\n                        for (int rId = 0; rId < roleCount; rId++)\n                        {\n                            if (IsUserInRole(usernames[uId], roleNames[rId]))\n                            {\n                                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, WebDataResources.SimpleRoleProvder_UserAlreadyInRole, usernames[uId], roleNames[rId]));\n                            }\n\n                            // REVIEW: is there a way to batch up these inserts?\n                            int rows = db.Execute(\"INSERT INTO \" + UsersInRoleTableName + \" VALUES (\" + userIds[uId] + \",\" + roleIds[rId] + \"); \");\n                            if (rows != 1)\n                            {\n                                throw new ProviderException(WebDataResources.Security_DbFailure);\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        // Inherited from RoleProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override void CreateRole(string roleName)\n        {\n            if (!InitializeCalled)\n            {\n                PreviousProvider.CreateRole(roleName);\n            }\n            else\n            {\n                using (var db = ConnectToDatabase())\n                {\n                    int roleId = FindRoleId(db, roleName);\n                    if (roleId != -1)\n                    {\n                        throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, WebDataResources.SimpleRoleProvider_RoleExists, roleName));\n                    }\n\n                    int rows = db.Execute(\"INSERT INTO \" + RoleTableName + \" (RoleName) VALUES (@0)\", roleName);\n                    if (rows != 1)\n                    {\n                        throw new ProviderException(WebDataResources.Security_DbFailure);\n                    }\n                }\n            }\n        }\n\n        // Inherited from RoleProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)\n        {\n            if (!InitializeCalled)\n            {\n                return PreviousProvider.DeleteRole(roleName, throwOnPopulatedRole);\n            }\n            using (var db = ConnectToDatabase())\n            {\n                int roleId = FindRoleId(db, roleName);\n                if (roleId == -1)\n                {\n                    return false;\n                }\n\n                if (throwOnPopulatedRole)\n                {\n                    int usersInRole = db.Query(@\"SELECT * FROM \" + UsersInRoleTableName + \" WHERE (RoleId = @0)\", roleId).Count();\n                    if (usersInRole > 0)\n                    {\n                        throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, WebDataResources.SimpleRoleProvder_RolePopulated, roleName));\n                    }\n                }\n                else\n                {\n                    // Delete any users in this role first\n                    db.Execute(@\"DELETE FROM \" + UsersInRoleTableName + \" WHERE (RoleId = @0)\", roleId);\n                }\n\n                int rows = db.Execute(@\"DELETE FROM \" + RoleTableName + \" WHERE (RoleId = @0)\", roleId);\n                return (rows == 1); // REVIEW: should this ever be > 1?\n            }\n        }\n\n        // Inherited from RoleProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override string[] FindUsersInRole(string roleName, string usernameToMatch)\n        {\n            if (!InitializeCalled)\n            {\n                return PreviousProvider.FindUsersInRole(roleName, usernameToMatch);\n            }\n            using (var db = ConnectToDatabase())\n            {\n                // REVIEW: Is there any way to directly get out a string[]?\n                List<dynamic> userNames = db.Query(@\"SELECT u.\" + SafeUserNameColumn + \" FROM \" + SafeUserTableName + \" u, \" + UsersInRoleTableName + \" ur, \" + RoleTableName + \" r Where (r.RoleName = @0 and ur.RoleId = r.RoleId and ur.UserId = u.\" + SafeUserIdColumn + \" and u.\" + SafeUserNameColumn + \" LIKE @1)\", new object[] { roleName, usernameToMatch }).ToList();\n                string[] users = new string[userNames.Count];\n                for (int i = 0; i < userNames.Count; i++)\n                {\n                    users[i] = (string)userNames[i][0];\n                }\n                return users;\n            }\n        }\n\n        // Inherited from RoleProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override string[] GetAllRoles()\n        {\n            if (!InitializeCalled)\n            {\n                return PreviousProvider.GetAllRoles();\n            }\n            using (var db = ConnectToDatabase())\n            {\n                return db.Query(@\"SELECT RoleName FROM \" + RoleTableName).Select<dynamic, string>(d => (string)d[0]).ToArray();\n            }\n        }\n\n        // Inherited from RoleProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override string[] GetRolesForUser(string username)\n        {\n            if (!InitializeCalled)\n            {\n                return PreviousProvider.GetRolesForUser(username);\n            }\n            using (var db = ConnectToDatabase())\n            {\n                int userId = SimpleMembershipProvider.GetUserId(db, SafeUserTableName, SafeUserNameColumn, SafeUserIdColumn, CasingBehavior, username);\n                if (userId == -1)\n                {\n                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, WebDataResources.Security_NoUserFound, username));\n                }\n\n                string query = @\"SELECT r.RoleName FROM \" + UsersInRoleTableName + \" u, \" + RoleTableName + \" r Where (u.UserId = @0 and u.RoleId = r.RoleId) GROUP BY RoleName\";\n                return db.Query(query, new object[] { userId }).Select<dynamic, string>(d => (string)d[0]).ToArray();\n            }\n        }\n\n        // Inherited from RoleProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override string[] GetUsersInRole(string roleName)\n        {\n            if (!InitializeCalled)\n            {\n                return PreviousProvider.GetUsersInRole(roleName);\n            }\n            using (var db = ConnectToDatabase())\n            {\n                string query = @\"SELECT u.\" + SafeUserNameColumn + \" FROM \" + SafeUserTableName + \" u, \" + UsersInRoleTableName + \" ur, \" + RoleTableName + \" r Where (r.RoleName = @0 and ur.RoleId = r.RoleId and ur.UserId = u.\" + SafeUserIdColumn + \")\";\n                return db.Query(query, new object[] { roleName }).Select<dynamic, string>(d => (string)d[0]).ToArray();\n            }\n        }\n\n        // Inherited from RoleProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override bool IsUserInRole(string username, string roleName)\n        {\n            if (!InitializeCalled)\n            {\n                return PreviousProvider.IsUserInRole(username, roleName);\n            }\n            using (var db = ConnectToDatabase())\n            {\n                var count = db.QuerySingle(\"SELECT COUNT(*) FROM \" + SafeUserTableName + \" u, \" + UsersInRoleTableName + \" ur, \" + RoleTableName + \" r Where (u.\" + SafeUserNameColumn + \" = @0 and r.RoleName = @1 and ur.RoleId = r.RoleId and ur.UserId = u.\" + SafeUserIdColumn + \")\", username, roleName);\n                return (count[0] == 1);\n            }\n        }\n\n        // Inherited from RoleProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)\n        {\n            if (!InitializeCalled)\n            {\n                PreviousProvider.RemoveUsersFromRoles(usernames, roleNames);\n            }\n            else\n            {\n                foreach (string rolename in roleNames)\n                {\n                    if (!RoleExists(rolename))\n                    {\n                        throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, WebDataResources.SimpleRoleProvider_NoRoleFound, rolename));\n                    }\n                }\n\n                foreach (string username in usernames)\n                {\n                    foreach (string rolename in roleNames)\n                    {\n                        if (!IsUserInRole(username, rolename))\n                        {\n                            throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, WebDataResources.SimpleRoleProvder_UserNotInRole, username, rolename));\n                        }\n                    }\n                }\n\n                using (var db = ConnectToDatabase())\n                {\n                    List<int> userIds = GetUserIdsFromNames(db, usernames);\n                    List<int> roleIds = GetRoleIdsFromNames(db, roleNames);\n\n                    foreach (int userId in userIds)\n                    {\n                        foreach (int roleId in roleIds)\n                        {\n                            // Review: Is there a way to do these all in one query?\n                            int rows = db.Execute(\"DELETE FROM \" + UsersInRoleTableName + \" WHERE UserId = \" + userId + \" and RoleId = \" + roleId);\n                            if (rows != 1)\n                            {\n                                throw new ProviderException(WebDataResources.Security_DbFailure);\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        private static int FindRoleId(IDatabase db, string roleName)\n        {\n            var result = db.QuerySingle(@\"SELECT RoleId FROM \" + RoleTableName + \" WHERE (RoleName = @0)\", roleName);\n            if (result == null)\n            {\n                return -1;\n            }\n            return (int)result[0];\n        }\n\n        // Inherited from RoleProvider ==> Forwarded to previous provider if this provider hasn't been initialized\n        public override bool RoleExists(string roleName)\n        {\n            if (!InitializeCalled)\n            {\n                return PreviousProvider.RoleExists(roleName);\n            }\n            using (var db = ConnectToDatabase())\n            {\n                return (FindRoleId(db, roleName) != -1);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/WebMatrix.WebData/WebMatrix.WebData.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{55A15F40-1435-4248-A7F2-2A146BB83586}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <RootNamespace>WebMatrix.WebData</RootNamespace>\n    <AssemblyName>WebMatrix.WebData</AssemblyName>\n    <DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>\n    <RunCodeAnalysis>$(CodeAnalysis)</RunCodeAnalysis>\n    <CodeAnalysisRuleSet>..\\Strict.ruleset</CodeAnalysisRuleSet>\n    <DefineConstants>$(DefineConstants);ASPNETWEBPAGES</DefineConstants>\n    <NoWarn>1591</NoWarn>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.configuration\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"System.Web.ApplicationServices\" />\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"System.Data\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\CommonAssemblyInfo.cs\">\n      <Link>Properties\\CommonAssemblyInfo.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\CommonResources.Designer.cs\">\n      <Link>Common\\CommonResources.Designer.cs</Link>\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>CommonResources.resx</DependentUpon>\n    </Compile>\n    <Compile Include=\"..\\GlobalSuppressions.cs\">\n      <Link>Common\\GlobalSuppressions.cs</Link>\n    </Compile>\n    <Compile Include=\"ConfigUtil.cs\" />\n    <Compile Include=\"DatabaseConnectionInfo.cs\" />\n    <Compile Include=\"DatabaseWrapper.cs\" />\n    <Compile Include=\"ExtendedMembershipProvider.cs\" />\n    <Compile Include=\"FormsAuthenticationSettings.cs\" />\n    <Compile Include=\"GlobalSuppressions.cs\" />\n    <Compile Include=\"IDatabase.cs\" />\n    <Compile Include=\"OAuthAccountData.cs\" />\n    <Compile Include=\"PreApplicationStartCode.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"Resources\\WebDataResources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>WebDataResources.resx</DependentUpon>\n    </Compile>\n    <Compile Include=\"SimpleMembershipProvider.cs\" />\n    <Compile Include=\"SimpleMembershipProviderCasingBehavior.cs\" />\n    <Compile Include=\"SimpleRoleProvider.cs\" />\n    <Compile Include=\"WebSecurity.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\System.Web.Helpers\\System.Web.Helpers.csproj\">\n      <Project>{9B7E3740-6161-4548-833C-4BBCA43B970E}</Project>\n      <Name>System.Web.Helpers</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.Razor\\System.Web.Razor.csproj\">\n      <Project>{8F18041B-9410-4C36-A9C5-067813DF5F31}</Project>\n      <Name>System.Web.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.WebPages.Razor\\System.Web.WebPages.Razor.csproj\">\n      <Project>{0939B11A-FE4E-4BA1-8AD6-D97741EE314F}</Project>\n      <Name>System.Web.WebPages.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.WebPages\\System.Web.WebPages.csproj\">\n      <Project>{76EFA9C5-8D7E-4FDF-B710-E20F8B6B00D2}</Project>\n      <Name>System.Web.WebPages</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\WebMatrix.Data\\WebMatrix.Data.csproj\">\n      <Project>{4D39BAAF-8A96-473E-AB79-C8A341885137}</Project>\n      <Name>WebMatrix.Data</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"..\\CommonResources.resx\">\n      <Link>Common\\CommonResources.resx</Link>\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>CommonResources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n    <EmbeddedResource Include=\"Resources\\WebDataResources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>WebDataResources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n  </ItemGroup>\n  <ItemGroup>\n    <CodeAnalysisDictionary Include=\"..\\CodeAnalysisDictionary.xml\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n</Project>"
  },
  {
    "path": "src/WebMatrix.WebData/WebSecurity.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Net;\nusing System.Web;\nusing System.Web.Routing;\nusing System.Web.Security;\nusing System.Web.WebPages;\nusing WebMatrix.WebData.Resources;\n\nnamespace WebMatrix.WebData\n{\n    public static class WebSecurity\n    {\n        public static readonly string EnableSimpleMembershipKey = \"enableSimpleMembership\";\n\n        /// <summary>\n        /// Gets a value indicating whether the <see cref=\"M:InitializeDatabaseConnection\"/> method has been initialized.\n        /// </summary>\n        /// <value>\n        ///   <c>true</c> if initialized; otherwise, <c>false</c>.\n        /// </value>\n        public static bool Initialized { get; private set; }\n\n        public static int CurrentUserId\n        {\n            get { return GetUserId(CurrentUserName); }\n        }\n\n        public static string CurrentUserName\n        {\n            get { return Context.User.Identity.Name; }\n        }\n\n        public static bool HasUserId\n        {\n            get { return CurrentUserId != -1; }\n        }\n\n        public static bool IsAuthenticated\n        {\n            get { return Request.IsAuthenticated; }\n        }\n\n        internal static HttpContextBase Context\n        {\n            get { return new HttpContextWrapper(HttpContext.Current); }\n        }\n\n        internal static HttpRequestBase Request\n        {\n            get { return Context.Request; }\n        }\n\n        internal static HttpResponseBase Response\n        {\n            get { return Context.Response; }\n        }\n\n        internal static void PreAppStartInit()\n        {\n            // Allow use of <add key=\"EnableSimpleMembershipKey\" value=\"false\" /> to disable registration of membership/role providers as default.\n            if (ConfigUtil.SimpleMembershipEnabled)\n            {\n                // called during PreAppStart, should also hook up the config for MembershipProviders?\n                // Replace the AspNetSqlMembershipProvider (which is the default that is registered in root web.config)\n                const string BuiltInMembershipProviderName = \"AspNetSqlMembershipProvider\";\n                var builtInMembership = Membership.Providers[BuiltInMembershipProviderName];\n                if (builtInMembership != null)\n                {\n                    var simpleMembership = CreateDefaultSimpleMembershipProvider(BuiltInMembershipProviderName, currentDefault: builtInMembership);\n                    Membership.Providers.Remove(BuiltInMembershipProviderName);\n                    Membership.Providers.Add(simpleMembership);\n                }\n\n                Roles.Enabled = true;\n                const string BuiltInRolesProviderName = \"AspNetSqlRoleProvider\";\n                var builtInRoles = Roles.Providers[BuiltInRolesProviderName];\n                if (builtInRoles != null)\n                {\n                    var simpleRoles = CreateDefaultSimpleRoleProvider(BuiltInRolesProviderName, currentDefault: builtInRoles);\n                    Roles.Providers.Remove(BuiltInRolesProviderName);\n                    Roles.Providers.Add(simpleRoles);\n                }\n            }\n        }\n\n        private static ExtendedMembershipProvider VerifyProvider()\n        {\n            ExtendedMembershipProvider provider = Membership.Provider as ExtendedMembershipProvider;\n            if (provider == null)\n            {\n                throw new InvalidOperationException(WebDataResources.Security_NoExtendedMembershipProvider);\n            }\n            provider.VerifyInitialized(); // Have the provider verify that it's initialized (only our SimpleMembershipProvider does anything here)\n            return provider;\n        }\n\n        public static void InitializeDatabaseConnection(string connectionStringName, string userTableName, string userIdColumn, string userNameColumn, bool autoCreateTables)\n        {\n            InitializeDatabaseConnection(\n                connectionStringName, \n                userTableName, \n                userIdColumn, \n                userNameColumn, \n                autoCreateTables, \n                SimpleMembershipProviderCasingBehavior.NormalizeCasing);\n        }\n\n        public static void InitializeDatabaseConnection(\n            string connectionStringName, \n            string userTableName, \n            string userIdColumn, \n            string userNameColumn, \n            bool autoCreateTables,\n            SimpleMembershipProviderCasingBehavior casingBehavior)\n        {\n            DatabaseConnectionInfo connect = new DatabaseConnectionInfo();\n            connect.ConnectionStringName = connectionStringName;\n            InitializeProviders(connect, userTableName, userIdColumn, userNameColumn, autoCreateTables, casingBehavior);\n        }\n\n        public static void InitializeDatabaseConnection(\n            string connectionString, \n            string providerName, \n            string userTableName, \n            string userIdColumn, \n            string userNameColumn, \n            bool autoCreateTables)\n        {\n            InitializeDatabaseConnection(\n                connectionString, \n                providerName, \n                userTableName, \n                userIdColumn, \n                userNameColumn, \n                autoCreateTables, \n                SimpleMembershipProviderCasingBehavior.NormalizeCasing);\n        }\n\n        public static void InitializeDatabaseConnection(\n            string connectionString, \n            string providerName, \n            string userTableName, \n            string userIdColumn, \n            string userNameColumn,\n            bool autoCreateTables,\n            SimpleMembershipProviderCasingBehavior casingBehavior)\n        {\n            DatabaseConnectionInfo connect = new DatabaseConnectionInfo();\n            connect.ConnectionString = connectionString;\n            connect.ProviderName = providerName;\n            InitializeProviders(connect, userTableName, userIdColumn, userNameColumn, autoCreateTables, casingBehavior);\n        }\n\n        private static void InitializeProviders(\n            DatabaseConnectionInfo connect, \n            string userTableName, \n            string userIdColumn, \n            string userNameColumn, \n            bool autoCreateTables, \n            SimpleMembershipProviderCasingBehavior casingBehavior)\n        {\n            SimpleMembershipProvider simpleMembership = Membership.Provider as SimpleMembershipProvider;\n            if (simpleMembership != null)\n            {\n                InitializeMembershipProvider(simpleMembership, connect, userTableName, userIdColumn, userNameColumn, autoCreateTables, casingBehavior);\n            }\n\n            SimpleRoleProvider simpleRoles = Roles.Provider as SimpleRoleProvider;\n            if (simpleRoles != null)\n            {\n                InitializeRoleProvider(simpleRoles, connect, userTableName, userIdColumn, userNameColumn, autoCreateTables, casingBehavior);\n            }\n\n            Initialized = true;\n        }\n\n        internal static void InitializeMembershipProvider(\n            SimpleMembershipProvider simpleMembership, \n            DatabaseConnectionInfo connect, \n            string userTableName, \n            string userIdColumn, \n            string userNameColumn, \n            bool createTables,\n            SimpleMembershipProviderCasingBehavior casingBehavior)\n        {\n            if (simpleMembership.InitializeCalled)\n            {\n                throw new InvalidOperationException(WebDataResources.Security_InitializeAlreadyCalled);\n            }\n\n            simpleMembership.CasingBehavior = casingBehavior;\n            simpleMembership.ConnectionInfo = connect;\n            simpleMembership.UserIdColumn = userIdColumn;\n            simpleMembership.UserNameColumn = userNameColumn;\n            simpleMembership.UserTableName = userTableName;\n            if (createTables)\n            {\n                simpleMembership.CreateTablesIfNeeded();\n            }\n            else\n            {\n                // We want to validate the user table if we aren't creating them\n                simpleMembership.ValidateUserTable();\n            }\n            simpleMembership.InitializeCalled = true;\n        }\n\n        internal static void InitializeRoleProvider(\n            SimpleRoleProvider simpleRoles, \n            DatabaseConnectionInfo connect, \n            string userTableName, \n            string userIdColumn, \n            string userNameColumn, \n            bool createTables,\n            SimpleMembershipProviderCasingBehavior casingBehavior)\n        {\n            if (simpleRoles.InitializeCalled)\n            {\n                throw new InvalidOperationException(WebDataResources.Security_InitializeAlreadyCalled);\n            }\n\n            simpleRoles.CasingBehavior = casingBehavior;\n            simpleRoles.ConnectionInfo = connect;\n            simpleRoles.UserTableName = userTableName;\n            simpleRoles.UserIdColumn = userIdColumn;\n            simpleRoles.UserNameColumn = userNameColumn;\n\n            if (createTables)\n            {\n                simpleRoles.CreateTablesIfNeeded();\n            }\n            simpleRoles.InitializeCalled = true;\n        }\n\n        private static SimpleMembershipProvider CreateDefaultSimpleMembershipProvider(string name, MembershipProvider currentDefault)\n        {\n            var membership = new SimpleMembershipProvider(previousProvider: currentDefault);\n            NameValueCollection config = new NameValueCollection();\n            membership.Initialize(name, config);\n            return membership;\n        }\n\n        private static SimpleRoleProvider CreateDefaultSimpleRoleProvider(string name, RoleProvider currentDefault)\n        {\n            var roleProvider = new SimpleRoleProvider(previousProvider: currentDefault);\n            NameValueCollection config = new NameValueCollection();\n            roleProvider.Initialize(name, config);\n            return roleProvider;\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1726:UsePreferredTerms\", MessageId = \"Login\", Justification = \"Login is used more consistently in ASP.Net\")]\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"This is a helper class, and we are not removing optional parameters from methods in helper classes\")]\n        public static bool Login(string userName, string password, bool persistCookie = false)\n        {\n            VerifyProvider();\n            bool success = Membership.ValidateUser(userName, password);\n            if (success)\n            {\n                FormsAuthentication.SetAuthCookie(userName, persistCookie);\n            }\n            return success;\n        }\n\n        [SuppressMessage(\"Microsoft.Naming\", \"CA1726:UsePreferredTerms\", MessageId = \"Logout\", Justification = \"Login is used more consistently in ASP.Net\")]\n        public static void Logout()\n        {\n            VerifyProvider();\n            FormsAuthentication.SignOut();\n        }\n\n        public static bool ChangePassword(string userName, string currentPassword, string newPassword)\n        {\n            VerifyProvider();\n            bool success = false;\n            try\n            {\n                var currentUser = Membership.GetUser(userName, true /* userIsOnline */);\n                success = currentUser.ChangePassword(currentPassword, newPassword);\n            }\n            catch (ArgumentException)\n            {\n                // An argument exception is thrown if the new password does not meet the provider's requirements\n            }\n\n            return success;\n        }\n\n        public static bool ConfirmAccount(string accountConfirmationToken)\n        {\n            ExtendedMembershipProvider provider = VerifyProvider();\n            Debug.Assert(provider != null); // VerifyProvider checks this\n            return provider.ConfirmAccount(accountConfirmationToken);\n        }\n\n        public static bool ConfirmAccount(string userName, string accountConfirmationToken)\n        {\n            ExtendedMembershipProvider provider = VerifyProvider();\n            Debug.Assert(provider != null); // VerifyProvider checks this\n            return provider.ConfirmAccount(userName, accountConfirmationToken);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"This is a helper class, and we are not removing optional parameters from methods in helper classes\")]\n        public static string CreateAccount(string userName, string password, bool requireConfirmationToken = false)\n        {\n            ExtendedMembershipProvider provider = VerifyProvider();\n            Debug.Assert(provider != null); // VerifyProvider checks this\n\n            return provider.CreateAccount(userName, password, requireConfirmationToken);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"This is a helper class, and we are not removing optional parameters from methods in helper classes\")]\n        public static string CreateUserAndAccount(string userName, string password, object propertyValues = null, bool requireConfirmationToken = false)\n        {\n            ExtendedMembershipProvider provider = VerifyProvider();\n            Debug.Assert(provider != null); // VerifyProvider checks this\n\n            IDictionary<string, object> values = propertyValues as RouteValueDictionary;\n            if (values == null && propertyValues != null)\n            {\n                var propertyValuesAsDictionary = propertyValues as IDictionary<string, object>;\n                if (propertyValuesAsDictionary != null)\n                {\n                    values = new RouteValueDictionary(propertyValuesAsDictionary);\n                }\n                else\n                {\n                    values = new RouteValueDictionary(propertyValues);\n                }\n            }\n\n            return provider.CreateUserAndAccount(userName, password, requireConfirmationToken, values);\n        }\n\n        [SuppressMessage(\"Microsoft.Design\", \"CA1026:DefaultParametersShouldNotBeUsed\", Justification = \"This is a helper class, and we are not removing optional parameters from methods in helper classes\")]\n        public static string GeneratePasswordResetToken(string userName, int tokenExpirationInMinutesFromNow = 1440)\n        {\n            ExtendedMembershipProvider provider = VerifyProvider();\n            Debug.Assert(provider != null); // VerifyProvider checks this\n\n            return provider.GeneratePasswordResetToken(userName, tokenExpirationInMinutesFromNow);\n        }\n\n        public static bool UserExists(string userName)\n        {\n            VerifyProvider();\n            return Membership.GetUser(userName) != null;\n        }\n\n        public static int GetUserId(string userName)\n        {\n            VerifyProvider();\n            MembershipUser user = Membership.GetUser(userName);\n            if (user == null)\n            {\n                return -1;\n            }\n\n            // REVIEW: This cast is breaking the abstraction for the membershipprovider, we basically assume that userids are ints\n            return (int)user.ProviderUserKey;\n        }\n\n        public static int GetUserIdFromPasswordResetToken(string token)\n        {\n            ExtendedMembershipProvider provider = VerifyProvider();\n            Debug.Assert(provider != null); // VerifyProvider checks this\n\n            return provider.GetUserIdFromPasswordResetToken(token);\n        }\n\n        public static bool IsCurrentUser(string userName)\n        {\n            VerifyProvider();\n            return String.Equals(CurrentUserName, userName, StringComparison.OrdinalIgnoreCase);\n        }\n\n        public static bool IsConfirmed(string userName)\n        {\n            ExtendedMembershipProvider provider = VerifyProvider();\n            Debug.Assert(provider != null); // VerifyProvider checks this\n\n            return provider.IsConfirmed(userName);\n        }\n\n        // Make sure the logged on user is same as the one specified by the id\n        private static bool IsUserLoggedOn(int userId)\n        {\n            VerifyProvider();\n            return CurrentUserId == userId;\n        }\n\n        // Make sure the user was authenticated\n        public static void RequireAuthenticatedUser()\n        {\n            VerifyProvider();\n            var user = Context.User;\n            if (user == null || !user.Identity.IsAuthenticated)\n            {\n                Response.SetStatus(HttpStatusCode.Unauthorized);\n            }\n        }\n\n        // Make sure the user was authenticated\n        public static void RequireUser(int userId)\n        {\n            VerifyProvider();\n            if (!IsUserLoggedOn(userId))\n            {\n                Response.SetStatus(HttpStatusCode.Unauthorized);\n            }\n        }\n\n        public static void RequireUser(string userName)\n        {\n            VerifyProvider();\n            if (!String.Equals(CurrentUserName, userName, StringComparison.OrdinalIgnoreCase))\n            {\n                Response.SetStatus(HttpStatusCode.Unauthorized);\n            }\n        }\n\n        public static void RequireRoles(params string[] roles)\n        {\n            VerifyProvider();\n            foreach (string role in roles)\n            {\n                if (!Roles.IsUserInRole(CurrentUserName, role))\n                {\n                    Response.SetStatus(HttpStatusCode.Unauthorized);\n                    return;\n                }\n            }\n        }\n\n        public static bool ResetPassword(string passwordResetToken, string newPassword)\n        {\n            ExtendedMembershipProvider provider = VerifyProvider();\n            Debug.Assert(provider != null); // VerifyProvider checks this\n            return provider.ResetPasswordWithToken(passwordResetToken, newPassword);\n        }\n\n        public static bool IsAccountLockedOut(string userName, int allowedPasswordAttempts, int intervalInSeconds)\n        {\n            VerifyProvider();\n            return IsAccountLockedOut(userName, allowedPasswordAttempts, TimeSpan.FromSeconds(intervalInSeconds));\n        }\n\n        public static bool IsAccountLockedOut(string userName, int allowedPasswordAttempts, TimeSpan interval)\n        {\n            ExtendedMembershipProvider provider = VerifyProvider();\n            Debug.Assert(provider != null); // VerifyProvider checks this\n\n            return IsAccountLockedOutInternal(provider, userName, allowedPasswordAttempts, interval);\n        }\n\n        internal static bool IsAccountLockedOutInternal(ExtendedMembershipProvider provider, string userName, int allowedPasswordAttempts, TimeSpan interval)\n        {\n            return (provider.GetUser(userName, false) != null &&\n                    provider.GetPasswordFailuresSinceLastSuccess(userName) > allowedPasswordAttempts &&\n                    provider.GetLastPasswordFailureDate(userName).Add(interval) > DateTime.UtcNow);\n        }\n\n        public static int GetPasswordFailuresSinceLastSuccess(string userName)\n        {\n            ExtendedMembershipProvider provider = VerifyProvider();\n            Debug.Assert(provider != null); // VerifyProvider checks this\n\n            return provider.GetPasswordFailuresSinceLastSuccess(userName);\n        }\n\n        public static DateTime GetCreateDate(string userName)\n        {\n            ExtendedMembershipProvider provider = VerifyProvider();\n            Debug.Assert(provider != null); // VerifyProvider checks this\n\n            return provider.GetCreateDate(userName);\n        }\n\n        public static DateTime GetPasswordChangedDate(string userName)\n        {\n            ExtendedMembershipProvider provider = VerifyProvider();\n            Debug.Assert(provider != null); // VerifyProvider checks this\n\n            return provider.GetPasswordChangedDate(userName);\n        }\n\n        public static DateTime GetLastPasswordFailureDate(string userName)\n        {\n            ExtendedMembershipProvider provider = VerifyProvider();\n            Debug.Assert(provider != null); // VerifyProvider checks this\n\n            return provider.GetLastPasswordFailureDate(userName);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Common/AttributeListTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing Microsoft.TestCommon;\n\nnamespace System.ComponentModel\n{\n    public class AttributeListTest\n    {\n        private readonly Attribute[] _testAttributes;\n        private readonly AttributeCollection _collection;\n        private readonly AttributeList _list;\n\n        public AttributeListTest()\n        {\n            _testAttributes = new Attribute[] { new TestAttribute(), new DerivedAttribute(), new DerivedDerivedAttribute() };\n            _collection = new AttributeCollection(_testAttributes);\n            _list = new AttributeList(_collection);\n        }\n\n        [Fact]\n        public void AttributeListCountMatchesWrapped()\n        {\n            Assert.Equal(_collection.Count, _list.Count);\n        }\n\n        [Fact]\n        public void AttributeListIsReadOnlyTrue()\n        {\n            Assert.True(_list.IsReadOnly);\n        }\n\n        [Fact]\n        public void AttributeListIndexerMatchesWrapped()\n        {\n            Assert.Equal(_collection[1], _list[1]);\n        }\n\n        [Fact]\n        public void AttributeListAddThrows()\n        {\n            Assert.Throws<NotSupportedException>(() => _list.Add(null));\n        }\n\n        [Fact]\n        public void AttributeListClearThrows()\n        {\n            Assert.Throws<NotSupportedException>(() => _list.Clear());\n        }\n\n        [Fact]\n        public void AttributeListContainsWrappedTrue()\n        {\n            Attribute presentAttribute = _collection[2];\n            Assert.Contains(presentAttribute, _list);\n        }\n\n        [Fact]\n        public void AttributeListContainsMissingFalse()\n        {\n            Attribute missingAttribute = new MissingAttribute();\n            Assert.DoesNotContain(missingAttribute, _list);\n        }\n\n        [Fact]\n        public void AttributeListCopyToResultsEqual()\n        {\n            Attribute[] arrayCopy = new Attribute[3];\n            _list.CopyTo(arrayCopy, 0);\n            Assert.Equal(_list, arrayCopy);\n        }\n\n        [Fact]\n        public void AttributeListIndexOfMatchesIndexer()\n        {\n            Assert.Equal(1, _list.IndexOf(_list[1]));\n        }\n\n        [Fact]\n        public void AttributeListRemoveAtThrows()\n        {\n            Assert.Throws<NotSupportedException>(() => _list.RemoveAt(0));\n            Assert.Throws<NotSupportedException>(() => ((ICollection<Attribute>)_list).Remove(_list[0]));\n        }\n\n        [Fact]\n        public void AttributeListEnumerationMatchesWrapped()\n        {\n            int i = 0;\n            foreach (Attribute attribute in _list)\n            {\n                Assert.Equal(_collection[i], attribute);\n                i++;\n            }\n            Assert.Equal(_collection.Count, i);\n\n            i = 0;\n            IEnumerable asEumerable = _list as IEnumerable;\n            foreach (Attribute attribute in asEumerable)\n            {\n                Assert.Equal(_collection[i], attribute);\n                i++;\n            }\n            Assert.Equal(_collection.Count, i);\n        }\n\n        private class TestAttribute : Attribute\n        {\n            public TestAttribute() { }\n        }\n\n        private class DerivedAttribute: TestAttribute\n        {\n            public DerivedAttribute() { }\n        }\n\n        private class DerivedDerivedAttribute : DerivedAttribute\n        {\n            public DerivedDerivedAttribute() { }\n        }\n\n        private class MissingAttribute : Attribute\n        {\n            public MissingAttribute() { }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Common/CollectionExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Collections.Generic\n{\n    public class CollectionExtensionsTest\n    {\n        [Fact]\n        public void AppendAndReallocateEmpty_ReturnsOne()\n        {\n            string[] empty = new string[0];\n\n            string[] emptyAppended = empty.AppendAndReallocate(\"AppendedEmpty\");\n\n            string singleAppended = Assert.Single(emptyAppended);\n            Assert.Equal(\"AppendedEmpty\", singleAppended);\n        }\n\n        [Fact]\n        public void AppendAndReallocateOne_ReturnsTwo()\n        {\n            string[] one = new string[] { \"One\" };\n\n            string[] oneAppended = one.AppendAndReallocate(\"AppendedOne\");\n\n            Assert.Equal(2, oneAppended.Length);\n            Assert.Equal(\"One\", oneAppended[0]);\n            Assert.Equal(\"AppendedOne\", oneAppended[1]);\n        }\n\n        [Fact]\n        public void AsArray_Array_ReturnsSameInstance()\n        {\n            object[] array = new object[] { new object(), new object() };\n\n            object[] arrayAsArray = ((IEnumerable<object>)array).AsArray();\n\n            Assert.Same(array, arrayAsArray);\n        }\n\n        [Fact]\n        public void AsArray_Enumerable_Copies()\n        {\n            IList<object> list = new List<object>() { new object(), new object() };\n            object[] listToArray = list.ToArray();\n\n            object[] listAsArray = ((IEnumerable<object>)list).AsArray();\n\n            Assert.Equal(listToArray, listAsArray);\n        }\n\n        [Fact]\n        public void AsCollection_Collection_ReturnsSameInstance()\n        {\n            Collection<object> collection = new Collection<object>() { new object(), new object() };\n\n            Collection<object> collectionAsCollection = ((IEnumerable<object>)collection).AsCollection();\n\n            Assert.Same(collection, collectionAsCollection);\n        }\n\n        [Fact]\n        public void AsCollection_Enumerable_Copies()\n        {\n            IEnumerable<object> enumerable = new LinkedList<object>(new object[] { new object(), new object() });\n\n            Collection<object> enumerableAsCollection = ((IEnumerable<object>)enumerable).AsCollection();\n\n            Assert.Equal(enumerable, ((IEnumerable<object>)enumerableAsCollection));\n        }\n\n        [Fact]\n        public void AsCollection_IList_Wraps()\n        {\n            IList<object> list = new List<object>() { new object(), new object() };\n\n            Collection<object> listAsCollection = list.AsCollection();\n            list.Add(new object());\n\n            Assert.Equal(list, listAsCollection.ToList());\n        }\n\n        [Fact]\n        public void AsIList_IList_ReturnsSameInstance()\n        {\n            List<object> list = new List<object> { new object(), new object() };\n\n            IList<object> listAsIList = ((IEnumerable<object>)list).AsIList();\n\n            Assert.Same(list, listAsIList);\n        }\n\n        [Fact]\n        public void AsIList_Enumerable_Copies()\n        {\n            LinkedList<object> enumerable = new LinkedList<object>();\n            enumerable.AddLast(new object());\n            enumerable.AddLast(new object());\n            List<object> expected = enumerable.ToList();\n\n            IList<object> enumerableAsIList = ((IEnumerable<object>)enumerable).AsIList();\n\n            Assert.Equal(expected, enumerableAsIList);\n            Assert.NotSame(expected, enumerableAsIList);\n        }\n\n        [Fact]\n        public void AsList_List_ReturnsSameInstance()\n        {\n            List<object> list = new List<object> { new object(), new object() };\n\n            List<object> listAsList = ((IEnumerable<object>)list).AsList();\n\n            Assert.Same(list, listAsList);\n        }\n\n        [Fact]\n        public void AsList_Enumerable_Copies()\n        {\n            List<object> list = new List<object>() { new object(), new object() };\n            object[] array = list.ToArray();\n\n            List<object> arrayAsList = ((IEnumerable<object>)array).AsList();\n\n            Assert.Equal(list, arrayAsList);\n            Assert.NotSame(list, arrayAsList);\n            Assert.NotSame(array, arrayAsList);\n        }\n\n        [Fact]\n        public void AsList_ListWrapperCollection_ReturnsSameInstance()\n        {\n            List<object> list = new List<object> { new object(), new object() };\n            ListWrapperCollection<object> listWrapper = new ListWrapperCollection<object>(list);\n\n            List<object> listWrapperAsList = ((IEnumerable<object>)listWrapper).AsList();\n\n            Assert.Same(list, listWrapperAsList);\n        }\n\n        [Fact]\n        void RemoveFromTwoElementsAtEnd_NoChange()\n        {\n            List<object> list = new List<object>() { new object(), new object() };\n            List<object> listExpected = new List<object>(list);\n            list.RemoveFrom(2);\n            Assert.Equal(listExpected, list);\n        }\n\n        [Fact]\n        void RemoveFromTwoElementsMiddle_ToOne()\n        {\n            List<object> list = new List<object>() { new object(), new object() };\n            List<object> listExpected = new List<object>() { list[0] };\n            list.RemoveFrom(1);\n            Assert.Equal(listExpected, list);\n        }\n\n        [Fact]\n        void RemoveFromTwoElementsStart_ToEmpty()\n        {\n            List<object> list = new List<object>() { new object(), new object() };\n            List<object> listExpected = new List<object>();\n            list.RemoveFrom(0);\n            Assert.Equal(listExpected, list);\n        }\n\n        [Fact]\n        void SingleDefaultOrErrorIListEmptyReturnsNull()\n        {\n            IList<object> empty = new List<object>();\n            object errorArgument = new object();\n            Action<object> errorAction = (object argument) =>\n            {\n                throw new InvalidOperationException();\n            };\n\n            Assert.Null(empty.SingleDefaultOrError(errorAction, errorArgument));\n        }\n\n        [Fact]\n        public void SingleDefaultOrErrorIListSingleReturns()\n        {\n            IList<object> single = new List<object>() { new object() };\n            object errorArgument = new object();\n            Action<object> errorAction = (object argument) =>\n            {\n                throw new InvalidOperationException();\n            };\n\n            Assert.Equal(single[0], single.SingleDefaultOrError(errorAction, errorArgument));\n        }\n\n        [Fact]\n        public void SingleDefaultOrErrorIListMultipleThrows()\n        {\n            IList<object> multiple = new List<object>() { new object(), new object() };\n            object errorArgument = new object();\n            Action<object> errorAction = (object argument) =>\n            {\n                Assert.Equal(errorArgument, argument);\n                throw new InvalidOperationException();\n            };\n\n            Assert.Throws<InvalidOperationException>(() => multiple.SingleDefaultOrError(errorAction, errorArgument));\n        }\n\n        [Fact]\n        public void SingleOfTypeDefaultOrErrorIListNoMatchReturnsNull()\n        {\n            IList<object> noMatch = new List<object>() { new object(), new object() };\n            object errorArgument = new object();\n            Action<object> errorAction = (object argument) =>\n            {\n                throw new InvalidOperationException();\n            };\n\n            Assert.Null(noMatch.SingleOfTypeDefaultOrError<object, string, object>(errorAction, errorArgument));\n        }\n\n        [Fact]\n        public void SingleOfTypeDefaultOrErrorIListOneMatchReturns()\n        {\n            IList<object> singleMatch = new List<object>() { new object(), \"Match\", new object() };\n            object errorArgument = new object();\n            Action<object> errorAction = (object argument) =>\n            {\n                throw new InvalidOperationException();\n            };\n\n            Assert.Equal(\"Match\", singleMatch.SingleOfTypeDefaultOrError<object, string, object>(errorAction, errorArgument));\n        }\n\n        [Fact]\n        public void SingleOfTypeDefaultOrErrorIListMultipleMatchesThrows()\n        {\n            IList<object> multipleMatch = new List<object>() { new object(), \"Match1\", new object(), \"Match2\" };\n            object errorArgument = new object();\n            Action<object> errorAction = (object argument) =>\n            {\n                Assert.Equal(errorArgument, argument);\n                throw new InvalidOperationException();\n            };\n\n            Assert.Throws<InvalidOperationException>(() => multipleMatch.SingleOfTypeDefaultOrError<object, string, object>(errorAction, errorArgument));\n        }\n\n        [Fact]\n        public void ToArrayWithoutNullsICollectionNoNullsCopies()\n        {\n            ICollection<object> noNulls = new object[] { new object(), new object() };\n\n            object[] noNullsresult = noNulls.ToArrayWithoutNulls();\n\n            Assert.Equal(noNulls, noNullsresult);\n        }\n\n        [Fact]\n        public void ToArrayWithoutNullsICollectionHasNullsRemovesNulls()\n        {\n            IList<object> hasNulls = new List<object>() { new object(), null, new object() };\n\n            object[] hasNullsResult = ((ICollection<object>)hasNulls).ToArrayWithoutNulls();\n\n            Assert.Equal(2, hasNullsResult.Length);\n            Assert.Equal(hasNulls[0], hasNullsResult[0]);\n            Assert.Equal(hasNulls[2], hasNullsResult[1]);\n        }\n\n        [Fact]\n        public void ToDictionaryFastArray2Element()\n        {\n            string[] input = new string[] {\"AA\", \"BB\"};\n            var expectedOutput = new Dictionary<string, string>() { { \"A\", \"AA\"}, {\"B\", \"BB\"}};\n            Func<string, string> keySelector = (string value) => value.Substring(1);\n\n            var result = input.ToDictionaryFast(keySelector, StringComparer.OrdinalIgnoreCase);\n\n            Assert.Equal(expectedOutput, result);\n            Assert.Equal(StringComparer.OrdinalIgnoreCase, result.Comparer);\n        }\n\n        [Fact]\n        public void ToDictionaryFastIListList2Element()\n        {\n            string[] input = new string[] {\"AA\", \"BB\"};\n            var expectedOutput = new Dictionary<string, string>() { { \"A\", \"AA\"}, {\"B\", \"BB\"}};\n            Func<string, string> keySelector = (string value) => value.Substring(1);\n            List<string> listInput = new List<string>(input);\n\n            var listResult = listInput.ToDictionaryFast(keySelector, StringComparer.OrdinalIgnoreCase);\n\n            Assert.Equal(expectedOutput, listResult);\n            Assert.Equal(StringComparer.OrdinalIgnoreCase, listResult.Comparer);\n        }\n\n        [Fact]\n        public void ToDictionaryFastIListArray2Element()\n        {\n            string[] input = new string[] { \"AA\", \"BB\" };\n            var expectedOutput = new Dictionary<string, string>() { { \"A\", \"AA\" }, { \"B\", \"BB\" } };\n            Func<string, string> keySelector = (string value) => value.Substring(1);\n            IList<string> arrayAsList = input;\n\n            var arrayResult = arrayAsList.ToDictionaryFast(keySelector, StringComparer.OrdinalIgnoreCase);\n\n            Assert.Equal(expectedOutput, arrayResult);\n            Assert.Equal(StringComparer.OrdinalIgnoreCase, arrayResult.Comparer);\n        }\n\n        [Fact]\n        public void ToDictionaryFastIEnumerableArray2Element()\n        {\n            string[] input = new string[] {\"AA\", \"BB\"};\n            var expectedOutput = new Dictionary<string, string>() { { \"A\", \"AA\"}, {\"B\", \"BB\"}};\n            Func<string, string> keySelector = (string value) => value.Substring(1);\n\n            var arrayResult = ((IEnumerable<string>)input).ToDictionaryFast(keySelector, StringComparer.OrdinalIgnoreCase);\n\n            Assert.Equal(expectedOutput, arrayResult);\n            Assert.Equal(StringComparer.OrdinalIgnoreCase, arrayResult.Comparer);\n        }\n\n        [Fact]\n        public void ToDictionaryFastIEnumerableList2Element()\n        {\n            string[] input = new string[] { \"AA\", \"BB\" };\n            var expectedOutput = new Dictionary<string, string>() { { \"A\", \"AA\" }, { \"B\", \"BB\" } };\n            Func<string, string> keySelector = (string value) => value.Substring(1);\n            List<string> listInput = new List<string>(input);\n\n            var listResult = ((IEnumerable<string>)listInput).ToDictionaryFast(keySelector, StringComparer.OrdinalIgnoreCase);\n\n            Assert.Equal(expectedOutput, listResult);\n            Assert.Equal(StringComparer.OrdinalIgnoreCase, listResult.Comparer);\n        }\n\n        [Fact]\n        public void ToDictionaryFastIEnumerableLinkedList2Element()\n        {\n            string[] input = new string[] { \"AA\", \"BB\" };\n            var expectedOutput = new Dictionary<string, string>() { { \"A\", \"AA\" }, { \"B\", \"BB\" } };\n            Func<string, string> keySelector = (string value) => value.Substring(1);\n            LinkedList<string> linkedListInput = new LinkedList<string>(input);\n\n            var enumerableResult = ((IEnumerable<string>)linkedListInput).ToDictionaryFast(keySelector, StringComparer.OrdinalIgnoreCase);\n\n            Assert.Equal(expectedOutput, enumerableResult);\n            Assert.Equal(StringComparer.OrdinalIgnoreCase, enumerableResult.Comparer);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Common/DictionaryExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net;\nusing Microsoft.TestCommon;\n\nnamespace System.Collections.Generic\n{\n    public class DictionaryExtensionsTest\n    {\n        public static TheoryDataSet<object> DictionaryValues\n        {\n            get\n            {\n                return new TheoryDataSet<object>\n                {\n                    \"test\",\n                    new string[] { \"A\", \"B\", \"C\" },\n                    8,\n                    new List<int> {1, 2, 3},\n                    1D,\n                    (IEnumerable<double>)new List<double> { 1D, 2D, 3D },\n                    new Uri(\"http://some.host\"),\n                    Guid.NewGuid(),\n                    HttpStatusCode.NotImplemented,\n                    new HttpStatusCode[] { HttpStatusCode.Accepted, HttpStatusCode.Ambiguous, HttpStatusCode.BadGateway }\n                };\n            }\n        }\n\n        [Fact]\n        public void IsCorrectType()\n        {\n            Assert.Type.HasProperties(typeof(DictionaryExtensions), TypeAssert.TypeProperties.IsStatic | TypeAssert.TypeProperties.IsClass);\n        }\n\n        [Fact]\n        public void RemoveFromDictionary_Args0_EvensRemoved()\n        {\n            Dictionary<object, int> dictionary = new Dictionary<object, int>();\n            object object1 = new object();\n            object object2 = new object();\n            object object3 = new object();\n            object object4 = new object();\n            dictionary.Add(object1, 1);\n            dictionary.Add(object2, 2);\n            dictionary.Add(object3, 3);\n            dictionary.Add(object4, 4);\n\n            Func<KeyValuePair<object, int>, bool> removeAction = (KeyValuePair<object, int> entry) =>\n            {\n                // remove even values\n                return (entry.Value % 2) == 0;\n            };\n            dictionary.RemoveFromDictionary(removeAction);\n\n            Assert.Equal(2, dictionary.Count);\n            Assert.True(dictionary.ContainsKey(object1));\n            Assert.False(dictionary.ContainsKey(object2));\n            Assert.True(dictionary.ContainsKey(object3));\n            Assert.False(dictionary.ContainsKey(object4));\n        }\n\n        [Fact]\n        public void RemoveFromDictionary_Args1_EvensRemoved()\n        {\n            Dictionary<object, int> dictionary = new Dictionary<object, int>();\n            object object1 = new object();\n            object object2 = new object();\n            object object3 = new object();\n            object object4 = new object();\n            dictionary.Add(object1, 1);\n            dictionary.Add(object2, 2);\n            dictionary.Add(object3, 3);\n            dictionary.Add(object4, 4);\n            object expectedArgument = new object();\n\n            Func<KeyValuePair<object, int>, object, bool> removeAction = (KeyValuePair<object, int> entry, object arg) =>\n            {\n                Assert.Equal(expectedArgument, arg);\n                // remove even values\n                return (entry.Value % 2) == 0;\n            };\n            dictionary.RemoveFromDictionary(removeAction, expectedArgument);\n\n            Assert.Equal(2, dictionary.Count);\n            Assert.True(dictionary.ContainsKey(object1));\n            Assert.False(dictionary.ContainsKey(object2));\n            Assert.True(dictionary.ContainsKey(object3));\n            Assert.False(dictionary.ContainsKey(object4));\n        }\n\n        [Fact]\n        public void TryGetValueThrowsOnNullKey()\n        {\n            IDictionary<string, object> dict = new Dictionary<string, object>();\n            string value;\n            Assert.ThrowsArgumentNull(() => dict.TryGetValue<string>(null, out value), \"key\");\n        }\n\n        [Fact]\n        public void TryGetValueReturnsFalse()\n        {\n            // Arrange\n            IDictionary<string, object> dict = new Dictionary<string, object>();\n\n            // Act\n            string resultValue = null;\n            bool result = dict.TryGetValue(\"notfound\", out resultValue);\n\n            // Assert\n            Assert.False(result);\n            Assert.Null(resultValue);\n        }\n\n        [Theory]\n        [PropertyData(\"DictionaryValues\")]\n        public void TryGetValueReturnsTrue<T>(T value)\n        {\n            // Arrange\n            IDictionary<string, object> dict = new Dictionary<string, object>()\n            {\n                { \"key\", value }\n            };\n\n\n            // Act\n            T resultValue;\n            bool result = DictionaryExtensions.TryGetValue(dict, \"key\", out resultValue);\n\n            // Assert\n            Assert.True(result);\n            Assert.Equal(typeof(T), resultValue.GetType());\n            Assert.Equal(value, resultValue);\n        }\n\n        [Fact]\n        public void FindKeysWithPrefixRecognizesRootChilden()\n        {\n            // Arrange\n            IDictionary<string, int> dict = new Dictionary<string, int>()\n            {\n                { \"[0]\", 1 },\n                { \"Name\", 2 },\n                { \"Address.Street\", 3 },\n                { \"\", 4 }\n            };\n\n            // Act\n            List<int> results = DictionaryExtensions.FindKeysWithPrefix<int>(dict, \"\").Select(kvp => kvp.Value).ToList();\n\n            // Assert\n            Assert.Equal(4, results.Count);\n            Assert.Contains(1, results);\n            Assert.Contains(2, results);\n            Assert.Contains(3, results);\n            Assert.Contains(4, results);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Common/ErrorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http\n{\n    public class ErrorTest\n    {\n        [Fact]\n        public void Format()\n        {\n            // Arrange\n            string expected = \"The formatted message\";\n\n            // Act\n            string actual = Error.Format(\"The {0} message\", \"formatted\");\n\n            // Assert\n            Assert.Equal(expected, actual);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Common/HttpMethodHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http\n{\n    public class HttpMethodHelperTest\n    {\n        public static TheoryDataSet<string, HttpMethod> CommonHttpMethods\n        {\n            get\n            {\n                return new TheoryDataSet<string, HttpMethod>\n                {\n                    { \"Get\", HttpMethod.Get },\n                    { \"Post\", HttpMethod.Post },\n                    { \"Put\", HttpMethod.Put },\n                    { \"Delete\", HttpMethod.Delete },\n                    { \"Head\", HttpMethod.Head },\n                    { \"Options\", HttpMethod.Options },\n                    { \"Trace\", HttpMethod.Trace },\n                };\n            }\n        }\n\n        public static TheoryDataSet<string> UncommonHttpMethods\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    \"Debug\",\n                    \"Patch\",\n                    \"Connect\",\n                    \"Random\",\n                    \"M-Get\",\n                };\n            }\n        }\n\n        [Fact]\n        public void GetHttpMethod_ReturnsNullOnNullorEmpty()\n        {\n            Assert.Null(HttpMethodHelper.GetHttpMethod(null));\n            Assert.Null(HttpMethodHelper.GetHttpMethod(String.Empty));\n        }\n\n        [Theory]\n        [PropertyData(\"CommonHttpMethods\")]\n        public void GetHttpMethod_RetunsStaticResult(string method, HttpMethod expectedMethod)\n        {\n            Assert.Same(expectedMethod, HttpMethodHelper.GetHttpMethod(method));\n            Assert.Same(expectedMethod, HttpMethodHelper.GetHttpMethod(method.ToLowerInvariant()));\n            Assert.Same(expectedMethod, HttpMethodHelper.GetHttpMethod(method.ToUpperInvariant()));\n        }\n\n        [Theory]\n        [PropertyData(\"UncommonHttpMethods\")]\n        public void GetHttpMethod_RetunsNonStaticResult(string method)\n        {\n            Assert.Equal(method, HttpMethodHelper.GetHttpMethod(method).ToString());\n        }\n    }\n}\n"
  },
  {
    "path": "test/Common/ListWrapperCollectionTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing Microsoft.TestCommon;\n\nnamespace System.Collections.ObjectModel\n{\n    public class ListWrapperCollectionTests\n    {\n        [Fact]\n        public void ListWrapperCollection_ItemsList_HasSameContents()\n        {\n            // Arrange\n            ListWrapperCollection<object> listWrapper = new ListWrapperCollection<object>();\n\n            // Act\n            listWrapper.Add(new object());\n            listWrapper.Add(new object());\n\n            // Assert\n            Assert.Equal(listWrapper, listWrapper.ItemsList);\n        }\n\n        [Fact]\n        public void ListWrapperCollection_ItemsList_IsPassedInList()\n        {\n            // Arrange\n            List<object> list = new List<object>() { new object(), new object() };\n            ListWrapperCollection<object> listWrapper = new ListWrapperCollection<object>(list);\n\n            // Act & Assert\n            Assert.Same(list, listWrapper.ItemsList);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Common/PathHelpersTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Test\n{\n    public class PathHelpersTest\n    {\n        [Theory]\n        [InlineData(\"foo.Bar\", \"bar\")]\n        [InlineData(\"foo.bar\", \"bar\")]\n        [InlineData(\".bar\", \"bar\")]\n        public void EndsWithExtensionReturnsTrue(string path, string extension)\n        {\n            Assert.True(PathHelpers.EndsWithExtension(path, extension));\n        }\n\n        [Theory]\n        [InlineData(\"foo.Baz\", \"bar\")]\n        [InlineData(\"\", \"bar\")]\n        [InlineData(\"Bar\", \"bar\")]\n        [InlineData(\"fooBar\", \"bar\")]\n        public void EndsWithExtensionReturnsFalse(string path, string extension)\n        {\n            Assert.False(PathHelpers.EndsWithExtension(path, extension));\n        }\n    }\n}\n"
  },
  {
    "path": "test/Common/PrefixContainerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web\n{\n    [CLSCompliant(false)]\n    public class PrefixContainerTests\n    {\n        [Fact]\n        public void Constructor_GuardClauses()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(() => new PrefixContainer(null), \"values\");\n        }\n\n        [Fact]\n        public void ContainsPrefix_GuardClauses()\n        {\n            // Arrange\n            var container = new PrefixContainer(new string[0]);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(() => container.ContainsPrefix(null), \"prefix\");\n        }\n\n        [Fact]\n        public void ContainsPrefix_EmptyCollectionReturnsFalse()\n        {\n            // Arrange\n            var container = new PrefixContainer(new string[0]);\n\n            // Act & Assert\n            Assert.False(container.ContainsPrefix(\"\"));\n        }\n\n        [Fact]\n        public void ContainsPrefix_ExactMatch()\n        {\n            // Arrange\n            var container = new PrefixContainer(new[] { \"Hello\" });\n\n            // Act & Assert\n            Assert.True(container.ContainsPrefix(\"Hello\"));\n        }\n\n        [Fact]\n        public void ContainsPrefix_MatchIsCaseInsensitive()\n        {\n            // Arrange\n            var container = new PrefixContainer(new[] { \"Hello\" });\n\n            // Act & Assert\n            Assert.True(container.ContainsPrefix(\"hello\"));\n        }\n\n        [Fact]\n        public void ContainsPrefix_MatchIsNotSimpleSubstringMatch()\n        {\n            // Arrange\n            var container = new PrefixContainer(new[] { \"Hello\" });\n\n            // Act & Assert\n            Assert.False(container.ContainsPrefix(\"He\"));\n        }\n\n        [Fact]\n        public void ContainsPrefix_NonEmptyCollectionReturnsTrueIfPrefixIsEmptyString()\n        {\n            // Arrange\n            var container = new PrefixContainer(new[] { \"Hello\" });\n\n            // Act & Assert\n            Assert.True(container.ContainsPrefix(\"\"));\n        }\n\n        [Fact]\n        public void ContainsPrefix_PrefixBoundaries()\n        {\n            // Arrange\n            var container = new PrefixContainer(new[] { \"Hello.There[0]\" });\n\n            // Act & Assert\n            Assert.True(container.ContainsPrefix(\"hello\"));\n            Assert.True(container.ContainsPrefix(\"hello.there\"));\n            Assert.True(container.ContainsPrefix(\"hello.there[0]\"));\n            Assert.False(container.ContainsPrefix(\"hello.there.0\"));\n        }\n\n        [Theory]\n        [InlineData(\"a\")]\n        [InlineData(\"a[d]\")]\n        [InlineData(\"c.b\")]\n        [InlineData(\"c.b.a\")]\n        public void ContainsPrefix_PositiveTests(string testValue)\n        {\n            // Arrange\n            var container = new PrefixContainer(new[] { \"a.b\", \"c.b.a\", \"a[d]\", \"a.c\" });\n\n            // Act & Assert\n            Assert.True(container.ContainsPrefix(testValue));\n        }\n\n        [Theory]\n        [InlineData(\"a.d\")]\n        [InlineData(\"b\")]\n        [InlineData(\"c.a\")]\n        [InlineData(\"c.b.a.a\")]\n        public void ContainsPrefix_NegativeTests(string testValue)\n        {\n            // Arrange\n            var container = new PrefixContainer(new[] { \"a.b\", \"c.b.a\", \"a[d]\", \"a.c\" });\n\n            // Act & Assert\n            Assert.False(container.ContainsPrefix(testValue));\n        }\n\n        [Fact]\n        public void ContainsPrefix_ShouldIdentifyCollectionWhenNonCollectionPropertyOccursOnBinarySearchBoundary()\n        {\n            // Arrange\n            var container = new PrefixContainer(new[] { \"foo.a\", \"foo.b\", \"foo.c\", \"foo.d\", \"foo.esSomethingElse\", \"foo.es[0].a\", \"foo.es[0].b\", \"foo.es[0].c\", \"foo.es[0].d\", \"foo.es[0].e\" });\n\n            // Act & Assert\n            Assert.True(container.ContainsPrefix(\"foo.es\"));\n        }\n\n        [Fact]\n        public void ContainsPrefix_ShouldIdentifyCollectionWhenNonCollectionPropertyDoesNotOccurOnBinarySearchBoundary()\n        {\n            // Arrange\n            var container = new PrefixContainer(new[] { \"foo.a\", \"foo.b\", \"foo.c\", \"foo.d\", \"foo.esSomethingElse\", \"foo.es[0].a\", \"foo.es[0].b\", \"foo.es[0].c\" });\n\n            // Act & Assert\n            Assert.True(container.ContainsPrefix(\"foo.es\"));\n        }\n\n        [Fact]\n        public void GetKeysFromPrefix_DotsNotation()\n        {\n            // Arrange\n            var container = new PrefixContainer(new[] { \"foo.bar.baz\", \"something.other\", \"foo.baz\", \"foot.hello\", \"fo.nothing\", \"foo\" });\n            string prefix = \"foo\";\n\n            // Act\n            IDictionary<string, string> result = container.GetKeysFromPrefix(prefix);\n\n            // Assert\n            Assert.Equal(2, result.Count());\n            Assert.True(result.ContainsKey(\"bar\"));\n            Assert.True(result.ContainsKey(\"baz\"));\n            Assert.Equal(\"foo.bar\", result[\"bar\"]);\n            Assert.Equal(\"foo.baz\", result[\"baz\"]);\n        }\n\n        [Fact]\n        public void GetKeysFromPrefix_BracketsNotation()\n        {\n            // Arrange\n            var container = new PrefixContainer(new[] { \"foo[bar]baz\", \"something[other]\", \"foo[baz]\", \"foot[hello]\", \"fo[nothing]\", \"foo\" });\n            string prefix = \"foo\";\n\n            // Act\n            IDictionary<string, string> result = container.GetKeysFromPrefix(prefix);\n\n            // Assert\n            Assert.Equal(2, result.Count());\n            Assert.True(result.ContainsKey(\"bar\"));\n            Assert.True(result.ContainsKey(\"baz\"));\n            Assert.Equal(\"foo[bar]\", result[\"bar\"]);\n            Assert.Equal(\"foo[baz]\", result[\"baz\"]);\n        }\n\n        [Fact]\n        public void GetKeysFromPrefix_MixedDotsAndBrackets()\n        {\n            // Arrange\n            var container = new PrefixContainer(new[] { \"foo[bar]baz\", \"something[other]\", \"foo.baz\", \"foot[hello]\", \"fo[nothing]\", \"foo\" });\n            string prefix = \"foo\";\n\n            // Act\n            IDictionary<string, string> result = container.GetKeysFromPrefix(prefix);\n\n            // Assert\n            Assert.Equal(2, result.Count());\n            Assert.True(result.ContainsKey(\"bar\"));\n            Assert.True(result.ContainsKey(\"baz\"));\n            Assert.Equal(\"foo[bar]\", result[\"bar\"]);\n            Assert.Equal(\"foo.baz\", result[\"baz\"]);\n        }\n\n        [Fact]\n        public void GetKeysFromPrefix_AllValues()\n        {\n            // Arrange\n            var container = new PrefixContainer(new[] { \"foo[bar]baz\", \"something[other]\", \"foo.baz\", \"foot[hello]\", \"fo[nothing]\", \"foo\" });\n            string prefix = \"\";\n\n            // Act\n            IDictionary<string, string> result = container.GetKeysFromPrefix(prefix);\n\n            // Assert\n            Assert.Equal(4, result.Count());\n            Assert.Equal(\"foo\", result[\"foo\"]);\n            Assert.Equal(\"something\", result[\"something\"]);\n            Assert.Equal(\"foot\", result[\"foot\"]);\n            Assert.Equal(\"fo\", result[\"fo\"]);\n        }\n\n        [Fact]\n        public void GetKeysFromPrefix_PrefixNotFound()\n        {\n            // Arrange\n            var container = new PrefixContainer(new[] { \"foo[bar]\", \"something[other]\", \"foo.baz\", \"foot[hello]\", \"fo[nothing]\", \"foo\" });\n            string prefix = \"notfound\";\n\n            // Act\n            IDictionary<string, string> result = container.GetKeysFromPrefix(prefix);\n\n            // Assert\n            Assert.Empty(result);\n        }\n    }\n}"
  },
  {
    "path": "test/Common/Routing/DefaultInlineConstraintResolverTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n#if ASPNETWEBAPI\nusing System.Web.Http.Routing.Constraints;\n#else\nusing System.Web.Mvc.Routing.Constraints;\n#endif\nusing Microsoft.TestCommon;\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing\n#else\nnamespace System.Web.Mvc.Routing\n#endif\n{\n    public class DefaultInlineConstraintResolverTest\n    {\n        [Fact]\n        public void ResolveConstraint_AlphaConstraint()\n        {\n            var constraint = new DefaultInlineConstraintResolver().ResolveConstraint(\"alpha\");\n\n            Assert.IsType<AlphaRouteConstraint>(constraint);\n        }\n\n        [Fact]\n        public void ResolveConstraint_BoolConstraint()\n        {\n            var constraint = new DefaultInlineConstraintResolver().ResolveConstraint(\"bool\");\n\n            Assert.IsType<BoolRouteConstraint>(constraint);\n        }\n\n        [Fact]\n        public void ResolveConstraint_CompoundConstraintIsNotRegistered()\n        {\n            Assert.Null(new DefaultInlineConstraintResolver().ResolveConstraint(\"compound\"));\n        }\n\n        [Fact]\n        public void ResolveConstraint_DateTimeConstraint()\n        {\n            var constraint = new DefaultInlineConstraintResolver().ResolveConstraint(\"datetime\");\n\n            Assert.IsType<DateTimeRouteConstraint>(constraint);\n        }\n\n        [Fact]\n        public void ResolveConstraint_DecimalConstraint()\n        {\n            var constraint = new DefaultInlineConstraintResolver().ResolveConstraint(\"decimal\");\n\n            Assert.IsType<DecimalRouteConstraint>(constraint);\n        }\n\n        [Fact]\n        public void ResolveConstraint_DoubleConstraint()\n        {\n            var constraint = new DefaultInlineConstraintResolver().ResolveConstraint(\"double\");\n\n            Assert.IsType<DoubleRouteConstraint>(constraint);\n        }\n\n        [Fact]\n        public void ResolveConstraint_EnumNameConstraintIsNotRegistered()\n        {\n            Assert.Null(new DefaultInlineConstraintResolver().ResolveConstraint(\"enumname\"));\n        }\n\n        [Fact]\n        public void ResolveConstraint_EnumValueConstraintIsNotRegistered()\n        {\n            Assert.Null(new DefaultInlineConstraintResolver().ResolveConstraint(\"enumvalue\"));\n        }\n\n        [Fact]\n        public void ResolveConstraint_FloatConstraint()\n        {\n            var constraint = new DefaultInlineConstraintResolver().ResolveConstraint(\"float\");\n\n            Assert.IsType<FloatRouteConstraint>(constraint);\n        }\n\n        [Fact]\n        public void ResolveConstraint_GuidConstraint()\n        {\n            var constraint = new DefaultInlineConstraintResolver().ResolveConstraint(\"guid\");\n\n            Assert.IsType<GuidRouteConstraint>(constraint);\n        }\n\n        [Fact]\n        public void ResolveConstraint_IntConstraint()\n        {\n            var constraint = new DefaultInlineConstraintResolver().ResolveConstraint(\"int\");\n\n            Assert.IsType<IntRouteConstraint>(constraint);\n        }\n\n        [Fact]\n        public void ResolveConstraint_LengthConstraint()\n        {\n            var constraint = new DefaultInlineConstraintResolver().ResolveConstraint(\"length(5)\");\n\n            var lengthRouteConstraint = Assert.IsType<LengthRouteConstraint>(constraint);\n            Assert.Equal(5, lengthRouteConstraint.Length);\n        }\n\n        [Fact]\n        public void ResolveConstraint_LengthRangeConstraint()\n        {\n            var constraint = new DefaultInlineConstraintResolver().ResolveConstraint(\"length(5, 10)\");\n\n            LengthRouteConstraint lengthConstraint = Assert.IsType<LengthRouteConstraint>(constraint);\n            Assert.Equal(5, lengthConstraint.MinLength);\n            Assert.Equal(10, lengthConstraint.MaxLength);\n        }\n\n        [Fact]\n        public void ResolveConstraint_LongRangeConstraint()\n        {\n            var constraint = new DefaultInlineConstraintResolver().ResolveConstraint(\"long\");\n\n            Assert.IsType<LongRouteConstraint>(constraint);\n        }\n\n        [Fact]\n        public void ResolveConstraint_MaxConstraint()\n        {\n            var constraint = new DefaultInlineConstraintResolver().ResolveConstraint(\"max(10)\");\n\n            var maxRouteConstraint = Assert.IsType<MaxRouteConstraint>(constraint);\n            Assert.Equal(10, maxRouteConstraint.Max);\n        }\n\n        [Fact]\n        public void ResolveConstraint_MaxLengthConstraint()\n        {\n            var constraint = new DefaultInlineConstraintResolver().ResolveConstraint(\"maxlength(10)\");\n\n            var maxLengthRouteConstraint = Assert.IsType<MaxLengthRouteConstraint>(constraint);\n            Assert.Equal(10, maxLengthRouteConstraint.MaxLength);\n        }\n\n        [Fact]\n        public void ResolveConstraint_MinConstraint()\n        {\n            var constraint = new DefaultInlineConstraintResolver().ResolveConstraint(\"min(3)\");\n\n            var minRouteConstraint = Assert.IsType<MinRouteConstraint>(constraint);\n            Assert.Equal(3, minRouteConstraint.Min);\n        }\n\n        [Fact]\n        public void ResolveConstraint_MinLengthConstraint()\n        {\n            var constraint = new DefaultInlineConstraintResolver().ResolveConstraint(\"minlength(3)\");\n\n            var minLengthRouteConstraint = Assert.IsType<MinLengthRouteConstraint>(constraint);\n            Assert.Equal(3, minLengthRouteConstraint.MinLength);\n        }\n\n        [Fact]\n        public void ResolveConstraint_OptionalConstraintIsNotRegistered()\n        {\n            Assert.Null(new DefaultInlineConstraintResolver().ResolveConstraint(\"optional\"));\n        }\n\n        [Fact]\n        public void ResolveConstraint_RangeConstraint()\n        {\n            var constraint = new DefaultInlineConstraintResolver().ResolveConstraint(\"range(5, 10)\");\n\n            RangeRouteConstraint rangeConstraint = Assert.IsType<RangeRouteConstraint>(constraint);\n            Assert.Equal(5, rangeConstraint.Min);\n            Assert.Equal(10, rangeConstraint.Max);\n        }\n\n        [Fact]\n        public void ResolveConstraint_RegexConstraint()\n        {\n            var constraint = new DefaultInlineConstraintResolver().ResolveConstraint(\"regex(abc,defg)\");\n\n            RegexRouteConstraint regexConstraint = Assert.IsType<RegexRouteConstraint>(constraint);\n            Assert.Equal(\"abc,defg\", regexConstraint.Pattern);\n        }\n\n        [Fact]\n        public void ResolveConstraint_IntConstraintWithArgument_Throws()\n        {\n            Assert.Throws<InvalidOperationException>(\n                () => new DefaultInlineConstraintResolver().ResolveConstraint(\"int(5)\"),\n               \"Could not find a constructor for constraint type 'IntRouteConstraint' with the following number of parameters: 1.\");\n        }\n\n        [Fact]\n        public void ResolveConstraint_SupportsCustomConstraints()\n        {\n            var resolver = new DefaultInlineConstraintResolver();\n            resolver.ConstraintMap.Add(\"custom\", typeof(IntRouteConstraint));\n\n            var constraint = resolver.ResolveConstraint(\"custom\");\n\n            Assert.IsType<IntRouteConstraint>(constraint);\n        }\n\n        [Fact]\n        public void ResolveConstraint_CustomConstraintThatDoesNotImplementouteConstraintInterfact_Throws()\n        {\n            var resolver = new DefaultInlineConstraintResolver();\n            resolver.ConstraintMap.Add(\"custom\", typeof(string));\n\n            Assert.Throws<InvalidOperationException>(\n                () => resolver.ResolveConstraint(\"custom\"),\n#if ASPNETWEBAPI\n                \"The constraint type 'String' which is mapped to constraint key 'custom' must implement the IHttpRouteConstraint interface.\");\n#else\n                \"The constraint type 'String' which is mapped to constraint key 'custom' must implement the IRouteConstraint interface.\");\n#endif\n        }\n    }\n}"
  },
  {
    "path": "test/Common/Routing/DirectRouteBuilderTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n#if ASPNETWEBAPI\nusing System.Net.Http;\nusing System.Web.Http.Routing.Constraints;\n#else\nusing System.Web.Mvc.Routing.Constraints;\n#endif\nusing Microsoft.TestCommon;\nusing Moq;\n\n#if ASPNETWEBAPI\nusing TActionDescriptor = System.Web.Http.Controllers.HttpActionDescriptor;\nusing TParsedRoute = System.Web.Http.Routing.HttpParsedRoute;\nusing TRouteValueDictionary = System.Web.Http.Routing.HttpRouteValueDictionary;\n#else\nusing TActionDescriptor = System.Web.Mvc.ActionDescriptor;\nusing TParsedRoute = System.Web.Mvc.Routing.ParsedRoute;\nusing TRouteValueDictionary = System.Web.Routing.RouteValueDictionary;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing\n#else\nnamespace System.Web.Mvc.Routing\n#endif\n{\n    public class DirectRouteBuilderTests\n    {\n        [Fact]\n        public void CreateRoute_ValidatesConstraintType_TRouteConstraint()\n        {\n            // Arrange\n            var actions = GetActions();\n            var builder = new DirectRouteBuilder(actions, targetIsAction: true);\n\n            var constraint = new AlphaRouteConstraint();\n            var constraints = new TRouteValueDictionary();\n            constraints.Add(\"custom\", constraint);\n            builder.Constraints = constraints;\n\n            // Act\n            var routeEntry = builder.Build();\n\n            // Assert\n            Assert.NotNull(routeEntry.Route.Constraints[\"custom\"]);\n        }\n\n        [Fact]\n        public void BuildRoute_ValidatesConstraintType_StringRegex()\n        {\n            // Arrange\n            var actions = GetActions();\n            var builder = new DirectRouteBuilder(actions, targetIsAction: true);\n\n            var constraint = \"product|products\";\n            var constraints = new TRouteValueDictionary();\n            constraints.Add(\"custom\", constraint);\n            builder.Constraints = constraints;\n\n            // Act\n            var routeEntry = builder.Build();\n\n            // Assert\n            Assert.NotNull(routeEntry.Route.Constraints[\"custom\"]);\n        }\n\n        [Fact]\n        public void BuildRoute_ValidatesConstraintType_InvalidType()\n        {\n            // Arrange\n            var actions = GetActions();\n            var builder = new DirectRouteBuilder(actions, targetIsAction: true);\n\n            var constraint = new Uri(\"http://localhost/\");\n            var constraints = new TRouteValueDictionary();\n            constraints.Add(\"custom\", constraint);\n\n            builder.Constraints = constraints;\n            builder.Template = \"c/{id}\";\n\n#if ASPNETWEBAPI\n            string expectedMessage =\n                \"The constraint entry 'custom' on the route with route template 'c/{id}' \" +\n                \"must have a string value or be of a type which implements 'System.Web.Http.Routing.IHttpRouteConstraint'.\";\n#else\n            string expectedMessage =\n                \"The constraint entry 'custom' on the route with route template 'c/{id}' \" +\n                \"must have a string value or be of a type which implements 'System.Web.Routing.IRouteConstraint'.\";\n#endif\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(() => builder.Build(), expectedMessage);\n        }\n\n        [Fact]\n        public void BuildRoute_ValidatesAllowedParameters()\n        {\n            // Arrange\n            var actions = GetActions();\n            var builder = new MockDirectRouteBuilder(actions, targetIsAction: true);\n            builder.Template = \"{a}/{b}\";\n\n            // Act\n            RouteEntry entry = builder.Build();\n\n            // Assert\n            Assert.NotNull(entry);\n            Assert.Equal(1, builder.TimesValidateParametersCalled);\n        }\n\n        [Theory]\n        [InlineData(\"{controller}\", true)]\n        [InlineData(\"{controller}\", false)]\n        [InlineData(\"{z}-abc-{controller}\", true)]\n        public void BuildRoute_ControllerParameterNotAllowed(string template, bool targetIsAction)\n        {\n            // Arrange\n            var actions = GetActions();\n\n            var expectedMessage =\n                \"A direct route cannot use the parameter 'controller'. \" +\n                \"Specify a literal path in place of this parameter to create a route to a controller.\";\n\n            var builder = new MockDirectRouteBuilder(actions, targetIsAction);\n            builder.Template = template;\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(() => builder.Build(), expectedMessage);\n            Assert.Equal(1, builder.TimesValidateParametersCalled);\n        }\n\n        [Fact]\n        public void BuildRoute_ActionParameterAllowed_OnControllerRoute()\n        {\n            // Arrange\n            var actions = GetActions();\n            var builder = new MockDirectRouteBuilder(actions, targetIsAction: false);\n            builder.Template = \"{a}/{action}\";\n\n            // Act\n            RouteEntry entry = builder.Build();\n\n            // Assert\n            Assert.NotNull(entry);\n            Assert.Equal(1, builder.TimesValidateParametersCalled);\n        }\n\n        [Theory]\n        [InlineData(\"{action}\")]\n        [InlineData(\"api/yy-{action}\")]\n        public void BuildRoute_ActionNotAllowed_OnActionRoute(string template)\n        {\n            // Arrange\n            var actions = GetActions();\n\n            var expectedMessage =\n                \"A direct route for an action method cannot use the parameter 'action'. \" +\n                \"Specify a literal path in place of this parameter to create a route to the action.\";\n\n            var builder = new MockDirectRouteBuilder(actions, targetIsAction: true);\n            builder.Template = template;\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(() => builder.Build(), expectedMessage);\n            Assert.Equal(1, builder.TimesValidateParametersCalled);\n        }\n\n#if ASPNETWEBAPI\n        private IReadOnlyCollection<TActionDescriptor> GetActions()\n        {\n            var actions = new List<TActionDescriptor>()\n            {\n                new Mock<TActionDescriptor>().Object,\n            };\n\n            return actions.AsReadOnly();\n        }\n#else\n        private IReadOnlyCollection<TActionDescriptor> GetActions()\n        {\n            var action = new Mock<ActionDescriptor>();\n            action.SetupGet(a => a.ControllerDescriptor).Returns(new Mock<ControllerDescriptor>().Object);\n            var actions = new List<ActionDescriptor>()\n            {\n                action.Object,\n            };\n\n            return actions.AsReadOnly();\n        }\n#endif\n\n        private class MockDirectRouteBuilder : DirectRouteBuilder\n        {\n            public MockDirectRouteBuilder(IReadOnlyCollection<TActionDescriptor> actionDescriptors, bool targetIsAction)\n                : base(actionDescriptors, targetIsAction)\n            {\n            }\n\n            public int TimesValidateParametersCalled\n            {\n                get;\n                private set;\n            }\n\n            internal override void ValidateParameters(TParsedRoute parsedRoute)\n            {\n                TimesValidateParametersCalled++;\n                base.ValidateParameters(parsedRoute);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Common/Routing/InlineRouteTemplateParserTests.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\n#if ASPNETWEBAPI\nusing System.Web.Http.Routing.Constraints;\n#else\nusing System.Web.Mvc.Routing.Constraints;\nusing System.Web.Routing;\n#endif\nusing Microsoft.TestCommon;\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing\n#else\nnamespace System.Web.Mvc.Routing\n#endif\n{\n    public class InlineRouteTemplateParserTests\n    {\n#if ASPNETWEBAPI\n        private static readonly RouteParameter OptionalParameter = RouteParameter.Optional;\n#else\n        private static readonly UrlParameter OptionalParameter = UrlParameter.Optional;\n#endif\n\n        [Fact]\n        public void ParseRouteTemplate_ChainedConstraintAndDefault()\n        {\n            var result = Act(@\"hello/{param:int=111111}\");\n\n            Assert.Equal(\"hello/{param}\", result.RouteUrl);\n            Assert.Equal(\"111111\", result.Defaults[\"param\"]);\n            Assert.IsType<IntRouteConstraint>(result.Constraints[\"param\"]);\n        }\n\n        [Fact]\n        public void ParseRouteTemplate_ChainedConstraintWithArgumentsAndDefault()\n        {\n            var result = Act(@\"hello/{param:regex(\\d+)=111111}\");\n\n            Assert.Equal(\"hello/{param}\", result.RouteUrl);\n            Assert.Equal(\"111111\", result.Defaults[\"param\"]);\n            var regexRouteConstraint = Assert.IsType<RegexRouteConstraint>(result.Constraints[\"param\"]);\n            Assert.Equal(@\"\\d+\", regexRouteConstraint.Pattern);\n        }\n\n        [Fact]\n        public void ParseRouteTemplate_ChainedConstraintAndOptional()\n        {\n            var result = Act(@\"hello/{param:int?}\");\n\n            Assert.Equal(\"hello/{param}\", result.RouteUrl);\n\n            Assert.Equal(OptionalParameter, result.Defaults[\"param\"]);\n\n            var constraint = Assert.IsType<OptionalRouteConstraint>(result.Constraints[\"param\"]);\n            Assert.IsType<IntRouteConstraint>(constraint.InnerConstraint);\n        }\n\n        [Fact]\n        public void ParseRouteTemplate_ChainedConstraintWithArgumentsAndOptional()\n        {\n            var result = Act(@\"hello/{param:regex(\\d+)?}\");\n\n            Assert.Equal(\"hello/{param}\", result.RouteUrl);\n\n            Assert.Equal(OptionalParameter, result.Defaults[\"param\"]);\n\n            var constraint = Assert.IsType<OptionalRouteConstraint>(result.Constraints[\"param\"]);\n            Assert.Equal(@\"\\d+\", Assert.IsType<RegexRouteConstraint>(constraint.InnerConstraint).Pattern);\n        }\n\n        [Fact]\n        public void ParseRouteTemplate_ChainedConstraints()\n        {\n            var result = Act(@\"hello/{param:regex(\\d+):regex(\\w+)}\");\n\n            Assert.Equal(\"hello/{param}\", result.RouteUrl);\n\n            CompoundRouteConstraint constraint = Assert.IsType<CompoundRouteConstraint>(result.Constraints[\"param\"]);\n            Assert.Equal(@\"\\d+\", Assert.IsType<RegexRouteConstraint>(constraint.Constraints.ElementAt(0)).Pattern);\n            Assert.Equal(@\"\\w+\", Assert.IsType<RegexRouteConstraint>(constraint.Constraints.ElementAt(1)).Pattern);\n        }\n\n        [Fact]\n        public void ParseRouteTemplate_Constraint()\n        {\n            var result = Act(@\"hello/{param:regex(\\d+)}\");\n\n            Assert.Equal(\"hello/{param}\", result.RouteUrl);\n\n            var constraint = Assert.IsType<RegexRouteConstraint>(result.Constraints[\"param\"]);\n            Assert.Equal(@\"\\d+\", constraint.Pattern);\n        }\n\n        [Fact]\n        public void ParseRouteTemplate_ConstraintsDefaultsAndOptionalsInMultipleSections()\n        {\n            var result = Act(@\"some/url-{p1:alpha:length(3)=hello}/{p2=abc}/{p3?}\");\n\n            Assert.Equal(\"some/url-{p1}/{p2}/{p3}\", result.RouteUrl);\n\n            Assert.Equal(\"hello\", result.Defaults[\"p1\"]);\n            Assert.Equal(\"abc\", result.Defaults[\"p2\"]);\n            Assert.Equal(OptionalParameter, result.Defaults[\"p3\"]);\n\n            CompoundRouteConstraint constraint = Assert.IsType<CompoundRouteConstraint>(result.Constraints[\"p1\"]);\n            Assert.IsType<AlphaRouteConstraint>(constraint.Constraints.ElementAt(0));\n            Assert.IsType<LengthRouteConstraint>(constraint.Constraints.ElementAt(1));\n        }\n\n        [Fact]\n        public void ParseRouteTemplate_NoTokens()\n        {\n            var result = Act(\"hello/world\");\n\n            Assert.Equal(\"hello/world\", result.RouteUrl);\n        }\n\n        [Fact]\n        public void ParseRouteTemplate_OptionalParam()\n        {\n            var result = Act(\"hello/{param?}\");\n\n            Assert.Equal(\"hello/{param}\", result.RouteUrl);\n            Assert.Equal(OptionalParameter, result.Defaults[\"param\"]);\n        }\n\n        [Fact]\n        public void ParseRouteTemplate_ParamDefault()\n        {\n            var result = Act(\"hello/{param=world}\");\n\n            Assert.Equal(\"hello/{param}\", result.RouteUrl);\n            Assert.Equal(\"world\", result.Defaults[\"param\"]);\n        }\n\n        [Fact]\n        public void ParseRouteTemplate_RegexConstraintWithClosingBraceInPattern()\n        {\n            var result = Act(@\"hello/{param:regex(\\})}\");\n\n            Assert.Equal(\"hello/{param}\", result.RouteUrl);\n\n            var constraint = Assert.IsType<RegexRouteConstraint>(result.Constraints[\"param\"]);\n            Assert.Equal(@\"\\}\", constraint.Pattern);\n        }\n\n        [Fact]\n        public void ParseRouteTemplate_RegexConstraintWithClosingParenInPattern()\n        {\n            var result = Act(@\"hello/{param:regex(\\))}\");\n\n            Assert.Equal(\"hello/{param}\", result.RouteUrl);\n\n            var constraint = Assert.IsType<RegexRouteConstraint>(result.Constraints[\"param\"]);\n            Assert.Equal(@\"\\)\", constraint.Pattern);\n        }\n\n        [Fact]\n        public void ParseRouteTemplate_RegexConstraintWithColonInPattern()\n        {\n            var result = Act(@\"hello/{param:regex(:)}\");\n\n            Assert.Equal(\"hello/{param}\", result.RouteUrl);\n            var constraint = Assert.IsType<RegexRouteConstraint>(result.Constraints[\"param\"]);\n            Assert.Equal(@\":\", constraint.Pattern);\n        }\n\n        [Fact]\n        public void ParseRouteTemplate_RegexConstraintWithCommaInPattern()\n        {\n            var result = Act(@\"hello/{param:regex(\\w,\\w)}\");\n\n            Assert.Equal(\"hello/{param}\", result.RouteUrl);\n            var constraint = Assert.IsType<RegexRouteConstraint>(result.Constraints[\"param\"]);\n            Assert.Equal(@\"\\w,\\w\", constraint.Pattern);\n        }\n\n        [Fact]\n        public void ParseRouteTemplate_RegexConstraintWithEqualsSignInPattern()\n        {\n            var result = Act(@\"hello/{param:regex(=)}\");\n\n            Assert.Equal(\"hello/{param}\", result.RouteUrl);\n\n            Assert.DoesNotContain(\"param\", result.Defaults.Keys);\n            var constraint = Assert.IsType<RegexRouteConstraint>(result.Constraints[\"param\"]);\n            Assert.Equal(@\"=\", constraint.Pattern);\n        }\n\n        [Fact]\n        public void ParseRouteTemplate_RegexConstraintWithOpenBraceInPattern()\n        {\n            var result = Act(@\"hello/{param:regex(\\{)}\");\n\n            Assert.Equal(\"hello/{param}\", result.RouteUrl);\n            var constraint = Assert.IsType<RegexRouteConstraint>(result.Constraints[\"param\"]);\n            Assert.Equal(@\"\\{\", constraint.Pattern);\n        }\n\n        [Fact]\n        public void ParseRouteTemplate_RegexConstraintWithOpenParenInPattern()\n        {\n            var result = Act(@\"hello/{param:regex(\\()}\");\n\n            Assert.Equal(\"hello/{param}\", result.RouteUrl);\n            var constraint = Assert.IsType<RegexRouteConstraint>(result.Constraints[\"param\"]);\n            Assert.Equal(@\"\\(\", constraint.Pattern);\n        }\n\n        [Fact]\n        public void ParseRouteTemplate_RegexConstraintWithQuestionMarkInPattern()\n        {\n            var result = Act(@\"hello/{param:regex(\\?)}\");\n\n            Assert.Equal(\"hello/{param}\", result.RouteUrl);\n            Assert.DoesNotContain(\"param\", result.Defaults.Keys);\n            var constraint = Assert.IsType<RegexRouteConstraint>(result.Constraints[\"param\"]);\n            Assert.Equal(@\"\\?\", constraint.Pattern);\n        }\n\n\n        private ParseResult Act(string template)\n        {\n            var result = new ParseResult();\n #if ASPNETWEBAPI\n            result.Constraints = new HttpRouteValueDictionary();\n            result.Defaults = new HttpRouteValueDictionary();\n#else\n            result.Constraints = new RouteValueDictionary();\n            result.Defaults = new RouteValueDictionary();\n#endif\n            result.RouteUrl = InlineRouteTemplateParser.ParseRouteTemplate(template, result.Defaults, result.Constraints, new DefaultInlineConstraintResolver());\n            return result;\n        }\n\n        struct ParseResult\n        {\n            public string RouteUrl;\n #if ASPNETWEBAPI\n            public HttpRouteValueDictionary Defaults;\n            public HttpRouteValueDictionary Constraints;\n#else\n            public RouteValueDictionary Defaults;\n            public RouteValueDictionary Constraints;\n#endif\n        }\n    }\n}\n"
  },
  {
    "path": "test/Common/Routing/RouteConstraintsTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq.Expressions;\n#if ASPNETWEBAPI\nusing System.Net.Http;\nusing System.Web.Http.Routing.Constraints;\n#else\nusing System.Web.Mvc.Routing.Constraints;\nusing System.Web.Routing;\n#endif\nusing Microsoft.TestCommon;\nusing Moq;\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing\n#else\nnamespace System.Web.Mvc.Routing\n#endif\n{\n    public class RouteConstraintsTests\n    {\n        [Theory]\n        [InlineData(42, true)]\n        [InlineData(\"42\", true)]\n        [InlineData(3.14, false)]\n        [InlineData(\"43.567\", false)]\n        [InlineData(\"42a\", false)]\n        public void IntRouteConstraintTests(object parameterValue, bool expected)\n        {\n            var constraint = new IntRouteConstraint();\n            var actual = TestValue(constraint, parameterValue);\n            Assert.Equal(expected, actual);\n        }\n\n        [Theory]\n        [InlineData(42, true)]\n        [InlineData(\"42\", true)]\n        [InlineData(\"9223372036854775807\", true)]\n        [InlineData(3.14, false)]\n        [InlineData(\"43.567\", false)]\n        [InlineData(\"42a\", false)]\n        public void LongRouteConstraintTests(object parameterValue, bool expected)\n        {\n            var constraint = new LongRouteConstraint();\n            var actual = TestValue(constraint, parameterValue);\n            Assert.Equal(expected, actual);\n        }\n\n        [Theory]\n        [InlineData(@\"^\\d{3}-\\d{3}-\\d{4}$\", \"406-555-0123\", true)]\n        [InlineData(@\"^\\d{3}$\", \"1234\", false)]\n        public void RegexRouteConstraintTests(string pattern, string parameterValue, bool expected)\n        {\n            var constraint = new RegexRouteConstraint(pattern);\n            var actual = TestValue(constraint, parameterValue);\n            Assert.Equal(expected, actual);\n        }\n\n        [Theory]\n        [InlineData(\"alpha\", true)]\n        [InlineData(\"a1pha\", false)]\n        [InlineData(\"\", true)]\n        public void AlphaRouteConstraintTests(string parameterValue, bool expected)\n        {\n            var constraint = new AlphaRouteConstraint();\n            var actual = TestValue(constraint, parameterValue);\n            Assert.Equal(expected, actual);\n        }\n\n        [Theory]\n        [InlineData(long.MinValue, long.MaxValue, 2, true)]\n        [InlineData(3, 5, 4, true)]\n        [InlineData(3, 5, 5, true)]\n        [InlineData(3, 5, 3, true)]\n        [InlineData(3, 5, 6, false)]\n        [InlineData(3, 5, 2, false)]\n        [InlineData(3, 1, 2, false)]\n        public void RangeRouteConstraintTests(long min, long max, int parameterValue, bool expected)\n        {\n            var constraint = new RangeRouteConstraint(min, max);\n            var actual = TestValue(constraint, parameterValue);\n            Assert.Equal(expected, actual);\n        }\n\n        [Theory]\n        [InlineData(3, 4, true)]\n        [InlineData(3, 3, true)]\n        [InlineData(3, 2, false)]\n        public void MinRouteConstraintTests(long min, int parameterValue, bool expected)\n        {\n            var constraint = new MinRouteConstraint(min);\n            var actual = TestValue(constraint, parameterValue);\n            Assert.Equal(expected, actual);\n        }\n\n        [Theory]\n        [InlineData(3, 2, true)]\n        [InlineData(3, 3, true)]\n        [InlineData(3, 4, false)]\n        public void MaxRouteConstraintTests(long max, int parameterValue, bool expected)\n        {\n            var constraint = new MaxRouteConstraint(max);\n            var actual = TestValue(constraint, parameterValue);\n            Assert.Equal(expected, actual);\n        }\n\n        [Theory]\n        [InlineData(3, \"1234\", true)]\n        [InlineData(3, \"123\", true)]\n        [InlineData(3, \"12\", false)]\n        [InlineData(3, \"\", false)]\n        public void MinLengthRouteConstraintTests(int min, string parameterValue, bool expected)\n        {\n            var constraint = new MinLengthRouteConstraint(min);\n            var actual = TestValue(constraint, parameterValue);\n            Assert.Equal(expected, actual);\n        }\n\n        [Theory]\n        [InlineData(3, \"\", true)]\n        [InlineData(3, \"12\", true)]\n        [InlineData(3, \"123\", true)]\n        [InlineData(3, \"1234\", false)]\n        public void MaxLengthRouteConstraintTests(int min, string parameterValue, bool expected)\n        {\n            var constraint = new MaxLengthRouteConstraint(min);\n            var actual = TestValue(constraint, parameterValue);\n            Assert.Equal(expected, actual);\n        }\n\n        [Theory]\n        [InlineData(3, \"123\", true)]\n        [InlineData(3, \"1234\", false)]\n        public void LengthRouteConstraint_ExactLength_Tests(int length, string parameterValue, bool expected)\n        {\n            var constraint = new LengthRouteConstraint(length);\n            var actual = TestValue(constraint, parameterValue);\n            Assert.Equal(expected, actual);\n        }\n\n        [Theory]\n        [InlineData(3, 5, \"12\", false)]\n        [InlineData(3, 5, \"123\", true)]\n        [InlineData(3, 5, \"1234\", true)]\n        [InlineData(3, 5, \"12345\", true)]\n        [InlineData(3, 5, \"123456\", false)]\n        public void LengthRouteConstraint_Range_Tests(int min, int max, string parameterValue, bool expected)\n        {\n            var constraint = new LengthRouteConstraint(min, max);\n            var actual = TestValue(constraint, parameterValue);\n            Assert.Equal(expected, actual);\n        }\n\n        [Theory]\n        [InlineData(\"12345678-1234-1234-1234-123456789012\", false, true)]\n        [InlineData(\"12345678-1234-1234-1234-123456789012\", true, true)]\n        [InlineData(\"12345678901234567890123456789012\", false, true)]\n        [InlineData(\"not-parseable-as-guid\", false, false)]\n        [InlineData(12, false, false)]\n        public void GuidRouteConstraintTests(object parameterValue, bool parseBeforeTest, bool expected)\n        {\n            if (parseBeforeTest)\n            {\n                parameterValue = Guid.Parse(parameterValue.ToString());\n            }\n            var constraint = new GuidRouteConstraint();\n            var actual = TestValue(constraint, parameterValue);\n            Assert.Equal(expected, actual);\n        }\n\n        [Theory]\n        [InlineData(\"3.14\", true)]\n        [InlineData(3.14f, true)]\n        [InlineData(\"not-parseable-as-float\", false)]\n        [InlineData(false, false)]\n        [InlineData(\"1.79769313486232E+300\", false)]\n        public void FloatRouteConstraintTests(object parameterValue, bool expected)\n        {\n            var constraint = new FloatRouteConstraint();\n            var actual = TestValue(constraint, parameterValue);\n            Assert.Equal(expected, actual);\n        }\n\n        [Theory]\n        [InlineData(\"3.14\", true)]\n        [InlineData(3.14f, true)]\n        [InlineData(\"1.79769313486232E+300\", true)]\n        [InlineData(\"not-parseable-as-double\", false)]\n        [InlineData(false, false)]\n        public void DoubleRouteConstraintTests(object parameterValue, bool expected)\n        {\n            var constraint = new DoubleRouteConstraint();\n            var actual = TestValue(constraint, parameterValue);\n            Assert.Equal(expected, actual);\n        }\n\n        [Theory]\n        [InlineData(\"3.14\", true)]\n        [InlineData(\"9223372036854775808.9223372036854775808\", true)]\n        [InlineData(\"1.79769313486232E+300\", false)]\n        [InlineData(\"not-parseable-as-decimal\", false)]\n        [InlineData(false, false)]\n        public void DecimalRouteConstraintTests(object parameterValue, bool expected)\n        {\n            var constraint = new DecimalRouteConstraint();\n            var actual = TestValue(constraint, parameterValue);\n            Assert.Equal(expected, actual);\n        }\n\n        [Theory]\n        [InlineData(\"12/25/2009\", true)]\n        [InlineData(\"12/25/2009 11:45:00 PM\", true)]\n        [InlineData(\"11:45:00 PM\", true)]\n        [InlineData(\"2009-05-12T11:45:00Z\", true)]\n        [InlineData(\"not-parseable-as-date\", false)]\n        [InlineData(false, false)]\n        public void DateTimeRouteConstraint(object parameterValue, bool expected)\n        {\n            var constraint = new DateTimeRouteConstraint();\n            var actual = TestValue(constraint, parameterValue);\n            Assert.Equal(expected, actual);\n        }\n\n        [Theory]\n        [InlineData(\"true\", true)]\n        [InlineData(\"false\", true)]\n        [InlineData(true, true)]\n        [InlineData(false, true)]\n        [InlineData(1, false)]\n        [InlineData(\"not-parseable-as-bool\", false)]\n        public void BoolRouteConstraint(object parameterValue, bool expected)\n        {\n            var constraint = new BoolRouteConstraint();\n            var actual = TestValue(constraint, parameterValue);\n            Assert.Equal(expected, actual);\n        }\n\n        [Theory]\n        [InlineData(null, false, true)]\n        [InlineData(\"pass\", true, true)]\n        [InlineData(\"fail\", true, false)]\n        public void OptionalRouteConstraintTests(object parameterValue, bool shouldCallInner, bool expected)\n        {\n            // Arrange\n            var inner = MockConstraintWithResult((string)parameterValue != \"fail\");\n\n            // Act\n            var constraint = new OptionalRouteConstraint(inner.Object);\n#if ASPNETWEBAPI\n            var optionalParameter = RouteParameter.Optional;\n#else\n            var optionalParameter = UrlParameter.Optional;\n#endif\n            var actual = TestValue(constraint, parameterValue ?? optionalParameter, route =>\n            {\n                route.Defaults.Add(\"fake\", optionalParameter);\n            });\n\n            // Assert\n            Assert.Equal(expected, actual);\n\n            var timeMatchShouldHaveBeenCalled = shouldCallInner\n                ? Times.Once()\n                : Times.Never();\n\n            AssertMatchWasCalled(inner, timeMatchShouldHaveBeenCalled);\n        }\n\n        [Theory]\n        [InlineData(true, true, true)]\n        [InlineData(true, false, false)]\n        [InlineData(false, true, false)]\n        [InlineData(false, false, false)]\n        public void CompoundRouteConstraintTests(bool inner1Result, bool inner2Result, bool expected)\n        {\n            // Arrange\n            var inner1 = MockConstraintWithResult(inner1Result);\n\n            var inner2 = MockConstraintWithResult(inner2Result);\n\n            // Act\n            var constraint = new CompoundRouteConstraint(new[] { inner1.Object, inner2.Object });\n            var actual = TestValue(constraint, null);\n\n            // Assert\n            Assert.Equal(expected, actual);\n        }\n\n#if ASPNETWEBAPI\n        static Expression<Func<IHttpRouteConstraint, bool>> ConstraintMatchMethodExpression =\n            c => c.Match(It.IsAny<HttpRequestMessage>(), It.IsAny<IHttpRoute>(), It.IsAny<string>(), It.IsAny<IDictionary<string, object>>(), It.IsAny<HttpRouteDirection>());\n\n        private static Mock<IHttpRouteConstraint> MockConstraintWithResult(bool result)\n        {\n            var mock = new Mock<IHttpRouteConstraint>();\n            mock.Setup(ConstraintMatchMethodExpression)\n                 .Returns(result)\n                 .Verifiable();\n            return mock;\n        }\n\n        private static void AssertMatchWasCalled(Mock<IHttpRouteConstraint> mock, Times times)\n        {\n            mock.Verify(ConstraintMatchMethodExpression, times);\n        }\n\n        private static bool TestValue(IHttpRouteConstraint constraint, object value, Action<IHttpRoute> routeConfig = null)\n        {\n            HttpRequestMessage httpRequestMessage = new HttpRequestMessage();\n\n            HttpRoute httpRoute = new HttpRoute();\n            if (routeConfig != null)\n            {\n                routeConfig(httpRoute);\n            }\n            const string parameterName = \"fake\";\n            HttpRouteValueDictionary values = new HttpRouteValueDictionary { { parameterName, value } };\n            const HttpRouteDirection httpRouteDirection = HttpRouteDirection.UriResolution;\n\n            return constraint.Match(httpRequestMessage, httpRoute, parameterName, values, httpRouteDirection);\n        }\n#else\n        static Expression<Func<IRouteConstraint, bool>> ConstraintMatchMethodExpression =\n            c => c.Match(It.IsAny<HttpContextBase>(), It.IsAny<Route>(), It.IsAny<string>(), It.IsAny<RouteValueDictionary>(), It.IsAny<RouteDirection>());\n\n        private static Mock<IRouteConstraint> MockConstraintWithResult(bool result)\n        {\n            var mock = new Mock<IRouteConstraint>();\n            mock.Setup(ConstraintMatchMethodExpression)\n                 .Returns(result)\n                 .Verifiable();\n            return mock;\n        }\n\n        private static void AssertMatchWasCalled(Mock<IRouteConstraint> mock, Times times)\n        {\n            mock.Verify(ConstraintMatchMethodExpression, times);\n        }\n\n        private static bool TestValue(IRouteConstraint constraint, object value, Action<Route> routeConfig = null)\n        {\n            var context = new Mock<HttpContextBase>();\n\n            Route route = new Route(\"\", null);\n            route.Defaults = new RouteValueDictionary();\n\n            if (routeConfig != null)\n            {\n                routeConfig(route);\n            }\n            const string parameterName = \"fake\";\n            RouteValueDictionary values = new RouteValueDictionary { { parameterName, value } };\n            const RouteDirection routeDirection = RouteDirection.IncomingRequest;\n\n            return constraint.Match(context.Object, route, parameterName, values, routeDirection);\n        }\n#endif\n\n    }\n}"
  },
  {
    "path": "test/Common/Routing/RouteFactoryAttributeTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\n#if ASPNETWEBAPI\nusing System.Web.Http.Controllers;\n#endif\nusing Microsoft.TestCommon;\nusing Moq;\n\n#if ASPNETWEBAPI\nusing TActionDescriptor = System.Web.Http.Controllers.HttpActionDescriptor;\nusing TRoute = System.Web.Http.Routing.IHttpRoute;\nusing TRouteDictionary = System.Collections.Generic.IDictionary<string, object>;\nusing TRouteDictionaryConcrete = System.Web.Http.Routing.HttpRouteValueDictionary;\n#else\nusing TActionDescriptor = System.Web.Mvc.ActionDescriptor;\nusing TRoute = System.Web.Routing.Route;\nusing TRouteDictionary = System.Web.Routing.RouteValueDictionary;\nusing TRouteDictionaryConcrete = System.Web.Routing.RouteValueDictionary;\n#endif\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing\n#else\nnamespace System.Web.Mvc.Routing\n#endif\n{\n    public class RouteFactoryAttributeTests\n    {\n        [Fact]\n        public void TemplateGet_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            string expectedTemplate = \"RouteTemplate\";\n            RouteFactoryAttribute product = CreateProductUnderTest(expectedTemplate);\n\n            // Act\n            string template = product.Template;\n\n            // Assert\n            Assert.Same(expectedTemplate, template);\n        }\n\n        [Fact]\n        public void NameGet_ReturnsNull()\n        {\n            // Arrange\n            RouteFactoryAttribute product = CreateProductUnderTest();\n\n            // Act\n            string name = product.Name;\n\n            // Assert\n            Assert.Null(name);\n        }\n\n        [Fact]\n        public void OrderGet_ReturnsZero()\n        {\n            // Arrange\n            RouteFactoryAttribute product = CreateProductUnderTest();\n\n            // Act\n            int order = product.Order;\n\n            // Assert\n            Assert.Equal(0, order);\n        }\n\n        [Fact]\n        public void ConstraintsGet_ReturnsNull()\n        {\n            // Arrange\n            RouteFactoryAttribute product = CreateProductUnderTest();\n\n            // Act\n            TRouteDictionary constraints = product.Constraints;\n\n            // Assert\n            Assert.Null(constraints);\n        }\n\n        [Fact]\n        public void CreateRoute_DelegatesToContextCreateBuilderBuild()\n        {\n            // Arrange\n            string expectedTemplate = \"RouteTemplate\";\n            IDirectRouteFactory product = CreateProductUnderTest(expectedTemplate);\n\n            RouteEntry expectedEntry = CreateEntry();\n\n            IDirectRouteBuilder builder = CreateBuilder(() => expectedEntry);\n            DirectRouteFactoryContext context = CreateContext((template) => template == expectedTemplate ? builder :\n                new DirectRouteBuilder(new TActionDescriptor[0], targetIsAction: true));\n\n            // Act\n            RouteEntry entry = product.CreateRoute(context);\n\n            // Assert\n            Assert.Same(expectedEntry, entry);\n        }\n\n        [Fact]\n        public void CreateRoute_IfContextIsNull_Throws()\n        {\n            // Arrange\n            DirectRouteFactoryContext context = null;\n            IDirectRouteFactory product = CreateProductUnderTest();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => product.CreateRoute(context), \"context\");\n        }\n\n        [Fact]\n        public void CreateRoute_UsesNamePropertyWhenBuilding()\n        {\n            // Arrange\n            string expectedName = \"RouteName\";\n            RouteFactoryAttribute product = CreateProductUnderTest();\n            product.Name = expectedName;\n\n            string name = null;\n            IDirectRouteBuilder builder = null;\n            builder = CreateBuilder(() =>\n            {\n                name = builder.Name;\n                return null;\n            });\n            DirectRouteFactoryContext context = CreateContext((i) => builder);\n\n            // Act\n            RouteEntry ignore = product.CreateRoute(context);\n\n            // Assert\n            Assert.Same(expectedName, name);\n        }\n\n        [Fact]\n        public void CreateRoute_UsesOrderPropertyWhenBuilding()\n        {\n            // Arrange\n            int expectedOrder = 123;\n            RouteFactoryAttribute product = CreateProductUnderTest();\n            product.Order = expectedOrder;\n\n            int order = 0;\n            IDirectRouteBuilder builder = null;\n            builder = CreateBuilder(() =>\n            {\n                order = builder.Order;\n                return null;\n            });\n            DirectRouteFactoryContext context = CreateContext((i) => builder);\n\n            // Act\n            RouteEntry ignore = product.CreateRoute(context);\n\n            // Assert\n            Assert.Equal(expectedOrder, order);\n        }\n\n        [Fact]\n        public void CreateRoute_IfBuilderDefaultsIsNull_UsesDefaultsPropertyWhenBuilding()\n        {\n            // Arrange\n            TRouteDictionary expectedDefaults = new TRouteDictionaryConcrete();\n            Mock<RouteFactoryAttribute> productMock = CreateProductUnderTestMock();\n            productMock.SetupGet(p => p.Defaults).Returns(expectedDefaults);\n            IDirectRouteFactory product = productMock.Object;\n\n            RouteEntry expectedEntry = CreateEntry();\n\n            TRouteDictionary defaults = null;\n            IDirectRouteBuilder builder = null;\n            builder = CreateBuilder(() =>\n            {\n                defaults = builder.Defaults;\n                return null;\n            });\n            Assert.Null(builder.Defaults); // Guard\n            DirectRouteFactoryContext context = CreateContext((i) => builder);\n\n            // Act\n            RouteEntry ignore = product.CreateRoute(context);\n\n            // Assert\n            Assert.Same(expectedDefaults, defaults);\n        }\n\n        [Fact]\n        public void CreateRoute_IfBuilderDefaultsIsNotNull_UpdatesDefaultsFromPropertyWhenBuilding()\n        {\n            // Arrange\n            TRouteDictionary existingDefaults = new TRouteDictionaryConcrete();\n            string existingDefaultKey = \"ExistingDefaultKey\";\n            object existingDefaultValue = \"ExistingDefault\";\n            existingDefaults.Add(existingDefaultKey, existingDefaultValue);\n            string conflictingDefaultKey = \"ConflictingDefaultKey\";\n            object oldConflictingDefaultValue = \"OldConflictingDefault\";\n            existingDefaults.Add(conflictingDefaultKey, oldConflictingDefaultValue);\n\n            TRouteDictionary additionalDefaults = new TRouteDictionaryConcrete();\n            string additionalDefaultKey = \"NewDefaultKey\";\n            string additionalDefaultValue = \"NewDefault\";\n            additionalDefaults.Add(additionalDefaultKey, additionalDefaultValue);\n            string newConflictingDefaultValue = \"NewConflictingDefault\";\n            additionalDefaults.Add(conflictingDefaultKey, newConflictingDefaultValue);\n\n            Mock<RouteFactoryAttribute> productMock = CreateProductUnderTestMock();\n            productMock.SetupGet(p => p.Defaults).Returns(additionalDefaults);\n            IDirectRouteFactory product = productMock.Object;\n\n            RouteEntry expectedEntry = CreateEntry();\n\n            TRouteDictionary defaults = null;\n            IDirectRouteBuilder builder = null;\n            builder = CreateBuilder(() =>\n            {\n                defaults = builder.Defaults;\n                return null;\n            });\n\n            builder.Defaults = existingDefaults;\n\n            DirectRouteFactoryContext context = CreateContext((i) => builder);\n\n            // Act\n            RouteEntry ignore = product.CreateRoute(context);\n\n            // Assert\n            Assert.Same(existingDefaults, defaults);\n            Assert.Equal(3, defaults.Count);\n            Assert.True(defaults.ContainsKey(existingDefaultKey));\n            Assert.Same(existingDefaultValue, defaults[existingDefaultKey]);\n            Assert.True(defaults.ContainsKey(conflictingDefaultKey));\n            Assert.Same(newConflictingDefaultValue, defaults[conflictingDefaultKey]);\n            Assert.True(defaults.ContainsKey(additionalDefaultKey));\n            Assert.Same(additionalDefaultValue, defaults[additionalDefaultKey]);\n        }\n\n        [Fact]\n        public void CreateRoute_IfBuilderConstraintsIsNotNullAndDefaultsPropertyIsNull_UsesBuilderDefaults()\n        {\n            // Arrange\n            TRouteDictionary existingDefaults = new TRouteDictionaryConcrete();\n\n            Mock<RouteFactoryAttribute> productMock = CreateProductUnderTestMock();\n            productMock.SetupGet(p => p.Defaults).Returns((TRouteDictionary)null);\n            IDirectRouteFactory product = productMock.Object;\n\n            RouteEntry expectedEntry = CreateEntry();\n\n            TRouteDictionary defaults = null;\n            IDirectRouteBuilder builder = null;\n            builder = CreateBuilder(() =>\n            {\n                defaults = builder.Defaults;\n                return null;\n            });\n\n            builder.Defaults = existingDefaults;\n\n            DirectRouteFactoryContext context = CreateContext((i) => builder);\n\n            // Act\n            RouteEntry ignore = product.CreateRoute(context);\n\n            // Assert\n            Assert.Same(existingDefaults, defaults);\n        }\n\n        [Fact]\n        public void CreateRoute_IfBuilderConstraintsIsNull_UsesConstraintsPropertyWhenBuilding()\n        {\n            // Arrange\n            TRouteDictionary expectedConstraints = new TRouteDictionaryConcrete();\n            Mock<RouteFactoryAttribute> productMock = CreateProductUnderTestMock();\n            productMock.SetupGet(p => p.Constraints).Returns(expectedConstraints);\n            IDirectRouteFactory product = productMock.Object;\n\n            RouteEntry expectedEntry = CreateEntry();\n\n            TRouteDictionary constraints = null;\n            IDirectRouteBuilder builder = null;\n            builder = CreateBuilder(() =>\n            {\n                constraints = builder.Constraints;\n                return null;\n            });\n            Assert.Null(builder.Constraints); // Guard\n            DirectRouteFactoryContext context = CreateContext((i) => builder);\n\n            // Act\n            RouteEntry ignore = product.CreateRoute(context);\n\n            // Assert\n            Assert.Same(expectedConstraints, constraints);\n        }\n\n        [Fact]\n        public void CreateRoute_IfBuilderConstraintsIsNotNull_UpdatesConstraintsFromPropertyWhenBuilding()\n        {\n            // Arrange\n            TRouteDictionary existingConstraints = new TRouteDictionaryConcrete();\n            string existingConstraintKey = \"ExistingConstraintKey\";\n            object existingConstraintValue = \"ExistingConstraint\";\n            existingConstraints.Add(existingConstraintKey, existingConstraintValue);\n            string conflictingConstraintKey = \"ConflictingConstraintKey\";\n            object oldConflictingConstraintValue = \"OldConflictingConstraint\";\n            existingConstraints.Add(conflictingConstraintKey, oldConflictingConstraintValue);\n\n            TRouteDictionary additionalConstraints = new TRouteDictionaryConcrete();\n            string additionalConstraintKey = \"NewConstraintKey\";\n            string additionalConstraintValue = \"NewConstraint\";\n            additionalConstraints.Add(additionalConstraintKey, additionalConstraintValue);\n            string newConflictingConstraintValue = \"NewConflictingConstraint\";\n            additionalConstraints.Add(conflictingConstraintKey, newConflictingConstraintValue);\n\n            Mock<RouteFactoryAttribute> productMock = CreateProductUnderTestMock();\n            productMock.SetupGet(p => p.Constraints).Returns(additionalConstraints);\n            IDirectRouteFactory product = productMock.Object;\n\n            RouteEntry expectedEntry = CreateEntry();\n\n            TRouteDictionary constraints = null;\n            IDirectRouteBuilder builder = null;\n            builder = CreateBuilder(() =>\n            {\n                constraints = builder.Constraints;\n                return null;\n            });\n\n            builder.Constraints = existingConstraints;\n\n            DirectRouteFactoryContext context = CreateContext((i) => builder);\n\n            // Act\n            RouteEntry ignore = product.CreateRoute(context);\n\n            // Assert\n            Assert.Same(existingConstraints, constraints);\n            Assert.Equal(3, constraints.Count);\n            Assert.True(constraints.ContainsKey(existingConstraintKey));\n            Assert.Same(existingConstraintValue, constraints[existingConstraintKey]);\n            Assert.True(constraints.ContainsKey(conflictingConstraintKey));\n            Assert.Same(newConflictingConstraintValue, constraints[conflictingConstraintKey]);\n            Assert.True(constraints.ContainsKey(additionalConstraintKey));\n            Assert.Same(additionalConstraintValue, constraints[additionalConstraintKey]);\n        }\n\n        [Fact]\n        public void CreateRoute_IfBuilderConstraintsIsNotNullAndConstraintsPropertyIsNull_UsesBuilderConstraints()\n        {\n            // Arrange\n            TRouteDictionary existingConstraints = new TRouteDictionaryConcrete();\n\n            Mock<RouteFactoryAttribute> productMock = CreateProductUnderTestMock();\n            productMock.SetupGet(p => p.Constraints).Returns((TRouteDictionary)null);\n            IDirectRouteFactory product = productMock.Object;\n\n            RouteEntry expectedEntry = CreateEntry();\n\n            TRouteDictionary constraints = null;\n            IDirectRouteBuilder builder = null;\n            builder = CreateBuilder(() =>\n            {\n                constraints = builder.Constraints;\n                return null;\n            });\n\n            builder.Constraints = existingConstraints;\n\n            DirectRouteFactoryContext context = CreateContext((i) => builder);\n\n            // Act\n            RouteEntry ignore = product.CreateRoute(context);\n\n            // Assert\n            Assert.Same(existingConstraints, constraints);\n        }\n\n        [Fact]\n        public void CreateRoute_IfBuilderDataTokensIsNull_UsesDataTokensPropertyWhenBuilding()\n        {\n            // Arrange\n            TRouteDictionary expectedDataTokens = new TRouteDictionaryConcrete();\n            Mock<RouteFactoryAttribute> productMock = CreateProductUnderTestMock();\n            productMock.SetupGet(p => p.DataTokens).Returns(expectedDataTokens);\n            IDirectRouteFactory product = productMock.Object;\n\n            RouteEntry expectedEntry = CreateEntry();\n\n            TRouteDictionary dataTokens = null;\n            IDirectRouteBuilder builder = null;\n            builder = CreateBuilder(() =>\n            {\n                dataTokens = builder.DataTokens;\n                return null;\n            });\n            Assert.Null(builder.DataTokens); // Guard\n            DirectRouteFactoryContext context = CreateContext((i) => builder);\n\n            // Act\n            RouteEntry ignore = product.CreateRoute(context);\n\n            // Assert\n            Assert.Same(expectedDataTokens, dataTokens);\n        }\n\n        [Fact]\n        public void CreateRoute_IfBuilderDataTokensIsNotNull_UpdatesDataTokensFromPropertyWhenBuilding()\n        {\n            // Arrange\n            TRouteDictionary existingDataTokens = new TRouteDictionaryConcrete();\n            string existingDataTokenKey = \"ExistingDataTokenKey\";\n            object existingDataTokenValue = \"ExistingDataToken\";\n            existingDataTokens.Add(existingDataTokenKey, existingDataTokenValue);\n            string conflictingDataTokenKey = \"ConflictingDataTokenKey\";\n            object oldConflictingDataTokenValue = \"OldConflictingDataToken\";\n            existingDataTokens.Add(conflictingDataTokenKey, oldConflictingDataTokenValue);\n\n            TRouteDictionary additionalDataTokens = new TRouteDictionaryConcrete();\n            string additionalDataTokenKey = \"NewDataTokenKey\";\n            string additionalDataTokenValue = \"NewDataToken\";\n            additionalDataTokens.Add(additionalDataTokenKey, additionalDataTokenValue);\n            string newConflictingDataTokenValue = \"NewConflictingDataToken\";\n            additionalDataTokens.Add(conflictingDataTokenKey, newConflictingDataTokenValue);\n\n            Mock<RouteFactoryAttribute> productMock = CreateProductUnderTestMock();\n            productMock.SetupGet(p => p.DataTokens).Returns(additionalDataTokens);\n            IDirectRouteFactory product = productMock.Object;\n\n            RouteEntry expectedEntry = CreateEntry();\n\n            TRouteDictionary dataTokens = null;\n            IDirectRouteBuilder builder = null;\n            builder = CreateBuilder(() =>\n            {\n                dataTokens = builder.DataTokens;\n                return null;\n            });\n\n            builder.DataTokens = existingDataTokens;\n\n            DirectRouteFactoryContext context = CreateContext((i) => builder);\n\n            // Act\n            RouteEntry ignore = product.CreateRoute(context);\n\n            // Assert\n            Assert.Same(existingDataTokens, dataTokens);\n            Assert.Equal(3, dataTokens.Count);\n            Assert.True(dataTokens.ContainsKey(existingDataTokenKey));\n            Assert.Same(existingDataTokenValue, dataTokens[existingDataTokenKey]);\n            Assert.True(dataTokens.ContainsKey(conflictingDataTokenKey));\n            Assert.Same(newConflictingDataTokenValue, dataTokens[conflictingDataTokenKey]);\n            Assert.True(dataTokens.ContainsKey(additionalDataTokenKey));\n            Assert.Same(additionalDataTokenValue, dataTokens[additionalDataTokenKey]);\n        }\n\n        [Fact]\n        public void CreateRoute_IfBuilderDataTokensIsNotNullAndDataTokensPropertyIsNull_UsesBuilderDataTokens()\n        {\n            // Arrange\n            TRouteDictionary existingDataTokens = new TRouteDictionaryConcrete();\n\n            Mock<RouteFactoryAttribute> productMock = CreateProductUnderTestMock();\n            productMock.SetupGet(p => p.DataTokens).Returns((TRouteDictionary)null);\n            IDirectRouteFactory product = productMock.Object;\n\n            RouteEntry expectedEntry = CreateEntry();\n\n            TRouteDictionary dataTokens = null;\n            IDirectRouteBuilder builder = null;\n            builder = CreateBuilder(() =>\n            {\n                dataTokens = builder.DataTokens;\n                return null;\n            });\n\n            builder.DataTokens = existingDataTokens;\n\n            DirectRouteFactoryContext context = CreateContext((i) => builder);\n\n            // Act\n            RouteEntry ignore = product.CreateRoute(context);\n\n            // Assert\n            Assert.Same(existingDataTokens, dataTokens);\n        }\n\n        [Fact]\n        public void AttributeUsage_IsAsSpecified()\n        {\n            // Act\n            AttributeUsageAttribute usage = (AttributeUsageAttribute)Attribute.GetCustomAttribute(\n                typeof(RouteFactoryAttribute), typeof(AttributeUsageAttribute));\n\n            // Assert\n            Assert.NotNull(usage);\n            Assert.Equal(AttributeTargets.Class | AttributeTargets.Method, usage.ValidOn);\n            Assert.False(usage.Inherited);\n            Assert.True(usage.AllowMultiple);\n        }\n\n        private static IDirectRouteBuilder CreateBuilder(Func<RouteEntry> build)\n        {\n            return new LambdaDirectRouteBuilder(build);\n        }\n\n        private static DirectRouteFactoryContext CreateContext(Func<string, IDirectRouteBuilder> createBuilder)\n        {\n            return new LambdaDirectRouteFactoryContext(createBuilder);\n        }\n\n        private static RouteEntry CreateEntry()\n        {\n#if ASPNETWEBAPI\n            TRoute route = new Mock<TRoute>(MockBehavior.Strict).Object;\n#else\n            TRoute route = new Mock<TRoute>(MockBehavior.Strict, null, null).Object;\n#endif\n            return new RouteEntry(\"IgnoreEntry\", route);\n        }\n\n        private static RouteFactoryAttribute CreateProductUnderTest()\n        {\n            return CreateProductUnderTest(\"IgnoreTemplate\");\n        }\n\n        private static RouteFactoryAttribute CreateProductUnderTest(string template)\n        {\n            return CreateProductUnderTestMock(template).Object;\n        }\n\n        private static Mock<RouteFactoryAttribute> CreateProductUnderTestMock()\n        {\n            return CreateProductUnderTestMock(\"IgnoreTemplate\");\n        }\n\n        private static Mock<RouteFactoryAttribute> CreateProductUnderTestMock(string template)\n        {\n            Mock<RouteFactoryAttribute> mock = new Mock<RouteFactoryAttribute>(template);\n            mock.CallBase = true;\n            return mock;\n        }\n\n        private class LambdaDirectRouteFactoryContext : DirectRouteFactoryContext\n        {\n            private readonly Func<string, IDirectRouteBuilder> _createBuilder;\n\n            public LambdaDirectRouteFactoryContext(Func<string, IDirectRouteBuilder> createBuilder)\n#if ASPNETWEBAPI\n                : base(null, new TActionDescriptor[] { new Mock<TActionDescriptor>().Object },\n                new Mock<IInlineConstraintResolver>(MockBehavior.Strict).Object,\n                targetIsAction: true)\n#else\n                : base(null, null, new TActionDescriptor[] { CreateStubActionDescriptor() },\n                new Mock<IInlineConstraintResolver>(MockBehavior.Strict).Object, targetIsAction: true)\n#endif\n            {\n                Contract.Assert(createBuilder != null);\n                _createBuilder = createBuilder;\n            }\n\n            internal override IDirectRouteBuilder CreateBuilderInternal(string template)\n            {\n                return _createBuilder.Invoke(template);\n            }\n\n#if !ASPNETWEBAPI\n            private static ActionDescriptor CreateStubActionDescriptor()\n            {\n                Mock<ActionDescriptor> mock = new Mock<TActionDescriptor>();\n                mock.Setup(m => m.ControllerDescriptor).Returns(new Mock<ControllerDescriptor>().Object);\n                return mock.Object;\n            }\n#endif\n        }\n\n        private class LambdaDirectRouteBuilder : DirectRouteBuilder\n        {\n            private readonly Func<RouteEntry> _build;\n\n            public LambdaDirectRouteBuilder(Func<RouteEntry> build)\n                : base(new TActionDescriptor[0], targetIsAction: true)\n            {\n                Contract.Assert(build != null);\n                _build = build;\n            }\n\n            public override RouteEntry Build()\n            {\n                return _build.Invoke();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Common/Routing/RoutePrecedenceTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n#if !ASPNETWEBAPI\nusing System.Web.Routing;\n#endif\nusing Microsoft.TestCommon;\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing\n#else\nnamespace System.Web.Mvc.Routing\n#endif\n{\n    public class RoutePrecedenceTests\n    {\n        [Theory]\n        [InlineData(\"Employees/{id}\", \"Employees/{id}\")]\n        [InlineData(\"abc\", \"def\")]\n        [InlineData(\"{x:alpha}\", \"{x:int}\")]\n        public void Compute_IsEqual(string xTemplate, string yTemplate)\n        {\n            // Arrange & Act\n            var xPrededence = Compute(xTemplate);\n            var yPrededence = Compute(yTemplate);\n\n            // Assert\n            Assert.Equal(xPrededence, yPrededence);\n        }\n\n        [Theory]\n        [InlineData(\"abc\", \"a{x}\")]\n        [InlineData(\"abc\", \"{x}c\")]\n        [InlineData(\"abc\", \"{x:int}\")]\n        [InlineData(\"abc\", \"{x}\")]\n        [InlineData(\"abc\", \"{*x}\")]\n        [InlineData(\"{x:int}\", \"{x}\")]\n        [InlineData(\"{x:int}\", \"{*x}\")]\n        [InlineData(\"a{x}\", \"{x}\")]\n        [InlineData(\"{x}c\", \"{x}\")]\n        [InlineData(\"a{x}\", \"{*x}\")]\n        [InlineData(\"{x}c\", \"{*x}\")]\n        [InlineData(\"{x}\", \"{*x}\")]\n        [InlineData(\"{*x:maxlength(10)}\", \"{*x}\")]\n        [InlineData(\"abc/def\", \"abc/{x:int}\")]\n        [InlineData(\"abc/def\", \"abc/{x}\")]\n        [InlineData(\"abc/def\", \"abc/{*x}\")]\n        [InlineData(\"abc/{x:int}\", \"abc/{x}\")]\n        [InlineData(\"abc/{x:int}\", \"abc/{*x}\")]\n        [InlineData(\"abc/{x}\", \"abc/{*x}\")]\n        [InlineData(\"{x}/{y:int}\", \"{x}/{y}\")]\n        public void Compute_IsLessThan(string xTemplate, string yTemplate)\n        {\n            // Arrange & Act\n            var xPrededence = Compute(xTemplate);\n            var yPrededence = Compute(yTemplate);\n\n            // Assert\n            Assert.True(xPrededence < yPrededence);\n        }\n\n        private static decimal Compute(string template)\n        {\n            DefaultInlineConstraintResolver resolver = new DefaultInlineConstraintResolver();\n#if ASPNETWEBAPI\n            HttpRouteValueDictionary defaults = new HttpRouteValueDictionary();\n            HttpRouteValueDictionary constraints = new HttpRouteValueDictionary();\n#else\n            RouteValueDictionary defaults = new RouteValueDictionary();\n            RouteValueDictionary constraints = new RouteValueDictionary();\n#endif\n            string standardRouteTemplate = InlineRouteTemplateParser.ParseRouteTemplate(template,\n                defaults, constraints, new DefaultInlineConstraintResolver());\n            var parsedRoute = RouteParser.Parse(standardRouteTemplate);\n            return RoutePrecedence.Compute(parsedRoute, constraints);\n        }\n    }\n}"
  },
  {
    "path": "test/Common/Routing/SubRouteCollectionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n#if !ASPNETWEBAPI\nusing System.Web.Routing;\n#endif\nusing Microsoft.TestCommon;\nusing Moq;\n\n#if ASPNETWEBAPI\nnamespace System.Web.Http.Routing\n#else\nnamespace System.Web.Mvc.Routing\n#endif\n{\n    public class SubRouteCollectionTest\n    {\n#if ASPNETWEBAPI\n        [Fact]\n        public void SubRouteCollection_Throws_OnDuplicateNamedRoute_WebAPI()\n        {\n            // Arrange\n            var collection = new SubRouteCollection();\n            var route1 = new HttpRoute(\"api/Person\");\n            var route2 = new HttpRoute(\"api/Car\");\n\n            collection.Add(new RouteEntry(\"route\", route1));\n\n            var expectedError =\n                \"A route named 'route' is already in the route collection. Route names must be unique.\\r\\n\\r\\n\" +\n                \"Duplicates:\" + Environment.NewLine +\n                \"api/Car\" + Environment.NewLine +\n                \"api/Person\";\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(() => collection.Add(new RouteEntry(\"route\", route2)), expectedError);\n        }\n#else\n        [Fact]\n        public void SubRouteCollection_Throws_OnDuplicateNamedRoute_MVC()\n        {\n            // Arrange\n            var collection = new SubRouteCollection();\n            var route1 = new Route(\"Home/Index\", new Mock<IRouteHandler>().Object);\n            var route2 = new Route(\"Person/Index\", new Mock<IRouteHandler>().Object);\n\n            collection.Add(new RouteEntry(\"route\", route1));\n\n            var expectedError =\n                \"A route named 'route' is already in the route collection. Route names must be unique.\\r\\n\\r\\n\" +\n                \"Duplicates:\" + Environment.NewLine +\n                \"Person/Index\" + Environment.NewLine +\n                \"Home/Index\";\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(() => collection.Add(new RouteEntry(\"route\", route2)), expectedError);\n        }\n#endif\n    }\n}\n"
  },
  {
    "path": "test/Common/TaskHelpersExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Threading.Tasks\n{\n    public class TaskHelpersExtensionsTest\n    {\n        // ----------------------------------------------------------------\n        //   Task<object> Task<T>.CastToObject()\n\n        [Fact, ForceGC]\n        public async Task ConvertFromTaskOfStringShouldSucceed()\n        {\n            // Arrange\n            var task = Task.FromResult(\"StringResult\")\n                .CastToObject();\n\n            // Act\n            var result = await task;\n\n            // Assert\n            Assert.Equal(TaskStatus.RanToCompletion, task.Status);\n            Assert.Equal(\"StringResult\", (string)result);\n        }\n\n        [Fact, ForceGC]\n        public async Task ConvertFromTaskOfIntShouldSucceed()\n        {\n            // Arrange\n            var task = Task.FromResult(123)\n                .CastToObject();\n\n            // Act\n            var result = await task;\n\n            // Assert\n            Assert.Equal(TaskStatus.RanToCompletion, task.Status);\n            Assert.Equal(123, (int)result);\n        }\n\n        [Fact, ForceGC]\n        public async Task ConvertFromFaultedTaskOfObjectShouldBeHandled()\n        {\n            // Arrange\n            var task = TaskHelpers.FromError<object>(new InvalidOperationException())\n                .CastToObject();\n\n            // Act & Assert\n            await Assert.ThrowsAsync<InvalidOperationException>(() => task);\n            Assert.Equal(TaskStatus.Faulted, task.Status);\n        }\n\n        [Fact, ForceGC]\n        public async Task ConvertFromCancelledTaskOfStringShouldBeHandled()\n        {\n            // Arrange\n            var task = TaskHelpers.Canceled<string>()\n                .CastToObject();\n\n            // Act & Assert\n            await Assert.ThrowsAsync<TaskCanceledException>(() => task);\n            Assert.Equal(TaskStatus.Canceled, task.Status);\n        }\n\n        // ----------------------------------------------------------------\n        //   Task<object> Task.CastToObject()\n\n        [Fact, ForceGC]\n        public async Task ConvertFromTaskShouldSucceed()\n        {\n            // Arrange\n            var task = TaskHelpers.Completed()\n                .CastToObject();\n\n            // Act\n            var result = await task;\n\n            // Assert\n            Assert.Equal(TaskStatus.RanToCompletion, task.Status);\n            Assert.Null(result);\n        }\n\n        [Fact, ForceGC]\n        public async Task ConvertFromFaultedTaskShouldBeHandled()\n        {\n            // Arrange\n            var task = TaskHelpers.FromError(new InvalidOperationException())\n                .CastToObject();\n\n            // Act & Assert\n            await Assert.ThrowsAsync<InvalidOperationException>(() => task);\n            Assert.Equal(TaskStatus.Faulted, task.Status);\n        }\n\n        [Fact, ForceGC]\n        public async Task ConvertFromCancelledTaskShouldBeHandled()\n        {\n            // Arrange\n            var task = TaskHelpers.Canceled()\n                .CastToObject();\n\n            // Act & Assert\n            await Assert.ThrowsAsync<TaskCanceledException>(() => task);\n            Assert.Equal(TaskStatus.Canceled, task.Status);\n        }\n\n        // -----------------------------------------------------------------\n        //  bool Task.TryGetResult(Task<TResult>, out TResult)\n\n        [Fact, ForceGC]\n        public void TryGetResult_CompleteTask_ReturnsTrueAndGivesResult()\n        {\n            // Arrange\n            var task = Task.FromResult(42);\n\n            // Act\n            int value;\n            bool result = task.TryGetResult(out value);\n\n            // Assert\n            Assert.True(result);\n            Assert.Equal(42, value);\n        }\n\n        [Fact, ForceGC]\n        public void TryGetResult_FaultedTask_ReturnsFalse()\n        {\n            // Arrange\n            var task = TaskHelpers.FromError<int>(new Exception());\n\n            // Act\n            int value;\n            bool result = task.TryGetResult(out value);\n\n            // Assert\n            Assert.False(result);\n            var ex = task.Exception; // Observe the task exception\n        }\n\n        [Fact, ForceGC]\n        public void TryGetResult_CanceledTask_ReturnsFalse()\n        {\n            // Arrange\n            var task = TaskHelpers.Canceled<int>();\n\n            // Act\n            int value;\n            bool result = task.TryGetResult(out value);\n\n            // Assert\n            Assert.False(result);\n        }\n\n        [Fact, ForceGC]\n        public Task TryGetResult_IncompleteTask_ReturnsFalse()\n        {\n            // Arrange\n            var incompleteTask = new Task<int>(() => 42);\n\n            // Act\n            int value;\n            bool result = incompleteTask.TryGetResult(out value);\n\n            // Assert\n            Assert.False(result);\n\n            incompleteTask.Start();\n            return incompleteTask;  // Make sure the task gets observed\n        }\n    }\n}\n"
  },
  {
    "path": "test/Common/TaskHelpersTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Threading.Tasks\n{\n    public class TaskHelpersTest\n    {\n        // -----------------------------------------------------------------\n        //  TaskHelpers.Canceled\n\n        [Fact]\n        public void Canceled_ReturnsCanceledTask()\n        {\n            Task result = TaskHelpers.Canceled();\n\n            Assert.NotNull(result);\n            Assert.True(result.IsCanceled);\n        }\n\n        // -----------------------------------------------------------------\n        //  TaskHelpers.Canceled<T>\n\n        [Fact]\n        public void Canceled_Generic_ReturnsCanceledTask()\n        {\n            Task<string> result = TaskHelpers.Canceled<string>();\n\n            Assert.NotNull(result);\n            Assert.True(result.IsCanceled);\n        }\n\n        // -----------------------------------------------------------------\n        //  TaskHelpers.Completed\n\n        [Fact]\n        public void Completed_ReturnsCompletedTask()\n        {\n            Task result = TaskHelpers.Completed();\n\n            Assert.NotNull(result);\n            Assert.Equal(TaskStatus.RanToCompletion, result.Status);\n        }\n\n        // -----------------------------------------------------------------\n        //  TaskHelpers.FromError\n\n        [Fact]\n        public void FromError_ReturnsFaultedTaskWithGivenException()\n        {\n            var exception = new Exception();\n\n            Task result = TaskHelpers.FromError(exception);\n\n            Assert.NotNull(result);\n            Assert.True(result.IsFaulted);\n            Assert.Same(exception, result.Exception.InnerException);\n        }\n\n        // -----------------------------------------------------------------\n        //  TaskHelpers.FromError<T>\n\n        [Fact]\n        public void FromError_Generic_ReturnsFaultedTaskWithGivenException()\n        {\n            var exception = new Exception();\n\n            Task<string> result = TaskHelpers.FromError<string>(exception);\n\n            Assert.NotNull(result);\n            Assert.True(result.IsFaulted);\n            Assert.Same(exception, result.Exception.InnerException);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Common/TypeExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing Microsoft.TestCommon;\n\nnamespace System\n{\n    public class TypeExtensionsTest\n    {\n        [Theory]\n        [InlineData(typeof(int), false)]\n        [InlineData(typeof(string), true)]\n        [InlineData(typeof(DateTime), false)]\n        [InlineData(typeof(int?), true)]\n        [InlineData(typeof(IEnumerable), true)]\n        [InlineData(typeof(int[]), true)]\n        [InlineData(typeof(string[]), true)]\n        public void IsNullable_Returns_ExpectedValue(Type type, bool expectedResult)\n        {\n            Assert.Equal(expectedResult, type.IsNullable());\n        }\n    }\n}\n"
  },
  {
    "path": "test/Common/UriQueryUtilityTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Net.Http.Formatting;\nusing System.Text;\nusing System.Web.Http;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http\n{\n    public class WebUtilityTest\n    {\n        public static TheoryDataSet<string, string, string> UriQueryData\n        {\n            get\n            {\n                return UriQueryTestData.UriQueryData;\n            }\n        }\n\n        [Fact]\n        public void TypeIsCorrect()\n        {\n            Assert.Type.HasProperties(typeof(WebUtility),\n                TypeAssert.TypeProperties.IsStatic | TypeAssert.TypeProperties.IsPublicVisibleClass);\n        }\n\n        [Fact]\n        public void UrlEncode_ReturnsNull()\n        {\n            Assert.Null(WebUtility.UrlEncode(null));\n        }\n\n        [Fact]\n        public void UrlDecode_ReturnsNull()\n        {\n            Assert.Null(WebUtility.UrlDecode(null));\n        }\n\n        [Fact]\n        public void UrlDecode_ParsesEmptySegmentsCorrectly()\n        {\n            int iterations = 16;\n            List<string> segments = new List<string>();\n\n            for (int index = 1; index < iterations; index++)\n            {\n                segments.Add(\"&\");\n                string query = string.Join(\"\", segments);\n                NameValueCollection result = ParseQueryString(query);\n                Assert.NotNull(result);\n\n                // Because this is a NameValueCollection, the same name appears only once\n                Assert.Single(result);\n\n                // Values should be a comma separated list of empty strings\n                string[] values = result[\"\"].Split(new char[] { ',' });\n\n                // We expect length+1 segment as the final '&' counts as a segment\n                Assert.Equal(index + 1, values.Length);\n                foreach (var value in values)\n                {\n                    Assert.Equal(\"\", value);\n                }\n            }\n        }\n\n        [Theory]\n        [InlineData(\"N\", \"N\", \"\")]\n        [InlineData(\"%26\", \"&\", \"\")]\n        [InlineData(\"foo=%u0026\", \"foo\", \"%u0026\")]\n        [PropertyData(\"UriQueryData\")]\n        public void UrlDecode_ParsesCorrectly(string segment, string resultName, string resultValue)\n        {\n            int iterations = 16;\n            List<string> segments = new List<string>();\n\n            for (int index = 1; index < iterations; index++)\n            {\n                segments.Add(segment);\n                string query = CreateQuery(segments.ToArray());\n                NameValueCollection result = ParseQueryString(query);\n                Assert.NotNull(result);\n\n                // Because this is a NameValueCollection, the same name appears only once\n                Assert.Single(result);\n\n                // Values should be a comma separated list of resultValue\n                string[] values = result[resultName].Split(new char[] { ',' });\n                Assert.Equal(index, values.Length);\n                foreach (var value in values)\n                {\n                    Assert.Equal(resultValue, value);\n                }\n            }\n        }\n\n        private static string CreateQuery(params string[] segments)\n        {\n            StringBuilder buffer = new StringBuilder();\n            bool first = true;\n            foreach (string segment in segments)\n            {\n                if (first)\n                {\n                    first = false;\n                }\n                else\n                {\n                    buffer.Append('&');\n                }\n\n                buffer.Append(segment);\n            }\n\n            return buffer.ToString();\n        }\n\n        private static NameValueCollection ParseQueryString(string query)\n        {\n            return new FormDataCollection(query).ReadAsNameValueCollection();\n        }\n    }\n}"
  },
  {
    "path": "test/Directory.Build.props",
    "content": "<Project>\n  <Import Project=\"..\\Directory.Build.props\" />\n\n  <PropertyGroup>\n    <IsPackable>false</IsPackable>\n    <IsTestProject>true</IsTestProject>\n    <TargetFrameworkVersion\n        Condition=\" '$(MSBuildProjectName)' != 'Microsoft.TestCommon' AND\n          '$(MSBuildProjectName)' != 'System.Net.Http.Formatting.ns1_3.Test' AND\n          '$(MSBuildProjectName)' != 'System.Net.Http.Formatting.ns2_0.Test' \">v4.6.2</TargetFrameworkVersion>\n  </PropertyGroup>\n</Project>\n"
  },
  {
    "path": "test/Directory.Build.targets",
    "content": "<Project>\n  <Import Project=\"..\\Directory.Build.targets\" />\n  <Import Project=\"..\\packages\\xunit.runner.msbuild.2.4.2\\**\\xunit.runner.msbuild.props\"\n      Condition=\"$(IsTestProject) and '$(MSBuildRuntimeType)' != 'Core' and '$(TargetFrameworkIdentifier)' == '.NETFramework'\" />\n\n  <Target Name=\"Test\" DependsOnTargets=\"_TestWithVSTest;_TestWithDotnetTest;_TestWithRunner\" />\n\n  <!-- Building with `dotnet msbuild`: Use VSTest target. -->\n  <Target\n    Name=\"_TestWithVSTest\"\n    Condition=\"$(IsTestProject) and '$(MSBuildRuntimeType)' == 'Core'\">\n\n    <MSBuild Projects=\"$(MSBuildProjectFullPath)\" Targets=\"VSTest\" Properties=\"VSTestNoBuild=true\" />\n  </Target>\n\n  <!-- Building with `msbuild` and in outer build or building .NET Core: Use `dotnet test`. -->\n  <Target\n    Name=\"_TestWithDotnetTest\"\n    Condition=\"$(IsTestProject) and '$(MSBuildRuntimeType)' != 'Core' and '$(TargetFrameworkIdentifier)' != '.NETFramework'\">\n\n    <Exec Command='dotnet test --no-restore --no-build --verbosity minimal --configuration $(Configuration) \"$(MSBuildProjectFullPath)\"'/>\n  </Target>\n\n  <!-- Building with `msbuild`, in inner build, and building .NET Framework: Use xUnit MSBuild runner. -->\n  <Target\n    Name=\"_TestWithRunner\"\n    Condition=\"$(IsTestProject) and '$(MSBuildRuntimeType)' != 'Core' and '$(TargetFrameworkIdentifier)' == '.NETFramework'\">\n\n    <ItemGroup Condition=\" '@(TestAssembly)' == '' \">\n      <TestAssembly Include=\"$(TargetPath)\" />\n    </ItemGroup>\n    <xunit Assemblies=\"@(TestAssembly)\" />\n  </Target>\n</Project>\n"
  },
  {
    "path": "test/Microsoft.AspNet.Facebook.Test/App.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n  <appSettings>\n    <add key=\"Facebook:AppId\" value=\"123456\" />\n    <add key=\"Facebook:AppSecret\" value=\"abcdefg\" />\n    <add key=\"Facebook:AppNamespace\" value=\"MyApp\" />\n    <add key=\"Facebook:AppUrl\" value=\"https://apps.newfacebook.example.com/myapp\" />\n    <add key=\"Facebook:AuthorizationRedirectPath\" value=\"~/Authorize/Index\" />\n    <add key=\"Facebook:CannotCreateCookiesRedirectPath\" value=\"~/NoCookies/Index\" />\n  </appSettings>\n</configuration>"
  },
  {
    "path": "test/Microsoft.AspNet.Facebook.Test/DefaultFacebookClientProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Facebook;\nusing Microsoft.AspNet.Facebook.Providers;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.AspNet.Facebook.Test\n{\n    public class DefaultFacebookClientProviderTest\n    {\n        [Fact]\n        public void Constructor_ThrowsArgumentNullException()\n        {\n            Assert.ThrowsArgumentNull(() => new DefaultFacebookClientProvider(null), \"configuration\");\n        }\n\n        [Fact]\n        public void CreateClient_ReturnsClientWithAppIdAndAppSecret()\n        {\n            string appId = \"654321\";\n            string appSecret = \"abcdefg123\";\n            FacebookConfiguration config = new FacebookConfiguration\n            {\n                AppId = appId,\n                AppSecret = appSecret\n            };\n            DefaultFacebookClientProvider clientProvider = new DefaultFacebookClientProvider(config);\n            FacebookClient client = clientProvider.CreateClient();\n\n            Assert.Equal(appId, client.AppId);\n            Assert.Equal(appSecret, client.AppSecret);\n        }\n    }\n}"
  },
  {
    "path": "test/Microsoft.AspNet.Facebook.Test/DefaultFacebookPermissionServiceTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.AspNet.Facebook.Providers;\nusing Microsoft.AspNet.Facebook.Test.Helpers;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.AspNet.Facebook.Test\n{\n    public class DefaultFacebookPermissionServiceTest\n    {\n        [Fact]\n        public void Constructor_ThrowsArgumentNullException()\n        {\n            Assert.ThrowsArgumentNull(() => new DefaultFacebookPermissionService(null), \"configuration\");\n        }\n\n        [Fact]\n        public void GetUserPermissions_ThrowsArgumentNullException()\n        {\n            FacebookConfiguration config = new FacebookConfiguration();\n            config.ClientProvider = new DefaultFacebookClientProvider(config);\n            DefaultFacebookPermissionService permissionService = new DefaultFacebookPermissionService(config);\n\n            Assert.ThrowsArgumentNull(() => permissionService.GetUserPermissions(null, \"accessToken\"), \"userId\");\n            Assert.ThrowsArgumentNull(() => permissionService.GetUserPermissions(\"userId\", null), \"accessToken\");\n        }\n\n        [Fact]\n        public void GetUserPermissions_CallsGetOnFacebookClientWithExpectedPath()\n        {\n            LocalFacebookClient localClient = new LocalFacebookClient();\n            FacebookConfiguration config = MockHelpers.CreateConfiguration(localClient);\n            DefaultFacebookPermissionService permissionService = new DefaultFacebookPermissionService(config);\n\n            permissionService.GetUserPermissions(\"123456\", \"sampleAccessToken\");\n\n            Assert.Equal(\"me/permissions\", localClient.Path);\n        }\n    }\n}"
  },
  {
    "path": "test/Microsoft.AspNet.Facebook.Test/FacebookAuthorizeAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.AspNet.Facebook.Test\n{\n    public class FacebookAuthorizeAttributeTest\n    {\n        [Fact]\n        public void Constructor_ThrowsArgumentNullException()\n        {\n            Assert.ThrowsArgumentNull(() => new FacebookAuthorizeAttribute(null), \"permissions\");\n        }\n\n        [Fact]\n        public void Permissions_ReturnsExpectedValues()\n        {\n            string[] permissions = new[] { \"email\", \"user_likes\", \"friends_likes\" };\n            FacebookAuthorizeAttribute authorizeAttribute = new FacebookAuthorizeAttribute(permissions);\n            HashSet<string> permissionSet = new HashSet<string>(permissions);\n\n            Assert.True(permissionSet.SetEquals(authorizeAttribute.Permissions));\n        }\n    }\n}"
  },
  {
    "path": "test/Microsoft.AspNet.Facebook.Test/FacebookAuthorizeFilterHookTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Web;\nusing System.Web.Mvc;\nusing Microsoft.AspNet.Facebook.Authorization;\nusing Microsoft.AspNet.Facebook.Test.Helpers;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.AspNet.Facebook.Test\n{\n    public class FacebookAuthorizeFilterHookTest\n    {\n        [Theory]\n        [InlineData(\"~/home/cannotcreatecookies\", \"https://apps.facebook.com/DefaultAppId/home/cannotcreatecookies\")]\n        [InlineData(null, \"https://www.facebook.com/\")]\n        public void OnAuthorization_CannotCreateCookiesHookRedirectsToConfigValueOrDefault(\n            string cannotCreateCookiesRedirectPath,\n            string expectedRedirectPath)\n        {\n            // Arrange\n            var config = BuildConfiguration(\"~/home/permissions\", cannotCreateCookiesRedirectPath);\n            var authorizeFilter = new FacebookAuthorizeFilter(config);\n            var context = BuildSignedAuthorizationContext(\"http://contoso.com?__fb_mps=true\", \"email\");\n\n            // Act\n            authorizeFilter.OnAuthorization(context);\n            var result = context.Result as JavaScriptRedirectResult;\n\n            // Assert\n            Assert.Equal(result.RedirectUrl.AbsoluteUri, new Uri(expectedRedirectPath).AbsoluteUri);\n        }\n\n        [Fact]\n        public void OnAuthorization_OnlyTriggersCannotCreateCookiesHook()\n        {\n            // Arrange\n            var config = BuildConfiguration(\"~/home/permissions\");\n            var authorizeFilter = new CustomDefaultAuthorizeFilter(config);\n            var context = BuildSignedAuthorizationContext(\"http://contoso.com?__fb_mps=true\", \"email\");\n\n            // Act\n            authorizeFilter.OnAuthorization(context);\n\n            // Assert\n            Assert.True(authorizeFilter.CannotCreateCookiesHookTriggered);\n            Assert.False(authorizeFilter.PermissionPromptHookTriggered);\n            Assert.False(authorizeFilter.DeniedPermissionPromptHookTriggered);\n        }\n\n        [Theory]\n        [InlineData(\"http://contoso.com?__fb_mps=true\", \"email\", true)]\n        [InlineData(\"http://contoso.com\", \"email\", false)]\n        [InlineData(\"http://contoso.com?__fb_mps=true\", null, false)]\n        public void OnAuthorization_TriggersCannotCreateCookiesHook(string requestUrl,\n                                                                    string permission,\n                                                                    bool expectedTrigger)\n        {\n            // Arrange\n            var config = BuildConfiguration(\"~/home/permissions\");\n            var authorizeFilter = new CustomDefaultAuthorizeFilter(config);\n            var context = BuildSignedAuthorizationContext(requestUrl, permission);\n\n            // Act\n            authorizeFilter.OnAuthorization(context);\n\n            // Assert\n            Assert.Equal(expectedTrigger, authorizeFilter.CannotCreateCookiesHookTriggered);\n        }\n\n        [Theory]\n        [InlineData(\"http://contoso.com\", \"email\", true)]\n        [InlineData(\"http://contoso.com?error=access_denied\", \"email\", false)]\n        [InlineData(\"http://contoso.com?error=access_denied\", null, false)]\n        public void OnAuthorization_TriggersPreHookPriorToPermissionsDialog(string requestUrl,\n                                                                            string permission,\n                                                                            bool expectedTrigger)\n        {\n            // Arrange\n            var config = BuildConfiguration(\"~/home/permissions\");\n            var authorizeFilter = new CustomDefaultAuthorizeFilter(config);\n            var context = BuildSignedAuthorizationContext(requestUrl, permission);\n\n            // Act\n            authorizeFilter.OnAuthorization(context);\n\n            // Assert\n            Assert.Equal(expectedTrigger, authorizeFilter.PermissionPromptHookTriggered);\n        }\n\n        [Theory]\n        [InlineData(\"http://contoso.com\", \"email\", true)]\n        [InlineData(\"http://contoso.com?error=access_denied\", \"email\", false)]\n        [InlineData(\"http://contoso.com?error=access_denied\", null, false)]\n        public void OnAuthorization_TriggersDeniedHook(string requestUrl, string permission, bool expectedTrigger)\n        {\n            // Arrange\n            var config = BuildConfiguration(\"~/home/permissions\");\n            var authorizeFilter = new CustomDefaultAuthorizeFilter(config);\n            var persistedCookies = new HttpCookieCollection();\n            persistedCookies.Add(\n                new HttpCookie(\n                    PermissionHelper.RequestedPermissionCookieName, permission ?? string.Empty));\n            var context = BuildSignedAuthorizationContext(requestUrl, permission, persistedCookies);\n\n            // Act\n            authorizeFilter.OnAuthorization(context);\n\n            // Assert\n            Assert.Equal(expectedTrigger, authorizeFilter.DeniedPermissionPromptHookTriggered);\n        }\n\n        [Theory]\n        [InlineData(\"http://contoso.com\", \"email\", \"email\", true)]\n        [InlineData(\"http://contoso.com\", \"email\", \"foo\", false)]\n        [InlineData(\"http://contoso.com?error=access_denied\", \"email\", \"email\", false)]\n        [InlineData(\"http://contoso.com?error=access_denied\", \"email\", \"foo\", false)]\n        [InlineData(\"http://contoso.com?error=access_denied\", null, \"foo\", false)]\n        public void OnAuthorization_TriggersDeniedHookWithRevokedPermissions(string requestUrl,\n                                                                             string permission,\n                                                                             string permissionInStatus,\n                                                                             bool expectedTrigger)\n        {\n            var rawPermissionsStatus = new Dictionary<string, string>\n            {\n                { \"permission\", permissionInStatus },\n                { \"status\", \"declined\" },\n            };\n\n            var data = new List<IDictionary<string, string>>(new[] { rawPermissionsStatus });\n\n            // Arrange\n            var config = BuildConfiguration(\"~/home/permissions\", userPermissionsStatus:\n                new PermissionsStatus(data));\n            var authorizeFilter = new CustomDefaultAuthorizeFilter(config);\n            var context = BuildSignedAuthorizationContext(requestUrl, permission);\n\n            // Act\n            authorizeFilter.OnAuthorization(context);\n\n            // Assert\n            Assert.Equal(expectedTrigger, authorizeFilter.DeniedPermissionPromptHookTriggered);\n        }\n\n        [Theory]\n        [InlineData(\"http://contoso.com\", \"email\", true)]\n        [InlineData(\"http://contoso.com?error=access_denied\", \"email\", false)]\n        [InlineData(\"http://contoso.com?error=access_denied\", null, false)]\n        public void OnAuthorization_TriggersDeniedHookAfterPersistingRequestedPermissions(string requestUrl,\n                                                                                          string permission,\n                                                                                          bool expectedTrigger)\n        {\n            // Arrange\n            var config = BuildConfiguration(\"~/home/permissions\");\n            var authorizeFilter = new CustomDefaultAuthorizeFilter(config);\n            var context = BuildSignedAuthorizationContext(requestUrl, permission);\n\n            // Act\n            authorizeFilter.OnAuthorization(context);\n\n            // Here we're acting like a browser and adding the responses cookies to the \"next\" request's cookies\n            var responseCookies = context.HttpContext.Response.Cookies;\n            foreach (var cookieName in responseCookies.AllKeys)\n            {\n                context.HttpContext.Request.Cookies.Add(responseCookies[cookieName]);\n            }\n\n            // Assert\n            Assert.False(authorizeFilter.DeniedPermissionPromptHookTriggered);\n\n            // Act 2\n            // We're making a \"second\" request essentially\n            authorizeFilter.OnAuthorization(context);\n\n            // Assert 2\n            Assert.Equal(expectedTrigger, authorizeFilter.DeniedPermissionPromptHookTriggered);\n        }\n\n        [Fact]\n        public void OnAuthorization_CannotCreateCookiesHookNullFlows()\n        {\n            // Arrange\n            var config = BuildConfiguration(\"~/home/permissions\");\n            var authorizeFilter = new CustomInvalidAuthorizeFilter(config);\n            var context = BuildSignedAuthorizationContext(\"http://contoso.com?__fb_mps=true\", \"email\");\n\n            // Act\n            authorizeFilter.OnAuthorization(context);\n\n            // Assert\n            Assert.Null(context.Result);\n        }\n\n        [Fact]\n        public void OnAuthorization_PreHookNullTreatedLikeIgnoreResult()\n        {\n            // Arrange\n            var config = BuildConfiguration(\"~/home/permissions\");\n            var authorizeFilter = new CustomInvalidAuthorizeFilter(config);\n            var context = BuildSignedAuthorizationContext(\"http://contoso.com\", \"email\");\n\n            // Act\n            authorizeFilter.OnAuthorization(context);\n\n            // Assert\n            Assert.Null(context.Result);\n        }\n\n        [Fact]\n        public void OnAuthorization_DeniedHookNullTreatedLikeIgnoreResult()\n        {\n            // Arrange\n            var config = BuildConfiguration(\"~/home/permissions\");\n            var authorizeFilter = new CustomInvalidAuthorizeFilter(config);\n            var persistedCookies = new HttpCookieCollection();\n            persistedCookies.Add(\n                new HttpCookie(\n                    PermissionHelper.RequestedPermissionCookieName, \"email\"));\n            var context = BuildSignedAuthorizationContext(\"http://contoso.com\", \"email\", persistedCookies);\n\n            // Act\n            authorizeFilter.OnAuthorization(context);\n\n            // Assert\n            Assert.Null(context.Result);\n        }\n\n        [Fact]\n        public void OnAuthorization_CannotCreateCookiesHookCustomActionResultIsContextsResult()\n        {\n            // Arrange\n            var tempUrl = \"http://contoso.com?__fb_mps=true\";\n            var config = BuildConfiguration(\"~/home/permissions\");\n            var cannotCreateCookiesHookResult = new RedirectResult(tempUrl);\n            var authorizeFilter = new CustomReturningAuthorizeFilter(config,\n                                                                     cannotCreateCookiesHookResult,\n                                                                     new RedirectResult(tempUrl),\n                                                                     new RedirectResult(tempUrl));\n            var context = BuildSignedAuthorizationContext(tempUrl, \"email\");\n\n            // Act\n            authorizeFilter.OnAuthorization(context);\n\n            // Assert\n            Assert.Equal(cannotCreateCookiesHookResult, context.Result);\n        }\n\n        [Fact]\n        public void OnAuthorization_PreHookCustomActionResultIsContextsResult()\n        {\n            // Arrange\n            var tempUrl = \"http://contoso.com\";\n            var config = BuildConfiguration(\"~/home/permissions\");\n            var preHookResult = new RedirectResult(tempUrl);\n            var authorizeFilter = new CustomReturningAuthorizeFilter(config,\n                                                                     new RedirectResult(tempUrl),\n                                                                     preHookResult,\n                                                                     new RedirectResult(tempUrl));\n            var context = BuildSignedAuthorizationContext(tempUrl, \"email\");\n\n            // Act\n            authorizeFilter.OnAuthorization(context);\n\n            // Assert\n            Assert.Equal(preHookResult, context.Result);\n        }\n\n        [Fact]\n        public void OnAuthorization_DeniedHookCustomActionResultIsContextsResult()\n        {\n            // Arrange\n            var tempUrl = \"http://contoso.com\";\n            var config = BuildConfiguration(\"~/home/permissions\");\n            var deniedHookResult = new RedirectResult(tempUrl);\n            var authorizeFilter = new CustomReturningAuthorizeFilter(config,\n                                                                     new RedirectResult(tempUrl),\n                                                                     new RedirectResult(tempUrl),\n                                                                     deniedHookResult);\n            var persistedCookies = new HttpCookieCollection();\n            persistedCookies.Add(\n                new HttpCookie(\n                    PermissionHelper.RequestedPermissionCookieName, \"email\"));\n            var context = BuildSignedAuthorizationContext(tempUrl, \"email\", persistedCookies);\n\n            // Act\n            authorizeFilter.OnAuthorization(context);\n\n            // Assert\n            Assert.Equal(deniedHookResult, context.Result);\n        }\n\n        // Helper methods and classes\n        private FacebookConfiguration BuildConfiguration(string authorizationRedirectPath,\n                                                         string cannotCreateCookiesRedirectPath = null,\n                                                         PermissionsStatus userPermissionsStatus = null)\n        {\n            var client = MockHelpers.CreateFacebookClient();\n            var permissionService = MockHelpers.CreatePermissionService(new[] { \"\" }, userPermissionsStatus);\n            var config = MockHelpers.CreateConfiguration(client, permissionService);\n            config.AuthorizationRedirectPath = authorizationRedirectPath;\n\n            if (cannotCreateCookiesRedirectPath != null)\n            {\n                config.CannotCreateCookieRedirectPath = cannotCreateCookiesRedirectPath;\n            }\n\n            return config;\n        }\n\n        private AuthorizationContext BuildSignedAuthorizationContext(string requestUrl,\n                                                                     string permission,\n                                                                     HttpCookieCollection requestCookies = null)\n        {\n            var permissions = permission == null ? new string[0] : new string[] { permission };\n\n            var requestUri = new Uri(requestUrl);\n\n            var context = new AuthorizationContext(\n                MockHelpers.CreateControllerContext(new NameValueCollection\n                {\n                    {\"signed_request\", \"exampleSignedRequest\"}\n                },\n                HttpUtility.ParseQueryString(requestUri.Query),\n                requestUri,\n                requestCookies),\n                MockHelpers.CreateActionDescriptor(new[] { new FacebookAuthorizeAttribute(permissions) }));\n\n            return context;\n        }\n\n        private class CustomInvalidAuthorizeFilter : FacebookAuthorizeFilter\n        {\n            public CustomInvalidAuthorizeFilter(FacebookConfiguration config)\n                : base(config)\n            { }\n\n            protected override void OnCannotCreateCookies(PermissionContext context)\n            {\n                context.Result = null;\n            }\n\n            protected override void OnPermissionPrompt(PermissionContext context)\n            {\n                context.Result = null;\n            }\n\n            protected override void OnDeniedPermissionPrompt(PermissionContext context)\n            {\n                context.Result = null;\n            }\n        }\n\n        private class CustomDefaultAuthorizeFilter : FacebookAuthorizeFilter\n        {\n            public CustomDefaultAuthorizeFilter(FacebookConfiguration config)\n                : base(config)\n            { }\n\n            public bool CannotCreateCookiesHookTriggered { get; private set; }\n            public bool PermissionPromptHookTriggered { get; private set; }\n            public bool DeniedPermissionPromptHookTriggered { get; private set; }\n\n            protected override void OnCannotCreateCookies(PermissionContext context)\n            {\n                CannotCreateCookiesHookTriggered = true;\n\n                base.OnCannotCreateCookies(context);\n            }\n\n            protected override void OnPermissionPrompt(PermissionContext context)\n            {\n                PermissionPromptHookTriggered = true;\n\n                base.OnPermissionPrompt(context);\n            }\n\n            protected override void OnDeniedPermissionPrompt(PermissionContext context)\n            {\n                DeniedPermissionPromptHookTriggered = true;\n\n                base.OnDeniedPermissionPrompt(context);\n            }\n        }\n\n        private class CustomReturningAuthorizeFilter : FacebookAuthorizeFilter\n        {\n            private ActionResult _cannotCreateCookieResult;\n            private ActionResult _promptPermissionHookResult;\n            private ActionResult _deniedPermissionPromptHookResult;\n\n            public CustomReturningAuthorizeFilter(FacebookConfiguration config,\n                                                  ActionResult cannotCreateCookieResult,\n                                                  ActionResult promptPermissionHookResult,\n                                                  ActionResult deniedPermissionPromptHookResult)\n                : base(config)\n            {\n                _cannotCreateCookieResult = cannotCreateCookieResult;\n                _promptPermissionHookResult = promptPermissionHookResult;\n                _deniedPermissionPromptHookResult = deniedPermissionPromptHookResult;\n            }\n\n            protected override void OnCannotCreateCookies(PermissionContext context)\n            {\n                context.Result = _cannotCreateCookieResult;\n            }\n\n            protected override void OnPermissionPrompt(PermissionContext context)\n            {\n                context.Result = _promptPermissionHookResult;\n            }\n\n            protected override void OnDeniedPermissionPrompt(PermissionContext context)\n            {\n                context.Result = _deniedPermissionPromptHookResult;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.AspNet.Facebook.Test/FacebookAuthorizeFilterTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Specialized;\nusing System.Web;\nusing System.Web.Mvc;\nusing Facebook;\nusing Microsoft.AspNet.Facebook.Authorization;\nusing Microsoft.AspNet.Facebook.Client;\nusing Microsoft.AspNet.Facebook.Providers;\nusing Microsoft.AspNet.Facebook.Test.Helpers;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace Microsoft.AspNet.Facebook.Test\n{\n    public class FacebookAuthorizeFilterTest\n    {\n        [Fact]\n        public void AddCookieVerificationQuery_AddsQueryParams()\n        {\n            // Arrange\n            var collection = new NameValueCollection();\n            var filter = new CustomAuthorizeFilter();\n\n            // Act\n            filter.ExposedAddCookieVerificationQuery(collection);\n\n            // Assert\n            Assert.NotEmpty(collection);\n        }\n\n        [Fact]\n        public void Constructor_ThrowsArgumentNullException()\n        {\n            Assert.ThrowsArgumentNull(\n                () => new FacebookAuthorizeFilter(null),\n                \"config\");\n        }\n\n        [Fact]\n        public void OnAuthorization_ThrowsArgumentNullException()\n        {\n            FacebookConfiguration config = MockHelpers.CreateConfiguration();\n            FacebookAuthorizeFilter authorizeFilter = new FacebookAuthorizeFilter(config);\n            Assert.ThrowsArgumentNull(\n                () => authorizeFilter.OnAuthorization(null),\n                \"filterContext\");\n        }\n\n        [Fact]\n        public void CreateRedirectResult_StringEncodesTheRedirectUrl()\n        {\n            Uri uri = new Uri(\"http://example.com?query=4'; alert('hello world')\");\n            FacebookConfiguration config = MockHelpers.CreateConfiguration();\n            FacebookAuthorizeFilter authorizeFilter = new FacebookAuthorizeFilter(config);\n\n            ContentResult result = Assert.IsType<JavaScriptRedirectResult>(authorizeFilter.CreateRedirectResult(uri));\n            Assert.Equal(\"text/html\", result.ContentType);\n            Assert.Equal(@\"<script>window.top.location = 'http://example.com/?query=4\\u0027;%20alert(\\u0027hello%20world\\u0027)';</script>\", result.Content);\n        }\n\n        [Fact]\n        public void OnAuthorization_RedirectsToOAuthDialog_WhenSignedRequestIsNull()\n        {\n            FacebookConfiguration config = MockHelpers.CreateConfiguration();\n            FacebookAuthorizeFilter authorizeFilter = new FacebookAuthorizeFilter(config);\n            AuthorizationContext context = new AuthorizationContext(\n                MockHelpers.CreateControllerContext(),\n                MockHelpers.CreateActionDescriptor(new[] { new FacebookAuthorizeAttribute(\"email\") }));\n\n            authorizeFilter.OnAuthorization(context);\n\n            ContentResult result = Assert.IsType<JavaScriptRedirectResult>(context.Result);\n            Assert.Equal(\"text/html\", result.ContentType);\n            Assert.Equal(\n                \"<script>window.top.location = 'https://www.facebook.com/dialog/oauth?redirect_uri=https%3A%2F%2Fapps.facebook.com%2FDefaultAppId%2F\\\\u0026client_id=DefaultAppId';</script>\",\n                result.Content);\n        }\n\n        [Fact]\n        public void OnAuthorization_RedirectsToOAuthDialog_ForMissingPermissions()\n        {\n            FacebookClient client = MockHelpers.CreateFacebookClient();\n            IFacebookPermissionService permissionService = MockHelpers.CreatePermissionService(new[] { \"\" });\n            FacebookConfiguration config = MockHelpers.CreateConfiguration(client, permissionService);\n            FacebookAuthorizeFilter authorizeFilter = new FacebookAuthorizeFilter(config);\n            AuthorizationContext context = new AuthorizationContext(\n                MockHelpers.CreateControllerContext(new NameValueCollection\n                {\n                    {\"signed_request\", \"exampleSignedRequest\"}\n                }),\n                MockHelpers.CreateActionDescriptor(new[] { new FacebookAuthorizeAttribute(\"email\", \"user_likes\") }));\n\n            authorizeFilter.OnAuthorization(context);\n\n            ContentResult result = Assert.IsType<ShowPromptResult>(context.Result);\n            Assert.Equal(\"text/html\", result.ContentType);\n            Assert.Equal(\n                \"<script>window.top.location = 'https://www.facebook.com/dialog/oauth?redirect_uri=example.com';</script>\",\n                result.Content);\n        }\n\n        [Theory]\n        [InlineData(\"http://example.com\", \"https://www.facebook.com/dialog/oauth?redirect_uri=example.com\")]\n        [InlineData(\"http://example.com?error=access_denied\", \"https://apps.facebook.com/DefaultAppId/home/permissions?originUrl=https%3a%2f%2fapps.facebook.com%2fDefaultAppId%2f\\\\u0026permissions=email\")]\n        public void OnAuthorization_RedirectsToAuthorizationRedirectPath_OnlyWhenUserDeniedGrantingPermissions(string requestUrl, string expectedRedirectUrl)\n        {\n            FacebookClient client = MockHelpers.CreateFacebookClient();\n            IFacebookPermissionService permissionService = MockHelpers.CreatePermissionService(new[] { \"\" });\n            FacebookConfiguration config = MockHelpers.CreateConfiguration(client, permissionService);\n            config.AuthorizationRedirectPath = \"~/home/permissions\";\n            FacebookAuthorizeFilter authorizeFilter = new FacebookAuthorizeFilter(config);\n            AuthorizationContext context = new AuthorizationContext(\n                MockHelpers.CreateControllerContext(new NameValueCollection\n                {\n                    {\"signed_request\", \"exampleSignedRequest\"}\n                },\n                null,\n                new Uri(requestUrl)),\n                MockHelpers.CreateActionDescriptor(new[] { new FacebookAuthorizeAttribute(\"email\") }));\n\n            authorizeFilter.OnAuthorization(context);\n\n            ContentResult result = Assert.IsAssignableFrom<JavaScriptRedirectResult>(context.Result);\n\n            Assert.Equal(\"text/html\", result.ContentType);\n            Assert.Equal(\n                String.Format(\"<script>window.top.location = '{0}';</script>\", expectedRedirectUrl),\n                result.Content);\n        }\n\n        private class CustomAuthorizeFilter : FacebookAuthorizeFilter\n        {\n            public CustomAuthorizeFilter()\n                : base(new FacebookConfiguration())\n            {\n            }\n\n            public void ExposedAddCookieVerificationQuery(NameValueCollection queries)\n            {\n                AddCookieVerificationQuery(queries);\n            }\n        }\n    }\n}"
  },
  {
    "path": "test/Microsoft.AspNet.Facebook.Test/FacebookClientExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading.Tasks;\nusing Microsoft.AspNet.Facebook.Client;\nusing Microsoft.AspNet.Facebook.Test.Helpers;\nusing Microsoft.AspNet.Facebook.Test.Types;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.AspNet.Facebook.Test\n{\n    public class FacebookClientExtensionsTest\n    {\n        [Fact]\n        public async Task GetCurrentUserAsyncOfT_CallsGetTaskAsyncWithTheExpectedPath()\n        {\n            LocalFacebookClient client = new LocalFacebookClient();\n            await client.GetCurrentUserAsync<SimpleUser>();\n\n            Assert.Equal(\"me?fields=id,name,picture.fields(url)\", client.Path);\n        }\n\n        [Fact]\n        public async Task GetCurrentUserAsync_CallsGetTaskAsyncWithTheExpectedPath()\n        {\n            LocalFacebookClient client = new LocalFacebookClient();\n            await client.GetCurrentUserAsync();\n\n            Assert.Equal(\"me\", client.Path);\n        }\n\n        [Fact]\n        public async Task GetCurrentUserFriendsAsyncOfT_CallsGetTaskAsyncWithTheExpectedPath()\n        {\n            LocalFacebookClient client = new LocalFacebookClient();\n            await client.GetCurrentUserFriendsAsync<SimpleUser>();\n\n            Assert.Equal(\"me/friends?fields=id,name,picture.fields(url)\", client.Path);\n        }\n\n        [Fact]\n        public async Task GetCurrentUserFriendsAsync_CallsGetTaskAsyncWithTheExpectedPath()\n        {\n            LocalFacebookClient client = new LocalFacebookClient();\n            await client.GetCurrentUserFriendsAsync();\n\n            Assert.Equal(\"me/friends\", client.Path);\n        }\n\n        [Fact]\n        public async Task GetCurrentUserPermissionsAsync_CallsGetTaskAsyncWithTheExpectedPath()\n        {\n            LocalFacebookClient client = new LocalFacebookClient();\n            await client.GetCurrentUserPermissionsAsync();\n\n            Assert.Equal(\"me/permissions\", client.Path);\n        }\n\n        [Fact]\n        public async Task GetCurrentUserPhotosAsyncOfT_CallsGetTaskAsyncWithTheExpectedPath()\n        {\n            LocalFacebookClient client = new LocalFacebookClient();\n            await client.GetCurrentUserPhotosAsync<UserPhoto>();\n\n            Assert.Equal(\"me/photos?fields=name,picture,source\", client.Path);\n        }\n\n        [Fact]\n        public async Task GetCurrentUserStatusesAsyncOfT_CallsGetTaskAsyncWithTheExpectedPath()\n        {\n            LocalFacebookClient client = new LocalFacebookClient();\n            await client.GetCurrentUserStatusesAsync<UserStatus>();\n\n            Assert.Equal(\"me/statuses?fields=message,time\", client.Path);\n        }\n\n        [Fact]\n        public async Task GetFacebookObjectAsyncOfT_CallsGetTaskAsyncWithTheExpectedPath()\n        {\n            LocalFacebookClient client = new LocalFacebookClient();\n            await client.GetFacebookObjectAsync<FacebookConnection<FacebookPicture>>(\"me/picture\");\n\n            Assert.Equal(\"me/picture?fields=url\", client.Path);\n        }\n\n        [Fact]\n        public async Task GetFacebookObjectAsync_CallsGetTaskAsyncWithTheExpectedPath()\n        {\n            LocalFacebookClient client = new LocalFacebookClient();\n            await client.GetFacebookObjectAsync(\"me/notes\");\n\n            Assert.Equal(\"me/notes\", client.Path);\n        }\n\n        [Fact]\n        public async Task GetFacebookObjectAsyncOfT_ThrowArgumentNullExceptions()\n        {\n            LocalFacebookClient client = null;\n            await Assert.ThrowsArgumentNullAsync(() => client.GetFacebookObjectAsync<SimpleUser>(\"me\"), \"client\");\n\n            client = new LocalFacebookClient();\n            await Assert.ThrowsArgumentNullAsync(() => client.GetFacebookObjectAsync<SimpleUser>(null), \"objectPath\");\n        }\n\n        [Fact]\n        public async Task GetFacebookObjectAsync_ThrowArgumentNullExceptions()\n        {\n            LocalFacebookClient client = null;\n            await Assert.ThrowsArgumentNullAsync(() => client.GetFacebookObjectAsync(\"me\"), \"client\");\n\n            client = new LocalFacebookClient();\n            await Assert.ThrowsArgumentNullAsync(() => client.GetFacebookObjectAsync(null), \"objectPath\");\n        }\n    }\n}"
  },
  {
    "path": "test/Microsoft.AspNet.Facebook.Test/FacebookConfigurationTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.AspNet.Facebook.Test\n{\n    public class FacebookConfigurationTest\n    {\n        [Fact]\n        public void Default_Constructor()\n        {\n            FacebookConfiguration config = new FacebookConfiguration();\n            Assert.Null(config.AppId);\n            Assert.Null(config.AppNamespace);\n            Assert.Null(config.AppSecret);\n            Assert.NotNull(config.AppUrl);\n            Assert.Null(config.AuthorizationRedirectPath);\n            Assert.Null(config.CannotCreateCookieRedirectPath);\n            Assert.Null(config.ClientProvider);\n            Assert.Null(config.PermissionService);\n            Assert.NotNull(config.Properties);\n        }\n\n        [Fact]\n        public void AppUrl_FromAppId()\n        {\n            FacebookConfiguration config = new FacebookConfiguration();\n            config.AppId = \"654321\";\n            Assert.Equal(\"https://apps.facebook.com/654321\", config.AppUrl);\n        }\n\n        [Fact]\n        public void AppUrl_FromAppNamespace()\n        {\n            FacebookConfiguration config = new FacebookConfiguration();\n            config.AppId = \"654321\";\n            config.AppNamespace = \"MyCustomApp\";\n            Assert.Equal(\"https://apps.facebook.com/MyCustomApp\", config.AppUrl);\n        }\n\n        [Fact]\n        public void AppUrl_FromCustomUrl()\n        {\n            FacebookConfiguration config = new FacebookConfiguration();\n            config.AppId = \"654321\";\n            config.AppNamespace = \"MyCustomApp\";\n            config.AppUrl = \"http://apps.example.com/myapp\";\n            Assert.Equal(\"http://apps.example.com/myapp\", config.AppUrl);\n        }\n\n        [Fact]\n        public void LoadFromAppSettings_ReadsFromAppConfig()\n        {\n            FacebookConfiguration config = new FacebookConfiguration();\n            config.LoadFromAppSettings();\n            Assert.Equal(\"123456\", config.AppId);\n            Assert.Equal(\"abcdefg\", config.AppSecret);\n            Assert.Equal(\"MyApp\", config.AppNamespace);\n            Assert.Equal(\"~/Authorize/Index\", config.AuthorizationRedirectPath);\n            Assert.Equal(\"~/NoCookies/Index\", config.CannotCreateCookieRedirectPath);\n            Assert.Equal(\"https://apps.newfacebook.example.com/myapp\", config.AppUrl);\n        }\n\n        [Fact]\n        public void AuthorizationRedirectPath_ThrowsArgumentException()\n        {\n            FacebookConfiguration config = new FacebookConfiguration();\n            Assert.ThrowsArgument(() => config.AuthorizationRedirectPath = \"Home/Permissions\", \"value\");\n        }\n\n        [Fact]\n        public void CannotCreateCookieRedirectPath_ThrowsArgumentException()\n        {\n            FacebookConfiguration config = new FacebookConfiguration();\n            Assert.ThrowsArgument(() => config.CannotCreateCookieRedirectPath = \"Home/Permissions\", \"value\");\n        }\n    }\n}"
  },
  {
    "path": "test/Microsoft.AspNet.Facebook.Test/FacebookContextModelBinderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing System.Web.Mvc;\nusing Microsoft.AspNet.Facebook.ModelBinders;\nusing Microsoft.AspNet.Facebook.Providers;\nusing Microsoft.AspNet.Facebook.Test.Helpers;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.AspNet.Facebook.Test\n{\n    public class FacebookContextModelBinderTest\n    {\n        [Fact]\n        public void Constructor_ThrowsArgumentNullException()\n        {\n            Assert.ThrowsArgumentNull(() => new FacebookContextModelBinder(null), \"config\");\n        }\n\n        [Fact]\n        public void BindModel_ReturnsExpectedFacebookContext_WhenSignedRequestComesFromForm()\n        {\n            FacebookConfiguration config = new FacebookConfiguration();\n            config.AppSecret = \"3e29b24f825e737d97aed5eb62df5076\";\n            config.ClientProvider = new DefaultFacebookClientProvider(config);\n            FacebookContextModelBinder contextBinder = new FacebookContextModelBinder(config);\n            ControllerContext controllerContext = MockHelpers.CreateControllerContext(new NameValueCollection\n            {\n                {\"signed_request\", \"x1yDEgacN3N5iu23Ji8NLYp9LGO1-cUXKHTJQrMqzVQ.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImV4cGlyZXMiOjEzNTM5MTMyMDAsImlzc3VlZF9hdCI6MTM1MzkwNzQ5Miwib2F1dGhfdG9rZW4iOiJBQUFGUlJPcWtwZ01CQURBSjNQZk5vNldXMlJ5WkFSQ1hjU0daQlhpNTBLTG9wRzFwYmFwc2M2aThKY3h6WkFQN1pDSnlpcXVHYlc3WXlCam1aQjh0UWpyelZ2VTNrYm44b3N3WXR5czkzTWdaRFpEIiwidXNlciI6eyJjb3VudHJ5IjoidXMiLCJsb2NhbGUiOiJlbl9VUyIsImFnZSI6eyJtaW4iOjIxfX0sInVzZXJfaWQiOiIxNzgyNTkwMSJ9\"}\n            });\n            ModelBindingContext modelBindingContext = new ModelBindingContext();\n\n            FacebookContext context = Assert.IsType<FacebookContext>(contextBinder.BindModel(controllerContext, modelBindingContext));\n\n            Assert.NotNull((object)context.SignedRequest);\n            Assert.NotNull(context.AccessToken);\n            Assert.Equal(\"17825901\", context.UserId);\n        }\n\n        [Fact]\n        public void BindModel_ReturnsExpectedFacebookContext_WhenSignedRequestComesFromQuery()\n        {\n            FacebookConfiguration config = new FacebookConfiguration();\n            config.AppSecret = \"3e29b24f825e737d97aed5eb62df5076\";\n            config.ClientProvider = new DefaultFacebookClientProvider(config);\n            FacebookContextModelBinder contextBinder = new FacebookContextModelBinder(config);\n            ControllerContext controllerContext = MockHelpers.CreateControllerContext(\n                null,\n                new NameValueCollection\n                {\n                    {\"signed_request\", \"x1yDEgacN3N5iu23Ji8NLYp9LGO1-cUXKHTJQrMqzVQ.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImV4cGlyZXMiOjEzNTM5MTMyMDAsImlzc3VlZF9hdCI6MTM1MzkwNzQ5Miwib2F1dGhfdG9rZW4iOiJBQUFGUlJPcWtwZ01CQURBSjNQZk5vNldXMlJ5WkFSQ1hjU0daQlhpNTBLTG9wRzFwYmFwc2M2aThKY3h6WkFQN1pDSnlpcXVHYlc3WXlCam1aQjh0UWpyelZ2VTNrYm44b3N3WXR5czkzTWdaRFpEIiwidXNlciI6eyJjb3VudHJ5IjoidXMiLCJsb2NhbGUiOiJlbl9VUyIsImFnZSI6eyJtaW4iOjIxfX0sInVzZXJfaWQiOiIxNzgyNTkwMSJ9\"}\n                });\n\n            FacebookContext context = Assert.IsType<FacebookContext>(contextBinder.BindModel(controllerContext, new ModelBindingContext()));\n\n            Assert.NotNull((object)context.SignedRequest);\n            Assert.NotNull(context.AccessToken);\n            Assert.Equal(\"17825901\", context.UserId);\n        }\n\n        [Fact]\n        public void BindModel_ReturnsInvalidModelState_WhenSignedRequestIsNull()\n        {\n            FacebookConfiguration config = new FacebookConfiguration();\n            config.AppSecret = \"abcdef\";\n            config.ClientProvider = new DefaultFacebookClientProvider(config);\n            FacebookContextModelBinder contextBinder = new FacebookContextModelBinder(config);\n            ControllerContext controllerContext = MockHelpers.CreateControllerContext();\n            ModelBindingContext modelBindingContext = new ModelBindingContext();\n\n            object context = contextBinder.BindModel(controllerContext, modelBindingContext);\n\n            Assert.Null(context);\n            Assert.False(modelBindingContext.ModelState.IsValid);\n        }\n    }\n}"
  },
  {
    "path": "test/Microsoft.AspNet.Facebook.Test/FacebookQueryHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing Microsoft.AspNet.Facebook.Client;\nusing Microsoft.AspNet.Facebook.Test.Types;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.AspNet.Facebook.Test\n{\n    public class FacebookQueryHelperTest\n    {\n        [Theory]\n        [InlineData(typeof(SimpleUser), \"?fields=id,name,picture.fields(url)\")]\n        [InlineData(typeof(UserWithFriends), \"?fields=id,name,picture.fields(url),friends.fields(id,name,picture.fields(url))\")]\n        [InlineData(typeof(UserTypeWithIgnoredProperties), \"?fields=id\")]\n        [InlineData(typeof(UserTypeWithRenamedProperties), \"?fields=id,name,picture.fields(url)\")]\n        [InlineData(typeof(UserTypeWithFieldModifiers), \"?fields=id,name,picture.type(large).fields(url),friends.limit(5).fields(id,name,picture.fields(url))\")]\n        public void GetFields_ReturnsExpectedQuery(Type modelType, string expectedQuery)\n        {\n            Assert.Equal(expectedQuery, FacebookQueryHelper.GetFields(modelType));\n        }\n\n        [Theory]\n        [InlineData(typeof(UserWithUserFriends))]\n        [InlineData(typeof(UserContainingFriendsWithCycle))]\n        public void GetFields_ThrowsExceptionWhenDetectsACycle(Type modelType)\n        {\n            Assert.Throws<InvalidOperationException>(\n                () => FacebookQueryHelper.GetFields(modelType),\n                Resources.CircularReferenceNotSupported);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.AspNet.Facebook.Test/FacebookRealtimeControllerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Net;\nusing System.Net.Http;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Microsoft.AspNet.Facebook.Models;\nusing Microsoft.AspNet.Facebook.Providers;\nusing Microsoft.AspNet.Facebook.Realtime;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.AspNet.Facebook.Test\n{\n    public class FacebookRealtimeControllerTest\n    {\n        private const string AppSignatureHeader1 = \"sha1=dbb5c0bfaac69ffee7b633e88d85e107fba7ecca\";\n        private const string AppSecret1 = \"f8ad79c0081a80bb885e2b280c3f8442\";\n        private const string AppSignatureHeader2 = \"sha1=3ee3a233ca0c872cae6b40d38a99dff26bf8eb27\";\n        private const string AppSecret2 = \"134cfa3691d1f51c64e70700f397ed20\";\n        private const string ContentString = \"{\\\"object\\\":\\\"user\\\",\\\"entry\\\":[{\\\"uid\\\":\\\"17825901\\\",\\\"id\\\":\\\"17825901\\\",\\\"time\\\":1352251746,\\\"changed_fields\\\":[\\\"likes\\\"]}]}\";\n\n        [Fact]\n        public void Overriding_VerificationToken()\n        {\n            var userRealTimeController = new UserRealtimeCallbackController();\n            Assert.Null(userRealTimeController.VerifyToken);\n\n            userRealTimeController = new UserRealtimeCallbackController(null, \"foo\");\n            Assert.Equal(\"foo\", userRealTimeController.VerifyToken);\n\n            userRealTimeController = new UserRealtimeCallbackController(null, String.Empty);\n            Assert.Equal(String.Empty, userRealTimeController.VerifyToken);\n        }\n\n        [Theory]\n        [InlineData(\"123456\", \"foo\")]\n        [InlineData(\"654321\", \"bar\")]\n        public async Task Get_ReturnsOk_WithValidParameters(string challenge, string verifyToken)\n        {\n            var userRealTimeController = new UserRealtimeCallbackController(null, verifyToken);\n            userRealTimeController.Request = new HttpRequestMessage();\n            var subscriptionVerification = new SubscriptionVerification\n            {\n                Challenge = challenge,\n                Mode = \"subscribe\",\n                Verify_Token = verifyToken\n            };\n            Assert.Equal(challenge, await userRealTimeController.Get(subscriptionVerification).Content.ReadAsStringAsync());\n        }\n\n        [Theory]\n        [InlineData(null, \"foo\", HttpStatusCode.BadRequest)]\n        [InlineData(\"654321\", null, HttpStatusCode.BadRequest)]\n        [InlineData(\"654321\", \"\", HttpStatusCode.BadRequest)]\n        [InlineData(\"\", \"bar\", HttpStatusCode.BadRequest)]\n        [InlineData(\"654321\", \"bar\", HttpStatusCode.OK)]\n        public void Get_ReturnsExpectedStatusCode(string challenge, string verifyToken, HttpStatusCode expectedStatusCode)\n        {\n            var userRealTimeController = new UserRealtimeCallbackController(null, verifyToken);\n            userRealTimeController.Request = new HttpRequestMessage();\n            var subscriptionVerification = new SubscriptionVerification\n            {\n                Challenge = challenge,\n                Mode = \"subscribe\",\n                Verify_Token = \"bar\"\n            };\n            Assert.Equal(expectedStatusCode, userRealTimeController.Get(subscriptionVerification).StatusCode);\n        }\n\n        [Theory]\n        [InlineData(ContentString, AppSignatureHeader1, AppSecret1)]\n        [InlineData(ContentString, AppSignatureHeader2, AppSecret2)]\n        public async Task Post_ReturnsOk_WithValidParameters(string contentString, string headerValue, string appSecret)\n        {\n            var userRealTimeController = new UserRealtimeCallbackController(appSecret, null);\n            userRealTimeController.Request = new HttpRequestMessage\n            {\n                Content = new StringContent(contentString, Encoding.UTF8, \"text/json\")\n            };\n            var request = userRealTimeController.Request;\n            request.Headers.Add(\"X-Hub-Signature\", headerValue);\n            Assert.Equal(HttpStatusCode.OK, (await userRealTimeController.Post()).StatusCode);\n        }\n\n        [Theory]\n        [InlineData(ContentString, AppSignatureHeader1, AppSecret2)]\n        [InlineData(ContentString, AppSignatureHeader2, AppSecret1)]\n        [InlineData(ContentString, null, AppSecret2)]\n        [InlineData(ContentString, AppSignatureHeader1, null)]\n        public async Task Post_ReturnsBadRequest_WithInValidParameters(string contentString, string headerValue, string AppSecret)\n        {\n            var userRealTimeController = new UserRealtimeCallbackController(AppSecret, null);\n            userRealTimeController.Request = new HttpRequestMessage\n            {\n                Content = new StringContent(contentString, Encoding.UTF8, \"text/json\")\n            };\n            var request = userRealTimeController.Request;\n            if (headerValue != null)\n            {\n                request.Headers.Add(\"X-Hub-Signature\", headerValue);\n            }\n            Assert.Equal(HttpStatusCode.BadRequest, (await userRealTimeController.Post()).StatusCode);\n        }\n\n        private sealed class UserRealtimeCallbackController : FacebookRealtimeUpdateController\n        {\n            private string _verifyToken;\n\n            public UserRealtimeCallbackController() : this(null, null) { }\n\n            public UserRealtimeCallbackController(string appSecret, string verifyToken)\n            {\n                // Avoid base class's fallback to static GlobalFacebookConfiguration.\n                var config = new FacebookConfiguration();\n                config.ClientProvider = new DefaultFacebookClientProvider(config);\n                config.PermissionService = new DefaultFacebookPermissionService(config);\n                config.AppSecret = appSecret;\n\n                FacebookConfiguration = config;\n                _verifyToken = verifyToken;\n            }\n\n            public override string VerifyToken\n            {\n                get\n                {\n                    return _verifyToken;\n                }\n            }\n\n            public override Task HandleUpdateAsync(ChangeNotification notification)\n            {\n                return Task.FromResult(0);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.AspNet.Facebook.Test/FacebookRedirectContextModelBinderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing System.Web.Mvc;\nusing Microsoft.AspNet.Facebook.ModelBinders;\nusing Microsoft.AspNet.Facebook.Providers;\nusing Microsoft.AspNet.Facebook.Test.Helpers;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.AspNet.Facebook.Test\n{\n    public class FacebookRedirectContextModelBinderTest\n    {\n        [Fact]\n        public void Constructor_ThrowsArgumentNullException()\n        {\n            Assert.ThrowsArgumentNull(() => new FacebookContextModelBinder(null), \"config\");\n        }\n\n        [Fact]\n        public void BindModel_ReturnsExpectedFacebookRedirectContext()\n        {\n            FacebookConfiguration config = new FacebookConfiguration();\n            config.AppId = \"123456\";\n            config.ClientProvider = new DefaultFacebookClientProvider(config);\n            FacebookRedirectContextModelBinder redirectContextBinder = new FacebookRedirectContextModelBinder(config);\n            ControllerContext controllerContext = MockHelpers.CreateControllerContext(\n                null,\n                new NameValueCollection\n                {\n                    {\"originUrl\", \"https://apps.facebook.com/123456/home/index\"},\n                    {\"permissions\", \"email,user_likes\"}\n                });\n            ModelBindingContext modelBindingContext = new ModelBindingContext();\n\n            FacebookRedirectContext context = Assert.IsType<FacebookRedirectContext>(redirectContextBinder.BindModel(controllerContext, modelBindingContext));\n\n            Assert.Equal(\"https://apps.facebook.com/123456/home/index\", context.OriginUrl);\n            // Redirect URL should not have any permissions on it.  That's handled by the authorization filter.\n            Assert.Equal(\"https://www.facebook.com/dialog/oauth?redirect_uri=https%3A%2F%2Fapps.facebook.com%2F123456%2Fhome%2Findex&client_id=123456\", context.RedirectUrl);\n            Assert.Equal(2, context.RequiredPermissions.Length);\n            Assert.Equal(\"email\", context.RequiredPermissions[0]);\n            Assert.Equal(\"user_likes\", context.RequiredPermissions[1]);\n            Assert.Same(config, context.Configuration);\n        }\n\n        [Fact]\n        public void BindModel_ReturnsInvalidModelState_WhenOriginUrlIsNull()\n        {\n            FacebookConfiguration config = new FacebookConfiguration();\n            config.AppId = \"123456\";\n            config.ClientProvider = new DefaultFacebookClientProvider(config);\n            FacebookRedirectContextModelBinder redirectContextBinder = new FacebookRedirectContextModelBinder(config);\n            ControllerContext controllerContext = MockHelpers.CreateControllerContext(\n                null,\n                new NameValueCollection\n                {\n                    {\"permissions\", \"email,user_likes\"}\n                });\n            ModelBindingContext modelBindingContext = new ModelBindingContext();\n\n            FacebookRedirectContext context = Assert.IsType<FacebookRedirectContext>(redirectContextBinder.BindModel(controllerContext, modelBindingContext));\n            Assert.False(modelBindingContext.ModelState.IsValid);\n        }\n\n        [Fact]\n        public void BindModel_ReturnsInvalidModelState_WhenOriginUrlIsExternal()\n        {\n            FacebookConfiguration config = new FacebookConfiguration();\n            config.AppId = \"123456\";\n            config.ClientProvider = new DefaultFacebookClientProvider(config);\n            FacebookRedirectContextModelBinder redirectContextBinder = new FacebookRedirectContextModelBinder(config);\n            ControllerContext controllerContext = MockHelpers.CreateControllerContext(\n                null,\n                new NameValueCollection\n                {\n                    {\"originUrl\", \"https://example.com/123456/home/index\"},\n                    {\"permissions\", \"email,user_likes\"}\n                });\n            ModelBindingContext modelBindingContext = new ModelBindingContext();\n\n            FacebookRedirectContext context = Assert.IsType<FacebookRedirectContext>(redirectContextBinder.BindModel(controllerContext, modelBindingContext));\n            Assert.False(modelBindingContext.ModelState.IsValid);\n        }\n    }\n}"
  },
  {
    "path": "test/Microsoft.AspNet.Facebook.Test/GlobalFacebookConfigurationTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.AspNet.Facebook.Test\n{\n    public class GlobalFacebookConfigurationTest\n    {\n        [Fact]\n        public void Default_Configuration()\n        {\n            FacebookConfiguration config = GlobalFacebookConfiguration.Configuration;\n            Assert.Null(config.AppId);\n            Assert.Null(config.AppNamespace);\n            Assert.Null(config.AppSecret);\n            Assert.NotNull(config.AppUrl);\n            Assert.Null(config.AuthorizationRedirectPath);\n            Assert.NotNull(config.ClientProvider);\n            Assert.NotNull(config.PermissionService);\n            Assert.NotNull(config.Properties);\n        }\n    }\n}"
  },
  {
    "path": "test/Microsoft.AspNet.Facebook.Test/Helpers/LocalFacebookClient.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Threading.Tasks;\nusing Facebook;\n\nnamespace Microsoft.AspNet.Facebook.Test.Helpers\n{\n    public class LocalFacebookClient : FacebookClient\n    {\n        public string Path { get; set; }\n\n        public override Task<TResult> GetTaskAsync<TResult>(string path)\n        {\n            Path = path;\n            return Task.FromResult<TResult>(Activator.CreateInstance<TResult>());\n        }\n\n        public override Task<object> GetTaskAsync(string path)\n        {\n            Path = path;\n            return Task.FromResult(new object());\n        }\n\n        public override object Get(string path)\n        {\n            Path = path;\n            return new object();\n        }\n\n        public override TResult Get<TResult>(string path)\n        {\n            Path = path;\n            return Activator.CreateInstance<TResult>();\n        }\n    }\n}"
  },
  {
    "path": "test/Microsoft.AspNet.Facebook.Test/Helpers/MockHelpers.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Dynamic;\nusing System.Web;\nusing System.Web.Mvc;\nusing Facebook;\nusing Microsoft.AspNet.Facebook.Providers;\nusing Moq;\n\nnamespace Microsoft.AspNet.Facebook.Test.Helpers\n{\n    internal class MockHelpers\n    {\n        public static ControllerContext CreateControllerContext(NameValueCollection requestFormData = null,\n                                                                NameValueCollection requestQueryData = null,\n                                                                Uri requestUrl = null,\n                                                                HttpCookieCollection requestCookies = null)\n        {\n            Mock<ControllerContext> controllerContext = new Mock<ControllerContext>();\n            controllerContext.Setup(c => c.HttpContext.Response).Returns(new EmptyHttpResponse());\n            controllerContext.Setup(c => c.HttpContext.Response.Cookies).Returns(new HttpCookieCollection());\n            controllerContext.Setup(c => c.HttpContext.Items).Returns(new Dictionary<object, object>());\n            controllerContext.Setup(c => c.HttpContext.Request.Url).Returns(requestUrl ?? new Uri(\"http://example.com\"));\n            controllerContext.Setup(c => c.HttpContext.Request.AppRelativeCurrentExecutionFilePath).Returns(\"~/\");\n            controllerContext.Setup(c => c.HttpContext.Request.Form).Returns(requestFormData ?? new NameValueCollection());\n            controllerContext.Setup(c => c.HttpContext.Request.QueryString).Returns(requestQueryData ?? new NameValueCollection());\n            controllerContext.Setup(c => c.HttpContext.Request.Cookies).Returns(requestCookies ?? new HttpCookieCollection());\n            return controllerContext.Object;\n        }\n\n        public static ActionDescriptor CreateActionDescriptor(object[] actionAuthorizeAttributes = null, object[] controllerAuthorizeAttributes = null)\n        {\n            Mock<ActionDescriptor> actionDescriptor = new Mock<ActionDescriptor>();\n            actionDescriptor.Setup(a => a.GetCustomAttributes(typeof(FacebookAuthorizeAttribute), true)).Returns(actionAuthorizeAttributes ?? new object[0]);\n            actionDescriptor.Setup(a => a.ControllerDescriptor.GetCustomAttributes(typeof(FacebookAuthorizeAttribute), true)).Returns(controllerAuthorizeAttributes ?? new object[0]);\n            return actionDescriptor.Object;\n        }\n\n        public static FacebookConfiguration CreateConfiguration(FacebookClient client = null, IFacebookPermissionService permissionService = null)\n        {\n            FacebookConfiguration config = new FacebookConfiguration();\n\n            if (client == null)\n            {\n                config.ClientProvider = new DefaultFacebookClientProvider(config);\n                config.AppId = \"DefaultAppId\";\n                config.AppSecret = \"DefaultAppSecret\";\n            }\n            else\n            {\n                Mock<IFacebookClientProvider> clientProvider = new Mock<IFacebookClientProvider>();\n                clientProvider.Setup(cp => cp.CreateClient()).Returns(client);\n                config.ClientProvider = clientProvider.Object;\n                config.AppId = client.AppId ?? \"DefaultAppId\";\n                config.AppSecret = client.AppSecret ?? \"DefaultAppSecret\";\n            }\n            config.PermissionService = permissionService ?? new DefaultFacebookPermissionService(config);\n            return config;\n        }\n\n        public static FacebookClient CreateFacebookClient()\n        {\n            Mock<FacebookClient> client = new Mock<FacebookClient>();\n            dynamic signedRequestParameters = new ExpandoObject();\n            signedRequestParameters.user_id = \"sampleId\";\n            signedRequestParameters.oauth_token = \"sampleToken\";\n            client.Setup(c => c.ParseSignedRequest(It.IsAny<string>())).Returns((object)signedRequestParameters);\n            client.Setup(c => c.GetLoginUrl(It.IsAny<object>())).Returns(new Uri(\"https://www.facebook.com/dialog/oauth?redirect_uri=example.com\"));\n            return client.Object;\n        }\n\n        public static IFacebookPermissionService CreatePermissionService(string[] permissionsToReturn,\n                                                                         PermissionsStatus permissionsStatusToReturn = null)\n        {\n            var client = new Mock<IFacebookPermissionService>();\n            permissionsStatusToReturn = permissionsStatusToReturn ?? new PermissionsStatus(apiResult: null);\n\n            client.Setup(p => p.GetUserPermissions(It.IsAny<string>(), It.IsAny<string>())).Returns(permissionsToReturn);\n            client.Setup(p => p.GetUserPermissionsStatus(It.IsAny<string>(), It.IsAny<string>())).Returns(permissionsStatusToReturn);\n\n            return client.Object;\n        }\n\n        private sealed class EmptyHttpResponse : HttpResponseBase\n        {\n        }\n    }\n}"
  },
  {
    "path": "test/Microsoft.AspNet.Facebook.Test/Microsoft.AspNet.Facebook.Test.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props\" Condition=\"Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" />\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" />\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{C3BEF382-C7C4-454D-B017-1EAC03E9A82C}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>Microsoft.AspNet.Facebook.Test</RootNamespace>\n    <AssemblyName>Microsoft.AspNet.Facebook.Test</AssemblyName>\n    <OutputPath>..\\..\\bin\\$(Configuration)\\Test\\</OutputPath>\n    <NuGetPackageImportStamp>\n    </NuGetPackageImportStamp>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Castle.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Castle.Core.5.1.1\\lib\\net462\\Castle.Core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Facebook, Version=6.0.10.0, Culture=neutral, PublicKeyToken=58cb4f2111d1e6de, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Facebook.6.4.2\\lib\\net45\\Facebook.dll</HintPath>\n    </Reference>\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"Moq, Version=4.18.0.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Moq.4.18.4\\lib\\net462\\Moq.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Newtonsoft.Json.13.0.1\\lib\\net45\\Newtonsoft.Json.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Net.Http\" />\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"System.Xml\" />\n    <Reference Include=\"xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.abstractions.2.0.3\\lib\\net35\\xunit.abstractions.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.assert, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.assert.2.4.2\\lib\\netstandard1.1\\xunit.assert.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.core, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.core.2.4.2\\lib\\net452\\xunit.core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.execution.desktop, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.execution.2.4.2\\lib\\net452\\xunit.execution.desktop.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"FacebookAuthorizeAttributeTest.cs\" />\n    <Compile Include=\"FacebookAuthorizeFilterHookTest.cs\" />\n    <Compile Include=\"GlobalFacebookConfigurationTest.cs\" />\n    <Compile Include=\"FacebookAuthorizeFilterTest.cs\" />\n    <Compile Include=\"FacebookClientExtensionsTest.cs\" />\n    <Compile Include=\"FacebookQueryHelperTest.cs\" />\n    <Compile Include=\"DefaultFacebookPermissionServiceTest.cs\" />\n    <Compile Include=\"DefaultFacebookClientProviderTest.cs\" />\n    <Compile Include=\"FacebookRedirectContextModelBinderTest.cs\" />\n    <Compile Include=\"FacebookConfigurationTest.cs\" />\n    <Compile Include=\"FacebookContextModelBinderTest.cs\" />\n    <Compile Include=\"FacebookRealtimeControllerTest.cs\" />\n    <Compile Include=\"Helpers\\MockHelpers.cs\" />\n    <Compile Include=\"Helpers\\LocalFacebookClient.cs\" />\n    <Compile Include=\"Types\\UserPhoto.cs\" />\n    <Compile Include=\"Types\\UserStatus.cs\" />\n    <Compile Include=\"Types\\UserTypeWithFieldModifiers.cs\" />\n    <Compile Include=\"Types\\UserTypeWithRenamedProperties.cs\" />\n    <Compile Include=\"Types\\UserTypeWithIgnoredProperties.cs\" />\n    <Compile Include=\"Types\\UserTypesWithCycles.cs\" />\n    <Compile Include=\"Types\\FacebookPicture.cs\" />\n    <Compile Include=\"Types\\UserWithFriends.cs\" />\n    <Compile Include=\"Types\\SimpleUser.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"App.config\">\n      <SubType>Designer</SubType>\n    </None>\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\..\\src\\Microsoft.AspNet.Facebook\\Microsoft.AspNet.Facebook.csproj\">\n      <Project>{821a136c-7c6f-44c6-a9e6-c39b5bfb1483}</Project>\n      <Name>Microsoft.AspNet.Facebook</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Net.Http.Formatting\\System.Net.Http.Formatting.csproj\">\n      <Project>{668e9021-ce84-49d9-98fb-df125a9fcdb0}</Project>\n      <Name>System.Net.Http.Formatting</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Helpers\\System.Web.Helpers.csproj\">\n      <Project>{9b7e3740-6161-4548-833c-4bbca43b970e}</Project>\n      <Name>System.Web.Helpers</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Http\\System.Web.Http.csproj\">\n      <Project>{ddc1ce0c-486e-4e35-bb3b-eab61f8f9440}</Project>\n      <Name>System.Web.Http</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Mvc\\System.Web.Mvc.csproj\">\n      <Project>{3d3ffd8a-624d-4e9b-954b-e1c105507975}</Project>\n      <Name>System.Web.Mvc</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Razor\\System.Web.Razor.csproj\">\n      <Project>{8f18041b-9410-4c36-a9c5-067813df5f31}</Project>\n      <Name>System.Web.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.WebPages.Deployment\\System.Web.WebPages.Deployment.csproj\">\n      <Project>{22babb60-8f02-4027-affc-acf069954536}</Project>\n      <Name>System.Web.WebPages.Deployment</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.WebPages.Razor\\System.Web.WebPages.Razor.csproj\">\n      <Project>{0939b11a-fe4e-4ba1-8ad6-d97741ee314f}</Project>\n      <Name>System.Web.WebPages.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.WebPages\\System.Web.WebPages.csproj\">\n      <Project>{76efa9c5-8d7e-4fdf-b710-e20f8b6b00d2}</Project>\n      <Name>System.Web.WebPages</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\">\n      <Project>{fccc4cb7-baf7-4a57-9f89-e5766fe536c0}</Project>\n      <Name>Microsoft.TestCommon</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <Service Include=\"{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Analyzer Include=\"..\\..\\packages\\xunit.analyzers.1.1.0\\analyzers\\dotnet\\cs\\xunit.analyzers.dll\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  <Target Name=\"EnsureNuGetPackageBuildImports\" BeforeTargets=\"PrepareForBuild\">\n    <PropertyGroup>\n      <ErrorText>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}.</ErrorText>\n    </PropertyGroup>\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props'))\" />\n  </Target>\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" />\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.\n       Other similar extension points exist, see Microsoft.Common.targets.\n  <Target Name=\"BeforeBuild\">\n  </Target>\n  <Target Name=\"AfterBuild\">\n  </Target>\n  -->\n</Project>"
  },
  {
    "path": "test/Microsoft.AspNet.Facebook.Test/Types/FacebookPicture.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.AspNet.Facebook.Test.Types\n{\n    public class FacebookPicture\n    {\n        public string Url { get; set; }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.AspNet.Facebook.Test/Types/SimpleUser.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.AspNet.Facebook.Test.Types\n{\n    public class SimpleUser\n    {\n        public string Id { get; set; }\n        public string Name { get; set; }\n        public FacebookConnection<FacebookPicture> Picture { get; set; }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.AspNet.Facebook.Test/Types/UserPhoto.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.AspNet.Facebook.Test.Types\n{\n    public class UserPhoto\n    {\n        public string Name { get; set; }\n\n        public string Picture { get; set; }\n\n        public string Source { get; set; }\n    }\n}"
  },
  {
    "path": "test/Microsoft.AspNet.Facebook.Test/Types/UserStatus.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.AspNet.Facebook.Test.Types\n{\n    public class UserStatus\n    {\n        public string Message { get; set; }\n\n        public long Time { get; set; }\n    }\n}"
  },
  {
    "path": "test/Microsoft.AspNet.Facebook.Test/Types/UserTypeWithFieldModifiers.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.AspNet.Facebook.Test.Types\n{\n    public class UserTypeWithFieldModifiers\n    {\n        public string Id { get; set; }\n        public string Name { get; set; }\n\n        [FacebookFieldModifier(\"type(large)\")]\n        public FacebookConnection<FacebookPicture> Picture { get; set; }\n\n        [FacebookFieldModifier(\"limit(5)\")]\n        public FacebookGroupConnection<SimpleUser> Friends { get; set; }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.AspNet.Facebook.Test/Types/UserTypeWithIgnoredProperties.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Newtonsoft.Json;\nnamespace Microsoft.AspNet.Facebook.Test.Types\n{\n    public class UserTypeWithIgnoredProperties\n    {\n        public string Id { get; set; }\n\n        [JsonIgnore]\n        public string Name { get; set; }\n\n        [JsonIgnore]\n        public FacebookConnection<FacebookPicture> Picture { get; set; }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.AspNet.Facebook.Test/Types/UserTypeWithRenamedProperties.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Newtonsoft.Json;\n\nnamespace Microsoft.AspNet.Facebook.Test.Types\n{\n    public class UserTypeWithRenamedProperties\n    {\n        [JsonProperty(\"Id\")]\n        public string FacebookId { get; set; }\n\n        public string Name { get; set; }\n\n        [JsonProperty(\"picture\")]\n        public FacebookConnection<FacebookPicture> PictureConnection { get; set; }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.AspNet.Facebook.Test/Types/UserTypesWithCycles.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.AspNet.Facebook.Test.Types\n{\n    public class UserWithUserFriends\n    {\n        public string Id { get; set; }\n        public string Name { get; set; }\n        public FacebookGroupConnection<UserWithUserFriends> Friends { get; set; }\n    }\n\n    public class UserContainingFriendsWithCycle\n    {\n        public string Id { get; set; }\n        public FacebookGroupConnection<UserWithUserFriends> Friends { get; set; }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.AspNet.Facebook.Test/Types/UserWithFriends.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.AspNet.Facebook.Test.Types\n{\n    public class UserWithFriends\n    {\n        public string Id { get; set; }\n        public string Name { get; set; }\n        public FacebookConnection<FacebookPicture> Picture { get; set; }\n        public FacebookGroupConnection<SimpleUser> Friends { get; set; }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.AspNet.Facebook.Test/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Castle.Core\" version=\"5.1.1\" targetFramework=\"net462\" />\n  <package id=\"Facebook\" version=\"6.4.2\" targetFramework=\"net462\" />\n  <package id=\"Moq\" version=\"4.18.4\" targetFramework=\"net462\" />\n  <package id=\"Newtonsoft.Json\" version=\"13.0.1\" targetFramework=\"net462\" />\n  <package id=\"xunit\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.abstractions\" version=\"2.0.3\" targetFramework=\"net462\" />\n  <package id=\"xunit.analyzers\" version=\"1.1.0\" targetFramework=\"net462\" />\n  <package id=\"xunit.assert\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.execution\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.runner.visualstudio\" version=\"2.4.5\" targetFramework=\"net462\" developmentDependency=\"true\" />\n</packages>"
  },
  {
    "path": "test/Microsoft.TestCommon/AppDomainUtils.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Reflection;\nusing System.Web.Compilation;\nusing System.Web.Hosting;\n\nnamespace System.Web.WebPages.TestUtils\n{\n    public static class AppDomainUtils\n    {\n        // Allow a test to modify static fields in an independent appdomain so that\n        // other tests will not be affected.\n        public static void RunInSeparateAppDomain(Action action)\n        {\n            RunInSeparateAppDomain(new AppDomainSetup(), action);\n        }\n\n        public static void RunInSeparateAppDomain(AppDomainSetup setup, Action action)\n        {\n            var dir = Path.GetDirectoryName(typeof(AppDomainUtils).Assembly.CodeBase).Replace(\"file:\\\\\", \"\");\n            setup.PrivateBinPath = dir;\n            setup.ApplicationBase = dir;\n            setup.ApplicationName = Guid.NewGuid().ToString();\n            setup.ShadowCopyFiles = \"true\";\n            setup.ShadowCopyDirectories = setup.ApplicationBase;\n            setup.CachePath = Path.Combine(Path.GetTempPath(), setup.ApplicationName);\n\n            AppDomain appDomain = null;\n            try\n            {\n                appDomain = AppDomain.CreateDomain(setup.ApplicationName, null, setup);\n                AppDomainHelper helper = appDomain.CreateInstanceAndUnwrap(typeof(AppDomainUtils).Assembly.FullName, typeof(AppDomainHelper).FullName) as AppDomainHelper;\n                helper.Run(action);\n            }\n            finally\n            {\n                if (appDomain != null)\n                {\n                    AppDomain.Unload(appDomain);\n                }\n            }\n        }\n\n        public class AppDomainHelper : MarshalByRefObject\n        {\n            public void Run(Action action)\n            {\n                action();\n            }\n        }\n\n        public static void SetPreAppStartStage()\n        {\n            var stage = typeof(BuildManager).GetProperty(\"PreStartInitStage\", BindingFlags.Static | BindingFlags.NonPublic);\n            var value = ((FieldInfo)typeof(BuildManager).Assembly.GetType(\"System.Web.Compilation.PreStartInitStage\").GetMember(\"DuringPreStartInit\")[0]).GetValue(null);\n            stage.SetValue(null, value, new object[] { });\n            SetAppData();\n            var env = new HostingEnvironment();\n        }\n\n        public static void SetAppData()\n        {\n            var appdomain = AppDomain.CurrentDomain;\n            // Set some dummy values to make the appdomain seem more like a ASP.NET hosted one\n            appdomain.SetData(\".appDomain\", \"*\");\n            appdomain.SetData(\".appId\", \"appId\");\n            appdomain.SetData(\".appPath\", \"appPath\");\n            appdomain.SetData(\".appVPath\", \"/WebSite1\");\n            appdomain.SetData(\".domainId\", \"1\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Assert.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.TestCommon\n{\n    // This extends xUnit.net's Assert class, and makes it partial so that we can\n    // organize the extension points by logical functionality (rather than dumping them\n    // all into this single file).\n    //\n    // See files named XxxAssertions for root extensions to Assert.\n    public partial class Assert : Xunit.Assert\n    {\n        public static readonly ReflectionAssert Reflection = new ReflectionAssert();\n\n        public static readonly TypeAssert Type = new TypeAssert();\n\n        public static readonly HttpAssert Http = new HttpAssert();\n\n        public static readonly MediaTypeAssert MediaType = new MediaTypeAssert();\n\n        public static readonly GenericTypeAssert GenericType = new GenericTypeAssert();\n\n        public static readonly SerializerAssert Serializer = new SerializerAssert();\n\n        public static readonly StreamAssert Stream = new StreamAssert();\n\n        public static readonly TaskAssert Task = new TaskAssert();\n\n        public static readonly XmlAssert Xml = new XmlAssert();\n\n        // Method has been marked [Obsolete] in xUnit.net v2.0.0+.\n        public static new void ReferenceEquals(object a, object b)\n        {\n            Same(a, b);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/CultureReplacer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Globalization;\nusing System.Threading;\n\nnamespace Microsoft.TestCommon\n{\n    public class CultureReplacer : IDisposable\n    {\n        private const string _defaultCultureName = \"en-GB\";\n        private const string _defaultUICultureName = \"en-US\";\n        private static readonly CultureInfo _defaultCulture = CultureInfo.GetCultureInfo(_defaultCultureName);\n        private readonly CultureInfo _originalCulture;\n        private readonly CultureInfo _originalUICulture;\n        private readonly long _threadId;\n\n        // Culture => Formatting of dates/times/money/etc, defaults to en-GB because en-US is the same as InvariantCulture\n        // We want to be able to find issues where the InvariantCulture is used, but a specific culture should be.\n        //\n        // UICulture => Language\n        public CultureReplacer(string culture = _defaultCultureName, string uiCulture = _defaultUICultureName)\n        {\n            _originalCulture = Thread.CurrentThread.CurrentCulture;\n            _originalUICulture = Thread.CurrentThread.CurrentUICulture;\n            _threadId = Thread.CurrentThread.ManagedThreadId;\n\n            Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(culture);\n            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(uiCulture);\n        }\n\n        /// <summary>\n        /// The name of the culture that is used as the default value for Thread.CurrentCulture when CultureReplacer is used.\n        /// </summary>\n        public static string DefaultCultureName\n        {\n            get { return _defaultCultureName; }\n        }\n\n        /// <summary>\n        /// The name of the culture that is used as the default value for Thread.UICurrentCulture when CultureReplacer is used.\n        /// </summary>\n        public static string DefaultUICultureName\n        {\n            get { return _defaultUICultureName; }\n        }\n\n        /// <summary>\n        /// The culture that is used as the default value for Thread.CurrentCulture when CultureReplacer is used.\n        /// </summary>\n        public static CultureInfo DefaultCulture\n        {\n            get { return _defaultCulture; }\n        }\n\n        public void Dispose()\n        {\n            Dispose(true);\n            GC.SuppressFinalize(this);\n        }\n\n        private void Dispose(bool disposing)\n        {\n            if (disposing)\n            {\n                Assert.True(Thread.CurrentThread.ManagedThreadId == _threadId, \"The current thread is not the same as the thread invoking the constructor. This should never happen.\");\n                Thread.CurrentThread.CurrentCulture = _originalCulture;\n                Thread.CurrentThread.CurrentUICulture = _originalUICulture;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/DataAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Reflection;\n\nnamespace Microsoft.TestCommon\n{\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]\n    public abstract class DataAttribute : Xunit.Sdk.DataAttribute\n    {\n        public abstract IEnumerable<Object[]> GetData(MethodInfo methodUnderTest, Type[] parameterTypes);\n\n        public override IEnumerable<Object[]> GetData(MethodInfo methodUnderTest)\n        {\n            return GetData(methodUnderTest, parameterTypes: null);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/DictionaryEqualityComparer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace Microsoft.TestCommon\n{\n    public class DictionaryEqualityComparer : IEqualityComparer<IDictionary<string, object>>\n    {\n        public bool Equals(IDictionary<string, object> x, IDictionary<string, object> y)\n        {\n            if (x.Count != y.Count)\n            {\n                return false;\n            }\n\n            foreach (string key in x.Keys)\n            {\n                object xVal = x[key];\n                object yVal;\n                if (!y.TryGetValue(key, out yVal))\n                {\n                    return false;\n                }\n\n                if (xVal == null)\n                {\n                    if (yVal == null)\n                    {\n                        continue;\n                    }\n\n                    return false;\n                }\n\n                if (!xVal.Equals(yVal))\n                {\n                    return false;\n                }\n            }\n\n            return true;\n        }\n\n        public int GetHashCode(IDictionary<string, object> obj)\n        {\n            return 1;\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Directory.Build.props",
    "content": "<Project>\n  <Import Project=\"..\\Directory.Build.props\" />\n\n  <PropertyGroup>\n    <!-- Set base intermediate output path early for ns1_3 but still exclude everything under the obj\\ folder. -->\n    <BaseIntermediateOutputPath Condition=\" '$(Testing_NetStandard1_3)' == 'true' \">obj\\ns1_3\\</BaseIntermediateOutputPath>\n    <DefaultItemExcludes>$(DefaultItemExcludes);obj\\**</DefaultItemExcludes>\n  </PropertyGroup>\n</Project>\n"
  },
  {
    "path": "test/Microsoft.TestCommon/EnumHelperTestBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\n\nnamespace Microsoft.TestCommon\n{\n    public abstract class EnumHelperTestBase<TEnum> where TEnum : IComparable, IFormattable, IConvertible\n    {\n        private Func<TEnum, bool> _isDefined;\n        private Action<TEnum, string> _validate;\n        private TEnum _undefined;\n\n        /// <summary>\n        /// Helper to verify that we validate enums correctly when passed as arguments etc.\n        /// </summary>\n        /// <param name=\"isDefined\">A Func used to validate that a value is defined.</param>\n        /// <param name=\"validate\">A Func used to validate that a value is definded of throw an exception.</param>\n        /// <param name=\"undefined\">An undefined value.</param>\n        protected EnumHelperTestBase(Func<TEnum, bool> isDefined, Action<TEnum, string> validate, TEnum undefined)\n        {\n            _isDefined = isDefined;\n            _validate = validate;\n            _undefined = undefined;\n        }\n\n        [Fact]\n        public void IsDefined_ReturnsTrueForDefinedValues()\n        {\n            Array values = Enum.GetValues(typeof(TEnum));\n            foreach (object value in values)\n            {\n                if (ValueExistsForFramework((TEnum)value))\n                {\n                    Assert.True(_isDefined((TEnum)value));\n                }\n                else\n                {\n                    Assert.False(_isDefined((TEnum)value));\n                }\n            }\n        }\n\n        [Fact]\n        public void IsDefined_ReturnsFalseForUndefinedValues()\n        {\n            Assert.False(_isDefined(_undefined));\n        }\n\n        [Fact]\n        public void Validate_DoesNotThrowForDefinedValues()\n        {\n            Array values = Enum.GetValues(typeof(TEnum));\n            foreach (object value in values)\n            {\n                if (ValueExistsForFramework((TEnum)value))\n                {\n                    _validate((TEnum)value, \"parameter\");\n                }\n            }\n        }\n\n        [Fact]\n        public void Validate_ThrowsForUndefinedValues()\n        {\n            AssertForUndefinedValue(\n                () => _validate(_undefined, \"parameter\"),\n                \"parameter\",\n                (int)Convert.ChangeType(_undefined, typeof(int)),\n                typeof(TEnum),\n                allowDerivedExceptions: false);\n        }\n\n        /// <summary>\n        /// Override this if InvalidEnumArgument is not supported in the targetted platform\n        /// </summary>\n        /// <param name=\"testCode\">A delegate to the code to be tested</param>\n        /// <param name=\"paramName\">The name of the parameter that should throw the exception</param>\n        /// <param name=\"invalidValue\">The expected invalid value that should appear in the message</param>\n        /// <param name=\"enumType\">The type of the enumeration</param>\n        /// <param name=\"allowDerivedExceptions\">Pass true to allow exceptions which derive from TException; pass false, otherwise</param>\n        protected virtual void AssertForUndefinedValue(Action testCode, string parameterName, int invalidValue, Type enumType, bool allowDerivedExceptions = false)\n        {\n            Assert.ThrowsInvalidEnumArgument(\n                testCode,\n                parameterName,\n                invalidValue,\n                enumType,\n                allowDerivedExceptions);\n        }\n\n        /// <summary>\n        /// Override this to determine if a given enum value for an enum exists in a given framework\n        /// </summary>\n        /// <param name=\"value\"></param>\n        /// <returns>Wheter the value exists</returns>\n        protected virtual bool ValueExistsForFramework(TEnum value)\n        {\n            return true;\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/ExceptionAssertions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.ComponentModel;\nusing System.Reflection;\nusing System.Threading.Tasks;\nusing System.Web;\n#if Testing_NetStandard1_3\nusing System.Web.Http;\n#endif\n\nnamespace Microsoft.TestCommon\n{\n    public partial class Assert\n    {\n        // Method has been removed in xUnit.net v2.0.0+.\n        public static void DoesNotThrow(Action testCode)\n        {\n            testCode();\n        }\n\n        /// <summary>\n        /// Verifies that the exact exception is thrown (and not a derived exception type).\n        /// </summary>\n        /// <typeparam name=\"T\">The type of the exception expected to be thrown</typeparam>\n        /// <param name=\"testCode\">A delegate to the code to be tested</param>\n        /// <returns>The exception that was thrown, when successful</returns>\n        /// <exception cref=\"ThrowsException\">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>\n        public static new T Throws<T>(Action testCode)\n            where T : Exception\n        {\n            return (T)Throws(typeof(T), testCode);\n        }\n\n        /// <summary>\n        /// Verifies that the exact exception is thrown (and not a derived exception type).\n        /// Generally used to test property accessors.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of the exception expected to be thrown</typeparam>\n        /// <param name=\"testCode\">A delegate to the code to be tested</param>\n        /// <returns>The exception that was thrown, when successful</returns>\n        /// <exception cref=\"ThrowsException\">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>\n        public static new T Throws<T>(Func<object> testCode)\n            where T : Exception\n        {\n            return (T)Throws(typeof(T), testCode);\n        }\n\n        /// <summary>\n        /// Verifies that the exact exception is thrown (and not a derived exception type).\n        /// </summary>\n        /// <param name=\"exceptionType\">The type of the exception expected to be thrown</param>\n        /// <param name=\"testCode\">A delegate to the code to be tested</param>\n        /// <returns>The exception that was thrown, when successful</returns>\n        /// <exception cref=\"ThrowsException\">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>\n        public static new Exception Throws(Type exceptionType, Action testCode)\n        {\n            Exception exception = RecordException(testCode);\n            return VerifyException(exceptionType, exception);\n        }\n\n        /// <summary>\n        /// Verifies that the exact exception is thrown (and not a derived exception type).\n        /// Generally used to test property accessors.\n        /// </summary>\n        /// <param name=\"exceptionType\">The type of the exception expected to be thrown</param>\n        /// <param name=\"testCode\">A delegate to the code to be tested</param>\n        /// <returns>The exception that was thrown, when successful</returns>\n        /// <exception cref=\"ThrowsException\">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>\n        public static new Exception Throws(Type exceptionType, Func<object> testCode)\n        {\n            return Throws(exceptionType, () => { testCode(); });\n        }\n\n        /// <summary>\n        /// Verifies that an exception of the given type (or optionally a derived type) is thrown.\n        /// </summary>\n        /// <typeparam name=\"TException\">The type of the exception expected to be thrown</typeparam>\n        /// <param name=\"testCode\">A delegate to the code to be tested</param>\n        /// <param name=\"allowDerivedExceptions\">Pass true to allow exceptions which derive from TException; pass false, otherwise</param>\n        /// <returns>The exception that was thrown, when successful</returns>\n        /// <exception cref=\"ThrowsException\">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>\n        public static TException Throws<TException>(Action testCode, bool allowDerivedExceptions)\n            where TException : Exception\n        {\n            Type exceptionType = typeof(TException);\n            Exception exception = RecordException(testCode);\n\n            TargetInvocationException tie = exception as TargetInvocationException;\n            if (tie != null)\n            {\n                exception = tie.InnerException;\n            }\n\n            if (exception == null)\n            {\n                throw new ThrowsException(exceptionType);\n            }\n\n            var typedException = exception as TException;\n            if (typedException == null || (!allowDerivedExceptions && typedException.GetType() != typeof(TException)))\n            {\n                throw new ThrowsException(exceptionType, exception);\n            }\n\n            return typedException;\n        }\n\n        /// <summary>\n        /// Verifies that an exception of the given type (or optionally a derived type) is thrown.\n        /// Generally used to test property accessors.\n        /// </summary>\n        /// <typeparam name=\"TException\">The type of the exception expected to be thrown</typeparam>\n        /// <param name=\"testCode\">A delegate to the code to be tested</param>\n        /// <param name=\"allowDerivedExceptions\">Pass true to allow exceptions which derive from TException; pass false, otherwise</param>\n        /// <returns>The exception that was thrown, when successful</returns>\n        /// <exception cref=\"ThrowsException\">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>\n        public static TException Throws<TException>(Func<object> testCode, bool allowDerivedExceptions)\n            where TException : Exception\n        {\n            return Throws<TException>(() => { testCode(); }, allowDerivedExceptions);\n        }\n\n        /// <summary>\n        /// Verifies that an exception of the given type (or optionally a derived type) is thrown.\n        /// Also verifies that the exception message matches.\n        /// </summary>\n        /// <typeparam name=\"TException\">The type of the exception expected to be thrown</typeparam>\n        /// <param name=\"testCode\">A delegate to the code to be tested</param>\n        /// <param name=\"exceptionMessage\">The exception message to verify</param>\n        /// <param name=\"allowDerivedExceptions\">Pass true to allow exceptions which derive from TException; pass false, otherwise</param>\n        /// <returns>The exception that was thrown, when successful</returns>\n        /// <exception cref=\"ThrowsException\">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>\n        public static TException Throws<TException>(Action testCode, string exceptionMessage, bool allowDerivedExceptions = false)\n            where TException : Exception\n        {\n            var ex = Throws<TException>(testCode, allowDerivedExceptions);\n            VerifyExceptionMessage(ex, exceptionMessage);\n            return ex;\n        }\n\n        /// <summary>\n        /// Verifies that an exception of the given type (or optionally a derived type) is thrown.\n        /// Also verified that the exception message matches.\n        /// </summary>\n        /// <typeparam name=\"TException\">The type of the exception expected to be thrown</typeparam>\n        /// <param name=\"testCode\">A delegate to the code to be tested</param>\n        /// <param name=\"exceptionMessage\">The exception message to verify</param>\n        /// <param name=\"allowDerivedExceptions\">Pass true to allow exceptions which derive from TException; pass false, otherwise</param>\n        /// <returns>The exception that was thrown, when successful</returns>\n        /// <exception cref=\"ThrowsException\">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>\n        public static TException Throws<TException>(Func<object> testCode, string exceptionMessage, bool allowDerivedExceptions = false)\n            where TException : Exception\n        {\n            return Throws<TException>(() => { testCode(); }, exceptionMessage, allowDerivedExceptions);\n        }\n\n        /// <summary>\n        /// Verifies that the code throws an <see cref=\"ArgumentException\"/> (or optionally any exception which derives from it).\n        /// </summary>\n        /// <param name=\"testCode\">A delegate to the code to be tested</param>\n        /// <param name=\"paramName\">The name of the parameter that should throw the exception</param>\n        /// <param name=\"allowDerivedExceptions\">Pass true to allow exceptions which derive from TException; pass false, otherwise</param>\n        /// <returns>The exception that was thrown, when successful</returns>\n        /// <exception cref=\"ThrowsException\">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>\n        public static ArgumentException ThrowsArgument(Action testCode, string paramName, bool allowDerivedExceptions = false)\n        {\n            var ex = Throws<ArgumentException>(testCode, allowDerivedExceptions);\n\n            if (paramName != null)\n            {\n                Equal(paramName, ex.ParamName);\n            }\n\n            return ex;\n        }\n\n        /// <summary>\n        /// Verifies the given <paramref name=\"testCode\"/> throws an <see cref=\"ArgumentException\"/>.\n        /// </summary>\n        /// <param name=\"testCode\">A delegate to the code to be tested.</param>\n        /// <param name=\"paramName\">The name of the parameter that should throw the exception.</param>\n        /// <returns>A <see cref=\"Task\"/> that on completion returns the exception that was thrown.</returns>\n        public static async Task<ArgumentException> ThrowsArgumentAsync(Func<Task> testCode, string paramName)\n        {\n            var ex = await ThrowsAsync<ArgumentException>(testCode);\n            if (paramName != null)\n            {\n                Equal(paramName, ex.ParamName);\n            }\n\n            return ex;\n        }\n\n        /// <summary>\n        /// Verifies that the code throws an <see cref=\"ArgumentException\"/> (or optionally any exception which derives from it).\n        /// </summary>\n        /// <param name=\"testCode\">A delegate to the code to be tested</param>\n        /// <param name=\"paramName\">The name of the parameter that should throw the exception</param>\n        /// <param name=\"exceptionMessage\">The exception message to verify</param>\n        /// <param name=\"allowDerivedExceptions\">Pass true to allow exceptions which derive from TException; pass false, otherwise</param>\n        /// <returns>The exception that was thrown, when successful</returns>\n        /// <exception cref=\"ThrowsException\">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>\n        public static ArgumentException ThrowsArgument(Action testCode, string paramName, string exceptionMessage, bool allowDerivedExceptions = false)\n        {\n            var ex = Throws<ArgumentException>(testCode, allowDerivedExceptions);\n\n            if (paramName != null)\n            {\n                Equal(paramName, ex.ParamName);\n            }\n\n            VerifyExceptionMessage(ex, exceptionMessage, partialMatch: true);\n\n            return ex;\n        }\n\n        /// <summary>\n        /// Verifies that the <paramref name=\"testCode\"/> throws an <see cref=\"ArgumentException\"/>.\n        /// </summary>\n        /// <param name=\"testCode\">A delegate to the code to be tested.</param>\n        /// <param name=\"paramName\">The name of the parameter that should throw the exception.</param>\n        /// <param name=\"exceptionMessage\">The exception message to verify (or a portion of the expected message).</param>\n        /// <returns>A <see cref=\"Task\"/> that on completion returns the exception that was thrown.</returns>\n        public static async Task<ArgumentException> ThrowsArgumentAsync(Func<Task> testCode, string paramName, string exceptionMessage)\n        {\n            var ex = await ThrowsArgumentAsync(testCode, paramName);\n            VerifyExceptionMessage(ex, exceptionMessage, partialMatch: true);\n\n            return ex;\n        }\n\n        /// <summary>\n        /// Verifies that the code throws an ArgumentException (or optionally any exception which derives from it).\n        /// </summary>\n        /// <param name=\"testCode\">A delegate to the code to be tested</param>\n        /// <param name=\"paramName\">The name of the parameter that should throw the exception</param>\n        /// <param name=\"allowDerivedExceptions\">Pass true to allow exceptions which derive from TException; pass false, otherwise</param>\n        /// <returns>The exception that was thrown, when successful</returns>\n        /// <exception cref=\"ThrowsException\">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>\n        public static ArgumentException ThrowsArgument(Func<object> testCode, string paramName, bool allowDerivedExceptions = false)\n        {\n            var ex = Throws<ArgumentException>(testCode, allowDerivedExceptions);\n\n            if (paramName != null)\n            {\n                Equal(paramName, ex.ParamName);\n            }\n\n            return ex;\n        }\n\n        /// <summary>\n        /// Verifies that the code throws an ArgumentNullException (or optionally any exception which derives from it).\n        /// </summary>\n        /// <param name=\"testCode\">A delegate to the code to be tested</param>\n        /// <param name=\"paramName\">The name of the parameter that should throw the exception</param>\n        /// <returns>The exception that was thrown, when successful</returns>\n        /// <exception cref=\"ThrowsException\">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>\n        public static ArgumentNullException ThrowsArgumentNull(Action testCode, string paramName)\n        {\n            var ex = Throws<ArgumentNullException>(testCode, allowDerivedExceptions: false);\n\n            if (paramName != null)\n            {\n                Equal(paramName, ex.ParamName);\n            }\n\n            return ex;\n        }\n\n        /// <summary>\n        /// Verifies that the <paramref name=\"testCode\"/> throws an <see cref=\"ArgumentNullException\"/>.\n        /// </summary>\n        /// <param name=\"testCode\">A delegate to the code to be tested.</param>\n        /// <param name=\"paramName\">The name of the parameter that should throw the exception.</param>\n        /// <returns>A <see cref=\"Task\"/> that on completion returns the exception that was thrown.</returns>\n        public static async Task<ArgumentNullException> ThrowsArgumentNullAsync(Func<Task> testCode, string paramName)\n        {\n            var ex = await ThrowsAsync<ArgumentNullException>(testCode);\n            if (paramName != null)\n            {\n                Equal(paramName, ex.ParamName);\n            }\n\n            return ex;\n        }\n\n        /// <summary>\n        /// Verifies that the code throws an ArgumentNullException with the expected message that indicates that the value cannot\n        /// be null or empty.\n        /// </summary>\n        /// <param name=\"testCode\">A delegate to the code to be tested</param>\n        /// <param name=\"paramName\">The name of the parameter that should throw the exception</param>\n        /// <returns>The exception that was thrown, when successful</returns>\n        /// <exception cref=\"ThrowsException\">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>\n        public static ArgumentException ThrowsArgumentNullOrEmpty(Action testCode, string paramName)\n        {\n            return Throws<ArgumentException>(testCode, \"Value cannot be null or empty.\" + GetParameterMessage(paramName), allowDerivedExceptions: false);\n        }\n\n        /// <summary>\n        /// Verifies that the code throws an ArgumentNullException with the expected message that indicates that the value cannot\n        /// be null or empty string.\n        /// </summary>\n        /// <param name=\"testCode\">A delegate to the code to be tested</param>\n        /// <param name=\"paramName\">The name of the parameter that should throw the exception</param>\n        /// <returns>The exception that was thrown, when successful</returns>\n        /// <exception cref=\"ThrowsException\">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>\n        public static ArgumentException ThrowsArgumentNullOrEmptyString(Action testCode, string paramName)\n        {\n            return ThrowsArgument(testCode, paramName, \"Value cannot be null or an empty string.\", allowDerivedExceptions: true);\n        }\n\n        /// <summary>\n        /// Verifies that the code throws an ArgumentOutOfRangeException (or optionally any exception which derives from it).\n        /// </summary>\n        /// <param name=\"testCode\">A delegate to the code to be tested</param>\n        /// <param name=\"paramName\">The name of the parameter that should throw the exception</param>\n        /// <param name=\"exceptionMessage\">The exception message to verify</param>\n        /// <param name=\"allowDerivedExceptions\">Pass true to allow exceptions which derive from TException; pass false, otherwise</param>\n        /// <param name=\"actualValue\">The actual value provided</param>\n        /// <returns>The exception that was thrown, when successful</returns>\n        /// <exception cref=\"ThrowsException\">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>\n        public static ArgumentOutOfRangeException ThrowsArgumentOutOfRange(Action testCode, string paramName, string exceptionMessage, bool allowDerivedExceptions = false, object actualValue = null)\n        {\n            if (exceptionMessage != null)\n            {\n                exceptionMessage = exceptionMessage + GetParameterMessage(paramName);\n                if (actualValue != null)\n                {\n                    exceptionMessage += String.Format(CultureReplacer.DefaultCulture, \"\\r\\nActual value was {0}.\", actualValue);\n                }\n            }\n\n            var ex = Throws<ArgumentOutOfRangeException>(testCode, exceptionMessage, allowDerivedExceptions);\n\n            if (paramName != null)\n            {\n                Equal(paramName, ex.ParamName);\n            }\n\n            return ex;\n        }\n\n        /// <summary>\n        /// Verifies that the <paramref name=\"testCode\"/> throws an <see cref=\"ArgumentOutOfRangeException\"/>.\n        /// </summary>\n        /// <param name=\"testCode\">A delegate to the code to be tested.</param>\n        /// <param name=\"paramName\">The name of the parameter that should throw the exception.</param>\n        /// <param name=\"exceptionMessage\">The exception message to verify (or a portion of the expected message).</param>\n        /// <param name=\"actualValue\">The actual value passed in for <paramref name=\"paramName\"/>.</param>\n        /// <returns>A <see cref=\"Task\"/> that on completion returns the exception that was thrown.</returns>\n        public static async Task<ArgumentOutOfRangeException> ThrowsArgumentOutOfRangeAsync(\n            Func<Task> testCode,\n            string paramName,\n            string exceptionMessage,\n            object actualValue = null)\n        {\n            if (exceptionMessage != null)\n            {\n                exceptionMessage = exceptionMessage + GetParameterMessage(paramName);\n                if (actualValue != null)\n                {\n                    exceptionMessage += String.Format(CultureReplacer.DefaultCulture, \"\\r\\nActual value was {0}.\", actualValue);\n                }\n            }\n\n            var ex = await ThrowsAsync<ArgumentOutOfRangeException>(testCode, exceptionMessage, partialMatch: true);\n            if (paramName != null)\n            {\n                Equal(paramName, ex.ParamName);\n            }\n\n            return ex;\n        }\n\n        /// <summary>\n        /// Verifies that the code throws an <see cref=\"ArgumentOutOfRangeException\"/> with the expected message that indicates that\n        /// the value must be greater than the given <paramref name=\"value\"/>.\n        /// </summary>\n        /// <param name=\"testCode\">A delegate to the code to be tested</param>\n        /// <param name=\"paramName\">The name of the parameter that should throw the exception</param>\n        /// <param name=\"actualValue\">The actual value provided.</param>\n        /// <param name=\"value\">The expected limit value.</param>\n        /// <returns>The exception that was thrown, when successful</returns>\n        /// <exception cref=\"ThrowsException\">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>\n        public static ArgumentOutOfRangeException ThrowsArgumentGreaterThan(Action testCode, string paramName, string value, object actualValue = null)\n        {\n            return ThrowsArgumentOutOfRange(\n                        testCode,\n                        paramName,\n                        String.Format(CultureReplacer.DefaultCulture, \"Value must be greater than {0}.\", value), false, actualValue);\n        }\n\n        /// <summary>\n        /// Verifies that the code throws an <see cref=\"ArgumentOutOfRangeException\"/> with the expected message that indicates that\n        /// the value must be greater than or equal to the given value.\n        /// </summary>\n        /// <param name=\"testCode\">A delegate to the code to be tested</param>\n        /// <param name=\"paramName\">The name of the parameter that should throw the exception</param>\n        /// <param name=\"value\">The expected limit value.</param>\n        /// <returns>The exception that was thrown, when successful</returns>\n        /// <exception cref=\"ThrowsException\">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>\n        public static ArgumentOutOfRangeException ThrowsArgumentGreaterThanOrEqualTo(Action testCode, string paramName, string value, object actualValue = null)\n        {\n            return ThrowsArgumentOutOfRange(\n                        testCode,\n                        paramName,\n                        String.Format(CultureReplacer.DefaultCulture, \"Value must be greater than or equal to {0}.\", value), false, actualValue);\n        }\n\n        /// <summary>\n        /// Verifies that the <paramref name=\"testCode\"/> throws an <see cref=\"ArgumentOutOfRangeException\"/>.\n        /// </summary>\n        /// <param name=\"testCode\">A delegate to the code to be tested.</param>\n        /// <param name=\"paramName\">The name of the parameter that should throw the exception.</param>\n        /// <param name=\"value\">The minimum allowed value for <paramref name=\"paramName\"/>.</param>\n        /// <param name=\"actualValue\">The actual value passed in for <paramref name=\"paramName\"/>.</param>\n        /// <returns>A <see cref=\"Task\"/> that on completion returns the exception that was thrown.</returns>\n        public static Task<ArgumentOutOfRangeException> ThrowsArgumentGreaterThanOrEqualToAsync(\n            Func<Task> testCode,\n            string paramName,\n            string value,\n            object actualValue = null)\n        {\n            return ThrowsArgumentOutOfRangeAsync(\n                testCode,\n                paramName,\n                String.Format(CultureReplacer.DefaultCulture, \"Value must be greater than or equal to {0}.\", value),\n                actualValue);\n        }\n\n\n        /// <summary>\n        /// Verifies that the code throws an <see cref=\"ArgumentOutOfRangeException\"/> with the expected message that indicates that\n        /// the value must be less than the given <paramref name=\"maxValue\"/>.\n        /// </summary>\n        /// <param name=\"testCode\">A delegate to the code to be tested</param>\n        /// <param name=\"paramName\">The name of the parameter that should throw the exception</param>\n        /// <param name=\"actualValue\">The actual value provided.</param>\n        /// <param name=\"maxValue\">The expected limit value.</param>\n        /// <returns>The exception that was thrown, when successful</returns>\n        /// <exception cref=\"ThrowsException\">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>\n        public static ArgumentOutOfRangeException ThrowsArgumentLessThan(Action testCode, string paramName, string maxValue, object actualValue = null)\n        {\n            return ThrowsArgumentOutOfRange(\n                        testCode,\n                        paramName,\n                        String.Format(CultureReplacer.DefaultCulture, \"Value must be less than {0}.\", maxValue), false, actualValue);\n        }\n\n        /// <summary>\n        /// Verifies that the code throws an <see cref=\"ArgumentOutOfRangeException\"/> with the expected message that indicates that\n        /// the value must be less than or equal to the given <paramref name=\"maxValue\"/>.\n        /// </summary>\n        /// <param name=\"testCode\">A delegate to the code to be tested</param>\n        /// <param name=\"paramName\">The name of the parameter that should throw the exception</param>\n        /// <param name=\"actualValue\">The actual value provided.</param>\n        /// <param name=\"maxValue\">The expected limit value.</param>\n        /// <returns>The exception that was thrown, when successful</returns>\n        /// <exception cref=\"ThrowsException\">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>\n        public static ArgumentOutOfRangeException ThrowsArgumentLessThanOrEqualTo(Action testCode, string paramName, string maxValue, object actualValue = null)\n        {\n            return ThrowsArgumentOutOfRange(\n                        testCode,\n                        paramName,\n                        String.Format(CultureReplacer.DefaultCulture, \"Value must be less than or equal to {0}.\", maxValue), false, actualValue);\n        }\n\n#if !NETCOREAPP\n        /// <summary>\n        /// Verifies that the code throws an HttpException (or optionally any exception which derives from it).\n        /// </summary>\n        /// <param name=\"testCode\">A delegate to the code to be tested</param>\n        /// <param name=\"exceptionMessage\">The exception message to verify</param>\n        /// <param name=\"httpCode\">The expected HTTP status code of the exception</param>\n        /// <param name=\"allowDerivedExceptions\">Pass true to allow exceptions which derive from TException; pass false, otherwise</param>\n        /// <returns>The exception that was thrown, when successful</returns>\n        /// <exception cref=\"ThrowsException\">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>\n        public static HttpException ThrowsHttpException(Action testCode, string exceptionMessage, int httpCode, bool allowDerivedExceptions = false)\n        {\n            var ex = Throws<HttpException>(testCode, exceptionMessage, allowDerivedExceptions);\n            Equal(httpCode, ex.GetHttpCode());\n            return ex;\n        }\n#endif\n\n        /// <summary>\n        /// Verifies that the code throws an InvalidEnumArgumentException (or optionally any exception which derives from it).\n        /// </summary>\n        /// <param name=\"testCode\">A delegate to the code to be tested</param>\n        /// <param name=\"paramName\">The name of the parameter that should throw the exception</param>\n        /// <param name=\"invalidValue\">The expected invalid value that should appear in the message</param>\n        /// <param name=\"enumType\">The type of the enumeration</param>\n        /// <param name=\"allowDerivedExceptions\">Pass true to allow exceptions which derive from TException; pass false, otherwise</param>\n        /// <returns>The exception that was thrown, when successful</returns>\n        /// <exception cref=\"ThrowsException\">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>\n        public static ArgumentException ThrowsInvalidEnumArgument(Action testCode, string paramName, int invalidValue, Type enumType, bool allowDerivedExceptions = false)\n        {\n            string message = String.Format(CultureReplacer.DefaultCulture,\n                                           \"The value of argument '{0}' ({1}) is invalid for Enum type '{2}'.{3}\",\n                                           paramName, invalidValue, enumType.Name, GetParameterMessage(paramName));\n\n#if Testing_NetStandard1_3 // InvalidEnumArgumentException not available in netstandard1.3.\n            return Throws<Error.InvalidEnumArgumentException>(testCode, message, allowDerivedExceptions);\n#else\n            return Throws<InvalidEnumArgumentException>(testCode, message, allowDerivedExceptions);\n#endif\n        }\n\n        /// <summary>\n        /// Verifies that the code throws an HttpException (or optionally any exception which derives from it).\n        /// </summary>\n        /// <param name=\"testCode\">A delegate to the code to be tested</param>\n        /// <param name=\"objectName\">The name of the object that was dispose</param>\n        /// <param name=\"allowDerivedExceptions\">Pass true to allow exceptions which derive from TException; pass false, otherwise</param>\n        /// <returns>The exception that was thrown, when successful</returns>\n        /// <exception cref=\"ThrowsException\">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>\n        public static ObjectDisposedException ThrowsObjectDisposed(Action testCode, string objectName, bool allowDerivedExceptions = false)\n        {\n            var ex = Throws<ObjectDisposedException>(testCode, allowDerivedExceptions);\n\n            if (objectName != null)\n            {\n                Equal(objectName, ex.ObjectName);\n            }\n\n            return ex;\n        }\n\n        /// <summary>\n        /// Verifies that an exception of the given type is thrown.\n        /// </summary>\n        /// <typeparam name=\"TException\">The type of the exception expected to be thrown</typeparam>\n        /// <param name=\"testCode\">A delegate to the code to be tested</param>\n        /// <returns>The exception that was thrown, when successful</returns>\n        /// <exception cref=\"ThrowsException\">Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown</exception>\n        /// <remarks>\n        /// Unlike other Throws* methods, this method does not enforce running the exception delegate with a known Thread Culture.\n        /// </remarks>\n        public static new async Task<TException> ThrowsAsync<TException>(Func<Task> testCode)\n            where TException : Exception\n        {\n            Exception exception = null;\n            try\n            {\n                // The 'testCode' Task might execute asynchronously in a different thread making it hard to enforce the thread culture.\n                // The correct way to verify exception messages in such a scenario would be to run the task synchronously inside of a\n                // culture enforced block.\n                await testCode();\n            }\n            catch (Exception ex)\n            {\n                exception = ex;\n            }\n            VerifyException(typeof(TException), exception);\n            return (TException)exception;\n        }\n\n        /// <summary>\n        /// Verifies that the <paramref name=\"testCode\"/> throws a <typeparamref name=\"TException\"/>.\n        /// </summary>\n        /// <typeparam name=\"TException\">The type of <see cref=\"Exception\"/> expected to be thrown.</typeparam>\n        /// <param name=\"testCode\">A delegate to the code to be tested.</param>\n        /// <param name=\"exceptionMessage\">The exception message to verify (or a portion of the expected message).</param>\n        /// <param name=\"partialMatch\">\n        /// If <paramref name=\"exceptionMessage\"/> is <c>null</c>, ignores this parameter. Otherwise if this parameter\n        /// is <c>true</c>, verifies the exception message contains <paramref name=\"exceptionMessage\"/>. Otherwise,\n        /// verifies the exception message exactly matches <paramref name=\"exceptionMessage\"/>.\n        /// </param>\n        /// <returns>A <see cref=\"Task\"/> that on completion returns the exception that was thrown.</returns>\n        public static async Task<TException> ThrowsAsync<TException>(\n            Func<Task> testCode,\n            string exceptionMessage,\n            bool partialMatch = false) where TException : Exception\n        {\n            var ex = await ThrowsAsync<TException>(testCode);\n            VerifyExceptionMessage(ex, exceptionMessage, partialMatch);\n            return ex;\n        }\n\n        private static string GetParameterMessage(string parameterName)\n        {\n#if NETCOREAPP3_1_OR_GREATER\n            return \" (Parameter '\" + parameterName + \"')\";\n#else\n            return Environment.NewLine + \"Parameter name: \" + parameterName;\n#endif\n        }\n\n        // We've re-implemented all the xUnit.net Throws code so that we can get this\n        // updated implementation of RecordException which silently unwraps any instances\n        // of AggregateException. In addition to unwrapping exceptions, this method ensures\n        // that tests are executed in with a known set of Culture and UICulture. This prevents\n        // tests from failing when executed on a non-English machine.\n        private static new Exception RecordException(Action testCode)\n        {\n            try\n            {\n                using (new CultureReplacer())\n                {\n                    testCode();\n                }\n                return null;\n            }\n            catch (Exception exception)\n            {\n                return UnwrapException(exception);\n            }\n        }\n\n        private static Exception UnwrapException(Exception exception)\n        {\n            AggregateException aggEx = exception as AggregateException;\n            if (aggEx != null)\n            {\n                return aggEx.GetBaseException();\n            }\n            return exception;\n        }\n\n        private static Exception VerifyException(Type exceptionType, Exception exception)\n        {\n            if (exception == null)\n            {\n                throw new ThrowsException(exceptionType);\n            }\n            else if (exceptionType != exception.GetType())\n            {\n                throw new ThrowsException(exceptionType, exception);\n            }\n\n            return exception;\n        }\n\n        private static void VerifyExceptionMessage(Exception exception, string expectedMessage, bool partialMatch = false)\n        {\n            if (expectedMessage != null)\n            {\n                if (!partialMatch)\n                {\n                    Equal(expectedMessage, exception.Message);\n                }\n                else\n                {\n                    Contains(expectedMessage, exception.Message);\n                }\n            }\n        }\n\n        // Custom ThrowsException so we can filter the stack trace.\n        [Serializable]\n        private class ThrowsException : Xunit.Sdk.ThrowsException\n        {\n            public ThrowsException(Type type) : base(type) { }\n\n            public ThrowsException(Type type, Exception ex) : base(type, ex) { }\n\n            public override string StackTrace\n            {\n                get\n                {\n                    return ExceptionUtility.FilterStackTrace(base.StackTrace);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/ExceptionUtility.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\n\n// Variation of Xunit.Sdk.ExceptionUtility which helps with Exceptions and their stack traces.\nnamespace Microsoft.TestCommon\n{\n    public static class ExceptionUtility\n    {\n        public static string FilterStackTrace(string stack)\n        {\n            if (stack == null)\n            {\n                return null;\n            }\n\n            var results = new List<string>();\n            foreach (var line in SplitLines(stack))\n            {\n                var trimmedLine = line.TrimStart();\n                if (!ExcludeStackFrame(trimmedLine))\n                {\n                    results.Add(line);\n                }\n            }\n\n            return string.Join(Environment.NewLine, results);\n        }\n\n        private static IEnumerable<string> SplitLines(string input)\n        {\n            while (true)\n            {\n                var index = input.IndexOf(Environment.NewLine, StringComparison.Ordinal);\n                if (index < 0)\n                {\n                    yield return input;\n                    break;\n                }\n\n                yield return input.Substring(0, index);\n                input = input.Substring(index + Environment.NewLine.Length);\n            }\n        }\n\n        private static bool ExcludeStackFrame(string stackFrame)\n        {\n            if (stackFrame.StartsWith(\"at Microsoft.TestCommon.Assert.\", StringComparison.OrdinalIgnoreCase))\n            {\n                return true;\n            }\n\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/FactAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing Xunit.Sdk;\n\nnamespace Microsoft.TestCommon\n{\n    /// <summary>\n    /// An override of <see cref=\"Xunit.FactAttribute\"/> that provides extended capabilities.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]\n    [XunitTestCaseDiscoverer(\"Microsoft.TestCommon.FactDiscoverer\", \"Microsoft.TestCommon\")]\n    public class FactAttribute : Xunit.FactAttribute\n    {\n        /// <summary>\n        /// Instantiates a new instance of <see cref=\"FactAttribute\"/>.\n        /// </summary>\n        public FactAttribute()\n        {\n            Platforms = Platform.All;\n            PlatformJustification = \"Unsupported platform (test runs on {0}, current platform is {1})\";\n        }\n\n        /// <summary>\n        /// Gets or set the platforms that the unit test is compatible with. Defaults to\n        /// <see cref=\"Platform.All\"/>.\n        /// </summary>\n        public Platform Platforms { get; set; }\n\n        /// <summary>\n        /// Gets or sets the platform skipping justification. This message can receive\n        /// the supported platforms as {0}, and the current platform as {1}.\n        /// </summary>\n        public string PlatformJustification { get; set; }\n    }\n}"
  },
  {
    "path": "test/Microsoft.TestCommon/FactDiscoverer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing Xunit.Abstractions;\nusing Xunit.Sdk;\n\nnamespace Microsoft.TestCommon\n{\n    /// <summary>\n    /// An override of <see cref=\"Xunit.Sdk.FactDiscoverer\"/> that provides extended capabilities.\n    /// </summary>\n    class FactDiscoverer : Xunit.Sdk.FactDiscoverer\n    {\n        private readonly IMessageSink _diagnosticMessageSink;\n\n        /// <summary>\n        /// Instantiates a new <see cref=\"FactDiscoverer\"/> instance.\n        /// </summary>\n        /// <param name=\"diagnosticMessageSink\">The <see cref=\"IMessageSink\"/> used to send diagnostic messages.</param>\n        public FactDiscoverer(IMessageSink diagnosticMessageSink)\n            : base(diagnosticMessageSink)\n        {\n            _diagnosticMessageSink = diagnosticMessageSink;\n        }\n\n        /// <summary>\n        /// Gets the platform that the unit test is currently running on.\n        /// </summary>\n        protected Platform Platform\n        {\n            get { return PlatformInfo.Platform; }\n        }\n\n        /// <inheritdoc/>\n        public override IEnumerable<IXunitTestCase> Discover(\n            ITestFrameworkDiscoveryOptions discoveryOptions,\n            ITestMethod testMethod,\n            IAttributeInfo factAttribute)\n        {\n            var baseCases = base.Discover(discoveryOptions, testMethod, factAttribute);\n            if (!String.IsNullOrEmpty(factAttribute.GetNamedArgument<string>(\"Skip\")))\n            {\n                // No need to change skipped tests.\n                return baseCases;\n            }\n\n            var platforms = factAttribute.GetNamedArgument<Platform>(\"Platforms\");\n            if ((platforms & Platform) != 0)\n            {\n                // No need to change tests that should run on the current platform.\n                return baseCases;\n            }\n\n            // Base implementation always returns a single test case.\n            var baseCase = baseCases.FirstOrDefault();\n            Contract.Assert(baseCase != null);\n            if (baseCase is ExecutionErrorTestCase)\n            {\n                // No need to change an erroneous test.\n                return baseCases;\n            }\n\n            if (!String.IsNullOrEmpty(baseCase.SkipReason))\n            {\n                // No need to change a skipped test. Covered to protect against changes in the base class.\n                return baseCases;\n            }\n\n            // Replace test with its skipped equivalent.\n            var platformJustification = factAttribute.GetNamedArgument<string>(\"PlatformJustification\");\n            var skipReason = String.Format(platformJustification, platforms.ToString().Replace(\", \", \" | \"), Platform);\n            var testCase = new SkippedXunitTestCase(\n                _diagnosticMessageSink,\n                discoveryOptions.MethodDisplayOrDefault(),\n                TestMethodDisplayOptions.None,\n                skipReason,\n                baseCase.TestMethod,\n                baseCase.TestMethodArguments);\n\n            return new[] { testCase };\n        }\n    }\n}"
  },
  {
    "path": "test/Microsoft.TestCommon/ForceGCAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Reflection;\n\nnamespace Microsoft.TestCommon\n{\n    public class ForceGCAttribute : Xunit.Sdk.BeforeAfterTestAttribute\n    {\n        public override void After(MethodInfo methodUnderTest)\n        {\n            GC.Collect(99);\n            GC.Collect(99);\n            GC.Collect(99);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/InlineDataAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing Xunit.Sdk;\n\nnamespace Microsoft.TestCommon\n{\n    // Xunit.InlineDataAttribute is unfortunately sealed. Delegate to an instance to avoid duplicating its code.\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]\n    [DataDiscoverer(\"Xunit.Sdk.InlineDataDiscoverer\", \"xunit.core\")]\n    public class InlineDataAttribute : Xunit.Sdk.DataAttribute\n    {\n        Xunit.InlineDataAttribute _inner;\n\n        public InlineDataAttribute(params object[] dataValues)\n            : base()\n        {\n            _inner = new Xunit.InlineDataAttribute(dataValues);\n        }\n\n        public override IEnumerable<object[]> GetData(MethodInfo testMethod)\n        {\n            return _inner.GetData(testMethod);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/MatrixTheoryDataSet.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\n\nnamespace Microsoft.TestCommon\n{\n    public class MatrixTheoryDataSet<T1, T2> : TheoryDataSet<T1, T2>\n    {\n        public MatrixTheoryDataSet(IEnumerable<T1> data1, IEnumerable<T2> data2)\n        {\n            Contract.Assert(data1 != null && data1.Any());\n            Contract.Assert(data2 != null && data2.Any());\n\n            foreach (T1 t1 in data1)\n            {\n                foreach (T2 t2 in data2)\n                {\n                    Add(t1, t2);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/MemberHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Reflection;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.TestUtil\n{\n    public static class MemberHelper\n    {\n        private static ConstructorInfo GetConstructorInfo(object instance, Type[] parameterTypes)\n        {\n            if (instance == null)\n            {\n                throw new ArgumentNullException(\"instance\");\n            }\n            ConstructorInfo constructorInfo = instance.GetType().GetConstructor(parameterTypes);\n            if (constructorInfo == null)\n            {\n                throw new ArgumentException(String.Format(\n                    \"A matching constructor on type '{0}' could not be found.\",\n                    instance.GetType().FullName));\n            }\n            return constructorInfo;\n        }\n\n        private static EventInfo GetEventInfo(object instance, string eventName)\n        {\n            if (instance == null)\n            {\n                throw new ArgumentNullException(\"instance\");\n            }\n            if (String.IsNullOrEmpty(eventName))\n            {\n                throw new ArgumentException(\"An event must be specified.\", \"eventName\");\n            }\n            EventInfo eventInfo = instance.GetType().GetEvent(eventName);\n            if (eventInfo == null)\n            {\n                throw new ArgumentException(String.Format(\n                    \"An event named '{0}' on type '{1}' could not be found.\",\n                    eventName, instance.GetType().FullName));\n            }\n            return eventInfo;\n        }\n\n        private static MethodInfo GetMethodInfo(object instance, string methodName, Type[] types = null, MethodAttributes attrs = MethodAttributes.Public)\n        {\n            if (instance == null)\n            {\n                throw new ArgumentNullException(\"instance\");\n            }\n            if (String.IsNullOrEmpty(methodName))\n            {\n                throw new ArgumentException(\"A method must be specified.\", \"methodName\");\n            }\n\n            MethodInfo methodInfo;\n            if (types != null)\n            {\n                methodInfo = instance.GetType().GetMethod(methodName,\n                                                          BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,\n                                                          null,\n                                                          types,\n                                                          null);\n            }\n            else\n            {\n                methodInfo = instance.GetType().GetMethod(methodName,\n                                                          BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);\n            }\n\n            if (methodInfo == null)\n            {\n                throw new ArgumentException(String.Format(\n                    \"A method named '{0}' on type '{1}' could not be found.\",\n                    methodName, instance.GetType().FullName));\n            }\n\n            if ((methodInfo.Attributes & attrs) != attrs)\n            {\n                throw new ArgumentException(String.Format(\n                    \"Method '{0}' on type '{1}' with attributes '{2}' does not match the attributes '{3}'.\",\n                    methodName, instance.GetType().FullName, methodInfo.Attributes, attrs));\n            }\n\n            return methodInfo;\n        }\n\n        private static PropertyInfo GetPropertyInfo(object instance, string propertyName)\n        {\n            if (instance == null)\n            {\n                throw new ArgumentNullException(\"instance\");\n            }\n            if (String.IsNullOrEmpty(propertyName))\n            {\n                throw new ArgumentException(\"A property must be specified.\", \"propertyName\");\n            }\n            PropertyInfo propInfo = instance.GetType().GetProperty(propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);\n            if (propInfo == null)\n            {\n                throw new ArgumentException(String.Format(\n                    \"A property named '{0}' on type '{1}' could not be found.\",\n                    propertyName, instance.GetType().FullName));\n            }\n            return propInfo;\n        }\n\n        private static void TestAttribute<TAttribute>(MemberInfo memberInfo, TAttribute attributeValue)\n            where TAttribute : Attribute\n        {\n            object[] attrs = memberInfo.GetCustomAttributes(typeof(TAttribute), true);\n\n            if (attributeValue == null)\n            {\n                Assert.True(attrs.Length == 0, \"Member should not have an attribute of type \" + typeof(TAttribute));\n            }\n            else\n            {\n                Assert.True(attrs != null && attrs.Length > 0,\n                            \"Member does not have an attribute of type \" + typeof(TAttribute));\n                Assert.Equal(attributeValue, attrs[0]);\n            }\n        }\n\n        public static void TestBooleanProperty(object instance, string propertyName, bool initialValue, bool testDefaultValue)\n        {\n            // Assert initial value\n            TestGetPropertyValue(instance, propertyName, initialValue);\n\n            if (testDefaultValue)\n            {\n                // Assert DefaultValue attribute matches inital value\n                TestDefaultValue(instance, propertyName);\n            }\n\n            TestPropertyValue(instance, propertyName, true);\n            TestPropertyValue(instance, propertyName, false);\n        }\n\n        public static void TestDefaultValue(object instance, string propertyName)\n        {\n            PropertyInfo propInfo = GetPropertyInfo(instance, propertyName);\n\n            object initialValue = propInfo.GetValue(instance, null);\n            TestAttribute(propInfo, new DefaultValueAttribute(initialValue));\n        }\n\n        public static void TestEvent<TEventArgs>(object instance, string eventName, TEventArgs eventArgs) where TEventArgs : EventArgs\n        {\n            EventInfo eventInfo = GetEventInfo(instance, eventName);\n\n            // Assert category \"Action\"\n            TestAttribute(eventInfo, new CategoryAttribute(\"Action\"));\n\n            // Call protected method with no event handlers, assert no error\n            MethodInfo methodInfo = GetMethodInfo(instance, \"On\" + eventName, attrs: MethodAttributes.Family | MethodAttributes.Virtual);\n            methodInfo.Invoke(instance, new object[] { eventArgs });\n\n            // Attach handler, call method, assert fires once\n            List<object> eventHandlerArgs = new List<object>();\n            EventHandler<TEventArgs> handler = new EventHandler<TEventArgs>(delegate(object sender, TEventArgs t)\n            {\n                eventHandlerArgs.Add(sender);\n                eventHandlerArgs.Add(t);\n            });\n            eventInfo.AddEventHandler(instance, handler);\n            methodInfo.Invoke(instance, new object[] { eventArgs });\n            Assert.Equal(new[] { instance, eventArgs }, eventHandlerArgs.ToArray());\n\n            // Detach handler, call method, assert not fired\n            eventHandlerArgs = new List<object>();\n            eventInfo.RemoveEventHandler(instance, handler);\n            methodInfo.Invoke(instance, new object[] { eventArgs });\n            Assert.Empty(eventHandlerArgs);\n        }\n\n        public static void TestGetPropertyValue(object instance, string propertyName, object valueToCheck)\n        {\n            PropertyInfo propInfo = GetPropertyInfo(instance, propertyName);\n            object value = propInfo.GetValue(instance, null);\n            Assert.Equal(valueToCheck, value);\n        }\n\n        public static void TestEnumProperty<TEnumValue>(object instance, string propertyName, TEnumValue initialValue, bool testDefaultValue)\n        {\n            // Assert initial value\n            TestGetPropertyValue(instance, propertyName, initialValue);\n\n            if (testDefaultValue)\n            {\n                // Assert DefaultValue attribute matches inital value\n                TestDefaultValue(instance, propertyName);\n            }\n\n            PropertyInfo propInfo = GetPropertyInfo(instance, propertyName);\n\n            // Values are sorted numerically\n            TEnumValue[] values = (TEnumValue[])Enum.GetValues(propInfo.PropertyType);\n\n            // Assert get/set works for all valid enum values\n            foreach (TEnumValue value in values)\n            {\n                TestPropertyValue(instance, propertyName, value);\n            }\n\n            // Assert ArgumentOutOfRangeException is thrown for value one less than smallest\n            // enum value, and one more than largest enum value\n            var targetException = Assert.Throws<TargetInvocationException>(() => propInfo.SetValue(instance, Convert.ToInt32(values[0]) - 1, null));\n            Assert.IsType<ArgumentOutOfRangeException>(targetException.InnerException);\n\n            targetException = Assert.Throws<TargetInvocationException>(() => propInfo.SetValue(instance, Convert.ToInt32(values[values.Length - 1]) + 1, null));\n            Assert.IsType<ArgumentOutOfRangeException>(targetException.InnerException);\n        }\n\n        public static void TestInt32Property(object instance, string propertyName, int value1, int value2)\n        {\n            TestPropertyValue(instance, propertyName, value1);\n            TestPropertyValue(instance, propertyName, value2);\n        }\n\n        public static void TestPropertyWithDefaultInstance(object instance, string propertyName, object valueToSet)\n        {\n            PropertyInfo propInfo = GetPropertyInfo(instance, propertyName);\n\n            // Set to explicit property\n            propInfo.SetValue(instance, valueToSet, null);\n            object value = propInfo.GetValue(instance, null);\n            Assert.Equal(valueToSet, value);\n\n            // Set to null\n            propInfo.SetValue(instance, null, null);\n            value = propInfo.GetValue(instance, null);\n            Assert.IsAssignableFrom(propInfo.PropertyType, value);\n        }\n\n        public static void TestPropertyWithDefaultInstance(object instance, string propertyName, object valueToSet, object defaultValue)\n        {\n            PropertyInfo propInfo = GetPropertyInfo(instance, propertyName);\n\n            // Set to explicit property\n            propInfo.SetValue(instance, valueToSet, null);\n            object value = propInfo.GetValue(instance, null);\n            Assert.Same(valueToSet, value);\n\n            // Set to null\n            propInfo.SetValue(instance, null, null);\n            value = propInfo.GetValue(instance, null);\n            Assert.Equal(defaultValue, value);\n        }\n\n        public static void TestPropertyValue(object instance, string propertyName, object value)\n        {\n            TestPropertyValue(instance, propertyName, value, value);\n        }\n\n        public static void TestPropertyValue(object instance, string propertyName, object valueToSet, object valueToCheck)\n        {\n            PropertyInfo propInfo = GetPropertyInfo(instance, propertyName);\n            propInfo.SetValue(instance, valueToSet, null);\n            object value = propInfo.GetValue(instance, null);\n            Assert.Equal(valueToCheck, value);\n        }\n\n        public static void TestStringParams(object instance, Type[] constructorParameterTypes, object[] parameters)\n        {\n            ConstructorInfo ctor = GetConstructorInfo(instance, constructorParameterTypes);\n            TestStringParams(ctor, instance, parameters);\n        }\n\n        public static void TestStringParams(object instance, string methodName, object[] parameters)\n        {\n            TestStringParams(instance, methodName, null, parameters);\n        }\n\n        public static void TestStringParams(object instance, string methodName, Type[] types, object[] parameters)\n        {\n            MethodInfo method = GetMethodInfo(instance, methodName, types);\n            TestStringParams(method, instance, parameters);\n        }\n\n        private static void TestStringParams(MethodBase method, object instance, object[] parameters)\n        {\n            ParameterInfo[] parameterInfos = method.GetParameters();\n            foreach (ParameterInfo parameterInfo in parameterInfos)\n            {\n                if (parameterInfo.ParameterType == typeof(String))\n                {\n                    object originalParameter = parameters[parameterInfo.Position];\n\n                    parameters[parameterInfo.Position] = null;\n                    Assert.ThrowsArgumentNullOrEmpty(\n                        delegate()\n                        {\n                            try\n                            {\n                                method.Invoke(instance, parameters);\n                            }\n                            catch (TargetInvocationException e)\n                            {\n                                throw e.InnerException;\n                            }\n                        },\n                        parameterInfo.Name);\n\n                    parameters[parameterInfo.Position] = String.Empty;\n                    Assert.ThrowsArgumentNullOrEmpty(\n                        delegate()\n                        {\n                            try\n                            {\n                                method.Invoke(instance, parameters);\n                            }\n                            catch (TargetInvocationException e)\n                            {\n                                throw e.InnerException;\n                            }\n                        },\n                        parameterInfo.Name);\n\n                    parameters[parameterInfo.Position] = originalParameter;\n                }\n            }\n        }\n\n        public static void TestStringProperty(object instance, string propertyName, string initialValue,\n                                              bool testDefaultValueAttribute = false, bool allowNullAndEmpty = true,\n                                              string nullAndEmptyReturnValue = \"\")\n        {\n            // Assert initial value\n            TestGetPropertyValue(instance, propertyName, initialValue);\n\n            if (testDefaultValueAttribute)\n            {\n                // Assert DefaultValue attribute matches inital value\n                TestDefaultValue(instance, propertyName);\n            }\n\n            if (allowNullAndEmpty)\n            {\n                // Assert get/set works for null\n                TestPropertyValue(instance, propertyName, null, nullAndEmptyReturnValue);\n\n                // Assert get/set works for String.Empty\n                TestPropertyValue(instance, propertyName, String.Empty, nullAndEmptyReturnValue);\n            }\n            else\n            {\n                Assert.ThrowsArgumentNullOrEmpty(\n                    delegate()\n                    {\n                        try\n                        {\n                            TestPropertyValue(instance, propertyName, null);\n                        }\n                        catch (TargetInvocationException e)\n                        {\n                            throw e.InnerException;\n                        }\n                    },\n                    \"value\");\n                Assert.ThrowsArgumentNullOrEmpty(\n                    delegate()\n                    {\n                        try\n                        {\n                            TestPropertyValue(instance, propertyName, String.Empty);\n                        }\n                        catch (TargetInvocationException e)\n                        {\n                            throw e.InnerException;\n                        }\n                    },\n                    \"value\");\n            }\n\n            // Assert get/set works for arbitrary value\n            TestPropertyValue(instance, propertyName, \"TestValue\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/DataSets/CommonUnitTestDataSets.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.ObjectModel;\nusing Microsoft.TestCommon.Types;\n\nnamespace Microsoft.TestCommon\n{\n    public class CommonUnitTestDataSets\n    {\n        public static ValueTypeTestData<char> Chars { get { return TestData.CharTestData; } }\n        public static ValueTypeTestData<int> Ints { get { return TestData.IntTestData; } }\n        public static ValueTypeTestData<uint> Uints { get { return TestData.UintTestData; } }\n        public static ValueTypeTestData<short> Shorts { get { return TestData.ShortTestData; } }\n        public static ValueTypeTestData<ushort> Ushorts { get { return TestData.UshortTestData; } }\n        public static ValueTypeTestData<long> Longs { get { return TestData.LongTestData; } }\n        public static ValueTypeTestData<ulong> Ulongs { get { return TestData.UlongTestData; } }\n        public static ValueTypeTestData<byte> Bytes { get { return TestData.ByteTestData; } }\n        public static ValueTypeTestData<sbyte> SBytes { get { return TestData.SByteTestData; } }\n        public static ValueTypeTestData<bool> Bools { get { return TestData.BoolTestData; } }\n        public static ValueTypeTestData<double> Doubles { get { return TestData.DoubleTestData; } }\n        public static ValueTypeTestData<float> Floats { get { return TestData.FloatTestData; } }\n        public static ValueTypeTestData<DateTime> DateTimes { get { return TestData.DateTimeTestData; } }\n        public static ValueTypeTestData<Decimal> Decimals { get { return TestData.DecimalTestData; } }\n        public static ValueTypeTestData<TimeSpan> TimeSpans { get { return TestData.TimeSpanTestData; } }\n        public static ValueTypeTestData<Guid> Guids { get { return TestData.GuidTestData; } }\n        public static ValueTypeTestData<DateTimeOffset> DateTimeOffsets { get { return TestData.DateTimeOffsetTestData; } }\n        public static ValueTypeTestData<SimpleEnum> SimpleEnums { get { return TestData.SimpleEnumTestData; } }\n        public static ValueTypeTestData<LongEnum> LongEnums { get { return TestData.LongEnumTestData; } }\n        public static ValueTypeTestData<FlagsEnum> FlagsEnums { get { return TestData.FlagsEnumTestData; } }\n        public static TestData<string> EmptyStrings { get { return TestData.EmptyStrings; } }\n        public static RefTypeTestData<string> Strings { get { return TestData.StringTestData; } }\n        public static TestData<string> NonNullEmptyStrings { get { return TestData.NonNullEmptyStrings; } }\n        public static RefTypeTestData<ISerializableType> ISerializableTypes { get { return TestData.ISerializableTypeTestData; } }\n        public static ReadOnlyCollection<TestData> ValueTypeTestDataCollection { get { return TestData.ValueTypeTestDataCollection; } }\n        public static ReadOnlyCollection<TestData> RefTypeTestDataCollection { get { return TestData.RefTypeTestDataCollection; } }\n        public static ReadOnlyCollection<TestData> ValueAndRefTypeTestDataCollection { get { return TestData.ValueAndRefTypeTestDataCollection; } }\n        public static ReadOnlyCollection<TestData> RepresentativeValueAndRefTypeTestDataCollection { get { return TestData.RepresentativeValueAndRefTypeTestDataCollection; } }\n    }\n}"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/DataSets/RefTypeTestData.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace Microsoft.TestCommon\n{\n    public class RefTypeTestData<T> : TestData<T> where T : class\n    {\n        private Func<IEnumerable<T>> testDataProvider;\n        private Func<IEnumerable<T>> derivedTypeTestDataProvider;\n        private Func<IEnumerable<T>> knownTypeTestDataProvider;\n\n        public RefTypeTestData(Func<IEnumerable<T>> testDataProvider)\n        {\n            if (testDataProvider == null)\n            {\n                throw new ArgumentNullException(\"testDataProvider\");\n            }\n\n            this.testDataProvider = testDataProvider;\n            this.RegisterTestDataVariation(TestDataVariations.WithNull, this.Type, GetNullTestData);\n        }\n\n        public RefTypeTestData(\n            Func<IEnumerable<T>> testDataProvider,\n            Func<IEnumerable<T>> derivedTypeTestDataProvider,\n            Func<IEnumerable<T>> knownTypeTestDataProvider)\n            : this(testDataProvider)\n        {\n            this.derivedTypeTestDataProvider = derivedTypeTestDataProvider;\n            if (this.derivedTypeTestDataProvider != null)\n            {\n                this.RegisterTestDataVariation(TestDataVariations.AsDerivedType, this.Type, this.GetTestDataAsDerivedType);\n            }\n\n            this.knownTypeTestDataProvider = knownTypeTestDataProvider;\n            if (this.knownTypeTestDataProvider != null)\n            {\n                this.RegisterTestDataVariation(TestDataVariations.AsKnownType, this.Type, this.GetTestDataAsDerivedKnownType);\n            }\n        }\n\n        public T GetNullTestData()\n        {\n            return null;\n        }\n\n        public IEnumerable<T> GetTestDataAsDerivedType()\n        {\n            if (this.derivedTypeTestDataProvider != null)\n            {\n                return this.derivedTypeTestDataProvider();\n            }\n\n            return Enumerable.Empty<T>();\n        }\n\n        public IEnumerable<T> GetTestDataAsDerivedKnownType()\n        {\n            if (this.knownTypeTestDataProvider != null)\n            {\n                return this.knownTypeTestDataProvider();\n            }\n\n            return Enumerable.Empty<T>();\n        }\n\n        protected override IEnumerable<T> GetTypedTestData()\n        {\n            return this.testDataProvider();\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/DataSets/TestData.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing Microsoft.TestCommon.Types;\n\nnamespace Microsoft.TestCommon\n{\n    /// <summary>\n    /// A base class for test data.  A <see cref=\"TestData\"/> instance is associated with a given type, and the <see cref=\"TestData\"/> instance can\n    /// provide instances of the given type to use as data in tests.  The same <see cref=\"TestData\"/> instance can also provide instances\n    /// of types related to the given type, such as a <see cref=\"List<>\"/> of the type.  See the <see cref=\"TestDataVariations\"/> enum for all the\n    /// variations of test data that a <see cref=\"TestData\"/> instance can provide.\n    /// </summary>\n    public abstract class TestData\n    {\n        /// <summary>\n        /// Common <see cref=\"TestData\"/> for a <see cref=\"char\"/>.\n        /// </summary>\n        public static readonly ValueTypeTestData<char> CharTestData = new ValueTypeTestData<char>('a', Char.MinValue, Char.MaxValue);\n\n        /// <summary>\n        /// Common <see cref=\"TestData\"/> for a <see cref=\"int\"/>.\n        /// </summary>\n        public static readonly ValueTypeTestData<int> IntTestData = new ValueTypeTestData<int>(-1, 0, 1, Int32.MinValue, Int32.MaxValue);\n\n        /// <summary>\n        /// Common <see cref=\"TestData\"/> for a <see cref=\"uint\"/>.\n        /// </summary>\n        public static readonly ValueTypeTestData<uint> UintTestData = new ValueTypeTestData<uint>(0, 1, UInt32.MinValue, UInt32.MaxValue);\n\n        /// <summary>\n        /// Common <see cref=\"TestData\"/> for a <see cref=\"short\"/>.\n        /// </summary>\n        public static readonly ValueTypeTestData<short> ShortTestData = new ValueTypeTestData<short>(-1, 0, 1, Int16.MinValue, Int16.MaxValue);\n\n        /// <summary>\n        /// Common <see cref=\"TestData\"/> for a <see cref=\"ushort\"/>.\n        /// </summary>\n        public static readonly ValueTypeTestData<ushort> UshortTestData = new ValueTypeTestData<ushort>(0, 1, UInt16.MinValue, UInt16.MaxValue);\n\n        /// <summary>\n        /// Common <see cref=\"TestData\"/> for a <see cref=\"long\"/>.\n        /// </summary>\n        public static readonly ValueTypeTestData<long> LongTestData = new ValueTypeTestData<long>(-1, 0, 1, Int64.MinValue, Int64.MaxValue);\n\n        /// <summary>\n        /// Common <see cref=\"TestData\"/> for a <see cref=\"ulong\"/>.\n        /// </summary>\n        public static readonly ValueTypeTestData<ulong> UlongTestData = new ValueTypeTestData<ulong>(0, 1, UInt64.MinValue, UInt64.MaxValue);\n\n        /// <summary>\n        /// Common <see cref=\"TestData\"/> for a <see cref=\"byte\"/>.\n        /// </summary>\n        public static readonly ValueTypeTestData<byte> ByteTestData = new ValueTypeTestData<byte>(0, 1, Byte.MinValue, Byte.MaxValue);\n\n        /// <summary>\n        /// Common <see cref=\"TestData\"/> for a <see cref=\"sbyte\"/>.\n        /// </summary>\n        public static readonly ValueTypeTestData<sbyte> SByteTestData = new ValueTypeTestData<sbyte>(-1, 0, 1, SByte.MinValue, SByte.MaxValue);\n\n        /// <summary>\n        /// Common <see cref=\"TestData\"/> for a <see cref=\"bool\"/>.\n        /// </summary>\n        public static readonly ValueTypeTestData<bool> BoolTestData = new ValueTypeTestData<bool>(true, false);\n\n        /// <summary>\n        /// Common <see cref=\"TestData\"/> for a <see cref=\"double\"/>.\n        /// </summary>\n        public static readonly ValueTypeTestData<double> DoubleTestData = new ValueTypeTestData<double>(\n            -1.0,\n            0.0,\n            1.0,\n            double.MinValue,\n            double.MaxValue,\n            double.PositiveInfinity,\n            double.NegativeInfinity);\n\n        /// <summary>\n        /// Common <see cref=\"TestData\"/> for a <see cref=\"float\"/>.\n        /// </summary>\n        public static readonly ValueTypeTestData<float> FloatTestData = new ValueTypeTestData<float>(\n            -1.0f,\n            0.0f,\n            1.0f,\n            float.MinValue,\n            float.MaxValue,\n            float.PositiveInfinity,\n            float.NegativeInfinity);\n\n        /// <summary>\n        /// Common <see cref=\"TestData\"/> for a <see cref=\"decimal\"/>.\n        /// </summary>\n        public static readonly ValueTypeTestData<decimal> DecimalTestData = new ValueTypeTestData<decimal>(\n            -1M,\n            0M,\n            1M,\n            decimal.MinValue,\n            decimal.MaxValue);\n\n        /// <summary>\n        /// Common <see cref=\"TestData\"/> for a <see cref=\"DateTime\"/>.\n        /// </summary>\n        public static readonly ValueTypeTestData<DateTime> DateTimeTestData = new ValueTypeTestData<DateTime>(\n            DateTime.Now,\n            DateTime.UtcNow,\n            DateTime.MaxValue,\n            DateTime.MinValue);\n\n        /// <summary>\n        /// Common <see cref=\"TestData\"/> for a <see cref=\"TimeSpan\"/>.\n        /// </summary>\n        public static readonly ValueTypeTestData<TimeSpan> TimeSpanTestData = new ValueTypeTestData<TimeSpan>(\n            TimeSpan.MinValue,\n            TimeSpan.MaxValue);\n\n        /// <summary>\n        /// Common <see cref=\"TestData\"/> for a <see cref=\"Guid\"/>.\n        /// </summary>\n        public static readonly ValueTypeTestData<Guid> GuidTestData = new ValueTypeTestData<Guid>(\n            Guid.NewGuid(),\n            Guid.Empty);\n\n        /// <summary>\n        /// Common <see cref=\"TestData\"/> for a <see cref=\"DateTimeOffset\"/>.\n        /// </summary>\n        public static readonly ValueTypeTestData<DateTimeOffset> DateTimeOffsetTestData = new ValueTypeTestData<DateTimeOffset>(\n            DateTimeOffset.MaxValue,\n            DateTimeOffset.MinValue,\n            new DateTimeOffset(DateTime.Now));\n\n        /// <summary>\n        /// Common <see cref=\"TestData\"/> for an <c>enum</c>.\n        /// </summary>\n        public static readonly ValueTypeTestData<SimpleEnum> SimpleEnumTestData = new ValueTypeTestData<SimpleEnum>(\n            SimpleEnum.First,\n            SimpleEnum.Second,\n            SimpleEnum.Third);\n\n        /// <summary>\n        /// Common <see cref=\"TestData\"/> for an <c>enum</c> implemented with a <see cref=\"long\"/>.\n        /// </summary>\n        public static readonly ValueTypeTestData<LongEnum> LongEnumTestData = new ValueTypeTestData<LongEnum>(\n            LongEnum.FirstLong,\n            LongEnum.SecondLong,\n            LongEnum.ThirdLong);\n\n        /// <summary>\n        /// Common <see cref=\"TestData\"/> for an <c>enum</c> decorated with a <see cref=\"FlagsAttribtute\"/>.\n        /// </summary>\n        public static readonly ValueTypeTestData<FlagsEnum> FlagsEnumTestData = new ValueTypeTestData<FlagsEnum>(\n            FlagsEnum.One,\n            FlagsEnum.Two,\n            FlagsEnum.Four);\n\n        /// <summary>\n        /// Expected permutations of non supported file paths.\n        /// </summary>\n        public static readonly TestData<string> NotSupportedFilePaths = new RefTypeTestData<string>(() => new List<string>() {\n            \"cc:\\\\a\\\\b\",\n        });\n\n        /// <summary>\n        /// Expected permutations of invalid file paths.\n        /// </summary>\n        public static readonly TestData<string> InvalidNonNullFilePaths = new RefTypeTestData<string>(() => new List<string>() {\n            String.Empty,\n            \"\",\n            \" \",\n            \"  \",\n            \"\\t\\t \\n \",\n            \"c:\\\\a<b\",\n            \"c:\\\\a>b\",\n            \"c:\\\\a\\\"b\",\n            \"c:\\\\a\\tb\",\n            \"c:\\\\a|b\",\n            \"c:\\\\a\\bb\",\n            \"c:\\\\a\\0b\",\n        });\n\n        /// <summary>\n        /// All expected permutations of an empty string.\n        /// </summary>\n        public static readonly TestData<string> NonNullEmptyStrings = new RefTypeTestData<string>(() => new List<string>() { String.Empty, \" \", \"\\t\\r\\n\" });\n\n        /// <summary>\n        /// All expected permutations of an empty string.\n        /// </summary>\n        public static readonly TestData<string> EmptyStrings = new RefTypeTestData<string>(() => new List<string>() { null, String.Empty, \" \", \"\\t\\r\\n\" });\n\n        /// <summary>\n        ///  Common <see cref=\"TestData\"/> for a <see cref=\"string\"/>.\n        /// </summary>\n        public static readonly RefTypeTestData<string> StringTestData = new RefTypeTestData<string>(() => new List<string>() {\n            \"\",\n            \" \",            // one space\n            \"  \",           // multiple spaces\n            \" data \",       // leading and trailing whitespace\n            \"\\t\\t \\n \",\n            \"Some String!\"});\n\n        /// <summary>\n        ///  Common <see cref=\"TestData\"/> for a class that implements <see cref=\"ISerializable\"/>.\n        /// </summary>\n        public static readonly RefTypeTestData<ISerializableType> ISerializableTypeTestData = new RefTypeTestData<ISerializableType>(\n            ISerializableType.GetTestData);\n\n        /// <summary>\n        /// A read-only collection of value type test data.\n        /// </summary>\n        public static readonly ReadOnlyCollection<TestData> ValueTypeTestDataCollection = new ReadOnlyCollection<TestData>(new TestData[] {\n            CharTestData,\n            IntTestData,\n            UintTestData,\n            ShortTestData,\n            UshortTestData,\n            LongTestData,\n            UlongTestData,\n            ByteTestData,\n            SByteTestData,\n            BoolTestData,\n            DoubleTestData,\n            FloatTestData,\n            DecimalTestData,\n            TimeSpanTestData,\n            GuidTestData,\n            DateTimeOffsetTestData,\n            SimpleEnumTestData,\n            LongEnumTestData,\n            FlagsEnumTestData});\n\n        /// <summary>\n        /// A read-only collection of reference type test data.\n        /// </summary>\n        public static readonly ReadOnlyCollection<TestData> RefTypeTestDataCollection = new ReadOnlyCollection<TestData>(new TestData[] {\n            StringTestData,\n            ISerializableTypeTestData});\n\n        /// <summary>\n        /// A read-only collection of value and reference type test data.\n        /// </summary>\n        public static readonly ReadOnlyCollection<TestData> ValueAndRefTypeTestDataCollection = new ReadOnlyCollection<TestData>(\n            ValueTypeTestDataCollection.Concat(RefTypeTestDataCollection).ToList());\n\n        /// <summary>\n        /// A read-only collection of representative values and reference type test data.\n        /// Uses where exhaustive coverage is not required.\n        /// </summary>\n        public static readonly ReadOnlyCollection<TestData> RepresentativeValueAndRefTypeTestDataCollection = new ReadOnlyCollection<TestData>(new TestData[] {\n            IntTestData,\n            BoolTestData,\n            SimpleEnumTestData,\n            StringTestData,\n        });\n\n        private Dictionary<TestDataVariations, TestDataVariationProvider> registeredTestDataVariations;\n\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"TestData\"/> class.\n        /// </summary>\n        /// <param name=\"type\">The type associated with the <see cref=\"TestData\"/> instance.</param>\n        protected TestData(Type type)\n        {\n            if (type.ContainsGenericParameters)\n            {\n                throw new InvalidOperationException(\"Only closed generic types are supported.\");\n            }\n\n            this.Type = type;\n            this.registeredTestDataVariations = new Dictionary<TestDataVariations, TestDataVariationProvider>();\n        }\n\n        /// <summary>\n        /// Gets the type associated with the <see cref=\"TestData\"/> instance.\n        /// </summary>\n        public Type Type { get; private set; }\n\n\n        /// <summary>\n        /// Gets the supported test data variations.\n        /// </summary>\n        /// <returns></returns>\n        public IEnumerable<TestDataVariations> GetSupportedTestDataVariations()\n        {\n            return this.registeredTestDataVariations.Keys;\n        }\n\n        /// <summary>\n        /// Gets the related type for the given test data variation or returns null if the <see cref=\"TestData\"/> instance\n        /// doesn't support the given variation.\n        /// </summary>\n        /// <param name=\"variation\">The test data variation with which to create the related <see cref=\"Type\"/>.</param>\n        /// <returns>The related <see cref=\"Type\"/> for the <see cref=\"TestData.Type\"/> as given by the test data variation.</returns>\n        /// <example>\n        /// For example, if the given <see cref=\"TestData\"/> was created for <see cref=\"string\"/> test data and the varation parameter\n        /// was <see cref=\"TestDataVariations.AsList\"/> then the returned type would be <see cref=\"List<string>\"/>.\n        /// </example>\n        public Type GetAsTypeOrNull(TestDataVariations variation)\n        {\n            TestDataVariationProvider testDataVariation = null;\n            if (this.registeredTestDataVariations.TryGetValue(variation, out testDataVariation))\n            {\n                return testDataVariation.Type;\n            }\n\n            return null;\n        }\n\n        /// <summary>\n        /// Gets test data for the given test data variation or returns null if the <see cref=\"TestData\"/> instance\n        /// doesn't support the given variation.\n        /// </summary>\n        /// <param name=\"variation\">The test data variation with which to create the related test data.</param>\n        /// <returns>Test data of the type specified by the <see cref=\"TestData.GetAsTypeOrNull\"/> method.</returns>\n        public object GetAsTestDataOrNull(TestDataVariations variation)\n        {\n            TestDataVariationProvider testDataVariation = null;\n            if (this.registeredTestDataVariations.TryGetValue(variation, out testDataVariation))\n            {\n                return testDataVariation.TestDataProvider();\n            }\n\n            return null;\n        }\n\n\n        /// <summary>\n        /// Allows derived classes to register a <paramref name=\"testDataProvider \"/> <see cref=\"Func<>\"/> that will\n        /// provide test data for a given variation.\n        /// </summary>\n        /// <param name=\"variation\">The variation with which to register the <paramref name=\"testDataProvider \"/>r.</param>\n        /// <param name=\"type\">The type of the test data created by the <paramref name=\"testDataProvider \"/></param>\n        /// <param name=\"testDataProvider\">A <see cref=\"Func<>\"/> that will provide test data.</param>\n        protected void RegisterTestDataVariation(TestDataVariations variation, Type type, Func<object> testDataProvider)\n        {\n            this.registeredTestDataVariations.Add(variation, new TestDataVariationProvider(type, testDataProvider));\n        }\n\n        private class TestDataVariationProvider\n        {\n            public TestDataVariationProvider(Type type, Func<object> testDataProvider)\n            {\n                this.Type = type;\n                this.TestDataProvider = testDataProvider;\n            }\n\n\n            public Func<object> TestDataProvider { get; private set; }\n\n            public Type Type { get; private set; }\n        }\n    }\n\n\n    /// <summary>\n    /// A generic base class for test data.\n    /// </summary>\n    /// <typeparam name=\"T\">The type associated with the test data.</typeparam>\n    public abstract class TestData<T> : TestData, IEnumerable<T>\n    {\n        private static readonly Type OpenIEnumerableType = typeof(IEnumerable<>);\n        private static readonly Type OpenListType = typeof(List<>);\n        private static readonly Type OpenIQueryableType = typeof(IQueryable<>);\n        private static readonly Type OpenDictionaryType = typeof(Dictionary<,>);\n        private static readonly Type OpenTestDataHolderType = typeof(TestDataHolder<>);\n\n        /// <summary>\n        /// Initializes a new instance of the <see cref=\"TestData&lt;T&gt;\"/> class.\n        /// </summary>\n        protected TestData()\n            : base(typeof(T))\n        {\n            Type[] typeParams = new Type[] { this.Type };\n            Type[] dictionaryTypeParams = new Type[] { typeof(string), this.Type };\n\n            Type arrayType = this.Type.MakeArrayType();\n            Type listType = OpenListType.MakeGenericType(typeParams);\n            Type iEnumerableType = OpenIEnumerableType.MakeGenericType(typeParams);\n            Type iQueryableType = OpenIQueryableType.MakeGenericType(typeParams);\n            Type dictionaryType = OpenDictionaryType.MakeGenericType(dictionaryTypeParams);\n            Type testDataHolderType = OpenTestDataHolderType.MakeGenericType(typeParams);\n\n            this.RegisterTestDataVariation(TestDataVariations.AsInstance, this.Type, () => GetTypedTestData());\n            this.RegisterTestDataVariation(TestDataVariations.AsArray, arrayType, GetTestDataAsArray);\n            this.RegisterTestDataVariation(TestDataVariations.AsIEnumerable, iEnumerableType, GetTestDataAsIEnumerable);\n            this.RegisterTestDataVariation(TestDataVariations.AsIQueryable, iQueryableType, GetTestDataAsIQueryable);\n            this.RegisterTestDataVariation(TestDataVariations.AsList, listType, GetTestDataAsList);\n            this.RegisterTestDataVariation(TestDataVariations.AsDictionary, dictionaryType, GetTestDataAsDictionary);\n            this.RegisterTestDataVariation(TestDataVariations.AsClassMember, testDataHolderType, GetTestDataInHolder);\n        }\n\n        public IEnumerator<T> GetEnumerator()\n        {\n            return (IEnumerator<T>)this.GetTypedTestData().ToList().GetEnumerator();\n        }\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return (IEnumerator)this.GetTypedTestData().ToList().GetEnumerator();\n        }\n\n        /// <summary>\n        /// Gets the test data as an array.\n        /// </summary>\n        /// <returns>An array of test data of the given type.</returns>\n        public T[] GetTestDataAsArray()\n        {\n            return this.GetTypedTestData().ToArray();\n        }\n\n        /// <summary>\n        /// Gets the test data as a <see cref=\"List<>\"/>.\n        /// </summary>\n        /// <returns>A <see cref=\"List<>\"/> of test data of the given type.</returns>\n        public List<T> GetTestDataAsList()\n        {\n            return this.GetTypedTestData().ToList();\n        }\n\n        /// <summary>\n        /// Gets the test data as an <see cref=\"IEnumerable<>\"/>.\n        /// </summary>\n        /// <returns>An <see cref=\"IEnumerable<>\"/> of test data of the given type.</returns>\n        public IEnumerable<T> GetTestDataAsIEnumerable()\n        {\n            return this.GetTypedTestData().AsEnumerable();\n        }\n\n        /// <summary>\n        /// Gets the test data as an <see cref=\"IQueryable<>\"/>.\n        /// </summary>\n        /// <returns>An <see cref=\"IQueryable<>\"/> of test data of the given type.</returns>\n        public IQueryable<T> GetTestDataAsIQueryable()\n        {\n            return this.GetTypedTestData().AsQueryable();\n        }\n\n        public Dictionary<string, T> GetTestDataAsDictionary()\n        {\n            // Some TestData collections contain duplicates e.g. UintTestData contains both 0 and UInt32.MinValue.\n            // Therefore use dictionaryKey, not _unused.ToString(). Do not reuse key to keep dictionaries consistent\n            // if enumerated multiple times.\n            int dictionaryKey = 0;\n            return this.GetTypedTestData().ToDictionary(_unused => (dictionaryKey++).ToString());\n        }\n\n        public IEnumerable<TestDataHolder<T>> GetTestDataInHolder()\n        {\n            return this.GetTypedTestData().Select(value => new TestDataHolder<T> { V1 = value, });\n        }\n\n        /// <summary>\n        /// Must be implemented by derived types to return test data of the given type.\n        /// </summary>\n        /// <returns>Test data of the given type.</returns>\n        protected abstract IEnumerable<T> GetTypedTestData();\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/DataSets/TestDataHolder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Globalization;\n\nnamespace Microsoft.TestCommon\n{\n    /// <summary>\n    /// Equatable class wrapping a single instance of type <paramref name=\"T\"/>. Equatable to ease test assertions.\n    /// </summary>\n    /// <typeparam name=\"T\">The <see cref=\"Type\"/> to wrap.</typeparam>\n    public class TestDataHolder<T> : IEquatable<TestDataHolder<T>>\n    {\n        public T V1 { get; set; }\n\n        bool IEquatable<TestDataHolder<T>>.Equals(TestDataHolder<T> other)\n        {\n            if (other == null)\n            {\n                return false;\n            }\n\n            return Object.Equals(V1, other.V1);\n        }\n\n        public override bool Equals(object obj)\n        {\n            TestDataHolder<T> that = obj as TestDataHolder<T>;\n            return ((IEquatable<TestDataHolder<T>>)this).Equals(that);\n        }\n\n        public override int GetHashCode()\n        {\n            if (typeof(ValueType).IsAssignableFrom(typeof(T)) || V1 != null)\n            {\n                return V1.GetHashCode();\n            }\n            else\n            {\n                return 0;\n            }\n        }\n\n        public override string ToString()\n        {\n            return String.Format(CultureInfo.InvariantCulture, \"{{ V1: '{0}' }}\", V1);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/DataSets/TestDataVariations.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\n\nnamespace Microsoft.TestCommon\n{\n    /// <summary>\n    /// An flags enum that can be used to indicate different variations of a given \n    /// <see cref=\"TestData\"/> instance.\n    /// </summary>\n    [Flags]\n    public enum TestDataVariations\n    {\n        /// <summary>\n        /// An individual instance of a given <see cref=\"TestData\"/> type.\n        /// </summary>\n        AsInstance = 0x1,\n\n        /// <summary>\n        /// An individual instance of a type that derives from a given <see cref=\"TestData\"/> type.\n        /// </summary>\n        AsDerivedType = 0x2,\n\n        /// <summary>\n        /// An individual instance of a given <see cref=\"TestData\"/> type that has a property value \n        /// that is a known type of the declared property type.\n        /// </summary>\n        AsKnownType = 0x4,\n\n        /// <summary>\n        /// A <see cref=\"Nullable<>\"/> instance of a given <see cref=\"TestData\"/> type.  Only applies to\n        /// instances of <see cref=\"ValueTypeTestData\"/>.\n        /// </summary>\n        AsNullable = 0x8,\n\n        /// <summary>\n        /// An instance of a <see cref=\"System.Collections.Generic.List<>\"/> of a given <see cref=\"TestData\"/> type.\n        /// </summary>\n        AsList = 0x10,\n\n        /// <summary>\n        /// An instance of a array of the <see cref=\"TestData\"/> type.\n        /// </summary>\n        AsArray = 0x20,\n\n        /// <summary>\n        /// An instance of an <see cref=\"System.Collections.Generic.IEnumerable<>\"/> of a given <see cref=\"TestData\"/> type.\n        /// </summary>\n        AsIEnumerable = 0x40,\n\n        /// <summary>\n        /// An instance of an <see cref=\"System.Linq.IQueryable<>\"/> of a given <see cref=\"TestData\"/> type.\n        /// </summary>\n        AsIQueryable = 0x80,\n\n        /// <summary>\n        /// An instance of a DataContract type in which a given <see cref=\"TestData\"/> type is a member.\n        /// </summary>\n        AsDataMember = 0x100,\n\n        /// <summary>\n        /// An instance of a type in which a given <see cref=\"TestData\"/> type is decorated with a \n        /// <see cref=\"System.Xml.Serialization.XmlElementAttribute\"/>.\n        /// </summary>\n        AsXmlElementProperty = 0x200,\n\n        /// <summary>\n        /// An instance of a <see cref=\"System.Collections.Generic.IDictionary{string,TValue}\"/> of a given\n        /// <see cref=\"TestData\"/> type.\n        /// </summary>\n        AsDictionary = 0x400,\n\n        /// <summary>\n        /// Add a <c>null</c> instance of the given <see cref=\"TestData\"/> type to the data set.  This variation is\n        /// not included in <see cref=\"All\"/> or other variation masks.\n        /// </summary>\n        WithNull = 0x800,\n\n        /// <summary>\n        /// Individual instances of <see cref=\"TestDataHolder{T}\"/> containing the given <see cref=\"TestData\"/>.  This\n        /// variation is not included in <see cref=\"All\"/> or other variation masks.\n        /// </summary>\n        AsClassMember = 0x1000,\n\n        /// <summary>\n        /// All of the flags for single instance variations of a given <see cref=\"TestData\"/> type.\n        /// </summary>\n        AllSingleInstances = AsInstance | AsDerivedType | AsKnownType | AsNullable,\n\n        /// <summary>\n        /// All of the flags for collection variations of a given <see cref=\"TestData\"/> type.\n        /// </summary>\n        AllCollections = AsList | AsArray | AsIEnumerable | AsIQueryable | AsDictionary,\n\n        /// <summary>\n        /// All of the flags for variations in which a given <see cref=\"TestData\"/> type is a property on another type.\n        /// </summary>\n        AllProperties = AsDataMember | AsXmlElementProperty,\n\n        /// <summary>\n        /// All of the flags for interface collection variations of a given <see cref=\"TestData\"/> type.\n        /// </summary>\n        AllInterfaces = AsIEnumerable | AsIQueryable,\n\n        /// <summary>\n        /// All of the flags except for the interface collection variations of a given <see cref=\"TestData\"/> type.\n        /// </summary>\n        AllNonInterfaces = All & ~AllInterfaces,\n\n        /// <summary>\n        /// All of the flags for all of the variations of a given <see cref=\"TestData\"/> type.\n        /// </summary>\n        All = AllSingleInstances | AllCollections | AllProperties\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/DataSets/ValueTypeTestData.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace Microsoft.TestCommon\n{\n    public class ValueTypeTestData<T> : TestData<T> where T : struct\n    {\n        private static readonly Type OpenNullableType = typeof(Nullable<>);\n        private T[] testData;\n\n        public ValueTypeTestData(params T[] testData)\n            : base()\n        {\n            this.testData = testData;\n\n            Type[] typeParams = new Type[] { this.Type };\n            this.RegisterTestDataVariation(TestDataVariations.WithNull, OpenNullableType.MakeGenericType(typeParams), GetNullTestData);\n            this.RegisterTestDataVariation(TestDataVariations.AsNullable, OpenNullableType.MakeGenericType(typeParams), GetTestDataAsNullable);\n        }\n\n        public object GetNullTestData()\n        {\n            return null;\n        }\n\n        public IEnumerable<Nullable<T>> GetTestDataAsNullable()\n        {\n            return this.GetTypedTestData().Select(d => new Nullable<T>(d));\n        }\n\n        protected override IEnumerable<T> GetTypedTestData()\n        {\n            return this.testData;\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/GenericTypeAssert.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Linq;\nusing System.Reflection;\n\nnamespace Microsoft.TestCommon\n{\n    /// <summary>\n    /// MSTest assertion class to provide convenience and assert methods for generic types\n    /// whose type parameters are not known at compile time.\n    /// </summary>\n    public class GenericTypeAssert\n    {\n        private static readonly GenericTypeAssert singleton = new GenericTypeAssert();\n\n        public static GenericTypeAssert Singleton { get { return singleton; } }\n\n        /// <summary>\n        /// Asserts the given <paramref name=\"genericBaseType\"/> is a generic type and creates a new\n        /// bound generic type using <paramref name=\"genericParameterType\"/>.  It then asserts there\n        /// is a constructor that will accept <paramref name=\"parameterTypes\"/> and returns it.\n        /// </summary>\n        /// <param name=\"genericBaseType\">The unbound generic base type.</param>\n        /// <param name=\"genericParameterType\">The type of the single generic parameter to apply to create a bound generic type.</param>\n        /// <param name=\"parameterTypes\">The list of parameter types for a constructor that must exist.</param>\n        /// <returns>The <see cref=\"ConstructorInfo\"/> of that constructor which may be invoked to create that new generic type.</returns>\n        public ConstructorInfo GetConstructor(Type genericBaseType, Type genericParameterType, params Type[] parameterTypes)\n        {\n            Assert.NotNull(genericBaseType);\n            Assert.True(genericBaseType.IsGenericTypeDefinition);\n            Assert.NotNull(genericParameterType);\n            Assert.NotNull(parameterTypes);\n\n            Type genericType = genericBaseType.MakeGenericType(new Type[] { genericParameterType });\n            ConstructorInfo ctor = genericType.GetConstructor(parameterTypes);\n            Assert.True(ctor != null, String.Format(\"Test error: failed to locate generic ctor for type '{0}<{1}>',\", genericBaseType.Name, genericParameterType.Name));\n            return ctor;\n        }\n\n        /// <summary>\n        /// Asserts the given <paramref name=\"genericBaseType\"/> is a generic type and creates a new\n        /// bound generic type using <paramref name=\"genericParameterType\"/>.  It then asserts there\n        /// is a constructor that will accept <paramref name=\"parameterTypes\"/> and returns it.\n        /// </summary>\n        /// <param name=\"genericBaseType\">The unbound generic base type.</param>\n        /// <param name=\"genericParameterTypes\">The types of the generic parameters to apply to create a bound generic type.</param>\n        /// <param name=\"parameterTypes\">The list of parameter types for a constructor that must exist.</param>\n        /// <returns>The <see cref=\"ConstructorInfo\"/> of that constructor which may be invoked to create that new generic type.</returns>\n        public ConstructorInfo GetConstructor(Type genericBaseType, Type[] genericParameterTypes, params Type[] parameterTypes)\n        {\n            Assert.NotNull(genericBaseType);\n            Assert.True(genericBaseType.IsGenericTypeDefinition);\n            Assert.NotNull(genericParameterTypes);\n            Assert.NotNull(parameterTypes);\n\n            Type genericType = genericBaseType.MakeGenericType(genericParameterTypes);\n            ConstructorInfo ctor = genericType.GetConstructor(parameterTypes);\n            Assert.True(ctor != null, String.Format(\"Test error: failed to locate generic ctor for type '{0}<>',\", genericBaseType.Name));\n            return ctor;\n        }\n\n        /// <summary>\n        /// Creates a new bound generic type and invokes the constructor matched from <see cref=\"parameterTypes\"/>.\n        /// </summary>\n        /// <param name=\"genericBaseType\">The unbound generic base type.</param>\n        /// <param name=\"genericParameterType\">The type of the single generic parameter to apply to create a bound generic type.</param>\n        /// <param name=\"parameterTypes\">The list of parameter types for a constructor that must exist.</param>\n        /// <param name=\"parameterValues\">The list of values to supply to the constructor</param>\n        /// <returns>The instance created by calling that constructor.</returns>\n        public object InvokeConstructor(Type genericBaseType, Type genericParameterType, Type[] parameterTypes, object[] parameterValues)\n        {\n            ConstructorInfo ctor = GetConstructor(genericBaseType, genericParameterType, parameterTypes);\n            Assert.NotNull(parameterValues);\n            Assert.Equal(parameterTypes.Length, parameterValues.Length);\n            return ctor.Invoke(parameterValues);\n        }\n\n        /// <summary>\n        /// Creates a new bound generic type and invokes the constructor matched from <see cref=\"parameterTypes\"/>.\n        /// </summary>\n        /// <param name=\"genericBaseType\">The unbound generic base type.</param>\n        /// <param name=\"genericParameterTypse\">The types of the generic parameters to apply to create a bound generic type.</param>\n        /// <param name=\"parameterTypes\">The list of parameter types for a constructor that must exist.</param>\n        /// <param name=\"parameterValues\">The list of values to supply to the constructor</param>\n        /// <returns>The instance created by calling that constructor.</returns>\n        public object InvokeConstructor(Type genericBaseType, Type[] genericParameterTypes, Type[] parameterTypes, object[] parameterValues)\n        {\n            ConstructorInfo ctor = GetConstructor(genericBaseType, genericParameterTypes, parameterTypes);\n            Assert.NotNull(parameterValues);\n            Assert.Equal(parameterTypes.Length, parameterValues.Length);\n            return ctor.Invoke(parameterValues);\n        }\n\n        /// <summary>\n        /// Creates a new bound generic type and invokes the constructor matched from the types of <paramref name=\"parameterValues\"/>.\n        /// </summary>\n        /// <param name=\"genericBaseType\">The unbound generic base type.</param>\n        /// <param name=\"genericParameterType\">The type of the single generic parameter to apply to create a bound generic type.</param>\n        /// <param name=\"parameterValues\">The list of values to supply to the constructor.  It must be possible to determine the</param>\n        /// <returns>The instance created by calling that constructor.</returns>\n        public object InvokeConstructor(Type genericBaseType, Type genericParameterType, params object[] parameterValues)\n        {\n            Assert.NotNull(genericBaseType);\n            Assert.True(genericBaseType.IsGenericTypeDefinition);\n            Assert.NotNull(genericParameterType);\n\n            Type genericType = genericBaseType.MakeGenericType(new Type[] { genericParameterType });\n\n            ConstructorInfo ctor = FindConstructor(genericType, parameterValues);\n            Assert.True(ctor != null, String.Format(\"Test error: failed to locate generic ctor for type '{0}<{1}>',\", genericBaseType.Name, genericParameterType.Name));\n            return ctor.Invoke(parameterValues);\n        }\n\n        /// <summary>\n        /// Creates a new bound generic type and invokes the constructor matched from the types of <paramref name=\"parameterValues\"/>.\n        /// </summary>\n        /// <param name=\"genericBaseType\">The unbound generic base type.</param>\n        /// <param name=\"genericParameterTypes\">The types of the generic parameters to apply to create a bound generic type.</param>\n        /// <param name=\"parameterValues\">The list of values to supply to the constructor.  It must be possible to determine the</param>\n        /// <returns>The instance created by calling that constructor.</returns>\n        public object InvokeConstructor(Type genericBaseType, Type[] genericParameterTypes, params object[] parameterValues)\n        {\n            Assert.NotNull(genericBaseType);\n            Assert.True(genericBaseType.IsGenericTypeDefinition);\n            Assert.NotNull(genericParameterTypes);\n\n            Type genericType = genericBaseType.MakeGenericType(genericParameterTypes);\n\n            ConstructorInfo ctor = FindConstructor(genericType, parameterValues);\n            Assert.True(ctor != null, String.Format(\"Test error: failed to locate generic ctor for type '{0}<>',\", genericBaseType.Name));\n            return ctor.Invoke(parameterValues);\n        }\n\n        /// <summary>\n        /// Creates a new bound generic type and invokes the constructor matched from <see cref=\"parameterTypes\"/>.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of object the constuctor is expected to yield.</typeparam>\n        /// <param name=\"genericBaseType\">The unbound generic base type.</param>\n        /// <param name=\"genericParameterType\">The type of the single generic parameter to apply to create a bound generic type.</param>\n        /// <param name=\"parameterTypes\">The list of parameter types for a constructor that must exist.</param>\n        /// <param name=\"parameterValues\">The list of values to supply to the constructor</param>\n        /// <returns>An instance of type <typeparamref name=\"T\"/>.</returns>\n        public T InvokeConstructor<T>(Type genericBaseType, Type genericParameterType, Type[] parameterTypes, object[] parameterValues)\n        {\n            ConstructorInfo ctor = GetConstructor(genericBaseType, genericParameterType, parameterTypes);\n            Assert.NotNull(parameterValues);\n            Assert.Equal(parameterTypes.Length, parameterValues.Length);\n            return (T)ctor.Invoke(parameterValues);\n        }\n\n        /// <summary>\n        /// Creates a new bound generic type and invokes the constructor matched from <see cref=\"parameterTypes\"/>.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of object the constuctor is expected to yield.</typeparam>\n        /// <param name=\"genericBaseType\">The unbound generic base type.</param>\n        /// <param name=\"genericParameterTypes\">The types of the generic parameters to apply to create a bound generic type.</param>\n        /// <param name=\"parameterTypes\">The list of parameter types for a constructor that must exist.</param>\n        /// <param name=\"parameterValues\">The list of values to supply to the constructor</param>\n        /// <returns>An instance of type <typeparamref name=\"T\"/>.</returns>\n        public T InvokeConstructor<T>(Type genericBaseType, Type[] genericParameterTypes, Type[] parameterTypes, object[] parameterValues)\n        {\n            ConstructorInfo ctor = GetConstructor(genericBaseType, genericParameterTypes, parameterTypes);\n            Assert.NotNull(parameterValues);\n            Assert.Equal(parameterTypes.Length, parameterValues.Length);\n            return (T)ctor.Invoke(parameterValues);\n        }\n\n        /// <summary>\n        /// Creates a new bound generic type and invokes the constructor matched from <see cref=\"parameterTypes\"/>.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of object the constuctor is expected to yield.</typeparam>\n        /// <param name=\"genericBaseType\">The unbound generic base type.</param>\n        /// <param name=\"genericParameterType\">The type of the single generic parameter to apply to create a bound generic type.</param>\n        /// <param name=\"parameterValues\">The list of values to supply to the constructor.  It must be possible to determine the</param>\n        /// <returns>The instance created by calling that constructor.</returns>\n        /// <returns>An instance of type <typeparamref name=\"T\"/>.</returns>\n        public T InvokeConstructor<T>(Type genericBaseType, Type genericParameterType, params object[] parameterValues)\n        {\n            Assert.NotNull(genericBaseType);\n            Assert.True(genericBaseType.IsGenericTypeDefinition);\n            Assert.NotNull(genericParameterType);\n\n            Type genericType = genericBaseType.MakeGenericType(new Type[] { genericParameterType });\n\n            ConstructorInfo ctor = FindConstructor(genericType, parameterValues);\n            Assert.True(ctor != null, String.Format(\"Test error: failed to locate generic ctor for type '{0}<{1}>',\", genericBaseType.Name, genericParameterType.Name));\n            return (T)ctor.Invoke(parameterValues);\n        }\n\n        /// <summary>\n        /// Creates a new bound generic type and invokes the constructor matched from <see cref=\"parameterTypes\"/>.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of object the constuctor is expected to yield.</typeparam>\n        /// <param name=\"genericBaseType\">The unbound generic base type.</param>\n        /// <param name=\"genericParameterTypes\">The types of the generic parameters to apply to create a bound generic type.</param>\n        /// <param name=\"parameterValues\">The list of values to supply to the constructor.  It must be possible to determine the</param>\n        /// <returns>The instance created by calling that constructor.</returns>\n        /// <returns>An instance of type <typeparamref name=\"T\"/>.</returns>\n        public T InvokeConstructor<T>(Type genericBaseType, Type[] genericParameterTypes, params object[] parameterValues)\n        {\n            Assert.NotNull(genericBaseType);\n            Assert.True(genericBaseType.IsGenericTypeDefinition);\n            Assert.NotNull(genericParameterTypes);\n\n            Type genericType = genericBaseType.MakeGenericType(genericParameterTypes);\n\n            ConstructorInfo ctor = FindConstructor(genericType, parameterValues);\n            Assert.True(ctor != null, String.Format(\"Test error: failed to locate generic ctor for type '{0}<>',\", genericBaseType.Name));\n            return (T)ctor.Invoke(parameterValues);\n        }\n\n        /// <summary>\n        /// Asserts the given instance is one from a generic type of the specified parameter type.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of instance.</typeparam>\n        /// <param name=\"instance\">The instance to test.</param>\n        /// <param name=\"genericTypeParameter\">The type of the generic parameter to which the instance's generic type should have been bound.</param>\n        public void IsCorrectGenericType<T>(T instance, Type genericTypeParameter) where T : class\n        {\n            Assert.NotNull(instance);\n            Assert.NotNull(genericTypeParameter);\n            Assert.True(instance.GetType().IsGenericType);\n            Type[] genericArguments = instance.GetType().GetGenericArguments();\n            Type genericArgument = Assert.Single(genericArguments);\n            Assert.Equal(genericTypeParameter, genericArgument);\n        }\n\n        /// <summary>\n        /// Invokes via Reflection the method on the given instance.\n        /// </summary>\n        /// <param name=\"instance\">The instance to use.</param>\n        /// <param name=\"methodName\">The name of the method to call.</param>\n        /// <param name=\"parameterTypes\">The types of the parameters to the method.</param>\n        /// <param name=\"parameterValues\">The values to supply to the method.</param>\n        /// <returns>The results of the method.</returns>\n        public object InvokeMethod(object instance, string methodName, Type[] parameterTypes, object[] parameterValues)\n        {\n            Assert.NotNull(instance);\n            Assert.NotNull(parameterTypes);\n            Assert.NotNull(parameterValues);\n            Assert.Equal(parameterTypes.Length, parameterValues.Length);\n            MethodInfo methodInfo = instance.GetType().GetMethod(methodName, parameterTypes);\n            Assert.NotNull(methodInfo);\n            return methodInfo.Invoke(instance, parameterValues);\n        }\n\n        /// <summary>\n        /// Invokes via Reflection the static method on the given type.\n        /// </summary>\n        /// <param name=\"type\">The type containing the method.</param>\n        /// <param name=\"methodName\">The name of the method to call.</param>\n        /// <param name=\"parameterTypes\">The types of the parameters to the method.</param>\n        /// <param name=\"parameterValues\">The values to supply to the method.</param>\n        /// <returns>The results of the method.</returns>\n        public object InvokeMethod(Type type, string methodName, Type[] parameterTypes, object[] parameterValues)\n        {\n            Assert.NotNull(type);\n            Assert.NotNull(parameterTypes);\n            Assert.NotNull(parameterValues);\n            Assert.Equal(parameterTypes.Length, parameterValues.Length);\n            MethodInfo methodInfo = type.GetMethod(methodName, parameterTypes);\n            Assert.NotNull(methodInfo);\n            return methodInfo.Invoke(null, parameterValues);\n        }\n\n        /// <summary>\n        /// Invokes via Reflection the static method on the given type.\n        /// </summary>\n        /// <param name=\"type\">The type containing the method.</param>\n        /// <param name=\"methodName\">The name of the method to call.</param>\n        /// <param name=\"genericParameterType\">The generic parameter type of the method.</param>\n        /// <param name=\"parameterTypes\">The types of the parameters to the method.</param>\n        /// <param name=\"parameterValues\">The values to supply to the method.</param>\n        /// <returns>The results of the method.</returns>\n        public MethodInfo CreateGenericMethod(Type type, string methodName, Type genericParameterType, Type[] parameterTypes)\n        {\n            Assert.NotNull(type);\n            Assert.NotNull(parameterTypes);\n            Assert.NotNull(genericParameterType);\n            //MethodInfo methodInfo = type.GetMethod(methodName, parameterTypes);\n            MethodInfo methodInfo = type.GetMethods().Where((m) => m.Name.Equals(methodName, StringComparison.OrdinalIgnoreCase) && m.IsGenericMethod && AreAssignableFrom(m.GetParameters(), parameterTypes)).FirstOrDefault();\n            Assert.NotNull(methodInfo);\n            Assert.True(methodInfo.IsGenericMethod);\n            MethodInfo genericMethod = methodInfo.MakeGenericMethod(genericParameterType);\n            Assert.NotNull(genericMethod);\n            return genericMethod;\n        }\n\n        /// <summary>\n        /// Invokes via Reflection the static generic method on the given type.\n        /// </summary>\n        /// <param name=\"type\">The type containing the method.</param>\n        /// <param name=\"methodName\">The name of the method to call.</param>\n        /// <param name=\"genericParameterType\">The generic parameter type of the method.</param>\n        /// <param name=\"parameterTypes\">The types of the parameters to the method.</param>\n        /// <param name=\"parameterValues\">The values to supply to the method.</param>\n        /// <returns>The results of the method.</returns>\n        public object InvokeGenericMethod(Type type, string methodName, Type genericParameterType, Type[] parameterTypes, object[] parameterValues)\n        {\n            MethodInfo methodInfo = CreateGenericMethod(type, methodName, genericParameterType, parameterTypes);\n            Assert.Equal(parameterTypes.Length, parameterValues.Length);\n            return methodInfo.Invoke(null, parameterValues);\n        }\n\n        /// <summary>\n        /// Invokes via Reflection the generic method on the given instance.\n        /// </summary>\n        /// <param name=\"instance\">The instance on which to invoke the method.</param>\n        /// <param name=\"methodName\">The name of the method to call.</param>\n        /// <param name=\"genericParameterType\">The generic parameter type of the method.</param>\n        /// <param name=\"parameterTypes\">The types of the parameters to the method.</param>\n        /// <param name=\"parameterValues\">The values to supply to the method.</param>\n        /// <returns>The results of the method.</returns>\n        public object InvokeGenericMethod(object instance, string methodName, Type genericParameterType, Type[] parameterTypes, object[] parameterValues)\n        {\n            Assert.NotNull(instance);\n            MethodInfo methodInfo = CreateGenericMethod(instance.GetType(), methodName, genericParameterType, parameterTypes);\n            Assert.Equal(parameterTypes.Length, parameterValues.Length);\n            return methodInfo.Invoke(instance, parameterValues);\n        }\n\n        /// <summary>\n        /// Invokes via Reflection the generic method on the given instance.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of the return value from the method.</typeparam>\n        /// <param name=\"instance\">The instance on which to invoke the method.</param>\n        /// <param name=\"methodName\">The name of the method to call.</param>\n        /// <param name=\"genericParameterType\">The generic parameter type of the method.</param>\n        /// <param name=\"parameterTypes\">The types of the parameters to the method.</param>\n        /// <param name=\"parameterValues\">The values to supply to the method.</param>\n        /// <returns>The results of the method.</returns>\n        public T InvokeGenericMethod<T>(object instance, string methodName, Type genericParameterType, Type[] parameterTypes, object[] parameterValues)\n        {\n            return (T)InvokeGenericMethod(instance, methodName, genericParameterType, parameterTypes, parameterValues);\n        }\n\n        /// <summary>\n        /// Invokes via Reflection the method on the given instance.\n        /// </summary>\n        /// <param name=\"instance\">The instance to use.</param>\n        /// <param name=\"methodName\">The name of the method to call.</param>\n        /// <param name=\"parameterValues\">The values to supply to the method.</param>\n        /// <returns>The results of the method.</returns>\n        public object InvokeMethod(object instance, string methodName, params object[] parameterValues)\n        {\n            Assert.NotNull(instance);\n            MethodInfo methodInfo = FindMethod(instance.GetType(), methodName, parameterValues);\n            Assert.NotNull(methodInfo);\n            return methodInfo.Invoke(instance, parameterValues);\n        }\n\n        /// <summary>\n        /// Invokes via Reflection the static method on the given type.\n        /// </summary>\n        /// <param name=\"instance\">The instance to use.</param>\n        /// <param name=\"methodName\">The name of the method to call.</param>\n        /// <param name=\"parameterValues\">The values to supply to the method.</param>\n        /// <returns>The results of the method.</returns>\n        public object InvokeMethod(Type type, string methodName, params object[] parameterValues)\n        {\n            Assert.NotNull(type);\n            MethodInfo methodInfo = FindMethod(type, methodName, parameterValues);\n            Assert.NotNull(methodInfo);\n            return methodInfo.Invoke(null, parameterValues);\n        }\n\n        /// <summary>\n        /// Invokes via Reflection the method on the given instance.\n        /// </summary>\n        /// <param name=\"instance\">The instance to use.</param>\n        /// <param name=\"methodName\">The name of the method to call.</param>\n        /// <param name=\"genericParameterType\">The type of the generic parameter.</param>\n        /// <param name=\"parameterValues\">The values to supply to the method.</param>\n        /// <returns>The results of the method.</returns>\n        public object InvokeGenericMethod(object instance, string methodName, Type genericParameterType, params object[] parameterValues)\n        {\n            Assert.NotNull(instance);\n            Assert.NotNull(genericParameterType);\n            MethodInfo methodInfo = FindMethod(instance.GetType(), methodName, parameterValues);\n            Assert.NotNull(methodInfo);\n            Assert.True(methodInfo.IsGenericMethod);\n            MethodInfo genericMethod = methodInfo.MakeGenericMethod(genericParameterType);\n            return genericMethod.Invoke(instance, parameterValues);\n        }\n\n        /// <summary>\n        /// Invokes via Reflection the method on the given instance.\n        /// </summary>\n        /// <param name=\"instance\">The instance to use.</param>\n        /// <param name=\"methodName\">The name of the method to call.</param>\n        /// <param name=\"genericParameterType\">The type of the generic parameter.</param>\n        /// <param name=\"parameterValues\">The values to supply to the method.</param>\n        /// <returns>The results of the method.</returns>\n        public object InvokeGenericMethod(Type type, string methodName, Type genericParameterType, params object[] parameterValues)\n        {\n            Assert.NotNull(type);\n            Assert.NotNull(genericParameterType);\n            MethodInfo methodInfo = FindMethod(type, methodName, parameterValues);\n            Assert.NotNull(methodInfo);\n            Assert.True(methodInfo.IsGenericMethod);\n            MethodInfo genericMethod = methodInfo.MakeGenericMethod(genericParameterType);\n            return genericMethod.Invoke(null, parameterValues);\n        }\n\n        /// <summary>\n        /// Retrieves the value from the specified property.\n        /// </summary>\n        /// <param name=\"instance\">The instance containing the property value.</param>\n        /// <param name=\"propertyName\">The name of the property.</param>\n        /// <param name=\"failureMessage\">The error message to prefix any test assertions.</param>\n        /// <returns>The value returned from the property.</returns>\n        public object GetProperty(object instance, string propertyName, string failureMessage)\n        {\n            PropertyInfo propertyInfo = instance.GetType().GetProperty(propertyName);\n            Assert.NotNull(propertyInfo);\n            return propertyInfo.GetValue(instance, null);\n        }\n\n        private static bool AreAssignableFrom(Type[] parameterTypes, params object[] parameterValues)\n        {\n            Assert.NotNull(parameterTypes);\n            Assert.NotNull(parameterValues);\n            if (parameterTypes.Length != parameterValues.Length)\n            {\n                return false;\n            }\n\n            for (int i = 0; i < parameterTypes.Length; ++i)\n            {\n                if (!parameterTypes[i].IsInstanceOfType(parameterValues[i]))\n                {\n                    return false;\n                }\n            }\n\n            return true;\n        }\n\n        private static bool AreAssignableFrom(ParameterInfo[] parameterInfos, params Type[] parameterTypes)\n        {\n            Assert.NotNull(parameterInfos);\n            Assert.NotNull(parameterTypes);\n            Type[] parameterInfoTypes = parameterInfos.Select<ParameterInfo, Type>((info) => info.ParameterType).ToArray();\n            if (parameterInfoTypes.Length != parameterTypes.Length)\n            {\n                return false;\n            }\n\n            for (int i = 0; i < parameterInfoTypes.Length; ++i)\n            {\n                // Generic parameters are assumed to be assignable\n                if (parameterInfoTypes[i].IsGenericParameter)\n                {\n                    continue;\n                }\n\n                if (!parameterInfoTypes[i].IsAssignableFrom(parameterTypes[i]))\n                {\n                    return false;\n                }\n            }\n\n            return true;\n        }\n\n        private static bool AreAssignableFrom(ParameterInfo[] parameterInfos, params object[] parameterValues)\n        {\n            Assert.NotNull(parameterInfos);\n            Assert.NotNull(parameterValues);\n            Type[] parameterTypes = parameterInfos.Select<ParameterInfo, Type>((info) => info.ParameterType).ToArray();\n            return AreAssignableFrom(parameterTypes, parameterValues);\n        }\n\n        private static ConstructorInfo FindConstructor(Type type, params object[] parameterValues)\n        {\n            Assert.NotNull(type);\n            Assert.NotNull(parameterValues);\n            return type.GetConstructors().FirstOrDefault((c) => AreAssignableFrom(c.GetParameters(), parameterValues));\n        }\n\n        private static MethodInfo FindMethod(Type type, string methodName, params object[] parameterValues)\n        {\n            Assert.NotNull(type);\n            Assert.False(String.IsNullOrWhiteSpace(methodName));\n            Assert.NotNull(parameterValues);\n            return type.GetMethods().FirstOrDefault((m) => String.Equals(m.Name, methodName, StringComparison.Ordinal) && AreAssignableFrom(m.GetParameters(), parameterValues));\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/HttpAssert.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Net.Http.Headers;\nusing System.Text.RegularExpressions;\nusing System.Threading.Tasks;\n\nnamespace Microsoft.TestCommon\n{\n    /// <summary>\n    /// Unit test utility for testing <see cref=\"HttpResponseMessage\"/> instances.\n    /// </summary>\n    public class HttpAssert\n    {\n        private const string CommaSeperator = \", \";\n        private static readonly HttpAssert singleton = new HttpAssert();\n\n        public static HttpAssert Singleton { get { return singleton; } }\n\n        /// <summary>\n        /// Asserts that the expected <see cref=\"HttpRequestMessage\"/> is equal to the actual <see cref=\"HttpRequestMessage\"/>.\n        /// </summary>\n        /// <param name=\"expected\">The expected <see cref=\"HttpRequestMessage\"/>. Should not be <c>null</c>.</param>\n        /// <param name=\"actual\">The actual <see cref=\"HttpRequestMessage\"/>. Should not be <c>null</c>.</param>\n        public async Task EqualAsync(HttpRequestMessage expected, HttpRequestMessage actual)\n        {\n            Assert.NotNull(expected);\n            Assert.NotNull(actual);\n\n            Assert.Equal(expected.Version, actual.Version);\n            Equal(expected.Headers, actual.Headers);\n\n            if (expected.Content == null)\n            {\n                Assert.Null(actual.Content);\n            }\n            else\n            {\n                string expectedContent = CleanContentString(await expected.Content.ReadAsStringAsync());\n                string actualContent = CleanContentString(await actual.Content.ReadAsStringAsync());\n                Assert.Equal(expectedContent, actualContent);\n                Equal(expected.Content.Headers, actual.Content.Headers);\n            }\n        }\n\n        /// <summary>\n        /// Asserts that the expected <see cref=\"HttpResponseMessage\"/> is equal to the actual <see cref=\"HttpResponseMessage\"/>.\n        /// </summary>\n        /// <param name=\"expected\">The expected <see cref=\"HttpResponseMessage\"/>. Should not be <c>null</c>.</param>\n        /// <param name=\"actual\">The actual <see cref=\"HttpResponseMessage\"/>. Should not be <c>null</c>.</param>\n        public Task EqualAsync(HttpResponseMessage expected, HttpResponseMessage actual)\n        {\n            return EqualAsync(expected, actual, verifyContentStringCallback: null);\n        }\n\n        /// <summary>\n        /// Asserts that the expected <see cref=\"HttpResponseMessage\"/> is equal to the actual <see cref=\"HttpResponseMessage\"/>.\n        /// </summary>\n        /// <param name=\"expected\">The expected <see cref=\"HttpResponseMessage\"/>. Should not be <c>null</c>.</param>\n        /// <param name=\"actual\">The actual <see cref=\"HttpResponseMessage\"/>. Should not be <c>null</c>.</param>\n        /// <param name=\"verifyContentCallback\">The callback to verify the Content string. If it is null, Assert.Equal will be used. </param>\n        public async Task EqualAsync(HttpResponseMessage expected, HttpResponseMessage actual, Action<string, string> verifyContentStringCallback)\n        {\n            Assert.NotNull(expected);\n            Assert.NotNull(actual);\n\n            Assert.Equal(expected.StatusCode, actual.StatusCode);\n            Assert.Equal(expected.ReasonPhrase, actual.ReasonPhrase);\n            Assert.Equal(expected.Version, actual.Version);\n            Equal(expected.Headers, actual.Headers);\n\n            if (expected.Content == null)\n            {\n                Assert.Null(actual.Content);\n            }\n            else\n            {\n                string expectedContent = CleanContentString(await expected.Content.ReadAsStringAsync());\n                string actualContent = CleanContentString(await actual.Content.ReadAsStringAsync());\n                if (verifyContentStringCallback != null)\n                {\n                    verifyContentStringCallback(expectedContent, actualContent);\n                }\n                else\n                {\n                    Assert.Equal(expectedContent, actualContent);\n                }\n                Equal(expected.Content.Headers, actual.Content.Headers);\n            }\n        }\n\n        /// <summary>\n        /// Asserts that the expected <see cref=\"HttpHeaders\"/> instance is equal to the actual <see cref=\"actualHeaders\"/> instance.\n        /// </summary>\n        /// <param name=\"expectedHeaders\">The expected <see cref=\"HttpHeaders\"/> instance. Should not be <c>null</c>.</param>\n        /// <param name=\"actualHeaders\">The actual <see cref=\"HttpHeaders\"/> instance. Should not be <c>null</c>.</param>\n        public void Equal(HttpHeaders expectedHeaders, HttpHeaders actualHeaders)\n        {\n            Assert.NotNull(expectedHeaders);\n            Assert.NotNull(actualHeaders);\n\n            Assert.Equal(expectedHeaders.Count(), actualHeaders.Count());\n\n            foreach (KeyValuePair<string, IEnumerable<string>> expectedHeader in expectedHeaders)\n            {\n                KeyValuePair<string, IEnumerable<string>> actualHeader = actualHeaders.FirstOrDefault(h => h.Key == expectedHeader.Key);\n                if (expectedHeader.Key == \"Date\")\n                {\n                    HandleDateHeader(expectedHeader.Value.ToArray(), actualHeader.Value.ToArray());\n                }\n                else\n                {\n                    string expectedHeaderStr = string.Join(CommaSeperator, expectedHeader.Value);\n                    string actualHeaderStr = string.Join(CommaSeperator, actualHeader.Value);\n                    Assert.Equal(expectedHeaderStr, actualHeaderStr);\n                }\n            }\n        }\n\n        /// <summary>\n        /// Asserts the given <see cref=\"HttpHeaders\"/> contain the given <paramref name=\"values\"/>\n        /// for the given <paramref name=\"name\"/>.\n        /// </summary>\n        /// <param name=\"headers\">The <see cref=\"HttpHeaders\"/> to examine.  It cannot be <c>null</c>.</param>\n        /// <param name=\"name\">The name of the header.  It cannot be empty.</param>\n        /// <param name=\"values\">The values that must all be present.  It cannot be null.</param>\n        public void Contains(HttpHeaders headers, string name, params string[] values)\n        {\n            Assert.NotNull(headers);\n            Assert.False(String.IsNullOrWhiteSpace(name), \"Test error: name cannot be empty.\");\n            Assert.NotNull(values);\n\n            IEnumerable<string> headerValues = null;\n            bool foundIt = headers.TryGetValues(name, out headerValues);\n            Assert.True(foundIt);\n\n            foreach (string value in values)\n            {\n                Assert.Contains(value, headerValues);\n            }\n        }\n\n        public bool IsKnownUnserializableType(Type type, Func<Type, bool> isTypeUnserializableCallback)\n        {\n            if (isTypeUnserializableCallback != null && isTypeUnserializableCallback(type))\n            {\n                return true;\n            }\n\n            if (type.IsGenericType)\n            {\n                if (typeof(IEnumerable).IsAssignableFrom(type))\n                {\n                    if (type.GetMethod(\"Add\") == null)\n                    {\n                        return true;\n                    }\n                }\n\n                // Generic type -- recursively analyze generic arguments\n                return IsKnownUnserializableType(type.GetGenericArguments()[0], isTypeUnserializableCallback);\n            }\n\n            if (type.HasElementType && IsKnownUnserializableType(type.GetElementType(), isTypeUnserializableCallback))\n            {\n                return true;\n            }\n\n            return false;\n        }\n\n        public bool IsKnownUnserializable(Type type, object obj, Func<Type, bool> isTypeUnserializableCallback)\n        {\n            if (IsKnownUnserializableType(type, isTypeUnserializableCallback))\n            {\n                return true;\n            }\n\n            return obj != null && IsKnownUnserializableType(obj.GetType(), isTypeUnserializableCallback);\n        }\n\n        public bool IsKnownUnserializable(Type type, object obj)\n        {\n            return IsKnownUnserializable(type, obj, null);\n        }\n\n        public bool CanRoundTrip(Type type)\n        {\n            if (typeof(DateTime).IsAssignableFrom(type))\n            {\n                return false;\n            }\n\n            if (typeof(DateTimeOffset).IsAssignableFrom(type))\n            {\n                return false;\n            }\n\n            if (type.IsGenericType)\n            {\n                foreach (Type genericParameterType in type.GetGenericArguments())\n                {\n                    if (!CanRoundTrip(genericParameterType))\n                    {\n                        return false;\n                    }\n                }\n            }\n\n            if (type.HasElementType)\n            {\n                return CanRoundTrip(type.GetElementType());\n            }\n\n            return true;\n        }\n\n        private static void HandleDateHeader(string[] expectedDateHeaderValues, string[] actualDateHeaderValues)\n        {\n            Assert.Equal(expectedDateHeaderValues.Length, actualDateHeaderValues.Length);\n\n            for (int i = 0; i < expectedDateHeaderValues.Length; i++)\n            {\n                DateTime expectedDateTime = DateTime.Parse(expectedDateHeaderValues[i]);\n                DateTime actualDateTime = DateTime.Parse(actualDateHeaderValues[i]);\n\n                Assert.Equal(expectedDateTime.Year, actualDateTime.Year);\n                Assert.Equal(expectedDateTime.Month, actualDateTime.Month);\n                Assert.Equal(expectedDateTime.Day, actualDateTime.Day);\n\n                int hourDifference = Math.Abs(actualDateTime.Hour - expectedDateTime.Hour);\n                Assert.True(hourDifference <= 1);\n\n                int minuteDifference = Math.Abs(actualDateTime.Minute - expectedDateTime.Minute);\n                Assert.True(minuteDifference <= 1);\n            }\n        }\n\n        private static string CleanContentString(string content)\n        {\n            Assert.Null(content);\n\n            string cleanedContent = null;\n\n            // remove any port numbers from Uri's\n            cleanedContent = Regex.Replace(content, \":\\\\d+\", \"\");\n\n            return cleanedContent;\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/MediaTypeAssert.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Net.Http.Headers;\n\nnamespace Microsoft.TestCommon\n{\n    public class MediaTypeAssert\n    {\n        private static readonly MediaTypeAssert singleton = new MediaTypeAssert();\n\n        public static MediaTypeAssert Singleton { get { return singleton; } }\n\n        public void AreEqual(MediaTypeHeaderValue expected, MediaTypeHeaderValue actual, string errorMessage)\n        {\n            if (expected != null || actual != null)\n            {\n                Assert.NotNull(expected);\n                Assert.Equal(0, new MediaTypeHeaderValueComparer().Compare(expected, actual));\n            }\n        }\n\n        public void AreEqual(MediaTypeHeaderValue expected, string actual, string errorMessage)\n        {\n            if (expected != null || !String.IsNullOrEmpty(actual))\n            {\n                MediaTypeHeaderValue actualMediaType = new MediaTypeHeaderValue(actual);\n                Assert.NotNull(expected);\n                Assert.Equal(0, new MediaTypeHeaderValueComparer().Compare(expected, actualMediaType));\n            }\n        }\n\n        public void AreEqual(string expected, string actual, string errorMessage)\n        {\n            if (!String.IsNullOrEmpty(expected) || !String.IsNullOrEmpty(actual))\n            {\n                Assert.NotNull(expected);\n                MediaTypeHeaderValue expectedMediaType = new MediaTypeHeaderValue(expected);\n                MediaTypeHeaderValue actualMediaType = new MediaTypeHeaderValue(actual);\n                Assert.Equal(0, new MediaTypeHeaderValueComparer().Compare(expectedMediaType, actualMediaType));\n            }\n        }\n\n        public void AreEqual(string expected, MediaTypeHeaderValue actual, string errorMessage)\n        {\n            if (!String.IsNullOrEmpty(expected) || actual != null)\n            {\n                Assert.NotNull(expected);\n                MediaTypeHeaderValue expectedMediaType = new MediaTypeHeaderValue(expected);\n                Assert.Equal(0, new MediaTypeHeaderValueComparer().Compare(expectedMediaType, actual));\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/MediaTypeHeaderValueComparer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Net.Http.Headers;\n\nnamespace Microsoft.TestCommon\n{\n    public class MediaTypeHeaderValueComparer : IComparer<MediaTypeHeaderValue>\n    {\n        private static readonly MediaTypeHeaderValueComparer mediaTypeComparer = new MediaTypeHeaderValueComparer();\n\n        public MediaTypeHeaderValueComparer()\n        {\n        }\n\n        public static MediaTypeHeaderValueComparer Comparer\n        {\n            get\n            {\n                return mediaTypeComparer;\n            }\n        }\n\n        public int Compare(MediaTypeHeaderValue mediaType1, MediaTypeHeaderValue mediaType2)\n        {\n            ParsedMediaTypeHeaderValue parsedMediaType1 = new ParsedMediaTypeHeaderValue(mediaType1);\n            ParsedMediaTypeHeaderValue parsedMediaType2 = new ParsedMediaTypeHeaderValue(mediaType2);\n\n            int returnValue = CompareBasedOnQualityFactor(parsedMediaType1, parsedMediaType2);\n\n            if (returnValue == 0)\n            {\n                if (!String.Equals(parsedMediaType1.Type, parsedMediaType2.Type, StringComparison.OrdinalIgnoreCase))\n                {\n                    if (parsedMediaType1.IsAllMediaRange)\n                    {\n                        return 1;\n                    }\n                    else if (parsedMediaType2.IsAllMediaRange)\n                    {\n                        return -1;\n                    }\n                }\n                else if (!String.Equals(parsedMediaType1.SubType, parsedMediaType2.SubType, StringComparison.OrdinalIgnoreCase))\n                {\n                    if (parsedMediaType1.IsSubTypeMediaRange)\n                    {\n                        return 1;\n                    }\n                    else if (parsedMediaType2.IsSubTypeMediaRange)\n                    {\n                        return -1;\n                    }\n                }\n                else\n                {\n                    if (!parsedMediaType1.HasNonQualityFactorParameter)\n                    {\n                        if (parsedMediaType2.HasNonQualityFactorParameter)\n                        {\n                            return 1;\n                        }\n                    }\n                    else if (!parsedMediaType2.HasNonQualityFactorParameter)\n                    {\n                        return -1;\n                    }\n                }\n            }\n\n            return returnValue;\n        }\n\n        private static int CompareBasedOnQualityFactor(ParsedMediaTypeHeaderValue parsedMediaType1, ParsedMediaTypeHeaderValue parsedMediaType2)\n        {\n            double qualityDifference = parsedMediaType1.QualityFactor - parsedMediaType2.QualityFactor;\n            if (qualityDifference < 0)\n            {\n                return 1;\n            }\n            else if (qualityDifference > 0)\n            {\n                return -1;\n            }\n\n            return 0;\n        }\n    }\n}"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/ParsedMediaTypeHeaderValue.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Net.Http.Headers;\n\nnamespace Microsoft.TestCommon\n{\n    internal class ParsedMediaTypeHeaderValue\n    {\n        private const string MediaRangeAsterisk = \"*\";\n        private const char MediaTypeSubTypeDelimiter = '/';\n        private const string QualityFactorParameterName = \"q\";\n        private const double DefaultQualityFactor = 1.0;\n\n        private MediaTypeHeaderValue mediaType;\n        private string type;\n        private string subType;\n        private bool? hasNonQualityFactorParameter;\n        private double? qualityFactor;\n\n        public ParsedMediaTypeHeaderValue(MediaTypeHeaderValue mediaType)\n        {\n            this.mediaType = mediaType;\n            string[] splitMediaType = mediaType.MediaType.Split(MediaTypeSubTypeDelimiter);\n            this.type = splitMediaType[0];\n            this.subType = splitMediaType[1];\n        }\n\n        public string Type\n        {\n            get\n            {\n                return this.type;\n            }\n        }\n\n        public string SubType\n        {\n            get\n            {\n                return this.subType;\n            }\n        }\n\n        public bool IsAllMediaRange\n        {\n            get\n            {\n                return this.IsSubTypeMediaRange && String.Equals(MediaRangeAsterisk, this.Type, StringComparison.Ordinal);\n            }\n        }\n\n        public bool IsSubTypeMediaRange\n        {\n            get\n            {\n                return String.Equals(MediaRangeAsterisk, this.SubType, StringComparison.Ordinal);\n            }\n        }\n\n        public bool HasNonQualityFactorParameter\n        {\n            get\n            {\n                if (!this.hasNonQualityFactorParameter.HasValue)\n                {\n                    this.hasNonQualityFactorParameter = false;\n                    foreach (NameValueHeaderValue param in this.mediaType.Parameters)\n                    {\n                        if (!String.Equals(QualityFactorParameterName, param.Name, StringComparison.Ordinal))\n                        {\n                            this.hasNonQualityFactorParameter = true;\n                        }\n                    }\n                }\n\n                return this.hasNonQualityFactorParameter.Value;\n            }\n        }\n\n        public string CharSet\n        {\n            get\n            {\n                return this.mediaType.CharSet;\n            }\n        }\n\n        public double QualityFactor\n        {\n            get\n            {\n                if (!this.qualityFactor.HasValue)\n                {\n                    MediaTypeWithQualityHeaderValue mediaTypeWithQuality = this.mediaType as MediaTypeWithQualityHeaderValue;\n                    if (mediaTypeWithQuality != null)\n                    {\n                        this.qualityFactor = mediaTypeWithQuality.Quality;\n                    }\n\n                    if (!this.qualityFactor.HasValue)\n                    {\n                        this.qualityFactor = DefaultQualityFactor;\n                    }\n                }\n\n                return this.qualityFactor.Value;\n            }\n        }\n    }\n}"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/RegexReplacement.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Text.RegularExpressions;\n\nnamespace Microsoft.TestCommon\n{\n    public class RegexReplacement\n    {\n        Regex regex;\n        string replacement;\n\n        public RegexReplacement(Regex regex, string replacement)\n        {\n            this.regex = regex;\n            this.replacement = replacement;\n        }\n\n        public RegexReplacement(string regex, string replacement)\n        {\n            this.regex = new Regex(regex);\n            this.replacement = replacement;\n        }\n\n        public Regex Regex\n        {\n            get\n            {\n                return this.regex;\n            }\n        }\n\n        public string Replacement\n        {\n            get\n            {\n                return this.replacement;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/RuntimeEnvironment.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing Microsoft.Win32;\n\nnamespace Microsoft.TestCommon\n{\n    public static class RuntimeEnvironment\n    {\n        private const string NetFx40FullSubKey = @\"SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\";\n        private const string Version = \"Version\";\n\n        static RuntimeEnvironment()\n        {\n            object runtimeVersion = Registry.LocalMachine.OpenSubKey(RuntimeEnvironment.NetFx40FullSubKey).GetValue(RuntimeEnvironment.Version);\n            string versionFor40String = runtimeVersion as string;\n            if (versionFor40String != null)\n            {\n                VersionFor40 = new Version(versionFor40String);\n            }\n        }\n\n        private static Version VersionFor40;\n\n        public static bool IsVersion45Installed\n        {\n            get\n            {\n                return VersionFor40.Major > 4 || (VersionFor40.Major == 4 && VersionFor40.Minor >= 5);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/SerializerAssert.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.IO;\nusing System.Runtime.Serialization;\nusing System.Runtime.Serialization.Json;\nusing System.Xml.Serialization;\n\nnamespace Microsoft.TestCommon\n{\n    /// <summary>\n    /// MSTest utility for testing code operating against a stream.\n    /// </summary>\n    public class SerializerAssert\n    {\n        private static SerializerAssert singleton = new SerializerAssert();\n\n        public static SerializerAssert Singleton { get { return singleton; } }\n\n        /// <summary>\n        /// Creates a <see cref=\"Stream\"/>, serializes <paramref name=\"objectInstance\"/> to it using\n        /// <see cref=\"XmlSerializer\"/>, rewinds the stream and calls <see cref=\"codeThatChecks\"/>.\n        /// </summary>\n        /// <param name=\"type\">The type to serialize.  It cannot be <c>null</c>.</param>\n        /// <param name=\"objectInstance\">The value to serialize.</param>\n        /// <param name=\"codeThatChecks\">Code to check the contents of the stream.</param>\n        public void UsingXmlSerializer(Type type, object objectInstance, Action<Stream> codeThatChecks)\n        {\n            if (type == null)\n            {\n                throw new ArgumentNullException(\"type\");\n            }\n\n            if (codeThatChecks == null)\n            {\n                throw new ArgumentNullException(\"codeThatChecks\");\n            }\n\n            XmlSerializer serializer = new XmlSerializer(type);\n\n            using (MemoryStream stream = new MemoryStream())\n            {\n                serializer.Serialize(stream, objectInstance);\n\n                stream.Flush();\n                stream.Seek(0L, SeekOrigin.Begin);\n\n                codeThatChecks(stream);\n            }\n        }\n\n        /// <summary>\n        /// Creates a <see cref=\"Stream\"/>, serializes <paramref name=\"objectInstance\"/> to it using\n        /// <see cref=\"XmlSerializer\"/>, rewinds the stream and calls <see cref=\"codeThatChecks\"/>.\n        /// </summary>\n        /// <typeparam name=\"T\">The type to serialize.</typeparam>\n        /// <param name=\"objectInstance\">The value to serialize.</param>\n        /// <param name=\"codeThatChecks\">Code to check the contents of the stream.</param>\n        public void UsingXmlSerializer<T>(T objectInstance, Action<Stream> codeThatChecks)\n        {\n            UsingXmlSerializer(typeof(T), objectInstance, codeThatChecks);\n        }\n\n        /// <summary>\n        /// Creates a <see cref=\"Stream\"/>, serializes <paramref name=\"objectInstance\"/> to it using\n        /// <see cref=\"DataContractSerializer\"/>, rewinds the stream and calls <see cref=\"codeThatChecks\"/>.\n        /// </summary>\n        /// <param name=\"type\">The type to serialize.  It cannot be <c>null</c>.</param>\n        /// <param name=\"objectInstance\">The value to serialize.</param>\n        /// <param name=\"codeThatChecks\">Code to check the contents of the stream.</param>\n        public void UsingDataContractSerializer(Type type, object objectInstance, Action<Stream> codeThatChecks)\n        {\n            if (type == null)\n            {\n                throw new ArgumentNullException(\"type\");\n            }\n\n            if (codeThatChecks == null)\n            {\n                throw new ArgumentNullException(\"codeThatChecks\");\n            }\n\n            DataContractSerializer serializer = new DataContractSerializer(type);\n\n            using (MemoryStream stream = new MemoryStream())\n            {\n                serializer.WriteObject(stream, objectInstance);\n\n                stream.Flush();\n                stream.Seek(0L, SeekOrigin.Begin);\n\n                codeThatChecks(stream);\n            }\n        }\n\n        /// <summary>\n        /// Creates a <see cref=\"Stream\"/>, serializes <paramref name=\"objectInstance\"/> to it using\n        /// <see cref=\"DataContractSerializer\"/>, rewinds the stream and calls <see cref=\"codeThatChecks\"/>.\n        /// </summary>\n        /// <typeparam name=\"T\">The type to serialize.</typeparam>\n        /// <param name=\"objectInstance\">The value to serialize.</param>\n        /// <param name=\"codeThatChecks\">Code to check the contents of the stream.</param>\n        public void UsingDataContractSerializer<T>(T objectInstance, Action<Stream> codeThatChecks)\n        {\n            UsingDataContractSerializer(typeof(T), objectInstance, codeThatChecks);\n        }\n\n        /// <summary>\n        /// Creates a <see cref=\"Stream\"/>, serializes <paramref name=\"objectInstance\"/> to it using\n        /// <see cref=\"DataContractJsonSerializer\"/>, rewinds the stream and calls <see cref=\"codeThatChecks\"/>.\n        /// </summary>\n        /// <param name=\"type\">The type to serialize.  It cannot be <c>null</c>.</param>\n        /// <param name=\"objectInstance\">The value to serialize.</param>\n        /// <param name=\"codeThatChecks\">Code to check the contents of the stream.</param>\n        public static void UsingDataContractJsonSerializer(Type type, object objectInstance, Action<Stream> codeThatChecks)\n        {\n            if (type == null)\n            {\n                throw new ArgumentNullException(\"type\");\n            }\n\n            if (codeThatChecks == null)\n            {\n                throw new ArgumentNullException(\"codeThatChecks\");\n            }\n\n            DataContractJsonSerializer serializer = new DataContractJsonSerializer(type);\n\n            using (MemoryStream stream = new MemoryStream())\n            {\n                serializer.WriteObject(stream, objectInstance);\n\n                stream.Flush();\n                stream.Seek(0L, SeekOrigin.Begin);\n\n                codeThatChecks(stream);\n            }\n        }\n\n        /// <summary>\n        /// Creates a <see cref=\"Stream\"/>, serializes <paramref name=\"objectInstance\"/> to it using\n        /// <see cref=\"DataContractJsonSerializer\"/>, rewinds the stream and calls <see cref=\"codeThatChecks\"/>.\n        /// </summary>\n        /// <typeparam name=\"T\">The type to serialize.</typeparam>\n        /// <param name=\"objectInstance\">The value to serialize.</param>\n        /// <param name=\"codeThatChecks\">Code to check the contents of the stream.</param>\n        public void UsingDataContractJsonSerializer<T>(T objectInstance, Action<Stream> codeThatChecks)\n        {\n            UsingDataContractJsonSerializer(typeof(T), objectInstance, codeThatChecks);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/StreamAssert.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.IO;\nusing System.Threading.Tasks;\n\nnamespace Microsoft.TestCommon\n{\n    //// TODO RONCAIN using System.Runtime.Serialization.Json;\n\n    /// <summary>\n    /// MSTest utility for testing code operating against a stream.\n    /// </summary>\n    public class StreamAssert\n    {\n        private static StreamAssert singleton = new StreamAssert();\n\n        public static StreamAssert Singleton { get { return singleton; } }\n\n        /// <summary>\n        /// Creates a <see cref=\"MemoryStream\"/>, invokes <paramref name=\"codeThatWrites\"/> to write to it,\n        /// rewinds the stream to the beginning and invokes <paramref name=\"codeThatReadsAsync\"/>.\n        /// </summary>\n        /// <param name=\"codeThatWrites\">Code to write to the stream. It cannot be <c>null</c>.</param>\n        /// <param name=\"codeThatReadsAsync\">Code that reads from the stream. It cannot be <c>null</c>.</param>\n        public async Task WriteAndReadAsync(Func<MemoryStream, Task> codeThatWrites, Func<MemoryStream, Task> codeThatReadsAsync)\n        {\n            if (codeThatWrites == null)\n            {\n                throw new ArgumentNullException(\"codeThatWrites\");\n            }\n\n            if (codeThatReadsAsync == null)\n            {\n                throw new ArgumentNullException(\"codeThatReads\");\n            }\n\n            using (MemoryStream stream = new MemoryStream())\n            {\n                await codeThatWrites(stream);\n\n                stream.Flush();\n                stream.Seek(0L, SeekOrigin.Begin);\n\n                await codeThatReadsAsync(stream);\n            }\n        }\n\n        /// <summary>\n        /// Creates a <see cref=\"Stream\"/>, invokes <paramref name=\"codeThatWrites\"/> to write to it,\n        /// rewinds the stream to the beginning and invokes <paramref name=\"codeThatReads\"/> to obtain\n        /// the result to return from this method.\n        /// </summary>\n        /// <param name=\"codeThatWrites\">Code to write to the stream.  It cannot be <c>null</c>.</param>\n        /// <param name=\"codeThatReads\">Code that reads from the stream and returns the result.  It cannot be <c>null</c>.</param>\n        /// <returns>The value returned from <paramref name=\"codeThatReads\"/>.</returns>\n        public static object WriteAndReadResult(Action<Stream> codeThatWrites, Func<Stream, object> codeThatReads)\n        {\n            if (codeThatWrites == null)\n            {\n                throw new ArgumentNullException(\"codeThatWrites\");\n            }\n\n            if (codeThatReads == null)\n            {\n                throw new ArgumentNullException(\"codeThatReads\");\n            }\n\n            object result = null;\n            using (MemoryStream stream = new MemoryStream())\n            {\n                codeThatWrites(stream);\n\n                stream.Flush();\n                stream.Seek(0L, SeekOrigin.Begin);\n\n                result = codeThatReads(stream);\n            }\n\n            return result;\n        }\n\n        /// <summary>\n        /// Creates a <see cref=\"Stream\"/>, invokes <paramref name=\"codeThatWrites\"/> to write to it,\n        /// rewinds the stream to the beginning and invokes <paramref name=\"codeThatReads\"/> to obtain\n        /// the result to return from this method.\n        /// </summary>\n        /// <typeparam name=\"T\">The type of the result expected.</typeparam>\n        /// <param name=\"codeThatWrites\">Code to write to the stream.  It cannot be <c>null</c>.</param>\n        /// <param name=\"codeThatReads\">Code that reads from the stream and returns the result.  It cannot be <c>null</c>.</param>\n        /// <returns>The value returned from <paramref name=\"codeThatReads\"/>.</returns>\n        public T WriteAndReadResult<T>(Action<Stream> codeThatWrites, Func<Stream, object> codeThatReads)\n        {\n            return (T)WriteAndReadResult(codeThatWrites, codeThatReads);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/TaskAssert.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading.Tasks;\n\nnamespace Microsoft.TestCommon\n{\n    /// <summary>\n    /// MSTest assert class to make assertions about tests using <see cref=\"Task\"/>.\n    /// </summary>\n    public class TaskAssert\n    {\n        /// <summary>\n        /// Asserts the given task has been started.  TAP guidelines are that all\n        /// <see cref=\"Task\"/> objects returned from public API's have been started.\n        /// </summary>\n        /// <param name=\"task\">The <see cref=\"Task\"/> to test.</param>\n        public void IsStarted(Task task)\n        {\n            Assert.NotNull(task);\n            Assert.True(task.Status != TaskStatus.Created);\n        }\n\n        /// <summary>\n        /// Asserts the given task completes successfully.  This method will block the\n        /// current thread waiting for the task, but will timeout if it does not complete.\n        /// </summary>\n        /// <param name=\"task\">The <see cref=\"Task\"/> to test.</param>\n        public Task SucceedsAsync(Task task)\n        {\n            IsStarted(task);\n            return task;\n        }\n\n        /// <summary>\n        /// Asserts the given task completes successfully and returns a <typeparamref name=\"T\"/> result.\n        /// This method will block the current thread waiting for the task, but will timeout if it does not complete.\n        /// </summary>\n        /// <typeparam name=\"T\">The result of the <see cref=\"Task\"/>.</typeparam>\n        /// <param name=\"task\">The <see cref=\"Task\"/> to test.</param>\n        /// <returns>The result from that task.</returns>\n        public Task<T> SucceedsWithResultAsync<T>(Task<T> task)\n        {\n            IsStarted(task);\n            return task;\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/TestDataSetAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\n\nnamespace Microsoft.TestCommon\n{\n    public class TestDataSetAttribute : DataAttribute\n    {\n        public Type DeclaringType { get; set; }\n\n        public string PropertyName { get; set; }\n\n        public TestDataVariations TestDataVariations { get; set; }\n\n        private IEnumerable<Tuple<Type, string>> ExtraDataSets { get; set; }\n\n        public TestDataSetAttribute(Type declaringType, string propertyName, TestDataVariations testDataVariations = TestCommon.TestDataVariations.All)\n        {\n            DeclaringType = declaringType;\n            PropertyName = propertyName;\n            TestDataVariations = testDataVariations;\n            ExtraDataSets = new List<Tuple<Type, string>>();\n        }\n\n        public TestDataSetAttribute(Type declaringType, string propertyName,\n                                    Type declaringType1, string propertyName1,\n                                    TestDataVariations testDataVariations = TestCommon.TestDataVariations.All)\n            : this(declaringType, propertyName, testDataVariations)\n        {\n            ExtraDataSets = new List<Tuple<Type, string>> { Tuple.Create(declaringType1, propertyName1) };\n        }\n\n        public TestDataSetAttribute(Type declaringType, string propertyName,\n            Type declaringType1, string propertyName1,\n            Type declaringType2, string propertyName2,\n            TestDataVariations testDataVariations = TestCommon.TestDataVariations.All)\n            : this(declaringType, propertyName, testDataVariations)\n        {\n            ExtraDataSets = new List<Tuple<Type, string>> { Tuple.Create(declaringType1, propertyName1), Tuple.Create(declaringType2, propertyName2) };\n        }\n\n        public TestDataSetAttribute(Type declaringType, string propertyName,\n            Type declaringType1, string propertyName1,\n            Type declaringType2, string propertyName2,\n            Type declaringType3, string propertyName3,\n            TestDataVariations testDataVariations = TestCommon.TestDataVariations.All)\n            : this(declaringType, propertyName, testDataVariations)\n        {\n            ExtraDataSets = new List<Tuple<Type, string>> { Tuple.Create(declaringType1, propertyName1), Tuple.Create(declaringType2, propertyName2), Tuple.Create(declaringType3, propertyName3) };\n        }\n\n        public TestDataSetAttribute(Type declaringType, string propertyName,\n            Type declaringType1, string propertyName1,\n            Type declaringType2, string propertyName2,\n            Type declaringType3, string propertyName3,\n            Type declaringType4, string propertyName4,\n            TestDataVariations testDataVariations = TestCommon.TestDataVariations.All)\n            : this(declaringType, propertyName, testDataVariations)\n        {\n            ExtraDataSets = new List<Tuple<Type, string>>\n            {\n                Tuple.Create(declaringType1, propertyName1), Tuple.Create(declaringType2, propertyName2),\n                Tuple.Create(declaringType3, propertyName3), Tuple.Create(declaringType4, propertyName4)\n            };\n        }\n\n        public override IEnumerable<object[]> GetData(MethodInfo methodUnderTest, Type[] parameterTypes)\n        {\n            IEnumerable<object[]> baseDataSet = GetBaseDataSet(DeclaringType, PropertyName, TestDataVariations);\n            IEnumerable<IEnumerable<object[]>> extraDataSets = GetExtraDataSets();\n\n            IEnumerable<IEnumerable<object[]>> finalDataSets = (new[] { baseDataSet }).Concat(extraDataSets);\n\n            var datasets = CrossProduct(finalDataSets);\n\n            return datasets;\n        }\n\n        private static IEnumerable<object[]> CrossProduct(IEnumerable<IEnumerable<object[]>> datasets)\n        {\n            if (datasets.Count() == 1)\n            {\n                foreach (var dataset in datasets.First())\n                {\n                    yield return dataset;\n                }\n            }\n            else\n            {\n                IEnumerable<object[]> datasetLeft = datasets.First();\n                IEnumerable<object[]> datasetRight = CrossProduct(datasets.Skip(1));\n\n                foreach (var dataLeft in datasetLeft)\n                {\n                    foreach (var dataRight in datasetRight)\n                    {\n                        yield return dataLeft.Concat(dataRight).ToArray();\n                    }\n                }\n            }\n        }\n\n        // The base data set(first one) can either be a TestDataSet or a TestDataSetCollection\n        private static IEnumerable<object[]> GetBaseDataSet(Type declaringType, string propertyName, TestDataVariations variations)\n        {\n            return TryGetDataSetFromTestDataCollection(declaringType, propertyName, variations) ?? GetDataSet(declaringType, propertyName);\n        }\n\n        private IEnumerable<IEnumerable<object[]>> GetExtraDataSets()\n        {\n            foreach (var tuple in ExtraDataSets)\n            {\n                yield return GetDataSet(tuple.Item1, tuple.Item2);\n            }\n        }\n\n        private static object GetTestDataPropertyValue(Type declaringType, string propertyName)\n        {\n            PropertyInfo property = declaringType.GetProperty(propertyName, BindingFlags.Static | BindingFlags.Public);\n\n            if (property == null)\n            {\n                throw new ArgumentException(String.Format(\"Could not find public static property {0} on {1}\", propertyName, declaringType.FullName));\n            }\n            else\n            {\n                return property.GetValue(null, null);\n            }\n        }\n\n        private static IEnumerable<object[]> GetDataSet(Type declaringType, string propertyName)\n        {\n            object propertyValue = GetTestDataPropertyValue(declaringType, propertyName);\n\n            // box the dataset items if the property is not a RefTypeTestData\n            IEnumerable<object> value = (propertyValue as IEnumerable<object>) ?? (propertyValue as IEnumerable).Cast<object>();\n            if (value == null)\n            {\n                throw new InvalidOperationException(String.Format(\"{0}.{1} is either null or does not implement IEnumerable\", declaringType.FullName, propertyName));\n            }\n\n            IEnumerable<object[]> dataset = value as IEnumerable<object[]>;\n            if (dataset != null)\n            {\n                return dataset;\n            }\n            else\n            {\n                return value.Select((data) => new object[] { data });\n            }\n        }\n\n        private static IEnumerable<object[]> TryGetDataSetFromTestDataCollection(Type declaringType, string propertyName, TestDataVariations variations)\n        {\n            object propertyValue = GetTestDataPropertyValue(declaringType, propertyName);\n\n            IEnumerable<TestData> testDataCollection = propertyValue as IEnumerable<TestData>;\n\n            return testDataCollection == null ? null : GetDataSetFromTestDataCollection(testDataCollection, variations);\n        }\n\n        private static IEnumerable<object[]> GetDataSetFromTestDataCollection(IEnumerable<TestData> testDataCollection, TestDataVariations variations)\n        {\n            foreach (TestData testdataInstance in testDataCollection)\n            {\n                foreach (TestDataVariations variation in testdataInstance.GetSupportedTestDataVariations())\n                {\n                    if ((variation & variations) == variation)\n                    {\n                        Type variationType = testdataInstance.GetAsTypeOrNull(variation);\n                        object testData = testdataInstance.GetAsTestDataOrNull(variation);\n                        if (AsSingleInstances(variation))\n                        {\n                            foreach (object obj in (IEnumerable)testData)\n                            {\n                                yield return new object[] { variationType, obj };\n                            }\n                        }\n                        else\n                        {\n                            yield return new object[] { variationType, testData };\n                        }\n                    }\n                }\n            }\n        }\n\n        private static bool AsSingleInstances(TestDataVariations variation)\n        {\n            return variation == TestDataVariations.AsInstance ||\n                   variation == TestDataVariations.AsNullable ||\n                   variation == TestDataVariations.AsDerivedType ||\n                   variation == TestDataVariations.AsKnownType ||\n                   variation == TestDataVariations.AsDataMember ||\n                   variation == TestDataVariations.AsClassMember ||\n                   variation == TestDataVariations.AsXmlElementProperty;\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/TimeoutConstant.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.TestCommon\n{\n    /// <summary>\n    /// MSTest timeout constants for use with the <see cref=\"Microsoft.VisualStudio.TestTools.UnitTesting.TimeoutAttribute\"/>.\n    /// </summary>\n    public class TimeoutConstant\n    {\n        private const int seconds = 1000;\n\n        /// <summary>\n        /// The default timeout for test methods.\n        /// </summary>\n        public const int DefaultTimeout = 30 * seconds;\n\n        /// <summary>\n        /// An extended timeout for longer running test methods.\n        /// </summary>\n        public const int ExtendedTimeout = 240 * seconds;\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/TypeAssert.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\n\nnamespace Microsoft.TestCommon\n{\n    /// <summary>\n    /// MSTest utility for testing that a given type has the expected properties such as being public, sealed, etc.\n    /// </summary>\n    public class TypeAssert\n    {\n        /// <summary>\n        /// Specifies a set of type properties to test for using the <see cref=\"CheckProperty\"/> method.\n        /// This enumeration has a <see cref=\"FlagsAttribute\"/> attribute that allows a bitwise combination of its member values.\n        /// </summary>\n        [Flags]\n        public enum TypeProperties\n        {\n            /// <summary>\n            /// Indicates that the type must be abstract.\n            /// </summary>\n            IsAbstract = 0x1,\n\n            /// <summary>\n            /// Indicates that the type must be a class.\n            /// </summary>\n            IsClass = 0x2,\n\n            /// <summary>\n            /// Indicates that the type must be a COM object.\n            /// </summary>\n            IsComObject = 0x4,\n\n            /// <summary>\n            /// Indicates that the type must be disposable.\n            /// </summary>\n            IsDisposable = 0x8,\n\n            /// <summary>\n            /// Indicates that the type must be an enum.\n            /// </summary>\n            IsEnum = 0x10,\n\n            /// <summary>\n            /// Indicates that the type must be a generic type.\n            /// </summary>\n            IsGenericType = 0x20,\n\n            /// <summary>\n            /// Indicates that the type must be a generic type definition.\n            /// </summary>\n            IsGenericTypeDefinition = 0x40,\n\n            /// <summary>\n            /// Indicates that the type must be an interface.\n            /// </summary>\n            IsInterface = 0x80,\n\n            /// <summary>\n            /// Indicates that the type must be nested and declared private.\n            /// </summary>\n            IsNestedPrivate = 0x100,\n\n            /// <summary>\n            /// Indicates that the type must be nested and declared public.\n            /// </summary>\n            IsNestedPublic = 0x200,\n\n            /// <summary>\n            /// Indicates that the type must be public.\n            /// </summary>\n            IsPublic = 0x400,\n\n            /// <summary>\n            /// Indicates that the type must be sealed.\n            /// </summary>\n            IsSealed = 0x800,\n\n            /// <summary>\n            /// Indicates that the type must be visible outside the assembly.\n            /// </summary>\n            IsVisible = 0x1000,\n\n            /// <summary>\n            /// Indicates that the type must be static.\n            /// </summary>\n            IsStatic = TypeAssert.TypeProperties.IsAbstract | TypeAssert.TypeProperties.IsSealed,\n\n            /// <summary>\n            /// Indicates that the type must be a public, visible class.\n            /// </summary>\n            IsPublicVisibleClass = TypeAssert.TypeProperties.IsClass | TypeAssert.TypeProperties.IsPublic | TypeAssert.TypeProperties.IsVisible\n        }\n\n        private static void CheckProperty(Type type, bool expected, bool actual, string property)\n        {\n            Assert.NotNull(type);\n            Assert.True(expected == actual, String.Format(\"Type '{0}' should{1} be {2}.\", type.FullName, expected ? \"\" : \" NOT\", property));\n        }\n\n        /// <summary>\n        /// Determines whether the specified type has a given set of properties such as being public, sealed, etc.\n        /// The method asserts if one or more of the properties are not satisfied.\n        /// </summary>\n        /// <typeparam name=\"T\">The type to test for properties.</typeparam>\n        /// <param name=\"typeProperties\">The set of type properties to test for.</param>\n        public void HasProperties<T>(TypeProperties typeProperties)\n        {\n            HasProperties(typeof(T), typeProperties);\n        }\n\n        /// <summary>\n        /// Determines whether the specified type has a given set of properties such as being public, sealed, etc.\n        /// The method asserts if one or more of the properties are not satisfied.\n        /// </summary>\n        /// <typeparam name=\"T\">The type to test for properties.</typeparam>\n        /// <typeparam name=\"TIsAssignableFrom\">Verify that the type to test is assignable from this type.</typeparam>\n        /// <param name=\"typeProperties\">The set of type properties to test for.</param>\n        public void HasProperties<T, TIsAssignableFrom>(TypeProperties typeProperties)\n        {\n            HasProperties(typeof(T), typeProperties, typeof(TIsAssignableFrom));\n        }\n\n        /// <summary>\n        /// Determines whether the specified type has a given set of properties such as being public, sealed, etc.\n        /// The method asserts if one or more of the properties are not satisfied.\n        /// </summary>\n        /// <param name=\"type\">The type to test for properties.</param>\n        /// <param name=\"typeProperties\">The set of type properties to test for.</param>\n        public void HasProperties(Type type, TypeProperties typeProperties)\n        {\n            HasProperties(type, typeProperties, null);\n        }\n\n        /// <summary>\n        /// Determines whether the specified type has a given set of properties such as being public, sealed, etc.\n        /// The method asserts if one or more of the properties are not satisfied.\n        /// </summary>\n        /// <param name=\"type\">The type to test for properties.</param>\n        /// <param name=\"typeProperties\">The set of type properties to test for.</param>\n        /// <param name=\"isAssignableFrom\">Verify that the type to test is assignable from this type.</param>\n        public void HasProperties(Type type, TypeProperties typeProperties, Type isAssignableFrom)\n        {\n            TypeAssert.CheckProperty(type, (typeProperties & TypeProperties.IsAbstract) > 0, type.IsAbstract, \"abstract\");\n            TypeAssert.CheckProperty(type, (typeProperties & TypeProperties.IsClass) > 0, type.IsClass, \"a class\");\n            TypeAssert.CheckProperty(type, (typeProperties & TypeProperties.IsComObject) > 0, type.IsCOMObject, \"a COM object\");\n            TypeAssert.CheckProperty(type, (typeProperties & TypeProperties.IsDisposable) > 0, typeof(IDisposable).IsAssignableFrom(type), \"disposable\");\n            TypeAssert.CheckProperty(type, (typeProperties & TypeProperties.IsEnum) > 0, type.IsEnum, \"an enum\");\n            TypeAssert.CheckProperty(type, (typeProperties & TypeProperties.IsGenericType) > 0, type.IsGenericType, \"a generic type\");\n            TypeAssert.CheckProperty(type, (typeProperties & TypeProperties.IsGenericTypeDefinition) > 0, type.IsGenericTypeDefinition, \"a generic type definition\");\n            TypeAssert.CheckProperty(type, (typeProperties & TypeProperties.IsInterface) > 0, type.IsInterface, \"an interface\");\n            TypeAssert.CheckProperty(type, (typeProperties & TypeProperties.IsNestedPrivate) > 0, type.IsNestedPrivate, \"nested private\");\n            TypeAssert.CheckProperty(type, (typeProperties & TypeProperties.IsNestedPublic) > 0, type.IsNestedPublic, \"nested public\");\n            TypeAssert.CheckProperty(type, (typeProperties & TypeProperties.IsPublic) > 0, type.IsPublic, \"public\");\n            TypeAssert.CheckProperty(type, (typeProperties & TypeProperties.IsSealed) > 0, type.IsSealed, \"sealed\");\n            TypeAssert.CheckProperty(type, (typeProperties & TypeProperties.IsVisible) > 0, type.IsVisible, \"visible\");\n            if (isAssignableFrom != null)\n            {\n                TypeAssert.CheckProperty(type, true, isAssignableFrom.IsAssignableFrom(type), String.Format(\"assignable from {0}\", isAssignableFrom.FullName));\n            }\n        }\n    }\n}"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/Types/ByteEnum.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.TestCommon.Types\n{\n    public enum ByteEnum : byte\n    {\n        FirstByte,\n        SecondByte,\n        ThirdByte\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/Types/FlagsEnum.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\n\nnamespace Microsoft.TestCommon.Types\n{\n    [Flags]\n    public enum FlagsEnum\n    {\n        One = 0x1,\n        Two = 0x2,\n        Four = 0x4\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/Types/INameAndIdContainer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.TestCommon.Types\n{\n    /// <summary>\n    /// Tagging interface to assist comparing instances of these types.\n    /// </summary>\n    public interface INameAndIdContainer\n    {\n        string Name { get; set; }\n\n        int Id { get; set; }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/Types/ISerializableType.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Runtime.Serialization;\n\nnamespace Microsoft.TestCommon.Types\n{\n    [Serializable]\n    public class ISerializableType : ISerializable, INameAndIdContainer\n    {\n        private int id;\n        private string name;\n\n        public ISerializableType()\n        {\n        }\n\n        public ISerializableType(int id, string name)\n        {\n            this.id = id;\n            this.name = name;\n        }\n\n        public ISerializableType(SerializationInfo information, StreamingContext context)\n        {\n            this.id = information.GetInt32(\"Id\");\n            this.name = information.GetString(\"Name\");\n        }\n\n        public int Id\n        {\n            get\n            {\n                return this.id;\n            }\n\n            set\n            {\n                this.IdSet = true;\n                this.id = value;\n            }\n        }\n\n        public string Name\n        {\n            get\n            {\n                return this.name;\n            }\n\n            set\n            {\n                this.NameSet = true;\n                this.name = value;\n            }\n\n        }\n\n        public bool IdSet { get; private set; }\n\n        public bool NameSet { get; private set; }\n\n        public void GetObjectData(SerializationInfo info, StreamingContext context)\n        {\n            info.AddValue(\"Id\", this.Id);\n            info.AddValue(\"Name\", this.Name);\n        }\n\n        public static IEnumerable<ISerializableType> GetTestData()\n        {\n            return new ISerializableType[] { new ISerializableType(), new ISerializableType(1, \"SomeName\") };\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/Types/LongEnum.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.TestCommon.Types\n{\n    public enum LongEnum : long\n    {\n        FirstLong,\n        SecondLong,\n        ThirdLong,\n        FourthLong\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/Types/SByteEnum.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.TestCommon.Types\n{\n    public enum SByteEnum : sbyte\n    {\n        FirstSByte,\n        SecondSByte,\n        ThirdSByte\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/Types/ShortEnum.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.TestCommon.Types\n{\n    public enum ShortEnum : short\n    {\n        FirstShort,\n        SecondShort,\n        ThirdShort\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/Types/SimpleEnum.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.TestCommon.Types\n{\n    public enum SimpleEnum\n    {\n        First,\n        Second,\n        Third,\n        Fourth\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/Types/UIntEnum.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.TestCommon.Types\n{\n    public enum UIntEnum : uint\n    {\n        FirstUInt,\n        SecondUInt,\n        ThirdUInt\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/Types/UShortEnum.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace Microsoft.TestCommon.Types\n{\n    public enum UShortEnum : ushort\n    {\n        FirstUShort,\n        SecondUShort,\n        ThirdUShort\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft/TestCommon/XmlAssert.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Xml.Linq;\n\nnamespace Microsoft.TestCommon\n{\n    /// <summary>\n    /// Assert class that compares two XML strings for equality. Namespaces are ignored during comparison\n    /// </summary>\n    public class XmlAssert\n    {\n        public void Equal(string expected, string actual, params RegexReplacement[] regexReplacements)\n        {\n            if (regexReplacements != null)\n            {\n                for (int i = 0; i < regexReplacements.Length; i++)\n                {\n                    actual = regexReplacements[i].Regex.Replace(actual, regexReplacements[i].Replacement);\n                }\n            }\n\n            Equal(XElement.Parse(expected), XElement.Parse(actual));\n        }\n\n        public void Equal(XElement expected, XElement actual)\n        {\n            Assert.Equal(Normalize(expected).ToString(), Normalize(actual).ToString());\n        }\n\n        private static XElement Normalize(XElement element)\n        {\n            if (element.HasElements)\n            {\n                return new XElement(\n                    Encode(element.Name),\n                    Normalize(element.Attributes()),\n                    Normalize(element.Elements()));\n            }\n\n            if (element.IsEmpty)\n            {\n                return new XElement(\n                    Encode(element.Name),\n                    Normalize(element.Attributes()));\n            }\n            else\n            {\n                return new XElement(\n                    Encode(element.Name),\n                    Normalize(element.Attributes()),\n                    element.Value);\n            }\n        }\n\n        private static IEnumerable<XAttribute> Normalize(IEnumerable<XAttribute> attributes)\n        {\n            return attributes\n                    .Where((attrib) => !attrib.IsNamespaceDeclaration)\n                    .Select((attrib) => new XAttribute(Encode(attrib.Name), attrib.Value))\n                    .OrderBy(a => a.Name.ToString());\n        }\n\n        private static IEnumerable<XElement> Normalize(IEnumerable<XElement> elements)\n        {\n            return elements\n                    .Select(e => Normalize(e))\n                    .OrderBy(a => a.ToString());\n        }\n\n        private static string Encode(XName name)\n        {\n            return string.Format(\"{0}_{1}\", HttpUtility.UrlEncode(name.NamespaceName).Replace('%', '_'), name.LocalName);\n        }\n    }\n}"
  },
  {
    "path": "test/Microsoft.TestCommon/Microsoft.TestCommon.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <TargetFrameworks>net462;netcoreapp2.1;net8.0</TargetFrameworks>\n    <Configurations>$(Configurations);CodeAnalysis</Configurations>\n    <DefineConstants\n        Condition=\" '$(Testing_NetStandard1_3)' == 'true' \">$(DefineConstants);Testing_NetStandard1_3</DefineConstants>\n    <GenerateAssemblyInfo>false</GenerateAssemblyInfo>\n    <OutputPath>..\\..\\bin\\$(Configuration)\\Test\\</OutputPath>\n    <OutputPath\n        Condition=\" '$(Testing_NetStandard1_3)' == 'true' \">$(OutputPath)ns1_3\\</OutputPath>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <None Include=\"xunit.runner.json\" CopyToOutputDirectory=\"PreserveNewest\" />\n\n    <!-- ns1_3 project brings in System.Net.Http from .NET Standard but doesn't expose that to us here. -->\n    <PackageReference Include=\"System.Net.Http\" Version=\"4.3.4\"\n        Condition=\" '$(TargetFrameworkIdentifier)' == '.NETFramework' AND '$(Testing_NetStandard1_3)' == 'true' \" />\n    <Reference Include=\"System.Net.Http\"\n        Condition=\" '$(TargetFrameworkIdentifier)' == '.NETFramework' AND '$(Testing_NetStandard1_3)' != 'true' \" />\n\n    <Reference Include=\"System.Web\"\n        Condition=\" '$(TargetFrameworkIdentifier)' == '.NETFramework' \" />\n\n    <PackageReference Include=\"Moq\" Version=\"4.18.4\" />\n    <PackageReference Include=\"xunit.abstractions\" Version=\"2.0.3\" />\n    <PackageReference Include=\"xunit.assert\" Version=\"2.4.2\" />\n    <PackageReference Include=\"xunit.extensibility.core\" Version=\"2.4.2\" />\n    <PackageReference Include=\"xunit.extensibility.execution\" Version=\"2.4.2\" />\n\n    <Compile Remove=\"AppDomainUtils.cs;Microsoft\\TestCommon\\RuntimeEnvironment.cs;WebUtils.cs\"\n        Condition=\" '$(TargetFrameworkIdentifier)' != '.NETFramework' \" />\n\n    <!-- To access Error.InvalidEnumArgumentException in this special case. -->\n    <ProjectReference Include=\"..\\..\\src\\System.Net.Http.Formatting.ns1_3\\System.Net.Http.Formatting.ns1_3.csproj\"\n        Condition=\" '$(Testing_NetStandard1_3)' == 'true' \" />\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "test/Microsoft.TestCommon/Platform.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\n\nnamespace Microsoft.TestCommon\n{\n    /// <summary>\n    /// An enumeration of known platforms that the unit test might be running under.\n    /// </summary>\n    [Flags]\n    public enum Platform\n    {\n        /// <summary>\n        /// A special value used to indicate that the test is valid on all known platforms.\n        /// </summary>\n        All = 0xFFFFFF,\n\n        /// <summary>\n        /// Indicates that the test wants to run on .NET 4 (when used with\n        /// <see cref=\"FactAttribute.Platforms\"/> and/or <see cref=\"TheoryAttribute.Platforms\"/>),\n        /// or that the current platform that the test is running on is .NET 4 (when used with the\n        /// <see cref=\"PlatformInfo.Platform\"/>, <see cref=\"FactDiscoverer.Platform\"/>, and/or\n        /// <see cref=\"TheoryDiscoverer.Platform\"/>).\n        /// </summary>\n        Net40 = 0x01,\n\n        /// <summary>\n        /// Indicates that the test wants to run on .NET 4.5 (when used with\n        /// <see cref=\"FactAttribute.Platforms\"/> and/or <see cref=\"TheoryAttribute.Platforms\"/>),\n        /// or that the current platform that the test is running on is .NET 4.5 (when used with the\n        /// <see cref=\"PlatformInfo.Platform\"/>, <see cref=\"FactDiscoverer.Platform\"/>, and/or\n        /// <see cref=\"TheoryDiscoverer.Platform\"/>).\n        /// </summary>\n        Net45 = 0x02,\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/PlatformInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\n\nnamespace Microsoft.TestCommon\n{\n    /// <summary>\n    /// Used to retrieve the currently running platform.\n    /// </summary>\n    public static class PlatformInfo\n    {\n        private const string _net45TypeName = \"System.IWellKnownStringEqualityComparer, mscorlib, Version=4.0.0.0, PublicKeyToken=b77a5c561934e089\";\n        private const string _netCore20TypeName = \"System.OrdinalCaseSensitiveComparer, system.private.corelib, Version=4.0.0.0, PublicKeyToken=7cec85d7bea7798e\";\n        private static Lazy<Platform> _platform = new Lazy<Platform>(GetPlatform, isThreadSafe: true);\n\n        /// <summary>\n        /// Gets the platform that the unit test is currently running on.\n        /// </summary>\n        public static Platform Platform\n        {\n            get { return _platform.Value; }\n        }\n\n        private static Platform GetPlatform()\n        {\n            if (Type.GetType(_netCore20TypeName, throwOnError: false) != null)\n            {\n                // Treat .NET Core 2.1 as a .NET 4.5 superset though internal types are different.\n                return Platform.Net45;\n            }\n\n            if (Type.GetType(_net45TypeName, throwOnError: false) != null)\n            {\n                return Platform.Net45;\n            }\n\n            return Platform.Net40;\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/PortReserver.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.Linq;\nusing System.Net;\nusing System.Net.NetworkInformation;\nusing System.Threading;\n\nnamespace Microsoft.TestCommon\n{\n    [Xunit.CollectionDefinition(\"PortReserver Collection\", DisableParallelization = true)]\n    public class PortReserverCollection\n    {\n    }\n\n    /// <summary>\n    /// This class allocates ports while ensuring that:\n    /// 1. Ports that are permanently taken (or taken for the duration of the test) are not being attempted to be used.\n    /// 2. Ports are not shared across different tests (but you can allocate two different ports in the same test).\n    ///\n    /// Gotcha: If another application grabs a port during the test, we have a race condition.\n    /// </summary>\n    [DebuggerDisplay(\"Port: {PortNumber}, Port count for this app domain: {_appDomainOwnedPorts.Count}\")]\n    public class PortReserver : IDisposable\n    {\n        private Mutex _portMutex;\n        private Thread _acquiredOn;\n\n        // We use this list to hold on to all the ports used because the Mutex will be blown through on the same thread.\n        // Theoretically we can do a thread local HashSet, but that makes dispose thread-dependent, or requires more complicated concurrency checks.\n        // Since practically there is no perf issue or concern here, this keeps the code the simplest possible.\n        private static HashSet<int> _appDomainOwnedPorts = new HashSet<int>();\n\n        public int PortNumber\n        {\n            get;\n            private set;\n        }\n\n        public PortReserver(int basePort = 50231)\n        {\n            if (basePort <= 0)\n            {\n                throw new ArgumentOutOfRangeException(\"basePort\", \"Argument must be greater than 0.\");\n            }\n\n            // Grab a cross appdomain/cross process/cross thread lock, to ensure only one port is reserved at a time.\n            using (Mutex mutex = GetGlobalMutex())\n            {\n                try\n                {\n                    var usedTCPPorts = new HashSet<int>();\n                    foreach (var endPoint in ListUsedTCPPort())\n                    {\n                        usedTCPPorts.Add(endPoint.Port);\n                    }\n\n                    int port = basePort - 1;\n                    while (true)\n                    {\n                        port++;\n\n                        if (port > 65535)\n                        {\n                            throw new InvalidOperationException(\"Exceeded port range\");\n                        }\n\n                        // AppDomainOwnedPorts check enables reserving two ports from the same thread in sequence.\n                        // ListUsedTCPPort prevents port contention with other apps.\n                        if (_appDomainOwnedPorts.Contains(port) || usedTCPPorts.Contains(port))\n                        {\n                            continue;\n                        }\n\n                        // Create a well known mutex\n                        string mutexName = \"WebStack-Port-\" + port.ToString(CultureInfo.InvariantCulture);\n                        _portMutex = new Mutex(initiallyOwned: false, name: mutexName);\n\n                        // If no one else is using this port grab it.\n                        if (_portMutex.WaitOne(millisecondsTimeout: 0))\n                        {\n                            _acquiredOn = Thread.CurrentThread;\n                            break;\n                        }\n\n                        // dispose this mutex since the port it represents is not available.\n                        _portMutex.Dispose();\n                        _portMutex = null;\n                    }\n\n                    PortNumber = port;\n                    _appDomainOwnedPorts.Add(port);\n                }\n                finally\n                {\n                    mutex.ReleaseMutex();\n                }\n            }\n        }\n\n        public string BaseUri\n        {\n            get\n            {\n                return String.Format(CultureInfo.InvariantCulture, \"http://localhost:{0}/\", PortNumber);\n            }\n        }\n\n        public void Dispose()\n        {\n            if (PortNumber == -1)\n            {\n                // Object already disposed\n                return;\n            }\n\n            using (Mutex mutex = GetGlobalMutex())\n            {\n                try\n                {\n                    using (_portMutex)\n                    {\n                        if (_acquiredOn == Thread.CurrentThread)\n                        {\n                            _portMutex.ReleaseMutex();\n                        }\n\n                        _portMutex = null;\n                    }\n\n                    _appDomainOwnedPorts.Remove(PortNumber);\n                    PortNumber = -1;\n                }\n                finally\n                {\n                    mutex.ReleaseMutex();\n                }\n            }\n        }\n\n        private static Mutex GetGlobalMutex()\n        {\n            const int timeoutInSeconds = 20;\n\n            Mutex mutex = new Mutex(initiallyOwned: false, name: \"WebStack-RandomPortAcquisition\");\n            if (!mutex.WaitOne(TimeSpan.FromSeconds(timeoutInSeconds)))\n            {\n                throw new InvalidOperationException(\n                    String.Format(\"Unable to reserve global Mutex within {0} seconds.\", timeoutInSeconds));\n            }\n\n            return mutex;\n        }\n\n        private static IPEndPoint[] ListUsedTCPPort()\n        {\n            IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();\n\n            return ipGlobalProperties.GetActiveTcpListeners()\n                .Concat(ipGlobalProperties.GetActiveUdpListeners())\n                .ToArray();\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/PreAppStartTestHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Reflection;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.TestUtils\n{\n    public static class PreAppStartTestHelper\n    {\n        public static void TestPreAppStartClass(Type preAppStartType)\n        {\n            string typeMessage = String.Format(\"The type '{0}' must be static, public, and named 'PreApplicationStartCode'.\", preAppStartType.FullName);\n            Assert.True(preAppStartType.IsSealed && preAppStartType.IsAbstract && preAppStartType.IsPublic && preAppStartType.Name == \"PreApplicationStartCode\", typeMessage);\n\n            string editorBrowsableMessage = String.Format(\"The only attribute on type '{0}' must be [EditorBrowsable(EditorBrowsableState.Never)].\", preAppStartType.FullName);\n            object[] attrs = preAppStartType.GetCustomAttributes(typeof(EditorBrowsableAttribute), true);\n            Assert.True(attrs.Length == 1 && ((EditorBrowsableAttribute)attrs[0]).State == EditorBrowsableState.Never, editorBrowsableMessage);\n\n            string startMethodMessage = String.Format(\"The only public member on type '{0}' must be a method called Start().\", preAppStartType.FullName);\n            MemberInfo[] publicMembers = preAppStartType.GetMembers(BindingFlags.Public | BindingFlags.Static);\n            Assert.True(publicMembers.Length == 1, startMethodMessage);\n            Assert.True(publicMembers[0].MemberType == MemberTypes.Method, startMethodMessage);\n            Assert.True(publicMembers[0].Name == \"Start\", startMethodMessage);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/PreserveSyncContextAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\n\nnamespace Microsoft.TestCommon\n{\n    /// <summary>\n    /// Preserves the current <see cref=\"SynchronizationContext\"/>. Use this attribute on\n    /// tests which modify the current <see cref=\"SynchronizationContext\"/>.\n    /// </summary>\n    public class PreserveSyncContextAttribute : Xunit.Sdk.BeforeAfterTestAttribute\n    {\n        private SynchronizationContext _syncContext;\n\n        public override void Before(System.Reflection.MethodInfo methodUnderTest)\n        {\n            _syncContext = SynchronizationContext.Current;\n        }\n\n        public override void After(System.Reflection.MethodInfo methodUnderTest)\n        {\n            SynchronizationContext.SetSynchronizationContext(_syncContext);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/PropertyDataAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Reflection;\nusing Xunit;\nusing Xunit.Sdk;\n\nnamespace Microsoft.TestCommon\n{\n    // Xunit.MemberDataAttribute is unfortunately sealed. Duplicate its code here since method we need is protected.\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]\n    [DataDiscoverer(\"Xunit.Sdk.MemberDataDiscoverer\", \"xunit.core\")]\n    public class PropertyDataAttribute : MemberDataAttributeBase\n    {\n        public PropertyDataAttribute(string propertyName, params object[] parameters)\n            : base(propertyName, parameters)\n        {\n        }\n\n        public Type PropertyType\n        {\n            get\n            {\n                return MemberType;\n            }\n            set\n            {\n                MemberType = value;\n            }\n        }\n\n        protected override object[] ConvertDataItem(MethodInfo testMethod, object item)\n        {\n            if (item == null)\n            {\n                return null;\n            }\n\n            var array = item as object[];\n            if (array == null)\n            {\n                throw new ArgumentException(String.Format(\n                    \"Property {0} on {1} yielded an item that is not an object[].\",\n                    MemberName,\n                    MemberType ?? testMethod.DeclaringType));\n            }\n\n            return array;\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/ReflectionAssert.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Linq.Expressions;\nusing System.Reflection;\n\nnamespace Microsoft.TestCommon\n{\n    public class ReflectionAssert\n    {\n        private static PropertyInfo GetPropertyInfo<T, TProp>(Expression<Func<T, TProp>> property)\n        {\n            if (property.Body is MemberExpression)\n            {\n                return (PropertyInfo)((MemberExpression)property.Body).Member;\n            }\n            else if (property.Body is UnaryExpression && property.Body.NodeType == ExpressionType.Convert)\n            {\n                return (PropertyInfo)((MemberExpression)((UnaryExpression)property.Body).Operand).Member;\n            }\n            else\n            {\n                throw new InvalidOperationException(\"Could not determine property from lambda expression.\");\n            }\n        }\n\n        private static void TestPropertyValue<TInstance, TValue>(TInstance instance, Func<TInstance, TValue> getFunc, Action<TInstance, TValue> setFunc, TValue valueToSet, TValue valueToCheck)\n        {\n            setFunc(instance, valueToSet);\n            TValue newValue = getFunc(instance);\n            Assert.Equal(valueToCheck, newValue);\n        }\n\n        private static void TestPropertyValue<TInstance, TValue>(TInstance instance, Func<TInstance, TValue> getFunc, Action<TInstance, TValue> setFunc, TValue value)\n        {\n            TestPropertyValue(instance, getFunc, setFunc, value, value);\n        }\n\n        public void Property<T, TResult>(T instance, Expression<Func<T, TResult>> propertyGetter, TResult expectedDefaultValue, bool allowNull = false, TResult roundTripTestValue = null) where TResult : class\n        {\n            PropertyInfo property = GetPropertyInfo(propertyGetter);\n            Func<T, TResult> getFunc = (obj) => (TResult)property.GetValue(obj, index: null);\n            Action<T, TResult> setFunc = (obj, value) => property.SetValue(obj, value, index: null);\n\n            Assert.Equal(expectedDefaultValue, getFunc(instance));\n\n            if (allowNull)\n            {\n                TestPropertyValue(instance, getFunc, setFunc, null);\n            }\n            else\n            {\n                Assert.ThrowsArgumentNull(() =>\n                {\n                    setFunc(instance, null);\n                }, \"value\");\n            }\n\n            if (roundTripTestValue != null)\n            {\n                TestPropertyValue(instance, getFunc, setFunc, roundTripTestValue);\n            }\n        }\n\n        public void IntegerProperty<T, TResult>(T instance, Expression<Func<T, TResult>> propertyGetter, TResult expectedDefaultValue,\n            TResult? minLegalValue, TResult? illegalLowerValue,\n            TResult? maxLegalValue, TResult? illegalUpperValue,\n            TResult roundTripTestValue) where TResult : struct\n        {\n            PropertyInfo property = GetPropertyInfo(propertyGetter);\n            Func<T, TResult> getFunc = (obj) => (TResult)property.GetValue(obj, index: null);\n            Action<T, TResult> setFunc = (obj, value) => property.SetValue(obj, value, index: null);\n\n            Assert.Equal(expectedDefaultValue, getFunc(instance));\n\n            if (minLegalValue.HasValue)\n            {\n                TestPropertyValue(instance, getFunc, setFunc, minLegalValue.Value);\n            }\n\n            if (maxLegalValue.HasValue)\n            {\n                TestPropertyValue(instance, getFunc, setFunc, maxLegalValue.Value);\n            }\n\n            if (illegalLowerValue.HasValue)\n            {\n                Assert.ThrowsArgumentGreaterThanOrEqualTo(() => { setFunc(instance, illegalLowerValue.Value); }, \"value\", minLegalValue.Value.ToString(), illegalLowerValue.Value);\n            }\n\n            if (illegalUpperValue.HasValue)\n            {\n                Assert.ThrowsArgumentLessThanOrEqualTo(() => { setFunc(instance, illegalLowerValue.Value); }, \"value\", maxLegalValue.Value.ToString(), illegalUpperValue.Value);\n            }\n\n            TestPropertyValue(instance, getFunc, setFunc, roundTripTestValue);\n        }\n\n        public void NullableIntegerProperty<T, TResult>(T instance, Expression<Func<T, TResult?>> propertyGetter, TResult? expectedDefaultValue,\n            TResult? minLegalValue, TResult? illegalLowerValue,\n            TResult? maxLegalValue, TResult? illegalUpperValue,\n            TResult roundTripTestValue) where TResult : struct\n        {\n            PropertyInfo property = GetPropertyInfo(propertyGetter);\n            Func<T, TResult?> getFunc = (obj) => (TResult?)property.GetValue(obj, index: null);\n            Action<T, TResult?> setFunc = (obj, value) => property.SetValue(obj, value, index: null);\n\n            Assert.Equal(expectedDefaultValue, getFunc(instance));\n\n            TestPropertyValue(instance, getFunc, setFunc, null);\n\n            if (minLegalValue.HasValue)\n            {\n                TestPropertyValue(instance, getFunc, setFunc, minLegalValue.Value);\n            }\n\n            if (maxLegalValue.HasValue)\n            {\n                TestPropertyValue(instance, getFunc, setFunc, maxLegalValue.Value);\n            }\n\n            if (illegalLowerValue.HasValue)\n            {\n                Assert.ThrowsArgumentGreaterThanOrEqualTo(() => { setFunc(instance, illegalLowerValue.Value); }, \"value\", minLegalValue.Value.ToString(), illegalLowerValue.Value);\n            }\n\n            if (illegalUpperValue.HasValue)\n            {\n                Assert.ThrowsArgumentLessThanOrEqualTo(() => { setFunc(instance, illegalLowerValue.Value); }, \"value\", maxLegalValue.Value.ToString(), illegalUpperValue.Value);\n            }\n\n            TestPropertyValue(instance, getFunc, setFunc, roundTripTestValue);\n        }\n\n        public void BooleanProperty<T>(T instance, Expression<Func<T, bool>> propertyGetter, bool expectedDefaultValue)\n        {\n            PropertyInfo property = GetPropertyInfo(propertyGetter);\n            Func<T, bool> getFunc = (obj) => (bool)property.GetValue(obj, index: null);\n            Action<T, bool> setFunc = (obj, value) => property.SetValue(obj, value, index: null);\n\n            Assert.Equal(expectedDefaultValue, getFunc(instance));\n\n            TestPropertyValue(instance, getFunc, setFunc, !expectedDefaultValue);\n        }\n\n        public void EnumProperty<T, TResult>(T instance, Expression<Func<T, TResult>> propertyGetter, TResult expectedDefaultValue, TResult illegalValue, TResult roundTripTestValue) where TResult : struct\n        {\n            PropertyInfo property = GetPropertyInfo(propertyGetter);\n            Func<T, TResult> getFunc = (obj) => (TResult)property.GetValue(obj, index: null);\n            Action<T, TResult> setFunc = (obj, value) => property.SetValue(obj, value, index: null);\n\n            Assert.Equal(expectedDefaultValue, getFunc(instance));\n\n            Assert.ThrowsInvalidEnumArgument(() => { setFunc(instance, illegalValue); }, \"value\", Convert.ToInt32(illegalValue), typeof(TResult));\n\n            TestPropertyValue(instance, getFunc, setFunc, roundTripTestValue);\n        }\n\n        public void EnumPropertyWithoutIllegalValueCheck<T, TResult>(T instance, Expression<Func<T, TResult>> propertyGetter, TResult expectedDefaultValue, TResult roundTripTestValue) where TResult : struct\n        {\n            PropertyInfo property = GetPropertyInfo(propertyGetter);\n            Func<T, TResult> getFunc = (obj) => (TResult)property.GetValue(obj, index: null);\n            Action<T, TResult> setFunc = (obj, value) => property.SetValue(obj, value, index: null);\n\n            Assert.Equal(expectedDefaultValue, getFunc(instance));\n\n            TestPropertyValue(instance, getFunc, setFunc, roundTripTestValue);\n        }\n\n        public void StringProperty<T>(T instance, Expression<Func<T, string>> propertyGetter, string expectedDefaultValue,\n                                      bool allowNullAndEmpty = true, bool treatNullAsEmpty = true)\n        {\n            PropertyInfo property = GetPropertyInfo(propertyGetter);\n            Func<T, string> getFunc = (obj) => (string)property.GetValue(obj, index: null);\n            Action<T, string> setFunc = (obj, value) => property.SetValue(obj, value, index: null);\n\n            Assert.Equal(expectedDefaultValue, getFunc(instance));\n\n            if (allowNullAndEmpty)\n            {\n                // Assert get/set works for null\n                TestPropertyValue(instance, getFunc, setFunc, null, treatNullAsEmpty ? String.Empty : null);\n\n                // Assert get/set works for String.Empty\n                TestPropertyValue(instance, getFunc, setFunc, String.Empty, String.Empty);\n            }\n            else\n            {\n                Assert.ThrowsArgumentNullOrEmpty(\n                    delegate()\n                    {\n                        try\n                        {\n                            TestPropertyValue(instance, getFunc, setFunc, null);\n                        }\n                        catch (TargetInvocationException e)\n                        {\n                            throw e.InnerException;\n                        }\n                    },\n                    \"value\");\n                Assert.ThrowsArgumentNullOrEmpty(\n                    delegate()\n                    {\n                        try\n                        {\n                            TestPropertyValue(instance, getFunc, setFunc, String.Empty);\n                        }\n                        catch (TargetInvocationException e)\n                        {\n                            throw e.InnerException;\n                        }\n                    },\n                    \"value\");\n            }\n\n            // Assert get/set works for arbitrary value\n            TestPropertyValue(instance, getFunc, setFunc, \"TestValue\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/ReplaceCultureAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Globalization;\nusing System.Reflection;\nusing System.Threading;\n\nnamespace Microsoft.TestCommon\n{\n    /// <summary>\n    /// Replaces the current culture and UI culture for the test.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Method)]\n    public class ReplaceCultureAttribute : Xunit.Sdk.BeforeAfterTestAttribute\n    {\n        private CultureInfo _originalCulture;\n        private CultureInfo _originalUICulture;\n\n        public ReplaceCultureAttribute()\n        {\n            Culture = CultureReplacer.DefaultCultureName;\n            UICulture = CultureReplacer.DefaultUICultureName;\n        }\n\n        /// <summary>\n        /// Sets <see cref=\"Thread.CurrentCulture\"/> for the test. Defaults to en-GB.\n        /// </summary>\n        /// <remarks>\n        /// en-GB is used here as the default because en-US is equivalent to the InvariantCulture. We\n        /// want to be able to find bugs where we're accidentally relying on the Invariant instead of the\n        /// user's culture.\n        /// </remarks>\n        public string Culture { get; set; }\n\n        /// <summary>\n        /// Sets <see cref=\"Thread.CurrentUICulture\"/> for the test. Defaults to en-US.\n        /// </summary>\n        public string UICulture { get; set; }\n\n        public override void Before(MethodInfo methodUnderTest)\n        {\n            _originalCulture = Thread.CurrentThread.CurrentCulture;\n            _originalUICulture = Thread.CurrentThread.CurrentUICulture;\n\n            Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(Culture);\n            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(UICulture);\n        }\n\n        public override void After(MethodInfo methodUnderTest)\n        {\n            Thread.CurrentThread.CurrentCulture = _originalCulture;\n            Thread.CurrentThread.CurrentUICulture = _originalUICulture;\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/RestoreThreadPrincipalAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Reflection;\nusing System.Security.Principal;\nusing System.Threading;\n\nnamespace Microsoft.TestCommon\n{\n    public class RestoreThreadPrincipalAttribute : Xunit.Sdk.BeforeAfterTestAttribute\n    {\n        private IPrincipal _originalPrincipal;\n\n        public override void Before(MethodInfo methodUnderTest)\n        {\n            _originalPrincipal = Thread.CurrentPrincipal;\n\n            AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.NoPrincipal);\n\n            Thread.CurrentPrincipal = null;\n        }\n\n        public override void After(MethodInfo methodUnderTest)\n        {\n            Thread.CurrentPrincipal = _originalPrincipal;\n\n            AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.UnauthenticatedPrincipal);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/SkippedXunitTestCase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing Xunit.Abstractions;\nusing Xunit.Sdk;\n\nnamespace Microsoft.TestCommon\n{\n    /// <summary>\n    /// An <see cref=\"XunitTestCase\"/> which is unconditionally skipped.\n    /// </summary>\n    /// <remarks>\n    /// Similar to <c>Xunit.Sdk.XunitSkippedDataRowTestCase</c> but with a more general name. Besides, that will not\n    /// exist until xUnit.net 2.2.0 is stable.\n    /// </remarks>\n    public class SkippedXunitTestCase : XunitTestCase\n    {\n        private readonly String _skipReason;\n\n        /// <summary>\n        /// Instantiates a new <see cref=\"SkippedXunitTestCase\"/> instance.\n        /// </summary>\n        /// <param name=\"diagnosticMessageSink\">The <see cref=\"IMessageSink\"/> used to send diagnostic messages.</param>\n        /// <param name=\"defaultMethodDisplay\">Default <see cref=\"TestMethodDisplay\"/>  to use (when not customized).</param>\n        /// <param name=\"skipReason\">The reason that this <see cref=\"SkippedXunitTestCase\"/> will be skipped.</param>\n        /// <param name=\"testMethod\">The <see cref=\"ITestMethod\"/> this test case belongs to.</param>\n        /// <param name=\"testMethodArguments\">The arguments for the test method.</param>\n        public SkippedXunitTestCase(\n            IMessageSink diagnosticMessageSink,\n            TestMethodDisplay defaultMethodDisplay,\n            TestMethodDisplayOptions defaultMethodDisplayOptions,\n            String skipReason,\n            ITestMethod testMethod,\n            object[] testMethodArguments = null)\n            : base(diagnosticMessageSink, defaultMethodDisplay, defaultMethodDisplayOptions, testMethod, testMethodArguments)\n        {\n            _skipReason = skipReason;\n        }\n\n        /// <inheritdoc/>\n        protected override string GetSkipReason(IAttributeInfo factAttribute)\n        {\n            return _skipReason;\n        }\n    }\n}"
  },
  {
    "path": "test/Microsoft.TestCommon/TestFile.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Reflection;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.TestUtils\n{\n    public class TestFile\n    {\n        public const string ResourceNameFormat = \"{0}.TestFiles.{1}\";\n\n        public string ResourceName { get; set; }\n        public Assembly Assembly { get; set; }\n\n        public TestFile(string resName, Assembly asm)\n        {\n            ResourceName = resName;\n            Assembly = asm;\n        }\n\n        public static TestFile Create(string localResourceName)\n        {\n            return new TestFile(String.Format(ResourceNameFormat, Assembly.GetCallingAssembly().GetName().Name, localResourceName), Assembly.GetCallingAssembly());\n        }\n\n        public Stream OpenRead()\n        {\n            Stream strm = Assembly.GetManifestResourceStream(ResourceName);\n            if (strm == null)\n            {\n                Assert.True(false, String.Format(\"Manifest resource: {0} not found\", ResourceName));\n            }\n            return strm;\n        }\n\n        public byte[] ReadAllBytes()\n        {\n            using (Stream stream = OpenRead())\n            {\n                byte[] buffer = new byte[stream.Length];\n                stream.Read(buffer, 0, buffer.Length);\n                return buffer;\n            }\n        }\n\n        public string ReadAllText()\n        {\n            using (StreamReader reader = new StreamReader(OpenRead()))\n            {\n                // The .Replace() calls normalize line endings, in case you get \\n instead of \\r\\n\n                // since all the unit tests rely on the assumption that the files will have \\r\\n endings.\n                return reader.ReadToEnd().Replace(\"\\r\", \"\").Replace(\"\\n\", \"\\r\\n\");\n            }\n        }\n\n        /// <summary>\n        /// Saves the file to the specified path.\n        /// </summary>\n        public void Save(string filePath)\n        {\n            var directory = Path.GetDirectoryName(filePath);\n            if (!Directory.Exists(directory))\n            {\n                Directory.CreateDirectory(directory);\n            }\n\n            using (Stream outStream = File.Create(filePath))\n            {\n                using (Stream inStream = OpenRead())\n                {\n                    inStream.CopyTo(outStream);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/TestHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.TestUtil\n{\n    public static class UnitTestHelper\n    {\n        public static bool EnglishBuildAndOS\n        {\n            get\n            {\n                bool englishBuild = String.Equals(CultureInfo.CurrentCulture.TwoLetterISOLanguageName, \"en\",\n                                                  StringComparison.OrdinalIgnoreCase);\n                bool englishOS = String.Equals(CultureInfo.CurrentCulture.TwoLetterISOLanguageName, \"en\",\n                                               StringComparison.OrdinalIgnoreCase);\n                return englishBuild && englishOS;\n            }\n        }\n\n        public static void AssertEqualsIgnoreWhitespace(string expected, string actual)\n        {\n            expected = new String(expected.Where(c => !Char.IsWhiteSpace(c)).ToArray());\n            actual = new String(actual.Where(c => !Char.IsWhiteSpace(c)).ToArray());\n\n            Assert.Equal(expected, actual, StringComparer.OrdinalIgnoreCase);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/TheoryAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing Xunit.Sdk;\n\nnamespace Microsoft.TestCommon\n{\n    /// <summary>\n    /// An override of <see cref=\"Xunit.TheoryAttribute\"/> that provides extended capabilities.\n    /// </summary>\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]\n    [XunitTestCaseDiscoverer(\"Microsoft.TestCommon.TheoryDiscoverer\", \"Microsoft.TestCommon\")]\n    public class TheoryAttribute : Xunit.TheoryAttribute\n    {\n        /// <summary>\n        /// Instantiates a new instance of <see cref=\"TheoryAttribute\"/>.\n        /// </summary>\n        public TheoryAttribute()\n        {\n            Platforms = Platform.All;\n            PlatformJustification = \"Unsupported platform (test runs on {0}, current platform is {1})\";\n        }\n\n        /// <summary>\n        /// Gets or set the platforms that the unit test is compatible with. Defaults to\n        /// <see cref=\"Platform.All\"/>.\n        /// </summary>\n        public Platform Platforms { get; set; }\n\n        /// <summary>\n        /// Gets or sets the platform skipping justification. This message can receive\n        /// the supported platforms as {0}, and the current platform as {1}.\n        /// </summary>\n        public string PlatformJustification { get; set; }\n    }\n}"
  },
  {
    "path": "test/Microsoft.TestCommon/TheoryDataSet.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\n\nnamespace Microsoft.TestCommon\n{\n    /// <summary>\n    /// Helper class for generating test data for XUnit's <see cref=\"Xunit.Extensions.TheoryAttribute\"/>-based tests.\n    /// Should be used in combination with <see cref=\"Xunit.Extensions.PropertyDataAttribute\"/>.\n    /// </summary>\n    /// <typeparam name=\"TParam\">First parameter type</typeparam>\n    public class TheoryDataSet<TParam> : TheoryDataSet\n    {\n        public void Add(TParam p)\n        {\n            AddItem(p);\n        }\n    }\n\n    /// <summary>\n    /// Helper class for generating test data for XUnit's <see cref=\"Xunit.Extensions.TheoryAttribute\"/>-based tests.\n    /// Should be used in combination with <see cref=\"Xunit.Extensions.PropertyDataAttribute\"/>.\n    /// </summary>\n    /// <typeparam name=\"TParam1\">First parameter type</typeparam>\n    /// <typeparam name=\"TParam2\">Second parameter type</typeparam>\n    public class TheoryDataSet<TParam1, TParam2> : TheoryDataSet\n    {\n        public void Add(TParam1 p1, TParam2 p2)\n        {\n            AddItem(p1, p2);\n        }\n    }\n\n    /// <summary>\n    /// Helper class for generating test data for XUnit's <see cref=\"Xunit.Extensions.TheoryAttribute\"/>-based tests.\n    /// Should be used in combination with <see cref=\"Xunit.Extensions.PropertyDataAttribute\"/>.\n    /// </summary>\n    /// <typeparam name=\"TParam1\">First parameter type</typeparam>\n    /// <typeparam name=\"TParam2\">Second parameter type</typeparam>\n    /// <typeparam name=\"TParam3\">Third parameter type</typeparam>\n    public class TheoryDataSet<TParam1, TParam2, TParam3> : TheoryDataSet\n    {\n        public void Add(TParam1 p1, TParam2 p2, TParam3 p3)\n        {\n            AddItem(p1, p2, p3);\n        }\n    }\n\n    /// <summary>\n    /// Helper class for generating test data for XUnit's <see cref=\"Xunit.Extensions.TheoryAttribute\"/>-based tests.\n    /// Should be used in combination with <see cref=\"Xunit.Extensions.PropertyDataAttribute\"/>.\n    /// </summary>\n    /// <typeparam name=\"TParam1\">First parameter type</typeparam>\n    /// <typeparam name=\"TParam2\">Second parameter type</typeparam>\n    /// <typeparam name=\"TParam3\">Third parameter type</typeparam>\n    /// <typeparam name=\"TParam4\">Fourth parameter type</typeparam>\n    public class TheoryDataSet<TParam1, TParam2, TParam3, TParam4> : TheoryDataSet\n    {\n        public void Add(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4)\n        {\n            AddItem(p1, p2, p3, p4);\n        }\n    }\n\n    /// <summary>\n    /// Helper class for generating test data for XUnit's <see cref=\"Xunit.Extensions.TheoryAttribute\"/>-based tests.\n    /// Should be used in combination with <see cref=\"Xunit.Extensions.PropertyDataAttribute\"/>.\n    /// </summary>\n    /// <typeparam name=\"TParam1\">First parameter type</typeparam>\n    /// <typeparam name=\"TParam2\">Second parameter type</typeparam>\n    /// <typeparam name=\"TParam3\">Third parameter type</typeparam>\n    /// <typeparam name=\"TParam4\">Fourth parameter type</typeparam>\n    /// <typeparam name=\"TParam5\">Fifth parameter type</typeparam>\n    public class TheoryDataSet<TParam1, TParam2, TParam3, TParam4, TParam5> : TheoryDataSet\n    {\n        public void Add(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5)\n        {\n            AddItem(p1, p2, p3, p4, p5);\n        }\n    }\n\n    /// <summary>\n    /// Base class for <c>TheoryDataSet</c> classes.\n    /// </summary>\n    public abstract class TheoryDataSet : IEnumerable<object[]>\n    {\n        private readonly List<object[]> data = new List<object[]>();\n\n        protected void AddItem(params object[] values)\n        {\n            data.Add(values);\n        }\n\n        public IEnumerator<object[]> GetEnumerator()\n        {\n            return data.GetEnumerator();\n        }\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return GetEnumerator();\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/TheoryDiscoverer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing Xunit.Abstractions;\nusing Xunit.Sdk;\n\nnamespace Microsoft.TestCommon\n{\n    /// <summary>\n    /// An override of <see cref=\"Xunit.Sdk.TheoryDiscoverer\"/> that provides extended capabilities.\n    /// </summary>\n    public class TheoryDiscoverer : Xunit.Sdk.TheoryDiscoverer\n    {\n        private readonly IMessageSink _diagnosticMessageSink;\n\n        /// <summary>\n        /// Instantiates a new <see cref=\"TheoryDiscoverer\"/> instance.\n        /// </summary>\n        /// <param name=\"diagnosticMessageSink\">The <see cref=\"IMessageSink\"/> used to send diagnostic messages.</param>\n        public TheoryDiscoverer(IMessageSink diagnosticMessageSink)\n            : base(diagnosticMessageSink)\n        {\n            _diagnosticMessageSink = diagnosticMessageSink;\n        }\n\n        /// <summary>\n        /// Gets the platform that the unit test is currently running on.\n        /// </summary>\n        protected Platform Platform\n        {\n            get { return PlatformInfo.Platform; }\n        }\n\n        /// <inheritdoc/>\n        public override IEnumerable<IXunitTestCase> Discover(\n            ITestFrameworkDiscoveryOptions discoveryOptions,\n            ITestMethod testMethod,\n            IAttributeInfo theoryAttribute)\n        {\n            var baseCases = base.Discover(discoveryOptions, testMethod, theoryAttribute);\n            if (!String.IsNullOrEmpty(theoryAttribute.GetNamedArgument<string>(\"Skip\")))\n            {\n                // No need to change skipped tests.\n                return baseCases;\n            }\n\n            var platforms = theoryAttribute.GetNamedArgument<Platform>(\"Platforms\");\n            if ((platforms & Platform) != 0)\n            {\n                // No need to change tests that should run on the current platform.\n                return baseCases;\n            }\n\n            // Update the individual test cases as needed: Skip test cases that would otherwise run.\n            var testCases = new List<IXunitTestCase>();\n            var platformJustification = theoryAttribute.GetNamedArgument<string>(\"PlatformJustification\");\n            var skipReason = String.Format(platformJustification, platforms.ToString().Replace(\", \", \" | \"), Platform);\n            foreach (var baseCase in baseCases)\n            {\n                if (baseCase is ExecutionErrorTestCase)\n                {\n                    // No need to change an erroneous test. Covered to protect against changes in the base class.\n                    testCases.Add(baseCase);\n                    continue;\n                }\n\n                if (!String.IsNullOrEmpty(baseCase.SkipReason))\n                {\n                    // No need to change a skipped test. Likely to hit this case only after xUnit.net has been updated\n                    // to 2.2.0+, where [Data] also has a Skip property.\n                    testCases.Add(baseCase);\n                    continue;\n                }\n\n                var testCase = new SkippedXunitTestCase(\n                    _diagnosticMessageSink,\n                    discoveryOptions.MethodDisplayOrDefault(),\n                    TestMethodDisplayOptions.None,\n                    skipReason,\n                    baseCase.TestMethod,\n                    baseCase.TestMethodArguments);\n                testCases.Add(testCase);\n            }\n\n            return testCases;\n        }\n    }\n}"
  },
  {
    "path": "test/Microsoft.TestCommon/ThreadPoolSyncContext.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\n\nnamespace Microsoft.TestCommon\n{\n    /// <summary>\n    /// This is an implementation of SynchronizationContext that not only queues things on the thread pool for\n    /// later work, but also ensures that it sets itself back as the synchronization context (something that the\n    /// default implementatation of SynchronizationContext does not do).\n    /// </summary>\n    public class ThreadPoolSyncContext : SynchronizationContext\n    {\n        public override void Post(SendOrPostCallback d, object state)\n        {\n            ThreadPool.QueueUserWorkItem(_ =>\n            {\n                SynchronizationContext oldContext = SynchronizationContext.Current;\n                SynchronizationContext.SetSynchronizationContext(this);\n                d.Invoke(state);\n                SynchronizationContext.SetSynchronizationContext(oldContext);\n            }, null);\n        }\n\n        public override void Send(SendOrPostCallback d, object state)\n        {\n            SynchronizationContext oldContext = SynchronizationContext.Current;\n            SynchronizationContext.SetSynchronizationContext(this);\n            d.Invoke(state);\n            SynchronizationContext.SetSynchronizationContext(oldContext);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/TraitAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing Xunit.Sdk;\n\nnamespace Microsoft.TestCommon\n{\n    // Xunit.MemberDataAttribute is unfortunately sealed. Duplicate its code here since there's nothing to it.\n    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]\n    [TraitDiscoverer(\"Xunit.Sdk.TraitDiscoverer\", \"xunit.core\")]\n    public class TraitAttribute : Attribute, ITraitAttribute\n    {\n        public TraitAttribute(string name, string value)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/VersionTestHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Reflection;\n\nnamespace Microsoft.TestCommon\n{\n    public static class VersionTestHelper\n    {\n        // returns a version for an assembly by using a type from the assembly\n        // also verifies that type wasn't moved to another assembly.\n        public static Version GetVersionFromAssembly(string assemblyName, Type typeFromAssembly)\n        {\n            Assembly assembly = typeFromAssembly.Assembly;\n\n            Assert.Equal(assemblyName, assembly.GetName().Name);\n            return assembly.GetName().Version;\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/WebUtils.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Reflection;\nusing System.Web.UI;\n\nnamespace System.Web.WebPages.TestUtils\n{\n    public static class WebUtils\n    {\n        /// <summary>\n        /// Creates an instance of HttpRuntime and assigns it (using magic) to the singleton instance of HttpRuntime. \n        /// Ensure that the returned value is disposed at the end of the test.\n        /// </summary>\n        /// <returns>Returns an IDisposable that restores the original HttpRuntime.</returns>\n        public static IDisposable CreateHttpRuntime(string appVPath, string appPath = null)\n        {\n            var runtime = new HttpRuntime();\n            var appDomainAppVPathField = typeof(HttpRuntime).GetField(\"_appDomainAppVPath\", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);\n            appDomainAppVPathField.SetValue(runtime, CreateVirtualPath(appVPath));\n\n            if (appPath != null)\n            {\n                var appDomainAppPathField = typeof(HttpRuntime).GetField(\"_appDomainAppPath\", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);\n                appDomainAppPathField.SetValue(runtime, Path.GetFullPath(appPath));\n            }\n\n            GetTheRuntime().SetValue(null, runtime);\n            var appDomainIdField = typeof(HttpRuntime).GetField(\"_appDomainId\", BindingFlags.NonPublic | BindingFlags.Instance);\n            appDomainIdField.SetValue(runtime, \"test\");\n\n            return new DisposableAction(RestoreHttpRuntime);\n        }\n\n        internal static FieldInfo GetTheRuntime()\n        {\n            return typeof(HttpRuntime).GetField(\"_theRuntime\", BindingFlags.NonPublic | BindingFlags.Static);\n        }\n\n        internal static void RestoreHttpRuntime()\n        {\n            GetTheRuntime().SetValue(null, null);\n        }\n\n        internal static object CreateVirtualPath(string path)\n        {\n            var vPath = typeof(Page).Assembly.GetType(\"System.Web.VirtualPath\");\n            var method = vPath.GetMethod(\"CreateNonRelativeTrailingSlash\", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);\n            return method.Invoke(null, new object[] { path });\n        }\n\n        private class DisposableAction : IDisposable\n        {\n            private Action _action;\n            private bool _hasDisposed;\n\n            public DisposableAction(Action action)\n            {\n                if (action == null)\n                {\n                    throw new ArgumentNullException(\"action\");\n                }\n                _action = action;\n            }\n\n            public void Dispose()\n            {\n                Dispose(true);\n                GC.SuppressFinalize(this);\n            }\n\n            protected virtual void Dispose(bool disposing)\n            {\n                // If we were disposed by the finalizer it's because the user didn't use a \"using\" block, so don't do anything!\n                if (disposing)\n                {\n                    lock (this)\n                    {\n                        if (!_hasDisposed)\n                        {\n                            _hasDisposed = true;\n                            _action();\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.TestCommon/xunit.runner.json",
    "content": "﻿{\n  \"diagnosticMessages\": false,\n  \"preEnumerateTheories\": false\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Helpers.Test/AnalyticsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Helpers.Test\n{\n    public class AnalyticsTest\n    {\n        [Fact]\n        public void GetYahooAnalyticsHtmlTest()\n        {\n            string account = \"My_yahoo_account\";\n            string actual = Analytics.GetYahooHtml(account).ToString();\n            Assert.True(actual.Contains(\".yahoo.com\") && actual.Contains(\"My_yahoo_account\"));\n        }\n\n        [Fact]\n        public void GetStatCounterAnalyticsHtmlTest()\n        {\n            int project = 31553;\n            string security = \"stat_security\";\n            string actual = Analytics.GetStatCounterHtml(project, security).ToString();\n            Assert.True(actual.Contains(\"statcounter.com/counter/counter_xhtml.js\") &&\n                        actual.Contains(project.ToString()) && actual.Contains(security));\n        }\n\n        [Fact]\n        public void GetGoogleAnalyticsHtmlTest()\n        {\n            string account = \"My_google_account\";\n            string actual = Analytics.GetGoogleHtml(account).ToString();\n            Assert.True(actual.Contains(\"google-analytics.com/ga.js\") && actual.Contains(\"My_google_account\"));\n        }\n\n        [Fact]\n        public void GetGoogleAnalyticsEscapesJavascript()\n        {\n            string account = \"My_\\\"google_account\";\n            string actual = Analytics.GetGoogleHtml(account).ToString();\n            string expected = \"<script type=\\\"text/javascript\\\">\\n\" +\n                              \"var gaJsHost = ((\\\"https:\\\" == document.location.protocol) ? \\\"https://ssl.\\\" : \\\"http://www.\\\");\\n\" +\n                              \"document.write(unescape(\\\"%3Cscript src='\\\" + gaJsHost + \\\"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E\\\"));\\n\" +\n                              \"</script>\\n\" +\n                              \"<script type=\\\"text/javascript\\\">\\n\" +\n                              \"try{\\n\" +\n                              \"var pageTracker = _gat._getTracker(\\\"My_\\\\\\\"google_account\\\");\\n\" +\n                              \"pageTracker._trackPageview();\\n\" +\n                              \"} catch(err) {}\\n\" +\n                              \"</script>\\n\";\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expected, actual);\n        }\n\n        [Fact]\n        public void GetGoogleAnalyticsAsyncHtmlTest()\n        {\n            string account = \"My_google_account\";\n            string actual = Analytics.GetGoogleAsyncHtml(account).ToString();\n            Assert.True(actual.Contains(\"google-analytics.com/ga.js\") && actual.Contains(\"My_google_account\"));\n        }\n\n        [Fact]\n        public void GetGoogleAnalyticsAsyncHtmlEscapesJavaScript()\n        {\n            string account = \"My_\\\"google_account\";\n            string actual = Analytics.GetGoogleAsyncHtml(account).ToString();\n            string expected = \"<script type=\\\"text/javascript\\\">\\n\" +\n                              \"var _gaq = _gaq || [];\\n\" +\n                              \"_gaq.push(['_setAccount', 'My_\\\\\\\"google_account']);\\n\" +\n                              \"_gaq.push(['_trackPageview']);\\n\" +\n                              \"(function() {\\n\" +\n                              \"var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;\\n\" +\n                              \"ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';\\n\" +\n                              \"var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);\\n\" +\n                              \"})();\\n\" +\n                              \"</script>\\n\";\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expected, actual);\n        }\n\n        [Fact]\n        public void GetYahooAnalyticsEscapesJavascript()\n        {\n            string account = \"My_\\\"yahoo_account\";\n            string actual = Analytics.GetYahooHtml(account).ToString();\n            string expected = \"<script type=\\\"text/javascript\\\">\\n\" +\n                              \"window.ysm_customData = new Object();\\n\" +\n                              \"window.ysm_customData.conversion = \\\"transId=,currency=,amount=\\\";\\n\" +\n                              \"var ysm_accountid = \\\"My_\\\\\\\"yahoo_account\\\";\\n\" +\n                              \"document.write(\\\"<SCR\\\" + \\\"IPT language='JavaScript' type='text/javascript' \\\"\\n\" +\n                              \"+ \\\"SRC=//\\\" + \\\"srv3.wa.marketingsolutions.yahoo.com\\\" + \\\"/script/ScriptServlet\\\" + \\\"?aid=\\\" + ysm_accountid\\n\" +\n                              \"+ \\\"></SCR\\\" + \\\"IPT>\\\");\\n\" +\n                              \"</script>\\n\";\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expected, actual);\n        }\n\n        [Fact]\n        public void GetStatCounterAnalyticsEscapesCorrectly()\n        {\n            string account = \"My_\\\"stat_account\";\n            string actual = Analytics.GetStatCounterHtml(2, account).ToString();\n            string expected = \"<script type=\\\"text/javascript\\\">\\n\" +\n                              \"var sc_project=2;\\n\" +\n                              \"var sc_invisible=1;\\n\" +\n                              \"var sc_security=\\\"My_\\\\\\\"stat_account\\\";\\n\" +\n                              \"var sc_text=2;\\n\" +\n                              \"var sc_https=1;\\n\" +\n                              \"var scJsHost = ((\\\"https:\\\" == document.location.protocol) ? \\\"https://secure.\\\" : \\\"http://www.\\\");\\n\" +\n                              \"document.write(\\\"<sc\\\" + \\\"ript type='text/javascript' src='\\\" + \" +\n                              \"scJsHost + \\\"statcounter.com/counter/counter_xhtml.js'></\\\" + \\\"script>\\\");\\n\" +\n                              \"</script>\\n\\n\" +\n                              \"<noscript>\" +\n                              \"<div class=\\\"statcounter\\\">\" +\n                              \"<a title=\\\"tumblrstatistics\\\" class=\\\"statcounter\\\" href=\\\"http://www.statcounter.com/tumblr/\\\">\" +\n                              \"<img class=\\\"statcounter\\\" src=\\\"https://c.statcounter.com/2/0/My_&quot;stat_account/1/\\\" alt=\\\"tumblr statistics\\\"/>\" +\n                              \"</a>\" +\n                              \"</div>\" +\n                              \"</noscript>\";\n\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expected, actual);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Helpers.Test/FacebookTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Web;\nusing System.Web.TestUtil;\nusing System.Web.WebPages.Scope;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace Microsoft.Web.Helpers.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")]\n    public class FacebookTest : IDisposable\n    {\n        public FacebookTest()\n        {\n            Facebook.AppId = \"myapp'\";\n            Facebook.AppSecret = \"myappsecret\";\n            Facebook.Language = \"french\";\n        }\n\n        [Fact]\n        public void GetFacebookCookieInfoReturnsEmptyStringIfCookieIsNotPresent()\n        {\n            // Arrange\n            var context = CreateHttpContext();\n\n            // Act\n            var info = Facebook.GetFacebookCookieInfo(context, \"foo\");\n\n            // Assert\n            Assert.Equal(\"\", info);\n        }\n\n        [Fact]\n        public void GetFacebookCookieInfoThrowsIfCookieIsNotValid()\n        {\n            // Arrange\n\n            var context = CreateHttpContext(new Dictionary<string, string>\n            {\n                {\"fbs_myapp'\", \"sig=malformed-signature&name=foo&val=bar&uid=MyFacebookName\"},\n                {\"fbs_uid\", \"MyFacebookName\"},\n            });\n\n            // Act and Assert\n            Assert.Throws<InvalidOperationException>(() => Facebook.GetFacebookCookieInfo(context, \"uid\"), \"Invalid Facebook cookie.\");\n        }\n\n        [Fact]\n        public void GetFacebookCookieReturnsUserIdIfCookieIsValid()\n        {\n            // Arrange\n            var context = CreateHttpContext(new Dictionary<string, string>\n            {\n                {\"fbs_myapp'\", \"sig=B2E6B3A21D0C9FA72E612BD6C3084807&name=foo&val=bar&uid=MyFacebookName\"},\n            });\n\n            // Act\n            var info = Facebook.GetFacebookCookieInfo(context, \"uid\");\n\n            // Assert\n            Assert.Equal(\"MyFacebookName\", info);\n        }\n\n        [Fact]\n        public void GetInitScriptsJSEncodesParameters()\n        {\n            // Arrange\n            var expectedText = @\"\n                <div id=\"\"fb-root\"\"></div>\n                <script type=\"\"text/javascript\"\">\n                    window.fbAsyncInit = function () {\n                        FB.init({ appId: 'MyApp\\u0027', status: true, cookie: true, xfbml: true });\n                    };\n                    (function () {\n                        var e = document.createElement('script'); e.async = true;\n                        e.src = document.location.protocol +\n                        '//connect.facebook.net/French/all.js';\n                        document.getElementById('fb-root').appendChild(e);\n                    } ());\n\n                    function loginRedirect(url) { window.location = url; }\n                </script>\n            \";\n\n            // Act\n            var actualText = Facebook.GetInitializationScripts();\n\n            // Assert\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedText, actualText.ToString());\n        }\n\n        [Fact]\n        public void LoginButtonTest()\n        {\n            // Arrange\n            var expected40 = @\"<fb:login-button autologoutlink=\"\"True\"\" size=\"\"extra-small\"\" length=\"\"extra-long\"\" onlogin=\"\"loginRedirect(&#39;http://www.test.com/facebook/?registerUrl=http%3a%2f%2fwww.test.com%2f&amp;returnUrl=http%3a%2f%2fww.test.com%2fLogin.cshtml&#39;)\"\" show-faces=\"\"True\"\" perms=\"\"email,none&quot;\"\">Awesome &quot;button text&quot;</fb:login-button>\";\n            var expected45 = @\"<fb:login-button autologoutlink=\"\"True\"\" size=\"\"extra-small\"\" length=\"\"extra-long\"\" onlogin=\"\"loginRedirect(&#39;http://www.test.com/facebook/?registerUrl=http%3a%2f%2fwww.test.com%2f\\u0026returnUrl=http%3a%2f%2fww.test.com%2fLogin.cshtml&#39;)\"\" show-faces=\"\"True\"\" perms=\"\"email,none&quot;\"\">Awesome &quot;button text&quot;</fb:login-button>\";\n\n            // Act\n            var actualText = Facebook.LoginButton(\"http://www.test.com\", \"http://ww.test.com/Login.cshtml\", \"http://www.test.com/facebook/\", \"Awesome \\\"button text\\\"\", true, \"extra-small\", \"extra-long\", true, \"none\\\"\");\n\n            // Assert\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(RuntimeEnvironment.IsVersion45Installed ? expected45 : expected40, actualText.ToString());\n        }\n\n        [Fact]\n        public void LoginButtonOnlyTagTest()\n        {\n            // Arrange\n            var expectedText = @\"<fb:login-button autologoutlink=\"\"True\"\" size=\"\"small\"\" length=\"\"medium\"\" onlogin=\"\"foobar();\"\" show-faces=\"\"True\"\" perms=\"\"none&quot;\"\">&quot;Awesome button text&quot;</fb:login-button>\";\n\n            // Act\n            var actualText = Facebook.LoginButtonTagOnly(\"\\\"Awesome button text\\\"\", true, \"small\", \"medium\", \"foobar();\", true, \"none\\\"\");\n\n            // Assert\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedText, actualText.ToString());\n        }\n\n        [Fact]\n        public void LikeButtonTest()\n        {\n            // Arrange\n            var expectedText = @\"<iframe src=\"\"http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fsomewebsite&amp;layout=modern&amp;show_faces=false&amp;width=300&amp;action=hop&amp;colorscheme=lighter&amp;height=30&amp;font=Comic+Sans&amp;locale=French&amp;ref=foo+bar\"\" scrolling=\"\"no\"\" frameborder=\"\"0\"\" style=\"\"border:none; overflow:hidden; width:300px; height:30px;\"\" allowTransparency=\"\"true\"\"></iframe>\";\n\n            // Act\n            var actualText = Facebook.LikeButton(\"http://somewebsite\", \"modern\", false, 300, 30, \"hop\", \"Comic Sans\", \"lighter\", \"foo bar\");\n\n            // Assert\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedText, actualText.ToString());\n        }\n\n        [Fact]\n        public void CommentsWithNoXidTest()\n        {\n            // Arrange\n            var expectedText = @\"<fb:comments numposts=\"\"3\"\" width=\"\"300\"\" reverse=\"\"true\"\" simple=\"\"true\"\" ></fb:comments>\";\n\n            // Act\n            var actualText = Facebook.Comments(null, 300, 3, true, true);\n\n            // Assert\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedText, actualText.ToString());\n        }\n\n        [Fact]\n        public void CommentsWithXidTest()\n        {\n            // Arrange\n            var expectedText = @\"<fb:comments xid=\"\"bar\"\" numposts=\"\"3\"\" width=\"\"300\"\" reverse=\"\"true\"\" simple=\"\"true\"\" ></fb:comments>\";\n\n            // Act\n            var actualText = Facebook.Comments(\"bar\", 300, 3, true, true);\n\n            // Assert\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedText, actualText.ToString());\n        }\n\n        [Fact]\n        public void RecommendationsTest()\n        {\n            // Arrange\n            var expectedText = @\"<iframe src=\"\"http://www.facebook.com/plugins/recommendations.php?site=http%3a%2f%2fsomesite&amp;width=100&amp;height=200&amp;header=False&amp;colorscheme=blue&amp;font=none&amp;border_color=black&amp;filter=All+posts&amp;ref=ref+label&amp;locale=french\"\" scrolling=\"\"no\"\" frameborder=\"\"0\"\" style=\"\"border:none; overflow:hidden; width:100px; height:200px;\"\" allowTransparency=\"\"true\"\"></iframe>\";\n\n            // Act\n            var actualText = Facebook.Recommendations(\"http://somesite\", 100, 200, false, \"blue\", \"none\", \"black\", \"All posts\", \"ref label\");\n\n            // Assert\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedText, actualText.ToString());\n        }\n\n        [Fact]\n        public void LikeBoxTest()\n        {\n            // Arrange\n            var expectedText = @\"<iframe src=\"\"http://www.facebook.com/plugins/likebox.php?href=http%3a%2f%2fsomesite&amp;width=100&amp;height=200&amp;header=False&amp;colorscheme=blue&amp;connections=5&amp;stream=True&amp;header=False&amp;locale=french\"\" scrolling=\"\"no\"\" frameborder=\"\"0\"\" style=\"\"border:none; overflow:hidden; width:100px; height:200px;\"\" allowTransparency=\"\"true\"\"></iframe>\";\n\n            // Act\n            var actualText = Facebook.LikeBox(\"http://somesite\", 100, 200, \"blue\", 5, true, false);\n\n            // Assert\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedText, actualText.ToString());\n        }\n\n        [Fact]\n        public void FacepileTest()\n        {\n            // Arrange\n            var expectedText = @\"<fb:facepile max-rows=\"\"3\"\" width=\"\"100\"\"></fb:facepile>\";\n\n            // Act\n            var actualText = Facebook.Facepile(3, 100);\n\n            // Assert\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedText, actualText.ToString());\n        }\n\n        [Fact]\n        public void LiveStreamWithEmptyXidTest()\n        {\n            // Arrange\n            var expectedText = @\"<iframe src=\"\"http://www.facebook.com/plugins/live_stream_box.php?app_id=myapp%27&amp;width=100&amp;height=100&amp;always_post_to_friends=True&amp;locale=french\"\" scrolling=\"\"no\"\" frameborder=\"\"0\"\" style=\"\"border:none; overflow:hidden; width:100px; height:100px;\"\" allowTransparency=\"\"true\"\"></iframe>\";\n\n            // Act\n            var actualText = Facebook.LiveStream(100, 100, \"\", \"\", true);\n\n            // Assert\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedText, actualText.ToString());\n        }\n\n        [Fact]\n        public void LiveStreamWithXidValueTest()\n        {\n            // Arrange\n            var expectedText = @\"<iframe src=\"\"http://www.facebook.com/plugins/live_stream_box.php?app_id=myapp%27&amp;width=100&amp;height=100&amp;always_post_to_friends=True&amp;locale=french&amp;xid=some-val&amp;via_url=http%3a%2f%2fmysite\"\" scrolling=\"\"no\"\" frameborder=\"\"0\"\" style=\"\"border:none; overflow:hidden; width:100px; height:100px;\"\" allowTransparency=\"\"true\"\"></iframe>\";\n\n            // Act\n            var actualText = Facebook.LiveStream(100, 100, \"some-val\", \"http://mysite\", true);\n\n            // Assert\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedText, actualText.ToString());\n        }\n\n        [Fact]\n        public void ActivityStreamTest()\n        {\n            // Arrange\n            var expectedText = @\"<iframe src=\"\"http://www.facebook.com/plugins/activity.php?site=http%3a%2f%2fmysite&amp;width=100&amp;height=120&amp;header=False&amp;colorscheme=gray&amp;font=Arial&amp;border_color=blue&amp;recommendations=True&amp;locale=french\"\" scrolling=\"\"no\"\" frameborder=\"\"0\"\" style=\"\"border:none; overflow:hidden; width:300px; height:300px;\"\" allowTransparency=\"\"true\"\"></iframe>\";\n\n            // Act\n            var actualText = Facebook.ActivityFeed(\"http://mysite\", 100, 120, false, \"gray\", \"Arial\", \"blue\", true);\n\n            // Assert\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedText, actualText.ToString());\n        }\n\n        [Fact]\n        public void FbmlNamespacesTest()\n        {\n            // Arrange\n            var expectedText = @\"xmlns:fb=\"\"http://www.facebook.com/2008/fbml\"\" xmlns:og=\"\"http://opengraphprotocol.org/schema/\"\"\";\n\n            // Act\n            var actualText = Facebook.FbmlNamespaces();\n\n            // Assert\n            Assert.Equal(expectedText, actualText.ToString());\n        }\n\n        private static HttpContextBase CreateHttpContext(IDictionary<string, string> cookieValues = null)\n        {\n            var context = new Mock<HttpContextBase>();\n            var httpRequest = new Mock<HttpRequestBase>();\n            var cookies = new HttpCookieCollection();\n            httpRequest.Setup(c => c.Cookies).Returns(cookies);\n\n            context.Setup(c => c.Request).Returns(httpRequest.Object);\n\n            if (cookieValues != null)\n            {\n                foreach (var item in cookieValues)\n                {\n                    cookies.Add(new HttpCookie(item.Key, item.Value));\n                }\n            }\n\n            return context.Object;\n        }\n\n        public void Dispose()\n        {\n            // Reset ScopeStorage (written via e.g. Facebook.AppId) between tests to avoid unexpected interactions.\n            ScopeStorage.CurrentProvider = new StaticScopeStorageProvider();\n            ScopeStorage.GlobalScope.Clear();\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Helpers.Test/FileUploadTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Web;\nusing System.Web.Helpers.Test;\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace Microsoft.Web.Helpers.Test\n{\n    public class FileUploadTest\n    {\n        private const string _fileUploadScript = \"<script type=\\\"text/javascript\\\"> if (!window[\\\"FileUploadHelper\\\"]) window[\\\"FileUploadHelper\\\"] = {};  FileUploadHelper.addInputElement = function(index, name) {  var inputElem = document.createElement(\\\"input\\\");  inputElem.type = \\\"file\\\";  inputElem.name = name;  var divElem = document.createElement(\\\"div\\\");  divElem.appendChild(inputElem.cloneNode(false));   var inputs = document.getElementById(\\\"file-upload-\\\" + index);  inputs.appendChild(divElem);  } </script>\";\n\n        [Fact]\n        public void RenderThrowsWhenNumberOfFilesIsLessThanZero()\n        {\n            // Act and Assert\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(\n                () => FileUpload._GetHtml(GetContext(), name: null, initialNumberOfFiles: -2, allowMoreFilesToBeAdded: false, includeFormTag: false, addText: \"\", uploadText: \"\").ToString(),\n                \"initialNumberOfFiles\", \"0\");\n        }\n\n        [Fact]\n        public void ResultIncludesFormTagAndSubmitButtonWhenRequested()\n        {\n            // Arrange\n            string expectedResult = @\"<form action=\"\"\"\" enctype=\"\"multipart/form-data\"\" method=\"\"post\"\"><div class=\"\"file-upload\"\" id=\"\"file-upload-0\"\">\"\n                                    + @\"<div><input name=\"\"fileUpload\"\" type=\"\"file\"\" /></div></div>\"\n                                    + @\"<div class=\"\"file-upload-buttons\"\"><input type=\"\"submit\"\" value=\"\"Upload\"\" /></div></form>\";\n\n            // Act\n            var actualResult = FileUpload._GetHtml(GetContext(), name: null, initialNumberOfFiles: 1, allowMoreFilesToBeAdded: false, includeFormTag: true, addText: null, uploadText: null);\n\n            // Assert\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedResult, actualResult.ToString());\n        }\n\n        [Fact]\n        public void ResultDoesNotIncludeFormTagAndSubmitButtonWhenNotRequested()\n        {\n            // Arrange\n            string expectedResult = @\"<div class=\"\"file-upload\"\" id=\"\"file-upload-0\"\"><div><input name=\"\"fileUpload\"\" type=\"\"file\"\" /></div></div>\";\n\n            // Act \n            var actualResult = FileUpload._GetHtml(GetContext(), name: null, initialNumberOfFiles: 1, allowMoreFilesToBeAdded: false, includeFormTag: false, addText: null, uploadText: null);\n\n            // Assert\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedResult, actualResult.ToString());\n        }\n\n        [Fact]\n        public void ResultIncludesCorrectNumberOfInputFields()\n        {\n            // Arrange\n            string expectedResult = @\"<div class=\"\"file-upload\"\" id=\"\"file-upload-0\"\"><div><input name=\"\"fileUpload\"\" type=\"\"file\"\" /></div><div><input name=\"\"fileUpload\"\" type=\"\"file\"\" /></div>\"\n                                    + @\"<div><input name=\"\"fileUpload\"\" type=\"\"file\"\" /></div></div>\";\n\n            // Act\n            var actualResult = FileUpload._GetHtml(GetContext(), name: null, initialNumberOfFiles: 3, allowMoreFilesToBeAdded: false, includeFormTag: false, addText: null, uploadText: null);\n\n            // Assert\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedResult, actualResult.ToString());\n        }\n\n        [Fact]\n        public void ResultIncludesAnchorTagWithCorrectAddText()\n        {\n            // Arrange\n            string customAddText = \"Add More\";\n            string expectedResult = _fileUploadScript\n                                    + @\"<div class=\"\"file-upload\"\" id=\"\"file-upload-0\"\"><div><input name=\"\"fileUpload\"\" type=\"\"file\"\" /></div></div>\"\n                                    + @\"<div class=\"\"file-upload-buttons\"\"><a href=\"\"#\"\" onclick=\"\"FileUploadHelper.addInputElement(0, &quot;fileUpload&quot;); return false;\"\">\" + customAddText + \"</a></div>\";\n\n            // Act\n            var result = FileUpload._GetHtml(GetContext(), name: null, allowMoreFilesToBeAdded: true, includeFormTag: false, addText: customAddText, initialNumberOfFiles: 1, uploadText: null);\n\n            // Assert\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedResult, result.ToString());\n        }\n\n        [Fact]\n        public void ResultDoesNotIncludeAnchorTagNorAddTextWhenNotRequested()\n        {\n            // Arrange\n            string customAddText = \"Add More\";\n            string expectedResult = @\"<div class=\"\"file-upload\"\" id=\"\"file-upload-0\"\"><div><input name=\"\"fileUpload\"\" type=\"\"file\"\" /></div></div>\";\n\n            // Act\n            var result = FileUpload._GetHtml(GetContext(), name: null, allowMoreFilesToBeAdded: false, includeFormTag: false, addText: customAddText, uploadText: null, initialNumberOfFiles: 1);\n\n            // Assert\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedResult, result.ToString());\n        }\n\n        [Fact]\n        public void ResultIncludesSubmitInputTagWithCustomUploadText()\n        {\n            // Arrange\n            string customUploadText = \"Now!\";\n            string expectedResult = @\"<form action=\"\"\"\" enctype=\"\"multipart/form-data\"\" method=\"\"post\"\"><div class=\"\"file-upload\"\" id=\"\"file-upload-0\"\">\"\n                                    + @\"<div><input name=\"\"fileUpload\"\" type=\"\"file\"\" /></div></div>\"\n                                    + @\"<div class=\"\"file-upload-buttons\"\"><input type=\"\"submit\"\" value=\"\"\" + customUploadText + @\"\"\" /></div></form>\";\n\n            // Act\n            var result = FileUpload._GetHtml(GetContext(), name: null, includeFormTag: true, uploadText: customUploadText, allowMoreFilesToBeAdded: false, initialNumberOfFiles: 1, addText: null);\n\n            // Assert\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedResult, result.ToString());\n        }\n\n        [Fact]\n        public void FileUploadGeneratesUniqueIdsForMultipleCallsForCommonRequest()\n        {\n            // Arrange\n            var context = GetContext();\n            string expectedResult1 = @\"<div class=\"\"file-upload\"\" id=\"\"file-upload-0\"\"><div><input name=\"\"fileUpload\"\" type=\"\"file\"\" /></div><div><input name=\"\"fileUpload\"\" type=\"\"file\"\" /></div>\"\n                                     + @\"<div><input name=\"\"fileUpload\"\" type=\"\"file\"\" /></div></div>\";\n            string expectedResult2 = @\"<form action=\"\"\"\" enctype=\"\"multipart/form-data\"\" method=\"\"post\"\"><div class=\"\"file-upload\"\" id=\"\"file-upload-1\"\"><div><input name=\"\"fileUpload\"\" type=\"\"file\"\" /></div>\"\n                                     + @\"<div><input name=\"\"fileUpload\"\" type=\"\"file\"\" /></div></div><div class=\"\"file-upload-buttons\"\"><input type=\"\"submit\"\" value=\"\"Upload\"\" /></div></form>\";\n\n            // Act\n            var result1 = FileUpload._GetHtml(context, name: null, initialNumberOfFiles: 3, allowMoreFilesToBeAdded: false, includeFormTag: false, addText: null, uploadText: null);\n            var result2 = FileUpload._GetHtml(context, name: null, initialNumberOfFiles: 2, allowMoreFilesToBeAdded: false, includeFormTag: true, addText: null, uploadText: null);\n\n            // Assert\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedResult1, result1.ToString());\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedResult2, result2.ToString());\n        }\n\n        [Fact]\n        public void FileUploadGeneratesScriptOncePerRequest()\n        {\n            // Arrange\n            var context = GetContext();\n            string expectedResult1 = _fileUploadScript\n                                     + @\"<div class=\"\"file-upload\"\" id=\"\"file-upload-0\"\"><div><input name=\"\"fileUpload\"\" type=\"\"file\"\" /></div></div>\"\n                                     + @\"<div class=\"\"file-upload-buttons\"\"><a href=\"\"#\"\" onclick=\"\"FileUploadHelper.addInputElement(0, &quot;fileUpload&quot;); return false;\"\">Add more files</a></div>\";\n            string expectedResult2 = @\"<form action=\"\"\"\" enctype=\"\"multipart/form-data\"\" method=\"\"post\"\"><div class=\"\"file-upload\"\" id=\"\"file-upload-1\"\"><div><input name=\"\"fileUpload\"\" type=\"\"file\"\" /></div></div>\"\n                                     + @\"<div class=\"\"file-upload-buttons\"\"><a href=\"\"#\"\" onclick=\"\"FileUploadHelper.addInputElement(1, &quot;fileUpload&quot;); return false;\"\">Add more files</a><input type=\"\"submit\"\" value=\"\"Upload\"\" /></div></form>\";\n            string expectedResult3 = @\"<form action=\"\"\"\" enctype=\"\"multipart/form-data\"\" method=\"\"post\"\"><div class=\"\"file-upload\"\" id=\"\"file-upload-2\"\">\"\n                                     + @\"<div><input name=\"\"fileUpload\"\" type=\"\"file\"\" /></div></div>\"\n                                     + @\"<div class=\"\"file-upload-buttons\"\"><input type=\"\"submit\"\" value=\"\"Upload\"\" /></div></form>\";\n\n            // Act\n            var result1 = FileUpload._GetHtml(context, name: null, initialNumberOfFiles: 1, allowMoreFilesToBeAdded: true, includeFormTag: false, addText: null, uploadText: null);\n            var result2 = FileUpload._GetHtml(context, name: null, initialNumberOfFiles: 1, allowMoreFilesToBeAdded: true, includeFormTag: true, addText: null, uploadText: null);\n            var result3 = FileUpload._GetHtml(context, name: null, initialNumberOfFiles: 1, allowMoreFilesToBeAdded: false, includeFormTag: true, addText: null, uploadText: null);\n\n            // Assert\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedResult1, result1.ToString());\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedResult2, result2.ToString());\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedResult3, result3.ToString());\n        }\n\n        [Fact]\n        public void FileUploadUsesNamePropertyInJavascript()\n        {\n            // Arrange\n            var context = GetContext();\n            string name = \"foobar\";\n            string expectedResult = _fileUploadScript\n                                    + @\"<form action=\"\"\"\" enctype=\"\"multipart/form-data\"\" method=\"\"post\"\"><div class=\"\"file-upload\"\" id=\"\"file-upload-0\"\"><div><input name=\"\"foobar\"\" type=\"\"file\"\" /></div></div>\"\n                                    + @\"<div class=\"\"file-upload-buttons\"\"><a href=\"\"#\"\" onclick=\"\"FileUploadHelper.addInputElement(0, &quot;foobar&quot;); return false;\"\">Add more files</a><input type=\"\"submit\"\" value=\"\"Upload\"\" /></div></form>\";\n\n            // Act\n            var result = FileUpload._GetHtml(context, name: name, initialNumberOfFiles: 1, allowMoreFilesToBeAdded: true, includeFormTag: true, addText: null, uploadText: null);\n\n            // Assert\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedResult, result.ToString());\n        }\n\n        [Fact]\n        public void _GetHtmlWithDefaultArgumentsProducesValidXhtml()\n        {\n            // Act \n            var result = FileUpload._GetHtml(GetContext(), name: null, initialNumberOfFiles: 1, includeFormTag: false, allowMoreFilesToBeAdded: false, addText: null, uploadText: null);\n\n            // Assert\n            XhtmlAssert.Validate1_1(result, \"div\");\n        }\n\n        [Fact]\n        public void _GetHtmlWithoutFormTagProducesValidXhtml()\n        {\n            // Act\n            var result = FileUpload._GetHtml(GetContext(), name: null, includeFormTag: false, initialNumberOfFiles: 1, allowMoreFilesToBeAdded: false, addText: null, uploadText: null);\n\n            XhtmlAssert.Validate1_1(result, \"div\");\n        }\n\n        private HttpContextBase GetContext()\n        {\n            var context = new Mock<HttpContextBase>();\n            context.Setup(c => c.Items).Returns(new Hashtable());\n            return context.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Helpers.Test/GamerCardTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Helpers.Test;\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Helpers.Test\n{\n    public class GamerCardTest\n    {\n        [Fact]\n        public void RenderThrowsWhenGamertagIsEmpty()\n        {\n            // Act & Assert \n            Assert.ThrowsArgumentNullOrEmptyString(() => { GamerCard.GetHtml(String.Empty).ToString(); }, \"gamerTag\");\n        }\n\n        [Fact]\n        public void RenderThrowsWhenGamertagIsNull()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmptyString(() => { GamerCard.GetHtml(null).ToString(); }, \"gamerTag\");\n        }\n\n        [Fact]\n        public void RenderGeneratesProperMarkupWithSimpleGamertag()\n        {\n            // Arrange \n            string expectedHtml = \"<iframe frameborder=\\\"0\\\" height=\\\"140\\\" scrolling=\\\"no\\\" src=\\\"http://gamercard.xbox.com/osbornm.card\\\" width=\\\"204\\\">osbornm</iframe>\";\n\n            // Act\n            string html = GamerCard.GetHtml(\"osbornm\").ToHtmlString();\n\n            // Assert\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedHtml, html);\n        }\n\n        [Fact]\n        public void RenderGeneratesProperMarkupWithComplexGamertag()\n        {\n            // Arrange \n            string expectedHtml = \"<iframe frameborder=\\\"0\\\" height=\\\"140\\\" scrolling=\\\"no\\\" src=\\\"http://gamercard.xbox.com/matthew%20osborn&#39;s.card\\\" width=\\\"204\\\">matthew osborn&#39;s</iframe>\";\n\n            // Act\n            string html = GamerCard.GetHtml(\"matthew osborn's\").ToHtmlString();\n\n            // Assert\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedHtml, html);\n        }\n\n        [Fact]\n        public void RenderGeneratesValidXhtml()\n        {\n            XhtmlAssert.Validate1_0(\n                GamerCard.GetHtml(\"osbornm\")\n                );\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Helpers.Test/GravatarTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Helpers.Test;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Helpers.Test\n{\n    public class GravatarTest\n    {\n        [Fact]\n        public void GetUrlDefaults()\n        {\n            string url = Gravatar.GetUrl(\"foo@bar.com\");\n            Assert.Equal(\"http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?s=80\", url);\n        }\n\n        [Fact]\n        public void RenderEncodesDefaultImageUrl()\n        {\n            string render = Gravatar.GetHtml(\"foo@bar.com\", defaultImage: \"http://example.com/images/example.jpg\").ToString();\n            Assert.Equal(\n                \"<img src=\\\"http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?s=80&amp;d=http%3a%2f%2fexample.com%2fimages%2fexample.jpg\\\" alt=\\\"gravatar\\\" />\",\n                render);\n        }\n\n        [Fact]\n        public void RenderLowerCasesEmail()\n        {\n            string render = Gravatar.GetHtml(\"FOO@BAR.COM\").ToString();\n            Assert.Equal(\n                \"<img src=\\\"http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?s=80\\\" alt=\\\"gravatar\\\" />\",\n                render);\n        }\n\n        [Fact]\n        public void RendersValidXhtml()\n        {\n            XhtmlAssert.Validate1_1(Gravatar.GetHtml(\"foo@bar.com\"));\n        }\n\n        [Fact]\n        public void RenderThrowsWhenEmailIsEmpty()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(() => { Gravatar.GetHtml(String.Empty); }, \"email\");\n        }\n\n        [Fact]\n        public void RenderThrowsWhenEmailIsNull()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(() => { Gravatar.GetHtml(null); }, \"email\");\n        }\n\n        [Fact]\n        public void RenderThrowsWhenImageSizeIsLessThanZero()\n        {\n            Assert.ThrowsArgument(() => { Gravatar.GetHtml(\"foo@bar.com\", imageSize: -1); }, \"imageSize\", \"The Gravatar image size must be between 1 and 512 pixels.\");\n        }\n\n        [Fact]\n        public void RenderThrowsWhenImageSizeIsZero()\n        {\n            Assert.ThrowsArgument(() => { Gravatar.GetHtml(\"foo@bar.com\", imageSize: 0); }, \"imageSize\", \"The Gravatar image size must be between 1 and 512 pixels.\");\n        }\n\n        [Fact]\n        public void RenderThrowsWhenImageSizeIsGreaterThan512()\n        {\n            Assert.ThrowsArgument(() => { Gravatar.GetHtml(\"foo@bar.com\", imageSize: 513); }, \"imageSize\", \"The Gravatar image size must be between 1 and 512 pixels.\");\n        }\n\n        [Fact]\n        public void RenderTrimsEmail()\n        {\n            string render = Gravatar.GetHtml(\" \\t foo@bar.com\\t\\r\\n\").ToString();\n            Assert.Equal(\n                \"<img src=\\\"http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?s=80\\\" alt=\\\"gravatar\\\" />\",\n                render);\n        }\n\n        [Fact]\n        public void RenderUsesDefaultImage()\n        {\n            string render = Gravatar.GetHtml(\"foo@bar.com\", defaultImage: \"wavatar\").ToString();\n            Assert.Equal(\n                \"<img src=\\\"http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?s=80&amp;d=wavatar\\\" alt=\\\"gravatar\\\" />\",\n                render);\n        }\n\n        [Fact]\n        public void RenderUsesImageSize()\n        {\n            string render = Gravatar.GetHtml(\"foo@bar.com\", imageSize: 512).ToString();\n            Assert.Equal(\n                \"<img src=\\\"http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?s=512\\\" alt=\\\"gravatar\\\" />\",\n                render);\n        }\n\n        [Fact]\n        public void RenderUsesRating()\n        {\n            string render = Gravatar.GetHtml(\"foo@bar.com\", rating: GravatarRating.G).ToString();\n            Assert.Equal(\n                \"<img src=\\\"http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?s=80&amp;r=g\\\" alt=\\\"gravatar\\\" />\",\n                render);\n        }\n\n        [Fact]\n        public void RenderWithAttributes()\n        {\n            string render = Gravatar.GetHtml(\"foo@bar.com\",\n                                             attributes: new { id = \"gravatar\", alT = \"<b>foo@bar.com</b>\", srC = \"ignored\" }).ToString();\n            // beware of attributes ordering in tests\n            Assert.Equal(\n                \"<img src=\\\"http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?s=80\\\" alT=\\\"&lt;b>foo@bar.com&lt;/b>\\\" id=\\\"gravatar\\\" />\",\n                render);\n        }\n\n        [Fact]\n        public void RenderWithDefaults()\n        {\n            string render = Gravatar.GetHtml(\"foo@bar.com\").ToString();\n            Assert.Equal(\n                \"<img src=\\\"http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8?s=80\\\" alt=\\\"gravatar\\\" />\",\n                render);\n        }\n\n        [Fact]\n        public void RenderWithExtension()\n        {\n            string render = Gravatar.GetHtml(\"foo@bar.com\", imageExtension: \".png\").ToString();\n            Assert.Equal(\n                \"<img src=\\\"http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8.png?s=80\\\" alt=\\\"gravatar\\\" />\",\n                render);\n\n            render = Gravatar.GetHtml(\"foo@bar.com\", imageExtension: \"xyz\").ToString();\n            Assert.Equal(\n                \"<img src=\\\"http://www.gravatar.com/avatar/f3ada405ce890b6f8204094deb12d8a8.xyz?s=80\\\" alt=\\\"gravatar\\\" />\",\n                render);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Helpers.Test/LinkShareTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Linq;\nusing System.Web;\nusing System.Web.Helpers.Test;\nusing System.Web.TestUtil;\nusing System.Web.WebPages.Scope;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Helpers.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")]\n    public class LinkShareTest : IDisposable\n    {\n        private static LinkShareSite[] _allLinkShareSites = new[]\n        {\n            LinkShareSite.Delicious, LinkShareSite.Digg,\n            LinkShareSite.Facebook, LinkShareSite.Reddit, LinkShareSite.StumbleUpon, LinkShareSite.Twitter\n        };\n\n        [Fact]\n        public void RenderWithFacebookFirst_ReturnsHtmlWithFacebookAndThenOthersTest()\n        {\n            string pageTitle = \"page1\";\n            string pageLinkBack = \"page link back\";\n            string twitterUserName = String.Empty;\n            string twitterTag = String.Empty;\n            string actual;\n            actual = LinkShare.GetHtml(pageTitle, pageLinkBack, twitterUserName, twitterTag, LinkShareSite.Facebook, LinkShareSite.All).ToString();\n            Assert.Contains(\"twitter.com\", actual);\n            int pos = actual.IndexOf(\"facebook.com\");\n            Assert.True(pos > 0);\n            int pos2 = actual.IndexOf(\"reddit.com\");\n            Assert.True(pos2 > pos);\n            pos2 = actual.IndexOf(\"digg.com\");\n            Assert.True(pos2 > pos);\n        }\n\n        [Fact]\n        public void BitlyApiKeyThrowsWhenSetToNull()\n        {\n            Assert.ThrowsArgumentNull(() => LinkShare.BitlyApiKey = null, \"value\");\n        }\n\n        [Fact]\n        public void BitlyApiKeyUsesScopeStorage()\n        {\n            // Arrange\n            var value = \"value\";\n\n            // Act\n            LinkShare.BitlyApiKey = value;\n\n            // Assert\n            Assert.Equal(LinkShare.BitlyApiKey, value);\n            Assert.Equal(ScopeStorage.CurrentScope[LinkShare._bitlyApiKey], value);\n        }\n\n        [Fact]\n        public void BitlyLoginThrowsWhenSetToNull()\n        {\n            Assert.ThrowsArgumentNull(() => LinkShare.BitlyLogin = null, \"value\");\n        }\n\n        [Fact]\n        public void BitlyLoginUsesScopeStorage()\n        {\n            // Arrange\n            var value = \"value\";\n\n            // Act\n            LinkShare.BitlyLogin = value;\n\n            // Assert\n            Assert.Equal(LinkShare.BitlyLogin, value);\n            Assert.Equal(ScopeStorage.CurrentScope[LinkShare._bitlyLogin], value);\n        }\n\n        [Fact]\n        public void RenderWithNullPageTitle_ThrowsException()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(\n                () => LinkShare.GetHtml(null).ToString(),\n                \"pageTitle\");\n        }\n\n        [Fact]\n        public void Render_WithFacebook_Works()\n        {\n            string actualHTML = LinkShare.GetHtml(\"page-title\", \"www.foo.com\", linkSites: LinkShareSite.Facebook).ToString();\n            string expectedHTML =\n                \"<a href=\\\"http://www.facebook.com/sharer.php?u=www.foo.com&amp;t=page-title\\\" target=\\\"_blank\\\" title=\\\"Share on Facebook\\\"><img alt=\\\"Share on Facebook\\\" src=\\\"http://facebook.com/favicon.ico\\\" style=\\\"border:0; height:16px; width:16px; margin:0 1px;\\\" title=\\\"Share on Facebook\\\" /></a>\";\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(actualHTML, expectedHTML);\n        }\n\n        [Fact]\n        public void Render_WithFacebookAndDigg_Works()\n        {\n            string actualHTML = LinkShare.GetHtml(\"page-title\", \"www.foo.com\", linkSites: new[] { LinkShareSite.Facebook, LinkShareSite.Digg }).ToString();\n            string expectedHTML =\n                \"<a href=\\\"http://www.facebook.com/sharer.php?u=www.foo.com&amp;t=page-title\\\" target=\\\"_blank\\\" title=\\\"Share on Facebook\\\"><img alt=\\\"Share on Facebook\\\" src=\\\"http://facebook.com/favicon.ico\\\" style=\\\"border:0; height:16px; width:16px; margin:0 1px;\\\" title=\\\"Share on Facebook\\\" /></a><a href=\\\"http://digg.com/submit?url=www.foo.com&amp;title=page-title\\\" target=\\\"_blank\\\" title=\\\"Digg!\\\"><img alt=\\\"Digg!\\\" src=\\\"http://digg.com/favicon.ico\\\" style=\\\"border:0; height:16px; width:16px; margin:0 1px;\\\" title=\\\"Digg!\\\" /></a>\";\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(actualHTML, expectedHTML);\n        }\n\n        [Fact]\n        public void Render_WithFacebook_RendersAnchorTitle()\n        {\n            string actualHTML = LinkShare.GetHtml(\"page-title\", \"www.foo.com\", linkSites: LinkShareSite.Facebook).ToString();\n            string expectedHtml = @\"<a href=\"\"http://www.facebook.com/sharer.php?u=www.foo.com&amp;t=page-title\"\" target=\"\"_blank\"\" title=\"\"Share on Facebook\"\">\n                <img alt=\"\"Share on Facebook\"\" src=\"\"http://facebook.com/favicon.ico\"\" style=\"\"border:0; height:16px; width:16px; margin:0 1px;\"\" title=\"\"Share on Facebook\"\" />\n                </a>\";\n\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedHtml, actualHTML);\n        }\n\n        [Fact]\n        public void LinkShare_GetSitesInOrderReturnsAllSitesWhenArgumentIsNull()\n        {\n            // Act and Assert\n            var result = LinkShare.GetSitesInOrder(linkSites: null);\n\n            Assert.Equal(_allLinkShareSites, result.ToArray());\n        }\n\n        [Fact]\n        public void LinkShare_GetSitesInOrderReturnsAllSitesWhenArgumentIEmpty()\n        {\n            // Act\n            var result = LinkShare.GetSitesInOrder(linkSites: new LinkShareSite[] { });\n\n            // Assert\n            Assert.Equal(_allLinkShareSites, result.ToArray());\n        }\n\n        [Fact]\n        public void LinkShare_GetSitesInOrderDoesNotReturnsGoogleBuzzForAll() {\n            // Act\n            var result = LinkShare.GetSitesInOrder(linkSites: new LinkShareSite[] { LinkShareSite.All });\n\n            // Assert\n            // 2 is the deprecated value for GoogleBuzz\n            Assert.DoesNotContain(((LinkShareSite)2), result.ToArray());\n        }\n\n        [Fact]\n        public void LinkShare_GetSitesInOrderReturnsAllSitesWhenAllIsFirstItem()\n        {\n            // Act\n            var result = LinkShare.GetSitesInOrder(linkSites: new[] { LinkShareSite.All, LinkShareSite.Reddit });\n\n            // Assert\n            Assert.Equal(_allLinkShareSites, result.ToArray());\n        }\n\n        [Fact]\n        public void LinkShare_GetSitesInOrderReturnsSitesInOrderWhenAllIsNotFirstItem()\n        {\n            // Act\n            var result = LinkShare.GetSitesInOrder(linkSites: new[] { LinkShareSite.Reddit, LinkShareSite.Facebook, LinkShareSite.All });\n\n            // Assert\n            Assert.Equal(new[]\n            {\n                LinkShareSite.Reddit, LinkShareSite.Facebook, LinkShareSite.Delicious, LinkShareSite.Digg, LinkShareSite.StumbleUpon, LinkShareSite.Twitter\n            }, result.ToArray());\n        }\n\n        [Fact]\n        public void LinkShare_EncodesParameters()\n        {\n            // Arrange\n            var expectedHtml =\n                @\"<a href=\"\"http://reddit.com/submit?url=www.foo.com&amp;title=%26%26\"\" target=\"\"_blank\"\" title=\"\"Reddit!\"\">\n                    <img alt=\"\"Reddit!\"\" src=\"\"http://www.Reddit.com/favicon.ico\"\" style=\"\"border:0; height:16px; width:16px; margin:0 1px;\"\" title=\"\"Reddit!\"\" />\n                </a>\n                <a href=\"\"http://twitter.com/home/?status=%26%26%3a+www.foo.com%2c+(via+%40%40%3cTweeter+Bot%3e)+I+%3c3+Tweets\"\" target=\"\"_blank\"\" title=\"\"Share on Twitter\"\">\n                    <img alt=\"\"Share on Twitter\"\" src=\"\"http://twitter.com/favicon.ico\"\" style=\"\"border:0; height:16px; width:16px; margin:0 1px;\"\" title=\"\"Share on Twitter\"\" />\n                </a>\";\n\n            // Act\n            var actualHtml = LinkShare.GetHtml(\"&&\", \"www.foo.com\", \"<Tweeter Bot>\", \"I <3 Tweets\", LinkShareSite.Reddit, LinkShareSite.Twitter).ToString();\n\n            // Assert\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(expectedHtml, actualHtml);\n        }\n\n        [Fact]\n        public void LinkshareRendersValidXhtml()\n        {\n            string result = \"<html> <head> \\n <title> </title> \\n </head> \\n <body> <div> \\n\" +\n                            LinkShare.GetHtml(\"any<>title\", \"my test page <>\") +\n                            \"\\n </div> </body> \\n </html>\";\n            HtmlString htmlResult = new HtmlString(result);\n            XhtmlAssert.Validate1_0(htmlResult);\n        }\n\n        public void Dispose()\n        {\n            // Reset ScopeStorage (written via e.g. LinkShare.BitlyApiKey) between tests to avoid unexpected interactions.\n            ScopeStorage.CurrentProvider = new StaticScopeStorageProvider();\n            ScopeStorage.GlobalScope.Clear();\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Helpers.Test/MapsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections;\nusing System.Linq;\nusing System.Web;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace Microsoft.Web.Helpers.Test\n{\n    public class MapsTest\n    {\n        [Fact]\n        public void GetDirectionsQueryReturnsLocationIfNotEmpty()\n        {\n            // Arrange\n            var location = \"a%\";\n            var latitude = \"12.34\";\n            var longitude = \"-56.78\";\n\n            // Act\n            string result = Maps.GetDirectionsQuery(location, latitude, longitude);\n\n            // Assert\n            Assert.Equal(\"a%25\", result);\n        }\n\n        [Fact]\n        public void GetDirectionsQueryReturnsLatitudeLongitudeIfLocationIsEmpty()\n        {\n            // Arrange\n            var location = \"\";\n            var latitude = \"12.34%\";\n            var longitude = \"-&56.78\";\n\n            // Act\n            string result = Maps.GetDirectionsQuery(location, latitude, longitude);\n\n            // Assert\n            Assert.Equal(\"12.34%25%2c-%2656.78\", result);\n        }\n\n        [Fact]\n        public void GetDirectionsQueryUsesSpecifiedEncoder()\n        {\n            // Arrange\n            var location = \"24 gnidliuB tfosorciM\";\n            var latitude = \"12.34%\";\n            var longitude = \"-&56.78\";\n            Func<string, string> encoder = k => new String(k.Reverse().ToArray());\n\n            // Act\n            string result = Maps.GetDirectionsQuery(location, latitude, longitude, encoder);\n\n            // Assert\n            Assert.Equal(\"Microsoft Building 42\", result);\n        }\n\n        [Fact]\n        public void GetProviderHtml_DoesNotContainBadRazorCompilation()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                // Arrange\n                var stubbedContext = new Mock<HttpContextBase>();\n                var contextItems = new Hashtable();\n                stubbedContext.SetupGet(x => x.Items).Returns(contextItems);\n                Maps.GetCurrentHttpContext = () => stubbedContext.Object;\n\n                // Act\n                string bingResults = Maps.GetBingHtml(\"somekey\", latitude: \"100\", longitude: \"10\").ToHtmlString();\n                string googleResults = Maps.GetGoogleHtml(latitude: \"100\", longitude: \"10\").ToHtmlString();\n                string mapQuestResults = Maps.GetMapQuestHtml(\"somekey\", latitude: \"100\", longitude: \"10\").ToHtmlString();\n\n                // Assert\n                Assert.DoesNotContain(\"<text>\", bingResults);\n                Assert.DoesNotContain(\"<text>\", googleResults);\n                Assert.DoesNotContain(\"<text>\", mapQuestResults);\n            });\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Helpers.Test/Microsoft.Web.Helpers.Test.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props\" Condition=\"Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" />\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" />\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{2C653A66-8159-4A41-954F-A67915DFDA87}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>Microsoft.Web.Helpers.Test</RootNamespace>\n    <AssemblyName>Microsoft.Web.Helpers.Test</AssemblyName>\n    <OutputPath>..\\..\\bin\\$(Configuration)\\Test\\</OutputPath>\n    <NuGetPackageImportStamp>\n    </NuGetPackageImportStamp>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Castle.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Castle.Core.5.1.1\\lib\\net462\\Castle.Core.dll</HintPath>\n    </Reference>\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"Moq, Version=4.18.0.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Moq.4.18.4\\lib\\net462\\Moq.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.abstractions.2.0.3\\lib\\net35\\xunit.abstractions.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.assert, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.assert.2.4.2\\lib\\netstandard1.1\\xunit.assert.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.core, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.core.2.4.2\\lib\\net452\\xunit.core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.execution.desktop, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.execution.2.4.2\\lib\\net452\\xunit.execution.desktop.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"AnalyticsTest.cs\" />\n    <Compile Include=\"FacebookTest.cs\" />\n    <Compile Include=\"FileUploadTest.cs\" />\n    <Compile Include=\"GamerCardTest.cs\" />\n    <Compile Include=\"GravatarTest.cs\" />\n    <Compile Include=\"LinkShareTest.cs\" />\n    <Compile Include=\"MapsTest.cs\" />\n    <Compile Include=\"PreAppStartCodeTest.cs\" />\n    <Compile Include=\"ThemesTest.cs\" />\n    <Compile Include=\"VideoTest.cs\" />\n    <Compile Include=\"ReCaptchaTest.cs\" />\n    <Compile Include=\"UrlBuilderTest.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\..\\src\\Microsoft.Web.Helpers\\Microsoft.Web.Helpers.csproj\">\n      <Project>{0C7CE809-0F72-4C19-8C64-D6573E4D9521}</Project>\n      <Name>Microsoft.Web.Helpers</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Helpers\\System.Web.Helpers.csproj\">\n      <Project>{9B7E3740-6161-4548-833C-4BBCA43B970E}</Project>\n      <Name>System.Web.Helpers</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Razor\\System.Web.Razor.csproj\">\n      <Project>{8F18041B-9410-4C36-A9C5-067813DF5F31}</Project>\n      <Name>System.Web.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.WebPages.Razor\\System.Web.WebPages.Razor.csproj\">\n      <Project>{0939B11A-FE4E-4BA1-8AD6-D97741EE314F}</Project>\n      <Name>System.Web.WebPages.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.WebPages\\System.Web.WebPages.csproj\">\n      <Project>{76EFA9C5-8D7E-4FDF-B710-E20F8B6B00D2}</Project>\n      <Name>System.Web.WebPages</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\">\n      <Project>{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}</Project>\n      <Name>Microsoft.TestCommon</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.Helpers.Test\\System.Web.Helpers.Test.csproj\">\n      <Project>{D3313BDF-8071-4AC8-9D98-ABF7F9E88A57}</Project>\n      <Name>System.Web.Helpers.Test</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Service Include=\"{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Analyzer Include=\"..\\..\\packages\\xunit.analyzers.1.1.0\\analyzers\\dotnet\\cs\\xunit.analyzers.dll\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\n  <Target Name=\"EnsureNuGetPackageBuildImports\" BeforeTargets=\"PrepareForBuild\">\n    <PropertyGroup>\n      <ErrorText>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}.</ErrorText>\n    </PropertyGroup>\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props'))\" />\n  </Target>\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" />\n</Project>"
  },
  {
    "path": "test/Microsoft.Web.Helpers.Test/PreAppStartCodeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.WebPages.Razor;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Helpers.Test\n{\n    public class PreApplicationStartCodeTest\n    {\n        [Fact]\n        public void StartTest()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                // Act\n                AppDomainUtils.SetPreAppStartStage();\n                PreApplicationStartCode.Start();\n\n                // Assert\n                var imports = WebPageRazorHost.GetGlobalImports();\n                Assert.Contains(imports, ns => ns.Equals(\"Microsoft.Web.Helpers\"));\n            });\n        }\n\n        [Fact]\n        public void TestPreAppStartClass()\n        {\n            PreAppStartTestHelper.TestPreAppStartClass(typeof(PreApplicationStartCode));\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Helpers.Test/ReCaptchaTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Web;\nusing System.Web.Helpers.Test;\nusing System.Web.TestUtil;\nusing System.Web.WebPages.Scope;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace Microsoft.Web.Helpers.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")]\n    public class ReCaptchaTest : IDisposable\n    {\n        [Fact]\n        public void ReCaptchaOptionsMissingWhenNoOptionsAndDefaultRendering()\n        {\n            var html = ReCaptcha.GetHtml(GetContext(), \"PUBLIC_KEY\");\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(\n                @\"<script src=\"\"http://www.google.com/recaptcha/api/challenge?k=PUBLIC_KEY\"\" type=\"\"text/javascript\"\"></script>\" +\n                @\"<noscript>\" +\n                @\"<iframe frameborder=\"\"0\"\" height=\"\"300px\"\" src=\"\"http://www.google.com/recaptcha/api/noscript?k=PUBLIC_KEY\"\" width=\"\"500px\"\"></iframe><br/><br/>\" +\n                @\"<textarea cols=\"\"40\"\" name=\"\"recaptcha_challenge_field\"\" rows=\"\"3\"\"></textarea>\" +\n                @\"<input name=\"\"recaptcha_response_field\"\" type=\"\"hidden\"\" value=\"\"manual_challenge\"\"/>\" +\n                @\"</noscript>\",\n                html.ToString());\n            XhtmlAssert.Validate1_0(html, addRoot: true);\n        }\n\n        [Fact]\n        public void ReCaptchaOptionsWhenOneOptionAndDefaultRendering()\n        {\n            var html = ReCaptcha.GetHtml(GetContext(), \"PUBLIC_KEY\", options: new { theme = \"white\" });\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(\n                @\"<script type=\"\"text/javascript\"\">var RecaptchaOptions={\"\"theme\"\":\"\"white\"\"};</script>\" +\n                @\"<script src=\"\"http://www.google.com/recaptcha/api/challenge?k=PUBLIC_KEY\"\" type=\"\"text/javascript\"\"></script>\" +\n                @\"<noscript>\" +\n                @\"<iframe frameborder=\"\"0\"\" height=\"\"300px\"\" src=\"\"http://www.google.com/recaptcha/api/noscript?k=PUBLIC_KEY\"\" width=\"\"500px\"\"></iframe><br/><br/>\" +\n                @\"<textarea cols=\"\"40\"\" name=\"\"recaptcha_challenge_field\"\" rows=\"\"3\"\"></textarea>\" +\n                @\"<input name=\"\"recaptcha_response_field\"\" type=\"\"hidden\"\" value=\"\"manual_challenge\"\"/>\" +\n                @\"</noscript>\",\n                html.ToString());\n            XhtmlAssert.Validate1_0(html, addRoot: true);\n        }\n\n        [Fact]\n        public void ReCaptchaOptionsWhenMultipleOptionsAndDefaultRendering()\n        {\n            var html = ReCaptcha.GetHtml(GetContext(), \"PUBLIC_KEY\", options: new { theme = \"white\", tabindex = 5 });\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(\n                @\"<script type=\"\"text/javascript\"\">var RecaptchaOptions={\"\"theme\"\":\"\"white\"\",\"\"tabindex\"\":5};</script>\" +\n                @\"<script src=\"\"http://www.google.com/recaptcha/api/challenge?k=PUBLIC_KEY\"\" type=\"\"text/javascript\"\"></script>\" +\n                @\"<noscript>\" +\n                @\"<iframe frameborder=\"\"0\"\" height=\"\"300px\"\" src=\"\"http://www.google.com/recaptcha/api/noscript?k=PUBLIC_KEY\"\" width=\"\"500px\"\"></iframe><br/><br/>\" +\n                @\"<textarea cols=\"\"40\"\" name=\"\"recaptcha_challenge_field\"\" rows=\"\"3\"\"></textarea>\" +\n                @\"<input name=\"\"recaptcha_response_field\"\" type=\"\"hidden\"\" value=\"\"manual_challenge\"\"/>\" +\n                @\"</noscript>\",\n                html.ToString());\n            XhtmlAssert.Validate1_0(html, addRoot: true);\n        }\n\n        [Fact]\n        public void ReCaptchaOptionsWhenMultipleOptionsFromDictionaryAndDefaultRendering()\n        {\n            // verifies that a dictionary will serialize the same as a projection\n            var options = new Dictionary<string, object> { { \"theme\", \"white\" }, { \"tabindex\", 5 } };\n            var html = ReCaptcha.GetHtml(GetContext(), \"PUBLIC_KEY\", options: options);\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(\n                @\"<script type=\"\"text/javascript\"\">var RecaptchaOptions={\"\"theme\"\":\"\"white\"\",\"\"tabindex\"\":5};</script>\" +\n                @\"<script src=\"\"http://www.google.com/recaptcha/api/challenge?k=PUBLIC_KEY\"\" type=\"\"text/javascript\"\"></script>\" +\n                @\"<noscript>\" +\n                @\"<iframe frameborder=\"\"0\"\" height=\"\"300px\"\" src=\"\"http://www.google.com/recaptcha/api/noscript?k=PUBLIC_KEY\"\" width=\"\"500px\"\"></iframe><br/><br/>\" +\n                @\"<textarea cols=\"\"40\"\" name=\"\"recaptcha_challenge_field\"\" rows=\"\"3\"\"></textarea>\" +\n                @\"<input name=\"\"recaptcha_response_field\"\" type=\"\"hidden\"\" value=\"\"manual_challenge\"\"/>\" +\n                @\"</noscript>\",\n                html.ToString());\n            XhtmlAssert.Validate1_0(html, addRoot: true);\n        }\n\n        [Fact]\n        public void RenderUsesLastError()\n        {\n            HttpContextBase context = GetContext();\n            ReCaptcha.HandleValidateResponse(context, \"false\\nincorrect-captcha-sol\");\n            var html = ReCaptcha.GetHtml(context, \"PUBLIC_KEY\");\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(\n                @\"<script src=\"\"http://www.google.com/recaptcha/api/challenge?k=PUBLIC_KEY&amp;error=incorrect-captcha-sol\"\" type=\"\"text/javascript\"\"></script>\" +\n                @\"<noscript>\" +\n                @\"<iframe frameborder=\"\"0\"\" height=\"\"300px\"\" src=\"\"http://www.google.com/recaptcha/api/noscript?k=PUBLIC_KEY\"\" width=\"\"500px\"\"></iframe><br/><br/>\" +\n                @\"<textarea cols=\"\"40\"\" name=\"\"recaptcha_challenge_field\"\" rows=\"\"3\"\"></textarea>\" +\n                @\"<input name=\"\"recaptcha_response_field\"\" type=\"\"hidden\"\" value=\"\"manual_challenge\"\"/>\" +\n                @\"</noscript>\",\n                html.ToString());\n            XhtmlAssert.Validate1_0(html, addRoot: true);\n        }\n\n        [Fact]\n        public void RenderWhenConnectionIsSecure()\n        {\n            var html = ReCaptcha.GetHtml(GetContext(isSecure: true), \"PUBLIC_KEY\");\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(\n                @\"<script src=\"\"https://www.google.com/recaptcha/api/challenge?k=PUBLIC_KEY\"\" type=\"\"text/javascript\"\"></script>\" +\n                @\"<noscript>\" +\n                @\"<iframe frameborder=\"\"0\"\" height=\"\"300px\"\" src=\"\"https://www.google.com/recaptcha/api/noscript?k=PUBLIC_KEY\"\" width=\"\"500px\"\"></iframe><br/><br/>\" +\n                @\"<textarea cols=\"\"40\"\" name=\"\"recaptcha_challenge_field\"\" rows=\"\"3\"\"></textarea>\" +\n                @\"<input name=\"\"recaptcha_response_field\"\" type=\"\"hidden\"\" value=\"\"manual_challenge\"\"/>\" +\n                @\"</noscript>\",\n                html.ToString());\n            XhtmlAssert.Validate1_0(html, addRoot: true);\n        }\n\n        [Fact]\n        public void ValidateThrowsWhenRemoteAddressNotAvailable()\n        {\n            HttpContextBase context = GetContext();\n            VirtualPathUtilityBase virtualPathUtility = GetVirtualPathUtility();\n            context.Request.Form[\"recaptcha_challenge_field\"] = \"CHALLENGE\";\n            context.Request.Form[\"recaptcha_response_field\"] = \"RESPONSE\";\n\n            Assert.Throws<InvalidOperationException>(() => { ReCaptcha.Validate(context, privateKey: \"PRIVATE_KEY\", virtualPathUtility: virtualPathUtility).ToString(); }, \"The captcha cannot be validated because the remote address was not found in the request.\");\n        }\n\n        [Fact]\n        public void ValidateReturnsFalseWhenChallengeNotPosted()\n        {\n            HttpContextBase context = GetContext();\n            VirtualPathUtilityBase virtualPathUtility = GetVirtualPathUtility();\n            context.Request.ServerVariables[\"REMOTE_ADDR\"] = \"127.0.0.1\";\n\n            Assert.False(ReCaptcha.Validate(context, privateKey: \"PRIVATE_KEY\", virtualPathUtility: virtualPathUtility));\n        }\n\n        [Fact]\n        public void ValidatePostData()\n        {\n            HttpContextBase context = GetContext();\n            VirtualPathUtilityBase virtualPathUtility = GetVirtualPathUtility();\n            context.Request.ServerVariables[\"REMOTE_ADDR\"] = \"127.0.0.1\";\n            context.Request.Form[\"recaptcha_challenge_field\"] = \"CHALLENGE\";\n            context.Request.Form[\"recaptcha_response_field\"] = \"RESPONSE\";\n\n            Assert.Equal(\"privatekey=PRIVATE_KEY&remoteip=127.0.0.1&challenge=CHALLENGE&response=RESPONSE\",\n                         ReCaptcha.GetValidatePostData(context, \"PRIVATE_KEY\", virtualPathUtility));\n        }\n\n        [Fact]\n        public void ValidatePostDataWhenNoResponse()\n        {\n            // Arrange\n            HttpContextBase context = GetContext();\n            VirtualPathUtilityBase virtualPathUtility = GetVirtualPathUtility();\n            context.Request.ServerVariables[\"REMOTE_ADDR\"] = \"127.0.0.1\";\n            context.Request.Form[\"recaptcha_challenge_field\"] = \"CHALLENGE\";\n\n            // Act\n            var validatePostData = ReCaptcha.GetValidatePostData(context, \"PRIVATE_KEY\", virtualPathUtility);\n\n            // Assert\n            Assert.Equal(\"privatekey=PRIVATE_KEY&remoteip=127.0.0.1&challenge=CHALLENGE&response=\", validatePostData);\n        }\n\n        [Fact]\n        public void ValidateResponseReturnsFalseOnEmptyReCaptchaResponse()\n        {\n            HttpContextBase context = GetContext();\n            Assert.False(ReCaptcha.HandleValidateResponse(context, \"\"));\n            Assert.Equal(String.Empty, ReCaptcha.GetLastError(context));\n        }\n\n        [Fact]\n        public void ValidateResponseReturnsTrueOnSuccess()\n        {\n            HttpContextBase context = GetContext();\n            Assert.True(ReCaptcha.HandleValidateResponse(context, \"true\\nsuccess\"));\n            Assert.Equal(String.Empty, ReCaptcha.GetLastError(context));\n        }\n\n        [Fact]\n        public void ValidateResponseReturnsFalseOnError()\n        {\n            HttpContextBase context = GetContext();\n            Assert.False(ReCaptcha.HandleValidateResponse(context, \"false\\nincorrect-captcha-sol\"));\n            Assert.Equal(\"incorrect-captcha-sol\", ReCaptcha.GetLastError(context));\n        }\n\n        [Fact]\n        public void ReCaptchaPrivateKeyThowsWhenSetToNull()\n        {\n            Assert.ThrowsArgumentNull(() => ReCaptcha.PrivateKey = null, \"value\");\n        }\n\n        [Fact]\n        public void ReCaptchaPrivateKeyUsesScopeStorage()\n        {\n            // Arrange\n            var value = \"value\";\n\n            // Act\n            ReCaptcha.PrivateKey = value;\n\n            // Assert\n            Assert.Equal(ReCaptcha.PrivateKey, value);\n            Assert.Equal(ScopeStorage.CurrentScope[ReCaptcha._privateKey], value);\n        }\n\n        [Fact]\n        public void PublicKeyThowsWhenSetToNull()\n        {\n            Assert.ThrowsArgumentNull(() => ReCaptcha.PublicKey = null, \"value\");\n        }\n\n        [Fact]\n        public void ReCaptchaPublicKeyUsesScopeStorage()\n        {\n            // Arrange\n            var value = \"value\";\n\n            // Act\n            ReCaptcha.PublicKey = value;\n\n            // Assert\n            Assert.Equal(ReCaptcha.PublicKey, value);\n            Assert.Equal(ScopeStorage.CurrentScope[ReCaptcha._publicKey], value);\n        }\n\n        private HttpContextBase GetContext(bool isSecure = false)\n        {\n            // mock HttpRequest\n            Mock<HttpRequestBase> requestMock = new Mock<HttpRequestBase>();\n            requestMock.Setup(request => request.IsSecureConnection).Returns(isSecure);\n            requestMock.Setup(request => request.Form).Returns(new NameValueCollection());\n            requestMock.Setup(request => request.ServerVariables).Returns(new NameValueCollection());\n\n            // mock HttpContext\n            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>();\n            contextMock.Setup(context => context.Items).Returns(new Hashtable());\n            contextMock.Setup(context => context.Request).Returns(requestMock.Object);\n            return contextMock.Object;\n        }\n\n        private static VirtualPathUtilityBase GetVirtualPathUtility()\n        {\n            var virtualPathUtility = new Mock<VirtualPathUtilityBase>();\n            virtualPathUtility.Setup(c => c.ToAbsolute(It.IsAny<string>())).Returns<string>(_ => _);\n\n            return virtualPathUtility.Object;\n        }\n\n        public void Dispose()\n        {\n            // Reset ScopeStorage (written via e.g. ReCaptcha.PrivateKey) between tests to avoid unexpected interactions.\n            ScopeStorage.CurrentProvider = new StaticScopeStorageProvider();\n            ScopeStorage.GlobalScope.Clear();\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Helpers.Test/ThemesTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Web.Hosting;\nusing System.Web.WebPages.Scope;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace Microsoft.Web.Helpers.Test\n{\n    public class ThemesTest\n    {\n        [Fact]\n        public void Initialize_WithBadParams_Throws()\n        {\n            // Arrange\n            var mockVpp = new Mock<VirtualPathProvider>().Object;\n            var scope = new ScopeStorageDictionary();\n\n            // Act and Assert\n            Assert.ThrowsArgumentNullOrEmptyString(() => new ThemesImplementation(mockVpp, scope).Initialize(null, \"foo\"), \"themeDirectory\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => new ThemesImplementation(mockVpp, scope).Initialize(\"\", \"foo\"), \"themeDirectory\");\n\n            Assert.ThrowsArgumentNullOrEmptyString(() => new ThemesImplementation(mockVpp, scope).Initialize(\"~/folder\", null), \"defaultTheme\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => new ThemesImplementation(mockVpp, scope).Initialize(\"~/folder\", \"\"), \"defaultTheme\");\n        }\n\n        [Fact]\n        public void CurrentThemeThrowsIfAssignedNullOrEmpty()\n        {\n            // Arrange\n            var mockVpp = new Mock<VirtualPathProvider>().Object;\n            var scope = new ScopeStorageDictionary();\n            var themesImpl = new ThemesImplementation(mockVpp, scope);\n\n            // Act and Assert\n            Assert.ThrowsArgumentNullOrEmptyString(() => { themesImpl.CurrentTheme = null; }, \"value\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => { themesImpl.CurrentTheme = String.Empty; }, \"value\");\n        }\n\n        [Fact]\n        public void InvokingPropertiesAndMethodsBeforeInitializationThrows()\n        {\n            // Arrange\n            var mockVpp = new Mock<VirtualPathProvider>().Object;\n            var scope = new ScopeStorageDictionary();\n            var themesImpl = new ThemesImplementation(mockVpp, scope);\n\n            // Act and Assert\n            Assert.Throws<InvalidOperationException>(() => themesImpl.CurrentTheme = \"Foo\",\n                                                              @\"You must call the \"\"Themes.Initialize\"\" method before you call any other method of the \"\"Themes\"\" class.\");\n\n            Assert.Throws<InvalidOperationException>(() => { var x = themesImpl.CurrentTheme; },\n                                                              @\"You must call the \"\"Themes.Initialize\"\" method before you call any other method of the \"\"Themes\"\" class.\");\n\n            Assert.Throws<InvalidOperationException>(() => { var x = themesImpl.AvailableThemes; },\n                                                              @\"You must call the \"\"Themes.Initialize\"\" method before you call any other method of the \"\"Themes\"\" class.\");\n\n            Assert.Throws<InvalidOperationException>(() => { var x = themesImpl.DefaultTheme; },\n                                                              @\"You must call the \"\"Themes.Initialize\"\" method before you call any other method of the \"\"Themes\"\" class.\");\n\n            Assert.Throws<InvalidOperationException>(() => { var x = themesImpl.GetResourcePath(\"baz\"); },\n                                                              @\"You must call the \"\"Themes.Initialize\"\" method before you call any other method of the \"\"Themes\"\" class.\");\n\n            Assert.Throws<InvalidOperationException>(() => { var x = themesImpl.GetResourcePath(\"baz\", \"some-file\"); },\n                                                              @\"You must call the \"\"Themes.Initialize\"\" method before you call any other method of the \"\"Themes\"\" class.\");\n        }\n\n        [Fact]\n        public void InitializeThrowsIfDefaultThemeDirectoryDoesNotExist()\n        {\n            // Arrange\n            var defaultTheme = \"default-theme\";\n            var themeDirectory = \"theme-directory\";\n\n            var scope = new ScopeStorageDictionary();\n            var themesImpl = new ThemesImplementation(GetVirtualPathProvider(themeDirectory, new Dir(\"not-default-theme\")), scope);\n\n            // Act And Assert\n            Assert.ThrowsArgument(\n                () => themesImpl.Initialize(themeDirectory: themeDirectory, defaultTheme: defaultTheme),\n                \"defaultTheme\",\n                \"Unknown theme 'default-theme'. Ensure that a directory labeled 'default-theme' exists under the theme directory.\");\n        }\n\n        [Fact]\n        public void ThemesImplUsesScopeStorageToStoreProperties()\n        {\n            // Arrange\n            var defaultTheme = \"default-theme\";\n            var themeDirectory = \"theme-directory\";\n\n            var scope = new ScopeStorageDictionary();\n            var themesImpl = new ThemesImplementation(GetVirtualPathProvider(themeDirectory, new Dir(defaultTheme)), scope);\n\n            // Act\n            themesImpl.Initialize(themeDirectory: themeDirectory, defaultTheme: defaultTheme);\n\n            // Ensure Theme use scope storage to store properties\n            Assert.Equal((object)true, scope[ThemesImplementation.ThemesInitializedKey]);\n            Assert.Equal(themeDirectory, scope[ThemesImplementation.ThemeDirectoryKey]);\n            Assert.Equal(defaultTheme, scope[ThemesImplementation.DefaultThemeKey]);\n        }\n\n        [Fact]\n        public void ThemesImplUsesDefaultThemeWhenNoCurrentThemeIsSpecified()\n        {\n            // Arrange\n            var defaultTheme = \"default-theme\";\n            var themeDirectory = \"theme-directory\";\n\n            var scope = new ScopeStorageDictionary();\n            var themesImpl = new ThemesImplementation(GetVirtualPathProvider(themeDirectory, new Dir(defaultTheme)), scope);\n            themesImpl.Initialize(themeDirectory, defaultTheme);\n\n            // Act and Assert\n            // CurrentTheme falls back to default theme when null\n            Assert.Equal(themesImpl.CurrentTheme, defaultTheme);\n        }\n\n        [Fact]\n        public void ThemesImplThrowsIfCurrentThemeIsInvalid()\n        {\n            // Arrange\n            var defaultTheme = \"default-theme\";\n            var themeDirectory = \"theme-directory\";\n            var themesImpl = new ThemesImplementation(GetVirtualPathProvider(themeDirectory, new Dir(defaultTheme), new Dir(\"not-a-random-value\")), new ScopeStorageDictionary());\n            themesImpl.Initialize(themeDirectory, defaultTheme);\n\n            // Act and Assert\n            Assert.ThrowsArgument(() => themesImpl.CurrentTheme = \"random-value\",\n                                                    \"value\",\n                                                    \"Unknown theme 'random-value'. Ensure that a directory labeled 'random-value' exists under the theme directory.\");\n        }\n\n        [Fact]\n        public void ThemesImplUsesScopeStorageToStoreCurrentTheme()\n        {\n            // Arrange\n            var defaultTheme = \"default-theme\";\n            var themeDirectory = \"theme-directory\";\n            var currentThemeDir = \"custom-theme-dir\";\n            var scope = new ScopeStorageDictionary();\n            var themesImpl = new ThemesImplementation(GetVirtualPathProvider(themeDirectory, new Dir(defaultTheme), new Dir(\"custom-theme-dir\")), scope);\n\n            // Act\n            themesImpl.Initialize(themeDirectory, defaultTheme);\n            themesImpl.CurrentTheme = currentThemeDir;\n\n            // Assert\n            Assert.Equal(scope[ThemesImplementation.CurrentThemeKey], currentThemeDir);\n        }\n\n        [Fact]\n        public void GetResourcePathThrowsIfCurrentDirectoryIsNull()\n        {\n            // Arrange\n            var themesImpl = new ThemesImplementation(scopeStorage: new ScopeStorageDictionary(),\n                                                      vpp: GetVirtualPathProvider(\"themes\", new Dir(\"default\"), new Dir(\"mobile\"), new Dir(@\"mobile\", \"wp7.css\")));\n            themesImpl.Initialize(\"themes\", \"default\");\n\n            // Act and Assert\n            Assert.ThrowsArgumentNull(() => themesImpl.GetResourcePath(folder: null, fileName: \"wp7.css\"), \"folder\");\n        }\n\n        [Fact]\n        public void GetResourcePathThrowsIfFileNameIsNullOrEmpty()\n        {\n            // Arrange\n            var themesImpl = new ThemesImplementation(scopeStorage: new ScopeStorageDictionary(),\n                                                      vpp: GetVirtualPathProvider(\"themes\", new Dir(\"default\"), new Dir(\"mobile\"), new Dir(@\"mobile\", \"wp7.css\")));\n            themesImpl.Initialize(\"themes\", \"default\");\n\n            // Act and Assert\n            Assert.ThrowsArgumentNullOrEmptyString(() => themesImpl.GetResourcePath(folder: String.Empty, fileName: null), \"fileName\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => themesImpl.GetResourcePath(folder: String.Empty, fileName: String.Empty), \"fileName\");\n        }\n\n        [Fact]\n        public void GetResourcePathReturnsItemFromThemeRootIfAvailable()\n        {\n            // Arrange\n            var themesImpl = new ThemesImplementation(scopeStorage: new ScopeStorageDictionary(),\n                                                      vpp: GetVirtualPathProvider(\"themes\", new Dir(\"default\"), new Dir(\"mobile\"), new Dir(@\"mobile\", \"wp7.css\")));\n            themesImpl.Initialize(\"themes\", \"default\");\n\n            // Act\n            themesImpl.CurrentTheme = \"mobile\";\n            var themePath = themesImpl.GetResourcePath(fileName: \"wp7.css\");\n\n            // Assert\n            Assert.Equal(@\"themes/mobile/wp7.css\", themePath);\n        }\n\n        [Fact]\n        public void GetResourcePathReturnsItemFromCurrentThemeDirectoryIfAvailable()\n        {\n            // Arrange\n            var themesImpl = new ThemesImplementation(scopeStorage: new ScopeStorageDictionary(),\n                                                      vpp: GetVirtualPathProvider(\"themes\", new Dir(\"default\"), new Dir(\"mobile\"), new Dir(@\"mobile\\styles\", \"wp7.css\"), new Dir(@\"default\\styles\", \"main.css\")));\n            themesImpl.Initialize(\"themes\", \"default\");\n\n            // Act\n            themesImpl.CurrentTheme = \"mobile\";\n            var themePath = themesImpl.GetResourcePath(folder: \"styles\", fileName: \"wp7.css\");\n\n            // Assert\n            Assert.Equal(@\"themes/mobile/styles/wp7.css\", themePath);\n        }\n\n        [Fact]\n        public void GetResourcePathReturnsItemFromDefaultThemeDirectoryIfNotFoundInCurrentThemeDirectory()\n        {\n            // Arrange\n            var themesImpl = new ThemesImplementation(scopeStorage: new ScopeStorageDictionary(),\n                                                      vpp: GetVirtualPathProvider(\"themes\", new Dir(\"default\"), new Dir(\"mobile\"), new Dir(@\"mobile\\styles\", \"wp7.css\"), new Dir(@\"default\\styles\", \"main.css\")));\n            themesImpl.Initialize(\"themes\", \"default\");\n\n            // Act\n            themesImpl.CurrentTheme = \"mobile\";\n            var themePath = themesImpl.GetResourcePath(folder: \"styles\", fileName: \"main.css\");\n\n            // Assert\n            Assert.Equal(@\"themes/default/styles/main.css\", themePath);\n        }\n\n        [Fact]\n        public void GetResourcePathReturnsNullIfDirectoryDoesNotExist()\n        {\n            // Arrange\n            var themesImpl = new ThemesImplementation(scopeStorage: new ScopeStorageDictionary(),\n                                                      vpp: GetVirtualPathProvider(\"themes\", new Dir(\"default\"), new Dir(\"mobile\"), new Dir(@\"mobile\\styles\", \"wp7.css\"), new Dir(@\"default\\styles\", \"main.css\")));\n            themesImpl.Initialize(\"themes\", \"default\");\n\n            // Act\n            themesImpl.CurrentTheme = \"mobile\";\n            var themePath = themesImpl.GetResourcePath(folder: \"does-not-exist\", fileName: \"main.css\");\n\n            // Assert\n            Assert.Null(themePath);\n        }\n\n        [Fact]\n        public void GetResourcePathReturnsNullIfItemNotFoundInCurrentAndDefaultThemeDirectories()\n        {\n            // Arrange\n            var themesImpl = new ThemesImplementation(scopeStorage: new ScopeStorageDictionary(),\n                                                      vpp: GetVirtualPathProvider(\"themes\", new Dir(\"default\"), new Dir(\"mobile\"), new Dir(@\"mobile\\styles\", \"wp7.css\"), new Dir(@\"default\\styles\", \"main.css\")));\n            themesImpl.Initialize(\"themes\", \"default\");\n\n            // Act\n            themesImpl.CurrentTheme = \"mobile\";\n            var themePath = themesImpl.GetResourcePath(folder: \"styles\", fileName: \"awesome-blinking-text.css\");\n\n            // Assert\n            Assert.Null(themePath);\n        }\n\n        [Fact]\n        public void AvaliableThemesReturnsTopLevelDirectoriesUnderThemeDirectory()\n        {\n            // Arrange\n            var themesImpl = new ThemesImplementation(scopeStorage: new ScopeStorageDictionary(),\n                                                      vpp: GetVirtualPathProvider(\"themes\", new Dir(\"default\"), new Dir(\"mobile\"), new Dir(\"rotary-phone\")));\n            // Act\n            themesImpl.Initialize(\"themes\", \"default\");\n            var themes = themesImpl.AvailableThemes;\n\n            // Assert\n            Assert.Equal(3, themes.Count);\n            Assert.Equal(\"default\", themes[0]);\n            Assert.Equal(\"mobile\", themes[1]);\n            Assert.Equal(\"rotary-phone\", themes[2]);\n        }\n\n        /// <remarks>\n        /// // folder structure:\n        /// // /root\n        /// //   /foo\n        /// //      /bar.cs\n        /// // testing that a file specified as foo/bar in folder root will return null\n        /// </remarks>\n        [Fact]\n        public void FileWithSlash_ReturnsNull()\n        {\n            // Arrange\n            var themesImpl = new ThemesImplementation(scopeStorage: new ScopeStorageDictionary(),\n                                                      vpp: GetVirtualPathProvider(\"themes\", new Dir(\"default\"), new Dir(\"root\"), new Dir(@\"root\\foo\", \"wp7.css\"), new Dir(@\"default\\styles\", \"main.css\")));\n\n            // Act\n            var actual = themesImpl.FindMatchingFile(\"root\", \"foo/bar.cs\");\n\n            // Assert\n            Assert.Null(actual);\n        }\n\n        [Fact]\n        public void DirectoryWithNoFilesReturnsNull()\n        {\n            // Arrange\n            var themesImpl = new ThemesImplementation(scopeStorage: new ScopeStorageDictionary(),\n                                                      vpp: GetVirtualPathProvider(\"themes\", new Dir(\"default\"), new Dir(\"empty-dir\")));\n\n            // Act\n            var actual = themesImpl.FindMatchingFile(@\"themes\\empty-dir\", \"main.css\");\n\n            // Assert\n            Assert.Null(actual);\n        }\n\n        [Fact]\n        public void MatchingFiles_ReturnsCorrectFile()\n        {\n            // Arrange\n            var themesImpl = new ThemesImplementation(scopeStorage: new ScopeStorageDictionary(),\n                                                      vpp: GetVirtualPathProvider(\"themes\", new Dir(@\"nomatchingfiles\", \"foo.cs\")));\n\n            // Act\n            var bar = themesImpl.FindMatchingFile(@\"themes\\nomatchingfiles\", \"bar.cs\");\n            var foo = themesImpl.FindMatchingFile(@\"themes\\nomatchingfiles\", \"foo.cs\");\n\n            // Assert\n            Assert.Null(bar);\n            Assert.Equal(@\"themes/nomatchingfiles/foo.cs\", foo);\n        }\n\n        private static VirtualPathProvider GetVirtualPathProvider(string themeRoot, params Dir[] fileSystem)\n        {\n            var mockVpp = new Mock<VirtualPathProvider>();\n            var dirRoot = new Mock<VirtualDirectory>(themeRoot);\n\n            var themeDirectories = new List<VirtualDirectory>();\n            foreach (var directory in fileSystem)\n            {\n                var dir = new Mock<VirtualDirectory>(directory.Name);\n                var directoryPath = themeRoot + '\\\\' + directory.Name;\n                dir.SetupGet(d => d.Name).Returns(directory.Name);\n                mockVpp.Setup(c => c.GetDirectory(It.Is<string>(p => p.Equals(directoryPath, StringComparison.OrdinalIgnoreCase)))).Returns(dir.Object);\n\n                var fileList = new List<VirtualFile>();\n                foreach (var item in directory.Files)\n                {\n                    var filePath = directoryPath + '\\\\' + item;\n                    var file = new Mock<VirtualFile>(filePath);\n                    file.SetupGet(f => f.Name).Returns(item);\n                    fileList.Add(file.Object);\n                }\n\n                dir.SetupGet(c => c.Files).Returns(fileList);\n                themeDirectories.Add(dir.Object);\n            }\n\n            dirRoot.SetupGet(c => c.Directories).Returns(themeDirectories);\n            mockVpp.Setup(c => c.GetDirectory(themeRoot)).Returns(dirRoot.Object);\n\n            return mockVpp.Object;\n        }\n\n        private class Dir\n        {\n            public Dir(string name, params string[] files)\n            {\n                Name = name;\n                Files = files;\n            }\n\n            public string Name { get; private set; }\n\n            public IEnumerable<string> Files { get; private set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Helpers.Test/UrlBuilderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections;\nusing System.IO;\nusing System.Reflection;\nusing System.Text;\nusing System.Web;\nusing System.Web.UI;\nusing System.Web.WebPages;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace Microsoft.Web.Helpers.Test\n{\n    public class UrlBuilderTest\n    {\n        private static TestVirtualPathUtility _virtualPathUtility = new TestVirtualPathUtility();\n\n        [Fact]\n        public void UrlBuilderUsesPathAsIsIfPathIsAValidUri()\n        {\n            // Arrange\n            var pagePath = \"http://www.test.com/page-path\";\n\n            // Act\n            var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);\n\n            // Assert\n            Assert.Equal(\"http://www.test.com/page-path\", builder.Path);\n        }\n\n        [Fact]\n        public void UrlBuilderUsesQueryComponentsIfPathIsAValidUri()\n        {\n            // Arrange\n            var pagePath = \"http://www.test.com/page-path.vbhtml?param=value&baz=biz\";\n\n            // Act\n            var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);\n\n            // Assert\n            Assert.Equal(\"http://www.test.com/page-path.vbhtml\", builder.Path);\n            Assert.Equal(\"?param=value&baz=biz\", builder.QueryString);\n        }\n\n        [Fact]\n        public void UrlBuilderUsesUsesObjectParameterAsQueryString()\n        {\n            // Arrange\n            var pagePath = \"http://www.test.com/page-path.vbhtml?param=value&baz=biz\";\n\n            // Act\n            var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);\n\n            // Assert\n            Assert.Equal(\"http://www.test.com/page-path.vbhtml\", builder.Path);\n            Assert.Equal(\"?param=value&baz=biz\", builder.QueryString);\n        }\n\n        [Fact]\n        public void UrlBuilderAppendsObjectParametersToPathWithQueryString()\n        {\n            // Arrange\n            var pagePath = \"http://www.test.com/page-path.vbhtml?param=value&baz=biz\";\n\n            // Act\n            var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, new { param2 = \"param2val\" });\n\n            // Assert\n            Assert.Equal(\"http://www.test.com/page-path.vbhtml\", builder.Path);\n            Assert.Equal(\"?param=value&baz=biz&param2=param2val\", builder.QueryString);\n        }\n\n        [Fact]\n        public void UrlBuilderWithVirtualPathUsesVirtualPathUtility()\n        {\n            // Arrange\n            var pagePath = \"~/page\";\n\n            // Act\n            var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);\n\n            // Assert\n            Assert.Equal(\"page\", builder.Path);\n        }\n\n        [Fact]\n        public void UrlBuilderDoesNotResolvePathIfContextIsNull()\n        {\n            // Arrange\n            var pagePath = \"~/foo/bar\";\n\n            // Act\n            var builder = new UrlBuilder(null, _virtualPathUtility, pagePath, null);\n\n            // Assert\n            Assert.Equal(pagePath, builder.Path);\n        }\n\n        [Fact]\n        public void UrlBuilderSetsPathToNullIfContextIsNullAndPagePathIsNotSpecified()\n        {\n            // Act\n            var builder = new UrlBuilder(null, null, null, null);\n\n            // Assert\n            Assert.Null(builder.Path);\n            Assert.True(String.IsNullOrEmpty(builder.ToString()));\n        }\n\n        [Fact]\n        public void UrlBuilderWithVirtualPathAppendsObjectAsQueryString()\n        {\n            // Arrange\n            var pagePath = \"~/page\";\n\n            // Act\n            var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, new { Foo = \"bar\", baz = \"qux\" });\n\n            // Assert\n            Assert.Equal(\"page\", builder.Path);\n            Assert.Equal(\"?Foo=bar&baz=qux\", builder.QueryString);\n        }\n\n        [Fact]\n        public void UrlBuilderWithVirtualPathExtractsQueryStringParameterFromPath()\n        {\n            // Arrange\n            var pagePath = \"~/dir/page?someparam=value\";\n\n            // Act\n            var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);\n\n            // Assert\n            Assert.Equal(\"dir/page\", builder.Path);\n            Assert.Equal(\"?someparam=value\", builder.QueryString);\n        }\n\n        [Fact]\n        public void UrlBuilderWithVirtualPathAndQueryStringAppendsObjectAsQueryStringParams()\n        {\n            // Arrange\n            var pagePath = \"~/dir/page?someparam=value\";\n\n            // Act\n            var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, new { someotherparam = \"value2\" });\n\n            // Assert\n            Assert.Equal(\"dir/page\", builder.Path);\n            Assert.Equal(\"?someparam=value&someotherparam=value2\", builder.QueryString);\n        }\n\n        [Fact]\n        public void AddPathAddsPathPortionToRelativeUrl()\n        {\n            // Arrange\n            var pagePath = \"~/dir/page?someparam=value\";\n\n            // Act\n            var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);\n            builder.AddPath(\"foo\").AddPath(\"bar/baz\");\n\n            // Assert\n            Assert.Equal(\"dir/page/foo/bar/baz\", builder.Path);\n            Assert.Equal(\"?someparam=value\", builder.QueryString);\n        }\n\n        [Fact]\n        public void AddPathEncodesPathParams()\n        {\n            // Arrange\n            var pagePath = \"~/dir/page?someparam=value\";\n\n            // Act\n            var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);\n            builder.AddPath(\"foo bar\").AddPath(\"baz biz\", \"qux\");\n\n            // Assert\n            Assert.Equal(\"dir/page/foo%20bar/baz%20biz/qux\", builder.Path);\n        }\n\n        [Fact]\n        public void AddPathAddsPathPortionToAbsoluteUrl()\n        {\n            // Arrange\n            var pagePath = \"http://some-site/dir/page?someparam=value\";\n\n            // Act\n            var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);\n            builder.AddPath(\"foo\").AddPath(\"bar/baz\");\n\n            // Assert\n            Assert.Equal(\"http://some-site/dir/page/foo/bar/baz\", builder.Path);\n            Assert.Equal(\"?someparam=value\", builder.QueryString);\n        }\n\n        [Fact]\n        public void AddPathWithParamsArrayAddsPathPortionToRelativeUrl()\n        {\n            // Arrange\n            var pagePath = \"~/dir/page/?someparam=value\";\n\n            // Act\n            var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);\n            builder.AddPath(\"foo\", \"bar\", \"baz\").AddPath(\"qux\");\n\n            // Assert\n            Assert.Equal(\"dir/page/foo/bar/baz/qux\", builder.Path);\n            Assert.Equal(\"?someparam=value\", builder.QueryString);\n        }\n\n        [Fact]\n        public void AddPathEnsuresSlashesAreNotRepeated()\n        {\n            // Arrange\n            var pagePath = \"~/dir/page/\";\n\n            // Act\n            var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);\n            builder.AddPath(\"foo\").AddPath(\"/bar/\").AddPath(\"/baz\");\n\n            // Assert\n            Assert.Equal(\"dir/page/foo/bar/baz\", builder.Path);\n        }\n\n        [Fact]\n        public void AddPathWithParamsEnsuresSlashAreNotRepeated()\n        {\n            // Arrange\n            var pagePath = \"~/dir/page/\";\n\n            // Act\n            var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);\n            builder.AddPath(\"foo\", \"/bar/\", \"/baz\").AddPath(\"qux/\");\n\n            // Assert\n            Assert.Equal(\"dir/page/foo/bar/baz/qux/\", builder.Path);\n        }\n\n        [Fact]\n        public void AddPathWithParamsArrayAddsPathPortionToAbsoluteUrl()\n        {\n            // Arrange\n            var pagePath = \"http://www.test.com/dir/page/?someparam=value\";\n\n            // Act\n            var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);\n            builder.AddPath(\"foo\", \"bar\", \"baz\").AddPath(\"qux\");\n\n            // Assert\n            Assert.Equal(\"http://www.test.com/dir/page/foo/bar/baz/qux\", builder.Path);\n            Assert.Equal(\"?someparam=value\", builder.QueryString);\n        }\n\n        [Fact]\n        public void UrlBuilderEncodesParameters()\n        {\n            // Arrange\n            var pagePath = \"~/dir/page/?someparam=value\";\n\n            // Act\n            var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, new { Λ = \"λ\" });\n            builder.AddParam(new { π = \"is not a lie\" }).AddParam(\"Π\", \"maybe a lie\");\n            // Assert\n            Assert.Equal(\"?someparam=value&%ce%9b=%ce%bb&%cf%80=is+not+a+lie&%ce%a0=maybe+a+lie\", builder.QueryString);\n        }\n\n        [Fact]\n        public void AddParamAddsParamToQueryString()\n        {\n            // Arrange\n            var pagePath = \"http://www.test.com/dir/page/?someparam=value\";\n\n            // Act\n            var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);\n            builder.AddParam(\"foo\", \"bar\");\n\n            // Assert\n            Assert.Equal(\"?someparam=value&foo=bar\", builder.QueryString);\n        }\n\n        [Fact]\n        public void AddParamAddsQuestionMarkToQueryStringIfFirstParam()\n        {\n            // Arrange\n            var pagePath = \"~/dir/page\";\n\n            // Act\n            var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);\n            builder.AddParam(\"foo\", \"bar\").AddParam(new { baz = \"qux\", biz = \"quark\" });\n\n            // Assert\n            Assert.Equal(\"?foo=bar&baz=qux&biz=quark\", builder.QueryString);\n        }\n\n        [Fact]\n        public void AddParamIgnoresParametersWithEmptyKey()\n        {\n            // Arrange\n            var pagePath = \"~/dir/page\";\n\n            // Act\n            var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);\n            builder.AddParam(\"\", \"bar\").AddParam(new { baz = \"\", biz = \"quark\" }).AddParam(\"qux\", null).AddParam(null, \"somevalue\");\n\n            // Assert\n            Assert.Equal(\"?baz=&biz=quark&qux=\", builder.QueryString);\n        }\n\n        [Fact]\n        public void ToStringConcatsPathAndQueryString()\n        {\n            // Arrange\n            var pagePath = \"~/dir/page\";\n\n            // Act\n            var builder = new UrlBuilder(GetContext(), _virtualPathUtility, pagePath, null);\n            builder.AddParam(\"foo\", \"bar\").AddParam(new { baz = \"qux\", biz = \"quark\" });\n\n            // Assert\n            Assert.Equal(\"dir/page?foo=bar&baz=qux&biz=quark\", builder.ToString());\n        }\n\n        [Fact]\n        public void UrlBuilderWithRealVirtualPathUtilityTest()\n        {\n            // Arrange\n            var pagePath = \"~/world/test.aspx\";\n            try\n            {\n                // Act\n                CreateHttpContext(\"default.aspx\", \"http://localhost/WebSite1/subfolder1/default.aspx\");\n                CreateHttpRuntime(\"/WebSite1/\");\n                var builder = new UrlBuilder(pagePath, null);\n\n                // Assert\n                Assert.Equal(@\"/WebSite1/world/test.aspx\", builder.Path);\n            }\n            finally\n            {\n                RestoreHttpRuntime();\n            }\n        }\n\n        private static HttpContextBase GetContext(params string[] virtualPaths)\n        {\n            var httpContext = new Mock<HttpContextBase>();\n            var table = new Hashtable();\n            httpContext.SetupGet(c => c.Items).Returns(table);\n\n            foreach (var item in virtualPaths)\n            {\n                var page = new Mock<ITemplateFile>();\n                page.SetupGet(p => p.TemplateInfo).Returns(new TemplateFileInfo(item));\n                TemplateStack.Push(httpContext.Object, page.Object);\n            }\n\n            return httpContext.Object;\n        }\n\n        private class TestVirtualPathUtility : VirtualPathUtilityBase\n        {\n            public override string Combine(string basePath, string relativePath)\n            {\n                return basePath + '/' + relativePath.TrimStart('~', '/');\n            }\n\n            public override string ToAbsolute(string virtualPath)\n            {\n                return virtualPath.TrimStart('~', '/');\n            }\n        }\n\n        internal static void CreateHttpRuntime(string appVPath)\n        {\n            var runtime = new HttpRuntime();\n            var appDomainAppVPathField = typeof(HttpRuntime).GetField(\"_appDomainAppVPath\", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);\n            appDomainAppVPathField.SetValue(runtime, CreateVirtualPath(appVPath));\n            GetTheRuntime().SetValue(null, runtime);\n            var appDomainIdField = typeof(HttpRuntime).GetField(\"_appDomainId\", BindingFlags.NonPublic | BindingFlags.Instance);\n            appDomainIdField.SetValue(runtime, \"test\");\n        }\n\n        internal static FieldInfo GetTheRuntime()\n        {\n            return typeof(HttpRuntime).GetField(\"_theRuntime\", BindingFlags.NonPublic | BindingFlags.Static);\n        }\n\n        internal static void RestoreHttpRuntime()\n        {\n            GetTheRuntime().SetValue(null, null);\n        }\n\n        // E.g. \"default.aspx\", \"http://localhost/WebSite1/subfolder1/default.aspx\"\n        internal static void CreateHttpContext(string filename, string url)\n        {\n            var request = new HttpRequest(filename, url, null);\n            var httpContext = new HttpContext(request, new HttpResponse(new StringWriter(new StringBuilder())));\n            HttpContext.Current = httpContext;\n        }\n\n        internal static void RestoreHttpContext()\n        {\n            HttpContext.Current = null;\n        }\n\n        internal static object CreateVirtualPath(string path)\n        {\n            var vPath = typeof(Page).Assembly.GetType(\"System.Web.VirtualPath\");\n            var method = vPath.GetMethod(\"CreateNonRelativeTrailingSlash\", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);\n            return method.Invoke(null, new object[] { path });\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Helpers.Test/VideoTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Reflection;\nusing System.Text.RegularExpressions;\nusing System.Web;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace Microsoft.Web.Helpers.Test\n{\n    public class VideoTest\n    {\n        private VirtualPathUtilityWrapper _pathUtility = new VirtualPathUtilityWrapper();\n\n        [Fact]\n        public void FlashCannotOverrideHtmlAttributes()\n        {\n            Assert.ThrowsArgument(() => { Video.Flash(GetContext(), _pathUtility, \"http://foo.bar.com/foo.swf\", htmlAttributes: new { cLASSid = \"CanNotOverride\" }); }, \"htmlAttributes\", \"Property \\\"cLASSid\\\" cannot be set through this argument.\");\n        }\n\n        [Fact]\n        public void FlashDefaults()\n        {\n            string html = Video.Flash(GetContext(), _pathUtility, \"http://foo.bar.com/foo.swf\").ToString().Replace(\"\\r\\n\", \"\");\n            Assert.StartsWith(\"<object classid=\\\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\\\" \" +\n                \"codebase=\\\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab\\\" type=\\\"application/x-oleobject\\\" >\",\n                html);\n            Assert.Contains(\"<param name=\\\"movie\\\" value=\\\"http://foo.bar.com/foo.swf\\\" />\", html);\n            Assert.Contains(\"<embed src=\\\"http://foo.bar.com/foo.swf\\\" type=\\\"application/x-shockwave-flash\\\" />\", html);\n            Assert.EndsWith(\"</object>\", html);\n        }\n\n        [Fact]\n        public void FlashThrowsWhenPathIsEmpty()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(() => { Video.Flash(GetContext(), _pathUtility, String.Empty); }, \"path\");\n        }\n\n        [Fact]\n        public void FlashThrowsWhenPathIsNull()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(() => { Video.Flash(GetContext(), _pathUtility, null); }, \"path\");\n        }\n\n        [Fact]\n        public void FlashWithExposedOptions()\n        {\n            string html = Video.Flash(GetContext(), _pathUtility, \"http://foo.bar.com/foo.swf\", width: \"100px\", height: \"100px\",\n                                      play: false, loop: false, menu: false, backgroundColor: \"#000\", quality: \"Q\", scale: \"S\", windowMode: \"WM\",\n                                      baseUrl: \"http://foo.bar.com/\", version: \"1.0.0.0\", htmlAttributes: new { id = \"fl\" }, embedName: \"efl\").ToString().Replace(\"\\r\\n\", \"\");\n\n            Assert.StartsWith(\"<object classid=\\\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\\\" \" +\n                \"codebase=\\\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=1,0,0,0\\\" \" +\n                \"height=\\\"100px\\\" id=\\\"fl\\\" type=\\\"application/x-oleobject\\\" width=\\\"100px\\\" >\",\n                html);\n            Assert.Contains(\"<param name=\\\"play\\\" value=\\\"False\\\" />\", html);\n            Assert.Contains(\"<param name=\\\"loop\\\" value=\\\"False\\\" />\", html);\n            Assert.Contains(\"<param name=\\\"menu\\\" value=\\\"False\\\" />\", html);\n            Assert.Contains(\"<param name=\\\"bgColor\\\" value=\\\"#000\\\" />\", html);\n            Assert.Contains(\"<param name=\\\"quality\\\" value=\\\"Q\\\" />\", html);\n            Assert.Contains(\"<param name=\\\"scale\\\" value=\\\"S\\\" />\", html);\n            Assert.Contains(\"<param name=\\\"wmode\\\" value=\\\"WM\\\" />\", html);\n            Assert.Contains(\"<param name=\\\"base\\\" value=\\\"http://foo.bar.com/\\\" />\", html);\n\n            var embed = new Regex(\"<embed.*/>\").Match(html);\n            Assert.True(embed.Success);\n            Assert.StartsWith(\"<embed src=\\\"http://foo.bar.com/foo.swf\\\" width=\\\"100px\\\" height=\\\"100px\\\" name=\\\"efl\\\" type=\\\"application/x-shockwave-flash\\\" \", embed.Value);\n            Assert.Contains(\"play=\\\"False\\\"\", embed.Value);\n            Assert.Contains(\"loop=\\\"False\\\"\", embed.Value);\n            Assert.Contains(\"menu=\\\"False\\\"\", embed.Value);\n            Assert.Contains(\"bgColor=\\\"#000\\\"\", embed.Value);\n            Assert.Contains(\"quality=\\\"Q\\\"\", embed.Value);\n            Assert.Contains(\"scale=\\\"S\\\"\", embed.Value);\n            Assert.Contains(\"wmode=\\\"WM\\\"\", embed.Value);\n            Assert.Contains(\"base=\\\"http://foo.bar.com/\\\"\", embed.Value);\n        }\n\n        [Fact]\n        public void FlashWithUnexposedOptions()\n        {\n            string html = Video.Flash(GetContext(), _pathUtility, \"http://foo.bar.com/foo.swf\", options: new { X = \"Y\", Z = 123 }).ToString().Replace(\"\\r\\n\", \"\");\n            Assert.Contains(\"<param name=\\\"X\\\" value=\\\"Y\\\" />\", html);\n            Assert.Contains(\"<param name=\\\"Z\\\" value=\\\"123\\\" />\", html);\n            // note - can't guarantee order of optional params:\n            Assert.True(\n                html.Contains(\"<embed src=\\\"http://foo.bar.com/foo.swf\\\" type=\\\"application/x-shockwave-flash\\\" X=\\\"Y\\\" Z=\\\"123\\\" />\") ||\n                html.Contains(\"<embed src=\\\"http://foo.bar.com/foo.swf\\\" type=\\\"application/x-shockwave-flash\\\" Z=\\\"123\\\" X=\\\"Y\\\" />\")\n                );\n        }\n\n        [Fact]\n        public void MediaPlayerCannotOverrideHtmlAttributes()\n        {\n            Assert.ThrowsArgument(() => { Video.MediaPlayer(GetContext(), _pathUtility, \"http://foo.bar.com/foo.wmv\", htmlAttributes: new { cODEbase = \"CanNotOverride\" }); }, \"htmlAttributes\", \"Property \\\"cODEbase\\\" cannot be set through this argument.\");\n        }\n\n        [Fact]\n        public void MediaPlayerDefaults()\n        {\n            string html = Video.MediaPlayer(GetContext(), _pathUtility, \"http://foo.bar.com/foo.wmv\").ToString().Replace(\"\\r\\n\", \"\");\n            Assert.StartsWith(\"<object classid=\\\"clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6\\\" >\", html);\n            Assert.Contains(\"<param name=\\\"URL\\\" value=\\\"http://foo.bar.com/foo.wmv\\\" />\", html);\n            Assert.Contains(\"<embed src=\\\"http://foo.bar.com/foo.wmv\\\" type=\\\"application/x-mplayer2\\\" />\", html);\n            Assert.EndsWith(\"</object>\", html);\n        }\n\n        [Fact]\n        public void MediaPlayerThrowsWhenPathIsEmpty()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(() => { Video.MediaPlayer(GetContext(), _pathUtility, String.Empty); }, \"path\");\n        }\n\n        [Fact]\n        public void MediaPlayerThrowsWhenPathIsNull()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(() => { Video.MediaPlayer(GetContext(), _pathUtility, null); }, \"path\");\n        }\n\n        [Fact]\n        public void MediaPlayerWithExposedOptions()\n        {\n            string html = Video.MediaPlayer(GetContext(), _pathUtility, \"http://foo.bar.com/foo.wmv\", width: \"100px\", height: \"100px\",\n                                            autoStart: false, playCount: 2, uiMode: \"UIMODE\", stretchToFit: true, enableContextMenu: false, mute: true,\n                                            volume: 1, baseUrl: \"http://foo.bar.com/\", htmlAttributes: new { id = \"mp\" }, embedName: \"emp\").ToString().Replace(\"\\r\\n\", \"\");\n            Assert.StartsWith(\"<object classid=\\\"clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6\\\" height=\\\"100px\\\" id=\\\"mp\\\" width=\\\"100px\\\" >\", html);\n            Assert.Contains(\"<param name=\\\"URL\\\" value=\\\"http://foo.bar.com/foo.wmv\\\" />\", html);\n            Assert.Contains(\"<param name=\\\"autoStart\\\" value=\\\"False\\\" />\", html);\n            Assert.Contains(\"<param name=\\\"playCount\\\" value=\\\"2\\\" />\", html);\n            Assert.Contains(\"<param name=\\\"uiMode\\\" value=\\\"UIMODE\\\" />\", html);\n            Assert.Contains(\"<param name=\\\"stretchToFit\\\" value=\\\"True\\\" />\", html);\n            Assert.Contains(\"<param name=\\\"enableContextMenu\\\" value=\\\"False\\\" />\", html);\n            Assert.Contains(\"<param name=\\\"mute\\\" value=\\\"True\\\" />\", html);\n            Assert.Contains(\"<param name=\\\"volume\\\" value=\\\"1\\\" />\", html);\n            Assert.Contains(\"<param name=\\\"baseURL\\\" value=\\\"http://foo.bar.com/\\\" />\", html);\n\n            var embed = new Regex(\"<embed.*/>\").Match(html);\n            Assert.True(embed.Success);\n            Assert.StartsWith(\"<embed src=\\\"http://foo.bar.com/foo.wmv\\\" width=\\\"100px\\\" height=\\\"100px\\\" name=\\\"emp\\\" type=\\\"application/x-mplayer2\\\" \", embed.Value);\n            Assert.Contains(\"autoStart=\\\"False\\\"\", embed.Value);\n            Assert.Contains(\"playCount=\\\"2\\\"\", embed.Value);\n            Assert.Contains(\"uiMode=\\\"UIMODE\\\"\", embed.Value);\n            Assert.Contains(\"stretchToFit=\\\"True\\\"\", embed.Value);\n            Assert.Contains(\"enableContextMenu=\\\"False\\\"\", embed.Value);\n            Assert.Contains(\"mute=\\\"True\\\"\", embed.Value);\n            Assert.Contains(\"volume=\\\"1\\\"\", embed.Value);\n            Assert.Contains(\"baseURL=\\\"http://foo.bar.com/\\\"\", embed.Value);\n        }\n\n        [Fact]\n        public void MediaPlayerWithUnexposedOptions()\n        {\n            string html = Video.MediaPlayer(GetContext(), _pathUtility, \"http://foo.bar.com/foo.wmv\", options: new { X = \"Y\", Z = 123 }).ToString().Replace(\"\\r\\n\", \"\");\n            Assert.Contains(\"<param name=\\\"X\\\" value=\\\"Y\\\" />\", html);\n            Assert.Contains(\"<param name=\\\"Z\\\" value=\\\"123\\\" />\", html);\n            Assert.True(\n                html.Contains(\"<embed src=\\\"http://foo.bar.com/foo.wmv\\\" type=\\\"application/x-mplayer2\\\" X=\\\"Y\\\" Z=\\\"123\\\" />\") ||\n                html.Contains(\"<embed src=\\\"http://foo.bar.com/foo.wmv\\\" type=\\\"application/x-mplayer2\\\" Z=\\\"123\\\" X=\\\"Y\\\" />\")\n                );\n        }\n\n        [Fact]\n        public void SilverlightCannotOverrideHtmlAttributes()\n        {\n            Assert.ThrowsArgument(() =>\n            {\n                Video.Silverlight(GetContext(), _pathUtility, \"http://foo.bar.com/foo.xap\", \"100px\", \"100px\",\n                                  htmlAttributes: new { WIDTH = \"CanNotOverride\" });\n            }, \"htmlAttributes\", \"Property \\\"WIDTH\\\" cannot be set through this argument.\");\n        }\n\n        [Fact]\n        public void SilverlightDefaults()\n        {\n            string html = Video.Silverlight(GetContext(), _pathUtility, \"http://foo.bar.com/foo.xap\", \"100px\", \"100px\").ToString().Replace(\"\\r\\n\", \"\");\n            Assert.StartsWith(\"<object data=\\\"data:application/x-silverlight-2,\\\" height=\\\"100px\\\" type=\\\"application/x-silverlight-2\\\" \" +\n                \"width=\\\"100px\\\" >\",\n                html);\n            Assert.Contains(\"<param name=\\\"source\\\" value=\\\"http://foo.bar.com/foo.xap\\\" />\", html);\n            Assert.Contains(\"<a href=\\\"http://go.microsoft.com/fwlink/?LinkID=149156\\\" style=\\\"text-decoration:none\\\">\" +\n                \"<img src=\\\"http://go.microsoft.com/fwlink?LinkId=108181\\\" alt=\\\"Get Microsoft Silverlight\\\" \" +\n                \"style=\\\"border-style:none\\\"/></a>\", html);\n            Assert.EndsWith(\"</object>\", html);\n        }\n\n        [Fact]\n        public void SilverlightThrowsWhenPathIsEmpty()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(() => { Video.Silverlight(GetContext(), _pathUtility, String.Empty, \"100px\", \"100px\"); }, \"path\");\n        }\n\n        [Fact]\n        public void SilverlightThrowsWhenPathIsNull()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(() => { Video.Silverlight(GetContext(), _pathUtility, null, \"100px\", \"100px\"); }, \"path\");\n        }\n\n        [Fact]\n        public void SilverlightThrowsWhenHeightIsEmpty()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(() => { Video.Silverlight(GetContext(), _pathUtility, \"http://foo.bar.com/foo.xap\", \"100px\", String.Empty); }, \"height\");\n        }\n\n        [Fact]\n        public void SilverlightThrowsWhenHeightIsNull()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(() => { Video.Silverlight(GetContext(), _pathUtility, \"http://foo.bar.com/foo.xap\", \"100px\", null); }, \"height\");\n        }\n\n        [Fact]\n        public void SilverlightThrowsWhenWidthIsEmpty()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(() => { Video.Silverlight(GetContext(), _pathUtility, \"http://foo.bar.com/foo.xap\", String.Empty, \"100px\"); }, \"width\");\n        }\n\n        [Fact]\n        public void SilverlightThrowsWhenWidthIsNull()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(() => { Video.Silverlight(GetContext(), _pathUtility, \"http://foo.bar.com/foo.xap\", null, \"100px\"); }, \"width\");\n        }\n\n        [Fact]\n        public void SilverlightWithExposedOptions()\n        {\n            string html = Video.Silverlight(GetContext(), _pathUtility, \"http://foo.bar.com/foo.xap\", width: \"85%\", height: \"85%\",\n                                            backgroundColor: \"red\", initParameters: \"X=Y\", minimumVersion: \"1.0.0.0\", autoUpgrade: false,\n                                            htmlAttributes: new { id = \"sl\" }).ToString().Replace(\"\\r\\n\", \"\");\n            Assert.StartsWith(\"<object data=\\\"data:application/x-silverlight-2,\\\" height=\\\"85%\\\" id=\\\"sl\\\" \" +\n                \"type=\\\"application/x-silverlight-2\\\" width=\\\"85%\\\" >\",\n                html);\n            Assert.Contains(\"<param name=\\\"background\\\" value=\\\"red\\\" />\", html);\n            Assert.Contains(\"<param name=\\\"initparams\\\" value=\\\"X=Y\\\" />\", html);\n            Assert.Contains(\"<param name=\\\"minruntimeversion\\\" value=\\\"1.0.0.0\\\" />\", html);\n            Assert.Contains(\"<param name=\\\"autoUpgrade\\\" value=\\\"False\\\" />\", html);\n\n            var embed = new Regex(\"<embed.*/>\").Match(html);\n            Assert.False(embed.Success);\n        }\n\n        [Fact]\n        public void SilverlightWithUnexposedOptions()\n        {\n            string html = Video.Silverlight(GetContext(), _pathUtility, \"http://foo.bar.com/foo.xap\", width: \"50px\", height: \"50px\",\n                                            options: new { X = \"Y\", Z = 123 }).ToString().Replace(\"\\r\\n\", \"\");\n            Assert.Contains(\"<param name=\\\"X\\\" value=\\\"Y\\\" />\", html);\n            Assert.Contains(\"<param name=\\\"Z\\\" value=\\\"123\\\" />\", html);\n        }\n\n        [Fact]\n        public void ValidatePathResolvesExistingLocalPath()\n        {\n            string path = Assembly.GetExecutingAssembly().Location;\n            Mock<VirtualPathUtilityBase> pathUtility = new Mock<VirtualPathUtilityBase>();\n            pathUtility.Setup(p => p.Combine(It.IsAny<string>(), It.IsAny<string>())).Returns(path);\n            pathUtility.Setup(p => p.ToAbsolute(It.IsAny<string>())).Returns(path);\n\n            Mock<HttpServerUtilityBase> serverMock = new Mock<HttpServerUtilityBase>();\n            serverMock.Setup(s => s.MapPath(It.IsAny<string>())).Returns(path);\n            HttpContextBase context = GetContext(serverMock.Object);\n\n            string html = Video.Flash(context, pathUtility.Object, \"foo.bar\").ToString();\n            Assert.StartsWith(\"<object\", html);\n            Assert.Contains(HttpUtility.HtmlAttributeEncode(HttpUtility.UrlPathEncode(path)), html);\n        }\n\n        [Fact]\n        public void ValidatePathThrowsForNonExistingLocalPath()\n        {\n            string path = \"c:\\\\does\\\\not\\\\exist.swf\";\n            Mock<VirtualPathUtilityBase> pathUtility = new Mock<VirtualPathUtilityBase>();\n            pathUtility.Setup(p => p.Combine(It.IsAny<string>(), It.IsAny<string>())).Returns(path);\n            pathUtility.Setup(p => p.ToAbsolute(It.IsAny<string>())).Returns(path);\n\n            Mock<HttpServerUtilityBase> serverMock = new Mock<HttpServerUtilityBase>();\n            serverMock.Setup(s => s.MapPath(It.IsAny<string>())).Returns(path);\n            HttpContextBase context = GetContext(serverMock.Object);\n\n            Assert.Throws<InvalidOperationException>(() => { Video.Flash(context, pathUtility.Object, \"exist.swf\"); }, \"The media file \\\"exist.swf\\\" does not exist.\");\n        }\n\n        private static HttpContextBase GetContext(HttpServerUtilityBase serverUtility = null)\n        {\n            // simple mocked context - won't reference as long as path starts with 'http'\n            Mock<HttpRequestBase> requestMock = new Mock<HttpRequestBase>();\n            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>();\n            contextMock.Setup(context => context.Request).Returns(requestMock.Object);\n            contextMock.Setup(context => context.Server).Returns(serverUtility);\n            return contextMock.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Helpers.Test/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Castle.Core\" version=\"5.1.1\" targetFramework=\"net462\" />\n  <package id=\"Moq\" version=\"4.18.4\" targetFramework=\"net462\" />\n  <package id=\"xunit\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.abstractions\" version=\"2.0.3\" targetFramework=\"net462\" />\n  <package id=\"xunit.analyzers\" version=\"1.1.0\" targetFramework=\"net462\" />\n  <package id=\"xunit.assert\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.execution\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.runner.visualstudio\" version=\"2.4.5\" targetFramework=\"net462\" developmentDependency=\"true\" />\n</packages>"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Controls/Test/DesignModeSite.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.ComponentModel;\n\nnamespace Microsoft.Web.Mvc.Controls.Test\n{\n    public class DesignModeSite : ISite\n    {\n        IComponent ISite.Component\n        {\n            get { throw new NotImplementedException(); }\n        }\n\n        IContainer ISite.Container\n        {\n            get { throw new NotImplementedException(); }\n        }\n\n        bool ISite.DesignMode\n        {\n            get { return true; }\n        }\n\n        string ISite.Name\n        {\n            get { throw new NotImplementedException(); }\n            set { throw new NotImplementedException(); }\n        }\n\n        object IServiceProvider.GetService(Type serviceType)\n        {\n            throw new NotImplementedException();\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Controls/Test/DropDownListTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Mvc.Controls.Test\n{\n    public class DropDownListTest\n    {\n        [Fact]\n        public void NameProperty()\n        {\n            // TODO: This\n        }\n\n        [Fact]\n        public void RenderWithNoNameNotInDesignModeThrows()\n        {\n            // TODO: This\n        }\n\n        [Fact]\n        public void RenderWithNoNameInDesignModeRendersWithSampleData()\n        {\n            // Setup\n            DropDownList c = new DropDownList();\n\n            // Execute\n            string html = MvcTestHelper.GetControlRendering(c, true);\n\n            // Verify\n            Assert.Equal(\"<select>\" + Environment.NewLine\n                       + \"\\t<option>\" + Environment.NewLine\n                       + \"\\t\\tSample Item\" + Environment.NewLine\n                       + \"\\t</option>\" + Environment.NewLine\n                       + \"</select>\",\n                         html);\n        }\n\n        [Fact]\n        public void RenderWithNoAttributes()\n        {\n            // Setup\n            DropDownList c = new DropDownList();\n            c.Name = \"nameKey\";\n\n            ViewDataContainer vdc = new ViewDataContainer();\n            vdc.Controls.Add(c);\n            vdc.ViewData = new ViewDataDictionary();\n            vdc.ViewData[\"nameKey\"] = new SelectList(new[] { \"aaa\", \"bbb\", \"ccc\" }, \"bbb\");\n\n            // Execute\n            string html = MvcTestHelper.GetControlRendering(c, false);\n\n            // Verify\n            Assert.Equal(\"<select name=\\\"nameKey\\\">\" + Environment.NewLine\n                       + \"\\t<option>\" + Environment.NewLine\n                       + \"\\t\\taaa\" + Environment.NewLine\n                       + \"\\t</option><option selected=\\\"selected\\\">\" + Environment.NewLine\n                       + \"\\t\\tbbb\" + Environment.NewLine\n                       + \"\\t</option><option>\" + Environment.NewLine\n                       + \"\\t\\tccc\" + Environment.NewLine\n                       + \"\\t</option>\" + Environment.NewLine\n                       + \"</select>\",\n                         html);\n        }\n\n        [Fact]\n        public void RenderWithTextsAndValues()\n        {\n            // Setup\n            DropDownList c = new DropDownList();\n            c.Name = \"nameKey\";\n\n            ViewDataContainer vdc = new ViewDataContainer();\n            vdc.Controls.Add(c);\n            vdc.ViewData = new ViewDataDictionary();\n            vdc.ViewData[\"nameKey\"] = new SelectList(\n                new[]\n                {\n                    new { Text = \"aaa\", Value = \"111\" },\n                    new { Text = \"bbb\", Value = \"222\" },\n                    new { Text = \"ccc\", Value = \"333\" }\n                },\n                \"Value\",\n                \"Text\",\n                \"222\");\n\n            // Execute\n            string html = MvcTestHelper.GetControlRendering(c, false);\n\n            // Verify\n            Assert.Equal(\"<select name=\\\"nameKey\\\">\" + Environment.NewLine\n                       + \"\\t<option value=\\\"111\\\">\" + Environment.NewLine\n                       + \"\\t\\taaa\" + Environment.NewLine\n                       + \"\\t</option><option value=\\\"222\\\" selected=\\\"selected\\\">\" + Environment.NewLine\n                       + \"\\t\\tbbb\" + Environment.NewLine\n                       + \"\\t</option><option value=\\\"333\\\">\" + Environment.NewLine\n                       + \"\\t\\tccc\" + Environment.NewLine\n                       + \"\\t</option>\" + Environment.NewLine\n                       + \"</select>\", html);\n        }\n\n        [Fact]\n        public void RenderWithNameAndIdRendersNameAndIdAttribute()\n        {\n            // Setup\n            DropDownList c = new DropDownList();\n            c.Name = \"nameKey\";\n            c.ID = \"someID\";\n\n            ViewDataContainer vdc = new ViewDataContainer();\n            vdc.Controls.Add(c);\n            vdc.ViewData = new ViewDataDictionary();\n            vdc.ViewData[\"nameKey\"] = new SelectList(new[] { \"aaa\", \"bbb\", \"ccc\" }, \"bbb\");\n\n            // Execute\n            string html = MvcTestHelper.GetControlRendering(c, false);\n\n            // Verify\n            Assert.Equal(\"<select id=\\\"someID\\\" name=\\\"nameKey\\\">\" + Environment.NewLine\n                       + \"\\t<option>\" + Environment.NewLine\n                       + \"\\t\\taaa\" + Environment.NewLine\n                       + \"\\t</option><option selected=\\\"selected\\\">\" + Environment.NewLine\n                       + \"\\t\\tbbb\" + Environment.NewLine\n                       + \"\\t</option><option>\" + Environment.NewLine\n                       + \"\\t\\tccc\" + Environment.NewLine\n                       + \"\\t</option>\" + Environment.NewLine\n                       + \"</select>\",\n                         html);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Controls/Test/MvcControlTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Mvc;\nusing System.Web.UI;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Mvc.Controls.Test\n{\n    public class MvcControlTest\n    {\n        [Fact]\n        public void AttributesProperty()\n        {\n            // Setup\n            DummyMvcControl c = new DummyMvcControl();\n\n            // Execute\n            IDictionary<string, string> attrs = c.Attributes;\n\n            // Verify\n            Assert.NotNull(attrs);\n            Assert.Empty(attrs);\n        }\n\n        [Fact]\n        public void GetSetAttributes()\n        {\n            // Setup\n            DummyMvcControl c = new DummyMvcControl();\n            IAttributeAccessor attrAccessor = c;\n            IDictionary<string, string> attrs = c.Attributes;\n\n            // Execute and Verify\n            string value;\n            value = attrAccessor.GetAttribute(\"xyz\");\n            Assert.Null(value);\n\n            attrAccessor.SetAttribute(\"a1\", \"v1\");\n            value = attrAccessor.GetAttribute(\"a1\");\n            Assert.Equal(\"v1\", value);\n            Assert.Single(attrs);\n            value = c.Attributes[\"a1\"];\n            Assert.Equal(\"v1\", value);\n        }\n\n        [Fact]\n        public void EnableViewStateProperty()\n        {\n            DummyMvcControl c = new DummyMvcControl();\n            Assert.True(c.EnableViewState);\n            Assert.True((c).EnableViewState);\n\n            c.EnableViewState = false;\n            Assert.False(c.EnableViewState);\n            Assert.False((c).EnableViewState);\n\n            c.EnableViewState = true;\n            Assert.True(c.EnableViewState);\n            Assert.True((c).EnableViewState);\n        }\n\n        [Fact]\n        public void ViewContextWithNoPageIsNull()\n        {\n            // Setup\n            DummyMvcControl c = new DummyMvcControl();\n            Control c1 = new Control();\n            c1.Controls.Add(c);\n\n            // Execute\n            ViewContext vc = c.ViewContext;\n\n            // Verify\n            Assert.Null(vc);\n        }\n\n        private sealed class DummyMvcControl : MvcControl\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Controls/Test/MvcTestHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Web.UI;\n\nnamespace Microsoft.Web.Mvc.Controls.Test\n{\n    public static class MvcTestHelper\n    {\n        public static string GetControlRendering(Control c, bool designMode)\n        {\n            if (designMode)\n            {\n                c.Site = new DesignModeSite();\n            }\n            HtmlTextWriter writer = new HtmlTextWriter(new StringWriter());\n            c.RenderControl(writer);\n            return writer.InnerWriter.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Controls/Test/ViewDataContainer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc;\nusing System.Web.UI;\n\nnamespace Microsoft.Web.Mvc.Controls.Test\n{\n    public class ViewDataContainer : Control, IViewDataContainer\n    {\n        public ViewDataDictionary ViewData { get; set; }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Microsoft.Web.Mvc.Test.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props\" Condition=\"Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" />\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" />\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{6C28DA70-60F1-4442-967F-591BF3962EC5}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>Microsoft.Web</RootNamespace>\n    <AssemblyName>Microsoft.Web.Mvc.Test</AssemblyName>\n    <OutputPath>..\\..\\bin\\$(Configuration)\\Test\\</OutputPath>\n    <!-- Force signing off -->\n    <SignAssembly>false</SignAssembly>\n    <NuGetPackageImportStamp>\n    </NuGetPackageImportStamp>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Castle.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Castle.Core.5.1.1\\lib\\net462\\Castle.Core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"Moq, Version=4.18.0.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Moq.4.18.4\\lib\\net462\\Moq.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Newtonsoft.Json.13.0.1\\lib\\net45\\Newtonsoft.Json.dll</HintPath>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.ComponentModel.DataAnnotations\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Data.Linq\" />\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"System.Web.Abstractions\" />\n    <Reference Include=\"System.Web.Routing\" />\n    <Reference Include=\"xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.abstractions.2.0.3\\lib\\net35\\xunit.abstractions.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.assert, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.assert.2.4.2\\lib\\netstandard1.1\\xunit.assert.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.core, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.core.2.4.2\\lib\\net452\\xunit.core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.execution.desktop, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.execution.2.4.2\\lib\\net452\\xunit.execution.desktop.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"Controls\\Test\\DesignModeSite.cs\" />\n    <Compile Include=\"Controls\\Test\\DropDownListTest.cs\" />\n    <Compile Include=\"Controls\\Test\\MvcControlTest.cs\" />\n    <Compile Include=\"Controls\\Test\\MvcTestHelper.cs\" />\n    <Compile Include=\"Controls\\Test\\ViewDataContainer.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\BindingBehaviorAttributeTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\BinaryDataModelBinderProviderTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\ExtensibleModelBinderAdapterTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\ExtensibleModelBindingContextTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\GenericModelBinderProviderTest.cs\" />\n    <Compile Include=\"Test\\AreaHelpersTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\CollectionModelBinderProviderTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\CollectionModelBinderTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\CollectionModelBinderUtilTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\ComplexModelDtoResultTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\ComplexModelDtoTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\ComplexModelDtoModelBinderTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\ComplexModelDtoModelBinderProviderTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\ArrayModelBinderTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\ArrayModelBinderProviderTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\DictionaryModelBinderProviderTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\DictionaryModelBinderTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\KeyValuePairModelBinderUtilTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\KeyValuePairModelBinderTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\KeyValuePairModelBinderProviderTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\MutableObjectModelBinderProviderTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\MutableObjectModelBinderTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\TypeConverterModelBinderTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\TypeConverterModelBinderProviderTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\ModelBinderConfigTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\SimpleModelBinderProviderTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\TypeMatchModelBinderProviderTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\TypeMatchModelBinderTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\ModelBinderProviderCollectionTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\ModelBinderUtilTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\ModelValidationNodeTest.cs\" />\n    <Compile Include=\"ModelBinding\\Test\\ModelBinderProvidersTest.cs\" />\n    <Compile Include=\"Test\\ButtonTest.cs\" />\n    <Compile Include=\"Test\\ContentTypeAttributeTest.cs\" />\n    <Compile Include=\"Test\\ControllerExtensionsTest.cs\" />\n    <Compile Include=\"Test\\AjaxOnlyAttributeTest.cs\" />\n    <Compile Include=\"Test\\AsyncManagerExtensionsTest.cs\" />\n    <Compile Include=\"Test\\CookieValueProviderFactoryTest.cs\" />\n    <Compile Include=\"Test\\AcceptAttributeTest.cs\" />\n    <Compile Include=\"Test\\CreditCardAttributeTest.cs\" />\n    <Compile Include=\"Test\\DynamicReflectionObjectTest.cs\" />\n    <Compile Include=\"Test\\DynamicViewDataDictionaryTest.cs\" />\n    <Compile Include=\"Test\\DynamicViewPageTest.cs\" />\n    <Compile Include=\"Test\\EmailAddressAttribueTest.cs\" />\n    <Compile Include=\"Test\\FileExtensionsAttributeTest.cs\" />\n    <Compile Include=\"Test\\ModelCopierTest.cs\" />\n    <Compile Include=\"Test\\ElementalValueProviderTest.cs\" />\n    <Compile Include=\"Test\\UrlAttributeTest.cs\" />\n    <Compile Include=\"Test\\ValueProviderUtilTest.cs\" />\n    <Compile Include=\"Test\\TempDataValueProviderFactoryTest.cs\" />\n    <Compile Include=\"Test\\SessionValueProviderFactoryTest.cs\" />\n    <Compile Include=\"Test\\ServerVariablesValueProviderFactoryTest.cs\" />\n    <Compile Include=\"Test\\CopyAsyncParametersAttributeTest.cs\" />\n    <Compile Include=\"Test\\CssExtensionsTests.cs\" />\n    <Compile Include=\"Test\\DeserializeAttributeTest.cs\" />\n    <Compile Include=\"Test\\ScriptExtensionsTest.cs\" />\n    <Compile Include=\"Test\\SerializationExtensionsTest.cs\" />\n    <Compile Include=\"Test\\MvcSerializerTest.cs\" />\n    <Compile Include=\"Test\\ExpressionHelperTest.cs\" />\n    <Compile Include=\"Test\\MailToExtensionsTest.cs\" />\n    <Compile Include=\"Test\\ReaderWriterCacheTest.cs\" />\n    <Compile Include=\"Test\\RenderActionTest.cs\" />\n    <Compile Include=\"Test\\SkipBindingAttributeTest.cs\" />\n    <Compile Include=\"Test\\FormExtensionsTest.cs\" />\n    <Compile Include=\"Test\\RadioExtensionsTest.cs\" />\n    <Compile Include=\"Test\\SubmitImageExtensionsTest.cs\" />\n    <Compile Include=\"Test\\ImageExtensionsTest.cs\" />\n    <Compile Include=\"Test\\SubmitButtonExtensionsTest.cs\" />\n    <Compile Include=\"Test\\TypeHelpersTest.cs\" />\n    <Compile Include=\"Test\\VersionTest.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\..\\src\\Microsoft.Web.Mvc\\Microsoft.Web.Mvc.csproj\">\n      <Project>{D3CF7430-6DA4-42B0-BD90-CA39D16687B2}</Project>\n      <Name>Microsoft.Web.Mvc</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Mvc\\System.Web.Mvc.csproj\">\n      <Project>{3D3FFD8A-624D-4E9B-954B-E1C105507975}</Project>\n      <Name>System.Web.Mvc</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.WebPages\\System.Web.WebPages.csproj\">\n      <Project>{76EFA9C5-8D7E-4FDF-B710-E20F8B6B00D2}</Project>\n      <Name>System.Web.WebPages</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\">\n      <Project>{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}</Project>\n      <Name>Microsoft.TestCommon</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.Mvc.Test\\System.Web.Mvc.Test.csproj\">\n      <Project>{8AC2A2E4-2F11-4D40-A887-62E2583A65E6}</Project>\n      <Name>System.Web.Mvc.Test</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Service Include=\"{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Analyzer Include=\"..\\..\\packages\\xunit.analyzers.1.1.0\\analyzers\\dotnet\\cs\\xunit.analyzers.dll\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\n  <Target Name=\"EnsureNuGetPackageBuildImports\" BeforeTargets=\"PrepareForBuild\">\n    <PropertyGroup>\n      <ErrorText>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}.</ErrorText>\n    </PropertyGroup>\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props'))\" />\n  </Target>\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" />\n</Project>"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/ArrayModelBinderProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class ArrayModelBinderProviderTest\n    {\n        [Fact]\n        public void GetBinder_CorrectModelTypeAndValueProviderEntries_ReturnsBinder()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int[])),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"foo[0]\", \"42\" },\n                }\n            };\n\n            ArrayModelBinderProvider binderProvider = new ArrayModelBinderProvider();\n\n            // Act\n            IExtensibleModelBinder binder = binderProvider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.IsType<ArrayModelBinder<int>>(binder);\n        }\n\n        [Fact]\n        public void GetBinder_ModelMetadataReturnsReadOnly_ReturnsNull()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int[])),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"foo[0]\", \"42\" },\n                }\n            };\n            bindingContext.ModelMetadata.IsReadOnly = true;\n\n            ArrayModelBinderProvider binderProvider = new ArrayModelBinderProvider();\n\n            // Act\n            IExtensibleModelBinder binder = binderProvider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        [Fact]\n        public void GetBinder_ModelTypeIsIncorrect_ReturnsNull()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(ICollection<int>)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"foo[0]\", \"42\" },\n                }\n            };\n\n            ArrayModelBinderProvider binderProvider = new ArrayModelBinderProvider();\n\n            // Act\n            IExtensibleModelBinder binder = binderProvider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        [Fact]\n        public void GetBinder_ValueProviderDoesNotContainPrefix_ReturnsNull()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int[])),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider()\n            };\n\n            ArrayModelBinderProvider binderProvider = new ArrayModelBinderProvider();\n\n            // Act\n            IExtensibleModelBinder binder = binderProvider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.Null(binder);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/ArrayModelBinderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\nusing Moq;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class ArrayModelBinderTest\n    {\n        [Fact]\n        public void BindModel()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int[])),\n                ModelName = \"someName\",\n                ModelBinderProviders = new ModelBinderProviderCollection(),\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"someName[0]\", \"42\" },\n                    { \"someName[1]\", \"84\" }\n                }\n            };\n\n            Mock<IExtensibleModelBinder> mockIntBinder = new Mock<IExtensibleModelBinder>();\n            mockIntBinder\n                .Setup(o => o.BindModel(controllerContext, It.IsAny<ExtensibleModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ExtensibleModelBindingContext mbc)\n                    {\n                        mbc.Model = mbc.ValueProvider.GetValue(mbc.ModelName).ConvertTo(mbc.ModelType);\n                        return true;\n                    });\n            bindingContext.ModelBinderProviders.RegisterBinderForType(typeof(int), mockIntBinder.Object, false /* suppressPrefixCheck */);\n\n            // Act\n            bool retVal = new ArrayModelBinder<int>().BindModel(controllerContext, bindingContext);\n\n            // Assert\n            Assert.True(retVal);\n\n            int[] array = bindingContext.Model as int[];\n            Assert.Equal(new[] { 42, 84 }, array);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/BinaryDataModelBinderProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Data.Linq;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class BinaryDataModelBinderProviderTest\n    {\n        private static readonly byte[] _base64Bytes = new byte[] { 0x12, 0x20, 0x34, 0x40 };\n        private const string _base64String = \"EiA0QA==\";\n\n        [Fact]\n        public void BindModel_BadValue_Fails()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(byte[])),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"foo\", \"not base64 encoded!\" }\n                }\n            };\n\n            BinaryDataModelBinderProvider binderProvider = new BinaryDataModelBinderProvider();\n\n            // Act\n            IExtensibleModelBinder binder = binderProvider.GetBinder(null, bindingContext);\n            bool retVal = binder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.False(retVal);\n        }\n\n        [Fact]\n        public void BindModel_EmptyValue_Fails()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(byte[])),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"foo\", \"\" }\n                }\n            };\n\n            BinaryDataModelBinderProvider binderProvider = new BinaryDataModelBinderProvider();\n\n            // Act\n            IExtensibleModelBinder binder = binderProvider.GetBinder(null, bindingContext);\n            bool retVal = binder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.False(retVal);\n        }\n\n        [Fact]\n        public void BindModel_GoodValue_ByteArray_Succeeds()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(byte[])),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"foo\", _base64String }\n                }\n            };\n\n            BinaryDataModelBinderProvider binderProvider = new BinaryDataModelBinderProvider();\n\n            // Act\n            IExtensibleModelBinder binder = binderProvider.GetBinder(null, bindingContext);\n            bool retVal = binder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Equal(_base64Bytes, (byte[])bindingContext.Model);\n        }\n\n        [Fact]\n        public void BindModel_GoodValue_LinqBinary_Succeeds()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(Binary)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"foo\", _base64String }\n                }\n            };\n\n            BinaryDataModelBinderProvider binderProvider = new BinaryDataModelBinderProvider();\n\n            // Act\n            IExtensibleModelBinder binder = binderProvider.GetBinder(null, bindingContext);\n            bool retVal = binder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.True(retVal);\n            Binary binaryModel = Assert.IsType<Binary>(bindingContext.Model);\n            Assert.Equal(_base64Bytes, binaryModel.ToArray());\n        }\n\n        [Fact]\n        public void BindModel_NoValue_Fails()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(byte[])),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"foo.bar\", _base64String }\n                }\n            };\n\n            BinaryDataModelBinderProvider binderProvider = new BinaryDataModelBinderProvider();\n\n            // Act\n            IExtensibleModelBinder binder = binderProvider.GetBinder(null, bindingContext);\n            bool retVal = binder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.False(retVal);\n        }\n\n        [Fact]\n        public void GetBinder_WrongModelType_ReturnsNull()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(object)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"foo\", _base64String }\n                }\n            };\n\n            BinaryDataModelBinderProvider binderProvider = new BinaryDataModelBinderProvider();\n\n            // Act\n            IExtensibleModelBinder modelBinder = binderProvider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.Null(modelBinder);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/BindingBehaviorAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class BindingBehaviorAttributeTest\n    {\n        [Fact]\n        public void Behavior_Property()\n        {\n            // Arrange\n            BindingBehavior expectedBehavior = (BindingBehavior)(-20);\n\n            // Act\n            BindingBehaviorAttribute attr = new BindingBehaviorAttribute(expectedBehavior);\n\n            // Assert\n            Assert.Equal(expectedBehavior, attr.Behavior);\n        }\n\n        [Fact]\n        public void TypeId_ReturnsSameValue()\n        {\n            // Arrange\n            BindNeverAttribute neverAttr = new BindNeverAttribute();\n            BindRequiredAttribute requiredAttr = new BindRequiredAttribute();\n\n            // Act & assert\n            Assert.Same(neverAttr.TypeId, requiredAttr.TypeId);\n        }\n\n        [Fact]\n        public void BindNever_SetsBehavior()\n        {\n            // Act\n            BindingBehaviorAttribute attr = new BindNeverAttribute();\n\n            // Assert\n            Assert.Equal(BindingBehavior.Never, attr.Behavior);\n        }\n\n        [Fact]\n        public void BindRequired_SetsBehavior()\n        {\n            // Act\n            BindingBehaviorAttribute attr = new BindRequiredAttribute();\n\n            // Assert\n            Assert.Equal(BindingBehavior.Required, attr.Behavior);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/CollectionModelBinderProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class CollectionModelBinderProviderTest\n    {\n        [Fact]\n        public void GetBinder_CorrectModelTypeAndValueProviderEntries_ReturnsBinder()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(IEnumerable<int>)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"foo[0]\", \"42\" },\n                }\n            };\n\n            CollectionModelBinderProvider binderProvider = new CollectionModelBinderProvider();\n\n            // Act\n            IExtensibleModelBinder binder = binderProvider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.IsType<CollectionModelBinder<int>>(binder);\n        }\n\n        [Fact]\n        public void GetBinder_ModelTypeIsIncorrect_ReturnsNull()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"foo[0]\", \"42\" },\n                }\n            };\n\n            CollectionModelBinderProvider binderProvider = new CollectionModelBinderProvider();\n\n            // Act\n            IExtensibleModelBinder binder = binderProvider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        [Fact]\n        public void GetBinder_ValueProviderDoesNotContainPrefix_ReturnsNull()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(IEnumerable<int>)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider()\n            };\n\n            CollectionModelBinderProvider binderProvider = new CollectionModelBinderProvider();\n\n            // Act\n            IExtensibleModelBinder binder = binderProvider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.Null(binder);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/CollectionModelBinderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\nusing Moq;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class CollectionModelBinderTest\n    {\n        [Fact]\n        public void BindComplexCollectionFromIndexes_FiniteIndexes()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            CultureInfo culture = CultureInfo.GetCultureInfo(\"fr-FR\");\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),\n                ModelName = \"someName\",\n                ModelBinderProviders = new ModelBinderProviderCollection(),\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"someName[foo]\", \"42\" },\n                    { \"someName[baz]\", \"200\" }\n                }\n            };\n\n            Mock<IExtensibleModelBinder> mockIntBinder = new Mock<IExtensibleModelBinder>();\n            mockIntBinder\n                .Setup(o => o.BindModel(controllerContext, It.IsAny<ExtensibleModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ExtensibleModelBindingContext mbc)\n                    {\n                        mbc.Model = mbc.ValueProvider.GetValue(mbc.ModelName).ConvertTo(mbc.ModelType);\n                        return true;\n                    });\n            bindingContext.ModelBinderProviders.RegisterBinderForType(typeof(int), mockIntBinder.Object, false /* suppressPrefixCheck */);\n\n            // Act\n            List<int> boundCollection = CollectionModelBinder<int>.BindComplexCollectionFromIndexes(controllerContext, bindingContext, new[] { \"foo\", \"bar\", \"baz\" });\n\n            // Assert\n            Assert.Equal(new[] { 42, 0, 200 }, boundCollection.ToArray());\n            Assert.Equal(new[] { \"someName[foo]\", \"someName[baz]\" }, bindingContext.ValidationNode.ChildNodes.Select(o => o.ModelStateKey).ToArray());\n        }\n\n        [Fact]\n        public void BindComplexCollectionFromIndexes_InfiniteIndexes()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            CultureInfo culture = CultureInfo.GetCultureInfo(\"fr-FR\");\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),\n                ModelName = \"someName\",\n                ModelBinderProviders = new ModelBinderProviderCollection(),\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"someName[0]\", \"42\" },\n                    { \"someName[1]\", \"100\" },\n                    { \"someName[3]\", \"400\" }\n                }\n            };\n\n            Mock<IExtensibleModelBinder> mockIntBinder = new Mock<IExtensibleModelBinder>();\n            mockIntBinder\n                .Setup(o => o.BindModel(controllerContext, It.IsAny<ExtensibleModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ExtensibleModelBindingContext mbc)\n                    {\n                        mbc.Model = mbc.ValueProvider.GetValue(mbc.ModelName).ConvertTo(mbc.ModelType);\n                        return true;\n                    });\n            bindingContext.ModelBinderProviders.RegisterBinderForType(typeof(int), mockIntBinder.Object, false /* suppressPrefixCheck */);\n\n            // Act\n            List<int> boundCollection = CollectionModelBinder<int>.BindComplexCollectionFromIndexes(controllerContext, bindingContext, null /* indexNames */);\n\n            // Assert\n            Assert.Equal(new[] { 42, 100 }, boundCollection.ToArray());\n            Assert.Equal(new[] { \"someName[0]\", \"someName[1]\" }, bindingContext.ValidationNode.ChildNodes.Select(o => o.ModelStateKey).ToArray());\n        }\n\n        [Fact]\n        public void BindModel_ComplexCollection()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            CultureInfo culture = CultureInfo.GetCultureInfo(\"fr-FR\");\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),\n                ModelName = \"someName\",\n                ModelBinderProviders = new ModelBinderProviderCollection(),\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"someName.index\", new[] { \"foo\", \"bar\", \"baz\" } },\n                    { \"someName[foo]\", \"42\" },\n                    { \"someName[bar]\", \"100\" },\n                    { \"someName[baz]\", \"200\" }\n                }\n            };\n\n            Mock<IExtensibleModelBinder> mockIntBinder = new Mock<IExtensibleModelBinder>();\n            mockIntBinder\n                .Setup(o => o.BindModel(controllerContext, It.IsAny<ExtensibleModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ExtensibleModelBindingContext mbc)\n                    {\n                        mbc.Model = mbc.ValueProvider.GetValue(mbc.ModelName).ConvertTo(mbc.ModelType);\n                        return true;\n                    });\n            bindingContext.ModelBinderProviders.RegisterBinderForType(typeof(int), mockIntBinder.Object, true /* suppressPrefixCheck */);\n\n            CollectionModelBinder<int> modelBinder = new CollectionModelBinder<int>();\n\n            // Act\n            bool retVal = modelBinder.BindModel(controllerContext, bindingContext);\n\n            // Assert\n            Assert.Equal(new[] { 42, 100, 200 }, ((List<int>)bindingContext.Model).ToArray());\n        }\n\n        [Fact]\n        public void BindModel_SimpleCollection()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            CultureInfo culture = CultureInfo.GetCultureInfo(\"fr-FR\");\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),\n                ModelName = \"someName\",\n                ModelBinderProviders = new ModelBinderProviderCollection(),\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"someName\", new[] { \"42\", \"100\", \"200\" } }\n                }\n            };\n\n            Mock<IExtensibleModelBinder> mockIntBinder = new Mock<IExtensibleModelBinder>();\n            mockIntBinder\n                .Setup(o => o.BindModel(controllerContext, It.IsAny<ExtensibleModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ExtensibleModelBindingContext mbc)\n                    {\n                        mbc.Model = mbc.ValueProvider.GetValue(mbc.ModelName).ConvertTo(mbc.ModelType);\n                        return true;\n                    });\n            bindingContext.ModelBinderProviders.RegisterBinderForType(typeof(int), mockIntBinder.Object, true /* suppressPrefixCheck */);\n\n            CollectionModelBinder<int> modelBinder = new CollectionModelBinder<int>();\n\n            // Act\n            bool retVal = modelBinder.BindModel(controllerContext, bindingContext);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Equal(new[] { 42, 100, 200 }, ((List<int>)bindingContext.Model).ToArray());\n        }\n\n        [Fact]\n        public void BindSimpleCollection_RawValueIsEmptyCollection_ReturnsEmptyList()\n        {\n            // Act\n            List<int> boundCollection = CollectionModelBinder<int>.BindSimpleCollection(null, null, new object[0], null);\n\n            // Assert\n            Assert.NotNull(boundCollection);\n            Assert.Empty(boundCollection);\n        }\n\n        [Fact]\n        public void BindSimpleCollection_RawValueIsNull_ReturnsNull()\n        {\n            // Act\n            List<int> boundCollection = CollectionModelBinder<int>.BindSimpleCollection(null, null, null, null);\n\n            // Assert\n            Assert.Null(boundCollection);\n        }\n\n        [Fact]\n        public void BindSimpleCollection_SubBinderDoesNotExist()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            CultureInfo culture = CultureInfo.GetCultureInfo(\"fr-FR\");\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),\n                ModelName = \"someName\",\n                ModelBinderProviders = new ModelBinderProviderCollection(),\n                ValueProvider = new SimpleValueProvider()\n            };\n\n            // Act\n            List<int> boundCollection = CollectionModelBinder<int>.BindSimpleCollection(controllerContext, bindingContext, new int[1], culture);\n\n            // Assert\n            Assert.Equal(new[] { 0 }, boundCollection.ToArray());\n            Assert.Empty(bindingContext.ValidationNode.ChildNodes);\n        }\n\n        [Fact]\n        public void BindSimpleCollection_SubBindingSucceeds()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            CultureInfo culture = CultureInfo.GetCultureInfo(\"fr-FR\");\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),\n                ModelName = \"someName\",\n                ModelBinderProviders = new ModelBinderProviderCollection(),\n                ValueProvider = new SimpleValueProvider()\n            };\n\n            ModelValidationNode childValidationNode = null;\n            Mock<IExtensibleModelBinder> mockIntBinder = new Mock<IExtensibleModelBinder>();\n            mockIntBinder\n                .Setup(o => o.BindModel(controllerContext, It.IsAny<ExtensibleModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ExtensibleModelBindingContext mbc)\n                    {\n                        Assert.Equal(\"someName\", mbc.ModelName);\n                        childValidationNode = mbc.ValidationNode;\n                        mbc.Model = 42;\n                        return true;\n                    });\n            bindingContext.ModelBinderProviders.RegisterBinderForType(typeof(int), mockIntBinder.Object, true /* suppressPrefixCheck */);\n\n            // Act\n            List<int> boundCollection = CollectionModelBinder<int>.BindSimpleCollection(controllerContext, bindingContext, new int[1], culture);\n\n            // Assert\n            Assert.Equal(new[] { 42 }, boundCollection.ToArray());\n            Assert.Equal(new[] { childValidationNode }, bindingContext.ValidationNode.ChildNodes.ToArray());\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/CollectionModelBinderUtilTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class CollectionModelBinderUtilTest\n    {\n        [Fact]\n        public void CreateOrReplaceCollection_OriginalModelImmutable_CreatesNewInstance()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => new ReadOnlyCollection<int>(new int[0]), typeof(ICollection<int>))\n            };\n\n            // Act\n            CollectionModelBinderUtil.CreateOrReplaceCollection(bindingContext, new[] { 10, 20, 30 }, () => new List<int>());\n\n            // Assert\n            int[] newModel = (bindingContext.Model as ICollection<int>).ToArray();\n            Assert.Equal(new[] { 10, 20, 30 }, newModel);\n        }\n\n        [Fact]\n        public void CreateOrReplaceCollection_OriginalModelMutable_UpdatesOriginalInstance()\n        {\n            // Arrange\n            List<int> originalInstance = new List<int> { 10, 20, 30 };\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => originalInstance, typeof(ICollection<int>))\n            };\n\n            // Act\n            CollectionModelBinderUtil.CreateOrReplaceCollection(bindingContext, new[] { 40, 50, 60 }, () => new List<int>());\n\n            // Assert\n            Assert.Same(originalInstance, bindingContext.Model);\n            Assert.Equal(new[] { 40, 50, 60 }, originalInstance.ToArray());\n        }\n\n        [Fact]\n        public void CreateOrReplaceCollection_OriginalModelNotCollection_CreatesNewInstance()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(ICollection<int>))\n            };\n\n            // Act\n            CollectionModelBinderUtil.CreateOrReplaceCollection(bindingContext, new[] { 10, 20, 30 }, () => new List<int>());\n\n            // Assert\n            int[] newModel = (bindingContext.Model as ICollection<int>).ToArray();\n            Assert.Equal(new[] { 10, 20, 30 }, newModel);\n        }\n\n        [Fact]\n        public void CreateOrReplaceDictionary_DisallowsDuplicateKeys()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(Dictionary<string, int>))\n            };\n\n            // Act\n            CollectionModelBinderUtil.CreateOrReplaceDictionary(\n                bindingContext,\n                new[]\n                {\n                    new KeyValuePair<string, int>(\"forty-two\", 40),\n                    new KeyValuePair<string, int>(\"forty-two\", 2),\n                    new KeyValuePair<string, int>(\"forty-two\", 42)\n                },\n                () => new Dictionary<string, int>());\n\n            // Assert\n            IDictionary<string, int> newModel = bindingContext.Model as IDictionary<string, int>;\n            Assert.Equal(new[] { \"forty-two\" }, newModel.Keys.ToArray());\n            Assert.Equal(42, newModel[\"forty-two\"]);\n        }\n\n        [Fact]\n        public void CreateOrReplaceDictionary_DisallowsNullKeys()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(Dictionary<string, int>))\n            };\n\n            // Act\n            CollectionModelBinderUtil.CreateOrReplaceDictionary(\n                bindingContext,\n                new[]\n                {\n                    new KeyValuePair<string, int>(\"forty-two\", 42),\n                    new KeyValuePair<string, int>(null, 84)\n                },\n                () => new Dictionary<string, int>());\n\n            // Assert\n            IDictionary<string, int> newModel = bindingContext.Model as IDictionary<string, int>;\n            Assert.Equal(new[] { \"forty-two\" }, newModel.Keys.ToArray());\n            Assert.Equal(42, newModel[\"forty-two\"]);\n        }\n\n        [Fact]\n        public void CreateOrReplaceDictionary_OriginalModelImmutable_CreatesNewInstance()\n        {\n            // Arrange\n            ReadOnlyDictionary<string, string> originalModel = new ReadOnlyDictionary<string, string>();\n\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => originalModel, typeof(IDictionary<string, string>))\n            };\n\n            // Act\n            CollectionModelBinderUtil.CreateOrReplaceDictionary(\n                bindingContext,\n                new Dictionary<string, string>\n                {\n                    { \"Hello\", \"World\" }\n                },\n                () => new Dictionary<string, string>());\n\n            // Assert\n            IDictionary<string, string> newModel = bindingContext.Model as IDictionary<string, string>;\n            Assert.NotSame(originalModel, newModel);\n            Assert.Equal(new[] { \"Hello\" }, newModel.Keys.ToArray());\n            Assert.Equal(\"World\", newModel[\"Hello\"]);\n        }\n\n        [Fact]\n        public void CreateOrReplaceDictionary_OriginalModelMutable_UpdatesOriginalInstance()\n        {\n            // Arrange\n            Dictionary<string, string> originalInstance = new Dictionary<string, string>\n            {\n                { \"dog\", \"Canidae\" },\n                { \"cat\", \"Felidae\" }\n            };\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => originalInstance, typeof(IDictionary<string, string>))\n            };\n\n            // Act\n            CollectionModelBinderUtil.CreateOrReplaceDictionary(\n                bindingContext,\n                new Dictionary<string, string>\n                {\n                    { \"horse\", \"Equidae\" },\n                    { \"bear\", \"Ursidae\" }\n                },\n                () => new Dictionary<string, string>());\n\n            // Assert\n            Assert.Same(originalInstance, bindingContext.Model);\n            Assert.Equal(new[] { \"horse\", \"bear\" }, originalInstance.Keys.ToArray());\n            Assert.Equal(\"Equidae\", originalInstance[\"horse\"]);\n            Assert.Equal(\"Ursidae\", originalInstance[\"bear\"]);\n        }\n\n        [Fact]\n        public void CreateOrReplaceDictionary_OriginalModelNotDictionary_CreatesNewInstance()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(IDictionary<string, string>))\n            };\n\n            // Act\n            CollectionModelBinderUtil.CreateOrReplaceDictionary(\n                bindingContext,\n                new Dictionary<string, string>\n                {\n                    { \"horse\", \"Equidae\" },\n                    { \"bear\", \"Ursidae\" }\n                },\n                () => new Dictionary<string, string>());\n\n            // Assert\n            IDictionary<string, string> newModel = bindingContext.Model as IDictionary<string, string>;\n            Assert.Equal(new[] { \"horse\", \"bear\" }, newModel.Keys.ToArray());\n            Assert.Equal(\"Equidae\", newModel[\"horse\"]);\n            Assert.Equal(\"Ursidae\", newModel[\"bear\"]);\n        }\n\n        [Fact]\n        public void GetIndexNamesFromValueProviderResult_ValueProviderResultIsNull_ReturnsNull()\n        {\n            // Act\n            IEnumerable<string> indexNames = CollectionModelBinderUtil.GetIndexNamesFromValueProviderResult(null);\n\n            // Assert\n            Assert.Null(indexNames);\n        }\n\n        [Fact]\n        public void GetIndexNamesFromValueProviderResult_ValueProviderResultReturnsEmptyArray_ReturnsNull()\n        {\n            // Arrange\n            ValueProviderResult vpResult = new ValueProviderResult(new string[0], \"\", null);\n\n            // Act\n            IEnumerable<string> indexNames = CollectionModelBinderUtil.GetIndexNamesFromValueProviderResult(vpResult);\n\n            // Assert\n            Assert.Null(indexNames);\n        }\n\n        [Fact]\n        public void GetIndexNamesFromValueProviderResult_ValueProviderResultReturnsNonEmptyArray_ReturnsArray()\n        {\n            // Arrange\n            ValueProviderResult vpResult = new ValueProviderResult(new[] { \"foo\", \"bar\", \"baz\" }, \"foo,bar,baz\", null);\n\n            // Act\n            IEnumerable<string> indexNames = CollectionModelBinderUtil.GetIndexNamesFromValueProviderResult(vpResult);\n\n            // Assert\n            Assert.NotNull(indexNames);\n            Assert.Equal(new[] { \"foo\", \"bar\", \"baz\" }, indexNames.ToArray());\n        }\n\n        [Fact]\n        public void GetIndexNamesFromValueProviderResult_ValueProviderResultReturnsNull_ReturnsNull()\n        {\n            // Arrange\n            ValueProviderResult vpResult = new ValueProviderResult(null, null, null);\n\n            // Act\n            IEnumerable<string> indexNames = CollectionModelBinderUtil.GetIndexNamesFromValueProviderResult(vpResult);\n\n            // Assert\n            Assert.Null(indexNames);\n        }\n\n        [Fact]\n        public void GetTypeArgumentsForUpdatableGenericCollection_ModelTypeNotGeneric_Fail()\n        {\n            // Arrange\n            ModelMetadata modelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int));\n\n            // Act\n            Type[] typeArguments = CollectionModelBinderUtil.GetTypeArgumentsForUpdatableGenericCollection(null, null, modelMetadata);\n\n            // Assert\n            Assert.Null(typeArguments);\n        }\n\n        [Fact]\n        public void GetTypeArgumentsForUpdatableGenericCollection_ModelTypeOpenGeneric_Fail()\n        {\n            // Arrange\n            ModelMetadata modelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(IList<>));\n\n            // Act\n            Type[] typeArguments = CollectionModelBinderUtil.GetTypeArgumentsForUpdatableGenericCollection(null, null, modelMetadata);\n\n            // Assert\n            Assert.Null(typeArguments);\n        }\n\n        [Fact]\n        public void GetTypeArgumentsForUpdatableGenericCollection_ModelTypeWrongNumberOfGenericArguments_Fail()\n        {\n            // Arrange\n            ModelMetadata modelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(KeyValuePair<int, string>));\n\n            // Act\n            Type[] typeArguments = CollectionModelBinderUtil.GetTypeArgumentsForUpdatableGenericCollection(typeof(ICollection<>), null, modelMetadata);\n\n            // Assert\n            Assert.Null(typeArguments);\n        }\n\n        [Fact]\n        public void GetTypeArgumentsForUpdatableGenericCollection_ReadOnlyReference_ModelInstanceImmutable_Valid()\n        {\n            // Arrange\n            ModelMetadata modelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => new int[0], typeof(IList<int>));\n            modelMetadata.IsReadOnly = true;\n\n            // Act\n            Type[] typeArguments = CollectionModelBinderUtil.GetTypeArgumentsForUpdatableGenericCollection(typeof(IList<>), typeof(List<>), modelMetadata);\n\n            // Assert\n            Assert.Null(typeArguments);\n        }\n\n        [Fact]\n        public void GetTypeArgumentsForUpdatableGenericCollection_ReadOnlyReference_ModelInstanceMutable_Valid()\n        {\n            // Arrange\n            ModelMetadata modelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => new List<int>(), typeof(IList<int>));\n            modelMetadata.IsReadOnly = true;\n\n            // Act\n            Type[] typeArguments = CollectionModelBinderUtil.GetTypeArgumentsForUpdatableGenericCollection(typeof(IList<>), typeof(List<>), modelMetadata);\n\n            // Assert\n            Assert.Equal(new[] { typeof(int) }, typeArguments);\n        }\n\n        [Fact]\n        public void GetTypeArgumentsForUpdatableGenericCollection_ReadOnlyReference_ModelInstanceOfWrongType_Fail()\n        {\n            // Arrange\n            ModelMetadata modelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => new HashSet<int>(), typeof(ICollection<int>));\n            modelMetadata.IsReadOnly = true;\n\n            // Act\n            Type[] typeArguments = CollectionModelBinderUtil.GetTypeArgumentsForUpdatableGenericCollection(typeof(IList<>), typeof(List<>), modelMetadata);\n\n            // Assert\n            // HashSet<> is not an IList<>, so we can't update\n            Assert.Null(typeArguments);\n        }\n\n        [Fact]\n        public void GetTypeArgumentsForUpdatableGenericCollection_ReadOnlyReference_ModelIsNull_Fail()\n        {\n            // Arrange\n            ModelMetadata modelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(IList<int>));\n            modelMetadata.IsReadOnly = true;\n\n            // Act\n            Type[] typeArguments = CollectionModelBinderUtil.GetTypeArgumentsForUpdatableGenericCollection(typeof(ICollection<>), typeof(List<>), modelMetadata);\n\n            // Assert\n            Assert.Null(typeArguments);\n        }\n\n        [Fact]\n        public void GetTypeArgumentsForUpdatableGenericCollection_ReadWriteReference_NewInstanceAssignableToModelType_Success()\n        {\n            // Arrange\n            ModelMetadata modelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(IList<int>));\n            modelMetadata.IsReadOnly = false;\n\n            // Act\n            Type[] typeArguments = CollectionModelBinderUtil.GetTypeArgumentsForUpdatableGenericCollection(typeof(ICollection<>), typeof(List<>), modelMetadata);\n\n            // Assert\n            Assert.Equal(new[] { typeof(int) }, typeArguments);\n        }\n\n        [Fact]\n        public void GetTypeArgumentsForUpdatableGenericCollection_ReadWriteReference_NewInstanceNotAssignableToModelType_MutableInstance_Success()\n        {\n            // Arrange\n            ModelMetadata modelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => new Collection<int>(), typeof(Collection<int>));\n            modelMetadata.IsReadOnly = false;\n\n            // Act\n            Type[] typeArguments = CollectionModelBinderUtil.GetTypeArgumentsForUpdatableGenericCollection(typeof(ICollection<>), typeof(List<>), modelMetadata);\n\n            // Assert\n            Assert.Equal(new[] { typeof(int) }, typeArguments);\n        }\n\n        [Fact]\n        public void GetZeroBasedIndexes()\n        {\n            // Act\n            string[] indexes = CollectionModelBinderUtil.GetZeroBasedIndexes().Take(5).ToArray();\n\n            // Assert\n            Assert.Equal(new[] { \"0\", \"1\", \"2\", \"3\", \"4\" }, indexes);\n        }\n\n        private class ReadOnlyDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>\n        {\n            bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly\n            {\n                get { return true; }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/ComplexModelDtoModelBinderProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class ComplexModelDtoModelBinderProviderTest\n    {\n        [Fact]\n        public void GetBinder_TypeDoesNotMatch_ReturnsNull()\n        {\n            // Arrange\n            ComplexModelDtoModelBinderProvider provider = new ComplexModelDtoModelBinderProvider();\n            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(object));\n\n            // Act\n            IExtensibleModelBinder binder = provider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        [Fact]\n        public void GetBinder_TypeMatches_ReturnsBinder()\n        {\n            // Arrange\n            ComplexModelDtoModelBinderProvider provider = new ComplexModelDtoModelBinderProvider();\n            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(ComplexModelDto));\n\n            // Act\n            IExtensibleModelBinder binder = provider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.IsType<ComplexModelDtoModelBinder>(binder);\n        }\n\n        private static ExtensibleModelBindingContext GetBindingContext(Type modelType)\n        {\n            return new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => null, modelType)\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/ComplexModelDtoModelBinderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Linq;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class ComplexModelDtoModelBinderTest\n    {\n        [Fact]\n        public void BindModel()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            MyModel model = new MyModel();\n            ModelMetadata modelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => model, typeof(MyModel));\n            ComplexModelDto dto = new ComplexModelDto(modelMetadata, modelMetadata.Properties);\n\n            Mock<IExtensibleModelBinder> mockStringBinder = new Mock<IExtensibleModelBinder>();\n            mockStringBinder\n                .Setup(b => b.BindModel(controllerContext, It.IsAny<ExtensibleModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ExtensibleModelBindingContext mbc)\n                    {\n                        Assert.Equal(typeof(string), mbc.ModelType);\n                        Assert.Equal(\"theModel.StringProperty\", mbc.ModelName);\n                        mbc.ValidationNode = new ModelValidationNode(mbc.ModelMetadata, \"theModel.StringProperty\");\n                        mbc.Model = \"someStringValue\";\n                        return true;\n                    });\n\n            Mock<IExtensibleModelBinder> mockIntBinder = new Mock<IExtensibleModelBinder>();\n            mockIntBinder\n                .Setup(b => b.BindModel(controllerContext, It.IsAny<ExtensibleModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ExtensibleModelBindingContext mbc)\n                    {\n                        Assert.Equal(typeof(int), mbc.ModelType);\n                        Assert.Equal(\"theModel.IntProperty\", mbc.ModelName);\n                        mbc.ValidationNode = new ModelValidationNode(mbc.ModelMetadata, \"theModel.IntProperty\");\n                        mbc.Model = 42;\n                        return true;\n                    });\n\n            Mock<IExtensibleModelBinder> mockDateTimeBinder = new Mock<IExtensibleModelBinder>();\n            mockDateTimeBinder\n                .Setup(b => b.BindModel(controllerContext, It.IsAny<ExtensibleModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ExtensibleModelBindingContext mbc)\n                    {\n                        Assert.Equal(typeof(DateTime), mbc.ModelType);\n                        Assert.Equal(\"theModel.DateTimeProperty\", mbc.ModelName);\n                        return false;\n                    });\n\n            ModelBinderProviderCollection binders = new ModelBinderProviderCollection();\n            binders.RegisterBinderForType(typeof(string), mockStringBinder.Object, true /* suppressPrefixCheck */);\n            binders.RegisterBinderForType(typeof(int), mockIntBinder.Object, true /* suppressPrefixCheck */);\n            binders.RegisterBinderForType(typeof(DateTime), mockDateTimeBinder.Object, true /* suppressPrefixCheck */);\n\n            ExtensibleModelBindingContext parentBindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => dto, typeof(ComplexModelDto)),\n                ModelName = \"theModel\",\n                ModelBinderProviders = binders\n            };\n\n            ComplexModelDtoModelBinder binder = new ComplexModelDtoModelBinder();\n\n            // Act\n            bool retVal = binder.BindModel(controllerContext, parentBindingContext);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Equal(dto, parentBindingContext.Model);\n\n            ComplexModelDtoResult stringDtoResult = dto.Results[dto.PropertyMetadata.Where(m => m.ModelType == typeof(string)).First()];\n            Assert.Equal(\"someStringValue\", stringDtoResult.Model);\n            Assert.Equal(\"theModel.StringProperty\", stringDtoResult.ValidationNode.ModelStateKey);\n\n            ComplexModelDtoResult intDtoResult = dto.Results[dto.PropertyMetadata.Where(m => m.ModelType == typeof(int)).First()];\n            Assert.Equal(42, intDtoResult.Model);\n            Assert.Equal(\"theModel.IntProperty\", intDtoResult.ValidationNode.ModelStateKey);\n\n            ComplexModelDtoResult dateTimeDtoResult = dto.Results[dto.PropertyMetadata.Where(m => m.ModelType == typeof(DateTime)).First()];\n            Assert.Null(dateTimeDtoResult);\n        }\n\n        private static ModelBindingContext GetBindingContext(Type modelType)\n        {\n            return new ModelBindingContext\n            {\n                ModelMetadata = new ModelMetadata(new Mock<ModelMetadataProvider>().Object, null, null, modelType, \"SomeProperty\")\n            };\n        }\n\n        private sealed class MyModel\n        {\n            public string StringProperty { get; set; }\n            public int IntProperty { get; set; }\n            public object ObjectProperty { get; set; } // no binding should happen since no registered binder\n            public DateTime DateTimeProperty { get; set; } // registered binder returns false\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/ComplexModelDtoResultTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class ComplexModelDtoResultTest\n    {\n        [Fact]\n        public void Constructor_ThrowsIfValidationNodeIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ComplexModelDtoResult(\"some string\", null); }, \"validationNode\");\n        }\n\n        [Fact]\n        public void Constructor_SetsProperties()\n        {\n            // Arrange\n            ModelValidationNode validationNode = GetValidationNode();\n\n            // Act\n            ComplexModelDtoResult result = new ComplexModelDtoResult(\"some string\", validationNode);\n\n            // Assert\n            Assert.Equal(\"some string\", result.Model);\n            Assert.Equal(validationNode, result.ValidationNode);\n        }\n\n        private static ModelValidationNode GetValidationNode()\n        {\n            EmptyModelMetadataProvider provider = new EmptyModelMetadataProvider();\n            ModelMetadata metadata = provider.GetMetadataForType(null, typeof(object));\n            return new ModelValidationNode(metadata, \"someKey\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/ComplexModelDtoTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class ComplexModelDtoTest\n    {\n        [Fact]\n        public void ConstructorThrowsIfModelMetadataIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ComplexModelDto(null, Enumerable.Empty<ModelMetadata>()); }, \"modelMetadata\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfPropertyMetadataIsNull()\n        {\n            // Arrange\n            ModelMetadata modelMetadata = GetModelMetadata();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ComplexModelDto(modelMetadata, null); }, \"propertyMetadata\");\n        }\n\n        [Fact]\n        public void ConstructorSetsProperties()\n        {\n            // Arrange\n            ModelMetadata modelMetadata = GetModelMetadata();\n            ModelMetadata[] propertyMetadata = new ModelMetadata[0];\n\n            // Act\n            ComplexModelDto dto = new ComplexModelDto(modelMetadata, propertyMetadata);\n\n            // Assert\n            Assert.Equal(modelMetadata, dto.ModelMetadata);\n            Assert.Equal(propertyMetadata, dto.PropertyMetadata.ToArray());\n            Assert.Empty(dto.Results);\n        }\n\n        private static ModelMetadata GetModelMetadata()\n        {\n            return new ModelMetadata(new EmptyModelMetadataProvider(), typeof(object), null, typeof(object), \"PropertyName\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/DictionaryModelBinderProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class DictionaryModelBinderProviderTest\n    {\n        [Fact]\n        public void GetBinder_CorrectModelTypeAndValueProviderEntries_ReturnsBinder()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(IDictionary<int, string>)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"foo[0]\", \"42\" },\n                }\n            };\n\n            DictionaryModelBinderProvider binderProvider = new DictionaryModelBinderProvider();\n\n            // Act\n            IExtensibleModelBinder binder = binderProvider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.IsType<DictionaryModelBinder<int, string>>(binder);\n        }\n\n        [Fact]\n        public void GetBinder_ModelTypeIsIncorrect_ReturnsNull()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"foo[0]\", \"42\" },\n                }\n            };\n\n            DictionaryModelBinderProvider binderProvider = new DictionaryModelBinderProvider();\n\n            // Act\n            IExtensibleModelBinder binder = binderProvider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        [Fact]\n        public void GetBinder_ValueProviderDoesNotContainPrefix_ReturnsNull()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(IDictionary<int, string>)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider()\n            };\n\n            DictionaryModelBinderProvider binderProvider = new DictionaryModelBinderProvider();\n\n            // Act\n            IExtensibleModelBinder binder = binderProvider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.Null(binder);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/DictionaryModelBinderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\nusing Moq;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class DictionaryModelBinderTest\n    {\n        [Fact]\n        public void BindModel()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(IDictionary<int, string>)),\n                ModelName = \"someName\",\n                ModelBinderProviders = new ModelBinderProviderCollection(),\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"someName[0]\", new KeyValuePair<int, string>(42, \"forty-two\") },\n                    { \"someName[1]\", new KeyValuePair<int, string>(84, \"eighty-four\") }\n                }\n            };\n\n            Mock<IExtensibleModelBinder> mockKvpBinder = new Mock<IExtensibleModelBinder>();\n            mockKvpBinder\n                .Setup(o => o.BindModel(controllerContext, It.IsAny<ExtensibleModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ExtensibleModelBindingContext mbc)\n                    {\n                        mbc.Model = mbc.ValueProvider.GetValue(mbc.ModelName).ConvertTo(mbc.ModelType);\n                        return true;\n                    });\n            bindingContext.ModelBinderProviders.RegisterBinderForType(typeof(KeyValuePair<int, string>), mockKvpBinder.Object, false /* suppressPrefixCheck */);\n\n            // Act\n            bool retVal = new DictionaryModelBinder<int, string>().BindModel(controllerContext, bindingContext);\n\n            // Assert\n            Assert.True(retVal);\n\n            var dictionary = Assert.IsAssignableFrom<IDictionary<int, string>>(bindingContext.Model);\n            Assert.NotNull(dictionary);\n            Assert.Equal(2, dictionary.Count);\n            Assert.Equal(\"forty-two\", dictionary[42]);\n            Assert.Equal(\"eighty-four\", dictionary[84]);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/ExtensibleModelBinderAdapterTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\nusing Moq;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class ExtensibleModelBinderAdapterTest\n    {\n        [Fact]\n        public void BindModel_PropertyFilterIsSet_Throws()\n        {\n            // Arrange\n            ControllerContext controllerContext = GetControllerContext();\n\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                FallbackToEmptyPrefix = true,\n                ModelMetadata = new DataAnnotationsModelMetadataProvider().GetMetadataForType(null, typeof(SimpleModel)),\n                PropertyFilter = (new BindAttribute { Include = \"FirstName \" }).IsPropertyAllowed\n            };\n\n            ModelBinderProviderCollection binderProviders = new ModelBinderProviderCollection();\n            ExtensibleModelBinderAdapter shimBinder = new ExtensibleModelBinderAdapter(binderProviders);\n\n            // Act & assert\n\n            Assert.Throws<InvalidOperationException>(\n                delegate { shimBinder.BindModel(controllerContext, bindingContext); },\n                @\"The new model binding system cannot be used when a property whitelist or blacklist has been specified in [Bind] or via the call to UpdateModel() / TryUpdateModel(). Use the [BindRequired] and [BindNever] attributes on the model type or its properties instead.\");\n        }\n\n        [Fact]\n        public void BindModel_SuccessfulBind_RunsValidationAndReturnsModel()\n        {\n            // Arrange\n            ControllerContext controllerContext = GetControllerContext();\n            bool validationCalled = false;\n\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                FallbackToEmptyPrefix = true,\n                ModelMetadata = new DataAnnotationsModelMetadataProvider().GetMetadataForType(null, typeof(int)),\n                ModelName = \"someName\",\n                ModelState = controllerContext.Controller.ViewData.ModelState,\n                PropertyFilter = _ => true,\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"someName\", \"dummyValue\" }\n                }\n            };\n\n            Mock<IExtensibleModelBinder> mockIntBinder = new Mock<IExtensibleModelBinder>();\n            mockIntBinder\n                .Setup(o => o.BindModel(controllerContext, It.IsAny<ExtensibleModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ExtensibleModelBindingContext mbc)\n                    {\n                        Assert.Same(bindingContext.ModelMetadata, mbc.ModelMetadata);\n                        Assert.Equal(\"someName\", mbc.ModelName);\n                        Assert.Same(bindingContext.ValueProvider, mbc.ValueProvider);\n\n                        mbc.Model = 42;\n                        mbc.ValidationNode.Validating += delegate { validationCalled = true; };\n                        return true;\n                    });\n\n            ModelBinderProviderCollection binderProviders = new ModelBinderProviderCollection();\n            binderProviders.RegisterBinderForType(typeof(int), mockIntBinder.Object, false /* suppressPrefixCheck */);\n            ExtensibleModelBinderAdapter shimBinder = new ExtensibleModelBinderAdapter(binderProviders);\n\n            // Act\n            object retVal = shimBinder.BindModel(controllerContext, bindingContext);\n\n            // Assert\n            Assert.Equal(42, retVal);\n            Assert.True(validationCalled);\n            Assert.True(bindingContext.ModelState.IsValid);\n        }\n\n        [Fact]\n        public void BindModel_SuccessfulBind_ComplexTypeFallback_RunsValidationAndReturnsModel()\n        {\n            // Arrange\n            ControllerContext controllerContext = GetControllerContext();\n\n            bool validationCalled = false;\n            List<int> expectedModel = new List<int> { 1, 2, 3, 4, 5 };\n\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                FallbackToEmptyPrefix = true,\n                ModelMetadata = new DataAnnotationsModelMetadataProvider().GetMetadataForType(null, typeof(List<int>)),\n                ModelName = \"someName\",\n                ModelState = controllerContext.Controller.ViewData.ModelState,\n                PropertyFilter = _ => true,\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"someOtherName\", \"dummyValue\" }\n                }\n            };\n\n            Mock<IExtensibleModelBinder> mockIntBinder = new Mock<IExtensibleModelBinder>();\n            mockIntBinder\n                .Setup(o => o.BindModel(controllerContext, It.IsAny<ExtensibleModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ExtensibleModelBindingContext mbc)\n                    {\n                        Assert.Same(bindingContext.ModelMetadata, mbc.ModelMetadata);\n                        Assert.Equal(\"\", mbc.ModelName);\n                        Assert.Same(bindingContext.ValueProvider, mbc.ValueProvider);\n\n                        mbc.Model = expectedModel;\n                        mbc.ValidationNode.Validating += delegate { validationCalled = true; };\n                        return true;\n                    });\n\n            ModelBinderProviderCollection binderProviders = new ModelBinderProviderCollection();\n            binderProviders.RegisterBinderForType(typeof(List<int>), mockIntBinder.Object, false /* suppressPrefixCheck */);\n            ExtensibleModelBinderAdapter shimBinder = new ExtensibleModelBinderAdapter(binderProviders);\n\n            // Act\n            object retVal = shimBinder.BindModel(controllerContext, bindingContext);\n\n            // Assert\n            Assert.Equal(expectedModel, retVal);\n            Assert.True(validationCalled);\n            Assert.True(bindingContext.ModelState.IsValid);\n        }\n\n        [Fact]\n        public void BindModel_UnsuccessfulBind_BinderFails_ReturnsNull()\n        {\n            // Arrange\n            ControllerContext controllerContext = GetControllerContext();\n            Mock<IExtensibleModelBinder> mockListBinder = new Mock<IExtensibleModelBinder>();\n            mockListBinder.Setup(o => o.BindModel(controllerContext, It.IsAny<ExtensibleModelBindingContext>())).Returns(false).Verifiable();\n\n            ModelBinderProviderCollection binderProviders = new ModelBinderProviderCollection();\n            binderProviders.RegisterBinderForType(typeof(List<int>), mockListBinder.Object, true /* suppressPrefixCheck */);\n            ExtensibleModelBinderAdapter shimBinder = new ExtensibleModelBinderAdapter(binderProviders);\n\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                FallbackToEmptyPrefix = false,\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(List<int>)),\n                ModelState = controllerContext.Controller.ViewData.ModelState\n            };\n\n            // Act\n            object retVal = shimBinder.BindModel(controllerContext, bindingContext);\n\n            // Assert\n            Assert.Null(retVal);\n            Assert.True(bindingContext.ModelState.IsValid);\n            mockListBinder.Verify();\n        }\n\n        [Fact]\n        public void BindModel_UnsuccessfulBind_SimpleTypeNoFallback_ReturnsNull()\n        {\n            // Arrange\n            ControllerContext controllerContext = GetControllerContext();\n            Mock<ModelBinderProvider> mockBinderProvider = new Mock<ModelBinderProvider>();\n            mockBinderProvider.Setup(o => o.GetBinder(controllerContext, It.IsAny<ExtensibleModelBindingContext>())).Returns((IExtensibleModelBinder)null).Verifiable();\n            ModelBinderProviderCollection binderProviders = new ModelBinderProviderCollection\n            {\n                mockBinderProvider.Object\n            };\n            ExtensibleModelBinderAdapter shimBinder = new ExtensibleModelBinderAdapter(binderProviders);\n\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                FallbackToEmptyPrefix = true,\n                ModelMetadata = new DataAnnotationsModelMetadataProvider().GetMetadataForType(null, typeof(int)),\n                ModelState = controllerContext.Controller.ViewData.ModelState\n            };\n\n            // Act\n            object retVal = shimBinder.BindModel(controllerContext, bindingContext);\n\n            // Assert\n            Assert.Null(retVal);\n            Assert.True(bindingContext.ModelState.IsValid);\n            mockBinderProvider.Verify();\n            mockBinderProvider.Verify(o => o.GetBinder(controllerContext, It.IsAny<ExtensibleModelBindingContext>()), Times.AtMostOnce());\n        }\n\n        private static ControllerContext GetControllerContext()\n        {\n            return new ControllerContext\n            {\n                Controller = new SimpleController()\n            };\n        }\n\n        private class SimpleController : Controller\n        {\n        }\n\n        private class SimpleModel\n        {\n            public string FirstName { get; set; }\n            public string LastName { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/ExtensibleModelBindingContextTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Mvc;\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class ExtensibleModelBindingContextTest\n    {\n        [Fact]\n        public void CopyConstructor()\n        {\n            // Arrange\n            ExtensibleModelBindingContext originalBindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(object)),\n                ModelName = \"theName\",\n                ModelState = new ModelStateDictionary(),\n                ValueProvider = new SimpleValueProvider()\n            };\n\n            // Act\n            ExtensibleModelBindingContext newBindingContext = new ExtensibleModelBindingContext(originalBindingContext);\n\n            // Assert\n            Assert.Null(newBindingContext.ModelMetadata);\n            Assert.Equal(\"\", newBindingContext.ModelName);\n            Assert.Equal(originalBindingContext.ModelState, newBindingContext.ModelState);\n            Assert.Equal(originalBindingContext.ValueProvider, newBindingContext.ValueProvider);\n        }\n\n        [Fact]\n        public void ModelBinderProvidersProperty()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext();\n\n            // Act & assert            \n            MemberHelper.TestPropertyWithDefaultInstance(bindingContext, \"ModelBinderProviders\", new ModelBinderProviderCollection(), ModelBinderProviders.Providers);\n        }\n\n        [Fact]\n        public void ModelProperty()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int))\n            };\n\n            // Act & assert            \n            MemberHelper.TestPropertyValue(bindingContext, \"Model\", 42);\n        }\n\n        [Fact]\n        public void ModelProperty_ThrowsIfModelMetadataDoesNotExist()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext();\n\n            // Act & assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { bindingContext.Model = null; },\n                \"The ModelMetadata property must be set before accessing this property.\");\n        }\n\n        [Fact]\n        public void ModelNameProperty()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext();\n\n            // Act & assert\n            Assert.Reflection.StringProperty(bindingContext, (context) => context.ModelName, String.Empty);\n        }\n\n        [Fact]\n        public void ModelStateProperty()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext();\n            ModelStateDictionary modelState = new ModelStateDictionary();\n\n            // Act & assert\n            MemberHelper.TestPropertyWithDefaultInstance(bindingContext, \"ModelState\", modelState);\n        }\n\n        [Fact]\n        public void ModelAndModelTypeAreFedFromModelMetadata()\n        {\n            // Act\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => 42, typeof(int))\n            };\n\n            // Assert\n            Assert.Equal(42, bindingContext.Model);\n            Assert.Equal(typeof(int), bindingContext.ModelType);\n        }\n\n        [Fact]\n        public void ValidationNodeProperty()\n        {\n            // Act\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => 42, typeof(int))\n            };\n\n            // Act & assert\n            MemberHelper.TestPropertyWithDefaultInstance(bindingContext, \"ValidationNode\", new ModelValidationNode(bindingContext.ModelMetadata, \"someName\"));\n        }\n\n        [Fact]\n        public void ValidationNodeProperty_DefaultValues()\n        {\n            // Act\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => 42, typeof(int)),\n                ModelName = \"theInt\"\n            };\n\n            // Act\n            ModelValidationNode validationNode = bindingContext.ValidationNode;\n\n            // Assert\n            Assert.NotNull(validationNode);\n            Assert.Equal(bindingContext.ModelMetadata, validationNode.ModelMetadata);\n            Assert.Equal(bindingContext.ModelName, validationNode.ModelStateKey);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/GenericModelBinderProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\nusing Moq;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class GenericModelBinderProviderTest\n    {\n        [Fact]\n        public void Constructor_WithFactory_ThrowsIfModelBinderFactoryIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new GenericModelBinderProvider(typeof(List<>), (Func<Type[], IExtensibleModelBinder>)null); }, \"modelBinderFactory\");\n        }\n\n        [Fact]\n        public void Constructor_WithFactory_ThrowsIfModelTypeIsNotOpenGeneric()\n        {\n            // Act & assert\n            Assert.Throws<ArgumentException>(\n                delegate { new GenericModelBinderProvider(typeof(List<int>), _ => null); },\n                \"The type 'System.Collections.Generic.List`1[System.Int32]' is not an open generic type.\" + Environment.NewLine\n              + \"Parameter name: modelType\");\n        }\n\n        [Fact]\n        public void Constructor_WithFactory_ThrowsIfModelTypeIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new GenericModelBinderProvider(null, _ => null); }, \"modelType\");\n        }\n\n        [Fact]\n        public void Constructor_WithInstance_ThrowsIfModelBinderIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new GenericModelBinderProvider(typeof(List<>), (IExtensibleModelBinder)null); }, \"modelBinder\");\n        }\n\n        [Fact]\n        public void Constructor_WithInstance_ThrowsIfModelTypeIsNotOpenGeneric()\n        {\n            // Act & assert\n            Assert.Throws<ArgumentException>(\n                delegate { new GenericModelBinderProvider(typeof(List<int>), new MutableObjectModelBinder()); },\n                \"The type 'System.Collections.Generic.List`1[System.Int32]' is not an open generic type.\" + Environment.NewLine\n              + \"Parameter name: modelType\");\n        }\n\n        [Fact]\n        public void Constructor_WithInstance_ThrowsIfModelTypeIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new GenericModelBinderProvider(null, new MutableObjectModelBinder()); }, \"modelType\");\n        }\n\n        [Fact]\n        public void Constructor_WithType_ThrowsIfModelBinderTypeIsNotModelBinder()\n        {\n            // Act & assert\n            Assert.Throws<ArgumentException>(\n                delegate { new GenericModelBinderProvider(typeof(List<>), typeof(string)); },\n                \"The type 'System.String' does not implement the interface 'Microsoft.Web.Mvc.ModelBinding.IExtensibleModelBinder'.\" + Environment.NewLine\n              + \"Parameter name: modelBinderType\");\n        }\n\n        [Fact]\n        public void Constructor_WithType_ThrowsIfModelBinderTypeIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new GenericModelBinderProvider(typeof(List<>), (Type)null); }, \"modelBinderType\");\n        }\n\n        [Fact]\n        public void Constructor_WithType_ThrowsIfModelBinderTypeTypeArgumentMismatch()\n        {\n            // Act & assert\n            Assert.Throws<ArgumentException>(\n                delegate { new GenericModelBinderProvider(typeof(List<>), typeof(DictionaryModelBinder<,>)); },\n                \"The open model type 'System.Collections.Generic.List`1[T]' has 1 generic type argument(s), but the open binder type 'Microsoft.Web.Mvc.ModelBinding.DictionaryModelBinder`2[TKey,TValue]' has 2 generic type argument(s). The binder type must not be an open generic type or must have the same number of generic arguments as the open model type.\" + Environment.NewLine\n              + \"Parameter name: modelBinderType\");\n        }\n\n        [Fact]\n        public void Constructor_WithType_ThrowsIfModelTypeIsNotOpenGeneric()\n        {\n            // Act & assert\n            Assert.Throws<ArgumentException>(\n                delegate { new GenericModelBinderProvider(typeof(List<int>), typeof(MutableObjectModelBinder)); },\n                \"The type 'System.Collections.Generic.List`1[System.Int32]' is not an open generic type.\" + Environment.NewLine\n              + \"Parameter name: modelType\");\n        }\n\n        [Fact]\n        public void Constructor_WithType_ThrowsIfModelTypeIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new GenericModelBinderProvider(null, typeof(MutableObjectModelBinder)); }, \"modelType\");\n        }\n\n        [Fact]\n        public void GetBinder_TypeDoesNotMatch_ModelTypeIsInterface_ReturnsNull()\n        {\n            // Arrange\n            GenericModelBinderProvider provider = new GenericModelBinderProvider(typeof(IEnumerable<>), typeof(CollectionModelBinder<>))\n            {\n                SuppressPrefixCheck = true\n            };\n            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(object));\n\n            // Act\n            IExtensibleModelBinder binder = provider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        [Fact]\n        public void GetBinder_TypeDoesNotMatch_ModelTypeIsNotInterface_ReturnsNull()\n        {\n            // Arrange\n            GenericModelBinderProvider provider = new GenericModelBinderProvider(typeof(List<>), typeof(CollectionModelBinder<>))\n            {\n                SuppressPrefixCheck = true\n            };\n            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(object));\n\n            // Act\n            IExtensibleModelBinder binder = provider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        [Fact]\n        public void GetBinder_TypeMatches_PrefixNotFound_ReturnsNull()\n        {\n            // Arrange\n            IExtensibleModelBinder binderInstance = new Mock<IExtensibleModelBinder>().Object;\n            GenericModelBinderProvider provider = new GenericModelBinderProvider(typeof(List<>), binderInstance);\n\n            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(List<int>));\n            bindingContext.ValueProvider = new SimpleValueProvider();\n\n            // Act\n            IExtensibleModelBinder returnedBinder = provider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.Null(returnedBinder);\n        }\n\n        [Fact]\n        public void GetBinder_TypeMatches_Success_Factory_ReturnsBinder()\n        {\n            // Arrange\n            IExtensibleModelBinder binderInstance = new Mock<IExtensibleModelBinder>().Object;\n\n            Func<Type[], IExtensibleModelBinder> binderFactory = typeArguments =>\n            {\n                Assert.Equal(new[] { typeof(int) }, typeArguments);\n                return binderInstance;\n            };\n\n            GenericModelBinderProvider provider = new GenericModelBinderProvider(typeof(IList<>), binderFactory)\n            {\n                SuppressPrefixCheck = true\n            };\n\n            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(List<int>));\n\n            // Act\n            IExtensibleModelBinder returnedBinder = provider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.Same(binderInstance, returnedBinder);\n        }\n\n        [Fact]\n        public void GetBinder_TypeMatches_Success_Instance_ReturnsBinder()\n        {\n            // Arrange\n            IExtensibleModelBinder binderInstance = new Mock<IExtensibleModelBinder>().Object;\n\n            GenericModelBinderProvider provider = new GenericModelBinderProvider(typeof(List<>), binderInstance)\n            {\n                SuppressPrefixCheck = true\n            };\n\n            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(List<int>));\n\n            // Act\n            IExtensibleModelBinder returnedBinder = provider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.Same(binderInstance, returnedBinder);\n        }\n\n        [Fact]\n        public void GetBinder_TypeMatches_Success_TypeActivation_ReturnsBinder()\n        {\n            // Arrange\n            GenericModelBinderProvider provider = new GenericModelBinderProvider(typeof(List<>), typeof(CollectionModelBinder<>))\n            {\n                SuppressPrefixCheck = true\n            };\n\n            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(List<int>));\n\n            // Act\n            IExtensibleModelBinder returnedBinder = provider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.IsType<CollectionModelBinder<int>>(returnedBinder);\n        }\n\n        [Fact]\n        public void GetBinderThrowsIfBindingContextIsNull()\n        {\n            // Arrange\n            GenericModelBinderProvider provider = new GenericModelBinderProvider(typeof(IEnumerable<>), typeof(CollectionModelBinder<>));\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { provider.GetBinder(null, null); }, \"bindingContext\");\n        }\n\n        [Fact]\n        public void GetBinderThrowsIfModelBinderHasNoParameterlessConstructor()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(List<int>));\n            GenericModelBinderProvider provider =\n                new GenericModelBinderProvider(typeof(List<>), typeof(NoParameterlessCtorBinder<>))\n                {\n                    SuppressPrefixCheck = true,\n                };\n\n            // Act & Assert, confirming type name and full stack are available in Exception\n            MissingMethodException exception = Assert.Throws<MissingMethodException>(\n                () => provider.GetBinder(null, bindingContext),\n                \"No parameterless constructor defined for this object. Object type 'Microsoft.Web.Mvc.ModelBinding.Test.GenericModelBinderProviderTest+NoParameterlessCtorBinder`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'.\");\n            Assert.Contains(\"System.Activator.CreateInstance(\", exception.ToString());\n        }\n\n        private static ExtensibleModelBindingContext GetBindingContext(Type modelType)\n        {\n            return new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => null, modelType)\n            };\n        }\n\n        private class NoParameterlessCtorBinder<T> : IExtensibleModelBinder\n        {\n            public NoParameterlessCtorBinder(int parameter)\n            {\n            }\n\n            public bool BindModel(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/KeyValuePairModelBinderProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class KeyValuePairModelBinderProviderTest\n    {\n        [Fact]\n        public void GetBinder_CorrectModelTypeAndValueProviderEntries_ReturnsBinder()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(KeyValuePair<int, string>)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"foo.key\", 42 },\n                    { \"foo.value\", \"someValue\" }\n                }\n            };\n\n            KeyValuePairModelBinderProvider binderProvider = new KeyValuePairModelBinderProvider();\n\n            // Act\n            IExtensibleModelBinder binder = binderProvider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.IsType<KeyValuePairModelBinder<int, string>>(binder);\n        }\n\n        [Fact]\n        public void GetBinder_ModelTypeIsIncorrect_ReturnsNull()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(List<int>)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"foo.key\", 42 },\n                    { \"foo.value\", \"someValue\" }\n                }\n            };\n\n            KeyValuePairModelBinderProvider binderProvider = new KeyValuePairModelBinderProvider();\n\n            // Act\n            IExtensibleModelBinder binder = binderProvider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        [Fact]\n        public void GetBinder_ValueProviderDoesNotContainKeyProperty_ReturnsNull()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(KeyValuePair<int, string>)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"foo.value\", \"someValue\" }\n                }\n            };\n\n            KeyValuePairModelBinderProvider binderProvider = new KeyValuePairModelBinderProvider();\n\n            // Act\n            IExtensibleModelBinder binder = binderProvider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        [Fact]\n        public void GetBinder_ValueProviderDoesNotContainValueProperty_ReturnsNull()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(KeyValuePair<int, string>)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"foo.key\", 42 }\n                }\n            };\n\n            KeyValuePairModelBinderProvider binderProvider = new KeyValuePairModelBinderProvider();\n\n            // Act\n            IExtensibleModelBinder binder = binderProvider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.Null(binder);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/KeyValuePairModelBinderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\nusing Moq;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class KeyValuePairModelBinderTest\n    {\n        [Fact]\n        public void BindModel_MissingKey_ReturnsFalse()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(KeyValuePair<int, string>)),\n                ModelName = \"someName\",\n                ModelBinderProviders = new ModelBinderProviderCollection(),\n                ValueProvider = new SimpleValueProvider()\n            };\n\n            KeyValuePairModelBinder<int, string> binder = new KeyValuePairModelBinder<int, string>();\n\n            // Act\n            bool retVal = binder.BindModel(controllerContext, bindingContext);\n\n            // Assert\n            Assert.False(retVal);\n            Assert.Null(bindingContext.Model);\n            Assert.Empty(bindingContext.ValidationNode.ChildNodes);\n        }\n\n        [Fact]\n        public void BindModel_MissingValue_ReturnsTrue()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(KeyValuePair<int, string>)),\n                ModelName = \"someName\",\n                ModelBinderProviders = new ModelBinderProviderCollection(),\n                ValueProvider = new SimpleValueProvider()\n            };\n\n            Mock<IExtensibleModelBinder> mockIntBinder = new Mock<IExtensibleModelBinder>();\n            mockIntBinder\n                .Setup(o => o.BindModel(controllerContext, It.IsAny<ExtensibleModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ExtensibleModelBindingContext mbc)\n                    {\n                        mbc.Model = 42;\n                        return true;\n                    });\n            bindingContext.ModelBinderProviders.RegisterBinderForType(typeof(int), mockIntBinder.Object, true /* suppressPrefixCheck */);\n\n            KeyValuePairModelBinder<int, string> binder = new KeyValuePairModelBinder<int, string>();\n\n            // Act\n            bool retVal = binder.BindModel(controllerContext, bindingContext);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Null(bindingContext.Model);\n            Assert.Equal(new[] { \"someName.key\" }, bindingContext.ValidationNode.ChildNodes.Select(n => n.ModelStateKey).ToArray());\n        }\n\n        [Fact]\n        public void BindModel_SubBindingSucceeds()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(KeyValuePair<int, string>)),\n                ModelName = \"someName\",\n                ModelBinderProviders = new ModelBinderProviderCollection(),\n                ValueProvider = new SimpleValueProvider()\n            };\n\n            Mock<IExtensibleModelBinder> mockIntBinder = new Mock<IExtensibleModelBinder>();\n            mockIntBinder\n                .Setup(o => o.BindModel(controllerContext, It.IsAny<ExtensibleModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ExtensibleModelBindingContext mbc)\n                    {\n                        mbc.Model = 42;\n                        return true;\n                    });\n            bindingContext.ModelBinderProviders.RegisterBinderForType(typeof(int), mockIntBinder.Object, true /* suppressPrefixCheck */);\n            Mock<IExtensibleModelBinder> mockStringBinder = new Mock<IExtensibleModelBinder>();\n            mockStringBinder\n                .Setup(o => o.BindModel(controllerContext, It.IsAny<ExtensibleModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ExtensibleModelBindingContext mbc)\n                    {\n                        mbc.Model = \"forty-two\";\n                        return true;\n                    });\n            bindingContext.ModelBinderProviders.RegisterBinderForType(typeof(string), mockStringBinder.Object, true /* suppressPrefixCheck */);\n\n            KeyValuePairModelBinder<int, string> binder = new KeyValuePairModelBinder<int, string>();\n\n            // Act\n            bool retVal = binder.BindModel(controllerContext, bindingContext);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Equal(new KeyValuePair<int, string>(42, \"forty-two\"), bindingContext.Model);\n            Assert.Equal(new[] { \"someName.key\", \"someName.value\" }, bindingContext.ValidationNode.ChildNodes.Select(n => n.ModelStateKey).ToArray());\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/KeyValuePairModelBinderUtilTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\nusing Moq;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class KeyValuePairModelBinderUtilTest\n    {\n        [Fact]\n        public void TryBindStrongModel_BinderExists_BinderReturnsCorrectlyTypedObject_ReturnsTrue()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),\n                ModelName = \"someName\",\n                ModelState = new ModelStateDictionary(),\n                ModelBinderProviders = new ModelBinderProviderCollection(),\n                ValueProvider = new SimpleValueProvider()\n            };\n\n            Mock<IExtensibleModelBinder> mockIntBinder = new Mock<IExtensibleModelBinder>();\n            mockIntBinder\n                .Setup(o => o.BindModel(controllerContext, It.IsAny<ExtensibleModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ExtensibleModelBindingContext mbc)\n                    {\n                        Assert.Equal(\"someName.key\", mbc.ModelName);\n                        mbc.Model = 42;\n                        return true;\n                    });\n            bindingContext.ModelBinderProviders.RegisterBinderForType(typeof(int), mockIntBinder.Object, true /* suppressPrefixCheck */);\n\n            // Act\n            int model;\n            bool retVal = KeyValuePairModelBinderUtil.TryBindStrongModel(controllerContext, bindingContext, \"key\", new EmptyModelMetadataProvider(), out model);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Equal(42, model);\n            Assert.Single(bindingContext.ValidationNode.ChildNodes);\n            Assert.Empty(bindingContext.ModelState);\n        }\n\n        [Fact]\n        public void TryBindStrongModel_BinderExists_BinderReturnsIncorrectlyTypedObject_ReturnsTrue()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),\n                ModelName = \"someName\",\n                ModelState = new ModelStateDictionary(),\n                ModelBinderProviders = new ModelBinderProviderCollection(),\n                ValueProvider = new SimpleValueProvider()\n            };\n\n            Mock<IExtensibleModelBinder> mockIntBinder = new Mock<IExtensibleModelBinder>();\n            mockIntBinder\n                .Setup(o => o.BindModel(controllerContext, It.IsAny<ExtensibleModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ExtensibleModelBindingContext mbc)\n                    {\n                        Assert.Equal(\"someName.key\", mbc.ModelName);\n                        return true;\n                    });\n            bindingContext.ModelBinderProviders.RegisterBinderForType(typeof(int), mockIntBinder.Object, true /* suppressPrefixCheck */);\n\n            // Act\n            int model;\n            bool retVal = KeyValuePairModelBinderUtil.TryBindStrongModel(controllerContext, bindingContext, \"key\", new EmptyModelMetadataProvider(), out model);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Equal(default(int), model);\n            Assert.Single(bindingContext.ValidationNode.ChildNodes);\n            Assert.Empty(bindingContext.ModelState);\n        }\n\n        [Fact]\n        public void TryBindStrongModel_NoBinder_ReturnsFalse()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),\n                ModelName = \"someName\",\n                ModelState = new ModelStateDictionary(),\n                ModelBinderProviders = new ModelBinderProviderCollection(),\n                ValueProvider = new SimpleValueProvider()\n            };\n\n            // Act\n            int model;\n            bool retVal = KeyValuePairModelBinderUtil.TryBindStrongModel(controllerContext, bindingContext, \"key\", new EmptyModelMetadataProvider(), out model);\n\n            // Assert\n            Assert.False(retVal);\n            Assert.Equal(default(int), model);\n            Assert.Empty(bindingContext.ValidationNode.ChildNodes);\n            Assert.Empty(bindingContext.ModelState);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/ModelBinderConfigTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Globalization;\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class ModelBinderConfigTest\n    {\n        [Fact]\n        public void GetUserResourceString_NullControllerContext_ReturnsNull()\n        {\n            // Act\n            string customResourceString = ModelBinderConfig.GetUserResourceString(null /* controllerContext */, \"someResourceName\", \"someResourceClassKey\");\n\n            // Assert\n            Assert.Null(customResourceString);\n        }\n\n        [Fact]\n        public void GetUserResourceString_NullHttpContext_ReturnsNull()\n        {\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(o => o.HttpContext).Returns((HttpContextBase)null);\n\n            // Act\n            string customResourceString = ModelBinderConfig.GetUserResourceString(mockControllerContext.Object, \"someResourceName\", \"someResourceClassKey\");\n\n            // Assert\n            Assert.Null(customResourceString);\n        }\n\n        [Fact]\n        public void GetUserResourceString_NullResourceKey_ReturnsNull()\n        {\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n\n            // Act\n            string customResourceString = ModelBinderConfig.GetUserResourceString(mockControllerContext.Object, \"someResourceName\", null /* resourceClassKey */);\n\n            // Assert\n            mockControllerContext.Verify(o => o.HttpContext, Times.Never());\n            Assert.Null(customResourceString);\n        }\n\n        [Fact]\n        public void GetUserResourceString_ValidResourceObject_ReturnsResourceString()\n        {\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(o => o.HttpContext.GetGlobalResourceObject(\"someResourceClassKey\", \"someResourceName\", CultureInfo.CurrentUICulture)).Returns(\"My custom resource string\");\n\n            // Act\n            string customResourceString = ModelBinderConfig.GetUserResourceString(mockControllerContext.Object, \"someResourceName\", \"someResourceClassKey\");\n\n            // Assert\n            Assert.Equal(\"My custom resource string\", customResourceString);\n        }\n\n        [Fact]\n        public void Initialize_ReplacesOriginalCollection()\n        {\n            // Arrange\n            ModelBinderDictionary oldBinders = new ModelBinderDictionary();\n            oldBinders[typeof(int)] = new Mock<IModelBinder>().Object;\n            ModelBinderProviderCollection newBinderProviders = new ModelBinderProviderCollection();\n\n            // Act\n            ModelBinderConfig.Initialize(oldBinders, newBinderProviders);\n\n            // Assert\n            Assert.Empty(oldBinders);\n\n            var shimBinder = Assert.IsType<ExtensibleModelBinderAdapter>(oldBinders.DefaultBinder);\n            Assert.Same(newBinderProviders, shimBinder.Providers);\n        }\n\n        [Fact]\n        public void TypeConversionErrorMessageProvider_DefaultValue()\n        {\n            // Arrange\n            ModelMetadata metadata = new ModelMetadata(new Mock<ModelMetadataProvider>().Object, null, null, typeof(int), \"SomePropertyName\");\n\n            // Act\n            string errorString = ModelBinderConfig.TypeConversionErrorMessageProvider(null, metadata, \"some incoming value\");\n\n            // Assert\n            Assert.Equal(\"The value 'some incoming value' is not valid for SomePropertyName.\", errorString);\n        }\n\n        [Fact]\n        public void TypeConversionErrorMessageProvider_Property()\n        {\n            // Arrange\n            ModelBinderConfigWrapper wrapper = new ModelBinderConfigWrapper();\n\n            // Act & assert\n            try\n            {\n                MemberHelper.TestPropertyWithDefaultInstance(wrapper, \"TypeConversionErrorMessageProvider\", (ModelBinderErrorMessageProvider)DummyErrorSelector);\n            }\n            finally\n            {\n                wrapper.Reset();\n            }\n        }\n\n        [Fact]\n        public void ValueRequiredErrorMessageProvider_DefaultValue()\n        {\n            // Arrange\n            ModelMetadata metadata = new ModelMetadata(new Mock<ModelMetadataProvider>().Object, null, null, typeof(int), \"SomePropertyName\");\n\n            // Act\n            string errorString = ModelBinderConfig.ValueRequiredErrorMessageProvider(null, metadata, \"some incoming value\");\n\n            // Assert\n            Assert.Equal(\"A value is required.\", errorString);\n        }\n\n        [Fact]\n        public void ValueRequiredErrorMessageProvider_Property()\n        {\n            // Arrange\n            ModelBinderConfigWrapper wrapper = new ModelBinderConfigWrapper();\n\n            // Act & assert\n            try\n            {\n                MemberHelper.TestPropertyWithDefaultInstance(wrapper, \"ValueRequiredErrorMessageProvider\", (ModelBinderErrorMessageProvider)DummyErrorSelector);\n            }\n            finally\n            {\n                wrapper.Reset();\n            }\n        }\n\n        private string DummyErrorSelector(ControllerContext controllerContext, ModelMetadata modelMetadata, object incomingValue)\n        {\n            throw new NotImplementedException();\n        }\n\n        private sealed class ModelBinderConfigWrapper\n        {\n            public ModelBinderErrorMessageProvider TypeConversionErrorMessageProvider\n            {\n                get { return ModelBinderConfig.TypeConversionErrorMessageProvider; }\n                set { ModelBinderConfig.TypeConversionErrorMessageProvider = value; }\n            }\n\n            public ModelBinderErrorMessageProvider ValueRequiredErrorMessageProvider\n            {\n                get { return ModelBinderConfig.ValueRequiredErrorMessageProvider; }\n                set { ModelBinderConfig.ValueRequiredErrorMessageProvider = value; }\n            }\n\n            public void Reset()\n            {\n                ModelBinderConfig.TypeConversionErrorMessageProvider = null;\n                ModelBinderConfig.ValueRequiredErrorMessageProvider = null;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/ModelBinderProviderCollectionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\nusing Moq;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class ModelBinderProviderCollectionTest\n    {\n        [Fact]\n        public void ListWrappingConstructor()\n        {\n            // Arrange\n            ModelBinderProvider[] providers = new[]\n            {\n                new Mock<ModelBinderProvider>().Object,\n                new Mock<ModelBinderProvider>().Object\n            };\n\n            // Act\n            ModelBinderProviderCollection collection = new ModelBinderProviderCollection(providers);\n\n            // Assert\n            Assert.Equal(providers, collection.ToArray());\n        }\n\n        [Fact]\n        public void DefaultConstructor()\n        {\n            // Act\n            ModelBinderProviderCollection collection = new ModelBinderProviderCollection();\n\n            // Assert\n            Assert.Empty(collection);\n        }\n\n        [Fact]\n        public void AddNullProviderThrows()\n        {\n            // Arrange\n            ModelBinderProviderCollection collection = new ModelBinderProviderCollection();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { collection.Add(null); },\n                \"item\");\n        }\n\n        [Fact]\n        public void RegisterBinderForGenericType_Factory()\n        {\n            // Arrange\n            ModelBinderProvider mockProvider = new Mock<ModelBinderProvider>().Object;\n            IExtensibleModelBinder mockBinder = new Mock<IExtensibleModelBinder>().Object;\n\n            ModelBinderProviderCollection collection = new ModelBinderProviderCollection\n            {\n                mockProvider\n            };\n\n            // Act\n            collection.RegisterBinderForGenericType(typeof(List<>), _ => mockBinder);\n\n            // Assert\n            var genericProvider = Assert.IsType<GenericModelBinderProvider>(collection[0]);\n            Assert.Equal(typeof(List<>), genericProvider.ModelType);\n            Assert.Equal(mockProvider, collection[1]);\n        }\n\n        [Fact]\n        public void RegisterBinderForGenericType_Instance()\n        {\n            // Arrange\n            ModelBinderProvider mockProvider = new Mock<ModelBinderProvider>().Object;\n            IExtensibleModelBinder mockBinder = new Mock<IExtensibleModelBinder>().Object;\n\n            ModelBinderProviderCollection collection = new ModelBinderProviderCollection\n            {\n                mockProvider\n            };\n\n            // Act\n            collection.RegisterBinderForGenericType(typeof(List<>), mockBinder);\n\n            // Assert\n            var genericProvider = Assert.IsType<GenericModelBinderProvider>(collection[0]);\n            Assert.Equal(typeof(List<>), genericProvider.ModelType);\n            Assert.Equal(mockProvider, collection[1]);\n        }\n\n        [Fact]\n        public void RegisterBinderForGenericType_Type()\n        {\n            // Arrange\n            ModelBinderProvider mockProvider = new Mock<ModelBinderProvider>().Object;\n            IExtensibleModelBinder mockBinder = new Mock<IExtensibleModelBinder>().Object;\n\n            ModelBinderProviderCollection collection = new ModelBinderProviderCollection\n            {\n                mockProvider\n            };\n\n            // Act\n            collection.RegisterBinderForGenericType(typeof(List<>), typeof(CollectionModelBinder<>));\n\n            // Assert\n            var genericProvider = Assert.IsType<GenericModelBinderProvider>(collection[0]);\n            Assert.Equal(typeof(List<>), genericProvider.ModelType);\n            Assert.Equal(mockProvider, collection[1]);\n        }\n\n        [Fact]\n        public void RegisterBinderForType_Factory()\n        {\n            // Arrange\n            ModelBinderProvider mockProvider = new Mock<ModelBinderProvider>().Object;\n            IExtensibleModelBinder mockBinder = new Mock<IExtensibleModelBinder>().Object;\n\n            ModelBinderProviderCollection collection = new ModelBinderProviderCollection\n            {\n                mockProvider\n            };\n\n            // Act\n            collection.RegisterBinderForType(typeof(int), () => mockBinder);\n\n            // Assert\n            var simpleProvider = Assert.IsType<SimpleModelBinderProvider>(collection[0]);\n            Assert.Equal(typeof(int), simpleProvider.ModelType);\n            Assert.Equal(mockProvider, collection[1]);\n        }\n\n        [Fact]\n        public void RegisterBinderForType_Instance()\n        {\n            // Arrange\n            ModelBinderProvider mockProvider = new Mock<ModelBinderProvider>().Object;\n            IExtensibleModelBinder mockBinder = new Mock<IExtensibleModelBinder>().Object;\n\n            ModelBinderProviderCollection collection = new ModelBinderProviderCollection\n            {\n                mockProvider\n            };\n\n            // Act\n            collection.RegisterBinderForType(typeof(int), mockBinder);\n\n            // Assert\n            var simpleProvider = Assert.IsType<SimpleModelBinderProvider>(collection[0]);\n            Assert.Equal(typeof(int), simpleProvider.ModelType);\n            Assert.Equal(mockProvider, collection[1]);\n        }\n\n        [Fact]\n        public void RegisterBinderForType_Instance_InsertsNewProviderBehindFrontOfListProviders()\n        {\n            // Arrange\n            ModelBinderProvider frontOfListProvider = new ProviderAtFront();\n            IExtensibleModelBinder mockBinder = new Mock<IExtensibleModelBinder>().Object;\n\n            ModelBinderProviderCollection collection = new ModelBinderProviderCollection\n            {\n                frontOfListProvider\n            };\n\n            // Act\n            collection.RegisterBinderForType(typeof(int), mockBinder);\n\n            // Assert\n            Assert.Equal(\n                new[] { typeof(ProviderAtFront), typeof(SimpleModelBinderProvider) },\n                collection.Select(o => o.GetType()).ToArray());\n        }\n\n        [Fact]\n        public void SetItem()\n        {\n            // Arrange\n            ModelBinderProvider provider0 = new Mock<ModelBinderProvider>().Object;\n            ModelBinderProvider provider1 = new Mock<ModelBinderProvider>().Object;\n            ModelBinderProvider provider2 = new Mock<ModelBinderProvider>().Object;\n\n            ModelBinderProviderCollection collection = new ModelBinderProviderCollection();\n            collection.Add(provider0);\n            collection.Add(provider1);\n\n            // Act\n            collection[1] = provider2;\n\n            // Assert\n            Assert.Equal(new[] { provider0, provider2 }, collection.ToArray());\n        }\n\n        [Fact]\n        public void SetNullProviderThrows()\n        {\n            // Arrange\n            ModelBinderProviderCollection collection = new ModelBinderProviderCollection();\n            collection.Add(new Mock<ModelBinderProvider>().Object);\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { collection[0] = null; },\n                \"item\");\n        }\n\n        [Fact]\n        public void GetBinder_FromAttribute_BadAttribute_Throws()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(ModelWithProviderAttribute_BadAttribute))\n            };\n\n            ModelBinderProviderCollection providers = new ModelBinderProviderCollection();\n\n            // Act & assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { providers.GetBinder(controllerContext, bindingContext); },\n                @\"The type 'System.Object' does not subclass Microsoft.Web.Mvc.ModelBinding.ModelBinderProvider or implement the interface Microsoft.Web.Mvc.ModelBinding.IExtensibleModelBinder.\");\n        }\n\n        [Fact]\n        public void GetBinder_FromAttribute_Binder_Generic_ReturnsBinder()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(ModelWithProviderAttribute_Binder_Generic<int>)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"foo\", \"fooValue\" }\n                }\n            };\n\n            ModelBinderProviderCollection providers = new ModelBinderProviderCollection();\n            providers.RegisterBinderForType(typeof(ModelWithProviderAttribute_Binder_Generic<int>), new Mock<IExtensibleModelBinder>().Object, true /* suppressPrefix */);\n\n            // Act\n            IExtensibleModelBinder binder = providers.GetBinder(controllerContext, bindingContext);\n\n            // Assert\n            Assert.IsType<CustomGenericBinder<int>>(binder);\n        }\n\n        [Fact]\n        public void GetBinder_FromAttribute_Binder_SuppressPrefixCheck_ReturnsBinder()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(ModelWithProviderAttribute_Binder_SuppressPrefix)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"bar\", \"barValue\" }\n                }\n            };\n\n            ModelBinderProviderCollection providers = new ModelBinderProviderCollection();\n            providers.RegisterBinderForType(typeof(ModelWithProviderAttribute_Binder_SuppressPrefix), new Mock<IExtensibleModelBinder>().Object, true /* suppressPrefix */);\n\n            // Act\n            IExtensibleModelBinder binder = providers.GetBinder(controllerContext, bindingContext);\n\n            // Assert\n            Assert.IsType<CustomBinder>(binder);\n        }\n\n        [Fact]\n        public void GetBinder_FromAttribute_Binder_ValueNotPresent_ReturnsNull()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(ModelWithProviderAttribute_Binder)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"bar\", \"barValue\" }\n                }\n            };\n\n            ModelBinderProviderCollection providers = new ModelBinderProviderCollection();\n            providers.RegisterBinderForType(typeof(ModelWithProviderAttribute_Binder), new Mock<IExtensibleModelBinder>().Object, true /* suppressPrefix */);\n\n            // Act\n            IExtensibleModelBinder binder = providers.GetBinder(controllerContext, bindingContext);\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        [Fact]\n        public void GetBinder_FromAttribute_Binder_ValuePresent_ReturnsBinder()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(ModelWithProviderAttribute_Binder)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"foo\", \"fooValue\" }\n                }\n            };\n\n            ModelBinderProviderCollection providers = new ModelBinderProviderCollection();\n            providers.RegisterBinderForType(typeof(ModelWithProviderAttribute_Binder), new Mock<IExtensibleModelBinder>().Object, true /* suppressPrefix */);\n\n            // Act\n            IExtensibleModelBinder binder = providers.GetBinder(controllerContext, bindingContext);\n\n            // Assert\n            Assert.IsType<CustomBinder>(binder);\n        }\n\n        [Fact]\n        public void GetBinder_FromAttribute_Provider_ReturnsBinder()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(ModelWithProviderAttribute_Provider))\n            };\n\n            ModelBinderProviderCollection providers = new ModelBinderProviderCollection();\n            providers.RegisterBinderForType(typeof(ModelWithProviderAttribute_Provider), new Mock<IExtensibleModelBinder>().Object, true /* suppressPrefix */);\n\n            // Act\n            IExtensibleModelBinder binder = providers.GetBinder(controllerContext, bindingContext);\n\n            // Assert\n            Assert.IsType<CustomBinder>(binder);\n        }\n\n        [Fact]\n        public void GetBinderReturnsFirstBinderFromProviders()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(object))\n            };\n            IExtensibleModelBinder expectedBinder = new Mock<IExtensibleModelBinder>().Object;\n\n            Mock<ModelBinderProvider> mockProvider = new Mock<ModelBinderProvider>();\n            mockProvider.Setup(p => p.GetBinder(controllerContext, bindingContext)).Returns(expectedBinder);\n\n            ModelBinderProviderCollection collection = new ModelBinderProviderCollection(new[]\n            {\n                new Mock<ModelBinderProvider>().Object,\n                mockProvider.Object,\n                new Mock<ModelBinderProvider>().Object\n            });\n\n            // Act\n            IExtensibleModelBinder returned = collection.GetBinder(controllerContext, bindingContext);\n\n            // Assert\n            Assert.Equal(expectedBinder, returned);\n        }\n\n        [Fact]\n        public void GetBinderReturnsNullIfNoProviderMatches()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(object))\n            };\n\n            ModelBinderProviderCollection collection = new ModelBinderProviderCollection(new[]\n            {\n                new Mock<ModelBinderProvider>().Object,\n            });\n\n            // Act\n            IExtensibleModelBinder returned = collection.GetBinder(controllerContext, bindingContext);\n\n            // Assert\n            Assert.Null(returned);\n        }\n\n        [Fact]\n        public void GetBinderThrowsIfBindingContextIsNull()\n        {\n            // Arrange\n            ModelBinderProviderCollection collection = new ModelBinderProviderCollection();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { collection.GetBinder(new ControllerContext(), null); }, \"bindingContext\");\n        }\n\n        [Fact]\n        public void GetBinderThrowsIfControllerContextIsNull()\n        {\n            // Arrange\n            ModelBinderProviderCollection collection = new ModelBinderProviderCollection();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { collection.GetBinder(null, new ExtensibleModelBindingContext()); }, \"controllerContext\");\n        }\n\n        [Fact]\n        public void GetBinderThrowsIfModelTypeHasBindAttribute()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(ModelWithBindAttribute))\n            };\n            ModelBinderProviderCollection collection = new ModelBinderProviderCollection();\n\n            // Act & assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { collection.GetBinder(controllerContext, bindingContext); },\n                @\"The model of type 'Microsoft.Web.Mvc.ModelBinding.Test.ModelBinderProviderCollectionTest+ModelWithBindAttribute' has a [Bind] attribute. The new model binding system cannot be used with models that have type-level [Bind] attributes. Use the [BindRequired] and [BindNever] attributes on the model type or its properties instead.\");\n        }\n\n        [Fact]\n        public void GetBinderThrowsIfBinderHasNoParameterlessConstructor()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            ModelBinderProviderCollection collection = new ModelBinderProviderCollection();\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(\n                    null,\n                    typeof(ModelWithProviderAttribute_ProviderHasNoParameterlessConstructor)),\n            };\n\n            // Act & Assert, confirming type name and full stack are available in Exception\n            MissingMethodException exception = Assert.Throws<MissingMethodException>(\n                () => collection.GetBinder(controllerContext, bindingContext),\n                \"No parameterless constructor defined for this object. Object type 'Microsoft.Web.Mvc.ModelBinding.Test.ModelBinderProviderCollectionTest+NoParameterlessCtorProvider'.\");\n            Assert.Contains(\"System.Activator.CreateInstance(\", exception.ToString());\n        }\n\n        [Fact]\n        public void GetBinderThrowsIfGenericProviderHasNoParameterlessConstructor()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            ModelBinderProviderCollection collection = new ModelBinderProviderCollection();\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(\n                    null,\n                    typeof(ModelWithProviderAttribute_ProviderHasNoParameterlessConstructor<int>)),\n            };\n\n            // Act & Assert, confirming type name and full stack are available in Exception\n            MissingMethodException exception = Assert.Throws<MissingMethodException>(\n                () => collection.GetBinder(controllerContext, bindingContext),\n                \"No parameterless constructor defined for this object. Object type 'Microsoft.Web.Mvc.ModelBinding.Test.ModelBinderProviderCollectionTest+NoParameterlessCtorBinder`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'.\");\n            Assert.Contains(\"System.Activator.CreateInstance(\", exception.ToString());\n        }\n\n        [Fact]\n        public void GetRequiredBinderThrowsIfNoProviderMatches()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int))\n            };\n\n            ModelBinderProviderCollection collection = new ModelBinderProviderCollection(new[]\n            {\n                new Mock<ModelBinderProvider>().Object,\n            });\n\n            // Act & assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { collection.GetRequiredBinder(controllerContext, bindingContext); },\n                @\"A binder for type System.Int32 could not be located.\");\n        }\n\n        [MetadataType(typeof(ModelWithBindAttribute_Buddy))]\n        private class ModelWithBindAttribute\n        {\n            [Bind]\n            private class ModelWithBindAttribute_Buddy\n            {\n            }\n        }\n\n        [ModelBinderProviderOptions(FrontOfList = true)]\n        private class ProviderAtFront : ModelBinderProvider\n        {\n            public override IExtensibleModelBinder GetBinder(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        [ExtensibleModelBinder(typeof(object))]\n        private class ModelWithProviderAttribute_BadAttribute\n        {\n        }\n\n        [ExtensibleModelBinder(typeof(CustomBinder))]\n        private class ModelWithProviderAttribute_Binder\n        {\n        }\n\n        [ExtensibleModelBinder(typeof(CustomGenericBinder<>))]\n        private class ModelWithProviderAttribute_Binder_Generic<T>\n        {\n        }\n\n        [ExtensibleModelBinder(typeof(CustomBinder), SuppressPrefixCheck = true)]\n        private class ModelWithProviderAttribute_Binder_SuppressPrefix\n        {\n        }\n\n        [ExtensibleModelBinder(typeof(CustomProvider))]\n        private class ModelWithProviderAttribute_Provider\n        {\n        }\n\n        [ExtensibleModelBinder(typeof(NoParameterlessCtorProvider))]\n        private class ModelWithProviderAttribute_ProviderHasNoParameterlessConstructor\n        {\n        }\n\n        [ExtensibleModelBinder(typeof(NoParameterlessCtorBinder<>))]\n        private class ModelWithProviderAttribute_ProviderHasNoParameterlessConstructor<T>\n        {\n        }\n\n        private class CustomProvider : ModelBinderProvider\n        {\n            public override IExtensibleModelBinder GetBinder(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n            {\n                return new CustomBinder();\n            }\n        }\n\n        private class CustomBinder : IExtensibleModelBinder\n        {\n            public bool BindModel(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class CustomGenericBinder<T> : IExtensibleModelBinder\n        {\n            public bool BindModel(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class NoParameterlessCtorProvider : ModelBinderProvider\n        {\n            public NoParameterlessCtorProvider(int parameter)\n            {\n            }\n\n            public override IExtensibleModelBinder GetBinder(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class NoParameterlessCtorBinder<T> : IExtensibleModelBinder\n        {\n            public NoParameterlessCtorBinder(int parameter)\n            {\n            }\n\n            public bool BindModel(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/ModelBinderProvidersTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class ModelBinderProvidersTest\n    {\n        [Fact]\n        public void CollectionDefaults()\n        {\n            // Arrange\n            Type[] expectedTypes = new[]\n            {\n                typeof(TypeMatchModelBinderProvider),\n                typeof(BinaryDataModelBinderProvider),\n                typeof(KeyValuePairModelBinderProvider),\n                typeof(ComplexModelDtoModelBinderProvider),\n                typeof(ArrayModelBinderProvider),\n                typeof(DictionaryModelBinderProvider),\n                typeof(CollectionModelBinderProvider),\n                typeof(TypeConverterModelBinderProvider),\n                typeof(MutableObjectModelBinderProvider)\n            };\n\n            // Act\n            Type[] actualTypes = ModelBinderProviders.Providers.Select(p => p.GetType()).ToArray();\n\n            // Assert\n            Assert.Equal(expectedTypes, actualTypes);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/ModelBinderUtilTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class ModelBinderUtilTest\n    {\n        [Fact]\n        public void CastOrDefault_CorrectType_ReturnsInput()\n        {\n            // Act\n            int retVal = ModelBinderUtil.CastOrDefault<int>(42);\n\n            // Assert\n            Assert.Equal(42, retVal);\n        }\n\n        [Fact]\n        public void CastOrDefault_IncorrectType_ReturnsDefaultTModel()\n        {\n            // Act\n            DateTime retVal = ModelBinderUtil.CastOrDefault<DateTime>(42);\n\n            // Assert\n            Assert.Equal(default(DateTime), retVal);\n        }\n\n        [Fact]\n        public void CreateIndexModelName_EmptyParentName()\n        {\n            // Act\n            string fullChildName = ModelBinderUtil.CreateIndexModelName(\"\", 42);\n\n            // Assert\n            Assert.Equal(\"[42]\", fullChildName);\n        }\n\n        [Fact]\n        public void CreateIndexModelName_IntIndex()\n        {\n            // Act\n            string fullChildName = ModelBinderUtil.CreateIndexModelName(\"parentName\", 42);\n\n            // Assert\n            Assert.Equal(\"parentName[42]\", fullChildName);\n        }\n\n        [Fact]\n        public void CreateIndexModelName_StringIndex()\n        {\n            // Act\n            string fullChildName = ModelBinderUtil.CreateIndexModelName(\"parentName\", \"index\");\n\n            // Assert\n            Assert.Equal(\"parentName[index]\", fullChildName);\n        }\n\n        [Fact]\n        public void CreatePropertyModelName()\n        {\n            // Act\n            string fullChildName = ModelBinderUtil.CreatePropertyModelName(\"parentName\", \"childName\");\n\n            // Assert\n            Assert.Equal(\"parentName.childName\", fullChildName);\n        }\n\n        [Fact]\n        public void CreatePropertyModelName_EmptyParentName()\n        {\n            // Act\n            string fullChildName = ModelBinderUtil.CreatePropertyModelName(\"\", \"childName\");\n\n            // Assert\n            Assert.Equal(\"childName\", fullChildName);\n        }\n\n        [Fact]\n        public void GetPossibleBinderInstance_Match_ReturnsBinder()\n        {\n            // Act\n            IExtensibleModelBinder binder = ModelBinderUtil.GetPossibleBinderInstance(typeof(List<int>), typeof(List<>), typeof(SampleGenericBinder<>));\n\n            // Assert\n            Assert.IsType<SampleGenericBinder<int>>(binder);\n        }\n\n        [Fact]\n        public void GetPossibleBinderInstance_NoMatch_ReturnsNull()\n        {\n            // Act\n            IExtensibleModelBinder binder = ModelBinderUtil.GetPossibleBinderInstance(typeof(ArraySegment<int>), typeof(List<>), typeof(SampleGenericBinder<>));\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        [Fact]\n        public void RawValueToObjectArray_RawValueIsEnumerable_ReturnsInputAsArray()\n        {\n            // Assert\n            List<int> original = new List<int> { 1, 2, 3, 4 };\n\n            // Act\n            object[] retVal = ModelBinderUtil.RawValueToObjectArray(original);\n\n            // Assert\n            Assert.Equal(new object[] { 1, 2, 3, 4 }, retVal);\n        }\n\n        [Fact]\n        public void RawValueToObjectArray_RawValueIsObject_WrapsObjectInSingleElementArray()\n        {\n            // Act\n            object[] retVal = ModelBinderUtil.RawValueToObjectArray(42);\n\n            // Assert\n            Assert.Equal(new object[] { 42 }, retVal);\n        }\n\n        [Fact]\n        public void RawValueToObjectArray_RawValueIsObjectArray_ReturnsInputInstance()\n        {\n            // Assert\n            object[] original = new object[2];\n\n            // Act\n            object[] retVal = ModelBinderUtil.RawValueToObjectArray(original);\n\n            // Assert\n            Assert.Same(original, retVal);\n        }\n\n        [Fact]\n        public void RawValueToObjectArray_RawValueIsString_WrapsStringInSingleElementArray()\n        {\n            // Act\n            object[] retVal = ModelBinderUtil.RawValueToObjectArray(\"hello\");\n\n            // Assert\n            Assert.Equal(new object[] { \"hello\" }, retVal);\n        }\n\n        [Fact]\n        public void ReplaceEmptyStringWithNull_ConvertEmptyStringToNullDisabled_ModelIsEmptyString_LeavesModelAlone()\n        {\n            // Arrange\n            ModelMetadata modelMetadata = GetMetadata(typeof(string));\n            modelMetadata.ConvertEmptyStringToNull = false;\n\n            // Act\n            object model = \"\";\n            ModelBinderUtil.ReplaceEmptyStringWithNull(modelMetadata, ref model);\n\n            // Assert\n            Assert.Equal(\"\", model);\n        }\n\n        [Fact]\n        public void ReplaceEmptyStringWithNull_ConvertEmptyStringToNullEnabled_ModelIsEmptyString_ReplacesModelWithNull()\n        {\n            // Arrange\n            ModelMetadata modelMetadata = GetMetadata(typeof(string));\n            modelMetadata.ConvertEmptyStringToNull = true;\n\n            // Act\n            object model = \"\";\n            ModelBinderUtil.ReplaceEmptyStringWithNull(modelMetadata, ref model);\n\n            // Assert\n            Assert.Null(model);\n        }\n\n        [Fact]\n        public void ReplaceEmptyStringWithNull_ConvertEmptyStringToNullEnabled_ModelIsWhitespaceString_ReplacesModelWithNull()\n        {\n            // Arrange\n            ModelMetadata modelMetadata = GetMetadata(typeof(string));\n            modelMetadata.ConvertEmptyStringToNull = true;\n\n            // Act\n            object model = \"     \"; // whitespace\n            ModelBinderUtil.ReplaceEmptyStringWithNull(modelMetadata, ref model);\n\n            // Assert\n            Assert.Null(model);\n        }\n\n        [Fact]\n        public void ReplaceEmptyStringWithNull_ConvertEmptyStringToNullDisabled_ModelIsNotEmptyString_LeavesModelAlone()\n        {\n            // Arrange\n            ModelMetadata modelMetadata = GetMetadata(typeof(string));\n            modelMetadata.ConvertEmptyStringToNull = true;\n\n            // Act\n            object model = 42;\n            ModelBinderUtil.ReplaceEmptyStringWithNull(modelMetadata, ref model);\n\n            // Assert\n            Assert.Equal(42, model);\n        }\n\n        [Fact]\n        public void ValidateBindingContext_SuccessWithNonNullModel()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = GetMetadata(typeof(string))\n            };\n            bindingContext.ModelMetadata.Model = \"hello!\";\n\n            // Act\n            ModelBinderUtil.ValidateBindingContext(bindingContext, typeof(string), false);\n\n            // Assert\n            // Nothing to do - if we got this far without throwing, the test succeeded\n        }\n\n        [Fact]\n        public void ValidateBindingContext_SuccessWithNullModel()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = GetMetadata(typeof(string))\n            };\n\n            // Act\n            ModelBinderUtil.ValidateBindingContext(bindingContext, typeof(string), true);\n\n            // Assert\n            // Nothing to do - if we got this far without throwing, the test succeeded\n        }\n\n        [Fact]\n        public void ValidateBindingContextThrowsIfBindingContextIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { ModelBinderUtil.ValidateBindingContext(null, typeof(string), true); }, \"bindingContext\");\n        }\n\n        [Fact]\n        public void ValidateBindingContextThrowsIfModelInstanceIsWrongType()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = GetMetadata(typeof(string))\n            };\n            bindingContext.ModelMetadata.Model = 42;\n\n            // Act & assert\n            Assert.Throws<ArgumentException>(\n                delegate { ModelBinderUtil.ValidateBindingContext(bindingContext, typeof(string), true); },\n                \"The binding context has a Model of type 'System.Int32', but this binder can only operate on models of type 'System.String'.\" + Environment.NewLine\n              + \"Parameter name: bindingContext\");\n        }\n\n        [Fact]\n        public void ValidateBindingContextThrowsIfModelIsNullButCannotBe()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = GetMetadata(typeof(string))\n            };\n\n            // Act & assert\n            Assert.Throws<ArgumentException>(\n                delegate { ModelBinderUtil.ValidateBindingContext(bindingContext, typeof(string), false); },\n                \"The binding context has a null Model, but this binder requires a non-null model of type 'System.String'.\" + Environment.NewLine\n              + \"Parameter name: bindingContext\");\n        }\n\n        [Fact]\n        public void ValidateBindingContextThrowsIfModelMetadataIsNull()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext();\n\n            // Act & assert\n            Assert.Throws<ArgumentException>(\n                delegate { ModelBinderUtil.ValidateBindingContext(bindingContext, typeof(string), true); },\n                \"The binding context cannot have a null ModelMetadata.\" + Environment.NewLine\n              + \"Parameter name: bindingContext\");\n        }\n\n        [Fact]\n        public void ValidateBindingContextThrowsIfModelTypeIsWrong()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = GetMetadata(typeof(object))\n            };\n\n            // Act & assert\n            Assert.Throws<ArgumentException>(\n                delegate { ModelBinderUtil.ValidateBindingContext(bindingContext, typeof(string), true); },\n                \"The binding context has a ModelType of 'System.Object', but this binder can only operate on models of type 'System.String'.\" + Environment.NewLine\n              + \"Parameter name: bindingContext\");\n        }\n\n        private static ModelMetadata GetMetadata(Type modelType)\n        {\n            EmptyModelMetadataProvider provider = new EmptyModelMetadataProvider();\n            return provider.GetMetadataForType(null, modelType);\n        }\n\n        private class SampleGenericBinder<T> : IExtensibleModelBinder\n        {\n            public bool BindModel(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/ModelValidationNodeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class ModelValidationNodeTest\n    {\n        [Fact]\n        public void ConstructorSetsCollectionInstance()\n        {\n            // Arrange\n            ModelMetadata metadata = GetModelMetadata();\n            string modelStateKey = \"someKey\";\n            ModelValidationNode[] childNodes = new[]\n            {\n                new ModelValidationNode(metadata, \"someKey0\"),\n                new ModelValidationNode(metadata, \"someKey1\")\n            };\n\n            // Act\n            ModelValidationNode node = new ModelValidationNode(metadata, modelStateKey, childNodes);\n\n            // Assert\n            Assert.Equal(childNodes, node.ChildNodes.ToArray());\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfModelMetadataIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ModelValidationNode(null, \"someKey\"); }, \"modelMetadata\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfModelStateKeyIsNull()\n        {\n            // Arrange\n            ModelMetadata metadata = GetModelMetadata();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ModelValidationNode(metadata, null); }, \"modelStateKey\");\n        }\n\n        [Fact]\n        public void PropertiesAreSet()\n        {\n            // Arrange\n            ModelMetadata metadata = GetModelMetadata();\n            string modelStateKey = \"someKey\";\n\n            // Act\n            ModelValidationNode node = new ModelValidationNode(metadata, modelStateKey);\n\n            // Assert\n            Assert.Equal(metadata, node.ModelMetadata);\n            Assert.Equal(modelStateKey, node.ModelStateKey);\n            Assert.NotNull(node.ChildNodes);\n            Assert.Empty(node.ChildNodes);\n        }\n\n        [Fact]\n        public void CombineWith()\n        {\n            // Arrange\n            List<string> log = new List<string>();\n\n            ModelValidationNode[] allChildNodes = new[]\n            {\n                new ModelValidationNode(GetModelMetadata(), \"key1\"),\n                new ModelValidationNode(GetModelMetadata(), \"key2\"),\n                new ModelValidationNode(GetModelMetadata(), \"key3\"),\n            };\n\n            ModelValidationNode parentNode1 = new ModelValidationNode(GetModelMetadata(), \"parent1\");\n            parentNode1.ChildNodes.Add(allChildNodes[0]);\n            parentNode1.Validating += delegate { log.Add(\"Validating parent1.\"); };\n            parentNode1.Validated += delegate { log.Add(\"Validated parent1.\"); };\n\n            ModelValidationNode parentNode2 = new ModelValidationNode(GetModelMetadata(), \"parent2\");\n            parentNode2.ChildNodes.Add(allChildNodes[1]);\n            parentNode2.ChildNodes.Add(allChildNodes[2]);\n            parentNode2.Validating += delegate { log.Add(\"Validating parent2.\"); };\n            parentNode2.Validated += delegate { log.Add(\"Validated parent2.\"); };\n\n            // Act\n            parentNode1.CombineWith(parentNode2);\n            parentNode1.Validate(new ControllerContext { Controller = new EmptyController() });\n\n            // Assert\n            Assert.Equal(new[] { \"Validating parent1.\", \"Validating parent2.\", \"Validated parent1.\", \"Validated parent2.\" }, log.ToArray());\n            Assert.Equal(allChildNodes, parentNode1.ChildNodes.ToArray());\n        }\n\n        [Fact]\n        public void CombineWith_OtherNodeIsSuppressed_DoesNothing()\n        {\n            // Arrange\n            List<string> log = new List<string>();\n\n            ModelValidationNode[] allChildNodes = new[]\n            {\n                new ModelValidationNode(GetModelMetadata(), \"key1\"),\n                new ModelValidationNode(GetModelMetadata(), \"key2\"),\n                new ModelValidationNode(GetModelMetadata(), \"key3\"),\n            };\n\n            ModelValidationNode[] expectedChildNodes = new[]\n            {\n                allChildNodes[0]\n            };\n\n            ModelValidationNode parentNode1 = new ModelValidationNode(GetModelMetadata(), \"parent1\");\n            parentNode1.ChildNodes.Add(allChildNodes[0]);\n            parentNode1.Validating += delegate { log.Add(\"Validating parent1.\"); };\n            parentNode1.Validated += delegate { log.Add(\"Validated parent1.\"); };\n\n            ModelValidationNode parentNode2 = new ModelValidationNode(GetModelMetadata(), \"parent2\");\n            parentNode2.ChildNodes.Add(allChildNodes[1]);\n            parentNode2.ChildNodes.Add(allChildNodes[2]);\n            parentNode2.Validating += delegate { log.Add(\"Validating parent2.\"); };\n            parentNode2.Validated += delegate { log.Add(\"Validated parent2.\"); };\n            parentNode2.SuppressValidation = true;\n\n            // Act\n            parentNode1.CombineWith(parentNode2);\n            parentNode1.Validate(new ControllerContext { Controller = new EmptyController() });\n\n            // Assert\n            Assert.Equal(new[] { \"Validating parent1.\", \"Validated parent1.\" }, log.ToArray());\n            Assert.Equal(expectedChildNodes, parentNode1.ChildNodes.ToArray());\n        }\n\n        [Fact]\n        public void Validate_Ordering()\n        {\n            // Proper order of invocation:\n            // 1. OnValidating()\n            // 2. Child validators\n            // 3. This validator\n            // 4. OnValidated()\n\n            // Arrange\n            List<string> log = new List<string>();\n            LoggingDataErrorInfoModel model = new LoggingDataErrorInfoModel(log);\n            ModelMetadata modelMetadata = GetModelMetadata(model);\n\n            ControllerContext controllerContext = new ControllerContext\n            {\n                Controller = new EmptyController()\n            };\n            ModelValidationNode node = new ModelValidationNode(modelMetadata, \"theKey\");\n\n            ModelMetadata childMetadata = new EmptyModelMetadataProvider().GetMetadataForProperty(() => model, model.GetType(), \"ValidStringProperty\");\n            node.ChildNodes.Add(new ModelValidationNode(childMetadata, \"theKey.ValidStringProperty\"));\n\n            node.Validating += delegate { log.Add(\"In OnValidating()\"); };\n            node.Validated += delegate { log.Add(\"In OnValidated()\"); };\n\n            // Act\n            node.Validate(controllerContext);\n\n            // Assert\n            Assert.Equal(new[] { \"In OnValidating()\", \"In IDataErrorInfo.get_Item('ValidStringProperty')\", \"In IDataErrorInfo.get_Error()\", \"In OnValidated()\" }, log.ToArray());\n        }\n\n        [Fact]\n        public void Validate_PassesNullContainerInstanceIfCannotBeConvertedToProperType()\n        {\n            // Arrange\n            List<string> log1 = new List<string>();\n            LoggingDataErrorInfoModel model1 = new LoggingDataErrorInfoModel(log1);\n            ModelMetadata modelMetadata1 = GetModelMetadata(model1);\n\n            List<string> log2 = new List<string>();\n            LoggingDataErrorInfoModel model2 = new LoggingDataErrorInfoModel(log2);\n            ModelMetadata modelMetadata2 = GetModelMetadata(model2);\n\n            ControllerContext controllerContext = new ControllerContext\n            {\n                Controller = new EmptyController()\n            };\n            ModelValidationNode node = new ModelValidationNode(modelMetadata1, \"theKey\");\n            node.ChildNodes.Add(new ModelValidationNode(modelMetadata2, \"theKey.SomeProperty\"));\n\n            // Act\n            node.Validate(controllerContext);\n\n            // Assert\n            Assert.Equal(new[] { \"In IDataErrorInfo.get_Error()\" }, log1.ToArray());\n            Assert.Equal(new[] { \"In IDataErrorInfo.get_Error()\" }, log2.ToArray());\n        }\n\n        [Fact]\n        public void Validate_SkipsRemainingValidationIfModelStateIsInvalid()\n        {\n            // Because a property validator fails, the model validator shouldn't run\n\n            // Arrange\n            List<string> log = new List<string>();\n            LoggingDataErrorInfoModel model = new LoggingDataErrorInfoModel(log);\n            ModelMetadata modelMetadata = GetModelMetadata(model);\n\n            ControllerContext controllerContext = new ControllerContext\n            {\n                Controller = new EmptyController()\n            };\n            ModelValidationNode node = new ModelValidationNode(modelMetadata, \"theKey\");\n\n            ModelMetadata childMetadata = new EmptyModelMetadataProvider().GetMetadataForProperty(() => model, model.GetType(), \"InvalidStringProperty\");\n            node.ChildNodes.Add(new ModelValidationNode(childMetadata, \"theKey.InvalidStringProperty\"));\n\n            node.Validating += delegate { log.Add(\"In OnValidating()\"); };\n            node.Validated += delegate { log.Add(\"In OnValidated()\"); };\n\n            // Act\n            node.Validate(controllerContext);\n\n            // Assert\n            Assert.Equal(new[] { \"In OnValidating()\", \"In IDataErrorInfo.get_Item('InvalidStringProperty')\", \"In OnValidated()\" }, log.ToArray());\n            Assert.Equal(\"Sample error message\", controllerContext.Controller.ViewData.ModelState[\"theKey.InvalidStringProperty\"].Errors[0].ErrorMessage);\n        }\n\n        [Fact]\n        public void Validate_SkipsValidationIfHandlerCancels()\n        {\n            // Arrange\n            List<string> log = new List<string>();\n            LoggingDataErrorInfoModel model = new LoggingDataErrorInfoModel(log);\n            ModelMetadata modelMetadata = GetModelMetadata(model);\n\n            ControllerContext controllerContext = new ControllerContext\n            {\n                Controller = new EmptyController()\n            };\n            ModelValidationNode node = new ModelValidationNode(modelMetadata, \"theKey\");\n\n            node.Validating += (sender, e) =>\n            {\n                log.Add(\"In OnValidating()\");\n                e.Cancel = true;\n            };\n            node.Validated += delegate { log.Add(\"In OnValidated()\"); };\n\n            // Act\n            node.Validate(controllerContext);\n\n            // Assert\n            Assert.Equal(new[] { \"In OnValidating()\" }, log.ToArray());\n        }\n\n        [Fact]\n        public void Validate_SkipsValidationIfSuppressed()\n        {\n            // Arrange\n            List<string> log = new List<string>();\n            LoggingDataErrorInfoModel model = new LoggingDataErrorInfoModel(log);\n            ModelMetadata modelMetadata = GetModelMetadata(model);\n\n            ControllerContext controllerContext = new ControllerContext\n            {\n                Controller = new EmptyController()\n            };\n            ModelValidationNode node = new ModelValidationNode(modelMetadata, \"theKey\")\n            {\n                SuppressValidation = true\n            };\n\n            node.Validating += (sender, e) => { log.Add(\"In OnValidating()\"); };\n            node.Validated += delegate { log.Add(\"In OnValidated()\"); };\n\n            // Act\n            node.Validate(controllerContext);\n\n            // Assert\n            Assert.Empty(log);\n        }\n\n        [Fact]\n        public void Validate_ThrowsIfControllerContextIsNull()\n        {\n            // Arrange\n            ModelValidationNode node = new ModelValidationNode(GetModelMetadata(), \"someKey\");\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { node.Validate(null); }, \"controllerContext\");\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void Validate_ValidateAllProperties_AddsValidationErrors()\n        {\n            // Arrange\n            ValidateAllPropertiesModel model = new ValidateAllPropertiesModel\n            {\n                RequiredString = null /* error */,\n                RangedInt = 0 /* error */,\n                ValidString = \"dog\"\n            };\n\n            ModelMetadata modelMetadata = GetModelMetadata(model);\n            ControllerContext controllerContext = new ControllerContext\n            {\n                Controller = new EmptyController()\n            };\n            ModelValidationNode node = new ModelValidationNode(modelMetadata, \"theKey\")\n            {\n                ValidateAllProperties = true\n            };\n\n            controllerContext.Controller.ViewData.ModelState.AddModelError(\"theKey.RequiredString.Dummy\", \"existing Error Text\");\n\n            // Act\n            node.Validate(controllerContext);\n\n            // Assert\n            Assert.Null(controllerContext.Controller.ViewData.ModelState[\"theKey.RequiredString\"]);\n            Assert.Equal(\"existing Error Text\", controllerContext.Controller.ViewData.ModelState[\"theKey.RequiredString.Dummy\"].Errors[0].ErrorMessage);\n            Assert.Equal(\"The field RangedInt must be between 10 and 30.\", controllerContext.Controller.ViewData.ModelState[\"theKey.RangedInt\"].Errors[0].ErrorMessage);\n            Assert.Null(controllerContext.Controller.ViewData.ModelState[\"theKey.ValidString\"]);\n            Assert.Null(controllerContext.Controller.ViewData.ModelState[\"theKey\"]);\n        }\n\n        private static ModelMetadata GetModelMetadata()\n        {\n            EmptyModelMetadataProvider provider = new EmptyModelMetadataProvider();\n            return provider.GetMetadataForType(null, typeof(object));\n        }\n\n        private static ModelMetadata GetModelMetadata(object o)\n        {\n            DataAnnotationsModelMetadataProvider provider = new DataAnnotationsModelMetadataProvider();\n            return provider.GetMetadataForType(() => o, o.GetType());\n        }\n\n        private sealed class EmptyController : Controller\n        {\n        }\n\n        private sealed class LoggingDataErrorInfoModel : IDataErrorInfo\n        {\n            private readonly IList<string> _log;\n\n            public LoggingDataErrorInfoModel(IList<string> log)\n            {\n                _log = log;\n            }\n\n            string IDataErrorInfo.Error\n            {\n                get\n                {\n                    _log.Add(\"In IDataErrorInfo.get_Error()\");\n                    return null;\n                }\n            }\n\n            string IDataErrorInfo.this[string columnName]\n            {\n                get\n                {\n                    _log.Add(\"In IDataErrorInfo.get_Item('\" + columnName + \"')\");\n                    return (columnName == \"ValidStringProperty\") ? null : \"Sample error message\";\n                }\n            }\n\n            public string ValidStringProperty { get; set; }\n            public string InvalidStringProperty { get; set; }\n        }\n\n        private class ValidateAllPropertiesModel\n        {\n            [Required]\n            public string RequiredString { get; set; }\n\n            [Range(10, 30)]\n            public int RangedInt { get; set; }\n\n            [RegularExpression(\"dog\")]\n            public string ValidString { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/MutableObjectModelBinderProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class MutableObjectModelBinderProviderTest\n    {\n        [Fact]\n        public void GetBinder_NoPrefixInValueProvider_ReturnsNull()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => 42, typeof(int)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider()\n            };\n\n            MutableObjectModelBinderProvider binderProvider = new MutableObjectModelBinderProvider();\n\n            // Act\n            IExtensibleModelBinder binder = binderProvider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        [Fact]\n        public void GetBinder_PrefixInValueProvider_ReturnsBinder()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => 42, typeof(int)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"foo.bar\", \"someValue\" }\n                }\n            };\n\n            MutableObjectModelBinderProvider binderProvider = new MutableObjectModelBinderProvider();\n\n            // Act\n            IExtensibleModelBinder binder = binderProvider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.NotNull(binder);\n            Assert.IsType<MutableObjectModelBinder>(binder);\n        }\n\n        [Fact]\n        public void GetBinder_TypeIsComplexModelDto_ReturnsNull()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(ComplexModelDto)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"foo.bar\", \"someValue\" }\n                }\n            };\n\n            MutableObjectModelBinderProvider binderProvider = new MutableObjectModelBinderProvider();\n\n            // Act\n            IExtensibleModelBinder binder = binderProvider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.Null(binder);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/MutableObjectModelBinderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class MutableObjectModelBinderTest\n    {\n        [Fact]\n        public void BindModel()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelBinderProviders = new ModelBinderProviderCollection(),\n                ModelMetadata = GetMetadataForObject(new Person()),\n                ModelName = \"someName\"\n            };\n\n            Mock<IExtensibleModelBinder> mockDtoBinder = new Mock<IExtensibleModelBinder>();\n            mockDtoBinder\n                .Setup(o => o.BindModel(controllerContext, It.IsAny<ExtensibleModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ExtensibleModelBindingContext mbc2)\n                    {\n                        return true; // just return the DTO unchanged\n                    });\n            bindingContext.ModelBinderProviders.RegisterBinderForType(typeof(ComplexModelDto), mockDtoBinder.Object, true /* suppressPrefixCheck */);\n\n            Mock<TestableMutableObjectModelBinder> mockTestableBinder = new Mock<TestableMutableObjectModelBinder> { CallBase = true };\n            mockTestableBinder.Setup(o => o.EnsureModelPublic(controllerContext, bindingContext)).Verifiable();\n            mockTestableBinder.Setup(o => o.GetMetadataForPropertiesPublic(controllerContext, bindingContext)).Returns(new ModelMetadata[0]).Verifiable();\n            TestableMutableObjectModelBinder testableBinder = mockTestableBinder.Object;\n            testableBinder.MetadataProvider = new DataAnnotationsModelMetadataProvider();\n\n            // Act\n            bool retValue = testableBinder.BindModel(controllerContext, bindingContext);\n\n            // Assert\n            Assert.True(retValue);\n            Assert.IsType<Person>(bindingContext.Model);\n            Assert.True(bindingContext.ValidationNode.ValidateAllProperties);\n            mockTestableBinder.Verify();\n        }\n\n        [Fact]\n        public void CanUpdateProperty_HasPublicSetter_ReturnsTrue()\n        {\n            // Arrange\n            ModelMetadata propertyMetadata = GetMetadataForCanUpdateProperty(\"ReadWriteString\");\n\n            // Act\n            bool canUpdate = MutableObjectModelBinder.CanUpdatePropertyInternal(propertyMetadata);\n\n            // Assert\n            Assert.True(canUpdate);\n        }\n\n        [Fact]\n        public void CanUpdateProperty_ReadOnlyArray_ReturnsFalse()\n        {\n            // Arrange\n            ModelMetadata propertyMetadata = GetMetadataForCanUpdateProperty(\"ReadOnlyArray\");\n\n            // Act\n            bool canUpdate = MutableObjectModelBinder.CanUpdatePropertyInternal(propertyMetadata);\n\n            // Assert\n            Assert.False(canUpdate);\n        }\n\n        [Fact]\n        public void CanUpdateProperty_ReadOnlyReferenceTypeNotBlacklisted_ReturnsTrue()\n        {\n            // Arrange\n            ModelMetadata propertyMetadata = GetMetadataForCanUpdateProperty(\"ReadOnlyObject\");\n\n            // Act\n            bool canUpdate = MutableObjectModelBinder.CanUpdatePropertyInternal(propertyMetadata);\n\n            // Assert\n            Assert.True(canUpdate);\n        }\n\n        [Fact]\n        public void CanUpdateProperty_ReadOnlyString_ReturnsFalse()\n        {\n            // Arrange\n            ModelMetadata propertyMetadata = GetMetadataForCanUpdateProperty(\"ReadOnlyString\");\n\n            // Act\n            bool canUpdate = MutableObjectModelBinder.CanUpdatePropertyInternal(propertyMetadata);\n\n            // Assert\n            Assert.False(canUpdate);\n        }\n\n        [Fact]\n        public void CanUpdateProperty_ReadOnlyValueType_ReturnsFalse()\n        {\n            // Arrange\n            ModelMetadata propertyMetadata = GetMetadataForCanUpdateProperty(\"ReadOnlyInt\");\n\n            // Act\n            bool canUpdate = MutableObjectModelBinder.CanUpdatePropertyInternal(propertyMetadata);\n\n            // Assert\n            Assert.False(canUpdate);\n        }\n\n        [Fact]\n        public void CreateModel()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = GetMetadataForType(typeof(Person))\n            };\n\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Act\n            object retModel = testableBinder.CreateModelPublic(null, bindingContext);\n\n            // Assert\n            Assert.IsType<Person>(retModel);\n        }\n\n        [Fact]\n        public void CreateModelThrowsIfModelTypeHasNoParameterlessConstructor()\n        {\n            // Arrange\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = GetMetadataForType(typeof(NoParameterlessCtor)),\n            };\n\n            // Act & Assert, confirming type name and full stack are available in Exception\n            MissingMethodException exception = Assert.Throws<MissingMethodException>(\n                () => testableBinder.CreateModelPublic(null, bindingContext),\n                \"No parameterless constructor defined for this object. Object type 'Microsoft.Web.Mvc.ModelBinding.Test.MutableObjectModelBinderTest+NoParameterlessCtor'.\");\n            Assert.Contains(\"System.Activator.CreateInstance(\", exception.ToString());\n        }\n\n        [Fact]\n        public void EnsureModel_ModelIsNotNull_DoesNothing()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = GetMetadataForObject(new Person())\n            };\n\n            Mock<TestableMutableObjectModelBinder> mockTestableBinder = new Mock<TestableMutableObjectModelBinder> { CallBase = true };\n            TestableMutableObjectModelBinder testableBinder = mockTestableBinder.Object;\n\n            // Act\n            object originalModel = bindingContext.Model;\n            testableBinder.EnsureModelPublic(null, bindingContext);\n            object newModel = bindingContext.Model;\n\n            // Assert\n            Assert.Same(originalModel, newModel);\n            mockTestableBinder.Verify(o => o.CreateModelPublic(null, bindingContext), Times.Never());\n        }\n\n        [Fact]\n        public void EnsureModel_ModelIsNull_CallsCreateModel()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = GetMetadataForType(typeof(Person))\n            };\n\n            Mock<TestableMutableObjectModelBinder> mockTestableBinder = new Mock<TestableMutableObjectModelBinder> { CallBase = true };\n            mockTestableBinder.Setup(o => o.CreateModelPublic(null, bindingContext)).Returns(new Person()).Verifiable();\n            TestableMutableObjectModelBinder testableBinder = mockTestableBinder.Object;\n\n            // Act\n            object originalModel = bindingContext.Model;\n            testableBinder.EnsureModelPublic(null, bindingContext);\n            object newModel = bindingContext.Model;\n\n            // Assert\n            Assert.Null(originalModel);\n            Assert.IsType<Person>(newModel);\n            mockTestableBinder.Verify();\n        }\n\n        [Fact]\n        public void GetMetadataForProperties_WithBindAttribute()\n        {\n            // Arrange\n            string[] expectedPropertyNames = new[] { \"FirstName\", \"LastName\" };\n\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = GetMetadataForType(typeof(PersonWithBindExclusion))\n            };\n\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Act\n            IEnumerable<ModelMetadata> propertyMetadatas = testableBinder.GetMetadataForPropertiesPublic(null, bindingContext);\n            string[] returnedPropertyNames = propertyMetadatas.Select(o => o.PropertyName).ToArray();\n\n            // Assert\n            Assert.Equal(expectedPropertyNames, returnedPropertyNames);\n        }\n\n        [Fact]\n        public void GetMetadataForProperties_WithoutBindAttribute()\n        {\n            // Arrange\n            string[] expectedPropertyNames = new[] { \"DateOfBirth\", \"DateOfDeath\", \"ValueTypeRequired\", \"FirstName\", \"LastName\", \"PropertyWithDefaultValue\" };\n\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = GetMetadataForType(typeof(Person))\n            };\n\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Act\n            IEnumerable<ModelMetadata> propertyMetadatas = testableBinder.GetMetadataForPropertiesPublic(null, bindingContext);\n            string[] returnedPropertyNames = propertyMetadatas.Select(o => o.PropertyName).ToArray();\n\n            // Assert\n            Assert.Equal(expectedPropertyNames, returnedPropertyNames);\n        }\n\n        [Fact]\n        public void GetRequiredPropertiesCollection_MixedAttributes()\n        {\n            // Arrange\n            Type modelType = typeof(ModelWithMixedBindingBehaviors);\n\n            // Act\n            HashSet<string> requiredProperties;\n            HashSet<string> skipProperties;\n            MutableObjectModelBinder.GetRequiredPropertiesCollection(modelType, out requiredProperties, out skipProperties);\n\n            // Assert\n            Assert.Equal(new[] { \"Required\" }, requiredProperties.ToArray());\n            Assert.Equal(new[] { \"Never\" }, skipProperties.ToArray());\n        }\n\n        [Fact]\n        public void NullCheckFailedHandler_ModelStateAlreadyInvalid_DoesNothing()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext\n            {\n                Controller = new EmptyController()\n            };\n            controllerContext.Controller.ViewData.ModelState.AddModelError(\"foo.bar\", \"Some existing error.\");\n\n            ModelMetadata modelMetadata = GetMetadataForType(typeof(Person));\n            ModelValidationNode validationNode = new ModelValidationNode(modelMetadata, \"foo\");\n            ModelValidatedEventArgs e = new ModelValidatedEventArgs(controllerContext, null /* parentNode */);\n\n            // Act\n            EventHandler<ModelValidatedEventArgs> handler = MutableObjectModelBinder.CreateNullCheckFailedHandler(controllerContext, modelMetadata, null /* incomingValue */);\n            handler(validationNode, e);\n\n            // Assert\n            Assert.False(controllerContext.Controller.ViewData.ModelState.ContainsKey(\"foo\"));\n        }\n\n        [Fact]\n        public void NullCheckFailedHandler_ModelStateValid_AddsErrorString()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext\n            {\n                Controller = new EmptyController()\n            };\n\n            ModelMetadata modelMetadata = GetMetadataForType(typeof(Person));\n            ModelValidationNode validationNode = new ModelValidationNode(modelMetadata, \"foo\");\n            ModelValidatedEventArgs e = new ModelValidatedEventArgs(controllerContext, null /* parentNode */);\n\n            // Act\n            EventHandler<ModelValidatedEventArgs> handler = MutableObjectModelBinder.CreateNullCheckFailedHandler(controllerContext, modelMetadata, null /* incomingValue */);\n            handler(validationNode, e);\n\n            // Assert\n            Assert.True(controllerContext.Controller.ViewData.ModelState.ContainsKey(\"foo\"));\n            Assert.Equal(\"A value is required.\", controllerContext.Controller.ViewData.ModelState[\"foo\"].Errors[0].ErrorMessage);\n        }\n\n        [Fact]\n        public void NullCheckFailedHandler_ModelStateValid_CallbackReturnsNull_DoesNothing()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext\n            {\n                Controller = new EmptyController()\n            };\n\n            ModelMetadata modelMetadata = GetMetadataForType(typeof(Person));\n            ModelValidationNode validationNode = new ModelValidationNode(modelMetadata, \"foo\");\n            ModelValidatedEventArgs e = new ModelValidatedEventArgs(controllerContext, null /* parentNode */);\n\n            // Act\n            ModelBinderErrorMessageProvider originalProvider = ModelBinderConfig.ValueRequiredErrorMessageProvider;\n            try\n            {\n                ModelBinderConfig.ValueRequiredErrorMessageProvider = delegate { return null; };\n                EventHandler<ModelValidatedEventArgs> handler = MutableObjectModelBinder.CreateNullCheckFailedHandler(controllerContext, modelMetadata, null /* incomingValue */);\n                handler(validationNode, e);\n            }\n            finally\n            {\n                ModelBinderConfig.ValueRequiredErrorMessageProvider = originalProvider;\n            }\n\n            // Assert\n            Assert.True(controllerContext.Controller.ViewData.ModelState.IsValid);\n        }\n\n        [Fact]\n        public void ProcessDto_BindRequiredFieldMissing_Throws()\n        {\n            // Arrange\n            ModelWithBindRequired model = new ModelWithBindRequired\n            {\n                Name = \"original value\",\n                Age = -20\n            };\n\n            ModelMetadata containerMetadata = GetMetadataForObject(model);\n\n            ControllerContext controllerContext = new ControllerContext();\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = containerMetadata,\n                ModelName = \"theModel\"\n            };\n            ComplexModelDto dto = new ComplexModelDto(containerMetadata, containerMetadata.Properties);\n\n            ModelMetadata nameProperty = dto.PropertyMetadata.Single(o => o.PropertyName == \"Name\");\n            dto.Results[nameProperty] = new ComplexModelDtoResult(\"John Doe\", new ModelValidationNode(nameProperty, \"\"));\n\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Act & assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { testableBinder.ProcessDto(controllerContext, bindingContext, dto); },\n                @\"A value for 'theModel.Age' is required but was not present in the request.\");\n\n            Assert.Equal(\"original value\", model.Name);\n            Assert.Equal(-20, model.Age);\n        }\n\n        [Fact]\n        public void ProcessDto_Success()\n        {\n            // Arrange\n            DateTime dob = new DateTime(2001, 1, 1);\n            Person model = new Person\n            {\n                DateOfBirth = dob\n            };\n            ModelMetadata containerMetadata = GetMetadataForObject(model);\n\n            ControllerContext controllerContext = new ControllerContext();\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = containerMetadata\n            };\n            ComplexModelDto dto = new ComplexModelDto(containerMetadata, containerMetadata.Properties);\n\n            ModelMetadata firstNameProperty = dto.PropertyMetadata.Single(o => o.PropertyName == \"FirstName\");\n            dto.Results[firstNameProperty] = new ComplexModelDtoResult(\"John\", new ModelValidationNode(firstNameProperty, \"\"));\n            ModelMetadata lastNameProperty = dto.PropertyMetadata.Single(o => o.PropertyName == \"LastName\");\n            dto.Results[lastNameProperty] = new ComplexModelDtoResult(\"Doe\", new ModelValidationNode(lastNameProperty, \"\"));\n            ModelMetadata dobProperty = dto.PropertyMetadata.Single(o => o.PropertyName == \"DateOfBirth\");\n            dto.Results[dobProperty] = null;\n\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Act\n            testableBinder.ProcessDto(controllerContext, bindingContext, dto);\n\n            // Assert\n            Assert.Equal(\"John\", model.FirstName);\n            Assert.Equal(\"Doe\", model.LastName);\n            Assert.Equal(dob, model.DateOfBirth);\n            Assert.True(bindingContext.ModelState.IsValid);\n        }\n\n        [Fact]\n        public void SetProperty_PropertyHasDefaultValue_SetsDefaultValue()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext\n            {\n                Controller = new EmptyController()\n            };\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = GetMetadataForObject(new Person())\n            };\n\n            ModelMetadata propertyMetadata = bindingContext.ModelMetadata.Properties.Single(o => o.PropertyName == \"PropertyWithDefaultValue\");\n            ModelValidationNode validationNode = new ModelValidationNode(propertyMetadata, \"foo\");\n            ComplexModelDtoResult dtoResult = new ComplexModelDtoResult(null /* model */, validationNode);\n\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Act\n            testableBinder.SetPropertyPublic(controllerContext, bindingContext, propertyMetadata, dtoResult);\n\n            // Assert\n            var person = Assert.IsType<Person>(bindingContext.Model);\n            Assert.Equal(123.456m, person.PropertyWithDefaultValue);\n            Assert.True(controllerContext.Controller.ViewData.ModelState.IsValid);\n        }\n\n        [Fact]\n        public void SetProperty_PropertyIsReadOnly_DoesNothing()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = GetMetadataForType(typeof(Person))\n            };\n\n            ModelMetadata propertyMetadata = bindingContext.ModelMetadata.Properties.Single(o => o.PropertyName == \"NonUpdateableProperty\");\n            ModelValidationNode validationNode = new ModelValidationNode(propertyMetadata, \"foo\");\n            ComplexModelDtoResult dtoResult = new ComplexModelDtoResult(null /* model */, validationNode);\n\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Act\n            testableBinder.SetPropertyPublic(null, bindingContext, propertyMetadata, dtoResult);\n\n            // Assert\n            // If didn't throw, success!\n        }\n\n        [Fact]\n        public void SetProperty_PropertyIsSettable_CallsSetter()\n        {\n            // Arrange\n            Person model = new Person();\n            ControllerContext controllerContext = new ControllerContext\n            {\n                Controller = new EmptyController()\n            };\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = GetMetadataForObject(model)\n            };\n\n            ModelMetadata propertyMetadata = bindingContext.ModelMetadata.Properties.Single(o => o.PropertyName == \"DateOfBirth\");\n            ModelValidationNode validationNode = new ModelValidationNode(propertyMetadata, \"foo\");\n            ComplexModelDtoResult dtoResult = new ComplexModelDtoResult(new DateTime(2001, 1, 1), validationNode);\n\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Act\n            testableBinder.SetPropertyPublic(controllerContext, bindingContext, propertyMetadata, dtoResult);\n\n            // Assert\n            validationNode.Validate(controllerContext);\n            Assert.True(controllerContext.Controller.ViewData.ModelState.IsValid);\n            Assert.Equal(new DateTime(2001, 1, 1), model.DateOfBirth);\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void SetProperty_PropertyIsSettable_SetterThrows_RecordsError()\n        {\n            // Arrange\n            Person model = new Person\n            {\n                DateOfBirth = new DateTime(1900, 1, 1)\n            };\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = GetMetadataForObject(model)\n            };\n\n            ModelMetadata propertyMetadata = bindingContext.ModelMetadata.Properties.Single(o => o.PropertyName == \"DateOfDeath\");\n            ModelValidationNode validationNode = new ModelValidationNode(propertyMetadata, \"foo\");\n            ComplexModelDtoResult dtoResult = new ComplexModelDtoResult(new DateTime(1800, 1, 1), validationNode);\n\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Act\n            testableBinder.SetPropertyPublic(null, bindingContext, propertyMetadata, dtoResult);\n\n            // Assert\n            Assert.Equal(\"Date of death can't be before date of birth.\" + Environment.NewLine\n                       + \"Parameter name: value\",\n                         bindingContext.ModelState[\"foo\"].Errors[0].Exception.Message);\n        }\n\n        [Fact]\n        public void SetProperty_SettingNonNullableValueTypeToNull_RequiredValidatorNotPresent_RegistersValidationCallback()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext\n            {\n                Controller = new EmptyController()\n            };\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = GetMetadataForObject(new Person()),\n            };\n\n            ModelMetadata propertyMetadata = bindingContext.ModelMetadata.Properties.Single(o => o.PropertyName == \"DateOfBirth\");\n            ModelValidationNode validationNode = new ModelValidationNode(propertyMetadata, \"foo\");\n            ComplexModelDtoResult dtoResult = new ComplexModelDtoResult(null /* model */, validationNode);\n\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Act\n            testableBinder.SetPropertyPublic(controllerContext, bindingContext, propertyMetadata, dtoResult);\n\n            // Assert\n            Assert.True(controllerContext.Controller.ViewData.ModelState.IsValid);\n            validationNode.Validate(controllerContext, bindingContext.ValidationNode);\n            Assert.False(controllerContext.Controller.ViewData.ModelState.IsValid);\n        }\n\n        [Fact]\n        public void SetProperty_SettingNonNullableValueTypeToNull_RequiredValidatorPresent_AddsModelError()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext\n            {\n                Controller = new EmptyController()\n            };\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = GetMetadataForObject(new Person()),\n                ModelName = \"foo\"\n            };\n\n            ModelMetadata propertyMetadata = bindingContext.ModelMetadata.Properties.Single(o => o.PropertyName == \"ValueTypeRequired\");\n            ModelValidationNode validationNode = new ModelValidationNode(propertyMetadata, \"foo.ValueTypeRequired\");\n            ComplexModelDtoResult dtoResult = new ComplexModelDtoResult(null /* model */, validationNode);\n\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Act\n            testableBinder.SetPropertyPublic(controllerContext, bindingContext, propertyMetadata, dtoResult);\n\n            // Assert\n            Assert.False(bindingContext.ModelState.IsValid);\n            Assert.Equal(\"Sample message\", bindingContext.ModelState[\"foo.ValueTypeRequired\"].Errors[0].ErrorMessage);\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void SetProperty_SettingNullableTypeToNull_RequiredValidatorNotPresent_PropertySetterThrows_AddsRequiredMessageString()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext\n            {\n                Controller = new EmptyController()\n            };\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = GetMetadataForObject(new ModelWhosePropertySetterThrows()),\n                ModelName = \"foo\"\n            };\n\n            ModelMetadata propertyMetadata = bindingContext.ModelMetadata.Properties.Single(o => o.PropertyName == \"NameNoAttribute\");\n            ModelValidationNode validationNode = new ModelValidationNode(propertyMetadata, \"foo.NameNoAttribute\");\n            ComplexModelDtoResult dtoResult = new ComplexModelDtoResult(null /* model */, validationNode);\n\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Act\n            testableBinder.SetPropertyPublic(controllerContext, bindingContext, propertyMetadata, dtoResult);\n\n            // Assert\n            Assert.False(bindingContext.ModelState.IsValid);\n            ModelError error = Assert.Single(bindingContext.ModelState[\"foo.NameNoAttribute\"].Errors);\n            Assert.Equal(\"This is a different exception.\" + Environment.NewLine\n                       + \"Parameter name: value\",\n                         error.Exception.Message);\n        }\n\n        [Fact]\n        public void SetProperty_SettingNullableTypeToNull_RequiredValidatorPresent_PropertySetterThrows_AddsRequiredMessageString()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext\n            {\n                Controller = new EmptyController()\n            };\n            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext\n            {\n                ModelMetadata = GetMetadataForObject(new ModelWhosePropertySetterThrows()),\n                ModelName = \"foo\"\n            };\n\n            ModelMetadata propertyMetadata = bindingContext.ModelMetadata.Properties.Single(o => o.PropertyName == \"Name\");\n            ModelValidationNode validationNode = new ModelValidationNode(propertyMetadata, \"foo.Name\");\n            ComplexModelDtoResult dtoResult = new ComplexModelDtoResult(null /* model */, validationNode);\n\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Act\n            testableBinder.SetPropertyPublic(controllerContext, bindingContext, propertyMetadata, dtoResult);\n\n            // Assert\n            Assert.False(bindingContext.ModelState.IsValid);\n            ModelError error = Assert.Single(bindingContext.ModelState[\"foo.Name\"].Errors);\n            Assert.Equal(\"This message comes from the [Required] attribute.\", error.ErrorMessage);\n        }\n\n        private static ModelMetadata GetMetadataForCanUpdateProperty(string propertyName)\n        {\n            DataAnnotationsModelMetadataProvider metadataProvider = new DataAnnotationsModelMetadataProvider();\n            return metadataProvider.GetMetadataForProperty(null, typeof(MyModelTestingCanUpdateProperty), propertyName);\n        }\n\n        private static ModelMetadata GetMetadataForObject(object o)\n        {\n            DataAnnotationsModelMetadataProvider metadataProvider = new DataAnnotationsModelMetadataProvider();\n            return metadataProvider.GetMetadataForType(() => o, o.GetType());\n        }\n\n        private static ModelMetadata GetMetadataForType(Type t)\n        {\n            DataAnnotationsModelMetadataProvider metadataProvider = new DataAnnotationsModelMetadataProvider();\n            return metadataProvider.GetMetadataForType(null, t);\n        }\n\n        private class Person\n        {\n            private DateTime? _dateOfDeath;\n\n            public DateTime DateOfBirth { get; set; }\n\n            public DateTime? DateOfDeath\n            {\n                get { return _dateOfDeath; }\n                set\n                {\n                    if (value < DateOfBirth)\n                    {\n                        throw new ArgumentOutOfRangeException(\"value\", \"Date of death can't be before date of birth.\");\n                    }\n                    _dateOfDeath = value;\n                }\n            }\n\n            [Required(ErrorMessage = \"Sample message\")]\n            public int ValueTypeRequired { get; set; }\n\n            public string FirstName { get; set; }\n            public string LastName { get; set; }\n            public string NonUpdateableProperty { get; private set; }\n\n            [DefaultValue(typeof(decimal), \"123.456\")]\n            public decimal PropertyWithDefaultValue { get; set; }\n        }\n\n        private class NoParameterlessCtor\n        {\n            public NoParameterlessCtor(int parameter)\n            {\n            }\n        }\n\n        private class PersonWithBindExclusion\n        {\n            [BindNever]\n            public DateTime DateOfBirth { get; set; }\n\n            [BindNever]\n            public DateTime? DateOfDeath { get; set; }\n\n            public string FirstName { get; set; }\n            public string LastName { get; set; }\n            public string NonUpdateableProperty { get; private set; }\n        }\n\n        private class ModelWithBindRequired\n        {\n            public string Name { get; set; }\n\n            [BindRequired]\n            public int Age { get; set; }\n        }\n\n        [BindRequired]\n        private class ModelWithMixedBindingBehaviors\n        {\n            public string Required { get; set; }\n\n            [BindNever]\n            public string Never { get; set; }\n\n            [BindingBehavior(BindingBehavior.Optional)]\n            public string Optional { get; set; }\n        }\n\n        private sealed class MyModelTestingCanUpdateProperty\n        {\n            public int ReadOnlyInt { get; private set; }\n            public string ReadOnlyString { get; private set; }\n            public string[] ReadOnlyArray { get; private set; }\n            public object ReadOnlyObject { get; private set; }\n            public string ReadWriteString { get; set; }\n        }\n\n        private sealed class ModelWhosePropertySetterThrows\n        {\n            [Required(ErrorMessage = \"This message comes from the [Required] attribute.\")]\n            public string Name\n            {\n                get { return null; }\n                set { throw new ArgumentException(\"This is an exception.\", \"value\"); }\n            }\n\n            public string NameNoAttribute\n            {\n                get { return null; }\n                set { throw new ArgumentException(\"This is a different exception.\", \"value\"); }\n            }\n        }\n\n        public class TestableMutableObjectModelBinder : MutableObjectModelBinder\n        {\n            public virtual bool CanUpdatePropertyPublic(ModelMetadata propertyMetadata)\n            {\n                return base.CanUpdateProperty(propertyMetadata);\n            }\n\n            protected override bool CanUpdateProperty(ModelMetadata propertyMetadata)\n            {\n                return CanUpdatePropertyPublic(propertyMetadata);\n            }\n\n            public virtual object CreateModelPublic(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n            {\n                return base.CreateModel(controllerContext, bindingContext);\n            }\n\n            protected override object CreateModel(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n            {\n                return CreateModelPublic(controllerContext, bindingContext);\n            }\n\n            public virtual void EnsureModelPublic(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n            {\n                base.EnsureModel(controllerContext, bindingContext);\n            }\n\n            protected override void EnsureModel(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n            {\n                EnsureModelPublic(controllerContext, bindingContext);\n            }\n\n            public virtual IEnumerable<ModelMetadata> GetMetadataForPropertiesPublic(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n            {\n                return base.GetMetadataForProperties(controllerContext, bindingContext);\n            }\n\n            protected override IEnumerable<ModelMetadata> GetMetadataForProperties(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext)\n            {\n                return GetMetadataForPropertiesPublic(controllerContext, bindingContext);\n            }\n\n            public virtual void SetPropertyPublic(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext, ModelMetadata propertyMetadata, ComplexModelDtoResult dtoResult)\n            {\n                base.SetProperty(controllerContext, bindingContext, propertyMetadata, dtoResult);\n            }\n\n            protected override void SetProperty(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext, ModelMetadata propertyMetadata, ComplexModelDtoResult dtoResult)\n            {\n                SetPropertyPublic(controllerContext, bindingContext, propertyMetadata, dtoResult);\n            }\n        }\n\n        private class EmptyController : Controller\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/SimpleModelBinderProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\nusing Moq;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class SimpleModelBinderProviderTest\n    {\n        [Fact]\n        public void ConstructorWithFactoryThrowsIfModelBinderFactoryIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new SimpleModelBinderProvider(typeof(object), (Func<IExtensibleModelBinder>)null); }, \"modelBinderFactory\");\n        }\n\n        [Fact]\n        public void ConstructorWithFactoryThrowsIfModelTypeIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new SimpleModelBinderProvider(null, () => null); }, \"modelType\");\n        }\n\n        [Fact]\n        public void ConstructorWithInstanceThrowsIfModelBinderIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new SimpleModelBinderProvider(typeof(object), (IExtensibleModelBinder)null); }, \"modelBinder\");\n        }\n\n        [Fact]\n        public void ConstructorWithInstanceThrowsIfModelTypeIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new SimpleModelBinderProvider(null, new Mock<IExtensibleModelBinder>().Object); }, \"modelType\");\n        }\n\n        [Fact]\n        public void GetBinder_TypeDoesNotMatch_ReturnsNull()\n        {\n            // Arrange\n            SimpleModelBinderProvider provider = new SimpleModelBinderProvider(typeof(string), new Mock<IExtensibleModelBinder>().Object)\n            {\n                SuppressPrefixCheck = true\n            };\n            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(object));\n\n            // Act\n            IExtensibleModelBinder binder = provider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        [Fact]\n        public void GetBinder_TypeMatches_PrefixNotFound_ReturnsNull()\n        {\n            // Arrange\n            IExtensibleModelBinder binderInstance = new Mock<IExtensibleModelBinder>().Object;\n            SimpleModelBinderProvider provider = new SimpleModelBinderProvider(typeof(string), binderInstance);\n\n            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(string));\n            bindingContext.ValueProvider = new SimpleValueProvider();\n\n            // Act\n            IExtensibleModelBinder returnedBinder = provider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.Null(returnedBinder);\n        }\n\n        [Fact]\n        public void GetBinder_TypeMatches_PrefixSuppressed_ReturnsFactoryInstance()\n        {\n            // Arrange\n            int numExecutions = 0;\n            IExtensibleModelBinder theBinderInstance = new Mock<IExtensibleModelBinder>().Object;\n            Func<IExtensibleModelBinder> factory = delegate\n            {\n                numExecutions++;\n                return theBinderInstance;\n            };\n\n            SimpleModelBinderProvider provider = new SimpleModelBinderProvider(typeof(string), factory)\n            {\n                SuppressPrefixCheck = true\n            };\n            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(string));\n\n            // Act\n            IExtensibleModelBinder returnedBinder = provider.GetBinder(null, bindingContext);\n            returnedBinder = provider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.Equal(2, numExecutions);\n            Assert.Equal(theBinderInstance, returnedBinder);\n        }\n\n        [Fact]\n        public void GetBinder_TypeMatches_PrefixSuppressed_ReturnsInstance()\n        {\n            // Arrange\n            IExtensibleModelBinder theBinderInstance = new Mock<IExtensibleModelBinder>().Object;\n            SimpleModelBinderProvider provider = new SimpleModelBinderProvider(typeof(string), theBinderInstance)\n            {\n                SuppressPrefixCheck = true\n            };\n            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(string));\n\n            // Act\n            IExtensibleModelBinder returnedBinder = provider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.Equal(theBinderInstance, returnedBinder);\n        }\n\n        [Fact]\n        public void GetBinderThrowsIfBindingContextIsNull()\n        {\n            // Arrange\n            SimpleModelBinderProvider provider = new SimpleModelBinderProvider(typeof(string), new Mock<IExtensibleModelBinder>().Object);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { provider.GetBinder(null, null); }, \"bindingContext\");\n        }\n\n        [Fact]\n        public void ModelTypeProperty()\n        {\n            // Arrange\n            SimpleModelBinderProvider provider = new SimpleModelBinderProvider(typeof(string), new Mock<IExtensibleModelBinder>().Object);\n\n            // Act & assert\n            Assert.Equal(typeof(string), provider.ModelType);\n        }\n\n        private static ExtensibleModelBindingContext GetBindingContext(Type modelType)\n        {\n            return new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => null, modelType)\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/TypeConverterModelBinderProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class TypeConverterModelBinderProviderTest\n    {\n        [Fact]\n        public void GetBinder_NoTypeConverterExistsFromString_ReturnsNull()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(void)); // no TypeConverter exists Void -> String\n\n            TypeConverterModelBinderProvider provider = new TypeConverterModelBinderProvider();\n\n            // Act\n            IExtensibleModelBinder binder = provider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        [Fact]\n        public void GetBinder_NullValueProviderResult_ReturnsNull()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(int));\n            bindingContext.ValueProvider = new SimpleValueProvider(); // clear the ValueProvider\n\n            TypeConverterModelBinderProvider provider = new TypeConverterModelBinderProvider();\n\n            // Act\n            IExtensibleModelBinder binder = provider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        [Fact]\n        public void GetBinder_TypeConverterExistsFromString_ReturnsNull()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(int)); // TypeConverter exists Int32 -> String\n\n            TypeConverterModelBinderProvider provider = new TypeConverterModelBinderProvider();\n\n            // Act\n            IExtensibleModelBinder binder = provider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.IsType<TypeConverterModelBinder>(binder);\n        }\n\n        private static ExtensibleModelBindingContext GetBindingContext(Type modelType)\n        {\n            return new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, modelType),\n                ModelName = \"theModelName\",\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"theModelName\", \"someValue\" }\n                }\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/TypeConverterModelBinderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class TypeConverterModelBinderTest\n    {\n        [Fact]\n        public void BindModel_Error_FormatExceptionsTurnedIntoStringsInModelState()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(int));\n            bindingContext.ValueProvider = new SimpleValueProvider\n            {\n                { \"theModelName\", \"not an integer\" }\n            };\n\n            TypeConverterModelBinder binder = new TypeConverterModelBinder();\n\n            // Act\n            bool retVal = binder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.False(retVal);\n            Assert.Equal(\"The value 'not an integer' is not valid for Int32.\", bindingContext.ModelState[\"theModelName\"].Errors[0].ErrorMessage);\n        }\n\n        [Fact]\n        public void BindModel_Error_FormatExceptionsTurnedIntoStringsInModelState_ErrorNotAddedIfCallbackReturnsNull()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(int));\n            bindingContext.ValueProvider = new SimpleValueProvider\n            {\n                { \"theModelName\", \"not an integer\" }\n            };\n\n            TypeConverterModelBinder binder = new TypeConverterModelBinder();\n\n            // Act\n            ModelBinderErrorMessageProvider originalProvider = ModelBinderConfig.TypeConversionErrorMessageProvider;\n            bool retVal;\n            try\n            {\n                ModelBinderConfig.TypeConversionErrorMessageProvider = delegate { return null; };\n                retVal = binder.BindModel(null, bindingContext);\n            }\n            finally\n            {\n                ModelBinderConfig.TypeConversionErrorMessageProvider = originalProvider;\n            }\n\n            // Assert\n            Assert.False(retVal);\n            Assert.Null(bindingContext.Model);\n            Assert.True(bindingContext.ModelState.IsValid);\n        }\n\n        [Fact]\n        public void BindModel_Error_GeneralExceptionsSavedInModelState()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(Dummy));\n            bindingContext.ValueProvider = new SimpleValueProvider\n            {\n                { \"theModelName\", \"foo\" }\n            };\n\n            TypeConverterModelBinder binder = new TypeConverterModelBinder();\n\n            // Act\n            bool retVal = binder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.False(retVal);\n            Assert.Null(bindingContext.Model);\n            Assert.Equal(\"The parameter conversion from type 'System.String' to type 'Microsoft.Web.Mvc.ModelBinding.Test.TypeConverterModelBinderTest+Dummy' failed. See the inner exception for more information.\", bindingContext.ModelState[\"theModelName\"].Errors[0].Exception.Message);\n            Assert.Equal(\"From DummyTypeConverter: foo\", bindingContext.ModelState[\"theModelName\"].Errors[0].Exception.InnerException.Message);\n        }\n\n        [Fact]\n        public void BindModel_NullValueProviderResult_ReturnsFalse()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(int));\n\n            TypeConverterModelBinder binder = new TypeConverterModelBinder();\n\n            // Act\n            bool retVal = binder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.False(retVal, \"BindModel should have returned null.\");\n            Assert.Empty(bindingContext.ModelState);\n        }\n\n        [Fact]\n        public void BindModel_ValidValueProviderResult_ConvertEmptyStringsToNull()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(string));\n            bindingContext.ValueProvider = new SimpleValueProvider\n            {\n                { \"theModelName\", \"\" }\n            };\n\n            TypeConverterModelBinder binder = new TypeConverterModelBinder();\n\n            // Act\n            bool retVal = binder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Null(bindingContext.Model);\n            Assert.True(bindingContext.ModelState.ContainsKey(\"theModelName\"));\n        }\n\n        [Fact]\n        public void BindModel_ValidValueProviderResult_ReturnsModel()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(int));\n            bindingContext.ValueProvider = new SimpleValueProvider\n            {\n                { \"theModelName\", \"42\" }\n            };\n\n            TypeConverterModelBinder binder = new TypeConverterModelBinder();\n\n            // Act\n            bool retVal = binder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Equal(42, bindingContext.Model);\n            Assert.True(bindingContext.ModelState.ContainsKey(\"theModelName\"));\n        }\n\n        private static ExtensibleModelBindingContext GetBindingContext(Type modelType)\n        {\n            return new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, modelType),\n                ModelName = \"theModelName\",\n                ValueProvider = new SimpleValueProvider() // empty\n            };\n        }\n\n        [TypeConverter(typeof(DummyTypeConverter))]\n        private struct Dummy\n        {\n        }\n\n        private sealed class DummyTypeConverter : TypeConverter\n        {\n            public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)\n            {\n                return (sourceType == typeof(string)) || base.CanConvertFrom(context, sourceType);\n            }\n\n            public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)\n            {\n                throw new InvalidOperationException(String.Format(\"From DummyTypeConverter: {0}\", value));\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/TypeMatchModelBinderProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Linq;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class TypeMatchModelBinderProviderTest\n    {\n        [Fact]\n        public void ProviderIsMarkedFrontOfList()\n        {\n            // Arrange\n            Type t = typeof(TypeMatchModelBinderProvider);\n\n            // Act & assert\n            Assert.True(t.GetCustomAttributes(typeof(ModelBinderProviderOptionsAttribute), true /* inherit */).Cast<ModelBinderProviderOptionsAttribute>().Single().FrontOfList);\n        }\n\n        [Fact]\n        public void GetBinder_InvalidValueProviderResult_ReturnsNull()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = GetBindingContext();\n            bindingContext.ValueProvider = new SimpleValueProvider\n            {\n                { \"theModelName\", \"not an integer\" }\n            };\n\n            TypeMatchModelBinderProvider provider = new TypeMatchModelBinderProvider();\n\n            // Act\n            IExtensibleModelBinder binder = provider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        [Fact]\n        public void BindModel_ValidValueProviderResult_ReturnsBinder()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = GetBindingContext();\n            bindingContext.ValueProvider = new SimpleValueProvider\n            {\n                { \"theModelName\", 42 }\n            };\n\n            TypeMatchModelBinderProvider provider = new TypeMatchModelBinderProvider();\n\n            // Act\n            IExtensibleModelBinder binder = provider.GetBinder(null, bindingContext);\n\n            // Assert\n            Assert.IsType<TypeMatchModelBinder>(binder);\n        }\n\n        private static ExtensibleModelBindingContext GetBindingContext()\n        {\n            return GetBindingContext(typeof(int));\n        }\n\n        private static ExtensibleModelBindingContext GetBindingContext(Type modelType)\n        {\n            return new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, modelType),\n                ModelName = \"theModelName\"\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/ModelBinding/Test/TypeMatchModelBinderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace Microsoft.Web.Mvc.ModelBinding.Test\n{\n    public class TypeMatchModelBinderTest\n    {\n        [Fact]\n        public void BindModel_InvalidValueProviderResult_ReturnsFalse()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = GetBindingContext();\n            bindingContext.ValueProvider = new SimpleValueProvider\n            {\n                { \"theModelName\", \"not an integer\" }\n            };\n\n            TypeMatchModelBinder binder = new TypeMatchModelBinder();\n\n            // Act\n            bool retVal = binder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.False(retVal);\n            Assert.Empty(bindingContext.ModelState);\n        }\n\n        [Fact]\n        public void BindModel_ValidValueProviderResult_ReturnsTrue()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = GetBindingContext();\n            bindingContext.ValueProvider = new SimpleValueProvider\n            {\n                { \"theModelName\", 42 }\n            };\n\n            TypeMatchModelBinder binder = new TypeMatchModelBinder();\n\n            // Act\n            bool retVal = binder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Equal(42, bindingContext.Model);\n            Assert.True(bindingContext.ModelState.ContainsKey(\"theModelName\"));\n        }\n\n        [Fact]\n        public void GetCompatibleValueProviderResult_ValueProviderResultRawValueIncorrect_ReturnsNull()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = GetBindingContext();\n            bindingContext.ValueProvider = new SimpleValueProvider\n            {\n                { \"theModelName\", \"not an integer\" }\n            };\n\n            // Act\n            ValueProviderResult vpResult = TypeMatchModelBinder.GetCompatibleValueProviderResult(bindingContext);\n\n            // Assert\n            Assert.Null(vpResult); // Raw value is the wrong type\n        }\n\n        [Fact]\n        public void GetCompatibleValueProviderResult_ValueProviderResultValid_ReturnsValueProviderResult()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = GetBindingContext();\n            bindingContext.ValueProvider = new SimpleValueProvider\n            {\n                { \"theModelName\", 42 }\n            };\n\n            // Act\n            ValueProviderResult vpResult = TypeMatchModelBinder.GetCompatibleValueProviderResult(bindingContext);\n\n            // Assert\n            Assert.NotNull(vpResult);\n        }\n\n        [Fact]\n        public void GetCompatibleValueProviderResult_ValueProviderReturnsNull_ReturnsNull()\n        {\n            // Arrange\n            ExtensibleModelBindingContext bindingContext = GetBindingContext();\n            bindingContext.ValueProvider = new SimpleValueProvider();\n\n            // Act\n            ValueProviderResult vpResult = TypeMatchModelBinder.GetCompatibleValueProviderResult(bindingContext);\n\n            // Assert\n            Assert.Null(vpResult); // No key matched\n        }\n\n        private static ExtensibleModelBindingContext GetBindingContext()\n        {\n            return GetBindingContext(typeof(int));\n        }\n\n        private static ExtensibleModelBindingContext GetBindingContext(Type modelType)\n        {\n            return new ExtensibleModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, modelType),\n                ModelName = \"theModelName\"\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/AcceptAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Linq;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class AcceptAttributeTest\n    {\n        [Fact]\n        public void DefaultIsEmpty()\n        {\n            Assert.True(String.IsNullOrEmpty(new AcceptAttribute().MimeTypes));\n        }\n\n        [Fact]\n        public void ClientRule()\n        {\n            // Arrange\n            var attribute = new AcceptAttribute { MimeTypes = \" text/html , application/javascript \" };\n            var provider = new Mock<ModelMetadataProvider>();\n            var metadata = new ModelMetadata(provider.Object, null, null, typeof(string), \"PropertyName\");\n\n            // Act\n            ModelClientValidationRule clientRule = attribute.GetClientValidationRules(metadata, null).Single();\n\n            // Assert\n            Assert.Equal(\"accept\", clientRule.ValidationType);\n            Assert.Equal(\"The PropertyName field only accepts files with one of the following content types: text/html, application/javascript.\", clientRule.ErrorMessage);\n            Assert.Single(clientRule.ValidationParameters);\n            Assert.Equal(\"text/html,application/javascript\", clientRule.ValidationParameters[\"mimetype\"]);\n        }\n\n        [Fact]\n        public void IsValidTests()\n        {\n            // Arrange\n            var attribute = new AcceptAttribute { MimeTypes = \" text/html , application/javascript \" };\n\n            // Act & Assert\n            Assert.True(attribute.IsValid(null)); // Optional values are always valid\n            Assert.True(attribute.IsValid(\"text/html\"));\n            Assert.True(attribute.IsValid(\"application/javascript\"));\n            Assert.False(attribute.IsValid(\"text/css\"));\n            Assert.False(attribute.IsValid(\"\\0text/html\")); // Illegal character\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/AjaxOnlyAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class AjaxOnlyAttributeTest\n    {\n        [Fact]\n        public void IsValidForRequestReturnsFalseIfHeaderNotPresent()\n        {\n            // Arrange\n            AjaxOnlyAttribute attr = new AjaxOnlyAttribute();\n            ControllerContext controllerContext = GetControllerContext(containsHeader: false);\n\n            // Act\n            bool isValid = attr.IsValidForRequest(controllerContext, null);\n\n            // Assert\n            Assert.False(isValid);\n        }\n\n        [Fact]\n        public void IsValidForRequestReturnsTrueIfHeaderIsPresent()\n        {\n            // Arrange\n            AjaxOnlyAttribute attr = new AjaxOnlyAttribute();\n            ControllerContext controllerContext = GetControllerContext(containsHeader: true);\n\n            // Act\n            bool isValid = attr.IsValidForRequest(controllerContext, null);\n\n            // Assert\n            Assert.True(isValid);\n        }\n\n        [Fact]\n        public void IsValidForRequestThrowsIfControllerContextIsNull()\n        {\n            // Arrange\n            AjaxOnlyAttribute attr = new AjaxOnlyAttribute();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { attr.IsValidForRequest(null, null); }, \"controllerContext\");\n        }\n\n        private static ControllerContext GetControllerContext(bool containsHeader)\n        {\n            Mock<ControllerContext> mockContext = new Mock<ControllerContext>();\n\n            NameValueCollection nvc = new NameValueCollection();\n            if (containsHeader)\n            {\n                nvc[\"X-Requested-With\"] = \"XMLHttpRequest\";\n            }\n\n            mockContext.Setup(o => o.HttpContext.Request.Headers).Returns(nvc);\n            mockContext.Setup(o => o.HttpContext.Request[\"X-Requested-With\"]).Returns(\"XMLHttpRequest\"); // always assume the request contains this, e.g. as a form value\n\n            return mockContext.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/AreaHelpersTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class AreaHelpersTest\n    {\n        [Fact]\n        public void GetAreaNameFromAreaRouteCollectionRoute()\n        {\n            // Arrange\n            RouteCollection routes = new RouteCollection();\n            AreaRegistrationContext context = new AreaRegistrationContext(\"area_name\", routes);\n            Route route = context.MapRoute(null, \"the_url\");\n\n            // Act\n            string areaName = AreaHelpers.GetAreaName(route);\n\n            // Assert\n            Assert.Equal(\"area_name\", areaName);\n        }\n\n        [Fact]\n        public void GetAreaNameFromIAreaAssociatedItem()\n        {\n            // Arrange\n            CustomRouteWithArea route = new CustomRouteWithArea();\n\n            // Act\n            string areaName = AreaHelpers.GetAreaName(route);\n\n            // Assert\n            Assert.Equal(\"area_name\", areaName);\n        }\n\n        [Fact]\n        public void GetAreaNameFromRouteData()\n        {\n            // Arrange\n            RouteData routeData = new RouteData();\n            routeData.DataTokens[\"area\"] = \"area_name\";\n\n            // Act\n            string areaName = AreaHelpers.GetAreaName(routeData);\n\n            // Assert\n            Assert.Equal(\"area_name\", areaName);\n        }\n\n        [Fact]\n        public void GetAreaNameFromRouteDataFallsBackToRoute()\n        {\n            // Arrange\n            RouteCollection routes = new RouteCollection();\n            AreaRegistrationContext context = new AreaRegistrationContext(\"area_name\", routes);\n            Route route = context.MapRoute(null, \"the_url\");\n            RouteData routeData = new RouteData(route, new MvcRouteHandler());\n\n            // Act\n            string areaName = AreaHelpers.GetAreaName(routeData);\n\n            // Assert\n            Assert.Equal(\"area_name\", areaName);\n        }\n\n        [Fact]\n        public void GetAreaNameReturnsNullIfRouteNotAreaAware()\n        {\n            // Arrange\n            Route route = new Route(\"the_url\", new MvcRouteHandler());\n\n            // Act\n            string areaName = AreaHelpers.GetAreaName(route);\n\n            // Assert\n            Assert.Null(areaName);\n        }\n\n        private class CustomRouteWithArea : RouteBase, IRouteWithArea\n        {\n            public string Area\n            {\n                get { return \"area_name\"; }\n            }\n\n            public override RouteData GetRouteData(HttpContextBase httpContext)\n            {\n                throw new NotImplementedException();\n            }\n\n            public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/AsyncManagerExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Threading;\nusing System.Web.Mvc.Async;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class AsyncManagerExtensionsTest\n    {\n        [Fact]\n        public void RegisterTask_AsynchronousCompletion()\n        {\n            // Arrange\n            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();\n            AsyncManager asyncManager = new AsyncManager(syncContext);\n            bool endDelegateWasCalled = false;\n\n            using (ManualResetEvent waitHandle = new ManualResetEvent(false /* initialState */))\n            {\n                Func<AsyncCallback, IAsyncResult> beginDelegate = callback =>\n                {\n                    Assert.Equal(1, asyncManager.OutstandingOperations.Count);\n                    MockAsyncResult asyncResult = new MockAsyncResult(false /* completedSynchronously */);\n                    ThreadPool.QueueUserWorkItem(_ =>\n                    {\n                        Assert.Equal(1, asyncManager.OutstandingOperations.Count);\n                        callback(asyncResult);\n                        waitHandle.Set();\n                    });\n                    return asyncResult;\n                };\n                Action<IAsyncResult> endDelegate = delegate { endDelegateWasCalled = true; };\n\n                // Act\n                asyncManager.RegisterTask(beginDelegate, endDelegate);\n                waitHandle.WaitOne();\n\n                // Assert\n                Assert.True(endDelegateWasCalled);\n                Assert.True(syncContext.SendWasCalled);\n                Assert.Equal(0, asyncManager.OutstandingOperations.Count);\n            }\n        }\n\n        [Fact]\n        public void RegisterTask_AsynchronousCompletion_SwallowsExceptionsThrownByEndDelegate()\n        {\n            // Arrange\n            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();\n            AsyncManager asyncManager = new AsyncManager(syncContext);\n            bool endDelegateWasCalled = false;\n\n            using (ManualResetEvent waitHandle = new ManualResetEvent(false /* initialState */))\n            {\n                Func<AsyncCallback, IAsyncResult> beginDelegate = callback =>\n                {\n                    MockAsyncResult asyncResult = new MockAsyncResult(false /* completedSynchronously */);\n                    ThreadPool.QueueUserWorkItem(_ =>\n                    {\n                        callback(asyncResult);\n                        waitHandle.Set();\n                    });\n                    return asyncResult;\n                };\n                Action<IAsyncResult> endDelegate = delegate\n                {\n                    endDelegateWasCalled = true;\n                    throw new Exception(\"This is a sample exception.\");\n                };\n\n                // Act\n                asyncManager.RegisterTask(beginDelegate, endDelegate);\n                waitHandle.WaitOne();\n\n                // Assert\n                Assert.True(endDelegateWasCalled);\n                Assert.Equal(0, asyncManager.OutstandingOperations.Count);\n            }\n        }\n\n        [Fact]\n        public void RegisterTask_ResetsOutstandingOperationCountIfBeginMethodThrows()\n        {\n            // Arrange\n            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();\n            AsyncManager asyncManager = new AsyncManager(syncContext);\n\n            Func<AsyncCallback, IAsyncResult> beginDelegate = cb => { throw new InvalidOperationException(\"BeginDelegate throws.\"); };\n            Action<IAsyncResult> endDelegate = ar => { Assert.True(false, \"This should never be called.\"); };\n\n            // Act & assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { asyncManager.RegisterTask(beginDelegate, endDelegate); }, \"BeginDelegate throws.\");\n\n            Assert.Equal(0, asyncManager.OutstandingOperations.Count);\n        }\n\n        [Fact]\n        public void RegisterTask_SynchronousCompletion()\n        {\n            // Arrange\n            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();\n            AsyncManager asyncManager = new AsyncManager(syncContext);\n            bool endDelegateWasCalled = false;\n\n            Func<AsyncCallback, IAsyncResult> beginDelegate = callback =>\n            {\n                Assert.Equal(1, asyncManager.OutstandingOperations.Count);\n                MockAsyncResult asyncResult = new MockAsyncResult(true /* completedSynchronously */);\n                callback(asyncResult);\n                return asyncResult;\n            };\n            Action<IAsyncResult> endDelegate = delegate { endDelegateWasCalled = true; };\n\n            // Act\n            asyncManager.RegisterTask(beginDelegate, endDelegate);\n\n            // Assert\n            Assert.True(endDelegateWasCalled);\n            Assert.False(syncContext.SendWasCalled);\n            Assert.Equal(0, asyncManager.OutstandingOperations.Count);\n        }\n\n        [Fact]\n        public void RegisterTask_ThrowsIfAsyncManagerIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { AsyncManagerExtensions.RegisterTask(null, _ => null, _ => { }); }, \"asyncManager\");\n        }\n\n        [Fact]\n        public void RegisterTask_ThrowsIfBeginDelegateIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new AsyncManager().RegisterTask(null, _ => { }); }, \"beginDelegate\");\n        }\n\n        [Fact]\n        public void RegisterTask_ThrowsIfEndDelegateIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new AsyncManager().RegisterTask(_ => null, null); }, \"endDelegate\");\n        }\n\n        private class SimpleSynchronizationContext : SynchronizationContext\n        {\n            public bool SendWasCalled;\n\n            public override void Send(SendOrPostCallback d, object state)\n            {\n                SendWasCalled = true;\n                d(state);\n            }\n        }\n\n        private class MockAsyncResult : IAsyncResult\n        {\n            private readonly bool _completedSynchronously;\n\n            public MockAsyncResult(bool completedSynchronously)\n            {\n                _completedSynchronously = completedSynchronously;\n            }\n\n            public object AsyncState\n            {\n                get { throw new NotImplementedException(); }\n            }\n\n            public WaitHandle AsyncWaitHandle\n            {\n                get { throw new NotImplementedException(); }\n            }\n\n            public bool CompletedSynchronously\n            {\n                get { return _completedSynchronously; }\n            }\n\n            public bool IsCompleted\n            {\n                get { throw new NotImplementedException(); }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/ButtonTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class ButtonTest\n    {\n        [Fact]\n        public void ButtonWithNullNameThrowsArgumentNullException()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            Assert.ThrowsArgumentNull(() => html.Button(null, \"text\", HtmlButtonType.Button), \"name\");\n        }\n\n        [Fact]\n        public void ButtonRendersBaseAttributes()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            MvcHtmlString result = html.Button(\"nameAttr\", \"buttonText\", HtmlButtonType.Reset, \"onclickAttr\");\n            Assert.Equal(\"<button name=\\\"nameAttr\\\" onclick=\\\"onclickAttr\\\" type=\\\"reset\\\">buttonText</button>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void ButtonWithoutOnClickDoesNotRenderOnclickAttribute()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            MvcHtmlString result = html.Button(\"nameAttr\", \"buttonText\", HtmlButtonType.Reset);\n            Assert.Equal(\"<button name=\\\"nameAttr\\\" type=\\\"reset\\\">buttonText</button>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void ButtonAllowsInnerHtml()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            MvcHtmlString result = html.Button(\"nameAttr\", \"<img src=\\\"puppy.jpg\\\" />\", HtmlButtonType.Submit, \"onclickAttr\");\n            Assert.Equal(\"<button name=\\\"nameAttr\\\" onclick=\\\"onclickAttr\\\" type=\\\"submit\\\"><img src=\\\"puppy.jpg\\\" /></button>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void ButtonRendersExplicitAttributes()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            MvcHtmlString result = html.Button(\"nameAttr\", \"buttonText\", HtmlButtonType.Reset, \"onclickAttr\", new { title = \"the-title\" });\n            Assert.Equal(\"<button name=\\\"nameAttr\\\" onclick=\\\"onclickAttr\\\" title=\\\"the-title\\\" type=\\\"reset\\\">buttonText</button>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void ButtonRendersExplicitAttributesWithUnderscores()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            MvcHtmlString result = html.Button(\"nameAttr\", \"buttonText\", HtmlButtonType.Reset, \"onclickAttr\", new { foo_bar = \"baz\" });\n            Assert.Equal(\"<button foo-bar=\\\"baz\\\" name=\\\"nameAttr\\\" onclick=\\\"onclickAttr\\\" type=\\\"reset\\\">buttonText</button>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void ButtonRendersExplicitDictionaryAttributes()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            MvcHtmlString result = html.Button(\"nameAttr\", \"buttonText\", HtmlButtonType.Button, \"onclickAttr\", new RouteValueDictionary(new { title = \"the-title\" }));\n            Assert.Equal(\"<button name=\\\"nameAttr\\\" onclick=\\\"onclickAttr\\\" title=\\\"the-title\\\" type=\\\"button\\\">buttonText</button>\", result.ToHtmlString());\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/ContentTypeAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class ContentTypeAttributeTest\n    {\n        [Fact]\n        public void ContentTypeSetInCtor()\n        {\n            var attr = new ContentTypeAttribute(\"text/html\");\n            Assert.Equal(\"text/html\", attr.ContentType);\n        }\n\n        [Fact]\n        public void ContentTypeCtorThrowsArgumentExceptionWhenContentTypeIsNull()\n        {\n            Assert.ThrowsArgumentNullOrEmpty(() => new ContentTypeAttribute(null), \"contentType\");\n        }\n\n        [Fact]\n        public void ExecuteResultSetsContentType()\n        {\n            var mockHttpResponse = new Mock<HttpResponseBase>();\n            var mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(c => c.Response).Returns(mockHttpResponse.Object);\n\n            var mockController = new Mock<Controller>();\n            var controllerContext = new ControllerContext(new RequestContext(mockHttpContext.Object, new RouteData()), mockController.Object);\n            var result = new ContentResult { Content = \"blah blah\" };\n            var filterContext = new ResultExecutingContext(controllerContext, result);\n\n            var filter = new ContentTypeAttribute(\"text/xml\");\n            filter.OnResultExecuting(filterContext);\n\n            mockHttpResponse.VerifySet(r => r.ContentType = \"text/xml\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/ControllerExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class ControllerExtensionsTest\n    {\n        private const string AppPathModifier = MvcHelper.AppPathModifier;\n\n        [Fact]\n        public void RedirectToAction_DifferentController()\n        {\n            // Act\n            RedirectToRouteResult result = new SampleController().RedirectToAction<DifferentController>(x => x.SomeOtherMethod(84));\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Equal(\"\", result.RouteName);\n            Assert.Equal(3, result.RouteValues.Count);\n            Assert.Equal(\"Different\", result.RouteValues[\"controller\"]);\n            Assert.Equal(\"SomeOtherMethod\", result.RouteValues[\"action\"]);\n            Assert.Equal(84, result.RouteValues[\"someOtherParameter\"]);\n        }\n\n        [Fact]\n        public void RedirectToAction_SameController()\n        {\n            // Act\n            RedirectToRouteResult result = new SampleController().RedirectToAction(x => x.SomeMethod(42));\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Equal(\"\", result.RouteName);\n            Assert.Equal(3, result.RouteValues.Count);\n            Assert.Equal(\"Sample\", result.RouteValues[\"controller\"]);\n            Assert.Equal(\"SomeMethod\", result.RouteValues[\"action\"]);\n            Assert.Equal(42, result.RouteValues[\"someParameter\"]);\n        }\n\n        [Fact]\n        public void RedirectToAction_ThrowsIfControllerIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { ((SampleController)null).RedirectToAction(x => x.SomeMethod(42)); }, \"controller\");\n        }\n\n        private class SampleController : Controller\n        {\n            public ActionResult SomeMethod(int someParameter)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class DifferentController : Controller\n        {\n            public ActionResult SomeOtherMethod(int someOtherParameter)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/CookieValueProviderFactoryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Web;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class CookieValueProviderFactoryTest\n    {\n        [Fact]\n        public void GetValueProvider()\n        {\n            // Arrange\n            HttpCookieCollection cookies = new HttpCookieCollection\n            {\n                new HttpCookie(\"foo\", \"fooValue\"),\n                new HttpCookie(\"bar.baz\", \"barBazValue\"),\n                new HttpCookie(\"\", \"emptyValue\"),\n                new HttpCookie(null, \"nullValue\")\n            };\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(o => o.HttpContext.Request.Cookies).Returns(cookies);\n\n            CookieValueProviderFactory factory = new CookieValueProviderFactory();\n\n            // Act\n            IValueProvider provider = factory.GetValueProvider(mockControllerContext.Object);\n\n            // Assert\n            Assert.Null(provider.GetValue(\"\"));\n            Assert.True(provider.ContainsPrefix(\"bar\"));\n            Assert.Equal(\"fooValue\", provider.GetValue(\"foo\").AttemptedValue);\n            Assert.Equal(CultureInfo.InvariantCulture, provider.GetValue(\"foo\").Culture);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/CopyAsyncParametersAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class CopyAsyncParametersAttributeTest\n    {\n        [Fact]\n        public void OnActionExecuting_CopiesParametersIfControllerIsAsync()\n        {\n            // Arrange\n            CopyAsyncParametersAttribute attr = new CopyAsyncParametersAttribute();\n            SampleAsyncController controller = new SampleAsyncController();\n\n            ActionExecutingContext filterContext = new ActionExecutingContext\n            {\n                ActionParameters = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase),\n                Controller = controller\n            };\n            filterContext.ActionParameters[\"foo\"] = \"fooAction\";\n            filterContext.ActionParameters[\"bar\"] = \"barAction\";\n            controller.AsyncManager.Parameters[\"bar\"] = \"barAsync\";\n            controller.AsyncManager.Parameters[\"baz\"] = \"bazAsync\";\n\n            // Act\n            attr.OnActionExecuting(filterContext);\n\n            // Assert\n            Assert.Equal(\"fooAction\", controller.AsyncManager.Parameters[\"foo\"]);\n            Assert.Equal(\"barAction\", controller.AsyncManager.Parameters[\"bar\"]);\n            Assert.Equal(\"bazAsync\", controller.AsyncManager.Parameters[\"baz\"]);\n        }\n\n        [Fact]\n        public void OnActionExecuting_DoesNothingIfControllerNotAsync()\n        {\n            // Arrange\n            CopyAsyncParametersAttribute attr = new CopyAsyncParametersAttribute();\n            SampleSyncController controller = new SampleSyncController();\n\n            ActionExecutingContext filterContext = new ActionExecutingContext\n            {\n                ActionParameters = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase),\n                Controller = controller\n            };\n            filterContext.ActionParameters[\"foo\"] = \"originalFoo\";\n            filterContext.ActionParameters[\"bar\"] = \"originalBar\";\n\n            // Act\n            attr.OnActionExecuting(filterContext);\n\n            // Assert\n            // If we got this far without crashing, life is good :)\n        }\n\n        [Fact]\n        public void OnActionExecuting_ThrowsIfFilterContextIsNull()\n        {\n            // Arrange\n            CopyAsyncParametersAttribute attr = new CopyAsyncParametersAttribute();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { attr.OnActionExecuting(null); }, \"filterContext\");\n        }\n\n        private class SampleSyncController : Controller\n        {\n        }\n\n        private class SampleAsyncController : AsyncController\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/CreditCardAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class CreditCardAttributeTest\n    {\n        [Fact]\n        public void ClientRule()\n        {\n            // Arrange\n            var attribute = new CreditCardAttribute();\n            var provider = new Mock<ModelMetadataProvider>();\n            var metadata = new ModelMetadata(provider.Object, null, null, typeof(string), \"PropertyName\");\n\n            // Act\n            ModelClientValidationRule clientRule = attribute.GetClientValidationRules(metadata, null).Single();\n\n            // Assert\n            Assert.Equal(\"creditcard\", clientRule.ValidationType);\n            Assert.Equal(\"The PropertyName field is not a valid credit card number.\", clientRule.ErrorMessage);\n            Assert.Empty(clientRule.ValidationParameters);\n        }\n\n        [Fact]\n        public void IsValidTests()\n        {\n            // Arrange\n            var attribute = new CreditCardAttribute();\n\n            // Act & Assert\n            Assert.True(attribute.IsValid(null)); // Optional values are always valid\n            Assert.True(attribute.IsValid(\"0000000000000000\")); // Simplest valid value\n            Assert.True(attribute.IsValid(\"1234567890123452\")); // Good checksum\n            Assert.True(attribute.IsValid(\"1234-5678-9012-3452\")); // Good checksum, with dashes\n            Assert.False(attribute.IsValid(\"0000000000000001\")); // Bad checksum\n            Assert.False(attribute.IsValid(0)); // Non-string\n            Assert.False(attribute.IsValid(\"000%000000000001\")); // Non-digit\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/CssExtensionsTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class CssExtensionsTests\n    {\n        [Fact]\n        public void CssWithoutFileThrowsArgumentNullException()\n        {\n            // Arrange\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n\n            // Assert\n            Assert.ThrowsArgumentNullOrEmpty(() => html.Css(null), \"file\");\n        }\n\n        [Fact]\n        public void CssWithRootedPathRendersProperElement()\n        {\n            // Arrange\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n\n            // Act\n            MvcHtmlString result = html.Css(\"~/Correct/Path.css\");\n\n            // Assert\n            Assert.Equal(\"<link href=\\\"/Correct/Path.css\\\" rel=\\\"stylesheet\\\" type=\\\"text/css\\\" />\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void CssWithRelativePathRendersProperElement()\n        {\n            // Arrange\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n\n            // Act\n            MvcHtmlString result = html.Css(\"../../Correct/Path.css\");\n\n            // Assert\n            Assert.Equal(\"<link href=\\\"../../Correct/Path.css\\\" rel=\\\"stylesheet\\\" type=\\\"text/css\\\" />\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void CssWithRelativeCurrentPathRendersProperElement()\n        {\n            // Arrange\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n\n            // Act\n            MvcHtmlString result = html.Css(\"/Correct/Path.css\");\n\n            // Assert\n            Assert.Equal(\"<link href=\\\"/Correct/Path.css\\\" rel=\\\"stylesheet\\\" type=\\\"text/css\\\" />\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void CssWithContentRelativePathRendersProperElement()\n        {\n            // Arrange\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n\n            // Act\n            MvcHtmlString result = html.Css(\"Correct/Path.css\");\n\n            // Assert\n            Assert.Equal(\"<link href=\\\"/Content/Correct/Path.css\\\" rel=\\\"stylesheet\\\" type=\\\"text/css\\\" />\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void CssWithNullMediaTypeRendersProperElement()\n        {\n            // Arrange\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n\n            // Act\n            MvcHtmlString result = html.Css(\"Correct/Path.css\", null);\n\n            // Assert\n            Assert.Equal(\"<link href=\\\"/Content/Correct/Path.css\\\" rel=\\\"stylesheet\\\" type=\\\"text/css\\\" />\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void CssWithEmptyMediaTypeRendersProperElement()\n        {\n            // Arrange\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n\n            // Act\n            MvcHtmlString result = html.Css(\"Correct/Path.css\", String.Empty);\n\n            // Assert\n            Assert.Equal(\"<link href=\\\"/Content/Correct/Path.css\\\" media=\\\"\\\" rel=\\\"stylesheet\\\" type=\\\"text/css\\\" />\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void CssWithMediaTypeRendersProperElement()\n        {\n            // Arrange\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n\n            // Act\n            MvcHtmlString result = html.Css(\"Correct/Path.css\", \"Print\");\n\n            // Assert\n            Assert.Equal(\"<link href=\\\"/Content/Correct/Path.css\\\" media=\\\"Print\\\" rel=\\\"stylesheet\\\" type=\\\"text/css\\\" />\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void CssWithUrlRendersProperElement()\n        {\n            // Arrange\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n\n            // Act\n            MvcHtmlString result = html.Css(\"http://ajax.Correct.com/Path.js\");\n\n            // Assert\n            Assert.Equal(\"<link href=\\\"http://ajax.Correct.com/Path.js\\\" rel=\\\"stylesheet\\\" type=\\\"text/css\\\" />\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void CssWithSecureUrlRendersProperElement()\n        {\n            // Arrange\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n\n            // Act\n            MvcHtmlString result = html.Css(\"https://ajax.Correct.com/Path.js\");\n\n            // Assert\n            Assert.Equal(\"<link href=\\\"https://ajax.Correct.com/Path.js\\\" rel=\\\"stylesheet\\\" type=\\\"text/css\\\" />\", result.ToHtmlString());\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/DeserializeAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Runtime.Serialization;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\nusing Moq;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class DeserializeAttributeTest\n    {\n        [Fact]\n        public void BinderReturnsDeserializedValue()\n        {\n            // Arrange\n            Mock<MvcSerializer> mockSerializer = new Mock<MvcSerializer>();\n            mockSerializer.Setup(o => o.Deserialize(\"some-value\")).Returns(42);\n            DeserializeAttribute attr = new DeserializeAttribute() { Serializer = mockSerializer.Object };\n\n            IModelBinder binder = attr.GetBinder();\n            ModelBindingContext mbContext = new ModelBindingContext\n            {\n                ModelName = \"someKey\",\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"someKey\", \"some-value\" }\n                }\n            };\n\n            // Act\n            object retVal = binder.BindModel(null, mbContext);\n\n            // Assert\n            Assert.Equal(42, retVal);\n        }\n\n        [Fact]\n        public void BinderReturnsNullIfValueProviderDoesNotContainKey()\n        {\n            // Arrange\n            DeserializeAttribute attr = new DeserializeAttribute();\n            IModelBinder binder = attr.GetBinder();\n            ModelBindingContext mbContext = new ModelBindingContext\n            {\n                ModelName = \"someKey\",\n                ValueProvider = new SimpleValueProvider()\n            };\n\n            // Act\n            object retVal = binder.BindModel(null, mbContext);\n\n            // Assert\n            Assert.Null(retVal);\n        }\n\n        [Fact]\n        public void BinderThrowsIfBindingContextIsNull()\n        {\n            // Arrange\n            DeserializeAttribute attr = new DeserializeAttribute();\n            IModelBinder binder = attr.GetBinder();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { binder.BindModel(null, null); }, \"bindingContext\");\n        }\n\n        [Fact]\n        public void BinderThrowsIfDataCorrupt()\n        {\n            // Arrange\n            Mock<MvcSerializer> mockSerializer = new Mock<MvcSerializer>();\n            mockSerializer.Setup(o => o.Deserialize(It.IsAny<string>())).Throws(new SerializationException());\n            DeserializeAttribute attr = new DeserializeAttribute { Serializer = mockSerializer.Object };\n\n            IModelBinder binder = attr.GetBinder();\n            ModelBindingContext mbContext = new ModelBindingContext\n            {\n                ModelName = \"someKey\",\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"someKey\", \"This data is corrupted.\" }\n                }\n            };\n\n            // Act & assert\n            Exception exception = Assert.Throws<SerializationException>(\n                delegate { binder.BindModel(null, mbContext); });\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/DynamicReflectionObjectTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class DynamicReflectionObjectTest\n    {\n        [Fact]\n        public void NoPropertiesThrows()\n        {\n            // Arrange\n            dynamic dro = DynamicReflectionObject.Wrap(new { });\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => dro.baz,\n                \"The property baz doesn't exist. There are no public properties on this object.\");\n        }\n\n        [Fact]\n        public void UnknownPropertyThrows()\n        {\n            // Arrange\n            dynamic dro = DynamicReflectionObject.Wrap(new { foo = 3.4, biff = \"Two\", bar = 1 });\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => dro.baz,\n                \"The property baz doesn't exist. Supported properties are: bar, biff, foo.\");\n        }\n\n        [Fact]\n        public void CanAccessProperties()\n        {\n            // Arrange\n            dynamic dro = DynamicReflectionObject.Wrap(new { foo = \"Hello world!\", bar = 42 });\n\n            // Act & Assert\n            Assert.Equal(\"Hello world!\", dro.foo);\n            Assert.Equal(42, dro.bar);\n        }\n\n        [Fact]\n        public void CanAccessNestedAnonymousProperties()\n        {\n            // Arrange\n            dynamic dro = DynamicReflectionObject.Wrap(new { foo = new { bar = \"Hello world!\" } });\n\n            // Act & Assert\n            Assert.Equal(\"Hello world!\", dro.foo.bar);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/DynamicViewDataDictionaryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class DynamicViewDataDictionaryTest\n    {\n        // Property-style accessor\n\n        [Fact]\n        public void Property_UnknownItemReturnsEmptyString()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary();\n            dynamic dvdd = DynamicViewDataDictionary.Wrap(vdd);\n\n            // Act\n            object result = dvdd.Foo;\n\n            // Assert\n            Assert.Equal(String.Empty, result);\n        }\n\n        [Fact]\n        public void Property_CanAccessViewDataValues()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary();\n            vdd[\"Foo\"] = \"Value for Foo\";\n            dynamic dvdd = DynamicViewDataDictionary.Wrap(vdd);\n\n            // Act\n            object result = dvdd.Foo;\n\n            // Assert\n            Assert.Equal(\"Value for Foo\", result);\n        }\n\n        [Fact]\n        public void Property_CanAccessModelProperties()\n        {\n            ViewDataDictionary vdd = new ViewDataDictionary(new { Foo = \"Value for Foo\" });\n            dynamic dvdd = DynamicViewDataDictionary.Wrap(vdd);\n\n            // Act\n            object result = dvdd.Foo;\n\n            // Assert\n            Assert.Equal(\"Value for Foo\", result);\n        }\n\n        // Index-style accessor\n\n        [Fact]\n        public void Indexer_GuardClauses()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary();\n            dynamic dvdd = DynamicViewDataDictionary.Wrap(vdd);\n\n            // Act & Assert\n            Assert.Throws<ArgumentException>(\n                () => { var x = dvdd[\"foo\", \"bar\"]; },\n                \"DynamicViewDataDictionary only supports single indexers.\");\n\n            Assert.Throws<ArgumentException>(\n                () => { var x = dvdd[42]; },\n                \"DynamicViewDataDictionary only supports string-based indexers.\");\n        }\n\n        [Fact]\n        public void Indexer_UnknownItemReturnsEmptyString()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary();\n            dynamic dvdd = DynamicViewDataDictionary.Wrap(vdd);\n\n            // Act\n            object result = dvdd[\"Foo\"];\n\n            // Assert\n            Assert.Equal(String.Empty, result);\n        }\n\n        [Fact]\n        public void Indexer_CanAccessViewDataValues()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary();\n            vdd[\"Foo\"] = \"Value for Foo\";\n            dynamic dvdd = DynamicViewDataDictionary.Wrap(vdd);\n\n            // Act\n            object result = dvdd[\"Foo\"];\n\n            // Assert\n            Assert.Equal(\"Value for Foo\", result);\n        }\n\n        [Fact]\n        public void Indexer_CanAccessModelProperties()\n        {\n            ViewDataDictionary vdd = new ViewDataDictionary(new { Foo = \"Value for Foo\" });\n            dynamic dvdd = DynamicViewDataDictionary.Wrap(vdd);\n\n            // Act\n            object result = dvdd[\"Foo\"];\n\n            // Assert\n            Assert.Equal(\"Value for Foo\", result);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/DynamicViewPageTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class DynamicViewPageTest\n    {\n        // DynamicViewPage\n\n        [Fact]\n        public void AnonymousObjectsAreWrapped()\n        {\n            // Arrange\n            DynamicViewPage page = new DynamicViewPage();\n            page.ViewData.Model = new { foo = \"Hello world!\" };\n\n            // Act & Assert\n            Assert.Equal(\"Microsoft.Web.Mvc.DynamicReflectionObject\", page.Model.GetType().FullName);\n        }\n\n        [Fact]\n        public void NonAnonymousObjectsAreNotWrapped()\n        {\n            // Arrange\n            DynamicViewPage page = new DynamicViewPage();\n            page.ViewData.Model = \"Hello world!\";\n\n            // Act & Assert\n            Assert.Equal(typeof(string), page.Model.GetType());\n        }\n\n        [Fact]\n        public void ViewDataDictionaryIsWrapped()\n        {\n            // Arrange\n            DynamicViewPage page = new DynamicViewPage();\n\n            // Act & Assert\n            Assert.Equal(\"Microsoft.Web.Mvc.DynamicViewDataDictionary\", page.ViewData.GetType().FullName);\n        }\n\n        // DynamicViewPage<T>\n\n        [Fact]\n        public void Generic_ViewDataDictionaryIsWrapped()\n        {\n            // Arrange\n            DynamicViewPage<object> page = new DynamicViewPage<object>();\n\n            // Act & Assert\n            Assert.Equal(\"Microsoft.Web.Mvc.DynamicViewDataDictionary\", page.ViewData.GetType().FullName);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/ElementalValueProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Globalization;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class ElementalValueProviderTest\n    {\n        [Fact]\n        public void ContainsPrefix()\n        {\n            // Arrange\n            ElementalValueProvider valueProvider = new ElementalValueProvider(\"foo\", 42, null);\n\n            // Act & assert\n            Assert.True(valueProvider.ContainsPrefix(\"foo\"));\n            Assert.False(valueProvider.ContainsPrefix(\"bar\"));\n        }\n\n        [Fact]\n        public void GetValue_NameDoesNotMatch_ReturnsNull()\n        {\n            // Arrange\n            CultureInfo culture = CultureInfo.GetCultureInfo(\"fr-FR\");\n            DateTime rawValue = new DateTime(2001, 1, 2);\n            ElementalValueProvider valueProvider = new ElementalValueProvider(\"foo\", rawValue, culture);\n\n            // Act\n            ValueProviderResult vpResult = valueProvider.GetValue(\"bar\");\n\n            // Assert\n            Assert.Null(vpResult);\n        }\n\n        [Fact]\n        public void GetValue_NameMatches_ReturnsValueProviderResult()\n        {\n            // Arrange\n            CultureInfo culture = CultureInfo.GetCultureInfo(\"fr-FR\");\n            DateTime rawValue = new DateTime(2001, 1, 2);\n            ElementalValueProvider valueProvider = new ElementalValueProvider(\"foo\", rawValue, culture);\n\n            // Act\n            ValueProviderResult vpResult = valueProvider.GetValue(\"FOO\");\n\n            // Assert\n            Assert.NotNull(vpResult);\n            Assert.Equal(rawValue, vpResult.RawValue);\n            Assert.Equal(\"02/01/2001 00:00:00\", vpResult.AttemptedValue);\n            Assert.Equal(culture, vpResult.Culture);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/EmailAddressAttribueTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class EmailAddressAttribueTest\n    {\n        [Fact]\n        public void ClientRule()\n        {\n            // Arrange\n            var attribute = new EmailAddressAttribute();\n            var provider = new Mock<ModelMetadataProvider>();\n            var metadata = new ModelMetadata(provider.Object, null, null, typeof(string), \"PropertyName\");\n\n            // Act\n            ModelClientValidationRule clientRule = attribute.GetClientValidationRules(metadata, null).Single();\n\n            // Assert\n            Assert.Equal(\"email\", clientRule.ValidationType);\n            Assert.Equal(\"The PropertyName field is not a valid e-mail address.\", clientRule.ErrorMessage);\n            Assert.Empty(clientRule.ValidationParameters);\n        }\n\n        [Fact]\n        public void IsValidTests()\n        {\n            // Arrange\n            var attribute = new EmailAddressAttribute();\n\n            // Act & Assert\n            Assert.True(attribute.IsValid(null)); // Optional values are always valid\n            Assert.True(attribute.IsValid(\"joe@contoso.com\"));\n            Assert.True(attribute.IsValid(\"joe%fred@contoso.com\"));\n            Assert.False(attribute.IsValid(\"joe\"));\n            Assert.False(attribute.IsValid(\"joe@\"));\n            Assert.False(attribute.IsValid(\"joe@contoso\"));\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/ExpressionHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Linq.Expressions;\nusing System.Web.Mvc;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\nusing ExpressionHelper = Microsoft.Web.Mvc.Internal.ExpressionHelper;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class ExpressionHelperTest\n    {\n        [Fact]\n        public void BuildRouteValueDictionary_TargetsAsynchronousAsyncMethod_StripsSuffix()\n        {\n            // Arrange\n            Expression<Action<TestAsyncController>> expr = (c => c.AsynchronousAsync());\n\n            // Act\n            RouteValueDictionary rvd = ExpressionHelper.GetRouteValuesFromExpression(expr);\n\n            // Assert\n            Assert.Equal(\"Asynchronous\", rvd[\"action\"]);\n            Assert.Equal(\"TestAsync\", rvd[\"controller\"]);\n            Assert.False(rvd.ContainsKey(\"area\"));\n        }\n\n        [Fact]\n        public void BuildRouteValueDictionary_TargetsAsynchronousCompletedMethod_Throws()\n        {\n            // Arrange\n            Expression<Action<TestAsyncController>> expr = (c => c.AsynchronousCompleted());\n\n            // Act & assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { ExpressionHelper.GetRouteValuesFromExpression(expr); },\n                @\"The method 'AsynchronousCompleted' is an asynchronous completion method and cannot be called directly.\");\n        }\n\n        [Fact]\n        public void BuildRouteValueDictionary_TargetsControllerWithAreaAttribute_AddsAreaName()\n        {\n            // Arrange\n            Expression<Action<ControllerWithAreaController>> expr = c => c.Index();\n\n            // Act\n            RouteValueDictionary rvd = ExpressionHelper.GetRouteValuesFromExpression(expr);\n\n            // Assert\n            Assert.Equal(\"Index\", rvd[\"action\"]);\n            Assert.Equal(\"ControllerWithArea\", rvd[\"controller\"]);\n            Assert.Equal(\"the area name\", rvd[\"area\"]);\n        }\n\n        [Fact]\n        public void BuildRouteValueDictionary_TargetsNonActionMethod_Throws()\n        {\n            // Arrange\n            Expression<Action<TestController>> expr = (c => c.NotAnAction());\n\n            // Act & assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { ExpressionHelper.GetRouteValuesFromExpression(expr); },\n                @\"The method 'NotAnAction' is marked [NonAction] and cannot be called directly.\");\n        }\n\n        [Fact]\n        public void BuildRouteValueDictionary_TargetsRenamedMethod_UsesNewName()\n        {\n            // Arrange\n            Expression<Action<TestController>> expr = (c => c.Renamed());\n\n            // Act\n            RouteValueDictionary rvd = ExpressionHelper.GetRouteValuesFromExpression(expr);\n\n            // Assert\n            Assert.Equal(\"NewName\", rvd[\"action\"]);\n            Assert.Equal(\"Test\", rvd[\"controller\"]);\n            Assert.False(rvd.ContainsKey(\"area\"));\n        }\n\n        [Fact]\n        public void BuildRouteValueDictionary_TargetsSynchronousMethodOnAsyncController_ReturnsOriginalName()\n        {\n            // Arrange\n            Expression<Action<TestAsyncController>> expr = (c => c.Synchronous());\n\n            // Act\n            RouteValueDictionary rvd = ExpressionHelper.GetRouteValuesFromExpression(expr);\n\n            // Assert\n            Assert.Equal(\"Synchronous\", rvd[\"action\"]);\n            Assert.Equal(\"TestAsync\", rvd[\"controller\"]);\n            Assert.False(rvd.ContainsKey(\"area\"));\n        }\n\n        [Fact]\n        public void BuildRouteValueDictionaryWithNullExpressionThrowsArgumentNullException()\n        {\n            Assert.ThrowsArgumentNull(\n                () => ExpressionHelper.GetRouteValuesFromExpression<TestController>(null),\n                \"action\");\n        }\n\n        [Fact]\n        public void BuildRouteValueDictionaryWithNonMethodExpressionThrowsInvalidOperationException()\n        {\n            // Arrange\n            Expression<Action<TestController>> expression = c => new TestController();\n\n            // Act & Assert\n            Assert.Throws<ArgumentException>(\n                () => ExpressionHelper.GetRouteValuesFromExpression(expression),\n                \"Expression must be a method call.\" + Environment.NewLine\n              + \"Parameter name: action\");\n        }\n\n        [Fact]\n        public void BuildRouteValueDictionaryWithoutControllerSuffixThrowsInvalidOperationException()\n        {\n            // Arrange\n            Expression<Action<TestControllerNot>> index = (c => c.Index(123));\n\n            // Act & Assert\n            Assert.Throws<ArgumentException>(\n                () => ExpressionHelper.GetRouteValuesFromExpression(index),\n                \"Controller name must end in 'Controller'.\" + Environment.NewLine\n              + \"Parameter name: action\");\n        }\n\n        [Fact]\n        public void BuildRouteValueDictionaryWithControllerBaseClassThrowsInvalidOperationException()\n        {\n            // Arrange\n            Expression<Action<Controller>> index = (c => c.Dispose());\n\n            // Act & Assert\n            Assert.Throws<ArgumentException>(\n                () => ExpressionHelper.GetRouteValuesFromExpression(index),\n                \"Cannot route to class named 'Controller'.\" + Environment.NewLine\n              + \"Parameter name: action\");\n        }\n\n        [Fact]\n        public void BuildRouteValueDictionaryAddsControllerNameToDictionary()\n        {\n            // Arrange\n            Expression<Action<TestController>> index = (c => c.Index(123));\n\n            // Act\n            RouteValueDictionary rvd = ExpressionHelper.GetRouteValuesFromExpression(index);\n\n            // Assert\n            Assert.Equal(\"Test\", rvd[\"Controller\"]);\n        }\n\n        [Fact]\n        public void BuildRouteValueDictionaryFromExpressionReturnsCorrectDictionary()\n        {\n            // Arrange\n            Expression<Action<TestController>> index = (c => c.Index(123));\n\n            // Act\n            RouteValueDictionary rvd = ExpressionHelper.GetRouteValuesFromExpression(index);\n\n            // Assert\n            Assert.Equal(\"Test\", rvd[\"Controller\"]);\n            Assert.Equal(\"Index\", rvd[\"Action\"]);\n            Assert.Equal(123, rvd[\"page\"]);\n        }\n\n        [Fact]\n        public void BuildRouteValueDictionaryFromNonConstantExpressionReturnsCorrectDictionary()\n        {\n            // Arrange\n            Expression<Action<TestController>> index = (c => c.About(Foo));\n\n            // Act\n            RouteValueDictionary rvd = ExpressionHelper.GetRouteValuesFromExpression(index);\n\n            // Assert\n            Assert.Equal(\"Test\", rvd[\"Controller\"]);\n            Assert.Equal(\"About\", rvd[\"Action\"]);\n            Assert.Equal(\"FooValue\", rvd[\"s\"]);\n        }\n\n        [Fact]\n        public void GetInputNameFromPropertyExpressionReturnsPropertyName()\n        {\n            // Arrange\n            Expression<Func<TestModel, int>> expression = m => m.IntProperty;\n\n            // Act\n            string name = ExpressionHelper.GetInputName(expression);\n\n            // Assert\n            Assert.Equal(\"IntProperty\", name);\n        }\n\n        [Fact]\n        public void GetInputNameFromPropertyWithMethodCallExpressionReturnsPropertyName()\n        {\n            // Arrange\n            Expression<Func<TestModel, string>> expression = m => m.IntProperty.ToString();\n\n            // Act\n            string name = ExpressionHelper.GetInputName(expression);\n\n            // Assert\n            Assert.Equal(\"IntProperty\", name);\n        }\n\n        [Fact]\n        public void GetInputNameFromPropertyWithTwoMethodCallExpressionReturnsPropertyName()\n        {\n            // Arrange\n            Expression<Func<TestModel, string>> expression = m => m.IntProperty.ToString().ToUpper();\n\n            // Act\n            string name = ExpressionHelper.GetInputName(expression);\n\n            // Assert\n            Assert.Equal(\"IntProperty\", name);\n        }\n\n        [Fact]\n        public void GetInputNameFromExpressionWithTwoPropertiesUsesWholeExpression()\n        {\n            // Arrange\n            Expression<Func<TestModel, int>> expression = m => m.StringProperty.Length;\n\n            // Act\n            string name = ExpressionHelper.GetInputName(expression);\n\n            // Assert\n            Assert.Equal(\"StringProperty.Length\", name);\n        }\n\n        public class TestController : Controller\n        {\n            public ActionResult Index(int page)\n            {\n                return null;\n            }\n\n            public string About(string s)\n            {\n                return \"The value is \" + s;\n            }\n\n            [ActionName(\"NewName\")]\n            public void Renamed()\n            {\n            }\n\n            [NonAction]\n            public void NotAnAction()\n            {\n            }\n        }\n\n        public class TestAsyncController : AsyncController\n        {\n            public void Synchronous()\n            {\n            }\n\n            public void AsynchronousAsync()\n            {\n            }\n\n            public void AsynchronousCompleted()\n            {\n            }\n        }\n\n        public string Foo\n        {\n            get { return \"FooValue\"; }\n        }\n\n        public class TestControllerNot : Controller\n        {\n            public ActionResult Index(int page)\n            {\n                return null;\n            }\n        }\n\n        [ActionLinkArea(\"the area name\")]\n        public class ControllerWithAreaController : Controller\n        {\n            public ActionResult Index()\n            {\n                return null;\n            }\n        }\n\n        public class TestModel\n        {\n            public int IntProperty { get; set; }\n            public string StringProperty { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/FileExtensionsAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class FileExtensionsAttributeTest\n    {\n        [Fact]\n        public void DefaultExtensions()\n        {\n            Assert.Equal(\"png,jpg,jpeg,gif\", new FileExtensionsAttribute().Extensions);\n        }\n\n        [Fact]\n        public void ClientRule()\n        {\n            // Arrange\n            var attribute = new FileExtensionsAttribute { Extensions = \" FoO, .bar,baz \" };\n            var provider = new Mock<ModelMetadataProvider>();\n            var metadata = new ModelMetadata(provider.Object, null, null, typeof(string), \"PropertyName\");\n\n            // Act\n            ModelClientValidationRule clientRule = attribute.GetClientValidationRules(metadata, null).Single();\n\n            // Assert\n            Assert.Equal(\"extension\", clientRule.ValidationType);\n            Assert.Equal(\"The PropertyName field only accepts files with the following extensions: .foo, .bar, .baz\", clientRule.ErrorMessage);\n            Assert.Single(clientRule.ValidationParameters);\n            Assert.Equal(\"foo,bar,baz\", clientRule.ValidationParameters[\"extension\"]);\n        }\n\n        [Fact]\n        public void IsValidTests()\n        {\n            // Arrange\n            var attribute = new FileExtensionsAttribute();\n\n            // Act & Assert\n            Assert.True(attribute.IsValid(null)); // Optional values are always valid\n            Assert.True(attribute.IsValid(\"foo.png\"));\n            Assert.True(attribute.IsValid(\"foo.jpeg\"));\n            Assert.True(attribute.IsValid(\"foo.jpg\"));\n            Assert.True(attribute.IsValid(\"foo.gif\"));\n            Assert.True(attribute.IsValid(@\"C:\\Foo\\baz.jpg\"));\n            Assert.False(attribute.IsValid(\"foo\"));\n            Assert.False(attribute.IsValid(\"foo.png.pif\"));\n            Assert.False(attribute.IsValid(@\"C:\\foo.png\\bar\"));\n            Assert.False(attribute.IsValid(\"\\0foo.png\")); // Illegal character\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/FormExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.IO;\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class FormExtensionsTest\n    {\n        internal const string AppPathModifier = \"/$(SESSION)\";\n\n        [Fact]\n        public void FormWithPostAction()\n        {\n            // Arrange\n            StringWriter writer;\n            HtmlHelper htmlHelper = GetFormHelper(out writer);\n\n            // Act\n            IDisposable formDisposable = htmlHelper.BeginForm<FormController>(action => action.About());\n            formDisposable.Dispose();\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + AppPathModifier + @\"/Form/About\"\" method=\"\"post\"\"></form>\", writer.ToString());\n        }\n\n        [Fact]\n        public void FormWithPostActionAndObjectAttributes()\n        {\n            // Arrange\n            StringWriter writer;\n            HtmlHelper htmlHelper = GetFormHelper(out writer);\n\n            // Act\n            IDisposable formDisposable = htmlHelper.BeginForm<FormController>(action => action.About(), FormMethod.Get, new { baz = \"baz\" });\n            formDisposable.Dispose();\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + AppPathModifier + @\"/Form/About\"\" baz=\"\"baz\"\" method=\"\"get\"\"></form>\", writer.ToString());\n        }\n\n        [Fact]\n        public void FormWithPostActionAndObjectAttributesWithUnderscores()\n        {\n            // Arrange\n            StringWriter writer;\n            HtmlHelper htmlHelper = GetFormHelper(out writer);\n\n            // Act\n            IDisposable formDisposable = htmlHelper.BeginForm<FormController>(action => action.About(), FormMethod.Get, new { foo_baz = \"baz\" });\n            formDisposable.Dispose();\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + AppPathModifier + @\"/Form/About\"\" foo-baz=\"\"baz\"\" method=\"\"get\"\"></form>\", writer.ToString());\n        }\n\n        public class FormController : Controller\n        {\n            public ActionResult About()\n            {\n                return RedirectToAction(\"foo\");\n            }\n        }\n\n        private static HtmlHelper GetFormHelper(out StringWriter writer)\n        {\n            Mock<HttpRequestBase> mockHttpRequest = new Mock<HttpRequestBase>();\n            mockHttpRequest.Setup(r => r.Url).Returns(new Uri(\"http://www.contoso.com/some/path\"));\n            Mock<HttpResponseBase> mockHttpResponse = new Mock<HttpResponseBase>(MockBehavior.Strict);\n\n            mockHttpResponse.Setup(r => r.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(r => AppPathModifier + r);\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(c => c.Request).Returns(mockHttpRequest.Object);\n            mockHttpContext.Setup(c => c.Response).Returns(mockHttpResponse.Object);\n            RouteCollection rt = new RouteCollection();\n            rt.Add(new Route(\"{controller}/{action}/{id}\", null) { Defaults = new RouteValueDictionary(new { id = \"defaultid\" }) });\n            rt.Add(\"namedroute\", new Route(\"named/{controller}/{action}/{id}\", null) { Defaults = new RouteValueDictionary(new { id = \"defaultid\" }) });\n            RouteData rd = new RouteData();\n            rd.Values.Add(\"controller\", \"home\");\n            rd.Values.Add(\"action\", \"oldaction\");\n\n            Mock<ViewContext> mockViewContext = new Mock<ViewContext>();\n            mockViewContext.Setup(c => c.HttpContext).Returns(mockHttpContext.Object);\n            mockViewContext.Setup(c => c.RouteData).Returns(rd);\n            writer = new StringWriter();\n            mockViewContext.Setup(c => c.Writer).Returns(writer);\n\n            HtmlHelper helper = new HtmlHelper(\n                mockViewContext.Object,\n                new Mock<IViewDataContainer>().Object,\n                rt);\n            return helper;\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/ImageExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class ImageExtensionsTest\n    {\n        [Fact]\n        public void ImageWithEmptyRelativeUrlThrowsArgumentNullException()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n            Assert.ThrowsArgumentNullOrEmpty(() => html.Image(null), \"imageRelativeUrl\");\n        }\n\n        [Fact]\n        public void ImageStaticWithEmptyRelativeUrlThrowsArgumentNullException()\n        {\n            Assert.ThrowsArgumentNullOrEmpty(() => ImageExtensions.Image((string)null, \"alt\", null), \"imageUrl\");\n        }\n\n        [Fact]\n        public void ImageWithRelativeUrlRendersProperImageTag()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n            MvcHtmlString imageResult = html.Image(\"/system/web/mvc.jpg\");\n            // NOTE: Although XHTML requires an alt tag, we don't construct one for you. Specify it yourself.\n            Assert.Equal(\"<img src=\\\"/system/web/mvc.jpg\\\" />\", imageResult.ToHtmlString());\n        }\n\n        [Fact]\n        public void ImageWithWithAttributesWithUnderscores()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n            MvcHtmlString imageResult = html.Image(\"/system/web/mvc.jpg\", new { foo_bar = \"baz\" });\n            Assert.Equal(\"<img foo-bar=\\\"baz\\\" src=\\\"/system/web/mvc.jpg\\\" />\", imageResult.ToHtmlString());\n        }\n\n        [Fact]\n        public void ImageWithAltValueRendersImageWithAltTag()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n            MvcHtmlString imageResult = html.Image(\"/system/web/mvc.jpg\", \"this is an alt value\");\n            Assert.Equal(\"<img alt=\\\"this is an alt value\\\" src=\\\"/system/web/mvc.jpg\\\" title=\\\"this is an alt value\\\" />\", imageResult.ToHtmlString());\n        }\n\n        [Fact]\n        public void ImageWithAltValueInObjectDictionaryRendersImageWithAltAndTitleTag()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n            MvcHtmlString imageResult = html.Image(\"/system/web/mvc.jpg\", new { alt = \"this is an alt value\" });\n            Assert.Equal(\"<img alt=\\\"this is an alt value\\\" src=\\\"/system/web/mvc.jpg\\\" title=\\\"this is an alt value\\\" />\", imageResult.ToHtmlString());\n        }\n\n        [Fact]\n        public void ImageWithAltValueHtmlAttributeEncodesAltTag()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n            MvcHtmlString imageResult = html.Image(\"/system/web/mvc.jpg\", @\"<\"\">\");\n            Assert.Equal(\"<img alt=\\\"&lt;&quot;>\\\" src=\\\"/system/web/mvc.jpg\\\" title=\\\"&lt;&quot;>\\\" />\", imageResult.ToHtmlString());\n        }\n\n        [Fact]\n        public void ImageWithAltValueInObjectDictionaryHtmlAttributeEncodesAltTag()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n            MvcHtmlString imageResult = html.Image(\"/system/web/mvc.jpg\", new { alt = \"this is an alt value\" });\n            Assert.Equal(\"<img alt=\\\"this is an alt value\\\" src=\\\"/system/web/mvc.jpg\\\" title=\\\"this is an alt value\\\" />\", imageResult.ToHtmlString());\n        }\n\n        [Fact]\n        public void ImageWithAltSpecifiedAndInDictionaryRendersExplicit()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n            MvcHtmlString imageResult = html.Image(\"/system/web/mvc.jpg\", \"specified-alt\", new { alt = \"object-dictionary-alt\" });\n            Assert.Equal(\"<img alt=\\\"object-dictionary-alt\\\" src=\\\"/system/web/mvc.jpg\\\" title=\\\"object-dictionary-alt\\\" />\", imageResult.ToHtmlString());\n        }\n\n        [Fact]\n        public void ImageWithAltAndAttributesWithUnderscores()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n            MvcHtmlString imageResult = html.Image(\"/system/web/mvc.jpg\", \"specified-alt\", new { foo_bar = \"baz\" });\n            Assert.Equal(\"<img alt=\\\"specified-alt\\\" foo-bar=\\\"baz\\\" src=\\\"/system/web/mvc.jpg\\\" title=\\\"specified-alt\\\" />\", imageResult.ToHtmlString());\n        }\n\n        [Fact]\n        public void ImageWithSrcSpecifiedAndInDictionaryRendersExplicit()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n            MvcHtmlString imageResult = html.Image(\"/system/web/mvc.jpg\", new { src = \"explicit.jpg\" });\n            Assert.Equal(\"<img src=\\\"explicit.jpg\\\" />\", imageResult.ToHtmlString());\n        }\n\n        [Fact]\n        public void ImageWithOtherAttributesRendersThoseAttributesCaseSensitively()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n            MvcHtmlString imageResult = html.Image(\"/system/web/mvc.jpg\", new { width = 100, Height = 200 });\n            Assert.Equal(\"<img Height=\\\"200\\\" src=\\\"/system/web/mvc.jpg\\\" width=\\\"100\\\" />\", imageResult.ToHtmlString());\n        }\n\n        [Fact]\n        public void ImageWithUrlAndDictionaryRendersAttributes()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n            var attributes = new RouteValueDictionary(new { width = 125 });\n            MvcHtmlString imageResult = html.Image(\"/system/web/mvc.jpg\", attributes);\n            Assert.Equal(\"<img src=\\\"/system/web/mvc.jpg\\\" width=\\\"125\\\" />\", imageResult.ToHtmlString());\n        }\n\n        [Fact]\n        public void ImageWithTildePathAndAppPathResolvesCorrectly()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary(), \"/app\");\n            MvcHtmlString imageResult = html.Image(\"~/system/web/mvc.jpg\");\n            Assert.Equal(\"<img src=\\\"/app/system/web/mvc.jpg\\\" />\", imageResult.ToHtmlString());\n        }\n\n        [Fact]\n        public void ImageWithTildePathWithoutAppPathResolvesCorrectly()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary(), \"/\");\n            MvcHtmlString imageResult = html.Image(\"~/system/web/mvc.jpg\");\n            Assert.Equal(\"<img src=\\\"/system/web/mvc.jpg\\\" />\", imageResult.ToHtmlString());\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/MailToExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Mvc;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class MailToExtensionsTest\n    {\n        [Fact]\n        public void MailToWithoutEmailThrowsArgumentNullException()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n            Assert.ThrowsArgumentNull(() => html.Mailto(\"link text\", null), \"emailAddress\");\n        }\n\n        [Fact]\n        public void MailToWithoutLinkTextThrowsArgumentNullException()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n            Assert.ThrowsArgumentNull(() => html.Mailto(null, \"somebody@example.com\"), \"linkText\");\n        }\n\n        [Fact]\n        public void MailToWithLinkTextAndEmailRendersProperElement()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n            MvcHtmlString result = html.Mailto(\"This is a test\", \"test@example.com\");\n            Assert.Equal(\"<a href=\\\"mailto:test@example.com\\\">This is a test</a>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void MailToWithLinkTextEmailAndHtmlAttributesRendersAttributes()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n            MvcHtmlString result = html.Mailto(\"This is a test\", \"test@example.com\", new { title = \"this is a test\" });\n            Assert.Equal(\"<a href=\\\"mailto:test@example.com\\\" title=\\\"this is a test\\\">This is a test</a>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void MailToWithLinkTextEmailAndHtmlAttributesDictionaryRendersAttributes()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n            MvcHtmlString result = html.Mailto(\"This is a test\", \"test@example.com\", new RouteValueDictionary(new { title = \"this is a test\" }));\n            Assert.Equal(\"<a href=\\\"mailto:test@example.com\\\" title=\\\"this is a test\\\">This is a test</a>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void MailToWithSubjectAndHtmlAttributesRendersAttributes()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n            MvcHtmlString result = html.Mailto(\"This is a test\", \"test@example.com\", \"The subject\", new { title = \"this is a test\" });\n            Assert.Equal(\"<a href=\\\"mailto:test@example.com?subject=The subject\\\" title=\\\"this is a test\\\">This is a test</a>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void MailToWithSubjectAndHtmlAttributesDictionaryRendersAttributes()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n            MvcHtmlString result = html.Mailto(\"This is a test\", \"test@example.com\", \"The subject\", new RouteValueDictionary(new { title = \"this is a test\" }));\n            Assert.Equal(\"<a href=\\\"mailto:test@example.com?subject=The subject\\\" title=\\\"this is a test\\\">This is a test</a>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void MailToAttributeEncodesEmail()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n            MvcHtmlString result = html.Mailto(\"This is a test\", \"te\\\">st@example.com\");\n            Assert.Equal(\"<a href=\\\"mailto:te&quot;>st@example.com\\\">This is a test</a>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void MailToWithMultipleRecipientsRendersWithCommas()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n            MvcHtmlString result = html.Mailto(\"This is a test\", \"te\\\">st@example.com,test2@example.com\");\n            Assert.Equal(\"<a href=\\\"mailto:te&quot;>st@example.com,test2@example.com\\\">This is a test</a>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void MailToWithSubjectAppendsSubjectQuery()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n            MvcHtmlString result = html.Mailto(\"This is a test\", \"test@example.com\", \"This is the subject\");\n            Assert.Equal(\"<a href=\\\"mailto:test@example.com?subject=This is the subject\\\">This is a test</a>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void MailToWithCopyOnlyAppendsCopyQuery()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n            MvcHtmlString result = html.Mailto(\"This is a test\", \"test@example.com\", null, null, \"cctest@example.com\", null, null);\n            Assert.Equal(\"<a href=\\\"mailto:test@example.com?cc=cctest@example.com\\\">This is a test</a>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void MailToWithMultipartBodyRendersProperMailtoEncoding()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n            string body = \"Line one\" + Environment.NewLine\n                        + \"Line two\" + Environment.NewLine\n                        + \"Line three\";\n\n            MvcHtmlString result = html.Mailto(\"email me\", \"test@example.com\", null, body, null, null, null);\n            Assert.Equal(\"<a href=\\\"mailto:test@example.com?body=Line one%0ALine two%0ALine three\\\">email me</a>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void MailToWithAllValuesProvidedRendersCorrectTag()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n            string body = \"Line one\" + Environment.NewLine\n                        + \"Line two\" + Environment.NewLine\n                        + \"Line three\";\n\n            MvcHtmlString result = html.Mailto(\"email me\", \"test@example.com\", \"the subject\", body, \"cc@example.com\", \"bcc@example.com\", new { title = \"email test\" });\n            string expected = @\"<a href=\"\"mailto:test@example.com?subject=the subject&amp;cc=cc@example.com&amp;bcc=bcc@example.com&amp;body=Line one%0ALine two%0ALine three\"\" title=\"\"email test\"\">email me</a>\";\n            Assert.Equal(expected, result.ToHtmlString());\n        }\n\n        [Fact]\n        public void MailToWithAttributesWithUnderscores()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n            string body = \"Line one\" + Environment.NewLine\n                        + \"Line two\" + Environment.NewLine\n                        + \"Line three\";\n\n            MvcHtmlString result = html.Mailto(\"email me\", \"test@example.com\", \"the subject\", body, \"cc@example.com\", \"bcc@example.com\", new { foo_bar = \"baz\" });\n            string expected = @\"<a foo-bar=\"\"baz\"\" href=\"\"mailto:test@example.com?subject=the subject&amp;cc=cc@example.com&amp;bcc=bcc@example.com&amp;body=Line one%0ALine two%0ALine three\"\">email me</a>\";\n            Assert.Equal(expected, result.ToHtmlString());\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/ModelCopierTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class ModelCopierTest\n    {\n        [Fact]\n        public void CopyCollection_FromIsNull_DoesNothing()\n        {\n            // Arrange\n            int[] from = null;\n            List<int> to = new List<int> { 1, 2, 3 };\n\n            // Act\n            ModelCopier.CopyCollection(from, to);\n\n            // Assert\n            Assert.Equal(new[] { 1, 2, 3 }, to.ToArray());\n        }\n\n        [Fact]\n        public void CopyCollection_ToIsImmutable_DoesNothing()\n        {\n            // Arrange\n            List<int> from = new List<int> { 1, 2, 3 };\n            ICollection<int> to = new ReadOnlyCollection<int>(new[] { 4, 5, 6 });\n\n            // Act\n            ModelCopier.CopyCollection(from, to);\n\n            // Assert\n            Assert.Equal(new[] { 1, 2, 3 }, from.ToArray());\n            Assert.Equal(new[] { 4, 5, 6 }, to.ToArray());\n        }\n\n        [Fact]\n        public void CopyCollection_ToIsMmutable_ClearsAndCopies()\n        {\n            // Arrange\n            List<int> from = new List<int> { 1, 2, 3 };\n            ICollection<int> to = new List<int> { 4, 5, 6 };\n\n            // Act\n            ModelCopier.CopyCollection(from, to);\n\n            // Assert\n            Assert.Equal(new[] { 1, 2, 3 }, from.ToArray());\n            Assert.Equal(new[] { 1, 2, 3 }, to.ToArray());\n        }\n\n        [Fact]\n        public void CopyCollection_ToIsNull_DoesNothing()\n        {\n            // Arrange\n            List<int> from = new List<int> { 1, 2, 3 };\n            List<int> to = null;\n\n            // Act\n            ModelCopier.CopyCollection(from, to);\n\n            // Assert\n            Assert.Equal(new[] { 1, 2, 3 }, from.ToArray());\n        }\n\n        [Fact]\n        public void CopyModel_ExactTypeMatch_Copies()\n        {\n            // Arrange\n            GenericModel<int> from = new GenericModel<int> { TheProperty = 21 };\n            GenericModel<int> to = new GenericModel<int> { TheProperty = 42 };\n\n            // Act\n            ModelCopier.CopyModel(from, to);\n\n            // Assert\n            Assert.Equal(21, from.TheProperty);\n            Assert.Equal(21, to.TheProperty);\n        }\n\n        [Fact]\n        public void CopyModel_FromIsNull_DoesNothing()\n        {\n            // Arrange\n            GenericModel<int> from = null;\n            GenericModel<int> to = new GenericModel<int> { TheProperty = 42 };\n\n            // Act\n            ModelCopier.CopyModel(from, to);\n\n            // Assert\n            Assert.Equal(42, to.TheProperty);\n        }\n\n        [Fact]\n        public void CopyModel_LiftedTypeMatch_ActualValueIsNotNull_Copies()\n        {\n            // Arrange\n            GenericModel<int?> from = new GenericModel<int?> { TheProperty = 21 };\n            GenericModel<int> to = new GenericModel<int> { TheProperty = 42 };\n\n            // Act\n            ModelCopier.CopyModel(from, to);\n\n            // Assert\n            Assert.Equal(21, from.TheProperty);\n            Assert.Equal(21, to.TheProperty);\n        }\n\n        [Fact]\n        public void CopyModel_LiftedTypeMatch_ActualValueIsNull_DoesNothing()\n        {\n            // Arrange\n            GenericModel<int?> from = new GenericModel<int?> { TheProperty = null };\n            GenericModel<int> to = new GenericModel<int> { TheProperty = 42 };\n\n            // Act\n            ModelCopier.CopyModel(from, to);\n\n            // Assert\n            Assert.Null(from.TheProperty);\n            Assert.Equal(42, to.TheProperty);\n        }\n\n        [Fact]\n        public void CopyModel_NoTypeMatch_DoesNothing()\n        {\n            // Arrange\n            GenericModel<int> from = new GenericModel<int> { TheProperty = 21 };\n            GenericModel<long> to = new GenericModel<long> { TheProperty = 42 };\n\n            // Act\n            ModelCopier.CopyModel(from, to);\n\n            // Assert\n            Assert.Equal(21, from.TheProperty);\n            Assert.Equal(42, to.TheProperty);\n        }\n\n        [Fact]\n        public void CopyModel_SubclassedTypeMatch_Copies()\n        {\n            // Arrange\n            string originalModel = \"Hello, world!\";\n\n            GenericModel<string> from = new GenericModel<string> { TheProperty = originalModel };\n            GenericModel<object> to = new GenericModel<object> { TheProperty = 42 };\n\n            // Act\n            ModelCopier.CopyModel(from, to);\n\n            // Assert\n            Assert.Same(originalModel, from.TheProperty);\n            Assert.Same(originalModel, to.TheProperty);\n        }\n\n        [Fact]\n        public void CopyModel_ToDoesNotContainProperty_DoesNothing()\n        {\n            // Arrange\n            GenericModel<int> from = new GenericModel<int> { TheProperty = 21 };\n            OtherGenericModel<int> to = new OtherGenericModel<int> { SomeOtherProperty = 42 };\n\n            // Act\n            ModelCopier.CopyModel(from, to);\n\n            // Assert\n            Assert.Equal(21, from.TheProperty);\n            Assert.Equal(42, to.SomeOtherProperty);\n        }\n\n        [Fact]\n        public void CopyModel_ToIsNull_DoesNothing()\n        {\n            // Arrange\n            GenericModel<int> from = new GenericModel<int> { TheProperty = 21 };\n            GenericModel<int> to = null;\n\n            // Act\n            ModelCopier.CopyModel(from, to);\n\n            // Assert\n            Assert.Equal(21, from.TheProperty);\n        }\n\n        [Fact]\n        public void CopyModel_ToIsReadOnly_DoesNothing()\n        {\n            // Arrange\n            GenericModel<int> from = new GenericModel<int> { TheProperty = 21 };\n            ReadOnlyGenericModel<int> to = new ReadOnlyGenericModel<int>(42);\n\n            // Act\n            ModelCopier.CopyModel(from, to);\n\n            // Assert\n            Assert.Equal(21, from.TheProperty);\n            Assert.Equal(42, to.TheProperty);\n        }\n\n        private class GenericModel<T>\n        {\n            public T TheProperty { get; set; }\n        }\n\n        private class OtherGenericModel<T>\n        {\n            public T SomeOtherProperty { get; set; }\n        }\n\n        private class ReadOnlyGenericModel<T>\n        {\n            public ReadOnlyGenericModel(T propertyValue)\n            {\n                TheProperty = propertyValue;\n            }\n\n            public T TheProperty { get; private set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/MvcSerializerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Runtime.Serialization;\nusing System.Web.Security;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class MvcSerializerTest\n    {\n        [Fact]\n        public void DeserializeThrowsIfSerializedValueIsCorrupt()\n        {\n            // Arrange\n            IMachineKey machineKey = new MockMachineKey();\n\n            // Act & assert\n            Exception exception = Assert.Throws<SerializationException>(\n                delegate { MvcSerializer.Deserialize(\"This is a corrupted value.\", machineKey); },\n                @\"Deserialization failed. Verify that the data is being deserialized using the same SerializationMode with which it was serialized. Otherwise see the inner exception.\");\n\n            Assert.NotNull(exception.InnerException);\n        }\n\n        [Fact]\n        public void DeserializeThrowsIfSerializedValueIsEmpty()\n        {\n            // Arrange\n            MvcSerializer serializer = new MvcSerializer();\n\n            // Act & assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { serializer.Deserialize(\"\"); }, \"serializedValue\");\n        }\n\n        [Fact]\n        public void DeserializeThrowsIfSerializedValueIsNull()\n        {\n            // Arrange\n            MvcSerializer serializer = new MvcSerializer();\n\n            // Act & assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { serializer.Deserialize(null); }, \"serializedValue\");\n        }\n\n        [Fact]\n        public void SerializeAllowsNullValues()\n        {\n            // Arrange\n            IMachineKey machineKey = new MockMachineKey();\n\n            // Act\n            string serializedValue = MvcSerializer.Serialize(null, machineKey);\n\n            // Assert\n            Assert.Equal(@\"Microsoft.Web.Mvc.MvcSerializer.v1-dwdhbnlUeXBlLgNuaWyGCQF6M2h0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vMjAwMy8xMC9TZXJpYWxpemF0aW9uLwkBaSlodHRwOi8vd3d3LnczLm9yZy8yMDAxL1hNTFNjaGVtYS1pbnN0YW5jZQE=\", serializedValue);\n        }\n\n        [Fact]\n        public void SerializeAndDeserializeRoundTripsValue()\n        {\n            // Arrange\n            IMachineKey machineKey = new MockMachineKey();\n\n            // Act\n            string serializedValue = MvcSerializer.Serialize(42, machineKey);\n            object deserializedValue = MvcSerializer.Deserialize(serializedValue, machineKey);\n\n            // Assert\n            Assert.Equal(42, deserializedValue);\n        }\n\n        private sealed class MockMachineKey : IMachineKey\n        {\n            public byte[] Unprotect(string protectedData, params string[] purposes)\n            {\n                string optionString = purposes[0].ToString();\n                if (protectedData.StartsWith(optionString, StringComparison.Ordinal))\n                {\n                    protectedData = protectedData.Substring(optionString.Length + 1);\n                }\n                else\n                {\n                    throw new Exception(\"Corrupted data.\");\n                }\n                return Convert.FromBase64String(protectedData);\n\n            }\n\n            public string Protect(byte[] userData, params string[] purposes)\n            {\n                return purposes[0].ToString() + \"-\" + Convert.ToBase64String(userData);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/RadioExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Web.Mvc;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class RadioExtensionsTest\n    {\n        [Fact]\n        public void RadioButtonListNothingSelected()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n\n            // Act\n            MvcHtmlString[] html = htmlHelper.RadioButtonList(\"FooList\", GetRadioButtonListData(false));\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"foo\"\" />\", html[0].ToHtmlString());\n            Assert.Equal(@\"<input id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"bar\"\" />\", html[1].ToHtmlString());\n            Assert.Equal(@\"<input id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"baz\"\" />\", html[2].ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonListItemSelected()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n\n            // Act\n            MvcHtmlString[] html = htmlHelper.RadioButtonList(\"FooList\", GetRadioButtonListData(true));\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"foo\"\" />\", html[0].ToHtmlString());\n            Assert.Equal(@\"<input id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"bar\"\" />\", html[1].ToHtmlString());\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"baz\"\" />\", html[2].ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonListItemSelectedWithValueFromViewData()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(new ViewDataDictionary(new { foolist = \"bar\" }));\n\n            // Act\n            MvcHtmlString[] html = htmlHelper.RadioButtonList(\"FooList\", GetRadioButtonListData(false));\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"foo\"\" />\", html[0].ToHtmlString());\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"bar\"\" />\", html[1].ToHtmlString());\n            Assert.Equal(@\"<input id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"baz\"\" />\", html[2].ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonListWithObjectAttributes()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n\n            // Act\n            MvcHtmlString[] html = htmlHelper.RadioButtonList(\"FooList\", GetRadioButtonListData(true), new { attr1 = \"value1\" });\n\n            // Assert\n            Assert.Equal(@\"<input attr1=\"\"value1\"\" id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"foo\"\" />\", html[0].ToHtmlString());\n            Assert.Equal(@\"<input attr1=\"\"value1\"\" id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"bar\"\" />\", html[1].ToHtmlString());\n            Assert.Equal(@\"<input attr1=\"\"value1\"\" checked=\"\"checked\"\" id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"baz\"\" />\", html[2].ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonListWithObjectAttributesWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n\n            // Act\n            MvcHtmlString[] html = htmlHelper.RadioButtonList(\"FooList\", GetRadioButtonListData(true), new { foo_bar = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<input foo-bar=\"\"baz\"\" id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"foo\"\" />\", html[0].ToHtmlString());\n            Assert.Equal(@\"<input foo-bar=\"\"baz\"\" id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"bar\"\" />\", html[1].ToHtmlString());\n            Assert.Equal(@\"<input checked=\"\"checked\"\" foo-bar=\"\"baz\"\" id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"baz\"\" />\", html[2].ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonListWithDictionaryAttributes()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n\n            // Act\n            MvcHtmlString[] html = htmlHelper.RadioButtonList(\"FooList\", GetRadioButtonListData(true), new RouteValueDictionary(new { attr1 = \"value1\" }));\n\n            // Assert\n            Assert.Equal(@\"<input attr1=\"\"value1\"\" id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"foo\"\" />\", html[0].ToHtmlString());\n            Assert.Equal(@\"<input attr1=\"\"value1\"\" id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"bar\"\" />\", html[1].ToHtmlString());\n            Assert.Equal(@\"<input attr1=\"\"value1\"\" checked=\"\"checked\"\" id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"baz\"\" />\", html[2].ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonListNothingSelectedWithSelectListFromViewData()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetRadioButtonListViewData(false));\n\n            // Act\n            MvcHtmlString[] html = htmlHelper.RadioButtonList(\"FooList\");\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"foo\"\" />\", html[0].ToHtmlString());\n            Assert.Equal(@\"<input id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"bar\"\" />\", html[1].ToHtmlString());\n            Assert.Equal(@\"<input id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"baz\"\" />\", html[2].ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonListItemSelectedWithSelectListFromViewData()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetRadioButtonListViewData(true));\n\n            // Act\n            MvcHtmlString[] html = htmlHelper.RadioButtonList(\"FooList\");\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"foo\"\" />\", html[0].ToHtmlString());\n            Assert.Equal(@\"<input id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"bar\"\" />\", html[1].ToHtmlString());\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"baz\"\" />\", html[2].ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonListWithObjectAttributesWithSelectListFromViewData()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetRadioButtonListViewData(true));\n\n            // Act\n            MvcHtmlString[] html = htmlHelper.RadioButtonList(\"FooList\", new { attr1 = \"value1\" });\n\n            // Assert\n            Assert.Equal(@\"<input attr1=\"\"value1\"\" id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"foo\"\" />\", html[0].ToHtmlString());\n            Assert.Equal(@\"<input attr1=\"\"value1\"\" id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"bar\"\" />\", html[1].ToHtmlString());\n            Assert.Equal(@\"<input attr1=\"\"value1\"\" checked=\"\"checked\"\" id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"baz\"\" />\", html[2].ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonListWithObjectAttributesWithUnderscoresWithSelectListFromViewData()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetRadioButtonListViewData(true));\n\n            // Act\n            MvcHtmlString[] html = htmlHelper.RadioButtonList(\"FooList\", new { foo_bar = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<input foo-bar=\"\"baz\"\" id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"foo\"\" />\", html[0].ToHtmlString());\n            Assert.Equal(@\"<input foo-bar=\"\"baz\"\" id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"bar\"\" />\", html[1].ToHtmlString());\n            Assert.Equal(@\"<input checked=\"\"checked\"\" foo-bar=\"\"baz\"\" id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"baz\"\" />\", html[2].ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonListWithDictionaryAttributesWithSelectListFromViewData()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetRadioButtonListViewData(true));\n\n            // Act\n            MvcHtmlString[] html = htmlHelper.RadioButtonList(\"FooList\", new RouteValueDictionary(new { attr1 = \"value1\" }));\n\n            // Assert\n            Assert.Equal(@\"<input attr1=\"\"value1\"\" id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"foo\"\" />\", html[0].ToHtmlString());\n            Assert.Equal(@\"<input attr1=\"\"value1\"\" id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"bar\"\" />\", html[1].ToHtmlString());\n            Assert.Equal(@\"<input attr1=\"\"value1\"\" checked=\"\"checked\"\" id=\"\"FooList\"\" name=\"\"FooList\"\" type=\"\"radio\"\" value=\"\"baz\"\" />\", html[2].ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonListWithDictionaryAttributesWithWrongSelectListName()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetRadioButtonListViewData(true));\n\n            // Act / Assert\n            Assert.Throws<InvalidOperationException>(() => \n                htmlHelper.RadioButtonList(\"WrongFooList\", new RouteValueDictionary(new { attr1 = \"value1\" })));\n        }\n\n        [Fact]\n        public void RadioButtonListWithDictionaryAttributesWithInvalidSelectListFromViewData()\n        {\n            // Arrange\n            ViewDataDictionary viewData = new ViewDataDictionary();\n            viewData[\"FooList\"] = \"FOOBAR3\";\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act / Assert\n            Assert.Throws<InvalidOperationException>(() => \n                htmlHelper.RadioButtonList(\"FooList\", new RouteValueDictionary(new { attr1 = \"value1\" })));\n        }\n\n        [Fact]\n        public void RadioButtonListWithDictionaryAttributesWithNullSelectListNameFromSelectList()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetRadioButtonListViewData(true));\n            SelectList selectList = GetRadioButtonListData(true);\n\n            // Act / Assert\n            Assert.Throws<ArgumentException>(() => \n                htmlHelper.RadioButtonList(\"\", selectList, new RouteValueDictionary(new { attr1 = \"value1\" })));\n        }\n\n        [Fact]\n        public void RadioButtonListWithDictionaryAttributesWithSelectListNameAndNullSelectList()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetRadioButtonListViewData(true));\n\n            // Act / Assert\n            Assert.Throws<ArgumentNullException>(() => \n                htmlHelper.RadioButtonList(\"FooBar\", null, new RouteValueDictionary(new { attr1 = \"value1\" })));\n        }\n\n        private static SelectList GetRadioButtonListData(bool selectBaz)\n        {\n            List<RadioItem> list = new List<RadioItem>();\n            list.Add(new RadioItem { Text = \"text-foo\", Value = \"foo\" });\n            list.Add(new RadioItem { Text = \"text-bar\", Value = \"bar\" });\n            list.Add(new RadioItem { Text = \"text-baz\", Value = \"baz\" });\n            return new SelectList(list, \"value\", \"TEXT\", selectBaz ? \"baz\" : \"something-else\");\n        }\n\n        private static ViewDataDictionary GetRadioButtonListViewData(bool selectBaz)\n        {\n            ViewDataDictionary viewData = new ViewDataDictionary();\n            viewData[\"FooList\"] = GetRadioButtonListData(selectBaz);\n            return viewData;\n        }\n\n        private class RadioItem\n        {\n            public string Text { get; set; }\n\n            public string Value { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/ReaderWriterCacheTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class ReaderWriterCacheTest\n    {\n        [Fact]\n        public void PublicFetchOrCreateItemCreatesItemIfNotAlreadyInCache()\n        {\n            // Arrange\n            ReaderWriterCacheHelper<int, string> helper = new ReaderWriterCacheHelper<int, string>();\n            Dictionary<int, string> cache = helper.PublicCache;\n\n            // Act\n            string item = helper.PublicFetchOrCreateItem(42, () => \"new\");\n\n            // Assert\n            Assert.Equal(\"new\", cache[42]);\n            Assert.Equal(\"new\", item);\n        }\n\n        [Fact]\n        public void PublicFetchOrCreateItemReturnsExistingItemIfFound()\n        {\n            // Arrange\n            ReaderWriterCacheHelper<int, string> helper = new ReaderWriterCacheHelper<int, string>();\n            Dictionary<int, string> cache = helper.PublicCache;\n            helper.PublicCache[42] = \"original\";\n\n            // Act\n            string item = helper.PublicFetchOrCreateItem(42, () => \"new\");\n\n            // Assert\n            Assert.Equal(\"original\", cache[42]);\n            Assert.Equal(\"original\", item);\n        }\n\n        [Fact]\n        public void PublicFetchOrCreateItemReturnsFirstItemIfTwoThreadsUpdateCacheSimultaneously()\n        {\n            // Arrange\n            ReaderWriterCacheHelper<int, string> helper = new ReaderWriterCacheHelper<int, string>();\n            Dictionary<int, string> cache = helper.PublicCache;\n            Func<string> creator = delegate\n            {\n                // fake a second thread coming along when we weren't looking\n                string firstItem = helper.PublicFetchOrCreateItem(42, () => \"original\");\n\n                Assert.Equal(\"original\", cache[42]);\n                Assert.Equal(\"original\", firstItem);\n                return \"new\";\n            };\n\n            // Act\n            string secondItem = helper.PublicFetchOrCreateItem(42, creator);\n\n            // Assert\n            Assert.Equal(\"original\", cache[42]);\n            Assert.Equal(\"original\", secondItem);\n        }\n\n        private class ReaderWriterCacheHelper<TKey, TValue> : ReaderWriterCache<TKey, TValue>\n        {\n            public Dictionary<TKey, TValue> PublicCache\n            {\n                get { return Cache; }\n            }\n\n            public TValue PublicFetchOrCreateItem(TKey key, Func<TValue> creator)\n            {\n                return FetchOrCreateItem(key, creator);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/RenderActionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.IO;\nusing System.Reflection;\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\nusing Moq;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class RenderActionTest\n    {\n        [Fact]\n        public void RenderActionUsingExpressionWithParametersInViewContextRendersCorrectly()\n        {\n            // Arrange\n            Func<RequestContext> requestContextAccessor;\n            HtmlHelper html = GetHtmlHelper(out requestContextAccessor);\n            html.ViewContext.RouteData.Values.Add(\"stuff\", \"42\");\n\n            // Act\n            html.RenderAction<TestController>(c => c.Stuff());\n            RequestContext requestContext = requestContextAccessor();\n\n            // Assert\n            Assert.NotNull(requestContext);\n            Assert.Equal(\"Test\", requestContext.RouteData.Values[\"controller\"]);\n            Assert.Equal(\"Stuff\", requestContext.RouteData.Values[\"action\"]);\n            Assert.Equal(\"42\", requestContext.RouteData.Values[\"stuff\"]);\n        }\n\n        [Fact]\n        public void RenderActionUsingExpressionRendersCorrectly()\n        {\n            // Arrange\n            Func<RequestContext> requestContextAccessor;\n            HtmlHelper html = GetHtmlHelper(out requestContextAccessor);\n\n            // Act\n            html.RenderAction<TestController>(c => c.About(76));\n            RequestContext requestContext = requestContextAccessor();\n\n            // Assert\n            Assert.NotNull(requestContext);\n            Assert.Equal(\"Test\", requestContext.RouteData.Values[\"controller\"]);\n            Assert.Equal(\"About\", requestContext.RouteData.Values[\"action\"]);\n            Assert.Equal(76, requestContext.RouteData.Values[\"page\"]);\n        }\n\n        [Fact]\n        public void RenderRouteWithNullRouteValueDictionaryThrowsException()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary(), \"/\");\n            Assert.ThrowsArgumentNull(() => html.RenderRoute(null), \"routeValues\");\n        }\n\n        [Fact]\n        public void RenderRouteWithActionAndControllerSpecifiedRendersCorrectAction()\n        {\n            // Arrange\n            Func<RequestContext> requestContextAccessor;\n            HtmlHelper html = GetHtmlHelper(out requestContextAccessor);\n\n            // Act\n            html.RenderRoute(new RouteValueDictionary(new { action = \"Index\", controller = \"Test\" }));\n            RequestContext requestContext = requestContextAccessor();\n\n            // Assert\n            Assert.NotNull(requestContext);\n            Assert.Equal(\"Test\", requestContext.RouteData.Values[\"controller\"]);\n            Assert.Equal(\"Index\", requestContext.RouteData.Values[\"action\"]);\n        }\n\n        private static HtmlHelper GetHtmlHelper(out Func<RequestContext> requestContextAccessor)\n        {\n            RequestContext requestContext = null;\n\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary(), \"/\");\n\n            html.RouteCollection.MapRoute(null, \"{*dummy}\");\n            Mock.Get(html.ViewContext.HttpContext)\n                .Setup(o => o.Server.Execute(It.IsAny<IHttpHandler>(), It.IsAny<TextWriter>(), It.IsAny<bool>()))\n                .Callback<IHttpHandler, TextWriter, bool>((_h, _w, _pf) =>\n                {\n                    MvcHandler mvcHandler = _h.GetType().GetProperty(\"InnerHandler\", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(_h, null) as MvcHandler;\n                    requestContext = mvcHandler.RequestContext;\n                });\n\n            requestContextAccessor = () => requestContext;\n            return html;\n        }\n\n        public class TestController : Controller\n        {\n            public string Index()\n            {\n                return \"It Worked!\";\n            }\n\n            public string About(int page)\n            {\n                return \"This is page #\" + page;\n            }\n\n            public string Stuff()\n            {\n                string stuff = ControllerContext.RouteData.Values[\"stuff\"] as string;\n                return \"Argument was \" + stuff;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/ScriptExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\nusing Moq;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class ScriptExtensionsTest\n    {\n        [Fact]\n        public void ScriptWithoutReleaseFileThrowsArgumentNullException()\n        {\n            // Arrange\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n\n            // Assert\n            Assert.ThrowsArgumentNullOrEmpty(() => html.Script(null, \"file\"), \"releaseFile\");\n        }\n\n        [Fact]\n        public void ScriptWithoutDebugFileThrowsArgumentNullException()\n        {\n            // Arrange\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n\n            // Assert\n            Assert.ThrowsArgumentNullOrEmpty(() => html.Script(\"File\", null), \"debugFile\");\n        }\n\n        [Fact]\n        public void ScriptWithRootedPathRendersProperElement()\n        {\n            // Arrange\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n\n            // Act\n            MvcHtmlString result = html.Script(\"~/Correct/Path.js\", \"~/Correct/Debug/Path.js\");\n\n            // Assert\n            Assert.Equal(\"<script src=\\\"/Correct/Path.js\\\" type=\\\"text/javascript\\\"></script>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void ScriptWithRelativePathRendersProperElement()\n        {\n            // Arrange\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n\n            // Act\n            MvcHtmlString result = html.Script(\"../../Correct/Path.js\", \"../../Correct/Debug/Path.js\");\n\n            // Assert\n            Assert.Equal(\"<script src=\\\"../../Correct/Path.js\\\" type=\\\"text/javascript\\\"></script>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void ScriptWithRelativeCurrentPathRendersProperElement()\n        {\n            // Arrange\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n\n            // Act\n            MvcHtmlString result = html.Script(\"/Correct/Path.js\", \"/Correct/Debug/Path.js\");\n\n            // Assert\n            Assert.Equal(\"<script src=\\\"/Correct/Path.js\\\" type=\\\"text/javascript\\\"></script>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void ScriptWithScriptRelativePathRendersProperElement()\n        {\n            // Arrange\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n\n            // Act\n            MvcHtmlString result = html.Script(\"Correct/Path.js\", \"Correct/Debug/Path.js\");\n\n            // Assert\n            Assert.Equal(\"<script src=\\\"/Scripts/Correct/Path.js\\\" type=\\\"text/javascript\\\"></script>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void ScriptWithUrlRendersProperElement()\n        {\n            // Arrange\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n\n            // Act\n            MvcHtmlString result = html.Script(\"http://ajax.Correct.com/Path.js\", \"http://ajax.Debug.com/Path.js\");\n\n            // Assert\n            Assert.Equal(\"<script src=\\\"http://ajax.Correct.com/Path.js\\\" type=\\\"text/javascript\\\"></script>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void ScriptWithSecureUrlRendersProperElement()\n        {\n            // Arrange\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n\n            // Act\n            MvcHtmlString result = html.Script(\"https://ajax.Correct.com/Path.js\", \"https://ajax.Debug.com/Path.js\");\n\n            // Assert\n            Assert.Equal(\"<script src=\\\"https://ajax.Correct.com/Path.js\\\" type=\\\"text/javascript\\\"></script>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void ScriptWithDebuggingOnUsesDebugUrl()\n        {\n            // Arrange\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary());\n            Mock.Get(html.ViewContext.HttpContext).Setup(v => v.IsDebuggingEnabled).Returns(true);\n\n            // Act\n            MvcHtmlString result = html.Script(\"Correct/Path.js\", \"Correct/Debug/Path.js\");\n\n            // Assert\n            Assert.Equal(\"<script src=\\\"/Scripts/Correct/Debug/Path.js\\\" type=\\\"text/javascript\\\"></script>\", result.ToHtmlString());\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/SerializationExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\nusing Moq;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class SerializationExtensionsTest\n    {\n        [Fact]\n        public void SerializeFromProvidedValueOverridesViewData()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary\n            {\n                { \"someKey\", 42 }\n            };\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(vdd);\n\n            Mock<MvcSerializer> mockSerializer = new Mock<MvcSerializer>();\n            mockSerializer.Setup(o => o.Serialize(\"Hello!\")).Returns(\"some-value\");\n\n            // Act\n            MvcHtmlString htmlString = helper.Serialize(\"someKey\", \"Hello!\", mockSerializer.Object);\n\n            // Assert\n            Assert.Equal(@\"<input name=\"\"someKey\"\" type=\"\"hidden\"\" value=\"\"some-value\"\" />\", htmlString.ToHtmlString());\n        }\n\n        [Fact]\n        public void SerializeFromViewData()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary\n            {\n                { \"someKey\", 42 }\n            };\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(vdd);\n\n            Mock<MvcSerializer> mockSerializer = new Mock<MvcSerializer>();\n            mockSerializer.Setup(o => o.Serialize(42)).Returns(\"some-other-value\");\n\n            // Act\n            MvcHtmlString htmlString = helper.Serialize(\"someKey\", mockSerializer.Object);\n\n            // Assert\n            Assert.Equal(@\"<input name=\"\"someKey\"\" type=\"\"hidden\"\" value=\"\"some-other-value\"\" />\", htmlString.ToHtmlString());\n        }\n\n        [Fact]\n        public void SerializeThrowsIfHtmlHelperIsNull()\n        {\n            Assert.ThrowsArgumentNull(\n                delegate { SerializationExtensions.Serialize(null, \"someName\"); }, \"htmlHelper\");\n        }\n\n        [Fact]\n        public void SerializeThrowsIfNameIsEmpty()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { helper.Serialize(\"\"); }, \"name\");\n        }\n\n        [Fact]\n        public void SerializeThrowsIfNameIsNull()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { helper.Serialize(null); }, \"name\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/ServerVariablesValueProviderFactoryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing System.Globalization;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class ServerVariablesValueProviderFactoryTest\n    {\n        [Fact]\n        public void GetValueProvider()\n        {\n            // Arrange\n            NameValueCollection serverVars = new NameValueCollection\n            {\n                { \"foo\", \"fooValue\" },\n                { \"bar.baz\", \"barBazValue\" }\n            };\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(o => o.HttpContext.Request.ServerVariables).Returns(serverVars);\n\n            ServerVariablesValueProviderFactory factory = new ServerVariablesValueProviderFactory();\n\n            // Act\n            IValueProvider provider = factory.GetValueProvider(mockControllerContext.Object);\n\n            // Assert\n            Assert.True(provider.ContainsPrefix(\"bar\"));\n            Assert.Equal(\"fooValue\", provider.GetValue(\"foo\").AttemptedValue);\n            Assert.Equal(CultureInfo.InvariantCulture, provider.GetValue(\"foo\").Culture);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/SessionValueProviderFactoryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Web;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class SessionValueProviderFactoryTest\n    {\n        [Fact]\n        public void GetValueProvider()\n        {\n            // Arrange\n            Dictionary<string, object> backingStore = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase)\n            {\n                { \"foo\", \"fooValue\" },\n                { \"bar.baz\", \"barBazValue\" }\n            };\n            MockSessionState session = new MockSessionState(backingStore);\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(o => o.HttpContext.Session).Returns(session);\n\n            SessionValueProviderFactory factory = new SessionValueProviderFactory();\n\n            // Act\n            IValueProvider provider = factory.GetValueProvider(mockControllerContext.Object);\n\n            // Assert\n            Assert.True(provider.ContainsPrefix(\"bar\"));\n            Assert.Equal(\"fooValue\", provider.GetValue(\"foo\").AttemptedValue);\n            Assert.Equal(CultureInfo.InvariantCulture, provider.GetValue(\"foo\").Culture);\n        }\n\n        private sealed class MockSessionState : HttpSessionStateBase\n        {\n            private readonly IDictionary<string, object> _backingStore;\n\n            public MockSessionState(IDictionary<string, object> backingStore)\n            {\n                _backingStore = backingStore;\n            }\n\n            public override object this[string name]\n            {\n                get { return _backingStore[name]; }\n                set { _backingStore[name] = value; }\n            }\n\n            public override IEnumerator GetEnumerator()\n            {\n                return _backingStore.Keys.GetEnumerator();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/SkipBindingAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class SkipBindingAttributeTest\n    {\n        [Fact]\n        public void GetBinderReturnsModelBinderWhichReturnsNull()\n        {\n            // Arrange\n            CustomModelBinderAttribute attr = new SkipBindingAttribute();\n            IModelBinder binder = attr.GetBinder();\n\n            // Act\n            object result = binder.BindModel(null, null);\n\n            // Assert\n            Assert.Null(result);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/SubmitButtonExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class SubmitButtonExtensionsTest\n    {\n        [Fact]\n        public void SubmitButtonRendersWithJustTypeAttribute()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            MvcHtmlString button = html.SubmitButton();\n            Assert.Equal(\"<input type=\\\"submit\\\" />\", button.ToHtmlString());\n        }\n\n        [Fact]\n        public void SubmitButtonWithAttributesWithUnderscores()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            MvcHtmlString button = html.SubmitButton(null, \"blah\", new { foo_bar = \"baz\" });\n            Assert.Equal(\"<input foo-bar=\\\"baz\\\" type=\\\"submit\\\" value=\\\"blah\\\" />\", button.ToHtmlString());\n        }\n\n        [Fact]\n        public void SubmitButtonWithNameRendersButtonWithNameAttribute()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            MvcHtmlString button = html.SubmitButton(\"button-name\");\n            Assert.Equal(\"<input id=\\\"button-name\\\" name=\\\"button-name\\\" type=\\\"submit\\\" />\", button.ToHtmlString());\n        }\n\n        [Fact]\n        public void SubmitButtonWithIdDifferentFromNameRendersButtonWithId()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            MvcHtmlString button = html.SubmitButton(\"button-name\", \"blah\", new { id = \"foo\" });\n            Assert.Equal(\"<input id=\\\"foo\\\" name=\\\"button-name\\\" type=\\\"submit\\\" value=\\\"blah\\\" />\", button.ToHtmlString());\n        }\n\n        [Fact]\n        public void SubmitButtonWithNameAndTextRendersAttributes()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            MvcHtmlString button = html.SubmitButton(\"button-name\", \"button-text\");\n            Assert.Equal(\"<input id=\\\"button-name\\\" name=\\\"button-name\\\" type=\\\"submit\\\" value=\\\"button-text\\\" />\", button.ToHtmlString());\n        }\n\n        [Fact]\n        public void SubmitButtonWithNameAndValueRendersBothAttributes()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            MvcHtmlString button = html.SubmitButton(\"button-name\", \"button-value\", new { id = \"button-id\" });\n            Assert.Equal(\"<input id=\\\"button-id\\\" name=\\\"button-name\\\" type=\\\"submit\\\" value=\\\"button-value\\\" />\", button.ToHtmlString());\n        }\n\n        [Fact]\n        public void SubmitButtonWithNameAndIdRendersBothAttributesCorrectly()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            MvcHtmlString button = html.SubmitButton(\"button-name\", \"button-value\", new { id = \"button-id\" });\n            Assert.Equal(\"<input id=\\\"button-id\\\" name=\\\"button-name\\\" type=\\\"submit\\\" value=\\\"button-value\\\" />\", button.ToHtmlString());\n        }\n\n        [Fact]\n        public void SubmitButtonWithTypeAttributeRendersCorrectType()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            MvcHtmlString button = html.SubmitButton(\"specified-name\", \"button-value\", new { type = \"not-submit\" });\n            Assert.Equal(\"<input id=\\\"specified-name\\\" name=\\\"specified-name\\\" type=\\\"not-submit\\\" value=\\\"button-value\\\" />\", button.ToHtmlString());\n        }\n\n        [Fact]\n        public void SubmitButtonWithNameAndValueSpecifiedAndPassedInAsAttributeChoosesSpecified()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            MvcHtmlString button = html.SubmitButton(\"specified-name\", \"button-value\", new RouteValueDictionary(new { name = \"name-attribute-value\", value = \"value-attribute\" }));\n            Assert.Equal(\"<input id=\\\"specified-name\\\" name=\\\"name-attribute-value\\\" type=\\\"submit\\\" value=\\\"value-attribute\\\" />\", button.ToHtmlString());\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/SubmitImageExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class SubmitImageExtensionsTest\n    {\n        [Fact]\n        public void SubmitImageWithEmptyImageSrcThrowsArgumentNullException()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            Assert.ThrowsArgumentNull(() => html.SubmitImage(\"name\", null), \"imageSrc\");\n        }\n\n        [Fact]\n        public void SubmitImageWithAttributesWithUnderscores()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            MvcHtmlString button = html.SubmitImage(\"specified-name\", \"/mvc.jpg\", new { foo_bar = \"baz\" });\n            Assert.Equal(\"<input foo-bar=\\\"baz\\\" id=\\\"specified-name\\\" name=\\\"specified-name\\\" src=\\\"/mvc.jpg\\\" type=\\\"image\\\" />\", button.ToHtmlString());\n        }\n\n        [Fact]\n        public void SubmitImageWithTypeAttributeRendersExplicitTypeAttribute()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            MvcHtmlString button = html.SubmitImage(\"specified-name\", \"/mvc.jpg\", new { type = \"not-image\" });\n            Assert.Equal(\"<input id=\\\"specified-name\\\" name=\\\"specified-name\\\" src=\\\"/mvc.jpg\\\" type=\\\"not-image\\\" />\", button.ToHtmlString());\n        }\n\n        [Fact]\n        public void SubmitImageWithNameAndImageUrlRendersNameAndSrcAttributes()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            MvcHtmlString button = html.SubmitImage(\"button-name\", \"/mvc.gif\");\n            Assert.Equal(\"<input id=\\\"button-name\\\" name=\\\"button-name\\\" src=\\\"/mvc.gif\\\" type=\\\"image\\\" />\", button.ToHtmlString());\n        }\n\n        [Fact]\n        public void SubmitImageWithImageUrlStartingWithTildeRendersAppPath()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelperWithPath(new ViewDataDictionary(), \"/app\");\n            MvcHtmlString button = html.SubmitImage(\"button-name\", \"~/mvc.gif\");\n            Assert.Equal(\"<input id=\\\"button-name\\\" name=\\\"button-name\\\" src=\\\"/app/mvc.gif\\\" type=\\\"image\\\" />\", button.ToHtmlString());\n        }\n\n        [Fact]\n        public void SubmitImageWithNameAndIdRendersBothAttributesCorrectly()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            MvcHtmlString button = html.SubmitImage(\"button-name\", \"/mvc.png\", new { id = \"button-id\" });\n            Assert.Equal(\"<input id=\\\"button-id\\\" name=\\\"button-name\\\" src=\\\"/mvc.png\\\" type=\\\"image\\\" />\", button.ToHtmlString());\n        }\n\n        [Fact]\n        public void SubmitButtonWithNameAndValueSpecifiedAndPassedInAsAttributeChoosesExplicitAttributes()\n        {\n            HtmlHelper html = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            MvcHtmlString button = html.SubmitImage(\"specified-name\", \"/specified-src.bmp\", new RouteValueDictionary(new { name = \"name-attribute\", src = \"src-attribute\" }));\n            Assert.Equal(\"<input id=\\\"specified-name\\\" name=\\\"name-attribute\\\" src=\\\"src-attribute\\\" type=\\\"image\\\" />\", button.ToHtmlString());\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/TempDataValueProviderFactoryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class TempDataValueProviderFactoryTest\n    {\n        [Fact]\n        public void GetValueProvider_CorrectlyRetainsOrRemovesKeys()\n        {\n            // Arrange\n            string[] expectedRetainedKeys = new[]\n            {\n                \"retainMe\"\n            };\n\n            TempDataDictionary tempData = new TempDataDictionary\n            {\n                { \"retainMe\", \"retainMeValue\" },\n                { \"removeMe\", \"removeMeValue\" },\n                { \"previouslyRemoved\", \"previouslyRemovedValue\" }\n            };\n            object dummy = tempData[\"previouslyRemoved\"]; // mark value for removal\n\n            ControllerContext controllerContext = GetControllerContext(tempData);\n\n            TempDataValueProviderFactory factory = new TempDataValueProviderFactory();\n\n            // Act\n            IValueProvider valueProvider = factory.GetValueProvider(controllerContext);\n            ValueProviderResult nonExistentResult = valueProvider.GetValue(\"nonExistent\");\n            ValueProviderResult removeMeResult = valueProvider.GetValue(\"removeme\");\n\n            // Assert\n            Assert.Null(nonExistentResult);\n            Assert.Equal(\"removeMeValue\", removeMeResult.AttemptedValue);\n            Assert.Equal(CultureInfo.InvariantCulture, removeMeResult.Culture);\n\n            // Verify that keys have been removed or retained correctly by the provider\n            Mock<ITempDataProvider> mockTempDataProvider = new Mock<ITempDataProvider>();\n            string[] retainedKeys = null;\n            mockTempDataProvider\n                .Setup(o => o.SaveTempData(controllerContext, It.IsAny<IDictionary<string, object>>()))\n                .Callback(\n                    delegate(ControllerContext cc, IDictionary<string, object> d) { retainedKeys = d.Keys.ToArray(); });\n\n            tempData.Save(controllerContext, mockTempDataProvider.Object);\n            Assert.Equal(expectedRetainedKeys, retainedKeys);\n        }\n\n        [Fact]\n        public void GetValueProvider_EmptyTempData_ReturnsNull()\n        {\n            // Arrange\n            TempDataDictionary tempData = new TempDataDictionary();\n            ControllerContext controllerContext = GetControllerContext(tempData);\n\n            TempDataValueProviderFactory factory = new TempDataValueProviderFactory();\n\n            // Act\n            IValueProvider provider = factory.GetValueProvider(controllerContext);\n\n            // Assert\n            Assert.Null(provider);\n        }\n\n        private static ControllerContext GetControllerContext(TempDataDictionary tempData)\n        {\n            return new ControllerContext\n            {\n                Controller = new EmptyController\n                {\n                    TempData = tempData\n                }\n            };\n        }\n\n        private sealed class EmptyController : Controller\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/TypeHelpersTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class TypeHelpersTest\n    {\n        [Fact]\n        public void GetTypeArgumentsIfMatch_ClosedTypeIsGenericAndMatches_ReturnsType()\n        {\n            // Act\n            Type[] typeArguments = TypeHelpers.GetTypeArgumentsIfMatch(typeof(List<int>), typeof(List<>));\n\n            // Assert\n            Assert.Equal(new[] { typeof(int) }, typeArguments);\n        }\n\n        [Fact]\n        public void GetTypeArgumentsIfMatch_ClosedTypeIsGenericButDoesNotMatch_ReturnsNull()\n        {\n            // Act\n            Type[] typeArguments = TypeHelpers.GetTypeArgumentsIfMatch(typeof(int?), typeof(List<>));\n\n            // Assert\n            Assert.Null(typeArguments);\n        }\n\n        [Fact]\n        public void GetTypeArgumentsIfMatch_ClosedTypeIsNotGeneric_ReturnsNull()\n        {\n            // Act\n            Type[] typeArguments = TypeHelpers.GetTypeArgumentsIfMatch(typeof(int), null);\n\n            // Assert\n            Assert.Null(typeArguments);\n        }\n\n        [Fact]\n        public void IsCompatibleObjectReturnsTrueIfTypeIsNotNullableAndValueIsNull()\n        {\n            // Act\n            bool retVal = TypeHelpers.IsCompatibleObject(typeof(int), null);\n\n            // Assert\n            Assert.False(retVal);\n        }\n\n        [Fact]\n        public void IsCompatibleObjectReturnsFalseIfValueIsIncorrectType()\n        {\n            // Arrange\n            object value = new[] { \"Hello\", \"world\" };\n\n            // Act\n            bool retVal = TypeHelpers.IsCompatibleObject(typeof(int), value);\n\n            // Assert\n            Assert.False(retVal);\n        }\n\n        [Fact]\n        public void IsCompatibleObjectReturnsTrueIfTypeIsNullableAndValueIsNull()\n        {\n            // Act\n            bool retVal = TypeHelpers.IsCompatibleObject(typeof(int?), null);\n\n            // Assert\n            Assert.True(retVal);\n        }\n\n        [Fact]\n        public void IsCompatibleObjectReturnsTrueIfValueIsOfCorrectType()\n        {\n            // Arrange\n            object value = new[] { \"Hello\", \"world\" };\n\n            // Act\n            bool retVal = TypeHelpers.IsCompatibleObject(typeof(IEnumerable<string>), value);\n\n            // Assert\n            Assert.True(retVal);\n        }\n\n        [Fact]\n        public void TypeAllowsNullValueReturnsFalseForNonNullableGenericValueType()\n        {\n            Assert.False(TypeHelpers.TypeAllowsNullValue(typeof(KeyValuePair<int, string>)));\n        }\n\n        [Fact]\n        public void TypeAllowsNullValueReturnsFalseForNonNullableGenericValueTypeDefinition()\n        {\n            Assert.False(TypeHelpers.TypeAllowsNullValue(typeof(KeyValuePair<,>)));\n        }\n\n        [Fact]\n        public void TypeAllowsNullValueReturnsFalseForNonNullableValueType()\n        {\n            Assert.False(TypeHelpers.TypeAllowsNullValue(typeof(int)));\n        }\n\n        [Fact]\n        public void TypeAllowsNullValueReturnsTrueForInterfaceType()\n        {\n            Assert.True(TypeHelpers.TypeAllowsNullValue(typeof(IDisposable)));\n        }\n\n        [Fact]\n        public void TypeAllowsNullValueReturnsTrueForNullableType()\n        {\n            Assert.True(TypeHelpers.TypeAllowsNullValue(typeof(int?)));\n        }\n\n        [Fact]\n        public void TypeAllowsNullValueReturnsTrueForReferenceType()\n        {\n            Assert.True(TypeHelpers.TypeAllowsNullValue(typeof(object)));\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/UrlAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class UrlAttributeTest\n    {\n        [Fact]\n        public void ClientRule()\n        {\n            // Arrange\n            var attribute = new UrlAttribute();\n            var provider = new Mock<ModelMetadataProvider>();\n            var metadata = new ModelMetadata(provider.Object, null, null, typeof(string), \"PropertyName\");\n\n            // Act\n            ModelClientValidationRule clientRule = attribute.GetClientValidationRules(metadata, null).Single();\n\n            // Assert\n            Assert.Equal(\"url\", clientRule.ValidationType);\n            Assert.Equal(\"The PropertyName field is not a valid fully-qualified http, https, or ftp URL.\", clientRule.ErrorMessage);\n            Assert.Empty(clientRule.ValidationParameters);\n        }\n\n        [Fact]\n        public void IsValidTests()\n        {\n            // Arrange\n            var attribute = new UrlAttribute();\n\n            // Act & Assert\n            Assert.True(attribute.IsValid(null)); // Optional values are always valid\n            Assert.True(attribute.IsValid(\"http://foo.bar\"));\n            Assert.True(attribute.IsValid(\"https://foo.bar\"));\n            Assert.True(attribute.IsValid(\"ftp://foo.bar\"));\n            Assert.False(attribute.IsValid(\"file:///foo.bar\"));\n            Assert.False(attribute.IsValid(\"http://user%password@foo.bar/\"));\n            Assert.False(attribute.IsValid(\"foo.png\"));\n            Assert.False(attribute.IsValid(\"\\0foo.png\")); // Illegal character\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/ValueProviderUtilTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Mvc.Test\n{\n    public class ValueProviderUtilTest\n    {\n        [Fact]\n        public void IsPrefixMatch_Misses()\n        {\n            // Arrange\n            var tests = new[]\n            {\n                new { Prefix = \"Prefix\", TestString = (string)null, Reason = \"Null test string shouldn't match anything.\" },\n                new { Prefix = \"Foo\", TestString = \"NotFoo\", Reason = \"Prefix 'foo' doesn't match 'notfoo'.\" },\n                new { Prefix = \"Foo\", TestString = \"FooBar\", Reason = \"Prefix 'foo' was not followed by a delimiter in the test string.\" }\n            };\n\n            // Act & assert\n            foreach (var test in tests)\n            {\n                bool retVal = ValueProviderUtil.IsPrefixMatch(test.Prefix, test.TestString);\n                Assert.False(retVal, test.Reason);\n            }\n        }\n\n        [Fact]\n        public void IsPrefixMatch_Hits()\n        {\n            // Arrange\n            var tests = new[]\n            {\n                new { Prefix = \"\", TestString = \"SomeTestString\", Reason = \"Empty prefix should match any non-null test string.\" },\n                new { Prefix = \"SomeString\", TestString = \"SomeString\", Reason = \"This was an exact match.\" },\n                new { Prefix = \"Foo\", TestString = \"foo.bar\", Reason = \"Prefix 'foo' matched.\" },\n                new { Prefix = \"Foo\", TestString = \"foo[bar]\", Reason = \"Prefix 'foo' matched.\" },\n            };\n\n            // Act & assert\n            foreach (var test in tests)\n            {\n                bool retVal = ValueProviderUtil.IsPrefixMatch(test.Prefix, test.TestString);\n                Assert.True(retVal, test.Reason);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/Test/VersionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.Test\n{\n    public class VersionTest\n    {\n        [Fact]\n        public void VerifyMVCVersionChangesAreIntentional()\n        {\n            Version mvcVersion = VersionTestHelper.GetVersionFromAssembly(\"System.Web.Mvc\", typeof(Controller));\n            Assert.Equal(new Version(5, 3, 0, 0), mvcVersion);\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.Mvc.Test/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Castle.Core\" version=\"5.1.1\" targetFramework=\"net462\" />\n  <package id=\"Moq\" version=\"4.18.4\" targetFramework=\"net462\" />\n  <package id=\"Newtonsoft.Json\" version=\"13.0.1\" targetFramework=\"net462\" />\n  <package id=\"xunit\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.abstractions\" version=\"2.0.3\" targetFramework=\"net462\" />\n  <package id=\"xunit.analyzers\" version=\"1.1.0\" targetFramework=\"net462\" />\n  <package id=\"xunit.assert\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.execution\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.runner.visualstudio\" version=\"2.4.5\" targetFramework=\"net462\" developmentDependency=\"true\" />\n</packages>"
  },
  {
    "path": "test/Microsoft.Web.WebPages.OAuth.Test/Microsoft.Web.WebPages.OAuth.Test.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props\" Condition=\"Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" />\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" />\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{694C6EDF-EA52-438F-B745-82B025ECC0E7}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>Microsoft.Web.WebPages.OAuth.Test</RootNamespace>\n    <AssemblyName>Microsoft.Web.WebPages.OAuth.Test</AssemblyName>\n    <OutputPath>..\\..\\bin\\$(Configuration)\\Test\\</OutputPath>\n    <NuGetPackageImportStamp>\n    </NuGetPackageImportStamp>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Castle.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Castle.Core.5.1.1\\lib\\net462\\Castle.Core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"DotNetOpenAuth.AspNet, Version=4.0.0.0, Culture=neutral, PublicKeyToken=2780ccd10d57b246, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\..\\packages\\DotNetOpenAuth.AspNet.4.0.3.12153\\lib\\net40-full\\DotNetOpenAuth.AspNet.dll</HintPath>\n    </Reference>\n    <Reference Include=\"DotNetOpenAuth.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=2780ccd10d57b246, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\..\\packages\\DotNetOpenAuth.Core.4.0.3.12153\\lib\\net40-full\\DotNetOpenAuth.Core.dll</HintPath>\n    </Reference>\n    <Reference Include=\"DotNetOpenAuth.OAuth, Version=4.0.0.0, Culture=neutral, PublicKeyToken=2780ccd10d57b246, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\..\\packages\\DotNetOpenAuth.OAuth.Core.4.0.3.12153\\lib\\net40-full\\DotNetOpenAuth.OAuth.dll</HintPath>\n    </Reference>\n    <Reference Include=\"DotNetOpenAuth.OAuth.Consumer, Version=4.0.0.0, Culture=neutral, PublicKeyToken=2780ccd10d57b246, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\..\\packages\\DotNetOpenAuth.OAuth.Consumer.4.0.3.12153\\lib\\net40-full\\DotNetOpenAuth.OAuth.Consumer.dll</HintPath>\n    </Reference>\n    <Reference Include=\"DotNetOpenAuth.OpenId, Version=4.0.0.0, Culture=neutral, PublicKeyToken=2780ccd10d57b246, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\..\\packages\\DotNetOpenAuth.OpenId.Core.4.0.3.12153\\lib\\net40-full\\DotNetOpenAuth.OpenId.dll</HintPath>\n    </Reference>\n    <Reference Include=\"DotNetOpenAuth.OpenId.RelyingParty, Version=4.0.0.0, Culture=neutral, PublicKeyToken=2780ccd10d57b246, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\..\\packages\\DotNetOpenAuth.OpenId.RelyingParty.4.0.3.12153\\lib\\net40-full\\DotNetOpenAuth.OpenId.RelyingParty.dll</HintPath>\n    </Reference>\n    <Reference Include=\"Moq, Version=4.18.0.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Moq.4.18.4\\lib\\net462\\Moq.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.abstractions.2.0.3\\lib\\net35\\xunit.abstractions.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.assert, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.assert.2.4.2\\lib\\netstandard1.1\\xunit.assert.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.core, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.core.2.4.2\\lib\\net452\\xunit.core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.execution.desktop, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.execution.2.4.2\\lib\\net452\\xunit.execution.desktop.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"OAuthWebSecurityTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"PreAppStartCodeTest.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\..\\src\\Microsoft.Web.WebPages.OAuth\\Microsoft.Web.WebPages.OAuth.csproj\">\n      <Project>{4CBFC7D3-1600-4CE5-BC6B-AC7BC2D6F853}</Project>\n      <Name>Microsoft.Web.WebPages.OAuth</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\">\n      <Project>{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}</Project>\n      <Name>Microsoft.TestCommon</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <Service Include=\"{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Analyzer Include=\"..\\..\\packages\\xunit.analyzers.1.1.0\\analyzers\\dotnet\\cs\\xunit.analyzers.dll\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  <Target Name=\"EnsureNuGetPackageBuildImports\" BeforeTargets=\"PrepareForBuild\">\n    <PropertyGroup>\n      <ErrorText>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}.</ErrorText>\n    </PropertyGroup>\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props'))\" />\n  </Target>\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" />\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.\n       Other similar extension points exist, see Microsoft.Common.targets.\n  <Target Name=\"BeforeBuild\">\n  </Target>\n  <Target Name=\"AfterBuild\">\n  </Target>\n  -->\n</Project>"
  },
  {
    "path": "test/Microsoft.Web.WebPages.OAuth.Test/OAuthWebSecurityTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Specialized;\nusing System.Linq;\nusing System.Web;\nusing System.Web.Security;\nusing DotNetOpenAuth.AspNet;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace Microsoft.Web.WebPages.OAuth.Test\n{\n    public class OAuthWebSecurityTest : IDisposable\n    {\n        [Fact]\n        public void RegisterClientThrowsOnNullValue()\n        {\n            Assert.ThrowsArgumentNull(() => OAuthWebSecurity.RegisterClient(null), \"client\");\n        }\n\n        [Fact]\n        public void RegisterClientThrowsIfProviderNameIsEmpty()\n        {\n            // Arrange\n            var client = new Mock<IAuthenticationClient>();\n            client.Setup(c => c.ProviderName).Returns((string)null);\n\n            // Act & Assert\n            Assert.ThrowsArgument(() => OAuthWebSecurity.RegisterClient(client.Object), \"client\");\n\n            client.Setup(c => c.ProviderName).Returns(\"\");\n\n            // Act & Assert\n            Assert.ThrowsArgument(() => OAuthWebSecurity.RegisterClient(client.Object), \"client\");\n        }\n\n        [Fact]\n        public void RegisterClientThrowsRegisterMoreThanOneClientWithTheSameName()\n        {\n            // Arrange\n            var client1 = new Mock<IAuthenticationClient>();\n            client1.Setup(c => c.ProviderName).Returns(\"provider\");\n\n            var client2 = new Mock<IAuthenticationClient>();\n            client2.Setup(c => c.ProviderName).Returns(\"provider\");\n\n            OAuthWebSecurity.RegisterClient(client1.Object);\n\n            // Act & Assert\n            Assert.ThrowsArgument(() => OAuthWebSecurity.RegisterClient(client2.Object), null);\n        }\n\n        [Fact]\n        public void RequestAuthenticationRedirectsToProviderWithNullReturnUrl()\n        {\n            var cookies = new HttpCookieCollection();\n\n            // Arrange\n            var context = new Mock<HttpContextBase>();\n            context.Setup(c => c.Response.Cookies).Returns(cookies);\n            context.Setup(c => c.Request.ServerVariables).Returns(new NameValueCollection());\n            context.Setup(c => c.Request.Url).Returns(new Uri(\"http://live.com/login.aspx\"));\n            context.Setup(c => c.Request.RawUrl).Returns(\"/login.aspx\");\n            context.Setup(c => c.User.Identity.IsAuthenticated).Returns(false);\n\n            var client = new Mock<IAuthenticationClient>();\n            client.Setup(c => c.ProviderName).Returns(\"windowslive\");\n            client.Setup(c => c.RequestAuthentication(\n                                    context.Object,\n                                    It.Is<Uri>(u => u.AbsoluteUri.StartsWith(\"http://live.com/login.aspx?__provider__=windowslive\", StringComparison.OrdinalIgnoreCase))))\n                  .Verifiable();\n\n            OAuthWebSecurity.RegisterClient(client.Object);\n\n            // Act\n            OAuthWebSecurity.RequestAuthenticationCore(context.Object, \"windowslive\", null);\n\n            // Assert\n            client.Verify();\n        }\n\n        [Fact]\n        public void RequestAuthenticationRedirectsToProviderWithReturnUrl()\n        {\n            var cookies = new HttpCookieCollection();\n\n            // Arrange\n            var context = new Mock<HttpContextBase>();\n            context.Setup(c => c.Request.ServerVariables).Returns(new NameValueCollection());\n            context.Setup(c => c.Request.Url).Returns(new Uri(\"http://live.com/login.aspx\"));\n            context.Setup(c => c.Request.RawUrl).Returns(\"/login.aspx\");\n            context.Setup(c => c.Response.Cookies).Returns(cookies);\n            context.Setup(c => c.User.Identity.IsAuthenticated).Returns(false);\n\n            var client = new Mock<IAuthenticationClient>();\n            client.Setup(c => c.ProviderName).Returns(\"yahoo\");\n            client.Setup(c => c.RequestAuthentication(\n                                    context.Object,\n                                    It.Is<Uri>(u => u.AbsoluteUri.StartsWith(\"http://yahoo.com/?__provider__=yahoo\", StringComparison.OrdinalIgnoreCase))))\n                  .Verifiable();\n\n            OAuthWebSecurity.RegisterClient(client.Object);\n\n            // Act\n            OAuthWebSecurity.RequestAuthenticationCore(context.Object, \"yahoo\", \"http://yahoo.com\");\n\n            // Assert\n            client.Verify();\n        }\n\n        [Fact]\n        public void VerifyAuthenticationFail()\n        {\n            // Arrange\n            var queryStrings = new NameValueCollection();\n            queryStrings.Add(\"__provider__\", \"twitter\");\n\n            var context = new Mock<HttpContextBase>();\n            context.Setup(c => c.Request.QueryString).Returns(queryStrings);\n\n            var client = new Mock<IAuthenticationClient>(MockBehavior.Strict);\n            client.Setup(c => c.ProviderName).Returns(\"facebook\");\n            client.Setup(c => c.VerifyAuthentication(context.Object)).Returns(new AuthenticationResult(true, \"facebook\", \"123\",\n                                                                                                \"super\", null));\n\n            var anotherClient = new Mock<IAuthenticationClient>(MockBehavior.Strict);\n            anotherClient.Setup(c => c.ProviderName).Returns(\"twitter\");\n            anotherClient.Setup(c => c.VerifyAuthentication(context.Object)).Returns(AuthenticationResult.Failed);\n\n            OAuthWebSecurity.RegisterClient(client.Object);\n            OAuthWebSecurity.RegisterClient(anotherClient.Object);\n\n            // Act\n            AuthenticationResult result = OAuthWebSecurity.VerifyAuthenticationCore(context.Object, \"one.aspx\");\n\n            // Assert\n            Assert.False(result.IsSuccessful);\n            Assert.Equal(\"twitter\", result.Provider);\n        }\n\n        [Fact]\n        public void VerifyAuthenticationFailIfNoProviderInQueryString()\n        {\n            // Arrange\n            var context = new Mock<HttpContextBase>();\n            context.Setup(c => c.Request.QueryString).Returns(new NameValueCollection());\n\n            var client = new Mock<IAuthenticationClient>(MockBehavior.Strict);\n            client.Setup(c => c.ProviderName).Returns(\"facebook\");\n\n            var anotherClient = new Mock<IAuthenticationClient>(MockBehavior.Strict);\n            anotherClient.Setup(c => c.ProviderName).Returns(\"twitter\");\n\n            OAuthWebSecurity.RegisterClient(client.Object);\n            OAuthWebSecurity.RegisterClient(anotherClient.Object);\n\n            // Act\n            AuthenticationResult result = OAuthWebSecurity.VerifyAuthenticationCore(context.Object, \"\");\n\n            // Assert\n            Assert.False(result.IsSuccessful);\n            Assert.Null(result.Provider);\n        }\n\n        [Fact]\n        public void LoginSetAuthenticationTicketIfSuccessful()\n        {\n            var originalProvider = OAuthWebSecurity.OAuthDataProvider;\n            try\n            {\n                // Arrange\n                var cookies = new HttpCookieCollection();\n                var context = new Mock<HttpContextBase>();\n                context.Setup(c => c.Request.IsSecureConnection).Returns(true);\n                context.Setup(c => c.Response.Cookies).Returns(cookies);\n\n                var dataProvider = new Mock<IOpenAuthDataProvider>(MockBehavior.Strict);\n                dataProvider.Setup(p => p.GetUserNameFromOpenAuth(\"twitter\", \"12345\")).Returns(\"hola\");\n                OAuthWebSecurity.OAuthDataProvider = dataProvider.Object;\n\n                OAuthWebSecurity.RegisterTwitterClient(\"sdfdsfsd\", \"dfdsfdsf\");\n\n                // Act\n                bool successful = OAuthWebSecurity.LoginCore(context.Object, \"twitter\", \"12345\", createPersistentCookie: false);\n\n                // Assert\n                Assert.True(successful);\n\n                Assert.Single(cookies);\n                HttpCookie addedCookie = cookies[0];\n\n                Assert.Equal(FormsAuthentication.FormsCookieName, addedCookie.Name);\n                Assert.True(addedCookie.HttpOnly);\n                Assert.Equal(\"/\", addedCookie.Path);\n                Assert.False(addedCookie.Secure);\n                Assert.False(String.IsNullOrEmpty(addedCookie.Value));\n\n                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(addedCookie.Value);\n                Assert.NotNull(ticket);\n                Assert.Equal(2, ticket.Version);\n                Assert.Equal(\"hola\", ticket.Name);\n                Assert.Equal(\"OAuth\", ticket.UserData);\n                Assert.False(ticket.IsPersistent);\n            }\n            finally\n            {\n                OAuthWebSecurity.OAuthDataProvider = originalProvider;\n            }\n        }\n\n        [Fact]\n        public void LoginFailIfUserIsNotFound()\n        {\n            var originalProvider = OAuthWebSecurity.OAuthDataProvider;\n            try\n            {\n                // Arrange\n                var context = new Mock<HttpContextBase>();\n                OAuthWebSecurity.RegisterTwitterClient(\"consumerKey\", \"consumerSecrte\");\n\n                var dataProvider = new Mock<IOpenAuthDataProvider>();\n                dataProvider.Setup(p => p.GetUserNameFromOpenAuth(\"twitter\", \"12345\")).Returns((string)null);\n                OAuthWebSecurity.OAuthDataProvider = dataProvider.Object;\n\n                // Act\n                bool successful = OAuthWebSecurity.LoginCore(context.Object, \"twitter\", \"12345\", createPersistentCookie: false);\n\n                // Assert\n                Assert.False(successful);\n            }\n            finally\n            {\n                OAuthWebSecurity.OAuthDataProvider = originalProvider;\n            }\n        }\n\n        [Fact]\n        public void GetOAuthClientReturnsTheCorrectClient()\n        {\n            // Arrange\n            var client = new Mock<IAuthenticationClient>();\n            client.Setup(c => c.ProviderName).Returns(\"facebook\");\n            OAuthWebSecurity.RegisterClient(client.Object);\n\n            var anotherClient = new Mock<IAuthenticationClient>();\n            anotherClient.Setup(c => c.ProviderName).Returns(\"hulu\");\n            OAuthWebSecurity.RegisterClient(anotherClient.Object);\n\n            // Act\n            var expectedClient = OAuthWebSecurity.GetOAuthClient(\"facebook\");\n\n            // Assert\n            Assert.Same(expectedClient, client.Object);\n        }\n\n        [Fact]\n        public void GetOAuthClientThrowsIfClientIsNotFound()\n        {\n            // Arrange\n            var client = new Mock<IAuthenticationClient>();\n            client.Setup(c => c.ProviderName).Returns(\"facebook\");\n            OAuthWebSecurity.RegisterClient(client.Object);\n\n            var anotherClient = new Mock<IAuthenticationClient>();\n            anotherClient.Setup(c => c.ProviderName).Returns(\"hulu\");\n            OAuthWebSecurity.RegisterClient(anotherClient.Object);\n\n            // Act & Assert\n            Assert.Throws<ArgumentException>(() => OAuthWebSecurity.GetOAuthClient(\"live\"));\n        }\n\n        [Fact]\n        public void TryGetOAuthClientSucceeds()\n        {\n            // Arrange\n            var client = new Mock<IAuthenticationClient>();\n            client.Setup(c => c.ProviderName).Returns(\"facebook\");\n            OAuthWebSecurity.RegisterClient(client.Object);\n\n            var anotherClient = new Mock<IAuthenticationClient>();\n            anotherClient.Setup(c => c.ProviderName).Returns(\"hulu\");\n            OAuthWebSecurity.RegisterClient(anotherClient.Object);\n\n            // Act\n            IAuthenticationClient expectedClient;\n            bool result = OAuthWebSecurity.TryGetOAuthClient(\"facebook\", out expectedClient);\n\n            // Assert\n            Assert.Same(expectedClient, client.Object);\n            Assert.True(result);\n        }\n\n        [Fact]\n        public void TryGetOAuthClientFail()\n        {\n            // Arrange\n            var client = new Mock<IAuthenticationClient>();\n            client.Setup(c => c.ProviderName).Returns(\"facebook\");\n            OAuthWebSecurity.RegisterClient(client.Object);\n\n            var anotherClient = new Mock<IAuthenticationClient>();\n            anotherClient.Setup(c => c.ProviderName).Returns(\"hulu\");\n            OAuthWebSecurity.RegisterClient(anotherClient.Object);\n\n            // Act\n            IAuthenticationClient expectedClient;\n            bool result = OAuthWebSecurity.TryGetOAuthClient(\"live\", out expectedClient);\n\n            // Assert\n            Assert.Null(expectedClient);\n            Assert.False(result);\n        }\n\n        [Fact]\n        public void TestRegisterFacebookClient()\n        {\n            // Arrange\n            OAuthWebSecurity.RegisterFacebookClient(\"one\", \"two\", displayName: \"FB\", extraData: null);\n\n            // Act\n            var data = OAuthWebSecurity.RegisteredClientData;\n\n            // Assert\n            Assert.True(data.IsReadOnly);\n            Assert.Equal(1, data.Count);\n            Assert.Equal(\"facebook\", data.First().AuthenticationClient.ProviderName);\n            Assert.Equal(\"FB\", data.First().DisplayName);\n            Assert.Null(data.First().ExtraData);\n        }\n\n        [Fact]\n        public void TestRegisterMicrosoftClient()\n        {\n            // Arrange\n            OAuthWebSecurity.RegisterMicrosoftClient(\"one\", \"two\", displayName: \"MS\", extraData: null);\n\n            // Act\n            var data = OAuthWebSecurity.RegisteredClientData;\n\n            // Assert\n            Assert.True(data.IsReadOnly);\n            Assert.Equal(1, data.Count);\n            Assert.Equal(\"microsoft\", data.First().AuthenticationClient.ProviderName);\n            Assert.Equal(\"MS\", data.First().DisplayName);\n            Assert.Null(data.First().ExtraData);\n        }\n\n        [Fact]\n        public void TestRegisterTwitterClient()\n        {\n            // Arrange\n            OAuthWebSecurity.RegisterTwitterClient(\"x0\", \"y0\", displayName: \"Tweet\", extraData: null);\n\n            // Act\n            var data = OAuthWebSecurity.RegisteredClientData;\n\n            // Assert\n            Assert.True(data.IsReadOnly);\n            Assert.Equal(1, data.Count);\n            Assert.Equal(\"twitter\", data.First().AuthenticationClient.ProviderName);\n            Assert.Equal(\"Tweet\", data.First().DisplayName);\n            Assert.Null(data.First().ExtraData);\n        }\n\n        [Fact]\n        public void TestRegisterLinkedInClient()\n        {\n            // Arrange\n            OAuthWebSecurity.RegisterLinkedInClient(\"x0\", \"y0\", displayName: \"LINKED\", extraData: null);\n\n            // Act\n            var data = OAuthWebSecurity.RegisteredClientData;\n\n            // Assert\n            Assert.True(data.IsReadOnly);\n            Assert.Equal(1, data.Count);\n            Assert.Equal(\"linkedIn\", data.First().AuthenticationClient.ProviderName);\n            Assert.Equal(\"LINKED\", data.First().DisplayName);\n            Assert.Null(data.First().ExtraData);\n        }\n\n        [Fact]\n        public void TestRegisterGoogleClient()\n        {\n            // Arrange\n            OAuthWebSecurity.RegisterGoogleClient(displayName: \"GOOG\", extraData: null);\n\n            // Act\n            var data = OAuthWebSecurity.RegisteredClientData;\n\n            // Assert\n            Assert.True(data.IsReadOnly);\n            Assert.Equal(1, data.Count);\n            Assert.Equal(\"google\", data.First().AuthenticationClient.ProviderName);\n            Assert.Equal(\"GOOG\", data.First().DisplayName);\n            Assert.Null(data.First().ExtraData);\n        }\n\n        [Fact]\n        public void TestRegisterYahooClient()\n        {\n            // Arrange\n            OAuthWebSecurity.RegisterYahooClient(displayName: \"YHOO\", extraData: null);\n\n            // Act\n            var data = OAuthWebSecurity.RegisteredClientData;\n\n            // Assert\n            Assert.True(data.IsReadOnly);\n            Assert.Equal(1, data.Count);\n            Assert.Equal(\"yahoo\", data.First().AuthenticationClient.ProviderName);\n            Assert.Equal(\"YHOO\", data.First().DisplayName);\n            Assert.Null(data.First().ExtraData);\n        }\n\n        public void Dispose()\n        {\n            OAuthWebSecurity.ClearProviders();\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.WebPages.OAuth.Test/PreAppStartCodeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\n\nnamespace Microsoft.Web.WebPages.OAuth.Test\n{\n    public class PreAppStartCodeTest\n    {\n        [Fact]\n        public void TestPreAppStartClass()\n        {\n            PreAppStartTestHelper.TestPreAppStartClass(typeof(PreApplicationStartCode));\n        }\n    }\n}\n"
  },
  {
    "path": "test/Microsoft.Web.WebPages.OAuth.Test/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Castle.Core\" version=\"5.1.1\" targetFramework=\"net462\" />\n  <package id=\"DotNetOpenAuth.AspNet\" version=\"4.0.3.12153\" targetFramework=\"net462\" />\n  <package id=\"DotNetOpenAuth.Core\" version=\"4.0.3.12153\" targetFramework=\"net462\" />\n  <package id=\"DotNetOpenAuth.OAuth.Consumer\" version=\"4.0.3.12153\" targetFramework=\"net462\" />\n  <package id=\"DotNetOpenAuth.OAuth.Core\" version=\"4.0.3.12153\" targetFramework=\"net462\" />\n  <package id=\"DotNetOpenAuth.OpenId.Core\" version=\"4.0.3.12153\" targetFramework=\"net462\" />\n  <package id=\"DotNetOpenAuth.OpenId.RelyingParty\" version=\"4.0.3.12153\" targetFramework=\"net462\" />\n  <package id=\"Moq\" version=\"4.18.4\" targetFramework=\"net462\" />\n  <package id=\"xunit\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.abstractions\" version=\"2.0.3\" targetFramework=\"net462\" />\n  <package id=\"xunit.analyzers\" version=\"1.1.0\" targetFramework=\"net462\" />\n  <package id=\"xunit.assert\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.execution\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.runner.visualstudio\" version=\"2.4.5\" targetFramework=\"net462\" developmentDependency=\"true\" />\n</packages>"
  },
  {
    "path": "test/Settings.StyleCop",
    "content": "<StyleCopSettings Version=\"105\">\n  <GlobalSettings>\n    <StringProperty Name=\"MergeSettingsFiles\">Parent</StringProperty>\n  </GlobalSettings>\n  <Analyzers>\n    <Analyzer AnalyzerId=\"Microsoft.Web.StyleCop.Rules\">\n      <Rules>\n        <Rule Name=\"DoNotUseBuiltInTypeAliasInExpression\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n      </Rules>\n      <AnalyzerSettings />\n    </Analyzer>\n    <Analyzer AnalyzerId=\"StyleCop.CSharp.DocumentationRules\">\n      <AnalyzerSettings>\n        <BooleanProperty Name=\"IncludeFields\">False</BooleanProperty>\n      </AnalyzerSettings>\n    </Analyzer>\n    <Analyzer AnalyzerId=\"StyleCop.CSharp.LayoutRules\">\n      <Rules>\n        <Rule Name=\"CurlyBracketsForMultiLineStatementsMustNotShareLine\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"StatementMustNotBeOnSingleLine\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"ElementMustNotBeOnSingleLine\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"CurlyBracketsMustNotBeOmitted\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"CodeMustNotContainMultipleBlankLinesInARow\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"ClosingCurlyBracketsMustNotBePrecededByBlankLine\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"OpeningCurlyBracketsMustNotBePrecededByBlankLine\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n      </Rules>\n      <AnalyzerSettings />\n    </Analyzer>\n    <Analyzer AnalyzerId=\"StyleCop.CSharp.MaintainabilityRules\">\n      <Rules>\n        <Rule Name=\"AccessModifierMustBeDeclared\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"FileMayOnlyContainASingleClass\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"FileMayOnlyContainASingleNamespace\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"RemoveDelegateParenthesisWhenPossible\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n      </Rules>\n      <AnalyzerSettings />\n    </Analyzer>\n    <Analyzer AnalyzerId=\"StyleCop.CSharp.NamingRules\">\n      <Rules>\n        <Rule Name=\"ElementMustBeginWithUpperCaseLetter\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"ConstFieldNamesMustBeginWithUpperCaseLetter\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"FieldNamesMustNotUseHungarianNotation\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"FieldNamesMustBeginWithLowerCaseLetter\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"AccessibleFieldsMustBeginWithUpperCaseLetter\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"FieldNamesMustNotContainUnderscore\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n      </Rules>\n      <AnalyzerSettings />\n    </Analyzer>\n    <Analyzer AnalyzerId=\"StyleCop.CSharp.OrderingRules\">\n      <Rules>\n        <Rule Name=\"ElementsMustAppearInTheCorrectOrder\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n      </Rules>\n      <AnalyzerSettings />\n    </Analyzer>\n    <Analyzer AnalyzerId=\"StyleCop.CSharp.ReadabilityRules\">\n      <Rules>\n        <Rule Name=\"DoNotPrefixCallsWithBaseUnlessLocalImplementationExists\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"ClosingParenthesisMustBeOnLineOfLastParameter\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"UseStringEmptyForEmptyStrings\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"UseShorthandForNullableTypes\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n      </Rules>\n      <AnalyzerSettings />\n    </Analyzer>\n    <Analyzer AnalyzerId=\"StyleCop.CSharp.SpacingRules\">\n      <Rules>\n        <Rule Name=\"CommasMustBeSpacedCorrectly\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"SemicolonsMustBeSpacedCorrectly\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"SymbolsMustBeSpacedCorrectly\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"PreprocessorKeywordsMustNotBePrecededBySpace\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"ClosingParenthesisMustBeSpacedCorrectly\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"OpeningCurlyBracketsMustBeSpacedCorrectly\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n        <Rule Name=\"ClosingCurlyBracketsMustBeSpacedCorrectly\">\n          <RuleSettings>\n            <BooleanProperty Name=\"Enabled\">False</BooleanProperty>\n          </RuleSettings>\n        </Rule>\n      </Rules>\n      <AnalyzerSettings />\n    </Analyzer>\n  </Analyzers>\n</StyleCopSettings>"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/ByteRangeStreamContentTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Net.Http.Headers;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Net.Http\n{\n    public class ByteRangeStreamContentTest\n    {\n        private MediaTypeHeaderValue _expectedMediatype = MediaTypeHeaderValue.Parse(\"text/test\");\n\n        public static TheoryDataSet<string, int, string> SingleRanges\n        {\n            get\n            {\n                // string ranges, int innerStreamLength, string expectedContentRange)\n                return new TheoryDataSet<string, int, string>\n                {\n                    { \"bytes=0-9\", 10, \"bytes 0-9/10\" },\n                    { \"bytes=0-0\", 10, \"bytes 0-0/10\" },\n                    { \"bytes=9-9\", 10, \"bytes 9-9/10\" },\n                    { \"bytes=9-20\", 10, \"bytes 9-9/10\" },\n                    { \"bytes=1-\", 10, \"bytes 1-9/10\" },\n                    { \"bytes=8-\", 10, \"bytes 8-9/10\" },\n                    { \"bytes=9-\", 10, \"bytes 9-9/10\" },\n                    { \"bytes=-1\", 10, \"bytes 9-9/10\" },\n                    { \"bytes=-2\", 10, \"bytes 8-9/10\" },\n                    { \"bytes=-20\", 10, \"bytes 0-9/10\" },\n                    { \"bytes=-9\", 10, \"bytes 1-9/10\" },\n                    { \"bytes=-10\", 10, \"bytes 0-9/10\" },\n                };\n            }\n        }\n\n        public static TheoryDataSet<string, int, int, string[]> MultiRanges\n        {\n            get\n            {\n                // string ranges, int innerStreamLength, int expectedBodyparts, string[] contentRanges)\n                return new TheoryDataSet<string, int, int, string[]>\n                {\n                    { \"bytes=0-9,0-0\", 10, 2, new string[] { \"bytes 0-9/10\", \"bytes 0-0/10\" } },\n                    { \"bytes=0-0,0-9\", 10, 2, new string[] { \"bytes 0-0/10\", \"bytes 0-9/10\" } },\n                    { \"bytes=0-0,9-20\", 10, 2, new string[] { \"bytes 0-0/10\", \"bytes 9-9/10\" } },\n                    { \"bytes=0-0,9-9,9-20\", 10, 3, new string[] { \"bytes 0-0/10\", \"bytes 9-9/10\", \"bytes 9-9/10\" } },\n                    { \"bytes=0-0,9-9,10-20\", 10, 2, new string[] { \"bytes 0-0/10\", \"bytes 9-9/10\" } },\n                };\n            }\n        }\n\n        public static TheoryDataSet<string, int, string> NoOverlappingRanges\n        {\n            get\n            {\n                // string ranges, int innerStreamLength, string expectedContentRange)\n                return new TheoryDataSet<string, int, string>\n                {\n                    { \"bytes=100-\", 10, \"bytes */10\" },\n                    { \"bytes=100-,200-,300-\", 10, \"bytes */10\" },\n                };\n            }\n        }\n\n        [Fact]\n        public void Ctor_ThrowsOnNullContent()\n        {\n            RangeHeaderValue range = new RangeHeaderValue();\n            Assert.ThrowsArgumentNull(() => new ByteRangeStreamContent(\n                content: null,\n                range: range,\n                mediaType: _expectedMediatype,\n                bufferSize: 128),\n                \"content\");\n        }\n\n        [Fact]\n        public void Ctor_ThrowsIfCantSeekContent()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>();\n            mockInnerStream.Setup(s => s.CanSeek).Returns(false);\n            RangeHeaderValue range = new RangeHeaderValue();\n\n            // Act/Assert\n            Assert.ThrowsArgument(() => new ByteRangeStreamContent(\n                content: mockInnerStream.Object,\n                range: range,\n                mediaType: _expectedMediatype,\n                bufferSize: 128),\n                \"content\");\n        }\n\n        [Fact]\n        public void Ctor_ThrowsOnNullRange()\n        {\n            Assert.ThrowsArgumentNull(() => new ByteRangeStreamContent(\n                content: Stream.Null,\n                range: null,\n                mediaType: _expectedMediatype,\n                bufferSize: 128),\n                \"range\");\n        }\n\n        [Fact]\n        public void Ctor_ThrowsOnNullMediaType()\n        {\n            RangeHeaderValue range = new RangeHeaderValue();\n            Assert.ThrowsArgumentNull(() => new ByteRangeStreamContent(\n                content: Stream.Null,\n                range: range,\n                mediaType: (MediaTypeHeaderValue)null,\n                bufferSize: 128),\n                \"mediaType\");\n        }\n\n        [Fact]\n        public void Ctor_ThrowsOnNullMediaTypeString()\n        {\n            RangeHeaderValue range = new RangeHeaderValue();\n            Assert.ThrowsArgument(() => new ByteRangeStreamContent(\n                content: Stream.Null,\n                range: range,\n                mediaType: (String)null,\n                bufferSize: 128),\n                \"mediaType\",\n                allowDerivedExceptions: true);\n        }\n\n        [Fact]\n        public void Ctor_ThrowsOnInvalidBufferSize()\n        {\n            RangeHeaderValue range = new RangeHeaderValue();\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(() => new ByteRangeStreamContent(\n                content: Stream.Null,\n                range: range,\n                mediaType: _expectedMediatype,\n                bufferSize: 0),\n                \"bufferSize\", \"1\", \"0\");\n        }\n\n        [Fact]\n        public void Ctor_ThrowsOnNonByteRangeUnit()\n        {\n            RangeHeaderValue range = RangeHeaderValue.Parse(\"pages=0-9\");\n            Assert.ThrowsArgument(() => new ByteRangeStreamContent(\n                content: Stream.Null,\n                range: range,\n                mediaType: _expectedMediatype,\n                bufferSize: 128),\n                \"range\");\n        }\n\n        [Fact]\n        public void Ctor_ThrowsOnNoByteRanges()\n        {\n            RangeHeaderValue range = new RangeHeaderValue() { Unit = \"bytes\" };\n            Assert.ThrowsArgument(() => new ByteRangeStreamContent(\n                content: Stream.Null,\n                range: range,\n                mediaType: _expectedMediatype,\n                bufferSize: 128),\n                \"range\");\n        }\n\n        [Theory]\n        [InlineData(\"bytes=-1\")]\n        [InlineData(\"bytes=0-\")]\n        [InlineData(\"bytes=0-,10-20,9-9\")]\n        public void RangesOverZeroLengthStream(string ranges)\n        {\n            // Arrange\n            RangeHeaderValue range = RangeHeaderValue.Parse(ranges);\n\n            // Act\n            try\n            {\n                new ByteRangeStreamContent(Stream.Null, range, _expectedMediatype);\n            }\n            catch (InvalidByteRangeException invalidByteRangeException)\n            {\n                ContentRangeHeaderValue expectedContentRange = new ContentRangeHeaderValue(length: 0);\n                Assert.Equal(expectedContentRange, invalidByteRangeException.ContentRange);\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"SingleRanges\")]\n        public void SingleRangeGeneratesNonMultipartContent(string ranges, int innerStreamLength, string contentRange)\n        {\n            // Arrange\n            string data = new String('a', innerStreamLength);\n            byte[] bytes = Encoding.UTF8.GetBytes(data);\n            MemoryStream memStream = new MemoryStream(bytes);\n            RangeHeaderValue range = RangeHeaderValue.Parse(ranges);\n\n            // Act\n            ByteRangeStreamContent rangeContent = new ByteRangeStreamContent(memStream, range, _expectedMediatype);\n\n            // Assert\n            Assert.Equal(_expectedMediatype, rangeContent.Headers.ContentType);\n            ContentRangeHeaderValue expectedContentRange = ContentRangeHeaderValue.Parse(contentRange);\n            Assert.Equal(expectedContentRange, rangeContent.Headers.ContentRange);\n        }\n\n        [Theory]\n        [PropertyData(\"MultiRanges\")]\n        public async Task MultipleRangesGeneratesMultipartByteRangesContent(string ranges, int innerStreamLength, int expectedBodyparts, string[] contentRanges)\n        {\n            // Arrange\n            string data = new String('a', innerStreamLength);\n            byte[] bytes = Encoding.UTF8.GetBytes(data);\n            MemoryStream memStream = new MemoryStream(bytes);\n            RangeHeaderValue range = RangeHeaderValue.Parse(ranges);\n\n            // Act\n            ByteRangeStreamContent content = new ByteRangeStreamContent(memStream, range, _expectedMediatype);\n            MemoryStream result = new MemoryStream();\n            await content.CopyToAsync(result);\n            MultipartMemoryStreamProvider multipart = await content.ReadAsMultipartAsync();\n\n            // Assert\n            Assert.Equal(expectedBodyparts, multipart.Contents.Count);\n            for (int count = 0; count < multipart.Contents.Count; count++)\n            {\n                MediaTypeHeaderValue contentType = multipart.Contents[count].Headers.ContentType;\n                Assert.Equal(_expectedMediatype, contentType);\n\n                ContentRangeHeaderValue expectedContentRange = ContentRangeHeaderValue.Parse(contentRanges[count]);\n                ContentRangeHeaderValue contentRange = multipart.Contents[count].Headers.ContentRange;\n                Assert.Equal(expectedContentRange, contentRange);\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"NoOverlappingRanges\")]\n        public void NoOverlappingRangesThrowException(string ranges, int innerStreamLength, string contentRange)\n        {\n            // Arrange\n            string data = new String('a', innerStreamLength);\n            byte[] bytes = Encoding.UTF8.GetBytes(data);\n            MemoryStream memStream = new MemoryStream(bytes);\n            RangeHeaderValue range = RangeHeaderValue.Parse(ranges);\n\n            // Act\n            try\n            {\n                new ByteRangeStreamContent(memStream, range, _expectedMediatype);\n            }\n            catch (InvalidByteRangeException invalidByteRangeException)\n            {\n                ContentRangeHeaderValue expectedContentRange = ContentRangeHeaderValue.Parse(contentRange);\n                Assert.Equal(expectedContentRange, invalidByteRangeException.ContentRange);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/CustomMultipartFormDataRemoteStreamProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Net.Http.Headers;\nusing Moq;\n\nnamespace System.Net.Http\n{\n    public class CustomMultipartFormDataRemoteStreamProvider : MultipartFormDataRemoteStreamProvider\n    {\n        public readonly string UrlBase = \"http://some/path/to/\";\n\n        public readonly List<Stream> RemoteStreams = new List<Stream>();\n\n        private readonly bool _isResultNull;\n\n        public CustomMultipartFormDataRemoteStreamProvider()\n        {\n        }\n\n        public CustomMultipartFormDataRemoteStreamProvider(bool isResultNull)\n        {\n            _isResultNull = isResultNull;\n        }\n\n        public override RemoteStreamInfo GetRemoteStream(HttpContent parent, HttpContentHeaders headers)\n        {\n            string fileName = headers.ContentDisposition.FileName;\n            return _isResultNull\n                ? null\n                : new RemoteStreamInfo(CreateMockStream(), UrlBase + fileName, fileName);\n        }\n\n        private Stream CreateMockStream()\n        {\n            Stream stream = new Mock<Stream>().Object;\n            RemoteStreams.Add(stream);\n            return stream;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/DataSets/HttpTestData.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.IO;\nusing System.Linq;\nusing System.Net.Http.Formatting.DataSets.Types;\nusing System.Net.Http.Headers;\nusing System.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Formatting.DataSets\n{\n    public class HttpTestData\n    {\n        public static TestData<HttpMethod> AllHttpMethods\n        {\n            get\n            {\n                return new RefTypeTestData<HttpMethod>(() =>\n                    StandardHttpMethods.Concat(CustomHttpMethods).ToList());\n            }\n        }\n\n        public static TestData<HttpMethod> StandardHttpMethods\n        {\n            get\n            {\n                return new RefTypeTestData<HttpMethod>(() => new List<HttpMethod>()\n                {\n                    HttpMethod.Head,\n                    HttpMethod.Get,\n                    HttpMethod.Post,\n                    HttpMethod.Put,\n                    HttpMethod.Delete,\n                    HttpMethod.Options,\n                    HttpMethod.Trace,\n                });\n            }\n        }\n\n        public static TestData<HttpMethod> CustomHttpMethods\n        {\n            get\n            {\n                return new RefTypeTestData<HttpMethod>(() => new List<HttpMethod>()\n                {\n                    new HttpMethod(\"Custom\")\n                });\n            }\n        }\n\n        public static TestData<HttpStatusCode> AllHttpStatusCodes\n        {\n            get\n            {\n                return new ValueTypeTestData<HttpStatusCode>(new HttpStatusCode[]\n                {\n                    HttpStatusCode.Accepted,\n                    HttpStatusCode.Ambiguous,\n                    HttpStatusCode.BadGateway,\n                    HttpStatusCode.BadRequest,\n                    HttpStatusCode.Conflict,\n                    HttpStatusCode.Continue,\n                    HttpStatusCode.Created,\n                    HttpStatusCode.ExpectationFailed,\n                    HttpStatusCode.Forbidden,\n                    HttpStatusCode.Found,\n                    HttpStatusCode.GatewayTimeout,\n                    HttpStatusCode.Gone,\n                    HttpStatusCode.HttpVersionNotSupported,\n                    HttpStatusCode.InternalServerError,\n                    HttpStatusCode.LengthRequired,\n                    HttpStatusCode.MethodNotAllowed,\n                    HttpStatusCode.Moved,\n                    HttpStatusCode.MovedPermanently,\n                    HttpStatusCode.MultipleChoices,\n                    HttpStatusCode.NoContent,\n                    HttpStatusCode.NonAuthoritativeInformation,\n                    HttpStatusCode.NotAcceptable,\n                    HttpStatusCode.NotFound,\n                    HttpStatusCode.NotImplemented,\n                    HttpStatusCode.NotModified,\n                    HttpStatusCode.OK,\n                    HttpStatusCode.PartialContent,\n                    HttpStatusCode.PaymentRequired,\n                    HttpStatusCode.PreconditionFailed,\n                    HttpStatusCode.ProxyAuthenticationRequired,\n                    HttpStatusCode.Redirect,\n                    HttpStatusCode.RedirectKeepVerb,\n                    HttpStatusCode.RedirectMethod,\n                    HttpStatusCode.RequestedRangeNotSatisfiable,\n                    HttpStatusCode.RequestEntityTooLarge,\n                    HttpStatusCode.RequestTimeout,\n                    HttpStatusCode.RequestUriTooLong,\n                    HttpStatusCode.ResetContent,\n                    HttpStatusCode.SeeOther,\n                    HttpStatusCode.ServiceUnavailable,\n                    HttpStatusCode.SwitchingProtocols,\n                    HttpStatusCode.TemporaryRedirect,\n                    HttpStatusCode.Unauthorized,\n                    HttpStatusCode.UnsupportedMediaType,\n                    HttpStatusCode.Unused,\n                    HttpStatusCode.UseProxy\n                });\n            }\n        }\n\n        public static TestData<HttpStatusCode> CustomHttpStatusCodes\n        {\n            get\n            {\n                return new ValueTypeTestData<HttpStatusCode>(new HttpStatusCode[]\n                {\n                    (HttpStatusCode)199,\n                    (HttpStatusCode)299,\n                    (HttpStatusCode)399,\n                    (HttpStatusCode)499,\n                    (HttpStatusCode)599,\n                    (HttpStatusCode)699,\n                    (HttpStatusCode)799,\n                    (HttpStatusCode)899,\n                    (HttpStatusCode)999,\n                });\n            }\n        }\n\n        public static ReadOnlyCollection<TestData> ConvertablePrimitiveValueTypes\n        {\n            get\n            {\n                return new ReadOnlyCollection<TestData>(new TestData[]\n                {\n                    TestData.CharTestData,\n                    TestData.IntTestData,\n                    TestData.UintTestData,\n                    TestData.ShortTestData,\n                    TestData.UshortTestData,\n                    TestData.LongTestData,\n                    TestData.UlongTestData,\n                    TestData.ByteTestData,\n                    TestData.SByteTestData,\n                    TestData.BoolTestData,\n                    TestData.DoubleTestData,\n                    TestData.FloatTestData,\n                    TestData.DecimalTestData,\n                    TestData.TimeSpanTestData,\n                    TestData.GuidTestData,\n                    TestData.DateTimeTestData,\n                    TestData.DateTimeOffsetTestData\n                });\n            }\n        }\n\n        public static ReadOnlyCollection<TestData> ConvertableEnumTypes\n        {\n            get\n            {\n                return new ReadOnlyCollection<TestData>(new TestData[]\n                {\n                    TestData.SimpleEnumTestData,\n                    TestData.LongEnumTestData,\n                    TestData.FlagsEnumTestData,\n                    DataContractEnumTestData\n                });\n            }\n        }\n\n        public static ReadOnlyCollection<TestData> ConvertableValueTypes\n        {\n            get\n            {\n                return new ReadOnlyCollection<TestData>(\n                    ConvertablePrimitiveValueTypes.Concat(ConvertableEnumTypes).ToList());\n            }\n        }\n\n        public static TestData<MediaTypeHeaderValue> StandardBsonMediaTypes\n        {\n            get\n            {\n                return new RefTypeTestData<MediaTypeHeaderValue>(() => new List<MediaTypeHeaderValue>()\n                {\n                    new MediaTypeHeaderValue(\"application/bson\"),\n                });\n            }\n        }\n\n        public static TestData<MediaTypeHeaderValue> StandardJsonMediaTypes\n        {\n            get\n            {\n                return new RefTypeTestData<MediaTypeHeaderValue>(() => new List<MediaTypeHeaderValue>()\n                {\n                    new MediaTypeHeaderValue(\"application/json\"),\n                    new MediaTypeHeaderValue(\"text/json\")\n                });\n            }\n        }\n\n        public static TestData<MediaTypeHeaderValue> StandardXmlMediaTypes\n        {\n            get\n            {\n                return new RefTypeTestData<MediaTypeHeaderValue>(() => new List<MediaTypeHeaderValue>()\n                {\n                    new MediaTypeHeaderValue(\"application/xml\"),\n                    new MediaTypeHeaderValue(\"text/xml\")\n                });\n            }\n        }\n\n        public static TestData<MediaTypeHeaderValue> StandardODataMediaTypes\n        {\n            get\n            {\n                return new RefTypeTestData<MediaTypeHeaderValue>(() => new List<MediaTypeHeaderValue>()\n                {\n                    new MediaTypeHeaderValue(\"application/atom+xml\"),\n                    new MediaTypeHeaderValue(\"application/json\"),\n                });\n            }\n        }\n\n        public static TestData<MediaTypeHeaderValue> StandardFormUrlEncodedMediaTypes\n        {\n            get\n            {\n                return new RefTypeTestData<MediaTypeHeaderValue>(() => new List<MediaTypeHeaderValue>()\n                {\n                    new MediaTypeHeaderValue(\"application/x-www-form-urlencoded\")\n                });\n            }\n        }\n\n        public static TestData<string> StandardJsonMediaTypeStrings\n        {\n            get\n            {\n                return new RefTypeTestData<string>(() => new List<string>()\n                {\n                    \"application/json\",\n                    \"text/json\"\n                });\n            }\n        }\n\n        public static TestData<string> StandardXmlMediaTypeStrings\n        {\n            get\n            {\n                return new RefTypeTestData<string>(() => new List<string>()\n                {\n                    \"application/xml\",\n                    \"text/xml\"\n                });\n            }\n        }\n\n        public static TestData<string> LegalMediaTypeStrings\n        {\n            get\n            {\n                return new RefTypeTestData<string>(() =>\n                    StandardXmlMediaTypeStrings.Concat(StandardJsonMediaTypeStrings).ToList());\n            }\n        }\n\n\n        // Illegal media type strings.  These will cause the MediaTypeHeaderValue ctor to throw FormatException\n        public static TestData<string> IllegalMediaTypeStrings\n        {\n            get\n            {\n                return new RefTypeTestData<string>(() => new List<string>()\n                {\n                    \"\\0\",\n                    \"9\\r\\n\"\n                });\n            }\n        }\n\n        public static TestData<Encoding> StandardEncodings\n        {\n            get\n            {\n                return new RefTypeTestData<Encoding>(() => new List<Encoding>()\n                {\n                    new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true),\n                    new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true),\n                });\n            }\n        }\n\n        public static TheoryDataSet<string, string, bool> ReadAndWriteCorrectCharacterEncoding\n        {\n            get\n            {\n                return new TheoryDataSet<string, string, bool>\n                {\n                    { \"This is a test 激光這兩個字是甚麼意思 string written using utf-8\", \"utf-8\", true },\n                    { \"This is a test 激光這兩個字是甚麼意思 string written using utf-16\", \"utf-16\", true },\n                    { \"This is a test 激光這兩個字是甚麼意思 string written using utf-32\", \"utf-32\", false },\n#if !NETCOREAPP // shift_jis and iso-2022-kr are not supported when running on .NET Core 2.1.\n                    { \"This is a test 激光這兩個字是甚麼意思 string written using shift_jis\", \"shift_jis\", false },\n#endif\n                    { \"This is a test æøå string written using iso-8859-1\", \"iso-8859-1\", false },\n#if !NETCOREAPP\n                    { \"This is a test 레이저 단어 뜻 string written using iso-2022-kr\", \"iso-2022-kr\", false },\n#endif\n                };\n            }\n        }\n\n        //// TODO: complete this list\n        // Legal MediaTypeHeaderValues\n        public static TestData<MediaTypeHeaderValue> LegalMediaTypeHeaderValues\n        {\n            get\n            {\n                return new RefTypeTestData<MediaTypeHeaderValue>(\n                    () => LegalMediaTypeStrings.Select(mediaType => new MediaTypeHeaderValue(mediaType)).ToList());\n            }\n        }\n\n        public static TestData<MediaTypeWithQualityHeaderValue> StandardMediaTypesWithQuality\n        {\n            get\n            {\n                return new RefTypeTestData<MediaTypeWithQualityHeaderValue>(() => new List<MediaTypeWithQualityHeaderValue>()\n                {\n                    new MediaTypeWithQualityHeaderValue(\"application/json\", .1) { CharSet=\"utf-8\"},\n                    new MediaTypeWithQualityHeaderValue(\"text/json\", .2) { CharSet=\"utf-8\"},\n                    new MediaTypeWithQualityHeaderValue(\"application/xml\", .3) { CharSet=\"utf-8\"},\n                    new MediaTypeWithQualityHeaderValue(\"text/xml\", .4) { CharSet=\"utf-8\"},\n                    new MediaTypeWithQualityHeaderValue(\"application/atom+xml\", .5) { CharSet=\"utf-8\"},\n                });\n            }\n        }\n\n        public static TestData<HttpContent> StandardHttpContents\n        {\n            get\n            {\n                return new RefTypeTestData<HttpContent>(() => new List<HttpContent>()\n                {\n                    new ByteArrayContent(new byte[0]),\n                    new FormUrlEncodedContent(new KeyValuePair<string, string>[0]),\n                    new MultipartContent(),\n                    new StringContent(\"\"),\n                    new StreamContent(new MemoryStream())\n                });\n            }\n        }\n\n        //// TODO: make this list compose from other data?\n        // Collection of legal instances of all standard MediaTypeMapping types\n        public static TestData<MediaTypeMapping> StandardMediaTypeMappings\n        {\n            get\n            {\n                return new RefTypeTestData<MediaTypeMapping>(() => QueryStringMappings.Cast<MediaTypeMapping>().ToList());\n            }\n        }\n\n        public static TestData<QueryStringMapping> QueryStringMappings\n        {\n            get\n            {\n                return new RefTypeTestData<QueryStringMapping>(() => new List<QueryStringMapping>()\n                {\n                    new QueryStringMapping(\"format\", \"json\", new MediaTypeHeaderValue(\"application/json\"))\n                });\n            }\n        }\n\n        public static TestData<string> LegalUriPathExtensions\n        {\n            get\n            {\n                return new RefTypeTestData<string>(() => new List<string>()\n                {\n                    \"xml\",\n                    \"json\"\n                });\n            }\n        }\n\n        public static TestData<string> LegalQueryStringParameterNames\n        {\n            get\n            {\n                return new RefTypeTestData<string>(() => new List<string>()\n                {\n                    \"format\",\n                    \"fmt\"\n                });\n            }\n        }\n\n        public static TestData<string> LegalHttpHeaderNames\n        {\n            get\n            {\n                return new RefTypeTestData<string>(() => new List<string>()\n                {\n                    \"x-requested-with\",\n                    \"some-random-name\"\n                });\n            }\n        }\n\n        public static TestData<string> LegalHttpHeaderValues\n        {\n            get\n            {\n                return new RefTypeTestData<string>(() => new List<string>()\n                {\n                    \"1\",\n                    \"XMLHttpRequest\",\n                    \"\\\"quoted-string\\\"\"\n                });\n            }\n        }\n\n        public static TestData<string> LegalQueryStringParameterValues\n        {\n            get\n            {\n                return new RefTypeTestData<string>(() => new List<string>()\n                {\n                    \"xml\",\n                    \"json\"\n                });\n            }\n        }\n\n        public static TestData<string> LegalMediaRangeStrings\n        {\n            get\n            {\n                return new RefTypeTestData<string>(() => new List<string>()\n                {\n                    \"application/*\",\n                    \"text/*\"\n                });\n            }\n        }\n\n        public static TestData<MediaTypeHeaderValue> LegalMediaRangeValues\n        {\n            get\n            {\n                return new RefTypeTestData<MediaTypeHeaderValue>(() =>\n                    LegalMediaRangeStrings.Select(s => new MediaTypeHeaderValue(s)).ToList()\n                    );\n            }\n        }\n\n        public static TestData<MediaTypeWithQualityHeaderValue> MediaRangeValuesWithQuality\n        {\n            get\n            {\n                return new RefTypeTestData<MediaTypeWithQualityHeaderValue>(() => new List<MediaTypeWithQualityHeaderValue>()\n                {\n                    new MediaTypeWithQualityHeaderValue(\"application/*\", .1),\n                    new MediaTypeWithQualityHeaderValue(\"text/*\", .2),\n                });\n            }\n        }\n\n        public static TestData<string> IllegalMediaRangeStrings\n        {\n            get\n            {\n                return new RefTypeTestData<string>(() => new List<string>()\n                {\n                    \"application/xml\",\n                    \"text/xml\"\n                });\n            }\n        }\n\n        public static TestData<MediaTypeHeaderValue> IllegalMediaRangeValues\n        {\n            get\n            {\n                return new RefTypeTestData<MediaTypeHeaderValue>(() =>\n                    IllegalMediaRangeStrings.Select(s => new MediaTypeHeaderValue(s)).ToList()\n                    );\n            }\n        }\n\n        public static TestData<MediaTypeFormatter> StandardFormatters\n        {\n            get\n            {\n                return new RefTypeTestData<MediaTypeFormatter>(() => new List<MediaTypeFormatter>()\n                {\n                    new XmlMediaTypeFormatter(),\n                    new JsonMediaTypeFormatter(),\n                    new FormUrlEncodedMediaTypeFormatter()\n                });\n            }\n        }\n\n        public static TestData<Type> StandardFormatterTypes\n        {\n            get\n            {\n                return new RefTypeTestData<Type>(() => StandardFormatters.Select(m => m.GetType()));\n            }\n        }\n\n        public static TestData<MediaTypeFormatter> DerivedFormatters\n        {\n            get\n            {\n                return new RefTypeTestData<MediaTypeFormatter>(() => new List<MediaTypeFormatter>()\n                {\n                    new DerivedXmlMediaTypeFormatter(),\n                    new DerivedJsonMediaTypeFormatter(),\n                    new DerivedFormUrlEncodedMediaTypeFormatter(),\n                });\n            }\n        }\n\n        public static TestData<IEnumerable<MediaTypeFormatter>> AllFormatterCollections\n        {\n            get\n            {\n                return new RefTypeTestData<IEnumerable<MediaTypeFormatter>>(() => new List<IEnumerable<MediaTypeFormatter>>()\n                {\n                    new MediaTypeFormatter[0],\n                    StandardFormatters,\n                    DerivedFormatters,\n                });\n            }\n        }\n\n        public static TestData<string> LegalHttpAddresses\n        {\n            get\n            {\n                return new RefTypeTestData<string>(() => new List<string>()\n                {\n                    \"http://somehost\",\n                    \"https://somehost\",\n                });\n            }\n        }\n\n        public static TestData<string> AddressesWithIllegalSchemes\n        {\n            get\n            {\n                return new RefTypeTestData<string>(() => new List<string>()\n                {\n                    \"net.tcp://somehost\",\n                    \"file://somehost\",\n                    \"net.pipe://somehost\",\n                    \"mailto:somehost\",\n                    \"ftp://somehost\",\n                    \"news://somehost\",\n                    \"ws://somehost\",\n                    \"abc://somehost\"\n                });\n            }\n        }\n\n        /// <summary>\n        /// A read-only collection of representative values and reference type test data.\n        /// Uses where exhaustive coverage is not required.  It includes null values.\n        /// </summary>\n        public static ReadOnlyCollection<TestData> RepresentativeValueAndRefTypeTestDataCollection\n        {\n            get\n            {\n                return new ReadOnlyCollection<TestData>(new TestData[]\n                {\n                     TestData.ByteTestData,\n                     TestData.IntTestData,\n                     TestData.BoolTestData,\n                     TestData.SimpleEnumTestData,\n                     TestData.StringTestData,\n                     TestData.DateTimeTestData,\n                     TestData.DateTimeOffsetTestData,\n                     TestData.TimeSpanTestData,\n                     WcfPocoTypeTestDataWithNull\n                });\n            }\n        }\n\n        public static TestData<HttpRequestMessage> NullContentHttpRequestMessages\n        {\n            get\n            {\n                return new RefTypeTestData<HttpRequestMessage>(() => new List<HttpRequestMessage>()\n                {\n                   new HttpRequestMessage() { Content = null },\n                });\n            }\n        }\n\n        public static TestData<string> LegalHttpParameterNames\n        {\n            get\n            {\n                return new RefTypeTestData<string>(() => new List<string>()\n                {\n                    \"文\",\n                    \"A\",\n                    \"a\",\n                    \"b\",\n                    \" a\",\n                    \"arg1\",\n                    \"arg2\",\n                    \"1\",\n                    \"@\",\n                    \"!\"\n                });\n            }\n        }\n\n        public static TestData<Type> LegalHttpParameterTypes\n        {\n            get\n            {\n                return new RefTypeTestData<Type>(() => new List<Type>()\n                {\n                    typeof(string),\n                    typeof(byte[]),\n                    typeof(byte[][]),\n                    typeof(char),\n                    typeof(DateTime),\n                    typeof(decimal),\n                    typeof(double),\n                    typeof(Guid),\n                    typeof(Int16),\n                    typeof(Int32),\n                    typeof(object),\n                    typeof(sbyte),\n                    typeof(Single),\n                    typeof(TimeSpan),\n                    typeof(UInt16),\n                    typeof(UInt32),\n                    typeof(UInt64),\n                    typeof(Uri),\n                    typeof(Enum),\n                    typeof(Collection<object>),\n                    typeof(IList<object>),\n                    typeof(System.Runtime.Serialization.ISerializable),\n                    typeof(System.Data.DataSet),\n                    typeof(System.Xml.Serialization.IXmlSerializable),\n                    typeof(Nullable),\n                    typeof(Nullable<DateTime>),\n                    typeof(Stream),\n                    typeof(HttpRequestMessage),\n                    typeof(HttpResponseMessage),\n                    typeof(ObjectContent),\n                    typeof(ObjectContent<object>),\n                    typeof(HttpContent),\n                    typeof(Delegate),\n                    typeof(Action),\n                    typeof(System.Threading.Tasks.Task<object>),\n                    typeof(System.Threading.Tasks.Task),\n                    typeof(List<dynamic>)\n                });\n            }\n        }\n\n        /// <summary>\n        /// Common <see cref=\"TestData\"/> for an <c>enum</c> decorated with a <see cref=\"DataContractAttribute\"/>.\n        /// </summary>\n        public static ValueTypeTestData<DataContractEnum> DataContractEnumTestData\n        {\n            get\n            {\n                return new ValueTypeTestData<DataContractEnum>(\n                    DataContractEnum.First,\n                    DataContractEnum.Second);\n            }\n        }\n\n        /// <summary>\n        ///  Common <see cref=\"TestData\"/> for the string form of a <see cref=\"Uri\"/>.\n        /// </summary>\n        public static RefTypeTestData<string> UriTestDataStrings\n        {\n            get\n            {\n                return new RefTypeTestData<string>(() => new List<string>()\n                {\n                    \"http://somehost\",\n                    \"http://somehost:8080\",\n                    \"http://somehost/\",\n                    \"http://somehost:8080/\",\n                    \"http://somehost/somepath\",\n                    \"http://somehost/somepath/\",\n                    \"http://somehost/somepath?somequery=somevalue\"\n                });\n            }\n        }\n\n        /// <summary>\n        ///  Common <see cref=\"TestData\"/> for a <see cref=\"Uri\"/>.\n        /// </summary>\n        public static RefTypeTestData<Uri> UriTestData\n        {\n            get\n            {\n                return new RefTypeTestData<Uri>(() => UriTestDataStrings.Select(s => new Uri(s)).ToList());\n            }\n        }\n\n        /// <summary>\n        ///  Common <see cref=\"TestData\"/> for a POCO class type that includes null values\n        ///  for both the base class and derived classes.\n        /// </summary>\n        public static RefTypeTestData<WcfPocoType> WcfPocoTypeTestDataWithNull\n        {\n            get\n            {\n                return new RefTypeTestData<WcfPocoType>(\n                    WcfPocoType.GetTestDataWithNull,\n                    WcfPocoType.GetDerivedTypeTestDataWithNull,\n                    null);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/DataSets/Types/DataContractEnum.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Runtime.Serialization;\n\nnamespace System.Net.Http.Formatting.DataSets.Types\n{\n    [DataContract]\n    public enum DataContractEnum\n    {\n        [EnumMember]\n        First,\n\n        [EnumMember]\n        Second,\n\n        Third\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/DataSets/Types/DataContractType.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Runtime.Serialization;\nusing System.Xml.Serialization;\nusing Microsoft.TestCommon.Types;\n\nnamespace System.Net.Http.Formatting.DataSets.Types\n{\n    [DataContract]\n    [KnownType(typeof(DerivedDataContractType))]\n    [XmlInclude(typeof(DerivedDataContractType))]\n    public class DataContractType : INameAndIdContainer\n    {\n        private int id;\n        private string name;\n\n        public DataContractType()\n        {\n        }\n\n        public DataContractType(int id, string name)\n        {\n            this.id = id;\n            this.name = name;\n        }\n\n        [DataMember]\n        public int Id\n        {\n            get\n            {\n                return this.id;\n            }\n\n            set\n            {\n                this.IdSet = true;\n                this.id = value;\n            }\n        }\n\n        [DataMember]\n        public string Name\n        {\n            get\n            {\n                return this.name;\n            }\n\n            set\n            {\n                this.NameSet = true;\n                this.name = value;\n            }\n        }\n\n        [XmlIgnore]\n        public bool IdSet { get; private set; }\n\n        [XmlIgnore]\n        public bool NameSet { get; private set; }\n\n        public static IEnumerable<DataContractType> GetTestData()\n        {\n            return new DataContractType[] { new DataContractType(), new DataContractType(1, \"SomeName\") };\n        }\n\n        public static IEnumerable<DerivedDataContractType> GetDerivedTypeTestData()\n        {\n            return new DerivedDataContractType[] { \n                new DerivedDataContractType(), \n                new DerivedDataContractType(1, \"SomeName\", null), \n                new DerivedDataContractType(1, \"SomeName\", new WcfPocoType(2, \"SomeOtherName\"))};\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/DataSets/Types/DerivedDataContractType.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Runtime.Serialization;\nusing System.Xml.Serialization;\n\nnamespace System.Net.Http.Formatting.DataSets.Types\n{\n    [DataContract]\n    [KnownType(typeof(DerivedWcfPocoType))]\n    [KnownType(typeof(DerivedDataContractType))]\n    [XmlInclude(typeof(DerivedWcfPocoType))]\n    [XmlInclude(typeof(DerivedDataContractType))]\n    public class DerivedDataContractType : DataContractType\n    {\n        private WcfPocoType reference;\n\n        public DerivedDataContractType()\n        {\n        }\n\n        public DerivedDataContractType(int id, string name, WcfPocoType reference)\n            : base(id, name)\n        {\n            this.reference = reference;\n        }\n\n        [DataMember]\n        public WcfPocoType Reference\n        {\n            get\n            {\n                return this.reference;\n            }\n\n            set\n            {\n                this.ReferenceSet = true;\n                this.reference = value;\n            }\n        }\n\n        [XmlIgnore]\n        public bool ReferenceSet { get; private set; }\n\n        public static new IEnumerable<DerivedDataContractType> GetTestData()\n        {\n            return new DerivedDataContractType[] { \n                new DerivedDataContractType(), \n                new DerivedDataContractType(1, \"SomeName\", new WcfPocoType(2, \"SomeOtherName\")) };\n        }\n\n        public static IEnumerable<DerivedDataContractType> GetKnownTypeTestData()\n        {\n            return new DerivedDataContractType[] { \n                new DerivedDataContractType(), \n                new DerivedDataContractType(1, \"SomeName\", null), \n                new DerivedDataContractType(1, \"SomeName\", new DerivedWcfPocoType(2, \"SomeOtherName\", null))};\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/DataSets/Types/DerivedFormUrlEncodedMediaTypeFormatter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n\nnamespace System.Net.Http.Formatting.DataSets.Types\n{\n    public class DerivedFormUrlEncodedMediaTypeFormatter : FormUrlEncodedMediaTypeFormatter\n    {\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/DataSets/Types/DerivedJsonMediaTypeFormatter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n\nnamespace System.Net.Http.Formatting.DataSets.Types\n{\n    public class DerivedJsonMediaTypeFormatter : JsonMediaTypeFormatter\n    {\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/DataSets/Types/DerivedWcfPocoType.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Runtime.Serialization;\nusing System.Xml.Serialization;\n\nnamespace System.Net.Http.Formatting.DataSets.Types\n{\n    public class DerivedWcfPocoType : WcfPocoType\n    {\n        private WcfPocoType reference;\n\n        public DerivedWcfPocoType()\n        {\n        }\n\n        public DerivedWcfPocoType(int id, string name, WcfPocoType reference)\n            : base(id, name)\n        {\n            this.reference = reference;\n        }\n\n        public WcfPocoType Reference\n        {\n            get\n            {\n                return this.reference;\n            }\n\n            set\n            {\n                this.ReferenceSet = true;\n                this.reference = value;\n            }\n        }\n\n        [IgnoreDataMember]\n        [XmlIgnore]\n        public bool ReferenceSet { get; private set; }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/DataSets/Types/DerivedXmlMediaTypeFormatter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n\nnamespace System.Net.Http.Formatting.DataSets.Types\n{\n    public class DerivedXmlMediaTypeFormatter : XmlMediaTypeFormatter\n    {\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/DataSets/Types/DerivedXmlSerializableType.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Runtime.Serialization;\nusing System.Xml.Serialization;\n\nnamespace System.Net.Http.Formatting.DataSets.Types\n{\n    [KnownType(typeof(DerivedWcfPocoType))]\n    [XmlInclude(typeof(DerivedWcfPocoType))]\n    public class DerivedXmlSerializableType : XmlSerializableType, INotJsonSerializable\n    {\n        private WcfPocoType reference;\n\n        public DerivedXmlSerializableType()\n        {\n        }\n\n        public DerivedXmlSerializableType(int id, string name, WcfPocoType reference)\n            : base(id, name)\n        {\n            this.reference = reference;\n        }\n\n        [XmlElement]\n        public WcfPocoType Reference\n        {\n            get\n            {\n                return this.reference;\n            }\n\n            set\n            {\n                this.ReferenceSet = true;\n                this.reference = value;\n            }\n        }\n\n        [XmlIgnore]\n        public bool ReferenceSet { get; private set; }\n\n        public static new IEnumerable<DerivedXmlSerializableType> GetTestData()\n        {\n            return new DerivedXmlSerializableType[] { \n                new DerivedXmlSerializableType(), \n                new DerivedXmlSerializableType(1, \"SomeName\", new WcfPocoType(2, \"SomeOtherName\")) };\n        }\n\n        public static IEnumerable<DerivedXmlSerializableType> GetKnownTypeTestData()\n        {\n            return new DerivedXmlSerializableType[] { \n                new DerivedXmlSerializableType(), \n                new DerivedXmlSerializableType(1, \"SomeName\", null), \n                new DerivedXmlSerializableType(1, \"SomeName\", new DerivedWcfPocoType(2, \"SomeOtherName\", null))};\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/DataSets/Types/INotJsonSerializable.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Net.Http.Formatting.DataSets.Types\n{\n    /// <summary>\n    /// Tagging interface to indicate types which we know Json cannot serialize.\n    /// </summary>\n    public interface INotJsonSerializable\n    {\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/DataSets/Types/WcfPocoType.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Runtime.Serialization;\nusing System.Xml.Serialization;\nusing Microsoft.TestCommon.Types;\n\nnamespace System.Net.Http.Formatting.DataSets.Types\n{\n    [KnownType(typeof(DerivedWcfPocoType))]\n    [XmlInclude(typeof(DerivedWcfPocoType))]\n    public class WcfPocoType : INameAndIdContainer\n    {\n        private int id;\n        private string name;\n\n        public WcfPocoType()\n        {\n        }\n\n        public WcfPocoType(int id, string name)\n        {\n            this.id = id;\n            this.name = name;\n        }\n\n        public int Id\n        {\n            get\n            {\n                return this.id;\n            }\n\n            set\n            {\n                this.IdSet = true;\n                this.id = value;\n            }\n        }\n\n        public string Name\n        {\n            get\n            {\n                return this.name;\n            }\n\n            set\n            {\n                this.NameSet = true;\n                this.name = value;\n            }\n\n        }\n\n        [IgnoreDataMember]\n        [XmlIgnore]\n        public bool IdSet { get; private set; }\n\n        [IgnoreDataMember]\n        [XmlIgnore]\n        public bool NameSet { get; private set; }\n\n        public static IEnumerable<WcfPocoType> GetTestData()\n        {\n            return new WcfPocoType[] { new WcfPocoType(), new WcfPocoType(1, \"SomeName\") };\n        }\n\n        public static IEnumerable<WcfPocoType> GetTestDataWithNull()\n        {\n            return GetTestData().Concat(new WcfPocoType[] { null });\n        }\n\n        public static IEnumerable<DerivedWcfPocoType> GetDerivedTypeTestData()\n        {\n            return new DerivedWcfPocoType[] { \n                new DerivedWcfPocoType(), \n                new DerivedWcfPocoType(1, \"SomeName\", null), \n                new DerivedWcfPocoType(1, \"SomeName\", new WcfPocoType(2, \"SomeOtherName\"))};\n        }\n\n        public static IEnumerable<DerivedWcfPocoType> GetDerivedTypeTestDataWithNull()\n        {\n            return GetDerivedTypeTestData().Concat(new DerivedWcfPocoType[] { null });\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/DataSets/Types/XmlSerializableType.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Runtime.Serialization;\nusing System.Xml.Serialization;\nusing Microsoft.TestCommon.Types;\n\nnamespace System.Net.Http.Formatting.DataSets.Types\n{\n    [KnownType(typeof(DerivedXmlSerializableType))]\n    [XmlInclude(typeof(DerivedXmlSerializableType))]\n    public class XmlSerializableType : INameAndIdContainer\n    {\n        private int id;\n        private string name;\n\n        public XmlSerializableType()\n        {\n        }\n\n        public XmlSerializableType(int id, string name)\n        {\n            this.id = id;\n            this.name = name;\n        }\n\n        [XmlAttribute]\n        public int Id\n        {\n            get\n            {\n                return this.id;\n            }\n\n            set\n            {\n                this.IdSet = true;\n                this.id = value;\n            }\n        }\n\n        [XmlElement]\n        public string Name\n        {\n            get\n            {\n                return this.name;\n            }\n\n            set\n            {\n                this.NameSet = true;\n                this.name = value;\n            }\n\n        }\n\n        [XmlIgnore]\n        public bool IdSet { get; private set; }\n\n        [XmlIgnore]\n        public bool NameSet { get; private set; }\n\n        public override bool Equals(object obj)\n        {\n            if (Object.ReferenceEquals(this, obj))\n            {\n                return true;\n            }\n\n            XmlSerializableType other = obj as XmlSerializableType;\n            if (Object.ReferenceEquals(other, null))\n            {\n                return false;\n            }\n\n            return String.Equals(this.Name, other.Name, StringComparison.Ordinal) && this.Id == other.Id;\n        }\n\n        public override int GetHashCode()\n        {\n            return base.GetHashCode();\n        }\n\n        public static IEnumerable<XmlSerializableType> GetTestData()\n        {\n            return new XmlSerializableType[] { new XmlSerializableType(), new XmlSerializableType(1, \"SomeName\") };\n        }\n\n        public static IEnumerable<DerivedXmlSerializableType> GetDerivedTypeTestData()\n        {\n            return new DerivedXmlSerializableType[] { \n                new DerivedXmlSerializableType(), \n                new DerivedXmlSerializableType(1, \"SomeName\", null), \n                new DerivedXmlSerializableType(1, \"SomeName\", new WcfPocoType(2, \"SomeOtherName\"))};\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/BsonMediaTypeFormatterTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Net.Http.Formatting.DataSets;\nusing System.Net.Http.Headers;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\n\nnamespace System.Net.Http.Formatting\n{\n    public class BsonMediaTypeFormatterTests : MediaTypeFormatterTestBase<BsonMediaTypeFormatter>\n    {\n        // Exclude IEnumerable<T> and IQueryable<T> to avoid attempts to round trip values that are known to cause\n        // trouble in deserialization e.g. base IEnumerable<T>.  BSON reader won't know how to construct such types.\n        private const TestDataVariations RoundTripVariations =\n            (TestDataVariations.All | TestDataVariations.WithNull | TestDataVariations.AsClassMember) &\n            ~(TestDataVariations.AsIEnumerable | TestDataVariations.AsIQueryable);\n\n        /// <summary>\n        /// Provide test data for round trip tests.  Avoid types BSON does not support.\n        /// <remarks>\n        /// BSON does not support some unsigned integers as well as having issues with <see cref=\"decimal\"/>.\n        /// <list type=\"bullet\">\n        /// <item><description>\n        /// BSON writer attempts to write an unsigned int or long as a signed integer of the same size e.g. it writes\n        /// an <see cref=\"uint\"/> as an <see cref=\"int\"/> and thus can only write values less than\n        /// <c>Int32.MaxValue</c>.  BSON writer fortunately uses an <see cref=\"int\"/> for <see cref=\"sbyte\"/>,\n        /// <see cref=\"byte\"/>, <see cref=\"short\"/>, and <see cref=\"ushort\"/> values.\n        /// </description></item>\n        /// <item><description>\n        /// BSON successfully writes all <see cref=\"decimal\"/> values as <see cref=\"double\"/>.  But BSON reader may not\n        /// be able to be convert the <see cref=\"double\"/> value back e.g. <c>Decimal.MaxValue</c> loses precision when\n        /// written and is rounded up -- to an invalid <see cref=\"decimal\"/> value.\n        /// </description></item>\n        /// <item><description>\n        /// BSON (as well as JSON and default <c>ToString()</c> in the <see cref=\"DateTime\"/> case) loses information\n        /// when writing <see cref=\"DateTime\"/> and <see cref=\"DateTimeOffset\"/> values.  BSON writer uses a UTC\n        /// datetime value in both cases -- losing <c>Kind</c> and <c>Offset</c> property values, respectively.\n        /// (<see cref=\"DateTime\"/> values are not currently included in\n        /// <see cref=\"CommonUnitTestDataSets.ValueAndRefTypeTestDataCollection\"/> but exclude\n        /// <see cref=\"CommonUnitTestDataSets.DateTimes\"/> to be safe.)\n        /// </description></item>\n        /// <item><description>\n        /// BSON readers and writers appear to round trip <see cref=\"ISerializableType\"/> values successfully.  However\n        /// <see cref=\"ISerializableType\"/> does not implement <see cref=\"IEquatable{T}\"/> or\n        /// <see cref=\"IComparable{T}\"/> and thus <see cref=\"Assert.Equals()\"/> fails.\n        /// </description></item>\n        /// </list>\n        /// </remarks>\n        /// </summary>\n        public static IEnumerable<TestData> ValueAndRefTypeTestDataCollection\n        {\n            get\n            {\n                return CommonUnitTestDataSets.ValueAndRefTypeTestDataCollection.Except(\n                    new TestData[] {\n                        CommonUnitTestDataSets.Uints,\n                        CommonUnitTestDataSets.Ulongs,\n                        CommonUnitTestDataSets.DateTimeOffsets,\n                        CommonUnitTestDataSets.DateTimes,\n                        CommonUnitTestDataSets.Decimals,\n                        CommonUnitTestDataSets.ISerializableTypes,\n                    });\n            }\n        }\n\n\n        public override IEnumerable<MediaTypeHeaderValue> ExpectedSupportedMediaTypes\n        {\n            get { return HttpTestData.StandardBsonMediaTypes; }\n        }\n\n        public override IEnumerable<Encoding> ExpectedSupportedEncodings\n        {\n            get { return HttpTestData.StandardEncodings; }\n        }\n\n        public override byte[] ExpectedSampleTypeByteRepresentation\n        {\n            get\n            {\n                return new byte[17]\n                {\n                    // Little-endian length\n                    17, 0, 0, 0,\n                    // Opcode indicating a 32bit integer\n                    0x10,\n                    // Field name as a C string\n                    (byte)'N', (byte)'u', (byte)'m', (byte)'b', (byte)'e', (byte)'r', 0,\n                    // Little-endian value\n                    42, 0, 0, 0,\n                    // BSON document terminator\n                    0,\n                };\n            }\n        }\n\n        public override Task ReadFromStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding)\n        {\n            // Arrange\n            BsonMediaTypeFormatter formatter = new BsonMediaTypeFormatter();\n\n            string mediaType = string.Format(\"application/bson; charset={0}\", encoding);\n            Encoding enc = CreateOrGetSupportedEncoding(formatter, encoding, isDefaultEncoding);\n\n            // Test roundtrip in this case, not against expectations\n            byte[] sourceData;\n            using (MemoryStream stream = new MemoryStream())\n            {\n                formatter.WriteToStream(typeof(string), content, stream, enc);\n                sourceData = stream.ToArray();\n            }\n\n            // Further Arrange, Act & Assert\n            return ReadContentUsingCorrectCharacterEncodingHelperAsync(formatter, content, sourceData, mediaType);\n        }\n\n        public override Task WriteToStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding)\n        {\n            // Arrange\n            GC.KeepAlive(isDefaultEncoding); // Mark parameter as used. See xUnit1026, [Theory] method doesn't use all parameters.\n            BsonMediaTypeFormatter formatter = new BsonMediaTypeFormatter();\n\n            string mediaType = string.Format(\"application/bson; charset={0}\", encoding);\n            Encoding enc = Encoding.GetEncoding(encoding);\n\n            // Test sync and async approaches match, not against expectations\n            // See ReadFromStreamAsync_UsesCorrectCharacterEncoding for roundtrip test\n            byte[] expectedData;\n            using (MemoryStream stream = new MemoryStream())\n            {\n                formatter.WriteToStream(typeof(string), content, stream, enc);\n                expectedData = stream.ToArray();\n            }\n\n            // Further Arrange, Act & Assert\n            return WriteContentUsingCorrectCharacterEncodingHelperAsync(formatter, content, expectedData, mediaType);\n        }\n\n        [Fact]\n        void CopyConstructor()\n        {\n            // Arrange\n            TestBsonMediaTypeFormatter formatter = new TestBsonMediaTypeFormatter()\n            {\n                MaxDepth = 42,\n            };\n\n            // Replace serializable settings and switch one property's value\n            JsonSerializerSettings oldSettings = formatter.SerializerSettings;\n            formatter.SerializerSettings = formatter.CreateDefaultSerializerSettings();\n            formatter.SerializerSettings.CheckAdditionalContent = !formatter.SerializerSettings.CheckAdditionalContent;\n\n            // Act\n            TestBsonMediaTypeFormatter derivedFormatter = new TestBsonMediaTypeFormatter(formatter);\n\n            // Assert\n            Assert.Equal(formatter.MaxDepth, derivedFormatter.MaxDepth);\n            Assert.NotSame(oldSettings, formatter.SerializerSettings);\n            Assert.NotEqual(oldSettings.CheckAdditionalContent, formatter.SerializerSettings.CheckAdditionalContent);\n            Assert.Same(formatter.SerializerSettings, derivedFormatter.SerializerSettings);\n            Assert.Same(formatter.SerializerSettings.ContractResolver, derivedFormatter.SerializerSettings.ContractResolver);\n        }\n\n        [Fact]\n        public void MaxDepth_RoundTrips()\n        {\n            // Arrange & Act & Assert\n            Assert.Reflection.IntegerProperty(\n                new BsonMediaTypeFormatter(),\n                c => c.MaxDepth,\n                expectedDefaultValue: 256,\n                minLegalValue: 1,\n                illegalLowerValue: 0,\n                maxLegalValue: null,\n                illegalUpperValue: null,\n                roundTripTestValue: 256);\n        }\n\n        [Theory]\n        [TestDataSet(typeof(CommonUnitTestDataSets), \"RepresentativeValueAndRefTypeTestDataCollection\")]\n        public void CanReadType_ReturnsExpectedValues(Type variationType, object testData)\n        {\n            // Arrange\n            GC.KeepAlive(testData); // Mark parameter as used. See xUnit1026, [Theory] method doesn't use all parameters.\n            BsonMediaTypeFormatter formatter = new BsonMediaTypeFormatter();\n\n            // Act & Assert\n            Assert.True(formatter.CanReadType(variationType));\n        }\n\n        [Theory]\n        [TestDataSet(typeof(CommonUnitTestDataSets), \"RepresentativeValueAndRefTypeTestDataCollection\")]\n        public void CanWriteType_ReturnsExpectedValues(Type variationType, object testData)\n        {\n            // Arrange\n            GC.KeepAlive(testData); // Mark parameter as used. See xUnit1026, [Theory] method doesn't use all parameters.\n            BsonMediaTypeFormatter formatter = new BsonMediaTypeFormatter();\n\n            // Act & Assert\n            Assert.True(formatter.CanWriteType(variationType));\n        }\n\n        [Fact]\n        public async Task FormatterThrowsOnWriteWhenOverridenCreateFails()\n        {\n            // Arrange\n            TestBsonMediaTypeFormatter formatter = new TestBsonMediaTypeFormatter\n            {\n                ThrowExceptionOnCreate = true,\n            };\n\n            MemoryStream memoryStream = new MemoryStream();\n            HttpContent content = new StringContent(String.Empty);\n\n            // Act & Assert\n            Func<Task> action = () => formatter.WriteToStreamAsync(typeof(SampleType), new SampleType(), memoryStream, content, transportContext: null);\n            await Assert.ThrowsAsync<Exception>(action, \"Throwing exception directly, since it needs to get caught by a catch all\");\n\n            Assert.False(formatter.WasCreateJsonReaderCalled);\n            Assert.True(formatter.WasCreateJsonWriterCalled);\n        }\n\n        [Fact]\n        public async Task FormatterThrowsOnWriteWhenOverridenCreateReturnsNull()\n        {\n            // Arrange\n            TestBsonMediaTypeFormatter formatter = new TestBsonMediaTypeFormatter\n            {\n                ReturnNullOncreate = true,\n            };\n\n            MemoryStream memoryStream = new MemoryStream();\n            HttpContent content = new StringContent(String.Empty);\n\n            // Act & Assert\n            Func<Task> action = () => formatter.WriteToStreamAsync(typeof(SampleType), new SampleType(), memoryStream, content, transportContext: null);\n            await Assert.ThrowsAsync<InvalidOperationException>(action, \"The 'CreateJsonWriter' method returned null. It must return a JSON writer instance.\");\n\n            Assert.False(formatter.WasCreateJsonReaderCalled);\n            Assert.True(formatter.WasCreateJsonWriterCalled);\n        }\n\n        [Fact]\n        public async Task FormatterThrowsOnWriteWithInvalidContent()\n        {\n            // Arrange (set up to serialize Int32.MaxValue + 1 as an UInt32; can't be done since serialization uses an Int32\n            Type variationType = typeof(uint);\n            uint testData = (uint)Int32.MaxValue + 1u;\n            BsonMediaTypeFormatter formatter = new BsonMediaTypeFormatter();\n            HttpContent content = new StringContent(String.Empty);\n            MemoryStream stream = new MemoryStream();\n            string expectedMessage =\n                \"Value is too large to fit in a signed 32 bit integer. BSON does not support unsigned values. Path 'Value'.\";\n\n            // Act & Assert\n            // Note error message is not quite correct: BSON supports byte, ushort, and smaller uint / ulong values.\n            await Assert.ThrowsAsync<JsonWriterException>(\n                () => formatter.WriteToStreamAsync(variationType, testData, stream, content, transportContext: null),\n                expectedMessage);\n        }\n\n        [Fact]\n        public async Task FormatterThrowsOnReadWhenOverridenCreateFails()\n        {\n            // Arrange\n            TestBsonMediaTypeFormatter formatter = new TestBsonMediaTypeFormatter\n            {\n                ThrowExceptionOnCreate = true,\n            };\n\n            byte[] array = Encoding.UTF8.GetBytes(\"foo\");\n            MemoryStream memoryStream = new MemoryStream(array);\n\n            HttpContent content = new StringContent(\"foo\");\n\n            // Act & Assert\n            Func<Task> action = () => formatter.ReadFromStreamAsync(typeof(SampleType), memoryStream, content, null);\n            await Assert.ThrowsAsync<Exception>(action, \"Throwing exception directly, since it needs to get caught by a catch all\");\n\n            Assert.True(formatter.WasCreateJsonReaderCalled);\n            Assert.False(formatter.WasCreateJsonWriterCalled);\n        }\n\n        [Fact]\n        public async Task FormatterThrowsOnReadWhenOverridenCreateReturnsNull()\n        {\n            // Arrange\n            TestBsonMediaTypeFormatter formatter = new TestBsonMediaTypeFormatter\n            {\n                ReturnNullOncreate = true,\n            };\n\n            byte[] array = Encoding.UTF8.GetBytes(\"foo\");\n            MemoryStream memoryStream = new MemoryStream(array);\n\n            HttpContent content = new StringContent(\"foo\");\n\n            // Act & Assert\n            Func<Task> action = () => formatter.ReadFromStreamAsync(typeof(SampleType), memoryStream, content, null);\n            await Assert.ThrowsAsync<InvalidOperationException>(action, \"The 'CreateJsonReader' method returned null. It must return a JSON reader instance.\");\n\n            Assert.True(formatter.WasCreateJsonReaderCalled);\n            Assert.False(formatter.WasCreateJsonWriterCalled);\n        }\n\n        [Fact]\n        public async Task FormatterThrowsOnReadWithInvalidContent()\n        {\n            // Arrange (serialize Decimal.MaxValue; can't be read back since serialization uses rounded Double)\n            Type variationType = typeof(decimal);\n            decimal testData = Decimal.MaxValue;\n            BsonMediaTypeFormatter formatter = new BsonMediaTypeFormatter();\n            HttpContent content = new StringContent(String.Empty);\n            HttpContentHeaders contentHeaders = content.Headers;\n            MemoryStream stream = new MemoryStream();\n\n            await formatter.WriteToStreamAsync(variationType, testData, stream, content, transportContext: null);\n\n            contentHeaders.ContentLength = stream.Length;\n            stream.Flush();\n            stream.Seek(0L, SeekOrigin.Begin);\n\n            // Act & Assert\n            await Assert.ThrowsAsync<JsonReaderException>(\n                () => formatter.ReadFromStreamAsync(variationType, stream, content, null),\n#if NETCOREAPP3_1_OR_GREATER\n                \"Could not convert to decimal: 7.922816251426434E+28. Path 'Value'.\"\n#else\n                \"Could not convert to decimal: 7.92281625142643E+28. Path 'Value'.\"\n#endif\n                );\n        }\n\n        [Theory]\n        [InlineData(typeof(IList<string>))]\n        [InlineData(typeof(IDictionary<string, object>))]\n        public async Task UseBsonFormatterWithNullCollections(Type type)\n        {\n            // Arrange\n            BsonMediaTypeFormatter formatter = new BsonMediaTypeFormatter();\n            MemoryStream memoryStream = new MemoryStream();\n            HttpContent content = new StringContent(String.Empty);\n\n            // Act & Assert\n            await Assert.Task.SucceedsAsync(formatter.WriteToStreamAsync(type, null, memoryStream, content, transportContext: null));\n            memoryStream.Position = 0;\n            string serializedString = new StreamReader(memoryStream).ReadToEnd();\n            Assert.Empty(serializedString);\n        }\n\n        [Theory]\n        [TestDataSet(typeof(BsonMediaTypeFormatterTests), \"ValueAndRefTypeTestDataCollection\", RoundTripVariations)]\n        public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsync(Type variationType, object testData)\n        {\n            // Arrange\n            BsonMediaTypeFormatter formatter = new BsonMediaTypeFormatter();\n\n            // Arrange & Act & Assert\n            object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n            Assert.Equal(testData, readObj);\n        }\n\n        [Theory]\n        [TestDataSet(typeof(JsonMediaTypeFormatterTests), \"BunchOfJsonObjectsTestDataCollection\", RoundTripVariations)]\n        public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsync_PerhapsJObject(Type variationType, object testData)\n        {\n            // Arrange\n            BsonMediaTypeFormatter formatter = new BsonMediaTypeFormatter();\n\n            // Arrange & Act & Assert\n            object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n\n            JObject readJObject = readObj as JObject;\n            if (readJObject != null)\n            {\n                // Serialized a Dictionary<string, object> to handle simple runtime type; round trips as a JObject\n                Assert.Single(readJObject);\n                JToken readJToken = readJObject[\"Value\"];\n                Assert.NotNull(readJToken);\n                Assert.Equal(testData, readJToken.ToObject(testData.GetType()));\n            }\n            else\n            {\n                Assert.Equal(testData, readObj);\n            }\n        }\n\n        // Test alternate null value\n        [Theory]\n        [TestDataSet(typeof(JsonMediaTypeFormatterTests), \"DBNullAsObjectTestDataCollection\", TestDataVariations.AllSingleInstances)]\n        public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsync_DBNullAsNull(Type variationType, object testData)\n        {\n            // Arrange\n            TestBsonMediaTypeFormatter formatter = new TestBsonMediaTypeFormatter();\n\n            // Arrange & Act & Assert\n            object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n\n            // DBNull.Value can be read back as null object.\n            Assert.Null(readObj);\n        }\n\n#if !NETCOREAPP2_1 // DBNull not serializable on .NET Core 2.1 except at top level (using BsonMediaTypeformatter special case).\n        [Theory]\n        [TestDataSet(typeof(JsonMediaTypeFormatterTests), \"DBNullAsObjectTestDataCollection\", TestDataVariations.AsDictionary)]\n        public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsync_DBNullAsNull_Dictionary(Type variationType, object testData)\n        {\n            // Guard\n            IDictionary<string, object> expectedDictionary = Assert.IsType<Dictionary<string, object>>(testData);\n\n            // Arrange\n            TestBsonMediaTypeFormatter formatter = new TestBsonMediaTypeFormatter();\n\n            // Arrange & Act & Assert\n            object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n\n            // DBNull.Value can be read back as null object. Reach into collections.\n            Assert.Equal(testData.GetType(), readObj.GetType());\n\n            IDictionary<string, object> readDictionary = (IDictionary<string, object>)readObj;\n            Assert.Equal(expectedDictionary.Count, readDictionary.Count);\n\n            foreach (string key in expectedDictionary.Keys)\n            {\n                Assert.True(readDictionary.ContainsKey(key));\n                Assert.Null(readDictionary[key]);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(JsonMediaTypeFormatterTests), \"DBNullAsObjectTestDataCollection\",\n            TestDataVariations.AsArray | TestDataVariations.AsList)]\n        public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsync_DBNullAsNull_Enumerable(Type variationType, object testData)\n        {\n            // Guard\n            Assert.True((testData as IEnumerable<object>) != null);\n\n            // Arrange\n            TestBsonMediaTypeFormatter formatter = new TestBsonMediaTypeFormatter();\n            IEnumerable<object> expectedEnumerable = (IEnumerable<object>)testData;\n\n            // Arrange & Act & Assert\n            object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n\n            // DBNull.Value can be read back as null object. Reach into collections.\n            Assert.Equal(testData.GetType(), readObj.GetType());\n\n            IEnumerable<object> readEnumerable = (IEnumerable<object>)readObj;\n            Assert.Equal(expectedEnumerable.Count(), readEnumerable.Count());\n\n            foreach (object readContent in readEnumerable)\n            {\n                Assert.Null(readContent);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(JsonMediaTypeFormatterTests), \"DBNullAsObjectTestDataCollection\", TestDataVariations.AsClassMember)]\n        public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsync_DBNullAsNull_Holder(Type variationType, object testData)\n        {\n            // Guard\n            Assert.IsType<TestDataHolder<object>>(testData);\n\n            // Arrange\n            TestBsonMediaTypeFormatter formatter = new TestBsonMediaTypeFormatter();\n\n            // Arrange & Act & Assert\n            object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n\n            // DBNull.Value can be read back as null object. Reach into objects.\n            Assert.Equal(testData.GetType(), readObj.GetType());\n\n            TestDataHolder<object> readDataHolder = (TestDataHolder<object>)readObj;\n            Assert.Null(readDataHolder.V1);\n        }\n#endif\n\n        [Fact]\n        public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsync_DBNullAsNullString()\n        {\n            // Arrange\n            TestBsonMediaTypeFormatter formatter = new TestBsonMediaTypeFormatter();\n            Type variationType = typeof(string);\n            object testData = DBNull.Value;\n\n            // Arrange & Act & Assert\n            object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n\n            // Null on wire can be read as null of any nullable type\n            Assert.Null(readObj);\n        }\n\n        [Fact]\n        public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsync_DBNull()\n        {\n            // Arrange\n            TestBsonMediaTypeFormatter formatter = new TestBsonMediaTypeFormatter();\n            Type variationType = typeof(DBNull);\n            object testData = DBNull.Value;\n\n            // Act & Assert\n            object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n\n            // Only BSON case where DBNull.Value round-trips\n            Assert.Equal(testData, readObj);\n        }\n\n        private class TestBsonMediaTypeFormatter : BsonMediaTypeFormatter\n        {\n            public TestBsonMediaTypeFormatter() : base()\n            {\n            }\n\n            public TestBsonMediaTypeFormatter(TestBsonMediaTypeFormatter formatter) : base(formatter)\n            {\n            }\n\n            public bool ReturnNullOncreate { get; set; }\n            public bool ThrowExceptionOnCreate { get; set; }\n            public bool WasCreateJsonReaderCalled { get; private set; }\n            public bool WasCreateJsonWriterCalled { get; private set; }\n\n            public override JsonReader CreateJsonReader(Type type, Stream readStream, Encoding effectiveEncoding)\n            {\n                WasCreateJsonReaderCalled = true;\n                if (ReturnNullOncreate)\n                {\n                    return null;\n                }\n\n                if (ThrowExceptionOnCreate)\n                {\n                    throw new Exception(\"Throwing exception directly, since it needs to get caught by a catch all\");\n                }\n\n                return base.CreateJsonReader(type, readStream, effectiveEncoding);\n            }\n\n            public override JsonWriter CreateJsonWriter(Type type, Stream writeStream, Encoding effectiveEncoding)\n            {\n                WasCreateJsonWriterCalled = true;\n                if (ReturnNullOncreate)\n                {\n                    return null;\n                }\n\n                if (ThrowExceptionOnCreate)\n                {\n                    throw new Exception(\"Throwing exception directly, since it needs to get caught by a catch all\");\n                }\n\n                return base.CreateJsonWriter(type, writeStream, effectiveEncoding);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/BufferedMediaTypeFormatterTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Net.Http.Formatting.DataSets;\nusing System.Net.Http.Headers;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Formatting\n{\n    public class BufferedMediaTypeFormatterTests : MediaTypeFormatterTestBase<MockBufferedMediaTypeFormatter>\n    {\n        private const string ExpectedSupportedMediaType = \"text/test\";\n        private const string TestData = \"Hello World Hello World Hello World Hello World Hello World Hello World\";\n\n        public override IEnumerable<MediaTypeHeaderValue> ExpectedSupportedMediaTypes\n        {\n            get { return new List<MediaTypeHeaderValue> { new MediaTypeHeaderValue(ExpectedSupportedMediaType) }; }\n        }\n\n        public override IEnumerable<Encoding> ExpectedSupportedEncodings\n        {\n            get { return HttpTestData.StandardEncodings; }\n        }\n\n        public override byte[] ExpectedSampleTypeByteRepresentation\n        {\n            get { return ExpectedSupportedEncodings.ElementAt(0).GetBytes(\"System.Net.Http.Formatting.MediaTypeFormatterTestBase`1+SampleType[System.Net.Http.Formatting.MockBufferedMediaTypeFormatter]\"); }\n        }\n\n        [Fact]\n        void CopyConstructor()\n        {\n            MockBufferedMediaTypeFormatter formatter = new MockBufferedMediaTypeFormatter()\n            {\n                BufferSize = 512\n            };\n\n            MockBufferedMediaTypeFormatter derivedFormatter = new MockBufferedMediaTypeFormatter(formatter);\n\n            Assert.Equal(formatter.BufferSize, derivedFormatter.BufferSize);\n        }\n\n        [Fact]\n        public void BufferSize_RoundTrips()\n        {\n            Assert.Reflection.IntegerProperty(\n                new MockBufferedMediaTypeFormatter(),\n                c => c.BufferSize,\n                expectedDefaultValue: 16 * 1024,\n                minLegalValue: 0,\n                illegalLowerValue: -1,\n                maxLegalValue: null,\n                illegalUpperValue: null,\n                roundTripTestValue: 1024);\n        }\n\n        [Fact]\n        public void WriteToStreamAsync_WhenTypeParameterIsNull_ThrowsException()\n        {\n            BufferedMediaTypeFormatter formatter = new MockBufferedMediaTypeFormatter();\n            Assert.ThrowsArgumentNull(\n                () => formatter.WriteToStreamAsync(null, new object(), new MemoryStream(), null, null), \"type\");\n        }\n\n        [Fact]\n        public void WriteToStreamAsync_WhenStreamParameterIsNull_ThrowsException()\n        {\n            BufferedMediaTypeFormatter formatter = new MockBufferedMediaTypeFormatter();\n            Assert.ThrowsArgumentNull(\n                () => formatter.WriteToStreamAsync(typeof(object), new object(), null, null, null), \"writeStream\");\n        }\n\n        [Fact]\n        public void ReadFromStreamAsync_WhenTypeParamterIsNull_ThrowsException()\n        {\n            BufferedMediaTypeFormatter formatter = new MockBufferedMediaTypeFormatter();\n            Assert.ThrowsArgumentNull(() => formatter.ReadFromStreamAsync(null, new MemoryStream(), null, null), \"type\");\n        }\n\n        [Fact]\n        public void ReadFromStreamAsync_WhenStreamParamterIsNull_ThrowsException()\n        {\n            BufferedMediaTypeFormatter formatter = new MockBufferedMediaTypeFormatter();\n            Assert.ThrowsArgumentNull(() => formatter.ReadFromStreamAsync(typeof(object), null, null, null), \"readStream\");\n        }\n\n        [Fact]\n        public async Task BufferedWrite()\n        {\n            // Arrange. Specifically use the base class with async signatures.\n            MediaTypeFormatter formatter = new MockBufferedMediaTypeFormatter();\n            MemoryStream output = new MemoryStream();\n\n            // Act. Call the async signature.\n            await formatter.WriteToStreamAsync(TestData.GetType(), TestData, output, null, null);\n\n            // Assert\n            byte[] expectedBytes = ExpectedSupportedEncodings.ElementAt(0).GetBytes(TestData);\n            byte[] actualBytes = output.ToArray();\n            Assert.Equal(expectedBytes, actualBytes);\n        }\n\n        [Fact]\n        public async Task BufferedRead()\n        {\n            // Arrange. Specifically use the base class with async signatures.\n            MediaTypeFormatter formatter = new MockBufferedMediaTypeFormatter();\n            byte[] expectedBytes = ExpectedSupportedEncodings.ElementAt(0).GetBytes(TestData);\n            MemoryStream input = new MemoryStream(expectedBytes);\n\n            // Act. Call the async signature.\n            object result = await formatter.ReadFromStreamAsync(TestData.GetType(), input, null, null);\n\n            // Assert\n            Assert.Equal(TestData, result);\n        }\n\n        public override Task ReadFromStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding)\n        {\n            // Arrange\n            MediaTypeFormatter formatter = new MockBufferedMediaTypeFormatter();\n            string mediaType = string.Format(\"{0}; charset={1}\", ExpectedSupportedMediaType, encoding);\n\n            // Act & assert\n            return ReadFromStreamAsync_UsesCorrectCharacterEncodingHelper(formatter, content, content, mediaType, encoding, isDefaultEncoding);\n        }\n\n        public override Task WriteToStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding)\n        {\n            // Arrange\n            MediaTypeFormatter formatter = new MockBufferedMediaTypeFormatter();\n            string mediaType = string.Format(\"{0}; charset={1}\", ExpectedSupportedMediaType, encoding);\n\n            // Act & assert\n            return WriteToStreamAsync_UsesCorrectCharacterEncodingHelper(formatter, content, content, mediaType, encoding, isDefaultEncoding);\n        }\n\n        [Fact]\n        public override Task Overridden_ReadFromStreamAsyncWithCancellationToken_GetsCalled()\n        {\n            // ReadFromStreamAsync is not overridable on BufferedMediaTypeFormatter.\n            // So, let this test be a NOOP\n            return TaskHelpers.Completed();\n        }\n\n        [Fact]\n        public override Task Overridden_ReadFromStreamAsyncWithoutCancellationToken_GetsCalled()\n        {\n            // ReadFromStreamAsync is not overridable on BufferedMediaTypeFormatter.\n            // So, let this test be a NOOP\n            return TaskHelpers.Completed();\n        }\n\n        [Fact]\n        public override Task Overridden_WriteToStreamAsyncWithCancellationToken_GetsCalled()\n        {\n            // WriteToStreamAsync is not overridable on BufferedMediaTypeFormatter.\n            // So, let this test be a NOOP\n            return TaskHelpers.Completed();\n        }\n\n        [Fact]\n        public override Task Overridden_WriteToStreamAsyncWithoutCancellationToken_GetsCalled()\n        {\n            // WriteToStreamAsync is not overridable on BufferedMediaTypeFormatter.\n            // So, let this test be a NOOP\n            return TaskHelpers.Completed();\n        }\n    }\n\n    public class MockBufferedMediaTypeFormatter : BufferedMediaTypeFormatter\n    {\n        private const string SupportedMediaType = \"text/test\";\n\n        public MockBufferedMediaTypeFormatter()\n        {\n            SupportedMediaTypes.Add(new MediaTypeHeaderValue(SupportedMediaType));\n\n            // Set default supported character encodings\n            SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true));\n            SupportedEncodings.Add(new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true));\n        }\n\n        public MockBufferedMediaTypeFormatter(MockBufferedMediaTypeFormatter formatter)\n            : base(formatter)\n        {\n        }\n\n        public override bool CanReadType(Type type)\n        {\n            return true;\n        }\n\n        public override bool CanWriteType(Type type)\n        {\n            return true;\n        }\n\n        public override object ReadFromStream(Type type, Stream stream, HttpContent content, IFormatterLogger formatterLogger)\n        {\n            object result = null;\n            HttpContentHeaders contentHeaders = content == null ? null : content.Headers;\n            Encoding effectiveEncoding = SelectCharacterEncoding(contentHeaders);\n            using (StreamReader sReader = new StreamReader(stream, effectiveEncoding))\n            {\n                if (type == typeof(SampleType))\n                {\n                    return new SampleType { Number = 42 };\n                }\n                else\n                {\n                    result = sReader.ReadToEnd();\n                }\n            }\n            return result;\n        }\n\n        public override void WriteToStream(Type type, object value, Stream stream, HttpContent content)\n        {\n            HttpContentHeaders contentHeaders = content == null ? null : content.Headers;\n            Encoding effectiveEncoding = SelectCharacterEncoding(contentHeaders);\n            using (StreamWriter sWriter = new StreamWriter(stream, effectiveEncoding))\n            {\n                if (value != null)\n                {\n                    sWriter.Write(value.ToString());\n                }\n                else\n                {\n                    sWriter.Write(\"null!\");\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/ContentNegotiationResultTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Headers;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Net.Http.Formatting\n{\n    public class ContentNegotiationResultTest\n    {\n        private readonly MediaTypeFormatter _formatter = new Mock<MediaTypeFormatter>().Object;\n        private readonly MediaTypeHeaderValue _mediaType = new MediaTypeHeaderValue(\"app/json\");\n\n        [Fact]\n        public void Constructor_WhenFormatterParameterIsNull_Throws()\n        {\n            Assert.ThrowsArgumentNull(() => new ContentNegotiationResult(formatter: null, mediaType: null), \"formatter\");\n        }\n\n        [Fact]\n        public void MediaTypeProperty()\n        {\n            Assert.Reflection.Property(new ContentNegotiationResult(_formatter, _mediaType),\n                nr => nr.MediaType, _mediaType, allowNull: true, roundTripTestValue: new MediaTypeHeaderValue(\"foo/bar\"));\n        }\n\n        [Fact]\n        public void FormatterProperty()\n        {\n            Assert.Reflection.Property(new ContentNegotiationResult(_formatter, _mediaType),\n                nr => nr.Formatter, _formatter, allowNull: false, roundTripTestValue: new JsonMediaTypeFormatter());\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/DataContractJsonMediaTypeFormatterTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Net.Http.Formatting.DataSets;\nusing System.Net.Http.Formatting.DataSets.Types;\nusing System.Net.Http.Headers;\nusing System.Runtime.Serialization.Json;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Formatting\n{\n    public class DataContractJsonMediaTypeFormatter : JsonMediaTypeFormatter\n    {\n        public DataContractJsonMediaTypeFormatter()\n        {\n            UseDataContractJsonSerializer = true;\n        }\n    }\n\n    public class DataContractJsonMediaTypeFormatterTests : MediaTypeFormatterTestBase<DataContractJsonMediaTypeFormatter>\n    {\n        public static readonly TheoryDataSet<Type> AFewValidTypes = new()\n        {\n            typeof(bool),\n            typeof(int),\n            typeof(string),\n        };\n\n        public override IEnumerable<MediaTypeHeaderValue> ExpectedSupportedMediaTypes\n        {\n            get { return HttpTestData.StandardJsonMediaTypes; }\n        }\n\n        public override IEnumerable<Encoding> ExpectedSupportedEncodings\n        {\n            get { return HttpTestData.StandardEncodings; }\n        }\n\n        public override byte[] ExpectedSampleTypeByteRepresentation\n        {\n            get { return ExpectedSupportedEncodings.ElementAt(0).GetBytes(\"{\\\"Number\\\":42}\"); }\n        }\n\n        [Fact]\n        public void DefaultMediaType_ReturnsApplicationJson()\n        {\n            MediaTypeHeaderValue mediaType = DataContractJsonMediaTypeFormatter.DefaultMediaType;\n            Assert.NotNull(mediaType);\n            Assert.Equal(\"application/json\", mediaType.MediaType);\n        }\n\n        [Fact]\n        public void Indent_RoundTrips()\n        {\n            Assert.Reflection.BooleanProperty(\n                new XmlMediaTypeFormatter(),\n                c => c.Indent,\n                expectedDefaultValue: false);\n        }\n\n        [Fact]\n        public void MaxDepth_RoundTrips()\n        {\n            Assert.Reflection.IntegerProperty(\n                new DataContractJsonMediaTypeFormatter(),\n                c => c.MaxDepth,\n                expectedDefaultValue: 256,\n                minLegalValue: 1,\n                illegalLowerValue: 0,\n                maxLegalValue: null,\n                illegalUpperValue: null,\n                roundTripTestValue: 256);\n        }\n\n        [Theory]\n        [TestDataSet(typeof(CommonUnitTestDataSets), \"RepresentativeValueAndRefTypeTestDataCollection\")]\n        public void CanReadType_ReturnsExpectedValues(Type variationType, object testData)\n        {\n            TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter();\n\n            bool isSerializable = IsTypeSerializableWithJsonSerializer(variationType, testData);\n            bool canSupport = formatter.CanReadTypeProxy(variationType);\n\n            // If we don't agree, we assert only if the DCJ serializer says it cannot support something we think it should\n            Assert.False(isSerializable != canSupport && isSerializable, String.Format(\"CanReadType returned wrong value for '{0}'.\", variationType));\n\n            // Ask a 2nd time to probe whether the cached result is treated the same\n            canSupport = formatter.CanReadTypeProxy(variationType);\n            Assert.False(isSerializable != canSupport && isSerializable, String.Format(\"2nd CanReadType returned wrong value for '{0}'.\", variationType));\n        }\n\n        [Theory]\n        [PropertyData(nameof(AFewValidTypes))]\n        public void CanWriteType_ReturnsFalse_ForValidTypes(Type type)\n        {\n            XmlMediaTypeFormatter formatter = new();\n\n            var canWrite = formatter.CanWriteType(type);\n\n#if Testing_NetStandard1_3 // Different behavior in netstandard1.3 due to no DataContract validation.\n            Assert.False(canWrite);\n#else\n            Assert.True(canWrite);\n#endif\n        }\n\n        public class InvalidDataContract\n        {\n            // removing the default ctor makes this invalid\n            public InvalidDataContract(string s)\n            {\n            }\n        }\n\n#if !Testing_NetStandard1_3 // Cannot read or write w/ DCS in netstandard1.3.\n        [Theory]\n        [InlineData(typeof(IQueryable<string>))]\n        [InlineData(typeof(IEnumerable<string>))]\n        public async Task UseJsonFormatterWithNull(Type type)\n        {\n            JsonMediaTypeFormatter xmlFormatter = new DataContractJsonMediaTypeFormatter();\n            MemoryStream memoryStream = new MemoryStream();\n            HttpContent content = new StringContent(String.Empty);\n            await Assert.Task.SucceedsAsync(xmlFormatter.WriteToStreamAsync(type, null, memoryStream, content, transportContext: null));\n            memoryStream.Position = 0;\n            string serializedString = new StreamReader(memoryStream).ReadToEnd();\n            Assert.True(serializedString.Contains(\"null\"), \"Using Json formatter to serialize null should emit 'null'.\");\n        }\n#endif\n\n        [Theory]\n        [TestDataSet(typeof(JsonMediaTypeFormatterTests), \"ValueAndRefTypeTestDataCollectionExceptULong\", RoundTripDataVariations)]\n        public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsync(Type variationType, object testData)\n        {\n            // Guard\n            bool canSerialize = IsTypeSerializableWithJsonSerializer(variationType, testData) && Assert.Http.CanRoundTrip(variationType);\n            if (canSerialize)\n            {\n                // Arrange\n                TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter();\n\n                // Arrange & Act & Assert\n                object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n                Assert.Equal(testData, readObj);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(XmlMediaTypeFormatterTests), \"BunchOfTypedObjectsTestDataCollection\", RoundTripDataVariations)]\n        public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsync_KnownTypes(Type variationType, object testData)\n        {\n            // Guard\n            bool canSerialize = IsTypeSerializableWithJsonSerializer(variationType, testData) && Assert.Http.CanRoundTrip(variationType);\n            if (canSerialize)\n            {\n                // Arrange\n                TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter { AddDBNullKnownType = true, };\n\n                // Arrange & Act & Assert\n                object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n                Assert.Equal(testData, readObj);\n            }\n        }\n\n#if Testing_NetStandard1_3 // Cannot read or write w/ DCS in netstandard1.3.\n        [Theory]\n        [TestDataSet(typeof(CommonUnitTestDataSets), \"RepresentativeValueAndRefTypeTestDataCollection\", RoundTripDataVariations)]\n        public async Task ReadFromStreamAsync_UsingDataContractSerializer_Throws(Type variationType, object testData)\n        {\n            // Arrange. First, get some data using XmlSerializer.\n            bool canSerialize = IsTypeSerializableWithJsonSerializer(variationType, testData, actuallyCheck: true) &&\n                Assert.Http.CanRoundTrip(variationType);\n            if (canSerialize)\n            {\n                var formatter = new JsonMediaTypeFormatter();\n                using var stream = new MemoryStream();\n                using var content = new StringContent(string.Empty);\n\n                await formatter.WriteToStreamAsync(variationType, testData, stream, content, transportContext: null);\n                await stream.FlushAsync();\n                stream.Position = 0L;\n\n                content.Headers.ContentLength = stream.Length;\n                formatter.UseDataContractJsonSerializer = true;\n\n                // Act & Assert\n                await Assert.ThrowsAsync<PlatformNotSupportedException>(() =>\n                    formatter.ReadFromStreamAsync(variationType, stream, content, formatterLogger: null),\n                    \"Unable to validate types on this platform when UseDataContractJsonSerializer is 'true'. \" +\n                    \"Please reset UseDataContractJsonSerializer or move to a supported platform, one where the \" +\n                    \".NET Standard 2.0 assembly is usable.\");\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(CommonUnitTestDataSets), \"RepresentativeValueAndRefTypeTestDataCollection\", RoundTripDataVariations)]\n        public async Task WriteToStreamAsync_UsingDataContractSerializer_Throws(Type variationType, object testData)\n        {\n            // Arrange\n            var formatter = new JsonMediaTypeFormatter() { UseDataContractJsonSerializer = true};\n            using var stream = new MemoryStream();\n            using var content = new StringContent(string.Empty);\n\n            // Act & Assert\n            await Assert.ThrowsAsync<PlatformNotSupportedException>(() =>\n                formatter.WriteToStreamAsync(variationType, testData, stream, content, transportContext: null),\n                \"Unable to validate types on this platform when UseDataContractJsonSerializer is 'true'. \" +\n                \"Please reset UseDataContractJsonSerializer or move to a supported platform, one where the \" +\n                \".NET Standard 2.0 assembly is usable.\");\n        }\n\n#else\n#if !NETCOREAPP2_1 // DBNull not serializable on .NET Core 2.1.\n        // Test alternate null value\n        [Fact]\n        public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsync_DBNull()\n        {\n            // Arrange\n            TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter();\n            Type variationType = typeof(DBNull);\n            object testData = DBNull.Value;\n\n            // Arrange & Act & Assert\n            object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n\n            // DBNull.Value round-trips as either Object or DBNull because serialization includes its type\n            Assert.Equal(testData, readObj);\n        }\n\n        [Fact]\n        public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsync_DBNullAsEmptyString()\n        {\n            // Arrange\n            TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter { AddDBNullKnownType = true, };\n            Type variationType = typeof(string);\n            object testData = DBNull.Value;\n\n            // Arrange & Act & Assert\n            object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n\n            // Lower levels convert DBNull.Value to empty string on read\n            Assert.Equal(String.Empty, readObj);\n        }\n#endif\n\n        [Fact]\n        public async Task UseDataContractJsonSerializer_Default()\n        {\n            DataContractJsonMediaTypeFormatter jsonFormatter = new DataContractJsonMediaTypeFormatter();\n            MemoryStream memoryStream = new MemoryStream();\n            HttpContent content = new StringContent(String.Empty);\n            await Assert.Task.SucceedsAsync(jsonFormatter.WriteToStreamAsync(typeof(SampleType), new SampleType(), memoryStream, content, transportContext: null));\n            memoryStream.Position = 0;\n            string serializedString = new StreamReader(memoryStream).ReadToEnd();\n            Assert.False(serializedString.Contains(\"\\r\\n\"), \"Using DCJS should emit data without indentation by default.\");\n        }\n#endif\n\n        [Fact]\n        public void UseDataContractJsonSerializer_True_Indent_Throws()\n        {\n            DataContractJsonMediaTypeFormatter jsonFormatter = new DataContractJsonMediaTypeFormatter { Indent = true };\n            MemoryStream memoryStream = new MemoryStream();\n            HttpContent content = new StringContent(String.Empty);\n            Assert.Throws<NotSupportedException>(\n                () => jsonFormatter.WriteToStreamAsync(typeof(SampleType),\n                    new SampleType(),\n                    memoryStream, content, transportContext: null));\n        }\n\n#if Testing_NetStandard1_3 // Cannot read or write w/ DCS in netstandard1.3.\n        [Fact]\n        public override Task Overridden_ReadFromStreamAsyncWithCancellationToken_GetsCalled()\n        {\n            return Task.CompletedTask;\n        }\n\n        [Fact]\n        public override Task Overridden_ReadFromStreamAsyncWithoutCancellationToken_GetsCalled()\n        {\n            return Task.CompletedTask;\n        }\n\n        [Fact]\n        public override Task Overridden_WriteToStreamAsyncWithCancellationToken_GetsCalled()\n        {\n            return Task.CompletedTask;\n        }\n\n        [Fact]\n        public override Task Overridden_WriteToStreamAsyncWithoutCancellationToken_GetsCalled()\n        {\n            return Task.CompletedTask;\n        }\n\n        [Fact]\n        public override Task ReadFromStreamAsync_ReadsDataButDoesNotCloseStream()\n        {\n            return Task.CompletedTask;\n        }\n\n        // Attributes are in base class.\n        public override Task ReadFromStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding)\n        {\n            return Task.CompletedTask;\n        }\n\n        [Fact]\n        public override Task ReadFromStreamAsync_WhenContentLengthIsNull_ReadsDataButDoesNotCloseStream()\n        {\n            return Task.CompletedTask;\n        }\n\n        // Attributes are in base class.\n        public override Task WriteToStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding)\n        {\n            return Task.CompletedTask;\n        }\n\n        [Fact]\n        public override Task WriteToStreamAsync_WhenObjectIsNull_WritesDataButDoesNotCloseStream()\n        {\n            return Task.CompletedTask;\n        }\n\n        [Fact]\n        public override Task WriteToStreamAsync_WritesDataButDoesNotCloseStream()\n        {\n            return Task.CompletedTask;\n        }\n#else\n        public override Task ReadFromStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding)\n        {\n            // Arrange\n            DataContractJsonMediaTypeFormatter formatter = new DataContractJsonMediaTypeFormatter();\n            string formattedContent = \"\\\"\" + content + \"\\\"\";\n            string mediaType = string.Format(\"application/json; charset={0}\", encoding);\n\n            // Act & assert\n            return ReadContentUsingCorrectCharacterEncodingHelperAsync(\n                formatter, content, formattedContent, mediaType, encoding, isDefaultEncoding);\n        }\n\n        public override Task WriteToStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding)\n        {\n            // Arrange\n            DataContractJsonMediaTypeFormatter formatter = new DataContractJsonMediaTypeFormatter();\n            string formattedContent = \"\\\"\" + content + \"\\\"\";\n            string mediaType = string.Format(\"application/json; charset={0}\", encoding);\n\n            // Act & assert\n            return WriteContentUsingCorrectCharacterEncodingHelperAsync(\n                formatter, content, formattedContent, mediaType, encoding, isDefaultEncoding);\n        }\n#endif\n\n        public class TestJsonMediaTypeFormatter : DataContractJsonMediaTypeFormatter\n        {\n            public bool AddDBNullKnownType { get; set; }\n\n            public bool CanReadTypeProxy(Type type)\n            {\n                return CanReadType(type);\n            }\n\n            public bool CanWriteTypeProxy(Type type)\n            {\n                return CanWriteType(type);\n            }\n\n            public override DataContractJsonSerializer CreateDataContractSerializer(Type type)\n            {\n                if (AddDBNullKnownType)\n                {\n                    return new DataContractJsonSerializer(type, new Type[] { typeof(DBNull), });\n                }\n                else\n                {\n                    return base.CreateDataContractSerializer(type);\n                }\n            }\n        }\n\n        private bool IsTypeSerializableWithJsonSerializer(Type type, object obj, bool actuallyCheck = false)\n        {\n#if Testing_NetStandard1_3 // Different behavior in netstandard1.3 due to no DataContract validation.\n            if (!actuallyCheck)\n            {\n                return false;\n            }\n#endif\n\n            try\n            {\n                new DataContractJsonSerializer(type);\n                if (obj != null && obj.GetType() != type)\n                {\n                    new DataContractJsonSerializer(obj.GetType());\n                }\n            }\n            catch\n            {\n                return false;\n            }\n\n            return !Assert.Http.IsKnownUnserializable(type, obj, (t) => typeof(INotJsonSerializable).IsAssignableFrom(t));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/DefaultContentNegotiatorTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http.Formatting.Mocks;\nusing System.Net.Http.Headers;\nusing System.Text;\nusing Microsoft.TestCommon;\nusing Newtonsoft.Json.Linq;\n\nnamespace System.Net.Http.Formatting\n{\n    public class DefaultContentNegotiatorTests\n    {\n        private readonly DefaultContentNegotiator _negotiator = new DefaultContentNegotiator();\n        private readonly HttpRequestMessage _request = new HttpRequestMessage();\n\n        public static TheoryDataSet<string, string[], string> MatchRequestMediaTypeData\n        {\n            get\n            {\n                // string requestMediaType, string[] supportedMediaTypes, string expectedMediaType\n                return new TheoryDataSet<string, string[], string>\n                {\n                    { \"text/plain\", new string[0], null }, \n                    { \"text/plain\", new string[] { \"text/xml\", \"application/xml\" }, null }, \n                    { \"application/xml\", new string[] { \"application/xml\", \"text/xml\" }, \"application/xml\" }, \n                    { \"APPLICATION/XML\", new string[] { \"text/xml\", \"application/xml\" }, \"application/xml\" }, \n                    { \"application/xml; charset=utf-8\", new string[] { \"text/xml\", \"application/xml\" }, \"application/xml\" }, \n                    { \"application/xml; charset=utf-8; parameter=value\", new string[] { \"text/xml\", \"application/xml\" }, \"application/xml\" }, \n                };\n            }\n        }\n\n        public static TheoryDataSet<string[], string[], string, double, int> MatchAcceptHeaderData\n        {\n            get\n            {\n                // string[] acceptHeader, string[] supportedMediaTypes, string expectedMediaType, double matchQuality, int range\n                return new TheoryDataSet<string[], string[], string, double, int>\n                {\n                    { new string[] { \"text/plain\" }, new string[0], null, 0.0, (int)MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderLiteral }, \n\n                    { new string[] { \"text/plain\" }, new string[] { \"text/xml\", \"application/xml\" }, null, 0.0, (int)MediaTypeFormatterMatchRanking.None }, \n                    { new string[] { \"text/plain; q=0.5\" }, new string[] { \"text/xml\", \"application/xml\" }, null, 0.0, (int)MediaTypeFormatterMatchRanking.None }, \n\n                    { new string[] { \"application/xml\" }, new string[] { \"application/xml\", \"text/xml\" }, \"application/xml\", 1.0, (int)MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderLiteral }, \n                    { new string[] { \"APPLICATION/XML; q=0.5\" }, new string[] { \"text/xml\", \"application/xml\" }, \"application/xml\", 0.5, (int)MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderLiteral }, \n                    { new string[] { \"text/xml; q=0.5\", \"APPLICATION/XML; q=0.7\" }, new string[] { \"text/xml\", \"application/xml\" }, \"application/xml\", 0.7, (int)MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderLiteral }, \n                    { new string[] { \"application/xml; q=0.0\" }, new string[] { \"application/xml\", \"text/xml\" }, null, 0.0, (int)MediaTypeFormatterMatchRanking.None }, \n                    { new string[] { \"APPLICATION/XML; q=0.0\" }, new string[] { \"text/xml\", \"application/xml\" }, null, 0.0, (int)MediaTypeFormatterMatchRanking.None }, \n                    { new string[] { \"text/xml; q=0.0\", \"APPLICATION/XML; q=0.0\" }, new string[] { \"text/xml\", \"application/xml\" }, null, 0.0, (int)MediaTypeFormatterMatchRanking.None }, \n\n                    { new string[] { \"text/*\" }, new string[] { \"text/xml\", \"application/xml\" }, \"text/xml\", 1.0, (int)MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderSubtypeMediaRange }, \n                    { new string[] { \"text/*\", \"application/xml\" }, new string[] { \"text/xml\", \"application/xml\" }, \"application/xml\", 1.0, (int)MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderLiteral }, \n                    { new string[] { \"text/*\", \"application/xml; q=0.5\" }, new string[] { \"text/xml\", \"application/xml\" }, \"text/xml\", 1.0, (int)MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderSubtypeMediaRange }, \n                    { new string[] { \"text/*; q=0.5\" }, new string[] { \"text/xml\", \"application/xml\" }, \"text/xml\", 0.5, (int)MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderSubtypeMediaRange }, \n                    { new string[] { \"text/*; q=0.5\", \"application/xml\" }, new string[] { \"text/xml\", \"application/xml\" }, \"application/xml\", 1.0, (int)MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderLiteral }, \n                    { new string[] { \"text/*; q=0.0\", \"application/xml; q=0.0\" }, new string[] { \"text/xml\", \"application/xml\" }, null, 0.0, (int)MediaTypeFormatterMatchRanking.None }, \n                    { new string[] { \"text/*; q=0.0\", \"application/xml\" }, new string[] { \"text/xml\", \"application/xml\" }, \"application/xml\", 1.0, (int)MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderLiteral }, \n\n                    { new string[] { \"*/*; q=0.5\" }, new string[] { \"text/xml\", \"application/xml\" }, \"text/xml\", 0.5, (int)MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderAllMediaRange }, \n                    { new string[] { \"*/*; q=0.0\" }, new string[] { \"text/xml\", \"application/xml\" }, null, 0.0, (int)MediaTypeFormatterMatchRanking.None }, \n                    { new string[] { \"*/*; q=0.5\", \"application/xml\" }, new string[] { \"text/xml\", \"application/xml\" }, \"application/xml\", 1.0, (int)MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderLiteral }, \n                    { new string[] { \"*/*; q=1.0\", \"application/xml; q=0.5\" }, new string[] { \"text/xml\", \"application/xml\" }, \"text/xml\", 1.0, (int)MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderAllMediaRange }, \n                    { new string[] { \"*/*\", \"application/xml\" }, new string[] { \"text/xml\", \"application/xml\" }, \"application/xml\", 1.0, (int)MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderLiteral },\n\n                    { new string[] { \"text/*; q=0.5\", \"*/*; q=0.2\", \"application/xml; q=1.0\" }, new string[] { \"text/xml\", \"application/xml\" }, \"application/xml\", 1.0,  (int)MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderLiteral }, \n\n                    { new string[] { \"application/xml; q=0.5\" }, new string[] { \"text/xml\", \"application/xml\" }, \"application/xml\", 0.5, (int)MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderLiteral }, \n                };\n            }\n        }\n\n        public static TheoryDataSet<bool, string[], bool> ShouldMatchOnTypeData\n        {\n            get\n            {\n                // bool excludeMatchOnType, string[] acceptHeaders, bool expectedResult\n                return new TheoryDataSet<bool, string[], bool>\n                {\n                    { false, new string[0], true }, \n                    { true, new string[0], true }, \n\n                    { false, new string[] { \"application/xml\" }, true }, \n                    { true, new string[] { \"application/xml\" }, false }, \n                    \n                    { false, new string[] { \"application/xml; q=1.0\" }, true }, \n                    { true, new string[] { \"application/xml; q=1.0\" }, false }, \n\n                    { false, new string[] { \"application/xml; q=0.0\" }, true }, \n                    { true, new string[] { \"application/xml; q=0.0\" }, false }, \n\n                    { false, new string[] { \"application/xml; q=0.0\", \"application/json\" }, true }, \n                    { true, new string[] { \"application/xml; q=0.0\", \"application/json\" }, false }, \n\n                    { false, new string[] { \"text/nomatch\" }, true }, \n                    { true, new string[] { \"text/nomatch\" }, false }, \n                };\n            }\n        }\n\n        public static TheoryDataSet<string[], string> MatchTypeData\n        {\n            get\n            {\n                // string[] supportedMediaTypes, string expectedMediaType\n                return new TheoryDataSet<string[], string>\n                {\n                    { new string[0], \"application/octet-stream\" }, \n\n                    { new string[] { \"text/xml\", \"application/xml\" }, \"text/xml\" }, \n                    { new string[] { \"application/xml\", \"text/xml\" }, \"application/xml\" }, \n                };\n            }\n        }\n\n        public static TheoryDataSet<string[], string, string[], string> SelectResponseCharacterEncodingData\n        {\n            get\n            {\n                // string[] acceptEncodings, string requestEncoding, string[] supportedEncodings, string expectedEncoding\n                return new TheoryDataSet<string[], string, string[], string>\n                {\n                    { new string[] { \"utf-8\" }, null, new string[0], null },\n                    { new string[0], \"utf-8\", new string[0], null },\n\n                    { new string[0], null, new string[] { \"utf-8\", \"utf-16\"}, \"utf-8\" },\n                    { new string[0], \"utf-16\", new string[] { \"utf-8\", \"utf-16\"}, \"utf-16\" },\n\n                    { new string[] { \"utf-8\" }, null, new string[] { \"utf-8\", \"utf-16\"}, \"utf-8\" },\n                    { new string[] { \"utf-16\" }, \"utf-8\", new string[] { \"utf-8\", \"utf-16\"}, \"utf-16\" },\n                    { new string[] { \"utf-16; q=0.5\" }, \"utf-8\", new string[] { \"utf-8\", \"utf-16\"}, \"utf-16\" },\n\n                    { new string[] { \"utf-8; q=0.0\" }, null, new string[] { \"utf-8\", \"utf-16\"}, \"utf-8\" },\n                    { new string[] { \"utf-8; q=0.0\" }, \"utf-16\", new string[] { \"utf-8\", \"utf-16\"}, \"utf-16\" },\n                    { new string[] { \"utf-8; q=0.0\", \"utf-16; q=0.0\" }, \"utf-16\", new string[] { \"utf-8\", \"utf-16\"}, \"utf-16\" },\n                    { new string[] { \"utf-8; q=0.0\", \"utf-16; q=0.0\" }, null, new string[] { \"utf-8\", \"utf-16\"}, \"utf-8\" },\n                    { new string[] { \"*; q=0.0\" }, null, new string[] { \"utf-8\", \"utf-16\"}, \"utf-8\" },\n                    { new string[] { \"*; q=0.0\" }, \"utf-16\", new string[] { \"utf-8\", \"utf-16\"}, \"utf-16\" },\n                };\n            }\n        }\n\n        public static TheoryDataSet<ICollection<MediaTypeFormatterMatch>, MediaTypeFormatterMatch> SelectResponseMediaTypeData\n        {\n            get\n            {\n                // Only mapping and accept makes sense with q != 1.0\n                MediaTypeFormatterMatch matchMapping10 = CreateMatch(1.0, MediaTypeFormatterMatchRanking.MatchOnRequestWithMediaTypeMapping);\n                MediaTypeFormatterMatch matchMapping05 = CreateMatch(0.5, MediaTypeFormatterMatchRanking.MatchOnRequestWithMediaTypeMapping);\n\n                MediaTypeFormatterMatch matchAccept10 = CreateMatch(1.0, MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderLiteral);\n                MediaTypeFormatterMatch matchAccept05 = CreateMatch(0.5, MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderLiteral);\n\n                MediaTypeFormatterMatch matchAcceptSubTypeRange10 = CreateMatch(1.0, MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderSubtypeMediaRange);\n                MediaTypeFormatterMatch matchAcceptSubTypeRange05 = CreateMatch(0.5, MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderSubtypeMediaRange);\n\n                MediaTypeFormatterMatch matchAcceptAllRange10 = CreateMatch(1.0, MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderAllMediaRange);\n                MediaTypeFormatterMatch matchAcceptAllRange05 = CreateMatch(0.5, MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderAllMediaRange);\n\n                MediaTypeFormatterMatch matchRequest10 = CreateMatch(1.0, MediaTypeFormatterMatchRanking.MatchOnRequestMediaType);\n                MediaTypeFormatterMatch matchType10 = CreateMatch(1.0, MediaTypeFormatterMatchRanking.MatchOnCanWriteType);\n\n                // ICollection<MediaTypeFormatterMatch> candidateMatches, MediaTypeFormatterMatch winner\n                return new TheoryDataSet<ICollection<MediaTypeFormatterMatch>, MediaTypeFormatterMatch>\n                {\n                    { new List<MediaTypeFormatterMatch>(), null },\n                    { new List<MediaTypeFormatterMatch>() { matchType10 }, matchType10 },\n                    { new List<MediaTypeFormatterMatch>() { matchType10, matchRequest10 }, matchRequest10 },\n                    { new List<MediaTypeFormatterMatch>() { matchType10, matchRequest10, matchAcceptAllRange10 }, matchAcceptAllRange10 },\n                    { new List<MediaTypeFormatterMatch>() { matchType10, matchRequest10, matchAcceptAllRange10, matchAcceptSubTypeRange10 }, matchAcceptSubTypeRange10 },\n                    { new List<MediaTypeFormatterMatch>() { matchType10, matchRequest10, matchAcceptAllRange10, matchAcceptSubTypeRange10, matchAccept10 }, matchAccept10 },\n                    { new List<MediaTypeFormatterMatch>() { matchType10, matchRequest10, matchAcceptAllRange10, matchAcceptSubTypeRange10, matchAccept10, matchMapping10 }, matchMapping10 },\n\n                    { new List<MediaTypeFormatterMatch>() { matchAccept05, matchAccept10 }, matchAccept10 },\n                    { new List<MediaTypeFormatterMatch>() { matchAccept10, matchAccept05 }, matchAccept10 },\n\n                    { new List<MediaTypeFormatterMatch>() { matchAcceptSubTypeRange05, matchAcceptSubTypeRange10 }, matchAcceptSubTypeRange10 },\n                    { new List<MediaTypeFormatterMatch>() { matchAcceptSubTypeRange10, matchAcceptSubTypeRange05 }, matchAcceptSubTypeRange10 },\n\n                    { new List<MediaTypeFormatterMatch>() { matchAcceptAllRange05, matchAcceptAllRange10 }, matchAcceptAllRange10 },\n                    { new List<MediaTypeFormatterMatch>() { matchAcceptAllRange10, matchAcceptAllRange05 }, matchAcceptAllRange10 },\n\n                    { new List<MediaTypeFormatterMatch>() { matchMapping05, matchMapping10 }, matchMapping10 },\n                    { new List<MediaTypeFormatterMatch>() { matchMapping10, matchMapping05 }, matchMapping10 },\n\n                    { new List<MediaTypeFormatterMatch>() { matchMapping05, matchAccept05 }, matchMapping05 },\n                    { new List<MediaTypeFormatterMatch>() { matchMapping10, matchAccept10 }, matchMapping10 },\n\n                    { new List<MediaTypeFormatterMatch>() { matchMapping05, matchAcceptSubTypeRange05 }, matchMapping05 },\n                    { new List<MediaTypeFormatterMatch>() { matchMapping10, matchAcceptSubTypeRange10 }, matchMapping10 },\n\n                    { new List<MediaTypeFormatterMatch>() { matchMapping05, matchAcceptAllRange05 }, matchMapping05 },\n                    { new List<MediaTypeFormatterMatch>() { matchMapping10, matchAcceptAllRange10 }, matchMapping10 },\n\n                    { new List<MediaTypeFormatterMatch>() { matchMapping05, matchAccept10 }, matchAccept10 },\n                    { new List<MediaTypeFormatterMatch>() { matchMapping05, matchAcceptSubTypeRange10 }, matchAcceptSubTypeRange10 },\n                    { new List<MediaTypeFormatterMatch>() { matchMapping05, matchAcceptAllRange10 }, matchAcceptAllRange10 },\n                };\n            }\n        }\n\n        public static TheoryDataSet<MediaTypeFormatterMatch, MediaTypeFormatterMatch, bool> UpdateBestMatchData\n        {\n            get\n            {\n                MediaTypeFormatterMatch matchMapping10 = CreateMatch(1.0, MediaTypeFormatterMatchRanking.None);\n                MediaTypeFormatterMatch matchMapping05 = CreateMatch(0.5, MediaTypeFormatterMatchRanking.None);\n\n                // MediaTypeFormatterMatch current, MediaTypeFormatterMatch potentialReplacement, currentWins\n                return new TheoryDataSet<MediaTypeFormatterMatch, MediaTypeFormatterMatch, bool>\n                {\n                    { null, matchMapping10, false },\n                    { null, matchMapping05, false },\n\n                    { matchMapping10, matchMapping10, true },\n                    { matchMapping10, matchMapping05, true },\n\n                    { matchMapping05, matchMapping10, false },\n                    { matchMapping05, matchMapping05, true },\n                };\n            }\n        }\n\n        private static MediaTypeFormatterMatch CreateMatch(double? quality, MediaTypeFormatterMatchRanking ranking)\n        {\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();\n            MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue(\"text/test\");\n            return new MediaTypeFormatterMatch(formatter, mediaType, quality, ranking);\n        }\n\n        [Fact]\n        public void TypeIsCorrect()\n        {\n            Assert.Type.HasProperties(typeof(DefaultContentNegotiator), TypeAssert.TypeProperties.IsPublicVisibleClass);\n        }\n\n        [Fact]\n        public void Negotiate_WhenTypeParameterIsNull_ThrowsException()\n        {\n            Assert.ThrowsArgumentNull(() => _negotiator.Negotiate(null, _request, Enumerable.Empty<MediaTypeFormatter>()), \"type\");\n        }\n\n        [Fact]\n        public void Negotiate_WhenRequestParameterIsNull_ThrowsException()\n        {\n            Assert.ThrowsArgumentNull(() => _negotiator.Negotiate(typeof(string), null, Enumerable.Empty<MediaTypeFormatter>()), \"request\");\n        }\n\n        [Fact]\n        public void Negotiate_WhenFormattersParameterIsNull_ThrowsException()\n        {\n            Assert.ThrowsArgumentNull(() => _negotiator.Negotiate(typeof(string), _request, null), \"formatters\");\n        }\n\n        [Fact]\n        public void Negotiate_ForEmptyFormatterCollection_ReturnsNull()\n        {\n            var result = _negotiator.Negotiate(typeof(string), _request, Enumerable.Empty<MediaTypeFormatter>());\n\n            Assert.Null(result);\n        }\n\n        [Fact]\n        public void Negotiate_MediaTypeMappingTakesPrecedenceOverAcceptHeader()\n        {\n            // Prepare the request message\n            _request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(\"application/xml\"));\n            _request.Headers.Add(\"Browser\", \"IE\");\n            _request.Headers.Add(\"Cookie\", \"ABC\");\n\n            // Prepare the formatters\n            List<MediaTypeFormatter> formatters = new List<MediaTypeFormatter>();\n            formatters.Add(new JsonMediaTypeFormatter());\n            formatters.Add(new XmlMediaTypeFormatter());\n            PlainTextFormatter frmtr = new PlainTextFormatter();\n            frmtr.SupportedMediaTypes.Clear();\n            frmtr.MediaTypeMappings.Clear();\n            frmtr.SupportedMediaTypes.Add(new MediaTypeHeaderValue(\"application/xml\"));\n            frmtr.MediaTypeMappings.Add(new MyMediaTypeMapping(new MediaTypeHeaderValue((\"application/xml\"))));\n            formatters.Add(frmtr);\n\n            // Act\n            var result = _negotiator.Negotiate(typeof(string), _request, formatters);\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Equal(\"application/xml\", result.MediaType.MediaType);\n            Assert.IsType<PlainTextFormatter>(result.Formatter);\n        }\n\n        [Fact]\n        public void Negotiate_ForRequestReturnsFirstMatchingFormatter()\n        {\n            MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue(\"application/myMediaType\");\n\n            MediaTypeFormatter formatter1 = new MockMediaTypeFormatter()\n            {\n                CanWriteTypeCallback = (Type t) => false\n            };\n\n            MediaTypeFormatter formatter2 = new MockMediaTypeFormatter()\n            {\n                CanWriteTypeCallback = (Type t) => true\n            };\n\n            formatter2.SupportedMediaTypes.Add(mediaType);\n\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection(\n                new MediaTypeFormatter[] \n                {\n                    formatter1,\n                    formatter2\n                });\n\n            _request.Content = new StringContent(\"test\", Encoding.Default, mediaType.MediaType);\n\n            var result = _negotiator.Negotiate(typeof(string), _request, collection);\n            Assert.Same(formatter2, result.Formatter);\n            Assert.MediaType.AreEqual(mediaType, result.MediaType, \"Expected the formatter's media type to be returned.\");\n        }\n\n        [Fact]\n        public void Negotiate_SelectsJsonAsDefaultFormatter()\n        {\n            // Arrange\n            _request.Content = new StringContent(\"test\");\n\n            // Act\n            var result = _negotiator.Negotiate(typeof(string), _request, new MediaTypeFormatterCollection());\n\n            // Assert\n            Assert.IsType<JsonMediaTypeFormatter>(result.Formatter);\n            Assert.Equal(MediaTypeConstants.ApplicationJsonMediaType.MediaType, result.MediaType.MediaType);\n        }\n\n        [Fact]\n        public void Negotiate_SelectsXmlFormatter_ForXhrRequestThatAcceptsXml()\n        {\n            // Arrange\n            _request.Content = new StringContent(\"test\");\n            _request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(\"application/xml\"));\n            _request.Headers.Add(\"x-requested-with\", \"XMLHttpRequest\");\n\n            // Act\n            var result = _negotiator.Negotiate(typeof(string), _request, new MediaTypeFormatterCollection());\n\n            // Assert\n            Assert.Equal(\"application/xml\", result.MediaType.MediaType);\n            Assert.IsType<XmlMediaTypeFormatter>(result.Formatter);\n        }\n\n        [Fact]\n        public void Negotiate_SelectsJsonFormatter_ForXhrRequestThatDoesNotSpecifyAcceptHeaders()\n        {\n            // Arrange\n            _request.Content = new StringContent(\"test\");\n            _request.Headers.Add(\"x-requested-with\", \"XMLHttpRequest\");\n\n            // Act\n            var result = _negotiator.Negotiate(typeof(string), _request, new MediaTypeFormatterCollection());\n\n            // Assert\n            Assert.Equal(\"application/json\", result.MediaType.MediaType);\n            Assert.IsType<JsonMediaTypeFormatter>(result.Formatter);\n        }\n\n        [Fact]\n        public void Negotiate_RespectsFormatterOrdering_ForXhrRequestThatDoesNotSpecifyAcceptHeaders()\n        {\n            // Arrange\n            _request.Content = new StringContent(\"test\");\n            _request.Headers.Add(\"x-requested-with\", \"XMLHttpRequest\");\n\n            MediaTypeFormatterCollection formatters = new MediaTypeFormatterCollection(new MediaTypeFormatter[]\n            {\n                new XmlMediaTypeFormatter(),\n                new JsonMediaTypeFormatter(),\n                new FormUrlEncodedMediaTypeFormatter()\n            });\n\n            // Act\n            var result = _negotiator.Negotiate(typeof(string), _request, formatters);\n\n            // Assert\n            Assert.Equal(\"application/json\", result.MediaType.MediaType);\n            Assert.IsType<JsonMediaTypeFormatter>(result.Formatter);\n        }\n\n        [Fact]\n        public void Negotiate_SelectsJsonFormatter_ForXHRAndJsonValueResponse()\n        {\n            // Arrange\n            _request.Content = new StringContent(\"test\");\n            _request.Headers.Add(\"x-requested-with\", \"XMLHttpRequest\");\n\n            // Act\n            var result = _negotiator.Negotiate(typeof(JToken), _request, new MediaTypeFormatterCollection());\n\n            Assert.Equal(\"application/json\", result.MediaType.MediaType);\n            Assert.IsType<JsonMediaTypeFormatter>(result.Formatter);\n        }\n\n        [Fact]\n        public void Negotiate_SelectsJsonFormatter_ForXHRAndMatchAllAcceptHeader()\n        {\n            // Accept\n            _request.Content = new StringContent(\"test\");\n            _request.Headers.Add(\"x-requested-with\", \"XMLHttpRequest\");\n            _request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(\"*/*\"));\n\n            // Act\n            var result = _negotiator.Negotiate(typeof(string), _request, new MediaTypeFormatterCollection());\n\n            // Assert\n            Assert.Equal(\"application/json\", result.MediaType.MediaType);\n            Assert.IsType<JsonMediaTypeFormatter>(result.Formatter);\n        }\n\n        [Fact]\n        public void Negotiate_UsesRequestedFormatterForXHRAndMatchAllPlusOtherAcceptHeader()\n        {\n            // Arrange\n            _request.Content = new StringContent(\"test\");\n            _request.Headers.Add(\"x-requested-with\", \"XMLHttpRequest\");\n            _request.Headers.Accept.ParseAdd(\"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\"); // XHR header sent by Firefox 3b5\n\n            // Act\n            var result = _negotiator.Negotiate(typeof(string), _request, new MediaTypeFormatterCollection());\n\n            // Assert\n            Assert.Equal(\"application/xml\", result.MediaType.MediaType);\n            Assert.IsType<XmlMediaTypeFormatter>(result.Formatter);\n        }\n\n        [Theory]\n        [InlineData(true)] \n        [InlineData(false)]\n        public void Negotiate_ObservesExcludeMatchOnTypeOnly(bool excludeMatchOnTypeOnly)\n        {\n            // Arrange\n            MockContentNegotiator negotiator = new MockContentNegotiator(excludeMatchOnTypeOnly);\n            _request.Content = new StringContent(\"test\");\n            _request.Headers.Accept.ParseAdd(\"text/html\");\n\n            // Act\n            var result = negotiator.Negotiate(typeof(string), _request, new MediaTypeFormatterCollection());\n\n            // Assert\n            if (excludeMatchOnTypeOnly)\n            {\n                Assert.Null(result);\n            }\n            else\n            {\n                Assert.NotNull(result);\n                Assert.Equal(\"application/json\", result.MediaType.MediaType);\n            }\n        }\n\n        [Fact]\n        public void ComputeFormatterMatches_ThrowsOnNull()\n        {\n            MockContentNegotiator negotiator = new MockContentNegotiator();\n            Type type = typeof(object);\n            HttpRequestMessage request = new HttpRequestMessage();\n            List<MediaTypeFormatter> formatters = new List<MediaTypeFormatter>();\n\n            Assert.ThrowsArgumentNull(() => negotiator.ComputeFormatterMatches(type: null, request: request, formatters: formatters), \"type\");\n            Assert.ThrowsArgumentNull(() => negotiator.ComputeFormatterMatches(type: type, request: null, formatters: formatters), \"request\");\n            Assert.ThrowsArgumentNull(() => negotiator.ComputeFormatterMatches(type: type, request: request, formatters: null), \"formatters\");\n        }\n\n        [Fact]\n        public void MatchMediaTypeMapping_ThrowsOnNull()\n        {\n            MockContentNegotiator negotiator = new MockContentNegotiator();\n            HttpRequestMessage request = new HttpRequestMessage();\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();\n\n            Assert.ThrowsArgumentNull(() => negotiator.MatchMediaTypeMapping(request: null, formatter: formatter), \"request\");\n            Assert.ThrowsArgumentNull(() => negotiator.MatchMediaTypeMapping(request: request, formatter: null), \"formatter\");\n        }\n\n        [Fact]\n        public void MatchMediaTypeMapping_ReturnsMatch()\n        {\n            // Arrange\n            MockContentNegotiator negotiator = new MockContentNegotiator();\n\n            HttpRequestMessage request = new HttpRequestMessage();\n            MediaTypeHeaderValue mappingMediatype = MediaTypeHeaderValue.Parse(\"application/other\");\n            MockMediaTypeMapping mockMediaTypeMapping = new MockMediaTypeMapping(mappingMediatype, 0.75);\n\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();\n            formatter.MediaTypeMappings.Add(mockMediaTypeMapping);\n\n            // Act\n            MediaTypeFormatterMatch match = negotiator.MatchMediaTypeMapping(request, formatter);\n\n            // Assert\n            Assert.True(mockMediaTypeMapping.WasInvoked);\n            Assert.Same(request, mockMediaTypeMapping.Request);\n\n            Assert.Same(formatter, match.Formatter);\n            Assert.Equal(mockMediaTypeMapping.MediaType, match.MediaType);\n            Assert.Equal(mockMediaTypeMapping.MatchQuality, match.Quality);\n            Assert.Equal(MediaTypeFormatterMatchRanking.MatchOnRequestWithMediaTypeMapping, match.Ranking);\n        }\n\n        [Fact]\n        public void MatchAcceptHeader_ThrowsOnNull()\n        {\n            MockContentNegotiator negotiator = new MockContentNegotiator();\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();\n            List<MediaTypeWithQualityHeaderValue> sortedAcceptValues = new List<MediaTypeWithQualityHeaderValue>();\n\n            Assert.ThrowsArgumentNull(() => negotiator.MatchAcceptHeader(sortedAcceptValues: null, formatter: formatter), \"sortedAcceptValues\");\n            Assert.ThrowsArgumentNull(() => negotiator.MatchAcceptHeader(sortedAcceptValues: sortedAcceptValues, formatter: null), \"formatter\");\n        }\n\n        [Theory]\n        [PropertyData(\"MatchAcceptHeaderData\")]\n        public void MatchAcceptHeader_ReturnsMatch(string[] acceptHeaders, string[] supportedMediaTypes, string expectedMediaType, double expectedQuality, int ranking)\n        {\n            // Arrange\n            MockContentNegotiator negotiator = new MockContentNegotiator();\n\n            List<MediaTypeWithQualityHeaderValue> unsortedAcceptHeaders = acceptHeaders.Select(a => MediaTypeWithQualityHeaderValue.Parse(a)).ToList();\n            IEnumerable<MediaTypeWithQualityHeaderValue> sortedAcceptHeaders = negotiator.SortMediaTypeWithQualityHeaderValuesByQFactor(unsortedAcceptHeaders);\n\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();\n            foreach (string supportedMediaType in supportedMediaTypes)\n            {\n                formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(supportedMediaType));\n            }\n\n            // Act\n            MediaTypeFormatterMatch match = negotiator.MatchAcceptHeader(sortedAcceptHeaders, formatter);\n\n            // Assert\n            if (expectedMediaType == null)\n            {\n                Assert.Null(match);\n            }\n            else\n            {\n                Assert.Same(formatter, match.Formatter);\n                Assert.Equal(MediaTypeHeaderValue.Parse(expectedMediaType), match.MediaType);\n                Assert.Equal(expectedQuality, match.Quality);\n                Assert.Equal(ranking, (int)match.Ranking);\n            }\n        }\n\n        [Fact]\n        public void MatchRequestMediaType_ThrowsOnNull()\n        {\n            MockContentNegotiator negotiator = new MockContentNegotiator();\n            HttpRequestMessage request = new HttpRequestMessage();\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();\n\n            Assert.ThrowsArgumentNull(() => negotiator.MatchRequestMediaType(request: null, formatter: formatter), \"request\");\n            Assert.ThrowsArgumentNull(() => negotiator.MatchRequestMediaType(request: request, formatter: null), \"formatter\");\n        }\n\n        [Theory]\n        [PropertyData(\"MatchRequestMediaTypeData\")]\n        public void MatchRequestMediaType_ReturnsMatch(string requestMediaType, string[] supportedMediaTypes, string expectedMediaType)\n        {\n            // Arrange\n            MockContentNegotiator negotiator = new MockContentNegotiator();\n\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.Content = new StringContent(String.Empty);\n            request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(requestMediaType);\n\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();\n            foreach (string supportedMediaType in supportedMediaTypes)\n            {\n                formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(supportedMediaType));\n            }\n\n            // Act\n            MediaTypeFormatterMatch match = negotiator.MatchRequestMediaType(request, formatter);\n\n            // Assert\n            if (expectedMediaType == null)\n            {\n                Assert.Null(match);\n            }\n            else\n            {\n                Assert.Same(formatter, match.Formatter);\n                Assert.Equal(MediaTypeHeaderValue.Parse(expectedMediaType), match.MediaType);\n                Assert.Equal(1.0, match.Quality);\n                Assert.Equal(MediaTypeFormatterMatchRanking.MatchOnRequestMediaType, match.Ranking);\n            }\n        }\n\n        [Fact]\n        public void ShouldMatchOnType_ThrowsOnNull()\n        {\n            MockContentNegotiator negotiator = new MockContentNegotiator();\n            Assert.ThrowsArgumentNull(() => negotiator.ShouldMatchOnType(sortedAcceptValues: null), \"sortedAcceptValues\");\n        }\n\n        [Theory]\n        [PropertyData(\"ShouldMatchOnTypeData\")]\n        public void ShouldMatchOnType_ReturnsExpectedResult(bool excludeMatchOnType, string[] acceptHeaders, bool expectedResult)\n        {\n            // Arrange\n            MockContentNegotiator negotiator = new MockContentNegotiator(excludeMatchOnType);\n            List<MediaTypeWithQualityHeaderValue> unsortedAcceptHeaders = acceptHeaders.Select(a => MediaTypeWithQualityHeaderValue.Parse(a)).ToList();\n            IEnumerable<MediaTypeWithQualityHeaderValue> sortedAcceptHeaders = negotiator.SortMediaTypeWithQualityHeaderValuesByQFactor(unsortedAcceptHeaders);\n\n            // Act\n            bool result = negotiator.ShouldMatchOnType(sortedAcceptHeaders);\n\n            // Assert\n            Assert.Equal(expectedResult, result);\n        }\n\n        [Fact]\n        public void MatchType_ThrowsOnNull()\n        {\n            MockContentNegotiator negotiator = new MockContentNegotiator();\n            Type type = typeof(object);\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();\n\n            Assert.ThrowsArgumentNull(() => negotiator.MatchType(type: null, formatter: formatter), \"type\");\n            Assert.ThrowsArgumentNull(() => negotiator.MatchType(type: type, formatter: null), \"formatter\");\n        }\n\n        [Theory]\n        [PropertyData(\"MatchTypeData\")]\n        public void MatchType_ReturnsMatch(string[] supportedMediaTypes, string expectedMediaType)\n        {\n            // Arrange\n            MockContentNegotiator negotiator = new MockContentNegotiator();\n\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();\n            foreach (string supportedMediaType in supportedMediaTypes)\n            {\n                formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(supportedMediaType));\n            }\n\n            // Act\n            MediaTypeFormatterMatch match = negotiator.MatchType(typeof(object), formatter);\n\n            // Assert\n            Assert.Same(formatter, match.Formatter);\n            Assert.Equal(MediaTypeHeaderValue.Parse(expectedMediaType), match.MediaType);\n            Assert.Equal(1.0, match.Quality);\n            Assert.Equal(MediaTypeFormatterMatchRanking.MatchOnCanWriteType, match.Ranking);\n        }\n\n        [Fact]\n        public void SelectResponseMediaTypeFormatter_ThrowsOnNull()\n        {\n            MockContentNegotiator negotiator = new MockContentNegotiator();\n            HttpRequestMessage request = new HttpRequestMessage();\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();\n\n            Assert.ThrowsArgumentNull(() => negotiator.SelectResponseMediaTypeFormatter(matches: null), \"matches\");\n        }\n\n        [Theory]\n        [PropertyData(\"SelectResponseMediaTypeData\")]\n        public void SelectResponseMediaTypeFormatter_SelectsMediaType(ICollection<MediaTypeFormatterMatch> matches, MediaTypeFormatterMatch expectedWinner)\n        {\n            // Arrange\n            MockContentNegotiator negotiator = new MockContentNegotiator();\n\n            // Act\n            MediaTypeFormatterMatch actualWinner = negotiator.SelectResponseMediaTypeFormatter(matches);\n\n            // Assert\n            Assert.Same(expectedWinner, actualWinner);\n        }\n\n        [Fact]\n        public void SelectResponseCharacterEncoding_ThrowsOnNull()\n        {\n            MockContentNegotiator negotiator = new MockContentNegotiator();\n            HttpRequestMessage request = new HttpRequestMessage();\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();\n\n            Assert.ThrowsArgumentNull(() => negotiator.SelectResponseCharacterEncoding(request: null, formatter: formatter), \"request\");\n            Assert.ThrowsArgumentNull(() => negotiator.SelectResponseCharacterEncoding(request: request, formatter: null), \"formatter\");\n        }\n\n        [Theory]\n        [PropertyData(\"SelectResponseCharacterEncodingData\")]\n        public void SelectResponseCharacterEncoding_SelectsEncoding(string[] acceptCharsetHeaders, string requestEncoding, string[] supportedEncodings, string expectedEncoding)\n        {\n            // Arrange\n            MockContentNegotiator negotiator = new MockContentNegotiator();\n\n            HttpRequestMessage request = new HttpRequestMessage();\n            foreach (string acceptCharsetHeader in acceptCharsetHeaders)\n            {\n                request.Headers.AcceptCharset.Add(StringWithQualityHeaderValue.Parse(acceptCharsetHeader));\n            }\n\n            if (requestEncoding != null)\n            {\n                Encoding reqEncoding = Encoding.GetEncoding(requestEncoding);\n                StringContent content = new StringContent(\"\", reqEncoding, \"text/plain\");\n                request.Content = content;\n            }\n\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter() { CallBase = true };\n            foreach (string supportedEncoding in supportedEncodings)\n            {\n                formatter.SupportedEncodings.Add(Encoding.GetEncoding(supportedEncoding));\n            }\n\n            // Act\n            Encoding actualEncoding = negotiator.SelectResponseCharacterEncoding(request, formatter);\n\n            // Assert\n            if (expectedEncoding == null)\n            {\n                Assert.Null(actualEncoding);\n            }\n            else\n            {\n                Assert.Equal(Encoding.GetEncoding(expectedEncoding), actualEncoding);\n            }\n        }\n\n        [Fact]\n        public void SortMediaTypeWithQualityHeaderValuesByQFactor_ThrowsOnNull()\n        {\n            MockContentNegotiator negotiator = new MockContentNegotiator();\n            Assert.ThrowsArgumentNull(() => negotiator.SortMediaTypeWithQualityHeaderValuesByQFactor((HttpHeaderValueCollection<MediaTypeWithQualityHeaderValue>)null), \"headerValues\");\n        }\n\n        [Theory]\n        [TestDataSet(typeof(MediaTypeWithQualityHeaderValueComparerTests), \"BeforeAfterSortedValues\")]\n        public void SortMediaTypeWithQualityHeaderValuesByQFactor_SortsCorrectly(IEnumerable<string> unsorted, IEnumerable<string> expectedSorted)\n        {\n            // Arrange\n            MockContentNegotiator negotiator = new MockContentNegotiator();\n\n            List<MediaTypeWithQualityHeaderValue> unsortedValues =\n                new List<MediaTypeWithQualityHeaderValue>(unsorted.Select(u => MediaTypeWithQualityHeaderValue.Parse(u)));\n\n            List<MediaTypeWithQualityHeaderValue> expectedSortedValues =\n                new List<MediaTypeWithQualityHeaderValue>(expectedSorted.Select(u => MediaTypeWithQualityHeaderValue.Parse(u)));\n\n            // Act\n            IEnumerable<MediaTypeWithQualityHeaderValue> actualSorted = negotiator.SortMediaTypeWithQualityHeaderValuesByQFactor(unsortedValues);\n\n            // Assert\n            Assert.True(expectedSortedValues.SequenceEqual(actualSorted));\n        }\n\n        [Fact]\n        public void SortStringWithQualityHeaderValuesByQFactor_ThrowsOnNull()\n        {\n            MockContentNegotiator negotiator = new MockContentNegotiator();\n            Assert.ThrowsArgumentNull(() => negotiator.SortStringWithQualityHeaderValuesByQFactor((HttpHeaderValueCollection<StringWithQualityHeaderValue>)null), \"headerValues\");\n        }\n\n        [Theory]\n        [TestDataSet(typeof(StringWithQualityHeaderValueComparerTests), \"BeforeAfterSortedValues\")]\n        public void SortStringWithQualityHeaderValuesByQFactor_SortsCorrectly(IEnumerable<string> unsorted, IEnumerable<string> expectedSorted)\n        {\n            // Arrange\n            MockContentNegotiator negotiator = new MockContentNegotiator();\n\n            List<StringWithQualityHeaderValue> unsortedValues =\n                new List<StringWithQualityHeaderValue>(unsorted.Select(u => StringWithQualityHeaderValue.Parse(u)));\n\n            List<StringWithQualityHeaderValue> expectedSortedValues =\n                new List<StringWithQualityHeaderValue>(expectedSorted.Select(u => StringWithQualityHeaderValue.Parse(u)));\n\n            // Act\n            IEnumerable<StringWithQualityHeaderValue> actualSorted = negotiator.SortStringWithQualityHeaderValuesByQFactor(unsortedValues);\n\n            // Assert\n            Assert.True(expectedSortedValues.SequenceEqual(actualSorted));\n        }\n\n        [Theory]\n        [PropertyData(\"UpdateBestMatchData\")]\n        public void UpdateBestMatch_SelectsCorrectly(MediaTypeFormatterMatch current, MediaTypeFormatterMatch replacement, bool currentWins)\n        {\n            // Arrange\n            MockContentNegotiator negotiator = new MockContentNegotiator();\n\n            // Act\n            MediaTypeFormatterMatch actualResult = negotiator.UpdateBestMatch(current, replacement);\n\n            // Assert\n            if (currentWins)\n            {\n                Assert.Same(current, actualResult);\n            }\n            else\n            {\n                Assert.Same(replacement, actualResult);\n            }\n        }\n\n        private class PlainTextFormatter : MediaTypeFormatter\n        {\n            public override bool CanReadType(Type type)\n            {\n                return true;\n            }\n\n            public override bool CanWriteType(Type type)\n            {\n                return true;\n            }\n        }\n\n        private class MyMediaTypeMapping : MediaTypeMapping\n        {\n            public MyMediaTypeMapping(MediaTypeHeaderValue mediaType)\n                : base(mediaType)\n            {\n            }\n\n            public override double TryMatchMediaType(HttpRequestMessage request)\n            {\n                if (request.Headers.Contains(\"Cookie\"))\n                {\n                    return 1.0;\n                }\n                else\n                {\n                    return 0;\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/FormDataCollectionTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Formatting\n{\n    public class FormDataCollectionTests\n    {\n        [Fact]\n        public void CreateFromUri()\n        {\n            FormDataCollection form = new FormDataCollection(new Uri(\"http://foo.com/?x=1&y=2\"));\n\n            Assert.Equal(\"1\", form.Get(\"x\"));\n            Assert.Equal(\"2\", form.Get(\"y\"));\n        }\n\n        [Fact]\n        public void IndexerIsEquivalentToGet()\n        {\n            FormDataCollection form = new FormDataCollection(new Uri(\"http://foo.com/?x=1&y=2\"));\n\n            Assert.Equal(\"1\", form.Get(\"x\"));\n            Assert.Equal(form[\"x\"], form.Get(\"x\"));\n            Assert.Equal(form[null], form.Get(null));\n        }\n\n        [Fact]\n        public void CreateFromEmptyUri()\n        {\n            FormDataCollection form = new FormDataCollection(new Uri(\"http://foo.com\"));\n\n            Assert.Empty(form);\n        }\n\n        [Fact]\n        public void UriConstructorThrowsNull()\n        {\n            Assert.ThrowsArgumentNull(() => new FormDataCollection((Uri)null), \"uri\");\n        }\n\n        [Fact]\n        public void CreateFromEmptyString()\n        {\n            FormDataCollection form = new FormDataCollection(\"\");\n\n            Assert.Empty(form);\n        }\n\n        [Fact]\n        public void CreateFromNullString()\n        {\n            FormDataCollection form = new FormDataCollection((string)null);\n\n            Assert.Empty(form);\n        }\n\n        [Fact]\n        public void PairConstructorThrowsNull()\n        {\n            var arg = (IEnumerable<KeyValuePair<string, string>>)null;\n            Assert.ThrowsArgumentNull(() => new FormDataCollection(arg), \"pairs\");\n        }\n\n        [Fact]\n        public void CreateFromPairs()\n        {\n            Dictionary<string, string> pairs = new Dictionary<string, string>\n            {\n                { \"x\",  \"1\"},\n                { \"y\" , \"2\"}\n            };\n\n            var form = new FormDataCollection(pairs);\n\n            Assert.Equal(\"1\", form.Get(\"x\"));\n            Assert.Equal(\"2\", form.Get(\"y\"));\n        }\n\n        [Fact]\n        public void Enumeration()\n        {\n            FormDataCollection form = new FormDataCollection(new Uri(\"http://foo.com/?x=1&y=2\"));\n\n            // Enumeration should be ordered\n            String s = \"\";\n            foreach (KeyValuePair<string, string> kv in form)\n            {\n                s += string.Format(\"{0}={1};\", kv.Key, kv.Value);\n            }\n\n            Assert.Equal(\"x=1;y=2;\", s);\n        }\n\n        [Fact]\n        public void GetValues()\n        {\n            FormDataCollection form = new FormDataCollection(new Uri(\"http://foo.com/?x=1&x=2&x=3\"));\n\n            Assert.Equal(new string[] { \"1\", \"2\", \"3\" }, form.GetValues(\"x\"));\n        }\n\n        [Fact]\n        public void CaseInSensitive()\n        {\n            FormDataCollection form = new FormDataCollection(new Uri(\"http://foo.com/?x=1&Y=2\"));\n\n            var nvc = form.ReadAsNameValueCollection();\n\n            Assert.Equal(2, nvc.Count);\n            Assert.Equal(\"1\", nvc.Get(\"x\"));\n            Assert.Equal(\"2\", nvc.Get(\"y\"));\n        }\n\n        [Fact]\n        public void ToNameValueCollection()\n        {\n            FormDataCollection form = new FormDataCollection(new Uri(\"http://foo.com/?x=1a&y=2&x=1b&=ValueOnly&KeyOnly\"));\n\n            var nvc = form.ReadAsNameValueCollection();\n\n            // y=2\n            // x=1a;x=1b\n            // =ValueOnly\n            // KeyOnly\n            Assert.Equal(4, nvc.Count);\n            Assert.Equal(new string[] { \"1a\", \"1b\" }, nvc.GetValues(\"x\"));\n            Assert.Equal(\"1a,1b\", nvc.Get(\"x\"));\n            Assert.Equal(\"2\", nvc.Get(\"y\"));\n            Assert.Equal(\"\", nvc.Get(\"KeyOnly\"));\n            Assert.Equal(\"ValueOnly\", nvc.Get(\"\"));\n        }\n\n        const string SPACE = \" \"; // single literal space character\n\n        [Theory]\n        [InlineData(\"x=?\", \"?\")] // normal\n        [InlineData(\"x=%3f\", \"?\")] // normal\n        [InlineData(\"x=%3d\", \"=\")] // normal\n        [InlineData(\"x=abc\", \"abc\")] // normal\n        [InlineData(\"x\", \"\")] // key only\n        [InlineData(\"x=\", \"\")] // rhs only\n        [InlineData(\"x=%20\", SPACE)] // escaped space\n        [InlineData(\"x=\" + SPACE, SPACE)] // literal space\n        [InlineData(\"x=+\", SPACE)]\n        [InlineData(\"x=null\", \"null\")] // null literal, not escaped\n        [InlineData(\"x=undefined\", \"undefined\")] // undefined literal, not escaped\n        [InlineData(\"x=\\\"null\\\"\", \"\\\"null\\\"\")] // quoted null, preserved as is\n        public void Whitespace(string queryString, string expected)\n        {\n            FormDataCollection fd = new FormDataCollection(queryString);\n\n            Assert.Single(fd);\n            Assert.Equal(expected, fd.Get(\"x\"));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/FormUrlEncodedFromContentTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http.Formatting.Parsers;\nusing System.Text;\nusing System.Web.Http;\nusing Microsoft.TestCommon;\nusing Newtonsoft.Json.Linq;\n\nnamespace System.Net.Http.Formatting\n{\n    public class FormUrlEncodedJsonFromContentTests\n    {\n        public static TheoryDataSet<string, string> TestEncodedNameTestData\n        {\n            get\n            {\n                // string: encoded string: result\n                return new TheoryDataSet<string, string>\n                {\n                    { \"some+thing=10\", @\"{\"\"some thing\"\":\"\"10\"\"}\" },\n                    { \"%E5%B8%A6%E4%B8%89%E4%B8%AA%E8%A1%A8=bar\", @\"{\"\"带三个表\"\":\"\"bar\"\"}\" },\n                    { \"some+thing=10&%E5%B8%A6%E4%B8%89%E4%B8%AA%E8%A1%A8=bar\", @\"{\"\"some thing\"\":\"\"10\"\",\"\"带三个表\"\":\"\"bar\"\"}\"},\n                    { \"a[0\\r\\n][b]=1\", \"{\\\"a\\\":{\\\"0\\\\r\\\\n\\\":{\\\"b\\\":\\\"1\\\"}}}\" },\n                    { \"a[0%0d\\n][b]=1\", \"{\\\"a\\\":{\\\"0\\\\r\\\\n\\\":{\\\"b\\\":\\\"1\\\"}}}\" },\n                    { \"a[0%0d%0a][b]=1\", \"{\\\"a\\\":{\\\"0\\\\r\\\\n\\\":{\\\"b\\\":\\\"1\\\"}}}\" },\n                    { \"a[0\\0]=1\", \"{\\\"a\\\":{\\\"0\\\\u0000\\\":\\\"1\\\"}}\" },\n                    { \"a[0%00]=1\", \"{\\\"a\\\":{\\\"0\\\\u0000\\\":\\\"1\\\"}}\" },\n                    { \"a[\\00]=1\", \"{\\\"a\\\":{\\\"\\\\u00000\\\":\\\"1\\\"}}\" },\n                    { \"a[%000]=1\", \"{\\\"a\\\":{\\\"\\\\u00000\\\":\\\"1\\\"}}\" },\n                };\n            }\n        }\n\n        public static TheoryDataSet<string, string> TestObjectTestData\n        {\n            get\n            {\n                // string: encoded string: result\n                return new TheoryDataSet<string, string>\n                {\n                    { \"a[]=4&a[]=5&b[x][]=7&b[y]=8&b[z][]=9&b[z][]=true&b[z][]=undefined&b[z][]=&c=1&f=\",\n                     @\"{\"\"a\"\":[\"\"4\"\",\"\"5\"\"],\"\"b\"\":{\"\"x\"\":[\"\"7\"\"],\"\"y\"\":\"\"8\"\",\"\"z\"\":[\"\"9\"\",\"\"true\"\",\"\"undefined\"\",\"\"\"\"]},\"\"c\"\":\"\"1\"\",\"\"f\"\":\"\"\"\"}\" },\n\n                    { \"customer[Name]=Pete&customer[Address]=Redmond&customer[Age][0][]=23&customer[Age][0][]=24&customer[Age][1][]=25&\" +\n                      \"customer[Age][1][]=26&customer[Phones][]=425+888+1111&customer[Phones][]=425+345+7777&customer[Phones][]=425+888+4564&\" +\n                      \"customer[EnrolmentDate]=%22%5C%2FDate(1276562539537)%5C%2F%22&role=NewRole&changeDate=3&count=15\",\n                      @\"{\"\"customer\"\":{\"\"Name\"\":\"\"Pete\"\",\"\"Address\"\":\"\"Redmond\"\",\"\"Age\"\":[[\"\"23\"\",\"\"24\"\"],[\"\"25\"\",\"\"26\"\"]],\" +\n                      @\"\"\"Phones\"\":[\"\"425 888 1111\"\",\"\"425 345 7777\"\",\"\"425 888 4564\"\"],\"\"EnrolmentDate\"\":\"\"\\\"\"\\\\/Date(1276562539537)\\\\/\\\"\"\"\"},\"\"role\"\":\"\"NewRole\"\",\"\"changeDate\"\":\"\"3\"\",\"\"count\"\":\"\"15\"\"}\" },\n\n                    { \"customers[0][Name]=Pete2&customers[0][Address]=Redmond2&customers[0][Age][0][]=23&customers[0][Age][0][]=24&\" +\n                      \"customers[0][Age][1][]=25&customers[0][Age][1][]=26&customers[0][Phones][]=425+888+1111&customers[0][Phones][]=425+345+7777&\" +\n                      \"customers[0][Phones][]=425+888+4564&customers[0][EnrolmentDate]=%22%5C%2FDate(1276634840700)%5C%2F%22&customers[1][Name]=Pete3&\" +\n                      \"customers[1][Address]=Redmond3&customers[1][Age][0][]=23&customers[1][Age][0][]=24&customers[1][Age][1][]=25&customers[1][Age][1][]=26&\" +\n                      \"customers[1][Phones][]=425+888+1111&customers[1][Phones][]=425+345+7777&customers[1][Phones][]=425+888+4564&customers[1][EnrolmentDate]=%22%5C%2FDate(1276634840700)%5C%2F%22\",\n                      @\"{\"\"customers\"\":[{\"\"Name\"\":\"\"Pete2\"\",\"\"Address\"\":\"\"Redmond2\"\",\"\"Age\"\":[[\"\"23\"\",\"\"24\"\"],[\"\"25\"\",\"\"26\"\"]],\" +\n                      @\"\"\"Phones\"\":[\"\"425 888 1111\"\",\"\"425 345 7777\"\",\"\"425 888 4564\"\"],\"\"EnrolmentDate\"\":\"\"\\\"\"\\\\/Date(1276634840700)\\\\/\\\"\"\"\"},\" +\n                      @\"{\"\"Name\"\":\"\"Pete3\"\",\"\"Address\"\":\"\"Redmond3\"\",\"\"Age\"\":[[\"\"23\"\",\"\"24\"\"],[\"\"25\"\",\"\"26\"\"]],\"\"Phones\"\":[\"\"425 888 1111\"\",\"\"425 345 7777\"\",\"\"425 888 4564\"\"],\"\"EnrolmentDate\"\":\"\"\\\"\"\\\\/Date(1276634840700)\\\\/\\\"\"\"\"}]}\" },\n\n                    { \"ab%5B%5D=hello\", @\"{\"\"ab\"\":[\"\"hello\"\"]}\" },\n\n                    { \"123=hello\", @\"{\"\"123\"\":\"\"hello\"\"}\" },\n\n                    { \"a%5B%5D=1&a\", @\"{\"\"a\"\":[\"\"1\"\",\"\"\"\"]}\" },\n\n                    { \"a=1&a\", @\"{\"\"a\"\":[\"\"1\"\",\"\"\"\"]}\" }\n                };\n            }\n        }\n\n        [Theory,\n            InlineData(\"abc\", \"{\\\"abc\\\":\\\"\\\"}\"),\n            InlineData(\"%2eabc%2e\", \"{\\\".abc.\\\":\\\"\\\"}\"),\n            InlineData(\"\", \"{}\"),\n            InlineData(\"a=1\", \"{\\\"a\\\":\\\"1\\\"}\")]\n        public void SimpleStringsTest(string encoded, string expectedResult)\n        {\n            ValidateFormUrlEncoded(encoded, expectedResult);\n\n        }\n\n        [Theory,\n            InlineData(\"a=2\", \"{\\\"a\\\":\\\"2\\\"}\"),\n            InlineData(\"b=true\", \"{\\\"b\\\":\\\"true\\\"}\"),\n            InlineData(\"c=hello\", \"{\\\"c\\\":\\\"hello\\\"}\"),\n            InlineData(\"d=\", \"{\\\"d\\\":\\\"\\\"}\"),\n            InlineData(\"e=null\", \"{\\\"e\\\":\\\"null\\\"}\")]\n        public void SimpleObjectsTest(string encoded, string expectedResult)\n        {\n            ValidateFormUrlEncoded(encoded, expectedResult);\n\n        }\n\n        [Fact]\n        public void LegacyArraysTest()\n        {\n            ValidateFormUrlEncoded(\"a=1&a=hello&a=333\", \"{\\\"a\\\":[\\\"1\\\",\\\"hello\\\",\\\"333\\\"]}\");\n\n            // Only valid in shallow serialization\n            ParseInvalidFormUrlEncoded(\"a[z]=2&a[z]=3\");\n        }\n\n        [Theory,\n            InlineData(\"a[]=1&a[]=hello&a[]=333\", \"{\\\"a\\\":[\\\"1\\\",\\\"hello\\\",\\\"333\\\"]}\"),\n            InlineData(\"a[b][]=1&a[b][]=hello&a[b][]=333\", \"{\\\"a\\\":{\\\"b\\\":[\\\"1\\\",\\\"hello\\\",\\\"333\\\"]}}\"),\n            InlineData(\"a[]=\", \"{\\\"a\\\":[\\\"\\\"]}\"),\n            InlineData(\"a%5B%5D=2\", @\"{\"\"a\"\":[\"\"2\"\"]}\"),\n            InlineData(\"a[x][0]=1&a[x][]=2\", @\"{\"\"a\"\":{\"\"x\"\":[\"\"1\"\",\"\"2\"\"]}}\")]\n        public void ArraysTest(string encoded, string expectedResult)\n        {\n            ValidateFormUrlEncoded(encoded, expectedResult);\n        }\n\n        [Theory,\n            InlineData(\"a[0][]=1&a[0][]=hello&a[1][]=333\", \"{\\\"a\\\":[[\\\"1\\\",\\\"hello\\\"],[\\\"333\\\"]]}\"),\n            InlineData(\"a[b][0][]=1&a[b][1][]=hello&a[b][1][]=333\", \"{\\\"a\\\":{\\\"b\\\":[[\\\"1\\\"],[\\\"hello\\\",\\\"333\\\"]]}}\"),\n            InlineData(\"a[0][0][0][]=1\", \"{\\\"a\\\":[[[[\\\"1\\\"]]]]}\")]\n        public void MultidimensionalArraysTest(string encoded, string expectedResult)\n        {\n            ValidateFormUrlEncoded(encoded, expectedResult);\n        }\n\n        [Theory,\n            InlineData(\"a[0][]=hello&a[2][]=333\", \"{\\\"a\\\":{\\\"0\\\":[\\\"hello\\\"],\\\"2\\\":[\\\"333\\\"]}}\"),\n            InlineData(\"a[0]=hello\", \"{\\\"a\\\":[\\\"hello\\\"]}\"),\n            InlineData(\"a[1][]=hello\", \"{\\\"a\\\":{\\\"1\\\":[\\\"hello\\\"]}}\"),\n            InlineData(\"a[1][0]=hello\", \"{\\\"a\\\":{\\\"1\\\":[\\\"hello\\\"]}}\")]\n        public void SparseArraysTest(string encoded, string expectedResult)\n        {\n            ValidateFormUrlEncoded(encoded, expectedResult);\n        }\n\n        [Theory,\n            InlineData(\"b[]=2&b[1][c]=d\", \"{\\\"b\\\":[\\\"2\\\",{\\\"c\\\":\\\"d\\\"}]}\")]\n        public void ArraysWithMixedMembers(string encoded, string expectedResult)\n        {\n            ValidateFormUrlEncoded(encoded, expectedResult);\n        }\n\n        [Theory,\n            InlineData(\"=3\", \"{\\\"\\\":\\\"3\\\"}\"),\n            InlineData(\"a=1&=3\", \"{\\\"a\\\":\\\"1\\\",\\\"\\\":\\\"3\\\"}\"),\n            InlineData(\"=3&b=2\", \"{\\\"\\\":\\\"3\\\",\\\"b\\\":\\\"2\\\"}\")]\n        public void EmptyKeyTest(string encoded, string expectedResult)\n        {\n            ValidateFormUrlEncoded(encoded, expectedResult);\n        }\n\n        [Theory,\n            InlineData(\"a[b]=1&a=2\"),\n            InlineData(\"a[b]=1&a[b][]=2\"),\n            InlineData(\"a[x][]=1&a[x][0]=2\"),\n            InlineData(\"a=2&a[b]=1\"),\n            InlineData(\"[]=1\"),\n            InlineData(\"a[][]=0\"),\n            InlineData(\"a[][x]=0\"),\n            InlineData(\"a&a[b]=1\")]\n        public void InvalidObjectGraphsTest(string encoded)\n        {\n            ParseInvalidFormUrlEncoded(encoded);\n        }\n\n        [Theory,\n            InlineData(\"a[b=2\"),\n            InlineData(\"a[[b]=2\"),\n            InlineData(\"a[b]]=2\")]\n        public void InvalidFormUrlEncodingTest(string encoded)\n        {\n            ParseInvalidFormUrlEncoded(encoded);\n        }\n\n        /// <summary>\n        /// Tests for parsing form-urlencoded data originated from JS primitives.\n        /// </summary>\n        [Theory,\n            InlineData(\"abc\", @\"{\"\"abc\"\":\"\"\"\"}\"),\n            InlineData(\"123\", @\"{\"\"123\"\":\"\"\"\"}\"),\n            InlineData(\"true\", @\"{\"\"true\"\":\"\"\"\"}\"),\n            InlineData(\"\", \"{}\"),\n            InlineData(\"%2fabc%2f\", @\"{\"\"/abc/\"\":\"\"\"\"}\")]\n        public void TestJValue(string encoded, string expectedResult)\n        {\n            ValidateFormUrlEncoded(encoded, expectedResult);\n        }\n\n        /// <summary>\n        /// Negative tests for parsing form-urlencoded data originated from JS primitives.\n        /// </summary>\n        [Theory,\n            InlineData(\"a[b]=1&a=2\"),\n            InlineData(\"a=2&a[b]=1\"),\n            InlineData(\"[]=1\")]\n        public void TestJValueNegative(string encoded)\n        {\n            ParseInvalidFormUrlEncoded(encoded);\n        }\n\n        /// <summary>\n        /// Tests for parsing form-urlencoded data originated from JS objects.\n        /// </summary>\n        [Theory,\n            InlineData(\"a=NaN\", @\"{\"\"a\"\":\"\"NaN\"\"}\"),\n            InlineData(\"a=false\", @\"{\"\"a\"\":\"\"false\"\"}\"),\n            InlineData(\"a=foo\", @\"{\"\"a\"\":\"\"foo\"\"}\"),\n            InlineData(\"1=1\", \"{\\\"1\\\":\\\"1\\\"}\")]\n        public void TestObjects(string encoded, string expectedResult)\n        {\n            ValidateFormUrlEncoded(encoded, expectedResult);\n        }\n\n        /// <summary>\n        /// Tests for parsing form-urlencoded data originated from JS arrays.\n        /// </summary>\n        [Theory,\n            InlineData(\"a[]=2\", @\"{\"\"a\"\":[\"\"2\"\"]}\"),\n            InlineData(\"a[]=\", @\"{\"\"a\"\":[\"\"\"\"]}\"),\n            InlineData(\"a[0][0][]=1\", @\"{\"\"a\"\":[[[\"\"1\"\"]]]}\"),\n            InlineData(\"z[]=9&z[]=true&z[]=undefined&z[]=\", @\"{\"\"z\"\":[\"\"9\"\",\"\"true\"\",\"\"undefined\"\",\"\"\"\"]}\"),\n            InlineData(\"z[]=9&z[]=true&z[]=undefined&z[]=null\", @\"{\"\"z\"\":[\"\"9\"\",\"\"true\"\",\"\"undefined\"\",\"\"null\"\"]}\"),\n            InlineData(\"z[0][]=9&z[0][]=true&z[1][]=undefined&z[1][]=null\", @\"{\"\"z\"\":[[\"\"9\"\",\"\"true\"\"],[\"\"undefined\"\",\"\"null\"\"]]}\"),\n            InlineData(\"a[0][x]=2\", @\"{\"\"a\"\":[{\"\"x\"\":\"\"2\"\"}]}\"),\n            InlineData(\"a%5B%5D=2\", @\"{\"\"a\"\":[\"\"2\"\"]}\"),\n            InlineData(\"a%5B%5D=\", @\"{\"\"a\"\":[\"\"\"\"]}\"),\n            InlineData(\"z%5B%5D=9&z%5B%5D=true&z%5B%5D=undefined&z%5B%5D=\", @\"{\"\"z\"\":[\"\"9\"\",\"\"true\"\",\"\"undefined\"\",\"\"\"\"]}\"),\n            InlineData(\"z%5B%5D=9&z%5B%5D=true&z%5B%5D=undefined&z%5B%5D=null\", @\"{\"\"z\"\":[\"\"9\"\",\"\"true\"\",\"\"undefined\"\",\"\"null\"\"]}\"),\n            InlineData(\"z%5B0%5D%5B%5D=9&z%5B0%5D%5B%5D=true&z%5B1%5D%5B%5D=undefined&z%5B1%5D%5B%5D=null\", @\"{\"\"z\"\":[[\"\"9\"\",\"\"true\"\"],[\"\"undefined\"\",\"\"null\"\"]]}\")]\n        public void TestArray(string encoded, string expectedResult)\n        {\n            ValidateFormUrlEncoded(encoded, expectedResult);\n        }\n\n        /// <summary>\n        /// Tests for parsing form-urlencoded data originated from JS arrays, using the jQuery 1.3 format (no []'s).\n        /// </summary>\n        [Theory,\n            InlineData(\"z=9&z=true&z=undefined&z=\", @\"{\"\"z\"\":[\"\"9\"\",\"\"true\"\",\"\"undefined\"\",\"\"\"\"]}\"),\n            InlineData(\"z=9&z=true&z=undefined&z=null\", @\"{\"\"z\"\":[\"\"9\"\",\"\"true\"\",\"\"undefined\"\",\"\"null\"\"]}\"),\n            InlineData(\"z=9&z=true&z=undefined&z=null&a=hello\", @\"{\"\"z\"\":[\"\"9\"\",\"\"true\"\",\"\"undefined\"\",\"\"null\"\"],\"\"a\"\":\"\"hello\"\"}\")]\n        public void TestArrayCompat(string encoded, string expectedResult)\n        {\n            ValidateFormUrlEncoded(encoded, expectedResult);\n        }\n\n        /// <summary>\n        /// Negative tests for parsing form-urlencoded data originated from JS arrays.\n        /// </summary>\n        [Theory,\n            InlineData(\"a[z]=2&a[z]=3\")]\n        public void TestArrayCompatNegative(string encoded)\n        {\n            ParseInvalidFormUrlEncoded(encoded);\n        }\n\n        /// <summary>\n        /// Tests for form-urlencoded data originated from sparse JS arrays.\n        /// </summary>\n        [Theory,\n            InlineData(\"a[2]=hello\", @\"{\"\"a\"\":{\"\"2\"\":\"\"hello\"\"}}\"),\n            InlineData(\"a[x][0]=2\", @\"{\"\"a\"\":{\"\"x\"\":[\"\"2\"\"]}}\"),\n            InlineData(\"a[x][1]=2\", @\"{\"\"a\"\":{\"\"x\"\":{\"\"1\"\":\"\"2\"\"}}}\"),\n            InlineData(\"a[x][0]=0&a[x][1]=1\", @\"{\"\"a\"\":{\"\"x\"\":[\"\"0\"\",\"\"1\"\"]}}\"),\n            InlineData(\"a[0][0][0]=hello&a[1][0][0][0][]=hello\", @\"{\"\"a\"\":[[[\"\"hello\"\"]],[[[[\"\"hello\"\"]]]]]}\"),\n            InlineData(\"a[0][0][0]=hello&a[1][0][0][0]=hello\", @\"{\"\"a\"\":[[[\"\"hello\"\"]],[[[\"\"hello\"\"]]]]}\"),\n            InlineData(\"a[1][0][]=1\", @\"{\"\"a\"\":{\"\"1\"\":[[\"\"1\"\"]]}}\"),\n            InlineData(\"a[1][1][]=1\", @\"{\"\"a\"\":{\"\"1\"\":{\"\"1\"\":[\"\"1\"\"]}}}\"),\n            InlineData(\"a[1][1][0]=1\", @\"{\"\"a\"\":{\"\"1\"\":{\"\"1\"\":[\"\"1\"\"]}}}\"),\n            InlineData(\"a[0][]=2&a[0][]=3&a[2][]=1\", \"{\\\"a\\\":{\\\"0\\\":[\\\"2\\\",\\\"3\\\"],\\\"2\\\":[\\\"1\\\"]}}\"),\n            InlineData(\"a[x][]=1&a[x][1]=2\", @\"{\"\"a\"\":{\"\"x\"\":[\"\"1\"\",\"\"2\"\"]}}\"),\n            InlineData(\"a[x][0]=1&a[x][]=2\", @\"{\"\"a\"\":{\"\"x\"\":[\"\"1\"\",\"\"2\"\"]}}\")]\n        public void TestArraySparse(string encoded, string expectedResult)\n        {\n            ValidateFormUrlEncoded(encoded, expectedResult);\n        }\n\n        /// <summary>\n        /// Negative tests for parsing form-urlencoded arrays.\n        /// </summary>\n        [Theory,\n            InlineData(\"a[x]=2&a[x][]=3\"),\n            InlineData(\"a[]=1&a[0][]=2\"),\n            InlineData(\"a[]=1&a[0][0][]=2\"),\n            InlineData(\"a[x][]=1&a[x][0]=2\"),\n            InlineData(\"a[][]=0\"),\n            InlineData(\"a[][x]=0\")]\n        public void TestArrayIndexNegative(string encoded)\n        {\n            ParseInvalidFormUrlEncoded(encoded);\n        }\n\n        /// <summary>\n        /// Tests for parsing complex object graphs form-urlencoded.\n        /// </summary>\n        [Theory]\n        [PropertyData(\"TestObjectTestData\")]\n        public void TestObject(string encoded, string expectedResult)\n        {\n            ValidateFormUrlEncoded(encoded, expectedResult);\n        }\n\n        /// <summary>\n        /// Tests for parsing form-urlencoded data with encoded names.\n        /// </summary>\n        [Theory]\n        [PropertyData(\"TestEncodedNameTestData\")]\n        public void TestEncodedName(string encoded, string expectedResult)\n        {\n            ValidateFormUrlEncoded(encoded, expectedResult);\n        }\n\n        /// <summary>\n        /// Tests for malformed form-urlencoded data.\n        /// </summary>\n        [Theory,\n            InlineData(\"a[b=2\"),\n            InlineData(\"a[[b]=2\"),\n            InlineData(\"a[b]]=2\")]\n        public void TestNegative(string encoded)\n        {\n            ParseInvalidFormUrlEncoded(encoded);\n        }\n\n        private static void BuildParams(string prefix, JToken jsonValue, List<string> results)\n        {\n            if (jsonValue is JValue)\n            {\n                JValue jsonPrimitive = jsonValue as JValue;\n                if (jsonPrimitive != null)\n                {\n                    if (jsonPrimitive.Type == JTokenType.String && String.IsNullOrEmpty(jsonPrimitive.Value.ToString()))\n                    {\n                        results.Add(prefix + \"=\" + String.Empty);\n                    }\n                    else\n                    {\n                        if (jsonPrimitive.Value is DateTime || jsonPrimitive.Value is DateTimeOffset)\n                        {\n                            string dateStr = jsonPrimitive.ToString();\n                            if (!String.IsNullOrEmpty(dateStr) && dateStr.StartsWith(\"\\\"\"))\n                            {\n                                dateStr = dateStr.Substring(1, dateStr.Length - 2);\n                            }\n                            results.Add(prefix + \"=\" + WebUtility.UrlEncode(dateStr));\n                        }\n                        else\n                        {\n                            results.Add(prefix + \"=\" + WebUtility.UrlEncode(jsonPrimitive.Value.ToString()));\n                        }\n                    }\n                }\n                else\n                {\n                    results.Add(prefix + \"=\" + String.Empty);\n                }\n            }\n            else if (jsonValue is JArray)\n            {\n                for (int i = 0; i < ((JArray)jsonValue).Count; i++)\n                {\n                    if (jsonValue[i] is JArray || jsonValue[i] is JObject)\n                    {\n                        BuildParams(prefix + \"[\" + i + \"]\", jsonValue[i], results);\n                    }\n                    else\n                    {\n                        BuildParams(prefix + \"[]\", jsonValue[i], results);\n                    }\n                }\n            }\n            else\n            {\n                //jsonValue is JObject\n                foreach (KeyValuePair<string, JToken> item in (JObject)jsonValue)\n                {\n                    BuildParams(prefix + \"[\" + item.Key + \"]\", item.Value, results);\n                }\n            }\n        }\n\n        private static void ParseInvalidFormUrlEncoded(string encoded)\n        {\n            byte[] data = Encoding.UTF8.GetBytes(encoded);\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                ICollection<KeyValuePair<string, string>> collection;\n                FormUrlEncodedParser parser = FormUrlEncodedParserTests.CreateParser(data.Length + 1, out collection);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed;\n                ParserState state = FormUrlEncodedParserTests.ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Done, state);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                Assert.ThrowsArgument(() => { FormUrlEncodedJson.Parse(collection); }, null);\n            }\n        }\n\n        private static void ValidateFormUrlEncoded(string encoded, string expectedResult)\n        {\n            byte[] data = Encoding.UTF8.GetBytes(encoded);\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                ICollection<KeyValuePair<string, string>> collection;\n                FormUrlEncodedParser parser = FormUrlEncodedParserTests.CreateParser(data.Length + 1, out collection);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed;\n                ParserState state = FormUrlEncodedParserTests.ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Done, state);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                JObject result = FormUrlEncodedJson.Parse(collection);\n                Assert.NotNull(result);\n                Assert.Equal(expectedResult, result.ToString(Newtonsoft.Json.Formatting.None));\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/FormUrlEncodedFromUriQueryTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http;\nusing Microsoft.TestCommon;\nusing Newtonsoft.Json.Linq;\n\nnamespace System.Net.Http.Formatting\n{\n    public class FormUrlEncodedJsonFromUriQueryTests\n    {\n        [Theory,\n            InlineData(\"abc\", \"{\\\"abc\\\":\\\"\\\"}\"),\n            InlineData(\"%2eabc%2e\", \"{\\\".abc.\\\":\\\"\\\"}\"),\n            InlineData(\"\", \"{}\"),\n            InlineData(\"a=1\", \"{\\\"a\\\":\\\"1\\\"}\")]\n        public void SimpleStringsTest(string encoded, string expectedResult)\n        {\n            ValidateFormUrlEncoded(encoded, expectedResult);\n        }\n\n        [Theory,\n            InlineData(\"a=2\", \"{\\\"a\\\":\\\"2\\\"}\"),\n            InlineData(\"b=true\", \"{\\\"b\\\":\\\"true\\\"}\"),\n            InlineData(\"c=hello\", \"{\\\"c\\\":\\\"hello\\\"}\"),\n            InlineData(\"d=\", \"{\\\"d\\\":\\\"\\\"}\"),\n            InlineData(\"e=null\", \"{\\\"e\\\":\\\"null\\\"}\")]\n        public void SimpleObjectsTest(string encoded, string expectedResult)\n        {\n            ValidateFormUrlEncoded(encoded, expectedResult);\n        }\n\n        [Fact]\n        public void LegacyArraysTest()\n        {\n            ValidateFormUrlEncoded(\"a=1&a=hello&a=333\", \"{\\\"a\\\":[\\\"1\\\",\\\"hello\\\",\\\"333\\\"]}\");\n\n            // Only valid in shallow serialization\n            ParseInvalidFormUrlEncoded(\"a[z]=2&a[z]=3\");\n        }\n\n        [Theory,\n            InlineData(\"a[]=1&a[]=hello&a[]=333\", \"{\\\"a\\\":[\\\"1\\\",\\\"hello\\\",\\\"333\\\"]}\"),\n            InlineData(\"a[b][]=1&a[b][]=hello&a[b][]=333\", \"{\\\"a\\\":{\\\"b\\\":[\\\"1\\\",\\\"hello\\\",\\\"333\\\"]}}\"),\n            InlineData(\"a[]=\", \"{\\\"a\\\":[\\\"\\\"]}\"),\n            InlineData(\"a%5B%5D=2\", @\"{\"\"a\"\":[\"\"2\"\"]}\"),\n            InlineData(\"a[x][0]=1&a[x][]=2\", @\"{\"\"a\"\":{\"\"x\"\":[\"\"1\"\",\"\"2\"\"]}}\")]\n        public void ArraysTest(string encoded, string expectedResult)\n        {\n            ValidateFormUrlEncoded(encoded, expectedResult);\n        }\n\n        [Theory,\n            InlineData(\"a[0][]=1&a[0][]=hello&a[1][]=333\", \"{\\\"a\\\":[[\\\"1\\\",\\\"hello\\\"],[\\\"333\\\"]]}\"),\n            InlineData(\"a[b][0][]=1&a[b][1][]=hello&a[b][1][]=333\", \"{\\\"a\\\":{\\\"b\\\":[[\\\"1\\\"],[\\\"hello\\\",\\\"333\\\"]]}}\"),\n            InlineData(\"a[0][0][0][]=1\", \"{\\\"a\\\":[[[[\\\"1\\\"]]]]}\")]\n        public void MultidimensionalArraysTest(string encoded, string expectedResult)\n        {\n            ValidateFormUrlEncoded(encoded, expectedResult);\n        }\n\n        [Theory,\n            InlineData(\"a[0][]=hello&a[2][]=333\", \"{\\\"a\\\":{\\\"0\\\":[\\\"hello\\\"],\\\"2\\\":[\\\"333\\\"]}}\"),\n            InlineData(\"a[0]=hello\", \"{\\\"a\\\":[\\\"hello\\\"]}\"),\n            InlineData(\"a[1][]=hello\", \"{\\\"a\\\":{\\\"1\\\":[\\\"hello\\\"]}}\"),\n            InlineData(\"a[1][0]=hello\", \"{\\\"a\\\":{\\\"1\\\":[\\\"hello\\\"]}}\")]\n        public void SparseArraysTest(string encoded, string expectedResult)\n        {\n            ValidateFormUrlEncoded(encoded, expectedResult);\n        }\n\n        [Theory,\n            InlineData(\"b[]=2&b[1][c]=d\", \"{\\\"b\\\":[\\\"2\\\",{\\\"c\\\":\\\"d\\\"}]}\")]\n        public void ArraysWithMixedMembers(string encoded, string expectedResult)\n        {\n            ValidateFormUrlEncoded(encoded, expectedResult);\n        }\n\n        [Theory,\n            InlineData(\"=3\", \"{\\\"\\\":\\\"3\\\"}\"),\n            InlineData(\"a=1&=3\", \"{\\\"a\\\":\\\"1\\\",\\\"\\\":\\\"3\\\"}\"),\n            InlineData(\"=3&b=2\", \"{\\\"\\\":\\\"3\\\",\\\"b\\\":\\\"2\\\"}\")]\n        public void EmptyKeyTest(string encoded, string expectedResult)\n        {\n            ValidateFormUrlEncoded(encoded, expectedResult);\n        }\n\n        [Theory,\n            InlineData(\"a[b]=1&a=2\"),\n            InlineData(\"a[b]=1&a[b][]=2\"),\n            InlineData(\"a[x][]=1&a[x][0]=2\"),\n            InlineData(\"a=2&a[b]=1\"),\n            InlineData(\"[]=1\"),\n            InlineData(\"a[][]=0\"),\n            InlineData(\"a[][x]=0\"),\n            InlineData(\"a&a[b]=1\")]\n        public void InvalidObjectGraphsTest(string encoded)\n        {\n            ParseInvalidFormUrlEncoded(encoded);\n        }\n\n        [Theory,\n            InlineData(\"a[b=2\"),\n            InlineData(\"a[[b]=2\"),\n            InlineData(\"a[b]]=2\")]\n        public void InvalidFormUrlEncodingTest(string encoded)\n        {\n            ParseInvalidFormUrlEncoded(encoded);\n        }\n\n        /// <summary>\n        /// Tests for parsing form-urlencoded data originated from JS primitives.\n        /// </summary>\n        [Theory,\n            InlineData(\"abc\", @\"{\"\"abc\"\":\"\"\"\"}\"),\n            InlineData(\"123\", @\"{\"\"123\"\":\"\"\"\"}\"),\n            InlineData(\"true\", @\"{\"\"true\"\":\"\"\"\"}\"),\n            InlineData(\"\", \"{}\"),\n            InlineData(\"%2fabc%2f\", @\"{\"\"/abc/\"\":\"\"\"\"}\")]\n        public void TestJValue(string encoded, string expectedResult)\n        {\n            ValidateFormUrlEncoded(encoded, expectedResult);\n        }\n\n        /// <summary>\n        /// Negative tests for parsing form-urlencoded data originated from JS primitives.\n        /// </summary>\n        [Theory,\n            InlineData(\"a[b]=1&a=2\"),\n            InlineData(\"a=2&a[b]=1\"),\n            InlineData(\"[]=1\")]\n        public void TestJValueNegative(string encoded)\n        {\n            ParseInvalidFormUrlEncoded(encoded);\n        }\n\n        /// <summary>\n        /// Tests for parsing form-urlencoded data originated from JS objects.\n        /// </summary>\n        [Theory,\n            InlineData(\"a=NaN\", @\"{\"\"a\"\":\"\"NaN\"\"}\"),\n            InlineData(\"a=false\", @\"{\"\"a\"\":\"\"false\"\"}\"),\n            InlineData(\"a=foo\", @\"{\"\"a\"\":\"\"foo\"\"}\"),\n            InlineData(\"1=1\", \"{\\\"1\\\":\\\"1\\\"}\")]\n        public void TestObjects(string encoded, string expectedResult)\n        {\n            ValidateFormUrlEncoded(encoded, expectedResult);\n        }\n\n        /// <summary>\n        /// Tests for parsing form-urlencoded data originated from JS arrays.\n        /// </summary>\n        [Theory,\n            InlineData(\"a[]=2\", @\"{\"\"a\"\":[\"\"2\"\"]}\"),\n            InlineData(\"a[]=\", @\"{\"\"a\"\":[\"\"\"\"]}\"),\n            InlineData(\"a[0][0][]=1\", @\"{\"\"a\"\":[[[\"\"1\"\"]]]}\"),\n            InlineData(\"z[]=9&z[]=true&z[]=undefined&z[]=\", @\"{\"\"z\"\":[\"\"9\"\",\"\"true\"\",\"\"undefined\"\",\"\"\"\"]}\"),\n            InlineData(\"z[]=9&z[]=true&z[]=undefined&z[]=null\", @\"{\"\"z\"\":[\"\"9\"\",\"\"true\"\",\"\"undefined\"\",\"\"null\"\"]}\"),\n            InlineData(\"z[0][]=9&z[0][]=true&z[1][]=undefined&z[1][]=null\", @\"{\"\"z\"\":[[\"\"9\"\",\"\"true\"\"],[\"\"undefined\"\",\"\"null\"\"]]}\"),\n            InlineData(\"a[0][x]=2\", @\"{\"\"a\"\":[{\"\"x\"\":\"\"2\"\"}]}\"),\n            InlineData(\"a%5B%5D=2\", @\"{\"\"a\"\":[\"\"2\"\"]}\"),\n            InlineData(\"a%5B%5D=\", @\"{\"\"a\"\":[\"\"\"\"]}\"),\n            InlineData(\"z%5B%5D=9&z%5B%5D=true&z%5B%5D=undefined&z%5B%5D=\", @\"{\"\"z\"\":[\"\"9\"\",\"\"true\"\",\"\"undefined\"\",\"\"\"\"]}\"),\n            InlineData(\"z%5B%5D=9&z%5B%5D=true&z%5B%5D=undefined&z%5B%5D=null\", @\"{\"\"z\"\":[\"\"9\"\",\"\"true\"\",\"\"undefined\"\",\"\"null\"\"]}\"),\n            InlineData(\"z%5B0%5D%5B%5D=9&z%5B0%5D%5B%5D=true&z%5B1%5D%5B%5D=undefined&z%5B1%5D%5B%5D=null\", @\"{\"\"z\"\":[[\"\"9\"\",\"\"true\"\"],[\"\"undefined\"\",\"\"null\"\"]]}\")]\n        public void TestArray(string encoded, string expectedResult)\n        {\n            ValidateFormUrlEncoded(encoded, expectedResult);\n        }\n\n        /// <summary>\n        /// Tests for parsing form-urlencoded data originated from JS arrays, using the jQuery 1.3 format (no []'s).\n        /// </summary>\n        [Theory,\n            InlineData(\"z=9&z=true&z=undefined&z=\", @\"{\"\"z\"\":[\"\"9\"\",\"\"true\"\",\"\"undefined\"\",\"\"\"\"]}\"),\n            InlineData(\"z=9&z=true&z=undefined&z=null\", @\"{\"\"z\"\":[\"\"9\"\",\"\"true\"\",\"\"undefined\"\",\"\"null\"\"]}\"),\n            InlineData(\"z=9&z=true&z=undefined&z=null&a=hello\", @\"{\"\"z\"\":[\"\"9\"\",\"\"true\"\",\"\"undefined\"\",\"\"null\"\"],\"\"a\"\":\"\"hello\"\"}\")]\n        public void TestArrayCompat(string encoded, string expectedResult)\n        {\n            ValidateFormUrlEncoded(encoded, expectedResult);\n        }\n\n        /// <summary>\n        /// Negative tests for parsing form-urlencoded data originated from JS arrays.\n        /// </summary>\n        [Theory,\n            InlineData(\"a[z]=2&a[z]=3\")]\n        public void TestArrayCompatNegative(string encoded)\n        {\n            ParseInvalidFormUrlEncoded(encoded);\n        }\n\n        /// <summary>\n        /// Tests for form-urlencoded data originated from sparse JS arrays.\n        /// </summary>\n        [Theory,\n            InlineData(\"a[2]=hello\", @\"{\"\"a\"\":{\"\"2\"\":\"\"hello\"\"}}\"),\n            InlineData(\"a[x][0]=2\", @\"{\"\"a\"\":{\"\"x\"\":[\"\"2\"\"]}}\"),\n            InlineData(\"a[x][1]=2\", @\"{\"\"a\"\":{\"\"x\"\":{\"\"1\"\":\"\"2\"\"}}}\"),\n            InlineData(\"a[x][0]=0&a[x][1]=1\", @\"{\"\"a\"\":{\"\"x\"\":[\"\"0\"\",\"\"1\"\"]}}\"),\n            InlineData(\"a[0][0][0]=hello&a[1][0][0][0][]=hello\", @\"{\"\"a\"\":[[[\"\"hello\"\"]],[[[[\"\"hello\"\"]]]]]}\"),\n            InlineData(\"a[0][0][0]=hello&a[1][0][0][0]=hello\", @\"{\"\"a\"\":[[[\"\"hello\"\"]],[[[\"\"hello\"\"]]]]}\"),\n            InlineData(\"a[1][0][]=1\", @\"{\"\"a\"\":{\"\"1\"\":[[\"\"1\"\"]]}}\"),\n            InlineData(\"a[1][1][]=1\", @\"{\"\"a\"\":{\"\"1\"\":{\"\"1\"\":[\"\"1\"\"]}}}\"),\n            InlineData(\"a[1][1][0]=1\", @\"{\"\"a\"\":{\"\"1\"\":{\"\"1\"\":[\"\"1\"\"]}}}\"),\n            InlineData(\"a[0][]=2&a[0][]=3&a[2][]=1\", \"{\\\"a\\\":{\\\"0\\\":[\\\"2\\\",\\\"3\\\"],\\\"2\\\":[\\\"1\\\"]}}\"),\n            InlineData(\"a[x][]=1&a[x][1]=2\", @\"{\"\"a\"\":{\"\"x\"\":[\"\"1\"\",\"\"2\"\"]}}\"),\n            InlineData(\"a[x][0]=1&a[x][]=2\", @\"{\"\"a\"\":{\"\"x\"\":[\"\"1\"\",\"\"2\"\"]}}\")]\n        public void TestArraySparse(string encoded, string expectedResult)\n        {\n            ValidateFormUrlEncoded(encoded, expectedResult);\n        }\n\n        /// <summary>\n        /// Negative tests for parsing form-urlencoded arrays.\n        /// </summary>\n        [Theory,\n            InlineData(\"a[x]=2&a[x][]=3\"),\n            InlineData(\"a[]=1&a[0][]=2\"),\n            InlineData(\"a[]=1&a[0][0][]=2\"),\n            InlineData(\"a[x][]=1&a[x][0]=2\"),\n            InlineData(\"a[][]=0\"),\n            InlineData(\"a[][x]=0\")]\n        public void TestArrayIndexNegative(string encoded)\n        {\n            ParseInvalidFormUrlEncoded(encoded);\n        }\n\n        /// <summary>\n        /// Tests for parsing complex object graphs form-urlencoded.\n        /// </summary>\n        [Theory]\n        [TestDataSet(typeof(FormUrlEncodedJsonFromContentTests), \"TestObjectTestData\")]\n        public void TestObject(string encoded, string expectedResult)\n        {\n            ValidateFormUrlEncoded(encoded, expectedResult);\n        }\n\n        /// <summary>\n        /// Tests for parsing form-urlencoded data with encoded names.\n        /// </summary>\n        [Theory]\n        [TestDataSet(typeof(FormUrlEncodedJsonFromContentTests), \"TestEncodedNameTestData\")]\n        public void TestEncodedName(string encoded, string expectedResult)\n        {\n            ValidateFormUrlEncoded(encoded, expectedResult);\n        }\n\n        /// <summary>\n        /// Tests for malformed form-urlencoded data.\n        /// </summary>\n        [Theory,\n            InlineData(\"a[b=2\"),\n            InlineData(\"a[[b]=2\"),\n            InlineData(\"a[b]]=2\")]\n        public void TestNegative(string encoded)\n        {\n            ParseInvalidFormUrlEncoded(encoded);\n        }\n\n        private static void BuildParams(string prefix, JToken jsonValue, List<string> results)\n        {\n            if (jsonValue is JValue)\n            {\n                JValue jsonPrimitive = jsonValue as JValue;\n                if (jsonPrimitive != null)\n                {\n                    if (jsonPrimitive.Type == JTokenType.String && String.IsNullOrEmpty(jsonPrimitive.Value.ToString()))\n                    {\n                        results.Add(prefix + \"=\" + String.Empty);\n                    }\n                    else\n                    {\n                        if (jsonPrimitive.Value is DateTime || jsonPrimitive.Value is DateTimeOffset)\n                        {\n                            string dateStr = jsonPrimitive.ToString();\n                            if (!String.IsNullOrEmpty(dateStr) && dateStr.StartsWith(\"\\\"\"))\n                            {\n                                dateStr = dateStr.Substring(1, dateStr.Length - 2);\n                            }\n                            results.Add(prefix + \"=\" + WebUtility.UrlEncode(dateStr));\n                        }\n                        else\n                        {\n                            results.Add(prefix + \"=\" + WebUtility.UrlEncode(jsonPrimitive.Value.ToString()));\n                        }\n                    }\n                }\n                else\n                {\n                    results.Add(prefix + \"=\" + String.Empty);\n                }\n            }\n            else if (jsonValue is JArray)\n            {\n                for (int i = 0; i < ((JArray)jsonValue).Count; i++)\n                {\n                    if (jsonValue[i] is JArray || jsonValue[i] is JObject)\n                    {\n                        BuildParams(prefix + \"[\" + i + \"]\", jsonValue[i], results);\n                    }\n                    else\n                    {\n                        BuildParams(prefix + \"[]\", jsonValue[i], results);\n                    }\n                }\n            }\n            else\n            {\n                //jsonValue is JObject\n                foreach (KeyValuePair<string, JToken> item in (JObject)jsonValue)\n                {\n                    BuildParams(prefix + \"[\" + item.Key + \"]\", item.Value, results);\n                }\n            }\n        }\n\n        private static Uri GetQueryUri(string query)\n        {\n            UriBuilder uriBuilder = new UriBuilder(\"http://some.host\");\n            uriBuilder.Query = query;\n            return uriBuilder.Uri;\n        }\n\n        private static void ParseInvalidFormUrlEncoded(string encoded)\n        {\n            Uri address = GetQueryUri(encoded);\n            JObject result;\n            Assert.False(address.TryReadQueryAsJson(out result), \"Expected parsing to return false\");\n            Assert.Null(result);\n        }\n\n        private static void ValidateFormUrlEncoded(string encoded, string expectedResult)\n        {\n            Uri address = GetQueryUri(encoded);\n            JObject result;\n            Assert.True(address.TryReadQueryAsJson(out result), \"Expected parsing to return true\");\n            Assert.NotNull(result);\n            Assert.Equal(expectedResult, result.ToString(Newtonsoft.Json.Formatting.None));\n        }\n    }\n}"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/FormUrlEncodedJsonTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing Microsoft.TestCommon;\nusing Newtonsoft.Json.Linq;\n\nnamespace System.Net.Http.Formatting\n{\n    public class FormUrlEncodedJsonTests\n    {\n        [Fact]\n        public void TypeIsCorrect()\n        {\n            Assert.Type.HasProperties(typeof(FormUrlEncodedJson), TypeAssert.TypeProperties.IsClass | TypeAssert.TypeProperties.IsStatic);\n        }\n\n        [Fact]\n        public void ParseThrowsOnNull()\n        {\n            Assert.ThrowsArgumentNull(() => FormUrlEncodedJson.Parse(null), null);\n        }\n\n        [Fact]\n        public void ParseThrowsInvalidMaxDepth()\n        {\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(() => FormUrlEncodedJson.Parse(CreateQuery(), -1), \"maxDepth\", \"1\", -1);\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(() => FormUrlEncodedJson.Parse(CreateQuery(), 0), \"maxDepth\", \"1\", 0);\n        }\n\n        [Fact]\n        public void ParseThrowsMaxDepthExceeded()\n        {\n            // Depth of 'a[b]=1' is 3\n            IEnumerable<KeyValuePair<string, string>> query = CreateQuery(new KeyValuePair<string, string>(\"a[b]\", \"1\"));\n            Assert.ThrowsArgument(() => { FormUrlEncodedJson.Parse(query, 2); }, null);\n\n            // This should succeed\n            Assert.NotNull(FormUrlEncodedJson.Parse(query, 3));\n        }\n\n        [Fact]\n        public void TryParseThrowsOnNull()\n        {\n            JObject value;\n            Assert.ThrowsArgumentNull(() => FormUrlEncodedJson.TryParse(null, out value), null);\n        }\n\n        [Fact]\n        public void TryParseThrowsInvalidMaxDepth()\n        {\n            JObject value;\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(() => FormUrlEncodedJson.TryParse(CreateQuery(), -1, out value), \"maxDepth\", \"1\", -1);\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(() => FormUrlEncodedJson.TryParse(CreateQuery(), 0, out value), \"maxDepth\", \"1\", 0);\n        }\n\n        [Fact]\n        public void TryParseReturnsFalseMaxDepthExceeded()\n        {\n            JObject value;\n\n            // Depth of 'a[b]=1' is 3\n            IEnumerable<KeyValuePair<string, string>> query = CreateQuery(new KeyValuePair<string, string>(\"a[b]\", \"1\"));\n            Assert.False(FormUrlEncodedJson.TryParse(query, 2, out value), \"Parse should have failed due to too high depth.\");\n\n            // This should succeed\n            Assert.True(FormUrlEncodedJson.TryParse(query, 3, out value), \"Expected non-null JsonObject instance\");\n            Assert.NotNull(value);\n        }\n\n        private static IEnumerable<KeyValuePair<string, string>> CreateQuery(params KeyValuePair<string, string>[] namevaluepairs)\n        {\n            return new List<KeyValuePair<string, string>>(namevaluepairs);\n        }\n    }\n}"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/FormUrlEncodedMediaTypeFormatterTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Linq;\nusing System.Net.Http.Formatting.DataSets;\nusing System.Net.Http.Headers;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Newtonsoft.Json.Linq;\n\nnamespace System.Net.Http.Formatting\n{\n    public class FormUrlEncodedMediaTypeFormatterTests\n    {\n        private const int MinBufferSize = 256;\n        private const int DefaultBufferSize = 32 * 1024;\n        private const int DefaultMaxDepth = 1024;\n\n        [Fact]\n        void CopyConstructor()\n        {\n            TestFormUrlEncodedMediaTypeFormatter formatter = new TestFormUrlEncodedMediaTypeFormatter()\n            {\n                MaxDepth = 42,\n                ReadBufferSize = 512\n            };\n\n            TestFormUrlEncodedMediaTypeFormatter derivedFormatter = new TestFormUrlEncodedMediaTypeFormatter(formatter);\n\n            Assert.Equal(formatter.MaxDepth, derivedFormatter.MaxDepth);\n            Assert.Equal(formatter.ReadBufferSize, derivedFormatter.ReadBufferSize);\n        }\n\n        [Fact]\n        public void TypeIsCorrect()\n        {\n            Assert.Type.HasProperties(typeof(FormUrlEncodedMediaTypeFormatter), TypeAssert.TypeProperties.IsPublicVisibleClass);\n        }\n\n        [Fact]\n        public void SupportedMediaTypes_HeaderValuesAreNotSharedBetweenInstances()\n        {\n            var formatter1 = new FormUrlEncodedMediaTypeFormatter();\n            var formatter2 = new FormUrlEncodedMediaTypeFormatter();\n\n            foreach (MediaTypeHeaderValue mediaType1 in formatter1.SupportedMediaTypes)\n            {\n                MediaTypeHeaderValue mediaType2 = formatter2.SupportedMediaTypes.Single(m => m.Equals(mediaType1));\n                Assert.NotSame(mediaType1, mediaType2);\n            }\n        }\n\n        [Fact]\n        public void SupportEncodings_ValuesAreNotSharedBetweenInstances()\n        {\n            var formatter1 = new FormUrlEncodedMediaTypeFormatter();\n            var formatter2 = new FormUrlEncodedMediaTypeFormatter();\n\n            foreach (Encoding encoding1 in formatter1.SupportedEncodings)\n            {\n                Encoding encoding2 = formatter2.SupportedEncodings.Single(e => e.Equals(encoding1));\n                Assert.NotSame(encoding1, encoding2);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(HttpTestData), \"StandardFormUrlEncodedMediaTypes\")]\n        public void Constructor(MediaTypeHeaderValue mediaType)\n        {\n            FormUrlEncodedMediaTypeFormatter formatter = new FormUrlEncodedMediaTypeFormatter();\n            Assert.True(formatter.SupportedMediaTypes.Contains(mediaType), String.Format(\"SupportedMediaTypes should have included {0}.\", mediaType.ToString()));\n        }\n\n        [Fact]\n        public void DefaultMediaTypeReturnsApplicationJson()\n        {\n            MediaTypeHeaderValue mediaType = FormUrlEncodedMediaTypeFormatter.DefaultMediaType;\n            Assert.NotNull(mediaType);\n            Assert.Equal(\"application/x-www-form-urlencoded\", mediaType.MediaType);\n        }\n\n        [Fact]\n        public void ReadBufferSize_RoundTrips()\n        {\n            Assert.Reflection.IntegerProperty(\n                new FormUrlEncodedMediaTypeFormatter(),\n                c => c.ReadBufferSize,\n                expectedDefaultValue: 32 * 1024,\n                minLegalValue: 256,\n                illegalLowerValue: 255,\n                maxLegalValue: null,\n                illegalUpperValue: null,\n                roundTripTestValue: 1024);\n        }\n\n        [Fact]\n        public void MaxDepthReturnsCorrectValue()\n        {\n            Assert.Reflection.IntegerProperty(\n                 new FormUrlEncodedMediaTypeFormatter(),\n                 f => f.MaxDepth,\n                 expectedDefaultValue: 256,\n                 minLegalValue: 1,\n                 illegalLowerValue: 0,\n                 maxLegalValue: null,\n                 illegalUpperValue: null,\n                 roundTripTestValue: 10);\n        }\n\n        [Fact]\n        public async Task ReadDeeplyNestedObjectThrows()\n        {\n            FormUrlEncodedMediaTypeFormatter formatter = new FormUrlEncodedMediaTypeFormatter() { MaxDepth = 100 };\n\n            StringContent content = new StringContent(GetDeeplyNestedObject(125));\n\n            content.Headers.ContentType = new MediaTypeHeaderValue(\"application/x-www-form-urlencoded\");\n            var contentStream = await content.ReadAsStreamAsync();\n            await Assert.ThrowsAsync<ArgumentException>(\n                () => formatter.ReadFromStreamAsync(typeof(JToken), contentStream, content, null));\n        }\n\n        [Fact]\n        public async Task ReadDeeplyNestedObjectWithBigDepthQuotaWorks()\n        {\n            FormUrlEncodedMediaTypeFormatter formatter = new FormUrlEncodedMediaTypeFormatter() { MaxDepth = 150 };\n\n            StringContent content = new StringContent(GetDeeplyNestedObject(125));\n\n            content.Headers.ContentType = new MediaTypeHeaderValue(\"application/x-www-form-urlencoded\");\n\n            var contentStream = await content.ReadAsStreamAsync();\n            JToken result = (JToken)(await formatter.ReadFromStreamAsync(typeof(JToken), contentStream, content, null));\n            Assert.NotNull(result);\n        }\n\n        static string GetDeeplyNestedObject(int depth)\n        {\n            StringBuilder sb = new StringBuilder(\"a\");\n            for (int i = 0; i < depth; i++)\n            {\n                sb.Append(\"[a]\");\n            }\n            sb.Append(\"=1\");\n            return sb.ToString();\n        }\n\n        [Fact]\n        public void CanReadTypeThrowsOnNull()\n        {\n            TestFormUrlEncodedMediaTypeFormatter formatter = new TestFormUrlEncodedMediaTypeFormatter();\n            Assert.ThrowsArgumentNull(() => { formatter.CanReadType(null); }, \"type\");\n        }\n\n        [Theory]\n        [InlineData(typeof(FormDataCollection))]\n        [InlineData(typeof(JToken))]\n        public void CanReadTypeTrue(Type type)\n        {\n            TestFormUrlEncodedMediaTypeFormatter formatter = new TestFormUrlEncodedMediaTypeFormatter();\n\n            Assert.True(formatter.CanReadType(type));\n        }\n\n\n        [Theory]\n        [TestDataSet(typeof(CommonUnitTestDataSets), \"RepresentativeValueAndRefTypeTestDataCollection\")]\n        public void CanReadTypeReturnsFalse(Type variationType, object testData)\n        {\n            GC.KeepAlive(testData); // Mark parameter as used. See xUnit1026, [Theory] method doesn't use all parameters.\n            TestFormUrlEncodedMediaTypeFormatter formatter = new TestFormUrlEncodedMediaTypeFormatter();\n\n            Assert.False(formatter.CanReadType(variationType));\n\n            // Ask a 2nd time to probe whether the cached result is treated the same\n            Assert.False(formatter.CanReadType(variationType));\n        }\n\n\n        [Fact]\n        public void CanWriteTypeThrowsOnNull()\n        {\n            TestFormUrlEncodedMediaTypeFormatter formatter = new TestFormUrlEncodedMediaTypeFormatter();\n            Assert.ThrowsArgumentNull(() => { formatter.CanWriteType(null); }, \"type\");\n        }\n\n        [Theory]\n        [TestDataSet(typeof(CommonUnitTestDataSets), \"RepresentativeValueAndRefTypeTestDataCollection\")]\n        public void CanWriteTypeReturnsFalse(Type variationType, object testData)\n        {\n            GC.KeepAlive(testData); // Mark parameter as used. See xUnit1026, [Theory] method doesn't use all parameters.\n            TestFormUrlEncodedMediaTypeFormatter formatter = new TestFormUrlEncodedMediaTypeFormatter();\n\n            Assert.False(formatter.CanWriteType(variationType), \"formatter should have returned false.\");\n\n            // Ask a 2nd time to probe whether the cached result is treated the same\n            Assert.False(formatter.CanWriteType(variationType), \"formatter should have returned false on 2nd try as well.\");\n        }\n\n        [Fact]\n        public void ReadFromStreamThrowsOnNull()\n        {\n            TestFormUrlEncodedMediaTypeFormatter formatter = new TestFormUrlEncodedMediaTypeFormatter();\n            Assert.ThrowsArgumentNull(() => { formatter.ReadFromStreamAsync(null, Stream.Null, null, null); }, \"type\");\n            Assert.ThrowsArgumentNull(() => { formatter.ReadFromStreamAsync(typeof(object), null, null, null); }, \"readStream\");\n        }\n\n        [Fact]\n        public void WriteToStreamAsyncThrowsNotImplemented()\n        {\n            FormUrlEncodedMediaTypeFormatter formatter = new FormUrlEncodedMediaTypeFormatter();\n            Assert.Throws<NotSupportedException>(\n                () => formatter.WriteToStreamAsync(typeof(object), new object(), Stream.Null, null, null),\n                \"The media type formatter of type 'FormUrlEncodedMediaTypeFormatter' does not support writing because it does not implement the WriteToStreamAsync method.\");\n        }\n\n        public class TestFormUrlEncodedMediaTypeFormatter : FormUrlEncodedMediaTypeFormatter\n        {\n            public TestFormUrlEncodedMediaTypeFormatter()\n            {\n            }\n\n            public TestFormUrlEncodedMediaTypeFormatter(TestFormUrlEncodedMediaTypeFormatter formatter)\n                : base(formatter)\n            {\n            }\n\n            public new bool CanReadType(Type type)\n            {\n                return base.CanReadType(type);\n            }\n\n            public new bool CanWriteType(Type type)\n            {\n                return base.CanWriteType(type);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/JsonMediaTypeFormatterTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Net.Http.Formatting.DataSets;\nusing System.Net.Http.Formatting.DataSets.Types;\nusing System.Net.Http.Headers;\nusing System.Runtime.Serialization.Json;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Moq;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\n\nnamespace System.Net.Http.Formatting\n{\n    public class JsonMediaTypeFormatterTests : MediaTypeFormatterTestBase<JsonMediaTypeFormatter>\n    {\n        // Test data which should round-trip without type information in the serialization.  Contains an exhaustive\n        // selection of JSON native types.  (BSON also supports Int32, Int64, DateTime, Guid, ... natively.)\n        private static readonly RefTypeTestData<object> BunchOfJsonObjectsTestData = new RefTypeTestData<object>(\n            () => new List<object> { null, String.Empty, \"This is a string\", false, true, Double.MinValue,\n                Double.MaxValue, });\n\n        // Test data for DBNull.  Separate from BunchOfJsonObjectsTestData because DBNull will round-trip as null.\n        private static readonly RefTypeTestData<object> DBNullAsObjectTestData = new RefTypeTestData<object>(\n            () => new List<object> { DBNull.Value, });\n\n        public static IEnumerable<TestData> BunchOfJsonObjectsTestDataCollection\n        {\n            get { return new TestData[] { BunchOfJsonObjectsTestData, }; }\n        }\n\n        public static IEnumerable<TestData> DBNullAsObjectTestDataCollection\n        {\n            get { return new TestData[] { DBNullAsObjectTestData, }; }\n        }\n\n        public static List<Type> JTokenTypes\n        {\n            get\n            {\n                return new List<Type>\n                {\n                    typeof(JToken),\n                    typeof(JValue),\n                    typeof(JArray),\n                    typeof(JObject)\n                };\n            }\n        }\n\n        public static IEnumerable<TestData> ValueAndRefTypeTestDataCollectionExceptULong\n        {\n            get\n            {\n                // Include neither ISerializable data set nor unsigned longs\n                return CommonUnitTestDataSets.ValueAndRefTypeTestDataCollection.Except(\n                    new TestData[] { CommonUnitTestDataSets.Ulongs, CommonUnitTestDataSets.ISerializableTypes });\n            }\n        }\n\n        public override IEnumerable<MediaTypeHeaderValue> ExpectedSupportedMediaTypes\n        {\n            get { return HttpTestData.StandardJsonMediaTypes; }\n        }\n\n        public override IEnumerable<Encoding> ExpectedSupportedEncodings\n        {\n            get { return HttpTestData.StandardEncodings; }\n        }\n\n        public override byte[] ExpectedSampleTypeByteRepresentation\n        {\n            get { return ExpectedSupportedEncodings.ElementAt(0).GetBytes(\"{\\\"Number\\\":42}\"); }\n        }\n\n        [Fact]\n        void CopyConstructor()\n        {\n            TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter()\n            {\n                Indent = true,\n                MaxDepth = 42,\n                UseDataContractJsonSerializer = true\n            };\n\n            TestJsonMediaTypeFormatter derivedFormatter = new TestJsonMediaTypeFormatter(formatter);\n\n            Assert.Equal(formatter.MaxDepth, derivedFormatter.MaxDepth);\n            Assert.Equal(formatter.UseDataContractJsonSerializer, derivedFormatter.UseDataContractJsonSerializer);\n            Assert.Equal(formatter.Indent, derivedFormatter.Indent);\n            Assert.Same(formatter.SerializerSettings, derivedFormatter.SerializerSettings);\n            Assert.Same(formatter.SerializerSettings.ContractResolver, derivedFormatter.SerializerSettings.ContractResolver);\n        }\n\n        [Fact]\n        public void DefaultMediaType_ReturnsApplicationJson()\n        {\n            MediaTypeHeaderValue mediaType = JsonMediaTypeFormatter.DefaultMediaType;\n            Assert.NotNull(mediaType);\n            Assert.Equal(\"application/json\", mediaType.MediaType);\n        }\n\n        [Fact]\n        public void Indent_RoundTrips()\n        {\n            Assert.Reflection.BooleanProperty(\n                new XmlMediaTypeFormatter(),\n                c => c.Indent,\n                expectedDefaultValue: false);\n        }\n\n        [Fact]\n        public void MaxDepth_RoundTrips()\n        {\n            Assert.Reflection.IntegerProperty(\n                new JsonMediaTypeFormatter(),\n                c => c.MaxDepth,\n                expectedDefaultValue: 256,\n                minLegalValue: 1,\n                illegalLowerValue: 0,\n                maxLegalValue: null,\n                illegalUpperValue: null,\n                roundTripTestValue: 256);\n        }\n\n        [Theory]\n        [TestDataSet(typeof(CommonUnitTestDataSets), \"RepresentativeValueAndRefTypeTestDataCollection\")]\n        public void CanReadType_ReturnsExpectedValues(Type variationType, object testData)\n        {\n            TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter();\n\n            bool isSerializable = IsTypeSerializableWithJsonSerializer(variationType, testData);\n            bool canSupport = formatter.CanReadTypeProxy(variationType);\n\n            // If we don't agree, we assert only if the DCJ serializer says it cannot support something we think it should\n            Assert.False(isSerializable != canSupport && isSerializable, String.Format(\"CanReadType returned wrong value for '{0}'.\", variationType));\n\n            // Ask a 2nd time to probe whether the cached result is treated the same\n            canSupport = formatter.CanReadTypeProxy(variationType);\n            Assert.False(isSerializable != canSupport && isSerializable, String.Format(\"2nd CanReadType returned wrong value for '{0}'.\", variationType));\n        }\n\n        [Fact]\n        public async Task FormatterThrowsOnWriteWhenOverridenCreateFails()\n        {\n            // Arrange\n            TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter();\n\n            formatter.ThrowAnExceptionOnCreate = true;\n\n            MemoryStream memoryStream = new MemoryStream();\n            HttpContent content = new StringContent(String.Empty);\n\n            // Act & Assert\n            Func<Task> action = () => formatter.WriteToStreamAsync(typeof(SampleType), new SampleType(), memoryStream, content, transportContext: null);\n            await Assert.ThrowsAsync<InvalidOperationException>(action, \"The 'CreateJsonSerializer' method threw an exception when attempting to create a JSON serializer.\");\n\n            Assert.Null(formatter.InnerDataContractSerializer);\n            Assert.NotNull(formatter.InnerJsonSerializer);\n        }\n\n        [Fact]\n        public async Task FormatterThrowsOnWriteWhenOverridenCreateReturnsNull()\n        {\n            // Arrange\n            TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter();\n\n            formatter.ReturnNullOnCreate = true;\n\n            MemoryStream memoryStream = new MemoryStream();\n            HttpContent content = new StringContent(String.Empty);\n\n            // Act & Assert\n            Func<Task> action = () => formatter.WriteToStreamAsync(typeof(SampleType), new SampleType(), memoryStream, content, transportContext: null);\n            await Assert.ThrowsAsync<InvalidOperationException>(action, \"The 'CreateJsonSerializer' method returned null. It must return a JSON serializer instance.\");\n\n            Assert.Null(formatter.InnerDataContractSerializer);\n            Assert.NotNull(formatter.InnerJsonSerializer);\n        }\n\n        [Fact]\n        public async Task FormatterThrowsOnReadWhenOverridenCreateFails()\n        {\n            // Arrange\n            TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter();\n\n            formatter.ThrowAnExceptionOnCreate = true;\n\n            byte[] array = Encoding.UTF8.GetBytes(\"foo\");\n            MemoryStream memoryStream = new MemoryStream(array);\n\n            HttpContent content = new StringContent(\"foo\");\n\n            // Act & Assert\n            Func<Task> action = () => formatter.ReadFromStreamAsync(typeof(SampleType), memoryStream, content, null);\n            await Assert.ThrowsAsync<InvalidOperationException>(action, \"The 'CreateJsonSerializer' method threw an exception when attempting to create a JSON serializer.\");\n\n            Assert.Null(formatter.InnerDataContractSerializer);\n            Assert.NotNull(formatter.InnerJsonSerializer);\n        }\n\n        [Fact]\n        public async Task FormatterThrowsOnReadWhenOverridenCreateReturnsNull()\n        {\n            // Arrange\n            TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter();\n\n            formatter.ReturnNullOnCreate = true;\n\n            byte[] array = Encoding.UTF8.GetBytes(\"foo\");\n            MemoryStream memoryStream = new MemoryStream(array);\n\n            HttpContent content = new StringContent(\"foo\");\n\n            // Act & Assert\n            Func<Task> action = () => formatter.ReadFromStreamAsync(typeof(SampleType), memoryStream, content, null);\n            await Assert.ThrowsAsync<InvalidOperationException>(action, \"The 'CreateJsonSerializer' method returned null. It must return a JSON serializer instance.\");\n\n            Assert.Null(formatter.InnerDataContractSerializer);\n            Assert.NotNull(formatter.InnerJsonSerializer);\n        }\n\n#if !Testing_NetStandard1_3 // Cannot read or write w/ DCS in netstandard1.3.\n        [Fact]\n        public async Task DataContractFormatterThrowsOnWriteWhenOverridenCreateFails()\n        {\n            // Arrange\n            TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter();\n\n            formatter.ThrowAnExceptionOnCreate = true;\n            formatter.UseDataContractJsonSerializer = true;\n\n            MemoryStream memoryStream = new MemoryStream();\n            HttpContent content = new StringContent(String.Empty);\n\n            // Act & Assert\n            Func<Task> action = () => formatter.WriteToStreamAsync(typeof(SampleType), new SampleType(), memoryStream, content, transportContext: null);\n            await Assert.ThrowsAsync<InvalidOperationException>(action, \"The 'DataContractJsonSerializer' serializer cannot serialize the type 'SampleType'.\");\n\n            Assert.NotNull(formatter.InnerDataContractSerializer);\n            Assert.Null(formatter.InnerJsonSerializer);\n        }\n\n        [Fact]\n        public async Task DataContractFormatterThrowsOnWriteWhenOverridenCreateReturnsNull()\n        {\n            // Arrange\n            TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter();\n\n            formatter.ReturnNullOnCreate = true;\n            formatter.UseDataContractJsonSerializer = true;\n\n            MemoryStream memoryStream = new MemoryStream();\n            HttpContent content = new StringContent(String.Empty);\n\n            // Act & Assert\n            Func<Task> action = () => formatter.WriteToStreamAsync(typeof(SampleType), new SampleType(), memoryStream, content, transportContext: null);\n            await Assert.ThrowsAsync<InvalidOperationException>(action, \"The 'DataContractJsonSerializer' serializer cannot serialize the type 'SampleType'.\");\n\n            Assert.NotNull(formatter.InnerDataContractSerializer);\n            Assert.Null(formatter.InnerJsonSerializer);\n        }\n\n        [Fact]\n        public async Task DataContractFormatterThrowsOnReadWhenOverridenCreateFails()\n        {\n            // Arrange\n            TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter();\n\n            formatter.ThrowAnExceptionOnCreate = true;\n            formatter.UseDataContractJsonSerializer = true;\n\n            byte[] array = Encoding.UTF8.GetBytes(\"foo\");\n            MemoryStream memoryStream = new MemoryStream(array);\n\n            HttpContent content = new StringContent(\"foo\");\n\n            // Act & Assert\n            Func<Task> action = () => formatter.ReadFromStreamAsync(typeof(SampleType), memoryStream, content, null);\n            await Assert.ThrowsAsync<InvalidOperationException>(action, \"The 'DataContractJsonSerializer' serializer cannot serialize the type 'SampleType'.\");\n\n            Assert.NotNull(formatter.InnerDataContractSerializer);\n            Assert.Null(formatter.InnerJsonSerializer);\n        }\n\n        [Fact]\n        public async Task DataContractFormatterThrowsOnReadWhenOverridenCreateReturnsNull()\n        {\n            // Arrange\n            TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter();\n\n            formatter.ReturnNullOnCreate = true;\n            formatter.UseDataContractJsonSerializer = true;\n\n            byte[] array = Encoding.UTF8.GetBytes(\"foo\");\n            MemoryStream memoryStream = new MemoryStream(array);\n\n            HttpContent content = new StringContent(\"foo\");\n\n            // Act & Assert\n            Func<Task> action = () => formatter.ReadFromStreamAsync(typeof(SampleType), memoryStream, content, null);\n\n            await Assert.ThrowsAsync<InvalidOperationException>(action, \"The 'DataContractJsonSerializer' serializer cannot serialize the type 'SampleType'.\");\n\n            Assert.NotNull(formatter.InnerDataContractSerializer);\n            Assert.Null(formatter.InnerJsonSerializer);\n        }\n#endif\n\n        [Fact]\n        public void CanReadType_ReturnsTrueOnJtoken()\n        {\n            TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter();\n            foreach (Type type in JTokenTypes)\n            {\n                Assert.True(formatter.CanReadTypeProxy(type), \"formatter should have returned true.\");\n            }\n        }\n\n        [Fact]\n        public void CanWriteType_ReturnsTrueOnJtoken()\n        {\n            TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter();\n            foreach (Type type in JTokenTypes)\n            {\n                Assert.True(formatter.CanWriteTypeProxy(type), \"formatter should have returned false.\");\n            }\n        }\n\n        [Fact]\n        public async Task ReadFromStreamAsync_RoundTripsJToken()\n        {\n            string beforeMessage = \"Hello World\";\n            TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter();\n            JToken before = beforeMessage;\n            MemoryStream memStream = new MemoryStream();\n            JsonTextWriter jsonWriter = new JsonTextWriter(new StreamWriter(memStream));\n            before.WriteTo(jsonWriter);\n            jsonWriter.Flush();\n            memStream.Position = 0;\n\n            JToken after = (await Assert.Task.SucceedsWithResultAsync<object>(formatter.ReadFromStreamAsync(typeof(JToken), memStream, null, null))) as JToken;\n            Assert.NotNull(after);\n            string afterMessage = after.ToObject<string>();\n\n            Assert.Equal(beforeMessage, afterMessage);\n        }\n\n        [Theory]\n        [TestDataSet(typeof(JsonMediaTypeFormatterTests), \"ValueAndRefTypeTestDataCollectionExceptULong\", RoundTripDataVariations)]\n        [TestDataSet(typeof(JsonMediaTypeFormatterTests), \"BunchOfJsonObjectsTestDataCollection\", RoundTripDataVariations)]\n        public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsync(Type variationType, object testData)\n        {\n            // Guard\n            bool canSerialize = IsTypeSerializableWithJsonSerializer(variationType, testData) && Assert.Http.CanRoundTrip(variationType);\n            if (canSerialize)\n            {\n                // Arrange\n                TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter();\n\n                // Arrange & Act & Assert\n                object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n                Assert.Equal(testData, readObj);\n            }\n        }\n\n#if !NETCOREAPP2_1 // DBNull not serializable on .NET Core 2.1.\n        // Test alternate null value; always serialized as \"null\"\n        [Theory]\n        [TestDataSet(typeof(JsonMediaTypeFormatterTests), \"DBNullAsObjectTestDataCollection\", TestDataVariations.AllSingleInstances)]\n        public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsync_DBNullAsNull(Type variationType, object testData)\n        {\n            // Arrange\n            TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter();\n\n            // Arrange & Act & Assert\n            object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n\n            // DBNull.Value can be read back as null object.\n            Assert.Null(readObj);\n        }\n\n        [Theory]\n        [TestDataSet(typeof(JsonMediaTypeFormatterTests), \"DBNullAsObjectTestDataCollection\", TestDataVariations.AsDictionary)]\n        public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsync_DBNullAsNull_Dictionary(Type variationType, object testData)\n        {\n            // Guard\n            IDictionary<string, object> expectedDictionary = Assert.IsType<Dictionary<string, object>>(testData);\n\n            // Arrange\n            TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter();\n\n            // Arrange & Act & Assert\n            object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n\n            // DBNull.Value can be read back as null object. Reach into collections.\n            Assert.Equal(testData.GetType(), readObj.GetType());\n\n            IDictionary<string, object> readDictionary = (IDictionary<string, object>)readObj;\n            Assert.Equal(expectedDictionary.Count, readDictionary.Count);\n\n            foreach (string key in expectedDictionary.Keys)\n            {\n                Assert.True(readDictionary.ContainsKey(key));\n                Assert.Null(readDictionary[key]);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(JsonMediaTypeFormatterTests), \"DBNullAsObjectTestDataCollection\",\n            TestDataVariations.AsArray | TestDataVariations.AsList)]\n        public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsync_DBNullAsNull_Enumerable(Type variationType, object testData)\n        {\n            // Guard\n            Assert.True((testData as IEnumerable<object>) != null);\n\n            // Arrange\n            TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter();\n            IEnumerable<object> expectedEnumerable = (IEnumerable<object>)testData;\n\n            // Arrange & Act & Assert\n            object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n\n            // DBNull.Value can be read back as null object. Reach into collections.\n            Assert.Equal(testData.GetType(), readObj.GetType());\n\n            IEnumerable<object> readEnumerable = (IEnumerable<object>)readObj;\n            Assert.Equal(expectedEnumerable.Count(), readEnumerable.Count());\n\n            foreach (object readContent in readEnumerable)\n            {\n                Assert.Null(readContent);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(JsonMediaTypeFormatterTests), \"DBNullAsObjectTestDataCollection\", TestDataVariations.AsClassMember)]\n        public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsync_DBNullAsNull_Holder(Type variationType, object testData)\n        {\n            // Guard\n            Assert.IsType<TestDataHolder<object>>(testData);\n\n            // Arrange\n            TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter();\n\n            // Arrange & Act & Assert\n            object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n\n            // DBNull.Value can be read back as null object. Reach into objects.\n            Assert.Equal(testData.GetType(), readObj.GetType());\n\n            TestDataHolder<object> readDataHolder = (TestDataHolder<object>)readObj;\n            Assert.Null(readDataHolder.V1);\n        }\n\n        [Fact]\n        public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsync_DBNullAsNullString()\n        {\n            // Arrange\n            TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter();\n            Type variationType = typeof(string);\n            object testData = DBNull.Value;\n\n            // Arrange & Act & Assert\n            object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n\n            // DBNull.value can be read as null of any nullable type\n            Assert.Null(readObj);\n        }\n\n        [Fact]\n        public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsync_DBNull()\n        {\n            // Arrange\n            TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter();\n            Type variationType = typeof(DBNull);\n            object testData = DBNull.Value;\n\n            // Arrange & Act & Assert\n            object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n\n            // Only JSON case where DBNull.Value round-trips\n            Assert.Equal(testData, readObj);\n        }\n#endif\n\n        [Fact]\n        public async Task UseDataContractJsonSerializer_False()\n        {\n            JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter\n            {\n                UseDataContractJsonSerializer = false\n            };\n            MemoryStream memoryStream = new MemoryStream();\n            HttpContent content = new StringContent(String.Empty);\n            await Assert.Task.SucceedsAsync(formatter.WriteToStreamAsync(typeof(SampleType), new SampleType(), memoryStream, content, transportContext: null));\n            memoryStream.Position = 0;\n            string serializedString = new StreamReader(memoryStream).ReadToEnd();\n            //Assert.True(serializedString.Contains(\"DataContractSampleType\"),\n            //    \"SampleType should be serialized with data contract name DataContractSampleType because UseDataContractJsonSerializer is set to true.\");\n            Assert.False(serializedString.Contains(\"\\r\\n\"), \"Using JsonSerializer should emit data without indentation by default.\");\n        }\n\n        [Fact]\n        public async Task UseDataContractJsonSerializer_False_Indent()\n        {\n            JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter\n            {\n                UseDataContractJsonSerializer = false,\n                Indent = true\n            };\n            MemoryStream memoryStream = new MemoryStream();\n            HttpContent content = new StringContent(String.Empty);\n            await Assert.Task.SucceedsAsync(formatter.WriteToStreamAsync(typeof(SampleType), new SampleType(), memoryStream, content, transportContext: null));\n            memoryStream.Position = 0;\n            string serializedString = new StreamReader(memoryStream).ReadToEnd();\n            Assert.True(serializedString.Contains(\"\\r\\n\"), \"Using JsonSerializer with Indent set to true should emit data with indentation.\");\n        }\n\n        [Theory]\n        [InlineData(typeof(IQueryable<string>))]\n        [InlineData(typeof(IEnumerable<string>))]\n        public async Task UseJsonFormatterWithNull(Type type)\n        {\n            JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter\n            {\n                UseDataContractJsonSerializer = false\n            };\n            MemoryStream memoryStream = new MemoryStream();\n            HttpContent content = new StringContent(String.Empty);\n            await Assert.Task.SucceedsAsync(formatter.WriteToStreamAsync(type, null, memoryStream, content, transportContext: null));\n            memoryStream.Position = 0;\n            string serializedString = new StreamReader(memoryStream).ReadToEnd();\n            Assert.True(serializedString.Contains(\"null\"), \"Using Json formatter to serialize null should emit 'null'.\");\n        }\n\n        [Fact]\n        public async Task WriteToStreamAsync_RoundTripsJToken()\n        {\n            string beforeMessage = \"Hello World\";\n            TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter();\n            JToken before = new JValue(beforeMessage);\n            MemoryStream memStream = new MemoryStream();\n\n            await Assert.Task.SucceedsAsync(formatter.WriteToStreamAsync(typeof(JToken), before, memStream, null, null));\n            memStream.Position = 0;\n            JToken after = JToken.Load(new JsonTextReader(new StreamReader(memStream)));\n            string afterMessage = after.ToObject<string>();\n\n            Assert.Equal(beforeMessage, afterMessage);\n        }\n\n        public override Task ReadFromStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding)\n        {\n            // Arrange\n            JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter();\n            string formattedContent = \"\\\"\" + content + \"\\\"\";\n            string mediaType = string.Format(\"application/json; charset={0}\", encoding);\n\n            // Act & assert\n            return ReadContentUsingCorrectCharacterEncodingHelperAsync(\n                formatter, content, formattedContent, mediaType, encoding, isDefaultEncoding);\n        }\n\n        public override Task WriteToStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding)\n        {\n            // Arrange\n            JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter();\n            string formattedContent = \"\\\"\" + content + \"\\\"\";\n            string mediaType = string.Format(\"application/json; charset={0}\", encoding);\n\n            // Act & assert\n            return WriteContentUsingCorrectCharacterEncodingHelperAsync(\n                formatter, content, formattedContent, mediaType, encoding, isDefaultEncoding);\n        }\n\n#if NET6_0_OR_GREATER\n        // Cannot Mock a Stream and let JsonWriter write to it. Writer will use ReadOnlySpan in this case and such\n        // parameters are not currently mockable. See moq/moq4#829, moq/moq4#979, and dotnet/runtime#45152.\n        // Override here avoids the Mock<Stream> and should confirm this Stream is not closed. Also adds an\n        // additional check of the written text.\n        [Fact]\n        public override async Task WriteToStreamAsync_WhenObjectIsNull_WritesDataButDoesNotCloseStream()\n        {\n            // Arrange\n            JsonMediaTypeFormatter formatter = CreateFormatter();\n            Stream stream = new MemoryStream();\n            HttpContent content = new StreamContent(Stream.Null);\n\n            // Act\n            await formatter.WriteToStreamAsync(typeof(SampleType), null, stream, content, null);\n\n            // Assert (stream will throw if it has been closed)\n            stream.Position = 0;\n            using var reader = new StreamReader(stream);\n            Assert.Equal(\"null\", reader.ReadToEnd());\n        }\n#endif\n\n        public class TestJsonMediaTypeFormatter : JsonMediaTypeFormatter\n        {\n            public TestJsonMediaTypeFormatter()\n            {\n            }\n\n            public TestJsonMediaTypeFormatter(TestJsonMediaTypeFormatter formatter)\n                : base(formatter)\n            {\n            }\n\n            public bool ThrowAnExceptionOnCreate { get; set; }\n            public bool ReturnNullOnCreate { get; set; }\n            public JsonSerializer InnerJsonSerializer { get; private set; }\n            public DataContractJsonSerializer InnerDataContractSerializer { get; private set; }\n\n            public bool CanReadTypeProxy(Type type)\n            {\n                return CanReadType(type);\n            }\n\n            public bool CanWriteTypeProxy(Type type)\n            {\n                return CanWriteType(type);\n            }\n\n            public override JsonSerializer CreateJsonSerializer()\n            {\n                InnerJsonSerializer = base.CreateJsonSerializer();\n\n                if (ReturnNullOnCreate)\n                {\n                    return null;\n                }\n\n                if (ThrowAnExceptionOnCreate)\n                {\n                    throw new Exception(\"Throwing exception directly, since it needs to get caught by a catch all\");\n                }\n\n                return InnerJsonSerializer;\n            }\n\n            public override DataContractJsonSerializer CreateDataContractSerializer(Type type)\n            {\n                InnerDataContractSerializer = base.CreateDataContractSerializer(type);\n\n                if (ReturnNullOnCreate)\n                {\n                    return null;\n                }\n\n                if (ThrowAnExceptionOnCreate)\n                {\n                    throw new Exception(\"Throwing exception directly, since it needs to get caught by a catch all\");\n                }\n\n                return InnerDataContractSerializer;\n            }\n        }\n\n        private bool IsTypeSerializableWithJsonSerializer(Type type, object obj)\n        {\n            try\n            {\n                new DataContractJsonSerializer(type);\n                if (obj != null && obj.GetType() != type)\n                {\n                    new DataContractJsonSerializer(obj.GetType());\n                }\n            }\n            catch\n            {\n                return false;\n            }\n\n            return !Assert.Http.IsKnownUnserializable(type, obj, (t) => typeof(INotJsonSerializable).IsAssignableFrom(t));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/JsonNetSerializationTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n// Portions copyright (c) 2007 James Newton-King\n//\n// Permission is hereby granted, free of charge, to any person\n// obtaining a copy of this software and associated documentation\n// files (the \"Software\"), to deal in the Software without\n// restriction, including without limitation the rights to use,\n// copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the\n// Software is furnished to do so, subject to the following\n// conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n// OTHER DEALINGS IN THE SOFTWARE.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Runtime.Serialization;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\n\nnamespace System.Net.Http.Formatting\n{\n    public class JsonNetSerializationTest\n    {\n        public static TheoryDataSet<object, string> SerializedJson\n        {\n            get\n            {\n                return new TheoryDataSet<object, string>()\n                {\n                    // Primitives\n                    { 'f', \"\\\"f\\\"\" },\n                    { \"abc\", \"\\\"abc\\\"\" },\n                    { \"\\\"\\\\\", @\"\"\"\\\"\"\\\\\"\"\" },\n                    { 256, \"256\" },\n                    { (ulong)long.MaxValue, long.MaxValue.ToString() },\n                    { 45.78m, \"45.78\" },\n                    { .00000457823432, \"4.57823432E-06\" },\n                    { (byte)24, \"24\" },\n                    { false, \"false\" },\n                    { AttributeTargets.Assembly | AttributeTargets.Constructor, \"33\" },\n                    { ConsoleColor.DarkCyan, \"3\" },\n                    { new DateTimeOffset(1999, 5, 27, 4, 34, 45, TimeSpan.Zero), \"\\\"1999-05-27T04:34:45+00:00\\\"\" },\n                    { new TimeSpan(5, 30, 0), \"\\\"05:30:00\\\"\" },\n                    { new Uri(\"http://www.bing.com\"), @\"\"\"http://www.bing.com\"\"\" },\n                    { new Uri(\"http://www.bing.com/\"), @\"\"\"http://www.bing.com/\"\"\" },\n                    { new Uri(\"http://www.bing.com/foo\"), @\"\"\"http://www.bing.com/foo\"\"\" },\n                    { new Uri(\"http://www.bing.com/foo/\"), @\"\"\"http://www.bing.com/foo/\"\"\" },\n                    { new Guid(\"4ed1cd44-11d7-4b27-b623-0b8b553c8906\"), \"\\\"4ed1cd44-11d7-4b27-b623-0b8b553c8906\\\"\" },\n\n                    // Structs\n                    { new Point() { x = 45, Y = -5}, \"{\\\"x\\\":45,\\\"Y\\\":-5}\" },\n\n                    // Arrays\n                    { new object[] {}, \"[]\" },\n                    { new int[] { 1, 2, 3}, \"[1,2,3]\" },\n                    { new string[] { \"a\", \"b\"}, \"[\\\"a\\\",\\\"b\\\"]\" },\n                    { new Point[] { new Point() { x = 10, Y = 10}, new Point() { x = 20, Y = 20}}, \"[{\\\"x\\\":10,\\\"Y\\\":10},{\\\"x\\\":20,\\\"Y\\\":20}]\" },\n\n                    // Collections\n                    { new List<int> { 1, 2, 3}, \"[1,2,3]\" },\n                    { new List<string> { \"a\", \"b\"}, \"[\\\"a\\\",\\\"b\\\"]\" },\n                    { new List<Point> { new Point() { x = 10, Y = 10}, new Point() { x = 20, Y = 20}}, \"[{\\\"x\\\":10,\\\"Y\\\":10},{\\\"x\\\":20,\\\"Y\\\":20}]\" },\n                    { new MyList<int> { 1, 2, 3}, \"[1,2,3]\" },\n                    { new MyList<string> { \"a\", \"b\"}, \"[\\\"a\\\",\\\"b\\\"]\" },\n                    { new MyList<Point> { new Point() { x = 10, Y = 10}, new Point() { x = 20, Y = 20}}, \"[{\\\"x\\\":10,\\\"Y\\\":10},{\\\"x\\\":20,\\\"Y\\\":20}]\" },\n\n                    // Dictionaries\n\n                    { new Dictionary<string, string> { { \"k1\", \"v1\" }, { \"k2\", \"v2\" } }, \"{\\\"k1\\\":\\\"v1\\\",\\\"k2\\\":\\\"v2\\\"}\" },\n                    { new Dictionary<int, string> { { 1, \"v1\" }, { 2, \"v2\" } }, \"{\\\"1\\\":\\\"v1\\\",\\\"2\\\":\\\"v2\\\"}\" },\n\n                    // Anonymous types\n                    { new { Anon1 = 56, Anon2 = \"foo\"}, \"{\\\"Anon1\\\":56,\\\"Anon2\\\":\\\"foo\\\"}\" },\n\n                    // Classes\n                    { new DataContractType() { s = \"foo\", i = 49, NotAMember = \"Error\" }, \"{\\\"s\\\":\\\"foo\\\",\\\"i\\\":49}\" },\n                    { new POCOType() { s = \"foo\", t = \"Error\"}, \"{\\\"s\\\":\\\"foo\\\"}\" },\n#if !Testing_NetStandard1_3 // Only publics are serialized in netstandard1.3\n                    { 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\\\"}\" },\n#else\n                    { new SerializableType(\"protected\") { publicField = \"public\", protectedInternalField = \"protected internal\", internalField = \"internal\", PublicProperty = \"private\", nonSerializedField = \"Error\" }, \"{\\\"publicField\\\":\\\"public\\\",\\\"PublicProperty\\\":\\\"private\\\"}\" },\n#endif\n                    { new { field1 = \"x\", field2 = (string)null, field3 = \"y\" }, \"{\\\"field1\\\":\\\"x\\\",\\\"field2\\\":null,\\\"field3\\\":\\\"y\\\"}\" },\n\n                    // Generics\n                    { new KeyValuePair<string, bool>(\"foo\", false), \"{\\\"Key\\\":\\\"foo\\\",\\\"Value\\\":false}\" },\n\n                    // ISerializable types\n                    { new ISerializableType() { Property = \"Value\" }, \"{\\\"SomeProperty\\\":\\\"Value\\\"}\" },\n\n                    // JSON Values\n                    { new JValue(false), \"false\" },\n                    { new JValue(54), \"54\" },\n                    { new JValue(\"s\"), \"\\\"s\\\"\" },\n                    { new JArray() { new JValue(1), new JValue(2) }, \"[1,2]\" },\n                    { new JObject() { { \"k1\", new JValue(\"v1\") }, { \"k2\", new JValue(\"v2\") } }, \"{\\\"k1\\\":\\\"v1\\\",\\\"k2\\\":\\\"v2\\\"}\" },\n                    { new KeyValuePair<JToken, JToken>(new JValue(\"k\"), new JArray() { new JValue(\"v1\"), new JValue(\"v2\") }), \"{\\\"Key\\\":\\\"k\\\",\\\"Value\\\":[\\\"v1\\\",\\\"v2\\\"]}\" },\n                };\n            }\n        }\n\n        public static TheoryDataSet<object, string, Type> TypedSerializedJson\n        {\n            get\n            {\n                return new TheoryDataSet<object, string, Type>()\n                {\n                    // Null\n                    { null, \"null\", typeof(POCOType) },\n                    { JValue.CreateNull(), \"null\", typeof(JToken) },\n\n                    // Nullables\n                    { new int?(), \"null\", typeof(int?) },\n                    { new Point?(), \"null\", typeof(Point?) },\n                    { new ConsoleColor?(), \"null\", typeof(ConsoleColor?) },\n                    { new int?(45), \"45\", typeof(int?) },\n                    { new Point?(new Point() { x = 45, Y = -5 }), \"{\\\"x\\\":45,\\\"Y\\\":-5}\", typeof(Point?) },\n                    { new ConsoleColor?(ConsoleColor.DarkMagenta), \"5\", typeof(ConsoleColor?)},\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"SerializedJson\")]\n        public Task ObjectsSerializeToExpectedJson(object o, string expectedJson)\n        {\n            return ObjectsSerializeToExpectedJsonWithProvidedType(o, expectedJson, o.GetType());\n        }\n\n        [Theory]\n        [PropertyData(\"SerializedJson\")]\n        public Task JsonDeserializesToExpectedObject(object expectedObject, string json)\n        {\n            return JsonDeserializesToExpectedObjectWithProvidedType(expectedObject, json, expectedObject.GetType());\n        }\n\n        [Theory]\n        [PropertyData(\"TypedSerializedJson\")]\n        public async Task ObjectsSerializeToExpectedJsonWithProvidedType(object o, string expectedJson, Type type)\n        {\n            Assert.Equal(expectedJson, await SerializeAsync(o, type));\n        }\n\n        [Theory]\n        [PropertyData(\"TypedSerializedJson\")]\n        public async Task JsonDeserializesToExpectedObjectWithProvidedType(object expectedObject, string json, Type type)\n        {\n            if (expectedObject == null)\n            {\n                Assert.Null(await DeserializeAsync(json, type));\n            }\n            else\n            {\n                object o = await DeserializeAsync(json, type);\n                Assert.Equal(expectedObject, o, new ObjectComparer());\n            }\n        }\n\n        [Fact]\n        public async Task CallbacksGetCalled()\n        {\n            TypeWithCallbacks o = new TypeWithCallbacks();\n\n            string json = await SerializeAsync(o, typeof(TypeWithCallbacks));\n            Assert.Equal(\"12\", o.callbackOrder);\n\n            TypeWithCallbacks deserializedObject = (await DeserializeAsync(json, typeof(TypeWithCallbacks))) as TypeWithCallbacks;\n            Assert.Equal(\"34\", deserializedObject.callbackOrder);\n        }\n\n        [Fact]\n        public async Task DerivedTypesArePreserved()\n        {\n            JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter();\n            formatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Objects;\n            string json = await SerializeAsync(new Derived(), typeof(Base), formatter);\n            object deserializedObject = await DeserializeAsync(json, typeof(Base), formatter);\n            Assert.IsType<Derived>(deserializedObject);\n        }\n\n        [Fact]\n        public async Task ArbitraryTypesArentDeserializedByDefault()\n        {\n            string json = \"{\\\"$type\\\":\\\"\" + typeof(DangerousType).AssemblyQualifiedName + \"\\\"}\";\n            object deserializedObject = await DeserializeAsync(json, typeof(object));\n            Assert.IsNotType<DangerousType>(deserializedObject);\n        }\n\n        [Fact]\n        public async Task ReferencesArePreserved()\n        {\n            Ref ref1 = new Ref();\n            Ref ref2 = new Ref();\n            ref1.Reference = ref2;\n            ref2.Reference = ref1;\n\n            string json = await SerializeAsync(ref1, typeof(Ref));\n            Ref deserializedObject = (await DeserializeAsync(json, typeof(Ref))) as Ref;\n\n            Assert.ReferenceEquals(deserializedObject, deserializedObject.Reference.Reference);\n        }\n\n        [Fact]\n        public async Task MissingMemberGetsDeserializedToNull()\n        {\n            string json = \"{}\";\n\n            POCOType deserializedObject = (await DeserializeAsync(json, typeof(POCOType))) as POCOType;\n\n            Assert.Null(deserializedObject.s);\n        }\n\n        [Fact]\n        public Task DeserializingDeepArraysThrows()\n        {\n            StringBuilder sb = new StringBuilder();\n            int depth = 500;\n            for (int i = 0; i < depth; i++)\n            {\n                sb.Append(\"[\");\n            }\n            sb.Append(\"null\");\n            for (int i = 0; i < depth; i++)\n            {\n                sb.Append(\"]\");\n            }\n            string json = sb.ToString();\n\n            return Assert.ThrowsAsync<JsonReaderException>(() => DeserializeAsync(json, typeof(object)));\n        }\n\n        [Theory]\n        // existing good surrogate pair\n        [InlineData(\"ABC \\\\ud800\\\\udc00 DEF\", \"ABC \\ud800\\udc00 DEF\")]\n        // invalid surrogates (two high back-to-back)\n        [InlineData(\"ABC \\\\ud800\\\\ud800 DEF\", \"ABC \\ufffd\\ufffd DEF\")]\n        // invalid high surrogate at end of string\n        [InlineData(\"ABC \\\\ud800\", \"ABC \\ufffd\")]\n        // high surrogate not followed by low surrogate\n        [InlineData(\"ABC \\\\ud800 DEF\", \"ABC \\ufffd DEF\")]\n        // low surrogate not preceded by high surrogate\n        [InlineData(\"ABC \\\\udc00\\\\ud800 DEF\", \"ABC \\ufffd\\ufffd DEF\")]\n        // make sure unencoded invalid surrogate characters don't make it through\n#if NETCOREAPP // Json.NET uses its regular invalid Unicode character on .NET Core 2.1; '?' elsewhere.\n        [InlineData(\"\\udc00\\ud800\\ud800\", \"\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\\ufffd\")]\n#else\n        [InlineData(\"\\udc00\\ud800\\ud800\", \"??????\")]\n#endif\n        public async Task InvalidUnicodeStringsAreFixedUp(string input, string expectedString)\n        {\n            string json = \"\\\"\" + input + \"\\\"\";\n            string deserializedString = (await DeserializeAsync(json, typeof(string))) as string;\n\n            Assert.Equal(expectedString, deserializedString);\n\n        }\n\n        private static async Task<string> SerializeAsync(object o, Type type, MediaTypeFormatter formatter = null)\n        {\n            formatter = formatter ?? new JsonMediaTypeFormatter();\n            MemoryStream ms = new MemoryStream();\n            await formatter.WriteToStreamAsync(type, o, ms, null, null);\n            ms.Flush();\n            ms.Position = 0;\n            return new StreamReader(ms).ReadToEnd();\n        }\n\n        internal static Task<object> DeserializeAsync(string json, Type type, MediaTypeFormatter formatter = null, IFormatterLogger formatterLogger = null)\n        {\n            formatter = formatter ?? new JsonMediaTypeFormatter();\n            MemoryStream ms = new MemoryStream();\n            byte[] bytes = Encoding.Default.GetBytes(json);\n            ms.Write(bytes, 0, bytes.Length);\n            ms.Flush();\n            ms.Position = 0;\n\n            return formatter.ReadFromStreamAsync(type, ms, content: null, formatterLogger: formatterLogger);\n        }\n    }\n\n    public class ObjectComparer : IEqualityComparer<object>\n    {\n        bool IEqualityComparer<object>.Equals(object x, object y)\n        {\n            Type xType = x.GetType();\n\n            if (xType == y.GetType())\n            {\n                if (typeof(JToken).IsAssignableFrom(xType) || xType == typeof(ArgumentNullException) || xType == typeof(KeyValuePair<JToken, JToken>))\n                {\n                    return x.ToString() == y.ToString();\n                }\n                if (xType == typeof(DataContractType))\n                {\n                    return Equals<DataContractType>(x, y);\n                }\n                if (xType == typeof(POCOType))\n                {\n                    return Equals<POCOType>(x, y);\n                }\n\n                if (xType == typeof(SerializableType))\n                {\n                    return Equals<SerializableType>(x, y);\n                }\n\n                if (xType == typeof(ISerializableType))\n                {\n                    return Equals<ISerializableType>(x, y);\n                }\n\n                if (xType == typeof(Point))\n                {\n                    return Equals<Point>(x, y);\n                }\n\n                if (typeof(IEnumerable).IsAssignableFrom(xType))\n                {\n                    IEnumerator xEnumerator = ((IEnumerable)x).GetEnumerator();\n                    IEnumerator yEnumerator = ((IEnumerable)y).GetEnumerator();\n                    while (xEnumerator.MoveNext())\n                    {\n                        // if x is longer than y\n                        if (!yEnumerator.MoveNext())\n                        {\n                            return false;\n                        }\n                        else\n                        {\n                            if (!xEnumerator.Current.Equals(yEnumerator.Current))\n                            {\n                                return false;\n                            }\n                        }\n                    }\n                    // if y is longer than x\n                    if (yEnumerator.MoveNext())\n                    {\n                        return false;\n                    }\n                    return true;\n                }\n            }\n\n            return x.Equals(y);\n        }\n\n        int IEqualityComparer<object>.GetHashCode(object obj)\n        {\n            throw new NotImplementedException();\n        }\n\n        bool Equals<T>(object x, object y) where T : IEquatable<T>\n        {\n            IEquatable<T> yEquatable = (IEquatable<T>)y;\n            return yEquatable.Equals((T)x);\n        }\n    }\n\n    // Marked as [Serializable] to check that [DataContract] takes precedence over [Serializable]\n    [DataContract]\n    [Serializable]\n    public class DataContractType : IEquatable<DataContractType>\n    {\n        [DataMember]\n        public string s;\n\n        [DataMember]\n        internal int i;\n\n        public string NotAMember;\n\n        public bool Equals(DataContractType other)\n        {\n            return this.s == other.s && this.i == other.i;\n        }\n    }\n\n    public class POCOType : IEquatable<POCOType>\n    {\n        public string s;\n        internal string t;\n\n        public bool Equals(POCOType other)\n        {\n            return this.s == other.s;\n        }\n    }\n\n    public class MyList<T> : ICollection<T>\n    {\n        List<T> innerList = new List<T>();\n\n        public IEnumerator<T> GetEnumerator()\n        {\n            return innerList.GetEnumerator();\n        }\n\n        public void Add(T item)\n        {\n            innerList.Add(item);\n        }\n\n        public void Clear()\n        {\n            innerList.Clear();\n        }\n\n        public bool Contains(T item)\n        {\n            return innerList.Contains(item);\n        }\n\n        public void CopyTo(T[] array, int arrayIndex)\n        {\n            innerList.CopyTo(array, arrayIndex);\n        }\n\n        public int Count\n        {\n            get { return innerList.Count; }\n        }\n\n        public bool IsReadOnly\n        {\n            get { return ((ICollection<T>)innerList).IsReadOnly; }\n        }\n\n        public bool Remove(T item)\n        {\n            return innerList.Remove(item);\n        }\n\n        IEnumerator IEnumerable.GetEnumerator()\n        {\n            return innerList.GetEnumerator();\n        }\n\n        IEnumerator<T> IEnumerable<T>.GetEnumerator()\n        {\n            return innerList.GetEnumerator();\n        }\n    }\n\n    [Serializable]\n    class SerializableType : IEquatable<SerializableType>\n    {\n        [JsonConstructor]\n        public SerializableType(string protectedFieldValue)\n        {\n            this.protectedField = protectedFieldValue;\n        }\n\n        public string publicField;\n        internal string internalField;\n        protected internal string protectedInternalField;\n        protected string protectedField;\n        private string privateField;\n\n        public string PublicProperty\n        {\n            get\n            {\n                return privateField;\n            }\n            set\n            {\n                this.privateField = value;\n            }\n        }\n\n        [NonSerialized]\n        public string nonSerializedField;\n\n        public bool Equals(SerializableType other)\n        {\n#if !Testing_NetStandard1_3 // Only publics are serialized in netstandard1.3. privateField is serialized through PublicProperty\n            return this.publicField == other.publicField &&\n                this.internalField == other.internalField &&\n                this.protectedInternalField == other.protectedInternalField &&\n                this.protectedField == other.protectedField &&\n                this.privateField == other.privateField;\n#else\n            // this.privateField is serialized through this.PublicProperty, thus the comparison here\n            return this.publicField == other.publicField &&\n                this.privateField == other.privateField;\n#endif\n        }\n    }\n\n    public struct Point : IEquatable<Point>\n    {\n        public int x;\n        public int Y { get; set; }\n\n        public bool Equals(Point other)\n        {\n            return this.x == other.x && this.Y == other.Y;\n        }\n    }\n\n    [DataContract(IsReference = true)]\n    public class Ref\n    {\n        [DataMember]\n        public Ref Reference;\n    }\n\n    public class Base\n    {\n    }\n\n    public class Derived : Base\n    {\n    }\n\n    [DataContract]\n    public class TypeWithCallbacks\n    {\n        public string callbackOrder = \"\";\n\n        [OnSerializing]\n        public void OnSerializing(StreamingContext c)\n        {\n            callbackOrder += \"1\";\n        }\n\n        [OnSerialized]\n        public void OnSerialized(StreamingContext c)\n        {\n            callbackOrder += \"2\";\n        }\n\n        [OnDeserializing]\n        public void OnDeserializing(StreamingContext c)\n        {\n            callbackOrder += \"3\";\n        }\n\n        [OnDeserialized]\n        public void OnDeserialized(StreamingContext c)\n        {\n            callbackOrder += \"4\";\n        }\n    }\n\n    public class DangerousType\n    {\n    }\n\n    [Serializable]\n    public class ISerializableType : ISerializable, IEquatable<ISerializableType>\n    {\n        public ISerializableType()\n        {\n        }\n\n        protected ISerializableType(SerializationInfo info, StreamingContext context)\n        {\n            // The key here for GetValue/SetValue is intentionally different from the property name.\n            // This tests that the serializer is using the result of GetObjectData, rather than the property\n            // name.\n            Property = (string)info.GetValue(\"SomeProperty\", typeof(String));\n        }\n\n        public string Property\n        {\n            get;\n            set;\n        }\n\n        public void GetObjectData(SerializationInfo info, StreamingContext context)\n        {\n            info.AddValue(\"SomeProperty\", this.Property, typeof(String));\n        }\n\n        public bool Equals(ISerializableType other)\n        {\n            return String.Equals(Property, other.Property, StringComparison.Ordinal);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/JsonNetValidationTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Net.Http.Formatting\n{\n    public class JsonNetValidationTest\n    {\n        public static TheoryDataSet<string, Type, int> Theories\n        {\n            get\n            {\n                return new TheoryDataSet<string, Type, int>()\n                {\n                    // Type coercion\n\n                    {\"null\", typeof(int), 1},\n                    {\"45\", typeof(string), 0},\n                    {\"random text\", typeof(DateTimeOffset), 1},\n                    {\"[1,2,3]\", typeof(string[]), 0},\n\n                    {\"\\\"foo\\\"\", typeof(int), 1},\n                    {\"\\\"foo\\\"\", typeof(DateTime), 1},\n\n                    {\"[\\\"a\\\",\\\"b\\\",\\\"45\\\",34]\", typeof(int[]), 2},\n                    {\"[\\\"a\\\",\\\"b\\\",\\\"45\\\",34]\", typeof(DateTime[]), 5},\n\n                    // Required members\n\n                    {\"{}\", typeof(DataContractWithRequiredMembers), 2},\n                    {\"[{},{},{}]\", typeof(DataContractWithRequiredMembers[]), 6},\n\n                    // Throwing setters\n\n                    {\"{\\\"Throws\\\":\\\"foo\\\"}\", typeof(TypeWithThrowingSetter), 1},\n                    {\"[{\\\"Throws\\\":\\\"foo\\\"},{\\\"Throws\\\":\\\"foo\\\"}]\", typeof(TypeWithThrowingSetter[]), 2},\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"Theories\")]\n        public async Task ModelErrorsPopulatedWithValidationErrors(string json, Type type, int expectedErrors)\n        {\n            JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter();\n            formatter.RequiredMemberSelector = new SimpleRequiredMemberSelector();\n            Mock<IFormatterLogger> mockLogger = new Mock<IFormatterLogger>() { };\n\n            await JsonNetSerializationTest.DeserializeAsync(json, type, formatter, mockLogger.Object);\n\n            mockLogger.Verify(mock => mock.LogError(It.IsAny<string>(), It.IsAny<Exception>()), Times.Exactly(expectedErrors));\n        }\n\n        [Fact]\n        public async Task HittingMaxDepthRaisesOnlyOneValidationError()\n        {\n            // Arrange\n            JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter();\n            Mock<IFormatterLogger> mockLogger = new Mock<IFormatterLogger>();\n\n            StringBuilder sb = new StringBuilder(\"{'A':null}\");\n            for (int i = 0; i < 5000; i++)\n            {\n                sb.Insert(0, \"{'A':\");\n                sb.Append('}');\n            }\n            string json = sb.ToString();\n\n            // Act\n            await JsonNetSerializationTest.DeserializeAsync(json, typeof(Nest), formatter, mockLogger.Object);\n\n            // Assert\n            mockLogger.Verify(mock => mock.LogError(It.IsAny<string>(), It.IsAny<Exception>()), Times.Once());\n        }\n    }\n\n    // this IRMS treats all member names that start with \"Required\" as required\n    public class SimpleRequiredMemberSelector : IRequiredMemberSelector\n    {\n        public bool IsRequiredMember(MemberInfo member)\n        {\n            return member.Name.StartsWith(\"Required\");\n        }\n    }\n\n    public class DataContractWithRequiredMembers\n    {\n        public string Required1;\n        public string Required2;\n        public string Optional;\n    }\n\n    public class TypeWithThrowingSetter\n    {\n        public string Throws\n        {\n            get\n            {\n                return \"foo\";\n            }\n            set\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n\n    public class Nest\n    {\n        public Nest A { get; set; }\n    }\n}"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/MediaTypeConstantsTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http\n{\n    public class MediaTypeConstantsTests\n    {\n        private static void ValidateClones(MediaTypeHeaderValue clone1, MediaTypeHeaderValue clone2, string charset)\n        {\n            Assert.NotNull(clone1);\n            Assert.NotNull(clone2);\n            Assert.NotSame(clone1, clone2);\n            Assert.Equal(clone1.MediaType, clone2.MediaType);\n            Assert.Equal(charset, clone1.CharSet);\n            Assert.Equal(charset, clone2.CharSet);\n        }\n\n        [Fact]\n        public void ApplicationOctetStreamMediaType_ReturnsClone()\n        {\n            ValidateClones(MediaTypeConstants.ApplicationOctetStreamMediaType, MediaTypeConstants.ApplicationOctetStreamMediaType, null);\n        }\n\n        [Fact]\n        public void ApplicationXmlMediaType_ReturnsClone()\n        {\n            ValidateClones(MediaTypeConstants.ApplicationXmlMediaType, MediaTypeConstants.ApplicationXmlMediaType, null);\n        }\n\n        [Fact]\n        public void ApplicationJsonMediaType_ReturnsClone()\n        {\n            ValidateClones(MediaTypeConstants.ApplicationJsonMediaType, MediaTypeConstants.ApplicationJsonMediaType, null);\n        }\n\n        [Fact]\n        public void TextXmlMediaType_ReturnsClone()\n        {\n            ValidateClones(MediaTypeConstants.TextXmlMediaType, MediaTypeConstants.TextXmlMediaType, null);\n        }\n\n        [Fact]\n        public void TextJsonMediaType_ReturnsClone()\n        {\n            ValidateClones(MediaTypeConstants.TextJsonMediaType, MediaTypeConstants.TextJsonMediaType, null);\n        }\n\n        [Fact]\n        public void ApplicationFormUrlEncodedMediaType_ReturnsClone()\n        {\n            ValidateClones(MediaTypeConstants.ApplicationFormUrlEncodedMediaType, MediaTypeConstants.ApplicationFormUrlEncodedMediaType, null);\n        }\n\n\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/MediaTypeFormatterCollectionTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Net.Http.Formatting.DataSets;\nusing System.Net.Http.Formatting.Mocks;\nusing System.Net.Http.Headers;\nusing System.Web.Http;\nusing System.Xml;\nusing System.Xml.Linq;\nusing Microsoft.TestCommon;\nusing Newtonsoft.Json.Linq;\n\nnamespace System.Net.Http.Formatting\n{\n    public class MediaTypeFormatterCollectionTests\n    {\n        [Fact]\n        public void TypeIsCorrect()\n        {\n            Assert.Type.HasProperties(typeof(MediaTypeFormatterCollection), TypeAssert.TypeProperties.IsPublicVisibleClass, typeof(Collection<MediaTypeFormatter>));\n        }\n\n        [Fact]\n        public void Constructor()\n        {\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection();\n\n            Assert.Equal(3, collection.Count);\n            Assert.NotNull(collection.XmlFormatter);\n            Assert.NotNull(collection.JsonFormatter);\n            Assert.NotNull(collection.FormUrlEncodedFormatter);\n        }\n\n        [Fact]\n        public void Constructor1_AcceptsEmptyList()\n        {\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection(new MediaTypeFormatter[0]);\n            Assert.Empty(collection);\n        }\n\n        [Theory]\n        [TestDataSet(typeof(HttpTestData), \"AllFormatterCollections\")]\n        public void Constructor1_SetsProperties(IEnumerable<MediaTypeFormatter> formatterCollection)\n        {\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection(formatterCollection);\n            if (collection.OfType<XmlMediaTypeFormatter>().Any())\n            {\n                Assert.NotNull(collection.XmlFormatter);\n            }\n            else\n            {\n                Assert.Null(collection.XmlFormatter);\n            }\n\n            if (collection.OfType<JsonMediaTypeFormatter>().Any())\n            {\n                Assert.NotNull(collection.JsonFormatter);\n            }\n            else\n            {\n                Assert.Null(collection.JsonFormatter);\n            }\n        }\n\n        [Fact]\n        public void Constructor1_SetsDerivedFormatters()\n        {\n            // force to array to get stable instances\n            MediaTypeFormatter[] derivedFormatters = HttpTestData.DerivedFormatters.ToArray();\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection(derivedFormatters);\n            Assert.True(derivedFormatters.SequenceEqual(collection));\n        }\n\n        [Fact]\n        public void Constructor1_ThrowsWithNullFormatters()\n        {\n            Assert.ThrowsArgumentNull(() => new MediaTypeFormatterCollection(null), \"formatters\");\n        }\n\n        [Fact]\n        public void Constructor1_ThrowsWithNullFormatterInCollection()\n        {\n            Assert.ThrowsArgument(\n                () => new MediaTypeFormatterCollection(new MediaTypeFormatter[] { null }), \"formatters\",\n                Error.Format(Properties.Resources.CannotHaveNullInList,\n                typeof(MediaTypeFormatter).Name));\n        }\n\n        [Fact]\n        public void Constructor1_AcceptsDuplicateFormatterTypes()\n        {\n            MediaTypeFormatter[] formatters = new MediaTypeFormatter[]\n            {\n                new XmlMediaTypeFormatter(),\n                new JsonMediaTypeFormatter(),\n                new FormUrlEncodedMediaTypeFormatter(),\n\n                new XmlMediaTypeFormatter(),\n                new JsonMediaTypeFormatter(),\n                new FormUrlEncodedMediaTypeFormatter(),\n            };\n\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection(formatters);\n            Assert.True(formatters.SequenceEqual(collection));\n        }\n\n        [Fact]\n        public void MediaTypeFormatterCollection_Changing_FiresOnClear()\n        {\n            TestChanging((collection) => collection.Clear(), 1);\n        }\n\n        [Fact]\n        public void MediaTypeFormatterCollection_Changing_FiresOnInsert()\n        {\n            TestChanging((collection) => collection.Insert(0, new XmlMediaTypeFormatter()), 1);\n        }\n\n        [Fact]\n        public void MediaTypeFormatterCollection_Changing_FiresOnRemove()\n        {\n            TestChanging((collection) => collection.RemoveAt(0), 1);\n        }\n\n        [Fact]\n        public void MediaTypeFormatterCollection_Changing_FiresOnSet()\n        {\n            TestChanging((collection) => collection[0] = new XmlMediaTypeFormatter(), 1);\n        }\n\n        private static void TestChanging(Action<MediaTypeFormatterCollection> mutation, int expectedCount)\n        {\n            // Arrange\n            MediaTypeFormatter formatter1 = new XmlMediaTypeFormatter();\n            MediaTypeFormatter formatter2 = new JsonMediaTypeFormatter();\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection(new MediaTypeFormatter[] { formatter1, formatter2 });\n            int changeCount = 0;\n            collection.Changing += (source, args) => { changeCount++; };\n\n            // Act\n            mutation(collection);\n\n            //Assert\n            Assert.Equal(expectedCount, changeCount);\n        }\n\n        [Fact]\n        public void XmlFormatter_SetByCtor()\n        {\n            XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter();\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection(new MediaTypeFormatter[] { formatter });\n            Assert.Same(formatter, collection.XmlFormatter);\n        }\n\n        [Fact]\n        public void XmlFormatter_ClearedByCtor()\n        {\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection(new MediaTypeFormatter[0]);\n            Assert.Null(collection.XmlFormatter);\n        }\n\n        [Fact]\n        public void JsonFormatter_SetByCtor()\n        {\n            JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter();\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection(new MediaTypeFormatter[] { formatter });\n            Assert.Same(formatter, collection.JsonFormatter);\n        }\n\n        [Fact]\n        public void JsonFormatter_ClearedByCtor()\n        {\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection(new MediaTypeFormatter[0]);\n            Assert.Null(collection.JsonFormatter);\n        }\n\n        [Fact]\n        public void FormUrlEncodedFormatter_SetByCtor()\n        {\n            FormUrlEncodedMediaTypeFormatter formatter = new FormUrlEncodedMediaTypeFormatter();\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection(new MediaTypeFormatter[] { formatter });\n            Assert.Same(formatter, collection.FormUrlEncodedFormatter);\n        }\n\n        [Fact]\n        public void FormUrlEncodedFormatter_ClearedByCtor()\n        {\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection(new MediaTypeFormatter[0]);\n            Assert.Null(collection.FormUrlEncodedFormatter);\n        }\n\n        [Fact]\n        public void Remove_SetsXmlFormatter()\n        {\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection();\n            int count = collection.Count;\n            collection.Remove(collection.XmlFormatter);\n            Assert.Null(collection.XmlFormatter);\n            Assert.Equal(count - 1, collection.Count);\n        }\n\n        [Fact]\n        public void Remove_SetsJsonFormatter()\n        {\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection();\n            int count = collection.Count;\n            collection.Remove(collection.JsonFormatter);\n            Assert.Null(collection.JsonFormatter);\n            Assert.Equal(count - 1, collection.Count);\n        }\n\n        [Fact]\n        public void Insert_SetsXmlFormatter()\n        {\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection();\n            int count = collection.Count;\n            XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter();\n            collection.Insert(0, formatter);\n            Assert.Same(formatter, collection.XmlFormatter);\n            Assert.Equal(count + 1, collection.Count);\n        }\n\n        [Fact]\n        public void Insert_SetsJsonFormatter()\n        {\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection();\n            int count = collection.Count;\n            JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter();\n            collection.Insert(0, formatter);\n            Assert.Same(formatter, collection.JsonFormatter);\n            Assert.Equal(count + 1, collection.Count);\n        }\n\n        [Fact]\n        public void FindReader_ThrowsOnNullType()\n        {\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection();\n            MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue(\"text/test\");\n            Assert.ThrowsArgumentNull(() => collection.FindReader(type: null, mediaType: mediaType), \"type\");\n        }\n\n        [Fact]\n        public void FindReader_ThrowsOnNullMediaType()\n        {\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection();\n            Assert.ThrowsArgumentNull(() => collection.FindReader(type: typeof(object), mediaType: null), \"mediaType\");\n        }\n\n        [Fact]\n        public void FindReader_ReturnsNullOnNoMatch()\n        {\n            // Arrange\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter() { CallBase = true };\n\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection();\n            collection.Clear();\n            collection.Add(formatter);\n\n            MediaTypeHeaderValue contentType = new MediaTypeHeaderValue(\"text/test\");\n\n            // Act\n            MediaTypeFormatter actualFormatter = collection.FindReader(typeof(object), contentType);\n\n            // Assert\n            Assert.Null(actualFormatter);\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(CommonUnitTestDataSets), \"RepresentativeValueAndRefTypeTestDataCollection\",\n            typeof(HttpTestData), \"LegalMediaTypeStrings\")]\n        public void FindReader_ReturnsFormatterOnMatch(Type variationType, object testData, string mediaType)\n        {\n            // Arrange\n            GC.KeepAlive(testData); // Mark parameter as used. See xUnit1026, [Theory] method doesn't use all parameters.\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter() { CallBase = true };\n            foreach (string legalMediaType in HttpTestData.LegalMediaTypeStrings)\n            {\n                formatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue(legalMediaType));\n            }\n\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection();\n            collection.Clear();\n            collection.Add(formatter);\n\n            MediaTypeHeaderValue contentType = new MediaTypeHeaderValue(mediaType);\n\n            // Act\n            MediaTypeFormatter actualFormatter = collection.FindReader(variationType, contentType);\n\n            // Assert\n            Assert.Same(formatter, actualFormatter);\n        }\n\n        [Fact]\n        public void FindWriter_ThrowsOnNullType()\n        {\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection();\n            MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue(\"text/test\");\n            Assert.ThrowsArgumentNull(() => collection.FindWriter(type: null, mediaType: mediaType), \"type\");\n        }\n\n        [Fact]\n        public void FindWriter_ThrowsOnNullMediaType()\n        {\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection();\n            Assert.ThrowsArgumentNull(() => collection.FindWriter(type: typeof(object), mediaType: null), \"mediaType\");\n        }\n\n        [Fact]\n        public void FindWriter_ReturnsNullOnNoMatch()\n        {\n            // Arrange\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter() { CallBase = true };\n\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection();\n            collection.Clear();\n            collection.Add(formatter);\n\n            MediaTypeHeaderValue contentType = new MediaTypeHeaderValue(\"text/test\");\n\n            // Act\n            MediaTypeFormatter actualFormatter = collection.FindWriter(typeof(object), contentType);\n\n            // Assert\n            Assert.Null(actualFormatter);\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(CommonUnitTestDataSets), \"RepresentativeValueAndRefTypeTestDataCollection\",\n            typeof(HttpTestData), \"LegalMediaTypeStrings\")]\n        public void FindWriter_ReturnsFormatterOnMatch(Type variationType, object testData, string mediaType)\n        {\n            // Arrange\n            GC.KeepAlive(testData); // Mark parameter as used. See xUnit1026, [Theory] method doesn't use all parameters.\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter() { CallBase = true };\n            foreach (string legalMediaType in HttpTestData.LegalMediaTypeStrings)\n            {\n                formatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue(mediaType));\n            }\n\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection();\n            collection.Clear();\n            collection.Add(formatter);\n\n            MediaTypeHeaderValue contentType = new MediaTypeHeaderValue(mediaType);\n\n            // Act\n            MediaTypeFormatter actualFormatter = collection.FindWriter(variationType, contentType);\n\n            // Assert\n            Assert.Same(formatter, actualFormatter);\n        }\n\n        [Theory]\n        [InlineData(typeof(JObject))]\n        [InlineData(typeof(XAttribute))]\n        [InlineData(typeof(Type))]\n        [InlineData(typeof(byte[]))]\n        [InlineData(typeof(XmlElement))]\n        [InlineData(typeof(FormDataCollection))]\n        public void IsTypeExcludedFromValidation_ReturnsTrueForExcludedTypes(Type type)\n        {\n            Assert.True(MediaTypeFormatterCollection.IsTypeExcludedFromValidation(type));\n        }\n\n        [Fact]\n        public void WritingFormatters_FiltersOutCanWriteAnyTypesFalse()\n        {\n            // Arrange\n            MockMediaTypeFormatter writableFormatter = new MockMediaTypeFormatter();\n            MockMediaTypeFormatter readOnlyFormatter = new MockMediaTypeFormatter() { CanWriteAnyTypesReturn = false };\n            List<MediaTypeFormatter> formatters = new List<MediaTypeFormatter>() { writableFormatter, readOnlyFormatter };\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection(formatters);\n\n            // Act\n            MediaTypeFormatter[] writableFormatters = collection.WritingFormatters;\n\n            // Assert\n            MediaTypeFormatter[] expectedFormatters = new MediaTypeFormatter[] { writableFormatter };\n            Assert.Equal(expectedFormatters, writableFormatters);\n        }\n\n        [Fact]\n        public void WritingFormatters_FiltersOutNull()\n        {\n            // Arrange\n            MockMediaTypeFormatter writableFormatter = new MockMediaTypeFormatter();\n            List<MediaTypeFormatter> formatters = new List<MediaTypeFormatter>() { writableFormatter };\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection(formatters);\n            collection.Add(null);\n\n            // Act\n            MediaTypeFormatter[] writableFormatters = collection.WritingFormatters;\n\n            // Assert\n            MediaTypeFormatter[] expectedFormatters = new MediaTypeFormatter[] { writableFormatter };\n            Assert.Equal(expectedFormatters, writableFormatters);\n        }\n\n        [Fact]\n        public void WritingFormatters_Caches()\n        {\n            // Arrange\n            MockMediaTypeFormatter formatter1 = new MockMediaTypeFormatter();\n            MockMediaTypeFormatter formatter2 = new MockMediaTypeFormatter();\n            List<MediaTypeFormatter> formatters = new List<MediaTypeFormatter>() { formatter1, formatter2 };\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection(formatters);\n\n            // Act\n            MediaTypeFormatter[] writableFormatters1 = collection.WritingFormatters;\n            MediaTypeFormatter[] writableFormatters2 = collection.WritingFormatters;\n\n            // Assert\n            MediaTypeFormatter[] expectedFormatters = formatters.ToArray();\n            Assert.Equal(expectedFormatters, writableFormatters1);\n            Assert.Same(writableFormatters1, writableFormatters2);\n        }\n\n        [Fact]\n        public void WritingFormatters_Insert_ResetsCache()\n        {\n            TestWritingFormattersCacheReset((collection) => collection.Insert(0, new MockMediaTypeFormatter()));\n        }\n\n        [Fact]\n        public void WritingFormatters_RemoveAt_ResetsCache()\n        {\n            TestWritingFormattersCacheReset((collection) => collection.RemoveAt(0));\n        }\n\n        private static void TestWritingFormattersCacheReset(Action<MediaTypeFormatterCollection> mutation)\n        {\n            // Arrange\n            MockMediaTypeFormatter formatter1 = new MockMediaTypeFormatter();\n            MockMediaTypeFormatter formatter2 = new MockMediaTypeFormatter();\n            List<MediaTypeFormatter> formatters = new List<MediaTypeFormatter>() { formatter1, formatter2 };\n            MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection(formatters);\n\n            // Act\n            mutation(collection);\n            MediaTypeFormatter[] expectedFormatters = collection.ToArray();\n            MediaTypeFormatter[] writableFormatters = collection.WritingFormatters;\n\n            // Assert\n            Assert.Equal(expectedFormatters, writableFormatters);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/MediaTypeFormatterExtensionsTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http.Formatting.Mocks;\nusing System.Net.Http.Headers;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Formatting\n{\n    public class MediaTypeFormatterExtensionsTests\n    {\n        [Fact]\n        public void TypeIsCorrect()\n        {\n            Assert.Type.HasProperties(typeof(MediaTypeFormatterExtensions), TypeAssert.TypeProperties.IsPublicVisibleClass | TypeAssert.TypeProperties.IsStatic);\n        }\n\n        [Fact]\n        public void AddQueryStringMappingThrowsWithNullThis()\n        {\n            MediaTypeFormatter formatter = null;\n            Assert.ThrowsArgumentNull(() => formatter.AddQueryStringMapping(\"name\", \"value\", new MediaTypeHeaderValue(\"application/xml\")), \"formatter\");\n        }\n\n        [Fact]\n        public void AddQueryStringMapping1ThrowsWithNullThis()\n        {\n            MediaTypeFormatter formatter = null;\n            Assert.ThrowsArgumentNull(() => formatter.AddQueryStringMapping(\"name\", \"value\", \"application/xml\"), \"formatter\");\n        }\n\n        [Fact]\n        public void AddRequestHeaderMappingThrowsWithNullThis()\n        {\n            MediaTypeFormatter formatter = null;\n            Assert.ThrowsArgumentNull(() => formatter.AddRequestHeaderMapping(\"name\", \"value\", StringComparison.CurrentCulture, true, new MediaTypeHeaderValue(\"application/xml\")), \"formatter\");\n        }\n\n        [Fact]\n        public void AddRequestHeaderMappingAddsSuccessfully()\n        {\n            MediaTypeFormatter formatter = new MockMediaTypeFormatter();\n            Assert.Empty(formatter.MediaTypeMappings);\n            formatter.AddRequestHeaderMapping(\"name\", \"value\", StringComparison.CurrentCulture, true, new MediaTypeHeaderValue(\"application/xml\"));\n            IEnumerable<RequestHeaderMapping> mappings = formatter.MediaTypeMappings.OfType<RequestHeaderMapping>();\n            RequestHeaderMapping mapping = Assert.Single(mappings);\n            Assert.Equal(\"name\", mapping.HeaderName);\n            Assert.Equal(\"value\", mapping.HeaderValue);\n            Assert.Equal(StringComparison.CurrentCulture, mapping.HeaderValueComparison);\n            Assert.True(mapping.IsValueSubstring);\n            Assert.Equal(new MediaTypeHeaderValue(\"application/xml\"), mapping.MediaType);\n        }\n\n        [Fact]\n        public void AddRequestHeaderMapping1ThrowsWithNullThis()\n        {\n            MediaTypeFormatter formatter = null;\n            Assert.ThrowsArgumentNull(() => formatter.AddRequestHeaderMapping(\"name\", \"value\", StringComparison.CurrentCulture, true, \"application/xml\"), \"formatter\");\n        }\n\n        [Fact]\n        public void AddRequestHeaderMapping1AddsSuccessfully()\n        {\n            MediaTypeFormatter formatter = new MockMediaTypeFormatter();\n            Assert.Empty(formatter.MediaTypeMappings);\n            formatter.AddRequestHeaderMapping(\"name\", \"value\", StringComparison.CurrentCulture, true, \"application/xml\");\n            IEnumerable<RequestHeaderMapping> mappings = formatter.MediaTypeMappings.OfType<RequestHeaderMapping>();\n            RequestHeaderMapping mapping = Assert.Single(mappings);\n            Assert.Equal(\"name\", mapping.HeaderName);\n            Assert.Equal(\"value\", mapping.HeaderValue);\n            Assert.Equal(StringComparison.CurrentCulture, mapping.HeaderValueComparison);\n            Assert.True(mapping.IsValueSubstring);\n            Assert.Equal(new MediaTypeHeaderValue(\"application/xml\"), mapping.MediaType);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/MediaTypeFormatterMatchTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Formatting.Mocks;\nusing System.Net.Http.Headers;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Formatting\n{\n    public class MediaTypeFormatterMatchTest\n    {\n        [Fact]\n        public void Ctor_ThrowsOnNullFormatter()\n        {\n            Assert.ThrowsArgumentNull(() => new MediaTypeFormatterMatch(null, null, null, MediaTypeFormatterMatchRanking.None), \"formatter\");\n        }\n\n        [Fact]\n        public void Ctor_ClonesMediaType()\n        {\n            // Arrange\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();\n            MediaTypeHeaderValue mediaType = MediaTypeHeaderValue.Parse(\"text/test\");\n\n            // Act\n            MediaTypeFormatterMatch match = new MediaTypeFormatterMatch(formatter, mediaType, null, MediaTypeFormatterMatchRanking.MatchOnCanWriteType);\n\n            // Assert\n            Assert.Equal(mediaType, match.MediaType);\n            Assert.NotSame(mediaType, match.MediaType);\n        }\n\n        [Fact]\n        public void Ctor_InitializesDefaultValues()\n        {\n            // Arrange\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();\n\n            // Act\n            MediaTypeFormatterMatch match = new MediaTypeFormatterMatch(formatter, null, null, MediaTypeFormatterMatchRanking.MatchOnCanWriteType);\n\n            // Assert\n            Assert.Same(formatter, match.Formatter);\n            Assert.Equal(MediaTypeConstants.ApplicationOctetStreamMediaType, match.MediaType);\n            Assert.Equal(FormattingUtilities.Match, match.Quality);\n            Assert.Equal(MediaTypeFormatterMatchRanking.MatchOnCanWriteType, match.Ranking);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/MediaTypeFormatterTestBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Net.Http.Formatting.DataSets;\nusing System.Net.Http.Headers;\nusing System.Reflection;\nusing System.Runtime.Serialization;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Net.Http.Formatting\n{\n    /// <summary>\n    /// A test class for common <see cref=\"MediaTypeFormatter\"/> functionality across multiple implementations.\n    /// </summary>\n    /// <typeparam name=\"TFormatter\">The type of formatter under test.</typeparam>\n    public abstract class MediaTypeFormatterTestBase<TFormatter> where TFormatter : MediaTypeFormatter\n    {\n        protected MediaTypeFormatterTestBase()\n        {\n        }\n\n        // Test data variations of interest in round-trip tests.\n        public const TestDataVariations RoundTripDataVariations =\n            TestDataVariations.All | TestDataVariations.WithNull | TestDataVariations.AsClassMember;\n\n        public abstract IEnumerable<MediaTypeHeaderValue> ExpectedSupportedMediaTypes { get; }\n\n        public abstract IEnumerable<Encoding> ExpectedSupportedEncodings { get; }\n\n        /// <summary>\n        /// Byte representation of an <see cref=\"SampleType\"/> with value 42 using the default encoding\n        /// for this media type formatter.\n        /// </summary>\n        public abstract byte[] ExpectedSampleTypeByteRepresentation { get; }\n\n        [Fact]\n        public void TypeIsCorrect()\n        {\n            Assert.Type.HasProperties<TFormatter, MediaTypeFormatter>(TypeAssert.TypeProperties.IsPublicVisibleClass);\n        }\n\n        [Fact]\n        public void SupportedMediaTypes_HeaderValuesAreNotSharedBetweenInstances()\n        {\n            var formatter1 = CreateFormatter();\n            var formatter2 = CreateFormatter();\n\n            foreach (MediaTypeHeaderValue mediaType1 in formatter1.SupportedMediaTypes)\n            {\n                MediaTypeHeaderValue mediaType2 = formatter2.SupportedMediaTypes.Single(m => m.Equals(mediaType1));\n                Assert.NotSame(mediaType1, mediaType2);\n            }\n        }\n\n        [Fact]\n        public void SupportEncodings_ValuesAreNotSharedBetweenInstances()\n        {\n            var formatter1 = CreateFormatter();\n            var formatter2 = CreateFormatter();\n\n            foreach (Encoding mediaType1 in formatter1.SupportedEncodings)\n            {\n                Encoding mediaType2 = formatter2.SupportedEncodings.Single(m => m.Equals(mediaType1));\n                Assert.NotSame(mediaType1, mediaType2);\n            }\n        }\n\n        [Fact]\n        public void SupportMediaTypes_DefaultSupportedMediaTypes()\n        {\n            TFormatter formatter = CreateFormatter();\n            Assert.True(ExpectedSupportedMediaTypes.SequenceEqual(formatter.SupportedMediaTypes));\n        }\n\n        [Fact]\n        public void SupportEncoding_DefaultSupportedEncodings()\n        {\n            TFormatter formatter = CreateFormatter();\n            Assert.True(ExpectedSupportedEncodings.SequenceEqual(formatter.SupportedEncodings));\n        }\n\n        [Fact]\n        public void ReadFromStreamAsync_ThrowsOnNull()\n        {\n            TFormatter formatter = CreateFormatter();\n            Assert.ThrowsArgumentNull(() => { formatter.ReadFromStreamAsync(null, Stream.Null, null, null); }, \"type\");\n            Assert.ThrowsArgumentNull(() => { formatter.ReadFromStreamAsync(typeof(object), null, null, null); }, \"readStream\");\n        }\n\n        [Fact]\n        public async Task ReadFromStreamAsync_WhenContentLengthIsZero_DoesNotReadStream()\n        {\n            // Arrange\n            TFormatter formatter = CreateFormatter();\n            Mock<Stream> mockStream = new Mock<Stream>();\n            IFormatterLogger mockFormatterLogger = new Mock<IFormatterLogger>().Object;\n            HttpContent content = new StringContent(String.Empty);\n            HttpContentHeaders contentHeaders = content.Headers;\n            contentHeaders.ContentLength = 0;\n\n            // Act\n            await formatter.ReadFromStreamAsync(typeof(SampleType), mockStream.Object, content, mockFormatterLogger);\n\n            // Assert\n            mockStream.Verify(s => s.Read(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>()), Times.Never());\n            mockStream.Verify(s => s.ReadByte(), Times.Never());\n            mockStream.Verify(s => s.BeginRead(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<AsyncCallback>(), It.IsAny<object>()), Times.Never());\n        }\n\n        [Fact]\n        public async Task ReadFromStreamAsync_WhenContentLengthIsZero_DoesNotCloseStream()\n        {\n            // Arrange\n            TFormatter formatter = CreateFormatter();\n            Mock<Stream> mockStream = new Mock<Stream>();\n            IFormatterLogger mockFormatterLogger = new Mock<IFormatterLogger>().Object;\n            HttpContent content = new StringContent(String.Empty);\n            HttpContentHeaders contentHeaders = content.Headers;\n            contentHeaders.ContentLength = 0;\n\n            // Act\n            await formatter.ReadFromStreamAsync(typeof(SampleType), mockStream.Object, content, mockFormatterLogger);\n\n            // Assert\n            mockStream.Verify(s => s.Close(), Times.Never());\n        }\n\n        [Theory]\n        [InlineData(false)]\n        [InlineData(0)]\n        [InlineData(\"\")]\n        public async Task ReadFromStreamAsync_WhenContentLengthIsZero_ReturnsDefaultTypeValue<T>(T value)\n        {\n            // Arrange\n            GC.KeepAlive(value); // Mark parameter as used. See xUnit1026, [Theory] method doesn't use all parameters.\n            TFormatter formatter = CreateFormatter();\n            HttpContent content = new StringContent(\"\");\n\n            // Act\n            var contentStream = await content.ReadAsStreamAsync();\n            var result = await formatter.ReadFromStreamAsync(typeof(T), contentStream, content, null);\n\n            // Assert\n            Assert.Equal(default(T), (T)result);\n        }\n\n        [Fact]\n        public virtual async Task ReadFromStreamAsync_ReadsDataButDoesNotCloseStream()\n        {\n            // Arrange\n            TFormatter formatter = CreateFormatter();\n            MemoryStream memStream = new MemoryStream(ExpectedSampleTypeByteRepresentation);\n            HttpContent content = new StringContent(String.Empty);\n            HttpContentHeaders contentHeaders = content.Headers;\n            contentHeaders.ContentLength = memStream.Length;\n            contentHeaders.ContentType = CreateSupportedMediaType();\n\n            // Act\n            var result = await formatter.ReadFromStreamAsync(typeof(SampleType), memStream, content, null);\n\n            // Assert\n            Assert.True(memStream.CanRead);\n\n            var value = Assert.IsType<SampleType>(result);\n            Assert.Equal(42, value.Number);\n        }\n\n        [Fact]\n        public virtual async Task ReadFromStreamAsync_WhenContentLengthIsNull_ReadsDataButDoesNotCloseStream()\n        {\n            // Arrange\n            TFormatter formatter = CreateFormatter();\n            MemoryStream memStream = new MemoryStream(ExpectedSampleTypeByteRepresentation);\n            HttpContent content = new StringContent(String.Empty);\n            HttpContentHeaders contentHeaders = content.Headers;\n            contentHeaders.ContentLength = null;\n            contentHeaders.ContentType = CreateSupportedMediaType();\n\n            // Act\n            var result = await formatter.ReadFromStreamAsync(typeof(SampleType), memStream, content, null);\n\n            // Assert\n            Assert.True(memStream.CanRead);\n\n            var value = Assert.IsType<SampleType>(result);\n            Assert.Equal(42, value.Number);\n        }\n\n        [Fact]\n        public void WriteToStreamAsync_ThrowsOnNull()\n        {\n            TFormatter formatter = CreateFormatter();\n            Assert.ThrowsArgumentNull(() => { formatter.WriteToStreamAsync(null, new object(), Stream.Null, null, null); }, \"type\");\n            Assert.ThrowsArgumentNull(() => { formatter.WriteToStreamAsync(typeof(object), new object(), null, null, null); }, \"writeStream\");\n        }\n\n        [Fact]\n        public virtual async Task WriteToStreamAsync_WhenObjectIsNull_WritesDataButDoesNotCloseStream()\n        {\n            // Arrange\n            TFormatter formatter = CreateFormatter();\n            Mock<Stream> mockStream = new Mock<Stream>();\n            mockStream.Setup(s => s.CanWrite).Returns(true);\n            HttpContent content = new StringContent(String.Empty);\n\n            // Act\n            await formatter.WriteToStreamAsync(typeof(SampleType), null, mockStream.Object, content, null);\n\n            // Assert\n            mockStream.Verify(s => s.Close(), Times.Never());\n            mockStream.Verify(s => s.BeginWrite(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<AsyncCallback>(), It.IsAny<object>()), Times.Never());\n        }\n\n        [Fact]\n        public virtual async Task WriteToStreamAsync_WritesDataButDoesNotCloseStream()\n        {\n            // Arrange\n            TFormatter formatter = CreateFormatter();\n            SampleType sampleType = new SampleType { Number = 42 };\n            MemoryStream memStream = new MemoryStream();\n            HttpContent content = new StringContent(String.Empty);\n            content.Headers.ContentType = CreateSupportedMediaType();\n\n            // Act\n            await formatter.WriteToStreamAsync(typeof(SampleType), sampleType, memStream, content, null);\n\n            // Assert\n            Assert.True(memStream.CanRead);\n\n            byte[] actualSampleTypeByteRepresentation = memStream.ToArray();\n            Assert.NotEmpty(actualSampleTypeByteRepresentation);\n        }\n\n        [Fact]\n        public virtual async Task Overridden_WriteToStreamAsyncWithoutCancellationToken_GetsCalled()\n        {\n            // Arrange\n            Stream stream = new MemoryStream();\n            Mock<TFormatter> formatter = CreateMockFormatter();\n            ObjectContent<int> content = new ObjectContent<int>(42, formatter.Object);\n\n            formatter\n                .Setup(f => f.WriteToStreamAsync(typeof(int), 42, stream, content, null /* transportContext */))\n                .Returns(TaskHelpers.Completed())\n                .Verifiable();\n\n            // Act\n            await content.CopyToAsync(stream);\n\n            // Assert\n            formatter.Verify();\n        }\n\n        [Fact]\n        public virtual async Task Overridden_WriteToStreamAsyncWithCancellationToken_GetsCalled()\n        {\n            // Arrange\n            Stream stream = new MemoryStream();\n            Mock<TFormatter> formatter = CreateMockFormatter();\n            ObjectContent<int> content = new ObjectContent<int>(42, formatter.Object);\n\n            formatter\n                .Setup(f => f.WriteToStreamAsync(typeof(int), 42, stream, content, null /* transportContext */, CancellationToken.None))\n                .Returns(TaskHelpers.Completed())\n                .Verifiable();\n\n            // Act\n            await content.CopyToAsync(stream);\n\n            // Assert\n            formatter.Verify();\n        }\n\n        [Fact]\n        public virtual async Task Overridden_ReadFromStreamAsyncWithoutCancellationToken_GetsCalled()\n        {\n            // Arrange\n            Stream stream = new MemoryStream();\n            Mock<TFormatter> formatter = CreateMockFormatter();\n            formatter.Object.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(\"application/test\"));\n            StringContent content = new StringContent(\" \", Encoding.Default, \"application/test\");\n            CancellationTokenSource cts = new CancellationTokenSource();\n\n            formatter\n                .Setup(f => f.ReadFromStreamAsync(typeof(string), It.IsAny<Stream>(), content, null /*formatterLogger */))\n                .Returns(Task.FromResult<object>(null))\n                .Verifiable();\n\n            // Act\n            await content.ReadAsAsync<string>(new[] { formatter.Object }, cts.Token);\n\n            // Assert\n            formatter.Verify();\n        }\n\n        [Fact]\n        public virtual async Task Overridden_ReadFromStreamAsyncWithCancellationToken_GetsCalled()\n        {\n            // Arrange\n            Stream stream = new MemoryStream();\n            Mock<TFormatter> formatter = CreateMockFormatter();\n            formatter.Object.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(\"application/test\"));\n            StringContent content = new StringContent(\" \", Encoding.Default, \"application/test\");\n            CancellationTokenSource cts = new CancellationTokenSource();\n\n            formatter\n                .Setup(f => f.ReadFromStreamAsync(typeof(string), It.IsAny<Stream>(), content, null /*formatterLogger */, cts.Token))\n                .Returns(Task.FromResult<object>(null))\n                .Verifiable();\n\n            // Act\n            await content.ReadAsAsync<string>(new[] { formatter.Object }, cts.Token);\n\n            // Assert\n            formatter.Verify();\n        }\n\n        // Remove this suppression once we pick up an xunit.analyzers package containing the xnuit/xunit#1466 fix.\n#pragma warning disable xUnit1013 // Public method should be marked as test\n        [Theory]\n        [TestDataSet(typeof(HttpTestData), \"ReadAndWriteCorrectCharacterEncoding\")]\n        public abstract Task ReadFromStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding);\n\n        [Theory]\n        [TestDataSet(typeof(HttpTestData), \"ReadAndWriteCorrectCharacterEncoding\")]\n        public abstract Task WriteToStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding);\n#pragma warning restore xUnit1013 // Public method should be marked as test\n\n        protected virtual TFormatter CreateFormatter()\n        {\n            ConstructorInfo constructor = typeof(TFormatter).GetConstructor(Type.EmptyTypes);\n            return (TFormatter)constructor.Invoke(null);\n        }\n\n        protected virtual Mock<TFormatter> CreateMockFormatter()\n        {\n            return new Mock<TFormatter>() { CallBase = true };\n        }\n\n        protected virtual MediaTypeHeaderValue CreateSupportedMediaType()\n        {\n            return ExpectedSupportedMediaTypes.First();\n        }\n\n        public async Task<object> ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(MediaTypeFormatter formatter, Type variationType, object testData)\n        {\n            // Arrange\n            HttpContent content = new StringContent(String.Empty);\n            HttpContentHeaders contentHeaders = content.Headers;\n            object readObj = null;\n\n            // Act & Assert\n            await Assert.Stream.WriteAndReadAsync(\n                async stream =>\n                {\n                    await Assert.Task.SucceedsAsync(formatter.WriteToStreamAsync(variationType, testData, stream, content, transportContext: null));\n                    contentHeaders.ContentLength = stream.Length;\n                },\n                async stream => readObj = await Assert.Task.SucceedsWithResultAsync(formatter.ReadFromStreamAsync(variationType, stream, content, formatterLogger: null)));\n\n            return readObj;\n        }\n\n        protected async Task ReadFromStreamAsync_UsesCorrectCharacterEncodingHelper(MediaTypeFormatter formatter, string content, string formattedContent, string mediaType, string encoding, bool isDefaultEncoding)\n        {\n            // Arrange\n            Encoding enc = null;\n            if (isDefaultEncoding)\n            {\n                enc = formatter.SupportedEncodings.First((e) => e.WebName.Equals(encoding, StringComparison.OrdinalIgnoreCase));\n            }\n            else\n            {\n                enc = Encoding.GetEncoding(encoding);\n                formatter.SupportedEncodings.Add(enc);\n            }\n\n            byte[] data = enc.GetBytes(formattedContent);\n            MemoryStream memStream = new MemoryStream(data);\n\n            StringContent dummyContent = new StringContent(string.Empty);\n            HttpContentHeaders headers = dummyContent.Headers;\n            headers.Clear();\n            headers.ContentType = MediaTypeHeaderValue.Parse(mediaType);\n            headers.ContentLength = data.Length;\n\n            IFormatterLogger mockFormatterLogger = new Mock<IFormatterLogger>().Object;\n\n            // Act\n            string result = (await formatter.ReadFromStreamAsync(typeof(string), memStream, dummyContent, mockFormatterLogger)) as string;\n\n            // Assert\n            Assert.Equal(content, result);\n        }\n\n        protected async Task WriteToStreamAsync_UsesCorrectCharacterEncodingHelper(MediaTypeFormatter formatter, string content, string formattedContent, string mediaType, string encoding, bool isDefaultEncoding)\n        {\n            // Arrange\n            Encoding enc = null;\n            if (isDefaultEncoding)\n            {\n                enc = formatter.SupportedEncodings.First((e) => e.WebName.Equals(encoding, StringComparison.OrdinalIgnoreCase));\n            }\n            else\n            {\n                enc = Encoding.GetEncoding(encoding);\n                formatter.SupportedEncodings.Add(enc);\n            }\n\n            byte[] preamble = enc.GetPreamble();\n            byte[] data = enc.GetBytes(formattedContent);\n            byte[] expectedData = new byte[preamble.Length + data.Length];\n            Buffer.BlockCopy(preamble, 0, expectedData, 0, preamble.Length);\n            Buffer.BlockCopy(data, 0, expectedData, preamble.Length, data.Length);\n\n            MemoryStream memStream = new MemoryStream();\n\n            HttpContent httpContent = new StringContent(String.Empty);\n            HttpContentHeaders contentHeaders = httpContent.Headers;\n            contentHeaders.Clear();\n            contentHeaders.ContentType = MediaTypeHeaderValue.Parse(mediaType);\n            contentHeaders.ContentLength = expectedData.Length;\n\n            IFormatterLogger mockFormatterLogger = new Mock<IFormatterLogger>().Object;\n\n            // Act\n            await formatter.WriteToStreamAsync(typeof(string), content, memStream, httpContent, null);\n\n            // Assert\n            byte[] actualData = memStream.ToArray();\n            Assert.Equal(expectedData, actualData);\n        }\n\n        public static Encoding CreateOrGetSupportedEncoding(MediaTypeFormatter formatter, string encoding, bool isDefaultEncoding)\n        {\n            Encoding enc = null;\n            if (isDefaultEncoding)\n            {\n                enc = formatter.SupportedEncodings.First((e) => e.WebName.Equals(encoding, StringComparison.OrdinalIgnoreCase));\n            }\n            else\n            {\n                enc = Encoding.GetEncoding(encoding);\n                formatter.SupportedEncodings.Add(enc);\n            }\n\n            return enc;\n        }\n\n        protected static Task ReadContentUsingCorrectCharacterEncodingHelperAsync(MediaTypeFormatter formatter, string content, string formattedContent, string mediaType, string encoding, bool isDefaultEncoding)\n        {\n            // Arrange\n            Encoding enc = CreateOrGetSupportedEncoding(formatter, encoding, isDefaultEncoding);\n            byte[] sourceData = enc.GetBytes(formattedContent);\n\n            // Further Arrange, Act & Assert\n            return ReadContentUsingCorrectCharacterEncodingHelperAsync(formatter, content, sourceData, mediaType);\n        }\n\n        protected static async Task ReadContentUsingCorrectCharacterEncodingHelperAsync(MediaTypeFormatter formatter, string content, byte[] sourceData, string mediaType)\n        {\n            // Arrange\n            MemoryStream memStream = new MemoryStream(sourceData);\n\n            StringContent dummyContent = new StringContent(string.Empty);\n            HttpContentHeaders headers = dummyContent.Headers;\n            headers.Clear();\n            headers.ContentType = MediaTypeHeaderValue.Parse(mediaType);\n            headers.ContentLength = sourceData.Length;\n\n            IFormatterLogger mockFormatterLogger = new Mock<IFormatterLogger>().Object;\n\n            // Act\n            var result = (await formatter.ReadFromStreamAsync(typeof(string), memStream, dummyContent, mockFormatterLogger)) as string;\n\n            // Assert\n            Assert.Equal(content, result);\n        }\n\n        protected static Task WriteContentUsingCorrectCharacterEncodingHelperAsync(MediaTypeFormatter formatter, string content, string formattedContent, string mediaType, string encoding, bool isDefaultEncoding)\n        {\n            // Arrange\n            Encoding enc = CreateOrGetSupportedEncoding(formatter, encoding, isDefaultEncoding);\n\n            byte[] preamble = enc.GetPreamble();\n            byte[] data = enc.GetBytes(formattedContent);\n            byte[] expectedData = new byte[preamble.Length + data.Length];\n            Buffer.BlockCopy(preamble, 0, expectedData, 0, preamble.Length);\n            Buffer.BlockCopy(data, 0, expectedData, preamble.Length, data.Length);\n\n            // Further Arrange, Act & Assert\n            return WriteContentUsingCorrectCharacterEncodingHelperAsync(formatter, content, expectedData, mediaType);\n        }\n\n\n        protected static async Task WriteContentUsingCorrectCharacterEncodingHelperAsync(MediaTypeFormatter formatter, string content, byte[] expectedData, string mediaType)\n        {\n            // Arrange\n            MemoryStream memStream = new MemoryStream();\n\n            StringContent dummyContent = new StringContent(string.Empty);\n            HttpContentHeaders headers = dummyContent.Headers;\n            headers.Clear();\n            headers.ContentType = MediaTypeHeaderValue.Parse(mediaType);\n            headers.ContentLength = expectedData.Length;\n\n            IFormatterLogger mockFormatterLogger = new Mock<IFormatterLogger>().Object;\n\n            // Act\n            await formatter.WriteToStreamAsync(typeof(string), content, memStream, dummyContent, null);\n\n            // Assert\n            byte[] actualData = memStream.ToArray();\n\n            Assert.Equal(expectedData, actualData);\n        }\n    }\n\n    [DataContract(Name = \"DataContractSampleType\")]\n    public class SampleType\n    {\n        [DataMember]\n        public int Number { get; set; }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/MediaTypeFormatterTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.IO;\nusing System.Linq;\nusing System.Net.Http.Formatting.DataSets;\nusing System.Net.Http.Formatting.Mocks;\nusing System.Net.Http.Headers;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Net.Http.Formatting\n{\n    [Xunit.Collection(\"MediaTypeFormatterTests\")] // Isolate MaxCollectionKeySize_RoundTrips.\n    [Xunit.CollectionDefinition(\"MediaTypeFormatterTests\", DisableParallelization = true)]\n    public class MediaTypeFormatterTests\n    {\n        private const string TestMediaType = \"text/test\";\n        private MediaTypeHeaderValue TestMediaTypeHeader = new MediaTypeHeaderValue(TestMediaType);\n\n        public static TheoryDataSet<string, string[], string> SelectCharacterEncodingTestData\n        {\n            get\n            {\n                // string bodyEncoding, string[] supportedEncodings, string expectedEncoding\n                return new TheoryDataSet<string, string[], string>\n                {\n                    { null, new string[] { \"utf-8\", \"utf-16\"}, \"utf-8\" },\n                    { null, new string[] { \"utf-16\", \"utf-8\"}, \"utf-16\"},\n                    { \"utf-32\", new string[] { \"utf-8\", \"utf-16\"}, \"utf-8\" },\n                    { \"utf-32\", new string[] { \"utf-8\", \"utf-16\", \"utf-32\"}, \"utf-32\"}\n                };\n            }\n        }\n\n        [Fact]\n        public void TypeIsCorrect()\n        {\n            Assert.Type.HasProperties(typeof(MediaTypeFormatter), TypeAssert.TypeProperties.IsPublicVisibleClass | TypeAssert.TypeProperties.IsAbstract);\n        }\n\n        [Fact]\n        public void Constructor()\n        {\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();\n            Collection<MediaTypeHeaderValue> supportedMediaTypes = formatter.SupportedMediaTypes;\n            Assert.NotNull(supportedMediaTypes);\n            Assert.Empty(supportedMediaTypes);\n            Collection<MediaTypeMapping> mappings = formatter.MediaTypeMappings;\n\n            Assert.NotNull(mappings);\n            Assert.Empty(mappings);\n        }\n\n        [Fact]\n        void CopyConstructor()\n        {\n            TestMediaTypeFormatter formatter = new TestMediaTypeFormatter();\n            TestMediaTypeFormatter derivedFormatter = new TestMediaTypeFormatter(formatter);\n\n            Assert.Same(formatter.MediaTypeMappings, derivedFormatter.MediaTypeMappings);\n            Assert.Same(formatter.MediaTypeMappingsInternal, derivedFormatter.MediaTypeMappingsInternal);\n            Assert.Equal(formatter.RequiredMemberSelector, derivedFormatter.RequiredMemberSelector);\n\n            Assert.Same(formatter.SupportedMediaTypes, derivedFormatter.SupportedMediaTypes);\n            Assert.Same(formatter.SupportedMediaTypesInternal, derivedFormatter.SupportedMediaTypesInternal);\n\n            Assert.Same(formatter.SupportedEncodings, derivedFormatter.SupportedEncodings);\n            Assert.Same(formatter.SupportedEncodingsInternal, derivedFormatter.SupportedEncodingsInternal);\n        }\n\n        [Fact]\n        public void MaxCollectionKeySize_RoundTrips()\n        {\n            var defaultMaxKeys = MediaTypeFormatter.MaxHttpCollectionKeys;\n            try\n            {\n                Assert.Reflection.IntegerProperty<MediaTypeFormatter, int>(\n                    null,\n                    c => MediaTypeFormatter.MaxHttpCollectionKeys,\n                    expectedDefaultValue: PlatformInfo.Platform == Platform.Net40 ? 1000 : Int32.MaxValue,\n                    minLegalValue: 1,\n                    illegalLowerValue: 0,\n                    maxLegalValue: null,\n                    illegalUpperValue: null,\n                    roundTripTestValue: 125);\n            }\n            finally\n            {\n                MediaTypeFormatter.MaxHttpCollectionKeys = defaultMaxKeys;\n            }\n        }\n\n        [Fact]\n        public void SupportedMediaTypes_IsMutable()\n        {\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();\n            Collection<MediaTypeHeaderValue> supportedMediaTypes = formatter.SupportedMediaTypes;\n            MediaTypeHeaderValue[] mediaTypes = HttpTestData.LegalMediaTypeHeaderValues.ToArray();\n            foreach (MediaTypeHeaderValue mediaType in mediaTypes)\n            {\n                supportedMediaTypes.Add(mediaType);\n            }\n\n            Assert.True(mediaTypes.SequenceEqual(formatter.SupportedMediaTypes));\n        }\n\n        [Fact]\n        public void SupportedMediaTypes_AddThrowsWithNullMediaType()\n        {\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();\n            Collection<MediaTypeHeaderValue> supportedMediaTypes = formatter.SupportedMediaTypes;\n\n            Assert.ThrowsArgumentNull(() => supportedMediaTypes.Add(null), \"item\");\n        }\n\n        [Theory]\n        [TestDataSet(typeof(HttpTestData), \"LegalMediaRangeValues\")]\n        public void SupportedMediaTypes_AddThrowsWithMediaRange(MediaTypeHeaderValue mediaType)\n        {\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();\n            Collection<MediaTypeHeaderValue> supportedMediaTypes = formatter.SupportedMediaTypes;\n            Assert.ThrowsArgument(() => supportedMediaTypes.Add(mediaType), \"item\", Error.Format(Properties.Resources.CannotUseMediaRangeForSupportedMediaType, typeof(MediaTypeHeaderValue).Name, mediaType.MediaType));\n        }\n\n        [Fact]\n        public void SupportedMediaTypes_InsertThrowsWithNullMediaType()\n        {\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();\n            Collection<MediaTypeHeaderValue> supportedMediaTypes = formatter.SupportedMediaTypes;\n\n            Assert.ThrowsArgumentNull(() => supportedMediaTypes.Insert(0, null), \"item\");\n        }\n\n        [Theory]\n        [TestDataSet(typeof(HttpTestData), \"LegalMediaRangeValues\")]\n        public void SupportedMediaTypes_InsertThrowsWithMediaRange(MediaTypeHeaderValue mediaType)\n        {\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();\n            Collection<MediaTypeHeaderValue> supportedMediaTypes = formatter.SupportedMediaTypes;\n\n            Assert.ThrowsArgument(() => supportedMediaTypes.Insert(0, mediaType), \"item\", Error.Format(Properties.Resources.CannotUseMediaRangeForSupportedMediaType, typeof(MediaTypeHeaderValue).Name, mediaType.MediaType));\n        }\n\n        [Fact]\n        public void MediaTypeMappings_IsMutable()\n        {\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();\n            Collection<MediaTypeMapping> mappings = formatter.MediaTypeMappings;\n            MediaTypeMapping[] standardMappings = HttpTestData.StandardMediaTypeMappings.ToArray();\n            foreach (MediaTypeMapping mapping in standardMappings)\n            {\n                mappings.Add(mapping);\n            }\n\n            Assert.True(standardMappings.SequenceEqual(formatter.MediaTypeMappings));\n        }\n\n        [Fact]\n        public void SelectCharacterEncoding_ThrowsIfNoSupportedEncodings()\n        {\n            // Arrange\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter { CallBase = true };\n            HttpContent content = new StringContent(\"Hello World\", Encoding.UTF8, \"text/plain\");\n\n            // Act\n            Assert.Throws<InvalidOperationException>(() => formatter.SelectCharacterEncoding(content.Headers));\n        }\n\n        [Theory]\n        [PropertyData(\"SelectCharacterEncodingTestData\")]\n        public void SelectCharacterEncoding_ReturnsBestEncoding(string bodyEncoding, string[] supportedEncodings, string expectedEncoding)\n        {\n            // Arrange\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter { CallBase = true };\n\n            foreach (string supportedEncoding in supportedEncodings)\n            {\n                formatter.SupportedEncodings.Add(Encoding.GetEncoding(supportedEncoding));\n            }\n\n            HttpContentHeaders contentHeaders = null;\n            if (bodyEncoding != null)\n            {\n                Encoding bodyEnc = Encoding.GetEncoding(bodyEncoding);\n                HttpContent content = new StringContent(\"Hello World\", bodyEnc, \"text/plain\");\n                contentHeaders = content.Headers;\n            }\n\n            // Act\n            Encoding actualEncoding = formatter.SelectCharacterEncoding(contentHeaders);\n\n            // Assert\n            Encoding expectedEnc = expectedEncoding != null ? Encoding.GetEncoding(expectedEncoding) : null;\n            Assert.Equal(expectedEnc, actualEncoding);\n        }\n\n        [Fact]\n        public void ReadFromStreamAsync_ThrowsNotSupportedException()\n        {\n            var formatter = new Mock<MediaTypeFormatter> { CallBase = true }.Object;\n\n            Assert.Throws<NotSupportedException>(() => formatter.ReadFromStreamAsync(null, null, null, null),\n                \"The media type formatter of type 'MediaTypeFormatterProxy' does not support reading because it does not implement the ReadFromStreamAsync method.\");\n        }\n\n        [Fact]\n        public void WriteToStreamAsync_ThrowsNotSupportedException()\n        {\n            var formatter = new Mock<MediaTypeFormatter> { CallBase = true }.Object;\n\n            Assert.Throws<NotSupportedException>(() => formatter.WriteToStreamAsync(null, null, null, null, null),\n                \"The media type formatter of type 'MediaTypeFormatterProxy' does not support writing because it does not implement the WriteToStreamAsync method.\");\n        }\n\n        [Theory]\n        [InlineData(typeof(object))]\n        [InlineData(typeof(string))]\n        [InlineData(typeof(Nullable<int>))]\n        public void GetDefaultValueForType_ReturnsNullForReferenceTypes(Type referenceType)\n        {\n            Assert.Null(MediaTypeFormatter.GetDefaultValueForType(referenceType));\n        }\n\n        [Theory]\n        [InlineData(false)]\n        [InlineData(0)]\n        [InlineData('a')]\n        public void GetDefaultValueForType_ReturnsValueForValueTypes<T>(T value)\n        {\n            Type valueType = value.GetType();\n            T defaultValue = default(T);\n            Assert.Equal(defaultValue, MediaTypeFormatter.GetDefaultValueForType(valueType));\n        }\n\n        [Fact]\n        public void GetDefaultValueForType_ReturnsValueForStruct()\n        {\n            TestStruct s = new TestStruct();\n\n            TestStruct result = (TestStruct)MediaTypeFormatter.GetDefaultValueForType(typeof(TestStruct));\n\n            Assert.Equal(s, result);\n        }\n\n        [Fact]\n        public void SetDefaultContentHeaders_ThrowsOnNullType()\n        {\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();\n            HttpContentHeaders contentHeaders = FormattingUtilities.CreateEmptyContentHeaders();\n            Assert.ThrowsArgumentNull(() => formatter.SetDefaultContentHeaders(null, contentHeaders, TestMediaTypeHeader), \"type\");\n        }\n\n        [Fact]\n        public void SetDefaultContentHeaders_ThrowsOnNullHeaders()\n        {\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();\n            Type type = typeof(object);\n            Assert.ThrowsArgumentNull(() => formatter.SetDefaultContentHeaders(type, null, TestMediaTypeHeader), \"headers\");\n        }\n\n        [Fact]\n        public void SetDefaultContentHeaders_UsesNonNullMediaTypeClone()\n        {\n            // Arrange\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();\n            Type type = typeof(object);\n            HttpContentHeaders contentHeaders = FormattingUtilities.CreateEmptyContentHeaders();\n\n            // Act\n            formatter.SetDefaultContentHeaders(type, contentHeaders, TestMediaTypeHeader);\n\n            // Assert\n            Assert.NotSame(TestMediaTypeHeader, contentHeaders.ContentType);\n            Assert.Equal(TestMediaType, contentHeaders.ContentType.MediaType);\n        }\n\n        [Fact]\n        public void SetDefaultContentHeaders_UsesDefaultSupportedMediaTypeClone()\n        {\n            // Arrange\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();\n            formatter.SupportedMediaTypes.Add(TestMediaTypeHeader);\n            Type type = typeof(object);\n            HttpContentHeaders contentHeaders = FormattingUtilities.CreateEmptyContentHeaders();\n\n            // Act\n            formatter.SetDefaultContentHeaders(type, contentHeaders, null);\n\n            // Assert\n            Assert.NotSame(TestMediaTypeHeader, contentHeaders.ContentType);\n            Assert.Equal(TestMediaType, contentHeaders.ContentType.MediaType);\n        }\n\n        [Fact]\n        public void SetDefaultContentHeaders_UsesDefaultSupportedEncoding()\n        {\n            // Arrange\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();\n            Encoding encoding = new UnicodeEncoding();\n            formatter.SupportedEncodings.Add(encoding);\n            Type type = typeof(object);\n            HttpContentHeaders contentHeaders = FormattingUtilities.CreateEmptyContentHeaders();\n\n            // Act\n            formatter.SetDefaultContentHeaders(type, contentHeaders, TestMediaTypeHeader);\n\n            // Assert\n            Assert.Equal(TestMediaType, contentHeaders.ContentType.MediaType);\n            Assert.Equal(encoding.WebName, contentHeaders.ContentType.CharSet);\n        }\n\n        [Fact]\n        public void SetDefaultContentHeaders_UsesDefaultSupportedMediaTypeAndEncoding()\n        {\n            // Arrange\n            MockMediaTypeFormatter formatter = new MockMediaTypeFormatter();\n            formatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue(TestMediaType));\n            Encoding encoding = new UnicodeEncoding();\n            formatter.SupportedEncodings.Add(encoding);\n            Type type = typeof(object);\n            HttpContentHeaders contentHeaders = FormattingUtilities.CreateEmptyContentHeaders();\n\n            // Act\n            formatter.SetDefaultContentHeaders(type, contentHeaders, null);\n\n            // Assert\n            Assert.Equal(TestMediaType, contentHeaders.ContentType.MediaType);\n            Assert.Equal(encoding.WebName, contentHeaders.ContentType.CharSet);\n        }\n\n        [Fact]\n        public async Task WriteToStreamAsyncWithCancellationToken_GetsCalled_DuringObjectContentWrite()\n        {\n            // Arrange\n            object value = new object();\n            Type type = typeof(object);\n            MemoryStream stream = new MemoryStream();\n            Mock<MediaTypeFormatter> formatter = new Mock<MediaTypeFormatter>{ CallBase = true };\n\n            formatter.Setup(f => f.CanWriteType(type)).Returns(true);\n            formatter\n                .Setup(f => f.WriteToStreamAsync(type, value, stream, It.IsAny<ObjectContent>(), null, CancellationToken.None))\n                .Returns(TaskHelpers.Completed())\n                .Verifiable();\n\n            ObjectContent content = new ObjectContent(type, value, formatter.Object);\n\n            // Act\n            await content.CopyToAsync(stream);\n\n            // Assert\n            formatter.Verify();\n        }\n\n        public struct TestStruct\n        {\n            private int I;\n            public TestStruct(int i)\n            {\n                I = i + 1;\n            }\n        }\n\n        private class TestMediaTypeFormatter : MediaTypeFormatter\n        {\n            public TestMediaTypeFormatter()\n            {\n            }\n\n            public TestMediaTypeFormatter(TestMediaTypeFormatter formatter)\n                : base(formatter)\n            {\n            }\n\n            public override bool CanReadType(Type type)\n            {\n                return true;\n            }\n\n            public override bool CanWriteType(Type type)\n            {\n                return true;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/MediaTypeHeaderValueExtensionsTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Headers;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Formatting\n{\n    public class MediaTypeHeaderValueExtensionsTests\n    {\n        public static TheoryDataSet<string, string, int> EqualValues\n        {\n            get\n            {\n                // These values are all equal\n                return new TheoryDataSet<string, string, int>\n                {\n                    { \"text/xml\", \"text/xml\", (int)MediaTypeHeaderValueRange.None },\n                    { \"text/xml\", \"TEXT/XML\", (int)MediaTypeHeaderValueRange.None },\n                    { \"text/xml; charset=utf-8\", \"text/xml; charset=utf-8\", (int)MediaTypeHeaderValueRange.None },\n                    { \"text/xml; parameter=value\", \"text/xml; parameter=value\", (int)MediaTypeHeaderValueRange.None },\n                    { \"text/xml; charset=utf-8; parameter=value\", \"text/xml; parameter=value; charset=utf-8\", (int)MediaTypeHeaderValueRange.None },\n\n                    { \"text/*\", \"text/*\", (int)MediaTypeHeaderValueRange.SubtypeMediaRange },\n                    { \"text/*\", \"TEXT/*\", (int)MediaTypeHeaderValueRange.SubtypeMediaRange },\n                    { \"text/*; charset=utf-8\", \"text/*; charset=utf-8\", (int)MediaTypeHeaderValueRange.SubtypeMediaRange },\n                    { \"text/*; parameter=value\", \"text/*; parameter=value\", (int)MediaTypeHeaderValueRange.SubtypeMediaRange },\n                    { \"text/*; charset=utf-8; parameter=value\", \"text/*; parameter=value; charset=utf-8\", (int)MediaTypeHeaderValueRange.SubtypeMediaRange },\n\n                    { \"*/*\", \"*/*\", (int)MediaTypeHeaderValueRange.AllMediaRange },\n                    { \"*/*; charset=utf-8\", \"*/*; charset=utf-8\", (int)MediaTypeHeaderValueRange.AllMediaRange },\n                    { \"*/*; parameter=value\", \"*/*; parameter=value\", (int)MediaTypeHeaderValueRange.AllMediaRange },\n                    { \"*/*; charset=utf-8; parameter=value\", \"*/*; parameter=value; charset=utf-8\", (int)MediaTypeHeaderValueRange.AllMediaRange },\n                };\n            }\n        }\n\n        public static TheoryDataSet<string, string, int> NonEqualValues\n        {\n            get\n            {\n                return new TheoryDataSet<string, string, int>\n                {\n                    // These values are all subsets. If compared in reverse they are all non-subsets.\n                    { \"text/xml\", \"text/xml; charset=utf-8\", (int)MediaTypeHeaderValueRange.None },\n                    { \"text/xml\", \"TEXT/XML; charset=utf-8\", (int)MediaTypeHeaderValueRange.None },\n                    { \"text/xml\", \"text/xml; parameter=value\", (int)MediaTypeHeaderValueRange.None },\n                    { \"text/xml; charset=utf-8\", \"text/xml; parameter=value; charset=utf-8\", (int)MediaTypeHeaderValueRange.None },\n\n                    { \"text/*\", \"text/*; charset=utf-8\", (int)MediaTypeHeaderValueRange.SubtypeMediaRange },\n                    { \"text/*\", \"TEXT/*; charset=utf-8\", (int)MediaTypeHeaderValueRange.SubtypeMediaRange },\n                    { \"text/*\", \"text/*; parameter=value\", (int)MediaTypeHeaderValueRange.SubtypeMediaRange },\n                    { \"text/*; charset=utf-8\", \"text/*; parameter=value; charset=utf-8\", (int)MediaTypeHeaderValueRange.SubtypeMediaRange },\n\n                    { \"text/xml\", \"text/*\", (int)MediaTypeHeaderValueRange.SubtypeMediaRange },\n                    { \"text/xml\", \"text/*; charset=utf-8\", (int)MediaTypeHeaderValueRange.SubtypeMediaRange },\n                    { \"text/xml\", \"TEXT/*; charset=utf-8\", (int)MediaTypeHeaderValueRange.SubtypeMediaRange },\n                    { \"text/xml\", \"text/*; parameter=value\", (int)MediaTypeHeaderValueRange.SubtypeMediaRange },\n                    { \"text/xml; charset=utf-8\", \"text/*; parameter=value; charset=utf-8\", (int)MediaTypeHeaderValueRange.SubtypeMediaRange },\n\n                    { \"*/*\", \"*/*; charset=utf-8\", (int)MediaTypeHeaderValueRange.AllMediaRange },\n                    { \"*/*\", \"*/*; parameter=value\", (int)MediaTypeHeaderValueRange.AllMediaRange },\n                    { \"*/*; charset=utf-8\", \"*/*; parameter=value; charset=utf-8\", (int)MediaTypeHeaderValueRange.AllMediaRange },\n\n                    { \"text/*\", \"*/*\", (int)MediaTypeHeaderValueRange.AllMediaRange },\n                    { \"text/*\", \"*/*; charset=utf-8\", (int)MediaTypeHeaderValueRange.AllMediaRange },\n                    { \"text/*\", \"*/*; parameter=value\", (int)MediaTypeHeaderValueRange.AllMediaRange },\n                    { \"text/*; charset=utf-8\", \"*/*; parameter=value; charset=utf-8\", (int)MediaTypeHeaderValueRange.AllMediaRange },\n\n                    { \"text/xml\", \"*/*\", (int)MediaTypeHeaderValueRange.AllMediaRange },\n                    { \"text/xml\", \"*/*; charset=utf-8\", (int)MediaTypeHeaderValueRange.AllMediaRange },\n                    { \"text/xml\", \"*/*; parameter=value\", (int)MediaTypeHeaderValueRange.AllMediaRange },\n                    { \"text/xml; charset=utf-8\", \"*/*; parameter=value; charset=utf-8\", (int)MediaTypeHeaderValueRange.AllMediaRange },\n                };\n            }\n        }\n\n        public static TheoryDataSet<string, string, int> NonOverlappingValues\n        {\n            get\n            {\n                return new TheoryDataSet<string, string, int>\n                {\n                    // These values are all value1 < value2 regardless of which value is first and second\n                    // We do this asymmetric sorting algorithm to ensure that subsets are always <=0.\n                    { \"text/xml\", \"application/xml\", (int)MediaTypeHeaderValueRange.None },\n                    { \"text/xml\", \"APPLICATION/XML\", (int)MediaTypeHeaderValueRange.None },\n                    { \"text/xml\", \"application/xml; charset=utf-8\", (int)MediaTypeHeaderValueRange.None },\n                    { \"text/xml; charset=utf-8\", \"application/xml; charset=utf-8\", (int)MediaTypeHeaderValueRange.None },\n                    { \"text/xml; charset=utf-8\", \"application/xml; parameter=value\", (int)MediaTypeHeaderValueRange.None },\n\n                    { \"text/xml\", \"text/plain\", (int)MediaTypeHeaderValueRange.None },\n                    { \"text/xml\", \"TEXT/PLAIN\", (int)MediaTypeHeaderValueRange.None },\n                    { \"text/xml\", \"text/plain; charset=utf-8\", (int)MediaTypeHeaderValueRange.None },\n                    { \"text/xml; charset=utf-8\", \"text/plain; charset=utf-8\", (int)MediaTypeHeaderValueRange.None },\n                    { \"text/xml; charset=utf-8\", \"text/plain; parameter=value\", (int)MediaTypeHeaderValueRange.None },\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"EqualValues\")]\n        public void IsSubsetOf_ReturnsTrueForEqualValues(string mediaType1, string mediaType2, int range)\n        {\n            MediaTypeHeaderValue mediaTypeHeaderValue1 = MediaTypeHeaderValue.Parse(mediaType1);\n            MediaTypeHeaderValue mediaTypeHeaderValue2 = MediaTypeHeaderValue.Parse(mediaType2);\n\n            MediaTypeHeaderValueRange actualRange;\n            Assert.True(mediaTypeHeaderValue1.IsSubsetOf(mediaTypeHeaderValue2, out actualRange));\n            Assert.Equal(range, (int)actualRange);\n\n            Assert.True(mediaTypeHeaderValue2.IsSubsetOf(mediaTypeHeaderValue1, out actualRange));\n        }\n\n        [Theory]\n        [PropertyData(\"NonEqualValues\")]\n        public void IsSubsetOf_ReturnsTrueForNonEqualValues(string mediaType1, string mediaType2, int range)\n        {\n            MediaTypeHeaderValue mediaTypeHeaderValue1 = MediaTypeHeaderValue.Parse(mediaType1);\n            MediaTypeHeaderValue mediaTypeHeaderValue2 = MediaTypeHeaderValue.Parse(mediaType2);\n\n            MediaTypeHeaderValueRange actualRange;\n            Assert.True(mediaTypeHeaderValue1.IsSubsetOf(mediaTypeHeaderValue2, out actualRange));\n            Assert.Equal(range, (int)actualRange);\n\n            Assert.False(mediaTypeHeaderValue2.IsSubsetOf(mediaTypeHeaderValue1));\n        }\n\n        [Theory]\n        [PropertyData(\"NonOverlappingValues\")]\n        public void IsSubsetOf_ReturnsFalseForNonOverlappingValues(string mediaType1, string mediaType2, int range)\n        {\n            MediaTypeHeaderValue mediaTypeHeaderValue1 = MediaTypeHeaderValue.Parse(mediaType1);\n            MediaTypeHeaderValue mediaTypeHeaderValue2 = MediaTypeHeaderValue.Parse(mediaType2);\n\n            MediaTypeHeaderValueRange actualRange;\n            Assert.False(mediaTypeHeaderValue1.IsSubsetOf(mediaTypeHeaderValue2, out actualRange));\n            Assert.Equal(range, (int)actualRange);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/MediaTypeMappingTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Headers;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Formatting\n{\n    public class MediaTypeMappingTests\n    {\n        [Fact]\n        public void Constructor_ThrowsOnNullMediaTypeHeaderValue()\n        {\n            Assert.ThrowsArgumentNull(() => new MockMediaTypeMapping((MediaTypeHeaderValue)null), \"mediaType\");\n        }\n\n        [Fact]\n        public void Constructor_ThrowsOnNullMediaType()\n        {\n            Assert.ThrowsArgumentNull(() => new MockMediaTypeMapping((string)null), \"mediaType\");\n            Assert.ThrowsArgumentNull(() => new MockMediaTypeMapping(String.Empty), \"mediaType\");\n        }\n\n        public class MockMediaTypeMapping : MediaTypeMapping\n        {\n            public MockMediaTypeMapping(MediaTypeHeaderValue mediaType)\n                : base(mediaType)\n            {\n            }\n\n            public MockMediaTypeMapping(string mediaType)\n                : base(mediaType)\n            {\n            }\n\n            public override double TryMatchMediaType(HttpRequestMessage request)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/MediaTypeWithQualityHeaderValueComparerTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http.Headers;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Formatting\n{\n    public class MediaTypeWithQualityHeaderValueComparerTests\n    {\n        public static TheoryDataSet<string, string> EqualValues\n        {\n            get\n            {\n                return new TheoryDataSet<string, string>\n                {\n                    { \"text/xml\", \"text/xml\" },\n                    { \"text/xml\", \"text/xml; q=1\" },\n                    { \"text/xml\", \"text/xml; q=1.0\" },\n                    { \"text/xml\", \"text/xml; q=1.0000\" },\n                    { \"text/xml\", \"TEXT/XML\" },\n                    { \"text/plain\", \"text/xml\" },\n                    { \"text/*\", \"text/*\" },\n                    { \"text/*\", \"TEXT/*\" },\n                    { \"*/*\", \"*/*\" },\n                    { \"text/xml\", \"text/xml; charset=utf8\" },\n                    { \"text/xml\", \"text/xml; parameter=value\" },\n                    { \"text/xml; parameter=value\", \"text/xml; parameter=value\" },\n                    { \"text/xml; parameter1=value1\", \"text/xml; parameter2=value2\" },\n                    { \"text/xml; q=0.5\", \"text/xml; q=0.50\" },\n                    { \"application/xml; q=0.5\", \"text/xml; q=0.5\" },\n                    { \"application/xml; q=0.1\", \"text/xml; q=0.1\" },\n                    { \"application/xml; parameter=value1; q=0.5\", \"text/xml; parameter=value2; q=0.5\" },\n                    { \"text/xml\", \"text/xml;q=1\" },\n                    { \"text/xml\", \"text/xml;q=1.0\" },\n                    { \"text/xml\", \"text/xml; q=1.00000\" },\n                    { \"text/xml; q=0.5\", \"text/xml; q=0.5\" },\n                    { \"text/xml; q=1.0\", \"text/xml; q=1.0\" },\n                    { \"*/*\", \"*/*;q=1\" },\n                    { \"*/*\", \"*/*; q=1\" },\n                    { \"*/*\", \"*/*;q=1.0\" },\n                    { \"*/*\", \"*/*; q=1.0\" },\n                    { \"*/*; q=0.5\", \"*/*; q=0.5\" },\n                    { \"*/*; q=1.0\", \"*/*; q=1.0\" },\n                };\n            }\n        }\n\n        public static TheoryDataSet<string, string> NonEqualValues\n        {\n            get\n            {\n                return new TheoryDataSet<string, string>\n                {\n                    { \"text/plain; q=0.5\", \"text/plain\" },\n                    { \"text/plain; q=0.5\", \"application/xml\" },\n                    { \"text/plain; q=0.5\", \"text/plain; q=1.0\" },\n                    { \"text/plain; q=0.5\", \"text/xml; q=1.0\" },\n                    { \"text/*\", \"text/plain\" },\n                    { \"application/*\", \"text/plain\" },\n                    { \"*/*\", \"text/xml\" },\n                    { \"*/*\", \"text/*\" },\n                    { \"*/*;q=0.5\", \"*/*;q=0.6\" },\n                    { \"*/*;q=0.5\", \"text/*;q=0.5\" },\n                    { \"*/*;q=1\", \"text/plain\" },\n                    { \"*/*; q=1\", \"text/plain\" },\n                    { \"*/*;q=1.0\", \"text/plain\" },\n                    { \"*/*; q=1.0\", \"text/plain\" },\n                    { \"*/*; q=0.5\", \"text/plain; q=0.5\" },\n                    { \"*/*; q=1.0\", \"text/plain; q=1.0\" },\n                    { \"*/*; q=0.5\", \"text/*; q=0.6\" },\n                };\n            }\n        }\n\n        public static TheoryDataSet<string[], string[]> BeforeAfterSortedValues\n        {\n            get\n            {\n                return new TheoryDataSet<string[], string[]>\n                {\n                    {\n                        new string[]\n                        {\n                            \"application/*\",\n                            \"text/plain\",\n                            \"text/plain;q=1.0\",\n                            \"text/plain\",\n                            \"text/plain;q=0\",\n                            \"*/*;q=0.8\",\n                            \"*/*;q=1\",\n                            \"text/*;q=1\",\n                            \"text/plain;q=0.8\",\n                            \"text/*;q=0.8\",\n                            \"text/*;q=0.6\",\n                            \"text/*;q=1.0\",\n                            \"*/*;q=0.4\",\n                            \"text/plain;q=0.6\",\n                            \"text/xml\",\n                        },\n                        new string[]\n                        {\n                            \"text/plain\",\n                            \"text/plain;q=1.0\",\n                            \"text/plain\",\n                            \"text/xml\",\n                            \"application/*\",\n                            \"text/*;q=1\",\n                            \"text/*;q=1.0\",\n                            \"*/*;q=1\",\n                            \"text/plain;q=0.8\",\n                            \"text/*;q=0.8\",\n                            \"*/*;q=0.8\",\n                            \"text/plain;q=0.6\",\n                            \"text/*;q=0.6\",\n                            \"*/*;q=0.4\",\n                            \"text/plain;q=0\",\n                        }\n                    }\n                };\n            }\n        }\n\n        [Fact]\n        public void StaticComparer_Returns_SameInstance()\n        {\n            MediaTypeWithQualityHeaderValueComparer comparer1 = MediaTypeWithQualityHeaderValueComparer.QualityComparer;\n            MediaTypeWithQualityHeaderValueComparer comparer2 = MediaTypeWithQualityHeaderValueComparer.QualityComparer;\n\n            Assert.NotNull(comparer1);\n            Assert.Same(comparer1, comparer2);\n        }\n\n        [Theory]\n        [PropertyData(\"EqualValues\")]\n        public void ComparerReturnsZeroForEqualValues(string mediaType1, string mediaType2)\n        {\n            // Arrange\n            MediaTypeWithQualityHeaderValueComparer comparer = MediaTypeWithQualityHeaderValueComparer.QualityComparer;\n\n            // Act\n            MediaTypeWithQualityHeaderValue mediaTypeHeaderValue1 = MediaTypeWithQualityHeaderValue.Parse(mediaType1);\n            MediaTypeWithQualityHeaderValue mediaTypeHeaderValue2 = MediaTypeWithQualityHeaderValue.Parse(mediaType2);\n\n            // Assert\n            Assert.Equal(0, comparer.Compare(mediaTypeHeaderValue1, mediaTypeHeaderValue2));\n            Assert.Equal(0, comparer.Compare(mediaTypeHeaderValue2, mediaTypeHeaderValue1));\n        }\n\n        [Theory]\n        [PropertyData(\"NonEqualValues\")]\n        public void ComparerReturnsNonZeroForNonEqualValues(string mediaType1, string mediaType2)\n        {\n            // Arrange\n            MediaTypeWithQualityHeaderValueComparer comparer = MediaTypeWithQualityHeaderValueComparer.QualityComparer;\n\n            // Act\n            MediaTypeWithQualityHeaderValue mediaTypeHeaderValue1 = MediaTypeWithQualityHeaderValue.Parse(mediaType1);\n            MediaTypeWithQualityHeaderValue mediaTypeHeaderValue2 = MediaTypeWithQualityHeaderValue.Parse(mediaType2);\n\n            // Assert\n            Assert.Equal(-1, comparer.Compare(mediaTypeHeaderValue1, mediaTypeHeaderValue2));\n            Assert.Equal(1, comparer.Compare(mediaTypeHeaderValue2, mediaTypeHeaderValue1));\n        }\n\n        [Theory]\n        [PropertyData(\"BeforeAfterSortedValues\")]\n        public void ComparerSortsListCorrectly(string[] unsorted, string[] expectedSorted)\n        {\n            // Arrange\n            IEnumerable<MediaTypeWithQualityHeaderValue> unsortedValues =\n                unsorted.Select(u => MediaTypeWithQualityHeaderValue.Parse(u));\n\n            IEnumerable<MediaTypeWithQualityHeaderValue> expectedSortedValues =\n                expectedSorted.Select(u => MediaTypeWithQualityHeaderValue.Parse(u));\n\n            // Act\n            IEnumerable<MediaTypeWithQualityHeaderValue> actualSorted = unsortedValues.OrderByDescending(m => m, MediaTypeWithQualityHeaderValueComparer.QualityComparer);\n\n            // Assert\n            Assert.True(expectedSortedValues.SequenceEqual(actualSorted));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/ParsedMediaTypeHeaderValueTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Headers;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Formatting\n{\n    public class ParsedMediaTypeHeadeValueTests\n    {\n        public static TheoryDataSet<string> FullMediaRanges\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    \"*/*\",\n                    \"*/*; charset=utf-8\",\n                    \"*/*; charset=utf-8; q=1.0\",\n                };\n            }\n        }\n\n        public static TheoryDataSet<string> SubTypeMediaRanges\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    \"text/*\",\n                    \"TEXT/*\",\n                    \"application/*; charset=utf-8\",\n                    \"APPLICATION/*; charset=utf-8\",\n                    \"APPLICATION/*; charset=utf-8; q=1.0\",\n                };\n            }\n        }\n\n        public static TheoryDataSet<string> InvalidMediaRanges\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    \"*/text\",\n                    \"*/XML\",\n                };\n            }\n        }\n        public static TheoryDataSet<string> NonMediaRanges\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    \"text/plain\",\n                    \"TEXT/XML\",\n                    \"application/xml; charset=utf-8\",\n                    \"APPLICATION/xml; charset=utf-8\",\n                };\n            }\n        }\n\n        public static TheoryDataSet<string> InvalidNonMediaRanges\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    \"\",\n                    \" \",\n                    \"\\n\",\n                    \"\\t\",\n                    \"text\",\n                    \"text/\",\n                    \"text\\\\\", \n                    \"\\\\\", \"//\", \n                    \"text/[\", \n                    \"text/ \", \n                    \" text/\", \n                    \" text/ \", \n                    \"text\\\\ \", \n                    \" text\\\\\", \n                    \" text\\\\ \", \n                    \"text\\\\xml\", \n                    \"text//xml\" \n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"InvalidNonMediaRanges\")]\n        public void MediaTypeHeaderValue_EnsuresValidMediaType(string invalidMediaType)\n        {\n            Assert.Throws<Exception>(() => new MediaTypeHeaderValue(invalidMediaType), exceptionMessage: null, allowDerivedExceptions: true);\n        }\n\n        [Fact]\n        public void TypesEqual_SameType_True()\n        {\n            ParsedMediaTypeHeaderValue parsedMediaType1 = new ParsedMediaTypeHeaderValue(MediaTypeHeaderValue.Parse(\"text/xml\"));\n            ParsedMediaTypeHeaderValue parsedMediaType2 = new ParsedMediaTypeHeaderValue(MediaTypeHeaderValue.Parse(\"text/json\"));\n            Assert.True(parsedMediaType1.TypesEqual(ref parsedMediaType2));\n        }\n\n        [Fact]\n        public void TypesEqual_SameTypeDifferentCase_True()\n        {\n            ParsedMediaTypeHeaderValue parsedMediaType1 = new ParsedMediaTypeHeaderValue(MediaTypeHeaderValue.Parse(\"text/xml\"));\n            ParsedMediaTypeHeaderValue parsedMediaType2 = new ParsedMediaTypeHeaderValue(MediaTypeHeaderValue.Parse(\"TEXT/xml\"));\n            Assert.True(parsedMediaType1.TypesEqual(ref parsedMediaType2));\n        }\n\n        [Fact]\n        public void TypesEqual_DifferentType_False()\n        {\n            ParsedMediaTypeHeaderValue parsedMediaType1 = new ParsedMediaTypeHeaderValue(MediaTypeHeaderValue.Parse(\"application/xml\"));\n            ParsedMediaTypeHeaderValue parsedMediaType2 = new ParsedMediaTypeHeaderValue(MediaTypeHeaderValue.Parse(\"text/xml\"));\n            Assert.False(parsedMediaType1.TypesEqual(ref parsedMediaType2));\n        }\n\n        [Fact]\n        public void TypesEqual_DifferentTypeSameLength_False()\n        {\n            ParsedMediaTypeHeaderValue parsedMediaType1 = new ParsedMediaTypeHeaderValue(MediaTypeHeaderValue.Parse(\"texx/xml\"));\n            ParsedMediaTypeHeaderValue parsedMediaType2 = new ParsedMediaTypeHeaderValue(MediaTypeHeaderValue.Parse(\"text/xml\"));\n            Assert.False(parsedMediaType1.TypesEqual(ref parsedMediaType2));\n        }\n\n        [Fact]\n        public void SubTypesEqual_SameType_True()\n        {\n            ParsedMediaTypeHeaderValue parsedMediaType1 = new ParsedMediaTypeHeaderValue(MediaTypeHeaderValue.Parse(\"text/xml\"));\n            ParsedMediaTypeHeaderValue parsedMediaType2 = new ParsedMediaTypeHeaderValue(MediaTypeHeaderValue.Parse(\"application/xml\"));\n            Assert.True(parsedMediaType1.SubTypesEqual(ref parsedMediaType2));\n        }\n\n        [Fact]\n        public void SubTypesEqual_SameTypeDifferentCase_True()\n        {\n            ParsedMediaTypeHeaderValue parsedMediaType1 = new ParsedMediaTypeHeaderValue(MediaTypeHeaderValue.Parse(\"text/xml\"));\n            ParsedMediaTypeHeaderValue parsedMediaType2 = new ParsedMediaTypeHeaderValue(MediaTypeHeaderValue.Parse(\"text/XML\"));\n            Assert.True(parsedMediaType1.SubTypesEqual(ref parsedMediaType2));\n        }\n\n        [Fact]\n        public void SubTypesEqual_DifferentType_False()\n        {\n            ParsedMediaTypeHeaderValue parsedMediaType1 = new ParsedMediaTypeHeaderValue(MediaTypeHeaderValue.Parse(\"text/xml\"));\n            ParsedMediaTypeHeaderValue parsedMediaType2 = new ParsedMediaTypeHeaderValue(MediaTypeHeaderValue.Parse(\"text/json\"));\n            Assert.False(parsedMediaType1.SubTypesEqual(ref parsedMediaType2));\n        }\n\n        [Fact]\n        public void SubTypesEqual_DifferentTypeSameLength_False()\n        {\n            ParsedMediaTypeHeaderValue parsedMediaType1 = new ParsedMediaTypeHeaderValue(MediaTypeHeaderValue.Parse(\"text/xml\"));\n            ParsedMediaTypeHeaderValue parsedMediaType2 = new ParsedMediaTypeHeaderValue(MediaTypeHeaderValue.Parse(\"text/yml\"));\n            Assert.False(parsedMediaType1.SubTypesEqual(ref parsedMediaType2));\n        }\n\n        [Theory]\n        [PropertyData(\"FullMediaRanges\")]\n        [PropertyData(\"SubTypeMediaRanges\")]\n        public void IsSubTypeMediaRange_ReturnsTrueForSubTypeMediaRanges(string mediaType)\n        {\n            MediaTypeHeaderValue mediaTypeHeaderValue = MediaTypeHeaderValue.Parse(mediaType);\n            ParsedMediaTypeHeaderValue parsedMediaType = new ParsedMediaTypeHeaderValue(mediaTypeHeaderValue);\n            Assert.True(parsedMediaType.IsSubtypeMediaRange);\n        }\n\n        [Theory]\n        [PropertyData(\"InvalidMediaRanges\")]\n        [PropertyData(\"NonMediaRanges\")]\n        public void IsSubTypeMediaRange_ReturnsFalseForNonSubTypeMediaRanges(string mediaType)\n        {\n            MediaTypeHeaderValue mediaTypeHeaderValue = MediaTypeHeaderValue.Parse(mediaType);\n            ParsedMediaTypeHeaderValue parsedMediaType = new ParsedMediaTypeHeaderValue(mediaTypeHeaderValue);\n            Assert.False(parsedMediaType.IsSubtypeMediaRange);\n        }\n\n        [Theory]\n        [PropertyData(\"FullMediaRanges\")]\n        public void IsAllMediaRange_ReturnsTrueForFullMediaTypeRanges(string mediaType)\n        {\n            MediaTypeHeaderValue mediaTypeHeaderValue = MediaTypeHeaderValue.Parse(mediaType);\n            ParsedMediaTypeHeaderValue parsedMediaType = new ParsedMediaTypeHeaderValue(mediaTypeHeaderValue);\n            Assert.True(parsedMediaType.IsAllMediaRange);\n        }\n\n        [Theory]\n        [PropertyData(\"SubTypeMediaRanges\")]\n        [PropertyData(\"InvalidMediaRanges\")]\n        [PropertyData(\"NonMediaRanges\")]\n        public void IsAllMediaRange_ReturnsFalseForNonFullMediaTypeRanges(string mediaType)\n        {\n            MediaTypeHeaderValue mediaTypeHeaderValue = MediaTypeHeaderValue.Parse(mediaType);\n            ParsedMediaTypeHeaderValue parsedMediaType = new ParsedMediaTypeHeaderValue(mediaTypeHeaderValue);\n            Assert.False(parsedMediaType.IsAllMediaRange);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/Parsers/FormUrlEncodedParserTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Formatting.Parsers\n{\n    public class FormUrlEncodedParserTests\n    {\n        private const int MinMessageSize = 1;\n        private const int Iterations = 16;\n\n        internal static Collection<KeyValuePair<string, string>> CreateCollection()\n        {\n            return new Collection<KeyValuePair<string, string>>();\n        }\n\n        internal static FormUrlEncodedParser CreateParser(int maxMessageSize, out ICollection<KeyValuePair<string, string>> nameValuePairs)\n        {\n            nameValuePairs = CreateCollection();\n            return new FormUrlEncodedParser(nameValuePairs, maxMessageSize);\n        }\n\n        internal static byte[] CreateBuffer(params string[] nameValuePairs)\n        {\n            StringBuilder buffer = new StringBuilder();\n            bool first = true;\n            foreach (var h in nameValuePairs)\n            {\n                if (first)\n                {\n                    first = false;\n                }\n                else\n                {\n                    buffer.Append('&');\n                }\n\n                buffer.Append(h);\n            }\n\n            return Encoding.UTF8.GetBytes(buffer.ToString());\n        }\n\n        internal static ParserState ParseBufferInSteps(FormUrlEncodedParser parser, byte[] buffer, int readsize, out int totalBytesConsumed)\n        {\n            ParserState state = ParserState.Invalid;\n            totalBytesConsumed = 0;\n            while (totalBytesConsumed <= buffer.Length)\n            {\n                int size = Math.Min(buffer.Length - totalBytesConsumed, readsize);\n                byte[] parseBuffer = new byte[size];\n                Buffer.BlockCopy(buffer, totalBytesConsumed, parseBuffer, 0, size);\n\n                int bytesConsumed = 0;\n                state = parser.ParseBuffer(parseBuffer, parseBuffer.Length, ref bytesConsumed, totalBytesConsumed == buffer.Length - size);\n                totalBytesConsumed += bytesConsumed;\n\n                if (state != ParserState.NeedMoreData)\n                {\n                    return state;\n                }\n            }\n\n            return state;\n        }\n\n        [Fact]\n        public void TypeIsCorrect()\n        {\n            Assert.Type.HasProperties<FormUrlEncodedParser>(TypeAssert.TypeProperties.IsClass);\n        }\n\n        [Fact]\n        public void FormUrlEncodedParserThrowsOnNull()\n        {\n            Assert.ThrowsArgumentNull(() => { new FormUrlEncodedParser(null, ParserData.MinHeaderSize); }, \"nameValuePairs\");\n        }\n\n        [Fact]\n        public void FormUrlEncodedParserThrowsOnInvalidSize()\n        {\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(() => { new FormUrlEncodedParser(CreateCollection(), MinMessageSize - 1); }, \"maxMessageSize\", MinMessageSize.ToString(), MinMessageSize - 1);\n\n            FormUrlEncodedParser parser = new FormUrlEncodedParser(CreateCollection(), MinMessageSize);\n            Assert.NotNull(parser);\n\n            parser = new FormUrlEncodedParser(CreateCollection(), MinMessageSize + 1);\n            Assert.NotNull(parser);\n        }\n\n        [Fact]\n        public void ParseBufferThrowsOnNullBuffer()\n        {\n            ICollection<KeyValuePair<string, string>> collection;\n            FormUrlEncodedParser parser = CreateParser(128, out collection);\n            int bytesConsumed = 0;\n            Assert.ThrowsArgumentNull(() => { parser.ParseBuffer(null, 0, ref bytesConsumed, false); }, \"buffer\");\n        }\n\n        [Fact]\n        public void ParseBufferHandlesEmptyBuffer()\n        {\n            byte[] data = CreateBuffer();\n            ICollection<KeyValuePair<string, string>> collection;\n            FormUrlEncodedParser parser = CreateParser(MinMessageSize, out collection);\n\n            int bytesConsumed = 0;\n            ParserState state = parser.ParseBuffer(data, data.Length, ref bytesConsumed, true);\n            Assert.Equal(ParserState.Done, state);\n            Assert.Equal(data.Length, bytesConsumed);\n            Assert.Empty(collection);\n        }\n\n        [Theory]\n        [InlineData(\"N\", \"N\", \"\")]\n        [InlineData(\"%26\", \"&\", \"\")]\n        [TestDataSet(typeof(UriQueryTestData), \"UriQueryData\")]\n        public void ParseBufferCorrectly(string segment, string name, string value)\n        {\n            for (int index = 1; index < Iterations; index++)\n            {\n                List<string> segments = new List<string>();\n                for (int cnt = 0; cnt < index; cnt++)\n                {\n                    segments.Add(segment);\n                }\n\n                byte[] data = CreateBuffer(segments.ToArray());\n                for (var cnt = 1; cnt <= data.Length; cnt++)\n                {\n                    ICollection<KeyValuePair<string, string>> collection;\n                    FormUrlEncodedParser parser = CreateParser(data.Length + 1, out collection);\n                    Assert.NotNull(parser);\n\n                    int totalBytesConsumed;\n                    ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                    Assert.Equal(ParserState.Done, state);\n                    Assert.Equal(data.Length, totalBytesConsumed);\n\n                    Assert.Equal(index, collection.Count());\n                    foreach (KeyValuePair<string, string> element in collection)\n                    {\n                        Assert.Equal(name, element.Key);\n                        Assert.Equal(value, element.Value);\n                    }\n                }\n            }\n        }\n\n        [Fact]\n        public void HeaderParserDataTooBig()\n        {\n            byte[] data = CreateBuffer(\"N=V\");\n            ICollection<KeyValuePair<string, string>> collection;\n            FormUrlEncodedParser parser = CreateParser(MinMessageSize, out collection);\n\n            int bytesConsumed = 0;\n            ParserState state = parser.ParseBuffer(data, data.Length, ref bytesConsumed, true);\n            Assert.Equal(ParserState.DataTooBig, state);\n            Assert.Equal(MinMessageSize, bytesConsumed);\n        }\n    }\n}"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/Parsers/HttpRequestHeaderParserTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http.Formatting.DataSets;\nusing System.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Formatting.Parsers\n{\n    public class HttpRequestHeaderParserTests\n    {\n        [Fact]\n        public void TypeIsCorrect()\n        {\n            Assert.Type.HasProperties<HttpRequestHeaderParser>(TypeAssert.TypeProperties.IsClass);\n        }\n\n        [Fact]\n        public void HttpRequestHeaderParserConstructorTest()\n        {\n            HttpUnsortedRequest result = new HttpUnsortedRequest();\n            Assert.NotNull(result);\n\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(() => new HttpRequestHeaderParser(result, ParserData.MinRequestLineSize - 1, ParserData.MinHeaderSize),\n                \"maxRequestLineSize\", ParserData.MinRequestLineSize.ToString(), ParserData.MinRequestLineSize - 1);\n\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(() => new HttpRequestHeaderParser(result, ParserData.MinRequestLineSize, ParserData.MinHeaderSize - 1),\n                \"maxHeaderSize\", ParserData.MinHeaderSize.ToString(), ParserData.MinHeaderSize - 1);\n\n            HttpRequestHeaderParser parser = new HttpRequestHeaderParser(result, ParserData.MinRequestLineSize, ParserData.MinHeaderSize);\n            Assert.NotNull(parser);\n\n            Assert.ThrowsArgumentNull(() => { new HttpRequestHeaderParser(null); }, \"httpRequest\");\n        }\n\n        [Fact]\n        public void RequestHeaderParserNullBuffer()\n        {\n            HttpUnsortedRequest result = new HttpUnsortedRequest();\n            HttpRequestHeaderParser parser = new HttpRequestHeaderParser(result, ParserData.MinRequestLineSize, ParserData.MinHeaderSize);\n            Assert.NotNull(parser);\n            int bytesConsumed = 0;\n            Assert.ThrowsArgumentNull(() => { parser.ParseBuffer(null, 0, ref bytesConsumed); }, \"buffer\");\n        }\n\n        [Fact]\n        public void RequestHeaderParserMinimumBuffer()\n        {\n            byte[] data = CreateBuffer(\"G\", \"/\", \"HTTP/1.1\", null);\n            HttpUnsortedRequest result = new HttpUnsortedRequest();\n            HttpRequestHeaderParser parser = new HttpRequestHeaderParser(result, ParserData.MinRequestLineSize, ParserData.MinHeaderSize);\n            Assert.NotNull(parser);\n\n            int bytesConsumed = 0;\n            ParserState state = parser.ParseBuffer(data, data.Length, ref bytesConsumed);\n            Assert.Equal(ParserState.Done, state);\n            Assert.Equal(data.Length, bytesConsumed);\n\n            ValidateResult(result, \"G\", \"/\", new Version(\"1.1\"), null);\n        }\n\n        [Theory]\n        [TestDataSet(typeof(HttpTestData), \"AllHttpMethods\")]\n        public void RequestHeaderParserAcceptsStandardMethods(HttpMethod method)\n        {\n            byte[] data = CreateBuffer(method.ToString(), \"/\", \"HTTP/1.1\", ParserData.ValidHeaders);\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpUnsortedRequest result = new HttpUnsortedRequest();\n                HttpRequestHeaderParser parser = new HttpRequestHeaderParser(result);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Done, state);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                ValidateResult(result, method.ToString(), \"/\", new Version(\"1.1\"), ParserData.ValidHeaders);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(HttpTestData), \"CustomHttpMethods\")]\n        public void RequestHeaderParserAcceptsCustomMethods(HttpMethod method)\n        {\n            byte[] data = CreateBuffer(method.ToString(), \"/\", \"HTTP/1.1\", ParserData.ValidHeaders);\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpUnsortedRequest result = new HttpUnsortedRequest();\n                HttpRequestHeaderParser parser = new HttpRequestHeaderParser(result);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Done, state);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                ValidateResult(result, method.ToString(), \"/\", new Version(\"1.1\"), ParserData.ValidHeaders);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(ParserData), \"InvalidMethods\")]\n        public void RequestHeaderParserRejectsInvalidMethod(string invalidMethod)\n        {\n            byte[] data = CreateBuffer(invalidMethod, \"/\", \"HTTP/1.1\", ParserData.ValidHeaders);\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpUnsortedRequest result = new HttpUnsortedRequest();\n                HttpRequestHeaderParser parser = new HttpRequestHeaderParser(result);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Invalid, state);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(ParserData), \"InvalidRequestUris\")]\n        public void RequestHeaderParserRejectsInvalidUri(string invalidRequestUri)\n        {\n            byte[] data = CreateBuffer(\"GET\", invalidRequestUri, \"HTTP/1.1\", ParserData.ValidHeaders);\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpUnsortedRequest result = new HttpUnsortedRequest();\n                HttpRequestHeaderParser parser = new HttpRequestHeaderParser(result);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Invalid, state);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(ParserData), \"Versions\")]\n        public void RequestHeaderParserAcceptsValidVersion(Version version)\n        {\n            byte[] data = CreateBuffer(\"GET\", \"/\", String.Format(\"HTTP/{0}\", version.ToString(2)), ParserData.ValidHeaders);\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpUnsortedRequest result = new HttpUnsortedRequest();\n                HttpRequestHeaderParser parser = new HttpRequestHeaderParser(result);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                ValidateResult(result, \"GET\", \"/\", version, ParserData.ValidHeaders);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(ParserData), \"InvalidVersions\")]\n        public void RequestHeaderParserRejectsInvalidVersion(string invalidVersion)\n        {\n            byte[] data = CreateBuffer(\"GET\", \"/\", invalidVersion, ParserData.ValidHeaders);\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpUnsortedRequest result = new HttpUnsortedRequest();\n                HttpRequestHeaderParser parser = new HttpRequestHeaderParser(result);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Invalid, state);\n            }\n        }\n\n        private static byte[] CreateBuffer(string method, string address, string version, Dictionary<string, string> headers)\n        {\n            const string SP = \" \";\n            const string CRLF = \"\\r\\n\";\n            string lws = SP;\n\n            StringBuilder request = new StringBuilder();\n            request.AppendFormat(\"{0}{1}{2}{3}{4}{5}\", method, lws, address, lws, version, CRLF);\n            if (headers != null)\n            {\n                foreach (var h in headers)\n                {\n                    request.AppendFormat(\"{0}: {1}{2}\", h.Key, h.Value, CRLF);\n                }\n            }\n\n            request.Append(CRLF);\n            return Encoding.UTF8.GetBytes(request.ToString());\n        }\n\n        private static ParserState ParseBufferInSteps(HttpRequestHeaderParser parser, byte[] buffer, int readsize, out int totalBytesConsumed)\n        {\n            ParserState state = ParserState.Invalid;\n            totalBytesConsumed = 0;\n            while (totalBytesConsumed <= buffer.Length)\n            {\n                int size = Math.Min(buffer.Length - totalBytesConsumed, readsize);\n                byte[] parseBuffer = new byte[size];\n                Buffer.BlockCopy(buffer, totalBytesConsumed, parseBuffer, 0, size);\n\n                int bytesConsumed = 0;\n                state = parser.ParseBuffer(parseBuffer, parseBuffer.Length, ref bytesConsumed);\n                totalBytesConsumed += bytesConsumed;\n\n                if (state != ParserState.NeedMoreData)\n                {\n                    return state;\n                }\n            }\n\n            return state;\n        }\n\n        private static void ValidateResult(\n            HttpUnsortedRequest requestLine,\n            string method,\n            string requestUri,\n            Version version,\n            Dictionary<string, string> headers)\n        {\n            Assert.Equal(new HttpMethod(method), requestLine.Method);\n            Assert.Equal(requestUri, requestLine.RequestUri);\n            Assert.Equal(version, requestLine.Version);\n\n            if (headers != null)\n            {\n                Assert.Equal(headers.Count, requestLine.HttpHeaders.Count());\n                foreach (var header in headers)\n                {\n                    Assert.True(requestLine.HttpHeaders.Contains(header.Key), \"Parsed header did not contain expected key \" + header.Key);\n                    Assert.Equal(header.Value, requestLine.HttpHeaders.GetValues(header.Key).ElementAt(0));\n                }\n            }\n        }\n    }\n}"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/Parsers/HttpRequestLineParserTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Formatting.DataSets;\nusing System.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Formatting.Parsers\n{\n    public class HttpRequestLineParserTests\n    {\n        [Fact]\n        public void TypeIsCorrect()\n        {\n            Assert.Type.HasProperties<HttpRequestLineParser>(TypeAssert.TypeProperties.IsClass);\n        }\n\n        [Fact]\n        public void HttpRequestLineParserConstructorTest()\n        {\n            HttpUnsortedRequest requestLine = new HttpUnsortedRequest();\n            Assert.NotNull(requestLine);\n\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(() => new HttpRequestLineParser(requestLine, ParserData.MinRequestLineSize - 1),\n                \"maxRequestLineSize\", ParserData.MinRequestLineSize.ToString(), ParserData.MinRequestLineSize - 1);\n\n            HttpRequestLineParser parser = new HttpRequestLineParser(requestLine, ParserData.MinRequestLineSize);\n            Assert.NotNull(parser);\n\n            Assert.ThrowsArgumentNull(() => { new HttpRequestLineParser(null, ParserData.MinRequestLineSize); }, \"httpRequest\");\n        }\n\n\n        [Fact]\n        public void RequestLineParserNullBuffer()\n        {\n            HttpUnsortedRequest requestLine = new HttpUnsortedRequest();\n            HttpRequestLineParser parser = new HttpRequestLineParser(requestLine, ParserData.MinRequestLineSize);\n            Assert.NotNull(parser);\n            int bytesConsumed = 0;\n            Assert.ThrowsArgumentNull(() => { parser.ParseBuffer(null, 0, ref bytesConsumed); }, \"buffer\");\n        }\n\n        [Fact]\n        public void RequestLineParserMinimumBuffer()\n        {\n            byte[] data = CreateBuffer(\"G\", \"/\", \"HTTP/1.1\");\n            HttpUnsortedRequest requestLine = new HttpUnsortedRequest();\n            HttpRequestLineParser parser = new HttpRequestLineParser(requestLine, ParserData.MinRequestLineSize);\n            Assert.NotNull(parser);\n\n            int bytesConsumed = 0;\n            ParserState state = parser.ParseBuffer(data, data.Length, ref bytesConsumed);\n            Assert.Equal(ParserState.Done, state);\n            Assert.Equal(data.Length, bytesConsumed);\n\n            ValidateResult(requestLine, \"G\", \"/\", new Version(\"1.1\"));\n        }\n\n        [Fact]\n        public void RequestLineParserRejectsLws()\n        {\n            byte[] data = CreateBuffer(\"GET\", \"/\", \"HTTP/1.1\", true);\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpUnsortedRequest requestLine = new HttpUnsortedRequest();\n                HttpRequestLineParser parser = new HttpRequestLineParser(requestLine, data.Length);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Invalid, state);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(HttpTestData), \"AllHttpMethods\")]\n        public void RequestLineParserAcceptsStandardMethods(HttpMethod method)\n        {\n            byte[] data = CreateBuffer(method.ToString(), \"/\", \"HTTP/1.1\");\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpUnsortedRequest requestLine = new HttpUnsortedRequest();\n                HttpRequestLineParser parser = new HttpRequestLineParser(requestLine, data.Length);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Done, state);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                ValidateResult(requestLine, method.ToString(), \"/\", new Version(\"1.1\"));\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(HttpTestData), \"CustomHttpMethods\")]\n        public void RequestLineParserAcceptsCustomMethods(HttpMethod method)\n        {\n            byte[] data = CreateBuffer(method.ToString(), \"/\", \"HTTP/1.1\");\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpUnsortedRequest requestLine = new HttpUnsortedRequest();\n                HttpRequestLineParser parser = new HttpRequestLineParser(requestLine, data.Length);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Done, state);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                ValidateResult(requestLine, method.ToString(), \"/\", new Version(\"1.1\"));\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(ParserData), \"InvalidMethods\")]\n        public void RequestLineParserRejectsInvalidMethod(string invalidMethod)\n        {\n            byte[] data = CreateBuffer(invalidMethod, \"/\", \"HTTP/1.1\");\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpUnsortedRequest requestLine = new HttpUnsortedRequest();\n                HttpRequestLineParser parser = new HttpRequestLineParser(requestLine, 256);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Invalid, state);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(ParserData), \"InvalidRequestUris\")]\n        public void RequestLineParserRejectsInvalidUri(string invalidRequestUri)\n        {\n            byte[] data = CreateBuffer(\"GET\", invalidRequestUri, \"HTTP/1.1\");\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpUnsortedRequest requestLine = new HttpUnsortedRequest();\n                HttpRequestLineParser parser = new HttpRequestLineParser(requestLine, 256);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Invalid, state);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(ParserData), \"Versions\")]\n        public void RequestLineParserAcceptsValidVersion(Version version)\n        {\n            byte[] data = CreateBuffer(\"GET\", \"/\", String.Format(\"HTTP/{0}\", version.ToString(2)));\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpUnsortedRequest requestLine = new HttpUnsortedRequest();\n                HttpRequestLineParser parser = new HttpRequestLineParser(requestLine, 256);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                ValidateResult(requestLine, \"GET\", \"/\", version);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(ParserData), \"InvalidVersions\")]\n        public void RequestLineParserRejectsInvalidVersion(string invalidVersion)\n        {\n            byte[] data = CreateBuffer(\"GET\", \"/\", invalidVersion);\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpUnsortedRequest requestLine = new HttpUnsortedRequest();\n                HttpRequestLineParser parser = new HttpRequestLineParser(requestLine, 256);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Invalid, state);\n            }\n        }\n\n        internal static byte[] CreateBuffer(string method, string address, string version)\n        {\n            return CreateBuffer(method, address, version, false);\n        }\n\n        private static byte[] CreateBuffer(string method, string address, string version, bool withLws)\n        {\n            const string SP = \" \";\n            const string HTAB = \"\\t\";\n            const string CRLF = \"\\r\\n\";\n\n            string lws = SP;\n            if (withLws)\n            {\n                lws = SP + SP + HTAB + SP;\n            }\n\n            string requestLine = String.Format(\"{0}{1}{2}{3}{4}{5}\", method, lws, address, lws, version, CRLF);\n            return Encoding.UTF8.GetBytes(requestLine);\n        }\n\n        private static ParserState ParseBufferInSteps(HttpRequestLineParser parser, byte[] buffer, int readsize, out int totalBytesConsumed)\n        {\n            ParserState state = ParserState.Invalid;\n            totalBytesConsumed = 0;\n            while (totalBytesConsumed <= buffer.Length)\n            {\n                int size = Math.Min(buffer.Length - totalBytesConsumed, readsize);\n                byte[] parseBuffer = new byte[size];\n                Buffer.BlockCopy(buffer, totalBytesConsumed, parseBuffer, 0, size);\n\n                int bytesConsumed = 0;\n                state = parser.ParseBuffer(parseBuffer, parseBuffer.Length, ref bytesConsumed);\n                totalBytesConsumed += bytesConsumed;\n\n                if (state != ParserState.NeedMoreData)\n                {\n                    return state;\n                }\n            }\n\n            return state;\n        }\n\n        private static void ValidateResult(HttpUnsortedRequest requestLine, string method, string requestUri, Version version)\n        {\n            Assert.Equal(new HttpMethod(method), requestLine.Method);\n            Assert.Equal(requestUri, requestLine.RequestUri);\n            Assert.Equal(version, requestLine.Version);\n        }\n    }\n}"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/Parsers/HttpResponseHeaderParserTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http.Formatting.DataSets;\nusing System.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Formatting.Parsers\n{\n    public class HttpResponseHeaderParserTests\n    {\n        [Fact]\n        public void TypeIsCorrect()\n        {\n            Assert.Type.HasProperties<HttpResponseHeaderParser>(TypeAssert.TypeProperties.IsClass);\n        }\n\n        [Fact]\n        public void HttpResponseHeaderParserConstructorTest()\n        {\n            HttpUnsortedResponse result = new HttpUnsortedResponse();\n            Assert.NotNull(result);\n\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(() => new HttpResponseHeaderParser(result, ParserData.MinStatusLineSize - 1, ParserData.MinHeaderSize),\n                \"maxStatusLineSize\", ParserData.MinStatusLineSize.ToString(), ParserData.MinStatusLineSize - 1);\n\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(() => new HttpResponseHeaderParser(result, ParserData.MinStatusLineSize, ParserData.MinHeaderSize - 1),\n                \"maxHeaderSize\", ParserData.MinHeaderSize.ToString(), ParserData.MinHeaderSize - 1);\n\n            HttpResponseHeaderParser parser = new HttpResponseHeaderParser(result, ParserData.MinStatusLineSize, ParserData.MinHeaderSize);\n            Assert.NotNull(parser);\n\n            Assert.ThrowsArgumentNull(() => { new HttpResponseHeaderParser(null); }, \"httpResponse\");\n        }\n\n\n        [Fact]\n        public void ResponseHeaderParserNullBuffer()\n        {\n            HttpUnsortedResponse result = new HttpUnsortedResponse();\n            HttpResponseHeaderParser parser = new HttpResponseHeaderParser(result, ParserData.MinStatusLineSize, ParserData.MinHeaderSize);\n            Assert.NotNull(parser);\n            int bytesConsumed = 0;\n            Assert.ThrowsArgumentNull(() => { parser.ParseBuffer(null, 0, ref bytesConsumed); }, \"buffer\");\n        }\n\n        [Fact]\n        public void ResponseHeaderParserMinimumBuffer()\n        {\n            byte[] data = CreateBuffer(\"HTTP/1.1\", \"200\", \"\", null);\n            HttpUnsortedResponse result = new HttpUnsortedResponse();\n            HttpResponseHeaderParser parser = new HttpResponseHeaderParser(result, ParserData.MinStatusLineSize, ParserData.MinHeaderSize);\n            Assert.NotNull(parser);\n\n            int bytesConsumed = 0;\n            ParserState state = parser.ParseBuffer(data, data.Length, ref bytesConsumed);\n            Assert.Equal(ParserState.Done, state);\n            Assert.Equal(data.Length, bytesConsumed);\n\n            ValidateResult(result, new Version(\"1.1\"), HttpStatusCode.OK, \"\", null);\n        }\n\n        [Theory]\n        [TestDataSet(typeof(HttpTestData), \"AllHttpStatusCodes\")]\n        public void ResponseHeaderParserAcceptsStandardStatusCodes(HttpStatusCode status)\n        {\n            byte[] data = CreateBuffer(\"HTTP/1.1\", ((int)status).ToString(), \"Reason\", ParserData.ValidHeaders);\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpUnsortedResponse result = new HttpUnsortedResponse();\n                HttpResponseHeaderParser parser = new HttpResponseHeaderParser(result);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Done, state);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                ValidateResult(result, new Version(\"1.1\"), status, \"Reason\", ParserData.ValidHeaders);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(HttpTestData), \"CustomHttpStatusCodes\")]\n        public void ResponseHeaderParserAcceptsCustomStatusCodes(HttpStatusCode status)\n        {\n            byte[] data = CreateBuffer(\"HTTP/1.1\", ((int)status).ToString(), \"Reason\", ParserData.ValidHeaders);\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpUnsortedResponse result = new HttpUnsortedResponse();\n                HttpResponseHeaderParser parser = new HttpResponseHeaderParser(result);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Done, state);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                ValidateResult(result, new Version(\"1.1\"), status, \"Reason\", ParserData.ValidHeaders);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(ParserData), \"InvalidStatusCodes\")]\n        public void ResponseHeaderParserRejectsInvalidStatusCodes(string invalidStatus)\n        {\n            byte[] data = CreateBuffer(\"HTTP/1.1\", invalidStatus, \"Reason\", ParserData.ValidHeaders);\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpUnsortedResponse result = new HttpUnsortedResponse();\n                HttpResponseHeaderParser parser = new HttpResponseHeaderParser(result);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Invalid, state);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(ParserData), \"InvalidReasonPhrases\")]\n        public void ResponseHeaderParserRejectsInvalidReasonPhrase(string invalidReason)\n        {\n            byte[] data = CreateBuffer(\"HTTP/1.1\", \"200\", invalidReason, ParserData.ValidHeaders);\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpUnsortedResponse result = new HttpUnsortedResponse();\n                HttpResponseHeaderParser parser = new HttpResponseHeaderParser(result);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Invalid, state);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(ParserData), \"Versions\")]\n        public void ResponseHeaderParserAcceptsValidVersion(Version version)\n        {\n            byte[] data = CreateBuffer(String.Format(\"HTTP/{0}\", version.ToString(2)), \"200\", \"Reason\", ParserData.ValidHeaders);\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpUnsortedResponse result = new HttpUnsortedResponse();\n                HttpResponseHeaderParser parser = new HttpResponseHeaderParser(result);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                ValidateResult(result, version, HttpStatusCode.OK, \"Reason\", ParserData.ValidHeaders);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(ParserData), \"InvalidVersions\")]\n        public void ResponseHeaderParserRejectsInvalidVersion(string invalid)\n        {\n            byte[] data = CreateBuffer(invalid, \"200\", \"Reason\", ParserData.ValidHeaders);\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpUnsortedResponse result = new HttpUnsortedResponse();\n                HttpResponseHeaderParser parser = new HttpResponseHeaderParser(result);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Invalid, state);\n            }\n        }\n\n        private static byte[] CreateBuffer(string version, string statusCode, string reasonPhrase, Dictionary<string, string> headers)\n        {\n            const string SP = \" \";\n            const string CRLF = \"\\r\\n\";\n            string lws = SP;\n\n            StringBuilder response = new StringBuilder();\n            response.AppendFormat(\"{0}{1}{2}{3}{4}{5}\", version, lws, statusCode, lws, reasonPhrase, CRLF);\n            if (headers != null)\n            {\n                foreach (var h in headers)\n                {\n                    response.AppendFormat(\"{0}: {1}{2}\", h.Key, h.Value, CRLF);\n                }\n            }\n\n            response.Append(CRLF);\n            return Encoding.UTF8.GetBytes(response.ToString());\n        }\n\n        private static ParserState ParseBufferInSteps(HttpResponseHeaderParser parser, byte[] buffer, int readsize, out int totalBytesConsumed)\n        {\n            ParserState state = ParserState.Invalid;\n            totalBytesConsumed = 0;\n            while (totalBytesConsumed <= buffer.Length)\n            {\n                int size = Math.Min(buffer.Length - totalBytesConsumed, readsize);\n                byte[] parseBuffer = new byte[size];\n                Buffer.BlockCopy(buffer, totalBytesConsumed, parseBuffer, 0, size);\n\n                int bytesConsumed = 0;\n                state = parser.ParseBuffer(parseBuffer, parseBuffer.Length, ref bytesConsumed);\n                totalBytesConsumed += bytesConsumed;\n\n                if (state != ParserState.NeedMoreData)\n                {\n                    return state;\n                }\n            }\n\n            return state;\n        }\n\n        private static void ValidateResult(\n            HttpUnsortedResponse statusLine,\n            Version version,\n            HttpStatusCode statusCode,\n            string reasonPhrase,\n            Dictionary<string, string> headers)\n        {\n            Assert.Equal(version, statusLine.Version);\n            Assert.Equal(statusCode, statusLine.StatusCode);\n            Assert.Equal(reasonPhrase, statusLine.ReasonPhrase);\n\n            if (headers != null)\n            {\n                Assert.Equal(headers.Count, statusLine.HttpHeaders.Count());\n                foreach (var header in headers)\n                {\n                    Assert.True(statusLine.HttpHeaders.Contains(header.Key), \"Parsed header did not contain expected key \" + header.Key);\n                    Assert.Equal(header.Value, statusLine.HttpHeaders.GetValues(header.Key).ElementAt(0));\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/Parsers/HttpStatusLineParserTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Formatting.DataSets;\nusing System.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Formatting.Parsers\n{\n    public class HttpStatusLineParserTests\n    {\n        [Fact]\n        public void TypeIsCorrect()\n        {\n            Assert.Type.HasProperties<HttpStatusLineParser>(TypeAssert.TypeProperties.IsClass);\n        }\n\n        [Fact]\n        public void HttpStatusLineParserConstructorTest()\n        {\n            HttpUnsortedResponse statusLine = new HttpUnsortedResponse();\n            Assert.NotNull(statusLine);\n\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(() => new HttpStatusLineParser(statusLine, ParserData.MinStatusLineSize - 1),\n                \"maxStatusLineSize\", ParserData.MinStatusLineSize.ToString(), ParserData.MinStatusLineSize - 1);\n\n            HttpStatusLineParser parser = new HttpStatusLineParser(statusLine, ParserData.MinStatusLineSize);\n            Assert.NotNull(parser);\n\n            Assert.ThrowsArgumentNull(() => { new HttpStatusLineParser(null, ParserData.MinStatusLineSize); }, \"httpResponse\");\n        }\n\n\n        [Fact]\n        public void StatusLineParserNullBuffer()\n        {\n            HttpUnsortedResponse statusLine = new HttpUnsortedResponse();\n            HttpStatusLineParser parser = new HttpStatusLineParser(statusLine, ParserData.MinStatusLineSize);\n            Assert.NotNull(parser);\n            int bytesConsumed = 0;\n            Assert.ThrowsArgumentNull(() => { parser.ParseBuffer(null, 0, ref bytesConsumed); }, \"buffer\");\n        }\n\n        [Fact]\n        public void StatusLineParserMinimumBuffer()\n        {\n            byte[] data = CreateBuffer(\"HTTP/1.1\", \"200\", \"\");\n            HttpUnsortedResponse statusLine = new HttpUnsortedResponse();\n            HttpStatusLineParser parser = new HttpStatusLineParser(statusLine, ParserData.MinStatusLineSize);\n            Assert.NotNull(parser);\n\n            int bytesConsumed = 0;\n            ParserState state = parser.ParseBuffer(data, data.Length, ref bytesConsumed);\n            Assert.Equal(ParserState.Done, state);\n            Assert.Equal(data.Length, bytesConsumed);\n\n            ValidateResult(statusLine, new Version(\"1.1\"), HttpStatusCode.OK, \"\");\n        }\n\n        [Fact]\n        public void StatusLineParserRejectsLws()\n        {\n            byte[] data = CreateBuffer(\"HTTP/1.1\", \"200\", \"Reason\", true);\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpUnsortedResponse statusLine = new HttpUnsortedResponse();\n                HttpStatusLineParser parser = new HttpStatusLineParser(statusLine, data.Length);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Invalid, state);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(HttpTestData), \"AllHttpStatusCodes\")]\n        public void StatusLineParserAcceptsStandardStatusCodes(HttpStatusCode status)\n        {\n            byte[] data = CreateBuffer(\"HTTP/1.1\", ((int)status).ToString(), \"Reason\");\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpUnsortedResponse statusLine = new HttpUnsortedResponse();\n                HttpStatusLineParser parser = new HttpStatusLineParser(statusLine, data.Length);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Done, state);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                ValidateResult(statusLine, new Version(\"1.1\"), status, \"Reason\");\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(HttpTestData), \"CustomHttpStatusCodes\")]\n        public void StatusLineParserAcceptsCustomStatusCodes(HttpStatusCode status)\n        {\n            byte[] data = CreateBuffer(\"HTTP/1.1\", ((int)status).ToString(), \"Reason\");\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpUnsortedResponse statusLine = new HttpUnsortedResponse();\n                HttpStatusLineParser parser = new HttpStatusLineParser(statusLine, data.Length);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Done, state);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                ValidateResult(statusLine, new Version(\"1.1\"), status, \"Reason\");\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(ParserData), \"InvalidStatusCodes\")]\n        public void StatusLineParserRejectsInvalidStatusCodes(string invalidStatus)\n        {\n            byte[] data = CreateBuffer(\"HTTP/1.1\", invalidStatus, \"Reason\");\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpUnsortedResponse statusLine = new HttpUnsortedResponse();\n                HttpStatusLineParser parser = new HttpStatusLineParser(statusLine, 256);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Invalid, state);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(ParserData), \"ValidReasonPhrases\")]\n        public void StatusLineParserAcceptsValidReasonPhrase(string validReasonPhrase)\n        {\n            byte[] data = CreateBuffer(\"HTTP/1.1\", \"200\", validReasonPhrase);\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpUnsortedResponse statusLine = new HttpUnsortedResponse();\n                HttpStatusLineParser parser = new HttpStatusLineParser(statusLine, 256);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n\n                ValidateResult(statusLine, new Version(\"1.1\"), HttpStatusCode.OK, validReasonPhrase);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(ParserData), \"Versions\")]\n        public void StatusLineParserAcceptsValidVersion(Version version)\n        {\n            byte[] data = CreateBuffer(String.Format(\"HTTP/{0}\", version.ToString(2)), \"200\", \"Reason\");\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpUnsortedResponse statusLine = new HttpUnsortedResponse();\n                HttpStatusLineParser parser = new HttpStatusLineParser(statusLine, 256);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                ValidateResult(statusLine, version, HttpStatusCode.OK, \"Reason\");\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(ParserData), \"InvalidVersions\")]\n        public void StatusLineParserRejectsInvalidVersion(string invalidVersion)\n        {\n            byte[] data = CreateBuffer(invalidVersion, \"200\", \"Reason\");\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpUnsortedResponse statusLine = new HttpUnsortedResponse();\n                HttpStatusLineParser parser = new HttpStatusLineParser(statusLine, 256);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Invalid, state);\n            }\n        }\n\n        internal static byte[] CreateBuffer(string version, string statusCode, string reasonPhrase)\n        {\n            return CreateBuffer(version, statusCode, reasonPhrase, false);\n        }\n\n        private static byte[] CreateBuffer(string version, string statusCode, string reasonPhrase, bool withLws)\n        {\n            const string SP = \" \";\n            const string HTAB = \"\\t\";\n            const string CRLF = \"\\r\\n\";\n\n            string lws = SP;\n            if (withLws)\n            {\n                lws = SP + SP + HTAB + SP;\n            }\n\n            string statusLine = String.Format(\"{0}{1}{2}{3}{4}{5}\", version, lws, statusCode, lws, reasonPhrase, CRLF);\n            return Encoding.UTF8.GetBytes(statusLine);\n        }\n\n        private static ParserState ParseBufferInSteps(HttpStatusLineParser parser, byte[] buffer, int readsize, out int totalBytesConsumed)\n        {\n            ParserState state = ParserState.Invalid;\n            totalBytesConsumed = 0;\n            while (totalBytesConsumed <= buffer.Length)\n            {\n                int size = Math.Min(buffer.Length - totalBytesConsumed, readsize);\n                byte[] parseBuffer = new byte[size];\n                Buffer.BlockCopy(buffer, totalBytesConsumed, parseBuffer, 0, size);\n\n                int bytesConsumed = 0;\n                state = parser.ParseBuffer(parseBuffer, parseBuffer.Length, ref bytesConsumed);\n                totalBytesConsumed += bytesConsumed;\n\n                if (state != ParserState.NeedMoreData)\n                {\n                    return state;\n                }\n            }\n\n            return state;\n        }\n\n        private static void ValidateResult(HttpUnsortedResponse statusLine, Version version, HttpStatusCode statusCode, string reasonPhrase)\n        {\n            Assert.Equal(version, statusLine.Version);\n            Assert.Equal(statusCode, statusLine.StatusCode);\n            Assert.Equal(reasonPhrase, statusLine.ReasonPhrase);\n        }\n    }\n}"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/Parsers/InternetMessageFormatHeaderParserTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http.Headers;\nusing System.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Formatting.Parsers\n{\n    public class InternetMessageFormatHeaderParserTests\n    {\n        [Fact]\n        public void TypeIsCorrect()\n        {\n            Assert.Type.HasProperties<InternetMessageFormatHeaderParser>(TypeAssert.TypeProperties.IsClass);\n        }\n\n        [Fact]\n        public void HeaderParserConstructorTest()\n        {\n            IEnumerable<HttpHeaders> headers = InternetMessageFormatHeaderParserTests.CreateHttpHeaders();\n            foreach (var header in headers)\n            {\n                InternetMessageFormatHeaderParser parser = new InternetMessageFormatHeaderParser(header, ParserData.MinHeaderSize);\n                Assert.NotNull(parser);\n            }\n\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(() => new InternetMessageFormatHeaderParser(headers.ElementAt(0), ParserData.MinHeaderSize - 1),\n                \"maxHeaderSize\", ParserData.MinHeaderSize.ToString(), ParserData.MinHeaderSize - 1);\n\n            Assert.ThrowsArgumentNull(() => { new InternetMessageFormatHeaderParser(null, ParserData.MinHeaderSize); }, \"headers\");\n        }\n\n\n        [Fact]\n        public void HeaderParserNullBuffer()\n        {\n            HttpHeaders headers;\n            InternetMessageFormatHeaderParser parser = InternetMessageFormatHeaderParserTests.CreateHeaderParser(128, out headers);\n            Assert.NotNull(parser);\n            int bytesConsumed = 0;\n            Assert.ThrowsArgumentNull(() => { parser.ParseBuffer(null, 0, ref bytesConsumed); }, \"buffer\");\n        }\n\n        [Fact]\n        public void HeaderParserEmptyBuffer()\n        {\n            byte[] data = InternetMessageFormatHeaderParserTests.CreateBuffer();\n            HttpHeaders headers;\n            InternetMessageFormatHeaderParser parser = InternetMessageFormatHeaderParserTests.CreateHeaderParser(data.Length, out headers);\n            Assert.NotNull(parser);\n\n            int bytesConsumed = 0;\n            ParserState state = parser.ParseBuffer(data, data.Length, ref bytesConsumed);\n            Assert.Equal(ParserState.Done, state);\n            Assert.Equal(data.Length, bytesConsumed);\n\n            Assert.Empty(headers);\n        }\n\n        [Fact]\n        public void HeaderParserSingleNameValueHeader()\n        {\n            byte[] data = InternetMessageFormatHeaderParserTests.CreateBuffer(\"N:V\");\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpHeaders headers;\n                InternetMessageFormatHeaderParser parser = InternetMessageFormatHeaderParserTests.CreateHeaderParser(data.Length, out headers);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed;\n                ParserState state = InternetMessageFormatHeaderParserTests.ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Done, state);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                Assert.Single(headers);\n                IEnumerable<string> parsedValues = headers.GetValues(\"N\");\n                string parsedValue = Assert.Single(parsedValues);\n                Assert.Equal(\"V\", parsedValue);\n            }\n        }\n\n        [Fact]\n        public void HeaderParserSingleNameHeader()\n        {\n            byte[] data = InternetMessageFormatHeaderParserTests.CreateBuffer(\"N:\");\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpHeaders headers;\n                InternetMessageFormatHeaderParser parser = InternetMessageFormatHeaderParserTests.CreateHeaderParser(data.Length, out headers);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed;\n                ParserState state = InternetMessageFormatHeaderParserTests.ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Done, state);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                Assert.Single(headers);\n                IEnumerable<string> parsedValues = headers.GetValues(\"N\");\n                string parsedValue = Assert.Single(parsedValues);\n                Assert.Equal(\"\", parsedValue);\n            }\n        }\n\n        [Fact]\n        public void HeaderParserMultipleNameHeader()\n        {\n            byte[] data = InternetMessageFormatHeaderParserTests.CreateBuffer(\"N:V1\", \"N:V2\");\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpHeaders headers;\n                InternetMessageFormatHeaderParser parser = InternetMessageFormatHeaderParserTests.CreateHeaderParser(data.Length, out headers);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed;\n                ParserState state = InternetMessageFormatHeaderParserTests.ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Done, state);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                Assert.Single(headers);\n                IEnumerable<string> parsedValues = headers.GetValues(\"N\");\n                Assert.Equal(2, parsedValues.Count());\n                Assert.Equal(\"V1\", parsedValues.ElementAt(0));\n                Assert.Equal(\"V2\", parsedValues.ElementAt(1));\n            }\n        }\n\n        [Fact]\n        public void HeaderParserLwsHeader()\n        {\n            byte[] data = InternetMessageFormatHeaderParserTests.CreateBuffer(\"N1:V1\", \"N2: V2\", \"N3:\\tV3\");\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpHeaders headers;\n                InternetMessageFormatHeaderParser parser = InternetMessageFormatHeaderParserTests.CreateHeaderParser(data.Length, out headers);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = InternetMessageFormatHeaderParserTests.ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Done, state);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                Assert.Equal(3, headers.Count());\n\n                IEnumerable<string> parsedValues = headers.GetValues(\"N1\");\n                string parsedValue = Assert.Single(parsedValues);\n                Assert.Equal(\"V1\", parsedValue);\n\n                parsedValues = headers.GetValues(\"N2\");\n                parsedValue = Assert.Single(parsedValues);\n                Assert.Equal(\"V2\", parsedValue);\n\n                parsedValues = headers.GetValues(\"N3\");\n                parsedValue = Assert.Single(parsedValues);\n                Assert.Equal(\"V3\", parsedValue);\n            }\n        }\n\n        [Fact]\n        public void HeaderParserInvalidHeader()\n        {\n            byte[] data = InternetMessageFormatHeaderParserTests.CreateBuffer(\"N1 :V1\");\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpHeaders headers;\n                InternetMessageFormatHeaderParser parser = InternetMessageFormatHeaderParserTests.CreateHeaderParser(data.Length, out headers);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = InternetMessageFormatHeaderParserTests.ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Invalid, state);\n                Assert.Equal(data.Length - 2, totalBytesConsumed);\n            }\n        }\n\n        [Fact]\n        public void HeaderParserSpecializedHeaders()\n        {\n            Dictionary<string, string> headerData = new Dictionary<string, string>\n            {\n                { @\"JsonProperties0\", @\"{ \"\"SessionId\"\": \"\"{27729E1-B37B-4D29-AA0A-E367906C206E}\"\", \"\"MessageId\"\": \"\"{701332E1-B37B-4D29-AA0A-E367906C206E}\"\", \"\"TimeToLive\"\" : 90, \"\"CorrelationId\"\": \"\"{701332F3-B37B-4D29-AA0A-E367906C206E}\"\", \"\"SequenceNumber\"\" : 12345, \"\"DeliveryCount\"\" : 2, \"\"To\"\" : \"\"http://contoso.com/path1\"\", \"\"ReplyTo\"\" : \"\"http://fabrikam.com/path1\"\",  \"\"SentTimeUtc\"\" : \"\"Sun, 06 Nov 1994 08:49:37 GMT\"\", \"\"ScheduledEnqueueTimeUtc\"\" : \"\"Sun, 06 Nov 1994 08:49:37 GMT\"\"}\" },\n                { @\"JsonProperties1\", @\"{ \"\"SessionId\"\": \"\"{2813D4D2-46A9-4F4D-8904-E9BDE3712B70}\"\", \"\"MessageId\"\": \"\"{24AE31D6-63B8-46F3-9975-A3DAF1B6D3F4}\"\", \"\"TimeToLive\"\" : 80, \"\"CorrelationId\"\": \"\"{896DD5BD-1645-44D7-9E7C-D7F70958ECD6}\"\", \"\"SequenceNumber\"\" : 54321, \"\"DeliveryCount\"\" : 4, \"\"To\"\" : \"\"http://contoso.com/path2\"\", \"\"ReplyTo\"\" : \"\"http://fabrikam.com/path2\"\",  \"\"SentTimeUtc\"\" : \"\"Sun, 06 Nov 1994 10:49:37 GMT\"\", \"\"ScheduledEnqueueTimeUtc\"\" : \"\"Sun, 06 Nov 1994 10:49:37 GMT\"\"}\" },\n                { @\"P3P\", @\"CP=\"\"ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI\"\"\" },\n                { @\"Cookie\", @\"omniID=1297715979621_9f45_1519_3f8a_f22f85346ac6; WT_FPC=id=65.55.227.138-2323234032.30136233:lv=1309374389020:ss=1309374389020; A=I&I=AxUFAAAAAACNCAAADYEZ7CFPss7Swnujy4PXZA!!&M=1&CS=126mAa0002ZB51a02gZB51a; MC1=GUID=568428660ad44d4ab8f46133f4b03738&HASH=6628&LV=20113&V=3; WT_NVR_RU=0=msdn:1=:2=; MUID=A44DE185EA1B4E8088CCF7B348C5D65F; MSID=Microsoft.CreationDate=03/04/2011 23:38:15&Microsoft.LastVisitDate=06/20/2011 04:15:08&Microsoft.VisitStartDate=06/20/2011 04:15:08&Microsoft.CookieId=f658f3f2-e6d6-42ab-b86b-96791b942b6f&Microsoft.TokenId=ffffffff-ffff-ffff-ffff-ffffffffffff&Microsoft.NumberOfVisits=106&Microsoft.CookieFirstVisit=1&Microsoft.IdentityToken=AA==&Microsoft.MicrosoftId=0441-6141-1523-9969; msresearch=%7B%22version%22%3A%224.6%22%2C%22state%22%3A%7B%22name%22%3A%22IDLE%22%2C%22url%22%3Aundefined%2C%22timestamp%22%3A1299281911415%7D%2C%22lastinvited%22%3A1299281911415%2C%22userid%22%3A%2212992819114151265672533023080%22%2C%22vendorid%22%3A1%2C%22surveys%22%3A%5Bundefined%5D%7D; CodeSnippetContainerLang=C#; msdn=L=1033; ADS=SN=175A21EF; s_cc=true; s_sq=%5B%5BB%5D%5D; TocHashCookie=ms310241(n)/aa187916(n)/aa187917(n)/dd273952(n)/dd295083(n)/ff472634(n)/ee667046(n)/ee667070(n)/gg259047(n)/gg618436(n)/; WT_NVR=0=/:1=query|library|en-us:2=en-us/vcsharp|en-us/library\" },\n                { @\"Set-Cookie\", @\"A=I&I=AxUFAAAAAADsBgAA1sWZz4FGun/kOeyV4LGZVg!!&M=1; domain=.microsoft.com; expires=Sun, 30-Jun-2041 00:14:40 GMT; path=/\" },\n            };\n\n            byte[] data = InternetMessageFormatHeaderParserTests.CreateBuffer(headerData.Select((kv) => { return String.Format(\"{0}: {1}\", kv.Key, kv.Value); }).ToArray());\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpHeaders headers;\n                InternetMessageFormatHeaderParser parser = InternetMessageFormatHeaderParserTests.CreateHeaderParser(data.Length, out headers);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = InternetMessageFormatHeaderParserTests.ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Done, state);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                Assert.Equal(headerData.Count, headers.Count());\n                for (int hCnt = 0; hCnt < headerData.Count; hCnt++)\n                {\n                    Assert.Equal(headerData.Keys.ElementAt(hCnt), headers.ElementAt(hCnt).Key);\n                    Assert.Equal(headerData.Values.ElementAt(hCnt), headers.ElementAt(hCnt).Value.ElementAt(0));\n                }\n            }\n        }\n\n        [Fact]\n        public void HeaderParserSplitHeader()\n        {\n            byte[] data = InternetMessageFormatHeaderParserTests.CreateBuffer(\"N:V1,\", \" V2,\", \"\\tV3,\", \"      V4,\", \" \\tV5\");\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpHeaders headers;\n                InternetMessageFormatHeaderParser parser = InternetMessageFormatHeaderParserTests.CreateHeaderParser(data.Length, out headers);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = InternetMessageFormatHeaderParserTests.ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Done, state);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                Assert.Single(headers);\n                IEnumerable<string> parsedValues = headers.GetValues(\"N\");\n                string parsedValue = Assert.Single(parsedValues);\n                Assert.Equal(\"V1, V2, V3,      V4, \\tV5\", parsedValues.ElementAt(0));\n            }\n        }\n\n        [Fact]\n        public void HeaderParserDataTooBigSingle()\n        {\n            byte[] data = InternetMessageFormatHeaderParserTests.CreateBuffer(\"N:V\");\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpHeaders headers;\n                InternetMessageFormatHeaderParser parser = InternetMessageFormatHeaderParserTests.CreateHeaderParser(ParserData.MinHeaderSize, out headers);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = InternetMessageFormatHeaderParserTests.ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.DataTooBig, state);\n                Assert.Equal(ParserData.MinHeaderSize, totalBytesConsumed);\n            }\n        }\n\n        [Fact]\n        public void HeaderParserTestDataTooBigMulti()\n        {\n            byte[] data = InternetMessageFormatHeaderParserTests.CreateBuffer(\"N1:V1\", \"N2:V2\", \"N3:V3\");\n\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpHeaders headers;\n                InternetMessageFormatHeaderParser parser = InternetMessageFormatHeaderParserTests.CreateHeaderParser(10, out headers);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = InternetMessageFormatHeaderParserTests.ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.DataTooBig, state);\n                Assert.Equal(10, totalBytesConsumed);\n            }\n        }\n\n        [Fact]\n        public void Rfc5322Sample1Test()\n        {\n            RunRfc5322SampleTest(Rfc5322Sample1,\n                (headers) =>\n                {\n                    Assert.NotNull(headers);\n                    Assert.True(headers.Contains(\"from\"));\n                    Assert.True(headers.Contains(\"to\"));\n                    Assert.True(headers.Contains(\"subject\"));\n                    Assert.True(headers.Contains(\"date\"));\n                    Assert.True(headers.Contains(\"message-id\"));\n                });\n        }\n\n        [Fact]\n        public void Rfc5322Sample2Test()\n        {\n            RunRfc5322SampleTest(Rfc5322Sample2,\n                (headers) =>\n                {\n                    Assert.NotNull(headers);\n                    Assert.True(headers.Contains(\"from\"));\n                    Assert.True(headers.Contains(\"sender\"));\n                    Assert.True(headers.Contains(\"to\"));\n                    Assert.True(headers.Contains(\"subject\"));\n                    Assert.True(headers.Contains(\"date\"));\n                    Assert.True(headers.Contains(\"message-id\"));\n                });\n        }\n\n        [Fact]\n        public void Rfc5322Sample3Test()\n        {\n            RunRfc5322SampleTest(Rfc5322Sample3,\n                (headers) =>\n                {\n                    Assert.NotNull(headers);\n                    Assert.True(headers.Contains(\"from\"));\n                    Assert.True(headers.Contains(\"to\"));\n                    Assert.True(headers.Contains(\"cc\"));\n                    Assert.True(headers.Contains(\"date\"));\n                    Assert.True(headers.Contains(\"message-id\"));\n                });\n        }\n\n        [Fact]\n        public void Rfc5322Sample4Test()\n        {\n            RunRfc5322SampleTest(Rfc5322Sample4,\n                (headers) =>\n                {\n                    Assert.NotNull(headers);\n                    Assert.True(headers.Contains(\"from\"));\n                    Assert.True(headers.Contains(\"to\"));\n                    Assert.True(headers.Contains(\"cc\"));\n                    Assert.True(headers.Contains(\"date\"));\n                    Assert.True(headers.Contains(\"message-id\"));\n                });\n        }\n\n        [Fact]\n        public void Rfc5322Sample5Test()\n        {\n            RunRfc5322SampleTest(Rfc5322Sample5,\n                (headers) =>\n                {\n                    Assert.NotNull(headers);\n                    Assert.True(headers.Contains(\"from\"));\n                    Assert.True(headers.Contains(\"to\"));\n                    Assert.True(headers.Contains(\"subject\"));\n                    Assert.True(headers.Contains(\"date\"));\n                    Assert.True(headers.Contains(\"message-id\"));\n                });\n        }\n\n        [Fact]\n        public void Rfc5322Sample6Test()\n        {\n            RunRfc5322SampleTest(Rfc5322Sample6,\n                (headers) =>\n                {\n                    Assert.NotNull(headers);\n                    Assert.True(headers.Contains(\"from\"));\n                    Assert.True(headers.Contains(\"to\"));\n                    Assert.True(headers.Contains(\"reply-to\"));\n                    Assert.True(headers.Contains(\"subject\"));\n                    Assert.True(headers.Contains(\"date\"));\n                    Assert.True(headers.Contains(\"message-id\"));\n                    Assert.True(headers.Contains(\"in-reply-to\"));\n                    Assert.True(headers.Contains(\"references\"));\n                });\n        }\n\n        [Fact]\n        public void Rfc5322Sample7Test()\n        {\n            RunRfc5322SampleTest(Rfc5322Sample7,\n                (headers) =>\n                {\n                    Assert.NotNull(headers);\n                    Assert.True(headers.Contains(\"to\"));\n                    Assert.True(headers.Contains(\"from\"));\n                    Assert.True(headers.Contains(\"subject\"));\n                    Assert.True(headers.Contains(\"date\"));\n                    Assert.True(headers.Contains(\"message-id\"));\n                    Assert.True(headers.Contains(\"in-reply-to\"));\n                    Assert.True(headers.Contains(\"references\"));\n                });\n        }\n\n        [Fact]\n        public void Rfc5322Sample8Test()\n        {\n            RunRfc5322SampleTest(Rfc5322Sample8,\n                (headers) =>\n                {\n                    Assert.NotNull(headers);\n                    Assert.True(headers.Contains(\"from\"));\n                    Assert.True(headers.Contains(\"to\"));\n                    Assert.True(headers.Contains(\"subject\"));\n                    Assert.True(headers.Contains(\"date\"));\n                    Assert.True(headers.Contains(\"message-id\"));\n                });\n        }\n\n        [Fact]\n        public void Rfc5322Sample9Test()\n        {\n            RunRfc5322SampleTest(Rfc5322Sample9,\n                (headers) =>\n                {\n                    Assert.NotNull(headers);\n                    Assert.True(headers.Contains(\"resent-from\"));\n                    Assert.True(headers.Contains(\"resent-to\"));\n                    Assert.True(headers.Contains(\"resent-date\"));\n                    Assert.True(headers.Contains(\"resent-message-id\"));\n                    Assert.True(headers.Contains(\"from\"));\n                    Assert.True(headers.Contains(\"to\"));\n                    Assert.True(headers.Contains(\"subject\"));\n                    Assert.True(headers.Contains(\"date\"));\n                    Assert.True(headers.Contains(\"message-id\"));\n                });\n        }\n\n        [Fact]\n        public void Rfc5322Sample10Test()\n        {\n            RunRfc5322SampleTest(Rfc5322Sample10,\n                (headers) =>\n                {\n                    Assert.NotNull(headers);\n                    Assert.True(headers.Contains(\"received\"));\n                    Assert.Equal(2, headers.GetValues(\"received\").Count());\n                    Assert.True(headers.Contains(\"from\"));\n                    Assert.True(headers.Contains(\"to\"));\n                    Assert.True(headers.Contains(\"subject\"));\n                    Assert.True(headers.Contains(\"date\"));\n                    Assert.True(headers.Contains(\"message-id\"));\n                });\n        }\n\n        [Fact]\n        public void Rfc5322Sample11Test()\n        {\n            RunRfc5322SampleTest(Rfc5322Sample11,\n                (headers) =>\n                {\n                    Assert.NotNull(headers);\n                    Assert.True(headers.Contains(\"from\"));\n                    Assert.True(headers.Contains(\"to\"));\n                    Assert.True(headers.Contains(\"cc\"));\n                    Assert.True(headers.Contains(\"date\"));\n                    Assert.True(headers.Contains(\"message-id\"));\n                });\n        }\n\n        // Set of samples from RFC 5322 with times adjusted to GMT following HTTP style for date time format.\n        static readonly string[] Rfc5322Sample1 = new string[] {\n            @\"From: John Doe <jdoe@machine.example>\",\n            @\"To: Mary Smith <mary@example.net>\",\n            @\"Subject: Saying Hello\",\n            @\"Date: Fri, 21 Nov 1997 09:55:06 GMT\",\n            @\"Message-ID: <1234@local.machine.example>\",\n        };\n\n        static readonly string[] Rfc5322Sample2 = new string[] {\n            @\"From: John Doe <jdoe@machine.example>\",\n            @\"Sender: Michael Jones <mjones@machine.example>\",\n            @\"To: Mary Smith <mary@example.net>\",\n            @\"Subject: Saying Hello\",\n            @\"Date: Fri, 21 Nov 1997 09:55:06 GMT\",\n            @\"Message-ID: <1234@local.machine.example>\",\n        };\n\n        static readonly string[] Rfc5322Sample3 = new string[] {\n            @\"From: \"\"Joe Q. Public\"\" <john.q.public@example.com>\",\n            @\"To: Mary Smith <mary@x.test>, jdoe@example.org, Who? <one@y.test>\",\n            @\"Cc: <boss@nil.test>, \"\"Giant; \\\"\"Big\\\"\" Box\"\" <sysservices@example.net>\",\n            @\"Date: Tue, 01 Jul 2003 10:52:37 GMT\",\n            @\"Message-ID: <5678.21-Nov-1997@example.com>\",\n        };\n\n        static readonly string[] Rfc5322Sample4 = new string[] {\n            @\"From: Pete <pete@silly.example>\",\n            @\"To: A Group:Ed Jones <c@a.test>,joe@where.test,John <jdoe@one.test>;\",\n            @\"Cc: Undisclosed recipients:;\",\n            @\"Date: Thu, 13 Feb 1969 23:32:54 GMT\",\n            @\"Message-ID: <testabcd.1234@silly.example>\",\n        };\n\n        static readonly string[] Rfc5322Sample5 = new string[] {\n            @\"From: John Doe <jdoe@machine.example>\",\n            @\"To: Mary Smith <mary@example.net>\",\n            @\"Subject: Saying Hello\",\n            @\"Date: Fri, 21 Nov 1997 09:55:06 GMT\",\n            @\"Message-ID: <1234@local.machine.example>\",\n        };\n\n        static readonly string[] Rfc5322Sample6 = new string[] {\n            @\"From: Mary Smith <mary@example.net>\",\n            @\"To: John Doe <jdoe@machine.example>\",\n            @\"Reply-To: \"\"Mary Smith: Personal Account\"\" <smith@home.example>\",\n            @\"Subject: Re: Saying Hello\",\n            @\"Date: Fri, 21 Nov 1997 10:01:10 GMT\",\n            @\"Message-ID: <3456@example.net>\",\n            @\"In-Reply-To: <1234@local.machine.example>\",\n            @\"References: <1234@local.machine.example>\",\n        };\n\n        static readonly string[] Rfc5322Sample7 = new string[] {\n            @\"To: \"\"Mary Smith: Personal Account\"\" <smith@home.example>\",\n            @\"From: John Doe <jdoe@machine.example>\",\n            @\"Subject: Re: Saying Hello\",\n            @\"Date: Fri, 21 Nov 1997 11:00:00 GMT\",\n            @\"Message-ID: <abcd.1234@local.machine.test>\",\n            @\"In-Reply-To: <3456@example.net>\",\n            @\"References: <1234@local.machine.example> <3456@example.net>\",\n        };\n\n        static readonly string[] Rfc5322Sample8 = new string[] {\n            @\"From: John Doe <jdoe@machine.example>\",\n            @\"To: Mary Smith <mary@example.net>\",\n            @\"Subject: Saying Hello\",\n            @\"Date: Fri, 21 Nov 1997 09:55:06 GMT\",\n            @\"Message-ID: <1234@local.machine.example>\",\n        };\n\n        static readonly string[] Rfc5322Sample9 = new string[] {\n            @\"Resent-From: Mary Smith <mary@example.net>\",\n            @\"Resent-To: Jane Brown <j-brown@other.example>\",\n            @\"Resent-Date: Mon, 24 Nov 1997 14:22:01 GMT\",\n            @\"Resent-Message-ID: <78910@example.net>\",\n            @\"From: John Doe <jdoe@machine.example>\",\n            @\"To: Mary Smith <mary@example.net>\",\n            @\"Subject: Saying Hello\",\n            @\"Date: Fri, 21 Nov 1997 09:55:06 GMT\",\n            @\"Message-ID: <1234@local.machine.example>\",\n        };\n\n        static readonly string[] Rfc5322Sample10 = new string[] {\n            @\"Received: from x.y.test\",\n            @\"   by example.net\",\n            @\"   via TCP\",\n            @\"   with ESMTP\",\n            @\"   id ABC12345\",\n            @\"   for <mary@example.net>;  21 Nov 1997 10:05:43 GMT\",\n            @\"Received: from node.example by x.y.test; 21 Nov 1997 10:01:22 GMT\",\n            @\"From: John Doe <jdoe@node.example>\",\n            @\"To: Mary Smith <mary@example.net>\",\n            @\"Subject: Saying Hello\",\n            @\"Date: Fri, 21 Nov 1997 09:55:06 GMT\",\n            @\"Message-ID: <1234@local.node.example>\",\n        };\n\n        static readonly string[] Rfc5322Sample11 = new string[] {\n            @\"From: Pete(A nice \\) chap) <pete(his account)@silly.test(his host)>\",\n            @\"To:A Group(Some people)\",\n            @\"     :Chris Jones <c@(Chris's host.)public.example>,\",\n            @\"         joe@example.org,\",\n            @\"  John <jdoe@one.test> (my dear friend); (the end of the group)\",\n            @\"Cc:(Empty list)(start)Hidden recipients  :(nobody(that I know))  ;\",\n            @\"Date: Thu,\",\n            @\"      13\",\n            @\"        Feb\",\n            @\"          1969\",\n            @\"      23:32:00\",\n            @\"               GMT\",\n            @\"Message-ID:              <testabcd.1234@silly.test>\",\n        };\n\n        private static IEnumerable<HttpHeaders> CreateHttpHeaders()\n        {\n            return new HttpHeaders[]\n            {\n                new HttpRequestMessage().Headers,\n                new HttpResponseMessage().Headers,\n                new StringContent(String.Empty).Headers,\n            };\n        }\n\n        private static InternetMessageFormatHeaderParser CreateHeaderParser(int maximumHeaderLength, out HttpHeaders headers)\n        {\n            headers = new HttpRequestMessage().Headers;\n            return new InternetMessageFormatHeaderParser(headers, maximumHeaderLength);\n        }\n\n        internal static byte[] CreateBuffer(params string[] headers)\n        {\n            const string CRLF = \"\\r\\n\";\n            StringBuilder header = new StringBuilder();\n            foreach (var h in headers)\n            {\n                header.Append(h + CRLF);\n            }\n\n            header.Append(CRLF);\n            return Encoding.UTF8.GetBytes(header.ToString());\n        }\n\n        private static void RunRfc5322SampleTest(string[] testHeaders, Action<HttpHeaders> validation)\n        {\n            byte[] data = InternetMessageFormatHeaderParserTests.CreateBuffer(testHeaders);\n            for (var cnt = 1; cnt <= data.Length; cnt++)\n            {\n                HttpHeaders headers;\n                InternetMessageFormatHeaderParser parser = InternetMessageFormatHeaderParserTests.CreateHeaderParser(data.Length, out headers);\n                Assert.NotNull(parser);\n\n                int totalBytesConsumed = 0;\n                ParserState state = InternetMessageFormatHeaderParserTests.ParseBufferInSteps(parser, data, cnt, out totalBytesConsumed);\n                Assert.Equal(ParserState.Done, state);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                validation(headers);\n            }\n        }\n\n        private static ParserState ParseBufferInSteps(InternetMessageFormatHeaderParser parser, byte[] buffer, int readsize, out int totalBytesConsumed)\n        {\n            ParserState state = ParserState.Invalid;\n            totalBytesConsumed = 0;\n            while (totalBytesConsumed <= buffer.Length)\n            {\n                int size = Math.Min(buffer.Length - totalBytesConsumed, readsize);\n                byte[] parseBuffer = new byte[size];\n                Buffer.BlockCopy(buffer, totalBytesConsumed, parseBuffer, 0, size);\n\n                int bytesConsumed = 0;\n                state = parser.ParseBuffer(parseBuffer, parseBuffer.Length, ref bytesConsumed);\n                totalBytesConsumed += bytesConsumed;\n\n                if (state != ParserState.NeedMoreData)\n                {\n                    return state;\n                }\n            }\n\n            return state;\n        }\n    }\n}"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/Parsers/MimeMultipartParserTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Formatting.Parsers\n{\n    public class MimeMultipartParserTests\n    {\n        private const string SP = \" \";\n        private const string LF = \"\\n\";\n        private const string CR = \"\\r\";\n        private const string CRLF = \"\\r\\n\";\n        private const string HTAB = \"\\t\";\n        private const string DashDash = \"--\";\n\n        public static TheoryDataSet<string> Boundaries\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    \"1\",\n                    \"a\",\n                    \"'()+_--./:=?\",\n                    \"--\",\n                    \"----\",\n                    \"9df4e21f-6e6f-4b08-8023-97283d2afeeb\",\n                    \"-----------------------------7d159c1302d0y0\",\n                    \"--------------------01234567890123456789\",\n                    \"--------------------01234567890123456789--------------------\",\n                    \"--A--B--C--D--E--F--\",\n                };\n            }\n        }\n\n        public static TheoryDataSet<string> SingleShortBodies\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    \"\",\n                    \"A\",\n                    \"AA\",\n                };\n            }\n        }\n\n        public static TheoryDataSet<string[]> MultipleShortBodies\n        {\n            get\n            {\n                return new TheoryDataSet<string[]>\n                {\n                    CreateMultipleShortBodies(\"\", 26),\n                    CreateMultipleShortBodies(\"{0}\", 26),\n                    CreateMultipleShortBodies(\"--{0}\", 26),\n                };\n            }\n        }\n\n        public static TheoryDataSet<string> SingleLongBodies\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    CreateLongString(\"1234567890\", \"A\", 128),\n                    CreateLongString(\"1234567890\", \"--\", 128),\n                };\n            }\n        }\n\n        public static TheoryDataSet<string[]> MultipleLongBodies\n        {\n            get\n            {\n                string[] result = new string[16];\n                for (int count = 0; count < result.Length; count++)\n                {\n                    string bookend = Char.ConvertFromUtf32(0x41 + count);\n                    result[count] = CreateLongString(\"1234567890\", bookend, 16);\n                }\n\n                return new TheoryDataSet<string[]>\n                {\n                    result\n                };\n            }\n        }\n\n        public static TheoryDataSet<string> NearBoundaryBodies\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    \"AAA\" + LF,\n                    \"AAA\" + CR,\n                    \"AAA\" + CRLF,\n                    \"AAA\" + CRLF + CRLF,\n                    \"AAA\" + CRLF + \"-\",\n                    \"AAA\" + CRLF + \"-\" + CR,\n                    \"AAA\" + CRLF + \"=\" + CRLF,\n                    CR + \"-\" + \"AAA\",\n                    CRLF + \"-\" + \"AAA\",\n                    CRLF + \"--\" + \"AAA\" + CR + \"AAA\",\n                    CRLF,\n                    \"AAA\",\n                    CRLF + CRLF,\n                    CRLF + CRLF + CRLF,\n                    \"AAA\" + \"--\" + \"AAA\",\n                    CRLF + \"AAA\" + \"--\" + \"AAA\" + \"--\",\n                    CRLF + \"--\" + \"AAA\" + CRLF,\n                    CRLF + \"--\" + \"AAA\" + CRLF + CRLF,\n                    CRLF + \"--\" + \"AAA\" + \"--\" + CRLF,\n                    CRLF + \"--\" + \"AAA\" + \"--\" + CRLF + CRLF,\n                    \"--úN\u001b$(Os#»Í\u001b(Bt\u001b$(Dqf\u001b(CS'.Â‚\u000fæ0\u0002j\",\n                    \"--123456\",\n                    \"123--456\",\n                    \"123456--\"\n                };\n            }\n        }\n\n        public static TheoryDataSet<bool> TrueAndFalse\n        {\n            get\n            {\n                return new TheoryDataSet<bool>\n                {\n                    true,\n                    false,\n                };\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(MimeMultipartParserTests), \"Boundaries\")]\n        public void MimeMultipartParserConstructorTest(string boundary)\n        {\n            MimeMultipartParser parser = new MimeMultipartParser(boundary, ParserData.MinMessageSize);\n\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(() => new MimeMultipartParser(\"-\", ParserData.MinMessageSize - 1),\n                \"maxMessageSize\", ParserData.MinMessageSize.ToString(), ParserData.MinMessageSize - 1);\n\n            foreach (string empty in TestData.EmptyStrings)\n            {\n                Assert.ThrowsArgument(() => { new MimeMultipartParser(empty, ParserData.MinMessageSize); }, \"boundary\", allowDerivedExceptions: true);\n            }\n\n            Assert.ThrowsArgument(() => { new MimeMultipartParser(\"trailingspace \", ParserData.MinMessageSize); }, \"boundary\");\n\n            Assert.ThrowsArgumentNull(() => { new MimeMultipartParser(null, ParserData.MinMessageSize); }, \"boundary\");\n        }\n\n        [Fact]\n        public void MimeMultipartParser_ThrowsOnTooBigBoundary()\n        {\n            string maxLegalBoundary = new string('a', 246);\n            MimeMultipartParser parser = new MimeMultipartParser(maxLegalBoundary, ParserData.MinMessageSize);\n\n            string minIllegalBoundary = new string('a', 247);\n            Assert.ThrowsArgumentLessThanOrEqualTo(() => new MimeMultipartParser(minIllegalBoundary, ParserData.MinMessageSize),\n                \"boundary\", \"246\", \"247\");\n        }\n\n        [Fact]\n        public void MultipartParserNullBuffer()\n        {\n            MimeMultipartParser parser = CreateMimeMultipartParser(\"-\", 128);\n\n            int bytesConsumed = 0;\n            ArraySegment<byte> out1;\n            ArraySegment<byte> out2;\n            bool isFinal;\n            Assert.ThrowsArgumentNull(() => { parser.ParseBuffer(null, 0, ref bytesConsumed, out out1, out out2, out isFinal); }, \"buffer\");\n        }\n\n        [Theory]\n        [TestDataSet(typeof(MimeMultipartParserTests), \"Boundaries\")]\n        public void MultipartParserEmptyBuffer(string boundary)\n        {\n            byte[] data = CreateBuffer(boundary);\n\n            for (var readSize = 1; readSize <= data.Length; readSize++)\n            {\n                MimeMultipartParser parser = CreateMimeMultipartParser(boundary);\n\n\n                int totalBytesConsumed;\n                List<string> bodyParts;\n                MimeMultipartParser.State state = ParseBufferInSteps(parser, data, readSize, out bodyParts, out totalBytesConsumed);\n                Assert.Equal(MimeMultipartParser.State.BodyPartCompleted, state);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                Assert.Equal(2, bodyParts.Count);\n                Assert.Equal(0, bodyParts[0].Length);\n                Assert.Equal(0, bodyParts[1].Length);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(MimeMultipartParserTests), \"Boundaries\",\n            typeof(MimeMultipartParserTests), \"TrueAndFalse\",\n            typeof(MimeMultipartParserTests), \"TrueAndFalse\",\n            typeof(MimeMultipartParserTests), \"SingleShortBodies\")]\n        public void MultipartParserSingleShortBodyPart(string boundary, bool withExtraWhitespace, bool withExtraCRLF, string singleShortBody)\n        {\n            byte[] data = CreateBuffer(boundary, withExtraWhitespace, withExtraCRLF, singleShortBody);\n\n            for (var readSize = 1; readSize <= data.Length; readSize++)\n            {\n                MimeMultipartParser parser = CreateMimeMultipartParser(boundary);\n\n                int totalBytesConsumed;\n                List<string> bodyParts;\n                MimeMultipartParser.State state = ParseBufferInSteps(parser, data, readSize, out bodyParts, out totalBytesConsumed);\n                Assert.Equal(MimeMultipartParser.State.BodyPartCompleted, state);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                Assert.Equal(2, bodyParts.Count);\n                Assert.Equal(0, bodyParts[0].Length);\n                Assert.Equal(singleShortBody, bodyParts[1]);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(MimeMultipartParserTests), \"Boundaries\",\n            typeof(MimeMultipartParserTests), \"TrueAndFalse\",\n            typeof(MimeMultipartParserTests), \"TrueAndFalse\",\n            typeof(MimeMultipartParserTests), \"MultipleShortBodies\")]\n        public void MultipartParserMultipleShortBodyParts(string boundary, bool withExtraWhitespace, bool withExtraCRLF, string[] multipleShortBodies)\n        {\n            byte[] data = CreateBuffer(boundary, withExtraWhitespace, withExtraCRLF, multipleShortBodies);\n\n            for (var readSize = 1; readSize <= data.Length; readSize++)\n            {\n                MimeMultipartParser parser = CreateMimeMultipartParser(boundary);\n\n                int totalBytesConsumed;\n                List<string> bodyParts;\n                MimeMultipartParser.State state = ParseBufferInSteps(parser, data, readSize, out bodyParts, out totalBytesConsumed);\n                Assert.Equal(MimeMultipartParser.State.BodyPartCompleted, state);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                Assert.Equal(multipleShortBodies.Length + 1, bodyParts.Count);\n                Assert.Equal(0, bodyParts[0].Length);\n\n                for (var check = 0; check < multipleShortBodies.Length; check++)\n                {\n                    Assert.Equal(multipleShortBodies[check], bodyParts[check + 1]);\n                }\n            }\n        }\n\n\n        [Theory]\n        [TestDataSet(\n            typeof(MimeMultipartParserTests), \"Boundaries\",\n            typeof(MimeMultipartParserTests), \"TrueAndFalse\",\n            typeof(MimeMultipartParserTests), \"TrueAndFalse\",\n            typeof(MimeMultipartParserTests), \"SingleLongBodies\")]\n        public void MultipartParserSingleLongBodyPart(string boundary, bool withExtraWhitespace, bool withExtraCRLF, string singleLongBody)\n        {\n            byte[] data = CreateBuffer(boundary, withExtraWhitespace, withExtraCRLF, singleLongBody);\n\n            for (var readSize = 1; readSize <= data.Length; readSize++)\n            {\n                MimeMultipartParser parser = CreateMimeMultipartParser(boundary);\n\n                int totalBytesConsumed;\n                List<string> bodyParts;\n                MimeMultipartParser.State state = ParseBufferInSteps(parser, data, readSize, out bodyParts, out totalBytesConsumed);\n                Assert.Equal(MimeMultipartParser.State.BodyPartCompleted, state);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                Assert.Equal(2, bodyParts.Count);\n                Assert.Equal(0, bodyParts[0].Length);\n\n                Assert.Equal(singleLongBody.Length, bodyParts[1].Length);\n                Assert.Equal(singleLongBody, bodyParts[1]);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(MimeMultipartParserTests), \"Boundaries\",\n            typeof(MimeMultipartParserTests), \"TrueAndFalse\",\n            typeof(MimeMultipartParserTests), \"TrueAndFalse\",\n            typeof(MimeMultipartParserTests), \"MultipleLongBodies\")]\n        public void MultipartParserMultipleLongBodyParts(string boundary, bool withExtraWhitespace, bool withExtraCRLF, string[] multipleLongBodies)\n        {\n            byte[] data = CreateBuffer(boundary, withExtraWhitespace, withExtraCRLF, multipleLongBodies);\n\n            for (var readSize = 1; readSize <= data.Length; readSize++)\n            {\n                MimeMultipartParser parser = CreateMimeMultipartParser(boundary);\n\n                int totalBytesConsumed;\n                List<string> bodyParts;\n                MimeMultipartParser.State state = ParseBufferInSteps(parser, data, readSize, out bodyParts, out totalBytesConsumed);\n                Assert.Equal(MimeMultipartParser.State.BodyPartCompleted, state);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                Assert.Equal(multipleLongBodies.Length + 1, bodyParts.Count);\n                Assert.Equal(0, bodyParts[0].Length);\n\n                for (var check = 0; check < multipleLongBodies.Length; check++)\n                {\n                    Assert.Equal(multipleLongBodies[check], bodyParts[check + 1]);\n                }\n            }\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(MimeMultipartParserTests), \"Boundaries\",\n            typeof(MimeMultipartParserTests), \"TrueAndFalse\",\n            typeof(MimeMultipartParserTests), \"TrueAndFalse\",\n            typeof(MimeMultipartParserTests), \"NearBoundaryBodies\")]\n        public void MultipartParserNearMatches(string boundary, bool withExtraWhitespace, bool withExtraCRLF, string nearBoundaryBody)\n        {\n            byte[] data = CreateBuffer(boundary, withExtraWhitespace, withExtraCRLF, nearBoundaryBody);\n\n            for (var readSize = 1; readSize <= data.Length; readSize++)\n            {\n                MimeMultipartParser parser = CreateMimeMultipartParser(boundary);\n\n                int totalBytesConsumed;\n                List<string> bodyParts;\n                MimeMultipartParser.State state = ParseBufferInSteps(parser, data, readSize, out bodyParts, out totalBytesConsumed);\n                Assert.Equal(MimeMultipartParser.State.BodyPartCompleted, state);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                Assert.Equal(2, bodyParts.Count);\n                Assert.Equal(0, bodyParts[0].Length);\n                Assert.Equal(nearBoundaryBody, bodyParts[1]);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(MimeMultipartParserTests), \"Boundaries\")]\n        public void MultipartParserNesting(string boundary)\n        {\n            for (var nesting = 0; nesting < 16; nesting++)\n            {\n                string nested = CreateNestedBuffer(nesting);\n\n                byte[] data = CreateBuffer(boundary, nested);\n\n                for (var readSize = 1; readSize <= data.Length; readSize++)\n                {\n                    MimeMultipartParser parser = CreateMimeMultipartParser(boundary);\n\n                    int totalBytesConsumed;\n                    List<string> bodyParts;\n                    MimeMultipartParser.State state = ParseBufferInSteps(parser, data, readSize, out bodyParts, out totalBytesConsumed);\n                    Assert.Equal(MimeMultipartParser.State.BodyPartCompleted, state);\n                    Assert.Equal(data.Length, totalBytesConsumed);\n\n                    Assert.Equal(2, bodyParts.Count);\n                    Assert.Equal(0, bodyParts[0].Length);\n                    Assert.Equal(nested.Length, bodyParts[1].Length);\n                }\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(MimeMultipartParserTests), \"Boundaries\")]\n        public void MimeMultipartParserTestDataTooBig(string boundary)\n        {\n            byte[] data = CreateBuffer(boundary);\n\n            for (var readSize = 1; readSize <= data.Length; readSize++)\n            {\n                MimeMultipartParser parser = CreateMimeMultipartParser(boundary, ParserData.MinMessageSize);\n\n                int totalBytesConsumed;\n                List<string> bodyParts;\n                MimeMultipartParser.State state = ParseBufferInSteps(parser, data, readSize, out bodyParts, out totalBytesConsumed);\n                Assert.Equal(MimeMultipartParser.State.DataTooBig, state);\n                Assert.Equal(ParserData.MinMessageSize, totalBytesConsumed);\n            }\n        }\n\n        [Fact]\n        public void MaxMessageSizeIsExact()\n        {\n            string boundary = \"--A\";\n            byte[] data = CreateBuffer(boundary, \"cool\");\n\n            for (var readSize = 1; readSize <= data.Length; readSize++)\n            {\n                MimeMultipartParser parser = CreateMimeMultipartParser(boundary, data.Length);\n\n                int totalBytesConsumed;\n                List<string> bodyParts;\n                MimeMultipartParser.State state = ParseBufferInSteps(parser, data, 2, out bodyParts, out totalBytesConsumed);\n                Assert.Equal(MimeMultipartParser.State.BodyPartCompleted, state);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                Assert.Equal(2, bodyParts.Count);\n                Assert.Empty(bodyParts[0]);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(MimeMultipartParserTests), \"Boundaries\")]\n        public async Task MimeMultipartParserTestMultipartContent(string boundary)\n        {\n            MultipartContent content = new MultipartContent(\"mixed\", boundary);\n            content.Add(new StringContent(\"A\"));\n            content.Add(new StringContent(\"B\"));\n            content.Add(new StringContent(\"C\"));\n\n            MemoryStream memStream = new MemoryStream();\n            await content.CopyToAsync(memStream);\n            memStream.Position = 0;\n            byte[] data = memStream.ToArray();\n\n            for (var readSize = 1; readSize <= data.Length; readSize++)\n            {\n                MimeMultipartParser parser = CreateMimeMultipartParser(boundary);\n\n                int totalBytesConsumed;\n                List<string> bodyParts;\n                MimeMultipartParser.State state = ParseBufferInSteps(parser, data, readSize, out bodyParts, out totalBytesConsumed);\n                Assert.Equal(MimeMultipartParser.State.BodyPartCompleted, state);\n                Assert.Equal(data.Length, totalBytesConsumed);\n\n                Assert.Equal(4, bodyParts.Count);\n                Assert.Empty(bodyParts[0]);\n\n                Assert.EndsWith(\"A\", bodyParts[1]);\n                Assert.EndsWith(\"B\", bodyParts[2]);\n                Assert.EndsWith(\"C\", bodyParts[3]);\n            }\n        }\n\n        private static MimeMultipartParser CreateMimeMultipartParser(string boundary)\n        {\n            return new MimeMultipartParser(boundary, MimeMultipartBodyPartParser.DefaultMaxMessageSize);\n        }\n\n        private static MimeMultipartParser CreateMimeMultipartParser(string boundary, int minimumLength)\n        {\n            return new MimeMultipartParser(boundary, minimumLength);\n        }\n\n        internal static byte[] CreateBuffer(string boundary, params string[] bodyparts)\n        {\n            return CreateBuffer(boundary, false, false, bodyparts);\n        }\n\n        internal static string CreateNestedBuffer(int count)\n        {\n            StringBuilder buffer = new StringBuilder(\"content\");\n\n            for (var readSize = 0; readSize < count; readSize++)\n            {\n                byte[] nested = CreateBuffer(\"N\" + readSize.ToString(), buffer.ToString());\n                var message = Encoding.UTF8.GetString(nested);\n                buffer.Length = 0;\n                buffer.AppendLine(message);\n            }\n\n            return buffer.ToString();\n        }\n\n        private static byte[] CreateBuffer(string boundary, bool withExtraWhitespace, bool withTrailingCRLF, params string[] bodyparts)\n        {\n            string whitespace = String.Empty;\n            if (withExtraWhitespace)\n            {\n                whitespace = SP + SP + HTAB + SP;\n            }\n\n            StringBuilder message = new StringBuilder();\n            message.Append(DashDash + boundary + whitespace + CRLF);\n            for (var i = 0; i < bodyparts.Length; i++)\n            {\n                message.Append(bodyparts[i]);\n                if (i < bodyparts.Length - 1)\n                {\n                    message.Append(CRLF + DashDash + boundary + whitespace + CRLF);\n                }\n            }\n\n            message.Append(CRLF + DashDash + boundary + DashDash + whitespace);\n            if (withTrailingCRLF)\n            {\n                message.Append(CRLF);\n            }\n\n            return Encoding.UTF8.GetBytes(message.ToString());\n        }\n\n        private static MimeMultipartParser.State ParseBufferInSteps(MimeMultipartParser parser, byte[] buffer, int readsize, out List<string> bodyParts, out int totalBytesConsumed)\n        {\n            MimeMultipartParser.State state = MimeMultipartParser.State.Invalid;\n            totalBytesConsumed = 0;\n            bodyParts = new List<string>();\n            bool isFinal = false;\n            byte[] currentBodyPart = new byte[32 * 1024];\n            int currentBodyLength = 0;\n\n            while (true)\n            {\n                int size = Math.Min(buffer.Length - totalBytesConsumed, readsize);\n                byte[] parseBuffer = new byte[size];\n                Buffer.BlockCopy(buffer, totalBytesConsumed, parseBuffer, 0, size);\n\n                int bytesConsumed = 0;\n                ArraySegment<byte> out1;\n                ArraySegment<byte> out2;\n                state = parser.ParseBuffer(parseBuffer, parseBuffer.Length, ref bytesConsumed, out out1, out out2, out isFinal);\n                totalBytesConsumed += bytesConsumed;\n\n                Buffer.BlockCopy(out1.Array, out1.Offset, currentBodyPart, currentBodyLength, out1.Count);\n                currentBodyLength += out1.Count;\n\n                Buffer.BlockCopy(out2.Array, out2.Offset, currentBodyPart, currentBodyLength, out2.Count);\n                currentBodyLength += out2.Count;\n\n                if (state == MimeMultipartParser.State.BodyPartCompleted)\n                {\n                    var bPart = new byte[currentBodyLength];\n                    Buffer.BlockCopy(currentBodyPart, 0, bPart, 0, currentBodyLength);\n                    bodyParts.Add(Encoding.UTF8.GetString(bPart));\n                    currentBodyLength = 0;\n                    if (isFinal)\n                    {\n                        break;\n                    }\n                }\n                else if (state != MimeMultipartParser.State.NeedMoreData)\n                {\n                    return state;\n                }\n            }\n\n            Assert.True(isFinal, \"The last segment is not a final segment.\");\n            return state;\n        }\n\n        private static string[] CreateMultipleShortBodies(string format, int iterations)\n        {\n            string[] result = new string[iterations];\n            for (int count = 0; count < iterations; count++)\n            {\n                result[count] = string.Format(format, Char.ConvertFromUtf32(0x41 + count));\n            }\n            return result;\n        }\n\n        private static string CreateLongString(string msg, string bookend, int iterations)\n        {\n            StringBuilder longBody = new StringBuilder();\n            if (!String.IsNullOrEmpty(bookend))\n            {\n                longBody.Append(bookend);\n            }\n\n            for (int i = 0; i < iterations; i++)\n            {\n                longBody.Append(msg);\n            }\n\n            if (!String.IsNullOrEmpty(bookend))\n            {\n                longBody.Append(bookend);\n            }\n\n            return longBody.ToString();\n        }\n    }\n}"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/QueryStringMappingTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http.Formatting.DataSets;\nusing System.Net.Http.Headers;\nusing System.Web.Http;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Formatting\n{\n    public class QueryStringMappingTests\n    {\n        public static IEnumerable<string> UriStringsWithoutQuery\n        {\n            get\n            {\n                return HttpTestData.UriTestDataStrings.Where((s) => !s.Contains('?'));\n            }\n        }\n\n        [Fact]\n        public void TypeIsCorrect()\n        {\n            Assert.Type.HasProperties(\n                typeof(QueryStringMapping),\n                TypeAssert.TypeProperties.IsPublicVisibleClass,\n                typeof(MediaTypeMapping));\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalQueryStringParameterNames\",\n            typeof(HttpTestData), \"LegalQueryStringParameterValues\",\n            typeof(HttpTestData), \"LegalMediaTypeHeaderValues\")]\n        public void Constructor(string queryStringParameterName, string queryStringParameterValue, MediaTypeHeaderValue mediaType)\n        {\n            QueryStringMapping mapping = new QueryStringMapping(queryStringParameterName, queryStringParameterValue, mediaType);\n            Assert.Equal(queryStringParameterName, mapping.QueryStringParameterName);\n            Assert.Equal(queryStringParameterValue, mapping.QueryStringParameterValue);\n            Assert.MediaType.AreEqual(mediaType, mapping.MediaType, \"MediaType failed to set.\");\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalMediaTypeHeaderValues\",\n            typeof(CommonUnitTestDataSets), \"EmptyStrings\")]\n        public void ConstructorThrowsWithEmptyQueryParameterName(MediaTypeHeaderValue mediaType, string queryStringParameterName)\n        {\n            Assert.ThrowsArgumentNull(() => new QueryStringMapping(queryStringParameterName, \"json\", mediaType), \"queryStringParameterName\");\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalMediaTypeHeaderValues\",\n            typeof(CommonUnitTestDataSets), \"EmptyStrings\")]\n        public void ConstructorThrowsWithEmptyQueryParameterValue(MediaTypeHeaderValue mediaType, string queryStringParameterValue)\n        {\n            Assert.ThrowsArgumentNull(() => new QueryStringMapping(\"query\", queryStringParameterValue, mediaType), \"queryStringParameterValue\");\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalQueryStringParameterNames\",\n            typeof(HttpTestData), \"LegalQueryStringParameterValues\")]\n        public void ConstructorThrowsWithNullMediaTypeHeaderValue(string queryStringParameterName, string queryStringParameterValue)\n        {\n            Assert.ThrowsArgumentNull(() => new QueryStringMapping(queryStringParameterName, queryStringParameterValue, (MediaTypeHeaderValue)null), \"mediaType\");\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalQueryStringParameterNames\",\n            typeof(HttpTestData), \"LegalQueryStringParameterValues\",\n            typeof(HttpTestData), \"LegalMediaTypeStrings\")]\n        public void Constructor1(string queryStringParameterName, string queryStringParameterValue, string mediaType)\n        {\n            QueryStringMapping mapping = new QueryStringMapping(queryStringParameterName, queryStringParameterValue, mediaType);\n            Assert.Equal(queryStringParameterName, mapping.QueryStringParameterName);\n            Assert.Equal(queryStringParameterValue, mapping.QueryStringParameterValue);\n            Assert.MediaType.AreEqual(mediaType, mapping.MediaType, \"MediaType failed to set.\");\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalMediaTypeStrings\",\n            typeof(CommonUnitTestDataSets), \"EmptyStrings\")]\n        public void Constructor1ThrowsWithEmptyQueryParameterName(string mediaType, string queryStringParameterName)\n        {\n            Assert.ThrowsArgumentNull(() => new QueryStringMapping(queryStringParameterName, \"json\", mediaType), \"queryStringParameterName\");\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalMediaTypeStrings\",\n            typeof(CommonUnitTestDataSets), \"EmptyStrings\")]\n        public void Constructor1ThrowsWithEmptyQueryParameterValue(string mediaType, string queryStringParameterValue)\n        {\n            Assert.ThrowsArgumentNull(() => new QueryStringMapping(\"query\", queryStringParameterValue, mediaType), \"queryStringParameterValue\");\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalQueryStringParameterNames\",\n            typeof(HttpTestData), \"LegalQueryStringParameterValues\",\n            typeof(CommonUnitTestDataSets), \"EmptyStrings\")]\n        public void Constructor1ThrowsWithEmptyMediaType(string queryStringParameterName, string queryStringParameterValue, string mediaType)\n        {\n            GC.KeepAlive(mediaType); // Mark parameter as used. See xUnit1026, [Theory] method doesn't use all parameters.\n            Assert.ThrowsArgumentNull(() => new QueryStringMapping(queryStringParameterName, queryStringParameterValue, (MediaTypeHeaderValue)null), \"mediaType\");\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalQueryStringParameterNames\",\n            typeof(HttpTestData), \"LegalQueryStringParameterValues\",\n            typeof(HttpTestData), \"LegalMediaTypeStrings\",\n            typeof(QueryStringMappingTests), \"UriStringsWithoutQuery\")]\n        public void TryMatchMediaTypeReturnsMatchWithQueryStringParameterNameAndValueInUri(string queryStringParameterName, string queryStringParameterValue, string mediaType, string uriBase)\n        {\n            QueryStringMapping mapping = new QueryStringMapping(queryStringParameterName, queryStringParameterValue, mediaType);\n            string uri = uriBase + \"?\" + queryStringParameterName + \"=\" + queryStringParameterValue;\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri);\n            Assert.Equal(1.0, mapping.TryMatchMediaType(request));\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalQueryStringParameterNames\",\n            typeof(HttpTestData), \"LegalQueryStringParameterValues\",\n            typeof(HttpTestData), \"LegalMediaTypeStrings\",\n            typeof(QueryStringMappingTests), \"UriStringsWithoutQuery\")]\n        public void TryMatchMediaTypeReturnsZeroWithQueryStringParameterNameNotInUri(string queryStringParameterName, string queryStringParameterValue, string mediaType, string uriBase)\n        {\n            QueryStringMapping mapping = new QueryStringMapping(queryStringParameterName, queryStringParameterValue, mediaType);\n            string uri = uriBase + \"?\" + \"not\" + queryStringParameterName + \"=\" + queryStringParameterValue;\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri);\n            Assert.Equal(0.0, mapping.TryMatchMediaType(request));\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalQueryStringParameterNames\",\n            typeof(HttpTestData), \"LegalQueryStringParameterValues\",\n            typeof(HttpTestData), \"LegalMediaTypeStrings\",\n            typeof(QueryStringMappingTests), \"UriStringsWithoutQuery\")]\n        public void TryMatchMediaTypeReturnsZeroWithQueryStringParameterValueNotInUri(string queryStringParameterName, string queryStringParameterValue, string mediaType, string uriBase)\n        {\n            QueryStringMapping mapping = new QueryStringMapping(queryStringParameterName, queryStringParameterValue, mediaType);\n            string uri = uriBase + \"?\" + queryStringParameterName + \"=\" + \"not\" + queryStringParameterValue;\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri);\n            Assert.Equal(0.0, mapping.TryMatchMediaType(request));\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalQueryStringParameterNames\",\n            typeof(HttpTestData), \"LegalQueryStringParameterValues\",\n            typeof(HttpTestData), \"LegalMediaTypeStrings\")]\n        public void TryMatchMediaTypeThrowsWithNullHttpRequestMessage(string queryStringParameterName, string queryStringParameterValue, string mediaType)\n        {\n            QueryStringMapping mapping = new QueryStringMapping(queryStringParameterName, queryStringParameterValue, mediaType);\n            Assert.ThrowsArgumentNull(() => mapping.TryMatchMediaType(request: null), \"request\");\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalQueryStringParameterNames\",\n            typeof(HttpTestData), \"LegalQueryStringParameterValues\",\n            typeof(HttpTestData), \"LegalMediaTypeStrings\")]\n        public void TryMatchMediaTypeThrowsWithNullUriInHttpRequestMessage(string queryStringParameterName, string queryStringParameterValue, string mediaType)\n        {\n            QueryStringMapping mapping = new QueryStringMapping(queryStringParameterName, queryStringParameterValue, mediaType);\n            string errorMessage = Error.Format(Properties.Resources.NonNullUriRequiredForMediaTypeMapping, typeof(QueryStringMapping).Name);\n            Assert.Throws<InvalidOperationException>(() => mapping.TryMatchMediaType(new HttpRequestMessage()), errorMessage);\n        }\n\n        [Theory]\n        [InlineData(\"nAmE\", \"VaLuE\", \"name=value\")]\n        [InlineData(\"Format\", \"Xml\", \"format=xml\")]\n        public void TryMatchMediaTypeIsCaseInsensitive(string name, string value, string query)\n        {\n            QueryStringMapping mapping = new QueryStringMapping(name, value, \"application/json\");\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, \"http://localhost/?\" + query);\n            Assert.Equal(1.0, mapping.TryMatchMediaType(request));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/RequestHeaderMappingTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Formatting.DataSets;\nusing System.Net.Http.Headers;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Formatting\n{\n    public class RequestHeaderMappingTests\n    {\n        [Fact]\n        public void TypeIsCorrect()\n        {\n            Assert.Type.HasProperties(\n                typeof(RequestHeaderMapping),\n                TypeAssert.TypeProperties.IsPublicVisibleClass,\n                typeof(MediaTypeMapping));\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalHttpHeaderNames\",\n            typeof(HttpTestData), \"LegalHttpHeaderValues\",\n            typeof(HttpTestData), \"LegalMediaTypeHeaderValues\")]\n        public void Constructor(string headerName, string headerValue, MediaTypeHeaderValue mediaType)\n        {\n            RequestHeaderMapping mapping = new RequestHeaderMapping(headerName, headerValue, StringComparison.CurrentCulture, true, mediaType);\n            Assert.Equal(headerName, mapping.HeaderName);\n            Assert.Equal(headerValue, mapping.HeaderValue);\n            Assert.Equal(StringComparison.CurrentCulture, mapping.HeaderValueComparison);\n            Assert.True(mapping.IsValueSubstring);\n            Assert.MediaType.AreEqual(mediaType, mapping.MediaType, \"MediaType failed to set.\");\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalMediaTypeHeaderValues\",\n            typeof(CommonUnitTestDataSets), \"EmptyStrings\")]\n        public void ConstructorThrowsWithEmptyHeaderName(MediaTypeHeaderValue mediaType, string headerName)\n        {\n            Assert.ThrowsArgumentNull(() => new RequestHeaderMapping(headerName, \"value\", StringComparison.CurrentCulture, false, mediaType), \"headerName\");\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalMediaTypeHeaderValues\",\n            typeof(CommonUnitTestDataSets), \"EmptyStrings\")]\n        public void ConstructorThrowsWithEmptyHeaderValue(MediaTypeHeaderValue mediaType, string headerValue)\n        {\n            Assert.ThrowsArgumentNull(() => new RequestHeaderMapping(\"name\", headerValue, StringComparison.CurrentCulture, false, mediaType), \"headerValue\");\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalHttpHeaderNames\",\n            typeof(HttpTestData), \"LegalHttpHeaderValues\")]\n        public void ConstructorThrowsWithNullMediaTypeHeaderValue(string headerName, string headerValue)\n        {\n            Assert.ThrowsArgumentNull(() => new RequestHeaderMapping(headerName, headerValue, StringComparison.CurrentCulture, false, (MediaTypeHeaderValue)null), \"mediaType\");\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalHttpHeaderNames\",\n            typeof(HttpTestData), \"LegalHttpHeaderValues\",\n            typeof(HttpTestData), \"LegalMediaTypeHeaderValues\")]\n        public void ConstructorThrowsWithInvalidStringComparison(string headerName, string headerValue, MediaTypeHeaderValue mediaType)\n        {\n            int invalidValue = 999;\n            Assert.ThrowsInvalidEnumArgument(() => new RequestHeaderMapping(headerName, headerValue, (StringComparison)invalidValue, false, mediaType),\n                \"valueComparison\", invalidValue, typeof(StringComparison));\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalHttpHeaderNames\",\n            typeof(HttpTestData), \"LegalHttpHeaderValues\",\n            typeof(HttpTestData), \"LegalMediaTypeStrings\")]\n        public void Constructor1(string headerName, string headerValue, string mediaType)\n        {\n            RequestHeaderMapping mapping = new RequestHeaderMapping(headerName, headerValue, StringComparison.CurrentCulture, true, mediaType);\n            Assert.Equal(headerName, mapping.HeaderName);\n            Assert.Equal(headerValue, mapping.HeaderValue);\n            Assert.Equal(StringComparison.CurrentCulture, mapping.HeaderValueComparison);\n            Assert.True(mapping.IsValueSubstring);\n            Assert.MediaType.AreEqual(mediaType, mapping.MediaType, \"MediaType failed to set.\");\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalMediaTypeStrings\",\n            typeof(CommonUnitTestDataSets), \"EmptyStrings\")]\n        public void Constructor1ThrowsWithEmptyHeaderName(string mediaType, string headerName)\n        {\n            Assert.ThrowsArgumentNull(() => new RequestHeaderMapping(headerName, \"value\", StringComparison.CurrentCulture, false, mediaType), \"headerName\");\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalMediaTypeStrings\",\n            typeof(CommonUnitTestDataSets), \"EmptyStrings\")]\n        public void Constructor1ThrowsWithEmptyHeaderValue(string mediaType, string headerValue)\n        {\n            Assert.ThrowsArgumentNull(() => new RequestHeaderMapping(\"name\", headerValue, StringComparison.CurrentCulture, false, mediaType), \"headerValue\");\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalHttpHeaderNames\",\n            typeof(HttpTestData), \"LegalHttpHeaderValues\",\n            typeof(CommonUnitTestDataSets), \"EmptyStrings\")]\n        public void Constructor1ThrowsWithEmptyMediaType(string headerName, string headerValue, string mediaType)\n        {\n            Assert.ThrowsArgumentNull(() => new RequestHeaderMapping(headerName, headerValue, StringComparison.CurrentCulture, false, mediaType), \"mediaType\");\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalHttpHeaderNames\",\n            typeof(HttpTestData), \"LegalHttpHeaderValues\",\n            typeof(HttpTestData), \"LegalMediaTypeStrings\")]\n        public void Constructor1ThrowsWithInvalidStringComparison(string headerName, string headerValue, string mediaType)\n        {\n            int invalidValue = 999;\n            Assert.ThrowsInvalidEnumArgument(\n                () => new RequestHeaderMapping(headerName, headerValue, (StringComparison)invalidValue, false, mediaType),\n                \"valueComparison\", invalidValue, typeof(StringComparison));\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalHttpHeaderNames\",\n            typeof(HttpTestData), \"LegalHttpHeaderValues\",\n            typeof(HttpTestData), \"LegalMediaTypeStrings\",\n            typeof(CommonUnitTestDataSets), \"Bools\")]\n        public void TryMatchMediaTypeReturnsTrueWithNameAndValueInRequest(string headerName, string headerValue, string mediaType, bool subset)\n        {\n            RequestHeaderMapping mapping = new RequestHeaderMapping(headerName, headerValue, StringComparison.Ordinal, subset, mediaType);\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.Headers.Add(headerName, headerValue);\n            Assert.Equal(1.0, mapping.TryMatchMediaType(request));\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalHttpHeaderNames\",\n            typeof(HttpTestData), \"LegalHttpHeaderValues\",\n            typeof(HttpTestData), \"LegalMediaTypeStrings\")]\n        public void TryMatchMediaTypeReturnsTrueWithNameAndValueSubsetInRequest(string headerName, string headerValue, string mediaType)\n        {\n            RequestHeaderMapping mapping = new RequestHeaderMapping(headerName, headerValue, StringComparison.Ordinal, true, mediaType);\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.Headers.Add(headerName, \"prefix\" + headerValue);\n            Assert.Equal(1.0, mapping.TryMatchMediaType(request));\n\n            request = new HttpRequestMessage();\n            request.Headers.Add(headerName, headerValue + \"postfix\");\n            Assert.Equal(1.0, mapping.TryMatchMediaType(request));\n\n            request = new HttpRequestMessage();\n            request.Headers.Add(headerName, \"prefix\" + headerValue + \"postfix\");\n            Assert.Equal(1.0, mapping.TryMatchMediaType(request));\n        }\n\n        [Theory]\n        [TestDataSet(\n           typeof(HttpTestData), \"LegalHttpHeaderNames\",\n           typeof(HttpTestData), \"LegalHttpHeaderValues\",\n           typeof(HttpTestData), \"LegalMediaTypeStrings\")]\n        public void TryMatchMediaTypeReturnsFalseWithNameNotInRequest(string headerName, string headerValue, string mediaType)\n        {\n            RequestHeaderMapping mapping = new RequestHeaderMapping(headerName, headerValue, StringComparison.Ordinal, false, mediaType);\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.Headers.Add(\"prefix\" + headerName, headerValue);\n            Assert.Equal(0.0, mapping.TryMatchMediaType(request));\n\n            request = new HttpRequestMessage();\n            request.Headers.Add(headerName + \"postfix\", headerValue);\n            Assert.Equal(0.0, mapping.TryMatchMediaType(request));\n\n            request = new HttpRequestMessage();\n            request.Headers.Add(\"prefix\" + headerName + \"postfix\", headerValue);\n            Assert.Equal(0.0, mapping.TryMatchMediaType(request));\n        }\n\n        [Theory]\n        [TestDataSet(\n           typeof(HttpTestData), \"LegalHttpHeaderNames\",\n           typeof(HttpTestData), \"LegalHttpHeaderValues\",\n           typeof(HttpTestData), \"LegalMediaTypeStrings\")]\n        public void TryMatchMediaTypeReturnsFalseWithValueNotInRequest(string headerName, string headerValue, string mediaType)\n        {\n            RequestHeaderMapping mapping = new RequestHeaderMapping(headerName, headerValue, StringComparison.Ordinal, false, mediaType);\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.Headers.Add(headerName, \"prefix\" + headerValue);\n            Assert.Equal(0.0, mapping.TryMatchMediaType(request));\n\n            request = new HttpRequestMessage();\n            request.Headers.Add(headerName, headerValue + \"postfix\");\n            Assert.Equal(0.0, mapping.TryMatchMediaType(request));\n\n            request = new HttpRequestMessage();\n            request.Headers.Add(headerName, \"prefix\" + headerValue + \"postfix\");\n            Assert.Equal(0.0, mapping.TryMatchMediaType(request));\n        }\n\n        [Theory]\n        [TestDataSet(\n           typeof(HttpTestData), \"LegalHttpHeaderNames\",\n           typeof(HttpTestData), \"LegalHttpHeaderValues\",\n           typeof(HttpTestData), \"LegalMediaTypeStrings\")]\n        public void TryMatchMediaTypeThrowsWithNullHttpRequestMessage(string headerName, string headerValue, string mediaType)\n        {\n            RequestHeaderMapping mapping = new RequestHeaderMapping(headerName, headerValue, StringComparison.CurrentCulture, true, mediaType);\n            Assert.ThrowsArgumentNull(() => mapping.TryMatchMediaType(request: null), \"request\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/SerializerConsistencyTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.Serialization;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Formatting\n{\n    // Tests for ensuring the serializers behave consistently in various cases.\n    // This is important for conneg.\n    public class SerializerConsistencyTests\n    {\n        [Fact]\n        public Task PartialContract()\n        {\n            var c = new PartialDataContract {\n                PropertyWithAttribute = \"one\",\n#if !Testing_NetStandard1_3 // Xml formatter ignores DCS attributes but JSON one does not in netstandard1.3.\n                PropertyWithoutAttribute = \"false\"\n#endif\n            };\n            return SerializerConsistencyHepers.TestAsync(c);\n        }\n\n        [Fact]\n        public Task ClassWithFields()\n        {\n            var c1 = new ClassWithFields { Property = \"prop\" };\n            c1.SetField(\"field\");\n            return SerializerConsistencyHepers.TestAsync(c1);\n        }\n\n        [Fact]\n        public Task PrivateProperty()\n        {\n            var source2 = new PrivateProperty { FirstName = \"John\", LastName = \"Smith\" };\n            source2.SetItem(\"shoes\");\n            return SerializerConsistencyHepers.TestAsync(source2);\n        }\n\n        [Fact]\n        public Task NormalClass()\n        {\n            var source = new NormalClass { FirstName = \"John\", LastName = \"Smith\", Item = \"Socks\" };\n            return SerializerConsistencyHepers.TestAsync(source);\n        }\n\n        [Fact]\n        public Task InheritedProperties()\n        {\n            // Will we pick up inherited properties from a base object?\n            BaseClass source = new DerivedClass { Property = \"base\", DerivedProperty = \"derived\" };\n            source.SetField(\"private\");\n            return SerializerConsistencyHepers.TestAsync(source, typeof(DerivedClass));\n        }\n\n        [Fact]\n        public Task NullEmptyWhitespaceString()\n        {\n            NormalClass source = new NormalClass { FirstName = string.Empty, LastName = null, Item = \"   \" };\n\n            return SerializerConsistencyHepers.TestAsync(source);\n        }\n\n#if !Testing_NetStandard1_3 // XmlSerializer is unable to write XML for a dictionary.\n        [Fact]\n        public Task Dictionary()\n        {\n            var dict = new Dictionary<string, int>();\n            dict[\"one\"] = 1;\n            dict[\"two\"] = 2;\n\n            return SerializerConsistencyHepers.TestAsync(dict);\n        }\n#endif\n\n        [Fact]\n        public Task Array()\n        {\n            string[] array = new string[] { \"First\", \"Second\", \"Last\" };\n\n            return SerializerConsistencyHepers.TestAsync(array);\n        }\n\n#if !Testing_NetStandard1_3 // XmlSerializer is unable to read XML for interfaces.\n        [Fact]\n        public async Task ArrayInterfaces()\n        {\n            string[] array = new string[] { \"First\", \"Second\", \"Last\" };\n\n            await SerializerConsistencyHepers.TestAsync(array, typeof(IList<string>));\n            await SerializerConsistencyHepers.TestAsync(array, typeof(ICollection<string>));\n            await SerializerConsistencyHepers.TestAsync(array, typeof(IEnumerable<string>));\n        }\n\n        [Fact]\n        public Task Linq()\n        {\n            var l = from i in Enumerable.Range(1, 10) where i > 5 select i * i;\n\n            // Runtime type of a linq expression is some derived Linq type which we can't deserialize to.\n            // So explicitly call out IEnumerable<T>\n            return SerializerConsistencyHepers.TestAsync(l, typeof(IEnumerable<int>));\n        }\n#endif\n\n        [Fact]\n        public Task StaticProps()\n        {\n            ClassWithStaticProperties source = new ClassWithStaticProperties();\n\n            return SerializerConsistencyHepers.TestAsync(source);\n        }\n    }\n\n    // public class, public properties\n    public class NormalClass\n    {\n        public string FirstName { get; set; }\n        public string LastName { get; set; }\n        public string Item { get; set; }\n    }\n\n    public class ClassWithStaticProperties\n    {\n        public string InstanceProp { get; set; }\n        public static string StaticProp\n        {\n            get\n            {\n                Assert.True(false, \"serializers should never call static properties\");\n                return string.Empty;\n            }\n            set\n            {\n                Assert.True(false, \"serializers should never call static properties\");\n                throw new InvalidOperationException(); // assert already threw\n            }\n        }\n    }\n\n    [DataContract]\n    public class PartialDataContract\n    {\n        [DataMember]\n        public string PropertyWithAttribute { get; set; }\n\n#if !Testing_NetStandard1_3 // Xml formatter ignores DCS attributes but JSON one does not in netstandard1.3.\n        // no attribute here\n        public string PropertyWithoutAttribute { get; set; }\n#endif\n    }\n\n    public class PrivateProperty // with private field\n    {\n        public string FirstName { get; set; }\n        public string LastName { get; set; }\n        private string Item { get; set; }\n\n        public void SetItem(string item)\n        {\n            this.Item = item;\n        }\n    }\n\n    public class ClassWithFields\n    {\n        public string Property { get; set; }\n        private string Field;\n\n        public void SetField(string field)\n        {\n            this.Field = field;\n        }\n    }\n\n    public class BaseClass\n    {\n        private string PrivateField;\n        public string Property { get; set; }\n\n        public void SetField(string field)\n        {\n            PrivateField = field;\n        }\n    }\n\n    public class DerivedClass : BaseClass\n    {\n        public string DerivedProperty { get; set; }\n    }\n\n    // Helpers for performing consistency checks with the serializers.\n    class SerializerConsistencyHepers\n    {\n        // Exercise the various serialization paths to verify that the default serializers behave consistently.\n        public static Task TestAsync(object source)\n        {\n            Type tSource = source.GetType();\n            return TestAsync(source, tSource);\n        }\n\n        // Allow explicitly passing in the type that gets passed to the serializer.\n        // The expectation is that the type can be read and written with both serializers.\n        public static Task TestAsync(object source, Type tSource)\n        {\n            return TestAsync(source, tSource, tSource);\n        }\n\n        // tSourceWrite - the type we use for the initial write.  This can be specific, and a 1-way serializable type (eg, a linq expression).\n        // tSourceRead - the type that we read back as. This should be more general because we need to instantiate it.\n        public static async Task TestAsync(object source, Type tSourceWrite, Type tSourceRead)\n        {\n            // Apply consistency chceks. This interleaves the results between the formatters.\n            // It doesn't actually matter specifically what the formatter does, it just matters that they're consistent.\n            // This will test various transitions between C#->JSON, JSON->C#, C#->XML, and XML->C#.\n            // We can't compare C# objects, but we can compare the textual representation from XML and JSON.\n            MediaTypeFormatter xmlFormatter = new MediaTypeFormatterCollection().XmlFormatter;\n            MediaTypeFormatter jsonFor = new MediaTypeFormatterCollection().JsonFormatter;\n\n            MemoryStream blobJson = await WriteAsync(source, tSourceWrite, jsonFor); // C# --> JSON\n            MemoryStream blobXml = await WriteAsync(source, tSourceWrite, xmlFormatter); // C# --> XML\n\n            object obj2 = await ReadAsync(blobJson, tSourceRead, jsonFor); // C# --> JSON --> C#\n            object obj1 = await ReadAsync(blobXml, tSourceRead, xmlFormatter); // C# --> XML --> C#\n\n            // We were able to round trip the source object through both formatters.\n            // Now see if the resulting object is the same.\n\n            // Check C# --> XML --> C#\n\n            var blobXml2 = await WriteAsync(obj1, tSourceRead, xmlFormatter);  // C# --> XML --> C# --> XML\n            var blobJson2 = await WriteAsync(obj1, tSourceRead, jsonFor); // C# --> XML --> C# --> JSON\n\n            // Ensure that C#->XMl and  C#->XML->C#->XML give us the same result..\n            Compare(blobXml, blobXml2);\n\n            // Ensure that C#->Json and C#->XML->C#->Json give us the same result\n            Compare(blobJson, blobJson2);\n\n            // Check C# --> JSON --> C#\n\n            var blobXml3 = await WriteAsync(obj2, tSourceRead, xmlFormatter);  // C# --> JSON --> C# --> XML\n            var blobJson3 = await WriteAsync(obj2, tSourceRead, jsonFor); // C# --> JSON --> C# --> JSON\n\n            // Ensure that C#->XML and C#->JSON->C#->XML are the same\n            Compare(blobXml, blobXml3);\n\n            // Ensure that C#->JSon and C#->JSON->C#->JSON are the same.\n            Compare(blobJson, blobJson3);\n        }\n\n        // Compare if 2 streams have the same contents.\n        private static void Compare(MemoryStream ms1, MemoryStream ms2)\n        {\n            string s1 = ToString(ms1);\n            string s2 = ToString(ms2);\n\n            Assert.Equal(s1, s2);\n        }\n\n        // Given a memory stream (which is representing a textual serialization format), get the string.\n        private static string ToString(MemoryStream ms)\n        {\n            byte[] b = ms.GetBuffer();\n            return System.Text.Encoding.UTF8.GetString(b, 0, (int)ms.Length);\n        }\n\n        private static async Task<object> ReadAsync(MemoryStream ms, Type tSource, MediaTypeFormatter formatter)\n        {\n            bool f = formatter.CanReadType(tSource);\n            Assert.True(f);\n\n            object o = await formatter.ReadFromStreamAsync(tSource, ms, content: null, formatterLogger: null);\n            Assert.True(tSource.IsAssignableFrom(o.GetType()));\n\n            return o;\n        }\n\n        private static async Task<MemoryStream> WriteAsync(object obj, Type tSource, MediaTypeFormatter formatter)\n        {\n            bool f = formatter.CanWriteType(tSource);\n            Assert.True(f);\n\n            MemoryStream ms = new MemoryStream();\n\n            await formatter.WriteToStreamAsync(tSource, obj, ms, content: null, transportContext: null);\n\n            ms.Position = 0;\n            return ms;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/StringComparisonHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Formatting\n{\n    public class StringComparisonHelperTest : EnumHelperTestBase<StringComparison>\n    {\n        public StringComparisonHelperTest()\n            : base(StringComparisonHelper.IsDefined, StringComparisonHelper.Validate, (StringComparison)999)\n        {\n        }\n\n#if Testing_NetStandard1_3 // InvariantCulture and InvariantCultureIgnoreCase case are not supported in netstandard1.3 project\n        protected override bool ValueExistsForFramework(StringComparison value)\n        {\n            return !(value == StringComparison.InvariantCulture || value == StringComparison.InvariantCultureIgnoreCase);\n        }\n#endif\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/StringWithQualityHeaderValueComparerTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http.Headers;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Formatting\n{\n    public class StringWithQualityHeaderValueComparerTests\n    {\n        public static TheoryDataSet<string, string> EqualValues\n        {\n            get\n            {\n                return new TheoryDataSet<string, string>\n                {\n                    { \"value\", \"value\" },\n                    { \"value\", \"VALUE\" },\n                    { \"value\", \"value;q=1\" },\n                    { \"value\", \"value; q=1\" },\n                    { \"value\", \"value;q=1.0\" },\n                    { \"value\", \"value; q=1.0\" },\n                    { \"value\", \"value; q=1.00000\" },\n                    { \"value; q=0.5\", \"value; q=0.5\" },\n                    { \"value; q=1.0\", \"value; q=1.0\" },\n                    { \"*\", \"*\" },\n                    { \"*\", \"*;q=1\" },\n                    { \"*\", \"*; q=1\" },\n                    { \"*\", \"*;q=1.0\" },\n                    { \"*\", \"*; q=1.0\" },\n                    { \"*; q=0.5\", \"*; q=0.5\" },\n                    { \"*; q=1.0\", \"*; q=1.0\" },\n                    { \"value1\", \"value2\" },\n                    { \"value1\", \"value2;q=1\" },\n                    { \"value1\", \"value2; q=1\" },\n                    { \"value1\", \"value2;q=1.0\" },\n                    { \"value1\", \"value2; q=1.0\" },\n                };\n            }\n        }\n\n        public static TheoryDataSet<string, string> NonEqualValues\n        {\n            get\n            {\n                return new TheoryDataSet<string, string>\n                {\n                    { \"value; q=0.5\", \"value\" },\n                    { \"value; q=0.5\", \"value; q=1.0\" },\n                    { \"value1; q=0.5\", \"value2; q=1.0\" },\n                    { \"*\", \"value1\" },\n                    { \"*;q=1\", \"value1\" },\n                    { \"*; q=1\", \"value1\" },\n                    { \"*;q=1.0\", \"value1\" },\n                    { \"*; q=1.0\", \"value1\" },\n                    { \"*; q=0.5\", \"value1; q=0.5\" },\n                    { \"*; q=1.0\", \"value1; q=1.0\" },\n                };\n            }\n        }\n\n        public static TheoryDataSet<string[], string[]> BeforeAfterSortedValues\n        {\n            get\n            {\n                return new TheoryDataSet<string[], string[]>\n                {\n                    {\n                        new string[]\n                        {\n                            \"text\",\n                            \"text;q=1.0\",\n                            \"text\",\n                            \"text;q=0\",\n                            \"*;q=0.8\",\n                            \"*;q=1\",\n                            \"text;q=0.8\",\n                            \"*;q=0.6\",\n                            \"text;q=1.0\",\n                            \"*;q=0.4\",\n                            \"text;q=0.6\",\n                        }, \n                        new string[]\n                        {\n                            \"text\",\n                            \"text;q=1.0\",\n                            \"text\",\n                            \"text;q=1.0\",\n                            \"*;q=1\",\n                            \"text;q=0.8\",\n                            \"*;q=0.8\",\n                            \"text;q=0.6\",\n                            \"*;q=0.6\",\n                            \"*;q=0.4\",\n                            \"text;q=0\",\n                        }\n                    }\n                };\n            }\n        }\n\n        [Fact]\n        public void StaticComparerReturnsSameInstance()\n        {\n            StringWithQualityHeaderValueComparer comparer1 = StringWithQualityHeaderValueComparer.QualityComparer;\n            StringWithQualityHeaderValueComparer comparer2 = StringWithQualityHeaderValueComparer.QualityComparer;\n\n            Assert.NotNull(comparer1);\n            Assert.Same(comparer1, comparer2);\n        }\n\n        [Theory]\n        [PropertyData(\"EqualValues\")]\n        public void ComparerReturnsZeroForEqualValues(string stringWithQuality1, string stringWithQuality2)\n        {\n            // Arrange\n            StringWithQualityHeaderValueComparer comparer = StringWithQualityHeaderValueComparer.QualityComparer;\n\n            // Act\n            StringWithQualityHeaderValue stringWithQualityHeaderValue1 = StringWithQualityHeaderValue.Parse(stringWithQuality1);\n            StringWithQualityHeaderValue stringWithQualityHeaderValue2 = StringWithQualityHeaderValue.Parse(stringWithQuality2);\n\n            // Assert\n            Assert.Equal(0, comparer.Compare(stringWithQualityHeaderValue1, stringWithQualityHeaderValue2));\n            Assert.Equal(0, comparer.Compare(stringWithQualityHeaderValue2, stringWithQualityHeaderValue1));\n        }\n\n        [Theory]\n        [PropertyData(\"NonEqualValues\")]\n        public void ComparerReturnsNonZeroForNonEqualValues(string stringWithQuality1, string stringWithQuality2)\n        {\n            // Arrange\n            StringWithQualityHeaderValueComparer comparer = StringWithQualityHeaderValueComparer.QualityComparer;\n\n            // Act\n            StringWithQualityHeaderValue stringWithQualityHeaderValue1 = StringWithQualityHeaderValue.Parse(stringWithQuality1);\n            StringWithQualityHeaderValue stringWithQualityHeaderValue2 = StringWithQualityHeaderValue.Parse(stringWithQuality2);\n\n            // Assert\n            Assert.Equal(-1, comparer.Compare(stringWithQualityHeaderValue1, stringWithQualityHeaderValue2));\n            Assert.Equal(1, comparer.Compare(stringWithQualityHeaderValue2, stringWithQualityHeaderValue1));\n        }\n\n        [Theory]\n        [PropertyData(\"BeforeAfterSortedValues\")]\n        public void ComparerSortsListCorrectly(string[] unsorted, string[] expectedSorted)\n        {\n            // Arrange\n            IEnumerable<StringWithQualityHeaderValue> unsortedValues =\n                unsorted.Select(u => StringWithQualityHeaderValue.Parse(u));\n\n            IEnumerable<StringWithQualityHeaderValue> expectedSortedValues =\n                expectedSorted.Select(u => StringWithQualityHeaderValue.Parse(u));\n\n            // Act\n            IEnumerable<StringWithQualityHeaderValue> actualSorted = unsortedValues.OrderByDescending(m => m, StringWithQualityHeaderValueComparer.QualityComparer);\n\n            // Assert\n            Assert.True(expectedSortedValues.SequenceEqual(actualSorted));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/XmlHttpRequestHeaderMappingTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Headers;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Formatting\n{\n    public class XmlHttpRequestHeaderMappingTest\n    {\n        // HttpRequestMessage request, double expectedMatch\n        public static TheoryDataSet<HttpRequestMessage, double> TryMatchMediaTypeData\n        {\n            get\n            {\n                return new TheoryDataSet<HttpRequestMessage, double>()\n                {\n                    { CreateXhrRequest(), 1.0 },\n                    { CreateXhrRequest(\"*/*\"), 1.0 },\n                    { CreateXhrRequest(\"*/*; q=0.5\"), 1.0 },\n\n                    { CreateXhrRequest(\"text/*\"), 0.0 },\n                    { CreateXhrRequest(\"text/*; q=0.5\"), 0.0 },\n                    { CreateXhrRequest(\"application/xml\"), 0.0 },\n                    { CreateXhrRequest(\"application/xml; q=0.5\"), 0.0 },\n                    { CreateXhrRequest(\"text/test\", \"*/*; q=0.5\"), 0.0 },\n                };\n            }\n        }\n\n        private static HttpRequestMessage CreateXhrRequest(params string[] acceptHeaders)\n        {\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.Headers.Add(\"X-Requested-With\", \"XmlHttpRequest\");\n            foreach (string accept in acceptHeaders)\n            {\n                request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse(accept));\n            }\n            return request;\n        }\n\n        [Fact]\n        public void Constructor_Initializes()\n        {\n            XmlHttpRequestHeaderMapping mapping = new XmlHttpRequestHeaderMapping();\n            Assert.Equal(\"x-requested-with\", mapping.HeaderName);\n            Assert.Equal(\"XMLHttpRequest\", mapping.HeaderValue);\n            Assert.Equal(StringComparison.OrdinalIgnoreCase, mapping.HeaderValueComparison);\n            Assert.True(mapping.IsValueSubstring);\n            Assert.Equal(MediaTypeConstants.ApplicationJsonMediaType, mapping.MediaType);\n        }\n\n        [Fact]\n        public void TryMatchMediaType_ThrowsOnNull()\n        {\n            XmlHttpRequestHeaderMapping mapping = new XmlHttpRequestHeaderMapping();\n            Assert.ThrowsArgumentNull(() => mapping.TryMatchMediaType(null), \"request\");\n        }\n\n        [Theory]\n        [PropertyData(\"TryMatchMediaTypeData\")]\n        public void TryMatchMediaType_Matches(HttpRequestMessage request, double expectedMatch)\n        {\n            // Arrange\n            XmlHttpRequestHeaderMapping mapping = new XmlHttpRequestHeaderMapping();\n\n            // Act\n            double actualMatch = mapping.TryMatchMediaType(request);\n\n            // Assert\n            Assert.Equal(expectedMatch, actualMatch);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/XmlMediaTypeFormatterTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Net.Http.Formatting.DataSets;\nusing System.Net.Http.Headers;\nusing System.Runtime.Serialization;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Xml;\nusing System.Xml.Serialization;\nusing Microsoft.TestCommon;\nusing Moq;\nusing Newtonsoft.Json;\n\nnamespace System.Net.Http.Formatting\n{\n    public class XmlMediaTypeFormatterTests : MediaTypeFormatterTestBase<XmlMediaTypeFormatter>\n    {\n        // Test data which should round-trip using a media type that includes type information.  A representative\n        // sample only; avoids types DataContractJsonSerializer fails to round trip (e.g. Guid, Uint16).  May require\n        // known types or similar (de)serializer configuration.\n        public static readonly RefTypeTestData<object> BunchOfTypedObjectsTestData = new RefTypeTestData<object>(\n            () => new List<object>\n            {\n                null,\n                String.Empty,\n                \"This is a string\",\n                false,\n                true,\n                Double.MinValue,\n                Double.MaxValue,\n                Int32.MinValue,\n                Int32.MaxValue,\n                Int64.MinValue,\n                Int64.MaxValue,\n#if !NETCOREAPP2_1 // DBNull not serializable on .NET Core 2.1.\n                DBNull.Value,\n#endif\n            });\n\n        public static readonly TheoryDataSet<Type> AFewValidTypes = new()\n        {\n            typeof(bool),\n            typeof(int),\n            typeof(string),\n        };\n\n        public static IEnumerable<TestData> BunchOfTypedObjectsTestDataCollection\n        {\n            get { return new TestData[] { BunchOfTypedObjectsTestData, }; }\n        }\n\n        public override IEnumerable<MediaTypeHeaderValue> ExpectedSupportedMediaTypes\n        {\n            get { return HttpTestData.StandardXmlMediaTypes; }\n        }\n\n        public override IEnumerable<Encoding> ExpectedSupportedEncodings\n        {\n            get { return HttpTestData.StandardEncodings; }\n        }\n\n        public override byte[] ExpectedSampleTypeByteRepresentation\n        {\n            get { return ExpectedSupportedEncodings.ElementAt(0).GetBytes(\"<DataContractSampleType xmlns:i=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns=\\\"http://schemas.datacontract.org/2004/07/System.Net.Http.Formatting\\\"><Number>42</Number></DataContractSampleType>\"); }\n        }\n\n        [Fact]\n        void CopyConstructor()\n        {\n            TestXmlMediaTypeFormatter formatter = new TestXmlMediaTypeFormatter()\n            {\n                Indent = true,\n                MaxDepth = 42,\n                UseXmlSerializer = true\n            };\n\n            TestXmlMediaTypeFormatter derivedFormatter = new TestXmlMediaTypeFormatter(formatter);\n\n            Assert.Equal(formatter.Indent, derivedFormatter.Indent);\n            Assert.Equal(formatter.MaxDepth, derivedFormatter.MaxDepth);\n            Assert.Equal(formatter.UseXmlSerializer, derivedFormatter.UseXmlSerializer);\n        }\n\n        [Fact]\n        public void DefaultMediaType_ReturnsApplicationXml()\n        {\n            MediaTypeHeaderValue mediaType = XmlMediaTypeFormatter.DefaultMediaType;\n            Assert.NotNull(mediaType);\n            Assert.Equal(\"application/xml\", mediaType.MediaType);\n        }\n\n        [Fact]\n        public void MaxDepthReturnsCorrectValue()\n        {\n            Assert.Reflection.IntegerProperty(\n                new XmlMediaTypeFormatter(),\n                f => f.MaxDepth,\n                expectedDefaultValue: 256,\n                minLegalValue: 1,\n                illegalLowerValue: 0,\n                maxLegalValue: null,\n                illegalUpperValue: null,\n                roundTripTestValue: 10);\n        }\n\n#if !Testing_NetStandard1_3 // Cannot read or write w/ DCS in netstandard1.3.\n        [Fact]\n        public async Task ReadDeeplyNestedObjectThrows()\n        {\n            XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter() { MaxDepth = 1 };\n\n            MemoryStream stream = new MemoryStream();\n            await formatter.WriteToStreamAsync(typeof(SampleType), new SampleType() { Number = 1 }, stream, null, null);\n            stream.Position = 0;\n            await Assert.ThrowsAsync<SerializationException>(() => formatter.ReadFromStreamAsync(typeof(SampleType), stream, null, null));\n        }\n#endif\n\n        [Fact]\n        public void Indent_RoundTrips()\n        {\n            Assert.Reflection.BooleanProperty(\n                new XmlMediaTypeFormatter(),\n                c => c.Indent,\n                expectedDefaultValue: false);\n        }\n\n        [Fact]\n        public void UseXmlSerializer_RoundTrips()\n        {\n            Assert.Reflection.BooleanProperty(\n                new XmlMediaTypeFormatter(),\n                c => c.UseXmlSerializer,\n                expectedDefaultValue: false);\n        }\n\n#if !Testing_NetStandard1_3 // Cannot read or write w/ DCS in netstandard1.3.\n        [Theory]\n        [InlineData(typeof(IEnumerable<string>))]\n        [InlineData(typeof(IQueryable<string>))]\n        public async Task UseXmlFormatterWithNull(Type type)\n        {\n            XmlMediaTypeFormatter xmlFormatter = new XmlMediaTypeFormatter { UseXmlSerializer = false };\n            MemoryStream memoryStream = new MemoryStream();\n            HttpContent content = new StringContent(String.Empty);\n            await Assert.Task.SucceedsAsync(xmlFormatter.WriteToStreamAsync(type, null, memoryStream, content, transportContext: null));\n            memoryStream.Position = 0;\n            string serializedString = new StreamReader(memoryStream).ReadToEnd();\n            Assert.True(serializedString.Contains(\"nil=\\\"true\\\"\"),\n                \"Null value should be serialized as nil.\");\n            Assert.True(serializedString.ToLower().Contains(\"arrayofstring\"),\n                \"It should be serialized out as an array of string.\");\n        }\n\n        [Fact]\n        public async Task UseXmlSerializer_False()\n        {\n            XmlMediaTypeFormatter xmlFormatter = new XmlMediaTypeFormatter { UseXmlSerializer = false };\n            MemoryStream memoryStream = new MemoryStream();\n            HttpContent content = new StringContent(String.Empty);\n            await Assert.Task.SucceedsAsync(xmlFormatter.WriteToStreamAsync(typeof(SampleType), new SampleType(), memoryStream, content, transportContext: null));\n            memoryStream.Position = 0;\n            string serializedString = new StreamReader(memoryStream).ReadToEnd();\n            Assert.True(serializedString.Contains(\"DataContractSampleType\"),\n                \"SampleType should be serialized with data contract name DataContractSampleType because we're using DCS.\");\n            Assert.False(serializedString.Contains(\"version=\\\"1.0\\\" encoding=\\\"utf-8\\\"\"),\n                    \"Using DCS should not emit the xml declaration by default.\");\n            Assert.False(serializedString.Contains(\"\\r\\n\"), \"Using DCS should emit data without indentation by default.\");\n        }\n\n        [Fact]\n        public async Task UseXmlSerializer_False_Indent()\n        {\n            XmlMediaTypeFormatter xmlFormatter = new XmlMediaTypeFormatter { UseXmlSerializer = false, Indent = true };\n            MemoryStream memoryStream = new MemoryStream();\n            HttpContent content = new StringContent(String.Empty);\n            await Assert.Task.SucceedsAsync(xmlFormatter.WriteToStreamAsync(typeof(SampleType), new SampleType(), memoryStream, content, transportContext: null));\n            memoryStream.Position = 0;\n            string serializedString = new StreamReader(memoryStream).ReadToEnd();\n            Assert.True(serializedString.Contains(\"\\r\\n\"), \"Using DCS with indent set to true should emit data with indentation.\");\n        }\n#endif\n\n        [Fact]\n        public void SetSerializer_ThrowsWithNullType()\n        {\n            XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter();\n            XmlSerializer xmlSerializer = new XmlSerializer(typeof(string));\n            Assert.ThrowsArgumentNull(() => { formatter.SetSerializer(null, xmlSerializer); }, \"type\");\n        }\n\n        [Fact]\n        public void SetSerializer_ThrowsWithNullSerializer()\n        {\n            XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter();\n            Assert.ThrowsArgumentNull(() => { formatter.SetSerializer(typeof(string), (XmlSerializer)null); }, \"serializer\");\n        }\n\n        [Fact]\n        public void SetSerializer1_ThrowsWithNullSerializer()\n        {\n            XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter();\n            Assert.ThrowsArgumentNull(() => { formatter.SetSerializer<string>((XmlSerializer)null); }, \"serializer\");\n        }\n\n        [Fact]\n        public void SetSerializer2_ThrowsWithNullType()\n        {\n            XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter();\n            XmlObjectSerializer xmlObjectSerializer = new DataContractSerializer(typeof(string));\n            Assert.ThrowsArgumentNull(() => { formatter.SetSerializer(null, xmlObjectSerializer); }, \"type\");\n        }\n\n        [Fact]\n        public void SetSerializer2_ThrowsWithNullSerializer()\n        {\n            XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter();\n            Assert.ThrowsArgumentNull(() => { formatter.SetSerializer(typeof(string), (XmlObjectSerializer)null); }, \"serializer\");\n        }\n\n        [Fact]\n        public void SetSerializer3_ThrowsWithNullSerializer()\n        {\n            XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter();\n            Assert.ThrowsArgumentNull(() => { formatter.SetSerializer<string>((XmlSerializer)null); }, \"serializer\");\n        }\n\n        [Fact]\n        public void RemoveSerializer_ThrowsWithNullType()\n        {\n            XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter();\n            Assert.ThrowsArgumentNull(() => { formatter.RemoveSerializer(null); }, \"type\");\n        }\n\n#if !Testing_NetStandard1_3 // Cannot read or write w/ DCS in netstandard1.3.\n        [Fact]\n        public async Task FormatterThrowsOnWriteWhenOverridenCreateFails()\n        {\n            // Arrange\n            TestXmlMediaTypeFormatter formatter = new TestXmlMediaTypeFormatter();\n\n            formatter.ThrowAnExceptionOnCreate = true;\n\n            MemoryStream memoryStream = new MemoryStream();\n            HttpContent content = new StringContent(String.Empty);\n\n            // Act & Assert\n            Func<Task> action = () => formatter.WriteToStreamAsync(typeof(SampleType), new SampleType(), memoryStream, content, transportContext: null);\n            await Assert.ThrowsAsync<InvalidOperationException>(action);\n\n            Assert.NotNull(formatter.InnerDataContractSerializer);\n            Assert.Null(formatter.InnerXmlSerializer);\n        }\n\n        [Fact]\n        public async Task FormatterThrowsOnWriteWhenOverridenCreateReturnsNull()\n        {\n            // Arrange\n            TestXmlMediaTypeFormatter formatter = new TestXmlMediaTypeFormatter();\n\n            formatter.ReturnNullOnCreate = true;\n\n            MemoryStream memoryStream = new MemoryStream();\n            HttpContent content = new StringContent(String.Empty);\n\n            // Act & Assert\n            Func<Task> action = () => formatter.WriteToStreamAsync(typeof(SampleType), new SampleType(), memoryStream, content, transportContext: null);\n            await Assert.ThrowsAsync<InvalidOperationException>(action);\n\n            Assert.NotNull(formatter.InnerDataContractSerializer);\n            Assert.Null(formatter.InnerXmlSerializer);\n        }\n\n        [Fact]\n        public async Task FormatterThrowsOnReadWhenOverridenCreateFails()\n        {\n            // Arrange\n            TestXmlMediaTypeFormatter formatter = new TestXmlMediaTypeFormatter();\n\n            formatter.ThrowAnExceptionOnCreate = true;\n\n            byte[] array = Encoding.UTF8.GetBytes(\"foo\");\n            MemoryStream memoryStream = new MemoryStream(array);\n\n            HttpContent content = new StringContent(\"foo\");\n\n            // Act & Assert\n            Func<Task> action = () => formatter.ReadFromStreamAsync(typeof(SampleType), memoryStream, content, null);\n            await Assert.ThrowsAsync<InvalidOperationException>(action);\n\n            Assert.NotNull(formatter.InnerDataContractSerializer);\n            Assert.Null(formatter.InnerXmlSerializer);\n        }\n\n        [Fact]\n        public async Task FormatterThrowsOnReadWhenOverridenCreateReturnsNull()\n        {\n            // Arrange\n            TestXmlMediaTypeFormatter formatter = new TestXmlMediaTypeFormatter();\n\n            formatter.ReturnNullOnCreate = true;\n\n            byte[] array = Encoding.UTF8.GetBytes(\"foo\");\n            MemoryStream memoryStream = new MemoryStream(array);\n\n            HttpContent content = new StringContent(\"foo\");\n\n            // Act & Assert\n            Func<Task> action = () => formatter.ReadFromStreamAsync(typeof(SampleType), memoryStream, content, null);\n\n            await Assert.ThrowsAsync<InvalidOperationException>(action);\n\n            Assert.NotNull(formatter.InnerDataContractSerializer);\n            Assert.Null(formatter.InnerXmlSerializer);\n        }\n#endif\n\n        [Fact]\n        public async Task XmlSerializerFormatterThrowsOnWriteWhenOverridenCreateFails()\n        {\n            // Arrange\n            TestXmlMediaTypeFormatter formatter = new TestXmlMediaTypeFormatter();\n\n            formatter.ThrowAnExceptionOnCreate = true;\n            formatter.UseXmlSerializer = true;\n\n            MemoryStream memoryStream = new MemoryStream();\n            HttpContent content = new StringContent(String.Empty);\n\n            // Act & Assert\n            Func<Task> action = () => formatter.WriteToStreamAsync(typeof(SampleType), new SampleType(), memoryStream, content, transportContext: null);\n            await Assert.ThrowsAsync<InvalidOperationException>(action);\n\n            Assert.Null(formatter.InnerDataContractSerializer);\n            Assert.NotNull(formatter.InnerXmlSerializer);\n        }\n\n        [Fact]\n        public async Task XmlSerializerFormatterThrowsOnWriteWhenOverridenCreateReturnsNull()\n        {\n            // Arrange\n            TestXmlMediaTypeFormatter formatter = new TestXmlMediaTypeFormatter();\n\n            formatter.ReturnNullOnCreate = true;\n            formatter.UseXmlSerializer = true;\n\n            MemoryStream memoryStream = new MemoryStream();\n            HttpContent content = new StringContent(String.Empty);\n\n            // Act & Assert\n            Func<Task> action = () => formatter.WriteToStreamAsync(typeof(SampleType), new SampleType(), memoryStream, content, transportContext: null);\n            await Assert.ThrowsAsync<InvalidOperationException>(action);\n\n            Assert.Null(formatter.InnerDataContractSerializer);\n            Assert.NotNull(formatter.InnerXmlSerializer);\n        }\n\n        [Fact]\n        public async Task XmlSerializerFormatterThrowsOnReadWhenOverridenCreateFails()\n        {\n            // Arrange\n            TestXmlMediaTypeFormatter formatter = new TestXmlMediaTypeFormatter();\n\n            formatter.ThrowAnExceptionOnCreate = true;\n            formatter.UseXmlSerializer = true;\n\n            byte[] array = Encoding.UTF8.GetBytes(\"foo\");\n            MemoryStream memoryStream = new MemoryStream(array);\n\n            HttpContent content = new StringContent(\"foo\");\n\n            // Act & Assert\n            Func<Task> action = () => formatter.ReadFromStreamAsync(typeof(SampleType), memoryStream, content, null);\n            await Assert.ThrowsAsync<InvalidOperationException>(action);\n\n            Assert.Null(formatter.InnerDataContractSerializer);\n            Assert.NotNull(formatter.InnerXmlSerializer);\n        }\n\n        [Fact]\n        public async Task XmlSerializerFormatterThrowsOnReadWhenOverridenCreateReturnsNull()\n        {\n            // Arrange\n            TestXmlMediaTypeFormatter formatter = new TestXmlMediaTypeFormatter();\n\n            formatter.ReturnNullOnCreate = true;\n            formatter.UseXmlSerializer = true;\n\n            byte[] array = Encoding.UTF8.GetBytes(\"foo\");\n            MemoryStream memoryStream = new MemoryStream(array);\n\n            HttpContent content = new StringContent(\"foo\");\n\n            // Act & Assert\n            Func<Task> action = () => formatter.ReadFromStreamAsync(typeof(SampleType), memoryStream, content, null);\n\n            await Assert.ThrowsAsync<InvalidOperationException>(action);\n\n            Assert.Null(formatter.InnerDataContractSerializer);\n            Assert.NotNull(formatter.InnerXmlSerializer);\n        }\n\n        [Theory]\n        [TestDataSet(typeof(CommonUnitTestDataSets), \"RepresentativeValueAndRefTypeTestDataCollection\", RoundTripDataVariations)]\n        public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsyncUsingXmlSerializer(Type variationType, object testData)\n        {\n            // Guard\n            bool canSerialize = IsSerializableWithXmlSerializer(variationType, testData) && Assert.Http.CanRoundTrip(variationType);\n            if (canSerialize)\n            {\n                // Arrange\n                TestXmlMediaTypeFormatter formatter = new TestXmlMediaTypeFormatter();\n                formatter.SetSerializer(variationType, new XmlSerializer(variationType));\n\n                // Arrange & Act & Assert\n                object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n                Assert.Equal(testData, readObj);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(XmlMediaTypeFormatterTests), \"BunchOfTypedObjectsTestDataCollection\", RoundTripDataVariations)]\n        public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsyncUsingXmlSerializer_ExtraTypes(Type variationType, object testData)\n        {\n            // Guard\n            bool canSerialize = IsSerializableWithXmlSerializer(variationType, testData) && Assert.Http.CanRoundTrip(variationType);\n            if (canSerialize)\n            {\n                // Arrange\n                TestXmlMediaTypeFormatter formatter = new TestXmlMediaTypeFormatter();\n                formatter.SetSerializer(variationType, new XmlSerializer(variationType, new Type[] { typeof(DBNull), }));\n\n                // Arrange & Act & Assert\n                object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n                Assert.Equal(testData, readObj);\n            }\n        }\n\n        // Test alternate null value; this serializer attempts to cast DBNull to variationType so typeof(string) variation fails\n        [Fact]\n        public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsyncUsingXmlSerializer_DBNull()\n        {\n            // Arrange\n            TestXmlMediaTypeFormatter formatter = new TestXmlMediaTypeFormatter();\n            Type variationType = typeof(DBNull);\n            formatter.SetSerializer(variationType, new XmlSerializer(variationType));\n            object testData = DBNull.Value;\n\n            // Arrange & Act & Assert\n            object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n            Assert.Equal(testData, readObj);\n        }\n\n        [Theory]\n        [TestDataSet(typeof(CommonUnitTestDataSets), \"RepresentativeValueAndRefTypeTestDataCollection\", RoundTripDataVariations)]\n        public async Task ReadFromStream_AsyncRoundTripsWriteToStreamUsingDataContractSerializer(Type variationType, object testData)\n        {\n            // Guard\n            bool canSerialize = IsSerializableWithDataContractSerializer(variationType, testData) && Assert.Http.CanRoundTrip(variationType);\n            if (canSerialize)\n            {\n                // Arrange\n                TestXmlMediaTypeFormatter formatter = new TestXmlMediaTypeFormatter();\n                formatter.SetSerializer(variationType, new DataContractSerializer(variationType));\n\n                // Arrange & Act & Assert\n                object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n                Assert.Equal(testData, readObj);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(XmlMediaTypeFormatterTests), \"BunchOfTypedObjectsTestDataCollection\", RoundTripDataVariations)]\n        public async Task ReadFromStream_AsyncRoundTripsWriteToStreamUsingDataContractSerializer_KnownTypes(Type variationType, object testData)\n        {\n            // Guard\n            bool canSerialize = IsSerializableWithDataContractSerializer(variationType, testData) && Assert.Http.CanRoundTrip(variationType);\n            if (canSerialize)\n            {\n                // Arrange\n                TestXmlMediaTypeFormatter formatter = new TestXmlMediaTypeFormatter();\n                formatter.SetSerializer(variationType, new DataContractSerializer(variationType, new Type[] { typeof(DBNull), }));\n\n                // Arrange & Act & Assert\n                object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n                Assert.Equal(testData, readObj);\n            }\n        }\n\n#if Testing_NetStandard1_3 // Cannot read or write w/ DCS in netstandard1.3.\n        [Theory]\n        [TestDataSet(typeof(CommonUnitTestDataSets), \"RepresentativeValueAndRefTypeTestDataCollection\", RoundTripDataVariations)]\n        public async Task ReadFromStreamAsync_UsingDataContractSerializer_Throws(Type variationType, object testData)\n        {\n            // Arrange. First, get some data using XmlSerializer.\n            bool canSerialize = IsSerializableWithXmlSerializer(variationType, testData) && Assert.Http.CanRoundTrip(variationType);\n            if (canSerialize)\n            {\n                var formatter = new XmlMediaTypeFormatter() { UseXmlSerializer = true };\n                using var stream = new MemoryStream();\n                using var content = new StringContent(string.Empty);\n\n                await formatter.WriteToStreamAsync(variationType, testData, stream, content, transportContext: null);\n                await stream.FlushAsync();\n                stream.Position = 0L;\n\n                content.Headers.ContentLength = stream.Length;\n                formatter.RemoveSerializer(variationType);\n                formatter.UseXmlSerializer = false;\n\n                // Act & Assert\n                await Assert.ThrowsAsync<PlatformNotSupportedException>(() =>\n                    formatter.ReadFromStreamAsync(variationType, stream, content, formatterLogger: null),\n                    \"Unable to validate types on this platform when UseXmlSerializer is 'false'. Please set \" +\n                    \"UseXmlSerializer or move to a supported platform, one where the .NET Standard 2.0 assembly \" +\n                    \"is usable.\");\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(CommonUnitTestDataSets), \"RepresentativeValueAndRefTypeTestDataCollection\", RoundTripDataVariations)]\n        public async Task WriteToStreamAsync_UsingDataContractSerializer_Throws(Type variationType, object testData)\n        {\n            // Arrange\n            var formatter = new XmlMediaTypeFormatter();\n            using var stream = new MemoryStream();\n            using var content = new StringContent(string.Empty);\n\n            // Act & Assert\n            await Assert.ThrowsAsync<PlatformNotSupportedException>(() =>\n                formatter.WriteToStreamAsync(variationType, testData, stream, content, transportContext: null),\n                \"Unable to validate types on this platform when UseXmlSerializer is 'false'. Please set \" +\n                \"UseXmlSerializer or move to a supported platform, one where the .NET Standard 2.0 assembly \" +\n                \"is usable.\");\n        }\n\n#else\n#if !NETCOREAPP2_1 // DBNull not serializable on .NET Core 2.1.\n        [Fact]\n        public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsyncUsingDataContractSerializer_DBNull()\n        {\n            // Arrange\n            TestXmlMediaTypeFormatter formatter = new TestXmlMediaTypeFormatter();\n            Type variationType = typeof(DBNull);\n            formatter.SetSerializer(variationType, new DataContractSerializer(variationType));\n            object testData = DBNull.Value;\n\n            // Arrange & Act & Assert\n            object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n\n            // DBNull.Value round-trips as either Object or DBNull because serialization includes its type\n            Assert.Equal(testData, readObj);\n        }\n\n        [Fact]\n        public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsyncUsingDataContractSerializer_DBNullAsEmptyString()\n        {\n            // Arrange\n            TestXmlMediaTypeFormatter formatter = new TestXmlMediaTypeFormatter();\n            Type variationType = typeof(string);\n            formatter.SetSerializer(variationType, new DataContractSerializer(variationType, new Type[] { typeof(DBNull), }));\n            object testData = DBNull.Value;\n\n            // Arrange & Act & Assert\n            object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n\n            // Lower levels convert DBNull.Value to empty string on read\n            Assert.Equal(String.Empty, readObj);\n        }\n#endif\n\n        public override Task ReadFromStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding)\n        {\n            // Arrange\n            XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter();\n\n            string formattedContent = \"<string xmlns=\\\"http://schemas.microsoft.com/2003/10/Serialization/\\\">\" + content + \"</string>\";\n            string mediaType = string.Format(\"application/xml; charset={0}\", encoding);\n\n            // Act & assert\n            return ReadFromStreamAsync_UsesCorrectCharacterEncodingHelper(formatter, content, formattedContent, mediaType, encoding, isDefaultEncoding);\n        }\n#endif\n\n        [Fact]\n        public async Task ReadFromStreamAsync_UsesGetDeserializerAndCreateXmlReader()\n        {\n            Type type = typeof(string);\n            string xml = \"<string xmlns=\\\"http://schemas.microsoft.com/2003/10/Serialization/\\\">x</string>\";\n            Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml));\n            var serializer = new Mock<XmlObjectSerializer>() { CallBase = true };\n            var reader = new Mock<XmlReader>() { CallBase = true };\n            var formatter = new Mock<XmlMediaTypeFormatter>() { CallBase = true };\n            formatter.Setup(f => f.GetDeserializer(type, null)).Returns(serializer.Object);\n            formatter.Setup(f => f.CreateXmlReader(stream, null)).Returns(reader.Object);\n\n            await formatter.Object.ReadFromStreamAsync(type, stream, content: null, formatterLogger: null);\n\n            serializer.Verify(s => s.ReadObject(reader.Object));\n        }\n\n        [Fact]\n        public Task ReadFromStreamAsync_ThrowsException_WhenGetDeserializerReturnsNull()\n        {\n            Type type = typeof(string);\n            string xml = \"<string xmlns=\\\"http://schemas.microsoft.com/2003/10/Serialization/\\\">x</string>\";\n            var formatter = new Mock<XmlMediaTypeFormatter>() { CallBase = true };\n            formatter.Setup(f => f.GetDeserializer(type, null)).Returns(null);\n\n            return Assert.ThrowsAsync<InvalidOperationException>(\n                () => formatter.Object.ReadFromStreamAsync(type, new MemoryStream(Encoding.UTF8.GetBytes(xml)), content: null, formatterLogger: null),\n                \"The object returned by GetDeserializer must not be a null value.\");\n        }\n\n        [Fact]\n        public Task ReadFromStreamAsync_ThrowsException_WhenGetDeserializerReturnsInvalidType()\n        {\n            Type type = typeof(string);\n            string xml = \"<string xmlns=\\\"http://schemas.microsoft.com/2003/10/Serialization/\\\">x</string>\";\n            var formatter = new Mock<XmlMediaTypeFormatter>() { CallBase = true };\n            formatter.Setup(f => f.GetDeserializer(type, null)).Returns(new JsonSerializer());\n\n            return Assert.ThrowsAsync<InvalidOperationException>(\n                () => formatter.Object.ReadFromStreamAsync(type, new MemoryStream(Encoding.UTF8.GetBytes(xml)), content: null, formatterLogger: null),\n                \"The object of type 'JsonSerializer' returned by GetDeserializer must be an instance of either XmlObjectSerializer or XmlSerializer.\");\n        }\n\n#if !Testing_NetStandard1_3 // Cannot read or write w/ DCS in netstandard1.3.\n        public override Task WriteToStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding)\n        {\n            // Arrange\n            XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter();\n            string formattedContent = \"<string xmlns=\\\"http://schemas.microsoft.com/2003/10/Serialization/\\\">\" + content +\n                                      \"</string>\";\n            string mediaType = string.Format(\"application/xml; charset={0}\", encoding);\n\n            // Act & assert\n            return WriteToStreamAsync_UsesCorrectCharacterEncodingHelper(formatter, content, formattedContent, mediaType, encoding, isDefaultEncoding);\n        }\n#endif\n\n        [Fact]\n        public async Task WriteToStreamAsync_UsesGetSerializerAndCreateXmlWriter()\n        {\n            Type type = typeof(string);\n            object value = \"x\";\n            Stream stream = new MemoryStream();\n            var serializer = new Mock<XmlObjectSerializer>() { CallBase = true };\n            var writer = new Mock<XmlWriter>() { CallBase = true };\n            var formatter = new Mock<XmlMediaTypeFormatter>() { CallBase = true };\n            formatter.Setup(f => f.GetSerializer(type, value, null)).Returns(serializer.Object);\n            formatter.Setup(f => f.CreateXmlWriter(stream, null)).Returns(writer.Object);\n\n            await formatter.Object.WriteToStreamAsync(type, value, stream, content: null, transportContext: null);\n\n            serializer.Verify(s => s.WriteObject(writer.Object, value));\n        }\n\n        [Fact]\n        public Task WriteToStreamAsync_ThrowsException_WhenGetSerializerReturnsNull()\n        {\n            Type type = typeof(string);\n            object value = \"x\";\n            var formatter = new Mock<XmlMediaTypeFormatter>() { CallBase = true };\n            formatter.Setup(f => f.GetSerializer(type, value, null)).Returns(null);\n\n            return Assert.ThrowsAsync<InvalidOperationException>(\n                () => formatter.Object.WriteToStreamAsync(type, value, new MemoryStream(), content: null, transportContext: null),\n                \"The object returned by GetSerializer must not be a null value.\");\n        }\n\n        [Fact]\n        public Task WriteToStreamAsync_ThrowsException_WhenGetSerializerReturnsInvalidType()\n        {\n            Type type = typeof(string);\n            object value = \"x\";\n            var formatter = new Mock<XmlMediaTypeFormatter>() { CallBase = true };\n            formatter.Setup(f => f.GetSerializer(type, value, null)).Returns(new JsonSerializer());\n\n            return Assert.ThrowsAsync<InvalidOperationException>(\n                () => formatter.Object.WriteToStreamAsync(type, value, new MemoryStream(), content: null, transportContext: null),\n                \"The object of type 'JsonSerializer' returned by GetSerializer must be an instance of either XmlObjectSerializer or XmlSerializer.\");\n        }\n\n        [Fact]\n        public void CreateXmlWriter_Uses_WriterSettings()\n        {\n            // Arrange\n            XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter();\n            formatter.WriterSettings.ConformanceLevel = ConformanceLevel.Fragment;\n            Stream stream = new MemoryStream();\n            HttpContent content = new StreamContent(stream);\n\n            // Act\n            XmlWriter writer = formatter.CreateXmlWriter(stream, content);\n\n            // Assert\n            Assert.Equal(writer.Settings.ConformanceLevel, formatter.WriterSettings.ConformanceLevel);\n        }\n\n        [Fact]\n        public void Property_WriterSettings_DefaultValues()\n        {\n            XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter();\n\n            Assert.NotNull(formatter.WriterSettings);\n            Assert.False(formatter.WriterSettings.Indent);\n            Assert.False(formatter.WriterSettings.CloseOutput);\n            Assert.True(formatter.WriterSettings.OmitXmlDeclaration);\n            Assert.False(formatter.WriterSettings.CheckCharacters);\n        }\n\n#if !Testing_NetStandard1_3 // Cannot read or write w/ DCS in netstandard1.3.\n        [Fact]\n        public async Task InvalidXmlCharacters_CanBeSerialized_Default()\n        {\n            XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter();\n            Stream stream = new MemoryStream();\n            HttpContent content = new StreamContent(stream);\n\n            await formatter.WriteToStreamAsync(typeof(string), \"\\x16\", stream, content, null);\n        }\n\n        [Fact]\n        public Task InvalidXmlCharacters_CannotBeSerialized_IfCheckCharactersIsTrue()\n        {\n            XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter();\n            formatter.WriterSettings.CheckCharacters = true;\n            Stream stream = new MemoryStream();\n            HttpContent content = new StreamContent(stream);\n\n            return Assert.ThrowsAsync<ArgumentException>(\n                () => formatter.WriteToStreamAsync(typeof(string), \"\\x16\", stream, content, null),\n                \"'\\x16', hexadecimal value 0x16, is an invalid character.\");\n        }\n#endif\n\n        [Theory]\n        [PropertyData(nameof(AFewValidTypes))]\n        public void CanReadType_ReturnsFalse_ForValidTypes(Type type)\n        {\n            XmlMediaTypeFormatter formatter = new();\n\n            var canRead = formatter.CanReadType(type);\n\n#if Testing_NetStandard1_3 // Different behavior in netstandard1.3 due to no DataContract validation.\n            Assert.False(canRead);\n#else\n            Assert.True(canRead);\n#endif\n        }\n\n        [Theory]\n        [PropertyData(nameof(AFewValidTypes))]\n        public void CanWriteType_ReturnsFalse_ForValidTypes(Type type)\n        {\n            XmlMediaTypeFormatter formatter = new();\n\n            var canWrite = formatter.CanWriteType(type);\n\n#if Testing_NetStandard1_3 // Different behavior in netstandard1.3 due to no DataContract validation.\n            Assert.False(canWrite);\n#else\n            Assert.True(canWrite);\n#endif\n        }\n\n        [Fact]\n        public void CanReadType_ReturnsFalse_ForInvalidDataContracts()\n        {\n            XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter();\n\n            Assert.False(formatter.CanReadType(typeof(InvalidDataContract)));\n        }\n\n        [Fact]\n        public void CanWriteType_ReturnsFalse_ForInvalidDataContracts()\n        {\n            XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter();\n\n            Assert.False(formatter.CanWriteType(typeof(InvalidDataContract)));\n        }\n\n#if Testing_NetStandard1_3 // Cannot read or write w/ DCS in netstandard1.3.\n        [Fact]\n        public override Task Overridden_ReadFromStreamAsyncWithCancellationToken_GetsCalled()\n        {\n            return Task.CompletedTask;\n        }\n\n        [Fact]\n        public override Task Overridden_ReadFromStreamAsyncWithoutCancellationToken_GetsCalled()\n        {\n            return Task.CompletedTask;\n        }\n\n        [Fact]\n        public override Task Overridden_WriteToStreamAsyncWithCancellationToken_GetsCalled()\n        {\n            return Task.CompletedTask;\n        }\n\n        [Fact]\n        public override Task Overridden_WriteToStreamAsyncWithoutCancellationToken_GetsCalled()\n        {\n            return Task.CompletedTask;\n        }\n\n        [Fact]\n        public override Task ReadFromStreamAsync_ReadsDataButDoesNotCloseStream()\n        {\n            return Task.CompletedTask;\n        }\n\n        // Attributes are in base class.\n        public override Task ReadFromStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding)\n        {\n            return Task.CompletedTask;\n        }\n\n        [Fact]\n        public override Task ReadFromStreamAsync_WhenContentLengthIsNull_ReadsDataButDoesNotCloseStream()\n        {\n            return Task.CompletedTask;\n        }\n\n        // Attributes are in base class.\n        public override Task WriteToStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding)\n        {\n            return Task.CompletedTask;\n        }\n\n        [Fact]\n        public override Task WriteToStreamAsync_WhenObjectIsNull_WritesDataButDoesNotCloseStream()\n        {\n            return Task.CompletedTask;\n        }\n\n        [Fact]\n        public override Task WriteToStreamAsync_WritesDataButDoesNotCloseStream()\n        {\n            return Task.CompletedTask;\n        }\n#endif\n\n        public class InvalidDataContract\n        {\n            // removing the default ctor makes this invalid\n            public InvalidDataContract(string s)\n            {\n            }\n        }\n\n        public class TestXmlMediaTypeFormatter : XmlMediaTypeFormatter\n        {\n            public TestXmlMediaTypeFormatter()\n            {\n            }\n\n            public TestXmlMediaTypeFormatter(TestXmlMediaTypeFormatter formatter)\n                : base(formatter)\n            {\n            }\n\n            public bool ThrowAnExceptionOnCreate { get; set; }\n            public bool ReturnNullOnCreate { get; set; }\n            public XmlSerializer InnerXmlSerializer { get; private set; }\n            public DataContractSerializer InnerDataContractSerializer { get; private set; }\n\n            public bool CanReadTypeCaller(Type type)\n            {\n                return CanReadType(type);\n            }\n\n            public bool CanWriteTypeCaller(Type type)\n            {\n                return CanWriteType(type);\n            }\n\n            public override XmlSerializer CreateXmlSerializer(Type type)\n            {\n                InnerXmlSerializer = base.CreateXmlSerializer(type);\n\n                if (ReturnNullOnCreate)\n                {\n                    return null;\n                }\n\n                if (ThrowAnExceptionOnCreate)\n                {\n                    throw new Exception(\"Throwing exception directly, since it needs to get caught by a catch all\");\n                }\n\n                return InnerXmlSerializer;\n            }\n\n            public override DataContractSerializer CreateDataContractSerializer(Type type)\n            {\n                InnerDataContractSerializer = base.CreateDataContractSerializer(type);\n\n                if (ReturnNullOnCreate)\n                {\n                    return null;\n                }\n\n                if (ThrowAnExceptionOnCreate)\n                {\n                    throw new Exception(\"Throwing exception directly, since it needs to get caught by a catch all\");\n                }\n\n                return InnerDataContractSerializer;\n            }\n        }\n\n        private bool IsSerializableWithXmlSerializer(Type type, object obj)\n        {\n            if (Assert.Http.IsKnownUnserializable(type, obj))\n            {\n                return false;\n            }\n\n            try\n            {\n                new XmlSerializer(type);\n                if (obj != null && obj.GetType() != type)\n                {\n                    new XmlSerializer(obj.GetType());\n                }\n            }\n            catch\n            {\n                return false;\n            }\n\n            return true;\n        }\n\n        private bool IsSerializableWithDataContractSerializer(Type type, object obj)\n        {\n#if Testing_NetStandard1_3 // Different behavior in netstandard1.3 due to no DataContract validation.\n            return false;\n#else\n            if (Assert.Http.IsKnownUnserializable(type, obj))\n            {\n                return false;\n            }\n\n            try\n            {\n                new DataContractSerializer(type);\n                if (obj != null && obj.GetType() != type)\n                {\n                    new DataContractSerializer(obj.GetType());\n                }\n            }\n            catch\n            {\n                return false;\n            }\n\n            return true;\n#endif\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Formatting/XmlSerializerMediaTypeFormatterTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Net.Http.Formatting.DataSets;\nusing System.Net.Http.Headers;\nusing System.Runtime.Serialization;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Xml.Serialization;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Formatting\n{\n    public class XmlSerializerMediaTypeFormatter : XmlMediaTypeFormatter\n    {\n        public XmlSerializerMediaTypeFormatter()\n        {\n            UseXmlSerializer = true;\n        }\n    }\n\n    public class XmlSerializerMediaTypeFormatterTests : MediaTypeFormatterTestBase<XmlSerializerMediaTypeFormatter>\n    {\n        public override IEnumerable<MediaTypeHeaderValue> ExpectedSupportedMediaTypes\n        {\n            get { return HttpTestData.StandardXmlMediaTypes; }\n        }\n\n        public override IEnumerable<Encoding> ExpectedSupportedEncodings\n        {\n            get { return HttpTestData.StandardEncodings; }\n        }\n\n        public override byte[] ExpectedSampleTypeByteRepresentation\n        {\n            get { return ExpectedSupportedEncodings.ElementAt(0).GetBytes(\"<SampleType xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns:xsd=\\\"http://www.w3.org/2001/XMLSchema\\\"><Number>42</Number></SampleType>\"); }\n        }\n\n        [Fact]\n        public void DefaultMediaType_ReturnsApplicationXml()\n        {\n            MediaTypeHeaderValue mediaType = XmlSerializerMediaTypeFormatter.DefaultMediaType;\n            Assert.NotNull(mediaType);\n            Assert.Equal(\"application/xml\", mediaType.MediaType);\n        }\n\n        [Fact]\n        public void Indent_RoundTrips()\n        {\n            Assert.Reflection.BooleanProperty(\n                new XmlSerializerMediaTypeFormatter(),\n                c => c.Indent,\n                expectedDefaultValue: false);\n        }\n\n        [Fact]\n        public async Task ReadDeeplyNestedObjectWorks()\n        {\n            XmlSerializerMediaTypeFormatter formatter = new XmlSerializerMediaTypeFormatter()\n            {\n                MaxDepth = 5001\n            };\n\n            StringContent content = new StringContent(GetDeeplyNestedObject(5000));\n\n            content.Headers.ContentType = new MediaTypeHeaderValue(\"application/xml\");\n\n            Assert.IsType<Nest>(await formatter.ReadFromStreamAsync(typeof(Nest), await content.ReadAsStreamAsync(), content, null));\n        }\n\n        [Fact]\n        public void UseXmlSerializer_RoundTrips()\n        {\n            Assert.Reflection.BooleanProperty(\n                new XmlSerializerMediaTypeFormatter(),\n                c => c.UseXmlSerializer,\n                expectedDefaultValue: true);\n        }\n\n        [Theory]\n        [InlineData(typeof(IQueryable<string>))]\n        [InlineData(typeof(IEnumerable<string>))]\n        public async Task UseXmlFormatterWithNull(Type type)\n        {\n            XmlMediaTypeFormatter xmlFormatter = new XmlSerializerMediaTypeFormatter();\n            MemoryStream memoryStream = new MemoryStream();\n            HttpContent content = new StringContent(String.Empty);\n            await Assert.Task.SucceedsAsync(xmlFormatter.WriteToStreamAsync(type, null, memoryStream, content, transportContext: null));\n            memoryStream.Position = 0;\n            string serializedString = new StreamReader(memoryStream).ReadToEnd();\n            Assert.True(serializedString.Contains(\"nil=\\\"true\\\"\"),\n                \"Null value should be serialized as nil.\");\n            Assert.True(serializedString.ToLower().Contains(\"arrayofstring\"),\n                \"It should be serialized out as an array of string.\");\n        }\n\n        [Fact]\n        public async Task UseXmlSerializer_True()\n        {\n            XmlSerializerMediaTypeFormatter xmlFormatter = new XmlSerializerMediaTypeFormatter();\n            MemoryStream memoryStream = new MemoryStream();\n            HttpContent content = new StringContent(String.Empty);\n            await Assert.Task.SucceedsAsync(xmlFormatter.WriteToStreamAsync(typeof(SampleType), new SampleType(), memoryStream, content, transportContext: null));\n            memoryStream.Position = 0;\n            string serializedString = new StreamReader(memoryStream).ReadToEnd();\n            Assert.False(serializedString.Contains(\"DataContractSampleType\"),\n                \"SampleType should not be serialized with data contract name DataContractSampleType because UseXmlSerializer is set to true.\");\n            Assert.False(serializedString.Contains(\"version=\\\"1.0\\\" encoding=\\\"utf-8\\\"\"),\n              \"Using XmlSerializer should not emit the xml declaration by default.\");\n            Assert.False(serializedString.Contains(\"\\r\\n\"), \"Using default XmlSerializer should emit data without indentation.\");\n        }\n\n        [Fact]\n        public async Task UseXmlSerializer_True_Indent()\n        {\n            XmlSerializerMediaTypeFormatter xmlFormatter = new XmlSerializerMediaTypeFormatter { Indent = true };\n            MemoryStream memoryStream = new MemoryStream();\n            HttpContent content = new StringContent(String.Empty);\n            await Assert.Task.SucceedsAsync(xmlFormatter.WriteToStreamAsync(typeof(SampleType), new SampleType(), memoryStream, content, transportContext: null));\n            memoryStream.Position = 0;\n            string serializedString = new StreamReader(memoryStream).ReadToEnd();\n            Assert.True(serializedString.Contains(\"\\r\\n\"), \"Using default XmlSerializer with Indent set to true should emit data with indentation.\");\n        }\n\n        [Theory]\n        [TestDataSet(typeof(CommonUnitTestDataSets), \"RepresentativeValueAndRefTypeTestDataCollection\")]\n        public void CanReadType_ReturnsSameResultAsXmlSerializerConstructor(Type variationType, object testData)\n        {\n            TestXmlSerializerMediaTypeFormatter formatter = new TestXmlSerializerMediaTypeFormatter();\n\n            bool isSerializable = IsSerializableWithXmlSerializer(variationType, testData);\n            bool canSupport = formatter.CanReadTypeCaller(variationType);\n            if (isSerializable != canSupport)\n            {\n                Assert.Equal(isSerializable, canSupport);\n            }\n\n            // Ask a 2nd time to probe whether the cached result is treated the same\n            canSupport = formatter.CanReadTypeCaller(variationType);\n            Assert.Equal(isSerializable, canSupport);\n\n        }\n\n        [Fact]\n        public void SetSerializer_ThrowsWithNullType()\n        {\n            XmlSerializerMediaTypeFormatter formatter = new XmlSerializerMediaTypeFormatter();\n            XmlSerializer xmlSerializer = new XmlSerializer(typeof(string));\n            Assert.ThrowsArgumentNull(() => { formatter.SetSerializer(null, xmlSerializer); }, \"type\");\n        }\n\n        [Fact]\n        public void SetSerializer_ThrowsWithNullSerializer()\n        {\n            XmlSerializerMediaTypeFormatter formatter = new XmlSerializerMediaTypeFormatter();\n            Assert.ThrowsArgumentNull(() => { formatter.SetSerializer(typeof(string), (XmlSerializer)null); }, \"serializer\");\n        }\n\n        [Fact]\n        public void SetSerializer1_ThrowsWithNullSerializer()\n        {\n            XmlSerializerMediaTypeFormatter formatter = new XmlSerializerMediaTypeFormatter();\n            Assert.ThrowsArgumentNull(() => { formatter.SetSerializer<string>((XmlSerializer)null); }, \"serializer\");\n        }\n\n        [Fact]\n        public void SetSerializer2_ThrowsWithNullType()\n        {\n            XmlSerializerMediaTypeFormatter formatter = new XmlSerializerMediaTypeFormatter();\n            XmlObjectSerializer xmlObjectSerializer = new DataContractSerializer(typeof(string));\n            Assert.ThrowsArgumentNull(() => { formatter.SetSerializer(null, xmlObjectSerializer); }, \"type\");\n        }\n\n        [Fact]\n        public void SetSerializer2_ThrowsWithNullSerializer()\n        {\n            XmlSerializerMediaTypeFormatter formatter = new XmlSerializerMediaTypeFormatter();\n            Assert.ThrowsArgumentNull(() => { formatter.SetSerializer(typeof(string), (XmlObjectSerializer)null); }, \"serializer\");\n        }\n\n        [Fact]\n        public void SetSerializer3_ThrowsWithNullSerializer()\n        {\n            XmlSerializerMediaTypeFormatter formatter = new XmlSerializerMediaTypeFormatter();\n            Assert.ThrowsArgumentNull(() => { formatter.SetSerializer<string>((XmlSerializer)null); }, \"serializer\");\n        }\n\n        [Fact]\n        public void RemoveSerializer_ThrowsWithNullType()\n        {\n            XmlSerializerMediaTypeFormatter formatter = new XmlSerializerMediaTypeFormatter();\n            Assert.ThrowsArgumentNull(() => { formatter.RemoveSerializer(null); }, \"type\");\n        }\n\n        [Theory]\n        [TestDataSet(typeof(CommonUnitTestDataSets), \"RepresentativeValueAndRefTypeTestDataCollection\", RoundTripDataVariations)]\n        public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsyncUsingXmlSerializer(Type variationType, object testData)\n        {\n            // Guard\n            bool canSerialize = IsSerializableWithXmlSerializer(variationType, testData) && Assert.Http.CanRoundTrip(variationType);\n            if (canSerialize)\n            {\n                // Arrange\n                TestXmlSerializerMediaTypeFormatter formatter = new TestXmlSerializerMediaTypeFormatter();\n                formatter.SetSerializer(variationType, new XmlSerializer(variationType));\n\n                // Arrange & Act & Assert\n                object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n                Assert.Equal(testData, readObj);\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(XmlMediaTypeFormatterTests), \"BunchOfTypedObjectsTestDataCollection\", RoundTripDataVariations)]\n        public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsyncUsingXmlSerializer_ExtraTypes(Type variationType, object testData)\n        {\n            // Guard\n            bool canSerialize = IsSerializableWithXmlSerializer(variationType, testData) && Assert.Http.CanRoundTrip(variationType);\n            if (canSerialize)\n            {\n                // Arrange\n                TestXmlSerializerMediaTypeFormatter formatter = new TestXmlSerializerMediaTypeFormatter();\n                formatter.SetSerializer(variationType, new XmlSerializer(variationType, new Type[] { typeof(DBNull), }));\n\n                // Arrange & Act & Assert\n                object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n                Assert.Equal(testData, readObj);\n            }\n        }\n\n        // Test alternate null value; this serializer attempts to cast DBNull to variationType so typeof(string) variation fails\n        [Fact]\n        public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsyncUsingXmlSerializer_DBNull()\n        {\n            // Arrange\n            TestXmlSerializerMediaTypeFormatter formatter = new TestXmlSerializerMediaTypeFormatter();\n            Type variationType = typeof(DBNull);\n            formatter.SetSerializer(variationType, new XmlSerializer(variationType));\n            object testData = DBNull.Value;\n\n            // Arrange & Act & Assert\n            object readObj = await ReadFromStreamAsync_RoundTripsWriteToStreamAsync_Helper(formatter, variationType, testData);\n            Assert.Equal(testData, readObj);\n        }\n\n        public override Task ReadFromStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding)\n        {\n            // Arrange\n            XmlSerializerMediaTypeFormatter formatter = new XmlSerializerMediaTypeFormatter();\n            string formattedContent = \"<string>\" + content + \"</string>\";\n            string mediaType = string.Format(\"application/xml; charset={0}\", encoding);\n\n            // Act & assert\n            return ReadFromStreamAsync_UsesCorrectCharacterEncodingHelper(formatter, content, formattedContent, mediaType, encoding, isDefaultEncoding);\n        }\n\n        public override Task WriteToStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding)\n        {\n            // Arrange\n            XmlSerializerMediaTypeFormatter formatter = new XmlSerializerMediaTypeFormatter();\n            string formattedContent = \"<string>\" + content + \"</string>\";\n            string mediaType = string.Format(\"application/xml; charset={0}\", encoding);\n\n            // Act & assert\n            return WriteToStreamAsync_UsesCorrectCharacterEncodingHelper(formatter, content, formattedContent, mediaType, encoding, isDefaultEncoding);\n        }\n\n        static string GetDeeplyNestedObject(int depth)\n        {\n            StringBuilder sb = new StringBuilder();\n            for (int i = 0; i < depth; i++)\n            {\n                sb.Insert(0, \"<A>\");\n                sb.Append(\"</A>\");\n            }\n            sb.Insert(0, \"<Nest xmlns=\\\"http://example.com\\\">\");\n            sb.Append(\"</Nest>\");\n            sb.Insert(0, \"<?xml version=\\\"1.0\\\"?>\");\n\n            return sb.ToString();\n        }\n\n        public class TestXmlSerializerMediaTypeFormatter : XmlSerializerMediaTypeFormatter\n        {\n            public bool CanReadTypeCaller(Type type)\n            {\n                return CanReadType(type);\n            }\n\n            public bool CanWriteTypeCaller(Type type)\n            {\n                return CanWriteType(type);\n            }\n        }\n\n        [XmlRoot(\"Nest\", Namespace = \"http://example.com\")]\n        public class Nest\n        {\n            public Nest A { get; set; }\n        }\n\n        private bool IsSerializableWithXmlSerializer(Type type, object obj)\n        {\n            if (Assert.Http.IsKnownUnserializable(type, obj))\n            {\n                return false;\n            }\n\n            try\n            {\n                new XmlSerializer(type);\n                if (obj != null && obj.GetType() != type)\n                {\n                    new XmlSerializer(obj.GetType());\n                }\n            }\n            catch\n            {\n                return false;\n            }\n\n            return true;\n        }\n\n        private bool IsSerializableWithDataContractSerializer(Type type, object obj)\n        {\n            if (Assert.Http.IsKnownUnserializable(type, obj))\n            {\n                return false;\n            }\n\n            try\n            {\n                new DataContractSerializer(type);\n                if (obj != null && obj.GetType() != type)\n                {\n                    new DataContractSerializer(obj.GetType());\n                }\n            }\n            catch\n            {\n                return false;\n            }\n\n            return true;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/FormattingUtilitiesTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Net.Http.Headers;\nusing Microsoft.TestCommon;\nusing Newtonsoft.Json.Linq;\n\nnamespace System.Net.Http\n{\n    public class FormattingUtilitiesTests\n    {\n        public static TheoryDataSet<string, string> QuotedStrings\n        {\n            get\n            {\n                return new TheoryDataSet<string, string>()\n                {\n                    { @\"\"\"\"\"\", @\"\" },\n                    { @\"\"\"string\"\"\", @\"string\" },\n                    { @\"string\", @\"string\" },\n                    { @\"\"\"str\"\"ing\"\"\", @\"str\"\"ing\" },\n                };\n            }\n        }\n\n        public static TheoryDataSet<string> NotQuotedStrings\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {       \n                    @\" \"\"\",\n                    @\" \"\"\"\"\",\n                    @\"string\",\n                    @\"str\"\"ing\",\n                    @\"s\"\"trin\"\"g\",\n                };\n            }\n        }\n\n        public static TheoryDataSet<string> ValidHeaderTokens\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    Convert.ToChar(0x21).ToString(),\n                    Convert.ToChar(0x7E).ToString(),\n                    \"acb\",\n                    \"ABC\",\n                    \"a&b\",\n                };\n            }\n        }\n\n        public static TheoryDataSet<string> InvalidHeaderTokens\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    Convert.ToChar(0x20).ToString(),\n                    Convert.ToChar(0x7F).ToString(),\n                    null,\n                    \"<acb>\",\n                    \"[ABC]\",\n                    \"{a&b}\",\n                    \"æææøøøååå\",\n                    \"いくつかのテキスト\",\n                };\n            }\n        }\n\n        public static TheoryDataSet<DateTimeOffset, string> ValidDateStringValues\n        {\n            get\n            {\n                return new TheoryDataSet<DateTimeOffset, string>\n                {\n                    { new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), \"Sun, 06 Nov 1994 08:49:37 GMT\" },\n                };\n            }\n        }\n\n        public static TheoryDataSet<string, DateTimeOffset> ValidDateValues\n        {\n            get\n            {\n                return new TheoryDataSet<string, DateTimeOffset>\n                {\n                    // RFC1123 date/time value\n                    { \"Sun, 06 Nov 1994 08:49:37 GMT\", new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero) },\n                    { \"Sun, 06 Nov 1994 08:49:37\", new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero) },\n                    { \"6 Nov 1994 8:49:37 GMT\", new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero) },\n                    { \"6 Nov 1994 8:49:37\",  new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero) },\n                    { \"Sun, 06 Nov 94 08:49:37\",  new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero) },\n                    { \"6 Nov 94 8:49:37\",  new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero) },\n\n                    // RFC850 date/time value\n                    { \"Sunday, 06-Nov-94 08:49:37 GMT\",  new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero) },\n                    { \"Sunday, 6-Nov-94 8:49:37\",  new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero) },\n                    { \"Sun, 6-Nov-1994 8:49:37 GMT\", new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero) },\n\n                    // ANSI C's asctime() format\n                    { \"Sun Nov  06 08:49:37 1994\",  new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero) },\n                    { \"Sun Nov  6 8:49:37 1994\",  new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero) },\n\n                    // RFC5322 date/time\n                    { \"Sat, 08 Nov 1997 09:55:06 -0600\", new DateTimeOffset(1997, 11, 8, 9, 55, 6, new TimeSpan(-6, 0, 0)) },\n                    { \"8 Nov 1997 9:55:6\", new DateTimeOffset(1997, 11, 8, 9, 55, 6, TimeSpan.Zero) },\n                    { \"Sat, 8 Nov 1997 9:55:6 +0200\", new DateTimeOffset(1997, 11, 8, 9, 55, 6, new TimeSpan(2, 0, 0)) },\n                };\n            }\n        }\n\n        public static TheoryDataSet<string> InvalidDateValues\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    \"Sun, 06 Nov 1994 08:49:37 GMT invalid\",\n                    \"Sun, 06 Nov 1994 08:49:37 GMT,\",\n                    \",Sun, 06 Nov 1994 08:49:37 GMT\",\n                    \"Sun, 06 Nov 1994 08:49:37 æøå\",\n                    \"Sun, 06 æøå 1994 08:49:37 GMT\",\n                    \"Sun, 06 Nov 1994 08:49:37 いくつ\",\n                    \"Sun, 06 いくつ 1994 08:49:37 Nov\",\n                    \"æææøøøååå\",\n                    \"いくつかのテキスト\",\n                };\n            }\n        }\n\n        [Fact]\n        public void TypeIsCorrect()\n        {\n            Assert.Type.HasProperties(typeof(FormattingUtilities), TypeAssert.TypeProperties.IsClass | TypeAssert.TypeProperties.IsStatic);\n        }\n\n        [Fact]\n        public void IsJsonValueTypeReturnsTrue()\n        {\n            Assert.True(FormattingUtilities.IsJTokenType(typeof(JToken)), \"Should return true\");\n            Assert.True(FormattingUtilities.IsJTokenType(typeof(JValue)), \"Should return true\");\n            Assert.True(FormattingUtilities.IsJTokenType(typeof(JObject)), \"Should return true\");\n            Assert.True(FormattingUtilities.IsJTokenType(typeof(JArray)), \"Should return true\");\n        }\n\n        [Fact]\n        public void CreateEmptyContentHeadersReturnsEmptyHeaders()\n        {\n            HttpContentHeaders headers = FormattingUtilities.CreateEmptyContentHeaders();\n            Assert.NotNull(headers);\n            Assert.Empty(headers);\n        }\n\n        [Theory]\n        [TestDataSet(typeof(CommonUnitTestDataSets), \"EmptyStrings\")]\n        public void UnquoteTokenReturnsSameRefOnEmpty(string empty)\n        {\n            string result = FormattingUtilities.UnquoteToken(empty);\n            Assert.Same(empty, result);\n        }\n\n        [Theory]\n        [PropertyData(\"NotQuotedStrings\")]\n        public void UnquoteTokenReturnsSameRefNonQuotedStrings(string test)\n        {\n            string result = FormattingUtilities.UnquoteToken(test);\n            Assert.Equal(test, result);\n        }\n\n        [Theory]\n        [PropertyData(\"QuotedStrings\")]\n        public void UnquoteTokenReturnsUnquotedStrings(string token, string expectedResult)\n        {\n            string result = FormattingUtilities.UnquoteToken(token);\n            Assert.Equal(expectedResult, result);\n        }\n\n        [Theory]\n        [PropertyData(\"ValidHeaderTokens\")]\n        public void ValidateHeaderToken_AcceptsValidTokens(string validToken)\n        {\n            bool result = FormattingUtilities.ValidateHeaderToken(validToken);\n            Assert.True(result);\n        }\n\n        [Theory]\n        [PropertyData(\"InvalidHeaderTokens\")]\n        public void ValidateHeaderToken_RejectsInvalidTokens(string invalidToken)\n        {\n            bool result = FormattingUtilities.ValidateHeaderToken(invalidToken);\n            Assert.False(result);\n        }\n\n        [Theory]\n        [PropertyData(\"ValidDateStringValues\")]\n        public void DateToString_GeneratesValidValue(DateTimeOffset input, string expectedValue)\n        {\n            string actualValue = FormattingUtilities.DateToString(input);\n            Assert.Equal(expectedValue, actualValue);\n        }\n\n        [Theory]\n        [PropertyData(\"ValidDateValues\")]\n        public void TryParseDate_AcceptsValidDates(string dateValue, DateTimeOffset expectedDate)\n        {\n            DateTimeOffset actualDate;\n            Assert.True(FormattingUtilities.TryParseDate(dateValue, out actualDate));\n            Assert.Equal(expectedDate, actualDate);\n        }\n\n        [Theory]\n        [PropertyData(\"InvalidDateValues\")]\n        public void TryStringToDate_RejectsInvalidDates(string dateValue)\n        {\n            DateTimeOffset actualDate;\n            Assert.False(FormattingUtilities.TryParseDate(dateValue, out actualDate));\n        }\n\n        [Theory]\n        [InlineData(\"0\", 0)]\n        [InlineData(\"1\", 1)]\n        [InlineData(\"2147483647\", Int32.MaxValue)]\n        public void TryParseInt32_AcceptsValidNumbers(string intValue, int expectedInt)\n        {\n            int actualInt;\n            Assert.True(FormattingUtilities.TryParseInt32(intValue, out actualInt));\n            Assert.Equal(expectedInt, actualInt);\n        }\n\n        [Theory]\n        [InlineData(\"-2147483649\")]\n        [InlineData(\"-2147483648\")]\n        [InlineData(\"2147483648\")]\n        [InlineData(\" 0\")]\n        public void TryParseInt32_RejectsInvalidNumbers(string intValue)\n        {\n            int actualInt;\n            Assert.False(FormattingUtilities.TryParseInt32(intValue, out actualInt));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Handlers/HttpProgressEventArgsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Handlers\n{\n    public class HttpProgressEventArgsTest\n    {\n        [Fact]\n        public void Constructor_Initializes()\n        {\n            // Arrange\n            int progressPercentage = 10;\n            object userState = new object();\n            long bytesTransferred = 10L * 1024 * 1024 * 1024;\n            long? totalBytes = 10L * 1024 * 1024 * 1024;\n\n            // Act\n            HttpProgressEventArgs args = new HttpProgressEventArgs(progressPercentage, userState, bytesTransferred, totalBytes);\n\n            // Assert\n            Assert.Equal(progressPercentage, args.ProgressPercentage);\n            Assert.Equal(userState, args.UserState);\n            Assert.Equal(bytesTransferred, args.BytesTransferred);\n            Assert.Equal(totalBytes, args.TotalBytes);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Handlers/ProgressContentTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Handlers\n{\n    public class ProgressContentTest\n    {\n        private const string TestHeader = \"TestHeader\";\n        private const string TestValue = \"TestValue\";\n\n        [Fact]\n        public void Constructor_CopyHeadersFromInnerContent()\n        {\n            // Arrange\n            StringContent innerContent = new StringContent(\"HelloWorld!\");\n            innerContent.Headers.Add(TestHeader, TestValue);\n            HttpRequestMessage request = new HttpRequestMessage();\n            ProgressMessageHandler progressHandler = new ProgressMessageHandler();\n\n            // Act\n            ProgressContent progressContent = new ProgressContent(innerContent, progressHandler, request);\n\n            // Assert\n            ValidateContentHeader(progressContent);\n            Assert.Equal(innerContent.Headers.ContentType, progressContent.Headers.ContentType);\n            Assert.Equal(innerContent.Headers.ContentLength, progressContent.Headers.ContentLength);\n        }\n\n        [Fact]\n        public async Task SerializeToStreamAsync_InsertsProgressStream()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.Content = new StringContent(\"HelloWorld!\");\n\n            MockProgressEventHandler progressEventHandler = new MockProgressEventHandler();\n            ProgressMessageHandler progressHandler = MockProgressEventHandler.CreateProgressMessageHandler(out progressEventHandler, sendProgress: true);\n            ProgressContent progressContent = new ProgressContent(request.Content, progressHandler, request);\n            MemoryStream memStream = new MemoryStream();\n\n            // Act\n            await progressContent.CopyToAsync(memStream);\n\n            // Assert\n            Assert.True(progressEventHandler.WasInvoked);\n            Assert.Equal(request, progressEventHandler.Sender);\n            Assert.Equal(request.Content.Headers.ContentLength, progressEventHandler.EventArgs.TotalBytes);\n        }\n\n        [Fact]\n        public void Dispose_DisposesInnerContent()\n        {\n            // Arrange\n            StringContent innerContent = new StringContent(\"HelloWorld!\");\n            HttpRequestMessage request = new HttpRequestMessage();\n            ProgressMessageHandler progressHandler = new ProgressMessageHandler();\n            ProgressContent progressContent = new ProgressContent(innerContent, progressHandler, request);\n\n            // Act\n            progressContent.Dispose();\n\n            // Assert\n            Assert.ThrowsObjectDisposed(() => innerContent.LoadIntoBufferAsync(), typeof(StringContent).FullName);\n        }\n\n        private static void ValidateContentHeader(HttpContent content)\n        {\n            IEnumerable<string> values;\n            bool headerResult = content.Headers.TryGetValues(TestHeader, out values);\n            Assert.True(headerResult);\n            Assert.Equal(TestValue, values.First());\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Handlers/ProgressMessageHandlerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Handlers\n{\n    public class ProgressMessageHandlerTest\n    {\n        private const string TestHeader = \"TestHeader\";\n        private const string TestValue = \"TestValue\";\n\n        [Theory]\n        [InlineData(false, false)]\n        [InlineData(false, true)]\n        [InlineData(true, false)]\n        [InlineData(true, true)]\n        public async Task SendAsync_DoesNotInsertSendProgressWithoutEntityOrHandlerPresent(bool insertRequestEntity, bool addSendProgressHandler)\n        {\n            // Arrange\n            HttpMessageInvoker invoker = CreateMessageInvoker(includeResponseEntity: false, addReceiveProgressHandler: false, addSendProgressHandler: addSendProgressHandler);\n            HttpRequestMessage request = new HttpRequestMessage();\n            HttpContent content = null;\n            if (insertRequestEntity)\n            {\n                content = new StringContent(\"Request Entity!\");\n                content.Headers.Add(TestHeader, TestValue);\n                request.Content = content;\n            }\n\n            // Act\n            await invoker.SendAsync(request, CancellationToken.None);\n\n            // Assert\n            if (insertRequestEntity && addSendProgressHandler)\n            {\n                ValidateContentHeader(request.Content);\n                Assert.NotSame(content, request.Content);\n                Assert.IsType<ProgressContent>(request.Content);\n            }\n            else\n            {\n                if (insertRequestEntity)\n                {\n                    Assert.IsType<StringContent>(request.Content);\n                }\n                else\n                {\n                    Assert.Null(request.Content);\n                }\n            }\n        }\n\n        [Theory]\n        [InlineData(false, false)]\n        [InlineData(false, true)]\n        [InlineData(true, false)]\n        [InlineData(true, true)]\n        public async Task SendAsync_InsertsReceiveProgressWhenResponseEntityPresent(bool insertResponseEntity, bool addReceiveProgressHandler)\n        {\n            // Arrange\n            HttpMessageInvoker invoker = CreateMessageInvoker(includeResponseEntity: insertResponseEntity, addSendProgressHandler: false, addReceiveProgressHandler: addReceiveProgressHandler);\n            HttpRequestMessage request = new HttpRequestMessage();\n\n            // Act\n            HttpResponseMessage response = await invoker.SendAsync(request, CancellationToken.None);\n\n            // Assert\n            if (insertResponseEntity && addReceiveProgressHandler)\n            {\n                ValidateContentHeader(response.Content);\n                Assert.NotNull(response.Content);\n                Assert.IsType<StreamContent>(response.Content);\n            }\n            else\n            {\n                if (insertResponseEntity)\n                {\n                    Assert.IsType<StringContent>(response.Content);\n                }\n                else\n                {\n                    Assert.NotNull(response.Content);\n                    Assert.Equal(0L, response.Content.Headers.ContentLength);\n                }\n            }\n        }\n\n        private static HttpMessageInvoker CreateMessageInvoker(bool includeResponseEntity, bool addSendProgressHandler, bool addReceiveProgressHandler)\n        {\n            ShortCircuitMessageHandler innerHandler = new ShortCircuitMessageHandler(includeResponseEntity);\n            ProgressMessageHandler progress = new ProgressMessageHandler(innerHandler);\n            if (addSendProgressHandler)\n            {\n                progress.HttpSendProgress += new MockProgressEventHandler().Handler;\n            }\n\n            if (addReceiveProgressHandler)\n            {\n                progress.HttpReceiveProgress += new MockProgressEventHandler().Handler;\n            }\n\n            return new HttpMessageInvoker(progress);\n        }\n\n        private static void ValidateContentHeader(HttpContent content)\n        {\n            IEnumerable<string> values;\n            bool headerResult = content.Headers.TryGetValues(TestHeader, out values);\n            Assert.True(headerResult);\n            Assert.Equal(TestValue, values.First());\n        }\n\n        private class ShortCircuitMessageHandler : HttpMessageHandler\n        {\n            bool _includeResponseEntity;\n\n            public ShortCircuitMessageHandler(bool includeResponseEntity)\n            {\n                _includeResponseEntity = includeResponseEntity;\n            }\n\n            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n            {\n                HttpResponseMessage response = request.CreateResponse();\n                if (_includeResponseEntity)\n                {\n                    response.Content = new StringContent(\"Response Entity\");\n                    response.Content.Headers.Add(TestHeader, TestValue);\n                }\n\n                return Task.FromResult(response);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Handlers/ProgressStreamTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Net.Http.Handlers\n{\n    public class ProgressStreamTest\n    {\n        [Fact]\n        public async Task Read_ReportsBytesRead()\n        {\n            // Arrange\n            HttpResponseMessage response = CreateResponse();\n            Stream innerStream = await response.Content.ReadAsStreamAsync();\n            long? expectedLength = response.Content.Headers.ContentLength;\n            MockProgressEventHandler mockProgressEventHandler;\n            ProgressMessageHandler progressMessageHandler = MockProgressEventHandler.CreateProgressMessageHandler(out mockProgressEventHandler, sendProgress: false);\n            ProgressStream progressStream = CreateProgressStream(innerStream: innerStream, progressMessageHandler: progressMessageHandler, response: response);\n\n            // Act/Assert\n            int totalBytesRead = 0;\n            int bytesRead = 0;\n            do\n            {\n                byte[] buffer = new byte[8];\n                bytesRead = progressStream.Read(buffer, 0, buffer.Length);\n                totalBytesRead += bytesRead;\n\n                Assert.Equal(totalBytesRead, mockProgressEventHandler.EventArgs.BytesTransferred);\n                Assert.Equal((100L * totalBytesRead) / expectedLength, mockProgressEventHandler.EventArgs.ProgressPercentage);\n            }\n            while (bytesRead > 0);\n\n            Assert.Equal(expectedLength, mockProgressEventHandler.EventArgs.TotalBytes);\n            Assert.Equal(100, mockProgressEventHandler.EventArgs.ProgressPercentage);\n        }\n\n        [Fact]\n        public async Task ReadByte_ReportsBytesRead()\n        {\n            // Arrange\n            HttpResponseMessage response = CreateResponse();\n            Stream innerStream = await response.Content.ReadAsStreamAsync();\n            long? expectedLength = response.Content.Headers.ContentLength;\n            MockProgressEventHandler mockProgressEventHandler;\n            ProgressMessageHandler progressMessageHandler = MockProgressEventHandler.CreateProgressMessageHandler(out mockProgressEventHandler, sendProgress: false);\n            ProgressStream progressStream = CreateProgressStream(innerStream: innerStream, progressMessageHandler: progressMessageHandler, response: response);\n\n            // Act/Assert\n            int totalBytesRead = 0;\n            while (progressStream.ReadByte() != -1)\n            {\n                totalBytesRead += 1;\n\n                Assert.Equal(totalBytesRead, mockProgressEventHandler.EventArgs.BytesTransferred);\n                Assert.Equal((100L * totalBytesRead) / expectedLength, mockProgressEventHandler.EventArgs.ProgressPercentage);\n            }\n\n            Assert.Equal(expectedLength, mockProgressEventHandler.EventArgs.TotalBytes);\n            Assert.Equal(100, mockProgressEventHandler.EventArgs.ProgressPercentage);\n        }\n\n#if !Testing_NetStandard1_3 // BeginX and EndX not supported on Streams in netstandard1.3\n        [Fact]\n        public async Task BeginEndRead_ReportsBytesRead()\n        {\n            // Arrange\n            HttpResponseMessage response = CreateResponse();\n            Stream innerStream = await response.Content.ReadAsStreamAsync();\n            long? expectedLength = response.Content.Headers.ContentLength;\n            MockProgressEventHandler mockProgressEventHandler;\n            ProgressMessageHandler progressMessageHandler = MockProgressEventHandler.CreateProgressMessageHandler(out mockProgressEventHandler, sendProgress: false);\n            ProgressStream progressStream = CreateProgressStream(innerStream: innerStream, progressMessageHandler: progressMessageHandler, response: response);\n            object userState = new object();\n\n            // Act/Assert\n            int totalBytesRead = 0;\n            int bytesRead = 0;\n            do\n            {\n                byte[] buffer = new byte[8];\n                IAsyncResult result = progressStream.BeginRead(buffer, 0, buffer.Length, null, userState);\n                bytesRead = progressStream.EndRead(result);\n                totalBytesRead += bytesRead;\n\n                Assert.Same(userState, mockProgressEventHandler.EventArgs.UserState);\n                Assert.Equal(totalBytesRead, mockProgressEventHandler.EventArgs.BytesTransferred);\n                Assert.Equal((100L * totalBytesRead) / expectedLength, mockProgressEventHandler.EventArgs.ProgressPercentage);\n            }\n            while (bytesRead > 0);\n\n            Assert.Equal(expectedLength, mockProgressEventHandler.EventArgs.TotalBytes);\n            Assert.Equal(100, mockProgressEventHandler.EventArgs.ProgressPercentage);\n        }\n#endif\n\n        [Fact]\n        public async Task ReadAsync_ReportsBytesRead()\n        {\n            // Arrange\n            HttpResponseMessage response = CreateResponse();\n            Stream innerStream = await response.Content.ReadAsStreamAsync();\n            long? expectedLength = response.Content.Headers.ContentLength;\n            MockProgressEventHandler mockProgressEventHandler;\n            ProgressMessageHandler progressMessageHandler = MockProgressEventHandler.CreateProgressMessageHandler(out mockProgressEventHandler, sendProgress: false);\n            ProgressStream progressStream = CreateProgressStream(innerStream: innerStream, progressMessageHandler: progressMessageHandler, response: response);\n            object userState = new object();\n\n            // Act/Assert\n            int totalBytesRead = 0;\n            int bytesRead = 0;\n            do\n            {\n                byte[] buffer = new byte[8];\n                bytesRead = await progressStream.ReadAsync(buffer, 0, buffer.Length);\n                totalBytesRead += bytesRead;\n\n                Assert.Equal(totalBytesRead, mockProgressEventHandler.EventArgs.BytesTransferred);\n                Assert.Equal((100L * totalBytesRead) / expectedLength, mockProgressEventHandler.EventArgs.ProgressPercentage);\n            }\n            while (bytesRead > 0);\n\n            Assert.Equal(expectedLength, mockProgressEventHandler.EventArgs.TotalBytes);\n            Assert.Equal(100, mockProgressEventHandler.EventArgs.ProgressPercentage);\n        }\n\n        [Fact]\n        public void Write_ReportsBytesWritten()\n        {\n            // Arrange\n            HttpRequestMessage request = CreateRequest();\n            Stream innerStream = new MemoryStream();\n            byte[] buffer = CreateBufferContent();\n            long? expectedLength = request.Content.Headers.ContentLength;\n            MockProgressEventHandler mockProgressEventHandler;\n            ProgressMessageHandler progressMessageHandler = MockProgressEventHandler.CreateProgressMessageHandler(out mockProgressEventHandler, sendProgress: true);\n            ProgressStream progressStream = CreateProgressStream(innerStream: innerStream, progressMessageHandler: progressMessageHandler, request: request);\n\n            // Act/Assert\n            int totalBytesWritten = 0;\n            int bytesWritten = 0;\n            while (totalBytesWritten < expectedLength)\n            {\n                bytesWritten = Math.Min(8, (int)expectedLength - totalBytesWritten);\n                progressStream.Write(buffer, totalBytesWritten, bytesWritten);\n                totalBytesWritten += bytesWritten;\n\n                Assert.Equal(totalBytesWritten, mockProgressEventHandler.EventArgs.BytesTransferred);\n                Assert.Equal((100L * totalBytesWritten) / expectedLength, mockProgressEventHandler.EventArgs.ProgressPercentage);\n            }\n\n            Assert.Equal(expectedLength, mockProgressEventHandler.EventArgs.TotalBytes);\n            Assert.Equal(100, mockProgressEventHandler.EventArgs.ProgressPercentage);\n        }\n\n        [Fact]\n        public void WriteByte_ReportsBytesWritten()\n        {\n            // Arrange\n            HttpRequestMessage request = CreateRequest();\n            Stream innerStream = new MemoryStream();\n            byte[] buffer = CreateBufferContent();\n            long? expectedLength = request.Content.Headers.ContentLength;\n            MockProgressEventHandler mockProgressEventHandler;\n            ProgressMessageHandler progressMessageHandler = MockProgressEventHandler.CreateProgressMessageHandler(out mockProgressEventHandler, sendProgress: true);\n            ProgressStream progressStream = CreateProgressStream(innerStream: innerStream, progressMessageHandler: progressMessageHandler, request: request);\n\n            // Act/Assert\n            int totalBytesWritten = 0;\n            while (totalBytesWritten < expectedLength)\n            {\n                progressStream.WriteByte(buffer[totalBytesWritten]);\n                totalBytesWritten += 1;\n\n                Assert.Equal(totalBytesWritten, mockProgressEventHandler.EventArgs.BytesTransferred);\n                Assert.Equal((100L * totalBytesWritten) / expectedLength, mockProgressEventHandler.EventArgs.ProgressPercentage);\n            }\n\n            Assert.Equal(expectedLength, mockProgressEventHandler.EventArgs.TotalBytes);\n            Assert.Equal(100, mockProgressEventHandler.EventArgs.ProgressPercentage);\n        }\n\n#if !Testing_NetStandard1_3 // BeginX and EndX not supported on Streams in netstandard1.3\n        [Fact]\n        public void BeginEndWrite_ReportsBytesWritten()\n        {\n            // Arrange\n            using (ManualResetEvent writeComplete = new ManualResetEvent(false))\n            {\n                HttpRequestMessage request = CreateRequest();\n                Stream innerStream = new MemoryStream();\n                byte[] buffer = CreateBufferContent();\n                long? expectedLength = request.Content.Headers.ContentLength;\n                MockProgressEventHandler mockProgressEventHandler;\n                ProgressMessageHandler progressMessageHandler = MockProgressEventHandler.CreateProgressMessageHandler(out mockProgressEventHandler, sendProgress: true);\n                ProgressStream progressStream = CreateProgressStream(innerStream: innerStream, progressMessageHandler: progressMessageHandler, request: request);\n                object userState = new object();\n\n                // Act/Assert\n                int totalBytesWritten = 0;\n                int bytesWritten = 0;\n                while (totalBytesWritten < expectedLength)\n                {\n                    bytesWritten = Math.Min(8, (int)expectedLength - totalBytesWritten);\n                    IAsyncResult result = progressStream.BeginWrite(buffer, totalBytesWritten, bytesWritten,\n                        ia =>\n                        {\n                            progressStream.EndWrite(ia);\n                            writeComplete.Set();\n                        },\n                        userState);\n\n                    writeComplete.WaitOne();\n                    writeComplete.Reset();\n                    totalBytesWritten += bytesWritten;\n\n                    Assert.Same(userState, mockProgressEventHandler.EventArgs.UserState);\n                    Assert.Equal(totalBytesWritten, mockProgressEventHandler.EventArgs.BytesTransferred);\n                    Assert.Equal((100L * totalBytesWritten) / expectedLength, mockProgressEventHandler.EventArgs.ProgressPercentage);\n                }\n\n                Assert.Equal(expectedLength, mockProgressEventHandler.EventArgs.TotalBytes);\n                Assert.Equal(100, mockProgressEventHandler.EventArgs.ProgressPercentage);\n            }\n        }\n#endif\n\n        [Fact]\n        public async Task WriteAsync_ReportsBytesWritten()\n        {\n            // Arrange\n            using (ManualResetEvent writeComplete = new ManualResetEvent(false))\n            {\n                HttpRequestMessage request = CreateRequest();\n                Stream innerStream = new MemoryStream();\n                byte[] buffer = CreateBufferContent();\n                long? expectedLength = request.Content.Headers.ContentLength;\n                MockProgressEventHandler mockProgressEventHandler;\n                ProgressMessageHandler progressMessageHandler = MockProgressEventHandler.CreateProgressMessageHandler(out mockProgressEventHandler, sendProgress: true);\n                ProgressStream progressStream = CreateProgressStream(innerStream: innerStream, progressMessageHandler: progressMessageHandler, request: request);\n                object userState = new object();\n\n                // Act/Assert\n                int totalBytesWritten = 0;\n                int bytesWritten = 0;\n                while (totalBytesWritten < expectedLength)\n                {\n                    bytesWritten = Math.Min(8, (int)expectedLength - totalBytesWritten);\n                    await progressStream.WriteAsync(buffer, totalBytesWritten, bytesWritten);\n\n                    totalBytesWritten += bytesWritten;\n\n                    Assert.Equal(totalBytesWritten, mockProgressEventHandler.EventArgs.BytesTransferred);\n                    Assert.Equal((100L * totalBytesWritten) / expectedLength, mockProgressEventHandler.EventArgs.ProgressPercentage);\n                }\n\n                Assert.Equal(expectedLength, mockProgressEventHandler.EventArgs.TotalBytes);\n                Assert.Equal(100, mockProgressEventHandler.EventArgs.ProgressPercentage);\n            }\n        }\n\n        internal static ProgressStream CreateProgressStream(\n            Stream innerStream = null,\n            ProgressMessageHandler progressMessageHandler = null,\n            HttpRequestMessage request = null,\n            HttpResponseMessage response = null)\n        {\n            Stream iStream = innerStream ?? new Mock<Stream>().Object;\n            ProgressMessageHandler pHandler = progressMessageHandler ?? new ProgressMessageHandler();\n            HttpRequestMessage req = request ?? new HttpRequestMessage();\n            HttpResponseMessage rsp = response ?? new HttpResponseMessage() { Content = new StreamContent(Stream.Null) };\n            return new ProgressStream(iStream, pHandler, req, rsp);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage\n            {\n                Content = CreateStringContent()\n            };\n        }\n\n        private static HttpResponseMessage CreateResponse()\n        {\n            return new HttpResponseMessage\n            {\n                Content = CreateStringContent()\n            };\n        }\n\n        private static String CreateContent()\n        {\n            StringBuilder content = new StringBuilder();\n            for (int count = 0; count < 100; count++)\n            {\n                content.Append(\"1234567890\");\n            }\n            return content.ToString();\n        }\n\n        private static HttpContent CreateStringContent()\n        {\n            return new StringContent(CreateContent());\n        }\n\n        private static byte[] CreateBufferContent()\n        {\n            return Encoding.UTF8.GetBytes(CreateContent());\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Handlers/ProgressWriteAsyncResultTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Net.Http.Formatting.Mocks;\nusing System.Text;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Net.Http.Handlers\n{\n    public class ProgressWriteAsyncResultTest\n    {\n        static readonly byte[] sampleData = Encoding.UTF8.GetBytes(\"Hello World! Hello World! Hello World! Hello World! Hello World!\");\n\n        [Fact]\n        public void Constructor_BeginWriteOnInnerStream()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>();\n            ProgressStream progressStream = ProgressStreamTest.CreateProgressStream();\n\n            // Act\n            IAsyncResult result = new ProgressWriteAsyncResult(\n                mockInnerStream.Object, progressStream, sampleData, 2, 4, null, null);\n\n            // Assert \n            mockInnerStream.Verify(s => s.BeginWrite(sampleData, 2, 4, It.IsAny<AsyncCallback>(), It.IsAny<object>()),\n                Times.Once());\n        }\n\n        [Fact]\n        public void Constructor_CompletesSynchronouslyIfInnerStreamCompletesSynchronously()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>();\n            object userState = new object();\n            IAsyncResult mockIAsyncResult = MockCompletedAsyncResult.Create(true, userState);\n            mockInnerStream.Setup(s => s.BeginWrite(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<AsyncCallback>(), It.IsAny<object>()))\n                .Returns(mockIAsyncResult);\n            ProgressStream progressStream = ProgressStreamTest.CreateProgressStream();\n\n            // Act\n            IAsyncResult result = new ProgressWriteAsyncResult(\n                mockInnerStream.Object, progressStream, sampleData, 2, 4, null, userState);\n\n            // Assert \n            Assert.True(result.IsCompleted);\n            Assert.True(result.CompletedSynchronously);\n            Assert.Same(userState, result.AsyncState);\n        }\n\n        [Fact]\n        public void Constructor_CompletesWithExceptionIfInnerStreamThrows()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>();\n            mockInnerStream.Setup(s => s.BeginWrite(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<AsyncCallback>(), It.IsAny<object>()))\n                .Throws<ApplicationException>();\n            ProgressStream progressStream = ProgressStreamTest.CreateProgressStream();\n\n            // Act\n            IAsyncResult result = new ProgressWriteAsyncResult(\n                mockInnerStream.Object, progressStream, sampleData, 2, 2, null, null);\n\n            // Assert \n            Assert.True(result.IsCompleted);\n            Assert.Throws<ApplicationException>(() => ProgressWriteAsyncResult.End(result));\n        }\n\n        [Theory]\n        [InlineData(0, 10)]\n        [InlineData(10, 1)]\n        public void Constructor_ReportsBytesWritten(int offset, int count)\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>();\n            object userState = new object();\n            IAsyncResult mockIAsyncResult = MockCompletedAsyncResult.Create(true, userState);\n            mockInnerStream.Setup(s => s.BeginWrite(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<AsyncCallback>(), It.IsAny<object>()))\n                .Returns(mockIAsyncResult);\n\n            MockProgressEventHandler mockProgressHandler;\n            ProgressMessageHandler progressMessageHandler = MockProgressEventHandler.CreateProgressMessageHandler(out mockProgressHandler, sendProgress: true);\n            HttpRequestMessage request = new HttpRequestMessage();\n\n            ProgressStream progressStream = ProgressStreamTest.CreateProgressStream(progressMessageHandler: progressMessageHandler, request: request);\n\n            // Act\n            IAsyncResult result = new ProgressWriteAsyncResult(\n                mockInnerStream.Object, progressStream, sampleData, offset, count, null, userState);\n\n            // Assert \n            Assert.True(mockProgressHandler.WasInvoked);\n            Assert.Same(request, mockProgressHandler.Sender);\n            Assert.Equal(count, mockProgressHandler.EventArgs.BytesTransferred);\n            Assert.Same(userState, mockProgressHandler.EventArgs.UserState);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Headers/CookieHeaderValueTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Headers\n{\n    public class CookieHeaderValueTest\n    {\n        public static TheoryDataSet<CookieHeaderValue, string> CookieHeaderDataSet\n        {\n            get\n            {\n                var dataset = new TheoryDataSet<CookieHeaderValue, string>();\n                NameValueCollection nvc = new NameValueCollection();\n                nvc.Add(\"n1\", \"v1\");\n                nvc.Add(\"n2\", \"v2\");\n                nvc.Add(\"n3\", \"v3\");\n                CookieHeaderValue header1 = new CookieHeaderValue(\"name1\", nvc)\n                {\n                    Domain = \"domain1\",\n                    Expires = new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero),\n                    HttpOnly = true,\n                    MaxAge = TimeSpan.FromDays(1),\n                    Path = \"path1\",\n                    Secure = true\n                };\n                dataset.Add(header1, \"name1=n1=v1&n2=v2&n3=v3; expires=Sun, 06 Nov 1994 08:49:37 GMT; max-age=86400; domain=domain1; path=path1; secure; httponly\");\n\n                CookieHeaderValue header2 = new CookieHeaderValue(\"name2\", \"\");\n                dataset.Add(header2, \"name2=\");\n\n                CookieHeaderValue header3 = new CookieHeaderValue(\"name2\", \"value2\");\n                dataset.Add(header3, \"name2=value2\");\n\n                CookieHeaderValue header4 = new CookieHeaderValue(\"name4\", \"value4\")\n                {\n                    MaxAge = TimeSpan.FromDays(1),\n                };\n                dataset.Add(header4, \"name4=value4; max-age=86400\");\n\n                CookieHeaderValue header5 = new CookieHeaderValue(\"name5\", \"value5\")\n                {\n                    Domain = \"domain1\",\n                    Expires = new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero),\n                };\n                dataset.Add(header5, \"name5=value5; expires=Sun, 06 Nov 1994 08:49:37 GMT; domain=domain1\");\n\n                return dataset;\n            }\n        }\n\n        public static TheoryDataSet<string> CookieHeaderDataSet_NoCookie\n        {\n            get\n            {\n                var dataSet = new TheoryDataSet<string>();\n                foreach (var item in CookieHeaderDataSet)\n                {\n                    dataSet.Add((string)item[1]);\n                }\n\n                return dataSet;\n            }\n        }\n\n        public static TheoryDataSet<string> InvalidCookieHeaderDataSet\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    \"expires=Sun, 06 Nov 1994 08:49:37 GMT; max-age=86400; domain=domain1\",\n                    \"name=value; expires=Sun, 06 Nov 1994 08:49:37 ZZZ; max-age=86400; domain=domain1\",\n                    \"name=value; expires=Sun, 06 Nov 1994 08:49:37 GMT; max-age=-86400; domain=domain1\",\n                };\n            }\n        }\n\n        [Fact]\n        public void CookieHeaderValue_Ctor1_InitializesCorrectly()\n        {\n            CookieHeaderValue header = new CookieHeaderValue(\"cookie\", \"value\");\n            CookieState cookie = Assert.Single(header.Cookies);\n            Assert.Equal(\"cookie\", cookie.Name);\n            Assert.Equal(\"value\", cookie.Values.AllKeys[0]);\n        }\n\n        [Fact]\n        public void CookieHeaderValue_Ctor2_InitializesCorrectly()\n        {\n            NameValueCollection nvc = new NameValueCollection();\n            nvc.Add(\"name\", \"value\");\n            CookieHeaderValue header = new CookieHeaderValue(\"cookie\", nvc);\n            CookieState cookie = Assert.Single(header.Cookies);\n            Assert.Equal(\"cookie\", cookie.Name);\n            Assert.Equal(\"name\", cookie.Values.AllKeys[0]);\n            Assert.Equal(\"value\", cookie.Values[\"name\"]);\n        }\n\n        [Fact]\n        public void CookieHeaderValue_Clone()\n        {\n            // Arrange\n            NameValueCollection nvc = new NameValueCollection();\n            nvc.Add(\"name\", \"value\");\n            CookieHeaderValue expectedValue = new CookieHeaderValue(\"cookie\", nvc);\n            expectedValue.Domain = \"domain\";\n            expectedValue.Expires = DateTimeOffset.Now;\n            expectedValue.MaxAge = TimeSpan.FromDays(10);\n            expectedValue.Path = \"path\";\n            expectedValue.HttpOnly = true;\n            expectedValue.Secure = true;\n\n            // Act\n            CookieHeaderValue actualValue = expectedValue.Clone() as CookieHeaderValue;\n\n            // Assert\n            Assert.Equal(expectedValue.ToString(), actualValue.ToString());\n        }\n\n        [Theory]\n        [PropertyData(\"CookieHeaderDataSet\")]\n        public void CookieHeaderValue_ToString(CookieHeaderValue input, string expectedValue)\n        {\n            Assert.Equal(expectedValue, input.ToString());\n        }\n\n        [Theory]\n        [InlineData(\"\")]\n        [InlineData(null)]\n        public void CookieHeaderValue_GetItem_ReturnsNullIfNameIsNullOrEmpty(string name)\n        {\n            CookieHeaderValue header = new CookieHeaderValue(\"cookie\", \"value\");\n            Assert.Null(header[name]);\n        }\n\n        [Fact]\n        public void CookieHeaderValue_GetItem_ReturnsCookie()\n        {\n            CookieHeaderValue header = new CookieHeaderValue(\"cookie\", \"value\");\n\n            Assert.Single(header.Cookies);\n            CookieState state = header[\"cookie\"];\n            Assert.Equal(\"value\", state.Value);\n        }\n\n        [Fact]\n        public void CookieHeaderValue_GetItem_CreatesEmptyCookieIfNotAlreadyPresent()\n        {\n            CookieHeaderValue header = new CookieHeaderValue(\"cookie\", \"value\");\n\n            CookieState state = header[\"newstate\"];\n            Assert.Equal(2, header.Cookies.Count);\n            Assert.Equal(String.Empty, state.Value);\n        }\n\n        [Theory]\n        [PropertyData(\"CookieHeaderDataSet_NoCookie\")]\n        public void CookieHeaderValue_TryParse_AcceptsValidValues(string expectedValue)\n        {\n            CookieHeaderValue header;\n            bool result = CookieHeaderValue.TryParse(expectedValue, out header);\n\n            Assert.True(result);\n            Assert.Equal(expectedValue, header.ToString());\n        }\n\n        [Theory]\n        [PropertyData(\"InvalidCookieHeaderDataSet\")]\n        public void CookieHeaderValue_TryParse_RejectsInvalidValues(string value)\n        {\n            CookieHeaderValue header;\n            bool result = CookieHeaderValue.TryParse(value, out header);\n\n            Assert.False(result);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Headers/CookieStateTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Headers\n{\n    public class CookieStateTest\n    {\n        public static TheoryDataSet<string> InvalidCookieNames\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    \"<acb>\",\n                    \"{acb}\",\n                    \"[acb]\",\n                    \"\\\"acb\\\"\",\n                    \"a,b\",\n                    \"a;b\",\n                    \"a\\\\b\",\n                };\n            }\n        }\n\n        public static TheoryDataSet<string, string> EncodedCookieStateStrings\n        {\n            get\n            {\n                TheoryDataSet<string, string> data = new TheoryDataSet<string, string>\n                {\n                    { \"?\", \"%3F\" },\n                    { \"=\", \"%3D\" },\n                    { \"<acb>\", \"%3Cacb%3E\" },\n                    { \"{acb}\", \"%7Bacb%7D\" },\n                    { \"[acb]\", \"%5Bacb%5D\" },\n                    { \"\\\"acb\\\"\", \"%22acb%22\" },\n                    { \"a,b\", \"a%2Cb\" },\n                    { \"a;b\", \"a%3Bb\" },\n                    { \"a\\\\b\", \"a%5Cb\" },\n                    { \"[]{}\\\\|!@#$%^&*()_-+=\", \"%5B%5D%7B%7D%5C%7C!%40%23%24%25%5E%26*()_-%2B%3D\" },\n                };\n\n                return data;\n            }\n        }\n\n        [Fact]\n        public void CookieState_CtorThrowsOnNullName()\n        {\n            Assert.ThrowsArgumentNull(() => new CookieState(null, \"value\"), \"name\");\n        }\n\n        [Theory]\n        [PropertyData(\"InvalidCookieNames\")]\n        public void CookieState_CtorThrowsOnInvalidName(string name)\n        {\n            Assert.ThrowsArgument(() => new CookieState(name, \"value\"), \"name\");\n        }\n\n        [Fact]\n        public void CookieState_CtorThrowsOnNullNameValueCollection()\n        {\n            Assert.ThrowsArgumentNull(() => new CookieState(\"name\", (NameValueCollection)null), \"values\");\n        }\n\n        [Theory]\n        [InlineData(\"name\", \"\")]\n        [InlineData(\"name\", \"value\")]\n        [InlineData(\"name\", \"+=\\\\[]{}!@#$%^&*()_\")]\n        public void CookieState_Ctor1InitializesCorrectly(string name, string value)\n        {\n            CookieState cookie = new CookieState(name, value);\n            Assert.Equal(name, cookie.Name);\n            Assert.Equal(value, cookie.Values.AllKeys[0]);\n            Assert.Equal(value, cookie.Value);\n        }\n\n        [Fact]\n        public void CookieState_Ctor2InitializesCorrectly()\n        {\n            // Arrange\n            NameValueCollection nvc = new NameValueCollection();\n            nvc.Add(\"n1\", \"v1\");\n\n            // Act\n            CookieState cookie = new CookieState(\"name\", nvc);\n\n            // Assert\n            Assert.Equal(\"name\", cookie.Name);\n            Assert.Single(cookie.Values);\n            Assert.Equal(\"n1\", cookie.Values.AllKeys[0]);\n            Assert.Equal(\"v1\", cookie.Values[\"n1\"]);\n            Assert.Equal(\"n1\", cookie.Value);\n        }\n\n        [Fact]\n        public void CookieState_Value()\n        {\n            CookieState cookie = new CookieState(\"name\");\n            Assert.Equal(String.Empty, cookie.Value);\n\n            cookie.Value = \"value1\";\n            Assert.Equal(\"value1\", cookie.Value);\n\n            cookie.Values.AllKeys[0] = \"value2\";\n            Assert.Equal(\"value2\", cookie.Value);\n        }\n\n        [Fact]\n        public void CookieState_ItemTreatsNullNameAsEmpty()\n        {\n            // Arrange\n            CookieState state = new CookieState(\"name\", \"value\");\n\n            // Act\n            state[null] = \"v1\";\n\n            // Assert\n            Assert.Equal(\"name=value&=v1\", state.ToString());\n        }\n\n        [Theory]\n        [PropertyData(\"EncodedCookieStateStrings\")]\n        public void CookieState_ItemEncodesName(string subname, string encodedSubname)\n        {\n            // Arrange\n            CookieState state = new CookieState(\"name\", \"value\");\n\n            // Act\n            state[subname] = \"v1\";\n\n            // Assert\n            string value = String.Format(\"name=value&{0}=v1\", encodedSubname);\n            Assert.Equal(value, state.ToString());\n        }\n\n        [Theory]\n        [PropertyData(\"EncodedCookieStateStrings\")]\n        public void CookieState_ItemEncodesValue(string subvalue, string encodedSubvalue)\n        {\n            // Arrange\n            CookieState state = new CookieState(\"name\", \"value\");\n\n            // Act\n            state[\"n1\"] = subvalue;\n\n            // Assert\n            string value = String.Format(\"name=value&n1={0}\", encodedSubvalue);\n            Assert.Equal(value, state.ToString());\n        }\n\n        [Fact]\n        public void CookieState_Clone()\n        {\n            // Arrange\n            NameValueCollection nvc = new NameValueCollection();\n            nvc.Add(\"n1\", \"v1\");\n            CookieState expectedValue = new CookieState(\"name\", nvc);\n\n            // Act\n            CookieState actualValue = expectedValue.Clone() as CookieState;\n\n            // Assert\n            Assert.Equal(\"name\", actualValue.Name);\n            Assert.Single(actualValue.Values);\n            Assert.Equal(\"n1\", actualValue.Values.AllKeys[0]);\n            Assert.Equal(\"v1\", actualValue.Values[\"n1\"]);\n        }\n\n        [Theory]\n        [PropertyData(\"EncodedCookieStateStrings\")]\n        public void CookieState_ToStringWithSingleValue(string subValue, string encodedSubvalue)\n        {\n            // Arrange\n            CookieState cookie = new CookieState(\"name\", subValue);\n\n            // Act\n            string actualValue = cookie.ToString();\n\n            // Assert\n            string expectedValue = String.Format(\"name={0}\", encodedSubvalue);\n            Assert.Equal(expectedValue, actualValue);\n        }\n\n        [Theory]\n        [PropertyData(\"EncodedCookieStateStrings\")]\n        public void CookieState_ToStringWithNameValueCollection(string subValue, string encodedSubvalue)\n        {\n            // Arrange\n            NameValueCollection nvc = new NameValueCollection();\n            nvc.Add(\"n1\", subValue);\n            nvc.Add(\"n2\", subValue);\n            nvc.Add(\"n3\", subValue);\n            CookieState cookie = new CookieState(\"name\", nvc);\n\n            // Act\n            string actualValue = cookie.ToString();\n\n            // Assert\n            string expectedValue = String.Format(\"name=n1={0}&n2={0}&n3={0}\", encodedSubvalue);\n            Assert.Equal(expectedValue, actualValue);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/HttpClientExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Formatting.Mocks;\nusing System.Net.Http.Headers;\nusing System.Net.Http.Mocks;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Net.Http\n{\n    public class HttpClientExtensionsTest\n    {\n        private const string InvalidUriMessage =\n#if NET6_0_OR_GREATER\n            \"An invalid request URI was provided. Either the request URI must be an absolute URI or BaseAddress must be set.\";\n#else\n            \"An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set.\";\n#endif\n        private readonly MediaTypeFormatter _formatter = new MockMediaTypeFormatter { CallBase = true };\n        private readonly HttpClient _client;\n        private readonly MediaTypeHeaderValue _mediaTypeHeader = MediaTypeHeaderValue.Parse(\"foo/bar; charset=utf-16\");\n\n        public HttpClientExtensionsTest()\n        {\n            Mock<TestableHttpMessageHandler> handlerMock = new Mock<TestableHttpMessageHandler> { CallBase = true };\n            handlerMock\n                .Setup(h => h.SendAsyncPublic(It.IsAny<HttpRequestMessage>(), It.IsAny<CancellationToken>()))\n                .Returns((HttpRequestMessage request, CancellationToken _) => Task.FromResult(new HttpResponseMessage() { RequestMessage = request }));\n\n            _client = new HttpClient(handlerMock.Object);\n        }\n\n        [Fact]\n        public void PostAsJsonAsync_String_WhenClientIsNull_ThrowsException()\n        {\n            HttpClient client = null;\n\n            Assert.ThrowsArgumentNull(() => client.PostAsJsonAsync(\"http://www.example.com\", new object()), \"client\");\n        }\n\n        [Fact]\n        public void PostAsJsonAsync_String_WhenUriIsNull_ThrowsException()\n        {\n            Assert.Throws<InvalidOperationException>(() => _client.PostAsJsonAsync((string)null, new object()),\n                InvalidUriMessage);\n        }\n\n        [Fact]\n        public async Task PostAsJsonAsync_String_UsesJsonMediaTypeFormatter()\n        {\n            var response = await _client.PostAsJsonAsync(\"http://example.com\", new object());\n\n            var content = Assert.IsType<ObjectContent<object>>(response.RequestMessage.Content);\n            Assert.IsType<JsonMediaTypeFormatter>(content.Formatter);\n        }\n\n        [Fact]\n        public void PostAsXmlAsync_String_WhenClientIsNull_ThrowsException()\n        {\n            HttpClient client = null;\n\n            Assert.ThrowsArgumentNull(() => client.PostAsXmlAsync(\"http://www.example.com\", new object()), \"client\");\n        }\n\n#if !Testing_NetStandard1_3 // Avoid \"The configured formatter 'System.Net.Http.Formatting.XmlMediaTypeFormatter' cannot write an object of type 'Object'.\"\n        [Fact]\n        public void PostAsXmlAsync_String_WhenUriIsNull_ThrowsException()\n        {\n            Assert.Throws<InvalidOperationException>(() => _client.PostAsXmlAsync((string)null, new object()),\n                InvalidUriMessage);\n        }\n\n        [Fact]\n        public async Task PostAsXmlAsync_String_UsesXmlMediaTypeFormatter()\n        {\n            var response = await _client.PostAsXmlAsync(\"http://example.com\", new object());\n\n            var content = Assert.IsType<ObjectContent<object>>(response.RequestMessage.Content);\n            Assert.IsType<XmlMediaTypeFormatter>(content.Formatter);\n        }\n#endif\n\n        [Fact]\n        public void PostAsync_String_WhenClientIsNull_ThrowsException()\n        {\n            HttpClient client = null;\n\n            Assert.ThrowsArgumentNull(() => client.PostAsync(\"http://www.example.com\", new object(), new JsonMediaTypeFormatter(), \"text/json\"), \"client\");\n        }\n\n        [Fact]\n        public void PostAsync_String_WhenRequestUriIsNull_ThrowsException()\n        {\n            Assert.Throws<InvalidOperationException>(() => _client.PostAsync((string)null, new object(), new JsonMediaTypeFormatter(), \"text/json\"),\n                InvalidUriMessage);\n        }\n\n        [Fact]\n        public async Task PostAsync_String_WhenRequestUriIsSet_CreatesRequestWithAppropriateUri()\n        {\n            _client.BaseAddress = new Uri(\"http://example.com/\");\n\n            var response = await _client.PostAsync(\"myapi/\", new object(), _formatter);\n\n            var request = response.RequestMessage;\n            Assert.Equal(\"http://example.com/myapi/\", request.RequestUri.ToString());\n        }\n\n        [Fact]\n        public async Task PostAsync_String_WhenAuthoritativeMediaTypeIsSet_CreatesRequestWithAppropriateContentType()\n        {\n            var response = await _client.PostAsync(\"http://example.com/myapi/\", new object(), _formatter, _mediaTypeHeader, CancellationToken.None);\n\n            var request = response.RequestMessage;\n            Assert.Equal(\"foo/bar\", request.Content.Headers.ContentType.MediaType);\n            Assert.Equal(\"utf-16\", request.Content.Headers.ContentType.CharSet);\n        }\n\n        [Fact]\n        public async Task PostAsync_String_WhenAuthoritativeMediaTypeStringIsSet_CreatesRequestWithAppropriateContentType()\n        {\n            string mediaType = _mediaTypeHeader.MediaType;\n            var response = await _client.PostAsync(\"http://example.com/myapi/\", new object(), _formatter, mediaType, CancellationToken.None);\n\n            var request = response.RequestMessage;\n            Assert.Equal(\"foo/bar\", request.Content.Headers.ContentType.MediaType);\n        }\n\n        [Fact]\n        public async Task PostAsync_String_WhenAuthoritativeMediaTypeStringIsSetWithoutCT_CreatesRequestWithAppropriateContentType()\n        {\n            string mediaType = _mediaTypeHeader.MediaType;\n            var response = await _client.PostAsync(\"http://example.com/myapi/\", new object(), _formatter, mediaType);\n\n            var request = response.RequestMessage;\n            Assert.Equal(\"foo/bar\", request.Content.Headers.ContentType.MediaType);\n        }\n\n        [Fact]\n        public async Task PostAsync_String_WhenFormatterIsSet_CreatesRequestWithObjectContentAndCorrectFormatter()\n        {\n            var response = await _client.PostAsync(\"http://example.com/myapi/\", new object(), _formatter, _mediaTypeHeader, CancellationToken.None);\n\n            var request = response.RequestMessage;\n            var content = Assert.IsType<ObjectContent<object>>(request.Content);\n            Assert.Same(_formatter, content.Formatter);\n        }\n\n        [Fact]\n        public async Task PostAsync_String_IssuesPostRequest()\n        {\n            var response = await _client.PostAsync(\"http://example.com/myapi/\", new object(), _formatter);\n\n            var request = response.RequestMessage;\n            Assert.Same(HttpMethod.Post, request.Method);\n        }\n\n        [Fact]\n        public void PostAsync_String_WhenMediaTypeFormatterIsNull_ThrowsException()\n        {\n            Assert.ThrowsArgumentNull(() => _client.PostAsync(\"http://example.com\", new object(), formatter: null), \"formatter\");\n        }\n\n        [Fact]\n        public void PutAsJsonAsync_String_WhenClientIsNull_ThrowsException()\n        {\n            HttpClient client = null;\n\n            Assert.ThrowsArgumentNull(() => client.PutAsJsonAsync(\"http://www.example.com\", new object()), \"client\");\n        }\n\n        [Fact]\n        public void PutAsJsonAsync_String_WhenUriIsNull_ThrowsException()\n        {\n            Assert.Throws<InvalidOperationException>(() => _client.PutAsJsonAsync((string)null, new object()),\n                InvalidUriMessage);\n        }\n\n        [Fact]\n        public async Task PutAsJsonAsync_String_UsesJsonMediaTypeFormatter()\n        {\n            var response = await _client.PutAsJsonAsync(\"http://example.com\", new object());\n\n            var content = Assert.IsType<ObjectContent<object>>(response.RequestMessage.Content);\n            Assert.IsType<JsonMediaTypeFormatter>(content.Formatter);\n        }\n\n        [Fact]\n        public void PutAsXmlAsync_String_WhenClientIsNull_ThrowsException()\n        {\n            HttpClient client = null;\n\n            Assert.ThrowsArgumentNull(() => client.PutAsXmlAsync(\"http://www.example.com\", new object()), \"client\");\n        }\n\n#if !Testing_NetStandard1_3 // Avoid \"The configured formatter 'System.Net.Http.Formatting.XmlMediaTypeFormatter' cannot write an object of type 'Object'.\"\n        [Fact]\n        public void PutAsXmlAsync_String_WhenUriIsNull_ThrowsException()\n        {\n            Assert.Throws<InvalidOperationException>(() => _client.PutAsXmlAsync((string)null, new object()),\n                InvalidUriMessage);\n        }\n\n        [Fact]\n        public async Task PutAsXmlAsync_String_UsesXmlMediaTypeFormatter()\n        {\n            var response = await _client.PutAsXmlAsync(\"http://example.com\", new object());\n\n            var content = Assert.IsType<ObjectContent<object>>(response.RequestMessage.Content);\n            Assert.IsType<XmlMediaTypeFormatter>(content.Formatter);\n        }\n#endif\n\n        [Fact]\n        public void PutAsync_String_WhenClientIsNull_ThrowsException()\n        {\n            HttpClient client = null;\n\n            Assert.ThrowsArgumentNull(() => client.PutAsync(\"http://www.example.com\", new object(), new JsonMediaTypeFormatter(), \"text/json\"), \"client\");\n        }\n\n        [Fact]\n        public void PutAsync_String_WhenRequestUriIsNull_ThrowsException()\n        {\n            Assert.Throws<InvalidOperationException>(() => _client.PutAsync((string)null, new object(), new JsonMediaTypeFormatter(), \"text/json\"),\n                InvalidUriMessage);\n        }\n\n        [Fact]\n        public async Task PutAsync_String_WhenRequestUriIsSet_CreatesRequestWithAppropriateUri()\n        {\n            _client.BaseAddress = new Uri(\"http://example.com/\");\n\n            var response = await _client.PutAsync(\"myapi/\", new object(), _formatter);\n\n            var request = response.RequestMessage;\n            Assert.Equal(\"http://example.com/myapi/\", request.RequestUri.ToString());\n        }\n\n        [Fact]\n        public async Task PutAsync_String_WhenAuthoritativeMediaTypeIsSet_CreatesRequestWithAppropriateContentType()\n        {\n            var response = await _client.PutAsync(\"http://example.com/myapi/\", new object(), _formatter, _mediaTypeHeader, CancellationToken.None);\n\n            var request = response.RequestMessage;\n            Assert.Equal(\"foo/bar\", request.Content.Headers.ContentType.MediaType);\n            Assert.Equal(\"utf-16\", request.Content.Headers.ContentType.CharSet);\n        }\n\n        [Fact]\n        public async Task PutAsync_String_WhenFormatterIsSet_CreatesRequestWithObjectContentAndCorrectFormatter()\n        {\n            var response = await _client.PutAsync(\"http://example.com/myapi/\", new object(), _formatter, _mediaTypeHeader, CancellationToken.None);\n\n            var request = response.RequestMessage;\n            var content = Assert.IsType<ObjectContent<object>>(request.Content);\n            Assert.Same(_formatter, content.Formatter);\n        }\n\n        [Fact]\n        public async Task PutAsync_String_WhenAuthoritativeMediaTypeStringIsSet_CreatesRequestWithAppropriateContentType()\n        {\n            string mediaType = _mediaTypeHeader.MediaType;\n            var response = await _client.PutAsync(\"http://example.com/myapi/\", new object(), _formatter, mediaType, CancellationToken.None);\n\n            var request = response.RequestMessage;\n            Assert.Equal(\"foo/bar\", request.Content.Headers.ContentType.MediaType);\n        }\n\n        [Fact]\n        public async Task PutAsync_String_WhenAuthoritativeMediaTypeStringIsSetWithoutCT_CreatesRequestWithAppropriateContentType()\n        {\n            string mediaType = _mediaTypeHeader.MediaType;\n            var response = await _client.PutAsync(\"http://example.com/myapi/\", new object(), _formatter, mediaType);\n\n            var request = response.RequestMessage;\n            Assert.Equal(\"foo/bar\", request.Content.Headers.ContentType.MediaType);\n        }\n\n        [Fact]\n        public async Task PutAsync_String_IssuesPutRequest()\n        {\n            var response = await _client.PutAsync(\"http://example.com/myapi/\", new object(), _formatter);\n\n            var request = response.RequestMessage;\n            Assert.Same(HttpMethod.Put, request.Method);\n        }\n\n        [Fact]\n        public void PutAsync_String_WhenMediaTypeFormatterIsNull_ThrowsException()\n        {\n            Assert.ThrowsArgumentNull(() => _client.PutAsync(\"http://example.com\", new object(), formatter: null), \"formatter\");\n        }\n\n        [Fact]\n        public void PostAsJsonAsync_Uri_WhenClientIsNull_ThrowsException()\n        {\n            HttpClient client = null;\n\n            Assert.ThrowsArgumentNull(() => client.PostAsJsonAsync(new Uri(\"http://www.example.com\"), new object()), \"client\");\n        }\n\n        [Fact]\n        public void PostAsJsonAsync_Uri_WhenUriIsNull_ThrowsException()\n        {\n            Assert.Throws<InvalidOperationException>(() => _client.PostAsJsonAsync((Uri)null, new object()),\n                InvalidUriMessage);\n        }\n\n        [Fact]\n        public async Task PostAsJsonAsync_Uri_UsesJsonMediaTypeFormatter()\n        {\n            var response = await _client.PostAsJsonAsync(new Uri(\"http://example.com\"), new object());\n\n            var content = Assert.IsType<ObjectContent<object>>(response.RequestMessage.Content);\n            Assert.IsType<JsonMediaTypeFormatter>(content.Formatter);\n        }\n\n        [Fact]\n        public void PostAsXmlAsync_Uri_WhenClientIsNull_ThrowsException()\n        {\n            HttpClient client = null;\n\n            Assert.ThrowsArgumentNull(() => client.PostAsXmlAsync(new Uri(\"http://www.example.com\"), new object()), \"client\");\n        }\n\n#if !Testing_NetStandard1_3 // Avoid \"The configured formatter 'System.Net.Http.Formatting.XmlMediaTypeFormatter' cannot write an object of type 'Object'.\"\n        [Fact]\n        public void PostAsXmlAsync_Uri_WhenUriIsNull_ThrowsException()\n        {\n            Assert.Throws<InvalidOperationException>(() => _client.PostAsXmlAsync((Uri)null, new object()),\n                InvalidUriMessage);\n        }\n\n        [Fact]\n        public async Task PostAsXmlAsync_Uri_UsesXmlMediaTypeFormatter()\n        {\n            var response = await _client.PostAsXmlAsync(new Uri(\"http://example.com\"), new object());\n\n            var content = Assert.IsType<ObjectContent<object>>(response.RequestMessage.Content);\n            Assert.IsType<XmlMediaTypeFormatter>(content.Formatter);\n        }\n#endif\n\n        [Fact]\n        public void PostAsync_Uri_WhenClientIsNull_ThrowsException()\n        {\n            HttpClient client = null;\n\n            Assert.ThrowsArgumentNull(() => client.PostAsync(new Uri(\"http://www.example.com\"), new object(), new JsonMediaTypeFormatter(), \"text/json\"), \"client\");\n        }\n\n        [Fact]\n        public void PostAsync_Uri_WhenRequestUriIsNull_ThrowsException()\n        {\n            Assert.Throws<InvalidOperationException>(() => _client.PostAsync((Uri)null, new object(), new JsonMediaTypeFormatter(), \"text/json\"),\n                InvalidUriMessage);\n        }\n\n        [Fact]\n        public async Task PostAsync_Uri_WhenRequestUriIsSet_CreatesRequestWithAppropriateUri()\n        {\n            _client.BaseAddress = new Uri(\"http://example.com/\");\n\n            var response = await _client.PostAsync(new Uri(\"myapi/\", UriKind.Relative), new object(), _formatter);\n\n            var request = response.RequestMessage;\n            Assert.Equal(\"http://example.com/myapi/\", request.RequestUri.ToString());\n        }\n\n        [Fact]\n        public async Task PostAsync_Uri_WhenAuthoritativeMediaTypeIsSet_CreatesRequestWithAppropriateContentType()\n        {\n            var response = await _client.PostAsync(new Uri(\"http://example.com/myapi/\"), new object(), _formatter, _mediaTypeHeader, CancellationToken.None);\n\n            var request = response.RequestMessage;\n            Assert.Equal(\"foo/bar\", request.Content.Headers.ContentType.MediaType);\n            Assert.Equal(\"utf-16\", request.Content.Headers.ContentType.CharSet);\n        }\n\n        [Fact]\n        public async Task PostAsync_Uri_WhenFormatterIsSet_CreatesRequestWithObjectContentAndCorrectFormatter()\n        {\n            var response = await _client.PostAsync(new Uri(\"http://example.com/myapi/\"), new object(), _formatter, _mediaTypeHeader, CancellationToken.None);\n\n            var request = response.RequestMessage;\n            var content = Assert.IsType<ObjectContent<object>>(request.Content);\n            Assert.Same(_formatter, content.Formatter);\n        }\n\n        [Fact]\n        public async Task PostAsync_Uri_WhenAuthoritativeMediaTypeStringIsSet_CreatesRequestWithAppropriateContentType()\n        {\n            string mediaType = _mediaTypeHeader.MediaType;\n            var response = await _client.PostAsync(new Uri(\"http://example.com/myapi/\"), new object(), _formatter, mediaType, CancellationToken.None);\n\n            var request = response.RequestMessage;\n            Assert.Equal(\"foo/bar\", request.Content.Headers.ContentType.MediaType);\n        }\n\n        [Fact]\n        public async Task PostAsync_Uri_WhenAuthoritativeMediaTypeStringIsSetWithoutCT_CreatesRequestWithAppropriateContentType()\n        {\n            string mediaType = _mediaTypeHeader.MediaType;\n            var response = await _client.PostAsync(new Uri(\"http://example.com/myapi/\"), new object(), _formatter, mediaType);\n\n            var request = response.RequestMessage;\n            Assert.Equal(\"foo/bar\", request.Content.Headers.ContentType.MediaType);\n        }\n\n        [Fact]\n        public async Task PostAsync_Uri_IssuesPostRequest()\n        {\n            var response = await _client.PostAsync(new Uri(\"http://example.com/myapi/\"), new object(), _formatter);\n\n            var request = response.RequestMessage;\n            Assert.Same(HttpMethod.Post, request.Method);\n        }\n\n        [Fact]\n        public void PostAsync_Uri_WhenMediaTypeFormatterIsNull_ThrowsException()\n        {\n            Assert.ThrowsArgumentNull(() => _client.PostAsync(new Uri(\"http://example.com\"), new object(), formatter: null), \"formatter\");\n        }\n\n        [Fact]\n        public void PutAsJsonAsync_Uri_WhenClientIsNull_ThrowsException()\n        {\n            HttpClient client = null;\n\n            Assert.ThrowsArgumentNull(() => client.PutAsJsonAsync(new Uri(\"http://www.example.com\"), new object()), \"client\");\n        }\n\n        [Fact]\n        public void PutAsJsonAsync_Uri_WhenUriIsNull_ThrowsException()\n        {\n            Assert.Throws<InvalidOperationException>(() => _client.PutAsJsonAsync((Uri)null, new object()),\n                InvalidUriMessage);\n        }\n\n        [Fact]\n        public async Task PutAsJsonAsync_Uri_UsesJsonMediaTypeFormatter()\n        {\n            var response = await _client.PutAsJsonAsync(new Uri(\"http://example.com\"), new object());\n\n            var content = Assert.IsType<ObjectContent<object>>(response.RequestMessage.Content);\n            Assert.IsType<JsonMediaTypeFormatter>(content.Formatter);\n        }\n\n        [Fact]\n        public void PutAsXmlAsync_Uri_WhenClientIsNull_ThrowsException()\n        {\n            HttpClient client = null;\n\n            Assert.ThrowsArgumentNull(() => client.PutAsXmlAsync(new Uri(\"http://www.example.com\"), new object()), \"client\");\n        }\n\n#if !Testing_NetStandard1_3 // Avoid \"The configured formatter 'System.Net.Http.Formatting.XmlMediaTypeFormatter' cannot write an object of type 'Object'.\"\n        [Fact]\n        public void PutAsXmlAsync_Uri_WhenUriIsNull_ThrowsException()\n        {\n            Assert.Throws<InvalidOperationException>(() => _client.PutAsXmlAsync((Uri)null, new object()),\n                InvalidUriMessage);\n        }\n\n        [Fact]\n        public async Task PutAsXmlAsync_Uri_UsesXmlMediaTypeFormatter()\n        {\n            var response = await _client.PutAsXmlAsync(new Uri(\"http://example.com\"), new object());\n\n            var content = Assert.IsType<ObjectContent<object>>(response.RequestMessage.Content);\n            Assert.IsType<XmlMediaTypeFormatter>(content.Formatter);\n        }\n#endif\n\n        [Fact]\n        public void PutAsync_Uri_WhenClientIsNull_ThrowsException()\n        {\n            HttpClient client = null;\n\n            Assert.ThrowsArgumentNull(() => client.PutAsync(new Uri(\"http://www.example.com\"), new object(), new JsonMediaTypeFormatter(), \"text/json\"), \"client\");\n        }\n\n        [Fact]\n        public void PutAsync_Uri_WhenRequestUriIsNull_ThrowsException()\n        {\n            Assert.Throws<InvalidOperationException>(() => _client.PutAsync((Uri)null, new object(), new JsonMediaTypeFormatter(), \"text/json\"),\n                InvalidUriMessage);\n        }\n\n        [Fact]\n        public async Task PutAsync_Uri_WhenRequestUriIsSet_CreatesRequestWithAppropriateUri()\n        {\n            _client.BaseAddress = new Uri(\"http://example.com/\");\n\n            var response = await _client.PutAsync(new Uri(\"myapi/\", UriKind.Relative), new object(), _formatter);\n\n            var request = response.RequestMessage;\n            Assert.Equal(\"http://example.com/myapi/\", request.RequestUri.ToString());\n        }\n\n        [Fact]\n        public async Task PutAsync_Uri_WhenAuthoritativeMediaTypeIsSet_CreatesRequestWithAppropriateContentType()\n        {\n            var response = await _client.PutAsync(new Uri(\"http://example.com/myapi/\"), new object(), _formatter, _mediaTypeHeader, CancellationToken.None);\n\n            var request = response.RequestMessage;\n            Assert.Equal(\"foo/bar\", request.Content.Headers.ContentType.MediaType);\n            Assert.Equal(\"utf-16\", request.Content.Headers.ContentType.CharSet);\n        }\n\n        [Fact]\n        public async Task PutAsync_Uri_WhenFormatterIsSet_CreatesRequestWithObjectContentAndCorrectFormatter()\n        {\n            var response = await _client.PutAsync(new Uri(\"http://example.com/myapi/\"), new object(), _formatter, _mediaTypeHeader, CancellationToken.None);\n\n            var request = response.RequestMessage;\n            var content = Assert.IsType<ObjectContent<object>>(request.Content);\n            Assert.Same(_formatter, content.Formatter);\n        }\n\n        [Fact]\n        public async Task PutAsync_Uri_WhenAuthoritativeMediaTypeStringIsSet_CreatesRequestWithAppropriateContentType()\n        {\n            string mediaType = _mediaTypeHeader.MediaType;\n            var response = await _client.PutAsync(new Uri(\"http://example.com/myapi/\"), new object(), _formatter, mediaType, CancellationToken.None);\n\n            var request = response.RequestMessage;\n            Assert.Equal(\"foo/bar\", request.Content.Headers.ContentType.MediaType);\n        }\n\n        [Fact]\n        public async Task PutAsync_Uri_WhenAuthoritativeMediaTypeStringIsSetWithoutCT_CreatesRequestWithAppropriateContentType()\n        {\n            string mediaType = _mediaTypeHeader.MediaType;\n            var response = await _client.PutAsync(new Uri(\"http://example.com/myapi/\"), new object(), _formatter, mediaType);\n\n            var request = response.RequestMessage;\n            Assert.Equal(\"foo/bar\", request.Content.Headers.ContentType.MediaType);\n        }\n\n        [Fact]\n        public async Task PutAsync_Uri_IssuesPutRequest()\n        {\n            var response = await _client.PutAsync(new Uri(\"http://example.com/myapi/\"), new object(), _formatter);\n\n            var request = response.RequestMessage;\n            Assert.Same(HttpMethod.Put, request.Method);\n        }\n\n        [Fact]\n        public void PutAsync_Uri_WhenMediaTypeFormatterIsNull_ThrowsException()\n        {\n            Assert.ThrowsArgumentNull(() => _client.PutAsync(new Uri(\"http://example.com\"), new object(), formatter: null), \"formatter\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/HttpClientFactoryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http.Mocks;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http\n{\n    public class HttpClientFactoryTest\n    {\n        public static TheoryDataSet<IEnumerable<DelegatingHandler>> InvalidPipelines\n        {\n            get\n            {\n                return new TheoryDataSet<IEnumerable<DelegatingHandler>>\n                {\n                    new List<DelegatingHandler>()\n                    {\n                        new MockDelegatingHandler(),\n                        new MockDelegatingHandler(new HttpClientHandler())\n                    },\n                    new List<DelegatingHandler>()\n                    {\n                        new MockDelegatingHandler(new HttpClientHandler()),\n                        new MockDelegatingHandler(),\n                    },\n                    new List<DelegatingHandler>()\n                    {\n                        null,\n                        new MockDelegatingHandler(),\n                    },\n                    new List<DelegatingHandler>()\n                    {\n                        new MockDelegatingHandler(),\n                        null,\n                    },\n                };\n            }\n        }\n\n        [Fact]\n        public void Create1_SetsInnerHandler()\n        {\n            // Arrange\n            MockDelegatingHandler handler = new MockDelegatingHandler();\n\n            // Act\n            HttpClient client = HttpClientFactory.Create(handler);\n\n            // Assert\n            Assert.IsType<HttpClientHandler>(handler.InnerHandler);\n        }\n\n        [Fact]\n        public void Create2_ThrowsOnNullInnerHandler()\n        {\n            Assert.ThrowsArgumentNull(() => HttpClientFactory.Create(null, new DelegatingHandler[0]), \"innerHandler\");\n        }\n\n        [Fact]\n        public void Create2_SetsInnerHandler()\n        {\n            // Arrange\n            MockDelegatingHandler handler = new MockDelegatingHandler();\n            HttpClientHandler innerHandler = new HttpClientHandler();\n\n            // Act\n            HttpClient client = HttpClientFactory.Create(innerHandler, handler);\n\n            // Assert\n            Assert.IsType<HttpClientHandler>(handler.InnerHandler);\n        }\n\n        [Theory]\n        [PropertyData(\"InvalidPipelines\")]\n        public void CreatePipeline_ThrowsOnInvalidPipeline(IEnumerable<DelegatingHandler> handlers)\n        {\n            Assert.ThrowsArgument(() => HttpClientFactory.CreatePipeline(new HttpClientHandler(), handlers), \"handlers\");\n        }\n\n        [Fact]\n        public void CreatePipeline_ReturnsInnerHandler()\n        {\n            // Arrange\n            HttpClientHandler innerHandler = new HttpClientHandler();\n\n            // Act\n            HttpMessageHandler handler = HttpClientFactory.CreatePipeline(innerHandler, null);\n\n            // Assert\n            Assert.Same(innerHandler, handler);\n        }\n\n        [Theory]\n        [InlineData(1)]\n        [InlineData(4)]\n        [InlineData(16)]\n        public void CreatePipeline_WiresUpHandlers(int maxHandlerCount)\n        {\n            // Arrange\n            List<DelegatingHandler> handlers = new List<DelegatingHandler>();\n\n            for (int handlerCount = 0; handlerCount < maxHandlerCount; handlerCount++)\n            {\n                handlers.Add(new MockDelegatingHandler());\n            }\n\n            HttpClientHandler innerHandler = new HttpClientHandler();\n\n            // Act\n            DelegatingHandler pipeline = HttpClientFactory.CreatePipeline(innerHandler, handlers) as DelegatingHandler;\n\n            // Assert\n            for (int index = 0; index < handlers.Count - 1; index++)\n            {\n                Assert.Same(handlers[index], pipeline);\n                pipeline = pipeline.InnerHandler as DelegatingHandler;\n            }\n            Assert.Same(innerHandler, pipeline.InnerHandler);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/HttpContentExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Net.Http\n{\n    public class HttpContentExtensionsTest\n    {\n        private static readonly IEnumerable<MediaTypeFormatter> _emptyFormatterList = Enumerable.Empty<MediaTypeFormatter>();\n        private readonly Mock<MediaTypeFormatter> _formatterMock = new Mock<MediaTypeFormatter> { CallBase = true };\n        private readonly MediaTypeHeaderValue _mediaType = new MediaTypeHeaderValue(\"foo/bar\");\n        private readonly MediaTypeFormatter[] _formatters;\n\n        public HttpContentExtensionsTest()\n        {\n            _formatterMock.Object.SupportedMediaTypes.Add(_mediaType);\n            _formatters = new[] { _formatterMock.Object };\n        }\n\n        [Fact]\n        public void ReadAsAsync_WhenContentParameterIsNull_Throws()\n        {\n            Assert.ThrowsArgumentNull(() => HttpContentExtensions.ReadAsAsync(null, typeof(string), _emptyFormatterList), \"content\");\n        }\n\n        [Fact]\n        public void ReadAsAsync_WhenTypeParameterIsNull_Throws()\n        {\n            Assert.ThrowsArgumentNull(() => HttpContentExtensions.ReadAsAsync(new StringContent(\"\"), null, _emptyFormatterList), \"type\");\n        }\n\n        [Fact]\n        public void ReadAsAsync_WhenFormattersParameterIsNull_Throws()\n        {\n            Assert.ThrowsArgumentNull(() => HttpContentExtensions.ReadAsAsync(new StringContent(\"\"), typeof(string), null), \"formatters\");\n        }\n\n        [Fact]\n        public void ReadAsAsyncOfT_WhenContentParameterIsNull_Throws()\n        {\n            Assert.ThrowsArgumentNull(() => HttpContentExtensions.ReadAsAsync<string>(null, _emptyFormatterList), \"content\");\n        }\n\n        [Fact]\n        public void ReadAsAsyncOfT_WhenFormattersParameterIsNull_Throws()\n        {\n            Assert.ThrowsArgumentNull(() => HttpContentExtensions.ReadAsAsync<string>(new StringContent(\"\"), null), \"formatters\");\n        }\n\n        [Fact]\n        public async Task ReadAsAsyncOfT_WhenContentIsObjectContent_GoesThroughSerializationCycleToConvertTypes()\n        {\n            var content = new ObjectContent<int[]>(new int[] { 10, 20, 30, 40 }, new JsonMediaTypeFormatter());\n\n            byte[] result = await content.ReadAsAsync<byte[]>();\n\n            Assert.Equal(new byte[] { 10, 20, 30, 40 }, result);\n        }\n\n        [Fact]\n        public void ReadAsAsyncOfT_WhenNoMatchingFormatterFound_Throws()\n        {\n            var content = new StringContent(\"{}\");\n            content.Headers.ContentType = _mediaType;\n            content.Headers.ContentType.CharSet = \"utf-16\";\n            var formatters = new MediaTypeFormatter[] { new JsonMediaTypeFormatter() };\n\n            Assert.Throws<UnsupportedMediaTypeException>(() => content.ReadAsAsync<List<string>>(formatters),\n                \"No MediaTypeFormatter is available to read an object of type 'List`1' from content with media type 'foo/bar'.\");\n        }\n\n        [Fact]\n        public void ReadAsAsyncOfT_WhenTypeIsReferenceTypeAndNoMediaType_Throws()\n        {\n            var content = new StringContent(\"{}\");\n            content.Headers.ContentType = null;\n            var formatters = new MediaTypeFormatter[] { new JsonMediaTypeFormatter() };\n\n            Assert.Throws<UnsupportedMediaTypeException>(() => content.ReadAsAsync<List<string>>(formatters),\n                \"No MediaTypeFormatter is available to read an object of type 'List`1' from content with media type 'application/octet-stream'.\");\n        }\n\n        [Fact]\n        public void ReadAsAsyncOfT_WhenTypeIsValueTypeAndNoMediaType_Throws()\n        {\n            var content = new StringContent(\"123456\");\n            content.Headers.ContentType = null;\n            var formatters = new MediaTypeFormatter[] { new JsonMediaTypeFormatter() };\n\n            Assert.Throws<UnsupportedMediaTypeException>(() => content.ReadAsAsync<int>(formatters),\n                \"No MediaTypeFormatter is available to read an object of type 'Int32' from content with media type 'application/octet-stream'.\");\n        }\n\n        [Fact]\n        public async Task ReadAsAsyncOfT_ReadsFromContent_ThenInvokesFormattersReadFromStreamMethod()\n        {\n            Stream contentStream = null;\n            string value = \"42\";\n            var contentMock = new Mock<TestableHttpContent> { CallBase = true };\n            contentMock.Setup(c => c.SerializeToStreamAsyncPublic(It.IsAny<Stream>(), It.IsAny<TransportContext>()))\n                .Returns(TaskHelpers.Completed)\n                .Callback((Stream s, TransportContext _) => contentStream = s)\n                .Verifiable();\n            HttpContent content = contentMock.Object;\n            content.Headers.ContentType = _mediaType;\n            _formatterMock\n                .Setup(f => f.ReadFromStreamAsync(typeof(string), It.IsAny<Stream>(), It.IsAny<HttpContent>(), It.IsAny<IFormatterLogger>()))\n                .Returns(Task.FromResult<object>(value));\n            _formatterMock.Setup(f => f.CanReadType(typeof(string))).Returns(true);\n\n            var resultValue = await content.ReadAsAsync<string>(_formatters);\n\n            Assert.Same(value, resultValue);\n            contentMock.Verify();\n            _formatterMock.Verify(f => f.ReadFromStreamAsync(typeof(string), contentStream, content, null), Times.Once());\n        }\n\n        [Fact]\n        public async Task ReadAsAsyncOfT_InvokesFormatterEvenIfContentLengthIsZero()\n        {\n            var content = new StringContent(\"\");\n            _formatterMock.Setup(f => f.CanReadType(typeof(string))).Returns(true);\n            _formatterMock.Object.SupportedMediaTypes.Add(content.Headers.ContentType);\n            _formatterMock\n                .Setup(f => f.ReadFromStreamAsync(It.IsAny<Type>(), It.IsAny<Stream>(), It.IsAny<HttpContent>(), It.IsAny<IFormatterLogger>()))\n                .Returns(Task.FromResult<object>(result: null));\n\n            await content.ReadAsAsync<string>(_formatters);\n\n            _formatterMock.Verify(f => f.ReadFromStreamAsync(typeof(string), It.IsAny<Stream>(), content, It.IsAny<IFormatterLogger>()), Times.Once());\n        }\n\n        [Fact]\n        public async Task ReadAsAsync_WhenContentIsObjectContentAndValueIsCompatibleType_ReadsValueFromObjectContent()\n        {\n            _formatterMock.Setup(f => f.CanWriteType(typeof(TestClass))).Returns(true);\n            var value = new TestClass();\n            var content = new ObjectContent<TestClass>(value, _formatterMock.Object);\n\n            Assert.Same(value, await content.ReadAsAsync<object>(_formatters));\n            Assert.Same(value, await content.ReadAsAsync<TestClass>(_formatters));\n            Assert.Same(value, await content.ReadAsAsync(typeof(object), _formatters));\n            Assert.Same(value, await content.ReadAsAsync(typeof(TestClass), _formatters));\n\n            _formatterMock.Verify(f => f.ReadFromStreamAsync(It.IsAny<Type>(), It.IsAny<Stream>(), content, It.IsAny<IFormatterLogger>()), Times.Never());\n        }\n\n        [Fact]\n        public async Task ReadAsAsync_WhenContentIsObjectContentAndValueIsNull_IfTypeIsNullable_SerializesAndDeserializesValue()\n        {\n            _formatterMock.Setup(f => f.CanWriteType(typeof(object))).Returns(true);\n            _formatterMock.Setup(f => f.CanReadType(It.IsAny<Type>())).Returns(true);\n            var content = new ObjectContent<object>(null, _formatterMock.Object);\n            SetupUpRoundTripSerialization(type => null);\n\n            Assert.Null(await content.ReadAsAsync<object>(_formatters));\n            Assert.Null(await content.ReadAsAsync<TestClass>(_formatters));\n            Assert.Null(await content.ReadAsAsync<Nullable<int>>(_formatters));\n            Assert.Null(await content.ReadAsAsync(typeof(object), _formatters));\n            Assert.Null(await content.ReadAsAsync(typeof(TestClass), _formatters));\n            Assert.Null(await content.ReadAsAsync(typeof(Nullable<int>), _formatters));\n\n            _formatterMock.Verify(f => f.ReadFromStreamAsync(It.IsAny<Type>(), It.IsAny<Stream>(), content, It.IsAny<IFormatterLogger>()), Times.Exactly(6));\n        }\n\n        [Fact]\n        public async Task ReadAsAsync_WhenContentIsObjectContentAndValueIsNull_IfTypeIsNotNullable_SerializesAndDeserializesValue()\n        {\n            _formatterMock.Setup(f => f.CanWriteType(typeof(object))).Returns(true);\n            _formatterMock.Setup(f => f.CanReadType(typeof(Int32))).Returns(true);\n            var content = new ObjectContent<object>(null, _formatterMock.Object, _mediaType);\n            SetupUpRoundTripSerialization();\n\n            Assert.IsType<Int32>(await content.ReadAsAsync<Int32>(_formatters));\n            Assert.IsType<Int32>(await content.ReadAsAsync(typeof(Int32), _formatters));\n\n            _formatterMock.Verify(f => f.ReadFromStreamAsync(It.IsAny<Type>(), It.IsAny<Stream>(), content, It.IsAny<IFormatterLogger>()), Times.Exactly(2));\n        }\n\n        [Fact]\n        public async Task ReadAsAsync_WhenContentIsObjectContentAndValueIsNotCompatibleType_SerializesAndDeserializesValue()\n        {\n            _formatterMock.Setup(f => f.CanWriteType(typeof(TestClass))).Returns(true);\n            _formatterMock.Setup(f => f.CanReadType(typeof(string))).Returns(true);\n            var value = new TestClass();\n            var content = new ObjectContent<TestClass>(value, _formatterMock.Object, _mediaType);\n            SetupUpRoundTripSerialization(type => new TestClass());\n\n            await Assert.ThrowsAsync<InvalidCastException>(() => content.ReadAsAsync<string>(_formatters));\n\n            Assert.IsNotType<string>(await content.ReadAsAsync(typeof(string), _formatters));\n\n            _formatterMock.Verify(f => f.ReadFromStreamAsync(It.IsAny<Type>(), It.IsAny<Stream>(), content, It.IsAny<IFormatterLogger>()), Times.Exactly(2));\n        }\n\n        [Fact]\n        public async Task ReadAsAsync_WhenContentIsMultipartContentAndFormatterCanReadFromTheContent()\n        {\n            MultipartContent mimeContent = new MultipartContent();\n            mimeContent.Add(new StringContent(\"multipartContent\"));\n\n            _formatterMock.Setup(f => f.CanWriteType(It.IsAny<Type>())).Returns(true);\n            _formatterMock.Setup(f => f.CanReadType(It.IsAny<Type>())).Returns(true);\n            _formatterMock.Setup(f => f.ReadFromStreamAsync(It.IsAny<Type>(), It.IsAny<Stream>(), It.IsAny<HttpContent>(), It.IsAny<IFormatterLogger>()))\n                .Returns<Type, Stream, HttpContent, IFormatterLogger>(async (type, stream, content, logger) =>\n                    {\n                        MultipartMemoryStreamProvider provider = await content.ReadAsMultipartAsync();\n                        HttpContent providerContent = Assert.Single(provider.Contents);\n                        return await providerContent.ReadAsStringAsync();\n                    });\n            MediaTypeFormatter formatter = _formatterMock.Object;\n            formatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue(\"multipart/mixed\"));\n\n            Assert.Equal(\"multipartContent\", await mimeContent.ReadAsAsync<string>(new[] { formatter }));\n        }\n\n        [Fact]\n        public async Task ReadAsAsync_type_cancellationToken_PassesCancellationTokenFurther()\n        {\n            CancellationTokenSource cts = new CancellationTokenSource();\n            cts.Cancel();\n            HttpContent content = new StringContent(\"42\", Encoding.Default, \"application/json\");\n\n            await Assert.ThrowsAsync<OperationCanceledException>(() => content.ReadAsAsync(typeof(int), cts.Token));\n        }\n\n        [Fact]\n        public async Task ReadAsAsync_type_formatters_cancellationToken_PassesCancellationTokenFurther()\n        {\n            // Arrange\n            Stream stream = new MemoryStream();\n            HttpContent content = new StreamContent(stream);\n            content.Headers.ContentType = MediaTypeHeaderValue.Parse(\"application/test\");\n            CancellationToken token = new CancellationToken();\n            Mock<MediaTypeFormatter> formatter = new Mock<MediaTypeFormatter>(MockBehavior.Strict);\n            formatter.Object.SupportedMediaTypes.Add(content.Headers.ContentType);\n            formatter.Setup(f => f.CanReadType(typeof(int))).Returns(true);\n            formatter\n                .Setup(f => f.ReadFromStreamAsync(typeof(int), It.IsAny<Stream>(), content, null, token))\n                .Returns(Task.FromResult<object>(42))\n                .Verifiable();\n\n            // Act\n            await content.ReadAsAsync(typeof(int), new[] { formatter.Object }, token);\n\n            // Assert\n            formatter.Verify();\n        }\n\n        [Fact]\n        public async Task ReadAsAsync_type_formatters_formatterLogger_cancellationToken_PassesCancellationTokenFurther()\n        {\n            // Arrange\n            Stream stream = new MemoryStream();\n            HttpContent content = new StreamContent(stream);\n            content.Headers.ContentType = MediaTypeHeaderValue.Parse(\"application/test\");\n            CancellationToken token = new CancellationToken();\n            IFormatterLogger formatterLogger = new Mock<IFormatterLogger>().Object;\n\n            Mock<MediaTypeFormatter> formatter = new Mock<MediaTypeFormatter>(MockBehavior.Strict);\n            formatter.Object.SupportedMediaTypes.Add(content.Headers.ContentType);\n            formatter.Setup(f => f.CanReadType(typeof(int))).Returns(true);\n            formatter\n                .Setup(f => f.ReadFromStreamAsync(typeof(int), It.IsAny<Stream>(), content, formatterLogger, token))\n                .Returns(Task.FromResult<object>(42))\n                .Verifiable();\n\n            // Act\n            await content.ReadAsAsync(typeof(int), new[] { formatter.Object }, formatterLogger, token);\n\n            // Assert\n            formatter.Verify();\n        }\n\n        [Fact]\n        public Task ReadAsAsyncOfT_cancellationToken_PassesCancellationTokenFurther()\n        {\n            CancellationTokenSource cts = new CancellationTokenSource();\n            cts.Cancel();\n            HttpContent content = new StringContent(\"42\", Encoding.Default, \"application/json\");\n\n            return Assert.ThrowsAsync<OperationCanceledException>(() => content.ReadAsAsync<int>(cts.Token));\n        }\n\n        [Fact]\n        public async Task ReadAsAsyncOfT_formatters_cancellationToken_PassesCancellationTokenFurther()\n        {\n            // Arrange\n            Stream stream = new MemoryStream();\n            HttpContent content = new StreamContent(stream);\n            content.Headers.ContentType = MediaTypeHeaderValue.Parse(\"application/test\");\n            CancellationToken token = new CancellationToken();\n            Mock<MediaTypeFormatter> formatter = new Mock<MediaTypeFormatter>(MockBehavior.Strict);\n            formatter.Object.SupportedMediaTypes.Add(content.Headers.ContentType);\n            formatter.Setup(f => f.CanReadType(typeof(int))).Returns(true);\n            formatter\n                .Setup(f => f.ReadFromStreamAsync(typeof(int), It.IsAny<Stream>(), content, null, token))\n                .Returns(Task.FromResult<object>(42))\n                .Verifiable();\n\n            // Act\n            await content.ReadAsAsync<int>(new[] { formatter.Object }, token);\n\n            // Assert\n            formatter.Verify();\n        }\n\n        [Fact]\n        public async Task ReadAsAsyncOfT_formatters_formatterLogger_cancellationToken_PassesCancellationTokenFurther()\n        {\n            // Arrange\n            Stream stream = new MemoryStream();\n            HttpContent content = new StreamContent(stream);\n            content.Headers.ContentType = MediaTypeHeaderValue.Parse(\"application/test\");\n            CancellationToken token = new CancellationToken();\n            IFormatterLogger formatterLogger = new Mock<IFormatterLogger>().Object;\n\n            Mock<MediaTypeFormatter> formatter = new Mock<MediaTypeFormatter>(MockBehavior.Strict);\n            formatter.Object.SupportedMediaTypes.Add(content.Headers.ContentType);\n            formatter.Setup(f => f.CanReadType(typeof(int))).Returns(true);\n            formatter\n                .Setup(f => f.ReadFromStreamAsync(typeof(int), It.IsAny<Stream>(), content, formatterLogger, token))\n                .Returns(Task.FromResult<object>(42))\n                .Verifiable();\n\n            // Act\n            await content.ReadAsAsync<int>(new[] { formatter.Object }, formatterLogger, token);\n\n            // Assert\n            formatter.Verify();\n        }\n\n        private void SetupUpRoundTripSerialization(Func<Type, object> factory = null)\n        {\n            factory = factory ?? Activator.CreateInstance;\n            _formatterMock.Setup(f => f.WriteToStreamAsync(It.IsAny<Type>(), It.IsAny<object>(), It.IsAny<Stream>(), It.IsAny<HttpContent>(), It.IsAny<TransportContext>()))\n                .Returns(TaskHelpers.Completed());\n            _formatterMock.Setup(f => f.ReadFromStreamAsync(It.IsAny<Type>(), It.IsAny<Stream>(), It.IsAny<HttpContent>(), It.IsAny<IFormatterLogger>()))\n                .Returns<Type, Stream, HttpContent, IFormatterLogger>((type, stream, content, logger) => Task.FromResult<object>(factory(type)));\n        }\n\n        public class TestClass { }\n\n        public abstract class TestableHttpContent : HttpContent\n        {\n            protected override Task<Stream> CreateContentReadStreamAsync()\n            {\n                return CreateContentReadStreamAsyncPublic();\n            }\n\n            public virtual Task<Stream> CreateContentReadStreamAsyncPublic()\n            {\n                return base.CreateContentReadStreamAsync();\n            }\n\n            protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)\n            {\n                return SerializeToStreamAsyncPublic(stream, context);\n            }\n\n            public abstract Task SerializeToStreamAsyncPublic(Stream stream, TransportContext context);\n\n            protected override bool TryComputeLength(out long length)\n            {\n                return TryComputeLengthPublic(out length);\n            }\n\n            public abstract bool TryComputeLengthPublic(out long length);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/HttpContentFormDataExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http\n{\n    public class HttpContentFormDataExtensionsTest\n    {\n        public static TheoryDataSet<string> FormDataContentTypes\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    \"application/x-www-form-urlencoded\",\n                    \"APPLICATION/x-www-form-urlencoded\",\n                    \"application/X-WWW-FORM-URLENCODED\",\n                    \"application/x-www-form-urlencoded; charset=utf-8\",\n                    \"application/x-www-form-urlencoded; parameter=value\",\n                };\n            }\n        }\n\n        public static TheoryDataSet<string> NonFormDataContentTypes\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    \"application/xml\",\n                    \"APPLICATION/json\",\n                    \"text/xml\",\n                    \"text/xml; charset=utf-8\",\n                    \"text/xml; parameter=value\",\n                };\n            }\n        }\n\n        public static TheoryDataSet<string> FormData\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    \"a=b\",\n                    \"a+c=d+e\",\n                    \"n1=v1&n2=v2\",\n                    \"n1=v1a+v1b&n2=v2a+v2b\",\n                };\n            }\n        }\n\n        public static TheoryDataSet<string> IrregularFormData\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    \"?data\",\n                    Char.ConvertFromUtf32(0x0D),\n                    \"Hello World\",\n                    \"<string>Hello World</string>\",\n                    \"{ \\\"Message\\\" : \\\"Hello World\\\"\",\n                };\n            }\n        }\n\n        [Fact]\n        public void IsFormData_ThrowsOnNull()\n        {\n            Assert.ThrowsArgumentNull(() => HttpContentFormDataExtensions.IsFormData(null), \"content\");\n        }\n\n        [Fact]\n        public void IsFormData_HandlesNullContentType()\n        {\n            HttpContent content = new StringContent(String.Empty);\n            content.Headers.ContentType = null;\n            Assert.False(content.IsFormData());\n        }\n\n        [Theory]\n        [PropertyData(\"FormDataContentTypes\")]\n        public void IsFormData_AcceptsFormDataMediaTypes(string mediaType)\n        {\n            HttpContent content = new StringContent(String.Empty);\n            content.Headers.ContentType = MediaTypeHeaderValue.Parse(mediaType);\n            Assert.True(content.IsFormData());\n        }\n\n        [Theory]\n        [PropertyData(\"NonFormDataContentTypes\")]\n        public void IsFormData_RejectsNonFormDataMediaTypes(string mediaType)\n        {\n            HttpContent content = new StringContent(String.Empty);\n            content.Headers.ContentType = MediaTypeHeaderValue.Parse(mediaType);\n            Assert.False(content.IsFormData());\n        }\n\n        [Fact]\n        public void ReadAsFormDataAsync_ThrowsOnNull()\n        {\n            Assert.ThrowsArgumentNull(() => HttpContentFormDataExtensions.ReadAsFormDataAsync(null), \"content\");\n        }\n\n        [Fact]\n        public async Task ReadAsFromDataAsync_PassesCancellationToken()\n        {\n            CancellationTokenSource cts = new CancellationTokenSource();\n            cts.Cancel();\n            HttpContent content = new StringContent(\"\");\n            content.Headers.ContentType = MediaTypeConstants.ApplicationFormUrlEncodedMediaType;\n\n            await Assert.ThrowsAsync<OperationCanceledException>(() => content.ReadAsFormDataAsync(cts.Token));\n        }\n\n        [Theory]\n        [PropertyData(\"FormData\")]\n        public async Task ReadAsFormDataAsync_HandlesFormData(string formData)\n        {\n            // Arrange\n            HttpContent content = new StringContent(formData);\n            content.Headers.ContentType = MediaTypeConstants.ApplicationFormUrlEncodedMediaType;\n\n            // Act\n            NameValueCollection data = await content.ReadAsFormDataAsync();\n\n            // Assert\n            Assert.Equal(formData, data.ToString());\n        }\n\n        [Fact]\n        public async Task ReadAsFormDataAsync_HandlesFormData_Encoded()\n        {\n            // Arrange\n            string formData = \"N=%c3%a6%c3%b8%c3%a5\";\n            HttpContent content = new StringContent(formData);\n            content.Headers.ContentType = MediaTypeConstants.ApplicationFormUrlEncodedMediaType;\n\n            // Act\n            NameValueCollection data = await content.ReadAsFormDataAsync();\n\n            // Assert\n            Assert.Equal(formData, data.ToString(), ignoreCase: true);\n        }\n\n        [Theory]\n        [PropertyData(\"IrregularFormData\")]\n        public async Task ReadAsFormDataAsync_HandlesIrregularFormData(string irregularFormData)\n        {\n            // Arrange\n            HttpContent content = new StringContent(irregularFormData);\n            content.Headers.ContentType = MediaTypeConstants.ApplicationFormUrlEncodedMediaType;\n\n            // Act\n            NameValueCollection data = await content.ReadAsFormDataAsync();\n\n            // Assert\n            Assert.Single(data);\n            Assert.NotNull(data[irregularFormData]);\n        }\n\n        [Fact]\n        public Task ReadAsFormDataAsync_HandlesNonFormData()\n        {\n            HttpContent content = new StringContent(\"{}\", Encoding.UTF8, \"test/unknown\");\n            return Assert.ThrowsAsync<UnsupportedMediaTypeException>(() => content.ReadAsFormDataAsync());\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/HttpContentMessageExtensionsTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http\n{\n    public class HttpContentMessageExtensionsTests\n    {\n        public static TheoryDataSet<IEnumerable<string>> ClientRoundTripData\n        {\n            get\n            {\n                return new TheoryDataSet<IEnumerable<string>>\n                {\n                    new string[]\n                    {\n                        @\"GET / HTTP/1.1\",\n                        @\"Accept: text/html, application/xhtml+xml, */*\",\n                        @\"Accept-Language: en-US\",\n                        @\"User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)\",\n                        @\"Accept-Encoding: gzip, deflate\",\n                        @\"Proxy-Connection: Keep-Alive\",\n                        @\"Host: msdn.microsoft.com\",\n                        @\"Cookie: omniID=1297715979621_9f45_1519_3f8a_f22f85346ac6; WT_FPC=id=65.55.227.138-2323234032.30136233:lv=1309374389020:ss=1309374389020; A=I&I=AxUFAAAAAACNCAAADYEZ7CFPss7Swnujy4PXZA!!&M=1&CS=126mAa0002ZB51a02gZB51a; MC1=GUID=568428660ad44d4ab8f46133f4b03738&HASH=6628&LV=20113&V=3; WT_NVR_RU=0=msdn:1=:2=; MUID=A44DE185EA1B4E8088CCF7B348C5D65F; MSID=Microsoft.CreationDate=03/04/2011 23:38:15&Microsoft.LastVisitDate=06/20/2011 04:15:08&Microsoft.VisitStartDate=06/20/2011 04:15:08&Microsoft.CookieId=f658f3f2-e6d6-42ab-b86b-96791b942b6f&Microsoft.TokenId=ffffffff-ffff-ffff-ffff-ffffffffffff&Microsoft.NumberOfVisits=106&Microsoft.CookieFirstVisit=1&Microsoft.IdentityToken=AA==&Microsoft.MicrosoftId=0441-6141-1523-9969; msresearch=%7B%22version%22%3A%224.6%22%2C%22state%22%3A%7B%22name%22%3A%22IDLE%22%2C%22url%22%3Aundefined%2C%22timestamp%22%3A1299281911415%7D%2C%22lastinvited%22%3A1299281911415%2C%22userid%22%3A%2212992819114151265672533023080%22%2C%22vendorid%22%3A1%2C%22surveys%22%3A%5Bundefined%5D%7D; CodeSnippetContainerLang=C#; msdn=L=1033; ADS=SN=175A21EF; s_cc=true; s_sq=%5B%5BB%5D%5D; TocHashCookie=ms310241(n)/aa187916(n)/aa187917(n)/dd273952(n)/dd295083(n)/ff472634(n)/ee667046(n)/ee667070(n)/gg259047(n)/gg618436(n)/; WT_NVR=0=/:1=query|library|en-us:2=en-us/vcsharp|en-us/library\",\n                        @\"Cookie: omniID=1297715979621_9f45_1519_3f8a_f22f85346ac6; WT_FPC=id=65.55.227.138-2323234032.30136233:lv=1309374389020:ss=1309374389020; A=I&I=AxUFAAAAAACNCAAADYEZ7CFPss7Swnujy4PXZA!!&M=1&CS=126mAa0002ZB51a02gZB51a; MC1=GUID=568428660ad44d4ab8f46133f4b03738&HASH=6628&LV=20113&V=3; WT_NVR_RU=0=msdn:1=:2=; MUID=A44DE185EA1B4E8088CCF7B348C5D65F; MSID=Microsoft.CreationDate=03/04/2011 23:38:15&Microsoft.LastVisitDate=06/20/2011 04:15:08&Microsoft.VisitStartDate=06/20/2011 04:15:08&Microsoft.CookieId=f658f3f2-e6d6-42ab-b86b-96791b942b6f&Microsoft.TokenId=ffffffff-ffff-ffff-ffff-ffffffffffff&Microsoft.NumberOfVisits=106&Microsoft.CookieFirstVisit=1&Microsoft.IdentityToken=AA==&Microsoft.MicrosoftId=0441-6141-1523-9969; msresearch=%7B%22version%22%3A%224.6%22%2C%22state%22%3A%7B%22name%22%3A%22IDLE%22%2C%22url%22%3Aundefined%2C%22timestamp%22%3A1299281911415%7D%2C%22lastinvited%22%3A1299281911415%2C%22userid%22%3A%2212992819114151265672533023080%22%2C%22vendorid%22%3A1%2C%22surveys%22%3A%5Bundefined%5D%7D; CodeSnippetContainerLang=C#; msdn=L=1033; ADS=SN=175A21EF; s_cc=true; s_sq=%5B%5BB%5D%5D; TocHashCookie=ms310241(n)/aa187916(n)/aa187917(n)/dd273952(n)/dd295083(n)/ff472634(n)/ee667046(n)/ee667070(n)/gg259047(n)/gg618436(n)/; WT_NVR=0=/:1=query|library|en-us:2=en-us/vcsharp|en-us/library\",\n                    },\n                    new string[]\n                    {\n                        @\"GET / HTTP/1.1\",\n                        @\"Host: msdn.microsoft.com\",\n                        @\"Proxy-Connection: keep-alive\",\n                        @\"User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0\",\n                        @\"Accept: text/html, application/xhtml+xml, application/xml; q=0.9, */*; q=0.8\",\n                        @\"Accept-Language: en-us, en; q=0.5\",\n                        @\"Accept-Encoding: gzip, deflate\",\n                        @\"Accept-Charset: ISO-8859-1, utf-8; q=0.7, *; q=0.7\",\n                    },\n                    new string[]\n                    {\n                        @\"GET / HTTP/1.1\",\n                        @\"Host: msdn.microsoft.com\",\n                        @\"Proxy-Connection: keep-alive\",\n                        @\"User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.100 Safari/534.30\",\n                        @\"Accept: text/html, application/xhtml+xml, application/xml; q=0.9, */*; q=0.8\",\n                        @\"Accept-Encoding: gzip, deflate, sdch\",\n                        @\"Accept-Language: en-US, en; q=0.8\",\n                        @\"Accept-Charset: ISO-8859-1, utf-8; q=0.7, *; q=0.3\",\n                    },\n                    new string[]\n                    {\n                        @\"GET / HTTP/1.1\",\n                        @\"Host: msdn.microsoft.com\",\n                        @\"User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1\",\n                        @\"Accept: application/xml, application/xhtml+xml, text/html; q=0.9, text/plain; q=0.8, image/png, */*; q=0.5\",\n                        @\"Accept-Language: en-US\",\n                        @\"Accept-Encoding: gzip, deflate\",\n                        @\"Connection: keep-alive\",\n                        @\"Proxy-Connection: keep-alive\",\n                    },\n                    new string[]\n                    {\n                        @\"GET / HTTP/1.0\",\n                        @\"User-Agent: Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11\",\n                        @\"Host: msdn.microsoft.com\",\n                        @\"Accept: text/html, application/xml; q=0.9, application/xhtml+xml, image/png, image/webp, image/jpeg, image/gif, image/x-xbitmap, */*; q=0.1\",\n                        @\"Accept-Language: en-US, en; q=0.9\",\n                        @\"Accept-Encoding: gzip, deflate\",\n                        @\"Proxy-Connection: Keep-Alive\",\n                    },\n                };\n            }\n        }\n\n        public static TheoryDataSet<IEnumerable<string>> ServerRoundTripData\n        {\n            get\n            {\n                return new TheoryDataSet<IEnumerable<string>>\n                {\n                    new string[]\n                    {\n                        @\"HTTP/1.1 200 OK\",\n                        @\"Server: nginx\",\n                        @\"Date: Mon, 26 Dec 2011 16:33:07 GMT\",\n                        @\"Connection: keep-alive\",\n                        @\"Set-Cookie: CG=US:WA:Bellevue; path=/\",\n                        @\"Vary: Accept-Encoding, User-Agent\",\n                        @\"Cache-Control: max-age=60, private\",\n                        @\"Content-Length: 124\",\n                        @\"Content-Type: text/html; charset=UTF-8\",\n                    },\n                    new string[]\n                    {\n                        @\"HTTP/1.1 302 Found\",\n                        @\"Proxy-Connection: Keep-Alive\",\n                        @\"Connection: Keep-Alive\",\n                        @\"Via: 1.1 RED-PRXY-23\",\n                        @\"Date: Thu, 30 Jun 2011 00:16:35 GMT\",\n                        @\"Location: /en-us/\",\n                        @\"Server: Microsoft-IIS/7.5\",\n                        @\"Cache-Control: private\",\n                        @\"P3P: CP=\"\"ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI\"\", CP=\"\"ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI\"\"\",\n                        @\"Set-Cookie: A=I&I=AxUFAAAAAAD7BwAA8Jx0njhGoW3MGASDmzeaGw!!&M=1; domain=.microsoft.com; expires=Sun, 30-Jun-2041 00:16:35 GMT; path=/\",\n                        @\"Set-Cookie: ADS=SN=175A21EF; domain=.microsoft.com; path=/\",\n                        @\"Set-Cookie: Sto.UserLocale=en-us; path=/\",\n                        @\"Set-Cookie: A=I&I=AxUFAAAAAAD7BwAA8Jx0njhGoW3MGASDmzeaGw!!&M=1; domain=.microsoft.com; expires=Sun, 30-Jun-2041 00:16:35 GMT; path=/; path=/\",\n                        @\"Set-Cookie: ADS=SN=175A21EF; domain=.microsoft.com; path=/; path=/\",\n                        @\"X-AspNetMvc-Version: 3.0\",\n                        @\"X-AspNet-Version: 4.0.30319\",\n                        @\"X-Powered-By: ASP.NET\",\n                        @\"X-Powered-By: ASP.NET\",\n                        @\"Content-Length: 124\",\n                        @\"Content-Type: text/html; charset=utf-8\",\n                    },\n                    new string[]\n                    {\n                        @\"HTTP/1.1 200 OK\",\n                        @\"Proxy-Connection: Keep-Alive\",\n                        @\"Connection: Keep-Alive\",\n                        @\"Transfer-Encoding: chunked\",\n                        @\"Via: 1.1 RED-PRXY-07\",\n                        @\"Date: Mon, 26 Dec 2011 19:11:47 GMT\",\n                        @\"Server: gws\",\n                        @\"Cache-Control: max-age=0, private\",\n                        @\"Set-Cookie: PREF=ID=e91cfd77b562e989:FF=0:TM=1324926707:LM=1324926707:S=4w8_eSySJPXCCjhT; expires=Wed, 25-Dec-2013 19:11:47 GMT; path=/; domain=.google.com\",\n                        @\"Set-Cookie: NID=54=bSMpxl0q0MVlvG-eZYSBtQuYTF1clqrA-TSIZT8wZcbhrrsdkP9G5zPiXGSBmiNu656QR3xfTXKUPkP-HqY_nSnsjj1fb-ipoZ3DUcyXb9oS9_8tjz3NZ3A44GPCmRPx; expires=Tue, 26-Jun-2012 19:11:47 GMT; path=/; domain=.google.com; HttpOnly\",\n                        @\"P3P: CP=\"\"This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info.\"\"\",\n                        @\"X-XSS-Protection: 1; mode=block\",\n                        @\"X-Frame-Options: SAMEORIGIN\",\n                        @\"Expires: -1\",\n                        @\"Content-Type: text/html; charset=ISO-8859-1\",\n                    }\n                };\n            }\n        }\n\n        public static TheoryDataSet<HttpContent> NotHttpMessageContent\n        {\n            get\n            {\n                return new TheoryDataSet<HttpContent>\n                {\n                    new ByteArrayContent(new byte[] { }),\n                    new StringContent(String.Empty),\n                    new StringContent(String.Empty, Encoding.UTF8, \"application/http\"),\n                };\n            }\n        }\n\n        private static HttpContent CreateContent(bool isRequest, bool hasEntity)\n        {\n            string message;\n            if (isRequest)\n            {\n                message = hasEntity ? ParserData.HttpRequestWithEntity : ParserData.HttpRequest;\n            }\n            else\n            {\n                message = hasEntity ? ParserData.HttpResponseWithEntity : ParserData.HttpResponse;\n            }\n\n            StringContent content = new StringContent(message);\n            content.Headers.ContentType = isRequest ? ParserData.HttpRequestMediaType : ParserData.HttpResponseMediaType;\n            return content;\n        }\n\n        private static HttpContent CreateContent(bool isRequest, IEnumerable<string> header, string body)\n        {\n            StringBuilder message = new StringBuilder();\n            foreach (string h in header)\n            {\n                message.Append(h);\n                message.Append(\"\\r\\n\");\n            }\n\n            message.Append(\"\\r\\n\");\n            if (body != null)\n            {\n                message.Append(body);\n            }\n\n            StringContent content = new StringContent(message.ToString());\n            content.Headers.ContentType = isRequest ? ParserData.HttpRequestMediaType : ParserData.HttpResponseMediaType;\n            return content;\n        }\n\n        private static async Task ValidateEntityAsync(HttpContent content)\n        {\n            Assert.NotNull(content);\n            Assert.Equal(ParserData.TextContentType, content.Headers.ContentType.ToString());\n            string entity = await content.ReadAsStringAsync();\n            Assert.Equal(ParserData.HttpMessageEntity, entity);\n        }\n\n        private static async Task ValidateRequestMessageAsync(HttpRequestMessage request, bool hasEntity)\n        {\n            Assert.NotNull(request);\n            Assert.Equal(Version.Parse(\"1.2\"), request.Version);\n            Assert.Equal(ParserData.HttpMethod, request.Method.ToString());\n            Assert.Equal(ParserData.HttpRequestUri, request.RequestUri);\n            Assert.Equal(ParserData.HttpHostName, request.Headers.Host);\n            Assert.True(request.Headers.Contains(\"N1\"), \"request did not contain expected N1 header.\");\n            Assert.True(request.Headers.Contains(\"N2\"), \"request did not contain expected N2 header.\");\n\n            if (hasEntity)\n            {\n                await ValidateEntityAsync(request.Content);\n            }\n        }\n\n        private static async Task ValidateResponseMessageAsync(HttpResponseMessage response, bool hasEntity)\n        {\n            Assert.NotNull(response);\n            Assert.Equal(new Version(\"1.2\"), response.Version);\n            Assert.Equal(ParserData.HttpStatus, response.StatusCode);\n            Assert.Equal(ParserData.HttpReasonPhrase, response.ReasonPhrase);\n            Assert.True(response.Headers.Contains(\"N1\"), \"Response did not contain expected N1 header.\");\n            Assert.True(response.Headers.Contains(\"N2\"), \"Response did not contain expected N2 header.\");\n\n            if (hasEntity)\n            {\n                await ValidateEntityAsync(response.Content);\n            }\n        }\n\n        [Fact]\n        public void ReadAsHttpRequestMessageAsync_VerifyArguments()\n        {\n            Assert.ThrowsArgumentNull(() => HttpContentMessageExtensions.ReadAsHttpRequestMessageAsync(null), \"content\");\n            Assert.ThrowsArgument(() => new ByteArrayContent(new byte[] { }).ReadAsHttpRequestMessageAsync(), \"content\");\n            Assert.ThrowsArgument(() => new StringContent(String.Empty).ReadAsHttpRequestMessageAsync(), \"content\");\n            Assert.ThrowsArgument(() => new StringContent(String.Empty, Encoding.UTF8, \"application/http\").ReadAsHttpRequestMessageAsync(), \"content\");\n\n            Assert.ThrowsArgument(() =>\n            {\n                HttpContent content = new StringContent(String.Empty);\n                content.Headers.ContentType = ParserData.HttpResponseMediaType;\n                content.ReadAsHttpRequestMessageAsync();\n            }, \"content\");\n\n            Assert.ThrowsArgumentNull(() =>\n            {\n                HttpContent content = new StringContent(String.Empty);\n                content.Headers.ContentType = ParserData.HttpRequestMediaType;\n                content.ReadAsHttpRequestMessageAsync(null);\n            }, \"uriScheme\");\n\n            Assert.ThrowsArgument(() =>\n            {\n                HttpContent content = new StringContent(String.Empty);\n                content.Headers.ContentType = ParserData.HttpRequestMediaType;\n                content.ReadAsHttpRequestMessageAsync(\"i n v a l i d\");\n            }, \"uriScheme\");\n\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(() =>\n            {\n                HttpContent content = new StringContent(String.Empty);\n                content.Headers.ContentType = ParserData.HttpRequestMediaType;\n                content.ReadAsHttpRequestMessageAsync(Uri.UriSchemeHttp, ParserData.MinBufferSize - 1);\n            }, \"bufferSize\", ParserData.MinBufferSize.ToString(), ParserData.MinBufferSize - 1);\n        }\n\n        [Fact]\n        public void ReadAsHttpResponseMessageAsync_VerifyArguments()\n        {\n            Assert.ThrowsArgumentNull(() => HttpContentMessageExtensions.ReadAsHttpResponseMessageAsync(null), \"content\");\n            Assert.ThrowsArgument(() => new ByteArrayContent(new byte[] { }).ReadAsHttpResponseMessageAsync(), \"content\");\n            Assert.ThrowsArgument(() => new StringContent(String.Empty).ReadAsHttpResponseMessageAsync(), \"content\");\n            Assert.ThrowsArgument(() => new StringContent(String.Empty, Encoding.UTF8, \"application/http\").ReadAsHttpResponseMessageAsync(), \"content\");\n\n            Assert.ThrowsArgument(() =>\n            {\n                HttpContent content = new StringContent(String.Empty);\n                content.Headers.ContentType = ParserData.HttpRequestMediaType;\n                content.ReadAsHttpResponseMessageAsync();\n            }, \"content\");\n\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(() =>\n            {\n                HttpContent content = new StringContent(String.Empty);\n                content.Headers.ContentType = ParserData.HttpResponseMediaType;\n                content.ReadAsHttpResponseMessageAsync(ParserData.MinBufferSize - 1);\n            }, \"bufferSize\", ParserData.MinBufferSize.ToString(), ParserData.MinBufferSize - 1);\n        }\n\n        [Fact]\n        public void IsHttpRequestMessageContentVerifyArguments()\n        {\n            Assert.ThrowsArgumentNull(() => HttpContentMessageExtensions.IsHttpRequestMessageContent(null), \"content\");\n        }\n\n        [Fact]\n        public void IsHttpResponseMessageContentVerifyArguments()\n        {\n            Assert.ThrowsArgumentNull(() =>\n            {\n                HttpContent content = null;\n                HttpContentMessageExtensions.IsHttpResponseMessageContent(content);\n            }, \"content\");\n        }\n\n        [Theory]\n        [PropertyData(\"NotHttpMessageContent\")]\n        public void IsHttpRequestMessageContentRespondsFalse(HttpContent notHttpMessageContent)\n        {\n            Assert.False(notHttpMessageContent.IsHttpRequestMessageContent());\n        }\n\n        [Fact]\n        public void IsHttpRequestMessageContentRespondsTrue()\n        {\n            HttpContent content = new StringContent(String.Empty);\n            content.Headers.ContentType = ParserData.HttpRequestMediaType;\n            Assert.True(content.IsHttpRequestMessageContent(), \"Content should be HTTP request.\");\n        }\n\n        [Theory]\n        [PropertyData(\"NotHttpMessageContent\")]\n        public void IsHttpResponseMessageContent(HttpContent notHttpMessageContent)\n        {\n            Assert.False(notHttpMessageContent.IsHttpResponseMessageContent());\n\n        }\n\n        [Fact]\n        public void IsHttpResponseMessageContentRespondsTrue()\n        {\n            HttpContent content = new StringContent(String.Empty);\n            content.Headers.ContentType = ParserData.HttpResponseMediaType;\n            Assert.True(content.IsHttpResponseMessageContent(), \"Content should be HTTP response.\");\n        }\n\n        [Fact]\n        public async Task ReadAsHttpRequestMessageAsync_RequestWithoutEntity_ShouldReturnHttpRequestMessage()\n        {\n            HttpContent content = CreateContent(isRequest: true, hasEntity: false);\n            HttpRequestMessage httpRequest = await content.ReadAsHttpRequestMessageAsync();\n            await ValidateRequestMessageAsync(httpRequest, hasEntity: false);\n        }\n\n        [Fact]\n        public async Task ReadAsHttpRequestMessageAsync_RequestWithEntity_ShouldReturnHttpRequestMessage()\n        {\n            HttpContent content = CreateContent(isRequest: true, hasEntity: true);\n            HttpRequestMessage httpRequest = await content.ReadAsHttpRequestMessageAsync();\n            await ValidateRequestMessageAsync(httpRequest, hasEntity: true);\n        }\n\n        [Fact]\n        public async Task ReadAsHttpRequestMessageAsync_WithHttpsUriScheme_ReturnsUriWithHttps()\n        {\n            HttpContent content = CreateContent(isRequest: true, hasEntity: true);\n            HttpRequestMessage httpRequest = await content.ReadAsHttpRequestMessageAsync(Uri.UriSchemeHttps);\n            Assert.Equal(ParserData.HttpsRequestUri, httpRequest.RequestUri);\n        }\n\n        [Fact]\n        public async Task ReadAsHttpResponseMessageAsync_ResponseWithoutEntity_ShouldReturnHttpResponseMessage()\n        {\n            HttpContent content = CreateContent(isRequest: false, hasEntity: false);\n            HttpResponseMessage httpResponse = await content.ReadAsHttpResponseMessageAsync();\n            await ValidateResponseMessageAsync(httpResponse, hasEntity: false);\n        }\n\n        [Fact]\n        public async Task ReadAsHttpResponseMessageAsync_ResponseWithEntity_ShouldReturnHttpResponseMessage()\n        {\n            HttpContent content = CreateContent(isRequest: false, hasEntity: true);\n            HttpResponseMessage httpResponse = await content.ReadAsHttpResponseMessageAsync();\n            await ValidateResponseMessageAsync(httpResponse, hasEntity: true);\n        }\n\n        [Fact]\n        public Task ReadAsHttpRequestMessageAsync_NoHostHeader_Throws()\n        {\n            string[] request = new[] {\n                @\"GET / HTTP/1.1\",\n            };\n\n            HttpContent content = CreateContent(true, request, null);\n            return Assert.ThrowsAsync<InvalidOperationException>(() => content.ReadAsHttpRequestMessageAsync());\n        }\n\n        [Fact]\n        public Task ReadAsHttpRequestMessageAsync_TwoHostHeaders_Throws()\n        {\n            string[] request = new[] {\n                @\"GET / HTTP/1.1\",\n                @\"Host: somehost.com\",\n                @\"Host: otherhost.com\",\n            };\n\n            HttpContent content = CreateContent(true, request, null);\n            return Assert.ThrowsAsync<InvalidOperationException>(() => content.ReadAsHttpRequestMessageAsync());\n        }\n\n        [Fact]\n        public async Task ReadAsHttpRequestMessageAsync_SortHeaders()\n        {\n            string[] request = new[] {\n                @\"GET / HTTP/1.1\",\n                @\"Host: somehost.com\",\n                @\"Content-Language: xx\",\n                @\"Request-Header: zz\",\n            };\n\n            HttpContent content = CreateContent(true, request, \"sample body\");\n            HttpRequestMessage httpRequest = await content.ReadAsHttpRequestMessageAsync();\n            Assert.Equal(\"xx\", httpRequest.Content.Headers.ContentLanguage.ToString());\n\n            IEnumerable<string> requestHeaderValues;\n            Assert.True(httpRequest.Headers.TryGetValues(\"request-header\", out requestHeaderValues));\n            Assert.Equal(\"zz\", requestHeaderValues.First());\n        }\n\n        [Fact]\n        public async Task ReadAsHttpResponseMessageAsync_SortHeaders()\n        {\n            string[] response = new[] {\n                @\"HTTP/1.1 200 OK\",\n                @\"Content-Language: xx\",\n                @\"Response-Header: zz\",\n            };\n\n            HttpContent content = CreateContent(false, response, \"sample body\");\n            HttpResponseMessage httpResponse = await content.ReadAsHttpResponseMessageAsync();\n            Assert.Equal(\"xx\", httpResponse.Content.Headers.ContentLanguage.ToString());\n\n            IEnumerable<string> ResponseHeaderValues;\n            Assert.True(httpResponse.Headers.TryGetValues(\"Response-header\", out ResponseHeaderValues));\n            Assert.Equal(\"zz\", ResponseHeaderValues.First());\n        }\n\n        [Fact]\n        public Task ReadAsHttpResponseMessageAsync_Throws_TheHeaderSizeExceededTheDefaultLimit()\n        {\n            string[] response = new[] {\n                @\"HTTP/1.1 200 OK\",\n                String.Format(\"Set-Cookie: {0}={1}\", new String('a', 16 * 1024), new String('b', 16 * 1024))\n            };\n\n            return Assert.ThrowsAsync<InvalidOperationException>(() =>\n                {\n                    HttpContent content = CreateContent(false, response, \"sample body\");\n                    return content.ReadAsHttpResponseMessageAsync();\n                });\n        }\n\n        [Fact]\n        public Task ReadAsHttpRequestMessageAsync_Throws_TheHeaderSizeExceededTheDefaultLimit()\n        {\n            string[] request = new[] {\n                @\"GET / HTTP/1.1\",\n                @\"Host: msdn.microsoft.com\",\n                String.Format(\"Cookie: {0}={1}\", new String('a', 16 * 1024), new String('b', 16 * 1024))\n            };\n\n            return Assert.ThrowsAsync<InvalidOperationException>(() =>\n            {\n                HttpContent content = CreateContent(true, request, \"sample body\");\n                return content.ReadAsHttpRequestMessageAsync();\n            });\n        }\n\n        [Fact]\n        public Task ReadAsHttpResponseMessageAsync_LargeHeaderSize()\n        {\n            string[] response = new[] {\n                @\"HTTP/1.1 200 OK\",\n                String.Format(\"Set-Cookie: {0}={1}\", new String('a', 16 * 1024), new String('b', 16 * 1024))\n            };\n\n            HttpContent content = CreateContent(false, response, \"sample body\");\n            return content.ReadAsHttpResponseMessageAsync(64 * 1024, 64 * 1024);\n        }\n\n        [Fact]\n        public async Task ReadAsHttpRequestMessageAsync_LargeHeaderSize()\n        {\n            string cookieValue = string.Format(\"{0}={1}\", new String('a', 16 * 1024), new String('b', 16 * 1024));\n            string[] request = new[] {\n                @\"GET / HTTP/1.1\",\n                @\"Host: msdn.microsoft.com\",\n                string.Format(\"Cookie: {0}\", cookieValue),\n            };\n\n            HttpContent content = CreateContent(true, request, \"sample body\");\n            var httpRequestMessage = await content.ReadAsHttpRequestMessageAsync(Uri.UriSchemeHttp, 64 * 1024, 64 * 1024);\n\n            Assert.Equal(HttpMethod.Get, httpRequestMessage.Method);\n            Assert.Equal(\"/\", httpRequestMessage.RequestUri.PathAndQuery);\n            Assert.Equal(\"msdn.microsoft.com\", httpRequestMessage.Headers.Host);\n            IEnumerable<string> actualCookieValue;\n            Assert.True(httpRequestMessage.Headers.TryGetValues(\"Cookie\", out actualCookieValue));\n            Assert.Equal(cookieValue, Assert.Single(actualCookieValue));\n        }\n\n        [Fact]\n        public async Task ReadAsHttpRequestMessageAsync_LargeHttpRequestLine()\n        {\n            string requestPath = string.Format(\"/myurl?{0}={1}\", new string('a', 4 * 1024), new string('b', 4 * 1024));\n            string cookieValue = string.Format(\"{0}={1}\", new String('a', 4 * 1024), new String('b', 4 * 1024));\n            string[] request = new[]\n            {\n                string.Format(\"GET {0} HTTP/1.1\", requestPath),\n                @\"Host: msdn.microsoft.com\",\n                string.Format(\"Cookie: {0}\", cookieValue),\n            };\n\n            HttpContent content = CreateContent(true, request, \"sample body\");\n            var httpRequestMessage = await content.ReadAsHttpRequestMessageAsync(\n                Uri.UriSchemeHttp,\n                bufferSize: 64 * 1024,\n                maxHeaderSize: 64 * 1024);\n\n            Assert.Equal(HttpMethod.Get, httpRequestMessage.Method);\n            Assert.Equal(requestPath, httpRequestMessage.RequestUri.PathAndQuery);\n            Assert.Equal(\"msdn.microsoft.com\", httpRequestMessage.Headers.Host);\n            IEnumerable<string> actualCookieValue;\n            Assert.True(httpRequestMessage.Headers.TryGetValues(\"Cookie\", out actualCookieValue));\n            Assert.Equal(cookieValue, Assert.Single(actualCookieValue));\n        }\n\n        [Theory]\n        [InlineData(\"\")]\n        [InlineData(\"HTTP/1.1\")]\n        [InlineData(\"HTTP/1.1 200 OK\")]\n        [InlineData(\"HTTP/1.1 200 OK\\r\\n\")]\n        [InlineData(\"HTTP/1.1 200 OK\\r\\nServer:\")]\n        [InlineData(\"HTTP/1.1 200 OK\\r\\nServer: server\")]\n        [InlineData(\"HTTP/1.1 200 OK\\r\\nServer: server\\r\\n\")]\n        [InlineData(\"HTTP/1.1 200 OK\\r\\nServer: server\\r\\n\\r\")]\n        public Task ReadAsHttpResponseMessageAsync_IncompleteResponse(string incompleteResponse)\n        {\n            StringContent content = new StringContent(incompleteResponse);\n            content.Headers.ContentType = ParserData.HttpResponseMediaType;\n            return Assert.ThrowsAsync<IOException>(() => content.ReadAsHttpResponseMessageAsync());\n        }\n\n        [Theory]\n        [InlineData(\"\")]\n        [InlineData(\"GET\")]\n        [InlineData(\"GET / HTTP/1.0\")]\n        [InlineData(\"GET / HTTP/1.0\\r\\n\")]\n        [InlineData(\"GET / HTTP/1.0\\r\\nHost:\")]\n        [InlineData(\"GET / HTTP/1.0\\r\\nHost: localhost\")]\n        [InlineData(\"GET / HTTP/1.0\\r\\nHost: localhost\\r\\n\")]\n        [InlineData(\"GET / HTTP/1.0\\r\\nHost: localhost\\r\\n\\r\")]\n        public Task ReadAsHttpRequestMessageAsync_IncompleteRequest(string incompleteRequest)\n        {\n            StringContent content = new StringContent(incompleteRequest);\n            content.Headers.ContentType = ParserData.HttpRequestMediaType;\n            return Assert.ThrowsAsync<IOException>(() => content.ReadAsHttpRequestMessageAsync());\n        }\n\n        [Theory]\n        [PropertyData(\"ClientRoundTripData\")]\n        public async Task RoundtripClientRequest(IEnumerable<string> message)\n        {\n            HttpContent content = CreateContent(true, message, null);\n            HttpRequestMessage httpRequest = await content.ReadAsHttpRequestMessageAsync();\n            HttpMessageContent httpMessageContent = new HttpMessageContent(httpRequest);\n\n            MemoryStream destination = new MemoryStream();\n            await httpMessageContent.CopyToAsync(destination);\n            destination.Seek(0, SeekOrigin.Begin);\n            string destinationMessage = new StreamReader(destination).ReadToEnd();\n            string sourceMessage = await content.ReadAsStringAsync();\n            Assert.Equal(sourceMessage, destinationMessage);\n        }\n\n        [Theory]\n        [PropertyData(\"ServerRoundTripData\")]\n        public async Task RoundtripServerResponse(IEnumerable<string> message)\n        {\n            HttpContent content = CreateContent(false, message, @\"<html><head><title>Object moved</title></head><body><h2>Object moved to <a href=\"\"/en-us/\"\">here</a>.</h2></body></html>\");\n            HttpResponseMessage httpResponse = await content.ReadAsHttpResponseMessageAsync();\n            HttpMessageContent httpMessageContent = new HttpMessageContent(httpResponse);\n\n            MemoryStream destination = new MemoryStream();\n            await httpMessageContent.CopyToAsync(destination);\n            destination.Seek(0, SeekOrigin.Begin);\n            string destinationMessage = new StreamReader(destination).ReadToEnd();\n            string sourceMessage = await content.ReadAsStringAsync();\n            Assert.Equal(sourceMessage, destinationMessage);\n        }\n\n        [Fact]\n        public Task ReadAsHttpRequestMessageAsync_cancellationToken_PassesCancellationToken()\n        {\n            CancellationTokenSource cts = new CancellationTokenSource();\n            cts.Cancel();\n            HttpContent content = CreateContent(isRequest: true, hasEntity: false);\n\n            return Assert.ThrowsAsync<OperationCanceledException>(() => content.ReadAsHttpRequestMessageAsync(cts.Token));\n        }\n\n        [Fact]\n        public Task ReadAsHttpRequestMessageAsync_uriScheme_cancellationToken_PassesCancellationToken()\n        {\n            CancellationTokenSource cts = new CancellationTokenSource();\n            cts.Cancel();\n            HttpContent content = CreateContent(isRequest: true, hasEntity: false);\n\n            return Assert.ThrowsAsync<OperationCanceledException>(\n                () => content.ReadAsHttpRequestMessageAsync(\"http\", cts.Token));\n        }\n\n        [Fact]\n        public Task ReadAsHttpRequestMessageAsync_uriScheme_bufferSize_cancellationToken_PassesCancellationToken()\n        {\n            CancellationTokenSource cts = new CancellationTokenSource();\n            cts.Cancel();\n            HttpContent content = CreateContent(isRequest: true, hasEntity: false);\n\n            return Assert.ThrowsAsync<OperationCanceledException>(\n                () => content.ReadAsHttpRequestMessageAsync(\"http\", 1024, cts.Token));\n        }\n\n        [Fact]\n        public Task ReadAsHttpRequestMessageAsync_uriScheme_bufferSize_maxHeaderSize_cancellationToken_PassesCancellationToken()\n        {\n            CancellationTokenSource cts = new CancellationTokenSource();\n            cts.Cancel();\n            HttpContent content = CreateContent(isRequest: true, hasEntity: false);\n\n            return Assert.ThrowsAsync<OperationCanceledException>(\n                () => content.ReadAsHttpRequestMessageAsync(\"http\", 1024, 1024, cts.Token));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/HttpContentMultipartExtensionsTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Net.Http.Formatting.Parsers;\nusing System.Net.Http.Headers;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Net.Http\n{\n    public class HttpContentMultipartExtensionsTests\n    {\n        private const string ValidBoundary = \"-A-\";\n        private const string DefaultContentType = \"text/plain\";\n        private const string DefaultContentDisposition = \"form-data\";\n        private const string ExceptionStreamProviderMessage = \"Bad Stream Provider!\";\n        private const string ExceptionSyncStreamMessage = \"Bad Sync Stream!\";\n        private const string ExceptionAsyncStreamMessage = \"Bad Async Stream!\";\n\n        public static TheoryDataSet<string, bool, string, bool> IsMimeMultipartContentTestData\n        {\n            get\n            {\n                return new TheoryDataSet<string, bool, string, bool>\n                {\n                    { \"text/plain\", false, \"plain\", false },\n                    { \"application/*\", false, \"related\", false },\n                    { \"*/*\", false, \"related\", false },\n                    { \"multipart/form-data\", false, \"form-data\", false },\n                    { \"multipart/form-data; boundary=1234\", true, \"related\", false },\n                    { \"multipart/form-data; boundary=1234; charset=utf-8\", true, \"form-data\", true },\n                    { \"Multipart/Related; boundary=example-1; start=\\\"<950120.aaCC@XIson.com>\\\"; type=\\\"Application/X-FixedRecord\\\"; start-info=\\\"-o ps\\\"\", true, \"related\", true },\n                };\n            }\n        }\n\n        public static TheoryDataSet<string, bool> IsMimeMultipartContentTestData_NoSubType\n        {\n            get\n            {\n                var dataSet = new TheoryDataSet<string, bool>();\n                foreach (var item in IsMimeMultipartContentTestData)\n                {\n                    dataSet.Add((string)item[0], (bool)item[1]);\n                }\n\n                return dataSet;\n            }\n        }\n\n        private static HttpContent CreateContent(string boundary, params string[] bodyEntity)\n        {\n            return CreateContentWithContentType(boundary, DefaultContentType, bodyEntity);\n        }\n\n        private static HttpContent CreateContentWithContentType(string boundary, string partContentType, params string[] bodyEntity)\n        {\n            List<string> entities = new List<string>();\n            int cnt = 0;\n            foreach (var body in bodyEntity)\n            {\n                byte[] header = InternetMessageFormatHeaderParserTests.CreateBuffer(\n                    String.Format(\"N{0}: V{0}\", cnt),\n                    String.Format(\"Content-Type: {0}\", partContentType),\n                    String.Format(\"Content-Disposition: {0}; FileName=\\\"N{1}\\\"\", DefaultContentDisposition, cnt));\n                entities.Add(Encoding.UTF8.GetString(header) + body);\n                cnt++;\n            }\n\n            byte[] message = MimeMultipartParserTests.CreateBuffer(boundary, entities.ToArray());\n            HttpContent result = new ByteArrayContent(message);\n            var contentType = new MediaTypeHeaderValue(\"multipart/form-data\");\n            contentType.Parameters.Add(new NameValueHeaderValue(\"boundary\", String.Format(\"\\\"{0}\\\"\", boundary)));\n            result.Headers.ContentType = contentType;\n            return result;\n        }\n\n        private static async Task ValidateContentsAsync(IEnumerable<HttpContent> contents)\n        {\n            int cnt = 0;\n            foreach (var content in contents)\n            {\n                Assert.NotNull(content);\n                Assert.NotNull(content.Headers);\n                Assert.Equal(4, content.Headers.Count());\n\n                IEnumerable<string> parsedValues = content.Headers.GetValues(String.Format(\"N{0}\", cnt));\n                string parsedValue = Assert.Single(parsedValues);\n                Assert.Equal(String.Format(\"V{0}\", cnt), parsedValue);\n\n                Assert.Equal(DefaultContentType, content.Headers.ContentType.MediaType);\n\n                Assert.Equal(DefaultContentDisposition, content.Headers.ContentDisposition.DispositionType);\n                Assert.Equal(String.Format(\"\\\"N{0}\\\"\", cnt), content.Headers.ContentDisposition.FileName);\n\n                await AssertContentLengthHeaderValueAsync(content);\n\n                cnt++;\n            }\n        }\n\n        private static async Task AssertContentLengthHeaderValueAsync(HttpContent content)\n        {\n            long contentLength = (await content.ReadAsByteArrayAsync()).LongLength;\n            long contentLengthHeaderValue = content.Headers.ContentLength.GetValueOrDefault();\n            Assert.Equal(contentLength, contentLengthHeaderValue);\n        }\n\n        [Fact]\n        public void IsMimeMultipartContent_ThrowsOnNullContent()\n        {\n            Assert.ThrowsArgumentNull(() => HttpContentMultipartExtensions.IsMimeMultipartContent(null), \"content\");\n        }\n\n        [Fact]\n        public void IsMimeMultipartContent_ThrowsOnNullSubType()\n        {\n            StringContent content = new StringContent(String.Empty);\n            Assert.ThrowsArgumentNull(() => HttpContentMultipartExtensions.IsMimeMultipartContent(content, null), \"subtype\");\n        }\n\n        [Theory]\n        [PropertyData(\"IsMimeMultipartContentTestData\")]\n        public void IsMimeMultipartContent_ReturnsCorrectValue(string mediaType, bool isMultipart, string subtype, bool hasSubtype)\n        {\n            StringContent content = new StringContent(String.Empty);\n            content.Headers.ContentType = MediaTypeHeaderValue.Parse(mediaType);\n\n            Assert.Equal(isMultipart, content.IsMimeMultipartContent());\n            Assert.Equal(hasSubtype, content.IsMimeMultipartContent(subtype));\n        }\n\n        [Fact]\n        public Task ReadAsMultipartAsync_ThrowsOnNullStreamProvider()\n        {\n            HttpContent content = CreateContent(ValidBoundary);\n            return Assert.ThrowsArgumentNullAsync(() => content.ReadAsMultipartAsync((MultipartStreamProvider)null), \"streamProvider\");\n        }\n\n        [Fact]\n        public Task ReadAsMultipartAsync_ThrowsOnInvalidBufferSize()\n        {\n            HttpContent content = CreateContent(ValidBoundary);\n            return Assert.ThrowsArgumentGreaterThanOrEqualToAsync(\n                () => content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider(), ParserData.MinBufferSize - 1),\n                \"bufferSize\", ParserData.MinBufferSize.ToString(), ParserData.MinBufferSize - 1);\n        }\n\n        [Theory]\n        [PropertyData(\"IsMimeMultipartContentTestData_NoSubType\")]\n        public async Task ReadAsMultipartAsync_DetectsNonMultipartContent(string mediaType, bool isMultipart)\n        {\n            StringContent content = new StringContent(String.Empty);\n            content.Headers.ContentType = MediaTypeHeaderValue.Parse(mediaType);\n            if (!isMultipart)\n            {\n                await Assert.ThrowsArgumentAsync(() => content.ReadAsMultipartAsync(), \"content\");\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(MimeMultipartParserTests), \"Boundaries\")]\n        public async Task ReadAsMultipartAsync_ParsesContent(string boundary)\n        {\n            HttpContent successContent;\n            MultipartMemoryStreamProvider result;\n\n            successContent = CreateContent(boundary, \"A\", \"B\", \"C\");\n            result = await successContent.ReadAsMultipartAsync();\n            Assert.Equal(3, result.Contents.Count);\n\n            successContent = CreateContent(boundary, \"A\", \"B\", \"C\");\n            result = await successContent.ReadAsMultipartAsync(new MultipartMemoryStreamProvider());\n            Assert.Equal(3, result.Contents.Count);\n\n            successContent = CreateContent(boundary, \"A\", \"B\", \"C\");\n            result = await successContent.ReadAsMultipartAsync(new MultipartMemoryStreamProvider(), 1024);\n            Assert.Equal(3, result.Contents.Count);\n        }\n\n        [Fact]\n        public async Task ReadAsMultipartAsync_SkipsHeaderValidation()\n        {\n            // Arrange\n            var content = CreateContentWithContentType(\"--boundary\", \"invalid\", \"SomeContent\");\n\n            // Act\n            var result = await content.ReadAsMultipartAsync(CancellationToken.None);\n\n            // Assert\n            var bodyPart = Assert.Single(result.Contents);\n            Assert.Null(bodyPart.Headers.ContentType);\n            Assert.Equal(\"invalid\", Assert.Single(bodyPart.Headers.GetValues(\"Content-Type\")));\n        }\n\n        [Fact]\n        public async Task ReadAsMultipartAsync_SetsStronglyTypedHeader_WhenHeaderIsValid()\n        {\n            // Arrange\n            var content = CreateContentWithContentType(\"--boundary\", \"application/json\", \"SomeContent\");\n\n            // Act\n            var result = await content.ReadAsMultipartAsync(CancellationToken.None);\n\n            // Assert\n            var bodyPart = Assert.Single(result.Contents);\n            Assert.NotNull(bodyPart.Headers.ContentType);\n            Assert.Equal(\"application/json\", bodyPart.Headers.ContentType.MediaType);\n        }\n\n        [Theory]\n        [TestDataSet(typeof(MimeMultipartParserTests), \"Boundaries\")]\n        public async Task ReadAsMultipartAsync_ParsesEmptyContent(string boundary)\n        {\n            HttpContent content = CreateContent(boundary);\n            MultipartMemoryStreamProvider result = await content.ReadAsMultipartAsync();\n            Assert.Empty(result.Contents);\n        }\n\n        [Fact]\n        public async Task ReadAsMultipartAsync_ThrowsOnBadStreamProvider()\n        {\n            HttpContent content = CreateContent(ValidBoundary, \"A\", \"B\", \"C\");\n            IOException exception = await Assert.ThrowsAsync<IOException>(() => content.ReadAsMultipartAsync(new BadStreamProvider()));\n            InvalidOperationException invalidOperationException = exception.InnerException as InvalidOperationException;\n            Assert.NotNull(invalidOperationException);\n            Assert.NotNull(invalidOperationException.InnerException);\n            Assert.Equal(ExceptionStreamProviderMessage, invalidOperationException.InnerException.Message);\n        }\n\n        [Fact]\n        public async Task ReadAsMultipartAsync_ThrowsOnNullProvider()\n        {\n            HttpContent content = CreateContent(ValidBoundary, \"A\", \"B\", \"C\");\n            IOException exception = await Assert.ThrowsAsync<IOException>(() => content.ReadAsMultipartAsync(new NullProvider()));\n            Assert.IsType<InvalidOperationException>(exception.InnerException);\n        }\n\n        [Fact]\n        public async Task ReadAsMultipartAsync_ThrowsOnReadOnlyStream()\n        {\n            HttpContent content = CreateContent(ValidBoundary, \"A\", \"B\", \"C\");\n            IOException exception = await Assert.ThrowsAsync<IOException>(() => content.ReadAsMultipartAsync(new ReadOnlyStreamProvider()));\n            Assert.IsType<InvalidOperationException>(exception.InnerException);\n        }\n\n        [Fact]\n        public Task ReadAsMultipartAsync_ThrowsOnPrematureEndOfStream()\n        {\n            HttpContent content = new StreamContent(Stream.Null);\n            string mediaType = String.Format(\"multipart/form-data; boundary=\\\"{0}\\\"\", ValidBoundary);\n            content.Headers.ContentType = MediaTypeHeaderValue.Parse(mediaType);\n            return Assert.ThrowsAsync<IOException>(() => content.ReadAsMultipartAsync());\n        }\n\n        [Fact]\n        public async Task ReadAsMultipartAsync_ThrowsOnReadError()\n        {\n            HttpContent content = new StreamContent(new ReadErrorStream());\n            string mediaType = String.Format(\"multipart/form-data; boundary=\\\"{0}\\\"\", ValidBoundary);\n            content.Headers.ContentType = MediaTypeHeaderValue.Parse(mediaType);\n            IOException exception = await Assert.ThrowsAsync<IOException>(() => content.ReadAsMultipartAsync());\n            Assert.NotNull(exception.InnerException);\n            Assert.Equal(ExceptionAsyncStreamMessage, exception.InnerException.Message);\n        }\n\n        [Fact]\n        public async Task ReadAsMultipartAsync_ThrowsOnWriteError()\n        {\n            HttpContent content = CreateContent(ValidBoundary, \"A\", \"B\", \"C\");\n            IOException exception = await Assert.ThrowsAsync<IOException>(() => content.ReadAsMultipartAsync(new WriteErrorStreamProvider()));\n            Assert.NotNull(exception.InnerException);\n            Assert.Equal(ExceptionAsyncStreamMessage, exception.InnerException.Message);\n        }\n\n        [Theory]\n        [TestDataSet(typeof(MimeMultipartParserTests), \"Boundaries\", typeof(MimeMultipartParserTests), \"SingleShortBodies\")]\n        public async Task ReadAsMultipartAsync_SingleShortBodyPart(string boundary, string singleShortBody)\n        {\n            HttpContent content = CreateContent(boundary, singleShortBody);\n\n            MultipartMemoryStreamProvider result = await content.ReadAsMultipartAsync();\n            HttpContent resultContent = Assert.Single(result.Contents);\n            Assert.Equal(singleShortBody, await resultContent.ReadAsStringAsync());\n            await ValidateContentsAsync(result.Contents);\n        }\n\n        [Fact]\n        public async Task ReadAsMultipartAsync_WithHugeBody_AvoidStackOverflow()\n        {\n            // Arrange\n            var fiftyMegs = 1024 * 1024 * 50;\n            HttpContent content = CreateContent(\"---3123---\", new string('x', fiftyMegs));\n\n            // Act\n            MultipartMemoryStreamProvider result = await content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider(), 256);\n\n            // Assert\n            // this is for sanity. The actual test here is that the Act part did not cause a stack overflow\n            Assert.Equal(fiftyMegs, (await result.Contents[0].ReadAsStringAsync()).Length);\n            await ValidateContentsAsync(result.Contents);\n        }\n\n        [Theory]\n        [TestDataSet(typeof(MimeMultipartParserTests), \"Boundaries\", typeof(MimeMultipartParserTests), \"MultipleShortBodies\")]\n        public async Task ReadAsMultipartAsync_MultipleShortBodyParts(string boundary, string[] multipleShortBodies)\n        {\n            HttpContent content = CreateContent(boundary, multipleShortBodies);\n            MultipartMemoryStreamProvider result = await content.ReadAsMultipartAsync();\n            Assert.Equal(multipleShortBodies.Length, result.Contents.Count);\n            for (var check = 0; check < multipleShortBodies.Length; check++)\n            {\n                Assert.Equal(multipleShortBodies[check], await result.Contents[check].ReadAsStringAsync());\n            }\n\n            await ValidateContentsAsync(result.Contents);\n        }\n\n        [Theory]\n        [TestDataSet(typeof(MimeMultipartParserTests), \"Boundaries\", typeof(MimeMultipartParserTests), \"SingleLongBodies\")]\n        public async Task ReadAsMultipartAsync_SingleLongBodyPart(string boundary, string singleLongBody)\n        {\n            HttpContent content = CreateContent(boundary, singleLongBody);\n\n            MultipartMemoryStreamProvider result = await content.ReadAsMultipartAsync();\n            HttpContent resultContent = Assert.Single(result.Contents);\n            Assert.Equal(singleLongBody, await resultContent.ReadAsStringAsync());\n            await ValidateContentsAsync(result.Contents);\n        }\n\n        [Theory]\n        [TestDataSet(typeof(MimeMultipartParserTests), \"Boundaries\", typeof(MimeMultipartParserTests), \"MultipleLongBodies\")]\n        public async Task ReadAsMultipartAsync_MultipleLongBodyParts(string boundary, string[] multipleLongBodies)\n        {\n            HttpContent content = CreateContent(boundary, multipleLongBodies);\n            MultipartMemoryStreamProvider result = await content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider(), ParserData.MinBufferSize);\n            Assert.Equal(multipleLongBodies.Length, result.Contents.Count);\n            for (var check = 0; check < multipleLongBodies.Length; check++)\n            {\n                Assert.Equal(multipleLongBodies[check], await result.Contents[check].ReadAsStringAsync());\n            }\n\n            await ValidateContentsAsync(result.Contents);\n        }\n\n        [Theory]\n        [TestDataSet(typeof(MimeMultipartParserTests), \"Boundaries\")]\n        public async Task ReadAsMultipartAsync_UsingMultipartContent(string boundary)\n        {\n            MultipartContent content = new MultipartContent(\"mixed\", boundary);\n            content.Add(new StringContent(\"A\"));\n            content.Add(new StringContent(\"B\"));\n            content.Add(new StringContent(\"C\"));\n\n            MemoryStream memStream = new MemoryStream();\n            await content.CopyToAsync(memStream);\n            memStream.Position = 0;\n            byte[] data = memStream.ToArray();\n            var byteContent = new ByteArrayContent(data);\n            byteContent.Headers.ContentType = content.Headers.ContentType;\n\n            MultipartMemoryStreamProvider result = await byteContent.ReadAsMultipartAsync();\n            Assert.Equal(3, result.Contents.Count);\n            Assert.Equal(\"A\", await result.Contents[0].ReadAsStringAsync());\n            Assert.Equal(\"B\", await result.Contents[1].ReadAsStringAsync());\n            Assert.Equal(\"C\", await result.Contents[2].ReadAsStringAsync());\n        }\n\n        [Theory]\n        [TestDataSet(typeof(MimeMultipartParserTests), \"Boundaries\")]\n        public async Task ReadAsMultipartAsync_NestedMultipartContent(string boundary)\n        {\n            const int nesting = 10;\n            const string innerText = \"Content\";\n\n            MultipartContent innerContent = new MultipartContent(\"mixed\", boundary);\n            innerContent.Add(new StringContent(innerText));\n            for (var cnt = 0; cnt < nesting; cnt++)\n            {\n                string outerBoundary = String.Format(\"{0}_{1}\", boundary, cnt);\n                MultipartContent outerContent = new MultipartContent(\"mixed\", outerBoundary);\n                outerContent.Add(innerContent);\n                innerContent = outerContent;\n            }\n\n            MemoryStream memStream = new MemoryStream();\n            await innerContent.CopyToAsync(memStream);\n            memStream.Position = 0;\n            byte[] data = memStream.ToArray();\n            HttpContent content = new ByteArrayContent(data);\n            content.Headers.ContentType = innerContent.Headers.ContentType;\n\n            for (var cnt = 0; cnt < nesting + 1; cnt++)\n            {\n                MultipartMemoryStreamProvider result = await content.ReadAsMultipartAsync();\n                content = Assert.Single(result.Contents);\n                Assert.NotNull(content);\n            }\n\n            string text = await content.ReadAsStringAsync();\n            Assert.Equal(innerText, text);\n        }\n\n        [Fact]\n        public async Task ReadAsMultipartAsyncOfT_PassesCancellationToken()\n        {\n            CancellationToken token = new CancellationToken();\n            HttpContent content = CreateContent(\"boundary\");\n            Mock<MultipartStreamProvider> provider = new Mock<MultipartStreamProvider>();\n            provider.Setup(p => p.ExecutePostProcessingAsync(token))\n                .Returns(Task.FromResult(42))\n                .Verifiable();\n\n            await content.ReadAsMultipartAsync<MultipartStreamProvider>(provider.Object, token);\n\n            provider.Verify();\n        }\n\n        public class ReadOnlyStream : MemoryStream\n        {\n            public override bool CanWrite\n            {\n                get\n                {\n                    return false;\n                }\n            }\n        }\n\n        public class ReadErrorStream : MemoryStream\n        {\n            public override int Read(byte[] buffer, int offset, int count)\n            {\n                throw new IOException(ExceptionSyncStreamMessage);\n            }\n            public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)\n            {\n                throw new IOException(ExceptionAsyncStreamMessage);\n            }\n\n#if !Testing_NetStandard1_3 // BeginX and EndX not supported on Streams in netstandard1.3\n            public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)\n            {\n                throw new IOException(ExceptionAsyncStreamMessage);\n            }\n#endif\n        }\n\n        public class WriteErrorStream : MemoryStream\n        {\n            public override void Write(byte[] buffer, int offset, int count)\n            {\n                throw new IOException(ExceptionSyncStreamMessage);\n            }\n\n            public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)\n            {\n                throw new IOException(ExceptionAsyncStreamMessage);\n            }\n\n#if !Testing_NetStandard1_3 // BeginX and EndX not supported on Streams in netstandard1.3\n            public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)\n            {\n                throw new IOException(ExceptionAsyncStreamMessage);\n            }\n#endif\n        }\n\n        public class BadStreamProvider : MultipartStreamProvider\n        {\n            public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)\n            {\n                throw new Exception(ExceptionStreamProviderMessage);\n            }\n        }\n\n        public class NullProvider : MultipartStreamProvider\n        {\n            public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)\n            {\n                return null;\n            }\n        }\n\n        public class ReadOnlyStreamProvider : MultipartStreamProvider\n        {\n            public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)\n            {\n                return new ReadOnlyStream();\n            }\n        }\n\n        public class WriteErrorStreamProvider : MultipartStreamProvider\n        {\n            public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)\n            {\n                return new WriteErrorStream();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/HttpHeaderExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Headers;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http\n{\n    public class HttpHeaderExtensionsTest\n    {\n        [Fact]\n        public void CopyTo_CopiesContentHeaders()\n        {\n            // Arrange\n            HttpContentHeaders source = FormattingUtilities.CreateEmptyContentHeaders();\n            source.ContentType = MediaTypeHeaderValue.Parse(\"application/json; charset=utf8; parameter=value\");\n            source.ContentLength = 1234;\n            source.ContentLocation = new Uri(\"http://some.host\");\n            source.Add(\"test-name1\", \"test-value1\");\n            source.Add(\"test-name2\", \"test-value2\");\n\n            HttpContentHeaders destination = FormattingUtilities.CreateEmptyContentHeaders();\n\n            // Act\n            source.CopyTo(destination);\n\n            // Assert\n            Assert.Equal(source.ToString(), destination.ToString());\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/HttpMessageContentTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Net.Http.Headers;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http\n{\n    public class HttpMessageContentTests\n    {\n        private static readonly int iterations = 5;\n\n        private static void AddMessageHeaders(HttpHeaders headers)\n        {\n            headers.Add(\"N1\", new string[] { \"V1a\", \"V1b\", \"V1c\", \"V1d\", \"V1e\" });\n            headers.Add(\"N2\", \"V2\");\n        }\n\n        private static HttpRequestMessage CreateRequest(Uri requestUri, bool containsEntity)\n        {\n            HttpRequestMessage httpRequest = new HttpRequestMessage();\n            httpRequest.Method = new HttpMethod(ParserData.HttpMethod);\n            httpRequest.RequestUri = requestUri;\n            httpRequest.Version = new Version(\"1.2\");\n            AddMessageHeaders(httpRequest.Headers);\n            if (containsEntity)\n            {\n                httpRequest.Content = new StringContent(ParserData.HttpMessageEntity);\n            }\n\n            return httpRequest;\n        }\n\n        private static HttpResponseMessage CreateResponse(bool containsEntity)\n        {\n            HttpResponseMessage httpResponse = new HttpResponseMessage();\n            httpResponse.StatusCode = ParserData.HttpStatus;\n            httpResponse.ReasonPhrase = ParserData.HttpReasonPhrase;\n            httpResponse.Version = new Version(\"1.2\");\n            AddMessageHeaders(httpResponse.Headers);\n            httpResponse.Content =\n                containsEntity ? new StringContent(ParserData.HttpMessageEntity) : new StreamContent(Stream.Null);\n\n            return httpResponse;\n        }\n\n        private static async Task<string> ReadContentAsync(HttpContent content, bool unBuffered = false)\n        {\n            if (unBuffered)\n            {\n                var stream = new MemoryStream();\n                await content.CopyToAsync(stream);\n                stream.Position = 0L;\n\n                // StreamReader will dispose of the Stream.\n                using var reader = new StreamReader(stream);\n\n                return await reader.ReadToEndAsync();\n            }\n            else\n            {\n                await content.LoadIntoBufferAsync();\n\n                return await content.ReadAsStringAsync();\n            }\n        }\n\n        private static async Task ValidateRequest(HttpContent content, bool containsEntity, bool unBuffered = false)\n        {\n            Assert.Equal(ParserData.HttpRequestMediaType, content.Headers.ContentType);\n            long? length = content.Headers.ContentLength;\n            Assert.NotNull(length);\n\n            string message = await ReadContentAsync(content, unBuffered);\n            if (containsEntity)\n            {\n                Assert.Equal(ParserData.HttpRequestWithEntity.Length, length);\n                Assert.Equal(ParserData.HttpRequestWithEntity, message);\n            }\n            else\n            {\n                Assert.Equal(ParserData.HttpRequest.Length, length);\n                Assert.Equal(ParserData.HttpRequest, message);\n            }\n        }\n\n        private static async Task ValidateResponse(HttpContent content, bool containsEntity, bool unBuffered = false)\n        {\n            Assert.Equal(ParserData.HttpResponseMediaType, content.Headers.ContentType);\n\n            long? length = content.Headers.ContentLength;\n            Assert.NotNull(length);\n\n            string message = await ReadContentAsync(content, unBuffered);\n            if (containsEntity)\n            {\n                Assert.Equal(ParserData.HttpResponseWithEntity.Length, length);\n                Assert.Equal(ParserData.HttpResponseWithEntity, message);\n            }\n            else\n            {\n                Assert.Equal(ParserData.HttpResponse.Length, length);\n                Assert.Equal(ParserData.HttpResponse, message);\n            }\n        }\n\n        [Fact]\n        public void TypeIsCorrect()\n        {\n            Assert.Type.HasProperties<HttpMessageContent, HttpContent>(TypeAssert.TypeProperties.IsPublicVisibleClass | TypeAssert.TypeProperties.IsDisposable);\n        }\n\n        [Fact]\n        public void RequestConstructor()\n        {\n            HttpRequestMessage request = new HttpRequestMessage();\n            HttpMessageContent instance = new HttpMessageContent(request);\n            Assert.NotNull(instance);\n            Assert.Same(request, instance.HttpRequestMessage);\n            Assert.Null(instance.HttpResponseMessage);\n        }\n\n        [Fact]\n        public void RequestConstructorThrowsOnNull()\n        {\n            Assert.ThrowsArgumentNull(() => { new HttpMessageContent((HttpRequestMessage)null); }, \"httpRequest\");\n        }\n\n        [Fact]\n        public void ResponseConstructor()\n        {\n            HttpResponseMessage response = new HttpResponseMessage();\n            HttpMessageContent instance = new HttpMessageContent(response);\n            Assert.NotNull(instance);\n            Assert.Same(response, instance.HttpResponseMessage);\n            Assert.Null(instance.HttpRequestMessage);\n        }\n\n        [Fact]\n        public void ResponseConstructorThrowsOnNull()\n        {\n            Assert.ThrowsArgumentNull(() => { new HttpMessageContent((HttpResponseMessage)null); }, \"httpResponse\");\n        }\n\n\n        [Fact]\n        public async Task SerializeRequest()\n        {\n            for (int cnt = 0; cnt < iterations; cnt++)\n            {\n                HttpRequestMessage request = CreateRequest(ParserData.HttpRequestUri, false);\n                HttpMessageContent instance = new HttpMessageContent(request);\n                await ValidateRequest(instance, false);\n            }\n        }\n\n        [Fact]\n        public async Task SerializeRequestWithExistingHostHeader()\n        {\n            HttpRequestMessage request = CreateRequest(ParserData.HttpRequestUri, false);\n            string host = ParserData.HttpHostName;\n            request.Headers.Host = host;\n            HttpMessageContent instance = new HttpMessageContent(request);\n            string message = await ReadContentAsync(instance);\n            Assert.Equal(ParserData.HttpRequestWithHost, message);\n        }\n\n        [Theory]\n        [InlineData(false)]\n        [InlineData(true)]\n        public async Task SerializeRequestMultipleTimes(bool unBuffered)\n        {\n            HttpRequestMessage request = CreateRequest(ParserData.HttpRequestUri, containsEntity: false);\n            HttpMessageContent instance = new(request);\n            for (int cnt = 0; cnt < iterations; cnt++)\n            {\n                await ValidateRequest(instance, containsEntity: false, unBuffered);\n            }\n        }\n\n        [Fact]\n        public async Task SerializeResponse()\n        {\n            for (int cnt = 0; cnt < iterations; cnt++)\n            {\n                HttpResponseMessage response = CreateResponse(false);\n                HttpMessageContent instance = new HttpMessageContent(response);\n                await ValidateResponse(instance, false);\n            }\n        }\n\n        [Theory]\n        [InlineData(false)]\n        [InlineData(true)]\n        public async Task SerializeResponseMultipleTimes(bool unBuffered)\n        {\n            HttpResponseMessage response = CreateResponse(containsEntity: false);\n            HttpMessageContent instance = new(response);\n            for (int cnt = 0; cnt < iterations; cnt++)\n            {\n                await ValidateResponse(instance, containsEntity: false, unBuffered);\n            }\n        }\n\n        [Fact]\n        public async Task SerializeRequestWithEntity()\n        {\n            for (int cnt = 0; cnt < iterations; cnt++)\n            {\n                HttpRequestMessage request = CreateRequest(ParserData.HttpRequestUri, true);\n                HttpMessageContent instance = new HttpMessageContent(request);\n                await ValidateRequest(instance, true);\n            }\n        }\n\n        [Theory]\n        [InlineData(false)]\n        [InlineData(true)]\n        public async Task SerializeRequestWithEntityMultipleTimes(bool unBuffered)\n        {\n            HttpRequestMessage request = CreateRequest(ParserData.HttpRequestUri, containsEntity: true);\n            HttpMessageContent instance = new(request);\n            for (int cnt = 0; cnt < iterations; cnt++)\n            {\n                await ValidateRequest(instance, containsEntity: true, unBuffered);\n            }\n        }\n\n        [Fact]\n        public async Task SerializeResponseWithEntity()\n        {\n            for (int cnt = 0; cnt < iterations; cnt++)\n            {\n                HttpResponseMessage response = CreateResponse(true);\n                HttpMessageContent instance = new HttpMessageContent(response);\n                await ValidateResponse(instance, true);\n            }\n        }\n\n        [Theory]\n        [InlineData(false)]\n        [InlineData(true)]\n        public async Task SerializeResponseWithEntityMultipleTimes(bool unBuffered)\n        {\n            HttpResponseMessage response = CreateResponse(containsEntity: true);\n            HttpMessageContent instance = new(response);\n            for (int cnt = 0; cnt < iterations; cnt++)\n            {\n                await ValidateResponse(instance, containsEntity: true, unBuffered);\n            }\n        }\n\n        [Fact]\n        public async Task SerializeRequestAsync()\n        {\n            for (int cnt = 0; cnt < iterations; cnt++)\n            {\n                HttpRequestMessage request = CreateRequest(ParserData.HttpRequestUri, false);\n                HttpMessageContent instance = new HttpMessageContent(request);\n                await ValidateRequest(instance, false);\n            }\n        }\n\n        [Fact]\n        public async Task SerializeResponseAsync()\n        {\n            for (int cnt = 0; cnt < iterations; cnt++)\n            {\n                HttpResponseMessage response = CreateResponse(false);\n                HttpMessageContent instance = new HttpMessageContent(response);\n                await ValidateResponse(instance, false);\n            }\n        }\n\n        [Fact]\n        public async Task SerializeRequestWithPortAndQueryAsync()\n        {\n            for (int cnt = 0; cnt < iterations; cnt++)\n            {\n                HttpRequestMessage request = CreateRequest(ParserData.HttpRequestUriWithPortAndQuery, false);\n                HttpMessageContent instance = new HttpMessageContent(request);\n                string message = await ReadContentAsync(instance);\n                Assert.Equal(ParserData.HttpRequestWithPortAndQuery, message);\n            }\n        }\n\n        [Fact]\n        public async Task SerializeRequestWithEntityAsync()\n        {\n            for (int cnt = 0; cnt < iterations; cnt++)\n            {\n                HttpRequestMessage request = CreateRequest(ParserData.HttpRequestUri, true);\n                HttpMessageContent instance = new HttpMessageContent(request);\n                await ValidateRequest(instance, true);\n            }\n        }\n\n        [Fact]\n        public async Task SerializeResponseWithEntityAsync()\n        {\n            for (int cnt = 0; cnt < iterations; cnt++)\n            {\n                HttpResponseMessage response = CreateResponse(true);\n                HttpMessageContent instance = new HttpMessageContent(response);\n                await ValidateResponse(instance, true);\n            }\n        }\n\n        [Fact]\n        public void DisposeInnerHttpRequestMessage()\n        {\n            HttpRequestMessage request = CreateRequest(ParserData.HttpRequestUri, false);\n            HttpMessageContent instance = new HttpMessageContent(request);\n            instance.Dispose();\n            Assert.ThrowsObjectDisposed(() => { request.Method = HttpMethod.Get; }, typeof(HttpRequestMessage).FullName);\n        }\n\n        [Fact]\n        public void DisposeInnerHttpResponseMessage()\n        {\n            HttpResponseMessage response = CreateResponse(false);\n            HttpMessageContent instance = new HttpMessageContent(response);\n            instance.Dispose();\n            Assert.ThrowsObjectDisposed(() => { response.StatusCode = HttpStatusCode.OK; }, typeof(HttpResponseMessage).FullName);\n        }\n\n        [Fact]\n        public void Request_ContentLengthNull_IfReadOnlyStream()\n        {\n            var request = CreateRequest(ParserData.HttpRequestUri, containsEntity: false);\n            request.Content = new StreamContent(new ReadOnlyStream());\n            var instance = new HttpMessageContent(request);\n\n            var length = instance.Headers.ContentLength;\n\n            Assert.Null(length);\n        }\n\n        [Fact]\n        public void Response_ContentLengthNull_IfReadOnlyStream()\n        {\n            var response = CreateResponse(containsEntity: false);\n            response.Content = new StreamContent(new ReadOnlyStream());\n            var instance = new HttpMessageContent(response);\n\n            var length = instance.Headers.ContentLength;\n\n            Assert.Null(length);\n        }\n\n        // Also confirms content can be serialized multiple times if either buffered or involves a seekable Stream.\n        [Theory]\n        [InlineData(false, true)]\n        [InlineData(true, false)]\n        public async Task Request_NoContentLength_IfNotRequested(bool readOnlyStream, bool unBuffered)\n        {\n            var request = CreateRequest(ParserData.HttpRequestUri, containsEntity: false);\n            if (readOnlyStream)\n            {\n                request.Content = new StreamContent(new ReadOnlyStream());\n            }\n            var instance = new HttpMessageContent(request);\n\n            for (int cnt = 0; cnt < iterations; cnt++)\n            {\n                var contentString = await ReadContentAsync(instance, unBuffered);\n\n                Assert.Equal(ParserData.HttpRequest.Replace(\"Content-Length: 0\\r\\n\", \"\"), contentString);\n            }\n        }\n\n        // Also confirms content can be serialized multiple times if either buffered or involves a seekable Stream.\n        [Theory]\n        [InlineData(false, true)]\n        [InlineData(true, false)]\n        public async Task Response_NoContentLength_IfNotRequested(bool readOnlyStream, bool unBuffered)\n        {\n            var response = CreateResponse(containsEntity: false);\n            if (readOnlyStream)\n            {\n                response.Content = new StreamContent(new ReadOnlyStream());\n            }\n            var instance = new HttpMessageContent(response);\n\n            for (int cnt = 0; cnt < iterations; cnt++)\n            {\n                var contentString = await ReadContentAsync(instance, unBuffered);\n\n                Assert.Equal(ParserData.HttpResponse.Replace(\"Content-Length: 0\\r\\n\", \"\"), contentString);\n            }\n        }\n\n        // Covers the false, false case of Request_NoContentLength_IfNotRequested(...).\n        [Fact]\n        public async Task Request_HasContentLength_IfBuffered_EvenIfNotRequested()\n        {\n            var request = CreateRequest(ParserData.HttpRequestUri, containsEntity: false);\n            var instance = new HttpMessageContent(request);\n            for (int cnt = 0; cnt < iterations; cnt++)\n            {\n                var contentString = await ReadContentAsync(instance, unBuffered: false);\n\n                Assert.Equal(ParserData.HttpRequest, contentString);\n            }\n        }\n\n        // Covers the false, false case of Response_NoContentLength_IfNotRequested(...).\n        [Fact]\n        public async Task Response_HasContentLength_IfBuffered_EvenIfNotRequested()\n        {\n            var response = CreateResponse(containsEntity: false);\n            var instance = new HttpMessageContent(response);\n            for (int cnt = 0; cnt < iterations; cnt++)\n            {\n                var contentString = await ReadContentAsync(instance, unBuffered: false);\n\n                Assert.Equal(ParserData.HttpResponse, contentString);\n            }\n        }\n\n        // Covers the true, true case of Request_NoContentLength_IfNotRequested(...).\n        [Fact]\n        public async Task Request_CannotSerializeMultipleTimes_IfNotBufferedAndNotSeekable()\n        {\n            var request = CreateRequest(ParserData.HttpRequestUri, containsEntity: false);\n            request.Content = new StreamContent(new ReadOnlyStream());\n            var instance = new HttpMessageContent(request);\n\n            // Act #1\n            var contentString = await ReadContentAsync(instance, unBuffered: true);\n\n            // Assert #1\n            Assert.Equal(ParserData.HttpRequest.Replace(\"Content-Length: 0\\r\\n\", \"\"), contentString);\n\n            // Act #2\n            await Assert.ThrowsAsync<InvalidOperationException>(\n                () => ReadContentAsync(instance, unBuffered: true),\n                \"The 'HttpContent' of the 'HttpRequestMessage' has already been read.\");\n        }\n\n        // Covers the true, true case of Response_NoContentLength_IfNotRequested(...).\n        [Fact]\n        public async Task Response_CannotSerializeMultipleTimes_IfNotBufferedAndNotSeekable()\n        {\n            var response = CreateResponse(containsEntity: false);\n            response.Content = new StreamContent(new ReadOnlyStream());\n            var instance = new HttpMessageContent(response);\n\n            // Act #1\n            var contentString = await ReadContentAsync(instance, unBuffered: true);\n\n            // Assert #1\n            Assert.Equal(ParserData.HttpResponse.Replace(\"Content-Length: 0\\r\\n\", \"\"), contentString);\n\n            // Act #2\n            await Assert.ThrowsAsync<InvalidOperationException>(\n                () => ReadContentAsync(instance, unBuffered: true),\n                \"The 'HttpContent' of the 'HttpResponseMessage' has already been read.\");\n        }\n\n        [Theory]\n        [InlineData(false)]\n        [InlineData(true)]\n        public async Task Request_CannotSerialize_IfWriteOnlyStream(bool unBuffered)\n        {\n            var request = CreateRequest(ParserData.HttpRequestUri, containsEntity: false);\n            request.Content = new StreamContent(new WriteOnlyStream());\n            var instance = new HttpMessageContent(request);\n\n            await Assert.ThrowsAsync<NotSupportedException>(\n                () => ReadContentAsync(instance, unBuffered),\n                \"Stream does not support reading.\");\n        }\n\n        [Theory]\n        [InlineData(false)]\n        [InlineData(true)]\n        public async Task Response_CannotSerialize_IfWriteOnlyStream(bool unBuffered)\n        {\n            var response = CreateResponse(containsEntity: false);\n            response.Content = new StreamContent(new WriteOnlyStream());\n            var instance = new HttpMessageContent(response);\n\n            await Assert.ThrowsAsync<NotSupportedException>(\n                () => ReadContentAsync(instance, unBuffered),\n                \"Stream does not support reading.\");\n        }\n\n        // Unlike Stream.Null, this stream does not support seeking. Bit more like (say) a network stream or\n        // the EmptyReadStream introduced in .NET 5. Note: EmptyReadStream should never be visible to our code\n        // because HttpContentMessageExtensions and HttpRequestMessageExtensions overwrite\n        // HttpResponseMessage.Content (or HttpRequestMessage.Content in one case) when creating an instance.\n        private class ReadOnlyStream : Stream\n        {\n            public override bool CanRead => true;\n            public override bool CanSeek => false;\n            public override bool CanWrite => false;\n            public override long Length => throw new NotImplementedException();\n            public override long Position\n            {\n                get => throw new NotImplementedException();\n                set => throw new NotImplementedException();\n            }\n\n            public override void Flush()\n            {\n                // Do nothing.\n            }\n\n            public override int Read(byte[] buffer, int offset, int count) => 0;\n\n            public override long Seek(long offset, SeekOrigin origin) => throw new NotImplementedException();\n\n            public override void SetLength(long value) => throw new NotImplementedException();\n\n            public override void Write(byte[] buffer, int offset, int count) => throw new NotImplementedException();\n        }\n\n        // Unlike Stream.Null, this stream does not support seeking. Bit more like (say) a network stream.\n        private class WriteOnlyStream : Stream\n        {\n            public override bool CanRead => false;\n            public override bool CanSeek => false;\n            public override bool CanWrite => true;\n            public override long Length => throw new NotImplementedException();\n            public override long Position\n            {\n                get => throw new NotImplementedException();\n                set => throw new NotImplementedException();\n            }\n\n            public override void Flush()\n            {\n                // Do nothing.\n            }\n\n            public override int Read(byte[] buffer, int offset, int count) => throw new NotImplementedException();\n\n            public override long Seek(long offset, SeekOrigin origin) => throw new NotImplementedException();\n\n            public override void SetLength(long value) => throw new NotImplementedException();\n\n            public override void Write(byte[] buffer, int offset, int count)\n            {\n                // Ignore all parameters and do nothing.\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/HttpRequestHeadersExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http.Headers;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http\n{\n    public class HttpRequestHeadersExtensionsTest\n    {\n        public static TheoryDataSet<string[], string, string[]> CookieMatches\n        {\n            get\n            {\n                // IEnumerable<string> inputCookies, string matchName, IEnumerable<string> expectedOuput\n                return new TheoryDataSet<string[], string, string[]>\n                {\n                    {\n                        new string[] {},\n                        \"empty\",\n                        new string[] {}\n                    },\n                    {\n                        new string[]\n                        {\n                            \"RMID=2dab5fc9747d4f8edaf410ff\",\n                            \"adxcs=-\",\n                            \"adxcl=l*2ba62=4fc449bf:1\",\n                            \"adxcs=si=0:1\",\n                        },\n                        \"nomatch\",\n                        new string[] {}\n                    },\n                    {\n                        new string[]\n                        {\n                            \"RMID=2dab5fc9747d4f8edaf410ff\",\n                            \"adxcs=-\",\n                            \"adxcl=l*2ba62=4fc449bf:1\",\n                            \"ADXCS=si=0:1\",\n                        },\n                        \"adxcs\",\n                        new string[]\n                        {\n                            \"adxcs=-\",\n                            \"ADXCS=si=0%3A1\"\n                        }\n                    },\n                    {\n                        new string[]\n                        {\n                            \"MC1=GUID=e87574286c55d547b5a0b19fb27d57a4&HASH=2874&LV=20124&V=3&LU=1334766376863; MS0=7bbaad2a8316483c89bbd2ca4e96fcea; A=I&I=AxUFAAAAAACSCAAAHFNnP3xE7Uth5BCZZSiqZQ!!\",\n                            \"MC0=1334766377159; MC1=GUID=e87574286c55d547b5a0b19fb27d57a4&HASH=2874&LV=20124&V=3&LU=1334766376863; MS0=7bbaad2a8316483c89bbd2ca4e96fcea; A=I&I=AxUFAAAAAACSCAAAHFNnP3xE7Uth5BCZZSiqZQ!!; MUID=20EC57A324256BF3039D54E520256B7D&TUID=1\",\n                        },\n                        \"A\",\n                        new string[]\n                        {\n                            \"MC1=GUID=e87574286c55d547b5a0b19fb27d57a4&HASH=2874&LV=20124&V=3&LU=1334766376863; MS0=7bbaad2a8316483c89bbd2ca4e96fcea; A=I&I=AxUFAAAAAACSCAAAHFNnP3xE7Uth5BCZZSiqZQ!!\",\n                            \"MC0=1334766377159; MC1=GUID=e87574286c55d547b5a0b19fb27d57a4&HASH=2874&LV=20124&V=3&LU=1334766376863; MS0=7bbaad2a8316483c89bbd2ca4e96fcea; A=I&I=AxUFAAAAAACSCAAAHFNnP3xE7Uth5BCZZSiqZQ!!; MUID=20EC57A324256BF3039D54E520256B7D&TUID=1\",\n                        }\n                    },\n                    {\n                        new string[]\n                        {\n                            \"MC1=GUID=e87574286c55d547b5a0b19fb27d57a4&HASH=2874&LV=20124&V=3&LU=1334766376863; MS0=7bbaad2a8316483c89bbd2ca4e96fcea; A=I&I=AxUFAAAAAACSCAAAHFNnP3xE7Uth5BCZZSiqZQ!!\",\n                            \"MC0=1334766377159; MC1=GUID=e87574286c55d547b5a0b19fb27d57a4&HASH=2874&LV=20124&V=3&LU=1334766376863; MS0=7bbaad2a8316483c89bbd2ca4e96fcea; A=I&I=AxUFAAAAAACSCAAAHFNnP3xE7Uth5BCZZSiqZQ!!; MUID=20EC57A324256BF3039D54E520256B7D&TUID=1\",\n                        },\n                        \"MC0\",\n                        new string[]\n                        {\n                            \"MC0=1334766377159; MC1=GUID=e87574286c55d547b5a0b19fb27d57a4&HASH=2874&LV=20124&V=3&LU=1334766376863; MS0=7bbaad2a8316483c89bbd2ca4e96fcea; A=I&I=AxUFAAAAAACSCAAAHFNnP3xE7Uth5BCZZSiqZQ!!; MUID=20EC57A324256BF3039D54E520256B7D&TUID=1\",\n                        }\n                    },\n                    {\n                        new string[]\n                        {\n                            \"MC1=GUID=e87574286c55d547b5a0b19fb27d57a4&HASH=2874&LV=20124&V=3&LU=1334766376863; MS0=7bbaad2a8316483c89bbd2ca4e96fcea; A=I&I=AxUFAAAAAACSCAAAHFNnP3xE7Uth5BCZZSiqZQ!!\",\n                            \"MC0=1334766377159; MC1=GUID=e87574286c55d547b5a0b19fb27d57a4&HASH=2874&LV=20124&V=3&LU=1334766376863; MS0=7bbaad2a8316483c89bbd2ca4e96fcea; A=I&I=AxUFAAAAAACSCAAAHFNnP3xE7Uth5BCZZSiqZQ!!; MUID=20EC57A324256BF3039D54E520256B7D&TUID=1\",\n                        },\n                        \"MC\",\n                        new string[] { }\n                    },\n                };\n            }\n        }\n\n        [Fact]\n        public void GetCookies_ThrowsOnNull()\n        {\n            Assert.ThrowsArgumentNull(() => HttpRequestHeadersExtensions.GetCookies(null), \"headers\");\n        }\n\n        [Fact]\n        public void GetCookies_GetsCookiesReturnsEmptyCollection()\n        {\n            // Arrange\n            HttpRequestHeaders headers = CreateHttpRequestHeaders();\n\n            // Act\n            IEnumerable<CookieHeaderValue> cookies = headers.GetCookies();\n\n            // Assert\n            Assert.Empty(cookies);\n        }\n\n        [Theory]\n        [InlineData(\"name1=n1=v1&n2=v2&n3=v3; expires=Sun, 06 Nov 1994 08:49:37 GMT; max-age=86400; domain=domain1; path=path1; secure; httponly\")]\n        public void GetCookies_GetsCookies(string expectedCookie)\n        {\n            // Arrange\n            HttpRequestHeaders headers = CreateHttpRequestHeaders();\n            headers.TryAddWithoutValidation(\"Cookie\", expectedCookie);\n\n            // Act\n            IEnumerable<CookieHeaderValue> cookies = headers.GetCookies();\n\n            // Assert\n            CookieHeaderValue cookie = Assert.Single(cookies);\n            string actualCookie = cookie.ToString();\n            Assert.Equal(expectedCookie, actualCookie);\n        }\n\n        [Fact]\n        public void GetCookiesByName_ThrowsOnNullHeaders()\n        {\n            Assert.ThrowsArgumentNull(() => HttpRequestHeadersExtensions.GetCookies(null, \"empty\"), \"headers\");\n        }\n\n        [Fact]\n        public void GetCookiesByName_ThrowsOnNullName()\n        {\n            HttpRequestHeaders headers = CreateHttpRequestHeaders();\n            Assert.ThrowsArgumentNull(() => HttpRequestHeadersExtensions.GetCookies(headers, null), \"name\");\n        }\n\n        [Theory]\n        [PropertyData(\"CookieMatches\")]\n        public void GetCookiesByName_GetsCookies(IEnumerable<string> cookies, string name, IEnumerable<string> expectedCookies)\n        {\n            // Arrange\n            HttpRequestHeaders headers = CreateHttpRequestHeaders();\n            foreach (string cookie in cookies)\n            {\n                headers.TryAddWithoutValidation(\"Cookie\", cookie);\n            }\n\n            // Act\n            IEnumerable<CookieHeaderValue> actualCookieHeaderValues = headers.GetCookies(name);\n\n            // Assert\n            IEnumerable<string> actualCookies = actualCookieHeaderValues.Select(c => c.ToString());\n            Assert.True(actualCookies.SequenceEqual(expectedCookies));\n        }\n\n        private static HttpRequestHeaders CreateHttpRequestHeaders()\n        {\n            HttpRequestMessage request = new HttpRequestMessage();\n            return request.Headers;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/HttpRequestMessageCommonExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http\n{\n    public class HttpRequestMessageExtensionsTest\n    {\n        [Fact]\n        public void IsCorrectType()\n        {\n            Assert.Type.HasProperties(typeof(HttpRequestMessageExtensions), TypeAssert.TypeProperties.IsStatic | TypeAssert.TypeProperties.IsPublicVisibleClass);\n        }\n\n        [Fact]\n        public void CreateResponseThrowsOnNull()\n        {\n            Assert.ThrowsArgumentNull(() => HttpRequestMessageExtensions.CreateResponse(null), \"request\");\n        }\n\n        [Fact]\n        public void CreateResponseWithStatusThrowsOnNull()\n        {\n            Assert.ThrowsArgumentNull(() => HttpRequestMessageExtensions.CreateResponse(null, HttpStatusCode.OK), \"request\");\n        }\n\n        [Fact]\n        public void CreateResponse()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n\n            // Act\n            HttpResponseMessage response = request.CreateResponse();\n\n            // Assert\n            Assert.Same(request, response.RequestMessage);\n            Assert.Equal(HttpStatusCode.OK, response.StatusCode);\n        }\n\n        [Fact]\n        public void CreateResponseWithStatus()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n\n            // Act\n            HttpResponseMessage response = request.CreateResponse(HttpStatusCode.NotImplemented);\n\n            // Assert\n            Assert.Same(request, response.RequestMessage);\n            Assert.Equal(HttpStatusCode.NotImplemented, response.StatusCode);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/HttpResponseHeadersExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http.Headers;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http\n{\n    public class HttpResponseHeadersExtensionsTest\n    {\n        [Fact]\n        public void AddCookies_ThrowsOnNull()\n        {\n            HttpResponseHeaders headers = CreateHttpResponseHeaders();\n            List<CookieHeaderValue> cookies = new List<CookieHeaderValue>();\n\n            Assert.ThrowsArgumentNull(() => HttpResponseHeadersExtensions.AddCookies(null, cookies), \"headers\");\n            Assert.ThrowsArgumentNull(() => HttpResponseHeadersExtensions.AddCookies(headers, null), \"cookies\");\n        }\n\n        [Fact]\n        public void AddCookies_ThrowsOnNullCookie()\n        {\n            HttpResponseHeaders headers = CreateHttpResponseHeaders();\n            List<CookieHeaderValue> cookies = new List<CookieHeaderValue>();\n            cookies.Add(null);\n\n            Assert.ThrowsArgument(() => HttpResponseHeadersExtensions.AddCookies(headers, cookies), \"cookies\");\n        }\n\n        [Theory]\n        [InlineData(\"name1=n1=v1&n2=v2&n3=v3; expires=Sun, 06 Nov 1994 08:49:37 GMT; max-age=86400; domain=domain1; path=path1; secure; httponly\")]\n        public void AddCookies_AddsCookies(string expectedCookie)\n        {\n            // Arrange\n            HttpResponseHeaders headers = CreateHttpResponseHeaders();\n            List<CookieHeaderValue> cookies = new List<CookieHeaderValue>();\n            CookieHeaderValue cookie;\n            bool parsedCorrectly = CookieHeaderValue.TryParse(expectedCookie, out cookie);\n            cookies.Add(cookie);\n\n            // Act\n            headers.AddCookies(cookies);\n\n            // Assert\n            Assert.True(parsedCorrectly);\n            IEnumerable<string> actualCookies;\n            bool addedCorrectly = headers.TryGetValues(\"Set-Cookie\", out actualCookies);\n            Assert.True(addedCorrectly);\n            string actualCookie = Assert.Single(actualCookies);\n            Assert.Equal(expectedCookie, actualCookie);\n        }\n\n        private static HttpResponseHeaders CreateHttpResponseHeaders()\n        {\n            HttpResponseMessage response = new HttpResponseMessage();\n            return response.Headers;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/HttpUnsortedRequestTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http\n{\n    public class HttpUnsortedRequestTest\n    {\n        [Fact]\n        public void Constructor_InitializesHeaders()\n        {\n            HttpUnsortedRequest request = new HttpUnsortedRequest();\n            Assert.IsType<HttpUnsortedHeaders>(request.HttpHeaders);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/HttpUnsortedResponseTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http\n{\n    public class HttpUnsortedResponseTest\n    {\n        [Fact]\n        public void Constructor_InitializesHeaders()\n        {\n            HttpUnsortedResponse response = new HttpUnsortedResponse();\n            Assert.IsType<HttpUnsortedHeaders>(response.HttpHeaders);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Internal/AsyncResultTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Internal;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http\n{\n    public class AsyncResultTest\n    {\n        private static readonly TimeSpan _timeout = TimeSpan.FromMilliseconds(10);\n\n        [Fact]\n        public void Constructor_Initializes()\n        {\n            // Arrange\n            AsyncCallback callback = new AsyncCallback(_ => { });\n            object state = new object();\n\n            // Act\n            MockAsyncResult mockAsyncResult = new MockAsyncResult(callback, state);\n\n            // Assert\n            Assert.True(mockAsyncResult.HasCallback);\n            Assert.False(mockAsyncResult.IsCompleted);\n            Assert.False(mockAsyncResult.CompletedSynchronously);\n            Assert.Same(state, mockAsyncResult.AsyncState);\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void Complete_SetsCompletedSynchronously(bool completedSynchronously)\n        {\n            // Arrange\n            MockAsyncResult mockAsyncResult = new MockAsyncResult(null, null);\n\n            // Act\n            mockAsyncResult.Complete(completedSynchronously);\n\n            // Assert\n            Assert.Equal(completedSynchronously, mockAsyncResult.CompletedSynchronously);\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void Complete_SetsIsCompleted(bool completedSynchronously)\n        {\n            // Arrange\n            MockAsyncResult mockAsyncResult = new MockAsyncResult(null, null);\n\n            // Act\n            mockAsyncResult.Complete(completedSynchronously);\n\n            // Assert\n            Assert.True(mockAsyncResult.IsCompleted);\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void Complete_CallsCallback(bool completedSynchronously)\n        {\n            // Arrange\n            MockAsyncCallback mockCallback = new MockAsyncCallback(false);\n            MockAsyncResult mockAsyncResult = new MockAsyncResult(mockCallback.Callback, null);\n\n            // Act\n            mockAsyncResult.Complete(completedSynchronously);\n\n            // Assert\n            Assert.True(mockCallback.WasInvoked);\n            Assert.Same(mockAsyncResult, mockCallback.AsyncResult);\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void Complete_ThrowsOnMultipleCompletes(bool completedSynchronously)\n        {\n            // Arrange\n            MockAsyncResult mockAsyncResult = new MockAsyncResult(null, null);\n\n            // Act\n            mockAsyncResult.Complete(completedSynchronously);\n\n            // Assert\n            Assert.Throws<InvalidOperationException>(() => mockAsyncResult.Complete(completedSynchronously));\n        }\n\n        [Fact]\n        public void Complete_ThrowsIfCallbackThrows()\n        {\n            // Arrange\n            MockAsyncCallback mockCallback = new MockAsyncCallback(true);\n            MockAsyncResult mockAsyncResult = new MockAsyncResult(mockCallback.Callback, null);\n\n            // Act/Assert\n            Assert.Throws<InvalidOperationException>(() => mockAsyncResult.Complete(false));\n        }\n\n        [Fact]\n        public void End_ThrowsOnNullAsyncResult()\n        {\n            Assert.ThrowsArgumentNull(() => MockAsyncResult.End<MockAsyncResult>(null), \"result\");\n        }\n\n        [Fact]\n        public void End_ThrowsOnInvalidAsyncResult()\n        {\n            Mock<IAsyncResult> mockIAsyncResult = new Mock<IAsyncResult>();\n            Assert.ThrowsArgument(() => MockAsyncResult.End<MockAsyncResult>(mockIAsyncResult.Object), \"result\");\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void End_ThrowsIfCalledTwiceOnSameAsyncResult(bool completedSynchronously)\n        {\n            // Arrange\n            MockAsyncCallback mockCallback = new MockAsyncCallback(false);\n            MockAsyncResult mockAsyncResult = new MockAsyncResult(mockCallback.Callback, null);\n            mockAsyncResult.Complete(completedSynchronously);\n\n            // Act\n            MockAsyncResult.End<MockAsyncResult>(mockAsyncResult);\n\n            // Act\n            Assert.Throws<InvalidOperationException>(() => MockAsyncResult.End<MockAsyncResult>(mockAsyncResult));\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void End_ThrowsIfCompletedWithException(bool completedSynchronously)\n        {\n            // Arrange\n            MockAsyncCallback mockCallback = new MockAsyncCallback(false);\n            MockAsyncResult mockAsyncResult = new MockAsyncResult(mockCallback.Callback, null);\n            ApplicationException applicationException = new ApplicationException(\"Complete failed!\");\n            mockAsyncResult.Complete(completedSynchronously, applicationException);\n\n            // Act/Assert\n            Assert.Throws<ApplicationException>(() => MockAsyncResult.End<MockAsyncResult>(mockAsyncResult));\n        }\n\n        internal class MockAsyncResult : AsyncResult\n        {\n            public MockAsyncResult(AsyncCallback callback, object state)\n                : base(callback, state)\n            {\n            }\n\n            public new void Complete(bool completedSynchronously)\n            {\n                base.Complete(completedSynchronously);\n            }\n\n            public new void Complete(bool completedSynchronously, Exception e)\n            {\n                base.Complete(completedSynchronously, e);\n            }\n\n            public static new TAsyncResult End<TAsyncResult>(IAsyncResult result) where TAsyncResult : AsyncResult\n            {\n                return AsyncResult.End<TAsyncResult>(result);\n            }\n        }\n\n        public class MockAsyncCallback\n        {\n            private bool _throwInCallback;\n\n            public MockAsyncCallback(bool throwInCallback)\n            {\n                _throwInCallback = throwInCallback;\n            }\n\n            public bool WasInvoked { get; private set; }\n\n            public IAsyncResult AsyncResult { get; private set; }\n\n            public Exception CallbackException { get; private set; }\n\n            public void Callback(IAsyncResult result)\n            {\n                WasInvoked = true;\n                AsyncResult = result;\n                if (_throwInCallback)\n                {\n                    CallbackException = new Exception(\"Callback exception\");\n                    throw CallbackException;\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Internal/ByteRangeStreamTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Net.Http.Internal\n{\n    public class ByteRangeStreamTest\n    {\n        // from, to, expectedText\n        public static TheoryDataSet<long?, long?, string> CopyBoundsData\n        {\n            get\n            {\n                return new TheoryDataSet<long?, long?, string>\n                {\n                    { null, 23, \"This is the whole text.\" },\n                    { 0, null, \"This is the whole text.\" },\n                    { 0, 22, \"This is the whole text.\" },\n                    { 0, 3, \"This\" },\n                    { 12, 16, \"whole\" },\n                    { null, 5, \"text.\" },\n                    { 18, null, \"text.\" },\n                    { 18, 22, \"text.\" },\n                };\n            }\n        }\n\n        // from, to, innerLength, effectiveLength\n        public static TheoryDataSet<int, int, int, int> ReadBoundsData\n        {\n            get\n            {\n                return new TheoryDataSet<int, int, int, int>\n                {\n                    { 0, 9, 20, 10 },\n                    { 8, 8, 10, 1 },\n                    { 0, 19, 20, 20 },\n                    { 0, 29, 40, 30 },\n                    { 0, 29, 20, 20 },\n                    { 19, 29, 20, 1 },\n                };\n            }\n        }\n\n        // from, to, innerLength, effectiveLength for reads limited by byte[] size.\n        public static TheoryDataSet<int, int, int, int> ReadBoundsDataWithLimit\n        {\n            get\n            {\n                return new TheoryDataSet<int, int, int, int>\n                {\n                    { 0, 9, 20, 10 },\n                    { 8, 8, 10, 1 },\n                    { 0, 19, 20, 20 },\n                    { 0, 29, 40, 25 },\n                    { 0, 29, 20, 20 },\n                    { 19, 29, 20, 1 },\n                };\n            }\n        }\n\n        [Fact]\n        public void Ctor_ThrowsOnNullInnerStream()\n        {\n            var range = new RangeItemHeaderValue(0, 10);\n            Assert.ThrowsArgumentNull(() => new ByteRangeStream(innerStream: null, range: range), \"innerStream\");\n        }\n\n        [Fact]\n        public void Ctor_ThrowsOnNullRange()\n        {\n            Assert.ThrowsArgumentNull(() => new ByteRangeStream(innerStream: Stream.Null, range: null), \"range\");\n        }\n\n        [Fact]\n        public void Ctor_ThrowsIfCantSeekInnerStream()\n        {\n            // Arrange\n            var mockInnerStream = new Mock<Stream>();\n            mockInnerStream.Setup(s => s.CanSeek).Returns(false);\n            var range = new RangeItemHeaderValue(0, 10);\n\n            // Act/Assert\n            Assert.ThrowsArgument(() => new ByteRangeStream(mockInnerStream.Object, range), \"innerStream\");\n        }\n\n        [Fact]\n        public void Ctor_ThrowsIfLowerRangeExceedsInnerStream()\n        {\n            // Arrange\n            var mockInnerStream = new Mock<Stream>();\n            mockInnerStream.Setup(s => s.CanSeek).Returns(true);\n            mockInnerStream.Setup(s => s.Length).Returns(5);\n            var range = new RangeItemHeaderValue(10, 20);\n\n            // Act/Assert\n            Assert.ThrowsArgumentOutOfRange(() => new ByteRangeStream(mockInnerStream.Object, range), \"range\",\n                \"The 'From' value of the range must be less than or equal to 5.\", false, 10);\n        }\n\n        [Fact]\n        public void Ctor_SetsContentRange()\n        {\n            // Arrange\n            var expectedContentRange = new ContentRangeHeaderValue(5, 9, 20);\n            var mockInnerStream = new Mock<Stream>();\n            mockInnerStream.Setup(s => s.CanSeek).Returns(true);\n            mockInnerStream.Setup(s => s.Length).Returns(20);\n            var range = new RangeItemHeaderValue(5, 9);\n\n            // Act\n            using (var rangeStream = new ByteRangeStream(mockInnerStream.Object, range))\n            {\n                // Assert\n                Assert.Equal(expectedContentRange, rangeStream.ContentRange);\n            }\n        }\n\n        [Theory]\n        [InlineData(0)]\n        [InlineData(-1)]\n        public void Ctor_ThrowsIfInnerStreamLengthIsLessThanOne(int innerLength)\n        {\n            // Arrange\n            var mockInnerStream = new Mock<Stream>();\n            mockInnerStream.Setup(s => s.CanSeek).Returns(true);\n            mockInnerStream.Setup(s => s.Length).Returns(innerLength);\n            var range = new RangeItemHeaderValue(null, 0);\n\n            // Act/Assert\n            Assert.ThrowsArgumentOutOfRange(\n                () => new ByteRangeStream(mockInnerStream.Object, range),\n                \"innerStream\",\n                \"The stream over which 'ByteRangeStream' provides a range view must have a length greater than or \" +\n                \"equal to 1.\",\n                false,\n                innerLength);\n        }\n\n        [Theory]\n        [PropertyData(\"ReadBoundsData\")]\n        public void Ctor_SetsLength(int from, int to, int innerLength, int expectedLength)\n        {\n            // Arrange\n            var mockInnerStream = new Mock<Stream>();\n            mockInnerStream.Setup(s => s.CanSeek).Returns(true);\n            mockInnerStream.Setup(s => s.Length).Returns(innerLength);\n            var range = new RangeItemHeaderValue(from, to);\n\n            // Act\n            using (var rangeStream = new ByteRangeStream(mockInnerStream.Object, range))\n            {\n                // Assert\n                Assert.Equal(expectedLength, rangeStream.Length);\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"CopyBoundsData\")]\n        public async Task CopyTo_ReadsSpecifiedRange(long? from, long? to, string expectedText)\n        {\n            // Arrange\n            var originalText = \"This is the whole text.\";\n            var range = new RangeItemHeaderValue(from, to);\n\n            using (var innerStream = new MemoryStream())\n            using (var writer = new StreamWriter(innerStream))\n            using (var targetStream = new MemoryStream())\n            using (var reader = new StreamReader(targetStream))\n            {\n                await writer.WriteAsync(originalText);\n                await writer.FlushAsync();\n\n                // Act\n                using (var rangeStream = new ByteRangeStream(innerStream, range))\n                {\n                    rangeStream.CopyTo(targetStream);\n                }\n\n                // Assert\n                targetStream.Position = 0L;\n                var text = await reader.ReadToEndAsync();\n                Assert.Equal(expectedText, text);\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"CopyBoundsData\")]\n        public async Task CopyToAsync_ReadsSpecifiedRange(long? from, long? to, string expectedText)\n        {\n            // Arrange\n            var originalText = \"This is the whole text.\";\n            var range = new RangeItemHeaderValue(from, to);\n\n            using (var innerStream = new MemoryStream())\n            using (var writer = new StreamWriter(innerStream))\n            using (var targetStream = new MemoryStream())\n            using (var reader = new StreamReader(targetStream))\n            {\n                await writer.WriteAsync(originalText);\n                await writer.FlushAsync();\n\n                // Act\n                using (var rangeStream = new ByteRangeStream(innerStream, range))\n                {\n                    await rangeStream.CopyToAsync(targetStream);\n                }\n\n                // Assert\n                targetStream.Position = 0L;\n                var text = await reader.ReadToEndAsync();\n                Assert.Equal(expectedText, text);\n            }\n        }\n\n        [Fact]\n        public void Position_ThrowsOnNegativeValue()\n        {\n            // Arrange\n            var mockInnerStream = new Mock<Stream>();\n            mockInnerStream.Setup(s => s.CanSeek).Returns(true);\n            mockInnerStream.Setup(s => s.Length).Returns(10L);\n            var range = new RangeItemHeaderValue(0, 25L);\n\n            using (var rangeStream = new ByteRangeStream(mockInnerStream.Object, range))\n            {\n                // Act & Assert\n                Assert.Throws<ArgumentOutOfRangeException>(() => rangeStream.Position = -1L);\n            }\n        }\n\n        [Theory]\n        [InlineData(null)]\n        [InlineData(0L)]\n        [InlineData(7L)]\n        [InlineData(9L)]\n        public void Position_ReturnsZeroInitially(long? from)\n        {\n            // Arrange\n            var mockInnerStream = new Mock<Stream>();\n            mockInnerStream.Setup(s => s.CanSeek).Returns(true);\n            mockInnerStream.Setup(s => s.Length).Returns(10L);\n            var range = new RangeItemHeaderValue(from, 25L);\n\n            using (var rangeStream = new ByteRangeStream(mockInnerStream.Object, range))\n            {\n                // Act\n                var position = rangeStream.Position;\n\n                // Assert\n                Assert.Equal(0L, position);\n            }\n        }\n\n        [Fact]\n        public void Position_CanBeSetAfterLength()\n        {\n            // Arrange\n            var expectedPosition = 300L;\n            var mockInnerStream = new Mock<Stream>();\n            mockInnerStream.Setup(s => s.CanSeek).Returns(true);\n            mockInnerStream.Setup(s => s.Length).Returns(10L);\n            var range = new RangeItemHeaderValue(0L, 10L);\n\n            using (var rangeStream = new ByteRangeStream(mockInnerStream.Object, range))\n            {\n                // Act\n                rangeStream.Position = expectedPosition;\n\n                // Assert\n                Assert.Equal(expectedPosition, rangeStream.Position);\n            }\n        }\n\n        [Fact]\n        public async Task Position_PositionsNextRead()\n        {\n            // Arrange\n            var originalText = \"890123456789\";\n            var range = new RangeItemHeaderValue(2L, null);\n\n            using (var innerStream = new MemoryStream())\n            using (var writer = new StreamWriter(innerStream))\n            {\n                await writer.WriteAsync(originalText);\n                await writer.FlushAsync();\n\n                using (var rangeStream = new ByteRangeStream(innerStream, range))\n                {\n                    // Act\n                    rangeStream.Position = 5L;\n\n                    // Assert\n                    var read = rangeStream.ReadByte();\n                    Assert.Equal('5', (char)read);\n                }\n            }\n        }\n\n#if !Testing_NetStandard1_3 // BeginX and EndX are not supported on Streams in netstandard1.3\n        [Theory]\n        [PropertyData(\"ReadBoundsDataWithLimit\")]\n        public void BeginRead_ReadsEffectiveLengthBytes(int from, int to, int innerLength, int effectiveLength)\n        {\n            // Arrange\n            var mockInnerStream = new Mock<Stream>();\n            mockInnerStream.Setup(s => s.CanSeek).Returns(true);\n            mockInnerStream.Setup(s => s.Length).Returns(innerLength);\n            var range = new RangeItemHeaderValue(from, to);\n            var data = new byte[25];\n            var offset = 5;\n            var callback = new AsyncCallback(_ => { });\n            var userState = new object();\n\n            using (var rangeStream = new ByteRangeStream(mockInnerStream.Object, range))\n            {\n                // Act\n                var result = rangeStream.BeginRead(data, offset, data.Length, callback, userState);\n                rangeStream.EndRead(result);\n\n                // Assert\n                mockInnerStream.Verify(\n                    s => s.BeginRead(data, offset, effectiveLength, callback, userState),\n                    Times.Once());\n                Assert.Equal(effectiveLength, rangeStream.Position);\n            }\n        }\n#endif\n\n        [Fact]\n        public async Task BeginRead_CanReadAfterLength()\n        {\n            // Arrange\n            var originalText = \"This is the whole text.\";\n            var range = new RangeItemHeaderValue(0L, null);\n            var data = new byte[25];\n            var callback = new AsyncCallback(_ => { });\n            var userState = new object();\n\n            using (var innerStream = new MemoryStream())\n            using (var writer = new StreamWriter(innerStream))\n            {\n                await writer.WriteAsync(originalText);\n                await writer.FlushAsync();\n\n                using (var rangeStream = new ByteRangeStream(innerStream, range))\n                {\n                    rangeStream.Position = 50L;\n\n                    // Act\n                    var result = rangeStream.BeginRead(data, 0, data.Length, callback, userState);\n                    var read = rangeStream.EndRead(result);\n\n                    // Assert\n                    Assert.Equal(0, read);\n                }\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"ReadBoundsDataWithLimit\")]\n        public void Read_ReadsEffectiveLengthBytes(int from, int to, int innerLength, int effectiveLength)\n        {\n            // Arrange\n            var mockInnerStream = new Mock<Stream>();\n            mockInnerStream.Setup(s => s.CanSeek).Returns(true);\n            mockInnerStream.Setup(s => s.Length).Returns(innerLength);\n            var range = new RangeItemHeaderValue(from, to);\n            var data = new byte[25];\n            var offset = 5;\n\n            using (var rangeStream = new ByteRangeStream(mockInnerStream.Object, range))\n            {\n                // Act\n                rangeStream.Read(data, offset, data.Length);\n\n                // Assert\n                mockInnerStream.Verify(s => s.Read(data, offset, effectiveLength), Times.Once());\n                Assert.Equal(effectiveLength, rangeStream.Position);\n            }\n        }\n\n        [Fact]\n        public async Task Read_CanReadAfterLength()\n        {\n            // Arrange\n            var originalText = \"This is the whole text.\";\n            var range = new RangeItemHeaderValue(0L, null);\n            var data = new byte[25];\n\n            using (var innerStream = new MemoryStream())\n            using (var writer = new StreamWriter(innerStream))\n            {\n                await writer.WriteAsync(originalText);\n                await writer.FlushAsync();\n\n                using (var rangeStream = new ByteRangeStream(innerStream, range))\n                {\n                    rangeStream.Position = 50L;\n\n                    // Act\n                    var read = rangeStream.Read(data, 0, data.Length);\n\n                    // Assert\n                    Assert.Equal(0, read);\n                }\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"ReadBoundsDataWithLimit\")]\n        public async Task ReadAsync_ReadsEffectiveLengthBytes(int from, int to, int innerLength, int effectiveLength)\n        {\n            // Arrange\n            var mockInnerStream = new Mock<Stream>();\n            mockInnerStream.Setup(s => s.CanSeek).Returns(true);\n            mockInnerStream.Setup(s => s.Length).Returns(innerLength);\n            var range = new RangeItemHeaderValue(from, to);\n            var data = new byte[25];\n            var offset = 5;\n\n            using (var rangeStream = new ByteRangeStream(mockInnerStream.Object, range))\n            {\n                // Act\n                await rangeStream.ReadAsync(data, offset, data.Length);\n\n                // Assert\n                mockInnerStream.Verify(\n                    s => s.ReadAsync(data, offset, effectiveLength, CancellationToken.None),\n                    Times.Once());\n                Assert.Equal(effectiveLength, rangeStream.Position);\n            }\n        }\n\n        [Fact]\n        public async Task ReadAsync_CanReadAfterLength()\n        {\n            // Arrange\n            var originalText = \"This is the whole text.\";\n            var range = new RangeItemHeaderValue(0L, null);\n            var data = new byte[25];\n\n            using (var innerStream = new MemoryStream())\n            using (var writer = new StreamWriter(innerStream))\n            {\n                await writer.WriteAsync(originalText);\n                await writer.FlushAsync();\n\n                using (var rangeStream = new ByteRangeStream(innerStream, range))\n                {\n                    rangeStream.Position = 50L;\n\n                    // Act\n                    var read = await rangeStream.ReadAsync(data, 0, data.Length);\n\n                    // Assert\n                    Assert.Equal(0, read);\n                }\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"ReadBoundsData\")]\n        public void ReadByte_ReadsEffectiveLengthTimes(int from, int to, int innerLength, int effectiveLength)\n        {\n            // Arrange\n            var mockInnerStream = new Mock<Stream>();\n            mockInnerStream.Setup(s => s.CanSeek).Returns(true);\n            mockInnerStream.Setup(s => s.Length).Returns(innerLength);\n            var range = new RangeItemHeaderValue(from, to);\n            var counter = 0;\n\n            using (var rangeStream = new ByteRangeStream(mockInnerStream.Object, range))\n            {\n                // Act\n                while (rangeStream.ReadByte() != -1)\n                {\n                    counter++;\n                }\n\n                // Assert\n                mockInnerStream.Verify(s => s.ReadByte(), Times.Exactly(effectiveLength));\n                Assert.Equal(effectiveLength, counter);\n                Assert.Equal(effectiveLength, rangeStream.Position);\n            }\n        }\n\n        [Fact]\n        public async Task ReadByte_CanReadAfterLength()\n        {\n            // Arrange\n            var originalText = \"This is the whole text.\";\n            var range = new RangeItemHeaderValue(0L, null);\n\n            using (var innerStream = new MemoryStream())\n            using (var writer = new StreamWriter(innerStream))\n            {\n                await writer.WriteAsync(originalText);\n                await writer.FlushAsync();\n\n                using (var rangeStream = new ByteRangeStream(innerStream, range))\n                {\n                    rangeStream.Position = 50L;\n\n                    // Act\n                    var read = rangeStream.ReadByte();\n\n                    // Assert\n                    Assert.Equal(-1, read);\n                }\n            }\n        }\n\n        [Theory]\n        [InlineData(-1, SeekOrigin.Begin)]\n        [InlineData(-1, SeekOrigin.Current)]\n        [InlineData(-11, SeekOrigin.End)]\n        public void Seek_ThrowsIfBeforeOrigin(int offset, SeekOrigin origin)\n        {\n            // Arrange\n            var mockInnerStream = new Mock<Stream>();\n            mockInnerStream.Setup(s => s.CanSeek).Returns(true);\n            mockInnerStream.Setup(s => s.Length).Returns(10L);\n            var range = new RangeItemHeaderValue(0, 25L);\n\n            using (var rangeStream = new ByteRangeStream(mockInnerStream.Object, range))\n            {\n                // Act & Assert\n                Assert.Throws<IOException>(() => rangeStream.Seek(offset, origin));\n            }\n        }\n\n        [Theory]\n        [InlineData(25, SeekOrigin.Begin)]\n        [InlineData(25, SeekOrigin.Current)]\n        [InlineData(15, SeekOrigin.End)]\n        public void Seek_CanMoveAfterLength(int offset, SeekOrigin origin)\n        {\n            // Arrange\n            var expectedPosition = 25L;\n            var mockInnerStream = new Mock<Stream>();\n            mockInnerStream.Setup(s => s.CanSeek).Returns(true);\n            mockInnerStream.Setup(s => s.Length).Returns(10L);\n            var range = new RangeItemHeaderValue(0L, 10L);\n\n            using (var rangeStream = new ByteRangeStream(mockInnerStream.Object, range))\n            {\n                // Act\n                var newPosition = rangeStream.Seek(offset, origin);\n\n                // Assert\n                Assert.Equal(expectedPosition, newPosition);\n                Assert.Equal(expectedPosition, rangeStream.Position);\n            }\n        }\n\n        [Theory]\n        [InlineData(5, SeekOrigin.Begin)]\n        [InlineData(5, SeekOrigin.Current)]\n        [InlineData(-5, SeekOrigin.End)]\n        public async Task Seek_PositionsNextRead(int offset, SeekOrigin origin)\n        {\n            // Arrange\n            var originalText = \"890123456789\";\n            var range = new RangeItemHeaderValue(2L, null);\n\n            using (var innerStream = new MemoryStream())\n            using (var writer = new StreamWriter(innerStream))\n            {\n                await writer.WriteAsync(originalText);\n                await writer.FlushAsync();\n\n                using (var rangeStream = new ByteRangeStream(innerStream, range))\n                {\n                    // Act\n                    rangeStream.Seek(offset, origin);\n\n                    // Assert\n                    var read = rangeStream.ReadByte();\n                    Assert.Equal('5', (char)read);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Internal/ConcurrentDictionaryTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing Microsoft.TestCommon;\n\nnamespace System.Collections.Concurrent\n{\n    public class ConcurrentDictionaryTests\n    {\n        [Fact]\n        public void ContainsKey_ReturnsFalseWhenKeyIsNotPresent()\n        {\n            // Arrange\n            ConcurrentDictionary<int, int> dictionary = new ConcurrentDictionary<int, int>();\n\n            // Act & Assert\n            Assert.False(dictionary.ContainsKey(3));\n        }\n\n        [Fact]\n        public void ContainsKey_ReturnsTrueWhenKeyIsPresent()\n        {\n            // Arrange\n            ConcurrentDictionary<int, int> dictionary = new ConcurrentDictionary<int, int>();\n\n            // Act\n            dictionary.TryAdd(1, 2);\n\n            // Assert\n            Assert.True(dictionary.ContainsKey(1));\n        }\n\n        [Fact]\n        public void GetOrAdd_AddsNewValueWhenKeyIsNotPresent()\n        {\n            // Arrange\n            ConcurrentDictionary<int, int> dictionary = new ConcurrentDictionary<int, int>();\n\n            // Act\n            int returnedValue = dictionary.GetOrAdd(1, (key) => { return ++key; });\n\n            // Assert\n            Assert.Equal(2, returnedValue);\n        }\n\n        [Fact]\n        public void GetOrAdd_ReturnsExistingValueWhenKeyIsPresent()\n        {\n            // Arrange\n            ConcurrentDictionary<int, int> dictionary = new ConcurrentDictionary<int, int>();\n            dictionary.TryAdd(1, -1);\n\n            // Act\n            int returnedValue = dictionary.GetOrAdd(1, (key) => { return ++key; });\n\n            // Assert\n            Assert.Equal(-1, returnedValue);\n        }\n\n        [Fact]\n        public void TryAdd_ReturnsTrueWhenKeyIsNotPresent()\n        {\n            // Arrange\n            ConcurrentDictionary<int, int> dictionary = new ConcurrentDictionary<int, int>();\n\n            // Act\n            bool result = dictionary.TryAdd(1, 2);\n\n            // Assert\n            Assert.True(result);\n            Assert.True(dictionary.ContainsKey(1));\n        }\n\n        [Fact]\n        public void TryAdd_ReturnsFalseWhenKeyIsPresent()\n        {\n            // Arrange\n            ConcurrentDictionary<int, int> dictionary = new ConcurrentDictionary<int, int>();\n            dictionary.TryAdd(1, 2);\n\n            // Act\n            bool result = dictionary.TryAdd(1, 2);\n\n            // Assert\n            Assert.False(result);\n        }\n\n        [Fact]\n        public void AddOrUpdate_AddsValueWhenKeyIsNotPresent()\n        {\n            // Arrange\n            ConcurrentDictionary<int, int> dictionary = new ConcurrentDictionary<int, int>();\n\n            // Act\n            int result = dictionary.AddOrUpdate(1, 2, (key, current) => { return ++current; });\n\n            // Assert\n            Assert.Equal(2, result);\n            Assert.Equal(2, dictionary.GetOrAdd(1, (key) => { return -1; }));\n        }\n\n        [Fact]\n        public void AddOrUpdate_UpdatesValueWhenKeyIsPresent()\n        {\n            // Arrange\n            ConcurrentDictionary<int, int> dictionary = new ConcurrentDictionary<int, int>();\n            dictionary.TryAdd(1, 2);\n\n            // Act\n            int result = dictionary.AddOrUpdate(1, 2, (key, current) => { return ++current; });\n\n            // Assert\n            Assert.Equal(3, result);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Internal/DelegatingStreamTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Net.Http.Mocks;\nusing System.Threading;\nusing Microsoft.TestCommon;\nusing Moq;\nusing Moq.Protected;\n\nnamespace System.Net.Http.Internal\n{\n    public class DelegatingStreamTest\n    {\n        [Fact]\n        public void DelegatingStream_CtorThrowsOnNull()\n        {\n            Assert.ThrowsArgumentNull(() => new MockDelegatingStream(null), \"innerStream\");\n        }\n\n        [Fact]\n        public void DelegatingStream_CanRead()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>();\n            MockDelegatingStream mockStream = new MockDelegatingStream(mockInnerStream.Object);\n\n            // Act\n            bool canRead = mockStream.CanRead;\n\n            // Assert\n            mockInnerStream.Verify(s => s.CanRead, Times.Once());\n        }\n\n        [Fact]\n        public void DelegatingStream_CanSeek()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>();\n            MockDelegatingStream mockStream = new MockDelegatingStream(mockInnerStream.Object);\n\n            // Act\n            bool canSeek = mockStream.CanSeek;\n\n            // Assert\n            mockInnerStream.Verify(s => s.CanSeek, Times.Once());\n        }\n\n        [Fact]\n        public void DelegatingStream_CanWrite()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>();\n            MockDelegatingStream mockStream = new MockDelegatingStream(mockInnerStream.Object);\n\n            // Act\n            bool canWrite = mockStream.CanWrite;\n\n            // Assert\n            mockInnerStream.Verify(s => s.CanWrite, Times.Once());\n        }\n\n        [Fact]\n        public void DelegatingStream_Length()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>();\n            MockDelegatingStream mockStream = new MockDelegatingStream(mockInnerStream.Object);\n\n            // Act\n            long length = mockStream.Length;\n\n            // Assert\n            mockInnerStream.Verify(s => s.Length, Times.Once());\n        }\n\n        [Fact]\n        public void DelegatingStream_Position()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>();\n            MockDelegatingStream mockStream = new MockDelegatingStream(mockInnerStream.Object);\n\n            // Act\n            long position = mockStream.Position;\n\n            // Assert\n            mockInnerStream.Verify(s => s.Position, Times.Once());\n        }\n\n        [Fact]\n        public void DelegatingStream_ReadTimeout()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>();\n            MockDelegatingStream mockStream = new MockDelegatingStream(mockInnerStream.Object);\n\n            // Act\n            int readTimeout = mockStream.ReadTimeout;\n\n            // Assert\n            mockInnerStream.Verify(s => s.ReadTimeout, Times.Once());\n        }\n\n        [Fact]\n        public void DelegatingStream_CanTimeout()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>();\n            MockDelegatingStream mockStream = new MockDelegatingStream(mockInnerStream.Object);\n\n            // Act\n            bool canTimeout = mockStream.CanTimeout;\n\n            // Assert\n            mockInnerStream.Verify(s => s.CanTimeout, Times.Once());\n        }\n\n        [Fact]\n        public void DelegatingStream_WriteTimeout()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>();\n            MockDelegatingStream mockStream = new MockDelegatingStream(mockInnerStream.Object);\n\n            // Act\n            int writeTimeout = mockStream.WriteTimeout;\n\n            // Assert\n            mockInnerStream.Verify(s => s.WriteTimeout, Times.Once());\n        }\n\n        [Fact]\n        public void DelegatingStream_Dispose()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>() { CallBase = true };\n            MockDelegatingStream mockStream = new MockDelegatingStream(mockInnerStream.Object);\n\n            // Act\n            mockStream.Dispose();\n\n            // Assert\n            mockInnerStream.Protected().Verify(\"Dispose\", Times.Once(), exactParameterMatch: true, args: true);\n            mockInnerStream.Verify(s => s.Close(), Times.Once());\n        }\n\n        [Fact]\n        public void DelegatingStream_Close()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>() { CallBase = true };\n            MockDelegatingStream mockStream = new MockDelegatingStream(mockInnerStream.Object);\n\n            // Act\n            mockStream.Close();\n\n            // Assert\n            mockInnerStream.Protected().Verify(\"Dispose\", Times.Once(), exactParameterMatch: true, args: true);\n            mockInnerStream.Verify(s => s.Close(), Times.Once());\n        }\n\n        [Fact]\n        public void DelegatingStream_Seek()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>();\n            MockDelegatingStream mockStream = new MockDelegatingStream(mockInnerStream.Object);\n            long offset = 1;\n            SeekOrigin origin = SeekOrigin.End;\n\n            // Act\n            long seek = mockStream.Seek(offset, origin);\n\n            // Assert\n            mockInnerStream.Verify(s => s.Seek(offset, origin), Times.Once());\n        }\n\n        [Fact]\n        public void DelegatingStream_Read()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>();\n            MockDelegatingStream mockStream = new MockDelegatingStream(mockInnerStream.Object);\n            byte[] buffer = new byte[2];\n            int offset = 1;\n            int count = 1;\n\n            // Act\n            mockStream.Read(buffer, offset, count);\n\n            // Assert\n            mockInnerStream.Verify(s => s.Read(buffer, offset, count), Times.Once());\n        }\n\n#if !Testing_NetStandard1_3 // BeginX and EndX not supported on Streams in netstandard1.3\n        [Fact]\n        public void DelegatingStream_BeginRead()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>();\n            MockDelegatingStream mockStream = new MockDelegatingStream(mockInnerStream.Object);\n            byte[] buffer = new byte[2];\n            int offset = 1;\n            int count = 1;\n            AsyncCallback callback = new AsyncCallback((asyncResult) => { });\n            object state = new object();\n\n            // Act\n            mockStream.BeginRead(buffer, offset, count, callback, state);\n\n            // Assert\n            mockInnerStream.Verify(s => s.BeginRead(buffer, offset, count, callback, state), Times.Once());\n        }\n\n        [Fact]\n        public void DelegatingStream_EndRead()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>();\n            MockDelegatingStream mockStream = new MockDelegatingStream(mockInnerStream.Object);\n            Mock<IAsyncResult> mockIAsyncResult = new Mock<IAsyncResult>();\n\n            // Act\n            int endRead = mockStream.EndRead(mockIAsyncResult.Object);\n\n            // Assert\n            mockInnerStream.Verify(s => s.EndRead(mockIAsyncResult.Object), Times.Once());\n        }\n#endif\n\n        [Fact]\n        public void DelegatingStream_ReadAsyc()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>();\n            MockDelegatingStream mockStream = new MockDelegatingStream(mockInnerStream.Object);\n            byte[] buffer = new byte[2];\n            int offset = 1;\n            int count = 1;\n\n            // Act\n            mockStream.ReadAsync(buffer, offset, count, CancellationToken.None);\n\n            // Assert\n            mockInnerStream.Verify(s => s.ReadAsync(buffer, offset, count, CancellationToken.None), Times.Once());\n        }\n\n        [Fact]\n        public void DelegatingStream_ReadByte()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>();\n            MockDelegatingStream mockStream = new MockDelegatingStream(mockInnerStream.Object);\n\n            // Act\n            int readByte = mockStream.ReadByte();\n\n            // Assert\n            mockInnerStream.Verify(s => s.ReadByte(), Times.Once());\n        }\n\n        [Fact]\n        public void DelegatingStream_Flush()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>();\n            MockDelegatingStream mockStream = new MockDelegatingStream(mockInnerStream.Object);\n\n            // Act\n            mockStream.Flush();\n\n            // Assert\n            mockInnerStream.Verify(s => s.Flush(), Times.Once());\n        }\n\n        [Fact]\n        public void DelegatingStream_SetLength()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>();\n            MockDelegatingStream mockStream = new MockDelegatingStream(mockInnerStream.Object);\n\n            // Act\n            mockStream.SetLength(10L);\n\n            // Assert\n            mockInnerStream.Verify(s => s.SetLength(10L), Times.Once());\n        }\n\n        [Fact]\n        public void DelegatingStream_Write()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>();\n            MockDelegatingStream mockStream = new MockDelegatingStream(mockInnerStream.Object);\n            byte[] buffer = new byte[2];\n            int offset = 1;\n            int count = 1;\n\n            // Act\n            mockStream.Write(buffer, offset, count);\n\n            // Assert\n            mockInnerStream.Verify(s => s.Write(buffer, offset, count), Times.Once());\n        }\n\n#if !Testing_NetStandard1_3 // BeginX and EndX not supported on Streams in netstandard1.3\n        [Fact]\n        public void DelegatingStream_BeginWrite()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>();\n            MockDelegatingStream mockStream = new MockDelegatingStream(mockInnerStream.Object);\n            byte[] buffer = new byte[2];\n            int offset = 1;\n            int count = 1;\n            AsyncCallback callback = new AsyncCallback((asyncResult) => { });\n            object state = new object();\n\n            // Act\n            mockStream.BeginWrite(buffer, offset, count, callback, state);\n\n            // Assert\n            mockInnerStream.Verify(s => s.BeginWrite(buffer, offset, count, callback, state), Times.Once());\n        }\n\n        [Fact]\n        public void DelegatingStream_EndWrite()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>();\n            MockDelegatingStream mockStream = new MockDelegatingStream(mockInnerStream.Object);\n            Mock<IAsyncResult> mockIAsyncResult = new Mock<IAsyncResult>();\n\n            // Act\n            mockStream.EndWrite(mockIAsyncResult.Object);\n\n            // Assert\n            mockInnerStream.Verify(s => s.EndWrite(mockIAsyncResult.Object), Times.Once());\n        }\n#endif\n\n        [Fact]\n        public void DelegatingStream_WriteAsync()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>();\n            MockDelegatingStream mockStream = new MockDelegatingStream(mockInnerStream.Object);\n            byte[] buffer = new byte[2];\n            int offset = 1;\n            int count = 1;\n\n            // Act\n            mockStream.WriteAsync(buffer, offset, count, CancellationToken.None);\n\n            // Assert\n            mockInnerStream.Verify(s => s.WriteAsync(buffer, offset, count, CancellationToken.None), Times.Once());\n        }\n\n        [Fact]\n        public void DelegatingStream_WriteByte()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>();\n            MockDelegatingStream mockStream = new MockDelegatingStream(mockInnerStream.Object);\n            byte data = new byte();\n\n            // Act\n            mockStream.WriteByte(data);\n\n            // Assert\n            mockInnerStream.Verify(s => s.WriteByte(data), Times.Once());\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Internal/HttpValueCollectionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Formatting.Internal;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Internal\n{\n    public class HttpValueCollectionTest\n    {\n#if !NETCOREAPP // Unused on .NET Core.\n        private static readonly int _maxCollectionKeys = 1000;\n#endif\n\n        private static HttpValueCollection CreateInstance()\n        {\n            return HttpValueCollection.Create();\n        }\n\n#if !NETCOREAPP // Unsupported on .NET Core.\n        private static void RunInIsolation(Action action)\n        {\n            AppDomainUtils.RunInSeparateAppDomain(action);\n        }\n#endif\n\n        public static TheoryDataSet<IEnumerable<KeyValuePair<string, string>>> KeyValuePairs\n        {\n            get\n            {\n                return new TheoryDataSet<IEnumerable<KeyValuePair<string, string>>>()\n                {\n                    new List<KeyValuePair<string, string>>\n                    {\n                        new KeyValuePair<string,string>(null, null),\n                        new KeyValuePair<string,string>(\"n0\", \"\"),\n                        new KeyValuePair<string,string>(\"n1\", \"v1\"),\n                        new KeyValuePair<string,string>(\"n@2\", \"v@2\"),\n                        new KeyValuePair<string,string>(\"n 3\", \"v 3\"),\n                        new KeyValuePair<string,string>(\"n+4\", \"v+4\"),\n                        new KeyValuePair<string,string>(\"n;5\", \"v;5\"),\n                        new KeyValuePair<string,string>(\"n=5\", \"v=5\"),\n                    }\n                };\n            }\n        }\n\n        internal class TestPropertyHolder\n        {\n            public static TheoryDataSet<HttpValueCollection, string> ToStringTestData\n            {\n                get\n                {\n                    TheoryDataSet<HttpValueCollection, string> dataSet = new TheoryDataSet<HttpValueCollection, string>();\n\n                    var hvc1 = CreateInstance();\n                    hvc1.Add(null, null);\n                    dataSet.Add(hvc1, \"\");\n\n                    var hvc2 = CreateInstance();\n                    hvc2.Add(\"name\", null);\n                    dataSet.Add(hvc2, \"name\");\n\n                    var hvc3 = CreateInstance();\n                    hvc3.Add(\"name\", \"\");\n                    dataSet.Add(hvc3, \"name\");\n\n                    var hvc4 = CreateInstance();\n                    hvc4.Add(\"na me\", \"\");\n                    dataSet.Add(hvc4, \"na+me\");\n\n                    string encoded5 = \"n%22%2C%3B%5Cn\";\n\n                    var hvc5 = CreateInstance();\n                    hvc5.Add(\"n\\\",;\\\\n\", \"\");\n                    dataSet.Add(hvc5, encoded5);\n\n                    var hvc6 = CreateInstance();\n                    hvc6.Add(\"\", \"v1\");\n                    hvc6.Add(\"\", \"v2\");\n                    hvc6.Add(\"\", \"v3\");\n                    hvc6.Add(\"\", \"v4\");\n                    dataSet.Add(hvc6, \"=v1&=v2&=v3&=v4\");\n\n                    var hvc7 = CreateInstance();\n                    hvc7.Add(\"n1\", \"v1\");\n                    hvc7.Add(\"n2\", \"v2\");\n                    hvc7.Add(\"n3\", \"v3\");\n                    hvc7.Add(\"n4\", \"v4\");\n                    dataSet.Add(hvc7, \"n1=v1&n2=v2&n3=v3&n4=v4\");\n\n                    string encoded8 = \"n%2C1=v%2C1&n%3B2=v%3B2\";\n\n                    var hvc8 = CreateInstance();\n                    hvc8.Add(\"n,1\", \"v,1\");\n                    hvc8.Add(\"n;2\", \"v;2\");\n                    dataSet.Add(hvc8, encoded8);\n\n                    string encoded9 = \"n1=%26&n2=%3B&n3=%26&n4=%2B&n5=%26&n6=%3D&n7=%26\";\n\n                    var hvc9 = CreateInstance();\n                    hvc9.Add(\"n1\", \"&\");\n                    hvc9.Add(\"n2\", \";\");\n                    hvc9.Add(\"n3\", \"&\");\n                    hvc9.Add(\"n4\", \"+\");\n                    hvc9.Add(\"n5\", \"&\");\n                    hvc9.Add(\"n6\", \"=\");\n                    hvc9.Add(\"n7\", \"&\");\n                    dataSet.Add(hvc9, encoded9);\n\n                    var hvc10 = CreateInstance();\n                    hvc10.Add(\"n1\", \"&\");\n                    hvc10.Add(\"n2\", null);\n                    hvc10.Add(\"n3\", \"null\");\n                    dataSet.Add(hvc10, \"n1=%26&n2&n3=null\");\n\n                    return dataSet;\n                }\n            }\n        }\n\n        [Fact]\n        public void Create_CreatesEmptyCollection()\n        {\n            var nvc = CreateInstance();\n\n            Assert.IsType<HttpValueCollection>(nvc);\n            Assert.Empty(nvc);\n        }\n\n#if !NETCOREAPP // Able to run on a separate AppDomain only on .NET Framework.\n        // This set of tests requires running on a separate appdomain so we don't\n        // touch the static property MediaTypeFormatter.MaxHttpCollectionKeys.\n        [Fact]\n        public void Create_CreateTooManyKeysThrows()\n        {\n            RunInIsolation(Create_CreateTooManyKeysThrowsPrivate);\n        }\n\n        private static void Create_CreateTooManyKeysThrowsPrivate()\n        {\n            // Arrange\n            MediaTypeFormatter.MaxHttpCollectionKeys = _maxCollectionKeys;\n\n            List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();\n\n            for (int i = 0; i < _maxCollectionKeys + 1; i++)\n            {\n                list.Add(new KeyValuePair<string, string>(i.ToString(), i.ToString()));\n            }\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(() => HttpValueCollection.Create(list), TooManyKeysError);\n        }\n\n        private static string TooManyKeysError\n        {\n            get\n            {\n                return \"The number of keys in a NameValueCollection has exceeded the limit of '\" + _maxCollectionKeys + \"'. You can adjust it by modifying the MaxHttpCollectionKeys property on the 'System.Net.Http.Formatting.MediaTypeFormatter' class.\";\n            }\n        }\n\n        [Fact]\n        public void Create_CreateDoesntThrowTooManyValues()\n        {\n            RunInIsolation(Create_CreateDoesntThrowTooManyValuesPrivate);\n        }\n\n        private static void Create_CreateDoesntThrowTooManyValuesPrivate()\n        {\n            // note this is static, but also the expected type in a real run.\n            MediaTypeFormatter.MaxHttpCollectionKeys = _maxCollectionKeys;\n\n            List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();\n\n            for (int i = 0; i < _maxCollectionKeys + 1; i++)\n            {\n                list.Add(new KeyValuePair<string, string>(\"key\", i.ToString()));\n            }\n\n            Assert.DoesNotThrow(() => HttpValueCollection.Create(list));\n        }\n\n        [Fact]\n        public void AddTooManyKeysThrows()\n        {\n            RunInIsolation(AddTooManyKeysThrowsPrivate);\n        }\n\n        private static void AddTooManyKeysThrowsPrivate()\n        {\n            // Note this is static, but also the expected type in a real run.\n            MediaTypeFormatter.MaxHttpCollectionKeys = _maxCollectionKeys;\n\n            HttpValueCollection collection = CreateInstance();\n            for (int i = 0; i < _maxCollectionKeys; i++)\n            {\n                collection.Add(i.ToString(), i.ToString());\n            }\n\n            // Act && Assert\n            Assert.Throws<InvalidOperationException>(\n                () => collection.Add(_maxCollectionKeys.ToString(), _maxCollectionKeys.ToString()),\n                TooManyKeysError);\n        }\n\n        [Fact]\n        public void AddDoesntThrowTooManyValues()\n        {\n            RunInIsolation(AddDoesntThrowTooManyValuesPrivate);\n        }\n\n        private static void AddDoesntThrowTooManyValuesPrivate()\n        {\n            // Note this is static, but also the expected type in a real run.\n            MediaTypeFormatter.MaxHttpCollectionKeys = _maxCollectionKeys;\n\n            HttpValueCollection collection = CreateInstance();\n\n            // Act && Assert\n            Assert.DoesNotThrow(() =>\n            {\n                for (int i = 0; i < 1001; i++)\n                {\n                    collection.Add(\"key\", i.ToString());\n                }\n            });\n        }\n#endif\n\n        [Theory]\n        [PropertyData(\"KeyValuePairs\")]\n        public void Create_InitializesCorrectly(IEnumerable<KeyValuePair<string, string>> input)\n        {\n            var nvc = HttpValueCollection.Create(input);\n\n            int count = input.Count();\n            Assert.IsType<HttpValueCollection>(nvc);\n            Assert.Equal(count, nvc.Count);\n\n            int index = 0;\n\n            foreach (KeyValuePair<string, string> kvp in input)\n            {\n                string expectedKey = kvp.Key ?? String.Empty;\n                string expectedValue = kvp.Value ?? String.Empty;\n\n                string actualKey = nvc.AllKeys[index];\n                string actualValue = nvc[index];\n                index++;\n\n                Assert.Equal(expectedKey, actualKey);\n                Assert.Equal(expectedValue, actualValue);\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"KeyValuePairs\")]\n        public void GetIsEquivalentToIndexerProperty(IEnumerable<KeyValuePair<string, string>> input)\n        {\n            var nvc = HttpValueCollection.Create(input);\n\n            int count = input.Count();\n            Assert.IsType<HttpValueCollection>(nvc);\n            Assert.Equal(count, nvc.Count);\n\n            foreach (KeyValuePair<string, string> kvp in input)\n            {\n                Assert.Equal(nvc[kvp.Key], nvc.Get(kvp.Key));\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"ToStringTestData\", PropertyType = typeof(TestPropertyHolder))]\n        internal void ToString_GeneratesCorrectOutput(HttpValueCollection input, string expectedOutput)\n        {\n            string actualOutput = input.ToString();\n            Assert.Equal(expectedOutput, actualOutput);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Internal/NonClosingDelegatingStreamTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Net.Http.Mocks;\nusing Microsoft.TestCommon;\nusing Moq;\nusing Moq.Protected;\n\nnamespace System.Net.Http.Internal\n{\n    public class NonClosingDelegatingStreamTest\n    {\n        [Fact]\n        public void NonClosingDelegatingStream_Dispose()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>() { CallBase = true };\n            MockNonClosingDelegatingStream mockStream = new MockNonClosingDelegatingStream(mockInnerStream.Object);\n\n            // Act\n            mockStream.Dispose();\n\n            // Assert\n            mockInnerStream.Protected().Verify(\"Dispose\", Times.Never(), exactParameterMatch: true, args: true);\n            mockInnerStream.Verify(s => s.Close(), Times.Never());\n        }\n\n        [Fact]\n        public void NonClosingDelegatingStream_Close()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>() { CallBase = true };\n            MockNonClosingDelegatingStream mockStream = new MockNonClosingDelegatingStream(mockInnerStream.Object);\n\n            // Act\n            mockStream.Close();\n\n            // Assert\n            mockInnerStream.Protected().Verify(\"Dispose\", Times.Never(), exactParameterMatch: true, args: true);\n            mockInnerStream.Verify(s => s.Close(), Times.Never());\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Internal/TranscodingStreamTests.cs",
    "content": "// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n\n// From https://github.com/dotnet/runtime/blob/88868b7a781f4e5b9037b8721f30440207a7aa42/src/libraries/System.Text.Encoding/tests/Encoding/TranscodingStreamTests.cs\n\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.IO;\nusing System.IO.Pipelines;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Moq;\n\n#nullable enable annotations\n\nnamespace System.Text.Tests\n{\n    public class TranscodingStreamTests\n    {\n        public static IEnumerable<object[]> ReadWriteTestBufferLengths\n        {\n            get\n            {\n                yield return new object[] { 1 };\n                yield return new object[] { 4 * 1024 };\n                yield return new object[] { 128 * 1024 };\n                yield return new object[] { 2 * 1024 * 1024 };\n            }\n        }\n\n#if Testing_NetStandard1_3 || Testing_NetStandard2_0 // .NET Framework implementation loses track of cancellation token.\n        [Fact]\n        public void AsyncMethods_ReturnCanceledTaskIfCancellationTokenTripped()\n        {\n            // Arrange\n\n            CancellationTokenSource cts = new();\n            CancellationToken expectedCancellationToken = cts.Token;\n            cts.Cancel();\n\n            var innerStreamMock = new Mock<Stream>(MockBehavior.Strict); // only CanRead/CanWrite should ever be invoked\n            innerStreamMock.Setup(o => o.CanRead).Returns(true);\n            innerStreamMock.Setup(o => o.CanWrite).Returns(true);\n\n            Stream transcodingStream = new TranscodingStream(innerStreamMock.Object, Encoding.UTF8, Encoding.UTF8, leaveOpen: true);\n\n            // Act & assert\n\n            RunTest(() => transcodingStream.ReadAsync(new byte[0], 0, 0, expectedCancellationToken));\n            RunTest(() => transcodingStream.WriteAsync(new byte[0], 0, 0, expectedCancellationToken));\n#if NETCOREAPP || NETSTANDARD2_1\n            RunTest(() => transcodingStream.ReadAsync(Memory<byte>.Empty, expectedCancellationToken).AsTask());\n            RunTest(() => transcodingStream.WriteAsync(ReadOnlyMemory<byte>.Empty, expectedCancellationToken).AsTask());\n#endif\n\n            void RunTest(Func<Task> callback)\n            {\n                Task task = callback();\n                Assert.True(task.IsCanceled);\n                Assert.Equal(expectedCancellationToken, Assert.Throws<TaskCanceledException>(() => task.GetAwaiter().GetResult()).CancellationToken);\n            }\n        }\n#endif\n\n        [Fact]\n        public void CreateTranscodingStream_InvalidArgs()\n        {\n            Assert.ThrowsArgumentNull(() => new TranscodingStream(null, Encoding.UTF8, Encoding.UTF8), \"innerStream\");\n            Assert.ThrowsArgumentNull(() => new TranscodingStream(Stream.Null, null, Encoding.UTF8), \"innerEncoding\");\n            Assert.ThrowsArgumentNull(() => new TranscodingStream(Stream.Null, Encoding.UTF8, null), \"thisEncoding\");\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void CanRead_DelegatesToInnerStream(bool expectedCanRead)\n        {\n            // Arrange\n\n            var innerStreamMock = new Mock<Stream>();\n            innerStreamMock.Setup(o => o.CanRead).Returns(expectedCanRead);\n            Stream transcodingStream = new TranscodingStream(innerStreamMock.Object, Encoding.UTF8, Encoding.UTF8, leaveOpen: true);\n\n            // Act\n\n            bool actualCanReadBeforeDispose = transcodingStream.CanRead;\n            transcodingStream.Dispose();\n            bool actualCanReadAfterDispose = transcodingStream.CanRead;\n\n            // Assert\n\n            Assert.Equal(expectedCanRead, actualCanReadBeforeDispose);\n            Assert.False(actualCanReadAfterDispose);\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void CanWrite_DelegatesToInnerStream(bool expectedCanWrite)\n        {\n            // Arrange\n\n            var innerStreamMock = new Mock<Stream>();\n            innerStreamMock.Setup(o => o.CanWrite).Returns(expectedCanWrite);\n            Stream transcodingStream = new TranscodingStream(innerStreamMock.Object, Encoding.UTF8, Encoding.UTF8, leaveOpen: true);\n\n            // Act\n\n            bool actualCanWriteBeforeDispose = transcodingStream.CanWrite;\n            transcodingStream.Dispose();\n            bool actualCanWriteAfterDispose = transcodingStream.CanWrite;\n\n            // Assert\n\n            Assert.Equal(expectedCanWrite, actualCanWriteBeforeDispose);\n            Assert.False(actualCanWriteAfterDispose);\n        }\n\n        [Fact]\n        public void Dispose_MakesMostSubsequentOperationsThrow()\n        {\n            // Arrange\n\n            MemoryStream innerStream = new();\n            Stream transcodingStream = new TranscodingStream(innerStream, Encoding.UTF8, Encoding.UTF8, leaveOpen: true);\n\n            // Act\n\n            transcodingStream.Dispose();\n\n            // Assert\n            // For Task/ValueTask-returning methods, we want the exception to be thrown synchronously.\n\n            Assert.False(transcodingStream.CanRead);\n            Assert.False(transcodingStream.CanSeek);\n            Assert.False(transcodingStream.CanWrite);\n\n#if true // Not overriding these and base Stream's BeginXYZ methods check CanXYZ first, throwing NotSupportedException.\n            Assert.Throws<NotSupportedException>(() => transcodingStream.BeginRead(new byte[0], 0, 0, null, null));\n            Assert.Throws<NotSupportedException>(() => transcodingStream.BeginWrite(new byte[0], 0, 0, null, null));\n#else\n            Assert.Throws<ObjectDisposedException>(() => transcodingStream.BeginRead(new byte[0], 0, 0, null, null));\n            Assert.Throws<ObjectDisposedException>(() => transcodingStream.BeginWrite(new byte[0], 0, 0, null, null));\n#endif\n#if NETCOREAPP || NETSTANDARD2_1\n            Assert.Throws<ObjectDisposedException>(() => transcodingStream.Read(Span<byte>.Empty));\n            Assert.Throws<ObjectDisposedException>(() => (object)transcodingStream.ReadAsync(Memory<byte>.Empty));\n            Assert.Throws<ObjectDisposedException>(() => transcodingStream.Write(ReadOnlySpan<byte>.Empty));\n            Assert.Throws<ObjectDisposedException>(() => (object)transcodingStream.WriteAsync(ReadOnlyMemory<byte>.Empty));\n#endif\n            Assert.Throws<ObjectDisposedException>(() => transcodingStream.Flush());\n            Assert.Throws<ObjectDisposedException>(() => (object)transcodingStream.FlushAsync());\n            Assert.Throws<ObjectDisposedException>(() => transcodingStream.Read(new byte[0], 0, 0));\n            Assert.Throws<ObjectDisposedException>(() => (object)transcodingStream.ReadAsync(new byte[0], 0, 0));\n            Assert.Throws<ObjectDisposedException>(() => transcodingStream.ReadByte());\n            Assert.Throws<ObjectDisposedException>(() => transcodingStream.Write(new byte[0], 0, 0));\n            Assert.Throws<ObjectDisposedException>(() => (object)transcodingStream.WriteAsync(new byte[0], 0, 0));\n            Assert.Throws<ObjectDisposedException>(() => transcodingStream.WriteByte((byte)'x'));\n        }\n\n        [Fact]\n        public void Dispose_WithLeaveOpenFalse_DisposesInnerStream()\n        {\n            // Sync\n\n            MemoryStream innerStream = new();\n            Stream transcodingStream = new TranscodingStream(innerStream, Encoding.UTF8, Encoding.UTF8, leaveOpen: false);\n            transcodingStream.Dispose();\n            transcodingStream.Dispose(); // calling it a second time should no-op\n            Assert.Throws<ObjectDisposedException>(() => innerStream.Read(Array.Empty<byte>(), 0, 0));\n\n            // Async\n\n#if NETCOREAPP3_1_OR_GREATER || NETSTANDARD2_1\n            innerStream = new MemoryStream();\n            transcodingStream = new TranscodingStream(innerStream, Encoding.UTF8, Encoding.UTF8, leaveOpen: false);\n            transcodingStream.DisposeAsync().GetAwaiter().GetResult();\n            transcodingStream.DisposeAsync().GetAwaiter().GetResult(); // calling it a second time should no-op\n            Assert.Throws<ObjectDisposedException>(() => innerStream.Read(Span<byte>.Empty));\n#endif\n        }\n\n        [Fact]\n        public void Dispose_WithLeaveOpenTrue_DoesNotDisposeInnerStream()\n        {\n            // Sync\n\n            MemoryStream innerStream = new();\n            Stream transcodingStream = new TranscodingStream(innerStream, Encoding.UTF8, Encoding.UTF8, leaveOpen: true);\n            transcodingStream.Dispose();\n            transcodingStream.Dispose(); // calling it a second time should no-op\n            innerStream.Read(Array.Empty<byte>(), 0, 0); // shouldn't throw\n\n            // Async\n\n#if NETCOREAPP3_1_OR_GREATER || NETSTANDARD2_1\n            innerStream = new MemoryStream();\n            transcodingStream = new TranscodingStream(innerStream, Encoding.UTF8, Encoding.UTF8, leaveOpen: true);\n            transcodingStream.DisposeAsync().GetAwaiter().GetResult();\n            transcodingStream.DisposeAsync().GetAwaiter().GetResult(); // calling it a second time should no-op\n            innerStream.Read(Span<byte>.Empty); // shouldn't throw\n#endif\n        }\n\n        // Moq heavily utilizes RefEmit, which does not work on most aot workloads\n        [Fact]\n        public void Flush_FlushesInnerStreamButNotDecodedState()\n        {\n            // Arrange\n\n            CancellationToken expectedCancellationToken = new CancellationTokenSource().Token;\n            Task expectedFlushAsyncTask = Task.FromResult(\"just some task\");\n\n            var innerStreamMock = new Mock<MemoryStream>() { CallBase = true };\n            innerStreamMock.Setup(o => o.FlushAsync(expectedCancellationToken)).Returns(expectedFlushAsyncTask);\n            Stream transcodingStream = new TranscodingStream(innerStreamMock.Object, Encoding.UTF8, Encoding.UTF8, leaveOpen: true);\n\n            transcodingStream.Write(new byte[] { 0x7A, 0xE0 }, 0, 2);\n            innerStreamMock.Verify(o => o.Flush(), Times.Never);\n            innerStreamMock.Verify(o => o.FlushAsync(It.IsAny<CancellationToken>()), Times.Never);\n\n            // Act & assert - sync flush\n\n            transcodingStream.Flush();\n            innerStreamMock.Verify(o => o.Flush(), Times.Once);\n            innerStreamMock.Verify(o => o.FlushAsync(It.IsAny<CancellationToken>()), Times.Never);\n\n            // Act & assert - async flush\n            // This also validates that we flowed the CancellationToken as expected\n\n            Task actualFlushAsyncReturnedTask = transcodingStream.FlushAsync(expectedCancellationToken);\n            Assert.Same(expectedFlushAsyncTask, actualFlushAsyncReturnedTask);\n            innerStreamMock.Verify(o => o.Flush(), Times.Once);\n            innerStreamMock.Verify(o => o.FlushAsync(expectedCancellationToken), Times.Once);\n\n            Assert.Equal(\"z\", Encoding.UTF8.GetString(innerStreamMock.Object.ToArray())); // [ E0 ] shouldn't have been flushed\n        }\n\n        [Fact]\n        public void IdenticalInnerAndOuterEncodings_DoesNotActAsPassthrough()\n        {\n            // Test read\n            // [ C0 ] is never a valid UTF-8 byte, should be replaced with U+FFFD\n\n            MemoryStream innerStream = new(new byte[] { 0xC0 });\n            Stream transcodingStream = new TranscodingStream(innerStream, Encoding.UTF8, Encoding.UTF8);\n\n            Assert.Equal(0xEF, transcodingStream.ReadByte());\n            Assert.Equal(0xBF, transcodingStream.ReadByte());\n            Assert.Equal(0xBD, transcodingStream.ReadByte());\n            Assert.Equal(-1 /* eof */, transcodingStream.ReadByte());\n\n            // Test write\n\n            innerStream = new MemoryStream();\n            transcodingStream = new TranscodingStream(innerStream, Encoding.UTF8, Encoding.UTF8);\n            transcodingStream.WriteByte(0xC0);\n            Assert.Equal(new byte[] { 0xEF, 0xBF, 0xBD }, innerStream.ToArray());\n        }\n\n        [Theory]\n        [PropertyData(nameof(ReadWriteTestBufferLengths))]\n        public void Read_ByteArray(int bufferLength)\n        {\n            // Tests TranscodingStream.Read(byte[], int, int)\n\n            byte[] buffer = new byte[bufferLength + 3];\n\n            RunReadTest((transcodingStream, sink) =>\n            {\n                int numBytesRead = transcodingStream.Read(buffer, 1, bufferLength);\n                Assert.True(numBytesRead >= 0);\n                Assert.True(numBytesRead <= bufferLength);\n\n                sink.Write(buffer, 1, numBytesRead);\n                return numBytesRead;\n            });\n        }\n\n        [Fact]\n        public void Read_ByteArray_WithInvalidArgs_Throws()\n        {\n            Stream transcodingStream = new TranscodingStream(new MemoryStream(), Encoding.UTF8, Encoding.UTF8);\n\n            Assert.ThrowsArgumentNull(() => transcodingStream.Read(null, 0, 0), \"buffer\");\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.Read(new byte[5], -1, -1));\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.Read(new byte[5], 3, -1));\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.Read(new byte[5], 5, 1));\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.Read(new byte[5], 6, -1));\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.Read(new byte[5], 6, 0));\n        }\n\n        [Fact]\n        public void Read_ByteByByte()\n        {\n            // Tests TranscodingStream.ReadByte\n\n            RunReadTest((transcodingStream, sink) =>\n            {\n                int value = transcodingStream.ReadByte();\n                if (value < 0)\n                {\n                    return 0;\n                }\n\n                sink.WriteByte(checked((byte)value));\n                return 1;\n            });\n        }\n\n#if NETCOREAPP || NETSTANDARD2_1\n        [Theory]\n        [PropertyData(nameof(ReadWriteTestBufferLengths))]\n        public void Read_Span(int bufferLength)\n        {\n            // Tests TranscodingStream.Read(Span<byte>)\n\n            byte[] buffer = new byte[bufferLength];\n\n            RunReadTest((transcodingStream, sink) =>\n            {\n                int numBytesRead = transcodingStream.Read(buffer.AsSpan());\n                Assert.True(numBytesRead >= 0);\n                Assert.True(numBytesRead <= bufferLength);\n\n                sink.Write(buffer.AsSpan(0, numBytesRead));\n                return numBytesRead;\n            });\n        }\n#endif\n\n        private void RunReadTest(Func<Stream, MemoryStream, int> callback)\n        {\n            MemoryStream sink = new();\n\n            MemoryStream innerStream = new();\n            Stream transcodingStream = new TranscodingStream(innerStream,\n                innerEncoding: Encoding.UTF8,\n                thisEncoding: CustomAsciiEncoding);\n\n            // Test with a small string, then test with a large string\n\n            RunOneTestIteration(128);\n            RunOneTestIteration(10 * 1024 * 1024);\n\n            Assert.Equal(-1, transcodingStream.ReadByte()); // should've reached EOF\n\n            // Now put some invalid data into the inner stream, followed by EOF, and ensure we get U+FFFD back out.\n\n            innerStream.SetLength(0); // reset\n            innerStream.WriteByte(0xC0); // [ C0 ] is never valid in UTF-8\n            innerStream.Position = 0;\n\n            sink.SetLength(0); // reset\n            int numBytesReadJustNow;\n            do\n            {\n                numBytesReadJustNow = callback(transcodingStream, sink);\n                Assert.True(numBytesReadJustNow >= 0);\n            } while (numBytesReadJustNow > 0);\n\n            Assert.Equal(\"[FFFD]\", ErrorCheckingAsciiEncoding.GetString(sink.ToArray()));\n            Assert.Equal(-1, transcodingStream.ReadByte()); // should've reached EOF\n\n            // Now put some incomplete data into the inner stream, followed by EOF, and ensure we get U+FFFD back out.\n\n            innerStream.SetLength(0); // reset\n            innerStream.WriteByte(0xC2); // [ C2 ] must be followed by [ 80..BF ] in UTF-8\n            innerStream.Position = 0;\n\n            sink.SetLength(0); // reset\n            do\n            {\n                numBytesReadJustNow = callback(transcodingStream, sink);\n                Assert.True(numBytesReadJustNow >= 0);\n            } while (numBytesReadJustNow > 0);\n\n            Assert.Equal(\"[FFFD]\", ErrorCheckingAsciiEncoding.GetString(sink.ToArray()));\n            Assert.Equal(-1, transcodingStream.ReadByte()); // should've reached EOF\n\n            void RunOneTestIteration(int stringLength)\n            {\n                sink.SetLength(0); // reset\n\n                string expectedStringContents = GetVeryLongAsciiString(stringLength);\n                innerStream.SetLength(0); // reset\n                var bytes = Encoding.UTF8.GetBytes(expectedStringContents);\n                innerStream.Write(bytes, 0, bytes.Length);\n                innerStream.Position = 0;\n\n                int numBytesReadJustNow;\n                do\n                {\n                    numBytesReadJustNow = callback(transcodingStream, sink);\n                    Assert.True(numBytesReadJustNow >= 0);\n                } while (numBytesReadJustNow > 0);\n\n                Assert.Equal(expectedStringContents, ErrorCheckingAsciiEncoding.GetString(sink.ToArray()));\n            }\n        }\n\n        [Fact]\n        public Task ReadApm()\n        {\n            // Tests TranscodingStream.BeginRead / EndRead\n\n            byte[] buffer = new byte[1024 * 1024];\n\n            return RunReadTestAsync((transcodingStream, cancellationToken, sink) =>\n            {\n                TaskCompletionSource<int> tcs = new();\n                object expectedState = new();\n\n                try\n                {\n                    IAsyncResult asyncResult = transcodingStream.BeginRead(buffer, 1, buffer.Length - 2, (asyncResult) =>\n                    {\n                        try\n                        {\n                            int numBytesReadJustNow = transcodingStream.EndRead(asyncResult);\n                            Assert.True(numBytesReadJustNow >= 0);\n                            Assert.True(numBytesReadJustNow < buffer.Length - 3);\n                            sink.Write(buffer, 1, numBytesReadJustNow);\n                            tcs.SetResult(numBytesReadJustNow);\n                        }\n                        catch (Exception ex)\n                        {\n                            tcs.SetException(ex);\n                        }\n                    }, expectedState);\n                    Assert.Same(expectedState, asyncResult.AsyncState);\n                }\n                catch (Exception ex)\n                {\n                    tcs.SetException(ex);\n                }\n\n                return new ValueTask<int>(tcs.Task);\n            },\n            suppressExpectedCancellationTokenAsserts: true); // APM pattern doesn't allow flowing CancellationToken\n        }\n\n        [Theory]\n        [PropertyData(nameof(ReadWriteTestBufferLengths))]\n        public Task ReadAsync_ByteArray(int bufferLength)\n        {\n            // Tests TranscodingStream.ReadAsync(byte[], int, int, CancellationToken)\n\n            byte[] buffer = new byte[bufferLength + 3];\n\n            return RunReadTestAsync(async (transcodingStream, cancellationToken, sink) =>\n            {\n                int numBytesRead = await transcodingStream.ReadAsync(buffer, 1, bufferLength, cancellationToken);\n                Assert.True(numBytesRead >= 0);\n                Assert.True(numBytesRead <= bufferLength);\n\n                sink.Write(buffer, 1, numBytesRead);\n                return numBytesRead;\n            });\n        }\n\n#if NETCOREAPP || NETSTANDARD2_1\n        [Theory]\n        [PropertyData(nameof(ReadWriteTestBufferLengths))]\n        public async Task ReadAsync_Memory(int bufferLength)\n        {\n            // Tests TranscodingStream.ReadAsync(Memory<byte>, CancellationToken)\n\n            byte[] buffer = new byte[bufferLength];\n\n            await RunReadTestAsync(async (transcodingStream, cancellationToken, sink) =>\n            {\n                int numBytesRead = await transcodingStream.ReadAsync(buffer.AsMemory(), cancellationToken);\n                Assert.True(numBytesRead >= 0);\n                Assert.True(numBytesRead <= bufferLength);\n\n                sink.Write(buffer.AsSpan(0, numBytesRead));\n                return numBytesRead;\n            });\n        }\n#endif\n\n        [Fact]\n        public async Task ReadAsync_LoopsWhenPartialDataReceived()\n        {\n            // Validates that the TranscodingStream will loop instead of returning 0\n            // if the inner stream read partial data and GetBytes cannot make forward progress.\n\n            using AsyncComms comms = new();\n            Stream transcodingStream = new TranscodingStream(comms.ReadStream, Encoding.UTF8, Encoding.UTF8);\n\n            // First, ensure that writing [ C0 ] (always invalid UTF-8) to the stream\n            // causes the reader to return immediately with fallback behavior.\n\n            byte[] readBuffer = new byte[1024];\n            comms.WriteBytes(new byte[] { 0xC0 });\n\n            int numBytesRead = await transcodingStream.ReadAsync(readBuffer, 0, readBuffer.Length);\n            Assert.Equal(new byte[] { 0xEF, 0xBF, 0xBD }, readBuffer.AsSpan(0, numBytesRead).ToArray()); // fallback substitution\n\n            // Next, ensure that writing [ C2 ] (partial UTF-8, needs more data) to the stream\n            // causes the reader to asynchronously loop, returning \"not yet complete\".\n\n            readBuffer = new byte[1024];\n            comms.WriteBytes(new byte[] { 0xC2 });\n\n            var task = transcodingStream.ReadAsync(readBuffer, 0, readBuffer.Length);\n            Assert.False(task.IsCompleted);\n            comms.WriteBytes(new byte[] { 0x80 }); // [ C2 80 ] is valid UTF-8\n\n            numBytesRead = await task; // should complete successfully\n            Assert.Equal(new byte[] { 0xC2, 0x80 }, readBuffer.AsSpan(0, numBytesRead).ToArray());\n\n            // Finally, ensure that writing [ C2 ] (partial UTF-8, needs more data) to the stream\n            // followed by EOF causes the reader to perform substitution before returning EOF.\n\n            readBuffer = new byte[1024];\n            comms.WriteBytes(new byte[] { 0xC2 });\n\n            task = transcodingStream.ReadAsync(readBuffer, 0, readBuffer.Length);\n            Assert.False(task.IsCompleted);\n            comms.WriteEof();\n\n            numBytesRead = await task; // should complete successfully\n            Assert.Equal(new byte[] { 0xEF, 0xBF, 0xBD }, readBuffer.AsSpan(0, numBytesRead).ToArray()); // fallback substitution\n\n            // Next call really should return \"EOF reached\"\n\n            readBuffer = new byte[1024];\n            Assert.Equal(0, await transcodingStream.ReadAsync(readBuffer, 0, readBuffer.Length));\n        }\n\n        [Fact]\n        public void ReadAsync_WithInvalidArgs_Throws()\n        {\n            Stream transcodingStream = new TranscodingStream(new MemoryStream(), Encoding.UTF8, Encoding.UTF8);\n\n            Assert.ThrowsArgumentNull(() => { transcodingStream.ReadAsync(null, 0, 0); }, \"buffer\");\n            Assert.Throws<ArgumentOutOfRangeException>(() => (object)transcodingStream.ReadAsync(new byte[5], -1, -1));\n            Assert.Throws<ArgumentOutOfRangeException>(() => (object)transcodingStream.ReadAsync(new byte[5], 3, -1));\n            Assert.Throws<ArgumentOutOfRangeException>(() => (object)transcodingStream.ReadAsync(new byte[5], 5, 1));\n            Assert.Throws<ArgumentOutOfRangeException>(() => (object)transcodingStream.ReadAsync(new byte[5], 6, -1));\n            Assert.Throws<ArgumentOutOfRangeException>(() => (object)transcodingStream.ReadAsync(new byte[5], 6, 0));\n        }\n\n        [Fact]\n        public void ReadApm_WithInvalidArgs_ThrowsAsync()\n        {\n            Stream transcodingStream = new TranscodingStream(new MemoryStream(), Encoding.UTF8, Encoding.UTF8);\n\n#if true\n            // Not overriding BeginRead and base Stream's method returns a Task as its IAsyncResult, delaying parameter checks.\n            Assert.ThrowsArgumentNull(() => transcodingStream.EndRead(transcodingStream.BeginRead(null, 0, 0, null, null)), \"buffer\");\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.EndRead(transcodingStream.BeginRead(new byte[5], -1, -1, null, null)));\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.EndRead(transcodingStream.BeginRead(new byte[5], 3, -1, null, null)));\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.EndRead(transcodingStream.BeginRead(new byte[5], 5, 1, null, null)));\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.EndRead(transcodingStream.BeginRead(new byte[5], 6, -1, null, null)));\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.EndRead(transcodingStream.BeginRead(new byte[5], 6, 0, null, null)));\n#else\n            Assert.ThrowsArgumentNull(() => transcodingStream.BeginRead(null, 0, 0, null, null), \"buffer\");\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.BeginRead(new byte[5], -1, -1, null, null));\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.BeginRead(new byte[5], 3, -1, null, null));\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.BeginRead(new byte[5], 5, 1, null, null));\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.BeginRead(new byte[5], 6, -1, null, null));\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.BeginRead(new byte[5], 6, 0, null, null));\n#endif\n        }\n\n        private async Task RunReadTestAsync(Func<Stream, CancellationToken, MemoryStream, ValueTask<int>> callback, bool suppressExpectedCancellationTokenAsserts = false)\n        {\n            CancellationToken expectedCancellationToken = new CancellationTokenSource().Token;\n            MemoryStream sink = new();\n            MemoryStream innerStream = new();\n\n            var delegatingInnerStreamMock = new Mock<Stream>(MockBehavior.Strict);\n            delegatingInnerStreamMock.Setup(o => o.CanRead).Returns(true);\n\n            // Needed for ReadByte calls.\n            delegatingInnerStreamMock.Setup(o => o.Read(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>()))\n                .Returns<byte[], int, int>(innerStream.Read);\n\n#if true // In current src/ projects, always pass byte array to inner Stream.\n            if (suppressExpectedCancellationTokenAsserts)\n            {\n                delegatingInnerStreamMock.Setup(o => o.ReadAsync(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<CancellationToken>()))\n                    .Returns<byte[], int, int, CancellationToken>(innerStream.ReadAsync);\n            }\n            else\n            {\n                delegatingInnerStreamMock.Setup(o => o.ReadAsync(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>(), expectedCancellationToken))\n                    .Returns<byte[], int, int, CancellationToken>(innerStream.ReadAsync);\n            }\n#else\n            if (suppressExpectedCancellationTokenAsserts)\n            {\n                delegatingInnerStreamMock.Setup(o => o.ReadAsync(It.IsAny<Memory<byte>>(), It.IsAny<CancellationToken>()))\n                    .Returns<Memory<byte>, CancellationToken>(innerStream.ReadAsync);\n            }\n            else\n            {\n                delegatingInnerStreamMock.Setup(o => o.ReadAsync(It.IsAny<Memory<byte>>(), expectedCancellationToken))\n                    .Returns<Memory<byte>, CancellationToken>(innerStream.ReadAsync);\n            }\n#endif\n\n            Stream transcodingStream = new TranscodingStream(\n                innerStream: delegatingInnerStreamMock.Object,\n                innerEncoding: Encoding.UTF8,\n                thisEncoding: CustomAsciiEncoding);\n\n            // Test with a small string, then test with a large string\n\n            await RunOneTestIteration(128);\n            await RunOneTestIteration(10 * 1024 * 1024);\n\n            Assert.Equal(-1, transcodingStream.ReadByte()); // should've reached EOF\n\n            // Now put some invalid data into the inner stream, followed by EOF, and ensure we get U+FFFD back out.\n\n            innerStream.SetLength(0); // reset\n            innerStream.WriteByte(0xC0); // [ C0 ] is never valid in UTF-8\n            innerStream.Position = 0;\n\n            sink.SetLength(0); // reset\n            int numBytesReadJustNow;\n            do\n            {\n                numBytesReadJustNow = await callback(transcodingStream, expectedCancellationToken, sink);\n                Assert.True(numBytesReadJustNow >= 0);\n            } while (numBytesReadJustNow > 0);\n\n            Assert.Equal(\"[FFFD]\", ErrorCheckingAsciiEncoding.GetString(sink.ToArray()));\n            Assert.Equal(-1, transcodingStream.ReadByte()); // should've reached EOF\n\n            // Now put some incomplete data into the inner stream, followed by EOF, and ensure we get U+FFFD back out.\n\n            innerStream.SetLength(0); // reset\n            innerStream.WriteByte(0xC2); // [ C2 ] must be followed by [ 80..BF ] in UTF-8\n            innerStream.Position = 0;\n\n            sink.SetLength(0); // reset\n            do\n            {\n                numBytesReadJustNow = await callback(transcodingStream, expectedCancellationToken, sink);\n                Assert.True(numBytesReadJustNow >= 0);\n            } while (numBytesReadJustNow > 0);\n\n            Assert.Equal(\"[FFFD]\", ErrorCheckingAsciiEncoding.GetString(sink.ToArray()));\n            Assert.Equal(-1, transcodingStream.ReadByte()); // should've reached EOF\n\n            async Task RunOneTestIteration(int stringLength)\n            {\n                sink.SetLength(0); // reset\n\n                string expectedStringContents = GetVeryLongAsciiString(stringLength);\n                innerStream.SetLength(0); // reset\n                var bytes = Encoding.UTF8.GetBytes(expectedStringContents);\n                innerStream.Write(bytes, 0, bytes.Length);\n                innerStream.Position = 0;\n\n                int numBytesReadJustNow;\n                do\n                {\n                    numBytesReadJustNow = await callback(transcodingStream, expectedCancellationToken, sink);\n                    Assert.True(numBytesReadJustNow >= 0);\n                } while (numBytesReadJustNow > 0);\n\n                Assert.Equal(expectedStringContents, ErrorCheckingAsciiEncoding.GetString(sink.ToArray()));\n            }\n        }\n\n        [Fact]\n        public void ReadTimeout_WriteTimeout_NotSupported()\n        {\n            // Arrange - allow inner stream to support ReadTimeout + WriteTimeout\n\n            var innerStreamMock = new Mock<Stream>();\n            innerStreamMock.SetupProperty(o => o.ReadTimeout);\n            innerStreamMock.SetupProperty(o => o.WriteTimeout);\n            Stream transcodingStream = new TranscodingStream(Stream.Null, Encoding.UTF8, Encoding.UTF8, leaveOpen: true);\n\n            // Act & assert - TranscodingStream shouldn't support ReadTimeout + WriteTimeout\n\n            Assert.False(transcodingStream.CanTimeout);\n            Assert.Throws<InvalidOperationException>(() => transcodingStream.ReadTimeout);\n            Assert.Throws<InvalidOperationException>(() => transcodingStream.ReadTimeout = 42);\n            Assert.Throws<InvalidOperationException>(() => transcodingStream.WriteTimeout);\n            Assert.Throws<InvalidOperationException>(() => transcodingStream.WriteTimeout = 42);\n        }\n\n        [Fact]\n        public void Seek_AlwaysThrows()\n        {\n            // MemoryStream is seekable, but we're not\n            Stream transcodingStream = new TranscodingStream(new MemoryStream(), Encoding.UTF8, Encoding.UTF8);\n\n            Assert.False(transcodingStream.CanSeek);\n            Assert.Throws<NotSupportedException>(() => transcodingStream.Length);\n            Assert.Throws<NotSupportedException>(() => transcodingStream.Position);\n            Assert.Throws<NotSupportedException>(() => transcodingStream.Position = 0);\n            Assert.Throws<NotSupportedException>(() => transcodingStream.Seek(0, SeekOrigin.Current));\n            Assert.Throws<NotSupportedException>(() => transcodingStream.SetLength(0));\n        }\n\n        [Fact]\n        public void Write()\n        {\n            MemoryStream innerStream = new();\n            Stream transcodingStream = new TranscodingStream(\n                innerStream,\n                innerEncoding: ErrorCheckingUnicodeEncoding /* throws on error */,\n                thisEncoding: Encoding.UTF8 /* performs substitution */,\n                leaveOpen: true);\n\n            // First, test Write(byte[], int, int)\n\n            transcodingStream.Write(Encoding.UTF8.GetBytes(\"abcdefg\"), 2, 3);\n            Assert.Equal(\"cde\", ErrorCheckingUnicodeEncoding.GetString(innerStream.ToArray()));\n\n            // Then test WriteByte(byte)\n\n            transcodingStream.WriteByte((byte)'z');\n            Assert.Equal(\"cdez\", ErrorCheckingUnicodeEncoding.GetString(innerStream.ToArray()));\n\n            // We'll write U+00E0 (utf-8: [C3 A0]) byte-by-byte.\n            // We shouldn't flush any intermediate bytes.\n\n            transcodingStream.WriteByte((byte)0xC3);\n            Assert.Equal(\"cdez\", ErrorCheckingUnicodeEncoding.GetString(innerStream.ToArray()));\n\n            transcodingStream.WriteByte((byte)0xA0);\n            Assert.Equal(\"cdez\\u00E0\", ErrorCheckingUnicodeEncoding.GetString(innerStream.ToArray()));\n\n            innerStream.SetLength(0); // reset inner stream\n\n            // Then test Write(ROS<byte>), once with a short string and once with a long string\n\n            string asciiString = GetVeryLongAsciiString(128);\n            byte[] asciiBytesAsUtf8 = Encoding.UTF8.GetBytes(asciiString);\n            transcodingStream.Write(asciiBytesAsUtf8, 0, asciiBytesAsUtf8.Length);\n            Assert.Equal(asciiString, ErrorCheckingUnicodeEncoding.GetString(innerStream.ToArray()));\n\n            innerStream.SetLength(0); // reset inner stream\n\n            asciiString = GetVeryLongAsciiString(16 * 1024 * 1024);\n            asciiBytesAsUtf8 = Encoding.UTF8.GetBytes(asciiString);\n            transcodingStream.Write(asciiBytesAsUtf8, 0, asciiBytesAsUtf8.Length);\n            Assert.Equal(asciiString, ErrorCheckingUnicodeEncoding.GetString(innerStream.ToArray()));\n\n            innerStream.SetLength(0); // reset inner stream\n\n            // Close the outer stream and ensure no leftover data was written to the inner stream\n\n            transcodingStream.Close();\n            Assert.Equal(0, innerStream.Position);\n        }\n\n        [Fact]\n        public void Write_WithPartialData()\n        {\n            MemoryStream innerStream = new();\n            Stream transcodingStream = new TranscodingStream(\n                innerStream,\n                innerEncoding: CustomAsciiEncoding /* performs custom substitution */,\n                thisEncoding: Encoding.UTF8 /* performs U+FFFD substitution */,\n                leaveOpen: true);\n\n            // First, write some incomplete data\n\n            transcodingStream.Write(new byte[] { 0x78, 0x79, 0x7A, 0xC3 }, 0, 4); // [C3] shouldn't be flushed yet\n            Assert.Equal(\"xyz\", ErrorCheckingAsciiEncoding.GetString(innerStream.ToArray()));\n\n            // Flushing should have no effect\n\n            transcodingStream.Flush();\n            Assert.Equal(\"xyz\", ErrorCheckingAsciiEncoding.GetString(innerStream.ToArray()));\n\n            // Provide the second byte of the multi-byte sequence\n\n            transcodingStream.WriteByte(0xA0); // [C3 A0] = U+00E0\n            Assert.Equal(\"xyz[00E0]\", ErrorCheckingAsciiEncoding.GetString(innerStream.ToArray()));\n\n            // Provide an incomplete sequence, then close the stream.\n            // Closing the stream should flush the underlying buffers and write the replacement char.\n\n            transcodingStream.Write(new byte[] { 0xE0, 0xBF }, 0, 1); // first 2 bytes of incomplete 3-byte sequence\n            Assert.Equal(\"xyz[00E0]\", ErrorCheckingAsciiEncoding.GetString(innerStream.ToArray())); // wasn't flushed yet\n\n            transcodingStream.Close();\n            Assert.Equal(\"xyz[00E0][FFFD]\", ErrorCheckingAsciiEncoding.GetString(innerStream.ToArray()));\n        }\n\n        [Fact]\n        public void Write_WithInvalidArgs_Throws()\n        {\n            Stream transcodingStream = new TranscodingStream(new MemoryStream(), Encoding.UTF8, Encoding.UTF8);\n\n            Assert.ThrowsArgumentNull(() => transcodingStream.Write(null, 0, 0), \"buffer\");\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.Write(new byte[5], -1, -1));\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.Write(new byte[5], 3, -1));\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.Write(new byte[5], 5, 1));\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.Write(new byte[5], 6, -1));\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.Write(new byte[5], 6, 0));\n        }\n\n        // Moq heavily utilizes RefEmit, which does not work on most aot workloads\n        [Fact]\n        public async Task WriteAsync_WithFullData()\n        {\n            MemoryStream sink = new();\n            CancellationToken expectedFlushAsyncCancellationToken = new CancellationTokenSource().Token;\n            CancellationToken expectedWriteAsyncCancellationToken = new CancellationTokenSource().Token;\n\n            var innerStreamMock = new Mock<Stream>(MockBehavior.Strict);\n            innerStreamMock.Setup(o => o.CanWrite).Returns(true);\n#if true // In current src/ projects, always pass byte array to inner Stream.\n            innerStreamMock.Setup(o => o.WriteAsync(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>(), expectedWriteAsyncCancellationToken))\n                .Returns<byte[], int, int, CancellationToken>(sink.WriteAsync);\n#else\n            innerStreamMock.Setup(o => o.WriteAsync(It.IsAny<ReadOnlyMemory<byte>>(), expectedWriteAsyncCancellationToken))\n                .Returns<ReadOnlyMemory<byte>, CancellationToken>(sink.WriteAsync);\n#endif\n            innerStreamMock.Setup(o => o.FlushAsync(expectedFlushAsyncCancellationToken)).Returns(TaskHelpers.Completed());\n\n            Stream transcodingStream = new TranscodingStream(\n                innerStreamMock.Object,\n                innerEncoding: ErrorCheckingUnicodeEncoding,\n                thisEncoding: Encoding.UTF8 /* performs U+FFFD substitution */,\n                leaveOpen: true);\n\n            // First, test WriteAsync(byte[], int, int, CancellationToken)\n\n            await transcodingStream.WriteAsync(Encoding.UTF8.GetBytes(\"abcdefg\"), 2, 3, expectedWriteAsyncCancellationToken);\n            Assert.Equal(\"cde\", ErrorCheckingUnicodeEncoding.GetString(sink.ToArray()));\n\n            // We'll write U+00E0 (utf-8: [C3 A0]) byte-by-byte.\n            // We shouldn't flush any intermediate bytes.\n\n            await transcodingStream.WriteAsync(new byte[] { 0xC3, 0xA0 }, 0, 1, expectedWriteAsyncCancellationToken);\n            await transcodingStream.FlushAsync(expectedFlushAsyncCancellationToken);\n            Assert.Equal(\"cde\", ErrorCheckingUnicodeEncoding.GetString(sink.ToArray()));\n\n            await transcodingStream.WriteAsync(new byte[] { 0xC3, 0xA0 }, 1, 1, expectedWriteAsyncCancellationToken);\n            Assert.Equal(\"cde\\u00E0\", ErrorCheckingUnicodeEncoding.GetString(sink.ToArray()));\n\n            sink.SetLength(0); // reset sink\n\n            // Then test WriteAsync(ROM<byte>, CancellationToken), once with a short string and once with a long string\n\n            string asciiString = GetVeryLongAsciiString(128);\n            byte[] asciiBytesAsUtf8 = Encoding.UTF8.GetBytes(asciiString);\n            await transcodingStream.WriteAsync(asciiBytesAsUtf8, 0, asciiBytesAsUtf8.Length, expectedWriteAsyncCancellationToken);\n            Assert.Equal(asciiString, ErrorCheckingUnicodeEncoding.GetString(sink.ToArray()));\n\n            sink.SetLength(0); // reset sink\n\n            asciiString = GetVeryLongAsciiString(16 * 1024 * 1024);\n            asciiBytesAsUtf8 = Encoding.UTF8.GetBytes(asciiString);\n            await transcodingStream.WriteAsync(asciiBytesAsUtf8, 0, asciiBytesAsUtf8.Length, expectedWriteAsyncCancellationToken);\n            Assert.Equal(asciiString, ErrorCheckingUnicodeEncoding.GetString(sink.ToArray()));\n\n            sink.SetLength(0); // reset sink\n\n            // Close the outer stream and ensure no leftover data was written to the inner stream\n\n            transcodingStream.Dispose();\n            Assert.Equal(0, sink.Position);\n        }\n\n        // Moq heavily utilizes RefEmit, which does not work on most aot workloads\n        [Fact]\n        public async Task WriteAsync_WithPartialData()\n        {\n            MemoryStream sink = new();\n            CancellationToken expectedCancellationToken = new CancellationTokenSource().Token;\n\n            var innerStreamMock = new Mock<Stream>(MockBehavior.Strict);\n            innerStreamMock.Setup(o => o.CanWrite).Returns(true);\n#if true // In current src/ projects, always pass byte array to inner Stream.\n            innerStreamMock.Setup(o => o.WriteAsync(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>(), expectedCancellationToken))\n                .Returns<byte[], int, int, CancellationToken>(sink.WriteAsync);\n#else\n            innerStreamMock.Setup(o => o.WriteAsync(It.IsAny<ReadOnlyMemory<byte>>(), expectedCancellationToken))\n                .Returns<ReadOnlyMemory<byte>, CancellationToken>(sink.WriteAsync);\n#endif\n\n            Stream transcodingStream = new TranscodingStream(\n                innerStreamMock.Object,\n                innerEncoding: CustomAsciiEncoding /* performs custom substitution */,\n                thisEncoding: Encoding.UTF8 /* performs U+FFFD substitution */,\n                leaveOpen: true);\n\n            // First, write some incomplete data\n\n            await transcodingStream.WriteAsync(new byte[] { 0x78, 0x79, 0x7A, 0xC3 }, 0, 4, expectedCancellationToken); // [C3] shouldn't be flushed yet\n            Assert.Equal(\"xyz\", ErrorCheckingAsciiEncoding.GetString(sink.ToArray()));\n\n            // Provide the second byte of the multi-byte sequence\n\n            await transcodingStream.WriteAsync(new byte[] { 0xA0 }, 0, 1, expectedCancellationToken); // [C3 A0] = U+00E0\n            Assert.Equal(\"xyz[00E0]\", ErrorCheckingAsciiEncoding.GetString(sink.ToArray()));\n\n            // Provide an incomplete sequence, then close the stream.\n            // Closing the stream should flush the underlying buffers and write the replacement char.\n\n            await transcodingStream.WriteAsync(new byte[] { 0xE0, 0xBF }, 0, 2, expectedCancellationToken); // first 2 bytes of incomplete 3-byte sequence\n            Assert.Equal(\"xyz[00E0]\", ErrorCheckingAsciiEncoding.GetString(sink.ToArray())); // wasn't flushed yet\n\n            // The call to Dispose() will call innerStream.Write.\n\n            innerStreamMock.Setup(o => o.Write(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>()))\n                .Callback<byte[], int, int>(sink.Write);\n            transcodingStream.Dispose();\n            Assert.Equal(\"xyz[00E0][FFFD]\", ErrorCheckingAsciiEncoding.GetString(sink.ToArray()));\n        }\n\n        [Fact]\n        public void WriteAsync_WithInvalidArgs_Throws()\n        {\n            Stream transcodingStream = new TranscodingStream(new MemoryStream(), Encoding.UTF8, Encoding.UTF8);\n\n            Assert.ThrowsArgumentNull(() => { transcodingStream.WriteAsync(null, 0, 0); }, \"buffer\");\n            Assert.Throws<ArgumentOutOfRangeException>(() => (object)transcodingStream.WriteAsync(new byte[5], -1, -1));\n            Assert.Throws<ArgumentOutOfRangeException>(() => (object)transcodingStream.WriteAsync(new byte[5], 3, -1));\n            Assert.Throws<ArgumentOutOfRangeException>(() => (object)transcodingStream.WriteAsync(new byte[5], 5, 1));\n            Assert.Throws<ArgumentOutOfRangeException>(() => (object)transcodingStream.WriteAsync(new byte[5], 6, -1));\n            Assert.Throws<ArgumentOutOfRangeException>(() => (object)transcodingStream.WriteAsync(new byte[5], 6, 0));\n        }\n\n        // Moq heavily utilizes RefEmit, which does not work on most aot workloads\n        [Fact]\n        public void WriteApm()\n        {\n            // Arrange\n\n            MemoryStream sink = new();\n            object expectedState = new();\n\n            var innerStreamMock = new Mock<Stream>(MockBehavior.Strict);\n            innerStreamMock.Setup(o => o.CanWrite).Returns(true);\n#if true // In current src/ projects, base Stream's BeginWrite method relies on Write and passes the byte array to the inner stream.\n            innerStreamMock.Setup(o => o.Write(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>()))\n                .Callback<byte[], int, int>(sink.Write);\n#else\n            innerStreamMock.Setup(o => o.WriteAsync(It.IsAny<ReadOnlyMemory<byte>>(), CancellationToken.None))\n                .Returns<ReadOnlyMemory<byte>, CancellationToken>(sink.WriteAsync);\n#endif\n\n            Stream transcodingStream = new TranscodingStream(innerStreamMock.Object, Encoding.UTF8, Encoding.UTF8);\n\n            // Act\n\n            IAsyncResult asyncResult = transcodingStream.BeginWrite(Encoding.UTF8.GetBytes(\"abcdefg\"), 1, 3, null, expectedState);\n            transcodingStream.EndWrite(asyncResult);\n\n            // Assert\n\n            Assert.Equal(expectedState, asyncResult.AsyncState);\n            Assert.Equal(\"bcd\", Encoding.UTF8.GetString(sink.ToArray()));\n        }\n\n        [Fact]\n        public void WriteApm_WithInvalidArgs_Throws()\n        {\n            Stream transcodingStream = new TranscodingStream(new MemoryStream(), Encoding.UTF8, Encoding.UTF8);\n\n#if true // Not overriding BeginRead and base Stream's method returns a Task as its IAsyncResult, delaying parameter checks.\n            Assert.ThrowsArgumentNull(() => transcodingStream.EndWrite(transcodingStream.BeginWrite(null, 0, 0, null, null)), \"buffer\");\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.EndWrite(transcodingStream.BeginWrite(new byte[5], -1, -1, null, null)));\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.EndWrite(transcodingStream.BeginWrite(new byte[5], 3, -1, null, null)));\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.EndWrite(transcodingStream.BeginWrite(new byte[5], 5, 1, null, null)));\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.EndWrite(transcodingStream.BeginWrite(new byte[5], 6, -1, null, null)));\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.EndWrite(transcodingStream.BeginWrite(new byte[5], 6, 0, null, null)));\n#else\n            Assert.ThrowsArgumentNull(() => transcodingStream.BeginWrite(null, 0, 0, null, null), \"buffer\");\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.BeginWrite(new byte[5], -1, -1, null, null));\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.BeginWrite(new byte[5], 3, -1, null, null));\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.BeginWrite(new byte[5], 5, 1, null, null));\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.BeginWrite(new byte[5], 6, -1, null, null));\n            Assert.Throws<ArgumentOutOfRangeException>(() => transcodingStream.BeginWrite(new byte[5], 6, 0, null, null));\n#endif\n        }\n\n        // returns \"abc...xyzabc...xyzabc...\"\n        private static string GetVeryLongAsciiString(int length)\n        {\n#if NETCOREAPP || NETSTANDARD2_1\n            return string.Create(length, (object)null, (buffer, _) =>\n            {\n                for (int i = 0; i < buffer.Length; i++)\n                {\n                    buffer[i] = (char)('a' + (i % 26));\n                }\n            });\n#else\n            // Somewhat minor that the string just repeats a single character.\n            return new string('z', length);\n#endif\n        }\n\n        // A custom ASCIIEncoding where both encoder + decoder fallbacks have been specified\n        private static readonly Encoding CustomAsciiEncoding = Encoding.GetEncoding(\n            \"ascii\", new CustomEncoderFallback(), new DecoderReplacementFallback(\"\\uFFFD\"));\n\n        private static readonly Encoding ErrorCheckingAsciiEncoding\n            = Encoding.GetEncoding(\"ascii\", EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback);\n\n        private static readonly UnicodeEncoding ErrorCheckingUnicodeEncoding\n            = new(bigEndian: false, byteOrderMark: false, throwOnInvalidBytes: true);\n\n        // A custom encoder fallback which substitutes unknown chars with \"[xxxx]\" (the code point as hex)\n        private sealed class CustomEncoderFallback : EncoderFallback\n        {\n            public override int MaxCharCount => 8; // = \"[10FFFF]\".Length\n\n            public override EncoderFallbackBuffer CreateFallbackBuffer()\n            {\n                return new CustomEncoderFallbackBuffer();\n            }\n\n            private sealed class CustomEncoderFallbackBuffer : EncoderFallbackBuffer\n            {\n                private string _remaining = string.Empty;\n                private int _remainingIdx = 0;\n\n                public override int Remaining => _remaining.Length - _remainingIdx;\n\n                public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index)\n                    => FallbackCommon((uint)char.ConvertToUtf32(charUnknownHigh, charUnknownLow));\n\n                public override bool Fallback(char charUnknown, int index)\n                    => FallbackCommon(charUnknown);\n\n                private bool FallbackCommon(uint codePoint)\n                {\n                    Assert.True(codePoint <= 0x10FFFF);\n                    _remaining = String.Format(CultureInfo.InvariantCulture, \"[{0:X4}]\", codePoint);\n                    _remainingIdx = 0;\n                    return true;\n                }\n\n                public override char GetNextChar()\n                {\n                    return (_remainingIdx < _remaining.Length)\n                        ? _remaining[_remainingIdx++]\n                        : '\\0' /* end of string reached */;\n                }\n\n                public override bool MovePrevious()\n                {\n                    if (_remainingIdx == 0)\n                    {\n                        return false;\n                    }\n\n                    _remainingIdx--;\n                    return true;\n                }\n            }\n        }\n\n        /// <summary>A custom encoding that's used to roundtrip from bytes to bytes through a string.</summary>\n        private sealed class IdentityEncoding : Encoding\n        {\n            public override int GetByteCount(char[] chars, int index, int count) => count;\n\n            public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)\n            {\n                Span<char> span = chars.AsSpan(charIndex, charCount);\n                for (int i = 0; i < span.Length; i++)\n                {\n                    Debug.Assert(span[i] <= 0xFF);\n                    bytes[byteIndex + i] = (byte)span[i];\n                }\n                return charCount;\n            }\n\n            public override int GetCharCount(byte[] bytes, int index, int count) => count;\n\n            public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)\n            {\n                Span<byte> span = bytes.AsSpan(byteIndex, byteCount);\n                for (int i = 0; i < span.Length; i++)\n                {\n                    Debug.Assert(span[i] <= 0xFF);\n                    chars[charIndex + i] = (char)span[i];\n                }\n                return byteCount;\n            }\n\n            public override int GetMaxByteCount(int charCount) => charCount;\n\n            public override int GetMaxCharCount(int byteCount) => byteCount;\n\n            public override byte[] GetPreamble() => Array.Empty<byte>();\n        }\n\n        // A helper type that allows synchronously writing to a stream while asynchronously\n        // reading from it.\n        private sealed class AsyncComms : IDisposable\n        {\n            private readonly BlockingCollection<byte[]> _blockingCollection;\n            private readonly PipeWriter _writer;\n\n            public AsyncComms()\n            {\n                _blockingCollection = new BlockingCollection<byte[]>();\n                var pipe = new Pipe();\n                ReadStream = pipe.Reader.AsStream();\n                _writer = pipe.Writer;\n                Task.Run(DrainWorker);\n            }\n\n            public Stream ReadStream { get; }\n\n            public void Dispose()\n            {\n                _blockingCollection.Dispose();\n            }\n\n            public void WriteBytes(ReadOnlySpan<byte> bytes)\n            {\n                _blockingCollection.Add(bytes.ToArray());\n            }\n\n            public void WriteEof()\n            {\n                _blockingCollection.Add(null);\n            }\n\n            private async Task DrainWorker()\n            {\n                byte[] buffer;\n                while ((buffer = _blockingCollection.Take()) is not null)\n                {\n                    await _writer.WriteAsync(buffer);\n                }\n                _writer.Complete();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/InvalidByteRangeExceptionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Headers;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http\n{\n    public class InvalidByteRangeExceptionTest\n    {\n        [Fact]\n        public void Ctor_ThrowsOnNullRange()\n        {\n            Assert.ThrowsArgumentNull(() => new InvalidByteRangeException(contentRange: null), \"contentRange\");\n        }\n\n        [Fact]\n        public void Ctor_SetsContentRange()\n        {\n            ContentRangeHeaderValue contentRange = new ContentRangeHeaderValue(0, 20, 100);\n            InvalidByteRangeException invalidByteRangeException = new InvalidByteRangeException(contentRange);\n            Assert.Same(contentRange, invalidByteRangeException.ContentRange);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/MimeBodyPartTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Net.Http\n{\n    public class MimeBodyPartTest\n    {\n        public static TheoryDataSet<MultipartStreamProvider> BadMultipartStreamProviders\n        {\n            get\n            {\n                return new TheoryDataSet<MultipartStreamProvider>\n                {\n                    new HttpContentMultipartExtensionsTests.NullProvider(),\n                    new HttpContentMultipartExtensionsTests.BadStreamProvider(),\n                    new HttpContentMultipartExtensionsTests.ReadOnlyStreamProvider(),\n                };\n            }\n        }\n\n        [Theory]\n        [TestDataSet(typeof(MimeBodyPartTest), \"BadMultipartStreamProviders\")]\n        public async Task GetOutputStream_ThrowsOnInvalidStreamProvider(MultipartStreamProvider streamProvider)\n        {\n            // Arrange\n            HttpContent parent = new StringContent(\"hello\");\n            MimeBodyPart bodypart = new MimeBodyPart(streamProvider, 1024, parent);\n            bodypart.Segments.Add(new ArraySegment<byte>(new byte[] { 1 }));\n\n            // Act and Assert\n            await Assert.ThrowsAsync<InvalidOperationException>(() => bodypart.WriteSegment(bodypart.Segments[0], CancellationToken.None));\n        }\n\n        [Fact]\n        public async Task Dispose_ClosesOutputStreamOnNonMemoryStream()\n        {\n            // Arrange\n            HttpContent parent = new StringContent(\"hello\");\n            Mock<Stream> mockStream = new Mock<Stream>() { CallBase = true };\n            mockStream.Setup(s => s.CanWrite).Returns(true);\n            Mock<MultipartStreamProvider> mockStreamProvider = new Mock<MultipartStreamProvider>();\n            mockStreamProvider.Setup(sp => sp.GetStream(It.IsAny<HttpContent>(), It.IsAny<HttpContentHeaders>())).Returns(mockStream.Object);\n            MimeBodyPart bodypart = new MimeBodyPart(mockStreamProvider.Object, 1024, parent);\n            bodypart.Segments.Add(new ArraySegment<byte>(new byte[] { 1 }));\n            await bodypart.WriteSegment(bodypart.Segments[0], CancellationToken.None);\n            bodypart.IsComplete = true;\n\n            // Act\n            bodypart.GetCompletedHttpContent();\n            bodypart.Dispose();\n\n            // Assert\n            mockStream.Verify(s => s.Close(), Times.Once());\n        }\n\n        [Fact]\n        public async Task Dispose_SetsPositionToZeroOnMemoryStream()\n        {\n            // Arrange\n            HttpContent parent = new StringContent(\"hello\");\n            Mock<MemoryStream> mockStream = new Mock<MemoryStream> { CallBase = true };\n            Mock<MultipartStreamProvider> mockStreamProvider = new Mock<MultipartStreamProvider>();\n            mockStreamProvider.Setup(sp => sp.GetStream(It.IsAny<HttpContent>(), It.IsAny<HttpContentHeaders>())).Returns(mockStream.Object);\n            MimeBodyPart bodypart = new MimeBodyPart(mockStreamProvider.Object, 1024, parent);\n            bodypart.Segments.Add(new ArraySegment<byte>(new byte[] { 1 }));\n            await bodypart.WriteSegment(bodypart.Segments[0], CancellationToken.None);\n            bodypart.IsComplete = true;\n\n            // Act\n            bodypart.GetCompletedHttpContent();\n            bodypart.Dispose();\n\n            // Assert\n            mockStream.VerifySet(s => s.Position = 0);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Mocks/MockAsyncCallback.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Net.Http.Formatting.Mocks\n{\n    public class MockAsyncCallback\n    {\n        public bool WasInvoked { get; private set; }\n\n        public IAsyncResult AsyncResult { get; private set; }\n\n        public void Handler(IAsyncResult result)\n        {\n            WasInvoked = true;\n            AsyncResult = result;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Mocks/MockCompletedAsyncResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Moq;\n\nnamespace System.Net.Http.Formatting.Mocks\n{\n    public class MockCompletedAsyncResult\n    {\n        private MockCompletedAsyncResult()\n        {\n        }\n\n        public static IAsyncResult Create(bool completedSynchronously, object userState)\n        {\n            Mock<IAsyncResult> mockIAsyncResult = new Mock<IAsyncResult>();\n            mockIAsyncResult.Setup(ar => ar.AsyncState).Returns(userState);\n            mockIAsyncResult.Setup(ar => ar.IsCompleted).Returns(true);\n            mockIAsyncResult.Setup(ar => ar.CompletedSynchronously).Returns(completedSynchronously);\n            return mockIAsyncResult.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Mocks/MockContentNegotiator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Net.Http.Headers;\nusing System.Text;\n\nnamespace System.Net.Http.Formatting.Mocks\n{\n    public class MockContentNegotiator : DefaultContentNegotiator\n    {\n        public MockContentNegotiator()\n        {\n        }\n\n        public MockContentNegotiator(bool excludeMatchOnTypeOnly)\n            : base(excludeMatchOnTypeOnly)\n        {\n        }\n\n        public new Collection<MediaTypeFormatterMatch> ComputeFormatterMatches(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)\n        {\n            return base.ComputeFormatterMatches(type, request, formatters);\n        }\n\n        public new MediaTypeFormatterMatch SelectResponseMediaTypeFormatter(ICollection<MediaTypeFormatterMatch> matches)\n        {\n            return base.SelectResponseMediaTypeFormatter(matches);\n        }\n\n        public new Encoding SelectResponseCharacterEncoding(HttpRequestMessage request, MediaTypeFormatter formatter)\n        {\n            return base.SelectResponseCharacterEncoding(request, formatter);\n        }\n\n        public new MediaTypeFormatterMatch MatchMediaTypeMapping(HttpRequestMessage request, MediaTypeFormatter formatter)\n        {\n            return base.MatchMediaTypeMapping(request, formatter);\n        }\n\n        public new MediaTypeFormatterMatch MatchAcceptHeader(IEnumerable<MediaTypeWithQualityHeaderValue> sortedAcceptValues, MediaTypeFormatter formatter)\n        {\n            return base.MatchAcceptHeader(sortedAcceptValues, formatter);\n        }\n\n        public new MediaTypeFormatterMatch MatchRequestMediaType(HttpRequestMessage request, MediaTypeFormatter formatter)\n        {\n            return base.MatchRequestMediaType(request, formatter);\n        }\n\n        public new bool ShouldMatchOnType(IEnumerable<MediaTypeWithQualityHeaderValue> sortedAcceptValues)\n        {\n            return base.ShouldMatchOnType(sortedAcceptValues);\n        }\n\n        public new MediaTypeFormatterMatch MatchType(Type type, MediaTypeFormatter formatter)\n        {\n            return base.MatchType(type, formatter);\n        }\n\n        public new IEnumerable<MediaTypeWithQualityHeaderValue> SortMediaTypeWithQualityHeaderValuesByQFactor(ICollection<MediaTypeWithQualityHeaderValue> headerValues)\n        {\n            return base.SortMediaTypeWithQualityHeaderValuesByQFactor(headerValues);\n        }\n\n        public new IEnumerable<StringWithQualityHeaderValue> SortStringWithQualityHeaderValuesByQFactor(ICollection<StringWithQualityHeaderValue> headerValues)\n        {\n            return base.SortStringWithQualityHeaderValuesByQFactor(headerValues);\n        }\n\n        public new MediaTypeFormatterMatch UpdateBestMatch(MediaTypeFormatterMatch current, MediaTypeFormatterMatch potentialReplacement)\n        {\n            return base.UpdateBestMatch(current, potentialReplacement);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Mocks/MockDelegatingHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Net.Http.Mocks\n{\n    internal class MockDelegatingHandler : DelegatingHandler\n    {\n        private bool _throwInSendAsync;\n\n        public MockDelegatingHandler(bool throwInSendAsync = false)\n        {\n            _throwInSendAsync = throwInSendAsync;\n        }\n\n        public MockDelegatingHandler(HttpMessageHandler innerHandler, bool throwInSendAsync = false)\n            : base(innerHandler)\n        {\n            _throwInSendAsync = throwInSendAsync;\n        }\n\n        public bool WasInvoked { get; private set; }\n\n        public HttpRequestMessage Request { get; private set; }\n\n        public CancellationToken CancellationToken { get; private set; }\n\n        public Exception SendAsyncException { get; private set; }\n\n        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n        {\n            WasInvoked = true;\n            Request = request;\n            CancellationToken = cancellationToken;\n\n            if (_throwInSendAsync)\n            {\n                SendAsyncException = new Exception(\"SendAsync exception\");\n                throw SendAsyncException;\n            }\n            return Task.FromResult(request.CreateResponse());\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Mocks/MockDelegatingStream.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Net.Http.Internal;\n\nnamespace System.Net.Http.Mocks\n{\n    internal class MockDelegatingStream : DelegatingStream\n    {\n        public MockDelegatingStream(Stream innerStream)\n            : base(innerStream)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Mocks/MockHttpContent.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Net.Http.Headers;\nusing System.Threading.Tasks;\n\nnamespace System.Net.Http.Formatting.Mocks\n{\n    public delegate bool TryComputeLengthDelegate(out long length);\n\n    public class MockHttpContent : HttpContent\n    {\n        public MockHttpContent()\n        {\n        }\n\n        public MockHttpContent(HttpContent innerContent)\n        {\n            InnerContent = innerContent;\n            Headers.ContentType = innerContent.Headers.ContentType;\n        }\n\n        public MockHttpContent(MediaTypeHeaderValue contentType)\n        {\n            if (contentType == null)\n            {\n                throw new ArgumentNullException(\"contentType\");\n            }\n            Headers.ContentType = contentType;\n        }\n\n        public MockHttpContent(string contentType)\n        {\n            if (String.IsNullOrWhiteSpace(contentType))\n            {\n                throw new ArgumentNullException(\"contentType\");\n            }\n            Headers.ContentType = new MediaTypeHeaderValue(contentType);\n        }\n\n        public HttpContent InnerContent { get; set; }\n\n        public Action<bool> DisposeCallback { get; set; }\n        public TryComputeLengthDelegate TryComputeLengthCallback { get; set; }\n        public Action<Stream, TransportContext> SerializeToStreamCallback { get; set; }\n        public Func<Stream, TransportContext, Task> SerializeToStreamAsyncCallback { get; set; }\n\n        protected override void Dispose(bool disposing)\n        {\n            if (DisposeCallback != null)\n            {\n                DisposeCallback(disposing);\n            }\n\n            base.Dispose(disposing);\n        }\n\n        protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)\n        {\n            if (SerializeToStreamAsyncCallback != null)\n            {\n                return SerializeToStreamAsyncCallback(stream, context);\n            }\n            else if (InnerContent != null)\n            {\n                return InnerContent.CopyToAsync(stream, context);\n            }\n            else\n            {\n                throw new InvalidOperationException(\"Construct with inner HttpContent or set SerializeToStreamCallback first.\");\n            }\n        }\n\n        protected override bool TryComputeLength(out long length)\n        {\n            if (TryComputeLengthCallback != null)\n            {\n                return TryComputeLengthCallback(out length);\n            }\n\n            if (InnerContent != null)\n            {\n                long? len = InnerContent.Headers.ContentLength;\n                length = len.HasValue ? len.Value : 0L;\n                return len.HasValue;\n            }\n\n            length = 0L;\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Mocks/MockMediaTypeFormatter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Headers;\nusing System.Text;\n\nnamespace System.Net.Http.Formatting.Mocks\n{\n    public class MockMediaTypeFormatter : MediaTypeFormatter\n    {\n        private bool _canWriteAnyTypes = true;\n        public bool CallBase { get; set; }\n        public Func<Type, bool> CanReadTypeCallback { get; set; }\n        public Func<Type, bool> CanWriteTypeCallback { get; set; }\n\n        internal override bool CanWriteAnyTypes\n        {\n            get { return _canWriteAnyTypes; }\n        }\n\n        public bool CanWriteAnyTypesReturn\n        {\n            get { return _canWriteAnyTypes; }\n            set { _canWriteAnyTypes = value; }\n        }\n\n        public override bool CanReadType(Type type)\n        {\n            if (!CallBase && CanReadTypeCallback == null)\n            {\n                throw new InvalidOperationException(\"CallBase or CanReadTypeCallback must be set first.\");\n            }\n\n            return CanReadTypeCallback != null ? CanReadTypeCallback(type) : true;\n        }\n\n        public override bool CanWriteType(Type type)\n        {\n            if (!CallBase && CanWriteTypeCallback == null)\n            {\n                throw new InvalidOperationException(\"CallBase or CanWriteTypeCallback must be set first.\");\n            }\n\n            return CanWriteTypeCallback != null ? CanWriteTypeCallback(type) : true;\n        }\n\n        public new Encoding SelectCharacterEncoding(HttpContentHeaders contentHeaders)\n        {\n            return base.SelectCharacterEncoding(contentHeaders);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Mocks/MockMediaTypeMapping.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Headers;\nnamespace System.Net.Http.Formatting.Mocks\n{\n    public class MockMediaTypeMapping : MediaTypeMapping\n    {\n        public MockMediaTypeMapping(string mediaType, double matchQuality)\n            : base(mediaType)\n        {\n            MatchQuality = matchQuality;\n        }\n\n        public MockMediaTypeMapping(MediaTypeHeaderValue mediaType, double matchQuality)\n            : base(mediaType)\n        {\n            MatchQuality = matchQuality;\n        }\n\n        public double MatchQuality { get; private set; }\n\n        public HttpRequestMessage Request { get; private set; }\n\n        public bool WasInvoked { get; private set; }\n\n        public override double TryMatchMediaType(HttpRequestMessage request)\n        {\n            WasInvoked = true;\n            Request = request;\n            return MatchQuality;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Mocks/MockNonClosingDelegatingStream.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Net.Http.Internal;\n\nnamespace System.Net.Http.Mocks\n{\n    internal class MockNonClosingDelegatingStream : NonClosingDelegatingStream\n    {\n        public MockNonClosingDelegatingStream(Stream innerStream)\n            : base(innerStream)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Mocks/MockProgressEventHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Net.Http.Handlers\n{\n    public class MockProgressEventHandler\n    {\n        public bool WasInvoked { get; private set; }\n\n        public object Sender { get; private set; }\n\n        public HttpProgressEventArgs EventArgs { get; private set; }\n\n        public void Handler(object sender, HttpProgressEventArgs eventArgs)\n        {\n            WasInvoked = true;\n            Sender = sender;\n            EventArgs = eventArgs;\n        }\n\n        public static ProgressMessageHandler CreateProgressMessageHandler(out MockProgressEventHandler progressEventHandler, bool sendProgress)\n        {\n            ProgressMessageHandler progressHandler = new ProgressMessageHandler();\n            progressEventHandler = new MockProgressEventHandler();\n            if (sendProgress)\n            {\n                progressHandler.HttpSendProgress += progressEventHandler.Handler;\n            }\n            else\n            {\n                progressHandler.HttpReceiveProgress += progressEventHandler.Handler;\n            }\n            return progressHandler;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/Mocks/TestableHttpMessageHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Net.Http.Mocks\n{\n    public class TestableHttpMessageHandler : HttpMessageHandler\n    {\n        public virtual Task<HttpResponseMessage> SendAsyncPublic(HttpRequestMessage request, CancellationToken cancellationToken)\n        {\n            throw new NotImplementedException();\n        }\n\n        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n        {\n            return SendAsyncPublic(request, cancellationToken);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/MultipartFileDataTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Headers;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http\n{\n    public class MultipartFileDataTest\n    {\n        [Fact]\n        public void Constructor_ThrowsOnNullHeaders()\n        {\n            Assert.ThrowsArgumentNull(() => new MultipartFileData(null, \"file\"), \"headers\");\n        }\n\n        [Fact]\n        public void Constructor_ThrowsOnNullLocalFileName()\n        {\n            HttpContentHeaders headers = FormattingUtilities.CreateEmptyContentHeaders();\n            Assert.ThrowsArgumentNull(() => new MultipartFileData(headers, null), \"localFileName\");\n        }\n\n        [Fact]\n        public void Constructor_InitializesCorrectly()\n        {\n            // Arrange\n            HttpContentHeaders headers = FormattingUtilities.CreateEmptyContentHeaders();\n            string fileName = \"filename\";\n\n            // Act\n            MultipartFileData fileData = new MultipartFileData(headers, fileName);\n\n\n            Assert.Same(headers, fileData.Headers);\n            Assert.Same(fileName, fileData.LocalFileName);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/MultipartFileStreamProviderTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Linq;\nusing System.Net.Http.Internal;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http\n{\n    public class MockMultipartFileStreamProvider : MultipartFileStreamProvider\n    {\n        public MockMultipartFileStreamProvider()\n            : base(Path.GetTempPath())\n        {\n        }\n\n        public MockMultipartFileStreamProvider(string rootPath)\n            : base(rootPath)\n        {\n        }\n\n        public MockMultipartFileStreamProvider(string rootPath, int bufferSize)\n            : base(rootPath, bufferSize)\n        {\n        }\n    }\n\n    public class MultipartFileStreamProviderTests : MultipartStreamProviderTestBase<MockMultipartFileStreamProvider>\n    {\n        private const int MinBufferSize = 1;\n        private const int ValidBufferSize = 0x111;\n        private const string ValidPath = @\"c:\\some\\path\";\n\n#if !NETCOREAPP // .NET Core does not enforce path validity in many APIs.\n        public static TheoryDataSet<string> NotSupportedFilePaths\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    \"cc:\\\\a\\\\b\",\n                    \"123:\\\\a\\\\b\",\n                    \"c d:\\\\a\\\\b\",\n                };\n            }\n        }\n#endif\n\n        public static TheoryDataSet<string> InvalidFilePaths\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    \"\",\n                    \" \",\n                    \"  \",\n#if !NETCOREAPP // .NET Core does not enforce path validity in many APIs.\n                    \"\\t\\t \\n \",\n                    \"c:\\\\a<b\",\n                    \"c:\\\\a>b\",\n                    \"c:\\\\a\\\"b\",\n                    \"c:\\\\a\\tb\",\n                    \"c:\\\\a|b\",\n                    \"c:\\\\a\\bb\",\n#endif\n                    \"c:\\\\a\\0b\",\n                    \"c :\\\\a\\0b\",\n                };\n            }\n        }\n\n        [Fact]\n        public void Constructor_ThrowsOnNullRootPath()\n        {\n            Assert.ThrowsArgumentNull(() => { new MultipartFileStreamProvider(null); }, \"rootPath\");\n        }\n\n#if !NETCOREAPP // .NET Core does not enforce path validity in many APIs.\n        [Theory]\n        [PropertyData(\"NotSupportedFilePaths\")]\n        public void Constructor_ThrowsOnNotSupportedRootPath(string notSupportedPath)\n        {\n            Assert.Throws<NotSupportedException>(() => new MultipartFileStreamProvider(notSupportedPath, ValidBufferSize));\n        }\n#endif\n\n        [Theory]\n        [PropertyData(\"InvalidFilePaths\")]\n        public void Constructor_ThrowsOnInvalidRootPath(string invalidPath)\n        {\n            Assert.ThrowsArgument(() => new MultipartFileStreamProvider(invalidPath, ValidBufferSize), null);\n        }\n\n        [Fact]\n        public void Constructor_InvalidBufferSize()\n        {\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(() => new MultipartFileStreamProvider(ValidPath, MinBufferSize - 1),\n                \"bufferSize\", MinBufferSize.ToString(), MinBufferSize - 1);\n        }\n\n        [Fact]\n        public void FileData_IsEmpty()\n        {\n            MultipartFileStreamProvider provider = new MultipartFileStreamProvider(ValidPath, ValidBufferSize);\n            Assert.Empty(provider.FileData);\n        }\n\n        [Fact]\n        public void GetStream()\n        {\n            Stream stream0 = null;\n            Stream stream1 = null;\n\n            try\n            {\n                string tempPath = Path.GetTempPath();\n                MultipartFormDataContent content = new MultipartFormDataContent();\n                content.Add(new StringContent(\"Content 1\"), \"NoFile\");\n                content.Add(new StringContent(\"Content 2\"), \"File\", \"Filename\");\n\n                MultipartFileStreamProvider provider = new MultipartFileStreamProvider(tempPath);\n                stream0 = provider.GetStream(content, content.ElementAt(0).Headers);\n                stream1 = provider.GetStream(content, content.ElementAt(1).Headers);\n\n                Assert.IsType<FileStream>(stream0);\n                Assert.IsType<FileStream>(stream1);\n\n                Assert.Equal(2, provider.FileData.Count);\n                string partialFileName = String.Format(\"{0}BodyPart_\", tempPath);\n                Assert.Contains(partialFileName, provider.FileData[0].LocalFileName);\n                Assert.Contains(partialFileName, provider.FileData[1].LocalFileName);\n\n                Assert.Same(content.ElementAt(0).Headers.ContentDisposition, provider.FileData[0].Headers.ContentDisposition);\n                Assert.Same(content.ElementAt(1).Headers.ContentDisposition, provider.FileData[1].Headers.ContentDisposition);\n            }\n            finally\n            {\n                if (stream0 != null)\n                {\n                    stream0.Close();\n                }\n\n                if (stream1 != null)\n                {\n                    stream1.Close();\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/MultipartFormDataRemoteStreamProviderTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Linq;\nusing System.Net.Http.Headers;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Net.Http\n{\n    public class MultipartFormDataRemoteStreamProviderTests :\n        MultipartStreamProviderTestBase<CustomMultipartFormDataRemoteStreamProvider>\n    {\n        [Fact]\n        public void FileData_IsEmpty()\n        {\n            CustomMultipartFormDataRemoteStreamProvider provider = new CustomMultipartFormDataRemoteStreamProvider();\n            Assert.Empty(provider.FileData);\n        }\n\n        [Fact]\n        public void FormData_IsEmpty()\n        {\n            CustomMultipartFormDataRemoteStreamProvider provider = new CustomMultipartFormDataRemoteStreamProvider();\n            Assert.Empty(provider.FormData);\n        }\n\n        [Fact]\n        public void GetStream_ThrowsOnNoContentDisposition()\n        {\n            // Arrange\n            CustomMultipartFormDataRemoteStreamProvider provider = new CustomMultipartFormDataRemoteStreamProvider();\n            HttpContent content = new StringContent(String.Empty);\n            HttpContentHeaders headers = FormattingUtilities.CreateEmptyContentHeaders();\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(() => { provider.GetStream(content, headers); });\n        }\n\n        [Fact]\n        public void GetStream()\n        {\n            // Arrange\n            Stream stream0 = null;\n            Stream stream1 = null;\n\n            try\n            {\n                MultipartFormDataContent content = new MultipartFormDataContent();\n                content.Add(new StringContent(\"Content 1\"), \"NoFile\");\n                content.Add(new StringContent(\"Content 2\"), \"File\", \"Filename\");\n\n                CustomMultipartFormDataRemoteStreamProvider provider =\n                    new CustomMultipartFormDataRemoteStreamProvider();\n\n                // Act\n                stream0 = provider.GetStream(content, content.ElementAt(0).Headers);\n                stream1 = provider.GetStream(content, content.ElementAt(1).Headers);\n\n                // Assert\n                Assert.IsType<MemoryStream>(stream0);\n                Assert.Single(provider.RemoteStreams, stream1);\n\n                MultipartRemoteFileData fileData = Assert.Single(provider.FileData);\n                string expectedUrl = provider.UrlBase + \"Filename\";\n                Assert.Equal(expectedUrl, fileData.Location);\n\n                Assert.Same(content.ElementAt(1).Headers.ContentDisposition,\n                    fileData.Headers.ContentDisposition);\n            }\n            finally\n            {\n                if (stream0 != null)\n                {\n                    stream0.Close();\n                }\n\n                if (stream1 != null)\n                {\n                    stream1.Close();\n                }\n            }\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void GetStream_StreamResultNullThrowsException()\n        {\n            // Arrange\n            MultipartFormDataContent content = new MultipartFormDataContent();\n            content.Add(new StringContent(\"Content\"), \"File\", \"Filename\");\n            CustomMultipartFormDataRemoteStreamProvider provider =\n                new CustomMultipartFormDataRemoteStreamProvider(isResultNull: true);\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => provider.GetStream(content, content.ElementAt(0).Headers),\n                \"The 'GetRemoteStream' method in 'CustomMultipartFormDataRemoteStreamProvider' returned null. \" +\n                \"It must return a RemoteStreamResult instance containing a writable stream and a valid URL.\"\n                );\n        }\n\n        [Fact]\n        public async Task PostProcessing_ProcessesFormData()\n        {\n            // Arrange\n            int maxContents = 16;\n            string contentFormat = \"Content {0}\";\n            string formNameFormat = \"FormName_{0}\";\n            string fileNameFormat = \"FileName_{0}\";\n\n            MultipartFormDataContent multipartContent = new MultipartFormDataContent();\n\n            // Create half contents for form data and the other half for file data.\n            for (int index = 0; index < maxContents; index++)\n            {\n                string content = String.Format(contentFormat, index);\n                string formName = String.Format(formNameFormat, index);\n                if (index < maxContents/2)\n                {\n                    multipartContent.Add(new StringContent(content), formName);\n                }\n                else\n                {\n                    string fileName = String.Format(fileNameFormat, index);\n                    multipartContent.Add(new StringContent(content), formName, fileName);\n                }\n            }\n\n            CustomMultipartFormDataRemoteStreamProvider provider =\n                new CustomMultipartFormDataRemoteStreamProvider();\n            foreach (HttpContent content in multipartContent)\n            {\n                provider.Contents.Add(content);\n                using (provider.GetStream(multipartContent, content.Headers))\n                {\n                }\n            }\n\n            // Act\n            await provider.ExecutePostProcessingAsync();\n\n            // Assert\n            Assert.Equal(maxContents/2, provider.FormData.Count);\n\n            // half contents for form data\n            for (int index = 0; index < maxContents/2; index++)\n            {\n                string content = String.Format(contentFormat, index);\n                string formName = String.Format(formNameFormat, index);\n                Assert.Equal(content, provider.FormData[formName]);\n            }\n\n            // the other half for file data\n            HttpContent[] contents = multipartContent.ToArray();\n            for (int index = maxContents/2; index < maxContents; index++)\n            {\n                int fileDataIndex = index - (maxContents/2);\n                string fileName = String.Format(fileNameFormat, index);\n                string url = provider.UrlBase + fileName;\n                Assert.Equal(url, provider.FileData[fileDataIndex].Location);\n                Assert.Same(contents[index].Headers, provider.FileData[fileDataIndex].Headers);\n            }\n        }\n\n        [Fact]\n        public async Task ExecutePostProcessingAsyncWithoutCancellationToken_GetCalledBy_ReadAsMultipartAsync()\n        {\n            // Arrange\n            MultipartFormDataContent multipartContent = new MultipartFormDataContent();\n            Mock<CustomMultipartFormDataRemoteStreamProvider> mockProvider =\n                new Mock<CustomMultipartFormDataRemoteStreamProvider>();\n            mockProvider.CallBase = true;\n\n            // Act\n            await multipartContent.ReadAsMultipartAsync(mockProvider.Object);\n\n            // Assert\n            mockProvider.Verify(p => p.ExecutePostProcessingAsync(), Times.Once());\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/MultipartFormDataStreamProviderTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Linq;\nusing System.Net.Http.Headers;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Net.Http\n{\n    public class MockMultipartFormDataStreamProvider : MultipartFormDataStreamProvider\n    {\n        public MockMultipartFormDataStreamProvider()\n            : base(Path.GetTempPath())\n        {\n        }\n\n        public MockMultipartFormDataStreamProvider(string rootPath)\n            : base(rootPath)\n        {\n        }\n\n        public MockMultipartFormDataStreamProvider(string rootPath, int bufferSize)\n            : base(rootPath, bufferSize)\n        {\n        }\n    }\n\n    public class MultipartFormDataStreamProviderTests : MultipartStreamProviderTestBase<MockMultipartFormDataStreamProvider>\n    {\n        private const int ValidBufferSize = 0x111;\n        private const string ValidPath = @\"c:\\some\\path\";\n\n        [Fact]\n        public void FormData_IsEmpty()\n        {\n            MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(ValidPath, ValidBufferSize);\n            Assert.Empty(provider.FormData);\n        }\n\n        [Fact]\n        public void GetStream_ThrowsOnNoContentDisposition()\n        {\n            MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(ValidPath);\n            HttpContent content = new StringContent(String.Empty);\n            HttpContentHeaders headers = FormattingUtilities.CreateEmptyContentHeaders();\n\n            Assert.Throws<InvalidOperationException>(() => { provider.GetStream(content, headers); });\n        }\n\n        [Fact]\n        public void GetStream()\n        {\n            Stream stream0 = null;\n            Stream stream1 = null;\n\n            try\n            {\n                string tempPath = Path.GetTempPath();\n                MultipartFormDataContent content = new MultipartFormDataContent();\n                content.Add(new StringContent(\"Content 1\"), \"NoFile\");\n                content.Add(new StringContent(\"Content 2\"), \"File\", \"Filename\");\n\n                MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(tempPath);\n                stream0 = provider.GetStream(content, content.ElementAt(0).Headers);\n                stream1 = provider.GetStream(content, content.ElementAt(1).Headers);\n\n                Assert.IsType<MemoryStream>(stream0);\n                Assert.IsType<FileStream>(stream1);\n\n                MultipartFileData fileData = Assert.Single(provider.FileData);\n                string partialFileName = String.Format(\"{0}BodyPart_\", tempPath);\n                Assert.Contains(partialFileName, fileData.LocalFileName);\n\n                Assert.Same(content.ElementAt(1).Headers.ContentDisposition, fileData.Headers.ContentDisposition);\n            }\n            finally\n            {\n                if (stream0 != null)\n                {\n                    stream0.Close();\n                }\n\n                if (stream1 != null)\n                {\n                    stream1.Close();\n                }\n            }\n        }\n\n        [Fact]\n        public async Task PostProcessing_ProcessesFormData()\n        {\n            // Arrange\n            int maxContents = 16;\n            string contentFormat = \"Content {0}\";\n            string formNameFormat = \"FormName_{0}\";\n\n            MultipartFormDataContent multipartContent = new MultipartFormDataContent();\n\n            for (int index = 0; index < maxContents; index++)\n            {\n                string content = String.Format(contentFormat, index);\n                string formName = String.Format(formNameFormat, index);\n                multipartContent.Add(new StringContent(content), formName);\n            }\n\n            MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(ValidPath);\n            foreach (HttpContent content in multipartContent)\n            {\n                provider.Contents.Add(content);\n                provider.GetStream(multipartContent, content.Headers);\n            }\n\n            // Act\n            await provider.ExecutePostProcessingAsync();\n\n            // Assert\n            Assert.Equal(maxContents, provider.FormData.Count);\n\n            for (int index = 0; index < maxContents; index++)\n            {\n                string content = String.Format(contentFormat, index);\n                string formName = String.Format(formNameFormat, index);\n                Assert.Equal(content, provider.FormData[formName]);\n            }\n        }\n\n        [Fact]\n        public async Task PostProcessing_ProcessesFormData_WithCustomMultipartFormDataStreamProvider()\n        {\n            // Arrange\n            string tempPath = Path.GetTempPath();\n            int maxContents = 16;\n            string contentFormat = \"Content {0}\";\n            string formNameFormat = \"FormName_{0}\";\n            string fileNameFormat = \"FileName_{0}\";\n\n            MultipartFormDataContent multipartContent = new MultipartFormDataContent();\n\n            // Create half contents for form data and the other half for file data.\n            for (int index = 0; index < maxContents; index++)\n            {\n                string content = String.Format(contentFormat, index);\n                string formName = String.Format(formNameFormat, index);\n                if (index < maxContents/2)\n                {\n                    multipartContent.Add(new StringContent(content), formName);\n                }\n                else\n                {\n                    string fileName = String.Format(fileNameFormat, index);\n                    multipartContent.Add(new StringContent(content), formName, fileName);\n                }\n            }\n\n            CustomMultipartFormDataStreamProvider provider =\n                new CustomMultipartFormDataStreamProvider(tempPath);\n            foreach (HttpContent content in multipartContent)\n            {\n                provider.Contents.Add(content);\n                using (provider.GetStream(multipartContent, content.Headers)) { }\n            }\n\n            // Act\n            await provider.ExecutePostProcessingAsync();\n\n            // Assert\n            Assert.Equal(maxContents / 2, provider.FormData.Count);\n\n            // half contents for form data\n            for (int index = 0; index < maxContents / 2; index++)\n            {\n                string content = String.Format(contentFormat, index);\n                string formName = String.Format(formNameFormat, index);\n                Assert.Equal(content, provider.FormData[formName]);\n            }\n\n            // the other half for file data\n            HttpContent[] contents = multipartContent.ToArray();\n            for (int index = maxContents / 2; index < maxContents; index++)\n            {\n                int fileDataIndex = index - (maxContents / 2);\n                string fileName = String.Format(fileNameFormat, index);\n                Assert.Equal(fileName, provider.FileData[fileDataIndex].LocalFileName);\n                Assert.Same(contents[index].Headers, provider.FileData[fileDataIndex].Headers);\n            }\n        }\n\n        [Fact]\n        public async Task ExecutePostProcessingAsyncWithoutCancellationToken_GetCalledBy_ReadAsMultipartAsync()\n        {\n            // Arrange\n            MultipartFormDataContent multipartContent = new MultipartFormDataContent();\n            Mock<MultipartFormDataStreamProvider> mockProvider = new Mock<MultipartFormDataStreamProvider>(ValidPath);\n            mockProvider.CallBase = true;\n\n            // Act\n            var provider = await multipartContent.ReadAsMultipartAsync(mockProvider.Object);\n\n            // Assert\n            mockProvider.Verify(p => p.ExecutePostProcessingAsync(), Times.Once());\n        }\n\n        private class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider\n        {\n            public CustomMultipartFormDataStreamProvider(string rootPath)\n                : base(rootPath)\n            {\n            }\n\n            public CustomMultipartFormDataStreamProvider(string rootPath, int bufferSize)\n                : base(rootPath, bufferSize)\n            {\n            }\n\n            public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)\n            {\n                Stream stream = null;\n                ContentDispositionHeaderValue contentDisposition = headers.ContentDisposition;\n                if (contentDisposition != null)\n                {\n                    if (!String.IsNullOrEmpty(contentDisposition.FileName))\n                    {\n                        FileData.Add(new MultipartFileData(headers, contentDisposition.FileName));\n                        // Can be replaced with any stream the user want. e.g. Azure Blob Storage Stream.\n                        stream = new MemoryStream();\n                    }\n                    else\n                    {\n                        stream = base.GetStream(parent, headers);\n                    }\n                }\n\n                return stream;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/MultipartMemoryStreamProviderTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Net.Http.Headers;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http\n{\n    public class MultipartMemoryStreamProviderTests : MultipartStreamProviderTestBase<MultipartMemoryStreamProvider>\n    {\n        [Fact]\n        public void GetStream_ReturnsNewMemoryStream()\n        {\n            // Arrange\n            MultipartMemoryStreamProvider instance = new MultipartMemoryStreamProvider();\n            HttpContent parent = new StringContent(String.Empty);\n            HttpContentHeaders headers = FormattingUtilities.CreateEmptyContentHeaders();\n\n            // Act\n            Stream stream1 = instance.GetStream(parent, headers);\n            Stream stream2 = instance.GetStream(parent, headers);\n\n            // Assert\n            Assert.IsType<MemoryStream>(stream1);\n            Assert.Equal(0, stream1.Length);\n            Assert.Equal(0, stream1.Position);\n\n            Assert.IsType<MemoryStream>(stream2);\n            Assert.Equal(0, stream2.Length);\n            Assert.Equal(0, stream2.Position);\n\n            Assert.NotSame(stream1, stream2);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/MultipartRelatedStreamProviderTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Headers;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http\n{\n    public class MultipartRelatedStreamProviderTests : MultipartStreamProviderTestBase<MultipartRelatedStreamProvider>\n    {\n        private const string ContentID = \"12345\";\n        private const string Boundary = \"-A-\";\n\n        private const string DefaultRootContent = \"Default root content\";\n        private const string ContentIDRootContent = \"Content with matching Content-ID\";\n        private const string OtherContent = \"Other Content\";\n\n        public static TheoryDataSet<string> MultipartRelatedWithStartParameter\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    { String.Format(\"multipart/related; boundary={0}; start=\\\"{1}\\\"\", Boundary, ContentID) },\n                    { String.Format(\"multipart/related; start={0}; boundary={1}\", ContentID, Boundary) },\n                };\n            }\n        }\n\n        public static TheoryDataSet<string> MultipartWithMissingOrInvalidStartParameter\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    { String.Format(\"multipart/form-data; start=\\\"{0}\\\"; boundary={1}\", ContentID, Boundary) },\n                    { String.Format(\"multipart/form-data; start={0}; boundary={1}\", ContentID, Boundary) },\n                    { String.Format(\"multipart/form-data; boundary={0}\", Boundary) },\n                    { String.Format(\"multipart/related; boundary={0}\", Boundary) },\n                    { String.Format(\"multipart/mixed; start={0}; boundary={1}\", ContentID, Boundary) },\n                    { String.Format(\"multipart/mixed; boundary={1}\", ContentID, Boundary) },\n                };\n            }\n        }\n\n        [Fact]\n        public void RootContent_ReturnsNull()\n        {\n            MultipartRelatedStreamProvider provider = new MultipartRelatedStreamProvider();\n            Assert.Null(provider.RootContent);\n        }\n\n        [Theory]\n        [PropertyData(\"MultipartRelatedWithStartParameter\")]\n        public async Task RootContent_ReturnsNullIfContentIDIsNotMatched(string mediaType)\n        {\n            // Arrange\n            MultipartContent content = new MultipartContent(\"related\", Boundary);\n            content.Headers.ContentType = MediaTypeHeaderValue.Parse(mediaType);\n\n            content.Add(new StringContent(DefaultRootContent));\n            content.Add(new StringContent(OtherContent));\n\n            HttpContent expectedRootContent = new StringContent(ContentIDRootContent);\n            expectedRootContent.Headers.Add(\"Content-ID\", \"NoMatch\");\n            content.Add(expectedRootContent);\n\n            MultipartRelatedStreamProvider provider = await content.ReadAsMultipartAsync(new MultipartRelatedStreamProvider());\n\n            // Act\n            HttpContent actualRootContent = provider.RootContent;\n\n            // Assert\n            Assert.Null(actualRootContent);\n        }\n\n        [Theory]\n        [PropertyData(\"MultipartRelatedWithStartParameter\")]\n        public async Task RootContent_PicksContent_WithStartParameter(string mediaType)\n        {\n            var result = await RootContent_PicksContent_Setup(mediaType);\n            Assert.Equal(ContentIDRootContent, result);\n        }\n\n        [Theory]\n        [PropertyData(\"MultipartWithMissingOrInvalidStartParameter\")]\n        public async Task RootContent_PicksContent_WithoutStartParameter(string mediaType)\n        {\n            var result = await RootContent_PicksContent_Setup(mediaType);\n            Assert.Equal(DefaultRootContent, result);\n        }\n\n        private async Task<string> RootContent_PicksContent_Setup(string mediaType)\n        {\n            // Arrange\n            MultipartContent content = new MultipartContent(\"related\", Boundary);\n            content.Headers.ContentType = MediaTypeHeaderValue.Parse(mediaType);\n\n            content.Add(new StringContent(DefaultRootContent));\n            content.Add(new StringContent(OtherContent));\n\n            HttpContent contentIDContent = new StringContent(ContentIDRootContent);\n            contentIDContent.Headers.Add(\"Content-ID\", ContentID);\n            content.Add(contentIDContent);\n\n            MultipartRelatedStreamProvider provider = await content.ReadAsMultipartAsync(new MultipartRelatedStreamProvider());\n\n            // Act\n            HttpContent actualRootContent = provider.RootContent;\n            return await actualRootContent.ReadAsStringAsync();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/MultipartRemoteFileDataTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Headers;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http\n{\n    public class MultipartRemoteFileDataTests\n    {\n        [Fact]\n        public void Constructor_ThrowsOnNullHeaders()\n        {\n            // Arrange, Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => new MultipartRemoteFileData(null, \"http://some/path/to\", \"Name\"),\n                \"headers\");\n        }\n\n        [Fact]\n        public void Constructor_ThrowsOnNullLocation()\n        {\n            // Arrange\n            HttpContentHeaders headers = FormattingUtilities.CreateEmptyContentHeaders();\n            \n            // Act and Assert\n            Assert.ThrowsArgumentNull(() => new MultipartRemoteFileData(headers, null, \"Name\"), \"location\");\n        }\n\n        [Fact]\n        public void Constructor_ThrowsOnNullFileName()\n        {\n            // Arrange\n            HttpContentHeaders headers = FormattingUtilities.CreateEmptyContentHeaders();\n\n            // Act and Assert\n            Assert.ThrowsArgumentNull(() => new MultipartRemoteFileData(headers, \"http://some/path/to\", null),\n                \"fileName\");\n        }\n\n        [Fact]\n        public void Constructor_InitializesCorrectly()\n        {\n            // Arrange\n            HttpContentHeaders headers = FormattingUtilities.CreateEmptyContentHeaders();\n            string remoteFileURL = \"http://some/path/to\";\n            string fileName = \"Name\";\n\n            // Act\n            MultipartRemoteFileData fileData = new MultipartRemoteFileData(headers, remoteFileURL, fileName);\n\n            // Assert\n            Assert.Same(headers, fileData.Headers);\n            Assert.Same(remoteFileURL, fileData.Location);\n            Assert.Same(fileName, fileData.FileName);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/MultipartStreamProviderTestBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Net.Http.Headers;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http\n{\n    public abstract class MultipartStreamProviderTestBase<TProvider> where TProvider : MultipartStreamProvider, new()\n    {\n        protected MultipartStreamProviderTestBase()\n        {\n        }\n\n        [Fact]\n        public void Contents_IsEmpty()\n        {\n            // Arrange\n            TProvider provider = new TProvider();\n\n            // Act\n            Collection<HttpContent> contents = provider.Contents;\n\n            // Assert\n            Assert.Empty(contents);\n        }\n\n        [Fact]\n        public void PostProcessing_ReturnsCompleteTask()\n        {\n            // Arrange\n            TProvider provider = new TProvider();\n\n            // Act\n            Task postProcessing = provider.ExecutePostProcessingAsync();\n\n            // Assert\n            Assert.Equal(TaskStatus.RanToCompletion, postProcessing.Status);\n        }\n\n        [Fact]\n        public void GetStream_ThrowsOnNullParent()\n        {\n            TProvider provider = new TProvider();\n            HttpContentHeaders headers = FormattingUtilities.CreateEmptyContentHeaders();\n\n            Assert.ThrowsArgumentNull(() => provider.GetStream(null, headers), \"parent\");\n        }\n\n        [Fact]\n        public void GetStream_ThrowsOnNullHeaders()\n        {\n            TProvider provider = new TProvider();\n            StringContent content = new StringContent(String.Empty);\n\n            Assert.ThrowsArgumentNull(() => provider.GetStream(content, null), \"headers\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/ObjectContentOfTTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Net.Http\n{\n    public class ObjectContentOfTTests\n    {\n        private MediaTypeHeaderValue _jsonHeaderValue = new MediaTypeHeaderValue(\"application/json\");\n\n        [Fact]\n        public void Constructor_WhenFormatterParameterIsNull_Throws()\n        {\n            Assert.ThrowsArgumentNull(() => new ObjectContent<string>(\"\", formatter: null), \"formatter\");\n            Assert.ThrowsArgumentNull(() => new ObjectContent<string>(\"\", formatter: null, mediaType: \"foo/bar\"), \"formatter\");\n            Assert.ThrowsArgumentNull(() => new ObjectContent<string>(\"\", formatter: null, mediaType: _jsonHeaderValue), \"formatter\");\n        }\n\n        [Fact]\n        public void Constructor_SetsFormatterProperty()\n        {\n            var formatterMock = new Mock<MediaTypeFormatter>();\n            formatterMock.Setup(f => f.CanWriteType(typeof(String))).Returns(true);\n            var formatter = formatterMock.Object;\n\n            var content = new ObjectContent<string>(null, formatter, mediaType: (MediaTypeHeaderValue)null);\n\n            Assert.Same(formatter, content.Formatter);\n        }\n\n        [Fact]\n        public void Constructor_CallsFormattersGetDefaultContentHeadersMethod()\n        {\n            var formatterMock = new Mock<MediaTypeFormatter>();\n            formatterMock.Setup(f => f.CanWriteType(typeof(String))).Returns(true);\n\n            var content = new ObjectContent(typeof(string), \"\", formatterMock.Object, _jsonHeaderValue);\n\n            formatterMock.Verify(f => f.SetDefaultContentHeaders(typeof(string), content.Headers, _jsonHeaderValue),\n                                 Times.Once());\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/ObjectContentTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Net.Http\n{\n    public class ObjectContentTests\n    {\n        private readonly object _value = new object();\n        private readonly MediaTypeFormatter _formatter = new TestableMediaTypeFormatter();\n        private readonly MediaTypeHeaderValue _jsonHeaderValue = new MediaTypeHeaderValue(\"application/json\");\n\n        [Fact]\n        public void Constructor_WhenTypeArgumentIsNull_ThrowsEsxception()\n        {\n            Assert.ThrowsArgumentNull(() => new ObjectContent(null, _value, _formatter), \"type\");\n            Assert.ThrowsArgumentNull(() => new ObjectContent(null, _value, _formatter, mediaType: \"foo/bar\"), \"type\");\n            Assert.ThrowsArgumentNull(() => new ObjectContent(null, _value, _formatter, mediaType: _jsonHeaderValue), \"type\");\n        }\n\n        [Fact]\n        public void Constructor_WhenFormatterArgumentIsNull_ThrowsEsxception()\n        {\n            Assert.ThrowsArgumentNull(() => new ObjectContent(typeof(Object), _value, formatter: null), \"formatter\");\n            Assert.ThrowsArgumentNull(() => new ObjectContent(typeof(Object), _value, formatter: null, mediaType: \"foo/bar\"), \"formatter\");\n            Assert.ThrowsArgumentNull(() => new ObjectContent(typeof(Object), _value, formatter: null, mediaType: _jsonHeaderValue), \"formatter\");\n        }\n\n        [Fact]\n        public void Constructor_WhenValueIsNullAndTypeIsNotCompatible_ThrowsException()\n        {\n            Assert.Throws<InvalidOperationException>(() =>\n            {\n                new ObjectContent(typeof(int), null, new JsonMediaTypeFormatter());\n            }, \"The 'ObjectContent' type cannot accept a null value for the value type 'Int32'.\");\n        }\n\n        [Fact]\n        public void Constructor_WhenValueIsNotNullButTypeDoesNotMatch_ThrowsException()\n        {\n            Assert.ThrowsArgument(() =>\n            {\n                new ObjectContent(typeof(IList<string>), new Dictionary<string, string>(), new JsonMediaTypeFormatter());\n            }, \"value\", \"An object of type 'Dictionary`2' cannot be used with a type parameter of 'IList`1'.\");\n        }\n\n        [Fact]\n        public void Constructor_WhenValueIsNotSupportedByFormatter_ThrowsException()\n        {\n            Mock<MediaTypeFormatter> formatterMock = new Mock<MediaTypeFormatter>();\n            formatterMock.Setup(f => f.CanWriteType(typeof(List<string>))).Returns(false).Verifiable();\n\n            Assert.Throws<InvalidOperationException>(() =>\n            {\n                new ObjectContent(typeof(List<string>), new List<string>(), formatterMock.Object);\n            }, \"The configured formatter 'Castle.Proxies.MediaTypeFormatterProxy' cannot write an object of type 'List`1'.\");\n\n            formatterMock.Verify();\n        }\n\n        [Fact]\n        public void Constructor_SetsFormatterProperty()\n        {\n            var content = new ObjectContent(typeof(object), _value, _formatter, mediaType: (MediaTypeHeaderValue)null);\n\n            Assert.Same(_formatter, content.Formatter);\n        }\n\n        [Fact]\n        public void Constructor_CallsFormattersGetDefaultContentHeadersMethod()\n        {\n            var formatterMock = new Mock<MediaTypeFormatter>();\n            formatterMock.Setup(f => f.CanWriteType(typeof(String))).Returns(true);\n\n            var content = new ObjectContent(typeof(string), \"\", formatterMock.Object, _jsonHeaderValue);\n\n            formatterMock.Verify(f => f.SetDefaultContentHeaders(typeof(string), content.Headers, _jsonHeaderValue),\n                                 Times.Once());\n        }\n\n        [Theory]\n        [PropertyData(\"ValidValueTypePairs\")]\n        public void Constructor_WhenValueAndTypeAreCompatible_SetsValue(Type type, object value)\n        {\n            var oc = new ObjectContent(type, value, new JsonMediaTypeFormatter());\n\n            Assert.Same(value, oc.Value);\n            Assert.Equal(type, oc.ObjectType);\n        }\n\n        [Fact]\n        public void Constructor_WhenTypeIsNotSupportedByFormatter_ThrowsException()\n        {\n            Mock<MediaTypeFormatter> formatterMock = new Mock<MediaTypeFormatter>();\n            formatterMock.Setup(f => f.CanWriteType(typeof(string))).Returns(true);\n            formatterMock.Setup(f => f.CanWriteType(typeof(object))).Returns(false).Verifiable();\n\n            Assert.Throws<InvalidOperationException>(() =>\n            {\n                var content = new ObjectContent(typeof(object), \"\", formatterMock.Object);\n            }, \"The configured formatter 'Castle.Proxies.MediaTypeFormatterProxy' cannot write an object of type 'Object'.\");\n\n            formatterMock.Verify();\n        }\n\n        public static TheoryDataSet<Type, object> ValidValueTypePairs\n        {\n            get\n            {\n                return new TheoryDataSet<Type, object>\n                {\n                    { typeof(Nullable<int>), null },\n                    { typeof(string), null },\n                    { typeof(int), 42 },\n                    //{ typeof(int), (short)42 }, TODO should this work?\n                    { typeof(object), \"abc\" },\n                    { typeof(string), \"abc\" },\n                    { typeof(IList<string>), new List<string>() },\n                };\n            }\n        }\n\n        [Fact]\n        public void SerializeToStreamAsync_CallsUnderlyingFormatter()\n        {\n            var stream = Stream.Null;\n            var context = new Mock<TransportContext>().Object;\n            var formatterMock = new Mock<TestableMediaTypeFormatter> { CallBase = true };\n            var oc = new TestableObjectContent(typeof(string), \"abc\", formatterMock.Object);\n            var task = new Task(() => { });\n            formatterMock.Setup(f => f.WriteToStreamAsync(typeof(string), \"abc\", stream, oc, context))\n                .Returns(task).Verifiable();\n\n            var result = oc.CallSerializeToStreamAsync(stream, context);\n\n            Assert.Same(task, result);\n            formatterMock.VerifyAll();\n        }\n\n        [Fact]\n        public void TryComputeLength_ReturnsFalseAnd0()\n        {\n            var oc = new TestableObjectContent(typeof(string), null, _formatter);\n            long length;\n\n            var result = oc.CallTryComputeLength(out length);\n\n            Assert.False(result);\n            Assert.Equal(-1, length);\n        }\n\n        public class TestableObjectContent : ObjectContent\n        {\n            public TestableObjectContent(Type type, object value, MediaTypeFormatter formatter)\n                : base(type, value, formatter)\n            {\n            }\n\n            public bool CallTryComputeLength(out long length)\n            {\n                return TryComputeLength(out length);\n            }\n\n            public Task CallSerializeToStreamAsync(Stream stream, TransportContext context)\n            {\n                return SerializeToStreamAsync(stream, context);\n            }\n        }\n\n        public class TestableMediaTypeFormatter : MediaTypeFormatter\n        {\n            public TestableMediaTypeFormatter()\n            {\n                SupportedMediaTypes.Add(new MediaTypeHeaderValue(\"application/json\"));\n            }\n\n            public override bool CanReadType(Type type)\n            {\n                return true;\n            }\n\n            public override bool CanWriteType(Type type)\n            {\n                return true;\n            }\n\n            public override Task WriteToStreamAsync(Type type, object value, Stream stream, HttpContent content, TransportContext transportContext)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/ParserData.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http.Headers;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http\n{\n    internal static class ParserData\n    {\n        public const int MinHeaderSize = 2;\n\n        public const int MinMessageSize = 10;\n\n        public const int MinRequestLineSize = 14;\n\n        public const int MinStatusLineSize = 15;\n\n        public const int MinBufferSize = 256;\n\n        public static TheoryDataSet<Version> Versions\n        {\n            get\n            {\n                return new TheoryDataSet<Version>\n                {\n                    Version.Parse(\"1.0\"),\n                    Version.Parse(\"1.1\"),\n                    Version.Parse(\"1.2\"),\n                    Version.Parse(\"2.0\"),\n                    Version.Parse(\"10.0\"),\n                    Version.Parse(\"1.15\"),\n                };\n            }\n        }\n\n        public static TheoryDataSet<string> InvalidVersions\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    \"\",\n                    \"http/1.1\",\n                    \"HTTP/a.1\",\n                    \"HTTP/1.a\",\n                    \"HTTP 1.1\",\n                    \"HTTP\\t1.1\",\n                    \"HTTP 1 1\",\n                    \"\\0\",\n                    \"HTTP\\01.1\",\n                    \"HTTP/4294967295.4294967295\",\n                    \"æææøøøååå\",\n                    \"HTTP/æææøøøååå\",\n                    \"いくつかのテキスト\",\n                    \"HTTP/いくつかのテキスト\",\n                };\n            }\n        }\n\n        public static TheoryDataSet<string> InvalidMethods\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    \"\",\n                    \"G\\tT\",\n                    \"G E T\",\n                    \"\\0\",\n                    \"G\\0T\",\n                    \"GET\\n\",\n                    \"æææøøøååå\",\n                    \"いくつかのテキスト\",\n                };\n            }\n        }\n\n        public static TheoryDataSet<string> ValidReasonPhrases\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    \"\",\n                    \"Ok\",\n                    \"public Server Error\",\n                    \"r e a s o n\",\n                    \"reason \",\n                    \" reason \",\n                };\n            }\n        }\n\n        public static TheoryDataSet<string> InvalidReasonPhrases\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    \"\\0\",\n                    \"\\t\",\n                    \"reason\\n\",\n                    \"æææøøøååå\",\n                    \"いくつかのテキスト\",\n                };\n            }\n        }\n\n        // This deliberately only checks for syntactic boundaries of the URI, not its content\n        public static TheoryDataSet<string> InvalidRequestUris\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    \"\",\n                    \"p a t h\",\n                    \"path \",\n                    \" path \",\n                    \"æææø ø øååå\",\n                    \"いくつか の テキスト\"\n                };\n            }\n        }\n\n        public static TheoryDataSet<string> InvalidStatusCodes\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    \"0\",\n                    \"99\",\n                    \"1a1\",\n                    \"abc\",\n                    \"1001\",\n                    \"2000\",\n                    Int32.MinValue.ToString(),\n                    Int32.MaxValue.ToString(),\n                    \"æææøøøååå\",\n                    \"いくつかのテキスト\"\n                };\n            }\n        }\n\n        public static readonly Dictionary<string, string> ValidHeaders = new Dictionary<string, string>\n        {\n            { \"N0\", \"V0\"},\n            { \"N1\", \"V1\"},\n            { \"N2\", \"V2\"},\n            { \"N3\", \"V3\"},\n            { \"N4\", \"V4\"},\n            { \"N5\", \"V5\"},\n            { \"N6\", \"V6\"},\n            { \"N7\", \"V7\"},\n            { \"N8\", \"V8\"},\n            { \"N9\", \"V9\"},\n        };\n\n        public static readonly string HttpMethod = \"TEG\";\n        public static readonly HttpStatusCode HttpStatus = HttpStatusCode.Created;\n        public static readonly string HttpReasonPhrase = \"ReasonPhrase\";\n        public static readonly string HttpHostName = \"example.com\";\n        public static readonly int HttpHostPort = 1234;\n        public static readonly string HttpMessageEntity = \"1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\";\n\n        public static readonly Uri HttpRequestUri = new Uri(\"http://\" + HttpHostName + \"/some/path\");\n        public static readonly Uri HttpRequestUriWithPortAndQuery = new Uri(\"http://\" + HttpHostName + \":\" + HttpHostPort + \"/some/path?%C3%A6%C3%B8%C3%A5\");\n        public static readonly Uri HttpsRequestUri = new Uri(\"https://\" + HttpHostName + \"/some/path\");\n\n        public static readonly string TextContentType = \"text/plain; charset=utf-8\";\n\n        public static readonly MediaTypeHeaderValue HttpRequestMediaType = MediaTypeHeaderValue.Parse(\"application/http; msgtype=request\");\n        public static readonly MediaTypeHeaderValue HttpResponseMediaType = MediaTypeHeaderValue.Parse(\"application/http; msgtype=response\");\n\n        public static readonly string HttpRequest =\n            HttpMethod +\n            \" /some/path HTTP/1.2\\r\\nHost: \" +\n            HttpHostName +\n            \"\\r\\nN1: V1a, V1b, V1c, V1d, V1e\\r\\nN2: V2\\r\\n\\r\\n\";\n\n        public static readonly string HttpRequestWithHost =\n            HttpMethod +\n            \" /some/path HTTP/1.2\\r\\n\" +\n            \"N1: V1a, V1b, V1c, V1d, V1e\\r\\nN2: V2\\r\\nHost: \" +\n            HttpHostName + \"\\r\\n\\r\\n\";\n\n        public static readonly string HttpRequestWithPortAndQuery =\n            HttpMethod +\n            \" /some/path?%C3%A6%C3%B8%C3%A5 HTTP/1.2\\r\\nHost: \" +\n            HttpHostName + \":\" + HttpHostPort.ToString() +\n            \"\\r\\nN1: V1a, V1b, V1c, V1d, V1e\\r\\nN2: V2\\r\\n\\r\\n\";\n\n        public static readonly string HttpResponse =\n            \"HTTP/1.2 \" +\n            ((int)HttpStatus).ToString() +\n            \" \" +\n            HttpReasonPhrase +\n            \"\\r\\nN1: V1a, V1b, V1c, V1d, V1e\\r\\nN2: V2\\r\\nContent-Length: 0\\r\\n\\r\\n\";\n\n        public static readonly string HttpRequestWithEntity =\n            HttpMethod +\n            \" /some/path HTTP/1.2\\r\\nHost: \" +\n            HttpHostName +\n            \"\\r\\nN1: V1a, V1b, V1c, V1d, V1e\\r\\nN2: V2\\r\\nContent-Type: \" +\n            TextContentType +\n            \"\\r\\nContent-Length: 100\" +\n            \"\\r\\n\\r\\n\" +\n            HttpMessageEntity;\n\n        public static readonly string HttpResponseWithEntity =\n            \"HTTP/1.2 \" +\n            ((int)HttpStatus).ToString() +\n            \" \" +\n            HttpReasonPhrase +\n            \"\\r\\nN1: V1a, V1b, V1c, V1d, V1e\\r\\nN2: V2\\r\\nContent-Type: \" +\n            TextContentType +\n            \"\\r\\nContent-Length: 100\" +\n            \"\\r\\n\\r\\n\" +\n            HttpMessageEntity;\n    }\n}"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/PushStreamContentTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Net.Http.Formatting;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Moq;\nusing Moq.Protected;\n\nnamespace System.Net.Http\n{\n    public class PushStreamContentTest\n    {\n        [Fact]\n        public void Constructor_ThrowsOnNullAction()\n        {\n            Action<Stream, HttpContent, TransportContext> action = null;\n            Assert.ThrowsArgumentNull(() => new PushStreamContent(action), \"onStreamAvailable\");\n        }\n\n        [Fact]\n        public void Constructor_SetsDefaultMediaType()\n        {\n            Action<Stream, HttpContent, TransportContext> streamAction = new MockStreamAction().Action;\n            PushStreamContent content = new PushStreamContent(streamAction);\n            Assert.Equal(MediaTypeConstants.ApplicationOctetStreamMediaType, content.Headers.ContentType);\n        }\n\n        [Fact]\n        public void Constructor_SetsMediaTypeFromString()\n        {\n            Action<Stream, HttpContent, TransportContext> streamAction = new MockStreamAction().Action;\n            PushStreamContent content = new PushStreamContent(streamAction, \"text/xml\");\n            Assert.Equal(MediaTypeConstants.TextXmlMediaType, content.Headers.ContentType);\n        }\n\n        [Fact]\n        public void Constructor_SetsMediaType()\n        {\n            Action<Stream, HttpContent, TransportContext> streamAction = new MockStreamAction().Action;\n            PushStreamContent content = new PushStreamContent(streamAction, MediaTypeConstants.TextXmlMediaType);\n            Assert.Equal(MediaTypeConstants.TextXmlMediaType, content.Headers.ContentType);\n        }\n\n        [Fact]\n        public async Task SerializeToStreamAsync_CallsAction()\n        {\n            // Arrange\n            MemoryStream outputStream = new MemoryStream();\n            MockStreamAction streamAction = new MockStreamAction(close: true);\n            PushStreamContent content = new PushStreamContent((Action<Stream, HttpContent, TransportContext>)streamAction.Action);\n\n            // Act\n            await content.CopyToAsync(outputStream);\n\n            // Assert\n            Assert.True(streamAction.WasInvoked);\n            Assert.Same(content, streamAction.Content);\n            Assert.IsType<PushStreamContent.CompleteTaskOnCloseStream>(streamAction.OutputStream);\n\n            // We don't close the underlying stream\n            Assert.True(outputStream.CanRead);\n        }\n\n        [Fact]\n        public async Task SerializeToStreamAsync_CompletesTaskOnActionException()\n        {\n            // Arrange\n            MemoryStream outputStream = new MemoryStream();\n            MockStreamAction streamAction = new MockStreamAction(throwException: true);\n            PushStreamContent content = new PushStreamContent((Action<Stream, HttpContent, TransportContext>)streamAction.Action);\n\n            // Act & Assert\n            await Assert.ThrowsAsync<ApplicationException>(() => content.CopyToAsync(outputStream));\n            Assert.True(streamAction.WasInvoked);\n            Assert.IsType<PushStreamContent.CompleteTaskOnCloseStream>(streamAction.OutputStream);\n            Assert.True(outputStream.CanRead);\n        }\n\n#if Testing_NetStandard1_3\n        [Fact]\n        public async Task CompleteTaskOnCloseStream_Dispose_CompletesTaskButDoNotDisposeInnerStream()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>() { CallBase = true };\n            TaskCompletionSource<bool> serializeToStreamTask = new TaskCompletionSource<bool>();\n            MockCompleteTaskOnCloseStream mockStream = new MockCompleteTaskOnCloseStream(mockInnerStream.Object, serializeToStreamTask);\n\n            // Act\n            mockStream.Dispose();\n\n            // Assert\n            mockInnerStream.Protected().Verify(\"Dispose\", Times.Never(), exactParameterMatch: true, args: true);\n            Assert.Equal(TaskStatus.RanToCompletion, serializeToStreamTask.Task.Status);\n            Assert.True(await serializeToStreamTask.Task);\n        }\n#else\n        [Fact]\n        public async Task CompleteTaskOnCloseStream_Dispose_CompletesTaskButDoNotCloseInnerStream()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>() { CallBase = true };\n            TaskCompletionSource<bool> serializeToStreamTask = new TaskCompletionSource<bool>();\n            MockCompleteTaskOnCloseStream mockStream = new MockCompleteTaskOnCloseStream(mockInnerStream.Object, serializeToStreamTask);\n\n            // Act\n            mockStream.Dispose();\n\n            // Assert\n            mockInnerStream.Protected().Verify(\"Dispose\", Times.Never(), exactParameterMatch: true, args: true);\n            mockInnerStream.Verify(s => s.Close(), Times.Never());\n            Assert.Equal(TaskStatus.RanToCompletion, serializeToStreamTask.Task.Status);\n            Assert.True(await serializeToStreamTask.Task);\n        }\n\n        [Fact]\n        public async Task NonClosingDelegatingStream_Close_CompletesTaskButDoNotCloseInnerStream()\n        {\n            // Arrange\n            Mock<Stream> mockInnerStream = new Mock<Stream>() { CallBase = true };\n            TaskCompletionSource<bool> serializeToStreamTask = new TaskCompletionSource<bool>();\n            MockCompleteTaskOnCloseStream mockStream = new MockCompleteTaskOnCloseStream(mockInnerStream.Object, serializeToStreamTask);\n\n            // Act\n            mockStream.Close();\n\n            // Assert\n            mockInnerStream.Protected().Verify(\"Dispose\", Times.Never(), exactParameterMatch: true, args: true);\n            mockInnerStream.Verify(s => s.Close(), Times.Never());\n            Assert.Equal(TaskStatus.RanToCompletion, serializeToStreamTask.Task.Status);\n            Assert.True(await serializeToStreamTask.Task);\n        }\n#endif\n\n        [Fact]\n        public async Task PushStreamContentWithAsyncOnStreamAvailableHandler_ExceptionsInOnStreamAvailable_AreCaught()\n        {\n            // Arrange\n            bool faulted = false;\n            Exception exception = new ApplicationException();\n            PushStreamContent content = new PushStreamContent(async (s, c, tc) =>\n            {\n                await Task.FromResult(42);\n                throw exception;\n            });\n            MemoryStream stream = new MemoryStream();\n\n            try\n            {\n                // Act\n                await content.CopyToAsync(stream);\n            }\n            catch (ApplicationException e)\n            {\n                Assert.Same(exception, e);\n                faulted = true;\n            }\n\n            // Assert\n            Assert.True(faulted);\n        }\n\n        [Fact]\n        public async Task PushStream_HttpContentIntegrationTest()\n        {\n            // Arrange\n            var expected = \"Hello, world!\";\n\n            using (var client = new MockHttpClient())\n            {\n                // We mock the client, so this doesn't actually hit the web. This client will just echo back\n                // the body content we give it.\n                using (var request = new HttpRequestMessage(HttpMethod.Post, \"http://localhost:30000/\"))\n                {\n                    request.Content = new PushStreamContent((stream, content, context) =>\n                    {\n                        using (var writer = new StreamWriter(stream))\n                        {\n                            writer.Write(expected);\n                        }\n                    }, \"text/plain\");\n\n                    // Act\n                    using (var response = await client.SendAsync(request, CancellationToken.None))\n                    {\n                        // Assert\n                        response.EnsureSuccessStatusCode();\n                        var responseText = await response.Content.ReadAsStringAsync();\n                        Assert.Equal(expected, responseText);\n                    }\n                }\n            }\n        }\n\n        private class MockStreamAction\n        {\n            bool _close;\n            bool _throwException;\n\n            public MockStreamAction(bool close = false, bool throwException = false)\n            {\n                _close = close;\n                _throwException = throwException;\n            }\n\n            public bool WasInvoked { get; private set; }\n\n            public Stream OutputStream { get; private set; }\n\n            public HttpContent Content { get; private set; }\n\n            public TransportContext TransportContext { get; private set; }\n\n            public void Action(Stream stream, HttpContent content, TransportContext context)\n            {\n                WasInvoked = true;\n                OutputStream = stream;\n                Content = content;\n                TransportContext = context;\n\n                if (_close)\n                {\n#if Testing_NetStandard1_3\n                    stream.Dispose();\n#else\n                    stream.Close();\n#endif\n                }\n\n                if (_throwException)\n                {\n                    throw new ApplicationException(\"Action threw exception!\");\n                }\n            }\n        }\n\n        internal class MockCompleteTaskOnCloseStream : PushStreamContent.CompleteTaskOnCloseStream\n        {\n            public MockCompleteTaskOnCloseStream(Stream innerStream, TaskCompletionSource<bool> serializeToStreamTask)\n                : base(innerStream, serializeToStreamTask)\n            {\n            }\n        }\n\n        private class MockHttpClient : HttpClient\n        {\n            public override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, Threading.CancellationToken cancellationToken)\n            {\n                var stream = new MemoryStream();\n                await request.Content.CopyToAsync(stream);\n                stream.Position = 0;\n\n                return new HttpResponseMessage(HttpStatusCode.OK)\n                {\n                    Content = new StreamContent(stream),\n                };\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/RemoteStreamInfoTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Net.Http.Headers;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http\n{\n    public class RemoteStreamInfoTests\n    {\n        [Fact]\n        public void Constructor_ThrowsOnNullStream()\n        {\n            // Arrange, Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => new RemoteStreamInfo(null,  \"http://some/path/to\", \"Name\"),\n                \"remoteStream\");\n        }\n\n        [Fact]\n        public void Constructor_ThrowsOnNullLocation()\n        {\n            // Arrange\n            HttpContentHeaders headers = FormattingUtilities.CreateEmptyContentHeaders();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => new RemoteStreamInfo(new MemoryStream(), null, \"Name\"), \"location\");\n        }\n\n        [Fact]\n        public void Constructor_ThrowsOnNullFileName()\n        {\n            // Arrange\n            HttpContentHeaders headers = FormattingUtilities.CreateEmptyContentHeaders();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => new RemoteStreamInfo(new MemoryStream(), \"http://some/path/to\", null),\n                \"fileName\");\n        }\n\n        [Fact]\n        public void Constructor_InitializesCorrectly()\n        {\n            // Arrange\n            HttpContentHeaders headers = FormattingUtilities.CreateEmptyContentHeaders();\n            string remoteFileURL = \"http://some/path/to\";\n            string fileName = \"Name\";\n            Stream stream = new MemoryStream();\n\n            // Act\n            RemoteStreamInfo fileData = new RemoteStreamInfo(stream, remoteFileURL, fileName);\n\n            // Assert\n            Assert.Same(stream, fileData.RemoteStream);\n            Assert.Same(remoteFileURL, fileData.Location);\n            Assert.Same(fileName, fileData.FileName);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/System.Net.Http.Formatting.Test.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" />\n  <Import Project=\"..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props\" Condition=\"Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" />\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{7AF77741-9158-4D5F-8782-8F21FADF025F}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>System.Net.Http</RootNamespace>\n    <AssemblyName>System.Net.Http.Formatting.Test</AssemblyName>\n    <OutputPath>..\\..\\bin\\$(Configuration)\\Test\\</OutputPath>\n    <NuGetPackageImportStamp>\n    </NuGetPackageImportStamp>\n    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Buffers, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\System.Buffers.4.5.1\\lib\\net461\\System.Buffers.dll</HintPath>\n      <SpecificVersion>False</SpecificVersion>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Data\" />\n    <Reference Include=\"System.IO.Pipelines, Version=4.0.2.4, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\System.IO.Pipelines.4.7.5\\lib\\net461\\System.IO.Pipelines.dll</HintPath>\n      <SpecificVersion>False</SpecificVersion>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"System.Memory, Version=4.0.1.2, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\System.Memory.4.5.5\\lib\\net461\\System.Memory.dll</HintPath>\n      <SpecificVersion>False</SpecificVersion>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"System.Net.Http\" />\n    <Reference Include=\"System.Net.Http.WebRequest\" />\n    <Reference Include=\"System.Runtime.CompilerServices.Unsafe, Version=4.0.6.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\System.Runtime.CompilerServices.Unsafe.4.7.1\\lib\\net461\\System.Runtime.CompilerServices.Unsafe.dll</HintPath>\n      <SpecificVersion>False</SpecificVersion>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"System.Runtime.Serialization\" />\n    <Reference Include=\"System.Threading.Tasks.Extensions, Version=4.2.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\System.Threading.Tasks.Extensions.4.5.4\\lib\\net461\\System.Threading.Tasks.Extensions.dll</HintPath>\n      <SpecificVersion>False</SpecificVersion>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"System.XML\" />\n    <Reference Include=\"System.Xml.Linq\" />\n\n    <Reference Include=\"Castle.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Castle.Core.5.1.1\\lib\\net462\\Castle.Core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Moq, Version=4.18.0.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Moq.4.18.4\\lib\\net462\\Moq.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Newtonsoft.Json.13.0.1\\lib\\net45\\Newtonsoft.Json.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Newtonsoft.Json.Bson, Version=1.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Newtonsoft.Json.Bson.1.0.2\\lib\\net45\\Newtonsoft.Json.Bson.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.abstractions.2.0.3\\lib\\net35\\xunit.abstractions.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.assert, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.assert.2.4.2\\lib\\netstandard1.1\\xunit.assert.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.core, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.core.2.4.2\\lib\\net452\\xunit.core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.execution.desktop, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.execution.2.4.2\\lib\\net452\\xunit.execution.desktop.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n\n    <CodeAnalysisDependentAssemblyPaths Condition=\" '$(VS100COMNTOOLS)' != '' \" Include=\"$(VS100COMNTOOLS)..\\IDE\\PrivateAssemblies\">\n      <Visible>False</Visible>\n    </CodeAnalysisDependentAssemblyPaths>\n\n    <Compile Include=\"**\\*.cs\" Exclude=\"obj\\**\\*.cs\" />\n\n    <ProjectReference Include=\"..\\..\\src\\System.Net.Http.Formatting\\System.Net.Http.Formatting.csproj\">\n      <Project>{668E9021-CE84-49D9-98FB-DF125A9FCDB0}</Project>\n      <Name>System.Net.Http.Formatting</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\">\n      <Project>{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}</Project>\n      <Name>Microsoft.TestCommon</Name>\n    </ProjectReference>\n\n    <None Include=\"packages.config\">\n      <SubType>Designer</SubType>\n    </None>\n\n    <Service Include=\"{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}\" />\n\n    <Analyzer Include=\"..\\..\\packages\\xunit.analyzers.1.1.0\\analyzers\\dotnet\\cs\\xunit.analyzers.dll\" />\n  </ItemGroup>\n\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets\"\n      Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" />\n  <Target Name=\"EnsureNuGetPackageBuildImports\" BeforeTargets=\"PrepareForBuild\">\n    <PropertyGroup>\n      <ErrorText>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}.</ErrorText>\n    </PropertyGroup>\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\"\n        Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\"\n        Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\"\n        Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props'))\" />\n  </Target>\n</Project>\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/UriExtensionsTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing System.Net.Http.Formatting.DataSets;\nusing Microsoft.TestCommon;\nusing Newtonsoft.Json.Linq;\n\nnamespace System.Net.Http\n{\n    public class UriExtensionsTests\n    {\n        private static readonly Uri TestAddress = new Uri(\"http://www.example.com\");\n        private static readonly Type TestType = typeof(string);\n\n        [Fact]\n        public void TypeIsCorrect()\n        {\n            Assert.Type.HasProperties(typeof(UriExtensions), TypeAssert.TypeProperties.IsPublicVisibleClass | TypeAssert.TypeProperties.IsStatic);\n        }\n\n        [Fact]\n        public void ParseQueryStringThrowsWithNull()\n        {\n            Assert.ThrowsArgumentNull(() => ((Uri)null).ParseQueryString(), \"address\");\n        }\n\n        [Theory]\n        [TestDataSet(typeof(HttpTestData), \"UriTestData\")]\n        public void ParseQueryStringSucceeds(Uri address)\n        {\n            var result = address.ParseQueryString();\n            Assert.NotNull(result);\n\n            bool addressContainsQuery = address.Query.Contains(\"?\");\n            if (!addressContainsQuery)\n            {\n                Assert.Empty(result);\n            }\n            else\n            {\n                Assert.True(result.Count > 0, \"Uri with query string should return non-empty set.\");\n            }\n        }\n\n        [Fact]\n        public void TryReadQueryAsJsonThrowsWithNull()\n        {\n            JObject value;\n            Assert.ThrowsArgumentNull(() => ((Uri)null).TryReadQueryAsJson(out value), \"address\");\n        }\n\n        [Theory]\n        [TestDataSet(typeof(HttpTestData), \"UriTestData\")]\n        public void TryReadQueryAsJsonSucceeds(Uri address)\n        {\n            JObject value;\n            Assert.True(address.TryReadQueryAsJson(out value), \"Expected 'true' as result\");\n            Assert.NotNull(value);\n            Assert.IsType<JObject>(value);\n        }\n\n        [Fact]\n        public void TryReadQueryAsThrowsWithNull()\n        {\n            object value;\n            Assert.ThrowsArgumentNull(() => ((Uri)null).TryReadQueryAs(TestType, out value), \"address\");\n            Assert.ThrowsArgumentNull(() => TestAddress.TryReadQueryAs(null, out value), \"type\");\n        }\n\n        [Fact]\n        public void TryReadQueryAsSucceeds()\n        {\n            object value;\n            UriBuilder address = new UriBuilder(\"http://some.host\");\n\n            address.Query = \"a=2\";\n            Assert.True(address.Uri.TryReadQueryAs(typeof(SimpleObject1), out value), \"Expected 'true' reading valid data\");\n            SimpleObject1 so1 = (SimpleObject1)value;\n            Assert.NotNull(so1);\n            Assert.Equal(2, so1.a);\n\n            address.Query = \"b=true\";\n            Assert.True(address.Uri.TryReadQueryAs(typeof(SimpleObject2), out value), \"Expected 'true' reading valid data\");\n            SimpleObject2 so2 = (SimpleObject2)value;\n            Assert.NotNull(so2);\n            Assert.True(so2.b, \"Value should have been true\");\n\n            address.Query = \"c=hello\";\n            Assert.True(address.Uri.TryReadQueryAs(typeof(SimpleObject3), out value), \"Expected 'true' reading valid data\");\n            SimpleObject3 so3 = (SimpleObject3)value;\n            Assert.NotNull(so3);\n            Assert.Equal(\"hello\", so3.c);\n\n            address.Query = \"c=\";\n            Assert.True(address.Uri.TryReadQueryAs(typeof(SimpleObject3), out value), \"Expected 'true' reading valid data\");\n            so3 = (SimpleObject3)value;\n            Assert.NotNull(so3);\n            Assert.Equal(\"\", so3.c);\n\n            address.Query = \"c=null\";\n            Assert.True(address.Uri.TryReadQueryAs(typeof(SimpleObject3), out value), \"Expected 'true' reading valid data\");\n            so3 = (SimpleObject3)value;\n            Assert.NotNull(so3);\n            Assert.Equal(\"null\", so3.c);\n        }\n\n        [Fact]\n        public void TryReadQueryAsTThrowsWithNull()\n        {\n            object value;\n            Assert.ThrowsArgumentNull(() => ((Uri)null).TryReadQueryAs<object>(out value), \"address\");\n        }\n\n        [Fact]\n        public void TryReadQueryAsTSucceeds()\n        {\n            UriBuilder address = new UriBuilder(\"http://some.host\");\n            address.Query = \"a=2\";\n            SimpleObject1 so1;\n            Assert.True(address.Uri.TryReadQueryAs<SimpleObject1>(out so1), \"Expected 'true' reading valid data\");\n            Assert.NotNull(so1);\n            Assert.Equal(2, so1.a);\n\n            address.Query = \"b=true\";\n            SimpleObject2 so2;\n            Assert.True(address.Uri.TryReadQueryAs<SimpleObject2>(out so2), \"Expected 'true' reading valid data\");\n            Assert.NotNull(so2);\n            Assert.True(so2.b, \"Value should have been true\");\n\n            address.Query = \"c=hello\";\n            SimpleObject3 so3;\n            Assert.True(address.Uri.TryReadQueryAs<SimpleObject3>(out so3), \"Expected 'true' reading valid data\");\n            Assert.NotNull(so3);\n            Assert.Equal(\"hello\", so3.c);\n\n            address.Query = \"c=\";\n            Assert.True(address.Uri.TryReadQueryAs<SimpleObject3>(out so3), \"Expected 'true' reading valid data\");\n            Assert.NotNull(so3);\n            Assert.Equal(\"\", so3.c);\n\n            address.Query = \"c=null\";\n            Assert.True(address.Uri.TryReadQueryAs<SimpleObject3>(out so3), \"Expected 'true' reading valid data\");\n            Assert.NotNull(so3);\n            Assert.Equal(\"null\", so3.c);\n        }\n\n\n        public class SimpleObject1\n        {\n            public int a { get; set; }\n        }\n\n        public class SimpleObject2\n        {\n            public bool b { get; set; }\n        }\n\n        public class SimpleObject3\n        {\n            public string c { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/UriQueryDataSet.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http\n{\n    public class UriQueryTestData\n    {\n        public static TheoryDataSet<string, string, string> UriQueryData\n        {\n            get\n            {\n                return new TheoryDataSet<string, string, string>\n                {\n                    { \"=\", \"\", \"\" },\n                    { \"N=\", \"N\", \"\" },\n                    { \"=N\", \"\", \"N\" },\n                    { \"N=V\", \"N\", \"V\" },\n                    { \"%26=%26\", \"&\", \"&\" },\n                    { \"%3D=%3D\", \"=\", \"=\" },\n                    { \"N=A%2BC\", \"N\", \"A+C\" },\n                    { \"N=100%25AA%21\", \"N\", \"100%AA!\"},\n                    { \"N=%7E%21%40%23%24%25%5E%26%2A%28%29_%2B\",\"N\",\"~!@#$%^&*()_+\"},\n                    { \"N=%601234567890-%3D\", \"N\", \"`1234567890-=\"},\n                    { \"N=%60%31%32%33%34%35%36%37%38%39%30%2D%3D\",\"N\", \"`1234567890-=\"},\n                    { \"N=%E6%BF%80%E5%85%89%E9%80%99%E5%85%A9%E5%80%8B%E5%AD%97%E6%98%AF%E7%94%9A%E9%BA%BC%E6%84%8F%E6%80%9D\", \"N\", \"激光這兩個字是甚麼意思\" },\n                    { \"N=%C3%A6%C3%B8%C3%A5\",\"N\",\"æøå\"},\n                    { \"N=%C3%A6+%C3%B8+%C3%A5\",\"N\",\"æ ø å\"},\n                };\n            }\n        }\n    }\n}"
  },
  {
    "path": "test/System.Net.Http.Formatting.Test/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Castle.Core\" version=\"5.1.1\" targetFramework=\"net462\" />\n  <package id=\"Moq\" version=\"4.18.4\" targetFramework=\"net462\" />\n  <package id=\"Newtonsoft.Json\" version=\"13.0.1\" targetFramework=\"net462\" />\n  <package id=\"Newtonsoft.Json.Bson\" version=\"1.0.2\" targetFramework=\"net462\" />\n  <package id=\"System.Buffers\" version=\"4.5.1\" targetFramework=\"net462\" />\n  <package id=\"System.IO.Pipelines\" version=\"4.7.5\" targetFramework=\"net462\" />\n  <package id=\"System.Memory\" version=\"4.5.5\" targetFramework=\"net462\" />\n  <package id=\"System.Runtime.CompilerServices.Unsafe\" version=\"4.7.1\" targetFramework=\"net462\" />\n  <package id=\"System.Threading.Tasks.Extensions\" version=\"4.5.4\" targetFramework=\"net462\" />\n  <package id=\"xunit\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.abstractions\" version=\"2.0.3\" targetFramework=\"net462\" />\n  <package id=\"xunit.analyzers\" version=\"1.1.0\" targetFramework=\"net462\" />\n  <package id=\"xunit.assert\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.execution\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.runner.visualstudio\" version=\"2.4.5\" targetFramework=\"net462\" developmentDependency=\"true\" />\n</packages>"
  },
  {
    "path": "test/System.Net.Http.Formatting.ns1_3.Test/System.Net.Http.Formatting.ns1_3.Test.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <TargetFrameworks>net462;netcoreapp2.1;net8.0</TargetFrameworks>\n    <RootNamespace>System.Net.Http</RootNamespace>\n    <OutputPath>..\\..\\bin\\$(Configuration)\\Test\\ns1_3\\</OutputPath>\n    <Configurations>$(Configurations);CodeAnalysis</Configurations>\n    <GenerateAssemblyInfo>false</GenerateAssemblyInfo>\n    <DefineConstants>$(DefineConstants);Testing_NetStandard1_3</DefineConstants>\n    <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>\n    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\n\n    <!-- Version 2.4.5 does not support netstandard2.1. -->\n    <_VSRunnerVersion Condition=\" '$(TargetFramework)' == 'netcoreapp2.1' \">2.4.3</_VSRunnerVersion>\n    <_VSRunnerVersion Condition=\" '$(TargetFramework)' != 'netcoreapp2.1' \">2.4.5</_VSRunnerVersion>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <PackageReference Include=\"System.IO.Pipelines\" Version=\"4.7.5\" />\n    <PackageReference Include=\"System.Net.Http\" Version=\"4.3.4\"\n        Condition=\" '$(TargetFrameworkIdentifier)' == '.NETFramework' \" />\n\n    <PackageReference Include=\"Microsoft.NET.Test.Sdk\" Version=\"16.11.0\" />\n    <PackageReference Include=\"Moq\" Version=\"4.18.4\" />\n    <PackageReference Include=\"xunit\" Version=\"2.4.2\" />\n    <PackageReference Include=\"xunit.analyzers\" Version=\"1.1.0\" />\n    <PackageReference Include=\"xunit.runner.visualstudio\" Version=\"$(_VSRunnerVersion)\">\n      <PrivateAssets>all</PrivateAssets>\n      <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>\n    </PackageReference>\n    <PackageReference Include=\"XunitXml.TestLogger\" Version=\"3.0.70\" />\n\n    <Compile Include=\"..\\System.Net.Http.Formatting.Test\\**\\*.cs\"\n        Exclude=\"..\\System.Net.Http.Formatting.Test\\obj\\**\\*.cs;\n                 ..\\System.Net.Http.Formatting.Test\\Formatting\\BufferedMediaTypeFormatterTests.cs;\n                 ..\\System.Net.Http.Formatting.Test\\Handlers\\ProgressWriteAsyncResultTest.cs\">\n      <Link>%(RecursiveDir)\\%(Filename).cs</Link>\n    </Compile>\n\n    <ProjectReference Include=\"..\\..\\src\\System.Net.Http.Formatting.ns1_3\\System.Net.Http.Formatting.ns1_3.csproj\" />\n    <ProjectReference Include=\"..\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\" Properties=\"Testing_NetStandard1_3=true\" />\n\n    <Service Include=\"{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}\" />\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "test/System.Net.Http.Formatting.ns2_0.Test/System.Net.Http.Formatting.ns2_0.Test.csproj",
    "content": "﻿<Project Sdk=\"Microsoft.NET.Sdk\">\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <TargetFrameworks>net462;netcoreapp2.1;net8.0</TargetFrameworks>\n    <RootNamespace>System.Net.Http</RootNamespace>\n    <OutputPath>..\\..\\bin\\$(Configuration)\\Test\\ns2_0\\</OutputPath>\n    <Configurations>$(Configurations);CodeAnalysis</Configurations>\n    <GenerateAssemblyInfo>false</GenerateAssemblyInfo>\n    <DefineConstants>$(DefineConstants);Testing_NetStandard2_0</DefineConstants>\n    <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>\n    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\n\n    <!-- Version 2.4.5 does not support netstandard2.1. -->\n    <_VSRunnerVersion Condition=\" '$(TargetFramework)' == 'netcoreapp2.1' \">2.4.3</_VSRunnerVersion>\n    <_VSRunnerVersion Condition=\" '$(TargetFramework)' != 'netcoreapp2.1' \">2.4.5</_VSRunnerVersion>\n  </PropertyGroup>\n\n  <ItemGroup>\n    <PackageReference Include=\"System.IO.Pipelines\" Version=\"4.7.5\" />\n\n    <PackageReference Include=\"Microsoft.NET.Test.Sdk\" Version=\"16.11.0\" />\n    <PackageReference Include=\"Moq\" Version=\"4.18.4\" />\n    <PackageReference Include=\"xunit\" Version=\"2.4.2\" />\n    <PackageReference Include=\"xunit.analyzers\" Version=\"1.1.0\" />\n    <PackageReference Include=\"xunit.runner.visualstudio\" Version=\"$(_VSRunnerVersion)\">\n      <PrivateAssets>all</PrivateAssets>\n      <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>\n    </PackageReference>\n    <PackageReference Include=\"XunitXml.TestLogger\" Version=\"3.0.70\" />\n\n    <Compile Include=\"..\\System.Net.Http.Formatting.Test\\**\\*.cs\"\n        Exclude=\"..\\System.Net.Http.Formatting.Test\\obj\\**\\*.cs\">\n      <Link>%(RecursiveDir)\\%(Filename).cs</Link>\n    </Compile>\n\n    <ProjectReference Include=\"..\\..\\src\\System.Net.Http.Formatting.ns2_0\\System.Net.Http.Formatting.ns2_0.csproj\" />\n    <ProjectReference Include=\"..\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\" />\n\n    <Service Include=\"{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}\" />\n  </ItemGroup>\n</Project>\n"
  },
  {
    "path": "test/System.Web.Cors.Test/CorsEngineTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Cors.Test\n{\n    public class CorsEngineTest\n    {\n        [Fact]\n        public void EvaluatePolicy_NullRequest_Throws()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n\n            Assert.ThrowsArgumentNull(() =>\n                corsEngine.EvaluatePolicy(null, new CorsPolicy()),\n                \"requestContext\");\n        }\n\n        [Fact]\n        public void EvaluatePolicy_NullPolicy_Throws()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n\n            Assert.ThrowsArgumentNull(() =>\n                corsEngine.EvaluatePolicy(new CorsRequestContext(), null),\n                \"policy\");\n        }\n\n        [Fact]\n        public void EvaluatePolicy_NoOrigin_ReturnsInvalidResult()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n            CorsRequestContext requestContext = new CorsRequestContext\n            {\n                Origin = null,\n                HttpMethod = \"GET\"\n            };\n\n            CorsResult result = corsEngine.EvaluatePolicy(requestContext, new CorsPolicy());\n\n            Assert.False(result.IsValid);\n            Assert.Contains(\"The request does not contain the Origin header.\", result.ErrorMessages);\n        }\n\n        [Fact]\n        public void EvaluatePolicy_NoMatchingOrigin_ReturnsInvalidResult()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n            CorsRequestContext requestContext = new CorsRequestContext\n            {\n                Origin = \"foo\"\n            };\n            CorsPolicy policy = new CorsPolicy();\n            policy.Origins.Add(\"bar\");\n\n            CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy);\n\n            Assert.False(result.IsValid);\n            Assert.Contains(\"The origin 'foo' is not allowed.\", result.ErrorMessages);\n        }\n\n        [Fact]\n        public void EvaluatePolicy_EmptyOriginsPolicy_ReturnsInvalidResult()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n            CorsRequestContext requestContext = new CorsRequestContext\n            {\n                Origin = \"foo\"\n            };\n            CorsPolicy policy = new CorsPolicy();\n\n            CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy);\n\n            Assert.False(result.IsValid);\n            Assert.Contains(\"The origin 'foo' is not allowed.\", result.ErrorMessages);\n        }\n\n        [Fact]\n        public void EvaluatePolicy_AllowAnyOrigin_DoesNotSupportCredentials_EmitsWildcardForOrigin()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n            CorsRequestContext requestContext = new CorsRequestContext\n            {\n                Origin = \"foo\"\n            };\n            CorsPolicy policy = new CorsPolicy\n            {\n                AllowAnyOrigin = true,\n                SupportsCredentials = false\n            };\n\n            CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy);\n\n            Assert.Equal(\"*\", result.AllowedOrigin);\n        }\n\n        [Fact]\n        public void EvaluatePolicy_AllowAnyOrigin_SupportsCredentials_AddsSpecificOrigin()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n            CorsRequestContext requestContext = new CorsRequestContext\n            {\n                Origin = \"foo\"\n            };\n            CorsPolicy policy = new CorsPolicy\n            {\n                AllowAnyOrigin = true,\n                SupportsCredentials = true\n            };\n\n            CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy);\n\n            Assert.Equal(\"foo\", result.AllowedOrigin);\n        }\n\n        [Fact]\n        public void EvaluatePolicy_DoesNotSupportCredentials_AllowCredentialsReturnsFalse()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n            CorsRequestContext requestContext = new CorsRequestContext\n            {\n                Origin = \"foo\"\n            };\n            CorsPolicy policy = new CorsPolicy\n            {\n                AllowAnyOrigin = true,\n                SupportsCredentials = false\n            };\n\n            CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy);\n\n            Assert.False(result.SupportsCredentials);\n        }\n\n        [Fact]\n        public void EvaluatePolicy_SupportsCredentials_AllowCredentialsReturnsTrue()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n            CorsRequestContext requestContext = new CorsRequestContext\n            {\n                Origin = \"foo\"\n            };\n            CorsPolicy policy = new CorsPolicy\n            {\n                AllowAnyOrigin = true,\n                SupportsCredentials = true\n            };\n\n            CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy);\n\n            Assert.True(result.SupportsCredentials);\n        }\n\n        [Fact]\n        public void EvaluatePolicy_NoExposedHeaders_NoAllowExposedHeaders()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n            CorsRequestContext requestContext = new CorsRequestContext\n            {\n                Origin = \"foo\"\n            };\n            CorsPolicy policy = new CorsPolicy\n            {\n                AllowAnyOrigin = true\n            };\n\n            CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy);\n\n            Assert.Empty(result.AllowedExposedHeaders);\n        }\n\n        [Fact]\n        public void EvaluatePolicy_OneExposedHeaders_HeadersAllowed()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n            CorsRequestContext requestContext = new CorsRequestContext\n            {\n                Origin = \"foo\"\n            };\n            CorsPolicy policy = new CorsPolicy\n            {\n                AllowAnyOrigin = true\n            };\n            policy.ExposedHeaders.Add(\"foo\");\n\n            CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy);\n\n            Assert.Equal(1, result.AllowedExposedHeaders.Count);\n            Assert.Contains(\"foo\", result.AllowedExposedHeaders);\n        }\n\n        [Fact]\n        public void EvaluatePolicy_ManyExposedHeaders_HeadersAllowed()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n            CorsRequestContext requestContext = new CorsRequestContext\n            {\n                Origin = \"foo\"\n            };\n            CorsPolicy policy = new CorsPolicy\n            {\n                AllowAnyOrigin = true\n            };\n            policy.ExposedHeaders.Add(\"foo\");\n            policy.ExposedHeaders.Add(\"bar\");\n            policy.ExposedHeaders.Add(\"baz\");\n\n            CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy);\n\n            Assert.Equal(3, result.AllowedExposedHeaders.Count());\n            Assert.Contains(\"foo\", result.AllowedExposedHeaders);\n            Assert.Contains(\"bar\", result.AllowedExposedHeaders);\n            Assert.Contains(\"baz\", result.AllowedExposedHeaders);\n        }\n\n        [Fact]\n        public void EvaluatePolicy_PreflightRequest_MethodNotAllowed_ReturnsInvalidResult()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n            CorsRequestContext requestContext = new CorsRequestContext\n            {\n                HttpMethod = \"OPTIONS\",\n                AccessControlRequestMethod = \"PUT\",\n                Origin = \"foo\"\n            };\n            CorsPolicy policy = new CorsPolicy\n            {\n                AllowAnyOrigin = true\n            };\n            policy.Methods.Add(\"GET\");\n\n            CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy);\n\n            Assert.True(requestContext.IsPreflight);\n            Assert.False(result.IsValid);\n            Assert.Contains(\"The method 'PUT' is not allowed.\", result.ErrorMessages);\n        }\n\n        [Fact]\n        public void EvaluatePolicy_PreflightRequest_MethodAllowed_ReturnsAllowMethods()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n            CorsRequestContext requestContext = new CorsRequestContext\n            {\n                HttpMethod = \"OPTIONS\",\n                AccessControlRequestMethod = \"PUT\",\n                Origin = \"foo\"\n            };\n            CorsPolicy policy = new CorsPolicy\n            {\n                AllowAnyOrigin = true\n            };\n            policy.Methods.Add(\"PUT\");\n\n            CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy);\n\n            Assert.True(requestContext.IsPreflight);\n            Assert.NotNull(result);\n            Assert.Contains(\"PUT\", result.AllowedMethods);\n        }\n\n        [Fact]\n        public void EvaluatePolicy_PreflightRequest_OriginAllowed_ReturnsOrigin()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n            CorsRequestContext requestContext = new CorsRequestContext\n            {\n                HttpMethod = \"OPTIONS\",\n                AccessControlRequestMethod = \"PUT\",\n                Origin = \"foo\"\n            };\n            CorsPolicy policy = new CorsPolicy\n            {\n                AllowAnyMethod = true\n            };\n            policy.Origins.Add(\"foo\");\n\n            CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy);\n\n            Assert.True(requestContext.IsPreflight);\n            Assert.Equal(\"foo\", result.AllowedOrigin);\n        }\n\n        [Fact]\n        public void EvaluatePolicy_PreflightRequest_SupportsCredentials_AllowCredentialsReturnsTrue()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n            CorsRequestContext requestContext = new CorsRequestContext\n            {\n                HttpMethod = \"OPTIONS\",\n                AccessControlRequestMethod = \"PUT\",\n                Origin = \"foo\",\n            };\n            CorsPolicy policy = new CorsPolicy\n            {\n                AllowAnyOrigin = true,\n                AllowAnyMethod = true,\n                SupportsCredentials = true\n            };\n\n            CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy);\n\n            Assert.True(requestContext.IsPreflight);\n            Assert.True(result.SupportsCredentials);\n        }\n\n        [Fact]\n        public void EvaluatePolicy_PreflightRequest_NoPreflightMaxAge_NoPreflightMaxAgeSet()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n            CorsRequestContext requestContext = new CorsRequestContext\n            {\n                HttpMethod = \"OPTIONS\",\n                AccessControlRequestMethod = \"PUT\",\n                Origin = \"foo\",\n            };\n            CorsPolicy policy = new CorsPolicy\n            {\n                AllowAnyOrigin = true,\n                AllowAnyMethod = true,\n                PreflightMaxAge = null\n            };\n\n            CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy);\n\n            Assert.True(requestContext.IsPreflight);\n            Assert.Null(result.PreflightMaxAge);\n        }\n\n        [Fact]\n        public void EvaluatePolicy_PreflightRequest_PreflightMaxAge_PreflightMaxAgeSet()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n            CorsRequestContext requestContext = new CorsRequestContext\n            {\n                HttpMethod = \"OPTIONS\",\n                AccessControlRequestMethod = \"PUT\",\n                Origin = \"foo\",\n            };\n            CorsPolicy policy = new CorsPolicy\n            {\n                AllowAnyOrigin = true,\n                AllowAnyMethod = true,\n                PreflightMaxAge = 10\n            };\n\n            CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy);\n\n            Assert.True(requestContext.IsPreflight);\n            Assert.Equal(10, result.PreflightMaxAge);\n        }\n\n        [Fact]\n        public void EvaluatePolicy_PreflightRequest_AnyMethod_ReturnsRequestMethod()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n            CorsRequestContext requestContext = new CorsRequestContext\n            {\n                HttpMethod = \"OPTIONS\",\n                AccessControlRequestMethod = \"GET\",\n                Origin = \"foo\"\n            };\n            CorsPolicy policy = new CorsPolicy\n            {\n                AllowAnyOrigin = true,\n                AllowAnyMethod = true\n            };\n\n            CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy);\n\n            Assert.True(requestContext.IsPreflight);\n            Assert.Equal(1, result.AllowedMethods.Count);\n            Assert.Contains(\"GET\", result.AllowedMethods);\n        }\n\n        [Fact]\n        public void EvaluatePolicy_PreflightRequest_ListedMethod_ReturnsSubsetOfListedMethods()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n            CorsRequestContext requestContext = new CorsRequestContext\n            {\n                HttpMethod = \"OPTIONS\",\n                AccessControlRequestMethod = \"PUT\",\n                Origin = \"foo\"\n            };\n            CorsPolicy policy = new CorsPolicy\n            {\n                AllowAnyOrigin = true\n            };\n            policy.Methods.Add(\"PUT\");\n            policy.Methods.Add(\"DELETE\");\n\n            CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy);\n\n            Assert.True(requestContext.IsPreflight);\n            Assert.Single(result.AllowedMethods);\n            Assert.Contains(\"PUT\", result.AllowedMethods);\n        }\n\n        [Fact]\n        public void EvaluatePolicy_PreflightRequest_NoHeadersRequested_AllowedAllHeaders_ReturnsEmptyHeaders()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n            CorsRequestContext requestContext = new CorsRequestContext\n            {\n                HttpMethod = \"OPTIONS\",\n                AccessControlRequestMethod = \"PUT\",\n                Origin = \"foo\",\n            };\n            CorsPolicy policy = new CorsPolicy\n            {\n                AllowAnyOrigin = true,\n                AllowAnyMethod = true,\n                AllowAnyHeader = true\n            };\n\n            CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy);\n\n            Assert.True(requestContext.IsPreflight);\n            Assert.Empty(result.AllowedHeaders);\n        }\n\n        [Fact]\n        public void EvaluatePolicy_PreflightRequest_HeadersRequested_AllowAllHeaders_ReturnsRequestedHeaders()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n            CorsRequestContext requestContext = new CorsRequestContext\n            {\n                HttpMethod = \"OPTIONS\",\n                AccessControlRequestMethod = \"PUT\",\n                Origin = \"foo\"\n            };\n            requestContext.AccessControlRequestHeaders.Add(\"foo\");\n            requestContext.AccessControlRequestHeaders.Add(\"bar\");\n            CorsPolicy policy = new CorsPolicy\n            {\n                AllowAnyOrigin = true,\n                AllowAnyHeader = true,\n                AllowAnyMethod = true\n            };\n\n            CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy);\n\n            Assert.True(requestContext.IsPreflight);\n            Assert.Equal(2, result.AllowedHeaders.Count());\n            Assert.Contains(\"foo\", result.AllowedHeaders);\n            Assert.Contains(\"bar\", result.AllowedHeaders);\n        }\n\n        [Fact]\n        public void EvaluatePolicy_PreflightRequest_HeadersRequested_AllowSomeHeaders_ReturnsSubsetOfListedHeaders()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n            CorsRequestContext requestContext = new CorsRequestContext\n            {\n                HttpMethod = \"OPTIONS\",\n                AccessControlRequestMethod = \"PUT\",\n                Origin = \"foo\"\n            };\n            requestContext.AccessControlRequestHeaders.Add(\"Content-Type\");\n            CorsPolicy policy = new CorsPolicy\n            {\n                AllowAnyOrigin = true,\n                AllowAnyMethod = true\n            };\n            policy.Headers.Add(\"foo\");\n            policy.Headers.Add(\"bar\");\n            policy.Headers.Add(\"Content-Type\");\n\n            CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy);\n\n            Assert.True(requestContext.IsPreflight);\n            Assert.Equal(1, result.AllowedHeaders.Count);\n            Assert.Contains(\"Content-Type\", result.AllowedHeaders);\n        }\n\n        [Fact]\n        public void EvaluatePolicy_PreflightRequest_HeadersRequested_NotAllHeaderMatches_ReturnsInvalidResult()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n            CorsRequestContext requestContext = new CorsRequestContext\n            {\n                HttpMethod = \"OPTIONS\",\n                AccessControlRequestMethod = \"PUT\",\n                Origin = \"foo\"\n            };\n            requestContext.AccessControlRequestHeaders.Add(\"match\");\n            requestContext.AccessControlRequestHeaders.Add(\"noMatch\");\n            CorsPolicy policy = new CorsPolicy\n            {\n                AllowAnyOrigin = true,\n                AllowAnyMethod = true\n            };\n            policy.Headers.Add(\"match\");\n            policy.Headers.Add(\"foo\");\n\n            CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy);\n\n            Assert.True(requestContext.IsPreflight);\n            Assert.False(result.IsValid);\n            Assert.Contains(\"The collection of headers 'match,noMatch' is not allowed.\", result.ErrorMessages);\n        }\n\n        [Fact]\n        public void TryValidateMethod_NullPolicy_Throws()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n\n            Assert.ThrowsArgumentNull(() =>\n                corsEngine.TryValidateMethod(new CorsRequestContext(), null, new CorsResult()),\n                \"policy\");\n        }\n\n        [Fact]\n        public void TryValidateMethod_NullRequestContext_Throws()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n\n            Assert.ThrowsArgumentNull(() =>\n                corsEngine.TryValidateMethod(null, new CorsPolicy(), new CorsResult()),\n                \"requestContext\");\n        }\n\n        [Fact]\n        public void TryValidateMethod_NullResult_Throws()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n\n            Assert.ThrowsArgumentNull(() =>\n                corsEngine.TryValidateMethod(new CorsRequestContext(), new CorsPolicy(), null),\n                \"result\");\n        }\n\n        [Fact]\n        public void TryValidateMethod_DoesCaseSensitiveComparison()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n\n            CorsPolicy policy = new CorsPolicy();\n            policy.Methods.Add(\"POST\");\n            CorsResult result = new CorsResult();\n\n            bool isValid = corsEngine.TryValidateMethod(new CorsRequestContext { AccessControlRequestMethod = \"post\" }, policy, result);\n            Assert.False(isValid);\n            Assert.Equal(1, result.ErrorMessages.Count);\n            Assert.Equal(\"The method 'post' is not allowed.\", result.ErrorMessages[0]);\n        }\n\n        [Fact]\n        public void TryValidateHeaders_NullPolicy_Throws()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n\n            Assert.ThrowsArgumentNull(() =>\n                corsEngine.TryValidateHeaders(new CorsRequestContext(), null, new CorsResult()),\n                \"policy\");\n        }\n\n        [Fact]\n        public void TryValidateHeaders_NullRequestContext_Throws()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n\n            Assert.ThrowsArgumentNull(() =>\n                corsEngine.TryValidateHeaders(null, new CorsPolicy(), new CorsResult()),\n                \"requestContext\");\n        }\n\n        [Fact]\n        public void TryValidateHeaders_NullResult_Throws()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n\n            Assert.ThrowsArgumentNull(() =>\n                corsEngine.TryValidateHeaders(new CorsRequestContext(), new CorsPolicy(), null),\n                \"result\");\n        }\n\n        [Fact]\n        public void TryValidateOrigin_NullPolicy_Throws()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n\n            Assert.ThrowsArgumentNull(() =>\n                corsEngine.TryValidateOrigin(new CorsRequestContext(), null, new CorsResult()),\n                \"policy\");\n        }\n\n        [Fact]\n        public void TryValidateOrigin_NullRequestContext_Throws()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n\n            Assert.ThrowsArgumentNull(() =>\n                corsEngine.TryValidateOrigin(null, new CorsPolicy(), new CorsResult()),\n                \"requestContext\");\n        }\n\n        [Fact]\n        public void TryValidateOrigin_NullResult_Throws()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n\n            Assert.ThrowsArgumentNull(() =>\n                corsEngine.TryValidateOrigin(new CorsRequestContext(), new CorsPolicy(), null),\n                \"result\");\n        }\n\n        [Fact]\n        public void TryValidateOrigin_DoesCaseSensitiveComparison()\n        {\n            CorsEngine corsEngine = new CorsEngine();\n\n            CorsPolicy policy = new CorsPolicy();\n            policy.Origins.Add(\"http://Example.com\");\n            CorsResult result = new CorsResult();\n\n            bool isValid = corsEngine.TryValidateOrigin(new CorsRequestContext { Origin = \"http://example.com\" }, policy, result);\n            Assert.False(isValid);\n            Assert.Equal(1, result.ErrorMessages.Count);\n            Assert.Equal(\"The origin 'http://example.com' is not allowed.\", result.ErrorMessages[0]);\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Cors.Test/CorsPolicyTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Cors.Test\n{\n    public class CorsPolicyTest\n    {\n        [Fact]\n        public void Default_Constructor()\n        {\n            CorsPolicy corsPolicy = new CorsPolicy();\n\n            Assert.False(corsPolicy.AllowAnyHeader);\n            Assert.False(corsPolicy.AllowAnyMethod);\n            Assert.False(corsPolicy.AllowAnyOrigin);\n            Assert.False(corsPolicy.SupportsCredentials);\n            Assert.Empty(corsPolicy.ExposedHeaders);\n            Assert.Empty(corsPolicy.Headers);\n            Assert.Empty(corsPolicy.Methods);\n            Assert.Empty(corsPolicy.Origins);\n            Assert.Null(corsPolicy.PreflightMaxAge);\n        }\n\n        [Fact]\n        public void SettingNegativePreflightMaxAge_Throws()\n        {\n            CorsPolicy corsPolicy = new CorsPolicy();\n            Assert.ThrowsArgumentOutOfRange(() =>\n            {\n                corsPolicy.PreflightMaxAge = -2;\n            },\n            \"value\",\n            \"PreflightMaxAge must be greater than or equal to 0.\");\n        }\n\n        [Fact]\n        public void ToString_ReturnsThePropertyValues()\n        {\n            CorsPolicy corsPolicy = new CorsPolicy\n            {\n                AllowAnyHeader = true,\n                AllowAnyOrigin = true,\n                PreflightMaxAge = 10,\n                SupportsCredentials = true\n            };\n            corsPolicy.Headers.Add(\"foo\");\n            corsPolicy.Headers.Add(\"bar\");\n            corsPolicy.Origins.Add(\"http://example.com\");\n            corsPolicy.Origins.Add(\"http://example.org\");\n            corsPolicy.Methods.Add(\"GET\");\n\n            Assert.Equal(@\"AllowAnyHeader: True, AllowAnyMethod: False, AllowAnyOrigin: True, PreflightMaxAge: 10, SupportsCredentials: True, Origins: {http://example.com,http://example.org}, Methods: {GET}, Headers: {foo,bar}, ExposedHeaders: {}\", corsPolicy.ToString());\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Cors.Test/CorsRequestContextTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Cors.Test\n{\n    public class CorsRequestContextTest\n    {\n        [Fact]\n        public void Default_Constructor()\n        {\n            CorsRequestContext requestContext = new CorsRequestContext();\n\n            Assert.Null(requestContext.AccessControlRequestMethod);\n            Assert.Null(requestContext.Host);\n            Assert.Null(requestContext.HttpMethod);\n            Assert.Null(requestContext.Origin);\n            Assert.Null(requestContext.RequestUri);\n            Assert.NotNull(requestContext.AccessControlRequestHeaders);\n            Assert.False(requestContext.IsPreflight);\n        }\n\n        [Theory]\n        [InlineData(\"OPTIONS\", \"POST\", \"foo\")]\n        [InlineData(\"options\", \"POST\", \"foo\")]\n        [InlineData(\"OPTIONS\", \"GET\", \"foo\")]\n        [InlineData(\"OPTIONS\", \"OPTIONS\", \"\")]\n        public void IsPreflight_ReturnsTrue(string httpMethod, string requestedMethod, string origin)\n        {\n            CorsRequestContext requestContext = new CorsRequestContext\n            {\n                HttpMethod = httpMethod,\n                AccessControlRequestMethod = requestedMethod,\n                Origin = origin\n            };\n\n            Assert.True(requestContext.IsPreflight);\n        }\n\n        [Theory]\n        [InlineData(\"OPTIONS\", \"POST\", null)]\n        [InlineData(\"options\", \"POST\", null)]\n        [InlineData(\"OPTIONS\", null, \"foo\")]\n        [InlineData(null, \"POST\", \"foo\")]\n        [InlineData(\"POST\", \"GET\", \"bar\")]\n        public void IsPreflight_ReturnsFalse(string httpMethod, string requestedMethod, string origin)\n        {\n            CorsRequestContext requestContext = new CorsRequestContext()\n            {\n                HttpMethod = httpMethod,\n                AccessControlRequestMethod = requestedMethod,\n                Origin = origin\n            };\n\n            Assert.False(requestContext.IsPreflight);\n        }\n\n        [Fact]\n        public void ToString_ReturnsThePropertyValues()\n        {\n            CorsRequestContext requestContext = new CorsRequestContext\n            {\n                Host = \"http://example.com\",\n                HttpMethod = \"OPTIONS\",\n                AccessControlRequestMethod = \"DELETE\",\n                Origin = \"http://localhost\",\n                RequestUri = new Uri(\"http://example.com\")\n            };\n            requestContext.AccessControlRequestHeaders.Add(\"foo\");\n            requestContext.AccessControlRequestHeaders.Add(\"bar\");\n\n            Assert.Equal(@\"Origin: http://localhost, HttpMethod: OPTIONS, IsPreflight: True, Host: http://example.com, AccessControlRequestMethod: DELETE, RequestUri: http://example.com/, AccessControlRequestHeaders: {foo,bar}\", requestContext.ToString());\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Cors.Test/CorsResultTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Cors.Test\n{\n    public class CorsResultTest\n    {\n        [Fact]\n        public void Default_Constructor()\n        {\n            CorsResult result = new CorsResult();\n\n            Assert.Empty(result.AllowedHeaders);\n            Assert.Empty(result.AllowedExposedHeaders);\n            Assert.Empty(result.AllowedMethods);\n            Assert.Empty(result.ErrorMessages);\n            Assert.False(result.SupportsCredentials);\n            Assert.Null(result.AllowedOrigin);\n            Assert.Null(result.PreflightMaxAge);\n            Assert.True(result.IsValid);\n        }\n\n        [Fact]\n        public void SettingNegativePreflightMaxAge_Throws()\n        {\n            CorsResult result = new CorsResult();\n            Assert.ThrowsArgumentOutOfRange(() =>\n            {\n                result.PreflightMaxAge = -2;\n            },\n            \"value\",\n            \"PreflightMaxAge must be greater than or equal to 0.\");\n        }\n\n        [Fact]\n        public void IsValid_ReturnsFalse_WhenThereIsError()\n        {\n            CorsResult result = new CorsResult();\n            result.ErrorMessages.Add(\"error\");\n\n            Assert.False(result.IsValid);\n        }\n\n        [Fact]\n        public void ToResponseHeaders_ReturnsNoHeaders_ByDefault()\n        {\n            CorsResult result = new CorsResult();\n\n            IDictionary<string, string> headers = result.ToResponseHeaders();\n\n            Assert.Empty(headers);\n        }\n\n        [Fact]\n        public void ToResponseHeaders_AllowOrigin_AllowOriginHeaderAdded()\n        {\n            CorsResult result = new CorsResult\n            {\n                AllowedOrigin = \"http://example.com\"\n            };\n\n            IDictionary<string, string> headers = result.ToResponseHeaders();\n\n            Assert.Equal(\"http://example.com\", headers[\"Access-Control-Allow-Origin\"]);\n        }\n\n        [Fact]\n        public void ToResponseHeaders_NoAllowOrigin_AllowOriginHeaderNotAdded()\n        {\n            CorsResult result = new CorsResult\n            {\n                AllowedOrigin = null\n            };\n\n            IDictionary<string, string> headers = result.ToResponseHeaders();\n\n            Assert.DoesNotContain(\"Access-Control-Allow-Origin\", headers.Keys);\n        }\n\n        [Fact]\n        public void ToResponseHeaders_AllowCredentials_AllowCredentialsHeaderAdded()\n        {\n            CorsResult result = new CorsResult\n            {\n                SupportsCredentials = true\n            };\n\n            IDictionary<string, string> headers = result.ToResponseHeaders();\n\n            Assert.Equal(\"true\", headers[\"Access-Control-Allow-Credentials\"]);\n        }\n\n        [Fact]\n        public void ToResponseHeaders_NoAllowCredentials_AllowCredentialsHeaderNotAdded()\n        {\n            CorsResult result = new CorsResult\n            {\n                SupportsCredentials = false\n            };\n\n            IDictionary<string, string> headers = result.ToResponseHeaders();\n\n            Assert.DoesNotContain(\"Access-Control-Allow-Credentials\", headers.Keys);\n        }\n\n        [Fact]\n        public void ToResponseHeaders_NoAllowMethods_AllowMethodsHeaderNotAdded()\n        {\n            CorsResult result = new CorsResult\n            {\n                // AllowMethods is empty by default\n            };\n\n            IDictionary<string, string> headers = result.ToResponseHeaders();\n\n            Assert.DoesNotContain(\"Access-Control-Allow-Methods\", headers.Keys);\n        }\n\n        [Fact]\n        public void ToResponseHeaders_OneAllowMethods_AllowMethodsHeaderAdded()\n        {\n            CorsResult result = new CorsResult();\n            result.AllowedMethods.Add(\"PUT\");\n\n            IDictionary<string, string> headers = result.ToResponseHeaders();\n\n            Assert.Equal(\"PUT\", headers[\"Access-Control-Allow-Methods\"]);\n        }\n\n        [Fact]\n        public void ToResponseHeaders_SomeSimpleAllowMethods_AllowMethodsHeaderAddedForNonSimpleMethods()\n        {\n            CorsResult result = new CorsResult();\n            result.AllowedMethods.Add(\"PUT\");\n            result.AllowedMethods.Add(\"get\");\n            result.AllowedMethods.Add(\"DELETE\");\n            result.AllowedMethods.Add(\"POST\");\n\n            IDictionary<string, string> headers = result.ToResponseHeaders();\n\n            Assert.Contains(\"Access-Control-Allow-Methods\", headers.Keys);\n            string[] methods = headers[\"Access-Control-Allow-Methods\"].Split(',');\n            Assert.Equal(2, methods.Length);\n            Assert.Contains(\"PUT\", methods);\n            Assert.Contains(\"DELETE\", methods);\n        }\n\n        [Fact]\n        public void ToResponseHeaders_SimpleAllowMethods_AllowMethodsHeaderNotAdded()\n        {\n            CorsResult result = new CorsResult();\n            result.AllowedMethods.Add(\"GET\");\n            result.AllowedMethods.Add(\"HEAD\");\n            result.AllowedMethods.Add(\"POST\");\n\n            IDictionary<string, string> headers = result.ToResponseHeaders();\n\n            Assert.DoesNotContain(\"Access-Control-Allow-Methods\", headers.Keys);\n        }\n\n        [Fact]\n        public void ToResponseHeaders_NoAllowHeaders_AllowHeadersHeaderNotAdded()\n        {\n            CorsResult result = new CorsResult\n            {\n                // AllowHeaders is empty by default\n            };\n\n            IDictionary<string, string> headers = result.ToResponseHeaders();\n\n            Assert.DoesNotContain(\"Access-Control-Allow-Headers\", headers.Keys);\n        }\n\n        [Fact]\n        public void ToResponseHeaders_OneAllowHeaders_AllowHeadersHeaderAdded()\n        {\n            CorsResult result = new CorsResult();\n            result.AllowedHeaders.Add(\"foo\");\n\n            IDictionary<string, string> headers = result.ToResponseHeaders();\n\n            Assert.Equal(\"foo\", headers[\"Access-Control-Allow-Headers\"]);\n        }\n\n        [Fact]\n        public void ToResponseHeaders_ManyAllowHeaders_AllowHeadersHeaderAdded()\n        {\n            CorsResult result = new CorsResult();\n            result.AllowedHeaders.Add(\"foo\");\n            result.AllowedHeaders.Add(\"bar\");\n            result.AllowedHeaders.Add(\"baz\");\n\n            IDictionary<string, string> headers = result.ToResponseHeaders();\n\n            Assert.Contains(\"Access-Control-Allow-Headers\", headers.Keys);\n            string[] headerValues = headers[\"Access-Control-Allow-Headers\"].Split(',');\n            Assert.Equal(3, headerValues.Length);\n            Assert.Contains(\"foo\", headerValues);\n            Assert.Contains(\"bar\", headerValues);\n            Assert.Contains(\"baz\", headerValues);\n        }\n\n        [Fact]\n        public void ToResponseHeaders_SomeSimpleAllowHeaders_AllowHeadersHeaderAddedForNonSimpleHeaders()\n        {\n            CorsResult result = new CorsResult();\n            result.AllowedHeaders.Add(\"Content-Language\");\n            result.AllowedHeaders.Add(\"foo\");\n            result.AllowedHeaders.Add(\"bar\");\n            result.AllowedHeaders.Add(\"Accept\");\n\n            IDictionary<string, string> headers = result.ToResponseHeaders();\n\n            Assert.Contains(\"Access-Control-Allow-Headers\", headers.Keys);\n            string[] headerValues = headers[\"Access-Control-Allow-Headers\"].Split(',');\n            Assert.Equal(2, headerValues.Length);\n            Assert.Contains(\"foo\", headerValues);\n            Assert.Contains(\"bar\", headerValues);\n        }\n\n        [Fact]\n        public void ToResponseHeaders_SimpleAllowHeaders_AllowHeadersHeaderNotAdded()\n        {\n            CorsResult result = new CorsResult();\n            result.AllowedHeaders.Add(\"Accept\");\n            result.AllowedHeaders.Add(\"Accept-Language\");\n            result.AllowedHeaders.Add(\"Content-Language\");\n\n            IDictionary<string, string> headers = result.ToResponseHeaders();\n\n            Assert.DoesNotContain(\"Access-Control-Allow-Headers\", headers.Keys);\n        }\n\n        [Fact]\n        public void ToResponseHeaders_NoAllowExposedHeaders_ExposedHeadersHeaderNotAdded()\n        {\n            CorsResult result = new CorsResult\n            {\n                // AllowExposedHeaders is empty by default\n            };\n\n            IDictionary<string, string> headers = result.ToResponseHeaders();\n\n            Assert.DoesNotContain(\"Access-Control-Expose-Headers\", headers.Keys);\n        }\n\n        [Fact]\n        public void ToResponseHeaders_OneAllowExposedHeaders_ExposedHeadersHeaderAdded()\n        {\n            CorsResult result = new CorsResult();\n            result.AllowedExposedHeaders.Add(\"foo\");\n\n            IDictionary<string, string> headers = result.ToResponseHeaders();\n\n            Assert.Equal(\"foo\", headers[\"Access-Control-Expose-Headers\"]);\n        }\n\n        [Fact]\n        public void ToResponseHeaders_ManyAllowExposedHeaders_ExposedHeadersHeaderAdded()\n        {\n            CorsResult result = new CorsResult();\n            result.AllowedExposedHeaders.Add(\"foo\");\n            result.AllowedExposedHeaders.Add(\"bar\");\n            result.AllowedExposedHeaders.Add(\"baz\");\n\n            IDictionary<string, string> headers = result.ToResponseHeaders();\n\n            Assert.Contains(\"Access-Control-Expose-Headers\", headers.Keys);\n            string[] exposedHeaderValues = headers[\"Access-Control-Expose-Headers\"].Split(',');\n            Assert.Equal(3, exposedHeaderValues.Length);\n            Assert.Contains(\"foo\", exposedHeaderValues);\n            Assert.Contains(\"bar\", exposedHeaderValues);\n            Assert.Contains(\"baz\", exposedHeaderValues);\n        }\n\n        [Fact]\n        public void ToResponseHeaders_NoPreflightMaxAge_MaxAgeHeaderNotAdded()\n        {\n            CorsResult result = new CorsResult\n            {\n                PreflightMaxAge = null\n            };\n\n            IDictionary<string, string> headers = result.ToResponseHeaders();\n\n            Assert.DoesNotContain(\"Access-Control-Max-Age\", headers.Keys);\n        }\n\n        [Fact]\n        public void ToResponseHeaders_PreflightMaxAge_MaxAgeHeaderAdded()\n        {\n            CorsResult result = new CorsResult\n            {\n                PreflightMaxAge = 30\n            };\n\n            IDictionary<string, string> headers = result.ToResponseHeaders();\n\n            Assert.Equal(\"30\", headers[\"Access-Control-Max-Age\"]);\n        }\n\n        [Fact]\n        public void ToString_ReturnsThePropertyValues()\n        {\n            CorsResult corsResult = new CorsResult\n            {\n                SupportsCredentials = true,\n                PreflightMaxAge = 20,\n                AllowedOrigin = \"*\"\n            };\n            corsResult.AllowedExposedHeaders.Add(\"foo\");\n            corsResult.AllowedHeaders.Add(\"bar\");\n            corsResult.AllowedHeaders.Add(\"baz\");\n            corsResult.AllowedMethods.Add(\"GET\");\n            corsResult.ErrorMessages.Add(\"error1\");\n            corsResult.ErrorMessages.Add(\"error2\");\n\n            Assert.Equal(@\"IsValid: False, AllowCredentials: True, PreflightMaxAge: 20, AllowOrigin: *, AllowExposedHeaders: {foo}, AllowHeaders: {bar,baz}, AllowMethods: {GET}, ErrorMessages: {error1,error2}\", corsResult.ToString());\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Cors.Test/System.Web.Cors.Test.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props\" Condition=\"Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" />\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" />\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>System.Web.Cors</RootNamespace>\n    <AssemblyName>System.Web.Cors.Test</AssemblyName>\n    <OutputPath>..\\..\\bin\\$(Configuration)\\Test\\</OutputPath>\n    <ProjectGuid>{BF07E947-120D-4E93-93DA-A4BF121753EA}</ProjectGuid>\n    <NuGetPackageImportStamp>\n    </NuGetPackageImportStamp>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Castle.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Castle.Core.5.1.1\\lib\\net462\\Castle.Core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Moq, Version=4.18.0.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Moq.4.18.4\\lib\\net462\\Moq.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.abstractions.2.0.3\\lib\\net35\\xunit.abstractions.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.assert, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.assert.2.4.2\\lib\\netstandard1.1\\xunit.assert.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.core, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.core.2.4.2\\lib\\net452\\xunit.core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.execution.desktop, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.execution.2.4.2\\lib\\net452\\xunit.execution.desktop.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"CorsPolicyTest.cs\" />\n    <Compile Include=\"CorsEngineTest.cs\" />\n    <Compile Include=\"CorsRequestContextTest.cs\" />\n    <Compile Include=\"CorsResultTest.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Cors\\System.Web.Cors.csproj\">\n      <Project>{43c1b979-d593-4a32-bb3a-4316f1c66d66}</Project>\n      <Name>System.Web.Cors</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\">\n      <Project>{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}</Project>\n      <Name>Microsoft.TestCommon</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <Folder Include=\"Properties\\\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Service Include=\"{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Analyzer Include=\"..\\..\\packages\\xunit.analyzers.1.1.0\\analyzers\\dotnet\\cs\\xunit.analyzers.dll\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  <Target Name=\"EnsureNuGetPackageBuildImports\" BeforeTargets=\"PrepareForBuild\">\n    <PropertyGroup>\n      <ErrorText>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}.</ErrorText>\n    </PropertyGroup>\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props'))\" />\n  </Target>\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" />\n</Project>"
  },
  {
    "path": "test/System.Web.Cors.Test/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Castle.Core\" version=\"5.1.1\" targetFramework=\"net462\" />\n  <package id=\"Moq\" version=\"4.18.4\" targetFramework=\"net462\" />\n  <package id=\"xunit\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.abstractions\" version=\"2.0.3\" targetFramework=\"net462\" />\n  <package id=\"xunit.analyzers\" version=\"1.1.0\" targetFramework=\"net462\" />\n  <package id=\"xunit.assert\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.execution\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.runner.visualstudio\" version=\"2.4.5\" targetFramework=\"net462\" developmentDependency=\"true\" />\n</packages>"
  },
  {
    "path": "test/System.Web.Helpers.Test/ChartTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Drawing;\nusing System.IO;\nusing System.Web.Hosting;\nusing System.Web.UI.DataVisualization.Charting;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Helpers.Test\n{\n    public class ChartTest\n    {\n        private byte[] _writeData;\n\n        public ChartTest()\n        {\n            _writeData = null;\n        }\n\n        [Fact]\n        public void BuildChartAddsDefaultArea()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100);\n            AssertBuiltChartAction(chart, c =>\n            {\n                ChartArea chartArea = Assert.Single(c.ChartAreas);\n                Assert.Equal(\"Default\", chartArea.Name);\n            });\n        }\n\n        [Fact]\n        public void XAxisOverrides()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100)\n                .SetXAxis(\"AxisX\", 1, 100);\n            AssertBuiltChartAction(chart, c =>\n            {\n                ChartArea chartArea = Assert.Single(c.ChartAreas);\n                Assert.Equal(\"AxisX\", chartArea.AxisX.Title);\n                Assert.Equal(1, chartArea.AxisX.Minimum);\n                Assert.Equal(100, chartArea.AxisX.Maximum);\n            });\n        }\n\n        [Fact]\n        public void YAxisOverrides()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100)\n                .SetYAxis(\"AxisY\", 1, 100);\n            AssertBuiltChartAction(chart, c =>\n            {\n                ChartArea chartArea = Assert.Single(c.ChartAreas);\n                Assert.Equal(\"AxisY\", chartArea.AxisY.Title);\n                Assert.Equal(1, chartArea.AxisY.Minimum);\n                Assert.Equal(100, chartArea.AxisY.Maximum);\n            });\n        }\n\n        [Fact]\n        public void ConstructorLoadsTemplate()\n        {\n            var template = WriteTemplate(@\"<Chart BorderWidth=\"\"2\"\"></Chart>\");\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100, themePath: template);\n            AssertBuiltChartAction(chart, c => { Assert.Equal(2, c.BorderWidth); });\n        }\n\n        [Fact]\n        public void ConstructorLoadsTheme()\n        {\n            //Vanilla theme\n            /*\n             * <Chart Palette=\"SemiTransparent\" BorderColor=\"#000\" BorderWidth=\"2\" BorderlineDashStyle=\"Solid\">\n                <ChartAreas>\n                    <ChartArea _Template_=\"All\" Name=\"Default\">\n                            <AxisX>\n                                <MinorGrid Enabled=\"False\" />\n                                <MajorGrid Enabled=\"False\" />\n                            </AxisX>\n                            <AxisY>\n                                <MajorGrid Enabled=\"False\" />\n                                <MinorGrid Enabled=\"False\" />\n                            </AxisY>\n                    </ChartArea>\n                </ChartAreas>\n                </Chart>\n             */\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100, theme: ChartTheme.Vanilla);\n            AssertBuiltChartAction(chart, c =>\n            {\n                Assert.Equal(ChartColorPalette.SemiTransparent, c.Palette);\n                Assert.Equal(c.BorderColor, Color.FromArgb(0, Color.Black));\n                ChartArea chartArea = Assert.Single(c.ChartAreas);\n                Assert.False(chartArea.AxisX.MajorGrid.Enabled);\n                Assert.False(chartArea.AxisY.MinorGrid.Enabled);\n            });\n        }\n\n        [Fact]\n        public void ConstructorLoadsThemeAndTemplate()\n        {\n            //Vanilla theme\n            /*\n             * <Chart Palette=\"SemiTransparent\" BorderColor=\"#000\" BorderWidth=\"2\" BorderlineDashStyle=\"Solid\">\n                <ChartAreas>\n                    <ChartArea _Template_=\"All\" Name=\"Default\">\n                            <AxisX>\n                                <MinorGrid Enabled=\"False\" />\n                                <MajorGrid Enabled=\"False\" />\n                            </AxisX>\n                            <AxisY>\n                                <MajorGrid Enabled=\"False\" />\n                                <MinorGrid Enabled=\"False\" />\n                            </AxisY>\n                    </ChartArea>\n                </ChartAreas>\n                </Chart>\n             */\n            var template = WriteTemplate(@\"<Chart BorderlineDashStyle=\"\"DashDot\"\"><Legends><Legend BackColor=\"\"Red\"\" /></Legends></Chart>\");\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100, theme: ChartTheme.Vanilla, themePath: template);\n            AssertBuiltChartAction(chart, c =>\n            {\n                Assert.Equal(ChartColorPalette.SemiTransparent, c.Palette);\n                Assert.Equal(c.BorderColor, Color.FromArgb(0, Color.Black));\n                Assert.Equal(ChartDashStyle.DashDot, c.BorderlineDashStyle);\n                Legend legend = Assert.Single(c.Legends);\n                Assert.Equal(legend.BackColor, Color.Red);\n                ChartArea chartArea = Assert.Single(c.ChartAreas);\n                Assert.False(chartArea.AxisX.MajorGrid.Enabled);\n                Assert.False(chartArea.AxisY.MinorGrid.Enabled);\n            });\n        }\n\n        [Fact]\n        public void ConstructorLoadsThemeAndTemplate_VPPRegistrationChanging()\n        {\n            // Arrange\n            // Vanilla theme, as in ConstructorLoadsThemeAndTemplate()\n            string template = WriteTemplate(@\"<Chart BorderlineDashStyle=\"\"DashDot\"\"><Legends><Legend BackColor=\"\"Red\"\" /></Legends></Chart>\");\n            HttpContextBase context = GetContext();\n            string templatePath = VirtualPathUtility.Combine(context.Request.AppRelativeCurrentExecutionFilePath, template);\n\n            MockVirtualPathProvider provider1 = new MockVirtualPathProvider();\n            MockVirtualPathProvider provider2 = new MockVirtualPathProvider();\n            VirtualPathProvider provider = provider1;\n\n            // Act; use one provider in constructor and another in ExecuteChartAction()\n            Chart chart = new Chart(context, () => provider, 100, 100, theme: ChartTheme.Vanilla, themePath: template);\n\n            // The moral equivalent of HostingEnvironment.RegisterVirtualPathProvider(provider2)\n            provider = provider2;\n\n            // Assert\n            AssertBuiltChartAction(chart, c =>\n            {\n                Assert.Equal(ChartColorPalette.SemiTransparent, c.Palette);\n                Assert.Equal(c.BorderColor, Color.FromArgb(0, Color.Black));\n                Assert.Equal(ChartDashStyle.DashDot, c.BorderlineDashStyle);\n                Legend legend = Assert.Single(c.Legends);\n                Assert.Equal(legend.BackColor, Color.Red);\n                ChartArea chartArea = Assert.Single(c.ChartAreas);\n                Assert.False(chartArea.AxisX.MajorGrid.Enabled);\n                Assert.False(chartArea.AxisY.MinorGrid.Enabled);\n            });\n\n            Assert.Equal(1, provider1.FileExistsCalls);\n            Assert.Equal(0, provider1.GetFileCalls);\n            Assert.Equal(0, provider2.FileExistsCalls);\n            Assert.Equal(1, provider2.GetFileCalls);\n        }\n\n        [Fact]\n        public void ConstructorSetsWidthAndHeight()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 101, 102);\n            Assert.Equal(101, chart.Width);\n            Assert.Equal(102, chart.Height);\n            AssertBuiltChartAction(chart, c =>\n            {\n                Assert.Equal(101, c.Width);\n                Assert.Equal(102, c.Height);\n            });\n        }\n\n        [Fact]\n        public void ConstructorThrowsWhenHeightIsLessThanZero()\n        {\n            Assert.ThrowsArgumentOutOfRange(() => { new Chart(GetContext(), GetVirtualPathProvider(), 100, -1); }, \"height\", \"Value must be greater than or equal to 0.\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsWhenTemplateNotFound()\n        {\n            var templateFile = @\"FileNotFound.xml\";\n            Assert.ThrowsArgument(() => { new Chart(GetContext(), GetVirtualPathProvider(), 100, 100, themePath: templateFile); },\n                                                    \"themePath\",\n                                                    String.Format(\"The theme file \\\"{0}\\\" could not be found.\", VirtualPathUtility.Combine(GetContext().Request.AppRelativeCurrentExecutionFilePath, templateFile)));\n        }\n\n        [Fact]\n        public void ConstructorThrowsWhenWidthIsLessThanZero()\n        {\n            Assert.ThrowsArgumentOutOfRange(() => { new Chart(GetContext(), GetVirtualPathProvider(), -1, 100); }, \"width\", \"Value must be greater than or equal to 0.\");\n        }\n\n        [Fact]\n        public void DataBindCrossTable()\n        {\n            var data = new[]\n            {\n                new { GroupBy = \"1\", YValue = 1 },\n                new { GroupBy = \"1\", YValue = 2 },\n                new { GroupBy = \"2\", YValue = 1 }\n            };\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100)\n                .DataBindCrossTable(data, \"GroupBy\", xField: null, yFields: \"YValue\");\n            // todo - anything else to verify here?\n            AssertBuiltChartAction(chart, c =>\n            {\n                Assert.Equal(2, c.Series.Count);\n                Assert.Equal(2, c.Series[0].Points.Count);\n                Assert.Single(c.Series[1].Points);\n            });\n        }\n\n        [Fact]\n        public void DataBindCrossTableThrowsWhenDataSourceIsNull()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100);\n            Assert.ThrowsArgumentNull(() => { chart.DataBindCrossTable(null, \"GroupBy\", xField: null, yFields: \"yFields\"); }, \"dataSource\");\n        }\n\n        [Fact]\n        public void DataBindCrossTableThrowsWhenDataSourceIsString()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100);\n            Assert.ThrowsArgument(() => { chart.DataBindCrossTable(\"DataSource\", \"GroupBy\", xField: null, yFields: \"yFields\"); }, \"dataSource\", \"A series cannot be data-bound to a string object.\");\n        }\n\n        [Fact]\n        public void DataBindCrossTableThrowsWhenGroupByIsNull()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100);\n            Assert.ThrowsArgumentNullOrEmptyString(() => { chart.DataBindCrossTable(new object[0], null, xField: null, yFields: \"yFields\"); }, \"groupByField\");\n        }\n\n        [Fact]\n        public void DataBindCrossTableThrowsWhenGroupByIsEmpty()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100);\n            Assert.ThrowsArgumentNullOrEmptyString(() => { chart.DataBindCrossTable(new object[0], \"\", xField: null, yFields: \"yFields\"); }, \"groupByField\");\n        }\n\n        [Fact]\n        public void DataBindCrossTableThrowsWhenYFieldsIsNull()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100);\n            Assert.ThrowsArgumentNullOrEmptyString(() => { chart.DataBindCrossTable(new object[0], \"GroupBy\", xField: null, yFields: null); }, \"yFields\");\n        }\n\n        [Fact]\n        public void DataBindCrossTableThrowsWhenYFieldsIsEmpty()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100);\n            Assert.ThrowsArgumentNullOrEmptyString(() => { chart.DataBindCrossTable(new object[0], \"GroupBy\", xField: null, yFields: \"\"); }, \"yFields\");\n        }\n\n        [Fact]\n        public void DataBindTable()\n        {\n            var data = new[]\n            {\n                new { XValue = \"1\", YValue = 1 },\n                new { XValue = \"2\", YValue = 2 },\n                new { XValue = \"3\", YValue = 3 }\n            };\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100)\n                .DataBindTable(data, xField: \"XValue\");\n            // todo - anything else to verify here?\n            AssertBuiltChartAction(chart, c =>\n            {\n                var series = Assert.Single(c.Series);\n                Assert.Equal(3, series.Points.Count);\n            });\n        }\n\n        [Fact]\n        public void DataBindTableWhenXFieldIsNull()\n        {\n            var data = new[]\n            {\n                new { YValue = 1 },\n                new { YValue = 2 },\n                new { YValue = 3 }\n            };\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100)\n                .DataBindTable(data, xField: null);\n            // todo - anything else to verify here?\n            AssertBuiltChartAction(chart, c =>\n            {\n                var series = Assert.Single(c.Series);\n                Assert.Equal(3, series.Points.Count);\n            });\n        }\n\n        [Fact]\n        public void DataBindTableThrowsWhenDataSourceIsNull()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100);\n            Assert.ThrowsArgumentNull(() => { chart.DataBindTable(null); }, \"dataSource\");\n        }\n\n        [Fact]\n        public void DataBindTableThrowsWhenDataSourceIsString()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100);\n            Assert.ThrowsArgument(() => { chart.DataBindTable(\"\"); }, \"dataSource\", \"A series cannot be data-bound to a string object.\");\n        }\n\n        [Fact]\n        public void GetBytesReturnsNonEmptyArray()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100);\n            Assert.True(chart.GetBytes().Length > 0);\n        }\n\n        [Fact]\n        public void GetBytesThrowsWhenFormatIsEmpty()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100);\n            Assert.ThrowsArgumentNullOrEmptyString(() => { chart.GetBytes(format: String.Empty); }, \"format\");\n        }\n\n        [Fact]\n        public void GetBytesThrowsWhenFormatIsInvalid()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100);\n            Assert.ThrowsArgument(() => { chart.GetBytes(format: \"foo\"); }, \"format\", \"\\\"foo\\\" is invalid image format. Valid values are image format names like: \\\"JPEG\\\", \\\"BMP\\\", \\\"GIF\\\", \\\"PNG\\\", etc.\");\n        }\n\n        [Fact]\n        public void GetBytesThrowsWhenFormatIsNull()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100);\n            Assert.ThrowsArgumentNullOrEmptyString(() => { chart.GetBytes(format: null); }, \"format\");\n        }\n\n        [Fact]\n        public void LegendDefaults()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100).AddLegend();\n            AssertBuiltChartAction(chart, c =>\n            {\n                Legend legend = Assert.Single(c.Legends);\n                // NOTE: Chart.Legends.Add will create default name\n                Assert.Equal(\"Legend1\", legend.Name);\n                Assert.Equal(1, legend.BorderWidth);\n            });\n        }\n\n        [Fact]\n        public void LegendOverrides()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100).AddLegend(\"Legend1\")\n                .AddLegend(\"Legend2\", \"Legend2Name\");\n            AssertBuiltChartAction(chart, c =>\n            {\n                Assert.Equal(2, c.Legends.Count);\n                Assert.Equal(\"Legend1\", c.Legends[0].Name);\n                Assert.Equal(\"Legend2\", c.Legends[1].Title);\n                Assert.Equal(\"Legend2Name\", c.Legends[1].Name);\n            });\n        }\n\n        [Fact]\n        public void SaveAndWriteFromCache()\n        {\n            var context1 = GetContext();\n            var chart = new Chart(context1, GetVirtualPathProvider(), 100, 100);\n\n            string key = chart.SaveToCache();\n            Assert.Equal(chart, WebCache.Get(key));\n\n            var context2 = GetContext();\n            Assert.Equal(chart, Chart.GetFromCache(context2, key));\n\n            Chart.WriteFromCache(context2, key);\n\n            Assert.Null(context1.Response.ContentType);\n            Assert.Equal(\"image/jpeg\", context2.Response.ContentType);\n        }\n\n        [Fact]\n        public void SaveThrowsWhenFormatIsEmpty()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100);\n            Assert.ThrowsArgumentNullOrEmptyString(() => { chart.Save(GetContext(), \"chartPath\", format: String.Empty); }, \"format\");\n        }\n\n        [Fact]\n        public void SaveWorksWhenFormatIsJPG()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100);\n\n            string fileName = \"chartPath\";\n\n            chart.Save(GetContext(), \"chartPath\", format: \"jpg\");\n            byte[] a = File.ReadAllBytes(fileName);\n\n            chart.Save(GetContext(), \"chartPath\", format: \"jpeg\");\n            byte[] b = File.ReadAllBytes(fileName);\n\n            Assert.Equal(a, b);\n        }\n\n        [Fact]\n        public void SaveThrowsWhenFormatIsInvalid()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100);\n            Assert.ThrowsArgument(() => { chart.Save(GetContext(), \"chartPath\", format: \"foo\"); }, \"format\", \"\\\"foo\\\" is invalid image format. Valid values are image format names like: \\\"JPEG\\\", \\\"BMP\\\", \\\"GIF\\\", \\\"PNG\\\", etc.\");\n        }\n\n        [Fact]\n        public void SaveThrowsWhenFormatIsNull()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100);\n            Assert.ThrowsArgumentNullOrEmptyString(() => { chart.Save(GetContext(), \"chartPath\", format: null); }, \"format\");\n        }\n\n        [Fact]\n        public void SaveThrowsWhenPathIsEmpty()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100);\n            Assert.ThrowsArgumentNullOrEmptyString(() => { chart.Save(GetContext(), path: String.Empty, format: \"jpeg\"); }, \"path\");\n        }\n\n        [Fact]\n        public void SaveThrowsWhenPathIsNull()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100);\n            Assert.ThrowsArgumentNullOrEmptyString(() => { chart.Save(GetContext(), path: null, format: \"jpeg\"); }, \"path\");\n        }\n\n        [Fact]\n        public void SaveWritesToFile()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100);\n            chart.Save(GetContext(), \"SaveWritesToFile.jpg\", format: \"image/jpeg\");\n            Assert.Equal(\"SaveWritesToFile.jpg\", Path.GetFileName(chart.FileName));\n            Assert.True(File.Exists(chart.FileName));\n        }\n\n        [Fact]\n        public void SaveXmlThrowsWhenPathIsEmpty()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100);\n            Assert.ThrowsArgumentNullOrEmptyString(() => { chart.SaveXml(GetContext(), String.Empty); }, \"path\");\n        }\n\n        [Fact]\n        public void SaveXmlThrowsWhenPathIsNull()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100);\n            Assert.ThrowsArgumentNullOrEmptyString(() => { chart.SaveXml(GetContext(), null); }, \"path\");\n        }\n\n        [Fact]\n        public void SaveXmlWritesToFile()\n        {\n            var template = WriteTemplate(@\"<Chart BorderWidth=\"\"2\"\"></Chart>\");\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100, themePath: template);\n            chart.SaveXml(GetContext(), \"SaveXmlWritesToFile.xml\");\n            Assert.True(File.Exists(\"SaveXmlWritesToFile.xml\"));\n            string result = File.ReadAllText(\"SaveXmlWritesToFile.xml\");\n            Assert.Contains(\"BorderWidth=\\\"2\\\"\", result);\n        }\n\n        [Fact]\n        public void TemplateWithCommentsDoesNotThrow()\n        {\n            var template = WriteTemplate(@\"<Chart BorderWidth=\"\"2\"\"><!-- This is a XML comment.  --> </Chart>\");\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100, themePath: template);\n            Assert.NotNull(chart.ToWebImage());\n        }\n\n        [Fact]\n        public void TemplateWithIncorrectPropertiesThrows()\n        {\n            var template = WriteTemplate(@\"<Chart borderWidth=\"\"2\"\"><fjkjkgjklfg /></Chart>\");\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100, themePath: template);\n            Assert.Throws<InvalidOperationException>(() => chart.ToWebImage(),\n                                                              \"Cannot deserialize property. Unknown property name 'borderWidth' in object \\\" System.Web.UI.DataVisualization.Charting.Chart\");\n        }\n\n        [Fact]\n        public void WriteWorksWithJPGFormat()\n        {\n            var response = new Mock<HttpResponseBase>();\n            var stream = new MemoryStream();\n            response.Setup(c => c.Output).Returns(new StreamWriter(stream));\n\n            var context = new Mock<HttpContextBase>();\n            context.Setup(c => c.Response).Returns(response.Object);\n\n            var chart = new Chart(context.Object, GetVirtualPathProvider(), 100, 100);\n            chart.Write(\"jpeg\");\n\n            byte[] a = stream.GetBuffer();\n\n            stream.SetLength(0);\n            chart.Write(\"jpg\");\n            byte[] b = stream.GetBuffer();\n\n            Assert.Equal(a, b);\n        }\n\n        [Fact]\n        public void WriteThrowsWithInvalidFormat()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100);\n            Assert.ThrowsArgument(() => chart.Write(\"foo\"),\n                                                    \"format\", \"\\\"foo\\\" is invalid image format. Valid values are image format names like: \\\"JPEG\\\", \\\"BMP\\\", \\\"GIF\\\", \\\"PNG\\\", etc.\");\n        }\n\n        [Fact]\n        public void SeriesOverrides()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100)\n                .AddSeries(chartType: \"Bar\");\n            AssertBuiltChartAction(chart, c =>\n            {\n                var series = Assert.Single(c.Series);\n                Assert.Equal(SeriesChartType.Bar, series.ChartType);\n            });\n        }\n\n        [Fact]\n        public void SeriesThrowsWhenChartTypeIsEmpty()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100);\n            Assert.ThrowsArgumentNullOrEmptyString(() => { chart.AddSeries(chartType: \"\"); }, \"chartType\");\n        }\n\n        [Fact]\n        public void SeriesThrowsWhenChartTypeIsNull()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100);\n            Assert.ThrowsArgumentNullOrEmptyString(() => { chart.AddSeries(chartType: null); }, \"chartType\");\n        }\n\n        [Fact]\n        public void TitleDefaults()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100).AddTitle();\n            AssertBuiltChartAction(chart, c =>\n            {\n                var title = Assert.Single(c.Titles);\n                // NOTE: Chart.Titles.Add will create default name\n                Assert.Equal(\"Title1\", title.Name);\n                Assert.Equal(String.Empty, title.Text);\n                Assert.Equal(1, title.BorderWidth);\n            });\n        }\n\n        [Fact]\n        public void TitleOverrides()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100).AddTitle(name: \"Title1\")\n                .AddTitle(\"Title2Text\", name: \"Title2\");\n            AssertBuiltChartAction(chart, c =>\n            {\n                Assert.Equal(2, c.Titles.Count);\n                Assert.Equal(\"Title1\", c.Titles[0].Name);\n                Assert.Equal(\"Title2\", c.Titles[1].Name);\n                Assert.Equal(\"Title2Text\", c.Titles[1].Text);\n            });\n        }\n\n        [Fact]\n        public void ToWebImage()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100);\n            var image = chart.ToWebImage();\n            Assert.NotNull(image);\n            Assert.Equal(\"jpeg\", image.ImageFormat);\n        }\n\n        [Fact]\n        public void ToWebImageUsesFormat()\n        {\n            var chart = new Chart(GetContext(), GetVirtualPathProvider(), 100, 100);\n            var image = chart.ToWebImage(format: \"png\");\n            Assert.NotNull(image);\n            Assert.Equal(\"png\", image.ImageFormat);\n        }\n\n        [Fact]\n        public void WriteFromCacheIsNoOpIfNotSavedInCache()\n        {\n            var context = GetContext();\n            Assert.Null(Chart.WriteFromCache(context, Guid.NewGuid().ToString()));\n            Assert.Null(context.Response.ContentType);\n        }\n\n        [Fact]\n        public void WriteUpdatesResponse()\n        {\n            var context = GetContext();\n            var chart = new Chart(context, GetVirtualPathProvider(), 100, 100);\n            chart.Write();\n            Assert.Equal(\"\", context.Response.Charset);\n            Assert.Equal(\"image/jpeg\", context.Response.ContentType);\n            Assert.True((_writeData != null) && (_writeData.Length > 0));\n        }\n\n        private static void AssertBuiltChartAction(Chart chart, Action<UI.DataVisualization.Charting.Chart> action)\n        {\n            bool actionCalled = false;\n            chart.ExecuteChartAction(c =>\n            {\n                action(c);\n                actionCalled = true;\n            });\n            Assert.True(actionCalled);\n        }\n\n        private HttpContextBase GetContext()\n        {\n            // Strip drive letter for VirtualPathUtility.Combine\n            var testPath = Directory.GetCurrentDirectory().Substring(2) + \"/Out\";\n            Mock<HttpRequestBase> request = new Mock<HttpRequestBase>();\n            request.Setup(r => r.AppRelativeCurrentExecutionFilePath).Returns(testPath);\n            request.Setup(r => r.MapPath(It.IsAny<string>())).Returns((string path) => path);\n\n            Mock<HttpResponseBase> response = new Mock<HttpResponseBase>();\n            response.SetupProperty(r => r.ContentType);\n            response.SetupProperty(r => r.Charset);\n            response.Setup(r => r.BinaryWrite(It.IsAny<byte[]>())).Callback((byte[] data) => _writeData = data);\n\n            Mock<HttpServerUtilityBase> server = new Mock<HttpServerUtilityBase>();\n            server.Setup(s => s.MapPath(It.IsAny<string>())).Returns((string s) => s);\n\n            var items = new Hashtable();\n\n            Mock<HttpContextBase> context = new Mock<HttpContextBase>();\n            context.Setup(c => c.Request).Returns(request.Object);\n            context.Setup(c => c.Response).Returns(response.Object);\n            context.Setup(c => c.Server).Returns(server.Object);\n            context.Setup(c => c.Items).Returns(items);\n            return context.Object;\n        }\n\n        private static string WriteTemplate(string xml)\n        {\n            var path = Guid.NewGuid() + \".xml\";\n            File.WriteAllText(path, xml);\n            return path;\n        }\n\n        private static MockVirtualPathProvider GetVirtualPathProvider()\n        {\n            return new MockVirtualPathProvider();\n        }\n\n        class MockVirtualPathProvider : VirtualPathProvider\n        {\n            public int FileExistsCalls { get; private set; }\n\n            public int GetFileCalls { get; private set; }\n\n            class MockVirtualFile : VirtualFile\n            {\n                public MockVirtualFile(string virtualPath)\n                    : base(virtualPath)\n                {\n                }\n\n                public override Stream Open()\n                {\n                    return File.Open(this.VirtualPath, FileMode.Open);\n                }\n            }\n\n            public override bool FileExists(string virtualPath)\n            {\n                ++FileExistsCalls;\n                return File.Exists(virtualPath);\n            }\n\n            public override VirtualFile GetFile(string virtualPath)\n            {\n                ++GetFileCalls;\n                return new MockVirtualFile(virtualPath);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Helpers.Test/ConversionUtilTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Drawing;\nusing System.Globalization;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Helpers.Test\n{\n    public class ConversionUtilTest\n    {\n        [Fact]\n        public void ConversionUtilReturnsStringTypes()\n        {\n            // Arrange\n            string original = \"Foo\";\n\n            // Act\n            object result;\n            bool success = ConversionUtil.TryFromString(typeof(String), original, out result);\n\n            // Assert\n            Assert.True(success);\n            Assert.Equal(original, result);\n        }\n\n        [Fact]\n        public void ConversionUtilConvertsStringsToColor()\n        {\n            // Arrange\n            string original = \"Blue\";\n\n            // Act\n            object result;\n            bool success = ConversionUtil.TryFromString(typeof(Color), original, out result);\n\n            // Assert\n            Assert.True(success);\n            Assert.Equal(Color.Blue, result);\n        }\n\n        [Fact]\n        public void ConversionUtilConvertsEnumValues()\n        {\n            // Arrange\n            string original = \"Weekday\";\n\n            // Act\n            object result;\n            bool success = ConversionUtil.TryFromString(typeof(TestEnum), original, out result);\n\n            // Assert\n            Assert.True(success);\n            Assert.Equal(TestEnum.Weekday, result);\n        }\n\n        [Fact]\n        public void ConversionUtilUsesTypeConverterToConvertArbitraryTypes()\n        {\n            // Arrange\n            var date = new DateTime(2010, 01, 01);\n            string original = date.ToString(CultureInfo.InvariantCulture);\n\n            // Act\n            object result;\n            bool success = ConversionUtil.TryFromString(typeof(DateTime), original, out result);\n\n            // Assert\n            Assert.True(success);\n            Assert.Equal(date, result);\n        }\n\n        private enum TestEnum\n        {\n            Weekend,\n            Weekday\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Helpers.Test/CryptoTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Security.Cryptography;\nusing System.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Helpers.Test\n{\n    /// <summary>\n    /// This is a test class for CryptoTest and is intended\n    /// to contain all CryptoTest Unit Tests\n    /// </summary>\n    public class CryptoTest\n    {\n        [Fact]\n        public void SHA256HashTest_ReturnsValidData()\n        {\n            string data = \"foo bar\";\n            string expected = \"FBC1A9F858EA9E177916964BD88C3D37B91A1E84412765E29950777F265C4B75\";\n            string actual;\n            actual = Crypto.SHA256(data);\n            Assert.Equal(expected, actual);\n\n            actual = Crypto.Hash(Encoding.UTF8.GetBytes(data));\n            Assert.Equal(expected, actual);\n        }\n\n        [Fact]\n        public void GenerateSaltTest()\n        {\n            string salt = Crypto.GenerateSalt();\n            salt = Crypto.GenerateSalt(64);\n            Assert.Equal(24, Crypto.GenerateSalt().Length);\n            Assert.Equal(12, Crypto.GenerateSalt(8).Length);\n            Assert.Equal(88, Crypto.GenerateSalt(64).Length);\n            Assert.Equal(44, Crypto.GenerateSalt(32).Length);\n        }\n\n        [Fact]\n        public void HashPassword_PasswordGeneration()\n        {\n            // Act - call helper directly\n            string generatedHash = Crypto.HashPassword(\"my-password\");\n            byte[] salt = new byte[16];\n            Buffer.BlockCopy(Convert.FromBase64String(generatedHash), 1, salt, 0, 16); // extract salt from generated hash\n\n            // Act - perform PBKDF2 directly\n            string generatedHash2;\n            using (var ms = new MemoryStream())\n            {\n                using (var bw = new BinaryWriter(ms))\n                {\n                    using (var deriveBytes = new Rfc2898DeriveBytes(\"my-password\", salt, iterations: 1000))\n                    {\n                        bw.Write((byte)0x00); // version identifier\n                        bw.Write(salt); // salt\n                        bw.Write(deriveBytes.GetBytes(32)); // subkey\n                    }\n\n                    generatedHash2 = Convert.ToBase64String(ms.ToArray());\n                }\n            }\n\n            // Assert\n            Assert.Equal(generatedHash2, generatedHash);\n        }\n\n        [Fact]\n        public void HashPassword_RoundTripping()\n        {\n            // Act & assert\n            string password = \"ImPepper\";\n            Assert.True(Crypto.VerifyHashedPassword(Crypto.HashPassword(password), password));\n            Assert.False(Crypto.VerifyHashedPassword(Crypto.HashPassword(password), \"ImSalt\"));\n            Assert.False(Crypto.VerifyHashedPassword(Crypto.HashPassword(\"Impepper\"), password));\n        }\n\n        [Fact]\n        public void VerifyHashedPassword_CorrectPassword_ReturnsTrue()\n        {\n            // Arrange\n            string hashedPassword = \"ALyuoraY/cIWD1hjo+K81/pf83qo6Q6T+UBYcXN9P3A9WHLvEY10f+lwW5qPG6h9xw==\"; // this is for 'my-password'\n\n            // Act\n            bool retVal = Crypto.VerifyHashedPassword(hashedPassword, \"my-password\");\n\n            // Assert\n            Assert.True(retVal);\n        }\n\n        [Fact]\n        public void VerifyHashedPassword_IncorrectPassword_ReturnsFalse()\n        {\n            // Arrange\n            string hashedPassword = \"ALyuoraY/cIWD1hjo+K81/pf83qo6Q6T+UBYcXN9P3A9WHLvEY10f+lwW5qPG6h9xw==\"; // this is for 'my-password'\n\n            // Act\n            bool retVal = Crypto.VerifyHashedPassword(hashedPassword, \"some-other-password\");\n\n            // Assert\n            Assert.False(retVal);\n        }\n\n        [Fact]\n        public void VerifyHashedPassword_InvalidPasswordHash_ReturnsFalse()\n        {\n            // Arrange\n            string hashedPassword = \"AAECAw==\"; // this is an invalid password hash\n\n            // Act\n            bool retVal = Crypto.VerifyHashedPassword(hashedPassword, \"hello-world\");\n\n            // Assert\n            Assert.False(retVal);\n        }\n\n        [Fact]\n        public void MD5HashTest_ReturnsValidData()\n        {\n            string data = \"foo bar\";\n            string expected = \"327B6F07435811239BC47E1544353273\";\n            string actual;\n            actual = Crypto.Hash(data, algorithm: \"md5\");\n            Assert.Equal(expected, actual);\n\n            actual = Crypto.Hash(Encoding.UTF8.GetBytes(data), algorithm: \"MD5\");\n            Assert.Equal(expected, actual);\n        }\n\n        [Fact]\n        public void SHA1HashTest_ReturnsValidData()\n        {\n            string data = \"foo bar\";\n            string expected = \"3773DEA65156909838FA6C22825CAFE090FF8030\";\n            string actual;\n            actual = Crypto.SHA1(data);\n            Assert.Equal(expected, actual);\n\n            actual = Crypto.Hash(Encoding.UTF8.GetBytes(data), algorithm: \"sha1\");\n            Assert.Equal(expected, actual);\n        }\n\n        [Fact]\n        public void SHA1HashTest_WithNull_ThrowsException()\n        {\n            Assert.Throws<ArgumentNullException>(() => Crypto.SHA1((string)null));\n            Assert.Throws<ArgumentNullException>(() => Crypto.Hash((byte[])null, algorithm: \"SHa1\"));\n        }\n\n        [Fact]\n        public void SHA256HashTest_WithNull_ThrowsException()\n        {\n            Assert.Throws<ArgumentNullException>(() => Crypto.SHA256((string)null));\n            Assert.Throws<ArgumentNullException>(() => Crypto.Hash((byte[])null, algorithm: \"sHa256\"));\n        }\n\n        [Fact]\n        public void MD5HashTest_WithNull_ThrowsException()\n        {\n            Assert.Throws<ArgumentNullException>(() => Crypto.Hash((string)null, algorithm: \"mD5\"));\n            Assert.Throws<ArgumentNullException>(() => Crypto.Hash((byte[])null, algorithm: \"mD5\"));\n        }\n\n        [Fact]\n        public void HashWithUnknownAlg_ThrowsException()\n        {\n            Assert.Throws<InvalidOperationException>(() => Crypto.Hash(\"sdflksd\", algorithm: \"hao\"), \"The hash algorithm 'hao' is not supported, valid values are: sha256, sha1, md5\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Helpers.Test/DynamicDictionary.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Dynamic;\nusing System.Linq.Expressions;\nusing System.Reflection;\n\nnamespace System.Web.Helpers.Test\n{\n    /// <summary>\n    /// Dynamic object implementation over a dictionary that doesn't implement anything but the interface.\n    /// Used for testing our types that consume dynamic objects to make sure they don't make any assumptions on the implementation.\n    /// </summary>\n    public class DynamicDictionary : IDynamicMetaObjectProvider\n    {\n        private readonly Dictionary<string, object> _values = new Dictionary<string, object>();\n\n        public object this[string name]\n        {\n            get\n            {\n                object result;\n                _values.TryGetValue(name, out result);\n                return result;\n            }\n            set { _values[name] = value; }\n        }\n\n        public DynamicMetaObject GetMetaObject(Expression parameter)\n        {\n            return new DynamicDictionaryMetaObject(parameter, this);\n        }\n\n        private class DynamicDictionaryMetaObject : DynamicMetaObject\n        {\n            private static readonly PropertyInfo ItemPropery = typeof(DynamicDictionary).GetProperty(\"Item\");\n\n            public DynamicDictionaryMetaObject(Expression expression, object value)\n                : base(expression, BindingRestrictions.Empty, value)\n            {\n            }\n\n            private IDictionary<string, object> WrappedDictionary\n            {\n                get { return ((DynamicDictionary)Value)._values; }\n            }\n\n            private Expression GetDynamicExpression()\n            {\n                return Expression.Convert(Expression, typeof(DynamicDictionary));\n            }\n\n            private Expression GetIndexExpression(string key)\n            {\n                return Expression.MakeIndex(\n                    GetDynamicExpression(),\n                    ItemPropery,\n                    new[]\n                    {\n                        Expression.Constant(key)\n                    }\n                    );\n            }\n\n            private Expression GetSetValueExpression(string key, object value)\n            {\n                return Expression.Assign(\n                    GetIndexExpression(key),\n                    Expression.Convert(Expression.Constant(value),\n                                       typeof(object))\n                    );\n            }\n\n            public override DynamicMetaObject BindGetMember(GetMemberBinder binder)\n            {\n                var binderDefault = binder.FallbackGetMember(this);\n\n                var expression = Expression.Convert(GetIndexExpression(binder.Name),\n                                                    typeof(object));\n\n                var dynamicSuggestion = new DynamicMetaObject(expression, BindingRestrictions.GetTypeRestriction(Expression, LimitType)\n                                                                              .Merge(binderDefault.Restrictions));\n\n                return binder.FallbackGetMember(this, dynamicSuggestion);\n            }\n\n            public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value)\n            {\n                var binderDefault = binder.FallbackSetMember(this, value);\n\n                Expression expression = GetSetValueExpression(binder.Name, value.Value);\n\n                var dynamicSuggestion = new DynamicMetaObject(expression, BindingRestrictions.GetTypeRestriction(Expression, LimitType)\n                                                                              .Merge(binderDefault.Restrictions));\n\n                return binder.FallbackSetMember(this, value, dynamicSuggestion);\n            }\n\n            public override IEnumerable<string> GetDynamicMemberNames()\n            {\n                return WrappedDictionary.Keys;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Helpers.Test/DynamicHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Dynamic;\nusing Microsoft.Internal.Web.Utils;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Helpers.Test\n{\n    public class DynamicHelperTest\n    {\n        [Fact]\n        public void TryGetMemberValueReturnsValueIfBinderIsNotCSharp()\n        {\n            // Arrange\n            var mockMemberBinder = new MockMemberBinder(\"Foo\");\n            var dynamic = new DynamicWrapper(new { Foo = \"Bar\" });\n\n            // Act\n            object value;\n            bool result = DynamicHelper.TryGetMemberValue(dynamic, mockMemberBinder, out value);\n\n            // Assert\n            Assert.Equal(\"Bar\", value);\n        }\n\n        private class MockMemberBinder : GetMemberBinder\n        {\n            public MockMemberBinder(string name)\n                : base(name, false)\n            {\n            }\n\n            public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Helpers.Test/DynamicWrapper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Dynamic;\nusing System.Linq;\nusing System.Linq.Expressions;\nusing System.Reflection;\n\nnamespace System.Web.Helpers.Test\n{\n    /// <summary>\n    /// Dynamic object implementation over a regualar CLR object. Getmember accesses members through reflection.\n    /// </summary>\n    public class DynamicWrapper : IDynamicMetaObjectProvider\n    {\n        private object _object;\n\n        public DynamicWrapper(object obj)\n        {\n            _object = obj;\n        }\n\n        public DynamicMetaObject GetMetaObject(Expression parameter)\n        {\n            return new DynamicWrapperMetaObject(parameter, this);\n        }\n\n        private class DynamicWrapperMetaObject : DynamicMetaObject\n        {\n            public DynamicWrapperMetaObject(Expression expression, object value)\n                : base(expression, BindingRestrictions.Empty, value)\n            {\n            }\n\n            private object WrappedObject\n            {\n                get { return ((DynamicWrapper)Value)._object; }\n            }\n\n            private Expression GetDynamicExpression()\n            {\n                return Expression.Convert(Expression, typeof(DynamicWrapper));\n            }\n\n            private Expression GetWrappedObjectExpression()\n            {\n                FieldInfo fieldInfo = typeof(DynamicWrapper).GetField(\"_object\", BindingFlags.NonPublic | BindingFlags.Instance);\n                Debug.Assert(fieldInfo != null);\n                return Expression.Convert(\n                    Expression.Field(GetDynamicExpression(), fieldInfo),\n                    WrappedObject.GetType());\n            }\n\n            private Expression GetMemberAccessExpression(string memberName)\n            {\n                return Expression.Property(\n                    GetWrappedObjectExpression(),\n                    memberName);\n            }\n\n            public override DynamicMetaObject BindGetMember(GetMemberBinder binder)\n            {\n                var binderDefault = binder.FallbackGetMember(this);\n\n                var expression = Expression.Convert(GetMemberAccessExpression(binder.Name), typeof(object));\n\n                var dynamicSuggestion = new DynamicMetaObject(expression, BindingRestrictions.GetTypeRestriction(Expression, LimitType)\n                                                                              .Merge(binderDefault.Restrictions));\n\n                return binder.FallbackGetMember(this, dynamicSuggestion);\n            }\n\n            public override IEnumerable<string> GetDynamicMemberNames()\n            {\n                return (from p in WrappedObject.GetType().GetProperties()\n                        orderby p.Name\n                        select p.Name).ToArray();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Helpers.Test/HelperResultTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Web.WebPages;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Helpers.Test\n{\n    /// <summary>\n    /// This is a test class for Util is intended\n    /// to contain all HelperResult Unit Tests\n    /// </summary>\n    public class HelperResultTest\n    {\n        [Fact]\n        public void HelperResultConstructorNullTest()\n        {\n            Assert.ThrowsArgumentNull(() => { var helper = new HelperResult(null); }, \"action\");\n        }\n\n        [Fact]\n        public void ToStringTest()\n        {\n            var text = \"Hello\";\n            Action<TextWriter> action = tw => tw.Write(text);\n            var helper = new HelperResult(action);\n            Assert.Equal(text, helper.ToString());\n        }\n\n        [Fact]\n        public void WriteToTest()\n        {\n            var text = \"Hello\";\n            Action<TextWriter> action = tw => tw.Write(text);\n            var helper = new HelperResult(action);\n            var writer = new StringWriter();\n            helper.WriteTo(writer);\n            Assert.Equal(text, writer.ToString());\n        }\n\n        [Fact]\n        public void ToHtmlStringDoesNotEncode()\n        {\n            // Arrange\n            string text = \"<strong>This is a test & it uses html.</strong>\";\n            Action<TextWriter> action = writer => writer.Write(text);\n            HelperResult helperResult = new HelperResult(action);\n\n            // Act\n            string result = helperResult.ToHtmlString();\n\n            // Assert\n            Assert.Equal(result, text);\n        }\n\n        [Fact]\n        public void ToHtmlStringReturnsSameResultAsWriteTo()\n        {\n            // Arrange\n            string text = \"<strong>This is a test & it uses html.</strong>\";\n            Action<TextWriter> action = writer => writer.Write(text);\n            HelperResult helperResult = new HelperResult(action);\n            StringWriter stringWriter = new StringWriter();\n\n            // Act\n            string htmlString = helperResult.ToHtmlString();\n            helperResult.WriteTo(stringWriter);\n\n            // Assert\n            Assert.Equal(htmlString, stringWriter.ToString());\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Helpers.Test/JsonTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Dynamic;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Helpers.Test\n{\n    public class JsonTest\n    {\n        [Fact]\n        public void EncodeWithDynamicObject()\n        {\n            // Arrange\n            dynamic obj = new DummyDynamicObject();\n            obj.Name = \"Hello\";\n            obj.Age = 1;\n            obj.Grades = new[] { \"A\", \"B\", \"C\" };\n\n            // Act\n            string json = Json.Encode(obj);\n\n            // Assert\n            Assert.Equal(\"{\\\"Name\\\":\\\"Hello\\\",\\\"Age\\\":1,\\\"Grades\\\":[\\\"A\\\",\\\"B\\\",\\\"C\\\"]}\", json);\n        }\n\n        [Fact]\n        public void EncodeArray()\n        {\n            // Arrange\n            object input = new string[] { \"one\", \"2\", \"three\", \"4\" };\n\n            // Act\n            string json = Json.Encode(input);\n\n            // Assert\n            Assert.Equal(\"[\\\"one\\\",\\\"2\\\",\\\"three\\\",\\\"4\\\"]\", json);\n        }\n\n        [Fact]\n        public void EncodeDynamicJsonArrayEncodesAsArray()\n        {\n            // Arrange\n            dynamic array = Json.Decode(\"[1,2,3]\");\n\n            // Act\n            string json = Json.Encode(array);\n\n            // Assert\n            Assert.Equal(\"[1,2,3]\", json);\n        }\n\n        [Fact]\n        public void EncodeObjectWithArrayProperty()\n        {\n            // Arrange\n            dynamic personJson = Json.Decode(\"{name:'George', aliases: ['Peter', 'David']}\");\n\n            // Act\n            string json = Json.Encode(personJson);\n\n            // Assert\n            Assert.Equal(\"{\\\"name\\\":\\\"George\\\",\\\"aliases\\\":[\\\"Peter\\\",\\\"David\\\"]}\", json);\n        }\n\n        [Fact]\n        public void DecodeDynamicObject()\n        {\n            // Act\n            var obj = Json.Decode(\"{\\\"Name\\\":\\\"Hello\\\",\\\"Age\\\":1,\\\"Grades\\\":[\\\"A\\\",\\\"B\\\",\\\"C\\\"]}\");\n\n            // Assert\n            Assert.Equal(\"Hello\", obj.Name);\n            Assert.Equal(1, obj.Age);\n            Assert.Equal(3, obj.Grades.Length);\n            Assert.Equal(\"A\", obj.Grades[0]);\n            Assert.Equal(\"B\", obj.Grades[1]);\n            Assert.Equal(\"C\", obj.Grades[2]);\n        }\n\n        [Fact]\n        public void DecodeDynamicObjectImplicitConversionToDictionary()\n        {\n            // Act\n            IDictionary<string, object> values = Json.Decode(\"{\\\"Name\\\":\\\"Hello\\\",\\\"Age\\\":1}\");\n\n            // Assert\n            Assert.Equal(\"Hello\", values[\"Name\"]);\n            Assert.Equal(1, values[\"Age\"]);\n        }\n\n        [Fact]\n        public void DecodeArrayImplicitConversionToArrayAndObjectArray()\n        {\n            // Act\n            Array array = Json.Decode(\"[1,2,3]\");\n            object[] objArray = Json.Decode(\"[1,2,3]\");\n            IEnumerable<dynamic> dynamicEnumerable = Json.Decode(\"[{a:1}]\");\n\n            // Assert\n            Assert.NotNull(array);\n            Assert.NotNull(objArray);\n            Assert.NotNull(dynamicEnumerable);\n        }\n\n        [Fact]\n        public void DecodeArrayImplicitConversionToArrayArrayValuesAreDynamic()\n        {\n            // Act            \n            dynamic[] objArray = Json.Decode(\"[{\\\"A\\\":1}]\");\n\n            // Assert\n            Assert.NotNull(objArray);\n            Assert.Equal(1, objArray[0].A);\n        }\n\n        [Fact]\n        public void DecodeDynamicObjectAccessPropertiesByIndexer()\n        {\n            // Arrange\n            var obj = Json.Decode(\"{\\\"Name\\\":\\\"Hello\\\",\\\"Age\\\":1,\\\"Grades\\\":[\\\"A\\\",\\\"B\\\",\\\"C\\\"]}\");\n\n            // Assert\n            Assert.Equal(\"Hello\", obj[\"Name\"]);\n            Assert.Equal(1, obj[\"Age\"]);\n            Assert.Equal(3, obj[\"Grades\"].Length);\n            Assert.Equal(\"A\", obj[\"Grades\"][0]);\n            Assert.Equal(\"B\", obj[\"Grades\"][1]);\n            Assert.Equal(\"C\", obj[\"Grades\"][2]);\n        }\n\n        [Fact]\n        public void DecodeDynamicObjectAccessPropertiesByNullIndexerReturnsNull()\n        {\n            // Arrange\n            var obj = Json.Decode(\"{\\\"Name\\\":\\\"Hello\\\",\\\"Age\\\":1,\\\"Grades\\\":[\\\"A\\\",\\\"B\\\",\\\"C\\\"]}\");\n\n            // Assert\n            Assert.Null(obj[null]);\n        }\n\n        [Fact]\n        public void DecodeDateTime()\n        {\n            // Act\n            DateTime dateTime = Json.Decode(\"\\\"\\\\/Date(940402800000)\\\\/\\\"\");\n\n            // Assert\n            Assert.Equal(1999, dateTime.Year);\n            Assert.Equal(10, dateTime.Month);\n            Assert.Equal(20, dateTime.Day);\n        }\n\n        [Fact]\n        public void DecodeNumber()\n        {\n            // Act\n            int number = Json.Decode(\"1\");\n\n            // Assert\n            Assert.Equal(1, number);\n        }\n\n        [Fact]\n        public void DecodeString()\n        {\n            // Act\n            string @string = Json.Decode(\"\\\"1\\\"\");\n\n            // Assert\n            Assert.Equal(\"1\", @string);\n        }\n\n        [Fact]\n        public void DecodeArray()\n        {\n            // Act\n            var values = Json.Decode(\"[11,12,13,14,15]\");\n\n            // Assert            \n            Assert.Equal(5, values.Length);\n            Assert.Equal(11, values[0]);\n            Assert.Equal(12, values[1]);\n            Assert.Equal(13, values[2]);\n            Assert.Equal(14, values[3]);\n            Assert.Equal(15, values[4]);\n        }\n\n        [Fact]\n        public void DecodeObjectWithArrayProperty()\n        {\n            // Act\n            var obj = Json.Decode(\"{\\\"A\\\":1,\\\"B\\\":[1,3,4]}\");\n            object[] bValues = obj.B;\n\n            // Assert\n            Assert.Equal(1, obj.A);\n            Assert.Equal(1, bValues[0]);\n            Assert.Equal(3, bValues[1]);\n            Assert.Equal(4, bValues[2]);\n        }\n\n        [Fact]\n        public void DecodeArrayWithObjectValues()\n        {\n            // Act\n            var obj = Json.Decode(\"[{\\\"A\\\":1},{\\\"B\\\":3, \\\"C\\\": \\\"hello\\\"}]\");\n\n            // Assert\n            Assert.Equal(2, obj.Length);\n            Assert.Equal(1, obj[0].A);\n            Assert.Equal(3, obj[1].B);\n            Assert.Equal(\"hello\", obj[1].C);\n        }\n\n        [Fact]\n        public void DecodeArraySetValues()\n        {\n            // Arrange\n            var values = Json.Decode(\"[1,2,3,4,5]\");\n            for (int i = 0; i < values.Length; i++)\n            {\n                values[i]++;\n            }\n\n            // Assert\n            Assert.Equal(5, values.Length);\n            Assert.Equal(2, values[0]);\n            Assert.Equal(3, values[1]);\n            Assert.Equal(4, values[2]);\n            Assert.Equal(5, values[3]);\n            Assert.Equal(6, values[4]);\n        }\n\n        [Fact]\n        public void DecodeArrayPassToMethodThatTakesArray()\n        {\n            // Arrange\n            var values = Json.Decode(\"[3,2,1]\");\n\n            // Act\n            int index = Array.IndexOf(values, 2);\n\n            // Assert\n            Assert.Equal(1, index);\n        }\n\n        [Fact]\n        public void DecodeArrayGetEnumerator()\n        {\n            // Arrange\n            var values = Json.Decode(\"[1,2,3]\");\n\n            // Assert\n            int val = 1;\n            foreach (var value in values)\n            {\n                Assert.Equal(val, val);\n                val++;\n            }\n        }\n\n        [Fact]\n        public void DecodeObjectPropertyAccessIsSameObjectInstance()\n        {\n            // Arrange\n            var obj = Json.Decode(\"{\\\"Name\\\":{\\\"Version:\\\":4.0, \\\"Key\\\":\\\"Key\\\"}}\");\n\n            // Assert\n            Assert.Same(obj.Name, obj.Name);\n        }\n\n        [Fact]\n        public void DecodeArrayAccessingMembersThatDontExistReturnsNull()\n        {\n            // Act\n            var obj = Json.Decode(\"[\\\"a\\\", \\\"b\\\"]\");\n\n            // Assert\n            Assert.Null(obj.PropertyThatDoesNotExist);\n        }\n\n        [Fact]\n        public void DecodeObjectSetProperties()\n        {\n            // Act\n            var obj = Json.Decode(\"{\\\"A\\\":{\\\"B\\\":100}}\");\n            obj.A.B = 20;\n\n            // Assert\n            Assert.Equal(20, obj.A.B);\n        }\n\n        [Fact]\n        public void DecodeObjectSettingObjectProperties()\n        {\n            // Act\n            var obj = Json.Decode(\"{\\\"A\\\":1}\");\n            obj.A = new { B = 1, D = 2 };\n\n            // Assert\n            Assert.Equal(1, obj.A.B);\n            Assert.Equal(2, obj.A.D);\n        }\n\n        [Fact]\n        public void DecodeObjectWithArrayPropertyPassPropertyToMethodThatTakesArray()\n        {\n            // Arrange\n            var obj = Json.Decode(\"{\\\"A\\\":[3,2,1]}\");\n\n            // Act\n            Array.Sort(obj.A);\n\n            // Assert\n            Assert.Equal(1, obj.A[0]);\n            Assert.Equal(2, obj.A[1]);\n            Assert.Equal(3, obj.A[2]);\n        }\n\n        [Fact]\n        public void DecodeObjectAccessingMembersThatDontExistReturnsNull()\n        {\n            // Act\n            var obj = Json.Decode(\"{\\\"A\\\":1}\");\n\n            // Assert\n            Assert.Null(obj.PropertyThatDoesntExist);\n        }\n\n        [Fact]\n        public void DecodeObjectWithSpecificType()\n        {\n            // Act\n            var person = Json.Decode<Person>(\"{\\\"Name\\\":\\\"David\\\", \\\"Age\\\":2}\");\n\n            // Assert\n            Assert.Equal(\"David\", person.Name);\n            Assert.Equal(2, person.Age);\n        }\n\n        [Fact]\n        public void DecodeObjectWithImplicitConversionToNonDynamicTypeThrows()\n        {\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(() => { Person person = Json.Decode(\"{\\\"Name\\\":\\\"David\\\", \\\"Age\\\":2, \\\"Address\\\":{\\\"Street\\\":\\\"Bellevue\\\"}}\"); }, \"Unable to convert to \\\"System.Web.Helpers.Test.JsonTest+Person\\\". Use Json.Decode<T> instead.\");\n        }\n\n        private class DummyDynamicObject : DynamicObject\n        {\n            private IDictionary<string, object> _values = new Dictionary<string, object>();\n\n            public override IEnumerable<string> GetDynamicMemberNames()\n            {\n                return _values.Keys;\n            }\n\n            public override bool TrySetMember(SetMemberBinder binder, object value)\n            {\n                _values[binder.Name] = value;\n                return true;\n            }\n\n            public override bool TryGetMember(GetMemberBinder binder, out object result)\n            {\n                return _values.TryGetValue(binder.Name, out result);\n            }\n        }\n\n        private class Person\n        {\n            public string Name { get; set; }\n            public int Age { get; set; }\n            public int GPA { get; set; }\n            public Address Address { get; set; }\n        }\n\n        private class Address\n        {\n            public string Street { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Helpers.Test/ObjectInfoTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Dynamic;\nusing System.Linq;\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Helpers.Test\n{\n    public class ObjectInfoTest\n    {\n        [Fact]\n        public void PrintWithNegativeDepthThrows()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(() => ObjectInfo.Print(null, depth: -1), \"depth\", \"0\");\n        }\n\n        [Fact]\n        public void PrintWithInvalidEnumerationLength()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentGreaterThan(() => ObjectInfo.Print(null, enumerationLength: -1), \"enumerationLength\", \"0\");\n        }\n\n        [Fact]\n        public void PrintWithNull()\n        {\n            // Arrange\n            MockObjectVisitor visitor = CreateObjectVisitor();\n\n            // Act\n            visitor.Print(null);\n\n            // Assert\n            string value = Assert.Single(visitor.Values);\n            Assert.Equal(\"null\", value);\n        }\n\n        [Fact]\n        public void PrintWithEmptyString()\n        {\n            // Arrange\n            MockObjectVisitor visitor = CreateObjectVisitor();\n\n            // Act\n            visitor.Print(String.Empty);\n\n            // Assert\n            string value = Assert.Single(visitor.Values);\n            Assert.Equal(String.Empty, value);\n        }\n\n        [Fact]\n        public void PrintWithInt()\n        {\n            // Arrange\n            MockObjectVisitor visitor = CreateObjectVisitor();\n\n            // Act\n            visitor.Print(404);\n\n            // Assert\n            string value = Assert.Single(visitor.Values);\n            Assert.Equal(\"404\", value);\n        }\n\n        [Fact]\n        public void PrintWithIDictionary()\n        {\n            // Arrange\n            MockObjectVisitor visitor = CreateObjectVisitor();\n            IDictionary dict = new OrderedDictionary();\n            dict.Add(\"foo\", \"bar\");\n            dict.Add(\"abc\", 500);\n\n            // Act\n            visitor.Print(dict);\n\n            // Assert\n            Assert.Equal(\"foo = bar\", visitor.KeyValuePairs[0]);\n            Assert.Equal(\"abc = 500\", visitor.KeyValuePairs[1]);\n        }\n\n        [Fact]\n        public void PrintWithIEnumerable()\n        {\n            // Arrange\n            MockObjectVisitor visitor = CreateObjectVisitor();\n            var values = Enumerable.Range(0, 10);\n\n            // Act\n            visitor.Print(values);\n\n            // Assert\n            foreach (var num in values)\n            {\n                Assert.Contains(num.ToString(), visitor.Values);\n            }\n        }\n\n        [Fact]\n        public void PrintWithGenericIListPrintsIndex()\n        {\n            // Arrange\n            MockObjectVisitor visitor = CreateObjectVisitor();\n            var values = Enumerable.Range(0, 10).ToList();\n\n            // Act\n            visitor.Print(values);\n\n            // Assert\n            for (int i = 0; i < values.Count; i++)\n            {\n                Assert.Contains(values[i].ToString(), visitor.Values);\n                Assert.Contains(i, visitor.Indexes);\n            }\n        }\n\n        [Fact]\n        public void PrintWithArrayPrintsIndex()\n        {\n            // Arrange\n            MockObjectVisitor visitor = CreateObjectVisitor();\n            var values = Enumerable.Range(0, 10).ToArray();\n\n            // Act\n            visitor.Print(values);\n\n            // Assert\n            for (int i = 0; i < values.Length; i++)\n            {\n                Assert.Contains(values[i].ToString(), visitor.Values);\n                Assert.Contains(i, visitor.Indexes);\n            }\n        }\n\n        [Fact]\n        public void PrintNameValueCollectionPrintsKeysAndValues()\n        {\n            // Arrange\n            MockObjectVisitor visitor = CreateObjectVisitor();\n            var values = new NameValueCollection();\n            values[\"a\"] = \"1\";\n            values[\"b\"] = null;\n\n            // Act\n            visitor.Print(values);\n\n            // Assert\n            Assert.Equal(\"a = 1\", visitor.KeyValuePairs[0]);\n            Assert.Equal(\"b = null\", visitor.KeyValuePairs[1]);\n        }\n\n        [Fact]\n        public void PrintDateTime()\n        {\n            using (new CultureReplacer(\"en-US\"))\n            {\n                // Arrange\n                MockObjectVisitor visitor = CreateObjectVisitor();\n                var dt = new DateTime(2001, 11, 20, 10, 30, 1);\n\n                // Act\n                visitor.Print(dt);\n\n                // Assert\n                Assert.Equal(\"11/20/2001 10:30:01 AM\", visitor.Values[0]);\n            }\n        }\n\n        [Fact]\n        public void PrintCustomObjectPrintsMembers()\n        {\n            // Arrange\n            MockObjectVisitor visitor = CreateObjectVisitor();\n            var person = new Person\n            {\n                Name = \"David\",\n                Age = 23.3,\n                Dob = new DateTime(1986, 11, 19),\n                LongType = 1000000000,\n                Type = 1\n            };\n\n            using (new CultureReplacer(\"en-US\"))\n            {\n                // Act\n                visitor.Print(person);\n\n                // Assert\n                Assert.Equal(9, visitor.Members.Count);\n                Assert.Contains(\"double Age = 23.3\", visitor.Members);\n                Assert.Contains(\"string Name = David\", visitor.Members);\n                Assert.Contains(\"DateTime Dob = 11/19/1986 12:00:00 AM\", visitor.Members);\n                Assert.Contains(\"short Type = 1\", visitor.Members);\n                Assert.Contains(\"float Float = 0\", visitor.Members);\n                Assert.Contains(\"byte Byte = 0\", visitor.Members);\n                Assert.Contains(\"decimal Decimal = 0\", visitor.Members);\n                Assert.Contains(\"bool Bool = False\", visitor.Members);\n            }\n        }\n\n        [Fact]\n        public void PrintShowsVisitedWhenCircularReferenceInObjectGraph()\n        {\n            // Arrange\n            MockObjectVisitor visitor = CreateObjectVisitor();\n            PersonNode node = new PersonNode\n            {\n                Person = new Person\n                {\n                    Name = \"David\",\n                    Age = 23.3\n                }\n            };\n            node.Next = node;\n\n            // Act\n            visitor.Print(node);\n\n            // Assert\n            Assert.Contains(\"string Name = David\", visitor.Members);\n            Assert.Contains(String.Format(\"double Age = {0}\", 23.3), visitor.Members);\n            Assert.Contains(\"PersonNode Next = Visited\", visitor.Members);\n        }\n\n        [Fact]\n        public void PrintShowsVisitedWhenCircularReferenceIsIEnumerable()\n        {\n            // Arrange\n            MockObjectVisitor visitor = CreateObjectVisitor();\n            List<object> values = new List<object>();\n            values.Add(values);\n\n            // Act\n            visitor.Print(values);\n\n            // Assert\n            Assert.Equal(\"Visited\", visitor.Values[0]);\n            Assert.Equal(\"Visited \" + values.GetHashCode(), visitor.Visited[0]);\n        }\n\n        [Fact]\n        public void PrintShowsVisitedWhenCircularReferenceIsIDictionary()\n        {\n            // Arrange\n            MockObjectVisitor visitor = CreateObjectVisitor();\n            OrderedDictionary values = new OrderedDictionary();\n            values[values] = values;\n\n            // Act\n            visitor.Print(values);\n\n            // Assert\n            Assert.Equal(\"Visited\", visitor.Values[0]);\n            Assert.Equal(\"Visited \" + values.GetHashCode(), visitor.Visited[0]);\n        }\n\n        [Fact]\n        public void PrintShowsVisitedWhenCircularReferenceIsNameValueCollection()\n        {\n            // Arrange\n            MockObjectVisitor visitor = CreateObjectVisitor();\n            NameValueCollection nameValues = new NameValueCollection();\n            nameValues[\"id\"] = \"1\";\n            List<NameValueCollection> values = new List<NameValueCollection>();\n            values.Add(nameValues);\n            values.Add(nameValues);\n\n            // Act\n            visitor.Print(values);\n\n            // Assert\n            Assert.Contains(\"Visited\", visitor.Values);\n            Assert.Contains(\"Visited \" + nameValues.GetHashCode(), visitor.Visited);\n        }\n\n        [Fact]\n        public void PrintExcludesWriteOnlyProperties()\n        {\n            // Arrange\n            MockObjectVisitor visitor = CreateObjectVisitor();\n            ClassWithWriteOnlyProperty cls = new ClassWithWriteOnlyProperty();\n\n            // Act\n            visitor.Print(cls);\n\n            // Assert\n            Assert.Empty(visitor.Members);\n        }\n\n        [Fact]\n        public void PrintWritesEnumeratedElementsUntilLimitIsReached()\n        {\n            // Arrange\n            MockObjectVisitor visitor = CreateObjectVisitor();\n            var enumeration = Enumerable.Range(0, 2000);\n\n            // Act\n            visitor.Print(enumeration);\n\n            // Assert\n            for (int i = 0; i <= 2000; i++)\n            {\n                if (i < 1000)\n                {\n                    Assert.Contains(i.ToString(), visitor.Values);\n                }\n                else\n                {\n                    Assert.DoesNotContain(i.ToString(), visitor.Values);\n                }\n            }\n            Assert.Contains(\"Limit Exceeded\", visitor.Values);\n        }\n\n        [Fact]\n        public void PrintWithAnonymousType()\n        {\n            // Arrange\n            MockObjectVisitor visitor = CreateObjectVisitor();\n            var value = new { Name = \"John\", X = 1 };\n\n            // Act\n            visitor.Print(value);\n\n            // Assert\n            Assert.Contains(\"string Name = John\", visitor.Members);\n            Assert.Contains(\"int X = 1\", visitor.Members);\n        }\n\n        [Fact]\n        public void PrintClassWithPublicFields()\n        {\n            // Arrange\n            MockObjectVisitor visitor = CreateObjectVisitor();\n            ClassWithFields value = new ClassWithFields();\n            value.Foo = \"John\";\n            value.Bar = 1;\n\n            // Actt\n            visitor.Print(value);\n\n            // Assert\n            Assert.Contains(\"string Foo = John\", visitor.Members);\n            Assert.Contains(\"int Bar = 1\", visitor.Members);\n        }\n\n        [Fact]\n        public void PrintClassWithDynamicMembersPrintsMembersIfGetDynamicMemberNamesIsImplemented()\n        {\n            // Arrange\n            MockObjectVisitor visitor = CreateObjectVisitor();\n            dynamic d = new DynamicDictionary();\n            d.Cycle = d;\n            d.Name = \"Foo\";\n            d.Value = null;\n\n            // Act\n            visitor.Print(d);\n\n            // Assert\n            Assert.Contains(\"DynamicDictionary Cycle = Visited\", visitor.Members);\n            Assert.Contains(\"string Name = Foo\", visitor.Members);\n            Assert.Contains(\"Value = null\", visitor.Members);\n        }\n\n        [Fact]\n        public void PrintClassWithDynamicMembersReturningNullPrintsNoMembers()\n        {\n            // Arrange\n            MockObjectVisitor visitor = CreateObjectVisitor();\n            dynamic d = new ClassWithDynamicAnNullMemberNames();\n            d.Cycle = d;\n            d.Name = \"Foo\";\n            d.Value = null;\n\n            // Act\n            visitor.Print(d);\n\n            // Assert\n            Assert.False(visitor.Members.Any());\n        }\n\n        [Fact]\n        public void PrintUsesToStringOfIConvertibleObjects()\n        {\n            // Arrange\n            MockObjectVisitor visitor = CreateObjectVisitor();\n            ConvertibleClass cls = new ConvertibleClass();\n\n            // Act\n            visitor.Print(cls);\n\n            // Assert\n            Assert.Equal(\"Test\", visitor.Values[0]);\n        }\n\n        [Fact]\n        public void PrintConvertsTypeToString()\n        {\n            // Arrange\n            MockObjectVisitor visitor = CreateObjectVisitor();\n\n            // Act\n            visitor.Print(typeof(string));\n\n            // Assert\n            Assert.Equal(\"typeof(string)\", visitor.Values[0]);\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void PrintClassWithPropertyThatThrowsExceptionPrintsException()\n        {\n            // Arrange\n            MockObjectVisitor visitor = CreateObjectVisitor();\n            ClassWithPropertyThatThrowsException value = new ClassWithPropertyThatThrowsException();\n\n            // Act\n            visitor.Print(value);\n\n            // Assert\n            Assert.Equal(\"int MyProperty = Property accessor 'MyProperty' on object 'System.Web.Helpers.Test.ObjectInfoTest+ClassWithPropertyThatThrowsException' threw the following exception:'Property that shows an exception'\", visitor.Members[0]);\n        }\n\n        [Fact]\n        public void ConvertEscapeSequencesPrintsStringEscapeSequencesAsLiterals()\n        {\n            // Act\n            string value = HtmlObjectPrinter.ConvertEscapseSequences(\"\\\\\\'\\\"\\0\\a\\b\\f\\n\\r\\t\\v\");\n\n            // Assert\n            Assert.Equal(\"\\\\\\\\'\\\\\\\"\\\\0\\\\a\\\\b\\\\f\\\\n\\\\r\\\\t\\\\v\", value);\n        }\n\n        [Fact]\n        public void ConvertEscapeSequencesDoesNotEscapeUnicodeSequences()\n        {\n            // Act\n            string value = HtmlObjectPrinter.ConvertEscapseSequences(\"\\u1023\\x2045\");\n\n            // Assert\n            Assert.Equal(\"\\u1023\\x2045\", value);\n        }\n\n        [Fact]\n        public void PrintCharPrintsQuotedString()\n        {\n            // Arrange\n            HtmlObjectPrinter printer = new HtmlObjectPrinter(100, 100);\n            HtmlElement element = new HtmlElement(\"span\");\n            printer.PushElement(element);\n\n            // Act\n            printer.VisitConvertedValue('x', \"x\");\n\n            // Assert\n            Assert.Equal(1, element.Children.Count);\n            HtmlElement child = element.Children[0];\n            Assert.Equal(\"'x'\", child.InnerText);\n            Assert.Equal(\"quote\", child[\"class\"]);\n        }\n\n        [Fact]\n        public void PrintEscapeCharPrintsEscapedCharAsLiteral()\n        {\n            // Arrange\n            HtmlObjectPrinter printer = new HtmlObjectPrinter(100, 100);\n            HtmlElement element = new HtmlElement(\"span\");\n            printer.PushElement(element);\n\n            // Act\n            printer.VisitConvertedValue('\\t', \"\\t\");\n\n            // Assert\n            Assert.Equal(1, element.Children.Count);\n            HtmlElement child = element.Children[0];\n            Assert.Equal(\"'\\\\t'\", child.InnerText);\n            Assert.Equal(\"quote\", child[\"class\"]);\n        }\n\n        [Fact]\n        public void GetTypeNameConvertsGenericTypesToCsharpSyntax()\n        {\n            // Act\n            string value = ObjectVisitor.GetTypeName(typeof(Func<Func<Func<int, int, object>, Action<int>>>));\n\n            // Assert\n            Assert.Equal(\"Func<Func<Func<int, int, object>, Action<int>>>\", value);\n        }\n\n        private class ConvertibleClass : IConvertible\n        {\n            public TypeCode GetTypeCode()\n            {\n                throw new NotImplementedException();\n            }\n\n            public bool ToBoolean(IFormatProvider provider)\n            {\n                throw new NotImplementedException();\n            }\n\n            public byte ToByte(IFormatProvider provider)\n            {\n                throw new NotImplementedException();\n            }\n\n            public char ToChar(IFormatProvider provider)\n            {\n                throw new NotImplementedException();\n            }\n\n            public DateTime ToDateTime(IFormatProvider provider)\n            {\n                throw new NotImplementedException();\n            }\n\n            public decimal ToDecimal(IFormatProvider provider)\n            {\n                throw new NotImplementedException();\n            }\n\n            public double ToDouble(IFormatProvider provider)\n            {\n                throw new NotImplementedException();\n            }\n\n            public short ToInt16(IFormatProvider provider)\n            {\n                throw new NotImplementedException();\n            }\n\n            public int ToInt32(IFormatProvider provider)\n            {\n                throw new NotImplementedException();\n            }\n\n            public long ToInt64(IFormatProvider provider)\n            {\n                throw new NotImplementedException();\n            }\n\n            public sbyte ToSByte(IFormatProvider provider)\n            {\n                throw new NotImplementedException();\n            }\n\n            public float ToSingle(IFormatProvider provider)\n            {\n                throw new NotImplementedException();\n            }\n\n            public string ToString(IFormatProvider provider)\n            {\n                return \"Test\";\n            }\n\n            public object ToType(Type conversionType, IFormatProvider provider)\n            {\n                throw new NotImplementedException();\n            }\n\n            public ushort ToUInt16(IFormatProvider provider)\n            {\n                throw new NotImplementedException();\n            }\n\n            public uint ToUInt32(IFormatProvider provider)\n            {\n                throw new NotImplementedException();\n            }\n\n            public ulong ToUInt64(IFormatProvider provider)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class ClassWithPropertyThatThrowsException\n        {\n            public int MyProperty\n            {\n                get { throw new InvalidOperationException(\"Property that shows an exception\"); }\n            }\n        }\n\n        private class ClassWithDynamicAnNullMemberNames : DynamicObject\n        {\n            public override IEnumerable<string> GetDynamicMemberNames()\n            {\n                return null;\n            }\n\n            public override bool TryGetMember(GetMemberBinder binder, out object result)\n            {\n                result = null;\n                return true;\n            }\n\n            public override bool TrySetMember(SetMemberBinder binder, object value)\n            {\n                return true;\n            }\n        }\n\n        private class Person\n        {\n            public string Name { get; set; }\n            public double Age { get; set; }\n            public DateTime Dob { get; set; }\n            public short Type { get; set; }\n            public long LongType { get; set; }\n            public float Float { get; set; }\n            public byte Byte { get; set; }\n            public decimal Decimal { get; set; }\n            public bool Bool { get; set; }\n        }\n\n        private class ClassWithFields\n        {\n            public string Foo;\n            public int Bar = 13;\n        }\n\n        private class ClassWithWriteOnlyProperty\n        {\n            public int Value\n            {\n                set { }\n            }\n        }\n\n        private class PersonNode\n        {\n            public Person Person { get; set; }\n            public PersonNode Next { get; set; }\n        }\n\n        private MockObjectVisitor CreateObjectVisitor(int recursionLimit = 10, int enumerationLimit = 1000)\n        {\n            return new MockObjectVisitor(recursionLimit, enumerationLimit);\n        }\n\n        private class MockObjectVisitor : ObjectVisitor\n        {\n            public MockObjectVisitor(int recursionLimit, int enumerationLimit)\n                : base(recursionLimit, enumerationLimit)\n            {\n                Values = new List<string>();\n                KeyValuePairs = new List<string>();\n                Members = new List<string>();\n                Indexes = new List<int>();\n                Visited = new List<string>();\n            }\n\n            public List<string> Values { get; set; }\n            public List<string> KeyValuePairs { get; set; }\n            public List<string> Members { get; set; }\n            public List<int> Indexes { get; set; }\n            public List<string> Visited { get; set; }\n\n            public void Print(object value)\n            {\n                Visit(value, 0);\n            }\n\n            public override void VisitObjectVisitorException(ObjectVisitorException exception)\n            {\n                Values.Add(exception.InnerException.Message);\n            }\n\n            public override void VisitStringValue(string stringValue)\n            {\n                Values.Add(stringValue);\n                base.VisitStringValue(stringValue);\n            }\n\n            public override void VisitVisitedObject(string id, object value)\n            {\n                Visited.Add(String.Format(\"Visited {0}\", id));\n                Values.Add(\"Visited\");\n                base.VisitVisitedObject(id, value);\n            }\n\n            public override void VisitIndexedEnumeratedValue(int index, object item, int depth)\n            {\n                Indexes.Add(index);\n                base.VisitIndexedEnumeratedValue(index, item, depth);\n            }\n\n            public override void VisitEnumeratonLimitExceeded()\n            {\n                Values.Add(\"Limit Exceeded\");\n                base.VisitEnumeratonLimitExceeded();\n            }\n\n            public override void VisitMember(string name, Type type, object value, int depth)\n            {\n                base.VisitMember(name, type, value, depth);\n                type = type ?? (value != null ? value.GetType() : null);\n                if (type == null)\n                {\n                    Members.Add(String.Format(\"{0} = null\", name));\n                }\n                else\n                {\n                    Members.Add(String.Format(\"{0} {1} = {2}\", GetTypeName(type), name, Values.Last()));\n                }\n            }\n\n            public override void VisitNull()\n            {\n                Values.Add(\"null\");\n                base.VisitNull();\n            }\n\n            public override void VisitKeyValue(object key, object value, int depth)\n            {\n                base.VisitKeyValue(key, value, depth);\n                KeyValuePairs.Add(String.Format(\"{0} = {1}\", Values[Values.Count - 2], Values[Values.Count - 1]));\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Helpers.Test/PreComputedGridDataSourceTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Helpers.Test\n{\n    public class PreComputedGridDataSourceTest\n    {\n        [Fact]\n        public void PreSortedDataSourceReturnsRowCountItWasSpecified()\n        {\n            // Arrange\n            int rows = 20;\n            var dataSource = new PreComputedGridDataSource(new WebGrid(GetContext()), values: Enumerable.Range(0, 10).Cast<dynamic>(), totalRows: rows);\n\n            // Act and Assert\n            Assert.Equal(rows, dataSource.TotalRowCount);\n        }\n\n        [Fact]\n        public void PreSortedDataSourceReturnsAllRows()\n        {\n            // Arrange\n            var grid = new WebGrid(GetContext());\n            var dataSource = new PreComputedGridDataSource(grid: grid, values: Enumerable.Range(0, 10).Cast<dynamic>(), totalRows: 10);\n\n            // Act\n            var rows = dataSource.GetRows(new SortInfo { SortColumn = String.Empty }, 0);\n\n            // Assert\n            Assert.Equal(10, rows.Count);\n            Assert.Equal(0, rows.First().Value);\n            Assert.Equal(9, rows.Last().Value);\n        }\n\n        private HttpContextBase GetContext()\n        {\n            return new Mock<HttpContextBase>().Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Helpers.Test/ServerInfoTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Helpers.Test\n{\n    public class InfoTest\n    {\n        [Fact]\n        public void ConfigurationReturnsExpectedInfo()\n        {\n            var configInfo = ServerInfo.Configuration();\n\n            // verification\n            // checks only subset of values\n            Assert.NotNull(configInfo);\n            VerifyKey(configInfo, \"Machine Name\");\n            VerifyKey(configInfo, \"OS Version\");\n            VerifyKey(configInfo, \"ASP.NET Version\");\n            VerifyKey(configInfo, \"ASP.NET Web Pages Version\");\n        }\n\n        [Fact]\n        public void EnvironmentVariablesReturnsExpectedInfo()\n        {\n            var envVariables = ServerInfo.EnvironmentVariables();\n\n            // verification\n            // checks only subset of values\n            Assert.NotNull(envVariables);\n            VerifyKey(envVariables, \"Path\");\n            VerifyKey(envVariables, \"SystemDrive\");\n        }\n\n        [Fact]\n        public void ServerVariablesReturnsExpectedInfoWithNoContext()\n        {\n            var serverVariables = ServerInfo.ServerVariables();\n\n            // verification\n            // since there is no HttpContext this will be empty\n            Assert.NotNull(serverVariables);\n        }\n\n        [Fact]\n        public void ServerVariablesReturnsExpectedInfoWthContext()\n        {\n            var serverVariables = new NameValueCollection();\n            serverVariables.Add(\"foo\", \"bar\");\n\n            var request = new Mock<HttpRequestBase>();\n            request.Setup(c => c.ServerVariables).Returns(serverVariables);\n\n            var context = new Mock<HttpContextBase>();\n            context.Setup(c => c.Request).Returns(request.Object);\n\n            // verification\n            Assert.NotNull(serverVariables);\n\n            IDictionary<string, string> returnedValues = ServerInfo.ServerVariables(context.Object);\n            Assert.Equal(serverVariables.Count, returnedValues.Count);\n            foreach (var item in returnedValues)\n            {\n                Assert.Equal(serverVariables[item.Key], item.Value);\n            }\n        }\n\n#if false // Avoid an NRE when accessing HttpRuntime.BinDirectory without initializing the runtime.\n        [Fact]\n        public void HttpRuntimeInfoReturnsExpectedInfo()\n        {\n            var httpRuntimeInfo = ServerInfo.HttpRuntimeInfo();\n\n            // verification\n            // checks only subset of values\n            Assert.NotNull(httpRuntimeInfo);\n            VerifyKey(httpRuntimeInfo, \"CLR Install Directory\");\n            VerifyKey(httpRuntimeInfo, \"Asp Install Directory\");\n            VerifyKey(httpRuntimeInfo, \"On UNC Share\");\n        }\n#endif\n\n        [Fact]\n        public void ServerInfoDoesNotProduceLegacyCasForHomogenousAppDomain()\n        {\n            // Act and Assert\n            Action action = () =>\n            {\n                IDictionary<string, string> configValue = ServerInfo.LegacyCAS(AppDomain.CurrentDomain);\n\n                Assert.NotNull(configValue);\n                Assert.Equal(0, configValue.Count);\n            };\n\n            AppDomainUtils.RunInSeparateAppDomain(GetAppDomainSetup(legacyCasEnabled: false), action);\n        }\n\n        [Fact]\n        public void ServerInfoProducesLegacyCasForNonHomogenousAppDomain()\n        {\n            // Arrange\n            Action action = () =>\n            {\n                // Act and Assert\n                IDictionary<string, string> configValue = ServerInfo.LegacyCAS(AppDomain.CurrentDomain);\n\n                // Assert\n                Assert.True(configValue.ContainsKey(\"Legacy Code Access Security\"));\n                Assert.Equal(\"Legacy Code Access Security has been detected on your system. Microsoft WebPage features require the ASP.NET 4 Code Access Security model. For information about how to resolve this, contact your server administrator.\", configValue[\"Legacy Code Access Security\"]);\n            };\n\n            AppDomainUtils.RunInSeparateAppDomain(GetAppDomainSetup(legacyCasEnabled: true), action);\n        }\n\n        //[Fact]\n        //public void SqlServerInfoReturnsExpectedInfo() {\n        //    var sqlInfo = ServerInfo.SqlServerInfo();\n\n        //    // verification\n        //    // just verifies that we don't get any unexpected exceptions\n        //    Assert.NotNull(sqlInfo);\n        //}\n\n#if false // Avoid NREs when accessing HttpRuntime.BinDirectory without initializing the runtime.\n        [Fact]\n        public void RenderResultContainsExpectedTags()\n        {\n            var htmlString = ServerInfo.GetHtml().ToString();\n\n            // just verify that the final HTML produced contains some expected info\n            Assert.True(htmlString.Contains(\"<table class=\\\"server-info\\\" dir=\\\"ltr\\\">\"));\n            Assert.True(htmlString.Contains(\"</style>\"));\n            Assert.True(htmlString.Contains(\"Server Configuration\"));\n        }\n\n        [Fact]\n        public void RenderGeneratesValidXhtml()\n        {\n            // Result does not validate against XHTML 1.1 and HTML5 because ServerInfo generates\n            // <style> inside <body>. This is by design however since we only use ServerInfo\n            // as debugging aid, not something to be permanently added to a web page.\n            XhtmlAssert.Validate1_0(\n                ServerInfo.GetHtml(),\n                addRoot: true\n                );\n        }\n#endif\n\n        private void VerifyKey(IDictionary<string, string> info, string key)\n        {\n            Assert.True(info.ContainsKey(key));\n            Assert.False(String.IsNullOrEmpty(info[key]));\n        }\n\n        private AppDomainSetup GetAppDomainSetup(bool legacyCasEnabled)\n        {\n            var setup = new AppDomainSetup();\n            if (legacyCasEnabled)\n            {\n                setup.SetCompatibilitySwitches(new[] { \"NetFx40_LegacySecurityPolicy\" });\n            }\n            return setup;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Helpers.Test/System.Web.Helpers.Test.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props\" Condition=\"Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" />\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" />\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{D3313BDF-8071-4AC8-9D98-ABF7F9E88A57}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>System.Web.Helpers.Test</RootNamespace>\n    <AssemblyName>System.Web.Helpers.Test</AssemblyName>\n    <OutputPath>..\\..\\bin\\$(Configuration)\\Test\\</OutputPath>\n    <NuGetPackageImportStamp>\n    </NuGetPackageImportStamp>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Castle.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Castle.Core.5.1.1\\lib\\net462\\Castle.Core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Moq, Version=4.18.0.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Moq.4.18.4\\lib\\net462\\Moq.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Drawing\" />\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"System.Web.DataVisualization\" />\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"System.XML\" />\n    <Reference Include=\"xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.abstractions.2.0.3\\lib\\net35\\xunit.abstractions.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.assert, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.assert.2.4.2\\lib\\netstandard1.1\\xunit.assert.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.core, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.core.2.4.2\\lib\\net452\\xunit.core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.execution.desktop, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.execution.2.4.2\\lib\\net452\\xunit.execution.desktop.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"ChartTest.cs\" />\n    <Compile Include=\"ConversionUtilTest.cs\" />\n    <Compile Include=\"CryptoTest.cs\" />\n    <Compile Include=\"DynamicDictionary.cs\" />\n    <Compile Include=\"DynamicHelperTest.cs\" />\n    <Compile Include=\"DynamicWrapper.cs\" />\n    <Compile Include=\"JsonTest.cs\" />\n    <Compile Include=\"ObjectInfoTest.cs\" />\n    <Compile Include=\"PreComputedGridDataSourceTest.cs\" />\n    <Compile Include=\"WebCacheTest.cs\" />\n    <Compile Include=\"HelperResultTest.cs\" />\n    <Compile Include=\"ServerInfoTest.cs\" />\n    <Compile Include=\"WebGridDataSourceTest.cs\" />\n    <Compile Include=\"WebGridTest.cs\" />\n    <Compile Include=\"WebImageTest.cs\" />\n    <Compile Include=\"WebMailTest.cs\" />\n    <Compile Include=\"XhtmlAssert.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.WebPages\\System.Web.WebPages.csproj\">\n      <Project>{76EFA9C5-8D7E-4FDF-B710-E20F8B6B00D2}</Project>\n      <Name>System.Web.WebPages</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Helpers\\System.Web.Helpers.csproj\">\n      <Project>{9B7E3740-6161-4548-833C-4BBCA43B970E}</Project>\n      <Name>System.Web.Helpers</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\">\n      <Project>{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}</Project>\n      <Name>Microsoft.TestCommon</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\LambdaFinal.jpg\" />\n    <EmbeddedResource Include=\"TestFiles\\logo.bmp\" />\n    <EmbeddedResource Include=\"TestFiles\\NETLogo.png\" />\n    <EmbeddedResource Include=\"TestFiles\\Test.ico\" />\n    <EmbeddedResource Include=\"TestFiles\\xhtml11-flat.dtd\" />\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Service Include=\"{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Analyzer Include=\"..\\..\\packages\\xunit.analyzers.1.1.0\\analyzers\\dotnet\\cs\\xunit.analyzers.dll\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\n  <Target Name=\"EnsureNuGetPackageBuildImports\" BeforeTargets=\"PrepareForBuild\">\n    <PropertyGroup>\n      <ErrorText>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}.</ErrorText>\n    </PropertyGroup>\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props'))\" />\n  </Target>\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" />\n</Project>"
  },
  {
    "path": "test/System.Web.Helpers.Test/TestFiles/xhtml11-flat.dtd",
    "content": "<!-- ....................................................................... -->\n<!-- XHTML 1.1 DTD  ........................................................ -->\n<!-- file: xhtml11.dtd\n-->\n\n<!-- XHTML 1.1 DTD\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n\n     The Extensible HyperText Markup Language (XHTML)\n     Copyright 1998-2000 World Wide Web Consortium\n        (Massachusetts Institute of Technology, Institut National de\n         Recherche en Informatique et en Automatique, Keio University).\n         All Rights Reserved.\n\n     Permission to use, copy, modify and distribute the XHTML DTD and its \n     accompanying documentation for any purpose and without fee is hereby \n     granted in perpetuity, provided that the above copyright notice and \n     this paragraph appear in all copies.  The copyright holders make no \n     representation about the suitability of the DTD for any purpose.\n\n     It is provided \"as is\" without expressed or implied warranty.\n\n        Author:     Murray M. Altheim <altheim@eng.sun.com>\n        Revision:   $Id: xhtml11.dtd,v 1.20 2001/04/05 14:20:51 ahby Exp $\n\n-->\n<!-- This is the driver file for version 1.1 of the XHTML DTD.\n\n     Please use this formal public identifier to identify it:\n\n         \"-//W3C//DTD XHTML 1.1//EN\"\n-->\n<!ENTITY % XHTML.version  \"-//W3C//DTD XHTML 1.1//EN\" >\n\n<!-- Use this URI to identify the default namespace:\n\n         \"http://www.w3.org/1999/xhtml\"\n\n     See the Qualified Names module for information\n     on the use of namespace prefixes in the DTD.\n-->\n<!ENTITY % NS.prefixed \"IGNORE\" >\n<!ENTITY % XHTML.prefix \"\" >\n\n<!-- Reserved for use with the XLink namespace:\n-->\n<!ENTITY % XLINK.xmlns \"\" >\n<!ENTITY % XLINK.xmlns.attrib \"\" >\n\n<!-- For example, if you are using XHTML 1.1 directly, use the FPI\n     in the DOCTYPE declaration, with the xmlns attribute on the\n     document element to identify the default namespace:\n\n       <?xml version=\"1.0\"?>\n       <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"xhtml11.dtd\">\n       <html xmlns=\"http://www.w3.org/1999/xhtml\"\n             xml:lang=\"en\">\n       ...\n       </html>\n\n     Revisions:\n     (none)\n-->\n\n<!-- reserved for future use with document profiles -->\n<!ENTITY % XHTML.profile  \"\" >\n\n<!-- Bidirectional Text features\n     This feature-test entity is used to declare elements\n     and attributes used for bidirectional text support.\n-->\n<!ENTITY % XHTML.bidi  \"INCLUDE\" >\n\n<?doc type=\"doctype\" role=\"title\" { XHTML 1.1 } ?>\n\n<!-- ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -->\n\n<!-- Pre-Framework Redeclaration placeholder  .................... -->\n<!-- this serves as a location to insert markup declarations\n     into the DTD prior to the framework declarations.\n-->\n<!ENTITY % xhtml-prefw-redecl.module \"IGNORE\" >\n<![%xhtml-prefw-redecl.module;[\n%xhtml-prefw-redecl.mod;\n<!-- end of xhtml-prefw-redecl.module -->]]>\n\n<!ENTITY % xhtml-events.module \"INCLUDE\" >\n\n<!-- Inline Style Module  ........................................ -->\n<!ENTITY % xhtml-inlstyle.module \"INCLUDE\" >\n<![%xhtml-inlstyle.module;[\n<!ENTITY % xhtml-inlstyle.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML Inline Style 1.0//EN\"\n            \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-inlstyle-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Inline Style Module  ........................................... -->\n<!-- file: xhtml-inlstyle-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-inlstyle-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ENTITIES XHTML Inline Style 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-inlstyle-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Inline Style\n\n     This module declares the 'style' attribute, used to support inline\n     style markup. This module must be instantiated prior to the XHTML\n     Common Attributes module in order to be included in %Core.attrib;.\n-->\n\n<!ENTITY % style.attrib\n     \"style        CDATA                    #IMPLIED\"\n>\n\n\n<!ENTITY % Core.extra.attrib\n     \"%style.attrib;\"\n>\n\n<!-- end of xhtml-inlstyle-1.mod -->\n]]>\n\n<!-- declare Document Model module instantiated in framework\n-->\n<!ENTITY % xhtml-model.mod\n     PUBLIC \"-//W3C//ENTITIES XHTML 1.1 Document Model 1.0//EN\"\n            \"xhtml11-model-1.mod\" >\n\n<!-- Modular Framework Module (required) ......................... -->\n<!ENTITY % xhtml-framework.module \"INCLUDE\" >\n<![%xhtml-framework.module;[\n<!ENTITY % xhtml-framework.mod\n     PUBLIC \"-//W3C//ENTITIES XHTML Modular Framework 1.0//EN\"\n            \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-framework-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Modular Framework Module  ...................................... -->\n<!-- file: xhtml-framework-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-framework-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ENTITIES XHTML Modular Framework 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-framework-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Modular Framework\n\n     This required module instantiates the modules needed\n     to support the XHTML modularization model, including:\n\n        +  notations\n        +  datatypes\n        +  namespace-qualified names\n        +  common attributes\n        +  document model\n        +  character entities\n\n     The Intrinsic Events module is ignored by default but\n     occurs in this module because it must be instantiated\n     prior to Attributes but after Datatypes.\n-->\n\n<!ENTITY % xhtml-arch.module \"IGNORE\" >\n<![%xhtml-arch.module;[\n<!ENTITY % xhtml-arch.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML Base Architecture 1.0//EN\"\n            \"xhtml-arch-1.mod\" >\n%xhtml-arch.mod;]]>\n\n<!ENTITY % xhtml-notations.module \"INCLUDE\" >\n<![%xhtml-notations.module;[\n<!ENTITY % xhtml-notations.mod\n     PUBLIC \"-//W3C//NOTATIONS XHTML Notations 1.0//EN\"\n            \"xhtml-notations-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Notations Module  .............................................. -->\n<!-- file: xhtml-notations-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-notations-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//NOTATIONS XHTML Notations 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-notations-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Notations\n\n     defines the following notations, many of these imported from\n     other specifications and standards. When an existing FPI is\n     known, it is incorporated here.\n-->\n\n<!-- XML Notations ..................................... -->\n<!-- SGML and XML Notations ............................ -->\n\n<!-- W3C XML 1.0 Recommendation -->\n<!NOTATION w3c-xml\n     PUBLIC \"ISO 8879//NOTATION Extensible Markup Language (XML) 1.0//EN\" >\n\n<!-- XML 1.0 CDATA -->\n<!NOTATION cdata\n     PUBLIC \"-//W3C//NOTATION XML 1.0: CDATA//EN\" >\n\n<!-- SGML Formal Public Identifiers -->\n<!NOTATION fpi\n     PUBLIC \"ISO 8879:1986//NOTATION Formal Public Identifier//EN\" >\n\n<!-- XHTML Notations ................................... -->\n\n<!-- Length defined for cellpadding/cellspacing -->\n\n<!-- nn for pixels or nn% for percentage length -->\n<!NOTATION length\n    PUBLIC \"-//W3C//NOTATION XHTML Datatype: Length//EN\" >\n\n<!-- space-separated list of link types -->\n<!NOTATION linkTypes\n    PUBLIC \"-//W3C//NOTATION XHTML Datatype: LinkTypes//EN\" >\n\n<!-- single or comma-separated list of media descriptors -->\n<!NOTATION mediaDesc\n    PUBLIC \"-//W3C//NOTATION XHTML Datatype: MediaDesc//EN\" >\n\n<!-- pixel, percentage, or relative -->\n<!NOTATION multiLength\n    PUBLIC \"-//W3C//NOTATION XHTML Datatype: MultiLength//EN\" >\n\n<!-- one or more digits (NUMBER) -->\n<!NOTATION number\n    PUBLIC \"-//W3C//NOTATION XHTML Datatype: Number//EN\" >\n\n<!-- integer representing length in pixels -->\n<!NOTATION pixels\n    PUBLIC \"-//W3C//NOTATION XHTML Datatype: Pixels//EN\" >\n\n<!-- script expression -->\n<!NOTATION script\n    PUBLIC \"-//W3C//NOTATION XHTML Datatype: Script//EN\" >\n\n<!-- textual content -->\n<!NOTATION text\n    PUBLIC \"-//W3C//NOTATION XHTML Datatype: Text//EN\" >\n\n<!-- Imported Notations ................................ -->\n\n<!-- a single character from [ISO10646] -->\n<!NOTATION character\n    PUBLIC \"-//W3C//NOTATION XHTML Datatype: Character//EN\" >\n\n<!-- a character encoding, as per [RFC2045] -->\n<!NOTATION charset\n    PUBLIC \"-//W3C//NOTATION XHTML Datatype: Charset//EN\" >\n\n<!-- a space separated list of character encodings, as per [RFC2045] -->\n<!NOTATION charsets\n    PUBLIC \"-//W3C//NOTATION XHTML Datatype: Charsets//EN\" >\n\n<!-- media type, as per [RFC2045] -->\n<!NOTATION contentType\n    PUBLIC \"-//W3C//NOTATION XHTML Datatype: ContentType//EN\" >\n\n<!-- comma-separated list of media types, as per [RFC2045] -->\n<!NOTATION contentTypes\n    PUBLIC \"-//W3C//NOTATION XHTML Datatype: ContentTypes//EN\" >\n\n<!-- date and time information. ISO date format -->\n<!NOTATION datetime\n    PUBLIC \"-//W3C//NOTATION XHTML Datatype: Datetime//EN\" >\n\n<!-- a language code, as per [RFC3066] -->\n<!NOTATION languageCode\n    PUBLIC \"-//W3C//NOTATION XHTML Datatype: LanguageCode//EN\" >\n\n<!-- a Uniform Resource Identifier, see [URI] -->\n<!NOTATION uri\n    PUBLIC \"-//W3C//NOTATION XHTML Datatype: URI//EN\" >\n\n<!-- a space-separated list of Uniform Resource Identifiers, see [URI] -->\n<!NOTATION uris\n    PUBLIC \"-//W3C//NOTATION XHTML Datatype: URIs//EN\" >\n\n<!-- end of xhtml-notations-1.mod -->\n]]>\n\n<!ENTITY % xhtml-datatypes.module \"INCLUDE\" >\n<![%xhtml-datatypes.module;[\n<!ENTITY % xhtml-datatypes.mod\n     PUBLIC \"-//W3C//ENTITIES XHTML Datatypes 1.0//EN\"\n            \"xhtml-datatypes-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Datatypes Module  .............................................. -->\n<!-- file: xhtml-datatypes-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-datatypes-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ENTITIES XHTML Datatypes 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-datatypes-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Datatypes\n\n     defines containers for the following datatypes, many of\n     these imported from other specifications and standards.\n-->\n\n<!-- Length defined for cellpadding/cellspacing -->\n\n<!-- nn for pixels or nn% for percentage length -->\n<!ENTITY % Length.datatype \"CDATA\" >\n\n<!-- space-separated list of link types -->\n<!ENTITY % LinkTypes.datatype \"NMTOKENS\" >\n\n<!-- single or comma-separated list of media descriptors -->\n<!ENTITY % MediaDesc.datatype \"CDATA\" >\n\n<!-- pixel, percentage, or relative -->\n<!ENTITY % MultiLength.datatype \"CDATA\" >\n\n<!-- one or more digits (NUMBER) -->\n<!ENTITY % Number.datatype \"CDATA\" >\n\n<!-- integer representing length in pixels -->\n<!ENTITY % Pixels.datatype \"CDATA\" >\n\n<!-- script expression -->\n<!ENTITY % Script.datatype \"CDATA\" >\n\n<!-- textual content -->\n<!ENTITY % Text.datatype \"CDATA\" >\n\n<!-- Imported Datatypes ................................ -->\n\n<!-- a single character from [ISO10646] -->\n<!ENTITY % Character.datatype \"CDATA\" >\n\n<!-- a character encoding, as per [RFC2045] -->\n<!ENTITY % Charset.datatype \"CDATA\" >\n\n<!-- a space separated list of character encodings, as per [RFC2045] -->\n<!ENTITY % Charsets.datatype \"CDATA\" >\n\n<!-- media type, as per [RFC2045] -->\n<!ENTITY % ContentType.datatype \"CDATA\" >\n\n<!-- comma-separated list of media types, as per [RFC2045] -->\n<!ENTITY % ContentTypes.datatype \"CDATA\" >\n\n<!-- date and time information. ISO date format -->\n<!ENTITY % Datetime.datatype \"CDATA\" >\n\n<!-- formal public identifier, as per [ISO8879] -->\n<!ENTITY % FPI.datatype \"CDATA\" >\n\n<!-- a language code, as per [RFC3066] -->\n<!ENTITY % LanguageCode.datatype \"NMTOKEN\" >\n\n<!-- a Uniform Resource Identifier, see [URI] -->\n<!ENTITY % URI.datatype \"CDATA\" >\n\n<!-- a space-separated list of Uniform Resource Identifiers, see [URI] -->\n<!ENTITY % URIs.datatype \"CDATA\" >\n\n<!-- end of xhtml-datatypes-1.mod -->\n]]>\n\n<!-- placeholder for XLink support module -->\n<!ENTITY % xhtml-xlink.mod \"\" >\n\n\n<!ENTITY % xhtml-qname.module \"INCLUDE\" >\n<![%xhtml-qname.module;[\n<!ENTITY % xhtml-qname.mod\n     PUBLIC \"-//W3C//ENTITIES XHTML Qualified Names 1.0//EN\"\n            \"xhtml-qname-1.mod\" >\n<!-- ....................................................................... -->\n<!-- XHTML Qname Module  ................................................... -->\n<!-- file: xhtml-qname-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-qname-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ENTITIES XHTML Qualified Names 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-qname-1.mod\"\n\n     Revisions:\n#2000-10-22: added qname declarations for ruby elements\n     ....................................................................... -->\n\n<!-- XHTML Qname (Qualified Name) Module\n\n     This module is contained in two parts, labeled Section 'A' and 'B':\n\n       Section A declares parameter entities to support namespace-\n       qualified names, namespace declarations, and name prefixing\n       for XHTML and extensions.\n\n       Section B declares parameter entities used to provide\n       namespace-qualified names for all XHTML element types:\n\n         %applet.qname;   the xmlns-qualified name for <applet>\n         %base.qname;     the xmlns-qualified name for <base>\n         ...\n\n     XHTML extensions would create a module similar to this one.\n     Included in the XHTML distribution is a template module\n     ('template-qname-1.mod') suitable for this purpose.\n-->\n\n<!-- Section A: XHTML XML Namespace Framework :::::::::::::::::::: -->\n\n<!-- 1. Declare a %XHTML.prefixed; conditional section keyword, used\n        to activate namespace prefixing. The default value should\n        inherit '%NS.prefixed;' from the DTD driver, so that unless\n        overridden, the default behaviour follows the overall DTD\n        prefixing scheme.\n-->\n<!ENTITY % NS.prefixed \"IGNORE\" >\n<!ENTITY % XHTML.prefixed \"%NS.prefixed;\" >\n\n<!-- 2. Declare a parameter entity (eg., %XHTML.xmlns;) containing\n        the URI reference used to identify the XHTML namespace:\n-->\n<!ENTITY % XHTML.xmlns  \"http://www.w3.org/1999/xhtml\" >\n\n<!-- 3. Declare parameter entities (eg., %XHTML.prefix;) containing\n        the default namespace prefix string(s) to use when prefixing\n        is enabled. This may be overridden in the DTD driver or the\n        internal subset of an document instance. If no default prefix\n        is desired, this may be declared as an empty string.\n\n     NOTE: As specified in [XMLNAMES], the namespace prefix serves\n     as a proxy for the URI reference, and is not in itself significant.\n-->\n<!ENTITY % XHTML.prefix  \"\" >\n\n<!-- 4. Declare parameter entities (eg., %XHTML.pfx;) containing the\n        colonized prefix(es) (eg., '%XHTML.prefix;:') used when\n        prefixing is active, an empty string when it is not.\n-->\n<![%XHTML.prefixed;[\n<!ENTITY % XHTML.pfx  \"%XHTML.prefix;:\" >\n]]>\n<!ENTITY % XHTML.pfx  \"\" >\n\n<!-- declare qualified name extensions here ............ -->\n<!ENTITY % xhtml-qname-extra.mod \"\" >\n\n\n<!-- 5. The parameter entity %XHTML.xmlns.extra.attrib; may be\n        redeclared to contain any non-XHTML namespace declaration\n        attributes for namespaces embedded in XHTML. The default\n        is an empty string.  XLink should be included here if used\n        in the DTD.\n-->\n<!ENTITY % XHTML.xmlns.extra.attrib \"\" >\n\n<!-- The remainder of Section A is only followed in XHTML, not extensions. -->\n\n<!-- Declare a parameter entity %NS.decl.attrib; containing\n     all XML Namespace declarations used in the DTD, plus the\n     xmlns declaration for XHTML, its form dependent on whether\n     prefixing is active.\n-->\n<![%XHTML.prefixed;[\n<!ENTITY % NS.decl.attrib\n     \"xmlns:%XHTML.prefix;  %URI.datatype;   #FIXED '%XHTML.xmlns;'\n      %XHTML.xmlns.extra.attrib;\"\n>\n]]>\n<!ENTITY % NS.decl.attrib\n     \"%XHTML.xmlns.extra.attrib;\"\n>\n\n<!-- This is a placeholder for future XLink support.\n-->\n<!ENTITY % XLINK.xmlns.attrib \"\" >\n\n<!-- Declare a parameter entity %NS.decl.attrib; containing all\n     XML namespace declaration attributes used by XHTML, including\n     a default xmlns attribute when prefixing is inactive.\n-->\n<![%XHTML.prefixed;[\n<!ENTITY % XHTML.xmlns.attrib\n     \"%NS.decl.attrib;\n      %XLINK.xmlns.attrib;\"\n>\n]]>\n<!ENTITY % XHTML.xmlns.attrib\n     \"xmlns        %URI.datatype;           #FIXED '%XHTML.xmlns;'\n      %XLINK.xmlns.attrib;\"\n>\n\n<!-- placeholder for qualified name redeclarations -->\n<!ENTITY % xhtml-qname.redecl \"\" >\n\n\n<!-- Section B: XHTML Qualified Names ::::::::::::::::::::::::::::: -->\n\n<!-- 6. This section declares parameter entities used to provide\n        namespace-qualified names for all XHTML element types.\n-->\n\n<!-- module:  xhtml-applet-1.mod -->\n<!ENTITY % applet.qname  \"%XHTML.pfx;applet\" >\n\n<!-- module:  xhtml-base-1.mod -->\n<!ENTITY % base.qname    \"%XHTML.pfx;base\" >\n\n<!-- module:  xhtml-bdo-1.mod -->\n<!ENTITY % bdo.qname     \"%XHTML.pfx;bdo\" >\n\n<!-- module:  xhtml-blkphras-1.mod -->\n<!ENTITY % address.qname \"%XHTML.pfx;address\" >\n<!ENTITY % blockquote.qname  \"%XHTML.pfx;blockquote\" >\n<!ENTITY % pre.qname     \"%XHTML.pfx;pre\" >\n<!ENTITY % h1.qname      \"%XHTML.pfx;h1\" >\n<!ENTITY % h2.qname      \"%XHTML.pfx;h2\" >\n<!ENTITY % h3.qname      \"%XHTML.pfx;h3\" >\n<!ENTITY % h4.qname      \"%XHTML.pfx;h4\" >\n<!ENTITY % h5.qname      \"%XHTML.pfx;h5\" >\n<!ENTITY % h6.qname      \"%XHTML.pfx;h6\" >\n\n<!-- module:  xhtml-blkpres-1.mod -->\n<!ENTITY % hr.qname      \"%XHTML.pfx;hr\" >\n\n<!-- module:  xhtml-blkstruct-1.mod -->\n<!ENTITY % div.qname     \"%XHTML.pfx;div\" >\n<!ENTITY % p.qname       \"%XHTML.pfx;p\" >\n\n<!-- module:  xhtml-edit-1.mod -->\n<!ENTITY % ins.qname     \"%XHTML.pfx;ins\" >\n<!ENTITY % del.qname     \"%XHTML.pfx;del\" >\n\n<!-- module:  xhtml-form-1.mod -->\n<!ENTITY % form.qname    \"%XHTML.pfx;form\" >\n<!ENTITY % label.qname   \"%XHTML.pfx;label\" >\n<!ENTITY % input.qname   \"%XHTML.pfx;input\" >\n<!ENTITY % select.qname  \"%XHTML.pfx;select\" >\n<!ENTITY % optgroup.qname  \"%XHTML.pfx;optgroup\" >\n<!ENTITY % option.qname  \"%XHTML.pfx;option\" >\n<!ENTITY % textarea.qname  \"%XHTML.pfx;textarea\" >\n<!ENTITY % fieldset.qname  \"%XHTML.pfx;fieldset\" >\n<!ENTITY % legend.qname  \"%XHTML.pfx;legend\" >\n<!ENTITY % button.qname  \"%XHTML.pfx;button\" >\n\n<!-- module:  xhtml-hypertext-1.mod -->\n<!ENTITY % a.qname       \"%XHTML.pfx;a\" >\n\n<!-- module:  xhtml-image-1.mod -->\n<!ENTITY % img.qname     \"%XHTML.pfx;img\" >\n\n<!-- module:  xhtml-inlphras-1.mod -->\n<!ENTITY % abbr.qname    \"%XHTML.pfx;abbr\" >\n<!ENTITY % acronym.qname \"%XHTML.pfx;acronym\" >\n<!ENTITY % cite.qname    \"%XHTML.pfx;cite\" >\n<!ENTITY % code.qname    \"%XHTML.pfx;code\" >\n<!ENTITY % dfn.qname     \"%XHTML.pfx;dfn\" >\n<!ENTITY % em.qname      \"%XHTML.pfx;em\" >\n<!ENTITY % kbd.qname     \"%XHTML.pfx;kbd\" >\n<!ENTITY % q.qname       \"%XHTML.pfx;q\" >\n<!ENTITY % samp.qname    \"%XHTML.pfx;samp\" >\n<!ENTITY % strong.qname  \"%XHTML.pfx;strong\" >\n<!ENTITY % var.qname     \"%XHTML.pfx;var\" >\n\n<!-- module:  xhtml-inlpres-1.mod -->\n<!ENTITY % b.qname       \"%XHTML.pfx;b\" >\n<!ENTITY % big.qname     \"%XHTML.pfx;big\" >\n<!ENTITY % i.qname       \"%XHTML.pfx;i\" >\n<!ENTITY % small.qname   \"%XHTML.pfx;small\" >\n<!ENTITY % sub.qname     \"%XHTML.pfx;sub\" >\n<!ENTITY % sup.qname     \"%XHTML.pfx;sup\" >\n<!ENTITY % tt.qname      \"%XHTML.pfx;tt\" >\n\n<!-- module:  xhtml-inlstruct-1.mod -->\n<!ENTITY % br.qname      \"%XHTML.pfx;br\" >\n<!ENTITY % span.qname    \"%XHTML.pfx;span\" >\n\n<!-- module:  xhtml-ismap-1.mod (also csismap, ssismap) -->\n<!ENTITY % map.qname     \"%XHTML.pfx;map\" >\n<!ENTITY % area.qname    \"%XHTML.pfx;area\" >\n\n<!-- module:  xhtml-link-1.mod -->\n<!ENTITY % link.qname    \"%XHTML.pfx;link\" >\n\n<!-- module:  xhtml-list-1.mod -->\n<!ENTITY % dl.qname      \"%XHTML.pfx;dl\" >\n<!ENTITY % dt.qname      \"%XHTML.pfx;dt\" >\n<!ENTITY % dd.qname      \"%XHTML.pfx;dd\" >\n<!ENTITY % ol.qname      \"%XHTML.pfx;ol\" >\n<!ENTITY % ul.qname      \"%XHTML.pfx;ul\" >\n<!ENTITY % li.qname      \"%XHTML.pfx;li\" >\n\n<!-- module:  xhtml-meta-1.mod -->\n<!ENTITY % meta.qname    \"%XHTML.pfx;meta\" >\n\n<!-- module:  xhtml-param-1.mod -->\n<!ENTITY % param.qname   \"%XHTML.pfx;param\" >\n\n<!-- module:  xhtml-object-1.mod -->\n<!ENTITY % object.qname  \"%XHTML.pfx;object\" >\n\n<!-- module:  xhtml-script-1.mod -->\n<!ENTITY % script.qname  \"%XHTML.pfx;script\" >\n<!ENTITY % noscript.qname  \"%XHTML.pfx;noscript\" >\n\n<!-- module:  xhtml-struct-1.mod -->\n<!ENTITY % html.qname    \"%XHTML.pfx;html\" >\n<!ENTITY % head.qname    \"%XHTML.pfx;head\" >\n<!ENTITY % title.qname   \"%XHTML.pfx;title\" >\n<!ENTITY % body.qname    \"%XHTML.pfx;body\" >\n\n<!-- module:  xhtml-style-1.mod -->\n<!ENTITY % style.qname   \"%XHTML.pfx;style\" >\n\n<!-- module:  xhtml-table-1.mod -->\n<!ENTITY % table.qname   \"%XHTML.pfx;table\" >\n<!ENTITY % caption.qname \"%XHTML.pfx;caption\" >\n<!ENTITY % thead.qname   \"%XHTML.pfx;thead\" >\n<!ENTITY % tfoot.qname   \"%XHTML.pfx;tfoot\" >\n<!ENTITY % tbody.qname   \"%XHTML.pfx;tbody\" >\n<!ENTITY % colgroup.qname  \"%XHTML.pfx;colgroup\" >\n<!ENTITY % col.qname     \"%XHTML.pfx;col\" >\n<!ENTITY % tr.qname      \"%XHTML.pfx;tr\" >\n<!ENTITY % th.qname      \"%XHTML.pfx;th\" >\n<!ENTITY % td.qname      \"%XHTML.pfx;td\" >\n\n<!-- module:  xhtml-ruby-1.mod -->\n\n<!ENTITY % ruby.qname    \"%XHTML.pfx;ruby\" >\n<!ENTITY % rbc.qname     \"%XHTML.pfx;rbc\" >\n<!ENTITY % rtc.qname     \"%XHTML.pfx;rtc\" >\n<!ENTITY % rb.qname      \"%XHTML.pfx;rb\" >\n<!ENTITY % rt.qname      \"%XHTML.pfx;rt\" >\n<!ENTITY % rp.qname      \"%XHTML.pfx;rp\" >\n\n<!-- Provisional XHTML 2.0 Qualified Names  ...................... -->\n\n<!-- module:  xhtml-image-2.mod -->\n<!ENTITY % alt.qname     \"%XHTML.pfx;alt\" >\n\n<!-- end of xhtml-qname-1.mod -->\n]]>\n\n<!ENTITY % xhtml-events.module \"IGNORE\" >\n<![%xhtml-events.module;[\n<!ENTITY % xhtml-events.mod\n     PUBLIC \"-//W3C//ENTITIES XHTML Intrinsic Events 1.0//EN\"\n            \"xhtml-events-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Intrinsic Events Module  ....................................... -->\n<!-- file: xhtml-events-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-events-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ENTITIES XHTML Intrinsic Events 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-events-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Intrinsic Event Attributes\n\n     These are the event attributes defined in HTML 4.0,\n     Section 18.2.3 \"Intrinsic Events\". This module must be\n     instantiated prior to the Attributes Module but after\n     the Datatype Module in the Modular Framework module.\n\n    \"Note: Authors of HTML documents are advised that changes\n     are likely to occur in the realm of intrinsic events\n     (e.g., how scripts are bound to events). Research in\n     this realm is carried on by members of the W3C Document\n     Object Model Working Group (see the W3C Web site at\n     http://www.w3.org/ for more information).\"\n-->\n<!-- NOTE: Because the ATTLIST declarations in this module occur\n     before their respective ELEMENT declarations in other\n     modules, there may be a dependency on this module that\n     should be considered if any of the parameter entities used\n     for element type names (eg., %a.qname;) are redeclared.\n-->\n\n<!ENTITY % Events.attrib\n     \"onclick      %Script.datatype;        #IMPLIED\n      ondblclick   %Script.datatype;        #IMPLIED\n      onmousedown  %Script.datatype;        #IMPLIED\n      onmouseup    %Script.datatype;        #IMPLIED\n      onmouseover  %Script.datatype;        #IMPLIED\n      onmousemove  %Script.datatype;        #IMPLIED\n      onmouseout   %Script.datatype;        #IMPLIED\n      onkeypress   %Script.datatype;        #IMPLIED\n      onkeydown    %Script.datatype;        #IMPLIED\n      onkeyup      %Script.datatype;        #IMPLIED\"\n>\n\n<!-- additional attributes on anchor element\n-->\n<!ATTLIST %a.qname;\n     onfocus      %Script.datatype;         #IMPLIED\n     onblur       %Script.datatype;         #IMPLIED\n>\n\n<!-- additional attributes on form element\n-->\n<!ATTLIST %form.qname;\n      onsubmit     %Script.datatype;        #IMPLIED\n      onreset      %Script.datatype;        #IMPLIED\n>\n\n<!-- additional attributes on label element\n-->\n<!ATTLIST %label.qname;\n      onfocus      %Script.datatype;        #IMPLIED\n      onblur       %Script.datatype;        #IMPLIED\n>\n\n<!-- additional attributes on input element\n-->\n<!ATTLIST %input.qname;\n      onfocus      %Script.datatype;        #IMPLIED\n      onblur       %Script.datatype;        #IMPLIED\n      onselect     %Script.datatype;        #IMPLIED\n      onchange     %Script.datatype;        #IMPLIED\n>\n\n<!-- additional attributes on select element\n-->\n<!ATTLIST %select.qname;\n      onfocus      %Script.datatype;        #IMPLIED\n      onblur       %Script.datatype;        #IMPLIED\n      onchange     %Script.datatype;        #IMPLIED\n>\n\n<!-- additional attributes on textarea element\n-->\n<!ATTLIST %textarea.qname;\n      onfocus      %Script.datatype;        #IMPLIED\n      onblur       %Script.datatype;        #IMPLIED\n      onselect     %Script.datatype;        #IMPLIED\n      onchange     %Script.datatype;        #IMPLIED\n>\n\n<!-- additional attributes on button element\n-->\n<!ATTLIST %button.qname;\n      onfocus      %Script.datatype;        #IMPLIED\n      onblur       %Script.datatype;        #IMPLIED\n>\n\n<!-- additional attributes on body element\n-->\n<!ATTLIST %body.qname;\n      onload       %Script.datatype;        #IMPLIED\n      onunload     %Script.datatype;        #IMPLIED\n>\n\n<!-- additional attributes on area element\n-->\n<!ATTLIST %area.qname;\n      onfocus      %Script.datatype;        #IMPLIED\n      onblur       %Script.datatype;        #IMPLIED\n>\n\n<!-- end of xhtml-events-1.mod -->\n]]>\n\n<!ENTITY % xhtml-attribs.module \"INCLUDE\" >\n<![%xhtml-attribs.module;[\n<!ENTITY % xhtml-attribs.mod\n     PUBLIC \"-//W3C//ENTITIES XHTML Common Attributes 1.0//EN\"\n            \"xhtml-attribs-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Common Attributes Module  ...................................... -->\n<!-- file: xhtml-attribs-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-attribs-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ENTITIES XHTML Common Attributes 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-attribs-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Common Attributes\n\n     This module declares many of the common attributes for the XHTML DTD.\n     %NS.decl.attrib; is declared in the XHTML Qname module.\n-->\n\n<!ENTITY % id.attrib\n     \"id           ID                       #IMPLIED\"\n>\n\n<!ENTITY % class.attrib\n     \"class        NMTOKENS                 #IMPLIED\"\n>\n\n<!ENTITY % title.attrib\n     \"title        %Text.datatype;          #IMPLIED\"\n>\n\n<!ENTITY % Core.extra.attrib \"\" >\n\n<!ENTITY % Core.attrib\n     \"%XHTML.xmlns.attrib;\n      %id.attrib;\n      %class.attrib;\n      %title.attrib;\n      %Core.extra.attrib;\"\n>\n\n<!ENTITY % lang.attrib\n     \"xml:lang     %LanguageCode.datatype;  #IMPLIED\"\n>\n\n<![%XHTML.bidi;[\n<!ENTITY % dir.attrib\n     \"dir          ( ltr | rtl )            #IMPLIED\"\n>\n\n<!ENTITY % I18n.attrib\n     \"%dir.attrib;\n      %lang.attrib;\"\n>\n\n]]>\n<!ENTITY % I18n.attrib\n     \"%lang.attrib;\"\n>\n\n<!ENTITY % Common.extra.attrib \"\" >\n\n<!-- intrinsic event attributes declared previously\n-->\n<!ENTITY % Events.attrib \"\" >\n\n<!ENTITY % Common.attrib\n     \"%Core.attrib;\n      %I18n.attrib;\n      %Events.attrib;\n      %Common.extra.attrib;\"\n>\n\n<!-- end of xhtml-attribs-1.mod -->\n]]>\n\n<!-- placeholder for content model redeclarations -->\n<!ENTITY % xhtml-model.redecl \"\" >\n\n\n<!ENTITY % xhtml-model.module \"INCLUDE\" >\n<![%xhtml-model.module;[\n<!-- instantiate the Document Model module declared in the DTD driver\n-->\n<!-- ....................................................................... -->\n<!-- XHTML 1.1 Document Model Module  ...................................... -->\n<!-- file: xhtml11-model-1.mod\n\n     This is XHTML 1.1, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2000 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml11-model-1.mod,v 1.12 2000/11/18 18:20:25 ahby Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ENTITIES XHTML 1.1 Document Model 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml11/DTD/xhtml11-model-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- XHTML 1.1 Document Model\n\n     This module describes the groupings of elements that make up\n     common content models for XHTML elements.\n\n     XHTML has three basic content models:\n\n         %Inline.mix;  character-level elements\n         %Block.mix;   block-like elements, eg., paragraphs and lists\n         %Flow.mix;    any block or inline elements\n\n     Any parameter entities declared in this module may be used\n     to create element content models, but the above three are\n     considered 'global' (insofar as that term applies here).\n\n     The reserved word '#PCDATA' (indicating a text string) is now\n     included explicitly with each element declaration that is\n     declared as mixed content, as XML requires that this token\n     occur first in a content model specification.\n-->\n<!-- Extending the Model\n\n     While in some cases this module may need to be rewritten to\n     accommodate changes to the document model, minor extensions\n     may be accomplished by redeclaring any of the three *.extra;\n     parameter entities to contain extension element types as follows:\n\n         %Misc.extra;    whose parent may be any block or\n                         inline element.\n\n         %Inline.extra;  whose parent may be any inline element.\n\n         %Block.extra;   whose parent may be any block element.\n\n     If used, these parameter entities must be an OR-separated\n     list beginning with an OR separator (\"|\"), eg., \"| a | b | c\"\n\n     All block and inline *.class parameter entities not part\n     of the *struct.class classes begin with \"| \" to allow for\n     exclusion from mixes.\n-->\n\n<!-- ..............  Optional Elements in head  .................. -->\n\n<!ENTITY % HeadOpts.mix\n     \"( %script.qname; | %style.qname; | %meta.qname;\n      | %link.qname; | %object.qname; )*\"\n>\n\n<!-- .................  Miscellaneous Elements  .................. -->\n\n<!-- ins and del are used to denote editing changes\n-->\n<!ENTITY % Edit.class \"| %ins.qname; | %del.qname;\" >\n\n<!-- script and noscript are used to contain scripts\n     and alternative content\n-->\n<!ENTITY % Script.class \"| %script.qname; | %noscript.qname;\" >\n\n<!ENTITY % Misc.extra \"\" >\n\n<!-- These elements are neither block nor inline, and can\n     essentially be used anywhere in the document body.\n-->\n<!ENTITY % Misc.class\n     \"%Edit.class;\n      %Script.class;\n      %Misc.extra;\"\n>\n\n<!-- ....................  Inline Elements  ...................... -->\n\n<!ENTITY % InlStruct.class \"%br.qname; | %span.qname;\" >\n\n<!ENTITY % InlPhras.class\n     \"| %em.qname; | %strong.qname; | %dfn.qname; | %code.qname;\n      | %samp.qname; | %kbd.qname; | %var.qname; | %cite.qname;\n      | %abbr.qname; | %acronym.qname; | %q.qname;\" >\n\n<!ENTITY % InlPres.class\n     \"| %tt.qname; | %i.qname; | %b.qname; | %big.qname;\n      | %small.qname; | %sub.qname; | %sup.qname;\" >\n\n<!ENTITY % I18n.class \"| %bdo.qname;\" >\n\n<!ENTITY % Anchor.class \"| %a.qname;\" >\n\n<!ENTITY % InlSpecial.class\n     \"| %img.qname; | %map.qname;\n      | %object.qname;\" >\n\n<!ENTITY % InlForm.class\n     \"| %input.qname; | %select.qname; | %textarea.qname;\n      | %label.qname; | %button.qname;\" >\n\n<!ENTITY % Inline.extra \"\" >\n\n<!ENTITY % Ruby.class \"| %ruby.qname;\" >\n\n<!-- %Inline.class; includes all inline elements,\n     used as a component in mixes\n-->\n<!ENTITY % Inline.class\n     \"%InlStruct.class;\n      %InlPhras.class;\n      %InlPres.class;\n      %I18n.class;\n      %Anchor.class;\n      %InlSpecial.class;\n      %InlForm.class;\n      %Ruby.class;\n      %Inline.extra;\"\n>\n\n<!-- %InlNoRuby.class; includes all inline elements\n     except ruby, used as a component in mixes\n-->\n<!ENTITY % InlNoRuby.class\n     \"%InlStruct.class;\n      %InlPhras.class;\n      %InlPres.class;\n      %I18n.class;\n      %Anchor.class;\n      %InlSpecial.class;\n      %InlForm.class;\n      %Inline.extra;\"\n>\n\n<!-- %NoRuby.content; includes all inlines except ruby\n-->\n<!ENTITY % NoRuby.content\n     \"( #PCDATA\n      | %InlNoRuby.class;\n      %Misc.class; )*\"\n>\n\n<!-- %InlNoAnchor.class; includes all non-anchor inlines,\n     used as a component in mixes\n-->\n<!ENTITY % InlNoAnchor.class\n     \"%InlStruct.class;\n      %InlPhras.class;\n      %InlPres.class;\n      %I18n.class;\n      %InlSpecial.class;\n      %InlForm.class;\n      %Ruby.class;\n      %Inline.extra;\"\n>\n\n<!-- %InlNoAnchor.mix; includes all non-anchor inlines\n-->\n<!ENTITY % InlNoAnchor.mix\n     \"%InlNoAnchor.class;\n      %Misc.class;\"\n>\n\n<!-- %Inline.mix; includes all inline elements, including %Misc.class;\n-->\n<!ENTITY % Inline.mix\n     \"%Inline.class;\n      %Misc.class;\"\n>\n\n<!-- .....................  Block Elements  ...................... -->\n\n<!-- In the HTML 4.0 DTD, heading and list elements were included\n     in the %block; parameter entity. The %Heading.class; and\n     %List.class; parameter entities must now be included explicitly\n     on element declarations where desired.\n-->\n\n<!ENTITY % Heading.class\n     \"%h1.qname; | %h2.qname; | %h3.qname;\n      | %h4.qname; | %h5.qname; | %h6.qname;\" >\n\n<!ENTITY % List.class \"%ul.qname; | %ol.qname; | %dl.qname;\" >\n\n<!ENTITY % Table.class \"| %table.qname;\" >\n\n<!ENTITY % Form.class  \"| %form.qname;\" >\n\n<!ENTITY % Fieldset.class  \"| %fieldset.qname;\" >\n\n<!ENTITY % BlkStruct.class \"%p.qname; | %div.qname;\" >\n\n<!ENTITY % BlkPhras.class\n     \"| %pre.qname; | %blockquote.qname; | %address.qname;\" >\n\n<!ENTITY % BlkPres.class \"| %hr.qname;\" >\n\n<!ENTITY % BlkSpecial.class\n     \"%Table.class;\n      %Form.class;\n      %Fieldset.class;\"\n>\n\n<!ENTITY % Block.extra \"\" >\n\n<!-- %Block.class; includes all block elements,\n     used as an component in mixes\n-->\n<!ENTITY % Block.class\n     \"%BlkStruct.class;\n      %BlkPhras.class;\n      %BlkPres.class;\n      %BlkSpecial.class;\n      %Block.extra;\"\n>\n\n<!-- %Block.mix; includes all block elements plus %Misc.class;\n-->\n<!ENTITY % Block.mix\n     \"%Heading.class;\n      | %List.class;\n      | %Block.class;\n      %Misc.class;\"\n>\n\n<!-- ................  All Content Elements  .................. -->\n\n<!-- %Flow.mix; includes all text content, block and inline\n-->\n<!ENTITY % Flow.mix\n     \"%Heading.class;\n      | %List.class;\n      | %Block.class;\n      | %Inline.class;\n      %Misc.class;\"\n>\n\n<!-- end of xhtml11-model-1.mod -->\n]]>\n\n<!ENTITY % xhtml-charent.module \"INCLUDE\" >\n<![%xhtml-charent.module;[\n<!ENTITY % xhtml-charent.mod\n     PUBLIC \"-//W3C//ENTITIES XHTML Character Entities 1.0//EN\"\n            \"xhtml-charent-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Character Entities Module  ......................................... -->\n<!-- file: xhtml-charent-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-charent-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ENTITIES XHTML Character Entities 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-charent-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Character Entities for XHTML\n\n     This module declares the set of character entities for XHTML,\n     including the Latin 1, Symbol and Special character collections.\n-->\n\n<!ENTITY % xhtml-lat1\n    PUBLIC \"-//W3C//ENTITIES Latin 1 for XHTML//EN\"\n           \"xhtml-lat1.ent\" >\n<!-- Portions (C) International Organization for Standardization 1986\n     Permission to copy in any form is granted for use with\n     conforming SGML systems and applications as defined in\n     ISO 8879, provided this notice is included in all copies.\n-->\n<!-- Character entity set. Typical invocation:\n    <!ENTITY % HTMLlat1 PUBLIC\n       \"-//W3C//ENTITIES Latin 1 for XHTML//EN\"\n       \"http://www.w3.org/TR/xhtml1/DTD/xhtml-lat1.ent\">\n    %HTMLlat1;\n-->\n\n<!ENTITY nbsp   \"&#160;\"> <!-- no-break space = non-breaking space,\n                                  U+00A0 ISOnum -->\n<!ENTITY iexcl  \"&#161;\"> <!-- inverted exclamation mark, U+00A1 ISOnum -->\n<!ENTITY cent   \"&#162;\"> <!-- cent sign, U+00A2 ISOnum -->\n<!ENTITY pound  \"&#163;\"> <!-- pound sign, U+00A3 ISOnum -->\n<!ENTITY curren \"&#164;\"> <!-- currency sign, U+00A4 ISOnum -->\n<!ENTITY yen    \"&#165;\"> <!-- yen sign = yuan sign, U+00A5 ISOnum -->\n<!ENTITY brvbar \"&#166;\"> <!-- broken bar = broken vertical bar,\n                                  U+00A6 ISOnum -->\n<!ENTITY sect   \"&#167;\"> <!-- section sign, U+00A7 ISOnum -->\n<!ENTITY uml    \"&#168;\"> <!-- diaeresis = spacing diaeresis,\n                                  U+00A8 ISOdia -->\n<!ENTITY copy   \"&#169;\"> <!-- copyright sign, U+00A9 ISOnum -->\n<!ENTITY ordf   \"&#170;\"> <!-- feminine ordinal indicator, U+00AA ISOnum -->\n<!ENTITY laquo  \"&#171;\"> <!-- left-pointing double angle quotation mark\n                                  = left pointing guillemet, U+00AB ISOnum -->\n<!ENTITY not    \"&#172;\"> <!-- not sign = discretionary hyphen,\n                                  U+00AC ISOnum -->\n<!ENTITY shy    \"&#173;\"> <!-- soft hyphen = discretionary hyphen,\n                                  U+00AD ISOnum -->\n<!ENTITY reg    \"&#174;\"> <!-- registered sign = registered trade mark sign,\n                                  U+00AE ISOnum -->\n<!ENTITY macr   \"&#175;\"> <!-- macron = spacing macron = overline\n                                  = APL overbar, U+00AF ISOdia -->\n<!ENTITY deg    \"&#176;\"> <!-- degree sign, U+00B0 ISOnum -->\n<!ENTITY plusmn \"&#177;\"> <!-- plus-minus sign = plus-or-minus sign,\n                                  U+00B1 ISOnum -->\n<!ENTITY sup2   \"&#178;\"> <!-- superscript two = superscript digit two\n                                  = squared, U+00B2 ISOnum -->\n<!ENTITY sup3   \"&#179;\"> <!-- superscript three = superscript digit three\n                                  = cubed, U+00B3 ISOnum -->\n<!ENTITY acute  \"&#180;\"> <!-- acute accent = spacing acute,\n                                  U+00B4 ISOdia -->\n<!ENTITY micro  \"&#181;\"> <!-- micro sign, U+00B5 ISOnum -->\n<!ENTITY para   \"&#182;\"> <!-- pilcrow sign = paragraph sign,\n                                  U+00B6 ISOnum -->\n<!ENTITY middot \"&#183;\"> <!-- middle dot = Georgian comma\n                                  = Greek middle dot, U+00B7 ISOnum -->\n<!ENTITY cedil  \"&#184;\"> <!-- cedilla = spacing cedilla, U+00B8 ISOdia -->\n<!ENTITY sup1   \"&#185;\"> <!-- superscript one = superscript digit one,\n                                  U+00B9 ISOnum -->\n<!ENTITY ordm   \"&#186;\"> <!-- masculine ordinal indicator,\n                                  U+00BA ISOnum -->\n<!ENTITY raquo  \"&#187;\"> <!-- right-pointing double angle quotation mark\n                                  = right pointing guillemet, U+00BB ISOnum -->\n<!ENTITY frac14 \"&#188;\"> <!-- vulgar fraction one quarter\n                                  = fraction one quarter, U+00BC ISOnum -->\n<!ENTITY frac12 \"&#189;\"> <!-- vulgar fraction one half\n                                  = fraction one half, U+00BD ISOnum -->\n<!ENTITY frac34 \"&#190;\"> <!-- vulgar fraction three quarters\n                                  = fraction three quarters, U+00BE ISOnum -->\n<!ENTITY iquest \"&#191;\"> <!-- inverted question mark\n                                  = turned question mark, U+00BF ISOnum -->\n<!ENTITY Agrave \"&#192;\"> <!-- latin capital letter A with grave\n                                  = latin capital letter A grave,\n                                  U+00C0 ISOlat1 -->\n<!ENTITY Aacute \"&#193;\"> <!-- latin capital letter A with acute,\n                                  U+00C1 ISOlat1 -->\n<!ENTITY Acirc  \"&#194;\"> <!-- latin capital letter A with circumflex,\n                                  U+00C2 ISOlat1 -->\n<!ENTITY Atilde \"&#195;\"> <!-- latin capital letter A with tilde,\n                                  U+00C3 ISOlat1 -->\n<!ENTITY Auml   \"&#196;\"> <!-- latin capital letter A with diaeresis,\n                                  U+00C4 ISOlat1 -->\n<!ENTITY Aring  \"&#197;\"> <!-- latin capital letter A with ring above\n                                  = latin capital letter A ring,\n                                  U+00C5 ISOlat1 -->\n<!ENTITY AElig  \"&#198;\"> <!-- latin capital letter AE\n                                  = latin capital ligature AE,\n                                  U+00C6 ISOlat1 -->\n<!ENTITY Ccedil \"&#199;\"> <!-- latin capital letter C with cedilla,\n                                  U+00C7 ISOlat1 -->\n<!ENTITY Egrave \"&#200;\"> <!-- latin capital letter E with grave,\n                                  U+00C8 ISOlat1 -->\n<!ENTITY Eacute \"&#201;\"> <!-- latin capital letter E with acute,\n                                  U+00C9 ISOlat1 -->\n<!ENTITY Ecirc  \"&#202;\"> <!-- latin capital letter E with circumflex,\n                                  U+00CA ISOlat1 -->\n<!ENTITY Euml   \"&#203;\"> <!-- latin capital letter E with diaeresis,\n                                  U+00CB ISOlat1 -->\n<!ENTITY Igrave \"&#204;\"> <!-- latin capital letter I with grave,\n                                  U+00CC ISOlat1 -->\n<!ENTITY Iacute \"&#205;\"> <!-- latin capital letter I with acute,\n                                  U+00CD ISOlat1 -->\n<!ENTITY Icirc  \"&#206;\"> <!-- latin capital letter I with circumflex,\n                                  U+00CE ISOlat1 -->\n<!ENTITY Iuml   \"&#207;\"> <!-- latin capital letter I with diaeresis,\n                                  U+00CF ISOlat1 -->\n<!ENTITY ETH    \"&#208;\"> <!-- latin capital letter ETH, U+00D0 ISOlat1 -->\n<!ENTITY Ntilde \"&#209;\"> <!-- latin capital letter N with tilde,\n                                  U+00D1 ISOlat1 -->\n<!ENTITY Ograve \"&#210;\"> <!-- latin capital letter O with grave,\n                                  U+00D2 ISOlat1 -->\n<!ENTITY Oacute \"&#211;\"> <!-- latin capital letter O with acute,\n                                  U+00D3 ISOlat1 -->\n<!ENTITY Ocirc  \"&#212;\"> <!-- latin capital letter O with circumflex,\n                                  U+00D4 ISOlat1 -->\n<!ENTITY Otilde \"&#213;\"> <!-- latin capital letter O with tilde,\n                                  U+00D5 ISOlat1 -->\n<!ENTITY Ouml   \"&#214;\"> <!-- latin capital letter O with diaeresis,\n                                  U+00D6 ISOlat1 -->\n<!ENTITY times  \"&#215;\"> <!-- multiplication sign, U+00D7 ISOnum -->\n<!ENTITY Oslash \"&#216;\"> <!-- latin capital letter O with stroke\n                                  = latin capital letter O slash,\n                                  U+00D8 ISOlat1 -->\n<!ENTITY Ugrave \"&#217;\"> <!-- latin capital letter U with grave,\n                                  U+00D9 ISOlat1 -->\n<!ENTITY Uacute \"&#218;\"> <!-- latin capital letter U with acute,\n                                  U+00DA ISOlat1 -->\n<!ENTITY Ucirc  \"&#219;\"> <!-- latin capital letter U with circumflex,\n                                  U+00DB ISOlat1 -->\n<!ENTITY Uuml   \"&#220;\"> <!-- latin capital letter U with diaeresis,\n                                  U+00DC ISOlat1 -->\n<!ENTITY Yacute \"&#221;\"> <!-- latin capital letter Y with acute,\n                                  U+00DD ISOlat1 -->\n<!ENTITY THORN  \"&#222;\"> <!-- latin capital letter THORN,\n                                  U+00DE ISOlat1 -->\n<!ENTITY szlig  \"&#223;\"> <!-- latin small letter sharp s = ess-zed,\n                                  U+00DF ISOlat1 -->\n<!ENTITY agrave \"&#224;\"> <!-- latin small letter a with grave\n                                  = latin small letter a grave,\n                                  U+00E0 ISOlat1 -->\n<!ENTITY aacute \"&#225;\"> <!-- latin small letter a with acute,\n                                  U+00E1 ISOlat1 -->\n<!ENTITY acirc  \"&#226;\"> <!-- latin small letter a with circumflex,\n                                  U+00E2 ISOlat1 -->\n<!ENTITY atilde \"&#227;\"> <!-- latin small letter a with tilde,\n                                  U+00E3 ISOlat1 -->\n<!ENTITY auml   \"&#228;\"> <!-- latin small letter a with diaeresis,\n                                  U+00E4 ISOlat1 -->\n<!ENTITY aring  \"&#229;\"> <!-- latin small letter a with ring above\n                                  = latin small letter a ring,\n                                  U+00E5 ISOlat1 -->\n<!ENTITY aelig  \"&#230;\"> <!-- latin small letter ae\n                                  = latin small ligature ae, U+00E6 ISOlat1 -->\n<!ENTITY ccedil \"&#231;\"> <!-- latin small letter c with cedilla,\n                                  U+00E7 ISOlat1 -->\n<!ENTITY egrave \"&#232;\"> <!-- latin small letter e with grave,\n                                  U+00E8 ISOlat1 -->\n<!ENTITY eacute \"&#233;\"> <!-- latin small letter e with acute,\n                                  U+00E9 ISOlat1 -->\n<!ENTITY ecirc  \"&#234;\"> <!-- latin small letter e with circumflex,\n                                  U+00EA ISOlat1 -->\n<!ENTITY euml   \"&#235;\"> <!-- latin small letter e with diaeresis,\n                                  U+00EB ISOlat1 -->\n<!ENTITY igrave \"&#236;\"> <!-- latin small letter i with grave,\n                                  U+00EC ISOlat1 -->\n<!ENTITY iacute \"&#237;\"> <!-- latin small letter i with acute,\n                                  U+00ED ISOlat1 -->\n<!ENTITY icirc  \"&#238;\"> <!-- latin small letter i with circumflex,\n                                  U+00EE ISOlat1 -->\n<!ENTITY iuml   \"&#239;\"> <!-- latin small letter i with diaeresis,\n                                  U+00EF ISOlat1 -->\n<!ENTITY eth    \"&#240;\"> <!-- latin small letter eth, U+00F0 ISOlat1 -->\n<!ENTITY ntilde \"&#241;\"> <!-- latin small letter n with tilde,\n                                  U+00F1 ISOlat1 -->\n<!ENTITY ograve \"&#242;\"> <!-- latin small letter o with grave,\n                                  U+00F2 ISOlat1 -->\n<!ENTITY oacute \"&#243;\"> <!-- latin small letter o with acute,\n                                  U+00F3 ISOlat1 -->\n<!ENTITY ocirc  \"&#244;\"> <!-- latin small letter o with circumflex,\n                                  U+00F4 ISOlat1 -->\n<!ENTITY otilde \"&#245;\"> <!-- latin small letter o with tilde,\n                                  U+00F5 ISOlat1 -->\n<!ENTITY ouml   \"&#246;\"> <!-- latin small letter o with diaeresis,\n                                  U+00F6 ISOlat1 -->\n<!ENTITY divide \"&#247;\"> <!-- division sign, U+00F7 ISOnum -->\n<!ENTITY oslash \"&#248;\"> <!-- latin small letter o with stroke,\n                                  = latin small letter o slash,\n                                  U+00F8 ISOlat1 -->\n<!ENTITY ugrave \"&#249;\"> <!-- latin small letter u with grave,\n                                  U+00F9 ISOlat1 -->\n<!ENTITY uacute \"&#250;\"> <!-- latin small letter u with acute,\n                                  U+00FA ISOlat1 -->\n<!ENTITY ucirc  \"&#251;\"> <!-- latin small letter u with circumflex,\n                                  U+00FB ISOlat1 -->\n<!ENTITY uuml   \"&#252;\"> <!-- latin small letter u with diaeresis,\n                                  U+00FC ISOlat1 -->\n<!ENTITY yacute \"&#253;\"> <!-- latin small letter y with acute,\n                                  U+00FD ISOlat1 -->\n<!ENTITY thorn  \"&#254;\"> <!-- latin small letter thorn with,\n                                  U+00FE ISOlat1 -->\n<!ENTITY yuml   \"&#255;\"> <!-- latin small letter y with diaeresis,\n                                  U+00FF ISOlat1 -->\n\n\n<!ENTITY % xhtml-symbol\n    PUBLIC \"-//W3C//ENTITIES Symbols for XHTML//EN\"\n           \"xhtml-symbol.ent\" >\n<!-- Mathematical, Greek and Symbolic characters for HTML -->\n\n<!-- Character entity set. Typical invocation:\n     <!ENTITY % HTMLsymbol PUBLIC\n        \"-//W3C//ENTITIES Symbols for XHTML//EN\"\n        \"http://www.w3.org/TR/xhtml1/DTD/xhtml-symbol.ent\">\n     %HTMLsymbol;\n-->\n\n<!-- Portions (C) International Organization for Standardization 1986:\n     Permission to copy in any form is granted for use with\n     conforming SGML systems and applications as defined in\n     ISO 8879, provided this notice is included in all copies.\n-->\n\n<!-- Relevant ISO entity set is given unless names are newly introduced.\n     New names (i.e., not in ISO 8879 list) do not clash with any\n     existing ISO 8879 entity names. ISO 10646 character numbers\n     are given for each character, in hex. values are decimal\n     conversions of the ISO 10646 values and refer to the document\n     character set. Names are Unicode names. \n-->\n\n<!-- Latin Extended-B -->\n<!ENTITY fnof     \"&#402;\"> <!-- latin small f with hook = function\n                                    = florin, U+0192 ISOtech -->\n\n<!-- Greek -->\n<!ENTITY Alpha    \"&#913;\"> <!-- greek capital letter alpha, U+0391 -->\n<!ENTITY Beta     \"&#914;\"> <!-- greek capital letter beta, U+0392 -->\n<!ENTITY Gamma    \"&#915;\"> <!-- greek capital letter gamma,\n                                    U+0393 ISOgrk3 -->\n<!ENTITY Delta    \"&#916;\"> <!-- greek capital letter delta,\n                                    U+0394 ISOgrk3 -->\n<!ENTITY Epsilon  \"&#917;\"> <!-- greek capital letter epsilon, U+0395 -->\n<!ENTITY Zeta     \"&#918;\"> <!-- greek capital letter zeta, U+0396 -->\n<!ENTITY Eta      \"&#919;\"> <!-- greek capital letter eta, U+0397 -->\n<!ENTITY Theta    \"&#920;\"> <!-- greek capital letter theta,\n                                    U+0398 ISOgrk3 -->\n<!ENTITY Iota     \"&#921;\"> <!-- greek capital letter iota, U+0399 -->\n<!ENTITY Kappa    \"&#922;\"> <!-- greek capital letter kappa, U+039A -->\n<!ENTITY Lambda   \"&#923;\"> <!-- greek capital letter lambda,\n                                    U+039B ISOgrk3 -->\n<!ENTITY Mu       \"&#924;\"> <!-- greek capital letter mu, U+039C -->\n<!ENTITY Nu       \"&#925;\"> <!-- greek capital letter nu, U+039D -->\n<!ENTITY Xi       \"&#926;\"> <!-- greek capital letter xi, U+039E ISOgrk3 -->\n<!ENTITY Omicron  \"&#927;\"> <!-- greek capital letter omicron, U+039F -->\n<!ENTITY Pi       \"&#928;\"> <!-- greek capital letter pi, U+03A0 ISOgrk3 -->\n<!ENTITY Rho      \"&#929;\"> <!-- greek capital letter rho, U+03A1 -->\n<!-- there is no Sigmaf, and no U+03A2 character either -->\n<!ENTITY Sigma    \"&#931;\"> <!-- greek capital letter sigma,\n                                    U+03A3 ISOgrk3 -->\n<!ENTITY Tau      \"&#932;\"> <!-- greek capital letter tau, U+03A4 -->\n<!ENTITY Upsilon  \"&#933;\"> <!-- greek capital letter upsilon,\n                                    U+03A5 ISOgrk3 -->\n<!ENTITY Phi      \"&#934;\"> <!-- greek capital letter phi,\n                                    U+03A6 ISOgrk3 -->\n<!ENTITY Chi      \"&#935;\"> <!-- greek capital letter chi, U+03A7 -->\n<!ENTITY Psi      \"&#936;\"> <!-- greek capital letter psi,\n                                    U+03A8 ISOgrk3 -->\n<!ENTITY Omega    \"&#937;\"> <!-- greek capital letter omega,\n                                    U+03A9 ISOgrk3 -->\n\n<!ENTITY alpha    \"&#945;\"> <!-- greek small letter alpha,\n                                    U+03B1 ISOgrk3 -->\n<!ENTITY beta     \"&#946;\"> <!-- greek small letter beta, U+03B2 ISOgrk3 -->\n<!ENTITY gamma    \"&#947;\"> <!-- greek small letter gamma,\n                                    U+03B3 ISOgrk3 -->\n<!ENTITY delta    \"&#948;\"> <!-- greek small letter delta,\n                                    U+03B4 ISOgrk3 -->\n<!ENTITY epsilon  \"&#949;\"> <!-- greek small letter epsilon,\n                                    U+03B5 ISOgrk3 -->\n<!ENTITY zeta     \"&#950;\"> <!-- greek small letter zeta, U+03B6 ISOgrk3 -->\n<!ENTITY eta      \"&#951;\"> <!-- greek small letter eta, U+03B7 ISOgrk3 -->\n<!ENTITY theta    \"&#952;\"> <!-- greek small letter theta,\n                                    U+03B8 ISOgrk3 -->\n<!ENTITY iota     \"&#953;\"> <!-- greek small letter iota, U+03B9 ISOgrk3 -->\n<!ENTITY kappa    \"&#954;\"> <!-- greek small letter kappa,\n                                    U+03BA ISOgrk3 -->\n<!ENTITY lambda   \"&#955;\"> <!-- greek small letter lambda,\n                                    U+03BB ISOgrk3 -->\n<!ENTITY mu       \"&#956;\"> <!-- greek small letter mu, U+03BC ISOgrk3 -->\n<!ENTITY nu       \"&#957;\"> <!-- greek small letter nu, U+03BD ISOgrk3 -->\n<!ENTITY xi       \"&#958;\"> <!-- greek small letter xi, U+03BE ISOgrk3 -->\n<!ENTITY omicron  \"&#959;\"> <!-- greek small letter omicron, U+03BF NEW -->\n<!ENTITY pi       \"&#960;\"> <!-- greek small letter pi, U+03C0 ISOgrk3 -->\n<!ENTITY rho      \"&#961;\"> <!-- greek small letter rho, U+03C1 ISOgrk3 -->\n<!ENTITY sigmaf   \"&#962;\"> <!-- greek small letter final sigma,\n                                    U+03C2 ISOgrk3 -->\n<!ENTITY sigma    \"&#963;\"> <!-- greek small letter sigma,\n                                    U+03C3 ISOgrk3 -->\n<!ENTITY tau      \"&#964;\"> <!-- greek small letter tau, U+03C4 ISOgrk3 -->\n<!ENTITY upsilon  \"&#965;\"> <!-- greek small letter upsilon,\n                                    U+03C5 ISOgrk3 -->\n<!ENTITY phi      \"&#966;\"> <!-- greek small letter phi, U+03C6 ISOgrk3 -->\n<!ENTITY chi      \"&#967;\"> <!-- greek small letter chi, U+03C7 ISOgrk3 -->\n<!ENTITY psi      \"&#968;\"> <!-- greek small letter psi, U+03C8 ISOgrk3 -->\n<!ENTITY omega    \"&#969;\"> <!-- greek small letter omega,\n                                    U+03C9 ISOgrk3 -->\n<!ENTITY thetasym \"&#977;\"> <!-- greek small letter theta symbol,\n                                    U+03D1 NEW -->\n<!ENTITY upsih    \"&#978;\"> <!-- greek upsilon with hook symbol,\n                                    U+03D2 NEW -->\n<!ENTITY piv      \"&#982;\"> <!-- greek pi symbol, U+03D6 ISOgrk3 -->\n\n<!-- General Punctuation -->\n<!ENTITY bull     \"&#8226;\"> <!-- bullet = black small circle,\n                                     U+2022 ISOpub  -->\n<!-- bullet is NOT the same as bullet operator, U+2219 -->\n<!ENTITY hellip   \"&#8230;\"> <!-- horizontal ellipsis = three dot leader,\n                                     U+2026 ISOpub  -->\n<!ENTITY prime    \"&#8242;\"> <!-- prime = minutes = feet, U+2032 ISOtech -->\n<!ENTITY Prime    \"&#8243;\"> <!-- double prime = seconds = inches,\n                                     U+2033 ISOtech -->\n<!ENTITY oline    \"&#8254;\"> <!-- overline = spacing overscore,\n                                     U+203E NEW -->\n<!ENTITY frasl    \"&#8260;\"> <!-- fraction slash, U+2044 NEW -->\n\n<!-- Letterlike Symbols -->\n<!ENTITY weierp   \"&#8472;\"> <!-- script capital P = power set\n                                     = Weierstrass p, U+2118 ISOamso -->\n<!ENTITY image    \"&#8465;\"> <!-- blackletter capital I = imaginary part,\n                                     U+2111 ISOamso -->\n<!ENTITY real     \"&#8476;\"> <!-- blackletter capital R = real part symbol,\n                                     U+211C ISOamso -->\n<!ENTITY trade    \"&#8482;\"> <!-- trade mark sign, U+2122 ISOnum -->\n<!ENTITY alefsym  \"&#8501;\"> <!-- alef symbol = first transfinite cardinal,\n                                     U+2135 NEW -->\n<!-- alef symbol is NOT the same as hebrew letter alef,\n     U+05D0 although the same glyph could be used to depict both characters -->\n\n<!-- Arrows -->\n<!ENTITY larr     \"&#8592;\"> <!-- leftwards arrow, U+2190 ISOnum -->\n<!ENTITY uarr     \"&#8593;\"> <!-- upwards arrow, U+2191 ISOnum-->\n<!ENTITY rarr     \"&#8594;\"> <!-- rightwards arrow, U+2192 ISOnum -->\n<!ENTITY darr     \"&#8595;\"> <!-- downwards arrow, U+2193 ISOnum -->\n<!ENTITY harr     \"&#8596;\"> <!-- left right arrow, U+2194 ISOamsa -->\n<!ENTITY crarr    \"&#8629;\"> <!-- downwards arrow with corner leftwards\n                                     = carriage return, U+21B5 NEW -->\n<!ENTITY lArr     \"&#8656;\"> <!-- leftwards double arrow, U+21D0 ISOtech -->\n<!-- Unicode does not say that lArr is the same as the 'is implied by' arrow\n    but also does not have any other character for that function. So ? lArr can\n    be used for 'is implied by' as ISOtech suggests -->\n<!ENTITY uArr     \"&#8657;\"> <!-- upwards double arrow, U+21D1 ISOamsa -->\n<!ENTITY rArr     \"&#8658;\"> <!-- rightwards double arrow,\n                                     U+21D2 ISOtech -->\n<!-- Unicode does not say this is the 'implies' character but does not have \n     another character with this function so ?\n     rArr can be used for 'implies' as ISOtech suggests -->\n<!ENTITY dArr     \"&#8659;\"> <!-- downwards double arrow, U+21D3 ISOamsa -->\n<!ENTITY hArr     \"&#8660;\"> <!-- left right double arrow,\n                                     U+21D4 ISOamsa -->\n\n<!-- Mathematical Operators -->\n<!ENTITY forall   \"&#8704;\"> <!-- for all, U+2200 ISOtech -->\n<!ENTITY part     \"&#8706;\"> <!-- partial differential, U+2202 ISOtech  -->\n<!ENTITY exist    \"&#8707;\"> <!-- there exists, U+2203 ISOtech -->\n<!ENTITY empty    \"&#8709;\"> <!-- empty set = null set = diameter,\n                                     U+2205 ISOamso -->\n<!ENTITY nabla    \"&#8711;\"> <!-- nabla = backward difference,\n                                     U+2207 ISOtech -->\n<!ENTITY isin     \"&#8712;\"> <!-- element of, U+2208 ISOtech -->\n<!ENTITY notin    \"&#8713;\"> <!-- not an element of, U+2209 ISOtech -->\n<!ENTITY ni       \"&#8715;\"> <!-- contains as member, U+220B ISOtech -->\n<!-- should there be a more memorable name than 'ni'? -->\n<!ENTITY prod     \"&#8719;\"> <!-- n-ary product = product sign,\n                                     U+220F ISOamsb -->\n<!-- prod is NOT the same character as U+03A0 'greek capital letter pi' though\n     the same glyph might be used for both -->\n<!ENTITY sum      \"&#8721;\"> <!-- n-ary sumation, U+2211 ISOamsb -->\n<!-- sum is NOT the same character as U+03A3 'greek capital letter sigma'\n     though the same glyph might be used for both -->\n<!ENTITY minus    \"&#8722;\"> <!-- minus sign, U+2212 ISOtech -->\n<!ENTITY lowast   \"&#8727;\"> <!-- asterisk operator, U+2217 ISOtech -->\n<!ENTITY radic    \"&#8730;\"> <!-- square root = radical sign,\n                                     U+221A ISOtech -->\n<!ENTITY prop     \"&#8733;\"> <!-- proportional to, U+221D ISOtech -->\n<!ENTITY infin    \"&#8734;\"> <!-- infinity, U+221E ISOtech -->\n<!ENTITY ang      \"&#8736;\"> <!-- angle, U+2220 ISOamso -->\n<!ENTITY and      \"&#8743;\"> <!-- logical and = wedge, U+2227 ISOtech -->\n<!ENTITY or       \"&#8744;\"> <!-- logical or = vee, U+2228 ISOtech -->\n<!ENTITY cap      \"&#8745;\"> <!-- intersection = cap, U+2229 ISOtech -->\n<!ENTITY cup      \"&#8746;\"> <!-- union = cup, U+222A ISOtech -->\n<!ENTITY int      \"&#8747;\"> <!-- integral, U+222B ISOtech -->\n<!ENTITY there4   \"&#8756;\"> <!-- therefore, U+2234 ISOtech -->\n<!ENTITY sim      \"&#8764;\"> <!-- tilde operator = varies with = similar to,\n                                     U+223C ISOtech -->\n<!-- tilde operator is NOT the same character as the tilde, U+007E,\n     although the same glyph might be used to represent both  -->\n<!ENTITY cong     \"&#8773;\"> <!-- approximately equal to, U+2245 ISOtech -->\n<!ENTITY asymp    \"&#8776;\"> <!-- almost equal to = asymptotic to,\n                                     U+2248 ISOamsr -->\n<!ENTITY ne       \"&#8800;\"> <!-- not equal to, U+2260 ISOtech -->\n<!ENTITY equiv    \"&#8801;\"> <!-- identical to, U+2261 ISOtech -->\n<!ENTITY le       \"&#8804;\"> <!-- less-than or equal to, U+2264 ISOtech -->\n<!ENTITY ge       \"&#8805;\"> <!-- greater-than or equal to,\n                                     U+2265 ISOtech -->\n<!ENTITY sub      \"&#8834;\"> <!-- subset of, U+2282 ISOtech -->\n<!ENTITY sup      \"&#8835;\"> <!-- superset of, U+2283 ISOtech -->\n<!-- note that nsup, 'not a superset of, U+2283' is not covered by the Symbol \n     font encoding and is not included. Should it be, for symmetry?\n     It is in ISOamsn  --> \n<!ENTITY nsub     \"&#8836;\"> <!-- not a subset of, U+2284 ISOamsn -->\n<!ENTITY sube     \"&#8838;\"> <!-- subset of or equal to, U+2286 ISOtech -->\n<!ENTITY supe     \"&#8839;\"> <!-- superset of or equal to,\n                                     U+2287 ISOtech -->\n<!ENTITY oplus    \"&#8853;\"> <!-- circled plus = direct sum,\n                                     U+2295 ISOamsb -->\n<!ENTITY otimes   \"&#8855;\"> <!-- circled times = vector product,\n                                     U+2297 ISOamsb -->\n<!ENTITY perp     \"&#8869;\"> <!-- up tack = orthogonal to = perpendicular,\n                                     U+22A5 ISOtech -->\n<!ENTITY sdot     \"&#8901;\"> <!-- dot operator, U+22C5 ISOamsb -->\n<!-- dot operator is NOT the same character as U+00B7 middle dot -->\n\n<!-- Miscellaneous Technical -->\n<!ENTITY lceil    \"&#8968;\"> <!-- left ceiling = apl upstile,\n                                     U+2308 ISOamsc  -->\n<!ENTITY rceil    \"&#8969;\"> <!-- right ceiling, U+2309 ISOamsc  -->\n<!ENTITY lfloor   \"&#8970;\"> <!-- left floor = apl downstile,\n                                     U+230A ISOamsc  -->\n<!ENTITY rfloor   \"&#8971;\"> <!-- right floor, U+230B ISOamsc  -->\n<!ENTITY lang     \"&#9001;\"> <!-- left-pointing angle bracket = bra,\n                                     U+2329 ISOtech -->\n<!-- lang is NOT the same character as U+003C 'less than' \n     or U+2039 'single left-pointing angle quotation mark' -->\n<!ENTITY rang     \"&#9002;\"> <!-- right-pointing angle bracket = ket,\n                                     U+232A ISOtech -->\n<!-- rang is NOT the same character as U+003E 'greater than' \n     or U+203A 'single right-pointing angle quotation mark' -->\n\n<!-- Geometric Shapes -->\n<!ENTITY loz      \"&#9674;\"> <!-- lozenge, U+25CA ISOpub -->\n\n<!-- Miscellaneous Symbols -->\n<!ENTITY spades   \"&#9824;\"> <!-- black spade suit, U+2660 ISOpub -->\n<!-- black here seems to mean filled as opposed to hollow -->\n<!ENTITY clubs    \"&#9827;\"> <!-- black club suit = shamrock,\n                                     U+2663 ISOpub -->\n<!ENTITY hearts   \"&#9829;\"> <!-- black heart suit = valentine,\n                                     U+2665 ISOpub -->\n<!ENTITY diams    \"&#9830;\"> <!-- black diamond suit, U+2666 ISOpub -->\n\n\n<!ENTITY % xhtml-special\n    PUBLIC \"-//W3C//ENTITIES Special for XHTML//EN\"\n           \"xhtml-special.ent\" >\n<!-- Special characters for HTML -->\n\n<!-- Character entity set. Typical invocation:\n     <!ENTITY % HTMLspecial PUBLIC\n        \"-//W3C//ENTITIES Special for XHTML//EN\"\n        \"http://www.w3.org/TR/xhtml1/DTD/xhtml-special.ent\">\n     %HTMLspecial;\n-->\n\n<!-- Portions (C) International Organization for Standardization 1986:\n     Permission to copy in any form is granted for use with\n     conforming SGML systems and applications as defined in\n     ISO 8879, provided this notice is included in all copies.\n-->\n\n<!-- Relevant ISO entity set is given unless names are newly introduced.\n     New names (i.e., not in ISO 8879 list) do not clash with any\n     existing ISO 8879 entity names. ISO 10646 character numbers\n     are given for each character, in hex. values are decimal\n     conversions of the ISO 10646 values and refer to the document\n     character set. Names are Unicode names. \n-->\n\n<!-- C0 Controls and Basic Latin -->\n<!ENTITY quot    \"&#34;\"> <!--  quotation mark = APL quote,\n                                    U+0022 ISOnum -->\n<!ENTITY amp     \"&#38;#38;\"> <!--  ampersand, U+0026 ISOnum -->\n<!ENTITY lt      \"&#38;#60;\"> <!--  less-than sign, U+003C ISOnum -->\n<!ENTITY gt      \"&#62;\"> <!--  greater-than sign, U+003E ISOnum -->\n<!ENTITY apos\t \"&#39;\"> <!--  apostrophe mark, U+0027 ISOnum -->\n\n<!-- Latin Extended-A -->\n<!ENTITY OElig   \"&#338;\"> <!--  latin capital ligature OE,\n                                    U+0152 ISOlat2 -->\n<!ENTITY oelig   \"&#339;\"> <!--  latin small ligature oe, U+0153 ISOlat2 -->\n<!-- ligature is a misnomer, this is a separate character in some languages -->\n<!ENTITY Scaron  \"&#352;\"> <!--  latin capital letter S with caron,\n                                    U+0160 ISOlat2 -->\n<!ENTITY scaron  \"&#353;\"> <!--  latin small letter s with caron,\n                                    U+0161 ISOlat2 -->\n<!ENTITY Yuml    \"&#376;\"> <!--  latin capital letter Y with diaeresis,\n                                    U+0178 ISOlat2 -->\n\n<!-- Spacing Modifier Letters -->\n<!ENTITY circ    \"&#710;\"> <!--  modifier letter circumflex accent,\n                                    U+02C6 ISOpub -->\n<!ENTITY tilde   \"&#732;\"> <!--  small tilde, U+02DC ISOdia -->\n\n<!-- General Punctuation -->\n<!ENTITY ensp    \"&#8194;\"> <!-- en space, U+2002 ISOpub -->\n<!ENTITY emsp    \"&#8195;\"> <!-- em space, U+2003 ISOpub -->\n<!ENTITY thinsp  \"&#8201;\"> <!-- thin space, U+2009 ISOpub -->\n<!ENTITY zwnj    \"&#8204;\"> <!-- zero width non-joiner,\n                                    U+200C NEW RFC 2070 -->\n<!ENTITY zwj     \"&#8205;\"> <!-- zero width joiner, U+200D NEW RFC 2070 -->\n<!ENTITY lrm     \"&#8206;\"> <!-- left-to-right mark, U+200E NEW RFC 2070 -->\n<!ENTITY rlm     \"&#8207;\"> <!-- right-to-left mark, U+200F NEW RFC 2070 -->\n<!ENTITY ndash   \"&#8211;\"> <!-- en dash, U+2013 ISOpub -->\n<!ENTITY mdash   \"&#8212;\"> <!-- em dash, U+2014 ISOpub -->\n<!ENTITY lsquo   \"&#8216;\"> <!-- left single quotation mark,\n                                    U+2018 ISOnum -->\n<!ENTITY rsquo   \"&#8217;\"> <!-- right single quotation mark,\n                                    U+2019 ISOnum -->\n<!ENTITY sbquo   \"&#8218;\"> <!-- single low-9 quotation mark, U+201A NEW -->\n<!ENTITY ldquo   \"&#8220;\"> <!-- left double quotation mark,\n                                    U+201C ISOnum -->\n<!ENTITY rdquo   \"&#8221;\"> <!-- right double quotation mark,\n                                    U+201D ISOnum -->\n<!ENTITY bdquo   \"&#8222;\"> <!-- double low-9 quotation mark, U+201E NEW -->\n<!ENTITY dagger  \"&#8224;\"> <!-- dagger, U+2020 ISOpub -->\n<!ENTITY Dagger  \"&#8225;\"> <!-- double dagger, U+2021 ISOpub -->\n<!ENTITY permil  \"&#8240;\"> <!-- per mille sign, U+2030 ISOtech -->\n<!ENTITY lsaquo  \"&#8249;\"> <!-- single left-pointing angle quotation mark,\n                                    U+2039 ISO proposed -->\n<!-- lsaquo is proposed but not yet ISO standardized -->\n<!ENTITY rsaquo  \"&#8250;\"> <!-- single right-pointing angle quotation mark,\n                                    U+203A ISO proposed -->\n<!-- rsaquo is proposed but not yet ISO standardized -->\n<!ENTITY euro   \"&#8364;\"> <!--  euro sign, U+20AC NEW -->\n\n\n<!-- end of xhtml-charent-1.mod -->\n]]>\n\n<!-- end of xhtml-framework-1.mod -->\n]]>\n\n<!-- Post-Framework Redeclaration placeholder  ................... -->\n<!-- this serves as a location to insert markup declarations\n     into the DTD following the framework declarations.\n-->\n<!ENTITY % xhtml-postfw-redecl.module \"IGNORE\" >\n<![%xhtml-postfw-redecl.module;[\n%xhtml-postfw-redecl.mod;\n<!-- end of xhtml-postfw-redecl.module -->]]>\n\n<!-- Text Module (Required)  ..................................... -->\n<!ENTITY % xhtml-text.module \"INCLUDE\" >\n<![%xhtml-text.module;[\n<!ENTITY % xhtml-text.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML Text 1.0//EN\"\n            \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-text-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Text Module  ................................................... -->\n<!-- file: xhtml-text-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-text-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ELEMENTS XHTML Text 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-text-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Textual Content\n\n     The Text module includes declarations for all core\n     text container elements and their attributes.\n-->\n\n<!ENTITY % xhtml-inlstruct.module \"INCLUDE\" >\n<![%xhtml-inlstruct.module;[\n<!ENTITY % xhtml-inlstruct.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML Inline Structural 1.0//EN\"\n            \"xhtml-inlstruct-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Inline Structural Module  ...................................... -->\n<!-- file: xhtml-inlstruct-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-inlstruct-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ELEMENTS XHTML Inline Structural 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-inlstruct-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Inline Structural\n\n        br, span\n\n     This module declares the elements and their attributes\n     used to support inline-level structural markup.\n-->\n\n<!-- br: forced line break ............................. -->\n\n<!ENTITY % br.element  \"INCLUDE\" >\n<![%br.element;[\n\n<!ENTITY % br.content  \"EMPTY\" >\n<!ENTITY % br.qname  \"br\" >\n<!ELEMENT %br.qname;  %br.content; >\n\n<!-- end of br.element -->]]>\n\n<!ENTITY % br.attlist  \"INCLUDE\" >\n<![%br.attlist;[\n<!ATTLIST %br.qname;\n      %Core.attrib;\n>\n<!-- end of br.attlist -->]]>\n\n<!-- span: generic inline container .................... -->\n\n<!ENTITY % span.element  \"INCLUDE\" >\n<![%span.element;[\n<!ENTITY % span.content\n     \"( #PCDATA | %Inline.mix; )*\"\n>\n<!ENTITY % span.qname  \"span\" >\n<!ELEMENT %span.qname;  %span.content; >\n<!-- end of span.element -->]]>\n\n<!ENTITY % span.attlist  \"INCLUDE\" >\n<![%span.attlist;[\n<!ATTLIST %span.qname;\n      %Common.attrib;\n>\n<!-- end of span.attlist -->]]>\n\n<!-- end of xhtml-inlstruct-1.mod -->\n]]>\n\n<!ENTITY % xhtml-inlphras.module \"INCLUDE\" >\n<![%xhtml-inlphras.module;[\n<!ENTITY % xhtml-inlphras.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML Inline Phrasal 1.0//EN\"\n            \"xhtml-inlphras-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Inline Phrasal Module  ......................................... -->\n<!-- file: xhtml-inlphras-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-inlphras-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ELEMENTS XHTML Inline Phrasal 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-inlphras-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Inline Phrasal\n\n        abbr, acronym, cite, code, dfn, em, kbd, q, samp, strong, var\n\n     This module declares the elements and their attributes used to\n     support inline-level phrasal markup.\n-->\n\n<!ENTITY % abbr.element  \"INCLUDE\" >\n<![%abbr.element;[\n<!ENTITY % abbr.content\n     \"( #PCDATA | %Inline.mix; )*\"\n>\n<!ENTITY % abbr.qname  \"abbr\" >\n<!ELEMENT %abbr.qname;  %abbr.content; >\n<!-- end of abbr.element -->]]>\n\n<!ENTITY % abbr.attlist  \"INCLUDE\" >\n<![%abbr.attlist;[\n<!ATTLIST %abbr.qname;\n      %Common.attrib;\n>\n<!-- end of abbr.attlist -->]]>\n\n<!ENTITY % acronym.element  \"INCLUDE\" >\n<![%acronym.element;[\n<!ENTITY % acronym.content\n     \"( #PCDATA | %Inline.mix; )*\"\n>\n<!ENTITY % acronym.qname  \"acronym\" >\n<!ELEMENT %acronym.qname;  %acronym.content; >\n<!-- end of acronym.element -->]]>\n\n<!ENTITY % acronym.attlist  \"INCLUDE\" >\n<![%acronym.attlist;[\n<!ATTLIST %acronym.qname;\n      %Common.attrib;\n>\n<!-- end of acronym.attlist -->]]>\n\n<!ENTITY % cite.element  \"INCLUDE\" >\n<![%cite.element;[\n<!ENTITY % cite.content\n     \"( #PCDATA | %Inline.mix; )*\"\n>\n<!ENTITY % cite.qname  \"cite\" >\n<!ELEMENT %cite.qname;  %cite.content; >\n<!-- end of cite.element -->]]>\n\n<!ENTITY % cite.attlist  \"INCLUDE\" >\n<![%cite.attlist;[\n<!ATTLIST %cite.qname;\n      %Common.attrib;\n>\n<!-- end of cite.attlist -->]]>\n\n<!ENTITY % code.element  \"INCLUDE\" >\n<![%code.element;[\n<!ENTITY % code.content\n     \"( #PCDATA | %Inline.mix; )*\"\n>\n<!ENTITY % code.qname  \"code\" >\n<!ELEMENT %code.qname;  %code.content; >\n<!-- end of code.element -->]]>\n\n<!ENTITY % code.attlist  \"INCLUDE\" >\n<![%code.attlist;[\n<!ATTLIST %code.qname;\n      %Common.attrib;\n>\n<!-- end of code.attlist -->]]>\n\n<!ENTITY % dfn.element  \"INCLUDE\" >\n<![%dfn.element;[\n<!ENTITY % dfn.content\n     \"( #PCDATA | %Inline.mix; )*\"\n>\n<!ENTITY % dfn.qname  \"dfn\" >\n<!ELEMENT %dfn.qname;  %dfn.content; >\n<!-- end of dfn.element -->]]>\n\n<!ENTITY % dfn.attlist  \"INCLUDE\" >\n<![%dfn.attlist;[\n<!ATTLIST %dfn.qname;\n      %Common.attrib;\n>\n<!-- end of dfn.attlist -->]]>\n\n<!ENTITY % em.element  \"INCLUDE\" >\n<![%em.element;[\n<!ENTITY % em.content\n     \"( #PCDATA | %Inline.mix; )*\"\n>\n<!ENTITY % em.qname  \"em\" >\n<!ELEMENT %em.qname;  %em.content; >\n<!-- end of em.element -->]]>\n\n<!ENTITY % em.attlist  \"INCLUDE\" >\n<![%em.attlist;[\n<!ATTLIST %em.qname;\n      %Common.attrib;\n>\n<!-- end of em.attlist -->]]>\n\n<!ENTITY % kbd.element  \"INCLUDE\" >\n<![%kbd.element;[\n<!ENTITY % kbd.content\n     \"( #PCDATA | %Inline.mix; )*\"\n>\n<!ENTITY % kbd.qname  \"kbd\" >\n<!ELEMENT %kbd.qname;  %kbd.content; >\n<!-- end of kbd.element -->]]>\n\n<!ENTITY % kbd.attlist  \"INCLUDE\" >\n<![%kbd.attlist;[\n<!ATTLIST %kbd.qname;\n      %Common.attrib;\n>\n<!-- end of kbd.attlist -->]]>\n\n<!ENTITY % q.element  \"INCLUDE\" >\n<![%q.element;[\n<!ENTITY % q.content\n     \"( #PCDATA | %Inline.mix; )*\"\n>\n<!ENTITY % q.qname  \"q\" >\n<!ELEMENT %q.qname;  %q.content; >\n<!-- end of q.element -->]]>\n\n<!ENTITY % q.attlist  \"INCLUDE\" >\n<![%q.attlist;[\n<!ATTLIST %q.qname;\n      %Common.attrib;\n      cite         %URI.datatype;           #IMPLIED\n>\n<!-- end of q.attlist -->]]>\n\n<!ENTITY % samp.element  \"INCLUDE\" >\n<![%samp.element;[\n<!ENTITY % samp.content\n     \"( #PCDATA | %Inline.mix; )*\"\n>\n<!ENTITY % samp.qname  \"samp\" >\n<!ELEMENT %samp.qname;  %samp.content; >\n<!-- end of samp.element -->]]>\n\n<!ENTITY % samp.attlist  \"INCLUDE\" >\n<![%samp.attlist;[\n<!ATTLIST %samp.qname;\n      %Common.attrib;\n>\n<!-- end of samp.attlist -->]]>\n\n<!ENTITY % strong.element  \"INCLUDE\" >\n<![%strong.element;[\n<!ENTITY % strong.content\n     \"( #PCDATA | %Inline.mix; )*\"\n>\n<!ENTITY % strong.qname  \"strong\" >\n<!ELEMENT %strong.qname;  %strong.content; >\n<!-- end of strong.element -->]]>\n\n<!ENTITY % strong.attlist  \"INCLUDE\" >\n<![%strong.attlist;[\n<!ATTLIST %strong.qname;\n      %Common.attrib;\n>\n<!-- end of strong.attlist -->]]>\n\n<!ENTITY % var.element  \"INCLUDE\" >\n<![%var.element;[\n<!ENTITY % var.content\n     \"( #PCDATA | %Inline.mix; )*\"\n>\n<!ENTITY % var.qname  \"var\" >\n<!ELEMENT %var.qname;  %var.content; >\n<!-- end of var.element -->]]>\n\n<!ENTITY % var.attlist  \"INCLUDE\" >\n<![%var.attlist;[\n<!ATTLIST %var.qname;\n      %Common.attrib;\n>\n<!-- end of var.attlist -->]]>\n\n<!-- end of xhtml-inlphras-1.mod -->\n]]>\n\n<!ENTITY % xhtml-blkstruct.module \"INCLUDE\" >\n<![%xhtml-blkstruct.module;[\n<!ENTITY % xhtml-blkstruct.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML Block Structural 1.0//EN\"\n            \"xhtml-blkstruct-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Block Structural Module  ....................................... -->\n<!-- file: xhtml-blkstruct-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-blkstruct-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ELEMENTS XHTML Block Structural 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-blkstruct-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Block Structural\n\n        div, p\n\n     This module declares the elements and their attributes used to\n     support block-level structural markup.\n-->\n\n<!ENTITY % div.element  \"INCLUDE\" >\n<![%div.element;[\n<!ENTITY % div.content\n     \"( #PCDATA | %Flow.mix; )*\"\n>\n<!ENTITY % div.qname  \"div\" >\n<!ELEMENT %div.qname;  %div.content; >\n<!-- end of div.element -->]]>\n\n<!ENTITY % div.attlist  \"INCLUDE\" >\n<![%div.attlist;[\n<!ATTLIST %div.qname;\n      %Common.attrib;\n>\n<!-- end of div.attlist -->]]>\n\n<!ENTITY % p.element  \"INCLUDE\" >\n<![%p.element;[\n<!ENTITY % p.content\n     \"( #PCDATA | %Inline.mix; )*\" >\n<!ENTITY % p.qname  \"p\" >\n<!ELEMENT %p.qname;  %p.content; >\n<!-- end of p.element -->]]>\n\n<!ENTITY % p.attlist  \"INCLUDE\" >\n<![%p.attlist;[\n<!ATTLIST %p.qname;\n      %Common.attrib;\n>\n<!-- end of p.attlist -->]]>\n\n<!-- end of xhtml-blkstruct-1.mod -->\n]]>\n\n<!ENTITY % xhtml-blkphras.module \"INCLUDE\" >\n<![%xhtml-blkphras.module;[\n<!ENTITY % xhtml-blkphras.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML Block Phrasal 1.0//EN\"\n            \"xhtml-blkphras-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Block Phrasal Module  .......................................... -->\n<!-- file: xhtml-blkphras-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-blkphras-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ELEMENTS XHTML Block Phrasal 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-blkphras-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Block Phrasal\n\n        address, blockquote, pre, h1, h2, h3, h4, h5, h6\n\n     This module declares the elements and their attributes used to\n     support block-level phrasal markup.\n-->\n\n<!ENTITY % address.element  \"INCLUDE\" >\n<![%address.element;[\n<!ENTITY % address.content\n     \"( #PCDATA | %Inline.mix; )*\" >\n<!ENTITY % address.qname  \"address\" >\n<!ELEMENT %address.qname;  %address.content; >\n<!-- end of address.element -->]]>\n\n<!ENTITY % address.attlist  \"INCLUDE\" >\n<![%address.attlist;[\n<!ATTLIST %address.qname;\n      %Common.attrib;\n>\n<!-- end of address.attlist -->]]>\n\n<!ENTITY % blockquote.element  \"INCLUDE\" >\n<![%blockquote.element;[\n<!ENTITY % blockquote.content\n     \"( %Block.mix; )+\"\n>\n<!ENTITY % blockquote.qname  \"blockquote\" >\n<!ELEMENT %blockquote.qname;  %blockquote.content; >\n<!-- end of blockquote.element -->]]>\n\n<!ENTITY % blockquote.attlist  \"INCLUDE\" >\n<![%blockquote.attlist;[\n<!ATTLIST %blockquote.qname;\n      %Common.attrib;\n      cite         %URI.datatype;           #IMPLIED\n>\n<!-- end of blockquote.attlist -->]]>\n\n<!ENTITY % pre.element  \"INCLUDE\" >\n<![%pre.element;[\n<!ENTITY % pre.content\n     \"( #PCDATA\n      | %InlStruct.class;\n      %InlPhras.class;\n      | %tt.qname; | %i.qname; | %b.qname;\n      %I18n.class;\n      %Anchor.class;\n      | %script.qname; | %map.qname;\n      %Inline.extra; )*\"\n>\n<!ENTITY % pre.qname  \"pre\" >\n<!ELEMENT %pre.qname;  %pre.content; >\n<!-- end of pre.element -->]]>\n\n<!ENTITY % pre.attlist  \"INCLUDE\" >\n<![%pre.attlist;[\n<!ATTLIST %pre.qname;\n      %Common.attrib;\n      xml:space    ( preserve )             #FIXED 'preserve'\n>\n<!-- end of pre.attlist -->]]>\n\n<!-- ...................  Heading Elements  ................... -->\n\n<!ENTITY % Heading.content  \"( #PCDATA | %Inline.mix; )*\" >\n\n<!ENTITY % h1.element  \"INCLUDE\" >\n<![%h1.element;[\n<!ENTITY % h1.qname  \"h1\" >\n<!ELEMENT %h1.qname;  %Heading.content; >\n<!-- end of h1.element -->]]>\n\n<!ENTITY % h1.attlist  \"INCLUDE\" >\n<![%h1.attlist;[\n<!ATTLIST %h1.qname;\n      %Common.attrib;\n>\n<!-- end of h1.attlist -->]]>\n\n<!ENTITY % h2.element  \"INCLUDE\" >\n<![%h2.element;[\n<!ENTITY % h2.qname  \"h2\" >\n<!ELEMENT %h2.qname;  %Heading.content; >\n<!-- end of h2.element -->]]>\n\n<!ENTITY % h2.attlist  \"INCLUDE\" >\n<![%h2.attlist;[\n<!ATTLIST %h2.qname;\n      %Common.attrib;\n>\n<!-- end of h2.attlist -->]]>\n\n<!ENTITY % h3.element  \"INCLUDE\" >\n<![%h3.element;[\n<!ENTITY % h3.qname  \"h3\" >\n<!ELEMENT %h3.qname;  %Heading.content; >\n<!-- end of h3.element -->]]>\n\n<!ENTITY % h3.attlist  \"INCLUDE\" >\n<![%h3.attlist;[\n<!ATTLIST %h3.qname;\n      %Common.attrib;\n>\n<!-- end of h3.attlist -->]]>\n\n<!ENTITY % h4.element  \"INCLUDE\" >\n<![%h4.element;[\n<!ENTITY % h4.qname  \"h4\" >\n<!ELEMENT %h4.qname;  %Heading.content; >\n<!-- end of h4.element -->]]>\n\n<!ENTITY % h4.attlist  \"INCLUDE\" >\n<![%h4.attlist;[\n<!ATTLIST %h4.qname;\n      %Common.attrib;\n>\n<!-- end of h4.attlist -->]]>\n\n<!ENTITY % h5.element  \"INCLUDE\" >\n<![%h5.element;[\n<!ENTITY % h5.qname  \"h5\" >\n<!ELEMENT %h5.qname;  %Heading.content; >\n<!-- end of h5.element -->]]>\n\n<!ENTITY % h5.attlist  \"INCLUDE\" >\n<![%h5.attlist;[\n<!ATTLIST %h5.qname;\n      %Common.attrib;\n>\n<!-- end of h5.attlist -->]]>\n\n<!ENTITY % h6.element  \"INCLUDE\" >\n<![%h6.element;[\n<!ENTITY % h6.qname  \"h6\" >\n<!ELEMENT %h6.qname;  %Heading.content; >\n<!-- end of h6.element -->]]>\n\n<!ENTITY % h6.attlist  \"INCLUDE\" >\n<![%h6.attlist;[\n<!ATTLIST %h6.qname;\n      %Common.attrib;\n>\n<!-- end of h6.attlist -->]]>\n\n<!-- end of xhtml-blkphras-1.mod -->\n]]>\n\n<!-- end of xhtml-text-1.mod -->\n]]>\n\n<!-- Hypertext Module (required) ................................. -->\n<!ENTITY % xhtml-hypertext.module \"INCLUDE\" >\n<![%xhtml-hypertext.module;[\n<!ENTITY % xhtml-hypertext.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML Hypertext 1.0//EN\"\n            \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-hypertext-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Hypertext Module  .............................................. -->\n<!-- file: xhtml-hypertext-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-hypertext-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ELEMENTS XHTML Hypertext 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-hypertext-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Hypertext\n\n        a\n\n     This module declares the anchor ('a') element type, which\n     defines the source of a hypertext link. The destination\n     (or link 'target') is identified via its 'id' attribute\n     rather than the 'name' attribute as was used in HTML.\n-->\n\n<!-- ............  Anchor Element  ............ -->\n\n<!ENTITY % a.element  \"INCLUDE\" >\n<![%a.element;[\n<!ENTITY % a.content\n     \"( #PCDATA | %InlNoAnchor.mix; )*\"\n>\n<!ENTITY % a.qname  \"a\" >\n<!ELEMENT %a.qname;  %a.content; >\n<!-- end of a.element -->]]>\n\n<!ENTITY % a.attlist  \"INCLUDE\" >\n<![%a.attlist;[\n<!ATTLIST %a.qname;\n      %Common.attrib;\n      href         %URI.datatype;           #IMPLIED\n      charset      %Charset.datatype;       #IMPLIED\n      type         %ContentType.datatype;   #IMPLIED\n      hreflang     %LanguageCode.datatype;  #IMPLIED\n      rel          %LinkTypes.datatype;     #IMPLIED\n      rev          %LinkTypes.datatype;     #IMPLIED\n      accesskey    %Character.datatype;     #IMPLIED\n      tabindex     %Number.datatype;        #IMPLIED\n>\n<!-- end of a.attlist -->]]>\n\n<!-- end of xhtml-hypertext-1.mod -->\n]]>\n\n<!-- Lists Module (required)  .................................... -->\n<!ENTITY % xhtml-list.module \"INCLUDE\" >\n<![%xhtml-list.module;[\n<!ENTITY % xhtml-list.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML Lists 1.0//EN\"\n            \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-list-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Lists Module  .................................................. -->\n<!-- file: xhtml-list-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-list-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ELEMENTS XHTML Lists 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-list-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Lists\n\n        dl, dt, dd, ol, ul, li\n\n     This module declares the list-oriented element types\n     and their attributes.\n-->\n\n<!ENTITY % dl.qname  \"dl\" >\n<!ENTITY % dt.qname  \"dt\" >\n<!ENTITY % dd.qname  \"dd\" >\n<!ENTITY % ol.qname  \"ol\" >\n<!ENTITY % ul.qname  \"ul\" >\n<!ENTITY % li.qname  \"li\" >\n\n<!-- dl: Definition List ............................... -->\n\n<!ENTITY % dl.element  \"INCLUDE\" >\n<![%dl.element;[\n<!ENTITY % dl.content  \"( %dt.qname; | %dd.qname; )+\" >\n<!ELEMENT %dl.qname;  %dl.content; >\n<!-- end of dl.element -->]]>\n\n<!ENTITY % dl.attlist  \"INCLUDE\" >\n<![%dl.attlist;[\n<!ATTLIST %dl.qname;\n      %Common.attrib;\n>\n<!-- end of dl.attlist -->]]>\n\n<!-- dt: Definition Term ............................... -->\n\n<!ENTITY % dt.element  \"INCLUDE\" >\n<![%dt.element;[\n<!ENTITY % dt.content\n     \"( #PCDATA | %Inline.mix; )*\"\n>\n<!ELEMENT %dt.qname;  %dt.content; >\n<!-- end of dt.element -->]]>\n\n<!ENTITY % dt.attlist  \"INCLUDE\" >\n<![%dt.attlist;[\n<!ATTLIST %dt.qname;\n      %Common.attrib;\n>\n<!-- end of dt.attlist -->]]>\n\n<!-- dd: Definition Description ........................ -->\n\n<!ENTITY % dd.element  \"INCLUDE\" >\n<![%dd.element;[\n<!ENTITY % dd.content\n     \"( #PCDATA | %Flow.mix; )*\"\n>\n<!ELEMENT %dd.qname;  %dd.content; >\n<!-- end of dd.element -->]]>\n\n<!ENTITY % dd.attlist  \"INCLUDE\" >\n<![%dd.attlist;[\n<!ATTLIST %dd.qname;\n      %Common.attrib;\n>\n<!-- end of dd.attlist -->]]>\n\n<!-- ol: Ordered List (numbered styles) ................ -->\n\n<!ENTITY % ol.element  \"INCLUDE\" >\n<![%ol.element;[\n<!ENTITY % ol.content  \"( %li.qname; )+\" >\n<!ELEMENT %ol.qname;  %ol.content; >\n<!-- end of ol.element -->]]>\n\n<!ENTITY % ol.attlist  \"INCLUDE\" >\n<![%ol.attlist;[\n<!ATTLIST %ol.qname;\n      %Common.attrib;\n>\n<!-- end of ol.attlist -->]]>\n\n<!-- ul: Unordered List (bullet styles) ................ -->\n\n<!ENTITY % ul.element  \"INCLUDE\" >\n<![%ul.element;[\n<!ENTITY % ul.content  \"( %li.qname; )+\" >\n<!ELEMENT %ul.qname;  %ul.content; >\n<!-- end of ul.element -->]]>\n\n<!ENTITY % ul.attlist  \"INCLUDE\" >\n<![%ul.attlist;[\n<!ATTLIST %ul.qname;\n      %Common.attrib;\n>\n<!-- end of ul.attlist -->]]>\n\n<!-- li: List Item ..................................... -->\n\n<!ENTITY % li.element  \"INCLUDE\" >\n<![%li.element;[\n<!ENTITY % li.content\n     \"( #PCDATA | %Flow.mix; )*\"\n>\n<!ELEMENT %li.qname;  %li.content; >\n<!-- end of li.element -->]]>\n\n<!ENTITY % li.attlist  \"INCLUDE\" >\n<![%li.attlist;[\n<!ATTLIST %li.qname;\n      %Common.attrib;\n>\n<!-- end of li.attlist -->]]>\n\n<!-- end of xhtml-list-1.mod -->\n]]>\n\n<!-- ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -->\n\n<!-- Edit Module  ................................................ -->\n<!ENTITY % xhtml-edit.module \"INCLUDE\" >\n<![%xhtml-edit.module;[\n<!ENTITY % xhtml-edit.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML Editing Elements 1.0//EN\"\n            \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-edit-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Editing Elements Module  ....................................... -->\n<!-- file: xhtml-edit-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-edit-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ELEMENTS XHTML Editing Markup 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-edit-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Editing Elements\n\n        ins, del\n\n     This module declares element types and attributes used to indicate\n     inserted and deleted content while editing a document.\n-->\n\n<!-- ins: Inserted Text  ............................... -->\n\n<!ENTITY % ins.element  \"INCLUDE\" >\n<![%ins.element;[\n<!ENTITY % ins.content\n     \"( #PCDATA | %Flow.mix; )*\"\n>\n<!ENTITY % ins.qname  \"ins\" >\n<!ELEMENT %ins.qname;  %ins.content; >\n<!-- end of ins.element -->]]>\n\n<!ENTITY % ins.attlist  \"INCLUDE\" >\n<![%ins.attlist;[\n<!ATTLIST %ins.qname;\n      %Common.attrib;\n      cite         %URI.datatype;           #IMPLIED\n      datetime     %Datetime.datatype;      #IMPLIED\n>\n<!-- end of ins.attlist -->]]>\n\n<!-- del: Deleted Text  ................................ -->\n\n<!ENTITY % del.element  \"INCLUDE\" >\n<![%del.element;[\n<!ENTITY % del.content\n     \"( #PCDATA | %Flow.mix; )*\"\n>\n<!ENTITY % del.qname  \"del\" >\n<!ELEMENT %del.qname;  %del.content; >\n<!-- end of del.element -->]]>\n\n<!ENTITY % del.attlist  \"INCLUDE\" >\n<![%del.attlist;[\n<!ATTLIST %del.qname;\n      %Common.attrib;\n      cite         %URI.datatype;           #IMPLIED\n      datetime     %Datetime.datatype;      #IMPLIED\n>\n<!-- end of del.attlist -->]]>\n\n<!-- end of xhtml-edit-1.mod -->\n]]>\n\n<!-- BIDI Override Module  ....................................... -->\n<!ENTITY % xhtml-bdo.module \"%XHTML.bidi;\" >\n<![%xhtml-bdo.module;[\n<!ENTITY % xhtml-bdo.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML BIDI Override Element 1.0//EN\"\n            \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-bdo-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML BDO Element Module ............................................. -->\n<!-- file: xhtml-bdo-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-bdo-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ELEMENTS XHTML BDO Element 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-bdo-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Bidirectional Override (bdo) Element\n\n     This modules declares the element 'bdo', used to override the\n     Unicode bidirectional algorithm for selected fragments of text.\n\n     DEPENDENCIES:\n     Relies on the conditional section keyword %XHTML.bidi; declared\n     as \"INCLUDE\". Bidirectional text support includes both the bdo\n     element and the 'dir' attribute.\n-->\n\n<!ENTITY % bdo.element  \"INCLUDE\" >\n<![%bdo.element;[\n<!ENTITY % bdo.content\n     \"( #PCDATA | %Inline.mix; )*\"\n>\n<!ENTITY % bdo.qname  \"bdo\" >\n<!ELEMENT %bdo.qname;  %bdo.content; >\n<!-- end of bdo.element -->]]>\n\n<!ENTITY % bdo.attlist  \"INCLUDE\" >\n<![%bdo.attlist;[\n<!ATTLIST %bdo.qname;\n      %Core.attrib;\n      xml:lang     %LanguageCode.datatype;  #IMPLIED\n      dir          ( ltr | rtl )            #REQUIRED\n>\n]]>\n\n<!-- end of xhtml-bdo-1.mod -->\n]]>\n\n<!-- Ruby Module  ................................................ -->\n<!ENTITY % Ruby.common.attlists \"INCLUDE\" >\n<!ENTITY % Ruby.common.attrib \"%Common.attrib;\" >\n<!ENTITY % xhtml-ruby.module \"INCLUDE\" >\n<![%xhtml-ruby.module;[\n<!ENTITY % xhtml-ruby.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML Ruby 1.0//EN\"\n            \"http://www.w3.org/TR/ruby/xhtml-ruby-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Ruby Module .................................................... -->\n<!-- file: xhtml-ruby-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1999-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-ruby-1.mod,v 4.0 2001/04/03 23:14:33 altheim Exp $\n\n     This module is based on the W3C Ruby Annotation Specification:\n\n        http://www.w3.org/TR/ruby\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ELEMENTS XHTML Ruby 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/ruby/xhtml-ruby-1.mod\"\n\n     ...................................................................... -->\n\n<!-- Ruby Elements\n\n        ruby, rbc, rtc, rb, rt, rp\n\n     This module declares the elements and their attributes used to\n     support ruby annotation markup.\n-->\n\n<!-- declare qualified element type names:\n-->\n<!ENTITY % ruby.qname  \"ruby\" >\n<!ENTITY % rbc.qname  \"rbc\" >\n<!ENTITY % rtc.qname  \"rtc\" >\n<!ENTITY % rb.qname  \"rb\" >\n<!ENTITY % rt.qname  \"rt\" >\n<!ENTITY % rp.qname  \"rp\" >\n\n<!-- rp fallback is included by default.\n-->\n<!ENTITY % Ruby.fallback \"INCLUDE\" >\n<!ENTITY % Ruby.fallback.mandatory \"IGNORE\" >\n\n<!-- Complex ruby is included by default; it may be \n     overridden by other modules to ignore it.\n-->\n<!ENTITY % Ruby.complex \"INCLUDE\" >\n\n<!-- Fragments for the content model of the ruby element -->\n<![%Ruby.fallback;[\n<![%Ruby.fallback.mandatory;[\n<!ENTITY % Ruby.content.simple \n     \"( %rb.qname;, %rp.qname;, %rt.qname;, %rp.qname; )\"\n>\n]]>\n<!ENTITY % Ruby.content.simple \n     \"( %rb.qname;, ( %rt.qname; | ( %rp.qname;, %rt.qname;, %rp.qname; ) ) )\"\n>\n]]>\n<!ENTITY % Ruby.content.simple \"( %rb.qname;, %rt.qname; )\" >\n\n<![%Ruby.complex;[\n<!ENTITY % Ruby.content.complex \n     \"| ( %rbc.qname;, %rtc.qname;, %rtc.qname;? )\"\n>\n]]>\n<!ENTITY % Ruby.content.complex \"\" >\n\n<!-- Content models of the rb and the rt elements are intended to\n     allow other inline-level elements of its parent markup language,\n     but it should not include ruby descendent elements. The following\n     parameter entity %NoRuby.content; can be used to redefine\n     those content models with minimum effort.  It's defined as\n     '( #PCDATA )' by default.\n-->\n<!ENTITY % NoRuby.content \"( #PCDATA )\" >\n\n<!-- one or more digits (NUMBER) -->\n<!ENTITY % Number.datatype \"CDATA\" >\n\n<!-- ruby element ...................................... -->\n\n<!ENTITY % ruby.element  \"INCLUDE\" >\n<![%ruby.element;[\n<!ENTITY % ruby.content\n     \"( %Ruby.content.simple; %Ruby.content.complex; )\"\n>\n<!ELEMENT %ruby.qname;  %ruby.content; >\n<!-- end of ruby.element -->]]>\n\n<![%Ruby.complex;[\n<!-- rbc (ruby base component) element ................. -->\n\n<!ENTITY % rbc.element  \"INCLUDE\" >\n<![%rbc.element;[\n<!ENTITY % rbc.content\n     \"(%rb.qname;)+\"\n>\n<!ELEMENT %rbc.qname;  %rbc.content; >\n<!-- end of rbc.element -->]]>\n\n<!-- rtc (ruby text component) element ................. -->\n\n<!ENTITY % rtc.element  \"INCLUDE\" >\n<![%rtc.element;[\n<!ENTITY % rtc.content\n     \"(%rt.qname;)+\"\n>\n<!ELEMENT %rtc.qname;  %rtc.content; >\n<!-- end of rtc.element -->]]>\n]]>\n\n<!-- rb (ruby base) element ............................ -->\n\n<!ENTITY % rb.element  \"INCLUDE\" >\n<![%rb.element;[\n<!-- %rb.content; uses %NoRuby.content; as its content model,\n     which is '( #PCDATA )' by default. It may be overridden\n     by other modules to allow other inline-level elements\n     of its parent markup language, but it should not include\n     ruby descendent elements.\n-->\n<!ENTITY % rb.content \"%NoRuby.content;\" >\n<!ELEMENT %rb.qname;  %rb.content; >\n<!-- end of rb.element -->]]>\n\n<!-- rt (ruby text) element ............................ -->\n\n<!ENTITY % rt.element  \"INCLUDE\" >\n<![%rt.element;[\n<!-- %rt.content; uses %NoRuby.content; as its content model,\n     which is '( #PCDATA )' by default. It may be overridden\n     by other modules to allow other inline-level elements\n     of its parent markup language, but it should not include\n     ruby descendent elements.\n-->\n<!ENTITY % rt.content \"%NoRuby.content;\" >\n\n<!ELEMENT %rt.qname;  %rt.content; >\n<!-- end of rt.element -->]]>\n\n<!-- rbspan attribute is used for complex ruby only ...... -->\n<![%Ruby.complex;[\n<!ENTITY % rt.attlist  \"INCLUDE\" >\n<![%rt.attlist;[\n<!ATTLIST %rt.qname;\n      rbspan         %Number.datatype;      \"1\"\n>\n<!-- end of rt.attlist -->]]>\n]]>\n\n<!-- rp (ruby parenthesis) element ..................... -->\n\n<![%Ruby.fallback;[\n<!ENTITY % rp.element  \"INCLUDE\" >\n<![%rp.element;[\n<!ENTITY % rp.content\n     \"( #PCDATA )\"\n>\n<!ELEMENT %rp.qname;  %rp.content; >\n<!-- end of rp.element -->]]>\n]]>\n\n<!-- Ruby Common Attributes\n\n     The following optional ATTLIST declarations provide an easy way\n     to define common attributes for ruby elements.  These declarations\n     are ignored by default.\n\n     Ruby elements are intended to have common attributes of its\n     parent markup language.  For example, if a markup language defines\n     common attributes as a parameter entity %attrs;, you may add\n     those attributes by just declaring the following parameter entities\n\n         <!ENTITY % Ruby.common.attlists  \"INCLUDE\" >\n         <!ENTITY % Ruby.common.attrib  \"%attrs;\" >\n\n     before including the Ruby module.\n-->\n\n<!ENTITY % Ruby.common.attlists  \"IGNORE\" >\n<![%Ruby.common.attlists;[\n<!ENTITY % Ruby.common.attrib  \"\" >\n\n<!-- common attributes for ruby ........................ -->\n\n<!ENTITY % Ruby.common.attlist  \"INCLUDE\" >\n<![%Ruby.common.attlist;[\n<!ATTLIST %ruby.qname;\n      %Ruby.common.attrib;\n>\n<!-- end of Ruby.common.attlist -->]]>\n\n<![%Ruby.complex;[\n<!-- common attributes for rbc ......................... -->\n\n<!ENTITY % Rbc.common.attlist  \"INCLUDE\" >\n<![%Rbc.common.attlist;[\n<!ATTLIST %rbc.qname;\n      %Ruby.common.attrib;\n>\n<!-- end of Rbc.common.attlist -->]]>\n\n<!-- common attributes for rtc ......................... -->\n\n<!ENTITY % Rtc.common.attlist  \"INCLUDE\" >\n<![%Rtc.common.attlist;[\n<!ATTLIST %rtc.qname;\n      %Ruby.common.attrib;\n>\n<!-- end of Rtc.common.attlist -->]]>\n]]>\n\n<!-- common attributes for rb .......................... -->\n\n<!ENTITY % Rb.common.attlist  \"INCLUDE\" >\n<![%Rb.common.attlist;[\n<!ATTLIST %rb.qname;\n      %Ruby.common.attrib;\n>\n<!-- end of Rb.common.attlist -->]]>\n\n<!-- common attributes for rt .......................... -->\n\n<!ENTITY % Rt.common.attlist  \"INCLUDE\" >\n<![%Rt.common.attlist;[\n<!ATTLIST %rt.qname;\n      %Ruby.common.attrib;\n>\n<!-- end of Rt.common.attlist -->]]>\n\n<![%Ruby.fallback;[\n<!-- common attributes for rp .......................... -->\n\n<!ENTITY % Rp.common.attlist  \"INCLUDE\" >\n<![%Rp.common.attlist;[\n<!ATTLIST %rp.qname;\n      %Ruby.common.attrib;\n>\n<!-- end of Rp.common.attlist -->]]>\n]]>\n]]>\n\n<!-- end of xhtml-ruby-1.mod -->\n]]>\n\n<!-- Presentation Module  ........................................ -->\n<!ENTITY % xhtml-pres.module \"INCLUDE\" >\n<![%xhtml-pres.module;[\n<!ENTITY % xhtml-pres.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML Presentation 1.0//EN\"\n            \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-pres-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Presentation Module ............................................ -->\n<!-- file: xhtml-pres-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-pres-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ELEMENTS XHTML Presentation 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-pres-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Presentational Elements\n\n     This module defines elements and their attributes for\n     simple presentation-related markup.\n-->\n\n<!ENTITY % xhtml-inlpres.module \"INCLUDE\" >\n<![%xhtml-inlpres.module;[\n<!ENTITY % xhtml-inlpres.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML Inline Presentation 1.0//EN\"\n            \"xhtml-inlpres-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Inline Presentation Module  .................................... -->\n<!-- file: xhtml-inlpres-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-inlpres-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ELEMENTS XHTML Inline Presentation 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-inlpres-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Inline Presentational Elements\n\n        b, big, i, small, sub, sup, tt\n\n     This module declares the elements and their attributes used to\n     support inline-level presentational markup.\n-->\n\n<!ENTITY % b.element  \"INCLUDE\" >\n<![%b.element;[\n<!ENTITY % b.content\n     \"( #PCDATA | %Inline.mix; )*\"\n>\n<!ENTITY % b.qname  \"b\" >\n<!ELEMENT %b.qname;  %b.content; >\n<!-- end of b.element -->]]>\n\n<!ENTITY % b.attlist  \"INCLUDE\" >\n<![%b.attlist;[\n<!ATTLIST %b.qname;\n      %Common.attrib;\n>\n<!-- end of b.attlist -->]]>\n\n<!ENTITY % big.element  \"INCLUDE\" >\n<![%big.element;[\n<!ENTITY % big.content\n     \"( #PCDATA | %Inline.mix; )*\"\n>\n<!ENTITY % big.qname  \"big\" >\n<!ELEMENT %big.qname;  %big.content; >\n<!-- end of big.element -->]]>\n\n<!ENTITY % big.attlist  \"INCLUDE\" >\n<![%big.attlist;[\n<!ATTLIST %big.qname;\n      %Common.attrib;\n>\n<!-- end of big.attlist -->]]>\n\n<!ENTITY % i.element  \"INCLUDE\" >\n<![%i.element;[\n<!ENTITY % i.content\n     \"( #PCDATA | %Inline.mix; )*\"\n>\n<!ENTITY % i.qname  \"i\" >\n<!ELEMENT %i.qname;  %i.content; >\n<!-- end of i.element -->]]>\n\n<!ENTITY % i.attlist  \"INCLUDE\" >\n<![%i.attlist;[\n<!ATTLIST %i.qname;\n      %Common.attrib;\n>\n<!-- end of i.attlist -->]]>\n\n<!ENTITY % small.element  \"INCLUDE\" >\n<![%small.element;[\n<!ENTITY % small.content\n     \"( #PCDATA | %Inline.mix; )*\"\n>\n<!ENTITY % small.qname  \"small\" >\n<!ELEMENT %small.qname;  %small.content; >\n<!-- end of small.element -->]]>\n\n<!ENTITY % small.attlist  \"INCLUDE\" >\n<![%small.attlist;[\n<!ATTLIST %small.qname;\n      %Common.attrib;\n>\n<!-- end of small.attlist -->]]>\n\n<!ENTITY % sub.element  \"INCLUDE\" >\n<![%sub.element;[\n<!ENTITY % sub.content\n     \"( #PCDATA | %Inline.mix; )*\"\n>\n<!ENTITY % sub.qname  \"sub\" >\n<!ELEMENT %sub.qname;  %sub.content; >\n<!-- end of sub.element -->]]>\n\n<!ENTITY % sub.attlist  \"INCLUDE\" >\n<![%sub.attlist;[\n<!ATTLIST %sub.qname;\n      %Common.attrib;\n>\n<!-- end of sub.attlist -->]]>\n\n<!ENTITY % sup.element  \"INCLUDE\" >\n<![%sup.element;[\n<!ENTITY % sup.content\n     \"( #PCDATA | %Inline.mix; )*\"\n>\n<!ENTITY % sup.qname  \"sup\" >\n<!ELEMENT %sup.qname;  %sup.content; >\n<!-- end of sup.element -->]]>\n\n<!ENTITY % sup.attlist  \"INCLUDE\" >\n<![%sup.attlist;[\n<!ATTLIST %sup.qname;\n      %Common.attrib;\n>\n<!-- end of sup.attlist -->]]>\n\n<!ENTITY % tt.element  \"INCLUDE\" >\n<![%tt.element;[\n<!ENTITY % tt.content\n     \"( #PCDATA | %Inline.mix; )*\"\n>\n<!ENTITY % tt.qname  \"tt\" >\n<!ELEMENT %tt.qname;  %tt.content; >\n<!-- end of tt.element -->]]>\n\n<!ENTITY % tt.attlist  \"INCLUDE\" >\n<![%tt.attlist;[\n<!ATTLIST %tt.qname;\n      %Common.attrib;\n>\n<!-- end of tt.attlist -->]]>\n\n<!-- end of xhtml-inlpres-1.mod -->\n]]>\n\n<!ENTITY % xhtml-blkpres.module \"INCLUDE\" >\n<![%xhtml-blkpres.module;[\n<!ENTITY % xhtml-blkpres.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML Block Presentation 1.0//EN\"\n            \"xhtml-blkpres-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Block Presentation Module  ..................................... -->\n<!-- file: xhtml-blkpres-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-blkpres-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ELEMENTS XHTML Block Presentation 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-blkpres-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Block Presentational Elements\n\n        hr\n\n     This module declares the elements and their attributes used to\n     support block-level presentational markup.\n-->\n\n<!ENTITY % hr.element  \"INCLUDE\" >\n<![%hr.element;[\n<!ENTITY % hr.content  \"EMPTY\" >\n<!ENTITY % hr.qname  \"hr\" >\n<!ELEMENT %hr.qname;  %hr.content; >\n<!-- end of hr.element -->]]>\n\n<!ENTITY % hr.attlist  \"INCLUDE\" >\n<![%hr.attlist;[\n<!ATTLIST %hr.qname;\n      %Common.attrib;\n>\n<!-- end of hr.attlist -->]]>\n\n<!-- end of xhtml-blkpres-1.mod -->\n]]>\n\n<!-- end of xhtml-pres-1.mod -->\n]]>\n\n<!-- Link Element Module  ........................................ -->\n<!ENTITY % xhtml-link.module \"INCLUDE\" >\n<![%xhtml-link.module;[\n<!ENTITY % xhtml-link.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML Link Element 1.0//EN\"\n            \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-link-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Link Element Module  ........................................... -->\n<!-- file: xhtml-link-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-link-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ELEMENTS XHTML Link Element 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-link-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Link element\n\n        link\n\n     This module declares the link element type and its attributes,\n     which could (in principle) be used to define document-level links\n     to external resources such as:\n\n     a) for document specific toolbars/menus, e.g. start, contents,\n        previous, next, index, end, help\n     b) to link to a separate style sheet (rel=\"stylesheet\")\n     c) to make a link to a script (rel=\"script\")\n     d) by stylesheets to control how collections of html nodes are\n        rendered into printed documents\n     e) to make a link to a printable version of this document\n        e.g. a postscript or pdf version (rel=\"alternate\" media=\"print\")\n-->\n\n<!-- link: Media-Independent Link ...................... -->\n\n<!ENTITY % link.element  \"INCLUDE\" >\n<![%link.element;[\n<!ENTITY % link.content  \"EMPTY\" >\n<!ENTITY % link.qname  \"link\" >\n<!ELEMENT %link.qname;  %link.content; >\n<!-- end of link.element -->]]>\n\n<!ENTITY % link.attlist  \"INCLUDE\" >\n<![%link.attlist;[\n<!ATTLIST %link.qname;\n      %Common.attrib;\n      charset      %Charset.datatype;       #IMPLIED\n      href         %URI.datatype;           #IMPLIED\n      hreflang     %LanguageCode.datatype;  #IMPLIED\n      type         %ContentType.datatype;   #IMPLIED\n      rel          %LinkTypes.datatype;     #IMPLIED\n      rev          %LinkTypes.datatype;     #IMPLIED\n      media        %MediaDesc.datatype;     #IMPLIED\n>\n<!-- end of link.attlist -->]]>\n\n<!-- end of xhtml-link-1.mod -->\n]]>\n\n<!-- Document Metainformation Module  ............................ -->\n<!ENTITY % xhtml-meta.module \"INCLUDE\" >\n<![%xhtml-meta.module;[\n<!ENTITY % xhtml-meta.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML Metainformation 1.0//EN\"\n            \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-meta-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Document Metainformation Module  ............................... -->\n<!-- file: xhtml-meta-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-meta-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ELEMENTS XHTML Metainformation 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-meta-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Meta Information\n\n        meta\n\n     This module declares the meta element type and its attributes,\n     used to provide declarative document metainformation.\n-->\n\n<!-- meta: Generic Metainformation ..................... -->\n\n<!ENTITY % meta.element  \"INCLUDE\" >\n<![%meta.element;[\n<!ENTITY % meta.content  \"EMPTY\" >\n<!ENTITY % meta.qname  \"meta\" >\n<!ELEMENT %meta.qname;  %meta.content; >\n<!-- end of meta.element -->]]>\n\n<!ENTITY % meta.attlist  \"INCLUDE\" >\n<![%meta.attlist;[\n<!ATTLIST %meta.qname;\n      %XHTML.xmlns.attrib;\n      %I18n.attrib;\n      http-equiv   NMTOKEN                  #IMPLIED\n      name         NMTOKEN                  #IMPLIED\n      content      CDATA                    #REQUIRED\n      scheme       CDATA                    #IMPLIED\n>\n<!-- end of meta.attlist -->]]>\n\n<!-- end of xhtml-meta-1.mod -->\n]]>\n\n<!-- Base Element Module  ........................................ -->\n<!ENTITY % xhtml-base.module \"INCLUDE\" >\n<![%xhtml-base.module;[\n<!ENTITY % xhtml-base.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML Base Element 1.0//EN\"\n            \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-base-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Base Element Module  ........................................... -->\n<!-- file: xhtml-base-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-base-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ELEMENTS XHTML Base Element 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-base-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Base element\n\n        base\n\n     This module declares the base element type and its attributes,\n     used to define a base URI against which relative URIs in the\n     document will be resolved.\n\n     Note that this module also redeclares the content model for\n     the head element to include the base element.\n-->\n\n<!-- base: Document Base URI ........................... -->\n\n<!ENTITY % base.element  \"INCLUDE\" >\n<![%base.element;[\n<!ENTITY % base.content  \"EMPTY\" >\n<!ENTITY % base.qname  \"base\" >\n<!ELEMENT %base.qname;  %base.content; >\n<!-- end of base.element -->]]>\n\n<!ENTITY % base.attlist  \"INCLUDE\" >\n<![%base.attlist;[\n<!ATTLIST %base.qname;\n      %XHTML.xmlns.attrib;\n      href         %URI.datatype;           #REQUIRED\n>\n<!-- end of base.attlist -->]]>\n\n<!ENTITY % head.content\n    \"( %HeadOpts.mix;,\n     ( ( %title.qname;, %HeadOpts.mix;, ( %base.qname;, %HeadOpts.mix; )? )\n     | ( %base.qname;, %HeadOpts.mix;, ( %title.qname;, %HeadOpts.mix; ))))\"\n>\n\n<!-- end of xhtml-base-1.mod -->\n]]>\n\n<!-- Scripting Module  ........................................... -->\n<!ENTITY % xhtml-script.module \"INCLUDE\" >\n<![%xhtml-script.module;[\n<!ENTITY % xhtml-script.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML Scripting 1.0//EN\"\n            \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-script-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Document Scripting Module  ..................................... -->\n<!-- file: xhtml-script-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-script-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ELEMENTS XHTML Scripting 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-script-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Scripting\n\n        script, noscript\n\n     This module declares element types and attributes used to provide\n     support for executable scripts as well as an alternate content\n     container where scripts are not supported.\n-->\n\n<!-- script: Scripting Statement ....................... -->\n\n<!ENTITY % script.element  \"INCLUDE\" >\n<![%script.element;[\n<!ENTITY % script.content  \"( #PCDATA )\" >\n<!ENTITY % script.qname  \"script\" >\n<!ELEMENT %script.qname;  %script.content; >\n<!-- end of script.element -->]]>\n\n<!ENTITY % script.attlist  \"INCLUDE\" >\n<![%script.attlist;[\n<!ATTLIST %script.qname;\n      %XHTML.xmlns.attrib;\n      charset      %Charset.datatype;       #IMPLIED\n      type         %ContentType.datatype;   #REQUIRED\n      src          %URI.datatype;           #IMPLIED\n      defer        ( defer )                #IMPLIED\n      xml:space    ( preserve )             #FIXED 'preserve'\n>\n<!-- end of script.attlist -->]]>\n\n<!-- noscript: No-Script Alternate Content ............. -->\n\n<!ENTITY % noscript.element  \"INCLUDE\" >\n<![%noscript.element;[\n<!ENTITY % noscript.content\n     \"( %Block.mix; )+\"\n>\n<!ENTITY % noscript.qname  \"noscript\" >\n<!ELEMENT %noscript.qname;  %noscript.content; >\n<!-- end of noscript.element -->]]>\n\n<!ENTITY % noscript.attlist  \"INCLUDE\" >\n<![%noscript.attlist;[\n<!ATTLIST %noscript.qname;\n      %Common.attrib;\n>\n<!-- end of noscript.attlist -->]]>\n\n<!-- end of xhtml-script-1.mod -->\n]]>\n\n<!-- Style Sheets Module  ......................................... -->\n<!ENTITY % xhtml-style.module \"INCLUDE\" >\n<![%xhtml-style.module;[\n<!ENTITY % xhtml-style.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML Style Sheets 1.0//EN\"\n            \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-style-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Document Style Sheet Module  .................................... -->\n<!-- file: xhtml-style-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-style-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//DTD XHTML Style Sheets 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-style-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Style Sheets\n\n        style\n\n     This module declares the style element type and its attributes,\n     used to embed stylesheet information in the document head element.\n-->\n\n<!-- style: Style Sheet Information ..................... -->\n\n<!ENTITY % style.element  \"INCLUDE\" >\n<![%style.element;[\n<!ENTITY % style.content  \"( #PCDATA )\" >\n<!ENTITY % style.qname  \"style\" >\n<!ELEMENT %style.qname;  %style.content; >\n<!-- end of style.element -->]]>\n\n<!ENTITY % style.attlist  \"INCLUDE\" >\n<![%style.attlist;[\n<!ATTLIST %style.qname;\n      %XHTML.xmlns.attrib;\n      %title.attrib;\n      %I18n.attrib;\n      type         %ContentType.datatype;   #REQUIRED\n      media        %MediaDesc.datatype;     #IMPLIED\n      xml:space    ( preserve )             #FIXED 'preserve'\n>\n<!-- end of style.attlist -->]]>\n\n<!-- end of xhtml-style-1.mod -->\n]]>\n\n<!-- Image Module  ............................................... -->\n<!ENTITY % xhtml-image.module \"INCLUDE\" >\n<![%xhtml-image.module;[\n<!ENTITY % xhtml-image.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML Images 1.0//EN\"\n            \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-image-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Images Module  ................................................. -->\n<!-- file: xhtml-image-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Rovision: $Id: xhtml-image-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ELEMENTS XHTML Images 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-image-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Images\n\n        img\n\n     This module provides markup to support basic image embedding.\n-->\n\n<!-- To avoid problems with text-only UAs as well as to make\n     image content understandable and navigable to users of\n     non-visual UAs, you need to provide a description with\n     the 'alt' attribute, and avoid server-side image maps.\n-->\n\n<!ENTITY % img.element  \"INCLUDE\" >\n<![%img.element;[\n<!ENTITY % img.content  \"EMPTY\" >\n<!ENTITY % img.qname  \"img\" >\n<!ELEMENT %img.qname;  %img.content; >\n<!-- end of img.element -->]]>\n\n<!ENTITY % img.attlist  \"INCLUDE\" >\n<![%img.attlist;[\n<!ATTLIST %img.qname;\n      %Common.attrib;\n      src          %URI.datatype;           #REQUIRED\n      alt          %Text.datatype;          #REQUIRED\n      longdesc     %URI.datatype;           #IMPLIED\n      height       %Length.datatype;        #IMPLIED\n      width        %Length.datatype;        #IMPLIED\n>\n<!-- end of img.attlist -->]]>\n\n<!-- end of xhtml-image-1.mod -->\n]]>\n\n<!-- Client-side Image Map Module  ............................... -->\n<!ENTITY % xhtml-csismap.module \"INCLUDE\" >\n<![%xhtml-csismap.module;[\n<!ENTITY % xhtml-csismap.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML Client-side Image Maps 1.0//EN\"\n            \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-csismap-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Client-side Image Map Module  .................................. -->\n<!-- file: xhtml-csismap-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-csismap-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ELEMENTS XHTML Client-side Image Maps 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-csismap-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Client-side Image Maps\n\n        area, map\n\n     This module declares elements and attributes to support client-side\n     image maps. This requires that the Image Module (or a module\n     declaring the img element type) be included in the DTD.\n\n     These can be placed in the same document or grouped in a\n     separate document, although the latter isn't widely supported\n-->\n\n<!ENTITY % area.element  \"INCLUDE\" >\n<![%area.element;[\n<!ENTITY % area.content  \"EMPTY\" >\n<!ENTITY % area.qname  \"area\" >\n<!ELEMENT %area.qname;  %area.content; >\n<!-- end of area.element -->]]>\n\n<!ENTITY % Shape.datatype \"( rect | circle | poly | default )\">\n<!ENTITY % Coords.datatype \"CDATA\" >\n\n<!ENTITY % area.attlist  \"INCLUDE\" >\n<![%area.attlist;[\n<!ATTLIST %area.qname;\n      %Common.attrib;\n      href         %URI.datatype;           #IMPLIED\n      shape        %Shape.datatype;         'rect'\n      coords       %Coords.datatype;        #IMPLIED\n      nohref       ( nohref )               #IMPLIED\n      alt          %Text.datatype;          #REQUIRED\n      tabindex     %Number.datatype;        #IMPLIED\n      accesskey    %Character.datatype;     #IMPLIED\n>\n<!-- end of area.attlist -->]]>\n\n<!-- modify anchor attribute definition list\n     to allow for client-side image maps\n-->\n<!ATTLIST %a.qname;\n      shape        %Shape.datatype;         'rect'\n      coords       %Coords.datatype;        #IMPLIED\n>\n\n<!-- modify img attribute definition list\n     to allow for client-side image maps\n-->\n<!ATTLIST %img.qname;\n      usemap       IDREF                    #IMPLIED\n>\n\n<!-- modify form input attribute definition list\n     to allow for client-side image maps\n-->\n<!ATTLIST %input.qname;\n      usemap       IDREF                    #IMPLIED\n>\n\n<!-- modify object attribute definition list\n     to allow for client-side image maps\n-->\n<!ATTLIST %object.qname;\n      usemap       IDREF                    #IMPLIED\n>\n\n<!-- 'usemap' points to the 'id' attribute of a <map> element,\n     which must be in the same document; support for external\n     document maps was not widely supported in HTML and is\n     eliminated in XHTML.\n\n     It is considered an error for the element pointed to by\n     a usemap IDREF to occur in anything but a <map> element.\n-->\n\n<!ENTITY % map.element  \"INCLUDE\" >\n<![%map.element;[\n<!ENTITY % map.content\n     \"(( %Block.mix; ) | %area.qname; )+\"\n>\n<!ENTITY % map.qname  \"map\" >\n<!ELEMENT %map.qname;  %map.content; >\n<!-- end of map.element -->]]>\n\n<!ENTITY % map.attlist  \"INCLUDE\" >\n<![%map.attlist;[\n<!ATTLIST %map.qname;\n      %XHTML.xmlns.attrib;\n      id           ID                       #REQUIRED\n      %class.attrib;\n      %title.attrib;\n      %Core.extra.attrib;\n      %I18n.attrib;\n      %Events.attrib;\n>\n<!-- end of map.attlist -->]]>\n\n<!-- end of xhtml-csismap-1.mod -->\n]]>\n\n<!-- Server-side Image Map Module  ............................... -->\n<!ENTITY % xhtml-ssismap.module \"INCLUDE\" >\n<![%xhtml-ssismap.module;[\n<!ENTITY % xhtml-ssismap.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML Server-side Image Maps 1.0//EN\"\n            \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-ssismap-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Server-side Image Map Module  .................................. -->\n<!-- file: xhtml-ssismap-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-ssismap-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ELEMENTS XHTML Server-side Image Maps 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-ssismap-1.mod\"\n\n     Revisions:\n#2000-10-22: added declaration for 'ismap' on <input>\n     ....................................................................... -->\n\n<!-- Server-side Image Maps\n\n     This adds the 'ismap' attribute to the img and input elements\n     to support server-side processing of a user selection.\n-->\n\n<!ATTLIST %img.qname;\n      ismap        ( ismap )                #IMPLIED\n>\n\n<!ATTLIST %input.qname;\n      ismap        ( ismap )                #IMPLIED\n>\n\n<!-- end of xhtml-ssismap-1.mod -->\n]]>\n\n<!-- Param Element Module  ....................................... -->\n<!ENTITY % xhtml-param.module \"INCLUDE\" >\n<![%xhtml-param.module;[\n<!ENTITY % xhtml-param.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML Param Element 1.0//EN\"\n            \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-param-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Param Element Module  ..................................... -->\n<!-- file: xhtml-param-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-param-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ELEMENTS XHTML Param Element 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-param-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Parameters for Java Applets and Embedded Objects\n\n        param\n\n     This module provides declarations for the param element,\n     used to provide named property values for the applet\n     and object elements.\n-->\n\n<!-- param: Named Property Value ....................... -->\n\n<!ENTITY % param.element  \"INCLUDE\" >\n<![%param.element;[\n<!ENTITY % param.content  \"EMPTY\" >\n<!ENTITY % param.qname  \"param\" >\n<!ELEMENT %param.qname;  %param.content; >\n<!-- end of param.element -->]]>\n\n<!ENTITY % param.attlist  \"INCLUDE\" >\n<![%param.attlist;[\n<!ATTLIST %param.qname;\n      %XHTML.xmlns.attrib;\n      %id.attrib;\n      name         CDATA                    #REQUIRED\n      value        CDATA                    #IMPLIED\n      valuetype    ( data | ref | object )  'data'\n      type         %ContentType.datatype;   #IMPLIED\n>\n<!-- end of param.attlist -->]]>\n\n<!-- end of xhtml-param-1.mod -->\n]]>\n\n<!-- Embedded Object Module  ..................................... -->\n<!ENTITY % xhtml-object.module \"INCLUDE\" >\n<![%xhtml-object.module;[\n<!ENTITY % xhtml-object.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML Embedded Object 1.0//EN\"\n            \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-object-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Embedded Object Module  ........................................ -->\n<!-- file: xhtml-object-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-object-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ELEMENTS XHTML Embedded Object 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-object-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Embedded Objects\n\n        object\n\n     This module declares the object element type and its attributes, used\n     to embed external objects as part of XHTML pages. In the document,\n     place param elements prior to other content within the object element.\n\n     Note that use of this module requires instantiation of the Param\n     Element Module.\n-->\n\n<!-- object: Generic Embedded Object ................... -->\n\n<!ENTITY % object.element  \"INCLUDE\" >\n<![%object.element;[\n<!ENTITY % object.content\n     \"( #PCDATA | %Flow.mix; | %param.qname; )*\"\n>\n<!ENTITY % object.qname  \"object\" >\n<!ELEMENT %object.qname;  %object.content; >\n<!-- end of object.element -->]]>\n\n<!ENTITY % object.attlist  \"INCLUDE\" >\n<![%object.attlist;[\n<!ATTLIST %object.qname;\n      %Common.attrib;\n      declare      ( declare )              #IMPLIED\n      classid      %URI.datatype;           #IMPLIED\n      codebase     %URI.datatype;           #IMPLIED\n      data         %URI.datatype;           #IMPLIED\n      type         %ContentType.datatype;   #IMPLIED\n      codetype     %ContentType.datatype;   #IMPLIED\n      archive      %URIs.datatype;          #IMPLIED\n      standby      %Text.datatype;          #IMPLIED\n      height       %Length.datatype;        #IMPLIED\n      width        %Length.datatype;        #IMPLIED\n      name         CDATA                    #IMPLIED\n      tabindex     %Number.datatype;        #IMPLIED\n>\n<!-- end of object.attlist -->]]>\n\n<!-- end of xhtml-object-1.mod -->\n]]>\n\n<!-- Tables Module ............................................... -->\n<!ENTITY % xhtml-table.module \"INCLUDE\" >\n<![%xhtml-table.module;[\n<!ENTITY % xhtml-table.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML Tables 1.0//EN\"\n            \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-table-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Table Module  .................................................. -->\n<!-- file: xhtml-table-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-table-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ELEMENTS XHTML Tables 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-table-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Tables\n\n        table, caption, thead, tfoot, tbody, colgroup, col, tr, th, td\n\n     This module declares element types and attributes used to provide\n     table markup similar to HTML 4.0, including features that enable\n     better accessibility for non-visual user agents.\n-->\n\n<!-- declare qualified element type names:\n-->\n<!ENTITY % table.qname  \"table\" >\n<!ENTITY % caption.qname  \"caption\" >\n<!ENTITY % thead.qname  \"thead\" >\n<!ENTITY % tfoot.qname  \"tfoot\" >\n<!ENTITY % tbody.qname  \"tbody\" >\n<!ENTITY % colgroup.qname  \"colgroup\" >\n<!ENTITY % col.qname  \"col\" >\n<!ENTITY % tr.qname  \"tr\" >\n<!ENTITY % th.qname  \"th\" >\n<!ENTITY % td.qname  \"td\" >\n\n<!-- The frame attribute specifies which parts of the frame around\n     the table should be rendered. The values are not the same as\n     CALS to avoid a name clash with the valign attribute.\n-->\n<!ENTITY % frame.attrib\n     \"frame        ( void\n                   | above\n                   | below\n                   | hsides\n                   | lhs\n                   | rhs\n                   | vsides\n                   | box\n                   | border )               #IMPLIED\"\n>\n\n<!-- The rules attribute defines which rules to draw between cells:\n\n     If rules is absent then assume:\n\n       \"none\" if border is absent or border=\"0\" otherwise \"all\"\n-->\n<!ENTITY % rules.attrib\n     \"rules        ( none\n                   | groups\n                   | rows\n                   | cols\n                   | all )                  #IMPLIED\"\n>\n\n<!-- horizontal alignment attributes for cell contents\n-->\n<!ENTITY % CellHAlign.attrib\n     \"align        ( left\n                   | center\n                   | right\n                   | justify\n                   | char )                 #IMPLIED\n      char         %Character.datatype;     #IMPLIED\n      charoff      %Length.datatype;        #IMPLIED\"\n>\n\n<!-- vertical alignment attribute for cell contents\n-->\n<!ENTITY % CellVAlign.attrib\n     \"valign       ( top\n                   | middle\n                   | bottom\n                   | baseline )             #IMPLIED\"\n>\n\n<!-- scope is simpler than axes attribute for common tables\n-->\n<!ENTITY % scope.attrib\n     \"scope        ( row\n                   | col\n                   | rowgroup\n                   | colgroup )             #IMPLIED\"\n>\n\n<!-- table: Table Element .............................. -->\n\n<!ENTITY % table.element  \"INCLUDE\" >\n<![%table.element;[\n<!ENTITY % table.content\n     \"( %caption.qname;?, ( %col.qname;* | %colgroup.qname;* ),\n      (( %thead.qname;?, %tfoot.qname;?, %tbody.qname;+ ) | ( %tr.qname;+ )))\"\n>\n<!ELEMENT %table.qname;  %table.content; >\n<!-- end of table.element -->]]>\n\n<!ENTITY % table.attlist  \"INCLUDE\" >\n<![%table.attlist;[\n<!ATTLIST %table.qname;\n      %Common.attrib;\n      summary      %Text.datatype;          #IMPLIED\n      width        %Length.datatype;        #IMPLIED\n      border       %Pixels.datatype;        #IMPLIED\n      %frame.attrib;\n      %rules.attrib;\n      cellspacing  %Length.datatype;        #IMPLIED\n      cellpadding  %Length.datatype;        #IMPLIED\n>\n<!-- end of table.attlist -->]]>\n\n<!-- caption: Table Caption ............................ -->\n\n<!ENTITY % caption.element  \"INCLUDE\" >\n<![%caption.element;[\n<!ENTITY % caption.content\n     \"( #PCDATA | %Inline.mix; )*\"\n>\n<!ELEMENT %caption.qname;  %caption.content; >\n<!-- end of caption.element -->]]>\n\n<!ENTITY % caption.attlist  \"INCLUDE\" >\n<![%caption.attlist;[\n<!ATTLIST %caption.qname;\n      %Common.attrib;\n>\n<!-- end of caption.attlist -->]]>\n\n<!-- thead: Table Header ............................... -->\n\n<!-- Use thead to duplicate headers when breaking table\n     across page boundaries, or for static headers when\n     tbody sections are rendered in scrolling panel.\n-->\n\n<!ENTITY % thead.element  \"INCLUDE\" >\n<![%thead.element;[\n<!ENTITY % thead.content  \"( %tr.qname; )+\" >\n<!ELEMENT %thead.qname;  %thead.content; >\n<!-- end of thead.element -->]]>\n\n<!ENTITY % thead.attlist  \"INCLUDE\" >\n<![%thead.attlist;[\n<!ATTLIST %thead.qname;\n      %Common.attrib;\n      %CellHAlign.attrib;\n      %CellVAlign.attrib;\n>\n<!-- end of thead.attlist -->]]>\n\n<!-- tfoot: Table Footer ............................... -->\n\n<!-- Use tfoot to duplicate footers when breaking table\n     across page boundaries, or for static footers when\n     tbody sections are rendered in scrolling panel.\n-->\n\n<!ENTITY % tfoot.element  \"INCLUDE\" >\n<![%tfoot.element;[\n<!ENTITY % tfoot.content  \"( %tr.qname; )+\" >\n<!ELEMENT %tfoot.qname;  %tfoot.content; >\n<!-- end of tfoot.element -->]]>\n\n<!ENTITY % tfoot.attlist  \"INCLUDE\" >\n<![%tfoot.attlist;[\n<!ATTLIST %tfoot.qname;\n      %Common.attrib;\n      %CellHAlign.attrib;\n      %CellVAlign.attrib;\n>\n<!-- end of tfoot.attlist -->]]>\n\n<!-- tbody: Table Body ................................. -->\n\n<!-- Use multiple tbody sections when rules are needed\n     between groups of table rows.\n-->\n\n<!ENTITY % tbody.element  \"INCLUDE\" >\n<![%tbody.element;[\n<!ENTITY % tbody.content  \"( %tr.qname; )+\" >\n<!ELEMENT %tbody.qname;  %tbody.content; >\n<!-- end of tbody.element -->]]>\n\n<!ENTITY % tbody.attlist  \"INCLUDE\" >\n<![%tbody.attlist;[\n<!ATTLIST %tbody.qname;\n      %Common.attrib;\n      %CellHAlign.attrib;\n      %CellVAlign.attrib;\n>\n<!-- end of tbody.attlist -->]]>\n\n<!-- colgroup: Table Column Group ...................... -->\n\n<!-- colgroup groups a set of col elements. It allows you\n     to group several semantically-related columns together.\n-->\n\n<!ENTITY % colgroup.element  \"INCLUDE\" >\n<![%colgroup.element;[\n<!ENTITY % colgroup.content  \"( %col.qname; )*\" >\n<!ELEMENT %colgroup.qname;  %colgroup.content; >\n<!-- end of colgroup.element -->]]>\n\n<!ENTITY % colgroup.attlist  \"INCLUDE\" >\n<![%colgroup.attlist;[\n<!ATTLIST %colgroup.qname;\n      %Common.attrib;\n      span         %Number.datatype;        '1'\n      width        %MultiLength.datatype;   #IMPLIED\n      %CellHAlign.attrib;\n      %CellVAlign.attrib;\n>\n<!-- end of colgroup.attlist -->]]>\n\n<!-- col: Table Column ................................. -->\n\n<!-- col elements define the alignment properties for\n     cells in one or more columns.\n\n     The width attribute specifies the width of the\n     columns, e.g.\n\n       width=\"64\"        width in screen pixels\n       width=\"0.5*\"      relative width of 0.5\n\n     The span attribute causes the attributes of one\n     col element to apply to more than one column.\n-->\n\n<!ENTITY % col.element  \"INCLUDE\" >\n<![%col.element;[\n<!ENTITY % col.content  \"EMPTY\" >\n<!ELEMENT %col.qname;  %col.content; >\n<!-- end of col.element -->]]>\n\n<!ENTITY % col.attlist  \"INCLUDE\" >\n<![%col.attlist;[\n<!ATTLIST %col.qname;\n      %Common.attrib;\n      span         %Number.datatype;        '1'\n      width        %MultiLength.datatype;   #IMPLIED\n      %CellHAlign.attrib;\n      %CellVAlign.attrib;\n>\n<!-- end of col.attlist -->]]>\n\n<!-- tr: Table Row ..................................... -->\n\n<!ENTITY % tr.element  \"INCLUDE\" >\n<![%tr.element;[\n<!ENTITY % tr.content  \"( %th.qname; | %td.qname; )+\" >\n<!ELEMENT %tr.qname;  %tr.content; >\n<!-- end of tr.element -->]]>\n\n<!ENTITY % tr.attlist  \"INCLUDE\" >\n<![%tr.attlist;[\n<!ATTLIST %tr.qname;\n      %Common.attrib;\n      %CellHAlign.attrib;\n      %CellVAlign.attrib;\n>\n<!-- end of tr.attlist -->]]>\n\n<!-- th: Table Header Cell ............................. -->\n\n<!-- th is for header cells, td for data,\n     but for cells acting as both use td\n-->\n\n<!ENTITY % th.element  \"INCLUDE\" >\n<![%th.element;[\n<!ENTITY % th.content\n     \"( #PCDATA | %Flow.mix; )*\"\n>\n<!ELEMENT %th.qname;  %th.content; >\n<!-- end of th.element -->]]>\n\n<!ENTITY % th.attlist  \"INCLUDE\" >\n<![%th.attlist;[\n<!ATTLIST %th.qname;\n      %Common.attrib;\n      abbr         %Text.datatype;          #IMPLIED\n      axis         CDATA                    #IMPLIED\n      headers      IDREFS                   #IMPLIED\n      %scope.attrib;\n      rowspan      %Number.datatype;        '1'\n      colspan      %Number.datatype;        '1'\n      %CellHAlign.attrib;\n      %CellVAlign.attrib;\n>\n<!-- end of th.attlist -->]]>\n\n<!-- td: Table Data Cell ............................... -->\n\n<!ENTITY % td.element  \"INCLUDE\" >\n<![%td.element;[\n<!ENTITY % td.content\n     \"( #PCDATA | %Flow.mix; )*\"\n>\n<!ELEMENT %td.qname;  %td.content; >\n<!-- end of td.element -->]]>\n\n<!ENTITY % td.attlist  \"INCLUDE\" >\n<![%td.attlist;[\n<!ATTLIST %td.qname;\n      %Common.attrib;\n      abbr         %Text.datatype;          #IMPLIED\n      axis         CDATA                    #IMPLIED\n      headers      IDREFS                   #IMPLIED\n      %scope.attrib;\n      rowspan      %Number.datatype;        '1'\n      colspan      %Number.datatype;        '1'\n      %CellHAlign.attrib;\n      %CellVAlign.attrib;\n>\n<!-- end of td.attlist -->]]>\n\n<!-- end of xhtml-table-1.mod -->\n]]>\n\n<!-- Forms Module  ............................................... -->\n<!ENTITY % xhtml-form.module \"INCLUDE\" >\n<![%xhtml-form.module;[\n<!ENTITY % xhtml-form.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML Forms 1.0//EN\"\n            \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-form-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Forms Module  .................................................. -->\n<!-- file: xhtml-form-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-form-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ELEMENTS XHTML Forms 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-form-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Forms\n\n        form, label, input, select, optgroup, option,\n        textarea, fieldset, legend, button\n\n     This module declares markup to provide support for online\n     forms, based on the features found in HTML 4.0 forms.\n-->\n\n<!-- declare qualified element type names:\n-->\n<!ENTITY % form.qname  \"form\" >\n<!ENTITY % label.qname  \"label\" >\n<!ENTITY % input.qname  \"input\" >\n<!ENTITY % select.qname  \"select\" >\n<!ENTITY % optgroup.qname  \"optgroup\" >\n<!ENTITY % option.qname  \"option\" >\n<!ENTITY % textarea.qname  \"textarea\" >\n<!ENTITY % fieldset.qname  \"fieldset\" >\n<!ENTITY % legend.qname  \"legend\" >\n<!ENTITY % button.qname  \"button\" >\n\n<!-- %BlkNoForm.mix; includes all non-form block elements,\n     plus %Misc.class;\n-->\n<!ENTITY % BlkNoForm.mix\n     \"%Heading.class;\n      | %List.class;\n      | %BlkStruct.class;\n      %BlkPhras.class;\n      %BlkPres.class;\n      %Table.class;\n      %Block.extra;\n      %Misc.class;\"\n>\n\n<!-- form: Form Element ................................ -->\n\n<!ENTITY % form.element  \"INCLUDE\" >\n<![%form.element;[\n<!ENTITY % form.content\n     \"( %BlkNoForm.mix;\n      | %fieldset.qname; )+\"\n>\n<!ELEMENT %form.qname;  %form.content; >\n<!-- end of form.element -->]]>\n\n<!ENTITY % form.attlist  \"INCLUDE\" >\n<![%form.attlist;[\n<!ATTLIST %form.qname;\n      %Common.attrib;\n      action       %URI.datatype;           #REQUIRED\n      method       ( get | post )           'get'\n      enctype      %ContentType.datatype;   'application/x-www-form-urlencoded'\n      accept-charset %Charsets.datatype;    #IMPLIED\n      accept       %ContentTypes.datatype;  #IMPLIED\n>\n<!-- end of form.attlist -->]]>\n\n<!-- label: Form Field Label Text ...................... -->\n\n<!-- Each label must not contain more than ONE field\n-->\n\n<!ENTITY % label.element  \"INCLUDE\" >\n<![%label.element;[\n<!ENTITY % label.content\n     \"( #PCDATA\n      | %input.qname; | %select.qname; | %textarea.qname; | %button.qname;\n      | %InlStruct.class;\n      %InlPhras.class;\n      %I18n.class;\n      %InlPres.class;\n      %Anchor.class;\n      %InlSpecial.class;\n      %Inline.extra;\n      %Misc.class; )*\"\n>\n<!ELEMENT %label.qname;  %label.content; >\n<!-- end of label.element -->]]>\n\n<!ENTITY % label.attlist  \"INCLUDE\" >\n<![%label.attlist;[\n<!ATTLIST %label.qname;\n      %Common.attrib;\n      for          IDREF                    #IMPLIED\n      accesskey    %Character.datatype;     #IMPLIED\n>\n<!-- end of label.attlist -->]]>\n\n<!-- input: Form Control ............................... -->\n\n<!ENTITY % input.element  \"INCLUDE\" >\n<![%input.element;[\n<!ENTITY % input.content  \"EMPTY\" >\n<!ELEMENT %input.qname;  %input.content; >\n<!-- end of input.element -->]]>\n\n<!ENTITY % input.attlist  \"INCLUDE\" >\n<![%input.attlist;[\n<!ENTITY % InputType.class\n     \"( text | password | checkbox | radio | submit\n      | reset | file | hidden | image | button )\"\n>\n<!-- attribute 'name' required for all but submit & reset\n-->\n<!ATTLIST %input.qname;\n      %Common.attrib;\n      type         %InputType.class;        'text'\n      name         CDATA                    #IMPLIED\n      value        CDATA                    #IMPLIED\n      checked      ( checked )              #IMPLIED\n      disabled     ( disabled )             #IMPLIED\n      readonly     ( readonly )             #IMPLIED\n      size         %Number.datatype;        #IMPLIED\n      maxlength    %Number.datatype;        #IMPLIED\n      src          %URI.datatype;           #IMPLIED\n      alt          %Text.datatype;          #IMPLIED\n      tabindex     %Number.datatype;        #IMPLIED\n      accesskey    %Character.datatype;     #IMPLIED\n      accept       %ContentTypes.datatype;  #IMPLIED\n>\n<!-- end of input.attlist -->]]>\n\n<!-- select: Option Selector ........................... -->\n\n<!ENTITY % select.element  \"INCLUDE\" >\n<![%select.element;[\n<!ENTITY % select.content\n     \"( %optgroup.qname; | %option.qname; )+\"\n>\n<!ELEMENT %select.qname;  %select.content; >\n<!-- end of select.element -->]]>\n\n<!ENTITY % select.attlist  \"INCLUDE\" >\n<![%select.attlist;[\n<!ATTLIST %select.qname;\n      %Common.attrib;\n      name         CDATA                    #IMPLIED\n      size         %Number.datatype;        #IMPLIED\n      multiple     ( multiple )             #IMPLIED\n      disabled     ( disabled )             #IMPLIED\n      tabindex     %Number.datatype;        #IMPLIED\n>\n<!-- end of select.attlist -->]]>\n\n<!-- optgroup: Option Group ............................ -->\n\n<!ENTITY % optgroup.element  \"INCLUDE\" >\n<![%optgroup.element;[\n<!ENTITY % optgroup.content  \"( %option.qname; )+\" >\n<!ELEMENT %optgroup.qname;  %optgroup.content; >\n<!-- end of optgroup.element -->]]>\n\n<!ENTITY % optgroup.attlist  \"INCLUDE\" >\n<![%optgroup.attlist;[\n<!ATTLIST %optgroup.qname;\n      %Common.attrib;\n      disabled     ( disabled )             #IMPLIED\n      label        %Text.datatype;          #REQUIRED\n>\n<!-- end of optgroup.attlist -->]]>\n\n<!-- option: Selectable Choice ......................... -->\n\n<!ENTITY % option.element  \"INCLUDE\" >\n<![%option.element;[\n<!ENTITY % option.content  \"( #PCDATA )\" >\n<!ELEMENT %option.qname;  %option.content; >\n<!-- end of option.element -->]]>\n\n<!ENTITY % option.attlist  \"INCLUDE\" >\n<![%option.attlist;[\n<!ATTLIST %option.qname;\n      %Common.attrib;\n      selected     ( selected )             #IMPLIED\n      disabled     ( disabled )             #IMPLIED\n      label        %Text.datatype;          #IMPLIED\n      value        CDATA                    #IMPLIED\n>\n<!-- end of option.attlist -->]]>\n\n<!-- textarea: Multi-Line Text Field ................... -->\n\n<!ENTITY % textarea.element  \"INCLUDE\" >\n<![%textarea.element;[\n<!ENTITY % textarea.content  \"( #PCDATA )\" >\n<!ELEMENT %textarea.qname;  %textarea.content; >\n<!-- end of textarea.element -->]]>\n\n<!ENTITY % textarea.attlist  \"INCLUDE\" >\n<![%textarea.attlist;[\n<!ATTLIST %textarea.qname;\n      %Common.attrib;\n      name         CDATA                    #IMPLIED\n      rows         %Number.datatype;        #REQUIRED\n      cols         %Number.datatype;        #REQUIRED\n      disabled     ( disabled )             #IMPLIED\n      readonly     ( readonly )             #IMPLIED\n      tabindex     %Number.datatype;        #IMPLIED\n      accesskey    %Character.datatype;     #IMPLIED\n>\n<!-- end of textarea.attlist -->]]>\n\n<!-- fieldset: Form Control Group ...................... -->\n\n<!-- #PCDATA is to solve the mixed content problem,\n     per specification only whitespace is allowed\n-->\n\n<!ENTITY % fieldset.element  \"INCLUDE\" >\n<![%fieldset.element;[\n<!ENTITY % fieldset.content\n     \"( #PCDATA | %legend.qname; | %Flow.mix; )*\"\n>\n<!ELEMENT %fieldset.qname;  %fieldset.content; >\n<!-- end of fieldset.element -->]]>\n\n<!ENTITY % fieldset.attlist  \"INCLUDE\" >\n<![%fieldset.attlist;[\n<!ATTLIST %fieldset.qname;\n      %Common.attrib;\n>\n<!-- end of fieldset.attlist -->]]>\n\n<!-- legend: Fieldset Legend ........................... -->\n\n<!ENTITY % legend.element  \"INCLUDE\" >\n<![%legend.element;[\n<!ENTITY % legend.content\n     \"( #PCDATA | %Inline.mix; )*\"\n>\n<!ELEMENT %legend.qname;  %legend.content; >\n<!-- end of legend.element -->]]>\n\n<!ENTITY % legend.attlist  \"INCLUDE\" >\n<![%legend.attlist;[\n<!ATTLIST %legend.qname;\n      %Common.attrib;\n      accesskey    %Character.datatype;     #IMPLIED\n>\n<!-- end of legend.attlist -->]]>\n\n<!-- button: Push Button ............................... -->\n\n<!ENTITY % button.element  \"INCLUDE\" >\n<![%button.element;[\n<!ENTITY % button.content\n     \"( #PCDATA\n      | %BlkNoForm.mix;\n      | %InlStruct.class;\n      %InlPhras.class;\n      %InlPres.class;\n      %I18n.class;\n      %InlSpecial.class;\n      %Inline.extra; )*\"\n>\n<!ELEMENT %button.qname;  %button.content; >\n<!-- end of button.element -->]]>\n\n<!ENTITY % button.attlist  \"INCLUDE\" >\n<![%button.attlist;[\n<!ATTLIST %button.qname;\n      %Common.attrib;\n      name         CDATA                    #IMPLIED\n      value        CDATA                    #IMPLIED\n      type         ( button | submit | reset ) 'submit'\n      disabled     ( disabled )             #IMPLIED\n      tabindex     %Number.datatype;        #IMPLIED\n      accesskey    %Character.datatype;     #IMPLIED\n>\n<!-- end of button.attlist -->]]>\n\n<!-- end of xhtml-form-1.mod -->\n]]>\n\n<!-- Legacy Markup ............................................... -->\n<!ENTITY % xhtml-legacy.module \"IGNORE\" >\n<![%xhtml-legacy.module;[\n<!ENTITY % xhtml-legacy.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML Legacy Markup 1.0//EN\"\n            \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-legacy-1.mod\" >\n%xhtml-legacy.mod;]]>\n\n<!-- Document Structure Module (required)  ....................... -->\n<!ENTITY % xhtml-struct.module \"INCLUDE\" >\n<![%xhtml-struct.module;[\n<!ENTITY % xhtml-struct.mod\n     PUBLIC \"-//W3C//ELEMENTS XHTML Document Structure 1.0//EN\"\n            \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-struct-1.mod\" >\n<!-- ...................................................................... -->\n<!-- XHTML Structure Module  .............................................. -->\n<!-- file: xhtml-struct-1.mod\n\n     This is XHTML, a reformulation of HTML as a modular XML application.\n     Copyright 1998-2001 W3C (MIT, INRIA, Keio), All Rights Reserved.\n     Revision: $Id: xhtml-struct-1.mod,v 4.0 2001/04/02 22:42:49 altheim Exp $ SMI\n\n     This DTD module is identified by the PUBLIC and SYSTEM identifiers:\n\n       PUBLIC \"-//W3C//ELEMENTS XHTML Document Structure 1.0//EN\"\n       SYSTEM \"http://www.w3.org/TR/xhtml-modularization/DTD/xhtml-struct-1.mod\"\n\n     Revisions:\n     (none)\n     ....................................................................... -->\n\n<!-- Document Structure\n\n        title, head, body, html\n\n     The Structure Module defines the major structural elements and\n     their attributes.\n\n     Note that the content model of the head element type is redeclared\n     when the Base Module is included in the DTD.\n\n     The parameter entity containing the XML namespace URI value used\n     for XHTML is '%XHTML.xmlns;', defined in the Qualified Names module.\n-->\n\n<!-- title: Document Title ............................. -->\n\n<!-- The title element is not considered part of the flow of text.\n     It should be displayed, for example as the page header or\n     window title. Exactly one title is required per document.\n-->\n\n<!ENTITY % title.element  \"INCLUDE\" >\n<![%title.element;[\n<!ENTITY % title.content  \"( #PCDATA )\" >\n<!ENTITY % title.qname  \"title\" >\n<!ELEMENT %title.qname;  %title.content; >\n<!-- end of title.element -->]]>\n\n<!ENTITY % title.attlist  \"INCLUDE\" >\n<![%title.attlist;[\n<!ATTLIST %title.qname;\n      %XHTML.xmlns.attrib;\n      %I18n.attrib;\n>\n<!-- end of title.attlist -->]]>\n\n<!-- head: Document Head ............................... -->\n\n<!ENTITY % head.element  \"INCLUDE\" >\n<![%head.element;[\n<!ENTITY % head.content\n    \"( %HeadOpts.mix;, %title.qname;, %HeadOpts.mix; )\"\n>\n<!ENTITY % head.qname  \"head\" >\n<!ELEMENT %head.qname;  %head.content; >\n<!-- end of head.element -->]]>\n\n<!ENTITY % head.attlist  \"INCLUDE\" >\n<![%head.attlist;[\n<!-- reserved for future use with document profiles\n-->\n<!ENTITY % profile.attrib\n     \"profile      %URI.datatype;           '%XHTML.profile;'\"\n>\n\n<!ATTLIST %head.qname;\n      %XHTML.xmlns.attrib;\n      %I18n.attrib;\n      %profile.attrib;\n>\n<!-- end of head.attlist -->]]>\n\n<!-- body: Document Body ............................... -->\n\n<!ENTITY % body.element  \"INCLUDE\" >\n<![%body.element;[\n<!ENTITY % body.content\n     \"( %Block.mix; )+\"\n>\n<!ENTITY % body.qname  \"body\" >\n<!ELEMENT %body.qname;  %body.content; >\n<!-- end of body.element -->]]>\n\n<!ENTITY % body.attlist  \"INCLUDE\" >\n<![%body.attlist;[\n<!ATTLIST %body.qname;\n      %Common.attrib;\n>\n<!-- end of body.attlist -->]]>\n\n<!-- html: XHTML Document Element ...................... -->\n\n<!ENTITY % html.element  \"INCLUDE\" >\n<![%html.element;[\n<!ENTITY % html.content  \"( %head.qname;, %body.qname; )\" >\n<!ENTITY % html.qname  \"html\" >\n<!ELEMENT %html.qname;  %html.content; >\n<!-- end of html.element -->]]>\n\n<!ENTITY % html.attlist  \"INCLUDE\" >\n<![%html.attlist;[\n<!-- version attribute value defined in driver\n-->\n<!ENTITY % XHTML.version.attrib\n     \"version      %FPI.datatype;           #FIXED '%XHTML.version;'\"\n>\n\n<!-- see the Qualified Names module for information\n     on how to extend XHTML using XML namespaces\n-->\n<!ATTLIST %html.qname;\n      %XHTML.xmlns.attrib;\n      %XHTML.version.attrib;\n      %I18n.attrib;\n>\n<!-- end of html.attlist -->]]>\n\n<!-- end of xhtml-struct-1.mod -->\n]]>\n\n<!-- end of XHTML 1.1 DTD  ................................................. -->\n<!-- ....................................................................... -->\n"
  },
  {
    "path": "test/System.Web.Helpers.Test/WebCacheTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Helpers.Test\n{\n    public class WebCacheTest\n    {\n        [Fact]\n        public void GetReturnsExpectedValueTest()\n        {\n            string key = DateTime.UtcNow.Ticks.ToString() + \"_GetTest\";\n            List<string> expected = new List<string>();\n            WebCache.Set(key, expected);\n\n            var actual = WebCache.Get(key);\n\n            Assert.Equal(expected, actual);\n            Assert.Equal(0, actual.Count);\n        }\n\n        [Fact]\n        public void RemoveRemovesRightValueTest()\n        {\n            string key = DateTime.UtcNow.Ticks.ToString() + \"_RemoveTest\";\n            List<string> expected = new List<string>();\n            WebCache.Set(key, expected);\n\n            var actual = WebCache.Remove(key);\n\n            Assert.Equal(expected, actual);\n            Assert.Equal(0, actual.Count);\n        }\n\n        [Fact]\n        public void RemoveRemovesValueFromCacheTest()\n        {\n            string key = DateTime.UtcNow.Ticks.ToString() + \"_RemoveTest2\";\n            List<string> expected = new List<string>();\n            WebCache.Set(key, expected);\n\n            var removed = WebCache.Remove(key);\n\n            Assert.Null(WebCache.Get(key));\n        }\n\n        [Fact]\n        public void SetWithAbsoluteExpirationDoesNotThrow()\n        {\n            string key = DateTime.UtcNow.Ticks.ToString() + \"SetWithAbsoluteExpirationDoesNotThrow_SetTest\";\n            object expected = new object();\n            int minutesToCache = 10;\n            bool slidingExpiration = false;\n            WebCache.Set(key, expected, minutesToCache, slidingExpiration);\n            object actual = WebCache.Get(key);\n            Assert.True(expected == actual);\n        }\n\n        [Fact]\n        public void CanSetWithSlidingExpiration()\n        {\n            string key = DateTime.UtcNow.Ticks.ToString() + \"_CanSetWithSlidingExpiration_SetTest\";\n            object expected = new object();\n\n            WebCache.Set(key, expected, slidingExpiration: true);\n            object actual = WebCache.Get(key);\n            Assert.True(expected == actual);\n        }\n\n        [Fact]\n        public void SetWithSlidingExpirationForNegativeTime()\n        {\n            string key = DateTime.UtcNow.Ticks.ToString() + \"_SetWithSlidingExpirationForNegativeTime_SetTest\";\n            object expected = new object();\n            Assert.ThrowsArgumentGreaterThan(() => WebCache.Set(key, expected, -1), \"minutesToCache\", \"0\");\n        }\n\n        [Fact]\n        public void SetWithSlidingExpirationForZeroTime()\n        {\n            string key = DateTime.UtcNow.Ticks.ToString() + \"_SetWithSlidingExpirationForZeroTime_SetTest\";\n            object expected = new object();\n            Assert.ThrowsArgumentGreaterThan(() => WebCache.Set(key, expected, 0), \"minutesToCache\", \"0\");\n        }\n\n        [Fact]\n        public void SetWithSlidingExpirationForYear()\n        {\n            string key = DateTime.UtcNow.Ticks.ToString() + \"_SetWithSlidingExpirationForYear_SetTest\";\n            object expected = new object();\n\n            WebCache.Set(key, expected, 365 * 24 * 60, true);\n            object actual = WebCache.Get(key);\n            Assert.True(expected == actual);\n        }\n\n        [Fact]\n        public void SetWithSlidingExpirationForMoreThanYear()\n        {\n            string key = DateTime.UtcNow.Ticks.ToString() + \"_SetWithSlidingExpirationForMoreThanYear_SetTest\";\n            object expected = new object();\n            Assert.ThrowsArgumentLessThanOrEqualTo(() => WebCache.Set(key, expected, (365 * 24 * 60) + 1, true), \"minutesToCache\", (365 * 24 * 60).ToString());\n        }\n\n        [Fact]\n        public void SetWithAbsoluteExpirationForMoreThanYear()\n        {\n            string key = DateTime.UtcNow.Ticks.ToString() + \"_SetWithAbsoluteExpirationForMoreThanYear_SetTest\";\n            object expected = new object();\n\n            WebCache.Set(key, expected, 365 * 24 * 60, true);\n            object actual = WebCache.Get(key);\n            Assert.True(expected == actual);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Helpers.Test/WebGridDataSourceTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Dynamic;\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Helpers.Test\n{\n    public class WebGridDataSourceTest\n    {\n        [Fact]\n        public void WebGridDataSourceReturnsNumberOfItemsAsTotalRowCount()\n        {\n            // Arrange\n            var rows = GetValues();\n            var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: GetValues(), elementType: typeof(Person), canPage: false, canSort: false);\n\n            // Act and Assert\n            Assert.Equal(rows.Count(), dataSource.TotalRowCount);\n        }\n\n        [Fact]\n        public void WebGridDataSourceReturnsUnsortedListIfSortColumnIsNull()\n        {\n            // Arrange\n            var values = GetValues();\n            var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: GetValues(), elementType: typeof(Person), canPage: false, canSort: true);\n\n            // Act \n            var rows = dataSource.GetRows(new SortInfo { SortColumn = null }, 0);\n\n            // Assert\n            Assert.True(Enumerable.SequenceEqual<object>(values.ToList(), rows.Select(r => r.Value).ToList(), new PersonComparer()));\n        }\n\n        [Fact]\n        public void WebGridDataSourceReturnsUnsortedListIfSortColumnIsEmpty()\n        {\n            // Arrange\n            var values = GetValues();\n            var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: GetValues(), elementType: typeof(Person), canPage: false, canSort: true);\n\n            // Act \n            var rows = dataSource.GetRows(new SortInfo { SortColumn = String.Empty }, 0);\n\n            // Assert\n            Assert.True(Enumerable.SequenceEqual<object>(values.ToList(), rows.Select(r => r.Value).ToList(), new PersonComparer()));\n        }\n\n        [Fact]\n        public void WebGridDataSourceReturnsUnsortedListIfSortCannotBeInferred()\n        {\n            // Arrange\n            var values = GetValues();\n            var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: GetValues(), elementType: typeof(Person), canPage: false, canSort: true);\n\n            // Act \n            var rows = dataSource.GetRows(new SortInfo { SortColumn = \"Does-not-exist\" }, 0);\n\n            // Assert\n            Assert.True(Enumerable.SequenceEqual<object>(values.ToList(), rows.Select(r => r.Value).ToList(), new PersonComparer()));\n        }\n\n        [Fact]\n        public void WebGridDataSourceReturnsUnsortedListIfDefaultSortCannotBeInferred()\n        {\n            // Arrange\n            var values = GetValues();\n            var defaultSort = new SortInfo { SortColumn = \"cannot-be-inferred\" };\n            var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: GetValues(), elementType: typeof(Person), canSort: true, canPage: false) { DefaultSort = defaultSort };\n\n            // Act \n            var rows = dataSource.GetRows(new SortInfo { SortColumn = \"Does-not-exist\" }, 0);\n\n            // Assert\n            Assert.True(Enumerable.SequenceEqual<object>(values.ToList(), rows.Select(r => r.Value).ToList(), new PersonComparer()));\n        }\n\n        [Fact]\n        public void WebGridDataSourceUsesDefaultSortWhenCurrentSortCannotBeInferred()\n        {\n            // Arrange\n            var values = GetValues();\n            var defaultSort = new SortInfo { SortColumn = \"FirstName\" };\n            var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: GetValues(), elementType: typeof(Person), canSort: true, canPage: false) { DefaultSort = defaultSort };\n\n            // Act \n            var rows = dataSource.GetRows(new SortInfo { SortColumn = \"Does-not-exist\" }, 0);\n\n            // Assert\n            Assert.True(Enumerable.SequenceEqual<object>(values.OrderBy(p => p.FirstName).ToList(), rows.Select(r => r.Value).ToList(), new PersonComparer()));\n        }\n\n        [Fact]\n        public void WebGridDataSourceSortsUsingSpecifiedSort()\n        {\n            // Arrange\n            var defaultSort = new SortInfo { SortColumn = \"FirstName\", SortDirection = SortDirection.Ascending };\n            IEnumerable<dynamic> values = new[] { new Person { LastName = \"Z\" }, new Person { LastName = \"X\" }, new Person { LastName = \"Y\" } };\n            var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: values, elementType: typeof(Person), canSort: true, canPage: false) { DefaultSort = defaultSort };\n\n            // Act \n            var rows = dataSource.GetRows(new SortInfo { SortColumn = \"LastName\" }, 0);\n\n            // Assert\n            Assert.Equal(rows.ElementAt(0).Value.LastName, \"X\");\n            Assert.Equal(rows.ElementAt(1).Value.LastName, \"Y\");\n            Assert.Equal(rows.ElementAt(2).Value.LastName, \"Z\");\n        }\n\n        [Fact]\n        public void WebGridDataSourceSortsDynamicType()\n        {\n            // Arrange\n            IEnumerable<dynamic> values = new[] { new TestDynamicType(\"col\", \"val1\"), new TestDynamicType(\"col\", \"val2\"), new TestDynamicType(\"col\", \"val3\") };\n            var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: values, elementType: typeof(TestDynamicType), canSort: true, canPage: false);\n\n            // Act \n            var rows = dataSource.GetRows(new SortInfo { SortColumn = \"col\", SortDirection = SortDirection.Descending }, 0);\n\n            // Assert\n            Assert.Equal(rows.ElementAt(0).Value.col, \"val3\");\n            Assert.Equal(rows.ElementAt(1).Value.col, \"val2\");\n            Assert.Equal(rows.ElementAt(2).Value.col, \"val1\");\n        }\n\n        [Fact]\n        public void WebGridDataSourceWithNestedPropertySortsCorrectly()\n        {\n            // Arrange\n            var element1 = new { Foo = new { Bar = \"val2\" } };\n            var element2 = new { Foo = new { Bar = \"val1\" } };\n            var element3 = new { Foo = new { Bar = \"val3\" } };\n            IEnumerable<dynamic> values = new[] { element1, element2, element3 };\n\n            var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: values, elementType: element1.GetType(), canSort: true, canPage: false);\n\n            // Act \n            var rows = dataSource.GetRows(new SortInfo { SortColumn = \"Foo.Bar\", SortDirection = SortDirection.Descending }, 0);\n\n            // Assert\n            Assert.Equal(rows.ElementAt(0).Value.Foo.Bar, \"val3\");\n            Assert.Equal(rows.ElementAt(1).Value.Foo.Bar, \"val2\");\n            Assert.Equal(rows.ElementAt(2).Value.Foo.Bar, \"val1\");\n        }\n\n        [Fact]\n        public void WebGridDataSourceSortsDictionaryBasedDynamicType()\n        {\n            // Arrange\n            var value1 = new DynamicDictionary();\n            value1[\"col\"] = \"val1\";\n            var value2 = new DynamicDictionary();\n            value2[\"col\"] = \"val2\";\n            var value3 = new DynamicDictionary();\n            value3[\"col\"] = \"val3\";\n            IEnumerable<dynamic> values = new[] { value1, value2, value3 };\n            var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: values, elementType: typeof(TestDynamicType), canSort: true, canPage: false);\n\n            // Act \n            var rows = dataSource.GetRows(new SortInfo { SortColumn = \"col\", SortDirection = SortDirection.Descending }, 0);\n\n            // Assert\n            Assert.Equal(rows.ElementAt(0).Value.col, \"val3\");\n            Assert.Equal(rows.ElementAt(1).Value.col, \"val2\");\n            Assert.Equal(rows.ElementAt(2).Value.col, \"val1\");\n        }\n\n        [Fact]\n        public void WebGridDataSourceReturnsOriginalDataSourceIfValuesCannotBeSorted()\n        {\n            // Arrange\n            IEnumerable<dynamic> values = new object[] { new TestDynamicType(\"col\", \"val1\"), new TestDynamicType(\"col\", \"val2\"), new TestDynamicType(\"col\", DBNull.Value) };\n            var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: values, elementType: typeof(TestDynamicType), canSort: true, canPage: false);\n\n            // Act \n            var rows = dataSource.GetRows(new SortInfo { SortColumn = \"col\", SortDirection = SortDirection.Descending }, 0);\n\n            // Assert\n            Assert.Equal(rows.ElementAt(0).Value.col, \"val1\");\n            Assert.Equal(rows.ElementAt(1).Value.col, \"val2\");\n            Assert.Equal(rows.ElementAt(2).Value.col, DBNull.Value);\n        }\n\n        [Fact]\n        public void WebGridDataSourceReturnsPagedResultsIfRowsPerPageIsSpecified()\n        {\n            // Arrange\n            IEnumerable<dynamic> values = GetValues();\n            var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: values, elementType: typeof(Person), canSort: false, canPage: true) { RowsPerPage = 2 };\n\n            // Act \n            var rows = dataSource.GetRows(new SortInfo(), 0);\n\n            // Assert\n            Assert.Equal(2, rows.Count);\n            Assert.Equal(rows.ElementAt(0).Value.LastName, \"B2\");\n            Assert.Equal(rows.ElementAt(1).Value.LastName, \"A2\");\n        }\n\n        [Fact]\n        public void WebGridDataSourceReturnsPagedSortedResultsIfRowsPerPageAndSortAreSpecified()\n        {\n            // Arrange\n            IEnumerable<dynamic> values = GetValues();\n            var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: values, elementType: typeof(Person), canSort: true, canPage: true) { RowsPerPage = 2 };\n\n            // Act \n            var rows = dataSource.GetRows(new SortInfo { SortColumn = \"LastName\", SortDirection = SortDirection.Descending }, 0);\n\n            // Assert\n            Assert.Equal(2, rows.Count);\n            Assert.Equal(rows.ElementAt(0).Value.LastName, \"E2\");\n            Assert.Equal(rows.ElementAt(1).Value.LastName, \"D2\");\n        }\n\n        [Fact]\n        public void WebGridDataSourceReturnsFewerThanRowsPerPageIfNumberOfItemsIsInsufficient()\n        {\n            // Arrange\n            IEnumerable<dynamic> values = GetValues();\n            var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: values, elementType: typeof(Person), canSort: true, canPage: true) { RowsPerPage = 3 };\n\n            // Act \n            var rows = dataSource.GetRows(new SortInfo(), 1);\n\n            // Assert\n            Assert.Equal(2, rows.Count);\n            Assert.Equal(rows.ElementAt(0).Value.LastName, \"C2\");\n            Assert.Equal(rows.ElementAt(1).Value.LastName, \"E2\");\n        }\n\n        [Fact]\n        public void WebGridDataSourceDoesNotThrowIfValuesAreNull()\n        {\n            // Arrange\n            IEnumerable<dynamic> values = new object[] { String.Empty, null, DBNull.Value, null };\n            var dataSource = new WebGridDataSource(new WebGrid(GetContext()), values: values, elementType: typeof(object), canSort: true, canPage: true) { RowsPerPage = 2 };\n\n            // Act \n            var rows = dataSource.GetRows(new SortInfo(), 0);\n\n            // Assert\n            Assert.Equal(2, rows.Count);\n            Assert.Equal(rows.ElementAt(0).Value, String.Empty);\n            Assert.Null(rows.ElementAt(1).Value);\n        }\n\n        private IEnumerable<Person> GetValues()\n        {\n            return new[]\n            {\n                new Person { FirstName = \"B1\", LastName = \"B2\" },\n                new Person { FirstName = \"A1\", LastName = \"A2\" },\n                new Person { FirstName = \"D1\", LastName = \"D2\" },\n                new Person { FirstName = \"C1\", LastName = \"C2\" },\n                new Person { FirstName = \"E1\", LastName = \"E2\" },\n            };\n        }\n\n        private class PersonComparer : IEqualityComparer<object>\n        {\n            public new bool Equals(object x, object y)\n            {\n                dynamic xDynamic = x;\n                dynamic yDynamic = y;\n                return (String.Equals(xDynamic.FirstName, yDynamic.FirstName, StringComparison.OrdinalIgnoreCase)\n                        && String.Equals(xDynamic.LastName, yDynamic.LastName, StringComparison.OrdinalIgnoreCase));\n            }\n\n            public int GetHashCode(dynamic obj)\n            {\n                return 4; // Random dice roll\n            }\n        }\n\n        private class TestDynamicType : DynamicObject\n        {\n            public Dictionary<string, object> _values = new Dictionary<string, object>();\n\n            public TestDynamicType(string a, object b)\n            {\n                _values[a] = b;\n            }\n\n            public override bool TryGetMember(GetMemberBinder binder, out object result)\n            {\n                return _values.TryGetValue(binder.Name, out result);\n            }\n        }\n\n        private class Person\n        {\n            public string FirstName { get; set; }\n\n            public string LastName { get; set; }\n        }\n\n        private HttpContextBase GetContext()\n        {\n            return new Mock<HttpContextBase>().Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Helpers.Test/WebGridTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Dynamic;\nusing System.Linq;\nusing System.Text;\nusing System.Web.TestUtil;\nusing System.Web.WebPages;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Helpers.Test\n{\n    public class WebGridTest\n    {\n        [Fact]\n        public void AjaxCheckedOnlyOnce()\n        {\n            var grid = new WebGrid(GetContext(), ajaxUpdateContainerId: \"grid\")\n                .Bind(new[] { new { First = \"First\", Second = \"Second\" } });\n            string html = grid.Table().ToString();\n            Assert.Contains(\"<script\", html);\n            html = grid.Table().ToString();\n            Assert.DoesNotContain(\"<script\", html);\n            html = grid.Pager().ToString();\n            Assert.DoesNotContain(\"<script\", html);\n        }\n\n        [Fact]\n        public void AjaxCallbackIgnoredIfAjaxUpdateContainerIdIsNotSet()\n        {\n            var grid = new WebGrid(GetContext(), ajaxUpdateCallback: \"myCallback\")\n                .Bind(new[] { new { First = \"First\", Second = \"Second\" } });\n            string html = grid.Table().ToString();\n            Assert.DoesNotContain(\"<script\", html);\n            Assert.DoesNotContain(\"myCallback\", html);\n        }\n\n        [Fact]\n        public void ColumnNameDefaultsExcludesIndexedProperties()\n        {\n            var grid = new WebGrid(GetContext()).Bind(new[] { \"First\", \"Second\" });\n            Assert.Single(grid.ColumnNames);\n            Assert.Contains(\"Length\", grid.ColumnNames);\n        }\n\n        [Fact]\n        public void ColumnNameDefaultsForDynamics()\n        {\n            var grid = new WebGrid(GetContext()).Bind(Dynamics(new { First = \"First\", Second = \"Second\" }));\n            Assert.Equal(2, grid.ColumnNames.Count());\n            Assert.Contains(\"First\", grid.ColumnNames);\n            Assert.Contains(\"Second\", grid.ColumnNames);\n        }\n\n        [Fact]\n        public void ColumnNameDefaultsForNonDynamics()\n        {\n            var grid = new WebGrid(GetContext()).Bind(new[] { new { First = \"First\", Second = \"Second\" } });\n            Assert.Equal(2, grid.ColumnNames.Count());\n            Assert.Contains(\"First\", grid.ColumnNames);\n            Assert.Contains(\"Second\", grid.ColumnNames);\n        }\n\n        [Fact]\n        public void ColumnNameDefaultsSupportsBindableTypes()\n        {\n            var grid = new WebGrid(GetContext()).Bind(new[]\n            {\n                new\n                {\n                    DateTime = DateTime.MinValue,\n                    DateTimeOffset = DateTimeOffset.MinValue,\n                    Decimal = Decimal.MinValue,\n                    Guid = Guid.Empty,\n                    Int32 = 1,\n                    NullableInt32 = (int?)1,\n                    Object = new object(),\n                    Projection = new { Foo = \"Bar\" },\n                    TimeSpan = TimeSpan.MinValue\n                }\n            });\n            Assert.Equal(7, grid.ColumnNames.Count());\n            Assert.Contains(\"DateTime\", grid.ColumnNames);\n            Assert.Contains(\"DateTimeOffset\", grid.ColumnNames);\n            Assert.Contains(\"Decimal\", grid.ColumnNames);\n            Assert.Contains(\"Guid\", grid.ColumnNames);\n            Assert.Contains(\"Int32\", grid.ColumnNames);\n            Assert.Contains(\"NullableInt32\", grid.ColumnNames);\n            Assert.Contains(\"TimeSpan\", grid.ColumnNames);\n            Assert.DoesNotContain(\"Object\", grid.ColumnNames);\n            Assert.DoesNotContain(\"Projection\", grid.ColumnNames);\n        }\n\n        [Fact]\n        public void ColumnsIsNoOp()\n        {\n            var grid = new WebGrid(GetContext()).Bind(new[]\n            {\n                new { First = \"First\", Second = \"Second\" }\n            });\n            var columns = new[]\n            {\n                grid.Column(\"First\"), grid.Column(\"Second\")\n            };\n            Assert.Equal(columns, grid.Columns(columns));\n        }\n\n        [Fact]\n        public void ColumnThrowsIfColumnNameIsEmptyAndNoFormat()\n        {\n            var grid = new WebGrid(GetContext()).Bind(new object[0]);\n            Assert.ThrowsArgument(() => { grid.Column(columnName: String.Empty, format: null); }, \"columnName\", \"The column name cannot be null or an empty string unless a custom format is specified.\");\n        }\n\n        [Fact]\n        public void ColumnThrowsIfColumnNameIsNullAndNoFormat()\n        {\n            var grid = new WebGrid(GetContext()).Bind(new object[0]);\n            Assert.ThrowsArgument(() => { grid.Column(columnName: null, format: null); }, \"columnName\", \"The column name cannot be null or an empty string unless a custom format is specified.\");\n        }\n\n        [Fact]\n        public void BindThrowsIfSourceIsNull()\n        {\n            Assert.ThrowsArgumentNull(() => { new WebGrid(GetContext()).Bind(null); }, \"source\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfRowsPerPageIsLessThanOne()\n        {\n            Assert.ThrowsArgumentOutOfRange(() => { new WebGrid(GetContext(), rowsPerPage: 0); }, \"rowsPerPage\", \"Value must be greater than or equal to 1.\", allowDerivedExceptions: true);\n        }\n\n        [Fact]\n        public void GetHtmlDefaults()\n        {\n            var grid = new WebGrid(GetContext(), rowsPerPage: 1)\n                .Bind(new[]\n                {\n                    new { P1 = 1, P2 = '2', P3 = \"3\" },\n                    new { P1 = 4, P2 = '5', P3 = \"6\" }\n                });\n            var html = grid.GetHtml();\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(\n                \"<table><thead><tr>\" +\n                \"<th scope=\\\"col\\\"><a href=\\\"?sort=P1&amp;sortdir=ASC\\\">P1</a></th>\" +\n                \"<th scope=\\\"col\\\"><a href=\\\"?sort=P2&amp;sortdir=ASC\\\">P2</a></th>\" +\n                \"<th scope=\\\"col\\\"><a href=\\\"?sort=P3&amp;sortdir=ASC\\\">P3</a></th>\" +\n                \"</tr></thead>\" +\n                \"<tfoot><tr>\" +\n                \"<td colspan=\\\"3\\\">1 <a href=\\\"?page=2\\\">2</a> <a href=\\\"?page=2\\\">&gt;</a> </td>\" +\n                \"</tr></tfoot>\" +\n                \"<tbody><tr><td>1</td><td>2</td><td>3</td></tr></tbody>\" +\n                \"</table>\", html.ToString());\n            XhtmlAssert.Validate1_1(html);\n        }\n\n        [Fact]\n        public void WebGridProducesValidHtmlWhenSummaryIsSpecified()\n        {\n            var grid = new WebGrid(GetContext(), rowsPerPage: 1)\n                .Bind(new[]\n                {\n                    new { P1 = 1, P2 = '2', P3 = \"3\" },\n                    new { P1 = 4, P2 = '5', P3 = \"6\" }\n                });\n            var caption = \"WebGrid With Caption\";\n            var html = grid.GetHtml(caption: caption);\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(\n                \"<table>\" +\n                \"<caption>\" + caption + \"</caption>\" +\n                \"<thead><tr>\" +\n                \"<th scope=\\\"col\\\"><a href=\\\"?sort=P1&amp;sortdir=ASC\\\">P1</a></th>\" +\n                \"<th scope=\\\"col\\\"><a href=\\\"?sort=P2&amp;sortdir=ASC\\\">P2</a></th>\" +\n                \"<th scope=\\\"col\\\"><a href=\\\"?sort=P3&amp;sortdir=ASC\\\">P3</a></th>\" +\n                \"</tr></thead>\" +\n                \"<tfoot><tr>\" +\n                \"<td colspan=\\\"3\\\">1 <a href=\\\"?page=2\\\">2</a> <a href=\\\"?page=2\\\">&gt;</a> </td>\" +\n                \"</tr></tfoot>\" +\n                \"<tbody><tr><td>1</td><td>2</td><td>3</td></tr></tbody>\" +\n                \"</table>\", html.ToString());\n            XhtmlAssert.Validate1_1(html);\n        }\n\n        [Fact]\n        public void WebGridEncodesCaptionText()\n        {\n            var grid = new WebGrid(GetContext(), rowsPerPage: 1)\n                .Bind(new[]\n                {\n                    new { P1 = 1, P2 = '2', P3 = \"3\" },\n                    new { P1 = 4, P2 = '5', P3 = \"6\" }\n                });\n            var caption = \"WebGrid <> With Caption\";\n            var html = grid.GetHtml(caption: caption);\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(\n                \"<table>\" +\n                \"<caption>WebGrid &lt;&gt; With Caption</caption>\" +\n                \"<thead><tr>\" +\n                \"<th scope=\\\"col\\\"><a href=\\\"?sort=P1&amp;sortdir=ASC\\\">P1</a></th>\" +\n                \"<th scope=\\\"col\\\"><a href=\\\"?sort=P2&amp;sortdir=ASC\\\">P2</a></th>\" +\n                \"<th scope=\\\"col\\\"><a href=\\\"?sort=P3&amp;sortdir=ASC\\\">P3</a></th>\" +\n                \"</tr></thead>\" +\n                \"<tfoot><tr>\" +\n                \"<td colspan=\\\"3\\\">1 <a href=\\\"?page=2\\\">2</a> <a href=\\\"?page=2\\\">&gt;</a> </td>\" +\n                \"</tr></tfoot>\" +\n                \"<tbody><tr><td>1</td><td>2</td><td>3</td></tr></tbody>\" +\n                \"</table>\", html.ToString());\n            XhtmlAssert.Validate1_1(html);\n        }\n\n        [Fact]\n        public void GetHtmlWhenPageCountIsOne()\n        {\n            var grid = new WebGrid(GetContext())\n                .Bind(new[]\n                {\n                    new { P1 = 1, P2 = '2', P3 = \"3\" }\n                });\n            var html = grid.GetHtml();\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(\n                \"<table><thead><tr>\" +\n                \"<th scope=\\\"col\\\"><a href=\\\"?sort=P1&amp;sortdir=ASC\\\">P1</a></th>\" +\n                \"<th scope=\\\"col\\\"><a href=\\\"?sort=P2&amp;sortdir=ASC\\\">P2</a></th>\" +\n                \"<th scope=\\\"col\\\"><a href=\\\"?sort=P3&amp;sortdir=ASC\\\">P3</a></th>\" +\n                \"</tr></thead>\" +\n                \"<tbody><tr><td>1</td><td>2</td><td>3</td></tr></tbody>\" +\n                \"</table>\", html.ToString());\n            XhtmlAssert.Validate1_1(html);\n        }\n\n        [Fact]\n        public void GetHtmlWhenPagingAndSortingAreDisabled()\n        {\n            var grid = new WebGrid(GetContext(), rowsPerPage: 1, canPage: false, canSort: false)\n                .Bind(new[]\n                {\n                    new { P1 = 1, P2 = '2', P3 = \"3\" },\n                    new { P1 = 4, P2 = '5', P3 = \"6\" }\n                });\n            var html = grid.GetHtml();\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(\n                \"<table><thead><tr>\" +\n                \"<th scope=\\\"col\\\">P1</th>\" +\n                \"<th scope=\\\"col\\\">P2</th>\" +\n                \"<th scope=\\\"col\\\">P3</th>\" +\n                \"</tr></thead>\" +\n                \"<tbody>\" +\n                \"<tr><td>1</td><td>2</td><td>3</td></tr>\" +\n                \"<tr><td>4</td><td>5</td><td>6</td></tr>\" +\n                \"</tbody>\" +\n                \"</table>\", html.ToString());\n            XhtmlAssert.Validate1_1(html);\n        }\n\n        [Fact]\n        public void PageIndexCanBeReset()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"page\"] = \"2\";\n            var grid = new WebGrid(GetContext(queryString), rowsPerPage: 1)\n                .Bind(new[]\n                {\n                    new { P1 = 1, P2 = '2', P3 = \"3\" },\n                    new { P1 = 4, P2 = '5', P3 = \"6\" }\n                });\n            Assert.Equal(1, grid.PageIndex);\n            grid.PageIndex = 0;\n            Assert.Equal(0, grid.PageIndex);\n            // verify that selection link has updated page\n            Assert.Equal(\"?page=1&row=1\", grid.Rows.FirstOrDefault().GetSelectUrl());\n        }\n\n        [Fact]\n        public void PageIndexCanBeResetToSameValue()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"page\"] = \"2\";\n            var grid = new WebGrid(GetContext(queryString), rowsPerPage: 1)\n                .Bind(new[]\n                {\n                    new { P1 = 1, P2 = '2', P3 = \"3\" },\n                    new { P1 = 4, P2 = '5', P3 = \"6\" }\n                });\n            grid.PageIndex = 0;\n            Assert.Equal(0, grid.PageIndex);\n        }\n\n        [Fact]\n        public void PageIndexDefaultsToZero()\n        {\n            var grid = new WebGrid(GetContext(), rowsPerPage: 1)\n                .Bind(new[]\n                {\n                    new { P1 = 1, P2 = '2', P3 = \"3\" },\n                    new { P1 = 4, P2 = '5', P3 = \"6\" }\n                });\n            Assert.Equal(0, grid.PageIndex);\n            Assert.Equal(1, grid.Rows.Count);\n            Assert.Equal(1, grid.Rows.First()[\"P1\"]);\n        }\n\n        [Fact]\n        public void SetPageIndexThrowsExceptionWhenValueIsNegative()\n        {\n            var grid = new WebGrid(GetContext(), rowsPerPage: 1)\n                .Bind(new[]\n                {\n                    new { P1 = 1, P2 = '2', P3 = \"3\" },\n                    new { P1 = 4, P2 = '5', P3 = \"6\" }\n                });\n            Assert.ThrowsArgumentOutOfRange(() => { grid.PageIndex = -1; }, \"value\", \"Value must be between 0 and 1.\");\n        }\n\n        [Fact]\n        public void SetPageIndexThrowsExceptionWhenValueIsEqualToPageCount()\n        {\n            var grid = new WebGrid(GetContext(), rowsPerPage: 1)\n                .Bind(new[]\n                {\n                    new { P1 = 1, P2 = '2', P3 = \"3\" },\n                    new { P1 = 4, P2 = '5', P3 = \"6\" }\n                });\n            Assert.ThrowsArgumentOutOfRange(() => { grid.PageIndex = grid.PageCount; }, \"value\", \"Value must be between 0 and 1.\");\n        }\n\n        [Fact]\n        public void SetPageIndexThrowsExceptionWhenValueIsGreaterToPageCount()\n        {\n            var grid = new WebGrid(GetContext(), rowsPerPage: 1)\n                .Bind(new[]\n                {\n                    new { P1 = 1, P2 = '2', P3 = \"3\" },\n                    new { P1 = 4, P2 = '5', P3 = \"6\" }\n                });\n            Assert.ThrowsArgumentOutOfRange(() => { grid.PageIndex = grid.PageCount + 1; }, \"value\", \"Value must be between 0 and 1.\");\n        }\n\n        [Fact]\n        public void SetPageIndexThrowsExceptionWhenPagingIsDisabled()\n        {\n            var grid = new WebGrid(GetContext(), canPage: false)\n                .Bind(new[]\n                {\n                    new { P1 = 1, P2 = '2', P3 = \"3\" },\n                    new { P1 = 4, P2 = '5', P3 = \"6\" }\n                });\n            Assert.Throws<NotSupportedException>(() => { grid.PageIndex = 1; }, \"This operation is not supported when paging is disabled for the \\\"WebGrid\\\" object.\");\n        }\n\n        [Fact]\n        public void PageIndexResetsToLastPageWhenQueryStringValueGreaterThanPageCount()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"page\"] = \"3\";\n            var grid = new WebGrid(GetContext(queryString), rowsPerPage: 1)\n                .Bind(new[]\n                {\n                    new { P1 = 1, P2 = '2', P3 = \"3\" },\n                    new { P1 = 4, P2 = '5', P3 = \"6\" }\n                });\n            Assert.Equal(1, grid.PageIndex);\n            Assert.Equal(1, grid.Rows.Count);\n            Assert.Equal(4, grid.Rows.First()[\"P1\"]);\n        }\n\n        [Fact]\n        public void PageIndexResetWhenQueryStringValueIsInvalid()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"page\"] = \"NotAnInt\";\n            var grid = new WebGrid(GetContext(queryString), rowsPerPage: 1)\n                .Bind(new[]\n                {\n                    new { P1 = 1, P2 = '2', P3 = \"3\" },\n                    new { P1 = 4, P2 = '5', P3 = \"6\" }\n                });\n            Assert.Equal(0, grid.PageIndex);\n            Assert.Equal(1, grid.Rows.Count);\n            Assert.Equal(1, grid.Rows.First()[\"P1\"]);\n        }\n\n        [Fact]\n        public void PageIndexResetWhenQueryStringValueLessThanOne()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"page\"] = \"0\";\n            var grid = new WebGrid(GetContext(queryString), rowsPerPage: 1)\n                .Bind(new[]\n                {\n                    new { P1 = 1, P2 = '2', P3 = \"3\" },\n                    new { P1 = 4, P2 = '5', P3 = \"6\" }\n                });\n            Assert.Equal(0, grid.PageIndex);\n            Assert.Equal(1, grid.Rows.Count);\n            Assert.Equal(1, grid.Rows.First()[\"P1\"]);\n        }\n\n        [Fact]\n        public void PageIndexUsesCustomQueryString()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"g_pg\"] = \"2\";\n            var grid = new WebGrid(GetContext(queryString), rowsPerPage: 1, fieldNamePrefix: \"g_\", pageFieldName: \"pg\")\n                .Bind(new[]\n                {\n                    new { P1 = 1, P2 = '2', P3 = \"3\" },\n                    new { P1 = 4, P2 = '5', P3 = \"6\" }\n                });\n            Assert.Equal(1, grid.PageIndex);\n            Assert.Equal(1, grid.Rows.Count);\n            Assert.Equal(4, grid.Rows.First()[\"P1\"]);\n        }\n\n        [Fact]\n        public void PageIndexUsesQueryString()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"page\"] = \"2\";\n            var grid = new WebGrid(GetContext(queryString), rowsPerPage: 1)\n                .Bind(new[]\n                {\n                    new { P1 = 1, P2 = '2', P3 = \"3\" },\n                    new { P1 = 4, P2 = '5', P3 = \"6\" }\n                });\n            Assert.Equal(1, grid.PageIndex);\n            Assert.Equal(1, grid.Rows.Count);\n            Assert.Equal(4, grid.Rows.First()[\"P1\"]);\n        }\n\n        [Fact]\n        public void GetPageCountWhenPagingIsTurnedOn()\n        {\n            var grid = new WebGrid(GetContext(), canPage: true, rowsPerPage: 1)\n                .Bind(new[]\n                {\n                    new { P1 = 1, P2 = '2', P3 = \"3\" },\n                    new { P1 = 4, P2 = '5', P3 = \"6\" }\n                });\n            Assert.Equal(2, grid.PageCount);\n        }\n\n        [Fact]\n        public void GetPageIndexWhenPagingIsTurnedOn()\n        {\n            var grid = new WebGrid(GetContext(), canPage: true, rowsPerPage: 1)\n                .Bind(new[]\n                {\n                    new { P1 = 1, P2 = '2', P3 = \"3\" },\n                    new { P1 = 4, P2 = '5', P3 = \"6\" },\n                    new { P1 = 4, P2 = '5', P3 = \"6\" },\n                });\n            grid.PageIndex = 1;\n            Assert.Equal(1, grid.PageIndex);\n            Assert.Equal(3, grid.PageCount);\n            grid.PageIndex = 2;\n            Assert.Equal(2, grid.PageIndex);\n        }\n\n        [Fact]\n        public void GetPageCountWhenPagingIsTurnedOff()\n        {\n            var grid = new WebGrid(GetContext(), canPage: false, rowsPerPage: 1)\n                .Bind(new[]\n                {\n                    new { P1 = 1, P2 = '2', P3 = \"3\" },\n                    new { P1 = 4, P2 = '5', P3 = \"6\" }\n                });\n            Assert.Equal(1, grid.PageCount);\n        }\n\n        [Fact]\n        public void GetPageIndexWhenPagingIsTurnedOff()\n        {\n            var grid = new WebGrid(GetContext(), canPage: false, rowsPerPage: 1)\n                .Bind(new[]\n                {\n                    new { P1 = 1, P2 = '2', P3 = \"3\" },\n                    new { P1 = 4, P2 = '5', P3 = \"6\" },\n                    new { P1 = 4, P2 = '5', P3 = \"6\" },\n                });\n            Assert.Equal(0, grid.PageIndex);\n            Assert.Equal(1, grid.PageCount);\n        }\n\n        [Fact]\n        public void PageUrlResetsSelection()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"page\"] = \"0\";\n            queryString[\"row\"] = \"0\";\n            queryString[\"sort\"] = \"P1\";\n            queryString[\"sortdir\"] = \"DESC\";\n            var grid = new WebGrid(GetContext(queryString), rowsPerPage: 1)\n                .Bind(new[]\n                {\n                    new { P1 = 1, P2 = '2', P3 = \"3\" },\n                    new { P1 = 4, P2 = '5', P3 = \"6\" }\n                });\n            string url = grid.GetPageUrl(1);\n            Assert.Equal(\"?page=2&sort=P1&sortdir=DESC\", url);\n        }\n\n        [Fact]\n        public void PageUrlResetsSelectionForAjax()\n        {\n            string expected40 = \"$(&quot;#grid-container&quot;).swhgLoad(&quot;?page=2&amp;sort=P1&amp;sortdir=DESC&quot;,&quot;#grid-container&quot;);\";\n            string expected45 = \"$(&quot;#grid-container&quot;).swhgLoad(&quot;?page=2\\\\u0026sort=P1\\\\u0026sortdir=DESC&quot;,&quot;#grid-container&quot;);\";\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"page\"] = \"0\";\n            queryString[\"row\"] = \"0\";\n            queryString[\"sort\"] = \"P1\";\n            queryString[\"sortdir\"] = \"DESC\";\n            var grid = new WebGrid(GetContext(queryString), rowsPerPage: 1, ajaxUpdateContainerId: \"grid-container\")\n                .Bind(new[]\n                {\n                    new { P1 = 1, P2 = '2', P3 = \"3\" },\n                    new { P1 = 4, P2 = '5', P3 = \"6\" }\n                });\n            string html = grid.GetContainerUpdateScript(grid.GetPageUrl(1)).ToString();\n\n            // Assert\n            Assert.Equal(RuntimeEnvironment.IsVersion45Installed ? expected45 : expected40, html);\n        }\n\n        [Fact]\n        public void PageUrlResetsSelectionForAjaxWithCallback()\n        {\n            string expected40 = \"$(&quot;#grid&quot;).swhgLoad(&quot;?page=2&amp;sort=P1&amp;sortdir=DESC&quot;,&quot;#grid&quot;,myCallback);\";\n            string expected45 = \"$(&quot;#grid&quot;).swhgLoad(&quot;?page=2\\\\u0026sort=P1\\\\u0026sortdir=DESC&quot;,&quot;#grid&quot;,myCallback);\";\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"page\"] = \"0\";\n            queryString[\"row\"] = \"0\";\n            queryString[\"sort\"] = \"P1\";\n            queryString[\"sortdir\"] = \"DESC\";\n            var grid = new WebGrid(GetContext(queryString), rowsPerPage: 1, ajaxUpdateContainerId: \"grid\", ajaxUpdateCallback: \"myCallback\")\n                .Bind(new[]\n                {\n                    new { P1 = 1, P2 = '2', P3 = \"3\" },\n                    new { P1 = 4, P2 = '5', P3 = \"6\" }\n                });\n            string html = grid.GetContainerUpdateScript(grid.GetPageUrl(1)).ToString();\n\n            // Assert\n            Assert.Equal(RuntimeEnvironment.IsVersion45Installed ? expected45 : expected40, html);\n        }\n\n        [Fact]\n        public void PageUrlThrowsIfIndexGreaterThanOrEqualToPageCount()\n        {\n            var grid = new WebGrid(GetContext(), rowsPerPage: 1).Bind(new[] { new { }, new { } });\n            Assert.ThrowsArgumentOutOfRange(() => { grid.GetPageUrl(2); }, \"pageIndex\", \"Value must be between 0 and 1.\");\n        }\n\n        [Fact]\n        public void PageUrlThrowsIfIndexLessThanZero()\n        {\n            var grid = new WebGrid(GetContext(), rowsPerPage: 1).Bind(new[] { new { }, new { } });\n            Assert.ThrowsArgumentOutOfRange(() => { grid.GetPageUrl(-1); }, \"pageIndex\", \"Value must be between 0 and 1.\");\n        }\n\n        [Fact]\n        public void PageUrlThrowsIfPagingIsDisabled()\n        {\n            var grid = new WebGrid(GetContext(), rowsPerPage: 1, canPage: false).Bind(new[] { new { }, new { } });\n            Assert.Throws<NotSupportedException>(() => { grid.GetPageUrl(2); }, \"This operation is not supported when paging is disabled for the \\\"WebGrid\\\" object.\");\n        }\n\n        [Fact]\n        public void PagerRenderingDefaults()\n        {\n            var grid = new WebGrid(GetContext(), rowsPerPage: 1).Bind(new[] { new { }, new { }, new { }, new { } });\n            var html = grid.Pager();\n            Assert.Equal(\n                \"1 \" +\n                \"<a href=\\\"?page=2\\\">2</a> \" +\n                \"<a href=\\\"?page=3\\\">3</a> \" +\n                \"<a href=\\\"?page=4\\\">4</a> \" +\n                \"<a href=\\\"?page=2\\\">&gt;</a> \",\n                html.ToString());\n            XhtmlAssert.Validate1_1(html, wrapper: \"div\");\n        }\n\n        [Fact]\n        public void PagerRenderingOnFirstShowingAll()\n        {\n            var grid = new WebGrid(GetContext(), rowsPerPage: 1).Bind(new[] { new { }, new { }, new { }, new { } });\n            var html = grid.Pager(WebGridPagerModes.All, numericLinksCount: 5);\n            Assert.Equal(\n                \"1 \" +\n                \"<a href=\\\"?page=2\\\">2</a> \" +\n                \"<a href=\\\"?page=3\\\">3</a> \" +\n                \"<a href=\\\"?page=4\\\">4</a> \" +\n                \"<a href=\\\"?page=2\\\">&gt;</a> \" +\n                \"<a href=\\\"?page=4\\\">&gt;&gt;</a>\",\n                html.ToString());\n            XhtmlAssert.Validate1_1(html, wrapper: \"div\");\n        }\n\n        [Fact]\n        public void PagerRenderingOnNextToLastShowingAll()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"page\"] = \"3\";\n            var grid = new WebGrid(GetContext(queryString), rowsPerPage: 1).Bind(new[]\n            {\n                new { }, new { }, new { }, new { }\n            });\n            var html = grid.Pager(WebGridPagerModes.All, numericLinksCount: 4);\n            Assert.Equal(\n                \"<a href=\\\"?page=1\\\">&lt;&lt;</a> \" +\n                \"<a href=\\\"?page=2\\\">&lt;</a> \" +\n                \"<a href=\\\"?page=1\\\">1</a> \" +\n                \"<a href=\\\"?page=2\\\">2</a> \" +\n                \"3 \" +\n                \"<a href=\\\"?page=4\\\">4</a> \" +\n                \"<a href=\\\"?page=4\\\">&gt;</a> \",\n                html.ToString());\n            XhtmlAssert.Validate1_1(html, wrapper: \"div\");\n        }\n\n        [Fact]\n        public void PagerRenderingOnMiddleShowingAll()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"page\"] = \"3\";\n            var grid = new WebGrid(GetContext(queryString), rowsPerPage: 1).Bind(new[]\n            {\n                new { }, new { }, new { }, new { }\n            });\n            var html = grid.Pager(WebGridPagerModes.All, numericLinksCount: 3);\n            Assert.Equal(\n                \"<a href=\\\"?page=1\\\">&lt;&lt;</a> \" +\n                \"<a href=\\\"?page=2\\\">&lt;</a> \" +\n                \"<a href=\\\"?page=2\\\">2</a> \" +\n                \"3 \" +\n                \"<a href=\\\"?page=4\\\">4</a> \" +\n                \"<a href=\\\"?page=4\\\">&gt;</a> \",\n                html.ToString());\n            XhtmlAssert.Validate1_1(html, wrapper: \"div\");\n        }\n\n        [Fact]\n        public void PagerRenderingOnSecondHidingFirstLast()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"page\"] = \"2\";\n            var grid = new WebGrid(GetContext(queryString), rowsPerPage: 1).Bind(new[]\n            {\n                new { }, new { }, new { }, new { }\n            });\n            var html = grid.Pager(WebGridPagerModes.NextPrevious | WebGridPagerModes.Numeric, numericLinksCount: 2);\n            Assert.Equal(\n                \"<a href=\\\"?page=1\\\">&lt;</a> \" +\n                \"2 \" +\n                \"<a href=\\\"?page=3\\\">3</a> \" +\n                \"<a href=\\\"?page=3\\\">&gt;</a> \",\n                html.ToString());\n            XhtmlAssert.Validate1_1(html, wrapper: \"div\");\n        }\n\n        [Fact]\n        public void PagerRenderingOnLastHidingFirstLast()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"page\"] = \"4\";\n            var grid = new WebGrid(GetContext(queryString), rowsPerPage: 1).Bind(new[]\n            {\n                new { }, new { }, new { }, new { }\n            });\n            var html = grid.Pager(WebGridPagerModes.NextPrevious | WebGridPagerModes.Numeric, numericLinksCount: 1);\n            Assert.Equal(\n                \"<a href=\\\"?page=3\\\">&lt;</a> \" +\n                \"4 \",\n                html.ToString());\n            XhtmlAssert.Validate1_1(html, wrapper: \"div\");\n        }\n\n        [Fact]\n        public void PagerRenderingOnMiddleHidingNextPrevious()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"page\"] = \"3\";\n            var grid = new WebGrid(GetContext(queryString), rowsPerPage: 1).Bind(new[]\n            {\n                new { }, new { }, new { }, new { }\n            });\n            var html = grid.Pager(WebGridPagerModes.FirstLast | WebGridPagerModes.Numeric, numericLinksCount: 0);\n            Assert.Equal(\n                \"<a href=\\\"?page=1\\\">&lt;&lt;</a> \",\n                html.ToString());\n            XhtmlAssert.Validate1_1(html, wrapper: \"div\");\n        }\n\n        [Fact]\n        public void PagerRenderingOnMiddleWithLinksCountGreaterThanPageCount()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"page\"] = \"3\";\n            var grid = new WebGrid(GetContext(queryString), rowsPerPage: 1).Bind(new[]\n            {\n                new { }, new { }, new { }, new { }\n            });\n            var html = grid.Pager(WebGridPagerModes.Numeric, numericLinksCount: 6);\n            Assert.Equal(\n                \"<a href=\\\"?page=1\\\">1</a> \" +\n                \"<a href=\\\"?page=2\\\">2</a> \" +\n                \"3 \" +\n                \"<a href=\\\"?page=4\\\">4</a> \",\n                html.ToString());\n            XhtmlAssert.Validate1_1(html, wrapper: \"div\");\n        }\n\n        [Fact]\n        public void PagerRenderingHidingAll()\n        {\n            var grid = new WebGrid(GetContext(), rowsPerPage: 2).Bind(new[]\n            {\n                new { }, new { }, new { }, new { }\n            });\n            var html = grid.Pager(WebGridPagerModes.Numeric, numericLinksCount: 0);\n            Assert.Equal(\"\", html.ToString());\n        }\n\n        [Fact]\n        public void PagerRenderingTextOverrides()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"page\"] = \"3\";\n            var grid = new WebGrid(GetContext(queryString), rowsPerPage: 1).Bind(new[]\n            {\n                new { }, new { }, new { }, new { }, new { }\n            });\n            var html = grid.Pager(WebGridPagerModes.FirstLast | WebGridPagerModes.NextPrevious,\n                                  firstText: \"first\", previousText: \"previous\", nextText: \"next\", lastText: \"last\");\n            Assert.Equal(\n                \"<a href=\\\"?page=1\\\">first</a> \" +\n                \"<a href=\\\"?page=2\\\">previous</a> \" +\n                \"<a href=\\\"?page=4\\\">next</a> \" +\n                \"<a href=\\\"?page=5\\\">last</a>\",\n                html.ToString());\n            XhtmlAssert.Validate1_1(html, wrapper: \"div\");\n        }\n\n        [Fact]\n        public void PagerThrowsIfTextSetAndModeNotEnabled()\n        {\n            var grid = new WebGrid(GetContext(), rowsPerPage: 1).Bind(new[] { new { }, new { } });\n            Assert.ThrowsArgument(() => { grid.Pager(firstText: \"first\"); }, \"firstText\", \"To use this argument, pager mode \\\"FirstLast\\\" must be enabled.\");\n            Assert.ThrowsArgument(() => { grid.Pager(mode: WebGridPagerModes.Numeric, previousText: \"previous\"); }, \"previousText\", \"To use this argument, pager mode \\\"NextPrevious\\\" must be enabled.\");\n            Assert.ThrowsArgument(() => { grid.Pager(mode: WebGridPagerModes.Numeric, nextText: \"next\"); }, \"nextText\", \"To use this argument, pager mode \\\"NextPrevious\\\" must be enabled.\");\n            Assert.ThrowsArgument(() => { grid.Pager(lastText: \"last\"); }, \"lastText\", \"To use this argument, pager mode \\\"FirstLast\\\" must be enabled.\");\n        }\n\n        [Fact]\n        public void PagerThrowsIfNumericLinkCountIsLessThanZero()\n        {\n            var grid = new WebGrid(GetContext(), rowsPerPage: 1).Bind(new[] { new { }, new { } });\n            Assert.ThrowsArgumentOutOfRange(() => { grid.Pager(numericLinksCount: -1); }, \"numericLinksCount\", \"Value must be greater than or equal to 0.\");\n        }\n\n        [Fact]\n        public void PagerThrowsIfPagingIsDisabled()\n        {\n            var grid = new WebGrid(GetContext(), rowsPerPage: 1, canPage: false).Bind(new[] { new { }, new { } });\n            Assert.Throws<NotSupportedException>(() => { grid.Pager(); }, \"This operation is not supported when paging is disabled for the \\\"WebGrid\\\" object.\");\n        }\n\n        [Fact]\n        public void PagerWithAjax()\n        {\n            var grid = new WebGrid(GetContext(), rowsPerPage: 1, ajaxUpdateContainerId: \"grid\")\n                .Bind(new[]\n                {\n                    new { P1 = 1, P2 = '2', P3 = \"3\" },\n                    new { P1 = 4, P2 = '5', P3 = \"6\" }\n                });\n            string html = grid.Pager().ToString();\n            Assert.Contains(\"<script\", html);\n        }\n\n        [Fact]\n        public void PagerWithAjaxAndCallback()\n        {\n            var grid = new WebGrid(GetContext(), rowsPerPage: 1, ajaxUpdateContainerId: \"grid\", ajaxUpdateCallback: \"myCallback\")\n                .Bind(new[]\n                {\n                    new { P1 = 1, P2 = '2', P3 = \"3\" },\n                    new { P1 = 4, P2 = '5', P3 = \"6\" }\n                });\n            string html = grid.Pager().ToString();\n            Assert.Contains(\"<script\", html);\n            Assert.Contains(\"data-swhgcallback=\\\"myCallback\\\"\", html);\n        }\n\n        [Fact]\n        public void PropertySettersDoNotThrowBeforePagingAndSorting()\n        {\n            // test with selection because SelectedIndex getter used to do range checking that caused paging and sorting\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"row\"] = \"1\";\n            var grid = new WebGrid(GetContext(queryString), rowsPerPage: 2).Bind(new[]\n            {\n                new { P1 = 1 }, new { P1 = 2 }, new { P1 = 3 }\n            });\n\n            // invoke other WebGrid properties to ensure they don't cause sorting and paging\n            foreach (var prop in typeof(WebGrid).GetProperties())\n            {\n                // exceptions: these do cause sorting and paging\n                if (prop.Name.Equals(\"Rows\") || prop.Name.Equals(\"SelectedRow\") || prop.Name.Equals(\"ElementType\"))\n                {\n                    continue;\n                }\n                prop.GetValue(grid, null);\n            }\n\n            grid.PageIndex = 1;\n            grid.SelectedIndex = 0;\n            grid.SortColumn = \"P1\";\n            grid.SortDirection = SortDirection.Descending;\n        }\n\n        [Fact]\n        public void PropertySettersDoNotThrowAfterPagingAndSortingIfValuesHaveNotChanged()\n        {\n            var grid = new WebGrid(GetContext(), rowsPerPage: 2).Bind(new[]\n            {\n                new { P1 = 1 }, new { P1 = 2 }, new { P1 = 3 }\n            });\n            // calling Rows will sort and page the data\n            Assert.Equal(2, grid.Rows.Count());\n\n            grid.PageIndex = 0;\n            grid.SelectedIndex = -1;\n            grid.SortColumn = String.Empty;\n            grid.SortDirection = SortDirection.Ascending;\n        }\n\n        [Fact]\n        public void PropertySettersThrowAfterPagingAndSorting()\n        {\n            var grid = new WebGrid(GetContext(), rowsPerPage: 2).Bind(new[]\n            {\n                new { P1 = 1 }, new { P1 = 2 }, new { P1 = 3 }\n            });\n            // calling Rows will sort and page the data\n            Assert.Equal(2, grid.Rows.Count());\n\n            var message = \"This property cannot be set after the \\\"WebGrid\\\" object has been sorted or paged. Make sure that this property is set prior to invoking the \\\"Rows\\\" property directly or indirectly through other methods such as \\\"GetHtml\\\", \\\"Pager\\\", \\\"Table\\\", etc.\";\n            Assert.Throws<InvalidOperationException>(() => { grid.PageIndex = 1; }, message);\n            Assert.Throws<InvalidOperationException>(() => { grid.SelectedIndex = 0; }, message);\n            Assert.Throws<InvalidOperationException>(() => { grid.SortColumn = \"P1\"; }, message);\n            Assert.Throws<InvalidOperationException>(() => { grid.SortDirection = SortDirection.Descending; }, message);\n        }\n\n        [Fact]\n        public void RowColumnsAreDynamicMembersForDynamics()\n        {\n            var grid = new WebGrid(GetContext()).Bind(Dynamics(\n                new { P1 = 1, P2 = '2', P3 = \"3\" }\n                                                          ));\n            dynamic row = grid.Rows.First();\n            Assert.Equal(1, row.P1);\n            Assert.Equal('2', row.P2);\n            Assert.Equal(\"3\", row.P3);\n        }\n\n        [Fact]\n        public void RowColumnsAreDynamicMembersForNonDynamics()\n        {\n            var grid = new WebGrid(GetContext()).Bind(new[]\n            {\n                new { P1 = 1, P2 = '2', P3 = \"3\" }\n            });\n            dynamic row = grid.Rows.First();\n            Assert.Equal(1, row.P1);\n            Assert.Equal('2', row.P2);\n            Assert.Equal(\"3\", row.P3);\n        }\n\n        [Fact]\n        public void RowExposesRowIndex()\n        {\n            var grid = new WebGrid(GetContext()).Bind(new[]\n            {\n                new { }, new { }, new { }\n            });\n            dynamic row = grid.Rows.First();\n            Assert.Equal(0, row[\"ROW\"]);\n            row = grid.Rows.Skip(1).First();\n            Assert.Equal(1, row.ROW);\n            row = grid.Rows.Skip(2).First();\n            Assert.Equal(2, row.ROW);\n        }\n\n        [Fact]\n        public void RowExposesUnderlyingValue()\n        {\n            var sb = new StringBuilder(\"Foo\");\n            sb.Append(\"Bar\");\n            var grid = new WebGrid(GetContext()).Bind(new[] { sb });\n            var row = grid.Rows.First();\n            Assert.Equal(sb, row.Value);\n            Assert.Equal(\"FooBar\", row.ToString());\n            Assert.Equal(grid, row.WebGrid);\n        }\n\n        [Fact]\n        public void RowIndexerThrowsWhenColumnNameIsEmpty()\n        {\n            var grid = new WebGrid(GetContext()).Bind(new[] { new { } });\n            var row = grid.Rows.First();\n            Assert.ThrowsArgumentNullOrEmptyString(() => { var value = row[String.Empty]; }, \"name\");\n        }\n\n        [Fact]\n        public void RowIndexerThrowsWhenColumnNameIsNull()\n        {\n            var grid = new WebGrid(GetContext()).Bind(new[] { new { } });\n            var row = grid.Rows.First();\n            Assert.ThrowsArgumentNullOrEmptyString(() => { var value = row[null]; }, \"name\");\n        }\n\n        [Fact] // todo - should throw ArgumentException?\n        public void RowIndexerThrowsWhenColumnNotFound()\n        {\n            var grid = new WebGrid(GetContext()).Bind(new[] { new { } });\n            var row = grid.Rows.First();\n            Assert.Throws<InvalidOperationException>(() => { var value = row[\"NotAColumn\"]; });\n        }\n\n        [Fact]\n        public void RowIndexerThrowsWhenGreaterThanColumnCount()\n        {\n            var grid = new WebGrid(GetContext()).Bind(new[]\n            {\n                new { P1 = 1, P2 = '2', P3 = \"3\" }\n            });\n            var row = grid.Rows.First();\n            Assert.Throws<ArgumentOutOfRangeException>(() => { var value = row[4]; });\n        }\n\n        [Fact]\n        public void RowIndexerThrowsWhenLessThanZero()\n        {\n            var grid = new WebGrid(GetContext()).Bind(new[] { new { } });\n            var row = grid.Rows.First();\n            Assert.Throws<ArgumentOutOfRangeException>(() => { var value = row[-1]; });\n        }\n\n        [Fact]\n        public void RowIsEnumerableForDynamics()\n        {\n            var grid = new WebGrid(GetContext()).Bind(Dynamics(\n                new { P1 = 1, P2 = '2', P3 = \"3\" }\n                                                          ));\n            int i = 0;\n            foreach (var col in (IEnumerable)grid.Rows.First())\n            {\n                i++;\n            }\n            Assert.Equal(3, i);\n        }\n\n        [Fact]\n        public void RowIsEnumerableForNonDynamics()\n        {\n            var grid = new WebGrid(GetContext()).Bind(new[]\n            {\n                new { P1 = 1, P2 = '2', P3 = \"3\" }\n            });\n            int i = 0;\n            foreach (var col in grid.Rows.First())\n            {\n                i++;\n            }\n            Assert.Equal(3, i);\n        }\n\n        [Fact]\n        public void RowIsIndexableByColumnForDynamics()\n        {\n            var grid = new WebGrid(GetContext()).Bind(Dynamics(\n                new { P1 = 1, P2 = '2', P3 = \"3\" }\n                                                          ));\n            var row = grid.Rows.First();\n            Assert.Equal(1, row[\"P1\"]);\n            Assert.Equal('2', row[\"P2\"]);\n            Assert.Equal(\"3\", row[\"P3\"]);\n        }\n\n        [Fact]\n        public void RowIsIndexableByColumnForNonDynamics()\n        {\n            var grid = new WebGrid(GetContext()).Bind(new[]\n            {\n                new { P1 = 1, P2 = '2', P3 = \"3\" }\n            });\n            var row = grid.Rows.First();\n            Assert.Equal(1, row[\"P1\"]);\n            Assert.Equal('2', row[\"P2\"]);\n            Assert.Equal(\"3\", row[\"P3\"]);\n        }\n\n        [Fact]\n        public void RowIsIndexableByIndexForDynamics()\n        {\n            var grid = new WebGrid(GetContext()).Bind(Dynamics(\n                new { P1 = 1, P2 = '2', P3 = \"3\" }\n                                                          ));\n            var row = grid.Rows.First();\n            Assert.Equal(1, row[0]);\n            Assert.Equal('2', row[1]);\n            Assert.Equal(\"3\", row[2]);\n        }\n\n        [Fact]\n        public void RowIsIndexableByIndexForNonDynamics()\n        {\n            var grid = new WebGrid(GetContext()).Bind(new[]\n            {\n                new { P1 = 1, P2 = '2', P3 = \"3\" }\n            });\n            var row = grid.Rows.First();\n            Assert.Equal(1, row[0]);\n            Assert.Equal('2', row[1]);\n            Assert.Equal(\"3\", row[2]);\n        }\n\n        [Fact]\n        public void RowsNotPagedWhenPagingIsDisabled()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"page\"] = \"2\";\n            var grid = new WebGrid(GetContext(queryString), rowsPerPage: 1, canPage: false)\n                .Bind(new[]\n                {\n                    new { P1 = 1, P2 = '2', P3 = \"3\" },\n                    new { P1 = 4, P2 = '5', P3 = \"6\" }\n                });\n            // review: should we reset PageIndex or Sort when operation disabled?\n            Assert.Equal(0, grid.PageIndex);\n            Assert.Equal(2, grid.Rows.Count);\n            Assert.Equal(1, grid.Rows.First()[\"P1\"]);\n            Assert.Equal(4, grid.Rows.Skip(1).First()[\"P1\"]);\n        }\n\n        [Fact] // todo - should throw ArgumentException?\n        public void RowTryGetMemberReturnsFalseWhenColumnNotFound()\n        {\n            var grid = new WebGrid(GetContext()).Bind(new[] { new { } });\n            var row = grid.Rows.First();\n            object value = null;\n            Assert.False(row.TryGetMember(\"NotAColumn\", out value));\n        }\n\n        [Fact]\n        public void SelectedIndexCanBeReset()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"row\"] = \"2\";\n            var grid = new WebGrid(GetContext(queryString)).Bind(new[]\n            {\n                new { P1 = 1, P2 = '2', P3 = \"3\" },\n                new { P1 = 4, P2 = '5', P3 = \"6\" }\n            });\n            Assert.Equal(1, grid.SelectedIndex);\n            grid.SelectedIndex = 0;\n            Assert.Equal(0, grid.SelectedIndex);\n        }\n\n        [Fact]\n        public void SelectedIndexCanBeResetToSameValue()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"row\"] = \"2\";\n            var grid = new WebGrid(GetContext(queryString)).Bind(new[]\n            {\n                new { P1 = 1, P2 = '2', P3 = \"3\" },\n                new { P1 = 4, P2 = '5', P3 = \"6\" }\n            });\n            grid.SelectedIndex = -1;\n            Assert.Equal(-1, grid.SelectedIndex);\n        }\n\n        [Fact]\n        public void SelectedIndexDefaultsToNegative()\n        {\n            var grid = new WebGrid(GetContext()).Bind(new[]\n            {\n                new { P1 = 1, P2 = '2', P3 = \"3\" },\n                new { P1 = 4, P2 = '5', P3 = \"6\" }\n            });\n            Assert.False(grid.HasSelection);\n            Assert.Equal(-1, grid.SelectedIndex);\n            Assert.Null(grid.SelectedRow);\n        }\n\n        [Fact]\n        public void SelectedIndexResetWhenQueryStringValueGreaterThanRowsPerPage()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"row\"] = \"3\";\n            var grid = new WebGrid(GetContext(queryString), rowsPerPage: 2).Bind(new[]\n            {\n                new { P1 = 1, P2 = '2', P3 = \"3\" },\n                new { P1 = 4, P2 = '5', P3 = \"6\" }\n            });\n            Assert.False(grid.HasSelection);\n            Assert.Equal(-1, grid.SelectedIndex);\n            Assert.Null(grid.SelectedRow);\n        }\n\n        [Fact]\n        public void SelectedIndexPersistsWhenPagingTurnedOff()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"row\"] = \"3\";\n            var grid = new WebGrid(GetContext(queryString), rowsPerPage: 2, canPage: false).Bind(new[]\n            {\n                new { }, new { }, new { }, new { }\n            });\n            grid.SelectedIndex = 3;\n            Assert.Equal(3, grid.SelectedIndex);\n        }\n\n        [Fact]\n        public void SelectedIndexResetWhenQueryStringValueIsInvalid()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"row\"] = \"NotAnInt\";\n            var grid = new WebGrid(GetContext(queryString)).Bind(new[]\n            {\n                new { P1 = 1, P2 = '2', P3 = \"3\" },\n                new { P1 = 4, P2 = '5', P3 = \"6\" }\n            });\n            Assert.False(grid.HasSelection);\n            Assert.Equal(-1, grid.SelectedIndex);\n            Assert.Null(grid.SelectedRow);\n        }\n\n        [Fact]\n        public void SelectedIndexResetWhenQueryStringValueLessThanOne()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"row\"] = \"0\";\n            var grid = new WebGrid(GetContext(queryString)).Bind(new[]\n            {\n                new { P1 = 1, P2 = '2', P3 = \"3\" },\n                new { P1 = 4, P2 = '5', P3 = \"6\" }\n            });\n            Assert.False(grid.HasSelection);\n            Assert.Equal(-1, grid.SelectedIndex);\n            Assert.Null(grid.SelectedRow);\n        }\n\n        [Fact]\n        public void SelectedIndexUsesCustomQueryString()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"g_sel\"] = \"2\";\n            var grid = new WebGrid(GetContext(queryString), fieldNamePrefix: \"g_\", selectionFieldName: \"sel\").Bind(new[]\n            {\n                new { P1 = 1, P2 = '2', P3 = \"3\" },\n                new { P1 = 4, P2 = '5', P3 = \"6\" }\n            });\n            Assert.True(grid.HasSelection);\n            Assert.Equal(1, grid.SelectedIndex);\n            Assert.NotNull(grid.SelectedRow);\n            Assert.Equal(4, grid.SelectedRow[\"P1\"]);\n        }\n\n        [Fact]\n        public void SelectedIndexUsesQueryString()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"row\"] = \"2\";\n            var grid = new WebGrid(GetContext(queryString)).Bind(new[]\n            {\n                new { P1 = 1, P2 = '2', P3 = \"3\" },\n                new { P1 = 4, P2 = '5', P3 = \"6\" }\n            });\n            Assert.True(grid.HasSelection);\n            Assert.Equal(1, grid.SelectedIndex);\n            Assert.NotNull(grid.SelectedRow);\n            Assert.Equal(4, grid.SelectedRow[\"P1\"]);\n        }\n\n        [Fact]\n        public void SelectLink()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"page\"] = \"1\";\n            queryString[\"row\"] = \"1\";\n            queryString[\"sort\"] = \"P1\";\n            queryString[\"sortdir\"] = \"DESC\";\n            var grid = new WebGrid(GetContext(queryString)).Bind(new[]\n            {\n                new { P1 = 1, P2 = '2', P3 = \"3\" },\n                new { P1 = 4, P2 = '5', P3 = \"6\" }\n            });\n            string html = grid.Rows[1].GetSelectLink().ToString();\n            Assert.Equal(\"<a href=\\\"?page=1&amp;row=2&amp;sort=P1&amp;sortdir=DESC\\\">Select</a>\", html.ToString());\n        }\n\n        [Fact]\n        public void SortCanBeReset()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"sort\"] = \"P1\";\n            var grid = new WebGrid(GetContext(queryString)).Bind(new[]\n            {\n                new { P1 = 1, P2 = '2', P3 = \"3\" },\n                new { P1 = 4, P2 = '5', P3 = \"6\" }\n            });\n            Assert.Equal(\"P1\", grid.SortColumn);\n            grid.SortColumn = \"P2\";\n            Assert.Equal(\"P2\", grid.SortColumn);\n            // verify that selection and page links have updated sort\n            Assert.Equal(\"?sort=P2&row=1\", grid.Rows.FirstOrDefault().GetSelectUrl());\n            Assert.Equal(\"?sort=P2&page=1\", grid.GetPageUrl(0));\n        }\n\n        [Fact]\n        public void SortCanBeResetToNull()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"sort\"] = \"P1\";\n            var grid = new WebGrid(GetContext(queryString)).Bind(new[]\n            {\n                new { P1 = 1, P2 = '2', P3 = \"3\" },\n                new { P1 = 4, P2 = '5', P3 = \"6\" }\n            });\n            Assert.Equal(\"P1\", grid.SortColumn);\n            grid.SortColumn = null;\n            Assert.Equal(String.Empty, grid.SortColumn);\n            // verify that selection and page links have updated sort\n            Assert.Equal(\"?row=1\", grid.Rows.FirstOrDefault().GetSelectUrl());\n            Assert.Equal(\"?page=1\", grid.GetPageUrl(0));\n        }\n\n        [Fact]\n        public void SortCanBeResetToSameValue()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"sort\"] = \"P1\";\n            var grid = new WebGrid(GetContext(queryString)).Bind(new[]\n            {\n                new { P1 = 1, P2 = '2', P3 = \"3\" },\n                new { P1 = 4, P2 = '5', P3 = \"6\" }\n            });\n            grid.SortColumn = String.Empty;\n            Assert.Equal(String.Empty, grid.SortColumn);\n        }\n\n        [Fact]\n        public void SortColumnDefaultsToEmpty()\n        {\n            var grid = new WebGrid(GetContext()).Bind(new[]\n            {\n                new { P1 = 1, P2 = '2', P3 = \"3\" }\n            });\n            Assert.Equal(String.Empty, grid.SortColumn);\n        }\n\n        [Fact]\n        public void SortColumnResetWhenQueryStringValueIsInvalid()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"sort\"] = \"P4\";\n            var grid = new WebGrid(GetContext(queryString)).Bind(new[]\n            {\n                new { P1 = 1, P2 = '2', P3 = \"3\" }\n            });\n            Assert.Equal(\"\", grid.SortColumn);\n        }\n\n        [Fact]\n        public void SortColumnUsesCustomQueryString()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"g_st\"] = \"P2\";\n            var grid = new WebGrid(GetContext(queryString), fieldNamePrefix: \"g_\", sortFieldName: \"st\").Bind(new[]\n            {\n                new { P1 = 1, P2 = '2', P3 = \"3\" }\n            });\n            Assert.Equal(\"P2\", grid.SortColumn);\n        }\n\n        [Fact]\n        public void SortColumnUsesQueryString()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"sort\"] = \"P2\";\n            var grid = new WebGrid(GetContext(queryString)).Bind(new[]\n            {\n                new { P1 = 1, P2 = '2', P3 = \"3\" }\n            });\n            Assert.Equal(\"P2\", grid.SortColumn);\n        }\n\n        [Fact]\n        public void SortDirectionCanBeReset()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"sortdir\"] = \"DESC\";\n            var grid = new WebGrid(GetContext(queryString)).Bind(new[]\n            {\n                new { P1 = 1, P2 = '2', P3 = \"3\" },\n                new { P1 = 4, P2 = '5', P3 = \"6\" }\n            });\n            Assert.Equal(SortDirection.Descending, grid.SortDirection);\n            grid.SortDirection = SortDirection.Ascending;\n            Assert.Equal(SortDirection.Ascending, grid.SortDirection);\n            // verify that selection and page links have updated sort\n            Assert.Equal(\"?sortdir=ASC&row=1\", grid.Rows.FirstOrDefault().GetSelectUrl());\n            Assert.Equal(\"?sortdir=ASC&page=1\", grid.GetPageUrl(0));\n        }\n\n        [Fact]\n        public void SortDirectionDefaultsToAscending()\n        {\n            var grid = new WebGrid(GetContext()).Bind(new object[0]);\n            Assert.Equal(SortDirection.Ascending, grid.SortDirection);\n        }\n\n        [Fact]\n        public void SortDirectionResetWhenQueryStringValueIsInvalid()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"sortdir\"] = \"NotASortDir\";\n            var grid = new WebGrid(GetContext(queryString)).Bind(new object[0]);\n            Assert.Equal(SortDirection.Ascending, grid.SortDirection);\n        }\n\n        [Fact]\n        public void SortDirectionUsesQueryStringOfAsc()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"sortdir\"] = \"aSc\";\n            var grid = new WebGrid(GetContext(queryString)).Bind(new object[0]);\n            Assert.Equal(SortDirection.Ascending, grid.SortDirection);\n        }\n\n        [Fact]\n        public void SortDirectionUsesQueryStringOfAscending()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"sortdir\"] = \"AScendING\";\n            var grid = new WebGrid(GetContext(queryString)).Bind(new object[0]);\n            Assert.Equal(SortDirection.Ascending, grid.SortDirection);\n        }\n\n        [Fact]\n        public void SortDirectionUsesQueryStringOfDesc()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"sortdir\"] = \"DeSc\";\n            var grid = new WebGrid(GetContext(queryString)).Bind(new object[0]);\n            Assert.Equal(SortDirection.Descending, grid.SortDirection);\n        }\n\n        [Fact]\n        public void SortDirectionUsesQueryStringOfDescending()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"g_sd\"] = \"DeScendING\";\n            var grid = new WebGrid(GetContext(queryString), fieldNamePrefix: \"g_\", sortDirectionFieldName: \"sd\").Bind(new object[0]);\n            Assert.Equal(SortDirection.Descending, grid.SortDirection);\n        }\n\n        [Fact]\n        public void SortDisabledIfSortIsEmpty()\n        {\n            var grid = new WebGrid(GetContext(), defaultSort: String.Empty).Bind(Dynamics(\n                new { FirstName = \"Joe\", LastName = \"Smith\" },\n                new { FirstName = \"Bob\", LastName = \"Johnson\" },\n                new { FirstName = \"Sam\", LastName = \"Jones\" },\n                new { FirstName = \"Tom\", LastName = \"Anderson\" }\n                                                                                     ));\n            Assert.Equal(\"Joe\", grid.Rows[0][\"FirstName\"]);\n            Assert.Equal(\"Bob\", grid.Rows[1][\"FirstName\"]);\n            Assert.Equal(\"Sam\", grid.Rows[2][\"FirstName\"]);\n            Assert.Equal(\"Tom\", grid.Rows[3][\"FirstName\"]);\n        }\n\n        [Fact]\n        public void SortDisabledIfSortIsNull()\n        {\n            var grid = new WebGrid(GetContext(), defaultSort: null).Bind(Dynamics(\n                new { FirstName = \"Joe\", LastName = \"Smith\" },\n                new { FirstName = \"Bob\", LastName = \"Johnson\" },\n                new { FirstName = \"Sam\", LastName = \"Jones\" },\n                new { FirstName = \"Tom\", LastName = \"Anderson\" }\n                                                                             ));\n            Assert.Equal(\"Joe\", grid.Rows[0][\"FirstName\"]);\n            Assert.Equal(\"Bob\", grid.Rows[1][\"FirstName\"]);\n            Assert.Equal(\"Sam\", grid.Rows[2][\"FirstName\"]);\n            Assert.Equal(\"Tom\", grid.Rows[3][\"FirstName\"]);\n        }\n\n        [Fact]\n        public void SortForDynamics()\n        {\n            var grid = new WebGrid(GetContext(), defaultSort: \"FirstName\").Bind(Dynamics(\n                new { FirstName = \"Joe\", LastName = \"Smith\" },\n                new { FirstName = \"Bob\", LastName = \"Johnson\" },\n                new { FirstName = \"Sam\", LastName = \"Jones\" },\n                new { FirstName = \"Tom\", LastName = \"Anderson\" }\n                                                                                    ));\n            Assert.Equal(\"Bob\", grid.Rows[0][\"FirstName\"]);\n            Assert.Equal(\"Joe\", grid.Rows[1][\"FirstName\"]);\n            Assert.Equal(\"Sam\", grid.Rows[2][\"FirstName\"]);\n            Assert.Equal(\"Tom\", grid.Rows[3][\"FirstName\"]);\n        }\n\n        [Fact]\n        public void SortForDynamicsDescending()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"sort\"] = \"LastName\";\n            queryString[\"sortdir\"] = \"DESCENDING\";\n            var grid = new WebGrid(GetContext(queryString), defaultSort: \"FirstName\").Bind(Dynamics(\n                new { FirstName = \"Joe\", LastName = \"Smith\" },\n                new { FirstName = \"Bob\", LastName = \"Johnson\" },\n                new { FirstName = \"Sam\", LastName = \"Jones\" },\n                new { FirstName = \"Tom\", LastName = \"Anderson\" }\n                                                                                               ));\n            Assert.Equal(\"Smith\", grid.Rows[0][\"LastName\"]);\n            Assert.Equal(\"Jones\", grid.Rows[1][\"LastName\"]);\n            Assert.Equal(\"Johnson\", grid.Rows[2][\"LastName\"]);\n            Assert.Equal(\"Anderson\", grid.Rows[3][\"LastName\"]);\n        }\n\n        [Fact]\n        public void SortForNonDynamicNavigationColumn()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"sort\"] = \"Not.A.Column\";\n            var grid = new WebGrid(GetContext(queryString), defaultSort: \"Person.FirstName\").Bind(new[]\n            {\n                new { Person = new { FirstName = \"Joe\", LastName = \"Smith\" } },\n                new { Person = new { FirstName = \"Bob\", LastName = \"Johnson\" } },\n                new { Person = new { FirstName = \"Sam\", LastName = \"Jones\" } },\n                new { Person = new { FirstName = \"Tom\", LastName = \"Anderson\" } }\n            });\n            Assert.Equal(\"Not.A.Column\", grid.SortColumn); // navigation columns are validated during sort\n            Assert.Equal(\"Bob\", grid.Rows[0][\"Person.FirstName\"]);\n            Assert.Equal(\"Joe\", grid.Rows[1][\"Person.FirstName\"]);\n            Assert.Equal(\"Sam\", grid.Rows[2][\"Person.FirstName\"]);\n            Assert.Equal(\"Tom\", grid.Rows[3][\"Person.FirstName\"]);\n        }\n\n        [Fact]\n        public void SortForNonDynamics()\n        {\n            var grid = new WebGrid(GetContext(), defaultSort: \"FirstName\").Bind(new[]\n            {\n                new { FirstName = \"Joe\", LastName = \"Smith\" },\n                new { FirstName = \"Bob\", LastName = \"Johnson\" },\n                new { FirstName = \"Sam\", LastName = \"Jones\" },\n                new { FirstName = \"Tom\", LastName = \"Anderson\" }\n            });\n            Assert.Equal(\"Bob\", grid.Rows[0][\"FirstName\"]);\n            Assert.Equal(\"Joe\", grid.Rows[1][\"FirstName\"]);\n            Assert.Equal(\"Sam\", grid.Rows[2][\"FirstName\"]);\n            Assert.Equal(\"Tom\", grid.Rows[3][\"FirstName\"]);\n        }\n\n        [Fact]\n        public void SortForNonDynamicsDescending()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"sort\"] = \"LastName\";\n            queryString[\"sortdir\"] = \"DESCENDING\";\n            var grid = new WebGrid(GetContext(queryString), defaultSort: \"FirstName\").Bind(new[]\n            {\n                new { FirstName = \"Joe\", LastName = \"Smith\" },\n                new { FirstName = \"Bob\", LastName = \"Johnson\" },\n                new { FirstName = \"Sam\", LastName = \"Jones\" },\n                new { FirstName = \"Tom\", LastName = \"Anderson\" }\n            });\n            Assert.Equal(\"Smith\", grid.Rows[0][\"LastName\"]);\n            Assert.Equal(\"Jones\", grid.Rows[1][\"LastName\"]);\n            Assert.Equal(\"Johnson\", grid.Rows[2][\"LastName\"]);\n            Assert.Equal(\"Anderson\", grid.Rows[3][\"LastName\"]);\n        }\n\n        [Fact]\n        public void SortForNonDynamicsEnumerable()\n        {\n            var grid = new WebGrid(GetContext(), defaultSort: \"FirstName\").Bind(new[]\n            {\n                new { FirstName = \"Joe\", LastName = \"Smith\" },\n                new { FirstName = \"Bob\", LastName = \"Johnson\" },\n                new { FirstName = \"Sam\", LastName = \"Jones\" },\n                new { FirstName = \"Tom\", LastName = \"Anderson\" }\n            }.ToList());\n            Assert.Equal(\"Bob\", grid.Rows[0][\"FirstName\"]);\n            Assert.Equal(\"Joe\", grid.Rows[1][\"FirstName\"]);\n            Assert.Equal(\"Sam\", grid.Rows[2][\"FirstName\"]);\n            Assert.Equal(\"Tom\", grid.Rows[3][\"FirstName\"]);\n        }\n\n        [Fact]\n        public void SortForNonDynamicsEnumerableDescending()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"sort\"] = \"LastName\";\n            queryString[\"sortdir\"] = \"DESCENDING\";\n            var grid = new WebGrid(GetContext(queryString), defaultSort: \"FirstName\").Bind(new[]\n            {\n                new { FirstName = \"Joe\", LastName = \"Smith\" },\n                new { FirstName = \"Bob\", LastName = \"Johnson\" },\n                new { FirstName = \"Sam\", LastName = \"Jones\" },\n                new { FirstName = \"Tom\", LastName = \"Anderson\" }\n            }.ToList());\n            Assert.Equal(\"Smith\", grid.Rows[0][\"LastName\"]);\n            Assert.Equal(\"Jones\", grid.Rows[1][\"LastName\"]);\n            Assert.Equal(\"Johnson\", grid.Rows[2][\"LastName\"]);\n            Assert.Equal(\"Anderson\", grid.Rows[3][\"LastName\"]);\n        }\n\n        [Fact]\n        public void SortForNonGenericEnumerable()\n        {\n            var grid = new WebGrid(GetContext(), defaultSort: \"FirstName\").Bind(new NonGenericEnumerable(new[]\n            {\n                new Person { FirstName = \"Joe\", LastName = \"Smith\" },\n                new Person { FirstName = \"Bob\", LastName = \"Johnson\" },\n                new Person { FirstName = \"Sam\", LastName = \"Jones\" },\n                new Person { FirstName = \"Tom\", LastName = \"Anderson\" }\n            }));\n            Assert.Equal(\"Bob\", grid.Rows[0][\"FirstName\"]);\n            Assert.Equal(\"Joe\", grid.Rows[1][\"FirstName\"]);\n            Assert.Equal(\"Sam\", grid.Rows[2][\"FirstName\"]);\n            Assert.Equal(\"Tom\", grid.Rows[3][\"FirstName\"]);\n        }\n\n        [Fact]\n        public void SortForNonGenericEnumerableDescending()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"sort\"] = \"LastName\";\n            queryString[\"sortdir\"] = \"DESCENDING\";\n            var grid = new WebGrid(GetContext(queryString), defaultSort: \"FirstName\").Bind(new NonGenericEnumerable(new[]\n            {\n                new Person { FirstName = \"Joe\", LastName = \"Smith\" },\n                new Person { FirstName = \"Bob\", LastName = \"Johnson\" },\n                new Person { FirstName = \"Sam\", LastName = \"Jones\" },\n                new Person { FirstName = \"Tom\", LastName = \"Anderson\" }\n            }));\n            Assert.Equal(\"Smith\", grid.Rows[0][\"LastName\"]);\n            Assert.Equal(\"Jones\", grid.Rows[1][\"LastName\"]);\n            Assert.Equal(\"Johnson\", grid.Rows[2][\"LastName\"]);\n            Assert.Equal(\"Anderson\", grid.Rows[3][\"LastName\"]);\n        }\n\n        [Fact]\n        public void SortUrlDefaults()\n        {\n            var grid = new WebGrid(GetContext()).Bind(new[]\n            {\n                new { FirstName = \"Bob\" }\n            });\n            string html = grid.GetSortUrl(\"FirstName\");\n            Assert.Equal(\"?sort=FirstName&sortdir=ASC\", html.ToString());\n        }\n\n        [Fact]\n        public void SortUrlThrowsIfColumnNameIsEmpty()\n        {\n            var grid = new WebGrid(GetContext()).Bind(new[]\n            {\n                new { }, new { }\n            });\n            Assert.ThrowsArgumentNullOrEmptyString(() => { grid.GetSortUrl(String.Empty); }, \"column\");\n        }\n\n        [Fact]\n        public void SortUrlThrowsIfColumnNameIsNull()\n        {\n            var grid = new WebGrid(GetContext()).Bind(new[]\n            {\n                new { }, new { }\n            });\n            Assert.ThrowsArgumentNullOrEmptyString(() => { grid.GetSortUrl(null); }, \"column\");\n        }\n\n        [Fact]\n        public void SortUrlThrowsIfSortingIsDisabled()\n        {\n            var grid = new WebGrid(GetContext(), canSort: false).Bind(new[]\n            {\n                new { P1 = 1 }, new { P1 = 2 }\n            });\n            Assert.Throws<NotSupportedException>(() => { grid.GetSortUrl(\"P1\"); }, \"This operation is not supported when sorting is disabled for the \\\"WebGrid\\\" object.\");\n        }\n\n        [Fact]\n        public void SortWhenSortIsDisabled()\n        {\n            var grid = new WebGrid(GetContext(), defaultSort: \"FirstName\", canSort: false).Bind(new[]\n            {\n                new { FirstName = \"Joe\", LastName = \"Smith\" },\n                new { FirstName = \"Bob\", LastName = \"Johnson\" },\n                new { FirstName = \"Sam\", LastName = \"Jones\" },\n                new { FirstName = \"Tom\", LastName = \"Anderson\" }\n            });\n            Assert.Equal(\"Joe\", grid.Rows[0][\"FirstName\"]);\n            Assert.Equal(\"Bob\", grid.Rows[1][\"FirstName\"]);\n            Assert.Equal(\"Sam\", grid.Rows[2][\"FirstName\"]);\n            Assert.Equal(\"Tom\", grid.Rows[3][\"FirstName\"]);\n        }\n\n        [Fact]\n        public void SortWithNullValues()\n        {\n            var data = new[]\n            {\n                new { FirstName = (object)\"Joe\", LastName = \"Smith\" },\n                new { FirstName = (object)\"Bob\", LastName = \"Johnson\" },\n                new { FirstName = (object)null, LastName = \"Jones\" }\n            };\n            var grid = new WebGrid(GetContext(), defaultSort: \"FirstName\").Bind(data);\n\n            Assert.Equal(\"Jones\", grid.Rows[0][\"LastName\"]);\n            Assert.Equal(\"Bob\", grid.Rows[1][\"FirstName\"]);\n            Assert.Equal(\"Joe\", grid.Rows[2][\"FirstName\"]);\n\n            grid = new WebGrid(GetContext(), defaultSort: \"FirstName desc\").Bind(data);\n\n            Assert.Equal(\"Joe\", grid.Rows[0][\"FirstName\"]);\n            Assert.Equal(\"Bob\", grid.Rows[1][\"FirstName\"]);\n            Assert.Equal(\"Jones\", grid.Rows[2][\"LastName\"]);\n        }\n\n        [Fact]\n        public void SortWithMultipleNullValues()\n        {\n            var data = new[]\n            {\n                new { FirstName = (object)\"Joe\", LastName = \"Smith\" },\n                new { FirstName = (object)\"Bob\", LastName = \"Johnson\" },\n                new { FirstName = (object)null, LastName = \"Hughes\" },\n                new { FirstName = (object)null, LastName = \"Jones\" }\n            };\n            var grid = new WebGrid(GetContext(), defaultSort: \"FirstName\").Bind(data);\n\n            Assert.Equal(\"Hughes\", grid.Rows[0][\"LastName\"]);\n            Assert.Equal(\"Jones\", grid.Rows[1][\"LastName\"]);\n            Assert.Equal(\"Bob\", grid.Rows[2][\"FirstName\"]);\n            Assert.Equal(\"Joe\", grid.Rows[3][\"FirstName\"]);\n\n            grid = new WebGrid(GetContext(), defaultSort: \"FirstName desc\").Bind(data);\n\n            Assert.Equal(\"Joe\", grid.Rows[0][\"FirstName\"]);\n            Assert.Equal(\"Bob\", grid.Rows[1][\"FirstName\"]);\n            Assert.Equal(\"Hughes\", grid.Rows[2][\"LastName\"]);\n            Assert.Equal(\"Jones\", grid.Rows[3][\"LastName\"]);\n        }\n\n        [Fact]\n        public void SortWithMixedValuesDoesNotThrow()\n        {\n            var data = new[]\n            {\n                new { FirstName = (object)1, LastName = \"Smith\" },\n                new { FirstName = (object)\"Bob\", LastName = \"Johnson\" },\n                new { FirstName = (object)DBNull.Value, LastName = \"Jones\" }\n            };\n            var grid = new WebGrid(GetContext(), defaultSort: \"FirstName\").Bind(data);\n\n            Assert.NotNull(grid.Rows);\n\n            Assert.Equal(\"Smith\", grid.Rows[0][\"LastName\"]);\n            Assert.Equal(\"Johnson\", grid.Rows[1][\"LastName\"]);\n            Assert.Equal(\"Jones\", grid.Rows[2][\"LastName\"]);\n        }\n\n        [Fact]\n        public void SortWithUnsortableDoesNotThrow()\n        {\n            var object1 = new object();\n            var object2 = new object();\n            var data = new[]\n            {\n                new { Value = object1 },\n                new { Value = object2 }\n            };\n            var grid = new WebGrid(GetContext(), defaultSort: \"Value\").Bind(data);\n\n            Assert.NotNull(grid.Rows);\n\n            Assert.Equal(object1, grid.Rows[0][\"Value\"]);\n            Assert.Equal(object2, grid.Rows[1][\"Value\"]);\n        }\n\n        [Fact]\n        public void TableRenderingWithColumnTemplates()\n        {\n            var grid = new WebGrid(GetContext(), rowsPerPage: 3).Bind(new[]\n            {\n                new { P1 = 1, P2 = '2', P3 = \"3\" }\n            });\n            var html = grid.Table(displayHeader: false,\n                                  columns: new[]\n                                  {\n                                      grid.Column(\"P1\", format: item => { return \"<span>P1: \" + item.P1 + \"</span>\"; }),\n                                      grid.Column(\"P2\", format: item => { return new HtmlString(\"<span>P2: \" + item.P2 + \"</span>\"); }),\n                                      grid.Column(\"P3\", format: item => { return new HelperResult(tw => { tw.Write(\"<span>P3: \" + item.P3 + \"</span>\"); }); })\n                                  });\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(\n                \"<table><tbody><tr>\" +\n                \"<td>&lt;span&gt;P1: 1&lt;/span&gt;</td>\" +\n                \"<td><span>P2: 2</span></td>\" +\n                \"<td><span>P3: 3</span></td>\" +\n                \"</tr></tbody></table>\", html.ToString());\n            XhtmlAssert.Validate1_1(html);\n        }\n\n        [Fact]\n        public void TableRenderingWithDefaultCellValueOfCustom()\n        {\n            var grid = new WebGrid(GetContext(), rowsPerPage: 3).Bind(new[]\n            {\n                new { P1 = String.Empty, P2 = (string)null },\n            });\n            var html = grid.Table(fillEmptyRows: true, emptyRowCellValue: \"N/A\", displayHeader: false);\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(\n                \"<table><tbody>\" +\n                \"<tr><td></td><td></td></tr>\" +\n                \"<tr><td>N/A</td><td>N/A</td></tr>\" +\n                \"<tr><td>N/A</td><td>N/A</td></tr>\" +\n                \"</tbody></table>\", html.ToString());\n            XhtmlAssert.Validate1_1(html);\n        }\n\n        [Fact]\n        public void TableRenderingWithDefaultCellValueOfEmpty()\n        {\n            var grid = new WebGrid(GetContext(), rowsPerPage: 3).Bind(new[]\n            {\n                new { P1 = String.Empty, P2 = (string)null }\n            });\n            var html = grid.Table(fillEmptyRows: true, emptyRowCellValue: \"\", displayHeader: false);\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(\n                \"<table><tbody>\" +\n                \"<tr><td></td><td></td></tr>\" +\n                \"<tr><td></td><td></td></tr>\" +\n                \"<tr><td></td><td></td></tr>\" +\n                \"</tbody></table>\", html.ToString());\n            XhtmlAssert.Validate1_1(html);\n        }\n\n        [Fact]\n        public void TableRenderingWithDefaultCellValueOfNbsp()\n        {\n            var grid = new WebGrid(GetContext(), rowsPerPage: 3).Bind(new[]\n            {\n                new { P1 = String.Empty, P2 = (string)null }\n            });\n            var html = grid.Table(fillEmptyRows: true, displayHeader: false);\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(\n                \"<table><tbody>\" +\n                \"<tr><td></td><td></td></tr>\" +\n                \"<tr><td>&nbsp;</td><td>&nbsp;</td></tr>\" +\n                \"<tr><td>&nbsp;</td><td>&nbsp;</td></tr>\" +\n                \"</tbody></table>\", html.ToString());\n            XhtmlAssert.Validate1_1(html);\n        }\n\n        [Fact]\n        public void TableRenderingWithExclusions()\n        {\n            var grid = new WebGrid(GetContext()).Bind(new[]\n            {\n                new { P1 = 1, P2 = '2', P3 = \"3\" }\n            });\n            var html = grid.Table(exclusions: new string[] { \"P2\" });\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(\n                \"<table><thead><tr>\" +\n                \"<th scope=\\\"col\\\"><a href=\\\"?sort=P1&amp;sortdir=ASC\\\">P1</a></th>\" +\n                \"<th scope=\\\"col\\\"><a href=\\\"?sort=P3&amp;sortdir=ASC\\\">P3</a></th>\" +\n                \"</tr></thead>\" +\n                \"<tbody>\" +\n                \"<tr><td>1</td><td>3</td></tr>\" +\n                \"</tbody></table>\", html.ToString());\n            XhtmlAssert.Validate1_1(html);\n        }\n\n        [Fact]\n        public void TableRenderingWithNoStylesAndFillEmptyRows()\n        {\n            var grid = new WebGrid(GetContext(), rowsPerPage: 3).Bind(new[]\n            {\n                new { FirstName = \"Joe\", LastName = \"Smith\" }\n            });\n            var html = grid.Table(fillEmptyRows: true);\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(\n                \"<table><thead><tr>\" +\n                \"<th scope=\\\"col\\\"><a href=\\\"?sort=FirstName&amp;sortdir=ASC\\\">FirstName</a></th>\" +\n                \"<th scope=\\\"col\\\"><a href=\\\"?sort=LastName&amp;sortdir=ASC\\\">LastName</a></th>\" +\n                \"</tr></thead>\" +\n                \"<tbody>\" +\n                \"<tr><td>Joe</td><td>Smith</td></tr>\" +\n                \"<tr><td>&nbsp;</td><td>&nbsp;</td></tr>\" +\n                \"<tr><td>&nbsp;</td><td>&nbsp;</td></tr>\" +\n                \"</tbody></table>\", html.ToString());\n            XhtmlAssert.Validate1_1(html);\n        }\n\n        [Fact]\n        public void TableRenderingWithSortingDisabled()\n        {\n            var grid = new WebGrid(GetContext(), canSort: false).Bind(new[]\n            {\n                new { FirstName = \"Joe\", LastName = \"Smith\" }\n            });\n            var html = grid.Table();\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(\n                \"<table><thead><tr>\" +\n                \"<th scope=\\\"col\\\">FirstName</th>\" +\n                \"<th scope=\\\"col\\\">LastName</th>\" +\n                \"</tr></thead>\" +\n                \"<tbody>\" +\n                \"<tr><td>Joe</td><td>Smith</td></tr>\" +\n                \"</tbody></table>\", html.ToString());\n            XhtmlAssert.Validate1_1(html);\n        }\n\n        [Fact]\n        public void TableRenderingWithAttributes()\n        {\n            var grid = new WebGrid(GetContext()).Bind(new[]\n            {\n                new { FirstName = \"Joe\", LastName = \"Smith\" }\n            });\n            var html = grid.Table(htmlAttributes: new { id = \"my-table-id\", summary = \"Table summary\" });\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(\n                \"<table id=\\\"my-table-id\\\" summary=\\\"Table summary\\\"><thead><tr>\" +\n                \"<th scope=\\\"col\\\"><a href=\\\"?sort=FirstName&amp;sortdir=ASC\\\">FirstName</a></th>\" +\n                \"<th scope=\\\"col\\\"><a href=\\\"?sort=LastName&amp;sortdir=ASC\\\">LastName</a></th>\" +\n                \"</tr></thead>\" +\n                \"<tbody>\" +\n                \"<tr><td>Joe</td><td>Smith</td></tr>\" +\n                \"</tbody></table>\", html.ToString());\n            XhtmlAssert.Validate1_1(html);\n        }\n\n        [Fact]\n        public void TableRenderingEncodesAttributes()\n        {\n            var grid = new WebGrid(GetContext()).Bind(new[]\n            {\n                new { FirstName = \"Joe\", LastName = \"Smith\" }\n            });\n            var html = grid.Table(htmlAttributes: new { summary = \"\\\"<Table summary\" });\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(\n                \"<table summary=\\\"&quot;&lt;Table summary\\\"><thead><tr>\" +\n                \"<th scope=\\\"col\\\"><a href=\\\"?sort=FirstName&amp;sortdir=ASC\\\">FirstName</a></th>\" +\n                \"<th scope=\\\"col\\\"><a href=\\\"?sort=LastName&amp;sortdir=ASC\\\">LastName</a></th>\" +\n                \"</tr></thead>\" +\n                \"<tbody>\" +\n                \"<tr><td>Joe</td><td>Smith</td></tr>\" +\n                \"</tbody></table>\", html.ToString());\n            XhtmlAssert.Validate1_1(html);\n        }\n\n        [Fact]\n        public void TableRenderingIsNotAffectedWhenAttributesIsNull()\n        {\n            var grid = new WebGrid(GetContext()).Bind(new[]\n            {\n                new { FirstName = \"Joe\", LastName = \"Smith\" }\n            });\n            var html = grid.Table(htmlAttributes: null);\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(\n                \"<table><thead><tr>\" +\n                \"<th scope=\\\"col\\\"><a href=\\\"?sort=FirstName&amp;sortdir=ASC\\\">FirstName</a></th>\" +\n                \"<th scope=\\\"col\\\"><a href=\\\"?sort=LastName&amp;sortdir=ASC\\\">LastName</a></th>\" +\n                \"</tr></thead>\" +\n                \"<tbody>\" +\n                \"<tr><td>Joe</td><td>Smith</td></tr>\" +\n                \"</tbody></table>\", html.ToString());\n            XhtmlAssert.Validate1_1(html);\n        }\n\n        [Fact]\n        public void TableRenderingIsNotAffectedWhenAttributesIsEmpty()\n        {\n            var grid = new WebGrid(GetContext()).Bind(new[]\n            {\n                new { FirstName = \"Joe\", LastName = \"Smith\" }\n            });\n            var html = grid.Table(htmlAttributes: new { });\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(\n                \"<table><thead><tr>\" +\n                \"<th scope=\\\"col\\\"><a href=\\\"?sort=FirstName&amp;sortdir=ASC\\\">FirstName</a></th>\" +\n                \"<th scope=\\\"col\\\"><a href=\\\"?sort=LastName&amp;sortdir=ASC\\\">LastName</a></th>\" +\n                \"</tr></thead>\" +\n                \"<tbody>\" +\n                \"<tr><td>Joe</td><td>Smith</td></tr>\" +\n                \"</tbody></table>\", html.ToString());\n            XhtmlAssert.Validate1_1(html);\n        }\n\n        [Fact]\n        public void TableRenderingWithStyles()\n        {\n            NameValueCollection queryString = new NameValueCollection();\n            queryString[\"row\"] = \"1\";\n            var grid = new WebGrid(GetContext(queryString), rowsPerPage: 4).Bind(new[]\n            {\n                new { FirstName = \"Joe\", LastName = \"Smith\" },\n                new { FirstName = \"Bob\", LastName = \"Johnson\" }\n            });\n            var html = grid.Table(tableStyle: \"tbl\", headerStyle: \"hdr\", footerStyle: \"ftr\",\n                                  rowStyle: \"row\", alternatingRowStyle: \"arow\", selectedRowStyle: \"sel\", fillEmptyRows: true,\n                                  footer: item => \"footer text\",\n                                  columns: new[]\n                                  {\n                                      grid.Column(\"firstName\", style: \"c1\", canSort: false),\n                                      grid.Column(\"lastName\", style: \"c2\", canSort: false)\n                                  });\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(\n                \"<table class=\\\"tbl\\\"><thead><tr class=\\\"hdr\\\">\" +\n                \"<th scope=\\\"col\\\">firstName</th><th scope=\\\"col\\\">lastName</th>\" +\n                \"</tr></thead>\" +\n                \"<tfoot>\" +\n                \"<tr class=\\\"ftr\\\"><td colspan=\\\"2\\\">footer text</td></tr>\" +\n                \"</tfoot>\" +\n                \"<tbody>\" +\n                \"<tr class=\\\"row sel\\\"><td class=\\\"c1\\\">Joe</td><td class=\\\"c2\\\">Smith</td></tr>\" +\n                \"<tr class=\\\"arow\\\"><td class=\\\"c1\\\">Bob</td><td class=\\\"c2\\\">Johnson</td></tr>\" +\n                \"<tr class=\\\"row\\\"><td class=\\\"c1\\\">&nbsp;</td><td class=\\\"c2\\\">&nbsp;</td></tr>\" +\n                \"<tr class=\\\"arow\\\"><td class=\\\"c1\\\">&nbsp;</td><td class=\\\"c2\\\">&nbsp;</td></tr>\" +\n                \"</tbody></table>\", html.ToString());\n            XhtmlAssert.Validate1_1(html);\n        }\n\n        [Fact]\n        public void TableWithAjax()\n        {\n            var grid = new WebGrid(GetContext(), ajaxUpdateContainerId: \"grid\").Bind(new[]\n            {\n                new { First = \"First\", Second = \"Second\" }\n            });\n            string html = grid.Table().ToString();\n            Assert.Contains(\"<script\", html);\n            Assert.Contains(\"swhgajax=\\\"true\\\"\", html);\n        }\n\n        [Fact]\n        public void TableWithAjaxAndCallback()\n        {\n            var grid = new WebGrid(GetContext(), ajaxUpdateContainerId: \"grid\", ajaxUpdateCallback: \"myCallback\").Bind(new[]\n            {\n                new { First = \"First\", Second = \"Second\" }\n            });\n            string html = grid.Table().ToString();\n            Assert.Contains(\"<script\", html);\n            Assert.Contains(\"myCallback\", html);\n        }\n\n        [Fact]\n        public void WebGridEncodesAjaxDataStrings()\n        {\n            var grid = new WebGrid(GetContext(), ajaxUpdateContainerId: \"'grid'\", ajaxUpdateCallback: \"'myCallback'\").Bind(new[]\n            {\n                new { First = \"First\", Second = \"Second\" }\n            });\n            string html = grid.Table().ToString();\n            Assert.Contains(@\"&#39;grid&#39;\", html);\n            Assert.Contains(@\"&#39;myCallback&#39;\", html);\n        }\n\n        [Fact]\n        public void WebGridThrowsIfOperationsArePerformedBeforeBinding()\n        {\n            // Arrange\n            string errorMessage = \"A data source must be bound before this operation can be performed.\";\n            var grid = new WebGrid(GetContext());\n\n            // Act and Assert\n            Assert.Throws<InvalidOperationException>(() => { var rows = grid.Rows; }, errorMessage);\n            Assert.Throws<InvalidOperationException>(() => { int count = grid.TotalRowCount; }, errorMessage);\n            Assert.Throws<InvalidOperationException>(() => grid.GetHtml().ToString(), errorMessage);\n            Assert.Throws<InvalidOperationException>(() => grid.Pager().ToString(), errorMessage);\n            Assert.Throws<InvalidOperationException>(() => grid.Table().ToString(), errorMessage);\n            Assert.Throws<InvalidOperationException>(() =>\n            {\n                grid.SelectedIndex = 1;\n                var row = grid.SelectedRow;\n            }, errorMessage);\n        }\n\n        [Fact]\n        public void WebGridThrowsIfBindingIsPerformedWhenAlreadyBound()\n        {\n            // Arrange\n            var grid = new WebGrid(GetContext());\n            var values = Enumerable.Range(0, 10).Cast<dynamic>();\n\n            // Act\n            grid.Bind(values);\n\n            // Assert\n            Assert.Throws<InvalidOperationException>(() => grid.Bind(values), \"The WebGrid instance is already bound to a data source.\");\n        }\n\n        [Fact]\n        public void GetElementTypeReturnsDynamicTypeIfElementIsDynamic()\n        {\n            // Arrange\n            IEnumerable<dynamic> elements = Dynamics(new[] { new Person { FirstName = \"Foo\", LastName = \"Bar\" } });\n\n            // Act\n            Type type = WebGrid.GetElementType(elements);\n\n            // Assert\n            Assert.Equal(typeof(IDynamicMetaObjectProvider), type);\n        }\n\n        [Fact]\n        public void GetElementTypeReturnsEnumerableTypeIfFirstInstanceIsNotDynamic()\n        {\n            // Arrange\n            IEnumerable<dynamic> elements = Iterator();\n\n            // Act\n            Type type = WebGrid.GetElementType(elements);\n\n            // Assert\n            Assert.Equal(typeof(Person), type);\n        }\n\n        [Fact]\n        public void TableThrowsIfQueryStringDerivedSortColumnIsExcluded()\n        {\n            // Arrange\n            NameValueCollection collection = new NameValueCollection();\n            collection[\"sort\"] = \"Salary\";\n            var context = GetContext(collection);\n            IList<Employee> employees = new List<Employee>();\n            employees.Add(new Employee { Name = \"A\", Salary = 5, Manager = new Employee { Name = \"-\" } });\n            employees.Add(new Employee { Name = \"B\", Salary = 20, Manager = employees[0] });\n            employees.Add(new Employee { Name = \"C\", Salary = 15, Manager = employees[0] });\n            employees.Add(new Employee { Name = \"D\", Salary = 5, Manager = employees[1] });\n\n            var grid = new WebGrid(context, defaultSort: \"Name\").Bind(employees);\n\n            // Act and Assert\n            Assert.Throws<InvalidOperationException>(() => grid.GetHtml(exclusions: new[] { \"Salary\" }), \"Column \\\"Salary\\\" does not exist.\");\n        }\n\n        [Fact]\n        public void TableThrowsIfQueryStringDerivedSortColumnDoesNotExistInColumnsArgument()\n        {\n            // Arrange\n            NameValueCollection collection = new NameValueCollection();\n            collection[\"sort\"] = \"Salary\";\n            var context = GetContext(collection);\n            IList<Employee> employees = new List<Employee>();\n            employees.Add(new Employee { Name = \"A\", Salary = 5, Manager = new Employee { Name = \"-\" } });\n            employees.Add(new Employee { Name = \"B\", Salary = 20, Manager = employees[0] });\n            employees.Add(new Employee { Name = \"C\", Salary = 15, Manager = employees[0] });\n            employees.Add(new Employee { Name = \"D\", Salary = 5, Manager = employees[1] });\n\n            var grid = new WebGrid(context, canSort: true, defaultSort: \"Name\").Bind(employees);\n\n            // Act and Assert\n            Assert.Throws<InvalidOperationException>(\n                () => grid.Table(columns: new[] { new WebGridColumn { ColumnName = \"Name\" }, new WebGridColumn { ColumnName = \"Manager.Name\" } }),\n                \"Column \\\"Salary\\\" does not exist.\");\n        }\n\n        [Fact]\n        public void TableDoesNotThrowIfQueryStringDerivedSortColumnIsVisibleButNotSortable()\n        {\n            // Arrange\n            NameValueCollection collection = new NameValueCollection();\n            collection[\"sort\"] = \"Salary\";\n            collection[\"sortDir\"] = \"Desc\";\n            var context = GetContext(collection);\n            IList<Employee> employees = new List<Employee>();\n            employees.Add(new Employee { Name = \"A\", Salary = 5, Manager = new Employee { Name = \"-\" } });\n            employees.Add(new Employee { Name = \"B\", Salary = 20, Manager = employees[0] });\n            employees.Add(new Employee { Name = \"C\", Salary = 15, Manager = employees[0] });\n            employees.Add(new Employee { Name = \"D\", Salary = 10, Manager = employees[1] });\n\n            var grid = new WebGrid(context, canSort: true).Bind(employees);\n\n            // Act\n            var html = grid.Table(columns: new[] { new WebGridColumn { ColumnName = \"Salary\", CanSort = false } });\n\n            // Assert\n            Assert.NotNull(html);\n            Assert.Equal(20, grid.Rows[0][\"Salary\"]);\n            Assert.Equal(15, grid.Rows[1][\"Salary\"]);\n            Assert.Equal(10, grid.Rows[2][\"Salary\"]);\n            Assert.Equal(5, grid.Rows[3][\"Salary\"]);\n        }\n\n        [Fact]\n        public void TableThrowsIfComplexPropertyIsUnsortable()\n        {\n            // Arrange\n            NameValueCollection collection = new NameValueCollection();\n            collection[\"sort\"] = \"Manager.Salary\";\n            var context = GetContext(collection);\n            IList<Employee> employees = new List<Employee>();\n            employees.Add(new Employee { Name = \"A\", Salary = 5, Manager = new Employee { Name = \"-\" } });\n            employees.Add(new Employee { Name = \"B\", Salary = 20, Manager = employees[0] });\n            employees.Add(new Employee { Name = \"C\", Salary = 15, Manager = employees[0] });\n            employees.Add(new Employee { Name = \"D\", Salary = 5, Manager = employees[1] });\n            var grid = new WebGrid(context).Bind(employees, columnNames: new[] { \"Name\", \"Manager.Name\" });\n\n            // Act and Assert\n            Assert.Throws<InvalidOperationException>(() => grid.GetHtml(),\n                                                              \"Column \\\"Manager.Salary\\\" does not exist.\");\n        }\n\n        [Fact]\n        public void TableDoesNotThrowIfUnsortableColumnIsExplicitlySpecifiedByUser()\n        {\n            // Arrange\n            var context = GetContext();\n            IList<Employee> employees = new List<Employee>();\n            employees.Add(new Employee { Name = \"A\", Salary = 5, Manager = new Employee { Name = \"-\" } });\n            employees.Add(new Employee { Name = \"C\", Salary = 15, Manager = employees[0] });\n            employees.Add(new Employee { Name = \"D\", Salary = 10, Manager = employees[1] });\n\n            // Act\n            var grid = new WebGrid(context).Bind(employees, columnNames: new[] { \"Name\", \"Manager.Name\" });\n            grid.SortColumn = \"Salary\";\n            var html = grid.Table();\n\n            // Assert\n            Assert.Equal(5, grid.Rows[0][\"Salary\"]);\n            Assert.Equal(10, grid.Rows[1][\"Salary\"]);\n            Assert.Equal(15, grid.Rows[2][\"Salary\"]);\n\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(\n                \"<table><thead><tr>\"\n                + \"<th scope=\\\"col\\\"><a href=\\\"?sort=Name&amp;sortdir=ASC\\\">Name</a></th>\"\n                + \"<th scope=\\\"col\\\"><a href=\\\"?sort=Manager.Name&amp;sortdir=ASC\\\">Manager.Name</a></th>\"\n                + \"</tr></thead><tbody>\"\n                + \"<tr><td>A</td><td>-</td></tr>\"\n                + \"<tr><td>D</td><td>C</td></tr>\"\n                + \"<tr><td>C</td><td>A</td></tr>\"\n                + \"</tbody></table>\", html.ToString());\n        }\n\n        [Fact]\n        public void TableDoesNotThrowIfUnsortableColumnIsDefaultSortColumn()\n        {\n            // Arrange\n            var context = GetContext();\n            IList<Employee> employees = new List<Employee>();\n            employees.Add(new Employee { Name = \"A\", Salary = 5, Manager = new Employee { Name = \"-\" } });\n            employees.Add(new Employee { Name = \"C\", Salary = 15, Manager = employees[0] });\n            employees.Add(new Employee { Name = \"D\", Salary = 10, Manager = employees[1] });\n\n            // Act\n            var grid = new WebGrid(context, defaultSort: \"Salary\").Bind(employees, columnNames: new[] { \"Name\", \"Manager.Name\" });\n            var html = grid.Table();\n\n            // Assert\n            Assert.Equal(5, grid.Rows[0][\"Salary\"]);\n            Assert.Equal(10, grid.Rows[1][\"Salary\"]);\n            Assert.Equal(15, grid.Rows[2][\"Salary\"]);\n\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(\n                \"<table><thead><tr>\"\n                + \"<th scope=\\\"col\\\"><a href=\\\"?sort=Name&amp;sortdir=ASC\\\">Name</a></th>\"\n                + \"<th scope=\\\"col\\\"><a href=\\\"?sort=Manager.Name&amp;sortdir=ASC\\\">Manager.Name</a></th>\"\n                + \"</tr></thead><tbody>\"\n                + \"<tr><td>A</td><td>-</td></tr>\"\n                + \"<tr><td>D</td><td>C</td></tr>\"\n                + \"<tr><td>C</td><td>A</td></tr>\"\n                + \"</tbody></table>\", html.ToString());\n        }\n\n        [Fact]\n        public void CustomSorter()\n        {\n            // Arrange\n            var context = GetContext();\n            IList<Employee> employees = new List<Employee>();\n            employees.Add(new Employee { Name = \"A\", Salary = 10, Manager = new Employee { Name = \"C\" } });\n            employees.Add(new Employee { Name = \"B\", Salary = 20, Manager = null });\n            employees.Add(new Employee { Name = \"C\", Salary = 30, Manager = new Employee { Name = \"A\" } });\n\n            // Act\n            var grid = new WebGrid(context, defaultSort: \"Salary\")\n                .AddSorter(\"Manager.Name\", (Employee x) => (x == null || x.Manager == null) ? null : x.Manager.Name);\n\n            grid.Bind(employees);\n\n            grid.SortColumn = \"Manager.Name\";\n            grid.SortDirection = SortDirection.Ascending;\n\n            var html = grid.Table(columns: grid.Columns(\n                grid.Column(\"Name\"),\n                grid.Column(\"Manager.Name\",\n                header: \"Manager\",\n                format: item => item.Manager == null ? \"\" : item.Manager.Name)));\n\n            // Assert\n            Assert.Equal(20, grid.Rows[0][\"Salary\"]);\n            Assert.Equal(30, grid.Rows[1][\"Salary\"]);\n            Assert.Equal(10, grid.Rows[2][\"Salary\"]);\n\n            UnitTestHelper.AssertEqualsIgnoreWhitespace(\n                \"<table><thead><tr>\"\n                + \"<th scope=\\\"col\\\"><a href=\\\"?sort=Name&amp;sortdir=ASC\\\">Name</a></th>\"\n                + \"<th scope=\\\"col\\\"><a href=\\\"?sort=Manager.Name&amp;sortdir=DESC\\\">Manager</a></th>\"\n                + \"</tr></thead><tbody>\"\n                + \"<tr><td>B</td><td></td></tr>\"\n                + \"<tr><td>C</td><td>A</td></tr>\"\n                + \"<tr><td>A</td><td>C</td></tr>\"\n                + \"</tbody></table>\", html.ToString());\n        }\n\n        private static IEnumerable<Person> Iterator()\n        {\n            yield return new Person { FirstName = \"Foo\", LastName = \"Bar\" };\n        }\n\n        [Fact]\n        public void GetElementTypeReturnsEnumerableTypeIfCollectionPassedImplementsEnumerable()\n        {\n            // Arrange\n            IList<Person> listElements = new List<Person> { new Person { FirstName = \"Foo\", LastName = \"Bar\" } };\n            HashSet<dynamic> setElements = new HashSet<dynamic> { new DynamicWrapper(new Person { FirstName = \"Foo\", LastName = \"Bar\" }) };\n\n            // Act\n            Type listType = WebGrid.GetElementType(listElements);\n            Type setType = WebGrid.GetElementType(setElements);\n\n            // Assert\n            Assert.Equal(typeof(Person), listType);\n            Assert.Equal(typeof(IDynamicMetaObjectProvider), setType);\n        }\n\n        [Fact]\n        public void GetElementTypeReturnsEnumerableTypeIfCollectionImplementsEnumerable()\n        {\n            // Arrange\n            IEnumerable<Person> elements = new NonGenericEnumerable(new[] { new Person { FirstName = \"Foo\", LastName = \"Bar\" } });\n\n            // Act\n            Type type = WebGrid.GetElementType(elements);\n\n            // Assert\n            Assert.Equal(typeof(Person), type);\n        }\n\n        [Fact]\n        public void GetElementTypeReturnsEnumerableTypeIfCollectionIsIEnumerable()\n        {\n            // Arrange\n            IEnumerable<Person> elements = new GenericEnumerable<Person>(new[] { new Person { FirstName = \"Foo\", LastName = \"Bar\" } });\n\n            // Act\n            Type type = WebGrid.GetElementType(elements);\n\n            // Assert\n            Assert.Equal(typeof(Person), type);\n        }\n\n        [Fact]\n        public void GetElementTypeDoesNotThrowIfTypeIsNotGeneric()\n        {\n            // Arrange\n            IEnumerable<dynamic> elements = new[] { new Person { FirstName = \"Foo\", LastName = \"Bar\" } };\n\n            // Act\n            Type type = WebGrid.GetElementType(elements);\n\n            // Assert\n            Assert.Equal(typeof(Person), type);\n        }\n\n        [Fact]\n        public void WebGridWithAttributesFromAnonymousObject_WithUnderscoreInName_TransformsUnderscoresToDashs()\n        {\n            // Arrange\n            const string expected = @\"data-name=\"\"value\"\"\";\n            const string unexpected = @\"data_name=\"\"value\"\"\";\n            var attributes = new { data_name = \"value\" };\n\n            var grid = new WebGrid(GetContext(), ajaxUpdateContainerId: \"grid\")\n                    .Bind(new[]\n            {\n                new { P1 = 1, P2 = '2', P3 = \"3\" },\n                new { P1 = 4, P2 = '5', P3 = \"6\" }\n            });\n\n            // Act\n            var htmlString = grid.GetHtml(htmlAttributes: attributes).ToHtmlString();\n\n            // Assert\n            Assert.DoesNotContain(unexpected, htmlString);\n            Assert.Contains(expected, htmlString);\n        }\n\n\n        private static IEnumerable<dynamic> Dynamics(params object[] objects)\n        {\n            return (from o in objects\n                    select new DynamicWrapper(o)).ToArray();\n        }\n\n        private static HttpContextBase GetContext(NameValueCollection queryString = null)\n        {\n            Mock<HttpRequestBase> requestMock = new Mock<HttpRequestBase>();\n            requestMock.Setup(request => request.QueryString).Returns(queryString ?? new NameValueCollection());\n\n            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>();\n            contextMock.Setup(context => context.Request).Returns(requestMock.Object);\n            contextMock.Setup(context => context.Items).Returns(new Hashtable());\n            return contextMock.Object;\n        }\n\n        class Person\n        {\n            public string FirstName { get; set; }\n            public string LastName { get; set; }\n        }\n\n        private class Employee\n        {\n            public string Name { get; set; }\n            public int Salary { get; set; }\n            public Employee Manager { get; set; }\n        }\n\n        class NonGenericEnumerable : IEnumerable<Person>\n        {\n            private IEnumerable<Person> _source;\n\n            public NonGenericEnumerable(IEnumerable<Person> source)\n            {\n                _source = source;\n            }\n\n            public IEnumerator<Person> GetEnumerator()\n            {\n                return _source.GetEnumerator();\n            }\n\n            IEnumerator IEnumerable.GetEnumerator()\n            {\n                return GetEnumerator();\n            }\n        }\n\n        class GenericEnumerable<T> : IEnumerable<T>\n        {\n            private IEnumerable<T> _source;\n\n            public GenericEnumerable(IEnumerable<T> source)\n            {\n                _source = source;\n            }\n\n            public IEnumerator<T> GetEnumerator()\n            {\n                return _source.GetEnumerator();\n            }\n\n            IEnumerator IEnumerable.GetEnumerator()\n            {\n                return GetEnumerator();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Helpers.Test/WebImageTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.Drawing.Imaging;\nusing System.IO;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Helpers.Test\n{\n    public class WebImageTest\n    {\n        private static readonly byte[] _JpgImageBytes = TestFile.Create(\"LambdaFinal.jpg\").ReadAllBytes();\n        private static readonly byte[] _BmpImageBytes = TestFile.Create(\"logo.bmp\").ReadAllBytes();\n        private static readonly byte[] _PngImageBytes = TestFile.Create(\"NETLogo.png\").ReadAllBytes();\n        private static readonly byte[] _IcoImageBytes = TestFile.Create(\"Test.ico\").ReadAllBytes();\n\n        [Fact]\n        public void ConstructorThrowsWhenFilePathIsNull()\n        {\n            Assert.ThrowsArgument(() =>\n                                                    new WebImage(GetContext(), s => new byte[] { }, filePath: null), \"filePath\", \"Value cannot be null or an empty string.\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsWhenFilePathIsEmpty()\n        {\n            Assert.ThrowsArgument(() =>\n                                                    new WebImage(GetContext(), s => new byte[] { }, filePath: String.Empty), \"filePath\", \"Value cannot be null or an empty string.\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsWhenFilePathIsInvalid()\n        {\n            Assert.Throws<DirectoryNotFoundException>(() =>\n                                                               new WebImage(GetContext(), s => { throw new DirectoryNotFoundException(); }, @\"x:\\this\\does\\not\\exist.jpg\"));\n        }\n\n        [Fact]\n        public void ConstructorThrowsWhenFileContentIsInvalid()\n        {\n            byte[] imageContent = new byte[] { 32, 111, 209, 138, 76, 32 };\n            Assert.ThrowsArgument(() => new WebImage(imageContent), \"content\",\n                                                    \"An image could not be constructed from the content provided.\");\n        }\n\n        [Fact]\n        public void FilePathReturnsCorrectPath()\n        {\n            // Arrange\n            string imageName = @\"x:\\My-test-image.png\";\n\n            // Act\n            WebImage image = new WebImage(GetContext(), s => _PngImageBytes, imageName);\n\n            // Assert\n            Assert.Equal(imageName, image.FileName);\n        }\n\n        [Fact]\n        public void FilePathCanBeSet()\n        {\n            // Arrange\n            string originalPath = @\"x:\\somePath.png\";\n            string newPath = @\"x:\\someOtherPath.jpg\";\n\n            // Act\n            WebImage image = new WebImage(GetContext(), s => _PngImageBytes, originalPath);\n            image.FileName = newPath;\n\n            // Assert\n            Assert.Equal(newPath, image.FileName);\n        }\n\n        [Fact]\n        public void SimpleGetBytesClonesArray()\n        {\n            WebImage image = new WebImage(_PngImageBytes);\n\n            byte[] returnedContent = image.GetBytes();\n\n            Assert.False(ReferenceEquals(_PngImageBytes, returnedContent), \"GetBytes should clone array.\");\n            Assert.Equal(_PngImageBytes, returnedContent);\n        }\n\n        [Fact]\n        public void WebImagePreservesOriginalFormatFromFile()\n        {\n            WebImage image = new WebImage(_PngImageBytes);\n\n            byte[] returnedContent = image.GetBytes();\n\n            // If format was changed; content would be different\n            Assert.Equal(_PngImageBytes, returnedContent);\n        }\n\n        [Fact]\n        public void WebImagePreservesOriginalFormatFromStream()\n        {\n            WebImage image = null;\n            byte[] originalContent = _PngImageBytes;\n            using (MemoryStream stream = new MemoryStream(originalContent))\n            {\n                image = new WebImage(stream);\n            } // dispose stream; WebImage should have no dependency on it\n\n            byte[] returnedContent = image.GetBytes();\n\n            // If format was changed; content would be different\n            Assert.Equal(originalContent, returnedContent);\n        }\n\n        [Fact]\n        public void WebImageCorrectlyReadsFromNoSeekStream()\n        {\n            WebImage image = null;\n\n            byte[] originalContent = _PngImageBytes;\n            using (MemoryStream stream = new MemoryStream(originalContent))\n            {\n                TestStream ts = new TestStream(stream);\n                image = new WebImage(ts);\n            } // dispose stream; WebImage should have no dependency on it\n\n            byte[] returnedContent = image.GetBytes();\n\n            // If chunks are not assembled correctly; content would be different and image would be corrupted.\n            Assert.Equal(originalContent, returnedContent);\n            Assert.Equal(\"png\", image.ImageFormat);\n        }\n\n        [Fact]\n        public void GetBytesWithNullReturnsClonesArray()\n        {\n            byte[] originalContent = _BmpImageBytes;\n            WebImage image = new WebImage(originalContent);\n\n            byte[] returnedContent = image.GetBytes();\n\n            Assert.False(ReferenceEquals(originalContent, returnedContent), \"GetBytes with string null should clone array.\");\n            Assert.Equal(originalContent, returnedContent);\n        }\n\n        [Fact]\n        public void GetBytesWithSameFormatReturnsSameFormat()\n        {\n            byte[] originalContent = _JpgImageBytes;\n            WebImage image = new WebImage(originalContent);\n\n            byte[] returnedContent = image.GetBytes(\"jpeg\");\n\n            Assert.False(ReferenceEquals(originalContent, returnedContent), \"GetBytes with string null should clone array.\");\n            Assert.Equal(originalContent, returnedContent);\n        }\n\n        [Fact]\n        public void GetBytesWithDifferentFormatReturnsExpectedFormat()\n        {\n            byte[] originalContent = _BmpImageBytes;\n            WebImage image = new WebImage(originalContent);\n\n            // Request different format\n            byte[] returnedContent = image.GetBytes(\"jpg\");\n\n            Assert.False(ReferenceEquals(originalContent, returnedContent), \"GetBytes with string format should clone array.\");\n            using (MemoryStream stream = new MemoryStream(returnedContent))\n            {\n                using (Image tempImage = Image.FromStream(stream))\n                {\n                    Assert.Equal(ImageFormat.Jpeg, tempImage.RawFormat);\n                }\n            }\n        }\n\n        [Fact]\n        public void GetBytesWithSameFormatReturnsSameFormatWhenCreatedFromFile()\n        {\n            byte[] originalContent = _BmpImageBytes;\n            // Format is not set during construction.\n            WebImage image = new WebImage(_BmpImageBytes);\n\n            byte[] returnedContent = image.GetBytes(\"bmp\");\n\n            Assert.False(ReferenceEquals(originalContent, returnedContent), \"GetBytes with string format should clone array.\");\n            Assert.Equal(originalContent, returnedContent);\n        }\n\n        [Fact]\n        public void GetBytesWithNoFormatReturnsInitialFormatEvenAfterTransformations()\n        {\n            byte[] originalContent = _BmpImageBytes;\n            // Format is not set during construction.\n            WebImage image = new WebImage(_BmpImageBytes);\n            image.Crop(top: 10, bottom: 10);\n\n            byte[] returnedContent = image.GetBytes();\n\n            Assert.NotEqual(originalContent, returnedContent);\n            using (MemoryStream stream = new MemoryStream(returnedContent))\n            {\n                using (Image tempImage = Image.FromStream(stream))\n                {\n                    Assert.Equal(ImageFormat.Bmp, tempImage.RawFormat);\n                }\n            }\n        }\n\n        [Fact]\n        public void GetBytesThrowsOnIncorrectFormat()\n        {\n            WebImage image = new WebImage(_JpgImageBytes);\n            Assert.ThrowsArgument(\n                () => image.GetBytes(\"bmpx\"),\n                \"format\",\n                \"\\\"bmpx\\\" is invalid image format. Valid values are image format names like: \\\"JPEG\\\", \\\"BMP\\\", \\\"GIF\\\", \\\"PNG\\\", etc.\");\n        }\n\n        [Fact]\n        public void GetBytesWithDifferentFormatReturnsExpectedFormatWhenCreatedFromFile()\n        {\n            // Format is not set during construction.\n            WebImage image = new WebImage(_PngImageBytes);\n\n            // Request different format\n            byte[] returnedContent = image.GetBytes(\"jpg\");\n\n            WebImage newImage = new WebImage(returnedContent);\n\n            Assert.Equal(\"jpeg\", newImage.ImageFormat);\n        }\n\n        [Fact]\n        public void GetImageFromRequestReturnsNullForIncorrectMimeType()\n        {\n            // Arrange\n            Mock<HttpPostedFileBase> postedFile = new Mock<HttpPostedFileBase>();\n            postedFile.Setup(c => c.FileName).Returns(\"index.cshtml\");\n            postedFile.Setup(c => c.ContentType).Returns(\"image/jpg\");\n\n            Mock<HttpFileCollectionBase> files = new Mock<HttpFileCollectionBase>();\n            files.Setup(c => c[0]).Returns(postedFile.Object);\n            Mock<HttpRequestBase> request = new Mock<HttpRequestBase>();\n            request.Setup(r => r.Files).Returns(files.Object);\n\n            // Act and Assert\n            Assert.Null(WebImage.GetImageFromRequest(request.Object));\n        }\n\n        public static IEnumerable<object[]> GetImageFromRequestDeterminesMimeTypeFromExtensionData\n        {\n            get\n            {\n                yield return new object[] { \"index.jpeg\", _JpgImageBytes, \"jpeg\" };\n                yield return new object[] { \"file1.jpg\", _JpgImageBytes, \"jpeg\" };\n                yield return new object[] { \"file4.png\", _PngImageBytes, \"png\" };\n                yield return new object[] { \"file5.ico\", _IcoImageBytes, \"icon\" };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"GetImageFromRequestDeterminesMimeTypeFromExtensionData\")]\n        public void GetImageFromRequestDeterminesMimeTypeFromExtension(string fileName,\n                                                                       byte[] content,\n                                                                       string expectedExtension)\n        {\n            // Arrange\n            Mock<HttpPostedFileBase> postedFile = new Mock<HttpPostedFileBase>();\n            postedFile.Setup(c => c.FileName).Returns(fileName);\n            postedFile.Setup(c => c.ContentType).Returns(\"application/octet-stream\");\n            postedFile.Setup(c => c.ContentLength).Returns(1);\n            postedFile.Setup(c => c.InputStream).Returns(new MemoryStream(content));\n\n            Mock<HttpFileCollectionBase> files = new Mock<HttpFileCollectionBase>();\n            files.Setup(c => c.Count).Returns(1);\n            files.Setup(c => c[0]).Returns(postedFile.Object);\n            Mock<HttpRequestBase> request = new Mock<HttpRequestBase>();\n            request.Setup(r => r.Files).Returns(files.Object);\n\n            // Act\n            WebImage image = WebImage.GetImageFromRequest(request.Object);\n\n            // Assert\n            Assert.NotNull(image);\n            Assert.Equal(expectedExtension, image.ImageFormat);\n        }\n\n        [Fact]\n        public void GetImageFromRequestIsCaseInsensitive()\n        {\n            // Arrange\n            Mock<HttpPostedFileBase> postedFile = new Mock<HttpPostedFileBase>();\n            postedFile.SetupGet(c => c.FileName).Returns(\"index.JPg\");\n            postedFile.SetupGet(c => c.ContentType).Returns(\"application/octet-stream\");\n            postedFile.SetupGet(c => c.ContentLength).Returns(1);\n            postedFile.SetupGet(c => c.InputStream).Returns(new MemoryStream(_JpgImageBytes));\n\n            Mock<HttpFileCollectionBase> files = new Mock<HttpFileCollectionBase>();\n            files.Setup(c => c.Count).Returns(1);\n            files.Setup(c => c[0]).Returns(postedFile.Object);\n            Mock<HttpRequestBase> request = new Mock<HttpRequestBase>();\n            request.Setup(r => r.Files).Returns(files.Object);\n\n            // Act\n            WebImage image = WebImage.GetImageFromRequest(request.Object);\n\n            // Assert\n            Assert.NotNull(image);\n            Assert.Equal(\"jpeg\", image.ImageFormat);\n        }\n\n        [Fact]\n        public void ImagePropertiesAreCorrectForBmpImage()\n        {\n            WebImage image = new WebImage(_BmpImageBytes);\n\n            Assert.Equal(\"bmp\", image.ImageFormat);\n            Assert.Equal(108, image.Width);\n            Assert.Equal(44, image.Height);\n        }\n\n        [Fact]\n        public void ImagePropertiesAreCorrectForPngImage()\n        {\n            WebImage image = new WebImage(_PngImageBytes);\n\n            Assert.Equal(\"png\", image.ImageFormat);\n            Assert.Equal(160, image.Width);\n            Assert.Equal(152, image.Height);\n        }\n\n        [Fact]\n        public void ImagePropertiesAreCorrectForJpgImage()\n        {\n            WebImage image = new WebImage(_JpgImageBytes);\n\n            Assert.Equal(\"jpeg\", image.ImageFormat);\n            Assert.Equal(634, image.Width);\n            Assert.Equal(489, image.Height);\n        }\n\n        [Fact]\n        public void ResizePreservesRatio()\n        {\n            WebImage image = new WebImage(_JpgImageBytes);\n\n            image.Resize(200, 100, preserveAspectRatio: true, preventEnlarge: true);\n\n            Assert.Equal(130, image.Width);\n            Assert.Equal(100, image.Height);\n        }\n\n        [Fact]\n        public void ResizePreservesResolution()\n        {\n            MemoryStream output = null;\n            Action<string, byte[]> saveAction = (_, content) => { output = new MemoryStream(content); };\n\n            WebImage image = new WebImage(_PngImageBytes);\n\n            image.Resize(100, 50, preserveAspectRatio: true, preventEnlarge: true);\n\n            image.Save(GetContext(), saveAction, @\"x:\\ResizePreservesResolution.jpg\", \"jpeg\", forceWellKnownExtension: true);\n            using (Image original = Image.FromStream(new MemoryStream(_PngImageBytes)))\n            {\n                using (Image modified = Image.FromStream(output))\n                {\n                    Assert.Equal(original.HorizontalResolution, modified.HorizontalResolution);\n                    Assert.Equal(original.VerticalResolution, modified.VerticalResolution);\n                }\n            }\n        }\n\n        [Fact]\n        public void ResizePreservesFormat()\n        {\n            // Arrange\n            WebImage image = new WebImage(_PngImageBytes);\n            MemoryStream output = null;\n            Action<string, byte[]> saveAction = (_, content) => { output = new MemoryStream(content); };\n\n            // Act\n            image.Resize(200, 100, preserveAspectRatio: true, preventEnlarge: true);\n\n            // Assert\n            Assert.Equal(\"png\", image.ImageFormat);\n            image.Save(GetContext(), saveAction, @\"x:\\1.png\", null, false);\n\n            using (Image modified = Image.FromStream(output))\n            {\n                Assert.Equal(ImageFormat.Png, modified.RawFormat);\n            }\n        }\n\n        [Fact]\n        public void SaveUpdatesFileNameOfWebImageWhenForcingWellKnownExtension()\n        {\n            // Arrange\n            var context = GetContext();\n\n            // Act\n            WebImage image = new WebImage(context, _ => _JpgImageBytes, @\"c:\\images\\foo.jpg\");\n\n            image.Save(context, (_, __) => { }, @\"x:\\1.exe\", \"jpg\", forceWellKnownExtension: true);\n\n            // Assert\n            Assert.Equal(@\"x:\\1.exe.jpeg\", image.FileName);\n        }\n\n        [Fact]\n        public void SaveUpdatesFileNameOfWebImageWhenFormatChanges()\n        {\n            // Arrange\n            string imagePath = @\"x:\\images\\foo.jpg\";\n            var context = GetContext();\n\n            // Act\n            WebImage image = new WebImage(context, _ => _JpgImageBytes, imagePath);\n\n            image.Save(context, (_, __) => { }, imagePath, \"png\", forceWellKnownExtension: true);\n\n            // Assert\n            Assert.Equal(@\"x:\\images\\foo.jpg.png\", image.FileName);\n        }\n\n        [Fact]\n        public void SaveKeepsNameIfFormatIsUnchanged()\n        {\n            // Arrange\n            string imagePath = @\"x:\\images\\foo.jpg\";\n            var context = GetContext();\n\n            // Act\n            WebImage image = new WebImage(context, _ => _JpgImageBytes, imagePath);\n\n            image.Save(context, (_, __) => { }, imagePath, \"jpg\", forceWellKnownExtension: true);\n\n            // Assert\n            Assert.Equal(@\"x:\\images\\foo.jpg\", image.FileName);\n        }\n\n        [Fact]\n        public void ResizeThrowsOnIncorrectWidthOrHeight()\n        {\n            WebImage image = new WebImage(_JpgImageBytes);\n\n            Assert.ThrowsArgumentGreaterThan(\n                () => image.Resize(-1, 100, preserveAspectRatio: true, preventEnlarge: true),\n                \"width\",\n                \"0\");\n\n            Assert.ThrowsArgumentGreaterThan(\n                () => image.Resize(100, -1, preserveAspectRatio: true, preventEnlarge: true),\n                \"height\",\n                \"0\");\n        }\n\n        [Fact]\n        public void ResizeAndRotateDoesOperationsInRightOrder()\n        {\n            WebImage image = new WebImage(_JpgImageBytes);\n            image.Resize(200, 100, preserveAspectRatio: true, preventEnlarge: true).RotateLeft();\n\n            Assert.Equal(100, image.Width);\n            Assert.Equal(130, image.Height);\n        }\n\n        [Fact]\n        public void ClonePreservesAllInformation()\n        {\n            WebImage image = new WebImage(_JpgImageBytes);\n            image.Resize(200, 100, preserveAspectRatio: true, preventEnlarge: true).RotateLeft();\n\n            // this should preserve list of transformations\n            WebImage cloned = image.Clone();\n\n            Assert.Equal(100, cloned.Width);\n            Assert.Equal(130, cloned.Height);\n        }\n\n        [Fact]\n        public void ResizePreventsEnlarge()\n        {\n            WebImage image = new WebImage(_JpgImageBytes);\n\n            int height = image.Height;\n            int width = image.Width;\n\n            image.Resize(width * 2, height, preserveAspectRatio: true, preventEnlarge: true);\n            Assert.Equal(width, image.Width);\n            Assert.Equal(height, image.Height);\n        }\n\n        [Fact]\n        public void CropCreatesCroppedImage()\n        {\n            WebImage image = new WebImage(_JpgImageBytes);\n            image.Crop(20, 20, 20, 20);\n\n            Assert.Equal(594, image.Width);\n            Assert.Equal(449, image.Height);\n        }\n\n        [Fact]\n        public void CropThrowsOnIncorrectArguments()\n        {\n            WebImage image = new WebImage(_JpgImageBytes);\n\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(\n                () => image.Crop(top: -1),\n                \"top\",\n                \"0\");\n\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(\n                () => image.Crop(left: -1),\n                \"left\",\n                \"0\");\n\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(\n                () => image.Crop(bottom: -1),\n                \"bottom\",\n                \"0\");\n\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(\n                () => image.Crop(right: -1),\n                \"right\",\n                \"0\");\n        }\n\n        [Fact]\n        public void RotateLeftReturnsRotatedImage()\n        {\n            WebImage image = new WebImage(_PngImageBytes);\n            image.RotateLeft();\n\n            Assert.Equal(152, image.Width);\n            Assert.Equal(160, image.Height);\n        }\n\n        [Fact]\n        public void RotateRightReturnsRotatedImage()\n        {\n            WebImage image = new WebImage(_PngImageBytes);\n            image.RotateRight();\n\n            Assert.Equal(152, image.Width);\n            Assert.Equal(160, image.Height);\n        }\n\n        [Fact]\n        public void FlipVerticalReturnsFlippedImage()\n        {\n            WebImage image = new WebImage(_PngImageBytes);\n            image.FlipVertical();\n\n            Assert.Equal(160, image.Width);\n            Assert.Equal(152, image.Height);\n        }\n\n        [Fact]\n        public void FlipHorizontalReturnsFlippedImage()\n        {\n            WebImage image = new WebImage(_PngImageBytes);\n            image.FlipHorizontal();\n\n            Assert.Equal(160, image.Width);\n            Assert.Equal(152, image.Height);\n        }\n\n        [Fact]\n        public void MultipleCombinedOperationsExecuteInRightOrder()\n        {\n            WebImage image = new WebImage(_JpgImageBytes);\n            image.Resize(200, 100, preserveAspectRatio: true, preventEnlarge: true).RotateLeft();\n            image.Crop(top: 10, right: 10).AddTextWatermark(\"plan9\");\n\n            Assert.Equal(90, image.Width);\n            Assert.Equal(120, image.Height);\n        }\n\n        [Fact]\n        public void AddTextWatermarkPreservesImageDimension()\n        {\n            WebImage image = new WebImage(_JpgImageBytes);\n            image.AddTextWatermark(\"Plan9\", fontSize: 16, horizontalAlign: \"Left\", verticalAlign: \"Bottom\", opacity: 50);\n\n            Assert.Equal(634, image.Width);\n            Assert.Equal(489, image.Height);\n        }\n\n        [Fact]\n        public void AddTextWatermarkParsesHexColorCorrectly()\n        {\n            WebImage image = new WebImage(_JpgImageBytes);\n            image.AddTextWatermark(\"Plan9\", fontSize: 16, fontColor: \"#FF0000\", horizontalAlign: \"Center\", verticalAlign: \"Middle\");\n\n            Assert.Equal(634, image.Width);\n            Assert.Equal(489, image.Height);\n        }\n\n        [Fact]\n        public void AddTextWatermarkParsesShortHexColorCorrectly()\n        {\n            WebImage image = new WebImage(_JpgImageBytes);\n            image.AddTextWatermark(\"Plan9\", fontSize: 16, fontColor: \"#F00\", horizontalAlign: \"Center\", verticalAlign: \"Middle\");\n\n            Assert.Equal(634, image.Width);\n            Assert.Equal(489, image.Height);\n        }\n\n        [Fact]\n        public void AddTextWatermarkDoesNotChangeImageIfPaddingIsTooBig()\n        {\n            WebImage image = new WebImage(_JpgImageBytes);\n            image.AddTextWatermark(\"Plan9\", padding: 1000);\n\n            Assert.Equal(634, image.Width);\n            Assert.Equal(489, image.Height);\n        }\n\n        [Fact]\n        public void AddTextWatermarkThrowsOnNegativeOpacity()\n        {\n            WebImage image = new WebImage(_JpgImageBytes);\n\n            Assert.ThrowsArgumentOutOfRange(() => image.AddTextWatermark(\"Plan9\", opacity: -1), \"opacity\", \"Value must be between 0 and 100.\");\n        }\n\n        [Fact]\n        public void AddTextWatermarkThrowsOnTooBigOpacity()\n        {\n            WebImage image = new WebImage(_JpgImageBytes);\n\n            Assert.ThrowsArgumentOutOfRange(() => image.AddTextWatermark(\"Plan9\", opacity: 155), \"opacity\", \"Value must be between 0 and 100.\");\n        }\n\n        [Fact]\n        public void AddTextWatermarkThrowsOnEmptyText()\n        {\n            WebImage image = new WebImage(_JpgImageBytes);\n            Assert.ThrowsArgumentNullOrEmptyString(\n                () => image.AddTextWatermark(\"\"),\n                \"text\");\n        }\n\n        [Fact]\n        public void AddTextWatermarkThrowsOnIncorrectColorName()\n        {\n            WebImage image = new WebImage(_JpgImageBytes);\n            Assert.Throws<ArgumentException>(\n                () => image.AddTextWatermark(\"p9\", fontColor: \"super\"),\n                \"The \\\"fontColor\\\" value is invalid. Valid values are names like \\\"White\\\", \\\"Black\\\", or \\\"DarkBlue\\\", or hexadecimal values in the form \\\"#RRGGBB\\\" or \\\"#RGB\\\".\");\n        }\n\n        [Fact]\n        public void AddTextWatermarkThrowsOnIncorrectHexColorValue()\n        {\n            WebImage image = new WebImage(_JpgImageBytes);\n            Assert.Throws<ArgumentException>(\n                () => image.AddTextWatermark(\"p9\", fontColor: \"#XXX\"),\n                \"The \\\"fontColor\\\" value is invalid. Valid values are names like \\\"White\\\", \\\"Black\\\", or \\\"DarkBlue\\\", or hexadecimal values in the form \\\"#RRGGBB\\\" or \\\"#RGB\\\".\");\n        }\n\n        [Fact]\n        public void AddTextWatermarkThrowsOnIncorrectHexColorLength()\n        {\n            WebImage image = new WebImage(_JpgImageBytes);\n            Assert.Throws<ArgumentException>(\n                () => image.AddTextWatermark(\"p9\", fontColor: \"#F000\"),\n                \"The \\\"fontColor\\\" value is invalid. Valid values are names like \\\"White\\\", \\\"Black\\\", or \\\"DarkBlue\\\", or hexadecimal values in the form \\\"#RRGGBB\\\" or \\\"#RGB\\\".\");\n        }\n\n        [Fact]\n        public void AddTextWatermarkThrowsOnIncorrectHorizontalAlignment()\n        {\n            WebImage image = new WebImage(_JpgImageBytes);\n            Assert.Throws<ArgumentException>(\n                () => image.AddTextWatermark(\"p9\", horizontalAlign: \"Justify\"),\n                \"The \\\"horizontalAlign\\\" value is invalid. Valid values are: \\\"Right\\\", \\\"Left\\\", and \\\"Center\\\".\");\n        }\n\n        [Fact]\n        public void AddTextWatermarkThrowsOnIncorrectVerticalAlignment()\n        {\n            WebImage image = new WebImage(_JpgImageBytes);\n            Assert.Throws<ArgumentException>(\n                () => image.AddTextWatermark(\"p9\", verticalAlign: \"NotSet\"),\n                \"The \\\"verticalAlign\\\" value is invalid. Valid values are: \\\"Top\\\", \\\"Bottom\\\", and \\\"Middle\\\".\");\n        }\n\n        [Fact]\n        public void AddTextWatermarkThrowsOnNegativePadding()\n        {\n            WebImage image = new WebImage(_JpgImageBytes);\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(\n                () => image.AddTextWatermark(\"p9\", padding: -10),\n                \"padding\",\n                \"0\");\n        }\n\n        [Fact]\n        public void AddTextWatermarkThrowsOnIncorrectFontSize()\n        {\n            WebImage image = new WebImage(_JpgImageBytes);\n            Assert.ThrowsArgumentGreaterThan(\n                () => image.AddTextWatermark(\"p9\", fontSize: -10),\n                \"fontSize\",\n                \"0\");\n\n            Assert.ThrowsArgumentGreaterThan(\n                () => image.AddTextWatermark(\"p9\", fontSize: 0),\n                \"fontSize\",\n                \"0\");\n        }\n\n        [Fact]\n        public void AddTextWatermarkThrowsOnIncorrectFontStyle()\n        {\n            WebImage image = new WebImage(_JpgImageBytes);\n\n            Assert.Throws<ArgumentException>(\n                () => image.AddTextWatermark(\"p9\", fontStyle: \"something\"),\n                \"The \\\"fontStyle\\\" value is invalid. Valid values are: \\\"Regular\\\", \\\"Bold\\\", \\\"Italic\\\", \\\"Underline\\\", and \\\"Strikeout\\\".\");\n        }\n\n        [Fact]\n        public void AddTextWatermarkThrowsOnIncorrectFontFamily()\n        {\n            WebImage image = new WebImage(_JpgImageBytes);\n\n            Assert.Throws<ArgumentException>(\n                () => image.AddTextWatermark(\"p9\", fontFamily: \"something\"),\n                \"The \\\"fontFamily\\\" value is invalid. Valid values are font family names like: \\\"Arial\\\", \\\"Times New Roman\\\", etc. Make sure that the font family you are trying to use is installed on the server.\");\n        }\n\n        [Fact]\n        public void AddImageWatermarkPreservesImageDimension()\n        {\n            WebImage watermark = new WebImage(_BmpImageBytes);\n            WebImage image = new WebImage(_JpgImageBytes);\n            image.AddImageWatermark(watermark, horizontalAlign: \"LEFT\", verticalAlign: \"top\", opacity: 50, padding: 10);\n\n            Assert.Equal(634, image.Width);\n            Assert.Equal(489, image.Height);\n        }\n\n        [Fact]\n        public void CanAddTextAndImageWatermarks()\n        {\n            WebImage watermark = new WebImage(_BmpImageBytes);\n            WebImage image = new WebImage(_JpgImageBytes);\n            image.AddImageWatermark(watermark, horizontalAlign: \"LEFT\", verticalAlign: \"top\", opacity: 30, padding: 10);\n            image.AddTextWatermark(\"plan9\");\n\n            Assert.Equal(634, image.Width);\n            Assert.Equal(489, image.Height);\n        }\n\n        [Fact]\n        public void AddImageWatermarkDoesNotChangeWatermarkImage()\n        {\n            WebImage watermark = new WebImage(_BmpImageBytes);\n            WebImage image = new WebImage(_JpgImageBytes);\n            image.AddImageWatermark(watermark, width: 54, height: 22, horizontalAlign: \"LEFT\", verticalAlign: \"top\", opacity: 50, padding: 10);\n\n            Assert.Equal(108, watermark.Width);\n            Assert.Equal(44, watermark.Height);\n        }\n\n        [Fact]\n        public void AddImageWatermarkThrowsOnNullImage()\n        {\n            WebImage image = new WebImage(_JpgImageBytes);\n\n            Assert.ThrowsArgumentNull(\n                () => image.AddImageWatermark(watermarkImage: null),\n                \"watermarkImage\");\n        }\n\n        [Fact]\n        public void AddImageWatermarkThrowsWhenJustOneDimensionIsZero()\n        {\n            WebImage watermark = new WebImage(_BmpImageBytes);\n            WebImage image = new WebImage(_JpgImageBytes);\n\n            string message = \"Watermark width and height must both be positive or both be zero.\";\n            Assert.Throws<ArgumentException>(\n                () => image.AddImageWatermark(watermark, width: 0, height: 22), message);\n\n            Assert.Throws<ArgumentException>(\n                () => image.AddImageWatermark(watermark, width: 100, height: 0), message);\n        }\n\n        [Fact]\n        public void AddImageWatermarkThrowsWhenOpacityIsIncorrect()\n        {\n            WebImage watermark = new WebImage(_BmpImageBytes);\n            WebImage image = new WebImage(_JpgImageBytes);\n\n            Assert.ThrowsArgumentOutOfRange(() => image.AddImageWatermark(watermark, opacity: -1), \"opacity\", \"Value must be between 0 and 100.\");\n\n            Assert.ThrowsArgumentOutOfRange(() => image.AddImageWatermark(watermark, opacity: 120), \"opacity\", \"Value must be between 0 and 100.\");\n        }\n\n        [Fact]\n        public void AddImageWatermarkThrowsOnNegativeDimensions()\n        {\n            WebImage watermark = new WebImage(_BmpImageBytes);\n            WebImage image = new WebImage(_JpgImageBytes);\n\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(\n                () => image.AddImageWatermark(watermark, width: -1),\n                \"width\",\n                \"0\");\n\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(\n                () => image.AddImageWatermark(watermark, height: -1),\n                \"height\",\n                \"0\");\n        }\n\n        [Fact]\n        public void AddImageWatermarkThrowsOnIncorrectHorizontalAlignment()\n        {\n            WebImage watermark = new WebImage(_BmpImageBytes);\n            WebImage image = new WebImage(_JpgImageBytes);\n\n            Assert.Throws<ArgumentException>(\n                () => image.AddImageWatermark(watermark, horizontalAlign: \"horizontal\"),\n                \"The \\\"horizontalAlign\\\" value is invalid. Valid values are: \\\"Right\\\", \\\"Left\\\", and \\\"Center\\\".\");\n        }\n\n        [Fact]\n        public void AddImageWatermarkThrowsOnIncorrectVerticalAlignment()\n        {\n            WebImage watermark = new WebImage(_BmpImageBytes);\n            WebImage image = new WebImage(_JpgImageBytes);\n\n            Assert.Throws<ArgumentException>(\n                () => image.AddImageWatermark(watermark, verticalAlign: \"vertical\"),\n                \"The \\\"verticalAlign\\\" value is invalid. Valid values are: \\\"Top\\\", \\\"Bottom\\\", and \\\"Middle\\\".\");\n        }\n\n        [Fact]\n        public void AddImageWatermarkThrowsOnNegativePadding()\n        {\n            WebImage watermark = new WebImage(_BmpImageBytes);\n            WebImage image = new WebImage(_JpgImageBytes);\n\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(\n                () => image.AddImageWatermark(watermark, padding: -10),\n                \"padding\",\n                \"0\");\n        }\n\n        [Fact]\n        public void AddImageWatermarkDoesNotChangeImageIfWatermarkIsTooBig()\n        {\n            WebImage watermark = new WebImage(_JpgImageBytes);\n            WebImage image = new WebImage(_BmpImageBytes);\n            byte[] originalBytes = image.GetBytes(\"jpg\");\n\n            // This will use original watermark image dimensions which is bigger than the target image.\n            image.AddImageWatermark(watermark);\n            byte[] watermarkedBytes = image.GetBytes(\"jpg\");\n\n            Assert.Equal(originalBytes, watermarkedBytes);\n        }\n\n        [Fact]\n        public void AddImageWatermarkWithFileNameThrowsExceptionWhenWatermarkDirectoryDoesNotExist()\n        {\n            var context = GetContext();\n            WebImage image = new WebImage(_BmpImageBytes);\n\n            Assert.Throws<DirectoryNotFoundException>(\n                () => image.AddImageWatermark(context, s => { throw new DirectoryNotFoundException(); }, @\"x:\\path\\does\\not\\exist\", width: 0, height: 0, horizontalAlign: \"Right\", verticalAlign: \"Bottom\", opacity: 100, padding: 5));\n        }\n\n        [Fact]\n        public void AddImageWatermarkWithFileNameThrowsExceptionWhenWatermarkFileDoesNotExist()\n        {\n            var context = GetContext();\n            WebImage image = new WebImage(_BmpImageBytes);\n            Assert.Throws<FileNotFoundException>(\n                () => image.AddImageWatermark(context, s => { throw new FileNotFoundException(); }, @\"x:\\there-is-no-file.jpg\", width: 0, height: 0, horizontalAlign: \"Right\", verticalAlign: \"Bottom\", opacity: 100, padding: 5));\n        }\n\n        [Fact]\n        public void AddImageWatermarkWithFileNameThrowsExceptionWhenWatermarkFilePathIsNull()\n        {\n            var context = GetContext();\n\n            WebImage image = new WebImage(_BmpImageBytes);\n            Assert.ThrowsArgument(\n                () => image.AddImageWatermark(context, s => _JpgImageBytes, watermarkImageFilePath: null, width: 0, height: 0, horizontalAlign: \"Right\", verticalAlign: \"Bottom\", opacity: 100, padding: 5),\n                \"filePath\",\n                \"Value cannot be null or an empty string.\");\n        }\n\n        [Fact]\n        public void AddImageWatermarkWithFileNameThrowsExceptionWhenWatermarkFilePathIsEmpty()\n        {\n            var context = GetContext();\n            WebImage image = new WebImage(_BmpImageBytes);\n            Assert.ThrowsArgument(\n                () => image.AddImageWatermark(context, s => _JpgImageBytes, watermarkImageFilePath: null, width: 0, height: 0, horizontalAlign: \"Right\", verticalAlign: \"Bottom\", opacity: 100, padding: 5),\n                \"filePath\",\n                \"Value cannot be null or an empty string.\");\n        }\n\n        [Fact]\n        public void CanAddImageWatermarkWithFileName()\n        {\n            // Arrange\n            var context = GetContext();\n            WebImage image = new WebImage(_BmpImageBytes);\n            WebImage watermark = new WebImage(_JpgImageBytes);\n\n            // Act\n            var watermarkedWithImageArgument = image.AddImageWatermark(watermark).GetBytes();\n            var watermarkedWithFilePathArgument = image.AddImageWatermark(context, (name) => _JpgImageBytes, @\"x:\\jpegimage.jpg\", width: 0, height: 0, horizontalAlign: \"Right\", verticalAlign: \"Bottom\", opacity: 100, padding: 5).GetBytes();\n\n            Assert.Equal(watermarkedWithImageArgument, watermarkedWithFilePathArgument);\n        }\n\n        [Fact]\n        public void SaveOverwritesExistingFile()\n        {\n            Action<string, byte[]> saveAction = (path, content) => { };\n\n            WebImage image = new WebImage(_BmpImageBytes);\n            string newFileName = @\"x:\\newImage.bmp\";\n\n            image.Save(GetContext(), saveAction, newFileName, imageFormat: null, forceWellKnownExtension: true);\n\n            image.RotateLeft();\n            // just verify this does not throw\n            image.Save(GetContext(), saveAction, newFileName, imageFormat: null, forceWellKnownExtension: true);\n        }\n\n        [Fact]\n        public void SaveThrowsWhenPathIsNull()\n        {\n            Action<string, byte[]> saveAction = (path, content) => { };\n\n            // this constructor will not set path\n            byte[] originalContent = _BmpImageBytes;\n            WebImage image = new WebImage(originalContent);\n\n            Assert.ThrowsArgumentNullOrEmptyString(\n                () => image.Save(GetContext(), saveAction, filePath: null, imageFormat: null, forceWellKnownExtension: true),\n                \"filePath\");\n        }\n\n        [Fact]\n        public void SaveThrowsWhenPathIsEmpty()\n        {\n            Action<string, byte[]> saveAction = (path, content) => { };\n            WebImage image = new WebImage(_BmpImageBytes);\n\n            Assert.ThrowsArgumentNullOrEmptyString(\n                () => image.Save(GetContext(), saveAction, filePath: String.Empty, imageFormat: null, forceWellKnownExtension: true),\n                \"filePath\");\n        }\n\n        [Fact]\n        public void SaveUsesOriginalFormatWhenNoFormatIsSpecified()\n        {\n            // Arrange\n            // Use rooted path so we by pass using HttpContext\n            var specifiedOutputFile = @\"C:\\some-dir\\foo.jpg\";\n            string actualOutputFile = null;\n            Action<string, byte[]> saveAction = (fileName, content) => { actualOutputFile = fileName; };\n\n            // Act\n            WebImage image = new WebImage(_PngImageBytes);\n            image.Save(GetContext(), saveAction, filePath: specifiedOutputFile, imageFormat: null, forceWellKnownExtension: true);\n\n            // Assert\n            Assert.Equal(\".png\", Path.GetExtension(actualOutputFile));\n        }\n\n        [Fact]\n        public void SaveUsesOriginalFormatForStreamsWhenNoFormatIsSpecified()\n        {\n            // Arrange\n            // Use rooted path so we by pass using HttpContext\n            var specifiedOutputFile = @\"x:\\some-dir\\foo.jpg\";\n            string actualOutputFile = null;\n            Action<string, byte[]> saveAction = (fileName, content) => { actualOutputFile = fileName; };\n\n            // Act\n            WebImage image = new WebImage(_PngImageBytes);\n            image.Save(GetContext(), saveAction, filePath: specifiedOutputFile, imageFormat: null, forceWellKnownExtension: true);\n\n            // Assert\n            Assert.Equal(\".png\", Path.GetExtension(actualOutputFile));\n        }\n\n        [Fact]\n        public void SaveSetsExtensionBasedOnFormatWhenForceExtensionIsSet()\n        {\n            // Arrange\n            // Use rooted path so we by pass using HttpContext\n            var specifiedOutputFile = @\"x:\\some-dir\\foo.exe\";\n            string actualOutputFile = null;\n            Action<string, byte[]> saveAction = (fileName, content) => { actualOutputFile = fileName; };\n\n            // Act\n            WebImage image = new WebImage(_BmpImageBytes);\n            image.Save(GetContext(), saveAction, filePath: specifiedOutputFile, imageFormat: \"jpg\", forceWellKnownExtension: true);\n\n            // Assert\n            Assert.Equal(\".jpeg\", Path.GetExtension(actualOutputFile));\n            Assert.Equal(specifiedOutputFile + \".jpeg\", actualOutputFile);\n        }\n\n        [Fact]\n        public void SaveAppendsExtensionBasedOnFormatWhenForceExtensionIsSet()\n        {\n            // Arrange\n            // Use rooted path so we by pass using HttpContext\n            var specifiedOutputFile = @\"x:\\some-dir\\foo\";\n            string actualOutputFile = null;\n            Action<string, byte[]> saveAction = (fileName, content) => { actualOutputFile = fileName; };\n\n            // Act\n            WebImage image = new WebImage(_BmpImageBytes);\n            image.Save(GetContext(), saveAction, filePath: specifiedOutputFile, imageFormat: \"jpg\", forceWellKnownExtension: true);\n\n            // Assert\n            Assert.Equal(\".jpeg\", Path.GetExtension(actualOutputFile));\n        }\n\n        [Fact]\n        public void SaveDoesNotModifyExtensionWhenExtensionIsCorrect()\n        {\n            // Arrange\n            // Use rooted path so we by pass using HttpContext\n            var specifiedOutputFile = @\"x:\\some-dir\\foo.jpg\";\n            string actualOutputFile = null;\n            Action<string, byte[]> saveAction = (fileName, content) => { actualOutputFile = fileName; };\n\n            // Act\n            WebImage image = new WebImage(_BmpImageBytes);\n            image.Save(GetContext(), saveAction, filePath: specifiedOutputFile, imageFormat: \"jpg\", forceWellKnownExtension: true);\n\n            // Assert\n            Assert.Equal(specifiedOutputFile, actualOutputFile);\n        }\n\n        [Fact]\n        public void SaveDoesNotModifyExtensionWhenForceCorrectExtensionRenameIsCleared()\n        {\n            // Arrange\n            // Use rooted path so we by pass using HttpContext\n            var specifiedOutputFile = @\"x:\\some-dir\\foo.exe\";\n            string actualOutputFile = null;\n            Action<string, byte[]> saveAction = (fileName, content) => { actualOutputFile = fileName; };\n\n            // Act\n            WebImage image = new WebImage(_BmpImageBytes);\n            image.Save(GetContext(), saveAction, filePath: specifiedOutputFile, imageFormat: \"jpg\", forceWellKnownExtension: false);\n\n            // Assert\n            Assert.Equal(specifiedOutputFile, actualOutputFile);\n        }\n\n        [Fact]\n        public void ImageFormatIsSavedCorrectly()\n        {\n            WebImage image = new WebImage(_BmpImageBytes);\n            Assert.Equal(\"bmp\", image.ImageFormat);\n        }\n\n        [Fact]\n        public void SaveUsesInitialFormatWhenNoFormatIsSpecified()\n        {\n            // Arrange\n            string savePath = @\"x:\\some-dir\\image.png\";\n            MemoryStream stream = null;\n            Action<string, byte[]> saveAction = (path, content) => { stream = new MemoryStream(content); };\n            var image = new WebImage(_PngImageBytes);\n\n            // Act \n            image.FlipVertical().FlipHorizontal();\n\n            // Assert\n            image.Save(GetContext(), saveAction, savePath, imageFormat: null, forceWellKnownExtension: true);\n\n            using (Image savedImage = Image.FromStream(stream))\n            {\n                Assert.Equal(savedImage.RawFormat, ImageFormat.Png);\n            }\n        }\n\n        [Fact]\n        public void ImageFormatIsParsedCorrectly()\n        {\n            WebImage image = new WebImage(_BmpImageBytes);\n            Assert.Equal(\"bmp\", image.ImageFormat);\n        }\n\n        private static HttpContextBase GetContext()\n        {\n            var httpContext = new Mock<HttpContextBase>();\n            var httpRequest = new Mock<HttpRequestBase>();\n            httpRequest.Setup(c => c.MapPath(It.IsAny<string>())).Returns((string path) => path);\n            httpContext.Setup(c => c.Request).Returns(httpRequest.Object);\n\n            return httpContext.Object;\n        }\n\n        // Test stream that pretends it can't seek. \n        private class TestStream : Stream\n        {\n            private MemoryStream _memoryStream;\n\n            public TestStream(MemoryStream memoryStream)\n            {\n                _memoryStream = memoryStream;\n            }\n\n            public override bool CanRead\n            {\n                get { return _memoryStream.CanRead; }\n            }\n\n            public override bool CanSeek\n            {\n                get { return false; }\n            }\n\n            public override bool CanWrite\n            {\n                get { return _memoryStream.CanWrite; }\n            }\n\n            public override void Flush()\n            {\n                _memoryStream.Flush();\n            }\n\n            public override long Length\n            {\n                get { throw new NotSupportedException(); }\n            }\n\n            public override long Position\n            {\n                get { return _memoryStream.Position; }\n                set { _memoryStream.Position = value; }\n            }\n\n            public override int Read(byte[] buffer, int offset, int count)\n            {\n                return _memoryStream.Read(buffer, offset, count);\n            }\n\n            public override long Seek(long offset, SeekOrigin origin)\n            {\n                throw new NotSupportedException();\n            }\n\n            public override void SetLength(long value)\n            {\n                _memoryStream.SetLength(value);\n            }\n\n            public override void Write(byte[] buffer, int offset, int count)\n            {\n                _memoryStream.Write(buffer, offset, count);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Helpers.Test/WebMailTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Linq;\nusing System.Net.Mail;\nusing System.Text;\nusing System.Web.WebPages.Scope;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Helpers.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")]\n    public class WebMailTest : IDisposable\n    {\n        const string FromAddress = \"abc@123.com\";\n        const string Server = \"myserver.com\";\n        const int Port = 100;\n        const string UserName = \"My UserName\";\n        const string Password = \"My Password\";\n\n        [Fact]\n        public void WebMailSmtpServerTests()\n        {\n            // All tests prior to setting smtp server go here\n            // Verify Send throws if no SmtpServer is set\n            Assert.Throws<InvalidOperationException>(\n                () => WebMail.Send(to: \"test@test.com\", subject: \"test\", body: \"test body\"),\n                \"\\\"SmtpServer\\\" was not specified.\"\n                );\n\n            // Verify SmtpServer uses scope storage.\n            // Arrange\n            var value = \"value\";\n\n            // Act\n            WebMail.SmtpServer = value;\n\n            // Assert\n            Assert.Equal(WebMail.SmtpServer, value);\n            Assert.Equal(ScopeStorage.CurrentScope[WebMail.SmtpServerKey], value);\n        }\n\n        [Fact]\n        public void WebMailSendThrowsIfPriorityIsInvalid()\n        {\n            Assert.ThrowsArgument(\n                () => WebMail.Send(to: \"test@test.com\", subject: \"test\", body: \"test body\", priority: \"foo\"),\n                \"priority\",\n                \"The \\\"priority\\\" value is invalid. Valid values are \\\"Low\\\", \\\"Normal\\\" and \\\"High\\\".\"\n                );\n        }\n\n        [Fact]\n        public void WebMailUsesScopeStorageForSmtpPort()\n        {\n            // Arrange\n            var value = 4;\n\n            // Act\n            WebMail.SmtpPort = value;\n\n            // Assert\n            Assert.Equal(WebMail.SmtpPort, value);\n            Assert.Equal(ScopeStorage.CurrentScope[WebMail.SmtpPortKey], value);\n        }\n\n        [Fact]\n        public void WebMailUsesScopeStorageForEnableSsl()\n        {\n            // Arrange\n            var value = true;\n\n            // Act\n            WebMail.EnableSsl = value;\n\n            // Assert\n            Assert.Equal(WebMail.EnableSsl, value);\n            Assert.Equal(ScopeStorage.CurrentScope[WebMail.EnableSslKey], value);\n        }\n\n        [Fact]\n        public void WebMailUsesScopeStorageForDefaultCredentials()\n        {\n            // Arrange\n            var value = true;\n\n            // Act\n            WebMail.SmtpUseDefaultCredentials = value;\n\n            // Assert\n            Assert.Equal(WebMail.SmtpUseDefaultCredentials, value);\n            Assert.Equal(ScopeStorage.CurrentScope[WebMail.SmtpUseDefaultCredentialsKey], value);\n        }\n\n        [Fact]\n        public void WebMailUsesScopeStorageForUserName()\n        {\n            // Arrange\n            var value = \"value\";\n\n            // Act\n            WebMail.UserName = value;\n\n            // Assert\n            Assert.Equal(WebMail.UserName, value);\n            Assert.Equal(ScopeStorage.CurrentScope[WebMail.UserNameKey], value);\n        }\n\n        [Fact]\n        public void WebMailUsesScopeStorageForPassword()\n        {\n            // Arrange\n            var value = \"value\";\n\n            // Act\n            WebMail.Password = value;\n\n            // Assert\n            Assert.Equal(WebMail.Password, value);\n            Assert.Equal(ScopeStorage.CurrentScope[WebMail.PasswordKey], value);\n        }\n\n        [Fact]\n        public void WebMailUsesScopeStorageForFrom()\n        {\n            // Arrange\n            var value = \"value\";\n\n            // Act\n            WebMail.From = value;\n\n            // Assert\n            Assert.Equal(WebMail.From, value);\n            Assert.Equal(ScopeStorage.CurrentScope[WebMail.FromKey], value);\n        }\n\n        [Fact]\n        public void WebMailThrowsWhenSmtpServerValueIsNullOrEmpty()\n        {\n            // Act and Assert\n            Assert.ThrowsArgumentNullOrEmptyString(() => WebMail.SmtpServer = null, \"SmtpServer\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => WebMail.SmtpServer = String.Empty, \"SmtpServer\");\n        }\n\n        [Fact]\n        public void ParseHeaderParsesStringInKeyValueFormat()\n        {\n            // Arrange\n            string header = \"foo: bar\";\n\n            // Act\n            string key, value;\n\n            // Assert\n            Assert.True(WebMail.TryParseHeader(header, out key, out value));\n            Assert.Equal(\"foo\", key);\n            Assert.Equal(\"bar\", value);\n        }\n\n        [Fact]\n        public void ParseHeaderReturnsFalseIfHeaderIsNotInCorrectFormat()\n        {\n            // Arrange\n            string header = \"foo bar\";\n\n            // Act\n            string key, value;\n\n            // Assert\n            Assert.False(WebMail.TryParseHeader(header, out key, out value));\n            Assert.Null(key);\n            Assert.Null(value);\n        }\n\n        [Fact]\n        public void SetPropertiesOnMessageTest_SetsAllInfoCorrectlyOnMailMessageTest()\n        {\n            // Arrange\n            MailMessage message = new MailMessage();\n            string to = \"abc123@xyz.com\";\n            string subject = \"subject1\";\n            string body = \"body1\";\n            string from = FromAddress;\n            string cc = \"cc@xyz.com\";\n            string attachmentName = \"NETLogo.png\";\n            string bcc = \"foo@bar.com\";\n            string replyTo = \"x@y.com,z@pqr.com\";\n            string contentEncoding = \"utf-8\";\n            string headerEncoding = \"utf-16\";\n            var priority = MailPriority.Low;\n\n            // Act\n            string fileToAttach = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());\n\n            try\n            {\n                TestFile.Create(attachmentName).Save(fileToAttach);\n                bool isBodyHtml = true;\n                var additionalHeaders = new[] { \"header1:value1\" };\n                WebMail.SetPropertiesOnMessage(message, to, subject, body, from, cc, bcc, replyTo, contentEncoding, headerEncoding, priority, new[] { fileToAttach }, isBodyHtml, additionalHeaders);\n\n                // Assert\n                Assert.Equal(body, message.Body);\n                Assert.Equal(subject, message.Subject);\n                Assert.Equal(to, message.To[0].Address);\n                Assert.Equal(cc, message.CC[0].Address);\n                Assert.Equal(from, message.From.Address);\n                Assert.Equal(bcc, message.Bcc[0].Address);\n                Assert.Equal(\"x@y.com\", message.ReplyToList[0].Address);\n                Assert.Equal(\"z@pqr.com\", message.ReplyToList[1].Address);\n                Assert.Equal(MailPriority.Low, message.Priority);\n                Assert.Equal(Encoding.UTF8, message.BodyEncoding);\n                Assert.Equal(Encoding.Unicode, message.HeadersEncoding);\n\n                Assert.Contains(\"header1\", message.Headers.AllKeys);\n                Assert.Single(message.Attachments);\n            }\n            finally\n            {\n                try\n                {\n                    File.Delete(fileToAttach);\n                }\n                catch (IOException)\n                {\n                } // Try our best to clean up after ourselves\n            }\n        }\n\n        [Fact]\n        public void MailSendWithNullInCollection_ThrowsArgumentException()\n        {\n            Assert.Throws<ArgumentException>(\n                () => WebMail.Send(\"foo@bar.com\", \"sub\", \"body\", filesToAttach: new string[] { \"c:\\\\foo.txt\", null }),\n                \"A string in the collection is null or empty.\\r\\nParameter name: filesToAttach\"\n            );\n\n            Assert.Throws<ArgumentException>(\n                () => WebMail.Send(\"foo@bar.com\", \"sub\", \"body\", additionalHeaders: new string[] { \"foo:bar\", null }),\n                \"A string in the collection is null or empty.\\r\\nParameter name: additionalHeaders\"\n            );\n        }\n\n        [Fact]\n        public void AssignHeaderValuesIgnoresMalformedHeaders()\n        {\n            // Arrange\n            var message = new MailMessage();\n            var headers = new[] { \"foo1:bar1\", \"foo2\", \"foo3|bar3\", \"foo4 bar4\" };\n\n            // Act\n            WebMail.AssignHeaderValues(message, headers);\n\n            // Assert\n            Assert.Single(message.Headers);\n            Assert.Equal(\"foo1\", message.Headers.AllKeys[0]);\n            Assert.Equal(\"bar1\", message.Headers[0]);\n        }\n\n        [Fact]\n        public void PropertiesDuplicatedAcrossHeaderAndArgumentDoesNotThrow()\n        {\n            // Arrange\n            var message = new MailMessage();\n            var headers = new[] { \"to:to@test.com\" };\n\n            // Act\n            WebMail.SetPropertiesOnMessage(message, \"to@test.com\", null, null, \"from@test.com\", null, null, null, null, null, MailPriority.Normal, null, false, headers);\n\n            // Assert\n            Assert.Equal(2, message.To.Count);\n            Assert.Equal(\"to@test.com\", message.To.First().Address);\n            Assert.Equal(\"to@test.com\", message.To.Last().Address);\n        }\n\n        [Fact]\n        public void AssignHeaderValuesSetsPropertiesForKnownHeaderValues()\n        {\n            // Arrange\n            var message = new MailMessage();\n            var headers = new[]\n            {\n                \"cc:cc@test.com\", \"bcc:bcc@test.com,bcc2@test.com\", \"from:from@test.com\", \"priority:high\", \"reply-to:replyto1@test.com,replyto2@test.com\",\n                \"sender: sender@test.com\", \"to:to@test.com\"\n            };\n\n            // Act\n            WebMail.AssignHeaderValues(message, headers);\n\n            // Assert\n            Assert.Equal(\"cc@test.com\", message.CC.Single().Address);\n            Assert.Equal(\"bcc@test.com\", message.Bcc.First().Address);\n            Assert.Equal(\"bcc2@test.com\", message.Bcc.Last().Address);\n            Assert.Equal(\"from@test.com\", message.From.Address);\n            Assert.Equal(MailPriority.High, message.Priority);\n            Assert.Equal(\"replyto1@test.com\", message.ReplyToList.First().Address);\n            Assert.Equal(\"replyto2@test.com\", message.ReplyToList.Last().Address);\n            Assert.Equal(\"sender@test.com\", message.Sender.Address);\n            Assert.Equal(\"to@test.com\", message.To.Single().Address);\n\n            // Assert we transparently set header values\n            Assert.Equal(headers.Count(), message.Headers.Count);\n        }\n\n        [Fact]\n        public void AssignHeaderDoesNotThrowIfPriorityValueIsInvalid()\n        {\n            // Arrange\n            var message = new MailMessage();\n            var headers = new[] { \"priority:invalid-value\" };\n\n            // Act\n            WebMail.AssignHeaderValues(message, headers);\n\n            // Assert\n            Assert.Equal(MailPriority.Normal, message.Priority);\n\n            // Assert we transparently set header values\n            Assert.Single(message.Headers);\n            Assert.Equal(\"Priority\", message.Headers.Keys[0]);\n            Assert.Equal(\"invalid-value\", message.Headers[\"Priority\"]);\n        }\n\n        [Fact]\n        public void AssignHeaderDoesNotThrowIfMailAddressIsInvalid()\n        {\n            // Arrange\n            var message = new MailMessage();\n            var headers = new[] { \"to:not-#-email@@\" };\n\n            // Act\n            WebMail.AssignHeaderValues(message, headers);\n\n            // Assert\n            Assert.Empty(message.To);\n\n            // Assert we transparently set header values\n            Assert.Single(message.Headers);\n            Assert.Equal(\"To\", message.Headers.Keys[0]);\n            Assert.Equal(\"not-#-email@@\", message.Headers[\"To\"]);\n        }\n\n        [Fact]\n        public void AssignHeaderDoesNotThrowIfKnownHeaderValuesAreEmptyOrMalformed()\n        {\n            // Arrange\n            var message = new MailMessage();\n            var headers = new[] { \"to:\", \":reply-to\", \"priority:false\" };\n\n            // Act\n            WebMail.AssignHeaderValues(message, headers);\n\n            // Assert\n            Assert.Empty(message.To);\n\n            // Assert we transparently set header values\n            Assert.Single(message.Headers);\n            Assert.Equal(\"Priority\", message.Headers.Keys[0]);\n            Assert.Equal(\"false\", message.Headers[\"Priority\"]);\n        }\n\n        [Fact]\n        public void ArgumentsToSendTakePriorityOverHeader()\n        {\n            // Arrange\n            var message = new MailMessage();\n            var headers = new[] { \"from:header-from@test.com\", \"cc:header-cc@test.com\", \"priority:low\" };\n\n            // Act\n            WebMail.SetPropertiesOnMessage(message, null, null, null, \"direct-from@test.com\", \"direct-cc@test.com\", null, null, null, null, MailPriority.High, null, false, headers);\n\n            // Assert\n            Assert.Equal(\"direct-from@test.com\", message.From.Address);\n            Assert.Equal(\"header-cc@test.com\", message.CC.First().Address);\n            Assert.Equal(\"direct-cc@test.com\", message.CC.Last().Address);\n            Assert.Equal(MailPriority.High, message.Priority);\n        }\n\n        public void Dispose()\n        {\n            // Reset ScopeStorage (written via e.g. WebMail.SmtpServer) between tests to avoid unexpected interactions.\n            ScopeStorage.CurrentProvider = new StaticScopeStorageProvider();\n            ScopeStorage.GlobalScope.Clear();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Helpers.Test/XhtmlAssert.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Net;\nusing System.Reflection;\nusing System.Text.RegularExpressions;\nusing System.Web.WebPages;\nusing System.Xml;\nusing System.Xml.Resolvers;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Helpers.Test\n{\n    // see: http://msdn.microsoft.com/en-us/library/hdf992b8(v=VS.100).aspx\n    // see: http://blogs.msdn.com/xmlteam/archive/2008/08/14/introducing-the-xmlpreloadedresolver.aspx\n    public class XhtmlAssert\n    {\n        const string Xhtml10Wrapper = \"<html xmlns=\\\"http://www.w3.org/1999/xhtml\\\"><head></head><body>{0}</body></html>\";\n        const string DOCTYPE_XHTML1_1 = \"<!DOCTYPE {0} PUBLIC \\\"-//W3C//DTD XHTML 1.1//EN\\\" \\\"xhtml11-flat.dtd\\\">\\r\\n\";\n\n        public static void Validate1_0(object result, bool addRoot = false)\n        {\n            string html = null;\n            if (addRoot)\n            {\n                html = String.Format(Xhtml10Wrapper, GetHtml(result));\n            }\n            else\n            {\n                html = GetHtml(result);\n            }\n\n            Validate1_0(html);\n        }\n\n        public static void Validate1_1(object result, string wrapper = null)\n        {\n            string root;\n            string html = GetHtml(result);\n            if (String.IsNullOrEmpty(wrapper))\n            {\n                root = GetRoot(html);\n            }\n            else\n            {\n                root = wrapper;\n                html = String.Format(\"<{0}>{1}</{0}>\", wrapper, html);\n            }\n            Validate1_1(root, html);\n        }\n\n        private static string GetHtml(object result)\n        {\n            Assert.True((result is IHtmlString) || (result is HelperResult), \"Helpers should return IHTMLString or HelperResult\");\n            return result.ToString();\n        }\n\n        private static string GetRoot(string html)\n        {\n            Regex regex = new Regex(@\"<(\\w+)[\\s>]\");\n            Match match = regex.Match(html);\n            Assert.True(match.Success, \"Could not determine root element\");\n            Assert.True(match.Groups.Count > 1, \"Could not determine root element\");\n            return match.Groups[1].Value;\n        }\n\n        private static void Validate1_0(string html)\n        {\n            XmlReaderSettings settings = new XmlReaderSettings();\n            settings.DtdProcessing = DtdProcessing.Parse;\n            settings.XmlResolver = new XmlPreloadedResolver(XmlKnownDtds.Xhtml10);\n\n            Validate(settings, html);\n        }\n\n        private static void Validate1_1(string root, string html)\n        {\n            var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Parse, ValidationType = ValidationType.DTD, XmlResolver = new AssemblyResourceXmlResolver() };\n\n            string docType = String.Format(DOCTYPE_XHTML1_1, root);\n            Validate(settings, docType + html);\n        }\n\n        private static void Validate(XmlReaderSettings settings, string html)\n        {\n            using (StringReader sr = new StringReader(html))\n            {\n                using (XmlReader reader = XmlReader.Create(sr, settings))\n                {\n                    while (reader.Read())\n                    {\n                        // XHTML element and attribute names must be lowercase, since XML is case sensitive.\n                        // The W3C validator detects this, but we must manually check since the XmlReader does not.\n                        // See: http://www.w3.org/TR/xhtml1/#h-4.2\n                        if (reader.NodeType == XmlNodeType.Element)\n                        {\n                            string element = reader.Name;\n                            Assert.True(element == element.ToLowerInvariant());\n                            if (reader.HasAttributes)\n                            {\n                                for (int i = 0; i < reader.AttributeCount; i++)\n                                {\n                                    reader.MoveToAttribute(i);\n                                    string attribute = reader.Name;\n                                    Assert.True(attribute == attribute.ToLowerInvariant());\n                                }\n                                // move back to element node\n                                reader.MoveToElement();\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        private class AssemblyResourceXmlResolver : XmlResolver\n        {\n            public override ICredentials Credentials\n            {\n                set { throw new NotSupportedException(); }\n            }\n\n            public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)\n            {\n                Assembly assembly = typeof(XhtmlAssert).Assembly;\n                return assembly.GetManifestResourceStream(\"System.Web.Helpers.Test.TestFiles.xhtml11-flat.dtd\");\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Helpers.Test/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Castle.Core\" version=\"5.1.1\" targetFramework=\"net462\" />\n  <package id=\"Moq\" version=\"4.18.4\" targetFramework=\"net462\" />\n  <package id=\"xunit\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.abstractions\" version=\"2.0.3\" targetFramework=\"net462\" />\n  <package id=\"xunit.analyzers\" version=\"1.1.0\" targetFramework=\"net462\" />\n  <package id=\"xunit.assert\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.execution\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.runner.visualstudio\" version=\"2.4.5\" targetFramework=\"net462\" developmentDependency=\"true\" />\n</packages>"
  },
  {
    "path": "test/System.Web.Http.Cors.Test/AttributeBasedPolicyProviderFactoryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Net.Http;\nusing System.Web.Cors;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Cors\n{\n    public class AttributeBasedPolicyProviderFactoryTest\n    {\n        [Fact]\n        public void GetCorsPolicyProvider_NullRequest_Throws()\n        {\n            AttributeBasedPolicyProviderFactory providerFactory = new AttributeBasedPolicyProviderFactory();\n            Assert.ThrowsArgumentNull(() =>\n                providerFactory.GetCorsPolicyProvider(null),\n                \"request\");\n        }\n\n        [Theory]\n        [InlineData(\"DELETE\", \"\", typeof(EnableCorsAttribute))]\n        [InlineData(\"Post\", \"\", typeof(DisableCorsAttribute))]\n        [InlineData(\"get\", \"\", typeof(EnableCorsAttribute))]\n        [InlineData(\"GET\", \"/3\", typeof(DisableCorsAttribute))]\n        public void GetCorsPolicyProvider_Preflight_ReturnsExpectedPolicyProvider(string httpMethod, string path, Type expectedProviderType)\n        {\n            AttributeBasedPolicyProviderFactory providerFactory = new AttributeBasedPolicyProviderFactory();\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, \"http://localhost/sample\" + path);\n            request.Headers.Add(\"Origin\", \"http://localhost\");\n            request.Headers.Add(CorsConstants.AccessControlRequestMethod, httpMethod);\n            HttpConfiguration config = new HttpConfiguration();\n            request.SetConfiguration(config);\n            IHttpRoute route = config.Routes.MapHttpRoute(\"default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            request.SetRouteData(route.GetRouteData(\"/\", request));\n\n            ICorsPolicyProvider provider = providerFactory.GetCorsPolicyProvider(request);\n\n            Assert.True(request.GetCorsRequestContext().IsPreflight);\n            Assert.IsType(expectedProviderType, provider);\n        }\n\n        [Fact]\n        public void GetCorsPolicyProvider_Preflight_ReturnsCompleteControllerContext()\n        {\n           // Arrange\n            AttributeBasedPolicyProviderFactory providerFactory = new AttributeBasedPolicyProviderFactory();\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, \"http://localhost/sample\");\n            request.Headers.Add(\"Origin\", \"http://localhost\");\n            request.Headers.Add(CorsConstants.AccessControlRequestMethod, \"POST\");\n            HttpConfiguration config = new HttpConfiguration();\n            HttpControllerContext controllerContext = null;\n            var actionSelector = new Mock<IHttpActionSelector>();\n            actionSelector.Setup(s => s.SelectAction(It.IsAny<HttpControllerContext>()))\n                          .Callback<HttpControllerContext>(context => controllerContext = context);\n            config.Services.Replace(typeof(IHttpActionSelector), actionSelector.Object);\n            request.SetConfiguration(config);\n            IHttpRoute route = config.Routes.MapHttpRoute(\"default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            request.SetRouteData(route.GetRouteData(\"/\", request));\n\n            ICorsPolicyProvider provider = providerFactory.GetCorsPolicyProvider(request);\n\n            // Assert\n            Assert.NotNull(controllerContext);\n            Assert.Equal(config, controllerContext.Configuration);\n            Assert.NotNull(controllerContext.Request);\n            Assert.NotNull(controllerContext.RequestContext);\n            Assert.NotNull(controllerContext.Controller);\n            Assert.NotNull(controllerContext.ControllerDescriptor);\n        }\n\n        [Fact]\n        public void GetCorsPolicyProvider_Preflight_DisposesControllerAfterActionSelection()\n        {\n            // Arrange\n            AttributeBasedPolicyProviderFactory providerFactory = new AttributeBasedPolicyProviderFactory();\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, \"http://localhost/sample\");\n            request.Headers.Add(\"Origin\", \"http://localhost\");\n            request.Headers.Add(CorsConstants.AccessControlRequestMethod, \"POST\");\n            HttpConfiguration config = new HttpConfiguration();\n            HttpControllerContext controllerContext = null;\n            var actionSelector = new Mock<IHttpActionSelector>();\n            actionSelector.Setup(s => s.SelectAction(It.IsAny<HttpControllerContext>()))\n                          .Callback<HttpControllerContext>(context =>\n                          {\n                              Assert.False(((SampleController)context.Controller).Disposed);\n                              controllerContext = context;\n                          });\n            config.Services.Replace(typeof(IHttpActionSelector), actionSelector.Object);\n            request.SetConfiguration(config);\n            IHttpRoute route = config.Routes.MapHttpRoute(\"default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            request.SetRouteData(route.GetRouteData(\"/\", request));\n\n            ICorsPolicyProvider provider = providerFactory.GetCorsPolicyProvider(request);\n\n            // Assert\n            Assert.True(((SampleController)controllerContext.Controller).Disposed);\n        }\n\n        [Fact]\n        public void GetCorsPolicyProvider_Preflight_NoHttpConfiguration_Throws()\n        {\n            AttributeBasedPolicyProviderFactory providerFactory = new AttributeBasedPolicyProviderFactory();\n\n            // No HttpConfiguration set on the request.\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, \"http://localhost/sample\");\n            request.Headers.Add(\"Origin\", \"http://localhost\");\n            request.Headers.Add(CorsConstants.AccessControlRequestMethod, \"GET\");\n            HttpConfiguration config = new HttpConfiguration();\n            IHttpRoute route = config.Routes.MapHttpRoute(\"default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            request.SetRouteData(route.GetRouteData(\"/\", request));\n\n            Assert.Throws<InvalidOperationException>(() =>\n                providerFactory.GetCorsPolicyProvider(request),\n                \"The request does not have an associated configuration object.\");\n        }\n\n        [Fact]\n        public void GetCorsPolicyProvider_Preflight_NoRouteData_ReturnsNull()\n        {\n            AttributeBasedPolicyProviderFactory providerFactory = new AttributeBasedPolicyProviderFactory();\n\n            // No RouteData set on the request.\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, \"http://localhost/sample\");\n            request.Headers.Add(\"Origin\", \"http://localhost\");\n            request.Headers.Add(CorsConstants.AccessControlRequestMethod, \"GET\");\n            HttpConfiguration config = new HttpConfiguration();\n            request.SetConfiguration(config);\n\n            var provider = providerFactory.GetCorsPolicyProvider(request);\n\n            Assert.Null(provider);\n        }\n\n        [Fact]\n        public void GetCorsPolicyProvider_Preflight_ReturnsDefaultPolicyProvider_WhenActionSelectionFails()\n        {\n            AttributeBasedPolicyProviderFactory providerFactory = new AttributeBasedPolicyProviderFactory();\n            ICorsPolicyProvider mockProvider = new Mock<ICorsPolicyProvider>().Object;\n            providerFactory.DefaultPolicyProvider = mockProvider;\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, \"http://localhost/sample\");\n            request.Headers.Add(\"Origin\", \"http://localhost\");\n            request.Headers.Add(CorsConstants.AccessControlRequestMethod, \"RandomMethod\");\n            HttpConfiguration config = new HttpConfiguration();\n            request.SetConfiguration(config);\n            IHttpRoute route = config.Routes.MapHttpRoute(\"default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            request.SetRouteData(route.GetRouteData(\"/\", request));\n\n            ICorsPolicyProvider provider = providerFactory.GetCorsPolicyProvider(request);\n\n            Assert.True(request.GetCorsRequestContext().IsPreflight);\n            Assert.Same(mockProvider, provider);\n        }\n\n        [Fact]\n        public void GetCorsPolicyProvider_Preflight_Throws_WhenNoDefaultPolicyProviderAndActionSelectionFails()\n        {\n            AttributeBasedPolicyProviderFactory providerFactory = new AttributeBasedPolicyProviderFactory();\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, \"http://localhost/sample\");\n            request.Headers.Add(\"Origin\", \"http://localhost\");\n            request.Headers.Add(CorsConstants.AccessControlRequestMethod, \"RandomMethod\");\n            HttpConfiguration config = new HttpConfiguration();\n            request.SetConfiguration(config);\n            IHttpRoute route = config.Routes.MapHttpRoute(\"default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            request.SetRouteData(route.GetRouteData(\"/\", request));\n\n            Assert.True(request.GetCorsRequestContext().IsPreflight);\n            Assert.Throws<HttpResponseException>(() =>\n                providerFactory.GetCorsPolicyProvider(request));\n        }\n\n        [Fact]\n        public void GetCorsPolicyProvider_ReturnsDefaultPolicyProvider()\n        {\n            ICorsPolicyProvider mockProvider = new Mock<ICorsPolicyProvider>().Object;\n            AttributeBasedPolicyProviderFactory providerFactory = new AttributeBasedPolicyProviderFactory();\n            providerFactory.DefaultPolicyProvider = mockProvider;\n            HttpRequestMessage request = new HttpRequestMessage();\n            Func<string> action = new DefaultController().Get;\n            request.SetActionDescriptor(new ReflectedHttpActionDescriptor\n            {\n                MethodInfo = action.Method\n            });\n            request.Headers.Add(\"Origin\", \"http://example.com\");\n\n            ICorsPolicyProvider policyProvider = providerFactory.GetCorsPolicyProvider(request);\n\n            Assert.Same(mockProvider, policyProvider);\n        }\n\n        [Fact]\n        public void GetCorsPolicyProvider_ReturnsPolicyProvider_OnController()\n        {\n            AttributeBasedPolicyProviderFactory providerFactory = new AttributeBasedPolicyProviderFactory();\n            HttpRequestMessage request = new HttpRequestMessage();\n            Func<string> action = new SampleController().Get;\n            HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor\n            {\n                ControllerName = \"Sample\",\n                ControllerType = typeof(SampleController)\n            };\n            request.SetActionDescriptor(new ReflectedHttpActionDescriptor\n            {\n                MethodInfo = action.Method,\n                ControllerDescriptor = controllerDescriptor\n            });\n            request.Headers.Add(\"Origin\", \"http://example.com\");\n\n            ICorsPolicyProvider policyProvider = providerFactory.GetCorsPolicyProvider(request);\n\n            Assert.NotNull(policyProvider);\n            Assert.IsType<EnableCorsAttribute>(policyProvider);\n        }\n\n        [Fact]\n        public void GetCorsPolicyProvider_ReturnsPolicyProvider_OnAction()\n        {\n            AttributeBasedPolicyProviderFactory providerFactory = new AttributeBasedPolicyProviderFactory();\n            HttpRequestMessage request = new HttpRequestMessage();\n            Func<string> action = new SampleController().Post;\n            request.SetActionDescriptor(new ReflectedHttpActionDescriptor\n            {\n                MethodInfo = action.Method\n            });\n            request.Headers.Add(\"Origin\", \"http://example.com\");\n\n            ICorsPolicyProvider policyProvider = providerFactory.GetCorsPolicyProvider(request);\n\n            Assert.NotNull(policyProvider);\n            Assert.IsType<DisableCorsAttribute>(policyProvider);\n        }\n\n        [Fact]\n        public void GetCorsPolicyProvider_Preflight_ReturnsPolicyProviderUsingPerControllerConfiguration()\n        {\n            AttributeBasedPolicyProviderFactory providerFactory = new AttributeBasedPolicyProviderFactory();\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, \"http://localhost/percontrollerconfig\");\n            request.Headers.Add(\"Origin\", \"http://localhost\");\n            request.Headers.Add(CorsConstants.AccessControlRequestMethod, \"httpmethod\");\n            HttpConfiguration config = new HttpConfiguration();\n            request.SetConfiguration(config);\n            config.Routes.MapHttpRoute(\"default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n\n            ICorsPolicyProvider provider = providerFactory.GetCorsPolicyProvider(request);\n\n            Assert.True(request.GetCorsRequestContext().IsPreflight);\n            EnableCorsAttribute enableCorsAttribute = Assert.IsType<EnableCorsAttribute>(provider);\n            string origin = Assert.Single(enableCorsAttribute.Origins);\n            Assert.Equal(\"http://example.com\", origin);\n        }\n\n        [Fact]\n        public void GetCorsPolicyProvider_Preflight_DoesNotUseRouteDataOnTheRequest()\n        {\n            AttributeBasedPolicyProviderFactory providerFactory = new AttributeBasedPolicyProviderFactory();\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, \"http://localhost/sample\");\n            request.Headers.Add(\"Origin\", \"http://localhost\");\n            request.Headers.Add(CorsConstants.AccessControlRequestMethod, \"Put\");\n            HttpConfiguration config = new HttpConfiguration();\n            request.SetConfiguration(config);\n            var route = config.Routes.MapHttpRoute(\"default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            request.SetRouteData(new HttpRouteData(route, new HttpRouteValueDictionary(new { action = \"Options\", controller = \"sample\", id = 2 })));\n\n            ICorsPolicyProvider provider = providerFactory.GetCorsPolicyProvider(request);\n\n            Assert.True(request.GetCorsRequestContext().IsPreflight);\n            EnableCorsAttribute enableCorsAttribute = Assert.IsType<EnableCorsAttribute>(provider);\n            Assert.Equal(2, enableCorsAttribute.Origins.Count());\n            Assert.Equal(\"http://example.com\", enableCorsAttribute.Origins[0]);\n            Assert.Equal(\"http://localhost\", enableCorsAttribute.Origins[1]);\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Cors.Test/Controllers/DefaultController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Cors\n{\n    public class DefaultController : ApiController\n    {\n        public string Get()\n        {\n            return \"value\";\n        }\n\n        [EnableCors(\"http://restrictedExample.com\", \"*\", \"*\")]\n        public string Post()\n        {\n            return \"value created\";\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Cors.Test/Controllers/ExternalActionSelectorAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Http.Controllers;\n\nnamespace System.Web.Http.Cors.Test.Controllers\n{\n    public class ExternalActionSelectorAttribute : Attribute, IControllerConfiguration\n    {\n        public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)\n        {\n            controllerSettings.Services.Replace(typeof(IHttpActionSelector), new ExternalActionSelector());\n        }\n\n        private class ExternalActionSelector : IHttpActionSelector\n        {\n            public HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)\n            {\n                HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor\n                {\n                    ControllerName = \"Sample\",\n                    ControllerType = typeof(SampleController)\n                };\n                Action action = new SampleController().Head;\n                return new ReflectedHttpActionDescriptor(controllerDescriptor, action.Method);\n            }\n\n            public ILookup<string, HttpActionDescriptor> GetActionMapping(HttpControllerDescriptor controllerDescriptor)\n            {\n                List<HttpActionDescriptor> descriptors = new List<HttpActionDescriptor>();\n                return descriptors.ToLookup(d => d.ActionName);\n            }\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Cors.Test/Controllers/PerControllerConfigController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Cors.Test.Controllers\n{\n    [ExternalActionSelector]\n    public class PerControllerConfigController : ApiController\n    {\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Cors.Test/Controllers/SampleController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Cors\n{\n    [EnableCors(\"*\", \"*\", \"*\")]\n    public class SampleController : ApiController\n    {\n        public bool Disposed { get; private set; }\n\n        public string Get()\n        {\n            return \"value\";\n        }\n\n        [DisableCors]\n        public string Get(int id)\n        {\n            return \"value\" + id;\n        }\n\n        [DisableCors]\n        public string Post()\n        {\n            return \"value\";\n        }\n\n        public void Delete()\n        {\n        }\n\n        [EnableCors(\"http://example.com\", \"*\", \"*\")]\n        public void Head()\n        {\n        }\n\n        [EnableCors(\"http://example.com, http://localhost\", \"*\", \"*\")]\n        public void Put()\n        {\n        }\n\n        protected override void Dispose(bool disposing)\n        {\n            Disposed = true;\n            base.Dispose(disposing);\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Cors.Test/Controllers/ThrowingController.cs",
    "content": "﻿namespace System.Web.Http.Cors\n{\n    [EnableCors(\"*\", \"*\", \"*\")]\n    public class ThrowingController : ApiController\n    {\n        public string Get()\n        {\n            throw new Exception();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Cors.Test/CorsHttpConfigurationExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Cors;\nusing System.Web.Http.Cors.Tracing;\nusing System.Web.Http.Tracing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Cors.Test\n{\n    public class CorsHttpConfigurationExtensionsTest\n    {\n        [Fact]\n        public void EnableCors_NullConfig_Throws()\n        {\n            Assert.ThrowsArgumentNull(() =>\n            {\n                CorsHttpConfigurationExtensions.EnableCors(null);\n            },\n            \"httpConfiguration\");\n        }\n\n        [Fact]\n        public void EnableCors_AddsCorsMessageHandler_DuringInitializerExecution()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.MessageHandlers.Clear();\n            config.EnableCors();\n\n            Assert.Empty(config.MessageHandlers);\n\n            config.Initializer(config);\n\n            var handler = Assert.Single(config.MessageHandlers);\n            Assert.IsType<CorsMessageHandler>(handler);\n        }\n\n        [Fact]\n        public void EnableCors_IsIdempotent()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.MessageHandlers.Clear();\n            config.EnableCors();\n            config.EnableCors();\n            config.EnableCors();\n\n            Assert.Empty(config.MessageHandlers);\n\n            config.Initializer(config);\n\n            var handler = Assert.Single(config.MessageHandlers);\n            Assert.IsType<CorsMessageHandler>(handler);\n        }\n\n        [Fact]\n        public void EnableCors_Initializer_IsIdempotent()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.MessageHandlers.Clear();\n            config.EnableCors();\n\n            Assert.Empty(config.MessageHandlers);\n\n            config.Initializer(config);\n            config.Initializer(config);\n            config.Initializer(config);\n\n            var handler = Assert.Single(config.MessageHandlers);\n            Assert.IsType<CorsMessageHandler>(handler);\n        }\n\n        [Fact]\n        public void EnableCors_AddsCorsPolicyProvider()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.MessageHandlers.Clear();\n            EnableCorsAttribute policyProvider = new EnableCorsAttribute(origins: \"*\", headers: \"*\", methods: \"*\");\n            config.EnableCors(policyProvider);\n            config.Initializer(config);\n\n            ICorsPolicyProviderFactory providerFactory = config.GetCorsPolicyProviderFactory();\n            AttributeBasedPolicyProviderFactory attributeProviderFactory = Assert.IsType<AttributeBasedPolicyProviderFactory>(providerFactory);\n            Assert.Same(policyProvider, attributeProviderFactory.DefaultPolicyProvider);\n        }\n\n        [Fact]\n        public void EnableCors_AddsTracers_WhenTracingIsEnabled()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            ITraceWriter traceMock = new Mock<ITraceWriter>().Object;\n            config.Services.Replace(typeof(ITraceWriter), traceMock);\n            config.MessageHandlers.Clear();\n            EnableCorsAttribute policyProvider = new EnableCorsAttribute(origins: \"*\", headers: \"*\", methods: \"*\");\n            config.EnableCors(policyProvider);\n            config.Initializer(config);\n\n            ICorsPolicyProviderFactory providerFactory = config.GetCorsPolicyProviderFactory();\n            Assert.IsType<CorsPolicyProviderFactoryTracer>(providerFactory);\n        }\n\n        [Fact]\n        public void GetCorsPolicyProviderFactory_NullHttpConfiguration_Throws()\n        {\n            Assert.ThrowsArgumentNull(() =>\n            {\n                CorsHttpConfigurationExtensions.GetCorsPolicyProviderFactory(null);\n            },\n            \"httpConfiguration\");\n        }\n\n        [Fact]\n        public void GetCorsPolicyProviderFactory_ReturnsDefaultCorsPolicyProviderFactory()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            ICorsPolicyProviderFactory providerFactory = config.GetCorsPolicyProviderFactory();\n\n            Assert.NotNull(providerFactory);\n            Assert.IsType<AttributeBasedPolicyProviderFactory>(providerFactory);\n        }\n\n        [Fact]\n        public void GetCorsPolicyProviderFactory_ReturnsTheCustomCorsPolicyProviderFactory()\n        {\n            ICorsPolicyProviderFactory mockFactory = new Mock<ICorsPolicyProviderFactory>().Object;\n            HttpConfiguration config = new HttpConfiguration();\n            config.SetCorsPolicyProviderFactory(mockFactory);\n            ICorsPolicyProviderFactory providerFactory = config.GetCorsPolicyProviderFactory();\n\n            Assert.Same(mockFactory, providerFactory);\n        }\n\n        [Fact]\n        public void GetCorsEngine_NullHttpConfiguration_Throws()\n        {\n            Assert.ThrowsArgumentNull(() =>\n            {\n                CorsHttpConfigurationExtensions.GetCorsEngine(null);\n            },\n            \"httpConfiguration\");\n        }\n\n        [Fact]\n        public void GetCorsEngine_ReturnsDefaultCorsEngine()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            ICorsEngine corsEngine = config.GetCorsEngine();\n            Assert.IsType<CorsEngine>(corsEngine);\n        }\n\n        [Fact]\n        public void GetCorsEngine_ReturnsTheCustomCorsEngine()\n        {\n            ICorsEngine mockEngine = new Mock<ICorsEngine>().Object;\n            HttpConfiguration config = new HttpConfiguration();\n            config.SetCorsEngine(mockEngine);\n            ICorsEngine corsEngine = config.GetCorsEngine();\n            Assert.Same(mockEngine, corsEngine);\n        }\n\n        [Fact]\n        public void SetCorsEngine_NullHttpConfiguration_Throws()\n        {\n            Assert.ThrowsArgumentNull(() =>\n            {\n                CorsHttpConfigurationExtensions.SetCorsEngine(null, new CorsEngine());\n            },\n            \"httpConfiguration\");\n        }\n\n        [Fact]\n        public void SetCorsEngine_NullCorsEngine_Throws()\n        {\n            Assert.ThrowsArgumentNull(() =>\n            {\n                CorsHttpConfigurationExtensions.SetCorsEngine(new HttpConfiguration(), null);\n            },\n            \"corsEngine\");\n        }\n\n        [Fact]\n        public void SetCorsPolicyProviderFactory_NullHttpConfiguration_Throws()\n        {\n            Assert.ThrowsArgumentNull(() =>\n            {\n                CorsHttpConfigurationExtensions.SetCorsPolicyProviderFactory(null, new AttributeBasedPolicyProviderFactory());\n            },\n            \"httpConfiguration\");\n        }\n\n        [Fact]\n        public void SetCorsPolicyProviderFactory_NullCorsEngine_Throws()\n        {\n            Assert.ThrowsArgumentNull(() =>\n            {\n                CorsHttpConfigurationExtensions.SetCorsPolicyProviderFactory(new HttpConfiguration(), null);\n            },\n            \"corsPolicyProviderFactory\");\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Cors.Test/CorsHttpRequestMessageExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Cors;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Cors.Test\n{\n    public class CorsHttpRequestMessageExtensionsTest\n    {\n        [Fact]\n        public void GetCorsRequestContext_NullRequestParam_Throws()\n        {\n            Assert.ThrowsArgumentNull(\n                () => CorsHttpRequestMessageExtensions.GetCorsRequestContext(null),\n                \"request\");\n        }\n\n        [Fact]\n        public void GetCorsRequestContext_NotOrigin_ReturnsNull()\n        {\n            HttpRequestMessage request = new HttpRequestMessage();\n            CorsRequestContext result = request.GetCorsRequestContext();\n            Assert.Null(result);\n        }\n\n        [Fact]\n        public void GetCorsRequestContext_CachesTheContext()\n        {\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, \"http://example.com/test\");\n            request.Headers.Add(\"Origin\", \"foo\");\n            request.Headers.Add(\"Host\", \"example.com\");\n            request.Headers.Add(\"Access-Control-Request-Method\", \"bar\");\n\n            CorsRequestContext result = request.GetCorsRequestContext();\n            CorsRequestContext result2 = request.GetCorsRequestContext();\n\n            Assert.Same(result, result2);\n        }\n\n        [Fact]\n        public void GetCorsRequestContext_ReturnsHost()\n        {\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, \"http://example.com/test\");\n            request.Headers.Add(\"Origin\", \"foo\");\n            request.Headers.Add(\"Host\", \"example.com\");\n\n            CorsRequestContext result = request.GetCorsRequestContext();\n\n            Assert.Equal(\"example.com\", result.Host);\n        }\n\n        [Fact]\n        public void GetCorsRequestContext_ReturnsHttpMethod()\n        {\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, \"http://example.com/test\");\n            request.Headers.Add(\"Origin\", \"foo\");\n\n            CorsRequestContext result = request.GetCorsRequestContext();\n\n            Assert.Equal(\"OPTIONS\", result.HttpMethod);\n        }\n\n        [Fact]\n        public void GetCorsRequestContext_ReturnsOrigin()\n        {\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, \"http://example.com/test\");\n            request.Headers.Add(\"Origin\", \"foo\");\n\n            CorsRequestContext result = request.GetCorsRequestContext();\n\n            Assert.Equal(\"foo\", result.Origin);\n        }\n\n        [Fact]\n        public void GetCorsRequestContext_ReturnsRequestMethod()\n        {\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, \"http://example.com/test\");\n            request.Headers.Add(\"Origin\", \"foo\");\n            request.Headers.Add(\"Access-Control-Request-Method\", \"bar\");\n\n            CorsRequestContext result = request.GetCorsRequestContext();\n\n            Assert.Equal(\"bar\", result.AccessControlRequestMethod);\n        }\n\n        [Fact]\n        public void GetCorsRequestContext_RetunsEmptyRequestHeaders()\n        {\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, \"http://example.com/test\");\n            request.Headers.Add(\"Origin\", \"foo\");\n\n            CorsRequestContext result = request.GetCorsRequestContext();\n\n            Assert.Empty(result.AccessControlRequestHeaders);\n        }\n\n        [Fact]\n        public void GetCorsRequestContext_RetunsRequestHeaders()\n        {\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, \"http://example.com/test\");\n            request.Headers.Add(\"Origin\", \"foo\");\n            request.Headers.Add(\"Access-Control-Request-Headers\", \"foo, bar\");\n\n            CorsRequestContext result = request.GetCorsRequestContext();\n\n            Assert.Equal(2, result.AccessControlRequestHeaders.Count);\n            Assert.Contains(\"foo\", result.AccessControlRequestHeaders);\n            Assert.Contains(\"bar\", result.AccessControlRequestHeaders);\n        }\n\n        [Fact]\n        public void GetCorsRequestContext_RetunsRequestHeadersFromMultipleAccessControlRequestHeaders()\n        {\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, \"http://example.com/test\");\n            request.Headers.Add(\"Origin\", \"foo\");\n            request.Headers.Add(\"Access-Control-Request-Headers\", \"foo, bar\");\n            request.Headers.Add(\"Access-Control-Request-Headers\", \"extra,baz\");\n\n            CorsRequestContext result = request.GetCorsRequestContext();\n\n            Assert.Equal(4, result.AccessControlRequestHeaders.Count);\n            Assert.Contains(\"foo\", result.AccessControlRequestHeaders);\n            Assert.Contains(\"bar\", result.AccessControlRequestHeaders);\n            Assert.Contains(\"extra\", result.AccessControlRequestHeaders);\n            Assert.Contains(\"baz\", result.AccessControlRequestHeaders);\n        }\n\n        [Fact]\n        public void GetCorsRequestContext_ReturnsHttpRequestInThePropertiesCollection()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, \"http://example.com/test\");\n            request.Headers.Add(\"Origin\", \"foo\");\n\n            // Act \n            CorsRequestContext result = request.GetCorsRequestContext();\n\n            // Assert\n            object actualRequest;\n            result.Properties.TryGetValue(typeof(HttpRequestMessage).FullName, out actualRequest);\n            Assert.Equal(request, actualRequest);\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Cors.Test/CorsHttpResponseMessageExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Net.Http;\nusing System.Net.Http.Headers;\nusing System.Web.Http.Cors;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Cors.Test.WebAPI\n{\n    public class CorsHttpResponseMessageExtensionsTest\n    {\n        [Fact]\n        public void WriteCorsHeaders_NullResponse_Throws()\n        {\n            Assert.ThrowsArgumentNull(() =>\n                System.Web.Http.Cors.CorsHttpResponseMessageExtensions.WriteCorsHeaders(null, new CorsResult()),\n                \"response\");\n        }\n\n        [Fact]\n        public void WriteCorsHeaders_NullCorsResult_Throws()\n        {\n            HttpResponseMessage response = new HttpResponseMessage();\n\n            Assert.ThrowsArgumentNull(() =>\n                response.WriteCorsHeaders(null),\n                \"corsResult\");\n        }\n\n        [Fact]\n        public void WriteCorsHeaders_EmptyCorsResult_EmptyHeaders()\n        {\n            HttpResponseMessage response = new HttpResponseMessage();\n            response.WriteCorsHeaders(new CorsResult());\n            Assert.Empty(response.Headers);\n        }\n\n        [Fact]\n        public void WriteCorsHeaders_WritesAllowMethods()\n        {\n            HttpResponseMessage response = new HttpResponseMessage();\n            CorsResult corsResult = new CorsResult();\n            corsResult.AllowedMethods.Add(\"DELETE\");\n            corsResult.AllowedMethods.Add(\"PUT\");\n\n            response.WriteCorsHeaders(corsResult);\n            HttpResponseHeaders headers = response.Headers;\n\n            Assert.Single(headers);\n            string[] allowMethods = headers.GetValues(\"Access-Control-Allow-Methods\").FirstOrDefault().Split(',');\n            Assert.Contains(\"DELETE\", allowMethods);\n            Assert.Contains(\"PUT\", allowMethods);\n        }\n\n        [Fact]\n        public void WriteCorsHeaders_WritesAllowExposedHeaders()\n        {\n            HttpResponseMessage response = new HttpResponseMessage();\n            CorsResult corsResult = new CorsResult();\n            corsResult.AllowedExposedHeaders.Add(\"baz\");\n\n            response.WriteCorsHeaders(corsResult);\n            HttpResponseHeaders headers = response.Headers;\n\n            Assert.Single(headers);\n            string[] exposedHeaders = headers.GetValues(\"Access-Control-Expose-Headers\").FirstOrDefault().Split(',');\n            Assert.Contains(\"baz\", exposedHeaders);\n        }\n\n        [Fact]\n        public void WriteCorsHeaders_WritesAllowHeaders()\n        {\n            HttpResponseMessage response = new HttpResponseMessage();\n            CorsResult corsResult = new CorsResult();\n            corsResult.AllowedHeaders.Add(\"foo\");\n            corsResult.AllowedHeaders.Add(\"bar\");\n\n            response.WriteCorsHeaders(corsResult);\n            HttpResponseHeaders headers = response.Headers;\n\n            Assert.Single(headers);\n            string[] allowHeaders = headers.GetValues(\"Access-Control-Allow-Headers\").FirstOrDefault().Split(',');\n            Assert.Contains(\"foo\", allowHeaders);\n            Assert.Contains(\"bar\", allowHeaders);\n        }\n\n        [Fact]\n        public void WriteCorsHeaders_WritesAllowCredentials()\n        {\n            HttpResponseMessage response = new HttpResponseMessage();\n            CorsResult corsResult = new CorsResult\n            {\n                SupportsCredentials = true\n            };\n\n            response.WriteCorsHeaders(corsResult);\n            HttpResponseHeaders headers = response.Headers;\n\n            Assert.Single(headers);\n            Assert.Equal(\"true\", headers.GetValues(\"Access-Control-Allow-Credentials\").FirstOrDefault());\n        }\n\n        [Fact]\n        public void WriteCorsHeaders_WritesAllowOrigin()\n        {\n            HttpResponseMessage response = new HttpResponseMessage();\n            CorsResult corsResult = new CorsResult\n            {\n                AllowedOrigin = \"*\"\n            };\n\n            response.WriteCorsHeaders(corsResult);\n            HttpResponseHeaders headers = response.Headers;\n\n            Assert.Single(headers);\n            Assert.Equal(\"*\", headers.GetValues(\"Access-Control-Allow-Origin\").FirstOrDefault());\n        }\n\n        [Fact]\n        public void WriteCorsHeaders_WritesPreflightMaxAge()\n        {\n            HttpResponseMessage response = new HttpResponseMessage();\n            CorsResult corsResult = new CorsResult\n            {\n                PreflightMaxAge = 10\n            };\n\n            response.WriteCorsHeaders(corsResult);\n            HttpResponseHeaders headers = response.Headers;\n\n            Assert.Single(headers);\n            Assert.Equal(\"10\", headers.GetValues(\"Access-Control-Max-Age\").FirstOrDefault());\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Cors.Test/CorsMessageHandlerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Cors;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Hosting;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Cors\n{\n    public class CorsMessageHandlerTest\n    {\n        [Fact]\n        public void Constructor_NullConfig_Throws()\n        {\n            Assert.ThrowsArgumentNull(() => new CorsMessageHandler(null), \"httpConfiguration\");\n        }\n\n        [Fact]\n        public async Task SendAsync_DoesNotAddHeaders_WhenOriginIsMissing()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"default\", \"{controller}\");\n            HttpServer server = new HttpServer(config);\n            CorsMessageHandler corsHandler = new CorsMessageHandler(config);\n            corsHandler.InnerHandler = server;\n            HttpMessageInvoker invoker = new HttpMessageInvoker(corsHandler);\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, \"http://localhost/sample\");\n\n            HttpResponseMessage response = await invoker.SendAsync(request, CancellationToken.None);\n\n            Assert.Empty(response.Headers);\n        }\n\n        [Theory]\n        [InlineData(\"GET\", \"*\")]\n        [InlineData(\"DELETE\", \"*\")]\n        [InlineData(\"HEAD\", \"http://example.com\")]\n        public async Task SendAsync_ReturnsAllowAOrigin(string httpMethod, string expectedOrigin)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"default\", \"{controller}\");\n            HttpServer server = new HttpServer(config);\n            CorsMessageHandler corsHandler = new CorsMessageHandler(config);\n            corsHandler.InnerHandler = server;\n            HttpMessageInvoker invoker = new HttpMessageInvoker(corsHandler);\n            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(httpMethod), \"http://localhost/sample\");\n            request.Headers.Add(CorsConstants.Origin, \"http://example.com\");\n\n            HttpResponseMessage response = await invoker.SendAsync(request, CancellationToken.None);\n            string origin = response.Headers.GetValues(\"Access-Control-Allow-Origin\").FirstOrDefault();\n\n            Assert.Equal(expectedOrigin, origin);\n        }\n\n        [Theory]\n        [InlineData(\"DELETE\", \"*\", \"foo,bar\")]\n        [InlineData(\"PUT\", \"http://localhost\", \"content-type,custom\")]\n        public async Task SendAsync_Preflight_ReturnsAllowMethodsAndAllowHeaders(string requestedMethod, string expectedOrigin, string requestedHeaders)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"default\", \"{controller}\");\n            HttpServer server = new HttpServer(config);\n            CorsMessageHandler corsHandler = new CorsMessageHandler(config);\n            corsHandler.InnerHandler = server;\n            HttpMessageInvoker invoker = new HttpMessageInvoker(corsHandler);\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, \"http://localhost/sample\");\n            request.SetConfiguration(config);\n            request.Headers.Add(CorsConstants.Origin, \"http://localhost\");\n            request.Headers.Add(CorsConstants.AccessControlRequestMethod, requestedMethod);\n            request.Headers.Add(CorsConstants.AccessControlRequestHeaders, requestedHeaders);\n\n            HttpResponseMessage response = await invoker.SendAsync(request, CancellationToken.None);\n            string origin = response.Headers.GetValues(CorsConstants.AccessControlAllowOrigin).FirstOrDefault();\n            string allowMethod = response.Headers.GetValues(CorsConstants.AccessControlAllowMethods).FirstOrDefault();\n            string[] allowHeaders = response.Headers.GetValues(CorsConstants.AccessControlAllowHeaders).FirstOrDefault().Split(',');\n            string[] requestedHeaderArray = requestedHeaders.Split(',');\n\n            Assert.Equal(HttpStatusCode.OK, response.StatusCode);\n            Assert.Equal(expectedOrigin, origin);\n            Assert.Equal(requestedMethod, allowMethod);\n            foreach (string requestedHeader in requestedHeaderArray)\n            {\n                Assert.Contains(requestedHeader, allowHeaders);\n            }\n        }\n\n        [Fact]\n        public async Task SendAsync_Preflight_ReturnsOriginalResponse_WhenNoCorsPolicyProviderIsFound()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"default\", \"{controller}\");\n            config.MessageHandlers.Add(new CorsMessageHandler(config));\n            HttpServer server = new HttpServer(config);\n            HttpMessageInvoker invoker = new HttpMessageInvoker(server);\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, \"http://localhost/default\");\n            request.Headers.Add(CorsConstants.Origin, \"http://localhost\");\n            request.Headers.Add(CorsConstants.AccessControlRequestMethod, \"GET\");\n\n            HttpResponseMessage response = await invoker.SendAsync(request, CancellationToken.None);\n\n            Assert.Equal(HttpStatusCode.MethodNotAllowed, response.StatusCode);\n        }\n\n        [Fact]\n        public async Task SendAsync_Preflight_ReturnsBadRequest_WhenOriginIsNotAllowed()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"default\", \"{controller}\");\n            config.MessageHandlers.Add(new CorsMessageHandler(config));\n            HttpServer server = new HttpServer(config);\n            HttpMessageInvoker invoker = new HttpMessageInvoker(server);\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, \"http://localhost/default\");\n            request.Headers.Add(CorsConstants.Origin, \"http://localhost\");\n            request.Headers.Add(CorsConstants.AccessControlRequestMethod, \"POST\");\n\n            HttpResponseMessage response = await invoker.SendAsync(request, CancellationToken.None);\n\n            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);\n            Assert.Equal(\"{\\\"Message\\\":\\\"The origin 'http://localhost' is not allowed.\\\"}\", await response.Content.ReadAsStringAsync());\n        }\n\n        [Fact]\n        public async Task SendAsync_Preflight_ReturnsSoftNotFound_WhenNoRouteMatches()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"default\", \"foo\");\n            config.MessageHandlers.Add(new CorsMessageHandler(config));\n            HttpServer server = new HttpServer(config);\n            HttpMessageInvoker invoker = new HttpMessageInvoker(server);\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, \"http://localhost/nomatch\");\n            request.Headers.Add(CorsConstants.Origin, \"http://localhost\");\n            request.Headers.Add(CorsConstants.AccessControlRequestMethod, \"POST\");\n\n            HttpResponseMessage response = await invoker.SendAsync(request, CancellationToken.None);\n\n            bool noRouteMatched = Assert.IsType<bool>(request.Properties[HttpPropertyKeys.NoRouteMatched]);\n            Assert.True(noRouteMatched);\n            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);\n            Assert.Equal(\"{\\\"Message\\\":\\\"No HTTP resource was found that matches the request URI 'http://localhost/nomatch'.\\\"}\", await response.Content.ReadAsStringAsync());\n        }\n\n        [Fact]\n        public async Task SendAsync_Preflight_ReturnsSoftNotFound_WhenControllerSelectionFails()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"default\", \"{controller}\");\n            config.MessageHandlers.Add(new CorsMessageHandler(config));\n            HttpServer server = new HttpServer(config);\n            HttpMessageInvoker invoker = new HttpMessageInvoker(server);\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, \"http://localhost/nomatch\");\n            request.Headers.Add(CorsConstants.Origin, \"http://localhost\");\n            request.Headers.Add(CorsConstants.AccessControlRequestMethod, \"POST\");\n\n            HttpResponseMessage response = await invoker.SendAsync(request, CancellationToken.None);\n\n            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);\n        }\n\n        [Fact]\n        public async Task SendAsync_HandlesExceptions_ThrownDuringPreflight()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"default\", \"{controller}\");\n            HttpServer server = new HttpServer(config);\n            CorsMessageHandler corsHandler = new CorsMessageHandler(config);\n            corsHandler.InnerHandler = server;\n            HttpMessageInvoker invoker = new HttpMessageInvoker(corsHandler);\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, \"http://localhost/sample\");\n            request.SetConfiguration(config);\n            request.Headers.Add(CorsConstants.Origin, \"http://localhost\");\n            request.Headers.Add(CorsConstants.AccessControlRequestMethod, \"RandomMethod\");\n\n            HttpResponseMessage response = await invoker.SendAsync(request, CancellationToken.None);\n\n            Assert.Equal(HttpStatusCode.MethodNotAllowed, response.StatusCode);\n        }\n\n        [Fact]\n        public async Task SendAsync_Preflight_RethrowsExceptions_WhenRethrowFlagIsTrue()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"default\", \"{controller}\");\n            HttpServer server = new HttpServer(config);\n            CorsMessageHandler corsHandler = new CorsMessageHandler(config, true);\n            corsHandler.InnerHandler = server;\n            HttpMessageInvoker invoker = new HttpMessageInvoker(corsHandler);\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, \"http://localhost/sample\");\n            request.SetConfiguration(config);\n            request.Headers.Add(CorsConstants.Origin, \"http://localhost\");\n            request.Headers.Add(CorsConstants.AccessControlRequestMethod, \"RandomMethod\");\n\n            await Assert.ThrowsAsync<HttpResponseException>(() => invoker.SendAsync(request, CancellationToken.None));\n        }\n\n        [Fact]\n        public async Task SendAsync_RethrowsExceptions_WhenRethrowFlagIsTrue()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"default\", \"{controller}\");\n            config.Services.Replace(typeof(IExceptionHandler), new PassthroughExceptionHandler());\n            HttpServer server = new HttpServer(config);\n            CorsMessageHandler corsHandler = new CorsMessageHandler(config, true);\n            corsHandler.InnerHandler = server;\n            HttpMessageInvoker invoker = new HttpMessageInvoker(corsHandler);\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, \"http://localhost/throwing\");\n            request.SetConfiguration(config);\n            request.Headers.Add(CorsConstants.Origin, \"http://localhost\");\n\n            await Assert.ThrowsAsync<Exception>(() => invoker.SendAsync(request, CancellationToken.None));\n        }\n\n        [Fact]\n        public Task HandleCorsRequestAsync_NullConfig_Throws()\n        {\n            CorsMessageHandler corsHandler = new CorsMessageHandler(new HttpConfiguration());\n            return Assert.ThrowsArgumentNullAsync(\n                () => corsHandler.HandleCorsRequestAsync(null, new CorsRequestContext(), CancellationToken.None),\n                \"request\");\n        }\n\n        [Fact]\n        public Task HandleCorsRequestAsync_NullContext_Throws()\n        {\n            CorsMessageHandler corsHandler = new CorsMessageHandler(new HttpConfiguration());\n            return Assert.ThrowsArgumentNullAsync(\n                () => corsHandler.HandleCorsRequestAsync(new HttpRequestMessage(), null, CancellationToken.None),\n                \"corsRequestContext\");\n        }\n\n        [Fact]\n        public async Task HandleCorsPreflightRequestAsync_ReturnsBadRequestWhenAccessControlRequestMethodIsInvalid()\n        {\n            CorsMessageHandler corsHandler = new CorsMessageHandler(new HttpConfiguration());\n            HttpResponseMessage response = await corsHandler.HandleCorsPreflightRequestAsync(new HttpRequestMessage(),\n                new CorsRequestContext\n                {\n                    AccessControlRequestMethod = \"Get-http://localhost\"\n                },\n                CancellationToken.None);\n\n            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);\n            Assert.Equal(\"The \\\"Access-Control-Request-Method\\\" header value 'Get-http://localhost' is invalid.\", (await response.Content.ReadAsAsync<HttpError>()).Message);\n        }\n\n        [Theory]\n        [InlineData(\"\")]\n        [InlineData(null)]\n        public async Task HandleCorsPreflightRequestAsync_ReturnsBadRequestWhenAccessControlRequestMethodIsNullOrEmpty(string accessControlRequestMethod)\n        {\n            CorsMessageHandler corsHandler = new CorsMessageHandler(new HttpConfiguration());\n            HttpResponseMessage response = await corsHandler.HandleCorsPreflightRequestAsync(new HttpRequestMessage(),\n                new CorsRequestContext\n                {\n                    AccessControlRequestMethod = accessControlRequestMethod\n                },\n                CancellationToken.None);\n\n            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);\n            Assert.Equal(\"The \\\"Access-Control-Request-Method\\\" header value cannot be null or empty.\", (await response.Content.ReadAsAsync<HttpError>()).Message);\n        }\n\n        [Fact]\n        public Task HandleCorsPreflightRequestAsync_NullContext_Throws()\n        {\n            CorsMessageHandler corsHandler = new CorsMessageHandler(new HttpConfiguration());\n            return Assert.ThrowsArgumentNullAsync(\n                () => corsHandler.HandleCorsPreflightRequestAsync(new HttpRequestMessage(), null, CancellationToken.None),\n                \"corsRequestContext\");\n        }\n\n        private class PassthroughExceptionHandler : IExceptionHandler\n        {\n            public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)\n            {\n                throw context.Exception;\n            }\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Cors.Test/DisableCorsAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Cors;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Cors.Test\n{\n    public class DisableCorsAttributeTest\n    {\n        [Fact]\n        public async Task GetCorsPolicyAsync_ReturnsNull()\n        {\n            DisableCorsAttribute disableCors = new DisableCorsAttribute();\n            CorsPolicy corsPolicy = await disableCors.GetCorsPolicyAsync(new HttpRequestMessage(), CancellationToken.None);\n\n            Assert.Null(corsPolicy);\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Cors.Test/EnableCorsAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Cors;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Cors.Test\n{\n    public class EnableCorsAttributeTest\n    {\n        [Fact]\n        public void Default_Constructor()\n        {\n            EnableCorsAttribute enableCors = new EnableCorsAttribute(origins: \"*\", headers: \"*\", methods: \"*\");\n\n            Assert.False(enableCors.SupportsCredentials);\n            Assert.Empty(enableCors.ExposedHeaders);\n            Assert.Empty(enableCors.Headers);\n            Assert.Empty(enableCors.Methods);\n            Assert.Empty(enableCors.Origins);\n            Assert.Equal(-1, enableCors.PreflightMaxAge);\n        }\n\n        [Theory]\n        [InlineData(null)]\n        [InlineData(\"\")]\n        public void SettingNullOrEmptyOrigins_Throws(string origins)\n        {\n            Assert.ThrowsArgument(() =>\n            {\n                new EnableCorsAttribute(origins: origins, headers: \"*\", methods: \"*\");\n            },\n            \"origins\",\n            \"Value cannot be null or an empty string.\");\n        }\n\n        [Fact]\n        public async Task GetCorsPolicyAsync_DefaultPolicyValues()\n        {\n            EnableCorsAttribute enableCors = new EnableCorsAttribute(origins: \"*\", headers: \"*\", methods: \"*\");\n\n            CorsPolicy corsPolicy = await enableCors.GetCorsPolicyAsync(new HttpRequestMessage(), CancellationToken.None);\n\n            Assert.True(corsPolicy.AllowAnyHeader);\n            Assert.True(corsPolicy.AllowAnyMethod);\n            Assert.True(corsPolicy.AllowAnyOrigin);\n            Assert.False(corsPolicy.SupportsCredentials);\n            Assert.Empty(corsPolicy.ExposedHeaders);\n            Assert.Empty(corsPolicy.Headers);\n            Assert.Empty(corsPolicy.Methods);\n            Assert.Empty(corsPolicy.Origins);\n            Assert.Null(corsPolicy.PreflightMaxAge);\n        }\n\n        [Fact]\n        public async Task GetCorsPolicyAsync_RetunsExpectedSupportsCredentials()\n        {\n            EnableCorsAttribute enableCors = new EnableCorsAttribute(origins: \"*\", headers: \"*\", methods: \"*\")\n            {\n                SupportsCredentials = true\n            };\n\n            CorsPolicy corsPolicy = await enableCors.GetCorsPolicyAsync(new HttpRequestMessage(), CancellationToken.None);\n\n            Assert.True(corsPolicy.SupportsCredentials);\n        }\n\n        [Fact]\n        public async Task GetCorsPolicyAsync_RetunsExpectedPreflightMaxAge()\n        {\n            EnableCorsAttribute enableCors = new EnableCorsAttribute(origins: \"*\", headers: \"*\", methods: \"*\")\n            {\n                PreflightMaxAge = 20\n            };\n\n            CorsPolicy corsPolicy = await enableCors.GetCorsPolicyAsync(new HttpRequestMessage(), CancellationToken.None);\n\n            Assert.Equal(20, corsPolicy.PreflightMaxAge);\n        }\n\n        [Theory]\n        [InlineData(\"foo\", new[] { \"foo\" })]\n        [InlineData(\"foo \", new[] { \"foo\" })]\n        [InlineData(\"foo,\", new[] { \"foo\" })]\n        [InlineData(\"foo,bar\", new[] { \"foo\", \"bar\" })]\n        [InlineData(\"foo, bar\", new[] { \"foo\", \"bar\" })]\n        [InlineData(\"foo,bar,\", new[] { \"foo\", \"bar\" })]\n        public async Task GetCorsPolicyAsync_RetunsExpectedExposeHeaders(string exposedHeaders, string[] expectedResults)\n        {\n            EnableCorsAttribute enableCors = new EnableCorsAttribute(origins: \"*\", headers: \"*\", methods: \"*\", exposedHeaders: exposedHeaders);\n\n            CorsPolicy corsPolicy = await enableCors.GetCorsPolicyAsync(new HttpRequestMessage(), CancellationToken.None);\n\n            Assert.Equal(new List<string>(expectedResults), corsPolicy.ExposedHeaders);\n        }\n\n        [Theory]\n        [InlineData(\"Accept\", new[] { \"Accept\" })]\n        [InlineData(\"Accept \", new[] { \"Accept\" })]\n        [InlineData(\"Accept,\", new[] { \"Accept\" })]\n        [InlineData(\"Accept,Content-Type\", new[] { \"Accept\", \"Content-Type\" })]\n        [InlineData(\"Accept, Content-Type\", new[] { \"Accept\", \"Content-Type\" })]\n        [InlineData(\"Accept,Content-Type,\", new[] { \"Accept\", \"Content-Type\" })]\n        public async Task GetCorsPolicyAsync_RetunsExpectedHeaders(string headers, string[] expectedResults)\n        {\n            EnableCorsAttribute enableCors = new EnableCorsAttribute(origins: \"*\", headers: headers, methods: \"*\");\n\n            CorsPolicy corsPolicy = await enableCors.GetCorsPolicyAsync(new HttpRequestMessage(), CancellationToken.None);\n\n            Assert.Equal(new List<string>(expectedResults), corsPolicy.Headers);\n        }\n\n        [Theory]\n        [InlineData(\"Get\", new[] { \"Get\" })]\n        [InlineData(\"Get \", new[] { \"Get\" })]\n        [InlineData(\"Get,\", new[] { \"Get\" })]\n        [InlineData(\"Get,Delete\", new[] { \"Get\", \"Delete\" })]\n        [InlineData(\"Get, Delete\", new[] { \"Get\", \"Delete\" })]\n        [InlineData(\"Get,Delete,\", new[] { \"Get\", \"Delete\" })]\n        public async Task GetCorsPolicyAsync_RetunsExpectedMethods(string methods, string[] expectedResults)\n        {\n            EnableCorsAttribute enableCors = new EnableCorsAttribute(origins: \"*\", headers: \"*\", methods: methods);\n\n            CorsPolicy corsPolicy = await enableCors.GetCorsPolicyAsync(new HttpRequestMessage(), CancellationToken.None);\n\n            Assert.Equal(new List<string>(expectedResults), corsPolicy.Methods);\n        }\n\n        [Theory]\n        [InlineData(\"http://example.com\", new[] { \"http://example.com\" })]\n        [InlineData(\"http://example.com \", new[] { \"http://example.com\" })]\n        [InlineData(\"http://example.com,\", new[] { \"http://example.com\" })]\n        [InlineData(\"http://example.com,http://localhost:8080\", new[] { \"http://example.com\", \"http://localhost:8080\" })]\n        [InlineData(\"http://example.com, http://localhost:8080\", new[] { \"http://example.com\", \"http://localhost:8080\" })]\n        [InlineData(\"http://example.com,http://localhost:8080,\", new[] { \"http://example.com\", \"http://localhost:8080\" })]\n        public async Task GetCorsPolicyAsync_RetunsExpectedOrigins(string origins, string[] expectedResults)\n        {\n            EnableCorsAttribute enableCors = new EnableCorsAttribute(origins: origins, headers: \"*\", methods: \"*\");\n\n            CorsPolicy corsPolicy = await enableCors.GetCorsPolicyAsync(new HttpRequestMessage(), CancellationToken.None);\n\n            Assert.Equal(new List<string>(expectedResults), corsPolicy.Origins);\n        }\n\n        [Theory]\n        [InlineData(\"foo\", \"The specified policy origin 'foo' is invalid. It must be correctly formed with the scheme, the host, and optionally, the port.\")]\n        [InlineData(\"://example.com\", \"The specified policy origin '://example.com' is invalid. It must be correctly formed with the scheme, the host, and optionally, the port.\")]\n        [InlineData(\"http://example.com/\", \"The specified policy origin 'http://example.com/' is invalid. It cannot end with a forward slash.\")]\n        [InlineData(\"http://example.com#fragment\", \"The specified policy origin 'http://example.com#fragment' is invalid. It must not contain a path, query, or fragment.\")]\n        [InlineData(\"http://example.com/path\", \"The specified policy origin 'http://example.com/path' is invalid. It must not contain a path, query, or fragment.\")]\n        [InlineData(\"http://example.com?query=foo\", \"The specified policy origin 'http://example.com?query=foo' is invalid. It must not contain a path, query, or fragment.\")]\n        public Task GetCorsPolicyAsync_InvalidOrigin_Throws(string origin, string expectedErrorMessage)\n        {\n            EnableCorsAttribute enableCors = new EnableCorsAttribute(origins: origin, headers: \"*\", methods: \"*\");\n\n            return Assert.ThrowsAsync<InvalidOperationException>(\n                () => enableCors.GetCorsPolicyAsync(new HttpRequestMessage(), CancellationToken.None),\n                expectedErrorMessage);\n        }\n\n        [Theory]\n        [InlineData(\"\", \"The specified policy origin cannot be null or empty.\")]\n        [InlineData(null, \"The specified policy origin cannot be null or empty.\")]\n        public Task GetCorsPolicyAsync_NullEmptyOrigin_Throws(string origin, string expectedErrorMessage)\n        {\n            EnableCorsAttribute enableCors = new EnableCorsAttribute(origins: \"http://localhost\", headers: \"*\", methods: \"*\");\n            enableCors.Origins.Add(origin);\n\n            return Assert.ThrowsAsync<InvalidOperationException>(\n                () => enableCors.GetCorsPolicyAsync(new HttpRequestMessage(), CancellationToken.None),\n                expectedErrorMessage);\n        }\n\n        [Fact]\n        public async Task AllowAnyHeader_IsFalse_WhenHeadersPropertyIsSet()\n        {\n            EnableCorsAttribute enableCors = new EnableCorsAttribute(origins: \"*\", headers: \"foo\", methods: \"*\");\n            CorsPolicy corsPolicy = await enableCors.GetCorsPolicyAsync(new HttpRequestMessage(), CancellationToken.None);\n\n            Assert.False(corsPolicy.AllowAnyHeader);\n        }\n\n        [Fact]\n        public async Task AllowAnyOrigin_IsFalse_WhenOriginsPropertyIsSet()\n        {\n            EnableCorsAttribute enableCors = new EnableCorsAttribute(origins: \"http://example.com\", headers: \"*\", methods: \"*\");\n            CorsPolicy corsPolicy = await enableCors.GetCorsPolicyAsync(new HttpRequestMessage(), CancellationToken.None);\n\n            Assert.False(corsPolicy.AllowAnyOrigin);\n        }\n\n        [Fact]\n        public async Task AllowAnyMethod_IsFalse_WhenMethodsPropertyIsSet()\n        {\n            EnableCorsAttribute enableCors = new EnableCorsAttribute(origins: \"*\", headers: \"*\", methods: \"GET\");\n            CorsPolicy corsPolicy = await enableCors.GetCorsPolicyAsync(new HttpRequestMessage(), CancellationToken.None);\n\n            Assert.False(corsPolicy.AllowAnyMethod);\n        }\n\n        [Fact]\n        public void SettingNegativePreflightMaxAge_Throws()\n        {\n            EnableCorsAttribute enableCors = new EnableCorsAttribute(origins: \"*\", headers: \"*\", methods: \"*\");\n            Assert.ThrowsArgumentOutOfRange(() =>\n            {\n                enableCors.PreflightMaxAge = -2;\n            },\n            \"value\",\n            \"PreflightMaxAge must be greater than or equal to 0.\");\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Cors.Test/HttpRequestMessageExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Hosting;\n\nnamespace System.Web.Http.Cors\n{\n    internal static class HttpRequestMessageExtensions\n    {\n        public static void SetActionDescriptor(this HttpRequestMessage request, HttpActionDescriptor actionDescriptor)\n        {\n            if (request == null)\n            {\n                throw new ArgumentNullException(\"request\");\n            }\n\n            request.Properties[HttpPropertyKeys.HttpActionDescriptorKey] = actionDescriptor;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Cors.Test/System.Web.Http.Cors.Test.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props\" Condition=\"Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" />\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" />\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{1E89A3E9-0A7F-418F-B4BE-6E38A6315373}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>System.Web.Http.Cors</RootNamespace>\n    <AssemblyName>System.Web.Http.Cors.Test</AssemblyName>\n    <OutputPath>..\\..\\bin\\$(Configuration)\\Test\\</OutputPath>\n    <NuGetPackageImportStamp>\n    </NuGetPackageImportStamp>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Castle.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Castle.Core.5.1.1\\lib\\net462\\Castle.Core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Moq, Version=4.18.0.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Moq.4.18.4\\lib\\net462\\Moq.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Newtonsoft.Json.13.0.1\\lib\\net45\\Newtonsoft.Json.dll</HintPath>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Net.Http\" />\n    <Reference Include=\"System.XML\" />\n    <Reference Include=\"xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.abstractions.2.0.3\\lib\\net35\\xunit.abstractions.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.assert, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.assert.2.4.2\\lib\\netstandard1.1\\xunit.assert.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.core, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.core.2.4.2\\lib\\net452\\xunit.core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.execution.desktop, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.execution.2.4.2\\lib\\net452\\xunit.execution.desktop.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\..\\src\\System.Net.Http.Formatting\\System.Net.Http.Formatting.csproj\">\n      <Project>{668e9021-ce84-49d9-98fb-df125a9fcdb0}</Project>\n      <Name>System.Net.Http.Formatting</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Cors\\System.Web.Cors.csproj\">\n      <Project>{43c1b979-d593-4a32-bb3a-4316f1c66d66}</Project>\n      <Name>System.Web.Cors</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Http.Cors\\System.Web.Http.Cors.csproj\">\n      <Project>{25def6f6-7f99-4eb7-91ed-5181a346afe1}</Project>\n      <Name>System.Web.Http.Cors</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Http\\System.Web.Http.csproj\">\n      <Project>{ddc1ce0c-486e-4e35-bb3b-eab61f8f9440}</Project>\n      <Name>System.Web.Http</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\">\n      <Project>{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}</Project>\n      <Name>Microsoft.TestCommon</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <Folder Include=\"Properties\\\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"AttributeBasedPolicyProviderFactoryTest.cs\" />\n    <Compile Include=\"Controllers\\ExternalActionSelectorAttribute.cs\" />\n    <Compile Include=\"Controllers\\PerControllerConfigController.cs\" />\n    <Compile Include=\"Controllers\\SampleController.cs\" />\n    <Compile Include=\"Controllers\\DefaultController.cs\" />\n    <Compile Include=\"Controllers\\ThrowingController.cs\" />\n    <Compile Include=\"CorsMessageHandlerTest.cs\" />\n    <Compile Include=\"DisableCorsAttributeTest.cs\" />\n    <Compile Include=\"EnableCorsAttributeTest.cs\" />\n    <Compile Include=\"CorsHttpConfigurationExtensionsTest.cs\" />\n    <Compile Include=\"CorsHttpRequestMessageExtensionsTest.cs\" />\n    <Compile Include=\"CorsHttpResponseMessageExtensionsTest.cs\" />\n    <Compile Include=\"HttpRequestMessageExtensions.cs\" />\n    <Compile Include=\"Tracing\\CorsEngineTracerTest.cs\" />\n    <Compile Include=\"Tracing\\CorsPolicyProviderFactoryTracerTest.cs\" />\n    <Compile Include=\"Tracing\\CorsPolicyProviderTracerTest.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Service Include=\"{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Analyzer Include=\"..\\..\\packages\\xunit.analyzers.1.1.0\\analyzers\\dotnet\\cs\\xunit.analyzers.dll\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  <Target Name=\"EnsureNuGetPackageBuildImports\" BeforeTargets=\"PrepareForBuild\">\n    <PropertyGroup>\n      <ErrorText>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}.</ErrorText>\n    </PropertyGroup>\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props'))\" />\n  </Target>\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" />\n</Project>"
  },
  {
    "path": "test/System.Web.Http.Cors.Test/Tracing/CorsEngineTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Cors;\nusing System.Web.Http.Tracing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Cors.Tracing\n{\n    public class CorsEngineTracerTest\n    {\n        [Fact]\n        public void EvaluatePolicy_CallsInner()\n        {\n            Mock<ITraceWriter> traceWriterMock = new Mock<ITraceWriter>();\n            Mock<ICorsEngine> corsEngineMock = new Mock<ICorsEngine>();\n            bool innerIsCalled = false;\n            corsEngineMock.Setup(engine => engine.EvaluatePolicy(It.IsAny<CorsRequestContext>(), It.IsAny<CorsPolicy>())).Returns(() =>\n            {\n                innerIsCalled = true;\n                return new CorsResult();\n            });\n            CorsEngineTracer tracer = new CorsEngineTracer(corsEngineMock.Object, traceWriterMock.Object);\n\n            tracer.EvaluatePolicy(new CorsRequestContext(), new CorsPolicy());\n\n            Assert.True(innerIsCalled);\n        }\n\n        [Fact]\n        public void EvaluatePolicy_EmitTraces()\n        {\n            TraceRecord beginTrace = null;\n            TraceRecord endTrace = null;\n            Mock<ITraceWriter> traceWriterMock = new Mock<ITraceWriter>();\n            traceWriterMock\n                .Setup(t => t.Trace(It.IsAny<HttpRequestMessage>(), It.IsAny<string>(), It.IsAny<TraceLevel>(), It.IsAny<Action<TraceRecord>>()))\n                .Callback<HttpRequestMessage, string, TraceLevel, Action<TraceRecord>>((request, category, level, traceAction) =>\n                {\n                    TraceRecord traceRecord = new TraceRecord(request, category, level);\n                    traceAction(traceRecord);\n                    if (traceRecord.Kind == TraceKind.Begin)\n                    {\n                        beginTrace = traceRecord;\n                    }\n                    else if (traceRecord.Kind == TraceKind.End)\n                    {\n                        endTrace = traceRecord;\n                    }\n                });\n            Mock<ICorsEngine> corsEngineMock = new Mock<ICorsEngine>();\n            corsEngineMock\n                .Setup(engine => engine.EvaluatePolicy(It.IsAny<CorsRequestContext>(), It.IsAny<CorsPolicy>()))\n                .Returns(new CorsResult());\n            CorsEngineTracer tracer = new CorsEngineTracer(corsEngineMock.Object, traceWriterMock.Object);\n\n            tracer.EvaluatePolicy(new CorsRequestContext(), new CorsPolicy());\n\n            Assert.NotNull(beginTrace);\n            Assert.Equal(TraceCategories.CorsCategory, beginTrace.Category);\n            Assert.Equal(TraceLevel.Info, beginTrace.Level);\n            Assert.Equal(\"EvaluatePolicy\", beginTrace.Operation);\n\n            Assert.NotNull(endTrace);\n            Assert.Equal(TraceCategories.CorsCategory, endTrace.Category);\n            Assert.Equal(TraceLevel.Info, endTrace.Level);\n            Assert.Equal(\"EvaluatePolicy\", endTrace.Operation);\n            Assert.Equal(\n                @\"CorsResult returned: 'IsValid: True, AllowCredentials: False, PreflightMaxAge: null, AllowOrigin: , AllowExposedHeaders: {}, AllowHeaders: {}, AllowMethods: {}, ErrorMessages: {}'\",\n                endTrace.Message);\n        }\n\n        [Fact]\n        public void EvaluatePolicy_Trace_ContainsHttpRequest()\n        {\n            // Arrange\n            HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Options, \"http://example.com/test\");\n            httpRequest.Headers.Add(\"Origin\", \"foo\");\n            CorsRequestContext corsRequestContext = httpRequest.GetCorsRequestContext();\n\n            Mock<ITraceWriter> traceWriterMock = new Mock<ITraceWriter>();\n            traceWriterMock\n                .Setup(t => t.Trace(httpRequest, It.IsAny<string>(), It.IsAny<TraceLevel>(), It.IsAny<Action<TraceRecord>>()))\n                .Verifiable();\n\n            Mock<ICorsEngine> corsEngineMock = new Mock<ICorsEngine>();\n            corsEngineMock\n                .Setup(engine => engine.EvaluatePolicy(corsRequestContext, It.IsAny<CorsPolicy>()))\n                .Returns(new CorsResult());\n\n            CorsEngineTracer tracer = new CorsEngineTracer(corsEngineMock.Object, traceWriterMock.Object);\n\n            // Act\n            tracer.EvaluatePolicy(corsRequestContext, new CorsPolicy());\n\n            // Assert \n            traceWriterMock.Verify();\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Cors.Test/Tracing/CorsPolicyProviderFactoryTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Cors;\nusing System.Web.Http.Tracing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Cors.Tracing\n{\n    public class CorsPolicyProviderFactoryTracerTest\n    {\n        [Fact]\n        public void GetCorsPolicyProvider_CallsInner()\n        {\n            bool innerIsCalled = false;\n            Mock<ITraceWriter> traceWriterMock = new Mock<ITraceWriter>();\n            Mock<ICorsPolicyProviderFactory> policyProviderFactoryMock = new Mock<ICorsPolicyProviderFactory>();\n            policyProviderFactoryMock\n                .Setup(f => f.GetCorsPolicyProvider(It.IsAny<HttpRequestMessage>()))\n                .Returns(() =>\n                {\n                    innerIsCalled = true;\n                    return new Mock<ICorsPolicyProvider>().Object;\n                });\n            CorsPolicyProviderFactoryTracer tracer = new CorsPolicyProviderFactoryTracer(policyProviderFactoryMock.Object, traceWriterMock.Object);\n\n            tracer.GetCorsPolicyProvider(new HttpRequestMessage());\n\n            Assert.True(innerIsCalled);\n        }\n\n        [Fact]\n        public void GetCorsPolicyProvider_ReturnsCorsPolicyProviderTracer()\n        {\n            Mock<ITraceWriter> traceWriterMock = new Mock<ITraceWriter>();\n            ICorsPolicyProvider expectedPolicyProvider = new Mock<ICorsPolicyProvider>().Object;\n            Mock<ICorsPolicyProviderFactory> policyProviderFactoryMock = new Mock<ICorsPolicyProviderFactory>();\n            policyProviderFactoryMock\n                .Setup(f => f.GetCorsPolicyProvider(It.IsAny<HttpRequestMessage>()))\n                .Returns(expectedPolicyProvider);\n            CorsPolicyProviderFactoryTracer tracer = new CorsPolicyProviderFactoryTracer(policyProviderFactoryMock.Object, traceWriterMock.Object);\n\n            ICorsPolicyProvider policyProvider = tracer.GetCorsPolicyProvider(new HttpRequestMessage());\n\n            Assert.IsType<CorsPolicyProviderTracer>(policyProvider);\n        }\n\n        [Fact]\n        public void GetCorsPolicyProvider_ReturnsNullWhenInnerReturnsNull()\n        {\n            Mock<ITraceWriter> traceWriterMock = new Mock<ITraceWriter>();\n            ICorsPolicyProvider expectedPolicyProvider = new Mock<ICorsPolicyProvider>().Object;\n            Mock<ICorsPolicyProviderFactory> policyProviderFactoryMock = new Mock<ICorsPolicyProviderFactory>();\n            policyProviderFactoryMock\n                .Setup(f => f.GetCorsPolicyProvider(It.IsAny<HttpRequestMessage>()))\n                .Returns((ICorsPolicyProvider)null);\n            CorsPolicyProviderFactoryTracer tracer = new CorsPolicyProviderFactoryTracer(policyProviderFactoryMock.Object, traceWriterMock.Object);\n\n            ICorsPolicyProvider policyProvider = tracer.GetCorsPolicyProvider(new HttpRequestMessage());\n\n            Assert.Null(policyProvider);\n        }\n\n        [Fact]\n        public void GetCorsPolicyProvider_EmitTraces()\n        {\n            TraceRecord beginTrace = null;\n            TraceRecord endTrace = null;\n            Mock<ITraceWriter> traceWriterMock = new Mock<ITraceWriter>();\n            traceWriterMock\n                .Setup(t => t.Trace(It.IsAny<HttpRequestMessage>(), It.IsAny<string>(), It.IsAny<TraceLevel>(), It.IsAny<Action<TraceRecord>>()))\n                .Callback<HttpRequestMessage, string, TraceLevel, Action<TraceRecord>>((request, category, level, traceAction) =>\n                {\n                    TraceRecord traceRecord = new TraceRecord(request, category, level);\n                    traceAction(traceRecord);\n                    if (traceRecord.Kind == TraceKind.Begin)\n                    {\n                        beginTrace = traceRecord;\n                    }\n                    else if (traceRecord.Kind == TraceKind.End)\n                    {\n                        endTrace = traceRecord;\n                    }\n                });\n            Mock<ICorsPolicyProviderFactory> policyProviderFactoryMock = new Mock<ICorsPolicyProviderFactory>();\n            policyProviderFactoryMock\n                .Setup(f => f.GetCorsPolicyProvider(It.IsAny<HttpRequestMessage>()))\n                .Returns(new EnableCorsAttribute(origins: \"*\", headers: \"*\", methods: \"*\"));\n            CorsPolicyProviderFactoryTracer tracer = new CorsPolicyProviderFactoryTracer(policyProviderFactoryMock.Object, traceWriterMock.Object);\n            HttpRequestMessage requestMessage = new HttpRequestMessage();\n            requestMessage.Method = HttpMethod.Get;\n            requestMessage.Headers.Add(CorsConstants.Origin, \"http://example.com\");\n\n            tracer.GetCorsPolicyProvider(requestMessage);\n\n            Assert.NotNull(beginTrace);\n            Assert.Equal(TraceCategories.CorsCategory, beginTrace.Category);\n            Assert.Equal(TraceLevel.Info, beginTrace.Level);\n            Assert.Equal(\"GetCorsPolicyProvider\", beginTrace.Operation);\n            Assert.Equal(\n                @\"CorsRequestContext: 'Origin: http://example.com, HttpMethod: GET, IsPreflight: False, Host: , AccessControlRequestMethod: null, RequestUri: , AccessControlRequestHeaders: {}'\",\n                beginTrace.Message);\n\n            Assert.NotNull(endTrace);\n            Assert.Equal(TraceCategories.CorsCategory, endTrace.Category);\n            Assert.Equal(TraceLevel.Info, endTrace.Level);\n            Assert.Equal(\"GetCorsPolicyProvider\", endTrace.Operation);\n            Assert.Equal(\n                @\"CorsPolicyProvider selected: 'System.Web.Http.Cors.EnableCorsAttribute'\",\n                endTrace.Message);\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Cors.Test/Tracing/CorsPolicyProviderTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Cors;\nusing System.Web.Http.Tracing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Cors.Tracing\n{\n    public class CorsPolicyProviderTracerTest\n    {\n        [Fact]\n        public async Task GetCorsPolicyAsync_CallsInner()\n        {\n            bool innerIsCalled = false;\n            Mock<ITraceWriter> traceWriterMock = new Mock<ITraceWriter>();\n            Mock<ICorsPolicyProvider> policyProviderMock = new Mock<ICorsPolicyProvider>();\n            policyProviderMock\n                .Setup(f => f.GetCorsPolicyAsync(It.IsAny<HttpRequestMessage>(), CancellationToken.None))\n                .Returns(() =>\n                {\n                    innerIsCalled = true;\n                    return Task.FromResult(new CorsPolicy());\n                });\n            CorsPolicyProviderTracer tracer = new CorsPolicyProviderTracer(policyProviderMock.Object, traceWriterMock.Object);\n\n            await tracer.GetCorsPolicyAsync(new HttpRequestMessage(), CancellationToken.None);\n\n            Assert.True(innerIsCalled);\n        }\n\n        [Fact]\n        public async Task GetCorsPolicyAsync_EmitTraces()\n        {\n            TraceRecord beginTrace = null;\n            TraceRecord endTrace = null;\n            Mock<ITraceWriter> traceWriterMock = new Mock<ITraceWriter>();\n            traceWriterMock\n                .Setup(t => t.Trace(It.IsAny<HttpRequestMessage>(), It.IsAny<string>(), It.IsAny<TraceLevel>(), It.IsAny<Action<TraceRecord>>()))\n                .Callback<HttpRequestMessage, string, TraceLevel, Action<TraceRecord>>((request, category, level, traceAction) =>\n                {\n                    TraceRecord traceRecord = new TraceRecord(request, category, level);\n                    traceAction(traceRecord);\n                    if (traceRecord.Kind == TraceKind.Begin)\n                    {\n                        beginTrace = traceRecord;\n                    }\n                    else if (traceRecord.Kind == TraceKind.End)\n                    {\n                        endTrace = traceRecord;\n                    }\n                });\n            CorsPolicyProviderTracer tracer = new CorsPolicyProviderTracer(new EnableCorsAttribute(origins: \"*\", headers: \"*\", methods: \"*\"), traceWriterMock.Object);\n            HttpRequestMessage requestMessage = new HttpRequestMessage();\n            requestMessage.Method = HttpMethod.Get;\n            requestMessage.Headers.Add(CorsConstants.Origin, \"http://example.com\");\n\n            await tracer.GetCorsPolicyAsync(requestMessage, CancellationToken.None);\n\n            Assert.NotNull(beginTrace);\n            Assert.Equal(TraceCategories.CorsCategory, beginTrace.Category);\n            Assert.Equal(TraceLevel.Info, beginTrace.Level);\n            Assert.Equal(\"GetCorsPolicyAsync\", beginTrace.Operation);\n            Assert.Equal(\n                @\"CorsRequestContext: 'Origin: http://example.com, HttpMethod: GET, IsPreflight: False, Host: , AccessControlRequestMethod: null, RequestUri: , AccessControlRequestHeaders: {}'\",\n                beginTrace.Message);\n\n            Assert.NotNull(endTrace);\n            Assert.Equal(TraceCategories.CorsCategory, endTrace.Category);\n            Assert.Equal(TraceLevel.Info, endTrace.Level);\n            Assert.Equal(\"GetCorsPolicyAsync\", endTrace.Operation);\n            Assert.Equal(\n                @\"CorsPolicy selected: 'AllowAnyHeader: True, AllowAnyMethod: True, AllowAnyOrigin: True, PreflightMaxAge: null, SupportsCredentials: False, Origins: {}, Methods: {}, Headers: {}, ExposedHeaders: {}'\",\n                endTrace.Message);\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Cors.Test/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Castle.Core\" version=\"5.1.1\" targetFramework=\"net462\" />\n  <package id=\"Moq\" version=\"4.18.4\" targetFramework=\"net462\" />\n  <package id=\"Newtonsoft.Json\" version=\"13.0.1\" targetFramework=\"net462\" />\n  <package id=\"xunit\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.abstractions\" version=\"2.0.3\" targetFramework=\"net462\" />\n  <package id=\"xunit.analyzers\" version=\"1.1.0\" targetFramework=\"net462\" />\n  <package id=\"xunit.assert\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.execution\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.runner.visualstudio\" version=\"2.4.5\" targetFramework=\"net462\" developmentDependency=\"true\" />\n</packages>"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ApiExplorer/ApiExplorerSettingsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Web.Http.Description;\nusing System.Web.Http.Dispatcher;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ApiExplorer\n{\n    public class ApiExplorerSettingsTest\n    {\n        public static IEnumerable<object[]> HiddenController_DoesNotShowUpOnDescription_PropertyData\n        {\n            get\n            {\n                object controllerType = typeof(HiddenController);\n                object expectedApiDescriptions = new List<object>();\n                yield return new[] { controllerType, expectedApiDescriptions };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"HiddenController_DoesNotShowUpOnDescription_PropertyData\")]\n        public void HiddenController_DoesNotShowUpOnDescription(Type controllerType, List<object> expectedResults)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, controllerType);\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n            ApiExplorerHelper.VerifyApiDescriptions(explorer.ApiDescriptions, expectedResults);\n        }\n\n        public static IEnumerable<object[]> HiddenAction_DoesNotShowUpOnDescription_PropertyData\n        {\n            get\n            {\n                object controllerType = typeof(HiddenActionController);\n                object expectedApiDescriptions = new List<object>\n                {\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"HiddenAction/{id}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1}\n                };\n                yield return new[] { controllerType, expectedApiDescriptions };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"HiddenAction_DoesNotShowUpOnDescription_PropertyData\")]\n        public void HiddenAction_DoesNotShowUpOnDescription(Type controllerType, List<object> expectedResults)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, controllerType);\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n            ApiExplorerHelper.VerifyApiDescriptions(explorer.ApiDescriptions, expectedResults);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ApiExplorer/AttributeRoutesTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Security.Cryptography;\nusing System.Web.Http.Description;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.Routing;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ApiExplorer\n{\n    public class AttributeRoutesTest\n    {\n        public static IEnumerable<object[]> VerifyDescription_OnAttributeRoutes_PropertyData\n        {\n            get\n            {\n                object controllerType;\n                object expectedApiDescriptions;\n\n                controllerType = typeof(MixedController);\n                expectedApiDescriptions = new List<object>\n                {\n                    new { HttpMethod = HttpMethod.Post, RelativePath = \"attribute/mixed\", HasRequestFormatters = true, HasResponseFormatters = true, NumberOfParameters = 1}\n                };\n                yield return new[] { controllerType, expectedApiDescriptions };\n\n                controllerType = typeof(AttributedController);\n                expectedApiDescriptions = new List<object>\n                {\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"controller/{id}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"controller/{name}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Put, RelativePath = \"controller/{id}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Put, RelativePath = \"controller/{id}?name={name}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 2},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"optional/{opt1}/{opt2}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 2},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"optionalwconstraint/{opt}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"default/{default1}/{default2}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 2},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"wildcard/{wildcard}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"multiverb\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 0},\n                    new { HttpMethod = HttpMethod.Put, RelativePath = \"multiverb\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 0},\n                    new { HttpMethod = HttpMethod.Delete, RelativePath = \"multi1\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 0},\n                    new { HttpMethod = HttpMethod.Delete, RelativePath = \"multi2\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 0},\n                };\n                yield return new[] { controllerType, expectedApiDescriptions };\n\n                controllerType = typeof(PrefixedController);\n                expectedApiDescriptions = new List<object>\n                {\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"prefix\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 0},\n                    new { HttpMethod = HttpMethod.Put, RelativePath = \"prefix\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 0},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"prefix/{id}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                };\n                yield return new[] { controllerType, expectedApiDescriptions };\n\n                controllerType = typeof(DefaultRouteController);\n                expectedApiDescriptions = new List<object>\n                {\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"prefix2/defaultroute/{id}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Post, RelativePath = \"prefix2\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 0},\n                    new { HttpMethod = HttpMethod.Put, RelativePath = \"prefix2/defaultrouteoverride/{id}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                };\n                yield return new[] { controllerType, expectedApiDescriptions };\n\n                controllerType = typeof(RpcController);\n                expectedApiDescriptions = new List<object>\n                {\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"api/default2/getallcustomers1\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 0},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"api/default2/getallcustomers2\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 0},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"api/resource/{id}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                };\n                yield return new[] { controllerType, expectedApiDescriptions };\n\n                controllerType = typeof(PartlyResourcePartlyRpcController);\n                expectedApiDescriptions = new List<object>\n                {\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"partial/doop1\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 0},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"partial/{id}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                };\n                yield return new[] { controllerType, expectedApiDescriptions };\n\n                controllerType = typeof(OptionalController);\n                expectedApiDescriptions = new List<object>\n                {\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"apioptional\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 0},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"apioptional/{id}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                };\n                yield return new[] { controllerType, expectedApiDescriptions };\n\n                controllerType = typeof(OverloadController);\n                expectedApiDescriptions = new List<object>\n                {\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"apioverload/{name}?age={age}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 2},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"apioverload/{id}?score={score}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 2},\n                };\n                yield return new[] { controllerType, expectedApiDescriptions };\n\n                controllerType = typeof(BaseClassController);\n                expectedApiDescriptions = new List<object>\n                {\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"baseclass?id={id}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                };\n                yield return new[] { controllerType, expectedApiDescriptions };\n\n                controllerType = typeof(BaseClassPrefixController);\n                expectedApiDescriptions = new List<object>\n                {\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"baseclassprefix\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 0},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"baseclassprefix/base/{id}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                };\n                yield return new[] { controllerType, expectedApiDescriptions };\n\n                controllerType = typeof(SubClassRouteController);\n                expectedApiDescriptions = new List<object>\n                {\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"subclassroute\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 0},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"subclassroute?id={id}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Post, RelativePath = \"subclassroute?name={name}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                };\n                yield return new[] { controllerType, expectedApiDescriptions };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"VerifyDescription_OnAttributeRoutes_PropertyData\")]\n        public void VerifyDescription_OnAttributeRoutes(Type controllerType, List<object> expectedResults)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.MapHttpAttributeRoutes();\n\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, controllerType);\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n            config.EnsureInitialized();\n            \n            IApiExplorer explorer = config.Services.GetApiExplorer();\n            ApiExplorerHelper.VerifyApiDescriptions(explorer.ApiDescriptions, expectedResults);\n        }\n\n        public static IEnumerable<object[]> VerifyDescription_OnMixedRoutes_PropertyData\n        {\n            get\n            {\n                object controllerType;\n                object expectedApiDescriptions;\n\n                controllerType = typeof(MixedController);\n                expectedApiDescriptions = new List<object>\n                {\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"api/Mixed?name={name}&series={series}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 2},\n                    new { HttpMethod = HttpMethod.Post, RelativePath = \"attribute/mixed\", HasRequestFormatters = true, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Delete, RelativePath = \"api/Mixed/{id}\", HasRequestFormatters = false, HasResponseFormatters = false, NumberOfParameters = 1}\n                };\n                yield return new[] { controllerType, expectedApiDescriptions };\n\n                controllerType = typeof(PrefixedController);\n                expectedApiDescriptions = new List<object>\n                {\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"prefix\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 0},\n                    new { HttpMethod = HttpMethod.Put, RelativePath = \"prefix\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 0},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"prefix/{id}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Post, RelativePath = \"api/prefixed\", HasRequestFormatters = false, HasResponseFormatters = false, NumberOfParameters = 0},\n                };\n                yield return new[] { controllerType, expectedApiDescriptions };\n\n                controllerType = typeof(SubClassController);\n                expectedApiDescriptions = new List<object>\n                {\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"subclass?id={id}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Post, RelativePath = \"subclass?name={name}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                };\n                yield return new[] { controllerType, expectedApiDescriptions };\n\n                controllerType = typeof(SubClassNoRouteController);\n                expectedApiDescriptions = new List<object>\n                {\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"api/subclassnoroute/{id}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Post, RelativePath = \"api/subclassnoroute?name={name}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                };\n                yield return new[] { controllerType, expectedApiDescriptions };\n\n                controllerType = typeof(SubClassNoPrefixController);\n                expectedApiDescriptions = new List<object>\n                {\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"api/subclassnoprefix\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 0},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"api/subclassnoprefix/{id}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Post, RelativePath = \"api/subclassnoprefix?name={name}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                };\n                yield return new[] { controllerType, expectedApiDescriptions };\n\n                controllerType = typeof(SubClassPrefixController);\n                expectedApiDescriptions = new List<object>\n                {\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"api/subclassprefix\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 0},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"api/subclassprefix/{id}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Post, RelativePath = \"subclassprefix?name={name}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                };\n                yield return new[] { controllerType, expectedApiDescriptions };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"VerifyDescription_OnMixedRoutes_PropertyData\")]\n        public void VerifyDescription_OnMixedRoutes(Type controllerType, List<object> expectedResults)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.MapHttpAttributeRoutes();\n            config.Routes.MapHttpRoute(\"Default\", \"api/{controller}/{id}\", new { id = RouteParameter.Optional });\n\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, controllerType);\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n            config.EnsureInitialized();\n\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n            ApiExplorerHelper.VerifyApiDescriptions(explorer.ApiDescriptions, expectedResults);\n        }\n\n        [Fact]\n        public void NoDescription_OnAttributeRoutedAction_UsingStandardControllerRoute()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            var route = config.Routes.MapHttpRoute(\"Default\", \"api/someController\", new { controller = \"DefaultRoute\" });\n            config.MapHttpAttributeRoutes();\n\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, typeof(DefaultRouteController));\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n            config.EnsureInitialized();\n\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n            Assert.True(explorer.ApiDescriptions.All(d => d.Route != route));\n        }\n\n        [Fact]\n        public void NoDescription_OnAttributeRoutedAction_UsingStandardRoute()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            var route = config.Routes.MapHttpRoute(\"Default\", \"api/someAction/{id}\", new { controller = \"Attributed\", action = \"Get\" });\n            config.MapHttpAttributeRoutes();\n\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, typeof(AttributedController));\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n            config.EnsureInitialized();\n\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n            Assert.True(explorer.ApiDescriptions.All(d => d.Route != route));\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ApiExplorer/Controllers/AmbiguousActionController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.ApiExplorer\n{\n    public class AmbiguousActionController : ApiController\n    {\n        // The actions GetItem and Get and potentially be ambiguous under\n        // route \"api/{controller}\" because they're both GET api/AmbiguousAction\n\n        public void GetItem()\n        {\n        }\n\n        public void Get()\n        {\n        }\n\n        public bool Post(int id)\n        {\n            return true;\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ApiExplorer/Controllers/AttributeRouteControllers.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.ApiExplorer\n{\n    public class MixedController : ApiController\n    {\n        public string Get(string name, int series)\n        {\n            return null;\n        }\n\n        [Route(\"attribute/mixed\")]\n        public string Post([FromBody]string values)\n        {\n            return values;\n        }\n\n        [HttpDelete]\n        public void RemoveItem(int id)\n        {\n        }\n    }\n\n    public class AttributedController : ApiController\n    {\n        [Route(\"controller/{id:int}\")]\n        public string Get(int id)\n        {\n            return \"Get\" + id;\n        }\n\n        [Route(\"controller/{name}\")]\n        public string GetByName(string name)\n        {\n            return \"GetByName\" + name;\n        }\n\n        [Route(\"controller/{id}\")]\n        public string Put(string id)\n        {\n            return \"Put\" + id;\n        }\n\n        [Route(\"controller/{id}\")]\n        public string Put(string id, string name)\n        {\n            return \"Put\" + id + name;\n        }\n\n        [HttpGet]\n        [Route(\"optional/{opt1?}/{opt2?}\")]\n        public string Optional(int opt1, string opt2)\n        {\n            return \"Optional\" + opt1 + opt2;\n        }\n\n        [HttpGet]\n        [Route(\"optionalwconstraint/{opt:int?}\")]\n        public string OptionalWithConstraint(string opt)\n        {\n            return \"OptionalWithConstraint\" + opt;\n        }\n\n        [HttpGet]\n        [Route(\"default/{default1=D1}/{default2=D2}\")]\n        public string Default(string default1, string default2)\n        {\n            return \"Default\" + default1 + default2;\n        }\n\n        [HttpGet]\n        [Route(\"wildcard/{*wildcard}\")]\n        public string Wildcard(string wildcard)\n        {\n            return \"Wildcard\" + wildcard;\n        }\n\n        [HttpGet]\n        [HttpPut]\n        [Route(\"multiverb\")]\n        public string MultiVerbs()\n        {\n            return Request.Method.ToString();\n        }\n\n        [HttpDelete] // Pick a unique verb\n        [Route(\"multi1\")]\n        [Route(\"multi2\")]\n        public string MultiRoute()\n        {\n            return \"multi\";\n        }\n    }\n\n    [RoutePrefix(\"prefix\")]\n    public class PrefixedController : ApiController\n    {\n        // Should not be reachable be our routes since there's no route attribute.\n        public void Post()\n        {\n        }\n\n        [Route(\"\")]\n        public string Get()\n        {\n            return \"PrefixedGet\";\n        }\n\n        [Route] // same behavior as Route(\"\")\n        public string Put()\n        {\n            return \"PrefixedPut\";\n        }\n\n        [HttpGet]\n        [Route(\"{id}\")]\n        public string GetById(int id)\n        {\n            return \"PrefixedGetById\" + id;\n        }\n    }\n\n    [RoutePrefix(\"prefix2\")]\n    [Route(\"defaultroute/{id:int}\")]\n    public class DefaultRouteController : ApiController\n    {\n        // This gets default route\n        public string Get(int id)\n        {\n            return \"get\" + id;\n        }\n\n        [Route]\n        public string Post()\n        {\n            return \"post\";\n        }\n\n        [Route(\"defaultrouteoverride/{id}\")]\n        public string Put(int id)\n        {\n            return \"put\" + id;\n        }\n    }\n\n    [Route(\"api/default2/{action}\")]\n    public class RpcController : ApiController\n    {\n        public string GetAllCustomers1()\n        {\n            return \"GetAllCustomers1\";\n        }\n\n        public string GetAllCustomers2()\n        {\n            return \"GetAllCustomers2\";\n        }\n\n        // Have a REST api on a RPC controller. Has unique URL\n        [Route(\"api/resource/{id}\")]\n        public string GetById(string id)\n        {\n            return id;\n        }\n    }\n\n    [Route(\"partial/{action}\")]\n    public class PartlyResourcePartlyRpcController : ApiController\n    {\n        // Normal RPC methods\n        [HttpGet]\n        public string DoOp1()\n        {\n            return \"op1\";\n        }\n\n        // Some non-RPC methods.  Has overlapping URL\n        [Route(\"partial/{id:int}\")]\n        public string GetById(int id)\n        {\n            return id.ToString();\n        }\n    }\n\n    [RoutePrefix(\"apioptional\")]\n    [Route(\"{id?}\")]\n    public class OptionalController : ApiController\n    {\n        public string GetAllCustomers()\n        {\n            return \"GetAllCustomers\";\n        }\n\n        public string GetCustomer(int id)\n        {\n            return \"GetCustomer:\" + id;\n        }\n    }\n\n    [RoutePrefix(\"apioverload\")]\n    public class OverloadController : ApiController\n    {\n        [Route(\"{name}\")]\n        public string GetAge(string name, int age)\n        {\n            return \"GetAge:\" + name + age;\n        }\n\n        [Route(\"{id}\")]\n        public string GetScore(string id, int score)\n        {\n            return \"GetScore:\" + id + score;\n        }\n    }\n\n    [Route(\"baseclass\", Name = \"Base\")]\n    public class BaseClassController : ApiController\n    {\n        public string Get(int id)\n        {\n            return \"Get:\" + id;\n        }\n    }\n\n    [Route(\"subclass\", Name = \"Sub\")]\n    public class SubClassController : BaseClassController\n    {\n        public string Post(string name)\n        {\n            return \"Post:\" + name;\n        }\n    }\n\n    public class SubClassNoRouteController : BaseClassController\n    {\n        public string Post(string name)\n        {\n            return \"Post:\" + name;\n        }\n    }\n\n    [RoutePrefix(\"baseclassprefix\")]\n    public class BaseClassPrefixController : ApiController\n    {\n        [Route]\n        public string GetAll()\n        {\n            return \"Get\";\n        }\n\n        [Route(\"base/{id}\", Name = \"GetById\")]\n        public string GetById(int id)\n        {\n            return \"Get:\" + id;\n        }\n    }\n\n    public class SubClassNoPrefixController : BaseClassPrefixController\n    {\n        public string Post(string name)\n        {\n            return \"Post:\" + name;\n        }\n    }\n\n    [RoutePrefix(\"subclassprefix\")]\n    public class SubClassPrefixController : BaseClassPrefixController\n    {\n        [Route]\n        public string Post(string name)\n        {\n            return \"Post:\" + name;\n        }\n    }\n\n    [Route(\"subclassroute\")]\n    public class SubClassRouteController : BaseClassPrefixController\n    {\n        public string Post(string name)\n        {\n            return \"Post:\" + name;\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ApiExplorer/Controllers/DocumentationController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n\nnamespace System.Web.Http.ApiExplorer\n{\n    [ApiDocumentation(\"Documentation controller\")]\n    public class DocumentationController : ApiController\n    {\n        [ApiDocumentation(\"Get action\")]\n        [ApiResponseDocumentation(\"Get response\")]\n        public string Get()\n        {\n            return string.Empty;\n        }\n\n        [ApiDocumentation(\"Post action\")]\n        [ApiParameterDocumentation(\"value\", \"value parameter\")]\n        public void Post(string value)\n        {\n        }\n\n        [ApiDocumentation(\"Put action\")]\n        [ApiParameterDocumentation(\"id\", \"id parameter\")]\n        [ApiParameterDocumentation(\"value\", \"value parameter\")]\n        public void Put(int id, string value)\n        {\n        }\n\n        [ApiDocumentation(\"Delete action\")]\n        [ApiParameterDocumentation(\"id\", \"id parameter\")]\n        public void Delete(int id)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ApiExplorer/Controllers/HiddenActionController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Description;\nnamespace System.Web.Http.ApiExplorer\n{\n    public class HiddenActionController : ApiController\n    {\n        public string GetVisibleAction(int id)\n        {\n            return \"visible action\";\n        }\n\n        [HttpPost]\n        [ApiExplorerSettings(IgnoreApi = true)]\n        public void AddData()\n        {\n        }\n\n        [ApiExplorerSettings(IgnoreApi = true)]\n        public int Get()\n        {\n            return 0;\n        }\n\n        [NonAction]\n        public string GetHiddenAction()\n        {\n            return \"Hidden action\";\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ApiExplorer/Controllers/HiddenController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Description;\nnamespace System.Web.Http.ApiExplorer\n{\n    [ApiExplorerSettings(IgnoreApi = true)]\n    public class HiddenController : ApiController\n    {\n        public string Get(int id)\n        {\n            return \"visible action\";\n        }\n\n        [HttpPost]\n        public void AddData()\n        {\n        }\n\n        public int Get()\n        {\n            return 0;\n        }\n\n        [NonAction]\n        public string GetHiddenAction()\n        {\n            return \"Hidden action\";\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ApiExplorer/Controllers/ItemController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.ApiExplorer\n{\n    public class ItemController : ApiController\n    {\n        public Item GetItem(string name, int series)\n        {\n            return new Item()\n            {\n                Name = name,\n                Series = series\n            };\n        }\n\n        [HttpPost]\n        [HttpPut]\n        public Item PostItem(Item item)\n        {\n            return item;\n        }\n\n        [HttpDelete]\n        public void RemoveItem(int id)\n        {\n        }\n\n        public class Item\n        {\n            public int Series { get; set; }\n            public string Name { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ApiExplorer/Controllers/OverloadsController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Http.ApiExplorer\n{\n    public class OverloadsController : ApiController\n    {\n        public Person Get(int id) { return null; }\n        public List<Person> Get() { return null; }\n        public List<Person> Get(string name) { return null; }\n        public Person GetPersonByNameAndId(string name, int id) { return null; }\n        public Person GetPersonByNameAndAge(string name, int age) { return null; }\n        public Person GetPersonByNameAgeAndSsn(string name, int age, int ssn) { return null; }\n        public Person GetPersonByNameIdAndSsn(string name, int id, int ssn) { return null; }\n        public Person GetPersonByNameAndSsn(string name, int ssn) { return null; }\n        public Person Post(Person Person) { return null; }\n        public Person ActionDefaultedToPost(string name, int age) { return null; }\n        public void Delete(int id, string name = \"Default Name\") { }\n        public void Delete(int id, string name, int age) { }\n\n        public class Person\n        {\n            public string Name { get; set; }\n            public int ID { get; set; }\n            public int SSN { get; set; }\n            public int Age { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ApiExplorer/Controllers/ParameterSourceController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.ValueProviders;\n\nnamespace System.Web.Http.ApiExplorer\n{\n    public class ParameterSourceController : ApiController\n    {\n        public void GetCompleTypeFromUri([FromUri]ComplexType value, string name)\n        {\n        }\n\n        public void PostSimpleTypeFromBody([FromBody] string name)\n        {\n        }\n\n        public void GetCustomFromUriAttribute([MyFromUriAttribute] ComplexType value, ComplexType bodyValue)\n        {\n        }\n\n        public void GetFromHeaderAttribute([FromHeaderAttribute] string value)\n        {\n        }\n\n        public class ComplexType\n        {\n            public int Id { get; set; }\n            public string Name { get; set; }\n        }\n\n        private class MyFromUriAttribute : ModelBinderAttribute, IUriValueProviderFactory\n        {\n            public override IEnumerable<ValueProviderFactory> GetValueProviderFactories(HttpConfiguration configuration)\n            {\n                var factories = from f in base.GetValueProviderFactories(configuration) where f is IUriValueProviderFactory select f;\n                return factories;\n            }\n        }\n\n        private class FromHeaderAttribute : ModelBinderAttribute\n        {\n            public override IEnumerable<ValueProviderFactory> GetValueProviderFactories(HttpConfiguration configuration)\n            {\n                var factories = new ValueProviderFactory[] { new HeaderValueProvider() };\n                return factories;\n            }\n        }\n\n        private class HeaderValueProvider : ValueProviderFactory\n        {\n            public override IValueProvider GetValueProvider(Controllers.HttpActionContext actionContext)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ApiExplorer/Controllers/ResponseTypeController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing System.Web.Http.Description;\n\nnamespace System.Web.Http.ApiExplorer\n{\n    public class ResponseTypeController : ApiController\n    {\n        [ResponseType(typeof(User))]\n        public IHttpActionResult Get()\n        {\n            return Content<User>(HttpStatusCode.OK, new User { FirstName = \"foo\", LastName = \"bar\" });\n        }\n\n        [ResponseType(typeof(User))]\n        public HttpResponseMessage Post(User user)\n        {\n            return Request.CreateResponse<User>(user);\n        }\n\n        public string Delete(int id)\n        {\n            return \"User deleted\";\n        }\n\n        [ResponseType(typeof(void))]\n        public IHttpActionResult Head()\n        {\n            return StatusCode(HttpStatusCode.OK);\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ApiExplorer/DocumentationProviders/AttributeDocumentationProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Description;\n\nnamespace System.Web.Http.ApiExplorer\n{\n    public class AttributeDocumentationProvider : IDocumentationProvider\n    {\n        public string GetDocumentation(HttpActionDescriptor actionDescriptor)\n        {\n            var apiDocumentation = actionDescriptor.GetCustomAttributes<ApiDocumentationAttribute>().FirstOrDefault();\n            if (apiDocumentation != null)\n            {\n                return apiDocumentation.Description;\n            }\n\n            return String.Empty;\n        }\n\n        public string GetDocumentation(HttpParameterDescriptor parameterDescriptor)\n        {\n            var parameterDocumentation = parameterDescriptor.ActionDescriptor.GetCustomAttributes<ApiParameterDocumentationAttribute>().FirstOrDefault(param => param.ParameterName == parameterDescriptor.ParameterName);\n            if (parameterDocumentation != null)\n            {\n                return parameterDocumentation.Description;\n            }\n\n            return String.Empty;\n        }\n\n        public string GetDocumentation(HttpControllerDescriptor controllerDescriptor)\n        {\n            var apiDocumentation = controllerDescriptor.GetCustomAttributes<ApiDocumentationAttribute>().FirstOrDefault();\n            if (apiDocumentation != null)\n            {\n                return apiDocumentation.Description;\n            }\n\n            return String.Empty;\n        }\n        \n        public string GetResponseDocumentation(HttpActionDescriptor actionDescriptor)\n        {\n            var apiDocumentation = actionDescriptor.GetCustomAttributes<ApiResponseDocumentationAttribute>().FirstOrDefault();\n            if (apiDocumentation != null)\n            {\n                return apiDocumentation.Description;\n            }\n\n            return String.Empty;\n        }\n    }\n\n    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]\n    public sealed class ApiDocumentationAttribute : Attribute\n    {\n        public ApiDocumentationAttribute(string description)\n        {\n            Description = description;\n        }\n\n        public string Description { get; private set; }\n    }\n\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]\n    public sealed class ApiResponseDocumentationAttribute : Attribute\n    {\n        public ApiResponseDocumentationAttribute(string description)\n        {\n            Description = description;\n        }\n\n        public string Description { get; private set; }\n    }\n\n    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]\n    public sealed class ApiParameterDocumentationAttribute : Attribute\n    {\n        public ApiParameterDocumentationAttribute(string parameterName, string description)\n        {\n            ParameterName = parameterName;\n            Description = description;\n        }\n\n        public string ParameterName { get; private set; }\n\n        public string Description { get; private set; }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ApiExplorer/DocumentationTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Description;\nusing System.Web.Http.Dispatcher;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ApiExplorer\n{\n    public class DocumentationTest\n    {\n        [Fact]\n        public void VerifyDefaultDocumentationMessage()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            ItemFormatter customFormatter = new ItemFormatter();\n            config.Formatters.Add(customFormatter);\n\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, typeof(ItemController));\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n            foreach (ApiDescription description in explorer.ApiDescriptions)\n            {\n                Assert.Null(description.Documentation);\n                foreach (ApiParameterDescription param in description.ParameterDescriptions)\n                {\n                    Assert.Null(param.Documentation);\n                }\n            }\n        }\n\n        [Fact]\n        public void VerifyCustomDocumentationProviderMessage()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            ItemFormatter customFormatter = new ItemFormatter();\n            config.Formatters.Add(customFormatter);\n\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, typeof(DocumentationController));\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n\n            AttributeDocumentationProvider documentationProvider = new AttributeDocumentationProvider();\n            config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);\n\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n            foreach (ApiDescription description in explorer.ApiDescriptions)\n            {\n                Assert.Equal(\n                    \"Documentation controller\",\n                    documentationProvider.GetDocumentation(description.ActionDescriptor.ControllerDescriptor));\n                Assert.Equal(\n                    String.Format(\"{0} action\", description.ActionDescriptor.ActionName),\n                    description.Documentation);\n                foreach (ApiParameterDescription param in description.ParameterDescriptions)\n                {\n                    Assert.Equal(\n                        String.Format(\"{0} parameter\", param.Name),\n                        param.Documentation);\n                }\n                if (description.ResponseDescription.DeclaredType != null)\n                {\n                    Assert.Equal(\n                        String.Format(\"{0} response\", description.ActionDescriptor.ActionName),\n                        description.ResponseDescription.Documentation);\n                }\n            }\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ApiExplorer/Formatters/ItemFormatter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Formatting;\n\nnamespace System.Web.Http.ApiExplorer\n{\n    public class ItemFormatter : BufferedMediaTypeFormatter\n    {\n        public override bool CanReadType(Type type)\n        {\n            return typeof(System.Web.Http.ApiExplorer.ItemController.Item).IsAssignableFrom(type);\n        }\n\n        public override bool CanWriteType(Type type)\n        {\n            return typeof(System.Web.Http.ApiExplorer.ItemController.Item).IsAssignableFrom(type);\n        }\n\n        public override object ReadFromStream(Type type, IO.Stream stream, Net.Http.HttpContent content, IFormatterLogger formatterLogger)\n        {\n            return base.ReadFromStream(type, stream, content, formatterLogger);\n        }\n\n        public override void WriteToStream(Type type, object value, IO.Stream stream, Net.Http.HttpContent content)\n        {\n            base.WriteToStream(type, value, stream, content);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ApiExplorer/FormattersTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Web.Http.Description;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.Tracing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.ApiExplorer\n{\n    public class FormattersTest\n    {\n        [Fact]\n        public void CustomRequestBodyFormatters_ShowUpOnDescription()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            ItemFormatter customFormatter = new ItemFormatter();\n            config.Formatters.Add(customFormatter);\n\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, typeof(ItemController));\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n            ApiDescription description = explorer.ApiDescriptions.FirstOrDefault(desc => desc.ActionDescriptor.ActionName == \"PostItem\");\n            Assert.True(description.SupportedRequestBodyFormatters.Any(formatter => formatter == customFormatter), \"Did not find the custom formatter on the SupportedRequestBodyFormatters.\");\n        }\n\n        [Fact]\n        public void CustomResponseFormatters_ShowUpOnDescription()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            ItemFormatter customFormatter = new ItemFormatter();\n            config.Formatters.Add(customFormatter);\n\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, typeof(ItemController));\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n            ApiDescription description = explorer.ApiDescriptions.FirstOrDefault(desc => desc.ActionDescriptor.ActionName == \"PostItem\");\n            Assert.True(description.SupportedResponseFormatters.Any(formatter => formatter == customFormatter), \"Did not find the custom formatter on the SupportedResponseFormatters.\");\n        }\n\n        [Fact]\n        public void SupportedRequestBodyFormatters_ReturnsFormattersWithoutTracers_WithNoTracing()\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            ItemFormatter customFormatter = new ItemFormatter();\n            config.Formatters.Add(customFormatter);\n            config.Initializer.Invoke(config);\n            int expectedFormatterCount = config.Formatters.Count - 1;\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, typeof(ItemController));\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n\n            // Act \n            ApiDescription description = explorer.ApiDescriptions.FirstOrDefault(desc => desc.ActionDescriptor.ActionName == \"PostItem\");\n            Collection<MediaTypeFormatter> formatters = description.SupportedRequestBodyFormatters;\n\n            // Assert\n            Assert.False(formatters.Any(f => f is IFormatterTracer), \"Tracers are present\");\n            Assert.Equal(expectedFormatterCount, formatters.Count);\n        }\n\n        [Fact]\n        public void SupportedResponseFormatters_ReturnsFormattersWithoutTracers_WithNoTracing()\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            ItemFormatter customFormatter = new ItemFormatter();\n            config.Formatters.Add(customFormatter);\n            config.Initializer.Invoke(config);\n            int expectedFormatterCount = config.Formatters.Count - 2;\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, typeof(ItemController));\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n\n            // Act \n            ApiDescription description = explorer.ApiDescriptions.FirstOrDefault(desc => desc.ActionDescriptor.ActionName == \"PostItem\");\n            Collection<MediaTypeFormatter> formatters = description.SupportedResponseFormatters;\n\n            // Assert\n            Assert.False(formatters.Any(f => f is IFormatterTracer), \"Tracers are present\");\n            Assert.Equal(expectedFormatterCount, formatters.Count);\n        }\n\n        [Fact]\n        public void SupportedRequestBodyFormatters_ReturnsFormattersWithoutTracers_WithTracing()\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            ItemFormatter customFormatter = new ItemFormatter();\n            config.Formatters.Add(customFormatter);\n            ITraceWriter testTraceWriter = new Mock<ITraceWriter>().Object;\n            config.Services.Replace(typeof(ITraceWriter), testTraceWriter);\n            config.Initializer.Invoke(config);\n            int expectedFormatterCount = config.Formatters.Count - 1;\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, typeof(ItemController));\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n\n            // Act \n            ApiDescription description = explorer.ApiDescriptions.FirstOrDefault(desc => desc.ActionDescriptor.ActionName == \"PostItem\");\n            Collection<MediaTypeFormatter> formatters = description.SupportedRequestBodyFormatters;\n\n            // Assert\n            Assert.False(formatters.Any(f => f is IFormatterTracer), \"Tracers are present\");\n            Assert.Equal(expectedFormatterCount, formatters.Count);\n        }\n\n        [Fact]\n        public void SupportedResponseFormatters_ReturnsFormattersWithoutTracers_WithTracing()\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            ItemFormatter customFormatter = new ItemFormatter();\n            config.Formatters.Add(customFormatter);\n            ITraceWriter testTraceWriter = new Mock<ITraceWriter>().Object;\n            config.Services.Replace(typeof(ITraceWriter), testTraceWriter);\n            config.Initializer.Invoke(config);\n            int expectedFormatterCount = config.Formatters.Count - 2;\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, typeof(ItemController));\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n\n            // Act \n            ApiDescription description = explorer.ApiDescriptions.FirstOrDefault(desc => desc.ActionDescriptor.ActionName == \"PostItem\");\n            Collection<MediaTypeFormatter> formatters = description.SupportedResponseFormatters;\n\n            // Assert\n            Assert.False(formatters.Any(f => f is IFormatterTracer), \"Tracers are present\");\n            Assert.Equal(expectedFormatterCount, formatters.Count);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ApiExplorer/ParameterSourceTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Linq;\nusing System.Web.Http.Description;\nusing System.Web.Http.Dispatcher;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ApiExplorer\n{\n    public class ParameterSourceTest\n    {\n        [Fact]\n        public void FromUriParameterSource_ShowUpCorrectlyOnDescription()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{action}/{id}\", new { id = RouteParameter.Optional });\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, typeof(ParameterSourceController));\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n\n            ApiDescription description = explorer.ApiDescriptions.FirstOrDefault(desc => desc.ActionDescriptor.ActionName == \"GetCompleTypeFromUri\");\n            Assert.NotNull(description);\n            Assert.True(description.ParameterDescriptions.All(param => param.Source == ApiParameterSource.FromUri), \"All parameters should come from URI.\");\n\n            description = explorer.ApiDescriptions.FirstOrDefault(desc => desc.ActionDescriptor.ActionName == \"GetCustomFromUriAttribute\");\n            Assert.NotNull(description);\n            Assert.True(description.ParameterDescriptions.Any(param => param.Source == ApiParameterSource.FromUri && param.Name == \"value\"), \"The 'value' parameter should come from URI.\");\n            Assert.True(description.ParameterDescriptions.Any(param => param.Source == ApiParameterSource.FromBody && param.Name == \"bodyValue\"), \"The 'bodyValue' parameter should come from body.\");\n        }\n\n        [Fact]\n        public void FromBodyParameterSource_ShowUpCorrectlyOnDescription()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{action}/{id}\", new { id = RouteParameter.Optional });\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, typeof(ParameterSourceController));\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n\n            ApiDescription description = explorer.ApiDescriptions.FirstOrDefault(desc => desc.ActionDescriptor.ActionName == \"PostSimpleTypeFromBody\");\n            Assert.NotNull(description);\n            Assert.True(description.ParameterDescriptions.All(param => param.Source == ApiParameterSource.FromBody), \"The parameter should come from Body.\");\n        }\n\n        [Fact]\n        public void UnknownParameterSource_ShowUpCorrectlyOnDescription()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{action}/{id}\", new { id = RouteParameter.Optional });\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, typeof(ParameterSourceController));\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n\n            ApiDescription description = explorer.ApiDescriptions.FirstOrDefault(desc => desc.ActionDescriptor.ActionName == \"GetFromHeaderAttribute\");\n            Assert.NotNull(description);\n            Assert.True(description.ParameterDescriptions.All(param => param.Source == ApiParameterSource.Unknown), \"The parameter source should be Unknown.\");\n        }\n\n        [Fact]\n        public void EnumParameters_ShowUpCorrectlyOnDescription()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}\");\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, typeof(EnumParameterOverloadsController));\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n\n            ApiDescription description = explorer.ApiDescriptions.FirstOrDefault(desc => desc.ActionDescriptor.ActionName == \"GetWithEnumParameter\");\n            Assert.NotNull(description);\n            ApiParameterDescription parameterDescription = Assert.Single(description.ParameterDescriptions);\n            Assert.Equal(ApiParameterSource.FromUri, parameterDescription.Source);\n            Assert.Equal(\"EnumParameterOverloads?scope={scope}\", description.RelativePath);\n\n            description = explorer.ApiDescriptions.FirstOrDefault(desc => desc.ActionDescriptor.ActionName == \"GetWithTwoEnumParameters\");\n            Assert.NotNull(description);\n            Assert.Equal(2, description.ParameterDescriptions.Count);\n            Assert.Equal(ApiParameterSource.FromUri, description.ParameterDescriptions[0].Source);\n            Assert.Equal(ApiParameterSource.FromUri, description.ParameterDescriptions[1].Source);\n            Assert.Equal(\"EnumParameterOverloads?level={level}&kind={kind}\", description.RelativePath);\n\n            description = explorer.ApiDescriptions.FirstOrDefault(desc => desc.ActionDescriptor.ActionName == \"GetWithNullableEnumParameter\");\n            Assert.NotNull(description);\n            parameterDescription = Assert.Single(description.ParameterDescriptions);\n            Assert.Equal(ApiParameterSource.FromUri, parameterDescription.Source);\n            Assert.Equal(\"EnumParameterOverloads?level={level}\", description.RelativePath);\n        }\n\n        [Theory]\n        [InlineData(\"api/values/{id}\", \"\", \"Get\")]\n        [InlineData(\"api/values\", \"?value={value}\", \"GetFromUri\")]\n        [InlineData(\"api/values\", \"?X={X}&Y={Y}\", \"GetPoint\")]\n        [InlineData(\"api/values\", \"?origin.X={origin.X}&origin.Y={origin.Y}&end.X={end.X}&end.Y={end.Y}\", \"GetDistance\")]\n        [InlineData(\"api/values\", \"?Latitude={Latitude}&Longitude={Longitude}\", \"GetLocation\")]\n        [InlineData(\"api/values\", \"?value={value}\", \"GetConvertible\")]\n        [InlineData(\"api/values\", \"\", \"GetNoDescribable\")]\n        [InlineData(\"api/values\", \"?X={X}\", \"GetParticle\")]\n        public void RelativePath_IsCorrectForTypesFromUri(string routeTemplate, string expectedQueryString, string methodName)\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", routeTemplate, new { controller = \"ApiExplorerActionsWithParameters\", action = methodName });\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, typeof(ApiExplorerActionsWithParametersController));\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n\n            // Act\n            ApiDescription description = explorer.ApiDescriptions.FirstOrDefault(desc => desc.ActionDescriptor.ActionName == methodName);\n\n            // Assert\n            Assert.NotNull(description);\n            Assert.Equal(routeTemplate + expectedQueryString, description.RelativePath);\n        }\n\n        public class ApiExplorerActionsWithParametersController : ApiController\n        {\n            public void Get(int id) { }\n            public void GetFromUri([FromUri]string value) { }\n            public void GetPoint([FromUri] Point complexParameterObject) { }\n            public void GetDistance([FromUri] Point origin, [FromUri] Point end) { }\n            public void GetLocation(Location location) { }\n            public void GetConvertible([FromUri] ConvertibleFromString value) { }\n            public void GetNoDescribable([FromUri] NonDescribable nonDescribable) { }\n            public void GetParticle([FromUri] Particle particle) { }\n        }\n\n        public class Point\n        {\n            public int X { get; set; }\n            public int Y { get; set; }\n        }\n\n        [FromUri]\n        public class Location\n        {\n            public int Latitude { get; set; }\n            public int Longitude { get; set; }\n            public static Location Greenwich { get; set; }\n        }\n\n        [TypeConverter(typeof(ConvertibleFromStringConverter))]\n        public class ConvertibleFromString\n        {\n            public class ConvertibleFromStringConverter : TypeConverter\n            {\n                public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)\n                {\n                    return sourceType == typeof(string);\n                }\n            }\n            public int Id { get; set; }\n            public string Value { get; set; }\n        }\n\n        // We only support complex types whose all of their individual\n        // properties can be converted from string.\n        public class NonDescribable\n        {\n            public Point Point { get; set; }\n        }\n\n        // Get only, Set only, and private properties are ignored.\n        public class Particle\n        {\n            public int X { get; set; }\n            public int Y { get; private set; }\n            public int Z\n            {\n                get\n                {\n                    return 0;\n                }\n            }\n            private int _mass;\n            public int Mass\n            {\n                set\n                {\n                    _mass = value;\n                }\n            }\n            private string Color { get; set; }\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ApiExplorer/ResponseTypeAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Web.Http.Description;\nusing System.Web.Http.Dispatcher;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ApiExplorer\n{\n    public class ResponseTypeAttributeTest\n    {\n        [Theory]\n        [InlineData(\"Get\", typeof(IHttpActionResult), typeof(User), 2)]\n        [InlineData(\"Post\", typeof(HttpResponseMessage), typeof(User), 2)]\n        [InlineData(\"Delete\", typeof(string), null, 2)]\n        [InlineData(\"Head\", typeof(IHttpActionResult), typeof(void), 0)]\n        public void DeclaredResponseType_AppearsOnApiDescription(string actionName, Type declaredType, Type responseType, int responseFormattersCount)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            Type controllerToTest = typeof(ResponseTypeController);\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, controllerToTest);\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n\n            Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;\n            ApiDescription expectedApi = apis.FirstOrDefault(api => api.ActionDescriptor.ActionName == actionName &&\n                api.ResponseDescription.DeclaredType == declaredType &&\n                api.ResponseDescription.ResponseType == responseType);\n\n            Assert.NotNull(expectedApi);\n            Assert.Equal(responseFormattersCount, expectedApi.SupportedResponseFormatters.Count);\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ApiExplorer/RouteConstraintsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Web.Http.Description;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.Routing;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ApiExplorer\n{\n    public class RouteConstraintsTest\n    {\n        public static IEnumerable<object[]> HttpMethodConstraints_LimitsTheDescriptions_PropertyData\n        {\n            get\n            {\n                object controllerType = typeof(ItemController);\n                object expectedApiDescriptions = new List<object>\n                {\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Item?name={name}&series={series}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 2},\n                    new { HttpMethod = HttpMethod.Put, RelativePath = \"Item\", HasRequestFormatters = true, HasResponseFormatters = true, NumberOfParameters = 1}\n                };\n                yield return new[] { controllerType, expectedApiDescriptions };\n\n                controllerType = typeof(OverloadsController);\n                expectedApiDescriptions = new List<object>\n                {\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads/{id}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 0},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads?name={name}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads/{id}?name={name}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 2},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads?name={name}&age={age}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 2},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads?name={name}&age={age}&ssn={ssn}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 3},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads/{id}?name={name}&ssn={ssn}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 3},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads?name={name}&ssn={ssn}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 2}\n                };\n                yield return new[] { controllerType, expectedApiDescriptions };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"HttpMethodConstraints_LimitsTheDescriptions_PropertyData\")]\n        public void HttpMethodConstraints_LimitsTheDescriptions(Type controllerType, List<object> expectedResults)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { id = RouteParameter.Optional }, new { routeConstraint = new HttpMethodConstraint(HttpMethod.Get, HttpMethod.Put) });\n\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, controllerType);\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n            ApiExplorerHelper.VerifyApiDescriptions(explorer.ApiDescriptions, expectedResults);\n        }\n\n        public static IEnumerable<object[]> RegexConstraint_LimitsTheController_PropertyData\n        {\n            get\n            {\n                object[] controllerTypes = new Type[] { typeof(OverloadsController), typeof(ItemController) };\n                object expectedApiDescriptions = new List<object>\n                {\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Item?name={name}&series={series}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 2},\n                    new { HttpMethod = HttpMethod.Post, RelativePath = \"Item\", HasRequestFormatters = true, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Put, RelativePath = \"Item\", HasRequestFormatters = true, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Delete, RelativePath = \"Item/{id}\", HasRequestFormatters = false, HasResponseFormatters = false, NumberOfParameters = 1}\n                };\n                yield return new[] { controllerTypes, expectedApiDescriptions };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"RegexConstraint_LimitsTheController_PropertyData\")]\n        public void RegexConstraint_LimitsTheController(Type[] controllerTypes, List<object> expectedResults)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { id = RouteParameter.Optional }, new { controller = \"It.*\" }); // controllers that start with \"It\"\n\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, controllerTypes);\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n            ApiExplorerHelper.VerifyApiDescriptions(explorer.ApiDescriptions, expectedResults);\n        }\n\n        public static IEnumerable<object[]> RegexConstraint_LimitsTheAction_PropertyData\n        {\n            get\n            {\n                object[] controllerTypes = new Type[] { typeof(OverloadsController), typeof(ItemController) };\n                object expectedApiDescriptions = new List<object>\n                {\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Item/GetItem?name={name}&series={series}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 2},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads/GetPersonByNameAndId/{id}?name={name}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 2},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads/GetPersonByNameAndAge?name={name}&age={age}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 2},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads/GetPersonByNameAgeAndSsn?name={name}&age={age}&ssn={ssn}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 3},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads/GetPersonByNameIdAndSsn/{id}?name={name}&ssn={ssn}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 3},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads/GetPersonByNameAndSsn?name={name}&ssn={ssn}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 2}\n                };\n                yield return new[] { controllerTypes, expectedApiDescriptions };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"RegexConstraint_LimitsTheAction_PropertyData\")]\n        public void RegexConstraint_LimitsTheAction(Type[] controllerTypes, List<object> expectedResults)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{action}/{id}\", new { id = RouteParameter.Optional }, new { action = \"Get.+\" }); // actions that start with \"Get\" and at least one extra character\n\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, controllerTypes);\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n            ApiExplorerHelper.VerifyApiDescriptions(explorer.ApiDescriptions, expectedResults);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ApiExplorer/RoutesTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Net.Http;\nusing System.Web.Http.Description;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.Routing;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ApiExplorer\n{\n    public class RoutesTest\n    {\n        [Fact]\n        public void VerifyDescription_OnEmptyRoute()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n\n            Assert.NotNull(explorer);\n            Assert.Empty(explorer.ApiDescriptions);\n        }\n\n        [Fact]\n        public void VerifyDescription_OnInvalidRoute()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Invalid\", \"badRouteWithNoControler\");\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n\n            Assert.NotNull(explorer);\n            Assert.Empty(explorer.ApiDescriptions);\n        }\n\n        public static IEnumerable<object[]> VerifyDescription_OnDefaultRoute_PropertyData\n        {\n            get\n            {\n                object controllerType = typeof(ItemController);\n                object expectedApiDescriptions = new List<object>\n                {\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Item?name={name}&series={series}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 2},\n                    new { HttpMethod = HttpMethod.Post, RelativePath = \"Item\", HasRequestFormatters = true, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Put, RelativePath = \"Item\", HasRequestFormatters = true, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Delete, RelativePath = \"Item/{id}\", HasRequestFormatters = false, HasResponseFormatters = false, NumberOfParameters = 1}\n                };\n                yield return new[] { controllerType, expectedApiDescriptions };\n\n                controllerType = typeof(OverloadsController);\n                expectedApiDescriptions = new List<object>\n                {\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads/{id}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 0},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads?name={name}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads/{id}?name={name}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 2},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads?name={name}&age={age}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 2},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads?name={name}&age={age}&ssn={ssn}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 3},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads/{id}?name={name}&ssn={ssn}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 3},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads?name={name}&ssn={ssn}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 2},\n                    new { HttpMethod = HttpMethod.Post, RelativePath = \"Overloads\", HasRequestFormatters = true, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Post, RelativePath = \"Overloads?name={name}&age={age}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 2},\n                    new { HttpMethod = HttpMethod.Delete, RelativePath = \"Overloads/{id}?name={name}\", HasRequestFormatters = false, HasResponseFormatters = false, NumberOfParameters = 2},\n                    new { HttpMethod = HttpMethod.Delete, RelativePath = \"Overloads/{id}?name={name}&age={age}\", HasRequestFormatters = false, HasResponseFormatters = false, NumberOfParameters = 3}\n                };\n                yield return new[] { controllerType, expectedApiDescriptions };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"VerifyDescription_OnDefaultRoute_PropertyData\")]\n        public void VerifyDescription_OnDefaultRoute(Type controllerType, List<object> expectedResults)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, controllerType);\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n            ApiExplorerHelper.VerifyApiDescriptions(explorer.ApiDescriptions, expectedResults);\n        }\n\n        public static IEnumerable<object[]> VerifyDescription_OnRouteWithControllerOnDefaults_PropertyData\n        {\n            get\n            {\n                object controllerType = typeof(ItemController);\n                object expectedApiDescriptions = new List<object>\n                {\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"myitem?name={name}&series={series}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 2},\n                    new { HttpMethod = HttpMethod.Post, RelativePath = \"myitem\", HasRequestFormatters = true, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Put, RelativePath = \"myitem\", HasRequestFormatters = true, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Delete, RelativePath = \"myitem/{id}\", HasRequestFormatters = false, HasResponseFormatters = false, NumberOfParameters = 1}\n                };\n                yield return new[] { controllerType, expectedApiDescriptions };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"VerifyDescription_OnRouteWithControllerOnDefaults_PropertyData\")]\n        public void VerifyDescription_OnRouteWithControllerOnDefaults(Type controllerType, List<object> expectedResults)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"myitem/{id}\", new { controller = \"Item\", id = RouteParameter.Optional });\n\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, controllerType);\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n            ApiExplorerHelper.VerifyApiDescriptions(explorer.ApiDescriptions, expectedResults);\n        }\n\n        public static IEnumerable<object[]> VerifyDescription_OnRouteWithActionVariable_PropertyData\n        {\n            get\n            {\n                object controllerType = typeof(ItemController);\n                object expectedApiDescriptions = new List<object>\n                {\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Item/GetItem?name={name}&series={series}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 2},\n                    new { HttpMethod = HttpMethod.Post, RelativePath = \"Item/PostItem\", HasRequestFormatters = true, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Put, RelativePath = \"Item/PostItem\", HasRequestFormatters = true, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Delete, RelativePath = \"Item/RemoveItem/{id}\", HasRequestFormatters = false, HasResponseFormatters = false, NumberOfParameters = 1}\n                };\n                yield return new[] { controllerType, expectedApiDescriptions };\n\n                controllerType = typeof(OverloadsController);\n                expectedApiDescriptions = new List<object>\n                {\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads/Get/{id}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads/Get\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 0},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads/Get?name={name}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads/GetPersonByNameAndId/{id}?name={name}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 2},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads/GetPersonByNameAndAge?name={name}&age={age}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 2},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads/GetPersonByNameAgeAndSsn?name={name}&age={age}&ssn={ssn}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 3},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads/GetPersonByNameIdAndSsn/{id}?name={name}&ssn={ssn}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 3},\n                    new { HttpMethod = HttpMethod.Get, RelativePath = \"Overloads/GetPersonByNameAndSsn?name={name}&ssn={ssn}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 2},\n                    new { HttpMethod = HttpMethod.Post, RelativePath = \"Overloads/Post\", HasRequestFormatters = true, HasResponseFormatters = true, NumberOfParameters = 1},\n                    new { HttpMethod = HttpMethod.Post, RelativePath = \"Overloads/ActionDefaultedToPost?name={name}&age={age}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 2},\n                    new { HttpMethod = HttpMethod.Delete, RelativePath = \"Overloads/Delete/{id}?name={name}\", HasRequestFormatters = false, HasResponseFormatters = false, NumberOfParameters = 2},\n                    new { HttpMethod = HttpMethod.Delete, RelativePath = \"Overloads/Delete/{id}?name={name}&age={age}\", HasRequestFormatters = false, HasResponseFormatters = false, NumberOfParameters = 3}\n                };\n                yield return new[] { controllerType, expectedApiDescriptions };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"VerifyDescription_OnRouteWithActionVariable_PropertyData\")]\n        public void VerifyDescription_OnRouteWithActionVariable(Type controllerType, List<object> expectedResults)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{action}/{id}\", new { id = RouteParameter.Optional });\n\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, controllerType);\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n            ApiExplorerHelper.VerifyApiDescriptions(explorer.ApiDescriptions, expectedResults);\n        }\n\n        public static IEnumerable<object[]> VerifyDescription_On_RouteWithActionOnDefaults_PropertyData\n        {\n            get\n            {\n                object controllerType = typeof(ItemController);\n                object expectedApiDescriptions = new List<object>\n                {\n                    new { HttpMethod = HttpMethod.Delete, RelativePath = \"Item/{id}\", HasRequestFormatters = false, HasResponseFormatters = false, NumberOfParameters = 1}\n                };\n                yield return new[] { controllerType, expectedApiDescriptions };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"VerifyDescription_On_RouteWithActionOnDefaults_PropertyData\")]\n        public void VerifyDescription_On_RouteWithActionOnDefaults(Type controllerType, List<object> expectedResults)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { action = \"RemoveItem\", id = RouteParameter.Optional });\n\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, controllerType);\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n            ApiExplorerHelper.VerifyApiDescriptions(explorer.ApiDescriptions, expectedResults);\n        }\n\n        [Fact]\n        public void InvalidActionNameOnRoute_DoesNotThrow()\n        {\n            Type controllerType = typeof(OverloadsController);\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { action = \"ActionThatDoesNotExist\", id = RouteParameter.Optional });\n\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, controllerType);\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n            Assert.Empty(explorer.ApiDescriptions);\n        }\n\n        [Fact]\n        public void InvalidControllerNameOnRoute_DoesNotThrow()\n        {\n            Type controllerType = typeof(OverloadsController);\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"mycontroller/{id}\", new { controller = \"ControllerThatDoesNotExist\", id = RouteParameter.Optional });\n\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, controllerType);\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n            Assert.Empty(explorer.ApiDescriptions);\n        }\n\n        [Fact]\n        public void VerifyOnlyOneSetOfDescriptionIsGenerated_OnTwoMatchingRoutes()\n        {\n            Type controllerType = typeof(ItemController);\n            HttpConfiguration config = new HttpConfiguration();\n            IHttpRoute matchingRoute = config.Routes.MapHttpRoute(\"Item\", \"Item/{id}\", new { id = RouteParameter.Optional, controller = \"Item\" });\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, controllerType);\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n            Collection<ApiDescription> descriptions = explorer.ApiDescriptions;\n\n            foreach (ApiDescription description in descriptions)\n            {\n                Assert.Same(matchingRoute, description.Route);\n            }\n            List<object> expectedResults = new List<object>\n            {\n                new { HttpMethod = HttpMethod.Get, RelativePath = \"Item?name={name}&series={series}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 2},\n                new { HttpMethod = HttpMethod.Post, RelativePath = \"Item\", HasRequestFormatters = true, HasResponseFormatters = true, NumberOfParameters = 1},\n                new { HttpMethod = HttpMethod.Put, RelativePath = \"Item\", HasRequestFormatters = true, HasResponseFormatters = true, NumberOfParameters = 1},\n                new { HttpMethod = HttpMethod.Delete, RelativePath = \"Item/{id}\", HasRequestFormatters = false, HasResponseFormatters = false, NumberOfParameters = 1}\n            };\n            ApiExplorerHelper.VerifyApiDescriptions(descriptions, expectedResults);\n        }\n\n        [Fact]\n        public void VerifyDescriptionIsNotGeneratedForAmbiguousAction_OnDefaultRoutes()\n        {\n            Type controllerType = typeof(AmbiguousActionController);\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, controllerType);\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n            Collection<ApiDescription> descriptions = explorer.ApiDescriptions;\n\n            List<object> expectedResults = new List<object>\n            {\n                new { HttpMethod = HttpMethod.Post, RelativePath = \"AmbiguousAction/{id}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 1}\n            };\n            ApiExplorerHelper.VerifyApiDescriptions(descriptions, expectedResults);\n        }\n\n        [Fact]\n        public void VerifyDescriptionIsGenerated_WhenRouteParameterIsNotInAction()\n        {\n            Type controllerType = typeof(ItemController);\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Custom\", \"{majorVersion}/{minorVersion}/custom\", new { controller = \"Item\" });\n            config.Routes.MapHttpRoute(\"Default\", \"{version}/{controller}/{id}\", new { id = RouteParameter.Optional });\n            DefaultHttpControllerSelector controllerSelector = ApiExplorerHelper.GetStrictControllerSelector(config, controllerType);\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n\n            IApiExplorer explorer = config.Services.GetApiExplorer();\n            Collection<ApiDescription> descriptions = explorer.ApiDescriptions;\n\n            List<object> expectedResults = new List<object>\n            {\n                new { HttpMethod = HttpMethod.Get, RelativePath = \"{majorVersion}/{minorVersion}/custom?name={name}&series={series}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 4},\n                new { HttpMethod = HttpMethod.Post, RelativePath = \"{majorVersion}/{minorVersion}/custom\", HasRequestFormatters = true, HasResponseFormatters = true, NumberOfParameters = 3},\n                new { HttpMethod = HttpMethod.Put, RelativePath = \"{majorVersion}/{minorVersion}/custom\", HasRequestFormatters = true, HasResponseFormatters = true, NumberOfParameters = 3},\n                new { HttpMethod = HttpMethod.Delete, RelativePath = \"{majorVersion}/{minorVersion}/custom?id={id}\", HasRequestFormatters = false, HasResponseFormatters = false, NumberOfParameters = 3},\n                new { HttpMethod = HttpMethod.Get, RelativePath = \"{version}/Item?name={name}&series={series}\", HasRequestFormatters = false, HasResponseFormatters = true, NumberOfParameters = 3},\n                new { HttpMethod = HttpMethod.Post, RelativePath = \"{version}/Item\", HasRequestFormatters = true, HasResponseFormatters = true, NumberOfParameters = 2},\n                new { HttpMethod = HttpMethod.Put, RelativePath = \"{version}/Item\", HasRequestFormatters = true, HasResponseFormatters = true, NumberOfParameters = 2},\n                new { HttpMethod = HttpMethod.Delete, RelativePath = \"{version}/Item/{id}\", HasRequestFormatters = false, HasResponseFormatters = false, NumberOfParameters = 2}\n            };\n            ApiExplorerHelper.VerifyApiDescriptions(descriptions, expectedResults);\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ContentNegotiation/AcceptHeaderTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Net.Http.Headers;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ContentNegotiation\n{\n    public class AcceptHeaderTests : ContentNegotiationTestBase\n    {\n        [Theory]\n        [InlineData(\"application/json\")]\n        [InlineData(\"application/xml\")]\n        public async Task Response_Contains_ContentType(string contentType)\n        {\n            // Arrange\n            MediaTypeWithQualityHeaderValue requestContentType = new MediaTypeWithQualityHeaderValue(contentType);\n            MediaTypeHeaderValue responseContentType = null;\n\n            // Act\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, BaseAddress);\n            request.Headers.Accept.Add(requestContentType);\n            HttpResponseMessage response = await Client.SendAsync(request);\n            response.EnsureSuccessStatusCode();\n            responseContentType = response.Content.Headers.ContentType;\n\n            // Assert\n            Assert.Equal(requestContentType.MediaType, responseContentType.MediaType);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ContentNegotiation/ConnegController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.ContentNegotiation\n{\n    public class ConnegController : ApiController\n    {\n        public ConnegItem GetItem(string name = \"Fido\", int age = 3)\n        {\n            return new ConnegItem()\n            {\n                Name = name,\n                Age = age\n            };\n        }\n\n        public ConnegItem PostItem(ConnegItem item)\n        {\n            return item;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ContentNegotiation/ConnegItem.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.ContentNegotiation\n{\n    public class ConnegItem\n    {\n        public string Name { get; set; }\n        public int Age { get; set; }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ContentNegotiation/ContentNegotiationTestBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.ContentNegotiation\n{\n    public abstract class ContentNegotiationTestBase : HttpServerTestBase\n    {\n        protected ContentNegotiationTestBase()\n            : base(\"http://localhost/Conneg\")\n        {\n        }\n\n        protected override void ApplyConfiguration(HttpConfiguration configuration)\n        {\n            configuration.Routes.MapHttpRoute(\"Default\", \"{controller}\", new { controller = \"Conneg\" });\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ContentNegotiation/CustomFormatterTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Threading.Tasks;\nusing System.Web.Http.SelfHost;\nusing System.Web.Http.Util;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ContentNegotiation\n{\n    public class CustomFormatterTests\n    {\n        private HttpServer server = null;\n        private string baseAddress = null;\n        private HttpClient httpClient = null;\n        private HttpConfiguration config = null;\n\n        public CustomFormatterTests()\n        {\n            SetupHost();\n        }\n\n        [Fact]\n        public async Task CustomFormatter_Overrides_SetResponseHeaders_During_Conneg()\n        {\n            Order reqOrdr = new Order() { OrderId = \"100\", OrderValue = 100.00 };\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                Content = new ObjectContent<Order>(reqOrdr, new XmlMediaTypeFormatter())\n            };\n            request.RequestUri = new Uri(baseAddress + \"/CustomFormatterTests/EchoOrder\");\n            request.Method = HttpMethod.Post;\n            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(\"text/plainwithversioninfo\"));\n\n            HttpResponseMessage response = await httpClient.SendAsync(request);\n\n            response.EnsureSuccessStatusCode();\n\n            IEnumerable<string> versionHdr = null;\n            Assert.True(response.Content.Headers.TryGetValues(\"Version\", out versionHdr));\n            Assert.Equal(\"1.3.5.0\", versionHdr.First());\n            Assert.NotNull(response.Content);\n            Assert.NotNull(response.Content.Headers.ContentType);\n            Assert.Equal(\"text/plainwithversioninfo\", response.Content.Headers.ContentType.MediaType);\n        }\n\n        [Fact]\n        public async Task CustomFormatter_Post_Returns_Request_String_Content()\n        {\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                Content = new ObjectContent<string>(\"Hello World!\", new PlainTextFormatter())\n            };\n            request.RequestUri = new Uri(baseAddress + \"/CustomFormatterTests/EchoString\");\n            request.Method = HttpMethod.Post;\n\n            HttpResponseMessage response = await httpClient.SendAsync(request);\n\n            response.EnsureSuccessStatusCode();\n            Assert.NotNull(response.Content);\n            Assert.NotNull(response.Content.Headers.ContentType);\n            Assert.Equal(\"text/plain\", response.Content.Headers.ContentType.MediaType);\n            Assert.Equal(\"Hello World!\", await response.Content.ReadAsStringAsync());\n        }\n\n        [Fact]\n        public async Task CustomFormatter_Post_Returns_Request_Integer_Content()\n        {\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                Content = new ObjectContent<int>(100, new PlainTextFormatter())\n            };\n\n            request.RequestUri = new Uri(baseAddress + \"/CustomFormatterTests/EchoInt\");\n            request.Method = HttpMethod.Post;\n\n            HttpResponseMessage response = await httpClient.SendAsync(request);\n\n            response.EnsureSuccessStatusCode();\n            Assert.NotNull(response.Content);\n            Assert.NotNull(response.Content.Headers.ContentType);\n            Assert.Equal(\"text/plain\", response.Content.Headers.ContentType.MediaType);\n            Assert.Equal(100, Convert.ToInt32(await response.Content.ReadAsStringAsync()));\n        }\n\n        [Fact]\n        public async Task CustomFormatter_Post_Returns_Request_ComplexType_Content()\n        {\n            Order reqOrdr = new Order() { OrderId = \"100\", OrderValue = 100.00 };\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                Content = new ObjectContent<Order>(reqOrdr, new PlainTextFormatter())\n            };\n            request.RequestUri = new Uri(baseAddress + \"/CustomFormatterTests/EchoOrder\");\n            request.Method = HttpMethod.Post;\n\n            HttpResponseMessage response = await httpClient.SendAsync(request);\n\n            response.EnsureSuccessStatusCode();\n            Assert.NotNull(response.Content);\n            Assert.NotNull(response.Content.Headers.ContentType);\n            Assert.Equal(\"text/plain\", response.Content.Headers.ContentType.MediaType);\n        }\n\n        private void SetupHost()\n        {\n            baseAddress = \"http://localhost/\";\n            config = new HttpSelfHostConfiguration(baseAddress);\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{action}\", new { controller = \"CustomFormatterTests\", action = \"EchoOrder\" });\n            config.MessageHandlers.Add(new ConvertToStreamMessageHandler());\n            config.Formatters.Add(new PlainTextFormatterWithVersionInfo());\n            config.Formatters.Add(new PlainTextFormatter());\n\n            server = new HttpServer(config);\n            httpClient = new HttpClient(server);\n        }\n    }\n\n    public class PlainTextFormatterWithVersionInfo : MediaTypeFormatter\n    {\n        public PlainTextFormatterWithVersionInfo()\n        {\n            this.SupportedMediaTypes.Add(new MediaTypeHeaderValue(\"text/plainwithversioninfo\"));\n        }\n\n        public override bool CanReadType(Type type)\n        {\n            return true;\n        }\n\n        public override bool CanWriteType(Type type)\n        {\n            return true;\n        }\n\n        public override void SetDefaultContentHeaders(Type objectType, HttpContentHeaders contentHeaders, MediaTypeHeaderValue mediaType)\n        {\n            base.SetDefaultContentHeaders(objectType, contentHeaders, mediaType);\n            contentHeaders.TryAddWithoutValidation(\"Version\", \"1.3.5.0\");\n        }\n\n        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)\n        {\n            string stringContent = null;\n\n            using (var reader = new StreamReader(readStream))\n            {\n                stringContent = reader.ReadToEnd();\n            }\n\n            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();\n            tcs.SetResult(stringContent);\n\n            return tcs.Task;\n        }\n\n        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)\n        {\n            var output = value.ToString();\n            var writer = new StreamWriter(writeStream);\n            writer.Write(output);\n            writer.Flush();\n\n            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();\n            tcs.SetResult(null);\n\n            return tcs.Task;\n        }\n    }\n\n    public class PlainTextFormatter : MediaTypeFormatter\n    {\n        public PlainTextFormatter()\n        {\n            this.SupportedMediaTypes.Add(new MediaTypeHeaderValue(\"text/plain\"));\n        }\n\n        public override bool CanReadType(Type type)\n        {\n            return true;\n        }\n\n        public override bool CanWriteType(Type type)\n        {\n            return true;\n        }\n\n        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)\n        {\n            object result = null;\n\n            using (var reader = new StreamReader(readStream))\n            {\n                result = reader.ReadToEnd();\n            }\n\n            if (type == typeof(Int32))\n            {\n                result = Int32.Parse((string)result);\n            }\n            else if (type == typeof(Order))\n            {\n                result = new Order((string)result);\n            }\n\n            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();\n            tcs.SetResult(result);\n            return tcs.Task;\n        }\n\n        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)\n        {\n            var output = value == null ? String.Empty : value.ToString();\n            var writer = new StreamWriter(writeStream);\n            writer.Write(output);\n            writer.Flush();\n\n            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();\n            tcs.SetResult(null);\n            return tcs.Task;\n        }\n    }\n\n    public class CustomFormatterTestsController : ApiController\n    {\n        [HttpPost]\n        public string EchoString([FromBody] string input)\n        {\n            return input;\n        }\n\n        [HttpPost]\n        public int EchoInt([FromBody] int input)\n        {\n            return input;\n        }\n\n        [HttpPost]\n        public Order EchoOrder(Order order)\n        {\n            return order;\n        }\n    }\n\n    public class Order : IEquatable<Order>, ICloneable\n    {\n        public string OrderId { get; set; }\n        public double OrderValue { get; set; }\n\n        public Order() { }\n\n        public Order(string value)\n        {\n            string[] pieces = value.Split(new[] { '\\n' }, 2);\n\n            OrderId = pieces[0];\n            OrderValue = Double.Parse(pieces[1]);\n        }\n\n        public bool Equals(Order other)\n        {\n            return (this.OrderId.Equals(other.OrderId) && this.OrderValue.Equals(other.OrderValue));\n        }\n\n        public object Clone()\n        {\n            return this.MemberwiseClone();\n        }\n\n        public override string ToString()\n        {\n            return String.Format(\"{0}\\n{1}\", OrderId, OrderValue);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ContentNegotiation/DefaultContentNegotiatorTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.ContentNegotiation\n{\n    public class DefaultContentNegotiatorTests : ContentNegotiationTestBase\n    {\n        [Fact]\n        public async Task Custom_ContentNegotiator_Used_In_Response()\n        {\n            // Arrange\n            Configuration.Formatters.Clear();\n            MediaTypeWithQualityHeaderValue requestContentType = new MediaTypeWithQualityHeaderValue(\"application/xml\");\n            MediaTypeHeaderValue responseContentType = null;\n\n            Mock<IContentNegotiator> selector = new Mock<IContentNegotiator>();\n            selector.Setup(s => s.Negotiate(It.IsAny<Type>(), It.IsAny<HttpRequestMessage>(), It.IsAny<IEnumerable<MediaTypeFormatter>>()))\n                .Returns(new ContentNegotiationResult(new XmlMediaTypeFormatter(), null));\n\n            Configuration.Services.Replace(typeof(IContentNegotiator), selector.Object);\n\n            // Act\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, BaseAddress);\n            request.Headers.Accept.Add(requestContentType);\n            HttpResponseMessage response = await Client.SendAsync(request);\n            response.EnsureSuccessStatusCode();\n            responseContentType = response.Content.Headers.ContentType;\n\n            // Assert\n            selector.Verify(s => s.Negotiate(It.IsAny<Type>(), It.IsAny<HttpRequestMessage>(), It.IsAny<IEnumerable<MediaTypeFormatter>>()), Times.AtLeastOnce());\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ContentNegotiation/HttpResponseReturnTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Threading.Tasks;\nusing System.Web.Http.SelfHost;\nusing System.Web.Http.Util;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ContentNegotiation\n{\n    public class HttpResponseReturnTests\n    {\n        private HttpServer server = null;\n        private string baseAddress = null;\n        private HttpClient httpClient = null;\n\n        public HttpResponseReturnTests()\n        {\n            this.SetupHost();\n        }\n\n        [Theory]\n        [InlineData(\"ReturnHttpResponseMessage\")]\n        [InlineData(\"ReturnHttpResponseMessageAsObject\")]\n        [InlineData(\"ReturnString\")]\n        public async Task ActionReturnsHttpResponseMessage(string action)\n        {\n            string expectedResponseValue = @\"<string xmlns=\"\"http://schemas.microsoft.com/2003/10/Serialization/\"\">Hello</string>\";\n\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.RequestUri = new Uri(baseAddress + String.Format(\"HttpResponseReturn/{0}\", action));\n            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(\"application/xml\"));\n            request.Method = HttpMethod.Get;\n\n            HttpResponseMessage response = await httpClient.SendAsync(request);\n\n            Assert.NotNull(response.Content);\n            Assert.NotNull(response.Content.Headers.ContentType);\n            Assert.Equal(\"application/xml\", response.Content.Headers.ContentType.MediaType);\n            Assert.Equal(expectedResponseValue, await response.Content.ReadAsStringAsync());\n        }\n\n        [Theory]\n        [InlineData(\"ReturnHttpResponseMessageAsXml\")]\n        public async Task ActionReturnsHttpResponseMessageWithExplicitMediaType(string action)\n        {\n            string expectedResponseValue = @\"<string xmlns=\"\"http://schemas.microsoft.com/2003/10/Serialization/\"\">Hello</string>\";\n\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.RequestUri = new Uri(baseAddress + String.Format(\"HttpResponseReturn/{0}\", action));\n            request.Method = HttpMethod.Get;\n\n            HttpResponseMessage response = await httpClient.SendAsync(request);\n\n            Assert.NotNull(response.Content);\n            Assert.NotNull(response.Content.Headers.ContentType);\n            Assert.Equal(\"application/xml\", response.Content.Headers.ContentType.MediaType);\n            Assert.Equal(expectedResponseValue, await response.Content.ReadAsStringAsync());\n        }\n\n        [Theory]\n        [InlineData(\"ReturnMultipleSetCookieHeaders\")]\n        public async Task ReturnMultipleSetCookieHeadersShouldWork(string action)\n        {\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.RequestUri = new Uri(baseAddress + String.Format(\"HttpResponseReturn/{0}\", action));\n            request.Method = HttpMethod.Get;\n            HttpResponseMessage response = await httpClient.SendAsync(request);\n            response.EnsureSuccessStatusCode();\n            IEnumerable<string> list;\n            Assert.True(response.Headers.TryGetValues(\"Set-Cookie\", out list));\n            Assert.Equal(new[] { \"cookie1\", \"cookie2\" }, list);\n        }\n\n        private void SetupHost()\n        {\n            baseAddress = \"http://localhost/\";\n\n            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(baseAddress);\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{action}\", new { controller = \"HttpResponseReturn\" });\n            config.MessageHandlers.Add(new ConvertToStreamMessageHandler());\n\n            server = new HttpServer(config);\n            httpClient = new HttpClient(server);\n        }\n    }\n\n    public class HttpResponseReturnController : ApiController\n    {\n        [HttpGet]\n        public HttpResponseMessage ReturnHttpResponseMessage()\n        {\n            return Request.CreateResponse(HttpStatusCode.OK, \"Hello\");\n        }\n\n        [HttpGet]\n        public object ReturnHttpResponseMessageAsObject()\n        {\n            return ReturnHttpResponseMessage();\n        }\n\n        [HttpGet]\n        public HttpResponseMessage ReturnHttpResponseMessageAsXml()\n        {\n            HttpResponseMessage response = new HttpResponseMessage()\n            {\n                Content = new ObjectContent<string>(\"Hello\", new XmlMediaTypeFormatter())\n            };\n            return response;\n        }\n\n        [HttpGet]\n        public string ReturnString()\n        {\n            return \"Hello\";\n        }\n\n        [HttpGet]\n        public HttpResponseMessage ReturnMultipleSetCookieHeaders()\n        {\n            HttpResponseMessage resp = new HttpResponseMessage(HttpStatusCode.OK);\n            resp.Headers.Add(\"Set-Cookie\", \"cookie1\");\n            resp.Headers.Add(\"Set-Cookie\", \"cookie2\");\n            return resp;\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/Controllers/ActionAttributesTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http\n{\n    [CLSCompliant(false)]\n    public class ActionAttributesTest\n    {\n        [Theory]\n        [InlineData(\"GET\", \"ActionAttributeTest/RetriveUsers\", \"RetriveUsers\")]\n        [InlineData(\"POST\", \"ActionAttributeTest/AddUsers/1\", \"AddUsers\")]\n        [InlineData(\"PUT\", \"ActionAttributeTest/UpdateUsers\", \"UpdateUsers\")]\n        [InlineData(\"DELETE\", \"ActionAttributeTest/DeleteUsers\", \"DeleteUsers\")]\n        [InlineData(\"PATCH\", \"ActionAttributeTest/Users?key=2\", \"Users\")]\n        [InlineData(\"HEAD\", \"ActionAttributeTest/Users?key=3\", \"Users\")]\n        public void SelectAction_OnRouteWithActionParameter(string httpMethod, string requestUrl, string expectedActionName)\n        {\n            string routeUrl = \"{controller}/{action}/{id}\";\n            object routeDefault = new { id = RouteParameter.Optional };\n\n            HttpControllerContext controllerContext = ApiControllerHelper.CreateControllerContext(httpMethod, requestUrl, routeUrl, routeDefault);\n            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, \"test\", typeof(ActionAttributeTestController));\n            HttpActionDescriptor descriptor = ApiControllerHelper.SelectAction(controllerContext);\n\n            Assert.Equal(expectedActionName, descriptor.ActionName);\n        }\n\n        [Theory]\n        [InlineData(\"POST\", \"ActionAttributeTest/RetriveUsers\")]\n        [InlineData(\"DELETE\", \"ActionAttributeTest/RetriveUsers\")]\n        [InlineData(\"WHATEVER\", \"ActionAttributeTest/RetriveUsers\")]\n        [InlineData(\"GET\", \"ActionAttributeTest/UpdateUsers\")]\n        [InlineData(\"WHATEVER\", \"ActionAttributeTest/UpdateUsers\")]\n        [InlineData(\"POST\", \"ActionAttributeTest/DeleteUsers\")]\n        [InlineData(\"DELETEME\", \"ActionAttributeTest/DeleteUsers\")]\n        public void SelectAction_ThrowsMethodNotSupported_OnRouteWithActionParameter(string httpMethod, string requestUrl)\n        {\n            string routeUrl = \"{controller}/{action}/{id}\";\n            object routeDefault = new { id = RouteParameter.Optional };\n            HttpControllerContext controllerContext = ApiControllerHelper.CreateControllerContext(httpMethod, requestUrl, routeUrl, routeDefault);\n            Type controllerType = typeof(ActionAttributeTestController);\n            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, controllerType.Name, controllerType);\n\n            var exception = Assert.Throws<HttpResponseException>(() =>\n                {\n                    HttpActionDescriptor descriptor = ApiControllerHelper.SelectAction(controllerContext);\n                });\n\n            Assert.Equal(HttpStatusCode.MethodNotAllowed, exception.Response.StatusCode);\n            var content = Assert.IsType<ObjectContent<HttpError>>(exception.Response.Content);\n            Assert.Equal(\"The requested resource does not support http method '\" + httpMethod + \"'.\", ((HttpError)content.Value).Message);\n        }\n\n        [Theory]\n        [InlineData(\"POST\", \"ActionAttributeTest/NonAction\")]\n        [InlineData(\"ACTION\", \"ActionAttributeTest/NonActionWitHttpMethod\")]\n        [InlineData(\"GET\", \"ActionAttributeTest/AddUsers\")] // id is required on this action, so url is invalid. 404\n        [InlineData(\"PUT\", \"ActionAttributeTest/AddUsers\")] // id is required on this action, so url is invalid. 404\n        [InlineData(\"WHATEVER\", \"ActionAttributeTest/AddUsers\")] // id is required on this action, so url is invalid. 404\n        [InlineData(\"GET\", \"ActionAttributeTest/Users\")] // key param is required, bad url. 404\n        [InlineData(\"POST\", \"ActionAttributeTest/Users\")] // key param is required, bad url. 404\n        [InlineData(\"PATCHING\", \"ActionAttributeTest/Users\")] // key param is required, bad url. 404\n        [InlineData(\"NonAction\", \"ActionAttributeTest/NonAction\")] // NonAction, 404\n        [InlineData(\"GET\", \"ActionAttributeTest/NonAction\")] // NonAction, 404\n        public void SelectAction_ThrowsNotFound_OnRouteWithActionParameter(string httpMethod, string requestUrl)\n        {\n            string routeUrl = \"{controller}/{action}/{id}\";\n            object routeDefault = new { id = RouteParameter.Optional };\n            HttpControllerContext controllerContext = ApiControllerHelper.CreateControllerContext(httpMethod, requestUrl, routeUrl, routeDefault);\n            controllerContext.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;\n            Type controllerType = typeof(ActionAttributeTestController);\n            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, controllerType.Name, controllerType);\n\n            var exception = Assert.Throws<HttpResponseException>(() =>\n                {\n                    HttpActionDescriptor descriptor = ApiControllerHelper.SelectAction(controllerContext);\n                });\n\n            Assert.Equal(HttpStatusCode.NotFound, exception.Response.StatusCode);\n            var content = Assert.IsType<ObjectContent<HttpError>>(exception.Response.Content);\n\n            // Error message might be ApiControllerActionSelector_ActionNameNotFound or ApiControllerActionSelector_ActionNotFound\n            string actualMessage = (string)((HttpError)content.Value)[\"MessageDetail\"];\n            Assert.StartsWith(\"No action was found on the controller 'ActionAttributeTestController' that matches\", actualMessage);\n        }\n\n        [Theory]\n        [InlineData(\"GET\", \"ActionAttributeTest/\", \"RetriveUsers\")]\n        [InlineData(\"GET\", \"ActionAttributeTest/3\", \"RetriveUsers\")]\n        [InlineData(\"GET\", \"ActionAttributeTest/4?ssn=12345\", \"RetriveUsers\")]\n        [InlineData(\"POST\", \"ActionAttributeTest/1\", \"AddUsers\")]\n        [InlineData(\"PUT\", \"ActionAttributeTest\", \"UpdateUsers\")]\n        [InlineData(\"PUT\", \"ActionAttributeTest/4\", \"UpdateUsers\")]\n        [InlineData(\"PUT\", \"ActionAttributeTest/4?extra=thing\", \"UpdateUsers\")]\n        [InlineData(\"DELETE\", \"ActionAttributeTest\", \"DeleteUsers\")]\n        [InlineData(\"PATCH\", \"ActionAttributeTest\", \"PatchUsers\")]\n        [InlineData(\"HEAD\", \"ActionAttributeTest/\", \"Head\")]\n        [InlineData(\"PATCH\", \"ActionAttributeTest?key=2\", \"Users\")]\n        [InlineData(\"HEAD\", \"ActionAttributeTest?key=2\", \"Users\")]\n        [InlineData(\"OPTIONS\", \"ActionAttributeTest\", \"Options\")]\n        [InlineData(\"PATCH\", \"ActionAttributeTest/2\", \"Update\")]\n        [InlineData(\"HEAD\", \"ActionAttributeTest/2\", \"Ping\")]\n        [InlineData(\"OPTIONS\", \"ActionAttributeTest/2\", \"Help\")]\n        public void SelectAction_OnDefaultRoute(string httpMethod, string requestUrl, string expectedActionName)\n        {\n            string routeUrl = \"{controller}/{id}\";\n            object routeDefault = new { id = RouteParameter.Optional };\n\n            HttpControllerContext controllerContext = ApiControllerHelper.CreateControllerContext(httpMethod, requestUrl, routeUrl, routeDefault);\n            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, \"test\", typeof(ActionAttributeTestController));\n            HttpActionDescriptor descriptor = ApiControllerHelper.SelectAction(controllerContext);\n\n            Assert.Equal(expectedActionName, descriptor.ActionName);\n        }\n\n        [Theory]\n        [InlineData(\"CONNECT\", \"ActionAttributeTest\")]\n        [InlineData(\"TRACE\", \"ActionAttributeTest\")]\n        [InlineData(\"NonAction\", \"ActionAttributeTest/\")]\n        [InlineData(\"DENY\", \"ActionAttributeTest\")]\n        [InlineData(\"APP\", \"ActionAttributeTest\")]\n        public void SelectAction_ThrowsMethodNotSupported_OnDefaultRoute(string httpMethod, string requestUrl)\n        {\n            string routeUrl = \"{controller}/{id}\";\n            object routeDefault = new { id = RouteParameter.Optional };\n            HttpControllerContext controllerContext = ApiControllerHelper.CreateControllerContext(httpMethod, requestUrl, routeUrl, routeDefault);\n            Type controllerType = typeof(ActionAttributeTestController);\n            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, controllerType.Name, controllerType);\n\n            var exception = Assert.Throws<HttpResponseException>(() =>\n                {\n                    HttpActionDescriptor descriptor = ApiControllerHelper.SelectAction(controllerContext);\n                });\n\n            Assert.Equal(HttpStatusCode.MethodNotAllowed, exception.Response.StatusCode);\n            var content = Assert.IsType<ObjectContent<HttpError>>(exception.Response.Content);\n            Assert.Equal(\"The requested resource does not support http method '\" + httpMethod + \"'.\", ((HttpError)content.Value).Message);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/Controllers/ActionReachabilityTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http\n{\n    public class ActionReachabilityTest\n    {\n        [Theory]\n        [InlineData(\"GET\", \"Users\", HttpStatusCode.OK, \"GetUser\")]\n        [InlineData(\"UPDATE\", \"Users\", HttpStatusCode.OK, \"PutUser\")]\n        [InlineData(\"DELETE\", \"Users\", HttpStatusCode.OK, \"Remove\")]\n        [InlineData(\"OPTIONS\", \"Users\", HttpStatusCode.OK, \"Assist\")]\n        [InlineData(\"PUT\", \"Users\", HttpStatusCode.OK, \"PutUserWithEmptyName\")]\n        [InlineData(\"GET\", \"ParameterTest\", HttpStatusCode.OK, \"Get(-1)\")]\n        [InlineData(\"GET\", \"ParameterTest?id=2\", HttpStatusCode.OK, \"Get(2)\")]\n        [InlineData(\"POST\", \"ParameterTest\", HttpStatusCode.OK, \"POST(null)\")]\n        [InlineData(\"POST\", \"ParameterTest?id=myId\", HttpStatusCode.OK, \"POST(myId)\")]\n        [InlineData(\"Put\", \"ParameterTest?id=1&value=myvalue\", HttpStatusCode.OK, \"Put(1, myvalue)\")]\n        [InlineData(\"DELETE\", \"ParameterTest?id=1\", HttpStatusCode.NoContent, \"\")]\n        [InlineData(\"POST\", \"Users\", HttpStatusCode.InternalServerError, \"\")] // InternalServerError because of ambiguous match, there're multiple POST actions given that every action is POST by default\n        [InlineData(\"POST\", \"Users/Approve\", HttpStatusCode.NotFound, \"\")] // NotFound because it doesn't match the route\n        [InlineData(\"DELETE\", \"Users/Remove\", HttpStatusCode.NotFound, \"\")] // NotFound because it doesn't match the route\n        [InlineData(\"POST\", \"Users/DefaultActionWithEmptyActionName\", HttpStatusCode.NotFound, \"\")] // NotFound because it doesn't match the route\n        [InlineData(\"DELETE\", \"ParameterTest\", HttpStatusCode.MethodNotAllowed, \"\")] // MethodNotAllowed because url is valid, but not for Delete.\n        [InlineData(\"Put\", \"ParameterTest\", HttpStatusCode.MethodNotAllowed, \"\")] // Put requires 'id' and 'value' as parameters, but url is still valid for other verbs (GET, Delete,Post).\n        [InlineData(\"Put\", \"ParameterTest?id=1\", HttpStatusCode.MethodNotAllowed, \"\")] // Put requires 'id' and 'value' as parameters, but url is still valid for other verbs (GET,Post).\n        public async Task ActionReachability_UsingResourceOrientedRoute(string httpMethod, string requestUrl, HttpStatusCode expectedStatusCode, string expectedActionName)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"REST\", \"{controller}\");\n            HttpServer server = new HttpServer(config);\n            HttpClient client = new HttpClient(server);\n            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(httpMethod), \"http://localhost/\" + requestUrl);\n\n            HttpResponseMessage response = await client.SendAsync(request);\n\n            Assert.Equal(expectedStatusCode, response.StatusCode);\n            if (response.StatusCode == HttpStatusCode.OK)\n            {\n                Assert.Equal(expectedActionName, await response.Content.ReadAsAsync<string>());\n            }\n        }\n\n        [Theory]\n        [InlineData(\"GET\", \"Users/GetUser\", HttpStatusCode.OK, \"GetUser\")]\n        [InlineData(\"POST\", \"Users/Approve\", HttpStatusCode.OK, \"Approve\")]\n        [InlineData(\"UPDATE\", \"Users/PutUser\", HttpStatusCode.OK, \"PutUser\")]\n        [InlineData(\"POST\", \"Users/UpdateUser\", HttpStatusCode.OK, \"PostUser\")]\n        [InlineData(\"PATCH\", \"Users/ReplaceUser\", HttpStatusCode.OK, \"DeleteUser\")]\n        [InlineData(\"DELETE\", \"Users/Remove\", HttpStatusCode.OK, \"Remove\")]\n        [InlineData(\"POST\", \"Users/Reject\", HttpStatusCode.OK, \"Deny\")]\n        [InlineData(\"OPTIONS\", \"Users/Help\", HttpStatusCode.OK, \"Assist\")]\n        [InlineData(\"GET\", \"ParameterTest/Get\", HttpStatusCode.OK, \"Get(-1)\")]\n        [InlineData(\"GET\", \"ParameterTest/Get?id=2\", HttpStatusCode.OK, \"Get(2)\")]\n        [InlineData(\"POST\", \"ParameterTest/post\", HttpStatusCode.OK, \"POST(null)\")]\n        [InlineData(\"POST\", \"ParameterTest/post?id=myId\", HttpStatusCode.OK, \"POST(myId)\")]\n        [InlineData(\"Put\", \"ParameterTest/put?id=1&value=myvalue\", HttpStatusCode.OK, \"Put(1, myvalue)\")]\n        [InlineData(\"DELETE\", \"ParameterTest/Delete?id=1\", HttpStatusCode.NoContent, \"\")]\n        [InlineData(\"POST\", \"Users/GetUser\", HttpStatusCode.MethodNotAllowed, \"\")] // MethodNotAllowed because the convention implies it's a GET\n        [InlineData(\"GET\", \"Users\", HttpStatusCode.NotFound, \"\")] // NotFound because it doesn't match the route\n        [InlineData(\"PUT\", \"Users\", HttpStatusCode.NotFound, \"\")] // NotFound because it doesn't match the route\n        [InlineData(\"PUT\", \"Users/PutUserWithEmptyName\", HttpStatusCode.NotFound, \"\")] // NotFound because the action has an empty name and it's not reachable through {action}\n        [InlineData(\"POST\", \"Users/PostUser\", HttpStatusCode.NotFound, \"\")] // NotFound because the action name is renamed to UpdateUser\n        [InlineData(\"GET\", \"Users/Approve\", HttpStatusCode.MethodNotAllowed, \"\")] // MethodNotAllowed because only POST is allowed by default for action that has no HttpMethd declared or implied\n        [InlineData(\"POST\", \"Users/Remove\", HttpStatusCode.MethodNotAllowed, \"\")] // MethodNotAllowed because the action has the attribute HttpDelete\n        [InlineData(\"POST\", \"Users/DefaultActionWithEmptyActionName\", HttpStatusCode.NotFound, \"\")] // NotFound because the action has an empty name and it's not reachable through {action}\n        [InlineData(\"DELETE\", \"ParameterTest/Delete\", HttpStatusCode.NotFound, \"\")] // NotFound because Delete requires 'id' as parameter\n        [InlineData(\"Put\", \"ParameterTest/put\", HttpStatusCode.NotFound, \"\")] // NotFound because Put requires 'id' and 'value' as parameters\n        [InlineData(\"Put\", \"ParameterTest/put?id=1\", HttpStatusCode.NotFound, \"\")] // NotFound because Put requires 'id' and 'value' as parameters\n        public async Task ActionReachability_UsingRpcStyleRoute(string httpMethod, string requestUrl, HttpStatusCode expectedStatusCode, string expectedActionName)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"RPC\", \"{controller}/{action}\");\n            HttpServer server = new HttpServer(config);\n            HttpClient client = new HttpClient(server);\n            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(httpMethod), \"http://localhost/\" + requestUrl);\n\n            HttpResponseMessage response = await client.SendAsync(request);\n\n            Assert.Equal(expectedStatusCode, response.StatusCode);\n            if (response.StatusCode == HttpStatusCode.OK)\n            {\n                Assert.Equal(expectedActionName, await response.Content.ReadAsAsync<string>());\n            }\n        }\n\n        [Theory]\n        [InlineData(\"GET\", \"Users/GetUser\", HttpStatusCode.OK, \"GetUser\")]\n        [InlineData(\"POST\", \"Users/Approve\", HttpStatusCode.OK, \"Approve\")]\n        [InlineData(\"UPDATE\", \"Users/PutUser\", HttpStatusCode.OK, \"PutUser\")]\n        [InlineData(\"POST\", \"Users/UpdateUser\", HttpStatusCode.OK, \"PostUser\")]\n        [InlineData(\"PATCH\", \"Users/ReplaceUser\", HttpStatusCode.OK, \"DeleteUser\")]\n        [InlineData(\"DELETE\", \"Users/Remove\", HttpStatusCode.OK, \"Remove\")]\n        [InlineData(\"POST\", \"Users/Reject\", HttpStatusCode.OK, \"Deny\")]\n        [InlineData(\"OPTIONS\", \"Users/Help\", HttpStatusCode.OK, \"Assist\")]\n        [InlineData(\"POST\", \"Users\", HttpStatusCode.OK, \"DefaultActionWithEmptyActionName\")]\n        [InlineData(\"PUT\", \"Users\", HttpStatusCode.OK, \"PutUserWithEmptyName\")]\n        [InlineData(\"GET\", \"Users\", HttpStatusCode.MethodNotAllowed, \"\")] // MethodNotAllowed because GetUser doesn't have the ActionName=\"\" so it's not reachable\n        [InlineData(\"UPDATE\", \"Users\", HttpStatusCode.MethodNotAllowed, \"\")] // MethodNotAllowed because GetUser doesn't have the ActionName=\"\" so it's not reachable\n        [InlineData(\"DELETE\", \"Users\", HttpStatusCode.MethodNotAllowed, \"Remove\")] // MethodNotAllowed because GetUser doesn't have the ActionName=\"\" so it's not reachable\n        [InlineData(\"OPTIONS\", \"Users\", HttpStatusCode.MethodNotAllowed, \"\")] // MethodNotAllowed because GetUser doesn't have the ActionName=\"\" so it's not reachable\n        [InlineData(\"PUT\", \"Users/PutUserWithEmptyName\", HttpStatusCode.NotFound, \"\")] // NotFound because the action has an empty name and it's not reachable through {action}\n        [InlineData(\"POST\", \"Users/GetUser\", HttpStatusCode.MethodNotAllowed, \"\")] // MethodNotAllowed because the convention implies it's a GET\n        [InlineData(\"POST\", \"Users/PostUser\", HttpStatusCode.NotFound, \"\")] // NotFound because the action name is renamed to UpdateUser\n        [InlineData(\"GET\", \"Users/Approve\", HttpStatusCode.MethodNotAllowed, \"\")] // MethodNotAllowed because only POST is allowed by default for action that has no HttpMethd declared or implied\n        [InlineData(\"POST\", \"Users/Remove\", HttpStatusCode.MethodNotAllowed, \"\")] // MethodNotAllowed because the action has the attribute HttpDelete\n        [InlineData(\"POST\", \"Users/DefaultActionWithEmptyActionName\", HttpStatusCode.NotFound, \"\")] // NotFound because the ActionName=\"\" and no HttpMethd is declared or implied\n        public async Task ActionReachability_UsingResourceAndRpcStyleRoutes(string httpMethod, string requestUrl, HttpStatusCode expectedStatusCode, string expectedActionName)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Hybrid\", \"{controller}/{action}\", new { action = \"\" });\n            HttpServer server = new HttpServer(config);\n            HttpClient client = new HttpClient(server);\n            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(httpMethod), \"http://localhost/\" + requestUrl);\n\n            HttpResponseMessage response = await client.SendAsync(request);\n\n            Assert.Equal(expectedStatusCode, response.StatusCode);\n            if (response.StatusCode == HttpStatusCode.OK)\n            {\n                Assert.Equal(expectedActionName, await response.Content.ReadAsAsync<string>());\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/Controllers/ApiControllerActionSelectorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.ValueProviders;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http\n{\n    [CLSCompliant(false)]\n    public class ApiControllerActionSelectorTest\n    {\n        [Theory]\n        [InlineData(\"GET\", \"Test\", \"GetUsers\")]\n        [InlineData(\"GET\", \"Test/2\", \"GetUser\")]\n        [InlineData(\"GET\", \"Test/3?name=mario\", \"GetUserByNameAndId\")]\n        [InlineData(\"GET\", \"Test/3?name=mario&ssn=123456\", \"GetUserByNameIdAndSsn\")]\n        [InlineData(\"GET\", \"Test?name=mario&ssn=123456\", \"GetUserByNameAndSsn\")]\n        [InlineData(\"GET\", \"Test?name=mario&ssn=123456&age=3\", \"GetUserByNameAgeAndSsn\")]\n        [InlineData(\"GET\", \"Test/5?random=9\", \"GetUser\")]\n        [InlineData(\"Post\", \"Test\", \"PostUser\")]\n        [InlineData(\"Post\", \"Test?name=mario&age=10\", \"PostUserByNameAndAge\")]\n\n        // Note: Normally the following would not match DeleteUserByIdAndOptName because it has 'id' and 'age' as parameters while the DeleteUserByIdAndOptName action has 'id' and 'name'.\n        // However, because the default value is provided on action parameter 'name', having the 'id' in the request was enough to match the action.\n        [InlineData(\"Delete\", \"Test/6?age=10\", \"DeleteUserByIdAndOptName\")]\n        [InlineData(\"Delete\", \"Test\", \"DeleteUserByOptName\")]\n        [InlineData(\"Delete\", \"Test?name=user\", \"DeleteUserByOptName\")]\n        [InlineData(\"Delete\", \"Test/6?email=user@test.com\", \"DeleteUserById_Email_OptName_OptPhone\")]\n        [InlineData(\"Delete\", \"Test/6?email=user@test.com&name=user\", \"DeleteUserById_Email_OptName_OptPhone\")]\n        [InlineData(\"Delete\", \"Test/6?email=user@test.com&name=user&phone=123456789\", \"DeleteUserById_Email_OptName_OptPhone\")]\n        [InlineData(\"Delete\", \"Test/6?email=user@test.com&height=1.8\", \"DeleteUserById_Email_Height_OptName_OptPhone\")]\n        [InlineData(\"Delete\", \"Test/6?email=user@test.com&height=1.8&name=user\", \"DeleteUserById_Email_Height_OptName_OptPhone\")]\n        [InlineData(\"Delete\", \"Test/6?email=user@test.com&height=1.8&name=user&phone=12345678\", \"DeleteUserById_Email_Height_OptName_OptPhone\")]\n        [InlineData(\"Head\", \"Test/6\", \"Head_Id_OptSize_OptIndex\")]\n        [InlineData(\"Head\", \"Test/6?size=2\", \"Head_Id_OptSize_OptIndex\")]\n        [InlineData(\"Head\", \"Test/6?index=2\", \"Head_Id_OptSize_OptIndex\")]\n        [InlineData(\"Head\", \"Test/6?index=2&size=10\", \"Head_Id_OptSize_OptIndex\")]\n        [InlineData(\"Head\", \"Test/6?index=2&otherParameter=10\", \"Head_Id_OptSize_OptIndex\")]\n        [InlineData(\"Head\", \"Test/6?otherQueryParameter=1234\", \"Head_Id_OptSize_OptIndex\")]\n        [InlineData(\"Head\", \"Test\", \"Head\")]\n        [InlineData(\"Head\", \"Test?otherParam=2\", \"Head\")]\n        [InlineData(\"Head\", \"Test?index=2&size=10\", \"Head\")]\n        public void Route_Parameters_Default(string httpMethod, string requestUrl, string expectedActionName)\n        {\n            string routeUrl = \"{controller}/{id}\";\n            object routeDefault = new { id = RouteParameter.Optional };\n\n            HttpControllerContext context = ApiControllerHelper.CreateControllerContext(httpMethod, requestUrl, routeUrl, routeDefault);\n            context.ControllerDescriptor = new HttpControllerDescriptor(context.Configuration, \"test\", typeof(TestController));\n            HttpActionDescriptor descriptor = ApiControllerHelper.SelectAction(context);\n\n            Assert.Equal(expectedActionName, descriptor.ActionName);\n        }\n\n        [Theory]\n        [InlineData(\"GET\", \"Test\", \"GetUsers\")]\n        [InlineData(\"GET\", \"Test/2\", \"GetUsersByName\")]\n        [InlineData(\"GET\", \"Test/luigi?ssn=123456\", \"GetUserByNameAndSsn\")]\n        [InlineData(\"GET\", \"Test/luigi?ssn=123456&id=2&ssn=12345\", \"GetUserByNameIdAndSsn\")]\n        [InlineData(\"GET\", \"Test?age=10&ssn=123456\", \"GetUsers\")]\n        [InlineData(\"GET\", \"Test?id=3&ssn=123456&name=luigi\", \"GetUserByNameIdAndSsn\")]\n        [InlineData(\"POST\", \"Test/luigi?age=20\", \"PostUserByNameAndAge\")]\n        public void Route_Parameters_Non_Id(string httpMethod, string requestUrl, string expectedActionName)\n        {\n            string routeUrl = \"{controller}/{name}\";\n            object routeDefault = new { name = RouteParameter.Optional };\n\n            HttpControllerContext context = ApiControllerHelper.CreateControllerContext(httpMethod, requestUrl, routeUrl, routeDefault);\n            context.ControllerDescriptor = new HttpControllerDescriptor(context.Configuration, \"test\", typeof(TestController));\n            HttpActionDescriptor descriptor = ApiControllerHelper.SelectAction(context);\n\n            Assert.Equal(expectedActionName, descriptor.ActionName);\n        }\n\n        [Theory]\n        [InlineData(\"GET\", \"Test/3?NAME=mario\", \"GetUserByNameAndId\")]\n        [InlineData(\"GET\", \"Test/3?name=mario&SSN=123456\", \"GetUserByNameIdAndSsn\")]\n        [InlineData(\"GET\", \"Test?nAmE=mario&ssn=123456&AgE=3\", \"GetUserByNameAgeAndSsn\")]\n        [InlineData(\"Delete\", \"Test/6?AGe=10\", \"DeleteUserByIdAndOptName\")]\n        public void Route_Parameters_Casing(string httpMethod, string requestUrl, string expectedActionName)\n        {\n            string routeUrl = \"{controller}/{ID}\";\n            object routeDefault = new { id = RouteParameter.Optional };\n\n            HttpControllerContext context = ApiControllerHelper.CreateControllerContext(httpMethod, requestUrl, routeUrl, routeDefault);\n            context.ControllerDescriptor = new HttpControllerDescriptor(context.Configuration, \"test\", typeof(TestController));\n            HttpActionDescriptor descriptor = ApiControllerHelper.SelectAction(context);\n\n            Assert.Equal(expectedActionName, descriptor.ActionName);\n        }\n\n        [Theory]\n        [InlineData(\"GET\", \"Test/GetUsers\", \"GetUsers\")]\n        [InlineData(\"GET\", \"Test/GetUser/7\", \"GetUser\")]\n        [InlineData(\"GET\", \"Test/GetUser?id=3\", \"GetUser\")]\n        [InlineData(\"GET\", \"Test/GetUser/4?id=3\", \"GetUser\")]\n        [InlineData(\"GET\", \"Test/GetUserByNameAgeAndSsn?name=user&age=90&ssn=123456789\", \"GetUserByNameAgeAndSsn\")]\n        [InlineData(\"GET\", \"Test/GetUserByNameAndSsn?name=user&ssn=123456789\", \"GetUserByNameAndSsn\")]\n        [InlineData(\"POST\", \"Test/PostUserByNameAndAddress?name=user\", \"PostUserByNameAndAddress\")]\n        public void Route_Action(string httpMethod, string requestUrl, string expectedActionName)\n        {\n            string routeUrl = \"{controller}/{action}/{id}\";\n            object routeDefault = new { id = RouteParameter.Optional };\n\n            HttpControllerContext context = ApiControllerHelper.CreateControllerContext(httpMethod, requestUrl, routeUrl, routeDefault);\n            context.ControllerDescriptor = new HttpControllerDescriptor(context.Configuration, \"test\", typeof(TestController));\n            HttpActionDescriptor descriptor = ApiControllerHelper.SelectAction(context);\n\n            Assert.Equal(expectedActionName, descriptor.ActionName);\n        }\n\n        [Theory]\n        [InlineData(\"GET\", \"Test/getusers\", \"GetUsers\")]\n        [InlineData(\"GET\", \"Test/getuseR/1\", \"GetUser\")]\n        [InlineData(\"GET\", \"Test/Getuser?iD=3\", \"GetUser\")]\n        [InlineData(\"GET\", \"Test/GetUser/4?Id=3\", \"GetUser\")]\n        [InlineData(\"GET\", \"Test/GetUserByNameAgeandSsn?name=user&age=90&ssn=123456789\", \"GetUserByNameAgeAndSsn\")]\n        [InlineData(\"GET\", \"Test/getUserByNameAndSsn?name=user&ssn=123456789\", \"GetUserByNameAndSsn\")]\n        [InlineData(\"POST\", \"Test/PostUserByNameAndAddress?name=user\", \"PostUserByNameAndAddress\")]\n        public void Route_Action_Name_Casing(string httpMethod, string requestUrl, string expectedActionName)\n        {\n            string routeUrl = \"{controller}/{action}/{id}\";\n            object routeDefault = new { id = RouteParameter.Optional };\n\n            HttpControllerContext context = ApiControllerHelper.CreateControllerContext(httpMethod, requestUrl, routeUrl, routeDefault);\n            context.ControllerDescriptor = new HttpControllerDescriptor(context.Configuration, \"test\", typeof(TestController));\n            HttpActionDescriptor descriptor = ApiControllerHelper.SelectAction(context);\n\n            Assert.Equal(expectedActionName, descriptor.ActionName);\n        }\n\n        [Theory]\n        [InlineData(\"GET\", \"Test\", \"GetUsers\")]\n        [InlineData(\"GET\", \"Test/?name=peach\", \"GetUsersByName\")]\n        [InlineData(\"GET\", \"Test?name=peach\", \"GetUsersByName\")]\n        [InlineData(\"GET\", \"Test?name=peach&ssn=123456\", \"GetUserByNameAndSsn\")]\n        [InlineData(\"GET\", \"Test?name=peach&ssn=123456&age=3\", \"GetUserByNameAgeAndSsn\")]\n        public void Route_No_Action(string httpMethod, string requestUrl, string expectedActionName)\n        {\n            string routeUrl = \"{controller}\";\n\n            HttpControllerContext context = ApiControllerHelper.CreateControllerContext(httpMethod, requestUrl, routeUrl);\n            context.ControllerDescriptor = new HttpControllerDescriptor(context.Configuration, \"test\", typeof(TestController));\n            HttpActionDescriptor descriptor = ApiControllerHelper.SelectAction(context);\n\n            Assert.Equal(expectedActionName, descriptor.ActionName);\n        }\n\n        [Theory]\n        [InlineData(\"GET\", \"ParameterAttribute/2\", \"GetUser\")]\n        [InlineData(\"GET\", \"ParameterAttribute?id=2\", \"GetUser\")]\n        [InlineData(\"GET\", \"ParameterAttribute?myId=2\", \"GetUserByMyId\")]\n        [InlineData(\"POST\", \"ParameterAttribute/3?name=user\", \"PostUserNameFromUri\")]\n        [InlineData(\"POST\", \"ParameterAttribute/3\", \"PostUserNameFromBody\")]\n        [InlineData(\"DELETE\", \"ParameterAttribute/3?name=user\", \"DeleteUserWithNullableIdAndName\")]\n        [InlineData(\"DELETE\", \"ParameterAttribute?address=userStreet\", \"DeleteUser\")]\n        public void ModelBindingParameterAttribute_AreAppliedWhenSelectingActions(string httpMethod, string requestUrl, string expectedActionName)\n        {\n            string routeUrl = \"{controller}/{id}\";\n            object routeDefault = new { id = RouteParameter.Optional };\n\n            HttpControllerContext context = ApiControllerHelper.CreateControllerContext(httpMethod, requestUrl, routeUrl, routeDefault);\n            context.ControllerDescriptor = new HttpControllerDescriptor(context.Configuration, \"ParameterAttribute\", typeof(ParameterAttributeController));\n            HttpActionDescriptor descriptor = ApiControllerHelper.SelectAction(context);\n\n            Assert.Equal(expectedActionName, descriptor.ActionName);\n        }\n\n        [Theory]\n        [InlineData(\"GET\", \"notActionParameterValue1/Test\", \"GetUsers\")]\n        [InlineData(\"GET\", \"notActionParameterValue2/Test/2\", \"GetUser\")]\n        [InlineData(\"GET\", \"notActionParameterValue1/Test?randomQueryVariable=val1\", \"GetUsers\")]\n        [InlineData(\"GET\", \"notActionParameterValue2/Test/2?randomQueryVariable=val2\", \"GetUser\")]\n        public void ActionsThatHaveSubsetOfRouteParameters_AreConsideredForSelection(string httpMethod, string requestUrl, string expectedActionName)\n        {\n            string routeUrl = \"{notActionParameter}/{controller}/{id}\";\n            object routeDefault = new { id = RouteParameter.Optional };\n\n            HttpControllerContext context = ApiControllerHelper.CreateControllerContext(httpMethod, requestUrl, routeUrl, routeDefault);\n            context.ControllerDescriptor = new HttpControllerDescriptor(context.Configuration, \"test\", typeof(TestController));\n            HttpActionDescriptor descriptor = ApiControllerHelper.SelectAction(context);\n\n            Assert.Equal(expectedActionName, descriptor.ActionName);\n        }\n\n        [Fact]\n        public void RequestToAmbiguousAction_OnDefaultRoute()\n        {\n            string routeUrl = \"{controller}/{id}\";\n            object routeDefault = new { id = RouteParameter.Optional };\n            string httpMethod = \"Post\";\n            string requestUrl = \"Test?name=mario\";\n\n            // This would result in ambiguous match because complex parameter is not considered for matching.\n            // Therefore, PostUserByNameAndAddress(string name, Address address) would conflicts with PostUserByName(string name)\n            Assert.Throws<InvalidOperationException>(() =>\n                {\n                    HttpControllerContext context = ApiControllerHelper.CreateControllerContext(httpMethod, requestUrl, routeUrl, routeDefault);\n                    context.ControllerDescriptor = new HttpControllerDescriptor(context.Configuration, \"test\", typeof(TestController));\n                    HttpActionDescriptor descriptor = ApiControllerHelper.SelectAction(context);\n                });\n        }\n\n        [Fact]\n        public void RequestToActionWithNotSupportedHttpMethod_OnRouteWithAction()\n        {\n            string routeUrl = \"{controller}/{action}/{id}\";\n            object routeDefault = new { id = RouteParameter.Optional };\n            string requestUrl = \"Test/GetUsers\";\n            string httpMethod = \"POST\";\n\n            var exception = Assert.Throws<HttpResponseException>(() =>\n            {\n                HttpControllerContext context = ApiControllerHelper.CreateControllerContext(httpMethod, requestUrl, routeUrl, routeDefault);\n                context.ControllerDescriptor = new HttpControllerDescriptor(context.Configuration, \"test\", typeof(TestController));\n                HttpActionDescriptor descriptor = ApiControllerHelper.SelectAction(context);\n            });\n\n            Assert.Equal(HttpStatusCode.MethodNotAllowed, exception.Response.StatusCode);\n            var content = Assert.IsType<ObjectContent<HttpError>>(exception.Response.Content);\n            AssertAllowedHeaders(exception.Response, HttpMethod.Get);\n            Assert.Equal(\"The requested resource does not support http method 'POST'.\", ((HttpError)content.Value).Message);\n        }\n\n        [Fact]\n        public void RequestToActionWith_HttpMethodDefinedByAttributeAndActionName()\n        {\n            string routeUrl = \"{controller}/{id}\";\n            object routeDefault = new { id = RouteParameter.Optional };\n            string requestUrl = \"Test\";\n            string httpMethod = \"PATCH\";\n\n            HttpControllerContext context = ApiControllerHelper.CreateControllerContext(httpMethod, requestUrl, routeUrl, routeDefault);\n            context.ControllerDescriptor = new HttpControllerDescriptor(context.Configuration, \"test\", typeof(TestController));\n            HttpActionDescriptor descriptor = ApiControllerHelper.SelectAction(context);\n\n            Assert.Equal(\"PutUser\", descriptor.ActionName);\n\n            // When you have the HttpMethod attribute, the convention should not be applied.\n            httpMethod = \"PUT\";\n            var exception = Assert.Throws<HttpResponseException>(() =>\n            {\n                context = ApiControllerHelper.CreateControllerContext(httpMethod, requestUrl, routeUrl, routeDefault);\n                context.ControllerDescriptor = new HttpControllerDescriptor(context.Configuration, \"test\", typeof(TestController));\n                ApiControllerHelper.SelectAction(context);\n            });\n\n            Assert.Equal(HttpStatusCode.MethodNotAllowed, exception.Response.StatusCode);\n            var content = Assert.IsType<ObjectContent<HttpError>>(exception.Response.Content);\n            Assert.Equal(\"The requested resource does not support http method 'PUT'.\", ((HttpError)content.Value).Message);\n            AssertAllowedHeaders(exception.Response, HttpMethod.Get, new HttpMethod(\"PATCH\"), HttpMethod.Post, HttpMethod.Delete, HttpMethod.Head);\n        }\n\n        // Verify response has all the methods in its Allow header. values are unsorted.\n        private void AssertAllowedHeaders(HttpResponseMessage response, params HttpMethod[] allowedMethods)\n        {\n            foreach (var method in allowedMethods)\n            {\n                Assert.Contains(method.ToString(), response.Content.Headers.Allow);\n            }\n            Assert.Equal(allowedMethods.Length, response.Content.Headers.Allow.Count);\n        }\n\n        [Theory]\n        [InlineData(\"GET\", \"Test\", \"GetUsers\")]\n        [InlineData(\"GET\", \"Test/2\", \"GetUser\")]\n        [InlineData(\"GET\", \"Test/3?name=mario\", \"GetUserByNameAndId\")]\n        [InlineData(\"GET\", \"Test/3?name=mario&ssn=123456\", \"GetUserByNameIdAndSsn\")]\n        [InlineData(\"GET\", \"Test?name=mario&ssn=123456\", \"GetUserByNameAndSsn\")]\n        [InlineData(\"GET\", \"Test?name=mario&ssn=123456&age=3\", \"GetUserByNameAgeAndSsn\")]\n        [InlineData(\"GET\", \"Test/5?random=9\", \"GetUser\")]\n        public void SelectionBasedOnParameter_IsNotAffectedBy_AddingGlobalValueProvider(string httpMethod, string requestUrl, string expectedActionName)\n        {\n            string routeUrl = \"{controller}/{id}\";\n            object routeDefault = new { id = RouteParameter.Optional };\n\n            HttpControllerContext context = ApiControllerHelper.CreateControllerContext(httpMethod, requestUrl, routeUrl, routeDefault);\n            context.Configuration.Services.Add(typeof(ValueProviderFactory), new HeaderValueProviderFactory());\n            context.ControllerDescriptor = new HttpControllerDescriptor(context.Configuration, \"test\", typeof(TestController));\n            HttpActionDescriptor descriptor = ApiControllerHelper.SelectAction(context);\n\n            Assert.Equal(expectedActionName, descriptor.ActionName);\n        }\n\n        [Theory]\n        [InlineData(\"GET\", \"Test\", \"Get\")]\n        [InlineData(\"GET\", \"Test?scope=global\", \"GetWithEnumParameter\")]\n        [InlineData(\"GET\", \"Test?level=off&kind=trace\", \"GetWithTwoEnumParameters\")]\n        [InlineData(\"GET\", \"Test?level=\", \"GetWithNullableEnumParameter\")]\n        public void SelectAction_ReturnsActionDescriptor_ForEnumParameterOverloads(string httpMethod, string requestUrl, string expectedActionName)\n        {\n            string routeUrl = \"{controller}\";\n\n            HttpControllerContext context = ApiControllerHelper.CreateControllerContext(httpMethod, requestUrl, routeUrl);\n            context.ControllerDescriptor = new HttpControllerDescriptor(context.Configuration, \"EnumParameterOverloadsController\", typeof(EnumParameterOverloadsController));\n            HttpActionDescriptor descriptor = ApiControllerHelper.SelectAction(context);\n\n            Assert.Equal(expectedActionName, descriptor.ActionName);\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/Controllers/Apis/ActionAttributeTestController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http\n{\n    public class ActionAttributeTestController : ApiController\n    {\n        [HttpGet]\n        public void RetriveUsers() { }\n\n        [HttpPost]\n        public void AddUsers(int id) { }\n\n        [HttpPut]\n        public void UpdateUsers(User user) { }\n\n        [HttpDelete]\n        [ActionName(\"DeleteUsers\")]\n        public void RemoveUsers(string name = null) { }\n\n        [HttpOptions]\n        public void Help(int id) { }\n\n        [HttpHead]\n        public void Ping(int id) { }\n\n        [HttpPatch]\n        public void Update(int id) { }\n\n        [AcceptVerbs(\"PATCH\", \"HEAD\")]\n        [CLSCompliant(false)]\n        public void Users(double key) { }\n\n        [NonAction]\n        public void NonAction() { }\n\n        [NonAction]\n        [AcceptVerbs(\"ACTION\")]\n        public void NonActionWitHttpMethod() { }\n\n        public void Options() { }\n\n        public void Head() { }\n\n        public void PatchUsers() { }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/Controllers/Apis/EnumParameterOverloadsController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Tracing;\n\nnamespace System.Web.Http\n{\n    public class EnumParameterOverloadsController : ApiController\n    {\n        public IEnumerable<string> Get()\n        {\n            return new string[] { \"get\" };\n        }\n\n        public FilterScope GetWithEnumParameter(FilterScope scope)\n        {\n            return scope;\n        }\n\n        public string GetWithTwoEnumParameters([FromUri]TraceLevel level, TraceKind kind)\n        {\n            return level.ToString() + kind.ToString();\n        }\n\n        public string GetWithNullableEnumParameter(TraceLevel? level)\n        {\n            return level.ToString();\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/Controllers/Apis/HeaderValueProviderFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Controllers;\nusing System.Web.Http.ValueProviders;\nnamespace System.Web.Http\n{\n    public class HeaderValueProviderFactory : ValueProviderFactory\n    {\n        public override IValueProvider GetValueProvider(HttpActionContext actionContext)\n        {\n            return new HeaderValueProvider();\n        }\n    }\n\n    public class HeaderValueProvider : IValueProvider\n    {\n        public bool ContainsPrefix(string prefix)\n        {\n            return false;\n        }\n\n        public ValueProviderResult GetValue(string key)\n        {\n            return null;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/Controllers/Apis/ParameterAttributeController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Http\n{\n    public class ParameterAttributeController : ApiController\n    {\n        public User GetUserByMyId(int myId) { return null; }\n        public User GetUser([FromUri(Name = \"id\")] int myId) { return null; }\n        public List<User> PostUserNameFromUri(int id, [FromUri]string name) { return null; }\n        public List<User> PostUserNameFromBody(int id, [FromBody] string name) { return null; }\n        public void DeleteUserWithNullableIdAndName(int? id, string name) { }\n        public void DeleteUser(string address) { }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/Controllers/Apis/ParameterTestController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http\n{\n    public class ParameterTestController : ApiController\n    {\n        public void Delete(int id)\n        {\n        }\n\n        public string Get(int id = -1)\n        {\n            return String.Format(\"Get({0})\", id);\n        }\n\n        public string POST(string id = null)\n        {\n            return String.Format(\"POST({0})\", id ?? \"null\");\n        }\n\n        public string Put(int id, string value)\n        {\n            return String.Format(\"Put({0}, {1})\", id, value);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/Controllers/Apis/RegularConfigController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Http.Description;\n\nnamespace System.Web.Http\n{\n    public class RegularConfigController : ApiController\n    {\n        public int GetFormattersCount_ControllerConfig()\n        {\n            return Configuration.Formatters.Count;\n        }\n\n        public int GetParameterRulesCount_ControllerConfig()\n        {\n            return Configuration.ParameterBindingRules.Count;\n        }\n\n        public int GetServicesCount_ControllerConfig()\n        {\n            return Configuration.Services.GetService(typeof(IDocumentationProvider)) == null ? 0 : 1;\n        }\n\n        public int GetFormattersCount_RequestConfig()\n        {\n            return Request.GetConfiguration().Formatters.Count;\n        }\n\n        public int GetParameterRulesCount_RequestConfig()\n        {\n            return Request.GetConfiguration().ParameterBindingRules.Count;\n        }\n\n        public int GetServicesCount_RequestConfig()\n        {\n            return Request.GetConfiguration().Services.GetService(typeof(IDocumentationProvider)) == null ? 0 : 1;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/Controllers/Apis/SpecialConfigController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Web.Http.ApiExplorer;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Description;\n\nnamespace System.Web.Http\n{\n    [ControllerConfigAttribute]\n    public class SpecialConfigController : ApiController\n    {\n        public int GetFormattersCount_ControllerConfig()\n        {\n            return Configuration.Formatters.Count;\n        }\n\n        public int GetParameterRulesCount_ControllerConfig()\n        {\n            return Configuration.ParameterBindingRules.Count;\n        }\n\n        public int GetServicesCount_ControllerConfig()\n        {\n            return Configuration.Services.GetService(typeof(IDocumentationProvider)) == null ? 0 : 1;\n        }\n\n        public int GetFormattersCount_RequestConfig()\n        {\n            return Request.GetConfiguration().Formatters.Count;\n        }\n\n        public int GetParameterRulesCount_RequestConfig()\n        {\n            return Request.GetConfiguration().ParameterBindingRules.Count;\n        }\n\n        public int GetServicesCount_RequestConfig()\n        {\n            return Request.GetConfiguration().Services.GetService(typeof(IDocumentationProvider)) == null ? 0 : 1;\n        }\n\n        private class ControllerConfigAttribute : Attribute, IControllerConfiguration\n        {\n            public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)\n            {\n                controllerSettings.Formatters.Clear();\n                controllerSettings.Formatters.Add(new XmlMediaTypeFormatter());\n\n                controllerSettings.ParameterBindingRules.Clear();\n\n                controllerSettings.Services.Replace(typeof(IDocumentationProvider), new AttributeDocumentationProvider());\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/Controllers/Apis/TestController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Http\n{\n    public class TestController : ApiController\n    {\n        public User GetUser(int id) { return null; }\n        public List<User> GetUsers() { return null; }\n\n        public List<User> GetUsersByName(string name) { return null; }\n\n        [AcceptVerbs(\"PATCH\")]\n        public void PutUser(User user) { }\n\n        public User GetUserByNameAndId(string name, int id) { return null; }\n        public User GetUserByNameAndAge(string name, int age) { return null; }\n        public User GetUserByNameAgeAndSsn(string name, int age, int ssn) { return null; }\n        public User GetUserByNameIdAndSsn(string name, int id, int ssn) { return null; }\n        public User GetUserByNameAndSsn(string name, int ssn) { return null; }\n        public User PostUser(User user) { return null; }\n        public User PostUserByNameAndAge(string name, int age) { return null; }\n        public User PostUserByName(string name) { return null; }\n        public User PostUserByNameAndAddress(string name, UserAddress address) { return null; }\n        public User DeleteUserByOptName(string name = null) { return null; }\n        public User DeleteUserByIdAndOptName(int id, string name = \"DefaultName\") { return null; }\n        public User DeleteUserByIdNameAndAge(int id, string name, int age) { return null; }\n        public User DeleteUserById_Email_OptName_OptPhone(int id, string email, string name = null, int phone = 0) { return null; }\n        public User DeleteUserById_Email_Height_OptName_OptPhone(int id, string email, double height, string name = \"DefaultName\", int? phone = null) { return null; }\n        public void Head_Id_OptSize_OptIndex(int id, int size = 10, int index = 0) { }\n        public void Head() { }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/Controllers/Apis/User.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n\nnamespace System.Web.Http\n{\n    public class User\n    {\n        public string FirstName { get; set; }\n        public string LastName { get; set; }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/Controllers/Apis/UserAddress.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n\nnamespace System.Web.Http\n{\n    public class UserAddress\n    {\n        public string Street;\n        public int ZipCode;\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/Controllers/Apis/UsersController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http\n{\n    public class UsersController : ApiController\n    {\n        // Undecorated action, following convention\n        public string GetUser() { return \"GetUser\"; }\n\n        // Undecorated action, not following conventions\n        public string Approve() { return \"Approve\"; }\n\n        // Action decorated with Verb only, following conventions\n        [AcceptVerbs(\"UPDATE\")]\n        public string PutUser() { return \"PutUser\"; }\n\n        // Action decorated with Name = \"\" only, following conventions, not reachable by {action}\n        [ActionName(\"\")]\n        public string PutUserWithEmptyName() { return \"PutUserWithEmptyName\"; }\n\n        // Action decorated with Name = \"\" only, not following conventions, it's a POST by default and not reachable by {action}\n        [ActionName(\"\")]\n        public string DefaultActionWithEmptyActionName() { return \"DefaultActionWithEmptyActionName\"; }\n\n        // Action decorated with Name only, following conventions\n        [ActionName(\"UpdateUser\")]\n        public string PostUser() { return \"PostUser\"; }\n\n        // Action decorated with both, following conventions\n        [AcceptVerbs(\"PATCH\")]\n        [ActionName(\"ReplaceUser\")]\n        public string DeleteUser() { return \"DeleteUser\"; }\n\n        // Action decorated with Verb only, not following conventions\n        [HttpDelete]\n        public string Remove() { return \"Remove\"; }\n\n        // Action decorated with Name only, not following conventions\n        [ActionName(\"Reject\")]\n        public string Deny() { return \"Deny\"; }\n\n        // Action decorated with both, not following conventions\n        [AcceptVerbs(\"OPTIONS\")]\n        [ActionName(\"Help\")]\n        public string Assist() { return \"Assist\"; }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/Controllers/Apis/ValuesController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// This controller is a clone from the standard WebApi project template\n    /// </summary>\n    public class ValuesController : ApiController\n    {\n        // GET api/values\n        public IEnumerable<string> Get()\n        {\n            return new string[] { \"value1\", \"value2\" };\n        }\n\n        // GET api/values/5\n        public string Get(int id)\n        {\n            return \"value\";\n        }\n\n        // POST api/values\n        public void Post(string value = null)\n        {\n        }\n\n        // PUT api/values/5\n        public void Put(int id, string value)\n        {\n        }\n\n        // DELETE api/values/5\n        public void Delete(int id)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/Controllers/ControllerConfigurationTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http\n{\n    public class ControllerConfigurationTest\n    {\n        [Theory]\n        [InlineData(\"SpecialConfig/GetFormattersCount_ControllerConfig\", 1)]\n        [InlineData(\"RegularConfig/GetFormattersCount_ControllerConfig\", 4)]\n        [InlineData(\"SpecialConfig/GetParameterRulesCount_ControllerConfig\", 0)]\n        [InlineData(\"RegularConfig/GetParameterRulesCount_ControllerConfig\", 3)]\n        [InlineData(\"SpecialConfig/GetServicesCount_ControllerConfig\", 1)]\n        [InlineData(\"RegularConfig/GetServicesCount_ControllerConfig\", 0)]\n        [InlineData(\"SpecialConfig/GetFormattersCount_RequestConfig\", 1)]\n        [InlineData(\"RegularConfig/GetFormattersCount_RequestConfig\", 4)]\n        [InlineData(\"SpecialConfig/GetParameterRulesCount_RequestConfig\", 0)]\n        [InlineData(\"RegularConfig/GetParameterRulesCount_RequestConfig\", 3)]\n        [InlineData(\"SpecialConfig/GetServicesCount_RequestConfig\", 1)]\n        [InlineData(\"RegularConfig/GetServicesCount_RequestConfig\", 0)]\n        public async Task ControllerConfigurationSettings_ArePropagatedTo_ControllerAndRequest(string requestUrl, int count)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{action}\");\n            HttpServer server = new HttpServer(config);\n            HttpClient client = new HttpClient(server);\n            HttpResponseMessage response = await client.GetAsync(\"http://localhost/\" + requestUrl);\n\n            Assert.Equal(HttpStatusCode.OK, response.StatusCode);\n            Assert.Equal(count, await response.Content.ReadAsAsync<int>());\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/Controllers/Helpers/ApiControllerHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Routing;\n\nnamespace System.Web.Http\n{\n    public class ApiControllerHelper\n    {\n        public static HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)\n        {\n            ApiControllerActionSelector selector = new ApiControllerActionSelector();\n            HttpActionDescriptor descriptor = selector.SelectAction(controllerContext);\n            return descriptor;\n        }\n\n        public static HttpControllerContext CreateControllerContext(string httpMethod, string requestUrl, string routeUrl, object routeDefault = null)\n        {\n            string baseAddress = \"http://localhost/\";\n            HttpConfiguration config = new HttpConfiguration();\n            HttpRoute route = routeDefault != null ? new HttpRoute(routeUrl, new HttpRouteValueDictionary(routeDefault)) : new HttpRoute(routeUrl);\n            config.Routes.Add(\"test\", route);\n\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethodHelper.GetHttpMethod(httpMethod), baseAddress + requestUrl);\n\n            IHttpRouteData routeData = config.Routes.GetRouteData(request);\n            if (routeData == null)\n            {\n                throw new InvalidOperationException(\"Could not dispatch to controller based on the route.\");\n            }\n\n            RemoveOptionalRoutingParameters(routeData.Values);\n\n            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(config, routeData, request);\n            return controllerContext;\n        }\n\n        private static void RemoveOptionalRoutingParameters(IDictionary<string, object> routeValueDictionary)\n        {\n            // Get all keys for which the corresponding value is 'Optional'.\n            // ToArray() necessary so that we don't manipulate the dictionary while enumerating.\n            string[] matchingKeys = (from entry in routeValueDictionary\n                                     where entry.Value == RouteParameter.Optional\n                                     select entry.Key).ToArray();\n\n            foreach (string key in matchingKeys)\n            {\n                routeValueDictionary.Remove(key);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/Dispatcher/CustomHttpControllerTypeResolverTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Dispatcher\n{\n    public class CustomControllerTypeResolverTest : HttpServerTestBase\n    {\n        internal static readonly string ExpectedContent = \"Hello World!\";\n\n        public CustomControllerTypeResolverTest()\n            : base(\"http://localhost/\")\n        {\n        }\n\n        protected override void ApplyConfiguration(HttpConfiguration configuration)\n        {\n            // Add default route\n            configuration.Routes.MapHttpRoute(\n                name: \"DefaultApi\",\n                routeTemplate: \"api/{controller}/{id}\",\n                defaults: new { id = RouteParameter.Optional }\n            );\n\n            // Set our own assembly resolver where we add the assemblies we need\n            CustomControllerTypeResolver customHttpControllerTypeResolver = new CustomControllerTypeResolver();\n            configuration.Services.Replace(typeof(IHttpControllerTypeResolver), customHttpControllerTypeResolver);\n        }\n\n        [Fact]\n        public async Task CustomControllerTypeResolver_ReplacesControllerTypeAndNameConvention()\n        {\n            // Arrange\n            string address = BaseAddress + \"api/custominternal\";\n\n            // Act\n            HttpResponseMessage response = await Client.GetAsync(address);\n            string content = await response.Content.ReadAsStringAsync();\n\n            // Assert\n            Assert.Equal(HttpStatusCode.OK, response.StatusCode);\n            Assert.Equal(ExpectedContent, content);\n        }\n    }\n\n    internal class CustomControllerTypeResolver : IHttpControllerTypeResolver\n    {\n        public ICollection<Type> GetControllerTypes(IAssembliesResolver assembliesResolver)\n        {\n            return new List<Type> { typeof(CustomInternalController) };\n        }\n    }\n\n    /// <summary>\n    /// Test controller which is declared internal so wouldn't not get picked up by\n    /// <see cref=\"DefaultHttpControllerTypeResolver\"/>.\n    /// </summary>\n    internal class CustomInternalController : ApiController\n    {\n        public HttpResponseMessage Get()\n        {\n            HttpResponseMessage response = Request.CreateResponse();\n            response.Content = new StringContent(CustomControllerTypeResolverTest.ExpectedContent);\n            return response;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ExceptionHandling/DuplicateControllers.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http;\n\nnamespace System.Web.Http\n{\n    public class DuplicateController : ApiController\n    {\n        public string GetAction()\n        {\n            return \"dup\";\n        }\n    }\n}\n\nnamespace System.Web.Http2\n{\n    public class DuplicateController : ApiController\n    {\n        public string GetAction()\n        {\n            return \"dup2\";\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ExceptionHandling/ExceptionController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Filters;\n\nnamespace System.Web.Http\n{\n    public class ExceptionController : ApiController\n    {\n        public static string ResponseExceptionHeaderKey = \"responseExceptionStatusCode\";\n\n        public HttpResponseMessage Unavailable()\n        {\n            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable));\n        }\n\n        public Task<HttpResponseMessage> AsyncUnavailable()\n        {\n            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable));\n        }\n\n        public Task<HttpResponseMessage> AsyncUnavailableDelegate()\n        {\n            return Task.Factory.StartNew<HttpResponseMessage>(() => { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)); });\n        }\n\n        public HttpResponseMessage ArgumentNull()\n        {\n            throw new ArgumentNullException(\"foo\");\n        }\n\n        public Task<HttpResponseMessage> AsyncArgumentNull()\n        {\n            return Task.Factory.StartNew<HttpResponseMessage>(() => { throw new ArgumentNullException(\"foo\"); });\n        }\n\n        [HttpGet]\n        public string GetException()\n        {\n            return \"foo\";\n        }\n\n        [HttpGet]\n        public string GetString()\n        {\n            return \"bar\";\n        }\n\n        public T GenericAction<T>() where T : User\n        {\n            return null;\n        }\n\n        [AuthenticationFilterAuthenticateThrows]\n        public void AuthenticationFilterAuthenticate() { }\n\n        [AuthenticationFilterAuthenticateResultThrows]\n        public void AuthenticationFilterAuthenticateResult() { }\n\n        [AuthenticationFilterChallengeThrows]\n        public void AuthenticationFilterChallenge() { }\n\n        [AuthenticationFilterChallengeResultThrows]\n        public void AuthenticationFilterChallengeResult() { }\n\n        [AuthorizationFilterThrows]\n        public void AuthorizationFilter() { }\n\n        [ActionFilterThrows]\n        public void ActionFilter() { }\n\n        [ExceptionFilterThrows]\n        public void ExceptionFilter() { throw new ArgumentException(\"exception\"); }\n\n        private class AuthenticationFilterAttribute : Attribute, IAuthenticationFilter\n        {\n            public virtual Task AuthenticateAsync(HttpAuthenticationContext context,\n                CancellationToken cancellationToken)\n            {\n                return Task.FromResult<object>(null);\n            }\n\n            public virtual Task ChallengeAsync(HttpAuthenticationChallengeContext context,\n                CancellationToken cancellationToken)\n            {\n                return Task.FromResult<object>(null);\n            }\n\n            public bool AllowMultiple\n            {\n                get { return false; }\n            }\n        }\n\n        private class AuthenticationErrorResult : IHttpActionResult\n        {\n            private readonly HttpActionContext _context;\n\n            public AuthenticationErrorResult(HttpActionContext context)\n            {\n                Contract.Assert(context != null);\n                _context = context;\n            }\n\n            public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)\n            {\n                TryThrowHttpResponseException(_context);\n                throw new ArgumentException(\"authentication\");\n            }\n        }\n\n        private class AuthenticationFilterAuthenticateThrows : AuthenticationFilterAttribute\n        {\n            public override Task AuthenticateAsync(HttpAuthenticationContext context,\n                CancellationToken cancellationToken)\n            {\n                TryThrowHttpResponseException(context.ActionContext);\n                throw new ArgumentException(\"authentication\");\n            }\n        }\n\n        private class AuthenticationFilterAuthenticateResultThrows : AuthenticationFilterAttribute\n        {\n            public override Task AuthenticateAsync(HttpAuthenticationContext context,\n                CancellationToken cancellationToken)\n            {\n                context.ErrorResult = new AuthenticationErrorResult(context.ActionContext);\n                return Task.FromResult<object>(null);\n            }\n        }\n\n        private class AuthenticationFilterChallengeThrows : AuthenticationFilterAttribute\n        {\n            public override Task ChallengeAsync(HttpAuthenticationChallengeContext context,\n                CancellationToken cancellationToken)\n            {\n                TryThrowHttpResponseException(context.ActionContext);\n                throw new ArgumentException(\"authentication\");\n            }\n        }\n\n        private class AuthenticationFilterChallengeResultThrows : AuthenticationFilterAttribute\n        {\n            public override Task ChallengeAsync(HttpAuthenticationChallengeContext context,\n                CancellationToken cancellationToken)\n            {\n                context.Result = new AuthenticationErrorResult(context.ActionContext);\n                return Task.FromResult<object>(null);\n            }\n        }\n\n        private class AuthorizationFilterThrows : AuthorizeAttribute\n        {\n            public override void OnAuthorization(HttpActionContext actionContext)\n            {\n                TryThrowHttpResponseException(actionContext);\n                throw new ArgumentException(\"authorization\");\n            }\n        }\n\n        private class ActionFilterThrows : ActionFilterAttribute\n        {\n            public override void OnActionExecuting(HttpActionContext actionContext)\n            {\n                TryThrowHttpResponseException(actionContext);\n                throw new ArgumentException(\"action\");\n            }\n        }\n\n        private class ExceptionFilterThrows : ExceptionFilterAttribute\n        {\n            public override void OnException(HttpActionExecutedContext actionExecutedContext)\n            {\n                TryThrowHttpResponseException(actionExecutedContext.ActionContext);\n                throw actionExecutedContext.Exception;\n            }\n        }\n\n        private static void TryThrowHttpResponseException(HttpActionContext actionContext)\n        {\n            IEnumerable<string> values;\n            if (actionContext.ControllerContext.Request.Headers.TryGetValues(ResponseExceptionHeaderKey, out values))\n            {\n                string statusString = values.First() as string;\n                if (!String.IsNullOrEmpty(statusString))\n                {\n                    HttpStatusCode status = (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), statusString);\n                    throw new HttpResponseException(actionContext.Request.CreateResponse(status, \"HttpResponseExceptionMessage\"));\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ExceptionHandling/ExceptionHandlingTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading.Tasks;\nusing System.Web.Http.Properties;\nusing Microsoft.TestCommon;\nusing Newtonsoft.Json.Linq;\n\nnamespace System.Web.Http\n{\n    public class ExceptionHandlingTest\n    {\n        [Theory]\n        [InlineData(\"Unavailable\")]\n        [InlineData(\"AsyncUnavailable\")]\n        [InlineData(\"AsyncUnavailableDelegate\")]\n        public async Task ThrowingHttpResponseException_FromAction_GetsReturnedToClient(string actionName)\n        {\n            string controllerName = \"Exception\";\n            string requestUrl = String.Format(\"{0}/{1}/{2}\", ScenarioHelper.BaseAddress, controllerName, actionName);\n\n            await ScenarioHelper.RunTestAsync(\n                controllerName,\n                \"/{action}\",\n                new HttpRequestMessage(HttpMethod.Post, requestUrl),\n                (response) =>\n                {\n                    Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode);\n                    return Task.FromResult(0);\n                }\n            );\n        }\n\n        [Theory]\n        [InlineData(\"ArgumentNull\")]\n        [InlineData(\"AsyncArgumentNull\")]\n        public async Task ThrowingArgumentNullException_FromAction_GetsReturnedToClient(string actionName)\n        {\n            string controllerName = \"Exception\";\n            string requestUrl = String.Format(\"{0}/{1}/{2}\", ScenarioHelper.BaseAddress, controllerName, actionName);\n\n            await ScenarioHelper.RunTestAsync(\n                controllerName,\n                \"/{action}\",\n                new HttpRequestMessage(HttpMethod.Post, requestUrl),\n                async (response) =>\n                {\n                    Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n                    HttpError exception = await response.Content.ReadAsAsync<HttpError>();\n                    Assert.Equal(typeof(ArgumentNullException).FullName, exception[\"ExceptionType\"].ToString());\n                }\n            );\n        }\n\n        [Theory]\n        [InlineData(\"ArgumentNull\")]\n        [InlineData(\"AsyncArgumentNull\")]\n        public async Task ThrowingArgumentNullException_FromAction_GetsReturnedToClientParsedAsJson(string actionName)\n        {\n            string controllerName = \"Exception\";\n            string requestUrl = String.Format(\"{0}/{1}/{2}\", ScenarioHelper.BaseAddress, controllerName, actionName);\n\n            await ScenarioHelper.RunTestAsync(\n                controllerName,\n                \"/{action}\",\n                new HttpRequestMessage(HttpMethod.Post, requestUrl),\n                async (response) =>\n                {\n                    Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n                    dynamic json = JToken.Parse(await response.Content.ReadAsStringAsync());\n                    string result = json.ExceptionType;\n                    Assert.Equal(typeof(ArgumentNullException).FullName, result);\n                }\n            );\n        }\n\n        [Theory]\n        [InlineData(\"AuthenticationFilterAuthenticate\")]\n        [InlineData(\"AuthenticationFilterAuthenticateResult\")]\n        [InlineData(\"AuthenticationFilterChallenge\")]\n        [InlineData(\"AuthenticationFilterChallengeResult\")]\n        [InlineData(\"AuthorizationFilter\")]\n        [InlineData(\"ActionFilter\")]\n        [InlineData(\"ExceptionFilter\")]\n        public async Task ThrowingArgumentException_FromFilter_GetsReturnedToClient(string actionName)\n        {\n            string controllerName = \"Exception\";\n            string requestUrl = String.Format(\"{0}/{1}/{2}\", ScenarioHelper.BaseAddress, controllerName, actionName);\n\n            await ScenarioHelper.RunTestAsync(\n                controllerName,\n                \"/{action}\",\n                new HttpRequestMessage(HttpMethod.Post, requestUrl),\n                async (response) =>\n                {\n                    Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n                    HttpError exception = await response.Content.ReadAsAsync<HttpError>();\n                    Assert.Equal(typeof(ArgumentException).FullName, exception[\"ExceptionType\"].ToString());\n                }\n            );\n        }\n\n        [Theory]\n        [InlineData(\"AuthenticationFilterAuthenticate\", HttpStatusCode.Ambiguous)]\n        [InlineData(\"AuthenticationFilterAuthenticateResult\", HttpStatusCode.BadGateway)]\n        [InlineData(\"AuthenticationFilterChallenge\", HttpStatusCode.BadRequest)]\n        [InlineData(\"AuthenticationFilterChallengeResult\", HttpStatusCode.Conflict)]\n        [InlineData(\"AuthorizationFilter\", HttpStatusCode.Forbidden)]\n        [InlineData(\"ActionFilter\", HttpStatusCode.NotAcceptable)]\n        [InlineData(\"ExceptionFilter\", HttpStatusCode.NotImplemented)]\n        public async Task ThrowingHttpResponseException_FromFilter_GetsReturnedToClient(string actionName, HttpStatusCode responseExceptionStatusCode)\n        {\n            string controllerName = \"Exception\";\n            string requestUrl = String.Format(\"{0}/{1}/{2}\", ScenarioHelper.BaseAddress, controllerName, actionName);\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUrl);\n            request.Headers.Add(ExceptionController.ResponseExceptionHeaderKey, responseExceptionStatusCode.ToString());\n\n            await ScenarioHelper.RunTestAsync(\n                controllerName,\n                \"/{action}\",\n                request,\n                async (response) =>\n                {\n                    Assert.Equal(responseExceptionStatusCode, response.StatusCode);\n                    Assert.Equal(\"HttpResponseExceptionMessage\", await response.Content.ReadAsAsync<string>());\n                }\n            );\n        }\n\n        // TODO: add tests that throws from custom model binders\n\n        [Fact]\n        public async Task Service_ReturnsNotFound_WhenControllerNameDoesNotExist()\n        {\n            string controllerName = \"randomControllerThatCannotBeFound\";\n            string requestUrl = String.Format(\"{0}/{1}\", ScenarioHelper.BaseAddress, controllerName);\n\n            await ScenarioHelper.RunTestAsync(\n                controllerName,\n                \"\",\n                new HttpRequestMessage(HttpMethod.Post, requestUrl),\n                async (response) =>\n                {\n                    Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);\n                    var result = await response.Content.ReadAsAsync<HttpError>();\n                    Assert.Equal(\n                        String.Format(SRResources.DefaultControllerFactory_ControllerNameNotFound, controllerName),\n                        result[\"MessageDetail\"]);\n                }\n            );\n        }\n\n        [Fact]\n        public async Task Service_ReturnsNotFound_WhenActionNameDoesNotExist()\n        {\n            string controllerName = \"Exception\";\n            string actionName = \"actionNotFound\";\n            string requestUrl = String.Format(\"{0}/{1}/{2}\", ScenarioHelper.BaseAddress, controllerName, actionName);\n\n            await ScenarioHelper.RunTestAsync(\n                controllerName,\n                \"/{action}\",\n                new HttpRequestMessage(HttpMethod.Post, requestUrl),\n                async (response) =>\n                {\n                    Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);\n                    var result = await response.Content.ReadAsAsync<HttpError>();\n                    Assert.Equal(\n                        String.Format(SRResources.ApiControllerActionSelector_ActionNameNotFound, controllerName, actionName),\n                        result[\"MessageDetail\"]);\n                }\n            );\n        }\n\n        [Fact]\n        public async Task Service_ReturnsMethodNotAllowed_WhenActionsDoesNotSupportTheRequestHttpMethod()\n        {\n            string controllerName = \"Exception\";\n            string actionName = \"GetString\";\n            HttpMethod requestMethod = HttpMethod.Post;\n            string requestUrl = String.Format(\"{0}/{1}/{2}\", ScenarioHelper.BaseAddress, controllerName, actionName);\n            await ScenarioHelper.RunTestAsync(\n                controllerName,\n                \"/{action}\",\n                new HttpRequestMessage(requestMethod, requestUrl),\n                async (response) =>\n                {\n                    Assert.Equal(HttpStatusCode.MethodNotAllowed, response.StatusCode);\n                    var result = await response.Content.ReadAsAsync<HttpError>();\n                    Assert.Equal(\n                        String.Format(SRResources.ApiControllerActionSelector_HttpMethodNotSupported, requestMethod.Method),\n                        result.Message);\n                }\n            );\n        }\n\n        [Fact]\n        public async Task Service_ReturnsInternalServerError_WhenMultipleActionsAreFound()\n        {\n            string controllerName = \"Exception\";\n            string requestUrl = String.Format(\"{0}/{1}\", ScenarioHelper.BaseAddress, controllerName);\n\n            await ScenarioHelper.RunTestAsync(\n                controllerName,\n                \"\",\n                new HttpRequestMessage(HttpMethod.Post, requestUrl),\n                async (response) =>\n                {\n                    Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n                    var result = await response.Content.ReadAsAsync<HttpError>();\n                    Assert.Contains(\n                        String.Format(SRResources.ApiControllerActionSelector_AmbiguousMatch, String.Empty),\n                        result[\"ExceptionMessage\"] as string);\n                }\n            );\n        }\n\n        [Fact]\n        public async Task Service_ReturnsInternalServerError_WhenMultipleControllersAreFound()\n        {\n            string controllerName = \"Duplicate\";\n            string requestUrl = String.Format(\"{0}/{1}\", ScenarioHelper.BaseAddress, controllerName);\n\n            await ScenarioHelper.RunTestAsync(\n                controllerName,\n                \"\",\n                new HttpRequestMessage(HttpMethod.Post, requestUrl),\n                async (response) =>\n                {\n                    Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n                    var result = await response.Content.ReadAsAsync<HttpError>();\n                    Assert.Contains(\n                        String.Format(SRResources.DefaultControllerFactory_ControllerNameAmbiguous_WithRouteTemplate, controllerName, \"{controller}\", String.Empty, Environment.NewLine),\n                        result[\"ExceptionMessage\"] as string);\n                }\n            );\n        }\n\n        [Fact]\n        public async Task GenericMethod_Throws_InvalidOperationException()\n        {\n            HttpConfiguration config = new HttpConfiguration() { IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always };\n            config.Routes.MapHttpRoute(\"Default\", \"Exception/{action}\", new { controller = \"Exception\" });\n            HttpServer server = new HttpServer(config);\n            HttpClient client = new HttpClient(server);\n\n            // Ensure that the behavior is repeatable and other action is still callable after the error\n            for (int i = 0; i < 10; i++)\n            {\n                // Make sure other action can be called\n                HttpResponseMessage response = await client.GetAsync(\"http://localhost/Exception/GetString\");\n                Assert.True(response.IsSuccessStatusCode,\n                    String.Format(\"Successful status code was expected but got '{0}' instead. Error: {1}\", response.StatusCode, await response.Content.ReadAsStringAsync()));\n\n                // Make a request to generic method and verify the exception\n                response = await client.PostAsync(\"http://localhost/Exception/GenericAction\", null);\n                Type controllerType = typeof(ExceptionController);\n                HttpError exception = await response.Content.ReadAsAsync<HttpError>();\n                Assert.Equal(typeof(InvalidOperationException).FullName, exception[\"ExceptionType\"]);\n                Assert.Equal(\n                    String.Format(\n                        SRResources.ReflectedHttpActionDescriptor_CannotCallOpenGenericMethods,\n                        controllerType.GetMethod(\"GenericAction\"),\n                        controllerType.FullName),\n                    exception[\"ExceptionMessage\"]);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ExceptionHandling/HttpResponseExceptionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Filters;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    public class HttpResponseExceptionTest\n    {\n        [Theory]\n        [InlineData(\"DoNotThrow\")]\n        [InlineData(\"ActionMethod\")]\n        // TODO : 332683 - HttpResponseExceptions in message handlers\n        //[InlineData(\"RequestMessageHandler\")]\n        //[InlineData(\"ResponseMessageHandler\")]\n        [InlineData(\"RequestAuthorization\")]\n        [InlineData(\"AuthenticationAuthenticate\")]\n        [InlineData(\"AuthenticationChallenge\")]\n        [InlineData(\"BeforeActionExecuted\")]\n        [InlineData(\"AfterActionExecuted\")]\n        [InlineData(\"ContentNegotiatorNegotiate\")]\n        [InlineData(\"ActionMethodAndExceptionFilter\")]\n        [InlineData(\"MediaTypeFormatterReadFromStreamAsync\")]\n        public async Task HttpResponseExceptionWithExplicitStatusCode(string throwAt)\n        {\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.RequestUri = new Uri(ScenarioHelper.BaseAddress + \"/ExceptionTests/ReturnString\");\n            request.Method = HttpMethod.Post;\n            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(\"application/json\"));\n            request.Content = new StringContent(\"\\\"\" + throwAt + \"\\\"\", Encoding.UTF8, \"application/json\");\n\n            await ScenarioHelper.RunTestAsync(\n                \"ExceptionTests\",\n                \"/{action}\",\n                request,\n                async response =>\n                {\n                    Assert.NotNull(response.Content);\n                    Assert.NotNull(response.Content.Headers.ContentType);\n                    Assert.Equal(\"application/json\", response.Content.Headers.ContentType.MediaType);\n\n                    if (throwAt == \"DoNotThrow\")\n                    {\n                        Assert.Equal(HttpStatusCode.OK, response.StatusCode);\n                        Assert.Equal(\"Hello World!\",\n                            await response.Content.ReadAsAsync<string>(new List<MediaTypeFormatter>() { new JsonMediaTypeFormatter() }));\n                    }\n                    else\n                    {\n                        Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);\n                        Assert.Equal(String.Format(\"Error at {0}\", throwAt),\n                            await response.Content.ReadAsAsync<string>(new List<MediaTypeFormatter>() { new JsonMediaTypeFormatter() }));\n                    }\n                },\n                config =>\n                {\n                    config.Services.Replace(typeof(IContentNegotiator), new CustomContentNegotiator(throwAt));\n\n                    config.MessageHandlers.Add(new CustomMessageHandler(throwAt));\n                    config.Filters.Add(new CustomActionFilterAttribute(throwAt));\n                    config.Filters.Add(new CustomAuthorizationFilterAttribute(throwAt));\n                    config.Filters.Add(new CustomAuthenticationFilter(throwAt));\n                    config.Filters.Add(new CustomExceptionFilterAttribute(throwAt));\n                    config.Formatters.Clear();\n                    config.Formatters.Add(new CustomJsonMediaTypeFormatter(throwAt));\n                }\n            );\n        }\n    }\n\n    public class CustomMessageHandler : DelegatingHandler\n    {\n        private string _throwAt;\n\n        public CustomMessageHandler(string throwAt)\n        {\n            _throwAt = throwAt;\n        }\n\n        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n        {\n            ExceptionTestsUtility.CheckForThrow(_throwAt, \"RequestMessageHandler\");\n\n            HttpResponseMessage response = await base.SendAsync(request, cancellationToken);\n            ExceptionTestsUtility.CheckForThrow(_throwAt, \"ResponseMessageHandler\");\n\n            return response;\n        }\n    }\n\n    public class ExceptionTestsController : ApiController\n    {\n        [HttpPost]\n        public string ReturnString([FromBody] string throwAt)\n        {\n            string message = \"Hello World!\";\n\n            // check if the test wants to throw from here\n            ExceptionTestsUtility.CheckForThrow(throwAt, \"ActionMethod\");\n\n            // NOTE: this indicates that we want to throw from here & after this gets intercepted\n            // by the ExceptionFilter, we want to throw from there too\n            ExceptionTestsUtility.CheckForThrow(throwAt, \"ActionMethodAndExceptionFilter\");\n\n            return message;\n        }\n    }\n\n    public class CustomAuthenticationFilter : IAuthenticationFilter\n    {\n        private string _throwAt;\n\n        public CustomAuthenticationFilter(string throwAt)\n        {\n            _throwAt = throwAt;\n        }\n\n        public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)\n        {\n            ExceptionTestsUtility.CheckForThrow(_throwAt, \"AuthenticationAuthenticate\");\n            return Task.FromResult<object>(null);\n        }\n\n        public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)\n        {\n            ExceptionTestsUtility.CheckForThrow(_throwAt, \"AuthenticationChallenge\");\n            return Task.FromResult<object>(null);\n        }\n\n        public bool AllowMultiple\n        {\n            get { return false; }\n        }\n    }\n\n    public class CustomAuthorizationFilterAttribute : AuthorizationFilterAttribute\n    {\n        private string _throwAt;\n\n        public CustomAuthorizationFilterAttribute(string throwAt)\n        {\n            _throwAt = throwAt;\n        }\n\n        public override void OnAuthorization(HttpActionContext context)\n        {\n            ExceptionTestsUtility.CheckForThrow(_throwAt, \"RequestAuthorization\");\n        }\n    }\n\n    public class CustomActionFilterAttribute : ActionFilterAttribute\n    {\n        private string _throwAt;\n\n        public CustomActionFilterAttribute(string throwAt)\n        {\n            _throwAt = throwAt;\n        }\n\n        public override void OnActionExecuting(HttpActionContext context)\n        {\n            ExceptionTestsUtility.CheckForThrow(_throwAt, \"BeforeActionExecuted\");\n        }\n\n        public override void OnActionExecuted(HttpActionExecutedContext context)\n        {\n            ExceptionTestsUtility.CheckForThrow(_throwAt, \"AfterActionExecuted\");\n        }\n    }\n\n    public class CustomExceptionFilterAttribute : ExceptionFilterAttribute\n    {\n        private string _throwAt;\n\n        public CustomExceptionFilterAttribute(string throwAt)\n        {\n            _throwAt = throwAt;\n        }\n\n        public override void OnException(HttpActionExecutedContext context)\n        {\n            ExceptionTestsUtility.CheckForThrow(_throwAt, \"ActionMethodAndExceptionFilter\");\n        }\n    }\n\n    public class CustomContentNegotiator : System.Net.Http.Formatting.DefaultContentNegotiator\n    {\n        private string _throwAt;\n\n        public CustomContentNegotiator(string throwAt)\n        {\n            _throwAt = throwAt;\n        }\n\n        public override ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)\n        {\n            ExceptionTestsUtility.CheckForThrow(_throwAt, \"ContentNegotiatorNegotiate\");\n\n            return base.Negotiate(type, request, formatters);\n        }\n    }\n\n    public class CustomJsonMediaTypeFormatter : JsonMediaTypeFormatter\n    {\n        private string _throwAt;\n\n        public CustomJsonMediaTypeFormatter(string throwAt)\n        {\n            _throwAt = throwAt;\n        }\n\n        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)\n        {\n            ExceptionTestsUtility.CheckForThrow(_throwAt, \"MediaTypeFormatterReadFromStreamAsync\");\n\n            return base.ReadFromStreamAsync(type, readStream, content, formatterLogger);\n        }\n\n        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)\n        {\n            ExceptionTestsUtility.CheckForThrow(_throwAt, \"MediaTypeFormatterWriteToStreamAsync\");\n\n            return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);\n        }\n    }\n\n    public static class ExceptionTestsUtility\n    {\n        public static void CheckForThrow(string throwAt, string stage)\n        {\n            if (throwAt == stage)\n            {\n                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.NotFound)\n                {\n                    Content = new ObjectContent<string>(String.Format(\"Error at {0}\", stage), new JsonMediaTypeFormatter())\n                };\n\n                throw new HttpResponseException(response);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ExceptionHandling/IncludeErrorDetailTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading.Tasks;\nusing System.Web.Http.Hosting;\nusing Microsoft.TestCommon;\nusing Newtonsoft.Json.Linq;\n\nnamespace System.Web.Http\n{\n    public class IncludeErrorDetailTest\n    {\n        public static TheoryDataSet ThrowingOnActionIncludesErrorDetailData\n        {\n            get\n            {\n                return new TheoryDataSet<bool, IncludeErrorDetailPolicy, bool?, bool>()\n                {\n                    // isLocal, includeErrorDetail, customErrors, expectErrorDetail\n                    { true, IncludeErrorDetailPolicy.LocalOnly, true, true },\n                    { false, IncludeErrorDetailPolicy.LocalOnly, true, false },\n                    { true, IncludeErrorDetailPolicy.LocalOnly, false, true },\n                    { false, IncludeErrorDetailPolicy.LocalOnly, false, false },\n                    { true, IncludeErrorDetailPolicy.LocalOnly, null, true },\n                    { false, IncludeErrorDetailPolicy.LocalOnly, null, false },\n\n                    { true, IncludeErrorDetailPolicy.Always, true, true },\n                    { false, IncludeErrorDetailPolicy.Always, true, true },\n                    { true, IncludeErrorDetailPolicy.Always, false, true },\n                    { false, IncludeErrorDetailPolicy.Always, false, true },\n                    { true, IncludeErrorDetailPolicy.Always, null, true },\n                    { false, IncludeErrorDetailPolicy.Always, null, true },\n\n                    { true, IncludeErrorDetailPolicy.Never, true, false },\n                    { false, IncludeErrorDetailPolicy.Never, true, false },\n                    { true, IncludeErrorDetailPolicy.Never, false, false },\n                    { false, IncludeErrorDetailPolicy.Never, false, false },\n                    { true, IncludeErrorDetailPolicy.Never, null, false },\n                    { false, IncludeErrorDetailPolicy.Never, null, false },\n\n                    { true, IncludeErrorDetailPolicy.Default, true, false },\n                    { false, IncludeErrorDetailPolicy.Default, true, false },\n                    { true, IncludeErrorDetailPolicy.Default, false, true },\n                    { false, IncludeErrorDetailPolicy.Default, false, true },\n                    { true, IncludeErrorDetailPolicy.Default, null, true },\n                    { false, IncludeErrorDetailPolicy.Default, null, false }\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"ThrowingOnActionIncludesErrorDetailData\")]\n        public async Task ThrowingOnActionIncludesErrorDetail(bool isLocal, IncludeErrorDetailPolicy includeErrorDetail, bool? customErrors, bool expectErrorDetail)\n        {\n            string controllerName = \"Exception\";\n            string requestUrl = String.Format(\"{0}/{1}/{2}\", \"http://www.foo.com\", controllerName, \"ArgumentNull\");\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUrl);\n            request.Properties[HttpPropertyKeys.IsLocalKey] = new Lazy<bool>(() => isLocal);\n            if (customErrors != null)\n            {\n                request.Properties[HttpPropertyKeys.IncludeErrorDetailKey] = new Lazy<bool>(() => !(bool)customErrors);\n            }\n\n            await ScenarioHelper.RunTestAsync(\n                controllerName,\n                \"/{action}\",\n                request,\n                async (response) =>\n                {\n                    if (expectErrorDetail)\n                    {\n                        await AssertResponseIncludesErrorDetailAsync(response);\n                    }\n                    else\n                    {\n                        await AssertResponseDoesNotIncludeErrorDetailAsync(response);\n                    }\n                },\n                (config) =>\n                {\n                    config.IncludeErrorDetailPolicy = includeErrorDetail;\n                }\n            );\n        }\n\n        private async Task AssertResponseIncludesErrorDetailAsync(HttpResponseMessage response)\n        {\n            Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n            dynamic json = JToken.Parse(await response.Content.ReadAsStringAsync());\n            string result = json.ExceptionType;\n            Assert.Equal(typeof(ArgumentNullException).FullName, result);\n        }\n\n        private async Task AssertResponseDoesNotIncludeErrorDetailAsync(HttpResponseMessage response)\n        {\n            Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n            JObject json = JToken.Parse(await response.Content.ReadAsStringAsync()) as JObject;\n            Assert.Single(json);\n            string errorMessage = ((JValue)json[\"Message\"]).ToString();\n            Assert.Equal(\"An error has occurred.\", errorMessage);\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ModelBinding/BodyBindingTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Web.Http.Properties;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ModelBinding\n{\n    /// <summary>\n    /// End to end functional tests for model binding via request body\n    /// </summary>\n    public class BodyBindingTests : ModelBindingTests\n    {\n        [Fact]\n        [ReplaceCulture]\n        public async Task Body_Bad_Input_Receives_Validation_Error()\n        {\n            // Arrange\n            string formUrlEncodedString = \"Id=101&Name=testFirstNameTooLong\";\n            StringContent stringContent = new StringContent(formUrlEncodedString, Encoding.UTF8, \"application/x-www-form-urlencoded\");\n\n            HttpRequestMessage request = new HttpRequestMessage()\n            {\n                RequestUri = new Uri(BaseAddress + \"ModelBinding/PostComplexWithValidation\"),\n                Method = HttpMethod.Post,\n                Content = stringContent,\n            };\n\n            // Act\n            HttpResponseMessage response = await Client.SendAsync(request);\n\n            // Assert\n            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);\n            Assert.Equal(\"Failed to bind customer.RequiredValue. The errors are:\\nErrorMessage: The RequiredValue property is required.\\nFailed to bind customer.Name. The errors are:\\nErrorMessage: The field Name must be a string with a maximum length of 6.\\n\",\n                await response.Content.ReadAsStringAsync());\n        }\n\n        [Fact]\n        public async Task Body_Good_Input_Succeed()\n        {\n            // Arrange\n            string formUrlEncodedString = \"Id=111&Name=John&RequiredValue=9\";\n            StringContent stringContent = new StringContent(formUrlEncodedString, Encoding.UTF8, \"application/x-www-form-urlencoded\");\n\n            HttpRequestMessage request = new HttpRequestMessage()\n            {\n                RequestUri = new Uri(BaseAddress + \"ModelBinding/PostComplexWithValidation\"),\n                Method = HttpMethod.Post,\n                Content = stringContent,\n            };\n\n            // Act\n            HttpResponseMessage response = await Client.SendAsync(request);\n\n            // Assert\n            Assert.Equal(HttpStatusCode.OK, response.StatusCode);\n            Assert.Equal(\"111\", await response.Content.ReadAsStringAsync());\n        }\n\n        [Theory]\n        [InlineData(\"PostWithOptionalBodyParameter\")]\n        [InlineData(\"PostWithOptionalBodyParameterAndUriParameter?id=3\")]\n        public async Task Body_OptionalParameter_Throws(string actionName)\n        {\n            // Arrange\n            StringContent stringContent = new StringContent(@\"\"\"string value\"\"\", Encoding.UTF8, \"application/json\");\n            HttpRequestMessage request = new HttpRequestMessage()\n            {\n                RequestUri = new Uri(BaseAddress + \"ModelBinding/\" + actionName),\n                Method = HttpMethod.Post,\n                Content = stringContent,\n            };\n\n            // Act\n            HttpResponseMessage response = await Client.SendAsync(request);\n            HttpError error = await response.Content.ReadAsAsync<HttpError>();\n\n            // Assert\n            Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n            Assert.Equal(String.Format(SRResources.OptionalBodyParameterNotSupported, \"value\", typeof(FormatterParameterBinding).Name), error[\"ExceptionMessage\"]);\n        }\n\n        [Theory]\n        [InlineData(\"application/json\")]\n        [InlineData(null)]\n        public async Task Body_Binds_EmptyContentWithOrWithoutContentTypeHeader(string mediaType)\n        {\n            // Arrange\n            StringContent stringContent = new StringContent(String.Empty);\n            stringContent.Headers.ContentType = mediaType != null ? new MediaTypeHeaderValue(mediaType) : null;\n\n            HttpRequestMessage request = new HttpRequestMessage()\n            {\n                RequestUri = new Uri(BaseAddress + \"ModelBinding/PostComplexTypeFromBody\"),\n                Method = HttpMethod.Post,\n                Content = stringContent,\n            };\n\n            // Act\n            HttpResponseMessage response = await Client.SendAsync(request);\n\n            // Assert\n            Assert.Equal(HttpStatusCode.OK, response.StatusCode);\n            ModelBindOrder actualItem = await response.Content.ReadAsAsync<ModelBindOrder>();\n            Assert.Null(actualItem);\n        }\n\n        [Theory]\n        [InlineData(\"PostComplexType\", \"application/json\")]\n        [InlineData(\"PostComplexType\", \"application/xml\")]\n        [InlineData(\"PostComplexTypeFromBody\", \"application/json\")]\n        [InlineData(\"PostComplexTypeFromBody\", \"application/xml\")]\n        public async Task Body_Binds_ComplexType_Type_Key_Value_Read(string action, string mediaType)\n        {\n            // Arrange\n            ModelBindOrder expectedItem = new ModelBindOrder()\n            {\n                ItemName = \"Bike\",\n                Quantity = 1,\n                Customer = new ModelBindCustomer { Name = \"Fred\" }\n            };\n            var formatter = new MediaTypeFormatterCollection().FindWriter(typeof(ModelBindOrder), new MediaTypeHeaderValue(mediaType));\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                Content = new ObjectContent<ModelBindOrder>(expectedItem, formatter),\n                RequestUri = new Uri(BaseAddress + String.Format(\"ModelBinding/{0}\", action)),\n                Method = HttpMethod.Post,\n            };\n\n            // Act\n            HttpResponseMessage response = await Client.SendAsync(request);\n\n            // Assert\n            ModelBindOrder actualItem = await response.Content.ReadAsAsync<ModelBindOrder>();\n            Assert.Equal(expectedItem, actualItem, new ModelBindOrderEqualityComparer());\n        }\n\n        [Theory]\n        [InlineData(\"PostComplexType\", \"application/json\")]\n        [InlineData(\"PostComplexType\", \"application/xml\")]\n        [InlineData(\"PostComplexTypeFromBody\", \"application/json\")]\n        [InlineData(\"PostComplexTypeFromBody\", \"application/xml\")]\n        public async Task Body_Binds_ComplexType_Type_Whole_Body_Read(string action, string mediaType)\n        {\n            // Arrange\n            ModelBindOrder expectedItem = new ModelBindOrder()\n            {\n                ItemName = \"Bike\",\n                Quantity = 1,\n                Customer = new ModelBindCustomer { Name = \"Fred\" }\n            };\n            var formatter = new MediaTypeFormatterCollection().FindWriter(typeof(ModelBindOrder), new MediaTypeHeaderValue(mediaType));\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                Content = new ObjectContent<ModelBindOrder>(expectedItem, formatter),\n                RequestUri = new Uri(BaseAddress + String.Format(\"ModelBinding/{0}\", action)),\n                Method = HttpMethod.Post,\n            };\n\n            // Act\n            HttpResponseMessage response = await Client.SendAsync(request);\n\n            // Assert\n            ModelBindOrder actualItem = await response.Content.ReadAsAsync<ModelBindOrder>();\n            Assert.Equal(expectedItem, actualItem, new ModelBindOrderEqualityComparer());\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ModelBinding/CustomBindingTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ModelBinding\n{\n    /// <summary>\n    /// End to end functional tests for model binding via custom providers\n    /// </summary>\n    public class CustomBindingTests : ModelBindingTests\n    {\n        [Fact]\n        public async Task Custom_ValueProvider_Binds_Simple_Types_Get()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage()\n            {\n                RequestUri = new Uri(BaseAddress + String.Format(\"ModelBinding/{0}\", \"GetIntCustom\")),\n                Method = HttpMethod.Get\n            };\n\n            request.Headers.Add(\"value\", \"5\");\n\n            // Act\n            HttpResponseMessage response = await Client.SendAsync(request);\n\n            // Assert\n            string responseString = await response.Content.ReadAsStringAsync();\n            Assert.Equal(\"5\", responseString);\n        }\n\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ModelBinding/DefaultActionValueBinderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Globalization;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Routing;\nusing System.Web.Http.ValueProviders;\nusing Microsoft.TestCommon;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\n\nnamespace System.Web.Http.ModelBinding\n{\n    public class DefaultActionValueBinderTest\n    {\n        [Fact]\n        public async Task BindValuesAsync_Uses_DefaultValues()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"Get\") });\n            CancellationToken cancellationToken = new CancellationToken();\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(context, cancellationToken);\n\n            // Assert\n            Dictionary<string, object> expectedResult = new Dictionary<string, object>();\n            expectedResult[\"id\"] = 0;\n            expectedResult[\"firstName\"] = \"DefaultFirstName\";\n            expectedResult[\"lastName\"] = \"DefaultLastName\";\n            Assert.Equal(expectedResult, context.ActionArguments, new DictionaryEqualityComparer());\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_WithObjectContentInRequest_Works()\n        {\n            // Arrange\n            ActionValueItem cust = new ActionValueItem() { FirstName = \"FirstName\", LastName = \"LastName\", Id = 1 };\n            HttpActionContext context = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"PostComplexType\") });\n            context.ControllerContext.Request = new HttpRequestMessage\n            {\n                Content = new ObjectContent<ActionValueItem>(cust, new JsonMediaTypeFormatter())\n            };\n            CancellationToken cancellationToken = new CancellationToken();\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(context, cancellationToken);\n\n            // Assert\n            var result = context.ActionArguments;\n            Assert.Single(result);\n            var item = Assert.IsType<ActionValueItem>(result[\"item\"]);\n            Assert.Equal(cust.FirstName, item.FirstName);\n            Assert.Equal(cust.LastName, item.LastName);\n            Assert.Equal(cust.Id, item.Id);\n        }\n\n        #region Query Strings\n\n        [Fact]\n        public async Task BindValuesAsync_ConvertEmptyString()\n        {\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(new HttpRequestMessage()\n                {\n                    Method = HttpMethod.Get,\n                    RequestUri = new Uri(\"http://localhost?A1=&A2=&A3=&A4=\")\n                }),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"GetTestEmptyString\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(actionContext, CancellationToken.None);\n\n            // Assert\n            ConvertEmptyStringContainer arg = (ConvertEmptyStringContainer)actionContext.ActionArguments[\"x\"];\n\n            Assert.NotNull(arg);\n            Assert.Equal(String.Empty, arg.A1);\n            Assert.Null(arg.A2);\n            Assert.Null(arg.A3);\n            Assert.Null(arg.A4);\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_Query_String_Values_To_Simple_Types()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(new HttpRequestMessage()\n                {\n                    Method = HttpMethod.Get,\n                    RequestUri = new Uri(\"http://localhost?id=5&firstName=queryFirstName&lastName=queryLastName\")\n                }),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"Get\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(actionContext, cancellationToken);\n\n            // Assert\n            Dictionary<string, object> expectedResult = new Dictionary<string, object>();\n            expectedResult[\"id\"] = 5;\n            expectedResult[\"firstName\"] = \"queryFirstName\";\n            expectedResult[\"lastName\"] = \"queryLastName\";\n            Assert.Equal(expectedResult, actionContext.ActionArguments, new DictionaryEqualityComparer());\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_Query_String_Values_To_Simple_Types_With_FromUriAttribute()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(new HttpRequestMessage()\n                {\n                    Method = HttpMethod.Get,\n                    RequestUri = new Uri(\"http://localhost?id=5&firstName=queryFirstName&lastName=queryLastName\")\n                }),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"GetFromUri\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(actionContext, cancellationToken);\n\n            // Assert\n            Dictionary<string, object> expectedResult = new Dictionary<string, object>();\n            expectedResult[\"id\"] = 5;\n            expectedResult[\"firstName\"] = \"queryFirstName\";\n            expectedResult[\"lastName\"] = \"queryLastName\";\n            Assert.Equal(expectedResult, actionContext.ActionArguments, new DictionaryEqualityComparer());\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_Query_String_Values_To_Complex_Types()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(new HttpRequestMessage()\n                {\n                    Method = HttpMethod.Get,\n                    RequestUri = new Uri(\"http://localhost?id=5&firstName=queryFirstName&lastName=queryLastName\")\n                }),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"GetItem\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(actionContext, cancellationToken);\n\n            // Assert\n            Assert.True(actionContext.ModelState.IsValid);\n            KeyValuePair<string, object> actionArgument = Assert.Single(actionContext.ActionArguments);\n            ActionValueItem deserializedActionValueItem = Assert.IsType<ActionValueItem>(actionArgument.Value);\n            Assert.Equal(5, deserializedActionValueItem.Id);\n            Assert.Equal(\"queryFirstName\", deserializedActionValueItem.FirstName);\n            Assert.Equal(\"queryLastName\", deserializedActionValueItem.LastName);\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_Query_String_Values_To_Post_Complex_Types()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(new HttpRequestMessage()\n                {\n                    Method = HttpMethod.Get,\n                    RequestUri = new Uri(\"http://localhost?id=5&firstName=queryFirstName&lastName=queryLastName\")\n                }),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"PostComplexTypeUri\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(actionContext, cancellationToken);\n\n            // Assert\n            Assert.True(actionContext.ModelState.IsValid);\n            KeyValuePair<string, object> actionArgument = Assert.Single(actionContext.ActionArguments);\n            ActionValueItem deserializedActionValueItem = Assert.IsType<ActionValueItem>(actionArgument.Value);\n            Assert.Equal(5, deserializedActionValueItem.Id);\n            Assert.Equal(\"queryFirstName\", deserializedActionValueItem.FirstName);\n            Assert.Equal(\"queryLastName\", deserializedActionValueItem.LastName);\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_Query_String_Values_To_Post_Enumerable_Complex_Types()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(new HttpRequestMessage()\n                {\n                    Method = HttpMethod.Get,\n                    RequestUri = new Uri(\"http://localhost?items[0].id=5&items[0].firstName=queryFirstName&items[0].lastName=queryLastName\")\n                }),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"PostEnumerableUri\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(actionContext, cancellationToken);\n\n            // Assert\n            Assert.True(actionContext.ModelState.IsValid);\n            KeyValuePair<string, object> keyValuePair = Assert.Single(actionContext.ActionArguments);\n            IEnumerable<ActionValueItem> items = Assert.IsAssignableFrom<IEnumerable<ActionValueItem>>(keyValuePair.Value);\n            ActionValueItem deserializedActionValueItem = items.First();\n            Assert.Equal(5, deserializedActionValueItem.Id);\n            Assert.Equal(\"queryFirstName\", deserializedActionValueItem.FirstName);\n            Assert.Equal(\"queryLastName\", deserializedActionValueItem.LastName);\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_Query_String_Values_To_Post_Enumerable_Complex_Types_No_Index()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(new HttpRequestMessage()\n                {\n                    Method = HttpMethod.Get,\n                    RequestUri = new Uri(\"http://localhost?id=5&firstName=queryFirstName&items.lastName=queryLastName\")\n                }),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"PostEnumerableUri\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(actionContext, cancellationToken);\n\n            // Assert\n            Assert.True(actionContext.ModelState.IsValid);\n            KeyValuePair<string, object> keyValuePair = Assert.Single(actionContext.ActionArguments);\n            IEnumerable<ActionValueItem> items = Assert.IsAssignableFrom<IEnumerable<ActionValueItem>>(keyValuePair.Value);\n            Assert.Empty(items);     // expect unsuccessful bind but proves we don't loop infinitely\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_Query_String_Values_To_ComplexType_Using_Prefixes()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(new HttpRequestMessage()\n                {\n                    Method = HttpMethod.Get,\n                    RequestUri = new Uri(\"http://localhost?item.id=5&item.firstName=queryFirstName&item.lastName=queryLastName\")\n                }),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"GetItem\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(actionContext, cancellationToken);\n\n            // Assert\n            KeyValuePair<string, object> keyValuePair = Assert.Single(actionContext.ActionArguments);\n            ActionValueItem deserializedActionValueItem = Assert.IsType<ActionValueItem>(keyValuePair.Value);\n            Assert.Equal(5, deserializedActionValueItem.Id);\n            Assert.Equal(\"queryFirstName\", deserializedActionValueItem.FirstName);\n            Assert.Equal(\"queryLastName\", deserializedActionValueItem.LastName);\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_Query_String_Values_To_ComplexType_Using_FromUriAttribute()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(new HttpRequestMessage()\n                {\n                    Method = HttpMethod.Get,\n                    RequestUri = new Uri(\"http://localhost?item.id=5&item.firstName=queryFirstName&item.lastName=queryLastName\")\n                }),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"GetItemFromUri\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(actionContext, cancellationToken);\n\n            // Assert\n            KeyValuePair<string, object> keyValuePair = Assert.Single(actionContext.ActionArguments);\n            ActionValueItem deserializedActionValueItem = Assert.IsType<ActionValueItem>(keyValuePair.Value);\n            Assert.Equal(5, deserializedActionValueItem.Id);\n            Assert.Equal(\"queryFirstName\", deserializedActionValueItem.FirstName);\n            Assert.Equal(\"queryLastName\", deserializedActionValueItem.LastName);\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_Query_String_Values_Using_Custom_ValueProviderAttribute()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(new HttpRequestMessage()\n                {\n                    Method = HttpMethod.Get\n                }),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"GetFromCustom\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(actionContext, cancellationToken);\n\n            // Assert\n            Dictionary<string, object> expectedResult = new Dictionary<string, object>();\n            expectedResult[\"id\"] = 99;\n            expectedResult[\"firstName\"] = \"99\";\n            expectedResult[\"lastName\"] = \"99\";\n            Assert.Equal(expectedResult, actionContext.ActionArguments, new DictionaryEqualityComparer());\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_Query_String_Values_Using_Prefix_To_Rename()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(new HttpRequestMessage()\n                {\n                    Method = HttpMethod.Get,\n                    RequestUri = new Uri(\"http://localhost?custid=5&first=renamedFirstName&last=renamedLastName\")\n                    // notice the query string names match the prefixes in GetFromNamed() and not the actual parameter names\n                }),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"GetFromNamed\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(actionContext, cancellationToken);\n\n            // Assert\n            Dictionary<string, object> expectedResult = new Dictionary<string, object>();\n            expectedResult[\"id\"] = 5;\n            expectedResult[\"firstName\"] = \"renamedFirstName\";\n            expectedResult[\"lastName\"] = \"renamedLastName\";\n            Assert.Equal(expectedResult, actionContext.ActionArguments, new DictionaryEqualityComparer());\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_Query_String_Values_To_Complex_Types_With_Validation_Error()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(new HttpRequestMessage()\n                {\n                    Method = HttpMethod.Get,\n                    RequestUri = new Uri(\"http://localhost?id=100&firstName=queryFirstName&lastName=queryLastName\")\n                }),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"GetItem\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(actionContext, cancellationToken);\n\n            // Assert\n            Assert.False(actionContext.ModelState.IsValid);\n        }\n\n        #endregion Query Strings\n\n        #region RouteData\n\n        [Fact]\n        public async Task BindValuesAsync_RouteData_Values_To_Simple_Types()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            HttpRouteData route = new HttpRouteData(new HttpRoute());\n            route.Values.Add(\"id\", 6);\n            route.Values.Add(\"firstName\", \"routeFirstName\");\n            route.Values.Add(\"lastName\", \"routeLastName\");\n\n            HttpActionContext controllerContext = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(route, new HttpRequestMessage()\n                {\n                    Method = HttpMethod.Get,\n                    RequestUri = new Uri(\"http://localhost\")\n                }),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"Get\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(controllerContext, cancellationToken);\n\n            // Assert\n            Dictionary<string, object> expectedResult = new Dictionary<string, object>();\n            expectedResult[\"id\"] = 6;\n            expectedResult[\"firstName\"] = \"routeFirstName\";\n            expectedResult[\"lastName\"] = \"routeLastName\";\n            Assert.Equal(expectedResult, controllerContext.ActionArguments, new DictionaryEqualityComparer());\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_RouteData_Values_To_Simple_Types_Using_FromUriAttribute()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            HttpRouteData route = new HttpRouteData(new HttpRoute());\n            route.Values.Add(\"id\", 6);\n            route.Values.Add(\"firstName\", \"routeFirstName\");\n            route.Values.Add(\"lastName\", \"routeLastName\");\n\n            HttpActionContext controllerContext = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(route, new HttpRequestMessage()\n                {\n                    Method = HttpMethod.Get,\n                    RequestUri = new Uri(\"http://localhost\")\n                }),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"Get\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(controllerContext, cancellationToken);\n\n            // Assert\n            Dictionary<string, object> expectedResult = new Dictionary<string, object>();\n            expectedResult[\"id\"] = 6;\n            expectedResult[\"firstName\"] = \"routeFirstName\";\n            expectedResult[\"lastName\"] = \"routeLastName\";\n            Assert.Equal(expectedResult, controllerContext.ActionArguments, new DictionaryEqualityComparer());\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_RouteData_Values_To_Complex_Types()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            HttpRouteData route = new HttpRouteData(new HttpRoute());\n            route.Values.Add(\"id\", 6);\n            route.Values.Add(\"firstName\", \"routeFirstName\");\n            route.Values.Add(\"lastName\", \"routeLastName\");\n\n            HttpActionContext controllerContext = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(route, new HttpRequestMessage()\n                {\n                    Method = HttpMethod.Get,\n                    RequestUri = new Uri(\"http://localhost\")\n                }),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"GetItem\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(controllerContext, cancellationToken);\n\n            // Assert\n            KeyValuePair<string, object> keyValuePair = Assert.Single(controllerContext.ActionArguments);\n            ActionValueItem deserializedActionValueItem = Assert.IsType<ActionValueItem>(keyValuePair.Value);\n            Assert.Equal(6, deserializedActionValueItem.Id);\n            Assert.Equal(\"routeFirstName\", deserializedActionValueItem.FirstName);\n            Assert.Equal(\"routeLastName\", deserializedActionValueItem.LastName);\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_RouteData_Values_To_Complex_Types_Using_FromUriAttribute()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            HttpRouteData route = new HttpRouteData(new HttpRoute());\n            route.Values.Add(\"id\", 6);\n            route.Values.Add(\"firstName\", \"routeFirstName\");\n            route.Values.Add(\"lastName\", \"routeLastName\");\n\n            HttpActionContext controllerContext = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(route, new HttpRequestMessage()\n                {\n                    Method = HttpMethod.Get,\n                    RequestUri = new Uri(\"http://localhost\")\n                }),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"GetItemFromUri\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(controllerContext, cancellationToken);\n\n            // Assert\n            KeyValuePair<string, object> keyValuePair = Assert.Single(controllerContext.ActionArguments);\n            ActionValueItem deserializedActionValueItem = Assert.IsType<ActionValueItem>(keyValuePair.Value);\n            Assert.Equal(6, deserializedActionValueItem.Id);\n            Assert.Equal(\"routeFirstName\", deserializedActionValueItem.FirstName);\n            Assert.Equal(\"routeLastName\", deserializedActionValueItem.LastName);\n        }\n\n        #endregion RouteData\n\n        #region ControllerContext\n        [Fact]\n        public async Task BindValuesAsync_ControllerContext_CancellationToken()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(new HttpRequestMessage()\n                {\n                    Method = HttpMethod.Get\n                }),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"GetFromCancellationToken\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(actionContext, cancellationToken);\n\n            // Assert\n            KeyValuePair<string, object> keyValuePair = Assert.Single(actionContext.ActionArguments);\n            Assert.Equal(cancellationToken, keyValuePair.Value);\n        }\n        #endregion ControllerContext\n\n        #region Body\n\n        [Fact]\n        public async Task BindValuesAsync_Body_To_Complex_Type_Json()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            string jsonString = \"{\\\"Id\\\":\\\"7\\\",\\\"FirstName\\\":\\\"testFirstName\\\",\\\"LastName\\\":\\\"testLastName\\\"}\";\n            StringContent stringContent = new StringContent(jsonString, Encoding.UTF8, \"application/json\");\n\n            HttpRequestMessage request = new HttpRequestMessage() { Content = stringContent };\n            HttpActionContext context = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(request),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"PostComplexType\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(context, cancellationToken);\n\n            // Assert\n            KeyValuePair<string, object> keyValuePair = Assert.Single(context.ActionArguments);\n            ActionValueItem deserializedActionValueItem = Assert.IsAssignableFrom<ActionValueItem>(keyValuePair.Value);\n            Assert.Equal(7, deserializedActionValueItem.Id);\n            Assert.Equal(\"testFirstName\", deserializedActionValueItem.FirstName);\n            Assert.Equal(\"testLastName\", deserializedActionValueItem.LastName);\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_Body_To_Complex_Type_Json_With_Validation_Error()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            string jsonString = \"{\\\"Id\\\":\\\"100\\\",\\\"FirstName\\\":\\\"testFirstName\\\",\\\"LastName\\\":\\\"testLastName\\\"}\";\n            StringContent stringContent = new StringContent(jsonString, Encoding.UTF8, \"application/json\");\n\n            HttpRequestMessage request = new HttpRequestMessage() { Content = stringContent };\n            HttpActionContext context = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(request),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"PostComplexType\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(context, cancellationToken);\n\n            // Assert\n            Assert.False(context.ModelState.IsValid);\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_Body_To_Complex_Type_FormUrlEncoded()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            string formUrlEncodedString = \"Id=7&FirstName=testFirstName&LastName=testLastName\";\n            StringContent stringContent = new StringContent(formUrlEncodedString, Encoding.UTF8, \"application/x-www-form-urlencoded\");\n\n            HttpRequestMessage request = new HttpRequestMessage() { Content = stringContent };\n            HttpActionContext context = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(request),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"PostComplexType\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(context, cancellationToken);\n\n            // Assert\n            KeyValuePair<string, object> keyValuePair = Assert.Single(context.ActionArguments);\n            ActionValueItem deserializedActionValueItem = Assert.IsAssignableFrom<ActionValueItem>(keyValuePair.Value);\n            Assert.Equal(7, deserializedActionValueItem.Id);\n            Assert.Equal(\"testFirstName\", deserializedActionValueItem.FirstName);\n            Assert.Equal(\"testLastName\", deserializedActionValueItem.LastName);\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_Body_To_Complex_Type_FormUrlEncoded_With_Validation_Error()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            string formUrlEncodedString = \"Id=101&FirstName=testFirstName&LastName=testLastName\";\n            StringContent stringContent = new StringContent(formUrlEncodedString, Encoding.UTF8, \"application/x-www-form-urlencoded\");\n\n            HttpRequestMessage request = new HttpRequestMessage() { Content = stringContent };\n            HttpActionContext context = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(request),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"PostComplexType\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(context, cancellationToken);\n\n            // Assert\n            Assert.False(context.ModelState.IsValid);\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_Body_To_Complex_Type_Xml()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue(\"application/xml\");\n            ActionValueItem item = new ActionValueItem() { Id = 7, FirstName = \"testFirstName\", LastName = \"testLastName\" };\n            ObjectContent<ActionValueItem> tempContent = new ObjectContent<ActionValueItem>(item, new XmlMediaTypeFormatter());\n            StringContent stringContent = new StringContent(await tempContent.ReadAsStringAsync());\n            stringContent.Headers.ContentType = mediaType;\n            HttpRequestMessage request = new HttpRequestMessage() { Content = stringContent };\n            HttpActionContext context = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(request),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"PostComplexType\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(context, cancellationToken);\n\n            // Assert\n            KeyValuePair<string, object> keyValuePair = Assert.Single(context.ActionArguments);\n            ActionValueItem deserializedActionValueItem = Assert.IsAssignableFrom<ActionValueItem>(keyValuePair.Value);\n            Assert.Equal(item.Id, deserializedActionValueItem.Id);\n            Assert.Equal(item.FirstName, deserializedActionValueItem.FirstName);\n            Assert.Equal(item.LastName, deserializedActionValueItem.LastName);\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_Body_To_Complex_Type_Xml_Structural()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue(\"application/xml\");\n\n            // Test sending from a non .NET type (raw xml).\n            // The default XML serializer requires that the xml root name matches the C# class name.\n            string xmlSource =\n                @\"<ActionValueItem xmlns='http://schemas.datacontract.org/2004/07/System.Web.Http.ModelBinding' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>\n                      <FirstName>testFirstName</FirstName>\n                      <Id>7</Id>\n                      <LastName>testLastName</LastName>\n                  </ActionValueItem>\".Replace('\\'', '\"');\n\n            StringContent stringContent = new StringContent(xmlSource);\n            stringContent.Headers.ContentType = mediaType;\n            HttpRequestMessage request = new HttpRequestMessage() { Content = stringContent };\n            HttpActionContext context = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(request),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"PostComplexType\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(context, cancellationToken);\n\n            // Assert\n            KeyValuePair<string, object> keyValuePair = Assert.Single(context.ActionArguments);\n            ActionValueItem deserializedActionValueItem = Assert.IsAssignableFrom<ActionValueItem>(keyValuePair.Value);\n            Assert.Equal(7, deserializedActionValueItem.Id);\n            Assert.Equal(\"testFirstName\", deserializedActionValueItem.FirstName);\n            Assert.Equal(\"testLastName\", deserializedActionValueItem.LastName);\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_Body_To_Complex_Type_Xml_With_Validation_Error()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue(\"application/xml\");\n            ActionValueItem item = new ActionValueItem() { Id = 101, FirstName = \"testFirstName\", LastName = \"testLastName\" };\n            var tempContent = new ObjectContent<ActionValueItem>(item, new XmlMediaTypeFormatter());\n            StringContent stringContent = new StringContent(await tempContent.ReadAsStringAsync());\n            stringContent.Headers.ContentType = mediaType;\n            HttpRequestMessage request = new HttpRequestMessage() { Content = stringContent };\n            HttpActionContext context = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(request),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"PostComplexType\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(context, cancellationToken);\n\n            // Assert\n            Assert.False(context.ModelState.IsValid);\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_Body_To_Complex_Type_NullContent()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage() { Content = null };\n            HttpActionContext context = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(request),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"PostComplexType\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(context, CancellationToken.None);\n\n            // Assert\n            KeyValuePair<string, object> keyValuePair = Assert.Single(context.ActionArguments);\n            object deserializedActionValueItem = keyValuePair.Value;\n            Assert.Null(deserializedActionValueItem);\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_Body_To_Complex_And_Uri_To_Simple()\n        {\n            // Arrange\n            string jsonString = \"{\\\"Id\\\":\\\"7\\\",\\\"FirstName\\\":\\\"testFirstName\\\",\\\"LastName\\\":\\\"testLastName\\\"}\";\n            StringContent stringContent = new StringContent(jsonString, Encoding.UTF8, \"application/json\");\n\n            HttpRequestMessage request = new HttpRequestMessage()\n            {\n                RequestUri = new Uri(\"http://localhost/ActionValueController/PostFromBody?id=123\"),\n                Content = stringContent\n            };\n\n            HttpActionContext context = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(request),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"PostFromBodyAndUri\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(context, CancellationToken.None);\n\n            // Assert\n            Assert.Equal(2, context.ActionArguments.Count);\n            Assert.Equal(123, context.ActionArguments[\"id\"]);\n\n            ActionValueItem deserializedActionValueItem = Assert.IsAssignableFrom<ActionValueItem>(context.ActionArguments[\"item\"]);\n            Assert.Equal(7, deserializedActionValueItem.Id);\n            Assert.Equal(\"testFirstName\", deserializedActionValueItem.FirstName);\n            Assert.Equal(\"testLastName\", deserializedActionValueItem.LastName);\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_Body_To_Complex_Type_Using_FromBodyAttribute()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            string jsonString = \"{\\\"Id\\\":\\\"7\\\",\\\"FirstName\\\":\\\"testFirstName\\\",\\\"LastName\\\":\\\"testLastName\\\"}\";\n            StringContent stringContent = new StringContent(jsonString, Encoding.UTF8, \"application/json\");\n\n            HttpRequestMessage request = new HttpRequestMessage() { Content = stringContent };\n\n            HttpActionContext context = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(request),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"PostFromBody\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(context, cancellationToken);\n\n            // Assert\n            KeyValuePair<string, object> keyValuePair = Assert.Single(context.ActionArguments);\n            ActionValueItem deserializedActionValueItem = Assert.IsAssignableFrom<ActionValueItem>(keyValuePair.Value);\n            Assert.Equal(7, deserializedActionValueItem.Id);\n            Assert.Equal(\"testFirstName\", deserializedActionValueItem.FirstName);\n            Assert.Equal(\"testLastName\", deserializedActionValueItem.LastName);\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_Body_To_Complex_Type_Using_Formatter_To_Deserialize()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            string jsonString = \"{\\\"Id\\\":\\\"7\\\",\\\"FirstName\\\":\\\"testFirstName\\\",\\\"LastName\\\":\\\"testLastName\\\"}\";\n            StringContent stringContent = new StringContent(jsonString, Encoding.UTF8, \"application/json\");\n\n            HttpRequestMessage request = new HttpRequestMessage() { Content = stringContent };\n            HttpActionContext context = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(request),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"PostComplexType\") });\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(context, cancellationToken);\n\n            // Assert\n            KeyValuePair<string, object> keyValuePair = Assert.Single(context.ActionArguments);\n            ActionValueItem deserializedActionValueItem = Assert.IsAssignableFrom<ActionValueItem>(keyValuePair.Value);\n            Assert.Equal(7, deserializedActionValueItem.Id);\n            Assert.Equal(\"testFirstName\", deserializedActionValueItem.FirstName);\n            Assert.Equal(\"testLastName\", deserializedActionValueItem.LastName);\n        }\n\n\n        [Fact]\n        public async Task BindValuesAsync_Body_To_IEnumerable_Complex_Type_Json()\n        {\n            // ModelBinding will bind T to IEnumerable<T>, but JSON.Net won't. So enclose JSON in [].\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            string jsonString = \"[{\\\"Id\\\":\\\"7\\\",\\\"FirstName\\\":\\\"testFirstName\\\",\\\"LastName\\\":\\\"testLastName\\\"}]\";\n            StringContent stringContent = new StringContent(jsonString, Encoding.UTF8, \"application/json\");\n\n            HttpRequestMessage request = new HttpRequestMessage() { Content = stringContent };\n            HttpActionContext context = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(request),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"PostEnumerable\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(context, cancellationToken);\n\n            // Assert\n            KeyValuePair<string, object> keyValuePair = Assert.Single(context.ActionArguments);\n            IEnumerable<ActionValueItem> items = Assert.IsAssignableFrom<IEnumerable<ActionValueItem>>(keyValuePair.Value);\n            ActionValueItem deserializedActionValueItem = items.First();\n            Assert.Equal(7, deserializedActionValueItem.Id);\n            Assert.Equal(\"testFirstName\", deserializedActionValueItem.FirstName);\n            Assert.Equal(\"testLastName\", deserializedActionValueItem.LastName);\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_Body_To_JToken()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue(\"application/json\");\n            ActionValueItem item = new ActionValueItem() { Id = 7, FirstName = \"testFirstName\", LastName = \"testLastName\" };\n            string json = \"{\\\"a\\\":123,\\\"b\\\":[false,null,12.34]}\";\n            JToken jt = JToken.Parse(json);\n            var tempContent = new ObjectContent<JToken>(jt, new JsonMediaTypeFormatter());\n            StringContent stringContent = new StringContent(await tempContent.ReadAsStringAsync());\n            stringContent.Headers.ContentType = mediaType;\n            HttpRequestMessage request = new HttpRequestMessage() { Content = stringContent };\n            HttpActionContext context = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(request),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"PostJsonValue\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(context, cancellationToken);\n\n            // Assert\n            KeyValuePair<string, object> keyValuePair = Assert.Single(context.ActionArguments);\n            JToken deserializedJsonValue = Assert.IsAssignableFrom<JToken>(keyValuePair.Value);\n            string deserializedJsonAsString = deserializedJsonValue.ToString(Formatting.None);\n            Assert.Equal(json, deserializedJsonAsString);\n        }\n\n        #endregion Body\n\n        [Fact]\n        public async Task BindValuesAsync_FromUriAttribute_DecoratedOn_Type()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(new HttpRequestMessage()\n                {\n                    Method = new HttpMethod(\"Patch\"),\n                    RequestUri = new Uri(\"http://localhost?x=123&y=456&data.description=mypoint\")\n                }),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"Patch\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(actionContext, cancellationToken);\n\n            // Assert\n            Dictionary<string, object> expectedResult = new Dictionary<string, object>();\n            expectedResult[\"point\"] = new Point { X = 123, Y = 456, Data = new Data { Description = \"mypoint\" } };\n            Assert.Equal(expectedResult, actionContext.ActionArguments, new DictionaryEqualityComparer());\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_ModelBinderAttribute_WithEmptyName()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(new HttpRequestMessage()\n                {\n                    Method = new HttpMethod(\"Options\"),\n                    RequestUri = new Uri(\"http://localhost?x=123&y=456&data.description=mypoint\")\n                }),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"Options\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(actionContext, cancellationToken);\n\n            // Assert\n            Dictionary<string, object> expectedResult = new Dictionary<string, object>();\n            expectedResult[\"data\"] = new Point { X = 123, Y = 456, Data = new Data { Description = \"mypoint\" } };\n            Assert.Equal(expectedResult, actionContext.ActionArguments, new DictionaryEqualityComparer());\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_Config_BindParameter()\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            config.BindParameter(typeof(Data), new CustomModelBinder());\n\n            HttpRequestMessage request = new HttpRequestMessage()\n                {\n                    RequestUri = new Uri(\"http://localhost\")\n                };\n\n            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(config, request);\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(controllerContext,\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"GetData\") });\n\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(actionContext, CancellationToken.None);\n\n            // Assert\n            Data argData = (Data)actionContext.ActionArguments[\"data\"];\n            Assert.NotNull(argData);\n            Assert.Equal(\"testing\", argData.Description);\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_Config_BindParameter_ShouldNotBeAppliedToUnrelatedTypes()\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            config.BindParameter(typeof(Data), new CustomModelBinder());\n\n            ActionValueItem item = new ActionValueItem() { Id = 7, FirstName = \"testFirstName\", LastName = \"testLastName\" };\n            HttpRequestMessage request = new HttpRequestMessage()\n            {\n                Content = new ObjectContent(typeof(ActionValueItem), item, config.Formatters.JsonFormatter)\n            };\n            HttpActionContext context = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(config, request),\n                new ReflectedHttpActionDescriptor() { MethodInfo = typeof(ActionValueController).GetMethod(\"PostItem\") });\n            DefaultActionValueBinder provider = new DefaultActionValueBinder();\n\n            // Act\n            await provider.BindValuesAsync(context, CancellationToken.None);\n\n            // Assert\n            KeyValuePair<string, object> keyValuePair = Assert.Single(context.ActionArguments);\n            ActionValueItem result = Assert.IsAssignableFrom<ActionValueItem>(keyValuePair.Value);\n            Assert.Equal(7, result.Id);\n            Assert.Equal(\"testFirstName\", result.FirstName);\n            Assert.Equal(\"testLastName\", result.LastName);\n        }\n    }\n\n    [FromUri]\n    public class Point\n    {\n        public int X { get; set; }\n        public int Y { get; set; }\n        public Data Data { get; set; }\n\n        public override bool Equals(object obj)\n        {\n            Point other = obj as Point;\n            if (other != null)\n            {\n                return other.X == X && other.Y == Y && other.Data.Description == other.Data.Description;\n            }\n            return false;\n        }\n\n        public override int GetHashCode()\n        {\n            return base.GetHashCode();\n        }\n    }\n\n    // Test model binder to bind typeof(Data)\n    public class CustomModelBinder : IModelBinder\n    {\n        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)\n        {\n            Assert.Equal(typeof(Data), bindingContext.ModelType);\n            bindingContext.Model = new Data { Description = \"testing\" };\n            return true;\n        }\n    }\n\n    public class Data\n    {\n        public string Description { get; set; }\n    }\n\n    public class ActionValueController : ApiController\n    {\n        public void GetData(Data data)\n        {\n        }\n\n        public void PostItem(ActionValueItem item)\n        {\n        }\n\n        // Demonstrates the use of ModelBinderAttribute with empty name\n        public void Options([FromUri(Name = \"\")]Point data) { }\n\n        // Demonstrates complex parameter that has FromUri declared on the type\n        public void Patch(Point point) { }\n\n        // Demonstrates parameter that can come from route, query string, or defaults\n        public ActionValueItem Get(int id = 0, string firstName = \"DefaultFirstName\", string lastName = \"DefaultLastName\")\n        {\n            return new ActionValueItem() { Id = id, FirstName = firstName, LastName = lastName };\n        }\n\n        // Demonstrates an explicit override to obtain parameters from URL\n        public ActionValueItem GetFromUri([FromUri] int id = 0,\n                                   [FromUri] string firstName = \"DefaultFirstName\",\n                                   [FromUri] string lastName = \"DefaultLastName\")\n        {\n            return new ActionValueItem() { Id = id, FirstName = firstName, LastName = lastName };\n        }\n\n\n        // Complex objects default to body. But we can bind from URI with an attribute.\n        public ActionValueItem GetItem([FromUri] ActionValueItem item)\n        {\n            return item;\n        }\n\n        // Demonstrates ModelBinding a Item object explicitly from Uri\n        public ActionValueItem GetItemFromUri([FromUri] ActionValueItem item)\n        {\n            return item;\n        }\n\n        // Demonstrates use of renaming parameters via name\n        public ActionValueItem GetFromNamed([FromUri(Name = \"custID\")] int id,\n                                     [FromUri(Name = \"first\")] string firstName,\n                                     [FromUri(Name = \"last\")] string lastName)\n        {\n            return new ActionValueItem() { Id = id, FirstName = firstName, LastName = lastName };\n        }\n\n\n        public void GetTestEmptyString([FromUri] ConvertEmptyStringContainer x)\n        {\n        }\n\n        // Demonstrates use of custom ValueProvider via attribute\n        public ActionValueItem GetFromCustom([ValueProvider(typeof(ActionValueControllerValueProviderFactory), Name = \"id\")] int id,\n                                      [ValueProvider(typeof(ActionValueControllerValueProviderFactory), Name = \"customFirstName\")] string firstName,\n                                      [ValueProvider(typeof(ActionValueControllerValueProviderFactory), Name = \"customLastName\")] string lastName)\n        {\n            return new ActionValueItem() { Id = id, FirstName = firstName, LastName = lastName };\n        }\n\n        // Demonstrates ModelBinding to the CancellationToken of the current request\n        public string GetFromCancellationToken(CancellationToken cancellationToken)\n        {\n            return cancellationToken.ToString();\n        }\n\n        // Demonstrates ModelBinding to the ModelState of the current request\n        public string GetFromModelState(ModelState modelState)\n        {\n            return modelState.ToString();\n        }\n\n        // Demonstrates binding to complex type from body\n        public ActionValueItem PostComplexType(ActionValueItem item)\n        {\n            return item;\n        }\n\n        // Demonstrates binding to complex type from uri\n        public ActionValueItem PostComplexTypeUri([FromUri] ActionValueItem item)\n        {\n            return item;\n        }\n\n        // Demonstrates binding to IEnumerable of complex type from body or Uri\n        public ActionValueItem PostEnumerable(IEnumerable<ActionValueItem> items)\n        {\n            return items.FirstOrDefault();\n        }\n\n        // Demonstrates binding to IEnumerable of complex type from body or Uri\n        public ActionValueItem PostEnumerableUri([FromUri] IEnumerable<ActionValueItem> items)\n        {\n            return items.FirstOrDefault();\n        }\n\n        // Demonstrates binding to JsonValue from body\n        public JToken PostJsonValue(JToken jsonValue)\n        {\n            return jsonValue;\n        }\n\n        // Demonstrate what we expect to be the common default scenario. No attributes are required.\n        // A complex object comes from the body, and simple objects come from the URI.\n        public ActionValueItem PostFromBodyAndUri(int id, ActionValueItem item)\n        {\n            return item;\n        }\n\n        // Demonstrates binding to complex type explicitly marked as coming from body\n        public ActionValueItem PostFromBody([FromBody] ActionValueItem item)\n        {\n            return item;\n        }\n\n        // Demonstrates how body can be shredded to name/value pairs to bind to simple types\n        public ActionValueItem PostToSimpleTypes(int id, string firstName, string lastName)\n        {\n            return new ActionValueItem() { Id = id, FirstName = firstName, LastName = lastName };\n        }\n\n        // Demonstrates binding to ObjectContent<T> from request body\n        public Task<ActionValueItem> PostObjectContentOfItemAsync(ObjectContent<ActionValueItem> item)\n        {\n            return item.ReadAsAsync<ActionValueItem>();\n        }\n\n        public class ActionValueControllerValueProviderFactory : ValueProviderFactory\n        {\n            public override IValueProvider GetValueProvider(HttpActionContext actionContext)\n            {\n                return new ActionValueControllerValueProvider();\n            }\n        }\n\n        public class ActionValueControllerValueProvider : IValueProvider\n        {\n            public bool ContainsPrefix(string prefix)\n            {\n                return true;\n            }\n\n            public ValueProviderResult GetValue(string key)\n            {\n                return new ValueProviderResult(\"99\", \"99\", CultureInfo.CurrentCulture);\n            }\n        }\n    }\n\n    static class DefaultActionValueBinderExtensions\n    {\n        public static Task BindValuesAsync(this DefaultActionValueBinder binder, HttpActionContext actionContext, CancellationToken cancellationToken)\n        {\n            HttpActionBinding binding = binder.GetBinding(actionContext.ActionDescriptor);\n            return binding.ExecuteBindingAsync(actionContext, cancellationToken);\n        }\n    }\n\n    public class ActionValueItem\n    {\n        [Range(0, 99)]\n        public int Id { get; set; }\n        public string FirstName { get; set; }\n        public string LastName { get; set; }\n    }\n\n    // Test variants of converting empty string to null.\n    // Pass each property the empty string.\n    public class ConvertEmptyStringContainer\n    {\n        [DisplayFormat(ConvertEmptyStringToNull = false)]\n        public string A1 { get; set; } // \"\"\n\n        [DisplayFormat(ConvertEmptyStringToNull = true)]\n        public string A2 { get; set; } // Null\n\n        [DisplayFormat]\n        public string A3 { get; set; } // Null\n\n        public string A4 { get; set; } // Null\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ModelBinding/HttpContentBindingTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.ServiceModel;\nusing System.Threading.Tasks;\nusing System.Web.Http.SelfHost;\nusing System.Web.Http.Util;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ModelBinding\n{\n    /// <summary>\n    /// Tests actions that directly use HttpRequestMessage parameters\n    /// </summary>\n    public class HttpContentBindingTests\n    {\n        public HttpContentBindingTests()\n        {\n            SetupHost();\n        }\n\n        [Theory]\n        [InlineData(\"application/xml\")]\n        [InlineData(\"text/xml\")]\n        [InlineData(\"application/json\")]\n        [InlineData(\"text/json\")]\n        public async Task Action_Directly_Reads_HttpRequestMessage(string mediaType)\n        {\n            Order order = new Order() { OrderId = \"99\", OrderValue = 100.0 };\n            var formatter = new MediaTypeFormatterCollection().FindWriter(typeof(Order), new MediaTypeHeaderValue(mediaType));\n            HttpRequestMessage request = new HttpRequestMessage()\n            {\n                Content = new ObjectContent<Order>(order, formatter, mediaType),\n                RequestUri = new Uri(baseAddress + \"/HttpContentBinding/HandleMessage\"),\n                Method = HttpMethod.Post\n            };\n\n            HttpResponseMessage response = await httpClient.SendAsync(request);\n\n            Order receivedOrder = await response.Content.ReadAsAsync<Order>();\n            Assert.Equal(order.OrderId, receivedOrder.OrderId);\n            Assert.Equal(order.OrderValue, receivedOrder.OrderValue);\n        }\n\n        private HttpServer server = null;\n        private string baseAddress = null;\n        private HttpClient httpClient = null;\n\n        private void SetupHost()\n        {\n            baseAddress = \"http://localhost/\";\n\n            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(baseAddress);\n            config.HostNameComparisonMode = HostNameComparisonMode.Exact;\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{action}\", new { controller = \"HttpContentBinding\", action = \"HandleMessage\" });\n            config.MessageHandlers.Add(new ConvertToStreamMessageHandler());\n\n            server = new HttpServer(config);\n            httpClient = new HttpClient(server);\n        }\n    }\n\n    public class Order\n    {\n        public string OrderId { get; set; }\n        public double OrderValue { get; set; }\n    }\n\n    public class HttpContentBindingController : ApiController\n    {\n        [HttpPost]\n        public async Task<HttpResponseMessage> HandleMessage()\n        {\n            Order order = await Request.Content.ReadAsAsync<Order>();\n            return new HttpResponseMessage(HttpStatusCode.OK)\n            {\n                Content = new ObjectContent<Order>(order, new JsonMediaTypeFormatter())\n            };\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ModelBinding/ModelBindingController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Globalization;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Http;\nusing System.Runtime.Serialization;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.ValueProviders;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ModelBinding\n{\n    public class ModelBindingController : ApiController\n    {\n        public string GetString(string value)\n        {\n            return value;\n        }\n\n        public string GetStringFromRoute(string controller = null, string action = null)\n        {\n            return controller + \":\" + action;\n        }\n\n        public int GetInt(int value)\n        {\n            return value;\n        }\n\n        public int? GetOptionalNullableInt(int? value = null)\n        {\n            return value;\n        }\n\n        public int GetIntWithDefault(int value = -1)\n        {\n            return value;\n        }\n\n        public string GetStringWithDefault(string value = null)\n        {\n            return value;\n        }\n\n        public int GetIntFromUri([FromUri] int value)\n        {\n            return value;\n        }\n\n        public int GetIntPrefixed([FromUri(Name = \"somePrefix\")] int value)\n        {\n            return value;\n        }\n\n        public int GetIntCustom([ValueProvider(typeof(RequestHeadersValueProviderFactory))] int value)\n        {\n            return value;\n        }\n\n        public Task<int> GetIntAsync(int value, CancellationToken token)\n        {\n            TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();\n            tcs.TrySetResult(value);\n            return tcs.Task;\n        }\n\n        public bool GetBool(bool value)\n        {\n            return value;\n        }\n\n        public ModelBindOrder GetComplexType(ModelBindOrder item)\n        {\n            return item;\n        }\n\n        public ModelBindOrder GetComplexTypeFromUri([FromUri] ModelBindOrder item)\n        {\n            return item;\n        }\n\n        public string PostString(string value)\n        {\n            return value;\n        }\n\n        public int PostInt(int value)\n        {\n            return value;\n        }\n\n        public HttpResponseMessage PostComplexWithValidation(CustomerNameMax6 customer)\n        {\n            string errors = String.Empty;\n            foreach (var kv in this.ModelState)\n            {\n                int errorCount = kv.Value.Errors.Count;\n\n                if (errorCount > 0)\n                {\n                    errors += String.Format(\"Failed to bind {0}. The errors are:\\n\", kv.Key);\n                    for (int i = 0; i < errorCount; i++)\n                    {\n                        ModelError error = kv.Value.Errors[i];\n                        errors += \"ErrorMessage: \" + error.ErrorMessage + \"\\n\";\n\n                        if (error.Exception != null)\n                        {\n                            errors += \"Exception\" + error.Exception + \"\\n\";\n                        }\n                    }\n                }\n            }\n\n            if (errors != String.Empty)\n            {\n                // Has validation failure\n                // TODO, 334736, support HttpResponseException which takes ModelState\n                // throw new HttpResponseException(this.ModelState);\n                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.BadRequest);\n                response.Content = new StringContent(errors);\n                throw new HttpResponseException(response);\n            }\n            else\n            {\n                // happy path\n                return Request.CreateResponse<int>(HttpStatusCode.OK, customer.Id);\n            }\n        }\n\n        public int PostIntFromUri([FromUri] int value)\n        {\n            return value;\n        }\n\n        public int PostIntFromBody([FromBody] int value)\n        {\n            return value;\n        }\n\n        public int PostIntUriPrefixed([FromUri(Name = \"somePrefix\")] int value)\n        {\n            return value;\n        }\n\n        public bool PostBool(bool value)\n        {\n            return value;\n        }\n\n        public int PostIntArray([FromUri] int[] value)\n        {\n            return value.Sum();\n        }\n\n        public ModelBindOrder PostComplexType(ModelBindOrder item)\n        {\n            return item;\n        }\n\n        public ModelBindOrder PostComplexTypeFromUri([FromUri] ModelBindOrder item)\n        {\n            return item;\n        }\n\n        public ComplexTypeWithNestedCollection PostComplexTypeFromUriWithNestedCollection([FromUri] ComplexTypeWithNestedCollection value)\n        {\n            return value;\n        }\n\n        public ModelBindOrder PostComplexTypeFromBody([FromBody] ModelBindOrder item)\n        {\n            return item;\n        }\n\n        // check if HttpRequestMessage prevents binding other parameters\n        public int PostComplexTypeHttpRequestMessage(HttpRequestMessage request, ModelBindOrder order)\n        {\n            return Int32.Parse(order.ItemName) + order.Quantity;\n        }\n\n        public string PostWithOptionalBodyParameter([FromBody] string value = \"default\")\n        {\n            return value;\n        }\n\n        public string PostWithOptionalBodyParameterAndUriParameter([FromUri]int id, [FromBody] string value = \"default\")\n        {\n            return value;\n        }\n    }\n\n    [DataContract]\n    public class CustomerNameMax6\n    {\n        [Required]\n        [StringLength(6)]\n        [DataMember]\n        public string Name { get; set; }\n\n        [DataMember]\n        public int Id { get; set; }\n\n        [Required]\n        [DataMember(IsRequired = true)]\n        public int RequiredValue { get; set; }\n    }\n\n    public class ModelBindCustomer\n    {\n        public string Name { get; set; }\n    }\n\n    public class ModelBindOrder\n    {\n        public string ItemName { get; set; }\n        public int Quantity { get; set; }\n        public ModelBindCustomer Customer { get; set; }\n    }\n\n    public class ComplexTypeWithNestedCollection\n    {\n        public IEnumerable<int> Numbers { get; set; }\n    }\n\n    public class ModelBindOrderEqualityComparer : IEqualityComparer<ModelBindOrder>\n    {\n        public bool Equals(ModelBindOrder x, ModelBindOrder y)\n        {\n            Assert.True(x != null, \"Expected ModelBindOrder cannot be null.\");\n            Assert.True(y != null, \"Actual ModelBindOrder was null.\");\n            Assert.Equal(x.ItemName, y.ItemName);\n            Assert.Equal(x.Quantity, y.Quantity);\n\n            if (x.Customer != null)\n            {\n                Assert.True(y.Customer != null, \"Actual Customer was null but expected was \" + x.Customer.Name);\n            }\n            else if (x.Customer == null)\n            {\n                Assert.True(y.Customer == null, \"Actual Customer was not null but should have been.\");\n            }\n            else\n            {\n                Assert.True(String.Equals(x.Customer.Name, y.Customer.Name, StringComparison.Ordinal), String.Format(\"Expected Customer.Name '{0}' but actual was '{1}'\", x.Customer.Name, y.Customer.Name));\n            }\n\n            return true;\n        }\n\n        public int GetHashCode(ModelBindOrder obj)\n        {\n            return obj.GetHashCode();\n        }\n    }\n\n    public class RequestHeadersValueProviderFactory : ValueProviderFactory\n    {\n        public override IValueProvider GetValueProvider(HttpActionContext actionContext)\n        {\n            return new RequestHeaderValueProvider(actionContext);\n        }\n    }\n\n    public class RequestHeaderValueProvider : IValueProvider\n    {\n        HttpActionContext _actionContext;\n        public RequestHeaderValueProvider(HttpActionContext actionContext)\n        {\n            _actionContext = actionContext;\n        }\n\n        public bool ContainsPrefix(string prefix)\n        {\n            return _actionContext.ControllerContext.Request.Headers.Contains(prefix);\n        }\n\n        public ValueProviderResult GetValue(string key)\n        {\n            string result = _actionContext.ControllerContext.Request.Headers.GetValues(key).FirstOrDefault();\n            return result == null\n                ? null\n                : new ValueProviderResult(result, result, CultureInfo.CurrentCulture);\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ModelBinding/ModelBindingTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.ModelBinding\n{\n    /// <summary>\n    /// End to end functional tests for model binding\n    /// </summary>\n    public abstract class ModelBindingTests : HttpServerTestBase\n    {\n        protected ModelBindingTests()\n            : base(\"http://localhost/\")\n        {\n        }\n\n        protected override void ApplyConfiguration(HttpConfiguration configuration)\n        {\n            configuration.Routes.MapHttpRoute(\"Default\", \"{controller}/{action}\", new { controller = \"ModelBinding\" });\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ModelBinding/QueryStringBindingTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Net.Http;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ModelBinding\n{\n    /// <summary>\n    /// End to end functional tests for model binding via query strings\n    /// </summary>\n    public class QueryStringBindingTests : ModelBindingTests\n    {\n        [Theory]\n        [InlineData(\"GetString\", \"?value=test\", \"\\\"test\\\"\")]\n        [InlineData(\"GetInt\", \"?value=99\", \"99\")]\n        [InlineData(\"GetBool\", \"?value=false\", \"false\")]\n        [InlineData(\"GetBool\", \"?value=true\", \"true\")]\n        [InlineData(\"GetIntWithDefault\", \"?value=99\", \"99\")]    // action has default, but we provide value\n        [InlineData(\"GetIntWithDefault\", \"\", \"-1\")]             // action has default, we provide no value\n        [InlineData(\"GetStringWithDefault\", \"\", \"null\")]        // action has null default, we provide no value\n        [InlineData(\"GetIntFromUri\", \"?value=99\", \"99\")]        // [FromUri]\n        [InlineData(\"GetIntPrefixed\", \"?somePrefix=99\", \"99\")]  // [FromUri(Prefix=somePrefix)]\n        [InlineData(\"GetIntAsync\", \"?value=5\", \"5\")]\n        [InlineData(\"GetOptionalNullableInt\", \"\", \"null\")]\n        [InlineData(\"GetOptionalNullableInt\", \"?value=6\", \"6\")]\n        public async Task Query_String_Binds_Simple_Types_Get(string action, string queryString, string expectedResponse)\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage()\n            {\n                RequestUri = new Uri(BaseAddress + String.Format(\"ModelBinding/{0}{1}\", action, queryString)),\n                Method = HttpMethod.Get\n            };\n\n            // Act\n            HttpResponseMessage response = await Client.SendAsync(request);\n\n            // Assert\n            string responseString = await response.Content.ReadAsStringAsync();\n            Assert.Equal(expectedResponse, responseString);\n        }\n\n        [Theory]\n        [InlineData(\"PostString\", \"?value=test\", \"\\\"test\\\"\")]\n        [InlineData(\"PostInt\", \"?value=99\", \"99\")]\n        [InlineData(\"PostBool\", \"?value=false\", \"false\")]\n        [InlineData(\"PostBool\", \"?value=true\", \"true\")]\n        [InlineData(\"PostIntFromUri\", \"?value=99\", \"99\")]           // [FromUri]\n        [InlineData(\"PostIntUriPrefixed\", \"?somePrefix=99\", \"99\")]  // [FromUri(Prefix=somePrefix)]\n        [InlineData(\"PostIntArray\", \"?value={[1,2,3]}\", \"0\")]       // TODO: DevDiv2 333257 -- make this array real when fix JsonValue array model binding\n        public async Task Query_String_Binds_Simple_Types_Post(string action, string queryString, string expectedResponse)\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage()\n            {\n                RequestUri = new Uri(BaseAddress + String.Format(\"ModelBinding/{0}{1}\", action, queryString)),\n                Method = HttpMethod.Post\n            };\n\n            // Act\n            HttpResponseMessage response = await Client.SendAsync(request);\n\n            // Assert\n            string responseString = await response.Content.ReadAsStringAsync();\n            Assert.Equal(expectedResponse, responseString);\n        }\n\n        [Theory]\n        [InlineData(\"GetComplexTypeFromUri\", \"itemName=Tires&quantity=2&customer.Name=Sue\", \"Tires\", 2, \"Sue\")]\n        public async Task Query_String_ComplexType_Type_Get(string action, string queryString, string itemName, int quantity, string customerName)\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage()\n            {\n                RequestUri = new Uri(BaseAddress + String.Format(\"ModelBinding/{0}?{1}\", action, queryString)),\n                Method = HttpMethod.Get\n            };\n\n            ModelBindOrder expectedItem = new ModelBindOrder()\n            {\n                ItemName = itemName,\n                Quantity = quantity,\n                Customer = new ModelBindCustomer { Name = customerName }\n            };\n\n            // Act\n            HttpResponseMessage response = await Client.SendAsync(request);\n\n            // Assert\n            ModelBindOrder actualItem = await response.Content.ReadAsAsync<ModelBindOrder>();\n            Assert.Equal(expectedItem, actualItem, new ModelBindOrderEqualityComparer());\n        }\n\n        [Theory]\n        [InlineData(\"PostComplexTypeFromUri\", \"itemName=Tires&quantity=2&customer.Name=Bob\", \"Tires\", 2, \"Bob\")]\n        public async Task Query_String_ComplexType_Type_Post(string action, string queryString, string itemName, int quantity, string customerName)\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage()\n            {\n                RequestUri = new Uri(BaseAddress + String.Format(\"ModelBinding/{0}?{1}\", action, queryString)),\n                Method = HttpMethod.Post\n            };\n            ModelBindOrder expectedItem = new ModelBindOrder()\n            {\n                ItemName = itemName,\n                Quantity = quantity,\n                Customer = new ModelBindCustomer { Name = customerName }\n            };\n\n            // Act\n            HttpResponseMessage response = await Client.SendAsync(request);\n\n            // Assert\n            ModelBindOrder actualItem = await response.Content.ReadAsAsync<ModelBindOrder>();\n            Assert.Equal(expectedItem, actualItem, new ModelBindOrderEqualityComparer());\n        }\n\n        [Theory]\n        [InlineData(\"PostComplexTypeFromUriWithNestedCollection\", \"value.Numbers[0]=1&value.Numbers[1]=2\", new[] { 1, 2 })]\n        public async Task Query_String_ComplexType_Type_Post_NestedCollection(string action, string queryString, int[] expectedValues)\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage()\n            {\n                RequestUri = new Uri(BaseAddress + String.Format(\"ModelBinding/{0}?{1}\", action, queryString)),\n                Method = HttpMethod.Post\n            };\n\n            // Act\n            HttpResponseMessage response = await Client.SendAsync(request);\n\n            // Assert\n            ComplexTypeWithNestedCollection actualResult = await response.Content.ReadAsAsync<ComplexTypeWithNestedCollection>();\n            int[] actualValues = actualResult.Numbers.ToArray();\n            Assert.Equal(expectedValues.Length, actualValues.Length);\n            for (int i = 0; i < expectedValues.Length; i++)\n            {\n                Assert.Equal(expectedValues[i], actualValues[i]);\n            }\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/ModelBinding/RouteBindingTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ModelBinding\n{\n    /// <summary>\n    /// End to end functional tests for model binding via routes\n    /// </summary>\n    public class RouteBindingTests : ModelBindingTests\n    {\n        [Fact]\n        public async Task Route_Binds_Simple_Types_Get()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage()\n            {\n                RequestUri = new Uri(BaseAddress + \"ModelBinding/GetStringFromRoute\"),\n                Method = HttpMethod.Get\n            };\n\n            // Act\n            HttpResponseMessage response = await Client.SendAsync(request);\n\n            // Assert\n            string responseString = await response.Content.ReadAsStringAsync();\n            Assert.Equal(\"\\\"ModelBinding:GetStringFromRoute\\\"\", responseString);\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/Properties/AssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\n\n[assembly: CLSCompliant(false)]"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/System.Web.Http.Integration.Test.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props\" Condition=\"Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" />\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" />\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{3267DFC6-B34D-4011-BC0F-D3B56AF6F608}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>System.Web.Http</RootNamespace>\n    <AssemblyName>System.Web.Http.Integration.Test</AssemblyName>\n    <OutputPath>..\\..\\bin\\$(Configuration)\\Test\\</OutputPath>\n    <NuGetPackageImportStamp>\n    </NuGetPackageImportStamp>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Castle.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Castle.Core.5.1.1\\lib\\net462\\Castle.Core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Moq, Version=4.18.0.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Moq.4.18.4\\lib\\net462\\Moq.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Newtonsoft.Json.13.0.1\\lib\\net45\\Newtonsoft.Json.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.ComponentModel.DataAnnotations\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.IdentityModel\" />\n    <Reference Include=\"System.Net.Http\" />\n    <Reference Include=\"System.Net.Http.WebRequest\" />\n    <Reference Include=\"System.Runtime.Serialization\" />\n    <Reference Include=\"System.ServiceModel\" />\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"System.Data\" />\n    <Reference Include=\"System.Xml\" />\n    <Reference Include=\"xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.abstractions.2.0.3\\lib\\net35\\xunit.abstractions.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.assert, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.assert.2.4.2\\lib\\netstandard1.1\\xunit.assert.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.core, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.core.2.4.2\\lib\\net452\\xunit.core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.execution.desktop, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.execution.2.4.2\\lib\\net452\\xunit.execution.desktop.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"ApiExplorer\\Controllers\\AmbiguousActionController.cs\" />\n    <Compile Include=\"ApiExplorer\\Controllers\\AttributeRouteControllers.cs\" />\n    <Compile Include=\"ApiExplorer\\Controllers\\ResponseTypeController.cs\" />\n    <Compile Include=\"ApiExplorer\\Controllers\\DocumentationController.cs\" />\n    <Compile Include=\"ApiExplorer\\Controllers\\ParameterSourceController.cs\" />\n    <Compile Include=\"ApiExplorer\\AttributeRoutesTest.cs\" />\n    <Compile Include=\"ApiExplorer\\ResponseTypeAttributeTest.cs\" />\n    <Compile Include=\"ApiExplorer\\DocumentationProviders\\AttributeDocumentationProvider.cs\" />\n    <Compile Include=\"ApiExplorer\\FormattersTest.cs\" />\n    <Compile Include=\"ApiExplorer\\Formatters\\ItemFormatter.cs\" />\n    <Compile Include=\"ApiExplorer\\ParameterSourceTest.cs\" />\n    <Compile Include=\"ApiExplorer\\DocumentationTest.cs\" />\n    <Compile Include=\"ApiExplorer\\RouteConstraintsTest.cs\" />\n    <Compile Include=\"ApiExplorer\\RoutesTest.cs\" />\n    <Compile Include=\"Controllers\\Apis\\EnumParameterOverloadsController.cs\" />\n    <Compile Include=\"Controllers\\Apis\\HeaderValueProviderFactory.cs\" />\n    <Compile Include=\"Controllers\\Apis\\ParameterTestController.cs\" />\n    <Compile Include=\"Controllers\\Apis\\SpecialConfigController.cs\" />\n    <Compile Include=\"Controllers\\Apis\\RegularConfigController.cs\" />\n    <Compile Include=\"Controllers\\Apis\\ParameterAttributeController.cs\" />\n    <Compile Include=\"Controllers\\Apis\\UsersController.cs\" />\n    <Compile Include=\"Controllers\\ActionReachabilityTest.cs\" />\n    <Compile Include=\"Controllers\\Apis\\ValuesController.cs\" />\n    <Compile Include=\"Controllers\\ControllerConfigurationTest.cs\" />\n    <Compile Include=\"Dispatcher\\CustomHttpControllerTypeResolverTest.cs\" />\n    <Compile Include=\"Tracing\\ITestTraceWriter.cs\" />\n    <Compile Include=\"Tracing\\MemoryTraceWriter.cs\" />\n    <Compile Include=\"Tracing\\NeverTracesTraceWriter.cs\" />\n    <Compile Include=\"Tracing\\TracingTest.cs\" />\n    <Compile Include=\"Util\\ApiExplorerHelper.cs\" />\n    <Compile Include=\"ApiExplorer\\ApiExplorerSettingsTest.cs\" />\n    <Compile Include=\"ApiExplorer\\Controllers\\HiddenController.cs\" />\n    <Compile Include=\"ApiExplorer\\Controllers\\ItemController.cs\" />\n    <Compile Include=\"ApiExplorer\\Controllers\\HiddenActionController.cs\" />\n    <Compile Include=\"ApiExplorer\\Controllers\\OverloadsController.cs\" />\n    <Compile Include=\"ContentNegotiation\\ContentNegotiationTestBase.cs\" />\n    <Compile Include=\"ContentNegotiation\\CustomFormatterTests.cs\" />\n    <Compile Include=\"ContentNegotiation\\DefaultContentNegotiatorTests.cs\" />\n    <Compile Include=\"ContentNegotiation\\HttpResponseReturnTests.cs\" />\n    <Compile Include=\"ContentNegotiation\\ConnegController.cs\" />\n    <Compile Include=\"ContentNegotiation\\ConnegItem.cs\" />\n    <Compile Include=\"ContentNegotiation\\AcceptHeaderTests.cs\" />\n    <Compile Include=\"Controllers\\ActionAttributesTest.cs\" />\n    <Compile Include=\"Controllers\\ApiControllerActionSelectorTest.cs\" />\n    <Compile Include=\"Controllers\\Apis\\ActionAttributeTestController.cs\" />\n    <Compile Include=\"Controllers\\Apis\\TestController.cs\" />\n    <Compile Include=\"Controllers\\Apis\\User.cs\" />\n    <Compile Include=\"Controllers\\Apis\\UserAddress.cs\" />\n    <Compile Include=\"Controllers\\Helpers\\ApiControllerHelper.cs\" />\n    <Compile Include=\"ExceptionHandling\\DuplicateControllers.cs\" />\n    <Compile Include=\"ExceptionHandling\\ExceptionController.cs\" />\n    <Compile Include=\"ExceptionHandling\\ExceptionHandlingTest.cs\" />\n    <Compile Include=\"ExceptionHandling\\HttpResponseExceptionTest.cs\" />\n    <Compile Include=\"ExceptionHandling\\IncludeErrorDetailTest.cs\" />\n    <Compile Include=\"ModelBinding\\BodyBindingTests.cs\" />\n    <Compile Include=\"ModelBinding\\CustomBindingTests.cs\" />\n    <Compile Include=\"ModelBinding\\DefaultActionValueBinderTest.cs\" />\n    <Compile Include=\"ModelBinding\\ModelBindingController.cs\" />\n    <Compile Include=\"ModelBinding\\ModelBindingTests.cs\" />\n    <Compile Include=\"ModelBinding\\HttpContentBindingTests.cs\" />\n    <Compile Include=\"ModelBinding\\QueryStringBindingTests.cs\" />\n    <Compile Include=\"ModelBinding\\RouteBindingTests.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"Util\\ContextUtil.cs\" />\n    <Compile Include=\"Util\\ConvertToStreamMessageHandler.cs\" />\n    <Compile Include=\"Util\\HttpServerTestBase.cs\" />\n    <Compile Include=\"Util\\ScenarioHelper.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\..\\src\\System.Net.Http.Formatting\\System.Net.Http.Formatting.csproj\">\n      <Project>{668E9021-CE84-49D9-98FB-DF125A9FCDB0}</Project>\n      <Name>System.Net.Http.Formatting</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Http.SelfHost\\System.Web.Http.SelfHost.csproj\">\n      <Project>{66492E69-CE4C-4FB1-9B1F-88DEE09D06F1}</Project>\n      <Name>System.Web.Http.SelfHost</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Http\\System.Web.Http.csproj\">\n      <Project>{DDC1CE0C-486E-4E35-BB3B-EAB61F8F9440}</Project>\n      <Name>System.Web.Http</Name>\n      <Private>True</Private>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\">\n      <Project>{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}</Project>\n      <Name>Microsoft.TestCommon</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Service Include=\"{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Analyzer Include=\"..\\..\\packages\\xunit.analyzers.1.1.0\\analyzers\\dotnet\\cs\\xunit.analyzers.dll\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  <Target Name=\"EnsureNuGetPackageBuildImports\" BeforeTargets=\"PrepareForBuild\">\n    <PropertyGroup>\n      <ErrorText>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}.</ErrorText>\n    </PropertyGroup>\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props'))\" />\n  </Target>\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" />\n</Project>"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/Tracing/ITestTraceWriter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.Tracing\n{\n    public interface ITestTraceWriter : ITraceWriter\n    {\n        // Asks the trace writer to initialize for another test iteration\n        void Start();\n\n        // Tells the trace writer to stop tracing\n        void Finish();\n\n        // Returns true if the tracer writer received any trace requests\n        bool DidReceiveTraceRequests { get; }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/Tracing/MemoryTraceWriter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\n\nnamespace System.Web.Http.Tracing\n{\n    /// <summary>\n    /// This <see cref=\"ITraceWriter\"/> unconditionally responds that\n    /// all categories and levels are enabled.  \n    /// All attempts to trace call back the caller for trace information\n    /// and the information is kept in memory for later use.\n    /// <para>\n    /// Its use forces all trace statements in all tracers to\n    /// evaluate their information and update their TraceRecord.\n    /// </para>\n    /// </summary>\n    public class MemoryTraceWriter : ITestTraceWriter\n    {\n        private List<TraceRecord> _records = new List<TraceRecord>();\n\n        public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)\n        {\n            TraceRecord record = new TraceRecord(request, category, level);\n            traceAction(record);\n            _records.Add(record);\n        }\n\n        public void Start()\n        {\n            _records.Clear();\n        }\n\n        public bool DidReceiveTraceRequests { get { return _records.Count != 0; } }\n\n        public void Finish()\n        {\n        }\n\n        public IList<TraceRecord> Records { get { return _records; } }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/Tracing/NeverTracesTraceWriter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\n\nnamespace System.Web.Http.Tracing\n{\n    /// <summary>\n    /// This <see cref=\"ITraceWriter\"/> unconditionally responds that\n    /// all categories and levels are disabled.  \n    /// All attempts to trace do not call back to the user for trace information.\n    /// </summary>\n    /// <para>\n    /// Its use forces all tracers to be installed and to execute,\n    /// but all their trace statements are not called back for\n    /// their trace information.\n    /// </para>\n    public class NeverTracesTraceWriter : ITestTraceWriter\n    {\n        public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)\n        {\n            DidReceiveTraceRequests = true;\n        }\n\n        public void Start()\n        {\n            DidReceiveTraceRequests = false;\n        }\n\n        public bool DidReceiveTraceRequests { get; set; }\n\n        public void Finish()\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/Tracing/TracingTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Http;\nusing System.Reflection;\nusing System.Threading.Tasks;\nusing System.Web.Http.Tracing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.ModelBinding\n{\n    /// <summary>\n    /// End to end functional tests for tracing.\n    /// Verifies ValuesController from standard WebApi project template\n    /// behaves the same whether tracing is on or off.  Also verifies\n    /// silent and verbose trace writers do not affect the responses.\n    ///\n    /// </summary>\n    public class TracingTest\n    {\n        private readonly string _baseAddress = \"http://localhost\";\n\n        public TracingTest()\n        {\n        }\n\n        // The test trace writers used when testing that the controller\n        // is unaffected by presence or behavior of trace writers\n        public static TheoryDataSet<ITestTraceWriter> TestTraceWriters\n        {\n            get\n            {\n                return new TheoryDataSet<ITestTraceWriter>\n                {\n                    // Null means tracing is disabled\n                    null,\n\n                    // This trace writer enables tracing, and the tracer\n                    // never calls back any tracing client to ask for more info.\n                    new NeverTracesTraceWriter(),\n\n                    // This trace writer enables tracing, and the tracer\n                    // always calls back all tracing clients to ask for more info.\n                    new MemoryTraceWriter(),\n                };\n            }\n        }\n\n        // These are all the Begin/End traces we expect in a successful ValuesController.Get(id).\n        // Tests assert all these are traced (both a Begin and End) and that no others are traced.\n        // We verify only the stable parts of the trace record, not the optional messages etc.\n        public static List<ExpectedTraceRecord> ExpectedTraceRecords = new List<ExpectedTraceRecord>() {\n            new ExpectedTraceRecord(\"System.Web.Http.Request\",      string.Empty,                     string.Empty),\n            new ExpectedTraceRecord(\"System.Web.Http.MessageHandlers\",  \"DelegatingHandlerProxy\",     \"SendAsync\"),\n            new ExpectedTraceRecord(\"System.Web.Http.Controllers\",  \"DefaultHttpControllerSelector\",  \"SelectController\"),\n            new ExpectedTraceRecord(\"System.Web.Http.Controllers\",  \"HttpControllerDescriptor\",       \"CreateController\"),\n            new ExpectedTraceRecord(\"System.Web.Http.Controllers\",  \"DefaultHttpControllerActivator\", \"Create\"),\n            new ExpectedTraceRecord(\"System.Web.Http.Controllers\",  \"DefaultHttpControllerTypeResolver\", \"GetControllerTypes\"),\n            new ExpectedTraceRecord(\"System.Web.Http.Controllers\",  \"ValuesController\",               \"ExecuteAsync\"),\n            new ExpectedTraceRecord(\"System.Web.Http.Action\",       \"ApiControllerActionSelector\",    \"SelectAction\"),\n            new ExpectedTraceRecord(\"System.Web.Http.Action\",       \"ApiControllerActionInvoker\",     \"InvokeActionAsync\"),\n            new ExpectedTraceRecord(\"System.Web.Http.Action\",       \"ReflectedHttpActionDescriptor\",  \"ExecuteAsync\"),\n            new ExpectedTraceRecord(\"System.Web.Http.ModelBinding\", \"HttpActionBinding\",              \"ExecuteBindingAsync\"),\n            new ExpectedTraceRecord(\"System.Web.Http.ModelBinding\", \"ModelBinderParameterBinding\",    \"ExecuteBindingAsync\"),\n            new ExpectedTraceRecord(\"System.Net.Http.Formatting\",   \"DefaultContentNegotiator\",       \"Negotiate\"),\n            new ExpectedTraceRecord(\"System.Net.Http.Formatting\",   \"JsonMediaTypeFormatter\",         \"GetPerRequestFormatterInstance\"),\n            new ExpectedTraceRecord(\"System.Net.Http.Formatting\",   \"JsonMediaTypeFormatter\",         \"WriteToStreamAsync\"),\n        };\n\n        // These are all the Begin/End traces we expect in a successful ValuesController.Get(id).\n        public static List<ExpectedTraceRecord> ExpectedTraceRecordOrder = new List<ExpectedTraceRecord>() {\n            new ExpectedTraceRecord(TraceKind.Begin,     \"System.Web.Http.Request\",      string.Empty,                     string.Empty),\n            new ExpectedTraceRecord(TraceKind.Begin,     \"System.Web.Http.MessageHandlers\",  \"DelegatingHandlerProxy\",  \"SendAsync\"),\n            new ExpectedTraceRecord(TraceKind.Begin,     \"System.Web.Http.Controllers\",  \"DefaultHttpControllerSelector\",  \"SelectController\"),\n            new ExpectedTraceRecord(TraceKind.Begin,     \"System.Web.Http.Controllers\",  \"DefaultHttpControllerTypeResolver\", \"GetControllerTypes\"),\n            new ExpectedTraceRecord(TraceKind.End,       \"System.Web.Http.Controllers\",  \"DefaultHttpControllerTypeResolver\", \"GetControllerTypes\"),\n            new ExpectedTraceRecord(TraceKind.End,       \"System.Web.Http.Controllers\",  \"DefaultHttpControllerSelector\",  \"SelectController\"),\n            new ExpectedTraceRecord(TraceKind.Begin,     \"System.Web.Http.Controllers\",  \"HttpControllerDescriptor\",       \"CreateController\"),\n            new ExpectedTraceRecord(TraceKind.Begin,     \"System.Web.Http.Controllers\",  \"DefaultHttpControllerActivator\", \"Create\"),\n            new ExpectedTraceRecord(TraceKind.End,       \"System.Web.Http.Controllers\",  \"DefaultHttpControllerActivator\", \"Create\"),\n            new ExpectedTraceRecord(TraceKind.End,       \"System.Web.Http.Controllers\",  \"HttpControllerDescriptor\",       \"CreateController\"),\n            new ExpectedTraceRecord(TraceKind.Begin,     \"System.Web.Http.Controllers\",  \"ValuesController\",               \"ExecuteAsync\"),\n            new ExpectedTraceRecord(TraceKind.Begin,    \"System.Web.Http.Action\",       \"ApiControllerActionSelector\",    \"SelectAction\"),\n            new ExpectedTraceRecord(TraceKind.End,      \"System.Web.Http.Action\",       \"ApiControllerActionSelector\",    \"SelectAction\"),\n            new ExpectedTraceRecord(TraceKind.Begin,    \"System.Web.Http.ModelBinding\", \"HttpActionBinding\",              \"ExecuteBindingAsync\"),\n            new ExpectedTraceRecord(TraceKind.Begin,    \"System.Web.Http.ModelBinding\", \"ModelBinderParameterBinding\",    \"ExecuteBindingAsync\"),\n            new ExpectedTraceRecord(TraceKind.End,      \"System.Web.Http.ModelBinding\", \"ModelBinderParameterBinding\",    \"ExecuteBindingAsync\"),\n            new ExpectedTraceRecord(TraceKind.End,      \"System.Web.Http.ModelBinding\", \"HttpActionBinding\",              \"ExecuteBindingAsync\"),\n            new ExpectedTraceRecord(TraceKind.Begin,    \"System.Web.Http.Action\",       \"ApiControllerActionInvoker\",     \"InvokeActionAsync\"),\n            new ExpectedTraceRecord(TraceKind.Begin,    \"System.Web.Http.Action\",       \"ReflectedHttpActionDescriptor\",  \"ExecuteAsync\"),\n            new ExpectedTraceRecord(TraceKind.End,      \"System.Web.Http.Action\",       \"ReflectedHttpActionDescriptor\",  \"ExecuteAsync\"),\n            new ExpectedTraceRecord(TraceKind.Begin,    \"System.Net.Http.Formatting\",   \"DefaultContentNegotiator\",       \"Negotiate\"),\n            new ExpectedTraceRecord(TraceKind.Begin,    \"System.Net.Http.Formatting\",   \"JsonMediaTypeFormatter\",         \"GetPerRequestFormatterInstance\"),\n            new ExpectedTraceRecord(TraceKind.End,      \"System.Net.Http.Formatting\",   \"JsonMediaTypeFormatter\",         \"GetPerRequestFormatterInstance\"),\n            new ExpectedTraceRecord(TraceKind.End,      \"System.Net.Http.Formatting\",   \"DefaultContentNegotiator\",       \"Negotiate\"),\n            new ExpectedTraceRecord(TraceKind.End,      \"System.Web.Http.Action\",       \"ApiControllerActionInvoker\",     \"InvokeActionAsync\"),\n            new ExpectedTraceRecord(TraceKind.End,      \"System.Web.Http.Controllers\",  \"ValuesController\",               \"ExecuteAsync\"),\n            new ExpectedTraceRecord(TraceKind.End,      \"System.Web.Http.MessageHandlers\",  \"DelegatingHandlerProxy\",  \"SendAsync\"),\n            new ExpectedTraceRecord(TraceKind.End,      \"System.Web.Http.Request\",      string.Empty,                     string.Empty),\n            new ExpectedTraceRecord(TraceKind.Begin,    \"System.Net.Http.Formatting\",   \"JsonMediaTypeFormatter\",         \"WriteToStreamAsync\"),\n            new ExpectedTraceRecord(TraceKind.End,      \"System.Net.Http.Formatting\",   \"JsonMediaTypeFormatter\",         \"WriteToStreamAsync\"),\n        };\n\n        [Theory]\n        [PropertyData(\"TestTraceWriters\")]\n        public async Task ValuesController_Behavior_Unchanged_By_Tracing(ITestTraceWriter traceWriter)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"DefaultApi\", \"api/{controller}/{id}\", new { id = RouteParameter.Optional });\n\n            // The null trace writer case is tested as well to verify the\n            // ValuesController works as expected without tracing.\n            if (traceWriter != null)\n            {\n                config.Services.Replace(typeof(ITraceWriter), traceWriter);\n                traceWriter.Start();\n            }\n\n            ValuesController valuesController = new ValuesController();\n\n            using (HttpServer server = new HttpServer(config))\n            {\n                using (HttpClient client = new HttpClient(server))\n                {\n                    if (traceWriter != null)\n                    {\n                        traceWriter.Start();\n                    }\n\n                    // Calls ValuesController.Get()\n                    string uri = _baseAddress + \"/api/Values\";\n                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri);\n                    HttpResponseMessage response = await client.SendAsync(request);\n                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);\n                    string[] expectedGetResponse = valuesController.Get().ToArray();\n                    string[] actualGetResponse = await response.Content.ReadAsAsync<string[]>();\n                    Assert.Equal(expectedGetResponse, actualGetResponse);\n                    if (traceWriter != null)\n                    {\n                        traceWriter.Finish();\n                        Assert.True(traceWriter.DidReceiveTraceRequests);\n                        traceWriter.Start();\n                    }\n\n                    // Calls ValuesController.Get(id) using query string\n                    uri = _baseAddress + \"/api/Values?id=5\";\n                    request = new HttpRequestMessage(HttpMethod.Get, uri);\n                    response = await client.SendAsync(request);\n                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);\n                    string expectedGetQueryStringResponse = valuesController.Get(5);\n                    string actualGetQueryStringResponse = await response.Content.ReadAsAsync<string>();\n                    Assert.Equal(expectedGetQueryStringResponse, actualGetQueryStringResponse);\n                    if (traceWriter != null)\n                    {\n                        traceWriter.Finish();\n                        Assert.True(traceWriter.DidReceiveTraceRequests);\n                        traceWriter.Start();\n                    }\n\n                    // Calls ValuesController.Get(id) using route\n                    uri = _baseAddress + \"/api/Values/5\";\n                    request = new HttpRequestMessage(HttpMethod.Get, uri);\n                    response = await client.SendAsync(request);\n                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);\n                    string expectedGetRouteResponse = valuesController.Get(5);\n                    string actualGetRouteResponse = await response.Content.ReadAsAsync<string>();\n                    Assert.Equal(expectedGetQueryStringResponse, actualGetRouteResponse);\n                    if (traceWriter != null)\n                    {\n                        traceWriter.Finish();\n                        Assert.True(traceWriter.DidReceiveTraceRequests);\n                        traceWriter.Start();\n                    }\n\n                    // Calls ValuesController.Get(id) using query string that causes model binding error\n                    uri = _baseAddress + \"/api/Values?id=x\";\n                    request = new HttpRequestMessage(HttpMethod.Get, uri);\n                    response = await client.SendAsync(request);\n                    Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);\n                    if (traceWriter != null)\n                    {\n                        traceWriter.Finish();\n                        Assert.True(traceWriter.DidReceiveTraceRequests);\n                        traceWriter.Start();\n                    }\n\n                    // Calls ValuesController.Post(value) with no parameters\n                    uri = _baseAddress + \"/api/Values\";\n                    request = new HttpRequestMessage(HttpMethod.Post, uri);\n                    response = await client.SendAsync(request);\n                    Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);\n                    if (traceWriter != null)\n                    {\n                        traceWriter.Finish();\n                        Assert.True(traceWriter.DidReceiveTraceRequests);\n                        traceWriter.Start();\n                    }\n\n                    // Calls ValuesController.Post(value) using query string\n                    uri = _baseAddress + \"/api/Values?value=hello\";\n                    request = new HttpRequestMessage(HttpMethod.Post, uri);\n                    response = await client.SendAsync(request);\n                    Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);\n                    if (traceWriter != null)\n                    {\n                        traceWriter.Finish();\n                        Assert.True(traceWriter.DidReceiveTraceRequests);\n                        traceWriter.Start();\n                    }\n\n                    // Calls ValuesController.Put(id, value) using query strings\n                    uri = _baseAddress + \"/api/Values?id=5&value=hello\";\n                    request = new HttpRequestMessage(HttpMethod.Put, uri);\n                    response = await client.SendAsync(request);\n                    Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);\n                    if (traceWriter != null)\n                    {\n                        traceWriter.Finish();\n                        Assert.True(traceWriter.DidReceiveTraceRequests);\n                        traceWriter.Start();\n                    }\n\n                    // Calls ValuesController.Put(id, value) using route + query string\n                    uri = _baseAddress + \"/api/Values/5?value=hello\";\n                    request = new HttpRequestMessage(HttpMethod.Put, uri);\n                    response = await client.SendAsync(request);\n                    Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);\n                    if (traceWriter != null)\n                    {\n                        traceWriter.Finish();\n                        Assert.True(traceWriter.DidReceiveTraceRequests);\n                        traceWriter.Start();\n                    }\n\n                    // Calls ValuesController.Delete(id) using query string\n                    uri = _baseAddress + \"/api/Values?id=5\";\n                    request = new HttpRequestMessage(HttpMethod.Delete, uri);\n                    response = await client.SendAsync(request);\n                    Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);\n                    if (traceWriter != null)\n                    {\n                        traceWriter.Finish();\n                        Assert.True(traceWriter.DidReceiveTraceRequests);\n                        traceWriter.Start();\n                    }\n\n                    // Calls ValuesController.Delete(id) using route\n                    uri = _baseAddress + \"/api/Values/5\";\n                    request = new HttpRequestMessage(HttpMethod.Delete, uri);\n                    response = await client.SendAsync(request);\n                    Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);\n                    if (traceWriter != null)\n                    {\n                        traceWriter.Finish();\n                        Assert.True(traceWriter.DidReceiveTraceRequests);\n                    }\n                }\n            }\n        }\n\n        [Fact]\n        public async Task ValuesController_Get_Id_Writes_Expected_Traces()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"DefaultApi\", \"api/{controller}/{id}\", new { id = RouteParameter.Optional });\n            Mock<DelegatingHandler> customMessageHandler = new Mock<DelegatingHandler>() { CallBase = true };\n            config.MessageHandlers.Add(customMessageHandler.Object);\n            MemoryTraceWriter traceWriter = new MemoryTraceWriter();\n            config.Services.Replace(typeof(ITraceWriter), traceWriter);\n\n            using (HttpServer server = new HttpServer(config))\n            {\n                using (HttpClient client = new HttpClient(server))\n                {\n                    traceWriter.Start();\n\n                    // Calls ValueController.Get(id) using query string\n                    string uri = _baseAddress + \"/api/Values?id=5\";\n                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri);\n                    HttpResponseMessage response = await client.SendAsync(request);\n                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);\n                    traceWriter.Finish();\n\n                    IList<string> missingTraces = MissingTraces(ExpectedTraceRecords, traceWriter.Records);\n                    Assert.True(missingTraces.Count == 0,\n                                string.Format(\"These expected traces were missing:{0}    {1}\",\n                                                Environment.NewLine, string.Join(Environment.NewLine + \"    \", missingTraces)));\n\n                    IList<string> unexpectedTraces = UnexpectedTraces(ExpectedTraceRecords, traceWriter.Records);\n                    Assert.True(unexpectedTraces.Count == 0,\n                                string.Format(\"These traces were not expected:{0}    {1}\",\n                                                Environment.NewLine, string.Join(Environment.NewLine + \"    \", unexpectedTraces)));\n                }\n            }\n        }\n\n        [Fact]\n        public async Task ValuesController_Get_Id_Writes_Expected_Traces_InTheCorrectOrder()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"DefaultApi\", \"api/{controller}/{id}\", new { id = RouteParameter.Optional });\n            Mock<DelegatingHandler> customMessageHandler = new Mock<DelegatingHandler>() { CallBase = true };\n            config.MessageHandlers.Add(customMessageHandler.Object);\n            MemoryTraceWriter traceWriter = new MemoryTraceWriter();\n            config.Services.Replace(typeof(ITraceWriter), traceWriter);\n\n            using (HttpServer server = new HttpServer(config))\n            {\n                using (HttpClient client = new HttpClient(server))\n                {\n                    traceWriter.Start();\n\n                    // Calls ValueController.Get(id) using query string\n                    string uri = _baseAddress + \"/api/Values?id=5\";\n                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri);\n                    HttpResponseMessage response = await client.SendAsync(request);\n                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);\n                    traceWriter.Finish();\n\n                    Assert.True(ConfirmTracingOrder(ExpectedTraceRecordOrder, traceWriter.Records));\n                }\n            }\n        }\n        // Returns a list of strings describing all of the expected trace records that were not\n        // actually traced.\n        // If you experience test failures from this list, it means someone stopped tracing or\n        // changed the content of what was traced.\n        // Update the ExpectedTraceRecords property to reflect what is expected.\n        private static IList<string> MissingTraces(IList<ExpectedTraceRecord> expectedRecords, IList<TraceRecord> actualRecords)\n        {\n            List<string> missing = new List<string>();\n\n            foreach (ExpectedTraceRecord expectedRecord in expectedRecords)\n            {\n                TraceRecord beginTrace = actualRecords.SingleOrDefault(r =>\n                    String.Equals(r.Category, expectedRecord.Category, StringComparison.OrdinalIgnoreCase) &&\n                    String.Equals(r.Operator, expectedRecord.OperatorName, StringComparison.OrdinalIgnoreCase) &&\n                    String.Equals(r.Operation, expectedRecord.OperationName, StringComparison.OrdinalIgnoreCase) &&\n                    r.Kind == TraceKind.Begin\n                    );\n\n                if (beginTrace == null)\n                {\n                    missing.Add(string.Format(\"Begin category={0}, operator={1}, operation={2}\",\n                                    expectedRecord.Category, expectedRecord.OperatorName, expectedRecord.OperationName));\n                }\n\n                TraceRecord endTrace = actualRecords.SingleOrDefault(r =>\n                    String.Equals(r.Category, expectedRecord.Category, StringComparison.OrdinalIgnoreCase) &&\n                    String.Equals(r.Operator, expectedRecord.OperatorName, StringComparison.OrdinalIgnoreCase) &&\n                    String.Equals(r.Operation, expectedRecord.OperationName, StringComparison.OrdinalIgnoreCase) &&\n                    r.Kind == TraceKind.End\n                    );\n\n                if (endTrace == null)\n                {\n                    missing.Add(string.Format(\"End category={0}, operator={1}, operation={2}\",\n                                    expectedRecord.Category, expectedRecord.OperatorName, expectedRecord.OperationName));\n                }\n            }\n\n            return missing;\n        }\n\n        // Returns a list of strings of trace records we did not expect.\n        // If you experience failures from this list, it means someone added new traces\n        // or changed the contents of the traces.\n        // Update the ExpectedTraceRecords property to reflect what is expected.\n        private static IList<string> UnexpectedTraces(IList<ExpectedTraceRecord> expectedRecords, IList<TraceRecord> actualRecords)\n        {\n            List<string> unexpected = new List<string>();\n\n            foreach (TraceRecord actualRecord in actualRecords)\n            {\n                // Ignore record of a ReflectionTypeLoadException to allow test to succeed in Visual Studio. The record is an\n                // artifact specific to testing in VS. (Attempting to load all types from xunit.runner.visualstudio.testadapter.dll\n                // fails with recent xUnit.net packages. The assembly references Microsoft.VisualStudio.TestPlatform.ObjectModel.dll\n                // which is not available with xUnit.net 2.0.x.)\n                //\n                // Similarly, ignore records for the same exception to allow test to succeed when using the xUnit MSBuild runner.\n                // In that case, missing types may come from System.Web and Microsoft.Build.Utilities.v4.0 as well as xunit.runner.msbuild.net452.\n                if (actualRecord.Operation == null &&\n                    actualRecord.Exception is ReflectionTypeLoadException &&\n                    actualRecord.Message != null &&\n                    (actualRecord.Message.StartsWith(\n                         \"Exception thrown while getting types from 'xunit.runner.visualstudio.testadapter, \",\n                         StringComparison.Ordinal) ||\n                     actualRecord.Message.StartsWith(\n                         \"Exception thrown while getting types from 'xunit.runner.msbuild.\",\n                         StringComparison.Ordinal) ||\n                     actualRecord.Message.StartsWith(\n                         \"Exception thrown while getting types from 'System.Web, \",\n                         StringComparison.Ordinal) ||\n                     actualRecord.Message.StartsWith(\n                         \"Exception thrown while getting types from 'Microsoft.Build.Utilities.\",\n                         StringComparison.Ordinal)))\n                {\n                    continue;\n                }\n\n                ExpectedTraceRecord expectedTrace = expectedRecords.FirstOrDefault(r =>\n                    String.Equals(r.Category, actualRecord.Category, StringComparison.OrdinalIgnoreCase) &&\n                    String.Equals(r.OperatorName, actualRecord.Operator, StringComparison.OrdinalIgnoreCase) &&\n                    String.Equals(r.OperationName, actualRecord.Operation, StringComparison.OrdinalIgnoreCase));\n\n                if (expectedTrace == null)\n                {\n                    unexpected.Add(string.Format(\"kind={0} category={1}, operator={2}, operation={3}, message={4}\",\n                        actualRecord.Kind, actualRecord.Category, actualRecord.Operator, actualRecord.Operation, actualRecord.Message));\n                }\n            }\n\n            return unexpected;\n        }\n\n        // Returns true if the tracing records are in the correct order, else returns false.\n        private static bool ConfirmTracingOrder(IList<ExpectedTraceRecord> expectedRecords, IList<TraceRecord> actualRecords)\n        {\n            int traceBeginPos = 0;\n            foreach (ExpectedTraceRecord expectedRecord in expectedRecords)\n            {\n                TraceRecord beginTrace = actualRecords.SingleOrDefault(r =>\n                    String.Equals(r.Category, expectedRecord.Category, StringComparison.OrdinalIgnoreCase) &&\n                    String.Equals(r.Operator, expectedRecord.OperatorName, StringComparison.OrdinalIgnoreCase) &&\n                    String.Equals(r.Operation, expectedRecord.OperationName, StringComparison.OrdinalIgnoreCase) &&\n                    object.Equals(r.Kind, expectedRecord.TraceKind)\n                    );\n\n                // Ignore record of a ReflectionTypeLoadException to allow test to succeed in Visual Studio. The record is an\n                // artifact specific to testing in VS. (Attempting to load all types from xunit.runner.visualstudio.testadapter.dll\n                // fails with recent xUnit.net packages. The assembly references Microsoft.VisualStudio.TestPlatform.ObjectModel.dll\n                // which is not available with xUnit.net 2.0.x.)\n                //\n                // Similarly, ignore records for the same exception to allow test to succeed when using the xUnit MSBuild runner.\n                // In that case, missing types may come from System.Web and Microsoft.Build.Utilities.v4.0 as well as xunit.runner.msbuild.net452.\n                var actualRecord = actualRecords.ElementAtOrDefault(traceBeginPos);\n                while (actualRecord != null &&\n                    actualRecord.Operation == null &&\n                    actualRecord.Exception is ReflectionTypeLoadException &&\n                    actualRecord.Message != null &&\n                    (actualRecord.Message.StartsWith(\n                         \"Exception thrown while getting types from 'xunit.runner.visualstudio.testadapter, \",\n                         StringComparison.Ordinal) ||\n                     actualRecord.Message.StartsWith(\n                         \"Exception thrown while getting types from 'xunit.runner.msbuild.\",\n                         StringComparison.Ordinal) ||\n                     actualRecord.Message.StartsWith(\n                         \"Exception thrown while getting types from 'System.Web, \",\n                         StringComparison.Ordinal) ||\n                     actualRecord.Message.StartsWith(\n                         \"Exception thrown while getting types from 'Microsoft.Build.Utilities.\",\n                         StringComparison.Ordinal)))\n                {\n                    traceBeginPos++;\n                    actualRecord = actualRecords.ElementAtOrDefault(traceBeginPos);\n                }\n\n                if (!object.ReferenceEquals(beginTrace, actualRecord))\n                {\n                    return false;\n                }\n\n                traceBeginPos++;\n            }\n            return true;\n        }\n    }\n\n    public class ExpectedTraceRecord\n    {\n        public ExpectedTraceRecord(string category, string operatorName, string operationName)\n        {\n            Category = category;\n            OperatorName = operatorName;\n            OperationName = operationName;\n        }\n\n        public ExpectedTraceRecord(TraceKind kind, string category, string operatorName, string operationName)\n        {\n            TraceKind = kind;\n            Category = category;\n            OperatorName = operatorName;\n            OperationName = operationName;\n        }\n\n        public string Category { get; private set; }\n        public TraceKind TraceKind { get; private set; }\n        public string OperatorName { get; private set; }\n        public string OperationName { get; private set; }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/Util/ApiExplorerHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Description;\nusing System.Web.Http.Dispatcher;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.ApiExplorer\n{\n    public static class ApiExplorerHelper\n    {\n        public static void VerifyApiDescriptions(Collection<ApiDescription> apiDescriptions, List<object> expectedResults)\n        {\n            Assert.Equal(expectedResults.Count, apiDescriptions.Count);\n            ApiDescription[] sortedDescriptions = apiDescriptions.OrderBy(description => description.ID).ToArray();\n            object[] sortedExpectedResults = expectedResults.OrderBy(r =>\n            {\n                dynamic expectedResult = r;\n                HttpMethod expectedHttpMethod = expectedResult.HttpMethod;\n                string expectedRelativePath = expectedResult.RelativePath;\n                return expectedHttpMethod + expectedRelativePath;\n            }).ToArray();\n\n            for (int i = 0; i < sortedDescriptions.Length; i++)\n            {\n                dynamic expectedResult = sortedExpectedResults[i];\n                ApiDescription matchingDescription = sortedDescriptions[i];\n                Assert.Equal(expectedResult.HttpMethod, matchingDescription.HttpMethod);\n                Assert.Equal(expectedResult.RelativePath, matchingDescription.RelativePath, ignoreCase: true);\n                Assert.Equal(expectedResult.HasRequestFormatters, matchingDescription.SupportedRequestBodyFormatters.Count > 0);\n                Assert.Equal(expectedResult.HasResponseFormatters, matchingDescription.SupportedResponseFormatters.Count > 0);\n                Assert.Equal(expectedResult.NumberOfParameters, matchingDescription.ParameterDescriptions.Count);\n            }\n        }\n\n        public static DefaultHttpControllerSelector GetStrictControllerSelector(HttpConfiguration config, params Type[] controllerTypes)\n        {\n            Dictionary<string, HttpControllerDescriptor> controllerMapping = new Dictionary<string, HttpControllerDescriptor>();\n            foreach (Type controllerType in controllerTypes)\n            {\n                string controllerName = controllerType.Name.Substring(0, controllerType.Name.Length - DefaultHttpControllerSelector.ControllerSuffix.Length);\n                var controllerDescriptor = new HttpControllerDescriptor(config, controllerName, controllerType);\n                controllerMapping.Add(controllerDescriptor.ControllerName, controllerDescriptor);\n            }\n\n            Mock<DefaultHttpControllerSelector> factory = new Mock<DefaultHttpControllerSelector>(config);\n            factory.Setup(f => f.GetControllerMapping()).Returns(controllerMapping);\n            return factory.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/Util/ContextUtil.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.Routing;\nusing Moq;\n\n// TODO: move this class to TestCommon after it has been refactored\nnamespace System.Web.Http\n{\n    public static class ContextUtil\n    {\n        public static HttpControllerContext CreateControllerContext()\n        {\n            return CreateControllerContext(null, null, null);\n        }\n\n        public static HttpControllerContext CreateControllerContext(HttpConfiguration configuration)\n        {\n            return CreateControllerContext(configuration, null, null);\n        }\n\n        public static HttpControllerContext CreateControllerContext(HttpRequestMessage request)\n        {\n            return CreateControllerContext(null, null, request);\n        }\n\n        public static HttpControllerContext CreateControllerContext(HttpConfiguration configuration, IHttpRouteData routeData)\n        {\n            return CreateControllerContext(configuration, routeData, null);\n        }\n\n        public static HttpControllerContext CreateControllerContext(IHttpRouteData routeData, HttpRequestMessage request)\n        {\n            return CreateControllerContext(null, routeData, request);\n        }\n\n        public static HttpControllerContext CreateControllerContext(HttpConfiguration configuration, HttpRequestMessage request)\n        {\n            return CreateControllerContext(configuration, null, request);\n        }\n\n        public static HttpControllerContext CreateControllerContext(HttpConfiguration configuration, IHttpRouteData routeData, HttpRequestMessage request)\n        {\n            HttpConfiguration config = configuration ?? new HttpConfiguration();\n            IHttpRouteData route = routeData ?? new HttpRouteData(new HttpRoute());\n            HttpRequestMessage req = request ?? new HttpRequestMessage();\n            req.SetConfiguration(config);\n            req.SetRouteData(route);\n            return new HttpControllerContext(config, route, req) { ControllerDescriptor = new HttpControllerDescriptor(config) };\n        }\n\n        public static HttpActionContext CreateActionContext(HttpControllerContext controllerContext = null, HttpActionDescriptor actionDescriptor = null)\n        {\n            HttpControllerContext context = controllerContext ?? ContextUtil.CreateControllerContext();\n            HttpActionDescriptor descriptor = actionDescriptor ?? new Mock<HttpActionDescriptor>() { CallBase = true }.Object;\n\n            if (descriptor.Configuration == null)\n            {\n                descriptor.Configuration = controllerContext.Configuration;\n            }\n\n            if (context.ControllerDescriptor == null)\n            {\n                context.ControllerDescriptor = new HttpControllerDescriptor(descriptor.Configuration);\n            }\n\n            if (descriptor.ControllerDescriptor == null)\n            {\n                descriptor.ControllerDescriptor = context.ControllerDescriptor;\n            }\n\n            return new HttpActionContext(context, descriptor);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/Util/ConvertToStreamMessageHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.Util\n{\n    internal class ConvertToStreamMessageHandler : DelegatingHandler\n    {\n        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n        {\n            HttpContent requestContent = await ToStreamContent(request.Content);\n            request.Content = requestContent;\n            HttpResponseMessage response = await base.SendAsync(request, cancellationToken);\n            HttpContent responseContent = await ToStreamContent(response.Content);\n            response.Content = responseContent;\n            return response;\n        }\n\n        private static Task<HttpContent> ToStreamContent(HttpContent content)\n        {\n            ObjectContent objectContent = content as ObjectContent;\n            if (objectContent != null)\n            {\n                return ToStreamContent(objectContent);\n            }\n            else\n            {\n                return Task.FromResult(content);\n            }\n        }\n\n        private static async Task<HttpContent> ToStreamContent(ObjectContent content)\n        {\n            Stream stream = await content.ReadAsStreamAsync();\n            StreamContent streamContent = new StreamContent(stream);\n            foreach (var header in content.Headers)\n            {\n                streamContent.Headers.TryAddWithoutValidation(header.Key, header.Value);\n            }\n\n            return streamContent;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/Util/HttpServerTestBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Http.Util;\n\nnamespace System.Web.Http\n{\n    public abstract class HttpServerTestBase\n    {\n        protected HttpServerTestBase(string baseAddress)\n        {\n            SetupHost(baseAddress);\n        }\n\n        protected HttpServer Server { get; private set; }\n\n        protected HttpConfiguration Configuration { get; private set; }\n\n        protected string BaseAddress { get; private set; }\n\n        protected HttpClient Client { get; private set; }\n\n        protected abstract void ApplyConfiguration(HttpConfiguration configuration);\n\n        private void SetupHost(string baseAddress)\n        {\n            BaseAddress = baseAddress;\n\n            Configuration = new HttpConfiguration();\n            Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;\n            Configuration.MessageHandlers.Add(new ConvertToStreamMessageHandler());\n            ApplyConfiguration(Configuration);\n\n            Server = new HttpServer(Configuration);\n            Client = new HttpClient(Server);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/Util/ScenarioHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http\n{\n    public static class ScenarioHelper\n    {\n        public static string BaseAddress = \"http://localhost\";\n        public static async Task RunTestAsync(\n            string controllerName,\n            string routeSuffix,\n            HttpRequestMessage request,\n            Func<HttpResponseMessage, Task> assert,\n            Action<HttpConfiguration> configurer = null)\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration() { IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always };\n\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}\" + routeSuffix, new { controller = controllerName });\n            if (configurer != null)\n            {\n                configurer(config);\n            }\n            HttpServer server = new HttpServer(config);\n            HttpMessageInvoker invoker = new HttpMessageInvoker(server);\n            HttpResponseMessage response = null;\n            try\n            {\n                // Act\n                response = await invoker.SendAsync(request, CancellationToken.None);\n\n                // Assert\n                await assert(response);\n            }\n            finally\n            {\n                request.Dispose();\n                if (response != null)\n                {\n                    response.Dispose();\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Integration.Test/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Castle.Core\" version=\"5.1.1\" targetFramework=\"net462\" />\n  <package id=\"Moq\" version=\"4.18.4\" targetFramework=\"net462\" />\n  <package id=\"Newtonsoft.Json\" version=\"13.0.1\" targetFramework=\"net462\" />\n  <package id=\"xunit\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.abstractions\" version=\"2.0.3\" targetFramework=\"net462\" />\n  <package id=\"xunit.analyzers\" version=\"1.1.0\" targetFramework=\"net462\" />\n  <package id=\"xunit.assert\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.execution\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.runner.visualstudio\" version=\"2.4.5\" targetFramework=\"net462\" developmentDependency=\"true\" />\n</packages>"
  },
  {
    "path": "test/System.Web.Http.Owin.Test/ExceptionHandling/DefaultExceptionHandlerTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Results;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Owin.ExceptionHandling\n{\n    public class DefaultExceptionHandlerTests\n    {\n        [Fact]\n        public void HandleAsync_IfContextIsNull_Throws()\n        {\n            // Arrange\n            IExceptionHandler product = CreateProductUnderTest();\n            ExceptionHandlerContext context = null;\n            CancellationToken cancellationToken = CancellationToken.None;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => product.HandleAsync(context, cancellationToken), \"context\");\n        }\n\n        [Fact]\n        public void HandleAsync_IfRequestIsNull_Throws()\n        {\n            // Arrange\n            IExceptionHandler product = CreateProductUnderTest();\n            ExceptionHandlerContext context = new ExceptionHandlerContext(new ExceptionContext(CreateException(), ExceptionCatchBlocks.HttpServer));\n\n            Assert.Null(context.ExceptionContext.Request); // Guard\n            CancellationToken cancellationToken = CancellationToken.None;\n\n            // Act & Assert\n            Assert.ThrowsArgument(() => product.HandleAsync(context, cancellationToken), \"context\",\n                \"ExceptionContext.Request must not be null.\");\n        }\n\n        [Fact]\n        public async Task HandleAsync_HandlesExceptionViaCreateErrorResponse()\n        {\n            IExceptionHandler product = CreateProductUnderTest();\n\n            // Arrange\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                expectedRequest.SetRequestContext(new HttpRequestContext { IncludeErrorDetail = true });\n                ExceptionHandlerContext context = CreateValidContext(expectedRequest);\n                CancellationToken cancellationToken = CancellationToken.None;\n\n                // Act\n                await product.HandleAsync(context, cancellationToken);\n\n                // Assert\n                IHttpActionResult result = context.Result;\n                ResponseMessageResult typedResult = Assert.IsType<ResponseMessageResult>(result);\n                using (HttpResponseMessage response = typedResult.Response)\n                {\n                    Assert.NotNull(response);\n\n                    using (HttpResponseMessage expectedResponse = expectedRequest.CreateErrorResponse(\n                        HttpStatusCode.InternalServerError, context.ExceptionContext.Exception))\n                    {\n                        AssertErrorResponse(expectedResponse, response);\n                    }\n\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        private static void AssertErrorResponse(HttpResponseMessage expected, HttpResponseMessage actual)\n        {\n            Assert.NotNull(expected); // Guard\n            ObjectContent<HttpError> expectedContent = Assert.IsType<ObjectContent<HttpError>>(expected.Content); // Guard\n            Assert.NotNull(expectedContent.Formatter); // Guard\n\n            Assert.NotNull(actual);\n            Assert.Equal(expected.StatusCode, actual.StatusCode);\n            ObjectContent<HttpError> actualContent = Assert.IsType<ObjectContent<HttpError>>(actual.Content);\n            Assert.NotNull(actualContent.Formatter);\n            Assert.Same(expectedContent.Formatter.GetType(), actualContent.Formatter.GetType());\n            Assert.Equal(expectedContent.Value, actualContent.Value);\n            Assert.Same(expected.RequestMessage, actual.RequestMessage);\n        }\n\n        private static ExceptionHandlerContext CreateContext(ExceptionContext exceptionContext)\n        {\n            return new ExceptionHandlerContext(exceptionContext);\n        }\n\n        private static Exception CreateException()\n        {\n            return new NotSupportedException();\n        }\n\n        private static DefaultExceptionHandler CreateProductUnderTest()\n        {\n            return new DefaultExceptionHandler();\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private static ExceptionHandlerContext CreateValidContext(HttpRequestMessage request)\n        {\n            return CreateContext(new ExceptionContext(CreateException(),\n                                                      ExceptionCatchBlocks.HttpServer,\n                                                      request));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Owin.Test/ExceptionHandling/EmptyExceptionLoggerTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.ExceptionHandling;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Owin.ExceptionHandling\n{\n    public class EmptyExceptionLoggerTests\n    {\n        [Fact]\n        public void LogAsync_ReturnsCompletedTask()\n        {\n            // Arrange\n            IExceptionLogger product = CreateProductUnderTest();\n            ExceptionLoggerContext context = CreateContext();\n            CancellationToken cancellationToken = CancellationToken.None;\n\n            // Act\n            Task task = product.LogAsync(context, cancellationToken);\n\n            // Assert\n            Assert.NotNull(task);\n            Assert.Equal(TaskStatus.RanToCompletion, task.Status);\n        }\n\n        private static ExceptionLoggerContext CreateContext()\n        {\n            return new ExceptionLoggerContext(new ExceptionContext(new Exception(), ExceptionCatchBlocks.HttpServer));\n        }\n\n        private static EmptyExceptionLogger CreateProductUnderTest()\n        {\n            return new EmptyExceptionLogger();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Owin.Test/HostAuthenticationAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Filters;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Owin\n{\n    public class HostAuthenticationAttributeTest\n    {\n        [Fact]\n        public void AttributeUsageValidOn_IsClassOrMethod()\n        {\n            // Act\n            AttributeUsageAttribute usage = (AttributeUsageAttribute)Attribute.GetCustomAttribute(\n                typeof(HostAuthenticationAttribute), typeof(AttributeUsageAttribute));\n\n            // Assert\n            Assert.NotNull(usage);\n            Assert.Equal(AttributeTargets.Class | AttributeTargets.Method, usage.ValidOn);\n        }\n\n        [Fact]\n        public void AttributeUsageAllowMultiple_IsTrue()\n        {\n            // Act\n            AttributeUsageAttribute usage = (AttributeUsageAttribute)Attribute.GetCustomAttribute(\n                typeof(HostAuthenticationAttribute), typeof(AttributeUsageAttribute));\n\n            // Assert\n            Assert.NotNull(usage);\n            Assert.True(usage.AllowMultiple);\n        }\n\n        [Fact]\n        public void Constructor_ThrowsWhenInnerFilterIsNull()\n        {\n            // Arrange\n            IAuthenticationFilter innerFilter = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { var ignore = CreateProductUnderTest(innerFilter); }, \"innerFilter\");\n        }\n\n        [Fact]\n        public void InnerFilter_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            IAuthenticationFilter expectedInnerFilter = CreateDummyFilter();\n            HostAuthenticationAttribute product = CreateProductUnderTest(expectedInnerFilter);\n\n            // Act\n            IAuthenticationFilter innerFilter = product.InnerFilter;\n\n            // Assert\n            Assert.Same(expectedInnerFilter, innerFilter);\n        }\n\n        [Fact]\n        public void AllowMultiple_ReturnsTrue()\n        {\n            // Arrange\n            IAuthenticationFilter innerFilter = CreateDummyFilter();\n            IAuthenticationFilter product = CreateProductUnderTest(innerFilter);\n\n            // Act\n            bool allowMultiple = product.AllowMultiple;\n\n            // Assert\n            Assert.True(allowMultiple);\n        }\n\n        [Fact]\n        public void AuthenticateAsync_DelegatesToInnerFilter()\n        {\n            // Arrange\n            Task expectedTask = CreateTask();\n            HttpAuthenticationContext context = CreateAuthenticationContext();\n            CancellationToken cancellationToken = CreateCancellationToken();\n            Mock<IAuthenticationFilter> spyMock = new Mock<IAuthenticationFilter>(MockBehavior.Strict);\n            spyMock.Setup(f => f.AuthenticateAsync(context, cancellationToken)).Returns(expectedTask);\n            IAuthenticationFilter spy = spyMock.Object;\n            IAuthenticationFilter product = CreateProductUnderTest(spy);\n\n            // Act\n            Task task = product.AuthenticateAsync(context, cancellationToken);\n\n            // Assert\n            Assert.Same(expectedTask, task);\n        }\n\n        [Fact]\n        public void ChallengeAsync_DelegatesToInnerFilter()\n        {\n            // Arrange\n            Task expectedTask = CreateTask();\n            HttpAuthenticationChallengeContext context = CreateChallengeContext();\n            CancellationToken cancellationToken = CreateCancellationToken();\n            Mock<IAuthenticationFilter> spyMock = new Mock<IAuthenticationFilter>(MockBehavior.Strict);\n            spyMock.Setup(f => f.ChallengeAsync(context, cancellationToken)).Returns(expectedTask);\n            IAuthenticationFilter spy = spyMock.Object;\n            IAuthenticationFilter product = CreateProductUnderTest(spy);\n\n            // Act\n            Task task = product.ChallengeAsync(context, cancellationToken);\n\n            // Assert\n            Assert.Same(expectedTask, task);\n        }\n\n        [Fact]\n        public void ConstructorWithString_ThrowsWhenAuthenticationTypeIsNull()\n        {\n            // Arrange\n            string authenticationType = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { var ignore = CreateProductUnderTest(authenticationType); },\n                \"authenticationType\");\n        }\n\n        [Fact]\n        public void InnerFilter_IsHostAuthenticationFilter_WhenUsingConstructorWithString()\n        {\n            // Arrange\n            string expectedAuthenticationType = \"Ignore\";\n            HostAuthenticationAttribute product = CreateProductUnderTest(expectedAuthenticationType);\n\n            // Act\n            IAuthenticationFilter innerFilter = product.InnerFilter;\n\n            // Assert\n            HostAuthenticationFilter typedInnerFilter = Assert.IsType<HostAuthenticationFilter>(innerFilter);\n            Assert.Same(expectedAuthenticationType, typedInnerFilter.AuthenticationType);\n        }\n\n        [Fact]\n        public void AuthenticationType_IsSpecifiedInstance_WhenUsingConstructorWithString()\n        {\n            // Arrange\n            string expectedAuthenticationType = \"Ignore\";\n            HostAuthenticationAttribute product = CreateProductUnderTest(expectedAuthenticationType);\n\n            // Act\n            string authenticationType = product.AuthenticationType;\n\n            // Assert\n            Assert.Same(expectedAuthenticationType, authenticationType);\n        }\n\n        private static HttpAuthenticationContext CreateAuthenticationContext()\n        {\n            return new HttpAuthenticationContext(new HttpActionContext(), CreateDummyPrincipal());\n        }\n\n        private static CancellationToken CreateCancellationToken()\n        {\n            return new CancellationToken(true);\n        }\n\n        private static HttpAuthenticationChallengeContext CreateChallengeContext()\n        {\n            return new HttpAuthenticationChallengeContext(new HttpActionContext(), CreateDummyActionResult());\n        }\n\n        private static IHttpActionResult CreateDummyActionResult()\n        {\n            return new Mock<IHttpActionResult>(MockBehavior.Strict).Object;\n        }\n\n        private static IAuthenticationFilter CreateDummyFilter()\n        {\n            return new Mock<IAuthenticationFilter>(MockBehavior.Strict).Object;\n        }\n\n        private static IPrincipal CreateDummyPrincipal()\n        {\n            return new Mock<IPrincipal>(MockBehavior.Strict).Object;\n        }\n\n        private static HostAuthenticationAttribute CreateProductUnderTest(string authenticationType)\n        {\n            return new HostAuthenticationAttribute(authenticationType);\n        }\n\n        private static HostAuthenticationAttribute CreateProductUnderTest(IAuthenticationFilter innerFilter)\n        {\n            return new HostAuthenticationAttribute(innerFilter);\n        }\n\n        private static Task CreateTask()\n        {\n            return Task.FromResult<object>(null);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Owin.Test/HostAuthenticationFilterTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Security.Claims;\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Filters;\nusing Microsoft.Owin;\nusing Microsoft.Owin.Security;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Owin\n{\n    public class HostAuthenticationFilterTest\n    {\n        private const string ChallengeKey = \"security.Challenge\";\n\n        [Fact]\n        public void Constructor_Throws_WhenAuthenticationTypeIsNull()\n        {\n            // Arrange\n            string authenticationType = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { var ignore = CreateProductUnderTest(authenticationType); },\n                \"authenticationType\");\n        }\n\n        [Fact]\n        public void AuthenticationType_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            string expectedAuthenticationType = \"AuthenticationType\";\n            HostAuthenticationFilter filter = CreateProductUnderTest(expectedAuthenticationType);\n\n            // Act\n            string authenticationType = filter.AuthenticationType;\n\n            // Assert\n            Assert.Same(expectedAuthenticationType, authenticationType);\n        }\n\n        [Fact]\n        public void AllowMultiple_ReturnsTrue()\n        {\n            // Arrange\n            IAuthenticationFilter filter = CreateProductUnderTest();\n\n            // Act\n            bool allowMultiple = filter.AllowMultiple;\n\n            // Assert\n            Assert.True(allowMultiple);\n        }\n\n        [Fact]\n        public async Task AuthenticateAsync_SetsClaimsPrincipal_WhenOwinAuthenticateReturnsIdentity()\n        {\n            // Arrange\n            string authenticationType = \"AuthenticationType\";\n            IAuthenticationFilter filter = CreateProductUnderTest(authenticationType);\n            IIdentity expectedIdentity = CreateDummyIdentity();\n            IAuthenticationManager authenticationManager = CreateAuthenticationManager((a) =>\n                {\n                    AuthenticateResult result;\n\n                    if (a == authenticationType)\n                    {\n                        result = new AuthenticateResult(expectedIdentity, new AuthenticationProperties(), new AuthenticationDescription());\n                    }\n                    else\n                    {\n                        result = null;\n                    }\n\n                    return Task.FromResult(result);\n                });\n            IOwinContext owinContext = CreateOwinContext(authenticationManager);\n            HttpAuthenticationContext context;\n\n            using (HttpRequestMessage request = CreateRequest(owinContext))\n            {\n                context = CreateAuthenticationContext(request);\n\n                // Act\n                await filter.AuthenticateAsync(context, CancellationToken.None);\n            }\n\n            // Assert\n            Assert.Null(context.ErrorResult);\n            IPrincipal principal = context.Principal;\n            ClaimsPrincipal claimsPrincipal = Assert.IsType<ClaimsPrincipal>(principal);\n            IIdentity identity = claimsPrincipal.Identity;\n            Assert.Same(expectedIdentity, identity);\n        }\n\n        [Fact]\n        public async Task AuthenticateAsync_SetsNoPrincipalOrError_WhenOwinAuthenticateReturnsNullResult()\n        {\n            // Arrange\n            string authenticationType = \"AuthenticationType\";\n            IAuthenticationFilter filter = CreateProductUnderTest(authenticationType);\n            IIdentity expectedIdentity = CreateDummyIdentity();\n            IAuthenticationManager authenticationManager = CreateAuthenticationManager(\n                (ignore1) => Task.FromResult<AuthenticateResult>(null));\n            IOwinContext owinContext = CreateOwinContext(authenticationManager);\n            IPrincipal expectedPrincipal = CreateDummyPrincipal();\n\n            HttpAuthenticationContext context;\n\n            using (HttpRequestMessage request = CreateRequest(owinContext))\n            {\n                context = CreateAuthenticationContext(request, expectedPrincipal);\n\n                // Act\n                await filter.AuthenticateAsync(context, CancellationToken.None);\n            }\n\n            // Assert\n            Assert.Null(context.ErrorResult);\n            Assert.Same(expectedPrincipal, context.Principal);\n        }\n\n        [Fact]\n        public async Task AuthenticateAsync_SetsNoPrincipalOrError_WhenOwinAuthenticateReturnsNullIdentity()\n        {\n            // Arrange\n            string authenticationType = \"AuthenticationType\";\n            IAuthenticationFilter filter = CreateProductUnderTest(authenticationType);\n            IIdentity expectedIdentity = CreateDummyIdentity();\n            IAuthenticationManager authenticationManager = CreateAuthenticationManager(\n                (ignore1) => Task.FromResult(new AuthenticateResult(null, new AuthenticationProperties(), new AuthenticationDescription())));\n            IOwinContext owinContext = CreateOwinContext(authenticationManager);\n            IPrincipal expectedPrincipal = CreateDummyPrincipal();\n\n            HttpAuthenticationContext context;\n\n            using (HttpRequestMessage request = CreateRequest(owinContext))\n            {\n                context = CreateAuthenticationContext(request, expectedPrincipal);\n\n                // Act\n                await filter.AuthenticateAsync(context, CancellationToken.None);\n            }\n\n            // Assert\n            Assert.Null(context.ErrorResult);\n            Assert.Same(expectedPrincipal, context.Principal);\n        }\n\n        [Fact]\n        public Task AuthenticateAsync_Throws_WhenContextIsNull()\n        {\n            // Arrange\n            IAuthenticationFilter filter = CreateProductUnderTest();\n\n            // Act & Assert\n            return Assert.ThrowsArgumentNullAsync(\n                () => filter.AuthenticateAsync(null, CancellationToken.None),\n                \"context\");\n        }\n\n        [Fact]\n        public Task AuthenticateAsync_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            IAuthenticationFilter filter = CreateProductUnderTest();\n            HttpAuthenticationContext context = CreateAuthenticationContext();\n            Assert.Null(context.Request);\n\n            // Act & Assert\n            return Assert.ThrowsAsync<InvalidOperationException>(\n                () => filter.AuthenticateAsync(context, CancellationToken.None),\n                \"HttpAuthenticationContext.Request must not be null.\");\n        }\n\n        [Fact]\n        public async Task AuthenticateAsync_Throws_WhenOwinContextIsNull()\n        {\n            // Arrange\n            IAuthenticationFilter filter = CreateProductUnderTest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpAuthenticationContext context = CreateAuthenticationContext(request);\n\n                // Act & Assert\n                await Assert.ThrowsAsync<InvalidOperationException>(\n                    () => filter.AuthenticateAsync(context, CancellationToken.None),\n                    \"No OWIN authentication manager is associated with the request.\");\n            }\n        }\n\n        [Fact]\n        public async Task AuthenticateAsync_Throws_WhenAuthenticationManagerIsNull()\n        {\n            // Arrange\n            IAuthenticationFilter filter = CreateProductUnderTest();\n            IOwinContext owinContext = CreateOwinContext(null);\n\n            using (HttpRequestMessage request = CreateRequest(owinContext))\n            {\n                HttpAuthenticationContext context = CreateAuthenticationContext(request);\n\n                // Act & Assert\n                await Assert.ThrowsAsync<InvalidOperationException>(\n                    () => filter.AuthenticateAsync(context, CancellationToken.None),\n                    \"No OWIN authentication manager is associated with the request.\");\n            }\n        }\n\n        [Fact]\n        public async Task AuthenticateAsync_ReturnsCanceledTask_WhenCancellationIsRequested()\n        {\n            // Arrange\n            IAuthenticationFilter filter = CreateProductUnderTest();\n            IOwinContext owinContext = CreateOwinContext();\n\n            using (HttpRequestMessage request = CreateRequest(owinContext))\n            {\n                HttpAuthenticationContext context = CreateAuthenticationContext(request);\n                CancellationToken cancellationToken = new CancellationToken(true);\n\n                // Act & Assert\n                await Assert.ThrowsAsync<OperationCanceledException>(() => filter.AuthenticateAsync(context, cancellationToken));\n            }\n        }\n\n        [Fact]\n        public async Task ChallengeAsync_AddsAuthenticationType_WhenOwinChallengeAlreadyExists()\n        {\n            // Arrange\n            string expectedAuthenticationType = \"AuthenticationType\";\n            IAuthenticationFilter filter = CreateProductUnderTest(expectedAuthenticationType);\n            IHttpActionResult result = CreateDummyActionResult();\n            string originalAuthenticationType = \"FirstChallenge\";\n            AuthenticationProperties originalExtra = CreateExtra();\n            AuthenticationResponseChallenge originalChallenge = new AuthenticationResponseChallenge(\n                new string[] { originalAuthenticationType }, originalExtra);\n            IAuthenticationManager authenticationManager = CreateAuthenticationManager(originalChallenge);\n            IOwinContext owinContext = CreateOwinContext(authenticationManager);\n\n            using (HttpRequestMessage request = CreateRequest(owinContext))\n            {\n                HttpAuthenticationChallengeContext context = CreateChallengeContext(request, result);\n\n                // Act\n                await filter.ChallengeAsync(context, CancellationToken.None);\n            }\n\n            // Assert\n            AuthenticationResponseChallenge challenge = authenticationManager.AuthenticationResponseChallenge;\n            Assert.NotNull(challenge);\n            string[] authenticationTypes = challenge.AuthenticationTypes;\n            Assert.NotNull(authenticationTypes);\n            Assert.Equal(2, authenticationTypes.Length);\n            Assert.Same(originalAuthenticationType, authenticationTypes[0]);\n            Assert.Same(expectedAuthenticationType, authenticationTypes[1]);\n            AuthenticationProperties extra = challenge.Properties;\n            Assert.Same(originalExtra, extra);\n        }\n\n        [Fact]\n        public async Task ChallengeAsync_CreatesAuthenticationTypes_WhenOwinChallengeWithNullTypesAlreadyExists()\n        {\n            // Arrange\n            string expectedAuthenticationType = \"AuthenticationType\";\n            IAuthenticationFilter filter = CreateProductUnderTest(expectedAuthenticationType);\n            IHttpActionResult result = CreateDummyActionResult();\n            AuthenticationProperties originalExtra = CreateExtra();\n            AuthenticationResponseChallenge originalChallenge = new AuthenticationResponseChallenge(null,\n                originalExtra);\n            IAuthenticationManager authenticationManager = CreateAuthenticationManager(originalChallenge);\n            IOwinContext owinContext = CreateOwinContext(authenticationManager);\n\n            using (HttpRequestMessage request = CreateRequest(owinContext))\n            {\n                HttpAuthenticationChallengeContext context = CreateChallengeContext(request, result);\n\n                // Act\n                await filter.ChallengeAsync(context, CancellationToken.None);\n            }\n\n            // Assert\n            AuthenticationResponseChallenge challenge = authenticationManager.AuthenticationResponseChallenge;\n            Assert.NotNull(challenge);\n            string[] authenticationTypes = challenge.AuthenticationTypes;\n            Assert.NotNull(authenticationTypes);\n            string authenticationType = Assert.Single(authenticationTypes);\n            Assert.Same(expectedAuthenticationType, authenticationType);\n            AuthenticationProperties extra = challenge.Properties;\n            Assert.Same(originalExtra, extra);\n        }\n\n        [Fact]\n        public async Task ChallengeAsync_CreatesOwinChallengeWithAuthenticationType_WhenNoChallengeExists()\n        {\n            // Arrange\n            string expectedAuthenticationType = \"AuthenticationType\";\n            IAuthenticationFilter filter = CreateProductUnderTest(expectedAuthenticationType);\n            IHttpActionResult result = CreateDummyActionResult();\n            IAuthenticationManager authenticationManager = CreateAuthenticationManager(\n                (AuthenticationResponseChallenge)null);\n            IOwinContext owinContext = CreateOwinContext(authenticationManager);\n\n            using (HttpRequestMessage request = CreateRequest(owinContext))\n            {\n                HttpAuthenticationChallengeContext context = CreateChallengeContext(request, result);\n\n                // Act\n                await filter.ChallengeAsync(context, CancellationToken.None);\n            }\n\n            // Assert\n            AuthenticationResponseChallenge challenge = authenticationManager.AuthenticationResponseChallenge;\n            Assert.NotNull(challenge);\n            string[] authenticationTypes = challenge.AuthenticationTypes;\n            Assert.NotNull(authenticationTypes);\n            string authenticationType = Assert.Single(authenticationTypes);\n            Assert.Same(expectedAuthenticationType, authenticationType);\n            AuthenticationProperties extra = challenge.Properties;\n            Assert.NotNull(extra);\n        }\n\n        [Fact]\n        public Task ChallengeAsync_Throws_WhenContextIsNull()\n        {\n            // Arrange\n            IAuthenticationFilter filter = CreateProductUnderTest();\n\n            // Act & Assert\n            return Assert.ThrowsArgumentNullAsync(() => filter.ChallengeAsync(null, CancellationToken.None), \"context\");\n        }\n\n        [Fact]\n        public Task ChallengeAsync_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            IAuthenticationFilter filter = CreateProductUnderTest();\n            IHttpActionResult result = CreateDummyActionResult();\n            HttpAuthenticationChallengeContext context = new HttpAuthenticationChallengeContext(\n                new HttpActionContext(), result);\n            Assert.Null(context.Request);\n\n            // Act & Assert\n            return Assert.ThrowsAsync<InvalidOperationException>(\n                () => filter.ChallengeAsync(context, CancellationToken.None),\n                \"HttpAuthenticationChallengeContext.Request must not be null.\");\n        }\n\n        [Fact]\n        public async Task ChallengeAsync_Throws_WhenOwinContextIsNull()\n        {\n            // Arrange\n            IAuthenticationFilter filter = CreateProductUnderTest();\n            IHttpActionResult result = CreateDummyActionResult();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpAuthenticationChallengeContext context = CreateChallengeContext(request, result);\n\n                // Act & Assert\n                await Assert.ThrowsAsync<InvalidOperationException>(\n                    () => filter.ChallengeAsync(context, CancellationToken.None),\n                    \"No OWIN authentication manager is associated with the request.\");\n            }\n        }\n\n        [Fact]\n        public async Task ChallengeAsync_Throws_WhenAuthenticationManagerIsNull()\n        {\n            // Arrange\n            IAuthenticationFilter filter = CreateProductUnderTest();\n            IHttpActionResult result = CreateDummyActionResult();\n            IOwinContext owinContext = CreateOwinContext(null);\n\n            using (HttpRequestMessage request = CreateRequest(owinContext))\n            {\n                HttpAuthenticationChallengeContext context = CreateChallengeContext(request, result);\n\n                // Act & Assert\n                await Assert.ThrowsAsync<InvalidOperationException>(\n                    () => filter.ChallengeAsync(context, CancellationToken.None),\n                    \"No OWIN authentication manager is associated with the request.\");\n            }\n        }\n\n        private static HttpActionContext CreateActionContext(HttpRequestMessage request)\n        {\n            HttpControllerContext controllerContext = new HttpControllerContext();\n            controllerContext.Request = request;\n            HttpActionDescriptor descriptor = CreateDummyActionDescriptor();\n            return new HttpActionContext(controllerContext, descriptor);\n        }\n\n        private static HttpAuthenticationContext CreateAuthenticationContext()\n        {\n            HttpActionContext actionContext = new HttpActionContext();\n            IPrincipal principal = CreateDummyPrincipal();\n            return new HttpAuthenticationContext(actionContext, principal);\n        }\n\n        private static HttpAuthenticationContext CreateAuthenticationContext(HttpRequestMessage request)\n        {\n            IPrincipal principal = CreateDummyPrincipal();\n            return CreateAuthenticationContext(request, principal);\n        }\n\n        private static HttpAuthenticationContext CreateAuthenticationContext(HttpRequestMessage request,\n            IPrincipal principal)\n        {\n            HttpActionContext actionContext = CreateActionContext(request);\n            return new HttpAuthenticationContext(actionContext, principal);\n        }\n\n        private static IAuthenticationManager CreateAuthenticationManager(\n            Func<string, Task<AuthenticateResult>> authenticate)\n        {\n            Mock<IAuthenticationManager> mock = new Mock<IAuthenticationManager>(\n                MockBehavior.Strict);\n            string authenticationType = null;\n            mock.Setup(m => m.AuthenticateAsync(It.IsAny<string>()))\n                .Callback<string>((a) => { authenticationType = a; })\n                .Returns(() => authenticate.Invoke(authenticationType));\n            return mock.Object;\n        }\n\n        private static IAuthenticationManager CreateAuthenticationManager(AuthenticationResponseChallenge challenge)\n        {\n            Mock<IAuthenticationManager> mock = new Mock<IAuthenticationManager>(MockBehavior.Strict);\n            mock.SetupProperty(m => m.AuthenticationResponseChallenge);\n            IAuthenticationManager authenticationManager = mock.Object;\n            authenticationManager.AuthenticationResponseChallenge = challenge;\n            return authenticationManager;\n        }\n\n        private static HttpAuthenticationChallengeContext CreateChallengeContext(HttpRequestMessage request,\n            IHttpActionResult result)\n        {\n            HttpActionContext actionContext = CreateActionContext(request);\n            return new HttpAuthenticationChallengeContext(actionContext, result);\n        }\n\n        private static HttpActionDescriptor CreateDummyActionDescriptor()\n        {\n            return new Mock<HttpActionDescriptor>(MockBehavior.Strict).Object;\n        }\n\n        private static IHttpActionResult CreateDummyActionResult()\n        {\n            return new Mock<IHttpActionResult>(MockBehavior.Strict).Object;\n        }\n\n        private static ClaimsIdentity CreateDummyIdentity()\n        {\n            return new Mock<ClaimsIdentity>(MockBehavior.Strict).Object;\n        }\n\n        private static IPrincipal CreateDummyPrincipal()\n        {\n            return new Mock<IPrincipal>(MockBehavior.Strict).Object;\n        }\n\n        private static AuthenticationProperties CreateExtra()\n        {\n            return new AuthenticationProperties();\n        }\n\n        private static IOwinContext CreateOwinContext()\n        {\n            return new OwinContext();\n        }\n\n        private static IOwinContext CreateOwinContext(IAuthenticationManager authenticationManager)\n        {\n            Mock<IOwinContext> mockContext = new Mock<IOwinContext>(MockBehavior.Strict);\n            mockContext.SetupGet(c => c.Authentication).Returns(authenticationManager);\n            return mockContext.Object;\n        }\n\n        private static HostAuthenticationFilter CreateProductUnderTest()\n        {\n            return CreateProductUnderTest(\"IgnoreAuthenticationType\");\n        }\n\n        private static HostAuthenticationFilter CreateProductUnderTest(string authenticationType)\n        {\n            return new HostAuthenticationFilter(authenticationType);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private static HttpRequestMessage CreateRequest(IOwinContext owinContext)\n        {\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.SetOwinContext(owinContext);\n            return request;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Owin.Test/HttpMessageHandlerAdapterTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Security.Cryptography.X509Certificates;\nusing System.Security.Principal;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.Owin.ExceptionHandling;\nusing System.Web.Http.Results;\nusing System.Web.Http.Routing;\nusing Microsoft.Owin;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Owin\n{\n    public class HttpMessageHandlerAdapterTest\n    {\n        [Fact]\n        public void ConstructorWithOptions_IfOptionsIsNull_Throws()\n        {\n            // Arrange\n            HttpMessageHandlerOptions options = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => CreateProductUnderTest(options), \"options\");\n        }\n\n        [Fact]\n        public void ConstructorWithOptions_IfMessageHandlerIsNull_Throws()\n        {\n            // Arrange\n            HttpMessageHandlerOptions options = CreateDummyOptions(messageHandler: null);\n\n            // Act & Assert.\n            Assert.ThrowsArgument(() => CreateProductUnderTest(options), \"options\",\n                \"HttpMessageHandlerOptions.MessageHandler must not be null.\");\n        }\n\n        [Fact]\n        public void ConstructorWithOptions_IfBufferPolicySelectorIsNull_Throws()\n        {\n            // Arrange\n            using (HttpMessageHandler messageHandler = CreateDummyMessageHandler())\n            {\n                HttpMessageHandlerOptions options = CreateDummyOptions(messageHandler);\n                options.BufferPolicySelector = null;\n\n                // Act & Assert.\n                Assert.ThrowsArgument(() => CreateProductUnderTest(options), \"options\",\n                    \"HttpMessageHandlerOptions.BufferPolicySelector must not be null.\");\n            }\n        }\n\n        [Fact]\n        public void ConstructorWithOptions_IfExceptionLoggerIsNull_Throws()\n        {\n            // Arrange\n            using (HttpMessageHandler messageHandler = CreateDummyMessageHandler())\n            {\n                HttpMessageHandlerOptions options = CreateDummyOptions(messageHandler);\n                options.ExceptionLogger = null;\n\n                // Act & Assert.\n                Assert.ThrowsArgument(() => CreateProductUnderTest(options), \"options\",\n                    \"HttpMessageHandlerOptions.ExceptionLogger must not be null.\");\n            }\n        }\n\n        [Fact]\n        public void ConstructorWithOptions_IfExceptionHandlerIsNull_Throws()\n        {\n            // Arrange\n            using (HttpMessageHandler messageHandler = CreateDummyMessageHandler())\n            {\n                HttpMessageHandlerOptions options = CreateDummyOptions(messageHandler);\n                options.ExceptionHandler = null;\n\n                // Act & Assert.\n                Assert.ThrowsArgument(() => CreateProductUnderTest(options), \"options\",\n                    \"HttpMessageHandlerOptions.ExceptionHandler must not be null.\");\n            }\n        }\n\n        [Fact]\n        public void ConstructorWithList_IfMessageHandlerIsNull_Throws()\n        {\n            // Arrange\n            HttpMessageHandler messageHandler = null;\n            IHostBufferPolicySelector bufferPolicySelector = CreateDummyBufferPolicy();\n\n            // Act & Assert.\n#pragma warning disable 0618\n            Assert.ThrowsArgumentNull(() => new HttpMessageHandlerAdapter(null, messageHandler, bufferPolicySelector),\n                \"messageHandler\");\n#pragma warning restore 0618\n        }\n\n        [Fact]\n        public void ConstructorWithList_IfBufferPolicySelectorIsNull_Throws()\n        {\n            // Arrange\n            using (HttpMessageHandler messageHandler = CreateDummyMessageHandler())\n            {\n                IHostBufferPolicySelector bufferPolicySelector = null;\n\n                // Act & Assert.\n#pragma warning disable 0618\n                Assert.ThrowsArgumentNull(() => new HttpMessageHandlerAdapter(null, messageHandler,\n                    bufferPolicySelector), \"bufferPolicySelector\");\n#pragma warning restore 0618\n            }\n        }\n\n        [Fact]\n        public void MessageHandler_IfUsingOptionsConstructor_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            using (HttpMessageHandler expectedMessageHandler = CreateDummyMessageHandler())\n            {\n                HttpMessageHandlerOptions options = CreateDummyOptions(expectedMessageHandler);\n                HttpMessageHandlerAdapter product = CreateProductUnderTest(options);\n\n                // Act\n                HttpMessageHandler messageHandler = product.MessageHandler;\n\n                // Assert\n                Assert.Same(expectedMessageHandler, messageHandler);\n            }\n        }\n\n        [Fact]\n        public void MessageHandler_IfUsingListConstructor_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            using (HttpMessageHandler expectedMessageHandler = CreateDummyMessageHandler())\n            {\n                IHostBufferPolicySelector bufferPolicySelector = CreateDummyBufferPolicy();\n#pragma warning disable 0618\n                HttpMessageHandlerAdapter product = new HttpMessageHandlerAdapter(null, expectedMessageHandler,\n                    bufferPolicySelector);\n#pragma warning restore 0618\n\n                // Act\n                HttpMessageHandler messageHandler = product.MessageHandler;\n\n                // Assert\n                Assert.Same(expectedMessageHandler, messageHandler);\n            }\n        }\n\n        [Fact]\n        public void BufferPolicySelector_IfUsingOptionsConstructor_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            using (HttpMessageHandler messageHandler = CreateDummyMessageHandler())\n            {\n                IHostBufferPolicySelector expectedBufferPolicySelector = CreateDummyBufferPolicy();\n                HttpMessageHandlerOptions options = CreateDummyOptions(messageHandler);\n                options.BufferPolicySelector = expectedBufferPolicySelector;\n                HttpMessageHandlerAdapter product = CreateProductUnderTest(options);\n\n                // Act\n                IHostBufferPolicySelector bufferPolicySelector = product.BufferPolicySelector;\n\n                // Assert\n                Assert.Same(expectedBufferPolicySelector, bufferPolicySelector);\n            }\n        }\n\n        [Fact]\n        public void BufferPolicySelector_IfUsingListConstructor_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            using (HttpMessageHandler messageHandler = CreateDummyMessageHandler())\n            {\n                IHostBufferPolicySelector expectedBufferPolicySelector = CreateDummyBufferPolicy();\n#pragma warning disable 0618\n                HttpMessageHandlerAdapter product = new HttpMessageHandlerAdapter(null, messageHandler,\n                    expectedBufferPolicySelector);\n#pragma warning restore 0618\n\n                // Act\n                IHostBufferPolicySelector bufferPolicySelector = product.BufferPolicySelector;\n\n                // Assert\n                Assert.Same(expectedBufferPolicySelector, bufferPolicySelector);\n            }\n        }\n\n        [Fact]\n        public void ExceptionLogger_IfUsingOptionsConstructor_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            using (HttpMessageHandler messageHandler = CreateDummyMessageHandler())\n            {\n                IExceptionLogger expectedExceptionLogger = CreateDummyExceptionLogger();\n                HttpMessageHandlerOptions options = CreateDummyOptions(messageHandler);\n                options.ExceptionLogger = expectedExceptionLogger;\n                HttpMessageHandlerAdapter product = CreateProductUnderTest(options);\n\n                // Act\n                IExceptionLogger exceptionLogger = product.ExceptionLogger;\n\n                // Assert\n                Assert.Same(expectedExceptionLogger, exceptionLogger);\n            }\n        }\n\n        [Fact]\n        public void ExceptionLogger_IfUsingListConstructor_ReturnsEmptyExceptionLogger()\n        {\n            // Arrange\n            using (HttpMessageHandler messageHandler = CreateDummyMessageHandler())\n            {\n                IHostBufferPolicySelector bufferPolicySelector = CreateDummyBufferPolicy();\n#pragma warning disable 0618\n                HttpMessageHandlerAdapter product = new HttpMessageHandlerAdapter(null, messageHandler,\n                    bufferPolicySelector);\n#pragma warning restore 0618\n\n                // Act\n                IExceptionLogger exceptionLogger = product.ExceptionLogger;\n\n                // Assert\n                Assert.IsType<EmptyExceptionLogger>(exceptionLogger);\n            }\n        }\n\n        [Fact]\n        public void ExceptionHandler_IfUsingOptionsConstructor_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            using (HttpMessageHandler messageHandler = CreateDummyMessageHandler())\n            {\n                IExceptionHandler expectedExceptionHandler = CreateDummyExceptionHandler();\n                HttpMessageHandlerOptions options = CreateDummyOptions(messageHandler);\n                options.ExceptionHandler = expectedExceptionHandler;\n                HttpMessageHandlerAdapter product = CreateProductUnderTest(options);\n\n                // Act\n                IExceptionHandler exceptionHandler = product.ExceptionHandler;\n\n                // Assert\n                Assert.Same(expectedExceptionHandler, exceptionHandler);\n            }\n        }\n\n        [Fact]\n        public void ExceptionHandler_IfUsingListConstructor_ReturnsDefaultExceptionHandler()\n        {\n            // Arrange\n            using (HttpMessageHandler messageHandler = CreateDummyMessageHandler())\n            {\n                IHostBufferPolicySelector bufferPolicySelector = CreateDummyBufferPolicy();\n#pragma warning disable 0618\n                HttpMessageHandlerAdapter product = new HttpMessageHandlerAdapter(null, messageHandler,\n                    bufferPolicySelector);\n#pragma warning restore 0618\n\n                // Act\n                IExceptionHandler exceptionHandler = product.ExceptionHandler;\n\n                // Assert\n                Assert.IsType<DefaultExceptionHandler>(exceptionHandler);\n            }\n        }\n\n        [Fact]\n        public void AppDisposing_IfUsingOptionsConstructor_ReturnsSpecifiedValue()\n        {\n            // Arrange\n            using (HttpMessageHandler messageHandler = CreateDummyMessageHandler())\n            using (CancellationTokenSource tokenSource = CreateCancellationTokenSource())\n            {\n                CancellationToken expectedAppDisposing = tokenSource.Token;\n                HttpMessageHandlerOptions options = CreateDummyOptions(messageHandler);\n                options.AppDisposing = expectedAppDisposing;\n                HttpMessageHandlerAdapter product = CreateProductUnderTest(options);\n\n                // Act\n                CancellationToken appDisposing = product.AppDisposing;\n\n                // Assert\n                Assert.Equal(expectedAppDisposing, appDisposing);\n            }\n        }\n\n        [Fact]\n        public void AppDisposing_IfUsingListConstructor_ReturnsDefaultExceptionHandler()\n        {\n            // Arrange\n            using (HttpMessageHandler messageHandler = CreateDummyMessageHandler())\n            {\n                IHostBufferPolicySelector bufferPolicySelector = CreateDummyBufferPolicy();\n#pragma warning disable 0618\n                HttpMessageHandlerAdapter product = new HttpMessageHandlerAdapter(null, messageHandler,\n                    bufferPolicySelector);\n#pragma warning restore 0618\n\n                // Act\n                CancellationToken appDisposing = product.AppDisposing;\n\n                // Assert\n                Assert.Equal(CancellationToken.None, appDisposing);\n            }\n        }\n\n        [Fact]\n        public void TriggeringHostOnAppDisposing_DisposesMessageHandler()\n        {\n            // Arrange\n            using (SpyDisposeHttpMessageHandler spy = new SpyDisposeHttpMessageHandler())\n            using (CancellationTokenSource tokenSource = CreateCancellationTokenSource())\n            {\n                HttpMessageHandlerOptions options = CreateDummyOptions(spy);\n                options.AppDisposing = tokenSource.Token;\n                HttpMessageHandlerAdapter product = CreateProductUnderTest(options);\n\n                // Act\n                tokenSource.Cancel(throwOnFirstException: true);\n                CancellationToken appDisposing = product.AppDisposing;\n\n                // Assert\n                Assert.True(spy.Disposed);\n            }\n        }\n\n        [Fact]\n        public async Task Invoke_ThrowsOnNullRequest()\n        {\n            var handler = CreateOKHandlerStub();\n            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n            var options = CreateValidOptions(handler, bufferPolicySelector);\n            var adapter = CreateProductUnderTest(options);\n            var mockContext = new Mock<IOwinContext>();\n            mockContext.Setup(context => context.Response).Returns(new OwinResponse());\n\n            await Assert.ThrowsAsync<InvalidOperationException>(\n                () => adapter.Invoke(mockContext.Object),\n                \"The OWIN context's Request property must not be null.\");\n        }\n\n        [Fact]\n        public async Task Invoke_ThrowsOnNullResponse()\n        {\n            var handler = CreateOKHandlerStub();\n            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n            var options = CreateValidOptions(handler, bufferPolicySelector);\n            var adapter = CreateProductUnderTest(options);\n            var mockContext = new Mock<IOwinContext>();\n            mockContext.Setup(context => context.Request).Returns(new OwinRequest());\n\n            await Assert.ThrowsAsync<InvalidOperationException>(\n                () => adapter.Invoke(mockContext.Object),\n                \"The OWIN context's Response property must not be null.\");\n        }\n\n        [Fact]\n        public async Task Invoke_BuildsAppropriateRequestMessage()\n        {\n            var handler = CreateOKHandlerStub();\n            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n            var environment = CreateOwinEnvironment(\"GET\", \"http\", \"localhost\", \"/vroot\", \"/api/customers\");\n            var options = CreateValidOptions(handler, bufferPolicySelector);\n            var adapter = CreateProductUnderTest(options);\n\n            await adapter.Invoke(new OwinContext(environment));\n\n            var request = handler.Request;\n            Assert.Equal(HttpMethod.Get, request.Method);\n            Assert.Equal(\"http://localhost/vroot/api/customers\", request.RequestUri.AbsoluteUri);\n        }\n\n        [Fact]\n        public async Task Invoke_BuildsUriWithQueryStringIfPresent()\n        {\n            var handler = CreateOKHandlerStub();\n            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n            var environment = CreateOwinEnvironment(\"GET\", \"http\", \"localhost\", \"/vroot\", \"/api/customers\");\n            environment[\"owin.RequestQueryString\"] = \"id=45\";\n            var adapter = CreateProductUnderTest(new HttpMessageHandlerOptions\n            {\n                MessageHandler = handler,\n                BufferPolicySelector = bufferPolicySelector,\n                ExceptionLogger = new EmptyExceptionLogger(),\n                ExceptionHandler = new DefaultExceptionHandler()\n            });\n\n            await adapter.Invoke(new OwinContext(environment));\n\n            var request = handler.Request;\n            Assert.Equal(HttpMethod.Get, request.Method);\n            Assert.Equal(\"http://localhost/vroot/api/customers?id=45\", request.RequestUri.AbsoluteUri);\n        }\n\n        [Fact]\n        public async Task Invoke_BuildsUriWithHostAndPort()\n        {\n            var handler = CreateOKHandlerStub();\n            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n            var environment = CreateOwinEnvironment(\"GET\", \"http\", \"localhost:12345\", \"/vroot\", \"/api/customers\");\n            var options = CreateValidOptions(handler, bufferPolicySelector);\n            var adapter = CreateProductUnderTest(options);\n\n            await adapter.Invoke(new OwinContext(environment));\n\n            var request = handler.Request;\n            Assert.Equal(HttpMethod.Get, request.Method);\n            Assert.Equal(\"http://localhost:12345/vroot/api/customers\", request.RequestUri.AbsoluteUri);\n        }\n\n        [Theory]\n        [InlineData(\"a b\")]\n        // reserved characters\n        [InlineData(\"!*'();:@&=$,[]\")]\n        // common unreserved characters\n        [InlineData(@\"-_.~+\"\"<>^`{|}\")]\n        // random unicode characters\n        [InlineData(\"激光這\")]\n        [InlineData(\"?#\")]\n        public async Task Invoke_CreatesUri_ThatGeneratesCorrectlyDecodedStrings(string decodedId)\n        {\n            var handler = CreateOKHandlerStub();\n            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n            var environment = CreateOwinEnvironment(\"GET\", \"http\", \"localhost\", \"/vroot\", \"/api/customers/\" + decodedId);\n            var options = CreateValidOptions(handler, bufferPolicySelector);\n            var adapter = CreateProductUnderTest(options);\n            var route = new HttpRoute(\"api/customers/{id}\");\n\n            await adapter.Invoke(new OwinContext(environment));\n            IHttpRouteData routeData = route.GetRouteData(\"/vroot\", handler.Request);\n\n            Assert.NotNull(routeData);\n            Assert.Equal(decodedId, routeData.Values[\"id\"]);\n        }\n\n        [Theory]\n        [InlineData(\"%24\", \"$\")]\n        [InlineData(\"%28%29\", \"()\")]\n        [InlineData(\"%5B%5D\", \"[]\")]\n        [InlineData(\"%7B%7D\", \"{}\")]\n        public async Task Invoke_CreatesUri_ContainingCorrectlyDecodedStrings(string encoded, string decoded)\n        {\n            var handler = CreateOKHandlerStub();\n            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n            var environment = CreateOwinEnvironment(\"GET\", \"http\", \"localhost\", \"/vroot\", \"/api/customers/\" + encoded);\n            var options = CreateValidOptions(handler, bufferPolicySelector);\n            var adapter = CreateProductUnderTest(options);\n            var route = new HttpRoute(\"api/customers/{id}\");\n\n            await adapter.Invoke(new OwinContext(environment));\n            IHttpRouteData routeData = route.GetRouteData(\"/vroot\", handler.Request);\n\n            Assert.NotNull(routeData);\n            Assert.Equal(decoded, routeData.Values[\"id\"]);\n        }\n\n        [Fact]\n        public async Task Invoke_AddsRequestHeadersToRequestMessage()\n        {\n            var handler = CreateOKHandlerStub();\n            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n            var environment = CreateOwinEnvironment(\"GET\", \"http\", \"localhost\", \"/vroot\", \"/api/customers\");\n            var requestHeaders = environment[\"owin.RequestHeaders\"] as IDictionary<string, string[]>;\n            requestHeaders[\"Accept\"] = new string[] { \"application/json\", \"application/xml\" };\n            requestHeaders[\"Content-Length\"] = new string[] { \"45\" };\n            var options = CreateValidOptions(handler, bufferPolicySelector);\n            var adapter = CreateProductUnderTest(options);\n\n            await adapter.Invoke(new OwinContext(environment));\n\n            var request = handler.Request;\n            Assert.Equal(2, request.Headers.Count());\n            Assert.Equal(new string[] { \"application/json\", \"application/xml\" }, request.Headers.Accept.Select(mediaType => mediaType.ToString()).ToArray());\n            Assert.Equal(\"localhost\", request.Headers.Host);\n            Assert.Single(request.Content.Headers);\n            Assert.Equal(45, request.Content.Headers.ContentLength);\n        }\n\n        [Fact]\n        public async Task Invoke_SetsRequestBodyOnRequestMessage()\n        {\n            string body = null;\n            Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> sendAsync = async (r, i) =>\n            {\n                body = await r.Content.ReadAsStringAsync();\n                return new HttpResponseMessage();\n            };\n            var handler = CreateLambdaMessageHandler(sendAsync);\n            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n            var environment = CreateOwinEnvironment(\"GET\", \"http\", \"localhost\", \"/vroot\", \"/api/customers\");\n            var expectedBody = \"This is the request body.\";\n            environment[\"owin.RequestBody\"] = new MemoryStream(Encoding.UTF8.GetBytes(expectedBody));\n            var options = CreateValidOptions(handler, bufferPolicySelector);\n            var adapter = CreateProductUnderTest(options);\n\n            await adapter.Invoke(new OwinContext(environment));\n\n            Assert.Equal(expectedBody, body);\n        }\n\n        [Theory]\n        [InlineData(false)]\n        [InlineData(true)]\n        public async Task Invoke_RespectsInputBufferingSetting(bool bufferInput)\n        {\n            var expectedBody = \"This is the request body.\";\n            var requestBodyMock = new Mock<MemoryStream>(Encoding.UTF8.GetBytes(expectedBody));\n            requestBodyMock.CallBase = true;\n            requestBodyMock.Setup(s => s.CanSeek).Returns(false);\n            MemoryStream requestBody = requestBodyMock.Object;\n\n            string body = null;\n            bool originalStreamDisposed = false;\n            Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> sendAsync = async (r, i) =>\n            {\n                body = await r.Content.ReadAsStringAsync();\n                originalStreamDisposed = !requestBody.CanRead;\n                return new HttpResponseMessage();\n            };\n            var handler = CreateLambdaMessageHandler(sendAsync);\n            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: bufferInput, bufferOutput: false);\n            var environment = CreateOwinEnvironment(\"GET\", \"http\", \"localhost\", \"/vroot\", \"/api/customers\");\n            environment[\"owin.RequestBody\"] = requestBody;\n            var options = CreateValidOptions(handler, bufferPolicySelector);\n            var adapter = CreateProductUnderTest(options);\n\n            await adapter.Invoke(new OwinContext(environment));\n\n            // Assert that Web API gets the right body\n            Assert.Equal(expectedBody, body);\n            // The original stream should have been fully read and then disposed only when buffering.\n            Assert.Equal(bufferInput, originalStreamDisposed);\n\n            if (bufferInput)\n            {\n                // Assert that the OWIN environment still has a request body that can be read\n                var owinRequestBody = environment[\"owin.RequestBody\"] as Stream;\n                byte[] bodyBytes = new byte[25];\n                int charsRead = owinRequestBody.Read(bodyBytes, 0, 25);\n                Assert.Equal(expectedBody, Encoding.UTF8.GetString(bodyBytes));\n            }\n        }\n\n        [Fact]\n        public async Task Invoke_IfBufferPolicyDisablesInputBuffering_DisablesRequestBuffering()\n        {\n            // Arrange\n            IHostBufferPolicySelector bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false,\n                bufferOutput: false);\n\n            using (HttpResponseMessage response = CreateResponse())\n            using (HttpMessageHandler messageHandler = CreateStubMessageHandler(response))\n            using (HttpMessageHandlerAdapter product = CreateProductUnderTest(CreateValidOptions(messageHandler,\n                bufferPolicySelector)))\n            {\n                bool bufferingDisabled = false;\n                Action disableBuffering = () => bufferingDisabled = true;\n                IOwinRequest owinRequest = CreateFakeOwinRequest(disableBuffering);\n                IOwinResponse owinResponse = CreateFakeOwinResponse();\n                IOwinContext expectedContext = CreateStubOwinContext(owinRequest, owinResponse);\n\n                // Act\n                await product.Invoke(expectedContext);\n\n                // Assert\n                Assert.True(bufferingDisabled);\n            }\n        }\n\n        [Fact]\n        public async Task Invoke_IfBufferPolicyEnablesInputBuffering_DoesNotDisableRequestBuffering()\n        {\n            // Arrange\n            IHostBufferPolicySelector bufferPolicySelector = CreateBufferPolicySelector(bufferInput: true,\n                bufferOutput: false);\n\n            using (HttpResponseMessage response = CreateResponse())\n            using (HttpMessageHandler messageHandler = CreateStubMessageHandler(response))\n            using (HttpMessageHandlerAdapter product = CreateProductUnderTest(CreateValidOptions(messageHandler,\n                bufferPolicySelector)))\n            {\n                bool bufferingDisabled = false;\n                Action disableBuffering = () => bufferingDisabled = true;\n                IOwinRequest owinRequest = CreateFakeOwinRequest(disableBuffering);\n                IOwinResponse owinResponse = CreateFakeOwinResponse();\n                IOwinContext expectedContext = CreateStubOwinContext(owinRequest, owinResponse);\n\n                // Act\n                await product.Invoke(expectedContext);\n\n                // Assert\n                Assert.False(bufferingDisabled);\n            }\n        }\n\n        [Fact]\n        public async Task Invoke_SetsOwinEnvironment()\n        {\n            var handler = CreateOKHandlerStub();\n            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n            var environment = CreateOwinEnvironment(\"GET\", \"http\", \"localhost\", \"/vroot\", \"/api/customers\");\n            var options = CreateValidOptions(handler, bufferPolicySelector);\n            var adapter = CreateProductUnderTest(options);\n\n            await adapter.Invoke(new OwinContext(environment));\n\n            var request = handler.Request;\n            Assert.Same(environment, request.GetOwinEnvironment());\n        }\n\n        [Fact]\n        public async Task Invoke_SetsOwinRequestContext()\n        {\n            // Arrange\n            IHostBufferPolicySelector bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false,\n                bufferOutput: true);\n\n            using (HttpResponseMessage response = CreateResponse())\n            {\n                HttpRequestMessage request = null;\n                Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> sendAsync = (r, c) =>\n                {\n                    request = r;\n                    return Task.FromResult(response);\n                };\n\n                using (HttpMessageHandler messageHandler = CreateLambdaMessageHandler(sendAsync))\n                using (HttpMessageHandlerAdapter product = CreateProductUnderTest(CreateValidOptions(messageHandler,\n                    bufferPolicySelector)))\n                {\n                    IOwinRequest owinRequest = CreateFakeOwinRequest();\n                    IOwinResponse owinResponse = CreateFakeOwinResponse();\n                    IOwinContext expectedContext = CreateStubOwinContext(owinRequest, owinResponse);\n\n                    // Act\n                    await product.Invoke(expectedContext);\n\n                    // Assert\n                    HttpRequestContext requestContext = request.GetRequestContext();\n                    OwinHttpRequestContext typedContext = Assert.IsType<OwinHttpRequestContext>(requestContext);\n                    Assert.Same(expectedContext, typedContext.Context);\n                    Assert.Same(request, typedContext.Request);\n                }\n            }\n        }\n\n        [Theory]\n        [InlineData(null, false)]\n        [InlineData(false, false)]\n        [InlineData(true, true)]\n        public async Task Invoke_SetsRequestIsLocalProperty(bool? isLocal, bool expectedRequestLocal)\n        {\n            var handler = CreateOKHandlerStub();\n            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n            var environment = CreateOwinEnvironment(\"GET\", \"http\", \"localhost\", \"/vroot\", \"/api/customers\");\n            if (isLocal.HasValue)\n            {\n                environment[\"server.IsLocal\"] = isLocal.Value;\n            }\n            var options = CreateValidOptions(handler, bufferPolicySelector);\n            var adapter = CreateProductUnderTest(options);\n\n            await adapter.Invoke(new OwinContext(environment));\n\n            var request = handler.Request;\n            Assert.Equal(expectedRequestLocal, request.IsLocal());\n        }\n\n        [Fact]\n        public async Task Invoke_SetsClientCertificate()\n        {\n            var handler = CreateOKHandlerStub();\n            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n            var environment = CreateOwinEnvironment(\"GET\", \"http\", \"localhost\", \"/vroot\", \"/api/customers\");\n            var clientCert = new Mock<X509Certificate2>().Object;\n            environment[\"ssl.ClientCertificate\"] = clientCert;\n            var options = CreateValidOptions(handler, bufferPolicySelector);\n            var adapter = CreateProductUnderTest(options);\n\n            await adapter.Invoke(new OwinContext(environment));\n\n            var request = handler.Request;\n            Assert.Equal(clientCert, request.GetClientCertificate());\n        }\n\n        [Fact]\n        public async Task Invoke_CallsMessageHandler_WithEnvironmentCancellationToken()\n        {\n            var handler = CreateOKHandlerStub();\n            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n            var environment = CreateOwinEnvironment(\"GET\", \"http\", \"localhost\", \"/vroot\", \"/api/customers\");\n            var cancellationToken = new CancellationToken();\n            environment[\"owin.CallCancelled\"] = cancellationToken;\n            var options = CreateValidOptions(handler, bufferPolicySelector);\n            var adapter = CreateProductUnderTest(options);\n\n            await adapter.Invoke(new OwinContext(environment));\n\n            Assert.Equal(cancellationToken, handler.CancellationToken);\n        }\n\n        [Fact]\n        public async Task Invoke_CallsMessageHandler_WithEnvironmentUser()\n        {\n            var handler = CreateOKHandlerStub();\n            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n            var environment = CreateOwinEnvironment(\"GET\", \"http\", \"localhost\", \"/vroot\", \"/api/customers\");\n            var user = new Mock<IPrincipal>().Object;\n            environment[\"server.User\"] = user;\n            var options = CreateValidOptions(handler, bufferPolicySelector);\n            var adapter = CreateProductUnderTest(options);\n\n            await adapter.Invoke(new OwinContext(environment));\n\n            Assert.Equal(user, handler.User);\n        }\n\n        [Fact]\n        public async Task Invoke_Throws_IfMessageHandlerReturnsNull()\n        {\n            HttpResponseMessage response = null;\n            var handler = new HandlerStub() { Response = response };\n            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n            var environment = CreateOwinEnvironment(\"GET\", \"http\", \"localhost\", \"/vroot\", \"/api/customers\");\n            var options = CreateValidOptions(handler, bufferPolicySelector);\n            var adapter = CreateProductUnderTest(options);\n\n            await Assert.ThrowsAsync<InvalidOperationException>(\n                () => adapter.Invoke(new OwinContext(environment)),\n                \"The message handler did not return a response message.\");\n        }\n\n        [Fact]\n        public async Task Invoke_DoesNotCallNext_IfMessageHandlerDoesNotReturn404()\n        {\n            var mockNext = new Mock<OwinMiddleware>(MockBehavior.Strict, null);\n            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);\n            var handler = new HandlerStub() { Response = response, AddNoRouteMatchedKey = true };\n            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n            var environment = CreateOwinEnvironment(\"GET\", \"http\", \"localhost\", \"/vroot\", \"/api/customers\");\n            var options = CreateValidOptions(handler, bufferPolicySelector);\n            var adapter = CreateProductUnderTest(mockNext.Object, options);\n\n            // Does not throw.\n            await adapter.Invoke(new OwinContext(environment));\n        }\n\n        [Fact]\n        public async Task Invoke_DoesNotCallNext_IfMessageHandlerDoesNotAddNoRouteMatchedProperty()\n        {\n            var mockNext = new Mock<OwinMiddleware>(MockBehavior.Strict, null);\n            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.NotFound);\n            var handler = new HandlerStub() { Response = response, AddNoRouteMatchedKey = false };\n            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n            var environment = CreateOwinEnvironment(\"GET\", \"http\", \"localhost\", \"/vroot\", \"/api/customers\");\n            var options = CreateValidOptions(handler, bufferPolicySelector);\n            var adapter = CreateProductUnderTest(mockNext.Object, options);\n\n            // Does not throw.\n            await adapter.Invoke(new OwinContext(environment));\n        }\n\n        [Fact]\n        public async Task Invoke_CallsNext_IfMessageHandlerReturns404WithNoRouteMatched()\n        {\n            var nextMock = new Mock<OwinMiddleware>(null);\n            nextMock.Setup(middleware => middleware.Invoke(It.IsAny<OwinContext>())).Returns(TaskHelpers.Completed()).Verifiable();\n            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.NotFound);\n            var handler = new HandlerStub() { Response = response, AddNoRouteMatchedKey = true };\n            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n            var environment = CreateOwinEnvironment(\"GET\", \"http\", \"localhost\", \"/vroot\", \"/api/customers\");\n            var options = CreateValidOptions(handler, bufferPolicySelector);\n            var adapter = CreateProductUnderTest(nextMock.Object, options);\n\n            await adapter.Invoke(new OwinContext(environment));\n\n            nextMock.Verify();\n        }\n\n        [Fact]\n        public async Task Invoke_SetsResponseStatusCodeAndReasonPhrase()\n        {\n            var expectedReasonPhrase = \"OH NO!\";\n            var response = new HttpResponseMessage(HttpStatusCode.ServiceUnavailable) { ReasonPhrase = expectedReasonPhrase };\n            var handler = new HandlerStub() { Response = response };\n            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n            var environment = CreateOwinEnvironment(\"GET\", \"http\", \"localhost\", \"/vroot\", \"/api/customers\");\n            var options = CreateValidOptions(handler, bufferPolicySelector);\n            var adapter = CreateProductUnderTest(options);\n\n            await adapter.Invoke(new OwinContext(environment));\n\n            Assert.Equal(503, environment[\"owin.ResponseStatusCode\"]);\n            Assert.Equal(expectedReasonPhrase, environment[\"owin.ResponseReasonPhrase\"]);\n        }\n\n        [Fact]\n        public async Task Invoke_SetsResponseHeaders()\n        {\n            var response = new HttpResponseMessage(HttpStatusCode.OK);\n            response.Headers.Location = new Uri(\"http://www.location.com/\");\n            response.Content = new StringContent(@\"{\"\"x\"\":\"\"y\"\"}\", Encoding.UTF8, \"application/json\");\n            var handler = new HandlerStub() { Response = response };\n            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n            var environment = CreateOwinEnvironment(\"GET\", \"http\", \"localhost\", \"/vroot\", \"/api/customers\");\n            var options = CreateValidOptions(handler, bufferPolicySelector);\n            var adapter = CreateProductUnderTest(options);\n\n            await adapter.Invoke(new OwinContext(environment));\n\n            var responseHeaders = environment[\"owin.ResponseHeaders\"] as IDictionary<string, string[]>;\n            Assert.Equal(3, responseHeaders.Count);\n            Assert.Equal(\"http://www.location.com/\", Assert.Single(responseHeaders[\"Location\"]));\n            Assert.Equal(\"9\", Assert.Single(responseHeaders[\"Content-Length\"]));\n            Assert.Equal(\"application/json; charset=utf-8\", Assert.Single(responseHeaders[\"Content-Type\"]));\n        }\n\n        [Fact]\n        public async Task Invoke_SetsResponseBody()\n        {\n            var response = new HttpResponseMessage(HttpStatusCode.OK);\n            var expectedBody = @\"{\"\"x\"\":\"\"y\"\"}\";\n            response.Content = new StringContent(expectedBody, Encoding.UTF8, \"application/json\");\n            var handler = new HandlerStub() { Response = response };\n            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n            var environment = CreateOwinEnvironment(\"GET\", \"http\", \"localhost\", \"/vroot\", \"/api/customers\");\n            var responseStream = new MemoryStream();\n            environment[\"owin.ResponseBody\"] = responseStream;\n            var options = CreateValidOptions(handler, bufferPolicySelector);\n            var adapter = CreateProductUnderTest(options);\n\n            await adapter.Invoke(new OwinContext(environment));\n\n            responseStream.Seek(0, SeekOrigin.Begin);\n            byte[] bodyBytes = new byte[9];\n            int charsRead = responseStream.Read(bodyBytes, 0, 9);\n            // Assert that we can read 9 characters and no more characters after that\n            Assert.Equal(9, charsRead);\n            Assert.Equal(-1, responseStream.ReadByte());\n            Assert.Equal(expectedBody, Encoding.UTF8.GetString(bodyBytes));\n        }\n\n        [Theory]\n        [InlineData(false)]\n        [InlineData(true)]\n        public async Task Invoke_RespectsOutputBufferingSetting(bool bufferOutput)\n        {\n            var response = new HttpResponseMessage(HttpStatusCode.OK);\n            response.Content = new ObjectContent<string>(\"blue\", new JsonMediaTypeFormatter());\n            var handler = new HandlerStub() { Response = response };\n            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: bufferOutput);\n            var environment = CreateOwinEnvironment(\"GET\", \"http\", \"localhost\", \"/vroot\", \"/api/customers\");\n            var options = CreateValidOptions(handler, bufferPolicySelector);\n            var adapter = CreateProductUnderTest(options);\n\n            await adapter.Invoke(new OwinContext(environment));\n\n            var responseHeaders = environment[\"owin.ResponseHeaders\"] as IDictionary<string, string[]>;\n            if (bufferOutput)\n            {\n                Assert.True(responseHeaders.ContainsKey(\"Content-Length\"));\n            }\n            else\n            {\n                Assert.False(responseHeaders.ContainsKey(\"Content-Length\"));\n            }\n        }\n\n        [Fact]\n        public async Task Invoke_IfBufferPolicyDisablesOutputBuffering_DisablesResponseBuffering()\n        {\n            // Arrange\n            IHostBufferPolicySelector bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false,\n                bufferOutput: false);\n\n            using (HttpResponseMessage response = CreateResponse())\n            using (HttpMessageHandler messageHandler = CreateStubMessageHandler(response))\n            using (HttpMessageHandlerAdapter product = CreateProductUnderTest(CreateValidOptions(messageHandler,\n                bufferPolicySelector)))\n            {\n                IOwinRequest owinRequest = CreateFakeOwinRequest();\n                bool bufferingDisabled = false;\n                Action disableBuffering = () => bufferingDisabled = true;\n                IOwinResponse owinResponse = CreateFakeOwinResponse(disableBuffering);\n                IOwinContext expectedContext = CreateStubOwinContext(owinRequest, owinResponse);\n\n                // Act\n                await product.Invoke(expectedContext);\n\n                // Assert\n                Assert.True(bufferingDisabled);\n            }\n        }\n\n        [Fact]\n        public async Task Invoke_IfBufferPolicyEnablesOutputBuffering_DoesNotDisableResponseBuffering()\n        {\n            // Arrange\n            IHostBufferPolicySelector bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false,\n                bufferOutput: true);\n\n            using (HttpResponseMessage response = CreateResponse())\n            using (HttpMessageHandler messageHandler = CreateStubMessageHandler(response))\n            using (HttpMessageHandlerAdapter product = CreateProductUnderTest(CreateValidOptions(messageHandler,\n                bufferPolicySelector)))\n            {\n                IOwinRequest owinRequest = CreateFakeOwinRequest();\n                bool bufferingDisabled = false;\n                Action disableBuffering = () => bufferingDisabled = true;\n                IOwinResponse owinResponse = CreateFakeOwinResponse(disableBuffering);\n                IOwinContext expectedContext = CreateStubOwinContext(owinRequest, owinResponse);\n\n                // Act\n                await product.Invoke(expectedContext);\n\n                // Assert\n                Assert.False(bufferingDisabled);\n            }\n        }\n\n        [Fact]\n        public async Task Invoke_AddsZeroContentLengthHeader_WhenThereIsNoContent()\n        {\n            var response = new HttpResponseMessage(HttpStatusCode.OK);\n            var handler = new HandlerStub() { Response = response };\n            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n            var environment = CreateOwinEnvironment(\"GET\", \"http\", \"localhost\", \"/vroot\", \"/api/customers\");\n            var options = CreateValidOptions(handler, bufferPolicySelector);\n            var adapter = CreateProductUnderTest(options);\n\n            await adapter.Invoke(new OwinContext(environment));\n\n            var responseHeaders = environment[\"owin.ResponseHeaders\"] as IDictionary<string, string[]>;\n            Assert.Equal(\"0\", responseHeaders[\"Content-Length\"][0]);\n        }\n\n        [Fact]\n        public async Task Invoke_IfTransferEncodingChunkedAndContentLengthAreBothSet_IgnoresContentLength()\n        {\n            var response = new HttpResponseMessage(HttpStatusCode.OK);\n            response.Content = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes(\"Hello world\")));\n            response.Headers.TransferEncodingChunked = true;\n            var handler = new HandlerStub() { Response = response };\n            var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n            var environment = CreateOwinEnvironment(\"GET\", \"http\", \"localhost\", \"/vroot\", \"/api/customers\");\n            var options = CreateValidOptions(handler, bufferPolicySelector);\n            var adapter = CreateProductUnderTest(options);\n\n            await adapter.Invoke(new OwinContext(environment));\n\n            var responseHeaders = environment[\"owin.ResponseHeaders\"] as IDictionary<string, string[]>;\n            Assert.False(responseHeaders.ContainsKey(\"Content-Length\"));\n        }\n\n        [Fact]\n        public async Task Invoke_IfTransferEncodingIsJustChunked_DoesNotCopyHeader()\n        {\n            // Arrange\n            IHostBufferPolicySelector bufferPolicy = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n\n            using (HttpResponseMessage response = CreateResponse())\n            using (HttpMessageHandler messageHandler = CreateStubMessageHandler(response))\n            using (HttpMessageHandlerAdapter product = CreateProductUnderTest(CreateValidOptions(messageHandler,\n                bufferPolicy)))\n            {\n                response.Headers.TransferEncodingChunked = true;\n\n                IOwinRequest owinRequest = CreateFakeOwinRequest();\n                IOwinResponse owinResponse = CreateFakeOwinResponseWithHeaders();\n                IOwinContext context = CreateStubOwinContext(owinRequest, owinResponse);\n\n                // Act\n                await product.Invoke(context);\n\n                // Assert\n                Assert.DoesNotContain(\"Transfer-Encoding\", owinResponse.Headers.Keys);\n            }\n        }\n\n        [Fact]\n        public async Task Invoke_IfTransferEncodingIsIdentity_DoesCopyHeader()\n        {\n            // Arrange\n            IHostBufferPolicySelector bufferPolicy = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n\n            using (HttpResponseMessage response = CreateResponse())\n            using (HttpMessageHandler messageHandler = CreateStubMessageHandler(response))\n            using (HttpMessageHandlerAdapter product = CreateProductUnderTest(CreateValidOptions(messageHandler,\n                bufferPolicy)))\n            {\n                response.Headers.TransferEncoding.Add(new TransferCodingHeaderValue(\"identity\"));\n\n                IOwinRequest owinRequest = CreateFakeOwinRequest();\n                IOwinResponse owinResponse = CreateFakeOwinResponseWithHeaders();\n                IOwinContext context = CreateStubOwinContext(owinRequest, owinResponse);\n\n                // Act\n                await product.Invoke(context);\n\n                // Assert\n                Assert.Contains(\"Transfer-Encoding\", owinResponse.Headers.Keys);\n                Assert.Equal(\"identity\", owinResponse.Headers[\"Transfer-Encoding\"]);\n            }\n        }\n\n        [Fact]\n        public async Task Invoke_IfTransferEncodingIsIdentityChunked_DoesCopyHeader()\n        {\n            // Arrange\n            IHostBufferPolicySelector bufferPolicy = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n\n            using (HttpResponseMessage response = CreateResponse())\n            using (HttpMessageHandler messageHandler = CreateStubMessageHandler(response))\n            using (HttpMessageHandlerAdapter product = CreateProductUnderTest(CreateValidOptions(messageHandler,\n                bufferPolicy)))\n            {\n                response.Headers.TransferEncoding.Add(new TransferCodingHeaderValue(\"identity\"));\n                response.Headers.TransferEncodingChunked = true;\n                Assert.Equal(\"identity, chunked\", response.Headers.TransferEncoding.ToString()); // Guard\n\n                IOwinRequest owinRequest = CreateFakeOwinRequest();\n                IOwinResponse owinResponse = CreateFakeOwinResponseWithHeaders();\n                IOwinContext context = CreateStubOwinContext(owinRequest, owinResponse);\n\n                // Act\n                await product.Invoke(context);\n\n                // Assert\n                Assert.Contains(\"Transfer-Encoding\", owinResponse.Headers.Keys);\n                Assert.Equal(\"identity,chunked\", owinResponse.Headers[\"Transfer-Encoding\"]);\n            }\n        }\n\n        [Fact]\n        public async Task Invoke_IfBufferingFaults_DisposesOriginalResponse()\n        {\n            // Arrange\n            IHostBufferPolicySelector bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false,\n                bufferOutput: true);\n\n            using (HttpContent content = CreateFaultingContent())\n            using (SpyDisposeHttpResponseMessage spy = new SpyDisposeHttpResponseMessage(content))\n            using (HttpMessageHandler messageHandler = CreateStubMessageHandler(spy))\n            {\n                HttpMessageHandlerOptions options = CreateValidOptions(messageHandler);\n                options.BufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: true);\n\n                using (HttpMessageHandlerAdapter product = CreateProductUnderTest(options))\n                using (MemoryStream output = new MemoryStream())\n                {\n                    IOwinRequest owinRequest = CreateFakeOwinRequest();\n                    IOwinResponse owinResponse = CreateFakeOwinResponse(Stream.Null);\n                    IOwinContext context = CreateStubOwinContext(owinRequest, owinResponse, isLocal: true);\n\n                    // Act\n                    await product.Invoke(context);\n\n                    // Assert\n                    Assert.True(spy.Disposed);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task Invoke_IfBufferingFaults_CallsExceptionServices()\n        {\n            // Arrange\n            Exception expectedException = CreateException();\n\n            using (HttpContent content = CreateFaultingContent(expectedException))\n            using (HttpResponseMessage expectedResponse = CreateResponse(content))\n            using (HttpMessageHandler messageHandler = CreateStubMessageHandler(expectedResponse))\n            {\n                Mock<IExceptionLogger> exceptionLoggerMock = CreateStubExceptionLoggerMock();\n                IExceptionLogger exceptionLogger = exceptionLoggerMock.Object;\n\n                Mock<IExceptionHandler> exceptionHandlerMock = CreateStubExceptionHandlerMock();\n                IExceptionHandler exceptionHandler = exceptionHandlerMock.Object;\n\n                HttpMessageHandlerOptions options = CreateValidOptions(messageHandler);\n                options.BufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: true);\n                options.ExceptionLogger = exceptionLogger;\n                options.ExceptionHandler = exceptionHandler;\n\n                using (HttpMessageHandlerAdapter product = CreateProductUnderTest(options))\n                using (CancellationTokenSource tokenSource = CreateCancellationTokenSource())\n                {\n                    CancellationToken expectedCancellationToken = tokenSource.Token;\n                    IOwinRequest owinRequest = CreateFakeOwinRequest(expectedCancellationToken);\n                    IOwinResponse owinResponse = CreateFakeOwinResponse(Stream.Null);\n\n                    IOwinContext context = CreateStubOwinContext(owinRequest, owinResponse, isLocal: true);\n\n                    // Act & Assert\n                    await Assert.ThrowsAsync<Exception>(() => product.Invoke(context));\n\n                    Func<ExceptionContext, bool> exceptionContextMatches = (c) =>\n                        c != null\n                        && c.Exception == expectedException\n                        && c.CatchBlock == OwinExceptionCatchBlocks.HttpMessageHandlerAdapterBufferContent\n                        && c.Request != null\n                        && c.Response == expectedResponse;\n\n                    exceptionLoggerMock.Verify(l => l.LogAsync(\n                        It.Is<ExceptionLoggerContext>(c => exceptionContextMatches(c.ExceptionContext)),\n                        expectedCancellationToken), Times.Once());\n                    exceptionHandlerMock.Verify(h => h.HandleAsync(\n                        It.Is<ExceptionHandlerContext>((c) => exceptionContextMatches(c.ExceptionContext)),\n                        expectedCancellationToken), Times.Once());\n                }\n            }\n        }\n\n        [Fact]\n        public async Task Invoke_IfBufferingCancels_DoesNotCallExceptionServices()\n        {\n            // Arrange\n            Exception expectedException = new OperationCanceledException();\n\n            using (HttpContent content = CreateFaultingContent(expectedException))\n            using (HttpResponseMessage expectedResponse = CreateResponse(content))\n            using (HttpMessageHandler messageHandler = CreateStubMessageHandler(expectedResponse))\n            {\n                Mock<IExceptionLogger> exceptionLoggerMock = new Mock<IExceptionLogger>(MockBehavior.Strict);\n                IExceptionLogger exceptionLogger = exceptionLoggerMock.Object;\n\n                Mock<IExceptionHandler> exceptionHandlerMock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n                IExceptionHandler exceptionHandler = exceptionHandlerMock.Object;\n\n                HttpMessageHandlerOptions options = CreateValidOptions(messageHandler);\n                options.BufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: true);\n                options.ExceptionLogger = exceptionLogger;\n                options.ExceptionHandler = exceptionHandler;\n\n                using (HttpMessageHandlerAdapter product = CreateProductUnderTest(options))\n                using (CancellationTokenSource tokenSource = CreateCancellationTokenSource())\n                {\n                    CancellationToken expectedCancellationToken = tokenSource.Token;\n                    IOwinRequest owinRequest = CreateFakeOwinRequest(expectedCancellationToken);\n                    IOwinResponse owinResponse = CreateFakeOwinResponse(Stream.Null);\n\n                    IOwinContext context = CreateStubOwinContext(owinRequest, owinResponse, isLocal: true);\n\n                    // Act & Assert\n                    await Assert.ThrowsAsync<OperationCanceledException>(() => product.Invoke(context));\n                }\n            }\n        }\n\n        [Fact]\n        public async Task Invoke_IfExceptionHandlerSetsNullResult_PropogatesFaultedTaskException()\n        {\n            // Arrange\n            Exception expectedException = CreateExceptionWithCallStack();\n            string expectedStackTrace = expectedException.StackTrace;\n\n            using (HttpContent content = CreateFaultingContent(expectedException))\n            using (HttpResponseMessage response = CreateResponse(content))\n            using (HttpMessageHandler messageHandler = CreateStubMessageHandler(response))\n            {\n                IExceptionLogger exceptionLogger = CreateStubExceptionLogger();\n                IExceptionHandler exceptionHandler = CreateExceptionHandler(result: null);\n\n                HttpMessageHandlerOptions options = CreateValidOptions(messageHandler);\n                options.BufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: true);\n                options.ExceptionLogger = exceptionLogger;\n                options.ExceptionHandler = exceptionHandler;\n\n                using (HttpMessageHandlerAdapter product = CreateProductUnderTest(options))\n                {\n                    IOwinRequest owinRequest = CreateFakeOwinRequest();\n                    IOwinResponse owinResponse = CreateFakeOwinResponse(Stream.Null);\n\n                    IOwinContext context = CreateStubOwinContext(owinRequest, owinResponse, isLocal: true);\n\n                    // Act & Assert\n                    var exception = await Assert.ThrowsAsync<Exception>(() => product.Invoke(context));\n                    Assert.Same(expectedException, exception);\n                    Assert.NotNull(exception.StackTrace);\n                    Assert.StartsWith(expectedStackTrace, exception.StackTrace);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task Invoke_IfExceptionHandlerHandlesException_SendsResponse()\n        {\n            // Arrange\n            Exception expectedException = CreateException();\n            string expectedErrorContents = \"Sorry\";\n            HttpStatusCode expectedErrorStatusCode = HttpStatusCode.BadRequest;\n\n            using (HttpContent content = CreateFaultingContent())\n            using (HttpResponseMessage response = CreateResponse(content))\n            using (HttpMessageHandler messageHandler = CreateStubMessageHandler(response))\n            using (StringContent errorContent = new StringContent(expectedErrorContents))\n            using (HttpResponseMessage errorResponse = CreateResponse(errorContent))\n            {\n                errorResponse.StatusCode = expectedErrorStatusCode;\n                errorResponse.Content = errorContent;\n\n                HttpMessageHandlerOptions options = CreateValidOptions(messageHandler);\n                options.BufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: true);\n                options.ExceptionLogger = CreateStubExceptionLogger();\n                options.ExceptionHandler = CreateExceptionHandler(new ResponseMessageResult(errorResponse));\n\n                using (HttpMessageHandlerAdapter product = CreateProductUnderTest(options))\n                using (MemoryStream output = new MemoryStream())\n                {\n                    IOwinRequest owinRequest = CreateFakeOwinRequest();\n\n                    int statusCode = 0;\n                    Mock<IOwinResponse> mock = new Mock<IOwinResponse>();\n                    mock.Setup(r => r.Headers).Returns(new Mock<IHeaderDictionary>().Object);\n                    mock.SetupGet(r => r.Body).Returns(output);\n                    mock.SetupSet(r => r.StatusCode = It.IsAny<int>()).Callback<int>((v) => statusCode = v);\n                    IOwinResponse owinResponse = mock.Object;\n\n                    IOwinContext context = CreateStubOwinContext(owinRequest, owinResponse, isLocal: true);\n\n                    // Act\n                    await product.Invoke(context);\n\n                    // Assert\n                    Assert.Equal((int)expectedErrorStatusCode, statusCode);\n                    using (HttpRequestMessage request = CreateRequest(includeErrorDetail: true))\n                    {\n                        Assert.Equal(expectedErrorContents, Encoding.UTF8.GetString(output.ToArray()));\n                    }\n                }\n            }\n        }\n\n        [Fact]\n        public async Task Invoke_IfBufferingFaultsAndUsingListConstructor_SendsErrorResponse()\n        {\n            // Arrange\n            Exception expectedException = CreateException();\n            IHostBufferPolicySelector bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false,\n                bufferOutput: true);\n\n            using (HttpContent content = CreateFaultingContent(expectedException))\n            using (HttpResponseMessage response = CreateResponse(content))\n            using (HttpMessageHandler messageHandler = CreateStubMessageHandler(response))\n            using (HttpMessageHandlerAdapter product = CreateProductUnderTest(CreateValidOptions(messageHandler,\n                bufferPolicySelector)))\n            using (MemoryStream output = new MemoryStream())\n            {\n                IOwinRequest owinRequest = CreateFakeOwinRequest();\n\n                int statusCode = 0;\n                Mock<IOwinResponse> mock = new Mock<IOwinResponse>();\n                mock.Setup(r => r.Headers).Returns(new Mock<IHeaderDictionary>().Object);\n                mock.SetupGet(r => r.Body).Returns(output);\n                mock.SetupSet(r => r.StatusCode = It.IsAny<int>()).Callback<int>((v) => statusCode = v);\n                IOwinResponse owinResponse = mock.Object;\n\n                IOwinContext context = CreateStubOwinContext(owinRequest, owinResponse, isLocal: true);\n\n                // Act\n                await product.Invoke(context);\n\n                // Assert\n                Assert.Equal(500, statusCode);\n                using (HttpRequestMessage request = CreateRequest(includeErrorDetail: true))\n                using (HttpResponseMessage expectedResponse = request.CreateErrorResponse(\n                    HttpStatusCode.InternalServerError, expectedException))\n                {\n                    string expectedContents = await expectedResponse.Content.ReadAsStringAsync();\n                    Assert.Equal(expectedContents, Encoding.UTF8.GetString(output.ToArray()));\n                }\n            }\n        }\n\n        [Fact]\n        public async Task Invoke_IfBufferingErrorFaults_DisposesErrorResponse()\n        {\n            // Arrange\n            Exception expectedOriginalException = CreateException();\n            Exception expectedErrorException = CreateException();\n\n            using (HttpContent content = CreateFaultingContent(expectedOriginalException))\n            using (HttpResponseMessage expectedOriginalResponse = CreateResponse(content))\n            using (HttpMessageHandler messageHandler = CreateStubMessageHandler(expectedOriginalResponse))\n            using (HttpContent errorContent = CreateFaultingContent(expectedErrorException))\n            using (SpyDisposeHttpResponseMessage spy = new SpyDisposeHttpResponseMessage(errorContent))\n            using (CancellationTokenSource tokenSource = CreateCancellationTokenSource())\n            {\n                HttpMessageHandlerOptions options = CreateValidOptions(messageHandler);\n                options.BufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: true);\n                options.ExceptionHandler = CreateExceptionHandler(new ResponseMessageResult(spy));\n\n                using (HttpMessageHandlerAdapter product = CreateProductUnderTest(options))\n                {\n                    CancellationToken expectedCancellationToken = tokenSource.Token;\n                    IOwinRequest owinRequest = CreateFakeOwinRequest(expectedCancellationToken);\n                    IOwinResponse owinResponse = CreateFakeOwinResponse(Stream.Null);\n\n                    IOwinContext context = CreateStubOwinContext(owinRequest, owinResponse, isLocal: true);\n\n                    // Act\n                    await product.Invoke(context);\n\n                    // Assert\n                    Assert.True(spy.Disposed);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task Invoke_IfBufferingErrorFaults_CallsExceptionLogger()\n        {\n            // Arrange\n            Exception expectedOriginalException = CreateException();\n            Exception expectedErrorException = CreateException();\n\n            using (HttpContent content = CreateFaultingContent(expectedOriginalException))\n            using (HttpResponseMessage expectedOriginalResponse = CreateResponse(content))\n            using (HttpMessageHandler messageHandler = CreateStubMessageHandler(expectedOriginalResponse))\n            using (HttpContent errorContent = CreateFaultingContent(expectedErrorException))\n            using (HttpResponseMessage expectedErrorResponse = CreateResponse(errorContent))\n            using (CancellationTokenSource tokenSource = CreateCancellationTokenSource())\n            {\n                Mock<IExceptionLogger> mock = CreateStubExceptionLoggerMock();\n                IExceptionLogger exceptionLogger = mock.Object;\n\n                HttpMessageHandlerOptions options = CreateValidOptions(messageHandler);\n                options.BufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: true);\n                options.ExceptionLogger = exceptionLogger;\n                options.ExceptionHandler = CreateExceptionHandler(new ResponseMessageResult(expectedErrorResponse));\n\n                using (HttpMessageHandlerAdapter product = CreateProductUnderTest(options))\n                {\n                    CancellationToken expectedCancellationToken = tokenSource.Token;\n                    IOwinRequest owinRequest = CreateFakeOwinRequest(expectedCancellationToken);\n                    IOwinResponse owinResponse = CreateFakeOwinResponse(Stream.Null);\n\n                    IOwinContext context = CreateStubOwinContext(owinRequest, owinResponse, isLocal: true);\n\n                    // Act\n                    await product.Invoke(context);\n\n                    // Assert\n                    mock.Verify(l => l.LogAsync(It.Is<ExceptionLoggerContext>(c =>\n                        c.ExceptionContext != null\n                        && c.ExceptionContext.Exception == expectedOriginalException\n                        && c.ExceptionContext.CatchBlock ==\n                            OwinExceptionCatchBlocks.HttpMessageHandlerAdapterBufferContent\n                        && c.ExceptionContext.Request != null\n                        && c.ExceptionContext.Response == expectedOriginalResponse),\n                        expectedCancellationToken), Times.Once());\n                    mock.Verify(l => l.LogAsync(It.Is<ExceptionLoggerContext>(c =>\n                        c.ExceptionContext != null\n                        && c.ExceptionContext.Exception == expectedErrorException\n                        && c.ExceptionContext.CatchBlock ==\n                            OwinExceptionCatchBlocks.HttpMessageHandlerAdapterBufferError\n                        && c.ExceptionContext.Request != null\n                        && c.ExceptionContext.Response == expectedErrorResponse),\n                        expectedCancellationToken), Times.Once());\n                }\n            }\n        }\n\n        [Fact]\n        public async Task Invoke_IfBufferingErrorCancels_DoesNotCallExceptionLogger()\n        {\n            // Arrange\n            Exception expectedOriginalException = CreateException();\n            Exception expectedErrorException = new OperationCanceledException();\n\n            using (HttpContent content = CreateFaultingContent(expectedOriginalException))\n            using (HttpResponseMessage expectedOriginalResponse = CreateResponse(content))\n            using (HttpMessageHandler messageHandler = CreateStubMessageHandler(expectedOriginalResponse))\n            using (HttpContent errorContent = CreateFaultingContent(expectedErrorException))\n            using (HttpResponseMessage expectedErrorResponse = CreateResponse(errorContent))\n            using (CancellationTokenSource tokenSource = CreateCancellationTokenSource())\n            {\n                Mock<IExceptionLogger> mock = CreateStubExceptionLoggerMock();\n                IExceptionLogger exceptionLogger = mock.Object;\n\n                HttpMessageHandlerOptions options = CreateValidOptions(messageHandler);\n                options.BufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: true);\n                options.ExceptionLogger = exceptionLogger;\n                options.ExceptionHandler = CreateExceptionHandler(new ResponseMessageResult(expectedErrorResponse));\n\n                using (HttpMessageHandlerAdapter product = CreateProductUnderTest(options))\n                {\n                    CancellationToken expectedCancellationToken = tokenSource.Token;\n                    IOwinRequest owinRequest = CreateFakeOwinRequest(expectedCancellationToken);\n                    IOwinResponse owinResponse = CreateFakeOwinResponse(Stream.Null);\n\n                    IOwinContext context = CreateStubOwinContext(owinRequest, owinResponse, isLocal: true);\n\n                    // Act & Assert\n                    await Assert.ThrowsAsync<OperationCanceledException>(() => product.Invoke(context));\n\n                    mock.Verify(l => l.LogAsync(It.Is<ExceptionLoggerContext>(c =>\n                        c.ExceptionContext != null\n                        && c.ExceptionContext.Exception == expectedOriginalException\n                        && c.ExceptionContext.CatchBlock ==\n                            OwinExceptionCatchBlocks.HttpMessageHandlerAdapterBufferContent\n                        && c.ExceptionContext.Request != null\n                        && c.ExceptionContext.Response == expectedOriginalResponse),\n                        expectedCancellationToken), Times.Once());\n\n                    // This shouldn't be called for 'HttpMessageHandlerAdapterBufferError' because that's what's being\n                    // cancelled.\n                    mock.Verify(l => l.LogAsync(It.Is<ExceptionLoggerContext>(c =>\n                        c.ExceptionContext != null\n                        && c.ExceptionContext.Exception == expectedErrorException\n                        && c.ExceptionContext.CatchBlock ==\n                            OwinExceptionCatchBlocks.HttpMessageHandlerAdapterBufferError\n                        && c.ExceptionContext.Request != null\n                        && c.ExceptionContext.Response == expectedErrorResponse),\n                        expectedCancellationToken), Times.Never());\n                }\n            }\n        }\n\n        [Fact]\n        public async Task Invoke_IfBufferingErrorFaults_SendsEmptyErrorResponse()\n        {\n            // Arrange\n            IHostBufferPolicySelector bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false,\n                bufferOutput: true);\n\n            using (HttpContent content = CreateFaultingContent())\n            using (HttpResponseMessage response = CreateResponse(content))\n            using (HttpContent errorContent = CreateFaultingContent())\n            using (HttpResponseMessage errorResponse = CreateResponse(errorContent))\n            using (HttpMessageHandler messageHandler = CreateStubMessageHandler(response))\n            {\n                HttpMessageHandlerOptions options = CreateValidOptions(messageHandler);\n                options.BufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: true);\n                options.ExceptionHandler = CreateExceptionHandler(new ResponseMessageResult(errorResponse));\n\n                using (HttpMessageHandlerAdapter product = CreateProductUnderTest(options))\n                using (MemoryStream output = new MemoryStream())\n                {\n                    IOwinRequest owinRequest = CreateFakeOwinRequest();\n\n                    int statusCode = 0;\n                    Mock<IOwinResponse> mock = new Mock<IOwinResponse>();\n                    mock.Setup(r => r.Headers).Returns(new Mock<IHeaderDictionary>().Object);\n                    mock.SetupGet(r => r.Body).Returns(output);\n                    mock.SetupSet(r => r.StatusCode = It.IsAny<int>()).Callback<int>((v) => statusCode = v);\n                    IOwinResponse owinResponse = mock.Object;\n\n                    IOwinContext context = CreateStubOwinContext(owinRequest, owinResponse, isLocal: true);\n\n                    // Act\n                    await product.Invoke(context);\n\n                    // Assert\n                    Assert.Equal(500, statusCode);\n                    Assert.Equal(new byte[0], output.ToArray());\n                }\n            }\n        }\n\n        [Fact]\n        public async Task Invoke_IfStreamingFaults_ReturnsCanceledTask()\n        {\n            // Arrange\n            IHostBufferPolicySelector bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false,\n                bufferOutput: false);\n\n            using (HttpContent content = CreateFaultingContent())\n            using (HttpResponseMessage response = CreateResponse(content))\n            using (HttpMessageHandler messageHandler = CreateStubMessageHandler(response))\n            using (HttpMessageHandlerAdapter product = CreateProductUnderTest(CreateValidOptions(messageHandler,\n                bufferPolicySelector)))\n            {\n                IOwinRequest owinRequest = CreateFakeOwinRequest();\n                IOwinResponse owinResponse = CreateFakeOwinResponse();\n\n                IOwinContext context = CreateStubOwinContext(owinRequest, owinResponse);\n\n                // Act & Assert\n                await Assert.ThrowsAsync<TaskCanceledException>(() => product.Invoke(context));\n            }\n        }\n\n        [Fact]\n        public async Task Invoke_IfStreamingFaults_CallsExceptionLogger()\n        {\n            // Arrange\n            Exception expectedException = CreateException();\n\n            using (HttpContent content = CreateFaultingContent(expectedException))\n            using (HttpResponseMessage expectedResponse = CreateResponse(content))\n            using (HttpMessageHandler messageHandler = CreateStubMessageHandler(expectedResponse))\n            {\n                Mock<IExceptionLogger> mock = CreateStubExceptionLoggerMock();\n                IExceptionLogger exceptionLogger = mock.Object;\n\n                HttpMessageHandlerOptions options = CreateValidOptions(messageHandler);\n                options.BufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n                options.ExceptionLogger = exceptionLogger;\n\n                using (HttpMessageHandlerAdapter product = CreateProductUnderTest(options))\n                using (CancellationTokenSource tokenSource = CreateCancellationTokenSource())\n                {\n                    CancellationToken expectedCancellationToken = tokenSource.Token;\n                    IOwinRequest owinRequest = CreateFakeOwinRequest(expectedCancellationToken);\n\n                    IOwinResponse owinResponse = CreateFakeOwinResponse(Stream.Null);\n\n                    IOwinContext context = CreateStubOwinContext(owinRequest, owinResponse);\n\n                    // Act & Assert\n                    await Assert.ThrowsAsync<TaskCanceledException>(() => product.Invoke(context));\n\n                    mock.Verify(l => l.LogAsync(It.Is<ExceptionLoggerContext>((c) =>\n                        c != null\n                        && c.ExceptionContext != null\n                        && c.ExceptionContext.Exception == expectedException\n                        && c.ExceptionContext.CatchBlock ==\n                            OwinExceptionCatchBlocks.HttpMessageHandlerAdapterStreamContent\n                        && c.ExceptionContext.Request != null\n                        && c.ExceptionContext.Response == expectedResponse),\n                        expectedCancellationToken), Times.Once());\n                }\n            }\n        }\n\n        [Fact]\n        public async Task Invoke_IfStreamingCancels_DoesNotCallExceptionLogger()\n        {\n            // Arrange\n            Exception expectedException = new OperationCanceledException();\n\n            using (HttpContent content = CreateFaultingContent(expectedException))\n            using (HttpResponseMessage expectedResponse = CreateResponse(content))\n            using (HttpMessageHandler messageHandler = CreateStubMessageHandler(expectedResponse))\n            {\n                Mock<IExceptionLogger> mock = new Mock<IExceptionLogger>(MockBehavior.Strict);\n                IExceptionLogger exceptionLogger = mock.Object;\n\n                HttpMessageHandlerOptions options = CreateValidOptions(messageHandler);\n                options.BufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n                options.ExceptionLogger = exceptionLogger;\n\n                using (HttpMessageHandlerAdapter product = CreateProductUnderTest(options))\n                using (CancellationTokenSource tokenSource = CreateCancellationTokenSource())\n                {\n                    CancellationToken expectedCancellationToken = tokenSource.Token;\n                    IOwinRequest owinRequest = CreateFakeOwinRequest(expectedCancellationToken);\n\n                    IOwinResponse owinResponse = CreateFakeOwinResponse(Stream.Null);\n\n                    IOwinContext context = CreateStubOwinContext(owinRequest, owinResponse);\n\n                    // Act\n                    await Assert.ThrowsAsync<OperationCanceledException>(() => product.Invoke(context));\n                }\n            }\n        }\n\n        [Fact]\n        public async Task Invoke_IfTryComputeLengthThrows_CallsExceptionLogger()\n        {\n            // Arrange\n            Exception expectedException = CreateException();\n\n            using (HttpContent content = CreateThrowingContent(expectedException))\n            using (HttpResponseMessage expectedResponse = CreateResponse(content))\n            using (HttpMessageHandler messageHandler = CreateStubMessageHandler(expectedResponse))\n            {\n                Mock<IExceptionLogger> mock = CreateStubExceptionLoggerMock();\n                IExceptionLogger exceptionLogger = mock.Object;\n\n                HttpMessageHandlerOptions options = CreateValidOptions(messageHandler);\n                options.ExceptionLogger = exceptionLogger;\n\n                using (HttpMessageHandlerAdapter product = CreateProductUnderTest(options))\n                using (CancellationTokenSource tokenSource = CreateCancellationTokenSource())\n                {\n                    CancellationToken expectedCancellationToken = tokenSource.Token;\n                    IOwinRequest owinRequest = CreateFakeOwinRequest(expectedCancellationToken);\n\n                    IOwinResponse owinResponse = CreateFakeOwinResponse(Stream.Null);\n\n                    IOwinContext context = CreateStubOwinContext(owinRequest, owinResponse);\n\n                    // Act\n                    await product.Invoke(context);\n\n                    // Assert\n                    mock.Verify(l => l.LogAsync(It.Is<ExceptionLoggerContext>((c) =>\n                        c != null\n                        && c.ExceptionContext != null\n                        && c.ExceptionContext.Exception == expectedException\n                        && c.ExceptionContext.CatchBlock ==\n                            OwinExceptionCatchBlocks.HttpMessageHandlerAdapterComputeContentLength\n                        && c.ExceptionContext.Request != null\n                        && c.ExceptionContext.Response == expectedResponse),\n                        expectedCancellationToken), Times.Once());\n                }\n            }\n        }\n\n        [Fact]\n        public async Task Invoke_IfTryComputeLengthThrows_SendsEmptyErrorResponse()\n        {\n            // Arrange\n            Exception expectedException = CreateException();\n\n            using (HttpContent content = CreateThrowingContent(expectedException))\n            using (HttpResponseMessage response = CreateResponse(content))\n            using (HttpMessageHandler messageHandler = CreateStubMessageHandler(response))\n            {\n                HttpMessageHandlerOptions options = CreateValidOptions(messageHandler);\n\n                using (HttpMessageHandlerAdapter product = CreateProductUnderTest(options))\n                {\n                    IOwinRequest owinRequest = CreateFakeOwinRequest();\n\n                    Mock<IOwinResponse> owinResponseMock = new Mock<IOwinResponse>(MockBehavior.Strict);\n                    int statusCode = 0;\n                    owinResponseMock.SetupGet(r => r.Environment).Returns((IDictionary<string, object>)null);\n                    owinResponseMock.SetupSet(r => r.StatusCode = It.IsAny<int>()).Callback<int>(s => statusCode = s);\n                    int? contentLength = null;\n                    Mock<IHeaderDictionary> headersMock = new Mock<IHeaderDictionary>(MockBehavior.Strict);\n                    headersMock\n                        .As<IDictionary<string, string[]>>()\n                        .SetupSet(h => h[\"Content-Length\"] = It.IsAny<string[]>())\n                        .Callback<string, string[]>((i, v) => contentLength = int.Parse(v[0]));\n                    IHeaderDictionary headers = headersMock.Object;\n                    owinResponseMock.SetupGet(r => r.Headers).Returns(headers);\n                    IOwinResponse owinResponse = owinResponseMock.Object;\n\n                    IOwinContext context = CreateStubOwinContext(owinRequest, owinResponse);\n\n                    // Act\n                    await product.Invoke(context);\n\n                    // Assert\n                    Assert.Equal(500, statusCode);\n                    Assert.Equal(0, contentLength);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task Invoke_IfTryComputeLengthThrows_DoesNotEvaluateOutputBufferPolicy()\n        {\n            // Arrange\n            using (HttpContent content = CreateThrowingContent(CreateException()))\n            using (HttpResponseMessage response = CreateResponse(content))\n            using (HttpMessageHandler messageHandler = CreateStubMessageHandler(response))\n            {\n                HttpMessageHandlerOptions options = CreateValidOptions(messageHandler);\n\n                Mock<IHostBufferPolicySelector> bufferPolicyMock =\n                    new Mock<IHostBufferPolicySelector>(MockBehavior.Strict);\n                bufferPolicyMock\n                    .Setup(p => p.UseBufferedInputStream(It.IsAny<object>()))\n                    .Returns(false);\n                bool calledUseBufferedOutputStream = false;\n                bufferPolicyMock\n                    .Setup(p => p.UseBufferedOutputStream(It.IsAny<HttpResponseMessage>()))\n                    .Callback(() => calledUseBufferedOutputStream = true)\n                    .Returns(false);\n                options.BufferPolicySelector = bufferPolicyMock.Object;\n\n                using (HttpMessageHandlerAdapter product = CreateProductUnderTest(options))\n                {\n                    IOwinRequest owinRequest = CreateFakeOwinRequest();\n                    IOwinResponse owinResponse = CreateFakeOwinResponse(Stream.Null);\n                    IOwinContext context = CreateStubOwinContext(owinRequest, owinResponse);\n\n                    // Act\n                    await product.Invoke(context);\n\n                    // Assert\n                    Assert.False(calledUseBufferedOutputStream);\n                }\n            }\n        }\n\n        private static IHostBufferPolicySelector CreateBufferPolicySelector(bool bufferInput, bool bufferOutput)\n        {\n            var mock = new Mock<IHostBufferPolicySelector>();\n            mock.Setup(bps => bps.UseBufferedInputStream(It.IsAny<object>())).Returns(bufferInput);\n            mock.Setup(bps => bps.UseBufferedOutputStream(It.IsAny<HttpResponseMessage>())).Returns(bufferOutput);\n            return mock.Object;\n        }\n\n        private static CancellationTokenSource CreateCancellationTokenSource()\n        {\n            return new CancellationTokenSource();\n        }\n\n        private static IHostBufferPolicySelector CreateDummyBufferPolicy()\n        {\n            return new Mock<IHostBufferPolicySelector>(MockBehavior.Strict).Object;\n        }\n\n        private static IExceptionHandler CreateDummyExceptionHandler()\n        {\n            return new Mock<IExceptionHandler>(MockBehavior.Strict).Object;\n        }\n\n        private static IExceptionLogger CreateDummyExceptionLogger()\n        {\n            return new Mock<IExceptionLogger>(MockBehavior.Strict).Object;\n        }\n\n        private static HttpMessageHandler CreateDummyMessageHandler()\n        {\n            Mock<HttpMessageHandler> mock = new Mock<HttpMessageHandler>(MockBehavior.Strict);\n            mock.As<IDisposable>().Setup(c => c.Dispose());\n            return mock.Object;\n        }\n\n        private static HttpMessageHandlerOptions CreateDummyOptions(HttpMessageHandler messageHandler)\n        {\n            return new HttpMessageHandlerOptions\n            {\n                MessageHandler = messageHandler,\n                BufferPolicySelector = CreateDummyBufferPolicy(),\n                ExceptionLogger = CreateDummyExceptionLogger(),\n                ExceptionHandler = CreateDummyExceptionHandler()\n            };\n        }\n\n        private static Exception CreateException()\n        {\n            return new Exception();\n        }\n\n        private static IExceptionHandler CreateExceptionHandler(IHttpActionResult result)\n        {\n            Mock<IExceptionHandler> mock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n            mock\n                .Setup(h => h.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                .Callback<ExceptionHandlerContext, CancellationToken>((c, i) => c.Result = result)\n                .Returns(Task.FromResult(0));\n            return mock.Object;\n        }\n\n        private static Exception CreateExceptionWithCallStack()\n        {\n            try\n            {\n                throw CreateException();\n            }\n            catch (Exception exception)\n            {\n                return exception;\n            }\n        }\n\n        private static IHeaderDictionary CreateFakeHeaders()\n        {\n            return new HeaderDictionary(new Dictionary<string, string[]>());\n        }\n\n        private static IOwinRequest CreateFakeOwinRequest()\n        {\n            return CreateFakeOwinRequest(CancellationToken.None);\n        }\n\n        private static IOwinRequest CreateFakeOwinRequest(CancellationToken cancellationToken)\n        {\n            return CreateFakeOwinRequestMock(cancellationToken).Object;\n        }\n\n        private static IOwinRequest CreateFakeOwinRequest(Action disableBuffering)\n        {\n            Mock<IDictionary<string, object>> environmentMock = new Mock<IDictionary<string, object>>(MockBehavior.Strict);\n            object disableBufferingValue = disableBuffering;\n            environmentMock.Setup(d => d.TryGetValue(\"server.DisableRequestBuffering\", out disableBufferingValue)).Returns(true);\n            IDictionary<string, object> environment = environmentMock.Object;\n\n            Mock<IOwinRequest> mock = CreateFakeOwinRequestMock(CancellationToken.None);\n            mock.SetupGet(r => r.Environment).Returns(environment);\n            return mock.Object;\n        }\n\n        private static Mock<IOwinRequest> CreateFakeOwinRequestMock(CancellationToken cancellationToken)\n        {\n            Mock<IHeaderDictionary> headersMock = new Mock<IHeaderDictionary>(MockBehavior.Strict);\n            headersMock.Setup(h => h.GetEnumerator()).Returns(\n                new Mock<IEnumerator<KeyValuePair<string, string[]>>>().Object);\n\n            Mock<IOwinRequest> mock = new Mock<IOwinRequest>(MockBehavior.Strict);\n            mock.SetupGet(r => r.Method).Returns(\"GET\");\n            mock.SetupGet(r => r.Uri).Returns(new Uri(\"http://ignore\"));\n            mock.SetupGet(r => r.Body).Returns(Stream.Null);\n            mock.SetupGet(r => r.Headers).Returns(headersMock.Object);\n            mock.SetupGet(r => r.User).Returns((IPrincipal)null);\n            mock.SetupGet(r => r.CallCancelled).Returns(cancellationToken);\n            mock.SetupGet(r => r.Environment).Returns((IDictionary<string, object>)null);\n            return mock;\n        }\n\n        private static IOwinResponse CreateFakeOwinResponse()\n        {\n            return CreateFakeOwinResponseMock().Object;\n        }\n\n        private static IOwinResponse CreateFakeOwinResponse(Stream body)\n        {\n            Mock<IOwinResponse> mock = CreateFakeOwinResponseMock();\n            mock.SetupGet(r => r.Body).Returns(body);\n            return mock.Object;\n        }\n\n        private static IOwinResponse CreateFakeOwinResponse(Action disableBuffering)\n        {\n            Mock<IDictionary<string, object>> environmentMock = new Mock<IDictionary<string, object>>(MockBehavior.Strict);\n            object disableBufferingValue = disableBuffering;\n            environmentMock.Setup(d => d.TryGetValue(\"server.DisableResponseBuffering\", out disableBufferingValue)).Returns(true);\n            IDictionary<string, object> environment = environmentMock.Object;\n\n            Mock<IOwinResponse> mock = CreateFakeOwinResponseMock();\n            mock.SetupGet(r => r.Environment).Returns(environment);\n            return mock.Object;\n        }\n\n        private static Mock<IOwinResponse> CreateFakeOwinResponseMock()\n        {\n            Mock<IOwinResponse> mock = new Mock<IOwinResponse>();\n            mock.Setup(r => r.Headers).Returns(new Mock<IHeaderDictionary>().Object);\n            return mock;\n        }\n\n        private static IOwinResponse CreateFakeOwinResponseWithHeaders()\n        {\n            Mock<IOwinResponse> mock = new Mock<IOwinResponse>();\n            IHeaderDictionary headers = CreateFakeHeaders();\n            mock.Setup(r => r.Headers).Returns(headers);\n            return mock.Object;\n        }\n\n        private static Task CreateFaultedTask(Exception exception)\n        {\n            TaskCompletionSource<object> source = new TaskCompletionSource<object>();\n            source.SetException(exception);\n            return source.Task;\n        }\n\n        private static FaultingHttpContent CreateFaultingContent()\n        {\n            return CreateFaultingContent(CreateException());\n        }\n\n        private static FaultingHttpContent CreateFaultingContent(Exception exception)\n        {\n            return new FaultingHttpContent(exception);\n        }\n\n        private static MediaTypeFormatter CreateFaultingFormatter(Exception exception)\n        {\n            Mock<MediaTypeFormatter> mock = new Mock<MediaTypeFormatter>();\n            mock.Setup(f => f.CanWriteType(It.IsAny<Type>())).Returns(true);\n            mock.Setup(f => f.GetPerRequestFormatterInstance(It.IsAny<Type>(), It.IsAny<HttpRequestMessage>(),\n                It.IsAny<MediaTypeHeaderValue>())).Returns(mock.Object);\n            mock\n                .Setup(f => f.WriteToStreamAsync(It.IsAny<Type>(), It.IsAny<object>(), It.IsAny<Stream>(),\n                    It.IsAny<HttpContent>(), It.IsAny<TransportContext>()))\n                .Returns(CreateFaultedTask(exception));\n            return mock.Object;\n        }\n\n        private static HttpMessageHandler CreateLambdaMessageHandler(\n            Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> sendAsync)\n        {\n            return new LambdaHttpMessageHandler(sendAsync);\n        }\n\n        private static HandlerStub CreateOKHandlerStub()\n        {\n            var response = new HttpResponseMessage(HttpStatusCode.OK);\n            return new HandlerStub() { Response = response };\n        }\n\n        private static Dictionary<string, object> CreateOwinEnvironment(string method, string scheme, string hostHeaderValue, string pathBase, string path)\n        {\n            var environment = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);\n            environment[\"owin.RequestMethod\"] = method;\n            environment[\"owin.RequestScheme\"] = scheme;\n            environment[\"owin.RequestHeaders\"] = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase) { { \"Host\", new string[] { hostHeaderValue } } };\n            environment[\"owin.RequestPathBase\"] = pathBase;\n            environment[\"owin.RequestPath\"] = path;\n            environment[\"owin.RequestQueryString\"] = \"\";\n            environment[\"owin.RequestBody\"] = new MemoryStream();\n            environment[\"owin.CallCancelled\"] = new CancellationToken();\n            environment[\"owin.ResponseHeaders\"] = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase);\n            environment[\"owin.ResponseBody\"] = new MemoryStream();\n            return environment;\n        }\n\n        private static HttpMessageHandlerAdapter CreateProductUnderTest(HttpMessageHandlerOptions options)\n        {\n            return CreateProductUnderTest(next: null, options: options);\n        }\n\n        private static HttpMessageHandlerAdapter CreateProductUnderTest(OwinMiddleware next, HttpMessageHandlerOptions options)\n        {\n            return new HttpMessageHandlerAdapter(next, options);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private static HttpRequestMessage CreateRequest(bool includeErrorDetail)\n        {\n            HttpRequestMessage request = CreateRequest();\n            request.SetRequestContext(new HttpRequestContext\n            {\n                IncludeErrorDetail = includeErrorDetail\n            });\n            return request;\n        }\n\n        private static HttpResponseMessage CreateResponse()\n        {\n            return new HttpResponseMessage();\n        }\n\n        private static HttpResponseMessage CreateResponse(HttpContent content)\n        {\n            return new HttpResponseMessage\n            {\n                Content = content\n            };\n        }\n\n        private static Mock<IExceptionHandler> CreateStubExceptionHandlerMock()\n        {\n            Mock<IExceptionHandler> mock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n            mock\n                .Setup(h => h.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                .Returns(Task.FromResult(0));\n            return mock;\n        }\n\n        private static IExceptionLogger CreateStubExceptionLogger()\n        {\n            return CreateStubExceptionLoggerMock().Object;\n        }\n\n        private static Mock<IExceptionLogger> CreateStubExceptionLoggerMock()\n        {\n            Mock<IExceptionLogger> mock = new Mock<IExceptionLogger>(MockBehavior.Strict);\n            mock\n                .Setup(l => l.LogAsync(It.IsAny<ExceptionLoggerContext>(), It.IsAny<CancellationToken>()))\n                .Returns(Task.FromResult(0));\n            return mock;\n        }\n\n        private static HttpMessageHandler CreateStubMessageHandler(HttpResponseMessage response)\n        {\n            return new LambdaHttpMessageHandler((r, c) => Task.FromResult(response));\n        }\n\n        private static IOwinContext CreateStubOwinContext(IOwinRequest request, IOwinResponse response)\n        {\n            Mock<IOwinContext> mock = new Mock<IOwinContext>(MockBehavior.Strict);\n            mock.Setup(c => c.Request).Returns(request);\n            mock.Setup(c => c.Response).Returns(response);\n            return mock.Object;\n        }\n\n        private static IOwinContext CreateStubOwinContext(IOwinRequest request, IOwinResponse response, bool isLocal)\n        {\n            Mock<IOwinContext> mock = new Mock<IOwinContext>(MockBehavior.Strict);\n            mock.Setup(c => c.Request).Returns(request);\n            mock.Setup(c => c.Response).Returns(response);\n            mock.Setup(c => c.Get<bool>(\"server.IsLocal\")).Returns(isLocal);\n            return mock.Object;\n        }\n\n        private static ThrowingHttpContent CreateThrowingContent(Exception exception)\n        {\n            return new ThrowingHttpContent(exception);\n        }\n\n        private static HttpMessageHandlerOptions CreateValidOptions(HttpMessageHandler messageHandler)\n        {\n            IHostBufferPolicySelector bufferPolicy =\n                CreateBufferPolicySelector(bufferInput: false, bufferOutput: false);\n            return CreateValidOptions(messageHandler, bufferPolicy);\n        }\n\n        private static HttpMessageHandlerOptions CreateValidOptions(HttpMessageHandler messageHandler,\n            IHostBufferPolicySelector bufferPolicySelector)\n        {\n            return new HttpMessageHandlerOptions\n            {\n                MessageHandler = messageHandler,\n                BufferPolicySelector = bufferPolicySelector,\n                ExceptionLogger = new EmptyExceptionLogger(),\n                ExceptionHandler = new DefaultExceptionHandler()\n            };\n        }\n\n        public class HandlerStub : HttpMessageHandler\n        {\n            public HttpRequestMessage Request { get; private set; }\n            public CancellationToken CancellationToken { get; private set; }\n            public HttpResponseMessage Response { get; set; }\n            public IPrincipal User { get; set; }\n            public bool AddNoRouteMatchedKey { get; set; }\n\n            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n            {\n                Request = request;\n                CancellationToken = cancellationToken;\n                User = Thread.CurrentPrincipal;\n\n                if (AddNoRouteMatchedKey)\n                {\n                    request.Properties[HttpPropertyKeys.NoRouteMatched] = true;\n                }\n\n                return Task.FromResult<HttpResponseMessage>(Response);\n            }\n        }\n\n        private class LambdaHttpMessageHandler : HttpMessageHandler\n        {\n            private readonly Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> _sendAsync;\n\n            public LambdaHttpMessageHandler(\n                Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> sendAsync)\n            {\n                _sendAsync = sendAsync;\n            }\n\n            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,\n                CancellationToken cancellationToken)\n            {\n                return _sendAsync.Invoke(request, cancellationToken);\n            }\n        }\n\n        private class FaultingHttpContent : HttpContent\n        {\n            private readonly Exception _exception;\n\n            public FaultingHttpContent(Exception exception)\n            {\n                _exception = exception;\n            }\n\n            protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)\n            {\n                return CreateFaultedTask(_exception);\n            }\n\n            protected override bool TryComputeLength(out long length)\n            {\n                length = 0;\n                return false;\n            }\n        }\n\n        private class SpyDisposeFaultingHttpContent : HttpContent\n        {\n            private readonly Exception _exception;\n\n            public SpyDisposeFaultingHttpContent(Exception exception)\n            {\n                _exception = exception;\n            }\n\n            public bool Disposed { get; private set; }\n\n            protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)\n            {\n                return CreateFaultedTask(_exception);\n            }\n\n            protected override bool TryComputeLength(out long length)\n            {\n                length = 0;\n                return false;\n            }\n\n            protected override void Dispose(bool disposing)\n            {\n                Disposed = true;\n                base.Dispose(disposing);\n            }\n        }\n\n        private class SpyDisposeHttpMessageHandler : HttpMessageHandler\n        {\n            public bool Disposed { get; private set; }\n\n            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,\n                CancellationToken cancellationToken)\n            {\n                throw new NotImplementedException();\n            }\n\n            protected override void Dispose(bool disposing)\n            {\n                Disposed = true;\n            }\n        }\n\n        private class SpyDisposeHttpResponseMessage : HttpResponseMessage\n        {\n            public SpyDisposeHttpResponseMessage(HttpContent content)\n            {\n                Content = content;\n            }\n\n            public bool Disposed { get; private set; }\n\n            protected override void Dispose(bool disposing)\n            {\n                Disposed = true;\n                base.Dispose(disposing);\n            }\n        }\n\n        private class SpyDisposeStream : Stream\n        {\n            public bool Disposed { get; private set; }\n\n            public override bool CanRead\n            {\n                get { return false; }\n            }\n\n            public override bool CanSeek\n            {\n                get { return false; }\n            }\n\n            public override bool CanWrite\n            {\n                get { return true; }\n            }\n\n            public override void Flush()\n            {\n            }\n\n            public override long Length\n            {\n                get { return 0; }\n            }\n\n            public override long Position\n            {\n                get\n                {\n                    return 0;\n                }\n                set\n                {\n                }\n            }\n\n            public override int Read(byte[] buffer, int offset, int count)\n            {\n                return 0;\n            }\n\n            public override long Seek(long offset, SeekOrigin origin)\n            {\n                throw new NotSupportedException();\n            }\n\n            public override void SetLength(long value)\n            {\n            }\n\n            public override void Write(byte[] buffer, int offset, int count)\n            {\n            }\n\n            protected override void Dispose(bool disposing)\n            {\n                Disposed = true;\n                base.Dispose(disposing);\n            }\n        }\n\n        private class ThrowingHttpContent : HttpContent\n        {\n            private readonly Exception _exception;\n\n            public ThrowingHttpContent(Exception exception)\n            {\n                _exception = exception;\n            }\n\n            protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)\n            {\n                throw _exception;\n            }\n\n            protected override bool TryComputeLength(out long length)\n            {\n                throw _exception;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Owin.Test/HttpMessageHandlerExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.Owin\n{\n    internal static class HttpMessageHandlerExtensions\n    {\n        public static Task<HttpResponseMessage> SendAsync(this HttpMessageHandler handler, HttpRequestMessage request,\n            CancellationToken cancellationToken)\n        {\n            HttpMessageInvoker invoker = new HttpMessageInvoker(handler, disposeHandler: false);\n            return invoker.SendAsync(request, cancellationToken);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Owin.Test/HttpMessageHandlerOptionsTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Hosting;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Owin\n{\n    public class HttpMessageHandlerOptionsTests\n    {\n        [Fact]\n        public void MessageHandlerGet_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            HttpMessageHandlerOptions product = CreateProductUnderTest();\n\n            using (HttpMessageHandler expectedMessageHandler = CreateDummyMessageHandler())\n            {\n                product.MessageHandler = expectedMessageHandler;\n\n                // Act\n                HttpMessageHandler messageHandler = product.MessageHandler;\n\n                // Assert\n                Assert.Same(expectedMessageHandler, messageHandler);\n            }\n        }\n\n        [Fact]\n        public void BufferPolicySelectorGet_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            HttpMessageHandlerOptions product = CreateProductUnderTest();\n            IHostBufferPolicySelector expectedBufferPolicySelector = CreateDummyBufferPolicy();\n            product.BufferPolicySelector = expectedBufferPolicySelector;\n\n            // Act\n            IHostBufferPolicySelector bufferPolicy = product.BufferPolicySelector;\n\n            // Assert\n            Assert.Same(expectedBufferPolicySelector, bufferPolicy);\n        }\n\n        [Fact]\n        public void ExceptionLoggerGet_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            HttpMessageHandlerOptions product = CreateProductUnderTest();\n            IExceptionLogger expectedExceptionLogger = CreateDummyExceptionLogger();\n            product.ExceptionLogger = expectedExceptionLogger;\n\n            // Act\n            IExceptionLogger exceptionLogger = product.ExceptionLogger;\n\n            // Assert\n            Assert.Same(expectedExceptionLogger, exceptionLogger);\n        }\n\n        [Fact]\n        public void ExceptionHandlerGet_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            HttpMessageHandlerOptions product = CreateProductUnderTest();\n            IExceptionHandler expectedExceptionHandler = CreateDummyExceptionHandler();\n            product.ExceptionHandler = expectedExceptionHandler;\n\n            // Act\n            IExceptionHandler exceptionHandler = product.ExceptionHandler;\n\n            // Assert\n            Assert.Same(expectedExceptionHandler, exceptionHandler);\n        }\n\n        [Fact]\n        public void AppDisposingGet_ReturnsSpecifiedValue()\n        {\n            // Arrange\n            using (CancellationTokenSource tokenSource = CreateCancellationTokenSource())\n            {\n                HttpMessageHandlerOptions product = CreateProductUnderTest();\n                CancellationToken expectedAppDisposing = tokenSource.Token;\n                product.AppDisposing = expectedAppDisposing;\n\n                // Act\n                CancellationToken appDisposing = product.AppDisposing;\n\n                // Assert\n                Assert.Equal(expectedAppDisposing, appDisposing);\n            }\n        }\n\n        private static CancellationTokenSource CreateCancellationTokenSource()\n        {\n            return new CancellationTokenSource();\n        }\n\n        private static IHostBufferPolicySelector CreateDummyBufferPolicy()\n        {\n            return new Mock<IHostBufferPolicySelector>(MockBehavior.Strict).Object;\n        }\n\n        private static IExceptionHandler CreateDummyExceptionHandler()\n        {\n            return new Mock<IExceptionHandler>(MockBehavior.Strict).Object;\n        }\n\n        private static IExceptionLogger CreateDummyExceptionLogger()\n        {\n            return new Mock<IExceptionLogger>(MockBehavior.Strict).Object;\n        }\n\n        private static HttpMessageHandler CreateDummyMessageHandler()\n        {\n            Mock<HttpMessageHandler> mock = new Mock<HttpMessageHandler>(MockBehavior.Strict);\n            mock.As<IDisposable>().Setup(c => c.Dispose());\n            return mock.Object;\n        }\n\n        private static HttpMessageHandlerOptions CreateProductUnderTest()\n        {\n            return new HttpMessageHandlerOptions();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Owin.Test/IgnoreRouteTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Net.Http;\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.Owin.ExceptionHandling;\nusing System.Web.Http.Routing;\nusing Microsoft.Owin;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Owin\n{\n    public class IgnoreRouteIntegrationTests\n    {\n        [Fact]\n        public void Invoke_IfRouteIsIgnored_CallsNextMiddleware()\n        {\n            // Arrange\n            int expectedStatusCode = 123;\n            string pathToIgnoreRoute = \"ignore\";\n            OwinMiddleware next = CreateStubMiddleware(expectedStatusCode);\n\n            using (HttpServer server = new HttpServer())\n            {\n                server.Configuration.Routes.IgnoreRoute(\"IgnoreRouteName\", pathToIgnoreRoute);\n                server.Configuration.MapHttpAttributeRoutes(); // See IgnoreController\n\n                OwinMiddleware product = CreateProductUnderTest(next, server);\n\n                IOwinRequest request = CreateStubRequest(new Uri(\"http://somehost/\" + pathToIgnoreRoute));\n\n                Mock<IOwinResponse> mock = CreateStubResponseMock();\n                int statusCode = 0;\n                mock.SetupSet(r => r.StatusCode = It.IsAny<int>()).Callback<int>((s) => statusCode = s);\n                IOwinResponse response = mock.Object;\n\n                IOwinContext context = CreateStubContext(request, response);\n\n                // Act\n                Task task = product.Invoke(context);\n\n                // Assert\n                Assert.NotNull(task);\n                task.WaitUntilCompleted();\n                task.ThrowIfFaulted();\n\n                Assert.Equal(expectedStatusCode, statusCode);\n            }\n        }\n\n        [Fact]\n        public void Invoke_IfRouteIsIgnored_WithConstraints_CallsNextMiddleware()\n        {\n            // Arrange\n            int expectedStatusCode = 0;\n            string pathToIgnoreRoute = \"constraint/10\";\n\n            using (HttpServer server = new HttpServer())\n            {\n                server.Configuration.Routes.IgnoreRoute(\"Constraints\", \"constraint/{id}\", constraints: new { constraint = new CustomConstraint() });\n                server.Configuration.MapHttpAttributeRoutes(); // See IgnoreController\n\n                OwinMiddleware product = CreateProductUnderTest(null, server);\n\n                IOwinRequest request = CreateStubRequest(new Uri(\"http://somehost/\" + pathToIgnoreRoute));\n\n                Mock<IOwinResponse> mock = CreateStubResponseMock();\n                int statusCode = 0;\n                mock.SetupSet(r => r.StatusCode = It.IsAny<int>()).Callback<int>((s) => statusCode = s);\n                IOwinResponse response = mock.Object;\n\n                IOwinContext context = CreateStubContext(request, response);\n\n                // Act\n                Task task = product.Invoke(context);\n\n                // Assert\n                Assert.NotNull(task);\n                task.WaitUntilCompleted();\n                task.ThrowIfFaulted();\n\n                Assert.Equal(expectedStatusCode, statusCode);\n            }\n        }\n\n        private static IOwinContext CreateStubContext(IOwinRequest request, IOwinResponse response)\n        {\n            Mock<IOwinContext> mock = new Mock<IOwinContext>(MockBehavior.Strict);\n            mock.SetupGet(c => c.Request).Returns(request);\n            mock.SetupGet(c => c.Response).Returns(response);\n            mock.Setup(c => c.Get<bool>(\"server.IsLocal\")).Returns(true);\n            return mock.Object;\n        }\n\n        private static OwinMiddleware CreateStubMiddleware(int statusCode)\n        {\n            Mock<OwinMiddleware> mock = new Mock<OwinMiddleware>(MockBehavior.Strict, null);\n            mock\n                .Setup(m => m.Invoke(It.IsAny<IOwinContext>()))\n                .Callback<IOwinContext>((c) => c.Response.StatusCode = statusCode)\n                .Returns(Task.FromResult(0));\n            return mock.Object;\n        }\n\n        private static IOwinRequest CreateStubRequest(Uri uri)\n        {\n            Mock<IOwinRequest> mock = new Mock<IOwinRequest>(MockBehavior.Strict);\n            mock.SetupGet(r => r.CallCancelled).Returns(CancellationToken.None);\n            mock.SetupGet(r => r.Environment).Returns((IDictionary<string, object>)null);\n            mock.SetupGet(r => r.Body).Returns(Stream.Null);\n            mock.SetupGet(r => r.Method).Returns(\"GET\");\n            mock.SetupGet(r => r.Uri).Returns(uri);\n            mock.SetupGet(r => r.PathBase).Returns(new PathString(String.Empty));\n            mock.SetupGet(r => r.Headers).Returns(CreateFakeHeaders());\n            mock.SetupGet(r => r.User).Returns((IPrincipal)null);\n            return mock.Object;\n        }\n\n        private static Mock<IOwinResponse> CreateStubResponseMock()\n        {\n            Mock<IOwinResponse> mock = new Mock<IOwinResponse>(MockBehavior.Strict);\n            mock.SetupSet(r => r.ReasonPhrase = It.IsAny<string>());\n            mock.SetupGet(r => r.Environment).Returns((IDictionary<string, object>)null);\n            mock.SetupGet(r => r.Headers).Returns(CreateFakeHeaders());\n            mock.SetupGet(r => r.Body).Returns(Stream.Null);\n            return mock;\n        }\n\n        private static IHeaderDictionary CreateFakeHeaders()\n        {\n            return new HeaderDictionary(new Dictionary<string, string[]>());\n        }\n\n        private static HttpMessageHandlerAdapter CreateProductUnderTest(OwinMiddleware next, HttpMessageHandler messageHandler)\n        {\n            return new HttpMessageHandlerAdapter(next: next, options: new HttpMessageHandlerOptions\n            {\n                MessageHandler = messageHandler,\n                BufferPolicySelector = new Mock<IHostBufferPolicySelector>().Object,\n                ExceptionLogger = new EmptyExceptionLogger(),\n                ExceptionHandler = new Mock<IExceptionHandler>().Object\n            });\n        }\n\n        public class IgnoreController : ApiController\n        {\n            [Route(\"ignore\")]\n            [Route(\"constraint/10\")]\n            public IHttpActionResult Get()\n            {\n                return Ok();\n            }\n        }\n\n        public class CustomConstraint : IHttpRouteConstraint\n        {\n            public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName,\n                IDictionary<string, object> values, HttpRouteDirection routeDirection)\n            {\n                long id;\n                if (values.ContainsKey(\"id\")\n                    && Int64.TryParse(values[\"id\"].ToString(), out id)\n                    && (id == 10))\n                {\n                    return true;\n                }\n\n                return false;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Owin.Test/NonOwnedStreamTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing Microsoft.TestCommon;\nusing Moq;\nusing Moq.Protected;\n\nnamespace System.Web.Http.Owin\n{\n    public class NonOwnedStreamTests\n    {\n        [Fact]\n        public void Constructor_IfInnerStreamIsNull_Throws()\n        {\n            // Arrange\n            Stream innerStream = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => CreateProductUnderTest(innerStream), \"innerStream\");\n        }\n\n        [Fact]\n        public void Read_DelegatesToInnerStream()\n        {\n            // Arrange\n            Mock<Stream> mock = new Mock<Stream>(MockBehavior.Strict);\n            int expectedBytesRead = 123;\n            mock.Setup(s => s.Read(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>()))\n                .Returns(expectedBytesRead);\n            mock.Setup(s => s.Close());\n            mock.As<IDisposable>().Setup(s => s.Dispose());\n\n            using (Stream innerStream = mock.Object)\n            using (Stream product = CreateProductUnderTest(innerStream))\n            {\n                byte[] expectedBuffer = new byte[0];\n                int expectedOffset = 456;\n                int expectedCount = 789;\n\n                // Act\n                int bytesRead = product.Read(expectedBuffer, expectedOffset, expectedCount);\n\n                // Assert\n                Assert.Equal(expectedBytesRead, bytesRead);\n                mock.Verify(s => s.Read(expectedBuffer, expectedOffset, expectedCount), Times.Once());\n            }\n        }\n\n        [Fact]\n        public void Read_IfDisposed_Throws()\n        {\n            // Arrange\n            Mock<Stream> mock = new Mock<Stream>(MockBehavior.Strict);\n            mock.Setup(s => s.Close());\n            mock.As<IDisposable>().Setup(s => s.Dispose());\n\n            using (Stream innerStream = mock.Object)\n            using (Stream product = CreateProductUnderTest(innerStream))\n            {\n                byte[] buffer = new byte[0];\n                int offset = 0;\n                int count = 0;\n\n                product.Dispose();\n\n                // Act & Assert\n                Assert.Throws<ObjectDisposedException>(() => product.Read(buffer, offset, count));\n            }\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void CanRead_DelegatesToInnerStream(bool expectedCanRead)\n        {\n            // Arrange\n            Mock<Stream> mock = new Mock<Stream>(MockBehavior.Strict);\n            mock.SetupGet(s => s.CanRead)\n                .Returns(expectedCanRead);\n            mock.Setup(s => s.Close());\n            mock.As<IDisposable>().Setup(s => s.Dispose());\n\n            using (Stream innerStream = mock.Object)\n            using (Stream product = CreateProductUnderTest(innerStream))\n            {\n                // Act\n                bool canRead = product.CanRead;\n\n                // Assert\n                Assert.Equal(expectedCanRead, canRead);\n            }\n        }\n\n        [Fact]\n        public void CanRead_IfDisposed_ReturnsFalse()\n        {\n            // Arrange\n            Mock<Stream> mock = new Mock<Stream>(MockBehavior.Strict);\n            mock.Setup(s => s.Close());\n            mock.As<IDisposable>().Setup(s => s.Dispose());\n\n            using (Stream innerStream = mock.Object)\n            using (Stream product = CreateProductUnderTest(innerStream))\n            {\n                product.Dispose();\n\n                // Act\n                bool canRead = product.CanRead;\n\n                // Assert\n                Assert.False(canRead);\n            }\n        }\n\n        [Fact]\n        public void Dispose_DoesNotDisposeInnerStream()\n        {\n            // Arrange\n            bool innerStreamDisposed = false;\n            Mock<Stream> mock = new Mock<Stream>(MockBehavior.Strict);\n            mock.Setup(s => s.Close()).Callback(() => innerStreamDisposed = true);\n            mock.As<IDisposable>().Setup(s => s.Dispose());\n            mock.Protected().Setup(\"Dispose\", exactParameterMatch: true, args: true).Callback(() => innerStreamDisposed = true);\n\n            using (Stream innerStream = mock.Object)\n            using (Stream product = CreateProductUnderTest(innerStream))\n            {\n                product.Dispose();\n\n                // Act & Assert\n                Assert.False(innerStreamDisposed);\n            }\n        }\n\n        [Fact]\n        public void Dispose_IfCalledTwice_DoesNotThrow()\n        {\n            // Arrange\n            Mock<Stream> mock = new Mock<Stream>(MockBehavior.Strict);\n            mock.Setup(s => s.Close());\n            mock.As<IDisposable>().Setup(s => s.Dispose());\n\n            using (Stream innerStream = mock.Object)\n            using (Stream product = CreateProductUnderTest(innerStream))\n            {\n                product.Dispose();\n\n                // Act & Assert\n                Assert.DoesNotThrow(() => product.Dispose());\n            }\n        }\n\n        [Fact]\n        public void Close_DoesNotDisposeInnerStream()\n        {\n            // Arrange\n            bool innerStreamDisposed = false;\n            Mock<Stream> mock = new Mock<Stream>(MockBehavior.Strict);\n            mock.Setup(s => s.Close()).Callback(() => innerStreamDisposed = true);\n            mock.As<IDisposable>().Setup(s => s.Dispose());\n            mock.Protected().Setup(\"Dispose\", exactParameterMatch: true, args: true).Callback(() => innerStreamDisposed = true);\n\n            using (Stream innerStream = mock.Object)\n            using (Stream product = CreateProductUnderTest(innerStream))\n            {\n                product.Close();\n\n                // Act & Assert\n                Assert.False(innerStreamDisposed);\n            }\n        }\n\n        [Fact]\n        public void Close_DisposesThisObject()\n        {\n            // Arrange\n            Mock<Stream> mock = new Mock<Stream>(MockBehavior.Strict);\n            mock.Setup(s => s.Close());\n            mock.As<IDisposable>().Setup(s => s.Dispose());\n\n            using (Stream innerStream = mock.Object)\n            using (Stream product = CreateProductUnderTest(innerStream))\n            {\n                product.Close();\n\n                byte[] buffer = new byte[0];\n                int offset = 0;\n                int count = 0;\n\n                // Act & Assert\n                Assert.Throws<ObjectDisposedException>(() => product.Read(buffer, offset, count));\n            }\n        }\n\n        private static NonOwnedStream CreateProductUnderTest(Stream innerStream)\n        {\n            return new NonOwnedStream(innerStream);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Owin.Test/OwinBufferPolicySelectorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Threading;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Owin\n{\n    public class OwinBufferPolicySelectorTest\n    {\n        [Fact]\n        public void UseBufferedInputStream_ReturnsFalse()\n        {\n            Assert.False(new OwinBufferPolicySelector().UseBufferedInputStream(null));\n        }\n\n        [Fact]\n        public void UseBufferedOutputStream_ReturnsTrue_ForObjectContent()\n        {\n            HttpResponseMessage response = new HttpResponseMessage();\n            response.Content = new ObjectContent<string>(\"blue\", new JsonMediaTypeFormatter());\n\n            Assert.True(new OwinBufferPolicySelector().UseBufferedOutputStream(response));\n        }\n\n        [Fact]\n        public void UseBufferedOutputStream_ReturnsFalse_ForSpecifiedContentLength()\n        {\n            HttpResponseMessage response = new HttpResponseMessage();\n            response.Content = new ObjectContent<string>(\"blue\", new JsonMediaTypeFormatter());\n            response.Content.Headers.ContentLength = 5;\n\n            Assert.False(new OwinBufferPolicySelector().UseBufferedOutputStream(response));\n        }\n\n        [Fact]\n        public void UseBufferedOutputStream_ReturnsFalse_ForChunkedTransferEncoding()\n        {\n            HttpResponseMessage response = new HttpResponseMessage();\n            response.Headers.TransferEncodingChunked = true;\n            response.Content = new ObjectContent<string>(\"blue\", new JsonMediaTypeFormatter());\n\n            Assert.False(new OwinBufferPolicySelector().UseBufferedOutputStream(response));\n        }\n\n        [Fact]\n        public void UseBufferedOutputStream_ReturnsFalse_ForStreamContent()\n        {\n            HttpResponseMessage response = new HttpResponseMessage();\n            response.Content = new StreamContent(new MemoryStream());\n\n            Assert.False(new OwinBufferPolicySelector().UseBufferedOutputStream(response));\n        }\n\n        [Fact]\n        public void UseBufferedOutputStream_ReturnsFalse_ForPushStreamContent()\n        {\n            HttpResponseMessage response = new HttpResponseMessage();\n            response.Content = new PushStreamContent((s, c, tc) => { return; });\n\n            Assert.False(new OwinBufferPolicySelector().UseBufferedOutputStream(response));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Owin.Test/OwinExceptionCatchBlocksTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Web.Http.ExceptionHandling;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Owin\n{\n    public class OwinExceptionCatchBlocksTests\n    {\n        [Fact]\n        public void HttpMessageHandlerAdapterBufferContent_IsSpecifiedValue()\n        {\n            // Act\n            ExceptionContextCatchBlock catchBlock = OwinExceptionCatchBlocks.HttpMessageHandlerAdapterBufferContent;\n\n            // Assert\n            ExceptionContextCatchBlock expected =\n                new ExceptionContextCatchBlock(\"HttpMessageHandlerAdapter.BufferContent\", isTopLevel: true,\n                    callsHandler: true);\n            AssertEqual(expected, catchBlock);\n        }\n\n        [Fact]\n        public void HttpMessageHandlerAdapterBufferContent_IsSameInstance()\n        {\n            // Arrange\n            ExceptionContextCatchBlock first = OwinExceptionCatchBlocks.HttpMessageHandlerAdapterBufferContent;\n\n            // Act\n            ExceptionContextCatchBlock second = OwinExceptionCatchBlocks.HttpMessageHandlerAdapterBufferContent;\n\n            // Assert\n            Assert.Same(first, second);\n        }\n\n        [Fact]\n        public void HttpMessageHandlerAdapterBufferError_IsSpecifiedValue()\n        {\n            // Act\n            ExceptionContextCatchBlock catchBlock = OwinExceptionCatchBlocks.HttpMessageHandlerAdapterBufferError;\n\n            // Assert\n            ExceptionContextCatchBlock expected =\n                new ExceptionContextCatchBlock(\"HttpMessageHandlerAdapter.BufferError\", isTopLevel: true,\n                    callsHandler: false);\n            AssertEqual(expected, catchBlock);\n        }\n\n        [Fact]\n        public void HttpMessageHandlerAdapterBufferError_IsSameInstance()\n        {\n            // Arrange\n            ExceptionContextCatchBlock first = OwinExceptionCatchBlocks.HttpMessageHandlerAdapterBufferError;\n\n            // Act\n            ExceptionContextCatchBlock second = OwinExceptionCatchBlocks.HttpMessageHandlerAdapterBufferError;\n\n            // Assert\n            Assert.Same(first, second);\n        }\n\n        [Fact]\n        public void HttpMessageHandlerAdapterComputeContentLength_IsSpecifiedValue()\n        {\n            // Act\n            ExceptionContextCatchBlock catchBlock =\n                OwinExceptionCatchBlocks.HttpMessageHandlerAdapterComputeContentLength;\n\n            // Assert\n            ExceptionContextCatchBlock expected =\n                new ExceptionContextCatchBlock(\"HttpMessageHandlerAdapter.ComputeContentLength\", isTopLevel: true,\n                    callsHandler: false);\n            AssertEqual(expected, catchBlock);\n        }\n\n        [Fact]\n        public void HttpMessageHandlerAdapterComputeContentLength_IsSameInstance()\n        {\n            // Arrange\n            ExceptionContextCatchBlock first = OwinExceptionCatchBlocks.HttpMessageHandlerAdapterComputeContentLength;\n\n            // Act\n            ExceptionContextCatchBlock second = OwinExceptionCatchBlocks.HttpMessageHandlerAdapterComputeContentLength;\n\n            // Assert\n            Assert.Same(first, second);\n        }\n\n        [Fact]\n        public void HttpMessageHandlerAdapterStreamContent_IsSpecifiedValue()\n        {\n            // Act\n            ExceptionContextCatchBlock catchBlock = OwinExceptionCatchBlocks.HttpMessageHandlerAdapterStreamContent;\n\n            // Assert\n            ExceptionContextCatchBlock expected =\n                new ExceptionContextCatchBlock(\"HttpMessageHandlerAdapter.StreamContent\", isTopLevel: true,\n                    callsHandler: false);\n            AssertEqual(expected, catchBlock);\n        }\n\n        [Fact]\n        public void HttpMessageHandlerAdapterStreamContent_IsSameInstance()\n        {\n            // Arrange\n            ExceptionContextCatchBlock first = OwinExceptionCatchBlocks.HttpMessageHandlerAdapterStreamContent;\n\n            // Act\n            ExceptionContextCatchBlock second = OwinExceptionCatchBlocks.HttpMessageHandlerAdapterStreamContent;\n\n            // Assert\n            Assert.Same(first, second);\n        }\n\n        private static void AssertEqual(ExceptionContextCatchBlock expected, ExceptionContextCatchBlock actual)\n        {\n            if (expected == null)\n            {\n                Assert.Null(actual);\n                return;\n            }\n\n            Assert.NotNull(actual);\n            Assert.Equal(expected.Name, actual.Name);\n            Assert.Equal(expected.IsTopLevel, actual.IsTopLevel);\n            Assert.Equal(expected.CallsHandler, actual.CallsHandler);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Owin.Test/OwinHostIntegrationTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Microsoft.Owin.Hosting;\nusing Microsoft.TestCommon;\nusing Newtonsoft.Json.Linq;\nusing Owin;\n\nnamespace System.Web.Http.Owin\n{\n    [Xunit.Collection(\"PortReserver Collection\")] // Avoid conflicts between different PortReserver consumers.\n    public class OwinHostIntegrationTest\n    {\n        [Fact]\n        public async Task SimpleGet_Works()\n        {\n            using (var port = new PortReserver())\n            using (WebApp.Start<OwinHostIntegrationTest>(url: CreateBaseUrl(port)))\n            {\n                HttpClient client = new HttpClient();\n\n                var response = await client.GetAsync(CreateUrl(port, \"HelloWorld\"));\n\n                Assert.True(response.IsSuccessStatusCode);\n                Assert.Equal(\"\\\"Hello from OWIN\\\"\", await response.Content.ReadAsStringAsync());\n                Assert.Null(response.Headers.TransferEncodingChunked);\n            }\n        }\n\n        [Fact]\n        public async Task SimplePost_Works()\n        {\n            using (var port = new PortReserver())\n            using (WebApp.Start<OwinHostIntegrationTest>(url: CreateBaseUrl(port)))\n            {\n                HttpClient client = new HttpClient();\n                var content = new StringContent(\"\\\"Echo this\\\"\", Encoding.UTF8, \"application/json\");\n\n                var response = await client.PostAsync(CreateUrl(port, \"Echo\"), content);\n\n                Assert.True(response.IsSuccessStatusCode);\n                Assert.Equal(\"\\\"Echo this\\\"\", await response.Content.ReadAsStringAsync());\n                Assert.Null(response.Headers.TransferEncodingChunked);\n            }\n        }\n\n        [Fact]\n        public async Task GetThatThrowsDuringSerializations_RespondsWith500()\n        {\n            using (var port = new PortReserver())\n            using (WebApp.Start<OwinHostIntegrationTest>(url: CreateBaseUrl(port)))\n            {\n                HttpClient client = new HttpClient();\n\n                var response = await client.GetAsync(CreateUrl(port, \"Error\"));\n\n                Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n                JObject json = Assert.IsType<JObject>(JToken.Parse(await response.Content.ReadAsStringAsync()));\n                JToken exceptionMessage;\n                Assert.True(json.TryGetValue(\"ExceptionMessage\", out exceptionMessage));\n                Assert.Null(response.Headers.TransferEncodingChunked);\n            }\n        }\n\n        private static string CreateBaseUrl(PortReserver port)\n        {\n            return port.BaseUri + \"vroot\";\n        }\n\n        private static string CreateUrl(PortReserver port, string localPath)\n        {\n            return CreateBaseUrl(port) + \"/\" + localPath;\n        }\n\n#pragma warning disable xUnit1013 // Public method should be marked as test\n        public void Configuration(IAppBuilder appBuilder)\n#pragma warning restore xUnit1013 // Public method should be marked as test\n        {\n            var config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}\");\n            appBuilder.UseWebApi(config);\n        }\n    }\n\n    public class HelloWorldController : ApiController\n    {\n        public string Get()\n        {\n            return \"Hello from OWIN\";\n        }\n    }\n\n    public class EchoController : ApiController\n    {\n        public string Post([FromBody] string s)\n        {\n            return s;\n        }\n    }\n\n    public class ErrorController : ApiController\n    {\n        public ExceptionThrower Get()\n        {\n            return new ExceptionThrower();\n        }\n\n        public class ExceptionThrower\n        {\n            public string Throws\n            {\n                get\n                {\n                    throw new InvalidOperationException();\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Owin.Test/OwinHttpConfigurationExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.Owin;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http\n{\n    public class OwinHttpConfigurationExtensionsTest\n    {\n        [Fact]\n        public void SuppressDefaultHostAuthentication_InsertsPassiveAuthenticationMessageHandler()\n        {\n            // Arrange\n            DelegatingHandler existingHandler = new Mock<DelegatingHandler>(MockBehavior.Strict).Object;\n\n            using (HttpConfiguration configuration = new HttpConfiguration())\n            {\n                configuration.MessageHandlers.Add(existingHandler);\n\n                // Act\n                configuration.SuppressDefaultHostAuthentication();\n\n                // Assert\n                Assert.Equal(2, configuration.MessageHandlers.Count);\n                DelegatingHandler firstHandler = configuration.MessageHandlers[0];\n                Assert.IsType<PassiveAuthenticationMessageHandler>(firstHandler);\n            }\n        }\n\n        [Fact]\n        public void SuppressDefaultHostAuthentication_Throws_WhenConfigurationIsNull()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() =>\n            {\n                OwinHttpConfigurationExtensions.SuppressDefaultHostAuthentication(null);\n            }, \"configuration\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Owin.Test/OwinHttpRequestContextTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Security.Cryptography.X509Certificates;\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Routing;\nusing Microsoft.Owin;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Owin\n{\n    public class OwinHttpRequestContextTests\n    {\n        [Fact]\n        public void ContextGet_ReturnsProvidedInstance()\n        {\n            // Arrange\n            IOwinContext expectedOwinContext = CreateStubOwinContext();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                OwinHttpRequestContext context = CreateProductUnderTest(expectedOwinContext, request);\n\n                // Act\n                IOwinContext owinContext = context.Context;\n\n                // Assert\n                Assert.Same(expectedOwinContext, owinContext);\n            }\n        }\n\n        [Fact]\n        public void RequestGet_ReturnsProvidedInstance()\n        {\n            // Arrange\n            IOwinContext owinContext = CreateStubOwinContext();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                OwinHttpRequestContext context = CreateProductUnderTest(owinContext, expectedRequest);\n\n                // Act\n                HttpRequestMessage request = context.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public void ClientCertificateGet_ReturnsContextClientCertificate()\n        {\n            // Arrange\n            X509Certificate2 expectedCertificate = CreateCertificate();\n            Mock<IOwinContext> owinContextMock = CreateOwinContextMock();\n            owinContextMock\n                .Setup(c => c.Get<X509Certificate2>(OwinConstants.ClientCertifiateKey))\n                .Returns(expectedCertificate);\n            IOwinContext owinContext = owinContextMock.Object;\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(owinContext, request);\n\n                // Act\n                X509Certificate2 certificate = context.ClientCertificate;\n\n                // Assert\n                Assert.Same(expectedCertificate, certificate);\n            }\n        }\n\n        [Fact]\n        public void ClientCertificateGet_ReturnsNull_ByDefault()\n        {\n            // Arrange\n            IOwinContext owinContext = new OwinContext();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(owinContext, request);\n\n                // Act\n                X509Certificate2 certificate = context.ClientCertificate;\n\n                // Assert\n                Assert.Null(certificate);\n            }\n        }\n\n        [Fact]\n        public void ClientCertificateSet_UpdatesClientCertificate()\n        {\n            // Arrange\n            IOwinContext owinContext = CreateStubOwinContext();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(owinContext, request);\n                X509Certificate2 expectedCertificate = CreateCertificate();\n\n                // Act\n                context.ClientCertificate = expectedCertificate;\n\n                // Assert\n                X509Certificate2 certificate = context.ClientCertificate;\n                Assert.Same(expectedCertificate, certificate);\n            }\n        }\n\n        [Fact]\n        public void ClientCertificateSet_UpdatesClientCertificate_WhenNull()\n        {\n            // Arrange\n            Mock<IOwinContext> owinContextMock = CreateOwinContextMock();\n            owinContextMock\n                .Setup(c => c.Get<X509Certificate2>(OwinConstants.ClientCertifiateKey))\n                .Returns(CreateCertificate());\n            IOwinContext owinContext = owinContextMock.Object;\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(owinContext, request);\n\n                // Act\n                context.ClientCertificate = null;\n\n                // Assert\n                X509Certificate2 certificate = context.ClientCertificate;\n                Assert.Null(certificate);\n            }\n        }\n\n        [Fact]\n        public void ClientCertificateGet_ReturnsFirstObservedContextClientCertificate()\n        {\n            // Arrange\n            X509Certificate2 expectedCertificate = CreateCertificate();\n            X509Certificate2 currentCertificate = expectedCertificate;\n            Mock<IOwinContext> owinContextMock = CreateOwinContextMock();\n            owinContextMock\n                .Setup(c => c.Get<X509Certificate2>(OwinConstants.ClientCertifiateKey))\n                .Returns(() => currentCertificate);\n            IOwinContext owinContext = owinContextMock.Object;\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(owinContext, request);\n                X509Certificate2 ignore = context.ClientCertificate;\n                currentCertificate = CreateCertificate();\n\n                // Act\n                X509Certificate2 certificate = context.ClientCertificate;\n\n                // Assert\n                Assert.Same(expectedCertificate, certificate);\n            }\n        }\n\n        [Fact]\n        public void IncludeErrorDetailGet_ReturnsFalse_ByDefault()\n        {\n            // Arrange\n            IOwinContext owinContext = new OwinContext();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(owinContext, request);\n\n                // Act\n                bool includeErrorDetail = context.IncludeErrorDetail;\n\n                // Assert\n                Assert.False(includeErrorDetail);\n            }\n        }\n\n        [Fact]\n        public void IncludeErrorDetailGet_ReturnsTrue_WhenUnconfiguredAndIsLocal()\n        {\n            // Arrange\n            IOwinContext owinContext = CreateStubOwinContext();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(owinContext, request);\n                context.IsLocal = true;\n\n                // Act\n                bool includeErrorDetail = context.IncludeErrorDetail;\n\n                // Assert\n                Assert.True(includeErrorDetail);\n            }\n        }\n\n        [Theory]\n        [InlineData(true, IncludeErrorDetailPolicy.Always, true)]\n        [InlineData(true, IncludeErrorDetailPolicy.Always, false)]\n        [InlineData(false, IncludeErrorDetailPolicy.Never, true)]\n        [InlineData(false, IncludeErrorDetailPolicy.Never, false)]\n        [InlineData(true, IncludeErrorDetailPolicy.LocalOnly, true)]\n        [InlineData(false, IncludeErrorDetailPolicy.LocalOnly, false)]\n        [InlineData(true, IncludeErrorDetailPolicy.Default, true)]\n        [InlineData(false, IncludeErrorDetailPolicy.Default, false)]\n        public void IncludeErrorDetailGet_ForPolicy(bool expected, IncludeErrorDetailPolicy policy, bool isLocal)\n        {\n            // Arrange\n            IOwinContext owinContext = CreateStubOwinContext();\n\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(owinContext, request);\n                context.Configuration = configuration;\n                context.IsLocal = isLocal;\n                configuration.IncludeErrorDetailPolicy = policy;\n\n                // Act\n                bool includeErrorDetail = context.IncludeErrorDetail;\n\n                // Assert\n                Assert.Equal(expected, includeErrorDetail);\n            }\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void IncludeErrorDetailSet_UpdatesIncludeErrorDetail(bool expectedIncludeErrorDetail)\n        {\n            // Arrange\n            IOwinContext owinContext = CreateStubOwinContext();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(owinContext, request);\n\n                // Act\n                context.IncludeErrorDetail = expectedIncludeErrorDetail;\n\n                // Assert\n                bool includeErrorDetail = context.IncludeErrorDetail;\n                Assert.Equal(expectedIncludeErrorDetail, includeErrorDetail);\n            }\n        }\n\n        [Theory]\n        [InlineData(true, IncludeErrorDetailPolicy.Never)]\n        [InlineData(false, IncludeErrorDetailPolicy.Always)]\n        public void IncludeErrorDetailSet_OverridesPolicy(bool expected, IncludeErrorDetailPolicy policy)\n        {\n            // Arrange\n            IOwinContext owinContext = CreateStubOwinContext();\n\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(owinContext, request);\n                context.Configuration = configuration;\n                configuration.IncludeErrorDetailPolicy = policy;\n\n                // Act\n                context.IncludeErrorDetail = expected;\n\n                // Assert\n                bool includeErrorDetail = context.IncludeErrorDetail;\n                Assert.Equal(expected, includeErrorDetail);\n            }\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void IncludeErrorDetailGet_ReturnsFirstObservedValue(bool expectedIncludeErrorDetail)\n        {\n            // Arrange\n            IOwinContext owinContext = CreateStubOwinContext();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(owinContext, request);\n                context.IsLocal = expectedIncludeErrorDetail;\n                bool ignore = context.IncludeErrorDetail;\n                context.IsLocal = !expectedIncludeErrorDetail;\n\n                // Act\n                bool includeErrorDetail = context.IncludeErrorDetail;\n\n                // Assert\n                Assert.Equal(expectedIncludeErrorDetail, includeErrorDetail);\n            }\n        }\n\n        [Fact]\n        public void IsLocalGet_ReturnsFalse_ByDefault()\n        {\n            // Arrange\n            IOwinContext owinContext = new OwinContext();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(owinContext, request);\n\n                // Act\n                bool isLocal = context.IsLocal;\n\n                // Assert\n                Assert.False(isLocal);\n            }\n        }\n\n        [Theory]\n        [InlineData(false)]\n        [InlineData(true)]\n        public void IsLocal_ReturnsContextIsLocalValue(bool expectedIsLocal)\n        {\n            // Arrange\n            Mock<IOwinContext> owinContextMock = CreateOwinContextMock();\n            owinContextMock.Setup(c => c.Get<bool>(OwinConstants.IsLocalKey)).Returns(expectedIsLocal);\n            IOwinContext owinContext = owinContextMock.Object;\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(owinContext, request);\n\n                // Act\n                bool isLocal = context.IsLocal;\n\n                // Assert\n                Assert.Equal(expectedIsLocal, isLocal);\n            }\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void IsLocalSet_UpdatesIsLocal(bool expectedIsLocal)\n        {\n            // Arrange\n            IOwinContext owinContext = CreateStubOwinContext();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(owinContext, request);\n\n                // Act\n                context.IsLocal = expectedIsLocal;\n\n                // Assert\n                bool isLocal = context.IsLocal;\n                Assert.Equal(expectedIsLocal, isLocal);\n            }\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void IsLocalGet_ReturnsFirstObservedValue(bool expectedIsLocal)\n        {\n            // Arrange\n            Mock<IOwinContext> owinContextMock = CreateOwinContextMock();\n            bool currentOwinContextIsLocal = expectedIsLocal;\n            owinContextMock.Setup(c => c.Get<bool>(OwinConstants.IsLocalKey)).Returns(() => currentOwinContextIsLocal);\n            IOwinContext owinContext = owinContextMock.Object;\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(owinContext, request);\n                bool ignore = context.IsLocal;\n                currentOwinContextIsLocal = !expectedIsLocal;\n\n                // Act\n                bool isLocal = context.IsLocal;\n\n                // Assert\n                Assert.Equal(expectedIsLocal, isLocal);\n            }\n        }\n\n        [Fact]\n        public void PrincipalGet_ReturnsContextRequestUser()\n        {\n            // Arrange\n            IPrincipal expectedPrincipal = CreateDummyPrincipal();\n            Mock<IOwinRequest> owinRequestMock = new Mock<IOwinRequest>(MockBehavior.Strict);\n            owinRequestMock.Setup(r => r.User).Returns(expectedPrincipal);\n            IOwinContext owinContext = CreateStubOwinContext(owinRequestMock.Object);\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(owinContext, request);\n\n                // Act\n                IPrincipal principal = context.Principal;\n\n                // Assert\n                Assert.Same(expectedPrincipal, principal);\n            }\n        }\n\n        [Fact]\n        [RestoreThreadPrincipal]\n        public void PrincipalSet_UpdatesContextRequestUser()\n        {\n            // Arrange\n            Mock<IOwinRequest> owinRequestMock = new Mock<IOwinRequest>(MockBehavior.Strict);\n            IPrincipal principal = null;\n            owinRequestMock.SetupSet((r) => r.User = It.IsAny<IPrincipal>()).Callback<IPrincipal>(\n                value => { principal = value; });\n            IOwinContext owinContext = CreateStubOwinContext(owinRequestMock.Object);\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(owinContext, request);\n                IPrincipal expectedPrincipal = CreateDummyPrincipal();\n\n                // Act\n                context.Principal = expectedPrincipal;\n\n                // Assert\n                Assert.Same(expectedPrincipal, principal);\n            }\n        }\n\n        [Fact]\n        [RestoreThreadPrincipal]\n        public void PrincipalSet_UpdatesThreadCurrentPrincipal()\n        {\n            // Arrange\n            IOwinContext owinContext = CreateStubOwinContext(new Mock<IOwinRequest>().Object);\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(owinContext, request);\n                IPrincipal expectedPrincipal = CreateDummyPrincipal();\n\n                // Act\n                context.Principal = expectedPrincipal;\n\n                // Assert\n                IPrincipal principal = Thread.CurrentPrincipal;\n                Assert.Same(expectedPrincipal, principal);\n            }\n        }\n\n        [Fact]\n        public void UrlGet_ReturnsUrlHelperForRequest()\n        {\n            // Arrange\n            IOwinContext owinContext = CreateStubOwinContext();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(owinContext, expectedRequest);\n\n                // Act\n                UrlHelper url = context.Url;\n\n                // Assert\n                Assert.NotNull(url);\n                Assert.Same(expectedRequest, url.Request);\n            }\n        }\n\n        [Fact]\n        public void UrlGet_ReturnsSameInstance()\n        {\n            // Arrange\n            IOwinContext owinContext = CreateStubOwinContext();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(owinContext, request);\n                UrlHelper firstUrl = context.Url;\n\n                // Act\n                UrlHelper url = context.Url;\n\n                // Assert\n                Assert.Same(firstUrl, url);\n            }\n        }\n\n        [Fact]\n        public void UrlSet_UpdatesUrl()\n        {\n            // Arrange\n            IOwinContext owinContext = CreateStubOwinContext();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(owinContext, request);\n                UrlHelper expectedUrl = CreateDummyUrlHelper();\n\n                // Act\n                context.Url = expectedUrl;\n\n                // Assert\n                UrlHelper url = context.Url;\n                Assert.Same(expectedUrl, url);\n            }\n        }\n\n        [Fact]\n        public void UrlSet_UpdatesUrl_WhenNull()\n        {\n            // Arrange\n            IOwinContext owinContext = CreateStubOwinContext();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(owinContext, request);\n\n                // Act\n                context.Url = null;\n\n                // Assert\n                UrlHelper url = context.Url;\n                Assert.Null(url);\n            }\n        }\n\n        [Fact]\n        public void VirtualPathRootGet_ReturnsSlash_ByDefault()\n        {\n            // Arrange\n            IOwinContext owinContext = new OwinContext();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(owinContext, request);\n\n                // Act\n                string virtualPathRoot = context.VirtualPathRoot;\n\n                // Assert\n                Assert.Equal(\"/\", virtualPathRoot);\n            }\n        }\n\n        [Fact]\n        public void VirtualPathRootGet_ReturnsContextRequestPathBase()\n        {\n            // Arrange\n            string expectedVirtualPathRoot = \"/foo\";\n            Mock<IOwinRequest> owinRequestMock = new Mock<IOwinRequest>(MockBehavior.Strict);\n            owinRequestMock.Setup(r => r.PathBase).Returns(new PathString(expectedVirtualPathRoot));\n            IOwinContext owinContext = CreateStubOwinContext(owinRequestMock.Object);\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(owinContext, request);\n\n                // Act\n                string virtualPathRoot = context.VirtualPathRoot;\n\n                // Assert\n                Assert.Equal(expectedVirtualPathRoot, virtualPathRoot);\n            }\n        }\n\n        // Regression test for #203.\n        [Fact]\n        public void VirtualPathRootGet_ReturnsUnescapedContextRequestPathBase()\n        {\n            // Arrange\n            var expectedVirtualPathRoot = \"/a b\";\n            var owinRequestMock = new Mock<IOwinRequest>(MockBehavior.Strict);\n            owinRequestMock\n                .Setup(r => r.PathBase)\n                .Returns(new PathString(expectedVirtualPathRoot));\n\n            var owinContext = CreateStubOwinContext(owinRequestMock.Object);\n            using (var request = CreateRequest())\n            {\n                var context = CreateProductUnderTest(owinContext, request);\n\n                // Act\n                var virtualPathRoot = context.VirtualPathRoot;\n\n                // Assert\n                Assert.Equal(expectedVirtualPathRoot, virtualPathRoot);\n            }\n        }\n\n        [Theory]\n        [InlineData(null)]\n        [InlineData(\"\")]\n        public void VirtualPathRootGet_ReturnsSlash_WhenContextRequestPathBaseIsValue(string contextRequestPathBase)\n        {\n            // Arrange\n            Mock<IOwinRequest> owinRequestMock = new Mock<IOwinRequest>(MockBehavior.Strict);\n            owinRequestMock.Setup(r => r.PathBase).Returns(new PathString(contextRequestPathBase));\n            IOwinContext owinContext = CreateStubOwinContext(owinRequestMock.Object);\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(owinContext, request);\n\n                // Act\n                string virtualPathRoot = context.VirtualPathRoot;\n\n                // Assert\n                Assert.Equal(\"/\", virtualPathRoot);\n            }\n        }\n\n        [Fact]\n        public void VirtualPathRootSet_UpdatesVirtualPathRoot()\n        {\n            // Arrange\n            IOwinContext owinContext = CreateStubOwinContext();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(owinContext, request);\n                string expectedVirtualPathRoot = \"foo\";\n\n                // Act\n                context.VirtualPathRoot = expectedVirtualPathRoot;\n\n                // Assert\n                string virtualPathRoot = context.VirtualPathRoot;\n                Assert.Same(expectedVirtualPathRoot, virtualPathRoot);\n            }\n        }\n\n        [Fact]\n        public void VirtualPathRootSet_UpdatesVirtualPathRoot_WhenNull()\n        {\n            // Arrange\n            Mock<IOwinRequest> owinRequestMock = new Mock<IOwinRequest>(MockBehavior.Strict);\n            owinRequestMock.Setup(r => r.PathBase).Returns(new PathString(\"/other\"));\n            IOwinContext owinContext = CreateStubOwinContext(owinRequestMock.Object);\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(owinContext, request);\n\n                // Act\n                context.VirtualPathRoot = null;\n\n                // Assert\n                string virtualPathRoot = context.VirtualPathRoot;\n                Assert.Null(virtualPathRoot);\n            }\n        }\n\n        [Fact]\n        public void VirtualPathRootGet_ReturnsFirstObservedContextRequestPathBase()\n        {\n            // Arrange\n            string expectedVirtualPathRoot = \"/expected\";\n            string currentVirtualPathRoot = expectedVirtualPathRoot;\n            Mock<IOwinRequest> owinRequestMock = new Mock<IOwinRequest>(MockBehavior.Strict);\n            owinRequestMock.Setup(r => r.PathBase).Returns(() => new PathString(currentVirtualPathRoot));\n            IOwinContext owinContext = CreateStubOwinContext(owinRequestMock.Object);\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(owinContext, request);\n                string ignore = context.VirtualPathRoot;\n                currentVirtualPathRoot = \"/other\";\n\n                // Act\n                string virtualPathRoot = context.VirtualPathRoot;\n\n                // Assert\n                Assert.Equal(expectedVirtualPathRoot, virtualPathRoot);\n            }\n        }\n\n        private static X509Certificate2 CreateCertificate()\n        {\n            return new X509Certificate2();\n        }\n\n        private static HttpConfiguration CreateConfiguration()\n        {\n            return new HttpConfiguration();\n        }\n\n        private static IOwinRequest CreateDummyOwinRequest()\n        {\n            return new Mock<IOwinRequest>(MockBehavior.Strict).Object;\n        }\n\n        private static IPrincipal CreateDummyPrincipal()\n        {\n            return new Mock<IPrincipal>(MockBehavior.Strict).Object;\n        }\n\n        private static UrlHelper CreateDummyUrlHelper()\n        {\n            return new Mock<UrlHelper>(MockBehavior.Strict).Object;\n        }\n\n        private static Mock<IOwinContext> CreateOwinContextMock()\n        {\n            Mock<IOwinContext> mock = new Mock<IOwinContext>(MockBehavior.Strict);\n            mock.Setup(c => c.Request).Returns(CreateDummyOwinRequest());\n            return mock;\n        }\n\n        private static OwinHttpRequestContext CreateProductUnderTest(IOwinContext context, HttpRequestMessage request)\n        {\n            return new OwinHttpRequestContext(context, request);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private static IOwinContext CreateStubOwinContext()\n        {\n            return CreateOwinContextMock().Object;\n        }\n\n        private static IOwinContext CreateStubOwinContext(IOwinRequest request)\n        {\n            Mock<IOwinContext> mock = new Mock<IOwinContext>(MockBehavior.Strict);\n            mock.Setup(c => c.Request).Returns(request);\n            return mock.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Owin.Test/OwinHttpRequestMessageExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing Microsoft.Owin;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Owin\n{\n    public class OwinHttpRequestMessageExtensionsTest\n    {\n        [Fact]\n        public void GetOwinContext_Throws_WhenRequestIsNull()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { OwinHttpRequestMessageExtensions.GetOwinContext(null); }, \"request\");\n        }\n\n        [Fact]\n        public void GetOwinContext_ReturnsNull_WhenNotSet()\n        {\n            // Act & Assert\n            Assert.Null(new HttpRequestMessage().GetOwinContext());\n        }\n\n        [Fact]\n        public void GetOwinContext_ReturnsSetContextInstance()\n        {\n            // Arrange\n            var request = new HttpRequestMessage();\n            var context = new OwinContext();\n            request.SetOwinContext(context);\n\n            // Act & Asert\n            Assert.Same(context, request.GetOwinContext());\n        }\n\n        [Fact]\n        public void SetOwinContext_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            var context = new OwinContext();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { OwinHttpRequestMessageExtensions.SetOwinContext(null, context); },\n                \"request\");\n        }\n\n        [Fact]\n        public void GetOwinContext_ReturnsOwinContextAndRemovesEnvironmentProperty_AfterSetEnvironmentProperty()\n        {\n            // Arrange\n            using (HttpRequestMessage request = new HttpRequestMessage())\n            {\n                var environment = new Dictionary<string, object>();\n                request.Properties.Add(\"MS_OwinEnvironment\", environment);\n\n                // Act\n                var context = request.GetOwinContext();\n\n                // Assert\n                Assert.NotNull(context);\n                Assert.Same(environment, context.Environment);\n                Assert.False(request.Properties.ContainsKey(\"MS_OwinEnvironment\"));\n            }\n        }\n\n        [Fact]\n        public void SetOwinContext_RemovesOwinEnvironmentProperty_WhenPresent()\n        {\n            // Arrange\n            using (HttpRequestMessage request = new HttpRequestMessage())\n            {\n                var environment = new Dictionary<string, object>();\n                request.Properties.Add(\"MS_OwinEnvironment\", environment);\n                var context = new OwinContext();\n\n                // Act\n                request.SetOwinContext(context);\n\n                // Assert\n                Assert.False(request.Properties.ContainsKey(\"MS_OwinEnvironment\"));\n            }\n        }\n\n        [Fact]\n        public void SetOwinContext_Throws_WhenContextIsNull()\n        {\n            // Arrange\n            var request = new HttpRequestMessage();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { OwinHttpRequestMessageExtensions.SetOwinContext(request, null); },\n                \"context\");\n        }\n\n        [Fact]\n        public void GetOwinEnvironment_Throws_WhenRequestIsNull()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { OwinHttpRequestMessageExtensions.GetOwinEnvironment(null); }, \"request\");\n        }\n\n        [Fact]\n        public void GetOwinEnvironment_ReturnsNull_WhenNotSet()\n        {\n            // Act & Assert\n            Assert.Null(new HttpRequestMessage().GetOwinEnvironment());\n        }\n\n        [Fact]\n        public void GetOwinEnvironment_ReturnsSetEnvironmentInstance()\n        {\n            // Arrange\n            var request = new HttpRequestMessage();\n            var environment = new Dictionary<string, object>();\n            request.SetOwinEnvironment(environment);\n\n            // Act & Assert\n            Assert.Same(environment, request.GetOwinEnvironment());\n        }\n\n        [Fact]\n        public void GetOwinEnvironment_ReturnsSetContextEnvironmentInstance()\n        {\n            // Arrange\n            var request = new HttpRequestMessage();\n            var environment = new Dictionary<string, object>();\n            var context = new OwinContext(environment);\n            request.SetOwinContext(context);\n\n            // Act & Assert\n            Assert.Same(environment, request.GetOwinEnvironment());\n        }\n\n        [Fact]\n        public void GetOwinContext_ReturnsOwinContext_AfterSetContextEnvironment()\n        {\n            // Arrange\n            var request = new HttpRequestMessage();\n            var environment = new Dictionary<string, object>();\n            request.SetOwinEnvironment(environment);\n\n            // Act\n            IOwinContext context = request.GetOwinContext();\n\n            // Assert\n            Assert.IsType<OwinContext>(context);\n            Assert.Same(environment, context.Environment);\n        }\n\n        [Fact]\n        public void SetOwinEnvironment_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            var environment = new Dictionary<string, object>();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => { OwinHttpRequestMessageExtensions.SetOwinEnvironment(null, environment); }, \"request\");\n        }\n\n        [Fact]\n        public void SetOwinEnvironment_Throws_WhenEnvironmentIsNull()\n        {\n            // Arrange\n            var request = new HttpRequestMessage();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { OwinHttpRequestMessageExtensions.SetOwinEnvironment(request, null); },\n                \"environment\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Owin.Test/OwinRequestExtensionsTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing Microsoft.Owin;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Owin\n{\n    public class OwinRequestExtensionsTests\n    {\n        [Fact]\n        public void DisableBuffering_IfActionIsAvailable_CallsAction()\n        {\n            // Arrange\n            bool bufferingDisabled = false;\n            Action disableBufferingAction = () => bufferingDisabled = true;\n            IDictionary<string, object> environment = CreateStubEnvironment(disableBufferingAction);\n            IOwinRequest request = CreateStubRequest(environment);\n\n            // Act\n            OwinRequestExtensions.DisableBuffering(request);\n\n            // Assert\n            Assert.True(bufferingDisabled);\n        }\n\n        [Fact]\n        public void DisableBuffering_IfRequestIsNull_Throws()\n        {\n            // Arrange\n            IOwinRequest request = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => OwinRequestExtensions.DisableBuffering(request), \"request\");\n        }\n\n        [Fact]\n        public void DisableBuffering_IfEnvironmentIsNull_DoesNotThrow()\n        {\n            // Arrange\n            IDictionary<string, object> environment = null;\n            IOwinRequest request = CreateStubRequest(environment);\n\n            // Act & Assert\n            Assert.DoesNotThrow(() => request.DisableBuffering());\n        }\n\n        [Fact]\n        public void DisableBuffering_IfServerDisableResponseBufferingIsAbsent_DoesNotThrow()\n        {\n            // Arrange\n            Mock<IDictionary<string, object>> environmentMock = new Mock<IDictionary<string, object>>(MockBehavior.Strict);\n            IDictionary<string, object> environment = CreateStubEnvironment(null, hasDisableBufferingAction: false);\n            IOwinRequest request = CreateStubRequest(environment);\n\n            // Act & Assert\n            Assert.DoesNotThrow(() => request.DisableBuffering());\n        }\n\n        [Fact]\n        public void DisableBuffering_IfServerDisableResponseBufferingIsNotAction_DoesNotThrow()\n        {\n            // Arrange\n            object nonAction = new object();\n            IDictionary<string, object> environment = CreateStubEnvironment(nonAction);\n            IOwinRequest request = CreateStubRequest(environment);\n\n            // Act & Assert\n            Assert.DoesNotThrow(() => request.DisableBuffering());\n        }\n\n        [Fact]\n        public void GetContentLength_IfHeadersIsNull_ReturnsNull()\n        {\n            // Arrange\n            IOwinRequest request = CreateStubRequest(headers: null);\n            Assert.Null(request.Headers); // Guard\n\n            // Act\n            int? length = OwinRequestExtensions.GetContentLength(request);\n\n            // Assert\n            Assert.False(length.HasValue);\n        }\n\n        [Fact]\n        public void GetContentLength_IfHeadersDoesNotContainContentLengthHeader_ReturnsNull()\n        {\n            // Arrange\n            IHeaderDictionary headers = CreateStubHeaders();\n            IOwinRequest request = CreateStubRequest(headers);\n\n            // Act\n            int? length = OwinRequestExtensions.GetContentLength(request);\n\n            // Assert\n            Assert.False(length.HasValue);\n        }\n\n        [Fact]\n        public void GetContentLength_IfContentLengthHeaderValuesIsNull_ReturnsNull()\n        {\n            // Arrange\n            IHeaderDictionary headers = CreateStubHeaders(\"Content-Length\", null);\n            IOwinRequest request = CreateStubRequest(headers);\n\n            // Act\n            int? length = OwinRequestExtensions.GetContentLength(request);\n\n            // Assert\n            Assert.False(length.HasValue);\n        }\n\n        [Fact]\n        public void GetContentLength_IfContentLengthHeaderValuesIsEmpty_ReturnsNull()\n        {\n            // Arrange\n            IHeaderDictionary headers = CreateStubHeaders(\"Content-Length\", new string[0]);\n            IOwinRequest request = CreateStubRequest(headers);\n\n            // Act\n            int? length = OwinRequestExtensions.GetContentLength(request);\n\n            // Assert\n            Assert.False(length.HasValue);\n        }\n\n        [Fact]\n        public void GetContentLength_IfContentLengthHeaderValuesIsMultiple_ReturnsNull()\n        {\n            // Arrange\n            IHeaderDictionary headers = CreateStubHeaders(\"Content-Length\", new string[] { \"123\", \"456\" });\n            IOwinRequest request = CreateStubRequest(headers);\n\n            // Act\n            int? length = OwinRequestExtensions.GetContentLength(request);\n\n            // Assert\n            Assert.False(length.HasValue);\n        }\n\n        [Fact]\n        public void GetContentLength_IfContentLengthHeaderIsSingleNullValue_ReturnsNull()\n        {\n            // Arrange\n            IHeaderDictionary headers = CreateStubHeaders(\"Content-Length\", new string[] { null });\n            IOwinRequest request = CreateStubRequest(headers);\n\n            // Act\n            int? length = OwinRequestExtensions.GetContentLength(request);\n\n            // Assert\n            Assert.False(length.HasValue);\n        }\n\n        [Fact]\n        public void GetContentLength_IfContentLengthHeaderIsSingleNonIntegerValue_ReturnsNull()\n        {\n            // Arrange\n            IHeaderDictionary headers = CreateStubHeaders(\"Content-Length\", new string[] { \"abc\" });\n            IOwinRequest request = CreateStubRequest(headers);\n\n            // Act\n            int? length = OwinRequestExtensions.GetContentLength(request);\n\n            // Assert\n            Assert.False(length.HasValue);\n        }\n\n        [Fact]\n        public void GetContentLength_IfContentLengthHeaderIsNegative_ReturnsNull()\n        {\n            // Arrange\n            IHeaderDictionary headers = CreateStubHeaders(\"Content-Length\", new string[] { \"-1\" });\n            IOwinRequest request = CreateStubRequest(headers);\n\n            // Act\n            int? length = OwinRequestExtensions.GetContentLength(request);\n\n            // Assert\n            Assert.False(length.HasValue);\n        }\n\n        [Fact]\n        public void GetContentLength_IfValid_ReturnsValue()\n        {\n            int expected = 123;\n            IHeaderDictionary headers = CreateStubHeaders(\"Content-Length\", new string[] { expected.ToString() });\n            IOwinRequest request = CreateStubRequest(headers);\n\n            // Act\n            int? length = request.GetContentLength();\n\n            // Assert\n            Assert.True(length.HasValue);\n            Assert.Equal(expected, length.Value);\n        }\n\n        private static IDictionary<string, object> CreateStubEnvironment(object disableBufferingAction)\n        {\n            return CreateStubEnvironment(disableBufferingAction, hasDisableBufferingAction: true);\n        }\n\n        private static IDictionary<string, object> CreateStubEnvironment(object disableBufferingAction, bool hasDisableBufferingAction)\n        {\n            Mock<IDictionary<string, object>> mock = new Mock<IDictionary<string, object>>(MockBehavior.Strict);\n            mock.Setup(d => d.TryGetValue(\"server.DisableRequestBuffering\", out disableBufferingAction)).Returns(hasDisableBufferingAction);\n            return mock.Object;\n        }\n\n        private static IHeaderDictionary CreateStubHeaders(string key, string[] value)\n        {\n            Mock<IHeaderDictionary> mock = new Mock<IHeaderDictionary>(MockBehavior.Strict);\n            mock.Setup(h => h.TryGetValue(key, out value)).Returns(true);\n            return mock.Object;\n        }\n\n        private static IHeaderDictionary CreateStubHeaders()\n        {\n            Mock<IHeaderDictionary> mock = new Mock<IHeaderDictionary>(MockBehavior.Strict);\n            string[] value = null;\n            mock.Setup(h => h.TryGetValue(It.IsAny<string>(), out value)).Returns(false);\n            return mock.Object;\n        }\n\n        private static IOwinRequest CreateStubRequest(IHeaderDictionary headers)\n        {\n            Mock<IOwinRequest> mock = new Mock<IOwinRequest>(MockBehavior.Strict);\n            mock.SetupGet(r => r.Headers).Returns(headers);\n            return mock.Object;\n        }\n\n        private static IOwinRequest CreateStubRequest(IDictionary<string, object> environment)\n        {\n            Mock<IOwinRequest> mock = new Mock<IOwinRequest>(MockBehavior.Strict);\n            mock.SetupGet(r => r.Environment).Returns(environment);\n            return mock.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Owin.Test/OwinResponseExtensionsTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Microsoft.Owin;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Owin\n{\n    public class OwinResponseExtensionsTests\n    {\n        [Fact]\n        public void DisableBuffering_IfActionIsAvailable_CallsAction()\n        {\n            // Arrange\n            bool bufferingDisabled = false;\n            Action disableBufferingAction = () => bufferingDisabled = true;\n            IDictionary<string, object> environment = CreateStubEnvironment(disableBufferingAction);\n            IOwinResponse response = CreateStubResponse(environment);\n\n            // Act\n            OwinResponseExtensions.DisableBuffering(response);\n\n            // Assert\n            Assert.True(bufferingDisabled);\n        }\n\n        [Fact]\n        public void DisableBuffering_IfResponseIsNull_Throws()\n        {\n            // Arrange\n            IOwinResponse response = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => OwinResponseExtensions.DisableBuffering(response), \"response\");\n        }\n\n        [Fact]\n        public void DisableBuffering_IfEnvironmentIsNull_DoesNotThrow()\n        {\n            // Arrange\n            IDictionary<string, object> environment = null;\n            IOwinResponse response = CreateStubResponse(environment);\n\n            // Act & Assert\n            Assert.DoesNotThrow(() => response.DisableBuffering());\n        }\n\n        [Fact]\n        public void DisableBuffering_IfServerDisableResponseBufferingIsAbsent_DoesNotThrow()\n        {\n            // Arrange\n            Mock<IDictionary<string, object>> environmentMock = new Mock<IDictionary<string,object>>(MockBehavior.Strict);\n            IDictionary<string, object> environment = CreateStubEnvironment(null, hasDisableBufferingAction: false);\n            IOwinResponse response = CreateStubResponse(environment);\n\n            // Act & Assert\n            Assert.DoesNotThrow(() => response.DisableBuffering());\n        }\n\n        [Fact]\n        public void DisableBuffering_IfServerDisableResponseBufferingIsNotAction_DoesNotThrow()\n        {\n            // Arrange\n            object nonAction = new object();\n            IDictionary<string, object> environment = CreateStubEnvironment(nonAction);\n            IOwinResponse response = CreateStubResponse(environment);\n\n            // Act & Assert\n            Assert.DoesNotThrow(() => response.DisableBuffering());\n        }\n\n        private static IDictionary<string, object> CreateStubEnvironment(object disableBufferingAction)\n        {\n            return CreateStubEnvironment(disableBufferingAction, hasDisableBufferingAction: true);\n        }\n\n        private static IDictionary<string, object> CreateStubEnvironment(object disableBufferingAction, bool hasDisableBufferingAction)\n        {\n            Mock<IDictionary<string, object>> mock = new Mock<IDictionary<string, object>>(MockBehavior.Strict);\n            mock.Setup(d => d.TryGetValue(\"server.DisableResponseBuffering\", out disableBufferingAction)).Returns(hasDisableBufferingAction);\n            return mock.Object;\n        }\n\n        private static IOwinResponse CreateStubResponse(IDictionary<string, object> environment)\n        {\n            Mock<IOwinResponse> mock = new Mock<IOwinResponse>(MockBehavior.Strict);\n            mock.SetupGet(r => r.Environment).Returns(environment);\n            return mock.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Owin.Test/PassiveAuthenticationMessageHandlerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing Microsoft.Owin;\nusing Microsoft.Owin.Security;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Owin\n{\n    public class PassiveAuthenticationMessageHandlerTest\n    {\n        [Fact]\n        public async Task SendAsync_DelegatesToInnerHandler()\n        {\n            // Arrange\n            HttpRequestMessage request = null;\n            CancellationToken cancellationToken = default(CancellationToken);\n            IOwinContext context = CreateOwinContext();\n\n            using (HttpResponseMessage expectedResponse = new HttpResponseMessage())\n            {\n                HttpMessageHandler innerHandler = new LambdaHttpMessageHandler((r, c) =>\n                {\n                    request = r;\n                    cancellationToken = c;\n                    return Task.FromResult(expectedResponse);\n                });\n                HttpMessageHandler handler = CreateProductUnderTest(innerHandler);\n                CancellationToken expectedCancellationToken = new CancellationToken(true);\n\n                using (HttpRequestMessage expectedRequest = CreateRequestWithOwinContextAndRequestContext(context))\n                {\n                    // Act\n                    HttpResponseMessage response = await handler.SendAsync(expectedRequest, expectedCancellationToken);\n\n                    // Assert\n                    Assert.Same(expectedRequest, request);\n                    Assert.Equal(expectedCancellationToken, cancellationToken);\n                    Assert.Same(expectedResponse, response);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task SendAsync_Throws_WhenRequestContextIsNull()\n        {\n            // Arrange\n            HttpMessageHandler innerHandler = CreateDummyHandler();\n            HttpMessageHandler handler = CreateProductUnderTest(innerHandler);\n\n            using (HttpRequestMessage request = new HttpRequestMessage())\n            {\n                // Act & Assert\n                await Assert.ThrowsArgumentAsync(\n                    () => handler.SendAsync(request, CancellationToken.None),\n                    \"request\",\n                    \"The request must have a request context.\");\n            }\n        }\n\n        [Fact]\n        public async Task SendAsync_Throws_WhenOwinContextIsNull()\n        {\n            // Arrange\n            HttpMessageHandler innerHandler = CreateStubHandler();\n            HttpMessageHandler handler = CreateProductUnderTest(innerHandler);\n\n            using (HttpRequestMessage request = new HttpRequestMessage())\n            {\n                request.SetRequestContext(new HttpRequestContext());\n\n                // Act & Assert\n                InvalidOperationException exception = await Assert.ThrowsAsync<InvalidOperationException>(\n                    () => handler.SendAsync(request, CancellationToken.None));\n                Assert.Equal(\"No OWIN authentication manager is associated with the request.\", exception.Message);\n            }\n        }\n\n        [Fact]\n        public async Task SendAsync_Throws_WhenAuthenticationManagerIsNull()\n        {\n            // Arrange\n            HttpMessageHandler innerHandler = CreateStubHandler();\n            HttpMessageHandler handler = CreateProductUnderTest(innerHandler);\n            IOwinContext context = CreateOwinContext(null);\n\n            using (HttpRequestMessage request = CreateRequestWithOwinContextAndRequestContext(context))\n            {\n                // Act & Assert\n                InvalidOperationException exception = await Assert.ThrowsAsync<InvalidOperationException>(\n                    () => handler.SendAsync(request, CancellationToken.None));\n                Assert.Equal(\"No OWIN authentication manager is associated with the request.\", exception.Message);\n            }\n        }\n\n        [Fact]\n        public async Task SendAsync_SetsRequestContextPrincipalToAnonymous_BeforeCallingInnerHandler()\n        {\n            // Arrange\n            var requestContextMock = new Mock<HttpRequestContext>(MockBehavior.Strict);\n            var sequence = new MockSequence();\n            var initialPrincipal = new GenericPrincipal(new GenericIdentity(\"generic user\"), new[] { \"generic role\" });\n            IPrincipal requestContextPrincipal = null;\n            requestContextMock\n                .InSequence(sequence)\n                .SetupGet(c => c.Principal)\n                .Returns(initialPrincipal);\n            requestContextMock\n                .InSequence(sequence)\n                .SetupSet(c => c.Principal = It.IsAny<IPrincipal>())\n                .Callback<IPrincipal>(value => requestContextPrincipal = value);\n\n            // SendAsync also restores the old principal.\n            requestContextMock\n                .InSequence(sequence)\n                .SetupGet(c => c.Principal)\n                .Returns(requestContextPrincipal);\n            requestContextMock\n                .InSequence(sequence)\n                .SetupSet(c => c.Principal = initialPrincipal);\n\n            IPrincipal principalBeforeInnerHandler = null;\n            HttpMessageHandler inner = new LambdaHttpMessageHandler((ignore1, ignore2) =>\n            {\n                principalBeforeInnerHandler = requestContextPrincipal;\n                return Task.FromResult<HttpResponseMessage>(null);\n            });\n            HttpMessageHandler handler = CreateProductUnderTest(inner);\n            var context = CreateOwinContext();\n\n            using (var request = new HttpRequestMessage())\n            {\n                request.SetOwinContext(context);\n                request.SetRequestContext(requestContextMock.Object);\n\n                // Act\n                await handler.SendAsync(request, CancellationToken.None);\n            }\n\n            // Assert\n            Assert.Equal(requestContextPrincipal, principalBeforeInnerHandler);\n            Assert.NotNull(principalBeforeInnerHandler);\n            var identity = principalBeforeInnerHandler.Identity;\n            Assert.NotNull(identity);\n            Assert.False(identity.IsAuthenticated);\n            Assert.Null(identity.Name);\n            Assert.Null(identity.AuthenticationType);\n        }\n\n        [Fact]\n        public async Task SendAsync_SuppressesAuthenticationChallenges_WhenNoChallengeIsSet()\n        {\n            // Arrange\n            HttpMessageHandler inner = CreateStubHandler();\n            HttpMessageHandler handler = CreateProductUnderTest(inner);\n            IOwinContext context = CreateOwinContext();\n\n            using (HttpRequestMessage request = CreateRequestWithOwinContextAndRequestContext(context))\n            {\n                // Act\n                HttpResponseMessage ignore = await handler.SendAsync(request, CancellationToken.None);\n            }\n\n            // Assert\n            IAuthenticationManager authenticationManager = context.Authentication;\n            AuthenticationResponseChallenge challenge = authenticationManager.AuthenticationResponseChallenge;\n            Assert.NotNull(challenge);\n            string[] authenticationTypes = challenge.AuthenticationTypes;\n            Assert.NotNull(authenticationTypes);\n            string authenticationType = Assert.Single(authenticationTypes);\n            Assert.Null(authenticationType);\n        }\n\n        [Fact]\n        public async Task SendAsync_SuppressesAuthenticationChallenges_WhenExistingAuthenticationTypesIsNull()\n        {\n            // Arrange\n            HttpMessageHandler inner = CreateStubHandler();\n            HttpMessageHandler handler = CreateProductUnderTest(inner);\n            IOwinContext context = CreateOwinContext();\n            IAuthenticationManager authenticationManager = context.Authentication;\n            IDictionary<string, string> expectedExtra = new Dictionary<string, string>();\n            AuthenticationProperties extraWrapper = new AuthenticationProperties(expectedExtra);\n            context.Authentication.AuthenticationResponseChallenge = new AuthenticationResponseChallenge(null,\n                extraWrapper);\n\n            using (HttpRequestMessage request = CreateRequestWithOwinContextAndRequestContext(context))\n            {\n                // Act\n                HttpResponseMessage ignore = await handler.SendAsync(request, CancellationToken.None);\n            }\n\n            // Assert\n            AuthenticationResponseChallenge challenge = authenticationManager.AuthenticationResponseChallenge;\n            Assert.NotNull(challenge);\n            string[] authenticationTypes = challenge.AuthenticationTypes;\n            Assert.NotNull(authenticationTypes);\n            string authenticationType = Assert.Single(authenticationTypes);\n            Assert.Null(authenticationType);\n            AuthenticationProperties actualExtraWrapper = challenge.Properties;\n            Assert.NotNull(actualExtraWrapper);\n            Assert.Same(expectedExtra, actualExtraWrapper.Dictionary);\n        }\n\n        [Fact]\n        public async Task SendAsync_SuppressesAuthenticationChallenges_WhenExistingAuthenticationTypesIsEmpty()\n        {\n            // Arrange\n            HttpMessageHandler inner = CreateStubHandler();\n            HttpMessageHandler handler = CreateProductUnderTest(inner);\n            IOwinContext context = CreateOwinContext();\n            IAuthenticationManager authenticationManager = context.Authentication;\n            AuthenticationProperties extraWrapper = new AuthenticationProperties();\n            IDictionary<string, string> expectedExtra = extraWrapper.Dictionary;\n            authenticationManager.AuthenticationResponseChallenge = new AuthenticationResponseChallenge(new string[0],\n                extraWrapper);\n\n            using (HttpRequestMessage request = CreateRequestWithOwinContextAndRequestContext(context))\n            {\n                // Act\n                HttpResponseMessage ignore = await handler.SendAsync(request, CancellationToken.None);\n            }\n\n            // Assert\n            AuthenticationResponseChallenge challenge = authenticationManager.AuthenticationResponseChallenge;\n            Assert.NotNull(challenge);\n            string[] authenticationTypes = challenge.AuthenticationTypes;\n            Assert.NotNull(authenticationTypes);\n            string authenticationType = Assert.Single(authenticationTypes);\n            Assert.Null(authenticationType);\n            AuthenticationProperties actualExtraWrapper = challenge.Properties;\n            Assert.NotNull(actualExtraWrapper);\n            Assert.Same(expectedExtra, actualExtraWrapper.Dictionary);\n        }\n\n        [Fact]\n        public async Task SendAsync_LeavesAuthenticationChallenges_WhenExistingAuthenticationTypesIsNonEmpty()\n        {\n            // Arrange\n            HttpMessageHandler inner = CreateStubHandler();\n            HttpMessageHandler handler = CreateProductUnderTest(inner);\n            IOwinContext context = CreateOwinContext();\n            IAuthenticationManager authenticationManager = context.Authentication;\n            AuthenticationProperties extraWrapper = new AuthenticationProperties();\n            string[] expectedAuthenticationTypes = new string[] { \"Existing\" };\n            IDictionary<string, string> expectedExtra = extraWrapper.Dictionary;\n            authenticationManager.AuthenticationResponseChallenge = new AuthenticationResponseChallenge(\n                expectedAuthenticationTypes, extraWrapper);\n\n            using (HttpRequestMessage request = CreateRequestWithOwinContextAndRequestContext(context))\n            {\n                // Act\n                HttpResponseMessage ignore = await handler.SendAsync(request, CancellationToken.None);\n            }\n\n            // Assert\n            AuthenticationResponseChallenge challenge = authenticationManager.AuthenticationResponseChallenge;\n            Assert.NotNull(challenge);\n            Assert.Same(expectedAuthenticationTypes, challenge.AuthenticationTypes);\n            AuthenticationProperties actualExtraWrapper = challenge.Properties;\n            Assert.NotNull(actualExtraWrapper);\n            Assert.Same(expectedExtra, actualExtraWrapper.Dictionary);\n        }\n\n        private static HttpMessageHandler CreateDummyHandler()\n        {\n            return new DummyHttpMessageHandler();\n        }\n\n        private static IOwinContext CreateOwinContext()\n        {\n            return new OwinContext();\n        }\n\n        private static IOwinContext CreateOwinContext(IAuthenticationManager authenticationManager)\n        {\n            Mock<IOwinContext> mock = new Mock<IOwinContext>(MockBehavior.Strict);\n            mock.SetupGet(m => m.Authentication).Returns(authenticationManager);\n            return mock.Object;\n        }\n\n        private static PassiveAuthenticationMessageHandler CreateProductUnderTest(HttpMessageHandler innerHandler)\n        {\n            PassiveAuthenticationMessageHandler handler = new PassiveAuthenticationMessageHandler();\n            handler.InnerHandler = innerHandler;\n            return handler;\n        }\n\n        private static HttpRequestMessage CreateRequestWithOwinContextAndRequestContext(IOwinContext context)\n        {\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.SetOwinContext(context);\n            request.SetRequestContext(new HttpRequestContext());\n            return request;\n        }\n\n        private static HttpMessageHandler CreateStubHandler()\n        {\n            return new LambdaHttpMessageHandler((ignore1, ignore2) =>\n            {\n                return Task.FromResult<HttpResponseMessage>(null);\n            });\n        }\n\n        private class DummyHttpMessageHandler : HttpMessageHandler\n        {\n            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,\n                CancellationToken cancellationToken)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class LambdaHttpMessageHandler : HttpMessageHandler\n        {\n            private readonly Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> _sendAsync;\n\n            public LambdaHttpMessageHandler(Func<HttpRequestMessage, CancellationToken,\n                Task<HttpResponseMessage>> sendAsync)\n            {\n                if (sendAsync == null)\n                {\n                    throw new ArgumentNullException(\"sendAsync\");\n                }\n\n                _sendAsync = sendAsync;\n            }\n\n            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,\n                CancellationToken cancellationToken)\n            {\n                return _sendAsync.Invoke(request, cancellationToken);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Owin.Test/System.Web.Http.Owin.Test.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props\" Condition=\"Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" />\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" />\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{C19267DD-3984-430C-AE18-4034F85DE4E5}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>System.Web.Http.Owin</RootNamespace>\n    <AssemblyName>System.Web.Http.Owin.Test</AssemblyName>\n    <OutputPath>..\\..\\bin\\$(Configuration)\\Test\\</OutputPath>\n    <NuGetPackageImportStamp>\n    </NuGetPackageImportStamp>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Castle.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Castle.Core.5.1.1\\lib\\net462\\Castle.Core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Microsoft.Owin\">\n      <HintPath>..\\..\\packages\\Microsoft.Owin.4.2.2\\lib\\net45\\Microsoft.Owin.dll</HintPath>\n    </Reference>\n    <Reference Include=\"Microsoft.Owin.Host.HttpListener, Version=4.2.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\..\\packages\\Microsoft.Owin.Host.HttpListener.4.2.2\\lib\\net45\\Microsoft.Owin.Host.HttpListener.dll</HintPath>\n    </Reference>\n    <Reference Include=\"Microsoft.Owin.Hosting, Version=4.2.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL\">\n      <SpecificVersion>False</SpecificVersion>\n      <HintPath>..\\..\\packages\\Microsoft.Owin.Hosting.4.2.2\\lib\\net45\\Microsoft.Owin.Hosting.dll</HintPath>\n    </Reference>\n    <Reference Include=\"Moq, Version=4.18.0.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Moq.4.18.4\\lib\\net462\\Moq.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Newtonsoft.Json.13.0.1\\lib\\net45\\Newtonsoft.Json.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Owin\">\n      <HintPath>..\\..\\packages\\Owin.1.0\\lib\\net40\\Owin.dll</HintPath>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Net.Http\" />\n    <Reference Include=\"System.Xml\" />\n    <Reference Include=\"xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.abstractions.2.0.3\\lib\\net35\\xunit.abstractions.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.assert, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.assert.2.4.2\\lib\\netstandard1.1\\xunit.assert.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.core, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.core.2.4.2\\lib\\net452\\xunit.core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.execution.desktop, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.execution.2.4.2\\lib\\net452\\xunit.execution.desktop.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"ExceptionHandling\\DefaultExceptionHandlerTests.cs\" />\n    <Compile Include=\"ExceptionHandling\\EmptyExceptionLoggerTests.cs\" />\n    <Compile Include=\"HttpMessageHandlerOptionsTests.cs\" />\n    <Compile Include=\"NonOwnedStreamTests.cs\" />\n    <Compile Include=\"OwinExceptionCatchBlocksTests.cs\" />\n    <Compile Include=\"OwinHttpRequestContextTests.cs\" />\n    <Compile Include=\"HostAuthenticationAttributeTest.cs\" />\n    <Compile Include=\"HostAuthenticationFilterTest.cs\" />\n    <Compile Include=\"OwinHttpConfigurationExtensionsTest.cs\" />\n    <Compile Include=\"HttpMessageHandlerExtensions.cs\" />\n    <Compile Include=\"OwinHttpRequestMessageExtensionsTest.cs\" />\n    <Compile Include=\"OwinRequestExtensionsTests.cs\" />\n    <Compile Include=\"OwinResponseExtensionsTests.cs\" />\n    <Compile Include=\"PassiveAuthenticationMessageHandlerTest.cs\" />\n    <Compile Include=\"WebApiAppBuilderExtensionsTest.cs\" />\n    <Compile Include=\"OwinBufferPolicySelectorTest.cs\" />\n    <Compile Include=\"HttpMessageHandlerAdapterTest.cs\" />\n    <Compile Include=\"OwinHostIntegrationTest.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\..\\src\\System.Net.Http.Formatting\\System.Net.Http.Formatting.csproj\">\n      <Project>{668e9021-ce84-49d9-98fb-df125a9fcdb0}</Project>\n      <Name>System.Net.Http.Formatting</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Http.Owin\\System.Web.Http.Owin.csproj\">\n      <Project>{66dd7cd7-c68f-4d0e-9f3d-3b58c49d1467}</Project>\n      <Name>System.Web.Http.Owin</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Http\\System.Web.Http.csproj\">\n      <Project>{ddc1ce0c-486e-4e35-bb3b-eab61f8f9440}</Project>\n      <Name>System.Web.Http</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\">\n      <Project>{fccc4cb7-baf7-4a57-9f89-e5766fe536c0}</Project>\n      <Name>Microsoft.TestCommon</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Service Include=\"{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Analyzer Include=\"..\\..\\packages\\xunit.analyzers.1.1.0\\analyzers\\dotnet\\cs\\xunit.analyzers.dll\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  <Target Name=\"EnsureNuGetPackageBuildImports\" BeforeTargets=\"PrepareForBuild\">\n    <PropertyGroup>\n      <ErrorText>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}.</ErrorText>\n    </PropertyGroup>\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props'))\" />\n  </Target>\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" />\n</Project>"
  },
  {
    "path": "test/System.Web.Http.Owin.Test/WebApiAppBuilderExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Hosting;\nusing Microsoft.TestCommon;\nusing Moq;\nusing Owin;\n\nnamespace System.Web.Http.Owin\n{\n    public class WebApiAppBuilderExtensionsTest\n    {\n        [Fact]\n        public void UseWebApiWithConfiguration_IfBuilderIsNull_Throws()\n        {\n            // Arrange\n            IAppBuilder builder = null;\n\n            using (HttpConfiguration configuration = CreateConfiguration())\n            {\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() => WebApiAppBuilderExtensions.UseWebApi(builder, configuration),\n                    \"builder\");\n            }\n        }\n\n        [Fact]\n        public void UseWebApiWithConfiguration_IfConfigurationIsNull_Throws()\n        {\n            // Arrange\n            IAppBuilder builder = CreateDummyAppBuilder();\n            HttpConfiguration configuration = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => WebApiAppBuilderExtensions.UseWebApi(builder, configuration),\n                \"configuration\");\n        }\n\n        [Fact]\n        public void UseWebApiWithServer_IfBuilderIsNull_Throws()\n        {\n            // Arrange\n            IAppBuilder builder = null;\n\n            using (HttpServer httpServer = CreateServer())\n            {\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() => WebApiAppBuilderExtensions.UseWebApi(builder, httpServer), \"builder\");\n            }\n        }\n\n        [Fact]\n        public void UseWebApiWithServer_IfServerIsNull_Throws()\n        {\n            // Arrange\n            IAppBuilder builder = CreateDummyAppBuilder();\n            HttpServer httpServer = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => WebApiAppBuilderExtensions.UseWebApi(builder, httpServer), \"httpServer\");\n        }\n\n        [Fact]\n        public void UseWebApi_UsesAdapter()\n        {\n            var config = new HttpConfiguration();\n            var appBuilder = new Mock<IAppBuilder>();\n            appBuilder\n                .Setup(ab => ab.Use(\n                    typeof(HttpMessageHandlerAdapter),\n                    It.Is<HttpMessageHandlerOptions>((o) => ((HttpServer)o.MessageHandler).Configuration == config)))\n                .Returns(appBuilder.Object)\n                .Verifiable();\n\n            IAppBuilder returnedAppBuilder = appBuilder.Object.UseWebApi(config);\n\n            Assert.Equal(appBuilder.Object, returnedAppBuilder);\n            appBuilder.Verify();\n        }\n\n        [Fact]\n        public async Task UseWebApi_UsesAdapterAndConfigServices()\n        {\n            using (CancellationTokenSource tokenSource = CreateCancellationTokenSource())\n            {\n                var config = new HttpConfiguration();\n                var bufferPolicySelector = new Mock<IHostBufferPolicySelector>().Object;\n                Mock<IExceptionLogger> loggerMock = new Mock<IExceptionLogger>();\n                Mock<IExceptionHandler> handlerMock = new Mock<IExceptionHandler>();\n                config.Services.Replace(typeof(IHostBufferPolicySelector), bufferPolicySelector);\n                config.Services.Replace(typeof(IExceptionLogger), loggerMock.Object);\n                config.Services.Replace(typeof(IExceptionHandler), handlerMock.Object);\n                IExceptionLogger exceptionLogger = null;\n                IExceptionHandler exceptionHandler = null;\n                var appBuilder = new Mock<IAppBuilder>();\n                CancellationToken expectedAppDisposing = tokenSource.Token;\n                IDictionary<string, object> properties = new Dictionary<string, object>\n                {\n                    { \"host.OnAppDisposing\", expectedAppDisposing }\n                };\n                appBuilder.SetupGet(b => b.Properties).Returns(properties);\n                appBuilder\n                    .Setup(ab => ab.Use(\n                        typeof(HttpMessageHandlerAdapter),\n                        It.Is<HttpMessageHandlerOptions>((o) => ((HttpServer)o.MessageHandler).Configuration == config\n                            && o.BufferPolicySelector == bufferPolicySelector\n                            && o.AppDisposing == expectedAppDisposing)))\n                    .Callback<object, object[]>((i, args) =>\n                    {\n                        HttpMessageHandlerOptions options = (HttpMessageHandlerOptions)args[0];\n                        exceptionLogger = options.ExceptionLogger;\n                        exceptionHandler = options.ExceptionHandler;\n                    })\n                    .Returns(appBuilder.Object)\n                    .Verifiable();\n\n                IAppBuilder returnedAppBuilder = appBuilder.Object.UseWebApi(config);\n\n                Assert.Equal(appBuilder.Object, returnedAppBuilder);\n                appBuilder.Verify();\n                await AssertDelegatesToAsync(loggerMock, exceptionLogger);\n                await AssertDelegatesToAsync(handlerMock, exceptionHandler);\n            }\n        }\n\n        [Fact]\n        public void UseWebApiWithHttpServer_UsesAdapter()\n        {\n            // Arrange\n            HttpServer httpServer = new Mock<HttpServer>().Object;\n            Mock<IAppBuilder> appBuilderMock = new Mock<IAppBuilder>();\n            appBuilderMock\n                .Setup(ab => ab.Use(\n                    typeof(HttpMessageHandlerAdapter),\n                    It.Is<HttpMessageHandlerOptions>((o) => o.MessageHandler == httpServer)))\n                .Returns(appBuilderMock.Object)\n                .Verifiable();\n\n            // Act\n            IAppBuilder returnedAppBuilder = appBuilderMock.Object.UseWebApi(httpServer);\n\n            // Assert\n            Assert.Equal(appBuilderMock.Object, returnedAppBuilder);\n            appBuilderMock.Verify();\n        }\n\n        [Fact]\n        public async Task UseWebApiWithHttpServer_UsesAdapterAndConfigServices()\n        {\n            // Arrange\n            using (CancellationTokenSource tokenSource = CreateCancellationTokenSource())\n            {\n                HttpConfiguration config = new HttpConfiguration();\n                IHostBufferPolicySelector bufferPolicySelector = new Mock<IHostBufferPolicySelector>().Object;\n                Mock<IExceptionLogger> loggerMock = new Mock<IExceptionLogger>();\n                Mock<IExceptionHandler> handlerMock = new Mock<IExceptionHandler>();\n                config.Services.Replace(typeof(IHostBufferPolicySelector), bufferPolicySelector);\n                config.Services.Replace(typeof(IExceptionLogger), loggerMock.Object);\n                config.Services.Replace(typeof(IExceptionHandler), handlerMock.Object);\n                HttpServer httpServer = new Mock<HttpServer>(config).Object;\n                IExceptionLogger exceptionLogger = null;\n                IExceptionHandler exceptionHandler = null;\n                Mock<IAppBuilder> appBuilderMock = new Mock<IAppBuilder>();\n                CancellationToken expectedAppDisposing = tokenSource.Token;\n                IDictionary<string, object> properties = new Dictionary<string, object>\n                {\n                    { \"host.OnAppDisposing\", expectedAppDisposing }\n                };\n                appBuilderMock.SetupGet(b => b.Properties).Returns(properties);\n                appBuilderMock\n                    .Setup(ab => ab.Use(\n                        typeof(HttpMessageHandlerAdapter),\n                        It.Is<HttpMessageHandlerOptions>((o) => o.MessageHandler == httpServer\n                            && o.BufferPolicySelector == bufferPolicySelector\n                            && o.AppDisposing == expectedAppDisposing)))\n                    .Callback<object, object[]>((i, args) =>\n                    {\n                        HttpMessageHandlerOptions options = (HttpMessageHandlerOptions)args[0];\n                        exceptionLogger = options.ExceptionLogger;\n                        exceptionHandler = options.ExceptionHandler;\n                    })\n                    .Returns(appBuilderMock.Object)\n                    .Verifiable();\n\n                // Act\n                IAppBuilder returnedAppBuilder = appBuilderMock.Object.UseWebApi(httpServer);\n\n                // Assert\n                Assert.Equal(appBuilderMock.Object, returnedAppBuilder);\n                appBuilderMock.Verify();\n                await AssertDelegatesToAsync(loggerMock, exceptionLogger);\n                await AssertDelegatesToAsync(handlerMock, exceptionHandler);\n            }\n        }\n\n        [Fact]\n        public void GetOnAppDisposingProperty_IfPropertiesIsPresent_ReturnsSpecifiedValue()\n        {\n            // Arrange\n            using (CancellationTokenSource tokenSource = CreateCancellationTokenSource())\n            {\n                CancellationToken expectedOnAppDisposing = tokenSource.Token;\n                IDictionary<string, object> properties = CreateStubOnAppDisposingDictionary(expectedOnAppDisposing);\n                IAppBuilder builder = CreateStubAppBuilder(properties);\n\n                // Act\n                CancellationToken onAppDisposing = builder.GetOnAppDisposingProperty();\n\n                // Assert\n                Assert.Equal(expectedOnAppDisposing, onAppDisposing);\n            }\n        }\n\n        [Fact]\n        public void GetOnAppDisposingProperty_IfPropertiesIsNull_ReturnsCancellationTokenNone()\n        {\n            // Arrange\n            IDictionary<string, object> properties = null;\n            IAppBuilder builder = CreateStubAppBuilder(properties);\n\n            // Act\n            CancellationToken onAppDisposing = WebApiAppBuilderExtensions.GetOnAppDisposingProperty(builder);\n\n            // Assert\n            Assert.Equal(CancellationToken.None, onAppDisposing);\n        }\n\n        [Fact]\n        public void GetOnAppDisposingProperty_IfPropertyIsAbsent_ReturnsCancellationTokenNone()\n        {\n            // Arrange\n            IDictionary<string, object> properties = CreateStubOnAppDisposingDictionary(onAppDisposing: null, hasOnAppDisposing: false);\n            IAppBuilder builder = CreateStubAppBuilder(properties);\n\n            // Act\n            CancellationToken onAppDisposing = WebApiAppBuilderExtensions.GetOnAppDisposingProperty(builder);\n\n            // Assert\n            Assert.Equal(CancellationToken.None, onAppDisposing);\n        }\n\n        [Fact]\n        public void GetOnAppDisposingProperty_IfPropertyIsNonCancellationToken_ReturnsCancellationTokenNone()\n        {\n            // Arrange\n            object nonCancellationToken = new object();\n            IDictionary<string, object> properties = CreateStubOnAppDisposingDictionary(nonCancellationToken);\n            IAppBuilder builder = CreateStubAppBuilder(properties);\n\n            // Act\n            CancellationToken onAppDisposing = WebApiAppBuilderExtensions.GetOnAppDisposingProperty(builder);\n\n            // Assert\n            Assert.Equal(CancellationToken.None, onAppDisposing);\n        }\n\n        private static async Task AssertDelegatesToAsync(Mock<IExceptionHandler> expected, IExceptionHandler actual)\n        {\n            Assert.NotNull(actual);\n\n            ExceptionHandlerContext context = new ExceptionHandlerContext(new ExceptionContext(new Exception(), ExceptionCatchBlocks.HttpServer));\n            CancellationToken cancellationToken = CancellationToken.None;\n\n            expected\n                .Setup((l) => l.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                .Returns(CreateCanceledTask());\n\n            await Assert.ThrowsAsync<TaskCanceledException>(() => actual.HandleAsync(context, cancellationToken));\n\n            expected.Verify((l) => l.HandleAsync(context, cancellationToken), Times.Once());\n        }\n\n        private static async Task AssertDelegatesToAsync(Mock<IExceptionLogger> expected, IExceptionLogger actual)\n        {\n            Assert.NotNull(actual);\n\n            ExceptionLoggerContext context = new ExceptionLoggerContext(new ExceptionContext(new Exception(), ExceptionCatchBlocks.HttpServer));\n            CancellationToken cancellationToken = CancellationToken.None;\n\n            expected\n                .Setup((l) => l.LogAsync(It.IsAny<ExceptionLoggerContext>(), It.IsAny<CancellationToken>()))\n                .Returns(CreateCanceledTask());\n\n            await Assert.ThrowsAsync<TaskCanceledException>(() => actual.LogAsync(context, cancellationToken));\n\n            expected.Verify((l) => l.LogAsync(context, cancellationToken), Times.Once());\n        }\n\n        private static Task CreateCanceledTask()\n        {\n            TaskCompletionSource<object> source = new TaskCompletionSource<object>();\n            source.SetCanceled();\n            return source.Task;\n        }\n\n        private static CancellationTokenSource CreateCancellationTokenSource()\n        {\n            return new CancellationTokenSource();\n        }\n\n        private static HttpConfiguration CreateConfiguration()\n        {\n            return new HttpConfiguration();\n        }\n\n        private static IAppBuilder CreateDummyAppBuilder()\n        {\n            return new Mock<IAppBuilder>(MockBehavior.Strict).Object;\n        }\n\n        private static HttpServer CreateServer()\n        {\n            return new HttpServer();\n        }\n\n        private static IAppBuilder CreateStubAppBuilder(IDictionary<string, object> properties)\n        {\n            Mock<IAppBuilder> mock = new Mock<IAppBuilder>(MockBehavior.Strict);\n            mock.SetupGet(b => b.Properties).Returns(properties);\n            return mock.Object;\n        }\n\n        private static IDictionary<string, object> CreateStubOnAppDisposingDictionary(object onAppDisposing)\n        {\n            return CreateStubOnAppDisposingDictionary(onAppDisposing, hasOnAppDisposing: true);\n        }\n\n        private static IDictionary<string, object> CreateStubOnAppDisposingDictionary(object onAppDisposing, bool hasOnAppDisposing)\n        {\n            Mock<IDictionary<string, object>> mock = new Mock<IDictionary<string, object>>();\n            mock.Setup(d => d.TryGetValue(\"host.OnAppDisposing\", out onAppDisposing)).Returns(hasOnAppDisposing);\n            return mock.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Owin.Test/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Castle.Core\" version=\"5.1.1\" targetFramework=\"net462\" />\n  <package id=\"Microsoft.Owin\" version=\"4.2.2\" targetFramework=\"net462\" />\n  <package id=\"Microsoft.Owin.Host.HttpListener\" version=\"4.2.2\" targetFramework=\"net462\" />\n  <package id=\"Microsoft.Owin.Hosting\" version=\"4.2.2\" targetFramework=\"net462\" />\n  <package id=\"Moq\" version=\"4.18.4\" targetFramework=\"net462\" />\n  <package id=\"Newtonsoft.Json\" version=\"13.0.1\" targetFramework=\"net462\" />\n  <package id=\"Owin\" version=\"1.0\" targetFramework=\"net462\" />\n  <package id=\"xunit\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.abstractions\" version=\"2.0.3\" targetFramework=\"net462\" />\n  <package id=\"xunit.analyzers\" version=\"1.1.0\" targetFramework=\"net462\" />\n  <package id=\"xunit.assert\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.execution\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.runner.visualstudio\" version=\"2.4.5\" targetFramework=\"net462\" developmentDependency=\"true\" />\n</packages>"
  },
  {
    "path": "test/System.Web.Http.SelfHost.Test/Authentication/BasicOverHttpTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing System.ServiceModel;\nusing System.Threading.Tasks;\nusing System.Web.Http.SelfHost;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http\n{\n    [Xunit.Collection(\"PortReserver Collection\")] // Avoid conflicts between different PortReserver consumers.\n    public class BasicOverHttpTest\n    {\n        [Fact]\n        public Task AuthenticateWithUsernameTokenSucceed()\n        {\n            return RunBasicAuthTest(\"Sample\", \"\", new NetworkCredential(\"username\", \"password\"),\n                (response) => Assert.Equal(HttpStatusCode.OK, response.StatusCode)\n                );\n        }\n\n        [Fact]\n        public Task AuthenticateWithWrongPasswordFail()\n        {\n            return RunBasicAuthTest(\"Sample\", \"\", new NetworkCredential(\"username\", \"wrong password\"),\n                (response) => Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode)\n                );\n        }\n\n        [Fact]\n        public Task AuthenticateWithNoCredentialFail()\n        {\n            return RunBasicAuthTest(\"Sample\", \"\", null,\n                (response) => Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode)\n                );\n        }\n\n        private static async Task RunBasicAuthTest(string controllerName, string routeSuffix, NetworkCredential credential, Action<HttpResponseMessage> assert)\n        {\n            using (var port = new PortReserver())\n            {\n                // Arrange\n                HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(port.BaseUri);\n                config.HostNameComparisonMode = HostNameComparisonMode.Exact;\n                config.Routes.MapHttpRoute(\"Default\", \"{controller}\" + routeSuffix, new { controller = controllerName });\n                config.UserNamePasswordValidator = new CustomUsernamePasswordValidator();\n                config.MessageHandlers.Add(new CustomMessageHandler());\n                HttpSelfHostServer server = new HttpSelfHostServer(config);\n\n                await server.OpenAsync();\n\n                // Create a GET request with correct username and password\n                HttpClientHandler handler = new HttpClientHandler();\n                handler.Credentials = credential;\n                HttpClient client = new HttpClient(handler);\n\n                HttpResponseMessage response = null;\n                try\n                {\n                    // Act\n                    response = await client.GetAsync(port.BaseUri);\n\n                    // Assert\n                    assert(response);\n                }\n                finally\n                {\n                    if (response != null)\n                    {\n                        response.Dispose();\n                    }\n                    client.Dispose();\n                }\n\n                await server.CloseAsync();\n            }\n        }\n\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.SelfHost.Test/Authentication/CustomMessageHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Security.Principal;\nusing System.ServiceModel;\nusing System.ServiceModel.Security;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http\n{\n    public class CustomMessageHandler : DelegatingHandler\n    {\n        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n        {\n            IPrincipal originalPrincipal = Thread.CurrentPrincipal;\n\n            // here you can see the requestor's identity via the request message\n            // convert the Generic Identity to some IPrincipal object, and set it in the request's property\n            // later the authorization filter will use the role information to authorize request.\n            SecurityMessageProperty property = request.GetSecurityMessageProperty();\n            if (property != null)\n            {\n                ServiceSecurityContext context = property.ServiceSecurityContext;\n\n                if (context.PrimaryIdentity.Name == \"username\")\n                {\n                    Thread.CurrentPrincipal = new GenericPrincipal(context.PrimaryIdentity, new string[] { \"Administrators\" });\n                }\n            }\n\n            try\n            {\n                return await base.SendAsync(request, cancellationToken);\n            }\n            finally\n            {\n                Thread.CurrentPrincipal = originalPrincipal;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.SelfHost.Test/Authentication/CustomUsernamePasswordValidator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IdentityModel.Selectors;\n\nnamespace System.Web.Http\n{\n    public class CustomUsernamePasswordValidator : UserNamePasswordValidator\n    {\n        public override void Validate(string userName, string password)\n        {\n            if (userName == \"username\" && password == \"password\")\n            {\n                return;\n            }\n            else\n            {\n                throw new InvalidOperationException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.SelfHost.Test/Authentication/RequireAdminAttribute.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Filters;\n\nnamespace System.Web.Http\n{\n    public class RequireAdminAttribute : AuthorizationFilterAttribute\n    {\n        public override void OnAuthorization(HttpActionContext context)\n        {\n            // do authorization based on the principle.\n            IPrincipal principal = Thread.CurrentPrincipal;\n            if (principal == null || !principal.IsInRole(\"Administrators\"))\n            {\n                context.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);\n            }\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.SelfHost.Test/Authentication/SampleController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http\n{\n    /// <summary>\n    /// Sample ApiControler\n    /// </summary>\n    public class SampleController : ApiController\n    {\n        [RequireAdmin]\n        public string Get()\n        {\n            return \"hello\";\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.SelfHost.Test/Channels/HttpBindingSecurityModeHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.SelfHost.Channels;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Formatting\n{\n    public class HttpBindingSecurityModeHelperTest : EnumHelperTestBase<HttpBindingSecurityMode>\n    {\n        public HttpBindingSecurityModeHelperTest()\n            : base(HttpBindingSecurityModeHelper.IsDefined, HttpBindingSecurityModeHelper.Validate, (HttpBindingSecurityMode)999)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.SelfHost.Test/DeeplyNestedTypeTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Headers;\nusing System.ServiceModel;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Xml.Linq;\nusing Microsoft.TestCommon;\nusing Newtonsoft.Json.Linq;\n\nnamespace System.Web.Http.SelfHost\n{\n    public class DeepNestedTypeTests\n    {\n        private HttpSelfHostServer server = null;\n        private string baseAddress = null;\n        private HttpClient httpClient = null;\n\n        public DeepNestedTypeTests()\n        {\n            this.SetupHost();\n        }\n\n        private void SetupHost()\n        {\n            baseAddress = String.Format(\"http://localhost/\");\n\n            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(baseAddress);\n            config.HostNameComparisonMode = HostNameComparisonMode.Exact;\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{action}\", new { controller = \"DeepNestedType\" });\n\n            server = new HttpSelfHostServer(config);\n\n            httpClient = new HttpClient(server);\n        }\n\n        [Fact]\n        public async Task PostDeeplyNestedTypeInXmlThrows()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.RequestUri = new Uri(Path.Combine(baseAddress, \"DeepNestedType/PostNest\"));\n            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(\"application/xml\"));\n            request.Method = HttpMethod.Post;\n            request.Content = new StringContent(GetNestedObjectInXml(8000), UTF8Encoding.UTF8, \"application/xml\");\n\n            // Action\n            HttpResponseMessage response = await httpClient.SendAsync(request);\n\n            // Assert\n            Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n        }\n\n        [Fact]\n        public async Task PostNotTooDeeplyNestedTypeInXmlWorks()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.RequestUri = new Uri(Path.Combine(baseAddress, \"DeepNestedType/PostNest\"));\n            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(\"application/xml\"));\n            request.Method = HttpMethod.Post;\n            request.Content = new StringContent(GetNestedObjectInXml(20), UTF8Encoding.UTF8, \"application/xml\");\n\n            // Action\n            HttpResponseMessage response = await httpClient.SendAsync(request);\n\n            // Assert\n            string expectedResponseValue = @\"<string xmlns=\"\"http://schemas.microsoft.com/2003/10/Serialization/\"\">success from PostNest</string>\";\n            Assert.NotNull(response.Content);\n            Assert.NotNull(response.Content.Headers.ContentType);\n            Assert.Equal(\"application/xml\", response.Content.Headers.ContentType.MediaType);\n            Assert.Equal(expectedResponseValue, await response.Content.ReadAsStringAsync());\n        }\n\n        [Fact]\n        public async Task PostDeeplyNestedTypeInFormUrlEncodedThrows()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.RequestUri = new Uri(Path.Combine(baseAddress, \"DeepNestedType/PostJToken\"));\n            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(\"application/xml\"));\n            request.Method = HttpMethod.Post;\n            request.Content = new StringContent(GetNestedObjectInFormUrl(5000), UTF8Encoding.UTF8, \"application/x-www-form-urlencoded\");\n\n            // Action\n            HttpResponseMessage response = await httpClient.SendAsync(request);\n\n            // Assert\n            Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n        }\n\n        [Fact]\n        public async Task PostNotTooDeeplyNestedTypeInFormUrlEncodedWorks()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.RequestUri = new Uri(Path.Combine(baseAddress, \"DeepNestedType/PostJToken\"));\n            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(\"application/xml\"));\n            request.Method = HttpMethod.Post;\n            request.Content = new StringContent(GetNestedObjectInFormUrl(20), UTF8Encoding.UTF8, \"application/x-www-form-urlencoded\");\n\n            // Action\n            HttpResponseMessage response = await httpClient.SendAsync(request);\n\n            // Assert\n            string expectedResponseValue = @\"<string xmlns=\"\"http://schemas.microsoft.com/2003/10/Serialization/\"\">success from PostJToken</string>\";\n            Assert.NotNull(response.Content);\n            Assert.NotNull(response.Content.Headers.ContentType);\n            Assert.Equal(\"application/xml\", response.Content.Headers.ContentType.MediaType);\n            Assert.Equal(expectedResponseValue, await response.Content.ReadAsStringAsync());\n        }\n\n        [Fact]\n        public async Task PostNestedListInFormUrlEncodedWorks()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.RequestUri = new Uri(Path.Combine(baseAddress, \"DeepNestedType/PostNestedList\"));\n            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(\"application/xml\"));\n            request.Method = HttpMethod.Post;\n            request.Content = new StringContent(GetBigListInFormUrl(70000), Encoding.UTF8, \"application/x-www-form-urlencoded\");\n\n            // Act\n            HttpResponseMessage response = await httpClient.SendAsync(request);\n\n            // Assert\n            string expectedResponseValue = @\"<string xmlns=\"\"http://schemas.microsoft.com/2003/10/Serialization/\"\">success from PostNestedList</string>\";\n            Assert.NotNull(response.Content);\n            Assert.NotNull(response.Content.Headers.ContentType);\n            Assert.Equal(\"application/xml\", response.Content.Headers.ContentType.MediaType);\n            Assert.Equal(expectedResponseValue, await response.Content.ReadAsStringAsync());\n        }\n\n        [Fact]\n        public async Task PostBigArrayWorks()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.RequestUri = new Uri(Path.Combine(baseAddress, \"DeepNestedType/PostXElement\"));\n            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(\"application/xml\"));\n            request.Method = HttpMethod.Post;\n\n            request.Content = new StringContent(GetBigArray(5000), Encoding.UTF8, \"application/xml\");\n\n            // Act\n            HttpResponseMessage response = await httpClient.SendAsync(request);\n\n            // Assert\n            string expectedResponseValue = @\"<string xmlns=\"\"http://schemas.microsoft.com/2003/10/Serialization/\"\">success from PostXElement</string>\";\n            Assert.NotNull(response.Content);\n            Assert.NotNull(response.Content.Headers.ContentType);\n            Assert.Equal(\"application/xml\", response.Content.Headers.ContentType.MediaType);\n            Assert.Equal(expectedResponseValue, await response.Content.ReadAsStringAsync());\n        }\n\n        /*\n        <?xml version=\"1.0\"?>\n        <ArrayOfString xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n        <string />\n        <string />\n        <string />\n        </ArrayOfString>\n        */\n            private string GetBigArray(int arraySize)\n            {\n                StringBuilder sb = new StringBuilder();\n                for (int i = 0; i < arraySize; i++)\n                {\n                    sb.Append(\"<string/>\");\n                }\n\n                sb.Insert(0, \"<ArrayOfString>\");\n                sb.Append(\"</ArrayOfString>\");\n                sb.Insert(0, \"<?xml version=\\\"1.0\\\"?>\");\n\n                return sb.ToString();\n            }\n\n        private string GetNestedObjectInXml(int depth)\n        {\n            StringBuilder sb = new StringBuilder();\n            for (int i = 0; i < depth; i++)\n            {\n                sb.Insert(0, \"<A>\");\n                sb.Append(\"</A>\");\n            }\n\n            sb.Insert(0, \"<Nest xmlns=\\\"http://schemas.datacontract.org/2004/07/System.Web.Http.SelfHost\\\">\");\n            sb.Append(\"</Nest>\");\n            sb.Insert(0, \"<?xml version=\\\"1.0\\\"?>\");\n\n            return sb.ToString();\n        }\n\n        private string GetNestedObjectInFormUrl(int depth)\n        {\n            StringBuilder sb = new StringBuilder(\"a\");\n            for (int i = 0; i < depth; i++)\n            {\n                sb.Append(\"[a]\");\n            }\n            sb.Append(\"=1\");\n            return sb.ToString();\n        }\n\n        private string GetBigListInFormUrl(int depth)\n        {\n            StringBuilder sb = new StringBuilder();\n            sb.Append(\"a\");\n            for (int i = 0; i < depth; i++)\n            {\n                sb.Append(\"[N]\");\n            }\n            sb.Append(\"[D]=1\");\n            return sb.ToString();\n        }\n    }\n\n    public class DeepNestedTypeController : ApiController\n    {\n        public string PostNest(Nest a)\n        {\n            if (!ModelState.IsValid)\n            {\n                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));\n            }\n            return \"success from PostNest\";\n        }\n\n        public string PostJToken(JToken token)\n        {\n            if (!ModelState.IsValid)\n            {\n                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));\n            }\n            return \"success from PostJToken\";\n        }\n\n        public string PostNestedList(MyList a)\n        {\n            if (!ModelState.IsValid)\n            {\n                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));\n            }\n            return \"success from PostNestedList\";\n        }\n\n        public string PostXElement(XElement input)\n        {\n            if (!ModelState.IsValid)\n            {\n                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));\n            }\n\n            return \"success from PostXElement\";\n        }\n    }\n\n    public class Nest\n    {\n        public Nest A { get; set; }\n    }\n\n    public class MyList\n    {\n        public int D { get; set; }\n        public MyList N { get; set; }\n    }\n\n}\n"
  },
  {
    "path": "test/System.Web.Http.SelfHost.Test/HttpSelfHostConfigurationTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IdentityModel.Selectors;\nusing System.ServiceModel;\nusing System.ServiceModel.Channels;\nusing System.ServiceModel.Description;\nusing System.Threading.Tasks;\nusing System.Web.Http.SelfHost.Channels;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.SelfHost\n{\n    public class HttpSelfHostConfigurationTest\n    {\n        public static TheoryDataSet<string, HttpBindingSecurityMode, HttpClientCredentialType> BasicClientCredentialTestData\n        {\n            get\n            {\n                return new TheoryDataSet<string, HttpBindingSecurityMode, HttpClientCredentialType>()\n                {\n                    {\"http://localhost\", HttpBindingSecurityMode.TransportCredentialOnly, HttpClientCredentialType.Basic},\n                    {\"https://localhost\", HttpBindingSecurityMode.Transport, HttpClientCredentialType.Basic},\n                };\n            }\n        }\n\n        public static TheoryDataSet<string, HttpBindingSecurityMode, HttpClientCredentialType> CertificateClientCredentialTestData\n        {\n            get\n            {\n                return new TheoryDataSet<string, HttpBindingSecurityMode, HttpClientCredentialType>()\n                {\n                    {\"http://localhost\", HttpBindingSecurityMode.TransportCredentialOnly, HttpClientCredentialType.Certificate},\n                    {\"https://localhost\", HttpBindingSecurityMode.Transport, HttpClientCredentialType.Certificate},\n                };\n            }\n        }\n\n        public static TheoryDataSet<string, HttpBindingSecurityMode, HttpClientCredentialType> NonCertificateClientCredentialTestData\n        {\n            get\n            {\n                return new TheoryDataSet<string, HttpBindingSecurityMode, HttpClientCredentialType>()\n                {\n                    {\"http://localhost\", HttpBindingSecurityMode.None, HttpClientCredentialType.None},\n                    {\"https://localhost\", HttpBindingSecurityMode.Transport, HttpClientCredentialType.None},\n                    {\"http://localhost\", HttpBindingSecurityMode.TransportCredentialOnly, HttpClientCredentialType.Basic},\n                    {\"https://localhost\", HttpBindingSecurityMode.Transport, HttpClientCredentialType.Basic},\n                    {\"http://localhost\", HttpBindingSecurityMode.TransportCredentialOnly, HttpClientCredentialType.Digest},\n                    {\"https://localhost\", HttpBindingSecurityMode.Transport, HttpClientCredentialType.Digest},\n                    {\"http://localhost\", HttpBindingSecurityMode.TransportCredentialOnly, HttpClientCredentialType.Ntlm},\n                    {\"https://localhost\", HttpBindingSecurityMode.Transport, HttpClientCredentialType.Ntlm},\n                    {\"http://localhost\", HttpBindingSecurityMode.TransportCredentialOnly, HttpClientCredentialType.Windows},\n                    {\"https://localhost\", HttpBindingSecurityMode.Transport, HttpClientCredentialType.Windows},\n                };\n            }\n        }\n\n        public static TheoryDataSet<string, HttpBindingSecurityMode, HttpClientCredentialType> NonBasicClientCredentialTestData\n        {\n            get\n            {\n                return new TheoryDataSet<string, HttpBindingSecurityMode, HttpClientCredentialType>()\n                {\n                    {\"http://localhost\", HttpBindingSecurityMode.None, HttpClientCredentialType.None},\n                    {\"https://localhost\", HttpBindingSecurityMode.Transport, HttpClientCredentialType.None},\n                    {\"http://localhost\", HttpBindingSecurityMode.TransportCredentialOnly, HttpClientCredentialType.Certificate},\n                    {\"https://localhost\", HttpBindingSecurityMode.Transport, HttpClientCredentialType.Certificate},\n                    {\"http://localhost\", HttpBindingSecurityMode.TransportCredentialOnly, HttpClientCredentialType.Digest},\n                    {\"https://localhost\", HttpBindingSecurityMode.Transport, HttpClientCredentialType.Digest},\n                    {\"http://localhost\", HttpBindingSecurityMode.TransportCredentialOnly, HttpClientCredentialType.Ntlm},\n                    {\"https://localhost\", HttpBindingSecurityMode.Transport, HttpClientCredentialType.Ntlm},\n                    {\"http://localhost\", HttpBindingSecurityMode.TransportCredentialOnly, HttpClientCredentialType.Windows},\n                    {\"https://localhost\", HttpBindingSecurityMode.Transport, HttpClientCredentialType.Windows},\n                };\n            }\n        }\n\n        [Fact]\n        public void HttpSelfHostConfiguration_NullBaseAddressString_Throws()\n        {\n            Assert.ThrowsArgumentNull(() => new HttpSelfHostConfiguration((string)null), \"baseAddress\");\n        }\n\n        [Fact]\n        public void HttpSelfHostConfiguration_RelativeBaseAddressString_Throws()\n        {\n            Assert.ThrowsArgument(() => new HttpSelfHostConfiguration(\"relative\"), \"baseAddress\");\n        }\n\n        [Fact]\n        public void HttpSelfHostConfiguration_QueryBaseAddressString_Throws()\n        {\n            Assert.ThrowsArgument(() => new HttpSelfHostConfiguration(\"http://localhost?somequery\"), \"baseAddress\");\n        }\n\n        [Fact]\n        public void HttpSelfHostConfiguration_FragmentBaseAddressString_Throws()\n        {\n            Assert.ThrowsArgument(() => new HttpSelfHostConfiguration(\"http://localhost#somefragment\"), \"baseAddress\");\n        }\n\n        [Fact]\n        public void HttpSelfHostConfiguration_InvalidSchemeBaseAddressString_Throws()\n        {\n            Assert.ThrowsArgument(() => new HttpSelfHostConfiguration(\"ftp://localhost\"), \"baseAddress\");\n        }\n\n        [Fact]\n        public void HttpSelfHostConfiguration_NullBaseAddress_Throws()\n        {\n            Assert.ThrowsArgumentNull(() => new HttpSelfHostConfiguration((Uri)null), \"baseAddress\");\n        }\n\n        [Fact]\n        public void HttpSelfHostConfiguration_RelativeBaseAddress_Throws()\n        {\n            Assert.ThrowsArgument(() => new HttpSelfHostConfiguration(new Uri(\"relative\", UriKind.Relative)), \"baseAddress\");\n        }\n\n        [Fact]\n        public void HttpSelfHostConfiguration_QueryBaseAddress_Throws()\n        {\n            Assert.ThrowsArgument(() => new HttpSelfHostConfiguration(new Uri(\"http://localhost?somequery\")), \"baseAddress\");\n        }\n\n        [Fact]\n        public void HttpSelfHostConfiguration_FragmentBaseAddress_Throws()\n        {\n            Assert.ThrowsArgument(() => new HttpSelfHostConfiguration(new Uri(\"http://localhost#somefragment\")), \"baseAddress\");\n        }\n\n        [Fact]\n        public void HttpSelfHostConfiguration_InvalidSchemeBaseAddress_Throws()\n        {\n            Assert.ThrowsArgument(() => new HttpSelfHostConfiguration(new Uri(\"ftp://localhost\")), \"baseAddress\");\n        }\n\n        [Fact]\n        public void HttpSelfHostConfiguration_BaseAddress_IsSet()\n        {\n            // Arrange\n            Uri baseAddress = new Uri(\"http://localhost\");\n\n            // Act\n            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(baseAddress);\n\n            // Assert\n            Assert.Same(baseAddress, config.BaseAddress);\n        }\n\n        [Fact]\n        public void HttpSelfHostConfiguration_MaxConcurrentRequests_RoundTrips()\n        {\n            Assert.Reflection.IntegerProperty(\n                new HttpSelfHostConfiguration(\"http://localhost\"),\n                c => c.MaxConcurrentRequests,\n                expectedDefaultValue: GetDefaultMaxConcurrentRequests(),\n                minLegalValue: 1,\n                illegalLowerValue: 0,\n                maxLegalValue: null,\n                illegalUpperValue: null,\n                roundTripTestValue: 10);\n        }\n\n        [Fact]\n        public void HttpSelfHostConfiguration_MaxBufferSize_RoundTrips()\n        {\n            Assert.Reflection.IntegerProperty(\n                new HttpSelfHostConfiguration(\"http://localhost\"),\n                c => c.MaxBufferSize,\n                expectedDefaultValue: 64 * 1024,\n                minLegalValue: 1,\n                illegalLowerValue: 0,\n                maxLegalValue: null,\n                illegalUpperValue: null,\n                roundTripTestValue: 10);\n        }\n\n        [Theory]\n        [InlineData(1, 1)]\n        [InlineData(1024, 1024)]\n        [InlineData(Int32.MaxValue - 1, Int32.MaxValue - 1)]\n        [InlineData(Int32.MaxValue, Int32.MaxValue)]\n        [InlineData(Int64.MaxValue - 1, Int32.MaxValue)]\n        [InlineData(Int64.MaxValue, Int32.MaxValue)]\n        public void HttpSelfHostConfiguration_MaxBufferSize_TracksMaxReceivedMessageSizeWhenNotSet(long maxReceivedMessageSize, int expectedMaxBufferSize)\n        {\n            // Arrange\n            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(\"http://localhost\");\n            config.MaxReceivedMessageSize = maxReceivedMessageSize;\n\n            // Act & Assert\n            Assert.Equal(expectedMaxBufferSize, config.MaxBufferSize);\n        }\n\n        [Theory]\n        [InlineData(2, 1)]\n        [InlineData(1025, 1024)]\n        [InlineData(Int64.MaxValue, Int32.MaxValue)]\n        public void HttpSelfHostConfiguration_MaxBufferSize_DoesNotTrackMaxReceivedMessageSizeWhenSet(long maxReceivedMessageSize, int maxBufferSize)\n        {\n            // Arrange\n            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(\"http://localhost\");\n            config.MaxBufferSize = maxBufferSize;\n            config.MaxReceivedMessageSize = maxReceivedMessageSize;\n\n            // Act & Assert\n            Assert.Equal(maxBufferSize, config.MaxBufferSize);\n            Assert.Equal(maxReceivedMessageSize, config.MaxReceivedMessageSize);\n        }\n\n        [Theory]\n        [InlineData(1)]\n        [InlineData(1024)]\n        [InlineData(Int64.MaxValue)]\n        public void HttpSelfHostConfiguration_MaxBufferSize_DoesNotTrackMaxReceivedMessageIfNotBuffered(long maxReceivedMessageSize)\n        {\n            // Arrange\n            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(\"http://localhost\");\n            config.TransferMode = TransferMode.Streamed;\n            config.MaxReceivedMessageSize = maxReceivedMessageSize;\n\n            // Act & Assert\n            Assert.Equal(maxReceivedMessageSize, config.MaxReceivedMessageSize);\n            Assert.Equal(64 * 1024, config.MaxBufferSize);\n        }\n\n        [Fact]\n        public void HttpSelfHostConfiguration_MaxReceivedMessageSize_RoundTrips()\n        {\n            Assert.Reflection.IntegerProperty(\n                new HttpSelfHostConfiguration(\"http://localhost\"),\n                c => c.MaxReceivedMessageSize,\n                expectedDefaultValue: 64 * 1024,\n                minLegalValue: 1,\n                illegalLowerValue: 0,\n                maxLegalValue: null,\n                illegalUpperValue: null,\n                roundTripTestValue: 10);\n        }\n\n        [Fact]\n        public Task HttpSelfHostConfiguration_ClientCredentialType_RoundTrips()\n        {\n            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(\"http://localhost\");\n\n            Assert.Reflection.EnumPropertyWithoutIllegalValueCheck<HttpSelfHostConfiguration, HttpClientCredentialType>(\n                   config,\n                   c => c.ClientCredentialType,\n                   expectedDefaultValue: HttpClientCredentialType.None,\n                   roundTripTestValue: HttpClientCredentialType.Windows);\n\n            // now let us check the illegal value differently\n            config.ClientCredentialType = (HttpClientCredentialType)999;\n            return Assert.ThrowsArgumentOutOfRangeAsync(() => new HttpSelfHostServer(config).OpenAsync(), \"value\", null, 999);\n        }\n\n        [Fact]\n        public void HttpSelfHostConfiguration_UserNamePasswordValidator_RoundTrips()\n        {\n            // Arrange\n            UserNamePasswordValidator userNamePasswordValidator = new Mock<UserNamePasswordValidator>().Object;\n\n            Assert.Reflection.Property(\n                new HttpSelfHostConfiguration(\"http://localhost\"),\n                c => c.UserNamePasswordValidator,\n                expectedDefaultValue: null,\n                allowNull: false,\n                roundTripTestValue: userNamePasswordValidator);\n        }\n\n        [Fact]\n        public void HttpSelfHostConfiguration_X509CertificateValidator_RoundTrips()\n        {\n            // Arrange\n            X509CertificateValidator x509CertificateValidator = new Mock<X509CertificateValidator>().Object;\n\n            Assert.Reflection.Property(\n                new HttpSelfHostConfiguration(\"http://localhost\"),\n                c => c.X509CertificateValidator,\n                expectedDefaultValue: null,\n                allowNull: false,\n                roundTripTestValue: x509CertificateValidator);\n        }\n\n        [Fact]\n        public void HttpSelfHostConfiguration_TransferMode_RoundTrips()\n        {\n            Assert.Reflection.EnumProperty(\n                new HttpSelfHostConfiguration(\"http://localhost\"),\n                c => c.TransferMode,\n                expectedDefaultValue: TransferMode.Buffered,\n                illegalValue: (TransferMode)999,\n                roundTripTestValue: TransferMode.Streamed);\n        }\n\n        [Fact]\n        public void HttpSelfHostConfiguration_HostNameComparisonMode_RoundTrips()\n        {\n            Assert.Reflection.EnumProperty(\n                new HttpSelfHostConfiguration(\"http://localhost\"),\n                c => c.HostNameComparisonMode,\n                expectedDefaultValue: HostNameComparisonMode.StrongWildcard,\n                illegalValue: (HostNameComparisonMode)999,\n                roundTripTestValue: HostNameComparisonMode.Exact);\n        }\n\n        [Fact]\n        public void HttpSelfHostConfiguration_NegativeTimeouts_ThrowArgumentOutOfRange()\n        {\n            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(\"http://localhost\");\n            TimeSpan negativeTimeout = new TimeSpan(-1, 0, 0);\n\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(() => config.ReceiveTimeout = negativeTimeout, \"value\", \"00:00:00\", \"-01:00:00\");\n            Assert.ThrowsArgumentGreaterThanOrEqualTo(() => config.SendTimeout = negativeTimeout, \"value\", \"00:00:00\", \"-01:00:00\");\n        }\n\n        [Fact]\n        public void HttpSelfHostConfiguration_Settings_PropagateToBinding()\n        {\n            // Arrange\n            HttpBinding binding = new HttpBinding();\n            binding.ConfigureTransportBindingElement = ConfigureTransportBindingElement;\n            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(\"http://localhost\")\n            {\n                MaxBufferSize = 10,\n                MaxReceivedMessageSize = 11,\n                ReceiveTimeout = new TimeSpan(1, 0, 0),\n                SendTimeout = new TimeSpan(1, 0, 0),\n                TransferMode = TransferMode.StreamedResponse,\n                HostNameComparisonMode = HostNameComparisonMode.WeakWildcard\n            };\n\n            // Act\n            config.ConfigureBinding(binding);\n\n            // Assert\n            Assert.Equal(10, binding.MaxBufferSize);\n            Assert.Equal(11, binding.MaxReceivedMessageSize);\n            Assert.Equal(new TimeSpan(1, 0, 0), binding.ReceiveTimeout);\n            Assert.Equal(new TimeSpan(1, 0, 0), binding.SendTimeout);\n            Assert.Equal(TransferMode.StreamedResponse, binding.TransferMode);\n            Assert.Equal(HostNameComparisonMode.WeakWildcard, binding.HostNameComparisonMode);\n            Assert.Equal(Net.AuthenticationSchemes.Ntlm, binding.CreateBindingElements().Find<HttpTransportBindingElement>().AuthenticationScheme);\n        }\n\n        void ConfigureTransportBindingElement(HttpTransportBindingElement element)\n        {\n            element.AuthenticationScheme = Net.AuthenticationSchemes.Ntlm;\n        }\n\n        [Theory]\n        [PropertyData(\"BasicClientCredentialTestData\")]\n        [PropertyData(\"NonBasicClientCredentialTestData\")]\n        public void HttpSelfHostConfiguration_ClientCredentialType_PropagatesToHttpBinding(string address, HttpBindingSecurityMode mode, HttpClientCredentialType clientCredentialType)\n        {\n            // Arrange\n            HttpBinding binding = new HttpBinding();\n            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(address)\n            {\n                ClientCredentialType = clientCredentialType\n            };\n\n            // Act\n            BindingParameterCollection parameters = config.ConfigureBinding(binding);\n\n            Assert.Equal(clientCredentialType, binding.Security.Transport.ClientCredentialType);\n            Assert.Equal(mode, binding.Security.Mode);\n        }\n\n\n        [Theory]\n        [PropertyData(\"NonBasicClientCredentialTestData\")]\n        public void HttpSelfHostConfiguration_WrongClientCredentialType_WithUsernamePasswordValidator_Throws(string address, HttpBindingSecurityMode mode, HttpClientCredentialType clientCredentialType)\n        {\n            // Arrange\n            GC.KeepAlive(mode); // Mark parameter as used. See xUnit1026, [Theory] method doesn't use all parameters.\n            HttpBinding binding = new HttpBinding();\n            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(address)\n            {\n                UserNamePasswordValidator = new CustomUsernamePasswordValidator()\n            };\n\n            config.ClientCredentialType = clientCredentialType;\n\n            Assert.Throws<InvalidOperationException>(() =>\n                {\n                    // Act\n                    BindingParameterCollection parameters = config.ConfigureBinding(binding);\n                });\n        }\n\n        [Theory]\n        [PropertyData(\"BasicClientCredentialTestData\")]\n        public void HttpSelfHostConfiguration_CorrectClientCredentialType_WithUsernamePasswordValidator_Works(string address, HttpBindingSecurityMode mode, HttpClientCredentialType clientCredentialType)\n        {\n            // Arrange\n            GC.KeepAlive(mode); // Mark parameter as used. See xUnit1026, [Theory] method doesn't use all parameters.\n            HttpBinding binding = new HttpBinding();\n            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(address)\n            {\n                UserNamePasswordValidator = new CustomUsernamePasswordValidator()\n            };\n\n            config.ClientCredentialType = clientCredentialType;\n\n            // Act\n            BindingParameterCollection parameters = config.ConfigureBinding(binding);\n        }\n\n        [Theory]\n        [PropertyData(\"NonCertificateClientCredentialTestData\")]\n        public void HttpSelfHostConfiguration_WrongClientCredentialType_WithX509CertificateValidator_Throws(string address, HttpBindingSecurityMode mode, HttpClientCredentialType clientCredentialType)\n        {\n            // Arrange\n            GC.KeepAlive(mode); // Mark parameter as used. See xUnit1026, [Theory] method doesn't use all parameters.\n            HttpBinding binding = new HttpBinding();\n            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(address)\n            {\n                X509CertificateValidator = new Mock<X509CertificateValidator>().Object\n            };\n\n            config.ClientCredentialType = clientCredentialType;\n\n            Assert.Throws<InvalidOperationException>(() =>\n            {\n                // Act\n                BindingParameterCollection parameters = config.ConfigureBinding(binding);\n            });\n        }\n\n        [Theory]\n        [PropertyData(\"CertificateClientCredentialTestData\")]\n        public void HttpSelfHostConfiguration_CorrectClientCredentialType_WithX509CertificateValidator_Works(string address, HttpBindingSecurityMode mode, HttpClientCredentialType clientCredentialType)\n        {\n            // Arrange\n            GC.KeepAlive(mode); // Mark parameter as used. See xUnit1026, [Theory] method doesn't use all parameters.\n            HttpBinding binding = new HttpBinding();\n            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(address)\n            {\n                X509CertificateValidator = new Mock<X509CertificateValidator>().Object\n            };\n\n            config.ClientCredentialType = clientCredentialType;\n\n            // Act\n            BindingParameterCollection parameters = config.ConfigureBinding(binding);\n        }\n\n\n        [Theory]\n        [InlineData(\"http://localhost\", HttpBindingSecurityMode.TransportCredentialOnly)]\n        [InlineData(\"https://localhost\", HttpBindingSecurityMode.Transport)]\n        public void HttpSelfHostConfiguration_UserNamePasswordValidator_PropagatesToBinding(string address, HttpBindingSecurityMode mode)\n        {\n            // Arrange\n            HttpBinding binding = new HttpBinding();\n            UserNamePasswordValidator validator = new Mock<UserNamePasswordValidator>().Object;\n            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(address)\n            {\n                UserNamePasswordValidator = validator\n            };\n\n            // Act\n            BindingParameterCollection parameters = config.ConfigureBinding(binding);\n\n            // Assert\n            Assert.NotNull(parameters);\n            ServiceCredentials serviceCredentials = parameters.Find<ServiceCredentials>();\n            Assert.NotNull(serviceCredentials);\n            Assert.Equal(HttpClientCredentialType.Basic, binding.Security.Transport.ClientCredentialType);\n            Assert.Equal(mode, binding.Security.Mode);\n        }\n\n        private static int GetDefaultMaxConcurrentRequests()\n        {\n            try\n            {\n                return Math.Max(Environment.ProcessorCount * 100, 100);\n            }\n            catch\n            {\n                return 100;\n            }\n        }\n\n        public class CustomUsernamePasswordValidator : UserNamePasswordValidator\n        {\n            public override void Validate(string userName, string password)\n            {\n                if (userName == \"username\" && password == \"password\")\n                {\n                    return;\n                }\n                else\n                {\n                    throw new InvalidOperationException();\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.SelfHost.Test/HttpSelfHostResponseTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.ServiceModel;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.SelfHost\n{\n    [Xunit.Collection(\"PortReserver Collection\")] // Avoid conflicts between different PortReserver consumers.\n    public class HttpSelfHostResponseTest\n    {\n        [Fact]\n        public async Task Get_Returns_500_And_No_Content_For_Null_HttpResponseMessage_From_MessageHandler()\n        {\n            using (var selfHostTester = new SelfHostTester())\n            {\n                // Arrange\n                selfHostTester.MessageHandler.ReturnNull = true;\n                HttpRequestMessage request = new HttpRequestMessage();\n                request.RequestUri = new Uri(Path.Combine(selfHostTester.BaseAddress, \"NullResponse/GetNormalResponse\"));\n                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(\"application/json\"));\n                request.Method = HttpMethod.Get;\n\n                // Action\n                HttpResponseMessage response = await selfHostTester.HttpClient.SendAsync(request);\n\n                // Assert\n                Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n                Assert.Equal(0, response.Content.Headers.ContentLength);\n            }\n        }\n\n        [Fact]\n        public async Task Post_Returns_500_And_No_Content_For_Null_HttpResponseMessage_From_MessageHandler()\n        {\n            using (var selfHostTester = new SelfHostTester())\n            {\n                // Arrange\n                selfHostTester.MessageHandler.ReturnNull = true;\n                HttpRequestMessage request = new HttpRequestMessage();\n                request.RequestUri = new Uri(Path.Combine(selfHostTester.BaseAddress, \"NullResponse/PostNormalResponse\"));\n                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(\"application/json\"));\n                request.Method = HttpMethod.Post;\n                request.Content = new ObjectContent<NullResponseCustomer>(new NullResponseCustomer() { Name = \"Sue\", Age = 39 }, new JsonMediaTypeFormatter());\n\n                // Action\n                HttpResponseMessage response = await selfHostTester.HttpClient.SendAsync(request);\n\n                // Assert\n                Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n                Assert.Equal(0, response.Content.Headers.ContentLength);\n            }\n        }\n\n        [Fact]\n        public async Task Get_Returns_500_And_Error_Content_For_Null_HttpResponseMessage_From_Action()\n        {\n            using (var selfHostTester = new SelfHostTester())\n            {\n                // Arrange\n                selfHostTester.MessageHandler.ReturnNull = false;\n                HttpRequestMessage request = new HttpRequestMessage();\n                request.RequestUri = new Uri(Path.Combine(selfHostTester.BaseAddress, \"NullResponse/GetNullResponseFromAction\"));\n                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(\"application/json\"));\n                request.Method = HttpMethod.Get;\n\n                // Action\n                HttpResponseMessage response = await selfHostTester.HttpClient.SendAsync(request);\n\n                // Assert\n                Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n                Assert.Contains(\"\\\"Message\\\":\\\"An error has occurred.\\\"\", await response.Content.ReadAsStringAsync());\n            }\n        }\n\n        [Fact]\n        public async Task Post_Returns_500_And_Error_Content_For_Null_HttpResponseMessage_From_Action()\n        {\n            using (var selfHostTester = new SelfHostTester())\n            {\n                // Arrange\n                selfHostTester.MessageHandler.ReturnNull = false;\n                HttpRequestMessage request = new HttpRequestMessage();\n                request.RequestUri = new Uri(Path.Combine(selfHostTester.BaseAddress, \"NullResponse/PostNullResponseFromAction\"));\n                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(\"application/json\"));\n                request.Method = HttpMethod.Post;\n                request.Content = new ObjectContent<NullResponseCustomer>(new NullResponseCustomer() { Name = \"Sue\", Age = 39 }, new JsonMediaTypeFormatter());\n\n                // Action\n                HttpResponseMessage response = await selfHostTester.HttpClient.SendAsync(request);\n\n                // Assert\n                Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n                Assert.Contains(\"\\\"Message\\\":\\\"An error has occurred.\\\"\", await response.Content.ReadAsStringAsync());\n            }\n        }\n\n        [Fact]\n        public async Task Get_Returns_500_And_Error_Content_For_Null_Task_From_Action()\n        {\n            using (var selfHostTester = new SelfHostTester())\n            {\n                // Arrange\n                selfHostTester.MessageHandler.ReturnNull = false;\n                HttpRequestMessage request = new HttpRequestMessage();\n                request.RequestUri = new Uri(Path.Combine(selfHostTester.BaseAddress, \"NullResponse/GetNullTaskFromAction\"));\n                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(\"application/json\"));\n                request.Method = HttpMethod.Get;\n\n                // Action\n                HttpResponseMessage response = await selfHostTester.HttpClient.SendAsync(request);\n\n                // Assert\n                Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n                Assert.Contains(\"\\\"Message\\\":\\\"An error has occurred.\\\"\", await response.Content.ReadAsStringAsync());\n            }\n        }\n\n        [Fact]\n        public async Task Post_Returns_500_And_Error_Content_For_Null_Task_From_Action()\n        {\n            using (var selfHostTester = new SelfHostTester())\n            {\n                // Arrange\n                selfHostTester.MessageHandler.ReturnNull = false;\n                HttpRequestMessage request = new HttpRequestMessage();\n                request.RequestUri = new Uri(Path.Combine(selfHostTester.BaseAddress, \"NullResponse/PostNullTaskFromAction\"));\n                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(\"application/json\"));\n                request.Method = HttpMethod.Post;\n                request.Content = new ObjectContent<NullResponseCustomer>(new NullResponseCustomer() { Name = \"Sue\", Age = 39 }, new JsonMediaTypeFormatter());\n\n                // Action\n                HttpResponseMessage response = await selfHostTester.HttpClient.SendAsync(request);\n\n                // Assert\n                Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n                Assert.Contains(\"\\\"Message\\\":\\\"An error has occurred.\\\"\", await response.Content.ReadAsStringAsync());\n            }\n        }\n\n        private class SelfHostTester : IDisposable\n        {\n            private HttpSelfHostServer _server;\n            private PortReserver _testPort = new PortReserver();\n\n            public string BaseAddress { get; private set; }\n            public HttpClient HttpClient { get; private set; }\n            public NullResponseMessageHandler MessageHandler { get; private set; }\n\n            public SelfHostTester()\n            {\n                HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_testPort.BaseUri);\n                BaseAddress = _testPort.BaseUri;\n\n                config.HostNameComparisonMode = HostNameComparisonMode.Exact;\n                config.Routes.MapHttpRoute(\"Default\", \"{controller}/{action}\", new { controller = \"NullResponse\" });\n\n                MessageHandler = new NullResponseMessageHandler();\n                config.MessageHandlers.Add(MessageHandler);\n\n                _server = new HttpSelfHostServer(config);\n                _server.OpenAsync().Wait();\n\n                HttpClient = new HttpClient();\n            }\n\n            public void Dispose()\n            {\n                _testPort.Dispose();\n                HttpClient.Dispose();\n                _server.CloseAsync().Wait();\n            }\n        }\n    }\n\n    public class NullResponseController : ApiController\n    {\n        [HttpGet]\n        public NullResponseCustomer GetNormalResponse()\n        {\n            return new NullResponseCustomer() { Name = \"Fred\", Age = 39 };\n        }\n\n        [HttpPost]\n        public NullResponseCustomer PostNormalResponse(NullResponseCustomer customer)\n        {\n            return customer;\n        }\n\n        [HttpGet]\n        public HttpResponseMessage GetNullResponseFromAction()\n        {\n            return null;\n        }\n\n        [HttpPost]\n        public HttpResponseMessage PostNullResponseFromAction(NullResponseCustomer customer)\n        {\n            return null;\n        }\n\n        [HttpGet]\n        public Task<HttpResponseMessage> GetNullTaskFromAction()\n        {\n            return null;\n        }\n\n        [HttpPost]\n        public Task<HttpResponseMessage> PostNullTaskFromAction(NullResponseCustomer customer)\n        {\n            return null;\n        }\n    }\n\n    public class NullResponseCustomer\n    {\n        public string Name { get; set; }\n        public int Age { get; set; }\n    }\n\n    public class NullResponseMessageHandler : DelegatingHandler\n    {\n        public bool ReturnNull { get; set; }\n\n        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, Threading.CancellationToken cancellationToken)\n        {\n            Task<HttpResponseMessage> t = base.SendAsync(request, cancellationToken);\n\n            if (!ReturnNull)\n            {\n                return t;\n            }\n\n            TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();\n            tcs.SetResult(null);\n            return tcs.Task;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.SelfHost.Test/HttpSelfHostServerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.ServiceModel;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.Routing;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.SelfHost\n{\n    [Xunit.Collection(\"PortReserver Collection\")] // Avoid conflicts between different PortReserver consumers.\n    public class HttpSelfHostServerTest : IDisposable\n    {\n        private HttpSelfHostServer server = null;\n\n        public void Dispose()\n        {\n            if (server != null)\n            {\n                server.CloseAsync().Wait();\n            }\n        }\n\n        [Theory]\n        [InlineData(\"/SelfHostServerTest/EchoString\", TransferMode.Buffered)]\n        [InlineData(\"/SelfHostServerTest/EchoString\", TransferMode.Streamed)]\n        public async Task SendAsync_Direct_Returns_OK_For_Successful_ObjectContent_Write(string uri, TransferMode transferMode)\n        {\n            using (var port = new PortReserver())\n            {\n                // Arrange & Act\n                server = await CreateServerAsync(port, transferMode);\n                HttpResponseMessage response = await new HttpClient().GetAsync(BaseUri(port, transferMode) + uri);\n                string responseString = await response.Content.ReadAsStringAsync();\n\n                // Assert\n                Assert.Equal(HttpStatusCode.OK, response.StatusCode);\n                Assert.Equal(\"\\\"echoString\\\"\", responseString);\n            }\n        }\n\n        [Theory]\n        [InlineData(\"/SelfHostServerTest/EchoString\", TransferMode.Buffered)]\n        [InlineData(\"/SelfHostServerTest/EchoString\", TransferMode.Streamed)]\n        public async Task SendAsync_ServiceModel_Returns_OK_For_Successful_ObjectContent_Write(string uri, TransferMode transferMode)\n        {\n            using (var port = new PortReserver())\n            {\n                // Arrange\n                server = await CreateServerAsync(port, transferMode);\n                bool shouldChunk = transferMode == TransferMode.Streamed;\n\n                // Act\n                HttpResponseMessage response = await new HttpClient().GetAsync(BaseUri(port, transferMode) + uri);\n                string responseString = await response.Content.ReadAsStringAsync();\n                IEnumerable<string> headerValues = null;\n                bool isChunked = response.Headers.TryGetValues(\"Transfer-Encoding\", out headerValues) && headerValues != null &&\n                                 headerValues.Any((v) => String.Equals(v, \"chunked\", StringComparison.OrdinalIgnoreCase));\n\n                // Assert\n                Assert.Equal(HttpStatusCode.OK, response.StatusCode);\n                Assert.Equal(\"\\\"echoString\\\"\", responseString);\n                Assert.Equal(shouldChunk, isChunked);\n            }\n        }\n\n        [Theory]\n        [InlineData(\"/SelfHostServerTest/EchoStream\", TransferMode.Buffered)]\n        [InlineData(\"/SelfHostServerTest/EchoStream\", TransferMode.Streamed)]\n        public async Task SendAsync_Direct_Returns_OK_For_Successful_Stream_Write(string uri, TransferMode transferMode)\n        {\n            using (var port = new PortReserver())\n            {\n                // Arrange & Act\n                server = await CreateServerAsync(port, transferMode);\n                HttpResponseMessage response = await new HttpClient(server).GetAsync(BaseUri(port, transferMode) + uri);\n                string responseString = await response.Content.ReadAsStringAsync();\n                IEnumerable<string> headerValues = null;\n                bool isChunked = response.Headers.TryGetValues(\"Transfer-Encoding\", out headerValues) && headerValues != null &&\n                                 headerValues.Any((v) => String.Equals(v, \"chunked\", StringComparison.OrdinalIgnoreCase));\n\n                Assert.Equal(HttpStatusCode.OK, response.StatusCode);\n                Assert.Equal(\"echoStream\", responseString);\n                Assert.False(isChunked);    // stream never chunk, buffered or streamed\n            }\n        }\n\n        [Theory]\n        [InlineData(\"/SelfHostServerTest/EchoStream\", TransferMode.Buffered)]\n        [InlineData(\"/SelfHostServerTest/EchoStream\", TransferMode.Streamed)]\n        public async Task SendAsync_ServiceModel_Returns_OK_For_Successful_Stream_Write(string uri, TransferMode transferMode)\n        {\n            using (var port = new PortReserver())\n            {\n                // Arrange & Act\n                server = await CreateServerAsync(port, transferMode);\n                HttpResponseMessage response = await new HttpClient().GetAsync(BaseUri(port, transferMode) + uri);\n                string responseString = await response.Content.ReadAsStringAsync();\n\n                // Assert\n                Assert.Equal(HttpStatusCode.OK, response.StatusCode);\n                Assert.Equal(\"echoStream\", responseString);\n            }\n        }\n\n        [Theory]\n        [InlineData(\"/SelfHostServerTest/ThrowBeforeTask\", TransferMode.Buffered)]\n        [InlineData(\"/SelfHostServerTest/ThrowBeforeTask\", TransferMode.Streamed)]\n        [InlineData(\"/SelfHostServerTest/ThrowBeforeWrite\", TransferMode.Buffered)]\n        [InlineData(\"/SelfHostServerTest/ThrowBeforeWrite\", TransferMode.Streamed)]\n        [InlineData(\"/SelfHostServerTest/ThrowAfterWrite\", TransferMode.Buffered)]\n        [InlineData(\"/SelfHostServerTest/ThrowAfterWrite\", TransferMode.Streamed)]\n        public async Task SendAsync_Direct_Throws_When_ObjectContent_CopyToAsync_Throws(string uri, TransferMode transferMode)\n        {\n            using (var port = new PortReserver())\n            {\n                // Arrange & Act & Assert\n                server = await CreateServerAsync(port, transferMode);\n                await Assert.ThrowsAsync<InvalidOperationException>(\n                    () => new HttpClient(server).GetAsync(BaseUri(port, transferMode) + uri));\n            }\n        }\n\n        [Theory]\n        [InlineData(\"/SelfHostServerTest/ThrowBeforeTask\", TransferMode.Buffered)]\n        [InlineData(\"/SelfHostServerTest/ThrowBeforeTask\", TransferMode.Streamed)]\n        [InlineData(\"/SelfHostServerTest/ThrowBeforeWrite\", TransferMode.Buffered)]\n        [InlineData(\"/SelfHostServerTest/ThrowBeforeWrite\", TransferMode.Streamed)]\n        [InlineData(\"/SelfHostServerTest/ThrowAfterWrite\", TransferMode.Buffered)]\n        [InlineData(\"/SelfHostServerTest/ThrowAfterWrite\", TransferMode.Streamed)]\n        public async Task SendAsync_ServiceModel_Closes_Connection_When_ObjectContent_CopyToAsync_Throws(string uri, TransferMode transferMode)\n        {\n            using (var port = new PortReserver())\n            {\n                // Arrange\n                server = await CreateServerAsync(port, transferMode);\n                Task<HttpResponseMessage> task = new HttpClient().GetAsync(BaseUri(port, transferMode) + uri);\n\n                // Act & Assert\n                await Assert.ThrowsAsync<HttpRequestException>(() => task);\n            }\n        }\n\n        [Theory]\n        [InlineData(\"/SelfHostServerTest/ThrowBeforeWriteStream\", TransferMode.Buffered)]\n        [InlineData(\"/SelfHostServerTest/ThrowBeforeWriteStream\", TransferMode.Streamed)]\n        [InlineData(\"/SelfHostServerTest/ThrowAfterWriteStream\", TransferMode.Buffered)]\n        [InlineData(\"/SelfHostServerTest/ThrowAfterWriteStream\", TransferMode.Streamed)]\n        public async Task SendAsync_Direct_Throws_When_StreamContent_Throws(string uri, TransferMode transferMode)\n        {\n            using (var port = new PortReserver())\n            {\n                // Arrange & Act & Assert\n                server = await CreateServerAsync(port, transferMode);\n                await Assert.ThrowsAsync<InvalidOperationException>(\n                    () => new HttpClient(server).GetAsync(BaseUri(port, transferMode) + uri));\n            }\n        }\n\n        [Theory]\n        [InlineData(\"/SelfHostServerTest/ThrowBeforeWriteStream\", TransferMode.Buffered)]\n        [InlineData(\"/SelfHostServerTest/ThrowBeforeWriteStream\", TransferMode.Streamed)]\n        [InlineData(\"/SelfHostServerTest/ThrowAfterWriteStream\", TransferMode.Buffered)]\n        [InlineData(\"/SelfHostServerTest/ThrowAfterWriteStream\", TransferMode.Streamed)]\n        public async Task SendAsync_ServiceModel_Throws_When_StreamContent_Throws(string uri, TransferMode transferMode)\n        {\n            using (var port = new PortReserver())\n            {\n                // Arrange\n                server = await CreateServerAsync(port, transferMode);\n                Task task = new HttpClient().GetAsync(BaseUri(port, transferMode) + uri);\n\n                // Act & Assert\n                await Assert.ThrowsAsync<HttpRequestException>(() => task);\n            }\n        }\n\n        [Fact]\n        public async Task SendAsync_ServiceModel_AddsSelfHostHttpRequestContext()\n        {\n            // Arrange\n            using (PortReserver port = new PortReserver())\n            {\n                string baseUri = port.BaseUri;\n\n                HttpRequestContext context = null;\n                Uri via = null;\n\n                Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> sendAsync = (r, c) =>\n                {\n                    if (r != null)\n                    {\n                        context = r.GetRequestContext();\n                    }\n\n                    SelfHostHttpRequestContext typedContext = context as SelfHostHttpRequestContext;\n\n                    if (typedContext != null)\n                    {\n                        via = typedContext.RequestContext.RequestMessage.Properties.Via;\n                    }\n\n                    return Task.FromResult(new HttpResponseMessage());\n                };\n\n                using (HttpSelfHostConfiguration expectedConfiguration = new HttpSelfHostConfiguration(baseUri))\n                {\n                    expectedConfiguration.HostNameComparisonMode = HostNameComparisonMode.Exact;\n\n                    using (HttpMessageHandler dispatcher = new LambdaHttpMessageHandler(sendAsync))\n                    using (HttpSelfHostServer server = new HttpSelfHostServer(expectedConfiguration, dispatcher))\n                    using (HttpClient client = new HttpClient())\n                    using (HttpRequestMessage expectedRequest = new HttpRequestMessage(HttpMethod.Get, baseUri))\n                    {\n                        await server.OpenAsync();\n\n                        // Act\n                        using (HttpResponseMessage ignore = await client.SendAsync(expectedRequest))\n                        {\n                            // Assert\n                            SelfHostHttpRequestContext typedContext = (SelfHostHttpRequestContext)context;\n                            Assert.Equal(expectedRequest.RequestUri, via);\n                            Assert.Same(expectedConfiguration, context.Configuration);\n                            Assert.Equal(expectedRequest.RequestUri, typedContext.Request.RequestUri);\n\n                            await server.CloseAsync();\n                        }\n                    }\n                }\n            }\n        }\n\n        [Theory]\n        [InlineData(\"/SelfHostServerTest/EchoString\", TransferMode.Buffered)]\n        [InlineData(\"/SelfHostServerTest/EchoString\", TransferMode.Streamed)]\n        public async Task Get_Returns_Hard404_If_IgnoreRoute(string uri, TransferMode transferMode)\n        {\n            using (var port = new PortReserver())\n            {\n                // Arrange & Act\n                server = await CreateServerAsync(port, transferMode, ignoreRoute: true);\n                HttpResponseMessage response = await new HttpClient().GetAsync(BaseUri(port, transferMode) + uri);\n\n                // Assert\n                Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);\n                Assert.False(response.RequestMessage.Properties.ContainsKey(HttpPropertyKeys.NoRouteMatched));\n            }\n        }\n\n        [Theory]\n        [InlineData(\"/a/b/c/d/e\", TransferMode.Buffered)]\n        [InlineData(\"/EchoString?f=12\", TransferMode.Streamed)]\n        public async Task Get_Returns_Hard404_If_IgnoreRouteDoesNotMatch(string uri, TransferMode transferMode)\n        {\n            using (var port = new PortReserver())\n            {\n                // Arrange & Act\n                server = await CreateServerAsync(port, transferMode, ignoreRoute: true);\n                HttpResponseMessage response = await new HttpClient().GetAsync(BaseUri(port, transferMode) + uri);\n\n                // Assert\n                Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);\n                Assert.False(response.RequestMessage.Properties.ContainsKey(HttpPropertyKeys.NoRouteMatched));\n            }\n        }\n\n        [Theory]\n        [InlineData(\"/constraint/values/10\", TransferMode.Buffered)]\n        [InlineData(\"/constraint/values/15\", TransferMode.Buffered)]\n        [InlineData(\"/constraint/values/20\", TransferMode.Buffered)]\n        public async Task Get_Returns_Hard404_If_IgnoreRoute_WithConstraints_ConstraintsMatched(string uri, TransferMode transferMode)\n        {\n            using (var port = new PortReserver())\n            {\n                // Arrange & Act\n                server = await CreateServerAsync(port, transferMode, ignoreRoute: true);\n                HttpResponseMessage response = await new HttpClient().GetAsync(BaseUri(port, transferMode) + uri);\n\n                // Assert\n                Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);\n                Assert.False(response.RequestMessage.Properties.ContainsKey(HttpPropertyKeys.NoRouteMatched));\n            }\n        }\n\n        [Theory]\n        [InlineData(\"/constraint/values/40\", TransferMode.Buffered)]\n        [InlineData(\"/constraint/values/50\", TransferMode.Buffered)]\n        [InlineData(\"/constraint/values/65\", TransferMode.Buffered)]\n        public async Task Get_Returns_Value_If_IgnoreRoute_WithConstraints_ConstraintsNotMatched(string uri, TransferMode transferMode)\n        {\n            using (var port = new PortReserver())\n            {\n                // Arrange & Act\n                server = await CreateServerAsync(port, transferMode, ignoreRoute: true);\n                HttpResponseMessage response = await new HttpClient().GetAsync(BaseUri(port, transferMode) + uri);\n                string responseString = await response.Content.ReadAsStringAsync();\n\n                // Assert\n                Assert.Equal(HttpStatusCode.OK, response.StatusCode);\n                Assert.Equal(String.Concat(\"/constraint/values/\", responseString), uri);\n            }\n        }\n\n        [Theory]\n        [InlineData(\"/other/SelfHostServerTest/EchoString\", TransferMode.Buffered)]\n        [InlineData(\"/other/SelfHostServerTest/EchoString\", TransferMode.Streamed)]\n        public async Task Get_Returns_Success_If_OtherRouteMatched(string uri, TransferMode transferMode)\n        {\n            using (var port = new PortReserver())\n            {\n                // Arrange & Act\n                server = await CreateServerAsync(port, transferMode, ignoreRoute: true);\n                HttpResponseMessage response = await new HttpClient().GetAsync(BaseUri(port, transferMode) + uri);\n                string responseString = await response.Content.ReadAsStringAsync();\n\n                // Assert\n                Assert.Equal(HttpStatusCode.OK, response.StatusCode);\n                Assert.Equal(\"\\\"echoString\\\"\", responseString);\n            }\n        }\n\n        internal class ThrowsBeforeTaskObjectContent : ObjectContent\n        {\n            public ThrowsBeforeTaskObjectContent()\n                : base(typeof(string), \"testContent\", new JsonMediaTypeFormatter())\n            {\n            }\n\n            protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)\n            {\n                throw new InvalidOperationException(\"ThrowBeforeTask\");\n            }\n        }\n\n        internal class ThrowBeforeWriteObjectContent : ObjectContent\n        {\n            public ThrowBeforeWriteObjectContent()\n                : base(typeof(string), \"testContent\", new JsonMediaTypeFormatter())\n            {\n            }\n\n            protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)\n            {\n                return Task.Factory.StartNew(() =>\n                        {\n                            throw new InvalidOperationException(\"ThrowBeforeWrite\");\n                        });\n\n            }\n        }\n\n        internal class ThrowAfterWriteObjectContent : ObjectContent\n        {\n            public ThrowAfterWriteObjectContent()\n                : base(typeof(string), \"testContent\", new JsonMediaTypeFormatter())\n            {\n            }\n\n            protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)\n            {\n                return Task.Factory.StartNew(() =>\n                                                 {\n                                                     byte[] buffer =\n                                                         Encoding.UTF8.GetBytes(\"ThrowAfterWrite\");\n                                                     stream.Write(buffer, 0, buffer.Length);\n                                                     throw new InvalidOperationException(\"ThrowAfterWrite\");\n                                                 });\n            }\n        }\n\n        internal class ThrowBeforeWriteStream : StreamContent\n        {\n            public ThrowBeforeWriteStream()\n                : base(new MemoryStream(Encoding.UTF8.GetBytes(\"ThrowBeforeWriteStream\")))\n            {\n            }\n\n            protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)\n            {\n                throw new InvalidOperationException(\"ThrowBeforeWriteStream\");\n            }\n        }\n\n        internal class ThrowAfterWriteStream : StreamContent\n        {\n            public ThrowAfterWriteStream()\n                : base(new MemoryStream(Encoding.UTF8.GetBytes(\"ThrowAfterWriteStream\")))\n            {\n            }\n\n            protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)\n            {\n                await base.SerializeToStreamAsync(stream, context);\n                throw new InvalidOperationException(\"ThrowAfterWriteStream\");\n            }\n        }\n\n        private static async Task<HttpSelfHostServer> CreateServerAsync(PortReserver port, TransferMode transferMode, bool ignoreRoute = false)\n        {\n            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(BaseUri(port, transferMode));\n            config.HostNameComparisonMode = HostNameComparisonMode.Exact;\n            if (ignoreRoute)\n            {\n                config.Routes.IgnoreRoute(\"Ignore\", \"{controller}/{action}\");\n                config.Routes.IgnoreRoute(\"IgnoreWithConstraints\", \"constraint/values/{id}\", constraints: new { constraint = new CustomConstraint() });\n            }\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{action}\");\n            config.Routes.MapHttpRoute(\"Other\", \"other/{controller}/{action}\");\n            config.TransferMode = transferMode;\n            config.MapHttpAttributeRoutes();\n\n            HttpSelfHostServer server = new HttpSelfHostServer(config);\n            await server.OpenAsync();\n            return server;\n        }\n\n        public class CustomConstraint : IHttpRouteConstraint\n        {\n            public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName,\n                IDictionary<string, object> values, HttpRouteDirection routeDirection)\n            {\n                long id;\n                if (values.ContainsKey(\"id\")\n                    && Int64.TryParse(values[\"id\"].ToString(), out id)\n                    && (id == 10 || id == 15 || id == 20))\n                {\n                    return true;\n                }\n\n                return false;\n            }\n        }\n\n        private static string BaseUri(PortReserver port, TransferMode transferMode)\n        {\n            return transferMode == TransferMode.Streamed\n                ? port.BaseUri + \"stream\"\n                : port.BaseUri;\n        }\n\n        private class LambdaHttpMessageHandler : HttpMessageHandler\n        {\n            private readonly Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> _sendAsync;\n\n            public LambdaHttpMessageHandler(\n                Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> sendAsync)\n            {\n                _sendAsync = sendAsync;\n            }\n\n            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,\n                CancellationToken cancellationToken)\n            {\n                return _sendAsync.Invoke(request, cancellationToken);\n            }\n        }\n    }\n\n    public class SelfHostServerTestController : ApiController\n    {\n        [HttpGet]\n        public string EchoString()\n        {\n            return \"echoString\";\n        }\n\n        [HttpGet]\n        public HttpResponseMessage EchoStream()\n        {\n            return new HttpResponseMessage(HttpStatusCode.OK)\n                       {\n                           Content = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes(\"echoStream\")))\n                       };\n        }\n\n        [HttpGet]\n        public HttpResponseMessage ThrowBeforeTask()\n        {\n            return new HttpResponseMessage(HttpStatusCode.OK)\n                {\n                    RequestMessage = Request,\n                    Content = new HttpSelfHostServerTest.ThrowsBeforeTaskObjectContent()\n                };\n        }\n\n        [HttpGet]\n        public HttpResponseMessage ThrowBeforeWrite()\n        {\n            return new HttpResponseMessage(HttpStatusCode.OK)\n            {\n                RequestMessage = Request,\n                Content = new HttpSelfHostServerTest.ThrowBeforeWriteObjectContent()\n            };\n        }\n\n        [HttpGet]\n        public HttpResponseMessage ThrowAfterWrite()\n        {\n            return new HttpResponseMessage(HttpStatusCode.OK)\n            {\n                RequestMessage = Request,\n                Content = new HttpSelfHostServerTest.ThrowAfterWriteObjectContent()\n            };\n        }\n\n        [HttpGet]\n        public HttpResponseMessage ThrowBeforeWriteStream()\n        {\n            return new HttpResponseMessage(HttpStatusCode.OK)\n            {\n                RequestMessage = Request,\n                Content = new HttpSelfHostServerTest.ThrowBeforeWriteStream()\n            };\n        }\n\n        [HttpGet]\n        public HttpResponseMessage ThrowAfterWriteStream()\n        {\n            return new HttpResponseMessage(HttpStatusCode.OK)\n            {\n                RequestMessage = Request,\n                Content = new HttpSelfHostServerTest.ThrowAfterWriteStream()\n            };\n        }\n    }\n\n    [RoutePrefix(\"constraint\")]\n    public class IgnoreRouteWithConstraintsTestController : ApiController\n    {\n        [Route(\"values/{id:int}\")]\n        public int Get(int id)\n        {\n            return id;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.SelfHost.Test/MaxHttpCollectionKeyTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.IO;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Newtonsoft.Json.Linq;\n\nnamespace System.Web.Http.SelfHost\n{\n    public class MaxHttpCollectionKeyTests\n    {\n        private HttpServer server = null;\n        private string baseAddress = null;\n        private HttpClient httpClient = null;\n\n        public MaxHttpCollectionKeyTests()\n        {\n            this.SetupHost();\n        }\n\n        private void SetupHost()\n        {\n            baseAddress = String.Format(\"http://localhost/\");\n\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{action}\", new { controller = \"MaxHttpCollectionKeyType\" });\n\n            server = new HttpServer(config);\n\n            httpClient = new HttpClient(server);\n        }\n\n        [Theory]\n        [InlineData(\"PostCustomer\")]\n        [InlineData(\"PostFormData\")]\n        public async Task PostManyKeysInFormUrlEncodedThrows(string actionName)\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.RequestUri = new Uri(Path.Combine(baseAddress, \"MaxHttpCollectionKeyType/\" + actionName));\n            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(\"application/xml\"));\n            request.Method = HttpMethod.Post;\n            request.Content = new StringContent(GenerateHttpCollectionKeyInput(100), UTF8Encoding.UTF8, \"application/x-www-form-urlencoded\");\n            MediaTypeFormatter.MaxHttpCollectionKeys = 99;\n\n            // Action\n            HttpResponseMessage response = await httpClient.SendAsync(request);\n\n            // Assert\n            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);\n            string expectedResponseValue = @\"The number of keys in a NameValueCollection has exceeded the limit of '99'. You can adjust it by modifying the MaxHttpCollectionKeys property on the 'System.Net.Http.Formatting.MediaTypeFormatter' class.\";\n            Assert.Equal(expectedResponseValue, await response.Content.ReadAsStringAsync());\n        }\n\n        [Theory]\n        [InlineData(\"PostCustomer\")]\n        [InlineData(\"PostFormData\")]\n        public async Task PostNotTooManyKeysInFormUrlEncodedWorks(string actionName)\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.RequestUri = new Uri(Path.Combine(baseAddress, \"MaxHttpCollectionKeyType/\" + actionName));\n            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(\"application/xml\"));\n            request.Method = HttpMethod.Post;\n            request.Content = new StringContent(GenerateHttpCollectionKeyInput(100), UTF8Encoding.UTF8, \"application/x-www-form-urlencoded\");\n            MediaTypeFormatter.MaxHttpCollectionKeys = 1000;\n\n            // Action\n            HttpResponseMessage response = await httpClient.SendAsync(request);\n\n            // Assert\n            string expectedResponseValue = @\"<string xmlns=\"\"http://schemas.microsoft.com/2003/10/Serialization/\"\">success from \" + actionName + \"</string>\";\n            Assert.NotNull(response.Content);\n            Assert.NotNull(response.Content.Headers.ContentType);\n            Assert.Equal(\"application/xml\", response.Content.Headers.ContentType.MediaType);\n            Assert.Equal(expectedResponseValue, await response.Content.ReadAsStringAsync());\n        }\n\n        [Theory]\n        [InlineData(\"PostCustomerFromUri\")]\n        [InlineData(\"GetWithQueryable\")]\n        public async Task PostManyKeysInUriThrows(string actionName)\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.RequestUri = new Uri(Path.Combine(baseAddress, \"MaxHttpCollectionKeyType/\" + actionName + \"/?\" + GenerateHttpCollectionKeyInput(100)));\n            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(\"application/xml\"));\n\n            if (actionName.StartsWith(\"Post\"))\n            {\n                request.Method = HttpMethod.Post;\n                request.Content = new StringContent(\"\", UTF8Encoding.UTF8, \"application/x-www-form-urlencoded\");\n            }\n            else\n            {\n                request.Method = HttpMethod.Get;\n            }\n\n            MediaTypeFormatter.MaxHttpCollectionKeys = 99;\n\n            // Action\n            HttpResponseMessage response = await httpClient.SendAsync(request);\n\n            // Assert\n            Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n        }\n\n        [Theory]\n        [InlineData(\"PostCustomerFromUri\")]\n        [InlineData(\"GetWithQueryable\")]\n        public async Task PostNotTooManyKeysInUriWorks(string actionName)\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.RequestUri = new Uri(Path.Combine(baseAddress, \"MaxHttpCollectionKeyType/\" + actionName + \"/?\" + GenerateHttpCollectionKeyInput(100)));\n            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(\"application/xml\"));\n\n            if (actionName.StartsWith(\"Post\"))\n            {\n                request.Method = HttpMethod.Post;\n                request.Content = new StringContent(\"\", UTF8Encoding.UTF8, \"application/x-www-form-urlencoded\");\n            }\n            else\n            {\n                request.Method = HttpMethod.Get;\n            }\n\n            MediaTypeFormatter.MaxHttpCollectionKeys = 1000;\n\n            // Action\n            HttpResponseMessage response = await httpClient.SendAsync(request);\n\n            // Assert\n            string expectedResponseValue = @\"success from \" + actionName;\n            Assert.NotNull(response.Content);\n            Assert.NotNull(response.Content.Headers.ContentType);\n            Assert.Equal(\"application/xml\", response.Content.Headers.ContentType.MediaType);\n            Assert.Contains(expectedResponseValue, await response.Content.ReadAsStringAsync());\n        }\n\n        private static string GenerateHttpCollectionKeyInput(int num)\n        {\n            StringBuilder sb = new StringBuilder(\"a=0\");\n\n            for (int i = 0; i < num; i++)\n            {\n                sb.Append(\"&\");\n                sb.Append(i.ToString());\n                sb.Append(\"=0\");\n            }\n\n            return sb.ToString();\n        }\n    }\n\n    public class MaxHttpCollectionKeyTypeController : ApiController\n    {\n        // Post strongly typed Customer\n        public string PostCustomer(Customer a)\n        {\n            if (!ModelState.IsValid)\n            {\n                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.BadRequest);\n                ModelBinding.ModelState value = null;\n                ModelState.TryGetValue(\"a\", out value);\n                response.Content = new StringContent(value.Errors[0].Exception.Message);\n                throw new HttpResponseException(response);\n            }\n\n            return \"success from PostCustomer\";\n        }\n\n        // Post form data\n        public string PostFormData(FormDataCollection a)\n        {\n            if (!ModelState.IsValid)\n            {\n                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));\n            }\n\n            try\n            {\n                NameValueCollection collection = a.ReadAsNameValueCollection();\n            }\n            catch (InvalidOperationException ex)\n            {\n                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.BadRequest);\n                response.Content = new StringContent(ex.Message);\n                throw new HttpResponseException(response);\n            }\n\n            return \"success from PostFormData\";\n        }\n\n        public string PostCustomerFromUri([FromUri]Customer a)\n        {\n            if (!ModelState.IsValid)\n            {\n                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.BadRequest);\n                ModelBinding.ModelState value = null;\n                ModelState.TryGetValue(\"a\", out value);\n                response.Content = new StringContent(value.Errors[0].ErrorMessage);\n                throw new HttpResponseException(response);\n            }\n\n            return \"success from PostCustomerFromUri\";\n        }\n\n        public IQueryable<string> GetWithQueryable()\n        {\n            return new List<string>() { \"success from GetWithQueryable\" }.AsQueryable();\n        }\n\n        public string PostJToken(JToken token)\n        {\n            if (!ModelState.IsValid)\n            {\n                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));\n            }\n\n            return \"success from PostJToken\";\n        }\n    }\n\n    public class Customer\n    {\n        public string Name { get; set; }\n        public int Age { get; set; }\n\n        public override string ToString()\n        {\n            return \"ModelBindingItem(\" + Name + \",\" + Age + \")\";\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.SelfHost.Test/SelfHostHttpRequestContextTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Diagnostics.Contracts;\nusing System.IdentityModel.Claims;\nusing System.IdentityModel.Policy;\nusing System.Net;\nusing System.Net.Http;\nusing System.Security.Cryptography.X509Certificates;\nusing System.Security.Principal;\nusing System.ServiceModel;\nusing System.ServiceModel.Channels;\nusing System.ServiceModel.Security;\nusing System.Threading;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.SelfHost\n{\n    public class SelfHostHttpRequestContextTests\n    {\n        [Fact]\n        public void RequestContextGet_ReturnsProvidedInstance()\n        {\n            // Arrange\n            using (RequestContext expectedServiceModelContext = CreateStubServiceModelContext())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                SelfHostHttpRequestContext context = CreateProductUnderTest(expectedServiceModelContext, configuration,\n                    request);\n\n                // Act\n                RequestContext serviceModelContext = context.RequestContext;\n\n                // Assert\n                Assert.Same(expectedServiceModelContext, serviceModelContext);\n            }\n        }\n\n        [Fact]\n        public void RequestGet_ReturnsProvidedInstance()\n        {\n            // Arrange\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                SelfHostHttpRequestContext context = CreateProductUnderTest(serviceModelContext, configuration,\n                    expectedRequest);\n\n                // Act\n                HttpRequestMessage request = context.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public void ClientCertificateGet_ReturnsNull_ByDefault()\n        {\n            // Arrange\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(serviceModelContext, configuration, request);\n\n                // Act\n                X509Certificate2 certificate = context.ClientCertificate;\n\n                // Assert\n                Assert.Null(certificate);\n            }\n        }\n\n        [Fact]\n        public void ClientCertificateGet_ReturnsContextClientCertificate()\n        {\n            // Arrange\n            X509Certificate2 expectedCertificate = CreateCertificate();\n\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(serviceModelContext, configuration, request);\n\n                request.Properties[HttpSelfHostServer.SecurityKey] = CreateSecurityProperty(expectedCertificate);\n\n                // Act\n                X509Certificate2 certificate = context.ClientCertificate;\n\n                // Assert\n                // WCF clones the certificate instance, so NotNull is the best we can check without creating a real\n                // certificate.\n                Assert.NotNull(certificate);\n            }\n        }\n\n        [Fact]\n        public void ClientCertificateSet_UpdatesClientCertificate()\n        {\n            // Arrange\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(serviceModelContext, configuration, request);\n                X509Certificate2 expectedCertificate = CreateCertificate();\n\n                // Act\n                context.ClientCertificate = expectedCertificate;\n\n                // Assert\n                X509Certificate2 certificate = context.ClientCertificate;\n                Assert.Same(expectedCertificate, certificate);\n            }\n        }\n\n        [Fact]\n        public void ClientCertificateSet_UpdatesClientCertificate_WhenNull()\n        {\n            // Arrange\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(serviceModelContext, configuration, request);\n\n                request.Properties[HttpSelfHostServer.SecurityKey] = CreateSecurityProperty(CreateCertificate());\n\n                // Act\n                context.ClientCertificate = null;\n\n                // Assert\n                X509Certificate2 certificate = context.ClientCertificate;\n                Assert.Null(certificate);\n            }\n        }\n\n        [Fact]\n        public void ConfigurationGet_ReturnsProvidedInstance()\n        {\n            // Arrange\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext())\n            using (HttpConfiguration expectedConfiguration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(serviceModelContext, expectedConfiguration,\n                    request);\n\n                // Act\n                HttpConfiguration configuration = context.Configuration;\n\n                // Assert\n                Assert.Same(expectedConfiguration, configuration);\n            }\n        }\n\n        [Fact]\n        public void ConfigurationSet_UpdatesConfiguration()\n        {\n            // Arrange\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext())\n            using (HttpConfiguration initialConfiguration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            using (HttpConfiguration expectedConfiguration = CreateConfiguration())\n            {\n                HttpRequestContext context = CreateProductUnderTest(serviceModelContext, initialConfiguration,\n                    request);\n\n                // Act\n                context.Configuration = expectedConfiguration;\n\n                // Assert\n                HttpConfiguration configuration = context.Configuration;\n                Assert.Same(expectedConfiguration, configuration);\n            }\n        }\n\n        [Fact]\n        public void IncludeErrorDetailGet_ReturnsFalse_ByDefault()\n        {\n            // Arrange\n            using (Message message = CreateMessage())\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext(message))\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(serviceModelContext, configuration, request);\n                context.Configuration = null;\n\n                // Act\n                bool includeErrorDetail = context.IncludeErrorDetail;\n\n                // Assert\n                Assert.False(includeErrorDetail);\n            }\n        }\n\n        [Fact]\n        public void IncludeErrorDetailGet_ReturnsTrue_WhenUnconfiguredAndIsLocal()\n        {\n            // Arrange\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(serviceModelContext, configuration, request);\n                context.Configuration = null;\n                context.IsLocal = true;\n\n                // Act\n                bool includeErrorDetail = context.IncludeErrorDetail;\n\n                // Assert\n                Assert.True(includeErrorDetail);\n            }\n        }\n\n        [Theory]\n        [InlineData(true, IncludeErrorDetailPolicy.Always, true)]\n        [InlineData(true, IncludeErrorDetailPolicy.Always, false)]\n        [InlineData(false, IncludeErrorDetailPolicy.Never, true)]\n        [InlineData(false, IncludeErrorDetailPolicy.Never, false)]\n        [InlineData(true, IncludeErrorDetailPolicy.LocalOnly, true)]\n        [InlineData(false, IncludeErrorDetailPolicy.LocalOnly, false)]\n        [InlineData(true, IncludeErrorDetailPolicy.Default, true)]\n        [InlineData(false, IncludeErrorDetailPolicy.Default, false)]\n        public void IncludeErrorDetailGet_ForPolicy(bool expected, IncludeErrorDetailPolicy policy, bool isLocal)\n        {\n            // Arrange\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(serviceModelContext, configuration, request);\n                context.IsLocal = isLocal;\n                configuration.IncludeErrorDetailPolicy = policy;\n\n                // Act\n                bool includeErrorDetail = context.IncludeErrorDetail;\n\n                // Assert\n                Assert.Equal(expected, includeErrorDetail);\n            }\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void IncludeErrorDetailSet_UpdatesIncludeErrorDetail(bool expectedIncludeErrorDetail)\n        {\n            // Arrange\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(serviceModelContext, configuration, request);\n\n                // Act\n                context.IncludeErrorDetail = expectedIncludeErrorDetail;\n\n                // Assert\n                bool includeErrorDetail = context.IncludeErrorDetail;\n                Assert.Equal(expectedIncludeErrorDetail, includeErrorDetail);\n            }\n        }\n\n        [Theory]\n        [InlineData(true, IncludeErrorDetailPolicy.Never)]\n        [InlineData(false, IncludeErrorDetailPolicy.Always)]\n        public void IncludeErrorDetailSet_OverridesPolicy(bool expected, IncludeErrorDetailPolicy policy)\n        {\n            // Arrange\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(serviceModelContext, configuration, request);\n                configuration.IncludeErrorDetailPolicy = policy;\n\n                // Act\n                context.IncludeErrorDetail = expected;\n\n                // Assert\n                bool includeErrorDetail = context.IncludeErrorDetail;\n                Assert.Equal(expected, includeErrorDetail);\n            }\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void IncludeErrorDetailGet_ReturnsFirstObservedValue(bool expectedIncludeErrorDetail)\n        {\n            // Arrange\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(serviceModelContext, configuration, request);\n                context.IsLocal = expectedIncludeErrorDetail;\n                bool ignore = context.IncludeErrorDetail;\n                context.IsLocal = !expectedIncludeErrorDetail;\n\n                // Act\n                bool includeErrorDetail = context.IncludeErrorDetail;\n\n                // Assert\n                Assert.Equal(expectedIncludeErrorDetail, includeErrorDetail);\n            }\n        }\n\n        [Fact]\n        public void IsLocalGet_ReturnsFalse_ByDefault()\n        {\n            // Arrange\n            using (Message message = CreateMessage())\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext(message))\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(serviceModelContext, configuration, request);\n\n                // Act\n                bool isLocal = context.IsLocal;\n\n                // Assert\n                Assert.False(isLocal);\n            }\n        }\n\n        [Theory]\n        [InlineData(false)]\n        [InlineData(true)]\n        public void IsLocal_ReturnsContextIsLocalValue(bool expectedIsLocal)\n        {\n            // Arrange\n            using (Message message = CreateMessage(expectedIsLocal))\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext(message))\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(serviceModelContext, configuration, request);\n\n                // Act\n                bool isLocal = context.IsLocal;\n\n                // Assert\n                Assert.Equal(expectedIsLocal, isLocal);\n            }\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void IsLocalSet_UpdatesIsLocal(bool expectedIsLocal)\n        {\n            // Arrange\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(serviceModelContext, configuration, request);\n\n                // Act\n                context.IsLocal = expectedIsLocal;\n\n                // Assert\n                bool isLocal = context.IsLocal;\n                Assert.Equal(expectedIsLocal, isLocal);\n            }\n        }\n\n        [Theory]\n        [InlineData(false)]\n        [InlineData(true)]\n        public void IsLocalGet_ReturnsFirstObservedValue(bool expectedIsLocal)\n        {\n            // Arrange\n            using (Message message = CreateMessage(expectedIsLocal))\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext(message))\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(serviceModelContext, configuration, request);\n                bool ignore = context.IsLocal;\n                SetIsLocal(message, !expectedIsLocal);\n\n                // Act\n                bool isLocal = context.IsLocal;\n\n                // Assert\n                Assert.Equal(expectedIsLocal, isLocal);\n            }\n        }\n\n        [Fact]\n        [RestoreThreadPrincipal]\n        public void PrincipalGet_ReturnsThreadCurrentPrincipal()\n        {\n            // Arrange\n            IPrincipal expectedPrincipal = CreateDummyPrincipal();\n\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(serviceModelContext, configuration, request);\n                Thread.CurrentPrincipal = expectedPrincipal;\n\n                // Act\n                IPrincipal principal = context.Principal;\n\n                // Assert\n                Assert.Same(expectedPrincipal, principal);\n            }\n        }\n\n        [Fact]\n        [RestoreThreadPrincipal]\n        public void PrincipalSet_UpdatesThreadCurrentPrincipal()\n        {\n            // Arrange\n            IPrincipal expectedPrincipal = CreateDummyPrincipal();\n\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(serviceModelContext, configuration, request);\n\n                // Act\n                context.Principal = expectedPrincipal;\n\n                // Assert\n                IPrincipal principal = Thread.CurrentPrincipal;\n                Assert.Same(expectedPrincipal, principal);\n            }\n        }\n\n        [Fact]\n        public void UrlGet_ReturnsUrlHelperForRequest()\n        {\n            // Arrange\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(serviceModelContext, configuration, expectedRequest);\n\n                // Act\n                UrlHelper url = context.Url;\n\n                // Assert\n                Assert.NotNull(url);\n                Assert.Same(expectedRequest, url.Request);\n            }\n        }\n\n        [Fact]\n        public void UrlGet_ReturnsSameInstance()\n        {\n            // Arrange\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(serviceModelContext, configuration, request);\n                UrlHelper firstUrl = context.Url;\n\n                // Act\n                UrlHelper url = context.Url;\n\n                // Assert\n                Assert.Same(firstUrl, url);\n            }\n        }\n\n        [Fact]\n        public void UrlSet_UpdatesUrl()\n        {\n            // Arrange\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(serviceModelContext, configuration, request);\n                UrlHelper expectedUrl = CreateDummyUrlHelper();\n\n                // Act\n                context.Url = expectedUrl;\n\n                // Assert\n                UrlHelper url = context.Url;\n                Assert.Same(expectedUrl, url);\n            }\n        }\n\n        [Fact]\n        public void UrlSet_UpdatesUrl_WhenNull()\n        {\n            // Arrange\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(serviceModelContext, configuration, request);\n\n                // Act\n                context.Url = null;\n\n                // Assert\n                UrlHelper url = context.Url;\n                Assert.Null(url);\n            }\n        }\n\n        [Fact]\n        public void VirtualPathRootGet_ReturnsSlash_ByDefault()\n        {\n            // Arrange\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(serviceModelContext, configuration, request);\n\n                // Act\n                string virtualPathRoot = context.VirtualPathRoot;\n\n                // Assert\n                Assert.Equal(\"/\", virtualPathRoot);\n            }\n        }\n\n        [Fact]\n        public void VirtualPathRootGet_ReturnsSlash_WhenConfigurationIsNull()\n        {\n            // Arrange\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(serviceModelContext, configuration, request);\n                context.Configuration = null;\n\n                // Act\n                string virtualPathRoot = context.VirtualPathRoot;\n\n                // Assert\n                Assert.Equal(\"/\", virtualPathRoot);\n            }\n        }\n\n        [Fact]\n        public void VirtualPathRootGet_ReturnsConfigurationVirtualPathRoot()\n        {\n            // Arrange\n            string expectedVirtualPathRoot = \"/foo\";\n\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext())\n            using (HttpConfiguration configuration = CreateConfiguration(expectedVirtualPathRoot))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(serviceModelContext, configuration, request);\n\n                // Act\n                string virtualPathRoot = context.VirtualPathRoot;\n\n                // Assert\n                Assert.Equal(expectedVirtualPathRoot, virtualPathRoot);\n            }\n        }\n\n        [Theory]\n        [InlineData(\"a b\")]\n        [InlineData(\"/a b\")]\n        [InlineData(\"/a%20b\")]\n        public void VirtualPathRootGet_ReturnsUnescapedConfigurationVirtualPathRoot(string configurationVirtualPathRoot)\n        {\n            // Arrange\n            var expectedVirtualPathRoot = \"/a b\";\n            using (var serviceModelContext = CreateStubServiceModelContext())\n            using (var configuration = CreateConfiguration(configurationVirtualPathRoot))\n            using (var request = CreateRequest())\n            {\n                var context = CreateProductUnderTest(serviceModelContext, configuration, request);\n\n                // Act\n                var virtualPathRoot = context.VirtualPathRoot;\n\n                // Assert\n                Assert.Equal(expectedVirtualPathRoot, virtualPathRoot);\n            }\n        }\n\n        [Fact]\n        public void VirtualPathRootSet_UpdatesVirtualPathRoot()\n        {\n            // Arrange\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(serviceModelContext, configuration, request);\n                string expectedVirtualPathRoot = \"foo\";\n\n                // Act\n                context.VirtualPathRoot = expectedVirtualPathRoot;\n\n                // Assert\n                string virtualPathRoot = context.VirtualPathRoot;\n                Assert.Same(expectedVirtualPathRoot, virtualPathRoot);\n            }\n        }\n\n        [Fact]\n        public void VirtualPathRootSet_UpdatesVirtualPathRoot_WhenNull()\n        {\n            // Arrange\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(serviceModelContext, configuration, request);\n\n                // Act\n                context.VirtualPathRoot = null;\n\n                // Assert\n                string virtualPathRoot = context.VirtualPathRoot;\n                Assert.Null(virtualPathRoot);\n            }\n        }\n\n        [Fact]\n        public void VirtualPathRootGet_ReturnsFirstObservedConfigurationVirtualPathRoot()\n        {\n            // Arrange\n            string expectedVirtualPathRoot = \"/expected\";\n            using (RequestContext serviceModelContext = CreateStubServiceModelContext())\n            using (HttpConfiguration configuration = CreateConfiguration(expectedVirtualPathRoot))\n            using (HttpRequestMessage request = CreateRequest())\n            using (HttpConfiguration otherConfiguration = CreateConfiguration(\"/other\"))\n            {\n                HttpRequestContext context = CreateProductUnderTest(serviceModelContext, configuration, request);\n                string ignore = context.VirtualPathRoot;\n                context.Configuration = otherConfiguration;\n\n                // Act\n                string virtualPathRoot = context.VirtualPathRoot;\n\n                // Assert\n                Assert.Equal(expectedVirtualPathRoot, virtualPathRoot);\n            }\n        }\n\n        private static X509Certificate2 CreateCertificate()\n        {\n            return new X509Certificate2();\n        }\n\n        private static HttpConfiguration CreateConfiguration()\n        {\n            return new HttpConfiguration();\n        }\n\n        private static HttpConfiguration CreateConfiguration(string virtualPathRoot)\n        {\n            return new HttpConfiguration(new HttpRouteCollection(virtualPathRoot));\n        }\n\n        private static IPrincipal CreateDummyPrincipal()\n        {\n            return new Mock<IPrincipal>(MockBehavior.Strict).Object;\n        }\n\n        private static UrlHelper CreateDummyUrlHelper()\n        {\n            return new Mock<UrlHelper>(MockBehavior.Strict).Object;\n        }\n\n        private static Message CreateMessage()\n        {\n            return Message.CreateMessage(MessageVersion.None, null);\n        }\n\n        private static Message CreateMessage(bool isLocal)\n        {\n            Message message = CreateMessage();\n            SetIsLocal(message, isLocal);\n            return message;\n        }\n\n        private static SelfHostHttpRequestContext CreateProductUnderTest(RequestContext requestContext,\n            HttpConfiguration configuration, HttpRequestMessage request)\n        {\n            return new SelfHostHttpRequestContext(requestContext, configuration, request);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private static SecurityMessageProperty CreateSecurityProperty(X509Certificate2 certificate)\n        {\n            AuthorizationContext authorizationContext = new X509AuthorizationContext(certificate);\n            ServiceSecurityContext securityContext = new ServiceSecurityContext(authorizationContext);\n            SecurityMessageProperty securityProperty = new SecurityMessageProperty();\n            securityProperty.ServiceSecurityContext = securityContext;\n            return securityProperty;\n        }\n\n        private static Mock<RequestContext> CreateServiceModelContextMock()\n        {\n            Mock<RequestContext> mock = new Mock<RequestContext>(MockBehavior.Strict);\n            mock.As<IDisposable>().Setup(c => c.Dispose());\n            return mock;\n        }\n\n        private static RequestContext CreateStubServiceModelContext()\n        {\n            return CreateServiceModelContextMock().Object;\n        }\n\n        private static RequestContext CreateStubServiceModelContext(Message requestMessage)\n        {\n            Mock<RequestContext> mock = CreateServiceModelContextMock();\n            mock.Setup(c => c.RequestMessage).Returns(requestMessage);\n            return mock.Object;\n        }\n\n        private static void SetIsLocal(Message message, bool value)\n        {\n            IPAddress address = value ? IPAddress.Loopback : IPAddress.None;\n            message.Properties[RemoteEndpointMessageProperty.Name] = new RemoteEndpointMessageProperty(\n                address.ToString(), 0);\n        }\n\n        private class X509AuthorizationContext : AuthorizationContext\n        {\n            private readonly ReadOnlyCollection<ClaimSet> _claimSets;\n\n            public X509AuthorizationContext(X509Certificate2 certificate)\n            {\n                Contract.Assert(certificate != null);\n                _claimSets = new ReadOnlyCollection<ClaimSet>(new List<ClaimSet>(new ClaimSet[] {\n                    new X509CertificateClaimSet(certificate) }));\n            }\n\n            public override ReadOnlyCollection<ClaimSet> ClaimSets\n            {\n                get { return _claimSets; }\n            }\n\n            public override DateTime ExpirationTime\n            {\n                get { throw new NotImplementedException(); }\n            }\n\n            public override string Id\n            {\n                get { throw new NotImplementedException(); }\n            }\n\n            public override IDictionary<string, object> Properties\n            {\n                get { throw new NotImplementedException(); }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.SelfHost.Test/ServiceModel/HostNameComparisonModeHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ServiceModel;\nusing System.Web.Http.SelfHost.ServiceModel;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Formatting\n{\n    public class HostNameComparisonModeHelperTest : EnumHelperTestBase<HostNameComparisonMode>\n    {\n        public HostNameComparisonModeHelperTest()\n            : base(HostNameComparisonModeHelper.IsDefined, HostNameComparisonModeHelper.Validate, (HostNameComparisonMode)999)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.SelfHost.Test/ServiceModel/TransferModeHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ServiceModel;\nusing System.Web.Http.SelfHost.ServiceModel;\nusing Microsoft.TestCommon;\n\nnamespace System.Net.Http.Formatting\n{\n    public class TransferModeHelperTest : EnumHelperTestBase<TransferMode>\n    {\n        public TransferModeHelperTest()\n            : base(TransferModeHelper.IsDefined, TransferModeHelper.Validate, (TransferMode)999)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.SelfHost.Test/System.Web.Http.SelfHost.Test.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props\" Condition=\"Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" />\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" />\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{7F29EE87-6A63-43C6-B7FF-74DD06815830}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>System.Web.Http.SelfHost</RootNamespace>\n    <AssemblyName>System.Web.Http.SelfHost.Test</AssemblyName>\n    <OutputPath>..\\..\\bin\\$(Configuration)\\Test\\</OutputPath>\n    <NuGetPackageImportStamp>\n    </NuGetPackageImportStamp>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Castle.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Castle.Core.5.1.1\\lib\\net462\\Castle.Core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Moq, Version=4.18.0.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Moq.4.18.4\\lib\\net462\\Moq.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Newtonsoft.Json.13.0.1\\lib\\net45\\Newtonsoft.Json.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.IdentityModel\" />\n    <Reference Include=\"System.Net.Http\" />\n    <Reference Include=\"System.Net.Http.WebRequest\" />\n    <Reference Include=\"System.ServiceModel\" />\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"System.XML\" />\n    <Reference Include=\"System.Xml.Linq\" />\n    <Reference Include=\"xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.abstractions.2.0.3\\lib\\net35\\xunit.abstractions.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.assert, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.assert.2.4.2\\lib\\netstandard1.1\\xunit.assert.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.core, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.core.2.4.2\\lib\\net452\\xunit.core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.execution.desktop, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.execution.2.4.2\\lib\\net452\\xunit.execution.desktop.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\Common\\HttpMethodHelperTest.cs\">\n      <Link>Common\\HttpMethodHelperTest.cs</Link>\n    </Compile>\n    <Compile Include=\"Authentication\\BasicOverHttpTest.cs\" />\n    <Compile Include=\"Authentication\\CustomMessageHandler.cs\" />\n    <Compile Include=\"Authentication\\CustomUsernamePasswordValidator.cs\" />\n    <Compile Include=\"Authentication\\RequireAdminAttribute.cs\" />\n    <Compile Include=\"Authentication\\SampleController.cs\" />\n    <Compile Include=\"Channels\\HttpBindingSecurityModeHelperTest.cs\" />\n    <Compile Include=\"DeeplyNestedTypeTests.cs\" />\n    <Compile Include=\"HttpSelfHostConfigurationTest.cs\" />\n    <Compile Include=\"HttpSelfHostServerTest.cs\" />\n    <Compile Include=\"MaxHttpCollectionKeyTests.cs\" />\n    <Compile Include=\"HttpSelfHostResponseTest.cs\" />\n    <Compile Include=\"SelfHostHttpRequestContextTests.cs\" />\n    <Compile Include=\"ServiceModel\\TransferModeHelperTest.cs\" />\n    <Compile Include=\"ServiceModel\\HostNameComparisonModeHelperTest.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\..\\src\\System.Net.Http.Formatting\\System.Net.Http.Formatting.csproj\">\n      <Project>{668E9021-CE84-49D9-98FB-DF125A9FCDB0}</Project>\n      <Name>System.Net.Http.Formatting</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Http.SelfHost\\System.Web.Http.SelfHost.csproj\">\n      <Project>{66492E69-CE4C-4FB1-9B1F-88DEE09D06F1}</Project>\n      <Name>System.Web.Http.SelfHost</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Http\\System.Web.Http.csproj\">\n      <Project>{DDC1CE0C-486E-4E35-BB3B-EAB61F8F9440}</Project>\n      <Name>System.Web.Http</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Mvc\\System.Web.Mvc.csproj\">\n      <Project>{3D3FFD8A-624D-4E9B-954B-E1C105507975}</Project>\n      <Name>System.Web.Mvc</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\">\n      <Project>{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}</Project>\n      <Name>Microsoft.TestCommon</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <Service Include=\"{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Analyzer Include=\"..\\..\\packages\\xunit.analyzers.1.1.0\\analyzers\\dotnet\\cs\\xunit.analyzers.dll\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  <Target Name=\"EnsureNuGetPackageBuildImports\" BeforeTargets=\"PrepareForBuild\">\n    <PropertyGroup>\n      <ErrorText>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}.</ErrorText>\n    </PropertyGroup>\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props'))\" />\n  </Target>\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" />\n</Project>"
  },
  {
    "path": "test/System.Web.Http.SelfHost.Test/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Castle.Core\" version=\"5.1.1\" targetFramework=\"net462\" />\n  <package id=\"Moq\" version=\"4.18.4\" targetFramework=\"net462\" />\n  <package id=\"Newtonsoft.Json\" version=\"13.0.1\" targetFramework=\"net462\" />\n  <package id=\"xunit\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.abstractions\" version=\"2.0.3\" targetFramework=\"net462\" />\n  <package id=\"xunit.analyzers\" version=\"1.1.0\" targetFramework=\"net462\" />\n  <package id=\"xunit.assert\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.execution\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.runner.visualstudio\" version=\"2.4.5\" targetFramework=\"net462\" developmentDependency=\"true\" />\n</packages>"
  },
  {
    "path": "test/System.Web.Http.SignalR.Test/HubControllerBaseTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.AspNet.SignalR;\nusing Microsoft.AspNet.SignalR.Hubs;\nusing Microsoft.AspNet.SignalR.Infrastructure;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http\n{\n    public class HubControllerBaseTest\n    {\n        [Fact]\n        public void Clients_ThrowsInvalidOperationForNullHubContext()\n        {\n            Assert.Throws<InvalidOperationException>(\n                () => new HubContextController(null).Clients,\n                \"No hub context could be found for the HubController of type 'HubContextController'.\");\n        }\n\n        [Fact]\n        public void Clients_ReturnsHubContextsClients()\n        {\n            Mock<IHubContext> mockContext = new Mock<IHubContext>();\n            IHubConnectionContext clients = new HubConnectionContext();\n            mockContext.Setup(mock => mock.Clients).Returns(clients);\n            var controller = new HubContextController(mockContext.Object);\n\n            Assert.Same(clients, controller.Clients);\n        }\n\n        [Fact]\n        public void Groups_ThrowsInvalidOperationForNullHubContext()\n        {\n            Assert.Throws<InvalidOperationException>(\n                () => new HubContextController(null).Groups,\n                \"No hub context could be found for the HubController of type 'HubContextController'.\");\n        }\n\n        [Fact]\n        public void Groups_ReturnsHubContextsClients()\n        {\n            Mock<IHubContext> mockContext = new Mock<IHubContext>();\n            IGroupManager groups = new Mock<IGroupManager>().Object;\n            mockContext.Setup(mock => mock.Groups).Returns(groups);\n            var controller = new HubContextController(mockContext.Object);\n\n            Assert.Same(groups, controller.Groups);\n        }\n\n        [Fact]\n        public void ConnectionManager_ReturnsGlobalConnectionManager_IfConfigurationIsNull()\n        {\n            HubContextController controller = new HubContextController();\n\n            Assert.Same(GlobalHost.ConnectionManager, controller.GetConnectionManager());\n        }\n\n        [Fact]\n        public void ConnectionManager_ReturnsGlobalConnectionManager_IfCannotResolveIConnectionManager()\n        {\n            HubContextController controller = new HubContextController();\n            controller.Configuration = new HttpConfiguration();\n            Mock<System.Web.Http.Dependencies.IDependencyResolver> mockDependencyResolver = new Mock<Dependencies.IDependencyResolver>();\n            mockDependencyResolver.Setup(mock => mock.GetService(typeof(IConnectionManager))).Returns(null);\n            controller.Configuration.DependencyResolver = mockDependencyResolver.Object;\n\n            Assert.Same(GlobalHost.ConnectionManager, controller.GetConnectionManager());\n        }\n\n        [Fact]\n        public void ConnectionManager_ReturnsConnectionManagerFromDependencyResolver_IfFound()\n        {\n            HubContextController controller = new HubContextController();\n            controller.Configuration = new HttpConfiguration();\n            IConnectionManager connectionManager = new Mock<IConnectionManager>().Object;\n            Mock<System.Web.Http.Dependencies.IDependencyResolver> mockDependencyResolver = new Mock<Dependencies.IDependencyResolver>();\n            mockDependencyResolver.Setup(mock => mock.GetService(typeof(IConnectionManager))).Returns(connectionManager);\n            controller.Configuration.DependencyResolver = mockDependencyResolver.Object;\n\n            Assert.Same(connectionManager, controller.GetConnectionManager());\n        }\n\n        public class HubContextController : HubControllerBase\n        {\n            IHubContext _hubContext;\n\n            public HubContextController(IHubContext hubContext = null)\n            {\n                _hubContext = hubContext;\n            }\n\n            protected override IHubContext HubContext\n            {\n                get\n                {\n                    return _hubContext;\n                }\n            }\n\n            public IConnectionManager GetConnectionManager()\n            {\n                return ConnectionManager;\n            }\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.SignalR.Test/HubControllerOfTHubTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http;\nusing Microsoft.AspNet.SignalR;\nusing Microsoft.AspNet.SignalR.Infrastructure;\nusing Microsoft.TestCommon;\nusing Moq;\n\npublic class HubControllerOfTTest\n{\n    [Fact]\n    public void HubContext_ReturnsContextResolvedFromConnectionManager()\n    {\n        DefaultContextController controller = new DefaultContextController();\n        controller.Configuration = new HttpConfiguration();\n        Mock<IConnectionManager> mockConnectionManager = new Mock<IConnectionManager>();\n        IHubContext context = new Mock<IHubContext>().Object;\n        mockConnectionManager.Setup(mock => mock.GetHubContext<MyHub>()).Returns(context);\n        Mock<System.Web.Http.Dependencies.IDependencyResolver> mockDependencyResolver = new Mock<System.Web.Http.Dependencies.IDependencyResolver>();\n        mockDependencyResolver.Setup(mock => mock.GetService(typeof(IConnectionManager))).Returns(mockConnectionManager.Object);\n        controller.Configuration.DependencyResolver = mockDependencyResolver.Object;\n\n        Assert.Same(context, controller.GetHubContext());\n    }\n\n    public class DefaultContextController : HubController<MyHub>\n    {\n        public IHubContext GetHubContext()\n        {\n            return HubContext;\n        }\n\n        public IConnectionManager GetConnectionManager()\n        {\n            return ConnectionManager;\n        }\n    }\n\n    public class MyHub : Hub\n    {\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.SignalR.Test/HubControllerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.AspNet.SignalR;\nusing Microsoft.AspNet.SignalR.Infrastructure;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http\n{\n    public class HubControllerTest\n    {\n        [Fact]\n        public void Constructor_ThrowsArgumentNullForNullHubName()\n        {\n            Assert.ThrowsArgumentNull(() => new NullHubNameController(), \"hubName\");\n        }\n\n        [Fact]\n        public void HubContext_ReturnsContextResolvedFromConnectionManager()\n        {\n            DefaultContextController controller = new DefaultContextController(\"hub\");\n            controller.Configuration = new HttpConfiguration();\n            Mock<IConnectionManager> mockConnectionManager = new Mock<IConnectionManager>();\n            IHubContext context = new Mock<IHubContext>().Object;\n            mockConnectionManager.Setup(mock => mock.GetHubContext(\"hub\")).Returns(context);\n            Mock<System.Web.Http.Dependencies.IDependencyResolver> mockDependencyResolver = new Mock<Dependencies.IDependencyResolver>();\n            mockDependencyResolver.Setup(mock => mock.GetService(typeof(IConnectionManager))).Returns(mockConnectionManager.Object);\n            controller.Configuration.DependencyResolver = mockDependencyResolver.Object;\n\n            Assert.Same(context, controller.GetHubContext());\n        }\n\n        public class NullHubNameController : HubController\n        {\n            public NullHubNameController() : base(null)\n            {\n            }\n        }\n\n        public class DefaultContextController : HubController\n        {\n            public DefaultContextController(string hubName) : base(hubName)\n            {\n            }\n\n            public IHubContext GetHubContext()\n            {\n                return HubContext;\n            }\n\n            public IConnectionManager GetConnectionManager()\n            {\n                return ConnectionManager;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.SignalR.Test/System.Web.Http.SignalR.Test.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props\" Condition=\"Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" />\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" />\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{E22245AF-D5E1-46F6-B443-C886983EC50C}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <RootNamespace>System.Web.Http</RootNamespace>\n    <AssemblyName>System.Web.Http.SignalR.Test</AssemblyName>\n    <OutputPath>..\\..\\bin\\$(Configuration)\\Test\\</OutputPath>\n    <NuGetPackageImportStamp>\n    </NuGetPackageImportStamp>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Castle.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Castle.Core.5.1.1\\lib\\net462\\Castle.Core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Microsoft.AspNet.SignalR.Core\">\n      <HintPath>..\\..\\packages\\Microsoft.AspNet.SignalR.Core.1.0.0\\lib\\net40\\Microsoft.AspNet.SignalR.Core.dll</HintPath>\n    </Reference>\n    <Reference Include=\"Moq, Version=4.18.0.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Moq.4.18.4\\lib\\net462\\Moq.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Newtonsoft.Json.13.0.1\\lib\\net45\\Newtonsoft.Json.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Net.Http\" />\n    <Reference Include=\"System.Net.Http.WebRequest\" />\n    <Reference Include=\"System.Xml\" />\n    <Reference Include=\"xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.abstractions.2.0.3\\lib\\net35\\xunit.abstractions.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.assert, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.assert.2.4.2\\lib\\netstandard1.1\\xunit.assert.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.core, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.core.2.4.2\\lib\\net452\\xunit.core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.execution.desktop, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.execution.2.4.2\\lib\\net452\\xunit.execution.desktop.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\..\\src\\System.Net.Http.Formatting\\System.Net.Http.Formatting.csproj\">\n      <Project>{668e9021-ce84-49d9-98fb-df125a9fcdb0}</Project>\n      <Name>System.Net.Http.Formatting</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Http.SignalR\\System.Web.Http.SignalR.csproj\">\n      <Project>{8a607ac9-e7dd-4b74-a0b1-47fc95b9838b}</Project>\n      <Name>System.Web.Http.SignalR</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Http\\System.Web.Http.csproj\">\n      <Project>{ddc1ce0c-486e-4e35-bb3b-eab61f8f9440}</Project>\n      <Name>System.Web.Http</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\">\n      <Project>{fccc4cb7-baf7-4a57-9f89-e5766fe536c0}</Project>\n      <Name>Microsoft.TestCommon</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"HubControllerBaseTest.cs\" />\n    <Compile Include=\"HubControllerOfTHubTest.cs\" />\n    <Compile Include=\"HubControllerTest.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Service Include=\"{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Analyzer Include=\"..\\..\\packages\\xunit.analyzers.1.1.0\\analyzers\\dotnet\\cs\\xunit.analyzers.dll\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  <Target Name=\"EnsureNuGetPackageBuildImports\" BeforeTargets=\"PrepareForBuild\">\n    <PropertyGroup>\n      <ErrorText>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}.</ErrorText>\n    </PropertyGroup>\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props'))\" />\n  </Target>\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" />\n</Project>"
  },
  {
    "path": "test/System.Web.Http.SignalR.Test/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Castle.Core\" version=\"5.1.1\" targetFramework=\"net462\" />\n  <package id=\"Microsoft.AspNet.SignalR.Core\" version=\"1.0.0\" targetFramework=\"net462\" />\n  <package id=\"Moq\" version=\"4.18.4\" targetFramework=\"net462\" />\n  <package id=\"Newtonsoft.Json\" version=\"13.0.1\" targetFramework=\"net462\" />\n  <package id=\"xunit\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.abstractions\" version=\"2.0.3\" targetFramework=\"net462\" />\n  <package id=\"xunit.analyzers\" version=\"1.1.0\" targetFramework=\"net462\" />\n  <package id=\"xunit.assert\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.execution\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.runner.visualstudio\" version=\"2.4.5\" targetFramework=\"net462\" developmentDependency=\"true\" />\n</packages>"
  },
  {
    "path": "test/System.Web.Http.Test/AuthorizeAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Http;\nusing System.Security.Principal;\nusing System.Web.Http.Controllers;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http\n{\n    public class AuthorizeAttributeTest\n    {\n        private readonly Mock<HttpActionDescriptor> _actionDescriptorMock = new Mock<HttpActionDescriptor>() { CallBase = true };\n        private readonly Collection<AllowAnonymousAttribute> _allowAnonymousAttributeCollection = new Collection<AllowAnonymousAttribute>(new AllowAnonymousAttribute[] { new AllowAnonymousAttribute() });\n        private readonly MockableAuthorizeAttribute _attribute;\n        private readonly Mock<MockableAuthorizeAttribute> _attributeMock = new Mock<MockableAuthorizeAttribute>() { CallBase = true };\n        private readonly Mock<HttpControllerDescriptor> _controllerDescriptorMock = new Mock<HttpControllerDescriptor>() { CallBase = true };\n        private readonly HttpControllerContext _controllerContext;\n        private readonly HttpActionContext _actionContext;\n        private readonly Mock<IPrincipal> _principalMock = new Mock<IPrincipal>();\n        private readonly HttpRequestMessage _request = new HttpRequestMessage();\n\n        public AuthorizeAttributeTest()\n        {\n            _attribute = _attributeMock.Object;\n            _controllerContext = new Mock<HttpControllerContext>() { CallBase = true }.Object;\n            _controllerDescriptorMock.Setup(cd => cd.GetCustomAttributes<AllowAnonymousAttribute>()).Returns(new Collection<AllowAnonymousAttribute>(Enumerable.Empty<AllowAnonymousAttribute>().ToList()));\n            _actionDescriptorMock.Setup(ad => ad.GetCustomAttributes<AllowAnonymousAttribute>()).Returns(new Collection<AllowAnonymousAttribute>(Enumerable.Empty<AllowAnonymousAttribute>().ToList()));\n            _controllerContext.ControllerDescriptor = _controllerDescriptorMock.Object;\n            _controllerContext.Request = _request;\n            _actionContext = ContextUtil.CreateActionContext(_controllerContext, _actionDescriptorMock.Object);\n            _controllerContext.RequestContext.Principal = _principalMock.Object;\n        }\n\n        [Fact]\n        public void Roles_Property()\n        {\n            AuthorizeAttribute attribute = new AuthorizeAttribute();\n\n            Assert.Reflection.StringProperty(attribute, a => a.Roles, expectedDefaultValue: String.Empty);\n        }\n\n        [Fact]\n        public void Users_Property()\n        {\n            AuthorizeAttribute attribute = new AuthorizeAttribute();\n\n            Assert.Reflection.StringProperty(attribute, a => a.Users, expectedDefaultValue: String.Empty);\n        }\n\n        [Fact]\n        public void AllowMultiple_ReturnsTrue()\n        {\n            Assert.True(_attribute.AllowMultiple);\n        }\n\n        [Fact]\n        public void TypeId_ReturnsUniqueInstances()\n        {\n            var attribute1 = new AuthorizeAttribute();\n            var attribute2 = new AuthorizeAttribute();\n\n            Assert.NotSame(attribute1.TypeId, attribute2.TypeId);\n        }\n\n        [Fact]\n        public void OnAuthorization_IfContextParameterIsNull_ThrowsException()\n        {\n            Assert.ThrowsArgumentNull(() =>\n            {\n                _attribute.OnAuthorization(actionContext: null);\n            }, \"actionContext\");\n        }\n\n        [Fact]\n        public void OnAuthorization_IfUserIsAuthenticated_DoesNotShortCircuitRequest()\n        {\n            _principalMock.Setup(p => p.Identity.IsAuthenticated).Returns(true);\n\n            _attribute.OnAuthorization(_actionContext);\n\n            Assert.Null(_actionContext.Response);\n        }\n\n        [Fact]\n        public void OnAuthorization_IfRequestContextDoesNotContainPrincipal_DoesShortCircuitRequest()\n        {\n            _actionContext.ControllerContext.RequestContext.Principal = null;\n\n            _attribute.OnAuthorization(_actionContext);\n\n            AssertUnauthorizedRequestSet(_actionContext);\n        }\n\n        [Fact]\n        public void OnAuthorization_IfPrincipalDoesNotContainIdentity_DoesShortCircuitRequest()\n        {\n            _principalMock.Setup(p => p.Identity).Returns((IIdentity)null);\n\n            _attribute.OnAuthorization(_actionContext);\n\n            AssertUnauthorizedRequestSet(_actionContext);\n        }\n\n        [Fact]\n        public void OnAuthorization_IfUserIsNotAuthenticated_DoesShortCircuitRequest()\n        {\n            _principalMock.Setup(p => p.Identity.IsAuthenticated).Returns(false).Verifiable();\n\n            _attribute.OnAuthorization(_actionContext);\n\n            AssertUnauthorizedRequestSet(_actionContext);\n            _principalMock.Verify();\n        }\n\n        [Fact]\n        public void OnAuthorization_IfUserIsNotInUsersCollection_DoesShortCircuitRequest()\n        {\n            _attribute.Users = \"John\";\n            _principalMock.Setup(p => p.Identity.IsAuthenticated).Returns(true).Verifiable();\n            _principalMock.Setup(p => p.Identity.Name).Returns(\"Mary\").Verifiable();\n\n            _attribute.OnAuthorization(_actionContext);\n\n            AssertUnauthorizedRequestSet(_actionContext);\n            _principalMock.Verify();\n        }\n\n        [Fact]\n        public void OnAuthorization_IfUserIsInUsersCollection_DoesNotShortCircuitRequest()\n        {\n            _attribute.Users = \" John , Mary \";\n            _principalMock.Setup(p => p.Identity.IsAuthenticated).Returns(true).Verifiable();\n            _principalMock.Setup(p => p.Identity.Name).Returns(\"Mary\").Verifiable();\n\n            _attribute.OnAuthorization(_actionContext);\n\n            Assert.Null(_actionContext.Response);\n            _principalMock.Verify();\n        }\n\n        [Fact]\n        public void OnAuthorization_IfUserIsNotInRolesCollection_DoesShortCircuitRequest()\n        {\n            _attribute.Users = \" John , Mary \";\n            _attribute.Roles = \"Administrators,PowerUsers\";\n            _principalMock.Setup(p => p.Identity.IsAuthenticated).Returns(true).Verifiable();\n            _principalMock.Setup(p => p.Identity.Name).Returns(\"Mary\").Verifiable();\n            _principalMock.Setup(p => p.IsInRole(\"Administrators\")).Returns(false).Verifiable();\n            _principalMock.Setup(p => p.IsInRole(\"PowerUsers\")).Returns(false).Verifiable();\n\n            _attribute.OnAuthorization(_actionContext);\n\n            AssertUnauthorizedRequestSet(_actionContext);\n            _principalMock.Verify();\n        }\n\n        [Fact]\n        public void OnAuthorization_IfUserIsInRolesCollection_DoesNotShortCircuitRequest()\n        {\n            _attribute.Users = \" John , Mary \";\n            _attribute.Roles = \"Administrators,PowerUsers\";\n            _principalMock.Setup(p => p.Identity.IsAuthenticated).Returns(true).Verifiable();\n            _principalMock.Setup(p => p.Identity.Name).Returns(\"Mary\").Verifiable();\n            _principalMock.Setup(p => p.IsInRole(\"Administrators\")).Returns(false).Verifiable();\n            _principalMock.Setup(p => p.IsInRole(\"PowerUsers\")).Returns(true).Verifiable();\n\n            _attribute.OnAuthorization(_actionContext);\n\n            Assert.Null(_actionContext.Response);\n            _principalMock.Verify();\n        }\n\n        [Fact]\n        public void OnAuthorization_IfActionDescriptorIsMarkedWithAllowAnonymousAttribute_DoesNotShortCircuitResponse()\n        {\n            _actionDescriptorMock.Setup(ad => ad.GetCustomAttributes<AllowAnonymousAttribute>()).Returns(_allowAnonymousAttributeCollection);\n            Mock<MockableAuthorizeAttribute> authorizeAttributeMock = new Mock<MockableAuthorizeAttribute>() { CallBase = true };\n            AuthorizeAttribute attribute = authorizeAttributeMock.Object;\n\n            attribute.OnAuthorization(_actionContext);\n\n            Assert.Null(_actionContext.Response);\n        }\n\n        [Fact]\n        public void OnAuthorization_IfControllerDescriptorIsMarkedWithAllowAnonymousAttribute_DoesNotShortCircuitResponse()\n        {\n            _controllerDescriptorMock.Setup(ad => ad.GetCustomAttributes<AllowAnonymousAttribute>()).Returns(_allowAnonymousAttributeCollection);\n            Mock<MockableAuthorizeAttribute> authorizeAttributeMock = new Mock<MockableAuthorizeAttribute>() { CallBase = true };\n            AuthorizeAttribute attribute = authorizeAttributeMock.Object;\n\n            attribute.OnAuthorization(_actionContext);\n\n            Assert.Null(_actionContext.Response);\n        }\n\n        [Fact]\n        public void OnAuthorization_IfRequestNotAuthorized_CallsHandleUnauthorizedRequest()\n        {\n            Mock<MockableAuthorizeAttribute> authorizeAttributeMock = new Mock<MockableAuthorizeAttribute>() { CallBase = true };\n            _principalMock.Setup(p => p.Identity.IsAuthenticated).Returns(false);\n            authorizeAttributeMock.Setup(a => a.HandleUnauthorizedRequestPublic(_actionContext)).Verifiable();\n            AuthorizeAttribute attribute = authorizeAttributeMock.Object;\n\n            attribute.OnAuthorization(_actionContext);\n\n            authorizeAttributeMock.Verify();\n        }\n\n        [Fact]\n        public void HandleUnauthorizedRequest_IfContextParameterIsNull_ThrowsArgumentNullException()\n        {\n            Assert.ThrowsArgumentNull(() =>\n            {\n                _attribute.HandleUnauthorizedRequestPublic(context: null);\n            }, \"actionContext\");\n        }\n\n        [Fact]\n        public void HandleUnauthorizedRequest_SetsResponseWithUnauthorizedStatusCode()\n        {\n            _attribute.HandleUnauthorizedRequestPublic(_actionContext);\n\n            Assert.NotNull(_actionContext.Response);\n            Assert.Equal(HttpStatusCode.Unauthorized, _actionContext.Response.StatusCode);\n            Assert.Same(_request, _actionContext.Response.RequestMessage);\n        }\n\n        [Theory]\n        [PropertyData(\"SplitStringTestData\")]\n        public void SplitString_SplitsOnCommaAndTrimsWhitespaceAndIgnoresEmptyStrings(string input, params string[] expectedResult)\n        {\n            string[] result = AuthorizeAttribute.SplitString(input);\n\n            Assert.Equal(expectedResult, result);\n        }\n\n        public static IEnumerable<object[]> SplitStringTestData\n        {\n            get\n            {\n                return new ParamsTheoryDataSet<string, string>() {\n                    { null },\n                    { String.Empty },\n                    { \"   \" },\n                    { \"  A  \", \"A\" },\n                    { \"  A, B  \", \"A\", \"B\" },\n                    { \"  , A, ,B, \", \"A\", \"B\" },\n                    { \"   A   B   \", \"A   B\" },\n                };\n            }\n        }\n\n        [CLSCompliant(false)]\n        public class ParamsTheoryDataSet<TParam1, TParam2> : TheoryDataSet\n        {\n            public void Add(TParam1 p1, params TParam2[] p2)\n            {\n                AddItem(p1, p2);\n            }\n        }\n\n        private static void AssertUnauthorizedRequestSet(HttpActionContext actionContext)\n        {\n            Assert.NotNull(actionContext.Response);\n            Assert.Equal(HttpStatusCode.Unauthorized, actionContext.Response.StatusCode);\n            Assert.Same(actionContext.ControllerContext.Request, actionContext.Response.RequestMessage);\n        }\n\n        public class MockableAuthorizeAttribute : AuthorizeAttribute\n        {\n            protected override void HandleUnauthorizedRequest(HttpActionContext context)\n            {\n                HandleUnauthorizedRequestPublic(context);\n            }\n\n            public virtual void HandleUnauthorizedRequestPublic(HttpActionContext context)\n            {\n                base.HandleUnauthorizedRequest(context);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Batch/BatchHttpRequestContextTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Security.Cryptography.X509Certificates;\nusing System.Security.Principal;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Batch\n{\n    public class BatchHttpRequestContextTests\n    {\n        [Fact]\n        public void Constructor_Throws_WhenBatchContextIsNull()\n        {\n            // Arrange\n            HttpRequestContext batchContext = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => CreateProductUnderTest(batchContext), \"batchContext\");\n        }\n\n        [Fact]\n        public void BatchContext_ReturnsProvidedInstance()\n        {\n            // Arrange\n            HttpRequestContext expectedBatchContext = CreateDummyContext();\n            BatchHttpRequestContext context = CreateProductUnderTest(expectedBatchContext);\n\n            // Act\n            HttpRequestContext batchContext = context.BatchContext;\n\n            // Assert\n            Assert.Same(expectedBatchContext, batchContext);\n        }\n\n        [Fact]\n        public void ClientCertificateGet_ReturnsBatchContextClientCertificate()\n        {\n            // Arrange\n            X509Certificate2 expectedCertificate = CreateCertificate();\n            HttpRequestContext batchContext = CreateContext();\n            batchContext.ClientCertificate = expectedCertificate;\n            HttpRequestContext context = CreateProductUnderTest(batchContext);\n\n            // Act\n            X509Certificate2 certificate = context.ClientCertificate;\n\n            // Assert\n            Assert.Same(expectedCertificate, certificate);\n        }\n\n        [Fact]\n        public void ClientCertificateSet_UpdatesBatchContextClientCertificate()\n        {\n            // Arrange\n            X509Certificate2 expectedCertificate = CreateCertificate();\n            HttpRequestContext batchContext = CreateContext();\n            HttpRequestContext context = CreateProductUnderTest(batchContext);\n\n            // Act\n            context.ClientCertificate = expectedCertificate;\n\n            // Assert\n            X509Certificate2 certificate = batchContext.ClientCertificate;\n            Assert.Same(expectedCertificate, certificate);\n        }\n\n        [Fact]\n        public void ConfigurationGet_DoesNotReturnBatchContextConfiguration()\n        {\n            // Arrange\n            using (HttpConfiguration unexpectedConfiguration = CreateConfiguration())\n            {\n                HttpRequestContext batchContext = CreateContext();\n                batchContext.Configuration = unexpectedConfiguration;\n                HttpRequestContext context = CreateProductUnderTest(batchContext);\n\n                // Act\n                HttpConfiguration configuration = context.Configuration;\n\n                // Assert\n                Assert.NotSame(unexpectedConfiguration, configuration);\n            }\n        }\n\n        [Fact]\n        public void ConfigurationSet_UpdatesConfiguration()\n        {\n            // Arrange\n            using (HttpConfiguration expectedConfiguration = CreateConfiguration())\n            {\n                HttpRequestContext batchContext = CreateContext();\n                HttpRequestContext context = CreateProductUnderTest(batchContext);\n\n                // Act\n                context.Configuration = expectedConfiguration;\n\n                // Assert\n                HttpConfiguration configuration = context.Configuration;\n                Assert.Same(expectedConfiguration, configuration);\n            }\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void IncludeErrorDetailGet_ReturnsBatchContextIncludeErrorDetail(bool expectedIncludeErrorDetail)\n        {\n            // Arrange\n            HttpRequestContext batchContext = CreateContext();\n            batchContext.IncludeErrorDetail = expectedIncludeErrorDetail;\n            HttpRequestContext context = CreateProductUnderTest(batchContext);\n\n            // Act\n            bool includeErrorDetail = context.IncludeErrorDetail;\n\n            // Assert\n            Assert.Equal(expectedIncludeErrorDetail, includeErrorDetail);\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void IncludeErrorDetailSet_UpdatesBatchContextIncludeErrorDetail(bool expectedIncludeErrorDetail)\n        {\n            // Arrange\n            HttpRequestContext batchContext = CreateContext();\n            HttpRequestContext context = CreateProductUnderTest(batchContext);\n\n            // Act\n            context.IncludeErrorDetail = expectedIncludeErrorDetail;\n\n            // Assert\n            bool includeErrorDetail = batchContext.IncludeErrorDetail;\n            Assert.Equal(expectedIncludeErrorDetail, includeErrorDetail);\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void IsLocalGet_ReturnsBatchContextIsLocal(bool expectedIsLocal)\n        {\n            // Arrange\n            HttpRequestContext batchContext = CreateContext();\n            batchContext.IsLocal = expectedIsLocal;\n            HttpRequestContext context = CreateProductUnderTest(batchContext);\n\n            // Act\n            bool isLocal = context.IsLocal;\n\n            // Assert\n            Assert.Equal(expectedIsLocal, isLocal);\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void IsLocalSet_UpdatesBatchContextIsLocal(bool expectedIsLocal)\n        {\n            // Arrange\n            HttpRequestContext batchContext = CreateContext();\n            HttpRequestContext context = CreateProductUnderTest(batchContext);\n\n            // Act\n            context.IsLocal = expectedIsLocal;\n\n            // Assert\n            bool isLocal = batchContext.IsLocal;\n            Assert.Equal(expectedIsLocal, isLocal);\n        }\n\n        [Fact]\n        public void PrincipalGet_ReturnsBatchContextPrincipal()\n        {\n            // Arrange\n            IPrincipal expectedPrincipal = CreateDummyPrincipal();\n            HttpRequestContext batchContext = CreateContext();\n            batchContext.Principal = expectedPrincipal;\n            HttpRequestContext context = CreateProductUnderTest(batchContext);\n\n            // Act\n            IPrincipal principal = context.Principal;\n\n            // Assert\n            Assert.Same(expectedPrincipal, principal);\n        }\n\n        [Fact]\n        public void PrincipalSet_UpdatesBatchContextPrincipal()\n        {\n            // Arrange\n            IPrincipal expectedPrincipal = CreateDummyPrincipal();\n            HttpRequestContext batchContext = CreateContext();\n            HttpRequestContext context = CreateProductUnderTest(batchContext);\n\n            // Act\n            context.Principal = expectedPrincipal;\n\n            // Assert\n            IPrincipal principal = batchContext.Principal;\n            Assert.Same(expectedPrincipal, principal);\n        }\n\n        [Fact]\n        public void RouteDataGet_DoesNotReturnBatchContextRouteData()\n        {\n            // Arrange\n            IHttpRouteData unexpectedRouteData = CreateDummyRouteData();\n            HttpRequestContext batchContext = CreateContext();\n            batchContext.RouteData = unexpectedRouteData;\n            HttpRequestContext context = CreateProductUnderTest(batchContext);\n\n            // Act\n            IHttpRouteData routeData = context.RouteData;\n\n            // Assert\n            Assert.NotSame(unexpectedRouteData, routeData);\n        }\n\n        [Fact]\n        public void RouteDataSet_UpdatesRouteData()\n        {\n            // Arrange\n            IHttpRouteData expectedRouteData = CreateDummyRouteData();\n            HttpRequestContext batchContext = CreateContext();\n            HttpRequestContext context = CreateProductUnderTest(batchContext);\n\n            // Act\n            context.RouteData = expectedRouteData;\n\n            // Assert\n            IHttpRouteData routeData = context.RouteData;\n            Assert.Same(expectedRouteData, routeData);\n        }\n\n        [Fact]\n        public void UrlGet_DoesNotReturnBatchContextUrl()\n        {\n            // Arrange\n            UrlHelper unexpectedUrl = CreateDummyUrlHelper();\n            HttpRequestContext batchContext = CreateContext();\n            batchContext.Url = unexpectedUrl;\n            HttpRequestContext context = CreateProductUnderTest(batchContext);\n\n            // Act\n            UrlHelper url = context.Url;\n\n            // Assert\n            Assert.NotSame(unexpectedUrl, url);\n        }\n\n        [Fact]\n        public void UrlSet_UpdatesUrl()\n        {\n            // Arrange\n            UrlHelper expectedUrl = CreateDummyUrlHelper();\n            HttpRequestContext batchContext = CreateContext();\n            HttpRequestContext context = CreateProductUnderTest(batchContext);\n\n            // Act\n            context.Url = expectedUrl;\n\n            // Assert\n            UrlHelper url = context.Url;\n            Assert.Same(expectedUrl, url);\n        }\n\n        [Fact]\n        public void VirtualPathRootGet_ReturnsBatchContextVirtualPathRoot()\n        {\n            // Arrange\n            string expectedVirtualPathRoot = \"foo\";\n            HttpRequestContext batchContext = CreateContext();\n            batchContext.VirtualPathRoot = expectedVirtualPathRoot;\n            HttpRequestContext context = CreateProductUnderTest(batchContext);\n\n            // Act\n            string virtualPathRoot = context.VirtualPathRoot;\n\n            // Assert\n            Assert.Same(expectedVirtualPathRoot, virtualPathRoot);\n        }\n\n        [Fact]\n        public void VirtualPathRootSet_UpdatesBatchContextVirtualPathRoot()\n        {\n            // Arrange\n            string expectedVirtualPathRoot = \"foo\";\n            HttpRequestContext batchContext = CreateContext();\n            HttpRequestContext context = CreateProductUnderTest(batchContext);\n\n            // Act\n            context.VirtualPathRoot = expectedVirtualPathRoot;\n\n            // Assert\n            string virtualPathRoot = batchContext.VirtualPathRoot;\n            Assert.Same(expectedVirtualPathRoot, virtualPathRoot);\n        }\n\n        private static X509Certificate2 CreateCertificate()\n        {\n            return new X509Certificate2();\n        }\n\n        private static HttpConfiguration CreateConfiguration()\n        {\n            return new HttpConfiguration();\n        }\n\n        private static HttpRequestContext CreateContext()\n        {\n            return new HttpRequestContext();\n        }\n\n        private static HttpRequestContext CreateDummyContext()\n        {\n            return new Mock<HttpRequestContext>(MockBehavior.Strict).Object;\n        }\n\n        private static IPrincipal CreateDummyPrincipal()\n        {\n            return new Mock<IPrincipal>(MockBehavior.Strict).Object;\n        }\n\n        private static IHttpRouteData CreateDummyRouteData()\n        {\n            return new Mock<IHttpRouteData>(MockBehavior.Strict).Object;\n        }\n\n        private static UrlHelper CreateDummyUrlHelper()\n        {\n            return new Mock<UrlHelper>(MockBehavior.Strict).Object;\n        }\n\n        private static BatchHttpRequestContext CreateProductUnderTest(HttpRequestContext batchContext)\n        {\n            return new BatchHttpRequestContext(batchContext);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Batch/BatchHttpRequestMessageExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Batch\n{\n    public class BatchHttpRequestMessageExtensionsTest\n    {\n        [Theory]\n        [InlineData(\"MS_HttpRouteData\")]\n        [InlineData(\"MS_DisposableRequestResources\")]\n        [InlineData(\"MS_SynchronizationContext\")]\n        [InlineData(\"MS_HttpConfiguration\")]\n        [InlineData(\"MS_HttpBatchContext\")]\n        [InlineData(\"MS_RoutingContext\")]\n        public void CopyBatchRequestProperties_IgnoresSpecialProperties(string specialPropertyName)\n        {\n            // Arrange\n            string notSpecialPropertyName = \"SomeProperty\";\n            HttpRequestMessage baseRequest = new HttpRequestMessage();\n            HttpRequestMessage childRequest = new HttpRequestMessage();\n\n            baseRequest.Properties.Add(notSpecialPropertyName, 42);\n            baseRequest.Properties.Add(specialPropertyName, 42);\n\n            // Act\n            childRequest.CopyBatchRequestProperties(baseRequest);\n\n            // Assert\n            Assert.Contains(notSpecialPropertyName, childRequest.Properties.Keys);\n            Assert.DoesNotContain(specialPropertyName, childRequest.Properties.Keys);\n        }\n\n        [Fact]\n        public void CopyBatchRequestProperties_AddsBatchHttpRequestContext()\n        {\n            using (HttpRequestMessage subRequest = new HttpRequestMessage())\n            using (HttpRequestMessage batchRequest = new HttpRequestMessage())\n            {\n                HttpRequestContext expectedOriginalContext = new HttpRequestContext();\n                subRequest.SetRequestContext(expectedOriginalContext);\n\n                // Act\n                BatchHttpRequestMessageExtensions.CopyBatchRequestProperties(subRequest, batchRequest);\n\n                // Assert\n                HttpRequestContext context = subRequest.GetRequestContext();\n                BatchHttpRequestContext typedContext = Assert.IsType<BatchHttpRequestContext>(context);\n                Assert.Same(expectedOriginalContext, typedContext.BatchContext);\n            }\n        }\n\n        [Fact]\n        public void CopyBatchRequestProperties_SetsRequestContextWithUrlHelperForSubRequest()\n        {\n            // Arrange\n            using (HttpRequestMessage subRequest = new HttpRequestMessage())\n            using (HttpRequestMessage batchRequest = new HttpRequestMessage())\n            {\n                subRequest.SetRequestContext(new HttpRequestContext());\n\n                // Act\n                BatchHttpRequestMessageExtensions.CopyBatchRequestProperties(subRequest, batchRequest);\n\n                // Assert\n                HttpRequestContext context = subRequest.GetRequestContext();\n                Assert.NotNull(context);\n                Assert.NotNull(context.Url);\n                Assert.Same(subRequest, context.Url.Request);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Batch/BatchLearningTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.Routing;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Batch\n{\n    public class BatchLearningTests\n    {\n        [Fact]\n        public async Task BatchRequest_SubRequestPropertiesDoNotContainRoutingContext_CopyProperties()\n        {\n            // Arrange\n            const string baseAddress = \"http://localhost/api/\";\n            HttpConfiguration config = new HttpConfiguration();\n            HttpServer server = new HttpServer(config);\n            config.Routes.MapHttpBatchRoute(\n                routeName: \"Batch\",\n                routeTemplate: \"api/$batch\",\n                batchHandler: new CustomHttpBatchHandler(server));\n            config.Routes.MapHttpRoute(\n                \"Default\",\n                \"api/{controller}/{id}\",\n                defaults: new { id = RouteParameter.Optional });\n\n            // Act\n            using (HttpClient client = new HttpClient(server))\n            using (HttpRequestMessage batchRequest = new HttpRequestMessage(HttpMethod.Post, baseAddress + \"$batch\"))\n            {\n                batchRequest.Content = new MultipartContent(\"mixed\")\n                {\n                    new HttpMessageContent(\n                        new HttpRequestMessage(HttpMethod.Post, baseAddress + \"values\")\n                        {\n                            Content = new ObjectContent<string>(\"newValue\", new JsonMediaTypeFormatter())\n                        }),\n                    new HttpMessageContent(new HttpRequestMessage(HttpMethod.Get, baseAddress + \"values/newValue\"))\n                };\n\n                using (HttpResponseMessage batchResponse = await client.SendAsync(batchRequest, CancellationToken.None))\n                {\n                    MultipartStreamProvider streamProvider = await batchResponse.Content.ReadAsMultipartAsync();\n                    foreach (HttpContent content in streamProvider.Contents)\n                    {\n                        HttpResponseMessage response = await content.ReadAsHttpResponseMessageAsync();\n                        string result = await response.Content.ReadAsStringAsync();\n\n                        // Assert\n                        Assert.Equal(\"\\\"newValue\\\"\", result);\n                    }\n                }\n            }\n        }\n\n        public class ValuesController : ApiController\n        {\n            public string Get(string id)\n            {\n                return id;\n            }\n\n            public string Post([FromBody] string value)\n            {\n                return value;\n            }\n        }\n\n        public class CustomHttpBatchHandler : DefaultHttpBatchHandler\n        {\n            public CustomHttpBatchHandler(HttpServer httpServer)\n                : base(httpServer)\n            {\n            }\n\n            public override async Task<IList<HttpRequestMessage>> ParseBatchRequestsAsync(\n                HttpRequestMessage request,\n                CancellationToken cancellationToken)\n            {\n                IList<HttpRequestMessage> subRequests = await base.ParseBatchRequestsAsync(request, cancellationToken);\n\n                // Assert\n                Assert.NotNull(subRequests);\n                foreach (HttpRequestMessage subRequest in subRequests)\n                {\n                    Assert.NotNull(subRequest);\n                    Assert.Equal(2, subRequest.Properties.Count);\n                    Assert.True(subRequest.Properties.ContainsKey(HttpPropertyKeys.RequestContextKey));\n                    Assert.True(subRequest.Properties.ContainsKey(HttpPropertyKeys.IsBatchRequest));\n                    Assert.False(subRequest.Properties.ContainsKey(HttpRoute.RoutingContextKey));\n                }\n\n                return subRequests;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Batch/DefaultHttpBatchHandlerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Batch;\nusing System.Web.Http.Routing;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http\n{\n    public class DefaultHttpBatchHandlerTest\n    {\n        [Fact]\n        public void Parameter_Constructor()\n        {\n            DefaultHttpBatchHandler batchHandler = new DefaultHttpBatchHandler(new HttpServer());\n\n            Assert.Equal(BatchExecutionOrder.Sequential, batchHandler.ExecutionOrder);\n            Assert.NotNull(batchHandler.Invoker);\n            Assert.Contains(\"multipart/mixed\", batchHandler.SupportedContentTypes);\n        }\n\n        [Fact]\n        public void Constructor_Throws_IfHttpServerIsNull()\n        {\n            Assert.ThrowsArgumentNull(\n                () => new DefaultHttpBatchHandler(null),\n                \"httpServer\");\n        }\n\n        [Fact]\n        public Task CreateResponseMessageAsync_Throws_IfResponsesAreNull()\n        {\n            DefaultHttpBatchHandler batchHandler = new DefaultHttpBatchHandler(new HttpServer());\n            return Assert.ThrowsArgumentNullAsync(\n                () => batchHandler.CreateResponseMessageAsync(null, new HttpRequestMessage(), CancellationToken.None),\n                \"responses\");\n        }\n\n        [Fact]\n        public Task CreateResponseMessageAsync_Throws_IfRequestIsNull()\n        {\n            DefaultHttpBatchHandler batchHandler = new DefaultHttpBatchHandler(new HttpServer());\n            return Assert.ThrowsArgumentNullAsync(\n                () => batchHandler.CreateResponseMessageAsync(new HttpResponseMessage[0], null, CancellationToken.None),\n                \"request\");\n        }\n\n        [Fact]\n        public async Task CreateResponseMessageAsync_ReturnsMultipartContent()\n        {\n            DefaultHttpBatchHandler batchHandler = new DefaultHttpBatchHandler(new HttpServer());\n            HttpResponseMessage[] responses = new HttpResponseMessage[]\n            {\n                new HttpResponseMessage(HttpStatusCode.OK),\n                new HttpResponseMessage(HttpStatusCode.BadRequest)\n            };\n\n            HttpResponseMessage response = await batchHandler.CreateResponseMessageAsync(responses, new HttpRequestMessage(), CancellationToken.None);\n\n            MultipartContent content = Assert.IsType<MultipartContent>(response.Content);\n            List<HttpResponseMessage> nestedResponses = new List<HttpResponseMessage>();\n            foreach (var part in content)\n            {\n                nestedResponses.Add(await part.ReadAsHttpResponseMessageAsync());\n            }\n\n            Assert.Equal(2, nestedResponses.Count);\n            Assert.Equal(HttpStatusCode.OK, nestedResponses[0].StatusCode);\n            Assert.Equal(HttpStatusCode.BadRequest, nestedResponses[1].StatusCode);\n        }\n\n        [Fact]\n        public Task ProcessBatchAsync_Throws_IfRequestIsNull()\n        {\n            DefaultHttpBatchHandler batchHandler = new DefaultHttpBatchHandler(new HttpServer());\n            return Assert.ThrowsArgumentNullAsync(\n                () => batchHandler.ProcessBatchAsync(null, CancellationToken.None),\n                \"request\");\n        }\n\n        [Fact]\n        public async Task ProcessBatchAsync_CallsRegisterForDispose()\n        {\n            List<IDisposable> expectedResourcesForDisposal = new List<IDisposable>();\n            MockHttpServer server = new MockHttpServer(request =>\n            {\n                var tmpContent = new StringContent(String.Empty);\n                request.RegisterForDispose(tmpContent);\n                expectedResourcesForDisposal.Add(tmpContent);\n                return new HttpResponseMessage { Content = new StringContent(request.RequestUri.AbsoluteUri) };\n            });\n            DefaultHttpBatchHandler batchHandler = new DefaultHttpBatchHandler(server);\n            HttpRequestMessage batchRequest = new HttpRequestMessage\n            {\n                Content = new MultipartContent(\"mixed\")\n                {\n                    new HttpMessageContent(new HttpRequestMessage(HttpMethod.Get, \"http://example.com/\")),\n                    new HttpMessageContent(new HttpRequestMessage(HttpMethod.Post, \"http://example.org/\"))\n                }\n            };\n\n            var response = await batchHandler.ProcessBatchAsync(batchRequest, CancellationToken.None);\n            var resourcesForDisposal = batchRequest.GetResourcesForDisposal();\n\n            foreach (var expectedResource in expectedResourcesForDisposal)\n            {\n                Assert.Contains(expectedResource, resourcesForDisposal);\n            }\n        }\n\n        [Fact]\n        public void ExecutionOrder_ThrowsWhenTheValueIsInvalid()\n        {\n            DefaultHttpBatchHandler batchHandler = new DefaultHttpBatchHandler(new HttpServer());\n\n            Assert.ThrowsInvalidEnumArgument(\n                () => batchHandler.ExecutionOrder = (BatchExecutionOrder)20,\n                \"value\",\n                20,\n                typeof(BatchExecutionOrder));\n        }\n\n        [Fact]\n        public Task ExecuteRequestMessagesAsync_Throws_IfRequestsAreNull()\n        {\n            DefaultHttpBatchHandler batchHandler = new DefaultHttpBatchHandler(new HttpServer());\n            return Assert.ThrowsArgumentNullAsync(\n                () => batchHandler.ExecuteRequestMessagesAsync(null, CancellationToken.None),\n                \"requests\");\n        }\n\n        [Fact]\n        public async Task ExecuteRequestMessagesAsync_CallsInvokerForEachRequest()\n        {\n            MockHttpServer server = new MockHttpServer(request =>\n            {\n                return new HttpResponseMessage { Content = new StringContent(request.RequestUri.AbsoluteUri) };\n            });\n            DefaultHttpBatchHandler batchHandler = new DefaultHttpBatchHandler(server);\n            HttpRequestMessage[] requests = new HttpRequestMessage[]\n            {\n                new HttpRequestMessage(HttpMethod.Get, \"http://example.com/\"),\n                new HttpRequestMessage(HttpMethod.Post, \"http://example.org/\")\n            };\n\n            var responses = await batchHandler.ExecuteRequestMessagesAsync(requests, CancellationToken.None);\n\n            Assert.Equal(2, responses.Count);\n            Assert.Equal(\"http://example.com/\", await responses[0].Content.ReadAsStringAsync());\n            Assert.Equal(\"http://example.org/\", await responses[1].Content.ReadAsStringAsync());\n        }\n\n        [Fact]\n        public async Task ExecuteRequestMessagesAsync_DisposesResponseInCaseOfException()\n        {\n            List<DisposableResponseMessage> responses = new List<DisposableResponseMessage>();\n            MockHttpServer server = new MockHttpServer(request =>\n            {\n                if (request.Method == HttpMethod.Put)\n                {\n                    throw new InvalidOperationException();\n                }\n                var response = new DisposableResponseMessage();\n                responses.Add(response);\n                return response;\n            });\n            DefaultHttpBatchHandler batchHandler = new DefaultHttpBatchHandler(server);\n            HttpRequestMessage[] requests = new HttpRequestMessage[]\n            {\n                new HttpRequestMessage(HttpMethod.Get, \"http://example.com/\"),\n                new HttpRequestMessage(HttpMethod.Post, \"http://example.com/\"),\n                new HttpRequestMessage(HttpMethod.Put, \"http://example.com/\")\n            };\n\n            await Assert.ThrowsAsync<InvalidOperationException>(\n                () => batchHandler.ExecuteRequestMessagesAsync(requests, CancellationToken.None));\n\n            Assert.Equal(2, responses.Count);\n            foreach (var response in responses)\n            {\n                Assert.True(response.IsDisposed);\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteRequestMessagesAsync_NonSequentialExecution()\n        {\n            List<HttpRequestMessage> completedRequests = new List<HttpRequestMessage>();\n\n            MockHttpServer server = new MockHttpServer(async request =>\n            {\n                if (request.Method == HttpMethod.Get)\n                {\n                    await Task.Delay(2000);\n                }\n                completedRequests.Add(request);\n                return new HttpResponseMessage();\n            });\n            DefaultHttpBatchHandler batchHandler = new DefaultHttpBatchHandler(server)\n            {\n                ExecutionOrder = BatchExecutionOrder.NonSequential\n            };\n            HttpRequestMessage[] requests = new HttpRequestMessage[]\n            {\n                new HttpRequestMessage(HttpMethod.Get, \"http://example.com/\"),\n                new HttpRequestMessage(HttpMethod.Post, \"http://example.com/\")\n            };\n\n            await batchHandler.ExecuteRequestMessagesAsync(requests, CancellationToken.None);\n\n            Assert.Equal(2, completedRequests.Count);\n            Assert.Equal(HttpMethod.Post, completedRequests[0].Method);\n            Assert.Equal(HttpMethod.Get, completedRequests[1].Method);\n        }\n\n        [Fact]\n        public async Task ExecuteRequestMessagesAsync_SequentialExecutionCallInvokerForEachRequest()\n        {\n            List<HttpRequestMessage> completedRequests = new List<HttpRequestMessage>();\n\n            MockHttpServer server = new MockHttpServer(async request =>\n            {\n                if (request.Method == HttpMethod.Get)\n                {\n                    await Task.Delay(2000);\n                }\n                completedRequests.Add(request);\n                return new HttpResponseMessage();\n            });\n            DefaultHttpBatchHandler batchHandler = new DefaultHttpBatchHandler(server)\n            {\n                ExecutionOrder = BatchExecutionOrder.Sequential\n            };\n            HttpRequestMessage[] requests = new HttpRequestMessage[]\n            {\n                new HttpRequestMessage(HttpMethod.Get, \"http://example.com/\"),\n                new HttpRequestMessage(HttpMethod.Post, \"http://example.com/\")\n            };\n\n            await batchHandler.ExecuteRequestMessagesAsync(requests, CancellationToken.None);\n\n            Assert.Equal(2, completedRequests.Count);\n            Assert.Equal(HttpMethod.Get, completedRequests[0].Method);\n            Assert.Equal(HttpMethod.Post, completedRequests[1].Method);\n        }\n\n        [Fact]\n        public Task ParseBatchRequestsAsync_Throws_IfRequestIsNull()\n        {\n            DefaultHttpBatchHandler batchHandler = new DefaultHttpBatchHandler(new HttpServer());\n            return Assert.ThrowsArgumentNullAsync(\n                () => batchHandler.ParseBatchRequestsAsync(null, CancellationToken.None),\n                \"request\");\n        }\n\n        [Fact]\n        public async Task ParseBatchRequestsAsync_Returns_RequestsFromMultipartContent()\n        {\n            DefaultHttpBatchHandler batchHandler = new DefaultHttpBatchHandler(new HttpServer());\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                Content = new MultipartContent(\"mixed\")\n                {\n                    new HttpMessageContent(new HttpRequestMessage(HttpMethod.Get, \"http://example.com/\")),\n                    new HttpMessageContent(new HttpRequestMessage(HttpMethod.Post, \"http://example.com/values\"))\n                }\n            };\n\n            IList<HttpRequestMessage> requests = await batchHandler.ParseBatchRequestsAsync(request, CancellationToken.None);\n\n            Assert.Equal(2, requests.Count);\n            Assert.Equal(HttpMethod.Get, requests[0].Method);\n            Assert.Equal(\"http://example.com/\", requests[0].RequestUri.AbsoluteUri);\n            Assert.Equal(HttpMethod.Post, requests[1].Method);\n            Assert.Equal(\"http://example.com/values\", requests[1].RequestUri.AbsoluteUri);\n        }\n\n        [Fact]\n        public async Task ParseBatchRequestsAsync_Returns_RequestsFromMultipartContent_WithUriSchemeSet_FromRequest()\n        {\n            DefaultHttpBatchHandler batchHandler = new DefaultHttpBatchHandler(new HttpServer());\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                Content = new MultipartContent(\"mixed\")\n                {\n                    new HttpMessageContent(new HttpRequestMessage(HttpMethod.Get, \"http://example.com/\")),\n                    new HttpMessageContent(new HttpRequestMessage(HttpMethod.Post, \"https://example.com/values\"))\n                },\n                RequestUri = new Uri(\"https://example.com/\")\n            };\n\n            IList<HttpRequestMessage> requests = await batchHandler.ParseBatchRequestsAsync(request, CancellationToken.None);\n\n            Assert.Equal(2, requests.Count);\n            Assert.Equal(HttpMethod.Get, requests[0].Method);\n            Assert.Equal(\"https://example.com/\", requests[0].RequestUri.AbsoluteUri);\n            Assert.Equal(HttpMethod.Post, requests[1].Method);\n            Assert.Equal(\"https://example.com/values\", requests[1].RequestUri.AbsoluteUri);\n        }\n\n        [Fact]\n        public async Task ParseBatchRequestsAsync_CopiesPropertiesFromRequest_WithoutExcludedProperties()\n        {\n            DefaultHttpBatchHandler batchHandler = new DefaultHttpBatchHandler(new HttpServer());\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                Content = new MultipartContent(\"mixed\")\n                {\n                    new HttpMessageContent(new HttpRequestMessage(HttpMethod.Get, \"http://example.com/\")),\n                    new HttpMessageContent(new HttpRequestMessage(HttpMethod.Post, \"http://example.com/values\"))\n                }\n            };\n            request.Properties.Add(\"foo\", \"bar\");\n            request.SetRouteData(new HttpRouteData(new HttpRoute()));\n            request.RegisterForDispose(new StringContent(String.Empty));\n\n            IList<HttpRequestMessage> requests = await batchHandler.ParseBatchRequestsAsync(request, CancellationToken.None);\n\n            Assert.Equal(2, requests.Count);\n            Assert.Equal(HttpMethod.Get, requests[0].Method);\n            Assert.Equal(\"bar\", requests[0].Properties[\"foo\"]);\n            Assert.Null(requests[0].GetRouteData());\n            Assert.Same(requests[0], requests[0].GetUrlHelper().Request);\n            Assert.Empty(requests[0].GetResourcesForDisposal());\n            Assert.Equal(\"http://example.com/\", requests[0].RequestUri.AbsoluteUri);\n\n            Assert.Equal(HttpMethod.Post, requests[1].Method);\n            Assert.Equal(\"http://example.com/values\", requests[1].RequestUri.AbsoluteUri);\n            Assert.Equal(\"bar\", requests[1].Properties[\"foo\"]);\n            Assert.Null(requests[1].GetRouteData());\n            Assert.Same(requests[1], requests[1].GetUrlHelper().Request);\n            Assert.Empty(requests[1].GetResourcesForDisposal());\n        }\n\n        [Fact]\n        public void ValidateRequest_Throws_IfRequestIsNull()\n        {\n            DefaultHttpBatchHandler batchHandler = new DefaultHttpBatchHandler(new HttpServer());\n            Assert.ThrowsArgumentNull(\n                () => batchHandler.ValidateRequest(null),\n                \"request\");\n        }\n\n        [Fact]\n        public async Task ValidateRequest_Throws_IfRequestContentIsNull()\n        {\n            DefaultHttpBatchHandler batchHandler = new DefaultHttpBatchHandler(new HttpServer());\n            HttpRequestMessage request = new HttpRequestMessage();\n\n            HttpResponseException errorResponse = Assert.Throws<HttpResponseException>(\n                () => batchHandler.ValidateRequest(request));\n            Assert.Equal(HttpStatusCode.BadRequest, errorResponse.Response.StatusCode);\n            Assert.Equal(\"The 'Content' property on the batch request cannot be null.\",\n                (await errorResponse.Response.Content.ReadAsAsync<HttpError>()).Message);\n        }\n\n        [Fact]\n        public async Task ValidateRequest_Throws_IfRequestContentTypeIsNull()\n        {\n            DefaultHttpBatchHandler batchHandler = new DefaultHttpBatchHandler(new HttpServer());\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.Content = new StringContent(String.Empty);\n            request.Content.Headers.ContentType = null;\n\n            HttpResponseException errorResponse = Assert.Throws<HttpResponseException>(\n                () => batchHandler.ValidateRequest(request));\n            Assert.Equal(HttpStatusCode.BadRequest, errorResponse.Response.StatusCode);\n            Assert.Equal(\"The batch request must have a \\\"Content-Type\\\" header.\",\n                (await errorResponse.Response.Content.ReadAsAsync<HttpError>()).Message);\n        }\n\n        [Fact]\n        public async Task ValidateRequest_Throws_IfRequestMediaTypeIsWrong()\n        {\n            DefaultHttpBatchHandler batchHandler = new DefaultHttpBatchHandler(new HttpServer());\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.Content = new StringContent(String.Empty);\n            request.Content.Headers.ContentType = new MediaTypeHeaderValue(\"text/json\");\n\n            HttpResponseException errorResponse = Assert.Throws<HttpResponseException>(\n                () => batchHandler.ValidateRequest(request));\n            Assert.Equal(HttpStatusCode.BadRequest, errorResponse.Response.StatusCode);\n            Assert.Equal(\"The batch request of media type 'text/json' is not supported.\",\n                (await errorResponse.Response.Content.ReadAsAsync<HttpError>()).Message);\n        }\n\n        private class MockHttpServer : HttpServer\n        {\n            private Func<HttpRequestMessage, Task<HttpResponseMessage>> _action;\n\n            public MockHttpServer(Func<HttpRequestMessage, HttpResponseMessage> action)\n            {\n                _action = request =>\n                {\n                    return Task.FromResult(action(request));\n                };\n            }\n\n            public MockHttpServer(Func<HttpRequestMessage, Task<HttpResponseMessage>> action)\n            {\n                _action = action;\n            }\n\n            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n            {\n                return _action(request);\n            }\n        }\n\n        private class DisposableResponseMessage : HttpResponseMessage\n        {\n            public bool IsDisposed { get; set; }\n\n            protected override void Dispose(bool disposing)\n            {\n                IsDisposed = true;\n            }\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Test/Batch/HttpBatchHandlerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Batch;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Results;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http\n{\n    public class HttpBatchHandlerTest\n    {\n        [Fact]\n        public void Constructor_Throws_WhenServerIsNull()\n        {\n            // Arrange\n            HttpServer httpServer = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => CreateProductUnderTest(httpServer), \"httpServer\");\n        }\n\n        [Fact]\n        public void ExceptionLoggerGet_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            IExceptionLogger expectedExceptionLogger = CreateDummyExceptionLogger();\n            IExceptionHandler exceptionHandler = CreateDummyExceptionHandler();\n\n            using (HttpServer server = CreateServer())\n            using (HttpBatchHandler handler = CreateProductUnderTest(server, expectedExceptionLogger,\n                exceptionHandler))\n            {\n                // Act\n                IExceptionLogger exceptionLogger = handler.ExceptionLogger;\n\n                // Assert\n                Assert.Same(expectedExceptionLogger, exceptionLogger);\n            }\n        }\n\n        [Fact]\n        public void ExceptionHandlerGet_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            IExceptionLogger exceptionLogger = CreateDummyExceptionLogger();\n            IExceptionHandler expectedExceptionHandler = CreateDummyExceptionHandler();\n\n            using (HttpServer server = CreateServer())\n            using (HttpBatchHandler handler = CreateProductUnderTest(server, exceptionLogger,\n                expectedExceptionHandler))\n            {\n                // Act\n                IExceptionHandler exceptionHandler = handler.ExceptionHandler;\n\n                // Assert\n                Assert.Same(expectedExceptionHandler, exceptionHandler);\n            }\n        }\n\n        [Fact]\n        public void ExceptionLoggerGet_IfUnset_ReturnsExceptionLoggerFromConfiguration()\n        {\n            // Arrange\n            using (HttpConfiguration configuration = CreateConfiguration())\n            {\n                IExceptionLogger expectedExceptionLogger = CreateDummyExceptionLogger();\n                configuration.Services.Add(typeof(IExceptionLogger), expectedExceptionLogger);\n\n                using (HttpServer server = new HttpServer(configuration))\n                using (HttpBatchHandler product = CreateProductUnderTest(server))\n                {\n                    // Act\n                    IExceptionLogger exceptionLogger = product.ExceptionLogger;\n\n                    // Assert\n                    CompositeExceptionLogger compositeLogger = Assert.IsType<CompositeExceptionLogger>(exceptionLogger);\n                    IEnumerable<IExceptionLogger> loggers = compositeLogger.Loggers;\n                    Assert.NotNull(loggers);\n                    IExceptionLogger logger = Assert.Single(loggers);\n                    Assert.Same(expectedExceptionLogger, logger);\n                }\n            }\n        }\n\n        [Fact]\n        public void ExceptionHandlerGet_IfUnset_ReturnsExceptionHandlerFromConfiguration()\n        {\n            // Arrange\n            using (HttpConfiguration configuration = CreateConfiguration())\n            {\n                IExceptionHandler expectedExceptionHandler = CreateDummyExceptionHandler();\n                configuration.Services.Replace(typeof(IExceptionHandler), expectedExceptionHandler);\n\n                using (HttpServer server = new HttpServer(configuration))\n                using (HttpBatchHandler product = CreateProductUnderTest(server))\n                {\n                    // Act\n                    IExceptionHandler exceptionHandler = product.ExceptionHandler;\n\n                    // Assert\n                    LastChanceExceptionHandler lastChanceHandler = Assert.IsType<LastChanceExceptionHandler>(exceptionHandler);\n                    Assert.Same(expectedExceptionHandler, lastChanceHandler.InnerHandler);\n                }\n            }\n        }\n\n        [Fact]\n        public Task SendAsync_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            MockHttpBatchHandler mockHandler = new MockHttpBatchHandler(new HttpServer());\n\n            // Act & Assert\n            return Assert.ThrowsArgumentNullAsync(() => mockHandler.SendAsync(null), \"request\");\n        }\n\n        [Fact]\n        public async Task SendAsync_CallsProcessBatchAsync()\n        {\n            Mock<HttpBatchHandler> handler = new Mock<HttpBatchHandler>(new HttpServer());\n            handler.Setup(h => h.ProcessBatchAsync(It.IsAny<HttpRequestMessage>(), CancellationToken.None))\n                .Returns(Task.FromResult(new HttpResponseMessage(HttpStatusCode.Redirect)\n                {\n                    Content = new StringContent(\"ProcessBatchAsync called.\")\n                }));\n            HttpMessageInvoker invoker = new HttpMessageInvoker(handler.Object);\n\n            var response = await invoker.SendAsync(new HttpRequestMessage(), CancellationToken.None);\n\n            Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);\n            Assert.Equal(\"ProcessBatchAsync called.\", await response.Content.ReadAsStringAsync());\n        }\n\n        [Fact]\n        public async Task SendAsync_ReturnsHttpResponseException()\n        {\n            Mock<HttpBatchHandler> handler = new Mock<HttpBatchHandler>(new HttpServer());\n            handler.Setup(h => h.ProcessBatchAsync(It.IsAny<HttpRequestMessage>(), CancellationToken.None))\n                .Returns(() =>\n                {\n                    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest)\n                    {\n                        Content = new StringContent(\"HttpResponseException Error.\")\n                    });\n                });\n            HttpMessageInvoker invoker = new HttpMessageInvoker(handler.Object);\n\n            var response = await invoker.SendAsync(new HttpRequestMessage(), CancellationToken.None);\n\n            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);\n            Assert.Equal(\"HttpResponseException Error.\", await response.Content.ReadAsStringAsync());\n        }\n\n        [Fact]\n        public async Task SendAsync_IfProcessBatchAsyncTaskIsFaulted_CallsExceptionServices()\n        {\n            // Arrange\n            Exception expectedException = CreateException();\n\n            Mock<IExceptionLogger> exceptionLoggerMock = CreateStubExceptionLoggerMock();\n            IExceptionLogger exceptionLogger = exceptionLoggerMock.Object;\n\n            Mock<IExceptionHandler> exceptionHandlerMock = CreateStubExceptionHandlerMock();\n            IExceptionHandler exceptionHandler = exceptionHandlerMock.Object;\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpServer server = CreateServer(configuration))\n            using (HttpBatchHandler product = new LambdaHttpBatchHandler(server, exceptionLogger, exceptionHandler,\n                (i1, i2) => CreateFaultedTask<HttpResponseMessage>(expectedException)))\n            {\n                CancellationToken cancellationToken = CreateCancellationToken();\n\n                // Act\n                await Assert.ThrowsAsync<Exception>(() => product.SendAsync(expectedRequest, cancellationToken));\n\n                // Assert\n                Func<ExceptionContext, bool> exceptionContextMatches = (c) =>\n                    c != null\n                    && c.Exception == expectedException\n                    && c.CatchBlock == ExceptionCatchBlocks.HttpBatchHandler\n                    && c.Request == expectedRequest;\n\n                exceptionLoggerMock.Verify(l => l.LogAsync(\n                    It.Is<ExceptionLoggerContext>(c => exceptionContextMatches(c.ExceptionContext)),\n                    cancellationToken), Times.Once());\n\n                exceptionHandlerMock.Verify(h => h.HandleAsync(\n                    It.Is<ExceptionHandlerContext>((c) => exceptionContextMatches(c.ExceptionContext)),\n                    cancellationToken), Times.Once());\n            }\n        }\n\n        [Fact]\n        public async Task SendAsync_IfProcessBatchAsyncTaskIsCanceled_DoesNotCallExceptionServices()\n        {\n            // Arrange\n            Exception expectedException = new OperationCanceledException();\n\n            Mock<IExceptionLogger> exceptionLoggerMock = new Mock<IExceptionLogger>(MockBehavior.Strict);\n            IExceptionLogger exceptionLogger = exceptionLoggerMock.Object;\n\n            Mock<IExceptionHandler> exceptionHandlerMock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n            IExceptionHandler exceptionHandler = exceptionHandlerMock.Object;\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpServer server = CreateServer(configuration))\n            using (HttpBatchHandler product = new LambdaHttpBatchHandler(server, exceptionLogger, exceptionHandler,\n                (i1, i2) => CreateFaultedTask<HttpResponseMessage>(expectedException)))\n            {\n                CancellationToken cancellationToken = CreateCancellationToken();\n\n                // Act & Assert\n                await Assert.ThrowsAsync<OperationCanceledException>(() => product.SendAsync(expectedRequest, cancellationToken));\n            }\n        }\n\n        [Fact]\n        public async Task SendAsync_IfExceptionHandlerSetsNullResult_PropogatesFaultedTaskException()\n        {\n            // Arrange\n            Exception expectedException = CreateExceptionWithCallStack();\n            string expectedStackTrace = expectedException.StackTrace;\n\n            IExceptionLogger exceptionLogger = CreateStubExceptionLogger();\n\n            Mock<IExceptionHandler> exceptionHandlerMock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n            exceptionHandlerMock\n                .Setup(h => h.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                .Callback<ExceptionHandlerContext, CancellationToken>((c, i) => c.Result = null)\n                .Returns(Task.FromResult(0));\n            IExceptionHandler exceptionHandler = exceptionHandlerMock.Object;\n\n            using (HttpRequestMessage request = CreateRequest())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpServer server = CreateServer(configuration))\n            using (HttpBatchHandler product = new LambdaHttpBatchHandler(server, exceptionLogger, exceptionHandler,\n                (i1, i2) => CreateFaultedTask<HttpResponseMessage>(expectedException)))\n            {\n                CancellationToken cancellationToken = CreateCancellationToken();\n\n                // Act\n                var exception = await Assert.ThrowsAsync<Exception>(() => product.SendAsync(request, cancellationToken));\n\n                // Assert\n                Assert.Same(expectedException, exception);\n                Assert.NotNull(exception.StackTrace);\n                Assert.StartsWith(expectedStackTrace, exception.StackTrace);\n            }\n        }\n\n        [Fact]\n        public async Task SendAsync_IfExceptionHandlerHandlesException_ReturnsResponse()\n        {\n            // Arrange\n            IExceptionLogger exceptionLogger = CreateStubExceptionLogger();\n\n            using (HttpResponseMessage expectedResponse = CreateResponse())\n            {\n                Mock<IExceptionHandler> exceptionHandlerMock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n                exceptionHandlerMock\n                    .Setup(h => h.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                    .Callback<ExceptionHandlerContext, CancellationToken>((c, i) =>\n                        c.Result = new ResponseMessageResult(expectedResponse))\n                    .Returns(Task.FromResult(0));\n                IExceptionHandler exceptionHandler = exceptionHandlerMock.Object;\n\n                using (HttpRequestMessage request = CreateRequest())\n                using (HttpConfiguration configuration = new HttpConfiguration())\n                using (HttpServer server = CreateServer(configuration))\n                using (HttpBatchHandler product = new LambdaHttpBatchHandler(server, exceptionLogger, exceptionHandler,\n                    (i1, i2) => CreateFaultedTask<HttpResponseMessage>(CreateException())))\n                {\n                    CancellationToken cancellationToken = CreateCancellationToken();\n\n                    // Act\n                    HttpResponseMessage response = await product.SendAsync(request, cancellationToken);\n\n                    // Assert\n                    Assert.Same(expectedResponse, response);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task SendAsync_WithDefaultExceptionHandler_IfProcessBatchAsyncTaskIsFaulted_ReturnsInternalServerError()\n        {\n            Mock<HttpBatchHandler> handler = new Mock<HttpBatchHandler>(new HttpServer());\n            handler.Setup(h => h.ProcessBatchAsync(It.IsAny<HttpRequestMessage>(), CancellationToken.None))\n                .Returns(() =>\n                {\n                    throw new InvalidOperationException();\n                });\n            HttpMessageInvoker invoker = new HttpMessageInvoker(handler.Object);\n\n            var response = await invoker.SendAsync(new HttpRequestMessage(), CancellationToken.None);\n\n            Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n        }\n\n        private static CancellationToken CreateCancellationToken()\n        {\n            CancellationTokenSource source = new CancellationTokenSource();\n            return source.Token;\n        }\n\n        private static HttpConfiguration CreateConfiguration()\n        {\n            return new HttpConfiguration();\n        }\n\n        private static IExceptionHandler CreateDummyExceptionHandler()\n        {\n            return new Mock<IExceptionHandler>(MockBehavior.Strict).Object;\n        }\n\n        private static IExceptionLogger CreateDummyExceptionLogger()\n        {\n            return new Mock<IExceptionLogger>(MockBehavior.Strict).Object;\n        }\n\n        private static Exception CreateException()\n        {\n            return new Exception();\n        }\n\n        private static Exception CreateExceptionWithCallStack()\n        {\n            try\n            {\n                throw CreateException();\n            }\n            catch (Exception exception)\n            {\n                return exception;\n            }\n        }\n\n        private static Task<TResult> CreateFaultedTask<TResult>(Exception exception)\n        {\n            TaskCompletionSource<TResult> source = new TaskCompletionSource<TResult>();\n            source.SetException(exception);\n            return source.Task;\n        }\n\n        private static HttpBatchHandler CreateProductUnderTest(HttpServer httpServer)\n        {\n            return new MockHttpBatchHandler(httpServer);\n        }\n\n        private static HttpBatchHandler CreateProductUnderTest(HttpServer httpServer, IExceptionLogger exceptionLogger,\n                IExceptionHandler exceptionHanlder)\n        {\n            return new MockHttpBatchHandler(httpServer, exceptionLogger, exceptionHanlder);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private static HttpResponseMessage CreateResponse()\n        {\n            return new HttpResponseMessage();\n        }\n\n        private static HttpServer CreateServer()\n        {\n            return new HttpServer();\n        }\n\n        private static HttpServer CreateServer(HttpConfiguration configuration)\n        {\n            return new HttpServer(configuration);\n        }\n\n        private static Mock<IExceptionHandler> CreateStubExceptionHandlerMock()\n        {\n            Mock<IExceptionHandler> mock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n            mock\n                .Setup(h => h.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                .Returns(Task.FromResult(0));\n            return mock;\n        }\n\n        private static IExceptionLogger CreateStubExceptionLogger()\n        {\n            return CreateStubExceptionLoggerMock().Object;\n        }\n\n        private static Mock<IExceptionLogger> CreateStubExceptionLoggerMock()\n        {\n            Mock<IExceptionLogger> mock = new Mock<IExceptionLogger>(MockBehavior.Strict);\n            mock\n                .Setup(l => l.LogAsync(It.IsAny<ExceptionLoggerContext>(), It.IsAny<CancellationToken>()))\n                .Returns(Task.FromResult(0));\n            return mock;\n        }\n\n        private class LambdaHttpBatchHandler : HttpBatchHandler\n        {\n            Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> _processBatchAsync;\n\n            public LambdaHttpBatchHandler(HttpServer httpServer, IExceptionLogger exceptionLogger,\n                IExceptionHandler exceptionHandler,\n                Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> processBatchAsync)\n                : base(httpServer)\n            {\n                Contract.Assert(processBatchAsync != null);\n                _processBatchAsync = processBatchAsync;\n                ExceptionLogger = exceptionLogger;\n                ExceptionHandler = exceptionHandler;\n            }\n\n            public override Task<HttpResponseMessage> ProcessBatchAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n            {\n                return _processBatchAsync.Invoke(request, cancellationToken);\n            }\n        }\n\n        private class MockHttpBatchHandler : HttpBatchHandler\n        {\n            public MockHttpBatchHandler(HttpServer server)\n                : base(server)\n            {\n            }\n\n            public MockHttpBatchHandler(HttpServer httpServer, IExceptionLogger exceptionLogger,\n                IExceptionHandler exceptionHanlder)\n                : base(httpServer)\n            {\n                ExceptionLogger = exceptionLogger;\n                ExceptionHandler = exceptionHanlder;\n            }\n\n            public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request)\n            {\n                return SendAsync(request, CancellationToken.None);\n            }\n\n            public override Task<HttpResponseMessage> ProcessBatchAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n            {\n                return Task.FromResult(new HttpResponseMessage());\n            }\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Test/Common/TraceWriterExceptionMapperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing System.Web.Http.Tracing;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Common\n{\n    public class TraceWriterExceptionMapperTest\n    {\n        public static TheoryDataSet<Exception, TraceLevel?> GetMappedTraceLevelTestData\n        {\n            get\n            {\n                return new TheoryDataSet<Exception, TraceLevel?>\n                {\n                    { new Exception(), null},\n                    { new HttpResponseException(new HttpResponseMessage(HttpStatusCode.OK)), TraceLevel.Info },\n                    { new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Accepted)), TraceLevel.Info },\n                    { new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest)), TraceLevel.Warn },\n                    { new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Conflict)), TraceLevel.Warn },\n                    { new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)), null },\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"GetMappedTraceLevelTestData\")]\n        public void GetMappedTraceLevel_ReturnsExpectedTraceLevel(Exception exception, TraceLevel? expectedTraceLevel)\n        {\n            Assert.Equal(expectedTraceLevel, TraceWriterExceptionMapper.GetMappedTraceLevel(exception));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Controllers/ActionFilterResultTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Filters;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Controllers\n{\n    public class ActionFilterResultTests\n    {\n        [Fact]\n        public async Task InvokeActionWithActionFilters_ChainsFiltersInOrderFollowedByInnerActionContinuation()\n        {\n            // Arrange\n            HttpActionContext actionContextInstance = ContextUtil.CreateActionContext();\n            List<string> log = new List<string>();\n            Mock<IActionFilter> globalFilterMock = CreateActionFilterMock((ctx, ct, continuation) =>\n            {\n                log.Add(\"globalFilter\");\n                return continuation();\n            });\n            Mock<IActionFilter> actionFilterMock = CreateActionFilterMock((ctx, ct, continuation) =>\n            {\n                log.Add(\"actionFilter\");\n                return continuation();\n            });\n            Func<Task<HttpResponseMessage>> innerAction = () => Task<HttpResponseMessage>.Factory.StartNew(() =>\n            {\n                log.Add(\"innerAction\");\n                return null;\n            });\n            var filters = new IActionFilter[] {\n                globalFilterMock.Object,\n                actionFilterMock.Object,\n            };\n\n            // Act\n            var result = ActionFilterResult.InvokeActionWithActionFilters(actionContextInstance,\n                CancellationToken.None, filters, innerAction);\n\n            // Assert\n            Assert.NotNull(result);\n            await result();\n\n            Assert.Equal(new[] { \"globalFilter\", \"actionFilter\", \"innerAction\" }, log.ToArray());\n            globalFilterMock.Verify();\n            actionFilterMock.Verify();\n        }\n\n        private Mock<IActionFilter> CreateActionFilterMock(Func<HttpActionContext, CancellationToken,\n            Func<Task<HttpResponseMessage>>, Task<HttpResponseMessage>> implementation)\n        {\n            Mock<IActionFilter> filterMock = new Mock<IActionFilter>();\n            filterMock.Setup(f => f.ExecuteActionFilterAsync(It.IsAny<HttpActionContext>(),\n                                                             CancellationToken.None,\n                                                             It.IsAny<Func<Task<HttpResponseMessage>>>()))\n                      .Returns(implementation)\n                      .Verifiable();\n            return filterMock;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Controllers/ApiControllerActionInvokerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http\n{\n    public class ApiControllerActionInvokerTest\n    {\n        private readonly HttpActionContext _actionContext;\n        private readonly Mock<HttpActionDescriptor> _actionDescriptorMock = new Mock<HttpActionDescriptor>();\n        private readonly ApiControllerActionInvoker _actionInvoker = new ApiControllerActionInvoker();\n        private readonly HttpControllerContext _controllerContext;\n        private readonly HttpRequestMessage _request = new HttpRequestMessage();\n        private readonly Mock<IActionResultConverter> _converterMock = new Mock<IActionResultConverter>();\n\n        public ApiControllerActionInvokerTest()\n        {\n            _controllerContext = new HttpControllerContext()\n            {\n                Request = _request\n            };\n            _actionContext = new HttpActionContext(_controllerContext, _actionDescriptorMock.Object);\n            _actionDescriptorMock.Setup(ad => ad.ResultConverter).Returns(_converterMock.Object);\n        }\n\n        [Fact]\n        public void InvokeActionAsync_Throws_IfContextIsNull()\n        {\n            Assert.ThrowsArgumentNull(\n                () => _actionInvoker.InvokeActionAsync(null, CancellationToken.None),\n                \"actionContext\");\n        }\n\n        [Fact]\n        public async Task InvokeActionAsync_InvokesActionDescriptorExecuteAsync()\n        {\n            var cts = new CancellationTokenSource();\n            _actionDescriptorMock.Setup(\n                ad => ad.ExecuteAsync(It.IsAny<HttpControllerContext>(), It.IsAny<IDictionary<string, object>>(), It.IsAny<CancellationToken>()))\n                .Returns(Task.FromResult((object)null));\n\n            await _actionInvoker.InvokeActionAsync(_actionContext, cts.Token);\n\n            _actionDescriptorMock.Verify(ad => ad.ExecuteAsync(_actionContext.ControllerContext, _actionContext.ActionArguments, cts.Token), Times.Once());\n        }\n\n        [Fact]\n        public async Task InvokeActionAsync_PassesExecutionResultToConfiguredConverter()\n        {\n            var value = new object();\n            _actionDescriptorMock.Setup(ad => ad.ExecuteAsync(_actionContext.ControllerContext, _actionContext.ActionArguments, CancellationToken.None))\n                .Returns(Task.FromResult(value));\n\n            await _actionInvoker.InvokeActionAsync(_actionContext, CancellationToken.None);\n\n            _converterMock.Verify(c => c.Convert(_actionContext.ControllerContext, value), Times.Once());\n        }\n\n        [Fact]\n        public async Task InvokeActionAsync_ReturnsResponseFromConverter()\n        {\n            var expectedResponse = new HttpResponseMessage();\n            _actionDescriptorMock.Setup(ad => ad.ExecuteAsync(_actionContext.ControllerContext, _actionContext.ActionArguments, CancellationToken.None))\n                .Returns(Task.FromResult(new object()));\n            _converterMock.Setup(c => c.Convert(_actionContext.ControllerContext, It.IsAny<object>()))\n                .Returns(expectedResponse);\n\n            var response = await _actionInvoker.InvokeActionAsync(_actionContext, CancellationToken.None);\n\n            Assert.Same(expectedResponse, response);\n        }\n\n        [Fact]\n        public async Task InvokeActionAsync_WhenExecuteThrowsHttpResponseException_ReturnsResponse()\n        {\n            HttpResponseMessage response = new HttpResponseMessage();\n            _actionDescriptorMock.Setup(ad => ad.ExecuteAsync(It.IsAny<HttpControllerContext>(), It.IsAny<IDictionary<string, object>>(), CancellationToken.None))\n                .Throws(new HttpResponseException(response));\n\n            var result = await _actionInvoker.InvokeActionAsync(_actionContext, CancellationToken.None);\n\n            Assert.Same(response, result);\n            Assert.Same(_request, result.RequestMessage);\n        }\n\n        [Fact]\n        public async Task InvokeActionAsync_WhenExecuteThrows_ReturnsFaultedTask()\n        {\n            Exception expectedException = new Exception();\n            _actionDescriptorMock.Setup(ad => ad.ExecuteAsync(It.IsAny<HttpControllerContext>(), It.IsAny<IDictionary<string, object>>(), CancellationToken.None))\n                .Throws(expectedException);\n\n            // Act & Assert\n            var exception = await Assert.ThrowsAsync<Exception>(() => _actionInvoker.InvokeActionAsync(_actionContext, CancellationToken.None));\n            Assert.Same(expectedException, exception);\n        }\n\n        [Fact]\n        public async Task InvokeActionAsync_ForActionResult_ReturnsResultResponse()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n\n            using (HttpResponseMessage expectedResponse = new HttpResponseMessage())\n            {\n                IHttpActionResult result = CreateStubResult(expectedResponse);\n                _actionDescriptorMock.Setup(d => d.ReturnType).Returns(typeof(IHttpActionResult));\n                _actionDescriptorMock.Setup(d => d.ExecuteAsync(_actionContext.ControllerContext,\n                    _actionContext.ActionArguments, cancellationToken)).Returns(Task.FromResult((object)result));\n\n                // Act\n                HttpResponseMessage response = await _actionInvoker.InvokeActionAsync(_actionContext, cancellationToken);\n\n                // Assert\n                Assert.Same(expectedResponse, response);\n            }\n        }\n\n        [Fact]\n        public async Task InvokeActionAsync_ForActionResult_AddsRequestMessage_WhenMissing()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n\n            using (HttpRequestMessage expectedRequest = new HttpRequestMessage())\n            {\n                _controllerContext.Request = expectedRequest;\n\n                using (HttpResponseMessage responseToReturn = new HttpResponseMessage())\n                {\n                    IHttpActionResult result = CreateStubResult(responseToReturn);\n                    _actionDescriptorMock.Setup(d => d.ReturnType).Returns(typeof(IHttpActionResult));\n                    _actionDescriptorMock.Setup(d => d.ExecuteAsync(It.IsAny<HttpControllerContext>(),\n                        It.IsAny<IDictionary<string, object>>(), It.IsAny<CancellationToken>())).Returns(\n                        Task.FromResult((object)result));\n\n                    // Act\n                    HttpResponseMessage response = await _actionInvoker.InvokeActionAsync(_actionContext, cancellationToken);\n\n                    // Assert\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task InvokeActionAsync_ForActionResult_LeavesRequestMessage_WhenPresent()\n        {\n            // Arrange\n            CancellationToken cancellationToken = new CancellationToken();\n\n            using (HttpRequestMessage expectedRequest = new HttpRequestMessage())\n            {\n                using (HttpRequestMessage otherRequest = new HttpRequestMessage())\n                {\n                    _controllerContext.Request = otherRequest;\n\n                    using (HttpResponseMessage responseToReturn = CreateResponse(expectedRequest))\n                    {\n                        IHttpActionResult result = CreateStubResult(responseToReturn);\n                        _actionDescriptorMock.Setup(d => d.ReturnType).Returns(typeof(IHttpActionResult));\n                        _actionDescriptorMock.Setup(d => d.ExecuteAsync(It.IsAny<HttpControllerContext>(),\n                            It.IsAny<IDictionary<string, object>>(), It.IsAny<CancellationToken>())).Returns(\n                            Task.FromResult((object)result));\n\n                        // Act\n                        HttpResponseMessage response = await _actionInvoker.InvokeActionAsync(_actionContext, cancellationToken);\n\n                        // Assert\n                        Assert.Same(expectedRequest, response.RequestMessage);\n                    }\n                }\n            }\n        }\n\n        [Fact]\n        public async Task InvokeActionAsync_ForActionResult_HandlesHttpResponseException()\n        {\n            // Arrange\n            _actionDescriptorMock.Setup(d => d.ReturnType).Returns(typeof(IHttpActionResult));\n            HttpResponseException expectedException = new HttpResponseException(HttpStatusCode.Ambiguous);\n            _actionDescriptorMock.Setup(d => d.ExecuteAsync(It.IsAny<HttpControllerContext>(),\n                It.IsAny<IDictionary<string, object>>(), It.IsAny<CancellationToken>())).Throws(expectedException);\n\n            // Act\n            HttpResponseMessage response = await _actionInvoker.InvokeActionAsync(_actionContext, CancellationToken.None);\n\n            // Assert\n            Assert.Equal(HttpStatusCode.Ambiguous, response.StatusCode);\n        }\n\n        [Fact]\n        public Task InvokeActionAsync_ForActionResult_Throws_WhenResultIsNull()\n        {\n            // Arrange\n            _actionDescriptorMock.Setup(d => d.ReturnType).Returns(typeof(IHttpActionResult));\n            _actionDescriptorMock.Setup(d => d.ExecuteAsync(It.IsAny<HttpControllerContext>(),\n                It.IsAny<IDictionary<string, object>>(), It.IsAny<CancellationToken>())).Returns(\n                Task.FromResult<object>(null));\n\n            // Act\n            Task<HttpResponseMessage> task = _actionInvoker.InvokeActionAsync(_actionContext, CancellationToken.None);\n\n            // Assert\n            return Assert.ThrowsAsync<InvalidOperationException>(() => task,\n                \"A null value was returned where an instance of IHttpActionResult was expected.\");\n        }\n\n        [Fact]\n        public Task InvokeActionAsync_ForActionResult_Throws_WhenResponseIsNull()\n        {\n            // Arrange\n            _actionDescriptorMock.Setup(d => d.ReturnType).Returns(typeof(IHttpActionResult));\n            IHttpActionResult emptyResult = CreateStubResult(null);\n            _actionDescriptorMock.Setup(d => d.ExecuteAsync(It.IsAny<HttpControllerContext>(),\n                It.IsAny<IDictionary<string, object>>(), It.IsAny<CancellationToken>())).Returns(\n                Task.FromResult((object)emptyResult));\n\n            // Act\n            Task<HttpResponseMessage> task = _actionInvoker.InvokeActionAsync(_actionContext, CancellationToken.None);\n\n            // Assert\n            return Assert.ThrowsAsync<InvalidOperationException>(() => task,\n                \"A null value was returned where an instance of HttpResponseMessage was expected.\");\n        }\n\n        [Fact]\n        public Task InvokeActionAsync_ForActionResult_Throws_WhenResultIsNotActionResult()\n        {\n            // Arrange\n            _actionDescriptorMock.Setup(d => d.ReturnType).Returns(typeof(IHttpActionResult));\n            _actionDescriptorMock.Setup(d => d.ExecuteAsync(It.IsAny<HttpControllerContext>(),\n                It.IsAny<IDictionary<string, object>>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(\n                new object()));\n\n            // Act\n            Task<HttpResponseMessage> task = _actionInvoker.InvokeActionAsync(_actionContext, CancellationToken.None);\n\n            // Assert\n            return Assert.ThrowsAsync<InvalidOperationException>(() => task,\n                \"An object of type 'System.Object' was returned where an instance of IHttpActionResult was expected.\");\n        }\n\n        [Fact]\n        public async Task InvokeActionAsync_DeclaredObject_ReturnsWidget()\n        {\n            using (var expectedResponse = new HttpResponseMessage())\n            {\n                var result = new Widget() { Name = \"CoolWidget\" };\n\n                _actionDescriptorMock.Setup(d => d.ReturnType).Returns(typeof(object));\n                _actionDescriptorMock.Setup(d => d.ExecuteAsync(\n                    It.IsAny<HttpControllerContext>(),\n                    It.IsAny<IDictionary<string, object>>(),\n                    It.IsAny<CancellationToken>())).Returns(Task.FromResult((object)result));\n\n                _converterMock.Setup(c => c.Convert(It.IsAny<HttpControllerContext>(), result)).Returns(expectedResponse);\n\n                // Act\n                HttpResponseMessage response = await _actionInvoker.InvokeActionAsync(_actionContext, CancellationToken.None);\n\n                // Assert\n                Assert.Same(expectedResponse, response);\n            }\n        }\n\n        [Fact]\n        public async Task InvokeActionAsync_WrongReturnType_Throws()\n        {\n            using (var expectedResponse = new HttpResponseMessage())\n            {\n                var result = new Mock<IHttpActionResult>().Object;\n\n                _actionDescriptorMock.Setup(d => d.ReturnType).Returns(typeof(Widget));\n                _actionDescriptorMock.SetupGet(d => d.ResultConverter).Returns(new ValueResultConverter<Widget>());\n                _actionDescriptorMock.Setup(d => d.ExecuteAsync(\n                    It.IsAny<HttpControllerContext>(),\n                    It.IsAny<IDictionary<string, object>>(),\n                    It.IsAny<CancellationToken>())).Returns(Task.FromResult((object)result));\n\n                // Act & Assert\n                await Assert.ThrowsAsync<InvalidCastException>(() => _actionInvoker.InvokeActionAsync(_actionContext, CancellationToken.None));\n            }\n        }\n\n        [Fact]\n        public async Task InvokeActionAsync_DeclaredObject_ReturnsActionResult()\n        {\n            // Arrange\n            using (var expectedResponse = new HttpResponseMessage())\n            {\n                var mockActionResult = new Mock<IHttpActionResult>();\n                mockActionResult\n                    .Setup(m => m.ExecuteAsync(It.IsAny<CancellationToken>()))\n                    .Returns(Task.FromResult(expectedResponse));\n\n                _actionDescriptorMock.Setup(d => d.ReturnType).Returns(typeof(object));\n                _actionDescriptorMock.Setup(d => d.ExecuteAsync(\n                    It.IsAny<HttpControllerContext>(),\n                    It.IsAny<IDictionary<string, object>>(),\n                    It.IsAny<CancellationToken>())).Returns(Task.FromResult((object)mockActionResult.Object));\n\n                // Act\n                HttpResponseMessage response = await _actionInvoker.InvokeActionAsync(_actionContext, CancellationToken.None);\n\n                // Assert\n                Assert.Same(expectedResponse, response);\n            }\n        }\n\n        private static HttpResponseMessage CreateResponse(HttpRequestMessage request)\n        {\n            return new HttpResponseMessage\n            {\n                RequestMessage = request\n            };\n        }\n\n        private static IHttpActionResult CreateStubResult(HttpResponseMessage response)\n        {\n            Mock<IHttpActionResult> mock = new Mock<IHttpActionResult>();\n            mock.Setup(r => r.ExecuteAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult(response));\n            return mock.Object;\n        }\n\n        private class Widget\n        {\n            public string Name\n            {\n                get;\n                set;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Controllers/ApiControllerActionSelectorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Routing;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http\n{\n    public class ApiControllerActionSelectorTest\n    {\n        [Fact]\n        public void SelectAction_With_DifferentExecutionContexts()\n        {\n            ApiControllerActionSelector actionSelector = new ApiControllerActionSelector();\n            HttpControllerContext GetContext = ContextUtil.CreateControllerContext();\n            HttpControllerDescriptor usersControllerDescriptor = new HttpControllerDescriptor(GetContext.Configuration, \"Users\", typeof(UsersController));\n            usersControllerDescriptor.Configuration.Services.Replace(typeof(IHttpActionSelector), actionSelector);\n            GetContext.ControllerDescriptor = usersControllerDescriptor;\n            GetContext.Request = new HttpRequestMessage\n                {\n                    Method = HttpMethod.Get\n                };\n            HttpControllerContext PostContext = ContextUtil.CreateControllerContext();\n            usersControllerDescriptor.Configuration.Services.Replace(typeof(IHttpActionSelector), actionSelector);\n            PostContext.ControllerDescriptor = usersControllerDescriptor;\n            PostContext.Request = new HttpRequestMessage\n            {\n                Method = HttpMethod.Post\n            };\n\n            HttpActionDescriptor getActionDescriptor = actionSelector.SelectAction(GetContext);\n            HttpActionDescriptor postActionDescriptor = actionSelector.SelectAction(PostContext);\n\n            Assert.Equal(\"Get\", getActionDescriptor.ActionName);\n            Assert.Equal(\"Post\", postActionDescriptor.ActionName);\n        }\n\n        [Fact]\n        public void SelectAction_RespectsDirectRoutes()\n        {\n            var actionSelector = new ApiControllerActionSelector();\n            HttpControllerContext context = ContextUtil.CreateControllerContext();\n            context.Request = new HttpRequestMessage { Method = HttpMethod.Get };\n            var controllerDescriptor = new HttpControllerDescriptor(context.Configuration, \"Users\", typeof(UsersController));\n            context.ControllerDescriptor = controllerDescriptor;\n            ReflectedHttpActionDescriptor directRouteAction = (ReflectedHttpActionDescriptor)actionSelector.GetActionMapping(controllerDescriptor)[\"Get\"].First();\n            context.RouteData.Route.DataTokens.Add(\"actions\", new ReflectedHttpActionDescriptor[] { directRouteAction });\n\n            HttpActionDescriptor actionDescriptor = actionSelector.SelectAction(context);\n\n            Assert.Same(directRouteAction, actionDescriptor);\n        }\n\n        [Fact]\n        public void SelectAction_WithDirectRoutes_RespectsRouteOrder()\n        {\n            // Arrange\n            var actionSelector = new ApiControllerActionSelector();\n            HttpControllerContext context = ContextUtil.CreateControllerContext();\n            context.Request = new HttpRequestMessage { Method = HttpMethod.Get };\n            var controllerDescriptor = new HttpControllerDescriptor(context.Configuration, \"MultipleGet\", typeof(MultipleGetController));\n            context.ControllerDescriptor = controllerDescriptor;\n            ReflectedHttpActionDescriptor firstDirectRouteAction = (ReflectedHttpActionDescriptor)actionSelector.GetActionMapping(controllerDescriptor)[\"GetA\"].Single();\n            HttpRouteData[] subRouteData = new HttpRouteData[2];\n            subRouteData[0] = new HttpRouteData(new HttpRoute());\n            subRouteData[1] = new HttpRouteData(new HttpRoute());\n            context.RouteData.Values.Add(RouteCollectionRoute.SubRouteDataKey, subRouteData);\n            subRouteData[0].Route.DataTokens.Add(\"actions\", new ReflectedHttpActionDescriptor[] { firstDirectRouteAction });\n            subRouteData[0].Route.DataTokens.Add(\"order\", 1);\n            ReflectedHttpActionDescriptor secondDirectRouteAction = (ReflectedHttpActionDescriptor)actionSelector.GetActionMapping(controllerDescriptor)[\"GetB\"].Single();\n            subRouteData[1].Route.DataTokens.Add(\"actions\", new ReflectedHttpActionDescriptor[] { secondDirectRouteAction });\n            subRouteData[1].Route.DataTokens.Add(\"order\", 2);\n\n            // Act\n            HttpActionDescriptor actionDescriptor = actionSelector.SelectAction(context);\n\n            // Assert\n            Assert.Same(firstDirectRouteAction, actionDescriptor);\n        }\n\n        [Fact]\n        public void SelectAction_WithDirectRoutes_RespectsPrecedence()\n        {\n            // Arrange\n            var actionSelector = new ApiControllerActionSelector();\n            HttpControllerContext context = ContextUtil.CreateControllerContext();\n            context.Request = new HttpRequestMessage { Method = HttpMethod.Get };\n            var controllerDescriptor = new HttpControllerDescriptor(context.Configuration, \"MultipleGet\", typeof(MultipleGetController));\n            context.ControllerDescriptor = controllerDescriptor;\n            ReflectedHttpActionDescriptor firstDirectRouteAction = (ReflectedHttpActionDescriptor)actionSelector.GetActionMapping(controllerDescriptor)[\"GetA\"].Single();\n            HttpRouteData[] subRouteData = new HttpRouteData[2];\n            subRouteData[0] = new HttpRouteData(new HttpRoute());\n            subRouteData[1] = new HttpRouteData(new HttpRoute());\n            context.RouteData.Values.Add(RouteCollectionRoute.SubRouteDataKey, subRouteData);\n            subRouteData[0].Route.DataTokens.Add(\"actions\", new ReflectedHttpActionDescriptor[] { firstDirectRouteAction });\n            subRouteData[0].Route.DataTokens.Add(\"precedence\", 2M);\n            ReflectedHttpActionDescriptor secondDirectRouteAction = (ReflectedHttpActionDescriptor)actionSelector.GetActionMapping(controllerDescriptor)[\"GetB\"].Single();\n            subRouteData[1].Route.DataTokens.Add(\"actions\", new ReflectedHttpActionDescriptor[] { secondDirectRouteAction });\n            subRouteData[1].Route.DataTokens.Add(\"precedence\", 1M);\n\n            // Act\n            HttpActionDescriptor actionDescriptor = actionSelector.SelectAction(context);\n\n            // Assert\n            Assert.Same(secondDirectRouteAction, actionDescriptor);\n        }\n\n        [Fact]\n        public void SelectAction_Throws_IfContextIsNull()\n        {\n            ApiControllerActionSelector actionSelector = new ApiControllerActionSelector();\n\n            Assert.ThrowsArgumentNull(\n                () => actionSelector.SelectAction(null),\n                \"controllerContext\");\n        }\n\n        [Fact]\n        public void GetActionMapping_IgnoresNonAction()\n        {\n            var actionSelector = new ApiControllerActionSelector();\n            HttpControllerContext context = ContextUtil.CreateControllerContext();\n            context.Request = new HttpRequestMessage { Method = HttpMethod.Get };\n            var controllerDescriptor = new HttpControllerDescriptor(context.Configuration, \"NonAction\", typeof(NonActionController));\n            context.ControllerDescriptor = controllerDescriptor;\n\n            var mapping = actionSelector.GetActionMapping(controllerDescriptor);\n\n            Assert.False(mapping.Contains(\"GetA\"));\n            Assert.True(mapping.Contains(\"GetB\"));            \n        }\n\n        public class NonActionController : ApiController\n        {\n            [NonAction]\n            public HttpResponseMessage GetA() { return null; }\n\n            public HttpResponseMessage GetB() { return null; }\n        }\n\n        public class MultipleGetController : ApiController\n        {\n            public HttpResponseMessage GetA() { return null; }\n\n            public HttpResponseMessage GetB() { return null; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Controllers/ApiControllerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel.DataAnnotations;\nusing System.Globalization;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.Routing;\nusing System.Web.Http.Services;\nusing System.Web.Http.Validation;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http\n{\n    public class ApiControllerTest\n    {\n        private readonly HttpActionContext _actionContextInstance = ContextUtil.CreateActionContext();\n        private readonly HttpConfiguration _configurationInstance = new HttpConfiguration();\n        private readonly HttpActionDescriptor _actionDescriptorInstance = new Mock<HttpActionDescriptor>() { CallBase = true }.Object;\n\n        [Fact]\n        public async Task Setting_CustomActionInvoker()\n        {\n            // Arrange\n            ApiController api = new UsersController();\n            string responseText = \"Hello World\";\n            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext();\n\n            HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, \"test\", typeof(UsersController));\n            controllerContext.ControllerDescriptor = controllerDescriptor;\n\n            Mock<IHttpActionInvoker> mockInvoker = new Mock<IHttpActionInvoker>();\n            mockInvoker\n                .Setup(invoker => invoker.InvokeActionAsync(It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>()))\n                .Returns(() =>\n                {\n                    TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();\n                    tcs.TrySetResult(new HttpResponseMessage() { Content = new StringContent(responseText) });\n                    return tcs.Task;\n                });\n            controllerDescriptor.Configuration.Services.Replace(typeof(IHttpActionInvoker), mockInvoker.Object);\n\n            // Act\n            HttpResponseMessage message = await api.ExecuteAsync(\n                controllerContext,\n                CancellationToken.None);\n\n            // Assert\n            Assert.Equal(responseText, await message.Content.ReadAsStringAsync());\n        }\n\n        [Fact]\n        public async Task Setting_CustomActionSelector()\n        {\n            // Arrange\n            var api = new UsersController();\n            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(instance: api);\n\n            HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, \"test\", typeof(UsersController));\n            controllerContext.ControllerDescriptor = controllerDescriptor;\n\n            Mock<IHttpActionSelector> mockSelector = new Mock<IHttpActionSelector>();\n            mockSelector\n                .Setup(invoker => invoker.SelectAction(It.IsAny<HttpControllerContext>()))\n                .Returns(() =>\n                {\n                    Func<HttpResponseMessage> testDelegate = api.Delete;\n                    return new ReflectedHttpActionDescriptor\n                    {\n                        Configuration = controllerContext.Configuration,\n                        ControllerDescriptor = controllerDescriptor,\n                        MethodInfo = testDelegate.Method\n                    };\n                });\n            controllerDescriptor.Configuration.Services.Replace(typeof(IHttpActionSelector), mockSelector.Object);\n\n            // Act\n            HttpResponseMessage message = await api.ExecuteAsync(\n                controllerContext,\n                CancellationToken.None);\n\n            // Assert\n            Assert.Equal(\"User Deleted\", await message.Content.ReadAsStringAsync());\n        }\n\n        [Fact]\n        public async Task Default_Get()\n        {\n            // Arrange\n            ApiController api = new UsersController();\n            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(instance: api, request: new HttpRequestMessage() { Method = HttpMethod.Get });\n            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, \"test\", typeof(UsersController));\n\n            // Act\n            HttpResponseMessage message = await api.ExecuteAsync(\n                controllerContext,\n                CancellationToken.None);\n\n            // Assert\n            Assert.Equal(\"Default User\", await message.Content.ReadAsStringAsync());\n        }\n\n        [Fact]\n        public async Task Default_Post()\n        {\n            // Arrange\n            ApiController api = new UsersController();\n            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(instance: api, request: new HttpRequestMessage() { Method = HttpMethod.Post });\n            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, \"test\", typeof(UsersController));\n\n            // Act\n            HttpResponseMessage message = await api.ExecuteAsync(\n                controllerContext,\n                CancellationToken.None);\n\n            // Assert\n            Assert.Equal(\"User Posted\", await message.Content.ReadAsStringAsync());\n        }\n\n        [Fact]\n        public async Task Default_Put()\n        {\n            // Arrange\n            ApiController api = new UsersController();\n            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(instance: api, request: new HttpRequestMessage() { Method = HttpMethod.Put });\n            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, \"test\", typeof(UsersController));\n\n            // Act\n            HttpResponseMessage message = await api.ExecuteAsync(\n                controllerContext,\n                CancellationToken.None);\n\n            // Assert\n            Assert.Equal(\"User Updated\", await message.Content.ReadAsStringAsync());\n        }\n\n        [Fact]\n        public async Task Default_Delete()\n        {\n            // Arrange\n            ApiController api = new UsersController();\n            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(instance: api, request: new HttpRequestMessage() { Method = HttpMethod.Delete });\n            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, \"test\", typeof(UsersController));\n\n            // Act\n            HttpResponseMessage message = await api.ExecuteAsync(\n                controllerContext,\n                CancellationToken.None);\n\n            // Assert\n            Assert.Equal(\"User Deleted\", await message.Content.ReadAsStringAsync());\n        }\n\n        [Fact]\n        public async Task Route_ActionName()\n        {\n            // Arrange\n            ApiController api = new UsersRpcController();\n            HttpRouteData route = new HttpRouteData(new HttpRoute());\n            route.Values.Add(\"action\", \"Admin\");\n            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(instance: api, routeData: route, request: new HttpRequestMessage() { Method = HttpMethod.Post });\n            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, \"test\", typeof(UsersRpcController));\n\n            // Act\n            HttpResponseMessage message = await api.ExecuteAsync(controllerContext, CancellationToken.None);\n            User user = await message.Content.ReadAsAsync<User>();\n\n            // Assert\n            Assert.Equal(\"Yao\", user.FirstName);\n            Assert.Equal(\"Huang\", user.LastName);\n        }\n\n        [Fact]\n        public async Task Route_Get_Action_With_Route_Parameters()\n        {\n            // Arrange\n            ApiController api = new UsersRpcController();\n            HttpRouteData route = new HttpRouteData(new HttpRoute());\n            route.Values.Add(\"action\", \"EchoUser\");\n            route.Values.Add(\"firstName\", \"RouteFirstName\");\n            route.Values.Add(\"lastName\", \"RouteLastName\");\n            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(instance: api, routeData: route, request: new HttpRequestMessage() { Method = HttpMethod.Post });\n            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, \"test\", typeof(UsersRpcController));\n\n            // Act\n            HttpResponseMessage message = await api.ExecuteAsync(controllerContext, CancellationToken.None);\n            User user = await message.Content.ReadAsAsync<User>();\n\n            // Assert\n            Assert.Equal(\"RouteFirstName\", user.FirstName);\n            Assert.Equal(\"RouteLastName\", user.LastName);\n        }\n\n        [Fact]\n        public async Task Route_Get_Action_With_Query_Parameters()\n        {\n            // Arrange\n            ApiController api = new UsersRpcController();\n            HttpRouteData route = new HttpRouteData(new HttpRoute());\n            route.Values.Add(\"action\", \"EchoUser\");\n\n            Uri requestUri = new Uri(\"http://localhost/?firstName=QueryFirstName&lastName=QueryLastName\");\n            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(instance: api, routeData: route, request: new HttpRequestMessage()\n                {\n                    Method = HttpMethod.Post,\n                    RequestUri = requestUri\n                });\n            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, \"test\", typeof(UsersRpcController));\n\n            // Act\n            HttpResponseMessage message = await api.ExecuteAsync(controllerContext, CancellationToken.None);\n            User user = await message.Content.ReadAsAsync<User>();\n\n            // Assert\n            Assert.Equal(\"QueryFirstName\", user.FirstName);\n            Assert.Equal(\"QueryLastName\", user.LastName);\n        }\n\n        [Fact]\n        public async Task Route_Post_Action_With_Content_Parameter()\n        {\n            // Arrange\n            ApiController api = new UsersRpcController();\n            HttpRouteData route = new HttpRouteData(new HttpRoute());\n            route.Values.Add(\"action\", \"EchoUserObject\");\n            User postedUser = new User()\n            {\n                FirstName = \"SampleFirstName\",\n                LastName = \"SampleLastName\"\n            };\n\n            HttpRequestMessage request = new HttpRequestMessage() { Method = HttpMethod.Post };\n\n            // Create a serialized request because this test directly calls the controller\n            // which would have normally been working with a serialized request content.\n            string serializedUserAsString = null;\n            using (HttpRequestMessage tempRequest = new HttpRequestMessage() { Content = new ObjectContent<User>(postedUser, new XmlMediaTypeFormatter()) })\n            {\n                serializedUserAsString = await tempRequest.Content.ReadAsStringAsync();\n            }\n\n            StringContent stringContent = new StringContent(serializedUserAsString);\n            stringContent.Headers.ContentType = new MediaTypeHeaderValue(\"application/xml\");\n            request.Content = stringContent;\n\n            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(instance: api, routeData: route, request: request);\n            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, \"test\", typeof(UsersRpcController));\n\n            // Act\n            HttpResponseMessage message = await api.ExecuteAsync(\n                controllerContext,\n                CancellationToken.None);\n            User user = await message.Content.ReadAsAsync<User>();\n\n            // Assert\n            Assert.Equal(postedUser.FirstName, user.FirstName);\n            Assert.Equal(postedUser.LastName, user.LastName);\n        }\n\n        [Fact]\n        public async Task Invalid_Action_In_Route()\n        {\n            // Arrange\n            ApiController api = new UsersController();\n            HttpRouteData route = new HttpRouteData(new HttpRoute());\n            string actionName = \"invalidOp\";\n            route.Values.Add(\"action\", actionName);\n            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(instance: api, routeData: route, request: new HttpRequestMessage() { Method = HttpMethod.Get });\n            Type controllerType = typeof(UsersController);\n            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, controllerType.Name, controllerType);\n            controllerContext.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;\n\n            // Act & Assert\n            var exception = await Assert.ThrowsAsync<HttpResponseException>(\n                () => api.ExecuteAsync(controllerContext, CancellationToken.None));\n\n            Assert.Equal(HttpStatusCode.NotFound, exception.Response.StatusCode);\n            var content = Assert.IsType<ObjectContent<HttpError>>(exception.Response.Content);\n            Assert.Equal(\"No action was found on the controller 'UsersController' that matches the name 'invalidOp'.\",\n                ((HttpError)content.Value)[\"MessageDetail\"]);\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_InvokesAuthenticationFilters_ThenInvokesAuthorizationFilters_ThenInvokesModelBinding_ThenInvokesActionFilters_ThenInvokesAction()\n        {\n            List<string> log = new List<string>();\n            Mock<ApiController> controllerMock = new Mock<ApiController>() { CallBase = true };\n            var controllerContextMock = new Mock<HttpControllerContext>();\n\n            Mock<IActionValueBinder> binderMock = new Mock<IActionValueBinder>();\n            Mock<HttpActionBinding> actionBindingMock = new Mock<HttpActionBinding>();\n            actionBindingMock.Setup(b => b.ExecuteBindingAsync(It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>())).Returns(() => Task.Factory.StartNew(() => { log.Add(\"model binding\"); }));\n            binderMock.Setup(b => b.GetBinding(It.IsAny<HttpActionDescriptor>())).Returns(actionBindingMock.Object);\n            HttpConfiguration configuration = new HttpConfiguration();\n\n            HttpControllerContext controllerContext = controllerContextMock.Object;\n            controllerContext.Configuration = configuration;\n            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(configuration, \"test\", typeof(object));\n            var actionFilterMock = CreateActionFilterMock((ac, ct, cont) =>\n            {\n                log.Add(\"action filters\");\n                return cont();\n            });\n            var authorizationFilterMock = CreateAuthorizationFilterMock((ac, ct, cont) =>\n            {\n                log.Add(\"authZ filters\");\n                return cont();\n            });\n            Mock<IAuthenticationFilter> authenticationFilterMock = new Mock<IAuthenticationFilter>();\n            authenticationFilterMock.Setup(f => f.AuthenticateAsync(It.IsAny<HttpAuthenticationContext>(),\n                It.IsAny<CancellationToken>())).Callback(() =>\n                    {\n                        log.Add(\"authN filters authenticate\");\n                    }).Returns(() => Task.FromResult<object>(null));\n            IHttpActionResult innerResult = null;\n            Mock<IHttpActionResult> challengeResultMock = new Mock<IHttpActionResult>();\n            challengeResultMock.Setup(r => r.ExecuteAsync(It.IsAny<CancellationToken>())).Returns(async () =>\n            {\n                HttpResponseMessage response = await innerResult.ExecuteAsync(CancellationToken.None);\n                log.Add(\"authN filters challenge\");\n                return response;\n            });\n            authenticationFilterMock.Setup(f => f.ChallengeAsync(It.IsAny<HttpAuthenticationChallengeContext>(),\n                It.IsAny<CancellationToken>()))\n                .Callback<HttpAuthenticationChallengeContext, CancellationToken>((c, t) =>\n                {\n                    innerResult = c.Result;\n                    c.Result = challengeResultMock.Object;\n                })\n                .Returns(() => Task.FromResult<object>(null));\n\n            var selectorMock = new Mock<IHttpActionSelector>();\n\n            Mock<HttpActionDescriptor> actionDescriptorMock = new Mock<HttpActionDescriptor>();\n            actionDescriptorMock.Setup(ad => ad.ActionBinding).Returns(actionBindingMock.Object);\n            actionDescriptorMock.Setup(ad => ad.GetFilterPipeline())\n                .Returns(new Collection<FilterInfo>(new List<FilterInfo>() { new FilterInfo(actionFilterMock.Object, FilterScope.Action), new FilterInfo(authorizationFilterMock.Object, FilterScope.Action), new FilterInfo(authenticationFilterMock.Object, FilterScope.Action) }));\n\n            selectorMock.Setup(s => s.SelectAction(controllerContext)).Returns(actionDescriptorMock.Object);\n\n            ApiController controller = controllerMock.Object;\n            var invokerMock = new Mock<IHttpActionInvoker>();\n            invokerMock.Setup(i => i.InvokeActionAsync(It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>()))\n                       .Returns(() => Task.Factory.StartNew(() =>\n                       {\n                           log.Add(\"action\");\n                           return new HttpResponseMessage();\n                       }));\n            controllerContext.Configuration.Services.Replace(typeof(IHttpActionInvoker), invokerMock.Object);\n            controllerContext.Configuration.Services.Replace(typeof(IHttpActionSelector), selectorMock.Object);\n            controllerContext.Configuration.Services.Replace(typeof(IActionValueBinder), binderMock.Object);\n\n            await controller.ExecuteAsync(controllerContext, CancellationToken.None);\n\n            Assert.Equal(new string[] { \"authN filters authenticate\", \"authZ filters\", \"model binding\", \"action filters\", \"action\", \"authN filters challenge\" }, log.ToArray());\n        }\n\n        [Fact]\n        public void GetFilters_QueriesFilterProvidersFromServices()\n        {\n            // Arrange\n            Mock<DefaultServices> servicesMock = new Mock<DefaultServices> { CallBase = true };\n            Mock<IFilterProvider> filterProviderMock = new Mock<IFilterProvider>();\n            servicesMock.Setup(r => r.GetServices(typeof(IFilterProvider))).Returns(new object[] { filterProviderMock.Object }).Verifiable();\n            _configurationInstance.Services = servicesMock.Object;\n\n            HttpActionDescriptor actionDescriptorMock = new Mock<HttpActionDescriptor>() { CallBase = true }.Object;\n            actionDescriptorMock.Configuration = _configurationInstance;\n\n            // Act\n            actionDescriptorMock.GetFilterPipeline();\n\n            // Assert\n            servicesMock.Verify();\n        }\n\n        [Fact]\n        public void GetFilters_UsesFilterProvidersToGetFilters()\n        {\n            // Arrange\n            Mock<DefaultServices> servicesMock = new Mock<DefaultServices> { CallBase = true };\n            Mock<IFilterProvider> filterProviderMock = new Mock<IFilterProvider>();\n            servicesMock.Setup(r => r.GetServices(typeof(IFilterProvider))).Returns(new[] { filterProviderMock.Object });\n            _configurationInstance.Services = servicesMock.Object;\n\n            HttpActionDescriptor actionDescriptorMock = new Mock<HttpActionDescriptor>() { CallBase = true }.Object;\n            actionDescriptorMock.Configuration = _configurationInstance;\n\n            // Act\n            actionDescriptorMock.GetFilterPipeline().ToList();\n\n            // Assert\n            filterProviderMock.Verify(fp => fp.GetFilters(_configurationInstance, actionDescriptorMock));\n        }\n\n        [Fact]\n        public void RequestPropertyGetterSetterWorks()\n        {\n            Assert.Reflection.Property(new Mock<ApiController>().Object,\n                c => c.Request, expectedDefaultValue: null, allowNull: false,\n                roundTripTestValue: new HttpRequestMessage());\n        }\n\n        [Fact]\n        public void ConfigurationPropertyGetterSetterWorks()\n        {\n            Assert.Reflection.Property(new Mock<ApiController>().Object,\n                c => c.Configuration, expectedDefaultValue: null, allowNull: false,\n                roundTripTestValue: new HttpConfiguration());\n        }\n\n        [Fact]\n        public void ModelStatePropertyGetterWorks()\n        {\n            // Arrange\n            ApiController controller = new Mock<ApiController>().Object;\n\n            // Act\n            ModelStateDictionary expected = new ModelStateDictionary();\n            expected.Add(\"a\", new ModelState() { Value = new ValueProviders.ValueProviderResult(\"result\", \"attempted\", CultureInfo.InvariantCulture) });\n\n            controller.ModelState.Add(\"a\", new ModelState() { Value = new ValueProviders.ValueProviderResult(\"result\", \"attempted\", CultureInfo.InvariantCulture) });\n\n            // Assert\n            Assert.Equal(expected.Count, controller.ModelState.Count);\n        }\n\n        // TODO: Move these tests to ActionDescriptorTest\n        [Fact]\n        public void GetFilters_OrdersFilters()\n        {\n            // Arrange\n            HttpActionDescriptor actionDescriptorMock = new Mock<HttpActionDescriptor>() { CallBase = true }.Object;\n            actionDescriptorMock.Configuration = _configurationInstance;\n\n            var globalFilter = new FilterInfo(new TestMultiFilter(), FilterScope.Global);\n            var actionFilter = new FilterInfo(new TestMultiFilter(), FilterScope.Action);\n            var controllerFilter = new FilterInfo(new TestMultiFilter(), FilterScope.Controller);\n            Mock<DefaultServices> servicesMock = BuildFilterProvidingServicesMock(_configurationInstance, actionDescriptorMock, globalFilter, actionFilter, controllerFilter);\n            _configurationInstance.Services = servicesMock.Object;\n\n            // Act\n            var result = actionDescriptorMock.GetFilterPipeline().ToArray();\n\n            // Assert\n            Assert.Equal(new[] { globalFilter, controllerFilter, actionFilter }, result);\n        }\n\n        [Fact]\n        public void GetFilters_RemovesDuplicateUniqueFiltersKeepingMostSpecificScope()\n        {\n            // Arrange\n            HttpActionDescriptor actionDescriptorMock = new Mock<HttpActionDescriptor>() { CallBase = true }.Object;\n            actionDescriptorMock.Configuration = _configurationInstance;\n\n            var multiActionFilter = new FilterInfo(new TestMultiFilter(), FilterScope.Action);\n            var multiGlobalFilter = new FilterInfo(new TestMultiFilter(), FilterScope.Global);\n            var uniqueControllerFilter = new FilterInfo(new TestUniqueFilter(), FilterScope.Controller);\n            var uniqueActionFilter = new FilterInfo(new TestUniqueFilter(), FilterScope.Action);\n            Mock<DefaultServices> servicesMock = BuildFilterProvidingServicesMock(\n                _configurationInstance, actionDescriptorMock,\n                multiActionFilter, multiGlobalFilter, uniqueControllerFilter, uniqueActionFilter);\n            _configurationInstance.Services = servicesMock.Object;\n\n            // Act\n            var result = actionDescriptorMock.GetFilterPipeline().ToArray();\n\n            // Assert\n            Assert.Equal(new[] { multiGlobalFilter, multiActionFilter, uniqueActionFilter }, result);\n        }\n\n        [Fact]\n        public Task ExecuteAsync_RunsExceptionFilter_WhenActionThrowsException()\n        {\n            // Arrange\n            Exception expectedException = new NotImplementedException();\n            ApiController controller = new ExceptionController(expectedException);\n\n            // Act & Assert\n            return TestExceptionFilterAsync(controller, expectedException, configure: null);\n        }\n\n        [Fact]\n        public Task ExecuteAsync_RunsExceptionFilter_WhenActionFilterThrowsException()\n        {\n            // Arrange\n            Exception expectedException = new NotImplementedException();\n            ApiController controller = new ExceptionlessController();\n            Mock<IActionFilter> filterMock = new Mock<IActionFilter>();\n            filterMock.Setup(f => f.ExecuteActionFilterAsync(It.IsAny<HttpActionContext>(),\n                It.IsAny<CancellationToken>(), It.IsAny<Func<Task<HttpResponseMessage>>>())).Callback(() =>\n            {\n                throw expectedException;\n            });\n            IActionFilter filter = filterMock.Object;\n\n            // Act & Assert\n            return TestExceptionFilterAsync(controller, expectedException, (configuration) =>\n                { configuration.Filters.Add(filter); });\n        }\n\n        [Fact]\n        public Task ExecuteAsync_RunsExceptionFilter_WhenAuthorizationFilterThrowsException()\n        {\n            // Arrange\n            Exception expectedException = new NotImplementedException();\n            ApiController controller = new ExceptionlessController();\n            Mock<IAuthorizationFilter> filterMock = new Mock<IAuthorizationFilter>();\n            filterMock.Setup(f => f.ExecuteAuthorizationFilterAsync(It.IsAny<HttpActionContext>(),\n                It.IsAny<CancellationToken>(), It.IsAny<Func<Task<HttpResponseMessage>>>())).Callback(() =>\n            {\n                throw expectedException;\n            });\n            IAuthorizationFilter filter = filterMock.Object;\n\n            // Act & Assert\n            return TestExceptionFilterAsync(controller, expectedException, (configuration) =>\n                { configuration.Filters.Add(filter); });\n        }\n\n        [Fact]\n        public Task ExecuteAsync_RunsExceptionFilter_WhenAuthenticationFilterAuthenticateThrowsException()\n        {\n            // Arrange\n            Exception expectedException = new NotImplementedException();\n            ApiController controller = new ExceptionlessController();\n            Mock<IAuthenticationFilter> filterMock = new Mock<IAuthenticationFilter>();\n            filterMock.Setup(f => f.AuthenticateAsync(It.IsAny<HttpAuthenticationContext>(),\n                It.IsAny<CancellationToken>())).Callback(() =>\n                {\n                    throw expectedException;\n                });\n            IAuthenticationFilter filter = filterMock.Object;\n\n            // Act & Assert\n            return TestExceptionFilterAsync(controller, expectedException, (configuration) =>\n                { configuration.Filters.Add(filter); });\n        }\n\n        [Fact]\n        public Task ExecuteAsync_RunsExceptionFilter_WhenAuthenticationFilterChallengeThrowsException()\n        {\n            // Arrange\n            Exception expectedException = new NotImplementedException();\n            ApiController controller = new ExceptionlessController();\n            Mock<IAuthenticationFilter> filterMock = new Mock<IAuthenticationFilter>();\n            filterMock.Setup(f => f.AuthenticateAsync(It.IsAny<HttpAuthenticationContext>(),\n                It.IsAny<CancellationToken>())).Returns(() => Task.FromResult<object>(null));\n            filterMock.Setup(f => f.ChallengeAsync(It.IsAny<HttpAuthenticationChallengeContext>(),\n                It.IsAny<CancellationToken>())).Callback(() =>\n                {\n                    throw expectedException;\n                });\n            IAuthenticationFilter filter = filterMock.Object;\n\n            // Act & Assert\n            return TestExceptionFilterAsync(controller, expectedException, (configuration) =>\n                { configuration.Filters.Add(filter); });\n        }\n\n        private static async Task TestExceptionFilterAsync(ApiController controller, Exception expectedException,\n            Action<HttpConfiguration> configure)\n        {\n            // Arrange\n            Exception actualException = null;\n            IHttpRouteData routeData = new HttpRouteData(new HttpRoute());\n\n            using (HttpRequestMessage request = new HttpRequestMessage())\n            using (HttpConfiguration configuration = new HttpConfiguration())\n            using (HttpResponseMessage response = new HttpResponseMessage())\n            {\n                HttpControllerContext context = new HttpControllerContext(configuration, routeData, request);\n                HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(configuration,\n                    \"Ignored\", controller.GetType());\n                context.Controller = controller;\n                context.ControllerDescriptor = controllerDescriptor;\n\n                if (configure != null)\n                {\n                    configure.Invoke(configuration);\n                }\n\n                Mock<IExceptionFilter> spy = new Mock<IExceptionFilter>();\n                spy.Setup(f => f.ExecuteExceptionFilterAsync(It.IsAny<HttpActionExecutedContext>(),\n                    It.IsAny<CancellationToken>())).Returns<HttpActionExecutedContext, CancellationToken>(\n                    (c, i) =>\n                    {\n                        actualException = c.Exception;\n                        c.Response = response;\n                        return Task.FromResult<object>(null);\n                    });\n\n                configuration.Filters.Add(spy.Object);\n\n                // Act\n                HttpResponseMessage ignore = await controller.ExecuteAsync(context, CancellationToken.None);\n            }\n\n            // Assert\n            Assert.Same(expectedException, actualException);\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_IfActionThrows_CallsExceptionServicesFromConfiguration()\n        {\n            List<string> log = new List<string>();\n            Exception expectedException = new Exception();\n            ExceptionController controller = new ExceptionController(expectedException);\n\n            Mock<IExceptionLogger> exceptionLoggerMock = new Mock<IExceptionLogger>(MockBehavior.Strict);\n            exceptionLoggerMock\n                .Setup(h => h.LogAsync(It.IsAny<ExceptionLoggerContext>(), It.IsAny<CancellationToken>()))\n                .Returns<ExceptionLoggerContext, CancellationToken>((c, i) =>\n                {\n                    log.Add(\"logger\");\n                    return Task.FromResult(0);\n                });\n            IExceptionLogger exceptionLogger = exceptionLoggerMock.Object;\n\n            Mock<IExceptionHandler> exceptionHandlerMock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n            exceptionHandlerMock\n                .Setup(h => h.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                .Returns<ExceptionHandlerContext, CancellationToken>((c, i) =>\n                {\n                    log.Add(\"handler\");\n                    return Task.FromResult(0);\n                });\n            IExceptionHandler exceptionHandler = exceptionHandlerMock.Object;\n\n            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext();\n\n            HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(\n                controllerContext.Configuration, \"Get\", typeof(ExceptionController));\n            controllerContext.ControllerDescriptor = controllerDescriptor;\n            controllerContext.Controller = controller;\n            controllerContext.Configuration.Services.Add(typeof(IExceptionLogger), exceptionLogger);\n            controllerContext.Configuration.Services.Replace(typeof(IExceptionHandler), exceptionHandler);\n            controllerContext.Configuration.Filters.Add(CreateStubExceptionFilter());\n\n            // Act & Assert\n            var exception = await Assert.ThrowsAsync<Exception>(() => controller.ExecuteAsync(controllerContext, CancellationToken.None));\n\n            Assert.Same(expectedException, exception);\n            Assert.Equal(new string[] { \"logger\", \"handler\" }, log.ToArray());\n        }\n\n        [Fact]\n        public async Task ApiControllerCannotBeReused()\n        {\n            // Arrange\n            var config = new HttpConfiguration() { IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always };\n            var singletonController = new Mock<ApiController> { CallBase = true }.Object;\n            var mockDescriptor = new Mock<HttpControllerDescriptor>(config, \"MyMock\", typeof(ApiController)) { CallBase = true };\n            mockDescriptor.Setup(d => d.CreateController(It.IsAny<HttpRequestMessage>())).Returns(singletonController);\n            var mockSelector = new Mock<DefaultHttpControllerSelector>(config) { CallBase = true };\n            mockSelector.Setup(s => s.SelectController(It.IsAny<HttpRequestMessage>())).Returns(mockDescriptor.Object);\n            config.Routes.MapHttpRoute(\"default\", \"\", new { controller = \"MyMock\" });\n            config.Services.Replace(typeof(IHttpControllerSelector), mockSelector.Object);\n            var server = new HttpServer(config);\n            var invoker = new HttpMessageInvoker(server);\n\n            // Act\n            HttpResponseMessage response1 = await invoker.SendAsync(new HttpRequestMessage(HttpMethod.Get, \"http://localhost/\"), CancellationToken.None);\n            HttpResponseMessage response2 = await invoker.SendAsync(new HttpRequestMessage(HttpMethod.Get, \"http://localhost/\"), CancellationToken.None);\n\n            // Assert\n            Assert.NotEqual(HttpStatusCode.InternalServerError, response1.StatusCode);\n            Assert.Equal(HttpStatusCode.InternalServerError, response2.StatusCode);\n            Assert.Contains(\"Cannot reuse an 'ApiController' instance. 'ApiController' has to be constructed per incoming message.\", await response2.Content.ReadAsStringAsync());\n        }\n\n        [Fact]\n        public async Task ApiControllerPutsSelfInRequestResourcesToBeDisposed()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"default\", \"\", new { controller = \"SpyDispose\" });\n            var server = new HttpServer(config);\n            var invoker = new HttpMessageInvoker(server);\n            var request = new HttpRequestMessage(HttpMethod.Get, \"http://localhost/\");\n            await invoker.SendAsync(request, CancellationToken.None);\n\n            // Act\n            request.DisposeRequestResources();\n\n            // Assert\n            Assert.True(SpyDisposeController.DisposeWasCalled);\n        }\n\n        [Fact]\n        public void ControllerContextDefault_IsNonNull()\n        {\n            // Arrange\n            ApiController controller = CreateFakeController();\n\n            // Act\n            HttpControllerContext context = controller.ControllerContext;\n\n            // Assert\n            Assert.NotNull(context);\n        }\n\n        [Fact]\n        public void RequestGet_ReturnsControllerContextRequest()\n        {\n            // Arrange\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                ApiController controller = CreateFakeController();\n                controller.ControllerContext = new HttpControllerContext\n                {\n                    Request = expectedRequest\n                };\n\n                // Act\n                HttpRequestMessage request = controller.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public void RequestSet_Throws_WhenNull()\n        {\n            // Arrange\n            ApiController controller = CreateFakeController();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { controller.Request = null; }, \"value\");\n        }\n\n        [Fact]\n        public void RequestSet_UpdatesControllerContextRequest()\n        {\n            // Arrange\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                ApiController controller = CreateFakeController();\n                HttpControllerContext controllerContext = CreateControllerContext();\n                controller.ControllerContext = controllerContext;\n\n                // Act\n                controller.Request = expectedRequest;\n\n                // Assert\n                Assert.Same(expectedRequest, controllerContext.Request);\n            }\n        }\n\n        [Fact]\n        public void RequestSet_UpdatesRequestRequestContext()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                ApiController controller = CreateFakeController();\n                HttpRequestContext expectedRequestContext = CreateRequestContext();\n                controller.RequestContext = expectedRequestContext;\n\n                // Act\n                controller.Request = request;\n\n                // Assert\n                Assert.Same(expectedRequestContext, request.GetRequestContext());\n            }\n        }\n\n        [Fact]\n        public void RequestSet_Throws_WhenRequestHasConflictingRequestContext()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                ApiController controller = CreateFakeController();\n                HttpRequestContext otherRequestContext = CreateRequestContext();\n                request.SetRequestContext(otherRequestContext);\n                Assert.NotSame(controller.RequestContext, otherRequestContext); // Guard\n\n                // Act & Assert\n                Assert.Throws<InvalidOperationException>(() => { controller.Request = request; },\n                    \"The request context property on the request must be null or match ApiController.RequestContext.\");\n            }\n        }\n\n        [Fact]\n        public void RequestSet_UpdatesRequestRequestContext_WhenRequestHasNoContext()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                ApiController controller = CreateFakeController();\n                HttpRequestContext expectedRequestContext = CreateRequestContext();\n                controller.RequestContext = expectedRequestContext;\n                Assert.Null(request.GetRequestContext()); // Guard\n\n                // Act\n                controller.Request = request;\n\n                // Assert\n                Assert.Same(expectedRequestContext, request.GetRequestContext());\n            }\n        }\n\n        [Fact]\n        public void RequestSet_WithConfigurationPropertyAndDefaultRequestContext_UpdatesConfiguration()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            using (HttpConfiguration expectedConfiguration = new HttpConfiguration())\n            {\n                ApiController controller = CreateFakeController();\n                request.SetConfiguration(expectedConfiguration);\n                controller.Request = request;\n\n                // Act\n                HttpConfiguration configuration = controller.Configuration;\n\n                // Assert\n                Assert.Same(expectedConfiguration, configuration);\n            }\n        }\n\n        [Fact]\n        public void RequestContextSet_LeavesRequestRequestContextUnchanged_WhenRequestHasControllerRequestContext()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                ApiController controller = CreateFakeController();\n                HttpRequestContext expectedRequestContext = controller.RequestContext;\n                request.SetRequestContext(expectedRequestContext);\n\n                // Act\n                controller.Request = request;\n\n                // Assert\n                HttpRequestContext requestContext = request.GetRequestContext();\n                Assert.Same(expectedRequestContext, requestContext);\n            }\n        }\n\n        [Fact]\n        public void RequestSet_UpdatesRequestBackedContextRequest()\n        {\n            // Arrange\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                ApiController controller = CreateFakeController();\n                RequestBackedHttpRequestContext context = Assert.IsType<RequestBackedHttpRequestContext>(controller.RequestContext); // Guard\n\n                // Act\n                controller.Request = expectedRequest;\n\n                // Assert\n                Assert.Same(expectedRequest, context.Request);\n            }\n        }\n\n        [Fact]\n        public void RequestContextGet_ReturnsControllerContextRequestContext()\n        {\n            // Arrange\n            HttpControllerContext controllerContext = CreateControllerContext();\n            HttpRequestContext expectedRequestContext = CreateRequestContext();\n            controllerContext.RequestContext = expectedRequestContext;\n            ApiController controller = CreateFakeController();\n            controller.ControllerContext = controllerContext;\n\n            // Act\n            HttpRequestContext requestContext = controller.RequestContext;\n\n            // Assert\n            Assert.Same(expectedRequestContext, requestContext);\n        }\n\n        [Fact]\n        public void RequestContextSet_Throws_WhenNull()\n        {\n            // Arrange\n            ApiController controller = CreateFakeController();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { controller.RequestContext = null; }, \"value\");\n        }\n\n        [Fact]\n        public void RequestContextSet_UpdatesControllerContextRequestContext()\n        {\n            // Arrange\n            ApiController controller = CreateFakeController();\n            HttpControllerContext controllerContext = CreateControllerContext();\n            controller.ControllerContext = controllerContext;\n            HttpRequestContext expectedRequestContext = CreateRequestContext();\n\n            // Act\n            controller.RequestContext = expectedRequestContext;\n\n            // Assert\n            Assert.Same(expectedRequestContext, controllerContext.RequestContext);\n        }\n\n        [Fact]\n        public void RequestContextSet_UpdatesRequestRequestContext_WhenRequestIsPresent()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                ApiController controller = CreateFakeController();\n                HttpRequestContext expectedRequestContext = CreateRequestContext();\n                controller.Request = request;\n\n                // Act\n                controller.RequestContext = expectedRequestContext;\n\n                // Assert\n                HttpRequestContext requestContext = request.GetRequestContext();\n                Assert.Same(expectedRequestContext, requestContext);\n            }\n        }\n\n        [Fact]\n        public void RequestContextSet_Throws_WhenRequestIsPresentWithConflictingRequestContext()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                ApiController controller = CreateFakeController();\n                HttpRequestContext otherRequestContext = CreateRequestContext();\n                controller.Request = request;\n                request.SetRequestContext(otherRequestContext);\n                HttpRequestContext requestContext = CreateRequestContext();\n\n                // Act & Assert\n                Assert.Throws<InvalidOperationException>(() => { controller.RequestContext = requestContext; },\n                    \"The request context property on the request must be null or match ApiController.RequestContext.\");\n            }\n        }\n\n        [Fact]\n        public void RequestContextSet_UpdatesRequestRequestContext_WhenRequestIsPresentWithNoContext()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                ApiController controller = CreateFakeController();\n                HttpRequestContext expectedRequestContext = CreateRequestContext();\n                controller.Request = request;\n                request.Properties.Remove(HttpPropertyKeys.RequestContextKey);\n\n                // Act\n                controller.RequestContext = expectedRequestContext;\n\n                // Assert\n                HttpRequestContext requestContext = request.GetRequestContext();\n                Assert.Same(expectedRequestContext, requestContext);\n            }\n        }\n\n        [Fact]\n        public void RequestContextSet_UpdatesRequestRequestContext_WhenRequestIsPresentWithExistingContext()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                ApiController controller = CreateFakeController();\n                HttpRequestContext expectedRequestContext = CreateRequestContext();\n                controller.Request = request;\n                request.SetRequestContext(controller.RequestContext);\n\n                // Act\n                controller.RequestContext = expectedRequestContext;\n\n                // Assert\n                HttpRequestContext requestContext = request.GetRequestContext();\n                Assert.Same(expectedRequestContext, requestContext);\n            }\n        }\n\n        [Fact]\n        public void RequestContextSet_LeavesRequestRequestContextUnchanged_WhenRequestIsPresentWithNewContext()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                ApiController controller = CreateFakeController();\n                HttpRequestContext expectedRequestContext = CreateRequestContext();\n                controller.Request = request;\n                request.SetRequestContext(expectedRequestContext);\n\n                // Act\n                controller.RequestContext = expectedRequestContext;\n\n                // Assert\n                HttpRequestContext requestContext = request.GetRequestContext();\n                Assert.Same(expectedRequestContext, requestContext);\n            }\n        }\n\n        [Fact]\n        public void RequestContextDefault_IsRequestBacked()\n        {\n            // Arrange\n            ApiController controller = CreateFakeController();\n\n            // Act\n            HttpRequestContext context = controller.RequestContext;\n\n            // Assert\n            Assert.IsType<RequestBackedHttpRequestContext>(context);\n        }\n\n        [Fact]\n        public void UserGet_ReturnsContextPrincipal()\n        {\n            // Arrange\n            ApiController controller = CreateFakeController();\n            IPrincipal expectedPrincipal = CreateDummyPrincipal();\n            controller.RequestContext = new HttpRequestContext\n            {\n                Principal = expectedPrincipal\n            };\n\n            // Act\n            IPrincipal principal = controller.User;\n\n            // Assert\n            Assert.Same(expectedPrincipal, principal);\n        }\n\n        [Fact]\n        public void UserSet_UpdatesContextPrincipal()\n        {\n            // Arrange\n            ApiController controller = CreateFakeController();\n            IPrincipal expectedPrincipal = CreateDummyPrincipal();\n            HttpRequestContext context = new HttpRequestContext();\n            controller.RequestContext = context;\n\n            // Act\n            controller.User = expectedPrincipal;\n\n            // Assert\n            Assert.Same(expectedPrincipal, context.Principal);\n        }\n\n        [Fact]\n        public void Validate_ThrowsInvalidOperationException_IfConfigurationIsNull()\n        {\n            // Arrange\n            TestController controller = new TestController();\n            TestEntity entity = new TestEntity();\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => controller.Validate(entity),\n                \"ApiController.Configuration must not be null.\");\n        }\n\n        [Fact]\n        public void Validate_DoesNothing_IfValidatorIsNull()\n        {\n            // Arrange\n            HttpConfiguration configuration = new HttpConfiguration();\n            configuration.Services.Replace(typeof(IBodyModelValidator), null);\n            TestEntity entity = new TestEntity { ID = 9999999 };\n\n            TestController controller = new TestController { Configuration = configuration };\n\n            // Act\n            controller.Validate(entity);\n\n            // Assert\n            Assert.True(controller.ModelState.IsValid);\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void Validate_CallsValidateOnConfiguredValidator_UsingConfiguredMetadataProvider()\n        {\n            // Arrange\n            Mock<IBodyModelValidator> validator = new Mock<IBodyModelValidator>();\n            Mock<ModelMetadataProvider> metadataProvider = new Mock<ModelMetadataProvider>();\n\n            HttpConfiguration configuration = new HttpConfiguration();\n            configuration.Services.Replace(typeof(IBodyModelValidator), validator.Object);\n            configuration.Services.Replace(typeof(ModelMetadataProvider), metadataProvider.Object);\n\n            TestController controller = new TestController { Configuration = configuration };\n            TestEntity entity = new TestEntity { ID = 42 };\n\n            // Act\n            controller.Validate(entity);\n\n            // Assert\n            validator.Verify(\n                v => v.Validate(entity, typeof(TestEntity), metadataProvider.Object, controller.ActionContext, String.Empty),\n                Times.Once());\n            Assert.True(controller.ModelState.IsValid);\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void Validate_SetsModelStateErrors_ForInvalidModels()\n        {\n            // Arrange\n            HttpConfiguration configuration = new HttpConfiguration();\n            TestController controller = new TestController { Configuration = configuration };\n            TestEntity entity = new TestEntity { ID = -1 };\n\n            // Act\n            controller.Validate(entity);\n\n            // Assert\n            Assert.False(controller.ModelState.IsValid);\n            Assert.Equal(\"The field ID must be between 0 and 100.\", controller.ModelState[\"ID\"].Errors[0].ErrorMessage);\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void Validate_SetsModelStateErrorsUnderRightPrefix_ForInvalidModels()\n        {\n            // Arrange\n            HttpConfiguration configuration = new HttpConfiguration();\n            TestController controller = new TestController { Configuration = configuration };\n            TestEntity entity = new TestEntity { ID = -1 };\n\n            // Act\n            controller.Validate(entity, keyPrefix: \"prefix\");\n\n            // Assert\n            Assert.False(controller.ModelState.IsValid);\n            Assert.Equal(\"The field ID must be between 0 and 100.\",\n                controller.ModelState[\"prefix.ID\"].Errors[0].ErrorMessage);\n        }\n\n        [Fact]\n        public void Validate_DoesNotThrow_ForValidModels()\n        {\n            // Arrange\n            HttpConfiguration configuration = new HttpConfiguration();\n            TestController controller = new TestController { Configuration = configuration };\n            TestEntity entity = new TestEntity { ID = 42 };\n\n            // Act && Assert\n            Assert.DoesNotThrow(() => controller.Validate(entity));\n        }\n\n        private class TestController : ApiController\n        {\n        }\n\n        private class TestEntity\n        {\n            [Range(0, 100)]\n            public int ID { get; set; }\n        }\n\n        private Mock<IAuthorizationFilter> CreateAuthorizationFilterMock(Func<HttpActionContext, CancellationToken, Func<Task<HttpResponseMessage>>, Task<HttpResponseMessage>> implementation)\n        {\n            Mock<IAuthorizationFilter> filterMock = new Mock<IAuthorizationFilter>();\n            filterMock.Setup(f => f.ExecuteAuthorizationFilterAsync(It.IsAny<HttpActionContext>(),\n                                                                    CancellationToken.None,\n                                                                    It.IsAny<Func<Task<HttpResponseMessage>>>()))\n                      .Returns(implementation)\n                      .Verifiable();\n            return filterMock;\n        }\n\n        private Mock<IActionFilter> CreateActionFilterMock(Func<HttpActionContext, CancellationToken, Func<Task<HttpResponseMessage>>, Task<HttpResponseMessage>> implementation)\n        {\n            Mock<IActionFilter> filterMock = new Mock<IActionFilter>();\n            filterMock.Setup(f => f.ExecuteActionFilterAsync(It.IsAny<HttpActionContext>(),\n                                                             CancellationToken.None,\n                                                             It.IsAny<Func<Task<HttpResponseMessage>>>()))\n                      .Returns(implementation)\n                      .Verifiable();\n            return filterMock;\n        }\n\n        private static HttpControllerContext CreateControllerContext()\n        {\n            return new HttpControllerContext();\n        }\n\n        private static IPrincipal CreateDummyPrincipal()\n        {\n            return new Mock<IPrincipal>(MockBehavior.Strict).Object;\n        }\n\n        private static ApiController CreateFakeController()\n        {\n            return new ExceptionlessController();\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private static HttpRequestContext CreateRequestContext()\n        {\n            return new HttpRequestContext();\n        }\n\n        private static IExceptionFilter CreateStubExceptionFilter()\n        {\n            Mock<IExceptionFilter> mock = new Mock<IExceptionFilter>(MockBehavior.Strict);\n            mock\n                .Setup(f => f.ExecuteExceptionFilterAsync(It.IsAny<HttpActionExecutedContext>(),\n                    It.IsAny<CancellationToken>()))\n                .Returns(Task.FromResult(0));\n            return mock.Object;\n        }\n\n        private static Mock<DefaultServices> BuildFilterProvidingServicesMock(HttpConfiguration configuration, HttpActionDescriptor action, params FilterInfo[] filters)\n        {\n            var servicesMock = new Mock<DefaultServices> { CallBase = true };\n            var filterProviderMock = new Mock<IFilterProvider>();\n            servicesMock.Setup(r => r.GetServices(typeof(IFilterProvider))).Returns(new[] { filterProviderMock.Object });\n            filterProviderMock.Setup(fp => fp.GetFilters(configuration, action)).Returns(filters);\n            return servicesMock;\n        }\n\n        public class ExceptionController : ApiController\n        {\n            private readonly Exception _exception;\n\n            public ExceptionController(Exception exception)\n            {\n                _exception = exception;\n            }\n\n            public void Get()\n            {\n                throw _exception;\n            }\n        }\n\n        public class ExceptionlessController : ApiController\n        {\n            public void Get()\n            {\n            }\n        }\n\n        public class SpyDisposeController : ApiController\n        {\n            public static bool DisposeWasCalled = false;\n\n            public SpyDisposeController()\n            {\n            }\n\n            public void Get() { }\n\n            protected override void Dispose(bool disposing)\n            {\n                DisposeWasCalled = true;\n                base.Dispose(disposing);\n            }\n        }\n\n        /// <summary>\n        /// Simple IFilter implementation with AllowMultiple = true\n        /// </summary>\n        public class TestMultiFilter : IFilter\n        {\n            public bool AllowMultiple\n            {\n                get { return true; }\n            }\n        }\n\n        /// <summary>\n        /// Simple IFilter implementation with AllowMultiple = false\n        /// </summary>\n        public class TestUniqueFilter : IFilter\n        {\n            public bool AllowMultiple\n            {\n                get { return false; }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Controllers/ApiControllerTestabilityTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing System.Web.Http.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Controllers\n{\n    public class ApiControllerTestabilityTest\n    {\n        [Fact]\n        public void Post_With_EmptyRequest_And_MockUrlHelper()\n        {\n            // Arrange\n            CustomersController controller = new CustomersController();\n            controller.Configuration = new HttpConfiguration();\n            controller.Request = new HttpRequestMessage();\n\n            Mock<UrlHelper> url = new Mock<UrlHelper>();\n            url.Setup(u => u.Link(\"default\", new { id = 42 })).Returns(\"http://location_header/\").Verifiable();\n            controller.Url = url.Object;\n\n            // Act\n            var result = controller.Post(new Customer { ID = 42 });\n\n            // Assert\n            Customer customer;\n            Assert.Equal(\"http://location_header/\", result.Headers.Location.AbsoluteUri);\n            Assert.True(result.TryGetContentValue<Customer>(out customer));\n            Assert.Equal(42, customer.ID);\n        }\n\n        [Fact]\n        public void Post_With_EmptyConfiguration_ThrowsNoRoute()\n        {\n            // Arrange\n            CustomersController controller = new CustomersController();\n            controller.Configuration = new HttpConfiguration();\n            controller.Request = new HttpRequestMessage();\n\n            // Act\n            Assert.ThrowsArgument(\n                () => controller.Post(new Customer { ID = 42 }),\n                \"name\",\n                \"A route named 'default' could not be found in the route collection.\");\n        }\n\n        [Fact]\n        public void Post_With_InitializeConfigurationAndRequestAndRouteData()\n        {\n            // Arrange\n            CustomersController controller = new CustomersController();\n            controller.Configuration = new HttpConfiguration();\n            controller.Configuration.Routes.MapHttpRoute(\"default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            controller.RequestContext.RouteData = new HttpRouteData(new HttpRoute(), new HttpRouteValueDictionary { { \"controller\", \"Customers\" } });\n            controller.Request = new HttpRequestMessage { RequestUri = new Uri(\"http://locahost/Customers\") };\n\n            // Act\n            var result = controller.Post(new Customer { ID = 42 });\n\n            // Assert\n            Customer customer;\n            Assert.Equal(\"http://locahost/Customers/42\", result.Headers.Location.AbsoluteUri);\n            Assert.True(result.TryGetContentValue<Customer>(out customer));\n            Assert.Equal(42, customer.ID);\n        }\n\n        private class CustomersController : ApiController\n        {\n            public HttpResponseMessage Post(Customer c)\n            {\n                var response = Request.CreateResponse(HttpStatusCode.Created, c);\n                response.Headers.Location = new Uri(Url.Link(\"default\", new { id = c.ID }));\n                return response;\n            }\n        }\n\n        private class Customer\n        {\n            public int ID { get; set; }\n\n            public string Name { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Controllers/Apis/User.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n\nnamespace System.Web.Http\n{\n    public class User\n    {\n        public string FirstName { get; set; }\n        public string LastName { get; set; }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Controllers/Apis/UsersController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\n\nnamespace System.Web.Http\n{\n    public class UsersController : ApiController\n    {\n        public HttpResponseMessage Get()\n        {\n            return new HttpResponseMessage(HttpStatusCode.OK)\n            {\n                Content = new StringContent(\"Default User\")\n            };\n        }\n\n        public HttpResponseMessage Post()\n        {\n            return new HttpResponseMessage(HttpStatusCode.OK)\n            {\n                Content = new StringContent(\"User Posted\")\n            };\n        }\n\n        public HttpResponseMessage Put()\n        {\n            return new HttpResponseMessage(HttpStatusCode.OK)\n            {\n                Content = new StringContent(\"User Updated\")\n            };\n        }\n\n        public HttpResponseMessage Delete()\n        {\n            return new HttpResponseMessage(HttpStatusCode.OK)\n            {\n                Content = new StringContent(\"User Deleted\")\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Controllers/Apis/UsersRpcController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http\n{\n    public class UsersRpcController : ApiController\n    {\n        public User EchoUser(string firstName, string lastName)\n        {\n            return new User()\n            {\n                FirstName = firstName,\n                LastName = lastName,\n            };\n        }\n\n        public Task<User> EchoUserAsync(string firstName, string lastName)\n        {\n            return Task.FromResult(new User()\n            {\n                FirstName = firstName,\n                LastName = lastName,\n            });\n        }\n\n        [Authorize]\n        [HttpGet]\n        public User AddAdmin(string firstName, string lastName)\n        {\n            return new User()\n            {\n                FirstName = firstName,\n                LastName = lastName,\n            };\n        }\n\n        public User RetriveUser(int id)\n        {\n            return new User()\n            {\n                LastName = \"UserLN\" + id,\n                FirstName = \"UserFN\" + id\n            };\n        }\n\n        public User EchoUserObject(User user)\n        {\n            return user;\n        }\n\n        public User Admin()\n        {\n            return new User\n            {\n                FirstName = \"Yao\",\n                LastName = \"Huang\"\n            };\n        }\n\n        public void DeleteAllUsers()\n        {\n        }\n\n        public Task DeleteAllUsersAsync()\n        {\n            return TaskHelpers.Completed();\n        }\n\n        public void AddUser([FromBody] User user)\n        {\n        }\n\n        public Task WrappedTaskReturningMethod()\n        {\n            return Task.FromResult(TaskHelpers.Completed());\n        }\n\n        public object TaskAsObjectReturningMethod()\n        {\n            return TaskHelpers.Completed();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Controllers/AuthenticationFilterResultTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Filters;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Controllers\n{\n    public class AuthenticationFilterResultTests\n    {\n        [Fact]\n        public async Task ExecuteAsync_DelegatesToInnerResult_WhenFiltersIsEmpty()\n        {\n            // Arrange\n            using (HttpResponseMessage expectedResponse = CreateResponse())\n            {\n                HttpActionContext context = CreateContext();\n                ApiController controller = CreateController();\n                IAuthenticationFilter[] filters = new IAuthenticationFilter[0];\n                int calls = 0;\n                CancellationToken cancellationToken;\n                IHttpActionResult innerResult = CreateActionResult((t) =>\n                {\n                    calls++;\n                    cancellationToken = t;\n                    return Task.FromResult(expectedResponse);\n                });\n                IHttpActionResult product = CreateProductUnderTest(context, controller, filters, innerResult);\n                CancellationToken expectedCancellationToken = CreateCancellationToken();\n\n                // Act\n                HttpResponseMessage response = await product.ExecuteAsync(expectedCancellationToken);\n\n                // Assert\n                Assert.Equal(1, calls);\n                Assert.Equal(expectedCancellationToken, cancellationToken);\n                Assert.Same(expectedResponse, response);\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_CallsRequestContextPrincipalGet()\n        {\n            // Arrange\n            HttpActionContext context = CreateContext();\n            ApiController controller = CreateController();\n            IAuthenticationFilter filter = CreateStubFilter();\n            IAuthenticationFilter[] filters = new IAuthenticationFilter[] { filter };\n            int calls = 0;\n            Mock<HttpRequestContext> requestContextMock = new Mock<HttpRequestContext>();\n            requestContextMock.Setup(c => c.Principal).Callback(() =>\n                {\n                    calls++;\n                });\n            controller.RequestContext = requestContextMock.Object;\n            IHttpActionResult innerResult = CreateStubActionResult();\n\n            IHttpActionResult product = CreateProductUnderTest(context, controller, filters, innerResult);\n\n            // Act\n            HttpResponseMessage response = await product.ExecuteAsync(CancellationToken.None);\n\n            // Assert\n            Assert.Equal(1, calls);\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_CallsFilterAuthenticateAsync()\n        {\n            // Arrange\n            HttpActionContext expectedActionContext = CreateContext();\n            ApiController controller = CreateController();\n            int calls = 0;\n            HttpAuthenticationContext authenticationContext = null;\n            CancellationToken cancellationToken = default(CancellationToken);\n            IAuthenticationFilter filter = CreateAuthenticationFilter((c, t) =>\n            {\n                calls++;\n                authenticationContext = c;\n                cancellationToken = t;\n            });\n            IAuthenticationFilter[] filters = new IAuthenticationFilter[] { filter };\n            IPrincipal expectedPrincipal = CreateDummyPrincipal();\n            Mock<HttpRequestContext> requestContextMock = new Mock<HttpRequestContext>(MockBehavior.Strict);\n            requestContextMock.Setup(c => c.Principal).Returns(expectedPrincipal);\n            controller.RequestContext = requestContextMock.Object;\n            IHttpActionResult innerResult = CreateStubActionResult();\n            CancellationToken expectedCancellationToken = CreateCancellationToken();\n\n            IHttpActionResult product = CreateProductUnderTest(expectedActionContext, controller, filters,\n                innerResult);\n\n            // Act\n            await product.ExecuteAsync(expectedCancellationToken);\n\n            // Assert\n            Assert.Equal(1, calls);\n            Assert.NotNull(authenticationContext);\n            HttpActionContext actionContext = authenticationContext.ActionContext;\n            Assert.Same(expectedActionContext, actionContext);\n            IPrincipal principal = authenticationContext.Principal;\n            Assert.Same(expectedPrincipal, principal);\n            Assert.Equal(expectedCancellationToken, cancellationToken);\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_DelegatesToErrorResult_WhenFilterReturnsFailure()\n        {\n            // Arrange\n            using (HttpResponseMessage expectedResponse = CreateResponse())\n            {\n                HttpActionContext context = CreateContext();\n                ApiController controller = CreateController();\n                int calls = 0;\n                CancellationToken cancellationToken;\n                IHttpActionResult errorResult = CreateActionResult((t) =>\n                {\n                    calls++;\n                    cancellationToken = t;\n                    return Task.FromResult(expectedResponse);\n                });\n                IAuthenticationFilter filter = CreateAuthenticationFilter((c, t) =>\n                {\n                    c.ErrorResult = errorResult;\n                });\n                IAuthenticationFilter[] filters = new IAuthenticationFilter[] { filter };\n                IHttpActionResult innerResult = CreateDummyActionResult();\n                IHttpActionResult product = CreateProductUnderTest(context, controller, filters, innerResult);\n                CancellationToken expectedCancellationToken = CreateCancellationToken();\n\n                // Act\n                HttpResponseMessage response = await product.ExecuteAsync(expectedCancellationToken);\n\n                // Assert\n                Assert.Equal(1, calls);\n                Assert.Equal(expectedCancellationToken, cancellationToken);\n                Assert.Same(expectedResponse, response);\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_DoesNotCallSecondFilterAuthenticateOrInnerResult_WhenFirstFilterReturnsFailure()\n        {\n            // Arrange\n            using (HttpResponseMessage expectedResponse = CreateResponse())\n            {\n                HttpActionContext context = CreateContext();\n                ApiController controller = CreateController();\n                IHttpActionResult errorResult = CreateActionResult((t) => Task.FromResult(expectedResponse));\n                IAuthenticationFilter firstFilter = CreateAuthenticationFilter((c, t) =>\n                {\n                    c.ErrorResult = errorResult;\n                });\n                int calls = 0;\n                IAuthenticationFilter secondFilter = CreateAuthenticationFilter((c, t) =>\n                    {\n                        calls++;\n                    });\n                IAuthenticationFilter[] filters = new IAuthenticationFilter[] { firstFilter, secondFilter };\n                IHttpActionResult innerResult = CreateDummyActionResult();\n                IHttpActionResult product = CreateProductUnderTest(context, controller, filters, innerResult);\n                CancellationToken expectedCancellationToken = CreateCancellationToken();\n\n                // Act\n                await product.ExecuteAsync(expectedCancellationToken);\n\n                // Assert\n                Assert.Equal(0, calls);\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_UpdatesRequestContextPrincipal_WhenFilterReturnsSuccess()\n        {\n            // Arrange\n            HttpActionContext context = CreateContext();\n            ApiController controller = CreateController();\n            IPrincipal expectedPrincipal = CreateDummyPrincipal();\n            IAuthenticationFilter filter = CreateAuthenticationFilter((c, t) =>\n            {\n                c.Principal = expectedPrincipal;\n            });\n            IAuthenticationFilter[] filters = new IAuthenticationFilter[] { filter };\n            IPrincipal principal = null;\n            IHttpActionResult innerResult = CreateActionResult((c) =>\n            {\n                principal = controller.User;\n                return Task.FromResult<HttpResponseMessage>(null);\n            });\n\n            IHttpActionResult product = CreateProductUnderTest(context, controller, filters, innerResult);\n\n            // Act\n            await product.ExecuteAsync(CancellationToken.None);\n\n            // Assert\n            Assert.Same(expectedPrincipal, principal);\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_PassesPrincipalFromFirstFilterSuccessToSecondFilter()\n        {\n            // Arrange\n            HttpActionContext context = CreateContext();\n            ApiController controller = CreateController();\n            IPrincipal expectedPrincipal = CreateDummyPrincipal();\n            IAuthenticationFilter firstFilter = CreateAuthenticationFilter((c, t) =>\n            {\n                c.Principal = expectedPrincipal;\n            });\n            IPrincipal principal = null;\n            IAuthenticationFilter secondFilter = CreateAuthenticationFilter((c, t) =>\n            {\n                if (c != null)\n                {\n                    principal = c.Principal;\n                }\n            });\n            IAuthenticationFilter[] filters = new IAuthenticationFilter[] { firstFilter, secondFilter };\n            IHttpActionResult innerResult = CreateStubActionResult();\n\n            IHttpActionResult product = CreateProductUnderTest(context, controller, filters, innerResult);\n\n            // Act\n            await product.ExecuteAsync(CancellationToken.None);\n\n            // Assert\n            Assert.Same(expectedPrincipal, principal);\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_OnlySetsPrincipalOnce_WhenMultipleFiltersReturnSuccess()\n        {\n            // Arrange\n            HttpActionContext context = CreateContext();\n            ApiController controller = CreateController();\n            IPrincipal principal = CreateDummyPrincipal();\n            IAuthenticationFilter filter = CreateAuthenticationFilter((c, t) =>\n            {\n                c.Principal = principal;\n            });\n            IAuthenticationFilter[] filters = new IAuthenticationFilter[] { filter, filter };\n            int calls = 0;\n            Mock<HttpRequestContext> requestContextMock = new Mock<HttpRequestContext>();\n            requestContextMock\n                .SetupSet(c => c.Principal = It.IsAny<IPrincipal>())\n                .Callback<IPrincipal>((i) => { calls++; });\n            controller.RequestContext = requestContextMock.Object;\n            IHttpActionResult innerResult = CreateStubActionResult();\n\n            IHttpActionResult product = CreateProductUnderTest(context, controller, filters, innerResult);\n\n            // Act\n            await product.ExecuteAsync(CancellationToken.None);\n\n            // Assert\n            Assert.Equal(1, calls);\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_DoesNotSetPrincipal_WhenNoFilterReturnsSuccess()\n        {\n            // Arrange\n            HttpActionContext context = CreateContext();\n            ApiController controller = CreateController();\n            IPrincipal principal = CreateDummyPrincipal();\n            IAuthenticationFilter filter = CreateAuthenticationFilter((c, t) => Task.FromResult<object>(null));\n            IAuthenticationFilter[] filters = new IAuthenticationFilter[] { filter, filter };\n            int calls = 0;\n            Mock<HttpRequestContext> requestContextMock = new Mock<HttpRequestContext>();\n            requestContextMock\n                .SetupSet(c => c.Principal = It.IsAny<IPrincipal>())\n                .Callback<IPrincipal>((i) => { calls++; });\n            controller.RequestContext = requestContextMock.Object;\n            IHttpActionResult innerResult = CreateStubActionResult();\n\n            IHttpActionResult product = CreateProductUnderTest(context, controller, filters, innerResult);\n\n            // Act\n            await product.ExecuteAsync(CancellationToken.None);\n\n            // Assert\n            Assert.Equal(0, calls);\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_CallsFilterChallengeAsync_WithInnerResult_WhenNoFilterReturnsFailure()\n        {\n            // Arrange\n            HttpActionContext expectedContext = CreateContext();\n            ApiController controller = CreateController();\n            int calls = 0;\n            HttpActionContext context = null;\n            IHttpActionResult innerResult = null;\n            CancellationToken cancellationToken = default(CancellationToken);\n            IAuthenticationFilter filter = CreateAuthenticationFilterChallenge((c, t) =>\n            {\n                calls++;\n                context = c.ActionContext;\n                innerResult = c.Result;\n                cancellationToken = t;\n            });\n            IAuthenticationFilter[] filters = new IAuthenticationFilter[] { filter };\n            IHttpActionResult expectedInnerResult = CreateStubActionResult();\n            CancellationToken expectedCancellationToken = CreateCancellationToken();\n\n            IHttpActionResult product = CreateProductUnderTest(expectedContext, controller, filters,\n                expectedInnerResult);\n\n            // Act\n            await product.ExecuteAsync(expectedCancellationToken);\n\n            // Assert\n            Assert.Equal(1, calls);\n            Assert.Same(expectedContext, context);\n            Assert.Same(expectedInnerResult, innerResult);\n            Assert.Equal(expectedCancellationToken, cancellationToken);\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_CallsFilterChallengeAsync_WithErrorResult_WhenFilterReturnsFailure()\n        {\n            // Arrange\n            HttpActionContext expectedContext = CreateContext();\n            ApiController controller = CreateController();\n            IHttpActionResult expectedErrorResult = CreateDummyActionResult();\n            int calls = 0;\n            HttpActionContext context = null;\n            IHttpActionResult innerResult = null;\n            CancellationToken cancellationToken = default(CancellationToken);\n            IAuthenticationFilter filter = CreateAuthenticationFilter(\n                (c, t) =>\n                {\n                    c.ErrorResult = expectedErrorResult;\n                },\n                (c, t) =>\n                {\n                    calls++;\n                    context = c.ActionContext;\n                    innerResult = c.Result;\n                    cancellationToken = t;\n\n                    c.Result = CreateStubActionResult();\n                });\n            IAuthenticationFilter[] filters = new IAuthenticationFilter[] { filter };\n            IHttpActionResult originalInnerResult = CreateDummyActionResult();\n            CancellationToken expectedCancellationToken = CreateCancellationToken();\n\n            IHttpActionResult product = CreateProductUnderTest(expectedContext, controller, filters,\n                originalInnerResult);\n\n            // Act\n            await product.ExecuteAsync(expectedCancellationToken);\n\n            // Assert\n            Assert.Equal(1, calls);\n            Assert.Same(expectedContext, context);\n            Assert.Same(expectedErrorResult, innerResult);\n            Assert.Equal(expectedCancellationToken, cancellationToken);\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_CallsSecondFilterChallengeAsync_WithFirstChallengeResult()\n        {\n            // Arrange\n            HttpActionContext expectedContext = CreateContext();\n            ApiController controller = CreateController();\n            IHttpActionResult expectedInnerResult = CreateDummyActionResult();\n            int calls = 0;\n            HttpActionContext context = null;\n            IHttpActionResult result = null;\n            CancellationToken cancellationToken = default(CancellationToken);\n            IAuthenticationFilter firstFilter = CreateAuthenticationFilterChallenge((c, t) =>\n            {\n                c.Result = expectedInnerResult;\n            });\n            IAuthenticationFilter secondFilter = CreateAuthenticationFilterChallenge((c, t) =>\n            {\n                calls++;\n                context = c.ActionContext;\n                result = c.Result;\n                cancellationToken = t;\n\n                c.Result = CreateStubActionResult();\n            });\n            IAuthenticationFilter[] filters = new IAuthenticationFilter[] { firstFilter, secondFilter };\n            IHttpActionResult originalInnerResult = CreateDummyActionResult();\n            CancellationToken expectedCancellationToken = CreateCancellationToken();\n\n            IHttpActionResult product = CreateProductUnderTest(expectedContext, controller, filters,\n                originalInnerResult);\n\n            // Act\n            await product.ExecuteAsync(expectedCancellationToken);\n\n            // Assert\n            Assert.Equal(1, calls);\n            Assert.Same(expectedContext, context);\n            Assert.Same(expectedInnerResult, result);\n            Assert.Equal(expectedCancellationToken, cancellationToken);\n        }\n\n        private static IHttpActionResult CreateActionResult(\n            Func<CancellationToken, Task<HttpResponseMessage>> executeAsync)\n        {\n            Mock<IHttpActionResult> mock = new Mock<IHttpActionResult>(MockBehavior.Strict);\n            CancellationToken cancellationToken;\n            mock.Setup(r => r.ExecuteAsync(It.IsAny<CancellationToken>()))\n                .Callback<CancellationToken>((t) => { cancellationToken = t; })\n                .Returns(() => executeAsync.Invoke(cancellationToken));\n            return mock.Object;\n        }\n\n        private static IAuthenticationFilter CreateAuthenticationFilter(\n            Action<HttpAuthenticationContext, CancellationToken> authenticate)\n        {\n            Mock<IAuthenticationFilter> mock = new Mock<IAuthenticationFilter>();\n            mock.Setup(f => f.AuthenticateAsync(It.IsAny<HttpAuthenticationContext>(), It.IsAny<CancellationToken>()))\n                .Callback<HttpAuthenticationContext, CancellationToken>((c, t) =>\n                {\n                    authenticate.Invoke(c, t);\n                })\n                .Returns(() => Task.FromResult<object>(null));\n            mock.Setup(f => f.ChallengeAsync(It.IsAny<HttpAuthenticationChallengeContext>(),\n                It.IsAny<CancellationToken>()))\n                .Returns(() => Task.FromResult<object>(null));\n            return mock.Object;\n        }\n\n        private static IAuthenticationFilter CreateAuthenticationFilter(\n            Action<HttpAuthenticationContext, CancellationToken> authenticate,\n            Action<HttpAuthenticationChallengeContext, CancellationToken> challenge)\n        {\n            Mock<IAuthenticationFilter> mock = new Mock<IAuthenticationFilter>();\n            mock.Setup(f => f.AuthenticateAsync(It.IsAny<HttpAuthenticationContext>(), It.IsAny<CancellationToken>()))\n                .Callback<HttpAuthenticationContext, CancellationToken>((c, t) =>\n                    {\n                        authenticate.Invoke(c, t);\n                    })\n                .Returns(() => Task.FromResult<object>(null));\n            mock.Setup(f => f.ChallengeAsync(It.IsAny<HttpAuthenticationChallengeContext>(),\n                It.IsAny<CancellationToken>()))\n                .Callback<HttpAuthenticationChallengeContext, CancellationToken>((c, t) =>\n                    {\n                        challenge.Invoke(c, t);\n                    })\n                .Returns(() => Task.FromResult<object>(null));\n            return mock.Object;\n        }\n\n        private static IAuthenticationFilter CreateAuthenticationFilterChallenge(\n            Action<HttpAuthenticationChallengeContext, CancellationToken> challenge)\n        {\n            Mock<IAuthenticationFilter> mock = new Mock<IAuthenticationFilter>();\n            mock.Setup(f => f.AuthenticateAsync(It.IsAny<HttpAuthenticationContext>(), It.IsAny<CancellationToken>()))\n                .Returns(() => Task.FromResult<object>(null));\n            mock.Setup(f => f.ChallengeAsync(It.IsAny<HttpAuthenticationChallengeContext>(),\n                It.IsAny<CancellationToken>()))\n                .Callback<HttpAuthenticationChallengeContext, CancellationToken>((c, t) =>\n                {\n                    challenge.Invoke(c, t);\n                })\n                .Returns(() => Task.FromResult<object>(null));\n            return mock.Object;\n        }\n\n        private static CancellationToken CreateCancellationToken()\n        {\n            return new CancellationToken(canceled: true);\n        }\n\n        private static HttpActionContext CreateContext()\n        {\n            return new HttpActionContext();\n        }\n\n        private static ApiController CreateController()\n        {\n            return new Mock<ApiController>().Object;\n        }\n\n        private static IHttpActionResult CreateDummyActionResult()\n        {\n            return new Mock<IHttpActionResult>(MockBehavior.Strict).Object;\n        }\n\n        private static IPrincipal CreateDummyPrincipal()\n        {\n            return new Mock<IPrincipal>(MockBehavior.Strict).Object;\n        }\n\n        private static AuthenticationFilterResult CreateProductUnderTest(HttpActionContext context,\n            ApiController controller, IAuthenticationFilter[] filters, IHttpActionResult innerResult)\n        {\n            return new AuthenticationFilterResult(context, controller, filters, innerResult);\n        }\n\n        private static HttpResponseMessage CreateResponse()\n        {\n            return new HttpResponseMessage();\n        }\n\n        private static IHttpActionResult CreateStubActionResult()\n        {\n            Mock<IHttpActionResult> mock = new Mock<IHttpActionResult>(MockBehavior.Strict);\n            HttpResponseMessage response = null;\n            mock.Setup(r => r.ExecuteAsync(It.IsAny<CancellationToken>())).Returns(() => Task.FromResult(response));\n            return mock.Object;\n        }\n\n        private static IAuthenticationFilter CreateStubFilter()\n        {\n            Mock<IAuthenticationFilter> mock = new Mock<IAuthenticationFilter>(MockBehavior.Strict);\n            mock.Setup(f => f.AuthenticateAsync(It.IsAny<HttpAuthenticationContext>(), It.IsAny<CancellationToken>()))\n                .Returns(() => Task.FromResult<object>(null));\n            mock.Setup(f => f.ChallengeAsync(It.IsAny<HttpAuthenticationChallengeContext>(),\n                It.IsAny<CancellationToken>()))\n                .Returns(() => Task.FromResult<object>(null));\n            return mock.Object;\n        }\n\n        private static HttpRequestContext CreateStubRequestContext()\n        {\n            Mock<HttpRequestContext> mock = new Mock<HttpRequestContext>(MockBehavior.Strict);\n            mock.Setup(c => c.Principal).Returns((IPrincipal)null);\n            return mock.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Controllers/AuthorizationFilterResultTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Filters;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Controllers\n{\n    public class AuthorizationFilterResultTests\n    {\n        [Fact]\n        public async Task ExecuteAsync_ChainsFiltersInOrderFollowedByInnerActionContinuation()\n        {\n            // Arrange\n            HttpActionContext actionContextInstance = ContextUtil.CreateActionContext();\n            List<string> log = new List<string>();\n            Mock<IAuthorizationFilter> globalFilterMock = CreateAuthorizationFilterMock((ctx, ct, continuation) =>\n            {\n                log.Add(\"globalFilter\");\n                return continuation();\n            });\n            Mock<IAuthorizationFilter> actionFilterMock = CreateAuthorizationFilterMock((ctx, ct, continuation) =>\n            {\n                log.Add(\"actionFilter\");\n                return continuation();\n            });\n            Mock<IHttpActionResult> innerResultMock = new Mock<IHttpActionResult>();\n            innerResultMock.Setup(r => r.ExecuteAsync(It.IsAny<CancellationToken>())).Returns(() =>\n            {\n                log.Add(\"innerAction\");\n                return Task.FromResult<HttpResponseMessage>(null);\n            });\n            IHttpActionResult innerResult = innerResultMock.Object;\n            var filters = new IAuthorizationFilter[] {\n                globalFilterMock.Object,\n                actionFilterMock.Object,\n            };\n            IHttpActionResult authorizationFilter = new AuthorizationFilterResult(actionContextInstance, filters,\n                innerResult);\n\n            // Act\n            await authorizationFilter.ExecuteAsync(CancellationToken.None);\n\n            // Assert\n            Assert.Equal(new[] { \"globalFilter\", \"actionFilter\", \"innerAction\" }, log.ToArray());\n            globalFilterMock.Verify();\n            actionFilterMock.Verify();\n        }\n\n        private Mock<IAuthorizationFilter> CreateAuthorizationFilterMock(Func<HttpActionContext, CancellationToken,\n            Func<Task<HttpResponseMessage>>, Task<HttpResponseMessage>> implementation)\n        {\n            Mock<IAuthorizationFilter> filterMock = new Mock<IAuthorizationFilter>();\n            filterMock.Setup(f => f.ExecuteAuthorizationFilterAsync(It.IsAny<HttpActionContext>(),\n                                                                    CancellationToken.None,\n                                                                    It.IsAny<Func<Task<HttpResponseMessage>>>()))\n                      .Returns(implementation)\n                      .Verifiable();\n            return filterMock;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Controllers/ExceptionFilterResultTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Results;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Controllers\n{\n    public class ExceptionFilterResultTests\n    {\n        [Fact]\n        public async Task ExecuteAsync_IfInnerResultTaskIsSuccessful_ReturnsSuccessTask()\n        {\n            // Arrange\n            List<string> log = new List<string>();\n            HttpActionContext actionContext = ContextUtil.CreateActionContext();\n            var exceptionFilter = CreateExceptionFilter((ec, ct) =>\n            {\n                log.Add(\"exceptionFilter\");\n                return Task.Factory.StartNew(() => { });\n            });\n            var filters = new IExceptionFilter[] { exceptionFilter };\n            IExceptionLogger exceptionLogger = CreateDummyExceptionLogger();\n            IExceptionHandler exceptionHandler = CreateDummyExceptionHandler();\n            var expectedResponse = new HttpResponseMessage();\n            var actionResult = CreateStubActionResult(Task.FromResult(expectedResponse));\n\n            IHttpActionResult product = CreateProductUnderTest(actionContext, filters, exceptionLogger,\n                exceptionHandler, actionResult);\n\n            // Act\n            var response = await product.ExecuteAsync(CancellationToken.None);\n\n            // Assert\n            Assert.Same(expectedResponse, response);\n            Assert.Equal(new string[] { }, log.ToArray());\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_IfInnerResultTaskIsCanceled_ReturnsCanceledTask()\n        {\n            // Arrange\n            List<string> log = new List<string>();\n            HttpActionContext actionContext = ContextUtil.CreateActionContext();\n\n            // ExceptionFilters still have a chance to see the cancellation exception\n            var exceptionFilter = CreateExceptionFilter((ec, ct) =>\n            {\n                log.Add(\"exceptionFilter\");\n                return Task.Factory.StartNew(() => { });\n            });\n\n            var filters = new IExceptionFilter[] { exceptionFilter };\n            IExceptionLogger exceptionLogger = new Mock<IExceptionLogger>(MockBehavior.Strict).Object;\n            IExceptionHandler exceptionHandler = new Mock<IExceptionHandler>(MockBehavior.Strict).Object;\n\n            var actionResult = CreateStubActionResult(TaskHelpers.Canceled<HttpResponseMessage>());\n\n            IHttpActionResult product = CreateProductUnderTest(actionContext, filters, exceptionLogger,\n                exceptionHandler, actionResult);\n\n            // Act & Assert\n            await Assert.ThrowsAsync<TaskCanceledException>(() => product.ExecuteAsync(CancellationToken.None));\n\n            Assert.Equal(new string[] { \"exceptionFilter\" }, log.ToArray());\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_IfInnerResultTaskIsFaulted_ExecutesFiltersAndReturnsFaultedTaskIfNotHandled()\n        {\n            // Arrange\n            List<string> log = new List<string>();\n            HttpActionContext actionContext = ContextUtil.CreateActionContext();\n            Exception exceptionSeenByFilter = null;\n            var exceptionFilter = CreateExceptionFilter((ec, ct) =>\n            {\n                exceptionSeenByFilter = ec.Exception;\n                log.Add(\"exceptionFilter\");\n                return Task.Factory.StartNew(() => { });\n            });\n            var filters = new IExceptionFilter[] { exceptionFilter };\n            IExceptionLogger exceptionLogger = CreateExceptionLogger((c, i) =>\n            {\n                log.Add(\"exceptionLogger\");\n                return Task.FromResult(0);\n            });\n            IExceptionHandler exceptionHandler = CreateStubExceptionHandler();\n            var expectedException = new Exception();\n            var actionResult = CreateStubActionResult(TaskHelpers.FromError<HttpResponseMessage>(expectedException));\n\n            IHttpActionResult product = CreateProductUnderTest(actionContext, filters, exceptionLogger,\n                exceptionHandler, actionResult);\n\n            // Act & Assert\n            var exception = await Assert.ThrowsAsync<Exception>(() => product.ExecuteAsync(CancellationToken.None));\n\n            Assert.Same(expectedException, exception);\n            Assert.Same(expectedException, exceptionSeenByFilter);\n            Assert.Equal(new string[] { \"exceptionLogger\", \"exceptionFilter\" }, log.ToArray());\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_IfInnerResultTaskIsFaulted_CallsExceptionLogger()\n        {\n            // Arrange\n            Exception expectedException = CreateException();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpActionContext expectedActionContext = CreateActionContext(request);\n                IExceptionFilter[] filters = new IExceptionFilter[0];\n\n                Mock<IExceptionLogger> exceptionLoggerMock = CreateStubExceptionLoggerMock();\n                IExceptionLogger exceptionLogger = exceptionLoggerMock.Object;\n\n                IExceptionHandler exceptionHandler = CreateStubExceptionHandler();\n                IHttpActionResult innerResult = CreateStubActionResult(\n                    CreateFaultedTask<HttpResponseMessage>(expectedException));\n\n                IHttpActionResult product = CreateProductUnderTest(expectedActionContext, filters, exceptionLogger,\n                    exceptionHandler, innerResult);\n\n                CancellationToken cancellationToken = CreateCancellationToken();\n\n                // Act\n                await Assert.ThrowsAsync<InvalidOperationException>(() => product.ExecuteAsync(cancellationToken));\n\n                // Assert\n                Func<ExceptionContext, bool> exceptionContextMatches = (c) =>\n                    c != null\n                    && c.Exception == expectedException\n                    && c.CatchBlock == ExceptionCatchBlocks.IExceptionFilter\n                    && c.ActionContext == expectedActionContext;\n\n                exceptionLoggerMock.Verify(l => l.LogAsync(\n                    It.Is<ExceptionLoggerContext>(c => exceptionContextMatches(c.ExceptionContext)),\n                    cancellationToken), Times.Once());\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_IfInnerResultTaskIsFaulted_ExecutesFiltersAndReturnsResultIfHandled()\n        {\n            // Arrange\n            List<string> log = new List<string>();\n            HttpActionContext actionContext = ContextUtil.CreateActionContext();\n            var exception = new Exception();\n            HttpResponseMessage globalFilterResponse = new HttpResponseMessage();\n            HttpResponseMessage actionFilterResponse = new HttpResponseMessage();\n            HttpResponseMessage resultSeenByGlobalFilter = null;\n            var globalFilter = CreateExceptionFilter((ec, ct) =>\n            {\n                log.Add(\"globalFilter\");\n                resultSeenByGlobalFilter = ec.Response;\n                ec.Response = globalFilterResponse;\n                return Task.Factory.StartNew(() => { });\n            });\n            var actionFilter = CreateExceptionFilter((ec, ct) =>\n            {\n                log.Add(\"actionFilter\");\n                ec.Response = actionFilterResponse;\n                return Task.Factory.StartNew(() => { });\n            });\n            var filters = new IExceptionFilter[] { globalFilter, actionFilter };\n            IExceptionLogger exceptionLogger = CreateStubExceptionLogger();\n            IExceptionHandler exceptionHandler = CreateDummyExceptionHandler();\n            var actionResult = CreateStubActionResult(TaskHelpers.FromError<HttpResponseMessage>(exception));\n\n            IHttpActionResult product = CreateProductUnderTest(actionContext, filters, exceptionLogger,\n                exceptionHandler, actionResult);\n\n            // Act\n            var response = await product.ExecuteAsync(CancellationToken.None);\n\n            // Assert\n            Assert.Same(globalFilterResponse, response);\n            Assert.Same(actionFilterResponse, resultSeenByGlobalFilter);\n            Assert.Equal(new string[] { \"actionFilter\", \"globalFilter\" }, log.ToArray());\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_IfInnerResultTaskIsFaulted_AndNoFilterHandles_RunsHandlerAndReturnsResultIfHandled()\n        {\n            // Arrange\n            List<string> log = new List<string>();\n            Exception expectedException = CreateException();\n\n            using (HttpRequestMessage request = CreateRequest())\n            using (HttpResponseMessage expectedResponse = CreateResponse())\n            {\n                HttpActionContext expectedActionContext = CreateActionContext(request);\n\n                IExceptionFilter filter = CreateExceptionFilter((c, i) =>\n                {\n                    log.Add(\"filter\");\n                    return Task.FromResult(0);\n                });\n\n                IExceptionFilter[] filters = new IExceptionFilter[] { filter };\n\n                IExceptionLogger exceptionLogger = CreateStubExceptionLogger();\n\n                Mock<IExceptionHandler> exceptionHandlerMock = new Mock<IExceptionHandler>();\n                exceptionHandlerMock\n                    .Setup(l => l.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                    .Callback<ExceptionHandlerContext, CancellationToken>((c, i) =>\n                    {\n                        log.Add(\"handler\");\n                        c.Result = new ResponseMessageResult(expectedResponse);\n                    })\n                    .Returns(Task.FromResult(0));\n                IExceptionHandler exceptionHandler = exceptionHandlerMock.Object;\n\n                IHttpActionResult innerResult = CreateStubActionResult(\n                    CreateFaultedTask<HttpResponseMessage>(expectedException));\n\n                IHttpActionResult product = CreateProductUnderTest(expectedActionContext, filters, exceptionLogger,\n                    exceptionHandler, innerResult);\n\n                CancellationToken cancellationToken = CreateCancellationToken();\n\n                // Act\n                HttpResponseMessage response = await product.ExecuteAsync(cancellationToken);\n\n                // Assert\n                Func<ExceptionContext, bool> exceptionContextMatches = (c) =>\n                    c != null\n                    && c.Exception == expectedException\n                    && c.CatchBlock == ExceptionCatchBlocks.IExceptionFilter\n                    && c.ActionContext == expectedActionContext;\n\n                exceptionHandlerMock.Verify(h => h.HandleAsync(\n                    It.Is<ExceptionHandlerContext>((c) => exceptionContextMatches(c.ExceptionContext)),\n                    cancellationToken), Times.Once());\n                Assert.Same(expectedResponse, response);\n                Assert.Equal(new string[] { \"filter\", \"handler\" }, log.ToArray());\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_IfFilterChangesException_ThrowsUpdatedException()\n        {\n            // Arrange\n            Exception expectedException = new NotImplementedException();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpActionContext context = CreateActionContext(request);\n\n                Mock<IExceptionFilter> filterMock = new Mock<IExceptionFilter>();\n                filterMock\n                    .Setup(f => f.ExecuteExceptionFilterAsync(It.IsAny<HttpActionExecutedContext>(),\n                        It.IsAny<CancellationToken>()))\n                    .Callback<HttpActionExecutedContext, CancellationToken>((c, t) =>\n                    {\n                        c.Exception = expectedException;\n                    })\n                    .Returns(() => Task.FromResult<object>(null));\n                IExceptionFilter filter = filterMock.Object;\n                IExceptionFilter[] filters = new IExceptionFilter[] { filter };\n\n                IExceptionLogger exceptionLogger = CreateStubExceptionLogger();\n                IExceptionHandler exceptionHandler = CreateStubExceptionHandler();\n\n                IHttpActionResult innerResult = CreateStubActionResult(\n                    CreateFaultedTask<HttpResponseMessage>(CreateException()));\n\n                IHttpActionResult product = CreateProductUnderTest(context, filters, exceptionLogger, exceptionHandler,\n                    innerResult);\n\n                // Act & Assert\n                var exception = await Assert.ThrowsAsync<NotImplementedException>(\n                    () => product.ExecuteAsync(CancellationToken.None));\n                Assert.Same(expectedException, exception);\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_IfFaultedTaskExceptionIsUnhandled_PreservesExceptionStackTrace()\n        {\n            // Arrange\n            Exception originalException = CreateExceptionWithStackTrace();\n            string expectedStackTrace = originalException.StackTrace;\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpActionContext context = CreateActionContext(request);\n                IExceptionFilter[] filters = new IExceptionFilter[0];\n\n                IExceptionLogger exceptionLogger = CreateStubExceptionLogger();\n                IExceptionHandler exceptionHandler = CreateStubExceptionHandler();\n\n                IHttpActionResult innerResult = CreateStubActionResult(\n                    CreateFaultedTask<HttpResponseMessage>(originalException));\n\n                IHttpActionResult product = CreateProductUnderTest(context, filters, exceptionLogger, exceptionHandler,\n                    innerResult);\n\n                // Act & Assert\n                var exception = await Assert.ThrowsAsync<InvalidOperationException>(\n                    () => product.ExecuteAsync(CancellationToken.None));\n\n                Assert.NotNull(expectedStackTrace);\n                Assert.NotNull(exception);\n                Assert.NotNull(exception.StackTrace);\n                Assert.StartsWith(expectedStackTrace, exception.StackTrace);\n            }\n        }\n\n        private static HttpActionContext CreateActionContext()\n        {\n            return new HttpActionContext();\n        }\n\n        private static HttpActionContext CreateActionContext(HttpRequestMessage request)\n        {\n            HttpActionContext actionContext = CreateActionContext();\n            actionContext.ControllerContext = new HttpControllerContext()\n            {\n                Request = request\n            };\n            return actionContext;\n        }\n\n        private static CancellationToken CreateCancellationToken()\n        {\n            CancellationTokenSource source = new CancellationTokenSource();\n            return source.Token;\n        }\n\n        private static IExceptionHandler CreateDummyExceptionHandler()\n        {\n            return new Mock<IExceptionHandler>(MockBehavior.Strict).Object;\n        }\n\n        private static IExceptionLogger CreateDummyExceptionLogger()\n        {\n            return new Mock<IExceptionLogger>(MockBehavior.Strict).Object;\n        }\n\n        private IExceptionFilter CreateExceptionFilter(\n            Func<HttpActionExecutedContext, CancellationToken, Task> executeExceptionFilterAsync)\n        {\n            Mock<IExceptionFilter> mock = new Mock<IExceptionFilter>();\n            mock\n                .Setup(f => f.ExecuteExceptionFilterAsync(It.IsAny<HttpActionExecutedContext>(),\n                    It.IsAny<CancellationToken>()))\n                .Returns(executeExceptionFilterAsync);\n            return mock.Object;\n        }\n\n        private static IExceptionLogger CreateExceptionLogger(\n            Func<ExceptionLoggerContext, CancellationToken, Task> logAsync)\n        {\n            Mock<IExceptionLogger> mock = new Mock<IExceptionLogger>();\n            mock\n                .Setup(l => l.LogAsync(It.IsAny<ExceptionLoggerContext>(), It.IsAny<CancellationToken>()))\n                .Returns(logAsync);\n            return mock.Object;\n        }\n\n        private static Exception CreateException()\n        {\n            return new InvalidOperationException();\n        }\n\n        private static Exception CreateExceptionWithStackTrace()\n        {\n            Exception exception;\n\n            try\n            {\n                throw CreateException();\n            }\n            catch (Exception ex)\n            {\n                exception = ex;\n            }\n\n            return exception;\n        }\n\n        private static Task<TResult> CreateFaultedTask<TResult>(Exception exception)\n        {\n            TaskCompletionSource<TResult> source = new TaskCompletionSource<TResult>();\n            source.SetException(exception);\n            return source.Task;\n        }\n\n        private static ExceptionFilterResult CreateProductUnderTest(HttpActionContext context, IExceptionFilter[] filters,\n            IExceptionLogger exceptionLogger, IExceptionHandler exceptionHandler, IHttpActionResult innerResult)\n        {\n            return new ExceptionFilterResult(context, filters, exceptionLogger, exceptionHandler, innerResult);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private static HttpResponseMessage CreateResponse()\n        {\n            return new HttpResponseMessage();\n        }\n\n        private static IHttpActionResult CreateStubActionResult(Task<HttpResponseMessage> task)\n        {\n            Mock<IHttpActionResult> actionResultMock = new Mock<IHttpActionResult>(MockBehavior.Strict);\n            actionResultMock.Setup(r => r.ExecuteAsync(It.IsAny<CancellationToken>())).Returns(() =>\n            {\n                return task;\n            });\n            return actionResultMock.Object;\n        }\n\n        private static IExceptionHandler CreateStubExceptionHandler()\n        {\n            return CreateStubExceptionHandlerMock().Object;\n        }\n\n        private static Mock<IExceptionHandler> CreateStubExceptionHandlerMock()\n        {\n            Mock<IExceptionHandler> mock = new Mock<IExceptionHandler>();\n            mock\n                .Setup(l => l.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                .Returns(Task.FromResult<HttpResponseMessage>(null));\n            return mock;\n        }\n\n        private static IExceptionLogger CreateStubExceptionLogger()\n        {\n            return CreateStubExceptionLoggerMock().Object;\n        }\n\n        private static Mock<IExceptionLogger> CreateStubExceptionLoggerMock()\n        {\n            Mock<IExceptionLogger> mock = new Mock<IExceptionLogger>();\n            mock\n                .Setup(l => l.LogAsync(It.IsAny<ExceptionLoggerContext>(), It.IsAny<CancellationToken>()))\n                .Returns(Task.FromResult(0));\n            return mock;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Controllers/FilterGroupingTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Filters;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Controllers\n{\n    public class FilterGroupingTests\n    {\n        [Fact]\n        public void ActionFilters_ReturnsEmptyArray_WhenFiltersIsEmpty()\n        {\n            // Arrange\n            IEnumerable<FilterInfo> filters = CreateEmptyFilters();\n            FilterGrouping product = CreateProductUnderTest(filters);\n\n            // Act\n            IActionFilter[] actionFilters = product.ActionFilters;\n\n            // Assert\n            Assert.NotNull(actionFilters);\n            Assert.Empty(actionFilters);\n        }\n\n        [Fact]\n        public void ActionFilters_ReturnsActionFilters()\n        {\n            // Arrange\n            IActionFilter expectedGlobalFilter = CreateDummyActionFilter();\n            FilterInfo globalFilter = new FilterInfo(expectedGlobalFilter, FilterScope.Global);\n            IActionFilter expectedControllerFilter = CreateDummyActionFilter();\n            FilterInfo controllerFilter = new FilterInfo(expectedControllerFilter, FilterScope.Controller);\n            IActionFilter expectedActionFilter = CreateDummyActionFilter();\n            FilterInfo actionFilter = new FilterInfo(expectedActionFilter, FilterScope.Action);\n            IEnumerable<FilterInfo> filters = new FilterInfo[] { globalFilter, controllerFilter, actionFilter };\n            FilterGrouping product = CreateProductUnderTest(filters);\n\n            // Act\n            IActionFilter[] actionFilters = product.ActionFilters;\n\n            // Assert\n            Assert.NotNull(actionFilters);\n            Assert.Equal(3, actionFilters.Length);\n            Assert.Same(expectedGlobalFilter, actionFilters[0]);\n            Assert.Same(expectedControllerFilter, actionFilters[1]);\n            Assert.Same(expectedActionFilter, actionFilters[2]);\n        }\n\n        [Fact]\n        public void ActionFilters_ReturnsAllActionFilters_WhenOverrideScopeIsGlobal()\n        {\n            // Arrange\n            IActionFilter expectedGlobalFilter = CreateDummyActionFilter();\n            FilterInfo globalFilter = new FilterInfo(expectedGlobalFilter, FilterScope.Global);\n            IActionFilter expectedControllerFilter = CreateDummyActionFilter();\n            FilterInfo controllerFilter = new FilterInfo(expectedControllerFilter, FilterScope.Controller);\n            IActionFilter expectedActionFilter = CreateDummyActionFilter();\n            FilterInfo actionFilter = new FilterInfo(expectedActionFilter, FilterScope.Action);\n            FilterInfo overrideFilter = new FilterInfo(CreateOverride(typeof(IActionFilter)), FilterScope.Global);\n            IEnumerable<FilterInfo> filters = new FilterInfo[] { globalFilter, controllerFilter, actionFilter, overrideFilter };\n            FilterGrouping product = CreateProductUnderTest(filters);\n\n            // Act\n            IActionFilter[] actionFilters = product.ActionFilters;\n\n            // Assert\n            Assert.NotNull(actionFilters);\n            Assert.Equal(3, actionFilters.Length);\n            Assert.Same(expectedGlobalFilter, actionFilters[0]);\n            Assert.Same(expectedControllerFilter, actionFilters[1]);\n            Assert.Same(expectedActionFilter, actionFilters[2]);\n        }\n\n        [Fact]\n        public void ActionFilters_ReturnsControllerAndBelowActionFilters_WhenOverrideScopeIsController()\n        {\n            // Arrange\n            IActionFilter expectedGlobalFilter = CreateDummyActionFilter();\n            FilterInfo globalFilter = new FilterInfo(expectedGlobalFilter, FilterScope.Global);\n            IActionFilter expectedControllerFilter = CreateDummyActionFilter();\n            FilterInfo controllerFilter = new FilterInfo(expectedControllerFilter, FilterScope.Controller);\n            IActionFilter expectedActionFilter = CreateDummyActionFilter();\n            FilterInfo actionFilter = new FilterInfo(expectedActionFilter, FilterScope.Action);\n            FilterInfo overrideFilter = new FilterInfo(CreateOverride(typeof(IActionFilter)), FilterScope.Controller);\n            IEnumerable<FilterInfo> filters = new FilterInfo[] { globalFilter, controllerFilter, actionFilter, overrideFilter };\n            FilterGrouping product = CreateProductUnderTest(filters);\n\n            // Act\n            IActionFilter[] actionFilters = product.ActionFilters;\n\n            // Assert\n            Assert.NotNull(actionFilters);\n            Assert.Equal(2, actionFilters.Length);\n            Assert.Same(expectedControllerFilter, actionFilters[0]);\n            Assert.Same(expectedActionFilter, actionFilters[1]);\n        }\n\n        [Fact]\n        public void ActionFilters_ReturnsActionScopeActionFilters_WhenOverrideScopeIsAction()\n        {\n            // Arrange\n            IActionFilter expectedGlobalFilter = CreateDummyActionFilter();\n            FilterInfo globalFilter = new FilterInfo(expectedGlobalFilter, FilterScope.Global);\n            IActionFilter expectedControllerFilter = CreateDummyActionFilter();\n            FilterInfo controllerFilter = new FilterInfo(expectedControllerFilter, FilterScope.Controller);\n            IActionFilter expectedActionFilter = CreateDummyActionFilter();\n            FilterInfo actionFilter = new FilterInfo(expectedActionFilter, FilterScope.Action);\n            FilterInfo overrideFilter = new FilterInfo(CreateOverride(typeof(IActionFilter)), FilterScope.Action);\n            IEnumerable<FilterInfo> filters = new FilterInfo[] { globalFilter, controllerFilter, actionFilter, overrideFilter };\n            FilterGrouping product = CreateProductUnderTest(filters);\n\n            // Act\n            IActionFilter[] actionFilters = product.ActionFilters;\n\n            // Assert\n            Assert.NotNull(actionFilters);\n            IActionFilter singleFilter = Assert.Single(actionFilters);\n            Assert.Same(expectedActionFilter, singleFilter);\n        }\n\n        [Fact]\n        public void ActionFilters_ReturnsAllActionFilters_WhenOtherFilterIsOverriddenAtActionLevel()\n        {\n            // Arrange\n            IActionFilter expectedGlobalFilter = CreateDummyActionFilter();\n            FilterInfo globalFilter = new FilterInfo(expectedGlobalFilter, FilterScope.Global);\n            IActionFilter expectedControllerFilter = CreateDummyActionFilter();\n            FilterInfo controllerFilter = new FilterInfo(expectedControllerFilter, FilterScope.Controller);\n            IActionFilter expectedActionFilter = CreateDummyActionFilter();\n            FilterInfo actionFilter = new FilterInfo(expectedActionFilter, FilterScope.Action);\n            FilterInfo overrideFilter = new FilterInfo(CreateOverride(typeof(object)), FilterScope.Action);\n            IEnumerable<FilterInfo> filters = new FilterInfo[] { globalFilter, controllerFilter, actionFilter, overrideFilter };\n            FilterGrouping product = CreateProductUnderTest(filters);\n\n            // Act\n            IActionFilter[] actionFilters = product.ActionFilters;\n\n            // Assert\n            Assert.NotNull(actionFilters);\n            Assert.Equal(3, actionFilters.Length);\n            Assert.Same(expectedGlobalFilter, actionFilters[0]);\n            Assert.Same(expectedControllerFilter, actionFilters[1]);\n            Assert.Same(expectedActionFilter, actionFilters[2]);\n        }\n\n        [Fact]\n        public void AuthorizationFilters_ReturnsActionScopeAuthorizationFilters_WhenOverrideScopeIsAction()\n        {\n            // Arrange\n            IAuthorizationFilter expectedGlobalFilter = CreateDummyAuthorizationFilter();\n            FilterInfo globalFilter = new FilterInfo(expectedGlobalFilter, FilterScope.Global);\n            IAuthorizationFilter expectedControllerFilter = CreateDummyAuthorizationFilter();\n            FilterInfo controllerFilter = new FilterInfo(expectedControllerFilter, FilterScope.Controller);\n            IAuthorizationFilter expectedActionFilter = CreateDummyAuthorizationFilter();\n            FilterInfo actionFilter = new FilterInfo(expectedActionFilter, FilterScope.Action);\n            FilterInfo overrideFilter = new FilterInfo(CreateOverride(typeof(IAuthorizationFilter)),\n                FilterScope.Action);\n            IEnumerable<FilterInfo> filters = new FilterInfo[] { globalFilter, controllerFilter, actionFilter, overrideFilter };\n            FilterGrouping product = CreateProductUnderTest(filters);\n\n            // Act\n            IAuthorizationFilter[] authorizationFilters = product.AuthorizationFilters;\n\n            // Assert\n            Assert.NotNull(authorizationFilters);\n            IAuthorizationFilter authorizationFilter = Assert.Single(authorizationFilters);\n            Assert.Same(expectedActionFilter, authorizationFilter);\n        }\n\n        [Fact]\n        public void AuthenticationFilters_ReturnsActionScopeAuthenticationFilters_WhenOverrideScopeIsAction()\n        {\n            // Arrange\n            IAuthenticationFilter expectedGlobalFilter = CreateDummyAuthenticationFilter();\n            FilterInfo globalFilter = new FilterInfo(expectedGlobalFilter, FilterScope.Global);\n            IAuthenticationFilter expectedControllerFilter = CreateDummyAuthenticationFilter();\n            FilterInfo controllerFilter = new FilterInfo(expectedControllerFilter, FilterScope.Controller);\n            IAuthenticationFilter expectedActionFilter = CreateDummyAuthenticationFilter();\n            FilterInfo actionFilter = new FilterInfo(expectedActionFilter, FilterScope.Action);\n            FilterInfo overrideFilter = new FilterInfo(CreateOverride(typeof(IAuthenticationFilter)),\n                FilterScope.Action);\n            IEnumerable<FilterInfo> filters = new FilterInfo[] { globalFilter, controllerFilter, actionFilter, overrideFilter };\n            FilterGrouping product = CreateProductUnderTest(filters);\n\n            // Act\n            IAuthenticationFilter[] authenticationFilters = product.AuthenticationFilters;\n\n            // Assert\n            Assert.NotNull(authenticationFilters);\n            IAuthenticationFilter authenticationFilter = Assert.Single(authenticationFilters);\n            Assert.Same(expectedActionFilter, authenticationFilter);\n        }\n\n        [Fact]\n        public void ExceptionFilters_ReturnsActionScopeExceptionFilters_WhenOverrideScopeIsAction()\n        {\n            // Arrange\n            IExceptionFilter expectedGlobalFilter = CreateDummyExceptionFilter();\n            FilterInfo globalFilter = new FilterInfo(expectedGlobalFilter, FilterScope.Global);\n            IExceptionFilter expectedControllerFilter = CreateDummyExceptionFilter();\n            FilterInfo controllerFilter = new FilterInfo(expectedControllerFilter, FilterScope.Controller);\n            IExceptionFilter expectedActionFilter = CreateDummyExceptionFilter();\n            FilterInfo actionFilter = new FilterInfo(expectedActionFilter, FilterScope.Action);\n            FilterInfo overrideFilter = new FilterInfo(CreateOverride(typeof(IExceptionFilter)), FilterScope.Action);\n            IEnumerable<FilterInfo> filters = new FilterInfo[] { globalFilter, controllerFilter, actionFilter, overrideFilter };\n            FilterGrouping product = CreateProductUnderTest(filters);\n\n            // Act\n            IExceptionFilter[] exceptionFilters = product.ExceptionFilters;\n\n            // Assert\n            Assert.NotNull(exceptionFilters);\n            IExceptionFilter exceptionFilter = Assert.Single(exceptionFilters);\n            Assert.Same(expectedActionFilter, exceptionFilter);\n        }\n\n        [Fact]\n        public void FilterImplementingMultipleType_WhereOneTypeIsOverridden_AppearsOnlyInTheOtherList()\n        {\n            // Arrange\n            IFilter expectedInstance = new ActionAndExceptionFilter();\n            FilterInfo actionAndExceptionFilter = new FilterInfo(expectedInstance, FilterScope.Global);\n            FilterInfo overrideExceptionFilter = new FilterInfo(CreateOverride(typeof(IExceptionFilter)),\n                FilterScope.Action);\n            IEnumerable<FilterInfo> filters = new FilterInfo[] { actionAndExceptionFilter, overrideExceptionFilter };\n            FilterGrouping product = CreateProductUnderTest(filters);\n\n            // Act\n            IActionFilter[] actionFilters = product.ActionFilters;\n            IExceptionFilter[] exceptionFilters = product.ExceptionFilters;\n\n            // Assert\n            Assert.NotNull(actionFilters);\n            IActionFilter actionFilter = Assert.Single(actionFilters);\n            Assert.Same(expectedInstance, actionFilter);\n            Assert.NotNull(exceptionFilters);\n            Assert.Empty(exceptionFilters);\n        }\n\n        private static IActionFilter CreateDummyActionFilter()\n        {\n            return new Mock<IActionFilter>(MockBehavior.Strict).Object;\n        }\n\n        private static IAuthenticationFilter CreateDummyAuthenticationFilter()\n        {\n            return new Mock<IAuthenticationFilter>(MockBehavior.Strict).Object;\n        }\n\n        private static IAuthorizationFilter CreateDummyAuthorizationFilter()\n        {\n            return new Mock<IAuthorizationFilter>(MockBehavior.Strict).Object;\n        }\n\n        private static IExceptionFilter CreateDummyExceptionFilter()\n        {\n            return new Mock<IExceptionFilter>(MockBehavior.Strict).Object;\n        }\n\n        private static IEnumerable<FilterInfo> CreateEmptyFilters()\n        {\n            return new FilterInfo[0];\n        }\n\n        private static IOverrideFilter CreateOverride(Type filtersToOverride)\n        {\n            Mock<IOverrideFilter> mock = new Mock<IOverrideFilter>();\n            mock.Setup(f => f.FiltersToOverride).Returns(filtersToOverride);\n            return mock.Object;\n        }\n\n        private static FilterGrouping CreateProductUnderTest(IEnumerable<FilterInfo> filters)\n        {\n            return new FilterGrouping(filters);\n        }\n\n        private class ActionAndExceptionFilter : IActionFilter, IExceptionFilter\n        {\n            public bool AllowMultiple\n            {\n                get { throw new NotImplementedException(); }\n            }\n\n            public Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext,\n                CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)\n            {\n                throw new NotImplementedException();\n            }\n\n            public Task ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext,\n                CancellationToken cancellationToken)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Controllers/HttpActionContextTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Controllers;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http\n{\n    public class HttpActionContextTest\n    {\n        [Fact]\n        public void Default_Constructor()\n        {\n            HttpActionContext actionContext = new HttpActionContext();\n\n            Assert.Null(actionContext.ControllerContext);\n            Assert.Null(actionContext.ActionDescriptor);\n            Assert.Null(actionContext.Response);\n            Assert.Null(actionContext.Request);\n            Assert.NotNull(actionContext.ActionArguments);\n            Assert.NotNull(actionContext.ModelState);\n        }\n\n        [Fact]\n        public void Parameter_Constructor()\n        {\n            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext();\n            HttpActionDescriptor actionDescriptor = new Mock<HttpActionDescriptor>().Object;\n            HttpActionContext actionContext = new HttpActionContext(controllerContext, actionDescriptor);\n\n            Assert.Same(controllerContext, actionContext.ControllerContext);\n            Assert.Same(actionDescriptor, actionContext.ActionDescriptor);\n            Assert.Same(controllerContext.Request, actionContext.Request);\n            Assert.Null(actionContext.Response);\n            Assert.NotNull(actionContext.ActionArguments);\n            Assert.NotNull(actionContext.ModelState);\n        }\n\n        [Fact]\n        public void Constructor_Throws_IfControllerContextIsNull()\n        {\n            Assert.ThrowsArgumentNull(\n                () => new HttpActionContext(null, new Mock<HttpActionDescriptor>().Object),\n                \"controllerContext\");\n        }\n\n        [Fact]\n        public void Constructor_Throws_IfActionDescriptorIsNull()\n        {\n            Assert.ThrowsArgumentNull(\n                () => new HttpActionContext(ContextUtil.CreateControllerContext(), null),\n                \"actionDescriptor\");\n        }\n\n        [Fact]\n        public void ControllerContext_Property()\n        {\n            Assert.Reflection.Property<HttpActionContext, HttpControllerContext>(\n                instance: new HttpActionContext(),\n                propertyGetter: ac => ac.ControllerContext,\n                expectedDefaultValue: null,\n                allowNull: false,\n                roundTripTestValue: ContextUtil.CreateControllerContext());\n        }\n\n        [Fact]\n        public void ActionDescriptor_Property()\n        {\n            Assert.Reflection.Property<HttpActionContext, HttpActionDescriptor>(\n                instance: new HttpActionContext(),\n                propertyGetter: ac => ac.ActionDescriptor,\n                expectedDefaultValue: null,\n                allowNull: false,\n                roundTripTestValue: new Mock<HttpActionDescriptor>().Object);\n        }\n\n        [Fact]\n        public void RequestContextGet_ReturnsControllerContextRequestContext()\n        {\n            // Arrange\n            HttpRequestContext expectedRequestContext = new HttpRequestContext();\n\n            HttpActionContext product = new HttpActionContext();\n            product.ControllerContext = new HttpControllerContext\n            {\n                RequestContext = expectedRequestContext\n            };\n\n            // Act\n            HttpRequestContext requestContext = product.RequestContext;\n\n            // Assert\n            Assert.Same(expectedRequestContext, requestContext);\n        }\n\n        [Fact]\n        public void RequestContextGet_IfControllerContextIsNull_ReturnsNull()\n        {\n            // Arrange\n            HttpRequestContext expectedRequestContext = new HttpRequestContext();\n\n            HttpActionContext product = new HttpActionContext();\n            Assert.Null(product.ControllerContext); // Guard\n\n            // Act\n            HttpRequestContext requestContext = product.RequestContext;\n\n            // Assert\n            Assert.Null(requestContext);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Controllers/HttpActionDescriptorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Controllers\n{\n    public class HttpActionDescriptorTest\n    {\n        [Theory]\n        [InlineData(null, typeof(VoidResultConverter))]\n        [InlineData(typeof(HttpResponseMessage), typeof(ResponseMessageResultConverter))]\n        [InlineData(typeof(object), typeof(ValueResultConverter<object>))]\n        [InlineData(typeof(string), typeof(ValueResultConverter<string>))]\n        public void GetResultConverter_GetAppropriateConverterInstance(Type actionReturnType, Type expectedConverterType)\n        {\n            var result = HttpActionDescriptor.GetResultConverter(actionReturnType);\n\n            Assert.IsType(expectedConverterType, result);\n        }\n\n        [Fact]\n        public void GetResultConverter_WhenReturnTypeIsActionResult_ReturnsNull()\n        {\n            // Act\n            IActionResultConverter converter = HttpActionDescriptor.GetResultConverter(typeof(IHttpActionResult));\n\n            // Assert\n            Assert.Null(converter);\n        }\n\n        [Fact]\n        public void GetResultConverter_WhenTypeIsAnGenericParameterType_Throws()\n        {\n            var genericType = typeof(HttpActionDescriptorTest).GetMethod(\"SampleGenericMethod\").ReturnType;\n\n            Assert.Throws<InvalidOperationException>(() => HttpActionDescriptor.GetResultConverter(genericType),\n                \"No action result converter could be constructed for a generic parameter type 'TResult'.\");\n        }\n\n        public TResult SampleGenericMethod<TResult>()\n        {\n            return default(TResult);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Controllers/HttpConfigurationTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Services;\nusing System.Web.Http.Tracing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http\n{\n    public class HttpConfigurationTest\n    {\n        [Fact]\n        public void TypeIsCorrect()\n        {\n            Assert.Type.HasProperties<HttpConfiguration>(TypeAssert.TypeProperties.IsPublicVisibleClass | TypeAssert.TypeProperties.IsDisposable);\n        }\n\n        [Fact]\n        public void Default_Constructor()\n        {\n            HttpConfiguration configuration = new HttpConfiguration();\n\n            Assert.Empty(configuration.Filters);\n            Assert.NotEmpty(configuration.Formatters);\n            Assert.Empty(configuration.MessageHandlers);\n            Assert.Empty(configuration.Properties);\n            Assert.Empty(configuration.Routes);\n            Assert.NotNull(configuration.DependencyResolver);\n            Assert.NotNull(configuration.Services);\n            Assert.Equal(\"/\", configuration.VirtualPathRoot);\n        }\n\n        [Fact]\n        public void Parameter_Constructor()\n        {\n            string path = \"/some/path\";\n            HttpRouteCollection routes = new HttpRouteCollection(path);\n            HttpConfiguration configuration = new HttpConfiguration(routes);\n\n            Assert.Same(routes, configuration.Routes);\n            Assert.Equal(path, configuration.VirtualPathRoot);\n        }\n\n        [Fact]\n        public void Dispose_Idempotent()\n        {\n            HttpConfiguration configuration = new HttpConfiguration();\n            configuration.Dispose();\n            configuration.Dispose();\n        }\n\n        [Fact]\n        public void DependencyResolver_GuardClauses()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(() => config.DependencyResolver = null, \"value\");\n        }\n\n        [Fact]\n        public void Initializer_Default_Set_By_Ctor()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n\n            // Assert\n            Assert.NotNull(config.Initializer);\n        }\n\n        [Fact]\n        public void Initializer_Throws_With_Null()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => config.Initializer = null, \"value\");\n        }\n\n        [Fact]\n        public void Initializer_Initializes_TraceManager_By_Default()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            Mock<ITraceManager> mock = new Mock<ITraceManager>() { CallBase = true };\n            mock.Setup(m => m.Initialize(config)).Verifiable();\n            config.Services.Replace(typeof(ITraceManager), mock.Object);\n\n            // Act\n            config.Initializer(config);\n\n            // Assert\n            mock.Verify();\n        }\n\n        [Fact]\n        public void EnsureInitialized_CallsInitializerOnce()\n        {\n            // Arrange\n            int count = 0;\n            var config = new HttpConfiguration();\n            config.Initializer = _ => { count++; };\n\n            // Act\n            config.EnsureInitialized();\n            Assert.Equal(1, count);\n\n            config.EnsureInitialized();\n            Assert.Equal(1, count);\n\n        }\n\n        [Fact]\n        public void Initializer_Sets_Formatter_RequiredMemberSelector_By_Default()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            Mock<MediaTypeFormatter> mockFormatter = new Mock<MediaTypeFormatter>() { CallBase = true };\n            mockFormatter.Object.RequiredMemberSelector = null;\n\n            config.Formatters.Clear();\n            config.Formatters.Add(mockFormatter.Object);\n\n            // Act\n            config.Initializer(config);\n\n            // Assert\n            Assert.NotNull(mockFormatter.Object.RequiredMemberSelector);\n        }\n\n        [Fact]\n        public void Initialize_Default_Initializer_Can_Be_Removed()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            config.Initializer = (c) => { };\n            bool initializeCalled = false;\n            Mock<ITraceManager> mock = new Mock<ITraceManager>() { CallBase = true };\n            mock.Setup(m => m.Initialize(config)).Callback(() => initializeCalled = true);\n            config.Services.Replace(typeof(ITraceManager), mock.Object);\n\n            // Act\n            config.Initializer(config);\n\n            // Assert\n            Assert.False(initializeCalled);\n        }\n\n        [Fact]\n        public void Initialize_Initializer_Can_Be_Reused()\n        {\n            // Arrange\n            HttpConfiguration config1 = new HttpConfiguration();\n            HttpConfiguration configPassedToAction = null;\n            config1.Initializer = (c) => configPassedToAction = c;\n\n            HttpConfiguration config2 = new HttpConfiguration();\n            config2.Initializer = config1.Initializer;\n\n            // Act\n            config2.Initializer(config2);\n\n            // Assert\n            Assert.Same(config2, configPassedToAction);\n        }\n\n        [Fact]\n        public void Initialize_Can_Be_Chained()\n        {\n            // Arrange\n            HttpConfiguration config1 = new HttpConfiguration();\n            HttpConfiguration configPassedToAction1 = null;\n            config1.Initializer = (c) => configPassedToAction1 = c;\n\n            HttpConfiguration config2 = new HttpConfiguration();\n            HttpConfiguration configPassedToAction2 = null;\n            config2.Initializer = (c) => { config1.Initializer(config1); configPassedToAction2 = c; };\n\n            // Act\n            config2.Initializer(config2);\n\n            // Assert\n            Assert.Same(config1, configPassedToAction1);\n            Assert.Same(config2, configPassedToAction2);\n        }\n\n        [Fact]\n        public void ApplyControllerSettings_Does_Not_Clone_When_Settings_Are_Not_Initialized()\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            HttpControllerSettings settings = new HttpControllerSettings(config);\n\n            // Act\n            HttpConfiguration clonedConfig = HttpConfiguration.ApplyControllerSettings(settings, config);\n\n            // Assert\n            Assert.Same(config, clonedConfig);\n        }\n\n        [Fact]\n        public void ApplyControllerSettings_Clones_Configuration_When_Settings_Are_Initialized()\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            HttpControllerSettings settings = new HttpControllerSettings(config);\n            settings.Formatters.Clear();    // accessing this property will force a clone\n\n            // Act\n            HttpConfiguration clonedConfig = HttpConfiguration.ApplyControllerSettings(settings, config);\n\n            // Assert\n            Assert.NotNull(clonedConfig);\n            Assert.NotSame(config, clonedConfig);\n        }\n\n        [Fact]\n        public void ApplyControllerSettings_Executes_Original_Initializer_On_Clone()\n        {\n            // Arrange\n            HttpConfiguration configPassedToAction = null;\n            HttpConfiguration config = new HttpConfiguration();\n            config.Initializer = (c) => configPassedToAction = c;\n            HttpControllerSettings settings = new HttpControllerSettings(config);\n            settings.Formatters.Clear();    // accessing this property will force a clone\n\n            // Act\n            HttpConfiguration clonedConfig = HttpConfiguration.ApplyControllerSettings(settings, config);\n\n            // Assert\n            Assert.Same(clonedConfig, configPassedToAction);\n        }\n\n        [Fact]\n        public void ApplyControllerSettings_Clone_Inherits_Tracing_On_PerController_Services()\n        {\n            // Arrange\n            bool calledTrace = false;\n            HttpConfiguration config = new HttpConfiguration();\n            Mock<ITraceWriter> mockTracer = new Mock<ITraceWriter>() { CallBase = true };\n            mockTracer.Setup(m => m.Trace(It.IsAny<HttpRequestMessage>(),\n                                          It.IsAny<string>(),\n                                          It.IsAny<TraceLevel>(),\n                                          It.IsAny<Action<TraceRecord>>())).Callback(() => { calledTrace = true; });\n\n            config.Services.Replace(typeof(ITraceWriter), mockTracer.Object);\n            config.Initializer(config);    // installs tracer on original config\n\n            HttpControllerSettings settings = new HttpControllerSettings(config);\n            Mock<IContentNegotiator> mockNegotiator = new Mock<IContentNegotiator>() { CallBase = true };\n            settings.Services.Replace(typeof(IContentNegotiator), mockNegotiator.Object);\n\n            // Act\n            HttpConfiguration clonedConfig = HttpConfiguration.ApplyControllerSettings(settings, config);\n            clonedConfig.Services.GetContentNegotiator().Negotiate(typeof(string), new HttpRequestMessage(), Enumerable.Empty<MediaTypeFormatter>());\n\n            // Assert\n            Assert.True(calledTrace);\n        }\n\n        [Fact]\n        public void ApplyControllerSettings_Clone_Inherits_Tracing_On_PerController_Formatters()\n        {\n            // Arrange\n            bool calledTrace = false;\n            HttpConfiguration config = new HttpConfiguration();\n            Mock<ITraceWriter> mockTracer = new Mock<ITraceWriter>() { CallBase = true };\n            mockTracer.Setup(m => m.Trace(It.IsAny<HttpRequestMessage>(),\n                                          It.IsAny<string>(),\n                                          It.IsAny<TraceLevel>(),\n                                          It.IsAny<Action<TraceRecord>>())).Callback(() => { calledTrace = true; });\n\n            config.Services.Replace(typeof(ITraceWriter), mockTracer.Object);\n            config.Initializer(config);    // installs tracer on original config\n\n            HttpControllerSettings settings = new HttpControllerSettings(config);\n            Mock<MediaTypeFormatter> mockFormatter = new Mock<MediaTypeFormatter>() { CallBase = true };\n            settings.Formatters.Clear();\n            settings.Formatters.Add(mockFormatter.Object);\n\n            // Act\n            HttpConfiguration clonedConfig = HttpConfiguration.ApplyControllerSettings(settings, config);\n            clonedConfig.Formatters[0].GetPerRequestFormatterInstance(typeof(string), new HttpRequestMessage(), new MediaTypeHeaderValue(\"application/mine\"));\n\n            // Assert\n            Assert.True(calledTrace);\n        }\n\n        [Fact]\n        public void ApplyControllerSettings_Clone_Can_Enable_Tracing_When_Original_Disabled_It()\n        {\n            // Arrange\n            bool calledTrace = false;\n            HttpConfiguration config = new HttpConfiguration();\n            Mock<ITraceWriter> mockTracer = new Mock<ITraceWriter>() { CallBase = true };\n            mockTracer.Setup(m => m.Trace(It.IsAny<HttpRequestMessage>(),\n                                          It.IsAny<string>(),\n                                          It.IsAny<TraceLevel>(),\n                                          It.IsAny<Action<TraceRecord>>())).Callback(() => { calledTrace = true; });\n\n            config.Initializer(config);    // ensures TraceManager is called, but it will be a NOP\n\n            HttpControllerSettings settings = new HttpControllerSettings(config);\n            settings.Services.Replace(typeof(ITraceWriter), mockTracer.Object);\n\n            // Act\n            HttpConfiguration clonedConfig = HttpConfiguration.ApplyControllerSettings(settings, config);\n            clonedConfig.Services.GetContentNegotiator().Negotiate(typeof(string), new HttpRequestMessage(), Enumerable.Empty<MediaTypeFormatter>());\n\n            // Assert\n            Assert.True(calledTrace);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Controllers/HttpControllerContextTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http\n{\n    public class HttpControllerContextTest\n    {\n        [Fact]\n        public void Default_Constructor()\n        {\n            HttpControllerContext controllerContext = new HttpControllerContext();\n\n            Assert.Null(controllerContext.Configuration);\n            Assert.Null(controllerContext.Controller);\n            Assert.Null(controllerContext.ControllerDescriptor);\n            Assert.Null(controllerContext.Request);\n            Assert.Null(controllerContext.RouteData);\n        }\n\n        [Fact]\n        public void Parameter_Constructor()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            IHttpRouteData routeData = new Mock<IHttpRouteData>().Object;\n            HttpRequestMessage request = new HttpRequestMessage();\n            HttpControllerContext controllerContext = new HttpControllerContext(config, routeData, request);\n\n            Assert.Same(config, controllerContext.Configuration);\n            Assert.Same(request, controllerContext.Request);\n            Assert.Same(routeData, controllerContext.RouteData);\n            Assert.Null(controllerContext.Controller);\n            Assert.Null(controllerContext.ControllerDescriptor);\n        }\n\n        [Fact]\n        public void Constructor_Throws_IfConfigurationIsNull()\n        {\n            Assert.ThrowsArgumentNull(\n                () => new HttpControllerContext(null, new Mock<IHttpRouteData>().Object, new HttpRequestMessage()),\n                \"configuration\");\n        }\n\n        [Fact]\n        public void Constructor_Throws_IfRouteDataIsNull()\n        {\n            Assert.ThrowsArgumentNull(\n                () => new HttpControllerContext(new HttpConfiguration(), null, new HttpRequestMessage()),\n                \"routeData\");\n        }\n\n        [Fact]\n        public void Constructor_Throws_IfRequestIsNull()\n        {\n            Assert.ThrowsArgumentNull(\n                () => new HttpControllerContext(new HttpConfiguration(), new Mock<IHttpRouteData>().Object, null),\n                \"request\");\n        }\n\n        [Fact]\n        public void Configuration_Property()\n        {\n            Assert.Reflection.Property<HttpControllerContext, HttpConfiguration>(\n                instance: new HttpControllerContext(),\n                propertyGetter: cc => cc.Configuration,\n                expectedDefaultValue: null,\n                allowNull: false,\n                roundTripTestValue: new HttpConfiguration());\n        }\n\n        [Fact]\n        public void Controller_Property()\n        {\n            Assert.Reflection.Property<HttpControllerContext, IHttpController>(\n                instance: new HttpControllerContext(),\n                propertyGetter: cc => cc.Controller,\n                expectedDefaultValue: null,\n                allowNull: false,\n                roundTripTestValue: new Mock<IHttpController>().Object);\n        }\n\n        [Fact]\n        public void ControllerDescriptor_Property()\n        {\n            Assert.Reflection.Property<HttpControllerContext, HttpControllerDescriptor>(\n                instance: new HttpControllerContext(),\n                propertyGetter: cc => cc.ControllerDescriptor,\n                expectedDefaultValue: null,\n                allowNull: false,\n                roundTripTestValue: new HttpControllerDescriptor());\n        }\n\n        [Fact]\n        public void RouteData_Property()\n        {\n            Assert.Reflection.Property<HttpControllerContext, IHttpRouteData>(\n                instance: new HttpControllerContext(),\n                propertyGetter: cc => cc.RouteData,\n                expectedDefaultValue: null,\n                allowNull: false,\n                roundTripTestValue: new Mock<IHttpRouteData>().Object);\n        }\n\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Controllers/HttpControllerDescriptorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Net.Http.Formatting;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Filters;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http\n{\n    public class HttpControllerDescriptorTest\n    {\n        [Fact]\n        public void Default_Constructor()\n        {\n            HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor();\n\n            Assert.Null(controllerDescriptor.ControllerName);\n            Assert.Null(controllerDescriptor.Configuration);\n            Assert.Null(controllerDescriptor.ControllerType);\n            Assert.NotNull(controllerDescriptor.Properties);\n        }\n\n        [Fact]\n        public void Parameter_Constructor()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            string controllerName = \"UsersController\";\n            Type controllerType = typeof(UsersController);\n\n            HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(config, controllerName, controllerType);\n            Assert.NotNull(controllerDescriptor.ControllerName);\n            Assert.NotNull(controllerDescriptor.Configuration);\n            Assert.NotNull(controllerDescriptor.ControllerType);\n            Assert.NotNull(controllerDescriptor.Properties);\n            Assert.Equal(config, controllerDescriptor.Configuration);\n            Assert.Equal(controllerName, controllerDescriptor.ControllerName);\n            Assert.Equal(controllerType, controllerDescriptor.ControllerType);\n        }\n\n        [Fact]\n        public void Constructor_Throws_IfConfigurationIsNull()\n        {\n            Assert.ThrowsArgumentNull(\n                () => new HttpControllerDescriptor(null, \"UsersController\", typeof(UsersController)),\n                \"configuration\");\n        }\n\n        [Fact]\n        public void Constructor_Throws_IfControllerNameIsNull()\n        {\n            Assert.ThrowsArgumentNull(\n                () => new HttpControllerDescriptor(new HttpConfiguration(), null, typeof(UsersController)),\n                \"controllerName\");\n        }\n\n        [Fact]\n        public void Constructor_Throws_IfControllerTypeIsNull()\n        {\n            Assert.ThrowsArgumentNull(\n                () => new HttpControllerDescriptor(new HttpConfiguration(), \"UsersController\", null),\n                \"controllerType\");\n        }\n\n        [Fact]\n        public void Configuration_Property()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor();\n\n            Assert.Reflection.Property<HttpControllerDescriptor, HttpConfiguration>(\n                instance: controllerDescriptor,\n                propertyGetter: cd => cd.Configuration,\n                expectedDefaultValue: null,\n                allowNull: false,\n                roundTripTestValue: config);\n        }\n\n        [Fact]\n        public void ControllerName_Property()\n        {\n            string controllerName = \"UsersController\";\n            HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor();\n\n            Assert.Reflection.Property<HttpControllerDescriptor, string>(\n                instance: controllerDescriptor,\n                propertyGetter: cd => cd.ControllerName,\n                expectedDefaultValue: null,\n                allowNull: false,\n                roundTripTestValue: controllerName);\n        }\n\n        [Fact]\n        public void ControllerType_Property()\n        {\n            Type controllerType = typeof(UsersController);\n            HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor();\n\n            Assert.Reflection.Property<HttpControllerDescriptor, Type>(\n                instance: controllerDescriptor,\n                propertyGetter: cd => cd.ControllerType,\n                expectedDefaultValue: null,\n                allowNull: false,\n                roundTripTestValue: controllerType);\n        }\n\n        [Fact]\n        public void GetFilters_InvokesGetCustomAttributesMethod()\n        {\n            var descriptorMock = new Mock<HttpControllerDescriptor> { CallBase = true };\n            var filters = new Collection<IFilter>(new List<IFilter>());\n            descriptorMock.Setup(d => d.GetCustomAttributes<IFilter>()).Returns(filters).Verifiable();\n\n            var result = descriptorMock.Object.GetFilters();\n\n            Assert.Same(filters, result);\n            descriptorMock.Verify();\n        }\n\n        [Fact]\n        public void Initialize_In_InheritenceHierarchy()\n        {\n            // Verifies that initialization is run in order with , and that they all mutate on the same descriptor object\n            HttpConfiguration config = new HttpConfiguration();\n\n            // Act.\n            HttpControllerDescriptor desc = new HttpControllerDescriptor(config, \"MyController\", typeof(MyDerived2Controller));\n\n            // Assert\n            Assert.Same(MyDerived1Controller.SelectorBase, desc.Configuration.Services.GetActionSelector());\n            Assert.Same(MyDerived1Controller.ActionValueBinderDerived1, desc.Configuration.Services.GetActionValueBinder());\n            Assert.Same(config.Formatters, desc.Configuration.Formatters); // didn't override, stays the same\n            Assert.Same(config.ParameterBindingRules, desc.Configuration.ParameterBindingRules); // didn't override, stays the same\n        }\n\n        [Fact]\n        public void Initialize_In_InheritenceHierarchy_Branching()\n        {\n            // Verifies that initialization is run in order with, and that they all mutate on the same descriptor object\n            HttpConfiguration config = new HttpConfiguration();\n\n            // Act.\n            HttpControllerDescriptor desc = new HttpControllerDescriptor(config, \"MyController\", typeof(MyDerived3Controller));\n\n            // Assert\n            Assert.Same(MyDerived1Controller.SelectorBase, desc.Configuration.Services.GetActionSelector());\n            Assert.Same(MyDerived3Controller.ActionValueBinderDerived3, desc.Configuration.Services.GetActionValueBinder());\n            Assert.Same(config.Formatters, desc.Configuration.Formatters); // didn't override, stays the same\n            Assert.Same(config.ParameterBindingRules, desc.Configuration.ParameterBindingRules); // didn't override, stays the same\n        }\n\n        [Fact]\n        public void Initialize_GetsTheActualControllerDescriptor_In_InheritenceHierarchy()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n\n            HttpControllerDescriptor desc = new HttpControllerDescriptor(config, \"MyController\", typeof(VerifyControllerDescriptorDerivedController));\n            Assert.Equal(typeof(VerifyControllerDescriptorDerivedController), VerifyControllerDescriptorAttribute.ControllerType);\n\n            desc = new HttpControllerDescriptor(config, \"MyController\", typeof(VerifyControllerDescriptorBaseController));\n            Assert.Equal(typeof(VerifyControllerDescriptorBaseController), VerifyControllerDescriptorAttribute.ControllerType);\n        }\n\n        [Fact]\n        public void EmptySetting_DoesNotChangeTheConfigurationInstance()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n\n            HttpControllerDescriptor desc = new HttpControllerDescriptor(config, \"MyController\", typeof(NoopControllerConfigController));\n            Assert.Same(config, desc.Configuration); // didn't change anything, the config instance stays the same\n        }\n\n        [Fact]\n        public void GetCustomAttributes_GetsInheritedAttributes()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            HttpControllerDescriptor desc = new HttpControllerDescriptor(config, \"MyController\", typeof(MyDerived1Controller));\n\n            var attributes = desc.GetCustomAttributes<MyConfigBaseAttribute>();\n\n            Assert.Single(attributes);\n        }\n\n        [Fact]\n        public void GetCustomAttributesInheritTrue_GetsInheritedAttributes()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            HttpControllerDescriptor desc = new HttpControllerDescriptor(config, \"MyController\", typeof(MyDerived1Controller));\n\n            var attributes = desc.GetCustomAttributes<MyConfigBaseAttribute>(inherit: true);\n\n            Assert.Single(attributes);\n        }\n\n        [Fact]\n        public void GetCustomAttributesInheritFalse_DoesNotGetInheritedAttributes()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            HttpControllerDescriptor desc = new HttpControllerDescriptor(config, \"MyController\", typeof(MyDerived1Controller));\n\n            var attributes = desc.GetCustomAttributes<MyConfigBaseAttribute>(inherit: false);\n\n            Assert.Empty(attributes);\n        }\n\n        [Fact]\n        public void GetCustomAttributesInheritFalse_GetsDeclaredAttributes()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            HttpControllerDescriptor desc = new HttpControllerDescriptor(config, \"MyController\", typeof(MyDerived1Controller));\n\n            var attributes = desc.GetCustomAttributes<MyConfigDerived1Attribute>(inherit: false);\n\n            Assert.Single(attributes);\n        }\n\n        class NoopControllerConfigAttribute : Attribute, IControllerConfiguration\n        {\n            public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)\n            {\n            }\n        }\n\n        [NoopControllerConfig]\n        class NoopControllerConfigController : ApiController\n        {\n        }\n\n        class VerifyControllerDescriptorAttribute : Attribute, IControllerConfiguration\n        {\n            public static Type ControllerType;\n            public void Initialize(HttpControllerSettings settings, HttpControllerDescriptor controllerDescriptor)\n            {\n                ControllerType = controllerDescriptor.ControllerType;\n            }\n        }\n\n        [VerifyControllerDescriptor]\n        class VerifyControllerDescriptorBaseController : ApiController\n        {\n        }\n\n        class VerifyControllerDescriptorDerivedController : VerifyControllerDescriptorBaseController\n        {\n        }\n\n        class MyConfigBaseAttribute : Attribute, IControllerConfiguration\n        {\n            public void Initialize(HttpControllerSettings settings, HttpControllerDescriptor controllerDescriptor)\n            {\n                settings.Services.Replace(typeof(IActionValueBinder), MyBaseController.ActionValueBinderBase);\n                settings.Services.Replace(typeof(IHttpActionSelector), MyBaseController.SelectorBase);\n            }\n        }\n\n        [MyConfigBase]\n        class MyBaseController : ApiController\n        {\n            public static IHttpActionSelector SelectorBase = new Mock<IHttpActionSelector>().Object;\n            public static IActionValueBinder ActionValueBinderBase = new Mock<IActionValueBinder>().Object;\n        }\n\n        class MyConfigDerived1Attribute : Attribute, IControllerConfiguration\n        {\n            public void Initialize(HttpControllerSettings settings, HttpControllerDescriptor controllerDescriptor)\n            {\n                // Base runs first, so we should be able to see changes from the base.\n                Assert.Same(MyBaseController.ActionValueBinderBase, settings.Services.GetActionValueBinder());\n\n                // Also overwrite them\n                settings.Services.Replace(typeof(IActionValueBinder), MyDerived1Controller.ActionValueBinderDerived1);\n            }\n        }\n\n        class MyConfigDerived3Attribute : Attribute, IControllerConfiguration\n        {\n            public void Initialize(HttpControllerSettings settings, HttpControllerDescriptor controllerDescriptor)\n            {\n                // MyConfigDerived1 runs first, so we should be able to see changes from the MyConfigDerived1.\n                Assert.Same(MyDerived1Controller.ActionValueBinderDerived1, settings.Services.GetActionValueBinder());\n\n                // Also overwrite them\n                settings.Services.Replace(typeof(IActionValueBinder), MyDerived3Controller.ActionValueBinderDerived3);\n            }\n        }\n\n        [MyConfigDerived1]\n        class MyDerived1Controller : MyBaseController\n        {\n            public static IActionValueBinder ActionValueBinderDerived1 = new Mock<IActionValueBinder>().Object;\n        }\n\n        class MyDerived2Controller : MyDerived1Controller\n        {\n        }\n\n        [MyConfigDerived3]\n        class MyDerived3Controller : MyDerived1Controller\n        {\n            public static IActionValueBinder ActionValueBinderDerived3 = new Mock<IActionValueBinder>().Object;\n        }\n\n\n        [Fact]\n        public void Initialize_Append_A_Formatter()\n        {\n            // Verifies that controller inherit the formatter list from the global config, and can mutate it.\n            HttpConfiguration config = new HttpConfiguration();\n\n            MediaTypeFormatter globalFormatter = new Mock<MediaTypeFormatter>().Object;\n            config.Formatters.Clear();\n            config.Formatters.Add(globalFormatter);\n\n            // Act.\n            HttpControllerDescriptor desc = new HttpControllerDescriptor(config, \"MyController\", typeof(MyControllerWithCustomFormatter));\n\n            // Assert\n            Assert.Equal(2, desc.Configuration.Formatters.Count);\n            Assert.Same(globalFormatter, desc.Configuration.Formatters[0]);\n            Assert.Same(MyControllerWithCustomFormatter.CustomFormatter, desc.Configuration.Formatters[1]);\n        }\n\n\n        class MyControllerWithCustomFormatterConfigAttribute : Attribute, IControllerConfiguration\n        {\n            public void Initialize(HttpControllerSettings settings, HttpControllerDescriptor controllerDescriptor)\n            {\n                // Appends to existing list. Formatter list has copy-on-write semantics.\n                Assert.Single(settings.Formatters); // the one we already set\n                settings.Formatters.Add(MyControllerWithCustomFormatter.CustomFormatter);\n            }\n        }\n\n        [MyControllerWithCustomFormatterConfig]\n        class MyControllerWithCustomFormatter : ApiController\n        {\n            public static MediaTypeFormatter CustomFormatter = new Mock<MediaTypeFormatter>().Object;\n\n        }\n\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Controllers/HttpParameterBindingTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Controllers;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http\n{\n    public class HttpParameterBindingTest\n    {\n        [Fact]\n        public void GetValueMissing()\n        {\n            CustomBinding binding = new CustomBinding(\"p1\");\n\n            HttpActionContext ctx = new HttpActionContext();\n\n            var result = binding.GetValue(ctx);\n\n            Assert.Null(result);\n        }\n\n        [Fact]\n        public void GetValue_Returns_Set()\n        {\n            CustomBinding binding = new CustomBinding(\"p1\");\n\n            HttpActionContext ctx = new HttpActionContext();\n\n            // Act\n            object result = \"abc\";\n            binding.SetValue(ctx, result);\n            var result2 = binding.GetValue(ctx);\n\n            // Assert\n            Assert.Same(result, result2);\n        }\n\n        [Fact]\n        public void Can_Set_Null()\n        {\n            // It's legal to set a parameter to null. Test against spurious null checks.\n            CustomBinding binding = new CustomBinding(\"p1\");\n\n            HttpActionContext ctx = new HttpActionContext();\n\n            // Act            \n            binding.SetValue(ctx, null);\n\n            var resultFinal = binding.GetValue(ctx);\n\n            // Assert\n            Assert.Null(resultFinal);\n        }\n\n        [Fact]\n        public void Call_Set_Multiple_Times()\n        {\n            // Make sure a binding can set the argument multiple times and that we get the latest. \n            // This is interesting with composite bindings that chain to an inner binding. \n            CustomBinding binding = new CustomBinding(\"p1\");\n\n            HttpActionContext ctx = new HttpActionContext();\n\n            // Act\n            object result1 = \"abc\";\n            binding.SetValue(ctx, result1);\n\n            object result2 = 123;\n            binding.SetValue(ctx, result2);\n\n            var resultFinal = binding.GetValue(ctx);\n\n            // Assert\n            Assert.Same(result2, resultFinal);\n        }\n\n        [Fact]\n        public void Set_Modifies_Dictionary()\n        {\n            string name = \"p1\";\n            CustomBinding binding = new CustomBinding(name);\n\n            HttpActionContext ctx = new HttpActionContext();\n\n            // Act\n            object result = \"abc\";\n            binding.SetValue(ctx, result);\n            var result2 = ctx.ActionArguments[name];\n\n            // Assert\n            Assert.Same(result, result2);\n        }\n\n        [Fact]\n        public void Reuse_Binding_With_Different_Contexts()\n        { \n            // The same binding can be used across multiple action contexts.\n\n            string name = \"p1\";\n            CustomBinding binding = new CustomBinding(name);\n\n            HttpActionContext ctx1 = new HttpActionContext();\n            HttpActionContext ctx2 = new HttpActionContext();\n\n            // Act\n            object result1 = \"abc\";\n            binding.SetValue(ctx1, result1);\n\n            object result2 = 123;            \n            binding.SetValue(ctx2, result2);\n\n            // Assert\n            Assert.Same(result1, binding.GetValue(ctx1));\n            Assert.Same(result2, binding.GetValue(ctx2));\n        }\n\n        // Helper for testing. \n        // Easily construct, mock out the the right things, and expose protected members to the tests. \n        public class CustomBinding : HttpParameterBinding\n        {\n            public CustomBinding(string paramName) : base(Build(paramName))\n            {\n            }\n\n            static HttpParameterDescriptor Build(string paramName)\n            {\n                Mock<HttpParameterDescriptor> mock = new Mock<HttpParameterDescriptor>();\n                mock.Setup(x => x.ParameterName).Returns(paramName);\n                return mock.Object;\n            }\n\n            public override Threading.Tasks.Task ExecuteBindingAsync(Metadata.ModelMetadataProvider metadataProvider, HttpActionContext actionContext, Threading.CancellationToken cancellationToken)\n            {\n                throw new NotImplementedException();\n            }\n\n            // Expose protected\n            public new object GetValue(HttpActionContext actionContext)\n            {\n                return base.GetValue(actionContext);\n            }\n\n            public new void SetValue(HttpActionContext actionContext, object value)\n            {\n                base.SetValue(actionContext, value);\n            }\n        }\n    }\n\n\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Controllers/HttpParameterDescriptorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Http.Controllers;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http\n{\n    public class HttpParameterDescriptorTest\n    {\n        [Fact]\n        public void Default_Constructor()\n        {\n            HttpParameterDescriptor parameterDescriptor = new Mock<HttpParameterDescriptor>().Object;\n\n            Assert.Null(parameterDescriptor.ParameterName);\n            Assert.Null(parameterDescriptor.ParameterType);\n            Assert.Null(parameterDescriptor.Configuration);\n            Assert.Null(parameterDescriptor.Prefix);\n            Assert.Null(parameterDescriptor.ParameterBinderAttribute);\n            Assert.Null(parameterDescriptor.ActionDescriptor);\n            Assert.Null(parameterDescriptor.DefaultValue);\n            Assert.NotNull(parameterDescriptor.Properties);\n            Assert.False(parameterDescriptor.IsOptional);\n        }\n\n        [Fact]\n        public void Configuration_Property()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            HttpParameterDescriptor parameterDescriptor = new Mock<HttpParameterDescriptor> { CallBase = true }.Object;\n\n            Assert.Reflection.Property<HttpParameterDescriptor, HttpConfiguration>(\n                 instance: parameterDescriptor,\n                 propertyGetter: pd => pd.Configuration,\n                 expectedDefaultValue: null,\n                 allowNull: false,\n                 roundTripTestValue: config);\n        }\n\n        [Fact]\n        public void ActionDescriptor_Property()\n        {\n            HttpParameterDescriptor parameterDescriptor = new Mock<HttpParameterDescriptor> { CallBase = true }.Object;\n            HttpActionDescriptor actionDescriptor = new Mock<HttpActionDescriptor>().Object;\n\n            Assert.Reflection.Property<HttpParameterDescriptor, HttpActionDescriptor>(\n                 instance: parameterDescriptor,\n                 propertyGetter: pd => pd.ActionDescriptor,\n                 expectedDefaultValue: null,\n                 allowNull: false,\n                 roundTripTestValue: actionDescriptor);\n        }\n\n        [Fact]\n        public void GetCustomAttributes_Returns_EmptyAttributes()\n        {\n            HttpParameterDescriptor parameterDescriptor = new Mock<HttpParameterDescriptor> { CallBase = true }.Object;\n            IEnumerable<object> attributes = parameterDescriptor.GetCustomAttributes<object>();\n\n            Assert.Empty(attributes);\n        }\n\n        [Fact]\n        public void GetCustomAttributes_AttributeType_Returns_EmptyAttributes()\n        {\n            HttpParameterDescriptor parameterDescriptor = new Mock<HttpParameterDescriptor> { CallBase = true }.Object;\n            IEnumerable<FromBodyAttribute> attributes = parameterDescriptor.GetCustomAttributes<FromBodyAttribute>();\n\n            Assert.Empty(attributes);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Controllers/ParameterBindingExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http.Formatting;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.Validation;\nusing System.Web.Http.ValueProviders;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Controllers\n{\n    public class ParameterBindingExtensionsTest\n    {\n        [Fact]\n        public void BindAsError()\n        {\n            HttpParameterDescriptor param = CreateParameterDescriptor();\n\n            string message = \"error message\";\n            HttpParameterBinding binding = param.BindAsError(message);\n\n            Assert.NotNull(binding);\n            Assert.False(binding.IsValid);\n            Assert.Equal(message, binding.ErrorMessage);\n        }\n\n        [Fact]\n        public void BindWithModelBinding_Default()\n        {\n            HttpParameterDescriptor param = CreateParameterDescriptor();\n\n            ModelBinderParameterBinding binding = (ModelBinderParameterBinding) param.BindWithModelBinding();\n\n            Assert.NotNull(binding);\n        }\n\n        [Fact]\n        public void BindWithModelBinding_Attribute()\n        {\n            HttpParameterDescriptor param = CreateParameterDescriptor();\n\n            ModelBinderAttribute attribute = new ModelBinderAttribute(typeof(CustomModelBinder));\n            ModelBinderParameterBinding binding = (ModelBinderParameterBinding) param.BindWithAttribute(attribute);\n\n            Assert.NotNull(binding);\n            Assert.IsType<CustomModelBinder>(binding.Binder);\n        }\n\n        [Fact]\n        public void BindWithModelBinding_IModelBinder()\n        {\n            HttpParameterDescriptor param = CreateParameterDescriptor();\n\n            var binder = new CustomModelBinder();\n            ModelBinderParameterBinding binding = (ModelBinderParameterBinding) param.BindWithModelBinding(binder);\n\n            Assert.NotNull(binding);\n            Assert.Equal(binder, binding.Binder);\n        }\n\n        [Fact]\n        public void BindWithModelBinding_ValueProviderFactory_Array()\n        {\n            HttpParameterDescriptor param = CreateParameterDescriptor();\n\n            ModelBinderParameterBinding binding = (ModelBinderParameterBinding) param.BindWithModelBinding(new CustomValueProviderFactory1(), new CustomValueProviderFactory2());\n\n            Assert.NotNull(binding);\n\n            ValueProviderFactory[] vpfs = binding.ValueProviderFactories.ToArray();\n            Assert.Equal(2, vpfs.Length);            \n            Assert.IsType<CustomValueProviderFactory1>(vpfs[0]);\n            Assert.IsType<CustomValueProviderFactory2>(vpfs[1]);\n        }\n\n        [Fact]\n        public void BindWithModelBinding_ValueProviderFactory_IEnumerable()\n        {\n            HttpParameterDescriptor param = CreateParameterDescriptor();\n\n            var binder = new CustomModelBinder();\n            ModelBinderParameterBinding binding = (ModelBinderParameterBinding) param.BindWithModelBinding(binder, new List<ValueProviderFactory>() { new CustomValueProviderFactory1(), new CustomValueProviderFactory2() });\n\n            Assert.NotNull(binding);\n            Assert.Equal(binder, binding.Binder);\n\n            ValueProviderFactory[] vpfs = binding.ValueProviderFactories.ToArray();\n            Assert.Equal(2, vpfs.Length);\n            Assert.IsType<CustomValueProviderFactory1>(vpfs[0]);\n            Assert.IsType<CustomValueProviderFactory2>(vpfs[1]);\n        }\n\n        [Fact]\n        public void BindWithModelBinding_ValueProviderFactory_Binder_and_IEnumerable()\n        {\n            HttpParameterDescriptor param = CreateParameterDescriptor();\n\n            ModelBinderParameterBinding binding = (ModelBinderParameterBinding) param.BindWithModelBinding(new List<ValueProviderFactory>() { new CustomValueProviderFactory1(), new CustomValueProviderFactory2() });\n\n            Assert.NotNull(binding);\n\n            ValueProviderFactory[] vpfs = binding.ValueProviderFactories.ToArray();\n            Assert.Equal(2, vpfs.Length);\n            Assert.IsType<CustomValueProviderFactory1>(vpfs[0]);\n            Assert.IsType<CustomValueProviderFactory2>(vpfs[1]);\n        }\n\n        [Fact]\n        public void BindWithFormatter()\n        {\n            HttpParameterDescriptor param = CreateParameterDescriptor();\n\n            FormatterParameterBinding binding = (FormatterParameterBinding) param.BindWithFormatter();\n\n            Assert.NotNull(binding);\n        }\n\n        [Fact]\n        public void BindWithFormatter_Formatter_Array()\n        {\n            HttpParameterDescriptor param = CreateParameterDescriptor();\n\n            MediaTypeFormatter formatter1 = new XmlMediaTypeFormatter();\n            MediaTypeFormatter formatter2 = new JsonMediaTypeFormatter();\n\n            FormatterParameterBinding binding = (FormatterParameterBinding) param.BindWithFormatter(formatter1, formatter2);\n            \n            Assert.NotNull(binding);\n            MediaTypeFormatter[] formatters = binding.Formatters.ToArray();\n            Assert.Equal(2, formatters.Length);\n            Assert.Equal(formatter1, formatters[0]);\n            Assert.Equal(formatter2, formatters[1]);\n        }\n\n        [Fact]\n        public void BindWithFormatter_Formatter_IEnumerable()\n        {\n            HttpParameterDescriptor param = CreateParameterDescriptor();\n\n            MediaTypeFormatter formatter1 = new XmlMediaTypeFormatter();\n            MediaTypeFormatter formatter2 = new JsonMediaTypeFormatter();\n\n            FormatterParameterBinding binding = (FormatterParameterBinding) param.BindWithFormatter(new List<MediaTypeFormatter> { formatter1, formatter2 });\n\n            Assert.NotNull(binding);\n            MediaTypeFormatter[] formatters = binding.Formatters.ToArray();\n            Assert.Equal(2, formatters.Length);\n            Assert.Equal(formatter1, formatters[0]);\n            Assert.Equal(formatter2, formatters[1]);\n        }\n\n        [Fact]\n        public void BindWithFormatter_Formatters_and_Validator()\n        {\n            HttpParameterDescriptor param = CreateParameterDescriptor();\n\n            IBodyModelValidator bodyModelValidator = new Mock<IBodyModelValidator>().Object;\n            MediaTypeFormatter formatter1 = new XmlMediaTypeFormatter();\n            MediaTypeFormatter formatter2 = new JsonMediaTypeFormatter();\n\n            FormatterParameterBinding binding = (FormatterParameterBinding) param.BindWithFormatter(new List<MediaTypeFormatter> { formatter1, formatter2 }, bodyModelValidator);\n\n            Assert.NotNull(binding);\n            Assert.Equal(bodyModelValidator, binding.BodyModelValidator);\n            MediaTypeFormatter[] formatters = binding.Formatters.ToArray();\n            Assert.Equal(2, formatters.Length);\n            Assert.Equal(formatter1, formatters[0]);\n            Assert.Equal(formatter2, formatters[1]);\n        }\n\n        // Create a parameter that's sufficiently complete that we can run a basic Bind() operation on it. \n        private static HttpParameterDescriptor CreateParameterDescriptor()\n        {\n            // Need config because bind looks up in config.\n            HttpConfiguration config = new HttpConfiguration();\n            HttpParameterDescriptor param = CreateParameterDescriptor(typeof(object), \"thing\");\n            param.Configuration = config;\n            param.ActionDescriptor = new Mock<HttpActionDescriptor>().Object;\n            param.ActionDescriptor.ControllerDescriptor = new HttpControllerDescriptor(config);\n\n            return param;\n        }\n\n        private static HttpParameterDescriptor CreateParameterDescriptor(Type type, string name)\n        {\n            Mock<HttpParameterDescriptor> mock = new Mock<HttpParameterDescriptor>();\n            mock.Setup(p => p.ParameterType).Returns(type);\n            mock.Setup(p => p.ParameterName).Returns(name);\n            return mock.Object;\n        }\n\n        public class CustomModelBinder : IModelBinder\n        {\n            public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        public class CustomValueProviderFactory1 : ValueProviderFactory\n        {\n            public override IValueProvider GetValueProvider(HttpActionContext actionContext)\n            {\n                throw new NotImplementedException();\n            }\n        }\n        public class CustomValueProviderFactory2 : ValueProviderFactory\n        {\n            public override IValueProvider GetValueProvider(HttpActionContext actionContext)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Controllers/ReflectedHttpActionDescriptorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Net;\nusing System.Net.Http;\nusing System.Reflection;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Filters;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http\n{\n    public class ReflectedHttpActionDescriptorTest\n    {\n        private readonly UsersRpcController _controller = new UsersRpcController();\n        private readonly HttpControllerContext _context;\n        private readonly Dictionary<string, object> _arguments = new Dictionary<string, object>();\n\n        public ReflectedHttpActionDescriptorTest()\n        {\n            _context = ContextUtil.CreateControllerContext(instance: _controller);\n            _context.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;\n        }\n\n        [Fact]\n        public void Default_Constructor()\n        {\n            ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor();\n\n            Assert.Null(actionDescriptor.ActionName);\n            Assert.Null(actionDescriptor.Configuration);\n            Assert.Null(actionDescriptor.ControllerDescriptor);\n            Assert.Null(actionDescriptor.MethodInfo);\n            Assert.Null(actionDescriptor.ReturnType);\n            Assert.NotNull(actionDescriptor.Properties);\n        }\n\n        [Fact]\n        public void Parameter_Constructor()\n        {\n            Func<string, string, User> echoUserMethod = _controller.EchoUser;\n            HttpConfiguration config = new HttpConfiguration();\n            HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(config, \"\", typeof(UsersRpcController));\n            ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(controllerDescriptor, echoUserMethod.Method);\n\n            Assert.Equal(\"EchoUser\", actionDescriptor.ActionName);\n            Assert.Equal(config, actionDescriptor.Configuration);\n            Assert.Equal(typeof(UsersRpcController), actionDescriptor.ControllerDescriptor.ControllerType);\n            Assert.Equal(echoUserMethod.Method, actionDescriptor.MethodInfo);\n            Assert.Equal(typeof(User), actionDescriptor.ReturnType);\n            Assert.NotNull(actionDescriptor.Properties);\n        }\n\n        [Fact]\n        public void Constructor_Throws_IfMethodInfoIsNull()\n        {\n            Assert.ThrowsArgumentNull(\n                () => new ReflectedHttpActionDescriptor(new HttpControllerDescriptor(), null),\n                \"methodInfo\");\n        }\n\n        [Fact]\n        public void MethodInfo_Property()\n        {\n            ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor();\n            Action action = new Action(() => { });\n\n            Assert.Reflection.Property<ReflectedHttpActionDescriptor, MethodInfo>(\n                 instance: actionDescriptor,\n                 propertyGetter: ad => ad.MethodInfo,\n                 expectedDefaultValue: null,\n                 allowNull: false,\n                 roundTripTestValue: action.Method);\n        }\n\n        [Fact]\n        public void ControllerDescriptor_Property()\n        {\n            ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor();\n            HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor();\n\n            Assert.Reflection.Property<ReflectedHttpActionDescriptor, HttpControllerDescriptor>(\n                 instance: actionDescriptor,\n                 propertyGetter: ad => ad.ControllerDescriptor,\n                 expectedDefaultValue: null,\n                 allowNull: false,\n                 roundTripTestValue: controllerDescriptor);\n        }\n\n        [Fact]\n        public void Configuration_Property()\n        {\n            ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor();\n            HttpConfiguration config = new HttpConfiguration();\n\n            Assert.Reflection.Property<ReflectedHttpActionDescriptor, HttpConfiguration>(\n                 instance: actionDescriptor,\n                 propertyGetter: ad => ad.Configuration,\n                 expectedDefaultValue: null,\n                 allowNull: false,\n                 roundTripTestValue: config);\n        }\n\n        [Fact]\n        public void GetFilter_Returns_AttributedFilter()\n        {\n            Func<string, string, User> echoUserMethod = _controller.AddAdmin;\n            ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };\n            _arguments[\"firstName\"] = \"test\";\n            _arguments[\"lastName\"] = \"unit\";\n\n            IEnumerable<IFilter> filters = actionDescriptor.GetFilters();\n\n            Assert.NotNull(filters);\n            IFilter filter = Assert.Single(filters);\n            Assert.IsType<AuthorizeAttribute>(filter);\n        }\n\n        [Fact]\n        public void GetFilterPipeline_Returns_ConfigurationFilters()\n        {\n            IActionFilter actionFilter = new Mock<IActionFilter>().Object;\n            IExceptionFilter exceptionFilter = new Mock<IExceptionFilter>().Object;\n            IAuthorizationFilter authorizationFilter = new AuthorizeAttribute();\n            Action deleteAllUsersMethod = _controller.DeleteAllUsers;\n\n            HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), \"UsersRpcController\", typeof(UsersRpcController));\n            controllerDescriptor.Configuration.Filters.Add(actionFilter);\n            controllerDescriptor.Configuration.Filters.Add(exceptionFilter);\n            controllerDescriptor.Configuration.Filters.Add(authorizationFilter);\n            ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(controllerDescriptor, deleteAllUsersMethod.Method);\n\n            Collection<FilterInfo> filters = actionDescriptor.GetFilterPipeline();\n\n            Assert.Same(actionFilter, filters[0].Instance);\n            Assert.Same(exceptionFilter, filters[1].Instance);\n            Assert.Same(authorizationFilter, filters[2].Instance);\n        }\n\n        [Fact]\n        public void GetCustomAttributes_Returns_ActionAttributes()\n        {\n            Func<string, string, User> echoUserMethod = _controller.AddAdmin;\n            ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };\n\n            IEnumerable<IFilter> filters = actionDescriptor.GetCustomAttributes<IFilter>();\n            IEnumerable<HttpGetAttribute> httpGet = actionDescriptor.GetCustomAttributes<HttpGetAttribute>();\n\n            Assert.NotNull(filters);\n            IFilter filter = Assert.Single(filters);\n            Assert.IsType<AuthorizeAttribute>(filter);\n            Assert.NotNull(httpGet);\n            Assert.Single(httpGet);\n        }\n\n        [Fact]\n        public void GetParameters_Returns_ActionParameters()\n        {\n            Func<string, string, User> echoUserMethod = _controller.EchoUser;\n            ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };\n\n            Collection<HttpParameterDescriptor> parameterDescriptors = actionDescriptor.GetParameters();\n\n            Assert.Equal(2, parameterDescriptors.Count);\n            Assert.Contains(parameterDescriptors, p => p.ParameterName == \"firstName\");\n            Assert.Contains(parameterDescriptors, p => p.ParameterName == \"lastName\");\n        }\n\n        [Fact]\n        public Task ExecuteAsync_DoesNotCallActionWhenCancelled()\n        {\n            var cts = new CancellationTokenSource();\n            cts.Cancel();\n            Action action = () => { throw new NotImplementedException(); };\n            ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = action.Method };\n\n            return Assert.ThrowsAsync<TaskCanceledException>(() => actionDescriptor.ExecuteAsync(_context, _arguments, cts.Token));\n        }\n\n\n        [Fact]\n        public async Task ExecuteAsync_Returns_TaskOfNull_ForVoidAction()\n        {\n            Action deleteAllUsersMethod = _controller.DeleteAllUsers;\n            ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = deleteAllUsersMethod.Method };\n\n            object returnValue = await actionDescriptor.ExecuteAsync(_context, _arguments, CancellationToken.None);\n\n            Assert.Null(returnValue);\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Returns_Results_ForNonVoidAction()\n        {\n            Func<string, string, User> echoUserMethod = _controller.EchoUser;\n            ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };\n            _arguments[\"firstName\"] = \"test\";\n            _arguments[\"lastName\"] = \"unit\";\n\n            object result = await actionDescriptor.ExecuteAsync(_context, _arguments, CancellationToken.None);\n\n            var returnValue = Assert.IsType<User>(result);\n            Assert.Equal(\"test\", returnValue.FirstName);\n            Assert.Equal(\"unit\", returnValue.LastName);\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Returns_TaskOfNull_ForTaskAction()\n        {\n            Func<Task> deleteAllUsersMethod = _controller.DeleteAllUsersAsync;\n            ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = deleteAllUsersMethod.Method };\n\n            object returnValue = await actionDescriptor.ExecuteAsync(_context, _arguments, CancellationToken.None);\n\n            Assert.Null(returnValue);\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Returns_Results_ForTaskOfTAction()\n        {\n            Func<string, string, Task<User>> echoUserMethod = _controller.EchoUserAsync;\n            ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };\n            _arguments[\"firstName\"] = \"test\";\n            _arguments[\"lastName\"] = \"unit\";\n\n            object result = await actionDescriptor.ExecuteAsync(_context, _arguments, CancellationToken.None);\n\n            var returnValue = Assert.IsType<User>(result);\n            Assert.Equal(\"test\", returnValue.FirstName);\n            Assert.Equal(\"unit\", returnValue.LastName);\n        }\n\n        [Fact]\n        public void ExecuteAsync_Throws_IfContextIsNull()\n        {\n            Func<string, string, User> echoUserMethod = _controller.EchoUser;\n            ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };\n\n            Assert.ThrowsArgumentNull(\n                () => actionDescriptor.ExecuteAsync(null, _arguments, CancellationToken.None),\n                \"controllerContext\");\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Throws_IfArgumentsIsNull()\n        {\n            Func<string, string, User> echoUserMethod = _controller.EchoUser;\n            ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };\n\n            await Assert.ThrowsAsync<ArgumentNullException>(\n                () => actionDescriptor.ExecuteAsync(_context, null, CancellationToken.None),\n                \"arguments\",\n                partialMatch: true);\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Throws_IfValueTypeArgumentsIsNull()\n        {\n            Func<int, User> retrieveUserMethod = _controller.RetriveUser;\n            ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = retrieveUserMethod.Method };\n            _arguments[\"id\"] = null;\n\n            var exception = await Assert.ThrowsAsync<HttpResponseException>(\n                 () => actionDescriptor.ExecuteAsync(_context, _arguments, CancellationToken.None));\n\n            Assert.Equal(HttpStatusCode.BadRequest, exception.Response.StatusCode);\n            var content = Assert.IsType<ObjectContent<HttpError>>(exception.Response.Content);\n            Assert.Equal(\"The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' \" +\n                \"for method 'System.Web.Http.User RetriveUser(Int32)' in 'System.Web.Http.UsersRpcController'. An optional parameter \" +\n                \"must be a reference type, a nullable type, or be declared as an optional parameter.\",\n                ((HttpError)content.Value)[\"MessageDetail\"]);\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Throws_IfArgumentNameIsWrong()\n        {\n            Func<int, User> retrieveUserMethod = _controller.RetriveUser;\n            ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = retrieveUserMethod.Method };\n            _arguments[\"otherId\"] = 6;\n\n            var exception = await Assert.ThrowsAsync<HttpResponseException>(\n                () => actionDescriptor.ExecuteAsync(_context, _arguments, CancellationToken.None));\n\n            Assert.Equal(HttpStatusCode.BadRequest, exception.Response.StatusCode);\n            var content = Assert.IsType<ObjectContent<HttpError>>(exception.Response.Content);\n            Assert.Equal(\"The parameters dictionary does not contain an entry for parameter 'id' of type 'System.Int32' \" +\n                \"for method 'System.Web.Http.User RetriveUser(Int32)' in 'System.Web.Http.UsersRpcController'. \" +\n                \"The dictionary must contain an entry for each parameter, including parameters that have null values.\",\n                ((HttpError)content.Value)[\"MessageDetail\"]);\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Throws_IfArgumentTypeIsWrong()\n        {\n            Func<int, User> retrieveUserMethod = _controller.RetriveUser;\n            ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = retrieveUserMethod.Method };\n            _arguments[\"id\"] = new DateTime();\n\n            var exception = await Assert.ThrowsAsync<HttpResponseException>(\n                 () => actionDescriptor.ExecuteAsync(_context, _arguments, CancellationToken.None));\n\n            Assert.Equal(HttpStatusCode.BadRequest, exception.Response.StatusCode);\n            var content = Assert.IsType<ObjectContent<HttpError>>(exception.Response.Content);\n            Assert.Equal(\"The parameters dictionary contains an invalid entry for parameter 'id' for method \" +\n                \"'System.Web.Http.User RetriveUser(Int32)' in 'System.Web.Http.UsersRpcController'. \" +\n                \"The dictionary contains a value of type 'System.DateTime', but the parameter requires a value \" +\n                \"of type 'System.Int32'.\",\n                ((HttpError)content.Value)[\"MessageDetail\"]);\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_IfTaskReturningMethod_ReturnsWrappedTaskInstance_Throws()\n        {\n            Func<Task> method = _controller.WrappedTaskReturningMethod;\n            ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = method.Method };\n\n            await Assert.ThrowsAsync<InvalidOperationException>(\n                 () => actionDescriptor.ExecuteAsync(_context, _arguments, CancellationToken.None),\n                 \"The method 'WrappedTaskReturningMethod' on type 'UsersRpcController' returned an instance of 'System.Threading.Tasks.Task`1[[System.Threading.Tasks.Task, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'. Make sure to call Unwrap on the returned value to avoid unobserved faulted Task.\");\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_IfObjectReturningMethod_ReturnsTaskInstance_Throws()\n        {\n            Func<object> method = _controller.TaskAsObjectReturningMethod;\n            ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = method.Method };\n\n            await Assert.ThrowsAsync<InvalidOperationException>(\n                 () => actionDescriptor.ExecuteAsync(_context, _arguments, CancellationToken.None),\n                 \"The method 'TaskAsObjectReturningMethod' on type 'UsersRpcController' returned a Task instance even though it is not an asynchronous method.\");\n        }\n\n        [Theory]\n        [InlineData(typeof(void), null)]\n        [InlineData(typeof(string), typeof(string))]\n        [InlineData(typeof(Task), null)]\n        [InlineData(typeof(Task<string>), typeof(string))]\n        public void GetReturnType_ReturnsUnwrappedActionType(Type methodReturnType, Type expectedReturnType)\n        {\n            Mock<MethodInfo> methodMock = new Mock<MethodInfo>();\n            methodMock.Setup(m => m.ReturnType).Returns(methodReturnType);\n\n            Assert.Equal(expectedReturnType, ReflectedHttpActionDescriptor.GetReturnType(methodMock.Object));\n        }\n\n        [Fact]\n        public void GetHashCode_ReturnsTheSameHashCode_ForDifferentInstancesWithTheSameMethodInfo()\n        {\n            Func<string, string, User> echoUserMethod = _controller.EchoUser;\n            HttpConfiguration config = new HttpConfiguration();\n            HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(config, \"\", typeof(UsersRpcController));\n            ReflectedHttpActionDescriptor actionDescriptor1 = new ReflectedHttpActionDescriptor(controllerDescriptor, echoUserMethod.Method);\n            ReflectedHttpActionDescriptor actionDescriptor2 = new ReflectedHttpActionDescriptor(controllerDescriptor, echoUserMethod.Method);\n\n            Assert.Equal(actionDescriptor1.GetHashCode(), actionDescriptor2.GetHashCode());\n        }\n\n        [Fact]\n        public void Equals_ReturnsTrue_ForDifferentInstancesWithTheSameMethodInfo()\n        {\n            Func<string, string, User> echoUserMethod = _controller.EchoUser;\n            HttpConfiguration config = new HttpConfiguration();\n            HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(config, \"\", typeof(UsersRpcController));\n            ReflectedHttpActionDescriptor actionDescriptor1 = new ReflectedHttpActionDescriptor(controllerDescriptor, echoUserMethod.Method);\n            ReflectedHttpActionDescriptor actionDescriptor2 = new ReflectedHttpActionDescriptor(controllerDescriptor, echoUserMethod.Method);\n\n            Assert.Equal(actionDescriptor1, actionDescriptor2);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Controllers/ReflectedHttpParameterDescriptorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing System.Web.Http.Controllers;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http\n{\n    public class ReflectedHttpParameterDescriptorTest\n    {\n        [Fact]\n        public void Parameter_Constructor()\n        {\n            UsersRpcController controller = new UsersRpcController();\n            Func<string, string, User> echoUserMethod = controller.EchoUser;\n            ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };\n            ParameterInfo parameterInfo = echoUserMethod.Method.GetParameters()[0];\n            ReflectedHttpParameterDescriptor parameterDescriptor = new ReflectedHttpParameterDescriptor(actionDescriptor, parameterInfo);\n\n            Assert.Equal(actionDescriptor, parameterDescriptor.ActionDescriptor);\n            Assert.Null(parameterDescriptor.DefaultValue);\n            Assert.Equal(parameterInfo, parameterDescriptor.ParameterInfo);\n            Assert.Equal(parameterInfo.Name, parameterDescriptor.ParameterName);\n            Assert.Equal(typeof(string), parameterDescriptor.ParameterType);\n            Assert.Null(parameterDescriptor.Prefix);\n            Assert.Null(parameterDescriptor.ParameterBinderAttribute);\n            Assert.False(parameterDescriptor.IsOptional);\n        }\n\n        [Fact]\n        public void Constructor_Throws_IfParameterInfoIsNull()\n        {\n            Assert.ThrowsArgumentNull(\n                () => new ReflectedHttpParameterDescriptor(new Mock<HttpActionDescriptor>().Object, null),\n                \"parameterInfo\");\n        }\n\n        [Fact]\n        public void Constructor_Throws_IfActionDescriptorIsNull()\n        {\n            Assert.ThrowsArgumentNull(\n                () => new ReflectedHttpParameterDescriptor(null, new Mock<ParameterInfo>().Object),\n                \"actionDescriptor\");\n        }\n\n        [Fact]\n        public void ParameterInfo_Property()\n        {\n            ParameterInfo referenceParameter = new Mock<ParameterInfo>().Object;\n            Assert.Reflection.Property(new ReflectedHttpParameterDescriptor(), d => d.ParameterInfo, expectedDefaultValue: null, allowNull: false, roundTripTestValue: referenceParameter);\n        }\n\n        [Fact]\n        public void ParameterBinderAttribute_NotNull_WhenParameterAttributeIsFound()\n        {\n            UsersRpcController controller = new UsersRpcController();\n            Action<User> addUserMethod = controller.AddUser;\n            ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = addUserMethod.Method };\n            ParameterInfo parameterInfo = addUserMethod.Method.GetParameters()[0];\n            ReflectedHttpParameterDescriptor parameterDescriptor = new ReflectedHttpParameterDescriptor(actionDescriptor, parameterInfo);\n            Assert.NotNull(parameterDescriptor.ParameterBinderAttribute);\n        }\n\n        private static void MethodWithOptionalParam(int id = 7) { }\n\n        [Fact]\n        public void IsOptional_Returns_True_ForOptionalParameter()\n        {\n            UsersRpcController controller = new UsersRpcController();\n            MethodInfo methodWithOptionalParam = GetType().GetMethod(\"MethodWithOptionalParam\", BindingFlags.Static | BindingFlags.NonPublic);\n            ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = methodWithOptionalParam };\n            ParameterInfo parameterInfo = methodWithOptionalParam.GetParameters()[0];\n            ReflectedHttpParameterDescriptor parameterDescriptor = new ReflectedHttpParameterDescriptor(actionDescriptor, parameterInfo);\n            Assert.True(parameterDescriptor.IsOptional);\n        }\n\n        [Fact]\n        public void GetCustomAttributes_Returns_ParameterAttributes()\n        {\n            UsersRpcController controller = new UsersRpcController();\n            Action<User> addUserMethod = controller.AddUser;\n            ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = addUserMethod.Method };\n            ParameterInfo parameterInfo = addUserMethod.Method.GetParameters()[0];\n            ReflectedHttpParameterDescriptor parameterDescriptor = new ReflectedHttpParameterDescriptor(actionDescriptor, parameterInfo);\n            object[] attributes = parameterDescriptor.GetCustomAttributes<object>().ToArray();\n\n            object attribute = Assert.Single(attributes);\n            Assert.IsType<FromBodyAttribute>(attribute);\n        }\n\n        [Fact]\n        public void GetCustomAttributes_AttributeType_Returns_ParameterAttributes()\n        {\n            UsersRpcController controller = new UsersRpcController();\n            Action<User> addUserMethod = controller.AddUser;\n            ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = addUserMethod.Method };\n            ParameterInfo parameterInfo = addUserMethod.Method.GetParameters()[0];\n            ReflectedHttpParameterDescriptor parameterDescriptor = new ReflectedHttpParameterDescriptor(actionDescriptor, parameterInfo);\n            IEnumerable<FromBodyAttribute> attributes = parameterDescriptor.GetCustomAttributes<FromBodyAttribute>();\n\n            Assert.Single(attributes);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Controllers/RequestBackedHttpRequestContextTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Security.Cryptography.X509Certificates;\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Controllers\n{\n    public class RequestBackedHttpRequestContextTests\n    {\n        [Fact]\n        public void ConstructorWithRequest_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            HttpRequestMessage request = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => new RequestBackedHttpRequestContext(request), \"request\");\n        }\n\n        [Fact]\n        public void RequestGet_ReturnsInstanceProvidedInConstructorWithRequest()\n        {\n            // Arrange\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                RequestBackedHttpRequestContext context = CreateProductUnderTest(expectedRequest);\n\n                // Act\n                HttpRequestMessage request = context.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public void RequestSet_UpdatesRequest()\n        {\n            // Arrange\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                RequestBackedHttpRequestContext context = CreateProductUnderTest();\n\n                // Act\n                context.Request = expectedRequest;\n\n                // Assert\n                Assert.Same(expectedRequest, context.Request);\n            }\n        }\n\n        [Fact]\n        public void ClientCertificateGet_ReturnsNull_AsDefault()\n        {\n            // Arrange\n            HttpRequestContext context = CreateProductUnderTest();\n\n            // Act\n            X509Certificate2 certificate = context.ClientCertificate;\n\n            // Assert\n            Assert.Null(certificate);\n        }\n\n        [Fact]\n        public void ClientCertificateSet_UpdatesClientCertificate()\n        {\n            // Arrange\n            HttpRequestContext context = CreateProductUnderTest();\n            X509Certificate2 expectedCertificate = CreateCertificate();\n\n            // Act\n            context.ClientCertificate = expectedCertificate;\n\n            // Assert\n            X509Certificate2 certificate = context.ClientCertificate;\n            Assert.Same(expectedCertificate, certificate);\n        }\n\n        [Fact]\n        public void ClientCertificateGet_ReturnsClientCertificateFromProperty_WhenRequestIsPresent()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(request);\n                X509Certificate2 expectedCertificate = CreateCertificate();\n                request.Properties[HttpPropertyKeys.ClientCertificateKey] = expectedCertificate;\n\n                // Act\n                X509Certificate2 certificate = context.ClientCertificate;\n\n                // Assert\n                Assert.Same(expectedCertificate, certificate);\n            }\n        }\n\n        [Fact]\n        public void ClientCertificateGet_IgnoresRequest_AfterClientCertificateSet()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(request);\n                X509Certificate2 expectedCertificate = CreateCertificate();\n                context.ClientCertificate = expectedCertificate;\n                request.Properties[HttpPropertyKeys.ClientCertificateKey] = CreateCertificate();\n\n                // Act\n                X509Certificate2 certificate = context.ClientCertificate;\n\n                // Assert\n                Assert.Same(expectedCertificate, certificate);\n            }\n        }\n\n        [Fact]\n        public void ClientCertificateGet_IgnoresRequest_AfterClientCertificateSetNull()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(request);\n                context.ClientCertificate = null;\n                request.Properties[HttpPropertyKeys.ClientCertificateKey] = CreateCertificate();\n\n                // Act\n                X509Certificate2 certificate = context.ClientCertificate;\n\n                // Assert\n                Assert.Null(certificate);\n            }\n        }\n\n        [Fact]\n        public void ConfigurationGet_ReturnsNull_AsDefault()\n        {\n            // Arrange\n            HttpRequestContext context = CreateProductUnderTest();\n\n            // Act\n            HttpConfiguration configuration = context.Configuration;\n\n            // Assert\n            Assert.Null(configuration);\n        }\n\n        [Fact]\n        public void ConfigurationSet_UpdatesConfiguration()\n        {\n            // Arrange\n            using (HttpConfiguration expectedConfiguration = CreateConfiguration())\n            {\n                HttpRequestContext context = CreateProductUnderTest();\n\n                // Act\n                context.Configuration = expectedConfiguration;\n\n                // Assert\n                HttpConfiguration configuration = context.Configuration;\n                Assert.Same(expectedConfiguration, configuration);\n            }\n        }\n\n        [Fact]\n        public void ConfigurationGet_ReturnsConfigurationFromProperty_WhenRequestIsPresent()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            using (HttpConfiguration expectedConfiguration = CreateConfiguration())\n            {\n                HttpRequestContext context = CreateProductUnderTest(request);\n                request.Properties[HttpPropertyKeys.HttpConfigurationKey] = expectedConfiguration;\n\n                // Act\n                HttpConfiguration configuration = context.Configuration;\n\n                // Assert\n                Assert.Same(expectedConfiguration, configuration);\n            }\n        }\n\n        [Fact]\n        public void ConfigurationGet_IgnoresRequest_AfterConfigurationSet()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            using (HttpConfiguration expectedConfiguration = CreateConfiguration())\n            using (HttpConfiguration otherConfiguration = CreateConfiguration())\n            {\n                HttpRequestContext context = CreateProductUnderTest(request);\n                context.Configuration = expectedConfiguration;\n                request.SetConfiguration(otherConfiguration);\n\n                // Act\n                HttpConfiguration configuration = context.Configuration;\n\n                // Assert\n                Assert.Same(expectedConfiguration, configuration);\n            }\n        }\n\n        [Fact]\n        public void ConfigurationGet_IgnoresRequest_AfterConfigurationSetNull()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            using (HttpConfiguration otherConfiguration = CreateConfiguration())\n            {\n                HttpRequestContext context = CreateProductUnderTest(request);\n                context.Configuration = null;\n                request.SetConfiguration(otherConfiguration);\n\n                // Act\n                HttpConfiguration configuration = context.Configuration;\n\n                // Assert\n                Assert.Null(configuration);\n            }\n        }\n\n        [Fact]\n        public void IncludeErrorDetailGet_ReturnsFalse_AsDefault()\n        {\n            // Arrange\n            HttpRequestContext context = CreateProductUnderTest();\n\n            // Act\n            bool includeErrorDetail = context.IncludeErrorDetail;\n\n            // Assert\n            Assert.False(includeErrorDetail);\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void IncludeErrorDetailSet_UpdatesIncludeErrorDetail(bool expectedIncludeErrorDetail)\n        {\n            // Arrange\n            HttpRequestContext context = CreateProductUnderTest();\n\n            // Act\n            context.IncludeErrorDetail = expectedIncludeErrorDetail;\n\n            // Assert\n            bool includeErrorDetail = context.IncludeErrorDetail;\n            Assert.Equal(expectedIncludeErrorDetail, includeErrorDetail);\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void IncludeErrorDetailGet_ReturnsIncludeErrorDetailFromProperty_WhenRequestIsPresent(bool expected)\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(request);\n                request.Properties[HttpPropertyKeys.IncludeErrorDetailKey] = new Lazy<bool>(() => expected);\n\n                // Act\n                bool actual = context.IncludeErrorDetail;\n\n                // Assert\n                Assert.Equal(expected, actual);\n            }\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void IncludeErrorDetailGet_IgnoresRequest_AfterIncludeErrorDetailSet(bool expectedIncludeErrorDetail)\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(request);\n                context.IncludeErrorDetail = expectedIncludeErrorDetail;\n                request.Properties[HttpPropertyKeys.IncludeErrorDetailKey] =\n                    new Lazy<bool>(() => !expectedIncludeErrorDetail);\n\n                // Act\n                bool includeErrorDetail = context.IncludeErrorDetail;\n\n                // Assert\n                Assert.Equal(expectedIncludeErrorDetail, includeErrorDetail);\n            }\n        }\n\n        [Fact]\n        public void IsLocalGet_ReturnsFalse_AsDefault()\n        {\n            // Arrange\n            HttpRequestContext context = CreateProductUnderTest();\n\n            // Act\n            bool isLocal = context.IsLocal;\n\n            // Assert\n            Assert.False(isLocal);\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void IsLocalSet_UpdatesIsLocal(bool expectedIsLocal)\n        {\n            // Arrange\n            HttpRequestContext context = CreateProductUnderTest();\n\n            // Act\n            context.IsLocal = expectedIsLocal;\n\n            // Assert\n            bool isLocal = context.IsLocal;\n            Assert.Equal(expectedIsLocal, isLocal);\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void IsLocalGet_ReturnsIsLocalFromProperty_WhenRequestIsPresent(bool expected)\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(request);\n                request.Properties[HttpPropertyKeys.IsLocalKey] = new Lazy<bool>(() => expected);\n\n                // Act\n                bool actual = context.IsLocal;\n\n                // Assert\n                Assert.Equal(expected, actual);\n            }\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void IsLocalGet_IgnoresRequest_AfterIsLocalSet(bool expectedIsLocal)\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(request);\n                context.IsLocal = expectedIsLocal;\n                request.Properties[HttpPropertyKeys.IsLocalKey] =\n                    new Lazy<bool>(() => !expectedIsLocal);\n\n                // Act\n                bool isLocal = context.IsLocal;\n\n                // Assert\n                Assert.Equal(expectedIsLocal, isLocal);\n            }\n        }\n\n        [Fact]\n        [RestoreThreadPrincipal]\n        public void PrincipalGet_ReturnsThreadCurrentPrincipalFromConstructor()\n        {\n            // Arrange\n            IPrincipal expectedPrincipal = CreateDummyPrincipal();\n            Thread.CurrentPrincipal = expectedPrincipal;\n\n            // Act\n            HttpRequestContext context = CreateProductUnderTest();\n\n            // Assert\n            Thread.CurrentPrincipal = CreateDummyPrincipal();\n            Assert.Same(expectedPrincipal, context.Principal);\n        }\n\n        [Fact]\n        [RestoreThreadPrincipal]\n        public void PrincipalGet_ReturnsThreadCurrentPrincipalFromConstructorWithRequest()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IPrincipal expectedPrincipal = CreateDummyPrincipal();\n                Thread.CurrentPrincipal = expectedPrincipal;\n\n                // Act\n                HttpRequestContext context = CreateProductUnderTest(request);\n\n                // Assert\n                Thread.CurrentPrincipal = CreateDummyPrincipal();\n                Assert.Same(expectedPrincipal, context.Principal);\n            }\n        }\n\n        [Fact]\n        public void PrincipalSet_UpdatesPrincipal()\n        {\n            // Arrange\n            HttpRequestContext context = CreateProductUnderTest();\n            IPrincipal expectedPrincipal = CreateDummyPrincipal();\n\n            // Act\n            context.Principal = expectedPrincipal;\n\n            // Assert\n            Assert.Same(expectedPrincipal, context.Principal);\n        }\n\n        [Fact]\n        public void RouteDataGet_ReturnsNull_AsDefault()\n        {\n            // Arrange\n            HttpRequestContext context = CreateProductUnderTest();\n\n            // Act\n            IHttpRouteData routeData = context.RouteData;\n\n            // Assert\n            Assert.Null(routeData);\n        }\n\n        [Fact]\n        public void RouteDataSet_UpdatesRouteData()\n        {\n            // Arrange\n            HttpRequestContext context = CreateProductUnderTest();\n            IHttpRouteData expectedRouteData = CreateDummyRouteData();\n\n            // Act\n            context.RouteData = expectedRouteData;\n\n            // Assert\n            IHttpRouteData routeData = context.RouteData;\n            Assert.Same(expectedRouteData, routeData);\n        }\n\n        [Fact]\n        public void RouteDataGet_ReturnsRouteDataFromProperty_WhenRequestIsPresent()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(request);\n                IHttpRouteData expectedRouteData = CreateDummyRouteData();\n                request.Properties[HttpPropertyKeys.HttpRouteDataKey] = expectedRouteData;\n\n                // Act\n                IHttpRouteData routeData = context.RouteData;\n\n                // Assert\n                Assert.Same(expectedRouteData, routeData);\n            }\n        }\n\n        [Fact]\n        public void RouteDataGet_IgnoresRequest_AfterRouteDataSet()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(request);\n                IHttpRouteData expectedRouteData = CreateDummyRouteData();\n                context.RouteData = expectedRouteData;\n                request.Properties[HttpPropertyKeys.HttpRouteDataKey] = CreateDummyRouteData();\n\n                // Act\n                IHttpRouteData routeData = context.RouteData;\n\n                // Assert\n                Assert.Same(expectedRouteData, routeData);\n            }\n        }\n\n        [Fact]\n        public void RouteDataGet_IgnoresRequest_AfterRouteDataSetNull()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(request);\n                context.RouteData = null;\n                request.Properties[HttpPropertyKeys.HttpRouteDataKey] = CreateDummyRouteData();\n\n                // Act\n                IHttpRouteData routeData = context.RouteData;\n\n                // Assert\n                Assert.Null(routeData);\n            }\n        }\n\n        [Fact]\n        public void UrlGet_ReturnsNull_AsDefault()\n        {\n            // Arrange\n            HttpRequestContext context = CreateProductUnderTest();\n\n            // Act\n            UrlHelper url = context.Url;\n\n            // Assert\n            Assert.Null(url);\n        }\n\n        [Fact]\n        public void UrlSet_UpdatesUrl()\n        {\n            // Arrange\n            HttpRequestContext context = CreateProductUnderTest();\n            UrlHelper expectedUrl = CreateUrlHelper();\n\n            // Act\n            context.Url = expectedUrl;\n\n            // Assert\n            UrlHelper url = context.Url;\n            Assert.Same(expectedUrl, url);\n        }\n\n        [Fact]\n        public void UrlGet_ReturnsNewInstanceForRequest_WhenRequestIsPresent()\n        {\n            // Arrange\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(expectedRequest);\n\n                // Act\n                UrlHelper url = context.Url;\n\n                // Assert\n                Assert.NotNull(url);\n                Assert.Same(expectedRequest, url.Request);\n            }\n        }\n\n        [Fact]\n        public void UrlGet_IgnoresRequest_AfterUrlSet()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(request);\n                UrlHelper expectedUrl = CreateUrlHelper();\n                context.Url = expectedUrl;\n\n                // Act\n                UrlHelper url = context.Url;\n\n                // Assert\n                Assert.Same(expectedUrl, url);\n            }\n        }\n\n        [Fact]\n        public void UrlGet_IgnoresRequest_AfterUrlSetNull()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(request);\n                context.Url = null;\n\n                // Act\n                UrlHelper url = context.Url;\n\n                // Assert\n                Assert.Null(url);\n            }\n        }\n\n        [Fact]\n        public void VirtualPathRootGet_ReturnsNull_AsDefault()\n        {\n            // Arrange\n            HttpRequestContext context = CreateProductUnderTest();\n\n            // Act\n            string virtualPathRoot = context.VirtualPathRoot;\n\n            // Assert\n            Assert.Null(virtualPathRoot);\n        }\n\n        [Fact]\n        public void VirtualPathRootSet_UpdatesVirtualPathRoot()\n        {\n            // Arrange\n            HttpRequestContext context = CreateProductUnderTest();\n            string expectedVirtualPathRoot = \"/\";\n\n            // Act\n            context.VirtualPathRoot = expectedVirtualPathRoot;\n\n            // Assert\n            string virtualPathRoot = context.VirtualPathRoot;\n            Assert.Same(expectedVirtualPathRoot, virtualPathRoot);\n        }\n\n        [Fact]\n        public void VirtualPathRootGet_ReturnsConfigurationVirtualPathRoot_WhenConfigurationIsPresent()\n        {\n            // Arrange\n            string expectedVirtualPathRoot = \"/\";\n\n            using (HttpConfiguration configuration = new HttpConfiguration(new HttpRouteCollection(\n                expectedVirtualPathRoot)))\n            {\n                HttpRequestContext context = CreateProductUnderTest();\n                context.Configuration = configuration;\n\n                // Act\n                string virtualPathRoot = context.VirtualPathRoot;\n\n                // Assert\n                Assert.Same(expectedVirtualPathRoot, virtualPathRoot);\n            }\n        }\n\n        [Theory]\n        [InlineData(\"a b\")]\n        [InlineData(\"/a b\")]\n        [InlineData(\"/a%20b\")]\n        public void VirtualPathRootGet_ReturnsUnescapedConfigurationVirtualPathRoot(string configurationVirtualPathRoot)\n        {\n            // Arrange\n            var expectedVirtualPathRoot = \"/a b\";\n            using (var routeCollection = new HttpRouteCollection(configurationVirtualPathRoot))\n            using (var configuration = new HttpConfiguration(routeCollection))\n            {\n                var context = CreateProductUnderTest();\n                context.Configuration = configuration;\n\n                // Act\n                var virtualPathRoot = context.VirtualPathRoot;\n\n                // Assert\n                Assert.Equal(expectedVirtualPathRoot, virtualPathRoot);\n            }\n        }\n\n        [Fact]\n        public void VirtualPathRootGet_IgnoresConfiguration_AfterVirtualPathRootSet()\n        {\n            // Arrange\n            using (HttpConfiguration configuration = new HttpConfiguration(new HttpRouteCollection(\"other\")))\n            {\n                HttpRequestContext context = CreateProductUnderTest();\n                context.Configuration = configuration;\n                string expectedVirtualPathRoot = \"/\";\n                context.VirtualPathRoot = expectedVirtualPathRoot;\n\n                // Act\n                string virtualPathRoot = context.VirtualPathRoot;\n\n                // Assert\n                Assert.Same(expectedVirtualPathRoot, virtualPathRoot);\n            }\n        }\n\n        [Fact]\n        public void VirtualPathRootGet_IgnoresConfiguration_AfterVirtualPathRootSetNull()\n        {\n            // Arrange\n            using (HttpConfiguration configuration = new HttpConfiguration(new HttpRouteCollection(\"other\")))\n            {\n                HttpRequestContext context = CreateProductUnderTest();\n                context.Configuration = configuration;\n                context.VirtualPathRoot = null;\n\n                // Act\n                string virtualPathRoot = context.VirtualPathRoot;\n\n                // Assert\n                Assert.Null(virtualPathRoot);\n            }\n        }\n\n        private static X509Certificate2 CreateCertificate()\n        {\n            return new X509Certificate2();\n        }\n\n        private static HttpConfiguration CreateConfiguration()\n        {\n            return new HttpConfiguration();\n        }\n\n        private static IPrincipal CreateDummyPrincipal()\n        {\n            return new Mock<IPrincipal>(MockBehavior.Strict).Object;\n        }\n\n        private static IHttpRouteData CreateDummyRouteData()\n        {\n            return new Mock<IHttpRouteData>(MockBehavior.Strict).Object;\n        }\n\n        private static RequestBackedHttpRequestContext CreateProductUnderTest()\n        {\n            return new RequestBackedHttpRequestContext();\n        }\n\n        private static RequestBackedHttpRequestContext CreateProductUnderTest(HttpRequestMessage request)\n        {\n            return new RequestBackedHttpRequestContext(request);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private static UrlHelper CreateUrlHelper()\n        {\n            return new UrlHelper();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Controllers/ResponseMessageResultConverterTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Controllers\n{\n    public class ResponseMessageResultConverterTest\n    {\n        private readonly ResponseMessageResultConverter _converter = new ResponseMessageResultConverter();\n        private readonly HttpControllerContext _context = new HttpControllerContext();\n        private readonly HttpRequestMessage _request = new HttpRequestMessage();\n\n        public ResponseMessageResultConverterTest()\n        {\n            _context.Request = _request;\n            _context.Configuration = new HttpConfiguration();\n        }\n\n        [Fact]\n        public void Convert_WhenValueIsResponseMessage_ReturnsResponseMessageWithRequestAssigned()\n        {\n            HttpResponseMessage response = new HttpResponseMessage();\n\n            var result = _converter.Convert(_context, response);\n\n            Assert.Same(response, result);\n            Assert.Same(_request, result.RequestMessage);\n        }\n\n        [Fact]\n        public void Convert_WhenContextIsNull_Throws()\n        {\n            Assert.ThrowsArgumentNull(() => _converter.Convert(controllerContext: null, actionResult: new HttpResponseMessage()), \"controllerContext\");\n        }\n\n        [Fact]\n        public void Convert_WhenValueIsNull_Throws()\n        {\n            Assert.Throws<InvalidOperationException>(() => _converter.Convert(_context, null),\n                \"A null value was returned where an instance of HttpResponseMessage was expected.\");\n        }\n\n        [Fact]\n        public void Convert_WhenValueIsIncompatibleType_Throws()\n        {\n            Assert.Throws<InvalidCastException>(() => _converter.Convert(_context, \"42\"),\n                \"Unable to cast object of type 'System.String' to type 'System.Net.Http.HttpResponseMessage'.\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Controllers/ValueResultConverterTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Controllers\n{\n    public class ValueResultConverterTest\n    {\n        private readonly ValueResultConverter<object> _objectValueConverter = new ValueResultConverter<object>();\n        private readonly ValueResultConverter<Animal> _animalValueConverter = new ValueResultConverter<Animal>();\n        private readonly HttpControllerContext _context = new HttpControllerContext();\n        private readonly HttpRequestMessage _request = new HttpRequestMessage();\n\n        public ValueResultConverterTest()\n        {\n            _context.Request = _request;\n            _context.Configuration = new HttpConfiguration();\n        }\n\n        [Fact]\n        public void Convert_WhenContextIsNull_Throws()\n        {\n            Assert.ThrowsArgumentNull(() => _objectValueConverter.Convert(controllerContext: null, actionResult: new object()), \"controllerContext\");\n        }\n\n        [Fact]\n        public void Convert_WhenValueTypeIsNotCompatible_Throws()\n        {\n            Assert.Throws<InvalidCastException>(() => _animalValueConverter.Convert(_context, new object()),\n                \"Unable to cast object of type 'System.Object' to type 'Animal'.\");\n        }\n\n        [Fact]\n        public void Convert_WhenValueIsResponseMessage_ReturnsResponseMessageWithRequestAssigned()\n        {\n            HttpResponseMessage response = new HttpResponseMessage();\n\n            var result = _objectValueConverter.Convert(_context, response);\n\n            Assert.Same(response, result);\n            Assert.Same(_request, result.RequestMessage);\n        }\n\n        [Fact]\n        public void Convert_WhenValueIsAnyType_CreatesContentNegotiatedResponse()\n        {\n            Dog dog = new Dog();\n            XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter();\n            _context.Configuration.Formatters.Clear();\n            _context.Configuration.Formatters.Add(formatter);\n\n            var result = _animalValueConverter.Convert(_context, dog);\n\n            Assert.Equal(HttpStatusCode.OK, result.StatusCode);\n            var content = Assert.IsType<ObjectContent<Animal>>(result.Content);\n            Assert.Same(dog, content.Value);\n            Assert.Same(formatter, content.Formatter);\n            Assert.Same(_request, result.RequestMessage);\n        }\n\n        public class Animal { }\n        public class Dog : Animal { }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Controllers/VoidResultConverterTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Controllers\n{\n    public class VoidResultConverterTest\n    {\n        private readonly VoidResultConverter _converter = new VoidResultConverter();\n        private readonly HttpControllerContext _context = new HttpControllerContext();\n        private readonly HttpRequestMessage _request = new HttpRequestMessage();\n\n        public VoidResultConverterTest()\n        {\n            _context.Request = _request;\n            _context.Configuration = new HttpConfiguration();\n        }\n\n        [Fact]\n        public void Convert_WhenContextIsNull_Throws()\n        {\n            Assert.ThrowsArgumentNull(() => _converter.Convert(controllerContext: null, actionResult: null), \"controllerContext\");\n        }\n\n        [Fact]\n        public void Convert_ReturnsResponseMessageWithRequestAssignedAndNoContentToReflectVoid()\n        {\n            var result = _converter.Convert(_context, null);\n\n            Assert.Equal(HttpStatusCode.NoContent, result.StatusCode);\n            Assert.NotNull(result.Content);\n            Assert.Equal(0L, result.Content.Headers.ContentLength);\n            Assert.Same(_request, result.RequestMessage);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Description/ApiExplorerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Description\n{\n    public class ApiExplorerTest\n    {\n        [Fact]\n        public void Descriptions_RecognizesDirectRoutes()\n        {\n            var config = new HttpConfiguration();\n            var routeTemplate = \"api/values\";\n            var controllerDescriptor = new HttpControllerDescriptor(config, \"ApiExplorerValues\", typeof(ApiExplorerValuesController));\n            var action = new ReflectedHttpActionDescriptor(controllerDescriptor, typeof(ApiExplorerValuesController).GetMethod(\"Get\"));\n            var actions = new ReflectedHttpActionDescriptor[] { action };\n            config.Routes.Add(\"Route\", CreateDirectRoute(routeTemplate, actions));\n\n            var descriptions = new ApiExplorer(config).ApiDescriptions;\n\n            ApiDescription description = Assert.Single(descriptions);\n            Assert.Equal(HttpMethod.Get, description.HttpMethod);\n            Assert.Equal(routeTemplate, description.RelativePath);\n            Assert.Equal(action, description.ActionDescriptor);\n        }\n\n        [Fact]\n        public void Descriptions_RecognizesIgnoreApiForDirectRoutes_Action()\n        {\n            var config = new HttpConfiguration();\n            var routeTemplate = \"api/values\";\n            var controllerDescriptor = new HttpControllerDescriptor(config, \"ApiExplorerValues\", typeof(ApiExplorerValuesController));\n            var actions = new ReflectedHttpActionDescriptor[] \n            {\n                new ReflectedHttpActionDescriptor(controllerDescriptor, typeof(ApiExplorerValuesController).GetMethod(\"Get\")),\n                new ReflectedHttpActionDescriptor(controllerDescriptor, typeof(ApiExplorerValuesController).GetMethod(\"Post\")),\n            };\n            config.Routes.Add(\"Route\", CreateDirectRoute(routeTemplate, actions));\n\n            var descriptions = new ApiExplorer(config).ApiDescriptions;\n\n            ApiDescription description = Assert.Single(descriptions);\n            Assert.Equal(HttpMethod.Get, description.HttpMethod);\n            Assert.Equal(routeTemplate, description.RelativePath);\n        }\n\n        [Fact]\n        public void Descriptions_RecognizesIgnoreApiForDirectRoutes_Controller()\n        {\n            var config = new HttpConfiguration();\n            var routeTemplate = \"api/values\";\n            var controllerDescriptor = new HttpControllerDescriptor(config, \"IgnoreApiValues\", typeof(IgnoreApiValuesController));\n            var actions = new ReflectedHttpActionDescriptor[] \n            {\n                new ReflectedHttpActionDescriptor(controllerDescriptor, typeof(IgnoreApiValuesController).GetMethod(\"Get\")),\n                new ReflectedHttpActionDescriptor(controllerDescriptor, typeof(IgnoreApiValuesController).GetMethod(\"Post\")),\n            };\n            config.Routes.Add(\"Route\", CreateDirectRoute(routeTemplate, actions));\n\n            var descriptions = new ApiExplorer(config).ApiDescriptions;\n\n            Assert.Empty(descriptions);\n        }\n\n        public class ApiExplorerValuesController : ApiController\n        {\n            public void Get() { }\n\n            [ApiExplorerSettings(IgnoreApi = true)]\n            public void Post() { }\n        }\n\n        [ApiExplorerSettings(IgnoreApi = true)]\n        public class IgnoreApiValuesController : ApiController\n        {\n            public void Get() { }\n            public void Post() { }\n        }\n\n        [Fact]\n        public void Descriptions_RecognizesCompositeRoutes()\n        {\n            var config = new HttpConfiguration();\n            var routeTemplate = \"api/values\";\n            var controllerDescriptor = new HttpControllerDescriptor(config, \"AttributeApiExplorerValues\", typeof(AttributeApiExplorerValuesController));\n            var action = new ReflectedHttpActionDescriptor(controllerDescriptor, typeof(AttributeApiExplorerValuesController).GetMethod(\"Action\"));\n            var actions = new ReflectedHttpActionDescriptor[] { action };\n\n            var routeCollection = new List<IHttpRoute>();\n            routeCollection.Add(CreateDirectRoute(routeTemplate, actions));\n\n            RouteCollectionRoute route = new RouteCollectionRoute();\n            route.EnsureInitialized(() => routeCollection);\n\n            config.Routes.Add(\"Route\", route);\n\n            var descriptions = new ApiExplorer(config).ApiDescriptions;\n\n            ApiDescription description = Assert.Single(descriptions);\n            Assert.Equal(HttpMethod.Get, description.HttpMethod);\n            Assert.Equal(routeTemplate, description.RelativePath);\n            Assert.Equal(action, description.ActionDescriptor);\n        }\n\n        [Fact]\n        public void TryExpandUriParameters_EnsureNoKeyConflicts()\n        {\n            // This test ensures that keys adding to parameterValuesForRoute are case-insensitive\n            // and would not cause any exeception if it already has the key. So set up two\n            // ApiParameterDescription instances, one with \"id\" and another with \"Id\". Act the\n            // method and assert that no exception occurs and the output is correct.\n            // Arrange\n            string expectedExpandedRouteTemplate = \"?id={id}\";\n            string expandedRouteTemplate;\n            Mock<HttpParameterDescriptor> parameterDescriptorMock = new Mock<HttpParameterDescriptor>();\n            parameterDescriptorMock.SetupGet(p => p.ParameterType).Returns(typeof(ClassWithId));\n            List<ApiParameterDescription> descriptions = new List<ApiParameterDescription>()\n            {\n                new ApiParameterDescription()\n                {\n                    Source = ApiParameterSource.FromUri,\n                    Name = \"id\"\n                },\n                new ApiParameterDescription()\n                {\n                    Source = ApiParameterSource.FromUri,\n                    ParameterDescriptor = parameterDescriptorMock.Object\n                },\n            };\n\n            // Act\n            bool isExpanded = ApiExplorer.TryExpandUriParameters(new HttpRoute(),\n                                                     new HttpParsedRoute(new List<PathSegment>()),\n                                                     descriptions,\n                                                     out expandedRouteTemplate);\n\n            // Assert\n            Assert.True(isExpanded);\n            Assert.Equal(expectedExpandedRouteTemplate, expandedRouteTemplate);\n        }\n\n\n        [Theory]\n        // Simple type\n        [InlineData(\"?id={id}\", typeof(int), \"id\")]\n        // Simple Array and Collection\n        [InlineData(\"?id[0]={id[0]}&id[1]={id[1]}\", typeof(int[]), \"id\")]\n        [InlineData(\"?id[0]={id[0]}&id[1]={id[1]}\", typeof(string[]), \"id\")]\n        [InlineData(\"?id[0]={id[0]}&id[1]={id[1]}\", typeof(IList<string>), \"id\")]\n        [InlineData(\"?id[0]={id[0]}&id[1]={id[1]}\", typeof(List<string>), \"id\")]\n        [InlineData(\"?id[0]={id[0]}&id[1]={id[1]}\", typeof(IEnumerable<string>), \"id\")]\n        [InlineData(\"?id[0]={id[0]}&id[1]={id[1]}\", typeof(ICollection<int>), \"id\")]\n        // Complex Array and Collection\n        [InlineData(\"?users[0].Name={users[0].Name}&users[0].Age={users[0].Age}\" +\n                        \"&users[1].Name={users[1].Name}&users[1].Age={users[1].Age}\",\n                    typeof(IEnumerable<User>),\n                    \"users\")]\n        [InlineData(\"?users[0].Name={users[0].Name}&users[0].Age={users[0].Age}\" +\n                        \"&users[1].Name={users[1].Name}&users[1].Age={users[1].Age}\",\n                    typeof(User[]),\n                    \"users\")]\n        // MutableObject\n        [InlineData(\"?Foo={Foo}&Bar={Bar}\", typeof(MutableObject), \"mutable\")]\n        // KeyValuePair\n        [InlineData(\"?key={key}&value={value}\", typeof(KeyValuePair<string, string>), \"pair\")]\n        // Dictionary\n        [InlineData(\"?dict[0].key={dict[0].key}&dict[0].value={dict[0].value}&dict[1].key={dict[1].key}\" +\n                        \"&dict[1].value={dict[1].value}\",\n                    typeof(Dictionary<string, string>),\n                    \"dict\")]\n        // MutableObject extending IList<> does not generate query string samples like ?id[0]={id[0]}&id[1]={id[1]}.\n        // Note that the \"Item\" query string in the following is not valid,\n        // which is a bug but will happen in rare cases.\n        [InlineData(\"?Foo={Foo}&Bar={Bar}&Capacity={Capacity}&Item={Item}\",\n                    typeof(GenericMutableObject<string>),\n                    \"genericMutable\")]\n        public void TryExpandUriParameters_FromUri_Succeeds(string expectedPath,\n                                                                      Type parameterType,\n                                                                      string parameterName)\n        {\n            // Arrange\n            string finalPath;\n            List<ApiParameterDescription> descriptions = new List<ApiParameterDescription>()\n            {\n                CreateApiParameterDescription(parameterType, parameterName),\n            };\n\n            // Act\n            bool isExpanded = ApiExplorer.TryExpandUriParameters(new HttpRoute(),\n                                                     new HttpParsedRoute(new List<PathSegment>()),\n                                                     descriptions,\n                                                     out finalPath);\n\n            // Assert\n            Assert.True(isExpanded);\n            Assert.Equal(expectedPath, finalPath);\n        }\n\n        [Fact]\n        public void TryExpandUriParameters_CompositeParametersFromUri_Succeeds()\n        {\n            // Arrange\n            string finalPath;\n            const string expectedPath = \n                \"?id[0]={id[0]}&id[1]={id[1]}&property[0]={property[0]}&property[1]={property[1]}&name={name}\";\n            List<ApiParameterDescription> descriptions = new List<ApiParameterDescription>()\n            {\n                CreateApiParameterDescription(typeof(int[]), \"id\"),\n                CreateApiParameterDescription(typeof(ICollection<string>), \"property\"),\n                CreateApiParameterDescription(typeof(string), \"name\"),\n            };\n\n            // Act\n            bool isExpanded = ApiExplorer.TryExpandUriParameters(new HttpRoute(),\n                                                     new HttpParsedRoute(new List<PathSegment>()),\n                                                     descriptions,\n                                                     out finalPath);\n\n            // Assert\n            Assert.True(isExpanded);\n            Assert.Equal(expectedPath, finalPath);\n        }\n\n        [Fact]\n        public void Descriptions_RecognizesMixedCaseParameters()\n        {\n            // Ensure that two \"Id\"s, one from \"api/values/{id}\" and another \"Id\" from ClassWithId,\n            // would not cause any exception and only one of them is added.\n            var config = new HttpConfiguration();\n            var routeTemplate = \"api/values/{id}\";\n            var controllerDescriptor = new HttpControllerDescriptor(config, \"ApiExplorerValues\", typeof(DuplicatedIdController));\n            var action = new ReflectedHttpActionDescriptor(controllerDescriptor, typeof(DuplicatedIdController).GetMethod(\"Get\"));\n            var actions = new ReflectedHttpActionDescriptor[] { action };\n            config.Routes.Add(\"Route\", CreateDirectRoute(routeTemplate, actions));\n\n            var descriptions = new ApiExplorer(config).ApiDescriptions;\n\n            ApiDescription description = Assert.Single(descriptions);\n            Assert.Equal(HttpMethod.Get, description.HttpMethod);\n            Assert.Equal(routeTemplate, description.RelativePath, StringComparer.OrdinalIgnoreCase);\n            Assert.Equal(action, description.ActionDescriptor);\n        }\n\n        private class ClassWithId\n        {\n            public int Id { get; set; }\n        }\n\n        private class DuplicatedIdController : ApiController\n        {\n            public void Get([FromUri] ClassWithId objectWithId) { }\n        }\n\n        public class AttributeApiExplorerValuesController : ApiController\n        {\n            [Route(\"\")]\n            [HttpGet]\n            public void Action() { }\n        }\n\n        private static IHttpRoute CreateDirectRoute(string template,\n            IReadOnlyCollection<ReflectedHttpActionDescriptor> actions)\n        {\n            DirectRouteBuilder builder = new DirectRouteBuilder(actions, targetIsAction: true);\n            builder.Template = template;\n            return builder.Build().Route;\n        }\n\n        private ApiParameterDescription CreateApiParameterDescription(Type type, string name)\n        {\n            Mock<HttpParameterDescriptor> parameterDescriptorMock = new Mock<HttpParameterDescriptor>();\n            parameterDescriptorMock.SetupGet(p => p.ParameterName).Returns(name);\n            parameterDescriptorMock.SetupGet(p => p.ParameterType).Returns(type);\n            return new ApiParameterDescription()\n            {\n                Source = ApiParameterSource.FromUri,\n                ParameterDescriptor = parameterDescriptorMock.Object,\n                Name = name\n            };\n        }\n\n        private class MutableObject\n        {\n            public string Foo { get; set; }\n            public string Bar { get; set; }\n        }\n\n        private class GenericMutableObject<T> : List<T>\n        {\n            public string Foo { get; set; }\n            public string Bar { get; set; }\n        }\n\n        private class User\n        {\n            public string Name { get; set; }\n            public int Age { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Description/ApiParameterDescriptionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Web.Http.Controllers;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Description\n{\n    public class ApiParameterDescriptionTest\n    {\n        [Fact]\n        public void GetBindableProperties_WorksOnlyFor_PublicInstanceProperties_WithPublicGettersAndSetters()\n        {\n            // Arrange\n            ApiParameterDescription parameter = new ApiParameterDescription();\n            Mock<HttpParameterDescriptor> parameterDescriptorMock = new Mock<HttpParameterDescriptor>();\n            parameterDescriptorMock.SetupGet(p => p.ParameterType).Returns(typeof(ClassWithAllKindsOfProperties));\n            parameter.ParameterDescriptor = parameterDescriptorMock.Object;\n\n            // Act\n            IEnumerable<PropertyInfo> bindableProperties = parameter.GetBindableProperties();\n\n            // Assert\n            PropertyInfo bindableProperty = Assert.Single(bindableProperties);\n            Assert.Equal(\"ValidProperty\", bindableProperty.Name);\n        }\n    }\n\n    internal class ClassWithAllKindsOfProperties\n    {\n        public int ValidProperty { get; set; }\n        public static string InvalidProperty { get; set; }\n        public int PropertyWithPrivateSetter { get; private set; }\n        public int PropertyWithPrivateGetter { private get; set; }\n        internal int InternalProperty { get; set; }\n        protected int ProtectedProperty { get; private set; }\n        private int PrivateProperty { get; set; }\n        public int PropertyWithoutSetter { get { return 0; } }\n        public int PropertyWithoutGetter { set { return; } }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Dispatcher/DefaultAssembliesResolverTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing System.Web.Http.Services;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Dispatcher\n{\n    public class DefaultAssembliesResolverTest\n    {\n        [Fact]\n        public void GetAssemblies_ContainsCurrentAssembly()\n        {\n            IAssembliesResolver ar = new DefaultAssembliesResolver();\n            Assembly currentAssembly = typeof(DefaultAssembliesResolverTest).Assembly;\n\n            Assert.True(ar.GetAssemblies().Contains(currentAssembly));\n        }\n\n        [Fact]\n        public void Class_IsDefaultIAssembliesResolver()\n        {\n            var serviceResolver = new DefaultServices(new HttpConfiguration());\n\n            Assert.IsType<DefaultAssembliesResolver>(serviceResolver.GetService(typeof(IAssembliesResolver)));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Dispatcher/DefaultHttpControllerActivatorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Dependencies;\nusing System.Web.Http.Hosting;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Dispatcher\n{\n    public class DefaultHttpControllerActivatorTest\n    {\n        // Create tests\n\n        [Fact]\n        public void Create_GuardClauses()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var request = new HttpRequestMessage();\n            request.SetConfiguration(config);\n            var descriptor = new HttpControllerDescriptor(config, \"Simple\", typeof(SimpleController));\n            var activator = new DefaultHttpControllerActivator();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(() => activator.Create(request: null, controllerDescriptor: descriptor, controllerType: typeof(SimpleController)), \"request\");\n            Assert.ThrowsArgumentNull(() => activator.Create(request, controllerDescriptor: null, controllerType: typeof(SimpleController)), \"controllerDescriptor\");\n            Assert.ThrowsArgumentNull(() => activator.Create(request, descriptor, controllerType: null), \"controllerType\");\n            Assert.Throws<InvalidOperationException>(\n                () => activator.Create(request, descriptor, typeof(AbstractController)),\n                \"An error occurred when trying to create a controller of type 'AbstractController'. Make sure that the controller has a parameterless public constructor.\");\n            Assert.Throws<InvalidOperationException>(\n                () => activator.Create(request, descriptor, typeof(ControllerWithCtorParams)),\n                \"An error occurred when trying to create a controller of type 'ControllerWithCtorParams'. Make sure that the controller has a parameterless public constructor.\");\n        }\n\n        [Fact]\n        public void Create_MakesInstanceOfController()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var request = new HttpRequestMessage();\n            request.SetConfiguration(config);\n            var descriptor = new HttpControllerDescriptor(config, \"Simple\", typeof(SimpleController));\n            var activator = new DefaultHttpControllerActivator();\n\n            // Act\n            IHttpController result = activator.Create(request, descriptor, typeof(SimpleController));\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.IsType<SimpleController>(result);\n        }\n\n        [Fact]\n        public void Create_UsesControllerFromRequestLevelDependencyScope()\n        {\n            // Arrange\n            var controller = new ControllerWithCtorParams(42);\n            var mockScope = new Mock<IDependencyScope>();\n            mockScope.Setup(r => r.GetService(typeof(ControllerWithCtorParams))).Returns(controller).Verifiable();\n            var config = new HttpConfiguration();\n            var request = new HttpRequestMessage();\n            request.SetConfiguration(config);\n            request.Properties[HttpPropertyKeys.DependencyScope] = mockScope.Object;\n            var descriptor = new HttpControllerDescriptor(config, \"Name\", typeof(ControllerWithCtorParams));\n            var activator = new DefaultHttpControllerActivator();\n\n            // Act\n            IHttpController result = activator.Create(request, descriptor, typeof(ControllerWithCtorParams));\n\n            // Assert\n            Assert.Same(controller, result);\n            mockScope.Verify();\n        }\n\n        [Fact]\n        public void Create_DoesnotCacheControllerFromRequestLevelDependencyScope()\n        {\n            // Arrange\n            int count = 0;\n            var controller = new ControllerWithCtorParams(42);\n            var mockScope = new Mock<IDependencyScope>();\n            mockScope.Setup(r => r.GetService(typeof(ControllerWithCtorParams))).Returns(() =>\n            {\n                count++;\n                return new ControllerWithCtorParams(42);\n            }).Verifiable();\n            var config = new HttpConfiguration();\n            var request = new HttpRequestMessage();\n            request.SetConfiguration(config);\n            request.Properties[HttpPropertyKeys.DependencyScope] = mockScope.Object;\n            var descriptor = new HttpControllerDescriptor(config, \"Name\", typeof(ControllerWithCtorParams));\n            var activator = new DefaultHttpControllerActivator();\n\n            // Act\n            IHttpController result1 = activator.Create(request, descriptor, typeof(ControllerWithCtorParams));\n            IHttpController result2 = activator.Create(request, descriptor, typeof(ControllerWithCtorParams));\n\n            // Assert\n            Assert.NotEqual(result1, result2);\n            mockScope.Verify();\n            Assert.Equal(2, count);\n        }\n\n        [Fact]\n        public void Create_MixupInstanceCreationAndDependencyScope()\n        {\n            // Arrange\n            var controller = new ControllerWithCtorParams(42);\n            var mockScope = new Mock<IDependencyScope>();\n            mockScope.Setup(r => r.GetService(typeof(ControllerWithCtorParams))).Returns(controller).Verifiable();\n            var config = new HttpConfiguration();\n            var request = new HttpRequestMessage();\n            request.SetConfiguration(config);\n            request.Properties[HttpPropertyKeys.DependencyScope] = mockScope.Object;\n            var descriptorControllerWithCtorParamsResult = new HttpControllerDescriptor(config, \"Name\", typeof(ControllerWithCtorParams));\n            var descriptorSimpleController = new HttpControllerDescriptor(config, \"Simple\", typeof(SimpleController));\n            var activator = new DefaultHttpControllerActivator();\n\n            // Act\n            IHttpController simpleController = activator.Create(request, descriptorSimpleController, typeof(SimpleController));\n            IHttpController controllerWithCtorParamsResult = activator.Create(request, descriptorControllerWithCtorParamsResult, typeof(ControllerWithCtorParams));\n\n            // Assert\n            Assert.NotNull(simpleController);\n            Assert.IsType<SimpleController>(simpleController);\n            Assert.Same(controller, controllerWithCtorParamsResult);\n            mockScope.Verify();\n        }\n\n        [Fact]\n        public void Create_ThrowsForNullDependencyScope()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var mockResolver = new Mock<IDependencyResolver>();\n            mockResolver.Setup(resolver => resolver.BeginScope()).Returns((IDependencyScope)null).Verifiable();\n            config.DependencyResolver = mockResolver.Object;\n            var request = new HttpRequestMessage();\n            request.SetConfiguration(config);\n            var descriptorSimpleController = new HttpControllerDescriptor(config, \"Simple\", typeof(SimpleController));\n            var activator = new DefaultHttpControllerActivator();\n\n            // Act & Assert\n            InvalidOperationException exception = Assert.Throws<InvalidOperationException>(\n                () => activator.Create(request, descriptorSimpleController, typeof(SimpleController)));\n\n            Assert.Equal(\n                \"An error occurred when trying to create a controller of type 'SimpleController'. Make sure that the controller has a parameterless public constructor.\",\n                exception.Message);\n            Assert.NotNull(exception.InnerException);\n            Assert.Matches(\n                \"A dependency resolver of type 'IDependencyResolverProxy' returned an invalid value of null from its \" +\n                \"BeginScope method. If the container does not have a concept of scope, consider returning a scope \" +\n                \"that resolves in the root of the container instead.\",\n                exception.InnerException.Message);\n\n            mockResolver.Verify();\n        }\n\n        // Helper classes\n\n        abstract class AbstractController : ApiController { }\n\n        class SimpleController : ApiController { }\n\n        class ControllerWithCtorParams : ApiController\n        {\n            public ControllerWithCtorParams(int unused) { }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Dispatcher/DefaultHttpControllerSelectorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Dispatcher\n{\n    public class DefaultHttpControllerSelectorTest\n    {\n        [Fact]\n        public void Constructor_Throws_NullConfiguration()\n        {\n            Assert.ThrowsArgumentNull(\n                () => new DefaultHttpControllerSelector(configuration: null),\n                \"configuration\");\n        }\n\n        [Theory]\n        [InlineData(\"controller\", \"abc\")]\n        [InlineData(\"Controller\", \"123\")]\n        [InlineData(\"ControLler\", \"123\")]\n        [InlineData(\"CONTROLLER\", \"ABC\")]\n        public void GetControllerName_PicksControllerNameFromRouteData(string controllerKeyName, string controllerName)\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            IHttpRouteData routeData = GetRouteData();\n            routeData.Values[controllerKeyName] = controllerName;\n            request.SetRouteData(routeData);\n            DefaultHttpControllerSelector selector = new DefaultHttpControllerSelector(new HttpConfiguration());\n\n            // Act\n            string selectedControllerName = selector.GetControllerName(request);\n\n            // Assert\n            Assert.Equal(controllerName, selectedControllerName);\n        }\n\n        [Fact]\n        public void GetControllerName_PicksNull_NoRouteData()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            DefaultHttpControllerSelector selector = new DefaultHttpControllerSelector(new HttpConfiguration());\n\n            // Act\n            string selectedControllerName = selector.GetControllerName(request);\n\n            // Assert\n            Assert.Null(selectedControllerName);\n        }\n\n        [Fact]\n        public void GetControllerName_PicksNull_EmptyRouteData()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.SetRouteData(GetRouteData());\n            DefaultHttpControllerSelector selector = new DefaultHttpControllerSelector(new HttpConfiguration());\n\n            // Act\n            string selectedControllerName = selector.GetControllerName(request);\n\n            // Assert\n            Assert.Null(selectedControllerName);\n        }\n\n        [Fact]\n        public void DefaultHttpControllerSelector_Uses_IAssemblyResolverAndIHttpControllerTypeResolver()\n        {\n            // Arrange\n            HttpConfiguration configuration = new HttpConfiguration();\n            Mock<IAssembliesResolver> assemblyResolver = new Mock<IAssembliesResolver>();\n            Mock<IHttpControllerTypeResolver> controllerTypeResolver = new Mock<IHttpControllerTypeResolver>();\n            configuration.Services.Replace(typeof(IAssembliesResolver), assemblyResolver.Object);\n            configuration.Services.Replace(typeof(IHttpControllerTypeResolver), controllerTypeResolver.Object);\n\n            controllerTypeResolver.Setup(c => c.GetControllerTypes(assemblyResolver.Object)).Returns(new Collection<Type> { GetMockControllerType(\"Sample\") }).Verifiable();\n            DefaultHttpControllerSelector selector = new DefaultHttpControllerSelector(configuration);\n\n            HttpRequestMessage request = new HttpRequestMessage();\n            IHttpRouteData routeData = GetRouteData();\n            routeData.Values[\"controller\"] = \"Sample\";\n            request.SetRouteData(routeData);\n\n            // Act\n            selector.SelectController(request);\n\n            // Assert\n            controllerTypeResolver.Verify();\n        }\n\n        [Theory]\n        [InlineData(\"Sample\")]\n        [InlineData(\"SAmple\")]\n        [InlineData(\"SAMPLE\")]\n        public void SelectController_IsCaseInsensitive(string controllerTypeName)\n        {\n            HttpConfiguration configuration = new HttpConfiguration();\n            Mock<IHttpControllerTypeResolver> controllerTypeResolver = new Mock<IHttpControllerTypeResolver>();\n            configuration.Services.Replace(typeof(IHttpControllerTypeResolver), controllerTypeResolver.Object);\n\n            Type controllerType = GetMockControllerType(\"Sample\");\n            controllerTypeResolver\n                .Setup(c => c.GetControllerTypes(It.IsAny<IAssembliesResolver>()))\n                .Returns(new Collection<Type> { controllerType });\n\n            HttpRequestMessage request = new HttpRequestMessage();\n            IHttpRouteData routeData = GetRouteData();\n            routeData.Values[\"controller\"] = controllerTypeName;\n            request.SetRouteData(routeData);\n\n            DefaultHttpControllerSelector selector = new DefaultHttpControllerSelector(configuration);\n\n            // Act\n            HttpControllerDescriptor descriptor = selector.SelectController(request);\n\n            // Assert\n            Assert.IsType<HttpControllerDescriptor>(descriptor);\n            Assert.Equal(controllerType, descriptor.ControllerType);\n        }\n\n        [Fact]\n        public void SelectController_DoesNotCreateNewInstances_ForSameController()\n        {\n            HttpConfiguration configuration = new HttpConfiguration();\n            Mock<IHttpControllerTypeResolver> controllerTypeResolver = new Mock<IHttpControllerTypeResolver>();\n            configuration.Services.Replace(typeof(IHttpControllerTypeResolver), controllerTypeResolver.Object);\n\n            Type controllerType = GetMockControllerType(\"Sample\");\n            controllerTypeResolver\n                .Setup(c => c.GetControllerTypes(It.IsAny<IAssembliesResolver>()))\n                .Returns(new Collection<Type> { controllerType });\n\n            HttpRequestMessage request = new HttpRequestMessage();\n            IHttpRouteData routeData = GetRouteData();\n            routeData.Values[\"controller\"] = \"Sample\";\n            request.SetRouteData(routeData);\n\n            DefaultHttpControllerSelector selector = new DefaultHttpControllerSelector(configuration);\n\n            // Act\n            HttpControllerDescriptor descriptor1 = selector.SelectController(request);\n            HttpControllerDescriptor descriptor2 = selector.SelectController(request);\n\n            // Assert\n            Assert.ReferenceEquals(descriptor1, descriptor2);\n        }\n\n        [Fact]\n        public void SelectController_DoesNotCreateNewInstances_ForSameController_DiferentCasedControllerName()\n        {\n            HttpConfiguration configuration = new HttpConfiguration();\n            Mock<IHttpControllerTypeResolver> controllerTypeResolver = new Mock<IHttpControllerTypeResolver>();\n            configuration.Services.Replace(typeof(IHttpControllerTypeResolver), controllerTypeResolver.Object);\n\n            Type controllerType = GetMockControllerType(\"Sample\");\n            controllerTypeResolver\n                .Setup(c => c.GetControllerTypes(It.IsAny<IAssembliesResolver>()))\n                .Returns(new Collection<Type> { controllerType });\n\n            HttpRequestMessage request1 = new HttpRequestMessage();\n            IHttpRouteData routeData1 = GetRouteData();\n            routeData1.Values[\"controller\"] = \"Sample\";\n            request1.SetRouteData(routeData1);\n\n            HttpRequestMessage request2 = new HttpRequestMessage();\n            IHttpRouteData routeData2 = GetRouteData();\n            routeData2.Values[\"controller\"] = \"SaMPle\";\n            request2.SetRouteData(routeData2);\n\n            DefaultHttpControllerSelector selector = new DefaultHttpControllerSelector(configuration);\n\n            // Act\n            HttpControllerDescriptor descriptor1 = selector.SelectController(request1);\n            HttpControllerDescriptor descriptor2 = selector.SelectController(request2);\n\n            // Assert\n            Assert.ReferenceEquals(descriptor1, descriptor2);\n        }\n\n        [Fact]\n        public void SelectController_Throws_NullRequest()\n        {\n            DefaultHttpControllerSelector selector = new DefaultHttpControllerSelector(new HttpConfiguration());\n\n            Assert.ThrowsArgumentNull(\n                () => selector.SelectController(request: null),\n                \"request\");\n        }\n\n        [Fact]\n        public void SelectController_Throws_NotFound_NoControllerInRouteData()\n        {\n            HttpConfiguration configuration = new HttpConfiguration();\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.SetRouteData(GetRouteData());\n\n            DefaultHttpControllerSelector selector = new DefaultHttpControllerSelector(configuration);\n\n            // Act\n            var ex = Assert.Throws<HttpResponseException>(\n                () => selector.SelectController(request));\n\n            // Assert\n            Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode);\n        }\n\n        [Fact]\n        public void SelectController_RespectsDirectRoutes()\n        {\n            HttpConfiguration configuration = new HttpConfiguration();\n            HttpRequestMessage request = new HttpRequestMessage();\n            var controllerDescriptor = new HttpControllerDescriptor();\n            var action1Descriptor = new ReflectedHttpActionDescriptor() { ControllerDescriptor = controllerDescriptor };\n            var action2Descriptor = new ReflectedHttpActionDescriptor() { ControllerDescriptor = controllerDescriptor };\n            IHttpRouteData routeData = GetRouteData();\n            routeData.Route.DataTokens.Add(\"actions\", new ReflectedHttpActionDescriptor[] { action1Descriptor, action2Descriptor });\n            request.SetRouteData(routeData);\n\n            DefaultHttpControllerSelector selector = new DefaultHttpControllerSelector(configuration);\n\n            // Act\n            var selectedController = selector.SelectController(request);\n\n            // Assert\n            Assert.Same(controllerDescriptor, selectedController);\n        }\n\n        [Fact]\n        public void SelectController_ThrowsOnDirectRoutesWithDifferentControllers()\n        {\n            var action1Descriptor = new ReflectedHttpActionDescriptor()\n            {\n                ControllerDescriptor = new HttpControllerDescriptor()\n                {\n                    ControllerType = GetMockControllerType(\"Controller1\"),\n                }\n            };\n\n            var action2Descriptor = new ReflectedHttpActionDescriptor()\n            {\n                ControllerDescriptor = new HttpControllerDescriptor()\n                {\n                    ControllerType = GetMockControllerType(\"Controller2\"),\n                }\n            };\n\n            IHttpRouteData routeData = GetRouteData();\n            routeData.Route.DataTokens.Add(\"actions\", new ReflectedHttpActionDescriptor[] { action1Descriptor, action2Descriptor });\n\n            HttpConfiguration configuration = new HttpConfiguration();\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.SetRouteData(routeData);\n\n            DefaultHttpControllerSelector selector = new DefaultHttpControllerSelector(configuration);\n\n            string expectedMessage =\n                \"Multiple controller types were found that match the URL. This can happen if attribute routes on multiple \" +\n                \"controllers match the requested URL.\" + Environment.NewLine +\n                Environment.NewLine +\n                \"The request has found the following matching controller types: \" + Environment.NewLine +\n                \"FullController1Controller\" + Environment.NewLine +\n                \"FullController2Controller\";\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(() => selector.SelectController(request), expectedMessage);\n        }\n\n        [Fact]\n        public void SelectController_Throws_NotFound_NoRouteData()\n        {\n            HttpConfiguration configuration = new HttpConfiguration();\n            HttpRequestMessage request = new HttpRequestMessage();\n\n            DefaultHttpControllerSelector selector = new DefaultHttpControllerSelector(configuration);\n\n            // Act\n            var ex = Assert.Throws<HttpResponseException>(\n                () => selector.SelectController(request));\n\n            // Assert\n            Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode);\n        }\n\n        // We ignore attribute routes when RouteData.Route is null\n        // See: https://aspnetwebstack.codeplex.com/workitem/1996\n        [Fact]\n        public void SelectController_WhenRouteData_RouteIsNull_FindsController()\n        {\n            // Arrange\n            HttpConfiguration configuration = new HttpConfiguration();\n            Mock<IHttpControllerTypeResolver> controllerTypeResolver = new Mock<IHttpControllerTypeResolver>();\n            configuration.Services.Replace(typeof(IHttpControllerTypeResolver), controllerTypeResolver.Object);\n\n            Type controllerType = GetMockControllerType(\"Sample\");\n            controllerTypeResolver\n                .Setup(c => c.GetControllerTypes(It.IsAny<IAssembliesResolver>()))\n                .Returns(new Collection<Type> { controllerType });\n\n            HttpRequestMessage request = new HttpRequestMessage();\n\n            var routeValues = new Dictionary<string, object>(StringComparer.Ordinal)\n            {\n                { \"controller\", \"Sample\" }\n            };\n\n            var routeData = new Mock<IHttpRouteData>();\n            routeData.SetupGet(rd => rd.Values).Returns(routeValues);\n            routeData.SetupGet(rd => rd.Route).Returns((IHttpRoute)null);\n            request.SetRouteData(routeData.Object);\n\n            DefaultHttpControllerSelector selector = new DefaultHttpControllerSelector(configuration);\n\n            // Act\n            var controller = selector.SelectController(request);\n\n            // Assert\n            Assert.Equal(controllerType, controller.ControllerType);\n        }\n\n        // We ignore attribute routes when RouteData.Route is null\n        // See: https://aspnetwebstack.codeplex.com/workitem/1996\n        [Fact]\n        public void SelectController_WhenRouteData_RouteIsNull_DoesNotFindController()\n        {\n            // Arrange\n            HttpConfiguration configuration = new HttpConfiguration();\n            Mock<IHttpControllerTypeResolver> controllerTypeResolver = new Mock<IHttpControllerTypeResolver>();\n            configuration.Services.Replace(typeof(IHttpControllerTypeResolver), controllerTypeResolver.Object);\n\n            controllerTypeResolver\n                .Setup(c => c.GetControllerTypes(It.IsAny<IAssembliesResolver>()))\n                .Returns(new Collection<Type> {}); // No controllers here\n\n            HttpRequestMessage request = new HttpRequestMessage();\n\n            var routeValues = new Dictionary<string, object>(StringComparer.Ordinal)\n            {\n                { \"controller\", \"Sample\" }\n            };\n\n            var routeData = new Mock<IHttpRouteData>();\n            routeData.SetupGet(rd => rd.Values).Returns(routeValues);\n            routeData.SetupGet(rd => rd.Route).Returns((IHttpRoute)null);\n            request.SetRouteData(routeData.Object);\n\n            DefaultHttpControllerSelector selector = new DefaultHttpControllerSelector(configuration);\n\n            // Act\n            var ex = Assert.Throws<HttpResponseException>(\n                () => selector.SelectController(request));\n\n            // Assert\n            Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode);\n        }\n\n        [Fact]\n        public async Task SelectController_Throws_NotFound_NoMatchingControllerType()\n        {\n            HttpConfiguration configuration = new HttpConfiguration();\n            Mock<IHttpControllerTypeResolver> controllerTypeResolver = new Mock<IHttpControllerTypeResolver>();\n            configuration.Services.Replace(typeof(IHttpControllerTypeResolver), controllerTypeResolver.Object);\n            configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;\n\n            controllerTypeResolver\n                .Setup(c => c.GetControllerTypes(It.IsAny<IAssembliesResolver>()))\n                .Returns(new Collection<Type>());\n\n            HttpRequestMessage request = new HttpRequestMessage();\n            IHttpRouteData routeData1 = GetRouteData();\n            routeData1.Values[\"controller\"] = \"Sample\";\n            request.SetRouteData(routeData1);\n            request.SetConfiguration(configuration);\n\n            DefaultHttpControllerSelector selector = new DefaultHttpControllerSelector(configuration);\n\n            // Act\n            var ex = Assert.Throws<HttpResponseException>(\n                () => selector.SelectController(request));\n\n            // Assert\n            Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode);\n            var result = await ex.Response.Content.ReadAsAsync<HttpError>();\n            string response = result[\"MessageDetail\"] as string;\n            Assert.Equal(\"No type was found that matches the controller named 'Sample'.\", response);\n        }\n\n        [Fact]\n        public void SelectController_Throws_DuplicateController()\n        {\n            HttpConfiguration configuration = new HttpConfiguration();\n            Mock<IHttpControllerTypeResolver> controllerTypeResolver = new Mock<IHttpControllerTypeResolver>();\n            configuration.Services.Replace(typeof(IHttpControllerTypeResolver), controllerTypeResolver.Object);\n            configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;\n\n            controllerTypeResolver\n                .Setup(c => c.GetControllerTypes(It.IsAny<IAssembliesResolver>()))\n                .Returns(new Collection<Type> { GetMockControllerType(\"Sample\"), GetMockControllerType(\"SampLe\"), GetMockControllerType(\"SAmpLE\") });\n\n            HttpRequestMessage request = new HttpRequestMessage();\n            IHttpRouteData routeData1 = GetRouteData();\n            routeData1.Values[\"controller\"] = \"Sample\";\n            request.SetRouteData(routeData1);\n            request.SetConfiguration(configuration);\n\n            DefaultHttpControllerSelector selector = new DefaultHttpControllerSelector(configuration);\n\n            // Act\n            var ex = Assert.Throws<InvalidOperationException>(\n                () => selector.SelectController(request));\n\n            // Assert\n            string message = ex.Message;\n            Assert.Contains(\n                \"Multiple types were found that match the controller named 'Sample'. This can happen if the route that services this request ('') found multiple controllers defined with the same name but differing namespaces, which is not supported.\\r\\n\\r\\nThe request for 'Sample' has found the following matching controllers:\",\n                message);\n\n            var duplicateControllers = message.Split(':')[1].Split('\\n').Select(str => str.Trim());\n            Assert.Contains(\"FullSampleController\", duplicateControllers);\n            Assert.Contains(\"FullSampLeController\", duplicateControllers);\n            Assert.Contains(\"FullSAmpLEController\", duplicateControllers);\n        }\n\n        private static IHttpRouteData GetRouteData()\n        {\n            HttpRoute route = new HttpRoute();\n            HttpRouteData routeData = new HttpRouteData(route);\n\n            return routeData;\n        }\n\n        private static Type GetMockControllerType(string controllerName)\n        {\n            Mock<Type> mockType = new Mock<Type>();\n\n            mockType.Setup(t => t.Name).Returns(controllerName + \"Controller\");\n            mockType.Setup(t => t.FullName).Returns(\"Full\" + controllerName + \"Controller\");\n            return mockType.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Dispatcher/DefaultHttpControllerTypeResolverTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Reflection;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Dispatcher\n{\n    public class DefaultHttpControllerTypeResolverTest\n    {\n        public static TheoryDataSet<Type> ValidControllerTypes\n        {\n            get\n            {\n                return new TheoryDataSet<Type>\n                {\n                    typeof(validcontroller),\n                    typeof(ValidController),\n                    typeof(VALIDController),\n                    typeof(VALIDCONTROLLER),\n                    typeof(ValidSealedController),\n                    typeof(ValidPartialController),\n                    typeof(ValidInheritedController),\n                    typeof(ControllerWrapper.ValidNestedController),\n                    typeof(ControllerWrapper.ValidInheritedNestedController),\n                    typeof(ControllerWrapper.ControllerNestedWrapper.ValidNestedNestedController),\n                    typeof(InheritedControllerHidingWrapper.ValidNestedController)\n                };\n            }\n        }\n\n        public static TheoryDataSet<Type> InvalidControllerTypesWithValidNames\n        {\n            get\n            {\n                return new TheoryDataSet<Type>\n                {\n                    typeof(InvalidAbstractController),\n                    typeof(ControllerWrapper.InvalidAbstractNestedController),\n                    ControllerWrapper.TypeOfInvalidProtectedNestedController(), // NOTE: Unable to get through typeof(ControllerWrapper.InvalidProtectedNestedController),\n                    ControllerWrapper.TypeOfInvalidPrivateNestedController(), // NOTE: Unable to get through typeof(ControllerWrapper.InvalidPrivateNestedController),\n                    typeof(ControllerWrapper.InvalidInternalNestedController)\n                };\n            }\n        }\n\n        public static TheoryDataSet<Type> InvalidControllerTypesWithInvalidNames\n        {\n            get\n            {\n                return new TheoryDataSet<Type>\n                {\n                    typeof(Ctrl),\n                    typeof(Controller),\n                    typeof(ControllerPrefix),\n                    typeof(InvalidControllerStruct),\n                    typeof(InvalidControllerWithInconsistentName),\n                    typeof(InvalidControllerWithNoBaseType)\n                };\n            }\n        }\n\n        [Fact]\n        public void DefaultHttpControllerTypeResolver_GuardClauses()\n        {\n            Assert.ThrowsArgumentNull(() => new DefaultHttpControllerTypeResolver(null), \"predicate\");\n        }\n\n        [Theory]\n        [PropertyData(\"ValidControllerTypes\")]\n        public void IsControllerType_AcceptsValidControllerTypes(Type validControllerType)\n        {\n            Assert.True(DefaultHttpControllerTypeResolver.IsControllerType(validControllerType));\n        }\n\n        [Theory]\n        [PropertyData(\"InvalidControllerTypesWithValidNames\"), PropertyData(\"InvalidControllerTypesWithInvalidNames\")]\n        public void IsControllerType_RejectsInvalidControllerTypes(Type invalidControllerType)\n        {\n            Assert.False(DefaultHttpControllerTypeResolver.IsControllerType(invalidControllerType));\n        }\n\n        [Theory]\n        [PropertyData(\"ValidControllerTypes\")]\n        public void HasValidControllerName_AcceptsValidControllerNames(Type validControllerType)\n        {\n            Assert.True(DefaultHttpControllerTypeResolver.HasValidControllerName(validControllerType));\n        }\n\n        [Theory]\n        [PropertyData(\"InvalidControllerTypesWithInvalidNames\")]\n        public void HasValidControllerName_RejectsInvalidControllerNames(Type invalidControllerType)\n        {\n            Assert.False(DefaultHttpControllerTypeResolver.HasValidControllerName(invalidControllerType));\n        }\n\n        [Fact]\n        public void GetControllerTypes_ThrowsOnNull()\n        {\n            DefaultHttpControllerTypeResolver resolver = new DefaultHttpControllerTypeResolver();\n            Assert.ThrowsArgumentNull(() => resolver.GetControllerTypes(null), \"assembliesResolver\");\n        }\n\n        [Fact]\n        public void GetControllerTypes_FindsTypes()\n        {\n            // Arrange\n            DefaultHttpControllerTypeResolver resolver = new DefaultHttpControllerTypeResolver();\n            Mock<IAssembliesResolver> mockAssemblyResolver = new Mock<IAssembliesResolver>();\n\n            mockAssemblyResolver.Setup(a => a.GetAssemblies()).Returns(new List<Assembly> \n            {\n                null,\n                new MockExportedTypesAssembly(ThrowException.ReflectionTypeLoadException,\n                    typeof(ControllerWrapper.ValidNestedController),\n                    typeof(ControllerWrapper.ValidInheritedNestedController),\n                    typeof(ControllerWrapper.ControllerNestedWrapper.ValidNestedNestedController),\n                    typeof(InheritedControllerHidingWrapper.ValidNestedController)),\n                new MockExportedTypesAssembly(ThrowException.Exception,\n                    typeof(ControllerWrapper.InvalidAbstractNestedController),\n                    ControllerWrapper.TypeOfInvalidProtectedNestedController(), // NOTE: Unable to get through typeof(ControllerWrapper.InvalidProtectedNestedController),\n                    ControllerWrapper.TypeOfInvalidPrivateNestedController(), // NOTE: Unable to get through typeof(ControllerWrapper.InvalidPrivateNestedController),\n                    typeof(ControllerWrapper.InvalidInternalNestedController)),\n                new MockExportedTypesAssembly(ThrowException.None,\n                    typeof(ValidSealedController),\n                    typeof(ValidPartialController),\n                    typeof(ValidInheritedController),\n                    typeof(ValidController),\n                    typeof(VALIDController),\n                    typeof(VALIDCONTROLLER),\n                    typeof(InvalidAbstractController),\n                    typeof(InvalidControllerStruct),\n                    typeof(InvalidControllerWithInconsistentName),\n                    typeof(InvalidControllerWithNoBaseType))\n            });\n\n            // Act\n            ICollection<Type> actualControllerTypes = resolver.GetControllerTypes(mockAssemblyResolver.Object);\n\n            // Assert\n            Assert.Equal(10, actualControllerTypes.Count);\n            Assert.True(actualControllerTypes.Contains(typeof(ControllerWrapper.ValidNestedController)));\n            Assert.True(actualControllerTypes.Contains(typeof(ControllerWrapper.ValidInheritedNestedController)));\n            Assert.True(actualControllerTypes.Contains(typeof(ControllerWrapper.ControllerNestedWrapper.ValidNestedNestedController)));\n            Assert.True(actualControllerTypes.Contains(typeof(ValidSealedController)));\n            Assert.True(actualControllerTypes.Contains(typeof(ValidPartialController)));\n            Assert.True(actualControllerTypes.Contains(typeof(ValidInheritedController)));\n            Assert.True(actualControllerTypes.Contains(typeof(ValidController)));\n            Assert.True(actualControllerTypes.Contains(typeof(VALIDController)));\n            Assert.True(actualControllerTypes.Contains(typeof(VALIDCONTROLLER)));\n            Assert.True(actualControllerTypes.Contains(typeof(InheritedControllerHidingWrapper.ValidNestedController)));\n        }\n\n        private static string GetDefaultControllerRouteName(Type controllerType)\n        {\n            return controllerType.Name.Substring(0, controllerType.Name.Length - \"Controller\".Length);\n        }\n    }\n\n    public enum ThrowException\n    {\n        None = 0,\n        Exception,\n        ReflectionTypeLoadException,\n    }\n\n    public class MockExportedTypesAssembly : Assembly\n    {\n        private ThrowException _throwException;\n        private Type[] _exportedTypes;\n\n        public MockExportedTypesAssembly(ThrowException throwException, params Type[] exportedTypes)\n        {\n            _throwException = throwException;\n            _exportedTypes = exportedTypes;\n        }\n\n        public override bool IsDynamic\n        {\n            get { return false; }\n        }\n\n        public override Type[] GetTypes()\n        {\n            switch (_throwException)\n            {\n                case ThrowException.Exception:\n                    throw new Exception(\"GetTypes exception\");\n\n                case ThrowException.ReflectionTypeLoadException:\n                    throw new ReflectionTypeLoadException(_exportedTypes, null, \"GetTypes exception\");\n            }\n\n            return _exportedTypes;\n        }\n    }\n\n    public class ControllerWrapper\n    {\n        public static Type TypeOfInvalidPrivateNestedController()\n        {\n            return typeof(InvalidPrivateNestedController);\n        }\n\n        public static Type TypeOfInvalidProtectedNestedController()\n        {\n            return typeof(InvalidProtectedNestedController);\n        }\n\n        public class ValidNestedController : ApiController\n        {\n        }\n\n        public abstract class InvalidAbstractNestedController : ApiController\n        {\n        }\n\n        public class ValidInheritedNestedController : InvalidAbstractNestedController\n        {\n        }\n\n        protected class InvalidProtectedNestedController : ApiController\n        {\n        }\n\n        private class InvalidPrivateNestedController : ApiController\n        {\n        }\n\n        internal class InvalidInternalNestedController : ApiController\n        {\n        }\n\n        public class ControllerNestedWrapper\n        {\n            public class ValidNestedNestedController : ApiController\n            {\n            }\n        }\n    }\n\n    public abstract class InvalidAbstractController : ApiController\n    {\n    }\n\n    public struct InvalidControllerStruct\n    {\n    }\n\n    public class ControllerPrefix\n    {\n    }\n\n    public class InvalidControllerWithInconsistentName : ApiController\n    {\n    }\n\n    public class InvalidControllerWithNoBaseType\n    {\n    }\n\n    public sealed class ValidSealedController : ApiController\n    {\n    }\n\n    public partial class ValidPartialController : ApiController\n    {\n    }\n\n    public partial class ValidPartialController\n    {\n    }\n\n    public class ValidInheritedController : InvalidAbstractController\n    {\n    }\n\n    public class Controller : ApiController\n    {\n    }\n\n    public class Ctrl : ApiController\n    {\n    }\n\n    public class validcontroller : ApiController\n    {\n    }\n\n    public class ValidController : ApiController\n    {\n    }\n\n    public class VALIDController : ApiController\n    {\n    }\n\n    public class VALIDCONTROLLER : ApiController\n    {\n    }\n\n    public class InheritedControllerHidingWrapper : ControllerWrapper\n    {\n        public new class ValidNestedController : ControllerWrapper.ValidNestedController\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Dispatcher/HttpControllerDispatcherTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Net;\nusing System.Net.Http;\nusing System.Runtime.ExceptionServices;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Results;\nusing System.Web.Http.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Dispatcher\n{\n    public class HttpControllerDispatcherTest\n    {\n        [Fact]\n        public void Constructor_GuardClauses()\n        {\n            Assert.ThrowsArgumentNull(\n                () => new HttpControllerDispatcher(configuration: null),\n                \"configuration\");\n        }\n\n        [Fact]\n        public void ExceptionLoggerGet_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            IExceptionLogger expectedExceptionLogger = CreateDummyExceptionLogger();\n            IExceptionHandler exceptionHandler = CreateDummyExceptionHandler();\n\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpControllerDispatcher product = CreateProductUnderTest(configuration, expectedExceptionLogger,\n                exceptionHandler))\n            {\n                // Act\n                IExceptionLogger exceptionLogger = product.ExceptionLogger;\n\n                // Assert\n                Assert.Same(expectedExceptionLogger, exceptionLogger);\n            }\n        }\n\n        [Fact]\n        public void ExceptionHandlerGet_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            IExceptionLogger exceptionLogger = CreateDummyExceptionLogger();\n            IExceptionHandler expectedExceptionHandler = CreateDummyExceptionHandler();\n\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpControllerDispatcher product = CreateProductUnderTest(configuration, exceptionLogger,\n                expectedExceptionHandler))\n            {\n                // Act\n                IExceptionHandler exceptionHandler = product.ExceptionHandler;\n\n                // Assert\n                Assert.Same(expectedExceptionHandler, exceptionHandler);\n            }\n        }\n\n        [Fact]\n        public void ExceptionLoggerGet_IfUnset_ReturnsExceptionLoggerFromConfiguration()\n        {\n            // Arrange\n            using (HttpConfiguration configuration = CreateConfiguration())\n            {\n                IExceptionLogger expectedExceptionLogger = CreateDummyExceptionLogger();\n                configuration.Services.Add(typeof(IExceptionLogger), expectedExceptionLogger);\n\n                using (HttpControllerDispatcher product = CreateProductUnderTest(configuration))\n                {\n                    // Act\n                    IExceptionLogger exceptionLogger = product.ExceptionLogger;\n\n                    // Assert\n                    CompositeExceptionLogger compositeLogger = Assert.IsType<CompositeExceptionLogger>(exceptionLogger);\n                    IEnumerable<IExceptionLogger> loggers = compositeLogger.Loggers;\n                    Assert.NotNull(loggers);\n                    IExceptionLogger logger = Assert.Single(loggers);\n                    Assert.Same(expectedExceptionLogger, logger);\n                }\n            }\n        }\n\n        [Fact]\n        public void ExceptionHandlerGet_IfUnset_UsesExceptionHandlerFromConfiguration()\n        {\n            // Arrange\n            using (HttpConfiguration configuration = CreateConfiguration())\n            {\n                IExceptionHandler expectedExceptionHandler = CreateDummyExceptionHandler();\n                configuration.Services.Replace(typeof(IExceptionHandler), expectedExceptionHandler);\n\n                using (HttpControllerDispatcher product = CreateProductUnderTest(configuration))\n                {\n                    // Act\n                    IExceptionHandler exceptionHandler = product.ExceptionHandler;\n\n                    // Assert\n                    LastChanceExceptionHandler lastChanceHandler = Assert.IsType<LastChanceExceptionHandler>(exceptionHandler);\n                    Assert.Same(expectedExceptionHandler, lastChanceHandler.InnerHandler);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task SendAsync_CallsControllerSelectorToGetControllerDescriptor()\n        {\n            var mockSelector = new Mock<IHttpControllerSelector>();\n            var config = new HttpConfiguration();\n            config.Services.Replace(typeof(IHttpControllerSelector), mockSelector.Object);\n            var request = CreateRequest(config, \"http://localhost/api/foo\");\n            var dispatcher = new HttpControllerDispatcher(config);\n            var invoker = new HttpMessageInvoker(dispatcher);\n\n            await invoker.SendAsync(request, CancellationToken.None);\n\n            mockSelector.Verify(s => s.SelectController(request), Times.Once());\n        }\n\n        [Fact]\n        public async Task SendAsync_CallsControllerDescriptorToCreateController()\n        {\n            var mockSelector = new Mock<IHttpControllerSelector>();\n            var mockDescriptor = new Mock<HttpControllerDescriptor>();\n            var config = new HttpConfiguration();\n            config.Services.Replace(typeof(IHttpControllerSelector), mockSelector.Object);\n            var request = CreateRequest(config, \"http://localhost/api/foo\");\n            mockSelector.Setup(s => s.SelectController(request))\n                        .Returns(mockDescriptor.Object);\n            mockDescriptor.Setup(d => d.CreateController(request))\n                          .Returns(new PrivateController())\n                          .Verifiable();\n            var dispatcher = new HttpControllerDispatcher(config);\n            var invoker = new HttpMessageInvoker(dispatcher);\n\n            await invoker.SendAsync(request, CancellationToken.None);\n\n            mockDescriptor.Verify();\n        }\n\n        [Fact]\n        public async Task SendAsync_CallsControllerExecuteAsyncWithPopulatedControllerContext()\n        {\n            HttpControllerContext calledContext = null;\n            var mockSelector = new Mock<IHttpControllerSelector>();\n            var mockDescriptor = new Mock<HttpControllerDescriptor>();\n            var mockController = new Mock<IHttpController>();\n            var config = new HttpConfiguration();\n            config.Services.Replace(typeof(IHttpControllerSelector), mockSelector.Object);\n            var request = CreateRequest(config, \"http://localhost/api/foo\");\n            mockSelector.Setup(s => s.SelectController(request))\n                        .Returns(mockDescriptor.Object);\n            mockDescriptor.Setup(d => d.CreateController(request))\n                          .Returns(mockController.Object);\n            mockDescriptor.Object.Initialize(config);\n            mockController.Setup(c => c.ExecuteAsync(It.IsAny<HttpControllerContext>(), CancellationToken.None))\n                          .Callback((HttpControllerContext ctxt, CancellationToken token) => { calledContext = ctxt; });\n            var dispatcher = new HttpControllerDispatcher(config);\n            var invoker = new HttpMessageInvoker(dispatcher);\n\n            await invoker.SendAsync(request, CancellationToken.None);\n\n            Assert.NotNull(calledContext);\n            Assert.Same(mockController.Object, calledContext.Controller);\n            Assert.Same(mockDescriptor.Object, calledContext.ControllerDescriptor);\n            Assert.Same(config, calledContext.Configuration);\n            Assert.Same(request, calledContext.Request);\n            Assert.Same(request.GetRouteData(), calledContext.RouteData);\n        }\n\n        [Fact]\n        public async Task SendAsync_Returns404WhenControllerSelectorReturnsNullControllerDescriptor()\n        {\n            var config = new HttpConfiguration();\n            var request = CreateRequest(config, \"http://localhost/api/foo\");\n            var dispatcher = new HttpControllerDispatcher(config);\n            var invoker = new HttpMessageInvoker(dispatcher);\n\n            HttpResponseMessage response = await invoker.SendAsync(request, CancellationToken.None);\n\n            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);\n        }\n\n        // In this case the controller selector throws, so we don't get a controller context in the\n        // exception handlers.\n        [Fact]\n        public async Task SendAsync_IfSendAsyncThrows_InControllerSelector_CallsExceptionServices()\n        {\n            // Arrange\n            Exception expectedException = CreateException();\n\n            Mock<IExceptionLogger> exceptionLoggerMock = CreateStubExceptionLoggerMock();\n            IExceptionLogger exceptionLogger = exceptionLoggerMock.Object;\n\n            Mock<IExceptionHandler> exceptionHandlerMock = CreateStubExceptionHandlerMock();\n            IExceptionHandler exceptionHandler = exceptionHandlerMock.Object;\n\n            using (HttpRequestMessage expectedRequest = CreateRequestWithRouteData())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpMessageHandler product = CreateProductUnderTest(configuration, exceptionLogger,\n                exceptionHandler))\n            {\n                configuration.Services.Replace(typeof(IHttpControllerSelector),\n                    CreateThrowingControllerSelector(expectedException));\n\n                CancellationToken cancellationToken = CreateCancellationToken();\n\n                // Act\n                await Assert.ThrowsAsync<Exception>(() => product.SendAsync(expectedRequest, cancellationToken));\n\n                // Assert\n                Func<ExceptionContext, bool> exceptionContextMatches = (c) =>\n                    c != null\n                    && c.Exception == expectedException\n                    && c.CatchBlock == ExceptionCatchBlocks.HttpControllerDispatcher\n                    && c.Request == expectedRequest\n                    && c.ControllerContext == null;\n\n                exceptionLoggerMock.Verify(l => l.LogAsync(\n                    It.Is<ExceptionLoggerContext>(c => exceptionContextMatches(c.ExceptionContext)),\n                    cancellationToken), Times.Once());\n\n                exceptionHandlerMock.Verify(h => h.HandleAsync(\n                    It.Is<ExceptionHandlerContext>((c) => exceptionContextMatches(c.ExceptionContext)),\n                    cancellationToken), Times.Once());\n            }\n        }\n\n        // In this case the controller itself throws, so we get a controller context in the\n        // exception handlers.\n        [Fact]\n        public async Task SendAsync_IfSendAsyncThrows_Controller_CallsExceptionServices()\n        {\n            // Arrange\n            Exception expectedException = CreateException();\n\n            Mock<IExceptionLogger> exceptionLoggerMock = CreateStubExceptionLoggerMock();\n            IExceptionLogger exceptionLogger = exceptionLoggerMock.Object;\n\n            Mock<IExceptionHandler> exceptionHandlerMock = CreateStubExceptionHandlerMock();\n            IExceptionHandler exceptionHandler = exceptionHandlerMock.Object;\n\n            var controller = new ThrowingController(expectedException);\n\n            var controllerActivator = new Mock<IHttpControllerActivator>();\n            controllerActivator\n                .Setup(\n                    activator => activator.Create(\n                        It.IsAny<HttpRequestMessage>(),\n                        It.IsAny<HttpControllerDescriptor>(),\n                        It.IsAny<Type>()))\n                .Returns(controller);\n\n            using (HttpRequestMessage expectedRequest = CreateRequestWithRouteData())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpMessageHandler product = CreateProductUnderTest(configuration, exceptionLogger,\n                exceptionHandler))\n            {\n                var controllerSelector = new Mock<IHttpControllerSelector>(MockBehavior.Strict);\n                controllerSelector\n                    .Setup(selector => selector.SelectController(It.IsAny<HttpRequestMessage>()))\n                    .Returns(new HttpControllerDescriptor(configuration, \"Throwing\", controller.GetType()));\n\n                configuration.Services.Replace(typeof(IHttpControllerSelector), controllerSelector.Object);\n                configuration.Services.Replace(typeof(IHttpControllerActivator), controllerActivator.Object);\n\n                CancellationToken cancellationToken = CreateCancellationToken();\n\n                // Act\n                await Assert.ThrowsAsync<Exception>(() => product.SendAsync(expectedRequest, cancellationToken));\n\n                // Assert\n                Func<ExceptionContext, bool> exceptionContextMatches = (c) =>\n                    c != null\n                    && c.Exception == expectedException\n                    && c.CatchBlock == ExceptionCatchBlocks.HttpControllerDispatcher\n                    && c.Request == expectedRequest\n                    && c.ControllerContext != null\n                    && c.ControllerContext == controller.ControllerContext\n                    && c.ControllerContext.Controller == controller;\n\n                exceptionLoggerMock.Verify(l => l.LogAsync(\n                    It.Is<ExceptionLoggerContext>(c => exceptionContextMatches(c.ExceptionContext)),\n                    cancellationToken), Times.Once());\n\n                exceptionHandlerMock.Verify(h => h.HandleAsync(\n                    It.Is<ExceptionHandlerContext>((c) => exceptionContextMatches(c.ExceptionContext)),\n                    cancellationToken), Times.Once());\n            }\n        }\n\n\n        [Fact]\n        public async Task SendAsync_IfSendAsyncCancels_InControllerSelector_DoesNotCallExceptionServices()\n        {\n            // Arrange\n            Exception expectedException = new OperationCanceledException();\n\n            Mock<IExceptionLogger> exceptionLoggerMock = new Mock<IExceptionLogger>(MockBehavior.Strict);\n            IExceptionLogger exceptionLogger = exceptionLoggerMock.Object;\n\n            Mock<IExceptionHandler> exceptionHandlerMock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n            IExceptionHandler exceptionHandler = exceptionHandlerMock.Object;\n\n            using (HttpRequestMessage expectedRequest = CreateRequestWithRouteData())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpMessageHandler product = CreateProductUnderTest(configuration, exceptionLogger,\n                exceptionHandler))\n            {\n                configuration.Services.Replace(typeof(IHttpControllerSelector),\n                    CreateThrowingControllerSelector(expectedException));\n\n                CancellationToken cancellationToken = CreateCancellationToken();\n\n                // Act & Assert\n                await Assert.ThrowsAsync<OperationCanceledException>(() => product.SendAsync(expectedRequest, cancellationToken));\n            }\n        }\n\n        [Fact]\n        public async Task SendAsync_IfExceptionHandlerSetsNullResult_PropogatesFaultedTaskException()\n        {\n            // Arrange\n            ExceptionDispatchInfo exceptionInfo = CreateExceptionInfo();\n            string expectedStackTrace = exceptionInfo.SourceException.StackTrace;\n\n            IExceptionLogger exceptionLogger = CreateStubExceptionLogger();\n\n            Mock<IExceptionHandler> exceptionHandlerMock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n            exceptionHandlerMock\n                .Setup(h => h.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                .Callback<ExceptionHandlerContext, CancellationToken>((c, i) => c.Result = null)\n                .Returns(Task.FromResult(0));\n            IExceptionHandler exceptionHandler = exceptionHandlerMock.Object;\n\n            using (HttpRequestMessage request = CreateRequestWithRouteData())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpMessageHandler product = CreateProductUnderTest(configuration, exceptionLogger,\n                exceptionHandler))\n            {\n                configuration.Services.Replace(typeof(IHttpControllerSelector),\n                    CreateThrowingControllerSelector(exceptionInfo));\n\n                CancellationToken cancellationToken = CreateCancellationToken();\n\n                // Act & Assert\n                var exception = await Assert.ThrowsAsync<Exception>(() => product.SendAsync(request, cancellationToken));\n\n                Assert.Same(exceptionInfo.SourceException, exception);\n                Assert.NotNull(exception.StackTrace);\n                Assert.StartsWith(expectedStackTrace, exception.StackTrace);\n            }\n        }\n\n        [Fact]\n        public async Task SendAsync_IfExceptionHandlerHandlesException_ReturnsResponse()\n        {\n            // Arrange\n            IExceptionLogger exceptionLogger = CreateStubExceptionLogger();\n\n            using (HttpResponseMessage expectedResponse = CreateResponse())\n            {\n                Mock<IExceptionHandler> exceptionHandlerMock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n                exceptionHandlerMock\n                    .Setup(h => h.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                    .Callback<ExceptionHandlerContext, CancellationToken>((c, i) =>\n                        c.Result = new ResponseMessageResult(expectedResponse))\n                    .Returns(Task.FromResult(0));\n                IExceptionHandler exceptionHandler = exceptionHandlerMock.Object;\n\n                using (HttpRequestMessage request = CreateRequestWithRouteData())\n                using (HttpConfiguration configuration = new HttpConfiguration())\n                using (HttpMessageHandler product = CreateProductUnderTest(configuration, exceptionLogger,\n                    exceptionHandler))\n                {\n                    configuration.Services.Replace(typeof(IHttpControllerSelector),\n                        CreateThrowingControllerSelector(CreateException()));\n\n                    CancellationToken cancellationToken = CreateCancellationToken();\n\n                    // Act\n                    HttpResponseMessage response = await product.SendAsync(request, cancellationToken);\n\n                    // Assert\n                    Assert.Same(expectedResponse, response);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task SendAsync_IfExceptionHandlerIsDefault_Returns500WithHttpErrorWhenControllerThrows()\n        {\n            var config = new HttpConfiguration() { IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always };\n            var request = CreateRequest(config, \"http://localhost/api/HttpControllerDispatcherThrowing\");\n            var dispatcher = new HttpControllerDispatcher(config);\n            var invoker = new HttpMessageInvoker(dispatcher);\n\n            HttpResponseMessage response = await invoker.SendAsync(request, CancellationToken.None);\n\n            Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n            var objectContent = Assert.IsType<ObjectContent<HttpError>>(response.Content);\n            var error = Assert.IsType<HttpError>(objectContent.Value);\n            Assert.Equal(\"Hello from the throwing controller\", error[\"ExceptionMessage\"]);\n        }\n\n        [Fact]\n        public async Task SendAsync_CreatesControllerContext_WithRequestContextFromRequest()\n        {\n            // Arrange\n            using (HttpConfiguration configuration = new HttpConfiguration())\n            using (HttpControllerDispatcher dispatcher = new HttpControllerDispatcher(configuration))\n            using (HttpMessageInvoker invoker = new HttpMessageInvoker(dispatcher))\n            using (HttpRequestMessage request = new HttpRequestMessage())\n            {\n                Mock<IHttpController> controllerMock = new Mock<IHttpController>();\n                HttpRequestContext requestContext = null;\n                controllerMock\n                    .Setup(c => c.ExecuteAsync(It.IsAny<HttpControllerContext>(), CancellationToken.None))\n                    .Callback<HttpControllerContext, CancellationToken>((c, t) =>\n                    {\n                        requestContext = c.RequestContext;\n                    });\n                Mock<HttpControllerDescriptor> controllerDescriptorMock = new Mock<HttpControllerDescriptor>();\n                controllerDescriptorMock.Setup(d => d.CreateController(request)).Returns(controllerMock.Object);\n                HttpControllerDescriptor controllerDescriptor = controllerDescriptorMock.Object;\n                controllerDescriptor.Configuration = configuration;\n                Mock<IHttpControllerSelector> controllerSelectorMock = new Mock<IHttpControllerSelector>();\n                controllerSelectorMock.Setup(s => s.SelectController(request)).Returns(controllerDescriptor);\n                configuration.Services.Replace(typeof(IHttpControllerSelector), controllerSelectorMock.Object);\n\n                HttpRequestContext expectedRequestContext = new HttpRequestContext\n                {\n                    Configuration = configuration\n                };\n                request.SetRequestContext(expectedRequestContext);\n\n                request.SetRouteData(new Mock<IHttpRouteData>(MockBehavior.Strict).Object);\n\n                // Act\n                HttpResponseMessage ignore = await invoker.SendAsync(request, CancellationToken.None);\n\n                // Assert\n                Assert.Same(expectedRequestContext, requestContext);\n            }\n        }\n\n        [Fact]\n        public async Task SendAsync_CreatesControllerContextWithRequestBackedRequestContext_WhenRequestRequestContextIsNull()\n        {\n            // Arrange\n            using (HttpConfiguration configuration = new HttpConfiguration())\n            using (HttpControllerDispatcher dispatcher = new HttpControllerDispatcher(configuration))\n            using (HttpMessageInvoker invoker = new HttpMessageInvoker(dispatcher))\n            using (HttpRequestMessage request = new HttpRequestMessage())\n            {\n                Mock<IHttpController> controllerMock = new Mock<IHttpController>();\n                HttpRequestContext requestContext = null;\n                controllerMock\n                    .Setup(c => c.ExecuteAsync(It.IsAny<HttpControllerContext>(), CancellationToken.None))\n                    .Callback<HttpControllerContext, CancellationToken>((c, t) =>\n                    {\n                        requestContext = c.RequestContext;\n                    });\n                Mock<HttpControllerDescriptor> controllerDescriptorMock = new Mock<HttpControllerDescriptor>();\n                controllerDescriptorMock.Setup(d => d.CreateController(request)).Returns(controllerMock.Object);\n                HttpControllerDescriptor controllerDescriptor = controllerDescriptorMock.Object;\n                controllerDescriptor.Configuration = configuration;\n                Mock<IHttpControllerSelector> controllerSelectorMock = new Mock<IHttpControllerSelector>();\n                controllerSelectorMock.Setup(s => s.SelectController(request)).Returns(controllerDescriptor);\n                configuration.Services.Replace(typeof(IHttpControllerSelector), controllerSelectorMock.Object);\n\n                request.SetRouteData(new Mock<IHttpRouteData>(MockBehavior.Strict).Object);\n\n                // Act\n                HttpResponseMessage ignore = await invoker.SendAsync(request, CancellationToken.None);\n\n                // Assert\n                RequestBackedHttpRequestContext typedRequestContext = Assert.IsType<RequestBackedHttpRequestContext>(requestContext);\n                Assert.Same(request, typedRequestContext.Request);\n                Assert.Same(configuration, typedRequestContext.Configuration);\n            }\n        }\n\n        [Fact]\n        public async Task SendAsync_SetsRequestBackedRequestContextOnRequest_WhenRequestRequestContextIsNull()\n        {\n            // Arrange\n            using (HttpConfiguration configuration = new HttpConfiguration())\n            using (HttpControllerDispatcher dispatcher = new HttpControllerDispatcher(configuration))\n            using (HttpMessageInvoker invoker = new HttpMessageInvoker(dispatcher))\n            using (HttpRequestMessage request = new HttpRequestMessage())\n            {\n                Mock<IHttpController> controllerMock = new Mock<IHttpController>();\n                HttpRequestContext requestContext = null;\n                controllerMock\n                    .Setup(c => c.ExecuteAsync(It.IsAny<HttpControllerContext>(), CancellationToken.None))\n                    .Callback<HttpControllerContext, CancellationToken>((c, t) =>\n                    {\n                        requestContext = request.GetRequestContext();\n                    });\n                Mock<HttpControllerDescriptor> controllerDescriptorMock = new Mock<HttpControllerDescriptor>();\n                controllerDescriptorMock.Setup(d => d.CreateController(request)).Returns(controllerMock.Object);\n                HttpControllerDescriptor controllerDescriptor = controllerDescriptorMock.Object;\n                controllerDescriptor.Configuration = configuration;\n                Mock<IHttpControllerSelector> controllerSelectorMock = new Mock<IHttpControllerSelector>();\n                controllerSelectorMock.Setup(s => s.SelectController(request)).Returns(controllerDescriptor);\n                configuration.Services.Replace(typeof(IHttpControllerSelector), controllerSelectorMock.Object);\n\n                request.SetRouteData(new Mock<IHttpRouteData>(MockBehavior.Strict).Object);\n\n                // Act\n                HttpResponseMessage ignore = await invoker.SendAsync(request, CancellationToken.None);\n\n                // Assert\n                RequestBackedHttpRequestContext typedRequestContext = Assert.IsType<RequestBackedHttpRequestContext>(requestContext);\n                Assert.Same(request, typedRequestContext.Request);\n                Assert.Same(configuration, typedRequestContext.Configuration);\n            }\n        }\n\n        private static CancellationToken CreateCancellationToken()\n        {\n            CancellationTokenSource source = new CancellationTokenSource();\n            return source.Token;\n        }\n\n        private static HttpConfiguration CreateConfiguration()\n        {\n            return new HttpConfiguration();\n        }\n\n        private static IExceptionHandler CreateDummyExceptionHandler()\n        {\n            return new Mock<IExceptionHandler>(MockBehavior.Strict).Object;\n        }\n\n        private static IExceptionLogger CreateDummyExceptionLogger()\n        {\n            return new Mock<IExceptionLogger>(MockBehavior.Strict).Object;\n        }\n\n        private static Exception CreateException()\n        {\n            return new Exception();\n        }\n\n        private static ExceptionDispatchInfo CreateExceptionInfo()\n        {\n            try\n            {\n                throw CreateException();\n            }\n            catch (Exception exception)\n            {\n                return ExceptionDispatchInfo.Capture(exception);\n            }\n        }\n\n        private static HttpControllerDispatcher CreateProductUnderTest(HttpConfiguration configuration)\n        {\n            return new HttpControllerDispatcher(configuration);\n        }\n\n        private static HttpControllerDispatcher CreateProductUnderTest(HttpConfiguration configuration,\n            IExceptionLogger exceptionLogger, IExceptionHandler exceptionHandler)\n        {\n            return new HttpControllerDispatcher(configuration)\n            {\n                ExceptionLogger = exceptionLogger,\n                ExceptionHandler = exceptionHandler\n            };\n        }\n\n        private static HttpRequestMessage CreateRequestWithRouteData()\n        {\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.SetRouteData(new Mock<IHttpRouteData>(MockBehavior.Strict).Object);\n            return request;\n        }\n\n        private static HttpRequestMessage CreateRequest(HttpConfiguration config, string requestUri)\n        {\n            IHttpRoute route = config.Routes.MapHttpRoute(\"default\", \"api/{controller}/{id}\", new { id = RouteParameter.Optional });\n            var request = new HttpRequestMessage(HttpMethod.Get, requestUri);\n            request.SetRouteData(route.GetRouteData(\"/\", request));\n            request.SetConfiguration(config);\n            return request;\n        }\n\n        private static HttpResponseMessage CreateResponse()\n        {\n            return new HttpResponseMessage();\n        }\n\n        private static Mock<IExceptionHandler> CreateStubExceptionHandlerMock()\n        {\n            Mock<IExceptionHandler> mock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n            mock\n                .Setup(h => h.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                .Returns(Task.FromResult(0));\n            return mock;\n        }\n\n        private static IExceptionLogger CreateStubExceptionLogger()\n        {\n            return CreateStubExceptionLoggerMock().Object;\n        }\n\n        private static Mock<IExceptionLogger> CreateStubExceptionLoggerMock()\n        {\n            Mock<IExceptionLogger> mock = new Mock<IExceptionLogger>(MockBehavior.Strict);\n            mock\n                .Setup(l => l.LogAsync(It.IsAny<ExceptionLoggerContext>(), It.IsAny<CancellationToken>()))\n                .Returns(Task.FromResult(0));\n            return mock;\n        }\n\n        private static IHttpControllerSelector CreateThrowingControllerSelector(Exception exception)\n        {\n            Mock<IHttpControllerSelector> mock = new Mock<IHttpControllerSelector>(MockBehavior.Strict);\n            mock\n                .Setup(s => s.SelectController(It.IsAny<HttpRequestMessage>()))\n                .Throws(exception);\n            return mock.Object;\n        }\n\n        private static IHttpControllerSelector CreateThrowingControllerSelector(ExceptionDispatchInfo exceptionInfo)\n        {\n            return new ThrowingControllerSelector(exceptionInfo);\n        }\n\n        private class PrivateController : ApiController\n        {\n            public void Get() { }\n\n            public override Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)\n            {\n                // Empty. Skip all the logic of execcuting a controller.\n                HttpResponseMessage response = new HttpResponseMessage();\n                return Task.FromResult(response);\n            }\n        }\n\n        private class ThrowingControllerSelector : IHttpControllerSelector\n        {\n            private readonly ExceptionDispatchInfo _exceptionInfo;\n\n            public ThrowingControllerSelector(ExceptionDispatchInfo exceptionInfo)\n            {\n                Contract.Assert(exceptionInfo != null);\n                _exceptionInfo = exceptionInfo;\n            }\n\n            public HttpControllerDescriptor SelectController(HttpRequestMessage request)\n            {\n                _exceptionInfo.Throw();\n                return null; // We'll never get here, but the compiler doesn't know that.\n            }\n\n            public IDictionary<string, HttpControllerDescriptor> GetControllerMapping()\n            {\n                _exceptionInfo.Throw();\n                return null; // We'll never get here, but the compiler doesn't know that.\n            }\n        }\n    }\n\n    public class ThrowingController : ApiController\n    {\n        private readonly Exception _exception;\n\n        public ThrowingController(Exception exception)\n        {\n            _exception = exception;\n        }\n\n        public override Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)\n        {\n            ControllerContext = controllerContext;\n            throw _exception;\n        }\n    }\n\n    // This is used in SendAsync_IfExceptionHandlerIsDefault_Returns500WithHttpErrorWhenControllerThrows\n    // Don't touch!\n    public class HttpControllerDispatcherThrowingController : ApiController\n    {\n        public void Get()\n        {\n            throw new Exception(\"Hello from the throwing controller\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Dispatcher/HttpErrorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Net.Http.Formatting;\nusing System.Threading.Tasks;\nusing System.Web.Http.ModelBinding;\nusing Microsoft.TestCommon;\nusing Newtonsoft.Json.Linq;\n\nnamespace System.Web.Http.Dispatcher\n{\n    public class HttpErrorTest\n    {\n        public static TheoryDataSet<HttpError, Func<string>, string, string> ErrorKeyValue\n        {\n            get\n            {\n                HttpError httpError = new HttpError();\n                return new TheoryDataSet<HttpError, Func<string>, string, string>\n                {\n                    { httpError, () => httpError.Message, \"Message\", \"Message_Value\" },\n                    { httpError, () => httpError.MessageDetail, \"MessageDetail\", \"MessageDetail_Value\" },\n                    { httpError, () => httpError.ExceptionMessage, \"ExceptionMessage\", \"ExceptionMessage_Value\" },\n                    { httpError, () => httpError.ExceptionType, \"ExceptionType\", \"ExceptionType_Value\" },\n                    { httpError, () => httpError.StackTrace, \"StackTrace\", \"StackTrace_Value\" },\n                };\n            }\n        }\n\n        public static TheoryDataSet<HttpError> HttpErrors\n        {\n            get\n            {\n                return new TheoryDataSet<HttpError>()\n                {\n                    new HttpError(),\n                    new HttpError(\"error\"),\n                    new HttpError(new NotImplementedException(), true),\n                    new HttpError(new ModelStateDictionary() { { \"key\", new ModelState() { Errors = { new ModelError(\"error\") } } } }, true),\n                    new HttpError(\"error\", \"errordetail\"),\n                };\n            }\n        }\n\n        [Fact]\n        public void Constructor_GuardClauses()\n        {\n            Assert.ThrowsArgumentNull(\n                () => new HttpError(message: null),\n                \"message\");\n            Assert.ThrowsArgumentNull(\n                () => new HttpError(exception: null, includeErrorDetail: false),\n                \"exception\");\n            Assert.ThrowsArgumentNull(\n                () => new HttpError(modelState: null, includeErrorDetail: false),\n                \"modelState\");\n        }\n\n        [Fact]\n        public void StringConstructor_AddsCorrectDictionaryItems()\n        {\n            HttpError error = new HttpError(\"something bad happened\");\n\n            Assert.Contains(new KeyValuePair<string, object>(\"Message\", \"something bad happened\"), error);\n        }\n\n        [Fact]\n        public void ExceptionConstructorWithDetail_AddsCorrectDictionaryItems()\n        {\n            HttpError error = new HttpError(new ArgumentException(\"error\", new Exception()), true);\n\n            Assert.Contains(new KeyValuePair<string, object>(\"Message\", \"An error has occurred.\"), error);\n            Assert.Contains(new KeyValuePair<string, object>(\"ExceptionMessage\", \"error\"), error);\n            Assert.Contains(new KeyValuePair<string, object>(\"ExceptionType\", \"System.ArgumentException\"), error);\n            Assert.True(error.ContainsKey(\"StackTrace\"));\n            Assert.True(error.ContainsKey(\"InnerException\"));\n            Assert.IsType<HttpError>(error[\"InnerException\"]);\n        }\n\n        [Fact]\n        public void ModelStateConstructorWithDetail_AddsCorrectDictionaryItems()\n        {\n            ModelStateDictionary modelState = new ModelStateDictionary();\n            modelState.AddModelError(\"[0].Name\", \"error1\");\n            modelState.AddModelError(\"[0].Name\", \"error2\");\n            modelState.AddModelError(\"[0].Address\", \"error\");\n            modelState.AddModelError(\"[2].Name\", new Exception(\"OH NO\"));\n\n            HttpError error = new HttpError(modelState, true);\n            HttpError modelStateError = error[\"ModelState\"] as HttpError;\n\n            Assert.Contains(new KeyValuePair<string, object>(\"Message\", \"The request is invalid.\"), error);\n            Assert.Contains(\"error1\", modelStateError[\"[0].Name\"] as IEnumerable<string>);\n            Assert.Contains(\"error2\", modelStateError[\"[0].Name\"] as IEnumerable<string>);\n            Assert.Contains(\"error\", modelStateError[\"[0].Address\"] as IEnumerable<string>);\n            Assert.True(modelStateError.ContainsKey(\"[2].Name\"));\n            Assert.Contains(\"OH NO\", modelStateError[\"[2].Name\"] as IEnumerable<string>);\n        }\n\n        [Fact]\n        public void ExceptionConstructorWithoutDetail_AddsCorrectDictionaryItems()\n        {\n            HttpError error = new HttpError(new ArgumentException(\"error\", new Exception()), false);\n\n            Assert.Contains(new KeyValuePair<string, object>(\"Message\", \"An error has occurred.\"), error);\n            Assert.False(error.ContainsKey(\"ExceptionMessage\"));\n            Assert.False(error.ContainsKey(\"ExceptionType\"));\n            Assert.False(error.ContainsKey(\"StackTrace\"));\n            Assert.False(error.ContainsKey(\"InnerException\"));\n        }\n\n        [Fact]\n        public void ModelStateConstructorWithoutDetail_AddsCorrectDictionaryItems()\n        {\n            ModelStateDictionary modelState = new ModelStateDictionary();\n            modelState.AddModelError(\"[0].Name\", \"error1\");\n            modelState.AddModelError(\"[0].Name\", \"error2\");\n            modelState.AddModelError(\"[0].Address\", \"error\");\n            modelState.AddModelError(\"[2].Name\", new Exception(\"OH NO\"));\n\n            HttpError error = new HttpError(modelState, false);\n            HttpError modelStateError = error[\"ModelState\"] as HttpError;\n\n            Assert.Contains(new KeyValuePair<string, object>(\"Message\", \"The request is invalid.\"), error);\n            Assert.Contains(\"error1\", modelStateError[\"[0].Name\"] as IEnumerable<string>);\n            Assert.Contains(\"error2\", modelStateError[\"[0].Name\"] as IEnumerable<string>);\n            Assert.Contains(\"error\", modelStateError[\"[0].Address\"] as IEnumerable<string>);\n            Assert.True(modelStateError.ContainsKey(\"[2].Name\"));\n            Assert.DoesNotContain(\"OH NO\", modelStateError[\"[2].Name\"] as IEnumerable<string>);\n        }\n\n        [Fact]\n        public async Task HttpError_Roundtrips_WithJsonFormatter()\n        {\n            HttpError error = new HttpError(\"error\") { { \"ErrorCode\", 42 }, { \"Data\", new[] { \"a\", \"b\", \"c\" } } };\n            MediaTypeFormatter formatter = new JsonMediaTypeFormatter();\n            MemoryStream stream = new MemoryStream();\n\n            await formatter.WriteToStreamAsync(typeof(HttpError), error, stream, content: null, transportContext: null);\n            stream.Position = 0;\n            HttpError roundtrippedError = (await formatter.ReadFromStreamAsync(typeof(HttpError), stream, content: null, formatterLogger: null)) as HttpError;\n\n            Assert.NotNull(roundtrippedError);\n            Assert.Equal(\"error\", roundtrippedError.Message);\n            Assert.Equal(42L, roundtrippedError[\"ErrorCode\"]);\n            JArray data = roundtrippedError[\"Data\"] as JArray;\n            Assert.Equal(3, data.Count);\n            Assert.Contains(\"a\", data);\n            Assert.Contains(\"b\", data);\n            Assert.Contains(\"c\", data);\n        }\n\n        [Fact]\n        public async Task HttpError_Roundtrips_WithXmlFormatter()\n        {\n            HttpError error = new HttpError(\"error\") { { \"ErrorCode\", 42 }, { \"Data\", new[] { \"a\", \"b\", \"c\" } } };\n            MediaTypeFormatter formatter = new XmlMediaTypeFormatter();\n            MemoryStream stream = new MemoryStream();\n\n            await formatter.WriteToStreamAsync(typeof(HttpError), error, stream, content: null, transportContext: null);\n            stream.Position = 0;\n            HttpError roundtrippedError = (await formatter.ReadFromStreamAsync(typeof(HttpError), stream, content: null, formatterLogger: null)) as HttpError;\n\n            Assert.NotNull(roundtrippedError);\n            Assert.Equal(\"error\", roundtrippedError.Message);\n            Assert.Equal(\"42\", roundtrippedError[\"ErrorCode\"]);\n            Assert.Equal(\"a b c\", roundtrippedError[\"Data\"]);\n        }\n\n        [Fact]\n        public async Task HttpErrorWithWhitespace_Roundtrips_WithXmlFormatter()\n        {\n            string message = \"  foo\\n bar  \\n \";\n            HttpError error = new HttpError(message);\n            MediaTypeFormatter formatter = new XmlMediaTypeFormatter();\n            MemoryStream stream = new MemoryStream();\n\n            await formatter.WriteToStreamAsync(typeof(HttpError), error, stream, content: null, transportContext: null);\n            stream.Position = 0;\n            HttpError roundtrippedError = (await formatter.ReadFromStreamAsync(typeof(HttpError), stream, content: null, formatterLogger: null)) as HttpError;\n\n            Assert.NotNull(roundtrippedError);\n            Assert.Equal(message, roundtrippedError.Message);\n        }\n\n        [Fact]\n        public async Task HttpError_Roundtrips_WithXmlSerializer()\n        {\n            HttpError error = new HttpError(\"error\") { { \"ErrorCode\", 42 }, { \"Data\", new[] { \"a\", \"b\", \"c\" } } };\n            MediaTypeFormatter formatter = new XmlMediaTypeFormatter() { UseXmlSerializer = true };\n            MemoryStream stream = new MemoryStream();\n\n            await formatter.WriteToStreamAsync(typeof(HttpError), error, stream, content: null, transportContext: null);\n            stream.Position = 0;\n            HttpError roundtrippedError = (await formatter.ReadFromStreamAsync(typeof(HttpError), stream, content: null, formatterLogger: null)) as HttpError;\n\n            Assert.NotNull(roundtrippedError);\n            Assert.Equal(\"error\", roundtrippedError.Message);\n            Assert.Equal(\"42\", roundtrippedError[\"ErrorCode\"]);\n            Assert.Equal(\"a b c\", roundtrippedError[\"Data\"]);\n        }\n\n        [Fact]\n        public async Task HttpErrorForInnerException_Serializes_WithXmlSerializer()\n        {\n            HttpError error = new HttpError(new ArgumentException(\"error\", new Exception(\"innerError\")), includeErrorDetail: true);\n            MediaTypeFormatter formatter = new XmlMediaTypeFormatter() { UseXmlSerializer = true };\n            MemoryStream stream = new MemoryStream();\n\n            await formatter.WriteToStreamAsync(typeof(HttpError), error, stream, content: null, transportContext: null);\n            stream.Position = 0;\n            string serializedError = new StreamReader(stream).ReadToEnd();\n\n            Assert.NotNull(serializedError);\n            Assert.Equal(\n                \"<Error><Message>An error has occurred.</Message><ExceptionMessage>error</ExceptionMessage><ExceptionType>System.ArgumentException</ExceptionType><StackTrace /><InnerException><Message>An error has occurred.</Message><ExceptionMessage>innerError</ExceptionMessage><ExceptionType>System.Exception</ExceptionType><StackTrace /></InnerException></Error>\",\n                serializedError);\n        }\n\n        [Fact]\n        public void HttpError_Message_RoundTrips()\n        {\n            string message = \"HelloWorld\";\n            Assert.Reflection.Property(\n                new HttpError(message),\n                e => e.Message,\n                expectedDefaultValue: message,\n                allowNull: true,\n                roundTripTestValue: \"HelloAgain\");\n        }\n\n        [Fact]\n        public void HttpError_MessageDetail_RoundTrips()\n        {\n            string messageDetail = \"HelloWorld\";\n            Assert.Reflection.Property(\n                new HttpError(\"message\", messageDetail),\n                e => e.MessageDetail,\n                expectedDefaultValue: messageDetail,\n                allowNull: true,\n                roundTripTestValue: \"HelloAgain\");\n        }\n\n        [Fact]\n        public void HttpError_ExceptionMessage_RoundTrips()\n        {\n            string exceptionMessage = \"ExceptionMessage\";\n            Exception exception = new Exception(exceptionMessage);\n            Assert.Reflection.Property(\n                new HttpError(exception, includeErrorDetail: true),\n                e => e.ExceptionMessage,\n                expectedDefaultValue: exceptionMessage,\n                allowNull: true,\n                roundTripTestValue: \"HelloAgain\");\n        }\n\n        [Fact]\n        public void HttpError_ExceptionType_RoundTrips()\n        {\n            ApplicationException exception = new ApplicationException(\"HelloWorld\");\n            Assert.Reflection.Property(\n                new HttpError(exception, includeErrorDetail: true),\n                e => e.ExceptionType,\n                expectedDefaultValue: exception.GetType().FullName,\n                allowNull: true,\n                roundTripTestValue: \"HelloAgain\");\n        }\n\n        [Fact]\n        public void HttpError_StackTrace_RoundTrips()\n        {\n            Exception exception;\n            try\n            {\n                throw new Exception(\"HelloWorld\");\n            }\n            catch (Exception e)\n            {\n                exception = e;\n            }\n\n            Assert.Reflection.Property(\n                new HttpError(exception, includeErrorDetail: true),\n                e => e.StackTrace,\n                expectedDefaultValue: exception.StackTrace,\n                allowNull: true,\n                roundTripTestValue: \"HelloAgain\");\n        }\n\n        [Fact]\n        public void GetPropertyValue_GetsValue_IfTypeMatches()\n        {\n            HttpError error = new HttpError();\n            error[\"key\"] = \"x\";\n\n            Assert.Equal(\"x\", error.GetPropertyValue<string>(\"key\"));\n            Assert.Equal(\"x\", error.GetPropertyValue<object>(\"key\"));\n        }\n\n        [Fact]\n        public void GetPropertyValue_GetsDefault_IfTypeDoesNotMatch()\n        {\n            HttpError error = new HttpError();\n            error[\"key\"] = \"x\";\n\n            Assert.Null(error.GetPropertyValue<Uri>(\"key\"));\n            Assert.Equal(0, error.GetPropertyValue<int>(\"key\"));\n        }\n\n        [Fact]\n        public void GetPropertyValue_GetsDefault_IfPropertyMissing()\n        {\n            HttpError error = new HttpError();\n\n            Assert.Null(error.GetPropertyValue<string>(\"key\"));\n            Assert.Equal(0, error.GetPropertyValue<int>(\"key\"));\n        }\n\n        [Theory]\n        [PropertyData(\"ErrorKeyValue\")]\n        public void HttpErrorStringProperties_UseCorrectHttpErrorKey(HttpError httpError, Func<string> productUnderTest, string key, string actualValue)\n        {\n            // Arrange\n            httpError[key] = actualValue;\n\n            // Act\n            string expectedValue = productUnderTest.Invoke();\n\n            // Assert\n            Assert.Equal(expectedValue, actualValue);\n        }\n\n        [Fact]\n        public void HttpErrorProperty_InnerException_UsesCorrectHttpErrorKey()\n        {\n            // Arrange\n            HttpError error = new HttpError(new ArgumentException(\"error\", new Exception()), true);\n\n            // Act\n            HttpError innerException = error.InnerException;\n\n            // Assert\n            Assert.Same(error[\"InnerException\"], innerException);\n        }\n\n        [Fact]\n        public void HttpErrorProperty_ModelState_UsesCorrectHttpErrorKey()\n        {\n            // Arrange\n            ModelStateDictionary modelState = new ModelStateDictionary();\n            modelState.AddModelError(\"[0].Name\", \"error1\");\n            HttpError error = new HttpError(modelState, true);\n\n            // Act\n            HttpError actualModelStateError = error.ModelState;\n\n            // Assert\n            Assert.Same(error[\"ModelState\"], actualModelStateError);\n        }\n\n        [Theory]\n        [PropertyData(\"HttpErrors\")]\n        public void HttpErrors_UseCaseInsensitiveComparer(HttpError httpError)\n        {\n            var lowercaseKey = \"abcd\";\n            var uppercaseKey = \"ABCD\";\n\n            httpError[lowercaseKey] = \"error\";\n\n            Assert.True(httpError.ContainsKey(lowercaseKey));\n            Assert.True(httpError.ContainsKey(uppercaseKey));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Dispatcher/HttpRoutingDispatcherTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\nusing Moq.Protected;\n\nnamespace System.Web.Http.Dispatcher\n{\n    public class HttpRoutingDispatcherTest\n    {\n        [Fact]\n        public void Constructor_GuardClauses()\n        {\n            Assert.ThrowsArgumentNull(\n                () => new HttpRoutingDispatcher(configuration: null),\n                \"configuration\");\n            Assert.ThrowsArgumentNull(\n                () => new HttpRoutingDispatcher(configuration: null, defaultHandler: new Mock<HttpMessageHandler>().Object),\n                \"configuration\");\n            Assert.ThrowsArgumentNull(\n                () => new HttpRoutingDispatcher(new HttpConfiguration(), defaultHandler: null),\n                \"defaultHandler\");\n        }\n\n        [Fact]\n        public async Task SendAsync_PopulatesRouteDataWhenNotPresentInRequest()\n        {\n            var config = new HttpConfiguration();\n            var request = CreateRequest(config, \"http://localhost/api/controllerName/42\");\n            var dispatcher = new HttpRoutingDispatcher(config);\n            var invoker = new HttpMessageInvoker(dispatcher);\n\n            await invoker.SendAsync(request, CancellationToken.None);\n\n            var routeData = request.GetRouteData();\n            Assert.NotNull(routeData);\n            Assert.Same(config.Routes.Single(), routeData.Route);\n            Assert.Equal(\"controllerName\", routeData.Values[\"controller\"]);\n            Assert.Equal(\"42\", routeData.Values[\"id\"]);\n        }\n\n        [Fact]\n        public async Task SendAsync_RemovesRouteParameterOptionalValuesThatAreNotPresent()\n        {\n            var config = new HttpConfiguration();\n            var request = CreateRequest(config, \"http://localhost/api/controllerName\");\n            var dispatcher = new HttpRoutingDispatcher(config);\n            var invoker = new HttpMessageInvoker(dispatcher);\n\n            await invoker.SendAsync(request, CancellationToken.None);\n\n            Assert.False(request.GetRouteData().Values.ContainsKey(\"id\"));\n        }\n\n        [Fact]\n        public async Task SendAsync_Returns404WhenNoMatchingRoute()\n        {\n            var config = new HttpConfiguration();\n            var request = CreateRequest(config, \"http://localhost/noMatch\");\n            var dispatcher = new HttpRoutingDispatcher(config);\n            var invoker = new HttpMessageInvoker(dispatcher);\n\n            var response = await invoker.SendAsync(request, CancellationToken.None);\n\n            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);\n            Assert.True((bool)request.Properties[HttpPropertyKeys.NoRouteMatched]);\n        }\n\n        [Fact]\n        public void SendAsync_CallsDefaultHandlerWhenRouteHandlerIsNull()\n        {\n            var mockHandler = new Mock<HttpMessageHandler>();\n            var config = new HttpConfiguration();\n            var request = CreateRequest(config, \"http://localhost/api/controllerName\", routeHandler: null);\n            var dispatcher = new HttpRoutingDispatcher(config, defaultHandler: mockHandler.Object);\n            var invoker = new HttpMessageInvoker(dispatcher);\n\n            invoker.SendAsync(request, CancellationToken.None);\n\n            mockHandler.Protected().Verify(\"SendAsync\", Times.Once(), request, CancellationToken.None);\n        }\n\n        [Fact]\n        public void SendAsync_CallsRouterHandlerWhenRouteHandlerIsNotNull()\n        {\n            var mockHandler = new Mock<HttpMessageHandler>();\n            var config = new HttpConfiguration();\n            var request = CreateRequest(config, \"http://localhost/api/controllerName\", routeHandler: mockHandler.Object);\n            var dispatcher = new HttpRoutingDispatcher(config);\n            var invoker = new HttpMessageInvoker(dispatcher);\n\n            invoker.SendAsync(request, CancellationToken.None);\n\n            mockHandler.Protected().Verify(\"SendAsync\", Times.Once(), request, CancellationToken.None);\n        }\n\n        [Fact]\n        public async Task SendAsync_UsesRouteDataFromRequestContext()\n        {\n            // Arrange\n            Mock<HttpMessageHandler> doNotUseDefaultHandlerMock = new Mock<HttpMessageHandler>(MockBehavior.Strict);\n            doNotUseDefaultHandlerMock.As<IDisposable>().Setup(c => c.Dispose());\n\n            using (HttpConfiguration configuration = new HttpConfiguration())\n            using (HttpMessageHandler doNoUseDefaultHandler = doNotUseDefaultHandlerMock.Object)\n            using (HttpRoutingDispatcher dispatcher = new HttpRoutingDispatcher(configuration, doNoUseDefaultHandler))\n            using (HttpMessageInvoker invoker = new HttpMessageInvoker(dispatcher))\n            using (HttpRequestMessage expectedRequest = new HttpRequestMessage())\n            using (HttpResponseMessage expectedResponse = new HttpResponseMessage())\n            {\n                SpyHttpMessageHandler routeHandler = new SpyHttpMessageHandler(expectedResponse);\n\n                Mock<IHttpRoute> routeMock = new Mock<IHttpRoute>(MockBehavior.Strict);\n                routeMock.Setup(r => r.Handler).Returns(routeHandler);\n\n                Mock<IHttpRouteData> routeDataMock = new Mock<IHttpRouteData>(MockBehavior.Strict);\n                routeDataMock.Setup(d => d.Route).Returns(routeMock.Object);\n                routeDataMock.Setup(d => d.Values).Returns(new Dictionary<string, object>());\n\n                HttpRequestContext context = new HttpRequestContext();\n                context.RouteData = routeDataMock.Object;\n                expectedRequest.SetRequestContext(context);\n\n                // Act\n                HttpResponseMessage response = await invoker.SendAsync(expectedRequest, CancellationToken.None);\n\n                // Assert\n                Assert.Same(expectedResponse, response);\n                Assert.Same(expectedRequest, routeHandler.Request);\n            }\n        }\n\n        [Fact]\n        public async Task SendAsync_IgnoreRoute_UsesRouteDataWithStopRoutingHandlerFromRequestContext()\n        {\n            // Arrange\n            Mock<HttpMessageHandler> doNotUseDefaultHandlerMock = new Mock<HttpMessageHandler>(MockBehavior.Strict);\n            doNotUseDefaultHandlerMock.As<IDisposable>().Setup(c => c.Dispose());\n\n            using (HttpConfiguration configuration = new HttpConfiguration())\n            using (HttpMessageHandler doNoUseDefaultHandler = doNotUseDefaultHandlerMock.Object)\n            using (HttpRoutingDispatcher dispatcher = new HttpRoutingDispatcher(configuration, doNoUseDefaultHandler))\n            using (HttpMessageInvoker invoker = new HttpMessageInvoker(dispatcher))\n            using (HttpRequestMessage expectedRequest = new HttpRequestMessage())\n            using (HttpResponseMessage expectedResponse = new HttpResponseMessage())\n            {\n                HttpMessageHandler routeHandler = new StopRoutingHandler();\n\n                Mock<IHttpRoute> routeMock = new Mock<IHttpRoute>(MockBehavior.Strict);\n                routeMock.Setup(r => r.Handler).Returns(routeHandler);\n\n                Mock<IHttpRouteData> routeDataMock = new Mock<IHttpRouteData>(MockBehavior.Strict);\n                routeDataMock.Setup(d => d.Route).Returns(routeMock.Object);\n                routeDataMock.Setup(d => d.Values).Returns(new Dictionary<string, object>());\n\n                HttpRequestContext context = new HttpRequestContext();\n                context.RouteData = routeDataMock.Object;\n                expectedRequest.SetRequestContext(context);\n\n                // Act\n                HttpResponseMessage response = await invoker.SendAsync(expectedRequest, CancellationToken.None);\n\n                // Assert\n                Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);\n                Assert.True(response.RequestMessage.Properties.ContainsKey(HttpPropertyKeys.NoRouteMatched));\n            }\n        }\n\n        private static HttpRequestMessage CreateRequest(HttpConfiguration config, string requestUri)\n        {\n            return CreateRequest(config, requestUri, routeHandler: new EmptyResponseHandler());\n        }\n\n        private static HttpRequestMessage CreateRequest(HttpConfiguration config, string requestUri, HttpMessageHandler routeHandler)\n        {\n            var route = config.Routes.CreateRoute(\"api/{controller}/{id}\",\n                                                  defaults: new Dictionary<string, object> { { \"id\", RouteParameter.Optional } },\n                                                  constraints: null,\n                                                  dataTokens: null,\n                                                  handler: routeHandler);\n            config.Routes.Add(\"default\", route);\n\n            var request = new HttpRequestMessage(HttpMethod.Get, requestUri);\n            request.SetConfiguration(config);\n            return request;\n        }\n\n        private class EmptyResponseHandler : HttpMessageHandler\n        {\n            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n            {\n                return Task.FromResult(request.CreateResponse(HttpStatusCode.OK));\n            }\n        }\n\n        private class SpyHttpMessageHandler : HttpMessageHandler\n        {\n            private readonly HttpResponseMessage _response;\n\n            public HttpRequestMessage Request { get; private set; }\n            public CancellationToken CancellationToken { get; private set; }\n\n            public SpyHttpMessageHandler(HttpResponseMessage response)\n            {\n                _response = response;\n            }\n\n            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n            {\n                Request = request;\n                CancellationToken = cancellationToken;\n                return Task.FromResult(_response);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ExceptionHandling/CompositeExceptionLoggerTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    public class CompositeExceptionLoggerTests\n    {\n        [Fact]\n        public void Constructor_IfLoggersIsNull_Throws()\n        {\n            // Arrange\n            IEnumerable<IExceptionLogger> loggers = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => CreateProductUnderTest(loggers), \"loggers\");\n        }\n\n        [Fact]\n        public void Loggers_ContainsSpecifiedInstances()\n        {\n            // Arrange\n            IExceptionLogger expectedLogger = CreateDummyLogger();\n            List<IExceptionLogger> expectedLoggers = new List<IExceptionLogger> { expectedLogger };\n            CompositeExceptionLogger product = CreateProductUnderTest(expectedLoggers);\n\n            // Act\n            IEnumerable<IExceptionLogger> loggers = product.Loggers;\n\n            // Assert\n            Assert.NotNull(loggers);\n            IExceptionLogger logger = Assert.Single(loggers);\n            Assert.Same(expectedLogger, logger);\n\n        }\n\n        [Fact]\n        public void Constructor_CapturesLoggersContents()\n        {\n            // Arrange\n            IExceptionLogger expectedLogger = CreateDummyLogger();\n            List<IExceptionLogger> expectedLoggers = new List<IExceptionLogger> { expectedLogger };\n\n            // Act\n            CompositeExceptionLogger product = CreateProductUnderTest(expectedLoggers);\n\n            // Assert\n            expectedLoggers.Clear();\n            IEnumerable<IExceptionLogger> loggers = product.Loggers;\n            Assert.NotNull(loggers);\n            IExceptionLogger logger = Assert.Single(loggers);\n            Assert.Same(expectedLogger, logger);\n        }\n\n        [Fact]\n        public void ConstructorWithParams_SetsLoggers()\n        {\n            // Arrange\n            IExceptionLogger expectedLogger1 = CreateDummyLogger();\n            IExceptionLogger expectedLogger2 = CreateDummyLogger();\n\n            // Act\n            CompositeExceptionLogger product = new CompositeExceptionLogger(expectedLogger1, expectedLogger2);\n\n            // Assert\n            IEnumerable<IExceptionLogger> loggers = product.Loggers;\n            Assert.NotNull(loggers);\n            Assert.Equal(2, loggers.Count());\n            Assert.Same(expectedLogger1, loggers.ElementAt(0));\n            Assert.Same(expectedLogger2, loggers.ElementAt(1));\n        }\n\n        [Fact]\n        public async Task LogAsync_DelegatesToLoggers()\n        {\n            // Arrange\n            Mock<IExceptionLogger> exceptionLogger1Mock = new Mock<IExceptionLogger>(MockBehavior.Strict);\n            Mock<IExceptionLogger> exceptionLogger2Mock = new Mock<IExceptionLogger>(MockBehavior.Strict);\n            exceptionLogger1Mock\n                .Setup(l => l.LogAsync(It.IsAny<ExceptionLoggerContext>(), It.IsAny<CancellationToken>()))\n                .Returns(Task.FromResult(0));\n            exceptionLogger2Mock\n                .Setup(l => l.LogAsync(It.IsAny<ExceptionLoggerContext>(), It.IsAny<CancellationToken>()))\n                .Returns(Task.FromResult(0));\n            IEnumerable<IExceptionLogger> loggers = new IExceptionLogger[]\n            {\n                exceptionLogger1Mock.Object,\n                exceptionLogger2Mock.Object\n            };\n            IExceptionLogger product = CreateProductUnderTest(loggers);\n\n            ExceptionLoggerContext expectedContext = CreateMinimalValidContext();\n            CancellationToken expectedCancellationToken = CreateCancellationToken();\n\n            // Act\n            await product.LogAsync(expectedContext, expectedCancellationToken);\n\n            // Assert\n            exceptionLogger1Mock.Verify(l => l.LogAsync(expectedContext, expectedCancellationToken), Times.Once());\n            exceptionLogger2Mock.Verify(l => l.LogAsync(expectedContext, expectedCancellationToken), Times.Once());\n        }\n\n        [Fact]\n        public void LogAsync_IfLoggerIsNull_Throws()\n        {\n            // Arrange\n            IEnumerable<IExceptionLogger> loggers = new IExceptionLogger[] { null };\n            IExceptionLogger product = CreateProductUnderTest(loggers);\n\n            ExceptionLoggerContext context = CreateMinimalValidContext();\n            CancellationToken cancellationToken = CreateCancellationToken();\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(() => product.LogAsync(context, cancellationToken),\n                \"The IExceptionLogger instance must not be null.\");\n\n        }\n\n        private static CancellationToken CreateCancellationToken()\n        {\n            CancellationTokenSource source = new CancellationTokenSource();\n            return source.Token;\n        }\n\n        private static ExceptionLoggerContext CreateMinimalValidContext()\n        {\n            return new ExceptionLoggerContext(new ExceptionContext(new Exception(), ExceptionCatchBlocks.HttpServer));\n        }\n\n        private static IExceptionLogger CreateDummyLogger()\n        {\n            return new Mock<IExceptionLogger>(MockBehavior.Strict).Object;\n        }\n\n        private static CompositeExceptionLogger CreateProductUnderTest(IEnumerable<IExceptionLogger> loggers)\n        {\n            return new CompositeExceptionLogger(loggers);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ExceptionHandling/DefaultExceptionHandlerTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Results;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    public class DefaultExceptionHandlerTests\n    {\n        [Fact]\n        public void HandleAsync_IfContextIsNull_Throws()\n        {\n            // Arrange\n            IExceptionHandler product = CreateProductUnderTest();\n            ExceptionHandlerContext context = null;\n            CancellationToken cancellationToken = CancellationToken.None;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => product.HandleAsync(context, cancellationToken), \"context\");\n        }\n\n        [Fact]\n        public void HandleAsync_IfRequestIsNull_Throws()\n        {\n            // Arrange\n            IExceptionHandler product = CreateProductUnderTest();\n            ExceptionHandlerContext context = new ExceptionHandlerContext(new ExceptionContext(CreateException(), ExceptionCatchBlocks.HttpServer));\n            Assert.Null(context.ExceptionContext.Request); // Guard\n            CancellationToken cancellationToken = CancellationToken.None;\n\n            // Act & Assert\n            Assert.ThrowsArgument(() => product.HandleAsync(context, cancellationToken), \"context\",\n                \"ExceptionContext.Request must not be null.\");\n        }\n\n        [Fact]\n        public async Task HandleAsync_HandlesExceptionViaCreateErrorResponse()\n        {\n            IExceptionHandler product = CreateProductUnderTest();\n\n            // Arrange\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                expectedRequest.SetRequestContext(new HttpRequestContext { IncludeErrorDetail = true });\n                ExceptionHandlerContext context = CreateValidContext(expectedRequest);\n                CancellationToken cancellationToken = CancellationToken.None;\n\n                // Act\n                await product.HandleAsync(context, cancellationToken);\n\n                // Assert\n                IHttpActionResult result = context.Result;\n                ResponseMessageResult typedResult = Assert.IsType<ResponseMessageResult>(result);\n                using (HttpResponseMessage response = typedResult.Response)\n                {\n                    Assert.NotNull(response);\n\n                    using (HttpResponseMessage expectedResponse = expectedRequest.CreateErrorResponse(\n                        HttpStatusCode.InternalServerError, context.ExceptionContext.Exception))\n                    {\n                        AssertErrorResponse(expectedResponse, response);\n                    }\n\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task HandleAsync_IfCatchBlockIsIExceptionFilter_LeavesExceptionUnhandled()\n        {\n            IExceptionHandler product = CreateProductUnderTest();\n\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                ExceptionHandlerContext context = CreateValidContext(request, ExceptionCatchBlocks.IExceptionFilter);\n                CancellationToken cancellationToken = CancellationToken.None;\n\n                // Act\n                await product.HandleAsync(context, cancellationToken);\n\n                // Assert\n                Assert.Null(context.Result);\n            }\n        }\n\n        private static void AssertErrorResponse(HttpResponseMessage expected, HttpResponseMessage actual)\n        {\n            Assert.NotNull(expected); // Guard\n            ObjectContent<HttpError> expectedContent = Assert.IsType<ObjectContent<HttpError>>(expected.Content); // Guard\n            Assert.NotNull(expectedContent.Formatter); // Guard\n\n            Assert.NotNull(actual);\n            Assert.Equal(expected.StatusCode, actual.StatusCode);\n            ObjectContent<HttpError> actualContent = Assert.IsType<ObjectContent<HttpError>>(actual.Content);\n            Assert.NotNull(actualContent.Formatter);\n            Assert.Same(expectedContent.Formatter.GetType(), actualContent.Formatter.GetType());\n            Assert.Equal(expectedContent.Value, actualContent.Value);\n            Assert.Same(expected.RequestMessage, actual.RequestMessage);\n        }\n\n        private static ExceptionHandlerContext CreateContext(ExceptionContext exceptionContext)\n        {\n            return new ExceptionHandlerContext(exceptionContext);\n        }\n\n        private static Exception CreateException()\n        {\n            return new NotSupportedException();\n        }\n\n        private static DefaultExceptionHandler CreateProductUnderTest()\n        {\n            return new DefaultExceptionHandler();\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private static ExceptionHandlerContext CreateValidContext(HttpRequestMessage request)\n        {\n            return CreateContext(new ExceptionContext(CreateException(), ExceptionCatchBlocks.HttpServer, request));\n        }\n\n        private static ExceptionHandlerContext CreateValidContext(HttpRequestMessage request,\n            ExceptionContextCatchBlock catchBlock)\n        {\n            return CreateContext(new ExceptionContext(CreateException(), catchBlock, request));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ExceptionHandling/EmptyExceptionHandlerTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    public class EmptyExceptionHandlerTests\n    {\n        [Fact]\n        public void HandleAsync_ReturnsCompletedTask()\n        {\n            // Arrange\n            IExceptionHandler product = CreateProductUnderTest();\n\n            ExceptionHandlerContext context = CreateContext();\n            CancellationToken cancellationToken = CancellationToken.None;\n\n            // Act\n            Task task = product.HandleAsync(context, cancellationToken);\n\n            // Assert\n            Assert.NotNull(task);\n            Assert.Equal(TaskStatus.RanToCompletion, task.Status);\n        }\n\n        private static ExceptionHandlerContext CreateContext()\n        {\n            return new ExceptionHandlerContext(new ExceptionContext(new Exception(), ExceptionCatchBlocks.HttpServer));\n        }\n\n        private static EmptyExceptionHandler CreateProductUnderTest()\n        {\n            return new EmptyExceptionHandler();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ExceptionHandling/ExceptionCatchBlocksTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    public class ExceptionCatchBlocksTests\n    {\n        [Fact]\n        public void HttpBatchHandler_IsSpecifiedValue()\n        {\n            // Act\n            ExceptionContextCatchBlock catchBlock = ExceptionCatchBlocks.HttpBatchHandler;\n\n            // Assert\n            ExceptionContextCatchBlock expected =\n                new ExceptionContextCatchBlock(\"HttpBatchHandler\", isTopLevel: false, callsHandler: true);\n            AssertEqual(expected, catchBlock);\n        }\n\n        [Fact]\n        public void HttpBatchHandler_IsSameInstance()\n        {\n            // Arrange\n            ExceptionContextCatchBlock first = ExceptionCatchBlocks.HttpBatchHandler;\n\n            // Act\n            ExceptionContextCatchBlock second = ExceptionCatchBlocks.HttpBatchHandler;\n\n            // Assert\n            Assert.Same(first, second);\n        }\n\n        [Fact]\n        public void HttpControllerDispatcher_IsSpecifiedValue()\n        {\n            // Act\n            ExceptionContextCatchBlock catchBlock = ExceptionCatchBlocks.HttpControllerDispatcher;\n\n            // Assert\n            ExceptionContextCatchBlock expected =\n                new ExceptionContextCatchBlock(\"HttpControllerDispatcher\", isTopLevel: false, callsHandler: true);\n            AssertEqual(expected, catchBlock);\n        }\n\n        [Fact]\n        public void HttpControllerDispatcher_IsSameInstance()\n        {\n            // Arrange\n            ExceptionContextCatchBlock first = ExceptionCatchBlocks.HttpControllerDispatcher;\n\n            // Act\n            ExceptionContextCatchBlock second = ExceptionCatchBlocks.HttpControllerDispatcher;\n\n            // Assert\n            Assert.Same(first, second);\n        }\n\n        [Fact]\n        public void HttpServer_IsSpecifiedValue()\n        {\n            // Act\n            ExceptionContextCatchBlock catchBlock = ExceptionCatchBlocks.HttpServer;\n\n            // Assert\n            ExceptionContextCatchBlock expected =\n                new ExceptionContextCatchBlock(\"HttpServer\", isTopLevel: true, callsHandler: true);\n            AssertEqual(expected, catchBlock);\n        }\n\n        [Fact]\n        public void HttpServer_IsSameInstance()\n        {\n            // Arrange\n            ExceptionContextCatchBlock first = ExceptionCatchBlocks.HttpServer;\n\n            // Act\n            ExceptionContextCatchBlock second = ExceptionCatchBlocks.HttpServer;\n\n            // Assert\n            Assert.Same(first, second);\n        }\n\n        [Fact]\n        public void IExceptionFilter_IsSpecifiedValue()\n        {\n            // Act\n            ExceptionContextCatchBlock catchBlock = ExceptionCatchBlocks.IExceptionFilter;\n\n            // Assert\n            ExceptionContextCatchBlock expected =\n                new ExceptionContextCatchBlock(\"IExceptionFilter\", isTopLevel: false, callsHandler: true);\n            AssertEqual(expected, catchBlock);\n        }\n\n        [Fact]\n        public void IExceptionFilter_IsSameInstance()\n        {\n            // Arrange\n            ExceptionContextCatchBlock first = ExceptionCatchBlocks.IExceptionFilter;\n\n            // Act\n            ExceptionContextCatchBlock second = ExceptionCatchBlocks.IExceptionFilter;\n\n            // Assert\n            Assert.Same(first, second);\n        }\n\n        private static void AssertEqual(ExceptionContextCatchBlock expected, ExceptionContextCatchBlock actual)\n        {\n            if (expected == null)\n            {\n                Assert.Null(actual);\n                return;\n            }\n\n            Assert.NotNull(actual);\n            Assert.Equal(expected.Name, actual.Name);\n            Assert.Equal(expected.IsTopLevel, actual.IsTopLevel);\n            Assert.Equal(expected.CallsHandler, actual.CallsHandler);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ExceptionHandling/ExceptionContextCatchBlockTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    public class ExceptionContextCatchBlockTests\n    {\n        [Fact]\n        public void Constructor_IfNameIsNull_Throws()\n        {\n            // Arrange\n            string name = null;\n            bool isTopLevel = false;\n            bool callsHandler = false;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => CreateProductUnderTest(name, isTopLevel, callsHandler), \"name\");\n        }\n\n        [Fact]\n        public void Name_IsSpecifiedInstance()\n        {\n            // Arrange\n            string expectedName = \"TheName\";\n            bool isTopLevel = true;\n            bool callsHandler = false;\n            ExceptionContextCatchBlock product = CreateProductUnderTest(expectedName, isTopLevel, callsHandler);\n\n            // Act\n            string name = product.Name;\n\n            // Assert\n            Assert.Same(expectedName, name);\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void IsTopLevel_IsSpecifiedValue(bool expectedIsTopLevel)\n        {\n            // Arrange\n            string name = \"IgnoreName\";\n            bool callsHandler = false;\n            ExceptionContextCatchBlock product = CreateProductUnderTest(name, expectedIsTopLevel, callsHandler);\n\n            // Act\n            bool isTopLevel = product.IsTopLevel;\n\n            // Assert\n            Assert.Equal(expectedIsTopLevel, isTopLevel);\n        }\n\n        [Theory]\n        [InlineData(false)]\n        [InlineData(true)]\n        public void CallsHandler_IsSpecifiedValue(bool expectedCallsHandler)\n        {\n            // Arrange\n            string name = \"IgnoreName\";\n            bool isTopLevel = true;\n            ExceptionContextCatchBlock product = CreateProductUnderTest(name, isTopLevel, expectedCallsHandler);\n\n            // Act\n            bool callsHandler = product.CallsHandler;\n\n            // Assert\n            Assert.Equal(expectedCallsHandler, callsHandler);\n        }\n\n        [Fact]\n        public void ToString_ReturnsName()\n        {\n            // Arrange\n            string expectedName = \"TheName\";\n            bool isTopLevel = false;\n            bool callsHandler= false;\n            object product = CreateProductUnderTest(expectedName, isTopLevel, callsHandler);\n\n            // Act\n            string value = product.ToString();\n\n            // Assert\n            Assert.Same(expectedName, value);\n        }\n\n        [Fact]\n        public void DebuggerDisplayAttribute_IsSpecifiedValue()\n        {\n            // Act\n            DebuggerDisplayAttribute attribute = (DebuggerDisplayAttribute)Attribute.GetCustomAttribute(\n                typeof(ExceptionContextCatchBlock), typeof(DebuggerDisplayAttribute));\n\n            // Assert\n            Assert.NotNull(attribute);\n            string value = attribute.Value;\n            Assert.Equal(\"Name: {Name}, IsTopLevel: {IsTopLevel}\", value);\n        }\n\n        private static ExceptionContextCatchBlock CreateProductUnderTest(string name, bool isTopLevel, bool callsHandler)\n        {\n            return new ExceptionContextCatchBlock(name, isTopLevel, callsHandler);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ExceptionHandling/ExceptionContextTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    public class ExceptionContextTests\n    {\n        [Fact]\n        public void ConstructorWithoutArguments_SetsPropertiesToSpecifiedValues()\n        {\n            // Act\n            ExceptionContext product = CreateProductUnderTest();\n\n            // Assert\n            Assert.NotNull(product.Exception);\n            Assert.NotNull(product.CatchBlock);\n\n            Assert.Null(product.ActionContext);\n            Assert.Null(product.ControllerContext);\n            Assert.Null(product.RequestContext);\n            Assert.Null(product.Request);\n            Assert.Null(product.Response);\n        }\n\n        [Fact]\n        public void ConstructorWithActionContext_SetsPropertiesToSpecifiedValues()\n        {\n            // Arrange\n            Exception expectedException = CreateException();\n            HttpRequestContext expectedRequestContext = CreateRequestContext();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                HttpControllerContext expectedControllerContext = CreateControllerContext(expectedRequestContext,\n                    expectedRequest);\n                HttpActionContext expectedActionContext = CreateActionContext(expectedControllerContext);\n                ExceptionContextCatchBlock expectedCatchBlock = CreateCatchBlock();\n\n                // Act\n                ExceptionContext product = CreateProductUnderTest(expectedException, expectedCatchBlock,\n                    expectedActionContext);\n\n                // Assert\n                Assert.Same(expectedException, product.Exception);\n                Assert.Same(expectedCatchBlock, product.CatchBlock);\n                Assert.Same(expectedActionContext, product.ActionContext);\n                Assert.Same(expectedControllerContext, product.ControllerContext);\n                Assert.Same(expectedRequestContext, product.RequestContext);\n                Assert.Same(expectedRequest, product.Request);\n                Assert.Null(product.Response);\n            }\n        }\n\n        [Fact]\n        public void ConstructorWithActionContext_IfExceptionIsNull_Throws()\n        {\n            // Arrange\n            Exception exception = null;\n            ExceptionContextCatchBlock catchBlock = CreateCatchBlock();\n            HttpRequestContext requestContext = CreateRequestContext();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpControllerContext controllerContext = CreateControllerContext(requestContext, request);\n                HttpActionContext actionContext = CreateActionContext(controllerContext);\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() => CreateProductUnderTest(exception, catchBlock, actionContext),\n                    \"exception\");\n            }\n        }\n\n        [Fact]\n        public void ConstructorWithActionContext_IfCatchBlockIsNull_Throws()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            ExceptionContextCatchBlock catchBlock = null;\n            HttpRequestContext requestContext = CreateRequestContext();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpControllerContext controllerContext = CreateControllerContext(requestContext, request);\n                HttpActionContext actionContext = CreateActionContext(controllerContext);\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() => CreateProductUnderTest(exception, catchBlock, actionContext),\n                    \"catchBlock\");\n            }\n        }\n\n        [Fact]\n        public void ConstructorWithActionContext_IfActionContextIsNull_Throws()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            ExceptionContextCatchBlock catchBlock = CreateCatchBlock();\n            HttpActionContext actionContext = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => CreateProductUnderTest(exception, catchBlock, actionContext),\n                \"actionContext\");\n        }\n\n        [Fact]\n        public void ConstructorWithActionContext_IfControllerContextIsNull_Throws()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            ExceptionContextCatchBlock catchBlock = CreateCatchBlock();\n            HttpActionContext actionContext = new HttpActionContext();\n            Assert.Null(actionContext.ControllerContext); // Guard\n\n            // Act & Assert\n            Assert.ThrowsArgument(() => CreateProductUnderTest(exception, catchBlock, actionContext), \"actionContext\",\n                \"HttpActionContext.ControllerContext must not be null.\");\n        }\n\n        [Fact]\n        public void ConstructorWithActionContext_IfRequestIsNull_Throws()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            ExceptionContextCatchBlock catchBlock = CreateCatchBlock();\n            HttpRequestContext requestContext = CreateRequestContext();\n            HttpControllerContext controllerContext = new HttpControllerContext\n            {\n                RequestContext = requestContext\n            };\n            Assert.Null(controllerContext.Request); // Guard\n            HttpActionContext actionContext = CreateActionContext(controllerContext);\n\n            // Act & Assert\n            Assert.ThrowsArgument(() => CreateProductUnderTest(exception, catchBlock, actionContext), \"actionContext\",\n                \"HttpControllerContext.Request must not be null\");\n        }\n\n        [Fact]\n        public void ConstructorWithRequest_SetsPropertiesToSpecifiedValues()\n        {\n            // Arrange\n            Exception expectedException = CreateException();\n            ExceptionContextCatchBlock expectedCatchBlock = CreateCatchBlock();\n            HttpRequestContext expectedRequestContext = CreateRequestContext();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                expectedRequest.SetRequestContext(expectedRequestContext);\n\n                // Act\n                ExceptionContext product = CreateProductUnderTest(expectedException, expectedCatchBlock,\n                    expectedRequest);\n\n                // Assert\n                Assert.Same(expectedException, product.Exception);\n                Assert.Same(expectedCatchBlock, product.CatchBlock);\n                Assert.Same(expectedRequest, product.Request);\n                Assert.Same(expectedRequestContext, product.RequestContext);\n                Assert.Null(product.ControllerContext);\n                Assert.Null(product.ActionContext);\n                Assert.Null(product.Response);\n            }\n        }\n\n        [Fact]\n        public void ConstructorWithRequest_IfExceptionIsNull_Throws()\n        {\n            // Arrange\n            Exception exception = null;\n            ExceptionContextCatchBlock catchBlock = CreateCatchBlock();\n            HttpRequestContext requestContext = CreateRequestContext();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                request.SetRequestContext(requestContext);\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() => CreateProductUnderTest(exception, catchBlock, request), \"exception\");\n            }\n        }\n\n        [Fact]\n        public void ConstructorWithRequest_IfCatchBlockIsNull_Throws()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            ExceptionContextCatchBlock catchBlock = null;\n            HttpRequestContext requestContext = CreateRequestContext();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                request.SetRequestContext(requestContext);\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() => CreateProductUnderTest(exception, catchBlock, request), \"catchBlock\");\n            }\n        }\n\n        [Fact]\n        public void ConstructorWithRequest_IfRequestIsNull_Throws()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            ExceptionContextCatchBlock catchBlock = CreateCatchBlock();\n            HttpRequestMessage request = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => CreateProductUnderTest(exception, catchBlock, request), \"request\");\n        }\n\n        [Fact]\n        public void ConstructorWithRequest_IfRequestContextIsNull_IgnoresRequestContext()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            ExceptionContextCatchBlock catchBlock = CreateCatchBlock();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                Assert.Null(request.GetRequestContext()); // Guard\n\n                // Act\n                ExceptionContext product = CreateProductUnderTest(exception, catchBlock, request);\n\n                // Assert\n                Assert.Null(product.RequestContext);\n            }\n        }\n\n        [Fact]\n        public void ConstructorWithRequestAndResponse_SetsPropertiesToSpecifiedValues()\n        {\n            // Arrange\n            Exception expectedException = CreateException();\n            ExceptionContextCatchBlock expectedCatchBlock = CreateCatchBlock();\n            HttpRequestContext expectedRequestContext = CreateRequestContext();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            using (HttpResponseMessage expectedResponse = CreateResponse())\n            {\n                expectedRequest.SetRequestContext(expectedRequestContext);\n\n                // Act\n                ExceptionContext product = CreateProductUnderTest(expectedException, expectedCatchBlock,\n                    expectedRequest, expectedResponse);\n\n                // Assert\n                Assert.Same(expectedException, product.Exception);\n                Assert.Same(expectedCatchBlock, product.CatchBlock);\n                Assert.Same(expectedRequest, product.Request);\n                Assert.Same(expectedRequestContext, product.RequestContext);\n                Assert.Same(expectedResponse, product.Response);\n                Assert.Null(product.ControllerContext);\n                Assert.Null(product.ActionContext);\n            }\n        }\n\n        [Fact]\n        public void ConstructorWithRequestAndResponse_IfExceptionIsNull_Throws()\n        {\n            // Arrange\n            Exception exception = null;\n            ExceptionContextCatchBlock catchBlock = CreateCatchBlock();\n            HttpRequestContext requestContext = CreateRequestContext();\n\n            using (HttpRequestMessage request = CreateRequest())\n            using (HttpResponseMessage response = CreateResponse())\n            {\n                request.SetRequestContext(requestContext);\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() => CreateProductUnderTest(exception, catchBlock, request, response),\n                    \"exception\");\n            }\n        }\n\n        [Fact]\n        public void ConstructorWithRequestAndResponse_IfCatchBlockIsNull_Throws()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            ExceptionContextCatchBlock catchBlock = null;\n            HttpRequestContext requestContext = CreateRequestContext();\n\n            using (HttpRequestMessage request = CreateRequest())\n            using (HttpResponseMessage response = CreateResponse())\n            {\n                request.SetRequestContext(requestContext);\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() => CreateProductUnderTest(exception, catchBlock, request, response),\n                    \"catchBlock\");\n            }\n        }\n\n        [Fact]\n        public void ConstructorWithRequestAndResponse_IfRequestIsNull_Throws()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            ExceptionContextCatchBlock catchBlock = CreateCatchBlock();\n            HttpRequestMessage request = null;\n\n            using (HttpResponseMessage response = CreateResponse())\n            {\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() => CreateProductUnderTest(exception, catchBlock, request, response),\n                    \"request\");\n            }\n        }\n\n        [Fact]\n        public void ConstructorWithRequestAndResponse_IfRequestContextIsNull_IgnoresRequestContext()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            ExceptionContextCatchBlock catchBlock = CreateCatchBlock();\n\n            using (HttpRequestMessage request = CreateRequest())\n            using (HttpResponseMessage response = CreateResponse())\n            {\n                Assert.Null(request.GetRequestContext()); // Guard\n\n                // Act\n                ExceptionContext product = CreateProductUnderTest(exception, catchBlock, request, response);\n\n                // Assert\n                Assert.Null(product.RequestContext);\n            }\n        }\n\n        [Fact]\n        public void ConstructorWithRequestAndResponse_IfResponseIsNull_Throws()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            ExceptionContextCatchBlock catchBlock = CreateCatchBlock();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpResponseMessage response = null;\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() => CreateProductUnderTest(exception, catchBlock, request, response),\n                    \"response\");\n            }\n        }\n\n        private static HttpActionContext CreateActionContext()\n        {\n            return new HttpActionContext();\n        }\n\n        private static HttpActionContext CreateActionContext(HttpControllerContext controllerContext)\n        {\n            return new HttpActionContext\n            {\n                ControllerContext = controllerContext\n            };\n        }\n\n        private static ExceptionContextCatchBlock CreateCatchBlock()\n        {\n            return new ExceptionContextCatchBlock(\"IgnoreCaughtAt\", isTopLevel: false, callsHandler: false);\n        }\n\n        private static HttpControllerContext CreateControllerContext()\n        {\n            return new HttpControllerContext();\n        }\n\n        private static HttpControllerContext CreateControllerContext(HttpRequestContext requestContext,\n            HttpRequestMessage request)\n        {\n            return new HttpControllerContext\n            {\n                RequestContext = requestContext,\n                Request = request\n            };\n        }\n\n        private static Exception CreateException()\n        {\n            return new DivideByZeroException();\n        }\n\n        private static ExceptionContext CreateProductUnderTest()\n        {\n            return new ExceptionContext(CreateException(), CreateCatchBlock());\n        }\n\n        private static ExceptionContext CreateProductUnderTest(Exception exception,\n            ExceptionContextCatchBlock catchBlock, HttpActionContext actionContext)\n        {\n            return new ExceptionContext(exception, catchBlock, actionContext);\n        }\n\n        private static ExceptionContext CreateProductUnderTest(Exception exception,\n            ExceptionContextCatchBlock catchBlock, HttpRequestMessage request)\n        {\n            return new ExceptionContext(exception, catchBlock, request);\n        }\n\n        private static ExceptionContext CreateProductUnderTest(Exception exception,\n            ExceptionContextCatchBlock catchBlock, HttpRequestMessage request, HttpResponseMessage response)\n        {\n            return new ExceptionContext(exception, catchBlock, request, response);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private static HttpRequestContext CreateRequestContext()\n        {\n            return new HttpRequestContext();\n        }\n\n        private static HttpResponseMessage CreateResponse()\n        {\n            return new HttpResponseMessage();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ExceptionHandling/ExceptionHandlerContextTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    public class ExceptionHandlerContextTests\n    {\n        [Fact]\n        public void Constructor_IfExceptionContextIsNull_Throws()\n        {\n            // Arrange\n            ExceptionContext context = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => CreateProductUnderTest(context), \"exceptionContext\");\n        }\n\n        [Fact]\n        public void ExceptionContextGet_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            ExceptionContext expectedContext = CreateMinimalContext();\n            ExceptionHandlerContext product = CreateProductUnderTest(expectedContext);\n\n            // Act\n            ExceptionContext context = product.ExceptionContext;\n\n            // Assert\n            Assert.Same(expectedContext, context);\n        }\n\n        [Fact]\n        public void ResultSet_UpdatesValue()\n        {\n            // Arrange\n            ExceptionHandlerContext product = CreateProductUnderTest(CreateMinimalContext());\n            IHttpActionResult expectedResult = CreateDummyResult();\n\n            // Act\n            product.Result = expectedResult;\n\n            // Assert\n            IHttpActionResult result = product.Result;\n            Assert.Same(expectedResult, result);\n        }\n\n        [Fact]\n        public void ExceptionGet_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            Exception expectedException = new InvalidOperationException();\n            ExceptionContext context = new ExceptionContext(expectedException, ExceptionCatchBlocks.HttpServer);\n            ExceptionHandlerContext product = CreateProductUnderTest(context);\n\n            // Act\n            Exception exception = product.Exception;\n\n            // Assert\n            Assert.Same(expectedException, exception);\n        }\n\n        [Fact]\n        public void CatchBlockGet_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            ExceptionContextCatchBlock expectedCatchBlock = new ExceptionContextCatchBlock(\"IgnoreName\", false, false);\n            ExceptionContext context = new ExceptionContext(new Exception(), expectedCatchBlock);\n            ExceptionHandlerContext product = CreateProductUnderTest(context);\n\n            // Act\n            ExceptionContextCatchBlock catchBlock = product.CatchBlock;\n\n            // Assert\n            Assert.Same(expectedCatchBlock, catchBlock);\n        }\n\n        [Fact]\n        public void RequestGet_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            using (HttpRequestMessage expectedRequest = new HttpRequestMessage())\n            {\n                ExceptionContext context = CreateMinimalContext(expectedRequest);\n                ExceptionHandlerContext product = CreateProductUnderTest(context);\n\n                // Act\n                HttpRequestMessage request = product.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public void RequestContextGet_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            HttpRequestContext expectedRequestContext = new HttpRequestContext();\n            ExceptionContext context = CreateMinimalContext(expectedRequestContext);\n            ExceptionHandlerContext product = CreateProductUnderTest(context);\n\n            // Act\n            HttpRequestContext requestContext = product.RequestContext;\n\n            // Assert\n            Assert.Same(expectedRequestContext, requestContext);\n        }\n\n        private static ExceptionContext CreateMinimalContext(HttpRequestContext context = null)\n        {\n            return new ExceptionContext(new Exception(), ExceptionCatchBlocks.HttpServer)\n            {\n                RequestContext = context,\n            };\n        }\n\n        private static ExceptionContext CreateMinimalContext(HttpRequestMessage request)\n        {\n            return new ExceptionContext(new Exception(), ExceptionCatchBlocks.HttpServer, request);\n        }\n\n        private static IHttpActionResult CreateDummyResult()\n        {\n            return new Mock<IHttpActionResult>(MockBehavior.Strict).Object;\n        }\n\n        private static ExceptionHandlerContext CreateProductUnderTest(ExceptionContext exceptionContext)\n        {\n            return new ExceptionHandlerContext(exceptionContext);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ExceptionHandling/ExceptionHandlerExtensionsTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    public class ExceptionHandlerExtensionsTests\n    {\n        [Fact]\n        public async Task HandleAsync_CallsInterfaceHandleAsync()\n        {\n            // Arrange\n            Mock<IExceptionHandler> mock = CreateStubHandlerMock();\n            IExceptionHandler handler = mock.Object;\n\n            using (CancellationTokenSource tokenSource = CreateCancellationTokenSource())\n            {\n                ExceptionContext expectedContext = CreateMinimalValidContext();\n                CancellationToken expectedCancellationToken = tokenSource.Token;\n\n                // Act\n                await ExceptionHandlerExtensions.HandleAsync(handler, expectedContext,\n                    expectedCancellationToken);\n\n                // Assert\n                mock.Verify(h => h.HandleAsync(It.Is<ExceptionHandlerContext>(\n                    c => c.ExceptionContext == expectedContext), expectedCancellationToken), Times.Once());\n            }\n        }\n\n        [Fact]\n        public async Task HandleAsync_IfResultIsNotSet_ReturnsCompletedTaskWithNullResponse()\n        {\n            // Arrange\n            IExceptionHandler handler = CreateStubHandler();\n            ExceptionContext context = CreateMinimalValidContext();\n            CancellationToken cancellationToken = CancellationToken.None;\n\n            // Act\n            HttpResponseMessage response = await ExceptionHandlerExtensions.HandleAsync(handler, context, cancellationToken);\n\n            // Assert\n            Assert.Null(response);\n        }\n\n        [Fact]\n        public async Task HandleAsync_IfResultIsSet_CallsResultExecuteAsync()\n        {\n            // Arrange\n            using (HttpResponseMessage response = CreateResponse())\n            {\n                Mock<IHttpActionResult> mock = new Mock<IHttpActionResult>(MockBehavior.Strict);\n                mock.Setup(r => r.ExecuteAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult(response));\n                IHttpActionResult result = mock.Object;\n                IExceptionHandler handler = CreateResultHandler(result);\n\n                using (CancellationTokenSource tokenSource = CreateCancellationTokenSource())\n                {\n                    ExceptionContext context = CreateMinimalValidContext();\n                    CancellationToken expectedCancellationToken = tokenSource.Token;\n\n                    // Act\n                    await ExceptionHandlerExtensions.HandleAsync(handler, context,\n                        expectedCancellationToken);\n\n                    // Assert\n                    mock.Verify(h => h.ExecuteAsync(expectedCancellationToken), Times.Once());\n                }\n            }\n        }\n\n        [Fact]\n        public async Task HandleAsync_IfResultIsSet_ReturnsCompletedTaskWithResultResponse()\n        {\n            // Arrange\n            using (HttpResponseMessage expectedResponse = CreateResponse())\n            {\n                Mock<IHttpActionResult> mock = new Mock<IHttpActionResult>(MockBehavior.Strict);\n                mock.Setup(r => r.ExecuteAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult(expectedResponse));\n                IHttpActionResult result = mock.Object;\n                IExceptionHandler handler = CreateResultHandler(result);\n\n                ExceptionContext context = CreateMinimalValidContext();\n                CancellationToken cancellationToken = CancellationToken.None;\n\n                // Act\n                HttpResponseMessage response = await handler.HandleAsync(context, cancellationToken);\n\n                // Assert\n                Assert.Same(expectedResponse, response);\n            }\n        }\n\n        [Fact]\n        public void HandleAsync_IfHandlerIsNull_Throws()\n        {\n            // Arrange\n            IExceptionHandler handler = null;\n            ExceptionContext context = CreateMinimalValidContext();\n            CancellationToken cancellationToken = CancellationToken.None;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() =>\n                ExceptionHandlerExtensions.HandleAsync(handler, context, cancellationToken), \"handler\");\n        }\n\n        [Fact]\n        public void HandleAsync_IfContextIsNull_Throws()\n        {\n            // Arrange\n            IExceptionHandler handler = CreateDummyHandler();\n            ExceptionContext context = null;\n            CancellationToken cancellationToken = CancellationToken.None;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() =>\n                ExceptionHandlerExtensions.HandleAsync(handler, context, cancellationToken), \"context\");\n        }\n\n        [Fact]\n        public async Task HandleAsync_IfResultIsSetButReturnsNull_ReturnsFaultedTask()\n        {\n            // Arrange\n            Mock<IHttpActionResult> mock = new Mock<IHttpActionResult>(MockBehavior.Strict);\n            mock\n                .Setup(r => r.ExecuteAsync(It.IsAny<CancellationToken>()))\n                .Returns(Task.FromResult<HttpResponseMessage>(null));\n            IHttpActionResult result = mock.Object;\n            IExceptionHandler handler = CreateResultHandler(result);\n            ExceptionContext context = CreateMinimalValidContext();\n            CancellationToken cancellationToken = CancellationToken.None;\n\n            // Act & Assert\n            var exception = await Assert.ThrowsAsync<InvalidOperationException>(\n                () => ExceptionHandlerExtensions.HandleAsync(handler, context, cancellationToken));\n            Assert.Equal(\"IHttpActionResult.ExecuteAsync must not return null.\", exception.Message);\n        }\n\n        private static CancellationTokenSource CreateCancellationTokenSource()\n        {\n            return new CancellationTokenSource();\n        }\n\n        private static ExceptionContext CreateMinimalValidContext()\n        {\n            return new ExceptionContext(new Exception(), ExceptionCatchBlocks.HttpServer);\n        }\n\n        private static IExceptionHandler CreateDummyHandler()\n        {\n            return new Mock<IExceptionHandler>(MockBehavior.Strict).Object;\n        }\n\n        private static HttpResponseMessage CreateResponse()\n        {\n            return new HttpResponseMessage();\n        }\n\n        private static IExceptionHandler CreateResultHandler(IHttpActionResult result)\n        {\n            Mock<IExceptionHandler> mock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n            mock\n                .Setup(h => h.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                .Returns<ExceptionHandlerContext, CancellationToken>((c, i) =>\n                {\n                    c.Result = result;\n                    return Task.FromResult(0);\n                });\n            return mock.Object;\n        }\n\n        private static IExceptionHandler CreateStubHandler()\n        {\n            return CreateStubHandlerMock().Object;\n        }\n\n        private static Mock<IExceptionHandler> CreateStubHandlerMock()\n        {\n            Mock<IExceptionHandler> mock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n            mock\n                .Setup(h => h.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                .Returns(Task.FromResult(0));\n            return mock;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ExceptionHandling/ExceptionHandlerTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    public class ExceptionHandlerTests\n    {\n        [Fact]\n        public void HandleAsync_IfContextIsNull_Throws()\n        {\n            // Arrange\n            Mock<ExceptionHandler> mock = new Mock<ExceptionHandler> { CallBase = true };\n            IExceptionHandler product = mock.Object;\n\n            ExceptionHandlerContext context = null;\n            CancellationToken cancellationToken = CancellationToken.None;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => product.HandleAsync(context, cancellationToken), \"context\");\n        }\n\n        [Fact]\n        public void HandleAsync_IfShouldHandleReturnsTrue_DelegatesToHandleAsyncCore()\n        {\n            // Arrange\n            Mock<ExceptionHandler> mock = new Mock<ExceptionHandler> { CallBase = true };\n            Task expectedTask = CreateCompletedTask();\n            mock.Setup(h => h.ShouldHandle(It.IsAny<ExceptionHandlerContext>())).Returns(true);\n            mock\n                .Setup(h => h.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                .Returns(expectedTask);\n\n            IExceptionHandler product = mock.Object;\n\n            ExceptionHandlerContext expectedContext = CreateMinimalValidHandlerContext();\n\n            using (CancellationTokenSource tokenSource = CreateTokenSource())\n            {\n                CancellationToken expectedCancellationToken = tokenSource.Token;\n\n                // Act\n                Task task = product.HandleAsync(expectedContext, expectedCancellationToken);\n\n                // Assert\n                Assert.Same(expectedTask, task);\n                mock.Verify(h => h.ShouldHandle(expectedContext), Times.Once());\n                mock.Verify(h => h.HandleAsync(expectedContext, expectedCancellationToken), Times.Once());\n            }\n        }\n\n        [Fact]\n        public void HandleAsync_IfShouldHandleReturnsFalse_ReturnsCompletedTask()\n        {\n            // Arrange\n            Mock<ExceptionHandler> mock = new Mock<ExceptionHandler> { CallBase = true };\n            mock.Setup(h => h.ShouldHandle(It.IsAny<ExceptionHandlerContext>())).Returns(false);\n\n            IExceptionHandler product = mock.Object;\n\n            ExceptionHandlerContext expectedContext = CreateMinimalValidHandlerContext();\n            CancellationToken expectedCancellationToken = CancellationToken.None;\n\n            // Act\n            Task task = product.HandleAsync(expectedContext, expectedCancellationToken);\n\n            // Assert\n            Assert.NotNull(task);\n            Assert.True(task.IsCompleted);\n            Assert.Equal(TaskStatus.RanToCompletion, task.Status);\n            mock.Verify(h => h.ShouldHandle(expectedContext), Times.Once());\n            mock.Verify(h => h.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()),\n                Times.Never());\n        }\n\n        [Fact]\n        public async Task HandleAsyncCore_DelegatesToHandleCore_AndReturnsCompletedTask()\n        {\n            // Arrange\n            Mock<ExceptionHandler> mock = new Mock<ExceptionHandler>();\n            mock.CallBase = true;\n            ExceptionHandler product = mock.Object;\n\n            ExceptionHandlerContext expectedContext = CreateMinimalValidHandlerContext();\n            CancellationToken cancellationToken = CancellationToken.None;\n\n            // Act\n            await product.HandleAsync(expectedContext, cancellationToken);\n\n            // Assert\n            mock.Verify(h => h.Handle(expectedContext), Times.Once());\n        }\n\n        [Fact]\n        public void HandleCore_DoesNotThrow()\n        {\n            // Arrange\n            Mock<ExceptionHandler> mock = new Mock<ExceptionHandler>();\n            mock.CallBase = true;\n            ExceptionHandler product = mock.Object;\n\n            ExceptionHandlerContext context = CreateMinimalValidHandlerContext();\n\n            // Act & Assert\n            Assert.DoesNotThrow(() => product.Handle(context));\n        }\n\n        [Fact]\n        public void ShouldHandle_IfContextIsNull_Throws()\n        {\n            // Arrange\n            Mock<ExceptionHandler> mock = new Mock<ExceptionHandler>();\n            mock.CallBase = true;\n            ExceptionHandler product = mock.Object;\n\n            ExceptionHandlerContext context = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => product.ShouldHandle(context), \"context\");\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void ShouldHandle_ReturnsIsTopLevelCatchBlock(bool isTopLevelCatchBlock)\n        {\n            // Arrange\n            Mock<ExceptionHandler> mock = new Mock<ExceptionHandler>();\n            mock.CallBase = true;\n            ExceptionHandler product = mock.Object;\n\n            ExceptionHandlerContext context = CreateContext(new ExceptionContext(new Exception(),\n                new ExceptionContextCatchBlock(\"IgnoreCaughtAt\", isTopLevelCatchBlock, callsHandler: false)));\n\n            // Act\n            bool shouldHandle = product.ShouldHandle(context);\n\n            // Assert\n            Assert.Equal(isTopLevelCatchBlock, shouldHandle);\n        }\n\n        private static Task CreateCompletedTask()\n        {\n            TaskCompletionSource<object> source = new TaskCompletionSource<object>();\n            return source.Task;\n        }\n\n        private static ExceptionHandlerContext CreateContext(ExceptionContext exceptionContext)\n        {\n            return new ExceptionHandlerContext(exceptionContext);\n        }\n\n        private static ExceptionContext CreateMinimalValidExceptionContext()\n        {\n            return new ExceptionContext(new Exception(), ExceptionCatchBlocks.HttpServer);\n        }\n\n        private static CancellationTokenSource CreateTokenSource()\n        {\n            return new CancellationTokenSource();\n        }\n\n        private static ExceptionHandlerContext CreateMinimalValidHandlerContext()\n        {\n            return new ExceptionHandlerContext(CreateMinimalValidExceptionContext());\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ExceptionHandling/ExceptionLoggerContextTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    public class ExceptionLoggerContextTests\n    {\n        [Fact]\n        public void Constructor_IfExceptionContextIsNull_Throws()\n        {\n            // Arrange\n            ExceptionContext context = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => CreateProductUnderTest(context), \"exceptionContext\");\n        }\n\n        [Fact]\n        public void ExceptionContextGet_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            ExceptionContext expectedContext = CreateMinimalValidContext();\n            ExceptionLoggerContext product = CreateProductUnderTest(expectedContext);\n\n            // Act\n            ExceptionContext context = product.ExceptionContext;\n\n            // Assert\n            Assert.Same(expectedContext, context);\n        }\n\n        [Fact]\n        public void ExceptionGet_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            Exception expectedException = new InvalidOperationException();\n            ExceptionContext context = new ExceptionContext(expectedException, ExceptionCatchBlocks.HttpServer);\n            ExceptionLoggerContext product = CreateProductUnderTest(context);\n\n            // Act\n            Exception exception = product.Exception;\n\n            // Assert\n            Assert.Same(expectedException, exception);\n        }\n\n        [Fact]\n        public void CatchBlockGet_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            ExceptionContextCatchBlock expectedCatchBlock = new ExceptionContextCatchBlock(\"IgnoreName\", false, false);\n            ExceptionContext context = new ExceptionContext(new Exception(), expectedCatchBlock);\n            ExceptionLoggerContext product = CreateProductUnderTest(context);\n\n            // Act\n            ExceptionContextCatchBlock catchBlock = product.CatchBlock;\n\n            // Assert\n            Assert.Same(expectedCatchBlock, catchBlock);\n        }\n\n        [Fact]\n        public void RequestGet_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            using (HttpRequestMessage expectedRequest = new HttpRequestMessage())\n            {\n                ExceptionContext context = new ExceptionContext(new Exception(), ExceptionCatchBlocks.HttpServer, expectedRequest);\n\n                ExceptionLoggerContext product = CreateProductUnderTest(context);\n\n                // Act\n                HttpRequestMessage request = product.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public void RequestContextGet_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            HttpRequestContext expectedRequestContext = new HttpRequestContext();\n            ExceptionContext context = CreateMinimalValidContext(expectedRequestContext);\n            ExceptionLoggerContext product = CreateProductUnderTest(context);\n\n            // Act\n            HttpRequestContext requestContext = product.RequestContext;\n\n            // Assert\n            Assert.Same(expectedRequestContext, requestContext);\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void CallsHandlerGet_ReturnsCatchBlockCallsHandler(bool expectedCallsHandler)\n        {\n            // Arrange\n            ExceptionContext context = new ExceptionContext(new Exception(),\n                new ExceptionContextCatchBlock(\"IgnoreName\", isTopLevel: false,\n                    callsHandler: expectedCallsHandler));\n\n            ExceptionLoggerContext product = CreateProductUnderTest(context);\n\n            // Act\n            bool callsHandler = product.CallsHandler;\n\n            // Assert\n            Assert.Equal(expectedCallsHandler, callsHandler);\n        }\n\n        private static ExceptionContext CreateMinimalValidContext(HttpRequestContext context = null)\n        {\n            return new ExceptionContext(new Exception(), ExceptionCatchBlocks.HttpServer)\n            {\n                RequestContext = context,\n            };\n        }\n\n        private static ExceptionLoggerContext CreateProductUnderTest(ExceptionContext exceptionContext)\n        {\n            return new ExceptionLoggerContext(exceptionContext);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ExceptionHandling/ExceptionLoggerExtensionsTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    public class ExceptionLoggerExtensionsTests\n    {\n        [Fact]\n        public async Task LogAsync_DelegatesToInterfaceLogAsync()\n        {\n            // Arrange\n            Task expectedTask = CreateCompletedTask();\n            Mock<IExceptionLogger> mock = new Mock<IExceptionLogger>(MockBehavior.Strict);\n            mock\n                .Setup(h => h.LogAsync(It.IsAny<ExceptionLoggerContext>(), It.IsAny<CancellationToken>()))\n                .Returns(expectedTask);\n\n            IExceptionLogger logger = mock.Object;\n\n            using (CancellationTokenSource tokenSource = CreateCancellationTokenSource())\n            {\n                ExceptionContext expectedContext = CreateMinimalValidContext();\n                CancellationToken expectedCancellationToken = tokenSource.Token;\n\n                // Act\n                Task task = ExceptionLoggerExtensions.LogAsync(logger, expectedContext, expectedCancellationToken);\n\n                // Assert\n                Assert.Same(expectedTask, task);\n                await task;\n\n                mock.Verify(h => h.LogAsync(It.Is<ExceptionLoggerContext>(c => c.ExceptionContext == expectedContext),\n                    expectedCancellationToken), Times.Once());\n            }\n        }\n\n        [Fact]\n        public void LogAsync_IfLoggerIsNull_Throws()\n        {\n            // Arrange\n            IExceptionLogger logger = null;\n            ExceptionContext context = CreateMinimalValidContext();\n            CancellationToken cancellationToken = CancellationToken.None;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() =>\n                ExceptionLoggerExtensions.LogAsync(logger, context, cancellationToken), \"logger\");\n        }\n\n        [Fact]\n        public void LogAsync_IfContextIsNull_Throws()\n        {\n            // Arrange\n            IExceptionLogger logger = CreateDummyLogger();\n            ExceptionContext context = null;\n            CancellationToken cancellationToken = CancellationToken.None;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() =>\n                ExceptionLoggerExtensions.LogAsync(logger, context, cancellationToken), \"context\");\n        }\n\n        private static CancellationTokenSource CreateCancellationTokenSource()\n        {\n            return new CancellationTokenSource();\n        }\n\n        private static Task CreateCompletedTask()\n        {\n            TaskCompletionSource<object> source = new TaskCompletionSource<object>();\n            source.SetResult(null);\n            return source.Task;\n        }\n\n        private static ExceptionContext CreateMinimalValidContext()\n        {\n            return new ExceptionContext(new Exception(), ExceptionCatchBlocks.HttpServer);\n        }\n\n        private static IExceptionLogger CreateDummyLogger()\n        {\n            return new Mock<IExceptionLogger>(MockBehavior.Strict).Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ExceptionHandling/ExceptionLoggerTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    public class ExceptionLoggerTests\n    {\n        [Fact]\n        public void LogAsync_IfContextIsNull_Throws()\n        {\n            // Arrange\n            Mock<ExceptionLogger> mock = new Mock<ExceptionLogger> { CallBase = true };\n\n            IExceptionLogger product = mock.Object;\n\n            ExceptionLoggerContext context = null;\n            CancellationToken cancellationToken = CancellationToken.None;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => product.LogAsync(context, cancellationToken), \"context\");\n        }\n\n        [Fact]\n        public void LogAsync_IfShouldLogReturnsTrue_DelegatesToLogAsyncCore()\n        {\n            // Arrange\n            Mock<ExceptionLogger> mock = new Mock<ExceptionLogger> { CallBase = true };\n            Task expectedTask = CreateCompletedTask();\n            mock.Setup(h => h.ShouldLog(It.IsAny<ExceptionLoggerContext>())).Returns(true);\n            mock\n                .Setup(h => h.LogAsync(It.IsAny<ExceptionLoggerContext>(), It.IsAny<CancellationToken>()))\n                .Returns(expectedTask);\n\n            IExceptionLogger product = mock.Object;\n\n            ExceptionLoggerContext expectedContext = CreateMinimalValidLoggerContext();\n\n            using (CancellationTokenSource tokenSource = CreateTokenSource())\n            {\n                CancellationToken expectedCancellationToken = tokenSource.Token;\n\n                // Act\n                Task task = product.LogAsync(expectedContext, expectedCancellationToken);\n\n                // Assert\n                Assert.Same(expectedTask, task);\n                mock.Verify(h => h.ShouldLog(expectedContext), Times.Once());\n                mock.Verify(h => h.LogAsync(expectedContext, expectedCancellationToken), Times.Once());\n            }\n        }\n\n        [Fact]\n        public void LogAsync_IfShouldLogReturnsFalse_ReturnsCompletedTask()\n        {\n            // Arrange\n            Mock<ExceptionLogger> mock = new Mock<ExceptionLogger> { CallBase = true };\n            mock.Setup(h => h.ShouldLog(It.IsAny<ExceptionLoggerContext>())).Returns(false);\n\n            IExceptionLogger product = mock.Object;\n\n            ExceptionLoggerContext expectedContext = CreateMinimalValidLoggerContext();\n            CancellationToken expectedCancellationToken = CancellationToken.None;\n\n            // Act\n            Task task = product.LogAsync(expectedContext, expectedCancellationToken);\n\n            // Assert\n            Assert.NotNull(task);\n            Assert.True(task.IsCompleted);\n            Assert.Equal(TaskStatus.RanToCompletion, task.Status);\n            mock.Verify(h => h.ShouldLog(expectedContext), Times.Once());\n            mock.Verify(h => h.LogAsync(It.IsAny<ExceptionLoggerContext>(), It.IsAny<CancellationToken>()),\n                Times.Never());\n        }\n\n        [Fact]\n        public async Task LogAsyncCore_DelegatesToLogCore_AndReturnsCompletedTask()\n        {\n            // Arrange\n            Mock<ExceptionLogger> mock = new Mock<ExceptionLogger>();\n            mock.CallBase = true;\n            ExceptionLogger product = mock.Object;\n\n            ExceptionLoggerContext expectedContext = CreateMinimalValidLoggerContext();\n            CancellationToken cancellationToken = CancellationToken.None;\n\n            // Act\n            await product.LogAsync(expectedContext, cancellationToken);\n\n            // Assert\n            mock.Verify(h => h.Log(expectedContext), Times.Once());\n        }\n\n        [Fact]\n        public void LogCore_DoesNotThrow()\n        {\n            // Arrange\n            Mock<ExceptionLogger> mock = new Mock<ExceptionLogger>();\n            mock.CallBase = true;\n            ExceptionLogger product = mock.Object;\n\n            ExceptionLoggerContext context = CreateMinimalValidLoggerContext();\n\n            // Act & Assert\n            Assert.DoesNotThrow(() => product.Log(context));\n        }\n\n        [Fact]\n        public void ShouldLog_IfContextIsNull_Throws()\n        {\n            // Arrange\n            Mock<ExceptionLogger> mock = new Mock<ExceptionLogger>();\n            mock.CallBase = true;\n            ExceptionLogger product = mock.Object;\n\n            ExceptionLoggerContext context = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => product.ShouldLog(context), \"context\");\n        }\n\n        [Fact]\n        public void ShouldLog_IfExceptionDataIsNull_ReturnsTrue()\n        {\n            // Arrange\n            Mock<ExceptionLogger> mock = new Mock<ExceptionLogger>();\n            mock.CallBase = true;\n            ExceptionLogger product = mock.Object;\n\n            Exception exception = CreateException(data: null);\n            ExceptionLoggerContext context = CreateMinimalValidLoggerContext(exception);\n\n            // Act\n            bool shouldLog = product.ShouldLog(context);\n\n            // Assert\n            Assert.True(shouldLog);\n        }\n\n        [Fact]\n        public void LoggedByKey_IsSpecifiedValue()\n        {\n            // Act & Assert\n            Assert.Equal(\"MS_LoggedBy\", ExceptionLogger.LoggedByKey);\n        }\n\n        [Fact]\n        public void ShouldLog_IfExceptionDataIsReadOnly_ReturnsTrue()\n        {\n            // Arrange\n            Mock<ExceptionLogger> mock = new Mock<ExceptionLogger>();\n            mock.CallBase = true;\n            ExceptionLogger product = mock.Object;\n\n            Mock<IDictionary> dataMock = new Mock<IDictionary>(MockBehavior.Strict);\n            dataMock.Setup(d => d.IsReadOnly).Returns(true);\n            IDictionary data = dataMock.Object;\n            Exception exception = CreateException(data);\n            ExceptionLoggerContext context = CreateMinimalValidLoggerContext(exception);\n\n            // Act\n            bool shouldLog = product.ShouldLog(context);\n\n            // Assert\n            Assert.True(shouldLog);\n        }\n\n        [Fact]\n        public void ShouldLog_IfExceptionDataIsEmpty_AddsLoggedByKeyWithLoggerValueAndReturnsTrue()\n        {\n            // Arrange\n            Mock<ExceptionLogger> mock = new Mock<ExceptionLogger>();\n            mock.CallBase = true;\n            ExceptionLogger product = mock.Object;\n\n            IDictionary data = new Dictionary();\n            Exception exception = CreateException(data);\n            ExceptionLoggerContext context = CreateMinimalValidLoggerContext(exception);\n\n            // Act\n            bool shouldLog = product.ShouldLog(context);\n\n            // Assert\n            Assert.True(shouldLog);\n            Assert.True(data.Contains(ExceptionLogger.LoggedByKey));\n            object loggedBy = data[ExceptionLogger.LoggedByKey];\n            ICollection<object> loggedByCollection = Assert.IsAssignableFrom<ICollection<object>>(loggedBy);\n            Assert.Contains(product, loggedByCollection);\n        }\n\n        [Fact]\n        public void ShouldLog_IfExceptionDataHasEmptyLoggedBy_AddsLoggerAndReturnsTrue()\n        {\n            // Arrange\n            Mock<ExceptionLogger> mock = new Mock<ExceptionLogger>();\n            mock.CallBase = true;\n            ExceptionLogger product = mock.Object;\n\n            ICollection<object> loggedBy = new List<object>();\n            IDictionary data = new Dictionary();\n            data.Add(ExceptionLogger.LoggedByKey, loggedBy);\n            Exception exception = CreateException(data);\n            ExceptionLoggerContext context = CreateMinimalValidLoggerContext(exception);\n\n            // Act\n            bool shouldLog = product.ShouldLog(context);\n\n            // Assert\n            Assert.True(shouldLog);\n            Assert.True(data.Contains(ExceptionLogger.LoggedByKey));\n            object updatedLoggedBy = data[ExceptionLogger.LoggedByKey];\n            Assert.Same(loggedBy, updatedLoggedBy);\n            Assert.Contains(product, loggedBy);\n        }\n\n        [Fact]\n        public void ShouldLog_IfExceptionDataContainsLoggedByLogger_ReturnsFalse()\n        {\n            // Arrange\n            Mock<ExceptionLogger> mock = new Mock<ExceptionLogger>();\n            mock.CallBase = true;\n            ExceptionLogger product = mock.Object;\n\n            IDictionary data = new Dictionary();\n            ICollection<object> loggedBy = new List<object>() { product };\n            data.Add(ExceptionLogger.LoggedByKey, loggedBy);\n            Exception exception = CreateException(data);\n            ExceptionLoggerContext context = CreateMinimalValidLoggerContext(exception);\n\n            // Act\n            bool shouldLog = product.ShouldLog(context);\n\n            // Assert\n            Assert.False(shouldLog);\n            Assert.True(data.Contains(ExceptionLogger.LoggedByKey));\n            object updatedLoggedBy = data[ExceptionLogger.LoggedByKey];\n            Assert.Same(loggedBy, updatedLoggedBy);\n            Assert.Equal(1, loggedBy.Count);\n        }\n\n        [Fact]\n        public void ShouldLog_IfExceptionDataContainsLoggedByOfIncompatibleType_ReturnsTrue()\n        {\n            // Arrange\n            Mock<ExceptionLogger> mock = new Mock<ExceptionLogger>();\n            mock.CallBase = true;\n            ExceptionLogger product = mock.Object;\n\n            IDictionary data = new Dictionary();\n            data.Add(ExceptionLogger.LoggedByKey, null);\n            Exception exception = CreateException(data);\n            ExceptionLoggerContext context = CreateMinimalValidLoggerContext(exception);\n\n            // Act\n            bool shouldLog = product.ShouldLog(context);\n\n            // Assert\n            Assert.True(shouldLog);\n            Assert.True(data.Contains(ExceptionLogger.LoggedByKey));\n            object updatedLoggedBy = data[ExceptionLogger.LoggedByKey];\n            Assert.Null(updatedLoggedBy);\n        }\n\n        private static Task CreateCompletedTask()\n        {\n            TaskCompletionSource<object> source = new TaskCompletionSource<object>();\n            return source.Task;\n        }\n\n        private static ExceptionLoggerContext CreateContext(ExceptionContext exceptionContext)\n        {\n            return new ExceptionLoggerContext(exceptionContext);\n        }\n\n        private static Exception CreateException(IDictionary data)\n        {\n            Mock<Exception> mock = new Mock<Exception>();\n            mock.Setup(e => e.Data).Returns(data);\n            return mock.Object;\n        }\n\n        private static ExceptionContext CreateMinimalValidExceptionContext()\n        {\n            return new ExceptionContext(new Exception(), ExceptionCatchBlocks.HttpServer);\n        }\n\n        private static CancellationTokenSource CreateTokenSource()\n        {\n            return new CancellationTokenSource();\n        }\n\n        private static ExceptionLoggerContext CreateMinimalValidLoggerContext()\n        {\n            return CreateMinimalValidLoggerContext(new Exception());\n        }\n\n        private static ExceptionLoggerContext CreateMinimalValidLoggerContext(Exception exception)\n        {\n            return CreateContext(new ExceptionContext(exception, ExceptionCatchBlocks.HttpServer));\n        }\n\n        private class Dictionary : DictionaryBase\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ExceptionHandling/ExceptionServicesTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http.Controllers;\nusing Microsoft.TestCommon;\nusing Moq;\nusing Moq.Protected;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    public class ExceptionServicesTests\n    {\n        [Fact]\n        public void GetLoggerWithServices_ReturnsCompositeExceptionLoggerWithServicesLoggers()\n        {\n            // Arrange\n            IExceptionLogger expectedLogger = CreateDummyLogger();\n\n            using (ServicesContainer services = CreateServices(expectedLogger))\n            {\n                // Act\n                IExceptionLogger logger = ExceptionServices.GetLogger(services);\n\n                // Assert\n                IEnumerable<IExceptionLogger> loggers = Assert.IsType<CompositeExceptionLogger>(logger).Loggers;\n                IExceptionLogger actualLogger = Assert.Single(loggers);\n                Assert.Same(expectedLogger, actualLogger);\n            }\n        }\n\n        [Fact]\n        public void GetLoggerWithServices_ReturnsSameInstance()\n        {\n            // Arrange\n            IExceptionLogger innerLogger = CreateDummyLogger();\n\n            using (ServicesContainer services = CreateServices(innerLogger))\n            {\n                IExceptionLogger firstLogger = ExceptionServices.GetLogger(services);\n\n                // Act\n                IExceptionLogger secondLogger = ExceptionServices.GetLogger(services);\n\n                // Assert\n                Assert.Same(firstLogger, secondLogger);\n            }\n        }\n\n        [Fact]\n        public void GetLoggerWithServices_IfServicesIsNull_Throws()\n        {\n            // Arrange\n            ServicesContainer services = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => ExceptionServices.GetLogger(services), \"services\");\n        }\n\n        [Fact]\n        public void GetLoggerWithConfiguration_ReturnsCompositeExceptionLoggerWithServicesLoggers()\n        {\n            // Arrange\n            IExceptionLogger expectedLogger = CreateDummyLogger();\n\n            using (HttpConfiguration configuration = CreateConfiguration(expectedLogger))\n            {\n                // Act\n                IExceptionLogger logger = ExceptionServices.GetLogger(configuration);\n\n                // Assert\n                IEnumerable<IExceptionLogger> loggers = Assert.IsType<CompositeExceptionLogger>(logger).Loggers;\n                IExceptionLogger actualLogger = Assert.Single(loggers);\n                Assert.Same(expectedLogger, actualLogger);\n            }\n        }\n\n        [Fact]\n        public void GetLoggerWithConfiguration_IfConfigurationIsNull_Throws()\n        {\n            // Arrange\n            HttpConfiguration configuration = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => ExceptionServices.GetLogger(configuration), \"configuration\");\n        }\n\n        [Fact]\n        public void GetHandlerWithServices_ReturnsLastChanceHandlerWithServicesInnerHandler()\n        {\n            // Arrange\n            IExceptionHandler expectedHandler = CreateDummyHandler();\n\n            using (ServicesContainer services = CreateServices(expectedHandler))\n            {\n                // Act\n                IExceptionHandler handler = ExceptionServices.GetHandler(services);\n\n                // Assert\n                IExceptionHandler innerHandler = Assert.IsType<LastChanceExceptionHandler>(handler).InnerHandler;\n                Assert.Same(expectedHandler, innerHandler);\n            }\n        }\n\n        [Fact]\n        public void GetHandlerWithServices_ReturnsSameInstance()\n        {\n            // Arrange\n            IExceptionHandler innerHandler = CreateDummyHandler();\n\n            using (ServicesContainer services = CreateServices(innerHandler))\n            {\n                IExceptionHandler firstHandler = ExceptionServices.GetHandler(services);\n\n                // Act\n                IExceptionHandler secondHandler = ExceptionServices.GetHandler(services);\n\n                // Assert\n                Assert.Same(firstHandler, secondHandler);\n            }\n        }\n\n        [Fact]\n        public void GetHandlerWithServices_IfHandlerIsAbsent_ReturnsLastChanceHandlerWithEmptyInnerHandler()\n        {\n            // Arrange\n            IExceptionHandler servicesHandler = null;\n\n            using (ServicesContainer services = CreateServices(servicesHandler))\n            {\n                // Act\n                IExceptionHandler handler = ExceptionServices.GetHandler(services);\n\n                // Assert\n                IExceptionHandler innerHandler = Assert.IsType<LastChanceExceptionHandler>(handler).InnerHandler;\n                Assert.IsType<EmptyExceptionHandler>(innerHandler);\n            }\n        }\n\n        [Fact]\n        public void GetHandlerWithServices_IfServicesIsNull_Throws()\n        {\n            // Arrange\n            ServicesContainer services = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => ExceptionServices.GetHandler(services), \"services\");\n        }\n\n        [Fact]\n        public void GetHandlerWithConfiguration_ReturnsLastChanceHandlerWithServicesInnerHandler()\n        {\n            // Arrange\n            IExceptionHandler expectedHandler = CreateDummyHandler();\n\n            using (HttpConfiguration configuration = CreateConfiguration(expectedHandler))\n            {\n                // Act\n                IExceptionHandler handler = ExceptionServices.GetHandler(configuration);\n\n                // Assert\n                IExceptionHandler innerHandler = Assert.IsType<LastChanceExceptionHandler>(handler).InnerHandler;\n                Assert.Same(expectedHandler, innerHandler);\n            }\n        }\n\n        [Fact]\n        public void GetHandlerWithConfiguration_IfConfigurationIsNull_Throws()\n        {\n            // Arrange\n            HttpConfiguration configuration = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => ExceptionServices.GetHandler(configuration), \"configuration\");\n        }\n\n        private static HttpConfiguration CreateConfiguration(IExceptionHandler handler)\n        {\n            HttpConfiguration configuration = new HttpConfiguration();\n            configuration.Services.Replace(typeof(IExceptionHandler), handler);\n            return configuration;\n        }\n\n        private static HttpConfiguration CreateConfiguration(params IExceptionLogger[] loggers)\n        {\n            HttpConfiguration configuration = new HttpConfiguration();\n            configuration.Services.ReplaceRange(typeof(IExceptionLogger), loggers);\n            return configuration;\n        }\n\n        private static IExceptionHandler CreateDummyHandler()\n        {\n            return new Mock<IExceptionHandler>(MockBehavior.Strict).Object;\n        }\n\n        private static IExceptionLogger CreateDummyLogger()\n        {\n            return new Mock<IExceptionLogger>(MockBehavior.Strict).Object;\n        }\n\n        private static ServicesContainer CreateServices(IExceptionHandler handler)\n        {\n            Mock<ServicesContainer> mock = new Mock<ServicesContainer>(MockBehavior.Strict);\n            mock.Setup(s => s.GetService(typeof(IExceptionHandler))).Returns(handler);\n            LastChanceExceptionHandler cached = null;\n            mock.Setup(s => s.GetService(typeof(LastChanceExceptionHandler))).Returns(() => cached);\n            mock.Protected()\n                .Setup(\"ReplaceSingle\", typeof(LastChanceExceptionHandler), ItExpr.IsAny<object>())\n                .Callback<Type, object>((i, o) => cached = (LastChanceExceptionHandler)o);\n            mock.Setup(s => s.IsSingleService(typeof(LastChanceExceptionHandler))).Returns(true);\n            mock.Protected().Setup(\"ResetCache\", typeof(LastChanceExceptionHandler));\n            mock.Setup(s => s.Dispose());\n            return mock.Object;\n        }\n\n        private static ServicesContainer CreateServices(params IExceptionLogger[] loggers)\n        {\n            Mock<ServicesContainer> mock = new Mock<ServicesContainer>(MockBehavior.Strict);\n            mock.Setup(s => s.GetServices(typeof(IExceptionLogger))).Returns(loggers);\n            CompositeExceptionLogger cached = null;\n            mock.Setup(s => s.GetService(typeof(CompositeExceptionLogger))).Returns(() => cached);\n            mock.Protected()\n                .Setup(\"ReplaceSingle\", typeof(CompositeExceptionLogger), ItExpr.IsAny<object>())\n                .Callback<Type, object>((i, o) => cached = (CompositeExceptionLogger)o);\n            mock.Setup(s => s.IsSingleService(typeof(CompositeExceptionLogger))).Returns(true);\n            mock.Protected().Setup(\"ResetCache\", typeof(CompositeExceptionLogger));\n            mock.Setup(s => s.Dispose());\n            return mock.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ExceptionHandling/LastChanceExceptionHandlerTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Results;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.ExceptionHandling\n{\n    public class LastChanceExceptionHandlerTests\n    {\n        [Fact]\n        public void Constructor_IfInnerHandlerIsNull_Throws()\n        {\n            // Arrange\n            IExceptionHandler innerHandler = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => CreateProductUnderTest(innerHandler), \"innerHandler\");\n        }\n\n        [Fact]\n        public void InnerHandler_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            IExceptionHandler expectedInnerHandler = CreateDummyHandler();\n            LastChanceExceptionHandler product = CreateProductUnderTest(expectedInnerHandler);\n\n            // Act\n            IExceptionHandler innerHandler = product.InnerHandler;\n\n            // Assert\n            Assert.Same(expectedInnerHandler, innerHandler);\n        }\n\n        [Fact]\n        public async Task HandleAsync_DelegatesToInnerHandler()\n        {\n            Mock<IExceptionHandler> mock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n            Task expectedTask = CreateCompletedTask();\n            mock\n                .Setup(h => h.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                .Returns(expectedTask);\n            IExceptionHandler innerHander = mock.Object;\n\n            IExceptionHandler product = CreateProductUnderTest(innerHander);\n\n            ExceptionHandlerContext expectedContext = CreateContext();\n\n            using (CancellationTokenSource tokenSource = CreateCancellationTokenSource())\n            {\n                CancellationToken expectedCancellationToken = tokenSource.Token;\n\n                // Act\n                Task task = product.HandleAsync(expectedContext, expectedCancellationToken);\n\n                // Assert\n                Assert.Same(expectedTask, task);\n                await task;\n                mock.Verify(h => h.HandleAsync(expectedContext, expectedCancellationToken), Times.Once());\n            }\n        }\n\n        [Theory]\n        [InlineData(false)]\n        [InlineData(true)]\n        public async Task HandleAsync_IfIsTopLevelCatchBlockAndCanCreateExceptionResult_InitializesResult(bool includeDetail)\n        {\n            Mock<IExceptionHandler> mock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n            IHttpActionResult result = null;\n            mock\n                .Setup(h => h.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                .Returns<ExceptionHandlerContext, CancellationToken>((c, i) =>\n                {\n                    result = c != null ? c.Result : null;\n                    return Task.FromResult(0);\n                });\n            IExceptionHandler innerHander = mock.Object;\n\n            IExceptionHandler product = CreateProductUnderTest(innerHander);\n\n            Exception expectedException = CreateDummyException();\n            IContentNegotiator expectedContentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                configuration.Services.Replace(typeof(IContentNegotiator), expectedContentNegotiator);\n                configuration.Formatters.Clear();\n                MediaTypeFormatter expectedFormatter = CreateDummyFormatter();\n                configuration.Formatters.Add(expectedFormatter);\n\n                ExceptionHandlerContext context = new ExceptionHandlerContext(new ExceptionContext(\n                    exception: expectedException,\n                    catchBlock: CreateTopLevelCatchBlock(),\n                    request: expectedRequest)\n                {\n                    RequestContext = new HttpRequestContext\n                                    {\n                                        Configuration = configuration,\n                                        IncludeErrorDetail = includeDetail\n                                    },\n                });\n\n                CancellationToken cancellationToken = CancellationToken.None;\n\n                // Act\n                await product.HandleAsync(context, cancellationToken);\n\n                // Assert\n                ExceptionResult exceptionResult = Assert.IsType<ExceptionResult>(result);\n                Assert.Same(expectedException, exceptionResult.Exception);\n                Assert.Equal(includeDetail, exceptionResult.IncludeErrorDetail);\n                Assert.Same(expectedContentNegotiator, exceptionResult.ContentNegotiator);\n                Assert.Same(expectedRequest, exceptionResult.Request);\n                Assert.NotNull(exceptionResult.Formatters);\n                MediaTypeFormatter formatter = Assert.Single(exceptionResult.Formatters);\n                Assert.Same(expectedFormatter, formatter);\n            }\n        }\n\n        [Fact]\n        public async Task HandleAsync_IfNotIsTopLevelCatchBlock_LeavesResultNull()\n        {\n            // Arrange\n            Exception exception = CreateDummyException();\n\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                ExceptionContext context = new ExceptionContext(\n                    exception,\n                    CreateNonTopLevelCatchBlock(),\n                    request)\n                    {\n                        RequestContext = new HttpRequestContext\n                                        {\n                                            Configuration = configuration\n                                        },\n                    };\n\n                // More Arrange; then Act & Assert\n                await TestHandleAsyncLeavesResultNull(context);\n            }\n        }\n\n        [Fact]\n        public Task HandleAsync_IfContextIsNull_LeavesResultNull()\n        {\n            // Arrange\n            ExceptionHandlerContext context = null;\n\n            // More Arrange; then Act & Assert\n            return TestHandleAsyncLeavesResultNull(context);\n        }\n\n        [Fact]\n        public async Task HandleAsync_IfRequestIsNull_LeavesResultNull()\n        {\n            // Arrange\n            Exception exception = CreateDummyException();\n\n            using (HttpConfiguration configuration = CreateConfiguration())\n            {\n                ExceptionContext context = new ExceptionContext(\n                    exception,\n                    CreateTopLevelCatchBlock())\n                {\n                    RequestContext = new HttpRequestContext\n                    {\n                        Configuration = configuration\n                    },\n                    Request = null\n                };\n\n                // More Arrange; then Act & Assert\n                await TestHandleAsyncLeavesResultNull(context);\n            }\n        }\n\n        [Fact]\n        public async Task HandleAsync_IfRequestContextIsNull_LeavesResultNull()\n        {\n            // Arrange\n            Exception exception = CreateDummyException();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                ExceptionContext context = new ExceptionContext(\n                    exception,\n                    CreateTopLevelCatchBlock())\n                {\n                    RequestContext = null,\n                    Request = request\n                };\n\n                // More Arrange; then Act & Assert\n                await TestHandleAsyncLeavesResultNull(context);\n            }\n        }\n\n        [Fact]\n        public async Task HandleAsync_IfConfigurationIsNull_LeavesResultNull()\n        {\n            // Arrange\n            Exception exception = CreateDummyException();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                ExceptionContext context = new ExceptionContext(\n                    exception,\n                    CreateTopLevelCatchBlock())\n                {\n                    RequestContext = new HttpRequestContext\n                    {\n                        Configuration = null\n                    },\n                    Request = request\n                };\n\n                // More Arrange; then Act & Assert\n                await TestHandleAsyncLeavesResultNull(context);\n            }\n        }\n\n        [Fact]\n        public async Task HandleAsync_IfContentNegotiatorIsNull_LeavesResultNull()\n        {\n            // Arrange\n            Exception exception = CreateDummyException();\n\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                configuration.Services.Clear(typeof(IContentNegotiator));\n\n                ExceptionContext context = new ExceptionContext(\n                    exception,\n                    CreateTopLevelCatchBlock())\n                {\n                    RequestContext = new HttpRequestContext\n                    {\n                        Configuration = configuration\n                    },\n                    Request = request\n                };\n\n                // More Arrange; then Act & Assert\n                await TestHandleAsyncLeavesResultNull(context);\n            }\n        }\n\n        private static Task TestHandleAsyncLeavesResultNull(ExceptionContext context)\n        {\n            return TestHandleAsyncLeavesResultNull(new ExceptionHandlerContext(context));\n        }\n\n        private static async Task TestHandleAsyncLeavesResultNull(ExceptionHandlerContext context)\n        {\n            Mock<IExceptionHandler> mock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n            IHttpActionResult result = null;\n            mock\n                .Setup(h => h.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                .Returns<ExceptionHandlerContext, CancellationToken>((c, i) =>\n                {\n                    result = c != null ? c.Result : null;\n                    return Task.FromResult(0);\n                });\n            IExceptionHandler innerHander = mock.Object;\n\n            IExceptionHandler product = CreateProductUnderTest(innerHander);\n\n            CancellationToken cancellationToken = CancellationToken.None;\n\n            // Act\n            await product.HandleAsync(context, cancellationToken);\n\n            // Assert\n            Assert.Null(result);\n        }\n\n        private static CancellationTokenSource CreateCancellationTokenSource()\n        {\n            return new CancellationTokenSource();\n        }\n\n        private static Task CreateCompletedTask()\n        {\n            TaskCompletionSource<object> source = new TaskCompletionSource<object>();\n            source.SetResult(null);\n            return source.Task;\n        }\n\n        private static HttpConfiguration CreateConfiguration()\n        {\n            return new HttpConfiguration();\n        }\n\n        private static ExceptionHandlerContext CreateContext()\n        {\n            return new ExceptionHandlerContext(CreateMinimalValidExceptionContext());\n        }\n\n        private static ExceptionContext CreateMinimalValidExceptionContext()\n        {\n            return new ExceptionContext(new Exception(), ExceptionCatchBlocks.HttpServer);\n        }\n\n        private static ExceptionHandlerContext CreateContext(ExceptionContext exceptionContext)\n        {\n            return new ExceptionHandlerContext(exceptionContext);\n        }\n\n        private static IContentNegotiator CreateDummyContentNegotiator()\n        {\n            return new Mock<IContentNegotiator>(MockBehavior.Strict).Object;\n        }\n\n        private static Exception CreateDummyException()\n        {\n            return new Mock<Exception>(MockBehavior.Strict).Object;\n        }\n\n        private static MediaTypeFormatter CreateDummyFormatter()\n        {\n            return new Mock<MediaTypeFormatter>(MockBehavior.Strict).Object;\n        }\n\n        private static IExceptionHandler CreateDummyHandler()\n        {\n            return new Mock<IExceptionHandler>(MockBehavior.Strict).Object;\n        }\n\n        private static ExceptionContextCatchBlock CreateNonTopLevelCatchBlock()\n        {\n            return new ExceptionContextCatchBlock(\"IgnoreCaughtAt\", isTopLevel: false, callsHandler: false);\n        }\n\n        private static LastChanceExceptionHandler CreateProductUnderTest(IExceptionHandler innerHandler)\n        {\n            return new LastChanceExceptionHandler(innerHandler);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private static ExceptionContextCatchBlock CreateTopLevelCatchBlock()\n        {\n            return new ExceptionContextCatchBlock(\"IgnoreCaughtAt\", isTopLevel: true, callsHandler: false);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Filters/ActionDescriptorFilterProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Web.Http.Controllers;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Filters\n{\n    public class ActionDescriptorFilterProviderTest\n    {\n        private readonly ActionDescriptorFilterProvider _provider = new ActionDescriptorFilterProvider();\n        private static readonly HttpConfiguration _configuration = new HttpConfiguration();\n\n        [Fact]\n        public void GetFilters_IfConfigurationParameterIsNull_ThrowsException()\n        {\n            Assert.ThrowsArgumentNull(() =>\n            {\n                _provider.GetFilters(configuration: null, actionDescriptor: new Mock<HttpActionDescriptor>().Object);\n            }, \"configuration\");\n        }\n\n        [Fact]\n        public void GetFilters_IfActionDescriptorParameterIsNull_ThrowsException()\n        {\n            Assert.ThrowsArgumentNull(() =>\n            {\n                _provider.GetFilters(_configuration, actionDescriptor: null);\n            }, \"actionDescriptor\");\n        }\n\n        [Fact]\n        public void GetFilters_GetsFilterObjectsFromActionDescriptorAndItsControllerDescriptor()\n        {\n            // Arrange\n            Mock<HttpActionDescriptor> adMock = new Mock<HttpActionDescriptor>();\n            IFilter filter1 = new Mock<IFilter>().Object;\n            IFilter filter2 = new Mock<IFilter>().Object;\n            IFilter filter3 = new Mock<IFilter>().Object;\n            adMock.Setup(ad => ad.GetFilters()).Returns(new Collection<IFilter>(new[] { filter1, filter2 })).Verifiable();\n\n            Mock<HttpControllerDescriptor> cdMock = new Mock<HttpControllerDescriptor>();\n            cdMock.Setup(cd => cd.GetFilters()).Returns(new Collection<IFilter>(new[] { filter3 })).Verifiable();\n\n            HttpActionDescriptor actionDescriptor = adMock.Object;\n            actionDescriptor.ControllerDescriptor = cdMock.Object;\n\n            // Act\n            var result = _provider.GetFilters(_configuration, actionDescriptor).ToList();\n\n            // Assert\n            adMock.Verify();\n            cdMock.Verify();\n            Assert.Equal(3, result.Count);\n            Assert.Equal(new FilterInfo(filter3, FilterScope.Controller), result[0], new TestFilterInfoComparer());\n            Assert.Equal(new FilterInfo(filter1, FilterScope.Action), result[1], new TestFilterInfoComparer());\n            Assert.Equal(new FilterInfo(filter2, FilterScope.Action), result[2], new TestFilterInfoComparer());\n        }\n\n        public class TestFilterInfoComparer : IEqualityComparer<FilterInfo>\n        {\n            public bool Equals(FilterInfo x, FilterInfo y)\n            {\n                return (x == null && y == null) || (Object.ReferenceEquals(x.Instance, y.Instance) && x.Scope == y.Scope);\n            }\n\n            public int GetHashCode(FilterInfo obj)\n            {\n                return obj.GetHashCode();\n            }\n        }\n\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Filters/ActionFilterAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Filters\n{\n    public class ActionFilterAttributeTest\n    {\n        [Fact]\n        public void AllowsMultiple_DefaultReturnsTrue()\n        {\n            ActionFilterAttribute actionFilter = new TestableActionFilter();\n\n            Assert.True(actionFilter.AllowMultiple);\n        }\n\n        [Fact]\n        public void ExecuteActionFilterAsync_IfContextParameterIsNull_ThrowsException()\n        {\n            var filter = new TestableActionFilter() as IActionFilter;\n            Assert.ThrowsArgumentNull(() =>\n            {\n                filter.ExecuteActionFilterAsync(actionContext: null, cancellationToken: CancellationToken.None, continuation: () => null);\n            }, \"actionContext\");\n        }\n\n        [Fact]\n        public void ExecuteActionFilterAsync_IfContinuationParameterIsNull_ThrowsException()\n        {\n            var filter = new TestableActionFilter() as IActionFilter;\n            Assert.ThrowsArgumentNull(() =>\n            {\n                filter.ExecuteActionFilterAsync(actionContext: ContextUtil.CreateActionContext(), cancellationToken: CancellationToken.None, continuation: null);\n            }, \"continuation\");\n        }\n\n        [Fact]\n        public async Task ExecuteActionFilterAsync_InvokesOnActionExecutingBeforeContinuation()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            Mock<ActionFilterAttribute> filterMock = new Mock<ActionFilterAttribute>() { CallBase = true };\n            bool onActionExecutingInvoked = false;\n            filterMock.Setup(f => f.OnActionExecuting(It.IsAny<HttpActionContext>())).Callback(() =>\n            {\n                onActionExecutingInvoked = true;\n            });\n            bool? flagWhenContinuationInvoked = null;\n            Func<Task<HttpResponseMessage>> continuation = () =>\n            {\n                flagWhenContinuationInvoked = onActionExecutingInvoked;\n                return Task.FromResult(new HttpResponseMessage());\n            };\n            var filter = (IActionFilter)filterMock.Object;\n\n            // Act\n            await filter.ExecuteActionFilterAsync(context, CancellationToken.None, continuation);\n            // Assert\n            Assert.True(flagWhenContinuationInvoked.Value);\n        }\n\n        [Fact]\n        public async Task ExecuteActionFilterAsync_OnActionExecutingMethodGetsPassedControllerContext()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            Mock<ActionFilterAttribute> filterMock = new Mock<ActionFilterAttribute>() { CallBase = true };\n            var filter = (IActionFilter)filterMock.Object;\n\n            // Act\n            await filter.ExecuteActionFilterAsync(context, CancellationToken.None, () =>\n            {\n                return Task.FromResult(new HttpResponseMessage());\n            });\n\n            // Assert\n            filterMock.Verify(f => f.OnActionExecuting(context));\n        }\n\n        [Fact]\n        public async Task ExecuteActionFilterAsync_IfOnActionExecutingThrowsException_ReturnsFaultedTask()\n        {\n            // Arrange\n            Exception expectedException = new Exception(\"{51C81EE9-F8D2-4F63-A1F8-B56052E0F2A4}\");\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            Mock<ActionFilterAttribute> filterMock = new Mock<ActionFilterAttribute>()\n            {\n                CallBase = true,\n            };\n\n            filterMock.Setup(f => f.OnActionExecuting(It.IsAny<HttpActionContext>())).Throws(expectedException);\n            var filter = (IActionFilter)filterMock.Object;\n            bool continuationCalled = false;\n\n            // Act\n            var exception = await Assert.ThrowsAsync<Exception>(\n                () => filter.ExecuteActionFilterAsync(context, CancellationToken.None, () =>\n                {\n                    continuationCalled = true;\n                    return null;\n                }));\n\n            // Assert\n            Assert.Same(expectedException, exception);\n            Assert.False(continuationCalled);\n        }\n\n        [Fact]\n        public async Task ExecuteActionFilterAsync_IfOnActionExecutingSetsResult_ShortCircuits()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            Mock<ActionFilterAttribute> filterMock = new Mock<ActionFilterAttribute>()\n            {\n                CallBase = true,\n            };\n\n            HttpResponseMessage response = new HttpResponseMessage();\n            filterMock.Setup(f => f.OnActionExecuting(It.IsAny<HttpActionContext>())).Callback<HttpActionContext>(c =>\n            {\n                c.Response = response;\n            });\n            bool continuationCalled = false;\n            var filter = (IActionFilter)filterMock.Object;\n\n            // Act\n            var result = await filter.ExecuteActionFilterAsync(context, CancellationToken.None, () =>\n            {\n                continuationCalled = true;\n                return null;\n            });\n\n            // Assert\n            Assert.False(continuationCalled);\n            Assert.Same(response, result);\n        }\n\n        [Fact]\n        public Task ExecuteActionFilterAsync_IfContinuationTaskWasCanceled_ReturnsCanceledTask()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            Mock<ActionFilterAttribute> filterMock = new Mock<ActionFilterAttribute>()\n            {\n                CallBase = true,\n            };\n\n            var filter = (IActionFilter)filterMock.Object;\n\n            // Act & Assert\n            return Assert.ThrowsAsync<TaskCanceledException>(\n                () =>filter.ExecuteActionFilterAsync(context, CancellationToken.None, () => TaskHelpers.Canceled<HttpResponseMessage>()));\n        }\n\n        [Fact]\n        public async Task ExecuteActionFilterAsync_IfContinuationSucceeded_InvokesOnActionExecutedAsSuccess()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            Mock<ActionFilterAttribute> filterMock = new Mock<ActionFilterAttribute>()\n            {\n                CallBase = true,\n            };\n\n            var filter = (IActionFilter)filterMock.Object;\n            HttpResponseMessage response = new HttpResponseMessage();\n\n            // Act\n            await filter.ExecuteActionFilterAsync(context, CancellationToken.None, () => Task.FromResult(response));\n\n            // Assert\n            filterMock.Verify(f => f.OnActionExecuted(It.Is<HttpActionExecutedContext>(ec =>\n                    Object.ReferenceEquals(ec.Response, response)\n                    && ec.Exception == null\n                    && Object.ReferenceEquals(ec.ActionContext, context)\n            )));\n        }\n\n        [Fact]\n        public async Task ExecuteActionFilterAsync_IfContinuationFaulted_InvokesOnActionExecutedAsError()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n\n            Mock<ActionFilterAttribute> filterMock = new Mock<ActionFilterAttribute>()\n            {\n                CallBase = true,\n            };\n\n            var filter = (IActionFilter)filterMock.Object;\n            Exception exception = new Exception(\"{ABCC912C-B6D1-4C27-9059-732ABC644A0C}\");\n            Func<Task<HttpResponseMessage>> continuation = () => TaskHelpers.FromError<HttpResponseMessage>(exception);\n\n            // Act & Assert\n            await Assert.ThrowsAsync<Exception>(\n                () => filter.ExecuteActionFilterAsync(context, CancellationToken.None, continuation));\n\n            // Assert\n            filterMock.Verify(f => f.OnActionExecuted(It.Is<HttpActionExecutedContext>(ec =>\n                    Object.ReferenceEquals(ec.Exception, exception)\n                    && ec.Response == null\n                    && Object.ReferenceEquals(ec.ActionContext, context)\n            )));\n\n            filterMock.Verify(f => f.OnActionExecutedAsync(It.Is<HttpActionExecutedContext>(ec =>\n                    Object.ReferenceEquals(ec.Exception, exception)\n                    && ec.Response == null\n                    && Object.ReferenceEquals(ec.ActionContext, context)),\n                    It.IsAny<CancellationToken>()\n            ));\n        }\n\n        [Fact]\n        public async Task ExecuteActionFilterAsync_CancellationTokenFlowsThrough()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n\n            using (var cts = new CancellationTokenSource())\n            {\n                CancellationToken token = cts.Token;\n\n                Mock<ActionFilterAttribute> filterMock = new Mock<ActionFilterAttribute>()\n                {\n                    CallBase = true,\n                };\n\n                var filter = (IActionFilter)filterMock.Object;\n                Func<Task<HttpResponseMessage>> continuation = () => Task.FromResult<HttpResponseMessage>(new HttpResponseMessage());\n\n                // Act\n                await filter.ExecuteActionFilterAsync(context, token, continuation);\n\n                // Assert\n                filterMock.Verify(f => f.OnActionExecutingAsync(It.IsAny<HttpActionContext>(),\n                                               It.Is<CancellationToken>(t => t == token)));\n\n                filterMock.Verify(f => f.OnActionExecutedAsync(It.IsAny<HttpActionExecutedContext>(),\n                                                               It.Is<CancellationToken>(t => t == token)));\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteActionFilterAsync_DoesNotInvokeOnActionExecutedWhenOverriden()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            Mock<ActionFilterAttribute> filterMock = new Mock<ActionFilterAttribute>()\n            {\n                CallBase = true,\n            };\n\n            Func<Task<HttpResponseMessage>> continuation = () => Task.FromResult(new HttpResponseMessage());\n\n            filterMock.Setup(f => f.OnActionExecutedAsync(It.IsAny<HttpActionExecutedContext>(), It.IsAny<CancellationToken>())).Returns(TaskHelpers.Completed());\n            filterMock.Setup(f => f.OnActionExecuted(It.IsAny<HttpActionExecutedContext>())).Callback(\n                () =>\n                {\n                    throw new InvalidOperationException();\n                });\n\n            var filter = (IActionFilter)filterMock.Object;\n\n            // Act\n            await filter.ExecuteActionFilterAsync(context, CancellationToken.None, continuation);\n\n            // Assert\n            filterMock.Verify(f => f.OnActionExecutedAsync(It.IsAny<HttpActionExecutedContext>(),\n                                                           It.IsAny<CancellationToken>()));\n        }\n\n        [Fact]\n        public async Task ExecuteActionFilterAsync_DoesNotInvokeOnActionExecutingWhenOverriden()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            Mock<ActionFilterAttribute> filterMock = new Mock<ActionFilterAttribute>()\n            {\n                CallBase = true,\n            };\n\n            Func<Task<HttpResponseMessage>> continuation = () => Task.FromResult(new HttpResponseMessage());\n\n            filterMock.Setup(f => f.OnActionExecutingAsync(It.IsAny<HttpActionContext>(), CancellationToken.None)).Returns(TaskHelpers.Completed());\n            filterMock.Setup(f => f.OnActionExecuting(It.IsAny<HttpActionContext>())).Callback(\n                () =>\n                {\n                    throw new InvalidOperationException();\n                });\n\n            var filter = (IActionFilter)filterMock.Object;\n\n            // Act\n            await filter.ExecuteActionFilterAsync(context, CancellationToken.None, continuation);\n\n            // Assert\n            filterMock.Verify(f => f.OnActionExecutedAsync(It.IsAny<HttpActionExecutedContext>(), CancellationToken.None));\n        }\n\n        [Fact]\n        public async Task ExecuteActionFilterAsync_IfOnActionExecutedDoesNotHandleExceptionFromContinuation_ReturnsFaultedTask()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            Mock<ActionFilterAttribute> filterMock = new Mock<ActionFilterAttribute>()\n            {\n                CallBase = true,\n            };\n\n            var filter = (IActionFilter)filterMock.Object;\n            Exception exception = new Exception(\"{1EC330A2-33D0-4892-9335-2D833849D54E}\");\n            filterMock.Setup(f => f.OnActionExecuted(It.IsAny<HttpActionExecutedContext>())).Callback<HttpActionExecutedContext>(ec =>\n            {\n                ec.Response = null;\n            });\n\n            // Act\n            Exception result = await Assert.ThrowsAsync<Exception>(\n                () => filter.ExecuteActionFilterAsync(context, CancellationToken.None, () => TaskHelpers.FromError<HttpResponseMessage>(exception))\n            );\n\n            // Assert\n            Assert.Same(exception, result);\n        }\n\n        [Fact]\n        public async Task ExecuteActionFilterAsync_IfOnActionExecutedDoesHandleExceptionFromContinuation_ReturnsSuccessfulTask()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            Mock<ActionFilterAttribute> filterMock = new Mock<ActionFilterAttribute>()\n            {\n                CallBase = true,\n            };\n\n            var filter = (IActionFilter)filterMock.Object;\n            HttpResponseMessage newResponse = new HttpResponseMessage();\n            filterMock.Setup(f => f.OnActionExecuted(It.IsAny<HttpActionExecutedContext>())).Callback<HttpActionExecutedContext>(ec =>\n            {\n                ec.Response = newResponse;\n            });\n\n            // Act\n            HttpResponseMessage result = await filter.ExecuteActionFilterAsync(\n                                                        context,\n                                                        CancellationToken.None,\n                                                        () => TaskHelpers.FromError<HttpResponseMessage>(new Exception(\"{ED525C8E-7165-4207-B3F6-4AB095739017}\")));\n\n            // Assert\n            Assert.Same(newResponse, result);\n        }\n\n        [Fact]\n        public async Task ExecuteActionFilterAsync_IfOnActionExecutedThrowsException_ReturnsFaultedTask()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            Mock<ActionFilterAttribute> filterMock = new Mock<ActionFilterAttribute>()\n            {\n                CallBase = true,\n            };\n\n            var filter = (IActionFilter)filterMock.Object;\n            Exception exception = new Exception(\"{AC32AD02-36A7-45E5-8955-76A4E3B461C6}\");\n            filterMock.Setup(f => f.OnActionExecuted(It.IsAny<HttpActionExecutedContext>())).Callback<HttpActionExecutedContext>(ec =>\n            {\n                throw exception;\n            });\n\n            // Act\n            Exception actual = await Assert.ThrowsAsync<Exception>(\n                () => filter.ExecuteActionFilterAsync(context, CancellationToken.None, () => Task.FromResult(new HttpResponseMessage()))\n            );\n\n\n            // Assert\n            Assert.Same(exception, actual);\n        }\n\n        [Fact]\n        public async Task ExecuteActionFilterAsync_IfOnActionExecutedSetsResult_ReturnsNewResult()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            Mock<ActionFilterAttribute> filterMock = new Mock<ActionFilterAttribute>()\n            {\n                CallBase = true,\n            };\n\n            var filter = (IActionFilter)filterMock.Object;\n            HttpResponseMessage newResponse = new HttpResponseMessage();\n            filterMock.Setup(f => f.OnActionExecuted(It.IsAny<HttpActionExecutedContext>())).Callback<HttpActionExecutedContext>(ec =>\n            {\n                ec.Response = newResponse;\n            });\n\n            // Act\n            HttpResponseMessage result = await filter.ExecuteActionFilterAsync(context, CancellationToken.None, () => Task.FromResult(new HttpResponseMessage()));\n\n            // Assert\n            Assert.Same(newResponse, result);\n        }\n\n        [Fact]\n        public async Task ExecuteActionFilterAsync_IfOnActionExecutedDoesNotChangeResult_ReturnsSameResult()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            Mock<ActionFilterAttribute> filterMock = new Mock<ActionFilterAttribute>()\n            {\n                CallBase = true,\n            };\n\n            var filter = (IActionFilter)filterMock.Object;\n            HttpResponseMessage response = new HttpResponseMessage();\n            filterMock.Setup(f => f.OnActionExecuted(It.IsAny<HttpActionExecutedContext>())).Callback<HttpActionExecutedContext>(ec =>\n            {\n                ec.Response = ec.Response;\n            });\n\n            // Act\n            HttpResponseMessage result = await filter.ExecuteActionFilterAsync(context, CancellationToken.None, () => Task.FromResult(response));\n\n            // Assert\n            Assert.Same(response, result);\n        }\n\n        [Fact]\n        public Task ExecuteActionFilterAsync_IfOnActionExecutedRemovesSuccessfulResult_ReturnsFaultedTask()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            Mock<ActionFilterAttribute> filterMock = new Mock<ActionFilterAttribute>()\n            {\n                CallBase = true,\n            };\n\n            var filter = (IActionFilter)filterMock.Object;\n            HttpResponseMessage response = new HttpResponseMessage();\n            filterMock.Setup(f => f.OnActionExecuted(It.IsAny<HttpActionExecutedContext>())).Callback<HttpActionExecutedContext>(ec =>\n            {\n                ec.Response = null;\n            });\n\n            // Act and Assert\n            return Assert.ThrowsAsync<InvalidOperationException>(\n                () => filter.ExecuteActionFilterAsync(context, CancellationToken.None, () => Task.FromResult(response)),\n                \"After calling ActionFilterAttributeProxy.OnActionExecuted, the HttpActionExecutedContext properties Result and Exception were both null. At least one of these values must be non-null. To provide a new response, please set the Result object; to indicate an error, please throw an exception.\"\n            );\n        }\n\n        [Fact]\n        public async Task ExecuteActionFilterAsync_IfOnActionExecutedReplacesException_ThrowsNewException()\n        {\n            // Arrange\n            Exception expectedReplacementException = CreateException();\n\n            using (HttpRequestMessage request = new HttpRequestMessage())\n            {\n                Mock<ActionFilterAttribute> mock = new Mock<ActionFilterAttribute>();\n                mock.CallBase = true;\n                mock\n                    .Setup(f => f.OnActionExecuted(It.IsAny<HttpActionExecutedContext>()))\n                    .Callback<HttpActionExecutedContext>((c) => c.Exception = expectedReplacementException);\n                IActionFilter product = mock.Object;\n\n                HttpActionContext context = ContextUtil.CreateActionContext();\n                Func<Task<HttpResponseMessage>> continuation = () =>\n                    CreateFaultedTask<HttpResponseMessage>(CreateException());\n\n                // Act\n                Exception exception = await Assert.ThrowsAsync<InvalidOperationException>(\n                    () => product.ExecuteActionFilterAsync(context, CancellationToken.None, continuation)\n                );\n\n                // Assert\n                Assert.Same(expectedReplacementException, exception);\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteActionFilterAsync_IfFaultedTaskExceptionIsUnhandled_PreservesExceptionStackTrace()\n        {\n            // Arrange\n            Exception originalException = CreateExceptionWithStackTrace();\n            string expectedStackTrace = originalException.StackTrace;\n\n            using (HttpRequestMessage request = new HttpRequestMessage())\n            {\n                IActionFilter product = new TestableActionFilter();\n                HttpActionContext context = ContextUtil.CreateActionContext();\n                Func<Task<HttpResponseMessage>> continuation = () => CreateFaultedTask<HttpResponseMessage>(\n                    originalException);\n\n                // Act\n                Exception exception = await Assert.ThrowsAsync<InvalidOperationException>(\n                    () => product.ExecuteActionFilterAsync(context, CancellationToken.None, continuation)\n                );\n\n                // Assert\n                Assert.NotNull(expectedStackTrace);\n                Assert.StartsWith(expectedStackTrace, exception.StackTrace);\n            }\n        }\n\n        private static Exception CreateException()\n        {\n            return new InvalidOperationException();\n        }\n\n        private static Exception CreateExceptionWithStackTrace()\n        {\n            Exception exception;\n\n            try\n            {\n                throw CreateException();\n            }\n            catch (Exception ex)\n            {\n                exception = ex;\n            }\n\n            return exception;\n        }\n\n        private static Task<T> CreateFaultedTask<T>(Exception exception)\n        {\n            return TaskHelpers.FromError<T>(exception);\n        }\n\n        public class TestableActionFilter : ActionFilterAttribute\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Filters/AuthorizationFilterAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Filters\n{\n    public class AuthorizationFilterAttributeTest\n    {\n        [Fact]\n        public void AllowsMultiple_DefaultReturnsTrue()\n        {\n            AuthorizationFilterAttribute actionFilter = new TestableAuthorizationFilter();\n\n            Assert.True(actionFilter.AllowMultiple);\n        }\n\n        [Fact]\n        public void ExecuteAuthorizationFilterAsync_IfContextParameterIsNull_ThrowsException()\n        {\n            var filter = new TestableAuthorizationFilter() as IAuthorizationFilter;\n            Assert.ThrowsArgumentNull(() =>\n            {\n                filter.ExecuteAuthorizationFilterAsync(actionContext: null, cancellationToken: CancellationToken.None, continuation: () => null);\n            }, \"actionContext\");\n        }\n\n        [Fact]\n        public void ExecuteAuthorizationFilterAsync_IfContinuationParameterIsNull_ThrowsException()\n        {\n            var filter = new TestableAuthorizationFilter() as IAuthorizationFilter;\n            Assert.ThrowsArgumentNull(() =>\n            {\n                filter.ExecuteAuthorizationFilterAsync(actionContext: ContextUtil.CreateActionContext(), cancellationToken: CancellationToken.None, continuation: null);\n            }, \"continuation\");\n        }\n\n        [Fact]\n        public async Task ExecuteAuthorizationFilterAsync_InvokesOnActionExecutingBeforeContinuation()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            Mock<AuthorizationFilterAttribute> filterMock = new Mock<AuthorizationFilterAttribute>() { CallBase = true };\n            bool onActionExecutingInvoked = false;\n            filterMock.Setup(f => f.OnAuthorization(It.IsAny<HttpActionContext>())).Callback(() =>\n            {\n                onActionExecutingInvoked = true;\n            });\n            bool? flagWhenContinuationInvoked = null;\n            Func<Task<HttpResponseMessage>> continuation = () =>\n            {\n                flagWhenContinuationInvoked = onActionExecutingInvoked;\n                return Task.FromResult(new HttpResponseMessage());\n            };\n            var filter = (IAuthorizationFilter)filterMock.Object;\n\n            // Act\n            await filter.ExecuteAuthorizationFilterAsync(context, CancellationToken.None, continuation);\n\n            // Assert\n            Assert.True(flagWhenContinuationInvoked.Value);\n        }\n\n        [Fact]\n        public async Task ExecuteAuthorizationFilterAsync_IfOnActionExecutingSetsResult_ShortCircuits()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            Mock<AuthorizationFilterAttribute> filterMock = new Mock<AuthorizationFilterAttribute>\n            {\n                CallBase = true,\n            };\n\n            HttpResponseMessage response = new HttpResponseMessage();\n            filterMock.Setup(f => f.OnAuthorization(It.IsAny<HttpActionContext>())).Callback<HttpActionContext>(c =>\n            {\n                c.Response = response;\n            });\n\n            bool continuationCalled = false;\n            var filter = (IAuthorizationFilter)filterMock.Object;\n\n            // Act\n            var result = await filter.ExecuteAuthorizationFilterAsync(context, CancellationToken.None, () =>\n            {\n                continuationCalled = true;\n                return null;\n            });\n\n            // Assert\n            Assert.False(continuationCalled);\n            Assert.Same(response, result);\n        }\n\n        [Fact]\n        public async Task ExecuteAuthorizationFilterAsync_IfOnActionExecutingThrowsException_ReturnsFaultedTask()\n        {\n            // Arrange\n            Exception expectedException = new Exception();\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            Mock<AuthorizationFilterAttribute> filterMock = new Mock<AuthorizationFilterAttribute>()\n            {\n                CallBase = true,\n            };\n\n            filterMock.Setup(f => f.OnAuthorization(It.IsAny<HttpActionContext>())).Throws(expectedException);\n            var filter = (IAuthorizationFilter)filterMock.Object;\n            bool continuationCalled = false;\n\n            // Act & Assert\n            Exception exception = await Assert.ThrowsAsync<Exception>(\n                () => filter.ExecuteAuthorizationFilterAsync(context, CancellationToken.None, () =>\n                {\n                    continuationCalled = true;\n                    return null;\n                }));\n\n            // Assert\n            Assert.Same(expectedException, exception);\n            Assert.False(continuationCalled);\n        }\n\n        [Fact]\n        public async Task ExecuteAuthorizationFilterAsync_OnActionExecutingMethodGetsPassedControllerContext()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            Mock<AuthorizationFilterAttribute> filterMock = new Mock<AuthorizationFilterAttribute>() { CallBase = true };\n            var filter = (IAuthorizationFilter)filterMock.Object;\n\n            // Act\n            await filter.ExecuteAuthorizationFilterAsync(context, CancellationToken.None, () =>\n            {\n                return Task.FromResult(new HttpResponseMessage());\n            });\n\n            // Assert\n            filterMock.Verify(f => f.OnAuthorization(context));\n        }\n\n        [Fact]\n        public Task ExecuteAuthorizationFilterAsync_IfContinuationTaskWasCanceled_ReturnsCanceledTask()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            Mock<AuthorizationFilterAttribute> filterMock = new Mock<AuthorizationFilterAttribute>()\n            {\n                CallBase = true,\n            };\n\n            var filter = (IAuthorizationFilter)filterMock.Object;\n\n            // Act & Assert\n            return Assert.ThrowsAsync<TaskCanceledException>(\n                () => filter.ExecuteAuthorizationFilterAsync(context, CancellationToken.None, () => TaskHelpers.Canceled<HttpResponseMessage>()));\n        }\n\n        [Fact]\n        public async Task ExecuteAuthorizationFilterAsync_IfContinuationSucceeded_ReturnsSuccessTask()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            Mock<AuthorizationFilterAttribute> filterMock = new Mock<AuthorizationFilterAttribute>()\n            {\n                CallBase = true,\n            };\n\n            var filter = (IAuthorizationFilter)filterMock.Object;\n            HttpResponseMessage expectedResponse = new HttpResponseMessage();\n\n            // Act\n            var response = await filter.ExecuteAuthorizationFilterAsync(context, CancellationToken.None, () => Task.FromResult(expectedResponse));\n\n            // Assert\n            Assert.Same(expectedResponse, response);\n        }\n\n        [Fact]\n        public async Task ExecuteAuthorizationFilterAsync_IfContinuationFaulted_ReturnsFaultedTask()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            Mock<AuthorizationFilterAttribute> filterMock = new Mock<AuthorizationFilterAttribute>()\n            {\n                CallBase = true,\n            };\n\n            var filter = (IAuthorizationFilter)filterMock.Object;\n            Exception expectedException = new Exception();\n\n            // Act\n            var exception = await Assert.ThrowsAsync<Exception>(\n                () => filter.ExecuteAuthorizationFilterAsync(context, CancellationToken.None, () => TaskHelpers.FromError<HttpResponseMessage>(expectedException)));\n\n            // Assert\n            Assert.Same(expectedException, exception);\n        }\n    }\n\n    public class TestableAuthorizationFilter : AuthorizationFilterAttribute\n    {\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Filters/ConfigurationFilterProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Filters\n{\n    public class ConfigurationFilterProviderTest\n    {\n        private readonly ConfigurationFilterProvider provider = new ConfigurationFilterProvider();\n\n        [Fact]\n        public void GetFilters_IfContextParameterIsNull_ThrowsException()\n        {\n            Assert.ThrowsArgumentNull(() =>\n            {\n                provider.GetFilters(configuration: null, actionDescriptor: null);\n            }, \"configuration\");\n        }\n\n        [Fact]\n        public void GetFilters_ReturnsFiltersFromConfiguration()\n        {\n            var config = new HttpConfiguration();\n            IFilter filter1 = new Mock<IFilter>().Object;\n            config.Filters.Add(filter1);\n\n            var result = provider.GetFilters(config, actionDescriptor: null);\n\n            Assert.True(result.All(f => f.Scope == FilterScope.Global));\n            Assert.Same(filter1, result.ToArray()[0].Instance);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Filters/ExceptionFilterAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Filters\n{\n    public class ExceptionFilterAttributeTest\n    {\n        private readonly HttpActionExecutedContext _context = new HttpActionExecutedContext(ContextUtil.CreateActionContext(), new Exception());\n\n        [Fact]\n        public void AllowsMultiple_DefaultReturnsTrue()\n        {\n            ExceptionFilterAttribute actionFilter = new TestableExceptionFilter();\n\n            Assert.True(actionFilter.AllowMultiple);\n        }\n\n        [Fact]\n        public void ExecuteExceptionFilterAsync_IfContextParameterIsNull_ThrowsException()\n        {\n            IExceptionFilter filter = new Mock<ExceptionFilterAttribute>() { CallBase = true }.Object;\n\n            Assert.ThrowsArgumentNull(() =>\n            {\n                filter.ExecuteExceptionFilterAsync(actionExecutedContext: null, cancellationToken: CancellationToken.None);\n            }, \"actionExecutedContext\");\n        }\n\n        [Fact]\n        public async Task ExecuteExceptionFilterAsync_IfOnExceptionThrowsException_RethrowsTheSameException()\n        {\n            // Arrange\n            var mockFilter = new Mock<ExceptionFilterAttribute>() { CallBase = true };\n\n            Exception exception = new Exception();\n            mockFilter.Setup(f => f.OnException(_context)).Throws(exception);\n            IExceptionFilter filter = mockFilter.Object;\n\n            // Act & Assert\n            var thrownException = await Assert.ThrowsAsync<Exception>(() =>\n                filter.ExecuteExceptionFilterAsync(_context, CancellationToken.None));\n            Assert.Same(exception, thrownException);\n        }\n\n        [Fact]\n        public async Task ExecuteExceptionFilterAsync_InvokesOnExceptionMethod()\n        {\n            // Arrange\n            var mockFilter = new Mock<ExceptionFilterAttribute>()\n            {\n                CallBase = true,\n            };\n\n            IExceptionFilter filter = mockFilter.Object;\n\n            // Act\n            await filter.ExecuteExceptionFilterAsync(_context, CancellationToken.None);\n\n            // Assert\n            mockFilter.Verify(f => f.OnException(_context));\n        }\n\n        [Fact]\n        public void ExecuteExceptionFilterAsync_ReturnsCompletedTask()\n        {\n            // Arrange\n            var mockFilter = new Mock<ExceptionFilterAttribute>() { CallBase = true };\n            IExceptionFilter filter = mockFilter.Object;\n\n            // Act\n            var result = filter.ExecuteExceptionFilterAsync(_context, CancellationToken.None);\n\n            // Assert\n            Assert.True(result.Status == TaskStatus.RanToCompletion);\n        }\n\n        public sealed class TestableExceptionFilter : ExceptionFilterAttribute\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Filters/FilterAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Filters\n{\n    [CLSCompliant(false)]\n    public class FilterAttributeTest\n    {\n        [Theory]\n        [InlineData(typeof(UniqueFilterAttribute), false)]\n        [InlineData(typeof(MultiFilterAttribute), true)]\n        [InlineData(typeof(DefaultFilterAttribute), true)]\n        public void AllowMultiple(Type filterType, bool expectedAllowsMultiple)\n        {\n            var attribute = (FilterAttribute)Activator.CreateInstance(filterType);\n\n            Assert.Equal(expectedAllowsMultiple, attribute.AllowMultiple);\n        }\n\n        [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]\n        public sealed class UniqueFilterAttribute : FilterAttribute\n        {\n        }\n\n        [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]\n        public sealed class MultiFilterAttribute : FilterAttribute\n        {\n        }\n\n        public sealed class DefaultFilterAttribute : FilterAttribute\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Filters/FilterInfoComparerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Filters\n{\n    public class FilterInfoComparerTest\n    {\n        public static TheoryDataSet<FilterInfo, FilterInfo, int> CompareTestData\n        {\n            get\n            {\n                IFilter f = new Mock<IFilter>().Object;\n                return new TheoryDataSet<FilterInfo, FilterInfo, int>()\n                {\n                    { null, null, 0 },\n                    { new FilterInfo(f, FilterScope.Action), null, 1 },\n                    { null, new FilterInfo(f, FilterScope.Action), -1 },\n                    { new FilterInfo(f, FilterScope.Action), new FilterInfo(f, FilterScope.Action), 0 },\n                    { new FilterInfo(f, FilterScope.Controller), new FilterInfo(f, FilterScope.Action), -1 },\n                    { new FilterInfo(f, FilterScope.Action), new FilterInfo(f, FilterScope.Controller), 1 },\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"CompareTestData\")]\n        public void Compare(FilterInfo x, FilterInfo y, int expectedSign)\n        {\n            int result = FilterInfoComparer.Instance.Compare(x, y);\n\n            Assert.Equal(expectedSign, Math.Sign(result));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Filters/FilterInfoTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Filters\n{\n    public class FilterInfoTest\n    {\n        [Fact]\n        public void Constructor()\n        {\n            var filterInstance = new Mock<IFilter>().Object;\n\n            FilterInfo filter = new FilterInfo(filterInstance, FilterScope.Controller);\n\n            Assert.Equal(FilterScope.Controller, filter.Scope);\n            Assert.Same(filterInstance, filter.Instance);\n        }\n\n        [Fact]\n        public void Constructor_IfInstanceParameterIsNull_ThrowsException()\n        {\n            Assert.ThrowsArgumentNull(() =>\n            {\n                new FilterInfo(instance: null, scope: FilterScope.Controller);\n            }, \"instance\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Filters/HttpActionExecutedContextTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Filters\n{\n    public class HttpActionExecutedContextTest\n    {\n        [Fact]\n        public void Default_Constructor()\n        {\n            HttpActionExecutedContext actionExecutedContext = new HttpActionExecutedContext();\n\n            Assert.Null(actionExecutedContext.ActionContext);\n            Assert.Null(actionExecutedContext.Exception);\n            Assert.Null(actionExecutedContext.Request);\n            Assert.Null(actionExecutedContext.Response);\n        }\n\n        [Fact]\n        public void Parameter_Constructor()\n        {\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            Exception exception = new Exception();\n\n            var actionContext = new HttpActionExecutedContext(context, exception);\n\n            Assert.Same(context, actionContext.ActionContext);\n            Assert.Same(exception, actionContext.Exception);\n            Assert.Same(context.ControllerContext.Request, actionContext.Request);\n            Assert.Null(actionContext.Response);\n        }\n\n        [Fact]\n        public void Constructor_AllowsNullExceptionParameter()\n        {\n            HttpActionContext context = ContextUtil.CreateActionContext();\n\n            var actionContext = new HttpActionExecutedContext(context, exception: null);\n\n            Assert.Null(actionContext.Exception);\n        }\n\n        [Fact]\n        public void Constructor_IfContextParameterIsNull_ThrowsException()\n        {\n            Assert.ThrowsArgumentNull(() =>\n            {\n                new HttpActionExecutedContext(actionContext: null, exception: null);\n            }, \"actionContext\");\n        }\n\n        [Fact]\n        public void ActionContext_Property()\n        {\n            Assert.Reflection.Property<HttpActionExecutedContext, HttpActionContext>(\n                instance: new HttpActionExecutedContext(),\n                propertyGetter: aec => aec.ActionContext,\n                expectedDefaultValue: null,\n                allowNull: false,\n                roundTripTestValue: ContextUtil.CreateActionContext());\n        }\n\n        [Fact]\n        public void Exception_Property()\n        {\n            Assert.Reflection.Property<HttpActionExecutedContext, Exception>(\n                instance: new HttpActionExecutedContext(),\n                propertyGetter: aec => aec.Exception,\n                expectedDefaultValue: null,\n                allowNull: true,\n                roundTripTestValue: new ArgumentException());\n        }\n\n        [Fact]\n        public void Result_Property()\n        {\n            Assert.Reflection.Property<HttpActionExecutedContext, HttpResponseMessage>(\n            instance: new HttpActionExecutedContext(actionContext: ContextUtil.CreateActionContext(), exception: null),\n                propertyGetter: aec => aec.Response,\n                expectedDefaultValue: null,\n                allowNull: true,\n                roundTripTestValue: new HttpResponseMessage());\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Filters/HttpAuthenticationChallengeContextTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Http.Filters;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Controllers\n{\n    public class HttpAuthenticationChallengeContextTests\n    {\n        [Fact]\n        public void Constructor_Throws_WhenActionContextIsNull()\n        {\n            // Arrange\n            HttpActionContext actionContext = null;\n            IHttpActionResult result = CreateDummyResult();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { CreateProductUnderTest(actionContext, result); }, \"actionContext\");\n        }\n\n        [Fact]\n        public void Constructor_Throws_WhenResultIsNull()\n        {\n            // Arrange\n            HttpActionContext actionContext = CreateActionContext();\n            IHttpActionResult result = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { CreateProductUnderTest(actionContext, result); }, \"result\");\n        }\n\n        [Fact]\n        public void ActionContext_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            HttpActionContext expectedActionContext = CreateActionContext();\n            IHttpActionResult result = CreateDummyResult();\n            HttpAuthenticationChallengeContext product = CreateProductUnderTest(expectedActionContext, result);\n\n            // Act\n            HttpActionContext actionContext = product.ActionContext;\n\n            // Assert\n            Assert.Same(expectedActionContext, actionContext);\n        }\n\n        [Fact]\n        public void Result_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            HttpActionContext actionContext = CreateActionContext();\n            IHttpActionResult expectedResult = CreateDummyResult();\n            HttpAuthenticationChallengeContext product = CreateProductUnderTest(actionContext, expectedResult);\n\n            // Act\n            IHttpActionResult result = product.Result;\n\n            // Assert\n            Assert.Same(expectedResult, result);\n        }\n\n        [Fact]\n        public void Request_ReturnsActionContextRequest()\n        {\n            // Arrange\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                HttpActionContext actionContext = CreateActionContext(expectedRequest);\n                IHttpActionResult result = CreateDummyResult();\n                HttpAuthenticationChallengeContext product = CreateProductUnderTest(actionContext, result);\n\n                // Act\n                HttpRequestMessage request = product.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public void ResultSetter_Throws_WhenNull()\n        {\n            // Arrange\n            HttpActionContext actionContext = CreateActionContext();\n            IHttpActionResult result = CreateDummyResult();\n            HttpAuthenticationChallengeContext product = CreateProductUnderTest(actionContext, result);\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { product.Result = null; }, \"value\");\n        }\n\n        private static HttpActionContext CreateActionContext()\n        {\n            return new HttpActionContext();\n        }\n\n        private static HttpActionContext CreateActionContext(HttpRequestMessage request)\n        {\n            HttpControllerContext controllerContext = new HttpControllerContext();\n            controllerContext.Request = request;\n            HttpActionContext actionContext = new HttpActionContext();\n            actionContext.ControllerContext = controllerContext;\n            return actionContext;\n        }\n\n        private static IHttpActionResult CreateDummyResult()\n        {\n            return new Mock<IHttpActionResult>(MockBehavior.Strict).Object;\n        }\n\n        private static HttpAuthenticationChallengeContext CreateProductUnderTest(HttpActionContext actionContext,\n            IHttpActionResult result)\n        {\n            return new HttpAuthenticationChallengeContext(actionContext, result);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Filters/HttpAuthenticationContextTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Security.Principal;\nusing System.Web.Http.Filters;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Controllers\n{\n    public class HttpAuthenticationContextTests\n    {\n        [Fact]\n        public void Constructor_Throws_WhenActionContextIsNull()\n        {\n            // Arrange\n            HttpActionContext actionContext = null;\n            IPrincipal principal = CreateDummyPrincipal();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { CreateProductUnderTest(actionContext, principal); }, \"actionContext\");\n        }\n\n        [Fact]\n        public void ActionContext_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            HttpActionContext expectedActionContext = CreateActionContext();\n            IPrincipal principal = CreateDummyPrincipal();\n            HttpAuthenticationContext product = CreateProductUnderTest(expectedActionContext, principal);\n\n            // Act\n            HttpActionContext actionContext = product.ActionContext;\n\n            // Assert\n            Assert.Same(expectedActionContext, actionContext);\n        }\n\n        [Fact]\n        public void Principal_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            HttpActionContext actionContext = CreateActionContext();\n            IPrincipal expectedPrincipal = CreateDummyPrincipal();\n            HttpAuthenticationContext product = CreateProductUnderTest(actionContext, expectedPrincipal);\n\n            // Act\n            IPrincipal principal = product.Principal;\n\n            // Assert\n            Assert.Same(expectedPrincipal, principal);\n        }\n\n        [Fact]\n        public void Request_ReturnsActionContextRequest()\n        {\n            // Arrange\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                HttpActionContext actionContext = CreateActionContext(expectedRequest);\n                IPrincipal principal = CreateDummyPrincipal();\n                HttpAuthenticationContext product = CreateProductUnderTest(actionContext, principal);\n\n                // Act\n                HttpRequestMessage request = product.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        private static HttpActionContext CreateActionContext()\n        {\n            return new HttpActionContext();\n        }\n\n        private static HttpActionContext CreateActionContext(HttpRequestMessage request)\n        {\n            HttpControllerContext controllerContext = new HttpControllerContext();\n            controllerContext.Request = request;\n            HttpActionContext actionContext = new HttpActionContext();\n            actionContext.ControllerContext = controllerContext;\n            return actionContext;\n        }\n\n        private static IPrincipal CreateDummyPrincipal()\n        {\n            return new Mock<IPrincipal>(MockBehavior.Strict).Object;\n        }\n\n        private static HttpAuthenticationContext CreateProductUnderTest(HttpActionContext actionContext,\n            IPrincipal principal)\n        {\n            return new HttpAuthenticationContext(actionContext, principal);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Filters/HttpFilterCollectionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Filters\n{\n    public class HttpFilterCollectionTest\n    {\n        private readonly IFilter _filter = new Mock<IFilter>().Object;\n        private readonly HttpFilterCollection _collection = new HttpFilterCollection();\n\n        [Fact]\n        public void Add_WhenFilterParameterIsNull_Throws()\n        {\n            Assert.ThrowsArgumentNull(() => _collection.Add(filter: null), \"filter\");\n        }\n\n        [Fact]\n        public void Add_AddsFilterWithGlobalScope()\n        {\n            _collection.Add(_filter);\n\n            Assert.Same(_filter, _collection.First().Instance);\n            Assert.Equal(FilterScope.Global, _collection.First().Scope);\n        }\n\n        [Fact]\n        public void Add_AllowsAddingSameInstanceMultipleTimes()\n        {\n            _collection.Add(_filter);\n            _collection.Add(_filter);\n\n            Assert.Equal(2, _collection.Count);\n        }\n\n        [Fact]\n        public void AddRange_AddsAllFilters()\n        {\n            IFilter[] filters = { _filter, _filter };\n\n            _collection.AddRange(filters);\n\n            Assert.Equal(filters.Length, _collection.Count);\n            Assert.True(filters.All(_collection.Contains));\n        }\n\n        [Fact]\n        public void AddRange_AddsAllFiltersWithGlobalScope()\n        {\n            IFilter[] filters = { _filter, _filter };\n\n            _collection.AddRange(filters);\n\n            Assert.True(_collection.All(f => FilterScope.Global == f.Scope));\n        }\n\n        [Fact]\n        public void AddRange_ValidatesNotNull()\n        {\n            IFilter[] filters = { _filter, null };\n\n            Assert.Throws<ArgumentException>(\n                () => _collection.AddRange(filters),\n                \"The parameter 'filters' cannot contain a null element.\" + Environment.NewLine +\n                \"Parameter name: filters\");\n\n            Assert.Equal(0, _collection.Count);\n        }\n\n        [Fact]\n        public void Clear_EmptiesCollection()\n        {\n            _collection.Add(_filter);\n\n            _collection.Clear();\n\n            Assert.Equal(0, _collection.Count);\n        }\n\n        [Fact]\n        public void Contains_WhenFilterNotInCollection_ReturnsFalse()\n        {\n            Assert.False(_collection.Contains(_filter));\n        }\n\n        [Fact]\n        public void Contains_WhenFilterInCollection_ReturnsTrue()\n        {\n            _collection.Add(_filter);\n\n            Assert.True(_collection.Contains(_filter));\n        }\n\n        [Fact]\n        public void Count_WhenCollectionIsEmpty_ReturnsZero()\n        {\n            Assert.Equal(0, _collection.Count);\n        }\n\n        [Fact]\n        public void Count_WhenItemAddedToCollection_ReturnsOne()\n        {\n            _collection.Add(_filter);\n\n            Assert.Equal(1, _collection.Count);\n        }\n\n        [Fact]\n        public void Remove_WhenCollectionDoesNotHaveFilter_DoesNothing()\n        {\n            _collection.Remove(_filter);\n\n            Assert.Equal(0, _collection.Count);\n        }\n\n        [Fact]\n        public void Remove_WhenCollectionHasFilter_RemovesIt()\n        {\n            _collection.Add(_filter);\n            _collection.Add(_filter);\n\n            _collection.Remove(_filter);\n\n            Assert.Equal(0, _collection.Count);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Hosting/HttpMessageHandlerExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http.Hosting\n{\n    internal static class HttpMessageHandlerExtensions\n    {\n        public static Task<HttpResponseMessage> SendAsync(this HttpMessageHandler handler, HttpRequestMessage request,\n            CancellationToken cancellationToken)\n        {\n            HttpMessageInvoker invoker = new HttpMessageInvoker(handler, false);\n            return invoker.SendAsync(request, cancellationToken);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Hosting/HttpRouteTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Web.Http.Routing;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Hosting\n{\n    public class HttpRouteTest\n    {\n        [Fact]\n        public void Ctor_PreservesWhitespaceInRouteTemplate()\n        {\n            string whitespace = \"   \";\n\n            HttpRoute httpRoute = new HttpRoute(whitespace);\n\n            Assert.Equal(whitespace, httpRoute.RouteTemplate);\n        }\n\n        [Theory]\n        [InlineData(\"{controller}/{id}\", \"/SelfHostServer\", \"http://localhost/SelfHostServer/Customer/999\")]\n        [InlineData(\"{controller}/{id}\", \"\", \"http://localhost/Customer/999\")]\n        [InlineData(\"{controller}\", \"\", \"http://localhost/\")]\n        [InlineData(\"{controller}\", \"/SelfHostServer\", \"http://localhost/SelfHostServer\")]\n        [InlineData(\"{controller}\", \"\", \"http://localhost\")]\n        [InlineData(\"{controller}/{id}\", \"\", \"http://localhost/\")]\n        [InlineData(\"{controller}/{id}\", \"/SelfHostServer\", \"http://localhost/SelfHostServer\")]\n        [InlineData(\"{controller}/{id}\", \"\", \"http://localhost\")]\n        [InlineData(\"api\", \"\", \"http://localhost/api\")]\n        [InlineData(\"api\", \"\", \"http://LOCALHOST/API\")]\n        [InlineData(\"{controller}/{id}\", \"/SelfHostServer/Customer/999\", \"http://localhost/SelfHostServer/Customer/999\")]\n        [InlineData(\"{controller}/{id}\", \"/SelfHostServer/Customer/999\", \"http://localhost/SelfHostServer/Customer/999/\")]\n        [InlineData(\"{controller}/{id}\", \"/SelfHostServer/Customer/999/\", \"http://localhost/SelfHostServer/Customer/999/\")]\n        [InlineData(\"{controller}\", \"/SelfHostServer\", \"http://localhost/SelfHostServer/\")]\n        [InlineData(\"{controller}\", \"/SelfHostServer/\", \"http://localhost/SelfHostServer/\")]\n        public void GetRouteDataShouldMatch(string uriTemplate, string virtualPathRoot, string requestUri)\n        {\n            HttpRoute route = new HttpRoute(uriTemplate);\n            route.Defaults.Add(\"controller\", \"Customer\");\n            route.Defaults.Add(\"id\", \"999\");\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.RequestUri = new Uri(requestUri);\n\n            IHttpRouteData data = route.GetRouteData(virtualPathRoot, request);\n\n            // Assert\n            Assert.NotNull(data);\n            IDictionary<string, object> expectedResult = new Dictionary<string, object>();\n            expectedResult[\"controller\"] = \"Customer\";\n            expectedResult[\"id\"] = \"999\";\n            Assert.Equal(expectedResult, data.Values, new DictionaryEqualityComparer());\n        }\n\n        [Theory]\n        [InlineData(\"{controller}/{id}\", \"/SelfHostServer/Customer/999/Invalid\", \"http://localhost/SelfHostServer/Customer/999\")]\n        [InlineData(\"{controller}\", \"/SelfHostServer/\", \"http://localhost/SelfHostServer\")]\n        public void GetRouteDataDoesNotMatch(string uriTemplate, string virtualPathRoot, string requestUri)\n        {\n            HttpRoute route = new HttpRoute(uriTemplate);\n            route.Defaults.Add(\"controller\", \"Customer\");\n            route.Defaults.Add(\"id\", \"999\");\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.RequestUri = new Uri(requestUri);\n\n            IHttpRouteData data = route.GetRouteData(virtualPathRoot, request);\n\n            // Assert\n            Assert.Null(data);\n        }\n\n        [Theory]\n        [InlineData(\"controller\")]\n        [InlineData(\"cOnTrOlLeR\")]\n        [InlineData(\"CONTROLLER\")]\n        public void GetVirtualPath_GetsValuesInCaseInsensitiveWay(string controllerKey)\n        {\n            var route = new HttpRoute(\"{controller}\");\n            var request = new HttpRequestMessage();\n            request.SetRouteData(\n                new HttpRouteData(route, new HttpRouteValueDictionary() {\n                    { \"controller\", \"Employees\" }\n                }));\n            var values = new HttpRouteValueDictionary()\n            {\n                { \"httproute\", true },\n                { controllerKey, \"Customers\" }\n            };\n\n            IHttpVirtualPathData virtualPath = route.GetVirtualPath(request, values);\n\n            Assert.NotNull(virtualPath);\n            Assert.Equal(\"Customers\", virtualPath.VirtualPath);\n        }\n\n        [Fact]\n        public void GetVirtualPath_GeneratesPathWithoutRouteData()\n        {\n            var route = new HttpRoute(\"{controller}\");\n            var request = new HttpRequestMessage();\n            var values = new HttpRouteValueDictionary()\n            {\n                { \"httproute\", true },\n                { \"controller\", \"Customers\" }\n            };\n\n            IHttpVirtualPathData virtualPath = route.GetVirtualPath(request, values);\n\n            Assert.NotNull(virtualPath);\n            Assert.Equal(\"Customers\", virtualPath.VirtualPath);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Hosting/SuppressHostPrincipalMessageHandlerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Hosting\n{\n    public class SuppressHostPrincipalMessageHandlerTest\n    {\n        [Fact]\n        public async Task SendAsync_DelegatesToInnerHandler()\n        {\n            // Arrange\n            HttpRequestMessage request = null;\n            var cancellationToken = default(CancellationToken);\n            HttpMessageHandler innerHandler = new LambdaHttpMessageHandler((r, c) =>\n            {\n                request = r;\n                cancellationToken = c;\n                return Task.FromResult<HttpResponseMessage>(null);\n            });\n            HttpMessageHandler handler = CreateProductUnderTest(innerHandler);\n            var expectedCancellationToken = new CancellationToken(true);\n\n            using (var expectedRequest = CreateRequestWithContext())\n            {\n                // Act\n                var result = await handler.SendAsync(expectedRequest, expectedCancellationToken);\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n                Assert.Equal(expectedCancellationToken, cancellationToken);\n                Assert.Null(result);\n            }\n        }\n\n        [Fact]\n        public async Task SendAsync_Throws_WhenRequestContextIsNull()\n        {\n            // Arrange\n            HttpMessageHandler innerHandler = CreateDummyHandler();\n            HttpMessageHandler handler = CreateProductUnderTest(innerHandler);\n\n            using (HttpRequestMessage request = new HttpRequestMessage())\n            {\n                // Act & Assert\n                await Assert.ThrowsArgumentAsync(\n                    () => handler.SendAsync(request, CancellationToken.None),\n                    \"request\",\n                    \"The request must have a request context.\");\n            }\n        }\n\n        [Fact]\n        public async Task SendAsync_SetsCurrentPrincipalToAnonymous_BeforeCallingInnerHandler()\n        {\n            // Arrange\n            var requestContextMock = new Mock<HttpRequestContext>(MockBehavior.Strict);\n            var sequence = new MockSequence();\n            var initialPrincipal = new GenericPrincipal(new GenericIdentity(\"generic user\"), new[] { \"generic role\" });\n            IPrincipal requestContextPrincipal = null;\n            requestContextMock\n                .InSequence(sequence)\n                .SetupGet(c => c.Principal)\n                .Returns(initialPrincipal);\n            requestContextMock\n                .InSequence(sequence)\n                .SetupSet(c => c.Principal = It.IsAny<IPrincipal>())\n                .Callback<IPrincipal>(value => requestContextPrincipal = value);\n\n            // SendAsync also restores the old principal.\n            requestContextMock\n                .InSequence(sequence)\n                .SetupGet(c => c.Principal)\n                .Returns(requestContextPrincipal);\n            requestContextMock\n                .InSequence(sequence)\n                .SetupSet(c => c.Principal = initialPrincipal);\n\n            IPrincipal principalBeforeInnerHandler = null;\n            HttpMessageHandler inner = new LambdaHttpMessageHandler((ignore1, ignore2) =>\n            {\n                principalBeforeInnerHandler = requestContextPrincipal;\n                return Task.FromResult<HttpResponseMessage>(null);\n            });\n            HttpMessageHandler handler = CreateProductUnderTest(inner);\n\n            using (var request = new HttpRequestMessage())\n            {\n                request.SetRequestContext(requestContextMock.Object);\n\n                // Act\n                await handler.SendAsync(request, CancellationToken.None);\n            }\n\n            // Assert\n            Assert.Equal(requestContextPrincipal, principalBeforeInnerHandler);\n            Assert.NotNull(principalBeforeInnerHandler);\n            var identity = principalBeforeInnerHandler.Identity;\n            Assert.NotNull(identity);\n            Assert.False(identity.IsAuthenticated);\n            Assert.Null(identity.Name);\n            Assert.Null(identity.AuthenticationType);\n        }\n\n        private static HttpMessageHandler CreateDummyHandler()\n        {\n            return new DummyHttpMessageHandler();\n        }\n\n        private static SuppressHostPrincipalMessageHandler CreateProductUnderTest(HttpMessageHandler innerHandler)\n        {\n            SuppressHostPrincipalMessageHandler handler = new SuppressHostPrincipalMessageHandler();\n            handler.InnerHandler = innerHandler;\n            return handler;\n        }\n\n        private static HttpRequestMessage CreateRequestWithContext()\n        {\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.SetRequestContext(new HttpRequestContext());\n            return request;\n        }\n\n        private class DummyHttpMessageHandler : HttpMessageHandler\n        {\n            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,\n                CancellationToken cancellationToken)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class LambdaHttpMessageHandler : HttpMessageHandler\n        {\n            private readonly Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> _sendAsync;\n\n            public LambdaHttpMessageHandler(Func<HttpRequestMessage, CancellationToken,\n                Task<HttpResponseMessage>> sendAsync)\n            {\n                if (sendAsync == null)\n                {\n                    throw new ArgumentNullException(\"sendAsync\");\n                }\n\n                _sendAsync = sendAsync;\n            }\n\n            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,\n                CancellationToken cancellationToken)\n            {\n                return _sendAsync.Invoke(request, cancellationToken);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/HttpConfigurationExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Web.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.ModelBinding.Binders;\nusing System.Web.Http.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Net.Http\n{\n    public class HttpConfigurationExtensionsTest\n    {\n        [Fact]\n        public void BindParameter_GuardClauses()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            Type type = typeof(TestParameter);\n            IModelBinder binder = new Mock<IModelBinder>().Object;\n\n            Assert.ThrowsArgumentNull(() => HttpConfigurationExtensions.BindParameter(null, type, binder), \"configuration\");\n            Assert.ThrowsArgumentNull(() => HttpConfigurationExtensions.BindParameter(config, null, binder), \"type\");\n            Assert.ThrowsArgumentNull(() => HttpConfigurationExtensions.BindParameter(config, type, null), \"binder\");\n        }\n\n        [Fact]\n        public void BindParameter_InsertsModelBinderProviderInPositionZero()\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            Type type = typeof(TestParameter);\n            IModelBinder binder = new Mock<IModelBinder>().Object;\n\n            // Act\n            config.BindParameter(type, binder);\n\n            // Assert\n            SimpleModelBinderProvider provider = config.Services.GetServices(typeof(ModelBinderProvider)).OfType<SimpleModelBinderProvider>().First();\n            Assert.Equal(type, provider.ModelType);\n        }\n\n        [Fact]\n        public void MapHttpAttributeRoutes_DoesNotAddRoutesWithoutAttribute()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var routePrefixes = new Collection<IRoutePrefix>() { new RoutePrefixAttribute(\"prefix\") };\n            var routeProviders = new Collection<RouteAttribute>() { };\n            SetUpConfiguration(config, routePrefixes, routeProviders);\n\n            // Act\n            config.MapHttpAttributeRoutes();\n\n            // Assert\n            var routes = config.GetAttributeRoutes();\n            Assert.Empty(routes);\n        }\n\n        [Fact]\n        public void MapHttpAttributeRoutes_DoesNotRegisterRoute_ForActionsWithPrefixButNoRouteTemplate()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var routePrefixes = new Collection<IRoutePrefix>() { new RoutePrefixAttribute(\"prefix\") };\n            var routeProviders = new Collection<RouteAttribute>() { };\n            SetUpConfiguration(config, routePrefixes, routeProviders);\n\n            // Act\n            config.MapHttpAttributeRoutes();\n\n            // Assert\n            var routes = config.GetAttributeRoutes();\n            Assert.Empty(routes);\n        }\n\n        [Theory]\n        [InlineData(null, \"\", \"\")]\n        [InlineData(null, \"   \", \"   \")]\n        [InlineData(null, \"controller/{id}\", \"controller/{id}\")]\n        [InlineData(\"\", \"\", \"\")]\n        [InlineData(\"\", \"   \", \"   \")]\n        [InlineData(\"\", \"controller/{id}\", \"controller/{id}\")]\n        [InlineData(\"   \", \"\", \"   \")]\n        [InlineData(\"   \", \"   \", \"   /   \")]\n        [InlineData(\"   \", \"controller/{id}\", \"   /controller/{id}\")]\n        [InlineData(\"prefix/{prefixId}\", \"\", \"prefix/{prefixId}\")]\n        [InlineData(\"prefix/{prefixId}\", \"   \", \"prefix/{prefixId}/   \")]\n        [InlineData(\"prefix/{prefixId}\", \"controller/{id}\", \"prefix/{prefixId}/controller/{id}\")]\n        [InlineData(null, \"~/controller/{id}\", \"controller/{id}\")]\n        [InlineData(\"prefix/{prefixId}\", \"~/\", \"\")]\n        [InlineData(\"prefix/{prefixId}\", \"~/controller/{id}\", \"controller/{id}\")]\n        public void MapHttpAttributeRoutes_AddsRouteFromAttribute(string prefix, string template, string expectedTemplate)\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var routePrefixes = new Collection<IRoutePrefix>();\n            if (prefix != null)\n            {\n                routePrefixes.Add(new RoutePrefixAttribute(prefix));\n            }\n\n            var routeProviders = new Collection<RouteAttribute>() { new RouteAttribute(template) };\n\n            SetUpConfiguration(config, routePrefixes, routeProviders);\n\n            // Act\n            config.MapHttpAttributeRoutes();\n\n            // Assert\n            var routes = config.GetAttributeRoutes();\n            IHttpRoute route = Assert.Single(routes);\n            Assert.Equal(expectedTemplate, route.RouteTemplate);\n        }\n\n        [Fact]\n        public void MapHttpAttributeRoutes_ThrowsForRoutePrefixThatEndsWithSeparator()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var routePrefixes = new Collection<IRoutePrefix>() { new RoutePrefixAttribute(\"prefix/\") };\n            var routeProviders = new Collection<RouteAttribute>() { new RouteAttribute(\"\") };\n            SetUpConfiguration(config, routePrefixes, routeProviders);\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => { config.MapHttpAttributeRoutes(); config.EnsureInitialized(); },\n                \"The route prefix 'prefix/' on the controller named 'Controller' cannot end with a '/' character.\");\n        }\n\n        [Fact]\n        public void MapHttpAttributeRoutes_ThrowsForRouteTemplateThatStartsWithSeparator()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var routePrefixes = new Collection<IRoutePrefix>() { };\n            var routeProviders = new Collection<RouteAttribute>() { new RouteAttribute(\"/get\") };\n            SetUpConfiguration(config, routePrefixes, routeProviders);\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => { config.MapHttpAttributeRoutes(); config.EnsureInitialized(); },\n                \"The route template '/get' on the action named 'Action' cannot start with a '/' character.\");\n        }\n\n        [Fact]\n        public void MapHttpAttributeRoutes_AddsMultipleRoutesFromAttributes()\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            var routePrefixes = new Collection<IRoutePrefix>();\n            var routeProviders = new Collection<RouteAttribute>() { new RouteAttribute(\"controller/get1\"), new RouteAttribute(\"controller/get2\") };\n            SetUpConfiguration(config, routePrefixes, routeProviders);\n\n            // Act\n            config.MapHttpAttributeRoutes();\n\n            // Assert\n            var routes = config.GetAttributeRoutes();\n            Assert.Equal(2, routes.Count);\n            Assert.Single(routes, route => route.RouteTemplate == \"controller/get1\");\n            Assert.Single(routes, route => route.RouteTemplate == \"controller/get2\");\n        }\n\n        [Fact]\n        public void MapHttpAttributeRoutes_IsDeferred()\n        {\n            bool called = false;\n            HttpConfiguration config = new HttpConfiguration();\n\n            config.Initializer = _ => called = true;\n            config.Services.Clear(typeof(IHttpControllerSelector));\n            config.Services.Clear(typeof(IHttpActionSelector));\n            config.Services.Clear(typeof(IActionValueBinder));\n\n            // Call Map, ensure that it's not touching any services yet since all work is deferred.\n            // This is important since these services aren't ready to be used until after config is finalized.\n            // Else we may end up caching objects prematurely.\n            config.MapHttpAttributeRoutes();\n\n            Assert.False(called);\n        }\n\n        [Fact]\n        public void MapHttpAttributeRoutes_AddsLinkGenerationRoutes()\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            var routePrefixes = new Collection<IRoutePrefix>() { };\n            var routeProviders = new Collection<RouteAttribute>()\n                {\n                    new RouteAttribute(\"get1\") { Name = \"one\" },\n                    new RouteAttribute(\"get2\") { Name = \"two\" },\n                    new RouteAttribute(\"get3\") { Name = \"three\" }\n                };\n            SetUpConfiguration(config, routePrefixes, routeProviders);\n\n            // Act\n            config.MapHttpAttributeRoutes();\n            config.Initializer(config);\n\n            // Assert\n            HttpRouteCollection routes = config.Routes;\n            Assert.Equal(4, routes.Count); // 1 attr route, plus 3 generation routes\n            Assert.IsType<RouteCollectionRoute>(routes.ElementAt(0));\n            for (int i = 1; i < 4; i++)\n            {\n                Assert.IsType<LinkGenerationRoute>(routes.ElementAt(i));\n            }\n\n            Assert.IsType<LinkGenerationRoute>(routes[\"one\"]);\n            Assert.IsType<LinkGenerationRoute>(routes[\"two\"]);\n            Assert.IsType<LinkGenerationRoute>(routes[\"three\"]);\n        }\n\n        [Fact]\n        public void MapHttpAttributeRoutes_RespectsPerControllerActionSelectors()\n        {\n            // Arrange\n            var globalConfiguration = new HttpConfiguration();\n            var controllerDescriptor = new HttpControllerDescriptor(globalConfiguration, \"PerControllerActionSelector\", typeof(PerControllerActionSelectorController));\n\n            // Set up the global action selector and controller selector\n            var controllerSelector = CreateControllerSelector(new[] { controllerDescriptor });\n            globalConfiguration.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n\n            var globalAction = CreateActionDescriptor(controllerDescriptor, \"Global\", new Collection<RouteAttribute>() { new RouteAttribute(\"Global\") });\n            var globalActionSelector = CreateActionSelector(\n                new Dictionary<HttpControllerDescriptor, IEnumerable<HttpActionDescriptor>>()\n                    {\n                        { controllerDescriptor, new HttpActionDescriptor[] { globalAction } }\n                    });\n            globalConfiguration.Services.Replace(typeof(IHttpActionSelector), globalActionSelector);\n\n            // Configure the per controller action selector to return the action with route \"PerController\"\n            var perControllerAction = CreateActionDescriptor(\n                controllerDescriptor,\n                \"PerController\",\n                new Collection<RouteAttribute>() { new RouteAttribute(\"PerController\") });\n            ActionSelectorConfigurationAttribute.PerControllerActionSelectorMock\n                .Setup(a => a.GetActionMapping(controllerDescriptor))\n                .Returns(new HttpActionDescriptor[] { perControllerAction }.ToLookup(ad => ad.ActionName));\n\n            // Act\n            globalConfiguration.MapHttpAttributeRoutes();\n\n            // Assert\n            var routes = globalConfiguration.GetAttributeRoutes();\n            Assert.Equal(\"PerController\", Assert.Single(routes).RouteTemplate);\n        }\n\n        [Fact]\n        public void SuppressHostPrincipal_InsertsSuppressHostPrincipalMessageHandler()\n        {\n            // Arrange\n            DelegatingHandler existingHandler = new Mock<DelegatingHandler>(MockBehavior.Strict).Object;\n\n            using (HttpConfiguration configuration = new HttpConfiguration())\n            {\n                configuration.MessageHandlers.Add(existingHandler);\n\n                // Act\n                configuration.SuppressHostPrincipal();\n\n                // Assert\n                Assert.Equal(2, configuration.MessageHandlers.Count);\n                DelegatingHandler firstHandler = configuration.MessageHandlers[0];\n                Assert.IsType<SuppressHostPrincipalMessageHandler>(firstHandler);\n            }\n        }\n\n        [Fact]\n        public void SuppressHostPrincipal_Throws_WhenConfigurationIsNull()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { HttpConfigurationExtensions.SuppressHostPrincipal(null); },\n                \"configuration\");\n        }\n\n        private static void SetUpConfiguration(HttpConfiguration config, Collection<IRoutePrefix> routePrefixes, IEnumerable<RouteAttribute> routeAttributes)\n        {\n            HttpControllerDescriptor controllerDescriptor = CreateControllerDescriptor(config, \"Controller\", routePrefixes);\n            HttpActionDescriptor actionDescriptor = CreateActionDescriptor(controllerDescriptor, \"Action\", routeAttributes);\n\n            var controllerSelector = CreateControllerSelector(new[] { controllerDescriptor });\n            config.Services.Replace(typeof(IHttpControllerSelector), controllerSelector);\n            var actionSelector = CreateActionSelector(\n                new Dictionary<HttpControllerDescriptor, IEnumerable<HttpActionDescriptor>>()\n                {\n                    { controllerDescriptor, new HttpActionDescriptor[] { actionDescriptor } }\n                });\n            config.Services.Replace(typeof(IHttpActionSelector), actionSelector);\n        }\n\n        private static HttpControllerDescriptor CreateControllerDescriptor(HttpConfiguration configuration, string controllerName,\n            Collection<IRoutePrefix> routePrefixes)\n        {\n            Mock<HttpControllerDescriptor> controllerDescriptor = new Mock<HttpControllerDescriptor>();\n            controllerDescriptor.Object.Configuration = configuration;\n            controllerDescriptor.Object.ControllerName = controllerName;\n            controllerDescriptor.Setup(cd => cd.GetCustomAttributes<IRoutePrefix>(false)).Returns(routePrefixes);\n            controllerDescriptor.Setup(cd => cd.GetCustomAttributes<IHttpRouteInfoProvider>(false)).Returns(new Collection<IHttpRouteInfoProvider>());\n            controllerDescriptor.Setup(cd => cd.GetCustomAttributes<IDirectRouteFactory>(false)).Returns(new Collection<IDirectRouteFactory>());\n            return controllerDescriptor.Object;\n        }\n\n        private static HttpActionDescriptor CreateActionDescriptor(\n            HttpControllerDescriptor controllerDescriptor,\n            string actionName, IEnumerable<RouteAttribute>\n            routeAttributes)\n        {\n            Collection<IDirectRouteFactory> newProviders = new Collection<IDirectRouteFactory>(new List<IDirectRouteFactory>(routeAttributes));\n            Collection<IHttpRouteInfoProvider> oldProviders = new Collection<IHttpRouteInfoProvider>(new List<IHttpRouteInfoProvider>(routeAttributes));\n            Mock<ReflectedHttpActionDescriptor> actionDescriptor = new Mock<ReflectedHttpActionDescriptor>();\n            actionDescriptor.Setup(ad => ad.ActionName).Returns(actionName);\n            actionDescriptor.Setup(ad => ad.GetCustomAttributes<IDirectRouteFactory>(false)).Returns(newProviders);\n            actionDescriptor.Setup(ad => ad.GetCustomAttributes<IHttpRouteInfoProvider>(false)).Returns(oldProviders);\n            actionDescriptor.Setup(ad => ad.SupportedHttpMethods).Returns(new Collection<HttpMethod>());\n            actionDescriptor.CallBase = true;\n\n            actionDescriptor.Object.ControllerDescriptor = controllerDescriptor;\n\n            return actionDescriptor.Object;\n        }\n\n        private static IHttpControllerSelector CreateControllerSelector(IEnumerable<HttpControllerDescriptor> controllerDescriptors)\n        {\n            Mock<IHttpControllerSelector> controllerSelector = new Mock<IHttpControllerSelector>();\n            controllerSelector.Setup(c => c.GetControllerMapping()).Returns(controllerDescriptors.ToDictionary(cd => cd.ControllerName));\n            return controllerSelector.Object;\n        }\n\n        private static IHttpActionSelector CreateActionSelector(Dictionary<HttpControllerDescriptor, IEnumerable<HttpActionDescriptor>> actionMap)\n        {\n            Mock<IHttpActionSelector> actionSelector = new Mock<IHttpActionSelector>();\n            foreach (var mapEntry in actionMap)\n            {\n                actionSelector.Setup(a => a.GetActionMapping(mapEntry.Key)).Returns(mapEntry.Value.ToLookup(ad => ad.ActionName));\n            }\n            return actionSelector.Object;\n        }\n\n        public class TestParameter\n        {\n        }\n\n        [ActionSelectorConfiguration]\n        public class PerControllerActionSelectorController : ApiController { }\n\n        public class ActionSelectorConfigurationAttribute : Attribute, IControllerConfiguration\n        {\n            public static Mock<IHttpActionSelector> PerControllerActionSelectorMock = new Mock<IHttpActionSelector>();\n\n            public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)\n            {\n                controllerSettings.Services.Replace(typeof(IHttpActionSelector), PerControllerActionSelectorMock.Object);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/HttpErrorKeysTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http\n{\n    public class HttpErrorKeysTest\n    {\n        public static TheoryDataSet<Func<string>, string> ErrorKeys\n        {\n            get\n            {\n                return new TheoryDataSet<Func<string>, string>\n                {\n                    { () => HttpErrorKeys.MessageKey, \"Message\" },\n                    { () => HttpErrorKeys.MessageDetailKey, \"MessageDetail\" },\n                    { () => HttpErrorKeys.ModelStateKey, \"ModelState\" },\n                    { () => HttpErrorKeys.ExceptionMessageKey, \"ExceptionMessage\" },\n                    { () => HttpErrorKeys.ExceptionTypeKey, \"ExceptionType\" },\n                    { () => HttpErrorKeys.StackTraceKey, \"StackTrace\" },\n                    { () => HttpErrorKeys.InnerExceptionKey, \"InnerException\" },\n                    { () => HttpErrorKeys.MessageLanguageKey, \"MessageLanguage\" },\n                    { () => HttpErrorKeys.ErrorCodeKey, \"ErrorCode\" }\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"ErrorKeys\")]\n        public void HttpErrorKeyProperties_Returns_CorrectKeys(Func<string> productUnderTest, string expectedResult)\n        {\n            // Act\n            string actualResult = productUnderTest.Invoke();\n\n            // Assert\n            Assert.Equal(expectedResult, actualResult);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/HttpMessageHandlerExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace System.Web.Http\n{\n    public static class HttpMessageHandlerExtensions\n    {\n        public static Task<HttpResponseMessage> SendAsync(this HttpMessageHandler handler, HttpRequestMessage request,\n            CancellationToken cancellationToken)\n        {\n            using (HttpMessageInvoker invoker = new HttpMessageInvoker(handler, disposeHandler: false))\n            {\n                return invoker.SendAsync(request, cancellationToken);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/HttpRequestMessageExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Formatting.Mocks;\nusing System.Net.Http.Headers;\nusing System.Security.Cryptography.X509Certificates;\nusing System.Threading;\nusing System.Web.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.Routing;\nusing System.Web.Http.Services;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Net.Http\n{\n    public class HttpRequestMessageExtensionsTest\n    {\n        [Fact]\n        public void GetRequestContext_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            HttpRequestMessage request = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => request.GetRequestContext(), \"request\");\n        }\n\n        [Fact]\n        public void GetRequestContext_ReturnsProperty()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext expectedContext = CreateContext();\n                request.Properties[HttpPropertyKeys.RequestContextKey] = expectedContext;\n\n                // Act\n                HttpRequestContext context = request.GetRequestContext();\n\n                // Assert\n                Assert.Same(expectedContext, context);\n            }\n        }\n\n        [Fact]\n        public void SetRequestContext_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            HttpRequestMessage request = null;\n            HttpRequestContext context = CreateContext();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { request.SetRequestContext(context); }, \"request\");\n        }\n\n        [Fact]\n        public void SetRequestContext_Throws_WhenContextIsNull()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = null;\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() => { request.SetRequestContext(context); }, \"context\");\n            }\n        }\n\n        [Fact]\n        public void SetRequestContext_AddsProperty()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext expectedContext = CreateContext();\n\n                // Act\n                request.SetRequestContext(expectedContext);\n\n                // Assert\n                Assert.Same(expectedContext, request.Properties[HttpPropertyKeys.RequestContextKey]);\n            }\n        }\n\n        [Fact]\n        public void GetConfigurationThrowsOnNull()\n        {\n            HttpRequestMessage request = null;\n            Assert.ThrowsArgumentNull(() => request.GetConfiguration(), \"request\");\n        }\n\n        [Fact]\n        public void GetConfiguration_ReturnsConfigurationFromContext_WhenOnlyContextIsPresent()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            using (HttpConfiguration expectedConfiguration = CreateConfiguration())\n            {\n                request.SetRequestContext(new HttpRequestContext\n                {\n                    Configuration = expectedConfiguration\n                });\n\n                // Act\n                HttpConfiguration configuration = request.GetConfiguration();\n\n                // Assert\n                Assert.Same(expectedConfiguration, configuration);\n            }\n        }\n\n        [Fact]\n        public void GetConfiguration_ReturnsConfigurationFromProperty_WhenOnlyPropertyIsPresent()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            using (HttpConfiguration expectedConfiguration = CreateConfiguration())\n            {\n                request.Properties[HttpPropertyKeys.HttpConfigurationKey] = expectedConfiguration;\n\n                // Act\n                HttpConfiguration configuration = request.GetConfiguration();\n\n                // Assert\n                Assert.Same(expectedConfiguration, configuration);\n            }\n        }\n\n        [Fact]\n        public void GetConfiguration_ReturnsConfigurationFromContext_WhenBothContextAndPropertyArePresent()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            using (HttpConfiguration expectedConfiguration = CreateConfiguration())\n            using (HttpConfiguration otherConfiguration = CreateConfiguration())\n            {\n                request.Properties[HttpPropertyKeys.HttpConfigurationKey] = otherConfiguration;\n                request.SetRequestContext(new HttpRequestContext\n                {\n                    Configuration = expectedConfiguration\n                });\n\n                // Act\n                HttpConfiguration configuration = request.GetConfiguration();\n\n                // Assert\n                Assert.Same(expectedConfiguration, configuration);\n            }\n        }\n\n        [Fact]\n        public void SetConfiguration_ThrowsArgumentNull_Request()\n        {\n            HttpRequestMessage request = null;\n\n            Assert.ThrowsArgumentNull(\n                () => request.SetConfiguration(CreateConfiguration()),\n                \"request\");\n        }\n\n        [Fact]\n        public void SetConfiguration_ThrowsArgumentNull_Configuration()\n        {\n            HttpRequestMessage request = CreateRequest();\n\n            Assert.ThrowsArgumentNull(\n                () => request.SetConfiguration(null),\n                \"configuration\");\n        }\n\n        [Fact]\n        public void SetConfiguration_AddsProperty()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            using (HttpConfiguration expectedConfiguration = CreateConfiguration())\n            {\n                // Act\n                request.SetConfiguration(expectedConfiguration);\n\n                // Assert\n                Assert.Same(expectedConfiguration, request.Properties[HttpPropertyKeys.HttpConfigurationKey]);\n            }\n        }\n\n        [Fact]\n        public void SetConfiguration_UpdatesContextAndAddsProperty_WhenContextIsPresent()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            using (HttpConfiguration expectedConfiguration = CreateConfiguration())\n            {\n                HttpRequestContext context = CreateContext();\n                request.SetRequestContext(context);\n\n                // Act\n                request.SetConfiguration(expectedConfiguration);\n\n                // Assert\n                Assert.Same(expectedConfiguration, context.Configuration);\n                Assert.Same(expectedConfiguration, request.Properties[HttpPropertyKeys.HttpConfigurationKey]);\n            }\n        }\n\n        [Fact]\n        public void GetSynchronizationContextThrowsOnNull()\n        {\n            HttpRequestMessage request = null;\n            Assert.ThrowsArgumentNull(() => request.GetSynchronizationContext(), \"request\");\n        }\n\n        [Fact]\n        public void GetSynchronizationContext()\n        {\n            // Arrange\n            HttpRequestMessage request = CreateRequest();\n            Mock<SynchronizationContext> syncContextMock = new Mock<SynchronizationContext>();\n            SynchronizationContext beforeSyncContext = syncContextMock.Object;\n            request.Properties.Add(HttpPropertyKeys.SynchronizationContextKey, beforeSyncContext);\n\n            // Act\n            SynchronizationContext afterSyncContext = request.GetSynchronizationContext();\n\n            // Assert\n            Assert.Same(beforeSyncContext, afterSyncContext);\n        }\n\n        [Fact]\n        public void GetRouteData_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            HttpRequestMessage request = null;\n\n            // Act\n            Assert.ThrowsArgumentNull(() => request.GetRouteData(), \"request\");\n        }\n\n        [Fact]\n        public void GetRouteData_ReturnsRouteDataFromContext_WhenOnlyContextIsPresent()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IHttpRouteData expectedRouteData = CreateDummyRouteData();\n                request.SetRequestContext(new HttpRequestContext\n                {\n                    RouteData = expectedRouteData\n                });\n\n                // Act\n                IHttpRouteData routeData = request.GetRouteData();\n\n                // Assert\n                Assert.Same(expectedRouteData, routeData);\n            }\n        }\n\n        [Fact]\n        public void GetRouteData_ReturnsRouteDataFromProperty_WhenOnlyPropertyIsPresent()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IHttpRouteData expectedRouteData = CreateDummyRouteData();\n                request.Properties[HttpPropertyKeys.HttpRouteDataKey] = expectedRouteData;\n\n                // Act\n                IHttpRouteData routeData = request.GetRouteData();\n\n                // Assert\n                Assert.Same(expectedRouteData, routeData);\n            }\n        }\n\n        [Fact]\n        public void GetRouteData_ReturnsRouteDataFromContext_WhenBothContextAndPropertyArePresent()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IHttpRouteData expectedRouteData = CreateDummyRouteData();\n                request.SetRequestContext(new HttpRequestContext\n                {\n                    RouteData = expectedRouteData\n                });\n                IHttpRouteData otherRouteData = CreateDummyRouteData();\n                request.Properties[HttpPropertyKeys.HttpRouteDataKey] = otherRouteData;\n\n                // Act\n                IHttpRouteData routeData = request.GetRouteData();\n\n                // Assert\n                Assert.Same(expectedRouteData, routeData);\n            }\n        }\n\n        [Fact]\n        public void SetRouteData_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            HttpRequestMessage request = null;\n            IHttpRouteData routeData = CreateDummyRouteData();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => request.SetRouteData(routeData), \"request\");\n        }\n\n        [Fact]\n        public void SetRouteData_Throws_WhenRouteDataIsNull()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IHttpRouteData routeData = null;\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() => request.SetRouteData(routeData), \"routeData\");\n            }\n        }\n\n        [Fact]\n        public void SetRouteData_AddsProperty()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IHttpRouteData expectedRouteData = CreateDummyRouteData();\n\n                // Act\n                request.SetRouteData(expectedRouteData);\n\n                // Assert\n                Assert.Same(expectedRouteData, request.Properties[HttpPropertyKeys.HttpRouteDataKey]);\n            }\n        }\n\n        [Fact]\n        public void SetRouteData_UpdatesContextAndAddsProperty_WhenContextIsPresent()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateContext();\n                request.SetRequestContext(context);\n                IHttpRouteData expectedRouteData = CreateDummyRouteData();\n\n                // Act\n                request.SetRouteData(expectedRouteData);\n\n                // Assert\n                Assert.Same(expectedRouteData, context.RouteData);\n                Assert.Same(expectedRouteData, request.Properties[HttpPropertyKeys.HttpRouteDataKey]);\n            }\n        }\n\n        [Fact]\n        public void GetUrlHelper_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            HttpRequestMessage request = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => request.GetUrlHelper(), \"request\");\n        }\n\n        [Fact]\n        public void GetUrlHelper_ReturnsUrlFromContext_WhenContextIsPresent()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                UrlHelper expectedUrl = new Mock<UrlHelper>().Object;\n                request.SetRequestContext(new HttpRequestContext\n                {\n                    Url = expectedUrl\n                });\n\n                // Act\n                UrlHelper url = request.GetUrlHelper();\n\n                // Assert\n                Assert.Same(expectedUrl, url);\n            }\n        }\n\n        [Fact]\n        public void GetUrlHelper_ReturnsNewUrlHelperForRequest_WhenContextIsAbsent()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                // Act\n                UrlHelper urlHelper = request.GetUrlHelper();\n\n                // Assert\n                Assert.NotNull(urlHelper);\n                Assert.Same(request, urlHelper.Request);\n            }\n        }\n\n        [Fact]\n        public void GetClientCertificate_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            HttpRequestMessage request = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => request.GetClientCertificate(), \"request\");\n        }\n\n        [Fact]\n        public void GetClientCertificate_ReturnsClientCertificateFromContext_WhenOnlyContextIsPresent()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                X509Certificate2 expectedCertificate = CreateCertificate();\n                request.SetRequestContext(new HttpRequestContext\n                {\n                    ClientCertificate = expectedCertificate\n                });\n\n                // Act\n                X509Certificate2 certificate = request.GetClientCertificate();\n\n                // Assert\n                Assert.Same(expectedCertificate, certificate);\n            }\n        }\n\n        [Fact]\n        public void GetClientCertificate_ReturnsClientCertificateFromProperty_WhenOnlyPropertyIsPresent()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                X509Certificate2 expectedCertificate = CreateCertificate();\n                request.Properties[HttpPropertyKeys.ClientCertificateKey] = expectedCertificate;\n\n                // Act\n                X509Certificate2 certificate = request.GetClientCertificate();\n\n                // Assert\n                Assert.Same(expectedCertificate, certificate);\n            }\n        }\n\n        [Fact]\n        public void GetClientCertificate_ReturnsClientCertificateFromContext_WhenBothContextAndPropertyArePresent()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                X509Certificate2 expectedCertificate = CreateCertificate();\n                request.SetRequestContext(new HttpRequestContext\n                {\n                    ClientCertificate = expectedCertificate\n                });\n                X509Certificate2 otherCertificate = CreateCertificate();\n                request.Properties[HttpPropertyKeys.ClientCertificateKey] = otherCertificate;\n\n                // Act\n                X509Certificate2 certificate = request.GetClientCertificate();\n\n                // Assert\n                Assert.Same(expectedCertificate, certificate);\n            }\n        }\n\n        [Fact]\n        public void CreateResponse_OnNullRequest_ThrowsException()\n        {\n            HttpRequestMessage request = null;\n            Assert.ThrowsArgumentNull(() =>\n            {\n                request.CreateResponse(CreateValue());\n            }, \"request\");\n\n            Assert.ThrowsArgumentNull(() =>\n            {\n                request.CreateResponse(HttpStatusCode.OK, CreateValue());\n            }, \"request\");\n\n            Assert.ThrowsArgumentNull(() =>\n            {\n                request.CreateResponse(HttpStatusCode.OK, CreateValue(), configuration: null);\n            }, \"request\");\n        }\n\n        [Fact]\n        public void CreateResponse_OnNullConfiguration_ThrowsException()\n        {\n            HttpRequestMessage request = CreateRequest();\n            request.Properties[HttpPropertyKeys.HttpConfigurationKey] = null;\n\n            Assert.Throws<InvalidOperationException>(() =>\n            {\n                request.CreateResponse(CreateValue());\n            }, \"The request does not have an associated configuration object or the provided configuration was null.\");\n\n            Assert.Throws<InvalidOperationException>(() =>\n            {\n                request.CreateResponse(HttpStatusCode.OK, CreateValue(), configuration: null);\n            }, \"The request does not have an associated configuration object or the provided configuration was null.\");\n        }\n\n        [Fact]\n        public void CreateResponse_DoingConneg_OnlyContent_RetrievesContentNegotiatorFromServiceResolver()\n        {\n            // Arrange\n            HttpRequestMessage request = CreateRequest();\n            HttpConfiguration config = CreateAndAddConfiguration(request);\n            Mock<DefaultServices> servicesMock = new Mock<DefaultServices> { CallBase = true };\n            servicesMock.Setup(s => s.GetService(typeof(IContentNegotiator)))\n                        .Returns(new Mock<IContentNegotiator>().Object)\n                        .Verifiable();\n            config.Services = servicesMock.Object;\n\n            // Act\n            request.CreateResponse(CreateValue());\n\n            // Assert\n            servicesMock.Verify();\n        }\n\n        [Fact]\n        public void CreateResponse_DoingConneg_RetrievesContentNegotiatorFromServiceResolver()\n        {\n            // Arrange\n            HttpRequestMessage request = CreateRequest();\n            HttpConfiguration config = CreateAndAddConfiguration(request);\n            Mock<DefaultServices> servicesMock = new Mock<DefaultServices> { CallBase = true };\n            servicesMock.Setup(s => s.GetService(typeof(IContentNegotiator)))\n                        .Returns(new Mock<IContentNegotiator>().Object)\n                        .Verifiable();\n            config.Services = servicesMock.Object;\n\n            // Act\n            request.CreateResponse(HttpStatusCode.OK, CreateValue(), config);\n\n            // Assert\n            servicesMock.Verify();\n        }\n\n        [Fact]\n        public void CreateResponse_DoingConneg_WhenNoContentNegotiatorInstanceRegistered_Throws()\n        {\n            // Arrange\n            HttpRequestMessage request = CreateRequest();\n            HttpConfiguration config = CreateAndAddConfiguration(request);\n            config.Services.Clear(typeof(IContentNegotiator));\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(() => request.CreateResponse(CreateValue()),\n                \"The provided configuration does not have an instance of the 'System.Net.Http.Formatting.IContentNegotiator' service registered.\");\n\n            Assert.Throws<InvalidOperationException>(() => request.CreateResponse(HttpStatusCode.OK, CreateValue(), config),\n                \"The provided configuration does not have an instance of the 'System.Net.Http.Formatting.IContentNegotiator' service registered.\");\n        }\n\n        [Fact]\n        public void CreateResponse_DoingConneg_WhenContentNegotiatorReturnsNullResult_Throws()\n        {\n            // Arrange\n            HttpRequestMessage request = CreateRequest();\n            HttpConfiguration config = CreateAndAddConfiguration(request);\n            Mock<IContentNegotiator> negotiatorMock = new Mock<IContentNegotiator>();\n            negotiatorMock.Setup(r => r.Negotiate(typeof(string), request, config.Formatters)).Returns(value: null);\n            config.Services.Replace(typeof(IContentNegotiator), negotiatorMock.Object);\n\n            // Act\n            var response = request.CreateResponse<string>(HttpStatusCode.OK, \"\", config);\n\n            // Assert\n            Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);\n            Assert.Same(request, response.RequestMessage);\n        }\n\n        [Fact]\n        public void CreateResponse_DoingConneg_PerformsContentNegotiationAndCreatesContentUsingResults()\n        {\n            // Arrange\n            HttpRequestMessage request = CreateRequest();\n            HttpConfiguration config = CreateAndAddConfiguration(request);\n            XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter();\n            Mock<IContentNegotiator> negotiatorMock = new Mock<IContentNegotiator>();\n            negotiatorMock.Setup(r => r.Negotiate(typeof(string), request, config.Formatters))\n                        .Returns(new ContentNegotiationResult(formatter, null));\n            config.Services.Replace(typeof(IContentNegotiator), negotiatorMock.Object);\n\n            // Act\n            var response = request.CreateResponse<string>(HttpStatusCode.NoContent, \"42\", config);\n\n            // Assert\n            Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);\n            Assert.Same(request, response.RequestMessage);\n            var objectContent = Assert.IsType<ObjectContent<string>>(response.Content);\n            Assert.Equal(\"42\", objectContent.Value);\n            Assert.Same(formatter, objectContent.Formatter);\n        }\n\n        [Fact]\n        public void CreateResponse_MatchingMediaType_WhenRequestIsNull_Throws()\n        {\n            // Arrange\n            HttpRequestMessage request = null;\n\n            // Act\n            Assert.ThrowsArgumentNull(() => request.CreateResponse(HttpStatusCode.OK, CreateValue(), \"foo/bar\"), \"request\");\n        }\n\n        [Fact]\n        public void CreateResponse_MatchingMediaType_WhenMediaTypeHeaderIsNull_Throws()\n        {\n            HttpRequestMessage request = CreateRequest();\n\n            Assert.ThrowsArgumentNull(() => request.CreateResponse(HttpStatusCode.OK, CreateValue(), (MediaTypeHeaderValue)null), \"mediaType\");\n        }\n\n        [Fact]\n        public void CreateResponse_MatchingMediaType_WhenMediaTypeStringIsNull_Throws()\n        {\n            HttpRequestMessage request = CreateRequest();\n\n            Assert.ThrowsArgument(() => request.CreateResponse(HttpStatusCode.OK, CreateValue(), (string)null), \"mediaType\");\n        }\n\n        [Fact]\n        public void CreateResponse_MatchingMediaType_WhenMediaTypeStringIsEmpty_Throws()\n        {\n            HttpRequestMessage request = CreateRequest();\n\n            Assert.ThrowsArgumentNull(() => request.CreateResponse(HttpStatusCode.OK, CreateValue(), (MediaTypeHeaderValue)null), \"mediaType\");\n        }\n\n        [Fact]\n        public void CreateResponse_MatchingMediaType_WhenMediaTypeStringIsInvalidFormat_Throws()\n        {\n            HttpRequestMessage request = CreateRequest();\n\n            Assert.Throws<FormatException>(() => request.CreateResponse(HttpStatusCode.OK, CreateValue(), \"foo/bar; param=value\"), \"The format of value 'foo/bar; param=value' is invalid.\");\n        }\n\n        [Fact]\n        public void CreateResponse_MatchingMediaType_WhenRequestDoesNotHaveConfiguration_Throws()\n        {\n            HttpRequestMessage request = CreateRequest();\n\n            // Arrange\n            request.Properties[HttpPropertyKeys.HttpConfigurationKey] = null;\n\n            // Act\n            Assert.Throws<InvalidOperationException>(() => request.CreateResponse(HttpStatusCode.OK, CreateValue(), mediaType: \"foo/bar\"),\n                \"The request does not have an associated configuration object or the provided configuration was null.\");\n        }\n\n        [Fact]\n        public void CreateResponse_MatchingMediaType_WhenMediaTypeDoesNotMatch_Throws()\n        {\n            // Arrange\n            HttpRequestMessage request = CreateRequest();\n            request.SetConfiguration(new HttpConfiguration());\n\n            // Act\n            Assert.Throws<InvalidOperationException>(() => request.CreateResponse(HttpStatusCode.OK, CreateValue(), mediaType: \"foo/bar\"),\n                \"Could not find a formatter matching the media type 'foo/bar' that can write an instance of 'Object'.\");\n        }\n\n        [Fact]\n        public void CreateResponse_MatchingMediaType_FindsMatchingFormatterAndCreatesResponse()\n        {\n            // Arrange\n            HttpRequestMessage request = CreateRequest();\n            var config = new HttpConfiguration();\n            request.SetConfiguration(config);\n            config.Formatters.Clear();\n            Mock<MediaTypeFormatter> formatterMock = new Mock<MediaTypeFormatter> { CallBase = true };\n            var formatter = formatterMock.Object;\n            formatterMock.Setup(f => f.CanWriteType(typeof(object))).Returns(true).Verifiable();\n            formatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue(\"foo/bar\"));\n            config.Formatters.Add(formatter);\n            object expectedValue = CreateValue();\n\n            // Act\n            var response = request.CreateResponse(HttpStatusCode.Gone, expectedValue, mediaType: \"foo/bar\");\n\n            // Assert\n            Assert.Equal(HttpStatusCode.Gone, response.StatusCode);\n            var content = Assert.IsType<ObjectContent<object>>(response.Content);\n            Assert.Same(expectedValue, content.Value);\n            Assert.Same(formatter, content.Formatter);\n            Assert.Equal(\"foo/bar\", content.Headers.ContentType.MediaType);\n            formatterMock.Verify();\n        }\n\n        [Fact]\n        public void CreateResponse_AcceptingFormatter_WhenRequestIsNull_Throws()\n        {\n            // Arrange\n            HttpRequestMessage request = null;\n\n            // Act\n            Assert.ThrowsArgumentNull(() => request.CreateResponse(HttpStatusCode.OK, CreateValue(), new MockMediaTypeFormatter()), \"request\");\n        }\n\n        [Fact]\n        public void CreateResponse_AcceptingFormatter_WhenFormatterIsNull_Throws()\n        {\n            // Arrange\n            HttpRequestMessage request = CreateRequest();\n\n            // Act\n            Assert.ThrowsArgumentNull(() => request.CreateResponse(HttpStatusCode.OK, CreateValue(), formatter: null), \"formatter\");\n        }\n\n        [Fact]\n        public void CreateResponse_AcceptingFormatter_CreatesResponseWithDefaultMediaType()\n        {\n            // Arrange\n            HttpRequestMessage request = CreateRequest();\n            var formatter = new MockMediaTypeFormatter { CallBase = true };\n            formatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue(\"foo/bar\"));\n            object expectedValue = CreateValue();\n\n            // Act\n            var response = request.CreateResponse(HttpStatusCode.MultipleChoices, expectedValue, formatter, mediaType: (string)null);\n\n            // Assert\n            Assert.Equal(HttpStatusCode.MultipleChoices, response.StatusCode);\n            var content = Assert.IsType<ObjectContent<object>>(response.Content);\n            Assert.Same(expectedValue, content.Value);\n            Assert.Same(formatter, content.Formatter);\n            Assert.Equal(\"foo/bar\", content.Headers.ContentType.MediaType);\n        }\n\n        [Fact]\n        public void CreateResponse_AcceptingFormatter_WithOverridenMediaTypeString_CreatesResponse()\n        {\n            // Arrange\n            HttpRequestMessage request = CreateRequest();\n            var formatter = new MockMediaTypeFormatter { CallBase = true };\n            formatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue(\"foo/bar\"));\n\n            // Act\n            var response = request.CreateResponse(HttpStatusCode.MultipleChoices, CreateValue(), formatter, mediaType: \"bin/baz\");\n\n            // Assert\n            Assert.Equal(\"bin/baz\", response.Content.Headers.ContentType.MediaType);\n        }\n\n        [Fact]\n        public void CreateResponse_AcceptingFormatter_WithOverridenMediaTypeHeader_CreatesResponse()\n        {\n            // Arrange\n            HttpRequestMessage request = CreateRequest();\n            var formatter = new MockMediaTypeFormatter { CallBase = true };\n            formatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue(\"foo/bar\"));\n\n            // Act\n            var response = request.CreateResponse(HttpStatusCode.MultipleChoices, CreateValue(), formatter, mediaType: new MediaTypeHeaderValue(\"bin/baz\"));\n\n            // Assert\n            Assert.Equal(\"bin/baz\", response.Content.Headers.ContentType.MediaType);\n        }\n\n        [Fact]\n        public void RegisterForDispose_WhenRequestParameterIsNull_Throws()\n        {\n            HttpRequestMessage request = null;\n            Assert.ThrowsArgumentNull(() => request.RegisterForDispose(resource: null), \"request\");\n        }\n\n        [Fact]\n        public void RegisterForDispose_WhenResourceParamterIsNull_DoesNothing()\n        {\n            HttpRequestMessage request = CreateRequest();\n            request.RegisterForDispose(resource: null);\n\n            Assert.False(request.Properties.ContainsKey(HttpPropertyKeys.DisposableRequestResourcesKey));\n        }\n\n        [Fact]\n        public void RegisterForDispose_WhenResourceListDoesNotExist_CreatesListAndAddsResource()\n        {\n            HttpRequestMessage request = CreateRequest();\n            request.Properties.Remove(HttpPropertyKeys.DisposableRequestResourcesKey);\n            IDisposable disposable = CreateStubDisposable();\n\n            request.RegisterForDispose(disposable);\n\n            var list = Assert.IsType<List<IDisposable>>(request.Properties[HttpPropertyKeys.DisposableRequestResourcesKey]);\n            IDisposable item = Assert.Single(list);\n            Assert.Same(disposable, item);\n        }\n\n        [Fact]\n        public void RegisterForDispose_WhenResourceListExists_AddsResource()\n        {\n            HttpRequestMessage request = CreateRequest();\n            var list = new List<IDisposable>();\n            request.Properties[HttpPropertyKeys.DisposableRequestResourcesKey] = list;\n            IDisposable disposable = CreateStubDisposable();\n\n            request.RegisterForDispose(disposable);\n\n            Assert.Same(list, request.Properties[HttpPropertyKeys.DisposableRequestResourcesKey]);\n            IDisposable item = Assert.Single(list);\n            Assert.Same(disposable, item);\n        }\n\n        [Fact]\n        public void DisposeRequestResources_WhenRequestParameterIsNull_Throws()\n        {\n            HttpRequestMessage request = null;\n            Assert.ThrowsArgumentNull(() => request.DisposeRequestResources(), \"request\");\n        }\n\n        [Fact]\n        public void DisposeRequestResources_WhenResourceListDoesNotExists_DoesNothing()\n        {\n            HttpRequestMessage request = CreateRequest();\n            request.Properties.Remove(HttpPropertyKeys.DisposableRequestResourcesKey);\n\n            request.DisposeRequestResources();\n\n            Assert.False(request.Properties.ContainsKey(HttpPropertyKeys.DisposableRequestResourcesKey));\n        }\n\n        [Fact]\n        public void DisposeRequestResources_WhenResourceListExists_DisposesResourceAndClearsReferences()\n        {\n            HttpRequestMessage request = CreateRequest();\n            Mock<IDisposable> disposableMock = new Mock<IDisposable>();\n            IDisposable disposable = disposableMock.Object;\n            var list = new List<IDisposable> { disposable };\n            request.Properties[HttpPropertyKeys.DisposableRequestResourcesKey] = list;\n\n            request.DisposeRequestResources();\n\n            disposableMock.Verify(d => d.Dispose());\n            Assert.Empty(list);\n        }\n\n        [Fact]\n        public void DisposeRequestResources_WhenResourcesDisposeMethodThrowsException_IgnoresExceptionsAndContinuesDisposingOtherResources()\n        {\n            HttpRequestMessage request = CreateRequest();\n            Mock<IDisposable> throwingDisposableMock = new Mock<IDisposable>();\n            throwingDisposableMock.Setup(d => d.Dispose()).Throws(new Exception());\n            Mock<IDisposable> disposableMock = new Mock<IDisposable>();\n            IDisposable disposable = disposableMock.Object;\n            var list = new List<IDisposable> { throwingDisposableMock.Object, disposable };\n            request.Properties[HttpPropertyKeys.DisposableRequestResourcesKey] = list;\n\n            request.DisposeRequestResources();\n\n            throwingDisposableMock.Verify(d => d.Dispose());\n            disposableMock.Verify(d => d.Dispose());\n            Assert.Empty(list);\n        }\n\n        [Fact]\n        public void CreateErrorResponseRangeNotSatisfiable_ThrowsOnNullException()\n        {\n            HttpRequestMessage request = CreateRequest();\n            Assert.ThrowsArgumentNull(() => request.CreateErrorResponse(invalidByteRangeException: null), \"invalidByteRangeException\");\n        }\n\n        [Fact]\n        public void CreateErrorResponseRangeNotSatisfiable_SetsCorrectStatusCodeAndContentRangeHeader()\n        {\n            // Arrange\n            HttpRequestMessage request = CreateRequest();\n            ContentRangeHeaderValue expectedContentRange = new ContentRangeHeaderValue(length: 128);\n            InvalidByteRangeException invalidByteRangeException = new InvalidByteRangeException(expectedContentRange);\n\n            // Act\n            HttpResponseMessage response = request.CreateErrorResponse(invalidByteRangeException);\n\n            // Assert\n            Assert.Equal(HttpStatusCode.RequestedRangeNotSatisfiable, response.StatusCode);\n            Assert.Same(expectedContentRange, response.Content.Headers.ContentRange);\n        }\n\n        [Fact]\n        public void IsLocal_When_Request_From_Local_Address()\n        {\n            // Arrange\n            HttpRequestMessage request = CreateRequest();\n            request.Properties.Add(HttpPropertyKeys.IsLocalKey, new Lazy<bool>(() => true));\n\n            // Act\n            bool isLocal = request.IsLocal();\n\n            // Assert\n            Assert.True(isLocal);\n        }\n\n        [Fact]\n        public void IsLocal_When_Request_Not_From_Local_Address()\n        {\n            // Arrange\n            HttpRequestMessage request = CreateRequest();\n            request.Properties.Add(HttpPropertyKeys.IsLocalKey, new Lazy<bool>(() => false));\n\n            // Act\n            bool isLocal = request.IsLocal();\n\n            // Assert\n            Assert.False(isLocal);\n        }\n\n        [Fact]\n        public void IsLocal_With_Property_Value_Null_Returns_False()\n        {\n            // Arrange\n            HttpRequestMessage request = CreateRequest();\n            request.Properties.Add(HttpPropertyKeys.IsLocalKey, null);\n\n            // Act\n            bool isLocal = request.IsLocal();\n\n            // Assert\n            Assert.False(isLocal);\n        }\n\n        [Fact]\n        public void IsLocal_With_Property_Value_String_Returns_False()\n        {\n            // Arrange\n            HttpRequestMessage request = CreateRequest();\n            request.Properties.Add(HttpPropertyKeys.IsLocalKey, \"Test String\");\n\n            // Act\n            bool isLocal = request.IsLocal();\n\n            // Assert\n            Assert.False(isLocal);\n        }\n\n        [Fact]\n        public void IsLocal_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            HttpRequestMessage request = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => request.IsLocal(), \"request\");\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void IsLocal_ReturnsValueFromContext_WhenOnlyContextIsPresent(bool expectedIsLocal)\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                request.SetRequestContext(new HttpRequestContext\n                {\n                    IsLocal = expectedIsLocal\n                });\n\n                // Act\n                bool isLocal = request.IsLocal();\n\n                // Assert\n                Assert.Equal(expectedIsLocal, isLocal);\n            }\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void IsLocal_ReturnsValueFromProperty_WhenOnlyPropertyIsPresent(bool expectedIsLocal)\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                request.Properties[HttpPropertyKeys.IsLocalKey] = new Lazy<bool>(() => expectedIsLocal);\n\n                // Act\n                bool isLocal = request.IsLocal();\n\n                // Assert\n                Assert.Equal(expectedIsLocal, isLocal);\n            }\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void IsLocal_ReturnsValueFromContext_WhenBothContextAndPropertyArePresent(bool expectedIsLocal)\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                request.SetRequestContext(new HttpRequestContext\n                {\n                    IsLocal = expectedIsLocal\n                });\n                request.Properties[HttpPropertyKeys.IsLocalKey] = new Lazy<bool>(() => !expectedIsLocal);\n\n                // Act\n                bool isLocal = request.IsLocal();\n\n                // Assert\n                Assert.Equal(expectedIsLocal, isLocal);\n            }\n        }\n\n        [Fact]\n        public void IsLocal_ReturnsFalse_WhenNeitherContextNorPropertyArePresent()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                // Act\n                bool isLocal = request.IsLocal();\n\n                // Assert\n                Assert.False(isLocal);\n            }\n        }\n\n        [Fact]\n        public void ShouldIncludeErrorDetail_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            HttpRequestMessage request = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => request.ShouldIncludeErrorDetail(), \"request\");\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void ShouldIncludeErrorDetail_ReturnsValueFromContext_WhenOnlyContextIsPresent(bool expected)\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                request.SetRequestContext(new HttpRequestContext\n                {\n                    IncludeErrorDetail = expected\n                });\n\n                // Act\n                bool actual = request.ShouldIncludeErrorDetail();\n\n                // Assert\n                Assert.Equal(expected, actual);\n            }\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void ShouldIncludeErrorDetail_ReturnsValueFromProperty_WhenOnlyPropertyIsPresent(bool expected)\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                request.Properties[HttpPropertyKeys.IncludeErrorDetailKey] = new Lazy<bool>(() => expected);\n\n                // Act\n                bool actual = request.ShouldIncludeErrorDetail();\n\n                // Assert\n                Assert.Equal(expected, actual);\n            }\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void ShouldIncludeErrorDetail_ReturnsValueFromContext_WhenBothArePresent(bool expected)\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                request.SetRequestContext(new HttpRequestContext\n                {\n                    IncludeErrorDetail = expected\n                });\n                request.Properties[HttpPropertyKeys.IncludeErrorDetailKey] = new Lazy<bool>(() => !expected);\n\n                // Act\n                bool actual = request.ShouldIncludeErrorDetail();\n\n                // Assert\n                Assert.Equal(expected, actual);\n            }\n        }\n\n        [Theory]\n        [InlineData(IncludeErrorDetailPolicy.Default, null, null, false)]\n        [InlineData(IncludeErrorDetailPolicy.Default, null, true, true)]\n        [InlineData(IncludeErrorDetailPolicy.Default, null, false, false)]\n        [InlineData(IncludeErrorDetailPolicy.Default, true, null, false)]\n        [InlineData(IncludeErrorDetailPolicy.Default, true, true, true)]\n        [InlineData(IncludeErrorDetailPolicy.Default, true, false, false)]\n        [InlineData(IncludeErrorDetailPolicy.Default, false, null, false)]\n        [InlineData(IncludeErrorDetailPolicy.Default, false, true, true)]\n        [InlineData(IncludeErrorDetailPolicy.Default, false, false, false)]\n        [InlineData(IncludeErrorDetailPolicy.LocalOnly, null, null, false)]\n        [InlineData(IncludeErrorDetailPolicy.LocalOnly, null, true, false)]\n        [InlineData(IncludeErrorDetailPolicy.LocalOnly, null, false, false)]\n        [InlineData(IncludeErrorDetailPolicy.LocalOnly, true, null, true)]\n        [InlineData(IncludeErrorDetailPolicy.LocalOnly, true, true, true)]\n        [InlineData(IncludeErrorDetailPolicy.LocalOnly, true, false, true)]\n        [InlineData(IncludeErrorDetailPolicy.LocalOnly, false, null, false)]\n        [InlineData(IncludeErrorDetailPolicy.LocalOnly, false, true, false)]\n        [InlineData(IncludeErrorDetailPolicy.LocalOnly, false, false, false)]\n        [InlineData(IncludeErrorDetailPolicy.Always, null, null, true)]\n        [InlineData(IncludeErrorDetailPolicy.Always, null, true, true)]\n        [InlineData(IncludeErrorDetailPolicy.Always, null, false, true)]\n        [InlineData(IncludeErrorDetailPolicy.Always, true, null, true)]\n        [InlineData(IncludeErrorDetailPolicy.Always, true, true, true)]\n        [InlineData(IncludeErrorDetailPolicy.Always, true, false, true)]\n        [InlineData(IncludeErrorDetailPolicy.Always, false, null, true)]\n        [InlineData(IncludeErrorDetailPolicy.Always, false, true, true)]\n        [InlineData(IncludeErrorDetailPolicy.Always, false, false, true)]\n        [InlineData(IncludeErrorDetailPolicy.Never, null, null, false)]\n        [InlineData(IncludeErrorDetailPolicy.Never, null, true, false)]\n        [InlineData(IncludeErrorDetailPolicy.Never, null, false, false)]\n        [InlineData(IncludeErrorDetailPolicy.Never, true, null, false)]\n        [InlineData(IncludeErrorDetailPolicy.Never, true, true, false)]\n        [InlineData(IncludeErrorDetailPolicy.Never, true, false, false)]\n        [InlineData(IncludeErrorDetailPolicy.Never, false, null, false)]\n        [InlineData(IncludeErrorDetailPolicy.Never, false, true, false)]\n        [InlineData(IncludeErrorDetailPolicy.Never, false, false, false)]\n        [InlineData(null, false, false, false)]\n        public void ShouldIncludeErrorDetail_WhenContextIsAbsent(IncludeErrorDetailPolicy errorDetail, bool isLocal, bool includeErrorDetail, bool expectedResult)\n        {\n            // Arrange\n            HttpRequestMessage request = CreateRequest();\n            HttpConfiguration config = CreateAndAddConfiguration(request);\n            config.IncludeErrorDetailPolicy = errorDetail;\n            request.Properties.Add(HttpPropertyKeys.IsLocalKey, new Lazy<bool>(() => isLocal));\n            request.Properties.Add(HttpPropertyKeys.IncludeErrorDetailKey, new Lazy<bool>(() => includeErrorDetail));\n\n            // Act\n            bool includeError = request.ShouldIncludeErrorDetail();\n\n            // Assert\n            Assert.Equal(includeError, expectedResult);\n        }\n\n        [Fact]\n        public void ShouldIncludeErrorDetail_Returns_False_WhenConfigIsNull_includeErrorDetail_Null()\n        {\n            // Arrange\n            HttpRequestMessage request = CreateRequest();\n\n            // Act\n            bool includeError = request.ShouldIncludeErrorDetail();\n\n            // Assert\n            Assert.False(includeError);\n        }\n\n        [Fact]\n        public void ShouldIncludeErrorDetail_Returns_Value_WhenConfigIsNull_includeErrorDetail_HasValue()\n        {\n            // Arrange\n            HttpRequestMessage request = CreateRequest();\n            request.Properties.Add(HttpPropertyKeys.IncludeErrorDetailKey, new Lazy<bool>(() => true));\n\n            // Act\n            bool includeError = request.ShouldIncludeErrorDetail();\n\n            // Assert\n            Assert.True(includeError);\n        }\n\n        [Fact]\n        public void GetCorrelationId_ReturnsTraceCorrelationManagerId_IfSet()\n        {\n            Guid traceId = Guid.NewGuid();\n            using (var scope = new TraceIdScope(traceId))\n            {\n                Assert.Equal(traceId, CreateRequest().GetCorrelationId());\n            }\n        }\n\n        [Fact]\n        public void GetCorrelationId_ReturnsNewGuid_IfTraceCorrelationManagerIdNotSet()\n        {\n            Guid traceId = Guid.Empty;\n            using (var scope = new TraceIdScope(traceId))\n            {\n                Assert.NotEqual(traceId, CreateRequest().GetCorrelationId());\n            }\n        }\n\n        [Fact]\n        public void GetQueryNameValuePairs_ParsesQueryString()\n        {\n            // Arrange\n            var request = CreateRequest();\n            request.RequestUri = new Uri(\"http://localhost/api/Person/10?x=7&y=cool\");\n\n            // Act\n            var actual = request.GetQueryNameValuePairs();\n\n            // Assert\n            Assert.IsType<KeyValuePair<string, string>[]>(actual); // We call ToArray to ensure that we're not caching an iterator block.\n\n            Assert.Single(actual, kvp => kvp.Key == \"x\" && kvp.Value == \"7\");\n            Assert.Single(actual, kvp => kvp.Key == \"y\" && kvp.Value == \"cool\");\n        }\n\n        [Fact]\n        public void GetQueryNameValuePairs_StoresResult()\n        {\n            // Arrange\n            var request = CreateRequest();\n            request.RequestUri = new Uri(\"http://localhost/api/Person/10?x=7&y=cool\");\n\n            // Act\n            var returned = request.GetQueryNameValuePairs();\n\n            // Assert\n            IEnumerable<KeyValuePair<string, string>> cached;\n            Assert.True(request.Properties.TryGetValue<IEnumerable<KeyValuePair<string, string>>>(HttpPropertyKeys.RequestQueryNameValuePairsKey, out cached));\n\n            Assert.Same(returned, cached);\n            Assert.Same(returned, request.GetQueryNameValuePairs());\n        }\n\n        [Fact]\n        public void GetQueryNameValuePairs_ReplacesResultWhenUriChanges()\n        {\n            // Arrange\n            var request = CreateRequest();\n            request.RequestUri = new Uri(\"http://localhost/api/Person/10?x=7&y=cool\");\n            request.GetQueryNameValuePairs();\n\n            // Act\n            request.RequestUri = new Uri(\"http://localhost/api/Person/10?x=7&y=verycool\");\n            var returned = request.GetQueryNameValuePairs();\n\n            // Assert\n            IEnumerable<KeyValuePair<string, string>> cached;\n            string queryString;\n\n            Assert.True(request.Properties.TryGetValue<IEnumerable<KeyValuePair<string, string>>>(HttpPropertyKeys.RequestQueryNameValuePairsKey, out cached));\n            Assert.True(request.Properties.TryGetValue<string>(HttpPropertyKeys.CachedRequestQueryKey, out queryString));\n\n            Assert.Same(returned, cached);\n            Assert.Same(returned, request.GetQueryNameValuePairs());\n            Assert.Same(request.RequestUri.Query, queryString);\n        }\n\n        [InlineData(\"http://localhost/api/Person/10?\", \"http://localhost/api/Person/10?x=7&y=verycool\")]\n        [InlineData(\"http://localhost/api/Person/10\", \"http://localhost/api/Person/10?x=7&y=verycool\")]\n        [Theory]\n        public void GetQueryNameValuePairs_ReplacesResultWhenUriChangesFromEmpty(string firstUri, string secondUri)\n        {\n            // Arrange\n            var request = CreateRequest();\n            request.RequestUri = new Uri(firstUri);\n            request.GetQueryNameValuePairs();\n\n            // Act\n            request.RequestUri = new Uri(secondUri);\n            var returned = request.GetQueryNameValuePairs();\n\n            // Assert\n            IEnumerable<KeyValuePair<string, string>> cached;\n            string queryString;\n\n            Assert.True(request.Properties.TryGetValue<IEnumerable<KeyValuePair<string, string>>>(HttpPropertyKeys.RequestQueryNameValuePairsKey, out cached));\n            Assert.True(request.Properties.TryGetValue<string>(HttpPropertyKeys.CachedRequestQueryKey, out queryString));\n\n            Assert.Same(returned, cached);\n            Assert.Same(returned, request.GetQueryNameValuePairs());\n            Assert.Same(request.RequestUri.Query, queryString);\n        }\n\n        [InlineData(\"http://localhost/api/Person/10?x=7&y=verycool\", \"http://localhost/api/Person/10?\")]\n        [InlineData(\"http://localhost/api/Person/10?x=7&y=verycool\", \"http://localhost/api/Person/10\")]\n        [Theory]\n        public void GetQueryNameValuePairs_ReplacesResultWhenUriChangesToEmpty(string firstUri, string secondUri)\n        {\n            // Arrange\n            var request = CreateRequest();\n            request.RequestUri = new Uri(firstUri);\n            IEnumerable<KeyValuePair<string, string>> original = request.GetQueryNameValuePairs();\n\n            // Act\n            request.RequestUri = new Uri(secondUri);\n            var returned = request.GetQueryNameValuePairs();\n\n            // Assert\n            IEnumerable<KeyValuePair<string, string>> cached;\n            string queryString;\n\n            // Cache is not cleared when the query is empty, but it is when the query is ?.\n            Assert.True(request.Properties.TryGetValue<IEnumerable<KeyValuePair<string, string>>>(HttpPropertyKeys.RequestQueryNameValuePairsKey, out cached));\n            Assert.True(request.Properties.TryGetValue<string>(HttpPropertyKeys.CachedRequestQueryKey, out queryString));\n\n            if (request.RequestUri.Query == \"?\")\n            {\n                Assert.Same(returned, cached);\n                Assert.Same(request.RequestUri.Query, queryString);\n                Assert.Equal(returned, Enumerable.Empty<KeyValuePair<string, string>>());\n            }\n            else\n            {\n                Assert.Same(original, cached);\n                Assert.NotSame(returned, cached);\n                Assert.NotSame(request.RequestUri.Query, queryString);\n                Assert.Same(returned, Enumerable.Empty<KeyValuePair<string, string>>());\n            }\n\n            Assert.Same(returned, request.GetQueryNameValuePairs());\n        }\n\n        [Fact]\n        public void GetQueryNameValuePairs_ReplacesResultWhenUriChanges_AndUserRemovedCache()\n        {\n            // This test verifies that users following the existing workaround for the issue\n            // https://aspnetwebstack.codeplex.com/workitem/2200 are not broken.\n\n            // Arrange\n            var request = CreateRequest();\n            request.RequestUri = new Uri(\"http://localhost/api/Person/10?x=7&y=cool\");\n            request.GetQueryNameValuePairs();\n            request.Properties.Remove(HttpPropertyKeys.RequestQueryNameValuePairsKey);\n\n            Assert.False(request.Properties.ContainsKey(HttpPropertyKeys.RequestQueryNameValuePairsKey));\n\n            // Act\n            request.RequestUri = new Uri(\"http://localhost/api/Person/10?x=7&y=verycool\");\n            var returned = request.GetQueryNameValuePairs();\n\n            // Assert\n            IEnumerable<KeyValuePair<string, string>> cached;\n            string queryString;\n\n            Assert.True(request.Properties.TryGetValue<IEnumerable<KeyValuePair<string, string>>>(HttpPropertyKeys.RequestQueryNameValuePairsKey, out cached));\n            Assert.True(request.Properties.TryGetValue<string>(HttpPropertyKeys.CachedRequestQueryKey, out queryString));\n\n            Assert.Same(returned, cached);\n            Assert.Same(returned, request.GetQueryNameValuePairs());\n            Assert.Same(request.RequestUri.Query, queryString);\n        }\n\n        [Fact]\n        public void GetQueryNameValuePairs_ReplacesResultWhenUriChangesToEmpty_AndUserRemovedCache()\n        {\n            // This test verifies that users following the existing workaround for the issue\n            // https://aspnetwebstack.codeplex.com/workitem/2200 are not broken.\n\n            // Arrange\n            var request = CreateRequest();\n            request.RequestUri = new Uri(\"http://localhost/api/Person/10?x=7&y=cool\");\n            request.GetQueryNameValuePairs();\n            request.Properties.Remove(HttpPropertyKeys.RequestQueryNameValuePairsKey);\n\n            Assert.False(request.Properties.ContainsKey(HttpPropertyKeys.RequestQueryNameValuePairsKey));\n\n            // Act\n            request.RequestUri = new Uri(\"http://localhost/api/Person/10\");\n            var returned = request.GetQueryNameValuePairs();\n\n            // Assert\n            IEnumerable<KeyValuePair<string, string>> cached;\n            string queryString;\n\n            Assert.False(request.Properties.TryGetValue<IEnumerable<KeyValuePair<string, string>>>(HttpPropertyKeys.RequestQueryNameValuePairsKey, out cached));\n            Assert.True(request.Properties.TryGetValue<string>(HttpPropertyKeys.CachedRequestQueryKey, out queryString)); // this will not get cleared.\n\n            Assert.Same(returned, Enumerable.Empty<KeyValuePair<string, string>>());\n            Assert.Same(returned, request.GetQueryNameValuePairs());\n            Assert.NotSame(request.RequestUri.Query, queryString);\n        }\n\n        [Fact]\n        public void GetQueryNameValuePairs_ReplacesResultWhenUriChangesFromEmpty_AndUserRemovedCache()\n        {\n            // This test verifies that users following the existing workaround for the issue\n            // https://aspnetwebstack.codeplex.com/workitem/2200 are not broken.\n\n            // Arrange\n            var request = CreateRequest();\n            request.RequestUri = new Uri(\"http://localhost/api/Person/10\");\n            request.GetQueryNameValuePairs();\n            request.Properties.Remove(HttpPropertyKeys.RequestQueryNameValuePairsKey);\n\n            Assert.False(request.Properties.ContainsKey(HttpPropertyKeys.RequestQueryNameValuePairsKey));\n\n            // Act\n            request.RequestUri = new Uri(\"http://localhost/api/Person/10?x=7&y=verycool\");\n            var returned = request.GetQueryNameValuePairs();\n\n            // Assert\n            IEnumerable<KeyValuePair<string, string>> cached;\n            string queryString;\n\n            Assert.True(request.Properties.TryGetValue<IEnumerable<KeyValuePair<string, string>>>(HttpPropertyKeys.RequestQueryNameValuePairsKey, out cached));\n            Assert.True(request.Properties.TryGetValue<string>(HttpPropertyKeys.CachedRequestQueryKey, out queryString));\n\n            Assert.Same(returned, cached);\n            Assert.Same(returned, request.GetQueryNameValuePairs());\n            Assert.Same(request.RequestUri.Query, queryString);\n        }\n\n        private class TraceIdScope : IDisposable\n        {\n            Guid _oldValue;\n\n            public TraceIdScope(Guid traceId)\n            {\n                _oldValue = Trace.CorrelationManager.ActivityId;\n                Trace.CorrelationManager.ActivityId = traceId;\n            }\n\n            public void Dispose()\n            {\n                Trace.CorrelationManager.ActivityId = _oldValue;\n            }\n        }\n\n        private static HttpConfiguration CreateAndAddConfiguration(HttpRequestMessage request)\n        {\n            HttpConfiguration configuration = CreateConfiguration();\n            request.SetConfiguration(configuration);\n            return configuration;\n        }\n\n        private static X509Certificate2 CreateCertificate()\n        {\n            return new X509Certificate2();\n        }\n\n        private static HttpConfiguration CreateConfiguration()\n        {\n            return new HttpConfiguration();\n        }\n\n        private static HttpRequestContext CreateContext()\n        {\n            return new HttpRequestContext();\n        }\n\n        private static IHttpRouteData CreateDummyRouteData()\n        {\n            return new Mock<IHttpRouteData>(MockBehavior.Strict).Object;\n        }\n\n        private static IDisposable CreateStubDisposable()\n        {\n            return new Mock<IDisposable>().Object;\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private static object CreateValue()\n        {\n            return new object();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/HttpResponseExceptionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http\n{\n    public class HttpResponseExceptionTest\n    {\n        [Fact]\n        public void Constructor_WhenResponseParameterIsNull_Throws()\n        {\n            Assert.ThrowsArgumentNull(() => new HttpResponseException(response: null), \"response\");\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void Constructor_SetsResponseProperty()\n        {\n            // Arrange and Act\n            var response = new HttpResponseMessage();\n            var exception = new HttpResponseException(response);\n\n            // Assert\n            Assert.Same(response, exception.Response);\n            Assert.Equal(\"Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by the 'Response' property of this exception for details.\", exception.Message);\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void Constructor_SetsResponsePropertyWithGivenStatusCode()\n        {\n            // Arrange and Act\n            var exception = new HttpResponseException(HttpStatusCode.BadGateway);\n\n            // Assert\n            Assert.Equal(HttpStatusCode.BadGateway, exception.Response.StatusCode);\n            Assert.Equal(\"Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by the 'Response' property of this exception for details.\", exception.Message);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/HttpResponseMessageExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http.Formatting;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Net.Http\n{\n    public class HttpResponseMessageExtensionsTest\n    {\n        private readonly HttpResponseMessage _response = new HttpResponseMessage();\n        private readonly Mock<MediaTypeFormatter> _formatterMock = new Mock<MediaTypeFormatter>();\n\n        public HttpResponseMessageExtensionsTest()\n        {\n            _formatterMock.Setup(f => f.CanWriteType(It.IsAny<Type>())).Returns(true);\n        }\n\n        [Fact]\n        public void TryGetContentValue_WhenResponseParameterIsNull_Throws()\n        {\n            object value;\n            Assert.ThrowsArgumentNull(() => HttpResponseMessageExtensions.TryGetContentValue<object>(null, out value), \"response\");\n        }\n\n        [Theory]\n        [InlineData(default(bool))]\n        [InlineData(default(int))]\n        [InlineData(default(object))]\n        public void TryGetContentValue_WhenResponseHasNoContent_ReturnsFalse<T>(T expectedResult)\n        {\n            T value;\n\n            Assert.False(_response.TryGetContentValue<T>(out value));\n\n            Assert.Equal(expectedResult, value);\n        }\n\n\n        [Theory]\n        [InlineData(default(bool))]\n        [InlineData(default(int))]\n        [InlineData(default(object))]\n        public void TryGetContentValue_WhenResponseHasNonObjectContent_ReturnsFalse<T>(T expectedResult)\n        {\n            _response.Content = new StringContent(\"43\");\n            T value;\n\n            Assert.False(_response.TryGetContentValue<T>(out value));\n\n            Assert.Equal(expectedResult, value);\n        }\n\n        [Theory]\n        [InlineData(default(bool))]\n        [InlineData(default(int))]\n        [InlineData(default(object))]\n        public void TryGetContentValue_WhenResponseHasObjectContentWithNullValue_ReturnsFalse<T>(T expectedResult)\n        {\n            _response.Content = new ObjectContent(typeof(object), null, _formatterMock.Object);\n            T value;\n\n            Assert.False(_response.TryGetContentValue<T>(out value));\n\n            Assert.Equal(expectedResult, value);\n        }\n\n        [Theory]\n        [InlineData(default(bool))]\n        [InlineData(default(int))]\n        public void TryGetContentValue_WhenResponseHasObjectContentWithIncompatibleValue_ReturnsFalse<T>(T expectedResult)\n        {\n            _response.Content = new ObjectContent<string>(\"42\", _formatterMock.Object);\n            T value;\n\n            Assert.False(_response.TryGetContentValue<T>(out value));\n\n            Assert.Equal(expectedResult, value);\n        }\n\n        [Fact]\n        public void TryGetContentValue_WhenResponseHasObjectContentWithCompatibleValue_ReturnsTrue()\n        {\n            List<string> value = new List<string>();\n            _response.Content = new ObjectContent<List<string>>(value, _formatterMock.Object);\n            IList<string> result;\n\n            Assert.True(_response.TryGetContentValue(out result));\n\n            Assert.Same(value, result);\n        }\n\n        [Fact]\n        public void TryGetContentValue_WhenResponseHasObjectContentValueTypeValue_RetrievingAsObjectReturnsTrue()\n        {\n            _response.Content = new ObjectContent<int>(32, _formatterMock.Object);\n            object result;\n\n            Assert.True(_response.TryGetContentValue(out result));\n\n            Assert.Equal(32, result);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/HttpRouteCollectionExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Web.Http.Batch;\nusing System.Web.Http.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http\n{\n    public class HttpRouteCollectionExtensionsTest\n    {\n        [Fact]\n        public void IsCorrectType()\n        {\n            Assert.Type.HasProperties(typeof(HttpRouteCollectionExtensions), TypeAssert.TypeProperties.IsStatic | TypeAssert.TypeProperties.IsPublicVisibleClass);\n        }\n\n        [Fact]\n        public void MapHttpRoute1ThrowsOnNullRouteCollection()\n        {\n            Assert.ThrowsArgumentNull(() => HttpRouteCollectionExtensions.MapHttpRoute(null, \"\", \"\", null), \"routes\");\n        }\n\n        [Fact]\n        public void MapHttpRoute1CreatesRoute()\n        {\n            // Arrange\n            HttpRouteCollection routes = new HttpRouteCollection();\n            object defaults = new { d1 = \"D1\" };\n\n            // Act\n            IHttpRoute route = routes.MapHttpRoute(\"name\", \"template\", defaults);\n\n            // Assert\n            Assert.NotNull(route);\n            Assert.Equal(\"template\", route.RouteTemplate);\n            Assert.Equal(1, route.Defaults.Count);\n            Assert.Equal(\"D1\", route.Defaults[\"d1\"]);\n            Assert.Same(route, routes[\"name\"]);\n        }\n\n        [Fact]\n        public void MapHttpRoute1WithDefaultsAsDictionaryCreatesRoute()\n        {\n            // Arrange\n            HttpRouteCollection routes = new HttpRouteCollection();\n            object defaults = new Dictionary<string, object> { { \"d1\", \"D1\" } };\n\n            // Act\n            IHttpRoute route = routes.MapHttpRoute(\"name\", \"template\", defaults);\n\n            // Assert\n            Assert.NotNull(route);\n            Assert.Equal(\"template\", route.RouteTemplate);\n            Assert.Equal(1, route.Defaults.Count);\n            Assert.Equal(\"D1\", route.Defaults[\"d1\"]);\n            Assert.Same(route, routes[\"name\"]);\n        }\n\n        [Fact]\n        public void MapHttpRoute2ThrowsOnNullRouteCollection()\n        {\n            Assert.ThrowsArgumentNull(() => HttpRouteCollectionExtensions.MapHttpRoute(null, \"\", \"\", null, null), \"routes\");\n        }\n\n        [Fact]\n        public void MapHttpRoute2CreatesRoute()\n        {\n            // Arrange\n            HttpRouteCollection routes = new HttpRouteCollection();\n            object defaults = new { d1 = \"D1\" };\n            object constraints = new { c1 = \"C1\" };\n\n            // Act\n            IHttpRoute route = routes.MapHttpRoute(\"name\", \"template\", defaults, constraints);\n\n            // Assert\n            Assert.NotNull(route);\n            Assert.Equal(\"template\", route.RouteTemplate);\n            Assert.Equal(1, route.Defaults.Count);\n            Assert.Equal(\"D1\", route.Defaults[\"d1\"]);\n            Assert.Equal(1, route.Defaults.Count);\n            Assert.Equal(\"C1\", route.Constraints[\"c1\"]);\n            Assert.Same(route, routes[\"name\"]);\n        }\n\n        [Fact]\n        public void MapHttpRoute2WithDefaultsAndConstraintsAsDictionaryCreatesRoute()\n        {\n            // Arrange\n            HttpRouteCollection routes = new HttpRouteCollection();\n            object defaults = new Dictionary<string, object> { { \"d1\", \"D1\" } };\n            object constraints = new Dictionary<string, object> { { \"c1\", \"C1\" } };\n\n            // Act\n            IHttpRoute route = routes.MapHttpRoute(\"name\", \"template\", defaults, constraints);\n\n            // Assert\n            Assert.NotNull(route);\n            Assert.Equal(\"template\", route.RouteTemplate);\n            Assert.Equal(1, route.Defaults.Count);\n            Assert.Equal(\"D1\", route.Defaults[\"d1\"]);\n            Assert.Equal(1, route.Defaults.Count);\n            Assert.Equal(\"C1\", route.Constraints[\"c1\"]);\n            Assert.Same(route, routes[\"name\"]);\n        }\n\n        [Fact]\n        public void MapHttpBatchRoute_CreatesRoutesUsingCustomBatchHandler()\n        {\n            HttpRouteCollection routes = new HttpRouteCollection();\n            HttpBatchHandler mockBatchHandler = new Mock<HttpBatchHandler>(new HttpServer()).Object;\n            IHttpRoute route = routes.MapHttpBatchRoute(\"batch\", \"api/batch\", mockBatchHandler);\n\n            Assert.NotNull(route);\n            Assert.Equal(\"api/batch\", route.RouteTemplate);\n            Assert.Same(route, routes[\"batch\"]);\n            Assert.Same(mockBatchHandler, route.Handler);\n        }\n\n        [Fact]\n        public void IgnoreRouteWithNullRouteCollectionThrows()\n        {\n            Assert.ThrowsArgumentNull(\n                delegate { HttpRouteCollectionExtensions.IgnoreRoute(null, \"bar\", \"foo\"); },\n                \"routes\");\n        }\n\n        [Fact]\n        public void IgnoreRouteWithNullRouteNameThrows()\n        {\n            // Arrange\n            HttpRouteCollection routes = new HttpRouteCollection();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { routes.IgnoreRoute(null, \"foo\"); },\n                \"routeName\");\n        }\n\n        [Fact]\n        public void IgnoreRouteWithNullUrlThrows()\n        {\n            // Arrange\n            HttpRouteCollection routes = new HttpRouteCollection();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { routes.IgnoreRoute(\"foo\", null); },\n                \"routeTemplate\");\n        }\n\n        [Fact]\n        public void IgnoreRouteWithoutConstraints()\n        {\n            // Arrange\n            HttpRouteCollection routes = new HttpRouteCollection();\n\n            // Act\n            routes.IgnoreRoute(\"SomeRouteName\", \"SomeRouteTemplate\");\n\n            // Assert\n            HttpRoute route = Assert.Single(routes.Cast<HttpRoute>());\n            Assert.NotNull(route);\n            Assert.Equal(\"SomeRouteTemplate\", route.RouteTemplate);\n            Assert.IsType<StopRoutingHandler>(route.Handler);\n            Assert.Empty(route.Defaults);\n            Assert.Empty(route.Constraints);\n        }\n\n        [Fact]\n        public void IgnoreRouteWithConstraints()\n        {\n            // Arrange\n            HttpRouteCollection routes = new HttpRouteCollection();\n            var constraints = new { Foo = \"DefaultFoo\" };\n\n            // Act\n            routes.IgnoreRoute(\"SomeRouteName\", \"SomeRouteTemplate\", constraints);\n\n            // Assert\n            HttpRoute route = Assert.Single(routes.Cast<HttpRoute>());\n            Assert.NotNull(route);\n            Assert.Equal(\"SomeRouteTemplate\", route.RouteTemplate);\n            Assert.IsType<StopRoutingHandler>(route.Handler);\n            Assert.Empty(route.Defaults);\n            Assert.Single(route.Constraints);\n            Assert.Equal(\"DefaultFoo\", route.Constraints[\"Foo\"]);\n        }\n\n        [Fact]\n        public void IgnoreRouteInternalNeverMatchesUrlGeneration()\n        {\n            // Arrange\n            HttpRouteCollection routes = new HttpRouteCollection();\n            IHttpRoute route = routes.IgnoreRoute(\"Foo\", \"SomeRouteTemplate\");\n\n            // Act\n            IHttpVirtualPathData vpd = route.GetVirtualPath(new HttpRequestMessage(HttpMethod.Get, \"SomeRouteTemplate\"), null);\n\n            // Assert\n            Assert.Null(vpd);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/HttpRouteCollectionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Web.Http.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http\n{\n    public class HttpRouteCollectionTest\n    {\n        [Fact]\n        public void HttpRouteCollection_Dispose_UniquifiesHandlers()\n        {\n            // Arrange\n            var collection = new HttpRouteCollection();\n\n            var handler1 = new Mock<HttpMessageHandler>();\n            handler1.As<IDisposable>().Setup(c => c.Dispose()).Verifiable();\n\n            var handler2 = new Mock<HttpMessageHandler>();\n            handler2.As<IDisposable>().Setup(c => c.Dispose()).Verifiable();\n\n            var route1 = new Mock<IHttpRoute>();\n            route1.SetupGet(r => r.Handler).Returns(handler1.Object);\n\n            var route2 = new Mock<IHttpRoute>();\n            route2.SetupGet(r => r.Handler).Returns(handler1.Object);\n\n            var route3 = new Mock<IHttpRoute>();\n            route3.SetupGet(r => r.Handler).Returns(handler2.Object);\n\n            collection.Add(\"route1\", route1.Object);\n            collection.Add(\"route2\", route2.Object);\n            collection.Add(\"route3\", route3.Object);\n\n            // Act\n            collection.Dispose();\n\n            // Assert\n            handler1.As<IDisposable>().Verify(c => c.Dispose(), Times.Once());\n            handler2.As<IDisposable>().Verify(c => c.Dispose(), Times.Once());\n        }\n\n        [Fact]\n        public void CreateRoute_ValidatesConstraintType_IHttpRouteConstraint()\n        {\n            // Arrange\n            var routes = new MockHttpRouteCollection();\n\n            var constraint = new CustomConstraint();\n            var constraints = new HttpRouteValueDictionary();\n            constraints.Add(\"custom\", constraint);\n\n            // Act\n            var route = routes.CreateRoute(\"{controller}/{id}\", null, constraints);\n\n            // Assert\n            Assert.NotNull(route.Constraints[\"custom\"]);\n            Assert.Equal(1, routes.TimesValidateConstraintCalled);\n        }\n\n        [Fact]\n        public void CreateRoute_ValidatesConstraintType_StringRegex()\n        {\n            // Arrange\n            var routes = new MockHttpRouteCollection();\n\n            var constraint = \"product|products\";\n            var constraints = new HttpRouteValueDictionary();\n            constraints.Add(\"custom\", constraint);\n\n            // Act\n            var route = routes.CreateRoute(\"{controller}/{id}\", null, constraints);\n\n            // Assert\n            Assert.NotNull(route.Constraints[\"custom\"]);\n            Assert.Equal(1, routes.TimesValidateConstraintCalled);\n        }\n\n        [Fact]\n        public void CreateRoute_ValidatesConstraintType_InvalidType()\n        {\n            // Arrange\n            var routes = new HttpRouteCollection();\n\n            var constraint = new Uri(\"http://localhost/\");\n            var constraints = new HttpRouteValueDictionary();\n            constraints.Add(\"custom\", constraint);\n\n            string expectedMessage =\n                \"The constraint entry 'custom' on the route with route template '{controller}/{id}' \" +\n                \"must have a string value or be of a type which implements 'System.Web.Http.Routing.IHttpRouteConstraint'.\";\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(() => routes.CreateRoute(\"{controller}/{id}\", null, constraints), expectedMessage);\n        }\n\n        private class CustomConstraint : IHttpRouteConstraint\n        {\n            public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class MockHttpRouteCollection : HttpRouteCollection\n        {\n            public int TimesValidateConstraintCalled\n            {\n                get;\n                private set;\n            }\n\n            protected override void ValidateConstraint(string routeTemplate, string name, object constraint)\n            {\n                TimesValidateConstraintCalled++;\n                base.ValidateConstraint(routeTemplate, name, constraint);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/HttpServerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net;\nusing System.Net.Http;\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Results;\nusing System.Web.Http.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\nusing Moq.Protected;\n\nnamespace System.Web.Http\n{\n    public class HttpServerTest\n    {\n        [Fact]\n        public void IsCorrectType()\n        {\n            Assert.Type.HasProperties<HttpServer, DelegatingHandler>(TypeAssert.TypeProperties.IsPublicVisibleClass | TypeAssert.TypeProperties.IsDisposable);\n        }\n\n        [Fact]\n        public void DefaultConstructor()\n        {\n            Assert.DoesNotThrow(() => new HttpServer());\n        }\n\n        [Fact]\n        public void ConstructorConfigThrowsOnNull()\n        {\n            Assert.ThrowsArgumentNull(() => new HttpServer((HttpConfiguration)null), \"configuration\");\n        }\n\n        [Fact]\n        public void ConstructorConfigSetsUpProperties()\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n\n            // Act\n            HttpServer server = new HttpServer(config);\n\n            // Assert\n            Assert.Same(config, server.Configuration);\n        }\n\n        [Fact]\n        public void ConstructorDispatcherThrowsOnNull()\n        {\n            Assert.ThrowsArgumentNull(() => new HttpServer((HttpMessageHandler)null), \"dispatcher\");\n        }\n\n        [Fact]\n        public void ConstructorDispatcherSetsUpProperties()\n        {\n            // Arrange\n            Mock<HttpMessageHandler> mockHandler = new Mock<HttpMessageHandler>();\n\n            // Act\n            HttpServer server = new HttpServer(mockHandler.Object);\n\n            // Assert\n            Assert.Same(mockHandler.Object, server.Dispatcher);\n        }\n\n        [Fact]\n        public void ConstructorThrowsOnNull()\n        {\n            Mock<HttpMessageHandler> mockHandler = new Mock<HttpMessageHandler>();\n            Assert.ThrowsArgumentNull(() => new HttpServer((HttpConfiguration)null, mockHandler.Object), \"configuration\");\n            Assert.ThrowsArgumentNull(() => new HttpServer(new HttpConfiguration(), null), \"dispatcher\");\n        }\n\n        [Fact]\n        public void ConstructorSetsUpProperties()\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            Mock<HttpControllerDispatcher> controllerDispatcherMock = new Mock<HttpControllerDispatcher>(config);\n\n            // Act\n            HttpServer server = new HttpServer(config, controllerDispatcherMock.Object);\n\n            // Assert\n            Assert.Same(config, server.Configuration);\n            Assert.Same(controllerDispatcherMock.Object, server.Dispatcher);\n        }\n\n        [Fact]\n        public void ExceptionLoggerGet_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            IExceptionLogger expectedExceptionLogger = CreateDummyExceptionLogger();\n            IExceptionHandler exceptionHandler = CreateDummyExceptionHandler();\n\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpMessageHandler dispatcher = CreateDummyMessageHandler())\n            using (HttpServer product = CreateProductUnderTest(configuration, dispatcher, expectedExceptionLogger,\n                exceptionHandler))\n            {\n                // Act\n                IExceptionLogger exceptionLogger = product.ExceptionLogger;\n\n                // Assert\n                Assert.Same(expectedExceptionLogger, exceptionLogger);\n            }\n        }\n\n        [Fact]\n        public void ExceptionHandlerGet_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            IExceptionLogger exceptionLogger = CreateDummyExceptionLogger();\n            IExceptionHandler expectedExceptionHandler = CreateDummyExceptionHandler();\n\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpMessageHandler dispatcher = CreateDummyMessageHandler())\n            using (HttpServer product = CreateProductUnderTest(configuration, dispatcher, exceptionLogger,\n                expectedExceptionHandler))\n            {\n                // Act\n                IExceptionHandler exceptionHandler = product.ExceptionHandler;\n\n                // Assert\n                Assert.Same(expectedExceptionHandler, exceptionHandler);\n            }\n        }\n\n        [Fact]\n        public void ExceptionLoggerGet_IfUnset_ReturnsExceptionLoggerFromConfiguration()\n        {\n            // Arrange\n            using (HttpConfiguration configuration = CreateConfiguration())\n            {\n                IExceptionLogger expectedExceptionLogger = CreateDummyExceptionLogger();\n                configuration.Services.Add(typeof(IExceptionLogger), expectedExceptionLogger);\n\n                using (HttpMessageHandler dispatcher = CreateDummyMessageHandler())\n                using (HttpServer product = new HttpServer(configuration, dispatcher))\n                {\n                    // Act\n                    IExceptionLogger exceptionLogger = product.ExceptionLogger;\n\n                    // Assert\n                    CompositeExceptionLogger compositeLogger = Assert.IsType<CompositeExceptionLogger>(exceptionLogger);\n                    IEnumerable<IExceptionLogger> loggers = compositeLogger.Loggers;\n                    Assert.NotNull(loggers);\n                    IExceptionLogger logger = Assert.Single(loggers);\n                    Assert.Same(expectedExceptionLogger, logger);\n                }\n            }\n        }\n\n        [Fact]\n        public void ExceptionHandlerGet_IfUnset_UsesExceptionHandlerFromConfiguration()\n        {\n            // Arrange\n            using (HttpConfiguration configuration = CreateConfiguration())\n            {\n                IExceptionHandler expectedExceptionHandler = CreateDummyExceptionHandler();\n                configuration.Services.Replace(typeof(IExceptionHandler), expectedExceptionHandler);\n\n                using (HttpMessageHandler dispatcher = CreateDummyMessageHandler())\n                using (HttpServer product = new HttpServer(configuration, dispatcher))\n                {\n                    // Act\n                    IExceptionHandler exceptionHandler = product.ExceptionHandler;\n\n                    // Assert\n                    LastChanceExceptionHandler lastChanceHandler = Assert.IsType<LastChanceExceptionHandler>(exceptionHandler);\n                    Assert.Same(expectedExceptionHandler, lastChanceHandler.InnerHandler);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task DisposedReturnsServiceUnavailable()\n        {\n            // Arrange\n            Mock<HttpMessageHandler> mockHandler = new Mock<HttpMessageHandler>();\n            HttpServer server = new HttpServer(mockHandler.Object);\n            HttpMessageInvoker invoker = new HttpMessageInvoker(server);\n            server.Dispose();\n            HttpRequestMessage request = new HttpRequestMessage();\n\n            // Act\n            var response = await invoker.SendAsync(request, CancellationToken.None);\n\n            // Assert\n            mockHandler.Protected().Verify<Task<HttpResponseMessage>>(\"SendAsync\", Times.Never(), request, CancellationToken.None);\n            Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode);\n        }\n\n        [Fact]\n        public async Task RequestGetsConfigurationAsParameter()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n\n            HttpConfiguration config = new HttpConfiguration();\n            Mock<HttpControllerDispatcher> dispatcherMock = new Mock<HttpControllerDispatcher>(config);\n            dispatcherMock.Protected().Setup<Task<HttpResponseMessage>>(\"SendAsync\", request, CancellationToken.None)\n                .Returns(Task.FromResult<HttpResponseMessage>(request.CreateResponse()));\n\n            HttpServer server = new HttpServer(config, dispatcherMock.Object);\n            HttpMessageInvoker invoker = new HttpMessageInvoker(server);\n\n            // Act\n            await invoker.SendAsync(request, CancellationToken.None);\n\n            // Assert\n            dispatcherMock.Protected().Verify<Task<HttpResponseMessage>>(\"SendAsync\", Times.Once(), request, CancellationToken.None);\n            Assert.Same(config, request.GetConfiguration());\n        }\n\n        [Fact]\n        public async Task RequestGetsSyncContextAsParameter()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n\n            HttpConfiguration config = new HttpConfiguration();\n            Mock<HttpControllerDispatcher> dispatcherMock = new Mock<HttpControllerDispatcher>(config);\n            dispatcherMock.Protected().Setup<Task<HttpResponseMessage>>(\"SendAsync\", request, CancellationToken.None)\n                .Returns(Task.FromResult<HttpResponseMessage>(request.CreateResponse()));\n\n            HttpServer server = new HttpServer(config, dispatcherMock.Object);\n            HttpMessageInvoker invoker = new HttpMessageInvoker(server);\n\n            SynchronizationContext syncContext = new SynchronizationContext();\n            SynchronizationContext.SetSynchronizationContext(syncContext);\n\n            // Act\n            await invoker.SendAsync(request, CancellationToken.None);\n\n            // Assert\n            dispatcherMock.Protected().Verify<Task<HttpResponseMessage>>(\"SendAsync\", Times.Once(), request, CancellationToken.None);\n            Assert.Same(syncContext, request.GetSynchronizationContext());\n        }\n\n        [Fact, RestoreThreadPrincipal]\n        public async Task SendAsync_SetsGenericPrincipalWhenThreadPrincipalIsNullAndCleansUpAfterward()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var request = new HttpRequestMessage();\n            var dispatcherMock = new Mock<HttpControllerDispatcher>(config);\n            var server = new HttpServer(config, dispatcherMock.Object);\n            var invoker = new HttpMessageInvoker(server);\n            IPrincipal callbackPrincipal = null;\n            Thread.CurrentPrincipal = null;\n            dispatcherMock.Protected()\n                          .Setup<Task<HttpResponseMessage>>(\"SendAsync\", request, CancellationToken.None)\n                          .Callback(() => callbackPrincipal = Thread.CurrentPrincipal)\n                          .Returns(Task.FromResult<HttpResponseMessage>(request.CreateResponse()));\n\n            // Act\n            await invoker.SendAsync(request, CancellationToken.None);\n\n            // Assert\n            Assert.NotNull(callbackPrincipal);\n            Assert.False(callbackPrincipal.Identity.IsAuthenticated);\n            Assert.Empty(callbackPrincipal.Identity.Name);\n            Assert.Null(Thread.CurrentPrincipal);\n        }\n\n        [Fact, RestoreThreadPrincipal]\n        public async Task SendAsync_DoesNotChangeExistingThreadPrincipal()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var request = new HttpRequestMessage();\n            var dispatcherMock = new Mock<HttpControllerDispatcher>(config);\n            var server = new HttpServer(config, dispatcherMock.Object);\n            var invoker = new HttpMessageInvoker(server);\n            var principal = new GenericPrincipal(new GenericIdentity(\"joe\"), new string[0]);\n            Thread.CurrentPrincipal = principal;\n            IPrincipal callbackPrincipal = null;\n            dispatcherMock.Protected()\n                          .Setup<Task<HttpResponseMessage>>(\"SendAsync\", request, CancellationToken.None)\n                          .Callback(() => callbackPrincipal = Thread.CurrentPrincipal)\n                          .Returns(Task.FromResult<HttpResponseMessage>(request.CreateResponse()));\n\n            // Act\n            await invoker.SendAsync(request, CancellationToken.None);\n\n            // Assert\n            Assert.Same(principal, callbackPrincipal);\n            Assert.Same(principal, Thread.CurrentPrincipal);\n        }\n\n        [Fact]\n        public async Task SendAsync_Handles_ExceptionsThrownInMessageHandlers()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            config.MessageHandlers.Add(new ThrowingMessageHandler(new InvalidOperationException()));\n            HttpServer server = new HttpServer(config);\n            var invoker = new HttpMessageInvoker(server);\n\n            // Act\n            var response = await invoker.SendAsync(new HttpRequestMessage(), CancellationToken.None);\n\n            // Assert\n            Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n        }\n\n        [Fact]\n        public async Task SendAsync_Handles_HttpResponseExceptionsThrownInMessageHandlers()\n        {\n            // Arrange\n            HttpResponseException exception = new HttpResponseException(new HttpResponseMessage(HttpStatusCode.HttpVersionNotSupported));\n            exception.Response.ReasonPhrase = \"whatever\";\n            var config = new HttpConfiguration();\n            config.MessageHandlers.Add(new ThrowingMessageHandler(exception));\n            HttpServer server = new HttpServer(config);\n            var invoker = new HttpMessageInvoker(server);\n\n            // Act\n            var response = await invoker.SendAsync(new HttpRequestMessage(), CancellationToken.None);\n\n            // Assert\n            Assert.Equal(exception.Response.StatusCode, response.StatusCode);\n            Assert.Equal(exception.Response.ReasonPhrase, response.ReasonPhrase);\n        }\n\n        [Fact]\n        public async Task SendAsync_Handles_ExceptionsThrownInCustomRoutes()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            config.Routes.Add(\"throwing route\", new ThrowingRoute(new InvalidOperationException()));\n            HttpServer server = new HttpServer(config);\n            var invoker = new HttpMessageInvoker(server);\n\n            // Act\n            var response = await invoker.SendAsync(new HttpRequestMessage(), CancellationToken.None);\n\n            // Assert\n            Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n        }\n\n        [Fact]\n        public async Task SendAsync_Handles_HttpResponseExceptionsThrownInCustomRoutes()\n        {\n            // Arrange\n            HttpResponseException exception = new HttpResponseException(new HttpResponseMessage(HttpStatusCode.HttpVersionNotSupported));\n            exception.Response.ReasonPhrase = \"whatever\";\n            var config = new HttpConfiguration();\n            config.Routes.Add(\"throwing route\", new ThrowingRoute(exception));\n            HttpServer server = new HttpServer(config);\n            var invoker = new HttpMessageInvoker(server);\n\n            // Act\n            var response = await invoker.SendAsync(new HttpRequestMessage(), CancellationToken.None);\n\n            // Assert\n            Assert.Equal(exception.Response.StatusCode, response.StatusCode);\n            Assert.Equal(exception.Response.ReasonPhrase, response.ReasonPhrase);\n        }\n\n        [Fact]\n        public async Task SendAsync_IfDispatcherTaskIsFaulted_CallsExceptionServices()\n        {\n            // Arrange\n            Exception expectedException = CreateException();\n\n            HttpMessageHandler dispatcher = CreateFaultingMessageHandler(expectedException);\n\n            Mock<IExceptionLogger> exceptionLoggerMock = CreateStubExceptionLoggerMock();\n            IExceptionLogger exceptionLogger = exceptionLoggerMock.Object;\n\n            Mock<IExceptionHandler> exceptionHandlerMock = CreateStubExceptionHandlerMock();\n            IExceptionHandler exceptionHandler = exceptionHandlerMock.Object;\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpServer product = CreateProductUnderTest(configuration, dispatcher, exceptionLogger,\n                exceptionHandler))\n            {\n                CancellationToken cancellationToken = CreateCancellationToken();\n\n                // Act\n                await Assert.ThrowsAsync<Exception>(() => product.SendAsync(expectedRequest, cancellationToken));\n\n                // Assert\n                Func<ExceptionContext, bool> exceptionContextMatches = (c) =>\n                    c != null\n                    && c.Exception == expectedException\n                    && c.CatchBlock == ExceptionCatchBlocks.HttpServer\n                    && c.Request == expectedRequest;\n\n                exceptionLoggerMock.Verify(l => l.LogAsync(\n                    It.Is<ExceptionLoggerContext>(c => exceptionContextMatches(c.ExceptionContext)),\n                    cancellationToken), Times.Once());\n\n                exceptionHandlerMock.Verify(h => h.HandleAsync(\n                    It.Is<ExceptionHandlerContext>((c) => exceptionContextMatches(c.ExceptionContext)),\n                    cancellationToken), Times.Once());\n            }\n        }\n\n        [Fact]\n        public async Task SendAsync_IfRequestCancelled_DoesNotCallExceptionServices()\n        {\n            // Arrange\n            Exception expectedException = new OperationCanceledException();\n\n            HttpMessageHandler dispatcher = CreateFaultingMessageHandler(expectedException);\n\n            Mock<IExceptionLogger> exceptionLoggerMock = new Mock<IExceptionLogger>(MockBehavior.Strict);\n            IExceptionLogger exceptionLogger = exceptionLoggerMock.Object;\n\n            Mock<IExceptionHandler> exceptionHandlerMock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n            IExceptionHandler exceptionHandler = exceptionHandlerMock.Object;\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpServer product = CreateProductUnderTest(configuration, dispatcher, exceptionLogger,\n                exceptionHandler))\n            {\n                CancellationToken cancellationToken = CreateCancellationToken();\n\n                // Act\n                await Assert.ThrowsAsync<OperationCanceledException>(() => product.SendAsync(expectedRequest, cancellationToken));\n\n                // The mock handler and logger will throw if they are called, so this test verifies that\n                // they aren't called by construction.\n            }\n        }\n\n        [Fact]\n        public async Task SendAsync_IfExceptionHandlerSetsNullResult_PropogatesFaultedTaskException()\n        {\n            // Arrange\n            Exception expectedException = CreateExceptionWithCallStack();\n            string expectedStackTrace = expectedException.StackTrace;\n\n            HttpMessageHandler dispatcher = CreateFaultingMessageHandler(expectedException);\n\n            IExceptionLogger exceptionLogger = CreateStubExceptionLogger();\n\n            Mock<IExceptionHandler> exceptionHandlerMock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n            exceptionHandlerMock\n                .Setup(h => h.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                .Callback<ExceptionHandlerContext, CancellationToken>((c, i) => c.Result = null)\n                .Returns(Task.FromResult(0));\n            IExceptionHandler exceptionHandler = exceptionHandlerMock.Object;\n\n            using (HttpRequestMessage request = CreateRequest())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            using (HttpServer product = CreateProductUnderTest(configuration, dispatcher, exceptionLogger,\n                exceptionHandler))\n            {\n                CancellationToken cancellationToken = CreateCancellationToken();\n\n                // Act & Assert\n                var exception = await Assert.ThrowsAsync<Exception>(() => product.SendAsync(request, cancellationToken));\n\n                Assert.Same(expectedException, exception);\n                Assert.NotNull(exception.StackTrace);\n                Assert.StartsWith(expectedStackTrace, exception.StackTrace);\n            }\n        }\n\n        [Fact]\n        public async Task SendAsync_IfExceptionHandlerHandlesException_ReturnsResponse()\n        {\n            // Arrange\n            HttpMessageHandler dispatcher = CreateFaultingMessageHandler(CreateException());\n\n            IExceptionLogger exceptionLogger = CreateStubExceptionLogger();\n\n            using (HttpResponseMessage expectedResponse = CreateResponse())\n            {\n                Mock<IExceptionHandler> exceptionHandlerMock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n                exceptionHandlerMock\n                    .Setup(h => h.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                    .Callback<ExceptionHandlerContext, CancellationToken>((c, i) =>\n                        c.Result = new ResponseMessageResult(expectedResponse))\n                    .Returns(Task.FromResult(0));\n                IExceptionHandler exceptionHandler = exceptionHandlerMock.Object;\n\n                using (HttpRequestMessage request = CreateRequest())\n                using (HttpConfiguration configuration = new HttpConfiguration())\n                using (HttpServer product = CreateProductUnderTest(configuration, dispatcher, exceptionLogger,\n                    exceptionHandler))\n                {\n                    CancellationToken cancellationToken = CreateCancellationToken();\n\n                    // Act\n                    HttpResponseMessage response = await product.SendAsync(request, cancellationToken);\n\n                    // Assert\n                    Assert.Same(expectedResponse, response);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task HttpServerAddsDefaultRequestContext()\n        {\n            // Arrange\n            HttpServer server = new HttpServer();\n            var handler = new ThrowIfNoContext();\n\n            server.Configuration.MessageHandlers.Add(handler);\n            server.Configuration.MapHttpAttributeRoutes();\n            server.Configuration.EnsureInitialized();\n\n            var invoker = new HttpMessageInvoker(server);\n\n            var request = new HttpRequestMessage(HttpMethod.Get, \"http://localhost/Customers\");\n\n            // Act\n            var response = await invoker.SendAsync(request, CancellationToken.None);\n\n            // Assert\n            response.EnsureSuccessStatusCode();\n            Assert.True(handler.ContextFound);\n        }\n\n        [Fact]\n        public async Task HttpServerDoesNotReplaceOriginalRequestContext()\n        {\n            // Arrange\n            HttpServer server = new HttpServer();\n            var handler = new ThrowIfNoContext();\n\n            server.Configuration.MessageHandlers.Add(handler);\n            server.Configuration.MapHttpAttributeRoutes();\n            server.Configuration.EnsureInitialized();\n\n            HttpMessageInvoker invoker = new HttpMessageInvoker(server);\n\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, \"http://localhost/Customers\");\n\n            HttpRequestContext context = new HttpRequestContext();\n\n            request.SetRequestContext(context);\n\n            // Act\n            var response = await invoker.SendAsync(request, CancellationToken.None);\n\n            // Assert\n            response.EnsureSuccessStatusCode();\n            Assert.True(handler.ContextFound);\n            Assert.Equal(context, response.RequestMessage.GetRequestContext());\n        }\n\n        private static CancellationToken CreateCancellationToken()\n        {\n            CancellationTokenSource source = new CancellationTokenSource();\n            return source.Token;\n        }\n\n        private static HttpConfiguration CreateConfiguration()\n        {\n            return new HttpConfiguration();\n        }\n\n        private static IExceptionHandler CreateDummyExceptionHandler()\n        {\n            return new Mock<IExceptionHandler>(MockBehavior.Strict).Object;\n        }\n\n        private static IExceptionLogger CreateDummyExceptionLogger()\n        {\n            return new Mock<IExceptionLogger>(MockBehavior.Strict).Object;\n        }\n\n        private static HttpMessageHandler CreateDummyMessageHandler()\n        {\n            Mock<HttpMessageHandler> mock = new Mock<HttpMessageHandler>(MockBehavior.Strict);\n            mock.As<IDisposable>().Setup(c => c.Dispose());\n            return mock.Object;\n        }\n\n        private static Exception CreateException()\n        {\n            return new Exception();\n        }\n\n        private static Exception CreateExceptionWithCallStack()\n        {\n            try\n            {\n                throw CreateException();\n            }\n            catch (Exception exception)\n            {\n                return exception;\n            }\n        }\n\n        private static Task<TResult> CreateFaultedTask<TResult>(Exception exception)\n        {\n            TaskCompletionSource<TResult> source = new TaskCompletionSource<TResult>();\n            source.SetException(exception);\n            return source.Task;\n        }\n\n        private static HttpMessageHandler CreateFaultingMessageHandler(Exception exception)\n        {\n            Mock<HttpMessageHandler> mock = new Mock<HttpMessageHandler>();\n            mock\n                .Protected()\n                .Setup<Task<HttpResponseMessage>>(\"SendAsync\", ItExpr.IsAny<HttpRequestMessage>(),\n                    ItExpr.IsAny<CancellationToken>())\n                .Returns(CreateFaultedTask<HttpResponseMessage>(exception));\n            return mock.Object;\n        }\n\n        private static HttpServer CreateProductUnderTest(HttpConfiguration configuration,\n            HttpMessageHandler dispatcher, IExceptionLogger exceptionLogger, IExceptionHandler exceptionHandler)\n        {\n            return new HttpServer(configuration, dispatcher)\n            {\n                ExceptionLogger = exceptionLogger,\n                ExceptionHandler = exceptionHandler\n            };\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private static HttpResponseMessage CreateResponse()\n        {\n            return new HttpResponseMessage();\n        }\n\n        private static Mock<IExceptionHandler> CreateStubExceptionHandlerMock()\n        {\n            Mock<IExceptionHandler> mock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n            mock\n                .Setup(h => h.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                .Returns(Task.FromResult(0));\n            return mock;\n        }\n\n        private static IExceptionLogger CreateStubExceptionLogger()\n        {\n            return CreateStubExceptionLoggerMock().Object;\n        }\n\n        private static Mock<IExceptionLogger> CreateStubExceptionLoggerMock()\n        {\n            Mock<IExceptionLogger> mock = new Mock<IExceptionLogger>(MockBehavior.Strict);\n            mock\n                .Setup(l => l.LogAsync(It.IsAny<ExceptionLoggerContext>(), It.IsAny<CancellationToken>()))\n                .Returns(Task.FromResult(0));\n            return mock;\n        }\n\n        private class ThrowIfNoContext : DelegatingHandler\n        {\n            public bool ContextFound { get; set; }\n\n            protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n            {\n                HttpRequestContext incomingContext = request.GetRequestContext();\n\n                if (incomingContext == null)\n                {\n                    throw new InvalidOperationException(\"context missing\");\n                }\n\n                ContextFound = true;\n\n                HttpResponseMessage result = await base.SendAsync(request, cancellationToken);\n\n                HttpRequestContext outgoingContext = result.RequestMessage.GetRequestContext();\n\n                if (outgoingContext != incomingContext)\n                {\n                    throw new InvalidOperationException(\"context mismatch\");\n                }\n\n                return result;\n            }\n        }\n\n        public class RequestHasContextController : ApiController\n        {\n            [Route(\"Customers\")]\n            public IHttpActionResult Get()\n            {\n                if (RequestContext == null)\n                {\n                    return InternalServerError();\n                }\n\n                if (Request.GetRequestContext() == null)\n                {\n                    return BadRequest();\n                }\n\n                return Ok();\n            }\n        }\n\n        private class ThrowingMessageHandler : DelegatingHandler\n        {\n            private Exception _exception;\n\n            public ThrowingMessageHandler(Exception exception)\n            {\n                _exception = exception;\n            }\n\n            protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n            {\n                // dummy await so that the task doesn't get completed synchronously.\n                await Task.FromResult(42);\n                throw _exception;\n            }\n        }\n\n        private class ThrowingRoute : HttpRoute\n        {\n            private Exception _exception;\n\n            public ThrowingRoute(Exception exception)\n            {\n                _exception = exception;\n            }\n\n            public override IHttpRouteData GetRouteData(string virtualPathRoot, HttpRequestMessage request)\n            {\n                throw _exception;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Internal/CollectionModelBinderUtilTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Web.Http.Metadata.Providers;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.ValueProviders;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Internal\n{\n    public class CollectionModelBinderUtilTest\n    {\n        [Fact]\n        public void CreateOrReplaceCollection_OriginalModelImmutable_CreatesNewInstance()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => new ReadOnlyCollection<int>(new int[0]), typeof(ICollection<int>))\n            };\n\n            // Act\n            CollectionModelBinderUtil.CreateOrReplaceCollection(bindingContext, new[] { 10, 20, 30 }, () => new List<int>());\n\n            // Assert\n            int[] newModel = (bindingContext.Model as ICollection<int>).ToArray();\n            Assert.Equal(new[] { 10, 20, 30 }, newModel);\n        }\n\n        [Fact]\n        public void CreateOrReplaceCollection_OriginalModelMutable_UpdatesOriginalInstance()\n        {\n            // Arrange\n            List<int> originalInstance = new List<int> { 10, 20, 30 };\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => originalInstance, typeof(ICollection<int>))\n            };\n\n            // Act\n            CollectionModelBinderUtil.CreateOrReplaceCollection(bindingContext, new[] { 40, 50, 60 }, () => new List<int>());\n\n            // Assert\n            Assert.Same(originalInstance, bindingContext.Model);\n            Assert.Equal(new[] { 40, 50, 60 }, originalInstance.ToArray());\n        }\n\n        [Fact]\n        public void CreateOrReplaceCollection_OriginalModelNotCollection_CreatesNewInstance()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(ICollection<int>))\n            };\n\n            // Act\n            CollectionModelBinderUtil.CreateOrReplaceCollection(bindingContext, new[] { 10, 20, 30 }, () => new List<int>());\n\n            // Assert\n            int[] newModel = (bindingContext.Model as ICollection<int>).ToArray();\n            Assert.Equal(new[] { 10, 20, 30 }, newModel);\n        }\n\n        [Fact]\n        public void CreateOrReplaceDictionary_DisallowsDuplicateKeys()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(Dictionary<string, int>))\n            };\n\n            // Act\n            CollectionModelBinderUtil.CreateOrReplaceDictionary(\n                bindingContext,\n                new[]\n                {\n                    new KeyValuePair<string, int>(\"forty-two\", 40),\n                    new KeyValuePair<string, int>(\"forty-two\", 2),\n                    new KeyValuePair<string, int>(\"forty-two\", 42)\n                },\n                () => new Dictionary<string, int>());\n\n            // Assert\n            IDictionary<string, int> newModel = bindingContext.Model as IDictionary<string, int>;\n            Assert.Equal(new[] { \"forty-two\" }, newModel.Keys.ToArray());\n            Assert.Equal(42, newModel[\"forty-two\"]);\n        }\n\n        [Fact]\n        public void CreateOrReplaceDictionary_DisallowsNullKeys()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(Dictionary<string, int>))\n            };\n\n            // Act\n            CollectionModelBinderUtil.CreateOrReplaceDictionary(\n                bindingContext,\n                new[]\n                {\n                    new KeyValuePair<string, int>(\"forty-two\", 42),\n                    new KeyValuePair<string, int>(null, 84)\n                },\n                () => new Dictionary<string, int>());\n\n            // Assert\n            IDictionary<string, int> newModel = bindingContext.Model as IDictionary<string, int>;\n            Assert.Equal(new[] { \"forty-two\" }, newModel.Keys.ToArray());\n            Assert.Equal(42, newModel[\"forty-two\"]);\n        }\n\n        [Fact]\n        public void CreateOrReplaceDictionary_OriginalModelImmutable_CreatesNewInstance()\n        {\n            // Arrange\n            ReadOnlyDictionary<string, string> originalModel = new ReadOnlyDictionary<string, string>();\n\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => originalModel, typeof(IDictionary<string, string>))\n            };\n\n            // Act\n            CollectionModelBinderUtil.CreateOrReplaceDictionary(\n                bindingContext,\n                new Dictionary<string, string>\n                {\n                    { \"Hello\", \"World\" }\n                },\n                () => new Dictionary<string, string>());\n\n            // Assert\n            IDictionary<string, string> newModel = bindingContext.Model as IDictionary<string, string>;\n            Assert.NotSame(originalModel, newModel);\n            Assert.Equal(new[] { \"Hello\" }, newModel.Keys.ToArray());\n            Assert.Equal(\"World\", newModel[\"Hello\"]);\n        }\n\n        [Fact]\n        public void CreateOrReplaceDictionary_OriginalModelMutable_UpdatesOriginalInstance()\n        {\n            // Arrange\n            Dictionary<string, string> originalInstance = new Dictionary<string, string>\n            {\n                { \"dog\", \"Canidae\" },\n                { \"cat\", \"Felidae\" }\n            };\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => originalInstance, typeof(IDictionary<string, string>))\n            };\n\n            // Act\n            CollectionModelBinderUtil.CreateOrReplaceDictionary(\n                bindingContext,\n                new Dictionary<string, string>\n                {\n                    { \"horse\", \"Equidae\" },\n                    { \"bear\", \"Ursidae\" }\n                },\n                () => new Dictionary<string, string>());\n\n            // Assert\n            Assert.Same(originalInstance, bindingContext.Model);\n            Assert.Equal(new[] { \"horse\", \"bear\" }, originalInstance.Keys.ToArray());\n            Assert.Equal(\"Equidae\", originalInstance[\"horse\"]);\n            Assert.Equal(\"Ursidae\", originalInstance[\"bear\"]);\n        }\n\n        [Fact]\n        public void CreateOrReplaceDictionary_OriginalModelNotDictionary_CreatesNewInstance()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(IDictionary<string, string>))\n            };\n\n            // Act\n            CollectionModelBinderUtil.CreateOrReplaceDictionary(\n                bindingContext,\n                new Dictionary<string, string>\n                {\n                    { \"horse\", \"Equidae\" },\n                    { \"bear\", \"Ursidae\" }\n                },\n                () => new Dictionary<string, string>());\n\n            // Assert\n            IDictionary<string, string> newModel = bindingContext.Model as IDictionary<string, string>;\n            Assert.Equal(new[] { \"horse\", \"bear\" }, newModel.Keys.ToArray());\n            Assert.Equal(\"Equidae\", newModel[\"horse\"]);\n            Assert.Equal(\"Ursidae\", newModel[\"bear\"]);\n        }\n\n        [Fact]\n        public void GetIndexNamesFromValueProviderResult_ValueProviderResultIsNull_ReturnsNull()\n        {\n            // Act\n            IEnumerable<string> indexNames = CollectionModelBinderUtil.GetIndexNamesFromValueProviderResult(null);\n\n            // Assert\n            Assert.Null(indexNames);\n        }\n\n        [Fact]\n        public void GetIndexNamesFromValueProviderResult_ValueProviderResultReturnsEmptyArray_ReturnsNull()\n        {\n            // Arrange\n            ValueProviderResult vpResult = new ValueProviderResult(new string[0], \"\", null);\n\n            // Act\n            IEnumerable<string> indexNames = CollectionModelBinderUtil.GetIndexNamesFromValueProviderResult(vpResult);\n\n            // Assert\n            Assert.Null(indexNames);\n        }\n\n        [Fact]\n        public void GetIndexNamesFromValueProviderResult_ValueProviderResultReturnsNonEmptyArray_ReturnsArray()\n        {\n            // Arrange\n            ValueProviderResult vpResult = new ValueProviderResult(new[] { \"foo\", \"bar\", \"baz\" }, \"foo,bar,baz\", null);\n\n            // Act\n            IEnumerable<string> indexNames = CollectionModelBinderUtil.GetIndexNamesFromValueProviderResult(vpResult);\n\n            // Assert\n            Assert.NotNull(indexNames);\n            Assert.Equal(new[] { \"foo\", \"bar\", \"baz\" }, indexNames.ToArray());\n        }\n\n        [Fact]\n        public void GetIndexNamesFromValueProviderResult_ValueProviderResultReturnsNull_ReturnsNull()\n        {\n            // Arrange\n            ValueProviderResult vpResult = new ValueProviderResult(null, null, null);\n\n            // Act\n            IEnumerable<string> indexNames = CollectionModelBinderUtil.GetIndexNamesFromValueProviderResult(vpResult);\n\n            // Assert\n            Assert.Null(indexNames);\n        }\n\n        [Fact]\n        public void GetZeroBasedIndexes()\n        {\n            // Act\n            string[] indexes = CollectionModelBinderUtil.GetZeroBasedIndexes().Take(5).ToArray();\n\n            // Assert\n            Assert.Equal(new[] { \"0\", \"1\", \"2\", \"3\", \"4\" }, indexes);\n        }\n\n        private class ReadOnlyDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>\n        {\n            bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly\n            {\n                get { return true; }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Internal/TypeActivatorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net;\nusing System.Net.Http;\nusing System.Reflection;\nusing System.Web.Http.Controllers;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Internal\n{\n    public class TypeActivatorTest\n    {\n        [Fact]\n        public void TypeIsCorrect()\n        {\n            Assert.Type.HasProperties(typeof(TypeActivator), TypeAssert.TypeProperties.IsClass | TypeAssert.TypeProperties.IsStatic);\n        }\n\n        public static TheoryDataSet<Type, Type> ValidTypeParameters\n        {\n            get\n            {\n                return new TheoryDataSet<Type, Type>\n                {\n                    { typeof(List<int>), typeof(IList<int>)},\n                    { typeof(Dictionary<int, int>), typeof(IDictionary<int, int>)},\n                    { typeof(HttpRequestMessage), typeof(HttpRequestMessage)},\n                    { typeof(HttpConfiguration), typeof(HttpConfiguration)},\n                    { typeof(ReflectedHttpActionDescriptor), typeof(HttpActionDescriptor) },\n                    { typeof(ApiControllerActionSelector), typeof(IHttpActionSelector)},\n                    { typeof(ApiControllerActionInvoker), typeof(IHttpActionInvoker)},\n                    { typeof(List<HttpStatusCode>), typeof(IEnumerable<HttpStatusCode>)},\n                };\n            }\n        }\n\n        public static TheoryDataSet<Type> ValidInstanceTypeParameters\n        {\n            get\n            {\n                return new TheoryDataSet<Type>\n                {\n                    { typeof(List<int>) },\n                    { typeof(Dictionary<int, int>) },\n                    { typeof(HttpRequestMessage) },\n                    { typeof(HttpConfiguration) },\n                    { typeof(ReflectedHttpActionDescriptor) },\n                    { typeof(ApiControllerActionSelector) },\n                    { typeof(ApiControllerActionInvoker) },\n                    { typeof(List<HttpStatusCode>) },\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"ValidInstanceTypeParameters\")]\n        public void CreateType(Type instanceType)\n        {\n            // Arrange\n            Func<object> instanceDelegate = TypeActivator.Create(instanceType);\n\n            // Act\n            object instance = instanceDelegate();\n\n            // Assert\n            Assert.IsType(instanceType, instance);\n        }\n\n        [Theory]\n        [InlineData(typeof(int))]\n        [InlineData(typeof(Guid))]\n        [InlineData(typeof(HttpStatusCode))]\n        [InlineData(typeof(string))]\n        [InlineData(typeof(Uri))]\n        [InlineData(typeof(IDictionary<object, object>))]\n        [InlineData(typeof(List<>))]\n        public void CreateTypeInvalidThrowsInvalidArgument(Type type)\n        {\n            // Value types, interfaces, and open generics cause ArgumentException\n            Assert.ThrowsArgument(() => TypeActivator.Create(type), paramName: null);\n        }\n\n        [Theory]\n        [InlineData(typeof(HttpContent))]\n        [InlineData(typeof(HttpActionDescriptor))]\n        public void CreateTypeInvalidThrowsInvalidOperation(Type type)\n        {\n            // Abstract types cause InvalidOperationException\n            Assert.Throws<InvalidOperationException>(() => TypeActivator.Create(type));\n        }\n\n        [Theory]\n        [PropertyData(\"ValidInstanceTypeParameters\")]\n        public void CreateOfT(Type instanceType)\n        {\n            // Arrange\n            Type activatorType = typeof(TypeActivator);\n            MethodInfo createMethodInfo = activatorType.GetMethod(\"Create\", Type.EmptyTypes);\n            MethodInfo genericCreateMethodInfo = createMethodInfo.MakeGenericMethod(instanceType);\n            Func<object> instanceDelegate = (Func<object>)genericCreateMethodInfo.Invoke(null, null);\n\n            // Act\n            object instance = instanceDelegate();\n\n            // Assert\n            Assert.IsType(instanceType, instance);\n        }\n\n        [Fact]\n        public void CreateOfTInvalid()\n        {\n            // string doesn't have a default ctor\n            Assert.ThrowsArgument(() => TypeActivator.Create<string>(), paramName: null);\n\n            // Uri doesn't have a default ctor\n            Assert.ThrowsArgument(() => TypeActivator.Create<Uri>(), paramName: null);\n\n            // HttpContent is abstract\n            Assert.Throws<InvalidOperationException>(() => TypeActivator.Create<HttpContent>());\n\n            // HttpActionDescriptor is abstract\n            Assert.Throws<InvalidOperationException>(() => TypeActivator.Create<HttpActionDescriptor>());\n        }\n\n        [Theory]\n        [PropertyData(\"ValidTypeParameters\")]\n        public void CreateOfTBase(Type instanceType, Type baseType)\n        {\n            // Arrange\n            Type activatorType = typeof(TypeActivator);\n            MethodInfo createMethodInfo = null;\n            foreach (MethodInfo methodInfo in activatorType.GetMethods())\n            {\n                ParameterInfo[] parameterInfo = methodInfo.GetParameters();\n                if (methodInfo.Name == \"Create\" && methodInfo.ContainsGenericParameters && parameterInfo.Length == 1 && parameterInfo[0].ParameterType == typeof(Type))\n                {\n                    createMethodInfo = methodInfo;\n                    break;\n                }\n            }\n\n            MethodInfo genericCreateMethodInfo = createMethodInfo.MakeGenericMethod(baseType);\n            Func<object> instanceDelegate = (Func<object>)genericCreateMethodInfo.Invoke(null, new object[] { instanceType });\n\n            // Act\n            object instance = instanceDelegate();\n\n            // Assert\n            Assert.IsType(instanceType, instance);\n        }\n\n        [Fact]\n        public void CreateOfTBaseInvalid()\n        {\n            // int not being a ref type\n            Assert.ThrowsArgument(() => TypeActivator.Create<object>(typeof(int)), paramName: null);\n\n            // GUID is not a ref type\n            Assert.ThrowsArgument(() => TypeActivator.Create<object>(typeof(Guid)), paramName: null);\n\n            // HttpStatusCode is not a ref type\n            Assert.ThrowsArgument(() => TypeActivator.Create<object>(typeof(HttpStatusCode)), paramName: null);\n\n            // string does not have a default ctor\n            Assert.ThrowsArgument(() => TypeActivator.Create<string>(typeof(string)), paramName: null);\n\n            // ObjectContent does not have a default ctor\n            Assert.ThrowsArgument(() => TypeActivator.Create<HttpContent>(typeof(ObjectContent)), paramName: null);\n\n            // Base type and instance type flipped\n            Assert.ThrowsArgument(() => TypeActivator.Create<ReflectedHttpActionDescriptor>(typeof(HttpActionDescriptor)), paramName: null);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Metadata/ModelMetadataTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Http.Metadata.Providers;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Metadata\n{\n    public class ModelMetadataTest\n    {\n        // Guard clauses\n\n        [Fact]\n        public void NullProviderThrows()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => new ModelMetadata(null /* provider */, null /* containerType */, null /* model */, typeof(object), null /* propertyName */),\n                \"provider\");\n        }\n\n        [Fact]\n        public void NullTypeThrows()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => new ModelMetadata(provider.Object, null /* containerType */, null /* model */, null /* modelType */, null /* propertyName */),\n                \"modelType\");\n        }\n\n        // Constructor\n\n        [Fact]\n        public void DefaultValues()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n\n            // Act\n            ModelMetadata metadata = new ModelMetadata(provider.Object, typeof(Exception), () => \"model\", typeof(string), \"propertyName\");\n\n            // Assert\n            Assert.Equal(typeof(Exception), metadata.ContainerType);\n            Assert.True(metadata.ConvertEmptyStringToNull);\n            Assert.Null(metadata.Description);\n            Assert.Equal(\"model\", metadata.Model);\n            Assert.Equal(typeof(string), metadata.ModelType);\n            Assert.Equal(\"propertyName\", metadata.PropertyName);\n            Assert.False(metadata.IsReadOnly);\n        }\n\n        // IsComplexType\n\n        struct IsComplexTypeModel\n        {\n        }\n\n        [Fact]\n        public void IsComplexTypeTests()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n\n            // Act & Assert\n            Assert.True(new ModelMetadata(provider.Object, null, null, typeof(Object), null).IsComplexType);\n            Assert.False(new ModelMetadata(provider.Object, null, null, typeof(string), null).IsComplexType);\n            Assert.True(new ModelMetadata(provider.Object, null, null, typeof(IDisposable), null).IsComplexType);\n            Assert.False(new ModelMetadata(provider.Object, null, null, typeof(Nullable<int>), null).IsComplexType);\n            Assert.False(new ModelMetadata(provider.Object, null, null, typeof(int), null).IsComplexType);\n            Assert.True(new ModelMetadata(provider.Object, null, null, typeof(IsComplexTypeModel), null).IsComplexType);\n            Assert.True(new ModelMetadata(provider.Object, null, null, typeof(Nullable<IsComplexTypeModel>), null).IsComplexType);\n        }\n\n        // IsNullableValueType\n\n        [Fact]\n        public void IsNullableValueTypeTests()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n\n            // Act & Assert\n            Assert.False(new ModelMetadata(provider.Object, null, null, typeof(string), null).IsNullableValueType);\n            Assert.False(new ModelMetadata(provider.Object, null, null, typeof(IDisposable), null).IsNullableValueType);\n            Assert.True(new ModelMetadata(provider.Object, null, null, typeof(Nullable<int>), null).IsNullableValueType);\n            Assert.False(new ModelMetadata(provider.Object, null, null, typeof(int), null).IsNullableValueType);\n        }\n\n        // Properties\n\n        [Fact]\n        public void PropertiesCallsProvider()\n        {\n            // Arrange\n            Type modelType = typeof(string);\n            List<ModelMetadata> propertyMetadata = new List<ModelMetadata>();\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            ModelMetadata metadata = new ModelMetadata(provider.Object, null, null, modelType, null);\n            provider.Setup(p => p.GetMetadataForProperties(null, modelType))\n                .Returns(propertyMetadata)\n                .Verifiable();\n\n            // Act\n            IEnumerable<ModelMetadata> result = metadata.Properties;\n\n            // Assert\n            Assert.Equal(propertyMetadata, result.ToList());\n            provider.Verify();\n        }\n\n        [Fact]\n        public void PropertiesListGetsResetWhenModelGetsReset()\n        { // Dev10 Bug #923263\n            // Arrange\n            var provider = new DataAnnotationsModelMetadataProvider();\n            var metadata = new ModelMetadata(provider, null, () => new Class1(), typeof(Class1), null);\n\n            // Act\n            ModelMetadata[] originalProps = metadata.Properties.ToArray();\n            metadata.Model = new Class2();\n            ModelMetadata[] newProps = metadata.Properties.ToArray();\n\n            // Assert\n            ModelMetadata originalProp = Assert.Single(originalProps);\n            Assert.Equal(typeof(string), originalProp.ModelType);\n            Assert.Equal(\"Prop1\", originalProp.PropertyName);\n            ModelMetadata newProp = Assert.Single(newProps);\n            Assert.Equal(typeof(int), newProp.ModelType);\n            Assert.Equal(\"Prop2\", newProp.PropertyName);\n        }\n\n        class Class1\n        {\n            public string Prop1 { get; set; }\n        }\n\n        class Class2\n        {\n            public int Prop2 { get; set; }\n        }\n\n        // GetDisplayName()\n\n        [Fact]\n        public void ReturnsPropertyNameWhenSetAndDisplayNameIsNull()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            ModelMetadata metadata = new ModelMetadata(provider.Object, null, null, typeof(object), \"PropertyName\");\n\n            // Act\n            string result = metadata.GetDisplayName();\n\n            // Assert\n            Assert.Equal(\"PropertyName\", result);\n        }\n\n        [Fact]\n        public void ReturnsTypeNameWhenPropertyNameAndDisplayNameAreNull()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            ModelMetadata metadata = new ModelMetadata(provider.Object, null, null, typeof(object), null);\n\n            // Act\n            string result = metadata.GetDisplayName();\n\n            // Assert\n            Assert.Equal(\"Object\", result);\n        }\n\n        // Helpers\n\n        private class DummyContactModel\n        {\n            public int IntField = 0;\n            public string FirstName { get; set; }\n            public string LastName { get; set; }\n            public Nullable<int> NullableIntValue { get; set; }\n            public int[] Array { get; set; }\n\n            public string this[int index]\n            {\n                get { return \"Indexed into \" + index; }\n            }\n        }\n\n        private class DummyModelContainer\n        {\n            public DummyContactModel Model { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Metadata/Providers/AssociatedMetadataProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Metadata.Providers\n{\n    public class AssociatedMetadataProviderTest\n    {\n        // GetMetadataForProperties\n\n        [Fact]\n        public void GetMetadataForPropertiesNullContainerTypeThrows()\n        {\n            // Arrange\n            TestableAssociatedMetadataProvider provider = new TestableAssociatedMetadataProvider();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => provider.GetMetadataForProperties(new Object(), containerType: null),\n                \"containerType\");\n        }\n\n        [Fact]\n        public void GetMetadataForPropertiesCreatesMetadataForAllPropertiesOnModelWithPropertyValues()\n        {\n            // Arrange\n            PropertyModel model = new PropertyModel { LocalAttributes = 42, MetadataAttributes = \"hello\", MixedAttributes = 21.12 };\n            TestableAssociatedMetadataProvider provider = new TestableAssociatedMetadataProvider();\n\n            // Act\n            provider.GetMetadataForProperties(model, typeof(PropertyModel)).ToList(); // Call ToList() to force the lazy evaluation to evaluate\n\n            // Assert\n            CreateMetadataPrototypeParams local = Assert.Single(\n                provider.CreateMetadataPrototypeLog,\n                m => m.ContainerType == typeof(PropertyModel) && m.PropertyName == \"LocalAttributes\");\n            Assert.Equal(typeof(int), local.ModelType);\n            Assert.Contains(local.Attributes, a => a is RequiredAttribute);\n\n            CreateMetadataPrototypeParams metadata = Assert.Single(\n                provider.CreateMetadataPrototypeLog,\n                m => m.ContainerType == typeof(PropertyModel) && m.PropertyName == \"MetadataAttributes\");\n            Assert.Equal(typeof(string), metadata.ModelType);\n            Assert.Contains(metadata.Attributes, a => a is RangeAttribute);\n\n            CreateMetadataPrototypeParams mixed = Assert.Single(\n                provider.CreateMetadataPrototypeLog,\n                m => m.ContainerType == typeof(PropertyModel) && m.PropertyName == \"MixedAttributes\");\n            Assert.Equal(typeof(double), mixed.ModelType);\n            Assert.Contains(mixed.Attributes, a => a is RequiredAttribute);\n            Assert.Contains(mixed.Attributes, a => a is RangeAttribute);\n        }\n\n        [Fact]\n        public void GetMetadataForPropertyWithNullContainerReturnsMetadataWithNullValuesForProperties()\n        {\n            // Arrange\n            TestableAssociatedMetadataProvider provider = new TestableAssociatedMetadataProvider();\n\n            // Act\n            provider.GetMetadataForProperties(null, typeof(PropertyModel)).ToList(); // Call ToList() to force the lazy evaluation to evaluate\n\n            // Assert\n            Assert.True(provider.CreateMetadataFromPrototypeLog.Any());\n            foreach (var parms in provider.CreateMetadataFromPrototypeLog)\n            {\n                Assert.Null(parms.Model);\n            }\n        }\n\n        // GetMetadataForProperty\n\n        [Fact]\n        public void GetMetadataForPropertyNullContainerTypeThrows()\n        {\n            // Arrange\n            TestableAssociatedMetadataProvider provider = new TestableAssociatedMetadataProvider();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => provider.GetMetadataForProperty(modelAccessor: null, containerType: null, propertyName: \"propertyName\"),\n                \"containerType\");\n        }\n\n        [Fact]\n        public void GetMetadataForPropertyNullOrEmptyPropertyNameThrows()\n        {\n            // Arrange\n            TestableAssociatedMetadataProvider provider = new TestableAssociatedMetadataProvider();\n\n            // Act & Assert\n            Assert.ThrowsArgument(\n                () => provider.GetMetadataForProperty(modelAccessor: null, containerType: typeof(object), propertyName: null),\n                \"propertyName\",\n                \"The argument 'propertyName' is null or empty.\");\n            Assert.ThrowsArgument(\n                () => provider.GetMetadataForProperty(modelAccessor: null, containerType: typeof(object), propertyName: String.Empty),\n                \"propertyName\",\n                \"The argument 'propertyName' is null or empty.\");\n        }\n\n        [Fact]\n        public void GetMetadataForPropertyInvalidPropertyNameThrows()\n        {\n            // Arrange\n            TestableAssociatedMetadataProvider provider = new TestableAssociatedMetadataProvider();\n\n            // Act & Assert\n            Assert.ThrowsArgument(\n                () => provider.GetMetadataForProperty(modelAccessor: null, containerType: typeof(object), propertyName: \"BadPropertyName\"),\n                \"propertyName\",\n                \"The property System.Object.BadPropertyName could not be found.\");\n        }\n\n        [Fact]\n        public void GetMetadataForPropertyWithLocalAttributes()\n        {\n            // Arrange\n            TestableAssociatedMetadataProvider provider = new TestableAssociatedMetadataProvider();\n            ModelMetadata metadata = new ModelMetadata(provider, typeof(PropertyModel), null, typeof(int), \"LocalAttributes\");\n            provider.CreateMetadataFromPrototypeReturnValue = metadata;\n\n            // Act\n            ModelMetadata result = provider.GetMetadataForProperty(null, typeof(PropertyModel), \"LocalAttributes\");\n\n            // Assert\n            Assert.Same(metadata, result);\n            CreateMetadataPrototypeParams metadataPrototypeParams = Assert.Single(\n                provider.CreateMetadataPrototypeLog,\n                parameters => parameters.PropertyName == \"LocalAttributes\");\n            Assert.Contains(metadataPrototypeParams.Attributes, a => a is RequiredAttribute);\n        }\n\n        [Fact]\n        public void GetMetadataForPropertyWithMetadataAttributes()\n        {\n            // Arrange\n            TestableAssociatedMetadataProvider provider = new TestableAssociatedMetadataProvider();\n            ModelMetadata metadata = new ModelMetadata(provider, typeof(PropertyModel), null, typeof(string), \"MetadataAttributes\");\n            provider.CreateMetadataFromPrototypeReturnValue = metadata;\n\n            // Act\n            ModelMetadata result = provider.GetMetadataForProperty(null, typeof(PropertyModel), \"MetadataAttributes\");\n\n            // Assert\n            Assert.Same(metadata, result);\n            CreateMetadataPrototypeParams parms = Assert.Single(\n                provider.CreateMetadataPrototypeLog,\n                parameters => parameters.PropertyName == \"MetadataAttributes\");\n            Assert.Contains(parms.Attributes, a => a is RangeAttribute);\n        }\n\n        [Fact]\n        public void GetMetadataForPropertyWithMixedAttributes()\n        {\n            // Arrange\n            TestableAssociatedMetadataProvider provider = new TestableAssociatedMetadataProvider();\n            ModelMetadata metadata = new ModelMetadata(provider, typeof(PropertyModel), null, typeof(double), \"MixedAttributes\");\n            provider.CreateMetadataFromPrototypeReturnValue = metadata;\n\n            // Act\n            ModelMetadata result = provider.GetMetadataForProperty(null, typeof(PropertyModel), \"MixedAttributes\");\n\n            // Assert\n            Assert.Same(metadata, result);\n            CreateMetadataPrototypeParams parms = Assert.Single(\n                provider.CreateMetadataPrototypeLog,\n                p => p.PropertyName == \"MixedAttributes\");\n            Assert.Contains(parms.Attributes, a => a is RequiredAttribute);\n            Assert.Contains(parms.Attributes, a => a is RangeAttribute);\n        }\n\n        // GetMetadataForType\n\n        [Fact]\n        public void GetMetadataForTypeNullModelTypeThrows()\n        {\n            // Arrange\n            TestableAssociatedMetadataProvider provider = new TestableAssociatedMetadataProvider();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => provider.GetMetadataForType(() => new Object(), modelType: null),\n                \"modelType\");\n        }\n\n        [Fact]\n        public void GetMetadataForTypeIncludesAttributesOnType()\n        {\n            TestableAssociatedMetadataProvider provider = new TestableAssociatedMetadataProvider();\n            ModelMetadata metadata = new ModelMetadata(provider, null, null, typeof(TypeModel), null);\n            provider.CreateMetadataFromPrototypeReturnValue = metadata;\n\n            // Act\n            ModelMetadata result = provider.GetMetadataForType(null, typeof(TypeModel));\n\n            // Assert\n            Assert.Same(metadata, result);\n            CreateMetadataPrototypeParams parms = Assert.Single(\n                provider.CreateMetadataPrototypeLog,\n                p => p.ModelType == typeof(TypeModel));\n            Assert.Contains(parms.Attributes, a => a is ReadOnlyAttribute);\n        }\n\n        // Helpers\n\n        [MetadataType(typeof(Metadata))]\n        private class PropertyModel\n        {\n            [Required]\n            public int LocalAttributes { get; set; }\n\n            public string MetadataAttributes { get; set; }\n\n            [Required]\n            public double MixedAttributes { get; set; }\n\n            private class Metadata\n            {\n                [Range(10, 100)]\n                public object MetadataAttributes { get; set; }\n\n                [Range(10, 100)]\n                public object MixedAttributes { get; set; }\n            }\n        }\n\n        private class ModelWithReadOnlyProperty\n        {\n            public int ReadOnlyProperty { get; private set; }\n        }\n\n        [ReadOnly(true)]\n        private class TypeModel\n        {\n        }\n\n        class TestableAssociatedMetadataProvider : AssociatedMetadataProvider<ModelMetadata>\n        {\n            public List<CreateMetadataPrototypeParams> CreateMetadataPrototypeLog = new List<CreateMetadataPrototypeParams>();\n            public List<CreateMetadataFromPrototypeParams> CreateMetadataFromPrototypeLog = new List<CreateMetadataFromPrototypeParams>();\n            public ModelMetadata CreateMetadataPrototypeReturnValue = null;\n            public ModelMetadata CreateMetadataFromPrototypeReturnValue = null;\n\n            protected override ModelMetadata CreateMetadataPrototype(IEnumerable<Attribute> attributes, Type containerType, Type modelType, string propertyName)\n            {\n                CreateMetadataPrototypeLog.Add(new CreateMetadataPrototypeParams\n                {\n                    Attributes = attributes,\n                    ContainerType = containerType,\n                    ModelType = modelType,\n                    PropertyName = propertyName\n                });\n\n                return CreateMetadataPrototypeReturnValue;\n            }\n\n            protected override ModelMetadata CreateMetadataFromPrototype(ModelMetadata prototype, Func<object> modelAccessor)\n            {\n                CreateMetadataFromPrototypeLog.Add(new CreateMetadataFromPrototypeParams\n                {\n                    Prototype = prototype,\n                    Model = modelAccessor == null ? null : modelAccessor()\n                });\n\n                return CreateMetadataFromPrototypeReturnValue;\n            }\n        }\n\n        class CreateMetadataPrototypeParams\n        {\n            public IEnumerable<Attribute> Attributes { get; set; }\n            public Type ContainerType { get; set; }\n            public Type ModelType { get; set; }\n            public string PropertyName { get; set; }\n        }\n\n        class CreateMetadataFromPrototypeParams\n        {\n            public ModelMetadata Prototype { get; set; }\n            public object Model { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Metadata/Providers/DataAnnotationsModelMetadataProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Metadata.Providers\n{\n    public class DataAnnotationsModelMetadataProviderTest\n    {\n        [Fact]\n        public void GetMetadataForPropertiesSetTypesAndPropertyNames()\n        {\n            // Arrange\n            var provider = new DataAnnotationsModelMetadataProvider();\n\n            // Act\n            IEnumerable<ModelMetadata> result = provider.GetMetadataForProperties(\"foo\", typeof(string));\n\n            // Assert\n            Assert.Contains(result, m => m.ModelType == typeof(int)\n                                        && m.PropertyName == \"Length\"\n                                        && (int)m.Model == 3);\n        }\n\n        [Fact]\n        public void GetMetadataForPropertySetsTypeAndPropertyName()\n        {\n            // Arrange\n            var provider = new DataAnnotationsModelMetadataProvider();\n\n            // Act\n            ModelMetadata result = provider.GetMetadataForProperty(null, typeof(string), \"Length\");\n\n            // Assert\n            Assert.Equal(typeof(int), result.ModelType);\n            Assert.Equal(\"Length\", result.PropertyName);\n        }\n\n        [Fact]\n        public void GetMetadataForTypeSetsTypeWithNullPropertyName()\n        {\n            // Arrange\n            var provider = new DataAnnotationsModelMetadataProvider();\n\n            // Act\n            ModelMetadata result = provider.GetMetadataForType(null, typeof(string));\n\n            // Assert\n            Assert.Equal(typeof(string), result.ModelType);\n            Assert.Null(result.PropertyName);\n        }\n\n        [Theory]\n        [InlineData(\"NoAttributes\", false)]\n        [InlineData(\"ReadOnlyAttribute\", true)]\n        [InlineData(\"EditableAttribute\", true)]\n        [InlineData(\"BothAttributes\", false)]\n        public void ReadOnlyTests(string propertyName, bool expected)\n        {\n            // Arrange\n            var provider = new DataAnnotationsModelMetadataProvider();\n\n            // Act\n            var actual = provider.GetMetadataForProperty(null, typeof(ReadOnlyModel), propertyName).IsReadOnly;\n\n            // Assert\n            Assert.Equal(expected, actual);\n        }\n\n        [Theory]\n        [InlineData(\"NoAttribute\", \"NoAttribute\")]\n        [InlineData(\"NothingSet\", \"NothingSet\")]\n        [InlineData(\"EmptyDisplayName\", \"\")]\n        [InlineData(\"DescriptionSet\", \"DescriptionSet\")]\n        [InlineData(\"NameSet\", \"Name text1\")]\n        [InlineData(\"DisplayNameSet\", \"Just DisplayName\")]\n        [InlineData(\"BothSet\", \"Name text2\")]\n        [InlineData(\"FallbackToDisplayName\", \"Fallback\")]\n        [InlineData(\"FallbackToProperty\", \"FallbackToProperty\")]\n        [InlineData(\"FallbackToPropertyFromDisplayName\", \"FallbackToPropertyFromDisplayName\")]\n        [InlineData(\"DisplayNameDefault\", \"\")] // The default for DisplayName is the empty string, we don't have special handling for it, and nither does MVC.\n        public void DataAnnotationsNameTests(string propertyName, string expected)\n        {\n            // Arrange\n            var provider = new DataAnnotationsModelMetadataProvider();\n\n            // Act\n            var actual = provider.GetMetadataForProperty(null, typeof(DisplayModel), propertyName).GetDisplayName();\n\n            // Assert\n            Assert.Equal(expected, actual);\n        }\n\n        [Fact]\n        public void DisplayAttribute_WithLocalizedName()\n        {\n            // Guard\n            var expected = Resources.String1;\n            Assert.NotEqual(\"String1\", expected);\n\n            // Arrange\n            var provider = new DataAnnotationsModelMetadataProvider();\n\n            // Act\n            var actual = provider.GetMetadataForProperty(null, typeof(DisplayModel), \"Localized\").GetDisplayName();\n            \n            // Assert\n            Assert.Equal(expected, actual);\n        }\n\n        [Theory]\n        [InlineData(\"NoAttribute\", null)]\n        [InlineData(\"NothingSet\", null)]\n        [InlineData(\"NameSet\", null)]\n        [InlineData(\"DescriptionSet\", \"Description text1\")]\n        [InlineData(\"BothSet\", \"Description text2\")]\n        public void DataAnnotationsDescriptionTests(string propertyName, string expected)\n        {\n            // Arrange\n            var provider = new DataAnnotationsModelMetadataProvider();\n\n            // Act\n            var actual = provider.GetMetadataForProperty(null, typeof(DisplayModel), propertyName).Description;\n\n            // Assert\n            Assert.Equal(expected, actual);\n        }\n\n        // [Display] & [DisplayName] tests\n        private class DisplayModel\n        {\n            public int NoAttribute { get; set; }\n\n            // Description + Name combination.\n\n            [Display]\n            public int NothingSet { get; set; }\n\n            [Display(Name = \"\")]\n            public int EmptyDisplayName { get; set; }\n\n            [Display(Description = \"Description text1\")]\n            public int DescriptionSet { get; set; }\n\n            [Display(Name = \"Name text1\")]\n            public int NameSet { get; set; }\n\n            [DisplayName(\"Just DisplayName\")]\n            public int DisplayNameSet { get; set; }\n\n            [Display(Description = \"Description text2\", Name = \"Name text2\")]\n            [DisplayName(\"This won't be used\")]\n            public int BothSet { get; set; }\n\n            [Display(Name = \"String1\", ResourceType = typeof(Resources))]\n            public int Localized { get; set; }\n\n            [Display]\n            [DisplayName(\"Fallback\")]\n            public int FallbackToDisplayName { get; set; }\n\n            [Display]\n            public int FallbackToProperty { get; set; }\n\n            [DisplayName(null)]\n            public int FallbackToPropertyFromDisplayName { get; set; }\n\n            [DisplayName]\n            public int DisplayNameDefault { get; set; }\n        }\n\n        // [ReadOnly] & [Editable] tests\n        private class ReadOnlyModel\n        {\n            public int NoAttributes { get; set; }\n\n            [ReadOnly(true)]\n            public int ReadOnlyAttribute { get; set; }\n\n            [Editable(false)]\n            public int EditableAttribute { get; set; }\n\n            [ReadOnly(true)]\n            [Editable(true)]\n            public int BothAttributes { get; set; }\n\n            // Editable trumps ReadOnly\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/Binders/ArrayModelBinderProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http.Metadata.Providers;\nusing System.Web.Http.Util;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public class ArrayModelBinderProviderTest\n    {\n        [Fact]\n        public void GetBinder_CorrectModelTypeAndValueProviderEntries_ReturnsBinder()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int[])),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleHttpValueProvider\n                {\n                    { \"foo[0]\", \"42\" },\n                }\n            };\n\n            ArrayModelBinderProvider binderProvider = new ArrayModelBinderProvider();\n\n            // Act\n            IModelBinder binder = binderProvider.GetBinder(null, bindingContext.ModelType);\n\n            // Assert\n            Assert.IsType<ArrayModelBinder<int>>(binder);\n        }\n\n        [Fact]\n        public void GetBinder_ModelTypeIsIncorrect_ReturnsNull()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(ICollection<int>)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleHttpValueProvider\n                {\n                    { \"foo[0]\", \"42\" },\n                }\n            };\n\n            ArrayModelBinderProvider binderProvider = new ArrayModelBinderProvider();\n\n            // Act\n            IModelBinder binder = binderProvider.GetBinder(null, bindingContext.ModelType);\n\n            // Assert\n            Assert.Null(binder);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/Binders/ArrayModelBinderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata.Providers;\nusing System.Web.Http.Util;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public class ArrayModelBinderTest\n    {\n        [Fact]\n        public void BindModel()\n        {\n            // Arrange\n            Mock<IModelBinder> mockIntBinder = new Mock<IModelBinder>();\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            context.ControllerContext.Configuration.Services.Replace(typeof(ModelBinderProvider), new SimpleModelBinderProvider(typeof(int), mockIntBinder.Object));\n\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int[])),\n                ModelName = \"someName\",\n                ValueProvider = new SimpleHttpValueProvider\n                {\n                    { \"someName[0]\", \"42\" },\n                    { \"someName[1]\", \"84\" }\n                }\n            };\n            mockIntBinder\n                .Setup(o => o.BindModel(context, It.IsAny<ModelBindingContext>()))\n                .Returns((HttpActionContext ec, ModelBindingContext mbc) =>\n                {\n                    mbc.Model = mbc.ValueProvider.GetValue(mbc.ModelName).ConvertTo(mbc.ModelType);\n                    return true;\n                });\n\n            // Act\n            bool retVal = new ArrayModelBinder<int>().BindModel(context, bindingContext);\n\n            // Assert\n            Assert.True(retVal);\n\n            int[] array = bindingContext.Model as int[];\n            Assert.Equal(new[] { 42, 84 }, array);\n        }\n\n        [Fact]\n        public void GetBinder_ValueProviderDoesNotContainPrefix_ReturnsNull()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int[])),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleHttpValueProvider()\n            };\n\n            ArrayModelBinderProvider binderProvider = new ArrayModelBinderProvider();\n\n            // Act\n            IModelBinder binder = binderProvider.GetBinder(null, bindingContext.ModelType);\n            bool bound = binder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.False(bound);\n        }\n\n        [Fact]\n        public void GetBinder_ModelMetadataReturnsReadOnly_ReturnsNull()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int[])),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleHttpValueProvider\n                {\n                    { \"foo[0]\", \"42\" },\n                }\n            };\n            bindingContext.ModelMetadata.IsReadOnly = true;\n\n            ArrayModelBinderProvider binderProvider = new ArrayModelBinderProvider();\n\n            // Act\n            IModelBinder binder = binderProvider.GetBinder(null, bindingContext.ModelType);\n            bool bound = binder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.False(bound);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/Binders/CollectionModelBinderProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http.Metadata.Providers;\nusing System.Web.Http.ModelBinding.Binders;\nusing System.Web.Http.Util;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ModelBinding\n{\n    public class CollectionModelBinderProviderTest\n    {\n        [Fact]\n        public void GetBinder_CorrectModelTypeAndValueProviderEntries_ReturnsBinder()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(IEnumerable<int>)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleHttpValueProvider\n                {\n                    { \"foo[0]\", \"42\" },\n                }\n            };\n\n            CollectionModelBinderProvider binderProvider = new CollectionModelBinderProvider();\n\n            // Act\n            IModelBinder binder = binderProvider.GetBinder(null, bindingContext.ModelType);\n\n            // Assert\n            Assert.IsType<CollectionModelBinder<int>>(binder);\n        }\n\n        [Fact]\n        public void GetBinder_ModelTypeIsIncorrect_ReturnsNull()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleHttpValueProvider\n                {\n                    { \"foo[0]\", \"42\" },\n                }\n            };\n\n            CollectionModelBinderProvider binderProvider = new CollectionModelBinderProvider();\n\n            // Act\n            IModelBinder binder = binderProvider.GetBinder(null, bindingContext.ModelType);\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        [Fact]\n        public void GetBinder_ModelTypeIsNullable_ReturnsNull()\n        {\n            // Arrange\n            CollectionModelBinderProvider binderProvider = new CollectionModelBinderProvider();\n\n            // Act\n            IModelBinder binder = binderProvider.GetBinder(null, typeof(int?));\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        [Fact]\n        public void GetBinder_ModelTypeIsGeneric_ReturnsNull()\n        {\n            // Arrange\n            CollectionModelBinderProvider binderProvider = new CollectionModelBinderProvider();\n\n            // Act\n            IModelBinder binder = binderProvider.GetBinder(null, typeof(Tuple<int>));\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        [Fact]\n        public void GetBinder_ValueProviderDoesNotContainPrefix_ReturnsNull()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(IEnumerable<int>)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleHttpValueProvider()\n            };\n\n            CollectionModelBinderProvider binderProvider = new CollectionModelBinderProvider();\n\n            // Act\n            IModelBinder binder = binderProvider.GetBinder(null, bindingContext.ModelType);\n            bool bound = binder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.False(bound);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/Binders/CollectionModelBinderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Metadata.Providers;\nusing System.Web.Http.ModelBinding.Binders;\nusing System.Web.Http.Util;\nusing System.Web.Http.Validation;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.ModelBinding\n{\n    public class CollectionModelBinderTest\n    {\n        [Fact]\n        public void BindComplexCollectionFromIndexes_FiniteIndexes()\n        {\n            // Arrange\n            CultureInfo culture = CultureInfo.GetCultureInfo(\"fr-FR\");\n            Mock<IModelBinder> mockIntBinder = new Mock<IModelBinder>();\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),\n                ModelName = \"someName\",\n                ValueProvider = new SimpleHttpValueProvider\n                {\n                    { \"someName[foo]\", \"42\" },\n                    { \"someName[baz]\", \"200\" }\n                }\n            };\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            context.ControllerContext.Configuration.Services.Replace(typeof(ModelBinderProvider), new SimpleModelBinderProvider(typeof(int), mockIntBinder.Object));\n\n            mockIntBinder\n                .Setup(o => o.BindModel(context, It.IsAny<ModelBindingContext>()))\n                .Returns((HttpActionContext ec, ModelBindingContext mbc) =>\n                {\n                    mbc.Model = mbc.ValueProvider.GetValue(mbc.ModelName).ConvertTo(mbc.ModelType);\n                    return true;\n                });\n\n            // Act\n            List<int> boundCollection = CollectionModelBinder<int>.BindComplexCollectionFromIndexes(context, bindingContext, new[] { \"foo\", \"bar\", \"baz\" });\n\n            // Assert\n            Assert.Equal(new[] { 42, 0, 200 }, boundCollection.ToArray());\n            Assert.Equal(new[] { \"someName[foo]\", \"someName[baz]\" }, bindingContext.ValidationNode.ChildNodes.Select(o => o.ModelStateKey).ToArray());\n        }\n\n        [Fact]\n        public void BindComplexCollectionFromIndexes_InfiniteIndexes()\n        {\n            // Arrange\n            CultureInfo culture = CultureInfo.GetCultureInfo(\"fr-FR\");\n            Mock<IModelBinder> mockIntBinder = new Mock<IModelBinder>();\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),\n                ModelName = \"someName\",\n                ValueProvider = new SimpleHttpValueProvider\n                {\n                    { \"someName[0]\", \"42\" },\n                    { \"someName[1]\", \"100\" },\n                    { \"someName[3]\", \"400\" }\n                }\n            };\n\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            context.ControllerContext.Configuration.Services.Replace(typeof(ModelBinderProvider), new SimpleModelBinderProvider(typeof(int), mockIntBinder.Object));\n\n            mockIntBinder\n                .Setup(o => o.BindModel(context, It.IsAny<ModelBindingContext>()))\n                .Returns((HttpActionContext ec, ModelBindingContext mbc) =>\n                {\n                    mbc.Model = mbc.ValueProvider.GetValue(mbc.ModelName).ConvertTo(mbc.ModelType);\n                    return true;\n                });\n\n            // Act\n            List<int> boundCollection = CollectionModelBinder<int>.BindComplexCollectionFromIndexes(context, bindingContext, null /* indexNames */);\n\n            // Assert\n            Assert.Equal(new[] { 42, 100 }, boundCollection.ToArray());\n            Assert.Equal(new[] { \"someName[0]\", \"someName[1]\" }, bindingContext.ValidationNode.ChildNodes.Select(o => o.ModelStateKey).ToArray());\n        }\n\n        [Fact]\n        public void BindModel_ComplexCollection()\n        {\n            // Arrange\n            CultureInfo culture = CultureInfo.GetCultureInfo(\"fr-FR\");\n            Mock<IModelBinder> mockIntBinder = new Mock<IModelBinder>();\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),\n                ModelName = \"someName\",\n                ValueProvider = new SimpleHttpValueProvider\n                {\n                    { \"someName.index\", new[] { \"foo\", \"bar\", \"baz\" } },\n                    { \"someName[foo]\", \"42\" },\n                    { \"someName[bar]\", \"100\" },\n                    { \"someName[baz]\", \"200\" }\n                }\n            };\n\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            context.ControllerContext.Configuration.Services.Replace(typeof(ModelBinderProvider), new SimpleModelBinderProvider(typeof(int), mockIntBinder.Object));\n\n            mockIntBinder\n                .Setup(o => o.BindModel(context, It.IsAny<ModelBindingContext>()))\n                .Returns((HttpActionContext ec, ModelBindingContext mbc) =>\n                {\n                    mbc.Model = mbc.ValueProvider.GetValue(mbc.ModelName).ConvertTo(mbc.ModelType);\n                    return true;\n                });\n\n            CollectionModelBinder<int> modelBinder = new CollectionModelBinder<int>();\n\n            // Act\n            bool retVal = modelBinder.BindModel(context, bindingContext);\n\n            // Assert\n            Assert.Equal(new[] { 42, 100, 200 }, ((List<int>)bindingContext.Model).ToArray());\n        }\n\n        [Fact]\n        public void BindModel_SimpleCollection()\n        {\n            // Arrange\n            CultureInfo culture = CultureInfo.GetCultureInfo(\"fr-FR\");\n            Mock<IModelBinder> mockIntBinder = new Mock<IModelBinder>();\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),\n                ModelName = \"someName\",\n                ValueProvider = new SimpleHttpValueProvider\n                {\n                    { \"someName\", new[] { \"42\", \"100\", \"200\" } }\n                }\n            };\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            context.ControllerContext.Configuration.Services.Replace(typeof(ModelBinderProvider), new SimpleModelBinderProvider(typeof(int), mockIntBinder.Object));\n\n            mockIntBinder\n                .Setup(o => o.BindModel(context, It.IsAny<ModelBindingContext>()))\n                .Returns((HttpActionContext ec, ModelBindingContext mbc) =>\n                {\n                    mbc.Model = mbc.ValueProvider.GetValue(mbc.ModelName).ConvertTo(mbc.ModelType);\n                    return true;\n                });\n\n            CollectionModelBinder<int> modelBinder = new CollectionModelBinder<int>();\n\n            // Act\n            bool retVal = modelBinder.BindModel(context, bindingContext);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Equal(new[] { 42, 100, 200 }, ((List<int>)bindingContext.Model).ToArray());\n        }\n\n        [Fact]\n        public void BindSimpleCollection_RawValueIsEmptyCollection_ReturnsEmptyList()\n        {\n            // Act\n            List<int> boundCollection = CollectionModelBinder<int>.BindSimpleCollection(null, null, new object[0], null);\n\n            // Assert\n            Assert.NotNull(boundCollection);\n            Assert.Empty(boundCollection);\n        }\n\n        [Fact]\n        public void BindSimpleCollection_RawValueIsNull_ReturnsNull()\n        {\n            // Act\n            List<int> boundCollection = CollectionModelBinder<int>.BindSimpleCollection(null, null, null, null);\n\n            // Assert\n            Assert.Null(boundCollection);\n        }\n\n        [Fact]\n        public void BindSimpleCollection_SubBindingSucceeds()\n        {\n            // Arrange\n            CultureInfo culture = CultureInfo.GetCultureInfo(\"fr-FR\");\n            Mock<IModelBinder> mockIntBinder = new Mock<IModelBinder>();\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),\n                ModelName = \"someName\",\n                ValueProvider = new SimpleHttpValueProvider()\n            };\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            context.ControllerContext.Configuration.Services.Replace(typeof(ModelBinderProvider), new SimpleModelBinderProvider(typeof(int), mockIntBinder.Object));\n\n            ModelValidationNode childValidationNode = null;\n            mockIntBinder\n                .Setup(o => o.BindModel(context, It.IsAny<ModelBindingContext>()))\n                .Returns((HttpActionContext ec, ModelBindingContext mbc) =>\n                {\n                    Assert.Equal(\"someName\", mbc.ModelName);\n                    childValidationNode = mbc.ValidationNode;\n                    mbc.Model = 42;\n                    return true;\n                });\n\n            // Act\n            List<int> boundCollection = CollectionModelBinder<int>.BindSimpleCollection(context, bindingContext, new int[1], culture);\n\n            // Assert\n            Assert.Equal(new[] { 42 }, boundCollection.ToArray());\n            Assert.Equal(new[] { childValidationNode }, bindingContext.ValidationNode.ChildNodes.ToArray());\n        }\n\n        [Fact]\n        public void BindingUnboundedCollection_WhenNoValuesArePresent_ProducesSingleEntryCollection()\n        {\n            // Arrange\n            string propertyName = \"Addresses\";\n            ModelMetadata modelMetadata = new EmptyModelMetadataProvider().GetMetadataForProperty(\n                                                            modelAccessor: null,\n                                                            containerType: typeof(UserWithAddress),\n                                                            propertyName: propertyName);\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = modelMetadata,\n                ModelName = propertyName,\n                ValueProvider = new SimpleHttpValueProvider { { propertyName, \"some value\" } }\n            };\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            CollectionModelBinder<UserWithAddress> binder = new CollectionModelBinder<UserWithAddress>();\n\n            // Act\n            bool result = binder.BindModel(context, bindingContext);\n\n            // Assert\n            Assert.True(result);\n            List<UserWithAddress> boundModel = Assert.IsType<List<UserWithAddress>>(bindingContext.Model);\n            UserWithAddress listModel = Assert.Single(boundModel);\n            Assert.Null(listModel.Addresses);\n        }\n\n        [Fact]\n        public void BindingNestedUnboundedCollection_WhenNoValuesArePresent_ProducesEmptyCollection()\n        {\n            // Arrange\n            string propertyName = \"Addresses\";\n            ModelMetadata modelMetadata = new EmptyModelMetadataProvider().GetMetadataForProperty(\n                                                            modelAccessor: null,\n                                                            containerType: typeof(UserWithAddress),\n                                                            propertyName: propertyName);\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = modelMetadata,\n                ModelName = propertyName,\n                ValueProvider = new SimpleHttpValueProvider { { \"Addresses.AddressLines\", \"some value\" } }\n            };\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            CollectionModelBinder<UserWithAddress> binder = new CollectionModelBinder<UserWithAddress>();\n\n            // Act\n            bool result = binder.BindModel(context, bindingContext);\n\n            // Assert\n            Assert.True(result);\n            List<UserWithAddress> boundModel = Assert.IsType<List<UserWithAddress>>(bindingContext.Model);\n            Assert.Empty(boundModel);\n        }\n\n        [Fact]\n        public void BindingListsWithIndex_ProducesSingleLengthCollection_WithNullValues()\n        {\n            // Arrange\n            string propertyName = \"Addresses\";\n            ModelMetadata modelMetadata = new EmptyModelMetadataProvider().GetMetadataForProperty(\n                                                            modelAccessor: null,\n                                                            containerType: typeof(UserWithAddress),\n                                                            propertyName: propertyName);\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = modelMetadata,\n                ModelName = propertyName,\n                ValueProvider = new SimpleHttpValueProvider { { \"Addresses.index\", \"10000\" } }\n            };\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            CollectionModelBinder<UserWithAddress> binder = new CollectionModelBinder<UserWithAddress>();\n\n            // Act\n            bool result = binder.BindModel(context, bindingContext);\n\n            // Assert\n            Assert.True(result);\n            List<UserWithAddress> boundModel = Assert.IsType<List<UserWithAddress>>(bindingContext.Model);\n            UserWithAddress listModel = Assert.Single(boundModel);\n            Assert.Null(listModel);\n        }\n\n        [Fact]\n        public void BindingUnboundedCollection_WithRecursiveRelation_ProducesSingleLengthCollection()\n        {\n            // Arrange\n            string propertyName = \"People\";\n            ModelMetadata modelMetadata = new EmptyModelMetadataProvider().GetMetadataForProperty(\n                                                            modelAccessor: null,\n                                                            containerType: typeof(PeopleModel),\n                                                            propertyName: propertyName);\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = modelMetadata,\n                ModelName = propertyName,\n                ValueProvider = new SimpleHttpValueProvider { { propertyName, \"test value\" } }\n            };\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            CollectionModelBinder<Person> binder =\n                new CollectionModelBinder<Person>();\n\n            // Act\n            bool result = binder.BindModel(context, bindingContext);\n\n            // Assert\n            Assert.True(result);\n            List<Person> boundModel = Assert.IsType<List<Person>>(bindingContext.Model);\n            Person type = Assert.Single(boundModel);\n            Assert.Null(type.Name);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/Binders/ComplexModelDtoModelBinderProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Metadata.Providers;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public class ComplexModelDtoModelBinderProviderTest\n    {\n        [Fact]\n        public void GetBinder_TypeDoesNotMatch_ReturnsNull()\n        {\n            // Arrange\n            ComplexModelDtoModelBinderProvider provider = new ComplexModelDtoModelBinderProvider();\n            ModelBindingContext bindingContext = GetBindingContext(typeof(object));\n\n            // Act\n            IModelBinder binder = provider.GetBinder(null, bindingContext.ModelType);\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        private static ModelBindingContext GetBindingContext(Type modelType)\n        {\n            return new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => null, modelType)\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/Binders/ComplexModelDtoModelBinderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Metadata.Providers;\nusing System.Web.Http.Validation;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public class ComplexModelDtoModelBinderTest\n    {\n        [Fact]\n        public void BindModel()\n        {\n            // Arrange\n            MyModel model = new MyModel();\n            ModelMetadata modelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => model, typeof(MyModel));\n            ComplexModelDto dto = new ComplexModelDto(modelMetadata, modelMetadata.Properties);\n            Mock<IModelBinder> mockStringBinder = new Mock<IModelBinder>();\n            Mock<IModelBinder> mockIntBinder = new Mock<IModelBinder>();\n            Mock<IModelBinder> mockDateTimeBinder = new Mock<IModelBinder>();\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            context.ControllerContext.Configuration.Services.ReplaceRange(typeof(ModelBinderProvider),\n                new ModelBinderProvider[] {\n                    new SimpleModelBinderProvider(typeof(string), mockStringBinder.Object) { SuppressPrefixCheck = true },\n                    new SimpleModelBinderProvider(typeof(int), mockIntBinder.Object) { SuppressPrefixCheck = true },\n                    new SimpleModelBinderProvider(typeof(DateTime), mockDateTimeBinder.Object) { SuppressPrefixCheck = true }\n                });\n\n            mockStringBinder\n                .Setup(b => b.BindModel(context, It.IsAny<ModelBindingContext>()))\n                .Returns((HttpActionContext ec, ModelBindingContext mbc) =>\n                {\n                    Assert.Equal(typeof(string), mbc.ModelType);\n                    Assert.Equal(\"theModel.StringProperty\", mbc.ModelName);\n                    mbc.ValidationNode = new ModelValidationNode(mbc.ModelMetadata, \"theModel.StringProperty\");\n                    mbc.Model = \"someStringValue\";\n                    return true;\n                });\n            mockIntBinder\n                .Setup(b => b.BindModel(context, It.IsAny<ModelBindingContext>()))\n                .Returns((HttpActionContext ec, ModelBindingContext mbc) =>\n                {\n                    Assert.Equal(typeof(int), mbc.ModelType);\n                    Assert.Equal(\"theModel.IntProperty\", mbc.ModelName);\n                    mbc.ValidationNode = new ModelValidationNode(mbc.ModelMetadata, \"theModel.IntProperty\");\n                    mbc.Model = 42;\n                    return true;\n                });\n            mockDateTimeBinder\n                .Setup(b => b.BindModel(context, It.IsAny<ModelBindingContext>()))\n                .Returns((HttpActionContext ec, ModelBindingContext mbc) =>\n                {\n                    Assert.Equal(typeof(DateTime), mbc.ModelType);\n                    Assert.Equal(\"theModel.DateTimeProperty\", mbc.ModelName);\n                    return false;\n                });\n            ModelBindingContext parentBindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => dto, typeof(ComplexModelDto)),\n                ModelName = \"theModel\",\n            };\n            ComplexModelDtoModelBinder binder = new ComplexModelDtoModelBinder();\n\n            // Act\n            bool retVal = binder.BindModel(context, parentBindingContext);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Equal(dto, parentBindingContext.Model);\n\n            ComplexModelDtoResult stringDtoResult = dto.Results[dto.PropertyMetadata.Where(m => m.ModelType == typeof(string)).First()];\n            Assert.Equal(\"someStringValue\", stringDtoResult.Model);\n            Assert.Equal(\"theModel.StringProperty\", stringDtoResult.ValidationNode.ModelStateKey);\n\n            ComplexModelDtoResult intDtoResult = dto.Results[dto.PropertyMetadata.Where(m => m.ModelType == typeof(int)).First()];\n            Assert.Equal(42, intDtoResult.Model);\n            Assert.Equal(\"theModel.IntProperty\", intDtoResult.ValidationNode.ModelStateKey);\n\n            // Bind failed, so DateTime won't even be in the DTO dictionary\n            bool containsMissingKey = dto.Results.ContainsKey(dto.PropertyMetadata.Where(m => m.ModelType == typeof(DateTime)).First());\n            Assert.False(containsMissingKey);\n        }\n\n        private sealed class MyModel\n        {\n            public string StringProperty { get; set; }\n            public int IntProperty { get; set; }\n            public object ObjectProperty { get; set; } // no binding should happen since no registered binder\n            public DateTime DateTimeProperty { get; set; } // registered binder returns false\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/Binders/ComplexModelDtoResultTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Metadata.Providers;\nusing System.Web.Http.Validation;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public class ComplexModelDtoResultTest\n    {\n        [Fact]\n        public void Constructor_ThrowsIfValidationNodeIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                () => new ComplexModelDtoResult(\"some string\", null),\n                \"validationNode\");\n        }\n\n        [Fact]\n        public void Constructor_SetsProperties()\n        {\n            // Arrange\n            ModelValidationNode validationNode = GetValidationNode();\n\n            // Act\n            ComplexModelDtoResult result = new ComplexModelDtoResult(\"some string\", validationNode);\n\n            // Assert\n            Assert.Equal(\"some string\", result.Model);\n            Assert.Equal(validationNode, result.ValidationNode);\n        }\n\n        private static ModelValidationNode GetValidationNode()\n        {\n            EmptyModelMetadataProvider provider = new EmptyModelMetadataProvider();\n            ModelMetadata metadata = provider.GetMetadataForType(null, typeof(object));\n            return new ModelValidationNode(metadata, \"someKey\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/Binders/ComplexModelDtoTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Metadata.Providers;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public class ComplexModelDtoTest\n    {\n        [Fact]\n        public void ConstructorThrowsIfModelMetadataIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                () => new ComplexModelDto(null, Enumerable.Empty<ModelMetadata>()),\n                \"modelMetadata\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfPropertyMetadataIsNull()\n        {\n            // Arrange\n            ModelMetadata modelMetadata = GetModelMetadata();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                () => new ComplexModelDto(modelMetadata, null),\n                \"propertyMetadata\");\n        }\n\n        [Fact]\n        public void ConstructorSetsProperties()\n        {\n            // Arrange\n            ModelMetadata modelMetadata = GetModelMetadata();\n            ModelMetadata[] propertyMetadata = new ModelMetadata[0];\n\n            // Act\n            ComplexModelDto dto = new ComplexModelDto(modelMetadata, propertyMetadata);\n\n            // Assert\n            Assert.Equal(modelMetadata, dto.ModelMetadata);\n            Assert.Equal(propertyMetadata, dto.PropertyMetadata.ToArray());\n            Assert.Empty(dto.Results);\n        }\n\n        private static ModelMetadata GetModelMetadata()\n        {\n            return new ModelMetadata(new EmptyModelMetadataProvider(), typeof(object), null, typeof(object), \"PropertyName\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/Binders/DictionaryModelBinderProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http.Metadata.Providers;\nusing System.Web.Http.Util;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public class DictionaryModelBinderProviderTest\n    {\n        [Fact]\n        public void GetBinder_CorrectModelTypeAndValueProviderEntries_ReturnsBinder()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(IDictionary<int, string>)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleHttpValueProvider\n                {\n                    { \"foo[0]\", \"42\" },\n                }\n            };\n\n            DictionaryModelBinderProvider binderProvider = new DictionaryModelBinderProvider();\n\n            // Act\n            IModelBinder binder = binderProvider.GetBinder(null, bindingContext.ModelType);\n\n            // Assert\n            Assert.IsType<DictionaryModelBinder<int, string>>(binder);\n        }\n\n        [Fact]\n        public void GetBinder_ModelTypeIsIncorrect_ReturnsNull()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleHttpValueProvider\n                {\n                    { \"foo[0]\", \"42\" },\n                }\n            };\n\n            DictionaryModelBinderProvider binderProvider = new DictionaryModelBinderProvider();\n\n            // Act\n            IModelBinder binder = binderProvider.GetBinder(null, bindingContext.ModelType);\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        [Fact]\n        public void GetBinder_ModelTypeIsNullable_ReturnsNull()\n        {\n            // Arrange\n            DictionaryModelBinderProvider binderProvider = new DictionaryModelBinderProvider();\n\n            // Act\n            IModelBinder binder = binderProvider.GetBinder(null, typeof(int?));\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        [Fact]\n        public void GetBinder_ModelTypeIsGeneric_ReturnsNull()\n        {\n            // Arrange\n            DictionaryModelBinderProvider binderProvider = new DictionaryModelBinderProvider();\n\n            // Act\n            IModelBinder binder = binderProvider.GetBinder(null, typeof(Tuple<int>));\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        [Fact]\n        public void GetBinder_ValueProviderDoesNotContainPrefix_ReturnsNull()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(IDictionary<int, string>)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleHttpValueProvider()\n            };\n\n            DictionaryModelBinderProvider binderProvider = new DictionaryModelBinderProvider();\n\n            // Act\n            IModelBinder binder = binderProvider.GetBinder(null, bindingContext.ModelType);\n            bool bound = binder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.False(bound);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/Binders/DictionaryModelBinderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata.Providers;\nusing System.Web.Http.Util;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public class DictionaryModelBinderTest\n    {\n        [Fact]\n        public void BindModel()\n        {\n            // Arrange\n            Mock<IModelBinder> mockKvpBinder = new Mock<IModelBinder>();\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(IDictionary<int, string>)),\n                ModelName = \"someName\",\n                ValueProvider = new SimpleHttpValueProvider\n                {\n                    { \"someName[0]\", new KeyValuePair<int, string>(42, \"forty-two\") },\n                    { \"someName[1]\", new KeyValuePair<int, string>(84, \"eighty-four\") }\n                }\n            };\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            context.ControllerContext.Configuration.Services.Replace(typeof(ModelBinderProvider), (new SimpleModelBinderProvider(typeof(KeyValuePair<int, string>), mockKvpBinder.Object)));\n\n            mockKvpBinder\n                .Setup(o => o.BindModel(context, It.IsAny<ModelBindingContext>()))\n                .Returns((HttpActionContext cc, ModelBindingContext mbc) =>\n                {\n                    mbc.Model = mbc.ValueProvider.GetValue(mbc.ModelName).ConvertTo(mbc.ModelType);\n                    return true;\n                });\n\n            // Act\n            bool retVal = new DictionaryModelBinder<int, string>().BindModel(context, bindingContext);\n\n            // Assert\n            Assert.True(retVal);\n\n            var dictionary = Assert.IsAssignableFrom<IDictionary<int, string>>(bindingContext.Model);\n            Assert.NotNull(dictionary);\n            Assert.Equal(2, dictionary.Count);\n            Assert.Equal(\"forty-two\", dictionary[42]);\n            Assert.Equal(\"eighty-four\", dictionary[84]);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/Binders/KeyValuePairModelBinderProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http.Metadata.Providers;\nusing System.Web.Http.Util;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public class KeyValuePairModelBinderProviderTest\n    {\n        [Fact]\n        public void GetBinder_CorrectModelTypeAndValueProviderEntries_ReturnsBinder()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(KeyValuePair<int, string>)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleHttpValueProvider\n                {\n                    { \"foo.key\", 42 },\n                    { \"foo.value\", \"someValue\" }\n                }\n            };\n\n            KeyValuePairModelBinderProvider binderProvider = new KeyValuePairModelBinderProvider();\n\n            // Act\n            IModelBinder binder = binderProvider.GetBinder(null, bindingContext.ModelType);\n\n            // Assert\n            Assert.IsType<KeyValuePairModelBinder<int, string>>(binder);\n        }\n\n        [Fact]\n        public void GetBinder_ModelTypeIsIncorrect_ReturnsNull()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(List<int>)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleHttpValueProvider\n                {\n                    { \"foo.key\", 42 },\n                    { \"foo.value\", \"someValue\" }\n                }\n            };\n\n            KeyValuePairModelBinderProvider binderProvider = new KeyValuePairModelBinderProvider();\n\n            // Act\n            IModelBinder binder = binderProvider.GetBinder(null, bindingContext.ModelType);\n\n            // Assert\n            Assert.Null(binder);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/Binders/KeyValuePairModelBinderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata.Providers;\nusing System.Web.Http.Util;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public class KeyValuePairModelBinderTest\n    {\n        [Fact]\n        public void BindModel_MissingKey_ReturnsFalse()\n        {\n            // Arrange\n            KeyValuePairModelBinder<int, string> binder = new KeyValuePairModelBinder<int, string>();\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(KeyValuePair<int, string>)),\n                ModelName = \"someName\",\n                ValueProvider = new SimpleHttpValueProvider()\n            };\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            context.ControllerContext.Configuration.Services.Replace(typeof(ModelBinderProvider), new SimpleModelBinderProvider(typeof(KeyValuePair<int, string>), binder));\n\n            // Act\n            bool retVal = binder.BindModel(context, bindingContext);\n\n            // Assert\n            Assert.False(retVal);\n            Assert.Null(bindingContext.Model);\n            Assert.Empty(bindingContext.ValidationNode.ChildNodes);\n        }\n\n        [Fact]\n        public void BindModel_MissingValue_ReturnsTrue()\n        {\n            // Arrange\n            Mock<IModelBinder> mockIntBinder = new Mock<IModelBinder>();\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(KeyValuePair<int, string>)),\n                ModelName = \"someName\",\n                ValueProvider = new SimpleHttpValueProvider()\n            };\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            context.ControllerContext.Configuration.Services.Replace(typeof(ModelBinderProvider), new SimpleModelBinderProvider(typeof(int), mockIntBinder.Object) { SuppressPrefixCheck = true });\n\n            mockIntBinder\n                .Setup(o => o.BindModel(context, It.IsAny<ModelBindingContext>()))\n                .Returns((HttpActionContext cc, ModelBindingContext mbc) =>\n                {\n                    mbc.Model = 42;\n                    return true;\n                });\n            KeyValuePairModelBinder<int, string> binder = new KeyValuePairModelBinder<int, string>();\n\n            // Act\n            bool retVal = binder.BindModel(context, bindingContext);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Null(bindingContext.Model);\n            Assert.Equal(new[] { \"someName.key\" }, bindingContext.ValidationNode.ChildNodes.Select(n => n.ModelStateKey).ToArray());\n        }\n\n        [Fact]\n        public void BindModel_SubBindingSucceeds()\n        {\n            // Arrange\n            Mock<IModelBinder> mockIntBinder = new Mock<IModelBinder>();\n            Mock<IModelBinder> mockStringBinder = new Mock<IModelBinder>();\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(KeyValuePair<int, string>)),\n                ModelName = \"someName\",\n                ValueProvider = new SimpleHttpValueProvider()\n            };\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            context.ControllerContext.Configuration.Services.ReplaceRange(typeof(ModelBinderProvider),\n                new ModelBinderProvider[] {\n                    new SimpleModelBinderProvider(typeof(int), mockIntBinder.Object) { SuppressPrefixCheck = true },\n                    new SimpleModelBinderProvider(typeof(string), mockStringBinder.Object) { SuppressPrefixCheck = true }\n                });\n\n            mockIntBinder\n                .Setup(o => o.BindModel(context, It.IsAny<ModelBindingContext>()))\n                .Returns((HttpActionContext cc, ModelBindingContext mbc) =>\n                {\n                    mbc.Model = 42;\n                    return true;\n                });\n            mockStringBinder\n                .Setup(o => o.BindModel(context, It.IsAny<ModelBindingContext>()))\n                .Returns((HttpActionContext cc, ModelBindingContext mbc) =>\n                {\n                    mbc.Model = \"forty-two\";\n                    return true;\n                });\n            KeyValuePairModelBinder<int, string> binder = new KeyValuePairModelBinder<int, string>();\n\n            // Act\n            bool retVal = binder.BindModel(context, bindingContext);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Equal(new KeyValuePair<int, string>(42, \"forty-two\"), bindingContext.Model);\n            Assert.Equal(new[] { \"someName.key\", \"someName.value\" }, bindingContext.ValidationNode.ChildNodes.Select(n => n.ModelStateKey).ToArray());\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/Binders/KeyValuePairModelBinderUtilTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata.Providers;\nusing System.Web.Http.Util;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public class KeyValuePairModelBinderUtilTest\n    {\n        [Fact]\n        public void TryBindStrongModel_BinderExists_BinderReturnsCorrectlyTypedObject_ReturnsTrue()\n        {\n            // Arrange\n            Mock<IModelBinder> mockIntBinder = new Mock<IModelBinder>();\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),\n                ModelName = \"someName\",\n                ModelState = new ModelStateDictionary(),\n                ValueProvider = new SimpleHttpValueProvider()\n            };\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            context.ControllerContext.Configuration.Services.Replace(typeof(ModelBinderProvider), new SimpleModelBinderProvider(typeof(int), mockIntBinder.Object) { SuppressPrefixCheck = true });\n\n            mockIntBinder\n                .Setup(o => o.BindModel(context, It.IsAny<ModelBindingContext>()))\n                .Returns((HttpActionContext cc, ModelBindingContext mbc) =>\n                {\n                    Assert.Equal(\"someName.key\", mbc.ModelName);\n                    mbc.Model = 42;\n                    return true;\n                });\n\n            // Act\n            int model;\n            bool retVal = context.TryBindStrongModel(bindingContext, \"key\", new EmptyModelMetadataProvider(), out model);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Equal(42, model);\n            Assert.Single(bindingContext.ValidationNode.ChildNodes);\n            Assert.Empty(bindingContext.ModelState);\n        }\n\n        [Fact]\n        public void TryBindStrongModel_BinderExists_BinderReturnsIncorrectlyTypedObject_ReturnsTrue()\n        {\n            // Arrange\n            Mock<IModelBinder> mockIntBinder = new Mock<IModelBinder>();\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),\n                ModelName = \"someName\",\n                ModelState = new ModelStateDictionary(),\n                ValueProvider = new SimpleHttpValueProvider()\n            };\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            context.ControllerContext.Configuration.Services.Replace(typeof(ModelBinderProvider), new SimpleModelBinderProvider(typeof(int), mockIntBinder.Object) { SuppressPrefixCheck = true });\n\n            mockIntBinder\n                .Setup(o => o.BindModel(context, It.IsAny<ModelBindingContext>()))\n                .Returns((HttpActionContext cc, ModelBindingContext mbc) =>\n                {\n                    Assert.Equal(\"someName.key\", mbc.ModelName);\n                    return true;\n                });\n\n            // Act\n            int model;\n            bool retVal = context.TryBindStrongModel(bindingContext, \"key\", new EmptyModelMetadataProvider(), out model);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Equal(default(int), model);\n            Assert.Single(bindingContext.ValidationNode.ChildNodes);\n            Assert.Empty(bindingContext.ModelState);\n        }\n\n        [Fact]\n        public void TryBindStrongModel_NoBinder_ReturnsFalse()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),\n                ModelName = \"someName\",\n                ModelState = new ModelStateDictionary(),\n                ValueProvider = new SimpleHttpValueProvider()\n            };\n\n            // Act\n            int model;\n            bool retVal = context.TryBindStrongModel(bindingContext, \"key\", new EmptyModelMetadataProvider(), out model);\n\n            // Assert\n            Assert.False(retVal);\n            Assert.Equal(default(int), model);\n            Assert.Empty(bindingContext.ValidationNode.ChildNodes);\n            Assert.Empty(bindingContext.ModelState);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/Binders/MutableObjectModelBinderProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Metadata.Providers;\nusing System.Web.Http.Util;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public class MutableObjectModelBinderProviderTest\n    {\n        [Fact]\n        public void GetBinder_NoPrefixInValueProvider_ReturnsNull()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => 42, typeof(int)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleHttpValueProvider()\n            };\n\n            MutableObjectModelBinderProvider binderProvider = new MutableObjectModelBinderProvider();\n\n            // Act\n            IModelBinder binder = binderProvider.GetBinder(null, bindingContext.ModelType);\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        [Fact]\n        public void GetBinder_PrefixInValueProvider_ComplexType_ReturnsBinder()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => new MutableTestType(), typeof(MutableTestType)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleHttpValueProvider\n                {\n                    { \"foo.bar\", \"someValue\" }\n                }\n            };\n\n            MutableObjectModelBinderProvider binderProvider = new MutableObjectModelBinderProvider();\n\n            // Act\n            IModelBinder binder = binderProvider.GetBinder(null, bindingContext.ModelType);\n\n            // Assert\n            Assert.NotNull(binder);\n            Assert.IsType<MutableObjectModelBinder>(binder);\n        }\n\n        [Fact]\n        public void GetBinder_PrefixInValueProvider_SimpleType_ReturnsNull()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => 42, typeof(int)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleHttpValueProvider\n                {\n                    { \"foo.bar\", \"someValue\" }\n                }\n            };\n\n            MutableObjectModelBinderProvider binderProvider = new MutableObjectModelBinderProvider();\n\n            // Act\n            IModelBinder binder = binderProvider.GetBinder(null, bindingContext.ModelType);\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        [Fact]\n        public void GetBinder_TypeIsComplexModelDto_ReturnsNull()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(ComplexModelDto)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleHttpValueProvider\n                {\n                    { \"foo.bar\", \"someValue\" }\n                }\n            };\n\n            MutableObjectModelBinderProvider binderProvider = new MutableObjectModelBinderProvider();\n\n            // Act\n            IModelBinder binder = binderProvider.GetBinder(null, bindingContext.ModelType);\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        class MutableTestType\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/Binders/MutableObjectModelBinderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Metadata.Providers;\nusing System.Web.Http.Validation;\nusing System.Web.Http.ValueProviders;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public class MutableObjectModelBinderTest\n    {\n        [Fact]\n        public void BindModel()\n        {\n            // Arrange\n            Mock<IValueProvider> mockValueProvider = new Mock<IValueProvider>();\n            mockValueProvider.Setup(o => o.ContainsPrefix(It.IsAny<string>())).Returns(true);\n\n            Mock<IModelBinder> mockDtoBinder = new Mock<IModelBinder>();\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = GetMetadataForObject(new Person()),\n                ModelName = \"someName\",\n                ValueProvider = mockValueProvider.Object\n            };\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            context.ControllerContext.Configuration.Services.Replace(typeof(ModelBinderProvider), new SimpleModelBinderProvider(typeof(ComplexModelDto), mockDtoBinder.Object) { SuppressPrefixCheck = true });\n\n            mockDtoBinder\n                .Setup(o => o.BindModel(context, It.IsAny<ModelBindingContext>()))\n                .Returns((HttpActionContext cc, ModelBindingContext mbc2) =>\n                {\n                    return true; // just return the DTO unchanged\n                });\n\n            Mock<TestableMutableObjectModelBinder> mockTestableBinder = new Mock<TestableMutableObjectModelBinder> { CallBase = true };\n            mockTestableBinder.Setup(o => o.EnsureModelPublic(context, bindingContext)).Verifiable();\n            mockTestableBinder.Setup(o => o.GetMetadataForPropertiesPublic(context, bindingContext)).Returns(new ModelMetadata[0]).Verifiable();\n            TestableMutableObjectModelBinder testableBinder = mockTestableBinder.Object;\n            testableBinder.MetadataProvider = new DataAnnotationsModelMetadataProvider();\n\n            // Act\n            bool retValue = testableBinder.BindModel(context, bindingContext);\n\n            // Assert\n            Assert.True(retValue);\n            Assert.IsType<Person>(bindingContext.Model);\n            Assert.True(bindingContext.ValidationNode.ValidateAllProperties);\n            mockTestableBinder.Verify();\n        }\n\n        [Fact]\n        public void CanUpdateProperty_HasPublicSetter_ReturnsTrue()\n        {\n            // Arrange\n            ModelMetadata propertyMetadata = GetMetadataForCanUpdateProperty(\"ReadWriteString\");\n\n            // Act\n            bool canUpdate = MutableObjectModelBinder.CanUpdatePropertyInternal(propertyMetadata);\n\n            // Assert\n            Assert.True(canUpdate);\n        }\n\n        [Fact]\n        public void CanUpdateProperty_ReadOnlyArray_ReturnsFalse()\n        {\n            // Arrange\n            ModelMetadata propertyMetadata = GetMetadataForCanUpdateProperty(\"ReadOnlyArray\");\n\n            // Act\n            bool canUpdate = MutableObjectModelBinder.CanUpdatePropertyInternal(propertyMetadata);\n\n            // Assert\n            Assert.False(canUpdate);\n        }\n\n        [Fact]\n        public void CanUpdateProperty_ReadOnlyReferenceTypeNotBlacklisted_ReturnsTrue()\n        {\n            // Arrange\n            ModelMetadata propertyMetadata = GetMetadataForCanUpdateProperty(\"ReadOnlyObject\");\n\n            // Act\n            bool canUpdate = MutableObjectModelBinder.CanUpdatePropertyInternal(propertyMetadata);\n\n            // Assert\n            Assert.True(canUpdate);\n        }\n\n        [Fact]\n        public void CanUpdateProperty_ReadOnlyString_ReturnsFalse()\n        {\n            // Arrange\n            ModelMetadata propertyMetadata = GetMetadataForCanUpdateProperty(\"ReadOnlyString\");\n\n            // Act\n            bool canUpdate = MutableObjectModelBinder.CanUpdatePropertyInternal(propertyMetadata);\n\n            // Assert\n            Assert.False(canUpdate);\n        }\n\n        [Fact]\n        public void CanUpdateProperty_ReadOnlyValueType_ReturnsFalse()\n        {\n            // Arrange\n            ModelMetadata propertyMetadata = GetMetadataForCanUpdateProperty(\"ReadOnlyInt\");\n\n            // Act\n            bool canUpdate = MutableObjectModelBinder.CanUpdatePropertyInternal(propertyMetadata);\n\n            // Assert\n            Assert.False(canUpdate);\n        }\n\n        [Fact]\n        public void CreateModel()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = GetMetadataForType(typeof(Person))\n            };\n\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Act\n            object retModel = testableBinder.CreateModelPublic(null, bindingContext);\n\n            // Assert\n            Assert.IsType<Person>(retModel);\n        }\n\n        [Fact]\n        public void EnsureModel_ModelIsNotNull_DoesNothing()\n        {\n            // Arrange\n            HttpActionContext actionContext = ContextUtil.CreateActionContext();\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = GetMetadataForObject(new Person())\n            };\n\n            Mock<TestableMutableObjectModelBinder> mockTestableBinder = new Mock<TestableMutableObjectModelBinder> { CallBase = true };\n            TestableMutableObjectModelBinder testableBinder = mockTestableBinder.Object;\n\n            // Act\n            object originalModel = bindingContext.Model;\n            testableBinder.EnsureModelPublic(null, bindingContext);\n            object newModel = bindingContext.Model;\n\n            // Assert\n            Assert.Same(originalModel, newModel);\n            mockTestableBinder.Verify(o => o.CreateModelPublic(actionContext, bindingContext), Times.Never());\n        }\n\n        [Fact]\n        public void EnsureModel_ModelIsNull_CallsCreateModel()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = GetMetadataForType(typeof(Person))\n            };\n\n            Mock<TestableMutableObjectModelBinder> mockTestableBinder = new Mock<TestableMutableObjectModelBinder> { CallBase = true };\n            mockTestableBinder.Setup(o => o.CreateModelPublic(null, bindingContext)).Returns(new Person()).Verifiable();\n            TestableMutableObjectModelBinder testableBinder = mockTestableBinder.Object;\n\n            // Act\n            object originalModel = bindingContext.Model;\n            testableBinder.EnsureModelPublic(null, bindingContext);\n            object newModel = bindingContext.Model;\n\n            // Assert\n            Assert.Null(originalModel);\n            Assert.IsType<Person>(newModel);\n            mockTestableBinder.Verify();\n        }\n\n        [Fact]\n        public void GetMetadataForProperties_WithBindAttribute()\n        {\n            // Arrange\n            string[] expectedPropertyNames = new[] { \"FirstName\", \"LastName\" };\n\n            HttpActionContext actionContext = ContextUtil.CreateActionContext();\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = GetMetadataForType(typeof(PersonWithBindExclusion))\n            };\n\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Act\n            IEnumerable<ModelMetadata> propertyMetadatas = testableBinder.GetMetadataForPropertiesPublic(actionContext, bindingContext);\n            string[] returnedPropertyNames = propertyMetadatas.Select(o => o.PropertyName).ToArray();\n\n            // Assert\n            Assert.Equal(expectedPropertyNames, returnedPropertyNames);\n        }\n\n        [Fact]\n        public void GetMetadataForProperties_WithoutBindAttribute()\n        {\n            // Arrange\n            string[] expectedPropertyNames = new[] { \"DateOfBirth\", \"DateOfDeath\", \"ValueTypeRequired\", \"FirstName\", \"LastName\", \"PropertyWithDefaultValue\" };\n\n            HttpActionContext actionContext = ContextUtil.CreateActionContext();\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = GetMetadataForType(typeof(Person))\n            };\n\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Act\n            IEnumerable<ModelMetadata> propertyMetadatas = testableBinder.GetMetadataForPropertiesPublic(actionContext, bindingContext);\n            string[] returnedPropertyNames = propertyMetadatas.Select(o => o.PropertyName).ToArray();\n\n            // Assert\n            Assert.Equal(expectedPropertyNames, returnedPropertyNames);\n        }\n\n        [Fact]\n        public void GetRequiredPropertiesCollection_MixedAttributes()\n        {\n            // Arrange\n            HttpActionContext actionContext = ContextUtil.CreateActionContext();\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = GetMetadataForObject(new ModelWithMixedBindingBehaviors())\n            };\n\n            // Act\n            HashSet<string> requiredProperties;\n            Dictionary<string, ModelValidator> requiredValidators;\n            HashSet<string> skipProperties;\n            MutableObjectModelBinder.GetRequiredPropertiesCollection(actionContext, bindingContext, out requiredProperties, out requiredValidators, out skipProperties);\n\n            // Assert\n            Assert.Equal(new[] { \"Required\" }, requiredProperties.ToArray());\n            Assert.Equal(new[] { \"Never\" }, skipProperties.ToArray());\n        }\n\n        [Fact]\n        public void NullCheckFailedHandler_ModelStateAlreadyInvalid_DoesNothing()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            context.ModelState.AddModelError(\"foo.bar\", \"Some existing error.\");\n\n            ModelMetadata modelMetadata = GetMetadataForType(typeof(Person));\n            ModelValidationNode validationNode = new ModelValidationNode(modelMetadata, \"foo\");\n            ModelValidatedEventArgs e = new ModelValidatedEventArgs(context, null /* parentNode */);\n\n            // Act\n            EventHandler<ModelValidatedEventArgs> handler = MutableObjectModelBinder.CreateNullCheckFailedHandler(modelMetadata, null /* incomingValue */);\n            handler(validationNode, e);\n\n            // Assert\n            Assert.False(context.ModelState.ContainsKey(\"foo\"));\n        }\n\n        [Fact]\n        public void NullCheckFailedHandler_ModelStateValid_AddsErrorString()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            ModelMetadata modelMetadata = GetMetadataForType(typeof(Person));\n            ModelValidationNode validationNode = new ModelValidationNode(modelMetadata, \"foo\");\n            ModelValidatedEventArgs e = new ModelValidatedEventArgs(context, null /* parentNode */);\n\n            // Act\n            EventHandler<ModelValidatedEventArgs> handler = MutableObjectModelBinder.CreateNullCheckFailedHandler(modelMetadata, null /* incomingValue */);\n            handler(validationNode, e);\n\n            // Assert\n            Assert.True(context.ModelState.ContainsKey(\"foo\"));\n            Assert.Equal(\"A value is required.\", context.ModelState[\"foo\"].Errors[0].ErrorMessage);\n        }\n\n        [Fact]\n        public void NullCheckFailedHandler_ModelStateValid_CallbackReturnsNull_DoesNothing()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            ModelMetadata modelMetadata = GetMetadataForType(typeof(Person));\n            ModelValidationNode validationNode = new ModelValidationNode(modelMetadata, \"foo\");\n            ModelValidatedEventArgs e = new ModelValidatedEventArgs(context, null /* parentNode */);\n\n            // Act\n            ModelBinderErrorMessageProvider originalProvider = ModelBinderConfig.ValueRequiredErrorMessageProvider;\n            try\n            {\n                ModelBinderConfig.ValueRequiredErrorMessageProvider = (ec, mm, value) => null;\n                EventHandler<ModelValidatedEventArgs> handler = MutableObjectModelBinder.CreateNullCheckFailedHandler(modelMetadata, null /* incomingValue */);\n                handler(validationNode, e);\n            }\n            finally\n            {\n                ModelBinderConfig.ValueRequiredErrorMessageProvider = originalProvider;\n            }\n\n            // Assert\n            Assert.True(context.ModelState.IsValid);\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void ProcessDto_BindRequiredFieldMissing_RaisesModelError()\n        {\n            // Arrange\n            ModelWithBindRequired model = new ModelWithBindRequired\n            {\n                Name = \"original value\",\n                Age = -20\n            };\n\n            ModelMetadata containerMetadata = GetMetadataForObject(model);\n\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = containerMetadata,\n                ModelName = \"theModel\"\n            };\n            ComplexModelDto dto = new ComplexModelDto(containerMetadata, containerMetadata.Properties);\n\n            ModelMetadata nameProperty = dto.PropertyMetadata.Single(o => o.PropertyName == \"Name\");\n            dto.Results[nameProperty] = new ComplexModelDtoResult(\"John Doe\", new ModelValidationNode(nameProperty, \"\"));\n\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Act\n            testableBinder.ProcessDto(context, bindingContext, dto);\n\n            // Assert\n            ModelStateDictionary modelStateDictionary = bindingContext.ModelState;\n            Assert.False(modelStateDictionary.IsValid);\n            Assert.Single(modelStateDictionary);\n\n            // Check Age error.\n            ModelState modelState;\n            Assert.True(modelStateDictionary.TryGetValue(\"theModel.Age\", out modelState));\n\n            ModelError modelError = Assert.Single(modelState.Errors);\n            Assert.Null(modelError.Exception);\n            Assert.NotNull(modelError.ErrorMessage);\n            Assert.Equal(\"The Age property is required.\", modelError.ErrorMessage);\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void ProcessDto_BindRequiredFieldNull_RaisesModelError()\n        {\n            // Arrange\n            ModelWithBindRequired model = new ModelWithBindRequired\n            {\n                Name = \"original value\",\n                Age = -20\n            };\n\n            ModelMetadata containerMetadata = GetMetadataForObject(model);\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = containerMetadata,\n                ModelName = \"theModel\",\n                ModelState = context.ModelState,\n            };\n\n            ComplexModelDto dto = new ComplexModelDto(containerMetadata, containerMetadata.Properties);\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            ModelMetadata propertyMetadata = dto.PropertyMetadata.Single(o => o.PropertyName == \"Name\");\n            dto.Results[propertyMetadata] =\n                new ComplexModelDtoResult(\"John Doe\", new ModelValidationNode(propertyMetadata, \"theModel.Name\"));\n\n            // Attempt to set non-Nullable property to null.  HttpBindRequiredAttribute should not be relevant in this\n            // case because the binding exists.\n            propertyMetadata = dto.PropertyMetadata.Single(o => o.PropertyName == \"Age\");\n            dto.Results[propertyMetadata] =\n                new ComplexModelDtoResult(null, new ModelValidationNode(propertyMetadata, \"theModel.Age\"));\n\n            // Act; must also Validate because null-check error handler is late-bound\n            testableBinder.ProcessDto(context, bindingContext, dto);\n            bindingContext.ValidationNode.Validate(context);\n\n            // Assert\n            ModelStateDictionary modelStateDictionary = bindingContext.ModelState;\n            Assert.False(modelStateDictionary.IsValid);\n            Assert.Single(modelStateDictionary);\n\n            // Check Age error.\n            ModelState modelState;\n            Assert.True(modelStateDictionary.TryGetValue(\"theModel.Age\", out modelState));\n\n            ModelError modelError = Assert.Single(modelState.Errors);\n            Assert.Null(modelError.Exception);\n            Assert.NotNull(modelError.ErrorMessage);\n            Assert.Equal(\"A value is required.\", modelError.ErrorMessage);\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void ProcessDto_RequiredFieldMissing_RaisesModelError()\n        {\n            // Arrange\n            ModelWithRequired model = new ModelWithRequired();\n            ModelMetadata containerMetadata = GetMetadataForObject(model);\n            HttpActionContext context = ContextUtil.CreateActionContext();\n\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = containerMetadata,\n                ModelName = \"theModel\"\n            };\n\n            // Set no properties though Age (a non-Nullable struct) and City (a class) properties are required.\n            ComplexModelDto dto = new ComplexModelDto(containerMetadata, containerMetadata.Properties);\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Act\n            testableBinder.ProcessDto(context, bindingContext, dto);\n\n            // Assert\n            ModelStateDictionary modelStateDictionary = bindingContext.ModelState;\n            Assert.False(modelStateDictionary.IsValid);\n            Assert.Equal(2, modelStateDictionary.Count);\n\n            // Check Age error.\n            ModelState modelState;\n            Assert.True(modelStateDictionary.TryGetValue(\"theModel.Age\", out modelState));\n\n            ModelError modelError = Assert.Single(modelState.Errors);\n            Assert.Null(modelError.Exception);\n            Assert.NotNull(modelError.ErrorMessage);\n            Assert.Equal(\"The Age field is required.\", modelError.ErrorMessage);\n\n            // Check City error.\n            Assert.True(modelStateDictionary.TryGetValue(\"theModel.City\", out modelState));\n\n            modelError = Assert.Single(modelState.Errors);\n            Assert.Null(modelError.Exception);\n            Assert.NotNull(modelError.ErrorMessage);\n            Assert.Equal(\"The City field is required.\", modelError.ErrorMessage);\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void ProcessDto_RequiredFieldNull_RaisesModelError()\n        {\n            // Arrange\n            ModelWithRequired model = new ModelWithRequired();\n            ModelMetadata containerMetadata = GetMetadataForObject(model);\n            HttpActionContext context = ContextUtil.CreateActionContext();\n\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = containerMetadata,\n                ModelName = \"theModel\"\n            };\n\n            ComplexModelDto dto = new ComplexModelDto(containerMetadata, containerMetadata.Properties);\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Make Age valid and City invalid.\n            ModelMetadata propertyMetadata = dto.PropertyMetadata.Single(p => p.PropertyName == \"Age\");\n            dto.Results[propertyMetadata] =\n                new ComplexModelDtoResult(23, new ModelValidationNode(propertyMetadata, \"theModel.Age\"));\n            propertyMetadata = dto.PropertyMetadata.Single(p => p.PropertyName == \"City\");\n            dto.Results[propertyMetadata] =\n                new ComplexModelDtoResult(null, new ModelValidationNode(propertyMetadata, \"theModel.City\"));\n\n            // Act\n            testableBinder.ProcessDto(context, bindingContext, dto);\n\n            // Assert\n            ModelStateDictionary modelStateDictionary = bindingContext.ModelState;\n            Assert.False(modelStateDictionary.IsValid);\n            Assert.Single(modelStateDictionary);\n\n            // Check City error.\n            ModelState modelState;\n            Assert.True(modelStateDictionary.TryGetValue(\"theModel.City\", out modelState));\n\n            ModelError modelError = Assert.Single(modelState.Errors);\n            Assert.Null(modelError.Exception);\n            Assert.NotNull(modelError.ErrorMessage);\n            Assert.Equal(\"The City field is required.\", modelError.ErrorMessage);\n        }\n\n        [Fact]\n        public void ProcessDto_RequiredFieldMissing_RaisesModelErrorWithMessage()\n        {\n            // Arrange\n            Person model = new Person();\n            ModelMetadata containerMetadata = GetMetadataForObject(model);\n            HttpActionContext context = ContextUtil.CreateActionContext();\n\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = containerMetadata,\n                ModelName = \"theModel\"\n            };\n\n            // Set no properties though ValueTypeRequired (a non-Nullable struct) property is required.\n            ComplexModelDto dto = new ComplexModelDto(containerMetadata, containerMetadata.Properties);\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Act\n            testableBinder.ProcessDto(context, bindingContext, dto);\n\n            // Assert\n            ModelStateDictionary modelStateDictionary = bindingContext.ModelState;\n            Assert.False(modelStateDictionary.IsValid);\n            Assert.Single(modelStateDictionary);\n\n            // Check ValueTypeRequired error.\n            ModelState modelState;\n            Assert.True(modelStateDictionary.TryGetValue(\"theModel.ValueTypeRequired\", out modelState));\n\n            ModelError modelError = Assert.Single(modelState.Errors);\n            Assert.Null(modelError.Exception);\n            Assert.NotNull(modelError.ErrorMessage);\n            Assert.Equal(\"Sample message\", modelError.ErrorMessage);\n        }\n\n        [Fact]\n        public void ProcessDto_RequiredFieldNull_RaisesModelErrorWithMessage()\n        {\n            // Arrange\n            Person model = new Person();\n            ModelMetadata containerMetadata = GetMetadataForObject(model);\n            HttpActionContext context = ContextUtil.CreateActionContext();\n\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = containerMetadata,\n                ModelName = \"theModel\"\n            };\n\n            ComplexModelDto dto = new ComplexModelDto(containerMetadata, containerMetadata.Properties);\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Make ValueTypeRequired invalid.\n            ModelMetadata propertyMetadata = dto.PropertyMetadata.Single(p => p.PropertyName == \"ValueTypeRequired\");\n            dto.Results[propertyMetadata] =\n                new ComplexModelDtoResult(null, new ModelValidationNode(propertyMetadata, \"theModel.ValueTypeRequired\"));\n\n            // Act\n            testableBinder.ProcessDto(context, bindingContext, dto);\n\n            // Assert\n            ModelStateDictionary modelStateDictionary = bindingContext.ModelState;\n            Assert.False(modelStateDictionary.IsValid);\n            Assert.Single(modelStateDictionary);\n\n            // Check ValueTypeRequired error.\n            ModelState modelState;\n            Assert.True(modelStateDictionary.TryGetValue(\"theModel.ValueTypeRequired\", out modelState));\n\n            ModelError modelError = Assert.Single(modelState.Errors);\n            Assert.Null(modelError.Exception);\n            Assert.NotNull(modelError.ErrorMessage);\n            Assert.Equal(\"Sample message\", modelError.ErrorMessage);\n        }\n\n        [Fact]\n        public void ProcessDto_Success()\n        {\n            // Arrange\n            DateTime dob = new DateTime(2001, 1, 1);\n            PersonWithBindExclusion model = new PersonWithBindExclusion\n            {\n                DateOfBirth = dob\n            };\n            ModelMetadata containerMetadata = GetMetadataForObject(model);\n\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = containerMetadata\n            };\n            ComplexModelDto dto = new ComplexModelDto(containerMetadata, containerMetadata.Properties);\n\n            ModelMetadata firstNameProperty = dto.PropertyMetadata.Single(o => o.PropertyName == \"FirstName\");\n            dto.Results[firstNameProperty] = new ComplexModelDtoResult(\"John\", new ModelValidationNode(firstNameProperty, \"\"));\n            ModelMetadata lastNameProperty = dto.PropertyMetadata.Single(o => o.PropertyName == \"LastName\");\n            dto.Results[lastNameProperty] = new ComplexModelDtoResult(\"Doe\", new ModelValidationNode(lastNameProperty, \"\"));\n            ModelMetadata dobProperty = dto.PropertyMetadata.Single(o => o.PropertyName == \"DateOfBirth\");\n            dto.Results[dobProperty] = null;\n\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Act\n            testableBinder.ProcessDto(context, bindingContext, dto);\n\n            // Assert\n            Assert.Equal(\"John\", model.FirstName);\n            Assert.Equal(\"Doe\", model.LastName);\n            Assert.Equal(dob, model.DateOfBirth);\n            Assert.True(bindingContext.ModelState.IsValid);\n        }\n\n        [Fact]\n        public void SetProperty_PropertyHasDefaultValue_SetsDefaultValue()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = GetMetadataForObject(new Person())\n            };\n\n            ModelMetadata propertyMetadata = bindingContext.ModelMetadata.Properties.Single(o => o.PropertyName == \"PropertyWithDefaultValue\");\n            ModelValidationNode validationNode = new ModelValidationNode(propertyMetadata, \"foo\");\n            ComplexModelDtoResult dtoResult = new ComplexModelDtoResult(null /* model */, validationNode);\n            ModelValidator requiredValidator = context.GetValidators(propertyMetadata).Where(v => v.IsRequired).FirstOrDefault();\n\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Act\n            testableBinder.SetPropertyPublic(context, bindingContext, propertyMetadata, dtoResult, requiredValidator);\n\n            // Assert\n            var person = Assert.IsType<Person>(bindingContext.Model);\n            Assert.Equal(123.456m, person.PropertyWithDefaultValue);\n            Assert.True(context.ModelState.IsValid);\n        }\n\n        [Fact]\n        public void SetProperty_PropertyIsReadOnly_DoesNothing()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = GetMetadataForType(typeof(Person))\n            };\n\n            ModelMetadata propertyMetadata = bindingContext.ModelMetadata.Properties.Single(o => o.PropertyName == \"NonUpdateableProperty\");\n            ModelValidationNode validationNode = new ModelValidationNode(propertyMetadata, \"foo\");\n            ComplexModelDtoResult dtoResult = new ComplexModelDtoResult(null /* model */, validationNode);\n\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Act\n            testableBinder.SetPropertyPublic(null, bindingContext, propertyMetadata, dtoResult, requiredValidator: null);\n\n            // Assert\n            // If didn't throw, success!\n        }\n\n        [Fact]\n        public void SetProperty_PropertyIsSettable_CallsSetter()\n        {\n            // Arrange\n            Person model = new Person();\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = GetMetadataForObject(model)\n            };\n\n            ModelMetadata propertyMetadata = bindingContext.ModelMetadata.Properties.Single(o => o.PropertyName == \"DateOfBirth\");\n            ModelValidationNode validationNode = new ModelValidationNode(propertyMetadata, \"foo\");\n            ComplexModelDtoResult dtoResult = new ComplexModelDtoResult(new DateTime(2001, 1, 1), validationNode);\n            ModelValidator requiredValidator = context.GetValidators(propertyMetadata).Where(v => v.IsRequired).FirstOrDefault();\n\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Act\n            testableBinder.SetPropertyPublic(context, bindingContext, propertyMetadata, dtoResult, requiredValidator);\n\n            // Assert\n            validationNode.Validate(context);\n            Assert.True(context.ModelState.IsValid);\n            Assert.Equal(new DateTime(2001, 1, 1), model.DateOfBirth);\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void SetProperty_PropertyIsSettable_SetterThrows_RecordsError()\n        {\n            // Arrange\n            Person model = new Person\n            {\n                DateOfBirth = new DateTime(1900, 1, 1)\n            };\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = GetMetadataForObject(model)\n            };\n\n            ModelMetadata propertyMetadata = bindingContext.ModelMetadata.Properties.Single(o => o.PropertyName == \"DateOfDeath\");\n            ModelValidationNode validationNode = new ModelValidationNode(propertyMetadata, \"foo\");\n            ComplexModelDtoResult dtoResult = new ComplexModelDtoResult(new DateTime(1800, 1, 1), validationNode);\n\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Act\n            testableBinder.SetPropertyPublic(null, bindingContext, propertyMetadata, dtoResult, requiredValidator: null);\n\n            // Assert\n            Assert.Equal(\"Date of death can't be before date of birth.\" + Environment.NewLine\n                       + \"Parameter name: value\",\n                         bindingContext.ModelState[\"foo\"].Errors[0].Exception.Message);\n        }\n\n        [Fact]\n        public void SetProperty_SettingNonNullableValueTypeToNull_RequiredValidatorNotPresent_RegistersValidationCallback()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = GetMetadataForObject(new Person()),\n            };\n\n            ModelMetadata propertyMetadata = bindingContext.ModelMetadata.Properties.Single(o => o.PropertyName == \"DateOfBirth\");\n            ModelValidationNode validationNode = new ModelValidationNode(propertyMetadata, \"foo\");\n            ComplexModelDtoResult dtoResult = new ComplexModelDtoResult(null /* model */, validationNode);\n            ModelValidator requiredValidator = context.GetValidators(propertyMetadata).Where(v => v.IsRequired).FirstOrDefault();\n\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Act\n            testableBinder.SetPropertyPublic(context, bindingContext, propertyMetadata, dtoResult, requiredValidator);\n\n            // Assert\n            Assert.True(context.ModelState.IsValid);\n            validationNode.Validate(context, bindingContext.ValidationNode);\n            Assert.False(context.ModelState.IsValid);\n        }\n\n        [Fact]\n        public void SetProperty_SettingNonNullableValueTypeToNull_RequiredValidatorPresent_AddsModelError()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = GetMetadataForObject(new Person()),\n                ModelName = \"foo\"\n            };\n\n            ModelMetadata propertyMetadata = bindingContext.ModelMetadata.Properties.Single(o => o.PropertyName == \"ValueTypeRequired\");\n            ModelValidationNode validationNode = new ModelValidationNode(propertyMetadata, \"foo.ValueTypeRequired\");\n            ComplexModelDtoResult dtoResult = new ComplexModelDtoResult(null /* model */, validationNode);\n            ModelValidator requiredValidator = context.GetValidators(propertyMetadata).Where(v => v.IsRequired).FirstOrDefault();\n\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Act\n            testableBinder.SetPropertyPublic(context, bindingContext, propertyMetadata, dtoResult, requiredValidator);\n\n            // Assert\n            Assert.False(bindingContext.ModelState.IsValid);\n            Assert.Equal(\"Sample message\", bindingContext.ModelState[\"foo.ValueTypeRequired\"].Errors[0].ErrorMessage);\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void SetProperty_SettingNullableTypeToNull_RequiredValidatorNotPresent_PropertySetterThrows_AddsRequiredMessageString()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = GetMetadataForObject(new ModelWhosePropertySetterThrows()),\n                ModelName = \"foo\"\n            };\n\n            ModelMetadata propertyMetadata = bindingContext.ModelMetadata.Properties.Single(o => o.PropertyName == \"NameNoAttribute\");\n            ModelValidationNode validationNode = new ModelValidationNode(propertyMetadata, \"foo.NameNoAttribute\");\n            ComplexModelDtoResult dtoResult = new ComplexModelDtoResult(null /* model */, validationNode);\n            ModelValidator requiredValidator = context.GetValidators(propertyMetadata).Where(v => v.IsRequired).FirstOrDefault();\n\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Act\n            testableBinder.SetPropertyPublic(context, bindingContext, propertyMetadata, dtoResult, requiredValidator);\n\n            // Assert\n            Assert.False(bindingContext.ModelState.IsValid);\n            ModelError modelError = Assert.Single(bindingContext.ModelState[\"foo.NameNoAttribute\"].Errors);\n            Assert.Equal(\n                \"This is a different exception.\" + Environment.NewLine + \"Parameter name: value\",\n                modelError.Exception.Message);\n        }\n\n        [Fact]\n        public void SetProperty_SettingNullableTypeToNull_RequiredValidatorPresent_PropertySetterThrows_AddsRequiredMessageString()\n        {\n            // Arrange\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = GetMetadataForObject(new ModelWhosePropertySetterThrows()),\n                ModelName = \"foo\"\n            };\n\n            ModelMetadata propertyMetadata = bindingContext.ModelMetadata.Properties.Single(o => o.PropertyName == \"Name\");\n            ModelValidationNode validationNode = new ModelValidationNode(propertyMetadata, \"foo.Name\");\n            ComplexModelDtoResult dtoResult = new ComplexModelDtoResult(null /* model */, validationNode);\n            ModelValidator requiredValidator = context.GetValidators(propertyMetadata).Where(v => v.IsRequired).FirstOrDefault();\n\n            TestableMutableObjectModelBinder testableBinder = new TestableMutableObjectModelBinder();\n\n            // Act\n            testableBinder.SetPropertyPublic(context, bindingContext, propertyMetadata, dtoResult, requiredValidator);\n\n            // Assert\n            Assert.False(bindingContext.ModelState.IsValid);\n            ModelError modelError = Assert.Single(bindingContext.ModelState[\"foo.Name\"].Errors);\n            Assert.Equal(\"This message comes from the [Required] attribute.\", modelError.ErrorMessage);\n        }\n\n        private static ModelMetadata GetMetadataForCanUpdateProperty(string propertyName)\n        {\n            DataAnnotationsModelMetadataProvider metadataProvider = new DataAnnotationsModelMetadataProvider();\n            return metadataProvider.GetMetadataForProperty(null, typeof(MyModelTestingCanUpdateProperty), propertyName);\n        }\n\n        private static ModelMetadata GetMetadataForObject(object o)\n        {\n            DataAnnotationsModelMetadataProvider metadataProvider = new DataAnnotationsModelMetadataProvider();\n            return metadataProvider.GetMetadataForType(() => o, o.GetType());\n        }\n\n        private static ModelMetadata GetMetadataForType(Type t)\n        {\n            DataAnnotationsModelMetadataProvider metadataProvider = new DataAnnotationsModelMetadataProvider();\n            return metadataProvider.GetMetadataForType(null, t);\n        }\n\n        private class Person\n        {\n            private DateTime? _dateOfDeath;\n\n            public DateTime DateOfBirth { get; set; }\n\n            public DateTime? DateOfDeath\n            {\n                get { return _dateOfDeath; }\n                set\n                {\n                    if (value < DateOfBirth)\n                    {\n                        throw new ArgumentOutOfRangeException(\"value\", \"Date of death can't be before date of birth.\");\n                    }\n                    _dateOfDeath = value;\n                }\n            }\n\n            [Required(ErrorMessage = \"Sample message\")]\n            public int ValueTypeRequired { get; set; }\n\n            public string FirstName { get; set; }\n            public string LastName { get; set; }\n            public string NonUpdateableProperty { get; private set; }\n\n            [DefaultValue(typeof(decimal), \"123.456\")]\n            public decimal PropertyWithDefaultValue { get; set; }\n        }\n\n        private class PersonWithBindExclusion\n        {\n            [HttpBindNever]\n            public DateTime DateOfBirth { get; set; }\n\n            [HttpBindNever]\n            public DateTime? DateOfDeath { get; set; }\n\n            public string FirstName { get; set; }\n            public string LastName { get; set; }\n            public string NonUpdateableProperty { get; private set; }\n        }\n\n        private class ModelWithRequired\n        {\n            public string Name { get; set; }\n\n            [Required]\n            public int Age { get; set; }\n\n            [Required]\n            public string City { get; set; }\n        }\n\n        private class ModelWithBindRequired\n        {\n            public string Name { get; set; }\n\n            [HttpBindRequired]\n            public int Age { get; set; }\n        }\n\n        [HttpBindRequired]\n        private class ModelWithMixedBindingBehaviors\n        {\n            public string Required { get; set; }\n\n            [HttpBindNever]\n            public string Never { get; set; }\n\n            [HttpBindingBehavior(HttpBindingBehavior.Optional)]\n            public string Optional { get; set; }\n        }\n\n        private sealed class MyModelTestingCanUpdateProperty\n        {\n            public int ReadOnlyInt { get; private set; }\n            public string ReadOnlyString { get; private set; }\n            public string[] ReadOnlyArray { get; private set; }\n            public object ReadOnlyObject { get; private set; }\n            public string ReadWriteString { get; set; }\n        }\n\n        private sealed class ModelWhosePropertySetterThrows\n        {\n            [Required(ErrorMessage = \"This message comes from the [Required] attribute.\")]\n            public string Name\n            {\n                get { return null; }\n                set { throw new ArgumentException(\"This is an exception.\", \"value\"); }\n            }\n\n            public string NameNoAttribute\n            {\n                get { return null; }\n                set { throw new ArgumentException(\"This is a different exception.\", \"value\"); }\n            }\n        }\n\n        public class TestableMutableObjectModelBinder : MutableObjectModelBinder\n        {\n            public virtual bool CanUpdatePropertyPublic(ModelMetadata propertyMetadata)\n            {\n                return base.CanUpdateProperty(propertyMetadata);\n            }\n\n            protected override bool CanUpdateProperty(ModelMetadata propertyMetadata)\n            {\n                return CanUpdatePropertyPublic(propertyMetadata);\n            }\n\n            public virtual object CreateModelPublic(HttpActionContext context, ModelBindingContext bindingContext)\n            {\n                return base.CreateModel(context, bindingContext);\n            }\n\n            protected override object CreateModel(HttpActionContext context, ModelBindingContext bindingContext)\n            {\n                return CreateModelPublic(context, bindingContext);\n            }\n\n            public virtual void EnsureModelPublic(HttpActionContext context, ModelBindingContext bindingContext)\n            {\n                base.EnsureModel(context, bindingContext);\n            }\n\n            protected override void EnsureModel(HttpActionContext context, ModelBindingContext bindingContext)\n            {\n                EnsureModelPublic(context, bindingContext);\n            }\n\n            public virtual IEnumerable<ModelMetadata> GetMetadataForPropertiesPublic(HttpActionContext context, ModelBindingContext bindingContext)\n            {\n                return base.GetMetadataForProperties(context, bindingContext);\n            }\n\n            protected override IEnumerable<ModelMetadata> GetMetadataForProperties(HttpActionContext context, ModelBindingContext bindingContext)\n            {\n                return GetMetadataForPropertiesPublic(context, bindingContext);\n            }\n\n            public virtual void SetPropertyPublic(HttpActionContext context, ModelBindingContext bindingContext, ModelMetadata propertyMetadata, ComplexModelDtoResult dtoResult, ModelValidator requiredValidator)\n            {\n                base.SetProperty(context, bindingContext, propertyMetadata, dtoResult, requiredValidator);\n            }\n\n            protected override void SetProperty(HttpActionContext actionContext, ModelBindingContext bindingContext, ModelMetadata propertyMetadata, ComplexModelDtoResult dtoResult, ModelValidator requiredValidator)\n            {\n                SetPropertyPublic(actionContext, bindingContext, propertyMetadata, dtoResult, requiredValidator);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/Binders/SimpleModelBinderProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Metadata.Providers;\nusing System.Web.Http.Util;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public class SimpleModelBinderProviderTest\n    {\n        [Fact]\n        public void ConstructorWithFactoryThrowsIfModelBinderFactoryIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                () => new SimpleModelBinderProvider(typeof(object), (Func<IModelBinder>)null),\n                \"modelBinderFactory\");\n        }\n\n        [Fact]\n        public void ConstructorWithFactoryThrowsIfModelTypeIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                () => new SimpleModelBinderProvider(null, () => null),\n                \"modelType\");\n        }\n\n        [Fact]\n        public void ConstructorWithInstanceThrowsIfModelBinderIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                () => new SimpleModelBinderProvider(typeof(object), (IModelBinder)null),\n                \"modelBinder\");\n        }\n\n        [Fact]\n        public void ConstructorWithInstanceThrowsIfModelTypeIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                () => new SimpleModelBinderProvider(null, new Mock<IModelBinder>().Object),\n                \"modelType\");\n        }\n\n        [Fact]\n        public void GetBinder_TypeDoesNotMatch_ReturnsNull()\n        {\n            // Arrange\n            SimpleModelBinderProvider provider = new SimpleModelBinderProvider(typeof(string), new Mock<IModelBinder>().Object)\n            {\n                SuppressPrefixCheck = true\n            };\n            ModelBindingContext bindingContext = GetBindingContext(typeof(object));\n\n            // Act\n            IModelBinder binder = provider.GetBinder(null, bindingContext.ModelType);\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        [Fact]\n        public void GetBinder_TypeMatches_PrefixNotFound_ReturnsNull()\n        {\n            // Arrange\n            IModelBinder binderInstance = new Mock<IModelBinder>().Object;\n            SimpleModelBinderProvider provider = new SimpleModelBinderProvider(typeof(string), binderInstance);\n\n            ModelBindingContext bindingContext = GetBindingContext(typeof(string));\n            bindingContext.ValueProvider = new SimpleHttpValueProvider();\n\n            // Act\n            IModelBinder returnedBinder = provider.GetBinder(null, bindingContext.ModelType);\n            bool bound = returnedBinder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.False(bound);\n        }\n\n        [Fact]\n        public void GetBinder_TypeMatches_PrefixSuppressed_ReturnsFactoryInstance()\n        {\n            // Arrange\n            int numExecutions = 0;\n            IModelBinder theBinderInstance = new Mock<IModelBinder>().Object;\n            Func<IModelBinder> factory = delegate\n            {\n                numExecutions++;\n                return theBinderInstance;\n            };\n\n            SimpleModelBinderProvider provider = new SimpleModelBinderProvider(typeof(string), factory)\n            {\n                SuppressPrefixCheck = true\n            };\n            ModelBindingContext bindingContext = GetBindingContext(typeof(string));\n\n            // Act\n            IModelBinder returnedBinder = provider.GetBinder(null, bindingContext.ModelType);\n            returnedBinder.BindModel(null, bindingContext);\n\n            returnedBinder = provider.GetBinder(null, bindingContext.ModelType);\n            returnedBinder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.Equal(2, numExecutions);\n        }\n\n        [Fact]\n        public void GetBinder_TypeMatches_PrefixSuppressed_ReturnsInstance()\n        {\n            // Arrange\n            IModelBinder theBinderInstance = new Mock<IModelBinder>().Object;\n            SimpleModelBinderProvider provider = new SimpleModelBinderProvider(typeof(string), theBinderInstance)\n            {\n                SuppressPrefixCheck = true\n            };\n            ModelBindingContext bindingContext = GetBindingContext(typeof(string));\n\n            // Act\n            IModelBinder returnedBinder = provider.GetBinder(null, bindingContext.ModelType);\n\n            // Assert\n            Assert.NotNull(returnedBinder);\n        }\n\n        [Fact]\n        public void GetBinderThrowsIfBindingContextIsNull()\n        {\n            // Arrange\n            SimpleModelBinderProvider provider = new SimpleModelBinderProvider(typeof(string), new Mock<IModelBinder>().Object);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { provider.GetBinder(null, null); }, \"modelType\");\n        }\n\n        [Fact]\n        public void ModelTypeProperty()\n        {\n            // Arrange\n            SimpleModelBinderProvider provider = new SimpleModelBinderProvider(typeof(string), new Mock<IModelBinder>().Object);\n\n            // Act & assert\n            Assert.Equal(typeof(string), provider.ModelType);\n        }\n\n        private static ModelBindingContext GetBindingContext(Type modelType)\n        {\n            return new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => null, modelType)\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/Binders/TypeConverterModelBinderProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Metadata.Providers;\nusing System.Web.Http.Util;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public class TypeConverterModelBinderProviderTest\n    {\n        [Fact]\n        public void GetBinder_NoTypeConverterExistsFromString_ReturnsNull()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = GetBindingContext(typeof(void)); // no TypeConverter exists Void -> String\n\n            TypeConverterModelBinderProvider provider = new TypeConverterModelBinderProvider();\n\n            // Act\n            IModelBinder binder = provider.GetBinder(null, bindingContext.ModelType);\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        [Fact]\n        public void GetBinder_NullValueProviderResult_ReturnsNull()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = GetBindingContext(typeof(int));\n            bindingContext.ValueProvider = new SimpleHttpValueProvider(); // clear the ValueProvider\n\n            TypeConverterModelBinderProvider provider = new TypeConverterModelBinderProvider();\n\n            // Act\n            IModelBinder binder = provider.GetBinder(null, bindingContext.ModelType);\n            bool bound = binder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.False(bound);\n        }\n\n        [Fact]\n        public void GetBinder_TypeConverterExistsFromString_ReturnsNull()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = GetBindingContext(typeof(int)); // TypeConverter exists Int32 -> String\n\n            TypeConverterModelBinderProvider provider = new TypeConverterModelBinderProvider();\n\n            // Act\n            IModelBinder binder = provider.GetBinder(null, bindingContext.ModelType);\n\n            // Assert\n            Assert.IsType<TypeConverterModelBinder>(binder);\n        }\n\n        private static ModelBindingContext GetBindingContext(Type modelType)\n        {\n            return new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, modelType),\n                ModelName = \"theModelName\",\n                ValueProvider = new SimpleHttpValueProvider\n                {\n                    { \"theModelName\", \"someValue\" }\n                }\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/Binders/TypeConverterModelBinderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Web.Http.Metadata.Providers;\nusing System.Web.Http.Util;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public class TypeConverterModelBinderTest\n    {\n        [Fact]\n        public void BindModel_Error_FormatExceptionsTurnedIntoStringsInModelState()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = GetBindingContext(typeof(int));\n            bindingContext.ValueProvider = new SimpleHttpValueProvider\n            {\n                { \"theModelName\", \"not an integer\" }\n            };\n\n            TypeConverterModelBinder binder = new TypeConverterModelBinder();\n\n            // Act\n            bool retVal = binder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.False(retVal);\n            Assert.Equal(\"The value 'not an integer' is not valid for Int32.\", bindingContext.ModelState[\"theModelName\"].Errors[0].ErrorMessage);\n        }\n\n        [Fact]\n        public void BindModel_Error_FormatExceptionsTurnedIntoStringsInModelState_ErrorNotAddedIfCallbackReturnsNull()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = GetBindingContext(typeof(int));\n            bindingContext.ValueProvider = new SimpleHttpValueProvider\n            {\n                { \"theModelName\", \"not an integer\" }\n            };\n\n            TypeConverterModelBinder binder = new TypeConverterModelBinder();\n\n            // Act\n            ModelBinderErrorMessageProvider originalProvider = ModelBinderConfig.TypeConversionErrorMessageProvider;\n            bool retVal;\n            try\n            {\n                ModelBinderConfig.TypeConversionErrorMessageProvider = delegate { return null; };\n                retVal = binder.BindModel(null, bindingContext);\n            }\n            finally\n            {\n                ModelBinderConfig.TypeConversionErrorMessageProvider = originalProvider;\n            }\n\n            // Assert\n            Assert.False(retVal);\n            Assert.Null(bindingContext.Model);\n            Assert.True(bindingContext.ModelState.IsValid);\n        }\n\n        [Fact]\n        public void BindModel_Error_GeneralExceptionsSavedInModelState()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = GetBindingContext(typeof(Dummy));\n            bindingContext.ValueProvider = new SimpleHttpValueProvider\n            {\n                { \"theModelName\", \"foo\" }\n            };\n\n            TypeConverterModelBinder binder = new TypeConverterModelBinder();\n\n            // Act\n            bool retVal = binder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.False(retVal);\n            Assert.Null(bindingContext.Model);\n            Assert.Equal(\"The parameter conversion from type 'System.String' to type 'System.Web.Http.ModelBinding.Binders.TypeConverterModelBinderTest+Dummy' failed. See the inner exception for more information.\", bindingContext.ModelState[\"theModelName\"].Errors[0].Exception.Message);\n            Assert.Equal(\"From DummyTypeConverter: foo\", bindingContext.ModelState[\"theModelName\"].Errors[0].Exception.InnerException.Message);\n        }\n\n        [Fact]\n        public void BindModel_NullValueProviderResult_ReturnsFalse()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = GetBindingContext(typeof(int));\n\n            TypeConverterModelBinder binder = new TypeConverterModelBinder();\n\n            // Act\n            bool retVal = binder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.False(retVal, \"BindModel should have returned null.\");\n            Assert.Empty(bindingContext.ModelState);\n        }\n\n        [Fact]\n        public void BindModel_ValidValueProviderResult_ConvertEmptyStringsToNull()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = GetBindingContext(typeof(string));\n            bindingContext.ValueProvider = new SimpleHttpValueProvider\n            {\n                { \"theModelName\", \"\" }\n            };\n\n            TypeConverterModelBinder binder = new TypeConverterModelBinder();\n\n            // Act\n            bool retVal = binder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Null(bindingContext.Model);\n            Assert.True(bindingContext.ModelState.ContainsKey(\"theModelName\"));\n        }\n\n        [Fact]\n        public void BindModel_ValidValueProviderResult_ReturnsModel()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = GetBindingContext(typeof(int));\n            bindingContext.ValueProvider = new SimpleHttpValueProvider\n            {\n                { \"theModelName\", \"42\" }\n            };\n\n            TypeConverterModelBinder binder = new TypeConverterModelBinder();\n\n            // Act\n            bool retVal = binder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Equal(42, bindingContext.Model);\n            Assert.True(bindingContext.ModelState.ContainsKey(\"theModelName\"));\n        }\n\n        private static ModelBindingContext GetBindingContext(Type modelType)\n        {\n            return new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, modelType),\n                ModelName = \"theModelName\",\n                ValueProvider = new SimpleHttpValueProvider() // empty\n            };\n        }\n\n        [TypeConverter(typeof(DummyTypeConverter))]\n        private struct Dummy\n        {\n        }\n\n        private sealed class DummyTypeConverter : TypeConverter\n        {\n            public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)\n            {\n                return (sourceType == typeof(string)) || base.CanConvertFrom(context, sourceType);\n            }\n\n            public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)\n            {\n                throw new InvalidOperationException(String.Format(\"From DummyTypeConverter: {0}\", value));\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/Binders/TypeMatchModelBinderProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Metadata.Providers;\nusing System.Web.Http.Util;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public class TypeMatchModelBinderProviderTest\n    {\n        [Fact]\n        public void GetBinder_InvalidValueProviderResult_ReturnsNull()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = GetBindingContext();\n            bindingContext.ValueProvider = new SimpleHttpValueProvider\n            {\n                { \"theModelName\", \"not an integer\" }\n            };\n\n            TypeMatchModelBinderProvider provider = new TypeMatchModelBinderProvider();\n\n            // Act\n            IModelBinder binder = provider.GetBinder(null, bindingContext.ModelType);\n            bool bound = binder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.False(bound);\n        }\n\n        [Fact]\n        public void BindModel_ValidValueProviderResult_ReturnsBinder()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = GetBindingContext();\n            bindingContext.ValueProvider = new SimpleHttpValueProvider\n            {\n                { \"theModelName\", 42 }\n            };\n\n            TypeMatchModelBinderProvider provider = new TypeMatchModelBinderProvider();\n\n            // Act\n            IModelBinder binder = provider.GetBinder(null, bindingContext.ModelType);\n\n            // Assert\n            Assert.IsType<TypeMatchModelBinder>(binder);\n        }\n\n        private static ModelBindingContext GetBindingContext()\n        {\n            return GetBindingContext(typeof(int));\n        }\n\n        private static ModelBindingContext GetBindingContext(Type modelType)\n        {\n            return new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, modelType),\n                ModelName = \"theModelName\"\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/Binders/TypeMatchModelBinderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel.DataAnnotations;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata.Providers;\nusing System.Web.Http.Util;\nusing System.Web.Http.ValueProviders;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ModelBinding.Binders\n{\n    public class TypeMatchModelBinderTest\n    {\n        [Fact]\n        public void BindModel_InvalidValueProviderResult_ReturnsFalse()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = GetBindingContext();\n            bindingContext.ValueProvider = new SimpleHttpValueProvider\n            {\n                { \"theModelName\", \"not an integer\" }\n            };\n\n            TypeMatchModelBinder binder = new TypeMatchModelBinder();\n\n            // Act\n            bool retVal = binder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.False(retVal);\n            Assert.Empty(bindingContext.ModelState);\n        }\n\n        [Fact]\n        public void BindModel_ValidValueProviderResult_ReturnsTrue()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = GetBindingContext();\n            bindingContext.ValueProvider = new SimpleHttpValueProvider\n            {\n                { \"theModelName\", 42 }\n            };\n\n            TypeMatchModelBinder binder = new TypeMatchModelBinder();\n            HttpActionContext actionContext = new HttpActionContext\n            {\n                ControllerContext = new HttpControllerContext { Configuration = new HttpConfiguration() }\n            };\n\n            // Act\n            bool retVal = binder.BindModel(actionContext, bindingContext);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Equal(42, bindingContext.Model);\n            Assert.True(bindingContext.ModelState.ContainsKey(\"theModelName\"));\n        }\n\n        [Fact]\n        public void GetCompatibleValueProviderResult_ValueProviderResultRawValueIncorrect_ReturnsNull()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = GetBindingContext();\n            bindingContext.ValueProvider = new SimpleHttpValueProvider\n            {\n                { \"theModelName\", \"not an integer\" }\n            };\n\n            // Act\n            ValueProviderResult vpResult = TypeMatchModelBinder.GetCompatibleValueProviderResult(bindingContext);\n\n            // Assert\n            Assert.Null(vpResult); // Raw value is the wrong type\n        }\n\n        [Fact]\n        public void GetCompatibleValueProviderResult_ValueProviderResultValid_ReturnsValueProviderResult()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = GetBindingContext();\n            bindingContext.ValueProvider = new SimpleHttpValueProvider\n            {\n                { \"theModelName\", 42 }\n            };\n\n            // Act\n            ValueProviderResult vpResult = TypeMatchModelBinder.GetCompatibleValueProviderResult(bindingContext);\n\n            // Assert\n            Assert.NotNull(vpResult);\n        }\n\n        [Fact]\n        public void GetCompatibleValueProviderResult_ValueProviderReturnsNull_ReturnsNull()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = GetBindingContext();\n            bindingContext.ValueProvider = new SimpleHttpValueProvider();\n\n            // Act\n            ValueProviderResult vpResult = TypeMatchModelBinder.GetCompatibleValueProviderResult(bindingContext);\n\n            // Assert\n            Assert.Null(vpResult); // No key matched\n        }\n\n        [Fact]\n        public void BindModel_ThrowsArgument_IfControllerContextIsNullOnActionContext()\n        {\n            // Arrange\n            TypeMatchModelBinder binder = new TypeMatchModelBinder();\n            HttpActionContext actionContext = new HttpActionContext();\n            Customer model = new Customer { Age = 99999 };\n            ModelBindingContext bindingContext = GetBindingContext(typeof(Customer));\n            bindingContext.ValueProvider = new SimpleHttpValueProvider\n            {\n                { \"theModelName\", model }\n            };\n\n            // Act\n            Assert.ThrowsArgument(() => binder.BindModel(actionContext, bindingContext),\n                \"actionContext\", \"HttpActionContext.ControllerContext must not be null.\");\n        }\n\n        [Fact]\n        public void BindModel_ThrowsArgument_IfConfigurationIsNullOnControllerContext()\n        {\n            // Arrange\n            TypeMatchModelBinder binder = new TypeMatchModelBinder();\n            HttpActionContext actionContext = new HttpActionContext { ControllerContext = new HttpControllerContext() };\n            Customer model = new Customer { Age = 99999 };\n            ModelBindingContext bindingContext = GetBindingContext(typeof(Customer));\n            bindingContext.ValueProvider = new SimpleHttpValueProvider\n            {\n                { \"theModelName\", model }\n            };\n\n            // Act\n            Assert.ThrowsArgument(() => binder.BindModel(actionContext, bindingContext),\n                \"actionContext\", \"HttpControllerContext.Configuration must not be null.\");\n        }\n\n        [Fact]\n        public void BindModel_Performs_Validation()\n        {\n            // Arrange\n            TypeMatchModelBinder binder = new TypeMatchModelBinder();\n            HttpActionContext actionContext = new HttpActionContext\n            {\n                ControllerContext = new HttpControllerContext { Configuration = new HttpConfiguration() }\n            };\n\n            Customer model = new Customer { Age = 99999 };\n            ModelBindingContext bindingContext = GetBindingContext(typeof(Customer));\n            bindingContext.ValueProvider = new SimpleHttpValueProvider\n            {\n                { \"theModelName\", model }\n            };\n            bindingContext.ModelState = actionContext.ModelState;\n\n            // Act\n            bool retVal = binder.BindModel(actionContext, bindingContext);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Same(model, bindingContext.Model);\n            Assert.True(actionContext.ModelState.ContainsKey(\"theModelName\"));\n            Assert.False(actionContext.ModelState.IsValid);\n            Assert.Equal(\"The field Age must be between 0 and 100.\", actionContext.ModelState[\"theModelName.Age\"].Errors[0].ErrorMessage);\n        }\n\n        [Fact]\n        public void BindModel_Performs_ValidationOnArrays()\n        {\n            // Arrange\n            TypeMatchModelBinder binder = new TypeMatchModelBinder();\n            HttpActionContext actionContext = new HttpActionContext\n            {\n                ControllerContext = new HttpControllerContext { Configuration = new HttpConfiguration() }\n            };\n\n            Customer[] model = new[] { new Customer { Age = 99999 } };\n            ModelBindingContext bindingContext = GetBindingContext(typeof(Customer[]));\n            bindingContext.ValueProvider = new SimpleHttpValueProvider\n            {\n                { \"theModelName\", model }\n            };\n            bindingContext.ModelState = actionContext.ModelState;\n\n            // Act\n            bool retVal = binder.BindModel(actionContext, bindingContext);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Same(model, bindingContext.Model);\n            Assert.True(actionContext.ModelState.ContainsKey(\"theModelName\"));\n            Assert.False(actionContext.ModelState.IsValid);\n            Assert.Equal(\"The field Age must be between 0 and 100.\", actionContext.ModelState[\"theModelName[0].Age\"].Errors[0].ErrorMessage);\n        }\n\n        private static ModelBindingContext GetBindingContext()\n        {\n            return GetBindingContext(typeof(int));\n        }\n\n        private static ModelBindingContext GetBindingContext(Type modelType)\n        {\n            return new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, modelType),\n                ModelName = \"theModelName\",\n            };\n        }\n\n        private class Customer\n        {\n            [Range(0, 100)]\n            public int Age { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/CompositeModelBinderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata.Providers;\nusing System.Web.Http.ModelBinding.Binders;\nusing System.Web.Http.ValueProviders;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.ModelBinding\n{\n    public class CompositeModelBinderTest\n    {\n        //// REVIEW: remove or activate when PropertyFilter is activated\n        ////[Fact]\n        ////public void BindModel_PropertyFilterIsSet_Throws()\n        ////{\n        ////    // Arrange\n        ////    HttpExecutionContext executionContext = GetHttpExecutionContext();\n\n        ////    ModelBindingContext bindingContext = new ModelBindingContext\n        ////    {\n        ////        FallbackToEmptyPrefix = true,\n        ////        ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(SimpleModel)),\n        ////        //PropertyFilter = (new BindAttribute { Include = \"FirstName \" }).IsPropertyAllowed\n        ////    };\n\n        ////    List<ModelBinderProvider> binderProviders = new List<ModelBinderProvider>();\n        ////    CompositeModelBinder shimBinder = new CompositeModelBinder(binderProviders);\n\n        ////    // Act & assert\n        ////    Assert.Throws<InvalidOperationException>(\n        ////        delegate { shimBinder.BindModel(executionContext, bindingContext); },\n        ////        @\"The new model binding system cannot be used when a property allow list or disallow list has been specified in [Bind] or via the call to UpdateModel() / TryUpdateModel(). Use the [BindRequired] and [BindNever] attributes on the model type or its properties instead.\");\n        ////}\n\n        [Fact]\n        public void BindModel_SuccessfulBind_RunsValidationAndReturnsModel()\n        {\n            // Arrange\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(GetHttpControllerContext());\n            bool validationCalled = false;\n\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                FallbackToEmptyPrefix = true,\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),\n                ModelName = \"someName\",\n                //ModelState = executionContext.Controller.ViewData.ModelState,\n                //PropertyFilter = _ => true,\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"someName\", \"dummyValue\" }\n                }\n            };\n\n            Mock<IModelBinder> mockIntBinder = new Mock<IModelBinder>();\n            mockIntBinder\n                .Setup(o => o.BindModel(actionContext, It.IsAny<ModelBindingContext>()))\n                .Returns(\n                    delegate(HttpActionContext cc, ModelBindingContext mbc)\n                    {\n                        Assert.Same(bindingContext.ModelMetadata, mbc.ModelMetadata);\n                        Assert.Equal(\"someName\", mbc.ModelName);\n                        Assert.Same(bindingContext.ValueProvider, mbc.ValueProvider);\n\n                        mbc.Model = 42;\n                        mbc.ValidationNode.Validating += delegate { validationCalled = true; };\n                        return true;\n                    });\n\n            //binderProviders.RegisterBinderForType(typeof(int), mockIntBinder.Object, false /* suppressPrefixCheck */);\n            IModelBinder shimBinder = new CompositeModelBinder(mockIntBinder.Object);\n\n            // Act\n            bool isBound = shimBinder.BindModel(actionContext, bindingContext);\n\n            // Assert\n            Assert.True(isBound);\n            Assert.Equal(42, bindingContext.Model);\n            Assert.True(validationCalled);\n            Assert.True(bindingContext.ModelState.IsValid);\n        }\n\n        [Fact]\n        public void BindModel_SuccessfulBind_ComplexTypeFallback_RunsValidationAndReturnsModel()\n        {\n            // Arrange\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(GetHttpControllerContext());\n\n            bool validationCalled = false;\n            List<int> expectedModel = new List<int> { 1, 2, 3, 4, 5 };\n\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                FallbackToEmptyPrefix = true,\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(List<int>)),\n                ModelName = \"someName\",\n                //ModelState = executionContext.Controller.ViewData.ModelState,\n                //PropertyFilter = _ => true,\n                ValueProvider = new SimpleValueProvider\n                {\n                    { \"someOtherName\", \"dummyValue\" }\n                }\n            };\n\n            Mock<IModelBinder> mockIntBinder = new Mock<IModelBinder>();\n            mockIntBinder\n                .Setup(o => o.BindModel(actionContext, It.IsAny<ModelBindingContext>()))\n                .Returns(\n                    delegate(HttpActionContext cc, ModelBindingContext mbc)\n                    {\n                        if (!String.IsNullOrEmpty(mbc.ModelName))\n                        {\n                            return false;\n                        }\n\n                        Assert.Same(bindingContext.ModelMetadata, mbc.ModelMetadata);\n                        Assert.Equal(\"\", mbc.ModelName);\n                        Assert.Same(bindingContext.ValueProvider, mbc.ValueProvider);\n\n                        mbc.Model = expectedModel;\n                        mbc.ValidationNode.Validating += delegate { validationCalled = true; };\n                        return true;\n                    });\n\n            //binderProviders.RegisterBinderForType(typeof(List<int>), mockIntBinder.Object, false /* suppressPrefixCheck */);\n            IModelBinder shimBinder = new CompositeModelBinder(mockIntBinder.Object);\n\n            // Act\n            bool isBound = shimBinder.BindModel(actionContext, bindingContext);\n\n            // Assert\n            Assert.True(isBound);\n            Assert.Equal(expectedModel, bindingContext.Model);\n            Assert.True(validationCalled);\n            Assert.True(bindingContext.ModelState.IsValid);\n        }\n\n        [Fact]\n        public void BindModel_UnsuccessfulBind_BinderFails_ReturnsNull()\n        {\n            // Arrange\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(GetHttpControllerContext());\n            Mock<IModelBinder> mockListBinder = new Mock<IModelBinder>();\n            mockListBinder.Setup(o => o.BindModel(actionContext, It.IsAny<ModelBindingContext>())).Returns(false).Verifiable();\n\n            IModelBinder shimBinder = (IModelBinder)mockListBinder.Object;\n\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                FallbackToEmptyPrefix = false,\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(List<int>)),\n                //ModelState = executionContext.Controller.ViewData.ModelState\n            };\n\n            // Act\n            bool isBound = shimBinder.BindModel(actionContext, bindingContext);\n\n            // Assert\n            Assert.False(isBound);\n            Assert.Null(bindingContext.Model);\n            Assert.True(bindingContext.ModelState.IsValid);\n            mockListBinder.Verify();\n        }\n\n        [Fact]\n        public void BindModel_UnsuccessfulBind_SimpleTypeNoFallback_ReturnsNull()\n        {\n            // Arrange\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(GetHttpControllerContext());\n            Mock<ModelBinderProvider> mockBinderProvider = new Mock<ModelBinderProvider>();\n            mockBinderProvider.Setup(o => o.GetBinder(It.IsAny<HttpConfiguration>(), It.IsAny<Type>())).Returns((IModelBinder)null).Verifiable();\n            List<ModelBinderProvider> binderProviders = new List<ModelBinderProvider>()\n            {\n                mockBinderProvider.Object\n            };\n            CompositeModelBinderProvider shimBinderProvider = new CompositeModelBinderProvider(binderProviders);\n            CompositeModelBinder shimBinder = new CompositeModelBinder(shimBinderProvider.GetBinder(null, null));\n\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                FallbackToEmptyPrefix = true,\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),\n                //ModelState = executionContext.Controller.ViewData.ModelState\n            };\n\n            // Act\n            bool isBound = shimBinder.BindModel(actionContext, bindingContext);\n\n            // Assert\n            Assert.False(isBound);\n            Assert.Null(bindingContext.Model);\n            Assert.True(bindingContext.ModelState.IsValid);\n            mockBinderProvider.Verify();\n            mockBinderProvider.Verify(o => o.GetBinder(It.IsAny<HttpConfiguration>(), It.IsAny<Type>()), Times.AtMostOnce());\n        }\n\n        private static HttpControllerContext GetHttpControllerContext()\n        {\n            return ContextUtil.CreateControllerContext();\n        }\n\n        private class SimpleController : ApiController\n        {\n        }\n\n        private class SimpleModel\n        {\n            public string FirstName { get; set; }\n            public string LastName { get; set; }\n        }\n\n        private class SimpleValueProvider : Dictionary<string, object>, IValueProvider\n        {\n            private readonly CultureInfo _culture;\n\n            public SimpleValueProvider()\n                : this(null)\n            {\n            }\n\n            public SimpleValueProvider(CultureInfo culture)\n                : base(StringComparer.OrdinalIgnoreCase)\n            {\n                _culture = culture ?? CultureInfo.InvariantCulture;\n            }\n\n            // copied from ValueProviderUtil\n            public bool ContainsPrefix(string prefix)\n            {\n                foreach (string key in Keys)\n                {\n                    if (key != null)\n                    {\n                        if (prefix.Length == 0)\n                        {\n                            return true; // shortcut - non-null key matches empty prefix\n                        }\n\n                        if (key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))\n                        {\n                            if (key.Length == prefix.Length)\n                            {\n                                return true; // exact match\n                            }\n                            else\n                            {\n                                switch (key[prefix.Length])\n                                {\n                                    case '.': // known separator characters\n                                    case '[':\n                                        return true;\n                                }\n                            }\n                        }\n                    }\n                }\n\n                return false; // nothing found\n            }\n\n            public ValueProviderResult GetValue(string key)\n            {\n                object rawValue;\n                if (TryGetValue(key, out rawValue))\n                {\n                    return new ValueProviderResult(rawValue, Convert.ToString(rawValue, _culture), _culture);\n                }\n                else\n                {\n                    // value not found\n                    return null;\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/DefaultActionValueBinderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Net.Http;\nusing System.Reflection;\nusing System.Threading;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.ValueProviders;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.ModelBinding\n{\n    // These tests primarily focus on getting the right binding contract. They don't actually execute the contract.\n    public class DefaultActionValueBinderTest\n    {\n        [Fact]\n        public void BindValuesAsync_Throws_Null_ActionDescriptor()\n        {\n            // Arrange\n            HttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = (MethodInfo)MethodInfo.GetCurrentMethod() };\n\n            // Act and Assert\n            Assert.ThrowsArgumentNull(\n                () => new DefaultActionValueBinder().GetBinding(null),\n                \"actionDescriptor\");\n        }\n\n        private void Action_Int(int id) { }\n\n        [Fact]\n        public void Check_Int_Is_ModelBound()\n        {\n            DefaultActionValueBinder binder = new DefaultActionValueBinder();\n\n            var binding = binder.GetBinding(GetAction(\"Action_Int\"));\n\n            Assert.Single(binding.ParameterBindings);\n            AssertIsModelBound(binding, 0);\n        }\n\n        [Fact]\n        public void Check_Config_Override_Use_Formatters()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.ParameterBindingRules.Add(param => param.BindWithFormatter()); // overrides\n\n            DefaultActionValueBinder binder = new DefaultActionValueBinder();\n\n            var binding = binder.GetBinding(GetAction(\"Action_Int\", config));\n\n            Assert.Single(binding.ParameterBindings);\n            AssertIsBody(binding, 0);\n        }\n\n        private void Action_Int_FromUri([FromUri] int id) { }\n\n        [Fact]\n        public void Check_Explicit_Int_Is_ModelBound()\n        {\n            // Even though int is implicitly model bound, still ok to specify it explicitly\n            DefaultActionValueBinder binder = new DefaultActionValueBinder();\n\n            var binding = binder.GetBinding(GetAction(\"Action_Int_FromUri\"));\n\n            Assert.Single(binding.ParameterBindings);\n            AssertIsModelBound(binding, 0);\n        }\n\n        // All types in this signature are model bound\n        private void Action_SimpleTypes(char ch, Byte b, Int16 i16, UInt16 u16, Int32 i32, UInt32 u32, Int64 i64, UInt64 u64, string s, DateTime d, Decimal dec, Guid g, DateTimeOffset dateTimeOffset, TimeSpan timespan) { }\n\n        [Fact]\n        public void Check_SimpleTypes_Are_ModelBound()\n        {\n            DefaultActionValueBinder binder = new DefaultActionValueBinder();\n\n            var binding = binder.GetBinding(GetAction(\"Action_SimpleTypes\"));\n\n            for (int i = 0; i < binding.ParameterBindings.Length; i++)\n            {\n                AssertIsModelBound(binding, 0);\n            }\n        }\n\n        private void Action_ComplexTypeWithStringConverter(ComplexTypeWithStringConverter x) { }\n\n        [Fact]\n        public void Check_String_TypeConverter_Is_ModelBound()\n        {\n            DefaultActionValueBinder binder = new DefaultActionValueBinder();\n\n            var binding = binder.GetBinding(GetAction(\"Action_ComplexTypeWithStringConverter\"));\n\n            Assert.Single(binding.ParameterBindings);\n            AssertIsModelBound(binding, 0);\n        }\n\n        private void Action_ComplexTypeWithStringConverter_Body_Override([FromBody] ComplexTypeWithStringConverter x) { }\n\n        [Fact]\n        public void Check_String_TypeConverter_With_Body_Override()\n        {\n            DefaultActionValueBinder binder = new DefaultActionValueBinder();\n\n            var binding = binder.GetBinding(GetAction(\"Action_ComplexTypeWithStringConverter_Body_Override\"));\n\n            Assert.Single(binding.ParameterBindings);\n            AssertIsBody(binding, 0);\n        }\n\n        private void Action_NullableInt(Nullable<int> id) { }\n\n        [Fact]\n        public void Check_NullableInt_Is_ModelBound()\n        {\n            DefaultActionValueBinder binder = new DefaultActionValueBinder();\n\n            var binding = binder.GetBinding(GetAction(\"Action_NullableInt\"));\n\n            Assert.Single(binding.ParameterBindings);\n            AssertIsModelBound(binding, 0);\n        }\n\n        private void Action_Nullable_ValueType(Nullable<ComplexValueType> id) { }\n\n        [Fact]\n        public void Check_Nullable_ValueType_Is_FromBody()\n        {\n            DefaultActionValueBinder binder = new DefaultActionValueBinder();\n\n            var binding = binder.GetBinding(GetAction(\"Action_Nullable_ValueType\"));\n\n            Assert.Single(binding.ParameterBindings);\n            AssertIsBody(binding, 0);\n        }\n\n\n        private void Action_IntArray(int[] arrayFrombody) { }\n\n        [Fact]\n        public void Check_IntArray_Is_FromBody()\n        {\n            DefaultActionValueBinder binder = new DefaultActionValueBinder();\n\n            var binding = binder.GetBinding(GetAction(\"Action_IntArray\"));\n\n            Assert.Single(binding.ParameterBindings);\n            AssertIsBody(binding, 0);\n        }\n\n\n        private void Action_SimpleType_Body([FromBody] int i) { }\n\n        [Fact]\n        public void Check_SimpleType_Body()\n        {\n            DefaultActionValueBinder binder = new DefaultActionValueBinder();\n\n            var binding = binder.GetBinding(GetAction(\"Action_SimpleType_Body\"));\n\n            Assert.Single(binding.ParameterBindings);\n            AssertIsBody(binding, 0);\n        }\n\n        private void Action_Empty() { }\n\n        [Fact]\n        public void Check_Empty_Action()\n        {\n            DefaultActionValueBinder binder = new DefaultActionValueBinder();\n\n            var binding = binder.GetBinding(GetAction(\"Action_Empty\"));\n\n            Assert.NotNull(binding.ParameterBindings);\n            Assert.Empty(binding.ParameterBindings);\n        }\n\n        private void Action_String_String(string s1, string s2) { }\n\n        [Fact]\n        public void Check_String_String_IsModelBound()\n        {\n            DefaultActionValueBinder binder = new DefaultActionValueBinder();\n\n            var binding = binder.GetBinding(GetAction(\"Action_String_String\"));\n\n            Assert.Equal(2, binding.ParameterBindings.Length);\n            AssertIsModelBound(binding, 0);\n            AssertIsModelBound(binding, 1);\n        }\n\n        private void Action_Complex_Type(ComplexType complex) { }\n\n        [Fact]\n        public void Check_Complex_Type_FromBody()\n        {\n            DefaultActionValueBinder binder = new DefaultActionValueBinder();\n\n            var binding = binder.GetBinding(GetAction(\"Action_Complex_Type\"));\n\n            Assert.Single(binding.ParameterBindings);\n            AssertIsBody(binding, 0);\n        }\n\n        [Fact]\n        public void Check_Config_Override_Use_ModelBinding()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.ParameterBindingRules.Add(param => param.BindWithModelBinding());\n            DefaultActionValueBinder binder = new DefaultActionValueBinder();\n\n            var binding = binder.GetBinding(GetAction(\"Action_Complex_Type\", config));\n\n            Assert.Single(binding.ParameterBindings);\n            AssertIsModelBound(binding, 0);\n        }\n\n\n        private void Action_Complex_ValueType(ComplexValueType complex) { }\n\n        [Fact]\n        public void Check_Complex_ValueType_FromBody()\n        {\n            DefaultActionValueBinder binder = new DefaultActionValueBinder();\n\n            var binding = binder.GetBinding(GetAction(\"Action_Complex_ValueType\"));\n\n            Assert.Single(binding.ParameterBindings);\n            AssertIsBody(binding, 0);\n        }\n\n        private void Action_Default_Custom_Model_Binder([ModelBinder] ComplexType complex) { }\n\n        [Fact]\n        public void Check_Customer_Binder()\n        {\n            // Mere presence of a ModelBinder attribute means the type is model bound.\n\n            DefaultActionValueBinder binder = new DefaultActionValueBinder();\n\n            var binding = binder.GetBinding(GetAction(\"Action_Default_Custom_Model_Binder\"));\n\n            Assert.Single(binding.ParameterBindings);\n            AssertIsModelBound(binding, 0);\n        }\n\n        private void Action_Complex_Type_Uri([FromUri] ComplexType complex) { }\n\n        [Fact]\n        public void Check_Complex_Type_FromUri()\n        {\n            // [FromUri] is just a specific instance of ModelBinder attribute\n            DefaultActionValueBinder binder = new DefaultActionValueBinder();\n\n            var binding = binder.GetBinding(GetAction(\"Action_Complex_Type_Uri\"));\n\n            Assert.Single(binding.ParameterBindings);\n            AssertIsModelBound(binding, 0);\n        }\n\n        private void Action_Two_Complex_Types(ComplexType complexBody1, ComplexType complexBody2) { }\n\n        [Fact]\n        public void Check_Two_Complex_Types_FromBody()\n        {\n            DefaultActionValueBinder binder = new DefaultActionValueBinder();\n\n            // It's illegal to have multiple parameters from the body.\n            // But we should still be able to get a binding for it. We just can't execute it.\n            var binding = binder.GetBinding(GetAction(\"Action_Two_Complex_Types\"));\n\n            Assert.Equal(2, binding.ParameterBindings.Length);\n            AssertIsError(binding, 0);\n            AssertIsError(binding, 1);\n        }\n\n        private void Action_Complex_Type_UriAndBody([FromUri] ComplexType complexUri, ComplexType complexBody) { }\n\n        [Fact]\n        public void Check_Complex_Type_FromBody_And_FromUri()\n        {\n            DefaultActionValueBinder binder = new DefaultActionValueBinder();\n\n            var binding = binder.GetBinding(GetAction(\"Action_Complex_Type_UriAndBody\"));\n\n            Assert.Equal(2, binding.ParameterBindings.Length);\n            AssertIsModelBound(binding, 0);\n            AssertIsBody(binding, 1);\n        }\n\n        private void Action_CancellationToken(CancellationToken ct) { }\n\n        [Fact]\n        public void Check_Cancellation_Token()\n        {\n            DefaultActionValueBinder binder = new DefaultActionValueBinder();\n\n            var binding = binder.GetBinding(GetAction(\"Action_CancellationToken\"));\n\n            Assert.Single(binding.ParameterBindings);\n            AssertIsCancellationToken(binding, 0);\n        }\n\n        private void Action_CustomModelBinder_On_Parameter_WithProvider([ModelBinder(typeof(CustomModelBinderProvider))] ComplexType complex) { }\n\n        [Fact]\n        public void Check_CustomModelBinder_On_Parameter()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Services.ReplaceRange(typeof(ValueProviderFactory), new ValueProviderFactory[] {\n                new CustomValueProviderFactory(),\n            });\n\n            DefaultActionValueBinder binder = new DefaultActionValueBinder();\n\n            var binding = binder.GetBinding(GetAction(\"Action_CustomModelBinder_On_Parameter_WithProvider\", config));\n\n            Assert.Single(binding.ParameterBindings);\n            AssertIsModelBound(binding, 0);\n\n            ModelBinderParameterBinding p = (ModelBinderParameterBinding)binding.ParameterBindings[0];\n            Assert.IsType<CustomModelBinder>(p.Binder);\n\n            // Since the ModelBinderAttribute didn't specify the valueproviders, we should pull those from config.\n            ValueProviderFactory valueProviderFactory = Assert.Single(p.ValueProviderFactories);\n            Assert.IsType<CustomValueProviderFactory>(valueProviderFactory);\n        }\n\n        // Model binder attribute is on the type's declaration.\n        private void Action_ComplexParameter_With_ModelBinder(ComplexTypeWithModelBinder complex) { }\n\n        [Fact]\n        public void Check_Parameter_With_ModelBinder_Attribute_On_Type()\n        {\n            DefaultActionValueBinder binder = new DefaultActionValueBinder();\n\n            var binding = binder.GetBinding(GetAction(\"Action_ComplexParameter_With_ModelBinder\"));\n\n            Assert.Single(binding.ParameterBindings);\n            AssertIsModelBound(binding, 0);\n        }\n\n        private void Action_Conflicting_Attributes([FromBody][FromUri] int i) { }\n\n        [Fact]\n        public void Error_Conflicting_Attributes()\n        {\n            DefaultActionValueBinder binder = new DefaultActionValueBinder();\n\n            var binding = binder.GetBinding(GetAction(\"Action_Conflicting_Attributes\"));\n\n            // Have 2 attributes that conflict with each other. Still get the contract, but it has an error in it.\n            Assert.Single(binding.ParameterBindings);\n            AssertIsError(binding, 0);\n        }\n\n        [FromBody]\n        class Widget\n        {\n        }\n        private void Action_Closest_Attribute_Wins([FromUri] Widget i) { }\n\n        [Fact]\n        public void Check_Closest_Attribute_Wins()\n        {\n            DefaultActionValueBinder binder = new DefaultActionValueBinder();\n\n            var binding = binder.GetBinding(GetAction(\"Action_Closest_Attribute_Wins\"));\n\n            // Have 2 attributes that conflict with each other. Still get the contract, but it has an error in it.\n            Assert.Single(binding.ParameterBindings);\n            AssertIsModelBound(binding, 0);\n        }\n\n        private void Action_HttpContent_Parameter(HttpContent c) { }\n\n        [Fact]\n        public void Check_HttpContent()\n        {\n            DefaultActionValueBinder binder = new DefaultActionValueBinder();\n\n            var binding = binder.GetBinding(GetAction(\"Action_HttpContent_Parameter\"));\n\n            Assert.Single(binding.ParameterBindings);\n            AssertIsError(binding, 0);\n        }\n\n        private void Action_Derived_HttpContent_Parameter(StreamContent c) { }\n\n        [Fact]\n        public void Check_Derived_HttpContent()\n        {\n            DefaultActionValueBinder binder = new DefaultActionValueBinder();\n\n            var binding = binder.GetBinding(GetAction(\"Action_Derived_HttpContent_Parameter\"));\n\n            Assert.Single(binding.ParameterBindings);\n            AssertIsError(binding, 0);\n        }\n\n        private void Action_Request_Parameter(HttpRequestMessage request) { }\n\n        [Fact]\n        public void Check_Request_Parameter()\n        {\n            DefaultActionValueBinder binder = new DefaultActionValueBinder();\n\n            var binding = binder.GetBinding(GetAction(\"Action_Request_Parameter\"));\n\n            Assert.Single(binding.ParameterBindings);\n            AssertIsCustomBinder<HttpRequestParameterBinding>(binding, 0);\n        }\n\n\n        private void Action_CustomBindingAttribute([CustomBindingAttribute] int x) { }\n\n        [Fact]\n        public void Check_CustomBindingAttribute()\n        {\n            DefaultActionValueBinder binder = new DefaultActionValueBinder();\n\n            var binding = binder.GetBinding(GetAction(\"Action_CustomBindingAttribute\"));\n\n            HttpParameterBinding parameterBinding = Assert.Single(binding.ParameterBindings);\n            Assert.Same(CustomBindingAttribute.MockBinding, parameterBinding);\n        }\n\n        [AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)]\n        private class CustomBindingAttribute : ParameterBindingAttribute\n        {\n            public static HttpParameterBinding MockBinding = new CustomBinding();\n\n            public override HttpParameterBinding GetBinding(HttpParameterDescriptor parameter)\n            {\n                return MockBinding;\n            }\n\n            private class CustomBinding : HttpParameterBinding\n            {\n                public CustomBinding()\n                    : base(new Mock<HttpParameterDescriptor>().Object)\n                {\n                }\n                public override Threading.Tasks.Task ExecuteBindingAsync(Metadata.ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)\n                {\n                    throw new NotImplementedException();\n                }\n            }\n        }\n\n\n\n        // Assert that the binding contract says the given parameter comes from the body\n        private void AssertIsBody(HttpActionBinding binding, int paramIdx)\n        {\n            HttpParameterBinding p = binding.ParameterBindings[paramIdx];\n            Assert.NotNull(p);\n            Assert.True(p.IsValid);\n            Assert.True(p.WillReadBody);\n        }\n\n        // Assert that the binding contract says the given parameter is not from the body (will be handled by model binding)\n        private void AssertIsModelBound(HttpActionBinding binding, int paramIdx)\n        {\n            HttpParameterBinding p = binding.ParameterBindings[paramIdx];\n            Assert.NotNull(p);\n            Assert.IsType<ModelBinderParameterBinding>(p);\n            Assert.True(p.IsValid);\n            Assert.False(p.WillReadBody);\n        }\n\n        // Assert that the binding contract says the given parameter will be bound to the cancellation token.\n        private void AssertIsCancellationToken(HttpActionBinding binding, int paramIdx)\n        {\n            AssertIsCustomBinder<CancellationTokenParameterBinding>(binding, paramIdx);\n        }\n\n        private void AssertIsError(HttpActionBinding binding, int paramIdx)\n        {\n            HttpParameterBinding p = binding.ParameterBindings[paramIdx];\n            Assert.NotNull(p);\n            Assert.False(p.IsValid);\n            Assert.False(p.WillReadBody);\n        }\n\n        private void AssertIsCustomBinder<T>(HttpActionBinding binding, int paramIdx)\n        {\n            HttpParameterBinding p = binding.ParameterBindings[paramIdx];\n            Assert.NotNull(p);\n            Assert.IsType<T>(p);\n            Assert.True(p.IsValid);\n            Assert.False(p.WillReadBody);\n        }\n\n\n        // Helper to get an ActionDescriptor for a method name.\n        private HttpActionDescriptor GetAction(string name)\n        {\n            return GetAction(name, new HttpConfiguration());\n        }\n\n        private HttpActionDescriptor GetAction(string name, HttpConfiguration config)\n        {\n            MethodInfo method = this.GetType().GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);\n            Assert.NotNull(method);\n            return new ReflectedHttpActionDescriptor { MethodInfo = method, Configuration = config, ControllerDescriptor = GetControllerDescriptor(config) };\n        }\n\n        // Get a controller descriptor that's sufficiently initialized to use with parameter binding\n        private HttpControllerDescriptor GetControllerDescriptor(HttpConfiguration config)\n        {\n            return new HttpControllerDescriptor(config);\n        }\n\n        // Complex type to use with tests\n        class ComplexType\n        {\n        }\n\n        struct ComplexValueType\n        {\n        }\n\n        // Complex type to use with tests\n        [ModelBinder]\n        class ComplexTypeWithModelBinder\n        {\n        }\n\n        // Add Type converter for string, which causes the type to be viewed as a Simple type.\n        [TypeConverter(typeof(MyTypeConverter))]\n        public class ComplexTypeWithStringConverter\n        {\n            public string Data { get; set; }\n            public ComplexTypeWithStringConverter(string data)\n            {\n                Data = data;\n            }\n        }\n\n        // A string type converter\n        public class MyTypeConverter : TypeConverter\n        {\n            public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)\n            {\n                if (sourceType == typeof(string))\n                {\n                    return true;\n                }\n                return base.CanConvertFrom(context, sourceType);\n            }\n\n            public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)\n            {\n                if (value is string)\n                {\n                    return new ComplexTypeWithStringConverter((string)value);\n                }\n\n                return base.ConvertFrom(context, culture, value);\n            }\n        }\n\n        class CustomModelBinderProvider : ModelBinderProvider\n        {\n            public override IModelBinder GetBinder(HttpConfiguration config, Type modelType)\n            {\n                return new CustomModelBinder();\n            }\n        }\n\n        class CustomModelBinder : IModelBinder\n        {\n            public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        class CustomValueProviderFactory : ValueProviderFactory\n        {\n            public override IValueProvider GetValueProvider(HttpActionContext actionContext)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/FormDataCollectionExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Validation;\nusing System.Web.Http.Validation.Providers;\nusing System.Web.Http.ValueProviders;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.ModelBinding\n{\n    public class FormDataCollectionExtensionsTest\n    {\n        [Theory]\n        [InlineData(\"\", null)]\n        [InlineData(\"\", \"\")] // empty\n        [InlineData(\"x\", \"x\")] // normal key\n        [InlineData(\"\", \"[]\")] // trim []\n        [InlineData(\"x\", \"x[]\")] // trim []\n        [InlineData(\"x[234]\", \"x[234]\")] // array index\n        [InlineData(\"x.y\", \"x[y]\")] // field lookup\n        [InlineData(\"x.y.z\", \"x[y][z]\")] // nested field lookup\n        [InlineData(\"x.y[234].x\", \"x[y][234][x]\")] // compound\n        public void TestNormalize(string expectedMvc, string jqueryString)\n        {\n            Assert.Equal(expectedMvc, FormDataCollectionExtensions.NormalizeJQueryToMvc(jqueryString));\n        }\n\n        [Fact]\n        public void TestGetJQueryNameValuePairs()\n        {\n            // Arrange\n            var formData = new FormDataCollection(\"x.y=30&x[y]=70&x[z][20]=cool\");\n\n            // Act\n            var actual = FormDataCollectionExtensions.GetJQueryNameValuePairs(formData).ToArray();\n\n            // Assert\n            var arraySetter = Assert.Single(actual, kvp => kvp.Key == \"x.z[20]\");\n            Assert.Equal(\"cool\", arraySetter.Value);\n\n            Assert.Single(actual, kvp => kvp.Key == \"x.y\" && kvp.Value == \"30\");\n            Assert.Single(actual, kvp => kvp.Key == \"x.y\" && kvp.Value == \"70\");\n        }\n\n        [Fact]\n        public async Task ReadIntArray()\n        {\n            // No key name means the top level object is an array\n            int[] result = await ParseJQueryAsync<int[]>(\"=30&=40&=50\");\n\n            Assert.Equal(new int[] { 30,40,50 } , result);\n        }\n\n        [Fact]\n        public async Task ReadIntArrayWithBrackets()\n        {\n            // brackets for explicit array\n            int[] result = await ParseJQueryAsync<int[]>(\"[]=30&[]=40&[]=50\");\n\n            Assert.Equal(new int[] { 30, 40, 50 }, result);\n        }\n\n        [Fact]\n        public async Task ReadIntArrayFromSingleElement()\n        {\n            // No key name means the top level object is an array\n            int[] result = await ParseJQueryAsync<int[]>(\"=30\");\n\n            Assert.Equal(new int[] { 30 }, result);\n        }\n\n        [Fact]\n        public async Task ReadClassWithIntArray()\n        {\n            // specifying key name 'x=30' means that we have a field named x.\n            // multiple x keys mean that field is an array.\n            var result = await ParseJQueryAsync<ClassWithArrayField>(\"x=30&x=40&x=50\");\n\n            Assert.Equal(new int[] { 30, 40, 50 }, result.x);\n        }\n\n        public class ComplexType\n        {\n            public string Str { get; set; }\n            public int I { get; set; }\n            public Point P { get; set; }\n        }\n        public class Point\n        {\n            public int X { get; set; }\n            public int Y { get; set; }\n        }\n\n        [Fact]\n        public async Task ReadClassWithFields()\n        {\n            // Basic container class with multiple fields\n            var result = await ParseJQueryAsync<Point>(\"X=3&Y=4\");\n            Assert.Equal(3, result.X);\n            Assert.Equal(4, result.Y);\n        }\n\n        [Fact]\n        public void ReadClassWithFieldsFromUri()\n        {\n            var uri = new Uri(\"http://foo.com/?X=3&Y=4&Z=5\");\n            FormDataCollection fd = new FormDataCollection(uri);\n            var result = fd.ReadAs<Point>();\n\n            Assert.Equal(3, result.X);\n            Assert.Equal(4, result.Y);\n        }\n\n        [Fact]\n        public async Task ReadClassWithFieldsAndPartialBind()\n        {\n            // Basic container class with multiple fields\n            // Extra Z=5 field, ignored since we're reading point.\n            var result = await ParseJQueryAsync<Point>(\"X=3&Y=4&Z=5\");\n            Assert.Equal(3, result.X);\n            Assert.Equal(4, result.Y);\n        }\n\n        public class Nest\n        {\n            public Nest A { get; set; }\n        }\n\n        [Fact]\n        public Task ReadDeeplyNestedFormUrlThrows()\n        {\n            StringBuilder sb = new StringBuilder(\"A\");\n            for (int i = 0; i < 10000; i++)\n            {\n                sb.Append(\"[A]\");\n            }\n            sb.Append(\"=1\");\n\n            return Assert.ThrowsAsync<InsufficientExecutionStackException>(() => ParseJQueryAsync<Nest>(sb.ToString()));\n        }\n\n        [Fact]\n        public Task ReadDeeplyNestedMvcThrows()\n        {\n            StringBuilder sb = new StringBuilder(\"A\");\n            for (int i = 0; i < 10000; i++)\n            {\n                sb.Append(\".A\");\n            }\n            sb.Append(\"=1\");\n\n            return Assert.ThrowsAsync<InsufficientExecutionStackException>(() => ParseJQueryAsync<Nest>(sb.ToString()));\n        }\n\n        public class ClassWithPointArray\n        {\n            public Point[] Data { get; set; }\n        }\n\n        [Fact]\n        public async Task ReadArrayOfClasses()\n        {\n            // Array of classes.\n            string s = \"Data[0][X]=10&Data[0][Y]=20&Data[1][X]=30&Data[1][Y]=40\";\n            var result = await ParseJQueryAsync<ClassWithPointArray>(s);\n\n            Assert.NotNull(result.Data);\n            Assert.Equal(2, result.Data.Length);\n            Assert.Equal(10, result.Data[0].X);\n            Assert.Equal(20, result.Data[0].Y);\n            Assert.Equal(30, result.Data[1].X);\n            Assert.Equal(40, result.Data[1].Y);\n        }\n\n        [Fact]\n        public async Task ReadComplexNestedType()\n        {\n            var result = await ParseJQueryAsync<ComplexType>(\"Str=Hello+world&I=123&P[X]=3&P[Y]=4\");\n            Assert.Equal(\"Hello world\", result.Str);\n            Assert.Equal(123, result.I);\n            Assert.NotNull(result.P); // failed to find P\n            Assert.Equal(3, result.P.X);\n            Assert.Equal(4, result.P.Y);\n        }\n\n        class ComplexType2\n        {\n            public class Epsilon\n            {\n                public int[] f { get; set; }\n            }\n\n            public class Beta\n            {\n                public int c { get; set; }\n                public int d { get; set; }\n            }\n\n            public int[] a { get; set; }\n            public Beta[] b { get; set; }\n            public Epsilon e { get; set; }\n        }\n\n        [Fact]\n        public async Task ReadComplexNestedType2()\n        {\n            // Jquery encoding from this JSON: \"{a:[1,2],b:[{c:3,d:4},{c:5,d:6}],e:{f:[7,8,9]}}\";\n            string s = \"a[]=1&a[]=2&b[0][c]=3&b[0][d]=4&b[1][c]=5&b[1][d]=6&e[f][]=7&e[f][]=8&e[f][]=9\";\n            var result = await ParseJQueryAsync<ComplexType2>(s);\n\n            Assert.NotNull(result);\n            Assert.Equal(new int[] { 1, 2 }, result.a);\n            Assert.Equal(2, result.b.Length);\n            Assert.Equal(3, result.b[0].c);\n            Assert.Equal(4, result.b[0].d);\n            Assert.Equal(5, result.b[1].c);\n            Assert.Equal(6, result.b[1].d);\n            Assert.Equal(new int[] { 7, 8, 9 }, result.e.f);\n        }\n\n        [Fact]\n        public async Task ReadJaggedArray()\n        {\n            string s = \"[0][]=9&[0][]=10&[1][]=11&[1][]=12&[2][]=13&[2][]=14\";\n            var result = await ParseJQueryAsync<int[][]>(s);\n\n            Assert.Equal(9, result[0][0]);\n            Assert.Equal(10, result[0][1]);\n            Assert.Equal(11, result[1][0]);\n            Assert.Equal(12, result[1][1]);\n            Assert.Equal(13, result[2][0]);\n            Assert.Equal(14, result[2][1]);\n        }\n\n        [Fact]\n        public async Task ReadMultipleParameters()\n        {\n            // Basic container class with multiple fields\n            HttpContent content = FormContent(\"X=3&Y=4\");\n            FormDataCollection fd = await content.ReadAsAsync<FormDataCollection>();\n\n            Assert.Equal(3, fd.ReadAs<int>(\"X\", requiredMemberSelector: null, formatterLogger: null));\n            Assert.Equal(\"3\", fd.ReadAs<string>(\"X\", requiredMemberSelector: null, formatterLogger: null));\n            Assert.Equal(4, fd.ReadAs<int>(\"Y\", requiredMemberSelector: null, formatterLogger: null));\n        }\n\n        [Fact]\n        public async Task ReadInvalidInt_ReturnsDefaultValue()\n        {\n            int result = await ParseJQueryAsync<int>(\"xyz\");\n            Assert.Equal(0, result);\n        }\n\n        [Fact]\n        public async Task ReadForThrowingSetterTypeRecordsCorrectModelError()\n        {\n            HttpContent content = FormContent(\"Throws=text\");\n            FormDataCollection formData = await content.ReadAsAsync<FormDataCollection>();\n            Mock<IFormatterLogger> mockLogger = new Mock<IFormatterLogger>();\n\n            formData.ReadAs<ThrowingSetterType>(String.Empty, requiredMemberSelector: null, formatterLogger: mockLogger.Object);\n\n            mockLogger.Verify(mock => mock.LogError(\"Throws\", ThrowingSetterType.Exception));\n        }\n\n        [Fact]\n        public async Task ReadAs_NullActionContextThrows()\n        {\n            // Arrange\n            HttpContent content = FormContent(\"=30\");\n            FormDataCollection formData = await content.ReadAsAsync<FormDataCollection>();\n\n            // Act/Assert\n            Assert.Throws<ArgumentNullException>(() => formData.ReadAs<int>((HttpActionContext)null));\n        }\n\n        [Fact]\n        public async Task ReadAs_WithHttpActionContext()\n        {\n            // Arrange\n            int expected = 30;\n            HttpContent content = FormContent(\"=30\");\n            FormDataCollection formData = await content.ReadAsAsync<FormDataCollection>();\n\n            using (HttpConfiguration configuration = new HttpConfiguration())\n            {\n                HttpActionContext actionContext = CreateActionContext(configuration);\n\n                // Act\n                int actual = formData.ReadAs<int>(actionContext);\n\n                // Assert\n                Assert.Equal(expected, actual);\n            }\n        }\n\n        [Fact]\n        public async Task ReadAs_WithModelNameAndHttpActionContext()\n        {\n            // Arrange\n            int expected = 30;\n            HttpContent content = FormContent(\"a=30\");\n            FormDataCollection formData = await content.ReadAsAsync<FormDataCollection>();\n\n            using (HttpConfiguration configuration = new HttpConfiguration())\n            {\n                HttpActionContext actionContext = CreateActionContext(configuration);\n\n                // Act\n                int actual = (int)formData.ReadAs(typeof(int), \"a\", actionContext);\n\n                // Assert\n                Assert.Equal(expected, actual);\n            }\n        }\n\n        // This test verifies the user scenario behind codeplex-999 - ReadAs should take HttpActionContext\n        // as a parameter to make use of ModelBinders in the configuration.\n        [Fact]\n        public async Task Read_As_WithHttpActionContextAndCustomModelBinder()\n        {\n            // Arrange\n            int expected = 15;\n            HttpContent content = FormContent(\"a=30\");\n            FormDataCollection formData = await content.ReadAsAsync<FormDataCollection>();\n\n            using (HttpConfiguration configuration = new HttpConfiguration())\n            {\n                configuration.Services.Insert(typeof(ModelBinderProvider), 0, new CustomIntModelBinderProvider());\n\n                HttpActionContext actionContext = CreateActionContext(configuration);\n\n                // Act\n                int actual = (int)formData.ReadAs(typeof(int), \"a\", actionContext);\n\n                // Assert\n                Assert.Equal(expected, actual);\n            }\n        }\n\n        // This test is to make sure that the ServicesConfigurationWrapper has not\n        // altered HttpConfiguration.Services in any way\n        [Fact]\n        public async Task Read_As_NoServicesChangeInConfig()\n        {\n            // Arrange\n            HttpContent content = FormContent(\"a=30\");\n            FormDataCollection formData = await content.ReadAsAsync<FormDataCollection>();\n\n            using (HttpConfiguration configuration = new HttpConfiguration())\n            {\n                // Act\n                HttpControllerSettings settings = new HttpControllerSettings(configuration);\n                HttpConfiguration clonedConfiguration =\n                    HttpConfiguration.ApplyControllerSettings(settings, configuration);\n                int actual = (int)formData.ReadAs(typeof(int), \"a\", requiredMemberSelector: null,\n                    formatterLogger: (new Mock<IFormatterLogger>()).Object, config: configuration);\n\n                // Assert\n                Assert.Equal(30, actual);\n                Assert.Same(clonedConfiguration.Services, configuration.Services);\n            }\n        }\n\n        [Fact]\n        public void ServicesContainerWrapper_GetServices_Returns_RequiredModelValidatorProvider()\n        {\n            // Arrange\n            var requiredMemberModelValidatorProvider =\n                new RequiredMemberModelValidatorProvider(requiredMemberSelector: null);\n            FormDataCollectionExtensions.ServicesContainerWrapper wrapper =\n                new FormDataCollectionExtensions.ServicesContainerWrapper(\n                    new HttpConfiguration(), requiredMemberModelValidatorProvider);\n\n            // Act\n            IEnumerable<object> services = wrapper.GetServices(typeof(ModelValidatorProvider));\n\n            // Assert\n            Assert.Same(requiredMemberModelValidatorProvider, services.ElementAt(0));\n        }\n\n        [Fact]\n        public void ServicesContainerWrapper_GetService_Returns_ModelValidatorCache()\n        {\n            // Arrange\n            FormDataCollectionExtensions.ServicesContainerWrapper wrapper =\n                new FormDataCollectionExtensions.ServicesContainerWrapper(\n                    new HttpConfiguration(), new RequiredMemberModelValidatorProvider(requiredMemberSelector: null));\n\n            // Act\n            object serviceInstance1 = wrapper.GetService(typeof(IModelValidatorCache));\n            object serviceInstance2 = wrapper.GetService(typeof(IModelValidatorCache));\n\n            // Assert\n            Assert.IsType<ModelValidatorCache>(serviceInstance1);\n            Assert.NotSame(serviceInstance1, serviceInstance2);\n        }\n\n        [Fact]\n        public void ServicesContainerWrapper_GetService_Returns_ModelValidatorProvider()\n        {\n            // Arrange\n            var requiredMemberModelValidatorProvider =\n                new RequiredMemberModelValidatorProvider(requiredMemberSelector: null);\n            FormDataCollectionExtensions.ServicesContainerWrapper wrapper =\n                new FormDataCollectionExtensions.ServicesContainerWrapper(\n                    new HttpConfiguration(), requiredMemberModelValidatorProvider);\n\n            // Act\n            object service = wrapper.GetService(typeof(ModelValidatorProvider));\n\n            // Assert\n            Assert.Equal(requiredMemberModelValidatorProvider, service);\n        }\n\n        private static HttpActionContext CreateActionContext(HttpConfiguration configuration)\n        {\n            HttpControllerContext controllerContext = new HttpControllerContext()\n            {\n                Configuration = configuration,\n                ControllerDescriptor = new HttpControllerDescriptor(configuration),\n            };\n\n            return new HttpActionContext { ControllerContext = controllerContext };\n        }\n\n        private static HttpContent FormContent(string s)\n        {\n            HttpContent content = new StringContent(s);\n            content.Headers.ContentType = new MediaTypeHeaderValue(\"application/x-www-form-urlencoded\");\n\n            return content;\n        }\n\n        private async Task<T> ParseJQueryAsync<T>(string jquery)\n        {\n            HttpContent content = FormContent(jquery);\n            FormDataCollection fd = await content.ReadAsAsync<FormDataCollection>();\n            T result = fd.ReadAs<T>();\n            return result;\n        }\n\n        private class CustomIntModelBinder : IModelBinder\n        {\n            public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)\n            {\n                ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);\n                int result = (int)valueResult.ConvertTo(typeof(int));\n\n                bindingContext.Model = result / 2;\n                return true;\n            }\n        }\n\n        private class CustomIntModelBinderProvider : ModelBinderProvider\n        {\n            public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)\n            {\n                if (modelType == typeof(int))\n                {\n                    return new CustomIntModelBinder();\n                }\n                else\n                {\n                    return null;\n                }\n            }\n        }\n\n        private class ThrowingSetterType\n        {\n            public static Exception Exception = new Exception(\"This setter throws\");\n            public string Throws { get { return null; } set { throw Exception; } }\n        }\n\n        private class ClassWithArrayField\n        {\n            public int[] x { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/FormatterParameterBindingTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Validation;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.ModelBinding\n{\n    public class FormatterParameterBindingTest\n    {\n        [Fact]\n        public void ReadContentAsync_Throws_ForNoContentType()\n        {\n            var request = new HttpRequestMessage(HttpMethod.Post, \"http://localhost\");\n            request.Content = new StringContent(\"The quick, brown fox tripped and fell.\");\n            request.Content.Headers.ContentType = null;\n            var formatters = new MediaTypeFormatterCollection();\n            var descriptor = new Mock<HttpParameterDescriptor>();\n            descriptor.Setup(desc => desc.IsOptional).Returns(false);\n            var binding = new FormatterParameterBinding(descriptor.Object, formatters, null);\n\n            HttpResponseException exception = Assert.Throws<HttpResponseException>(\n                () => binding.ReadContentAsync(request, typeof(string), formatters, null));\n\n            Assert.Equal(HttpStatusCode.UnsupportedMediaType, exception.Response.StatusCode);\n            HttpError error;\n            exception.Response.TryGetContentValue(out error);\n            Assert.Equal(\n                \"The request contains an entity body but no Content-Type header. The inferred media type 'application/octet-stream' is not supported for this resource.\",\n                error.Message);\n        }\n\n        [Fact]\n        public void ReadContentAsync_Throws_ForUnsupportedMediaType()\n        {\n            var request = new HttpRequestMessage(HttpMethod.Post, \"http://localhost\");\n            request.Content = new StringContent(\"The quick, brown fox tripped and fell.\");\n            var formatters = new MediaTypeFormatterCollection();\n            var descriptor = new Mock<HttpParameterDescriptor>();\n            descriptor.Setup(desc => desc.IsOptional).Returns(false);\n            var binding = new FormatterParameterBinding(descriptor.Object, formatters, null);\n\n            HttpResponseException exception = Assert.Throws<HttpResponseException>(\n                () => binding.ReadContentAsync(request, typeof(string), formatters, null));\n\n            Assert.Equal(HttpStatusCode.UnsupportedMediaType, exception.Response.StatusCode);\n            HttpError error;\n            exception.Response.TryGetContentValue(out error);\n            Assert.Equal(\n                \"The request entity's media type 'text/plain' is not supported for this resource.\",\n                error.Message);\n        }\n\n        [Fact]\n        public async Task ExecuteBindingAsync_PassesCancellationTokenTo_ReadContentAsync()\n        {\n            // Arrange\n            var parameter = new Mock<HttpParameterDescriptor>();\n            parameter.Setup(p => p.IsOptional).Returns(false);\n            parameter.Setup(p => p.ParameterName).Returns(\"ParameterName\");\n            var formatters = Enumerable.Empty<MediaTypeFormatter>();\n            IBodyModelValidator validator = null;\n            ModelMetadataProvider metadataProvider = new Mock<ModelMetadataProvider>().Object;\n            HttpRequestMessage request = new HttpRequestMessage();\n            HttpActionContext actionContext = new HttpActionContext { ControllerContext = new HttpControllerContext { Request = request } };\n            CancellationTokenSource cts = new CancellationTokenSource();\n\n            Mock<FormatterParameterBinding> binding = new Mock<FormatterParameterBinding>(parameter.Object, formatters, validator);\n            binding.CallBase = true;\n            binding.Setup(b => b.ReadContentAsync(request, null, formatters, It.IsAny<IFormatterLogger>()))\n                .Returns(Task.FromResult<object>(42))\n                .Verifiable();\n\n            // Act\n            await binding.Object.ExecuteBindingAsync(metadataProvider, actionContext, cts.Token);\n\n            // Assert\n            binding.Verify();\n        }\n\n        [Fact]\n        public async Task ReadContentAsync_PassesCancellationToken_Further()\n        {\n            // Arrange\n            var parameter = new Mock<HttpParameterDescriptor>();\n            parameter.Setup(p => p.IsOptional).Returns(false);\n            IBodyModelValidator validator = null;\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.Content = new StringContent(\"\");\n            request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(\"app/test\");\n            IFormatterLogger logger = null;\n            CancellationTokenSource cts = new CancellationTokenSource();\n\n            Mock<MediaTypeFormatter> formatter = new Mock<MediaTypeFormatter>();\n            formatter.Setup(f => f.CanReadType(typeof(int))).Returns(true);\n            formatter.Object.SupportedMediaTypes.Add(request.Content.Headers.ContentType);\n            formatter.Setup(f => f.ReadFromStreamAsync(typeof(int), It.IsAny<Stream>(), request.Content, logger, cts.Token))\n                .Returns(Task.FromResult<object>(42))\n                .Verifiable();\n\n            var formatters = new[] { formatter.Object };\n            FormatterParameterBinding binding = new FormatterParameterBinding(parameter.Object, formatters, validator);\n\n            // Act\n            await binding.ReadContentAsync(request, typeof(int), formatters, logger, cts.Token);\n\n            // Assert\n            formatter.Verify();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/HttpBindingBehaviorAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ModelBinding\n{\n    public class HttpHttpBindingBehaviorAttributeTest\n    {\n        [Fact]\n        public void Behavior_Property()\n        {\n            // Arrange\n            HttpBindingBehavior expectedBehavior = (HttpBindingBehavior)(-20);\n\n            // Act\n            HttpBindingBehaviorAttribute attr = new HttpBindingBehaviorAttribute(expectedBehavior);\n\n            // Assert\n            Assert.Equal(expectedBehavior, attr.Behavior);\n        }\n\n        [Fact]\n        public void TypeId_ReturnsSameValue()\n        {\n            // Arrange\n            HttpBindNeverAttribute neverAttr = new HttpBindNeverAttribute();\n            HttpBindRequiredAttribute requiredAttr = new HttpBindRequiredAttribute();\n\n            // Act & assert\n            Assert.Same(neverAttr.TypeId, requiredAttr.TypeId);\n        }\n\n        [Fact]\n        public void BindNever_SetsBehavior()\n        {\n            // Act\n            HttpBindingBehaviorAttribute attr = new HttpBindNeverAttribute();\n\n            // Assert\n            Assert.Equal(HttpBindingBehavior.Never, attr.Behavior);\n        }\n\n        [Fact]\n        public void BindRequired_SetsBehavior()\n        {\n            // Act\n            HttpBindingBehaviorAttribute attr = new HttpBindRequiredAttribute();\n\n            // Assert\n            Assert.Equal(HttpBindingBehavior.Required, attr.Behavior);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/HttpParameterBindingExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Internal;\nusing System.Web.Http.ValueProviders;\nusing System.Web.Http.ValueProviders.Providers;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.ModelBinding\n{\n    public class HttpParameterBindingExtensionsTest\n    {\n        [Fact]\n        public void WillReadUri_Throws_With_Null_ParameterBinding()\n        {\n            // Arrange\n            HttpParameterBinding binding = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => binding.WillReadUri(), \"parameterBinding\");\n        }\n\n        [Fact]\n        public void WillReadUri_Returns_True_For_IValueProviderParameterBinding_Containing_Only_Standard_Uri_ValueProviders()\n        {\n            // Arrange\n            Mock<HttpParameterDescriptor> descriptorMock = new Mock<HttpParameterDescriptor>();\n            HttpParameterBinding bindingMock = new HttpValueProviderParameterBindingTestDouble(\n                                                    descriptorMock.Object,\n                                                    new List<ValueProviderFactory>() \n                                                    {\n                                                        new QueryStringValueProviderFactory(), \n                                                        new RouteDataValueProviderFactory()\n                                                    });\n\n            // Act\n            bool result = bindingMock.WillReadUri();\n\n            // Assert\n            Assert.True(result);\n        }\n\n        [Fact]\n        public void WillReadUri_Returns_False_For_IValueProviderParameterBinding_Containing_Non_Uri_ValueProviders()\n        {\n            // Arrange\n            Mock<HttpParameterDescriptor> descriptorMock = new Mock<HttpParameterDescriptor>();\n            Mock<ValueProviderFactory> valueProviderMock = new Mock<ValueProviderFactory>();\n            HttpParameterBinding bindingMock = new HttpValueProviderParameterBindingTestDouble(\n                                                    descriptorMock.Object,\n                                                    new List<ValueProviderFactory>() \n                                                    {\n                                                        new QueryStringValueProviderFactory(), \n                                                        new RouteDataValueProviderFactory(),\n                                                        valueProviderMock.Object,\n                                                    });\n\n            // Act\n            bool result = bindingMock.WillReadUri();\n\n            // Assert\n            Assert.False(result);\n        }\n\n        [Fact]\n        public void WillReadUri_Returns_False_For_IValueProviderParameterBinding_Containing_No_ValueProviders()\n        {\n            // Arrange\n            Mock<HttpParameterDescriptor> descriptorMock = new Mock<HttpParameterDescriptor>();\n            HttpParameterBinding bindingMock = new HttpValueProviderParameterBindingTestDouble(\n                                                    descriptorMock.Object,\n                                                    new List<ValueProviderFactory>());\n\n            // Act\n            bool result = bindingMock.WillReadUri();\n\n            // Assert\n            Assert.False(result);\n        }\n\n        [Fact]\n        public void WillReadUri_Returns_False_For_HttpParameterBinding_Not_Implementing_IValueProviderParameterBinding()\n        {\n            // Arrange\n            Mock<HttpParameterDescriptor> descriptorMock = new Mock<HttpParameterDescriptor>();\n            Mock<HttpParameterBinding> bindingMock = new Mock<HttpParameterBinding>(descriptorMock.Object);\n\n            // Act\n            bool result = bindingMock.Object.WillReadUri();\n\n            // Assert\n            Assert.False(result);\n        }\n\n        class HttpValueProviderParameterBindingTestDouble : HttpParameterBinding, IValueProviderParameterBinding\n        {\n            public IEnumerable<ValueProviderFactory> Factories { get; set; }\n\n            public HttpValueProviderParameterBindingTestDouble(HttpParameterDescriptor descriptor, IEnumerable<ValueProviderFactory> factories) : base(descriptor)\n            {\n                Factories = factories;\n            }\n\n            public override Task ExecuteBindingAsync(Metadata.ModelMetadataProvider metadataProvider, HttpActionContext actionContext, Threading.CancellationToken cancellationToken)\n            {\n                throw new NotImplementedException();\n            }\n\n            public IEnumerable<ValueProviderFactory> ValueProviderFactories\n            {\n                get { return Factories; }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/ModelBinderAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Dependencies;\nusing System.Web.Http.ValueProviders;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.ModelBinding\n{\n    public class ModelBinderAttributeTest\n    {\n        [Fact]\n        public void Empty_BinderType()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Services.Replace(typeof(ModelBinderProvider), new CustomModelBinderProvider());\n\n            ModelBinderAttribute attr = new ModelBinderAttribute();\n\n            ModelBinderProvider provider = attr.GetModelBinderProvider(config);\n            Assert.IsType<CustomModelBinderProvider>(provider);\n        }\n\n        [Fact]\n        public void Illegal_BinderType()\n        {\n            // Given an illegal type.\n            // Constructor shouldn't throw. But trying to instantiate the model binder provider will throw.\n            HttpConfiguration config = new HttpConfiguration();\n            ModelBinderAttribute attr = new ModelBinderAttribute(typeof(object));\n\n            Assert.Equal(typeof(object), attr.BinderType); // can still lookup illegal type\n            Assert.Throws<InvalidOperationException>(\n                () => attr.GetModelBinderProvider(config)\n            );\n        }\n\n        [Fact]\n        public void BinderType_Provided()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            ModelBinderAttribute attr = new ModelBinderAttribute(typeof(CustomModelBinderProvider));\n\n            ModelBinderProvider provider = attr.GetModelBinderProvider(config);\n            Assert.IsType<CustomModelBinderProvider>(provider);\n        }\n\n        [Fact]\n        public void BinderType_From_DependencyResolver()\n        {\n            // To test dependency resolver, the registered type and actual type should be different.\n            HttpConfiguration config = new HttpConfiguration();\n            var mockDependencyResolver = new Mock<IDependencyResolver>();\n            mockDependencyResolver.Setup(r => r.GetService(typeof(CustomModelBinderProvider)))\n                               .Returns(new SecondCustomModelBinderProvider());\n            config.DependencyResolver = mockDependencyResolver.Object;\n\n            ModelBinderAttribute attr = new ModelBinderAttribute(typeof(CustomModelBinderProvider));\n\n            ModelBinderProvider provider = attr.GetModelBinderProvider(config);\n            Assert.IsType<SecondCustomModelBinderProvider>(provider);\n        }\n\n        [Fact]\n        public void BinderType_From_DependencyResolver_ReleasedWhenConfigIsDisposed()\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            var mockDependencyResolver = new Mock<IDependencyResolver>();\n            SecondCustomModelBinderProvider provider = new SecondCustomModelBinderProvider();\n            mockDependencyResolver.Setup(r => r.GetService(typeof(CustomModelBinderProvider))).Returns(provider);\n            config.DependencyResolver = mockDependencyResolver.Object;\n\n            ModelBinderAttribute attr = new ModelBinderAttribute(typeof(CustomModelBinderProvider));\n            attr.GetModelBinderProvider(config);\n\n            // Act\n            config.Dispose();\n\n            // Assert\n            mockDependencyResolver.Verify(dr => dr.Dispose(), Times.Once());\n        }\n\n        [Fact]\n        public void Set_ModelBinder_And_ValueProviders()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            ModelBinderAttribute attr = new ValueProviderAttribute(typeof(CustomValueProviderFactory)) { BinderType = typeof(CustomModelBinderProvider) };\n            IEnumerable<ValueProviderFactory> vpfs = attr.GetValueProviderFactories(config);\n\n            Assert.IsType<CustomModelBinderProvider>(attr.GetModelBinderProvider(config));\n            object valueProviderFactory = Assert.Single(vpfs);\n            Assert.IsType<CustomValueProviderFactory>(valueProviderFactory);\n        }\n\n        [Fact]\n        public void Get_ModelBinder_From_Empty_Attribute()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Services.Replace(typeof(ModelBinderProvider), new CustomModelBinderProvider());\n\n            // binder = null, so pulls default from config. But attribute still has value by specifying the value providers.\n            ModelBinderAttribute attr = new ValueProviderAttribute(typeof(CustomValueProviderFactory));\n\n            // Act\n            IModelBinder binder = attr.GetModelBinder(config, null);\n\n            // Assert\n            Assert.Null(attr.BinderType); // using the default\n            Assert.NotNull(binder);\n            Assert.IsType<CustomModelBinder>(binder);\n        }\n\n        [Fact]\n        public void Get_ModelBinder_From_Binder()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            ModelBinderAttribute attr = new ModelBinderAttribute { BinderType = typeof(CustomModelBinder) };\n\n            // Act\n            IModelBinder binder = attr.GetModelBinder(config, null);\n\n            // Assert\n            Assert.NotNull(binder);\n            Assert.IsType<CustomModelBinder>(binder);\n        }\n\n        [Fact]\n        public void Get_ModelBinder_From_BinderProvider()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            ModelBinderAttribute attr = new ModelBinderAttribute { BinderType = typeof(CustomModelBinderProvider) };\n\n            // Act\n            IModelBinder binder = attr.GetModelBinder(config, null);\n\n            // Assert\n            Assert.NotNull(binder);\n            Assert.IsType<CustomModelBinder>(binder);\n        }\n\n        private class CustomModelBinderProvider : ModelBinderProvider\n        {\n            public override IModelBinder GetBinder(HttpConfiguration config, Type modelType)\n            {\n                return new CustomModelBinder();\n            }\n        }\n\n        private class CustomModelBinder : IModelBinder\n        {\n            public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)\n            {\n                return true;\n            }\n        }\n\n        private class SecondCustomModelBinderProvider : ModelBinderProvider\n        {\n            public override IModelBinder GetBinder(HttpConfiguration config, Type modelType)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class CustomValueProviderFactory : ValueProviderFactory\n        {\n            public override IValueProvider GetValueProvider(HttpActionContext actionContext)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/ModelBinderConfigTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata;\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.ModelBinding\n{\n    public class ModelBinderConfigTest\n    {\n        [Fact]\n        public void GetUserResourceString_NullControllerContext_ReturnsNull()\n        {\n            // Act\n            string customResourceString = ModelBinderConfig.GetUserResourceString(null /* controllerContext */, \"someResourceName\", \"someResourceClassKey\");\n\n            // Assert\n            Assert.Null(customResourceString);\n        }\n\n        [Fact]\n        public void TypeConversionErrorMessageProvider_DefaultValue()\n        {\n            // Arrange\n            ModelMetadata metadata = new ModelMetadata(new Mock<ModelMetadataProvider>().Object, null, null, typeof(int), \"SomePropertyName\");\n\n            // Act\n            string errorString = ModelBinderConfig.TypeConversionErrorMessageProvider(null, metadata, \"some incoming value\");\n\n            // Assert\n            Assert.Equal(\"The value 'some incoming value' is not valid for SomePropertyName.\", errorString);\n        }\n\n        [Fact]\n        public void TypeConversionErrorMessageProvider_Property()\n        {\n            // Arrange\n            ModelBinderConfigWrapper wrapper = new ModelBinderConfigWrapper();\n\n            // Act & assert\n            try\n            {\n                MemberHelper.TestPropertyWithDefaultInstance(wrapper, \"TypeConversionErrorMessageProvider\", (ModelBinderErrorMessageProvider)DummyErrorSelector);\n            }\n            finally\n            {\n                wrapper.Reset();\n            }\n        }\n\n        [Fact]\n        public void ValueRequiredErrorMessageProvider_DefaultValue()\n        {\n            // Arrange\n            ModelMetadata metadata = new ModelMetadata(new Mock<ModelMetadataProvider>().Object, null, null, typeof(int), \"SomePropertyName\");\n\n            // Act\n            string errorString = ModelBinderConfig.ValueRequiredErrorMessageProvider(null, metadata, \"some incoming value\");\n\n            // Assert\n            Assert.Equal(\"A value is required.\", errorString);\n        }\n\n        [Fact]\n        public void ValueRequiredErrorMessageProvider_Property()\n        {\n            // Arrange\n            ModelBinderConfigWrapper wrapper = new ModelBinderConfigWrapper();\n\n            // Act & assert\n            try\n            {\n                MemberHelper.TestPropertyWithDefaultInstance(wrapper, \"ValueRequiredErrorMessageProvider\", (ModelBinderErrorMessageProvider)DummyErrorSelector);\n            }\n            finally\n            {\n                wrapper.Reset();\n            }\n        }\n\n        private string DummyErrorSelector(HttpActionContext actionContext, ModelMetadata modelMetadata, object incomingValue)\n        {\n            throw new NotImplementedException();\n        }\n\n        private sealed class ModelBinderConfigWrapper\n        {\n            public ModelBinderErrorMessageProvider TypeConversionErrorMessageProvider\n            {\n                get { return ModelBinderConfig.TypeConversionErrorMessageProvider; }\n                set { ModelBinderConfig.TypeConversionErrorMessageProvider = value; }\n            }\n\n            public ModelBinderErrorMessageProvider ValueRequiredErrorMessageProvider\n            {\n                get { return ModelBinderConfig.ValueRequiredErrorMessageProvider; }\n                set { ModelBinderConfig.ValueRequiredErrorMessageProvider = value; }\n            }\n\n            public void Reset()\n            {\n                ModelBinderConfig.TypeConversionErrorMessageProvider = null;\n                ModelBinderConfig.ValueRequiredErrorMessageProvider = null;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/ModelBindingContextTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Metadata.Providers;\nusing System.Web.Http.Util;\nusing System.Web.Http.Validation;\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ModelBinding\n{\n    public class ModelBindingContextTest\n    {\n        [Fact]\n        public void CopyConstructor()\n        {\n            // Arrange\n            ModelBindingContext originalBindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(object)),\n                ModelName = \"theName\",\n                ModelState = new ModelStateDictionary(),\n                ValueProvider = new SimpleHttpValueProvider()\n            };\n\n            // Act\n            ModelBindingContext newBindingContext = new ModelBindingContext(originalBindingContext);\n\n            // Assert\n            Assert.Null(newBindingContext.ModelMetadata);\n            Assert.Equal(\"\", newBindingContext.ModelName);\n            Assert.Equal(originalBindingContext.ModelState, newBindingContext.ModelState);\n            Assert.Equal(originalBindingContext.ValueProvider, newBindingContext.ValueProvider);\n        }\n\n        [Fact]\n        public void ModelProperty()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int))\n            };\n\n            // Act & assert\n            MemberHelper.TestPropertyValue(bindingContext, \"Model\", 42);\n        }\n\n        [Fact]\n        public void ModelProperty_ThrowsIfModelMetadataDoesNotExist()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext();\n\n            // Act & assert\n            Assert.Throws<InvalidOperationException>(\n                () => bindingContext.Model = null,\n                \"The ModelMetadata property must be set before accessing this property.\");\n        }\n\n        [Fact]\n        public void ModelNameProperty()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext();\n\n            // Act & assert\n            Assert.Reflection.StringProperty(bindingContext, bc => bc.ModelName, String.Empty);\n        }\n\n        [Fact]\n        public void ModelStateProperty()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext();\n            ModelStateDictionary modelState = new ModelStateDictionary();\n\n            // Act & assert\n            MemberHelper.TestPropertyWithDefaultInstance(bindingContext, \"ModelState\", modelState);\n        }\n\n        [Fact]\n        public void ModelAndModelTypeAreFedFromModelMetadata()\n        {\n            // Act\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => 42, typeof(int))\n            };\n\n            // Assert\n            Assert.Equal(42, bindingContext.Model);\n            Assert.Equal(typeof(int), bindingContext.ModelType);\n        }\n\n        [Fact]\n        public void ValidationNodeProperty()\n        {\n            // Act\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => 42, typeof(int))\n            };\n\n            // Act & assert\n            MemberHelper.TestPropertyWithDefaultInstance(bindingContext, \"ValidationNode\", new ModelValidationNode(bindingContext.ModelMetadata, \"someName\"));\n        }\n\n        [Fact]\n        public void ValidationNodeProperty_DefaultValues()\n        {\n            // Act\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => 42, typeof(int)),\n                ModelName = \"theInt\"\n            };\n\n            // Act\n            ModelValidationNode validationNode = bindingContext.ValidationNode;\n\n            // Assert\n            Assert.NotNull(validationNode);\n            Assert.Equal(bindingContext.ModelMetadata, validationNode.ModelMetadata);\n            Assert.Equal(bindingContext.ModelName, validationNode.ModelStateKey);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/ModelBindingEndToEndTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Newtonsoft.Json;\n\nnamespace System.Web.Http.ModelBinding\n{\n    /// <summary>\n    /// End-to-end tests for model binding.\n    /// </summary>\n    public class ModelBindingEndToEndTests\n    {\n        [Fact]\n        public async Task BindModel_BindsValuesFromUrl()\n        {\n            // Arrange\n            string value = \"some-value\";\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get,\n                            \"http://localhost/ModelBinding/Url?somekey=\" + value);\n\n            // Act\n            HttpResponseMessage response = await SubmitRequestAsync(request);\n\n            // Assert\n            Assert.Equal(value, await ReadAsJson<string>(response));\n        }\n\n        [Fact]\n        public async Task BindModel_BindsSimpleTypesFromBody()\n        {\n            // Arrange\n            Dictionary<string, string> bodyParameters = new Dictionary<string, string>\n            {\n                { \"Name\", \"PersonName\" },\n                { \"Sibling.Name\", \"SiblingName\" },\n            };\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post,\n                            \"http://localhost/ModelBinding/SimpleType\")\n            {\n                Content = new FormUrlEncodedContent(bodyParameters)\n            };\n\n            // Act\n            HttpResponseMessage response = await SubmitRequestAsync(request);\n\n            // Assert\n            Person result = await ReadAsJson<Person>(response);\n            Assert.Equal(\"PersonName\", result.Name);\n            Assert.Equal(\"SiblingName\", result.Sibling.Name);\n        }\n\n        [Fact]\n        public async Task BindModel_WithCollection()\n        {\n            // Arrange\n            Dictionary<string, string> bodyParameters = new Dictionary<string, string>\n            {\n                { \"AddressLines[0].Line\", \"Street Address 0\" },\n                { \"AddressLines[1].Line\", \"Street Address 1\" },\n                { \"ZipCode\", \"98052\" },\n            };\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put,\n                            \"http://localhost/ModelBinding/CollectionType\")\n            {\n                Content = new FormUrlEncodedContent(bodyParameters)\n            };\n\n            // Act\n            HttpResponseMessage response = await SubmitRequestAsync(request);\n\n            // Assert\n            Address address = await ReadAsJson<Address>(response);\n            Assert.Equal(2, address.AddressLines.Count);\n            Assert.Equal(\"Street Address 0\", address.AddressLines[0].Line);\n            Assert.Equal(\"Street Address 1\", address.AddressLines[1].Line);\n            Assert.Equal(\"98052\", address.ZipCode);\n        }\n\n        [Fact]\n        public async Task BindModel_WithCollection_SpecifyingIndex()\n        {\n            // Arrange\n            IEnumerable<KeyValuePair<string, string>> bodyParameters = new[]\n            {\n                new KeyValuePair<string, string>(\"AddressLines.index\", \"3\"),\n                new KeyValuePair<string, string>(\"AddressLines.index\", \"10000\"),\n                new KeyValuePair<string, string>(\"AddressLines[3].Line\", \"Street Address 0\"),\n                new KeyValuePair<string, string>(\"AddressLines[10000].Line\", \"Street Address 1\"),\n            };\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put,\n                            \"http://localhost/ModelBinding/CollectionType\")\n            {\n                Content = new FormUrlEncodedContent(bodyParameters)\n            };\n\n            // Act\n            HttpResponseMessage response = await SubmitRequestAsync(request);\n\n            // Assert\n            Address address = await ReadAsJson<Address>(response);\n            Assert.Equal(2, address.AddressLines.Count);\n            Assert.Equal(\"Street Address 0\", address.AddressLines[0].Line);\n            Assert.Equal(\"Street Address 1\", address.AddressLines[1].Line);\n        }\n\n        [Fact]\n        public async Task BindModel_WithNestedCollection()\n        {\n            // Arrange\n            Dictionary<string, string> bodyParameters = new Dictionary<string, string>\n            {\n                { \"Addresses[0].AddressLines[0].Line\", \"Street Address 00\" },\n                { \"Addresses[0].AddressLines[1].Line\", \"Street Address 01\" },\n                { \"Addresses[0].ZipCode\", \"98052\" },\n                { \"Addresses[1].AddressLines[0].Line\", \"Street Address 10\" },\n                { \"Addresses[1].AddressLines[3].Line\", \"Street Address 13\" },\n            };\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post,\n                            \"http://localhost/ModelBinding/NestedCollection\")\n            {\n                Content = new FormUrlEncodedContent(bodyParameters)\n            };\n\n            // Act\n            HttpResponseMessage response = await SubmitRequestAsync(request);\n\n            // Assert\n            UserWithAddress result = await ReadAsJson<UserWithAddress>(response);\n            Assert.Equal(2, result.Addresses.Count);\n            Address address = result.Addresses[0];\n            Assert.Equal(2, address.AddressLines.Count);\n            Assert.Equal(\"Street Address 00\", address.AddressLines[0].Line);\n            Assert.Equal(\"Street Address 01\", address.AddressLines[1].Line);\n            Assert.Equal(\"98052\", address.ZipCode);\n\n            address = result.Addresses[1];\n            StreetAddress streetAddress= streetAddress = Assert.Single(address.AddressLines);\n            Assert.Equal(\"Street Address 10\", streetAddress.Line);\n            Assert.Null(address.ZipCode);\n        }\n\n        [Fact]\n        public async Task BindModel_WithIncorrectlyFormattedNestedCollectionValue()\n        {\n            // Arrange\n            Dictionary<string, string> bodyParameters = new Dictionary<string, string>\n            {\n                { \"Addresses\", \"Street Address 00\" },\n            };\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post,\n                            \"http://localhost/ModelBinding/NestedCollection\")\n            {\n                Content = new FormUrlEncodedContent(bodyParameters)\n            };\n\n            // Act\n            HttpResponseMessage response = await SubmitRequestAsync(request);\n\n            // Assert\n            UserWithAddress result = await ReadAsJson<UserWithAddress>(response);\n            Address address = Assert.Single(result.Addresses);\n            Assert.Null(address.AddressLines);\n            Assert.Null(address.ZipCode);\n        }\n\n        [Fact]\n        public async Task BindModel_WithNestedCollectionContainingARecursiveRelation()\n        {\n            // Arrange\n            Dictionary<string, string> bodyParameters = new Dictionary<string, string>\n            {\n                { \"People[0].Name\", \"Person 0\" },\n                { \"People[0].Sibling.Name\", \"Person 0 Sibling\" },\n                { \"People[1].Sibling.Name\", \"Person 1 Sibling\" },\n                { \"People[2].Sibling\", \"Person 2 Sibling\" },\n                { \"People[1000].Name\", \"Person 1000 Sibling\" },\n            };\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post,\n                            \"http://localhost/ModelBinding/NestedCollectionOfRecursiveTypes\")\n            {\n                Content = new FormUrlEncodedContent(bodyParameters)\n            };\n\n            // Act\n            HttpResponseMessage response = await SubmitRequestAsync(request);\n\n            // Assert\n            PeopleModel result = await ReadAsJson<PeopleModel>(response);\n            Assert.Equal(3, result.People.Count);\n            Person person = result.People[0];\n\n            Assert.Equal(\"Person 0\", person.Name);\n            Assert.Equal(\"Person 0 Sibling\", person.Sibling.Name);\n            Assert.Null(person.Sibling.Sibling);\n\n            person = result.People[1];\n            Assert.Equal(\"Person 1 Sibling\", person.Sibling.Name);\n            Assert.Null(person.Sibling.Sibling);\n\n            person = result.People[2];\n            Assert.Null(person.Name);\n            Assert.NotNull(person.Sibling);\n            Assert.Null(person.Sibling.Name);\n        }\n\n        [Fact]\n        public async Task BindModel_WithNestedCollectionContainingRecursiveRelation_WithMalformedValue()\n        {\n            // Arrange\n            Dictionary<string, string> bodyParameters = new Dictionary<string, string>\n            {\n                { \"People\", \"Person 0\" },\n            };\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post,\n                            \"http://localhost/ModelBinding/NestedCollectionOfRecursiveTypes\")\n            {\n                Content = new FormUrlEncodedContent(bodyParameters)\n            };\n\n            // Act\n            HttpResponseMessage response = await SubmitRequestAsync(request);\n\n            // Assert\n            PeopleModel result = await ReadAsJson<PeopleModel>(response);\n            Person person = Assert.Single(result.People);\n            Assert.Null(person.Name);\n            Assert.Null(person.Sibling);\n        }\n\n        private static async Task<HttpResponseMessage> SubmitRequestAsync(HttpRequestMessage request)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.MapHttpAttributeRoutes();\n            HttpServer server = new HttpServer(config);\n            using (HttpMessageInvoker client = new HttpMessageInvoker(server))\n            {\n                HttpResponseMessage response = await client.SendAsync(request, CancellationToken.None);\n                response.EnsureSuccessStatusCode();\n\n                return response;\n            }\n        }\n\n        private static async Task<TVal> ReadAsJson<TVal>(HttpResponseMessage response)\n        {\n            Assert.Equal(MediaTypeHeaderValue.Parse(\"application/json; charset=utf-8\"),\n                         response.Content.Headers.ContentType);\n            string content = await response.Content.ReadAsStringAsync();\n            return JsonConvert.DeserializeObject<TVal>(content);\n        }\n    }\n\n    [RoutePrefix(\"ModelBinding\")]\n    public class ModelBindingController : ApiController\n    {\n        [HttpGet]\n        [Route(\"Url\")]\n        public string UrlBinding([FromUri] string someKey)\n        {\n            return someKey;\n        }\n\n        [HttpPost]\n        [Route(\"SimpleType\")]\n        public Person SimpleType([FromBody] Person model)\n        {\n            return model;\n        }\n\n        [HttpPut]\n        [Route(\"CollectionType\")]\n        public Address CollectionType([FromBody] Address address)\n        {\n            return address;\n        }\n\n        [HttpPost]\n        [Route(\"NestedCollection\")]\n        public UserWithAddress NestedCollectionType([FromBody] UserWithAddress user)\n        {\n            return user;\n        }\n\n        [HttpPost]\n        [Route(\"NestedCollectionOfRecursiveTypes\")]\n        public PeopleModel NestedCollectionType([FromBody] PeopleModel model)\n        {\n            return model;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/ModelBindingUtilTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Metadata.Providers;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ModelBinding\n{\n    public class ModelBindingUtilTest\n    {\n        [Fact]\n        public void CastOrDefault_CorrectType_ReturnsInput()\n        {\n            // Act\n            int retVal = ModelBindingHelper.CastOrDefault<int>(42);\n\n            // Assert\n            Assert.Equal(42, retVal);\n        }\n\n        [Fact]\n        public void CastOrDefault_IncorrectType_ReturnsDefaultTModel()\n        {\n            // Act\n            DateTime retVal = ModelBindingHelper.CastOrDefault<DateTime>(42);\n\n            // Assert\n            Assert.Equal(default(DateTime), retVal);\n        }\n\n        [Fact]\n        public void CreateIndexModelName_EmptyParentName()\n        {\n            // Act\n            string fullChildName = ModelBindingHelper.CreateIndexModelName(\"\", 42);\n\n            // Assert\n            Assert.Equal(\"[42]\", fullChildName);\n        }\n\n        [Fact]\n        public void CreateIndexModelName_IntIndex()\n        {\n            // Act\n            string fullChildName = ModelBindingHelper.CreateIndexModelName(\"parentName\", 42);\n\n            // Assert\n            Assert.Equal(\"parentName[42]\", fullChildName);\n        }\n\n        [Fact]\n        public void CreateIndexModelName_StringIndex()\n        {\n            // Act\n            string fullChildName = ModelBindingHelper.CreateIndexModelName(\"parentName\", \"index\");\n\n            // Assert\n            Assert.Equal(\"parentName[index]\", fullChildName);\n        }\n\n        [Fact]\n        public void CreatePropertyModelName()\n        {\n            // Act\n            string fullChildName = ModelBindingHelper.CreatePropertyModelName(\"parentName\", \"childName\");\n\n            // Assert\n            Assert.Equal(\"parentName.childName\", fullChildName);\n        }\n\n        [Fact]\n        public void CreatePropertyModelName_EmptyParentName()\n        {\n            // Act\n            string fullChildName = ModelBindingHelper.CreatePropertyModelName(\"\", \"childName\");\n\n            // Assert\n            Assert.Equal(\"childName\", fullChildName);\n        }\n\n        [Fact]\n        public void GetPossibleBinderInstance_Match_ReturnsBinder()\n        {\n            // Act\n            IModelBinder binder = ModelBindingHelper.GetPossibleBinderInstance(typeof(List<int>), typeof(List<>), typeof(SampleGenericBinder<>));\n\n            // Assert\n            Assert.IsType<SampleGenericBinder<int>>(binder);\n        }\n\n        [Fact]\n        public void GetPossibleBinderInstance_NoMatch_ReturnsNull()\n        {\n            // Act\n            IModelBinder binder = ModelBindingHelper.GetPossibleBinderInstance(typeof(ArraySegment<int>), typeof(List<>), typeof(SampleGenericBinder<>));\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        [Fact]\n        public void RawValueToObjectArray_RawValueIsEnumerable_ReturnsInputAsArray()\n        {\n            // Assert\n            List<int> original = new List<int> { 1, 2, 3, 4 };\n\n            // Act\n            object[] retVal = ModelBindingHelper.RawValueToObjectArray(original);\n\n            // Assert\n            Assert.Equal(new object[] { 1, 2, 3, 4 }, retVal);\n        }\n\n        [Fact]\n        public void RawValueToObjectArray_RawValueIsObject_WrapsObjectInSingleElementArray()\n        {\n            // Act\n            object[] retVal = ModelBindingHelper.RawValueToObjectArray(42);\n\n            // Assert\n            Assert.Equal(new object[] { 42 }, retVal);\n        }\n\n        [Fact]\n        public void RawValueToObjectArray_RawValueIsObjectArray_ReturnsInputInstance()\n        {\n            // Assert\n            object[] original = new object[2];\n\n            // Act\n            object[] retVal = ModelBindingHelper.RawValueToObjectArray(original);\n\n            // Assert\n            Assert.Same(original, retVal);\n        }\n\n        [Fact]\n        public void RawValueToObjectArray_RawValueIsString_WrapsStringInSingleElementArray()\n        {\n            // Act\n            object[] retVal = ModelBindingHelper.RawValueToObjectArray(\"hello\");\n\n            // Assert\n            Assert.Equal(new object[] { \"hello\" }, retVal);\n        }\n\n        [Fact]\n        public void ReplaceEmptyStringWithNull_ConvertEmptyStringToNullDisabled_ModelIsEmptyString_LeavesModelAlone()\n        {\n            // Arrange\n            ModelMetadata modelMetadata = GetMetadata(typeof(string));\n            modelMetadata.ConvertEmptyStringToNull = false;\n\n            // Act\n            object model = \"\";\n            ModelBindingHelper.ReplaceEmptyStringWithNull(modelMetadata, ref model);\n\n            // Assert\n            Assert.Equal(\"\", model);\n        }\n\n        [Fact]\n        public void ReplaceEmptyStringWithNull_ConvertEmptyStringToNullEnabled_ModelIsEmptyString_ReplacesModelWithNull()\n        {\n            // Arrange\n            ModelMetadata modelMetadata = GetMetadata(typeof(string));\n            modelMetadata.ConvertEmptyStringToNull = true;\n\n            // Act\n            object model = \"\";\n            ModelBindingHelper.ReplaceEmptyStringWithNull(modelMetadata, ref model);\n\n            // Assert\n            Assert.Null(model);\n        }\n\n        [Fact]\n        public void ReplaceEmptyStringWithNull_ConvertEmptyStringToNullEnabled_ModelIsWhitespaceString_ReplacesModelWithNull()\n        {\n            // Arrange\n            ModelMetadata modelMetadata = GetMetadata(typeof(string));\n            modelMetadata.ConvertEmptyStringToNull = true;\n\n            // Act\n            object model = \"     \"; // whitespace\n            ModelBindingHelper.ReplaceEmptyStringWithNull(modelMetadata, ref model);\n\n            // Assert\n            Assert.Null(model);\n        }\n\n        [Fact]\n        public void ReplaceEmptyStringWithNull_ConvertEmptyStringToNullDisabled_ModelIsNotEmptyString_LeavesModelAlone()\n        {\n            // Arrange\n            ModelMetadata modelMetadata = GetMetadata(typeof(string));\n            modelMetadata.ConvertEmptyStringToNull = true;\n\n            // Act\n            object model = 42;\n            ModelBindingHelper.ReplaceEmptyStringWithNull(modelMetadata, ref model);\n\n            // Assert\n            Assert.Equal(42, model);\n        }\n\n        [Fact]\n        public void ValidateBindingContext_SuccessWithNonNullModel()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = GetMetadata(typeof(string))\n            };\n            bindingContext.ModelMetadata.Model = \"hello!\";\n\n            // Act\n            ModelBindingHelper.ValidateBindingContext(bindingContext, typeof(string), false);\n\n            // Assert\n            // Nothing to do - if we got this far without throwing, the test succeeded\n        }\n\n        [Fact]\n        public void ValidateBindingContext_SuccessWithNullModel()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = GetMetadata(typeof(string))\n            };\n\n            // Act\n            ModelBindingHelper.ValidateBindingContext(bindingContext, typeof(string), true);\n\n            // Assert\n            // Nothing to do - if we got this far without throwing, the test succeeded\n        }\n\n        [Fact]\n        public void ValidateBindingContextThrowsIfBindingContextIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                () => ModelBindingHelper.ValidateBindingContext(null, typeof(string), true),\n                \"bindingContext\");\n        }\n\n        [Fact]\n        public void ValidateBindingContextThrowsIfModelInstanceIsWrongType()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = GetMetadata(typeof(string))\n            };\n            bindingContext.ModelMetadata.Model = 42;\n\n            // Act & assert\n            Assert.ThrowsArgument(\n                () => ModelBindingHelper.ValidateBindingContext(bindingContext, typeof(string), allowNullModel: true),\n                \"bindingContext\",\n                \"The binding context has a Model of type 'System.Int32', but this binder can only operate on models of type 'System.String'.\");\n        }\n\n        [Fact]\n        public void ValidateBindingContextThrowsIfModelIsNullButCannotBe()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = GetMetadata(typeof(string))\n            };\n\n            // Act & assert\n            Assert.ThrowsArgument(\n                () => ModelBindingHelper.ValidateBindingContext(bindingContext, typeof(string), false),\n                \"bindingContext\",\n                \"The binding context has a null Model, but this binder requires a non-null model of type 'System.String'.\");\n        }\n\n        [Fact]\n        public void ValidateBindingContextThrowsIfModelMetadataIsNull()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext();\n\n            // Act & assert\n            Assert.ThrowsArgument(\n                () => ModelBindingHelper.ValidateBindingContext(bindingContext, typeof(string), true),\n                \"bindingContext\",\n                \"The binding context cannot have a null ModelMetadata.\");\n        }\n\n        [Fact]\n        public void ValidateBindingContextThrowsIfModelTypeIsWrong()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = GetMetadata(typeof(object))\n            };\n\n            // Act & assert\n            Assert.ThrowsArgument(\n                () => ModelBindingHelper.ValidateBindingContext(bindingContext, typeof(string), true),\n                \"bindingContext\",\n                \"The binding context has a ModelType of 'System.Object', but this binder can only operate on models of type 'System.String'.\");\n        }\n\n        private static ModelMetadata GetMetadata(Type modelType)\n        {\n            EmptyModelMetadataProvider provider = new EmptyModelMetadataProvider();\n            return provider.GetMetadataForType(null, modelType);\n        }\n\n        private class SampleGenericBinder<T> : IModelBinder\n        {\n            public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/ParameterBindingProvidersTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.ModelBinding\n{\n    public class ParameterBindingProvidersTest\n    {\n        [Fact]\n        public void AsCollection()\n        {\n            ParameterBindingRulesCollection pb = new ParameterBindingRulesCollection();\n\n            // Knowing that it's a collection means we have known behavior around \n            // the collection methods (like insert, add, clear, etc).\n            Assert.True(pb is Collection<Func<HttpParameterDescriptor, HttpParameterBinding>>);\n        }\n\n        [Fact]\n        public void Lookup_empty_collection_returns_null()\n        {\n            // The collection is empty,  so lookup will fail.\n            ParameterBindingRulesCollection pb = new ParameterBindingRulesCollection();\n            HttpParameterDescriptor parameter = CreateParameterDescriptor(typeof(object), \"none\");\n\n            // Act\n            HttpParameterBinding binding = pb.LookupBinding(parameter);\n\n            // Assert. \n            Assert.Null(binding);\n        }\n\n        [Fact]\n        public void Lookup_is_ordered()\n        {\n            ParameterBindingRulesCollection pb = new ParameterBindingRulesCollection();\n            HttpParameterBinding mockBinding1 = new EmptyParameterBinding();\n            HttpParameterBinding mockBinding2 = new EmptyParameterBinding();\n            HttpParameterBinding mockBinding3 = new EmptyParameterBinding();\n\n            pb.Add(param => param.ParameterName == \"first\" ? mockBinding1 : null);\n            pb.Add(param => param.ParameterName == \"first\" ? mockBinding2 : null);\n            pb.Add(param => param.ParameterType == typeof(int) ? mockBinding3 : null);\n\n            // Act\n            HttpParameterBinding b1 = pb.LookupBinding(CreateParameterDescriptor(null, \"first\"));\n            HttpParameterBinding b2 = pb.LookupBinding(CreateParameterDescriptor(typeof(string), \"none\"));\n            HttpParameterBinding b3 = pb.LookupBinding(CreateParameterDescriptor(typeof(int), \"first\"));\n            HttpParameterBinding b4 = pb.LookupBinding(CreateParameterDescriptor(typeof(int), \"last\"));\n\n\n            // Assert\n            Assert.Equal(mockBinding1, b1);\n            Assert.Null(b2);\n            Assert.Equal(mockBinding1, b3);\n            Assert.Equal(mockBinding3, b4);\n        }\n\n        [Fact]\n        public void Add_with_type_match()\n        {\n            ParameterBindingRulesCollection pb = new ParameterBindingRulesCollection();\n            HttpParameterBinding mockBinding = new EmptyParameterBinding();\n\n            pb.Add(typeof(string), param => mockBinding);\n\n            // Act\n            HttpParameterBinding b1 = pb.LookupBinding(CreateParameterDescriptor(typeof(string), \"first\"));\n            HttpParameterBinding b2 = pb.LookupBinding(CreateParameterDescriptor(typeof(int), \"first\"));\n\n            // Assert\n            Assert.Equal(mockBinding, b1);\n            Assert.Null(b2); // doesn't match type, misses.\n        }\n\n        [Fact]\n        public void type_match_user_function_not_invoked_if_type_doesnt_match()\n        {\n            ParameterBindingRulesCollection pb = new ParameterBindingRulesCollection();\n            HttpParameterBinding mockBinding = new EmptyParameterBinding();\n\n            pb.Add(typeof(string), param => { throw new InvalidOperationException(\"shouldn't be called\"); });\n            pb.Insert(0, typeof(string), param => { throw new InvalidOperationException(\"shouldn't be called\"); });\n\n            // Act\n            HttpParameterBinding b2 = pb.LookupBinding(CreateParameterDescriptor(typeof(int), \"first\"));\n\n            // Assert - made it through the action without throwing.\n        }\n\n        [Fact]\n        public void Insert_with_type_match()\n        {\n            ParameterBindingRulesCollection pb = new ParameterBindingRulesCollection();\n            HttpParameterBinding mockBinding1 = new EmptyParameterBinding();\n            HttpParameterBinding mockBinding2 = new EmptyParameterBinding();\n            HttpParameterBinding mockBinding3 = new EmptyParameterBinding();\n\n            // Act, test insertion            \n            pb.Add(typeof(string), param => mockBinding2);\n            pb.Add(typeof(int), param => mockBinding2);\n            pb.Insert(0, typeof(string), param => mockBinding1);\n            pb.Insert(2, typeof(int), param => mockBinding3); // goes in middle\n\n            // Assert via lookups\n            Assert.Equal(mockBinding1, pb.LookupBinding(CreateParameterDescriptor(typeof(string), \"first\")));\n            Assert.Equal(mockBinding3, pb.LookupBinding(CreateParameterDescriptor(typeof(int), \"first\")));            \n        }\n\n        // For unit testing purposes, just create a unique binding objet. \n        // We'll just compare object reference identity to determine if binds give the expected binding back.\n        // ParameterDescriptor is ignored.\n        private class EmptyParameterBinding : HttpParameterBinding\n        {\n            public EmptyParameterBinding()\n                : base(CreateParameterDescriptor(typeof(object), \"dummy\"))\n            { \n            }\n\n            public override Threading.Tasks.Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, Threading.CancellationToken cancellationToken)\n            {\n                throw new NotImplementedException();\n            }\n        }\n        \n        private static HttpParameterDescriptor CreateParameterDescriptor(Type type, string name)\n        {\n            Mock<HttpParameterDescriptor> mock = new Mock<HttpParameterDescriptor>();\n            mock.Setup(p => p.ParameterType).Returns(type);\n            mock.Setup(p => p.ParameterName).Returns(name);\n            return mock.Object;\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/SharedModels/Address.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Http.ModelBinding\n{\n    public class Address\n    {\n        public List<StreetAddress> AddressLines { get; set; }\n\n        public string ZipCode { get; set; }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/SharedModels/PeopleModel.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Http.ModelBinding\n{\n    public class PeopleModel\n    {\n        public List<Person> People { get; set; }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/SharedModels/Person.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.ModelBinding\n{\n    public class Person\n    {\n        public Person Sibling { get; set; }\n\n        public string Name { get; set; }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/SharedModels/StreetAddress.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Http.ModelBinding\n{\n    public class StreetAddress\n    {\n        public string Line { get; set; }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ModelBinding/SharedModels/User.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Http.ModelBinding\n{\n    public class UserWithAddress\n    {\n        public List<Address> Addresses { get; set; }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Properties/AssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\n\n[assembly: CLSCompliant(false)]\n"
  },
  {
    "path": "test/System.Web.Http.Test/Resources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.18033\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace System.Web.Http {\n    using System;\n    \n    \n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    public class Resources {\n        \n        private static global::System.Resources.ResourceManager resourceMan;\n        \n        private static global::System.Globalization.CultureInfo resourceCulture;\n        \n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal Resources() {\n        }\n        \n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        public static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"System.Web.Http.Resources\", typeof(Resources).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n        \n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        public static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Localized Value.\n        /// </summary>\n        public static string String1 {\n            get {\n                return ResourceManager.GetString(\"String1\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Resources.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"String1\" xml:space=\"preserve\">\n    <value>Localized Value</value>\n  </data>\n</root>"
  },
  {
    "path": "test/System.Web.Http.Test/Results/BadRequestErrorMessageResultTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq.Expressions;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Results\n{\n    public class BadRequestErrorMessageResultTests\n    {\n        [Fact]\n        public void Constructor_Throws_WhenMessageIsNull()\n        {\n            // Arrange\n            string message = null;\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() =>\n                {\n                    CreateProductUnderTest(message, contentNegotiator, request, formatters);\n                }, \"message\");\n            }\n        }\n\n        [Fact]\n        public void Constructor_Throws_WhenContentNegotiatorIsNull()\n        {\n            // Arrange\n            string message = CreateMessage();\n            IContentNegotiator contentNegotiator = null;\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() =>\n                {\n                    CreateProductUnderTest(message, contentNegotiator, request, formatters);\n                }, \"contentNegotiator\");\n            }\n        }\n\n        [Fact]\n        public void Constructor_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            string message = CreateMessage();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n            HttpRequestMessage request = null;\n            IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() =>\n            {\n                CreateProductUnderTest(message, contentNegotiator, request, formatters);\n            }, \"request\");\n        }\n\n        [Fact]\n        public void Constructor_Throws_WhenFormattersIsNull()\n        {\n            // Arrange\n            string message = CreateMessage();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = null;\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() =>\n                {\n                    CreateProductUnderTest(message, contentNegotiator, request, formatters);\n                }, \"formatters\");\n            }\n        }\n\n        [Fact]\n        public void Message_ReturnsInstanceProvided()\n        {\n            // Arrange\n            string expectedMessage = CreateMessage();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                BadRequestErrorMessageResult result = CreateProductUnderTest(expectedMessage, contentNegotiator,\n                    request, formatters);\n\n                // Act\n                string message = result.Message;\n\n                // Assert\n                Assert.Same(expectedMessage, message);\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ReturnsInstanceProvided()\n        {\n            // Arrange\n            string message = CreateMessage();\n            IContentNegotiator expectedContentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                BadRequestErrorMessageResult result = CreateProductUnderTest(message, expectedContentNegotiator,\n                    request, formatters);\n\n                // Act\n                IContentNegotiator contentNegotiator = result.ContentNegotiator;\n\n                // Assert\n                Assert.Same(expectedContentNegotiator, contentNegotiator);\n            }\n        }\n\n        [Fact]\n        public void Request_ReturnsInstanceProvided()\n        {\n            // Arrange\n            string message = CreateMessage();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                BadRequestErrorMessageResult result = CreateProductUnderTest(message, contentNegotiator,\n                    expectedRequest, formatters);\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public void Formatters_ReturnsInstanceProvided()\n        {\n            // Arrange\n            string message = CreateMessage();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();\n\n                BadRequestErrorMessageResult result = CreateProductUnderTest(message, contentNegotiator, request,\n                    expectedFormatters);\n\n                // Act\n                IEnumerable<MediaTypeFormatter> formatters = result.Formatters;\n\n                // Assert\n                Assert.Same(expectedFormatters, formatters);\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_ReturnsCorrectResponse_WhenContentNegotiationSucceeds()\n        {\n            // Arrange\n            string expectedMessage = CreateMessage();\n            MediaTypeFormatter expectedFormatter = CreateFormatter();\n            MediaTypeHeaderValue expectedMediaType = CreateMediaType();\n            ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedFormatter,\n                expectedMediaType);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();\n\n                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();\n                spy.Setup(n => n.Negotiate(typeof(HttpError), expectedRequest, expectedFormatters)).Returns(\n                    negotiationResult);\n                IContentNegotiator contentNegotiator = spy.Object;\n\n                IHttpActionResult result = CreateProductUnderTest(expectedMessage, contentNegotiator, expectedRequest,\n                    expectedFormatters);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);\n                    HttpContent content = response.Content;\n                    ObjectContent<HttpError> typedContent = Assert.IsType<ObjectContent<HttpError>>(content);\n                    HttpError error = (HttpError)typedContent.Value;\n                    Assert.NotNull(error);\n                    Assert.Same(expectedMessage, error.Message);\n                    Assert.Same(expectedFormatter, typedContent.Formatter);\n                    Assert.NotNull(typedContent.Headers);\n                    Assert.Equal(expectedMediaType, typedContent.Headers.ContentType);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_ReturnsCorrectResponse_WhenContentNegotiationFails()\n        {\n            // Arrange\n            string message = CreateMessage();\n            ContentNegotiationResult negotiationResult = null;\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();\n\n                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();\n                spy.Setup(n => n.Negotiate(typeof(HttpError), expectedRequest, expectedFormatters)).Returns(\n                    negotiationResult);\n                IContentNegotiator contentNegotiator = spy.Object;\n\n                IHttpActionResult result = CreateProductUnderTest(message, contentNegotiator, expectedRequest,\n                    expectedFormatters);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public void Constructor_ForApiController_Throws_WhenControllerIsNull()\n        {\n            // Arrange\n            string message = CreateMessage();\n            ApiController controller = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { CreateProductUnderTest(message, controller); }, \"controller\");\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_ForApiController_ReturnsCorrectResponse_WhenContentNegotationSucceeds()\n        {\n            // Arrange\n            string expectedMessage = CreateMessage();\n            ApiController controller = CreateController();\n            MediaTypeFormatter expectedInputFormatter = CreateFormatter();\n            MediaTypeFormatter expectedOutputFormatter = CreateFormatter();\n            MediaTypeHeaderValue expectedMediaType = CreateMediaType();\n            ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedOutputFormatter,\n                expectedMediaType);\n\n            Expression<Func<IEnumerable<MediaTypeFormatter>, bool>> formattersMatch = (f) =>\n                f != null && f.AsArray().Length == 1 && f.AsArray()[0] == expectedInputFormatter;\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();\n                spy.Setup(n => n.Negotiate(typeof(HttpError), expectedRequest, It.Is(formattersMatch))).Returns(\n                    negotiationResult);\n                IContentNegotiator contentNegotiator = spy.Object;\n\n                using (HttpConfiguration configuration = CreateConfiguration(expectedInputFormatter,\n                    contentNegotiator))\n                {\n                    configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;\n                    controller.Configuration = configuration;\n                    controller.Request = expectedRequest;\n\n                    IHttpActionResult result = CreateProductUnderTest(expectedMessage, controller);\n\n                    // Act\n                    Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                    // Assert\n                    Assert.NotNull(task);\n\n                    using (HttpResponseMessage response = await task)\n                    {\n                        Assert.NotNull(response);\n                        Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);\n                        HttpContent content = response.Content;\n                        ObjectContent<HttpError> typedContent = Assert.IsType<ObjectContent<HttpError>>(content);\n                        HttpError error = (HttpError)typedContent.Value;\n                        Assert.NotNull(error);\n                        Assert.Same(expectedMessage, error.Message);\n                        Assert.NotNull(typedContent.Headers);\n                        Assert.Equal(expectedMediaType, typedContent.Headers.ContentType);\n                        Assert.Same(expectedRequest, response.RequestMessage);\n                    }\n                }\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            string message = CreateMessage();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            {\n                controller.Configuration = configuration;\n\n                using (HttpRequestMessage request = CreateRequest())\n                {\n                    controller.Request = request;\n\n                    BadRequestErrorMessageResult result = CreateProductUnderTest(message, controller);\n\n                    IContentNegotiator expectedContentNegotiator = CreateDummyContentNegotiator();\n                    configuration.Services.Replace(typeof(IContentNegotiator), expectedContentNegotiator);\n\n                    // Act\n                    IContentNegotiator contentNegotiator = result.ContentNegotiator;\n\n                    // Assert\n                    Assert.Same(expectedContentNegotiator, contentNegotiator);\n                }\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            string message = CreateMessage();\n            MediaTypeFormatter formatter = CreateFormatter();\n            MediaTypeHeaderValue mediaType = CreateMediaType();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            {\n                controller.Configuration = configuration;\n                BadRequestErrorMessageResult result = CreateProductUnderTest(message, controller);\n\n                using (HttpRequestMessage expectedRequest = CreateRequest())\n                {\n                    controller.Request = expectedRequest;\n\n                    // Act\n                    HttpRequestMessage request = result.Request;\n\n                    // Assert\n                    Assert.Same(expectedRequest, request);\n                }\n            }\n        }\n\n        [Fact]\n        public void Formatters_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            string message = CreateMessage();\n            ApiController controller = CreateController();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpConfiguration earlyConfiguration = CreateConfiguration(CreateFormatter(), contentNegotiator))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Configuration = earlyConfiguration;\n                controller.Request = request;\n\n                BadRequestErrorMessageResult result = CreateProductUnderTest(message, controller);\n\n                MediaTypeFormatter expectedFormatter = CreateFormatter();\n\n                using (HttpConfiguration lateConfiguration = CreateConfiguration(expectedFormatter, contentNegotiator))\n                {\n                    controller.Configuration = lateConfiguration;\n\n                    // Act\n                    IEnumerable<MediaTypeFormatter> formatters = result.Formatters;\n\n                    // Assert\n                    Assert.NotNull(formatters);\n                    MediaTypeFormatter formatter = Assert.Single(formatters);\n                    Assert.Same(expectedFormatter, formatter);\n                }\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            string message = CreateMessage();\n            IContentNegotiator expectedContentNegotiator = CreateDummyContentNegotiator();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), expectedContentNegotiator))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Configuration = configuration;\n                controller.Request = request;\n\n                BadRequestErrorMessageResult result = CreateProductUnderTest(message, controller);\n\n                IContentNegotiator ignore = result.ContentNegotiator;\n\n                configuration.Services.Replace(typeof(IContentNegotiator), CreateDummyContentNegotiator());\n\n                // Act\n                IContentNegotiator contentNegotiator = result.ContentNegotiator;\n\n                // Assert\n                Assert.Same(expectedContentNegotiator, contentNegotiator);\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            string message = CreateMessage();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            {\n                controller.Configuration = configuration;\n\n                BadRequestErrorMessageResult result = CreateProductUnderTest(message, controller);\n\n                using (HttpRequestMessage expectedRequest = CreateRequest())\n                {\n                    controller.Request = expectedRequest;\n                    HttpRequestMessage ignore = result.Request;\n\n                    using (HttpRequestMessage otherRequest = CreateRequest())\n                    {\n                        controller.Request = otherRequest;\n\n                        // Act\n                        HttpRequestMessage request = result.Request;\n\n                        // Assert\n                        Assert.Same(expectedRequest, request);\n                    }\n                }\n            }\n        }\n\n        [Fact]\n        public void Formatters_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            string message = CreateMessage();\n            ApiController controller = CreateController();\n            MediaTypeFormatter expectedFormatter = CreateFormatter();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpConfiguration earlyConfiguration = CreateConfiguration(expectedFormatter, contentNegotiator))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Configuration = earlyConfiguration;\n                controller.Request = request;\n\n                BadRequestErrorMessageResult result = CreateProductUnderTest(message, controller);\n\n                IEnumerable<MediaTypeFormatter> ignore = result.Formatters;\n\n                using (HttpConfiguration lateConfiguration = CreateConfiguration(CreateFormatter(), contentNegotiator))\n                {\n                    controller.Configuration = lateConfiguration;\n\n                    // Act\n                    IEnumerable<MediaTypeFormatter> formatters = result.Formatters;\n\n                    // Assert\n                    Assert.NotNull(formatters);\n                    MediaTypeFormatter formatter = Assert.Single(formatters);\n                    Assert.Same(expectedFormatter, formatter);\n                }\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ForApiController_Throws_WhenConfigurationIsNull()\n        {\n            // Arrange\n            string message = CreateMessage();\n            ApiController controller = CreateController();\n            HttpControllerContext context = new HttpControllerContext();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.ControllerContext = context;\n\n                BadRequestErrorMessageResult result = CreateProductUnderTest(message, controller);\n\n                // Act & Assert\n                Assert.Throws<InvalidOperationException>(\n                    () => { IContentNegotiator ignore = result.ContentNegotiator; },\n                    \"HttpControllerContext.Configuration must not be null.\");\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ForApiController_Throws_WhenServiceIsNull()\n        {\n            // Arrange\n            string message = CreateMessage();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), null))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Request = request;\n                controller.Configuration = configuration;\n\n                BadRequestErrorMessageResult result = CreateProductUnderTest(message, controller);\n\n                // Act & Assert\n                Assert.Throws<InvalidOperationException>(\n                    () => { IContentNegotiator ignore = result.ContentNegotiator; },\n                    \"The provided configuration does not have an instance of the \" +\n                    \"'System.Net.Http.Formatting.IContentNegotiator' service registered.\");\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_Throws_WhenControllerRequestIsNull()\n        {\n            // Arrange\n            string message = CreateMessage();\n            ApiController controller = CreateController();\n            Assert.Null(controller.Request);\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            {\n                controller.Configuration = configuration;\n                BadRequestErrorMessageResult result = CreateProductUnderTest(message, controller);\n\n                // Act & Assert\n                InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() =>\n                { HttpRequestMessage ignore = result.Request; }, \"ApiController.Request must not be null.\");\n            }\n        }\n\n        [Fact]\n        public void ApiControllerBadRequest_WithString_CreatesCorrectResult()\n        {\n            // Arrange\n            string expectedMessage = CreateMessage();\n            ApiController controller = CreateController();\n\n            // Act\n            BadRequestErrorMessageResult result = controller.BadRequest(expectedMessage);\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Same(expectedMessage, result.Message);\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Configuration = configuration;\n                controller.Request = expectedRequest;\n                Assert.Same(expectedRequest, result.Request);\n            }\n        }\n\n        private static HttpConfiguration CreateConfiguration(MediaTypeFormatter formatter,\n            IContentNegotiator contentNegotiator)\n        {\n            HttpConfiguration configuration = new HttpConfiguration();\n            configuration.Formatters.Clear();\n            configuration.Formatters.Add(formatter);\n            configuration.Services.Replace(typeof(IContentNegotiator), contentNegotiator);\n            return configuration;\n        }\n\n        private static ApiController CreateController()\n        {\n            return new FakeController();\n        }\n\n        private static IContentNegotiator CreateDummyContentNegotiator()\n        {\n            return new Mock<IContentNegotiator>(MockBehavior.Strict).Object;\n        }\n\n        private static MediaTypeFormatter CreateFormatter()\n        {\n            return new StubMediaTypeFormatter();\n        }\n\n        private static IEnumerable<MediaTypeFormatter> CreateFormatters()\n        {\n            return new MediaTypeFormatter[0];\n        }\n\n        private static MediaTypeHeaderValue CreateMediaType()\n        {\n            return new MediaTypeHeaderValue(\"text/plain\");\n        }\n\n        private static string CreateMessage()\n        {\n            return \"IgnoreMessage\";\n        }\n\n        private static BadRequestErrorMessageResult CreateProductUnderTest(string message,\n            IContentNegotiator contentNegotiator, HttpRequestMessage request,\n            IEnumerable<MediaTypeFormatter> formatters)\n        {\n            return new BadRequestErrorMessageResult(message, contentNegotiator, request, formatters);\n        }\n\n        private static BadRequestErrorMessageResult CreateProductUnderTest(string message, ApiController controller)\n        {\n            return new BadRequestErrorMessageResult(message, controller);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private class StubMediaTypeFormatter : MediaTypeFormatter\n        {\n            public override bool CanReadType(Type type)\n            {\n                return true;\n            }\n\n            public override bool CanWriteType(Type type)\n            {\n                return true;\n            }\n        }\n\n        private class FakeController : ApiController\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Results/BadRequestResultTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Results\n{\n    public class BadRequestResultTests\n    {\n        [Fact]\n        public void Constructor_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            HttpRequestMessage request = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { CreateProductUnderTest(request); }, \"request\");\n        }\n\n        [Fact]\n        public void Request_Returns_InstanceProvided()\n        {\n            // Arrange\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                BadRequestResult result = CreateProductUnderTest(expectedRequest);\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Returns_CorrectResponse()\n        {\n            // Arrange\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IHttpActionResult result = CreateProductUnderTest(expectedRequest);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public void Constructor_ForApiController_Throws_WhenControllerIsNull()\n        {\n            // Arrange\n            ApiController controller = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { CreateProductUnderTest(controller); }, \"controller\");\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_ForApiController_ReturnsCorrectResponse()\n        {\n            // Arrange\n            ApiController controller = CreateController();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                IHttpActionResult result = CreateProductUnderTest(controller);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            ApiController controller = CreateController();\n            BadRequestResult result = CreateProductUnderTest(controller);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            ApiController controller = CreateController();\n            BadRequestResult result = CreateProductUnderTest(controller);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                HttpRequestMessage ignore = result.Request;\n\n                using (HttpRequestMessage otherRequest = CreateRequest())\n                {\n                    controller.Request = otherRequest;\n\n                    // Act\n                    HttpRequestMessage request = result.Request;\n\n                    // Assert\n                    Assert.Same(expectedRequest, request);\n                }\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_Throws_WhenControllerRequestIsNull()\n        {\n            // Arrange\n            ApiController controller = CreateController();\n            Assert.Null(controller.Request);\n            BadRequestResult result = CreateProductUnderTest(controller);\n\n            // Act & Assert\n            InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() =>\n                { HttpRequestMessage ignore = result.Request; }, \"ApiController.Request must not be null.\");\n        }\n\n        [Fact]\n        public void ApiControllerBadRequest_CreatesCorrectResult()\n        {\n            // Arrange\n            ApiController controller = CreateController();\n\n            // Act\n            BadRequestResult result = controller.BadRequest();\n\n            // Assert\n            Assert.NotNull(result);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                Assert.Same(expectedRequest, result.Request);\n            }\n        }\n\n        private static ApiController CreateController()\n        {\n            return new FakeController();\n        }\n\n        private static BadRequestResult CreateProductUnderTest(HttpRequestMessage request)\n        {\n            return new BadRequestResult(request);\n        }\n\n        private static BadRequestResult CreateProductUnderTest(ApiController controller)\n        {\n            return new BadRequestResult(controller);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private class FakeController : ApiController\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Results/ConflictResultTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Results\n{\n    public class ConflictResultTests\n    {\n        [Fact]\n        public void Constructor_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            HttpRequestMessage request = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { CreateProductUnderTest(request); }, \"request\");\n        }\n\n        [Fact]\n        public void Request_Returns_InstanceProvided()\n        {\n            // Arrange\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                ConflictResult result = CreateProductUnderTest(expectedRequest);\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Returns_CorrectResponse()\n        {\n            // Arrange\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IHttpActionResult result = CreateProductUnderTest(expectedRequest);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public void Constructor_ForApiController_Throws_WhenControllerIsNull()\n        {\n            // Arrange\n            ApiController controller = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { CreateProductUnderTest(controller); }, \"controller\");\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_ForApiController_ReturnsCorrectResponse()\n        {\n            // Arrange\n            ApiController controller = CreateController();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                IHttpActionResult result = CreateProductUnderTest(controller);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            ApiController controller = CreateController();\n            ConflictResult result = CreateProductUnderTest(controller);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            ApiController controller = CreateController();\n            ConflictResult result = CreateProductUnderTest(controller);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                HttpRequestMessage ignore = result.Request;\n\n                using (HttpRequestMessage otherRequest = CreateRequest())\n                {\n                    controller.Request = otherRequest;\n\n                    // Act\n                    HttpRequestMessage request = result.Request;\n\n                    // Assert\n                    Assert.Same(expectedRequest, request);\n                }\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_Throws_WhenControllerRequestIsNull()\n        {\n            // Arrange\n            ApiController controller = CreateController();\n            Assert.Null(controller.Request);\n            ConflictResult result = CreateProductUnderTest(controller);\n\n            // Act & Assert\n            InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() =>\n                { HttpRequestMessage ignore = result.Request; }, \"ApiController.Request must not be null.\");\n        }\n\n        [Fact]\n        public void ApiControllerConflict_CreatesCorrectResult()\n        {\n            // Arrange\n            ApiController controller = CreateController();\n\n            // Act\n            ConflictResult result = controller.Conflict();\n\n            // Assert\n            Assert.NotNull(result);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                Assert.Same(expectedRequest, result.Request);\n            }\n        }\n\n        private static ApiController CreateController()\n        {\n            return new FakeController();\n        }\n\n        private static ConflictResult CreateProductUnderTest(HttpRequestMessage request)\n        {\n            return new ConflictResult(request);\n        }\n\n        private static ConflictResult CreateProductUnderTest(ApiController controller)\n        {\n            return new ConflictResult(controller);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private class FakeController : ApiController\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Results/CreatedAtRouteNegotiatedContentResultTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq.Expressions;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Results\n{\n    public class CreatedAtRouteNegotiatedContentResultTests\n    {\n        [Fact]\n        public void Constructor_Throws_WhenRouteNameIsNull()\n        {\n            // Arrange\n            string routeName = null;\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            object content = CreateContent();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n            UrlHelper urlFactory = CreateDummyUrlFactory();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() =>\n                {\n                    CreateProductUnderTest(routeName, routeValues, content, urlFactory, contentNegotiator, request,\n                        formatters);\n                }, \"routeName\");\n            }\n        }\n\n        [Fact]\n        public void Constructor_Throws_WhenUrlFactoryIsNull()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            object content = CreateContent();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n            UrlHelper urlFactory = null;\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() =>\n                {\n                    CreateProductUnderTest(routeName, routeValues, content, urlFactory, contentNegotiator, request,\n                        formatters);\n                }, \"urlFactory\");\n            }\n        }\n\n        [Fact]\n        public void Constructor_Throws_WhenContentNegotiatorIsNull()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            object content = CreateContent();\n            UrlHelper urlFactory = CreateDummyUrlFactory();\n            IContentNegotiator contentNegotiator = null;\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() =>\n                {\n                    CreateProductUnderTest(routeName, routeValues, content, urlFactory, contentNegotiator, request,\n                        formatters);\n                }, \"contentNegotiator\");\n            }\n        }\n\n        [Fact]\n        public void Constructor_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            object content = CreateContent();\n            UrlHelper urlFactory = CreateDummyUrlFactory();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n            HttpRequestMessage request = null;\n            IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() =>\n            {\n                CreateProductUnderTest(routeName, routeValues, content, urlFactory, contentNegotiator, request,\n                    formatters);\n            }, \"request\");\n        }\n\n        [Fact]\n        public void Constructor_Throws_WhenFormattersIsNull()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            object content = CreateContent();\n            UrlHelper urlFactory = CreateDummyUrlFactory();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = null;\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() =>\n                {\n                    CreateProductUnderTest(routeName, routeValues, content, urlFactory, contentNegotiator, request,\n                        formatters);\n                }, \"formatters\");\n            }\n        }\n\n        [Fact]\n        public void RouteName_Returns_InstanceProvided()\n        {\n            // Arrange\n            string expectedRouteName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            object content = CreateContent();\n            UrlHelper urlFactory = CreateDummyUrlFactory();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                CreatedAtRouteNegotiatedContentResult<object> result = CreateProductUnderTest(expectedRouteName,\n                    routeValues, content, urlFactory, contentNegotiator, request, formatters);\n\n                // Act\n                string routeName = result.RouteName;\n\n                // Assert\n                Assert.Same(expectedRouteName, routeName);\n            }\n        }\n\n        [Fact]\n        public void RouteValues_Returns_InstanceProvided()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> expectedRouteValues = CreateRouteValues();\n            object content = CreateContent();\n            UrlHelper urlFactory = CreateDummyUrlFactory();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                CreatedAtRouteNegotiatedContentResult<object> result = CreateProductUnderTest(routeName,\n                    expectedRouteValues, content, urlFactory, contentNegotiator, request, formatters);\n\n                // Act\n                IDictionary<string, object> routeValues = result.RouteValues;\n\n                // Assert\n                Assert.Same(expectedRouteValues, routeValues);\n            }\n        }\n\n        [Fact]\n        public void Content_Returns_InstanceProvided()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            object expectedContent = CreateContent();\n            UrlHelper urlFactory = CreateDummyUrlFactory();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                CreatedAtRouteNegotiatedContentResult<object> result = CreateProductUnderTest(routeName, routeValues,\n                    expectedContent, urlFactory, contentNegotiator, request, formatters);\n\n                // Act\n                object content = result.Content;\n\n                // Assert\n                Assert.Same(expectedContent, content);\n            }\n        }\n\n        [Fact]\n        public void UrlFactory_Returns_InstanceProvided()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            object content = CreateContent();\n            UrlHelper expectedUrlFactory = CreateDummyUrlFactory();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                CreatedAtRouteNegotiatedContentResult<object> result = CreateProductUnderTest(routeName, routeValues,\n                    content, expectedUrlFactory, contentNegotiator, request, formatters);\n\n                // Act\n                UrlHelper urlFactory = result.UrlFactory;\n\n                // Assert\n                Assert.Same(expectedUrlFactory, urlFactory);\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_Returns_InstanceProvided()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            object content = CreateContent();\n            UrlHelper urlFactory = CreateDummyUrlFactory();\n            IContentNegotiator expectedContentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                CreatedAtRouteNegotiatedContentResult<object> result = CreateProductUnderTest(routeName, routeValues,\n                    content, urlFactory, expectedContentNegotiator, request, formatters);\n\n                // Act\n                IContentNegotiator contentNegotiator = result.ContentNegotiator;\n\n                // Assert\n                Assert.Same(expectedContentNegotiator, contentNegotiator);\n            }\n        }\n\n        [Fact]\n        public void Request_Returns_InstanceProvided()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            object content = CreateContent();\n            UrlHelper urlFactory = CreateDummyUrlFactory();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                CreatedAtRouteNegotiatedContentResult<object> result = CreateProductUnderTest(routeName, routeValues,\n                    content, urlFactory, contentNegotiator, expectedRequest, formatters);\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public void Formatters_Returns_InstanceProvided()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            object content = CreateContent();\n            UrlHelper urlFactory = CreateDummyUrlFactory();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();\n\n                CreatedAtRouteNegotiatedContentResult<object> result = CreateProductUnderTest(routeName, routeValues,\n                    content, urlFactory, contentNegotiator, request, expectedFormatters);\n\n                // Act\n                IEnumerable<MediaTypeFormatter> formatters = result.Formatters;\n\n                // Assert\n                Assert.Same(expectedFormatters, formatters);\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Returns_CorrectResponse_WhenContentNegotiationSucceeds()\n        {\n            // Arrange\n            string expectedRouteName = CreateRouteName();\n            IDictionary<string, object> expectedRouteValues = CreateRouteValues();\n            object expectedContent = CreateContent();\n            Mock<UrlHelper> spyUrlFactory = new Mock<UrlHelper>(MockBehavior.Strict);\n            string expectedLocation = CreateLocation().AbsoluteUri;\n            spyUrlFactory.Setup(f => f.Link(expectedRouteName, expectedRouteValues)).Returns(expectedLocation);\n            UrlHelper urlFactory = spyUrlFactory.Object;\n            MediaTypeFormatter expectedFormatter = CreateFormatter();\n            MediaTypeHeaderValue expectedMediaType = CreateMediaType();\n            ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedFormatter,\n                expectedMediaType);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();\n\n                Mock<IContentNegotiator> spyContentNegotiator = new Mock<IContentNegotiator>();\n                spyContentNegotiator.Setup(n => n.Negotiate(typeof(object), expectedRequest, expectedFormatters))\n                    .Returns(negotiationResult);\n                IContentNegotiator contentNegotiator = spyContentNegotiator.Object;\n\n                IHttpActionResult result = CreateProductUnderTest(expectedRouteName, expectedRouteValues,\n                    expectedContent, urlFactory, contentNegotiator, expectedRequest, expectedFormatters);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.Created, response.StatusCode);\n                    Assert.Same(expectedLocation, response.Headers.Location.OriginalString);\n                    HttpContent content = response.Content;\n                    ObjectContent<object> typedContent = Assert.IsType<ObjectContent<object>>(content);\n                    Assert.Same(expectedContent, typedContent.Value);\n                    Assert.Same(expectedFormatter, typedContent.Formatter);\n                    Assert.NotNull(typedContent.Headers);\n                    Assert.Equal(expectedMediaType, typedContent.Headers.ContentType);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Returns_CorrectResponse_WhenContentNegotiationFails()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            object content = CreateContent();\n            UrlHelper urlFactory = CreateDummyUrlFactory();\n            ContentNegotiationResult negotiationResult = null;\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();\n\n                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();\n                spy.Setup(n => n.Negotiate(typeof(object), expectedRequest, expectedFormatters)).Returns(\n                    negotiationResult);\n                IContentNegotiator contentNegotiator = spy.Object;\n\n                IHttpActionResult result = CreateProductUnderTest(routeName, routeValues, content, urlFactory,\n                    contentNegotiator, expectedRequest, expectedFormatters);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);\n                    Assert.Null(response.Headers.Location);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Throws_WhenUrlHelperLinkReturnsNull_AfterContentNegotiationSucceeds()\n        {\n            // Arrange\n            string expectedRouteName = CreateRouteName();\n            IDictionary<string, object> expectedRouteValues = CreateRouteValues();\n            object expectedContent = CreateContent();\n            Mock<UrlHelper> stubUrlFactory = new Mock<UrlHelper>(MockBehavior.Strict);\n            stubUrlFactory.Setup(f => f.Link(expectedRouteName, expectedRouteValues)).Returns((string)null);\n            UrlHelper urlFactory = stubUrlFactory.Object;\n            MediaTypeFormatter expectedFormatter = CreateFormatter();\n            MediaTypeHeaderValue expectedMediaType = CreateMediaType();\n            ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedFormatter,\n                expectedMediaType);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();\n\n                Mock<IContentNegotiator> spyContentNegotiator = new Mock<IContentNegotiator>();\n                spyContentNegotiator.Setup(n => n.Negotiate(typeof(object), expectedRequest, expectedFormatters))\n                    .Returns(negotiationResult);\n                IContentNegotiator contentNegotiator = spyContentNegotiator.Object;\n\n                IHttpActionResult result = CreateProductUnderTest(expectedRouteName, expectedRouteValues,\n                    expectedContent, urlFactory, contentNegotiator, expectedRequest, expectedFormatters);\n\n                // Act & Assert\n                InvalidOperationException exception = await Assert.ThrowsAsync<InvalidOperationException>(\n                    () => result.ExecuteAsync(CancellationToken.None));\n                Assert.Equal(\"UrlHelper.Link must not return null.\", exception.Message);\n            }\n        }\n\n        [Fact]\n        public void Constructor_ForApiController_Throws_WhenControllerIsNull()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            object content = CreateContent();\n            ApiController controller = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() =>\n            {\n                CreateProductUnderTest(routeName, routeValues, content, controller);\n            }, \"controller\");\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_ForApiController_ReturnsCorrectResponse_WhenContentNegotationSucceeds()\n        {\n            // Arrange\n            string expectedRouteName = CreateRouteName();\n            IDictionary<string, object> expectedRouteValues = CreateRouteValues();\n            object expectedContent = CreateContent();\n            Mock<UrlHelper> spyUrlFactory = new Mock<UrlHelper>(MockBehavior.Strict);\n            string expectedLocation = CreateLocation().AbsoluteUri;\n            spyUrlFactory.Setup(f => f.Link(expectedRouteName, expectedRouteValues)).Returns(expectedLocation);\n            UrlHelper urlFactory = spyUrlFactory.Object;\n            ApiController controller = CreateController();\n            MediaTypeFormatter expectedInputFormatter = CreateFormatter();\n            MediaTypeFormatter expectedOutputFormatter = CreateFormatter();\n            MediaTypeHeaderValue expectedMediaType = CreateMediaType();\n            ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedOutputFormatter,\n                expectedMediaType);\n\n            Expression<Func<IEnumerable<MediaTypeFormatter>, bool>> formattersMatch = (f) =>\n                f != null && f.AsArray().Length == 1 && f.AsArray()[0] == expectedInputFormatter;\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();\n                spy.Setup(n => n.Negotiate(typeof(object), expectedRequest, It.Is(formattersMatch))).Returns(\n                    negotiationResult);\n                IContentNegotiator contentNegotiator = spy.Object;\n\n                using (HttpConfiguration configuration = CreateConfiguration(expectedInputFormatter,\n                    contentNegotiator))\n                {\n                    controller.Configuration = configuration;\n                    controller.Request = expectedRequest;\n                    controller.Url = urlFactory;\n\n                    IHttpActionResult result = CreateProductUnderTest(expectedRouteName, expectedRouteValues,\n                        expectedContent, controller);\n\n                    // Act\n                    Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                    // Assert\n                    Assert.NotNull(task);\n\n                    using (HttpResponseMessage response = await task)\n                    {\n                        Assert.NotNull(response);\n                        Assert.Equal(HttpStatusCode.Created, response.StatusCode);\n                        Assert.Same(expectedLocation, response.Headers.Location.OriginalString);\n                        HttpContent content = response.Content;\n                        ObjectContent<object> typedContent = Assert.IsType<ObjectContent<object>>(content);\n                        Assert.Same(expectedContent, typedContent.Value);\n                        Assert.Same(expectedOutputFormatter, typedContent.Formatter);\n                        Assert.NotNull(typedContent.Headers);\n                        Assert.Equal(expectedMediaType, typedContent.Headers.ContentType);\n                        Assert.Same(expectedRequest, response.RequestMessage);\n                    }\n                }\n            }\n        }\n\n        [Fact]\n        public void UrlFactory_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            object content = CreateContent();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Configuration = configuration;\n                controller.Request = request;\n                controller.Url = CreateDummyUrlFactory();\n\n                CreatedAtRouteNegotiatedContentResult<object> result = CreateProductUnderTest(routeName,\n                    routeValues, content, controller);\n\n                UrlHelper expectedUrlFactory = CreateDummyUrlFactory();\n                controller.Url = expectedUrlFactory;\n\n                // Act\n                UrlHelper urlFactory = result.UrlFactory;\n\n                // Assert\n                Assert.Same(expectedUrlFactory, urlFactory);\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            object content = CreateContent();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            {\n                controller.Configuration = configuration;\n\n                using (HttpRequestMessage request = CreateRequest())\n                {\n                    controller.Request = request;\n\n                    CreatedAtRouteNegotiatedContentResult<object> result = CreateProductUnderTest(routeName,\n                        routeValues, content, controller);\n\n                    IContentNegotiator expectedContentNegotiator = CreateDummyContentNegotiator();\n                    configuration.Services.Replace(typeof(IContentNegotiator), expectedContentNegotiator);\n\n                    // Act\n                    IContentNegotiator contentNegotiator = result.ContentNegotiator;\n\n                    // Assert\n                    Assert.Same(expectedContentNegotiator, contentNegotiator);\n                }\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            object content = CreateContent();\n            MediaTypeFormatter formatter = CreateFormatter();\n            MediaTypeHeaderValue mediaType = CreateMediaType();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            {\n                controller.Configuration = configuration;\n                CreatedAtRouteNegotiatedContentResult<object> result = CreateProductUnderTest(routeName, routeValues,\n                    content, controller);\n\n                using (HttpRequestMessage expectedRequest = CreateRequest())\n                {\n                    controller.Request = expectedRequest;\n\n                    // Act\n                    HttpRequestMessage request = result.Request;\n\n                    // Assert\n                    Assert.Same(expectedRequest, request);\n                }\n            }\n        }\n\n        [Fact]\n        public void Formatters_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            object content = CreateContent();\n            ApiController controller = CreateController();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpConfiguration earlyConfiguration = CreateConfiguration(CreateFormatter(), contentNegotiator))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Configuration = earlyConfiguration;\n                controller.Request = request;\n\n                CreatedAtRouteNegotiatedContentResult<object> result = CreateProductUnderTest(routeName, routeValues,\n                    content, controller);\n\n                MediaTypeFormatter expectedFormatter = CreateFormatter();\n\n                using (HttpConfiguration lateConfiguration = CreateConfiguration(expectedFormatter, contentNegotiator))\n                {\n                    controller.Configuration = lateConfiguration;\n\n                    // Act\n                    IEnumerable<MediaTypeFormatter> formatters = result.Formatters;\n\n                    // Assert\n                    Assert.NotNull(formatters);\n                    MediaTypeFormatter formatter = Assert.Single(formatters);\n                    Assert.Same(expectedFormatter, formatter);\n                }\n            }\n        }\n\n        [Fact]\n        public void UrlFactory_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            object content = CreateContent();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Configuration = configuration;\n                controller.Request = request;\n                UrlHelper expectedUrlFactory = CreateDummyUrlFactory();\n                controller.Url = expectedUrlFactory;\n\n                CreatedAtRouteNegotiatedContentResult<object> result = CreateProductUnderTest(routeName, routeValues,\n                    content, controller);\n\n                UrlHelper ignore = result.UrlFactory;\n\n                controller.Url = CreateDummyUrlFactory();\n\n                // Act\n                UrlHelper urlFactory = result.UrlFactory;\n\n                // Assert\n                Assert.Same(expectedUrlFactory, urlFactory);\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            object content = CreateContent();\n            IContentNegotiator expectedContentNegotiator = CreateDummyContentNegotiator();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), expectedContentNegotiator))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Configuration = configuration;\n                controller.Request = request;\n\n                CreatedAtRouteNegotiatedContentResult<object> result = CreateProductUnderTest(routeName, routeValues,\n                    content, controller);\n\n                IContentNegotiator ignore = result.ContentNegotiator;\n\n                configuration.Services.Replace(typeof(IContentNegotiator), CreateDummyContentNegotiator());\n\n                // Act\n                IContentNegotiator contentNegotiator = result.ContentNegotiator;\n\n                // Assert\n                Assert.Same(expectedContentNegotiator, contentNegotiator);\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            object content = CreateContent();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            {\n                controller.Configuration = configuration;\n\n                CreatedAtRouteNegotiatedContentResult<object> result = CreateProductUnderTest(routeName, routeValues,\n                    content, controller);\n\n                using (HttpRequestMessage expectedRequest = CreateRequest())\n                {\n                    controller.Request = expectedRequest;\n                    HttpRequestMessage ignore = result.Request;\n\n                    using (HttpRequestMessage otherRequest = CreateRequest())\n                    {\n                        controller.Request = otherRequest;\n\n                        // Act\n                        HttpRequestMessage request = result.Request;\n\n                        // Assert\n                        Assert.Same(expectedRequest, request);\n                    }\n                }\n            }\n        }\n\n        [Fact]\n        public void Formatters_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            object content = CreateContent();\n            ApiController controller = CreateController();\n            MediaTypeFormatter expectedFormatter = CreateFormatter();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpConfiguration earlyConfiguration = CreateConfiguration(expectedFormatter, contentNegotiator))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Configuration = earlyConfiguration;\n                controller.Request = request;\n\n                CreatedAtRouteNegotiatedContentResult<object> result = CreateProductUnderTest(routeName, routeValues,\n                    content, controller);\n\n                IEnumerable<MediaTypeFormatter> ignore = result.Formatters;\n\n                using (HttpConfiguration lateConfiguration = CreateConfiguration(CreateFormatter(), contentNegotiator))\n                {\n                    controller.Configuration = lateConfiguration;\n\n                    // Act\n                    IEnumerable<MediaTypeFormatter> formatters = result.Formatters;\n\n                    // Assert\n                    Assert.NotNull(formatters);\n                    MediaTypeFormatter formatter = Assert.Single(formatters);\n                    Assert.Same(expectedFormatter, formatter);\n                }\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ForApiController_Throws_WhenConfigurationIsNull()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            object content = CreateContent();\n            ApiController controller = CreateController();\n            HttpControllerContext context = new HttpControllerContext();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.ControllerContext = context;\n                controller.Request = request;\n\n                CreatedAtRouteNegotiatedContentResult<object> result = CreateProductUnderTest(routeName, routeValues,\n                    content, controller);\n\n                // Act & Assert\n                Assert.Throws<InvalidOperationException>(\n                    () => { IContentNegotiator ignore = result.ContentNegotiator; },\n                    \"HttpControllerContext.Configuration must not be null.\");\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ForApiController_Throws_WhenServiceIsNull()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            object content = CreateContent();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), null))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Configuration = configuration;\n                controller.Request = request;\n\n                CreatedAtRouteNegotiatedContentResult<object> result = CreateProductUnderTest(routeName, routeValues,\n                    content, controller);\n\n                // Act & Assert\n                Assert.Throws<InvalidOperationException>(\n                    () => { IContentNegotiator ignore = result.ContentNegotiator; },\n                    \"The provided configuration does not have an instance of the \" +\n                    \"'System.Net.Http.Formatting.IContentNegotiator' service registered.\");\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_Throws_WhenControllerRequestIsNull()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            object content = CreateContent();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            {\n                controller.Configuration = configuration;\n                Assert.Null(controller.Request);\n\n                CreatedAtRouteNegotiatedContentResult<object> result = CreateProductUnderTest(routeName, routeValues,\n                    content, controller);\n\n                // Act & Assert\n                InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() =>\n                    { HttpRequestMessage ignore = result.Request; }, \"ApiController.Request must not be null.\");\n            }\n        }\n\n        [Fact]\n        public void ApiControllerCreatedAtRoute_WithStringAndDictionary_CreatesCorrectResult()\n        {\n            // Arrange\n            string expectedRouteName = CreateRouteName();\n            IDictionary<string, object> expectedRouteValues = CreateRouteValues();\n            object expectedContent = CreateContent();\n            ApiController controller = CreateController();\n\n            // Act\n            CreatedAtRouteNegotiatedContentResult<object> result = controller.CreatedAtRoute(expectedRouteName,\n                expectedRouteValues, expectedContent);\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Same(expectedRouteName, result.RouteName);\n            Assert.Same(expectedRouteValues, result.RouteValues);\n            Assert.Same(expectedContent, result.Content);\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Configuration = configuration;\n                controller.Request = expectedRequest;\n                Assert.Same(expectedRequest, result.Request);\n            }\n        }\n\n        [Fact]\n        public void ApiControllerCreatedAtRoute_WithStringAndObject_CreatesCorrectResult()\n        {\n            // Arrange\n            string expectedRouteName = CreateRouteName();\n            object routeValues = new { id = 1 };\n            object expectedContent = CreateContent();\n            ApiController controller = CreateController();\n\n            // Act\n            CreatedAtRouteNegotiatedContentResult<object> result = controller.CreatedAtRoute(expectedRouteName,\n                routeValues, expectedContent);\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Same(expectedRouteName, result.RouteName);\n            Assert.IsType<HttpRouteValueDictionary>(result.RouteValues);\n            Assert.True(result.RouteValues.ContainsKey(\"id\"));\n            Assert.Equal(1, result.RouteValues[\"id\"]);\n            Assert.Same(expectedContent, result.Content);\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Configuration = configuration;\n                controller.Request = expectedRequest;\n                Assert.Same(expectedRequest, result.Request);\n            }\n        }\n\n        private static HttpConfiguration CreateConfiguration(MediaTypeFormatter formatter,\n            IContentNegotiator contentNegotiator)\n        {\n            HttpConfiguration configuration = new HttpConfiguration();\n            configuration.Formatters.Clear();\n            configuration.Formatters.Add(formatter);\n            configuration.Services.Replace(typeof(IContentNegotiator), contentNegotiator);\n            return configuration;\n        }\n\n        private static object CreateContent()\n        {\n            return new object();\n        }\n\n        private static ApiController CreateController()\n        {\n            return new FakeController();\n        }\n\n        private static IContentNegotiator CreateDummyContentNegotiator()\n        {\n            return new Mock<IContentNegotiator>(MockBehavior.Strict).Object;\n        }\n\n        private static UrlHelper CreateDummyUrlFactory()\n        {\n            return new Mock<UrlHelper>(MockBehavior.Strict).Object;\n        }\n\n        private static MediaTypeFormatter CreateFormatter()\n        {\n            return new StubMediaTypeFormatter();\n        }\n\n        private static IEnumerable<MediaTypeFormatter> CreateFormatters()\n        {\n            return new MediaTypeFormatter[0];\n        }\n\n        private static Uri CreateLocation()\n        {\n            return new Uri(\"aa://b\");\n        }\n\n        private static MediaTypeHeaderValue CreateMediaType()\n        {\n            return new MediaTypeHeaderValue(\"text/plain\");\n        }\n\n        private static CreatedAtRouteNegotiatedContentResult<object> CreateProductUnderTest(string routeName,\n            IDictionary<string, object> routeValues, object content, UrlHelper urlFactory,\n            IContentNegotiator contentNegotiator, HttpRequestMessage request,\n            IEnumerable<MediaTypeFormatter> formatters)\n        {\n            return new CreatedAtRouteNegotiatedContentResult<object>(routeName, routeValues, content, urlFactory,\n                contentNegotiator, request, formatters);\n        }\n\n        private static CreatedAtRouteNegotiatedContentResult<object> CreateProductUnderTest(string routeName,\n            IDictionary<string, object> routeValues, object content, ApiController controller)\n        {\n            return new CreatedAtRouteNegotiatedContentResult<object>(routeName, routeValues, content, controller);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private static string CreateRouteName()\n        {\n            return \"IgnoreRouteName\";\n        }\n\n        private static IDictionary<string, object> CreateRouteValues()\n        {\n            return new Dictionary<string, object>();\n        }\n\n        private class StubMediaTypeFormatter : MediaTypeFormatter\n        {\n            public override bool CanReadType(Type type)\n            {\n                return true;\n            }\n\n            public override bool CanWriteType(Type type)\n            {\n                return true;\n            }\n        }\n\n        private class FakeController : ApiController\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Results/CreatedNegotiatedContentResultTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq.Expressions;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Results\n{\n    public class CreatedNegotiatedContentResultTests\n    {\n        [Fact]\n        public void Constructor_Throws_WhenLocationIsNull()\n        {\n            // Arrange\n            Uri location = null;\n            object content = CreateContent();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() =>\n                {\n                    CreateProductUnderTest(location, content, contentNegotiator, request, formatters);\n                }, \"location\");\n            }\n        }\n\n        [Fact]\n        public void Constructor_Throws_WhenContentNegotiatorIsNull()\n        {\n            // Arrange\n            Uri location = CreateLocation();\n            object content = CreateContent();\n            IContentNegotiator contentNegotiator = null;\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() =>\n                {\n                    CreateProductUnderTest(location, content, contentNegotiator, request, formatters);\n                }, \"contentNegotiator\");\n            }\n        }\n\n        [Fact]\n        public void Constructor_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            Uri location = CreateLocation();\n            object content = CreateContent();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n            HttpRequestMessage request = null;\n            IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() =>\n            {\n                CreateProductUnderTest(location, content, contentNegotiator, request, formatters);\n            }, \"request\");\n        }\n\n        [Fact]\n        public void Constructor_Throws_WhenFormattersIsNull()\n        {\n            // Arrange\n            Uri location = CreateLocation();\n            object content = CreateContent();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = null;\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() =>\n                {\n                    CreateProductUnderTest(location, content, contentNegotiator, request, formatters);\n                }, \"formatters\");\n            }\n        }\n\n        [Fact]\n        public void Location_Returns_InstanceProvided()\n        {\n            // Arrange\n            Uri expectedLocation = CreateLocation();\n            object content = CreateContent();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                CreatedNegotiatedContentResult<object> result = CreateProductUnderTest(expectedLocation, content,\n                    contentNegotiator, request, formatters);\n\n                // Act\n                Uri location = result.Location;\n\n                // Assert\n                Assert.Same(expectedLocation, location);\n            }\n        }\n\n        [Fact]\n        public void Content_Returns_InstanceProvided()\n        {\n            // Arrange\n            Uri location = CreateLocation();\n            object expectedContent = CreateContent();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                CreatedNegotiatedContentResult<object> result = CreateProductUnderTest(location, expectedContent,\n                    contentNegotiator, request, formatters);\n\n                // Act\n                object content = result.Content;\n\n                // Assert\n                Assert.Same(expectedContent, content);\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_Returns_InstanceProvided()\n        {\n            // Arrange\n            Uri location = CreateLocation();\n            object content = CreateContent();\n            IContentNegotiator expectedContentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                CreatedNegotiatedContentResult<object> result = CreateProductUnderTest(location, content,\n                    expectedContentNegotiator, request, formatters);\n\n                // Act\n                IContentNegotiator contentNegotiator = result.ContentNegotiator;\n\n                // Assert\n                Assert.Same(expectedContentNegotiator, contentNegotiator);\n            }\n        }\n\n        [Fact]\n        public void Request_Returns_InstanceProvided()\n        {\n            // Arrange\n            Uri location = CreateLocation();\n            object content = CreateContent();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                CreatedNegotiatedContentResult<object> result = CreateProductUnderTest(location, content,\n                    contentNegotiator, expectedRequest, formatters);\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public void Formatters_Returns_InstanceProvided()\n        {\n            // Arrange\n            Uri location = CreateLocation();\n            object content = CreateContent();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();\n\n                CreatedNegotiatedContentResult<object> result = CreateProductUnderTest(location, content,\n                    contentNegotiator, request, expectedFormatters);\n\n                // Act\n                IEnumerable<MediaTypeFormatter> formatters = result.Formatters;\n\n                // Assert\n                Assert.Same(expectedFormatters, formatters);\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Returns_CorrectResponse_WhenContentNegotiationSucceeds()\n        {\n            // Arrange\n            Uri expectedLocation = CreateLocation();\n            object expectedContent = CreateContent();\n            MediaTypeFormatter expectedFormatter = CreateFormatter();\n            MediaTypeHeaderValue expectedMediaType = CreateMediaType();\n            ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedFormatter,\n                expectedMediaType);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();\n\n                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();\n                spy.Setup(n => n.Negotiate(typeof(object), expectedRequest, expectedFormatters)).Returns(\n                    negotiationResult);\n                IContentNegotiator contentNegotiator = spy.Object;\n\n                IHttpActionResult result = CreateProductUnderTest(expectedLocation, expectedContent, contentNegotiator,\n                    expectedRequest, expectedFormatters);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.Created, response.StatusCode);\n                    Assert.Same(expectedLocation, response.Headers.Location);\n                    HttpContent content = response.Content;\n                    ObjectContent<object> typedContent = Assert.IsType<ObjectContent<object>>(content);\n                    Assert.Same(expectedContent, typedContent.Value);\n                    Assert.Same(expectedFormatter, typedContent.Formatter);\n                    Assert.NotNull(typedContent.Headers);\n                    Assert.Equal(expectedMediaType, typedContent.Headers.ContentType);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Returns_CorrectResponse_WhenContentNegotiationFails()\n        {\n            // Arrange\n            Uri location = CreateLocation();\n            object content = CreateContent();\n            ContentNegotiationResult negotiationResult = null;\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();\n\n                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();\n                spy.Setup(n => n.Negotiate(typeof(object), expectedRequest, expectedFormatters)).Returns(\n                    negotiationResult);\n                IContentNegotiator contentNegotiator = spy.Object;\n\n                IHttpActionResult result = CreateProductUnderTest(location, content, contentNegotiator,\n                    expectedRequest, expectedFormatters);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);\n                    Assert.Null(response.Headers.Location);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public void Constructor_ForApiController_Throws_WhenControllerIsNull()\n        {\n            // Arrange\n            Uri location = CreateLocation();\n            object content = CreateContent();\n            ApiController controller = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() =>\n            {\n                CreateProductUnderTest(location, content, controller);\n            }, \"controller\");\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_ForApiController_ReturnsCorrectResponse_WhenContentNegotationSucceeds()\n        {\n            // Arrange\n            Uri expectedLocation = CreateLocation();\n            object expectedContent = CreateContent();\n            ApiController controller = CreateController();\n            MediaTypeFormatter expectedInputFormatter = CreateFormatter();\n            MediaTypeFormatter expectedOutputFormatter = CreateFormatter();\n            MediaTypeHeaderValue expectedMediaType = CreateMediaType();\n            ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedOutputFormatter,\n                expectedMediaType);\n\n            Expression<Func<IEnumerable<MediaTypeFormatter>, bool>> formattersMatch = (f) =>\n                f != null && f.AsArray().Length == 1 && f.AsArray()[0] == expectedInputFormatter;\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();\n                spy.Setup(n => n.Negotiate(typeof(object), expectedRequest, It.Is(formattersMatch))).Returns(\n                    negotiationResult);\n                IContentNegotiator contentNegotiator = spy.Object;\n\n                using (HttpConfiguration configuration = CreateConfiguration(expectedInputFormatter,\n                    contentNegotiator))\n                {\n                    controller.Configuration = configuration;\n                    controller.Request = expectedRequest;\n\n                    IHttpActionResult result = CreateProductUnderTest(expectedLocation, expectedContent, controller);\n\n                    // Act\n                    Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                    // Assert\n                    Assert.NotNull(task);\n\n                    using (HttpResponseMessage response = await task)\n                    {\n                        Assert.NotNull(response);\n                        Assert.Equal(HttpStatusCode.Created, response.StatusCode);\n                        Assert.Same(expectedLocation, response.Headers.Location);\n                        HttpContent content = response.Content;\n                        ObjectContent<object> typedContent = Assert.IsType<ObjectContent<object>>(content);\n                        Assert.Same(expectedContent, typedContent.Value);\n                        Assert.Same(expectedOutputFormatter, typedContent.Formatter);\n                        Assert.NotNull(typedContent.Headers);\n                        Assert.Equal(expectedMediaType, typedContent.Headers.ContentType);\n                        Assert.Same(expectedRequest, response.RequestMessage);\n                    }\n                }\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            Uri location = CreateLocation();\n            object content = CreateContent();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            {\n                controller.Configuration = configuration;\n\n                using (HttpRequestMessage request = CreateRequest())\n                {\n                    controller.Request = request;\n\n                    CreatedNegotiatedContentResult<object> result = CreateProductUnderTest(location, content,\n                        controller);\n\n                    IContentNegotiator expectedContentNegotiator = CreateDummyContentNegotiator();\n                    configuration.Services.Replace(typeof(IContentNegotiator), expectedContentNegotiator);\n\n                    // Act\n                    IContentNegotiator contentNegotiator = result.ContentNegotiator;\n\n                    // Assert\n                    Assert.Same(expectedContentNegotiator, contentNegotiator);\n                }\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            Uri location = CreateLocation();\n            object content = CreateContent();\n            MediaTypeFormatter formatter = CreateFormatter();\n            MediaTypeHeaderValue mediaType = CreateMediaType();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            {\n                controller.Configuration = configuration;\n                CreatedNegotiatedContentResult<object> result = CreateProductUnderTest(location, content, controller);\n\n                using (HttpRequestMessage expectedRequest = CreateRequest())\n                {\n                    controller.Request = expectedRequest;\n\n                    // Act\n                    HttpRequestMessage request = result.Request;\n\n                    // Assert\n                    Assert.Same(expectedRequest, request);\n                }\n            }\n        }\n\n        [Fact]\n        public void Formatters_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            Uri location = CreateLocation();\n            object content = CreateContent();\n            ApiController controller = CreateController();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpConfiguration earlyConfiguration = CreateConfiguration(CreateFormatter(), contentNegotiator))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Configuration = earlyConfiguration;\n                controller.Request = request;\n\n                CreatedNegotiatedContentResult<object> result = CreateProductUnderTest(location, content, controller);\n\n                MediaTypeFormatter expectedFormatter = CreateFormatter();\n\n                using (HttpConfiguration lateConfiguration = CreateConfiguration(expectedFormatter, contentNegotiator))\n                {\n                    controller.Configuration = lateConfiguration;\n\n                    // Act\n                    IEnumerable<MediaTypeFormatter> formatters = result.Formatters;\n\n                    // Assert\n                    Assert.NotNull(formatters);\n                    MediaTypeFormatter formatter = Assert.Single(formatters);\n                    Assert.Same(expectedFormatter, formatter);\n                }\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            Uri location = CreateLocation();\n            object content = CreateContent();\n            IContentNegotiator expectedContentNegotiator = CreateDummyContentNegotiator();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), expectedContentNegotiator))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Configuration = configuration;\n                controller.Request = request;\n\n                CreatedNegotiatedContentResult<object> result = CreateProductUnderTest(location, content, controller);\n\n                IContentNegotiator ignore = result.ContentNegotiator;\n\n                configuration.Services.Replace(typeof(IContentNegotiator), CreateDummyContentNegotiator());\n\n                // Act\n                IContentNegotiator contentNegotiator = result.ContentNegotiator;\n\n                // Assert\n                Assert.Same(expectedContentNegotiator, contentNegotiator);\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            Uri location = CreateLocation();\n            object content = CreateContent();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            {\n                controller.Configuration = configuration;\n\n                CreatedNegotiatedContentResult<object> result = CreateProductUnderTest(location, content, controller);\n\n                using (HttpRequestMessage expectedRequest = CreateRequest())\n                {\n                    controller.Request = expectedRequest;\n                    HttpRequestMessage ignore = result.Request;\n\n                    using (HttpRequestMessage otherRequest = CreateRequest())\n                    {\n                        controller.Request = otherRequest;\n\n                        // Act\n                        HttpRequestMessage request = result.Request;\n\n                        // Assert\n                        Assert.Same(expectedRequest, request);\n                    }\n                }\n            }\n        }\n\n        [Fact]\n        public void Formatters_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            Uri location = CreateLocation();\n            object content = CreateContent();\n            ApiController controller = CreateController();\n            MediaTypeFormatter expectedFormatter = CreateFormatter();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpConfiguration earlyConfiguration = CreateConfiguration(expectedFormatter, contentNegotiator))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Configuration = earlyConfiguration;\n                controller.Request = request;\n\n                CreatedNegotiatedContentResult<object> result = CreateProductUnderTest(location, content, controller);\n\n                IEnumerable<MediaTypeFormatter> ignore = result.Formatters;\n\n                using (HttpConfiguration lateConfiguration = CreateConfiguration(CreateFormatter(), contentNegotiator))\n                {\n                    controller.Configuration = lateConfiguration;\n\n                    // Act\n                    IEnumerable<MediaTypeFormatter> formatters = result.Formatters;\n\n                    // Assert\n                    Assert.NotNull(formatters);\n                    MediaTypeFormatter formatter = Assert.Single(formatters);\n                    Assert.Same(expectedFormatter, formatter);\n                }\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ForApiController_Throws_WhenConfigurationIsNull()\n        {\n            // Arrange\n            Uri location = CreateLocation();\n            object content = CreateContent();\n            ApiController controller = CreateController();\n            HttpControllerContext context = new HttpControllerContext();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.ControllerContext = context;\n\n                CreatedNegotiatedContentResult<object> result = CreateProductUnderTest(location, content, controller);\n\n                // Act & Assert\n                Assert.Throws<InvalidOperationException>(\n                    () => { IContentNegotiator ignore = result.ContentNegotiator; },\n                    \"HttpControllerContext.Configuration must not be null.\");\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ForApiController_Throws_WhenServiceIsNull()\n        {\n            // Arrange\n            Uri location = CreateLocation();\n            object content = CreateContent();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), null))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Configuration = configuration;\n\n                CreatedNegotiatedContentResult<object> result = CreateProductUnderTest(location, content, controller);\n\n                // Act & Assert\n                Assert.Throws<InvalidOperationException>(\n                    () => { IContentNegotiator ignore = result.ContentNegotiator; },\n                    \"The provided configuration does not have an instance of the \" +\n                    \"'System.Net.Http.Formatting.IContentNegotiator' service registered.\");\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_Throws_WhenControllerRequestIsNull()\n        {\n            // Arrange\n            Uri location = CreateLocation();\n            object content = CreateContent();\n            ApiController controller = CreateController();\n            Assert.Null(controller.Request);\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            {\n                controller.Configuration = configuration;\n                CreatedNegotiatedContentResult<object> result = CreateProductUnderTest(location, content, controller);\n\n                // Act & Assert\n                InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() =>\n                    { HttpRequestMessage ignore = result.Request; }, \"ApiController.Request must not be null.\");\n            }\n        }\n\n        [Fact]\n        public void ApiControllerCreated_WithUriAndContent_CreatesCorrectResult()\n        {\n            // Arrange\n            Uri expectedLocation = CreateLocation();\n            object expectedContent = CreateContent();\n            ApiController controller = CreateController();\n\n            // Act\n            CreatedNegotiatedContentResult<object> result = controller.Created(expectedLocation, expectedContent);\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Same(expectedLocation, result.Location);\n            Assert.Same(expectedContent, result.Content);\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Configuration = configuration;\n                controller.Request = expectedRequest;\n                Assert.Same(expectedRequest, result.Request);\n            }\n        }\n\n        [Fact]\n        public void ApiControllerCreated_WithStringAndContent_Throws_WhenLocationIsNull()\n        {\n            // Arrange\n            string location = null;\n            object content = CreateContent();\n            ApiController controller = CreateController();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { controller.Created(location, content); }, \"location\");\n        }\n\n        [Theory]\n        [InlineData(\"/example/yes\")] // Absolute path\n        [InlineData(\"relative/relative\")] // Relative path\n        [InlineData(\"http://example.com\")] // Absolute URL with host\n        public void ApiControllerCreated_WithStringAndContent_CreatesCorrectResult(string location)\n        {\n            // Arrange\n            object expectedContent = CreateContent();\n            ApiController controller = CreateController();\n\n            // Act\n            CreatedNegotiatedContentResult<object> result = controller.Created(location, expectedContent);\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Same(location, result.Location.OriginalString);\n            Assert.Same(expectedContent, result.Content);\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Configuration = configuration;\n                controller.Request = expectedRequest;\n                Assert.Same(expectedRequest, result.Request);\n            }\n        }\n\n        private static HttpConfiguration CreateConfiguration(MediaTypeFormatter formatter,\n            IContentNegotiator contentNegotiator)\n        {\n            HttpConfiguration configuration = new HttpConfiguration();\n            configuration.Formatters.Clear();\n            configuration.Formatters.Add(formatter);\n            configuration.Services.Replace(typeof(IContentNegotiator), contentNegotiator);\n            return configuration;\n        }\n\n        private static object CreateContent()\n        {\n            return new object();\n        }\n\n        private static ApiController CreateController()\n        {\n            return new FakeController();\n        }\n\n        private static IContentNegotiator CreateDummyContentNegotiator()\n        {\n            return new Mock<IContentNegotiator>(MockBehavior.Strict).Object;\n        }\n\n        private static MediaTypeFormatter CreateFormatter()\n        {\n            return new StubMediaTypeFormatter();\n        }\n\n        private static IEnumerable<MediaTypeFormatter> CreateFormatters()\n        {\n            return new MediaTypeFormatter[0];\n        }\n\n        private static Uri CreateLocation()\n        {\n            return new Uri(\"aa://b\");\n        }\n\n        private static MediaTypeHeaderValue CreateMediaType()\n        {\n            return new MediaTypeHeaderValue(\"text/plain\");\n        }\n\n        private static CreatedNegotiatedContentResult<object> CreateProductUnderTest(Uri location, object content,\n            IContentNegotiator contentNegotiator, HttpRequestMessage request,\n            IEnumerable<MediaTypeFormatter> formatters)\n        {\n            return new CreatedNegotiatedContentResult<object>(location, content, contentNegotiator, request,\n                formatters);\n        }\n\n        private static CreatedNegotiatedContentResult<object> CreateProductUnderTest(Uri location, object content,\n            ApiController controller)\n        {\n            return new CreatedNegotiatedContentResult<object>(location, content, controller);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private class StubMediaTypeFormatter : MediaTypeFormatter\n        {\n            public override bool CanReadType(Type type)\n            {\n                return true;\n            }\n\n            public override bool CanWriteType(Type type)\n            {\n                return true;\n            }\n        }\n\n        private class FakeController : ApiController\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Results/ExceptionResultTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq.Expressions;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.ModelBinding;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Results\n{\n    public class ExceptionResultTests\n    {\n        [Fact]\n        public void Constructor_Throws_WhenExceptionIsNull()\n        {\n            // Arrange\n            Exception exception = null;\n            bool includeErrorDetail = true;\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() =>\n                {\n                    CreateProductUnderTest(exception, includeErrorDetail, contentNegotiator, request, formatters);\n                }, \"exception\");\n            }\n        }\n\n        [Fact]\n        public void Constructor_Throws_WhenContentNegotiatorIsNull()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            bool includeErrorDetail = true;\n            IContentNegotiator contentNegotiator = null;\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() =>\n                {\n                    CreateProductUnderTest(exception, includeErrorDetail, contentNegotiator, request, formatters);\n                }, \"contentNegotiator\");\n            }\n        }\n\n        [Fact]\n        public void Constructor_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            bool includeErrorDetail = true;\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n            HttpRequestMessage request = null;\n            IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() =>\n            {\n                CreateProductUnderTest(exception, includeErrorDetail, contentNegotiator, request, formatters);\n            }, \"request\");\n        }\n\n        [Fact]\n        public void Constructor_Throws_WhenFormattersIsNull()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            bool includeErrorDetail = true;\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = null;\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() =>\n                {\n                    CreateProductUnderTest(exception, includeErrorDetail, contentNegotiator, request, formatters);\n                }, \"formatters\");\n            }\n        }\n\n        [Fact]\n        public void Exception_ReturnsInstanceProvided()\n        {\n            // Arrange\n            Exception expectedException = CreateException();\n            bool includeErrorDetail = true;\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                ExceptionResult result = CreateProductUnderTest(expectedException, includeErrorDetail,\n                    contentNegotiator, request, formatters);\n\n                // Act\n                Exception exception = result.Exception;\n\n                // Assert\n                Assert.Same(expectedException, exception);\n            }\n        }\n\n        [Fact]\n        public void IncludeErrorDetail_ReturnsValueProvided()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            bool expectedIncludeErrorDetail = true;\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                ExceptionResult result = CreateProductUnderTest(exception, expectedIncludeErrorDetail,\n                    contentNegotiator, request, formatters);\n\n                // Act\n                bool includeErrorDetail = result.IncludeErrorDetail;\n\n                // Assert\n                Assert.Equal(expectedIncludeErrorDetail, includeErrorDetail);\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ReturnsInstanceProvided()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            bool includeErrorDetail = true;\n            IContentNegotiator expectedContentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                ExceptionResult result = CreateProductUnderTest(exception, includeErrorDetail,\n                    expectedContentNegotiator, request, formatters);\n\n                // Act\n                IContentNegotiator contentNegotiator = result.ContentNegotiator;\n\n                // Assert\n                Assert.Same(expectedContentNegotiator, contentNegotiator);\n            }\n        }\n\n        [Fact]\n        public void Request_ReturnsInstanceProvided()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            bool includeErrorDetail = true;\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                ExceptionResult result = CreateProductUnderTest(exception, includeErrorDetail, contentNegotiator,\n                    expectedRequest, formatters);\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public void Formatters_ReturnsInstanceProvided()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            bool includeErrorDetail = true;\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();\n\n                ExceptionResult result = CreateProductUnderTest(exception, includeErrorDetail, contentNegotiator,\n                    request, expectedFormatters);\n\n                // Act\n                IEnumerable<MediaTypeFormatter> formatters = result.Formatters;\n\n                // Assert\n                Assert.Same(expectedFormatters, formatters);\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_ReturnsCorrectResponse_WhenContentNegotiationSucceedsAndIncludeErrorDetailIsTrue()\n        {\n            // Arrange\n            Exception expectedException = CreateExceptionWithStackTrace();\n            bool includeErrorDetail = true;\n            MediaTypeFormatter expectedFormatter = CreateFormatter();\n            MediaTypeHeaderValue expectedMediaType = CreateMediaType();\n            ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedFormatter,\n                expectedMediaType);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();\n\n                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();\n                spy.Setup(n => n.Negotiate(typeof(HttpError), expectedRequest, expectedFormatters)).Returns(\n                    negotiationResult);\n                IContentNegotiator contentNegotiator = spy.Object;\n\n                IHttpActionResult result = CreateProductUnderTest(expectedException, includeErrorDetail,\n                    contentNegotiator, expectedRequest, expectedFormatters);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n                    HttpContent content = response.Content;\n                    ObjectContent<HttpError> typedContent = Assert.IsType<ObjectContent<HttpError>>(content);\n                    HttpError error = (HttpError)typedContent.Value;\n                    Assert.NotNull(error);\n                    Assert.Equal(expectedException.Message, error.ExceptionMessage);\n                    Assert.Equal(expectedException.GetType().FullName, error.ExceptionType);\n                    Assert.Equal(expectedException.StackTrace, error.StackTrace);\n                    Assert.Same(expectedFormatter, typedContent.Formatter);\n                    Assert.NotNull(typedContent.Headers);\n                    Assert.Equal(expectedMediaType, typedContent.Headers.ContentType);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_ReturnsCorrectResponse_WhenContentNegotiationSucceedsAndIncludeErrorDetailIsFalse()\n        {\n            // Arrange\n            Exception exception = CreateExceptionWithStackTrace();\n            bool includeErrorDetail = false;\n            MediaTypeFormatter expectedFormatter = CreateFormatter();\n            MediaTypeHeaderValue expectedMediaType = CreateMediaType();\n            ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedFormatter,\n                expectedMediaType);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();\n\n                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();\n                spy.Setup(n => n.Negotiate(typeof(HttpError), expectedRequest, expectedFormatters)).Returns(\n                    negotiationResult);\n                IContentNegotiator contentNegotiator = spy.Object;\n\n                IHttpActionResult result = CreateProductUnderTest(exception, includeErrorDetail, contentNegotiator,\n                    expectedRequest, expectedFormatters);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n                    HttpContent content = response.Content;\n                    ObjectContent<HttpError> typedContent = Assert.IsType<ObjectContent<HttpError>>(content);\n                    HttpError error = (HttpError)typedContent.Value;\n                    Assert.NotNull(error);\n                    Assert.Null(error.ExceptionMessage);\n                    Assert.Null(error.ExceptionType);\n                    Assert.Null(error.StackTrace);\n                    Assert.Same(expectedFormatter, typedContent.Formatter);\n                    Assert.NotNull(typedContent.Headers);\n                    Assert.Equal(expectedMediaType, typedContent.Headers.ContentType);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_ReturnsCorrectResponse_WhenContentNegotiationFails()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            bool includeErrorDetail = true;\n            ContentNegotiationResult negotiationResult = null;\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();\n\n                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();\n                spy.Setup(n => n.Negotiate(typeof(ModelStateDictionary), expectedRequest, expectedFormatters)).Returns(\n                    negotiationResult);\n                IContentNegotiator contentNegotiator = spy.Object;\n\n                IHttpActionResult result = CreateProductUnderTest(exception, includeErrorDetail, contentNegotiator,\n                    expectedRequest, expectedFormatters);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public void Constructor_ForApiController_Throws_WhenControllerIsNull()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            ApiController controller = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { CreateProductUnderTest(exception, controller); }, \"controller\");\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_ForApiController_ReturnsCorrectResponse_WhenContentNegotationSucceeds()\n        {\n            // Arrange\n            Exception expectedException = CreateExceptionWithStackTrace();\n            ApiController controller = CreateController();\n            MediaTypeFormatter expectedInputFormatter = CreateFormatter();\n            MediaTypeFormatter expectedOutputFormatter = CreateFormatter();\n            MediaTypeHeaderValue expectedMediaType = CreateMediaType();\n            ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedOutputFormatter,\n                expectedMediaType);\n\n            Expression<Func<IEnumerable<MediaTypeFormatter>, bool>> formattersMatch = (f) =>\n                f != null && f.AsArray().Length == 1 && f.AsArray()[0] == expectedInputFormatter;\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();\n                spy.Setup(n => n.Negotiate(typeof(HttpError), expectedRequest, It.Is(formattersMatch))).Returns(\n                    negotiationResult);\n                IContentNegotiator contentNegotiator = spy.Object;\n\n                using (HttpConfiguration configuration = CreateConfiguration(expectedInputFormatter,\n                    contentNegotiator))\n                {\n                    controller.RequestContext = new HttpRequestContext\n                    {\n                        Configuration = configuration,\n                        IncludeErrorDetail = true\n                    };\n                    controller.Request = expectedRequest;\n\n                    IHttpActionResult result = CreateProductUnderTest(expectedException, controller);\n\n                    // Act\n                    Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                    // Assert\n                    Assert.NotNull(task);\n\n                    using (HttpResponseMessage response = await task)\n                    {\n                        Assert.NotNull(response);\n                        Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n                        HttpContent content = response.Content;\n                        ObjectContent<HttpError> typedContent = Assert.IsType<ObjectContent<HttpError>>(content);\n                        HttpError error = (HttpError)typedContent.Value;\n                        Assert.NotNull(error);\n                        Assert.Equal(expectedException.Message, error.ExceptionMessage);\n                        Assert.Equal(expectedException.GetType().FullName, error.ExceptionType);\n                        Assert.Equal(expectedException.StackTrace, error.StackTrace);\n                        Assert.Same(expectedOutputFormatter, typedContent.Formatter);\n                        Assert.NotNull(typedContent.Headers);\n                        Assert.Equal(expectedMediaType, typedContent.Headers.ContentType);\n                        Assert.Same(expectedRequest, response.RequestMessage);\n                    }\n                }\n            }\n        }\n\n        [Fact]\n        public void IncludeErrorDetail_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            {\n                configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;\n                controller.Configuration = configuration;\n\n                using (HttpRequestMessage request = CreateRequest())\n                {\n                    controller.Request = request;\n\n                    ExceptionResult result = CreateProductUnderTest(exception, controller);\n\n                    configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Never;\n\n                    // Act\n                    IContentNegotiator contentNegotiator = result.ContentNegotiator;\n\n                    // Assert\n                    Assert.False(result.IncludeErrorDetail);\n                }\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            {\n                controller.Configuration = configuration;\n\n                using (HttpRequestMessage request = CreateRequest())\n                {\n                    controller.Request = request;\n\n                    ExceptionResult result = CreateProductUnderTest(exception, controller);\n\n                    IContentNegotiator expectedContentNegotiator = CreateDummyContentNegotiator();\n                    configuration.Services.Replace(typeof(IContentNegotiator), expectedContentNegotiator);\n\n                    // Act\n                    IContentNegotiator contentNegotiator = result.ContentNegotiator;\n\n                    // Assert\n                    Assert.Same(expectedContentNegotiator, contentNegotiator);\n                }\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            MediaTypeFormatter formatter = CreateFormatter();\n            MediaTypeHeaderValue mediaType = CreateMediaType();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            {\n                controller.Configuration = configuration;\n                ExceptionResult result = CreateProductUnderTest(exception, controller);\n\n                using (HttpRequestMessage expectedRequest = CreateRequest())\n                {\n                    controller.Request = expectedRequest;\n\n                    // Act\n                    HttpRequestMessage request = result.Request;\n\n                    // Assert\n                    Assert.Same(expectedRequest, request);\n                }\n            }\n        }\n\n        [Fact]\n        public void Formatters_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            ApiController controller = CreateController();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpConfiguration earlyConfiguration = CreateConfiguration(CreateFormatter(), contentNegotiator))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Configuration = earlyConfiguration;\n                controller.Request = request;\n\n                ExceptionResult result = CreateProductUnderTest(exception, controller);\n\n                MediaTypeFormatter expectedFormatter = CreateFormatter();\n\n                using (HttpConfiguration lateConfiguration = CreateConfiguration(expectedFormatter, contentNegotiator))\n                {\n                    controller.Configuration = lateConfiguration;\n\n                    // Act\n                    IEnumerable<MediaTypeFormatter> formatters = result.Formatters;\n\n                    // Assert\n                    Assert.NotNull(formatters);\n                    MediaTypeFormatter formatter = Assert.Single(formatters);\n                    Assert.Same(expectedFormatter, formatter);\n                }\n            }\n        }\n\n        [Fact]\n        public void IncludeErrorDetail_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext requestContext = new HttpRequestContext\n                {\n                    Configuration = configuration,\n                    IncludeErrorDetail = true\n                };\n                controller.RequestContext = requestContext;\n                controller.Request = request;\n\n                ExceptionResult result = CreateProductUnderTest(exception, controller);\n\n                bool ignore = result.IncludeErrorDetail;\n\n                requestContext.IncludeErrorDetail = false;\n\n                // Act\n                bool includeErrorDetail = result.IncludeErrorDetail;\n\n                // Assert\n                Assert.True(includeErrorDetail);\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            IContentNegotiator expectedContentNegotiator = CreateDummyContentNegotiator();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), expectedContentNegotiator))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Configuration = configuration;\n                controller.Request = request;\n\n                ExceptionResult result = CreateProductUnderTest(exception, controller);\n\n                IContentNegotiator ignore = result.ContentNegotiator;\n\n                configuration.Services.Replace(typeof(IContentNegotiator), CreateDummyContentNegotiator());\n\n                // Act\n                IContentNegotiator contentNegotiator = result.ContentNegotiator;\n\n                // Assert\n                Assert.Same(expectedContentNegotiator, contentNegotiator);\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            {\n                controller.Configuration = configuration;\n\n                ExceptionResult result = CreateProductUnderTest(exception, controller);\n\n                using (HttpRequestMessage expectedRequest = CreateRequest())\n                {\n                    controller.Request = expectedRequest;\n                    HttpRequestMessage ignore = result.Request;\n\n                    using (HttpRequestMessage otherRequest = CreateRequest())\n                    {\n                        controller.Request = otherRequest;\n\n                        // Act\n                        HttpRequestMessage request = result.Request;\n\n                        // Assert\n                        Assert.Same(expectedRequest, request);\n                    }\n                }\n            }\n        }\n\n        [Fact]\n        public void Formatters_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            ApiController controller = CreateController();\n            MediaTypeFormatter expectedFormatter = CreateFormatter();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpConfiguration earlyConfiguration = CreateConfiguration(expectedFormatter, contentNegotiator))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Configuration = earlyConfiguration;\n                controller.Request = request;\n\n                ExceptionResult result = CreateProductUnderTest(exception, controller);\n\n                IEnumerable<MediaTypeFormatter> ignore = result.Formatters;\n\n                using (HttpConfiguration lateConfiguration = CreateConfiguration(CreateFormatter(), contentNegotiator))\n                {\n                    controller.Configuration = lateConfiguration;\n\n                    // Act\n                    IEnumerable<MediaTypeFormatter> formatters = result.Formatters;\n\n                    // Assert\n                    Assert.NotNull(formatters);\n                    MediaTypeFormatter formatter = Assert.Single(formatters);\n                    Assert.Same(expectedFormatter, formatter);\n                }\n            }\n        }\n\n        [Fact]\n        public void IncludeErrorDetail_ForApiController_Throws_WhenControllerRequestIsNull()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            ApiController controller = CreateController();\n            Assert.Null(controller.Request);\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            {\n                controller.Configuration = configuration;\n                ExceptionResult result = CreateProductUnderTest(exception, controller);\n\n                // Act & Assert\n                Assert.Throws<InvalidOperationException>(() => { bool ignore = result.IncludeErrorDetail; },\n                    \"ApiController.Request must not be null.\");\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ForApiController_Throws_WhenConfigurationIsNull()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            ApiController controller = CreateController();\n            HttpControllerContext context = new HttpControllerContext();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.ControllerContext = context;\n\n                ExceptionResult result = CreateProductUnderTest(exception, controller);\n\n                // Act & Assert\n                Assert.Throws<InvalidOperationException>(\n                    () => { IContentNegotiator ignore = result.ContentNegotiator; },\n                    \"HttpControllerContext.Configuration must not be null.\");\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ForApiController_Throws_WhenServiceIsNull()\n        {\n            // Arrange\n            Exception exception = CreateException();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), null))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Request = request;\n                controller.Configuration = configuration;\n\n                ExceptionResult result = CreateProductUnderTest(exception, controller);\n\n                // Act & Assert\n                Assert.Throws<InvalidOperationException>(\n                    () => { IContentNegotiator ignore = result.ContentNegotiator; },\n                    \"The provided configuration does not have an instance of the \" +\n                    \"'System.Net.Http.Formatting.IContentNegotiator' service registered.\");\n            }\n        }\n\n        [Fact]\n        public void ApiControllerInternalServerError_WithException_CreatesCorrectResult()\n        {\n            // Arrange\n            Exception expectedException = CreateException();\n            ApiController controller = CreateController();\n\n            // Act\n            ExceptionResult result = controller.InternalServerError(expectedException);\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Same(expectedException, result.Exception);\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Configuration = configuration;\n                controller.Request = expectedRequest;\n                Assert.Same(expectedRequest, result.Request);\n            }\n        }\n\n        private static HttpConfiguration CreateConfiguration(MediaTypeFormatter formatter,\n            IContentNegotiator contentNegotiator)\n        {\n            HttpConfiguration configuration = new HttpConfiguration();\n            configuration.Formatters.Clear();\n            configuration.Formatters.Add(formatter);\n            configuration.Services.Replace(typeof(IContentNegotiator), contentNegotiator);\n            return configuration;\n        }\n\n        private static ApiController CreateController()\n        {\n            return new FakeController();\n        }\n\n        private static IContentNegotiator CreateDummyContentNegotiator()\n        {\n            return new Mock<IContentNegotiator>(MockBehavior.Strict).Object;\n        }\n\n        private static Exception CreateException()\n        {\n            return new Exception();\n        }\n\n        private static Exception CreateExceptionWithStackTrace()\n        {\n            try\n            {\n                throw CreateException();\n            }\n            catch (Exception ex)\n            {\n                return ex;\n            }\n        }\n\n        private static MediaTypeFormatter CreateFormatter()\n        {\n            return new StubMediaTypeFormatter();\n        }\n\n        private static IEnumerable<MediaTypeFormatter> CreateFormatters()\n        {\n            return new MediaTypeFormatter[0];\n        }\n\n        private static MediaTypeHeaderValue CreateMediaType()\n        {\n            return new MediaTypeHeaderValue(\"text/plain\");\n        }\n\n        private static ExceptionResult CreateProductUnderTest(Exception exception, bool includeErrorDetail,\n            IContentNegotiator contentNegotiator, HttpRequestMessage request,\n            IEnumerable<MediaTypeFormatter> formatters)\n        {\n            return new ExceptionResult(exception, includeErrorDetail, contentNegotiator, request, formatters);\n        }\n\n        private static ExceptionResult CreateProductUnderTest(Exception exception, ApiController controller)\n        {\n            return new ExceptionResult(exception, controller);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private class StubMediaTypeFormatter : MediaTypeFormatter\n        {\n            public override bool CanReadType(Type type)\n            {\n                return true;\n            }\n\n            public override bool CanWriteType(Type type)\n            {\n                return true;\n            }\n        }\n\n        private class FakeController : ApiController\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Results/FormattedContentResultTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Results\n{\n    public class FormattedContentResultTests\n    {\n        [Fact]\n        public void Constructor_Throws_WhenFormatterIsNull()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            object content = CreateContent();\n            MediaTypeFormatter formatter = null;\n            MediaTypeHeaderValue mediaType = CreateMediaType();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() =>\n                {\n                    new FormattedContentResult<object>(statusCode, content, formatter, mediaType, request);\n                }, \"formatter\");\n            }\n        }\n\n        [Fact]\n        public void Constructor_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            object content = CreateContent();\n            MediaTypeFormatter formatter = CreateFormatter();\n            MediaTypeHeaderValue mediaType = CreateMediaType();\n            HttpRequestMessage request = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() =>\n            {\n                new FormattedContentResult<object>(statusCode, content, formatter, mediaType, request);\n            }, \"request\");\n        }\n\n        [Fact]\n        public void StatusCode_Returns_ValueProvided()\n        {\n            // Arrange\n            HttpStatusCode expectedStatusCode = CreateStatusCode();\n            object content = CreateContent();\n            MediaTypeFormatter formatter = CreateFormatter();\n            MediaTypeHeaderValue mediaType = CreateMediaType();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                FormattedContentResult<object> result = new FormattedContentResult<object>(expectedStatusCode, content,\n                    formatter, mediaType, request);\n\n                // Act\n                HttpStatusCode statusCode = result.StatusCode;\n\n                // Assert\n                Assert.Equal(expectedStatusCode, statusCode);\n            }\n        }\n\n        [Fact]\n        public void Content_Returns_InstanceProvided()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            object expectedContent = CreateContent();\n            MediaTypeFormatter formatter = CreateFormatter();\n            MediaTypeHeaderValue mediaType = CreateMediaType();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                FormattedContentResult<object> result = new FormattedContentResult<object>(statusCode, expectedContent,\n                    formatter, mediaType, request);\n\n                // Act\n                object content = result.Content;\n\n                // Assert\n                Assert.Same(expectedContent, content);\n            }\n        }\n\n        [Fact]\n        public void Formatter_Returns_InstanceProvided()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            object content = CreateContent();\n            MediaTypeFormatter expectedFormatter = CreateFormatter();\n            MediaTypeHeaderValue mediaType = CreateMediaType();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                FormattedContentResult<object> result = new FormattedContentResult<object>(statusCode, content,\n                    expectedFormatter, mediaType, request);\n\n                // Act\n                MediaTypeFormatter formatter = result.Formatter;\n\n                // Assert\n                Assert.Same(expectedFormatter, formatter);\n            }\n        }\n\n        [Fact]\n        public void MediaType_Returns_InstanceProvided()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            object content = CreateContent();\n            MediaTypeFormatter formatter = CreateFormatter();\n            MediaTypeHeaderValue expectedMediaType = CreateMediaType();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                FormattedContentResult<object> result = new FormattedContentResult<object>(statusCode, content,\n                    formatter, expectedMediaType, request);\n\n                // Act\n                MediaTypeHeaderValue mediaType = result.MediaType;\n\n                // Assert\n                Assert.Same(expectedMediaType, mediaType);\n            }\n        }\n\n        [Fact]\n        public void Request_Returns_InstanceProvided()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            object content = CreateContent();\n            MediaTypeFormatter formatter = CreateFormatter();\n            MediaTypeHeaderValue mediaType = CreateMediaType();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                FormattedContentResult<object> result = new FormattedContentResult<object>(statusCode, content,\n                    formatter, mediaType, expectedRequest);\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Returns_CorrectResponse()\n        {\n            // Arrange\n            HttpStatusCode expectedStatusCode = CreateStatusCode();\n            object expectedContent = CreateContent();\n            MediaTypeFormatter expectedFormatter = CreateFormatter();\n            MediaTypeHeaderValue expectedMediaType = CreateMediaType();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IHttpActionResult result = new FormattedContentResult<object>(expectedStatusCode, expectedContent,\n                    expectedFormatter, expectedMediaType, expectedRequest);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(expectedStatusCode, response.StatusCode);\n                    HttpContent content = response.Content;\n                    ObjectContent<object> typedContent = Assert.IsType<ObjectContent<object>>(content);\n                    Assert.Same(expectedContent, typedContent.Value);\n                    Assert.Same(expectedFormatter, typedContent.Formatter);\n                    Assert.NotNull(typedContent.Headers);\n                    Assert.Equal(expectedMediaType, typedContent.Headers.ContentType);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public void Constructor_ForApiController_Throws_WhenControllerIsNull()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            object content = CreateContent();\n            MediaTypeFormatter formatter = CreateFormatter();\n            MediaTypeHeaderValue mediaType = CreateMediaType();\n            ApiController controller = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() =>\n            {\n                new FormattedContentResult<object>(statusCode, content, formatter, mediaType, controller);\n            }, \"controller\");\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_ForApiController_ReturnsCorrectResponse()\n        {\n            // Arrange\n            HttpStatusCode expectedStatusCode = CreateStatusCode();\n            object expectedContent = CreateContent();\n            MediaTypeFormatter expectedFormatter = CreateFormatter();\n            MediaTypeHeaderValue expectedMediaType = CreateMediaType();\n            ApiController controller = CreateController();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                IHttpActionResult result = new FormattedContentResult<object>(expectedStatusCode, expectedContent,\n                    expectedFormatter, expectedMediaType, controller);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(expectedStatusCode, response.StatusCode);\n                    HttpContent content = response.Content;\n                    ObjectContent<object> typedContent = Assert.IsType<ObjectContent<object>>(content);\n                    Assert.Same(expectedContent, typedContent.Value);\n                    Assert.Same(expectedFormatter, typedContent.Formatter);\n                    Assert.NotNull(typedContent.Headers);\n                    Assert.Equal(expectedMediaType, typedContent.Headers.ContentType);\n                    Assert.Equal(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            object content = CreateContent();\n            MediaTypeFormatter formatter = CreateFormatter();\n            MediaTypeHeaderValue mediaType = CreateMediaType();\n            ApiController controller = CreateController();\n            FormattedContentResult<object> result = new FormattedContentResult<object>(statusCode, content, formatter,\n                mediaType, controller);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            object content = CreateContent();\n            MediaTypeFormatter formatter = CreateFormatter();\n            MediaTypeHeaderValue mediaType = CreateMediaType();\n            ApiController controller = CreateController();\n            FormattedContentResult<object> result = new FormattedContentResult<object>(statusCode, content, formatter,\n                mediaType, controller);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                HttpRequestMessage ignore = result.Request;\n\n                using (HttpRequestMessage otherRequest = CreateRequest())\n                {\n                    controller.Request = otherRequest;\n\n                    // Act\n                    HttpRequestMessage request = result.Request;\n\n                    // Assert\n                    Assert.Same(expectedRequest, request);\n                }\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_Throws_WhenControllerRequestIsNull()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            object content = CreateContent();\n            MediaTypeFormatter formatter = CreateFormatter();\n            MediaTypeHeaderValue mediaType = CreateMediaType();\n            ApiController controller = CreateController();\n            Assert.Null(controller.Request);\n            FormattedContentResult<object> result = new FormattedContentResult<object>(statusCode, content, formatter,\n                mediaType, controller);\n\n            // Act & Assert\n            InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() =>\n                { HttpRequestMessage ignore = result.Request; }, \"ApiController.Request must not be null.\");\n        }\n\n        [Fact]\n        public void ApiControllerContent_WithFormatter_CreatesCorrectFormattedContentResult()\n        {\n            // Arrange\n            HttpStatusCode expectedStatusCode = CreateStatusCode();\n            object expectedContent = CreateContent();\n            MediaTypeFormatter expectedFormatter = CreateFormatter();\n            MediaTypeHeaderValue expectedMediaType = CreateMediaType();\n            ApiController controller = CreateController();\n\n            // Act\n            FormattedContentResult<object> result = controller.Content(expectedStatusCode, expectedContent,\n                expectedFormatter, expectedMediaType);\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Equal(expectedStatusCode, result.StatusCode);\n            Assert.Same(expectedContent, result.Content);\n            Assert.Same(expectedFormatter, result.Formatter);\n            Assert.Same(expectedMediaType, result.MediaType);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                Assert.Same(expectedRequest, result.Request);\n            }\n        }\n\n        [Fact]\n        public void ApiControllerContent_WithFormatterAndStringMediaType_CreatesCorrectFormattedContentResult()\n        {\n            // Arrange\n            HttpStatusCode expectedStatusCode = CreateStatusCode();\n            object expectedContent = CreateContent();\n            MediaTypeFormatter expectedFormatter = CreateFormatter();\n            string expectedMediaType = CreateMediaType().MediaType;\n            ApiController controller = CreateController();\n\n            // Act\n            FormattedContentResult<object> result = controller.Content(expectedStatusCode, expectedContent,\n                expectedFormatter, expectedMediaType);\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Equal(expectedStatusCode, result.StatusCode);\n            Assert.Same(expectedContent, result.Content);\n            Assert.Same(expectedFormatter, result.Formatter);\n            MediaTypeHeaderValue mediaType = result.MediaType;\n            Assert.NotNull(mediaType);\n            Assert.Equal(expectedMediaType, mediaType.MediaType);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                Assert.Same(expectedRequest, result.Request);\n            }\n        }\n\n        [Fact]\n        public void ApiControllerContent_WithFormatterButNotMediaType_CreatesCorrectFormattedContentResult()\n        {\n            // Arrange\n            HttpStatusCode expectedStatusCode = CreateStatusCode();\n            object expectedContent = CreateContent();\n            MediaTypeFormatter expectedFormatter = CreateFormatter();\n            ApiController controller = CreateController();\n\n            // Act\n            FormattedContentResult<object> result = controller.Content(expectedStatusCode, expectedContent,\n                expectedFormatter);\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Equal(expectedStatusCode, result.StatusCode);\n            Assert.Same(expectedContent, result.Content);\n            Assert.Same(expectedFormatter, result.Formatter);\n            Assert.Null(result.MediaType);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                Assert.Same(expectedRequest, result.Request);\n            }\n        }\n\n        private static object CreateContent()\n        {\n            return new object();\n        }\n\n        private static ApiController CreateController()\n        {\n            return new FakeController();\n        }\n\n        private static MediaTypeFormatter CreateFormatter()\n        {\n            return new StubFormatter();\n        }\n\n        private static MediaTypeHeaderValue CreateMediaType()\n        {\n            return new MediaTypeHeaderValue(\"text/plain\");\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private static HttpStatusCode CreateStatusCode()\n        {\n            return HttpStatusCode.Continue;\n        }\n\n        private class StubFormatter : MediaTypeFormatter\n        {\n            public override bool CanReadType(Type type)\n            {\n                return true;\n            }\n\n            public override bool CanWriteType(Type type)\n            {\n                return true;\n            }\n        }\n\n        private class FakeController : ApiController\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Results/InternalServerErrorResultTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Results\n{\n    public class InternalServerErrorResultTests\n    {\n        [Fact]\n        public void Constructor_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            HttpRequestMessage request = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { CreateProductUnderTest(request); }, \"request\");\n        }\n\n        [Fact]\n        public void Request_Returns_InstanceProvided()\n        {\n            // Arrange\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                InternalServerErrorResult result = CreateProductUnderTest(expectedRequest);\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Returns_CorrectResponse()\n        {\n            // Arrange\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IHttpActionResult result = CreateProductUnderTest(expectedRequest);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public void Constructor_ForApiController_Throws_WhenControllerIsNull()\n        {\n            // Arrange\n            ApiController controller = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { CreateProductUnderTest(controller); }, \"controller\");\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_ForApiController_ReturnsCorrectResponse()\n        {\n            // Arrange\n            ApiController controller = CreateController();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                IHttpActionResult result = CreateProductUnderTest(controller);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            ApiController controller = CreateController();\n            InternalServerErrorResult result = CreateProductUnderTest(controller);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            ApiController controller = CreateController();\n            InternalServerErrorResult result = CreateProductUnderTest(controller);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                HttpRequestMessage ignore = result.Request;\n\n                using (HttpRequestMessage otherRequest = CreateRequest())\n                {\n                    controller.Request = otherRequest;\n\n                    // Act\n                    HttpRequestMessage request = result.Request;\n\n                    // Assert\n                    Assert.Same(expectedRequest, request);\n                }\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_Throws_WhenControllerRequestIsNull()\n        {\n            // Arrange\n            ApiController controller = CreateController();\n            Assert.Null(controller.Request);\n            InternalServerErrorResult result = CreateProductUnderTest(controller);\n\n            // Act & Assert\n            InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() =>\n                { HttpRequestMessage ignore = result.Request; }, \"ApiController.Request must not be null.\");\n        }\n\n        [Fact]\n        public void ApiControllerInternalServerError_CreatesCorrectResult()\n        {\n            // Arrange\n            ApiController controller = CreateController();\n\n            // Act\n            InternalServerErrorResult result = controller.InternalServerError();\n\n            // Assert\n            Assert.NotNull(result);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                Assert.Same(expectedRequest, result.Request);\n            }\n        }\n\n        private static ApiController CreateController()\n        {\n            return new FakeController();\n        }\n\n        private static InternalServerErrorResult CreateProductUnderTest(HttpRequestMessage request)\n        {\n            return new InternalServerErrorResult(request);\n        }\n\n        private static InternalServerErrorResult CreateProductUnderTest(ApiController controller)\n        {\n            return new InternalServerErrorResult(controller);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private class FakeController : ApiController\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Results/InvalidModelStateResultTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq.Expressions;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.ModelBinding;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Results\n{\n    public class InvalidModelStateResultTests\n    {\n        [Fact]\n        public void Constructor_Throws_WhenModelStateIsNull()\n        {\n            // Arrange\n            ModelStateDictionary modelState = null;\n            bool includeErrorDetail = true;\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() =>\n                {\n                    CreateProductUnderTest(modelState, includeErrorDetail, contentNegotiator, request, formatters);\n                }, \"modelState\");\n            }\n        }\n\n        [Fact]\n        public void Constructor_Throws_WhenContentNegotiatorIsNull()\n        {\n            // Arrange\n            ModelStateDictionary modelState = CreateModelState();\n            bool includeErrorDetail = true;\n            IContentNegotiator contentNegotiator = null;\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() =>\n                {\n                    CreateProductUnderTest(modelState, includeErrorDetail, contentNegotiator, request, formatters);\n                }, \"contentNegotiator\");\n            }\n        }\n\n        [Fact]\n        public void Constructor_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            ModelStateDictionary modelState = CreateModelState();\n            bool includeErrorDetail = true;\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n            HttpRequestMessage request = null;\n            IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() =>\n            {\n                CreateProductUnderTest(modelState, includeErrorDetail, contentNegotiator, request, formatters);\n            }, \"request\");\n        }\n\n        [Fact]\n        public void Constructor_Throws_WhenFormattersIsNull()\n        {\n            // Arrange\n            ModelStateDictionary modelState = CreateModelState();\n            bool includeErrorDetail = true;\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = null;\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() =>\n                {\n                    CreateProductUnderTest(modelState, includeErrorDetail, contentNegotiator, request, formatters);\n                }, \"formatters\");\n            }\n        }\n\n        [Fact]\n        public void ModelState_ReturnsInstanceProvided()\n        {\n            // Arrange\n            ModelStateDictionary expectedModelState = CreateModelState();\n            bool includeErrorDetail = true;\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                InvalidModelStateResult result = CreateProductUnderTest(expectedModelState, includeErrorDetail,\n                    contentNegotiator, request, formatters);\n\n                // Act\n                ModelStateDictionary modelState = result.ModelState;\n\n                // Assert\n                Assert.Same(expectedModelState, modelState);\n            }\n        }\n\n        [Fact]\n        public void IncludeErrorDetail_ReturnsValueProvided()\n        {\n            // Arrange\n            ModelStateDictionary modelState = CreateModelState();\n            bool expectedIncludeErrorDetail = true;\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                InvalidModelStateResult result = CreateProductUnderTest(modelState, expectedIncludeErrorDetail,\n                    contentNegotiator, request, formatters);\n\n                // Act\n                bool includeErrorDetail = result.IncludeErrorDetail;\n\n                // Assert\n                Assert.Equal(expectedIncludeErrorDetail, includeErrorDetail);\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ReturnsInstanceProvided()\n        {\n            // Arrange\n            ModelStateDictionary modelState = CreateModelState();\n            bool includeErrorDetail = true;\n            IContentNegotiator expectedContentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                InvalidModelStateResult result = CreateProductUnderTest(modelState, includeErrorDetail,\n                    expectedContentNegotiator, request, formatters);\n\n                // Act\n                IContentNegotiator contentNegotiator = result.ContentNegotiator;\n\n                // Assert\n                Assert.Same(expectedContentNegotiator, contentNegotiator);\n            }\n        }\n\n        [Fact]\n        public void Request_ReturnsInstanceProvided()\n        {\n            // Arrange\n            ModelStateDictionary modelState = CreateModelState();\n            bool includeErrorDetail = true;\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                InvalidModelStateResult result = CreateProductUnderTest(modelState, includeErrorDetail,\n                    contentNegotiator, expectedRequest, formatters);\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public void Formatters_ReturnsInstanceProvided()\n        {\n            // Arrange\n            ModelStateDictionary modelState = CreateModelState();\n            bool includeErrorDetail = true;\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();\n\n                InvalidModelStateResult result = CreateProductUnderTest(modelState, includeErrorDetail,\n                    contentNegotiator, request, expectedFormatters);\n\n                // Act\n                IEnumerable<MediaTypeFormatter> formatters = result.Formatters;\n\n                // Assert\n                Assert.Same(expectedFormatters, formatters);\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_ReturnsCorrectResponse_WhenContentNegotiationSucceedsAndIncludeErrorDetailIsTrue()\n        {\n            // Arrange\n            ModelStateDictionary modelState = CreateModelState();\n            string expectedModelStateKey = \"ModelStateKey\";\n            string expectedModelStateExceptionMessage = \"ModelStateExceptionMessage\";\n            modelState.AddModelError(expectedModelStateKey, new InvalidOperationException(\n                expectedModelStateExceptionMessage));\n            bool includeErrorDetail = true;\n            MediaTypeFormatter expectedFormatter = CreateFormatter();\n            MediaTypeHeaderValue expectedMediaType = CreateMediaType();\n            ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedFormatter,\n                expectedMediaType);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();\n\n                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();\n                spy.Setup(n => n.Negotiate(typeof(HttpError), expectedRequest, expectedFormatters)).Returns(\n                    negotiationResult);\n                IContentNegotiator contentNegotiator = spy.Object;\n\n                IHttpActionResult result = CreateProductUnderTest(modelState, includeErrorDetail, contentNegotiator,\n                    expectedRequest, expectedFormatters);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);\n                    HttpContent content = response.Content;\n                    ObjectContent<HttpError> typedContent = Assert.IsType<ObjectContent<HttpError>>(content);\n                    HttpError error = (HttpError)typedContent.Value;\n                    Assert.NotNull(error);\n                    HttpError modelStateError = error.ModelState;\n                    Assert.NotNull(modelStateError);\n                    Assert.True(modelState.ContainsKey(expectedModelStateKey));\n                    object modelStateValue = modelStateError[expectedModelStateKey];\n                    string[] typedModelStateValues = Assert.IsType<string[]>(modelStateValue);\n                    string typedModelStateValue = Assert.Single(typedModelStateValues);\n                    Assert.Same(expectedModelStateExceptionMessage, typedModelStateValue);\n                    Assert.Same(expectedFormatter, typedContent.Formatter);\n                    Assert.NotNull(typedContent.Headers);\n                    Assert.Equal(expectedMediaType, typedContent.Headers.ContentType);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_ReturnsCorrectResponse_WhenContentNegotiationSucceedsAndIncludeErrorDetailIsFalse()\n        {\n            // Arrange\n            ModelStateDictionary modelState = CreateModelState();\n            string expectedModelStateKey = \"ModelStateKey\";\n            string expectedModelStateErrorMessage = \"ModelStateErrorMessage\";\n            ModelState originalModelStateItem = new ModelState();\n            originalModelStateItem.Errors.Add(new ModelError(new InvalidOperationException(),\n                expectedModelStateErrorMessage));\n            modelState.Add(expectedModelStateKey, originalModelStateItem);\n            bool includeErrorDetail = false;\n            MediaTypeFormatter expectedFormatter = CreateFormatter();\n            MediaTypeHeaderValue expectedMediaType = CreateMediaType();\n            ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedFormatter,\n                expectedMediaType);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();\n\n                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();\n                spy.Setup(n => n.Negotiate(typeof(HttpError), expectedRequest, expectedFormatters)).Returns(\n                    negotiationResult);\n                IContentNegotiator contentNegotiator = spy.Object;\n\n                IHttpActionResult result = CreateProductUnderTest(modelState, includeErrorDetail, contentNegotiator,\n                    expectedRequest, expectedFormatters);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);\n                    HttpContent content = response.Content;\n                    ObjectContent<HttpError> typedContent = Assert.IsType<ObjectContent<HttpError>>(content);\n                    HttpError error = (HttpError)typedContent.Value;\n                    Assert.NotNull(error);\n                    HttpError modelStateError = error.ModelState;\n                    Assert.NotNull(modelStateError);\n                    Assert.True(modelState.ContainsKey(expectedModelStateKey));\n                    object modelStateValue = modelStateError[expectedModelStateKey];\n                    string[] typedModelStateValues = Assert.IsType<string[]>(modelStateValue);\n                    string typedModelStateValue = Assert.Single(typedModelStateValues);\n                    Assert.Same(expectedModelStateErrorMessage, typedModelStateValue);\n                    Assert.Same(expectedFormatter, typedContent.Formatter);\n                    Assert.NotNull(typedContent.Headers);\n                    Assert.Equal(expectedMediaType, typedContent.Headers.ContentType);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_ReturnsCorrectResponse_WhenContentNegotiationFails()\n        {\n            // Arrange\n            ModelStateDictionary modelState = CreateModelStateWithError();\n            bool includeErrorDetail = true;\n            ContentNegotiationResult negotiationResult = null;\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();\n\n                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();\n                spy.Setup(n => n.Negotiate(typeof(ModelStateDictionary), expectedRequest, expectedFormatters)).Returns(\n                    negotiationResult);\n                IContentNegotiator contentNegotiator = spy.Object;\n\n                IHttpActionResult result = CreateProductUnderTest(modelState, includeErrorDetail, contentNegotiator,\n                    expectedRequest, expectedFormatters);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public void Constructor_ForApiController_Throws_WhenControllerIsNull()\n        {\n            // Arrange\n            ModelStateDictionary modelState = CreateModelState();\n            ApiController controller = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { CreateProductUnderTest(modelState, controller); }, \"controller\");\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_ForApiController_ReturnsCorrectResponse_WhenContentNegotationSucceeds()\n        {\n            // Arrange\n            ModelStateDictionary modelState = CreateModelState();\n            string expectedModelStateKey = \"ModelStateKey\";\n            string expectedModelStateExceptionMessage = \"ModelStateExceptionMessage\";\n            modelState.AddModelError(expectedModelStateKey, new InvalidOperationException(\n                expectedModelStateExceptionMessage));\n            ApiController controller = CreateController();\n            MediaTypeFormatter expectedInputFormatter = CreateFormatter();\n            MediaTypeFormatter expectedOutputFormatter = CreateFormatter();\n            MediaTypeHeaderValue expectedMediaType = CreateMediaType();\n            ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedOutputFormatter,\n                expectedMediaType);\n\n            Expression<Func<IEnumerable<MediaTypeFormatter>, bool>> formattersMatch = (f) =>\n                f != null && f.AsArray().Length == 1 && f.AsArray()[0] == expectedInputFormatter;\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();\n                spy.Setup(n => n.Negotiate(typeof(HttpError), expectedRequest, It.Is(formattersMatch))).Returns(\n                    negotiationResult);\n                IContentNegotiator contentNegotiator = spy.Object;\n\n                using (HttpConfiguration configuration = CreateConfiguration(expectedInputFormatter,\n                    contentNegotiator))\n                {\n                    controller.RequestContext = new HttpRequestContext\n                    {\n                        Configuration = configuration,\n                        IncludeErrorDetail = true\n                    };\n                    controller.Request = expectedRequest;\n\n                    IHttpActionResult result = CreateProductUnderTest(modelState, controller);\n\n                    // Act\n                    Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                    // Assert\n                    Assert.NotNull(task);\n\n                    using (HttpResponseMessage response = await task)\n                    {\n                        Assert.NotNull(response);\n                        Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);\n                        HttpContent content = response.Content;\n                        ObjectContent<HttpError> typedContent = Assert.IsType<ObjectContent<HttpError>>(content);\n                        HttpError error = (HttpError)typedContent.Value;\n                        Assert.NotNull(error);\n                        HttpError modelStateError = error.ModelState;\n                        Assert.NotNull(modelStateError);\n                        Assert.True(modelState.ContainsKey(expectedModelStateKey));\n                        object modelStateValue = modelStateError[expectedModelStateKey];\n                        string[] typedModelStateValues = Assert.IsType<string[]>(modelStateValue);\n                        string typedModelStateValue = Assert.Single(typedModelStateValues);\n                        Assert.Same(expectedModelStateExceptionMessage, typedModelStateValue);\n                        Assert.Same(expectedOutputFormatter, typedContent.Formatter);\n                        Assert.NotNull(typedContent.Headers);\n                        Assert.Equal(expectedMediaType, typedContent.Headers.ContentType);\n                        Assert.Same(expectedRequest, response.RequestMessage);\n                    }\n                }\n            }\n        }\n\n        [Fact]\n        public void IncludeErrorDetail_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            ModelStateDictionary modelState = CreateModelState();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            {\n                configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;\n                controller.Configuration = configuration;\n\n                using (HttpRequestMessage request = CreateRequest())\n                {\n                    controller.Request = request;\n\n                    InvalidModelStateResult result = CreateProductUnderTest(modelState, controller);\n\n                    configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Never;\n\n                    // Act\n                    IContentNegotiator contentNegotiator = result.ContentNegotiator;\n\n                    // Assert\n                    Assert.False(result.IncludeErrorDetail);\n                }\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            ModelStateDictionary modelState = CreateModelState();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            {\n                controller.Configuration = configuration;\n\n                using (HttpRequestMessage request = CreateRequest())\n                {\n                    controller.Request = request;\n\n                    InvalidModelStateResult result = CreateProductUnderTest(modelState, controller);\n\n                    IContentNegotiator expectedContentNegotiator = CreateDummyContentNegotiator();\n                    configuration.Services.Replace(typeof(IContentNegotiator), expectedContentNegotiator);\n\n                    // Act\n                    IContentNegotiator contentNegotiator = result.ContentNegotiator;\n\n                    // Assert\n                    Assert.Same(expectedContentNegotiator, contentNegotiator);\n                }\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            ModelStateDictionary modelState = CreateModelState();\n            MediaTypeFormatter formatter = CreateFormatter();\n            MediaTypeHeaderValue mediaType = CreateMediaType();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            {\n                controller.Configuration = configuration;\n                InvalidModelStateResult result = CreateProductUnderTest(modelState, controller);\n\n                using (HttpRequestMessage expectedRequest = CreateRequest())\n                {\n                    controller.Request = expectedRequest;\n\n                    // Act\n                    HttpRequestMessage request = result.Request;\n\n                    // Assert\n                    Assert.Same(expectedRequest, request);\n                }\n            }\n        }\n\n        [Fact]\n        public void Formatters_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            ModelStateDictionary modelState = CreateModelState();\n            ApiController controller = CreateController();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpConfiguration earlyConfiguration = CreateConfiguration(CreateFormatter(), contentNegotiator))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Configuration = earlyConfiguration;\n                controller.Request = request;\n\n                InvalidModelStateResult result = CreateProductUnderTest(modelState, controller);\n\n                MediaTypeFormatter expectedFormatter = CreateFormatter();\n\n                using (HttpConfiguration lateConfiguration = CreateConfiguration(expectedFormatter, contentNegotiator))\n                {\n                    controller.Configuration = lateConfiguration;\n\n                    // Act\n                    IEnumerable<MediaTypeFormatter> formatters = result.Formatters;\n\n                    // Assert\n                    Assert.NotNull(formatters);\n                    MediaTypeFormatter formatter = Assert.Single(formatters);\n                    Assert.Same(expectedFormatter, formatter);\n                }\n            }\n        }\n\n        [Fact]\n        public void IncludeErrorDetail_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            ModelStateDictionary modelState = CreateModelState();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext requestContext = new HttpRequestContext\n                {\n                    Configuration = configuration,\n                    IncludeErrorDetail = true\n                };\n                controller.RequestContext = requestContext;\n                controller.Request = request;\n\n                InvalidModelStateResult result = CreateProductUnderTest(modelState, controller);\n\n                bool ignore = result.IncludeErrorDetail;\n\n                requestContext.IncludeErrorDetail = false;\n\n                // Act\n                bool includeErrorDetail = result.IncludeErrorDetail;\n\n                // Assert\n                Assert.True(includeErrorDetail);\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            ModelStateDictionary modelState = CreateModelState();\n            IContentNegotiator expectedContentNegotiator = CreateDummyContentNegotiator();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), expectedContentNegotiator))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Configuration = configuration;\n                controller.Request = request;\n\n                InvalidModelStateResult result = CreateProductUnderTest(modelState, controller);\n\n                IContentNegotiator ignore = result.ContentNegotiator;\n\n                configuration.Services.Replace(typeof(IContentNegotiator), CreateDummyContentNegotiator());\n\n                // Act\n                IContentNegotiator contentNegotiator = result.ContentNegotiator;\n\n                // Assert\n                Assert.Same(expectedContentNegotiator, contentNegotiator);\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            ModelStateDictionary modelState = CreateModelState();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            {\n                controller.Configuration = configuration;\n\n                InvalidModelStateResult result = CreateProductUnderTest(modelState, controller);\n\n                using (HttpRequestMessage expectedRequest = CreateRequest())\n                {\n                    controller.Request = expectedRequest;\n                    HttpRequestMessage ignore = result.Request;\n\n                    using (HttpRequestMessage otherRequest = CreateRequest())\n                    {\n                        controller.Request = otherRequest;\n\n                        // Act\n                        HttpRequestMessage request = result.Request;\n\n                        // Assert\n                        Assert.Same(expectedRequest, request);\n                    }\n                }\n            }\n        }\n\n        [Fact]\n        public void Formatters_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            ModelStateDictionary modelState = CreateModelState();\n            ApiController controller = CreateController();\n            MediaTypeFormatter expectedFormatter = CreateFormatter();\n            IContentNegotiator contentNegotiator = CreateDummyContentNegotiator();\n\n            using (HttpConfiguration earlyConfiguration = CreateConfiguration(expectedFormatter, contentNegotiator))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Configuration = earlyConfiguration;\n                controller.Request = request;\n\n                InvalidModelStateResult result = CreateProductUnderTest(modelState, controller);\n\n                IEnumerable<MediaTypeFormatter> ignore = result.Formatters;\n\n                using (HttpConfiguration lateConfiguration = CreateConfiguration(CreateFormatter(), contentNegotiator))\n                {\n                    controller.Configuration = lateConfiguration;\n\n                    // Act\n                    IEnumerable<MediaTypeFormatter> formatters = result.Formatters;\n\n                    // Assert\n                    Assert.NotNull(formatters);\n                    MediaTypeFormatter formatter = Assert.Single(formatters);\n                    Assert.Same(expectedFormatter, formatter);\n                }\n            }\n        }\n\n        [Fact]\n        public void IncludeErrorDetail_ForApiController_Throws_WhenControllerRequestIsNull()\n        {\n            // Arrange\n            ModelStateDictionary modelState = CreateModelState();\n            ApiController controller = CreateController();\n            Assert.Null(controller.Request);\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            {\n                controller.Configuration = configuration;\n                InvalidModelStateResult result = CreateProductUnderTest(modelState, controller);\n\n                // Act & Assert\n                InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() =>\n                    { bool ignore = result.IncludeErrorDetail; }, \"ApiController.Request must not be null.\");\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ForApiController_Throws_WhenConfigurationIsNull()\n        {\n            // Arrange\n            ModelStateDictionary modelState = CreateModelState();\n            ApiController controller = CreateController();\n            HttpControllerContext context = new HttpControllerContext();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.ControllerContext = context;\n\n                InvalidModelStateResult result = CreateProductUnderTest(modelState, controller);\n\n                // Act & Assert\n                Assert.Throws<InvalidOperationException>(\n                    () => { IContentNegotiator ignore = result.ContentNegotiator; },\n                    \"HttpControllerContext.Configuration must not be null.\");\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ForApiController_Throws_WhenServiceIsNull()\n        {\n            // Arrange\n            ModelStateDictionary modelState = CreateModelState();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), null))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Request = request;\n                controller.Configuration = configuration;\n\n                InvalidModelStateResult result = CreateProductUnderTest(modelState, controller);\n\n                // Act & Assert\n                Assert.Throws<InvalidOperationException>(\n                    () => { IContentNegotiator ignore = result.ContentNegotiator; },\n                    \"The provided configuration does not have an instance of the \" +\n                    \"'System.Net.Http.Formatting.IContentNegotiator' service registered.\");\n            }\n        }\n\n        [Fact]\n        public void ApiControllerBadRequest_WithModelStateDictionary_CreatesCorrectResult()\n        {\n            // Arrange\n            ModelStateDictionary expectedModelState = CreateModelState();\n            ApiController controller = CreateController();\n\n            // Act\n            InvalidModelStateResult result = controller.BadRequest(expectedModelState);\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Same(expectedModelState, result.ModelState);\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(),\n                CreateDummyContentNegotiator()))\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Configuration = configuration;\n                controller.Request = expectedRequest;\n                Assert.Same(expectedRequest, result.Request);\n            }\n        }\n\n        private static HttpConfiguration CreateConfiguration(MediaTypeFormatter formatter,\n            IContentNegotiator contentNegotiator)\n        {\n            HttpConfiguration configuration = new HttpConfiguration();\n            configuration.Formatters.Clear();\n            configuration.Formatters.Add(formatter);\n            configuration.Services.Replace(typeof(IContentNegotiator), contentNegotiator);\n            return configuration;\n        }\n\n        private static ApiController CreateController()\n        {\n            return new FakeController();\n        }\n\n        private static IContentNegotiator CreateDummyContentNegotiator()\n        {\n            return new Mock<IContentNegotiator>(MockBehavior.Strict).Object;\n        }\n\n        private static MediaTypeFormatter CreateFormatter()\n        {\n            return new StubMediaTypeFormatter();\n        }\n\n        private static IEnumerable<MediaTypeFormatter> CreateFormatters()\n        {\n            return new MediaTypeFormatter[0];\n        }\n\n        private static MediaTypeHeaderValue CreateMediaType()\n        {\n            return new MediaTypeHeaderValue(\"text/plain\");\n        }\n\n        private static ModelStateDictionary CreateModelState()\n        {\n            return new ModelStateDictionary();\n        }\n\n        private static ModelStateDictionary CreateModelStateWithError()\n        {\n            ModelStateDictionary modelState = new ModelStateDictionary();\n            modelState.AddModelError(String.Empty, String.Empty);\n            return modelState;\n        }\n\n        private static InvalidModelStateResult CreateProductUnderTest(ModelStateDictionary modelState,\n            bool includeErrorDetail, IContentNegotiator contentNegotiator, HttpRequestMessage request,\n            IEnumerable<MediaTypeFormatter> formatters)\n        {\n            return new InvalidModelStateResult(modelState, includeErrorDetail, contentNegotiator,\n                request, formatters);\n        }\n\n        private static InvalidModelStateResult CreateProductUnderTest(ModelStateDictionary modelState,\n            ApiController controller)\n        {\n            return new InvalidModelStateResult(modelState, controller);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private class StubMediaTypeFormatter : MediaTypeFormatter\n        {\n            public override bool CanReadType(Type type)\n            {\n                return true;\n            }\n\n            public override bool CanWriteType(Type type)\n            {\n                return true;\n            }\n        }\n\n        private class FakeController : ApiController\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Results/JsonResultTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.IO;\nusing System.Net;\nusing System.Net.Http;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Moq;\nusing Newtonsoft.Json;\n\nnamespace System.Web.Http.Results\n{\n    public class JsonResultTests\n    {\n        [Fact]\n        public void Constructor_Throws_WhenSerializerSettingsIsNull()\n        {\n            // Arrange\n            object content = CreateContent();\n            JsonSerializerSettings serializerSettings = null;\n            Encoding encoding = CreateDummyEncoding();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() =>\n                {\n                    CreateProductUnderTest(content, serializerSettings, encoding, request);\n                }, \"serializerSettings\");\n            }\n        }\n\n        [Fact]\n        public void Constructor_Throws_WhenEncodingIsNull()\n        {\n            // Arrange\n            object content = CreateContent();\n            JsonSerializerSettings serializerSettings = CreateSerializerSettings();\n            Encoding encoding = null;\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() =>\n                {\n                    CreateProductUnderTest(content, serializerSettings, encoding, request);\n                }, \"encoding\");\n            }\n        }\n\n        [Fact]\n        public void Constructor_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            object content = CreateContent();\n            JsonSerializerSettings serializerSettings = CreateSerializerSettings();\n            Encoding encoding = CreateDummyEncoding();\n            HttpRequestMessage request = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() =>\n            {\n                CreateProductUnderTest(content, serializerSettings, encoding, request);\n            }, \"request\");\n        }\n\n        [Fact]\n        public void Content_Returns_InstanceProvided()\n        {\n            // Arrange\n            object expectedContent = CreateContent();\n            JsonSerializerSettings serializerSettings = CreateSerializerSettings();\n            Encoding encoding = CreateDummyEncoding();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                JsonResult<object> result = CreateProductUnderTest(expectedContent, serializerSettings, encoding,\n                    request);\n\n                // Act\n                object content = result.Content;\n\n                // Assert\n                Assert.Same(expectedContent, content);\n            }\n        }\n\n        [Fact]\n        public void SerializerSettings_Returns_InstanceProvided()\n        {\n            // Arrange\n            object content = CreateContent();\n            JsonSerializerSettings expectedSerializerSettings = CreateSerializerSettings();\n            Encoding encoding = CreateDummyEncoding();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                JsonResult<object> result = CreateProductUnderTest(content, expectedSerializerSettings, encoding,\n                    request);\n\n                // Act\n                JsonSerializerSettings serializerSettings = result.SerializerSettings;\n\n                // Assert\n                Assert.Same(expectedSerializerSettings, serializerSettings);\n            }\n        }\n\n        [Fact]\n        public void Encoding_Returns_InstanceProvided()\n        {\n            // Arrange\n            object content = CreateContent();\n            JsonSerializerSettings serializerSettings = CreateSerializerSettings();\n            Encoding expectedEncoding = CreateDummyEncoding();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                JsonResult<object> result = CreateProductUnderTest(content, serializerSettings, expectedEncoding,\n                    request);\n\n                // Act\n                Encoding encoding = result.Encoding;\n\n                // Assert\n                Assert.Same(expectedEncoding, encoding);\n            }\n        }\n\n        [Fact]\n        public void Request_Returns_InstanceProvided()\n        {\n            // Arrange\n            object content = CreateContent();\n            JsonSerializerSettings serializerSettings = CreateSerializerSettings();\n            Encoding encoding = CreateDummyEncoding();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                JsonResult<object> result = CreateProductUnderTest(content, serializerSettings, encoding,\n                    expectedRequest);\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Returns_CorrectResponse()\n        {\n            // Arrange\n            string[] content = new string[] { \"Content\" };\n            JsonSerializerSettings serializerSettings = CreateSerializerSettings();\n            Encoding encoding = CreateEncoding();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IHttpActionResult result = CreateProductUnderTest(content, serializerSettings, encoding,\n                    expectedRequest);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);\n                    Assert.NotNull(response.Content);\n                    Assert.NotNull(response.Content.Headers.ContentType);\n                    Assert.Equal(\"application/json\", response.Content.Headers.ContentType.MediaType);\n                    Assert.Equal(encoding.WebName, response.Content.Headers.ContentType.CharSet);\n                    Assert.IsType<ByteArrayContent>(response.Content);\n                    StringBuilder expectedBuilder = new StringBuilder();\n                    using (TextWriter textWriter = new StringWriter(expectedBuilder, CultureInfo.InvariantCulture))\n                    {\n                        JsonSerializer serializer = JsonSerializer.Create(serializerSettings);\n\n                        using (JsonWriter jsonWriter = new JsonTextWriter(textWriter))\n                        {\n                            serializer.Serialize(jsonWriter, content);\n                            jsonWriter.Flush();\n                        }\n                    }\n                    byte[] expectedContents = encoding.GetBytes(expectedBuilder.ToString());\n                    byte[] contents = await response.Content.ReadAsByteArrayAsync();\n                    Assert.Equal(expectedContents, contents);\n                    Assert.True(response.Content.Headers.ContentLength.HasValue);\n                    Assert.Equal((long)expectedContents.Length, response.Content.Headers.ContentLength.Value);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public void Constructor_ForApiController_Throws_WhenControllerIsNull()\n        {\n            // Arrange\n            object content = CreateContent();\n            JsonSerializerSettings serializerSettings = CreateSerializerSettings();\n            Encoding encoding = CreateDummyEncoding();\n            ApiController controller = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() =>\n            {\n                CreateProductUnderTest(content, serializerSettings, encoding, controller);\n            }, \"controller\");\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_ForApiController_ReturnsCorrectResponse()\n        {\n            // Arrange\n            string[] content = new string[] { \"Content\" };\n            JsonSerializerSettings serializerSettings = CreateSerializerSettings();\n            Encoding encoding = CreateEncoding();\n            ApiController controller = CreateController();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                IHttpActionResult result = CreateProductUnderTest(content, serializerSettings, encoding, controller);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);\n                    Assert.NotNull(response.Content);\n                    Assert.NotNull(response.Content.Headers.ContentType);\n                    Assert.Equal(\"application/json\", response.Content.Headers.ContentType.MediaType);\n                    Assert.Equal(encoding.WebName, response.Content.Headers.ContentType.CharSet);\n                    Assert.IsType<ByteArrayContent>(response.Content);\n                    StringBuilder expectedBuilder = new StringBuilder();\n                    using (TextWriter textWriter = new StringWriter(expectedBuilder, CultureInfo.InvariantCulture))\n                    {\n                        JsonSerializer serializer = JsonSerializer.Create(serializerSettings);\n\n                        using (JsonWriter jsonWriter = new JsonTextWriter(textWriter))\n                        {\n                            serializer.Serialize(jsonWriter, content);\n                            jsonWriter.Flush();\n                        }\n                    }\n                    byte[] expectedContents = encoding.GetBytes(expectedBuilder.ToString());\n                    byte[] contents = await response.Content.ReadAsByteArrayAsync();\n                    Assert.Equal(expectedContents, contents);\n                    Assert.True(response.Content.Headers.ContentLength.HasValue);\n                    Assert.Equal((long)expectedContents.Length, response.Content.Headers.ContentLength.Value);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            object content = CreateContent();\n            JsonSerializerSettings serializerSettings = CreateSerializerSettings();\n            Encoding encoding = CreateDummyEncoding();\n            ApiController controller = CreateController();\n            JsonResult<object> result = CreateProductUnderTest(content, serializerSettings, encoding, controller);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            object content = CreateContent();\n            JsonSerializerSettings serializerSettings = CreateSerializerSettings();\n            Encoding encoding = CreateDummyEncoding();\n            ApiController controller = CreateController();\n            JsonResult<object> result = CreateProductUnderTest(content, serializerSettings, encoding, controller);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                HttpRequestMessage ignore = result.Request;\n\n                using (HttpRequestMessage otherRequest = CreateRequest())\n                {\n                    controller.Request = otherRequest;\n\n                    // Act\n                    HttpRequestMessage request = result.Request;\n\n                    // Assert\n                    Assert.Same(expectedRequest, request);\n                }\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_Throws_WhenControllerRequestIsNull()\n        {\n            // Arrange\n            object content = CreateContent();\n            JsonSerializerSettings serializerSettings = CreateSerializerSettings();\n            Encoding encoding = CreateDummyEncoding();\n            ApiController controller = CreateController();\n            Assert.Null(controller.Request);\n            JsonResult<object> result = CreateProductUnderTest(content, serializerSettings, encoding, controller);\n\n            // Act & Assert\n            InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() =>\n                { HttpRequestMessage ignore = result.Request; }, \"ApiController.Request must not be null.\");\n        }\n\n        [Fact]\n        public void ApiControllerJson_WithObjectJsonSerializerSettingsAndEncoding_CreatesCorrectResult()\n        {\n            // Arrange\n            object expectedContent = CreateContent();\n            JsonSerializerSettings expectedSerializerSettings = CreateSerializerSettings();\n            Encoding expectedEncoding = CreateDummyEncoding();\n            ApiController controller = CreateController();\n\n            // Act\n            JsonResult<object> result = controller.Json(expectedContent, expectedSerializerSettings, expectedEncoding);\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Same(expectedContent, result.Content);\n            Assert.Same(expectedSerializerSettings, result.SerializerSettings);\n            Assert.Same(expectedEncoding, result.Encoding);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                Assert.Same(expectedRequest, result.Request);\n            }\n        }\n\n        [Fact]\n        public void ApiControllerJson_WithObjectAndJsonSerializerSettings_CreatesCorrectResult()\n        {\n            // Arrange\n            object expectedContent = CreateContent();\n            JsonSerializerSettings expectedSerializerSettings = CreateSerializerSettings();\n            ApiController controller = CreateController();\n\n            // Act\n            JsonResult<object> result = controller.Json(expectedContent, expectedSerializerSettings);\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Same(expectedContent, result.Content);\n            Assert.Same(expectedSerializerSettings, result.SerializerSettings);\n            Encoding expectedEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false,\n                throwOnInvalidBytes: true);\n            Assert.Equal(expectedEncoding, result.Encoding);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                Assert.Same(expectedRequest, result.Request);\n            }\n        }\n\n        [Fact]\n        public void ApiControllerJson_WithObject_CreatesCorrectResult()\n        {\n            // Arrange\n            object expectedContent = CreateContent();\n            ApiController controller = CreateController();\n\n            // Act\n            JsonResult<object> result = controller.Json(expectedContent);\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Same(expectedContent, result.Content);\n            Assert.NotNull(result.SerializerSettings);\n            Encoding expectedEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false,\n                throwOnInvalidBytes: true);\n            Assert.Equal(expectedEncoding, result.Encoding);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                Assert.Same(expectedRequest, result.Request);\n            }\n        }\n\n        private static object CreateContent()\n        {\n            return new object();\n        }\n\n        private static ApiController CreateController()\n        {\n            return new FakeController();\n        }\n\n        private static Encoding CreateDummyEncoding()\n        {\n            return new Mock<Encoding>(MockBehavior.Strict).Object;\n        }\n\n        private static Encoding CreateEncoding()\n        {\n            return new ASCIIEncoding();\n        }\n\n        private static JsonResult<T> CreateProductUnderTest<T>(T content, JsonSerializerSettings serializerSettings,\n            Encoding encoding, HttpRequestMessage request)\n        {\n            return new JsonResult<T>(content, serializerSettings, encoding, request);\n        }\n\n        private static JsonResult<T> CreateProductUnderTest<T>(T content, JsonSerializerSettings serializerSettings,\n            Encoding encoding, ApiController controller)\n        {\n            return new JsonResult<T>(content, serializerSettings, encoding, controller);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private static JsonSerializerSettings CreateSerializerSettings()\n        {\n            return new JsonSerializerSettings();\n        }\n\n        private class FakeController : ApiController\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Results/NegotiatedContentResultTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq.Expressions;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Results\n{\n    public class NegotiatedContentResultTests\n    {\n        [Fact]\n        public void Constructor_Throws_WhenContentNegotiatorIsNull()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            object content = CreateContent();\n            IContentNegotiator contentNegotiator = null;\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() =>\n                {\n                    new NegotiatedContentResult<object>(statusCode, content, contentNegotiator, request, formatters);\n                }, \"contentNegotiator\");\n            }\n        }\n\n        [Fact]\n        public void Constructor_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            object content = CreateContent();\n            IContentNegotiator contentNegotiator = CreateContentNegotiator();\n            HttpRequestMessage request = null;\n            IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() =>\n            {\n                new NegotiatedContentResult<object>(statusCode, content, contentNegotiator, request, formatters);\n            }, \"request\");\n        }\n\n        [Fact]\n        public void Constructor_Throws_WhenFormattersIsNull()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            object content = CreateContent();\n            IContentNegotiator contentNegotiator = CreateContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = null;\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() =>\n                {\n                    new NegotiatedContentResult<object>(statusCode, content, contentNegotiator, request, formatters);\n                }, \"formatters\");\n            }\n        }\n\n        [Fact]\n        public void StatusCode_Returns_ValueProvided()\n        {\n            // Arrange\n            HttpStatusCode expectedStatusCode = CreateStatusCode();\n            object content = CreateContent();\n            IContentNegotiator contentNegotiator = CreateContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                NegotiatedContentResult<object> result = new NegotiatedContentResult<object>(expectedStatusCode,\n                    content, contentNegotiator, request, formatters);\n\n                // Act\n                HttpStatusCode statusCode = result.StatusCode;\n\n                // Assert\n                Assert.Equal(expectedStatusCode, statusCode);\n            }\n        }\n\n        [Fact]\n        public void Content_Returns_InstanceProvided()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            object expectedContent = CreateContent();\n            IContentNegotiator contentNegotiator = CreateContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                NegotiatedContentResult<object> result = new NegotiatedContentResult<object>(statusCode,\n                    expectedContent, contentNegotiator, request, formatters);\n\n                // Act\n                object content = result.Content;\n\n                // Assert\n                Assert.Same(expectedContent, content);\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_Returns_InstanceProvided()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            object content = CreateContent();\n            IContentNegotiator expectedContentNegotiator = CreateContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                NegotiatedContentResult<object> result = new NegotiatedContentResult<object>(statusCode, content,\n                    expectedContentNegotiator, request, formatters);\n\n                // Act\n                IContentNegotiator contentNegotiator = result.ContentNegotiator;\n\n                // Assert\n                Assert.Same(expectedContentNegotiator, contentNegotiator);\n            }\n        }\n\n        [Fact]\n        public void Request_Returns_InstanceProvided()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            object content = CreateContent();\n            IContentNegotiator contentNegotiator = CreateContentNegotiator();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                NegotiatedContentResult<object> result = new NegotiatedContentResult<object>(statusCode, content,\n                    contentNegotiator, expectedRequest, formatters);\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public void Formatters_Returns_InstanceProvided()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            object content = CreateContent();\n            IContentNegotiator contentNegotiator = CreateContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();\n\n                NegotiatedContentResult<object> result = new NegotiatedContentResult<object>(statusCode, content,\n                    contentNegotiator, request, expectedFormatters);\n\n                // Act\n                IEnumerable<MediaTypeFormatter> formatters = result.Formatters;\n\n                // Assert\n                Assert.Same(expectedFormatters, formatters);\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Returns_CorrectResponse_WhenContentNegotiationSucceeds()\n        {\n            // Arrange\n            HttpStatusCode expectedStatusCode = CreateStatusCode();\n            object expectedContent = CreateContent();\n            MediaTypeFormatter expectedFormatter = CreateFormatter();\n            MediaTypeHeaderValue expectedMediaType = CreateMediaType();\n            ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedFormatter, expectedMediaType);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();\n\n                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();\n                spy.Setup(n => n.Negotiate(typeof(object), expectedRequest, expectedFormatters)).Returns(\n                    negotiationResult);\n                IContentNegotiator contentNegotiator = spy.Object;\n\n                IHttpActionResult result = new NegotiatedContentResult<object>(expectedStatusCode, expectedContent,\n                    contentNegotiator, expectedRequest, expectedFormatters);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(expectedStatusCode, response.StatusCode);\n                    HttpContent content = response.Content;\n                    ObjectContent<object> typedContent = Assert.IsType<ObjectContent<object>>(content);\n                    Assert.Same(expectedContent, typedContent.Value);\n                    Assert.Same(expectedFormatter, typedContent.Formatter);\n                    Assert.NotNull(typedContent.Headers);\n                    Assert.Equal(expectedMediaType, typedContent.Headers.ContentType);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Returns_CorrectResponse_WhenContentNegotiationFails()\n        {\n            // Arrange\n            HttpStatusCode statusCode = HttpStatusCode.Conflict;\n            object content = CreateContent();\n            ContentNegotiationResult negotiationResult = null;\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();\n\n                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();\n                spy.Setup(n => n.Negotiate(typeof(object), expectedRequest, expectedFormatters)).Returns(\n                    negotiationResult);\n                IContentNegotiator contentNegotiator = spy.Object;\n\n                IHttpActionResult result = new NegotiatedContentResult<object>(statusCode, content, contentNegotiator,\n                    expectedRequest, expectedFormatters);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public void Constructor_ForApiController_Throws_WhenControllerIsNull()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            object content = CreateContent();\n            ApiController controller = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() =>\n            {\n                new NegotiatedContentResult<object>(statusCode, content, controller);\n            }, \"controller\");\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_ForApiController_ReturnsCorrectResponse_WhenContentNegotationSucceeds()\n        {\n            // Arrange\n            HttpStatusCode expectedStatusCode = CreateStatusCode();\n            object expectedContent = CreateContent();\n            ApiController controller = CreateController();\n            MediaTypeFormatter expectedInputFormatter = CreateFormatter();\n            MediaTypeFormatter expectedOutputFormatter = CreateFormatter();\n            MediaTypeHeaderValue expectedMediaType = CreateMediaType();\n            ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedOutputFormatter,\n                expectedMediaType);\n\n            Expression<Func<IEnumerable<MediaTypeFormatter>, bool>> formattersMatch = (f) =>\n                f != null && f.AsArray().Length == 1 && f.AsArray()[0] == expectedInputFormatter;\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();\n                spy.Setup(n => n.Negotiate(typeof(object), expectedRequest, It.Is(formattersMatch))).Returns(\n                    negotiationResult);\n                IContentNegotiator contentNegotiator = spy.Object;\n\n                using (HttpConfiguration configuration = CreateConfiguration(expectedInputFormatter,\n                    contentNegotiator))\n                {\n                    controller.Configuration = configuration;\n                    controller.Request = expectedRequest;\n\n                    IHttpActionResult result = new NegotiatedContentResult<object>(expectedStatusCode, expectedContent,\n                        controller);\n\n                    // Act\n                    Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                    // Assert\n                    Assert.NotNull(task);\n\n                    using (HttpResponseMessage response = await task)\n                    {\n                        Assert.NotNull(response);\n                        Assert.Equal(expectedStatusCode, response.StatusCode);\n                        HttpContent content = response.Content;\n                        ObjectContent<object> typedContent = Assert.IsType<ObjectContent<object>>(content);\n                        Assert.Same(expectedContent, typedContent.Value);\n                        Assert.Same(expectedOutputFormatter, typedContent.Formatter);\n                        Assert.NotNull(typedContent.Headers);\n                        Assert.Equal(expectedMediaType, typedContent.Headers.ContentType);\n                        Assert.Same(expectedRequest, response.RequestMessage);\n                    }\n                }\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            object content = CreateContent();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), CreateContentNegotiator()))\n            {\n                controller.Configuration = configuration;\n\n                using (HttpRequestMessage request = CreateRequest())\n                {\n                    controller.Request = request;\n\n                    NegotiatedContentResult<object> result = new NegotiatedContentResult<object>(statusCode, content,\n                        controller);\n\n                    IContentNegotiator expectedContentNegotiator = CreateContentNegotiator();\n                    configuration.Services.Replace(typeof(IContentNegotiator), expectedContentNegotiator);\n\n                    // Act\n                    IContentNegotiator contentNegotiator = result.ContentNegotiator;\n\n                    // Assert\n                    Assert.Same(expectedContentNegotiator, contentNegotiator);\n                }\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            object content = CreateContent();\n            MediaTypeFormatter formatter = CreateFormatter();\n            MediaTypeHeaderValue mediaType = CreateMediaType();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), CreateContentNegotiator()))\n            {\n                controller.Configuration = configuration;\n                NegotiatedContentResult<object> result = new NegotiatedContentResult<object>(statusCode, content,\n                    controller);\n\n                using (HttpRequestMessage expectedRequest = CreateRequest())\n                {\n                    controller.Request = expectedRequest;\n\n                    // Act\n                    HttpRequestMessage request = result.Request;\n\n                    // Assert\n                    Assert.Same(expectedRequest, request);\n                }\n            }\n        }\n\n        [Fact]\n        public void Formatters_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            object content = CreateContent();\n            ApiController controller = CreateController();\n            IContentNegotiator contentNegotiator = CreateContentNegotiator();\n\n            using (HttpConfiguration earlyConfiguration = CreateConfiguration(CreateFormatter(), contentNegotiator))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Configuration = earlyConfiguration;\n                controller.Request = request;\n\n                NegotiatedContentResult<object> result = new NegotiatedContentResult<object>(statusCode, content,\n                    controller);\n\n                MediaTypeFormatter expectedFormatter = CreateFormatter();\n\n                using (HttpConfiguration lateConfiguration = CreateConfiguration(expectedFormatter, contentNegotiator))\n                {\n                    controller.Configuration = lateConfiguration;\n\n                    // Act\n                    IEnumerable<MediaTypeFormatter> formatters = result.Formatters;\n\n                    // Assert\n                    Assert.NotNull(formatters);\n                    MediaTypeFormatter formatter = Assert.Single(formatters);\n                    Assert.Same(expectedFormatter, formatter);\n                }\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            object content = CreateContent();\n            IContentNegotiator expectedContentNegotiator = CreateContentNegotiator();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), expectedContentNegotiator))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Configuration = configuration;\n                controller.Request = request;\n\n                NegotiatedContentResult<object> result = new NegotiatedContentResult<object>(statusCode, content,\n                    controller);\n\n                IContentNegotiator ignore = result.ContentNegotiator;\n\n                configuration.Services.Replace(typeof(IContentNegotiator), CreateContentNegotiator());\n\n                // Act\n                IContentNegotiator contentNegotiator = result.ContentNegotiator;\n\n                // Assert\n                Assert.Same(expectedContentNegotiator, contentNegotiator);\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            object content = CreateContent();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), CreateContentNegotiator()))\n            {\n                controller.Configuration = configuration;\n\n                NegotiatedContentResult<object> result = new NegotiatedContentResult<object>(statusCode, content,\n                    controller);\n\n                using (HttpRequestMessage expectedRequest = CreateRequest())\n                {\n                    controller.Request = expectedRequest;\n                    HttpRequestMessage ignore = result.Request;\n\n                    using (HttpRequestMessage otherRequest = CreateRequest())\n                    {\n                        controller.Request = otherRequest;\n\n                        // Act\n                        HttpRequestMessage request = result.Request;\n\n                        // Assert\n                        Assert.Same(expectedRequest, request);\n                    }\n                }\n            }\n        }\n\n        [Fact]\n        public void Formatters_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            object content = CreateContent();\n            ApiController controller = CreateController();\n            MediaTypeFormatter expectedFormatter = CreateFormatter();\n            IContentNegotiator contentNegotiator = CreateContentNegotiator();\n\n            using (HttpConfiguration earlyConfiguration = CreateConfiguration(expectedFormatter, contentNegotiator))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Configuration = earlyConfiguration;\n                controller.Request = request;\n\n                NegotiatedContentResult<object> result = new NegotiatedContentResult<object>(statusCode, content,\n                    controller);\n\n                IEnumerable<MediaTypeFormatter> ignore = result.Formatters;\n\n                using (HttpConfiguration lateConfiguration = CreateConfiguration(CreateFormatter(), contentNegotiator))\n                {\n                    controller.Configuration = lateConfiguration;\n\n                    // Act\n                    IEnumerable<MediaTypeFormatter> formatters = result.Formatters;\n\n                    // Assert\n                    Assert.NotNull(formatters);\n                    MediaTypeFormatter formatter = Assert.Single(formatters);\n                    Assert.Same(expectedFormatter, formatter);\n                }\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ForApiController_Throws_WhenConfigurationIsNull()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            object content = CreateContent();\n            ApiController controller = CreateController();\n            HttpControllerContext context = new HttpControllerContext();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.ControllerContext = context;\n\n                NegotiatedContentResult<object> result = new NegotiatedContentResult<object>(statusCode, content,\n                    controller);\n\n                // Act & Assert\n                Assert.Throws<InvalidOperationException>(\n                    () => { IContentNegotiator ignore = result.ContentNegotiator; },\n                    \"HttpControllerContext.Configuration must not be null.\");\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ForApiController_Throws_WhenServiceIsNull()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            object content = CreateContent();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), null))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Configuration = configuration;\n\n                NegotiatedContentResult<object> result = new NegotiatedContentResult<object>(statusCode, content,\n                    controller);\n\n                // Act & Assert\n                Assert.Throws<InvalidOperationException>(\n                    () => { IContentNegotiator ignore = result.ContentNegotiator; },\n                    \"The provided configuration does not have an instance of the \" +\n                    \"'System.Net.Http.Formatting.IContentNegotiator' service registered.\");\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_Throws_WhenControllerRequestIsNull()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            object content = CreateContent();\n            ApiController controller = CreateController();\n            Assert.Null(controller.Request);\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), CreateContentNegotiator()))\n            {\n                controller.Configuration = configuration;\n                NegotiatedContentResult<object> result = new NegotiatedContentResult<object>(statusCode, content,\n                    controller);\n\n                // Act & Assert\n                InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() =>\n                    { HttpRequestMessage ignore = result.Request; }, \"ApiController.Request must not be null.\");\n            }\n        }\n\n        [Fact]\n        public void ApiControllerContent_WithContent_CreatesCorrectNegotiatedContentResult()\n        {\n            // Arrange\n            HttpStatusCode expectedStatusCode = CreateStatusCode();\n            object expectedContent = CreateContent();\n            ApiController controller = CreateController();\n\n            // Act\n            NegotiatedContentResult<object> result = controller.Content(expectedStatusCode, expectedContent);\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Equal(expectedStatusCode, result.StatusCode);\n            Assert.Same(expectedContent, result.Content);\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), CreateContentNegotiator()))\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Configuration = configuration;\n                controller.Request = expectedRequest;\n                Assert.Same(expectedRequest, result.Request);\n            }\n        }\n\n        private static HttpConfiguration CreateConfiguration(MediaTypeFormatter formatter,\n            IContentNegotiator contentNegotiator)\n        {\n            HttpConfiguration configuration = new HttpConfiguration();\n            configuration.Formatters.Clear();\n            configuration.Formatters.Add(formatter);\n            configuration.Services.Replace(typeof(IContentNegotiator), contentNegotiator);\n            return configuration;\n        }\n\n        private static object CreateContent()\n        {\n            return new object();\n        }\n\n        private static IContentNegotiator CreateContentNegotiator()\n        {\n            return new DummyContentNegotiator();\n        }\n\n        private static ApiController CreateController()\n        {\n            return new FakeController();\n        }\n\n        private static MediaTypeFormatter CreateFormatter()\n        {\n            return new StubMediaTypeFormatter();\n        }\n\n        private static IEnumerable<MediaTypeFormatter> CreateFormatters()\n        {\n            return new MediaTypeFormatter[0];\n        }\n\n        private static MediaTypeHeaderValue CreateMediaType()\n        {\n            return new MediaTypeHeaderValue(\"text/plain\");\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private static HttpStatusCode CreateStatusCode()\n        {\n            return HttpStatusCode.Continue;\n        }\n\n        private class DummyContentNegotiator : IContentNegotiator\n        {\n            public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request,\n                IEnumerable<MediaTypeFormatter> formatters)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class StubMediaTypeFormatter : MediaTypeFormatter\n        {\n            public override bool CanReadType(Type type)\n            {\n                return true;\n            }\n\n            public override bool CanWriteType(Type type)\n            {\n                return true;\n            }\n        }\n\n        private class FakeController : ApiController\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Results/NotFoundResultTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Results\n{\n    public class NotFoundResultTests\n    {\n        [Fact]\n        public void Constructor_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            HttpRequestMessage request = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { CreateProductUnderTest(request); }, \"request\");\n        }\n\n        [Fact]\n        public void Request_Returns_InstanceProvided()\n        {\n            // Arrange\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                NotFoundResult result = CreateProductUnderTest(expectedRequest);\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Returns_CorrectResponse()\n        {\n            // Arrange\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IHttpActionResult result = CreateProductUnderTest(expectedRequest);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public void Constructor_ForApiController_Throws_WhenControllerIsNull()\n        {\n            // Arrange\n            ApiController controller = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { CreateProductUnderTest(controller); }, \"controller\");\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_ForApiController_ReturnsCorrectResponse()\n        {\n            // Arrange\n            ApiController controller = CreateController();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                IHttpActionResult result = CreateProductUnderTest(controller);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            ApiController controller = CreateController();\n            NotFoundResult result = CreateProductUnderTest(controller);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            ApiController controller = CreateController();\n            NotFoundResult result = CreateProductUnderTest(controller);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                HttpRequestMessage ignore = result.Request;\n\n                using (HttpRequestMessage otherRequest = CreateRequest())\n                {\n                    controller.Request = otherRequest;\n\n                    // Act\n                    HttpRequestMessage request = result.Request;\n\n                    // Assert\n                    Assert.Same(expectedRequest, request);\n                }\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_Throws_WhenControllerRequestIsNull()\n        {\n            // Arrange\n            ApiController controller = CreateController();\n            Assert.Null(controller.Request);\n            NotFoundResult result = CreateProductUnderTest(controller);\n\n            // Act & Assert\n            InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() =>\n                { HttpRequestMessage ignore = result.Request; }, \"ApiController.Request must not be null.\");\n        }\n\n        [Fact]\n        public void ApiControllerNotFound_CreatesCorrectResult()\n        {\n            // Arrange\n            ApiController controller = CreateController();\n\n            // Act\n            NotFoundResult result = controller.NotFound();\n\n            // Assert\n            Assert.NotNull(result);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                Assert.Same(expectedRequest, result.Request);\n            }\n        }\n\n        private static ApiController CreateController()\n        {\n            return new FakeController();\n        }\n\n        private static NotFoundResult CreateProductUnderTest(HttpRequestMessage request)\n        {\n            return new NotFoundResult(request);\n        }\n\n        private static NotFoundResult CreateProductUnderTest(ApiController controller)\n        {\n            return new NotFoundResult(controller);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private class FakeController : ApiController\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Results/OkNegotiatedContentResultTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq.Expressions;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Results\n{\n    public class OkNegotiatedContentResultTests\n    {\n        [Fact]\n        public void Constructor_Throws_WhenContentNegotiatorIsNull()\n        {\n            // Arrange\n            object content = CreateContent();\n            IContentNegotiator contentNegotiator = null;\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() =>\n                {\n                    CreateProductUnderTest(content, contentNegotiator, request, formatters);\n                }, \"contentNegotiator\");\n            }\n        }\n\n        [Fact]\n        public void Constructor_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            object content = CreateContent();\n            IContentNegotiator contentNegotiator = CreateContentNegotiator();\n            HttpRequestMessage request = null;\n            IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() =>\n            {\n                CreateProductUnderTest(content, contentNegotiator, request, formatters);\n            }, \"request\");\n        }\n\n        [Fact]\n        public void Constructor_Throws_WhenFormattersIsNull()\n        {\n            // Arrange\n            object content = CreateContent();\n            IContentNegotiator contentNegotiator = CreateContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = null;\n\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() =>\n                {\n                    CreateProductUnderTest(content, contentNegotiator, request, formatters);\n                }, \"formatters\");\n            }\n        }\n\n        [Fact]\n        public void Content_Returns_InstanceProvided()\n        {\n            // Arrange\n            object expectedContent = CreateContent();\n            IContentNegotiator contentNegotiator = CreateContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                OkNegotiatedContentResult<object> result = CreateProductUnderTest(expectedContent, contentNegotiator,\n                    request, formatters);\n\n                // Act\n                object content = result.Content;\n\n                // Assert\n                Assert.Same(expectedContent, content);\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_Returns_InstanceProvided()\n        {\n            // Arrange\n            object content = CreateContent();\n            IContentNegotiator expectedContentNegotiator = CreateContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                OkNegotiatedContentResult<object> result = CreateProductUnderTest(content, expectedContentNegotiator,\n                    request, formatters);\n\n                // Act\n                IContentNegotiator contentNegotiator = result.ContentNegotiator;\n\n                // Assert\n                Assert.Same(expectedContentNegotiator, contentNegotiator);\n            }\n        }\n\n        [Fact]\n        public void Request_Returns_InstanceProvided()\n        {\n            // Arrange\n            object content = CreateContent();\n            IContentNegotiator contentNegotiator = CreateContentNegotiator();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> formatters = CreateFormatters();\n\n                OkNegotiatedContentResult<object> result = CreateProductUnderTest(content, contentNegotiator,\n                    expectedRequest, formatters);\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public void Formatters_Returns_InstanceProvided()\n        {\n            // Arrange\n            object content = CreateContent();\n            IContentNegotiator contentNegotiator = CreateContentNegotiator();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();\n\n                OkNegotiatedContentResult<object> result = CreateProductUnderTest(content, contentNegotiator, request,\n                    expectedFormatters);\n\n                // Act\n                IEnumerable<MediaTypeFormatter> formatters = result.Formatters;\n\n                // Assert\n                Assert.Same(expectedFormatters, formatters);\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Returns_CorrectResponse_WhenContentNegotiationSucceeds()\n        {\n            // Arrange\n            object expectedContent = CreateContent();\n            MediaTypeFormatter expectedFormatter = CreateFormatter();\n            MediaTypeHeaderValue expectedMediaType = CreateMediaType();\n            ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedFormatter, expectedMediaType);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();\n\n                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();\n                spy.Setup(n => n.Negotiate(typeof(object), expectedRequest, expectedFormatters)).Returns(\n                    negotiationResult);\n                IContentNegotiator contentNegotiator = spy.Object;\n\n                IHttpActionResult result = CreateProductUnderTest(expectedContent, contentNegotiator, expectedRequest,\n                    expectedFormatters);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);\n                    HttpContent content = response.Content;\n                    ObjectContent<object> typedContent = Assert.IsType<ObjectContent<object>>(content);\n                    Assert.Same(expectedContent, typedContent.Value);\n                    Assert.Same(expectedFormatter, typedContent.Formatter);\n                    Assert.NotNull(typedContent.Headers);\n                    Assert.Equal(expectedMediaType, typedContent.Headers.ContentType);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Returns_CorrectResponse_WhenContentNegotiationFails()\n        {\n            // Arrange\n            object content = CreateContent();\n            ContentNegotiationResult negotiationResult = null;\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();\n\n                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();\n                spy.Setup(n => n.Negotiate(typeof(object), expectedRequest, expectedFormatters)).Returns(\n                    negotiationResult);\n                IContentNegotiator contentNegotiator = spy.Object;\n\n                IHttpActionResult result = CreateProductUnderTest(content, contentNegotiator, expectedRequest,\n                    expectedFormatters);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public void Constructor_ForApiController_Throws_WhenControllerIsNull()\n        {\n            // Arrange\n            object content = CreateContent();\n            ApiController controller = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() =>\n            {\n                CreateProductUnderTest(content, controller);\n            }, \"controller\");\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_ForApiController_ReturnsCorrectResponse_WhenContentNegotationSucceeds()\n        {\n            // Arrange\n            object expectedContent = CreateContent();\n            ApiController controller = CreateController();\n            MediaTypeFormatter expectedInputFormatter = CreateFormatter();\n            MediaTypeFormatter expectedOutputFormatter = CreateFormatter();\n            MediaTypeHeaderValue expectedMediaType = CreateMediaType();\n            ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedOutputFormatter,\n                expectedMediaType);\n\n            Expression<Func<IEnumerable<MediaTypeFormatter>, bool>> formattersMatch = (f) =>\n                f != null && f.AsArray().Length == 1 && f.AsArray()[0] == expectedInputFormatter;\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();\n                spy.Setup(n => n.Negotiate(typeof(object), expectedRequest, It.Is(formattersMatch))).Returns(\n                    negotiationResult);\n                IContentNegotiator contentNegotiator = spy.Object;\n\n                using (HttpConfiguration configuration = CreateConfiguration(expectedInputFormatter,\n                    contentNegotiator))\n                {\n                    controller.Configuration = configuration;\n                    controller.Request = expectedRequest;\n\n                    IHttpActionResult result = CreateProductUnderTest(expectedContent, controller);\n\n                    // Act\n                    Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                    // Assert\n                    Assert.NotNull(task);\n\n                    using (HttpResponseMessage response = await task)\n                    {\n                        Assert.NotNull(response);\n                        Assert.Equal(HttpStatusCode.OK, response.StatusCode);\n                        HttpContent content = response.Content;\n                        ObjectContent<object> typedContent = Assert.IsType<ObjectContent<object>>(content);\n                        Assert.Same(expectedContent, typedContent.Value);\n                        Assert.Same(expectedOutputFormatter, typedContent.Formatter);\n                        Assert.NotNull(typedContent.Headers);\n                        Assert.Equal(expectedMediaType, typedContent.Headers.ContentType);\n                        Assert.Same(expectedRequest, response.RequestMessage);\n                    }\n                }\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            object content = CreateContent();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), CreateContentNegotiator()))\n            {\n                controller.Configuration = configuration;\n\n                using (HttpRequestMessage request = CreateRequest())\n                {\n                    controller.Request = request;\n\n                    OkNegotiatedContentResult<object> result = CreateProductUnderTest(content, controller);\n\n                    IContentNegotiator expectedContentNegotiator = CreateContentNegotiator();\n                    configuration.Services.Replace(typeof(IContentNegotiator), expectedContentNegotiator);\n\n                    // Act\n                    IContentNegotiator contentNegotiator = result.ContentNegotiator;\n\n                    // Assert\n                    Assert.Same(expectedContentNegotiator, contentNegotiator);\n                }\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            object content = CreateContent();\n            MediaTypeFormatter formatter = CreateFormatter();\n            MediaTypeHeaderValue mediaType = CreateMediaType();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), CreateContentNegotiator()))\n            {\n                controller.Configuration = configuration;\n                OkNegotiatedContentResult<object> result = CreateProductUnderTest(content, controller);\n\n                using (HttpRequestMessage expectedRequest = CreateRequest())\n                {\n                    controller.Request = expectedRequest;\n\n                    // Act\n                    HttpRequestMessage request = result.Request;\n\n                    // Assert\n                    Assert.Same(expectedRequest, request);\n                }\n            }\n        }\n\n        [Fact]\n        public void Formatters_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            object content = CreateContent();\n            ApiController controller = CreateController();\n            IContentNegotiator contentNegotiator = CreateContentNegotiator();\n\n            using (HttpConfiguration earlyConfiguration = CreateConfiguration(CreateFormatter(), contentNegotiator))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Configuration = earlyConfiguration;\n                controller.Request = request;\n\n                OkNegotiatedContentResult<object> result = CreateProductUnderTest(content, controller);\n\n                MediaTypeFormatter expectedFormatter = CreateFormatter();\n\n                using (HttpConfiguration lateConfiguration = CreateConfiguration(expectedFormatter, contentNegotiator))\n                {\n                    controller.Configuration = lateConfiguration;\n\n                    // Act\n                    IEnumerable<MediaTypeFormatter> formatters = result.Formatters;\n\n                    // Assert\n                    Assert.NotNull(formatters);\n                    MediaTypeFormatter formatter = Assert.Single(formatters);\n                    Assert.Same(expectedFormatter, formatter);\n                }\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            object content = CreateContent();\n            IContentNegotiator expectedContentNegotiator = CreateContentNegotiator();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), expectedContentNegotiator))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Configuration = configuration;\n                controller.Request = request;\n\n                OkNegotiatedContentResult<object> result = CreateProductUnderTest(content, controller);\n\n                IContentNegotiator ignore = result.ContentNegotiator;\n\n                configuration.Services.Replace(typeof(IContentNegotiator), CreateContentNegotiator());\n\n                // Act\n                IContentNegotiator contentNegotiator = result.ContentNegotiator;\n\n                // Assert\n                Assert.Same(expectedContentNegotiator, contentNegotiator);\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            object content = CreateContent();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), CreateContentNegotiator()))\n            {\n                controller.Configuration = configuration;\n\n                OkNegotiatedContentResult<object> result = CreateProductUnderTest(content, controller);\n\n                using (HttpRequestMessage expectedRequest = CreateRequest())\n                {\n                    controller.Request = expectedRequest;\n                    HttpRequestMessage ignore = result.Request;\n\n                    using (HttpRequestMessage otherRequest = CreateRequest())\n                    {\n                        controller.Request = otherRequest;\n\n                        // Act\n                        HttpRequestMessage request = result.Request;\n\n                        // Assert\n                        Assert.Same(expectedRequest, request);\n                    }\n                }\n            }\n        }\n\n        [Fact]\n        public void Formatters_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            object content = CreateContent();\n            ApiController controller = CreateController();\n            MediaTypeFormatter expectedFormatter = CreateFormatter();\n            IContentNegotiator contentNegotiator = CreateContentNegotiator();\n\n            using (HttpConfiguration earlyConfiguration = CreateConfiguration(expectedFormatter, contentNegotiator))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Configuration = earlyConfiguration;\n                controller.Request = request;\n\n                OkNegotiatedContentResult<object> result = CreateProductUnderTest(content, controller);\n\n                IEnumerable<MediaTypeFormatter> ignore = result.Formatters;\n\n                using (HttpConfiguration lateConfiguration = CreateConfiguration(CreateFormatter(), contentNegotiator))\n                {\n                    controller.Configuration = lateConfiguration;\n\n                    // Act\n                    IEnumerable<MediaTypeFormatter> formatters = result.Formatters;\n\n                    // Assert\n                    Assert.NotNull(formatters);\n                    MediaTypeFormatter formatter = Assert.Single(formatters);\n                    Assert.Same(expectedFormatter, formatter);\n                }\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ForApiController_Throws_WhenConfigurationIsNull()\n        {\n            // Arrange\n            object content = CreateContent();\n            ApiController controller = CreateController();\n            HttpControllerContext context = new HttpControllerContext();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.ControllerContext = context;\n\n                OkNegotiatedContentResult<object> result = CreateProductUnderTest(content, controller);\n\n                // Act & Assert\n                Assert.Throws<InvalidOperationException>(\n                    () => { IContentNegotiator ignore = result.ContentNegotiator; },\n                    \"HttpControllerContext.Configuration must not be null.\");\n            }\n        }\n\n        [Fact]\n        public void ContentNegotiator_ForApiController_Throws_WhenServiceIsNull()\n        {\n            // Arrange\n            object content = CreateContent();\n            ApiController controller = CreateController();\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), null))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Configuration = configuration;\n\n                OkNegotiatedContentResult<object> result = CreateProductUnderTest(content, controller);\n\n                // Act & Assert\n                Assert.Throws<InvalidOperationException>(\n                    () => { IContentNegotiator ignore = result.ContentNegotiator; },\n                    \"The provided configuration does not have an instance of the \" +\n                    \"'System.Net.Http.Formatting.IContentNegotiator' service registered.\");\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_Throws_WhenControllerRequestIsNull()\n        {\n            // Arrange\n            object content = CreateContent();\n            ApiController controller = CreateController();\n            Assert.Null(controller.Request);\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), CreateContentNegotiator()))\n            {\n                controller.Configuration = configuration;\n                OkNegotiatedContentResult<object> result = CreateProductUnderTest(content, controller);\n\n                // Act & Assert\n                InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() =>\n                    { HttpRequestMessage ignore = result.Request; }, \"ApiController.Request must not be null.\");\n            }\n        }\n\n        [Fact]\n        public void ApiControllerOk_WithContent_CreatesCorrectResult()\n        {\n            // Arrange\n            object expectedContent = CreateContent();\n            ApiController controller = CreateController();\n\n            // Act\n            OkNegotiatedContentResult<object> result = controller.Ok(expectedContent);\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Same(expectedContent, result.Content);\n\n            using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), CreateContentNegotiator()))\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Configuration = configuration;\n                controller.Request = expectedRequest;\n                Assert.Same(expectedRequest, result.Request);\n            }\n        }\n\n        private static HttpConfiguration CreateConfiguration(MediaTypeFormatter formatter,\n            IContentNegotiator contentNegotiator)\n        {\n            HttpConfiguration configuration = new HttpConfiguration();\n            configuration.Formatters.Clear();\n            configuration.Formatters.Add(formatter);\n            configuration.Services.Replace(typeof(IContentNegotiator), contentNegotiator);\n            return configuration;\n        }\n\n        private static object CreateContent()\n        {\n            return new object();\n        }\n\n        private static IContentNegotiator CreateContentNegotiator()\n        {\n            return new DummyContentNegotiator();\n        }\n\n        private static ApiController CreateController()\n        {\n            return new FakeController();\n        }\n\n        private static MediaTypeFormatter CreateFormatter()\n        {\n            return new StubMediaTypeFormatter();\n        }\n\n        private static IEnumerable<MediaTypeFormatter> CreateFormatters()\n        {\n            return new MediaTypeFormatter[0];\n        }\n\n        private static MediaTypeHeaderValue CreateMediaType()\n        {\n            return new MediaTypeHeaderValue(\"text/plain\");\n        }\n\n        private static OkNegotiatedContentResult<object> CreateProductUnderTest(object content,\n            IContentNegotiator contentNegotiator, HttpRequestMessage request,\n            IEnumerable<MediaTypeFormatter> formatters)\n        {\n            return new OkNegotiatedContentResult<object>(content, contentNegotiator, request, formatters);\n        }\n\n        private static OkNegotiatedContentResult<object> CreateProductUnderTest(object content,\n            ApiController controller)\n        {\n            return new OkNegotiatedContentResult<object>(content, controller);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private class DummyContentNegotiator : IContentNegotiator\n        {\n            public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request,\n                IEnumerable<MediaTypeFormatter> formatters)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class StubMediaTypeFormatter : MediaTypeFormatter\n        {\n            public override bool CanReadType(Type type)\n            {\n                return true;\n            }\n\n            public override bool CanWriteType(Type type)\n            {\n                return true;\n            }\n        }\n\n        private class FakeController : ApiController\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Results/OkResultTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Results\n{\n    public class OkResultTests\n    {\n        [Fact]\n        public void Constructor_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            HttpRequestMessage request = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { CreateProductUnderTest(request); }, \"request\");\n        }\n\n        [Fact]\n        public void Request_Returns_InstanceProvided()\n        {\n            // Arrange\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                OkResult result = CreateProductUnderTest(expectedRequest);\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Returns_CorrectResponse()\n        {\n            // Arrange\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IHttpActionResult result = CreateProductUnderTest(expectedRequest);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public void Constructor_ForApiController_Throws_WhenControllerIsNull()\n        {\n            // Arrange\n            ApiController controller = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { CreateProductUnderTest(controller); }, \"controller\");\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_ForApiController_ReturnsCorrectResponse()\n        {\n            // Arrange\n            ApiController controller = CreateController();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                IHttpActionResult result = CreateProductUnderTest(controller);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            ApiController controller = CreateController();\n            OkResult result = CreateProductUnderTest(controller);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            ApiController controller = CreateController();\n            OkResult result = CreateProductUnderTest(controller);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                HttpRequestMessage ignore = result.Request;\n\n                using (HttpRequestMessage otherRequest = CreateRequest())\n                {\n                    controller.Request = otherRequest;\n\n                    // Act\n                    HttpRequestMessage request = result.Request;\n\n                    // Assert\n                    Assert.Same(expectedRequest, request);\n                }\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_Throws_WhenControllerRequestIsNull()\n        {\n            // Arrange\n            ApiController controller = CreateController();\n            Assert.Null(controller.Request);\n            OkResult result = CreateProductUnderTest(controller);\n\n            // Act & Assert\n            InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() =>\n                { HttpRequestMessage ignore = result.Request; }, \"ApiController.Request must not be null.\");\n        }\n\n        [Fact]\n        public void ApiControllerOk_CreatesCorrectResult()\n        {\n            // Arrange\n            ApiController controller = CreateController();\n\n            // Act\n            OkResult result = controller.Ok();\n\n            // Assert\n            Assert.NotNull(result);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                Assert.Same(expectedRequest, result.Request);\n            }\n        }\n\n        private static ApiController CreateController()\n        {\n            return new FakeController();\n        }\n\n        private static OkResult CreateProductUnderTest(HttpRequestMessage request)\n        {\n            return new OkResult(request);\n        }\n\n        private static OkResult CreateProductUnderTest(ApiController controller)\n        {\n            return new OkResult(controller);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private class FakeController : ApiController\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Results/RedirectResultTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Results\n{\n    public class RedirectResultTests\n    {\n        [Fact]\n        public void Constructor_Throws_WhenLocationIsNull()\n        {\n            // Arrange\n            Uri location = null;\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() => { CreateProductUnderTest(location, request); }, \"location\");\n            }\n        }\n\n        [Fact]\n        public void Constructor_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            Uri location = CreateLocation();\n            HttpRequestMessage request = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { CreateProductUnderTest(location, request); }, \"request\");\n        }\n\n        [Fact]\n        public void Location_Returns_InstanceProvided()\n        {\n            // Arrange\n            Uri expectedLocation = CreateLocation();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                RedirectResult result = CreateProductUnderTest(expectedLocation, request);\n\n                // Act\n                Uri location = result.Location;\n\n                // Assert\n                Assert.Same(expectedLocation, location);\n            }\n        }\n\n        [Fact]\n        public void Request_Returns_InstanceProvided()\n        {\n            // Arrange\n            Uri location = CreateLocation();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                RedirectResult result = CreateProductUnderTest(location, expectedRequest);\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Returns_CorrectResponse()\n        {\n            // Arrange\n            Uri expectedLocation = CreateLocation();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IHttpActionResult result = CreateProductUnderTest(expectedLocation, expectedRequest);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);\n                    Assert.Same(expectedLocation, response.Headers.Location);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public void Constructor_ForApiController_Throws_WhenControllerIsNull()\n        {\n            // Arrange\n            Uri location = CreateLocation();\n            ApiController controller = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { CreateProductUnderTest(location, controller); }, \"controller\");\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_ForApiController_ReturnsCorrectResponse()\n        {\n            // Arrange\n            Uri expectedLocation = CreateLocation();\n            ApiController controller = CreateController();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n\n                IHttpActionResult result = CreateProductUnderTest(expectedLocation, controller);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);\n                    Assert.Same(expectedLocation, response.Headers.Location);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            Uri location = CreateLocation();\n            ApiController controller = CreateController();\n            RedirectResult result = CreateProductUnderTest(location, controller);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            Uri location = CreateLocation();\n            ApiController controller = CreateController();\n            RedirectResult result = CreateProductUnderTest(location, controller);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                HttpRequestMessage ignore = result.Request;\n\n                using (HttpRequestMessage otherRequest = CreateRequest())\n                {\n                    controller.Request = otherRequest;\n\n                    // Act\n                    HttpRequestMessage request = result.Request;\n\n                    // Assert\n                    Assert.Same(expectedRequest, request);\n                }\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_Throws_WhenControllerRequestIsNull()\n        {\n            // Arrange\n            Uri location = CreateLocation();\n            ApiController controller = CreateController();\n            Assert.Null(controller.Request);\n            RedirectResult result = CreateProductUnderTest(location, controller);\n\n            // Act & Assert\n            InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() =>\n                { HttpRequestMessage ignore = result.Request; }, \"ApiController.Request must not be null.\");\n        }\n\n        [Fact]\n        public void ApiControllerRedirect_WithUri_CreatesCorrectResult()\n        {\n            // Arrange\n            Uri expectedLocation = CreateLocation();\n            ApiController controller = CreateController();\n\n            // Act\n            RedirectResult result = controller.Redirect(expectedLocation);\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Same(expectedLocation, result.Location);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                Assert.Same(expectedRequest, result.Request);\n            }\n        }\n\n        [Fact]\n        public void ApiControllerRedirect_WithString_Throws_WhenLocationIsNull()\n        {\n            // Arrange\n            string location = null;\n            ApiController controller = CreateController();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { controller.Redirect(location); }, \"location\");\n        }\n\n        [Fact]\n        public void ApiControllerRedirect_WithString_CreatesCorrectResult()\n        {\n            // Arrange\n            string expectedLocation = CreateLocation().OriginalString;\n            ApiController controller = CreateController();\n\n            // Act\n            RedirectResult result = controller.Redirect(expectedLocation);\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Same(expectedLocation, result.Location.OriginalString);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                Assert.Same(expectedRequest, result.Request);\n            }\n        }\n\n        private static ApiController CreateController()\n        {\n            return new FakeController();\n        }\n\n        private static Uri CreateLocation()\n        {\n            return new Uri(\"aa://b\");\n        }\n\n        private static RedirectResult CreateProductUnderTest(Uri location, HttpRequestMessage request)\n        {\n            return new RedirectResult(location, request);\n        }\n\n        private static RedirectResult CreateProductUnderTest(Uri location, ApiController controller)\n        {\n            return new RedirectResult(location, controller);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private class FakeController : ApiController\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Results/RedirectToRouteResultTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Results\n{\n    public class RedirectToRouteResultTests\n    {\n        [Fact]\n        public void Constructor_Throws_WhenRouteNameIsNull()\n        {\n            // Arrange\n            string routeName = null;\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            UrlHelper urlFactory = CreateDummyUrlFactory();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() =>\n                {\n                    CreateProductUnderTest(routeName, routeValues, urlFactory, request);\n                }, \"routeName\");\n            }\n        }\n\n        [Fact]\n        public void Constructor_Throws_WhenUrlFactoryIsNull()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            UrlHelper urlFactory = null;\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() =>\n                {\n                    CreateProductUnderTest(routeName, routeValues, urlFactory, request);\n                }, \"urlFactory\");\n            }\n        }\n\n        [Fact]\n        public void Constructor_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            UrlHelper urlFactory = CreateDummyUrlFactory();\n            HttpRequestMessage request = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() =>\n            {\n                CreateProductUnderTest(routeName, routeValues, urlFactory, request);\n            }, \"request\");\n        }\n\n        [Fact]\n        public void RouteName_Returns_InstanceProvided()\n        {\n            // Arrange\n            string expectedRouteName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            UrlHelper urlFactory = CreateDummyUrlFactory();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                RedirectToRouteResult result = CreateProductUnderTest(expectedRouteName, routeValues, urlFactory,\n                    request);\n\n                // Act\n                string routeName = result.RouteName;\n\n                // Assert\n                Assert.Same(expectedRouteName, routeName);\n            }\n        }\n\n        [Fact]\n        public void RouteValues_Returns_InstanceProvided()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> expectedRouteValues = CreateRouteValues();\n            UrlHelper urlFactory = CreateDummyUrlFactory();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                RedirectToRouteResult result = CreateProductUnderTest(routeName, expectedRouteValues, urlFactory,\n                    request);\n\n                // Act\n                IDictionary<string, object> routeValues = result.RouteValues;\n\n                // Assert\n                Assert.Same(expectedRouteValues, routeValues);\n            }\n        }\n\n        [Fact]\n        public void UrlFactory_Returns_InstanceProvided()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            UrlHelper expectedUrlFactory = CreateDummyUrlFactory();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                RedirectToRouteResult result = CreateProductUnderTest(routeName, routeValues, expectedUrlFactory,\n                    request);\n\n                // Act\n                UrlHelper urlFactory = result.UrlFactory;\n\n                // Assert\n                Assert.Same(expectedUrlFactory, urlFactory);\n            }\n        }\n\n        [Fact]\n        public void Request_Returns_InstanceProvided()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            UrlHelper urlFactory = CreateDummyUrlFactory();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                RedirectToRouteResult result = CreateProductUnderTest(routeName, routeValues, urlFactory,\n                    expectedRequest);\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Returns_CorrectResponse()\n        {\n            // Arrange\n            string expectedRouteName = CreateRouteName();\n            IDictionary<string, object> expectedRouteValues = CreateRouteValues();\n            Mock<UrlHelper> spyUrlFactory = new Mock<UrlHelper>(MockBehavior.Strict);\n            string expectedLocation = CreateLocation().AbsoluteUri;\n            spyUrlFactory.Setup(f => f.Link(expectedRouteName, expectedRouteValues)).Returns(expectedLocation);\n            UrlHelper urlFactory = spyUrlFactory.Object;\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IHttpActionResult result = CreateProductUnderTest(expectedRouteName, expectedRouteValues, urlFactory,\n                    expectedRequest);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);\n                    Assert.Same(expectedLocation, response.Headers.Location.OriginalString);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Throws_WhenUrlHelperLinkReturnsNull()\n        {\n            // Arrange\n            string expectedRouteName = CreateRouteName();\n            IDictionary<string, object> expectedRouteValues = CreateRouteValues();\n            Mock<UrlHelper> stubUrlFactory = new Mock<UrlHelper>(MockBehavior.Strict);\n            stubUrlFactory.Setup(f => f.Link(expectedRouteName, expectedRouteValues)).Returns((string)null);\n            UrlHelper urlFactory = stubUrlFactory.Object;\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IHttpActionResult result = CreateProductUnderTest(expectedRouteName, expectedRouteValues, urlFactory,\n                    expectedRequest);\n\n                // Act & Assert\n                InvalidOperationException exception = await Assert.ThrowsAsync<InvalidOperationException>(\n                    () => result.ExecuteAsync(CancellationToken.None));\n                Assert.Equal(\"UrlHelper.Link must not return null.\", exception.Message);\n            }\n        }\n\n        [Fact]\n        public void Constructor_ForApiController_Throws_WhenControllerIsNull()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            ApiController controller = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() =>\n            {\n                CreateProductUnderTest(routeName, routeValues, controller);\n            }, \"controller\");\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_ForApiController_ReturnsCorrectResponse()\n        {\n            // Arrange\n            string expectedRouteName = CreateRouteName();\n            IDictionary<string, object> expectedRouteValues = CreateRouteValues();\n            Mock<UrlHelper> spyUrlFactory = new Mock<UrlHelper>(MockBehavior.Strict);\n            string expectedLocation = CreateLocation().AbsoluteUri;\n            spyUrlFactory.Setup(f => f.Link(expectedRouteName, expectedRouteValues)).Returns(expectedLocation);\n            UrlHelper urlFactory = spyUrlFactory.Object;\n            ApiController controller = CreateController();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                controller.Url = urlFactory;\n\n                IHttpActionResult result = CreateProductUnderTest(expectedRouteName, expectedRouteValues, controller);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);\n                    Assert.Same(expectedLocation, response.Headers.Location.OriginalString);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public void UrlFactory_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            ApiController controller = CreateController();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Request = request;\n                controller.Url = CreateDummyUrlFactory();\n\n                RedirectToRouteResult result = CreateProductUnderTest(routeName, routeValues, controller);\n\n                UrlHelper expectedUrlFactory = CreateDummyUrlFactory();\n                controller.Url = expectedUrlFactory;\n\n                // Act\n                UrlHelper urlFactory = result.UrlFactory;\n\n                // Assert\n                Assert.Same(expectedUrlFactory, urlFactory);\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            ApiController controller = CreateController();\n            RedirectToRouteResult result = CreateProductUnderTest(routeName, routeValues, controller);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public void UrlFactory_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            ApiController controller = CreateController();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                controller.Request = request;\n                UrlHelper expectedUrlFactory = CreateDummyUrlFactory();\n                controller.Url = expectedUrlFactory;\n\n                RedirectToRouteResult result = CreateProductUnderTest(routeName, routeValues, controller);\n\n                UrlHelper ignore = result.UrlFactory;\n\n                controller.Url = CreateDummyUrlFactory();\n\n                // Act\n                UrlHelper urlFactory = result.UrlFactory;\n\n                // Assert\n                Assert.Same(expectedUrlFactory, urlFactory);\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            ApiController controller = CreateController();\n\n            RedirectToRouteResult result = CreateProductUnderTest(routeName, routeValues, controller);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                HttpRequestMessage ignore = result.Request;\n\n                using (HttpRequestMessage otherRequest = CreateRequest())\n                {\n                    controller.Request = otherRequest;\n\n                    // Act\n                    HttpRequestMessage request = result.Request;\n\n                    // Assert\n                    Assert.Same(expectedRequest, request);\n                }\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_Throws_WhenControllerRequestIsNull()\n        {\n            // Arrange\n            string routeName = CreateRouteName();\n            IDictionary<string, object> routeValues = CreateRouteValues();\n            ApiController controller = CreateController();\n            Assert.Null(controller.Request);\n\n            RedirectToRouteResult result = CreateProductUnderTest(routeName, routeValues, controller);\n\n            // Act & Assert\n            InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() =>\n                { HttpRequestMessage ignore = result.Request; }, \"ApiController.Request must not be null.\");\n        }\n\n        [Fact]\n        public void ApiControllerRedirectToRoute_WithStringAndDictionary_CreatesCorrectResult()\n        {\n            // Arrange\n            string expectedRouteName = CreateRouteName();\n            IDictionary<string, object> expectedRouteValues = CreateRouteValues();\n            ApiController controller = CreateController();\n\n            // Act\n            RedirectToRouteResult result = controller.RedirectToRoute(expectedRouteName, expectedRouteValues);\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Same(expectedRouteName, result.RouteName);\n            Assert.Same(expectedRouteValues, result.RouteValues);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                Assert.Same(expectedRequest, result.Request);\n            }\n        }\n\n        [Fact]\n        public void ApiControllerRedirectToRoute_WithStringAndObject_CreatesCorrectResult()\n        {\n            // Arrange\n            string expectedRouteName = CreateRouteName();\n            object routeValues = new { id = 1 };\n            ApiController controller = CreateController();\n\n            // Act\n            RedirectToRouteResult result = controller.RedirectToRoute(expectedRouteName, routeValues);\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Same(expectedRouteName, result.RouteName);\n            Assert.IsType<HttpRouteValueDictionary>(result.RouteValues);\n            Assert.True(result.RouteValues.ContainsKey(\"id\"));\n            Assert.Equal(1, result.RouteValues[\"id\"]);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                Assert.Same(expectedRequest, result.Request);\n            }\n        }\n\n        private static ApiController CreateController()\n        {\n            return new FakeController();\n        }\n\n        private static UrlHelper CreateDummyUrlFactory()\n        {\n            return new Mock<UrlHelper>(MockBehavior.Strict).Object;\n        }\n\n        private static Uri CreateLocation()\n        {\n            return new Uri(\"aa://b\");\n        }\n\n        private static RedirectToRouteResult CreateProductUnderTest(string routeName,\n            IDictionary<string, object> routeValues, UrlHelper urlFactory, HttpRequestMessage request)\n        {\n            return new RedirectToRouteResult(routeName, routeValues, urlFactory, request);\n        }\n\n        private static RedirectToRouteResult CreateProductUnderTest(string routeName,\n            IDictionary<string, object> routeValues, ApiController controller)\n        {\n            return new RedirectToRouteResult(routeName, routeValues, controller);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private static string CreateRouteName()\n        {\n            return \"IgnoreRouteName\";\n        }\n\n        private static IDictionary<string, object> CreateRouteValues()\n        {\n            return new Dictionary<string, object>();\n        }\n\n        private class FakeController : ApiController\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Results/ResponseMessageResultTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Results\n{\n    public class ResponseMessageResultTests\n    {\n        [Fact]\n        public void Constructor_Throws_WhenResponseIsNull()\n        {\n            // Arrange, Act & Assert\n            Assert.ThrowsArgumentNull(() => { new ResponseMessageResult(null); }, \"response\");\n        }\n\n        [Fact]\n        public void Response_Returns_InstanceProvided()\n        {\n            // Arrange\n            using (HttpResponseMessage expectedResponse = CreateResponse())\n            {\n                ResponseMessageResult result = new ResponseMessageResult(expectedResponse);\n\n                // Act\n                HttpResponseMessage response = result.Response;\n\n                // Assert\n                Assert.Same(expectedResponse, response);\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Returns_InstanceProvided()\n        {\n            // Arrange\n            using (HttpResponseMessage expectedResponse = CreateResponse())\n            {\n                IHttpActionResult result = new ResponseMessageResult(expectedResponse);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.Same(expectedResponse, response);\n                }\n            }\n        }\n\n        [Fact]\n        public void ApiControllerResponseMessage_CreatesCorrectResponseMessageResult()\n        {\n            // Arrange\n            using (HttpResponseMessage expectedResponse = CreateResponse())\n            {\n                ApiController controller = CreateController();\n\n                // Act\n                ResponseMessageResult result = controller.ResponseMessage(expectedResponse);\n\n                // Assert\n                Assert.NotNull(result);\n                Assert.Same(expectedResponse, result.Response);\n            }\n        }\n\n        private static ApiController CreateController()\n        {\n            return new FakeController();\n        }\n\n        private static HttpResponseMessage CreateResponse()\n        {\n            return new HttpResponseMessage();\n        }\n\n        private class FakeController : ApiController\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Results/StatusCodeResultTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Results\n{\n    public class StatusCodeResultTests\n    {\n        [Fact]\n        public void Constructor_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            HttpRequestMessage request = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { new StatusCodeResult(statusCode, request); }, \"request\");\n        }\n\n        [Fact]\n        public void StatusCode_Returns_ValueProvided()\n        {\n            // Arrange\n            HttpStatusCode expectedStatusCode = CreateStatusCode();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                StatusCodeResult result = new StatusCodeResult(expectedStatusCode, request);\n\n                // Act\n                HttpStatusCode statusCode = result.StatusCode;\n\n                // Assert\n                Assert.Equal(expectedStatusCode, statusCode);\n            }\n        }\n\n        [Fact]\n        public void Request_Returns_InstanceProvided()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                StatusCodeResult result = new StatusCodeResult(statusCode, expectedRequest);\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Returns_CorrectResponse()\n        {\n            // Arrange\n            HttpStatusCode expectedStatusCode = CreateStatusCode();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IHttpActionResult result = new StatusCodeResult(expectedStatusCode, expectedRequest);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(expectedStatusCode, response.StatusCode);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public void Constructor_ForApiController_Throws_WhenControllerIsNull()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            ApiController controller = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { new StatusCodeResult(statusCode, controller); }, \"controller\");\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_ForApiController_ReturnsCorrectResponse()\n        {\n            // Arrange\n            HttpStatusCode expectedStatusCode = CreateStatusCode();\n            ApiController controller = CreateController();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                IHttpActionResult result = new StatusCodeResult(expectedStatusCode, controller);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(expectedStatusCode, response.StatusCode);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            ApiController controller = CreateController();\n            StatusCodeResult result = new StatusCodeResult(statusCode, controller);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            ApiController controller = CreateController();\n            StatusCodeResult result = new StatusCodeResult(statusCode, controller);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                HttpRequestMessage ignore = result.Request;\n\n                using (HttpRequestMessage otherRequest = CreateRequest())\n                {\n                    controller.Request = otherRequest;\n\n                    // Act\n                    HttpRequestMessage request = result.Request;\n\n                    // Assert\n                    Assert.Same(expectedRequest, request);\n                }\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_Throws_WhenControllerRequestIsNull()\n        {\n            // Arrange\n            HttpStatusCode statusCode = CreateStatusCode();\n            ApiController controller = CreateController();\n            Assert.Null(controller.Request);\n            StatusCodeResult result = new StatusCodeResult(statusCode, controller);\n\n            // Act & Assert\n            InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() =>\n                { HttpRequestMessage ignore = result.Request; }, \"ApiController.Request must not be null.\");\n        }\n\n        [Fact]\n        public void ApiControllerStatusCode_CreatesCorrectStatusCodeResult()\n        {\n            // Arrange\n            HttpStatusCode expectedStatusCode = CreateStatusCode();\n            ApiController controller = CreateController();\n\n            // Act\n            StatusCodeResult result = controller.StatusCode(expectedStatusCode);\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Equal(expectedStatusCode, result.StatusCode);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                Assert.Same(expectedRequest, result.Request);\n            }\n        }\n\n        private static ApiController CreateController()\n        {\n            return new FakeController();\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private static HttpStatusCode CreateStatusCode()\n        {\n            return HttpStatusCode.Continue;\n        }\n\n        private class FakeController : ApiController\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Results/UnauthorizedResultTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Results\n{\n    public class UnauthorizedResultTests\n    {\n        [Fact]\n        public void Constructor_Throws_WhenChallengesIsNull()\n        {\n            // Arrange\n            IEnumerable<AuthenticationHeaderValue> challenges = null;\n            HttpRequestMessage request = CreateRequest();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { CreateProductUnderTest(challenges, request); }, \"challenges\");\n        }\n\n        [Fact]\n        public void Constructor_Throws_WhenRequestIsNull()\n        {\n            // Arrange\n            IEnumerable<AuthenticationHeaderValue> challenges = CreateChallenges();\n            HttpRequestMessage request = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { CreateProductUnderTest(challenges, request); }, \"request\");\n        }\n\n        [Fact]\n        public void Challenges_Returns_InstanceProvided()\n        {\n            // Arrange\n            IEnumerable<AuthenticationHeaderValue> expectedChallenges = CreateChallenges();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                UnauthorizedResult result = CreateProductUnderTest(expectedChallenges, request);\n\n                // Act\n                IEnumerable<AuthenticationHeaderValue> challenges = result.Challenges;\n\n                // Assert\n                Assert.Same(expectedChallenges, challenges);\n            }\n        }\n\n        [Fact]\n        public void Request_Returns_InstanceProvided()\n        {\n            // Arrange\n            IEnumerable<AuthenticationHeaderValue> challenges = CreateChallenges();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                UnauthorizedResult result = CreateProductUnderTest(challenges, expectedRequest);\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Returns_CorrectResponse()\n        {\n            // Arrange\n            AuthenticationHeaderValue expectedChallenge1 = CreateChallenge();\n            AuthenticationHeaderValue expectedChallenge2 = CreateChallenge();\n            IEnumerable<AuthenticationHeaderValue> challenges = new[] { expectedChallenge1, expectedChallenge2 };\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                IHttpActionResult result = CreateProductUnderTest(challenges, expectedRequest);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);\n                    Assert.Equal(2, response.Headers.WwwAuthenticate.Count);\n                    Assert.Same(expectedChallenge1, response.Headers.WwwAuthenticate.ElementAt(0));\n                    Assert.Same(expectedChallenge2, response.Headers.WwwAuthenticate.ElementAt(1));\n                    Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public void Constructor_ForApiController_Throws_WhenControllerIsNull()\n        {\n            // Arrange\n            IEnumerable<AuthenticationHeaderValue> challenges = CreateChallenges();\n            ApiController controller = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => { CreateProductUnderTest(challenges, controller); }, \"controller\");\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_ForApiController_ReturnsCorrectResponse()\n        {\n            // Arrange\n            AuthenticationHeaderValue expectedChallenge1 = CreateChallenge();\n            AuthenticationHeaderValue expectedChallenge2 = CreateChallenge();\n            IEnumerable<AuthenticationHeaderValue> challenges = new[] { expectedChallenge1, expectedChallenge2 };\n            ApiController controller = CreateController();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                IHttpActionResult result = CreateProductUnderTest(challenges, controller);\n\n                // Act\n                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);\n\n                // Assert\n                Assert.NotNull(task);\n\n                using (HttpResponseMessage response = await task)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);\n                    Assert.Equal(2, response.Headers.WwwAuthenticate.Count);\n                    Assert.Same(expectedChallenge1, response.Headers.WwwAuthenticate.ElementAt(0));\n                    Assert.Same(expectedChallenge2, response.Headers.WwwAuthenticate.ElementAt(1));\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesLazily()\n        {\n            // Arrange\n            IEnumerable<AuthenticationHeaderValue> challenges = CreateChallenges();\n            ApiController controller = CreateController();\n            UnauthorizedResult result = CreateProductUnderTest(challenges, controller);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n\n                // Act\n                HttpRequestMessage request = result.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_EvaluatesOnce()\n        {\n            // Arrange\n            IEnumerable<AuthenticationHeaderValue> challenges = CreateChallenges();\n            ApiController controller = CreateController();\n            UnauthorizedResult result = CreateProductUnderTest(challenges, controller);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                HttpRequestMessage ignore = result.Request;\n\n                using (HttpRequestMessage otherRequest = CreateRequest())\n                {\n                    controller.Request = otherRequest;\n\n                    // Act\n                    HttpRequestMessage request = result.Request;\n\n                    // Assert\n                    Assert.Same(expectedRequest, request);\n                }\n            }\n        }\n\n        [Fact]\n        public void Request_ForApiController_Throws_WhenControllerRequestIsNull()\n        {\n            // Arrange\n            IEnumerable<AuthenticationHeaderValue> challenges = CreateChallenges();\n            ApiController controller = CreateController();\n            Assert.Null(controller.Request);\n            UnauthorizedResult result = CreateProductUnderTest(challenges, controller);\n\n            // Act & Assert\n            InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() =>\n                { HttpRequestMessage ignore = result.Request; }, \"ApiController.Request must not be null.\");\n        }\n\n        [Fact]\n        public void ApiControllerUnauthorized_WithIEnumerable_CreatesCorrectResult()\n        {\n            // Arrange\n            IEnumerable<AuthenticationHeaderValue> expectedChallenges = CreateChallenges();\n            ApiController controller = CreateController();\n\n            // Act\n            UnauthorizedResult result = controller.Unauthorized(expectedChallenges);\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Same(expectedChallenges, result.Challenges);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                Assert.Same(expectedRequest, result.Request);\n            }\n        }\n\n        [Fact]\n        public void ApiControllerUnauthorized_WithParams_CreatesCorrectResult()\n        {\n            // Arrange\n            AuthenticationHeaderValue challenge1 = CreateChallenge();\n            AuthenticationHeaderValue challenge2 = CreateChallenge();\n            ApiController controller = CreateController();\n\n            // Act\n            UnauthorizedResult result = controller.Unauthorized(challenge1, challenge2);\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Equal(2, result.Challenges.Count());\n            Assert.Same(challenge1, result.Challenges.ElementAt(0));\n            Assert.Same(challenge2, result.Challenges.ElementAt(1));\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                controller.Request = expectedRequest;\n                Assert.Same(expectedRequest, result.Request);\n            }\n        }\n\n        private static IEnumerable<AuthenticationHeaderValue> CreateChallenges()\n        {\n            return new AuthenticationHeaderValue[0];\n        }\n\n        private static AuthenticationHeaderValue CreateChallenge()\n        {\n            return new AuthenticationHeaderValue(\"IgnoreScheme\");\n        }\n\n        private static ApiController CreateController()\n        {\n            return new FakeController();\n        }\n\n        private static UnauthorizedResult CreateProductUnderTest(IEnumerable<AuthenticationHeaderValue> challenges,\n            HttpRequestMessage request)\n        {\n            return new UnauthorizedResult(challenges, request);\n        }\n\n        private static UnauthorizedResult CreateProductUnderTest(IEnumerable<AuthenticationHeaderValue> challenges,\n            ApiController controller)\n        {\n            return new UnauthorizedResult(challenges, controller);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private class FakeController : ApiController\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Routing/AttributeRoutingTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Routing\n{\n    public class AttributeRoutingTest\n    {\n        [Theory]\n        [InlineData(\"GET\", \"controller/42\", \"Get42\")]\n        // Tests inline route constraints\n        [InlineData(\"GET\", \"controller/Ethan\", \"GetByNameEthan\")]\n        // Tests the HTTP method constraint\n        [InlineData(\"PUT\", \"controller/42\", \"Put42\")]\n        // Tests route consolidation (or lack thereof)\n        [InlineData(\"PUT\", \"controller/42?name=foo\", \"Put42foo\")]\n        // Tests optional parameters\n        [InlineData(\"GET\", \"optional/1/2\", \"Optional12\")]\n        [InlineData(\"GET\", \"optional/1\", \"Optional1opt\")]\n        [InlineData(\"GET\", \"optional\", \"Optional8opt\")]\n        [InlineData(\"GET\", \"optionalwconstraint\", \"OptionalWithConstraintx\")]\n        [InlineData(\"GET\", \"optionalwnullable/12\", \"Optional12\")]\n        [InlineData(\"GET\", \"optionalwnullable\", \"Optional\")]\n        [InlineData(\"GET\", \"apibadcontrollerx/int/12\", \"GetInt12\")]\n        [InlineData(\"GET\", \"apibadcontrollerx/nullableint/12\", \"GetNullable12\")]\n        [InlineData(\"GET\", \"apibadcontrollerx/string/12\", \"GetString12\")]\n        // Tests default values\n        [InlineData(\"GET\", \"default/1/2\", \"Default12\")]\n        [InlineData(\"GET\", \"default/1\", \"Default1D2\")]\n        [InlineData(\"GET\", \"default\", \"DefaultD1D2\")]\n        // Test wildcard parameters\n        [InlineData(\"GET\", \"wildcard/a/b/c\", \"Wildcarda/b/c\")]\n        // Test prefixes\n        [InlineData(\"GET\", \"prefix\", \"PrefixedGet\")]\n        [InlineData(\"GET\", \"prefix/123\", \"PrefixedGetById123\")]\n        [InlineData(\"PUT\", \"prefix\", \"PrefixedPut\")]\n        // Test multiple controllerRouteFactories to same action\n        [InlineData(\"DELETE\", \"multi1\", \"multi\")]\n        [InlineData(\"DELETE\", \"multi2\", \"multi\")]\n        // Test multiple verbs on the same route\n        [InlineData(\"GET\", \"multiverb\", \"GET\")]\n        [InlineData(\"PUT\", \"multiverb\", \"PUT\")]\n        // Test with default route\n        [InlineData(\"GET\", \"prefix2/defaultroute/12\", \"get12\")]\n        [InlineData(\"PUT\", \"prefix2/defaultrouteoverride/12\", \"put12\")]\n        [InlineData(\"POST\", \"prefix2\", \"post\")]\n        // {action} values\n        [InlineData(\"GET\", \"api/default2/GetAllCustomers1\", \"GetAllCustomers1\")]\n        [InlineData(\"GET\", \"api/resource/12\", \"12\")]\n        [InlineData(\"GET\", \"apiactionstress/ActionY/ActionX?useX=5\", \"XActionY5\")]\n        [InlineData(\"GET\", \"apiactionstress/ActionY/ActionX?useY=7\", \"YActionX7\")]\n        // Mixing {action} with REST\n        [InlineData(\"GET\", \"partial/DoOp1\", \"op1\")]\n        [InlineData(\"GET\", \"partial/154\", \"154\")]\n        // Optional on controller [Route]\n        [InlineData(\"GET\", \"apioptional\", \"GetAllCustomers\")]\n        [InlineData(\"GET\", \"apioptional/57\", \"GetCustomer:57\")]\n        // Overload resolution\n        [InlineData(\"GET\", \"apioverload/Fred?age=12\", \"GetAge:Fred12\")]\n        [InlineData(\"GET\", \"apioverload/Fred?score=12\", \"GetScore:Fred12\")]\n        // Controller route attribute inheritance\n        [InlineData(\"GET\", \"subclass?id=8\", \"Get:8\")]\n        [InlineData(\"POST\", \"subclass?name=foo\", \"Post:foo\")]\n        [InlineData(\"GET\", \"api/subclassnoroute?id=8\", \"Get:8\")]\n        [InlineData(\"POST\", \"api/subclassnoroute?name=foo\", \"Post:foo\")]\n        [InlineData(\"GET\", \"baseclass?id=9\", \"Get:9\")]\n        [InlineData(\"GET\", \"baseclassprefix\", \"Get\")]\n        [InlineData(\"GET\", \"baseclassprefix/base/8\", \"Get:8\")]\n        [InlineData(\"GET\", \"api/subclassnoprefix\", \"Get\")]\n        [InlineData(\"GET\", \"api/subclassnoprefix?id=9\", \"Get:9\")]\n        [InlineData(\"POST\", \"api/subclassnoprefix?name=foo\", \"Post:foo\")]\n        [InlineData(\"POST\", \"subclassprefix?name=foo\", \"Post:foo\")]\n        [InlineData(\"GET\", \"api/subclassprefix\", \"Get\")]\n        [InlineData(\"GET\", \"api/subclassprefix?id=3\", \"Get:3\")]\n        [InlineData(\"GET\", \"subclassroute\", \"Get\")]\n        [InlineData(\"GET\", \"subclassroute?id=9\", \"Get:9\")]\n        [InlineData(\"POST\", \"subclassroute?name=foo\", \"Post:foo\")]\n        // Route order\n        [InlineData(\"GET\", \"routeorder/11\", \"GetById:11\")]\n        [InlineData(\"GET\", \"routeorder/name\", \"GetByName:name\")]\n        [InlineData(\"GET\", \"routeorder/literal\", \"GetLiteral\")]\n        [InlineData(\"GET\", \"routeorderoverload\", \"Get\")]\n        [InlineData(\"GET\", \"routeorderoverload?name=name&id=1\", \"GetByNameAndId:name1\")]\n        [InlineData(\"GET\", \"routeorderoverload?name=name\", \"GetByName:name\")]\n        // Route precedence\n        [InlineData(\"GET\", \"routeprecedence/11\", \"GetById:11\")]\n        [InlineData(\"GET\", \"routeprecedence/name\", \"GetByName:name\")]\n        [InlineData(\"GET\", \"routeprecedence/literal\", \"GetLiteral\")]\n        [InlineData(\"GET\", \"routeprecedence/name?id=20\", \"GetByNameAndId:name20\")]\n        [InlineData(\"GET\", \"constraint\", \"pass\")]\n        public async Task AttributeRouting_RoutesToAction(string httpMethod, string uri, string responseBody)\n        {\n            var request = new HttpRequestMessage(new HttpMethod(httpMethod), \"http://localhost/\" + uri);\n\n            var response = await SubmitRequestAsync(request);\n\n            Assert.True(response.IsSuccessStatusCode);\n            Assert.Equal(responseBody, GetContentValue<string>(response));\n        }\n\n        [Theory]\n        // default controllerRouteFactories\n        [InlineData(\"GET\", \"prefix2/defaultroute/name\", HttpStatusCode.NotFound)] // miss route constraint\n        [InlineData(\"PUT\", \"prefix2/defaultroute/12\", HttpStatusCode.MethodNotAllowed)] // override, different url\n        [InlineData(\"POST\", \"prefix\", HttpStatusCode.MethodNotAllowed)]\n        // wrong verb, 405\n        [InlineData(\"MISSING\", \"controller/42\", HttpStatusCode.MethodNotAllowed)]\n        [InlineData(\"MISSING\", \"default/1/2\", HttpStatusCode.MethodNotAllowed)]\n        [InlineData(\"MISSING\", \"controller/Ethan\", HttpStatusCode.MethodNotAllowed)]\n        // accessing attribute routed method via standard route\n        [InlineData(\"GET\", \"api/Attributed?id=42\", HttpStatusCode.NotFound)]\n        [InlineData(\"GET\", \"api/DefaultRoute?id=42\", HttpStatusCode.NotFound)]\n        [InlineData(\"GET\", \"api/Default2/GetById\", HttpStatusCode.NotFound)]\n        [InlineData(\"GET\", \"api/Default2/MethodNotFound\", HttpStatusCode.NotFound)]\n        // Ambiguous match\n        [InlineData(\"GET\", \"apioverload/Fred?score=12&age=23\", HttpStatusCode.InternalServerError)]\n        [InlineData(\"GET\", \"apiactionstress/ActionY/ActionX?useY=7&useX=8\", HttpStatusCode.InternalServerError)]\n        // Unreachable inherited controllerRouteFactories\n        [InlineData(\"GET\", \"api/subclassroute\", HttpStatusCode.NotFound)]\n        [InlineData(\"GET\", \"api/subclassroute?id=9\", HttpStatusCode.NotFound)]\n        [InlineData(\"POST\", \"api/subclassroute?name=foo\", HttpStatusCode.NotFound)]\n        [InlineData(\"GET\", \"api/baseclass?id=2\", HttpStatusCode.NotFound)]\n        [InlineData(\"GET\", \"api/baseclassprefix\", HttpStatusCode.NotFound)]\n        [InlineData(\"GET\", \"api/baseclassprefix?id=2\", HttpStatusCode.NotFound)]\n        // Default value is required, 500 would be a better error, but important thing is we fail\n        [InlineData(\"GET\", \"apibadcontrollerx/int\", HttpStatusCode.NotFound)]\n        [InlineData(\"GET\", \"apibadcontrollerx/nullableint\", HttpStatusCode.NotFound)]\n        [InlineData(\"GET\", \"apibadcontrollerx/string\", HttpStatusCode.NotFound)]\n        public async Task AttributeRouting_Failures(string httpMethod, string uri, HttpStatusCode failureCode)\n        {\n            var request = new HttpRequestMessage(new HttpMethod(httpMethod), \"http://localhost/\" + uri);\n\n            var response = await SubmitRequestAsync(request);\n\n            Assert.False(response.IsSuccessStatusCode);\n            Assert.Equal(failureCode, response.StatusCode);\n        }\n\n        [Fact]\n        public async Task AttributeRouting_MultipleControllerMatches()\n        {\n            var request = new HttpRequestMessage(new HttpMethod(\"GET\"), \"http://localhost/ambiguousmatch\");\n\n            var response = await SubmitRequestAsync(request);\n\n            Assert.False(response.IsSuccessStatusCode);\n            Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n        }\n\n        [Fact]\n        public void RoutePrefixAttribute_IsSingleInstance()\n        {\n            var attr = typeof(RoutePrefixAttribute);\n            var attrs = attr.GetCustomAttributes(typeof(AttributeUsageAttribute), false);\n            var usage = (AttributeUsageAttribute)attrs[0];\n\n            Assert.Equal(AttributeTargets.Class, usage.ValidOn);\n            Assert.False(usage.AllowMultiple); // only 1 per class\n            Assert.True(usage.Inherited); // RoutePrefix is not inherited.\n        }\n\n        [Theory]\n        [InlineData(\"GET\", \"NS1Home/Introduction\", \"Home.Index()\")]\n        [InlineData(\"GET\", \"NS2Account/PeopleList\", \"Account.Index()\")]\n        [InlineData(\"GET\", \"CustomizedDefaultPrefix/Unknown\", \"Default.Index()\")]\n        public async Task AttributeRouting_RoutesToAction_WithCustomizedRoutePrefix(string httpMethod, string uri, string responseBody)\n        {\n            var request = new HttpRequestMessage(new HttpMethod(httpMethod), \"http://localhost/\" + uri);\n\n            var response = await SubmitRequestAsync(request);\n\n            Assert.True(response.IsSuccessStatusCode);\n            Assert.Equal(responseBody, GetContentValue<string>(response));\n        }\n\n        [Fact]\n        public async Task AttributeRouting_DirectRouteProvider_ControllerRoute()\n        {\n            var controllerRoutes = new Dictionary<Type, IEnumerable<IDirectRouteFactory>>()\n            {\n                { typeof(DirectRouteProviderController), new[] { new RouteAttribute(\"CoolRouteBro\") } }\n            };\n\n            var routeProvider = new DirectRouteProvider(controllerRoutes, null);\n\n\n            var request = new HttpRequestMessage(HttpMethod.Get, \"http://localhost/CoolRouteBro\");\n\n            var response = await SubmitRequestAsync(request, routeProvider);\n\n            Assert.True(response.IsSuccessStatusCode);\n            Assert.Equal(\"DirectRouteProviderController.Get239303030()\", GetContentValue<string>(response));\n        }\n\n        [Fact]\n        public async Task AttributeRouting_DirectRouteProvider_ControllerRoute_TraditionalRouteDoesntMatch()\n        {\n            var controllerRoutes = new Dictionary<Type, IEnumerable<IDirectRouteFactory>>()\n            {\n                { typeof(DirectRouteProviderController), new[] { new RouteAttribute(\"CoolRouteBro\") } }\n            };\n\n            var routeProvider = new DirectRouteProvider(controllerRoutes, null);\n\n\n            var request = new HttpRequestMessage(HttpMethod.Get, \"http://localhost/DirectRouteProvider\");\n\n            var response = await SubmitRequestAsync(request, routeProvider);\n\n            Assert.False(response.IsSuccessStatusCode);\n            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);\n        }\n\n        [Fact]\n        public async Task AttributeRouting_DirectRouteProvider_ActionRoute()\n        {\n            var actionRoutes = new Dictionary<string, IEnumerable<IDirectRouteFactory>>()\n            {\n                { \"Get239303030\", new[] { new RouteAttribute(\"CoolRouteBro\") } }\n            };\n\n            var routeProvider = new DirectRouteProvider(null, actionRoutes);\n\n\n            var request = new HttpRequestMessage(HttpMethod.Get, \"http://localhost/CoolRouteBro\");\n\n            var response = await SubmitRequestAsync(request, routeProvider);\n\n            Assert.True(response.IsSuccessStatusCode);\n            Assert.Equal(\"DirectRouteProviderController.Get239303030()\", GetContentValue<string>(response));\n        }\n\n        private static async Task<HttpResponseMessage> SubmitRequestAsync(HttpRequestMessage request, IDirectRouteProvider routeProvider = null)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"DefaultApi\", \"api/{controller}\");\n            if (routeProvider == null)\n            {\n                config.MapHttpAttributeRoutes();\n            }\n            else\n            {\n                config.MapHttpAttributeRoutes(routeProvider);\n            }\n\n            HttpResponseMessage response;\n            HttpServer server = new HttpServer(config);\n            using (HttpMessageInvoker client = new HttpMessageInvoker(server))\n            {\n                response = await client.SendAsync(request, CancellationToken.None);\n            }\n\n            return response;\n        }\n\n        private static T GetContentValue<T>(HttpResponseMessage response)\n        {\n            T value;\n            response.TryGetContentValue<T>(out value);\n            return value;\n        }\n\n        private class DirectRouteProvider : DefaultDirectRouteProvider\n        {\n            private readonly IDictionary<Type, IEnumerable<IDirectRouteFactory>> _controllerRouteFactories;\n            private readonly IDictionary<string, IEnumerable<IDirectRouteFactory>> _actionRouteFactories;\n\n            public DirectRouteProvider(\n                IDictionary<Type, IEnumerable<IDirectRouteFactory>> controllerRouteFactories,\n                IDictionary<string, IEnumerable<IDirectRouteFactory>> actionRouteFactories)\n            {\n                _controllerRouteFactories = controllerRouteFactories ?? new Dictionary<Type, IEnumerable<IDirectRouteFactory>>();\n                _actionRouteFactories = actionRouteFactories ?? new Dictionary<string, IEnumerable<IDirectRouteFactory>>();\n            }\n\n            protected override IReadOnlyList<IDirectRouteFactory> GetControllerRouteFactories(HttpControllerDescriptor controllerDescriptor)\n            {\n                IEnumerable<IDirectRouteFactory> factories;\n                _controllerRouteFactories.TryGetValue(controllerDescriptor.ControllerType, out factories);\n                return factories == null ? null : factories.ToList();\n            }\n\n            protected override IReadOnlyList<IDirectRouteFactory> GetActionRouteFactories(HttpActionDescriptor actionDescriptor)\n            {\n                IEnumerable<IDirectRouteFactory> factories;\n                _actionRouteFactories.TryGetValue(actionDescriptor.ActionName, out factories);\n                return factories == null ? null : factories.ToList();\n            }\n        }\n    }\n\n    public class DirectRouteProviderController : ApiController\n    {\n        public string Get239303030()\n        {\n            return \"DirectRouteProviderController.Get239303030()\";\n        }\n    }\n\n    public class AttributedController : ApiController\n    {\n        [Route(\"controller/{id:int}\")]\n        public string Get(int id)\n        {\n            return \"Get\" + id;\n        }\n\n        [Route(\"controller/{name}\")]\n        public string GetByName(string name)\n        {\n            return \"GetByName\" + name;\n        }\n\n        [Route(\"controller/{id}\")]\n        public string Put(string id)\n        {\n            return \"Put\" + id;\n        }\n\n        [Route(\"controller/{id}\")]\n        public string Put(string id, string name)\n        {\n            return \"Put\" + id + name;\n        }\n\n        // Optional route parameters still require a default value in the signature.\n        [HttpGet]\n        [Route(\"optional/{opt1?}/{opt2?}\")]\n        public string Optional(int opt1 = 8, string opt2 = \"opt\")\n        {\n            return \"Optional\" + opt1 + opt2;\n        }\n\n        [HttpGet]\n        [Route(\"optionalwnullable/{opt1?}\")]\n        public string Optional(int? opt1 = null)\n        {\n            return \"Optional\" + opt1;\n        }\n\n        [HttpGet]\n        [Route(\"optionalwconstraint/{opt:int?}\")]\n        public string OptionalWithConstraint(string opt = \"x\")\n        {\n            return \"OptionalWithConstraint\" + opt;\n        }\n\n        [HttpGet]\n        [Route(\"default/{default1=D1}/{default2=D2}\")]\n        public string Default(string default1, string default2)\n        {\n            return \"Default\" + default1 + default2;\n        }\n\n        [HttpGet]\n        [Route(\"wildcard/{*wildcard}\")]\n        public string Wildcard(string wildcard)\n        {\n            return \"Wildcard\" + wildcard;\n        }\n\n        [HttpGet]\n        [HttpPut]\n        [Route(\"multiverb\")]\n        public string MultiVerbs()\n        {\n            return Request.Method.ToString();\n        }\n\n        [HttpDelete] // Pick a unique verb\n        [Route(\"multi1\")]\n        [Route(\"multi2\")]\n        public string MultiRoute()\n        {\n            return \"multi\";\n        }\n\n    }\n\n    // Routes have optional parameters, but signature says it's required.\n    // Try with value-type, reference type, and nullable.\n    public class OptionalParameterController : ApiController\n    {\n        // Optional in route, required in signature.\n        [Route(\"apibadcontrollerx/int/{id?}\")]\n        public string Get(int id)\n        {\n            return \"GetInt\" + id;\n        }\n\n        [Route(\"apibadcontrollerx/nullableint/{id?}\")]\n        public string GetNullable(int? id)\n        {\n            return \"GetNullable\" + id;\n        }\n\n        [Route(\"apibadcontrollerx/string/{id?}\")]\n        public string GetString(string id)\n        {\n            return \"GetString\" + id;\n        }\n    }\n\n    [RoutePrefix(\"prefix\")]\n    public class PrefixedController : ApiController\n    {\n        // Should not be reachable be our routes since there's no route attribute.\n        public void Post()\n        {\n        }\n\n        [Route(\"\")]\n        public string Get()\n        {\n            return \"PrefixedGet\";\n        }\n\n        [Route] // same behavior as Route(\"\")\n        public string Put()\n        {\n            return \"PrefixedPut\";\n        }\n\n        [HttpGet]\n        [Route(\"{id}\")]\n        public string GetById(int id)\n        {\n            return \"PrefixedGetById\" + id;\n        }\n    }\n\n    [RoutePrefix(\"prefix2\")]\n    [Route(\"defaultroute/{id:int}\")]\n    public class DefaultRouteController : ApiController\n    {\n        // This gets default route\n        public string Get(int id)\n        {\n            return \"get\" + id;\n        }\n\n        [Route]\n        public string Post()\n        {\n            return \"post\";\n        }\n\n        [Route(\"defaultrouteoverride/{id}\")]\n        public string Put(int id)\n        {\n            return \"put\" + id;\n        }\n    }\n\n    [Route(\"api/default2/{action}\")]\n    public class RpcController : ApiController\n    {\n        public string GetAllCustomers1()\n        {\n            return \"GetAllCustomers1\";\n        }\n\n        public string GetAllCustomers2()\n        {\n            return \"GetAllCustomers2\";\n        }\n\n        // Have a REST api on a RPC controller. Has unique URL\n        [Route(\"api/resource/{id}\")]\n        public string GetById(string id)\n        {\n            return id;\n        }\n    }\n\n    [RoutePrefix(\"apioptional\")]\n    [Route(\"{id?}\")]\n    public class OptionalController : ApiController\n    {\n        public string GetAllCustomers()\n        {\n            return \"GetAllCustomers\";\n        }\n\n        public string GetCustomer(int id)\n        {\n            return \"GetCustomer:\" + id;\n        }\n    }\n\n    [Route(\"partial/{action}\")]\n    public class PartlyResourcePartlyRpcController : ApiController\n    {\n        // Normal RPC methods\n        [HttpGet]\n        public string DoOp1()\n        {\n            return \"op1\";\n        }\n\n        // Some non-RPC methods.  Has overlapping URL\n        [Route(\"partial/{id:int}\")]\n        public string GetById(int id)\n        {\n            return id.ToString();\n        }\n    }\n\n    [RoutePrefix(\"apioverload\")]\n    public class OverloadController : ApiController\n    {\n        [Route(\"{name}\")]\n        public string GetAge(string name, int age)\n        {\n            return \"GetAge:\" + name + age;\n        }\n\n        [Route(\"{id}\")]\n        public string GetScore(string id, int score)\n        {\n            return \"GetScore:\" + id + score;\n        }\n    }\n\n    [RoutePrefix(\"apitokens\")]\n    public class TokensController : ApiController\n    {\n        [Route(\"{id:int}\")]\n        public string GetById(int id)\n        {\n            return \"id\" + id;\n        }\n\n        [Route(\"{name}\")]\n        public string GetByName(string name)\n        {\n            return \"name\" + name;\n        }\n\n        [Route(\"{id:int}\")]\n        public string GetDetails(int id, string name)\n        {\n            return \"id\" + id + \"name\" + name;\n        }\n    }\n\n    // Stress test for action selection. This stresses that the union route really keeps the various\n    // sub routes separate and properly elevates the correct one.\n    // Uses query string parameters to disambiguate.\n    [RoutePrefix(\"apiactionstress\")]\n    [Route(\"{x}/{action}\")]\n    [Route(\"{action}/{y}\")]\n    public class ActionStressController : ApiController\n    {\n        [HttpGet]\n        public string ActionX(string x, int useX)\n        {\n            return \"X\" + x + useX;\n        }\n\n        [HttpGet]\n        public string ActionY(string y, int useY)\n        {\n            return \"Y\" + y + useY;\n        }\n    }\n\n    [Route(\"baseclass\", Name = \"Base\")]\n    public class BaseClassController : ApiController\n    {\n        public string Get(int id)\n        {\n            return \"Get:\" + id;\n        }\n    }\n\n    [Route(\"subclass\", Name = \"Sub\")]\n    public class SubClassController : BaseClassController\n    {\n        public string Post(string name)\n        {\n            return \"Post:\" + name;\n        }\n    }\n\n    public class SubClassNoRouteController : BaseClassController\n    {\n        public string Post(string name)\n        {\n            return \"Post:\" + name;\n        }\n    }\n\n    [RoutePrefix(\"baseclassprefix\")]\n    public class BaseClassPrefixController : ApiController\n    {\n        [Route]\n        public string GetAll()\n        {\n            return \"Get\";\n        }\n\n        [Route(\"base/{id}\", Name = \"GetById\")]\n        public string GetById(int id)\n        {\n            return \"Get:\" + id;\n        }\n    }\n\n    public class SubClassNoPrefixController : BaseClassPrefixController\n    {\n        public string Post(string name)\n        {\n            return \"Post:\" + name;\n        }\n    }\n\n    [RoutePrefix(\"subclassprefix\")]\n    public class SubClassPrefixController : BaseClassPrefixController\n    {\n        [Route]\n        public string Post(string name)\n        {\n            return \"Post:\" + name;\n        }\n    }\n\n    [Route(\"subclassroute\")]\n    public class SubClassRouteController : BaseClassPrefixController\n    {\n        public string Post(string name)\n        {\n            return \"Post:\" + name;\n        }\n    }\n\n    public class RouteOrderController : ApiController\n    {\n        [Route(\"routeorder/{id:int}\", Order = 1)]\n        public string GetById(int id)\n        {\n            return \"GetById:\" + id;\n        }\n\n        [Route(\"routeorder/{name}\", Order = 2)]\n        public string GetByName(string name)\n        {\n            return \"GetByName:\" + name;\n        }\n\n        [Route(\"routeorder/literal\", Order = 0)]\n        public string GetLiteral()\n        {\n            return \"GetLiteral\";\n        }\n    }\n\n    public class RouteOrderOverloadController : ApiController\n    {\n        [Route(\"routeorderoverload\", Order = 1)]\n        public string GetByNameAndId(string name, int id)\n        {\n            return \"GetByNameAndId:\" + name + id;\n        }\n\n        [Route(\"routeorderoverload\", Order = 2)]\n        public string GetByName(string name)\n        {\n            return \"GetByName:\" + name;\n        }\n\n        [Route(\"routeorderoverload\", Order = 3)]\n        public string Get()\n        {\n            return \"Get\";\n        }\n    }\n\n    public class RoutePrecedenceController : ApiController\n    {\n        [Route(\"routeprecedence/{id:int}\")]\n        public string GetById(int id)\n        {\n            return \"GetById:\" + id;\n        }\n\n        [Route(\"routeprecedence/{name}\")]\n        public string GetByName(string name)\n        {\n            return \"GetByName:\" + name;\n        }\n\n        [Route(\"routeprecedence/{name}\")]\n        public string GetByNameAndId(string name, int id)\n        {\n            return \"GetByNameAndId:\" + name + id;\n        }\n\n        [Route(\"routeprecedence/literal\")]\n        public string GetLiteral()\n        {\n            return \"GetLiteral\";\n        }\n    }\n\n    [RoutePrefix(\"constraint\")]\n    public class ConstraintController : ApiController\n    {\n        [ConstrainedRoute(Order = 1, ConstraintMatches = true)]\n        public string GetHigherOrderWithMatchingContsraint()\n        {\n            return \"pass\";\n        }\n\n        [ConstrainedRoute(Order = 0, ConstraintMatches = false)]\n        public string GetLowerOrderWithNonMatchingConstraint()\n        {\n            return \"fail\";\n        }\n\n        private class ConstrainedRouteAttribute : RouteFactoryAttribute\n        {\n            public ConstrainedRouteAttribute()\n                : base(null)\n            {\n            }\n\n            public bool ConstraintMatches { get; set; }\n\n            public override IDictionary<string, object> Constraints\n            {\n                get\n                {\n                    return new HttpRouteValueDictionary()\n                    {\n                        { String.Empty, new Constraint(ConstraintMatches) }\n                    };\n                }\n            }\n\n            private class Constraint : IHttpRouteConstraint\n            {\n                private readonly bool _matches;\n\n                public Constraint(bool matches)\n                {\n                    _matches = matches;\n                }\n\n                public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName,\n                    IDictionary<string, object> values, HttpRouteDirection routeDirection)\n                {\n                    return _matches;\n                }\n            }\n        }\n    }\n\n    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]\n    public class CustomizedRoutePrefixAttribute : Attribute, IRoutePrefix\n    {\n        public CustomizedRoutePrefixAttribute(Type controller)\n        {\n            if (controller == null)\n            {\n                throw Error.ArgumentNull(\"prefix\");\n            }\n\n            if (controller.Equals(typeof(HomeWithCustomizedRoutePrefixController)))\n            {\n                Prefix = \"NS1Home\";\n            }\n            else if (controller.Equals(typeof(AccountWithCustomizedRoutePrefixController)))\n            {\n                Prefix = \"NS2Account\";\n            }\n            else\n            {\n                Prefix = \"CustomizedDefaultPrefix\";\n            }\n        }\n\n        public string Prefix { get; private set; }\n    }\n\n    [CustomizedRoutePrefix(typeof(HomeWithCustomizedRoutePrefixController))]\n    public class HomeWithCustomizedRoutePrefixController : ApiController\n    {\n        [Route(\"Introduction\")]\n        public string Get()\n        {\n            return \"Home.Index()\";\n        }\n    }\n\n    [CustomizedRoutePrefix(typeof(AccountWithCustomizedRoutePrefixController))]\n    public class AccountWithCustomizedRoutePrefixController : ApiController\n    {\n        [Route(\"PeopleList\")]\n        public string Get()\n        {\n            return \"Account.Index()\";\n        }\n    }\n\n    [CustomizedRoutePrefix(typeof(OtherWithCustomizedRoutePrefixController))]\n    public class OtherWithCustomizedRoutePrefixController : ApiController\n    {\n        [Route(\"Unknown\")]\n        public String Get()\n        {\n            return \"Default.Index()\";\n    }\n    }\n\n    [Route(\"ambiguousmatch\")]\n    public class AmbiguousMatch1Controller : ApiController\n    {\n        public string Get()\n        {\n            return \"Get()\";\n        }\n    }\n\n    [Route(\"ambiguousmatch\")]\n    public class AmbiguousMatch2Controller : ApiController\n    {\n        public string Get()\n        {\n            return \"Get()\";\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Routing/DefaultDirectRouteProviderTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Internal;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Routing\n{\n    public class DefaultDirectRouteProviderTests\n    {\n        [Fact]\n        public void GetActionDirectRoutes_IfDirectRouteProviderReturnsNull_Throws()\n        {\n            // Arrange\n            var factories = new[] { CreateStubRouteFactory(null) };\n            var action = CreateStubActionDescriptor(\"IgnoreAction\");\n            var constraintResolver = new Mock<IInlineConstraintResolver>(MockBehavior.Strict).Object;\n\n            var provider = new AccessibleDirectRouteProvider();\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => provider.GetActionDirectRoutes(action, factories, constraintResolver),\n                \"IDirectRouteFactory.CreateRoute must not return null.\");\n        }\n\n        [Fact]\n        public void GetControllerDirectRoutes_IfDirectRouteProviderReturnsNull_Throws()\n        {\n            // Arrange\n            var factories = new[] { CreateStubRouteFactory(null) };\n            var action = CreateStubActionDescriptor(\"IgnoreAction\");\n            var constraintResolver = new Mock<IInlineConstraintResolver>(MockBehavior.Strict).Object;\n\n            var provider = new AccessibleDirectRouteProvider();\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => provider.GetControllerDirectRoutes(action.ControllerDescriptor, new[] { action }, factories, constraintResolver),\n                \"IDirectRouteFactory.CreateRoute must not return null.\");\n        }\n\n        [Fact]\n        public void GetActionDirectRoutes_IfDirectRouteProviderReturnsRouteWithoutActionDescriptors_Throws()\n        {\n            // Arrange\n            IHttpRoute route = new Mock<IHttpRoute>().Object;\n            RouteEntry entry = new RouteEntry(name: null, route: route);\n            var factories = new[] { CreateStubRouteFactory(entry) };\n\n            var action = CreateStubActionDescriptor(\"IgnoreAction\");\n            var constraintResolver = new Mock<IInlineConstraintResolver>(MockBehavior.Strict).Object;\n\n            var provider = new AccessibleDirectRouteProvider();\n\n            // Act & Assert\n            string expectedMessage = \"The route does not have any associated action descriptors. Routing requires \" +\n                \"that each direct route map to a non-empty set of actions.\";\n            Assert.Throws<InvalidOperationException>(\n                () => provider.GetActionDirectRoutes(action, factories, constraintResolver),\n                expectedMessage);\n        }\n\n        [Fact]\n        public void GetControllerDirectRoutes_IfDirectRouteProviderReturnsRouteWithoutActionDescriptors_Throws()\n        {\n            // Arrange\n            IHttpRoute route = new Mock<IHttpRoute>().Object;\n            RouteEntry entry = new RouteEntry(name: null, route: route);\n            var factories = new[] { CreateStubRouteFactory(entry) };\n\n            var action = CreateStubActionDescriptor(\"IgnoreAction\");\n            var constraintResolver = new Mock<IInlineConstraintResolver>(MockBehavior.Strict).Object;\n\n            var provider = new AccessibleDirectRouteProvider();\n\n            // Act & Assert\n            string expectedMessage = \"The route does not have any associated action descriptors. Routing requires \" +\n                \"that each direct route map to a non-empty set of actions.\";\n            Assert.Throws<InvalidOperationException>(\n                () => provider.GetControllerDirectRoutes(action.ControllerDescriptor, new[] { action }, factories, constraintResolver),\n                expectedMessage);\n        }\n\n        [Fact]\n        public void GetActionDirectRoutes_IfDirectRouteProviderReturnsRouteWithEmptyActionDescriptors_Throws()\n        {\n            // Arrange\n            HttpRouteValueDictionary dataTokens = new HttpRouteValueDictionary\n            {\n                { RouteDataTokenKeys.Actions, new HttpActionDescriptor[0] }\n            };\n            HttpRoute route = new HttpRoute(null, null, null, dataTokens);\n            RouteEntry entry = new RouteEntry(name: null, route: route);\n            var factories = new[] { CreateStubRouteFactory(entry) };\n\n            var action = CreateStubActionDescriptor(\"IgnoreAction\");\n            var constraintResolver = new Mock<IInlineConstraintResolver>(MockBehavior.Strict).Object;\n\n            var provider = new AccessibleDirectRouteProvider();\n\n            // Act & Assert\n            string expectedMessage = \"The route does not have any associated action descriptors. Routing requires \" +\n                \"that each direct route map to a non-empty set of actions.\";\n            Assert.Throws<InvalidOperationException>(\n                () => provider.GetActionDirectRoutes(action, factories, constraintResolver),\n                expectedMessage);\n        }\n\n        [Fact]\n        public void GetControllerDirectRoute_IfDirectRouteProviderReturnsRouteWithEmptyActionDescriptors_Throws()\n        {\n            // Arrange\n            HttpRouteValueDictionary dataTokens = new HttpRouteValueDictionary\n            {\n                { RouteDataTokenKeys.Actions, new HttpActionDescriptor[0] }\n            };\n            HttpRoute route = new HttpRoute(null, null, null, dataTokens);\n            RouteEntry entry = new RouteEntry(name: null, route: route);\n            var factories = new[] { CreateStubRouteFactory(entry) };\n\n            var action = CreateStubActionDescriptor(\"IgnoreAction\");\n            var constraintResolver = new Mock<IInlineConstraintResolver>(MockBehavior.Strict).Object;\n\n            var provider = new AccessibleDirectRouteProvider();\n\n            // Act & Assert\n            string expectedMessage = \"The route does not have any associated action descriptors. Routing requires \" +\n                \"that each direct route map to a non-empty set of actions.\";\n            Assert.Throws<InvalidOperationException>(\n                () => provider.GetControllerDirectRoutes(action.ControllerDescriptor, new[] { action }, factories, constraintResolver),\n                expectedMessage);\n        }\n\n        [Fact]\n        public void GetActionDirectRoutes_IfDirectRouteProviderReturnsRouteWithHandler_Throws()\n        {\n            // Arrange\n            var action = CreateStubActionDescriptor(\"IgnoreAction\");\n\n            HttpRouteValueDictionary dataTokens = new HttpRouteValueDictionary\n            {\n                { RouteDataTokenKeys.Actions, new HttpActionDescriptor[] { action } }\n            };\n            HttpMessageHandler handler = new Mock<HttpMessageHandler>(MockBehavior.Strict).Object;\n            HttpRoute route = new HttpRoute(null, null, null, dataTokens, handler);\n            RouteEntry entry = new RouteEntry(name: null, route: route);\n            var factories = new[] { CreateStubRouteFactory(entry) };\n\n            var constraintResolver = new Mock<IInlineConstraintResolver>(MockBehavior.Strict).Object;\n\n            var provider = new AccessibleDirectRouteProvider();\n\n            // Act & Assert\n            string expectedMessage = \"Direct routing does not support per-route message handlers.\";\n            Assert.Throws<InvalidOperationException>(\n                () => provider.GetActionDirectRoutes(action, factories, constraintResolver), \n                expectedMessage);\n        }\n\n        [Fact]\n        public void GetControllerDirectRoutes_IfDirectRouteProviderReturnsRouteWithHandler_Throws()\n        {\n            // Arrange\n            var action = CreateStubActionDescriptor(\"IgnoreAction\");\n\n            HttpRouteValueDictionary dataTokens = new HttpRouteValueDictionary\n            {\n                { RouteDataTokenKeys.Actions, new HttpActionDescriptor[] { action } }\n            };\n            HttpMessageHandler handler = new Mock<HttpMessageHandler>(MockBehavior.Strict).Object;\n            HttpRoute route = new HttpRoute(null, null, null, dataTokens, handler);\n            RouteEntry entry = new RouteEntry(name: null, route: route);\n            var factories = new[] { CreateStubRouteFactory(entry) };\n\n            var constraintResolver = new Mock<IInlineConstraintResolver>(MockBehavior.Strict).Object;\n\n            var provider = new AccessibleDirectRouteProvider();\n\n            // Act & Assert\n            string expectedMessage = \"Direct routing does not support per-route message handlers.\";\n            Assert.Throws<InvalidOperationException>(\n                () => provider.GetControllerDirectRoutes(action.ControllerDescriptor, new[] { action }, factories, constraintResolver),\n                expectedMessage);\n        }\n\n        [Fact]\n        public void GetRoutePrefix_WithMultiRoutePrefix_ThrowsInvalidOperationException()\n        {\n            // Arrange\n            var httpControllerDescriptor = new MultiRoutePrefixControllerDescripter();\n            var typeMock = new Mock<Type>();\n            typeMock.SetupGet(t => t.FullName).Returns(\"Namespace.TypeFullName\");\n            httpControllerDescriptor.ControllerType = typeMock.Object;\n\n            var provider = new AccessibleDirectRouteProvider();\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => provider.GetRoutePrefix(httpControllerDescriptor),\n                \"Only one route prefix attribute is supported. Remove extra attributes from the controller of type 'Namespace.TypeFullName'.\");\n        }\n\n        [Fact]\n        public void GetRoutePrefix_WithNullPrefix_ThrowsInvalidOperationException()\n        {\n            // Arrange\n            var httpControllerDescriptor = new NullRoutePrefixControllerDescripter();\n            var typeMock = new Mock<Type>();\n            typeMock.SetupGet(t => t.FullName).Returns(\"Namespace.TypeFullName\");\n            httpControllerDescriptor.ControllerType = typeMock.Object;\n\n            var provider = new AccessibleDirectRouteProvider();\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => provider.GetRoutePrefix(httpControllerDescriptor),\n                \"The property 'prefix' from route prefix attribute on controller of type 'Namespace.TypeFullName' cannot be null.\");\n        }\n\n        private static HttpActionDescriptor CreateStubActionDescriptor(string actionName)\n        {\n            Mock<HttpActionDescriptor> mock = new Mock<HttpActionDescriptor>(MockBehavior.Strict, new Mock<HttpControllerDescriptor>().Object);\n            mock.SetupGet(d => d.ActionName).Returns(actionName);\n            return mock.Object;\n        }\n\n        private static IDirectRouteFactory CreateStubRouteFactory(RouteEntry entry)\n        {\n            Mock<IDirectRouteFactory> mock = new Mock<IDirectRouteFactory>(MockBehavior.Strict);\n            mock.Setup(p => p.CreateRoute(It.IsAny<DirectRouteFactoryContext>())).Returns(entry);\n            return mock.Object;\n        }\n\n        private class MultiRoutePrefixControllerDescripter : HttpControllerDescriptor\n        {\n            public override Collection<T> GetCustomAttributes<T>(bool inherit)\n            {\n                object[] attributes = new object[] { new ExtendedRoutePrefixAttribute(), new RoutePrefixAttribute(\"Prefix\") };\n                return new Collection<T>(TypeHelper.OfType<T>(attributes));\n            }\n        }\n\n        private class NullRoutePrefixControllerDescripter : HttpControllerDescriptor\n        {\n            public override Collection<T> GetCustomAttributes<T>(bool inherit)\n            {\n                object[] attributes = new object[] { new ExtendedRoutePrefixAttribute() };\n                return new Collection<T>(TypeHelper.OfType<T>(attributes));\n            }\n        }\n\n        private class ExtendedRoutePrefixAttribute : RoutePrefixAttribute\n        {\n        }\n\n        private class AccessibleDirectRouteProvider : DefaultDirectRouteProvider\n        {\n            public new IReadOnlyCollection<IDirectRouteFactory> GetActionRouteFactories(HttpActionDescriptor actionDescriptor)\n            {\n                return base.GetActionRouteFactories(actionDescriptor);\n            }\n\n            public new IReadOnlyList<RouteEntry> GetControllerDirectRoutes(\n                HttpControllerDescriptor controllerDescriptor,\n                IReadOnlyList<HttpActionDescriptor> actionDescriptors,\n                IReadOnlyList<IDirectRouteFactory> factories,\n                IInlineConstraintResolver constraintResolver)\n            {\n                return base.GetControllerDirectRoutes(controllerDescriptor, actionDescriptors, factories, constraintResolver);\n            }\n\n            public new IReadOnlyList<RouteEntry> GetActionDirectRoutes(\n                HttpActionDescriptor actionDescriptor,\n                IReadOnlyList<IDirectRouteFactory> factories,\n                IInlineConstraintResolver constraintResolver)\n            {\n                return base.GetActionDirectRoutes(actionDescriptor, factories, constraintResolver);\n            }\n\n            public new IReadOnlyCollection<IDirectRouteFactory> GetControllerRouteFactories(HttpControllerDescriptor controllerDescriptor)\n            {\n                return base.GetControllerRouteFactories(controllerDescriptor);\n            }\n\n            public new string GetRoutePrefix(HttpControllerDescriptor controllerDescriptor)\n            {\n                return base.GetRoutePrefix(controllerDescriptor);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Routing/DirectRouteProviderContextTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Routing\n{\n    public class DirectRouteProviderContextTests\n    {\n        [Fact]\n        public void CreateBuilderWithoutResolverAndBuild_SetsActionsDataToken()\n        {\n            var actions = new HttpActionDescriptor[] { new ReflectedHttpActionDescriptor() };\n\n            var route = BuildWithoutResolver(\"route\", actions);\n\n            var actualActions = route.DataTokens[RouteDataTokenKeys.Actions];\n            Assert.Equal(actions, actualActions);\n        }\n\n        [Fact]\n        public void CreateBuilderWithoutResolverAndBuild_AddsDefaultValuesAsOptional()\n        {\n            var actions = new ReflectedHttpActionDescriptor[] { new ReflectedHttpActionDescriptor() };\n            var route = BuildWithoutResolver(\"movies/{id}\", actions);\n            route.Defaults.Add(\"id\", RouteParameter.Optional);\n\n            var routeData = route.GetRouteData(\"\", new HttpRequestMessage(HttpMethod.Get, \"http://localhost/movies\"));\n\n            Assert.Equal(RouteParameter.Optional, routeData.Values[\"id\"]);\n        }\n\n        [Fact]\n        public void CreateBuilderWithResolverAndBuild_Throws_WhenConstraintResolverReturnsNull()\n        {\n            Mock<IInlineConstraintResolver> constraintResolver = new Mock<IInlineConstraintResolver>();\n            constraintResolver.Setup(r => r.ResolveConstraint(\"constraint\")).Returns<IHttpRouteConstraint>(null);\n\n            var ex = Assert.Throws<InvalidOperationException>(\n                () => BuildWithResolver(@\"hello/{param:constraint}\", constraintResolver: constraintResolver.Object));\n            Assert.Matches(\n                \"The inline constraint resolver of type 'IInlineConstraintResolverProxy' was unable to resolve the following inline constraint: 'constraint'.\",\n                ex.Message);\n        }\n\n        [Fact]\n        public void CreateBuilderWithResolverAndBuild_ResolvesConstraintUsingConstraintResolver()\n        {\n            IHttpRouteConstraint routeConstraint = new Mock<IHttpRouteConstraint>().Object;\n            Mock<IInlineConstraintResolver> constraintResolver = new Mock<IInlineConstraintResolver>();\n            constraintResolver.Setup(r => r.ResolveConstraint(\"constraint\")).Returns(routeConstraint);\n\n            var route = BuildWithResolver(@\"hello/{param:constraint}\", constraintResolver: constraintResolver.Object);\n\n            Assert.Equal(\"hello/{param}\", route.RouteTemplate);\n            Assert.Equal(routeConstraint, route.Constraints[\"param\"]);\n        }\n\n        private static IHttpRoute BuildWithoutResolver(string template,\n            IReadOnlyCollection<HttpActionDescriptor> actions)\n        {\n            DirectRouteFactoryContext context = new DirectRouteFactoryContext(null, actions,\n                new Mock<IInlineConstraintResolver>(MockBehavior.Strict).Object, targetIsAction: true);\n            IDirectRouteBuilder builder = context.CreateBuilder(template, constraintResolver: null);\n            return builder.Build().Route;\n        }\n\n        private static IHttpRoute BuildWithResolver(string template, IInlineConstraintResolver constraintResolver)\n        {\n            HttpActionDescriptor[] actions = new HttpActionDescriptor[] { new ReflectedHttpActionDescriptor() };\n            DirectRouteFactoryContext context = new DirectRouteFactoryContext(null, actions, constraintResolver, targetIsAction: true);\n\n            // Act\n            IDirectRouteBuilder builder = context.CreateBuilder(template);\n            IHttpRoute route = builder.Build().Route;\n\n            // Assertions for default, unspecified behavior:\n            Assert.NotNull(route);\n            Assert.Equal(actions, route.DataTokens[\"actions\"]);\n\n            return route;\n        }\n\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Routing/HttpRouteTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Routing\n{\n    public class HttpRouteTest\n    {\n        [Theory]\n        [InlineData(\"123 456\")]\n        [InlineData(\"123 {456\")]\n        [InlineData(\"123 [45]6\")]\n        [InlineData(\"123 (4)56\")]\n        [InlineData(\"abc+56\")]\n        [InlineData(\"abc.56\")]\n        [InlineData(\"abc*56\")]\n        [InlineData(@\"hello12.1[)]*^$=!@23}\")]\n        public void GetRouteData_HandlesUrlEncoding(string id)\n        {\n            HttpRoute route = new HttpRoute(\"{controller}/{id}\");\n            Uri uri = new Uri(\"http://localhost/test/\" + id + \"/\");\n            IHttpRouteData routeData = route.GetRouteData(\"\", new HttpRequestMessage(HttpMethod.Get, uri));\n            Assert.Equal(\"test\", routeData.Values[\"controller\"]);\n            Assert.Equal(id, routeData.Values[\"id\"]);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Routing/HttpRouteValueDictionaryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Routing\n{\n    public class HttpRouteValueDictionaryTest\n    {\n        private static readonly Dictionary<string, object> data0 = null;\n        private static readonly Dictionary<string, object> data1 = new Dictionary<string, object>();\n        private static readonly Dictionary<string, object> data2 = new Dictionary<string, object> \n            {\n                { \"key1\", \"value1\" },\n                { \"key2\", 2 },\n                { \"key3\", TimeSpan.FromDays(1) },\n            };\n\n        public static TheoryDataSet<Dictionary<string, object>, Dictionary<string, object>> DictionaryConstructorData\n        {\n            get\n            {\n                // Input, expected output\n                return new TheoryDataSet<Dictionary<string, object>, Dictionary<string, object>>\n                {\n                    { null, data1 },\n                    { data0, data1 },\n                    { data1, data1 },\n                    { data2, data2 },\n                };\n            }\n        }\n\n        public static TheoryDataSet<object, Dictionary<string, object>> ObjectConstructorData\n        {\n            get\n            {\n                // Input, expected output\n                return new TheoryDataSet<object, Dictionary<string, object>>\n                {\n                    { null, data1 },\n                    { data0, data1 },\n                    { data1, data1 },\n                    { new { }, data1},\n                    { data2, data2 },\n                    { new { key1 = \"value1\", key2 = 2, key3 = TimeSpan.FromDays(1) }, data2},\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"DictionaryConstructorData\")]\n        public void Constructor_AcceptsDictionaryValues(Dictionary<string, object> input, Dictionary<string, object> expectedOutput)\n        {\n            HttpRouteValueDictionary routeValues = new HttpRouteValueDictionary(input);\n            Assert.True(expectedOutput.SequenceEqual(routeValues));\n        }\n\n        [Theory]\n        [PropertyData(\"ObjectConstructorData\")]\n        public void Constructor_AcceptsObjectValues(object input, Dictionary<string, object> expectedOutput)\n        {\n            HttpRouteValueDictionary routeValues = new HttpRouteValueDictionary(input);\n            Assert.True(expectedOutput.SequenceEqual(routeValues));\n        }\n\n        [Fact]\n        public void Constructor_IsCaseInsensitive()\n        {\n            // Arrange\n            HttpRouteValueDictionary routeValues = new HttpRouteValueDictionary();\n\n            // Act\n            routeValues.Add(\"KEY\", null);\n\n            // Assert\n            Assert.True(routeValues.ContainsKey(\"key\"));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Routing/LinkGenerationRouteTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Routing\n{\n    public class LinkGenerationRouteTests\n    {\n        [Fact]\n        public void GenerateRoute_DoesNotClaimData()\n        {\n            LinkGenerationRoute route = new LinkGenerationRoute(new InnerRoute());\n\n            IHttpRouteData data = route.GetRouteData(string.Empty, new HttpRequestMessage());\n\n            Assert.Null(data);\n        }\n\n        [Fact]\n        public void GenerateRoute_ForwardsInnerProperties()\n        {\n            IHttpRoute innerRoute = new InnerRoute();\n            LinkGenerationRoute route = new LinkGenerationRoute(innerRoute);\n\n            Assert.NotNull(route.Defaults);\n            Assert.Equal(innerRoute.Defaults, route.Defaults);\n\n            Assert.NotNull(route.Constraints);\n            Assert.Equal(innerRoute.Constraints, route.Constraints);\n\n            Assert.NotNull(route.DataTokens);\n            Assert.Equal(innerRoute.DataTokens, route.DataTokens);\n\n            Assert.NotNull(innerRoute.Handler);\n            Assert.Null(route.Handler);\n\n            Assert.NotNull(route.RouteTemplate);\n            Assert.Equal(innerRoute.RouteTemplate, route.RouteTemplate);\n        }\n\n        [Fact]\n        public void GenerateRoute_GetVirtualPathIsForwarded()\n        {\n            HttpRequestMessage request = new HttpRequestMessage();\n            IDictionary<string, object> values = new Dictionary<string, object>();\n\n            IHttpVirtualPathData data = new Mock<IHttpVirtualPathData>().Object;\n\n            Mock<IHttpRoute> inner = new Mock<IHttpRoute>();\n            inner.Setup(r => r.GetVirtualPath(request, values)).Returns(data);\n\n            LinkGenerationRoute route = new LinkGenerationRoute(inner.Object);\n\n            IHttpVirtualPathData result = route.GetVirtualPath(request, values);\n\n            Assert.Equal(data, result);\n        }\n\n        // Route where everything is not implemented. Tests that the generated route is not forwarding calls. \n        private class InnerRoute : IHttpRoute\n        {\n            private readonly IHttpRouteData _routeData = new Mock<IHttpRouteData>().Object;\n            private readonly IHttpVirtualPathData _virtualPathData = new Mock<IHttpVirtualPathData>().Object;\n\n            public InnerRoute()\n            {\n                Defaults = new Dictionary<string, object>();\n                Defaults.Add(\"default\", \"value\");\n\n                Constraints = new Dictionary<string, object>();\n                Constraints.Add(\"constraint\", \"value\");\n\n                DataTokens = new Dictionary<string, object>();\n                DataTokens.Add(\"token\", \"value\");\n\n                Handler = new Mock<HttpMessageHandler>().Object;\n            }\n\n            public string RouteTemplate\n            {\n                get { return \"InnerRoute\"; }\n            }\n\n            public IDictionary<string, object> Defaults { get; private set; }\n\n            public IDictionary<string, object> Constraints { get; private set; }\n\n            public IDictionary<string, object> DataTokens { get; private set; }\n\n            public HttpMessageHandler Handler { get; private set; }\n\n            public IHttpRouteData GetRouteData(string virtualPathRoot, HttpRequestMessage request)\n            {\n                return _routeData;\n            }\n\n            public IHttpVirtualPathData GetVirtualPath(HttpRequestMessage request, Collections.Generic.IDictionary<string, object> values)\n            {\n                return _virtualPathData;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Routing/MediaTypeFormatterExtensionsTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Headers;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Net.Http.Formatting\n{\n    public class MediaTypeFormatterExtensionsTests\n    {\n        [Fact]\n        public void AddUriPathExtensionMapping_MediaTypeHeaderValue_ThrowsWithNullThis()\n        {\n            MediaTypeFormatter formatter = null;\n            Assert.ThrowsArgumentNull(() => formatter.AddUriPathExtensionMapping(\"xml\", new MediaTypeHeaderValue(\"application/xml\")), \"formatter\");\n        }\n\n        [Fact]\n        public void AddUriPathExtensionMapping_MediaTypeHeaderValue_UpdatesMediaTypeMappingsCollection()\n        {\n            MediaTypeFormatter mockFormatter = new Mock<MediaTypeFormatter> { CallBase = true }.Object;\n\n            mockFormatter.AddUriPathExtensionMapping(\"ext\", new MediaTypeHeaderValue(\"application/test\"));\n\n            MediaTypeMapping mediaTypeMapping = Assert.Single(mockFormatter.MediaTypeMappings);\n            UriPathExtensionMapping uriPathExtensionMapping = Assert.IsType<UriPathExtensionMapping>(mediaTypeMapping);\n            Assert.Equal(\"ext\", uriPathExtensionMapping.UriPathExtension);\n            Assert.Equal(\"application/test\", uriPathExtensionMapping.MediaType.MediaType);\n        }\n\n        [Fact]\n        public void AddUriPathExtensionMapping_MediaType_ThrowsWithNullThis()\n        {\n            MediaTypeFormatter formatter = null;\n            Assert.ThrowsArgumentNull(() => formatter.AddUriPathExtensionMapping(\"xml\", \"application/xml\"), \"formatter\");\n        }\n\n        [Fact]\n        public void AddUriPathExtensionMapping_MediaType_UpdatesMediaTypeMappingsCollection()\n        {\n            MediaTypeFormatter mockFormatter = new Mock<MediaTypeFormatter> { CallBase = true }.Object;\n\n            mockFormatter.AddUriPathExtensionMapping(\"ext\", \"application/test\");\n\n            MediaTypeMapping mediaTypeMapping = Assert.Single(mockFormatter.MediaTypeMappings);\n            UriPathExtensionMapping uriPathExtensionMapping = Assert.IsType<UriPathExtensionMapping>(mediaTypeMapping);\n            Assert.Equal(\"ext\", uriPathExtensionMapping.UriPathExtension);\n            Assert.Equal(\"application/test\", uriPathExtensionMapping.MediaType.MediaType);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Routing/RouteAttributeTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http\n{\n    public class RouteAttributeTest\n    {\n        [Fact]\n        public void DefaultCtor_IsEmptyString()\n        {\n            RouteAttribute attribute = new RouteAttribute();\n\n            Assert.Equal(String.Empty, attribute.Template);\n        }\n        \n        [Fact]\n        public void Ctor_NotNull()\n        {\n            Assert.ThrowsArgumentNull(() => new RouteAttribute(null), \"template\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Routing/UriPathExtensionMappingTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Formatting.DataSets;\nusing System.Net.Http.Headers;\nusing System.Web.Http.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Net.Http.Formatting\n{\n    public class UriPathExtensionMappingTests\n    {\n        [Fact]\n        public void TypeIsCorrect()\n        {\n            Assert.Type.HasProperties(\n                typeof(UriPathExtensionMapping),\n                TypeAssert.TypeProperties.IsPublicVisibleClass,\n                typeof(MediaTypeMapping));\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalUriPathExtensions\",\n            typeof(HttpTestData), \"LegalMediaTypeStrings\")]\n        public void ConstructorMediaType_Initialises_MediaTypeAndUriPathExtension(string uriPathExtension, string mediaType)\n        {\n            UriPathExtensionMapping mapping = new UriPathExtensionMapping(uriPathExtension, mediaType);\n            Assert.Equal(uriPathExtension, mapping.UriPathExtension);\n            Assert.MediaType.AreEqual(mediaType, mapping.MediaType, \"Failed to set MediaType.\");\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(CommonUnitTestDataSets), \"EmptyStrings\",\n            typeof(HttpTestData), \"LegalMediaTypeStrings\")]\n        public void ConstructorMediaType_ThrowsWithEmptyUriPathExtension(string uriPathExtension, string mediaType)\n        {\n            Assert.ThrowsArgumentNull(() => new UriPathExtensionMapping(uriPathExtension, mediaType), \"uriPathExtension\");\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalUriPathExtensions\",\n            typeof(CommonUnitTestDataSets), \"EmptyStrings\")]\n        public void ConstructorMediaType_ThrowsWithEmptyMediaType(string uriPathExtension, string mediaType)\n        {\n            Assert.ThrowsArgumentNull(() => new UriPathExtensionMapping(uriPathExtension, mediaType), \"mediaType\");\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalUriPathExtensions\",\n            typeof(HttpTestData), \"LegalMediaTypeHeaderValues\")]\n        public void ConstructorMediaTypeHeaderValue_Initialises_MediaTypeAndUriPathExtension(string uriPathExtension, MediaTypeHeaderValue mediaType)\n        {\n            UriPathExtensionMapping mapping = new UriPathExtensionMapping(uriPathExtension, mediaType);\n            Assert.Equal(uriPathExtension, mapping.UriPathExtension);\n            Assert.MediaType.AreEqual(mediaType, mapping.MediaType, \"Failed to set MediaType.\");\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(CommonUnitTestDataSets), \"EmptyStrings\",\n            typeof(HttpTestData), \"LegalMediaTypeHeaderValues\")]\n        public void ConstructorMediaTypeHeaderValue_ThrowsWithEmptyUriPathExtension(string uriPathExtension, MediaTypeHeaderValue mediaType)\n        {\n            Assert.ThrowsArgumentNull(() => new UriPathExtensionMapping(uriPathExtension, mediaType), \"uriPathExtension\");\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalUriPathExtensions\")]\n        public void ConstructorMediaTypeHeaderValue_ThrowsWithEmptyMediaType(string uriPathExtension)\n        {\n            Assert.ThrowsArgumentNull(() => new UriPathExtensionMapping(uriPathExtension, (MediaTypeHeaderValue)null), \"mediaType\");\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalUriPathExtensions\",\n            typeof(HttpTestData), \"LegalMediaTypeStrings\",\n            typeof(HttpTestData), \"UriTestDataStrings\")]\n        public void TryMatchMediaType_Returns_MatchWithExtensionInRouteData(string uriPathExtension, string mediaType, string baseUriString)\n        {\n            GC.KeepAlive(baseUriString); // Mark parameter as used. See xUnit1026, [Theory] method doesn't use all parameters.\n            UriPathExtensionMapping mapping = new UriPathExtensionMapping(uriPathExtension, mediaType);\n            HttpRequestMessage request = GetRequestWithExtInRouteData(uriPathExtension);\n            Assert.Equal(1.0, mapping.TryMatchMediaType(request));\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalUriPathExtensions\",\n            typeof(HttpTestData), \"LegalMediaTypeStrings\",\n            typeof(HttpTestData), \"UriTestDataStrings\")]\n        public void TryMatchMediaType_Returns_MatchWithExtensionInRouteData_DifferCase(string uriPathExtension, string mediaType, string baseUriString)\n        {\n            GC.KeepAlive(baseUriString); // Mark parameter as used. See xUnit1026, [Theory] method doesn't use all parameters.\n            UriPathExtensionMapping mapping = new UriPathExtensionMapping(uriPathExtension.ToUpperInvariant(), mediaType);\n            HttpRequestMessage request = GetRequestWithExtInRouteData(uriPathExtension.ToLowerInvariant());\n            Assert.Equal(1.0, mapping.TryMatchMediaType(request));\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalUriPathExtensions\",\n            typeof(HttpTestData), \"LegalMediaTypeStrings\",\n            typeof(HttpTestData), \"UriTestDataStrings\")]\n        public void TryMatchMediaType_Returns_ZeroWithExtensionNotInRouteData(string uriPathExtension, string mediaType, string baseUriString)\n        {\n            UriPathExtensionMapping mapping = new UriPathExtensionMapping(uriPathExtension, mediaType);\n            Uri uri = new Uri(baseUriString);\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri);\n            Assert.Equal(0.0, mapping.TryMatchMediaType(request));\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(HttpTestData), \"LegalUriPathExtensions\",\n            typeof(HttpTestData), \"LegalMediaTypeStrings\")]\n        public void TryMatchMediaType_Throws_WithNullHttpRequestMessage(string uriPathExtension, string mediaType)\n        {\n            UriPathExtensionMapping mapping = new UriPathExtensionMapping(uriPathExtension, mediaType);\n            Assert.ThrowsArgumentNull(() => mapping.TryMatchMediaType(request: null), \"request\");\n        }\n\n        private static HttpRequestMessage GetRequestWithExtInRouteData(string extensionValue)\n        {\n            IHttpRoute route = new Mock<IHttpRoute>().Object;\n            IHttpRouteData routeData = new HttpRouteData(route);\n            routeData.Values[UriPathExtensionMapping.UriPathExtensionKey] = extensionValue;\n\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.SetRouteData(routeData);\n\n            return request;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Routing/UrlHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Hosting;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Routing\n{\n    public class UrlHelperTest\n    {\n        public static TheoryDataSet<string, int?, string> UrlGeneratorTestData\n        {\n            get\n            {\n                return new TheoryDataSet<string, int?, string>()\n                {\n                    { null, 456, \"/somerootpath/people/456\"}, // Just override ID, so ID is replaced\n                    { \"people\", 456, \"/somerootpath/people/456\"}, // Just override ID, so ID is replaced\n                    { null, null, \"/somerootpath/people/123\"}, // Override nothing, so everything the same\n                    { \"people\", null, \"/somerootpath/people/123\"}, // Override nothing, so everything the same\n                    { \"customers\", 456, \"/somerootpath/customers/456\"}, // Override everything, so everything changed\n                    { \"customers\", null, null}, // Override controller, which clears out the ID, so it doesn't match (i.e. null)\n                };\n            }\n        }\n\n        public static TheoryDataSet<string> RequestUrlTestData\n        {\n            get\n            {\n                return new TheoryDataSet<string>\n                {\n                    \"http://localhost\",\n                    \"http://localhost/123\",\n                    \"http://localhost/123?q=odata&$filter=123#123\"\n                };\n            }\n        }\n\n        [Fact]\n        public void EmptyCtor_MeantForUnitTesting_DoesntThrow()\n        {\n            Assert.DoesNotThrow(() => new UrlHelper());\n        }\n\n        [Fact]\n        public void UrlHelper_CtorThrows_WithNullContext()\n        {\n            Assert.ThrowsArgumentNull(\n                () => new UrlHelper(null),\n                \"request\");\n        }\n\n        [Theory]\n        [PropertyData(\"UrlGeneratorTestData\")]\n        public void UrlHelper_UsesCurrentRouteDataToPopulateValues_WithObjectValues(string controller, int? id, string expectedUrl)\n        {\n            var url = GetUrlHelperForApi();\n            object routeValues = GetRouteValuesAsObject(controller, id);\n\n            string generatedUrl = url.Route(\"route1\", routeValues);\n\n            Assert.Equal(expectedUrl, generatedUrl);\n        }\n\n        [Theory]\n        [PropertyData(\"UrlGeneratorTestData\")]\n        public void UrlHelper_UsesCurrentRouteDataToPopulateValues_WithDictionaryValues(string controller, int? id, string expectedUrl)\n        {\n            var url = GetUrlHelperForApi();\n            Dictionary<string, object> routeValues = GetRouteValuesAsDictionary(controller, id);\n\n            string generatedUrl = url.Route(\"route1\", routeValues);\n\n            Assert.Equal(expectedUrl, generatedUrl);\n        }\n\n        [Fact]\n        public void UrlHelper_Throws_WhenWrongNameUsed_WithObjectValues()\n        {\n            var url = GetUrlHelperForApi();\n            Assert.ThrowsArgument(\n                () => url.Route(\"route-doesn't-exist\", null),\n                \"name\",\n                \"A route named 'route-doesn't-exist' could not be found in the route collection.\");\n        }\n\n        [Fact]\n        public void UrlHelper_Throws_WhenWrongNameUsed_WithDictionaryValues()\n        {\n            var url = GetUrlHelperForApi();\n            Assert.ThrowsArgument(\n                () => url.Route(\"route-doesn't-exist\", (IDictionary<string, object>)null),\n                \"name\",\n                \"A route named 'route-doesn't-exist' could not be found in the route collection.\");\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(UrlHelperTest), \"UrlGeneratorTestData\",\n            typeof(UrlHelperTest), \"RequestUrlTestData\")]\n        public void UrlHelper_LinkGeneration_GeneratesRightLinksWithDictionary(string controller, int? id, string expectedUrl, string requestUrl)\n        {\n            var urlHelper = GetUrlHelperForApi();\n            urlHelper.Request.RequestUri = new Uri(requestUrl);\n            Dictionary<string, object> routeValues = GetRouteValuesAsDictionary(controller, id);\n            string baseUrl = new Uri(requestUrl).GetLeftPart(UriPartial.Authority);\n\n            string generatedlink = urlHelper.Link(\"route1\", routeValues);\n\n            Assert.Equal(expectedUrl != null ? baseUrl + expectedUrl : null, generatedlink);\n        }\n\n        [Theory]\n        [TestDataSet(\n            typeof(UrlHelperTest), \"UrlGeneratorTestData\",\n            typeof(UrlHelperTest), \"RequestUrlTestData\")]\n        public void UrlHelper_LinkGeneration_GeneratesRightLinksWithObject(string controller, int? id, string expectedUrl, string requestUrl)\n        {\n            var urlHelper = GetUrlHelperForApi();\n            urlHelper.Request.Method = HttpMethod.Get;\n            urlHelper.Request.RequestUri = new Uri(requestUrl);\n            object routeValues = GetRouteValuesAsObject(controller, id);\n            string baseUrl = new Uri(requestUrl).GetLeftPart(UriPartial.Authority);\n\n            string generatedlink = urlHelper.Link(\"route1\", routeValues);\n\n            Assert.Equal(expectedUrl != null ? baseUrl + expectedUrl : null, generatedlink);\n        }\n\n        [Fact]\n        public void UrlHelper_Content_NoOpsAbsoluteUrl()\n        {\n            // Arrange\n            var request = new HttpRequestMessage();\n            request.RequestUri = new Uri(\"http://contoso.com/api/Products\");\n            var urlHelper = new UrlHelper(request);\n\n            // Act\n            string link = urlHelper.Content(\"http://microsoft.com/webapi\");\n\n            // Assert\n            Assert.Equal(\"http://microsoft.com/webapi\", link);\n        }\n\n        [Fact]\n        public void UrlHelper_Content_CombinesAbsolutePath()\n        {\n            // Arrange\n            var request = new HttpRequestMessage();\n            request.RequestUri = new Uri(\"http://contoso.com/api/Products\");\n            var urlHelper = new UrlHelper(request);\n\n            // Act\n            string link = urlHelper.Content(\"/store\");\n\n            // Assert\n            Assert.Equal(\"http://contoso.com/store\", link);\n        }\n\n        [Fact]\n        public void UrlHelper_Content_CombinesVirtualPath()\n        {\n            // Arrange\n            var request = new HttpRequestMessage();\n            request.SetRequestContext(new HttpRequestContext\n            {\n                VirtualPathRoot = \"/AppPath\"\n            });\n            request.RequestUri = new Uri(\"http://contoso.com/AppPath/api/Products\");\n            var urlHelper = new UrlHelper(request);\n\n            // Act\n            string link = urlHelper.Content(\"~/store\");\n\n            // Assert\n            Assert.Equal(\"http://contoso.com/AppPath/store\", link);\n        }\n\n        [Fact]\n        public void UrlHelper_Content_UsesVirtualPathFromConfiguration()\n        {\n            // Arrange\n            var request = new HttpRequestMessage();\n            request.SetConfiguration(new HttpConfiguration(new HttpRouteCollection(\"/AppPath\")));\n            request.RequestUri = new Uri(\"http://contoso.com/AppPath/api/Products\");\n            var urlHelper = new UrlHelper(request);\n\n            // Act\n            string link = urlHelper.Content(\"~/store\");\n\n            // Assert\n            Assert.Equal(\"http://contoso.com/AppPath/store\", link);\n        }\n\n        [Fact]\n        public void UrlHelper_Content_DefaultsVirtualPathToSlash()\n        {\n            // Arrange\n            var request = new HttpRequestMessage();\n            request.SetRequestContext(new HttpRequestContext());\n            request.RequestUri = new Uri(\"http://contoso.com/api/Products\");\n            var urlHelper = new UrlHelper(request);\n\n            // Act\n            string link = urlHelper.Content(\"~/store\");\n\n            // Assert\n            Assert.Equal(\"http://contoso.com/store\", link);\n        }\n\n        private static UrlHelper GetUrlHelperForApi()\n        {\n            HttpRequestMessage request = new HttpRequestMessage();\n\n            // Set up routes\n            var routes = new HttpRouteCollection(\"/somerootpath\");\n            IHttpRoute route = routes.MapHttpRoute(\"route1\", \"{controller}/{id}\");\n            request.Properties[HttpPropertyKeys.HttpConfigurationKey] = new HttpConfiguration(routes);\n            request.Properties[HttpPropertyKeys.HttpRouteDataKey] = new HttpRouteData(route, new HttpRouteValueDictionary(new { controller = \"people\", id = \"123\" }));\n\n            return new UrlHelper(request);\n        }\n\n        private static object GetRouteValuesAsObject(string controller, int? id)\n        {\n            object routeValues = null;\n            if (controller == null)\n            {\n                if (id == null)\n                {\n                    routeValues = null;\n                }\n                else\n                {\n                    routeValues = new { id };\n                }\n            }\n            else\n            {\n                if (id == null)\n                {\n                    routeValues = new { controller };\n                }\n                else\n                {\n                    routeValues = new { controller, id };\n                }\n            }\n\n            return routeValues;\n        }\n\n        private static Dictionary<string, object> GetRouteValuesAsDictionary(string controller, int? id)\n        {\n            Dictionary<string, object> routeValues = new Dictionary<string, object>();\n            if (controller == null)\n            {\n                if (id == null)\n                {\n                    routeValues = null;\n                }\n                else\n                {\n                    routeValues.Add(\"id\", id);\n                }\n            }\n            else\n            {\n                if (id == null)\n                {\n                    routeValues.Add(\"controller\", controller);\n                }\n                else\n                {\n                    routeValues.Add(\"controller\", controller);\n                    routeValues.Add(\"id\", id);\n                }\n            }\n\n            return routeValues;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Services/ControllerServicesTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Dependencies;\nusing System.Web.Http.ValueProviders;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Services\n{\n    public class ControllerServicesTests\n    {\n        [Fact]\n        public void Get_Falls_Through_To_Global()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            ControllerServices cs = new ControllerServices(config.Services);\n\n            // Act\n            IActionValueBinder localVal = (IActionValueBinder) cs.GetService(typeof(IActionValueBinder));\n            IActionValueBinder globalVal = (IActionValueBinder) config.Services.GetService(typeof(IActionValueBinder));\n            \n            // Assert\n            // Local controller didn't override, should get same value as global case.\n            Assert.Same(localVal, globalVal);\n        }\n\n        [Fact]\n        public void Controller_Overrides_Global()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            ControllerServices cs = new ControllerServices(config.Services);\n                        \n            IActionValueBinder newLocalService = new Mock<IActionValueBinder>().Object;\n            cs.Replace(typeof(IActionValueBinder), newLocalService);\n\n            // Act            \n            IActionValueBinder localVal = (IActionValueBinder)cs.GetService(typeof(IActionValueBinder));\n            IActionValueBinder globalVal = (IActionValueBinder)config.Services.GetService(typeof(IActionValueBinder));\n\n            // Assert\n            // Local controller didn't override, should get same value as global case.\n            Assert.Same(localVal, newLocalService);\n            Assert.NotSame(localVal, globalVal);\n        }\n\n        [Fact]\n        public void Controller_Overrides_DependencyInjection()\n        {\n            // Setting on Controller config overrides the DI container. \n            HttpConfiguration config = new HttpConfiguration();\n\n            IActionValueBinder newDIService = new Mock<IActionValueBinder>().Object;\n            var mockDependencyResolver = new Mock<IDependencyResolver>();\n            mockDependencyResolver.Setup(dr => dr.GetService(typeof(IActionValueBinder))).Returns(newDIService);\n            config.DependencyResolver = mockDependencyResolver.Object;\n            \n            ControllerServices cs = new ControllerServices(config.Services);\n\n            IActionValueBinder newLocalService = new Mock<IActionValueBinder>().Object;\n            cs.Replace(typeof(IActionValueBinder), newLocalService);\n\n            // Act            \n            IActionValueBinder localVal = (IActionValueBinder)cs.GetService(typeof(IActionValueBinder));\n            IActionValueBinder globalVal = (IActionValueBinder)config.Services.GetService(typeof(IActionValueBinder));\n\n            // Assert\n            // Local controller didn't override, should get same value as global case.            \n            Assert.Same(newDIService, globalVal); // asking the config will give back the DI service\n            Assert.Same(newLocalService, localVal); // but asking locally will get back the local service.\n        }\n\n        [Fact]\n        public void Controller_Appends_Inherited_List()\n        {\n            // Controller Services has \"copy on write\" semantics for inherited list. \n            // It can get the inherited list and mutate it. \n\n            HttpConfiguration config = new HttpConfiguration();\n            ServicesContainer global = config.Services;\n\n            ControllerServices cs = new ControllerServices(config.Services);\n\n            ValueProviderFactory vpf = new Mock<ValueProviderFactory>().Object;\n\n            // Act\n            cs.Add(typeof(ValueProviderFactory), vpf); // appends to end\n\n            // Assert\n            IEnumerable<object> original = global.GetServices(typeof(ValueProviderFactory));\n            object[] modified = cs.GetServices(typeof(ValueProviderFactory)).ToArray();\n\n            Assert.True(original.Count() > 1);\n            object[] expected = original.Concat(new object[] { vpf }).ToArray();\n            Assert.Equal(expected, modified);\n        }\n\n        [Fact]\n        public void Controller_Clear_Single_Item()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            ServicesContainer global = config.Services;\n\n            ControllerServices cs = new ControllerServices(config.Services);\n            IActionValueBinder newLocalService = new Mock<IActionValueBinder>().Object;\n            cs.Replace(typeof(IActionValueBinder), newLocalService);\n\n            // Act\n            cs.Clear(typeof(IActionValueBinder));\n\n            // Assert\n            IActionValueBinder localVal = (IActionValueBinder)cs.GetService(typeof(IActionValueBinder));\n            IActionValueBinder globalVal = (IActionValueBinder)config.Services.GetService(typeof(IActionValueBinder));\n\n            Assert.Same(globalVal, localVal);\n        }\n\n        [Fact]\n        public void Controller_Set_Null()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            ServicesContainer global = config.Services;\n\n            ControllerServices cs = new ControllerServices(config.Services);\n\n            // Act\n            // Setting to null is not the same as clear. Clear() means fall through to global config. \n            cs.Replace(typeof(IActionValueBinder), null);\n\n            // Assert\n            IActionValueBinder localVal = (IActionValueBinder)cs.GetService(typeof(IActionValueBinder));\n            \n            Assert.Null(localVal);\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Test/Services/DecoratorTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Services\n{\n    public class DecoratorTests\n    {\n        [Fact]\n        public void GetInner_Returns_Inner_Object_From_ObjectWrapper()\n        {\n            // Arrange\n            DummyAggregatedClass dummyInnerObject = new DummyAggregatedClass();\n            DummyObjectWrapper dummyObjectWrapper = new DummyObjectWrapper(dummyInnerObject);\n            IBaseInterface dummyBase = dummyObjectWrapper as IBaseInterface;\n\n            // Act\n            DummyAggregatedClass innerObject = Decorator.GetInner(dummyBase) as DummyAggregatedClass;\n\n            // Assert\n            Assert.Same(dummyInnerObject, innerObject);\n        }\n\n        [Fact]\n        public void GetInner_Returns_InnerMost_Object_From_ObjectWrapper()\n        {\n            // Arrange\n            DummyAggregatedClass dummyInnerObject = new DummyAggregatedClass();\n            DummyObjectWrapper dummyObjectWrapper = new DummyObjectWrapper(dummyInnerObject);\n            DummyDoubleLayerWrapper dummyDoubleLayerWrapper = new DummyDoubleLayerWrapper(dummyObjectWrapper);\n            IBaseInterface dummyBase = dummyDoubleLayerWrapper as IBaseInterface;\n\n            // Act\n            DummyAggregatedClass innerObject = Decorator.GetInner(dummyBase) as DummyAggregatedClass;\n\n            // Assert\n            Assert.Same(dummyInnerObject, innerObject);\n        }\n\n        [Fact]\n        public void GetInner_Call_On_InnerObject_Returns_InnerObject()\n        {\n            // Arrange\n            DummyAggregatedClass dummyInnerObject = new DummyAggregatedClass();\n            IBaseInterface dummyBase = dummyInnerObject as IBaseInterface;\n\n            // Act\n            DummyAggregatedClass innerObject = Decorator.GetInner(dummyBase) as DummyAggregatedClass;\n\n            // Assert\n            Assert.Same(dummyInnerObject, innerObject);\n        }\n\n        [Fact]\n        public void GetInner_Call_On_Wrapper_Which_Does_Not_Contain_InnerObject_Returns_Wrapper()\n        {\n            // Arrange\n            DummyWrapper dummyWrapper = new DummyWrapper();\n            IBaseInterface dummyBase = dummyWrapper as IBaseInterface;\n\n            // Act\n            DummyWrapper innerObject = Decorator.GetInner(dummyBase) as DummyWrapper;\n\n            // Assert\n            Assert.Same(dummyWrapper, innerObject);\n        }\n\n        [Fact]\n        public void GetInner_Returns_Itself_From_AnyClass_Which_Does_Not_Implement_Base_Interface()\n        {\n            // Arrange\n            Mock<object> dummyClass = new Mock<object>();\n\n            // Act\n            object innerObject = Decorator.GetInner(dummyClass.Object);\n\n            // Assert\n            Assert.Same(dummyClass.Object, innerObject);\n        }\n\n        [Fact]\n        public void GetInner_Returns_Null_When_Null_Is_Passed()\n        {\n            // Arrange\n            object nullValue = null;\n\n            // Act\n            object innerObject = Decorator.GetInner(nullValue);\n\n            // Assert\n            Assert.Null(innerObject);\n        }\n\n        [Fact]\n        public void GetInner_Returns_Inner_Object_From_ObjectWrapper_Which_Wraps_Itself()\n        {\n            // Arrange\n            DummyAggregatedClass dummyInnerObject = new DummyAggregatedClass();\n            DummyBaseWrapper dummyBaseWrapper = new DummyBaseWrapper(dummyInnerObject);\n            IBaseInterface dummyBase = dummyBaseWrapper as IBaseInterface;\n\n            // Act\n            DummyBaseWrapper innerObject = Decorator.GetInner(dummyBase) as DummyBaseWrapper;\n\n            // Assert\n            Assert.Same(dummyBaseWrapper, innerObject);\n        }\n\n        private interface IBaseInterface { }\n\n        private class DummyAggregatedClass : IBaseInterface { }\n\n        private class DummyWrapper : IBaseInterface { }\n\n        private class DummyObjectWrapper : IBaseInterface, IDecorator<DummyAggregatedClass>\n        {\n            private readonly DummyAggregatedClass _inner;\n\n            public DummyObjectWrapper(DummyAggregatedClass innerObject)\n            {\n                _inner = innerObject;\n            }\n\n            public DummyAggregatedClass Inner\n            {\n                get { return _inner; }\n            }\n        }\n\n        private class DummyDoubleLayerWrapper : IBaseInterface, IDecorator<DummyObjectWrapper>\n        {\n            private readonly DummyObjectWrapper _inner;\n\n            public DummyDoubleLayerWrapper(DummyObjectWrapper innerObject)\n            {\n                _inner = innerObject;\n            }\n\n            public DummyObjectWrapper Inner\n            {\n                get { return _inner; }\n            }\n        }\n\n        private class DummyBaseWrapper : IBaseInterface, IDecorator<IBaseInterface>\n        {\n            private readonly IBaseInterface _inner;\n\n            public DummyBaseWrapper(IBaseInterface innerObject)\n            {\n                _inner = innerObject;\n            }\n\n            public IBaseInterface Inner\n            {\n                get { return this; }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Services/DefaultServicesTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http.Formatting;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Dependencies;\nusing System.Web.Http.Description;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Metadata.Providers;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.ModelBinding.Binders;\nusing System.Web.Http.Tracing;\nusing System.Web.Http.Validation;\nusing System.Web.Http.Validation.Providers;\nusing System.Web.Http.ValueProviders;\nusing System.Web.Http.ValueProviders.Providers;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Services\n{\n    public class DefaultServicesTests\n    {\n        // Constructor tests\n\n        [Fact]\n        public void Constructor_GuardClauses()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(() => new DefaultServices(configuration: null), \"configuration\");\n        }\n\n        [Fact]\n        public void Constructor_DefaultServicesInContainer()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n\n            // Act\n            var defaultServices = new DefaultServices(config);\n\n            // Assert\n            Assert.Null(defaultServices.GetService(typeof(IDocumentationProvider)));\n            Assert.Null(defaultServices.GetService(typeof(ITraceWriter)));\n\n            Assert.IsType<DefaultActionValueBinder>(defaultServices.GetService(typeof(IActionValueBinder)));\n            Assert.IsType<ApiExplorer>(defaultServices.GetService(typeof(IApiExplorer)));\n            Assert.IsType<DefaultAssembliesResolver>(defaultServices.GetService(typeof(IAssembliesResolver)));\n            Assert.IsType<DefaultBodyModelValidator>(defaultServices.GetService(typeof(IBodyModelValidator)));\n            Assert.IsType<DefaultContentNegotiator>(defaultServices.GetService(typeof(IContentNegotiator)));\n            Assert.IsType<ApiControllerActionInvoker>(defaultServices.GetService(typeof(IHttpActionInvoker)));\n            Assert.IsType<ApiControllerActionSelector>(defaultServices.GetService(typeof(IHttpActionSelector)));\n            Assert.IsType<DefaultHttpControllerActivator>(defaultServices.GetService(typeof(IHttpControllerActivator)));\n            Assert.IsType<DefaultHttpControllerSelector>(defaultServices.GetService(typeof(IHttpControllerSelector)));\n            Assert.IsType<DefaultHttpControllerTypeResolver>(defaultServices.GetService(typeof(IHttpControllerTypeResolver)));\n            Assert.IsType<TraceManager>(defaultServices.GetService(typeof(ITraceManager)));\n            Assert.IsType<DataAnnotationsModelMetadataProvider>(defaultServices.GetService(typeof(ModelMetadataProvider)));\n            Assert.IsType<ModelValidatorCache>(defaultServices.GetService(typeof(IModelValidatorCache)));\n            Assert.IsType<DefaultExceptionHandler>(defaultServices.GetService(typeof(IExceptionHandler)));\n\n            object[] filterProviders = defaultServices.GetServices(typeof(IFilterProvider)).ToArray();\n            Assert.Equal(2, filterProviders.Length);\n            Assert.IsType<ConfigurationFilterProvider>(filterProviders[0]);\n            Assert.IsType<ActionDescriptorFilterProvider>(filterProviders[1]);\n\n            object[] modelBinderProviders = defaultServices.GetServices(typeof(ModelBinderProvider)).ToArray();\n            Assert.Equal(8, modelBinderProviders.Length);\n            Assert.IsType<TypeConverterModelBinderProvider>(modelBinderProviders[0]);\n            Assert.IsType<TypeMatchModelBinderProvider>(modelBinderProviders[1]);\n            Assert.IsType<KeyValuePairModelBinderProvider>(modelBinderProviders[2]);\n            Assert.IsType<ComplexModelDtoModelBinderProvider>(modelBinderProviders[3]);\n            Assert.IsType<ArrayModelBinderProvider>(modelBinderProviders[4]);\n            Assert.IsType<DictionaryModelBinderProvider>(modelBinderProviders[5]);\n            Assert.IsType<CollectionModelBinderProvider>(modelBinderProviders[6]);\n            Assert.IsType<MutableObjectModelBinderProvider>(modelBinderProviders[7]);\n\n            object[] validatorProviders = defaultServices.GetServices(typeof(ModelValidatorProvider)).ToArray();\n            Assert.Equal(2, validatorProviders.Length);\n            Assert.IsType<DataAnnotationsModelValidatorProvider>(validatorProviders[0]);\n            Assert.IsType<DataMemberModelValidatorProvider>(validatorProviders[1]);\n\n            object[] valueProviderFactories = defaultServices.GetServices(typeof(ValueProviderFactory)).ToArray();\n            Assert.Equal(2, valueProviderFactories.Length);\n            Assert.IsType<QueryStringValueProviderFactory>(valueProviderFactories[0]);\n            Assert.IsType<RouteDataValueProviderFactory>(valueProviderFactories[1]);\n\n            object[] exceptionLoggers = defaultServices.GetServices(typeof(IExceptionLogger)).ToArray();\n            Assert.Empty(exceptionLoggers);\n        }\n\n        // Add tests\n\n        [Fact]\n        public void Add_GuardClauses()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(() => defaultServices.Add(serviceType: null, service: new object()), \"serviceType\");\n            Assert.ThrowsArgumentNull(() => defaultServices.Add(typeof(object), service: null), \"service\");\n            Assert.ThrowsArgument(\n                () => defaultServices.Add(typeof(object), new object()),\n                \"serviceType\",\n                \"The service type Object is not supported.\");\n            Assert.ThrowsArgument(\n                () => defaultServices.Add(typeof(IHttpActionInvoker), new object()),\n                \"service\",\n                \"The type Object must derive from IHttpActionInvoker.\");\n        }\n\n        [Fact]\n        public void Add_AddsServiceToEndOfServicesList()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n            var filterProvider = new Mock<IFilterProvider>().Object;\n            IEnumerable<object> servicesBefore = defaultServices.GetServices(typeof(IFilterProvider));\n\n            // Act\n            defaultServices.Add(typeof(IFilterProvider), filterProvider);\n\n            // Assert\n            IEnumerable<object> servicesAfter = defaultServices.GetServices(typeof(IFilterProvider));\n            Assert.Equal(servicesBefore.Concat(new[] { filterProvider }), servicesAfter);\n        }\n\n        // AddRange tests\n\n        [Fact]\n        public void AddRange_GuardClauses()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(() => defaultServices.AddRange(serviceType: null, services: new[] { new object() }), \"serviceType\");\n            Assert.ThrowsArgumentNull(() => defaultServices.AddRange(typeof(object), services: null), \"services\");\n            Assert.ThrowsArgument(\n                () => defaultServices.AddRange(typeof(object), new[] { new object() }),\n                \"serviceType\",\n                \"The service type Object is not supported.\");\n            Assert.ThrowsArgument(() => defaultServices.AddRange(typeof(ValueProviderFactory), new[] { new object() }),\n                \"services\",\n                \"The type Object must derive from ValueProviderFactory.\");\n        }\n\n        [Fact]\n        public void AddRange_AddsServicesToEndOfServicesList()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n            var filterProvider = new Mock<IFilterProvider>().Object;\n            IEnumerable<object> servicesBefore = defaultServices.GetServices(typeof(IFilterProvider));\n\n            // Act\n            defaultServices.AddRange(typeof(IFilterProvider), new[] { filterProvider });\n\n            // Assert\n            IEnumerable<object> servicesAfter = defaultServices.GetServices(typeof(IFilterProvider));\n            Assert.Equal(servicesBefore.Concat(new[] { filterProvider }), servicesAfter);\n        }\n\n        [Fact]\n        public void AddRange_SkipsNullObjects()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n            IEnumerable<object> servicesBefore = defaultServices.GetServices(typeof(IFilterProvider));\n\n            // Act\n            defaultServices.AddRange(typeof(IFilterProvider), new object[] { null });\n\n            // Assert\n            IEnumerable<object> servicesAfter = defaultServices.GetServices(typeof(IFilterProvider));\n            Assert.Equal(servicesBefore, servicesAfter);\n        }\n\n        // Clear tests\n\n        [Fact]\n        public void Clear_GuardClauses()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(() => defaultServices.Clear(serviceType: null), \"serviceType\");\n            Assert.ThrowsArgument(\n                () => defaultServices.Clear(typeof(object)),\n                \"serviceType\",\n                \"The service type Object is not supported.\");\n        }\n\n        [Fact]\n        public void Clear_RemovesAllServices()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n            Assert.NotEmpty(defaultServices.GetServices(typeof(IFilterProvider)));\n\n            // Act\n            defaultServices.Clear(typeof(IFilterProvider));\n\n            // Assert\n            Assert.Empty(defaultServices.GetServices(typeof(IFilterProvider)));\n        }\n\n        // FindIndex tests\n\n        [Fact]\n        public void FindIndex_GuardClauses()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(() => defaultServices.FindIndex(serviceType: null, match: _ => true), \"serviceType\");\n            Assert.ThrowsArgumentNull(() => defaultServices.FindIndex(typeof(object), match: null), \"match\");\n            Assert.ThrowsArgument(\n                () => defaultServices.FindIndex(typeof(object), _ => true),\n                \"serviceType\",\n                \"The service type Object is not supported.\");\n        }\n\n        [Fact]\n        public void FindIndex_SuccessfulFind()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n\n            // Act\n            int index = defaultServices.FindIndex(typeof(IFilterProvider), _ => true);\n\n            // Assert\n            Assert.Equal(0, index);\n        }\n\n        [Fact]\n        public void FindIndex_FailedFind()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n\n            // Act\n            int index = defaultServices.FindIndex(typeof(IFilterProvider), _ => false);\n\n            // Assert\n            Assert.Equal(-1, index);\n        }\n\n        [Fact]\n        public void FindIndex_EmptyServiceListAlwaysReturnsFailure()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n            defaultServices.Clear(typeof(IFilterProvider));\n\n            // Act\n            int index = defaultServices.FindIndex(typeof(IFilterProvider), _ => true);\n\n            // Assert\n            Assert.Equal(-1, index);\n        }\n\n        // GetService tests\n\n        [Fact]\n        public void GetService_GuardClauses()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(() => defaultServices.GetService(serviceType: null), \"serviceType\");\n            Assert.ThrowsArgument(\n                () => defaultServices.GetService(typeof(object)),\n                \"serviceType\",\n                \"The service type Object is not supported.\");\n        }\n\n        [Fact]\n        public void GetService_ReturnsNullWhenServiceListEmpty()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n            defaultServices.Clear(typeof(IActionValueBinder));\n\n            // Act\n            object service = defaultServices.GetService(typeof(IActionValueBinder));\n\n            // Assert\n            Assert.Null(service);\n        }\n\n        [Fact]\n        public void GetService_PrefersServiceInDependencyInjectionContainer()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n            var filterProvider = new Mock<IActionValueBinder>().Object;\n            var mockDependencyResolver = new Mock<IDependencyResolver>();\n            mockDependencyResolver.Setup(dr => dr.GetService(typeof(IActionValueBinder))).Returns(filterProvider);\n            config.DependencyResolver = mockDependencyResolver.Object;\n\n            // Act\n            object service = defaultServices.GetService(typeof(IActionValueBinder));\n\n            // Assert\n            Assert.Same(filterProvider, service);\n        }\n\n        [Fact]\n        public void GetService_CachesResultFromDependencyInjectionContainer()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n            var mockDependencyResolver = new Mock<IDependencyResolver>();\n            config.DependencyResolver = mockDependencyResolver.Object;\n\n            // Act\n            defaultServices.GetService(typeof(IActionValueBinder));\n            defaultServices.GetService(typeof(IActionValueBinder));\n\n            // Assert\n            mockDependencyResolver.Verify(dr => dr.GetService(typeof(IActionValueBinder)), Times.Once());\n        }\n\n        // GetServicesTests\n\n        [Fact]\n        public void GetServices_GuardClauses()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(() => defaultServices.GetServices(serviceType: null), \"serviceType\");\n            Assert.ThrowsArgument(\n                () => defaultServices.GetServices(typeof(object)),\n                \"serviceType\",\n                \"The service type Object is not supported.\");\n        }\n\n        [Fact]\n        public void GetServices_ReturnsEmptyEnumerationWhenServiceListEmpty()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n            defaultServices.Clear(typeof(IFilterProvider));\n\n            // Act\n            IEnumerable<object> services = defaultServices.GetServices(typeof(IFilterProvider));\n\n            // Assert\n            Assert.Empty(services);\n        }\n\n        [Fact]\n        public void GetServices_PrependsServiceInDependencyInjectionContainer()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n            IEnumerable<object> servicesBefore = defaultServices.GetServices(typeof(IFilterProvider));\n            var filterProvider = new Mock<IFilterProvider>().Object;\n            var mockDependencyResolver = new Mock<IDependencyResolver>();\n            mockDependencyResolver.Setup(dr => dr.GetServices(typeof(IFilterProvider))).Returns(new[] { filterProvider });\n            config.DependencyResolver = mockDependencyResolver.Object;\n\n            // Act\n            IEnumerable<object> servicesAfter = defaultServices.GetServices(typeof(IFilterProvider));\n\n            // Assert\n            Assert.Equal(new[] { filterProvider }.Concat(servicesBefore), servicesAfter);\n        }\n\n        [Fact]\n        public void GetServices_CachesResultFromDependencyInjectionContainer()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n            var mockDependencyResolver = new Mock<IDependencyResolver>();\n            config.DependencyResolver = mockDependencyResolver.Object;\n\n            // Act\n            defaultServices.GetServices(typeof(IFilterProvider));\n            defaultServices.GetServices(typeof(IFilterProvider));\n\n            // Assert\n            mockDependencyResolver.Verify(dr => dr.GetServices(typeof(IFilterProvider)), Times.Once());\n        }\n\n        // Insert tests\n\n        [Fact]\n        public void Insert_GuardClauses()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(() => defaultServices.Insert(serviceType: null, index: 0, service: new object()), \"serviceType\");\n            Assert.ThrowsArgumentNull(() => defaultServices.Insert(typeof(object), 0, service: null), \"service\");\n            Assert.ThrowsArgument(\n                () => defaultServices.Insert(typeof(object), 0, new object()),\n                \"serviceType\",\n                \"The service type Object is not supported.\");\n            Assert.ThrowsArgument(\n                () => defaultServices.Insert(typeof(IHttpActionInvoker), 0, new object()),\n                \"service\",\n                \"The type Object must derive from IHttpActionInvoker.\");\n            Assert.ThrowsArgumentOutOfRange(\n                () => defaultServices.Insert(typeof(ValueProviderFactory), -1, new Mock<ValueProviderFactory>().Object),\n                \"index\",\n                \"Index must be within the bounds of the List.\");\n        }\n\n        [Fact]\n        public void Insert_AddsElementAtTheRequestedLocation()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n            var filterProvider1 = new Mock<IFilterProvider>().Object;\n            var filterProvider2 = new Mock<IFilterProvider>().Object;\n            var newFilterProvider = new Mock<IFilterProvider>().Object;\n            defaultServices.ReplaceRange(typeof(IFilterProvider), new[] { filterProvider1, filterProvider2 });\n\n            // Act\n            defaultServices.Insert(typeof(IFilterProvider), 1, newFilterProvider);\n\n            // Assert\n            Assert.Equal(new[] { filterProvider1, newFilterProvider, filterProvider2 }, defaultServices.GetServices(typeof(IFilterProvider)));\n        }\n\n        // InsertRange tests\n\n        [Fact]\n        public void InsertRange_GuardClauses()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(() => defaultServices.InsertRange(serviceType: null, index: 0, services: new[] { new object() }), \"serviceType\");\n            Assert.ThrowsArgumentNull(() => defaultServices.InsertRange(typeof(object), 0, services: null), \"services\");\n            Assert.ThrowsArgument(\n                () => defaultServices.InsertRange(typeof(object), 0, new[] { new object() }),\n                \"serviceType\",\n                \"The service type Object is not supported.\");\n            Assert.ThrowsArgument(\n                () => defaultServices.InsertRange(typeof(IHttpActionInvoker), 0, new[] { new object() }),\n                \"services\",\n                \"The type Object must derive from IHttpActionInvoker.\");\n            Assert.ThrowsArgumentOutOfRange(\n                () => defaultServices.InsertRange(typeof(ValueProviderFactory), -1, new[] { new Mock<ValueProviderFactory>().Object }),\n                \"index\",\n                \"Index was out of range. Must be non-negative and less than the size of the collection.\");\n        }\n\n        [Fact]\n        public void InsertRange_AddsElementAtTheRequestedLocation()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n            var filterProvider1 = new Mock<IFilterProvider>().Object;\n            var filterProvider2 = new Mock<IFilterProvider>().Object;\n            var newFilterProvider1 = new Mock<IFilterProvider>().Object;\n            var newFilterProvider2 = new Mock<IFilterProvider>().Object;\n            defaultServices.ReplaceRange(typeof(IFilterProvider), new[] { filterProvider1, filterProvider2 });\n\n            // Act\n            defaultServices.InsertRange(typeof(IFilterProvider), 1, new[] { newFilterProvider1, newFilterProvider2 });\n\n            // Assert\n            Assert.Equal(new[] { filterProvider1, newFilterProvider1, newFilterProvider2, filterProvider2 }, defaultServices.GetServices(typeof(IFilterProvider)));\n        }\n\n        // Remove tests\n\n        [Fact]\n        public void Remove_GuardClauses()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(() => defaultServices.Remove(serviceType: null, service: new object()), \"serviceType\");\n            Assert.ThrowsArgumentNull(() => defaultServices.Remove(typeof(object), service: null), \"service\");\n            Assert.ThrowsArgument(\n                () => defaultServices.Remove(typeof(object), new object()),\n                \"serviceType\",\n                \"The service type Object is not supported.\");\n        }\n\n        [Fact]\n        public void Remove_ObjectFound()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n            var filterProvider1 = new Mock<IFilterProvider>().Object;\n            var filterProvider2 = new Mock<IFilterProvider>().Object;\n            defaultServices.ReplaceRange(typeof(IFilterProvider), new[] { filterProvider1, filterProvider2 });\n\n            // Act\n            defaultServices.Remove(typeof(IFilterProvider), filterProvider1);\n\n            // Assert\n            Assert.Equal(new[] { filterProvider2 }, defaultServices.GetServices(typeof(IFilterProvider)));\n        }\n\n        [Fact]\n        public void Remove_ObjectNotFound()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n            var filterProvider1 = new Mock<IFilterProvider>().Object;\n            var filterProvider2 = new Mock<IFilterProvider>().Object;\n            var notPresentFilterProvider = new Mock<IFilterProvider>().Object;\n            defaultServices.ReplaceRange(typeof(IFilterProvider), new[] { filterProvider1, filterProvider2 });\n\n            // Act\n            defaultServices.Remove(typeof(IFilterProvider), notPresentFilterProvider);\n\n            // Assert\n            Assert.Equal(new[] { filterProvider1, filterProvider2 }, defaultServices.GetServices(typeof(IFilterProvider)));\n        }\n\n        // RemoveAll tests\n\n        [Fact]\n        public void RemoveAll_GuardClauses()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(() => defaultServices.RemoveAll(serviceType: null, match: _ => true), \"serviceType\");\n            Assert.ThrowsArgumentNull(() => defaultServices.RemoveAll(typeof(object), match: null), \"match\");\n            Assert.ThrowsArgument(\n                () => defaultServices.RemoveAll(typeof(object), _ => true),\n                \"serviceType\",\n                \"The service type Object is not supported.\");\n        }\n\n        [Fact]\n        public void RemoveAll_SuccessfulMatch()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n            var filterProvider1 = new Mock<IFilterProvider>().Object;\n            var filterProvider2 = new Mock<IFilterProvider>().Object;\n            defaultServices.ReplaceRange(typeof(IFilterProvider), new[] { filterProvider1, filterProvider2 });\n\n            // Act\n            defaultServices.RemoveAll(typeof(IFilterProvider), _ => true);\n\n            // Assert\n            Assert.Empty(defaultServices.GetServices(typeof(IFilterProvider)));\n        }\n\n        [Fact]\n        public void RemoveAll_PartialMatch()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n            var filterProvider1 = new Mock<IFilterProvider>().Object;\n            var filterProvider2 = new Mock<IFilterProvider>().Object;\n            defaultServices.ReplaceRange(typeof(IFilterProvider), new[] { filterProvider1, filterProvider2 });\n\n            // Act\n            defaultServices.RemoveAll(typeof(IFilterProvider), obj => obj == filterProvider2);\n\n            // Assert\n            Assert.Equal(new[] { filterProvider1 }, defaultServices.GetServices(typeof(IFilterProvider)));\n        }\n\n        // RemoveAt tests\n\n        [Fact]\n        public void RemoveAt_GuardClauses()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(() => defaultServices.RemoveAt(serviceType: null, index: 0), \"serviceType\");\n            Assert.ThrowsArgument(\n                () => defaultServices.RemoveAt(typeof(object), 0),\n                \"serviceType\",\n                \"The service type Object is not supported.\");\n            Assert.ThrowsArgumentOutOfRange(\n                () => defaultServices.RemoveAt(typeof(IFilterProvider), -1),\n                \"index\",\n                \"Index was out of range. Must be non-negative and less than the size of the collection.\");\n        }\n\n        [Fact]\n        public void RemoteAt_RemovesService()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n            var filterProvider1 = new Mock<IFilterProvider>().Object;\n            var filterProvider2 = new Mock<IFilterProvider>().Object;\n            defaultServices.ReplaceRange(typeof(IFilterProvider), new[] { filterProvider1, filterProvider2 });\n\n            // Act\n            defaultServices.RemoveAt(typeof(IFilterProvider), 1);\n\n            // Assert\n            Assert.Equal(new[] { filterProvider1 }, defaultServices.GetServices(typeof(IFilterProvider)));\n        }\n\n        // Replace tests\n        [Fact]\n        public void Replace_SetsNull()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n\n            defaultServices.Replace(typeof(IActionValueBinder), service: null);\n        }\n\n        [Fact]\n        public void Replace_GuardClauses()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(() => defaultServices.Replace(serviceType: null, service: new object()), \"serviceType\");\n            Assert.ThrowsArgument(\n                () => defaultServices.Replace(typeof(object), new object()),\n                \"serviceType\",\n                \"The service type Object is not supported.\");\n            Assert.ThrowsArgument(\n                () => defaultServices.Replace(typeof(IHttpActionInvoker), new object()),\n                \"service\",\n                \"The type Object must derive from IHttpActionInvoker.\");\n        }\n\n        [Fact]\n        public void Replace_ReplacesAllValuesWithTheGivenService()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n            var filterProvider1 = new Mock<IFilterProvider>().Object;\n            var filterProvider2 = new Mock<IFilterProvider>().Object;\n            var newFilterProvider = new Mock<IFilterProvider>().Object;\n            defaultServices.ReplaceRange(typeof(IFilterProvider), new[] { filterProvider1, filterProvider2 });\n\n            // Act\n            defaultServices.Replace(typeof(IFilterProvider), newFilterProvider);\n\n            // Assert\n            Assert.Equal(new[] { newFilterProvider }, defaultServices.GetServices(typeof(IFilterProvider)));\n        }\n\n        // ReplaceRange tests\n\n        [Fact]\n        public void ReplaceRange_GuardClauses()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(() => defaultServices.ReplaceRange(serviceType: null, services: new[] { new object() }), \"serviceType\");\n            Assert.ThrowsArgumentNull(() => defaultServices.ReplaceRange(typeof(object), services: null), \"services\");\n            Assert.ThrowsArgument(\n                () => defaultServices.ReplaceRange(typeof(object), new[] { new object() }),\n                \"serviceType\",\n                \"The service type Object is not supported.\");\n            Assert.ThrowsArgument(\n                () => defaultServices.ReplaceRange(typeof(ValueProviderFactory), new[] { new object() }),\n                \"services\",\n                \"The type Object must derive from ValueProviderFactory.\");\n        }\n\n        [Fact]\n        public void ReplaceRange_ReplacesAllValuesWithTheGivenServices()\n        {\n            // Arrange\n            var config = new HttpConfiguration();\n            var defaultServices = new DefaultServices(config);\n            var filterProvider1 = new Mock<IFilterProvider>().Object;\n            var filterProvider2 = new Mock<IFilterProvider>().Object;\n\n            // Act\n            defaultServices.ReplaceRange(typeof(IFilterProvider), new[] { filterProvider1, filterProvider2 });\n\n            // Assert\n            Assert.Equal(new[] { filterProvider1, filterProvider2 }, defaultServices.GetServices(typeof(IFilterProvider)));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Services/ServicesExtensionsTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.ExceptionHandling;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Services\n{\n    public class ServicesExtensionsTests\n    {\n        [Fact]\n        public void GetValueProviderFactories_Throws_WhenServicesIsNull()\n        {\n            // Arrange\n            ServicesContainer services = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => ServicesExtensions.GetValueProviderFactories(services), \"services\");\n        }\n\n        [Fact]\n        public void GetExceptionHandler_DelegatesToGetService()\n        {\n            // Arrange\n            IExceptionHandler expectedExceptionHandler = new Mock<IExceptionHandler>(MockBehavior.Strict).Object;\n\n            Mock<ServicesContainer> mock = new Mock<ServicesContainer>(MockBehavior.Strict);\n            mock.Setup(s => s.GetService(typeof(IExceptionHandler))).Returns(expectedExceptionHandler);\n            ServicesContainer services = mock.Object;\n\n            // Act\n            IExceptionHandler exceptionHandler = ServicesExtensions.GetExceptionHandler(services);\n\n            // Assert\n            mock.Verify(s => s.GetService(typeof(IExceptionHandler)), Times.Once());\n            Assert.Same(expectedExceptionHandler, exceptionHandler);\n        }\n\n        [Fact]\n        public void GetExceptionLoggers_DelegatesToGetServices()\n        {\n            // Arrange\n            IExceptionLogger expectedExceptionLogger = new Mock<IExceptionLogger>(MockBehavior.Strict).Object;\n            IEnumerable<IExceptionLogger> expectedExceptionLoggers =\n                new IExceptionLogger[] { expectedExceptionLogger };\n\n            Mock<ServicesContainer> mock = new Mock<ServicesContainer>(MockBehavior.Strict);\n            mock.Setup(s => s.GetServices(typeof(IExceptionLogger))).Returns(expectedExceptionLoggers);\n            ServicesContainer services = mock.Object;\n\n            // Act\n            IEnumerable<IExceptionLogger> exceptionLoggers = ServicesExtensions.GetExceptionLoggers(services);\n\n            // Assert\n            mock.Verify(s => s.GetServices(typeof(IExceptionLogger)), Times.Once());\n            Assert.NotNull(exceptionLoggers);\n            IExceptionLogger exceptionLogger = Assert.Single(exceptionLoggers);\n            Assert.Same(expectedExceptionLogger, exceptionLogger);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/System.Web.Http.Test.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props\" Condition=\"Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" />\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" />\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{7F2C796F-43B2-4F8F-ABFF-A154EC8AAFA1}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>System.Web.Http</RootNamespace>\n    <AssemblyName>System.Web.Http.Test</AssemblyName>\n    <OutputPath>..\\..\\bin\\$(Configuration)\\Test\\</OutputPath>\n    <DefineConstants>$(DefineConstants);ASPNETWEBAPI</DefineConstants>\n    <NuGetPackageImportStamp>\n    </NuGetPackageImportStamp>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Castle.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Castle.Core.5.1.1\\lib\\net462\\Castle.Core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Moq, Version=4.18.0.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Moq.4.18.4\\lib\\net462\\Moq.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Newtonsoft.Json.13.0.1\\lib\\net45\\Newtonsoft.Json.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.ComponentModel.DataAnnotations\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Data.Linq\" />\n    <Reference Include=\"System.Net.Http\" />\n    <Reference Include=\"System.Net.Http.WebRequest\" />\n    <Reference Include=\"System.Runtime.Caching\" />\n    <Reference Include=\"System.Runtime.Serialization\" />\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"System.XML\" />\n    <Reference Include=\"System.Xml.Linq\" />\n    <Reference Include=\"xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.abstractions.2.0.3\\lib\\net35\\xunit.abstractions.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.assert, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.assert.2.4.2\\lib\\netstandard1.1\\xunit.assert.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.core, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.core.2.4.2\\lib\\net452\\xunit.core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.execution.desktop, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.execution.2.4.2\\lib\\net452\\xunit.execution.desktop.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\Common\\CollectionExtensionsTest.cs\">\n      <Link>Common\\CollectionExtensionsTest.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\DictionaryExtensionsTest.cs\">\n      <Link>Common\\DictionaryExtensionsTest.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\ErrorTest.cs\">\n      <Link>Common\\ErrorTest.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\ListWrapperCollectionTests.cs\">\n      <Link>Common\\ListWrapperCollectionTests.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\PrefixContainerTest.cs\">\n      <Link>Common\\PrefixContainerTest.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\RouteFactoryAttributeTests.cs\">\n      <Link>Routing\\RouteFactoryAttributeTests.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\RoutePrecedenceTests.cs\">\n      <Link>Routing\\RoutePrecedenceTests.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\TaskHelpersExtensionsTest.cs\">\n      <Link>Common\\TaskHelpersExtensionsTest.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\TaskHelpersTest.cs\">\n      <Link>Common\\TaskHelpersTest.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\TypeExtensionsTest.cs\">\n      <Link>Common\\TypeExtensionsTest.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\UriQueryUtilityTest.cs\">\n      <Link>Common\\UriQueryUtilityTest.cs</Link>\n    </Compile>\n    <Compile Include=\"AuthorizeAttributeTest.cs\" />\n    <Compile Include=\"Batch\\BatchHttpRequestMessageExtensionsTest.cs\" />\n    <Compile Include=\"Batch\\BatchHttpRequestContextTests.cs\" />\n    <Compile Include=\"Batch\\BatchLearningTests.cs\" />\n    <Compile Include=\"Batch\\HttpBatchHandlerTest.cs\" />\n    <Compile Include=\"Batch\\DefaultHttpBatchHandlerTest.cs\" />\n    <Compile Include=\"Common\\TraceWriterExceptionMapperTest.cs\" />\n    <Compile Include=\"Controllers\\ActionFilterResultTests.cs\" />\n    <Compile Include=\"Controllers\\ApiControllerTestabilityTest.cs\" />\n    <Compile Include=\"Controllers\\Apis\\User.cs\" />\n    <Compile Include=\"Controllers\\Apis\\UsersRpcController.cs\" />\n    <Compile Include=\"Controllers\\AuthorizationFilterResultTests.cs\" />\n    <Compile Include=\"Controllers\\AuthenticationFilterResultTests.cs\" />\n    <Compile Include=\"Controllers\\ExceptionFilterResultTests.cs\" />\n    <Compile Include=\"Controllers\\RequestBackedHttpRequestContextTests.cs\" />\n    <Compile Include=\"Controllers\\FilterGroupingTests.cs\" />\n    <Compile Include=\"Controllers\\HttpParameterBindingTest.cs\" />\n    <Compile Include=\"Controllers\\ParameterBindingExtensionsTest.cs\" />\n    <Compile Include=\"Controllers\\ResponseMessageResultConverterTest.cs\" />\n    <Compile Include=\"Controllers\\ValueResultConverterTest.cs\" />\n    <Compile Include=\"Controllers\\HttpActionDescriptorTest.cs\" />\n    <Compile Include=\"Controllers\\HttpControllerContextTest.cs\" />\n    <Compile Include=\"Controllers\\HttpConfigurationTest.cs\" />\n    <Compile Include=\"Controllers\\VoidResultConverterTest.cs\" />\n    <Compile Include=\"Description\\ApiExplorerTest.cs\" />\n    <Compile Include=\"Description\\ApiParameterDescriptionTest.cs\" />\n    <Compile Include=\"ExceptionHandling\\CompositeExceptionLoggerTests.cs\" />\n    <Compile Include=\"ExceptionHandling\\ExceptionContextCatchBlockTests.cs\" />\n    <Compile Include=\"ExceptionHandling\\ExceptionLoggerExtensionsTests.cs\" />\n    <Compile Include=\"ExceptionHandling\\ExceptionLoggerContextTests.cs\" />\n    <Compile Include=\"ExceptionHandling\\DefaultExceptionHandlerTests.cs\" />\n    <Compile Include=\"ExceptionHandling\\EmptyExceptionHandlerTests.cs\" />\n    <Compile Include=\"ExceptionHandling\\ExceptionCatchBlocksTests.cs\" />\n    <Compile Include=\"ExceptionHandling\\ExceptionContextTests.cs\" />\n    <Compile Include=\"ExceptionHandling\\ExceptionHandlerContextTests.cs\" />\n    <Compile Include=\"ExceptionHandling\\ExceptionHandlerExtensionsTests.cs\" />\n    <Compile Include=\"ExceptionHandling\\ExceptionHandlerTests.cs\" />\n    <Compile Include=\"ExceptionHandling\\ExceptionLoggerTests.cs\" />\n    <Compile Include=\"ExceptionHandling\\ExceptionServicesTests.cs\" />\n    <Compile Include=\"ExceptionHandling\\LastChanceExceptionHandlerTests.cs\" />\n    <Compile Include=\"Filters\\HttpAuthenticationChallengeContextTests.cs\" />\n    <Compile Include=\"Filters\\HttpAuthenticationContextTests.cs\" />\n    <Compile Include=\"Hosting\\HttpMessageHandlerExtensions.cs\" />\n    <Compile Include=\"Hosting\\SuppressHostPrincipalMessageHandlerTest.cs\" />\n    <Compile Include=\"HttpMessageHandlerExtensions.cs\" />\n    <Compile Include=\"HttpRouteCollectionTest.cs\" />\n    <Compile Include=\"ModelBinding\\ModelBindingEndToEndTests.cs\" />\n    <Compile Include=\"ModelBinding\\SharedModels\\PeopleModel.cs\" />\n    <Compile Include=\"ModelBinding\\SharedModels\\User.cs\" />\n    <Compile Include=\"ModelBinding\\SharedModels\\Address.cs\" />\n    <Compile Include=\"ModelBinding\\SharedModels\\StreetAddress.cs\" />\n    <Compile Include=\"ModelBinding\\SharedModels\\Person.cs\" />\n    <Compile Include=\"Resources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>Resources.resx</DependentUpon>\n    </Compile>\n    <Compile Include=\"Results\\BadRequestResultTests.cs\" />\n    <Compile Include=\"Results\\RedirectToRouteResultTests.cs\" />\n    <Compile Include=\"Results\\CreatedAtRouteNegotiatedContentResultTests.cs\" />\n    <Compile Include=\"Results\\BadRequestErrorMessageResultTests.cs\" />\n    <Compile Include=\"Results\\JsonResultTests.cs\" />\n    <Compile Include=\"Results\\ConflictResultTests.cs\" />\n    <Compile Include=\"Results\\UnauthorizedResultTests.cs\" />\n    <Compile Include=\"Results\\ExceptionResultTests.cs\" />\n    <Compile Include=\"Results\\OkResultTests.cs\" />\n    <Compile Include=\"Results\\InternalServerErrorResultTests.cs\" />\n    <Compile Include=\"Results\\NotFoundResultTests.cs\" />\n    <Compile Include=\"Results\\CreatedNegotiatedContentResultTests.cs\" />\n    <Compile Include=\"Results\\OkNegotiatedContentResultTests.cs\" />\n    <Compile Include=\"Results\\InvalidModelStateResultTests.cs\" />\n    <Compile Include=\"Results\\NegotiatedContentResultTests.cs\" />\n    <Compile Include=\"Results\\FormattedContentResultTests.cs\" />\n    <Compile Include=\"Results\\RedirectResultTests.cs\" />\n    <Compile Include=\"Results\\StatusCodeResultTests.cs\" />\n    <Compile Include=\"HttpConfigurationExtensionsTest.cs\" />\n    <Compile Include=\"Dispatcher\\DefaultHttpControllerTypeResolverTest.cs\" />\n    <Compile Include=\"Dispatcher\\DefaultHttpControllerSelectorTest.cs\" />\n    <Compile Include=\"Dispatcher\\DefaultHttpControllerActivatorTest.cs\" />\n    <Compile Include=\"Dispatcher\\HttpControllerDispatcherTest.cs\" />\n    <Compile Include=\"Dispatcher\\HttpErrorTest.cs\" />\n    <Compile Include=\"Dispatcher\\HttpRoutingDispatcherTest.cs\" />\n    <Compile Include=\"Filters\\HttpFilterCollectionTest.cs\" />\n    <Compile Include=\"HttpErrorKeysTest.cs\" />\n    <Compile Include=\"HttpResponseMessageExtensionsTest.cs\" />\n    <Compile Include=\"HttpResponseExceptionTest.cs\" />\n    <Compile Include=\"HttpServerTest.cs\" />\n    <Compile Include=\"HttpRequestMessageExtensionsTest.cs\" />\n    <Compile Include=\"HttpRouteCollectionExtensionsTest.cs\" />\n    <Compile Include=\"Results\\ResponseMessageResultTests.cs\" />\n    <Compile Include=\"Metadata\\Providers\\AssociatedMetadataProviderTest.cs\" />\n    <Compile Include=\"ModelBinding\\FormatterParameterBindingTest.cs\" />\n    <Compile Include=\"ModelBinding\\HttpParameterBindingExtensionsTest.cs\" />\n    <Compile Include=\"ModelBinding\\ParameterBindingProvidersTest.cs\" />\n    <Compile Include=\"Dispatcher\\DefaultAssembliesResolverTest.cs\" />\n    <Compile Include=\"Controllers\\ApiControllerActionInvokerTest.cs\" />\n    <Compile Include=\"Controllers\\ApiControllerActionSelectorTest.cs\" />\n    <Compile Include=\"Controllers\\HttpParameterDescriptorTest.cs\" />\n    <Compile Include=\"Controllers\\ReflectedHttpParameterDescriptorTest.cs\" />\n    <Compile Include=\"Controllers\\HttpControllerDescriptorTest.cs\" />\n    <Compile Include=\"Controllers\\ReflectedHttpActionDescriptorTest.cs\" />\n    <Compile Include=\"Controllers\\HttpActionContextTest.cs\" />\n    <Compile Include=\"Hosting\\HttpRouteTest.cs\" />\n    <Compile Include=\"Internal\\TypeActivatorTest.cs\" />\n    <Compile Include=\"Metadata\\ModelMetadataTest.cs\" />\n    <Compile Include=\"Metadata\\Providers\\DataAnnotationsModelMetadataProviderTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"ModelBinding\\FormDataCollectionExtensionsTest.cs\" />\n    <Compile Include=\"ModelBinding\\ModelBinderAttributeTest.cs\" />\n    <Compile Include=\"Routing\\AttributeRoutingTest.cs\" />\n    <Compile Include=\"..\\Common\\Routing\\RouteConstraintsTests.cs\">\n      <Link>Routing\\RouteConstraintsTests.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\DefaultInlineConstraintResolverTest.cs\">\n      <Link>Routing\\DefaultInlineConstraintResolverTest.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\InlineRouteTemplateParserTests.cs\">\n      <Link>Routing\\InlineRouteTemplateParserTests.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\DirectRouteBuilderTests.cs\">\n      <Link>Routing\\DirectRouteBuilderTests.cs</Link>\n    </Compile>\n    <Compile Include=\"Routing\\DefaultDirectRouteProviderTests.cs\" />\n    <Compile Include=\"Routing\\LinkGenerationRouteTests.cs\" />\n    <Compile Include=\"Routing\\DirectRouteProviderContextTests.cs\" />\n    <Compile Include=\"Routing\\HttpRouteValueDictionaryTest.cs\" />\n    <Compile Include=\"Routing\\HttpRouteTest.cs\" />\n    <Compile Include=\"Routing\\MediaTypeFormatterExtensionsTests.cs\" />\n    <Compile Include=\"Routing\\RouteAttributeTests.cs\" />\n    <Compile Include=\"..\\Common\\Routing\\SubRouteCollectionTest.cs\">\n      <Link>Routing\\SubRouteCollectionTest.cs</Link>\n    </Compile>\n    <Compile Include=\"Routing\\UriPathExtensionMappingTests.cs\" />\n    <Compile Include=\"Routing\\UrlHelperTest.cs\" />\n    <Compile Include=\"Services\\ControllerServicesTests.cs\" />\n    <Compile Include=\"Services\\DecoratorTests.cs\" />\n    <Compile Include=\"Services\\DefaultServicesTests.cs\" />\n    <Compile Include=\"Services\\ServicesExtensionsTests.cs\" />\n    <Compile Include=\"Tracing\\TraceRecordTest.cs\" />\n    <Compile Include=\"Tracing\\TraceLevelHelperTest.cs\" />\n    <Compile Include=\"Tracing\\FormattingUtilitiesTest.cs\" />\n    <Compile Include=\"Tracing\\HttpRequestMessageExtensionsTest.cs\" />\n    <Compile Include=\"Tracing\\ITraceWriterExtensionsTest.cs\" />\n    <Compile Include=\"Tracing\\TestTraceWriter.cs\" />\n    <Compile Include=\"Tracing\\TraceManagerTest.cs\" />\n    <Compile Include=\"Tracing\\TracerCorrectnessTest.cs\" />\n    <Compile Include=\"Tracing\\TraceRecordComparer.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\BufferedMediaTypeFormatterTracerTest.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\DefaultHttpControllerTypeResolverTracerTest.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\OverrideFilterTracerTests.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\AuthenticationFilterTracerTests.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\ReadWriteMediaTypeFormatterTracerTestBase.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\FormUrlEncodedMediaTypeFormatterTracerTest.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\HttpActionBindingTracerTest.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\HttpActionDescriptorTracerTest.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\ActionFilterAttributeTracerTest.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\ActionFilterTracerTest.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\HttpActionInvokerTracerTest.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\HttpActionSelectorTracerTest.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\ActionValueBinderTracerTest.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\HttpControllerDescriptorTracerTest.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\HttpControllerTracerTest.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\AuthorizationFilterAttributeTracerTest.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\AuthorizationFilterTracerTest.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\ContentNegotiatorTracerTest.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\HttpControllerActivatorTracerTest.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\HttpControllerSelectorTracerTest.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\ExceptionFilterAttributeTracerTest.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\ExceptionFilterTracerTest.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\FilterTracerTest.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\FormatterParameterBindingTracerTest.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\HttpParameterBindingTracerTest.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\JsonMediaTypeFormatterTracerTest.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\MediaTypeFormatterTracerTest.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\MediaTypeFormatterTracerTestBase.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\MessageHandlerTracerTest.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\RequestMessageHandlerTracerTest.cs\" />\n    <Compile Include=\"Tracing\\Tracers\\XmlMediaTypeFormatterTracerTest.cs\" />\n    <Compile Include=\"Tracing\\TraceKindHelperTest.cs\" />\n    <Compile Include=\"Util\\ContextUtil.cs\" />\n    <Compile Include=\"Filters\\HttpActionExecutedContextTest.cs\" />\n    <Compile Include=\"Filters\\ActionFilterAttributeTest.cs\" />\n    <Compile Include=\"Filters\\ActionDescriptorFilterProviderTest.cs\" />\n    <Compile Include=\"Filters\\AuthorizationFilterAttributeTest.cs\" />\n    <Compile Include=\"Filters\\ExceptionFilterAttributeTest.cs\" />\n    <Compile Include=\"Filters\\FilterAttributeTest.cs\" />\n    <Compile Include=\"Filters\\FilterInfoComparerTest.cs\" />\n    <Compile Include=\"Filters\\FilterInfoTest.cs\" />\n    <Compile Include=\"Filters\\ConfigurationFilterProviderTest.cs\" />\n    <Compile Include=\"ModelBinding\\CompositeModelBinderTest.cs\" />\n    <Compile Include=\"ModelBinding\\DefaultActionValueBinderTest.cs\" />\n    <Compile Include=\"Controllers\\ApiControllerTest.cs\" />\n    <Compile Include=\"Controllers\\Apis\\UsersController.cs\" />\n    <Compile Include=\"ModelBinding\\HttpBindingBehaviorAttributeTest.cs\" />\n    <Compile Include=\"Internal\\CollectionModelBinderUtilTest.cs\" />\n    <Compile Include=\"ModelBinding\\Binders\\ArrayModelBinderProviderTest.cs\" />\n    <Compile Include=\"ModelBinding\\Binders\\ArrayModelBinderTest.cs\" />\n    <Compile Include=\"ModelBinding\\Binders\\CollectionModelBinderProviderTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"ModelBinding\\Binders\\CollectionModelBinderTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"ModelBinding\\Binders\\ComplexModelDtoModelBinderProviderTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"ModelBinding\\Binders\\ComplexModelDtoModelBinderTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"ModelBinding\\Binders\\ComplexModelDtoResultTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"ModelBinding\\Binders\\ComplexModelDtoTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"ModelBinding\\Binders\\DictionaryModelBinderProviderTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"ModelBinding\\Binders\\DictionaryModelBinderTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"ModelBinding\\Binders\\KeyValuePairModelBinderProviderTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"ModelBinding\\Binders\\KeyValuePairModelBinderTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"ModelBinding\\Binders\\KeyValuePairModelBinderUtilTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"ModelBinding\\Binders\\MutableObjectModelBinderProviderTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"ModelBinding\\Binders\\MutableObjectModelBinderTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"ModelBinding\\Binders\\SimpleModelBinderProviderTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"ModelBinding\\Binders\\TypeConverterModelBinderProviderTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"ModelBinding\\Binders\\TypeConverterModelBinderTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"ModelBinding\\Binders\\TypeMatchModelBinderProviderTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"ModelBinding\\Binders\\TypeMatchModelBinderTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"ModelBinding\\ModelBinderConfigTest.cs\" />\n    <Compile Include=\"ModelBinding\\ModelBindingUtilTest.cs\" />\n    <Compile Include=\"ModelBinding\\ModelBindingContextTest.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"Util\\SimpleHttpValueProvider.cs\" />\n    <Compile Include=\"Validation\\DefaultBodyModelValidatorTest.cs\" />\n    <Compile Include=\"Validation\\ModelStateFormatterLoggerTest.cs\" />\n    <Compile Include=\"Validation\\ModelValidationNodeTest.cs\" />\n    <Compile Include=\"Validation\\ModelValidationRequiredMemberSelectorTest.cs\" />\n    <Compile Include=\"Validation\\ModelValidationResultTest.cs\" />\n    <Compile Include=\"Validation\\ModelValidatorTest.cs\" />\n    <Compile Include=\"Validation\\Providers\\AssociatedValidatorProviderTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"Validation\\Providers\\DataAnnotationsModelValidatorProviderTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"Validation\\Providers\\DataMemberModelValidatorProviderTest.cs\" />\n    <Compile Include=\"Validation\\Providers\\InvalidModelValidatorProviderTest.cs\" />\n    <Compile Include=\"Validation\\ReferenceEqualityComparerTest.cs\" />\n    <Compile Include=\"Validation\\Validators\\DataAnnotationsModelValidatorTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"Validation\\Validators\\ErrorModelValidatorTest.cs\" />\n    <Compile Include=\"ValueProviders\\Providers\\ElementalValueProviderTest.cs\" />\n    <Compile Include=\"ValueProviders\\Providers\\RouteDataValueProviderFactoryTest.cs\" />\n    <Compile Include=\"ValueProviders\\Providers\\NameValuePairsValueProviderTest.cs\" />\n    <Compile Include=\"ValueProviders\\Providers\\QueryStringValueProviderFactoryTest.cs\" />\n    <Compile Include=\"ValueProviders\\Providers\\QueryStringValueProviderTest.cs\" />\n    <Compile Include=\"ValueProviders\\Providers\\RouteDataValueProviderTest.cs\" />\n    <Compile Include=\"ValueProviders\\ValueProviderResultTest.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\..\\src\\System.Net.Http.Formatting\\System.Net.Http.Formatting.csproj\">\n      <Project>{668E9021-CE84-49D9-98FB-DF125A9FCDB0}</Project>\n      <Name>System.Net.Http.Formatting</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Http\\System.Web.Http.csproj\">\n      <Project>{DDC1CE0C-486E-4E35-BB3B-EAB61F8F9440}</Project>\n      <Name>System.Web.Http</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\">\n      <Project>{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}</Project>\n      <Name>Microsoft.TestCommon</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Net.Http.Formatting.Test\\System.Net.Http.Formatting.Test.csproj\">\n      <Project>{7AF77741-9158-4D5F-8782-8F21FADF025F}</Project>\n      <Name>System.Net.Http.Formatting.Test</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"Resources.resx\">\n      <Generator>PublicResXFileCodeGenerator</Generator>\n      <LastGenOutput>Resources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n  </ItemGroup>\n  <ItemGroup>\n    <Service Include=\"{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Analyzer Include=\"..\\..\\packages\\xunit.analyzers.1.1.0\\analyzers\\dotnet\\cs\\xunit.analyzers.dll\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  <Target Name=\"EnsureNuGetPackageBuildImports\" BeforeTargets=\"PrepareForBuild\">\n    <PropertyGroup>\n      <ErrorText>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}.</ErrorText>\n    </PropertyGroup>\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props'))\" />\n  </Target>\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" />\n</Project>"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/FormattingUtilitiesTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Globalization;\nusing System.Linq;\nusing System.Net.Http.Formatting;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.ModelBinding.Binders;\nusing System.Web.Http.Routing;\nusing System.Web.Http.ValueProviders;\nusing System.Web.Http.ValueProviders.Providers;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Tracing\n{\n    public class FormattingUtilitiesTest\n    {\n        [Theory]\n        [TestDataSet(typeof(CommonUnitTestDataSets), \"RefTypeTestDataCollection\")]\n        public void ValueToString_Formats(Type variationType, object testData)\n        {\n            // Arrange\n            GC.KeepAlive(variationType); // Mark parameter as used. See xUnit1026, [Theory] method doesn't use all parameters.\n            string expected = Convert.ToString(testData, CultureInfo.CurrentCulture);\n\n            // Act\n            string actual = FormattingUtilities.ValueToString(testData, CultureInfo.CurrentCulture);\n\n            // Assert\n            Assert.Equal(expected, actual);\n        }\n\n        [Fact]\n        public void ValueToString_Formats_Null_Value()\n        {\n            // Arrange & Act\n            string actual = FormattingUtilities.ValueToString(null, CultureInfo.CurrentCulture);\n\n            // Assert\n            Assert.Equal(\"null\", actual);\n        }\n\n        [Fact]\n        public void ActionArgumentsToString_Formats()\n        {\n            // Arrange\n            Dictionary<string, object> arguments = new Dictionary<string, object>()\n                                                       {\n                                                           {\"p1\", 1},\n                                                           {\"p2\", true}\n                                                       };\n\n            string expected = String.Format(\"p1={0}, p2={1}\",\n                                    FormattingUtilities.ValueToString(arguments[\"p1\"], CultureInfo.CurrentCulture),\n                                    FormattingUtilities.ValueToString(arguments[\"p2\"], CultureInfo.CurrentCulture));\n\n            // Act\n            string actual = FormattingUtilities.ActionArgumentsToString(arguments);\n\n            // Assert\n            Assert.Equal(expected, actual);\n        }\n\n        [Fact]\n        public void ActionDescriptorToString_Formats()\n        {\n            // Arrange\n            Mock<HttpParameterDescriptor> paramDescriptor1 = new Mock<HttpParameterDescriptor>() { CallBase = true };\n            paramDescriptor1.Setup(p => p.ParameterName).Returns(\"p1\");\n            paramDescriptor1.Setup(p => p.ParameterType).Returns(typeof(int));\n            Mock<HttpParameterDescriptor> paramDescriptor2 = new Mock<HttpParameterDescriptor>() { CallBase = true };\n            paramDescriptor2.Setup(p => p.ParameterName).Returns(\"p2\");\n            paramDescriptor2.Setup(p => p.ParameterType).Returns(typeof(bool));\n\n            Collection<HttpParameterDescriptor> parameterCollection = new Collection<HttpParameterDescriptor>(\n                new HttpParameterDescriptor[] { paramDescriptor1.Object, paramDescriptor2.Object });\n            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };\n            mockActionDescriptor.Setup(a => a.GetParameters()).Returns(parameterCollection);\n            mockActionDescriptor.Setup(a => a.ActionName).Returns(\"SampleAction\");\n\n            string expected = String.Format(\"SampleAction({0} p1, {1} p2)\", typeof(int).Name, typeof(bool).Name);\n\n            // Act\n            string actual = FormattingUtilities.ActionDescriptorToString(mockActionDescriptor.Object);\n\n            // Assert\n            Assert.Equal(expected, actual);\n        }\n\n        [Fact]\n        public void ActionInvokeToString_Formats()\n        {\n            // Arrange\n            Dictionary<string, object> arguments = new Dictionary<string, object>()\n                                                       {\n                                                           {\"p1\", 1},\n                                                           {\"p2\", true}\n                                                       };\n\n            string expected = String.Format(\"SampleAction(p1={0}, p2={1})\",\n                                    FormattingUtilities.ValueToString(arguments[\"p1\"], CultureInfo.CurrentCulture),\n                                    FormattingUtilities.ValueToString(arguments[\"p2\"], CultureInfo.CurrentCulture));\n\n            // Act\n            string actual = FormattingUtilities.ActionInvokeToString(\"SampleAction\", arguments);\n\n            // Assert\n            Assert.Equal(expected, actual);\n        }\n\n        [Fact]\n        public void ActionInvokeToString_With_ActionContext_Formats()\n        {\n            // Arrange\n            Mock<HttpParameterDescriptor> paramDescriptor1 = new Mock<HttpParameterDescriptor>() { CallBase = true };\n            paramDescriptor1.Setup(p => p.ParameterName).Returns(\"p1\");\n            paramDescriptor1.Setup(p => p.ParameterType).Returns(typeof(int));\n            Mock<HttpParameterDescriptor> paramDescriptor2 = new Mock<HttpParameterDescriptor>() { CallBase = true };\n            paramDescriptor2.Setup(p => p.ParameterName).Returns(\"p2\");\n            paramDescriptor2.Setup(p => p.ParameterType).Returns(typeof(bool));\n\n            Collection<HttpParameterDescriptor> parameterCollection = new Collection<HttpParameterDescriptor>(\n                new HttpParameterDescriptor[] { paramDescriptor1.Object, paramDescriptor2.Object });\n            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };\n            mockActionDescriptor.Setup(a => a.GetParameters()).Returns(parameterCollection);\n            mockActionDescriptor.Setup(a => a.ActionName).Returns(\"SampleAction\");\n\n            HttpActionContext actionContext =\n                ContextUtil.CreateActionContext(actionDescriptor: mockActionDescriptor.Object);\n            actionContext.ActionArguments[\"p1\"] = 1;\n            actionContext.ActionArguments[\"p2\"] = true;\n\n            string expected = String.Format(\"SampleAction(p1={0}, p2={1})\",\n                                    FormattingUtilities.ValueToString(actionContext.ActionArguments[\"p1\"], CultureInfo.CurrentCulture),\n                                    FormattingUtilities.ValueToString(actionContext.ActionArguments[\"p2\"], CultureInfo.CurrentCulture));\n\n            // Act\n            string actual = FormattingUtilities.ActionInvokeToString(actionContext);\n\n            // Assert\n            Assert.Equal(expected, actual);\n        }\n\n        [Fact]\n        public void FormattersToString_Formats()\n        {\n            // Arrange\n            MediaTypeFormatterCollection formatters = new MediaTypeFormatterCollection();\n            string expected = String.Join(\", \", formatters.Select<MediaTypeFormatter, string>((f) => f.GetType().Name));\n\n            // Act\n            string actual = FormattingUtilities.FormattersToString(formatters);\n\n            // Assert\n            Assert.Equal(expected, actual);\n        }\n\n        [Fact]\n        public void ModelBinderToString_Formats()\n        {\n            // Arrange\n            ModelBinderProvider provider = new SimpleModelBinderProvider(typeof(int), () => null);\n            string expected = typeof(SimpleModelBinderProvider).Name;\n\n            // Act\n            string actual = FormattingUtilities.ModelBinderToString(provider);\n\n            // Assert\n            Assert.Equal(expected, actual);\n        }\n\n        [Fact]\n        public void ModelBinderToString_With_CompositeModelBinder_Formats()\n        {\n            // Arrange\n            ModelBinderProvider innerProvider1 = new SimpleModelBinderProvider(typeof(int), () => null);\n            ModelBinderProvider innerProvider2 = new ArrayModelBinderProvider();\n            CompositeModelBinderProvider compositeProvider = new CompositeModelBinderProvider(new ModelBinderProvider[] { innerProvider1, innerProvider2 });\n            string expected = String.Format(\n                                \"{0}({1}, {2})\",\n                                typeof(CompositeModelBinderProvider).Name,\n                                typeof(SimpleModelBinderProvider).Name,\n                                typeof(ArrayModelBinderProvider).Name);\n\n            // Act\n            string actual = FormattingUtilities.ModelBinderToString(compositeProvider);\n\n            // Assert\n            Assert.Equal(expected, actual);\n        }\n\n        [Fact]\n        public void ValueProviderToString_Formats()\n        {\n            // Arrange\n            IValueProvider provider = new ElementalValueProvider(\"unused\", 1, CultureInfo.CurrentCulture);\n            string expected = typeof(ElementalValueProvider).Name;\n\n            // Act\n            string actual = FormattingUtilities.ValueProviderToString(provider);\n\n            // Assert\n            Assert.Equal(expected, actual);\n        }\n\n        [Fact]\n        public void ValueProviderToString_With_CompositeProvider_Formats()\n        {\n            // Arrange\n            List<IValueProvider> providers = new List<IValueProvider>()\n                                                 {\n                                                    new ElementalValueProvider(\"unused\", 1, CultureInfo.CurrentCulture),\n                                                    new NameValuePairsValueProvider(() => null, CultureInfo.CurrentCulture)\n                                                 };\n\n            CompositeValueProvider compositeProvider = new CompositeValueProvider(providers);\n            string expected = String.Format(\n                                \"{0}({1}, {2})\",\n                                typeof(CompositeValueProvider).Name,\n                                typeof(ElementalValueProvider).Name,\n                                typeof(NameValuePairsValueProvider).Name);\n\n            // Act\n            string actual = FormattingUtilities.ValueProviderToString(compositeProvider);\n\n            // Assert\n            Assert.Equal(expected, actual);\n        }\n\n        [Fact]\n        public void RouteToString_Formats()\n        {\n            // Arrange\n            Dictionary<string, object> routeDictionary = new Dictionary<string, object>()\n                                                             {\n                                                                 {\"r1\", \"c1\"},\n                                                                 {\"r2\", \"c2\"}\n                                                             };\n            Mock<IHttpRouteData> mockRouteData = new Mock<IHttpRouteData>() { CallBase = true };\n            mockRouteData.Setup(r => r.Values).Returns(routeDictionary);\n            string expected = \"r1:c1,r2:c2\";\n\n            // Act\n            string actual = FormattingUtilities.RouteToString(mockRouteData.Object);\n\n            // Assert\n            Assert.Equal(expected, actual);\n        }\n\n        [Fact]\n        public void ModelStateToString_Formats_With_Valid_ModelState()\n        {\n            // Arrange\n            ModelStateDictionary modelState = new ModelStateDictionary();\n            string expected = String.Empty;\n\n            // Act\n            string actual = FormattingUtilities.ModelStateToString(modelState);\n\n            // Assert\n            Assert.Equal(expected, actual);\n        }\n\n        [Fact]\n        public void ModelStateToString_Formats_With_InValid_ModelState()\n        {\n            // Arrange\n            ModelStateDictionary modelState = new ModelStateDictionary();\n            modelState.AddModelError(\"p1\", \"is bad\");\n\n            string expected = \"p1: is bad\";\n\n            // Act\n            string actual = FormattingUtilities.ModelStateToString(modelState);\n\n            // Assert\n            Assert.Equal(expected, actual);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/HttpRequestMessageExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Tracing\n{\n    public class HttpRequestMessageExtensionsTest\n    {\n        [Fact]\n        public void GetCorrelationId_Returns_Valid_Guid()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n\n            // Act\n            Guid guid1 = request.GetCorrelationId();\n            Guid guid2 = request.GetCorrelationId();\n\n            // Assert\n            Assert.Equal(guid1, guid2);\n            Assert.NotEqual(guid1, Guid.Empty);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/ITraceWriterExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Threading.Tasks;\nusing System.Web.Http.ModelBinding;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Tracing\n{\n    public class ITraceWriterExtensionsTest\n    {\n        [Fact]\n        public void Debug_With_Message_Traces()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Debug) { Kind = TraceKind.Trace, Message = \"The formatted message\" },\n            };\n\n            // Act\n            traceWriter.Debug(request, \"testCategory\", \"The {0} message\", \"formatted\");\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void Debug_With_Exception_Traces()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            InvalidOperationException exception = new InvalidOperationException();\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Debug) { Kind = TraceKind.Trace, Exception = exception },\n            };\n\n            // Act\n            traceWriter.Debug(request, \"testCategory\", exception);\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void Debug_With_Message_And_Exception_Traces()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            InvalidOperationException exception = new InvalidOperationException();\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Debug) { Kind = TraceKind.Trace, Message = \"The formatted message\", Exception = exception },\n            };\n\n            // Act\n            traceWriter.Debug(request, \"testCategory\", exception, \"The {0} message\", \"formatted\");\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void Info_With_Message_Traces()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Info) { Kind = TraceKind.Trace, Message = \"The formatted message\" },\n            };\n\n            // Act\n            traceWriter.Info(request, \"testCategory\", \"The {0} message\", \"formatted\");\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void Info_With_Exception_Traces()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            InvalidOperationException exception = new InvalidOperationException();\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Info) { Kind = TraceKind.Trace, Exception = exception },\n            };\n\n            // Act\n            traceWriter.Info(request, \"testCategory\", exception);\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void Info_With_Message_And_Exception_Traces()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            InvalidOperationException exception = new InvalidOperationException();\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Info) { Kind = TraceKind.Trace, Message = \"The formatted message\", Exception = exception },\n            };\n\n            // Act\n            traceWriter.Info(request, \"testCategory\", exception, \"The {0} message\", \"formatted\");\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void Warn_With_Message_Traces()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Warn) { Kind = TraceKind.Trace, Message = \"The formatted message\" },\n            };\n\n            // Act\n            traceWriter.Warn(request, \"testCategory\", \"The {0} message\", \"formatted\");\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void Warn_With_Exception_Traces()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            InvalidOperationException exception = new InvalidOperationException();\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Warn) { Kind = TraceKind.Trace, Exception = exception },\n            };\n\n            // Act\n            traceWriter.Warn(request, \"testCategory\", exception);\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void Warn_With_Message_And_Exception_Traces()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            InvalidOperationException exception = new InvalidOperationException();\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Warn) { Kind = TraceKind.Trace, Message = \"The formatted message\", Exception = exception },\n            };\n\n            // Act\n            traceWriter.Warn(request, \"testCategory\", exception, \"The {0} message\", \"formatted\");\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void Error_With_Message_Traces()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Error) { Kind = TraceKind.Trace, Message = \"The formatted message\" },\n            };\n\n            // Act\n            traceWriter.Error(request, \"testCategory\", \"The {0} message\", \"formatted\");\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void Error_With_Exception_Traces()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            InvalidOperationException exception = new InvalidOperationException();\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Error) { Kind = TraceKind.Trace, Exception = exception },\n            };\n\n            // Act\n            traceWriter.Error(request, \"testCategory\", exception);\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void Error_With_Message_And_Exception_Traces()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            InvalidOperationException exception = new InvalidOperationException();\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Error) { Kind = TraceKind.Trace, Message = \"The formatted message\", Exception = exception },\n            };\n\n            // Act\n            traceWriter.Error(request, \"testCategory\", exception, \"The {0} message\", \"formatted\");\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void Fatal_With_Message_Traces()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Fatal) { Kind = TraceKind.Trace, Message = \"The formatted message\" },\n            };\n\n            // Act\n            traceWriter.Fatal(request, \"testCategory\", \"The {0} message\", \"formatted\");\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void Fatal_With_Exception_Traces()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            InvalidOperationException exception = new InvalidOperationException();\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Fatal) { Kind = TraceKind.Trace, Exception = exception },\n            };\n\n            // Act\n            traceWriter.Fatal(request, \"testCategory\", exception);\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void Fatal_With_Message_And_Exception_Traces()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            InvalidOperationException exception = new InvalidOperationException();\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Fatal) { Kind = TraceKind.Trace, Message = \"The formatted message\", Exception = exception },\n            };\n\n            // Act\n            traceWriter.Fatal(request, \"testCategory\", exception, \"The {0} message\", \"formatted\");\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void TraceBeginEnd_Throws_With_Null_This()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = null;\n            HttpRequestMessage request = new HttpRequestMessage();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => traceWriter.TraceBeginEnd(request,\n                                             \"\",\n                                             TraceLevel.Off,\n                                             \"\",\n                                             \"\",\n                                             beginTrace: null,\n                                             execute: () => { },\n                                             endTrace: null,\n                                             errorTrace: null),\n                                       \"traceWriter\");\n        }\n\n        [Fact]\n        public void TraceBeginEnd_Throws_With_Null_Execute_Action()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => traceWriter.TraceBeginEnd(request,\n                                             \"\",\n                                             TraceLevel.Off,\n                                             \"\",\n                                             \"\",\n                                             beginTrace: null,\n                                             execute: null,\n                                             endTrace: null,\n                                             errorTrace: null),\n                                       \"execute\");\n        }\n\n        [Fact]\n        public void TraceBeginEnd_Accepts_Null_Trace_Actions()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n\n            // Act & Assert\n            traceWriter.TraceBeginEnd(request,\n                     \"\",\n                     TraceLevel.Off,\n                     \"\",\n                     \"\",\n                     beginTrace: null,\n                     execute: () => { },\n                     endTrace: null,\n                     errorTrace: null);\n        }\n\n        [Fact]\n        public void TraceBeginEnd_Invokes_BeginTrace()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n\n            // Act\n            traceWriter.TraceBeginEnd(request,\n                                 \"\",\n                                 TraceLevel.Fatal,\n                                 \"\",\n                                 \"\",\n                                 beginTrace: (tr) => { invoked = true; },\n                                 execute: () => { },\n                                 endTrace: (tr) => { },\n                                 errorTrace: (tr) => { });\n\n            // Assert\n            Assert.True(invoked);\n        }\n\n        [Fact]\n        public void TraceBeginEnd_Does_Not_Invoke_BeginTrace_When_Tracing_Only_Higher_Level()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            traceWriter.TraceSelector = (rqst, category, level) => level >= TraceLevel.Error;\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n\n            // Act\n            traceWriter.TraceBeginEnd(request,\n                                 \"\",\n                                 TraceLevel.Info,\n                                 \"\",\n                                 \"\",\n                                 beginTrace: (tr) => { invoked = true; },\n                                 execute: () => { },\n                                 endTrace: (tr) => { },\n                                 errorTrace: (tr) => { });\n\n            // Assert\n            Assert.False(invoked);\n        }\n\n        [Fact]\n        public void TraceBeginEnd_Invokes_Execute()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n\n            // Act\n            traceWriter.TraceBeginEnd(request,\n                                 \"\",\n                                 TraceLevel.Fatal,\n                                 \"\",\n                                 \"\",\n                                 beginTrace: (tr) => { },\n                                 execute: () => { invoked = true; },\n                                 endTrace: (tr) => { },\n                                 errorTrace: (tr) => { });\n\n            // Assert\n            Assert.True(invoked);\n        }\n\n        [Fact]\n        public void TraceBeginEnd_Invokes_EndTrace()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n\n            // Act\n            traceWriter.TraceBeginEnd(request,\n                                 \"\",\n                                 TraceLevel.Off,\n                                 \"\",\n                                 \"\",\n                                 beginTrace: (tr) => { },\n                                 execute: () => { },\n                                 endTrace: (tr) => { invoked = true; },\n                                 errorTrace: (tr) => { });\n\n            // Assert\n            Assert.True(invoked);\n        }\n\n        [Fact]\n        public void TraceBeginEnd_Does_Not_Invoke_EndTrace_When_Error_Occurs()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            Exception exception = new InvalidOperationException();\n            bool invoked = false;\n\n            // Act & Assert\n            Exception thrown = Assert.Throws<InvalidOperationException>(\n                    () => traceWriter.TraceBeginEnd(request,\n                                 \"\",\n                                 TraceLevel.Off,\n                                 \"\",\n                                 \"\",\n                                 beginTrace: (tr) => { },\n                                 execute: () => { throw exception; },\n                                 endTrace: (tr) => { invoked = true; },\n                                 errorTrace: (tr) => { }));\n            Assert.False(invoked);\n            Assert.Same(exception, thrown);\n        }\n\n        [Fact]\n        public void TraceBeginEnd_Does_Not_Invoke_EndTrace_When_Tracing_Only_High_Level()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            traceWriter.TraceSelector = (rqst, category, level) => level >= TraceLevel.Error;\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n\n            // Act\n            traceWriter.TraceBeginEnd(request,\n                                 \"\",\n                                 TraceLevel.Info,\n                                 \"\",\n                                 \"\",\n                                 beginTrace: (tr) => { },\n                                 execute: () => { },\n                                 endTrace: (tr) => { invoked = true; },\n                                 errorTrace: (tr) => { });\n\n            // Assert\n            Assert.False(invoked);\n        }\n\n        [Fact]\n        public void TraceBeginEnd_Invokes_ErrorTrace()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            Exception exception = new InvalidOperationException();\n            bool invoked = false;\n\n            // Act & Assert\n            Exception thrown = Assert.Throws<InvalidOperationException>(\n                    () => traceWriter.TraceBeginEnd(request,\n                                 \"\",\n                                 TraceLevel.Off,\n                                 \"\",\n                                 \"\",\n                                 beginTrace: (tr) => { },\n                                 execute: () => { throw exception; },\n                                 endTrace: (tr) => { },\n                                 errorTrace: (tr) => { invoked = true; }));\n            Assert.True(invoked);\n            Assert.Same(exception, thrown);\n        }\n\n        [Fact]\n        public void TraceBeginEnd_Does_Not_Invoke_ErrorTrace_When_Tracing_Only_Higher_Level()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            traceWriter.TraceSelector = (rqst, category, level) => level >= TraceLevel.Fatal;\n            HttpRequestMessage request = new HttpRequestMessage();\n            Exception exception = new InvalidOperationException();\n            bool invoked = false;\n\n            // Act & Assert\n            Exception thrown = Assert.Throws<InvalidOperationException>(\n                    () => traceWriter.TraceBeginEnd(request,\n                                 \"\",\n                                 TraceLevel.Info,\n                                 \"\",\n                                 \"\",\n                                 beginTrace: (tr) => { },\n                                 execute: () => { throw exception; },\n                                 endTrace: (tr) => { },\n                                 errorTrace: (tr) => { invoked = true; }));\n            Assert.False(invoked);\n            Assert.Same(exception, thrown);\n        }\n\n        [Fact]\n        public void TraceBeginEnd_Invokes_ErrorTrace_When_Tracing_Only_Errors()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            traceWriter.TraceSelector = (rqst, category, level) => level >= TraceLevel.Error;\n            HttpRequestMessage request = new HttpRequestMessage();\n            Exception exception = new InvalidOperationException();\n            bool invoked = false;\n\n            // Act & Assert\n            Exception thrown = Assert.Throws<InvalidOperationException>(\n                    () => traceWriter.TraceBeginEnd(request,\n                                 \"\",\n                                 TraceLevel.Off,\n                                 \"\",\n                                 \"\",\n                                 beginTrace: (tr) => { },\n                                 execute: () => { throw exception; },\n                                 endTrace: (tr) => { },\n                                 errorTrace: (tr) => { invoked = true; }));\n            Assert.True(invoked);\n            Assert.Same(exception, thrown);\n        }\n\n        [Fact]\n        public void TraceBeginEnd_Does_Not_Invoke_ErrorTrace_Unless_Error_Occurs()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n\n            // Act\n            traceWriter.TraceBeginEnd(request,\n                                 \"\",\n                                 TraceLevel.Info,\n                                 \"\",\n                                 \"\",\n                                 beginTrace: (tr) => { },\n                                 execute: () => { },\n                                 endTrace: (tr) => { },\n                                 errorTrace: (tr) => { invoked = true; });\n\n            // Assert\n            Assert.False(invoked);\n        }\n\n        [Fact]\n        public void TraceBeginEnd_Traces()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Info) { Kind = TraceKind.Begin, Operator = \"tester\", Operation = \"testOp\", Message = \"beginMessage\" },\n                new TraceRecord(request, \"testCategory\", TraceLevel.Info) { Kind = TraceKind.End, Operator = \"tester\", Operation = \"testOp\", Message = \"endMessage\" },\n            };\n\n            // Act\n            traceWriter.TraceBeginEnd(request,\n                                 \"testCategory\",\n                                 TraceLevel.Info,\n                                 \"tester\",\n                                 \"testOp\",\n                                 beginTrace: (tr) => { tr.Message = \"beginMessage\"; },\n                                 execute: () => { },\n                                 endTrace: (tr) => { tr.Message = \"endMessage\"; },\n                                 errorTrace: (tr) => { tr.Message = \"won't happen\"; });\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void TraceBeginEnd_Traces_And_Throws_When_Execute_Throws()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            InvalidOperationException exception = new InvalidOperationException(\"test exception\");\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Info) { Kind = TraceKind.Begin, Operator = \"tester\", Operation = \"testOp\", Message = \"beginMessage\" },\n                new TraceRecord(request, \"testCategory\", TraceLevel.Error) { Kind = TraceKind.End, Operator = \"tester\", Operation = \"testOp\", Exception = exception, Message = \"errorMessage\" },\n            };\n\n            // Act & Assert\n            Exception thrown = Assert.Throws<InvalidOperationException>(\n                                () => traceWriter.TraceBeginEnd(request,\n                                    \"testCategory\",\n                                    TraceLevel.Info,\n                                    \"tester\",\n                                    \"testOp\",\n                                    beginTrace: (tr) => { tr.Message = \"beginMessage\"; },\n                                    execute: () => { throw exception; },\n                                    endTrace: (tr) => { tr.Message = \"won't happen\"; },\n                                    errorTrace: (tr) => { tr.Message = \"errorMessage\"; }));\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(exception, thrown);\n        }\n\n        [Fact]\n        public void TraceBeginEnd_Traces_And_Throws_HttpResponseException()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            HttpResponseException exception = new HttpResponseException(Net.HttpStatusCode.NotFound);\n            List<TraceRecord> expectedTraces = new List<TraceRecord>\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Error)\n                {\n                    Kind = TraceKind.Begin, Operator = \"tester\", Operation = \"testOp\", Message = \"beginMessage\"\n                },\n                new TraceRecord(request, \"testCategory\", TraceLevel.Warn)\n                {\n                    Kind = TraceKind.End, Operator = \"tester\", Operation = \"testOp\", Exception = exception,\n                    Message = \"errorMessage\", Status = Net.HttpStatusCode.NotFound\n                },\n            };\n\n            // Act & Assert\n            Exception thrown = Assert.Throws<HttpResponseException>(\n                                () => traceWriter.TraceBeginEnd(request,\n                                    \"testCategory\",\n                                    TraceLevel.Error,\n                                    \"tester\",\n                                    \"testOp\",\n                                    beginTrace: (tr) => { tr.Message = \"beginMessage\"; },\n                                    execute: () => { throw exception; },\n                                    endTrace: (tr) => { tr.Message = \"won't Happen\"; },\n                                    errorTrace: (tr) => { tr.Message = \"errorMessage\"; }));\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(thrown, exception);\n        }\n\n        [Fact]\n        public void TraceBeginEnd_Traces_And_Throws_AggregateException()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            AggregateException aggregateException = CreateAggregateException(request);\n            List<TraceRecord> expectedTraces = new List<TraceRecord>\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Error)\n                {\n                    Kind = TraceKind.Begin, Operator = \"tester\", Operation = \"testOp\", Message = \"beginMessage\"\n                },\n                new TraceRecord(request, \"testCategory\", TraceLevel.Warn)\n                {\n                    Kind = TraceKind.End, Operator = \"tester\", Operation = \"testOp\", Exception = aggregateException,\n                    // In the aggregateException, only the httpResponseException with the highest status code\n                    // will be reflected in the trace record's message. In this test case, it should be NotFound.\n                    Message = \"UserMessage='The request is invalid.', ModelStateError=[key=[error], username=[invalid]]\",\n                    Status = Net.HttpStatusCode.NotFound\n                },\n            };\n\n            // Act & Assert\n            Exception thrown = Assert.Throws<AggregateException>(\n                                () => traceWriter.TraceBeginEnd(request,\n                                    \"testCategory\",\n                                    TraceLevel.Error,\n                                    \"tester\",\n                                    \"testOp\",\n                                    beginTrace: (tr) => { tr.Message = \"beginMessage\"; },\n                                    execute: () => { throw aggregateException; },\n                                    endTrace: (tr) => { tr.Message = \"won't Happen\"; },\n                                    errorTrace: null));\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(thrown, expectedTraces[1].Exception);\n        }\n\n        [Fact]\n        public void TraceBeginEnd_Does_Not_Trace_HttpResponseException_When_Tracing_Only_Higher_Level()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            traceWriter.TraceSelector = (rqst, category, level) => level >= TraceLevel.Error;\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n            Exception exception = new HttpResponseException(Net.HttpStatusCode.NotFound);\n\n            // Act & Assert\n            Exception thrown = Assert.Throws<HttpResponseException>(\n                                () => traceWriter.TraceBeginEnd(request,\n                                \"\",\n                                TraceLevel.Info,\n                                \"\",\n                                \"\",\n                                beginTrace: (tr) => { invoked = true; },\n                                execute: () => { throw exception; },\n                                endTrace: (tr) => { },\n                                errorTrace: (tr) => { }));\n            Assert.False(invoked);\n            Assert.Empty(traceWriter.Traces);\n            Assert.Same(thrown, exception);\n        }\n\n        [Fact]\n        public void TraceBeginEndAsync_Throws_With_Null_This()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = null;\n            HttpRequestMessage request = new HttpRequestMessage();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => traceWriter.TraceBeginEndAsync(request,\n                                             \"\",\n                                             TraceLevel.Off,\n                                             \"\",\n                                             \"\",\n                                             beginTrace: null,\n                                             execute: () => TaskHelpers.Completed(),\n                                             endTrace: null,\n                                             errorTrace: null),\n                                       \"traceWriter\");\n        }\n\n        [Fact]\n        public void TraceBeginEndAsync_Throws_With_Null_Execute_Action()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => traceWriter.TraceBeginEndAsync(request,\n                                             \"\",\n                                             TraceLevel.Off,\n                                             \"\",\n                                             \"\",\n                                             beginTrace: null,\n                                             execute: null,\n                                             endTrace: null,\n                                             errorTrace: null),\n                                       \"execute\");\n        }\n\n        [Fact]\n        public Task TraceBeginEndAsync_Accepts_Null_Trace_Actions()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n\n            // Act & Assert\n            return traceWriter.TraceBeginEndAsync(request,\n                     \"\",\n                     TraceLevel.Off,\n                     \"\",\n                     \"\",\n                     beginTrace: null,\n                     execute: () => TaskHelpers.Completed(),\n                     endTrace: null,\n                     errorTrace: null);\n        }\n\n        [Fact]\n        public async Task TraceBeginEndAsync_Invokes_BeginTrace()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n\n            // Act\n            await traceWriter.TraceBeginEndAsync(request,\n                                 \"\",\n                                 TraceLevel.Fatal,\n                                 \"\",\n                                 \"\",\n                                 beginTrace: (tr) => { invoked = true; },\n                                 execute: () => TaskHelpers.Completed(),\n                                 endTrace: (tr) => { },\n                                 errorTrace: (tr) => { });\n\n            // Assert\n            Assert.True(invoked);\n        }\n\n        [Fact]\n        public async Task TraceBeginEndAsync_Does_Not_Invoke_BeginTrace_When_Tracing_Only_Higher_Level()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            traceWriter.TraceSelector = (rqst, category, level) => level >= TraceLevel.Error;\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n\n            // Act\n            await traceWriter.TraceBeginEndAsync(request,\n                                 \"\",\n                                 TraceLevel.Info,\n                                 \"\",\n                                 \"\",\n                                 beginTrace: (tr) => { invoked = true; },\n                                 execute: () => TaskHelpers.Completed(),\n                                 endTrace: (tr) => { },\n                                 errorTrace: (tr) => { });\n\n            // Assert\n            Assert.False(invoked);\n        }\n\n        [Fact]\n        public async Task TraceBeginEndAsync_Traces_And_Throws_HttpResponseException()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            HttpResponseException exception = new HttpResponseException(Net.HttpStatusCode.InternalServerError);\n            List<TraceRecord> expectedTraces = new List<TraceRecord>\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Info)\n                {\n                    Kind = TraceKind.Begin, Operator = \"tester\", Operation = \"testOp\", Message = \"beginMessage\"\n                },\n                new TraceRecord(request, \"testCategory\", TraceLevel.Error)\n                {\n                    Kind = TraceKind.End, Operator = \"tester\", Operation = \"testOp\", Exception = exception,\n                    Message = \"errorMessage\", Status = Net.HttpStatusCode.InternalServerError\n                },\n            };\n\n            // Act & Assert\n            Exception thrown = await Assert.ThrowsAsync<HttpResponseException>(\n                                () => traceWriter.TraceBeginEndAsync(request,\n                                    \"testCategory\",\n                                    TraceLevel.Info,\n                                    \"tester\",\n                                    \"testOp\",\n                                    beginTrace: (tr) => { tr.Message = \"beginMessage\"; },\n                                    execute: () => { throw exception; },\n                                    endTrace: (tr) => { tr.Message = \"won't Happen\"; },\n                                    errorTrace: (tr) => { tr.Message = \"errorMessage\"; }));\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(thrown, exception);\n        }\n\n        [Fact]\n        public async Task TraceBeginEndAsync_Does_Not_Trace_HttpResponseException_When_Tracing_Only_Higher_Level()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            traceWriter.TraceSelector = (rqst, category, level) => level >= TraceLevel.Error;\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n            Exception exception = new HttpResponseException(Net.HttpStatusCode.NotFound);\n\n            // Act & Assert\n            Exception thrown = await Assert.ThrowsAsync<HttpResponseException>(\n                                () => traceWriter.TraceBeginEndAsync(request,\n                                \"\",\n                                TraceLevel.Info,\n                                \"\",\n                                \"\",\n                                beginTrace: (tr) => { invoked = true; },\n                                execute: () => TaskHelpers.FromError(exception),\n                                endTrace: (tr) => { },\n                                errorTrace: (tr) => { }));\n            Assert.False(invoked);\n            Assert.Empty(traceWriter.Traces);\n            Assert.Same(thrown, exception);\n        }\n\n        [Fact]\n        public async Task TraceBeginEndAsync_Invokes_Execute()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n\n            // Act\n            await traceWriter.TraceBeginEndAsync(request,\n                                 \"\",\n                                 TraceLevel.Fatal,\n                                 \"\",\n                                 \"\",\n                                 beginTrace: (tr) => { },\n                                 execute: () =>\n                                 {\n                                     invoked = true;\n                                     return TaskHelpers.Completed();\n                                 },\n                                 endTrace: (tr) => { },\n                                 errorTrace: (tr) => { });\n\n            // Assert\n            Assert.True(invoked);\n        }\n\n        [Fact]\n        public async Task TraceBeginEndAsync_Invokes_EndTrace()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n\n            // Act\n            await traceWriter.TraceBeginEndAsync(request,\n                                 \"\",\n                                 TraceLevel.Off,\n                                 \"\",\n                                 \"\",\n                                 beginTrace: (tr) => { },\n                                 execute: () => TaskHelpers.Completed(),\n                                 endTrace: (tr) => { invoked = true; },\n                                 errorTrace: (tr) => { });\n\n            // Assert\n            Assert.True(invoked);\n        }\n\n        [Fact]\n        public async Task TraceBeginEndAsync_Does_Not_Invoke_End_Trace_When_Error_Occurs()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n            Exception exception = new InvalidOperationException();\n            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(null);\n            tcs.TrySetException(exception);\n\n            // Act & Assert\n            Exception thrown = await Assert.ThrowsAsync<InvalidOperationException>(\n                        () => traceWriter.TraceBeginEndAsync(request,\n                                 \"\",\n                                 TraceLevel.Off,\n                                 \"\",\n                                 \"\",\n                                 beginTrace: (tr) => { },\n                                 execute: () => tcs.Task,\n                                 endTrace: (tr) => { invoked = true; },\n                                 errorTrace: (tr) => { }));\n            Assert.False(invoked);\n            Assert.Same(exception, thrown);\n        }\n\n        [Fact]\n        public async Task TraceBeginEndAsync_Does_Not_Invoke_EndTrace_When_Tracing_Only_Higher_Level()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            traceWriter.TraceSelector = (rqst, category, level) => level >= TraceLevel.Error;\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n\n            // Act\n            await traceWriter.TraceBeginEndAsync(request,\n                                 \"\",\n                                 TraceLevel.Info,\n                                 \"\",\n                                 \"\",\n                                 beginTrace: (tr) => { },\n                                 execute: () => TaskHelpers.Completed(),\n                                 endTrace: (tr) => { invoked = true; },\n                                 errorTrace: (tr) => { });\n\n            // Assert\n            Assert.False(invoked);\n        }\n\n        [Fact]\n        public async Task TraceBeginEndAsync_Invokes_ErrorTrace()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n            Exception exception = new InvalidOperationException();\n            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(null);\n            tcs.TrySetException(exception);\n\n            // Act & Assert\n            Exception thrown = await Assert.ThrowsAsync<InvalidOperationException>(\n                        () => traceWriter.TraceBeginEndAsync(request,\n                                 \"\",\n                                 TraceLevel.Off,\n                                 \"\",\n                                 \"\",\n                                 beginTrace: (tr) => { },\n                                 execute: () => tcs.Task,\n                                 endTrace: (tr) => { },\n                                 errorTrace: (tr) => { invoked = true; }));\n            Assert.True(invoked);\n            Assert.Same(exception, thrown);\n        }\n\n        [Fact]\n        public async Task TraceBeginEndAsync_Does_Not_Invoke_ErrorTrace_When_Tracing_Only_Higher_Level()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            traceWriter.TraceSelector = (rqst, category, level) => level >= TraceLevel.Fatal;\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n            Exception exception = new InvalidOperationException();\n            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(null);\n            tcs.TrySetException(exception);\n\n            // Act & Assert\n            Exception thrown = await Assert.ThrowsAsync<InvalidOperationException>(\n                        () => traceWriter.TraceBeginEndAsync(request,\n                                 \"\",\n                                 TraceLevel.Info,\n                                 \"\",\n                                 \"\",\n                                 beginTrace: (tr) => { },\n                                 execute: () => tcs.Task,\n                                 endTrace: (tr) => { },\n                                 errorTrace: (tr) => { invoked = true; }));\n            Assert.False(invoked);\n            Assert.Same(exception, thrown);\n        }\n\n        [Fact]\n        public async Task TraceBeginEndAsync_Invokes_ErrorTrace_When_Tracing_Only_Errors()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            traceWriter.TraceSelector = (rqst, category, level) => level >= TraceLevel.Error;\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n            Exception exception = new InvalidOperationException();\n            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(null);\n            tcs.TrySetException(exception);\n\n            // Act & Assert\n            Exception thrown = await Assert.ThrowsAsync<InvalidOperationException>(\n                        () => traceWriter.TraceBeginEndAsync(request,\n                                 \"\",\n                                 TraceLevel.Info,\n                                 \"\",\n                                 \"\",\n                                 beginTrace: (tr) => { },\n                                 execute: () => tcs.Task,\n                                 endTrace: (tr) => { },\n                                 errorTrace: (tr) => { invoked = true; }));\n            Assert.True(invoked);\n            Assert.Same(exception, thrown);\n        }\n\n        [Fact]\n        public async Task TraceBeginEndAsync_Does_Not_Invoke_ErrorTrace_Unless_Error_Occurs()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(null);\n            tcs.TrySetResult(null);\n\n            // Act\n            await traceWriter.TraceBeginEndAsync(\n                            request,\n                            \"\",\n                            TraceLevel.Off,\n                            \"\",\n                            \"\",\n                            beginTrace: (tr) => { },\n                            execute: () => tcs.Task,\n                            endTrace: (tr) => { },\n                            errorTrace: (tr) => { invoked = true; });\n\n            // Assert\n            Assert.False(invoked);\n        }\n\n        [Fact]\n        public async Task TraceBeginEndAsync_Traces()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Info)\n                {\n                    Kind = TraceKind.Begin, Operator = \"tester\", Operation = \"testOp\", Message = \"beginMessage\"\n                },\n                new TraceRecord(request, \"testCategory\", TraceLevel.Info)\n                {\n                    Kind = TraceKind.End, Operator = \"tester\", Operation = \"testOp\", Message = \"endMessage\"\n                },\n            };\n\n            // Act\n            await traceWriter.TraceBeginEndAsync(request,\n                                 \"testCategory\",\n                                 TraceLevel.Info,\n                                 \"tester\",\n                                 \"testOp\",\n                                 beginTrace: (tr) => { tr.Message = \"beginMessage\"; },\n                                 execute: () => TaskHelpers.Completed(),\n                                 endTrace: (tr) => { tr.Message = \"endMessage\"; },\n                                 errorTrace: (tr) => { tr.Message = \"won't happen\"; });\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public async Task TraceBeginEndAsync_Traces_When_Inner_Cancels()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Info)\n                {\n                    Kind = TraceKind.Begin, Operator = \"tester\", Operation = \"testOp\", Message = \"beginMessage\"\n                },\n                new TraceRecord(request, \"testCategory\", TraceLevel.Warn)\n                {\n                    Kind = TraceKind.End, Operator = \"tester\", Operation = \"testOp\", Message = \"errorMessage\"\n                },\n            };\n\n            // Act & Assert\n            await Assert.ThrowsAsync<TaskCanceledException>(\n                () => traceWriter.TraceBeginEndAsync(request,\n                     \"testCategory\",\n                     TraceLevel.Info,\n                     \"tester\",\n                     \"testOp\",\n                     beginTrace: (tr) => { tr.Message = \"beginMessage\"; },\n                     execute: () => TaskHelpers.Canceled(),\n                     endTrace: (tr) => { tr.Message = \"won't happen\"; },\n                     errorTrace: (tr) => { tr.Message = \"errorMessage\"; }));\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public async Task TraceBeginEndAsync_Traces_And_Throws_AggregateException(bool isExThrownAtExecution)\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            AggregateException aggregateException = CreateAggregateException(request);\n            List<TraceRecord> expectedTraces = new List<TraceRecord>\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Error)\n                {\n                    Kind = TraceKind.Begin, Operator = \"tester\", Operation = \"testOp\", Message = \"beginMessage\"\n                },\n                new TraceRecord(request, \"testCategory\", TraceLevel.Warn)\n                {\n                    Kind = TraceKind.End, Operator = \"tester\", Operation = \"testOp\", Exception = aggregateException,\n                    // In the aggregateException, only the httpResponseException with the highest status code\n                    // will be reflected in the trace record's message. In this test case, it should be NotFound.\n                    Message = \"UserMessage='The request is invalid.', ModelStateError=[key=[error], username=[invalid]]\",\n                    Status = Net.HttpStatusCode.NotFound\n                },\n            };\n\n            // Act & Assert\n            Exception thrown = await Assert.ThrowsAsync<AggregateException>(\n                                () => traceWriter.TraceBeginEndAsync(request,\n                                    \"testCategory\",\n                                    TraceLevel.Error,\n                                    \"tester\",\n                                    \"testOp\",\n                                    beginTrace: (tr) => { tr.Message = \"beginMessage\"; },\n                                    execute: () =>\n                                    {\n                                        if (isExThrownAtExecution)\n                                        {\n                                            throw aggregateException;\n                                        }\n                                        Task task = new Task(() => { throw aggregateException; });\n                                        task.Start();\n                                        return task;\n                                    },\n                                    endTrace: (tr) => { tr.Message = \"won't Happen\"; },\n                                    errorTrace: null));\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(thrown, expectedTraces[1].Exception);\n        }\n\n        [Fact]\n        public async Task TraceBeginAsync_Traces_And_Faults_When_Inner_Faults()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            InvalidOperationException exception = new InvalidOperationException();\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Info)\n                {\n                    Kind = TraceKind.Begin, Operator = \"tester\", Operation = \"testOp\", Message = \"beginMessage\"\n                },\n                new TraceRecord(request, \"testCategory\", TraceLevel.Error)\n                {\n                    Kind = TraceKind.End, Operator = \"tester\", Operation = \"testOp\",\n                    Message = \"errorMessage\", Exception = exception\n                },\n            };\n\n            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(null);\n            tcs.TrySetException(exception);\n\n            // Act & Assert\n            InvalidOperationException thrown = await Assert.ThrowsAsync<InvalidOperationException>(\n                        () => traceWriter.TraceBeginEndAsync(request,\n                                     \"testCategory\",\n                                     TraceLevel.Info,\n                                     \"tester\",\n                                     \"testOp\",\n                                     beginTrace: (tr) => { tr.Message = \"beginMessage\"; },\n                                     execute: () => tcs.Task,\n                                     endTrace: (tr) => { tr.Message = \"won't happen\"; },\n                                     errorTrace: (tr) => { tr.Message = \"errorMessage\"; }));\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(exception, thrown);\n        }\n\n        [Fact]\n        public void TraceBeginEndAsyncGeneric_Throws_With_Null_This()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = null;\n            HttpRequestMessage request = new HttpRequestMessage();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => traceWriter.TraceBeginEndAsync<int>(request,\n                                             \"\",\n                                             TraceLevel.Off,\n                                             \"\",\n                                             \"\",\n                                             beginTrace: null,\n                                             execute: () => Task.FromResult<int>(1),\n                                             endTrace: null,\n                                             errorTrace: null),\n                                       \"traceWriter\");\n        }\n\n        [Fact]\n        public void TraceBeginEndAsyncGeneric_Throws_With_Null_Execute_Action()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => traceWriter.TraceBeginEndAsync<int>(request,\n                                             \"\",\n                                             TraceLevel.Off,\n                                             \"\",\n                                             \"\",\n                                             beginTrace: null,\n                                             execute: null,\n                                             endTrace: null,\n                                             errorTrace: null),\n                                       \"execute\");\n        }\n\n        [Fact]\n        public Task TraceBeginEndAsyncGeneric_Accepts_Null_Trace_Actions()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n\n            // Act & Assert\n            return traceWriter.TraceBeginEndAsync<int>(request,\n                     \"\",\n                     TraceLevel.Off,\n                     \"\",\n                     \"\",\n                     beginTrace: null,\n                     execute: () => Task.FromResult<int>(1),\n                     endTrace: null,\n                     errorTrace: null);\n        }\n\n        [Fact]\n        public async Task TraceBeginEndAsyncGeneric_Invokes_BeginTrace()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n\n            // Act\n            await traceWriter.TraceBeginEndAsync<int>(request,\n                                 \"\",\n                                 TraceLevel.Fatal,\n                                 \"\",\n                                 \"\",\n                                 beginTrace: (tr) => { invoked = true; },\n                                 execute: () => Task.FromResult<int>(1),\n                                 endTrace: (tr, value) => { },\n                                 errorTrace: (tr) => { });\n\n            // Assert\n            Assert.True(invoked);\n        }\n\n        [Fact]\n        public async Task TraceBeginEndAsyncGeneric_Traces_And_Throws_HttpResponseException()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            HttpResponseException exception = new HttpResponseException(Net.HttpStatusCode.NotFound);\n            List<TraceRecord> expectedTraces = new List<TraceRecord>\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Error)\n                {\n                    Kind = TraceKind.Begin, Operator = \"tester\", Operation = \"testOp\", Message = \"beginMessage\"\n                },\n                new TraceRecord(request, \"testCategory\", TraceLevel.Warn)\n                {\n                    Kind = TraceKind.End, Operator = \"tester\", Operation = \"testOp\", Exception = exception,\n                    Message = \"errorMessage\", Status = Net.HttpStatusCode.NotFound\n                },\n            };\n\n            // Act & Assert\n            Exception thrown = await Assert.ThrowsAsync<HttpResponseException>(\n                                () => traceWriter.TraceBeginEndAsync<int>(request,\n                                    \"testCategory\",\n                                    TraceLevel.Error,\n                                    \"tester\",\n                                    \"testOp\",\n                                    beginTrace: (tr) => { tr.Message = \"beginMessage\"; },\n                                    execute: () => { throw exception; },\n                                    endTrace: (tr, result) => { tr.Message = \"won't Happen\"; },\n                                    errorTrace: (tr) => { tr.Message = \"errorMessage\"; }));\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(thrown, exception);\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public async Task TraceBeginEndAsyncGeneric_Traces_And_Throws_AggregateException(bool isExThrownAtExecution)\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            AggregateException aggregateException = CreateAggregateException(request);\n            List<TraceRecord> expectedTraces = new List<TraceRecord>\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Error)\n                {\n                    Kind = TraceKind.Begin, Operator = \"tester\", Operation = \"testOp\", Message = \"beginMessage\"\n                },\n                new TraceRecord(request, \"testCategory\", TraceLevel.Warn)\n                {\n                    Kind = TraceKind.End, Operator = \"tester\", Operation = \"testOp\", Exception = aggregateException,\n                    // In the aggregateException, only the httpResponseException with the highest status code\n                    // will be reflected in the trace record's message. In this test case, it should be NotFound.\n                    Message = \"UserMessage='The request is invalid.', ModelStateError=[key=[error], username=[invalid]]\",\n                    Status = Net.HttpStatusCode.NotFound\n                },\n            };\n\n            // Act & Assert\n            Exception thrown = await Assert.ThrowsAsync<AggregateException>(\n                                () => traceWriter.TraceBeginEndAsync<int>(request,\n                                    \"testCategory\",\n                                    TraceLevel.Error,\n                                    \"tester\",\n                                    \"testOp\",\n                                    beginTrace: (tr) => { tr.Message = \"beginMessage\"; },\n                                    execute: () =>\n                                    {\n                                        if (isExThrownAtExecution)\n                                        {\n                                            throw aggregateException;\n                                        }\n                                        Task<int> task = new Task<int>(() => { throw aggregateException; });\n                                        task.Start();\n                                        return task;\n                                    },\n                                    endTrace: (tr, result) => { tr.Message = \"won't Happen\"; },\n                                    errorTrace: null));\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(thrown, expectedTraces[1].Exception);\n        }\n\n        [Fact]\n        public async Task TraceBeginEndAsyncGeneric_Does_Not_Trace_HttpResponseException_When_Tracing_Only_Higher_Level()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            traceWriter.TraceSelector = (rqst, category, level) => level >= TraceLevel.Error;\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n\n            // Act & Assert\n            await Assert.ThrowsAsync<HttpResponseException>(\n                () => traceWriter.TraceBeginEndAsync(request,\n                \"\",\n                TraceLevel.Info,\n                \"\",\n                \"\",\n                beginTrace: (tr) => { invoked = true; },\n                execute: () => TaskHelpers.FromError(new HttpResponseException(Net.HttpStatusCode.NotFound)),\n                endTrace: (tr) => { },\n                errorTrace: (tr) => { }));\n            Assert.False(invoked);\n            Assert.Empty(traceWriter.Traces);\n        }\n\n        [Fact]\n        public async Task TraceBeginEndAsyncGeneric_Does_Not_Invoke_BeginTrace_When_Tracing_Only_Higher_Level()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            traceWriter.TraceSelector = (rqst, category, level) => level >= TraceLevel.Error;\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n\n            // Act\n            await traceWriter.TraceBeginEndAsync<int>(request,\n                                 \"\",\n                                 TraceLevel.Info,\n                                 \"\",\n                                 \"\",\n                                 beginTrace: (tr) => { invoked = true; },\n                                 execute: () => Task.FromResult<int>(1),\n                                 endTrace: (tr, value) => { },\n                                 errorTrace: (tr) => { });\n\n            // Assert\n            Assert.False(invoked);\n        }\n\n        [Fact]\n        public async Task TraceBeginEndAsyncGeneric_Invokes_Execute()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n\n            // Act\n            int result = await traceWriter.TraceBeginEndAsync<int>(request,\n                                 \"\",\n                                 TraceLevel.Fatal,\n                                 \"\",\n                                 \"\",\n                                 beginTrace: (tr) => { },\n                                 execute: () =>\n                                 {\n                                     invoked = true;\n                                     return Task.FromResult<int>(1);\n                                 },\n                                 endTrace: (tr, value) => { },\n                                 errorTrace: (tr) => { });\n\n            // Assert\n            Assert.True(invoked);\n            Assert.Equal(1, result);\n        }\n\n        [Fact]\n        public async Task TraceBeginEndAsyncGeneric_Invokes_EndTrace()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n            int invokedValue = 0;\n\n            // Act\n            await traceWriter.TraceBeginEndAsync<int>(request,\n                                 \"\",\n                                 TraceLevel.Off,\n                                 \"\",\n                                 \"\",\n                                 beginTrace: (tr) => { },\n                                 execute: () => Task.FromResult<int>(1),\n                                 endTrace: (tr, value) => { invoked = true; invokedValue = value; },\n                                 errorTrace: (tr) => { });\n\n            // Assert\n            Assert.True(invoked);\n            Assert.Equal(1, invokedValue);\n        }\n\n        [Fact]\n        public async Task TraceBeginEndAsyncGeneric_Does_Not_Invoke_EndTrace_When_Error_Occurs()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n            Exception exception = new InvalidOperationException();\n            TaskCompletionSource<int> tcs = new TaskCompletionSource<int>(0);\n            tcs.TrySetException(exception);\n\n            // Act & Assert\n            Exception thrown = await Assert.ThrowsAsync<InvalidOperationException>(\n                () => traceWriter.TraceBeginEndAsync<int>(request,\n                                 \"\",\n                                 TraceLevel.Off,\n                                 \"\",\n                                 \"\",\n                                 beginTrace: (tr) => { },\n                                 execute: () => tcs.Task,\n                                 endTrace: (tr, value) => { invoked = true; },\n                                 errorTrace: (tr) => { }));\n            Assert.False(invoked);\n            Assert.Same(exception, thrown);\n        }\n\n        [Fact]\n        public async Task TraceBeginEndAsyncGeneric_Does_Not_Invoke_EndTrace_When_Tracing_Only_Higher_Level()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            traceWriter.TraceSelector = (rqst, category, level) => level >= TraceLevel.Error;\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n\n            // Act\n            await traceWriter.TraceBeginEndAsync<int>(request,\n                                 \"\",\n                                 TraceLevel.Info,\n                                 \"\",\n                                 \"\",\n                                 beginTrace: (tr) => { },\n                                 execute: () => Task.FromResult<int>(1),\n                                 endTrace: (tr, value) => { invoked = true; },\n                                 errorTrace: (tr) => { });\n\n            // Assert\n            Assert.False(invoked);\n        }\n\n        [Fact]\n        public async Task TraceBeginEndAsyncGeneric_Invokes_ErrorTrace()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n            Exception exception = new InvalidOperationException();\n            TaskCompletionSource<int> tcs = new TaskCompletionSource<int>(0);\n            tcs.TrySetException(exception);\n\n            // Act & Assert\n            Exception thrown = await Assert.ThrowsAsync<InvalidOperationException>(\n                () => traceWriter.TraceBeginEndAsync<int>(request,\n                                 \"\",\n                                 TraceLevel.Off,\n                                 \"\",\n                                 \"\",\n                                 beginTrace: (tr) => { },\n                                 execute: () => tcs.Task,\n                                 endTrace: (tr, value) => { },\n                                 errorTrace: (tr) => { invoked = true; }));\n            Assert.True(invoked);\n            Assert.Same(exception, thrown);\n        }\n\n        [Fact]\n        public async Task TraceBeginEndAsyncGeneric_Does_Not_Invoke_ErrorTrace_When_Tracing_Only_Higher_Level()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            traceWriter.TraceSelector = (rqst, category, level) => level >= TraceLevel.Fatal;\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n            Exception exception = new InvalidOperationException();\n            TaskCompletionSource<int> tcs = new TaskCompletionSource<int>(0);\n            tcs.TrySetException(exception);\n\n            // Act & Assert\n            Exception thrown = await Assert.ThrowsAsync<InvalidOperationException>(\n                () => traceWriter.TraceBeginEndAsync<int>(request,\n                                 \"\",\n                                 TraceLevel.Info,\n                                 \"\",\n                                 \"\",\n                                 beginTrace: (tr) => { },\n                                 execute: () => tcs.Task,\n                                 endTrace: (tr, value) => { },\n                                 errorTrace: (tr) => { invoked = true; }));\n            Assert.False(invoked);\n            Assert.Same(exception, thrown);\n        }\n\n        [Fact]\n        public async Task TraceBeginEndAsyncGeneric_Invokes_ErrorTrace_When_Tracing_Only_Errors()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            traceWriter.TraceSelector = (rqst, category, level) => level >= TraceLevel.Error;\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n            Exception exception = new InvalidOperationException();\n            TaskCompletionSource<int> tcs = new TaskCompletionSource<int>(0);\n            tcs.TrySetException(exception);\n\n            // Act & Assert\n            Exception thrown = await Assert.ThrowsAsync<InvalidOperationException>(\n                () => traceWriter.TraceBeginEndAsync<int>(request,\n                                 \"\",\n                                 TraceLevel.Info,\n                                 \"\",\n                                 \"\",\n                                 beginTrace: (tr) => { },\n                                 execute: () => tcs.Task,\n                                 endTrace: (tr, value) => { },\n                                 errorTrace: (tr) => { invoked = true; }));\n            Assert.True(invoked);\n            Assert.Same(exception, thrown);\n        }\n\n        [Fact]\n        public async Task TraceBeginEndAsyncGeneric_Does_Not_Invoke_ErrorTrace_Unless_Error_Occurs()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            bool invoked = false;\n            TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();\n            tcs.TrySetResult(1);\n\n            // Act\n            await traceWriter.TraceBeginEndAsync<int>(\n                            request,\n                            \"\",\n                            TraceLevel.Off,\n                            \"\",\n                            \"\",\n                            beginTrace: (tr) => { },\n                            execute: () => tcs.Task,\n                            endTrace: (tr, value) => { },\n                            errorTrace: (tr) => { invoked = true; });\n\n            // Assert\n            Assert.False(invoked);\n        }\n\n        [Fact]\n        public async Task TraceBeginEndAsyncGeneric_Traces()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Info)\n                {\n                    Kind = TraceKind.Begin, Operator = \"tester\", Operation = \"testOp\", Message = \"beginMessage\"\n                },\n                new TraceRecord(request, \"testCategory\", TraceLevel.Info)\n                {\n                    Kind = TraceKind.End, Operator = \"tester\", Operation = \"testOp\", Message = \"endMessage1\"\n                },\n            };\n\n            // Act\n            await traceWriter.TraceBeginEndAsync<int>(request,\n                                 \"testCategory\",\n                                 TraceLevel.Info,\n                                 \"tester\",\n                                 \"testOp\",\n                                 beginTrace: (tr) => { tr.Message = \"beginMessage\"; },\n                                 execute: () => Task.FromResult<int>(1),\n                                 endTrace: (tr, value) => { tr.Message = \"endMessage\" + value; },\n                                 errorTrace: (tr) => { tr.Message = \"won't happen\"; });\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public async Task TraceBeginEndAsyncGeneric_Traces_When_Inner_Cancels()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Info)\n                {\n                    Kind = TraceKind.Begin, Operator = \"tester\", Operation = \"testOp\", Message = \"beginMessage\"\n                },\n                new TraceRecord(request, \"testCategory\", TraceLevel.Warn)\n                {\n                    Kind = TraceKind.End, Operator = \"tester\", Operation = \"testOp\", Message = \"errorMessage\"\n                },\n            };\n\n            // Act & Assert\n            await Assert.ThrowsAsync<TaskCanceledException>(\n                () => traceWriter.TraceBeginEndAsync<int>(request,\n                     \"testCategory\",\n                     TraceLevel.Info,\n                     \"tester\",\n                     \"testOp\",\n                     beginTrace: (tr) => { tr.Message = \"beginMessage\"; },\n                     execute: () => TaskHelpers.Canceled<int>(),\n                     endTrace: (tr, value) => { tr.Message = \"won't happen\"; },\n                     errorTrace: (tr) => { tr.Message = \"errorMessage\"; }));\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public async Task TraceBeginAsyncGeneric_Traces_And_Faults_When_Inner_Faults()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            InvalidOperationException exception = new InvalidOperationException();\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, \"testCategory\", TraceLevel.Info)\n                {\n                    Kind = TraceKind.Begin, Operator = \"tester\", Operation = \"testOp\", Message = \"beginMessage\"\n                },\n                new TraceRecord(request, \"testCategory\", TraceLevel.Error)\n                {\n                    Kind = TraceKind.End, Operator = \"tester\", Operation = \"testOp\",\n                    Message = \"errorMessage\", Exception = exception\n                },\n            };\n\n            TaskCompletionSource<int> tcs = new TaskCompletionSource<int>(1);\n            tcs.TrySetException(exception);\n\n            // Act & Assert\n            InvalidOperationException thrown = await Assert.ThrowsAsync<InvalidOperationException>(\n                        () => traceWriter.TraceBeginEndAsync<int>(request,\n                                     \"testCategory\",\n                                     TraceLevel.Info,\n                                     \"tester\",\n                                     \"testOp\",\n                                     beginTrace: (tr) => { tr.Message = \"beginMessage\"; },\n                                     execute: () => tcs.Task,\n                                     endTrace: (tr, value) => { tr.Message = \"won't happen\"; },\n                                     errorTrace: (tr) => { tr.Message = \"errorMessage\"; }));\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(exception, thrown);\n        }\n\n        private static AggregateException CreateAggregateException(HttpRequestMessage request)\n        {\n            using (new CultureReplacer())\n            {\n                HttpError httpError = new HttpError(new ModelStateDictionary()\n                {\n                    { \"key\", new ModelState() { Errors = { new ModelError(\"error\") } } },\n                    { \"username\", new ModelState() { Errors = { new ModelError(\"invalid\") } } },\n                }, true);\n                HttpResponseException hre = new HttpResponseException(\n                    request.CreateErrorResponse(Net.HttpStatusCode.BadRequest,\n                                                new HttpError(\"Error Message from HRE.\")));\n                Exception nestedHre = new Exception(\"Level 1\",\n                    new Exception(\"Level 2\",\n                        new HttpResponseException(request.CreateErrorResponse(Net.HttpStatusCode.NotFound, httpError))));\n                List<Exception> exceptions = new List<Exception>();\n                exceptions.Add(hre);\n                exceptions.Add(nestedHre);\n                return new AggregateException(exceptions);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/TestTraceWriter.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\n\nnamespace System.Web.Http.Tracing\n{\n    /// <summary>\n    /// Test spy used internally to capture <see cref=\"TraceRecord\"/>s.\n    /// </summary>\n    internal class TestTraceWriter : ITraceWriter\n    {\n        private List<TraceRecord> _traceRecords = new List<TraceRecord>();\n\n        public Func<HttpRequestMessage, string, TraceLevel, bool> TraceSelector { get; set; }\n\n        public IList<TraceRecord> Traces { get { return _traceRecords;  } }\n\n        public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)\n        {\n            if (TraceSelector == null || TraceSelector(request, category, level))\n            {\n                TraceRecord traceRecord = new TraceRecord(request, category, level);\n                traceAction(traceRecord);\n                lock (_traceRecords)\n                {\n                    _traceRecords.Add(traceRecord);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/TraceKindHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Tracing\n{\n    public class TraceKindHelperTest : EnumHelperTestBase<TraceKind>\n    {\n        public TraceKindHelperTest()\n            : base(TraceKindHelper.IsDefined, TraceKindHelper.Validate, (TraceKind)999)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/TraceLevelHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Tracing\n{\n    public class TraceLevelHelperTest : EnumHelperTestBase<TraceLevel>\n    {\n        public TraceLevelHelperTest()\n            : base(TraceLevelHelper.IsDefined, TraceLevelHelper.Validate, (TraceLevel)999)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/TraceManagerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.Services;\nusing System.Web.Http.Tracing.Tracers;\nusing Microsoft.TestCommon;\nusing Moq;\nusing Moq.Protected;\n\nnamespace System.Web.Http.Tracing\n{\n    public class TraceManagerTest\n    {\n        public static TheoryDataSet<List<DelegatingHandler>> MultipleMessageHandlers\n        {\n            get\n            {\n                TestTraceWriter traceWriter = new TestTraceWriter();\n                DelegatingHandler messageHandler = new Mock<DelegatingHandler>().Object;\n                DelegatingHandler msgHandlerTracer = new MessageHandlerTracer(messageHandler, traceWriter);\n                RequestMessageHandlerTracer requestMsgtracer = new RequestMessageHandlerTracer(traceWriter);\n                DelegatingHandler messageHandlerDummy = new Mock<DelegatingHandler>().Object;\n                DelegatingHandler msgHandlerTracerDummy = new MessageHandlerTracer(messageHandlerDummy, traceWriter);\n                return new TheoryDataSet<List<DelegatingHandler>>\n                {\n                    { new List<DelegatingHandler>() },\n                    { new List<DelegatingHandler>() { messageHandler } },\n                    { new List<DelegatingHandler>() { messageHandler, messageHandler } },\n                    { new List<DelegatingHandler>() { messageHandler, messageHandler, messageHandler } },\n                    { new List<DelegatingHandler>() { msgHandlerTracer } },\n                    { new List<DelegatingHandler>() { msgHandlerTracer, msgHandlerTracer } },\n                    { new List<DelegatingHandler>() { msgHandlerTracer, msgHandlerTracer, msgHandlerTracer } },\n                    { new List<DelegatingHandler>() { requestMsgtracer } },\n                    { new List<DelegatingHandler>() { requestMsgtracer, requestMsgtracer } },\n                    { new List<DelegatingHandler>() { requestMsgtracer, requestMsgtracer, requestMsgtracer } },\n                    { new List<DelegatingHandler>() { messageHandler, msgHandlerTracer } },\n                    { new List<DelegatingHandler>() { msgHandlerTracer, messageHandler } },\n                    { new List<DelegatingHandler>() { requestMsgtracer, messageHandler, msgHandlerTracer } },\n                    { new List<DelegatingHandler>() { messageHandler, requestMsgtracer, msgHandlerTracer } },\n                    { new List<DelegatingHandler>() { messageHandler, msgHandlerTracer, requestMsgtracer } },\n                    { new List<DelegatingHandler>() { requestMsgtracer, msgHandlerTracer, messageHandler } },\n                    { new List<DelegatingHandler>() { msgHandlerTracer, requestMsgtracer, messageHandler } },\n                    { new List<DelegatingHandler>() { msgHandlerTracer, messageHandler, requestMsgtracer } },\n                    { new List<DelegatingHandler>() { messageHandler, msgHandlerTracerDummy, requestMsgtracer } }\n                };\n            }\n        }\n\n        [Fact]\n        public void TraceManager_Is_In_Default_ServiceResolver()\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n\n            // Act\n            ITraceManager traceManager = config.Services.GetService(typeof(ITraceManager)) as ITraceManager;\n\n            // Assert\n            Assert.IsType<TraceManager>(traceManager);\n        }\n\n        [Theory]\n        [InlineData(typeof(IHttpControllerSelector))]\n        [InlineData(typeof(IHttpControllerActivator))]\n        [InlineData(typeof(IHttpActionSelector))]\n        [InlineData(typeof(IHttpActionInvoker))]\n        [InlineData(typeof(IActionValueBinder))]\n        [InlineData(typeof(IContentNegotiator))]\n        [InlineData(typeof(IHttpControllerTypeResolver))]\n        public void Initialize_Does_Not_Alter_Configuration_When_No_TraceWriter_Present(Type serviceType)\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            object defaultService = config.Services.GetService(serviceType);\n\n            // Act\n            new TraceManager().Initialize(config);\n\n            // Assert\n            Assert.Same(defaultService.GetType(), config.Services.GetService(serviceType).GetType());\n        }\n\n        [Theory]\n        [InlineData(typeof(IHttpControllerSelector))]\n        [InlineData(typeof(IHttpControllerActivator))]\n        [InlineData(typeof(IHttpActionSelector))]\n        [InlineData(typeof(IHttpActionInvoker))]\n        [InlineData(typeof(IActionValueBinder))]\n        [InlineData(typeof(IContentNegotiator))]\n        [InlineData(typeof(IHttpControllerTypeResolver))]\n        public void Initialize_Alters_Configuration_When_TraceWriter_Present(Type serviceType)\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            Mock<ITraceWriter> traceWriter = new Mock<ITraceWriter>() { CallBase = true };\n            config.Services.Replace(typeof(ITraceWriter), traceWriter.Object);\n            object defaultService = config.Services.GetService(serviceType);\n\n            // Act\n            new TraceManager().Initialize(config);\n\n            // Assert\n            Assert.NotSame(defaultService.GetType(), config.Services.GetService(serviceType).GetType());\n        }\n\n        [Fact]\n        public void Initialize_Does_Not_Alter_MessageHandlers_When_No_TraceWriter_Present()\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            Mock<DelegatingHandler> mockHandler = new Mock<DelegatingHandler>() { CallBase = true };\n            config.MessageHandlers.Add(mockHandler.Object);\n\n            // Act\n            new TraceManager().Initialize(config);\n\n            // Assert\n            Assert.Equal(config.MessageHandlers[config.MessageHandlers.Count - 1].GetType(), mockHandler.Object.GetType());\n        }\n\n        [Fact]\n        public void Initialize_Alters_MessageHandlers_WhenTraceWriter_Present()\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            Mock<ITraceWriter> traceWriter = new Mock<ITraceWriter>() { CallBase = true };\n            config.Services.Replace(typeof(ITraceWriter), traceWriter.Object);\n            Mock<DelegatingHandler> mockHandler = new Mock<DelegatingHandler>() { CallBase = true };\n            config.MessageHandlers.Add(mockHandler.Object);\n\n            // Act\n            new TraceManager().Initialize(config);\n\n            // Assert\n            Assert.IsAssignableFrom<RequestMessageHandlerTracer>(config.MessageHandlers[0]);\n            Assert.IsAssignableFrom<MessageHandlerTracer>(config.MessageHandlers[config.MessageHandlers.Count - 2]);\n            Assert.Equal(3, config.MessageHandlers.Count);\n            Assert.True(IsMessageHandlerCollectionValid(config.MessageHandlers));\n        }\n\n        [Fact]\n        public void Initialize_Does_Not_Alter_MediaTypeFormatters_When_No_TraceWriter_Present()\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n\n            // Act\n            new TraceManager().Initialize(config);\n\n            // Assert\n            foreach (var formatter in config.Formatters)\n            {\n                Assert.False(typeof(IFormatterTracer).IsAssignableFrom(formatter.GetType()));\n            }\n        }\n\n        [Fact]\n        public void Initialize_Alters_MediaTypeFormatters_WhenTraceWriter_Present()\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            Mock<ITraceWriter> traceWriter = new Mock<ITraceWriter>() { CallBase = true };\n            config.Services.Replace(typeof(ITraceWriter), traceWriter.Object);\n\n            // Act\n            new TraceManager().Initialize(config);\n\n            // Assert\n            foreach (var formatter in config.Formatters)\n            {\n                Assert.IsAssignableFrom<IFormatterTracer>(formatter);\n            }\n        }\n\n        [Fact]\n        public void Multiple_Initialize_DoesNotAlter_Num_Of_MessageHandlers_With_No_TraceWriter()\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            TraceManager traceManager = new TraceManager();\n            traceManager.Initialize(config);\n            int expectedHandlerCount = config.MessageHandlers.Count;\n\n            // Act\n            traceManager.Initialize(config);\n\n            // Assert\n            int actualHandlerCount = config.MessageHandlers.Count;\n            Assert.Equal(expectedHandlerCount, actualHandlerCount);\n        }\n\n        [Theory]\n        [PropertyData(\"MultipleMessageHandlers\")]\n        public void Multiple_Initialize_DoesNotAlter_MessageHandlerCollection(List<DelegatingHandler> handlerList)\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            config.Services.Replace(typeof(ITraceWriter), new TestTraceWriter());\n            foreach (var eachHandler in handlerList)\n            {\n                config.MessageHandlers.Add(eachHandler);\n            }\n            TraceManager traceManager = new TraceManager();\n            traceManager.Initialize(config);\n            Collection<DelegatingHandler> expectedMessageHandlers = config.MessageHandlers;\n\n            // Act\n            traceManager.Initialize(config);\n\n            // Assert\n            Collection<DelegatingHandler> actualMessageHandlers = config.MessageHandlers;\n            Assert.Equal(expectedMessageHandlers, actualMessageHandlers);\n            Assert.True(IsMessageHandlerCollectionValid(config.MessageHandlers));\n        }\n\n        [Fact]\n        public void HttpServer_Initialize_After_Trace_Manager_Initialize_DoesNotAlter_MessageHandlerCollection()\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            config.Services.Replace(typeof(ITraceWriter), new TestTraceWriter());\n            DelegatingHandler messageHandler = new Mock<DelegatingHandler>().Object;\n            config.MessageHandlers.Add(messageHandler);\n            TraceManager traceManager = new TraceManager();\n            traceManager.Initialize(config);\n            Collection<DelegatingHandler> expectedMessageHandlers = config.MessageHandlers;\n            HttpRequestMessage request = new HttpRequestMessage();\n            Mock<HttpControllerDispatcher> dispatcherMock = new Mock<HttpControllerDispatcher>(config);\n            dispatcherMock.Protected().Setup<Task<HttpResponseMessage>>(\"SendAsync\", request, CancellationToken.None)\n                .Returns(Task.FromResult<HttpResponseMessage>(request.CreateResponse()));\n\n            HttpServer server = new HttpServer(config, dispatcherMock.Object);\n            HttpMessageInvoker invoker = new HttpMessageInvoker(server);\n\n            // Act\n            Task<HttpResponseMessage> response = invoker.SendAsync(request, CancellationToken.None);\n\n            // Assert\n            Collection<DelegatingHandler> actualMessageHandlers = config.MessageHandlers;\n            Assert.Equal(expectedMessageHandlers, actualMessageHandlers);\n            Assert.True(IsMessageHandlerCollectionValid(config.MessageHandlers));\n        }\n\n        [Fact]\n        public void TraceManager_Initialize_After_HttpServer_Initialize_DoesNotAlter_MessageHandlerCollection()\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            config.Services.Replace(typeof(ITraceWriter), new TestTraceWriter());\n            DelegatingHandler messageHandler = new Mock<DelegatingHandler>().Object;\n            config.MessageHandlers.Add(messageHandler);\n            TraceManager traceManager = new TraceManager();\n            Collection<DelegatingHandler> expectedMessageHandlers = config.MessageHandlers;\n            HttpRequestMessage request = new HttpRequestMessage();\n            Mock<HttpControllerDispatcher> dispatcherMock = new Mock<HttpControllerDispatcher>(config);\n            dispatcherMock.Protected().Setup<Task<HttpResponseMessage>>(\"SendAsync\", request, CancellationToken.None)\n                .Returns(Task.FromResult<HttpResponseMessage>(request.CreateResponse()));\n\n            HttpServer server = new HttpServer(config, dispatcherMock.Object);\n            HttpMessageInvoker invoker = new HttpMessageInvoker(server);\n\n            // Act\n            Task<HttpResponseMessage> response = invoker.SendAsync(request, CancellationToken.None);\n            traceManager.Initialize(config);\n\n            // Assert\n            Collection<DelegatingHandler> actualMessageHandlers = config.MessageHandlers;\n            Assert.Equal(expectedMessageHandlers, actualMessageHandlers);\n            Assert.True(IsMessageHandlerCollectionValid(config.MessageHandlers));\n        }\n\n        [Fact]\n        public void HttpServer_CallsCustomMessageHandlers_InTheCorrectOrder()\n        {\n            // Arrange\n            List<int> order = new List<int>();\n            order.Add(1);\n            order.Add(2);\n            order.Add(3);\n            order.Add(4);\n            List<int>.Enumerator e = order.GetEnumerator();\n            OrderAwareMessageHandler messageHandler1 = new OrderAwareMessageHandler(e, 1);\n            OrderAwareMessageHandler messageHandler2 = new OrderAwareMessageHandler(e, 2);\n            OrderAwareMessageHandler messageHandler3 = new OrderAwareMessageHandler(e, 3);\n            OrderAwareMessageHandler messageHandler4 = new OrderAwareMessageHandler(e, 4);\n            HttpRequestMessage request = new HttpRequestMessage();\n            TraceManager traceManager = new TraceManager();\n            HttpConfiguration config = new HttpConfiguration();\n            config.Services.Replace(typeof(ITraceWriter), new TestTraceWriter());\n            config.MessageHandlers.Add(messageHandler1);\n            config.MessageHandlers.Add(messageHandler2);\n            config.MessageHandlers.Add(messageHandler3);\n            config.MessageHandlers.Add(messageHandler4);\n            Mock<HttpControllerDispatcher> dispatcherMock = new Mock<HttpControllerDispatcher>(config);\n            dispatcherMock.Protected().Setup<Task<HttpResponseMessage>>(\"SendAsync\", request, CancellationToken.None)\n                .Returns(Task.FromResult<HttpResponseMessage>(request.CreateResponse()));\n            HttpServer server = new HttpServer(config, dispatcherMock.Object);\n            HttpMessageInvoker invoker = new HttpMessageInvoker(server);\n\n            // Act\n            Task<HttpResponseMessage> response = invoker.SendAsync(request, CancellationToken.None);\n\n            // Assert\n            Assert.True(IsMessageHandlerCollectionValid(config.MessageHandlers));\n        }\n\n        public class OrderAwareMessageHandler : DelegatingHandler\n        {\n            private static IEnumerator<int> _order;\n            private int _expectedOrder;\n\n            public OrderAwareMessageHandler(IEnumerator<int> order, int expectedOrder)\n            {\n                _order = order;\n                _expectedOrder = expectedOrder;\n            }\n            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n            {\n                _order.MoveNext();\n                Assert.True(_order.Current == _expectedOrder);\n                return base.SendAsync(request, cancellationToken);\n            }\n        }\n\n        [Fact]\n        public void Initialize_Repairs_Handler_Collection_If_MsgHandler_Deleted()\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            config.Services.Replace(typeof(ITraceWriter), new TestTraceWriter());\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            DelegatingHandler messageHandler = new Mock<DelegatingHandler>().Object;\n            DelegatingHandler msgHandlerTracer = new MessageHandlerTracer(messageHandler, traceWriter);\n            RequestMessageHandlerTracer requestMsgtracer = new RequestMessageHandlerTracer(traceWriter);\n            List<DelegatingHandler> handlerList = new List<DelegatingHandler>() { messageHandler, msgHandlerTracer, requestMsgtracer };\n            foreach (var eachHandler in handlerList)\n            {\n                config.MessageHandlers.Add(eachHandler);\n            }\n            TraceManager traceManager = new TraceManager();\n            traceManager.Initialize(config);\n            int expectedHandlerCount = config.MessageHandlers.Count;\n\n            // Act\n            config.MessageHandlers.RemoveAt(expectedHandlerCount - 1);\n            traceManager.Initialize(config);\n\n            // Assert\n            int actualHandlerCount = config.MessageHandlers.Count;\n            Assert.Equal(expectedHandlerCount - 2, actualHandlerCount);\n            Assert.True(IsMessageHandlerCollectionValid(config.MessageHandlers));\n        }\n\n        [Fact]\n        public void Initialize_Repairs_Handler_Collection_If_Tracer_Deleted()\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            config.Services.Replace(typeof(ITraceWriter), new TestTraceWriter());\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            DelegatingHandler messageHandler = new Mock<DelegatingHandler>().Object;\n            DelegatingHandler msgHandlerTracer = new MessageHandlerTracer(messageHandler, traceWriter);\n            RequestMessageHandlerTracer requestMsgtracer = new RequestMessageHandlerTracer(traceWriter);\n            List<DelegatingHandler> handlerList = new List<DelegatingHandler>() { messageHandler, msgHandlerTracer, requestMsgtracer };\n            foreach (var eachHandler in handlerList)\n            {\n                config.MessageHandlers.Add(eachHandler);\n            }\n            TraceManager traceManager = new TraceManager();\n            traceManager.Initialize(config);\n            int handlerCount = config.MessageHandlers.Count;\n            Collection<DelegatingHandler> expectedMessageHandlers = config.MessageHandlers;\n\n            // Act\n            config.MessageHandlers.RemoveAt(handlerCount - 2);\n            traceManager.Initialize(config);\n\n            // Assert\n            Collection<DelegatingHandler> actualMessageHandlers = config.MessageHandlers;\n            Assert.Equal(expectedMessageHandlers, actualMessageHandlers);\n            Assert.True(IsMessageHandlerCollectionValid(config.MessageHandlers));\n        }\n\n        [Fact]\n        public void Initialize_Repairs_Handler_Collection_If_RequestTracer_Deleted()\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            config.Services.Replace(typeof(ITraceWriter), new TestTraceWriter());\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            DelegatingHandler messageHandler = new Mock<DelegatingHandler>().Object;\n            DelegatingHandler msgHandlerTracer = new MessageHandlerTracer(messageHandler, traceWriter);\n            RequestMessageHandlerTracer requestMsgtracer = new RequestMessageHandlerTracer(traceWriter);\n            List<DelegatingHandler> handlerList = new List<DelegatingHandler>() { messageHandler, msgHandlerTracer, requestMsgtracer };\n            foreach (var eachHandler in handlerList)\n            {\n                config.MessageHandlers.Add(eachHandler);\n            }\n            TraceManager traceManager = new TraceManager();\n            traceManager.Initialize(config);\n            Collection<DelegatingHandler> expectedMessageHandlers = config.MessageHandlers;\n\n            // Act\n            config.MessageHandlers.RemoveAt(2);\n            traceManager.Initialize(config);\n\n            // Assert\n            Collection<DelegatingHandler> actualMessageHandlers = config.MessageHandlers;\n            Assert.Equal(expectedMessageHandlers, actualMessageHandlers);\n            Assert.True(IsMessageHandlerCollectionValid(config.MessageHandlers));\n        }\n\n        [Fact]\n        public void Initialize_Repairs_Handler_Collection_If_MsgHandler_Inserted()\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            config.Services.Replace(typeof(ITraceWriter), new TestTraceWriter());\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            DelegatingHandler messageHandler = new Mock<DelegatingHandler>().Object;\n            DelegatingHandler msgHandlerTracer = new MessageHandlerTracer(messageHandler, traceWriter);\n            RequestMessageHandlerTracer requestMsgtracer = new RequestMessageHandlerTracer(traceWriter);\n            List<DelegatingHandler> handlerList = new List<DelegatingHandler>() { messageHandler, msgHandlerTracer, requestMsgtracer };\n            foreach (var eachHandler in handlerList)\n            {\n                config.MessageHandlers.Add(eachHandler);\n            }\n            TraceManager traceManager = new TraceManager();\n            traceManager.Initialize(config);\n            int expectedHandlerCount = config.MessageHandlers.Count;\n\n            // Act\n            config.MessageHandlers.Insert(1, messageHandler);\n            traceManager.Initialize(config);\n\n            // Assert\n            int actualHandlerCount = config.MessageHandlers.Count;\n            Assert.Equal(expectedHandlerCount + 2, actualHandlerCount);\n            Assert.True(IsMessageHandlerCollectionValid(config.MessageHandlers));\n        }\n\n        [Fact]\n        public void Initialize_Repairs_Handler_Collection_If_Tracer_Inserted()\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            config.Services.Replace(typeof(ITraceWriter), new TestTraceWriter());\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            DelegatingHandler messageHandler = new Mock<DelegatingHandler>().Object;\n            DelegatingHandler msgHandlerTracer = new MessageHandlerTracer(messageHandler, traceWriter);\n            RequestMessageHandlerTracer requestMsgtracer = new RequestMessageHandlerTracer(traceWriter);\n            List<DelegatingHandler> handlerList = new List<DelegatingHandler>() { messageHandler, msgHandlerTracer, requestMsgtracer };\n            foreach (var eachHandler in handlerList)\n            {\n                config.MessageHandlers.Add(eachHandler);\n            }\n            TraceManager traceManager = new TraceManager();\n            traceManager.Initialize(config);\n            Collection<DelegatingHandler> expectedMessageHandlers = config.MessageHandlers;\n\n            // Act\n            config.MessageHandlers.Insert(0, msgHandlerTracer);\n            traceManager.Initialize(config);\n\n            // Assert\n            Collection<DelegatingHandler> actualMessageHandlers = config.MessageHandlers;\n            Assert.Equal(expectedMessageHandlers, actualMessageHandlers);\n            Assert.True(IsMessageHandlerCollectionValid(config.MessageHandlers));\n        }\n\n        [Fact]\n        public void Initialize_Repairs_Handler_Collection_If_RequestTracer_Inserted()\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            config.Services.Replace(typeof(ITraceWriter), new TestTraceWriter());\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            DelegatingHandler messageHandler = new Mock<DelegatingHandler>().Object;\n            DelegatingHandler msgHandlerTracer = new MessageHandlerTracer(messageHandler, traceWriter);\n            RequestMessageHandlerTracer requestMsgtracer = new RequestMessageHandlerTracer(traceWriter);\n            List<DelegatingHandler> handlerList = new List<DelegatingHandler>() { messageHandler, msgHandlerTracer, requestMsgtracer };\n            foreach (var eachHandler in handlerList)\n            {\n                config.MessageHandlers.Add(eachHandler);\n            }\n            TraceManager traceManager = new TraceManager();\n            traceManager.Initialize(config);\n            Collection<DelegatingHandler> expectedMessageHandlers = config.MessageHandlers;\n\n            // Act\n            config.MessageHandlers.Insert(0, requestMsgtracer);\n            traceManager.Initialize(config);\n\n            // Assert\n            Collection<DelegatingHandler> actualMessageHandlers = config.MessageHandlers;\n            Assert.Equal(expectedMessageHandlers, actualMessageHandlers);\n            Assert.True(IsMessageHandlerCollectionValid(config.MessageHandlers));\n        }\n\n        private static bool IsMessageHandlerCollectionValid(Collection<DelegatingHandler> messageHandlers)\n        {\n            int handlerCount = messageHandlers.Count;\n\n            // if the handler count is zero, exit early.\n            if (handlerCount == 0)\n            {\n                return false;\n            }\n\n            // if RequestMessageHandlerTracer is absent, exit early.\n            if (!(messageHandlers[0] is RequestMessageHandlerTracer))\n            {\n                return false;\n            }\n\n            // Message handler list must be an odd number (2*N+1) for N message handlers.\n            if (handlerCount % 2 != 1)\n            {\n                return false;\n            }\n\n            // Check if all odd positions have tracers and even positions have their corresponding handlers.\n            for (int i = 2; i < handlerCount; i += 2)\n            {\n                DelegatingHandler tracer = messageHandlers[i - 1];\n                DelegatingHandler messageHandler = messageHandlers[i];\n                if (!(tracer is MessageHandlerTracer))\n                {\n                    return false;\n                }\n\n                DelegatingHandler innerHandler = Decorator.GetInner(tracer);\n                if (innerHandler != messageHandler)\n                {\n                    return false;\n                }\n            }\n\n            return true;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/TraceRecordComparer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Http.Tracing\n{\n    /// <summary>\n    /// Comparer class to allow xUnit asserts for <see cref=\"TraceRecord\"/>.\n    /// </summary>\n    internal class TraceRecordComparer : IEqualityComparer<TraceRecord>\n    {\n        public bool IgnoreExceptionReference { get; set; }\n\n        public bool Equals(TraceRecord x, TraceRecord y)\n        {\n            if (!String.Equals(x.Category, y.Category) ||\n                   x.Level != y.Level ||\n                   x.Kind != y.Kind ||\n                   !Object.ReferenceEquals(x.Request, y.Request))\n            {\n                return false;\n            }\n\n            // The following must match only if they are present on 'x' -- the expected value\n            if (x.Exception != null)\n            {\n                if (IgnoreExceptionReference)\n                {\n                    if (y.Exception == null || !String.Equals(x.Exception.Message, y.Exception.Message))\n                    {\n                        return false;\n                    }\n                }\n                else\n                {\n                    if (!Object.ReferenceEquals(x.Exception, y.Exception))\n                    {\n                        return false;\n                    }\n                }\n            }\n\n            if (!String.IsNullOrEmpty(x.Message) && !String.Equals(x.Message, y.Message))\n            {\n                return false;\n            }\n\n            if (!String.IsNullOrEmpty(x.Operation) && !String.Equals(x.Operation, y.Operation))\n            {\n                return false;\n            }\n\n            if (!String.IsNullOrEmpty(x.Operator) && !String.Equals(x.Operator, y.Operator))\n            {\n                return false;\n            }\n\n            return true;\n        }\n\n        public int GetHashCode(TraceRecord obj)\n        {\n            return obj.GetHashCode();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/TraceRecordTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Tracing\n{\n    public class TraceRecordTest\n    {\n        [Fact]\n        public void TraceRecord_TraceKind_RoundTrips()\n        {\n            Assert.Reflection.EnumProperty(\n                new TraceRecord(request: null, category: null, level: TraceLevel.Info),\n                r => r.Kind,\n                expectedDefaultValue: TraceKind.Trace,\n                illegalValue: (TraceKind)999,\n                roundTripTestValue: TraceKind.End);\n        }\n\n        [Fact]\n        public void TraceRecord_TraceLevel_RoundTrips()\n        {\n            Assert.Reflection.EnumProperty(\n                new TraceRecord(request: null, category: null, level: TraceLevel.Info),\n                r => r.Level,\n                expectedDefaultValue: TraceLevel.Info,\n                illegalValue: (TraceLevel)999,\n                roundTripTestValue: TraceLevel.Fatal);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/TracerCorrectnessTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Reflection;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.Filters;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.Tracing.Tracers;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Tracing\n{\n    /// <summary>\n    /// This test class verifies that all tracers are correctly written.\n    /// </summary>\n    public class TracerCorrectnessTest\n    {\n        // Theory data for Tracers.  Tuple is:\n        // [0] a framework type known to have a tracer\n        // [1] the type of the tracer for that framework type\n        // [2] member exclusion list,\n        //     A string array containing member names the tracer handles in some way hidden from analysis.\n        //     They will not be reported as issues.\n        // !!! Exercise care in adding to the exclusion list !!!\n        //     It means you have dealt with the issue, not that you're hiding from it.\n        public static TheoryDataSet<Type, Type, string[]> AllKnownTracers\n        {\n            get\n            {\n                return new TheoryDataSet<Type, Type, string[]>\n                {\n                    { typeof(ActionFilterAttribute), typeof(ActionFilterAttributeTracer), new string[0] },\n                    { typeof(IActionValueBinder), typeof(ActionValueBinderTracer), new string[0] },\n                    { typeof(IActionFilter), typeof(ActionFilterTracer), new string[0] },\n                    { typeof(AuthorizationFilterAttribute), typeof(AuthorizationFilterAttributeTracer), new string[0] },\n                    { typeof(IAuthorizationFilter), typeof(AuthorizationFilterTracer), new string[0] },\n                    { typeof(IAuthenticationFilter), typeof(AuthenticationFilterTracer), new string[0] },\n                    { typeof(IOverrideFilter), typeof(OverrideFilterTracer), new string[0] },\n                    { typeof(BufferedMediaTypeFormatter), typeof(BufferedMediaTypeFormatterTracer), new string[]\n                        {\n                            // Values copied in ctor\n                            \"get_BufferSize\", \"set_BufferSize\",\n                            \"get_SupportedMediaTypes\",\n                            \"get_SupportedEncodings\",\n                            \"get_MediaTypeMappings\",\n                            \"get_RequiredMemberSelector\", \"set_RequiredMemberSelector\",\n                            // Cannot override, inner handles correctly\n                            \"ReadFromStreamAsync\", \"WriteToStreamAsync\", \"SelectCharacterEncoding\"\n                        }\n                    },\n                    { typeof(IContentNegotiator), typeof(ContentNegotiatorTracer), new string[0] },\n                    { typeof(ExceptionFilterAttribute), typeof(ExceptionFilterAttributeTracer), new string[0] },\n                    { typeof(IExceptionFilter), typeof(ExceptionFilterTracer), new string[0] },\n                    { typeof(IFilter), typeof(FilterTracer), new string[0] },\n                    { typeof(FormatterParameterBinding), typeof(FormatterParameterBindingTracer), new string[]\n                        {\n                            // Handled in base ctor\n                            \"get_Formatters\", \"set_Formatters\",\n                            \"get_BodyModelValidator\", \"set_BodyModelValidator\",\n                            \"get_Descriptor\",\n                            // Cannot override but handled by overriding ErrorMessage\n                            \"get_IsValid\",\n                            \"GetValue\", \"SetValue\"\n                        }\n                    },\n                    { typeof(FormUrlEncodedMediaTypeFormatter), typeof(FormUrlEncodedMediaTypeFormatterTracer), new string[]\n                        {\n                            // Values copied in ctor\n                            \"get_MaxDepth\", \"set_MaxDepth\",\n                            \"get_ReadBufferSize\", \"set_ReadBufferSize\",\n                            \"get_SupportedMediaTypes\",\n                            \"get_SupportedEncodings\",\n                            \"get_MediaTypeMappings\",\n                            \"get_RequiredMemberSelector\", \"set_RequiredMemberSelector\",\n                            // Cannot override, base handles correctly via SupportedEncodings\n                            \"SelectCharacterEncoding\",\n                        }\n                    },\n                    { typeof(HttpActionBinding), typeof(HttpActionBindingTracer), new string[]\n                        {\n                            // Values copied in ctor\n                            \"get_ActionDescriptor\", \"set_ActionDescriptor\",\n                            \"get_ParameterBindings\", \"set_ParameterBindings\"\n                        }\n                    },\n                    { typeof(HttpActionDescriptor), typeof(HttpActionDescriptorTracer), new string[]\n                        {\n                            // Values copied in ctor\n                            \"get_Configuration\", \"set_Configuration\",\n                            \"get_ControllerDescriptor\", \"set_ControllerDescriptor\"\n                        }\n                    },\n\n                    { typeof(IHttpActionInvoker), typeof(HttpActionInvokerTracer), new string[0] },\n                    { typeof(IHttpActionSelector), typeof(HttpActionSelectorTracer), new string[0] },\n                    { typeof(IHttpControllerActivator), typeof(HttpControllerActivatorTracer), new string[0] },\n                    { typeof(HttpControllerDescriptor), typeof(HttpControllerDescriptorTracer), new string[]\n                        {\n                            // Values copied in ctor\n                            \"get_Configuration\", \"set_Configuration\",\n                            \"get_ControllerType\", \"set_ControllerType\",\n                            \"get_ControllerName\", \"set_ControllerName\"\n                        }\n                    },\n                    { typeof(IHttpControllerSelector), typeof(HttpControllerSelectorTracer), new string[0] },\n                    { typeof(IHttpController), typeof(HttpControllerTracer), new string[0] },\n                    { typeof(HttpParameterBinding), typeof(HttpParameterBindingTracer), new string[]\n                        {\n                            // Handled in base ctor\n                            \"get_Descriptor\",\n                            // Cannot override but handled by overriding ErrorMessage\n                            \"get_IsValid\",\n                            \"GetValue\", \"SetValue\",\n                        }\n                    },\n                    { typeof(JsonMediaTypeFormatter), typeof(JsonMediaTypeFormatterTracer), new string[]\n                        {\n                            // Values copied in ctor\n                            \"get_MaxDepth\", \"set_MaxDepth\",\n                            \"get_SupportedMediaTypes\",\n                            \"get_SupportedEncodings\",\n                            \"get_MediaTypeMappings\",\n                            \"get_RequiredMemberSelector\", \"set_RequiredMemberSelector\",\n                            \"get_Indent\", \"set_Indent\",\n                            \"get_UseDataContractJsonSerializer\", \"set_UseDataContractJsonSerializer\",\n                            \"get_SerializerSettings\", \"set_SerializerSettings\",\n                            // Cannot override, base handles correctly\n                            \"SelectCharacterEncoding\",\n                            // Cannot override behavior, but copying SerializerSettings in ctor captures inner's result\n                            \"CreateDefaultSerializerSettings\"\n                        }\n                    },\n                    { typeof(MediaTypeFormatter), typeof(MediaTypeFormatterTracer), new string[]\n                        {\n                            // Values copied in ctor\n                            \"get_SupportedMediaTypes\", \"get_SupportedEncodings\",\n                            \"get_MediaTypeMappings\",\n                            \"get_RequiredMemberSelector\", \"set_RequiredMemberSelector\",\n                            // Cannot override, base handles correctly\n                            \"SelectCharacterEncoding\"\n                        }\n                    },\n                    { typeof(DelegatingHandler), typeof(MessageHandlerTracer),  new string[]\n                        {\n                            // Value set by framework before we trace\n                            \"get_InnerHandler\", \"set_InnerHandler\",\n                            // Not meant to be delegated to inner, just to base\n                            \"Dispose\"\n                        }\n                    },\n                    { typeof(DelegatingHandler), typeof(RequestMessageHandlerTracer),new string[]\n                        {\n                            // Value set by framework before we trace\n                            \"get_InnerHandler\", \"set_InnerHandler\",\n                            // Not meant to be delegated to inner, just to base\n                            \"Dispose\"\n                        }\n                    },\n                    { typeof(XmlMediaTypeFormatter), typeof(XmlMediaTypeFormatterTracer), new string[]\n                        {\n                            // Values copied in ctor\n                            \"get_SupportedMediaTypes\",\n                            \"get_SupportedEncodings\",\n                            \"get_MediaTypeMappings\",\n                            \"get_RequiredMemberSelector\", \"set_RequiredMemberSelector\",\n                            \"get_UseXmlSerializer\", \"set_UseXmlSerializer\",\n                            \"get_Indent\", \"set_Indent\",\n                            \"get_WriterSettings\",\n                            \"get_MaxDepth\", \"set_MaxDepth\",\n                            \"InvokeCreateXmlReader\", \"InvokeCreateXmlWriter\",\n                            \"InvokeGetDeserializer\", \"InvokeGetSerializer\",\n                            // Cannot override, base handles correctly\n                            \"SelectCharacterEncoding\",\n                            // Assume these are called before starting app.\n                            // Tracer does not need to see them,\n                            // and inner will uses its copies in read or write\n                            \"SetSerializer\", \"RemoveSerializer\",\n                        }\n                    },\n                    { typeof(DefaultHttpControllerTypeResolver), typeof(DefaultHttpControllerTypeResolverTracer), new string[0] },\n                };\n            }\n        }\n\n        // Following filters work best if there are no duplicate tracer types in AllKnownTracers. Currently the case.\n        public static TheoryDataSet<Type, Type> AllKnownTracers_NoExclusions\n        {\n            get\n            {\n                var dataSet = new TheoryDataSet<Type, Type>();\n                foreach (var item in AllKnownTracers)\n                {\n                    dataSet.Add((Type)item[0], (Type)item[1]);\n                }\n\n                return dataSet;\n            }\n        }\n\n        public static TheoryDataSet<Type, string[]> AllKnownTracers_NoInnerType\n        {\n            get\n            {\n                var dataSet = new TheoryDataSet<Type, string[]>();\n                foreach (var item in AllKnownTracers)\n                {\n                    dataSet.Add((Type)item[1], (string[])item[2]);\n                }\n\n                return dataSet;\n            }\n        }\n\n        public static TheoryDataSet<Type> AllKnownTracers_JustTracerType\n        {\n            get\n            {\n                var dataSet = new TheoryDataSet<Type>();\n                foreach (var item in AllKnownTracers)\n                {\n                    dataSet.Add((Type)item[1]);\n                }\n\n                return dataSet;\n            }\n        }\n\n        [Fact]\n        public void All_Tracers_Are_Tested()\n        {\n            // Arrange & Act\n            Type[] allTracerTypes = typeof(ITraceWriter).Assembly.GetTypes().Where(t => !t.IsAbstract && t.Name.EndsWith(\"Tracer\")).ToArray();\n            Type[] allKnownTracerTypes = AllKnownTracers.Select<object[], Type>(tds => (Type)tds[1]).ToArray();\n            Type[] untestedTypes = allTracerTypes.Where(tAll => !allKnownTracerTypes.Any(tKnown => tKnown == tAll)).ToArray();\n            untestedTypes = untestedTypes.OrderBy<Type, string>(t => t.Name).ToArray();\n\n            // Assert\n            Assert.True(untestedTypes.Length == 0,\n                        String.Format(\"These tracer types must be added to {0}.AllKnownTracers:{1}        {2}\",\n                        this.GetType().Name,\n                        Environment.NewLine,\n                        string.Join(Environment.NewLine + \"        \", untestedTypes.Select<Type, string>(t => t.Name))));\n        }\n\n        [Theory]\n        [PropertyData(\"AllKnownTracers_NoExclusions\")]\n        public void All_Tracers_Are_Internal_And_Disposable_When_Inner_Is_Disposable(Type innerType, Type tracerType)\n        {\n            // Arrange\n            TypeAssert.TypeProperties typeProperties = TypeAssert.TypeProperties.IsClass;\n\n            // If the inner is IDisposable, the tracer must be too.\n            // The IHttpController case is special -- it must be disposable to invoke the inner.Dispose\n            // only if the implementation type is IDisposable.\n            if (typeof(IDisposable).IsAssignableFrom(innerType) || innerType == typeof(IHttpController))\n            {\n                typeProperties |= TypeAssert.TypeProperties.IsDisposable;\n            }\n\n            // Act & Assert\n            Assert.Type.HasProperties(tracerType, typeProperties);\n        }\n\n        [Theory]\n        [PropertyData(\"AllKnownTracers_JustTracerType\")]\n        public void All_Tracers_Use_Correct_Namespace(Type tracerType)\n        {\n            // Arrange & Act & Assert\n            Assert.Equal(\"System.Web.Http.Tracing.Tracers\", tracerType.Namespace);\n        }\n\n        [Theory]\n        [PropertyData(\"AllKnownTracers_NoInnerType\")]\n        public void All_Excluded_Members_Are_Declared(Type tracerType, string[] exclusions)\n        {\n            // Arrange & Act\n            string[] declaredMembers = tracerType.GetMembers(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Select<MemberInfo, string>(m => m.Name).ToArray();\n            string[] unDeclaredExcludedMembers = exclusions.Where(e => !declaredMembers.Contains(e.Substring(e.LastIndexOf('.') + 1))).ToArray();\n\n            // Assert\n            Assert.True(unDeclaredExcludedMembers.Length == 0,\n                        String.Format(\"The tracer '{0}' does not declare these members listed for exclusion: {1}\",\n                                        tracerType.Name,\n                                        string.Join(\",\", unDeclaredExcludedMembers)));\n        }\n\n        [Theory]\n        [PropertyData(\"AllKnownTracers\")]\n        public void All_Tracers_Handle_All_Inner_Members(Type innerType, Type tracerType, string[] excludedMembers)\n        {\n            // Arrange & Act\n            IList<string> issues = DetermineIssues(innerType, tracerType, excludedMembers);\n\n            // Assert\n            Assert.True(issues.Count == 0,\n                        String.Format(\"'{0}' does not handle these members from '{1}':{2}        {3}\",\n                        tracerType.Name,\n                        innerType.Name,\n                        Environment.NewLine,\n                        string.Join(Environment.NewLine + \"        \", issues)));\n        }\n\n        private static IList<string> DetermineIssues(Type innerType, Type tracerType, string[] excludedMembers)\n        {\n            List<string> issues = new List<string>();\n\n            MemberInfo[] typeMembers = innerType.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);\n            foreach (MemberInfo memberInfo in typeMembers)\n            {\n                if (memberInfo is ConstructorInfo)\n                {\n                    continue;\n                }\n\n                MethodInfo methodInfo = memberInfo as MethodInfo;\n                if (methodInfo != null)\n                {\n                    AddIssues(tracerType, issues, methodInfo, excludedMembers);\n                }\n            }\n\n            return issues;\n        }\n\n        private static void AddIssues(Type tracerType, IList<string> issues, MethodInfo methodInfo, string[] excludedMembers)\n        {\n            if (methodInfo == null ||\n                !(methodInfo.IsPublic || methodInfo.IsFamily) ||\n                methodInfo.DeclaringType == typeof(Object))\n            {\n                return;\n            }\n\n            // Allow exclusion list to be short name or long name, because some members are up the inheritance chain\n            string visibleMemberName = String.Format(\"{0}.{1}\", methodInfo.DeclaringType.Name, GetSignature(methodInfo));\n            if (!DoesTracerDeclare(tracerType, methodInfo) && !excludedMembers.Contains(visibleMemberName) && !excludedMembers.Contains(methodInfo.Name))\n            {\n                bool isOverrideable = IsOverrideable(methodInfo);\n                bool isSetter = methodInfo.IsSpecialName && methodInfo.Name.StartsWith(\"set_\");\n                bool isGetter = methodInfo.IsSpecialName && methodInfo.Name.StartsWith(\"get_\");\n                issues.Add(String.Format(\"{0} [{1}]\",\n                            visibleMemberName,\n                            isOverrideable\n                                ? \"Override this virtual in the tracer\"\n                                : isGetter\n                                    ? \"Capture this value from inner in the tracer's ctor, and add to it to the exclude list\"\n                                    : isSetter\n                                        ? \"Ensure this non-virtual setter cannot be called after the tracer has captured it, and add it to the exclude list\"\n                                        : \"Make this member virtual and override it, or add it to the exclude list\"));\n            }\n        }\n\n        private static bool IsOverrideable(MethodInfo methodInfo)\n        {\n            return !methodInfo.IsFinal && (methodInfo.IsVirtual || methodInfo.IsAbstract);\n        }\n\n        private static bool DoMethodsMatch(MethodInfo originalMethodInfo, MethodInfo candidateMethodInfo)\n        {\n            if (!GetSignature(candidateMethodInfo).Equals(GetSignature(originalMethodInfo)))\n            {\n                return false;\n            }\n\n            return true;\n        }\n\n        private static string GetSignature(MethodInfo methodInfo)\n        {\n            return\n                String.Format(\"{0}({1})\", methodInfo.Name.Substring(methodInfo.Name.LastIndexOf(\".\") + 1),\n                    String.Join(\",\", methodInfo.GetParameters().Select(p => p.ParameterType.Name)));\n        }\n\n        private static bool DoesTracerDeclare(Type tracerType, MethodInfo methodInfo)\n        {\n            if (methodInfo == null)\n            {\n                return true;\n            }\n\n            MethodInfo matchingMethod = tracerType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).FirstOrDefault(m => DoMethodsMatch(methodInfo, m));\n            return matchingMethod != null && matchingMethod.DeclaringType != methodInfo.DeclaringType;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/ActionFilterAttributeTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Services;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class ActionFilterAttributeTracerTest\n    {\n        [Fact]\n        public void Equals_Calls_Inner()\n        {\n            // Arrange\n            object randomObject = new Object();\n            Mock<ActionFilterAttribute> mockAttribute = new Mock<ActionFilterAttribute>();\n            mockAttribute.Setup(a => a.Equals(randomObject)).Returns(true).Verifiable();\n            ActionFilterAttributeTracer tracer = new ActionFilterAttributeTracer(mockAttribute.Object, new TestTraceWriter());\n\n            // Act\n            bool valueReturned = tracer.Equals(randomObject);\n\n            // Assert\n            Assert.True(valueReturned);\n            mockAttribute.Verify();\n        }\n\n        [Fact]\n        public void GetHashCode_Calls_Inner()\n        {\n            // Arrange\n            Mock<ActionFilterAttribute> mockAttribute = new Mock<ActionFilterAttribute>();\n            mockAttribute.Setup(a => a.GetHashCode()).Returns(1).Verifiable();\n            ActionFilterAttributeTracer tracer = new ActionFilterAttributeTracer(mockAttribute.Object, new TestTraceWriter());\n\n            // Act\n            int valueReturned = tracer.GetHashCode();\n\n            // Assert\n            Assert.Equal(1, valueReturned);\n            mockAttribute.Verify();\n        }\n\n        [Fact]\n        public void IsDefaultAttribute_Calls_Inner()\n        {\n            // Arrange\n            Mock<ActionFilterAttribute> mockAttribute = new Mock<ActionFilterAttribute>();\n            mockAttribute.Setup(a => a.IsDefaultAttribute()).Returns(true).Verifiable();\n            ActionFilterAttributeTracer tracer = new ActionFilterAttributeTracer(mockAttribute.Object, new TestTraceWriter());\n\n            // Act\n            bool valueReturned = tracer.IsDefaultAttribute();\n\n            // Assert\n            Assert.True(valueReturned);\n            mockAttribute.Verify();\n        }\n\n        [Fact]\n        public void Match_Calls_Inner()\n        {\n            // Arrange\n            object randomObject = new Object();\n            Mock<ActionFilterAttribute> mockAttribute = new Mock<ActionFilterAttribute>();\n            mockAttribute.Setup(a => a.Match(randomObject)).Returns(true).Verifiable();\n            ActionFilterAttributeTracer tracer = new ActionFilterAttributeTracer(mockAttribute.Object, new TestTraceWriter());\n\n            // Act\n            bool valueReturned = tracer.Match(randomObject);\n\n            // Assert\n            Assert.True(valueReturned);\n            mockAttribute.Verify();\n        }\n\n        [Fact]\n        public void TypeId_Calls_Inner()\n        {\n            // Arrange\n            object randomObject = new Object();\n            Mock<ActionFilterAttribute> mockAttribute = new Mock<ActionFilterAttribute>();\n            mockAttribute.Setup(a => a.TypeId).Returns(randomObject).Verifiable();\n            ActionFilterAttributeTracer tracer = new ActionFilterAttributeTracer(mockAttribute.Object, new TestTraceWriter());\n\n            // Act\n            object valueReturned = tracer.TypeId;\n\n            // Assert\n            Assert.Same(randomObject, valueReturned);\n            mockAttribute.Verify();\n        }\n\n        [Fact]\n        public void AllowMultiple_Calls_Inner()\n        {\n            // Arrange\n            Mock<ActionFilterAttribute> mockAttribute = new Mock<ActionFilterAttribute>();\n            mockAttribute.Setup(a => a.AllowMultiple).Returns(true).Verifiable();\n            ActionFilterAttributeTracer tracer = new ActionFilterAttributeTracer(mockAttribute.Object, new TestTraceWriter());\n\n            // Act\n            bool valueReturned = tracer.AllowMultiple;\n\n            // Assert\n            Assert.True(valueReturned);\n            mockAttribute.Verify();\n        }\n\n        [Fact]\n        public async Task ExecuteActionFilterAsync_Traces_Executing_And_Executed()\n        {\n            // Arrange\n            Mock<ActionFilterAttribute> mockAttr = new Mock<ActionFilterAttribute>() { CallBase = true };\n            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };\n            mockActionDescriptor.Setup(a => a.ActionName).Returns(\"test\");\n            mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0]));\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(actionDescriptor: mockActionDescriptor.Object);\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            IActionFilter tracer = new ActionFilterAttributeTracer(mockAttr.Object, traceWriter) as IActionFilter;\n            Func<Task<HttpResponseMessage>> continuation =\n                () => Task.FromResult<HttpResponseMessage>(new HttpResponseMessage());\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"OnActionExecutingAsync\" },\n                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.End,  Operation = \"OnActionExecutingAsync\" },\n                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"OnActionExecutedAsync\" },\n                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.End,  Operation = \"OnActionExecutedAsync\" }\n            };\n\n            // Act\n            await tracer.ExecuteActionFilterAsync(actionContext, CancellationToken.None, continuation);\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public async Task ExecuteActionFilterAsync_Faults_And_Traces_When_OnExecuting_Faults()\n        {\n            // Arrange\n            Mock<ActionFilterAttribute> mockAttr = new Mock<ActionFilterAttribute>() { CallBase = true };\n            InvalidOperationException exception = new InvalidOperationException(\"test\");\n            mockAttr.Setup(a => a.OnActionExecuting(It.IsAny<HttpActionContext>())).Throws(exception);\n            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };\n            mockActionDescriptor.Setup(a => a.ActionName).Returns(\"test\");\n            mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0]));\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(actionDescriptor: mockActionDescriptor.Object);\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            IActionFilter tracer = new ActionFilterAttributeTracer(mockAttr.Object, traceWriter) as IActionFilter;\n            Func<Task<HttpResponseMessage>> continuation =\n                () => Task.FromResult<HttpResponseMessage>(new HttpResponseMessage());\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"OnActionExecutingAsync\" },\n                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Error) { Kind = TraceKind.End,  Operation = \"OnActionExecutingAsync\" }\n            };\n\n            // Act\n            Task<HttpResponseMessage> task = tracer.ExecuteActionFilterAsync(actionContext, CancellationToken.None, continuation);\n\n            // Assert\n            Exception thrown = await Assert.ThrowsAsync<InvalidOperationException>(() => task);\n            Assert.Same(exception, thrown);\n            Assert.Same(exception, traceWriter.Traces[1].Exception);\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public async Task ExecuteActionFilterAsync_Faults_And_Traces_When_OnExecuted_Faults()\n        {\n            // Arrange\n            Mock<ActionFilterAttribute> mockAttr = new Mock<ActionFilterAttribute>() { CallBase = true };\n            InvalidOperationException exception = new InvalidOperationException(\"test\");\n            mockAttr.Setup(a => a.OnActionExecuted(It.IsAny<HttpActionExecutedContext>())).Throws(exception);\n            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };\n            mockActionDescriptor.Setup(a => a.ActionName).Returns(\"test\");\n            mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0]));\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(actionDescriptor: mockActionDescriptor.Object);\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            IActionFilter tracer = new ActionFilterAttributeTracer(mockAttr.Object, traceWriter) as IActionFilter;\n\n            Func<Task<HttpResponseMessage>> continuation =\n                () => Task.FromResult<HttpResponseMessage>(new HttpResponseMessage());\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"OnActionExecutingAsync\" },\n                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.End,  Operation = \"OnActionExecutingAsync\" },\n                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"OnActionExecutedAsync\" },\n                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Error) { Kind = TraceKind.End,  Operation = \"OnActionExecutedAsync\" }\n            };\n\n            // Act\n            Task<HttpResponseMessage> task = tracer.ExecuteActionFilterAsync(actionContext, CancellationToken.None, continuation);\n\n            // Assert\n            Exception thrown = await Assert.ThrowsAsync<InvalidOperationException>(() => task);\n            Assert.Same(exception, thrown);\n            Assert.Same(exception, traceWriter.Traces[3].Exception);\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void Inner_Property_On_ActionFilterAttributeTracer_Returns_ActionFilterAttribute()\n        {\n            // Arrange\n            ActionFilterAttribute expectedInner = new Mock<ActionFilterAttribute>().Object;\n            ActionFilterAttributeTracer productUnderTest = new ActionFilterAttributeTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            ActionFilterAttribute actualInner = productUnderTest.Inner;\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n\n        [Fact]\n        public void Decorator_GetInner_On_ActionFilterAttributeTracer_Returns_ActionFilterAttribute()\n        {\n            // Arrange\n            ActionFilterAttribute expectedInner = new Mock<ActionFilterAttribute>().Object;\n            ActionFilterAttributeTracer productUnderTest = new ActionFilterAttributeTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            ActionFilterAttribute actualInner = Decorator.GetInner(productUnderTest as ActionFilterAttribute);\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/ActionFilterTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Services;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class ActionFilterTracerTest\n    {\n        [Fact]\n        public async Task ExecuteActionAsync_Traces_ExecuteActionFilterAsync()\n        {\n            // Arrange\n            HttpResponseMessage response = new HttpResponseMessage();\n            Mock<IActionFilter> mockFilter = new Mock<IActionFilter>() { CallBase = true };\n            mockFilter.Setup(\n                f =>\n                f.ExecuteActionFilterAsync(It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>(),\n                                           It.IsAny<Func<Task<HttpResponseMessage>>>())).Returns(\n                                               Task.FromResult<HttpResponseMessage>(response));\n            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };\n            mockActionDescriptor.Setup(a => a.ActionName).Returns(\"test\");\n            mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0]));\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(actionDescriptor: mockActionDescriptor.Object);\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            ActionFilterTracer tracer = new ActionFilterTracer(mockFilter.Object, traceWriter);\n            Func<Task<HttpResponseMessage>> continuation =\n                () => Task.FromResult<HttpResponseMessage>(new HttpResponseMessage());\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"ExecuteActionFilterAsync\" },\n                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.End,  Operation = \"ExecuteActionFilterAsync\" },\n            };\n\n            // Act\n            var filter = (IActionFilter)tracer;\n            await filter.ExecuteActionFilterAsync(actionContext, CancellationToken.None, continuation);\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public async Task ExecuteActionAsync_Faults_And_Traces_When_Inner_Faults()\n        {\n            // Arrange\n            InvalidOperationException exception = new InvalidOperationException(\"test\");\n            Mock<IActionFilter> mockFilter = new Mock<IActionFilter>() { CallBase = true };\n            TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>(null);\n            tcs.TrySetException(exception);\n            mockFilter.Setup(f => f.ExecuteActionFilterAsync(It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>(),\n                                It.IsAny<Func<Task<HttpResponseMessage>>>())).Returns(tcs.Task);\n            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };\n            mockActionDescriptor.Setup(a => a.ActionName).Returns(\"test\");\n            mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0]));\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(actionDescriptor: mockActionDescriptor.Object);\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            ActionFilterTracer tracer = new ActionFilterTracer(mockFilter.Object, traceWriter);\n            Func<Task<HttpResponseMessage>> continuation =\n                () => Task.FromResult<HttpResponseMessage>(new HttpResponseMessage());\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"ExecuteActionFilterAsync\" },\n                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Error) { Kind = TraceKind.End,  Operation = \"ExecuteActionFilterAsync\" },\n            };\n\n            // Act\n            Task<HttpResponseMessage> task = ((IActionFilter)tracer).ExecuteActionFilterAsync(actionContext, CancellationToken.None, continuation);\n\n\n            // Assert\n            Exception thrown = await Assert.ThrowsAsync<InvalidOperationException>(() => task);\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(exception, traceWriter.Traces[1].Exception);\n        }\n\n        [Fact]\n        public void Inner_Property_On_ActionFilterTracer_Returns_IActionFilter()\n        {\n            // Arrange\n            IActionFilter expectedInner = new Mock<IActionFilter>().Object;\n            ActionFilterTracer productUnderTest = new ActionFilterTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            IActionFilter actualInner = productUnderTest.Inner as IActionFilter;\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n\n        [Fact]\n        public void Decorator_GetInner_Property_On_ActionFilterTracer_Returns_IActionFilter()\n        {\n            // Arrange\n            IActionFilter expectedInner = new Mock<IActionFilter>().Object;\n            ActionFilterTracer productUnderTest = new ActionFilterTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            IActionFilter actualInner = Decorator.GetInner(productUnderTest as IActionFilter);\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/ActionValueBinderTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.Services;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class ActionValueBinderTracerTest\n    {\n        [Fact]\n        public void GetBinding_Returns_HttpActionBindingTracer()\n        {\n            // Arrange\n            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };\n            mockActionDescriptor.Setup(a => a.ActionName).Returns(\"test\");\n            mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0]));\n\n            Mock<HttpParameterDescriptor> mockParameterDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true };\n            Mock<HttpParameterBinding> mockParameterBinding = new Mock<HttpParameterBinding>(mockParameterDescriptor.Object) { CallBase = true };\n            HttpActionBinding actionBinding = new HttpActionBinding(mockActionDescriptor.Object, new HttpParameterBinding[] { mockParameterBinding.Object });\n\n            HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), \"controller\", typeof(ApiController));\n\n            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(request: new HttpRequestMessage());\n            controllerContext.ControllerDescriptor = controllerDescriptor;\n\n            Mock<IActionValueBinder> mockBinder = new Mock<IActionValueBinder>() { CallBase = true };\n            mockBinder.Setup(b => b.GetBinding(It.IsAny<HttpActionDescriptor>())).Returns(actionBinding);\n            ActionValueBinderTracer tracer = new ActionValueBinderTracer(mockBinder.Object, new TestTraceWriter());\n\n            // Act\n            HttpActionBinding actualBinding = ((IActionValueBinder)tracer).GetBinding(mockActionDescriptor.Object);\n\n            // Assert\n            Assert.IsType<HttpActionBindingTracer>(actualBinding);\n            Assert.Same(mockActionDescriptor.Object, actualBinding.ActionDescriptor);\n        }\n\n        [Fact]\n        public void GetBinding_Invokes_Inner_And_Returns_ActionBinder_With_Tracing_HttpParameterBinding()\n        {\n            // Arrange\n            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };\n            mockActionDescriptor.Setup(a => a.ActionName).Returns(\"test\");\n            mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0]));\n\n            Mock<HttpParameterDescriptor> mockParameterDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true };\n            Mock<HttpParameterBinding> mockParameterBinding = new Mock<HttpParameterBinding>(mockParameterDescriptor.Object) { CallBase = true };\n            HttpActionBinding actionBinding = new HttpActionBinding(mockActionDescriptor.Object, new HttpParameterBinding[] { mockParameterBinding.Object });\n\n            HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), \"controller\", typeof(ApiController));\n\n            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(request: new HttpRequestMessage());\n            controllerContext.ControllerDescriptor = controllerDescriptor;\n\n            Mock<IActionValueBinder> mockBinder = new Mock<IActionValueBinder>() { CallBase = true };\n            mockBinder.Setup(b => b.GetBinding(It.IsAny<HttpActionDescriptor>())).Returns(actionBinding);\n            ActionValueBinderTracer tracer = new ActionValueBinderTracer(mockBinder.Object, new TestTraceWriter());\n\n            // Act\n            HttpActionBinding actualBinding = ((IActionValueBinder)tracer).GetBinding(mockActionDescriptor.Object);\n\n            // Assert\n            Assert.IsAssignableFrom<HttpParameterBindingTracer>(actualBinding.ParameterBindings[0]);\n        }\n\n        [Fact]\n        public void GetBinding_Invokes_Inner_And_Returns_ActionBinder_With_Tracing_FormatterParameterBinding()\n        {\n            // Arrange\n            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };\n            mockActionDescriptor.Setup(a => a.ActionName).Returns(\"test\");\n            mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0]));\n\n            Mock<HttpParameterDescriptor> mockParameterDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true };\n            Mock<FormatterParameterBinding> mockParameterBinding = new Mock<FormatterParameterBinding>(mockParameterDescriptor.Object, new MediaTypeFormatterCollection(), null) { CallBase = true };\n            HttpActionBinding actionBinding = new HttpActionBinding(mockActionDescriptor.Object, new HttpParameterBinding[] { mockParameterBinding.Object });\n\n            HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), \"controller\", typeof(ApiController));\n\n            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(request: new HttpRequestMessage());\n            controllerContext.ControllerDescriptor = controllerDescriptor;\n\n            Mock<IActionValueBinder> mockBinder = new Mock<IActionValueBinder>() { CallBase = true };\n            mockBinder.Setup(b => b.GetBinding(It.IsAny<HttpActionDescriptor>())).Returns(actionBinding);\n            ActionValueBinderTracer tracer = new ActionValueBinderTracer(mockBinder.Object, new TestTraceWriter());\n\n            // Act\n            HttpActionBinding actualBinding = ((IActionValueBinder)tracer).GetBinding(mockActionDescriptor.Object);\n\n            // Assert\n            Assert.IsAssignableFrom<FormatterParameterBindingTracer>(actualBinding.ParameterBindings[0]);\n        }\n\n        [Fact]\n        public void GetBinding_DoesNotWrapHttpActionBindingTracer()\n        {\n            // Arrange\n            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };\n            Mock<HttpParameterDescriptor> mockParameterDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true };\n            Mock<FormatterParameterBinding> mockParameterBinding = new Mock<FormatterParameterBinding>(mockParameterDescriptor.Object, new MediaTypeFormatterCollection(), null) { CallBase = true };\n            HttpActionBinding actionBinding = new HttpActionBinding(mockActionDescriptor.Object, new HttpParameterBinding[] { mockParameterBinding.Object });\n\n            ITraceWriter traceWriter = new TestTraceWriter();\n            HttpActionBindingTracer actionBindingTracer = new HttpActionBindingTracer(actionBinding, traceWriter);\n            Mock<IActionValueBinder> mockBinder = new Mock<IActionValueBinder>() { CallBase = true };\n            mockBinder.Setup(b => b.GetBinding(It.IsAny<HttpActionDescriptor>())).Returns(actionBindingTracer);\n            ActionValueBinderTracer tracer = new ActionValueBinderTracer(mockBinder.Object, traceWriter);\n\n            // Act\n            HttpActionBinding actualBinding = ((IActionValueBinder)tracer).GetBinding(mockActionDescriptor.Object);\n\n            // Assert\n            Assert.Same(actionBindingTracer, actualBinding);\n        }\n\n        [Fact]\n        public void Inner_Property_On_ActionValueBinderTracer_Returns_IActionValueBinder()\n        {\n            // Arrange\n            IActionValueBinder expectedInner = new Mock<IActionValueBinder>().Object;\n            ActionValueBinderTracer productUnderTest = new ActionValueBinderTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            IActionValueBinder actualInner = productUnderTest.Inner;\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n\n        [Fact]\n        public void Decorator_GetInner_Property_On_ActionValueBinderTracer_Returns_IActionValueBinder()\n        {\n            // Arrange\n            IActionValueBinder expectedInner = new Mock<IActionValueBinder>().Object;\n            ActionValueBinderTracer productUnderTest = new ActionValueBinderTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            IActionValueBinder actualInner = Decorator.GetInner(productUnderTest as IActionValueBinder);\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/AuthenticationFilterTracerTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Filters;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class AuthenticationFilterTracerTests\n    {\n        [Fact]\n        public void Inner_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            IAuthenticationFilter expectedInner = CreateDummyFilter();\n            ITraceWriter tracer = CreateDummyTracer();\n            AuthenticationFilterTracer product = CreateProductUnderTest(expectedInner, tracer);\n\n            // Act\n            IAuthenticationFilter inner = product.Inner;\n\n            // Assert\n            Assert.Same(expectedInner, inner);\n        }\n\n        [Fact]\n        public async Task AuthenticateAsync_DelegatesToInnerFilter()\n        {\n            // Arrange\n            HttpAuthenticationContext expectedAuthenticationContext = CreateAuthenticationContext();\n            CancellationToken expectedCancellationToken = CreateCancellationToken();\n            Mock<IAuthenticationFilter> mock = new Mock<IAuthenticationFilter>();\n            int calls = 0;\n            mock.Setup(f => f.AuthenticateAsync(expectedAuthenticationContext, expectedCancellationToken)).Callback(\n                () => { calls++; }).Returns(() => Task.FromResult<object>(null));\n            IAuthenticationFilter filter = mock.Object;\n            ITraceWriter tracer = CreateStubTracer();\n            IAuthenticationFilter product = CreateProductUnderTest(filter, tracer);\n\n            // Act\n            await product.AuthenticateAsync(expectedAuthenticationContext, expectedCancellationToken);\n\n            // Assert\n            Assert.Equal(1, calls);\n        }\n\n        [Theory]\n        [ReplaceCulture]\n        [InlineData(true, \"The authentication filter successfully set a principal \"\n                        + \"to a known identity. Identity.Name='User'. \"\n                        + \"Identity.AuthenticationType='Basic'.\")]\n        [InlineData(false, \"The authentication filter set a principal to an unknown identity.\")]\n        public async Task AuthenticateAsync_Traces(bool withIdentity, string expectedMessage)\n        {\n            // Arrange\n            CancellationToken cancellationToken = CreateCancellationToken();\n            Mock<IAuthenticationFilter> filterMock = new Mock<IAuthenticationFilter>();\n            filterMock.Setup(f => f.AuthenticateAsync(It.IsAny<HttpAuthenticationContext>(),\n                                                      It.IsAny<CancellationToken>()))\n                .Callback((HttpAuthenticationContext context,\n                           CancellationToken token) => context.Principal = CreateDummyPrincipal(withIdentity))\n                .Returns(Task.FromResult<object>(null));\n            IAuthenticationFilter filter = filterMock.Object;\n            TraceRecord record = null;\n            ITraceWriter tracer = CreateTracer((r) => { record = r; });\n            IAuthenticationFilter product = CreateProductUnderTest(filter, tracer);\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                HttpAuthenticationContext authenticationContext = CreateAuthenticationContext(expectedRequest,\n                                                                                              isPrincipalSet: false);\n\n                // Act\n                await product.AuthenticateAsync(authenticationContext, cancellationToken);\n\n                // Assert\n                Assert.NotNull(record);\n                Assert.Same(expectedRequest, record.Request);\n                Assert.Same(TraceCategories.FiltersCategory, record.Category);\n                Assert.Equal(TraceLevel.Info, record.Level);\n                Assert.Equal(TraceKind.End, record.Kind);\n                Assert.Equal(filter.GetType().Name, record.Operator);\n                Assert.Equal(\"AuthenticateAsync\", record.Operation);\n                Assert.Null(record.Exception);\n                Assert.Equal(expectedMessage, record.Message);\n            }\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public async Task AuthenticateAsync_Traces_ErrorResult()\n        {\n            // Arrange\n            IHttpActionResult result = new AuthenticationFailureResult();\n            CancellationToken cancellationToken = CreateCancellationToken();\n            Mock<IAuthenticationFilter> filterMock = new Mock<IAuthenticationFilter>();\n            filterMock.Setup(f => f.AuthenticateAsync(It.IsAny<HttpAuthenticationContext>(),\n                                                      It.IsAny<CancellationToken>()))\n                .Callback((HttpAuthenticationContext context,\n                           CancellationToken token) => context.ErrorResult = result)\n                .Returns(Task.FromResult<object>(null));\n            TraceRecord record = null;\n            ITraceWriter tracer = CreateTracer((r) => { record = r; });\n            IAuthenticationFilter product = CreateProductUnderTest(filterMock.Object, tracer);\n            const string expectedMessage = \"The authentication filter encountered an error. ErrorResult=\"\n                + \"'System.Web.Http.Tracing.Tracers.AuthenticationFilterTracerTests+AuthenticationFailureResult'.\";\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                HttpAuthenticationContext authenticationContext = CreateAuthenticationContext(expectedRequest);\n\n                // Act\n                await product.AuthenticateAsync(authenticationContext, cancellationToken);\n\n                // Assert\n                Assert.NotNull(record);\n                Assert.Same(expectedRequest, record.Request);\n                Assert.Same(TraceCategories.FiltersCategory, record.Category);\n                Assert.Equal(TraceLevel.Info, record.Level);\n                Assert.Equal(TraceKind.End, record.Kind);\n                Assert.Equal(filterMock.Object.GetType().Name, record.Operator);\n                Assert.Equal(\"AuthenticateAsync\", record.Operation);\n                Assert.Null(record.Exception);\n                Assert.Equal(expectedMessage, record.Message);\n            }\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public async Task AuthenticateAsync_Traces_DidNothing()\n        {\n            // Arrange\n            CancellationToken cancellationToken = CreateCancellationToken();\n            IAuthenticationFilter filter = CreateStubFilter();\n            TraceRecord record = null;\n            ITraceWriter tracer = CreateTracer((r) => { record = r; });\n            IAuthenticationFilter product = CreateProductUnderTest(filter, tracer);\n            const string expectedMessage = \"The authentication filter did not encounter an error or set a principal.\";\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                HttpAuthenticationContext authenticationContext = CreateAuthenticationContext(expectedRequest);\n\n                // Act\n                await product.AuthenticateAsync(authenticationContext, cancellationToken);\n\n                // Assert\n                Assert.NotNull(record);\n                Assert.Same(expectedRequest, record.Request);\n                Assert.Same(TraceCategories.FiltersCategory, record.Category);\n                Assert.Equal(TraceLevel.Info, record.Level);\n                Assert.Equal(TraceKind.End, record.Kind);\n                Assert.Equal(filter.GetType().Name, record.Operator);\n                Assert.Equal(\"AuthenticateAsync\", record.Operation);\n                Assert.Null(record.Exception);\n                Assert.Equal(expectedMessage, record.Message);\n            }\n        }\n\n        [Fact]\n        public async Task AuthenticateAsync_Traces_WhenContextIsNull()\n        {\n            // Arrange\n            CancellationToken cancellationToken = CreateCancellationToken();\n            IAuthenticationFilter filter = CreateStubFilter();\n            TraceRecord record = null;\n            ITraceWriter tracer = CreateTracer((r) => { record = r; });\n            IAuthenticationFilter product = CreateProductUnderTest(filter, tracer);\n            HttpAuthenticationContext authenticationContext = null;\n\n            // Act\n            await product.AuthenticateAsync(authenticationContext, cancellationToken);\n\n            // Assert\n            Assert.NotNull(record);\n            Assert.Null(record.Request);\n        }\n\n        [Fact]\n        public async Task ChallengeAsync_DelegatesToInnerFilter()\n        {\n            // Arrange\n            HttpAuthenticationChallengeContext expectedChallengeContext = CreateChallengeContext();\n            CancellationToken expectedCancellationToken = CreateCancellationToken();\n            IHttpActionResult expectedInnerResult = CreateDummyActionResult();\n            IHttpActionResult expectedResult = CreateDummyActionResult();\n            Mock<IAuthenticationFilter> mock = new Mock<IAuthenticationFilter>();\n            int calls = 0;\n            mock.Setup(f => f.ChallengeAsync(expectedChallengeContext, expectedCancellationToken))\n                .Callback(() => { calls++; })\n                .Returns(() => Task.FromResult(expectedResult));\n            IAuthenticationFilter filter = mock.Object;\n            ITraceWriter tracer = CreateStubTracer();\n            IAuthenticationFilter product = CreateProductUnderTest(filter, tracer);\n\n            // Act\n            await product.ChallengeAsync(expectedChallengeContext, expectedCancellationToken);\n\n            // Assert\n            Assert.Equal(1, calls);\n        }\n\n        [Fact]\n        public async Task ChallengeAsync_Traces()\n        {\n            // Arrange\n            CancellationToken cancellationToken = CreateCancellationToken();\n            IAuthenticationFilter filter = CreateStubFilter();\n            TraceRecord record = null;\n            ITraceWriter tracer = CreateTracer((r) => { record = r; });\n            IAuthenticationFilter product = CreateProductUnderTest(filter, tracer);\n            IHttpActionResult innerResult = CreateDummyActionResult();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                HttpAuthenticationChallengeContext context = CreateChallengeContext(expectedRequest, innerResult);\n\n                // Act\n                await product.ChallengeAsync(context, cancellationToken);\n\n                // Assert\n                Assert.NotNull(record);\n                Assert.Same(expectedRequest, record.Request);\n                Assert.Same(TraceCategories.FiltersCategory, record.Category);\n                Assert.Equal(TraceLevel.Info, record.Level);\n                Assert.Equal(TraceKind.End, record.Kind);\n                Assert.Equal(filter.GetType().Name, record.Operator);\n                Assert.Equal(\"ChallengeAsync\", record.Operation);\n                Assert.Null(record.Exception);\n                Assert.Null(record.Message);\n            }\n        }\n\n        [Fact]\n        public async Task ChallengeAsync_Traces_WhenContextIsNull()\n        {\n            // Arrange\n            CancellationToken cancellationToken = CreateCancellationToken();\n            IAuthenticationFilter filter = CreateStubFilter();\n            TraceRecord record = null;\n            ITraceWriter tracer = CreateTracer((r) => { record = r; });\n            IAuthenticationFilter product = CreateProductUnderTest(filter, tracer);\n            HttpAuthenticationChallengeContext context = null;\n\n            // Act\n            await product.ChallengeAsync(context, cancellationToken);\n\n            // Assert\n            Assert.NotNull(record);\n            Assert.Null(record.Request);\n        }\n\n        private static HttpActionContext CreateActionContext()\n        {\n            return new HttpActionContext();\n        }\n\n        private static HttpActionContext CreateActionContext(HttpRequestMessage request)\n        {\n            HttpControllerContext controllerContext = new HttpControllerContext();\n            controllerContext.Request = request;\n            HttpActionContext actionContext = new HttpActionContext();\n            actionContext.ControllerContext = controllerContext;\n            return actionContext;\n        }\n\n        private static HttpAuthenticationContext CreateAuthenticationContext()\n        {\n            HttpActionContext actionContext = CreateActionContext();\n            IPrincipal principal = CreateDummyPrincipal();\n            return new HttpAuthenticationContext(actionContext, principal);\n        }\n\n        private static HttpAuthenticationContext CreateAuthenticationContext(HttpRequestMessage request,\n                                                                             bool isPrincipalSet = true)\n        {\n            HttpActionContext actionContext = CreateActionContext(request);\n            IPrincipal principal = (isPrincipalSet) ? CreateDummyPrincipal() : null;\n            return new HttpAuthenticationContext(actionContext, principal);\n        }\n\n        private static CancellationToken CreateCancellationToken()\n        {\n            return new CancellationToken(canceled: true);\n        }\n\n        private static HttpAuthenticationChallengeContext CreateChallengeContext()\n        {\n            HttpActionContext actionContext = CreateActionContext();\n            IHttpActionResult result = CreateDummyResult();\n            return new HttpAuthenticationChallengeContext(actionContext, result);\n        }\n\n        private static HttpAuthenticationChallengeContext CreateChallengeContext(HttpRequestMessage request,\n            IHttpActionResult result)\n        {\n            HttpActionContext actionContext = CreateActionContext(request);\n            return new HttpAuthenticationChallengeContext(actionContext, result);\n        }\n\n        private IHttpActionResult CreateDummyActionResult()\n        {\n            return new Mock<IHttpActionResult>(MockBehavior.Strict).Object;\n        }\n\n        private static IAuthenticationFilter CreateDummyFilter()\n        {\n            return new Mock<IAuthenticationFilter>(MockBehavior.Strict).Object;\n        }\n\n        private static IPrincipal CreateDummyPrincipal(bool withIdentity = true)\n        {\n            var principalMock = new Mock<IPrincipal>(MockBehavior.Strict);\n            if (withIdentity)\n            {\n                principalMock.Setup(p => p.Identity.Name).Returns(\"User\");\n                principalMock.Setup(p => p.Identity.AuthenticationType).Returns(\"Basic\");\n            }\n            else\n            {\n                principalMock.Setup(p => p.Identity).Returns((IIdentity)null);\n            }\n            return principalMock.Object;\n        }\n\n        private static IHttpActionResult CreateDummyResult()\n        {\n            return new Mock<IHttpActionResult>(MockBehavior.Strict).Object;\n        }\n\n        private static ITraceWriter CreateDummyTracer()\n        {\n            return new Mock<ITraceWriter>(MockBehavior.Strict).Object;\n        }\n\n        private static AuthenticationFilterTracer CreateProductUnderTest(IAuthenticationFilter innerFilter,\n            ITraceWriter traceWriter)\n        {\n            return new AuthenticationFilterTracer(innerFilter, traceWriter);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private static IAuthenticationFilter CreateStubFilter()\n        {\n            Mock<IAuthenticationFilter> mock = new Mock<IAuthenticationFilter>();\n            mock.Setup(f => f.AuthenticateAsync(It.IsAny<HttpAuthenticationContext>(), It.IsAny<CancellationToken>()))\n                .Returns(Task.FromResult<object>(null));\n            mock.Setup(f => f.ChallengeAsync(It.IsAny<HttpAuthenticationChallengeContext>(),\n                It.IsAny<CancellationToken>()))\n                .Returns(Task.FromResult<object>(null));\n            return mock.Object;\n        }\n\n        private static ITraceWriter CreateStubTracer()\n        {\n            return new Mock<ITraceWriter>().Object;\n        }\n\n        private static ITraceWriter CreateTracer(Action<TraceRecord> trace)\n        {\n            Mock<ITraceWriter> mock = new Mock<ITraceWriter>(MockBehavior.Strict);\n            TraceRecord record = null;\n            mock.Setup(t => t.Trace(It.IsAny<HttpRequestMessage>(), It.IsAny<string>(), It.IsAny<TraceLevel>(),\n                It.IsAny<Action<TraceRecord>>()))\n                .Callback<HttpRequestMessage, string, TraceLevel, Action<TraceRecord>>((r, c, l, a) =>\n                    {\n                        record = new TraceRecord(r, c, l);\n                        a.Invoke(record);\n                        trace.Invoke(record);\n                    });\n            return mock.Object;\n        }\n\n        private class AuthenticationFailureResult : IHttpActionResult\n        {\n            public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/AuthorizationFilterAttributeTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Services;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class AuthorizationFilterAttributeTracerTest\n    {\n        [Fact]\n        public void Equals_Calls_Inner()\n        {\n            // Arrange\n            object randomObject = new Object();\n            Mock<AuthorizationFilterAttribute> mockAttribute = new Mock<AuthorizationFilterAttribute>();\n            mockAttribute.Setup(a => a.Equals(randomObject)).Returns(true).Verifiable();\n            AuthorizationFilterAttributeTracer tracer = new AuthorizationFilterAttributeTracer(mockAttribute.Object, new TestTraceWriter());\n\n            // Act\n            bool valueReturned = tracer.Equals(randomObject);\n\n            // Assert\n            Assert.True(valueReturned);\n            mockAttribute.Verify();\n        }\n\n        [Fact]\n        public void GetHashCode_Calls_Inner()\n        {\n            // Arrange\n            Mock<AuthorizationFilterAttribute> mockAttribute = new Mock<AuthorizationFilterAttribute>();\n            mockAttribute.Setup(a => a.GetHashCode()).Returns(1).Verifiable();\n            AuthorizationFilterAttributeTracer tracer = new AuthorizationFilterAttributeTracer(mockAttribute.Object, new TestTraceWriter());\n\n            // Act\n            int valueReturned = tracer.GetHashCode();\n\n            // Assert\n            Assert.Equal(1, valueReturned);\n            mockAttribute.Verify();\n        }\n\n        [Fact]\n        public void IsDefaultAttribute_Calls_Inner()\n        {\n            // Arrange\n            Mock<AuthorizationFilterAttribute> mockAttribute = new Mock<AuthorizationFilterAttribute>();\n            mockAttribute.Setup(a => a.IsDefaultAttribute()).Returns(true).Verifiable();\n            AuthorizationFilterAttributeTracer tracer = new AuthorizationFilterAttributeTracer(mockAttribute.Object, new TestTraceWriter());\n\n            // Act\n            bool valueReturned = tracer.IsDefaultAttribute();\n\n            // Assert\n            Assert.True(valueReturned);\n            mockAttribute.Verify();\n        }\n\n        [Fact]\n        public void Match_Calls_Inner()\n        {\n            // Arrange\n            object randomObject = new Object();\n            Mock<AuthorizationFilterAttribute> mockAttribute = new Mock<AuthorizationFilterAttribute>();\n            mockAttribute.Setup(a => a.Match(randomObject)).Returns(true).Verifiable();\n            AuthorizationFilterAttributeTracer tracer = new AuthorizationFilterAttributeTracer(mockAttribute.Object, new TestTraceWriter());\n\n            // Act\n            bool valueReturned = tracer.Match(randomObject);\n\n            // Assert\n            Assert.True(valueReturned);\n            mockAttribute.Verify();\n        }\n\n        [Fact]\n        public void TypeId_Calls_Inner()\n        {\n            // Arrange\n            object randomObject = new Object();\n            Mock<AuthorizationFilterAttribute> mockAttribute = new Mock<AuthorizationFilterAttribute>();\n            mockAttribute.Setup(a => a.TypeId).Returns(randomObject).Verifiable();\n            AuthorizationFilterAttributeTracer tracer = new AuthorizationFilterAttributeTracer(mockAttribute.Object, new TestTraceWriter());\n\n            // Act\n            object valueReturned = tracer.TypeId;\n\n            // Assert\n            Assert.Same(randomObject, valueReturned);\n            mockAttribute.Verify();\n        }\n\n        [Fact]\n        public void AllowMultiple_Calls_Inner()\n        {\n            // Arrange\n            Mock<AuthorizationFilterAttribute> mockAttribute = new Mock<AuthorizationFilterAttribute>();\n            mockAttribute.Setup(a => a.AllowMultiple).Returns(true).Verifiable();\n            AuthorizationFilterAttributeTracer tracer = new AuthorizationFilterAttributeTracer(mockAttribute.Object, new TestTraceWriter());\n\n            // Act\n            bool valueReturned = tracer.AllowMultiple;\n\n            // Assert\n            Assert.True(valueReturned);\n            mockAttribute.Verify();\n        }\n\n        [Fact]\n        public async Task ExecuteAuthorizationFilterAsync_Traces()\n        {\n            // Arrange\n            Mock<AuthorizationFilterAttribute> mockAttr = new Mock<AuthorizationFilterAttribute>() { CallBase = true };\n            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };\n            mockActionDescriptor.Setup(a => a.ActionName).Returns(\"test\");\n            mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0]));\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(actionDescriptor: mockActionDescriptor.Object);\n            Func<Task<HttpResponseMessage>> continuation = () => Task.FromResult<HttpResponseMessage>(new HttpResponseMessage());\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            AuthorizationFilterAttributeTracer tracer = new AuthorizationFilterAttributeTracer(mockAttr.Object, traceWriter);\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"OnAuthorizationAsync\" },\n                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.End,  Operation = \"OnAuthorizationAsync\" },\n            };\n\n            // Act\n            var filter = (IAuthorizationFilter)tracer;\n            await filter.ExecuteAuthorizationFilterAsync(actionContext, CancellationToken.None, continuation);\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public async Task ExecuteAuthorizationFilterAsync_Throws_And_Traces_When_Inner_OnException_Throws()\n        {\n            // Arrange\n            Mock<AuthorizationFilterAttribute> mockAttr = new Mock<AuthorizationFilterAttribute>() { CallBase = true };\n            InvalidOperationException exception = new InvalidOperationException(\"test\");\n            mockAttr.Setup(a => a.OnAuthorization(It.IsAny<HttpActionContext>())).Throws(exception);\n            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };\n            mockActionDescriptor.Setup(a => a.ActionName).Returns(\"test\");\n            mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0]));\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(actionDescriptor: mockActionDescriptor.Object);\n            Func<Task<HttpResponseMessage>> continuation = () => Task.FromResult<HttpResponseMessage>(new HttpResponseMessage());\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            AuthorizationFilterAttributeTracer tracer = new AuthorizationFilterAttributeTracer(mockAttr.Object, traceWriter);\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"OnAuthorizationAsync\" },\n                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Error) { Kind = TraceKind.End,  Operation = \"OnAuthorizationAsync\" }\n            };\n\n            // Act\n            Exception thrown =\n                await Assert.ThrowsAsync<InvalidOperationException>(\n                    () => ((IAuthorizationFilter)tracer).ExecuteAuthorizationFilterAsync(actionContext, CancellationToken.None, continuation));\n\n            // Assert\n            Assert.Same(exception, thrown);\n            Assert.Same(exception, traceWriter.Traces[1].Exception);\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void Inner_Property_On_AuthorizationFilterAttributeTracer_Returns_AuthorizationFilterAttribute()\n        {\n            // Arrange\n            AuthorizationFilterAttribute expectedInner = new Mock<AuthorizationFilterAttribute>().Object;\n            AuthorizationFilterAttributeTracer productUnderTest = new AuthorizationFilterAttributeTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            AuthorizationFilterAttribute actualInner = productUnderTest.Inner;\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n\n        [Fact]\n        public void Decorator_GetInner_On_AuthorizationFilterAttributeTracer_Returns_AuthorizationFilterAttribute()\n        {\n            // Arrange\n            AuthorizationFilterAttribute expectedInner = new Mock<AuthorizationFilterAttribute>().Object;\n            AuthorizationFilterAttributeTracer productUnderTest = new AuthorizationFilterAttributeTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            AuthorizationFilterAttribute actualInner = Decorator.GetInner(productUnderTest as AuthorizationFilterAttribute);\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/AuthorizationFilterTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Services;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class AuthorizationFilterTracerTest\n    {\n        [Fact]\n        public async Task ExecuteAuthorizationFilterAsync_Traces()\n        {\n            // Arrange\n            HttpResponseMessage response = new HttpResponseMessage();\n            Mock<IAuthorizationFilter> mockFilter = new Mock<IAuthorizationFilter>() { CallBase = true };\n            mockFilter.Setup(f => f.ExecuteAuthorizationFilterAsync(It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>(), It.IsAny<Func<Task<HttpResponseMessage>>>())).Returns(Task.FromResult(response));\n            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };\n            mockActionDescriptor.Setup(a => a.ActionName).Returns(\"test\");\n            mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0]));\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(actionDescriptor: mockActionDescriptor.Object);\n            Func<Task<HttpResponseMessage>> continuation = () => Task.FromResult<HttpResponseMessage>(new HttpResponseMessage());\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            AuthorizationFilterTracer tracer = new AuthorizationFilterTracer(mockFilter.Object, traceWriter);\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"ExecuteAuthorizationFilterAsync\" },\n                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.End,  Operation = \"ExecuteAuthorizationFilterAsync\" },\n            };\n\n            // Act\n            var filter = (IAuthorizationFilter)tracer;\n            await filter.ExecuteAuthorizationFilterAsync(actionContext, CancellationToken.None, continuation);\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public async Task ExecuteAuthorizationFilterAsync_Faults_And_Traces_When_Inner_Faults()\n        {\n            // Arrange\n            Mock<IAuthorizationFilter> mockAttr = new Mock<IAuthorizationFilter>() { CallBase = true };\n            HttpResponseMessage response = new HttpResponseMessage();\n            InvalidOperationException exception = new InvalidOperationException(\"test\");\n            TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>(response);\n            tcs.TrySetException(exception);\n            mockAttr.Setup(a => a.ExecuteAuthorizationFilterAsync(It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>(), It.IsAny<Func<Task<HttpResponseMessage>>>())).Returns(tcs.Task);\n            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };\n            mockActionDescriptor.Setup(a => a.ActionName).Returns(\"test\");\n            mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0]));\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(actionDescriptor: mockActionDescriptor.Object);\n            Func<Task<HttpResponseMessage>> continuation = () => Task.FromResult<HttpResponseMessage>(response);\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            AuthorizationFilterTracer tracer = new AuthorizationFilterTracer(mockAttr.Object, traceWriter);\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"ExecuteAuthorizationFilterAsync\" },\n                new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Error) { Kind = TraceKind.End,  Operation = \"ExecuteAuthorizationFilterAsync\" }\n            };\n\n            // Act & Assert\n            Task task = ((IAuthorizationFilter)tracer).ExecuteAuthorizationFilterAsync(actionContext, CancellationToken.None, continuation);\n            Exception thrown = await Assert.ThrowsAsync<InvalidOperationException>(() => task);\n\n            // Assert\n            Assert.Same(exception, thrown);\n            Assert.Same(exception, traceWriter.Traces[1].Exception);\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void Inner_Property_On_AuthorizationFilterTracer_Returns_IAuthorizationFilter()\n        {\n            // Arrange\n            IAuthorizationFilter expectedInner = new Mock<IAuthorizationFilter>().Object;\n            AuthorizationFilterTracer productUnderTest = new AuthorizationFilterTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            IAuthorizationFilter actualInner = productUnderTest.Inner as IAuthorizationFilter;\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n\n        [Fact]\n        public void Decorator_GetInner_On_AuthorizationFilterTracer_Returns_IAuthorizationFilter()\n        {\n            // Arrange\n            IAuthorizationFilter expectedInner = new Mock<IAuthorizationFilter>().Object;\n            AuthorizationFilterTracer productUnderTest = new AuthorizationFilterTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            IAuthorizationFilter actualInner = Decorator.GetInner(productUnderTest as IAuthorizationFilter);\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/BufferedMediaTypeFormatterTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Threading;\nusing System.Web.Http.Services;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class BufferedMediaTypeFormatterTracerTest : MediaTypeFormatterTracerTestBase<BufferedMediaTypeFormatter>\n    {\n        public override MediaTypeFormatter CreateTracer(BufferedMediaTypeFormatter formatter, HttpRequestMessage request, ITraceWriter traceWriter)\n        {\n            return new BufferedMediaTypeFormatterTracer(formatter, traceWriter, request);\n        }\n\n        [Fact]\n        public void BufferSize_Uses_Inners()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            Mock<BufferedMediaTypeFormatter> mockFormatter = new Mock<BufferedMediaTypeFormatter>() { CallBase = true };\n            BufferedMediaTypeFormatter innerFormatter = mockFormatter.Object;\n            innerFormatter.BufferSize = innerFormatter.BufferSize + 1;\n            BufferedMediaTypeFormatterTracer tracer = new BufferedMediaTypeFormatterTracer(innerFormatter, new TestTraceWriter(), request);\n\n            // Act & Assert\n            Assert.Equal(innerFormatter.BufferSize, tracer.BufferSize);\n        }\n\n        [Fact]\n        public void ReadFromStream_Traces()\n        {\n            // Arrange\n            Mock<BufferedMediaTypeFormatter> mockFormatter = new Mock<BufferedMediaTypeFormatter>() { CallBase = true };\n            mockFormatter.Setup(f => f.ReadFromStream(It.IsAny<Type>(), It.IsAny<Stream>(), It.IsAny<HttpContent>(), It.IsAny<IFormatterLogger>()))\n                .Returns(\"sampleValue\");\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.Content = new StringContent(\"\");\n            BufferedMediaTypeFormatterTracer tracer = new BufferedMediaTypeFormatterTracer(mockFormatter.Object, traceWriter, request);\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"ReadFromStream\" },\n                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = \"ReadFromStream\" }\n            };\n\n            // Act\n            string valueReturned = tracer.ReadFromStream(typeof(string), new MemoryStream(), request.Content, null) as string;\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Equal(\"sampleValue\", valueReturned);\n        }\n\n        [Fact]\n        public void ReadFromStreamWithCancellationToken_Traces()\n        {\n            // Arrange\n            Mock<BufferedMediaTypeFormatter> mockFormatter = new Mock<BufferedMediaTypeFormatter>() { CallBase = true };\n            mockFormatter.Setup(f => f.ReadFromStream(It.IsAny<Type>(), It.IsAny<Stream>(), It.IsAny<HttpContent>(), It.IsAny<IFormatterLogger>()))\n                .Returns(\"sampleValue\");\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.Content = new StringContent(\"\");\n            BufferedMediaTypeFormatterTracer tracer = new BufferedMediaTypeFormatterTracer(mockFormatter.Object, traceWriter, request);\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"ReadFromStream\" },\n                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = \"ReadFromStream\" }\n            };\n\n            // Act\n            string valueReturned = tracer.ReadFromStream(typeof(string), new MemoryStream(), request.Content, null, CancellationToken.None) as string;\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Equal(\"sampleValue\", valueReturned);\n        }\n\n        [Fact]\n        public void ReadFromStream_Traces_And_Throws_When_Inner_Throws()\n        {\n            // Arrange\n            InvalidOperationException exception = new InvalidOperationException(\"test\");\n            Mock<BufferedMediaTypeFormatter> mockFormatter = new Mock<BufferedMediaTypeFormatter>() { CallBase = true };\n            mockFormatter.Setup(\n                f => f.ReadFromStream(It.IsAny<Type>(), It.IsAny<Stream>(), It.IsAny<HttpContent>(), It.IsAny<IFormatterLogger>())).Throws(exception);\n\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.Content = new StringContent(\"\");\n            BufferedMediaTypeFormatterTracer tracer = new BufferedMediaTypeFormatterTracer(mockFormatter.Object, traceWriter, request);\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"ReadFromStream\" },\n                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = \"ReadFromStream\" }\n            };\n\n            // Act\n            Exception thrown = Assert.Throws<InvalidOperationException>(() => tracer.ReadFromStream(typeof(string), new MemoryStream(), request.Content, null));\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(exception, thrown);\n            Assert.Same(exception, traceWriter.Traces[1].Exception);\n        }\n\n        [Fact]\n        public void WriteToStream_Traces()\n        {\n            // Arrange\n            Mock<BufferedMediaTypeFormatter> mockFormatter = new Mock<BufferedMediaTypeFormatter>() { CallBase = true };\n            mockFormatter.Setup(\n                f => f.WriteToStream(It.IsAny<Type>(), It.IsAny<Object>(), It.IsAny<Stream>(), It.IsAny<HttpContent>()));\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.Content = new StringContent(\"\");\n            BufferedMediaTypeFormatterTracer tracer = new BufferedMediaTypeFormatterTracer(mockFormatter.Object, traceWriter, request);\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"WriteToStream\" },\n                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = \"WriteToStream\" }\n            };\n\n            // Act\n            tracer.WriteToStream(typeof(string), \"sampleValue\", new MemoryStream(), request.Content);\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void WriteToStreamWithCancellationToken_Traces()\n        {\n            // Arrange\n            Mock<BufferedMediaTypeFormatter> mockFormatter = new Mock<BufferedMediaTypeFormatter>() { CallBase = true };\n            mockFormatter.Setup(\n                f => f.WriteToStream(It.IsAny<Type>(), It.IsAny<Object>(), It.IsAny<Stream>(), It.IsAny<HttpContent>()));\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.Content = new StringContent(\"\");\n            BufferedMediaTypeFormatterTracer tracer = new BufferedMediaTypeFormatterTracer(mockFormatter.Object, traceWriter, request);\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"WriteToStream\" },\n                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = \"WriteToStream\" }\n            };\n\n            // Act\n            tracer.WriteToStream(typeof(string), \"sampleValue\", new MemoryStream(), request.Content, CancellationToken.None);\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void WriteToStream_Traces_And_Throws_When_Inner_Throws()\n        {\n            // Arrange\n            InvalidOperationException exception = new InvalidOperationException(\"test\");\n            Mock<BufferedMediaTypeFormatter> mockFormatter = new Mock<BufferedMediaTypeFormatter>() { CallBase = true };\n            mockFormatter.Setup(f => f.WriteToStream(It.IsAny<Type>(), It.IsAny<Object>(), It.IsAny<Stream>(),\n                                                     It.IsAny<HttpContent>()))\n                         .Throws(exception);\n\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.Content = new StringContent(\"\");\n            BufferedMediaTypeFormatterTracer tracer = new BufferedMediaTypeFormatterTracer(mockFormatter.Object, traceWriter, request);\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"WriteToStream\" },\n                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = \"WriteToStream\" }\n            };\n\n            // Act\n            Exception thrown = Assert.Throws<InvalidOperationException>(() => tracer.WriteToStream(typeof(string), \"sampleValue\", new MemoryStream(), request.Content));\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(exception, thrown);\n            Assert.Same(exception, traceWriter.Traces[1].Exception);\n        }\n\n        [Fact]\n        public void Inner_Property_On_BufferedMediaTypeFormatterTracer_Returns_BufferedMediaTypeFormatter()\n        {\n            // Arrange\n            BufferedMediaTypeFormatter expectedInner = new Mock<BufferedMediaTypeFormatter>().Object;\n            BufferedMediaTypeFormatterTracer productUnderTest = new BufferedMediaTypeFormatterTracer(expectedInner, new TestTraceWriter(), new HttpRequestMessage());\n\n            // Act\n            BufferedMediaTypeFormatter actualInner = productUnderTest.Inner;\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n\n        [Fact]\n        public void Decorator_GetInner_On_BufferedMediaTypeFormatterTracer_Returns_BufferedMediaTypeFormatter()\n        {\n            // Arrange\n            BufferedMediaTypeFormatter expectedInner = new Mock<BufferedMediaTypeFormatter>().Object;\n            BufferedMediaTypeFormatterTracer productUnderTest = new BufferedMediaTypeFormatterTracer(expectedInner, new TestTraceWriter(), new HttpRequestMessage());\n\n            // Act\n            BufferedMediaTypeFormatter actualInner = Decorator.GetInner(productUnderTest as BufferedMediaTypeFormatter);\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/ContentNegotiatorTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Web.Http.Services;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class ContentNegotiatorTracerTest\n    {\n        private readonly HttpRequestMessage _request = new HttpRequestMessage();\n        private readonly Mock<IContentNegotiator> _mockNegotiator = new Mock<IContentNegotiator>();\n        private readonly ContentNegotiatorTracer _tracer;\n        private readonly TestTraceWriter _traceWriter = new TestTraceWriter();\n\n        public ContentNegotiatorTracerTest()\n        {\n            _tracer = new ContentNegotiatorTracer(_mockNegotiator.Object, _traceWriter);\n        }\n\n        [Fact]\n        public void Negotiate_Calls_Inner_Negotiate()\n        {\n            // Act\n            ((IContentNegotiator)_tracer).Negotiate(typeof(int), _request, new MediaTypeFormatter[0]);\n\n            // Assert\n            _mockNegotiator.Verify(\n                n =>\n                n.Negotiate(It.IsAny<Type>(), It.IsAny<HttpRequestMessage>(),\n                            It.IsAny<IEnumerable<MediaTypeFormatter>>()), Times.Once());\n        }\n\n        [Fact]\n        public void Negotiate_Returns_Inner_MediaType()\n        {\n            // Arrange\n            MediaTypeHeaderValue expectedMediaType = new MediaTypeHeaderValue(\"application/xml\");\n            _mockNegotiator.Setup(\n                n =>\n                n.Negotiate(It.IsAny<Type>(), It.IsAny<HttpRequestMessage>(),\n                            It.IsAny<IEnumerable<MediaTypeFormatter>>())).Returns(\n                                new ContentNegotiationResult(new JsonMediaTypeFormatter(), expectedMediaType));\n\n            // Act\n            var result = ((IContentNegotiator)_tracer).Negotiate(typeof(int), _request, new MediaTypeFormatter[0]);\n\n            // Assert\n            Assert.Same(expectedMediaType, result.MediaType);\n        }\n\n        [Fact]\n        public void Negotiate_Returns_Wrapped_Inner_XmlFormatter()\n        {\n            // Arrange\n            MediaTypeFormatter expectedFormatter = new XmlMediaTypeFormatter();\n            _mockNegotiator.Setup(\n                n =>\n                n.Negotiate(It.IsAny<Type>(), It.IsAny<HttpRequestMessage>(),\n                            It.IsAny<IEnumerable<MediaTypeFormatter>>())).Returns(\n                                new ContentNegotiationResult(expectedFormatter, null));\n\n            // Act\n            var result = ((IContentNegotiator)_tracer).Negotiate(typeof(int), _request, new MediaTypeFormatter[0]);\n\n            // Assert\n            Assert.IsType<XmlMediaTypeFormatterTracer>(result.Formatter);\n        }\n\n        [Fact]\n        public void Negotiate_Returns_Wrapped_Inner_JsonFormatter()\n        {\n            // Arrange\n            MediaTypeFormatter expectedFormatter = new JsonMediaTypeFormatter();\n            _mockNegotiator.Setup(\n                n =>\n                n.Negotiate(It.IsAny<Type>(), It.IsAny<HttpRequestMessage>(),\n                            It.IsAny<IEnumerable<MediaTypeFormatter>>())).Returns(\n                                new ContentNegotiationResult(expectedFormatter, null));\n\n            // Act\n            var result = ((IContentNegotiator)_tracer).Negotiate(typeof(int), _request, new MediaTypeFormatter[0]);\n\n            // Assert\n            Assert.IsType<JsonMediaTypeFormatterTracer>(result.Formatter);\n        }\n\n        [Fact]\n        public void Negotiate_Returns_Wrapped_Inner_FormUrlEncodedFormatter()\n        {\n            // Arrange\n            MediaTypeFormatter expectedFormatter = new FormUrlEncodedMediaTypeFormatter();\n            _mockNegotiator.Setup(\n                n =>\n                n.Negotiate(It.IsAny<Type>(), It.IsAny<HttpRequestMessage>(),\n                            It.IsAny<IEnumerable<MediaTypeFormatter>>())).Returns(\n                                new ContentNegotiationResult(expectedFormatter, null));\n\n            // Act\n            var result = ((IContentNegotiator)_tracer).Negotiate(typeof(int), _request, new MediaTypeFormatter[0]);\n\n            // Assert\n            Assert.IsType<FormUrlEncodedMediaTypeFormatterTracer>(result.Formatter);\n        }\n\n        [Fact]\n        public void Negotiate_Returns_Null_Inner_Formatter()\n        {\n            // Arrange\n            _mockNegotiator.Setup(\n                n =>\n                n.Negotiate(It.IsAny<Type>(), It.IsAny<HttpRequestMessage>(),\n                            It.IsAny<IEnumerable<MediaTypeFormatter>>())).Returns(\n                                value: null);\n\n            // Act\n            var result = ((IContentNegotiator)_tracer).Negotiate(typeof(int), _request, new MediaTypeFormatter[0]);\n\n            // Assert\n            Assert.Null(result);\n        }\n\n        [Fact]\n        public void Negotiate_Traces_BeginEnd()\n        {\n            // Arrange\n            MediaTypeFormatter expectedFormatter = new XmlMediaTypeFormatter();\n            _mockNegotiator.Setup(\n                n =>\n                n.Negotiate(It.IsAny<Type>(), It.IsAny<HttpRequestMessage>(),\n                            It.IsAny<IEnumerable<MediaTypeFormatter>>())).Returns(\n                                new ContentNegotiationResult(expectedFormatter, null));\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(_request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin },\n                new TraceRecord(_request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.End }\n            };\n\n            // Act\n            ((IContentNegotiator)_tracer).Negotiate(typeof(int), _request, new MediaTypeFormatter[0]);\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, _traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void Negotiate_Throws_When_Inner_Throws()\n        {\n            // Arrange\n            MediaTypeFormatter expectedFormatter = new XmlMediaTypeFormatter();\n            InvalidOperationException expectedException = new InvalidOperationException(\"test\");\n            _mockNegotiator.Setup(\n                n =>\n                n.Negotiate(It.IsAny<Type>(), It.IsAny<HttpRequestMessage>(),\n                            It.IsAny<IEnumerable<MediaTypeFormatter>>())).Throws(expectedException);\n\n            // Act & Assert\n            InvalidOperationException actualException = Assert.Throws<InvalidOperationException>(() => ((IContentNegotiator)_tracer).Negotiate(typeof(int), _request, new MediaTypeFormatter[0]));\n\n            // Assert\n            Assert.Same(expectedException, actualException);\n        }\n\n        [Fact]\n        public void Negotiate_Traces_BeginEnd_When_Inner_Throws()\n        {\n            // Arrange\n            MediaTypeFormatter expectedFormatter = new XmlMediaTypeFormatter();\n            InvalidOperationException expectedException = new InvalidOperationException(\"test\");\n            _mockNegotiator.Setup(\n                n =>\n                n.Negotiate(It.IsAny<Type>(), It.IsAny<HttpRequestMessage>(),\n                            It.IsAny<IEnumerable<MediaTypeFormatter>>())).Throws(expectedException);\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(_request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin },\n                new TraceRecord(_request, TraceCategories.FormattingCategory, TraceLevel.Error) { Kind = TraceKind.End }\n            };\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(() => ((IContentNegotiator)_tracer).Negotiate(typeof(int), _request, new MediaTypeFormatter[0]));\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, _traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(expectedException, _traceWriter.Traces[1].Exception);\n        }\n\n        [Fact]\n        public void Inner_Property_On_ContentNegotiatiorTracer_Returns_IContentNegotiator()\n        {\n            // Arrange\n            IContentNegotiator expectedInner = new Mock<IContentNegotiator>().Object;\n            ContentNegotiatorTracer productUnderTest = new ContentNegotiatorTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            IContentNegotiator actualInner = productUnderTest.Inner;\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n\n        [Fact]\n        public void Decorator_GetInner_On_ContentNegotiatiorTracer_Returns_IContentNegotiator()\n        {\n            // Arrange\n            IContentNegotiator expectedInner = new Mock<IContentNegotiator>().Object;\n            ContentNegotiatorTracer productUnderTest = new ContentNegotiatorTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            IContentNegotiator actualInner = Decorator.GetInner(productUnderTest as IContentNegotiator);\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/DefaultHttpControllerTypeResolverTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing System.Runtime.Serialization;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.Services;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class DefaultHttpControllerTypeResolverTracerTest\n    {\n        private static readonly string ExceptionMessage = \"Remember my name\";\n        private readonly List<Type> ExpectedTypes;\n        private readonly List<TraceRecord> ExpectedTraces;\n\n        private readonly Mock<MockableAssembly>[] Assemblies;\n        private readonly Mock<IAssembliesResolver> AssembliesResolver;\n        private readonly Mock<DefaultHttpControllerTypeResolver> HttpControllerTypeResolver;\n\n        public DefaultHttpControllerTypeResolverTracerTest()\n        {\n            ExpectedTypes = new List<Type>\n            {\n                typeof(ValidController), typeof(UsersRpcController), typeof(UsersController),\n            };\n\n            Type[] fine1Types = new Type[]\n            {\n                typeof(DefaultHttpControllerTypeResolverTracerTest),\n                null,\n                typeof(ValidController),\n            };\n            Type[] poorTypes = new Type[]\n            {\n                typeof(string),\n                null,\n                typeof(Action),\n                null,\n                typeof(UsersRpcController),\n            };\n            Type[] fine2Types = new Type[]\n            {\n                typeof(DefaultHttpControllerTypeResolver),\n                null,\n                typeof(DefaultHttpControllerTypeResolverTracer),\n                null,\n                typeof(UsersController)\n            };\n\n            Exception worseException = new Exception(ExceptionMessage);\n            Exception poorException = new ReflectionTypeLoadException(poorTypes, new Exception[] { worseException });\n            ExpectedTraces = new List<TraceRecord>\n            {\n                new TraceRecord(null, TraceCategories.ControllersCategory, TraceLevel.Debug)\n                {\n                    Kind = TraceKind.Begin,\n                    Operator = \"DefaultHttpControllerTypeResolverProxy\", // Moq type name\n                    Operation = \"GetControllerTypes\",\n                },\n                new TraceRecord(null, TraceCategories.ControllersCategory, TraceLevel.Warn)\n                {\n                    Kind = TraceKind.Trace,\n                    Exception = poorException,\n                    Message = \"Exception thrown while getting types from 'PoorAssembly'.\",\n                },\n                new TraceRecord(null, TraceCategories.ControllersCategory, TraceLevel.Warn)\n                {\n                    Kind = TraceKind.Trace,\n                    Exception = worseException,\n                    Message = \"Exception thrown while getting types from 'WorseAssembly'.\",\n                },\n                new TraceRecord(null, TraceCategories.ControllersCategory, TraceLevel.Debug)\n                {\n                    Kind = TraceKind.End,\n                    Operator = \"DefaultHttpControllerTypeResolverProxy\",\n                    Operation = \"GetControllerTypes\",\n                },\n            };\n\n            Mock<MockableAssembly> fine1Assembly = new Mock<MockableAssembly>(MockBehavior.Strict);\n            fine1Assembly.Setup(assembly => assembly.GetTypes()).Returns(fine1Types);\n            fine1Assembly.SetupGet(assembly => assembly.IsDynamic).Returns(false);\n\n            Exception[] exceptions = new Exception[] { new Exception(ExceptionMessage), };\n            Mock<MockableAssembly> poorAssembly = new Mock<MockableAssembly>(MockBehavior.Strict);\n            poorAssembly.Setup(assembly => assembly.GetTypes()).Throws(poorException);\n            poorAssembly.SetupGet(assembly => assembly.IsDynamic).Returns(false);\n            poorAssembly.SetupGet(assembly => assembly.FullName).Returns(\"PoorAssembly\");\n\n            Mock<MockableAssembly> worseAssembly = new Mock<MockableAssembly>(MockBehavior.Strict);\n            worseAssembly.Setup(assembly => assembly.GetTypes()).Throws(worseException);\n            worseAssembly.SetupGet(assembly => assembly.IsDynamic).Returns(false);\n            worseAssembly.SetupGet(assembly => assembly.FullName).Returns(\"WorseAssembly\");\n\n            Mock<MockableAssembly> fine2Assembly = new Mock<MockableAssembly>(MockBehavior.Strict);\n            fine2Assembly.Setup(assembly => assembly.GetTypes()).Returns(fine2Types);\n            fine2Assembly.SetupGet(assembly => assembly.IsDynamic).Returns(false);\n\n            Mock<MockableAssembly> dynamicAssembly = new Mock<MockableAssembly>(MockBehavior.Strict);\n            dynamicAssembly.SetupGet(assembly => assembly.IsDynamic).Returns(true);\n\n            Assemblies = new Mock<MockableAssembly>[]\n            {\n                fine1Assembly,\n                poorAssembly,\n                worseAssembly,\n                fine2Assembly,\n                dynamicAssembly,\n            };\n\n            AssembliesResolver = new Mock<IAssembliesResolver>(MockBehavior.Strict);\n            AssembliesResolver.Setup(resolver => resolver.GetAssemblies()).Returns(\n                Assemblies.Select(assembly => (Assembly)assembly.Object).AsCollection());\n\n            HttpControllerTypeResolver =\n                new Mock<DefaultHttpControllerTypeResolver>() { CallBase = true, };\n        }\n\n        [Fact]\n        public void GetControllerTypes_CallsMocks()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            DefaultHttpControllerTypeResolverTracer tracer =\n                new DefaultHttpControllerTypeResolverTracer(HttpControllerTypeResolver.Object, traceWriter);\n\n            // Act\n            tracer.GetControllerTypes(AssembliesResolver.Object);\n\n            // Assert (particularly important tracer delegates to original DefaultHttpControllerTypeResolver)\n            HttpControllerTypeResolver.Verify(\n                controller => controller.GetControllerTypes(AssembliesResolver.Object), Times.Once());\n\n            // Predicate is not called on null entries or internal types in the Type arrays (see TypeIsVisible)\n            HttpControllerTypeResolver.VerifyGet(controller => controller.IsControllerTypePredicate, Times.Exactly(7));\n\n            AssembliesResolver.Verify(resolver => resolver.GetAssemblies(), Times.Once());\n            foreach (Mock<MockableAssembly> mock in Assemblies)\n            {\n                mock.VerifyGet(assembly => assembly.IsDynamic, Times.Once());\n                mock.Verify(assembly => assembly.GetTypes(), mock.Object.IsDynamic ? Times.Never() : Times.Once());\n            }\n        }\n\n        [Fact]\n        public void GetControllerTypes_ReturnsExpectedTypes()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            DefaultHttpControllerTypeResolverTracer tracer =\n                new DefaultHttpControllerTypeResolverTracer(HttpControllerTypeResolver.Object, traceWriter);\n\n            // Act\n            ICollection<Type> types = tracer.GetControllerTypes(AssembliesResolver.Object);\n\n            // Assert\n            Assert.NotNull(types);\n            Assert.NotEmpty(types);\n            Assert.Equal(ExpectedTypes, types);\n        }\n\n        [Fact]\n        public void GetControllerTypes_TracesAsExpected()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            DefaultHttpControllerTypeResolverTracer tracer =\n                new DefaultHttpControllerTypeResolverTracer(HttpControllerTypeResolver.Object, traceWriter);\n\n            // Act\n            ICollection<Type> types = tracer.GetControllerTypes(AssembliesResolver.Object);\n\n            // Assert\n            Assert.NotNull(traceWriter.Traces);\n            Assert.Equal(ExpectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void InnerProperty_ReturnsOriginal()\n        {\n            // Arrange\n            DefaultHttpControllerTypeResolver expectedResolver = HttpControllerTypeResolver.Object;\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            DefaultHttpControllerTypeResolverTracer tracer =\n                new DefaultHttpControllerTypeResolverTracer(HttpControllerTypeResolver.Object, traceWriter);\n\n            // Act\n            DefaultHttpControllerTypeResolver resolver = tracer.Inner;\n\n            // Assert\n            Assert.NotNull(resolver);\n            Assert.Same(expectedResolver, resolver);\n        }\n\n        [Fact]\n        public void Decorator_GetInner_ReturnsOriginal()\n        {\n            // Arrange\n            DefaultHttpControllerTypeResolver expectedResolver = HttpControllerTypeResolver.Object;\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            DefaultHttpControllerTypeResolverTracer tracer =\n                new DefaultHttpControllerTypeResolverTracer(HttpControllerTypeResolver.Object, traceWriter);\n\n            // Act\n            DefaultHttpControllerTypeResolver resolver = Decorator.GetInner(tracer as DefaultHttpControllerTypeResolver);\n\n            // Assert\n            Assert.NotNull(resolver);\n            Assert.Same(expectedResolver, resolver);\n        }\n\n        [Fact]\n        public void IsControllerTypePredicateProperty_SameAsInInner()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            DefaultHttpControllerTypeResolverTracer tracer =\n                new DefaultHttpControllerTypeResolverTracer(HttpControllerTypeResolver.Object, traceWriter);\n\n            // Act\n            Predicate<Type> innerPredicate = HttpControllerTypeResolver.Object.IsControllerTypePredicate;\n            Predicate<Type> tracerPredicate = tracer.IsControllerTypePredicate;\n\n            // Assert\n            Assert.NotNull(tracerPredicate);\n            Assert.Same(innerPredicate, tracerPredicate);\n        }\n\n        [Fact]\n        public void IsControllerTypePredicateProperty_RoundTrips()\n        {\n            // Arrange\n            Predicate<Type> expectedPredicate = type => type != null;\n            DefaultHttpControllerTypeResolver resolver = new DefaultHttpControllerTypeResolver(expectedPredicate);\n\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            DefaultHttpControllerTypeResolverTracer tracer =\n                new DefaultHttpControllerTypeResolverTracer(resolver, traceWriter);\n\n            // Act\n            Predicate<Type> predicate = tracer.IsControllerTypePredicate;\n\n            // Assert\n            Assert.NotNull(predicate);\n            Assert.Same(expectedPredicate, predicate);\n        }\n\n        // Workaround Moq / Castle requirement that ISerializable object must have the ISerializable constructor.\n        // Assembly implements ISerializable but lacks the constructor.\n        public abstract class MockableAssembly : Assembly\n        {\n            public MockableAssembly()\n            {\n            }\n\n            public MockableAssembly(SerializationInfo info, StreamingContext context)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/ExceptionFilterAttributeTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Services;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class ExceptionFilterAttributeTracerTest\n    {\n        [Fact]\n        public void Equals_Calls_Inner()\n        {\n            // Arrange\n            object randomObject = new Object();\n            Mock<ExceptionFilterAttribute> mockAttribute = new Mock<ExceptionFilterAttribute>();\n            mockAttribute.Setup(a => a.Equals(randomObject)).Returns(true).Verifiable();\n            ExceptionFilterAttributeTracer tracer = new ExceptionFilterAttributeTracer(mockAttribute.Object, new TestTraceWriter());\n\n            // Act\n            bool valueReturned = tracer.Equals(randomObject);\n\n            // Assert\n            Assert.True(valueReturned);\n            mockAttribute.Verify();\n        }\n\n        [Fact]\n        public void GetHashCode_Calls_Inner()\n        {\n            // Arrange\n            Mock<ExceptionFilterAttribute> mockAttribute = new Mock<ExceptionFilterAttribute>();\n            mockAttribute.Setup(a => a.GetHashCode()).Returns(1).Verifiable();\n            ExceptionFilterAttributeTracer tracer = new ExceptionFilterAttributeTracer(mockAttribute.Object, new TestTraceWriter());\n\n            // Act\n            int valueReturned = tracer.GetHashCode();\n\n            // Assert\n            Assert.Equal(1, valueReturned);\n            mockAttribute.Verify();\n        }\n\n        [Fact]\n        public void IsDefaultAttribute_Calls_Inner()\n        {\n            // Arrange\n            Mock<ExceptionFilterAttribute> mockAttribute = new Mock<ExceptionFilterAttribute>();\n            mockAttribute.Setup(a => a.IsDefaultAttribute()).Returns(true).Verifiable();\n            ExceptionFilterAttributeTracer tracer = new ExceptionFilterAttributeTracer(mockAttribute.Object, new TestTraceWriter());\n\n            // Act\n            bool valueReturned = tracer.IsDefaultAttribute();\n\n            // Assert\n            Assert.True(valueReturned);\n            mockAttribute.Verify();\n        }\n\n        [Fact]\n        public void Match_Calls_Inner()\n        {\n            // Arrange\n            object randomObject = new Object();\n            Mock<ExceptionFilterAttribute> mockAttribute = new Mock<ExceptionFilterAttribute>();\n            mockAttribute.Setup(a => a.Match(randomObject)).Returns(true).Verifiable();\n            ExceptionFilterAttributeTracer tracer = new ExceptionFilterAttributeTracer(mockAttribute.Object, new TestTraceWriter());\n\n            // Act\n            bool valueReturned = tracer.Match(randomObject);\n\n            // Assert\n            Assert.True(valueReturned);\n            mockAttribute.Verify();\n        }\n\n        [Fact]\n        public void TypeId_Calls_Inner()\n        {\n            // Arrange\n            object randomObject = new Object();\n            Mock<ExceptionFilterAttribute> mockAttribute = new Mock<ExceptionFilterAttribute>();\n            mockAttribute.Setup(a => a.TypeId).Returns(randomObject).Verifiable();\n            ExceptionFilterAttributeTracer tracer = new ExceptionFilterAttributeTracer(mockAttribute.Object, new TestTraceWriter());\n\n            // Act\n            object valueReturned = tracer.TypeId;\n\n            // Assert\n            Assert.Same(randomObject, valueReturned);\n            mockAttribute.Verify();\n        }\n\n        [Fact]\n        public void AllowMultiple_Calls_Inner()\n        {\n            // Arrange\n            Mock<ExceptionFilterAttribute> mockAttribute = new Mock<ExceptionFilterAttribute>();\n            mockAttribute.Setup(a => a.AllowMultiple).Returns(true).Verifiable();\n            ExceptionFilterAttributeTracer tracer = new ExceptionFilterAttributeTracer(mockAttribute.Object, new TestTraceWriter());\n\n            // Act\n            bool valueReturned = tracer.AllowMultiple;\n\n            // Assert\n            Assert.True(valueReturned);\n            mockAttribute.Verify();\n        }\n\n        [Fact]\n        public async Task ExecuteExceptionFilterAsync_Traces()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            HttpResponseMessage response = new HttpResponseMessage();\n            Mock<ExceptionFilterAttribute> mockAttr = new Mock<ExceptionFilterAttribute>() { CallBase = true };\n            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };\n            mockActionDescriptor.Setup(a => a.ActionName).Returns(\"test\");\n            mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0]));\n            HttpActionExecutedContext actionExecutedContext = ContextUtil.GetActionExecutedContext(request, response);\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            ExceptionFilterAttributeTracer tracer = new ExceptionFilterAttributeTracer(mockAttr.Object, traceWriter);\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"OnExceptionAsync\" },\n                new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.End,  Operation = \"OnExceptionAsync\" },\n            };\n\n            // Act\n            var filter = (IExceptionFilter)tracer;\n            await filter.ExecuteExceptionFilterAsync(actionExecutedContext, CancellationToken.None);\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public async Task ExecuteExceptionFilterAsync_Throws_And_Traces_When_Inner_OnException_Throws()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            HttpResponseMessage response = new HttpResponseMessage();\n            Mock<ExceptionFilterAttribute> mockAttr = new Mock<ExceptionFilterAttribute>() { CallBase = true };\n            InvalidOperationException exception = new InvalidOperationException(\"test\");\n            mockAttr.Setup(a => a.OnException(It.IsAny<HttpActionExecutedContext>())).Callback(() => { throw exception; });\n            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };\n            mockActionDescriptor.Setup(a => a.ActionName).Returns(\"test\");\n            mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0]));\n            HttpActionExecutedContext actionExecutedContext = ContextUtil.GetActionExecutedContext(request, response);\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            IExceptionFilter tracer = new ExceptionFilterAttributeTracer(mockAttr.Object, traceWriter) as IExceptionFilter;\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"OnExceptionAsync\" },\n                new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Error) { Kind = TraceKind.End,  Operation = \"OnExceptionAsync\" }\n            };\n\n            // Act\n            // We separate the task creation and the wait, to verify we don't throw at task creation\n            // and that the exception flows inside the task (even if an Aggregate Exception was thrown).\n            var task = tracer.ExecuteExceptionFilterAsync(actionExecutedContext, CancellationToken.None);\n            Exception thrown = await Assert.ThrowsAsync<InvalidOperationException>(() => task);\n\n            // Assert\n            Assert.Same(exception, thrown);\n            Assert.Same(exception, traceWriter.Traces[1].Exception);\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void Inner_Property_On_ExceptionFilterAttributeTracer_Returns_ExceptionFilterAttribute()\n        {\n            // Arrange\n            ExceptionFilterAttribute expectedInner = new Mock<ExceptionFilterAttribute>().Object;\n            ExceptionFilterAttributeTracer productUnderTest = new ExceptionFilterAttributeTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            ExceptionFilterAttribute actualInner = productUnderTest.Inner;\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n\n        [Fact]\n        public void Decorator_GetInner_On_ExceptionFilterAttributeTracer_Returns_ExceptionFilterAttribute()\n        {\n            // Arrange\n            ExceptionFilterAttribute expectedInner = new Mock<ExceptionFilterAttribute>().Object;\n            ExceptionFilterAttributeTracer productUnderTest = new ExceptionFilterAttributeTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            ExceptionFilterAttribute actualInner = Decorator.GetInner(productUnderTest as ExceptionFilterAttribute);\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/ExceptionFilterTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Services;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class ExceptionFilterTracerTest\n    {\n        [Fact]\n        public async Task ExecuteExceptionFilterAsync_Traces()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            HttpResponseMessage response = new HttpResponseMessage();\n            Mock<IExceptionFilter> mockFilter = new Mock<IExceptionFilter>() { CallBase = true };\n            mockFilter.Setup(f => f.ExecuteExceptionFilterAsync(It.IsAny<HttpActionExecutedContext>(), It.IsAny<CancellationToken>()))\n                .Returns(TaskHelpers.Completed());\n            HttpActionExecutedContext actionExecutedContext = ContextUtil.GetActionExecutedContext(request, response);\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            ExceptionFilterTracer tracer = new ExceptionFilterTracer(mockFilter.Object, traceWriter);\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"ExecuteExceptionFilterAsync\" },\n                new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.End,  Operation = \"ExecuteExceptionFilterAsync\" },\n            };\n\n            // Act\n            var filter = (IExceptionFilter)tracer;\n            await filter.ExecuteExceptionFilterAsync(actionExecutedContext, CancellationToken.None);\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public async Task ExecuteExceptionFilterAsync_Faults_And_Traces_When_Inner_Faults()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            HttpResponseMessage response = new HttpResponseMessage();\n            Mock<IExceptionFilter> mockFilter = new Mock<IExceptionFilter>() { CallBase = true };\n            InvalidOperationException exception = new InvalidOperationException(\"test\");\n            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(null);\n            tcs.TrySetException(exception);\n            mockFilter.Setup(a => a.ExecuteExceptionFilterAsync(It.IsAny<HttpActionExecutedContext>(), It.IsAny<CancellationToken>())).Returns(tcs.Task);\n            HttpActionExecutedContext actionExecutedContext = ContextUtil.GetActionExecutedContext(request, response);\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            ExceptionFilterTracer tracer = new ExceptionFilterTracer(mockFilter.Object, traceWriter);\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"ExecuteExceptionFilterAsync\" },\n                new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Error) { Kind = TraceKind.End,  Operation = \"ExecuteExceptionFilterAsync\" }\n            };\n\n            // Act\n            Task task = ((IExceptionFilter)tracer).ExecuteExceptionFilterAsync(actionExecutedContext, CancellationToken.None);\n\n            // Assert\n            Exception thrown = await Assert.ThrowsAsync<InvalidOperationException>(() => task);\n            Assert.Same(exception, thrown);\n            Assert.Same(exception, traceWriter.Traces[1].Exception);\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void Inner_Property_On_ExceptionFilterTracer_Returns_IExceptionFilter()\n        {\n            // Arrange\n            IExceptionFilter expectedInner = new Mock<IExceptionFilter>().Object;\n            ExceptionFilterTracer productUnderTest = new ExceptionFilterTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            IExceptionFilter actualInner = productUnderTest.Inner as IExceptionFilter;\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n\n        [Fact]\n        public void Decorator_GetInner_On_ExceptionFilterTracer_Returns_IExceptionFilter()\n        {\n            // Arrange\n            IExceptionFilter expectedInner = new Mock<IExceptionFilter>().Object;\n            ExceptionFilterTracer productUnderTest = new ExceptionFilterTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            IExceptionFilter actualInner = Decorator.GetInner(productUnderTest.Inner as IExceptionFilter);\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/FilterTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Services;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class FilterTracerTest\n    {\n        [Fact]\n        public void CreateFilterTracers_IFilter_With_IFilter_Returns_Single_Wrapped_IFilter()\n        {\n            // Arrange\n            Mock<IFilter> mockFilter = new Mock<IFilter>();\n\n            // Act\n            IEnumerable<IFilter> wrappedFilters = FilterTracer.CreateFilterTracers(mockFilter.Object, new TestTraceWriter());\n\n            // Assert\n            IFilter wrappedFilter = Assert.Single(wrappedFilters);\n            Assert.IsType<FilterTracer>(wrappedFilter);\n        }\n\n        [Fact]\n        public void CreateFilterTracers_IFilter_With_IActionFilter_Returns_Single_Wrapped_IActionFilter()\n        {\n            // Arrange\n            Mock<IActionFilter> mockFilter = new Mock<IActionFilter>();\n\n            // Act\n            IEnumerable<IFilter> wrappedFilters = FilterTracer.CreateFilterTracers(mockFilter.Object, new TestTraceWriter());\n\n            // Assert\n            IFilter wrappedFilter = Assert.Single(wrappedFilters);\n            Assert.IsType<ActionFilterTracer>(wrappedFilter);\n        }\n\n        [Fact]\n        public void CreateFilterTracers_IFilter_With_IExceptionFilter_Returns_Single_Wrapped_IExceptionFilter()\n        {\n            // Arrange\n            Mock<IExceptionFilter> mockFilter = new Mock<IExceptionFilter>();\n\n            // Act\n            IEnumerable<IFilter> wrappedFilters = FilterTracer.CreateFilterTracers(mockFilter.Object, new TestTraceWriter());\n\n            // Assert\n            IFilter wrappedFilter = Assert.Single(wrappedFilters);\n            Assert.IsType<ExceptionFilterTracer>(wrappedFilter);\n        }\n\n        [Fact]\n        public void CreateFilterTracers_IFilter_With_IAuthenticationFilter_Returns_Single_Wrapped_IAuthenticationFilter()\n        {\n            // Arrange\n            IAuthenticationFilter expectedInner = new Mock<IAuthenticationFilter>().Object;\n            ITraceWriter expectedTraceWriter = new TestTraceWriter();\n\n            // Act\n            IEnumerable<IFilter> tracers = FilterTracer.CreateFilterTracers(expectedInner, expectedTraceWriter);\n\n            // Assert\n            Assert.NotNull(tracers);\n            IFilter untypedFilter = Assert.Single(tracers);\n            AuthenticationFilterTracer tracer = Assert.IsType<AuthenticationFilterTracer>(untypedFilter);\n            Assert.Same(expectedInner, tracer.InnerFilter);\n            Assert.Same(expectedTraceWriter, tracer.TraceWriter);\n        }\n\n        [Fact]\n        public void CreateFilterTracers_IFilter_With_IAuthorizationFilter_Returns_Single_Wrapped_IAuthorizationFilter()\n        {\n            // Arrange\n            Mock<IAuthorizationFilter> mockFilter = new Mock<IAuthorizationFilter>();\n\n            // Act\n            IEnumerable<IFilter> wrappedFilters = FilterTracer.CreateFilterTracers(mockFilter.Object, new TestTraceWriter());\n\n            // Assert\n            IFilter wrappedFilter = Assert.Single(wrappedFilters);\n            Assert.IsType<AuthorizationFilterTracer>(wrappedFilter);\n        }\n\n        [Fact]\n        public void CreateFilterTracers_IFilter_With_IOverrideFilter_Returns_Single_Wrapped_IOverrideFilter()\n        {\n            // Arrange\n            IOverrideFilter expectedInner = new Mock<IOverrideFilter>().Object;\n            ITraceWriter expectedTraceWriter = new TestTraceWriter();\n\n            // Act\n            IEnumerable<IFilter> tracers = FilterTracer.CreateFilterTracers(expectedInner, expectedTraceWriter);\n\n            // Assert\n            Assert.NotNull(tracers);\n            IFilter untypedFilter = Assert.Single(tracers);\n            OverrideFilterTracer tracer = Assert.IsType<OverrideFilterTracer>(untypedFilter);\n            Assert.Same(expectedInner, tracer.InnerFilter);\n            Assert.Same(expectedTraceWriter, tracer.TraceWriter);\n        }\n\n        [Fact]\n        public void CreateFilterTracers_IFilter_With_ActionFilterAttribute_Returns_Single_Wrapped_Filter()\n        {\n            // Arrange\n            Mock<ActionFilterAttribute> mockFilter = new Mock<ActionFilterAttribute>();\n\n            // Act\n            IEnumerable<IFilter> wrappedFilters = FilterTracer.CreateFilterTracers(mockFilter.Object, new TestTraceWriter());\n\n            // Assert\n            IFilter wrappedFilter = Assert.Single(wrappedFilters);\n            Assert.IsType<ActionFilterAttributeTracer>(wrappedFilter);\n        }\n\n        [Fact]\n        public void CreateFilterTracers_IFilter_With_ExceptionFilterAttribute_Returns_Single_Wrapped_Filter()\n        {\n            // Arrange\n            Mock<ExceptionFilterAttribute> mockFilter = new Mock<ExceptionFilterAttribute>();\n\n            // Act\n            IEnumerable<IFilter> wrappedFilters = FilterTracer.CreateFilterTracers(mockFilter.Object, new TestTraceWriter());\n\n            // Assert\n            IFilter wrappedFilter = Assert.Single(wrappedFilters);\n            Assert.IsType<ExceptionFilterAttributeTracer>(wrappedFilter);\n        }\n\n        [Fact]\n        public void CreateFilterTracers_IFilter_With_AuthorizationFilterAttribute_Returns_Single_Wrapped_Filter()\n        {\n            // Arrange\n            Mock<AuthorizationFilterAttribute> mockFilter = new Mock<AuthorizationFilterAttribute>();\n\n            // Act\n            IEnumerable<IFilter> wrappedFilters = FilterTracer.CreateFilterTracers(mockFilter.Object, new TestTraceWriter());\n\n            // Assert\n            IFilter wrappedFilter = Assert.Single(wrappedFilters);\n            Assert.IsType<AuthorizationFilterAttributeTracer>(wrappedFilter);\n        }\n\n        [Fact]\n        public void CreateFilterTracers_IFilter_With_All_Filter_Interfaces_Returns_Wrapped_Filters_For_Each_Filter()\n        {\n            // Arrange\n            IFilter filter = new TestFilterAllBehaviors();\n\n            // Act\n            IFilter[] wrappedFilters = FilterTracer.CreateFilterTracers(filter, new TestTraceWriter()).ToArray();\n\n            // Assert\n            Assert.Equal(5, wrappedFilters.Length);\n            Assert.Single(wrappedFilters.OfType<ActionFilterTracer>());\n            Assert.Single(wrappedFilters.OfType<AuthorizationFilterTracer>());\n            Assert.Single(wrappedFilters.OfType<AuthenticationFilterTracer>());\n            Assert.Single(wrappedFilters.OfType<ExceptionFilterTracer>());\n            Assert.Single(wrappedFilters.OfType<OverrideFilterTracer>());\n        }\n\n        [Fact]\n        public void CreateFilterTracers_With_IFilter_Returns_Single_Wrapped_IFilter()\n        {\n            // Arrange\n            Mock<IFilter> mockFilter = new Mock<IFilter>();\n            FilterInfo filter = new FilterInfo(mockFilter.Object, FilterScope.Action);\n\n            // Act\n            IEnumerable<FilterInfo> wrappedFilters = FilterTracer.CreateFilterTracers(filter, new TestTraceWriter());\n\n            // Assert\n            FilterInfo wrappedFilter = Assert.Single(wrappedFilters);\n            Assert.IsType<FilterTracer>(wrappedFilter.Instance);\n        }\n\n        [Fact]\n        public void CreateFilterTracers_With_IActionFilter_Returns_Single_Wrapped_IActionFilter()\n        {\n            // Arrange\n            Mock<IActionFilter> mockFilter = new Mock<IActionFilter>();\n            FilterInfo filter = new FilterInfo(mockFilter.Object, FilterScope.Action);\n\n            // Act\n            IEnumerable<FilterInfo> wrappedFilters = FilterTracer.CreateFilterTracers(filter, new TestTraceWriter());\n\n            // Assert\n            FilterInfo wrappedFilter = Assert.Single(wrappedFilters);\n            Assert.IsType<ActionFilterTracer>(wrappedFilter.Instance);\n        }\n\n        [Fact]\n        public void CreateFilterTracers_With_IExceptionFilter_Returns_Single_Wrapped_IExceptionFilter()\n        {\n            // Arrange\n            Mock<IExceptionFilter> mockFilter = new Mock<IExceptionFilter>();\n            FilterInfo filter = new FilterInfo(mockFilter.Object, FilterScope.Action);\n\n            // Act\n            IEnumerable<FilterInfo> wrappedFilters = FilterTracer.CreateFilterTracers(filter, new TestTraceWriter());\n\n            // Assert\n            FilterInfo wrappedFilter = Assert.Single(wrappedFilters);\n            Assert.IsType<ExceptionFilterTracer>(wrappedFilter.Instance);\n        }\n\n        [Fact]\n        public void CreateFilterTracers_With_IAuthenticationFilter_Returns_Single_Wrapped_IAuthenticationFilter()\n        {\n            // Arrange\n            IAuthenticationFilter expectedInner = new Mock<IAuthenticationFilter>().Object;\n            FilterInfo inputFilterInfo = new FilterInfo(expectedInner, FilterScope.Action);\n            ITraceWriter expectedTraceWriter = new TestTraceWriter();\n\n            // Act\n            IEnumerable<FilterInfo> filters = FilterTracer.CreateFilterTracers(inputFilterInfo, expectedTraceWriter);\n\n            // Assert\n            Assert.NotNull(filters);\n            FilterInfo filterInfo = Assert.Single(filters);\n            Assert.NotNull(filterInfo);\n            IFilter untypedFilter = filterInfo.Instance;\n            AuthenticationFilterTracer tracer = Assert.IsType<AuthenticationFilterTracer>(untypedFilter);\n            Assert.Same(expectedInner, tracer.InnerFilter);\n            Assert.Same(expectedTraceWriter, tracer.TraceWriter);\n        }\n\n        [Fact]\n        public void CreateFilterTracers_With_IAuthorizationFilter_Returns_Single_Wrapped_IAuthorizationFilter()\n        {\n            // Arrange\n            Mock<IAuthorizationFilter> mockFilter = new Mock<IAuthorizationFilter>();\n            FilterInfo filter = new FilterInfo(mockFilter.Object, FilterScope.Action);\n\n            // Act\n            IEnumerable<FilterInfo> wrappedFilters = FilterTracer.CreateFilterTracers(filter, new TestTraceWriter());\n\n            // Assert\n            FilterInfo wrappedFilter = Assert.Single(wrappedFilters);\n            Assert.IsType<AuthorizationFilterTracer>(wrappedFilter.Instance);\n        }\n\n        [Fact]\n        public void CreateFilterTracers_With_IOverrideFilter_Returns_Single_Wrapped_IOverrideFilter()\n        {\n            // Arrange\n            IOverrideFilter expectedInner = new Mock<IOverrideFilter>().Object;\n            FilterInfo inputFilterInfo = new FilterInfo(expectedInner, FilterScope.Action);\n            ITraceWriter expectedTraceWriter = new TestTraceWriter();\n\n            // Act\n            IEnumerable<FilterInfo> filters = FilterTracer.CreateFilterTracers(inputFilterInfo, expectedTraceWriter);\n\n            // Assert\n            Assert.NotNull(filters);\n            FilterInfo filterInfo = Assert.Single(filters);\n            Assert.NotNull(filterInfo);\n            IFilter untypedFilter = filterInfo.Instance;\n            OverrideFilterTracer tracer = Assert.IsType<OverrideFilterTracer>(untypedFilter);\n            Assert.Same(expectedInner, tracer.InnerFilter);\n            Assert.Same(expectedTraceWriter, tracer.TraceWriter);\n        }\n\n        [Fact]\n        public void CreateFilterTracers_With_ActionFilterAttribute_Returns_Single_Wrapped_Filter()\n        {\n            // Arrange\n            Mock<ActionFilterAttribute> mockFilter = new Mock<ActionFilterAttribute>();\n            FilterInfo filter = new FilterInfo(mockFilter.Object, FilterScope.Action);\n\n            // Act\n            IEnumerable<FilterInfo> wrappedFilters = FilterTracer.CreateFilterTracers(filter, new TestTraceWriter());\n\n            // Assert\n            FilterInfo wrappedFilter = Assert.Single(wrappedFilters);\n            Assert.IsType<ActionFilterAttributeTracer>(wrappedFilter.Instance);\n        }\n\n        [Fact]\n        public void CreateFilterTracers_With_ExceptionFilterAttribute_Returns_Single_Wrapped_Filter()\n        {\n            // Arrange\n            Mock<ExceptionFilterAttribute> mockFilter = new Mock<ExceptionFilterAttribute>();\n            FilterInfo filter = new FilterInfo(mockFilter.Object, FilterScope.Action);\n\n            // Act\n            IEnumerable<FilterInfo> wrappedFilters = FilterTracer.CreateFilterTracers(filter, new TestTraceWriter());\n\n            // Assert\n            FilterInfo wrappedFilter = Assert.Single(wrappedFilters);\n            Assert.IsType<ExceptionFilterAttributeTracer>(wrappedFilter.Instance);\n        }\n\n        [Fact]\n        public void CreateFilterTracers_With_AuthorizationFilterAttribute_Returns_Single_Wrapped_Filter()\n        {\n            // Arrange\n            Mock<AuthorizationFilterAttribute> mockFilter = new Mock<AuthorizationFilterAttribute>();\n            FilterInfo filter = new FilterInfo(mockFilter.Object, FilterScope.Action);\n\n            // Act\n            IEnumerable<FilterInfo> wrappedFilters = FilterTracer.CreateFilterTracers(filter, new TestTraceWriter());\n\n            // Assert\n            FilterInfo wrappedFilter = Assert.Single(wrappedFilters);\n            Assert.IsType<AuthorizationFilterAttributeTracer>(wrappedFilter.Instance);\n        }\n\n        [Fact]\n        public void CreateFilterTracers_With_All_Filter_Interfaces_Returns_Wrapped_Filters_For_Each_Filter()\n        {\n            // Arrange\n            FilterInfo filter = new FilterInfo(new TestFilterAllBehaviors(), FilterScope.Action);\n\n            // Act\n            FilterInfo[] wrappedFilters = FilterTracer.CreateFilterTracers(filter, new TestTraceWriter()).ToArray();\n\n            // Assert\n            Assert.Equal(5, wrappedFilters.Length);\n            Assert.Single(wrappedFilters, f => f.Instance.GetType() == typeof(ActionFilterTracer));\n            Assert.Single(wrappedFilters, f => f.Instance.GetType() == typeof(AuthorizationFilterTracer));\n            Assert.Single(wrappedFilters, f => f.Instance.GetType() == typeof(AuthenticationFilterTracer));\n            Assert.Single(wrappedFilters, f => f.Instance.GetType() == typeof(ExceptionFilterTracer));\n            Assert.Single(wrappedFilters, f => f.Instance.GetType() == typeof(OverrideFilterTracer));\n        }\n\n        [Fact]\n        public void Inner_Property_On_FilterTracer_Returns_IFilter()\n        {\n            // Arrange\n            IFilter expectedInner = new Mock<IFilter>().Object;\n            FilterTracer productUnderTest = new FilterTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            IFilter actualInner = productUnderTest.Inner;\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n\n        [Fact]\n        public void Decorator_GetInner_Property_On_FilterTracer_Returns_IFilter()\n        {\n            // Arrange\n            IFilter expectedInner = new Mock<IFilter>().Object;\n            FilterTracer productUnderTest = new FilterTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            IFilter actualInner = Decorator.GetInner(productUnderTest as IFilter);\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n\n        // Test filter class that exposes all filter behaviors will cause separate filters for each\n        class TestFilterAllBehaviors : IActionFilter, IExceptionFilter, IAuthorizationFilter, IAuthenticationFilter,\n            IOverrideFilter\n        {\n            Task<Net.Http.HttpResponseMessage> IActionFilter.ExecuteActionFilterAsync(Controllers.HttpActionContext actionContext, Threading.CancellationToken cancellationToken, Func<Threading.Tasks.Task<Net.Http.HttpResponseMessage>> continuation)\n            {\n                throw new NotImplementedException();\n            }\n\n            bool IFilter.AllowMultiple\n            {\n                get { throw new NotImplementedException(); }\n            }\n\n            Task IExceptionFilter.ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)\n            {\n                throw new NotImplementedException();\n            }\n\n            Task<HttpResponseMessage> IAuthorizationFilter.ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<Net.Http.HttpResponseMessage>> continuation)\n            {\n                throw new NotImplementedException();\n            }\n\n            Task IAuthenticationFilter.AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)\n            {\n                throw new NotImplementedException();\n            }\n\n            Task IAuthenticationFilter.ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)\n            {\n                throw new NotImplementedException();\n            }\n\n            public Type FiltersToOverride\n            {\n                get { throw new NotImplementedException(); }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/FormUrlEncodedMediaTypeFormatterTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Web.Http.Services;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class FormUrlEncodedMediaTypeFormatterTracerTest : ReadWriteMediaTypeFormatterTracerTestBase<FormUrlEncodedMediaTypeFormatter>\n    {\n        public override MediaTypeFormatter CreateTracer(FormUrlEncodedMediaTypeFormatter formatter, HttpRequestMessage request, ITraceWriter traceWriter)\n        {\n            return new FormUrlEncodedMediaTypeFormatterTracer(formatter, traceWriter, request);\n        }\n\n        [Fact]\n        public void MaxDepth_Uses_Inners()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            FormUrlEncodedMediaTypeFormatter innerFormatter = new FormUrlEncodedMediaTypeFormatter();\n            innerFormatter.MaxDepth = innerFormatter.MaxDepth + 1;\n            FormUrlEncodedMediaTypeFormatterTracer tracer = new FormUrlEncodedMediaTypeFormatterTracer(innerFormatter, new TestTraceWriter(), request);\n\n            // Act & Assert\n            Assert.Equal(innerFormatter.MaxDepth, tracer.MaxDepth);\n        }\n\n        [Fact]\n        public void ReadBufferSize_Uses_Inners()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            FormUrlEncodedMediaTypeFormatter innerFormatter = new FormUrlEncodedMediaTypeFormatter();\n            innerFormatter.ReadBufferSize = innerFormatter.ReadBufferSize + 1;\n            FormUrlEncodedMediaTypeFormatterTracer tracer = new FormUrlEncodedMediaTypeFormatterTracer(innerFormatter, new TestTraceWriter(), request);\n\n            // Act & Assert\n            Assert.Equal(innerFormatter.ReadBufferSize, tracer.ReadBufferSize);\n        }\n\n        [Fact]\n        public void Inner_Property_On_FormUrlEncodedMediaTypeFormatterTracer_Returns_FormUrlEncodedMediaTypeFormatter()\n        {\n            // Arrange\n            FormUrlEncodedMediaTypeFormatter expectedInner = new FormUrlEncodedMediaTypeFormatter();\n            FormUrlEncodedMediaTypeFormatterTracer productUnderTest = new FormUrlEncodedMediaTypeFormatterTracer(expectedInner, new TestTraceWriter(), new HttpRequestMessage());\n\n            // Act\n            FormUrlEncodedMediaTypeFormatter actualInner = productUnderTest.Inner;\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n\n        [Fact]\n        public void Decorator_GetInner_On_FormUrlEncodedMediaTypeFormatterTracer_Returns_FormUrlEncodedMediaTypeFormatter()\n        {\n            // Arrange\n            FormUrlEncodedMediaTypeFormatter expectedInner = new FormUrlEncodedMediaTypeFormatter();\n            FormUrlEncodedMediaTypeFormatterTracer productUnderTest = new FormUrlEncodedMediaTypeFormatterTracer(expectedInner, new TestTraceWriter(), new HttpRequestMessage());\n\n            // Act\n            FormUrlEncodedMediaTypeFormatter actualInner = Decorator.GetInner(productUnderTest as FormUrlEncodedMediaTypeFormatter);\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/FormatterParameterBindingTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Metadata.Providers;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.Services;\nusing System.Web.Http.Validation;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class FormatterParameterBindingTracerTest\n    {\n        [Fact]\n        public void ErrorMessage_Calls_Inner()\n        {\n            // Arrange\n            Mock<HttpParameterDescriptor> mockParamDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true };\n            mockParamDescriptor.Setup(d => d.ParameterName).Returns(\"paramName\");\n            mockParamDescriptor.Setup(d => d.ParameterType).Returns(typeof(string));\n            Mock<FormatterParameterBinding> mockBinding = new Mock<FormatterParameterBinding>(mockParamDescriptor.Object, new MediaTypeFormatterCollection(), null);\n            mockBinding.Setup(b => b.ErrorMessage).Returns(\"errorMessage\").Verifiable();\n            FormatterParameterBindingTracer tracer = new FormatterParameterBindingTracer(mockBinding.Object, new TestTraceWriter());\n\n            // Act & Assert\n            Assert.Equal(\"errorMessage\", tracer.ErrorMessage);\n            mockBinding.Verify();\n        }\n\n        [Fact]\n        public void WillReadBody_Calls_Inner()\n        {\n            // Arrange\n            Mock<HttpParameterDescriptor> mockParamDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true };\n            mockParamDescriptor.Setup(d => d.ParameterName).Returns(\"paramName\");\n            mockParamDescriptor.Setup(d => d.ParameterType).Returns(typeof(string));\n            Mock<FormatterParameterBinding> mockBinding = new Mock<FormatterParameterBinding>(mockParamDescriptor.Object, new MediaTypeFormatterCollection(), null);\n            mockBinding.Setup(b => b.WillReadBody).Returns(true).Verifiable();\n            FormatterParameterBindingTracer tracer = new FormatterParameterBindingTracer(mockBinding.Object, new TestTraceWriter());\n\n            // Act & Assert\n            Assert.True(tracer.WillReadBody);\n            mockBinding.Verify();\n        }\n\n        [Fact]\n        public void Descriptor_Uses_Inners()\n        {\n            // Arrange\n            Mock<HttpParameterDescriptor> mockParamDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true };\n            mockParamDescriptor.Setup(d => d.ParameterName).Returns(\"paramName\");\n            mockParamDescriptor.Setup(d => d.ParameterType).Returns(typeof(string));\n            Mock<FormatterParameterBinding> mockBinding = new Mock<FormatterParameterBinding>(mockParamDescriptor.Object, new MediaTypeFormatterCollection(), null) { CallBase = true };\n            FormatterParameterBindingTracer tracer = new FormatterParameterBindingTracer(mockBinding.Object, new TestTraceWriter());\n\n            // Act & Assert\n            Assert.Same(mockBinding.Object.Descriptor, tracer.Descriptor);\n        }\n\n        [Fact]\n        public void Formatters_Uses_Inners()\n        {\n            // Arrange\n            Mock<HttpParameterDescriptor> mockParamDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true };\n            mockParamDescriptor.Setup(d => d.ParameterName).Returns(\"paramName\");\n            mockParamDescriptor.Setup(d => d.ParameterType).Returns(typeof(string));\n            Mock<FormatterParameterBinding> mockBinding = new Mock<FormatterParameterBinding>(mockParamDescriptor.Object, new MediaTypeFormatterCollection(), null) { CallBase = true };\n            FormatterParameterBindingTracer tracer = new FormatterParameterBindingTracer(mockBinding.Object, new TestTraceWriter());\n\n            // Act & Assert\n            Assert.Equal(mockBinding.Object.Formatters, tracer.Formatters);\n        }\n\n        [Fact]\n        public void BodyModelValidator_Uses_Inners()\n        {\n            // Arrange\n            Mock<HttpParameterDescriptor> mockParamDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true };\n            mockParamDescriptor.Setup(d => d.ParameterName).Returns(\"paramName\");\n            mockParamDescriptor.Setup(d => d.ParameterType).Returns(typeof(string));\n            Mock<IBodyModelValidator> mockValidator = new Mock<IBodyModelValidator>();\n            Mock<FormatterParameterBinding> mockBinding = new Mock<FormatterParameterBinding>(mockParamDescriptor.Object, new MediaTypeFormatterCollection(), mockValidator.Object) { CallBase = true };\n            FormatterParameterBindingTracer tracer = new FormatterParameterBindingTracer(mockBinding.Object, new TestTraceWriter());\n\n            // Act & Assert\n            Assert.Equal(mockBinding.Object.BodyModelValidator, tracer.BodyModelValidator);\n        }\n\n        /// <summary>\n        /// This test verifies that our <see cref=\"FormatterParameterBindingTracer\"/>\n        /// intercepts the async bind request and redirects it to use tracing formatters\n        /// correlated to the request.\n        /// </summary>\n        [Fact]\n        public async Task ExecuteBindingAsync_Traces_And_Invokes_Inner_ReadAsync()\n        {\n            // Arrange\n            Mock<HttpParameterDescriptor> mockParamDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true };\n            mockParamDescriptor.Setup(d => d.ParameterName).Returns(\"paramName\");\n            mockParamDescriptor.Setup(d => d.ParameterType).Returns(typeof(string));\n            FormatterParameterBinding binding = new FormatterParameterBinding(mockParamDescriptor.Object, new MediaTypeFormatterCollection(), null);\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            FormatterParameterBindingTracer tracer = new FormatterParameterBindingTracer(binding, traceWriter);\n            HttpActionContext actionContext = ContextUtil.CreateActionContext();\n            actionContext.Request.Content = new StringContent(\"true\");\n            actionContext.Request.Content.Headers.ContentType = new MediaTypeHeaderValue(\"application/json\");\n            ModelMetadataProvider metadataProvider = new EmptyModelMetadataProvider();\n\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"ExecuteBindingAsync\" },\n                new TraceRecord(actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = \"ExecuteBindingAsync\" }\n            };\n\n            // Act\n            await tracer.ExecuteBindingAsync(metadataProvider, actionContext, CancellationToken.None);\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Equal(\"true\", actionContext.ActionArguments[\"paramName\"]);\n        }\n\n        [Fact]\n        public void ExecuteBindingAsync_Traces_And_Throws_When_Inner_Throws()\n        {\n            // Arrange\n            Mock<HttpParameterDescriptor> mockParamDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true };\n            mockParamDescriptor.Setup(d => d.ParameterName).Returns(\"paramName\");\n            mockParamDescriptor.Setup(d => d.ParameterType).Returns(typeof(string));\n            Mock<FormatterParameterBinding> mockBinding = new Mock<FormatterParameterBinding>(mockParamDescriptor.Object, new MediaTypeFormatterCollection(), null) { CallBase = true };\n            InvalidOperationException exception = new InvalidOperationException(\"test\");\n            mockBinding.Setup(\n                b =>\n                b.ExecuteBindingAsync(It.IsAny<ModelMetadataProvider>(), It.IsAny<HttpActionContext>(),\n                                      It.IsAny<CancellationToken>())).Throws(exception);\n\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            FormatterParameterBindingTracer tracer = new FormatterParameterBindingTracer(mockBinding.Object, traceWriter);\n            HttpActionContext actionContext = ContextUtil.CreateActionContext();\n            ModelMetadataProvider metadataProvider = new EmptyModelMetadataProvider();\n\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"ExecuteBindingAsync\" },\n                new TraceRecord(actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = \"ExecuteBindingAsync\" }\n            };\n\n            // Act & Assert\n            Exception thrown = Assert.Throws<InvalidOperationException>(() => tracer.ExecuteBindingAsync(metadataProvider, actionContext, CancellationToken.None));\n\n            // Assert\n            Assert.Same(exception, thrown);\n            Assert.Same(exception, traceWriter.Traces[1].Exception);\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public async Task ExecuteBindingAsync_Traces_And_Faults_When_Inner_Faults()\n        {\n            // Arrange\n\n            Mock<HttpParameterDescriptor> mockParamDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true };\n            mockParamDescriptor.Setup(d => d.ParameterName).Returns(\"paramName\");\n            mockParamDescriptor.Setup(d => d.ParameterType).Returns(typeof(string));\n            Mock<FormatterParameterBinding> mockBinding = new Mock<FormatterParameterBinding>(mockParamDescriptor.Object, new MediaTypeFormatterCollection(), null) { CallBase = true };\n            InvalidOperationException exception = new InvalidOperationException(\"test\");\n            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();\n            tcs.TrySetException(exception);\n\n            mockBinding.Setup(\n                b =>\n                b.ExecuteBindingAsync(It.IsAny<ModelMetadataProvider>(), It.IsAny<HttpActionContext>(),\n                                      It.IsAny<CancellationToken>())).Returns(tcs.Task);\n\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            FormatterParameterBindingTracer tracer = new FormatterParameterBindingTracer(mockBinding.Object, traceWriter);\n            HttpActionContext actionContext = ContextUtil.CreateActionContext();\n            ModelMetadataProvider metadataProvider = new EmptyModelMetadataProvider();\n\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"ExecuteBindingAsync\" },\n                new TraceRecord(actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = \"ExecuteBindingAsync\" }\n            };\n\n            // Act & Assert\n            Task task = tracer.ExecuteBindingAsync(metadataProvider, actionContext, CancellationToken.None);\n\n            // Assert\n            Exception thrown = await Assert.ThrowsAsync<InvalidOperationException>(() => task);\n            Assert.Same(exception, thrown);\n            Assert.Same(exception, traceWriter.Traces[1].Exception);\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void Inner_Property_On_FormatterParameterBindingTracer_Returns_FormatterParameterBinding()\n        {\n            // Arrange\n            HttpParameterDescriptor httpParameterDescriptor = new Mock<HttpParameterDescriptor>().Object;\n            MediaTypeFormatterCollection mediaTypeFormatterCollection = new MediaTypeFormatterCollection();\n            FormatterParameterBinding expectedInner = new FormatterParameterBinding(httpParameterDescriptor, mediaTypeFormatterCollection, null);\n            FormatterParameterBindingTracer productUnderTest = new FormatterParameterBindingTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            FormatterParameterBinding actualInner = productUnderTest.Inner;\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n\n        [Fact]\n        public void Decorator_GetInner_On_FormatterParameterBindingTracer_Returns_FormatterParameterBinding()\n        {\n            // Arrange\n            HttpParameterDescriptor httpParameterDescriptor = new Mock<HttpParameterDescriptor>().Object;\n            MediaTypeFormatterCollection mediaTypeFormatterCollection = new MediaTypeFormatterCollection();\n            FormatterParameterBinding expectedInner = new FormatterParameterBinding(httpParameterDescriptor, mediaTypeFormatterCollection, null);\n            FormatterParameterBindingTracer productUnderTest = new FormatterParameterBindingTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            FormatterParameterBinding actualInner = Decorator.GetInner(productUnderTest as FormatterParameterBinding);\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/HttpActionBindingTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Services;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class HttpActionBindingTracerTest\n    {\n        private Mock<HttpActionDescriptor> _mockActionDescriptor;\n        private Mock<HttpParameterDescriptor> _mockParameterDescriptor;\n        private Mock<HttpParameterBinding> _mockParameterBinding;\n        private HttpActionBinding _actionBinding;\n        private HttpActionContext _actionContext;\n        private HttpControllerContext _controllerContext;\n        private HttpControllerDescriptor _controllerDescriptor;\n\n        public HttpActionBindingTracerTest()\n        {\n            _mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };\n            _mockActionDescriptor.Setup(a => a.ActionName).Returns(\"test\");\n            _mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0]));\n\n            _mockParameterDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true };\n            _mockParameterBinding = new Mock<HttpParameterBinding>(_mockParameterDescriptor.Object) { CallBase = true };\n            _actionBinding = new HttpActionBinding(_mockActionDescriptor.Object, new HttpParameterBinding[] { _mockParameterBinding.Object });\n\n            _controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), \"controller\", typeof(ApiController));\n\n            _controllerContext = ContextUtil.CreateControllerContext(request: new HttpRequestMessage());\n            _controllerContext.ControllerDescriptor = _controllerDescriptor;\n\n            _actionContext = ContextUtil.CreateActionContext(_controllerContext, actionDescriptor: _mockActionDescriptor.Object);\n\n        }\n\n        [Fact]\n        public void ActionDescriptor_Uses_Inners()\n        {\n            // Arrange\n            HttpActionBinding binding = new Mock<HttpActionBinding>() { CallBase = true }.Object;\n            binding.ActionDescriptor = _mockActionDescriptor.Object;\n            HttpActionBindingTracer tracer = new HttpActionBindingTracer(binding, new TestTraceWriter());\n\n            // Assert\n            Assert.Same(binding.ActionDescriptor, tracer.ActionDescriptor);\n        }\n\n        [Fact]\n        public void ParameterBindings_Uses_Inners()\n        {\n            // Arrange\n            HttpActionBinding binding = new Mock<HttpActionBinding>() { CallBase = true }.Object;\n            HttpParameterBinding[] parameterBindings = new HttpParameterBinding[0];\n            binding.ParameterBindings = parameterBindings;\n            HttpActionBindingTracer tracer = new HttpActionBindingTracer(binding, new TestTraceWriter());\n\n            // Assert\n            Assert.Same(parameterBindings, tracer.ParameterBindings);\n        }\n\n        [Fact]\n        public async Task BindValuesAsync_Invokes_Inner_And_Traces()\n        {\n            // Arrange\n            bool wasInvoked = false;\n            Mock<HttpActionBinding> mockBinder = new Mock<HttpActionBinding>() { CallBase = true };\n            mockBinder.Setup(b => b.ExecuteBindingAsync(It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>()))\n                .Callback(() => wasInvoked = true).Returns(TaskHelpers.Completed());\n\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpActionBindingTracer tracer = new HttpActionBindingTracer(mockBinder.Object, traceWriter);\n\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(_actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info) { Kind = TraceKind.Begin },\n                new TraceRecord(_actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info) { Kind = TraceKind.End }\n            };\n\n            // Act\n            await tracer.ExecuteBindingAsync(_actionContext, CancellationToken.None);\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.True(wasInvoked);\n        }\n\n        [Fact]\n        public async Task ExecuteBindingAsync_Faults_And_Traces_When_Inner_Faults()\n        {\n            // Arrange\n            InvalidOperationException exception = new InvalidOperationException();\n            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();\n            tcs.TrySetException(exception);\n            Mock<HttpActionBinding> mockBinder = new Mock<HttpActionBinding>() { CallBase = true };\n            mockBinder.Setup(b => b.ExecuteBindingAsync(It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>()))\n                .Returns(tcs.Task);\n\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpActionBindingTracer tracer = new HttpActionBindingTracer(mockBinder.Object, traceWriter);\n\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(_actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info) { Kind = TraceKind.Begin },\n                new TraceRecord(_actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Error) { Kind = TraceKind.End }\n            };\n\n            // Act\n            Task task = tracer.ExecuteBindingAsync(_actionContext, CancellationToken.None);\n\n            // Assert\n            Exception thrown = await Assert.ThrowsAsync<InvalidOperationException>(() => task);\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(exception, thrown);\n            Assert.Same(exception, traceWriter.Traces[1].Exception);\n        }\n\n        [Fact]\n        public void Inner_Property_On_HttpActionBindingTracer_Returns_HttpActionBinding()\n        {\n            // Arrange\n            HttpActionBinding expectedInner = new HttpActionBinding();\n            HttpActionBindingTracer productUnderTest = new HttpActionBindingTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            HttpActionBinding actualInner = productUnderTest.Inner;\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n\n        [Fact]\n        public void Decorator_GetInner_On_HttpActionBindingTracer_Returns_HttpActionBinding()\n        {\n            // Arrange\n            HttpActionBinding expectedInner = new HttpActionBinding();\n            HttpActionBindingTracer productUnderTest = new HttpActionBindingTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            HttpActionBinding actualInner = Decorator.GetInner(productUnderTest as HttpActionBinding);\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/HttpActionDescriptorTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Services;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class HttpActionDescriptorTracerTest\n    {\n        [Fact]\n        public void ActionName_Calls_Inner()\n        {\n            // Arrange\n            HttpControllerDescriptor controllerDescriptor = new Mock<HttpControllerDescriptor>().Object;\n            controllerDescriptor.Configuration = new HttpConfiguration();\n            Mock<HttpActionDescriptor> mockDescriptor = new Mock<HttpActionDescriptor>(controllerDescriptor);\n            mockDescriptor.Setup(d => d.ActionName).Returns(\"actionName\").Verifiable();\n            HttpActionDescriptor actionDescriptor = mockDescriptor.Object;\n            HttpControllerContext controllerContext = new Mock<HttpControllerContext>().Object;\n            controllerContext.Configuration = controllerDescriptor.Configuration;\n            controllerContext.ControllerDescriptor = controllerDescriptor;\n            HttpActionDescriptorTracer tracer = new HttpActionDescriptorTracer(controllerContext, actionDescriptor, new TestTraceWriter());\n\n            // Act and Assert\n            Assert.Same(\"actionName\", tracer.ActionName);\n            mockDescriptor.Verify();\n        }\n\n        [Fact]\n        public void SupportedHttpMethods_Calls_Inner()\n        {\n            // Arrange\n            HttpControllerDescriptor controllerDescriptor = new Mock<HttpControllerDescriptor>().Object;\n            controllerDescriptor.Configuration = new HttpConfiguration();\n            Collection<HttpMethod> methods = new Collection<HttpMethod>() { HttpMethod.Delete };\n            Mock<HttpActionDescriptor> mockDescriptor = new Mock<HttpActionDescriptor>(controllerDescriptor);\n            mockDescriptor.Setup(d => d.SupportedHttpMethods).Returns(methods).Verifiable();\n            HttpActionDescriptor actionDescriptor = mockDescriptor.Object;\n            HttpControllerContext controllerContext = new Mock<HttpControllerContext>().Object;\n            controllerContext.Configuration = controllerDescriptor.Configuration;\n            controllerContext.ControllerDescriptor = controllerDescriptor;\n            HttpActionDescriptorTracer tracer = new HttpActionDescriptorTracer(controllerContext, actionDescriptor, new TestTraceWriter());\n\n            // Act and Assert\n            Assert.Equal(methods, tracer.SupportedHttpMethods);\n            mockDescriptor.Verify();\n        }\n\n        [Fact]\n        public void ActionBinding_Calls_Inner()\n        {\n            // Arrange\n            HttpActionBinding binding = new Mock<HttpActionBinding>().Object;\n            HttpControllerDescriptor controllerDescriptor = new Mock<HttpControllerDescriptor>().Object;\n            controllerDescriptor.Configuration = new HttpConfiguration();\n            Mock<HttpActionDescriptor> mockDescriptor = new Mock<HttpActionDescriptor>(controllerDescriptor);\n            mockDescriptor.Setup(d => d.ActionBinding).Returns(binding).Verifiable();\n            HttpActionDescriptor actionDescriptor = mockDescriptor.Object;\n            HttpControllerContext controllerContext = new Mock<HttpControllerContext>().Object;\n            controllerContext.Configuration = controllerDescriptor.Configuration;\n            controllerContext.ControllerDescriptor = controllerDescriptor;\n            HttpActionDescriptorTracer tracer = new HttpActionDescriptorTracer(controllerContext, actionDescriptor, new TestTraceWriter());\n\n            // Act and Assert\n            Assert.Same(binding, tracer.ActionBinding);\n            mockDescriptor.Verify();\n        }\n\n        [Fact]\n        public void ReturnType_Calls_Inner()\n        {\n            // Arrange\n            HttpControllerDescriptor controllerDescriptor = new Mock<HttpControllerDescriptor>().Object;\n            controllerDescriptor.Configuration = new HttpConfiguration();\n            Mock<HttpActionDescriptor> mockDescriptor = new Mock<HttpActionDescriptor>(controllerDescriptor);\n            mockDescriptor.Setup(d => d.ReturnType).Returns(typeof(string)).Verifiable();\n            HttpActionDescriptor actionDescriptor = mockDescriptor.Object;\n            HttpControllerContext controllerContext = new Mock<HttpControllerContext>().Object;\n            controllerContext.Configuration = controllerDescriptor.Configuration;\n            controllerContext.ControllerDescriptor = controllerDescriptor;\n            HttpActionDescriptorTracer tracer = new HttpActionDescriptorTracer(controllerContext, actionDescriptor, new TestTraceWriter());\n\n            // Act and Assert\n            Assert.Equal(typeof(string), tracer.ReturnType);\n            mockDescriptor.Verify();\n        }\n\n        [Fact]\n        public void ResultConverter_Calls_Inner()\n        {\n            // Arrange\n            IActionResultConverter resultConverter = new Mock<IActionResultConverter>().Object;\n            HttpControllerDescriptor controllerDescriptor = new Mock<HttpControllerDescriptor>().Object;\n            controllerDescriptor.Configuration = new HttpConfiguration();\n            Mock<HttpActionDescriptor> mockDescriptor = new Mock<HttpActionDescriptor>(controllerDescriptor);\n            mockDescriptor.Setup(d => d.ResultConverter).Returns(resultConverter).Verifiable();\n            HttpActionDescriptor actionDescriptor = mockDescriptor.Object;\n            HttpControllerContext controllerContext = new Mock<HttpControllerContext>().Object;\n            controllerContext.Configuration = controllerDescriptor.Configuration;\n            controllerContext.ControllerDescriptor = controllerDescriptor;\n            HttpActionDescriptorTracer tracer = new HttpActionDescriptorTracer(controllerContext, actionDescriptor, new TestTraceWriter());\n\n            // Act and Assert\n            Assert.Same(resultConverter, tracer.ResultConverter);\n            mockDescriptor.Verify();\n        }\n\n        [Fact]\n        public void Properties_Calls_Inner()\n        {\n            // Arrange\n            ConcurrentDictionary<object, object> properties = new ConcurrentDictionary<object, object>();\n            HttpControllerDescriptor controllerDescriptor = new Mock<HttpControllerDescriptor>().Object;\n            controllerDescriptor.Configuration = new HttpConfiguration();\n            Mock<HttpActionDescriptor> mockDescriptor = new Mock<HttpActionDescriptor>(controllerDescriptor);\n            mockDescriptor.Setup(d => d.Properties).Returns(properties).Verifiable();\n            HttpActionDescriptor actionDescriptor = mockDescriptor.Object;\n            HttpControllerContext controllerContext = new Mock<HttpControllerContext>().Object;\n            controllerContext.Configuration = controllerDescriptor.Configuration;\n            controllerContext.ControllerDescriptor = controllerDescriptor;\n            HttpActionDescriptorTracer tracer = new HttpActionDescriptorTracer(controllerContext, actionDescriptor, new TestTraceWriter());\n\n            // Act and Assert\n            Assert.Same(properties, tracer.Properties);\n            mockDescriptor.Verify();\n        }\n\n        [Fact]\n        public void GetCustomAttributes_Calls_Inner()\n        {\n            // Arrange\n            Collection<Attribute> customAttributes = new Collection<Attribute>();\n            HttpControllerDescriptor controllerDescriptor = new Mock<HttpControllerDescriptor>().Object;\n            controllerDescriptor.Configuration = new HttpConfiguration();\n            Mock<HttpActionDescriptor> mockDescriptor = new Mock<HttpActionDescriptor>(controllerDescriptor);\n            mockDescriptor.Setup(d => d.GetCustomAttributes<Attribute>()).Returns(customAttributes).Verifiable();\n            HttpActionDescriptor actionDescriptor = mockDescriptor.Object;\n            HttpControllerContext controllerContext = new Mock<HttpControllerContext>().Object;\n            controllerContext.Configuration = controllerDescriptor.Configuration;\n            controllerContext.ControllerDescriptor = controllerDescriptor;\n            HttpActionDescriptorTracer tracer = new HttpActionDescriptorTracer(controllerContext, actionDescriptor, new TestTraceWriter());\n\n            // Act and Assert\n            Assert.Same(customAttributes, tracer.GetCustomAttributes<Attribute>());\n            mockDescriptor.Verify();\n        }\n\n        [Fact]\n        public void GetParameters_Calls_Inner()\n        {\n            // Arrange\n            Collection<HttpParameterDescriptor> parameters = new Collection<HttpParameterDescriptor>();\n            HttpControllerDescriptor controllerDescriptor = new Mock<HttpControllerDescriptor>().Object;\n            controllerDescriptor.Configuration = new HttpConfiguration();\n            Mock<HttpActionDescriptor> mockDescriptor = new Mock<HttpActionDescriptor>(controllerDescriptor);\n            mockDescriptor.Setup(d => d.GetParameters()).Returns(parameters).Verifiable();\n            HttpActionDescriptor actionDescriptor = mockDescriptor.Object;\n            HttpControllerContext controllerContext = new Mock<HttpControllerContext>().Object;\n            controllerContext.Configuration = controllerDescriptor.Configuration;\n            controllerContext.ControllerDescriptor = controllerDescriptor;\n            HttpActionDescriptorTracer tracer = new HttpActionDescriptorTracer(controllerContext, actionDescriptor, new TestTraceWriter());\n\n            // Act and Assert\n            Assert.Same(parameters, tracer.GetParameters());\n            mockDescriptor.Verify();\n        }\n\n        [Fact]\n        public void GetFilters_Calls_Inner()\n        {\n            // Arrange\n            Collection<IFilter> filters = new Collection<IFilter>();\n            HttpControllerDescriptor controllerDescriptor = new Mock<HttpControllerDescriptor>().Object;\n            controllerDescriptor.Configuration = new HttpConfiguration();\n            Mock<HttpActionDescriptor> mockDescriptor = new Mock<HttpActionDescriptor>(controllerDescriptor);\n            mockDescriptor.Setup(d => d.GetFilters()).Returns(filters).Verifiable();\n            HttpActionDescriptor actionDescriptor = mockDescriptor.Object;\n            HttpControllerContext controllerContext = new Mock<HttpControllerContext>().Object;\n            controllerContext.Configuration = controllerDescriptor.Configuration;\n            controllerContext.ControllerDescriptor = controllerDescriptor;\n            HttpActionDescriptorTracer tracer = new HttpActionDescriptorTracer(controllerContext, actionDescriptor, new TestTraceWriter());\n\n            // Act\n            tracer.GetFilters();\n\n            // Assert\n            mockDescriptor.Verify();\n        }\n\n        [Fact]\n        public void GetFilterPipeline_Calls_Inner()\n        {\n            // Arrange\n            Collection<FilterInfo> filters = new Collection<FilterInfo>();\n            HttpControllerDescriptor controllerDescriptor = new Mock<HttpControllerDescriptor>().Object;\n            controllerDescriptor.Configuration = new HttpConfiguration();\n            Mock<HttpActionDescriptor> mockDescriptor = new Mock<HttpActionDescriptor>(controllerDescriptor);\n            mockDescriptor.Setup(d => d.GetFilterPipeline()).Returns(filters).Verifiable();\n            HttpActionDescriptor actionDescriptor = mockDescriptor.Object;\n            HttpControllerContext controllerContext = new Mock<HttpControllerContext>().Object;\n            controllerContext.Configuration = controllerDescriptor.Configuration;\n            controllerContext.ControllerDescriptor = controllerDescriptor;\n            HttpActionDescriptorTracer tracer = new HttpActionDescriptorTracer(controllerContext, actionDescriptor, new TestTraceWriter());\n\n            // Act\n            tracer.GetFilterPipeline();\n\n            // Assert\n            mockDescriptor.Verify();\n        }\n        [Fact]\n        public void Configuration_Uses_Inners()\n        {\n            // Assert\n            HttpControllerDescriptor controllerDescriptor = new Mock<HttpControllerDescriptor>().Object;\n            controllerDescriptor.Configuration = new HttpConfiguration();\n            Mock<HttpActionDescriptor> mockDescriptor = new Mock<HttpActionDescriptor>(controllerDescriptor);\n            HttpActionDescriptor actionDescriptor = mockDescriptor.Object;\n            HttpControllerContext controllerContext = new Mock<HttpControllerContext>().Object;\n            controllerContext.Configuration = controllerDescriptor.Configuration;\n            controllerContext.ControllerDescriptor = controllerDescriptor;\n            HttpActionDescriptorTracer tracer = new HttpActionDescriptorTracer(controllerContext, actionDescriptor, new TestTraceWriter());\n\n            // Act and Assert\n            Assert.Same(actionDescriptor.Configuration, tracer.Configuration);\n        }\n\n        [Fact]\n        public void ControllerDescriptor_Uses_Inners()\n        {\n            // Assert\n            HttpControllerDescriptor controllerDescriptor = new Mock<HttpControllerDescriptor>().Object;\n            controllerDescriptor.Configuration = new HttpConfiguration();\n            Mock<HttpActionDescriptor> mockDescriptor = new Mock<HttpActionDescriptor>(controllerDescriptor);\n            HttpActionDescriptor actionDescriptor = mockDescriptor.Object;\n            HttpControllerContext controllerContext = new Mock<HttpControllerContext>().Object;\n            controllerContext.Configuration = controllerDescriptor.Configuration;\n            controllerContext.ControllerDescriptor = controllerDescriptor;\n            HttpActionDescriptorTracer tracer = new HttpActionDescriptorTracer(controllerContext, actionDescriptor, new TestTraceWriter());\n\n            // Act and Assert\n            Assert.Same(actionDescriptor.ControllerDescriptor, tracer.ControllerDescriptor);\n        }\n\n        // This test verifies only one kind of filter is wrapped, proving\n        // the static FilterTracer.CreateFilterTracer was called from GetFilterPipeline.\n        // Deeper testing of FilterTracer.CreateFilterTracer is in FilterTracerTest.\n        [Fact]\n        public void GetFilterPipeline_Returns_Wrapped_Filters()\n        {\n            // Arrange\n            Mock<IFilter> mockFilter = new Mock<IFilter>();\n            FilterInfo filter = new FilterInfo(mockFilter.Object, FilterScope.Global);\n            Collection<FilterInfo> filterCollection = new Collection<FilterInfo>(new FilterInfo[] { filter });\n            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };\n            mockActionDescriptor.Setup(a => a.ActionName).Returns(\"test\");\n            mockActionDescriptor.Setup(a => a.GetFilterPipeline()).Returns(filterCollection);\n            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext();\n            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, \"test\", typeof(ApiController));\n            HttpActionDescriptorTracer tracer = new HttpActionDescriptorTracer(controllerContext, mockActionDescriptor.Object, new TestTraceWriter());\n\n            // Act\n            Collection<FilterInfo> wrappedFilterCollection = tracer.GetFilterPipeline();\n\n            // Assert\n            Assert.IsType<FilterTracer>(wrappedFilterCollection[0].Instance);\n        }\n\n        // This test verifies only one kind of filter is wrapped, proving\n        // the static FilterTracer.CreateFilterTracer was called from GetFilterPipeline.\n        // Deeper testing of FilterTracer.CreateFilterTracer is in FilterTracerTest.\n        [Fact]\n        public void GetFilters_Returns_Wrapped_IFilters()\n        {\n            // Arrange\n            Mock<IFilter> mockFilter = new Mock<IFilter>();\n            Collection<IFilter> filters = new Collection<IFilter>(new IFilter[] { mockFilter.Object });\n            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };\n            mockActionDescriptor.Setup(a => a.ActionName).Returns(\"test\");\n            mockActionDescriptor.Setup(a => a.GetFilters()).Returns(filters);\n            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext();\n            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, \"test\", typeof(ApiController));\n            HttpActionDescriptorTracer tracer = new HttpActionDescriptorTracer(controllerContext, mockActionDescriptor.Object, new TestTraceWriter());\n\n            // Act\n            IFilter[] wrappedFilters = tracer.GetFilters().ToArray();\n\n            // Assert\n            Assert.IsType<FilterTracer>(wrappedFilters[0]);\n        }\n\n        [Fact]\n        public void ExecuteAsync_Invokes_Inner_ExecuteAsync()\n        {\n            // Arrange\n            var cts = new CancellationTokenSource();\n            var mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };\n            mockActionDescriptor.Setup(a => a.ActionName).Returns(\"test\");\n            var controllerContext = ContextUtil.CreateControllerContext();\n            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, \"test\", typeof(ApiController));\n            var arguments = new Dictionary<string, object>();\n            var tracer = new HttpActionDescriptorTracer(controllerContext, mockActionDescriptor.Object, new TestTraceWriter());\n\n            // Act\n            tracer.ExecuteAsync(controllerContext, arguments, cts.Token);\n\n            // Assert\n            mockActionDescriptor.Verify(a => a.ExecuteAsync(controllerContext, arguments, cts.Token), Times.Once());\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Traces()\n        {\n            // Arrange\n            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };\n            mockActionDescriptor.Setup(a => a.ActionName).Returns(\"test\");\n            mockActionDescriptor.Setup(a => a.ExecuteAsync(It.IsAny<HttpControllerContext>(), It.IsAny<IDictionary<string, object>>(), CancellationToken.None))\n                .Returns(Task.FromResult<object>(null));\n            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext();\n            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, \"test\", typeof(ApiController));\n            IDictionary<string, object> arguments = new Dictionary<string, object>();\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpActionDescriptorTracer tracer = new HttpActionDescriptorTracer(controllerContext, mockActionDescriptor.Object, traceWriter);\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(controllerContext.Request, TraceCategories.ActionCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"ExecuteAsync\" },\n                new TraceRecord(controllerContext.Request, TraceCategories.ActionCategory, TraceLevel.Info) { Kind = TraceKind.End }\n            };\n\n            // Act\n            await tracer.ExecuteAsync(controllerContext, arguments, CancellationToken.None);\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void ExecuteAsync_Throws_What_Inner_Throws_And_Traces()\n        {\n            // Arrange\n            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };\n            InvalidOperationException exception = new InvalidOperationException(\"test\");\n            mockActionDescriptor.Setup(\n                a => a.ExecuteAsync(It.IsAny<HttpControllerContext>(), It.IsAny<IDictionary<string, object>>(), CancellationToken.None)).Throws(exception);\n            mockActionDescriptor.Setup(a => a.ActionName).Returns(\"test\");\n            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext();\n            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, \"test\", typeof(ApiController));\n            IDictionary<string, object> arguments = new Dictionary<string, object>();\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpActionDescriptorTracer tracer = new HttpActionDescriptorTracer(controllerContext, mockActionDescriptor.Object, traceWriter);\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(controllerContext.Request, TraceCategories.ActionCategory, TraceLevel.Info) { Kind = TraceKind.Begin },\n                new TraceRecord(controllerContext.Request, TraceCategories.ActionCategory, TraceLevel.Error) { Kind = TraceKind.End }\n            };\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(() => tracer.ExecuteAsync(controllerContext, arguments, CancellationToken.None));\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(exception, traceWriter.Traces[1].Exception);\n        }\n\n        [Fact]\n        public void Inner_Property_On_HttpActionDescriptorTracer_Returns_HttpActionDescriptor()\n        {\n            // Arrange\n            HttpActionDescriptor expectedInner = new Mock<HttpActionDescriptor>().Object;\n            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext();\n            HttpActionDescriptorTracer productUnderTest = new HttpActionDescriptorTracer(controllerContext, expectedInner, new TestTraceWriter());\n\n            // Act\n            HttpActionDescriptor actualInner = productUnderTest.Inner;\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n\n        [Fact]\n        public void Decorator_GetInner_On_HttpActionDescriptorTracer_Returns_HttpActionDescriptor()\n        {\n            // Arrange\n            HttpActionDescriptor expectedInner = new Mock<HttpActionDescriptor>().Object;\n            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext();\n            HttpActionDescriptorTracer productUnderTest = new HttpActionDescriptorTracer(controllerContext, expectedInner, new TestTraceWriter());\n\n            // Act\n            HttpActionDescriptor actualInner = Decorator.GetInner(productUnderTest as HttpActionDescriptor);\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/HttpActionInvokerTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Services;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class HttpActionInvokerTracerTest\n    {\n        private HttpActionContext _actionContext;\n        private ApiController _apiController;\n\n        public HttpActionInvokerTracerTest()\n        {\n            UsersController controller = new UsersController();\n            _apiController = controller;\n\n            Func<HttpResponseMessage> actionMethod = controller.Get;\n            _actionContext = ContextUtil.CreateActionContext(\n                ContextUtil.CreateControllerContext(instance: _apiController),\n                new ReflectedHttpActionDescriptor { MethodInfo = actionMethod.Method });\n            HttpRequestMessage request = new HttpRequestMessage();\n            _actionContext.ControllerContext.Request = request;\n        }\n\n        [Fact]\n        public void InvokeActionAsync_Invokes_Inner_InvokeActionAsync()\n        {\n            // Arrange\n            var cts = new CancellationTokenSource();\n            var mockInnerInvoker = new Mock<IHttpActionInvoker>();\n            IHttpActionInvoker invoker = new HttpActionInvokerTracer(mockInnerInvoker.Object, new Mock<ITraceWriter>().Object);\n\n            // Act\n            invoker.InvokeActionAsync(_actionContext, cts.Token);\n\n            // Assert\n            mockInnerInvoker.Verify(i => i.InvokeActionAsync(_actionContext, cts.Token), Times.Once());\n        }\n\n        [Fact]\n        public async Task InvokeActionAsync_Traces_Begin_And_End_Info()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpActionInvokerTracer tracer = new HttpActionInvokerTracer(new ApiControllerActionInvoker(), traceWriter);\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(_actionContext.Request, TraceCategories.ActionCategory, TraceLevel.Info) { Kind = TraceKind.Begin },\n                new TraceRecord(_actionContext.Request, TraceCategories.ActionCategory, TraceLevel.Info) { Kind = TraceKind.End }\n            };\n\n            // Act\n            var actionInvoker = (IHttpActionInvoker)tracer;\n            await actionInvoker.InvokeActionAsync(_actionContext, CancellationToken.None);\n\n            // Assert\n            Assert.Equal(2, traceWriter.Traces.Count);\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public async Task InvokeActionAsync_Returns_Cancelled_Inner_Task()\n        {\n            // Arrange\n            CancellationTokenSource cancellationSource = new CancellationTokenSource();\n            cancellationSource.Cancel();\n\n            HttpActionInvokerTracer tracer = new HttpActionInvokerTracer(new ApiControllerActionInvoker(), new TestTraceWriter());\n\n            // Act\n            var response = ((IHttpActionInvoker)tracer).InvokeActionAsync(_actionContext, cancellationSource.Token);\n\n            // Assert\n            await Assert.ThrowsAsync<TaskCanceledException>(() => response);\n        }\n\n        [Fact]\n        public async Task InvokeActionAsync_Traces_Cancelled_Inner_Task()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpActionInvokerTracer tracer = new HttpActionInvokerTracer(new ApiControllerActionInvoker(), traceWriter);\n            CancellationTokenSource cancellationSource = new CancellationTokenSource();\n            cancellationSource.Cancel();\n\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(_actionContext.Request, TraceCategories.ActionCategory, TraceLevel.Info) { Kind = TraceKind.Begin },\n                new TraceRecord(_actionContext.Request, TraceCategories.ActionCategory, TraceLevel.Warn) { Kind = TraceKind.End }\n            };\n\n            // Act\n            var response = ((IHttpActionInvoker)tracer).InvokeActionAsync(_actionContext, cancellationSource.Token);\n\n            // Assert\n            await Assert.ThrowsAsync<TaskCanceledException>(() => response);\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public async Task InvokeActionAsync_Returns_Faulted_Inner_Task()\n        {\n            // Arrange\n            Mock<ApiControllerActionInvoker> mockActionInvoker = new Mock<ApiControllerActionInvoker>() { CallBase = true };\n            InvalidOperationException expectedException = new InvalidOperationException(\"test message\");\n            TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>(null);\n            tcs.TrySetException(expectedException);\n            mockActionInvoker.Setup(\n                a => a.InvokeActionAsync(It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>())).Returns(tcs.Task);\n            HttpActionInvokerTracer tracer = new HttpActionInvokerTracer(mockActionInvoker.Object, new TestTraceWriter());\n\n            // Act & Assert\n            var exception = await Assert.ThrowsAsync<InvalidOperationException>(\n                () => ((IHttpActionInvoker)tracer).InvokeActionAsync(_actionContext, CancellationToken.None));\n\n            Assert.Equal(expectedException.Message, exception.Message);\n        }\n\n        [Fact]\n        public async Task InvokeActionAsync_Traces_Faulted_Inner_Task()\n        {\n            // Arrange\n            Mock<ApiControllerActionInvoker> mockActionInvoker = new Mock<ApiControllerActionInvoker>() { CallBase = true };\n            InvalidOperationException expectedException = new InvalidOperationException(\"test message\");\n            TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>(null);\n            tcs.TrySetException(expectedException);\n            mockActionInvoker.Setup(\n                a => a.InvokeActionAsync(It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>())).Returns(tcs.Task);\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpActionInvokerTracer tracer = new HttpActionInvokerTracer(mockActionInvoker.Object, traceWriter);\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(_actionContext.Request, TraceCategories.ActionCategory, TraceLevel.Info) { Kind = TraceKind.Begin },\n                new TraceRecord(_actionContext.Request, TraceCategories.ActionCategory, TraceLevel.Error) { Kind = TraceKind.End }\n            };\n\n            // Act\n            var response = ((IHttpActionInvoker)tracer).InvokeActionAsync(_actionContext, CancellationToken.None);\n\n            // Assert\n            await Assert.ThrowsAsync<InvalidOperationException>(() => response);\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Equal(expectedException, traceWriter.Traces[1].Exception);\n        }\n\n        [Fact]\n        public void InvokeActionAsync_Throws_When_ActionContext_Is_Null()\n        {\n            // Arrange\n            HttpActionInvokerTracer tracer = new HttpActionInvokerTracer(new ApiControllerActionInvoker(), new TestTraceWriter());\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => ((IHttpActionInvoker)tracer).InvokeActionAsync(null, CancellationToken.None),\n                \"actionContext\");\n        }\n\n        [Fact]\n        public void InvokeActionAsync_Throws_Exception_Thrown_From_Inner()\n        {\n            // Arrange\n            InvalidOperationException expectedException = new InvalidOperationException(\"test message\");\n            Mock<ApiControllerActionInvoker> mockActionInvoker = new Mock<ApiControllerActionInvoker>() { CallBase = true };\n            mockActionInvoker.Setup(\n                a => a.InvokeActionAsync(It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>())).Throws(expectedException);\n            HttpActionInvokerTracer tracer = new HttpActionInvokerTracer(mockActionInvoker.Object, new TestTraceWriter());\n\n            // Act & Assert\n            InvalidOperationException thrownException = Assert.Throws<InvalidOperationException>(\n                () => ((IHttpActionInvoker)tracer).InvokeActionAsync(_actionContext, CancellationToken.None)\n            );\n\n            // Assert\n            Assert.Equal(expectedException, thrownException);\n        }\n\n        [Fact]\n        public void InvokeActionAsync_Traces_Exception_Thrown_From_Inner()\n        {\n            // Arrange\n            InvalidOperationException expectedException = new InvalidOperationException(\"test message\");\n            Mock<ApiControllerActionInvoker> mockActionInvoker = new Mock<ApiControllerActionInvoker>() { CallBase = true };\n            mockActionInvoker.Setup(\n                a => a.InvokeActionAsync(It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>())).Throws(expectedException);\n\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpActionInvokerTracer tracer = new HttpActionInvokerTracer(mockActionInvoker.Object, traceWriter);\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(_actionContext.Request, TraceCategories.ActionCategory, TraceLevel.Info) { Kind = TraceKind.Begin },\n                new TraceRecord(_actionContext.Request, TraceCategories.ActionCategory, TraceLevel.Error) { Kind = TraceKind.End }\n            };\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => ((IHttpActionInvoker)tracer).InvokeActionAsync(_actionContext, CancellationToken.None)\n            );\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Equal(expectedException, traceWriter.Traces[1].Exception);\n        }\n\n        [Fact]\n        public void Inner_Property_On_HttpActionInvokerTracer_Returns_IHttpActionInvoker()\n        {\n            // Arrange\n            IHttpActionInvoker expectedInner = new Mock<IHttpActionInvoker>().Object;\n            HttpActionInvokerTracer productUnderTest = new HttpActionInvokerTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            IHttpActionInvoker actualInner = productUnderTest.Inner;\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n\n        [Fact]\n        public void Decorator_GetInner_On_HttpActionInvokerTracer_Returns_IHttpActionInvoker()\n        {\n            // Arrange\n            IHttpActionInvoker expectedInner = new Mock<IHttpActionInvoker>().Object;\n            HttpActionInvokerTracer productUnderTest = new HttpActionInvokerTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            IHttpActionInvoker actualInner = Decorator.GetInner(productUnderTest as IHttpActionInvoker);\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/HttpActionSelectorTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Services;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class HttpActionSelectorTracerTest\n    {\n        private Mock<HttpActionDescriptor> _mockActionDescriptor;\n        private HttpActionContext _actionContext;\n        private HttpControllerContext _controllerContext;\n        private HttpControllerDescriptor _controllerDescriptor;\n\n        public HttpActionSelectorTracerTest()\n        {\n            _mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };\n            _mockActionDescriptor.Setup(a => a.ActionName).Returns(\"test\");\n            _mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0]));\n\n            _controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), \"controller\", typeof(ApiController));\n\n            _controllerContext = ContextUtil.CreateControllerContext(request: new HttpRequestMessage());\n            _controllerContext.ControllerDescriptor = _controllerDescriptor;\n\n            _actionContext = ContextUtil.CreateActionContext(_controllerContext, actionDescriptor: _mockActionDescriptor.Object);\n        }\n\n        [Fact]\n        public void SelectAction_Traces_And_Returns_ActionDescriptor_Tracer()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            Mock<IHttpActionSelector> mockSelector = new Mock<IHttpActionSelector>();\n            mockSelector.Setup(s => s.SelectAction(_controllerContext)).Returns(_mockActionDescriptor.Object);\n            HttpActionSelectorTracer tracer = new HttpActionSelectorTracer(mockSelector.Object, traceWriter);\n\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(_actionContext.Request, TraceCategories.ActionCategory, TraceLevel.Info) { Kind = TraceKind.Begin },\n                new TraceRecord(_actionContext.Request, TraceCategories.ActionCategory, TraceLevel.Info) { Kind = TraceKind.End }\n            };\n\n            // Act\n            HttpActionDescriptor selectedActionDescriptor = ((IHttpActionSelector)tracer).SelectAction(_controllerContext);\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.IsAssignableFrom<HttpActionDescriptorTracer>(selectedActionDescriptor);\n        }\n\n        [Fact]\n        public void SelectAction_DoesNotWrapHttpActionDescriptorTracer()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            Mock<IHttpActionSelector> mockSelector = new Mock<IHttpActionSelector>();\n\n            HttpActionDescriptorTracer actionDescriptorTracer = new HttpActionDescriptorTracer(_controllerContext, _mockActionDescriptor.Object, traceWriter);\n            mockSelector.Setup(s => s.SelectAction(_controllerContext)).Returns(actionDescriptorTracer);\n            HttpActionSelectorTracer tracer = new HttpActionSelectorTracer(mockSelector.Object, traceWriter);\n\n            // Act\n            HttpActionDescriptor selectedActionDescriptor = ((IHttpActionSelector)tracer).SelectAction(_controllerContext);\n\n            // Assert\n            Assert.Same(actionDescriptorTracer, selectedActionDescriptor);\n        }\n\n        [Fact]\n        public void SelectAction_Traces_And_Throws_Exception_Thrown_From_Inner()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            Mock<IHttpActionSelector> mockSelector = new Mock<IHttpActionSelector>();\n            InvalidOperationException exception = new InvalidOperationException();\n            mockSelector.Setup(s => s.SelectAction(_controllerContext)).Throws(exception);\n            HttpActionSelectorTracer tracer = new HttpActionSelectorTracer(mockSelector.Object, traceWriter);\n\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(_actionContext.Request, TraceCategories.ActionCategory, TraceLevel.Info) { Kind = TraceKind.Begin },\n                new TraceRecord(_actionContext.Request, TraceCategories.ActionCategory, TraceLevel.Error) { Kind = TraceKind.End }\n            };\n\n            // Act\n            Exception thrown = Assert.Throws<InvalidOperationException>(() => ((IHttpActionSelector)tracer).SelectAction(_controllerContext));\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(exception, thrown);\n            Assert.Same(exception, traceWriter.Traces[1].Exception);\n        }\n\n        [Fact]\n        public void Inner_Property_On_HttpActionSelectorTracer_Returns_IHttpActionSelector()\n        {\n            // Arrange\n            IHttpActionSelector expectedInner = new Mock<IHttpActionSelector>().Object;\n            HttpActionSelectorTracer productUnderTest = new HttpActionSelectorTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            IHttpActionSelector actualInner = productUnderTest.Inner;\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n\n        [Fact]\n        public void Decorator_GetInner_On_HttpActionSelectorTracer_Returns_IHttpActionSelector()\n        {\n            // Arrange\n            IHttpActionSelector expectedInner = new Mock<IHttpActionSelector>().Object;\n            HttpActionSelectorTracer productUnderTest = new HttpActionSelectorTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            IHttpActionSelector actualInner = Decorator.GetInner(productUnderTest as IHttpActionSelector);\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/HttpControllerActivatorTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.Services;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class HttpControllerActivatorTracerTest\n    {\n        [Fact]\n        public void Create_Invokes_Inner_And_Traces()\n        {\n            // Arrange\n            Mock<ApiController> mockController = new Mock<ApiController>();\n            Mock<IHttpControllerActivator> mockActivator = new Mock<IHttpControllerActivator>() { CallBase = true };\n            mockActivator.Setup(b => b.Create(It.IsAny<HttpRequestMessage>(), It.IsAny<HttpControllerDescriptor>(), It.IsAny<Type>())).Returns(mockController.Object);\n            HttpRequestMessage request = new HttpRequestMessage();\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpControllerActivatorTracer tracer = new HttpControllerActivatorTracer(mockActivator.Object, traceWriter);\n\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"Create\" },\n                new TraceRecord(request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = \"Create\" }\n            };\n\n            // Act\n            IHttpController createdController = ((IHttpControllerActivator)tracer).Create(request, controllerDescriptor: null, controllerType: mockController.Object.GetType());\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.IsAssignableFrom<HttpControllerTracer>(createdController);\n        }\n\n        [Fact]\n        public void Create_Throws_And_Traces_When_Inner_Throws()\n        {\n            // Arrange\n            Mock<ApiController> mockController = new Mock<ApiController>();\n            Mock<IHttpControllerActivator> mockActivator = new Mock<IHttpControllerActivator>() { CallBase = true };\n            InvalidOperationException exception = new InvalidOperationException(\"test\");\n            mockActivator.Setup(b => b.Create(It.IsAny<HttpRequestMessage>(), It.IsAny<HttpControllerDescriptor>(), It.IsAny<Type>())).Throws(exception);\n            HttpRequestMessage request = new HttpRequestMessage();\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpControllerActivatorTracer tracer = new HttpControllerActivatorTracer(mockActivator.Object, traceWriter);\n\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"Create\" },\n                new TraceRecord(request, TraceCategories.ControllersCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = \"Create\" }\n            };\n\n            // Act & Assert\n            Exception thrown = Assert.Throws<InvalidOperationException>(() => ((IHttpControllerActivator)tracer).Create(request, controllerDescriptor: null, controllerType: mockController.Object.GetType()));\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(exception, thrown);\n            Assert.Same(exception, traceWriter.Traces[1].Exception);\n        }\n\n        [Fact]\n        public void Inner_Property_On_HttpControllerActivatorTracer_Returns_IHttpControllerActivator()\n        {\n            // Arrange\n            IHttpControllerActivator expectedInner = new Mock<IHttpControllerActivator>().Object;\n            HttpControllerActivatorTracer productUnderTest = new HttpControllerActivatorTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            IHttpControllerActivator actualInner = productUnderTest.Inner;\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n\n        [Fact]\n        public void Decorator_GetInner_On_HttpControllerActivatorTracer_Returns_IHttpControllerActivator()\n        {\n            // Arrange\n            IHttpControllerActivator expectedInner = new Mock<IHttpControllerActivator>().Object;\n            HttpControllerActivatorTracer productUnderTest = new HttpControllerActivatorTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            IHttpControllerActivator actualInner = Decorator.GetInner(productUnderTest as IHttpControllerActivator);\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/HttpControllerDescriptorTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Services;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class HttpControllerDescriptorTracerTest\n    {\n        private static readonly HttpControllerContext _controllerContext = ContextUtil.CreateControllerContext(instance: _controller);\n        private static readonly HttpRequestMessage _request = _controllerContext.Request;\n        private static readonly IHttpController _controller = new Mock<IHttpController>().Object;\n        private static readonly InvalidOperationException _exception = new InvalidOperationException(\"test\");\n\n        [Fact]\n        public void Properties_Calls_Inner()\n        {\n            // Arrange\n            ConcurrentDictionary<object, object> properties = new ConcurrentDictionary<object, object>();\n            Mock<HttpControllerDescriptor> mockControllerDescriptor = new Mock<HttpControllerDescriptor>();\n            mockControllerDescriptor.Setup(d => d.Properties).Returns(properties).Verifiable();\n            HttpControllerDescriptorTracer tracer = GetHttpControllerDescriptorTracer(mockControllerDescriptor.Object, new TestTraceWriter());\n\n            // Act and Assert\n            Assert.Same(properties, tracer.Properties);\n            mockControllerDescriptor.Verify();\n        }\n\n        [Fact]\n        public void CreateController_Invokes_Inner_And_Traces()\n        {\n            // Arrange\n            Mock<HttpControllerDescriptor> mockControllerDescriptor = CreateMockControllerDescriptor();\n            mockControllerDescriptor.Setup(b => b.CreateController(It.IsAny<HttpRequestMessage>())).Returns(_controller);\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpControllerDescriptorTracer tracer = GetHttpControllerDescriptorTracer(mockControllerDescriptor.Object, traceWriter);\n\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(_request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"CreateController\" },\n                new TraceRecord(_request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = \"CreateController\" }\n            };\n\n            // Act\n            IHttpController controller = tracer.CreateController(_request);\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.IsAssignableFrom<HttpControllerTracer>(controller);\n        }\n\n        [Fact]\n        public void CreateController_Throws_And_Traces_When_Inner_Throws()\n        {\n            // Arrange\n            Mock<HttpControllerDescriptor> mockControllerDescriptor = CreateMockControllerDescriptor();\n            mockControllerDescriptor.Setup(b => b.CreateController(It.IsAny<HttpRequestMessage>())).Throws(_exception);\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpControllerDescriptorTracer tracer = GetHttpControllerDescriptorTracer(mockControllerDescriptor.Object, traceWriter);\n\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(_request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"CreateController\" },\n                new TraceRecord(_request, TraceCategories.ControllersCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = \"CreateController\" }\n            };\n\n            // Act\n            Exception thrown = Assert.Throws<InvalidOperationException>(() => tracer.CreateController(_request));\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(_exception, thrown);\n            Assert.Same(_exception, traceWriter.Traces[1].Exception);\n        }\n\n        [Fact]\n        public void Inner_Property_On_HttpControllerDescriptorTracer_Returns_HttpControllerDescriptor()\n        {\n            // Arrange\n            HttpControllerDescriptor expectedInner = BuildHttpControllerDescriptor(_controller);\n\n            HttpControllerDescriptorTracer productUnderTest = new HttpControllerDescriptorTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            HttpControllerDescriptor actualInner = productUnderTest.Inner;\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n\n        [Fact]\n        public void Decorator_GetInner_On_HttpControllerDescriptorTracer_Returns_HttpControllerDescriptor()\n        {\n            // Arrange\n            HttpControllerDescriptor expectedInner = BuildHttpControllerDescriptor(_controller);\n\n            HttpControllerDescriptorTracer productUnderTest = new HttpControllerDescriptorTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            HttpControllerDescriptor actualInner = Decorator.GetInner(productUnderTest as HttpControllerDescriptor);\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n\n        [Fact]\n        public void Decorator_DoesNotCauseControllerInitializationToHappenAgainAndAgain()\n        {\n            // Arrange\n            int raisedCount = 0;\n            RaiseWhenInitializedAttribute.Initialized += delegate { ++raisedCount; };\n\n            var descriptor = new HttpControllerDescriptor(new HttpConfiguration(), \"my\", typeof(MyController));\n            Assert.Equal(1, raisedCount);\n\n            // Act\n            new HttpControllerDescriptorTracer(descriptor, new TestTraceWriter());\n            new HttpControllerDescriptorTracer(descriptor, new TestTraceWriter());\n            new HttpControllerDescriptorTracer(descriptor, new TestTraceWriter());\n\n            // Assert\n            Assert.Equal(1, raisedCount);\n        }\n\n        private static HttpControllerDescriptor BuildHttpControllerDescriptor(IHttpController controller, string controllerName = \"AnyController\", HttpConfiguration httpConfiguration = null)\n        {\n            HttpControllerDescriptor expectedInner = new Mock<HttpControllerDescriptor>().Object;\n            expectedInner.ControllerName = controllerName;\n            expectedInner.ControllerType = controller.GetType();\n            expectedInner.Configuration = httpConfiguration ?? new HttpConfiguration();\n            return expectedInner;\n        }\n\n        private static HttpControllerDescriptorTracer GetHttpControllerDescriptorTracer(HttpControllerDescriptor controllerDescriptor, ITraceWriter traceWriter)\n        {\n            if (controllerDescriptor.Configuration == null)\n            {\n                controllerDescriptor.Configuration = new HttpConfiguration();\n            }\n\n            if (controllerDescriptor.ControllerName == null)\n            {\n                controllerDescriptor.ControllerName = \"AnyController\";\n            }\n\n            if (controllerDescriptor.ControllerType == null)\n            {\n                controllerDescriptor.ControllerType = _controller.GetType();\n            }\n\n            return new HttpControllerDescriptorTracer(\n                innerDescriptor: controllerDescriptor,\n                traceWriter: traceWriter);\n        }\n\n        private static Mock<HttpControllerDescriptor> CreateMockControllerDescriptor()\n        {\n            Mock<HttpControllerDescriptor> mockControllerDescriptor = new Mock<HttpControllerDescriptor>(_controllerContext.Configuration, \"AnyController\", _controller.GetType());\n            return mockControllerDescriptor;\n        }\n\n        private class RaiseWhenInitializedAttribute : Attribute, IControllerConfiguration\n        {\n            public static event EventHandler Initialized;\n            public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)\n            {\n                Initialized(this, EventArgs.Empty);\n            }\n        }\n\n        [RaiseWhenInitialized]\n        private class MyController : ApiController\n        {\n            public string Foo()\n            {\n                return \"bar\";\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/HttpControllerSelectorTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.Services;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class HttpControllerSelectorTracerTest\n    {\n        private static readonly IHttpController _controller = new Mock<IHttpController>().Object;\n        private static readonly HttpControllerContext _controllerContext = ContextUtil.CreateControllerContext(instance: _controller);\n        private static readonly HttpRequestMessage _request = _controllerContext.Request;\n\n        [Fact]\n        public void SelectController_Invokes_Inner_And_Traces()\n        {\n            // Arrange\n            Mock<HttpControllerDescriptor> mockControllerDescriptor = new Mock<HttpControllerDescriptor>(_controllerContext.Configuration, \"AnyController\", _controller.GetType());\n            Mock<IHttpControllerSelector> mockSelector = new Mock<IHttpControllerSelector>();\n            mockSelector.Setup(b => b.SelectController(It.IsAny<HttpRequestMessage>())).Returns(mockControllerDescriptor.Object);\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpControllerSelectorTracer tracer = new HttpControllerSelectorTracer(mockSelector.Object, traceWriter);\n\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(_request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"SelectController\" },\n                new TraceRecord(_request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = \"SelectController\" }\n            };\n\n            // Act\n            HttpControllerDescriptor controllerDescriptor = ((IHttpControllerSelector)tracer).SelectController(_request);\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.IsAssignableFrom<HttpControllerDescriptorTracer>(controllerDescriptor);\n        }\n\n        [Fact]\n        public void SelectController_Throws_And_Traces_When_Inner_Throws()\n        {\n            // Arrange\n            Mock<IHttpControllerSelector> mockSelector = new Mock<IHttpControllerSelector>();\n            InvalidOperationException exception = new InvalidOperationException(\"test\");\n            mockSelector.Setup(b => b.SelectController(It.IsAny<HttpRequestMessage>())).Throws(exception);\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpControllerSelectorTracer tracer = new HttpControllerSelectorTracer(mockSelector.Object, traceWriter);\n\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(_request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"SelectController\" },\n                new TraceRecord(_request, TraceCategories.ControllersCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = \"SelectController\" }\n            };\n\n            // Act\n            Exception thrown = Assert.Throws<InvalidOperationException>(() => ((IHttpControllerSelector)tracer).SelectController(_request));\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(exception, thrown);\n            Assert.Same(exception, traceWriter.Traces[1].Exception);\n        }\n\n        [Fact]\n        public void Inner_Property_On_HttpControllerSelectorTracer_Returns_IHttpControllerSelector()\n        {\n            // Arrange\n            IHttpControllerSelector expectedInner = new Mock<IHttpControllerSelector>().Object;\n            HttpControllerSelectorTracer productUnderTest = new HttpControllerSelectorTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            IHttpControllerSelector actualInner = productUnderTest.Inner;\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n\n        [Fact]\n        public void Decorator_GetInner_On_HttpControllerSelectorTracer_Returns_IHttpControllerSelector()\n        {\n            // Arrange\n            IHttpControllerSelector expectedInner = new Mock<IHttpControllerSelector>().Object;\n            HttpControllerSelectorTracer productUnderTest = new HttpControllerSelectorTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            IHttpControllerSelector actualInner = Decorator.GetInner(productUnderTest as IHttpControllerSelector);\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/HttpControllerTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.Services;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class HttpControllerTracerTest\n    {\n        private Mock<HttpActionDescriptor> _mockActionDescriptor;\n        private HttpControllerDescriptor _controllerDescriptor;\n\n        public HttpControllerTracerTest()\n        {\n            _mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };\n            _mockActionDescriptor.Setup(a => a.ActionName).Returns(\"test\");\n            _mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0]));\n\n            _controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), \"controller\", typeof(ApiController));\n        }\n\n        [Fact]\n        public void Dispose_TracesAndInvokesInnerDisposeWhenControllerIsDisposable()\n        {\n            // Arrange\n            var mockController = new Mock<IHttpController>();\n            var mockDisposable = mockController.As<IDisposable>();\n            var request = new HttpRequestMessage();\n            var traceWriter = new TestTraceWriter();\n            var tracer = new HttpControllerTracer(request, mockController.Object, traceWriter);\n            var expectedTraces = new[]\n            {\n                new TraceRecord(request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"Dispose\" },\n                new TraceRecord(request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = \"Dispose\" }\n            };\n\n            // Act\n            ((IDisposable)tracer).Dispose();\n\n            // Assert\n            Assert.Equal(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            mockDisposable.Verify(d => d.Dispose(), Times.Once());\n        }\n\n        [Fact]\n        public void Dispose_DoesNotTraceWhenControllerIsNotDisposable()\n        {\n            // Arrange\n            var mockController = new Mock<IHttpController>();\n            var request = new HttpRequestMessage();\n            var traceWriter = new TestTraceWriter();\n            var tracer = new HttpControllerTracer(request, mockController.Object, traceWriter);\n\n            // Act\n            ((IDisposable)tracer).Dispose();\n\n            // Assert\n            Assert.Empty(traceWriter.Traces);\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_RemovesInnerControllerFromReleaseListAndAddsItselfInstead()\n        {\n            // Arrange\n            var request = new HttpRequestMessage();\n            var context = ContextUtil.CreateControllerContext(request: request);\n            var mockController = new Mock<IHttpController>();\n            var mockDisposable = mockController.As<IDisposable>();\n            mockController.Setup(c => c.ExecuteAsync(context, CancellationToken.None))\n                          .Callback<HttpControllerContext, CancellationToken>((cc, ct) => cc.Request.RegisterForDispose(mockDisposable.Object))\n                          .Returns(() => Task.FromResult(new HttpResponseMessage()))\n                          .Verifiable();\n            context.ControllerDescriptor = _controllerDescriptor;\n            context.Controller = mockController.Object;\n            var traceWriter = new TestTraceWriter();\n            var tracer = new HttpControllerTracer(request, mockController.Object, traceWriter);\n\n            // Act\n            var controller = (IHttpController)tracer;\n            await controller.ExecuteAsync(context, CancellationToken.None);\n\n            // Assert\n            IEnumerable<IDisposable> disposables = (IEnumerable<IDisposable>)request.Properties[HttpPropertyKeys.DisposableRequestResourcesKey];\n            Assert.Contains(tracer, disposables);\n            Assert.DoesNotContain(mockDisposable.Object, disposables);\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Invokes_Inner_And_Traces()\n        {\n            // Arrange\n            HttpResponseMessage response = new HttpResponseMessage();\n            Mock<ApiController> mockController = new Mock<ApiController>() { CallBase = true };\n            mockController.Setup(b => b.ExecuteAsync(It.IsAny<HttpControllerContext>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult<HttpResponseMessage>(response));\n\n            HttpRequestMessage request = new HttpRequestMessage();\n            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(request: request);\n            controllerContext.ControllerDescriptor = _controllerDescriptor;\n            controllerContext.Controller = mockController.Object;\n\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(controllerContext, actionDescriptor: _mockActionDescriptor.Object);\n\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpControllerTracer tracer = new HttpControllerTracer(request, mockController.Object, traceWriter);\n\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(actionContext.Request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.Begin },\n                new TraceRecord(actionContext.Request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.End }\n            };\n\n            // Act\n            var task = ((IHttpController)tracer).ExecuteAsync(controllerContext, CancellationToken.None);\n            HttpResponseMessage actualResponse = await task;\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(response, actualResponse);\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_Faults_And_Traces_When_Inner_Faults()\n        {\n            // Arrange\n            InvalidOperationException exception = new InvalidOperationException();\n            TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();\n            tcs.TrySetException(exception);\n            Mock<ApiController> mockController = new Mock<ApiController>() { CallBase = true };\n            mockController.Setup(b => b.ExecuteAsync(It.IsAny<HttpControllerContext>(), It.IsAny<CancellationToken>())).Returns(tcs.Task);\n\n            HttpRequestMessage request = new HttpRequestMessage();\n            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(request: request);\n            controllerContext.ControllerDescriptor = _controllerDescriptor;\n            controllerContext.Controller = mockController.Object;\n\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(controllerContext, actionDescriptor: _mockActionDescriptor.Object);\n\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpControllerTracer tracer = new HttpControllerTracer(request, mockController.Object, traceWriter);\n\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(actionContext.Request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.Begin },\n                new TraceRecord(actionContext.Request, TraceCategories.ControllersCategory, TraceLevel.Error) { Kind = TraceKind.End }\n            };\n\n            // Act\n            Exception thrown = await Assert.ThrowsAsync<InvalidOperationException>(() => ((IHttpController)tracer).ExecuteAsync(controllerContext, CancellationToken.None));\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(exception, thrown);\n            Assert.Same(exception, traceWriter.Traces[1].Exception);\n        }\n\n        [Fact]\n        public async Task ExecuteAsync_IsCancelled_And_Traces_When_Inner_IsCancelled()\n        {\n            // Arrange\n            Mock<ApiController> mockController = new Mock<ApiController>() { CallBase = true };\n            mockController.Setup(b => b.ExecuteAsync(It.IsAny<HttpControllerContext>(), It.IsAny<CancellationToken>())).Returns(TaskHelpers.Canceled<HttpResponseMessage>());\n\n            HttpRequestMessage request = new HttpRequestMessage();\n            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(request: request);\n            controllerContext.ControllerDescriptor = _controllerDescriptor;\n            controllerContext.Controller = mockController.Object;\n\n            HttpActionContext actionContext = ContextUtil.CreateActionContext(controllerContext, actionDescriptor: _mockActionDescriptor.Object);\n\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpControllerTracer tracer = new HttpControllerTracer(request, mockController.Object, traceWriter);\n\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(actionContext.Request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.Begin },\n                new TraceRecord(actionContext.Request, TraceCategories.ControllersCategory, TraceLevel.Warn) { Kind = TraceKind.End }\n            };\n\n            // Act\n            Task task = ((IHttpController)tracer).ExecuteAsync(controllerContext, CancellationToken.None);\n            Exception thrown = await Assert.ThrowsAsync<TaskCanceledException>(() => task);\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void Inner_Property_On_HttpControllerTracer_Returns_IHttpController()\n        {\n            // Arrange\n            IHttpController expectedInner = new Mock<IHttpController>().Object;\n            HttpControllerTracer productUnderTest = new HttpControllerTracer(new HttpRequestMessage(), expectedInner, new TestTraceWriter());\n\n            // Act\n            IHttpController actualInner = productUnderTest.Inner;\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n\n        [Fact]\n        public void Decorator_GetInner_On_HttpControllerTracer_Returns_IHttpController()\n        {\n            // Arrange\n            IHttpController expectedInner = new Mock<IHttpController>().Object;\n            HttpControllerTracer productUnderTest = new HttpControllerTracer(new HttpRequestMessage(), expectedInner, new TestTraceWriter());\n\n            // Act\n            IHttpController actualInner = Decorator.GetInner(productUnderTest as IHttpController);\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/HttpParameterBindingTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Metadata.Providers;\nusing System.Web.Http.ModelBinding;\nusing System.Web.Http.Services;\nusing System.Web.Http.ValueProviders;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class HttpParameterBindingTracerTest\n    {\n        [Fact]\n        public void ErrorMessage_Calls_Inner()\n        {\n            // Arrange\n            Mock<HttpParameterDescriptor> mockParamDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true };\n            mockParamDescriptor.Setup(d => d.ParameterName).Returns(\"paramName\");\n            mockParamDescriptor.Setup(d => d.ParameterType).Returns(typeof(string));\n            Mock<HttpParameterBinding> mockBinding = new Mock<HttpParameterBinding>(mockParamDescriptor.Object);\n            mockBinding.Setup(b => b.ErrorMessage).Returns(\"errorMessage\").Verifiable();\n            HttpParameterBindingTracer tracer = new HttpParameterBindingTracer(mockBinding.Object, new TestTraceWriter());\n\n            // Act & Assert\n            Assert.Equal(\"errorMessage\", tracer.ErrorMessage);\n            mockBinding.Verify();\n        }\n\n        [Fact]\n        public void WillReadBody_Calls_Inner()\n        {\n            // Arrange\n            Mock<HttpParameterDescriptor> mockParamDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true };\n            mockParamDescriptor.Setup(d => d.ParameterName).Returns(\"paramName\");\n            mockParamDescriptor.Setup(d => d.ParameterType).Returns(typeof(string));\n            Mock<HttpParameterBinding> mockBinding = new Mock<HttpParameterBinding>(mockParamDescriptor.Object);\n            mockBinding.Setup(b => b.WillReadBody).Returns(true).Verifiable();\n            HttpParameterBindingTracer tracer = new HttpParameterBindingTracer(mockBinding.Object, new TestTraceWriter());\n\n            // Act & Assert\n            Assert.True(tracer.WillReadBody);\n            mockBinding.Verify();\n        }\n\n        [Fact]\n        public void Descriptor_Uses_Inners()\n        {\n            // Arrange\n            Mock<HttpParameterDescriptor> mockParamDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true };\n            mockParamDescriptor.Setup(d => d.ParameterName).Returns(\"paramName\");\n            mockParamDescriptor.Setup(d => d.ParameterType).Returns(typeof(string));\n            Mock<HttpParameterBinding> mockBinding = new Mock<HttpParameterBinding>(mockParamDescriptor.Object) { CallBase = true };\n            HttpParameterBindingTracer tracer = new HttpParameterBindingTracer(mockBinding.Object, new TestTraceWriter());\n\n            // Act & Assert\n            Assert.Same(mockBinding.Object.Descriptor, tracer.Descriptor);\n        }\n\n        [Fact]\n        public void ValueProviderFactories_Calls_Inner()\n        {\n            // Arrange\n            Mock<HttpParameterDescriptor> mockParamDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true };\n            mockParamDescriptor.Setup(d => d.ParameterName).Returns(\"paramName\");\n            mockParamDescriptor.Setup(d => d.ParameterType).Returns(typeof(string));\n            Mock<IModelBinder> mockModelBinder = new Mock<IModelBinder>() { CallBase = true };\n            Mock<ValueProviderFactory> mockValueProviderFactory = new Mock<ValueProviderFactory>() { CallBase = true };\n\n            List<ValueProviderFactory> expectedFactories = new List<ValueProviderFactory>\n            {\n                mockValueProviderFactory.Object\n            };\n\n            ModelBinderParameterBinding binding = new ModelBinderParameterBinding(mockParamDescriptor.Object, mockModelBinder.Object, expectedFactories);\n            HttpParameterBindingTracer tracer = new HttpParameterBindingTracer(binding, new TestTraceWriter());\n\n            // Act\n            List<ValueProviderFactory> actualFactories = tracer.ValueProviderFactories.ToList();\n\n            // Assert\n            Assert.Equal(expectedFactories, actualFactories);\n        }\n\n        [Fact]\n        public void ValueProviderFactories_Returns_Empty_Enumerable_When_Not_IValueProviderParameterBinding()\n        {\n            // Arrange\n            Mock<HttpParameterDescriptor> mockParamDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true };\n            mockParamDescriptor.Setup(d => d.ParameterName).Returns(\"paramName\");\n            mockParamDescriptor.Setup(d => d.ParameterType).Returns(typeof(string));\n            Mock<HttpParameterBinding> mockBinding = new Mock<HttpParameterBinding>(mockParamDescriptor.Object);\n            HttpParameterBindingTracer tracer = new HttpParameterBindingTracer(mockBinding.Object, new TestTraceWriter());\n\n            // Act\n            ValueProviderFactory[] actualFactories = tracer.ValueProviderFactories.ToArray();\n\n            // Assert\n            Assert.Empty(actualFactories);\n        }\n\n        [Fact]\n        public async Task ExecuteBindingAsync_Traces_And_Invokes_Inner()\n        {\n            // Arrange\n            Mock<HttpParameterDescriptor> mockParamDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true };\n            mockParamDescriptor.Setup(d => d.ParameterName).Returns(\"paramName\");\n            mockParamDescriptor.Setup(d => d.ParameterType).Returns(typeof(string));\n            Mock<HttpParameterBinding> mockBinding = new Mock<HttpParameterBinding>(mockParamDescriptor.Object) { CallBase = true };\n            bool innerInvoked = false;\n            mockBinding.Setup(\n                b =>\n                b.ExecuteBindingAsync(It.IsAny<ModelMetadataProvider>(), It.IsAny<HttpActionContext>(),\n                                      It.IsAny<CancellationToken>())).Returns(TaskHelpers.Completed()).Callback(() => innerInvoked = true);\n\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpParameterBindingTracer tracer = new HttpParameterBindingTracer(mockBinding.Object, traceWriter);\n            HttpActionContext actionContext = ContextUtil.CreateActionContext();\n            ModelMetadataProvider metadataProvider = new EmptyModelMetadataProvider();\n\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"ExecuteBindingAsync\" },\n                new TraceRecord(actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = \"ExecuteBindingAsync\" }\n            };\n\n            // Act\n            await tracer.ExecuteBindingAsync(metadataProvider, actionContext, CancellationToken.None);\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.True(innerInvoked);\n        }\n\n        [Fact]\n        public void ExecuteBindingAsync_Traces_And_Throws_When_Inner_Throws()\n        {\n            // Arrange\n            Mock<HttpParameterDescriptor> mockParamDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true };\n            mockParamDescriptor.Setup(d => d.ParameterName).Returns(\"paramName\");\n            mockParamDescriptor.Setup(d => d.ParameterType).Returns(typeof(string));\n            Mock<HttpParameterBinding> mockBinding = new Mock<HttpParameterBinding>(mockParamDescriptor.Object) { CallBase = true };\n            InvalidOperationException exception = new InvalidOperationException(\"test\");\n            mockBinding.Setup(\n                b =>\n                b.ExecuteBindingAsync(It.IsAny<ModelMetadataProvider>(), It.IsAny<HttpActionContext>(),\n                                      It.IsAny<CancellationToken>())).Throws(exception);\n\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpParameterBindingTracer tracer = new HttpParameterBindingTracer(mockBinding.Object, traceWriter);\n            HttpActionContext actionContext = ContextUtil.CreateActionContext();\n            ModelMetadataProvider metadataProvider = new EmptyModelMetadataProvider();\n\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"ExecuteBindingAsync\" },\n                new TraceRecord(actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = \"ExecuteBindingAsync\" }\n            };\n\n            // Act & Assert\n            Exception thrown = Assert.Throws<InvalidOperationException>(() => tracer.ExecuteBindingAsync(metadataProvider, actionContext, CancellationToken.None));\n\n            // Assert\n            Assert.Same(exception, thrown);\n            Assert.Same(exception, traceWriter.Traces[1].Exception);\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public async Task ExecuteBindingAsync_Traces_And_Faults_When_Inner_Faults()\n        {\n            // Arrange\n\n            Mock<HttpParameterDescriptor> mockParamDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true };\n            mockParamDescriptor.Setup(d => d.ParameterName).Returns(\"paramName\");\n            mockParamDescriptor.Setup(d => d.ParameterType).Returns(typeof(string));\n            Mock<HttpParameterBinding> mockBinding = new Mock<HttpParameterBinding>(mockParamDescriptor.Object) { CallBase = true };\n            InvalidOperationException exception = new InvalidOperationException(\"test\");\n            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();\n            tcs.TrySetException(exception);\n\n            mockBinding.Setup(\n                b =>\n                b.ExecuteBindingAsync(It.IsAny<ModelMetadataProvider>(), It.IsAny<HttpActionContext>(),\n                                      It.IsAny<CancellationToken>())).Returns(tcs.Task);\n\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpParameterBindingTracer tracer = new HttpParameterBindingTracer(mockBinding.Object, traceWriter);\n            HttpActionContext actionContext = ContextUtil.CreateActionContext();\n            ModelMetadataProvider metadataProvider = new EmptyModelMetadataProvider();\n\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"ExecuteBindingAsync\" },\n                new TraceRecord(actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = \"ExecuteBindingAsync\" }\n            };\n\n            // Act & Assert\n            Task task = tracer.ExecuteBindingAsync(metadataProvider, actionContext, CancellationToken.None);\n\n            // Assert\n            Exception thrown = await Assert.ThrowsAsync<InvalidOperationException>(() => task);\n            Assert.Same(exception, thrown);\n            Assert.Same(exception, traceWriter.Traces[1].Exception);\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void Inner_Property_On_HttpParameterBindingTracer_Returns_HttpParameterBinding()\n        {\n            // Arrange\n            Mock<HttpParameterDescriptor> mockParamDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true };\n            mockParamDescriptor.Setup(d => d.ParameterName).Returns(\"paramName\");\n            mockParamDescriptor.Setup(d => d.ParameterType).Returns(typeof(string));\n            HttpParameterBinding expectedInner = new Mock<HttpParameterBinding>(mockParamDescriptor.Object).Object;\n            HttpParameterBindingTracer productUnderTest = new HttpParameterBindingTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            HttpParameterBinding actualInner = productUnderTest.Inner;\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n\n        [Fact]\n        public void Decorator_GetInner_On_HttpParameterBindingTracer_Returns_HttpParameterBinding()\n        {\n            // Arrange\n            Mock<HttpParameterDescriptor> mockParamDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true };\n            mockParamDescriptor.Setup(d => d.ParameterName).Returns(\"paramName\");\n            mockParamDescriptor.Setup(d => d.ParameterType).Returns(typeof(string));\n            HttpParameterBinding expectedInner = new Mock<HttpParameterBinding>(mockParamDescriptor.Object).Object;\n            HttpParameterBindingTracer productUnderTest = new HttpParameterBindingTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            HttpParameterBinding actualInner = Decorator.GetInner(productUnderTest as HttpParameterBinding);\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/JsonMediaTypeFormatterTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Threading.Tasks;\nusing System.Web.Http.Services;\nusing Microsoft.TestCommon;\nusing Moq;\nusing Newtonsoft.Json;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class JsonMediaTypeFormatterTracerTest : ReadWriteMediaTypeFormatterTracerTestBase<JsonMediaTypeFormatter>\n    {\n        public override MediaTypeFormatter CreateTracer(JsonMediaTypeFormatter formatter, HttpRequestMessage request, ITraceWriter traceWriter)\n        {\n            return new JsonMediaTypeFormatterTracer(formatter, traceWriter, request);\n        }\n\n        [Fact]\n        public void UseDataContractJsonSerializer_Uses_Inners()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            JsonMediaTypeFormatter innerFormatter = new JsonMediaTypeFormatter();\n            innerFormatter.UseDataContractJsonSerializer = !innerFormatter.UseDataContractJsonSerializer;\n            JsonMediaTypeFormatterTracer tracer = new JsonMediaTypeFormatterTracer(innerFormatter, new TestTraceWriter(), request);\n\n            // Act & Assert\n            Assert.Equal(innerFormatter.UseDataContractJsonSerializer, tracer.UseDataContractJsonSerializer);\n        }\n\n        [Fact]\n        public void MaxDepth_Uses_Inners()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            JsonMediaTypeFormatter innerFormatter = new JsonMediaTypeFormatter();\n            innerFormatter.MaxDepth = innerFormatter.MaxDepth + 1;\n            JsonMediaTypeFormatterTracer tracer = new JsonMediaTypeFormatterTracer(innerFormatter, new TestTraceWriter(), request);\n\n            // Act & Assert\n            Assert.Equal(innerFormatter.MaxDepth, tracer.MaxDepth);\n        }\n\n        [Fact]\n        public void Indent_Uses_Inners()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            JsonMediaTypeFormatter innerFormatter = new JsonMediaTypeFormatter();\n            innerFormatter.Indent = !innerFormatter.Indent;\n            JsonMediaTypeFormatterTracer tracer = new JsonMediaTypeFormatterTracer(innerFormatter, new TestTraceWriter(), request);\n\n            // Act & Assert\n            Assert.Equal(innerFormatter.Indent, tracer.Indent);\n        }\n\n        [Fact]\n        public void SerializerSettings_Uses_Inners()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            JsonSerializerSettings serializerSettings = new JsonSerializerSettings();\n            JsonMediaTypeFormatter innerFormatter = new JsonMediaTypeFormatter() { SerializerSettings = serializerSettings };\n            JsonMediaTypeFormatterTracer tracer = new JsonMediaTypeFormatterTracer(innerFormatter, new TestTraceWriter(), request);\n\n            // Act & Assert\n            Assert.Same(innerFormatter.SerializerSettings, tracer.SerializerSettings);\n        }\n\n        [Fact]\n        public void Inner_Property_On_JsonMediaTypeFormatterTracerTest_Returns_JsonMediaTypeFormatter()\n        {\n            // Arrange\n            JsonMediaTypeFormatter expectedInner = new JsonMediaTypeFormatter();\n            JsonMediaTypeFormatterTracer productUnderTest = new JsonMediaTypeFormatterTracer(expectedInner, new TestTraceWriter(), new HttpRequestMessage());\n\n            // Act\n            JsonMediaTypeFormatter actualInner = productUnderTest.Inner;\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n\n        [Fact]\n        public void Decorator_GetInner_On_JsonMediaTypeFormatterTracerTest_Returns_JsonMediaTypeFormatter()\n        {\n            // Arrange\n            JsonMediaTypeFormatter expectedInner = new JsonMediaTypeFormatter();\n            JsonMediaTypeFormatterTracer productUnderTest = new JsonMediaTypeFormatterTracer(expectedInner, new TestTraceWriter(), new HttpRequestMessage());\n\n            // Act\n            JsonMediaTypeFormatter actualInner = Decorator.GetInner(productUnderTest as JsonMediaTypeFormatter);\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n\n        public static IEnumerable<object[]> RequestBodies\n        {\n            get\n            {\n                HttpRequestMessage request = new HttpRequestMessage();\n                return new[]\n                {\n                    new object[]\n                    {\n                        new List<TraceRecord>\n                        {\n                            new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info)\n                            {\n                                Kind = TraceKind.Begin,\n                                Operation = \"ReadFromStreamAsync\",\n                                Message = \"Type='SampleType', content-type='application/json'\",\n                                Operator = \"JsonMediaTypeFormatter\"\n                            },\n                            new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info)\n                            {\n                                Kind = TraceKind.End,\n                                Operation = \"ReadFromStreamAsync\",\n                                Message = \"Value read='System.Net.Http.Formatting.SampleType'\",\n                                Operator = \"JsonMediaTypeFormatter\"\n                            },\n                        },\n                        request,\n                        \"{\\\"Number\\\":42}\"\n                    },\n                    new object[]\n                    {\n                        new List<TraceRecord>\n                        {\n                            new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info)\n                            {\n                                Kind = TraceKind.Begin,\n                                Operation = \"ReadFromStreamAsync\",\n                                Message = \"Type='SampleType', content-type='application/json'\",\n                                Operator = \"JsonMediaTypeFormatter\"\n                            },\n                            new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Error)\n                            {\n                                Kind = TraceKind.Trace,\n                                Operation = \"ReadFromStreamAsync\",\n                                Operator = \"JsonMediaTypeFormatter\",\n                                Exception = new JsonReaderException(\n                                    \"Unterminated string. Expected delimiter: \\\". Path '', line 1, position 12.\")\n                            },\n                            new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info)\n                            {\n                                Kind = TraceKind.End,\n                                Operation = \"ReadFromStreamAsync\",\n                                Message = \"Value read='null'\",\n                                Operator = \"JsonMediaTypeFormatter\"\n                            },\n                        },\n                        request,\n                        \"{\\\"Number:42}\"\n                    }\n                };\n            }\n        }\n\n        [Theory]\n        [ReplaceCulture]\n        [PropertyData(\"RequestBodies\")]\n        public async Task ReadFromStreamAsync_LogErrorFromJsonRequestBody(IList<TraceRecord> expectedTraces,\n                                                                    HttpRequestMessage request,\n                                                                    string requestBody)\n        {\n            // Arrange\n            var formatter = new JsonMediaTypeFormatter();\n            formatter.UseDataContractJsonSerializer = false;\n            HttpContent content = new StringContent(requestBody);\n            content.Headers.ContentType = MediaTypeHeaderValue.Parse(\"application/json\");\n            var loggerMock = new Mock<IFormatterLogger>();\n            loggerMock.Setup(l => l.LogError(It.IsAny<string>(), It.IsAny<Exception>()));\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            var tracer = new MediaTypeFormatterTracer(formatter, traceWriter, request);\n\n            // Act\n            await tracer.ReadFromStreamAsync(typeof(SampleType),\n                                       await content.ReadAsStreamAsync(),\n                                       content, loggerMock.Object\n                                      );\n\n            // Assert\n            // Error must always be marked as handled at ReadFromStream in BaseJsonMediaTypeFormatters,\n            // so it would ﻿not propagate to here.\n            // Note that regarding the exception's comparison in the record we only compare its message,\n            // because we cannot get the exact exception and message would be enough for logging.\n            Assert.Equal<TraceRecord>(expectedTraces,\n                                      traceWriter.Traces,\n                                      new TraceRecordComparer() { IgnoreExceptionReference = true });\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/MediaTypeFormatterTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics.Contracts;\nusing System.IO;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Services;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class MediaTypeFormatterTracerTest\n    {\n        public static TheoryDataSet<MediaTypeFormatter> AllKnownFormatters\n        {\n            get\n            {\n                return new TheoryDataSet<MediaTypeFormatter>\n                {\n                    new XmlMediaTypeFormatter(), \n                    new JsonMediaTypeFormatter(),\n                    new FormUrlEncodedMediaTypeFormatter(),\n                    new Mock<BufferedMediaTypeFormatter>().Object\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"AllKnownFormatters\")]\n        public void CreateTracer_Returns_Tracing_Formatter(MediaTypeFormatter formatter)\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n\n            // Act\n            MediaTypeFormatter tracingFormatter = MediaTypeFormatterTracer.CreateTracer(formatter, new TestTraceWriter(), request);\n\n            // Assert\n            IFormatterTracer tracer = Assert.IsAssignableFrom<IFormatterTracer>(tracingFormatter);\n            Assert.Same(formatter, tracer.InnerFormatter);\n        }\n\n        [Theory]\n        [PropertyData(\"AllKnownFormatters\")]\n        public void Inner_Property_On_All_MediaTypeFormatterTracers_Returns_Object_Of_Type_MediaTypeFormatter(MediaTypeFormatter formatter)\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            MediaTypeFormatter formatterTracer = MediaTypeFormatterTracer.CreateTracer(formatter, new TestTraceWriter(), request);\n\n            // Act\n            MediaTypeFormatter innerFormatter = (formatterTracer as IDecorator<MediaTypeFormatter>).Inner;\n\n            // Assert\n            Assert.Same(formatter, innerFormatter);\n        }\n\n        [Theory]\n        [PropertyData(\"AllKnownFormatters\")]\n        public void Decorator_GetInner_On_All_MediaTypeFormatterTracers_Returns_Object_Of_Type_MediaTypeFormatter(MediaTypeFormatter formatter)\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            MediaTypeFormatter formatterTracer = MediaTypeFormatterTracer.CreateTracer(formatter, new TestTraceWriter(), request);\n\n            // Act\n            MediaTypeFormatter innerFormatter = Decorator.GetInner(formatterTracer);\n\n            // Assert\n            Assert.Same(formatter, innerFormatter);\n        }\n\n        [Fact]\n        public async Task ReadFromStream_Traces()\n        {\n            // Arrange\n            string contentType = \"text/plain\";\n            object value = new object();\n            CustomMediaTypeFormatter formatter = new CustomMediaTypeFormatter(value);\n            formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(contentType));\n\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.Content = new StringContent(\"42\", Encoding.Default, contentType);\n            MediaTypeFormatterTracer tracer = new MediaTypeFormatterTracer(formatter, traceWriter, request);\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"ReadFromStreamAsync\" },\n                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = \"ReadFromStreamAsync\" }\n            };\n\n            // Act\n            object valueReturned = await request.Content.ReadAsAsync<object>(new[] { tracer });\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Equal(value, valueReturned);\n        }\n\n        [Fact]\n        public async Task WriteToStream_Traces()\n        {\n            // Arrange\n            object value = new object();\n            CustomMediaTypeFormatter formatter = new CustomMediaTypeFormatter(value);\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            MediaTypeFormatterTracer tracer = new MediaTypeFormatterTracer(formatter, traceWriter, request);\n            request.Content = new ObjectContent<object>(value, tracer);\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"WriteToStreamAsync\" },\n                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = \"WriteToStreamAsync\" }\n            };\n\n            // Act\n            await request.Content.CopyToAsync(new MemoryStream());\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void FormatterLoggerTracer_LogErrorException()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            string operatorName = this.GetType().Name;\n            string operationName = \"FormatterLoggerTracer_LogErrorException\";\n            var loggerMock = new Mock<IFormatterLogger>();\n            loggerMock.Setup(o => o.LogError(It.IsAny<string>(), It.IsAny<Exception>()));\n            IFormatterLogger tracer = new FormatterLoggerTraceWrapper(loggerMock.Object, traceWriter, request, operatorName, operationName);\n            Exception exception = new Exception(\"message\");\n            string errorPath = \"errorPath\";\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Error) \n                {\n                    Kind = TraceKind.Trace, Operation = operationName, Exception = exception, Operator = operatorName\n                },\n            };\n\n            // Act\n            tracer.LogError(errorPath, exception);\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void FormatterLoggerTracer_LogErrorMessage()\n        {\n            // Arrange\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            string operatorName = this.GetType().Name;\n            string operationName = \"FormatterLoggerTracer_LogErrorMessage\";\n            var loggerMock = new Mock<IFormatterLogger>();\n            loggerMock.Setup(o => o.LogError(It.IsAny<string>(), It.IsAny<string>()));\n            IFormatterLogger tracer = new FormatterLoggerTraceWrapper(loggerMock.Object, traceWriter, request, operatorName, operationName);\n            string errorMessage = \"errorMessage\";\n            string errorPath = \"errorPath\";\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Error)\n                {\n                    Kind = TraceKind.Trace, Operation = operationName, Message = errorMessage, Operator = operatorName \n                },\n            };\n\n            // Act\n            tracer.LogError(errorPath, errorMessage);\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        private class CustomMediaTypeFormatter : MediaTypeFormatter\n        {\n            private object _result;\n\n            public CustomMediaTypeFormatter(object result)\n            {\n                Contract.Assert(result != null);\n                _result = result;\n            }\n\n            public override bool CanReadType(Type type)\n            {\n                return true;\n            }\n\n            public override bool CanWriteType(Type type)\n            {\n                return true;\n            }\n\n            public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content,\n                IFormatterLogger formatterLogger, CancellationToken cancellationToken)\n            {\n                return Task.FromResult(_result);\n            }\n\n            public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content,\n                TransportContext transportContext, CancellationToken cancellationToken)\n            {\n                return Task.FromResult(_result);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/MediaTypeFormatterTracerTestBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Text;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    // Abstract base test class for MediaTypeFormatter tracers.\n    // This tests core functionality common to all MediaTypeFormatters.\n    // It does not test read/write paths because BufferedMediaTypeFormatter\n    // has sealed those methods, and they cannot be overridden by mocks.\n    // Refer to ReadWriteMediaTypeFormatterTracerTestBase for read/write tests.\n    public abstract class MediaTypeFormatterTracerTestBase<TFormatter> \n        where TFormatter: MediaTypeFormatter\n    {\n        public abstract MediaTypeFormatter CreateTracer(TFormatter formatter, HttpRequestMessage request, ITraceWriter traceWriter);\n\n        [Fact]\n        public void CanReadType_Calls_Inner()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            Type randomType = typeof(string);\n            Mock<TFormatter> mockFormatter = new Mock<TFormatter>() { CallBase = true };\n\n            mockFormatter.Setup(f => f.CanReadType(randomType)).Returns(true).Verifiable();\n            MediaTypeFormatter tracer = CreateTracer(mockFormatter.Object, request, new TestTraceWriter());\n\n            // Act\n            bool valueReturned = tracer.CanReadType(randomType);\n\n            // Assert\n            Assert.True(valueReturned);\n            mockFormatter.Verify();\n        }\n\n        [Fact]\n        public void CanWriteType_Calls_Inner()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            Type randomType = typeof(string);\n            Mock<TFormatter> mockFormatter = new Mock<TFormatter>() { CallBase = true };\n            mockFormatter.Setup(f => f.CanWriteType(randomType)).Returns(true).Verifiable();\n            MediaTypeFormatter tracer = CreateTracer(mockFormatter.Object, request, new TestTraceWriter());\n\n            // Act\n            bool valueReturned = tracer.CanWriteType(randomType);\n\n            // Assert\n            Assert.True(valueReturned);\n            mockFormatter.Verify();\n        }\n\n        [Fact]\n        public void GetPerRequestFormatterInstance_Calls_Inner_And_Wraps_Tracer_Around_It()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            Type randomType = typeof(string);\n            MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue(\"plain/text\");\n            Mock<TFormatter> mockFormatter = new Mock<TFormatter>() { CallBase = true };\n            MediaTypeFormatter formatterObject = mockFormatter.Object;\n\n            mockFormatter.Setup(f => f.GetPerRequestFormatterInstance(randomType, request, mediaType)).Returns(formatterObject).Verifiable();\n            MediaTypeFormatter tracer = CreateTracer(mockFormatter.Object, request, new TestTraceWriter());\n\n            // Act\n            MediaTypeFormatter valueReturned = tracer.GetPerRequestFormatterInstance(randomType, request, mediaType);\n\n            // Assert\n            IFormatterTracer tracerReturned = Assert.IsAssignableFrom<IFormatterTracer>(valueReturned);\n            Assert.Same(formatterObject, tracerReturned.InnerFormatter);\n            mockFormatter.Verify();\n        }\n\n        [Fact]\n        public void SetDefaultContentHeaders_Calls_Inner()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            Type randomType = typeof(string);\n            HttpContentHeaders contentHeaders = new StringContent(\"\").Headers;\n            MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue(\"plain/text\");\n            Mock<TFormatter> mockFormatter = new Mock<TFormatter>() { CallBase = true };\n            MediaTypeFormatter formatterObject = mockFormatter.Object;\n\n            mockFormatter.Setup(f => f.SetDefaultContentHeaders(randomType, contentHeaders, mediaType)).Verifiable();\n            MediaTypeFormatter tracer = CreateTracer(mockFormatter.Object, request, new TestTraceWriter());\n\n            // Act\n            tracer.SetDefaultContentHeaders(randomType, contentHeaders, mediaType);\n\n            // Assert\n            mockFormatter.Verify();\n        }\n\n        [Fact]\n        public void SupportedMediaTypes_Uses_Inners()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue(\"text/fake\");\n            Mock<TFormatter> mockFormatter = new Mock<TFormatter>() { CallBase = true };\n            MediaTypeFormatter innerFormatter = mockFormatter.Object;\n            innerFormatter.SupportedMediaTypes.Clear();\n            innerFormatter.SupportedMediaTypes.Add(mediaType);\n            MediaTypeFormatter tracer = CreateTracer(mockFormatter.Object, request, new TestTraceWriter());\n\n            // Act & Assert\n            Assert.Same(innerFormatter.SupportedMediaTypes, tracer.SupportedMediaTypes);\n        }\n\n        [Fact]\n        public void MediaTypeMappings_Uses_Inners()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue(\"text/fake\");\n            Mock<MediaTypeMapping> mockMapping = new Mock<MediaTypeMapping>(mediaType);\n            Mock<TFormatter> mockFormatter = new Mock<TFormatter>() { CallBase = true };\n            MediaTypeFormatter innerFormatter = mockFormatter.Object;\n            innerFormatter.MediaTypeMappings.Clear();\n            innerFormatter.MediaTypeMappings.Add(mockMapping.Object);\n            MediaTypeFormatter tracer = CreateTracer(mockFormatter.Object, request, new TestTraceWriter());\n\n            // Act & Assert\n            Assert.Same(innerFormatter.MediaTypeMappings, tracer.MediaTypeMappings);\n        }\n\n        [Fact]\n        public void SupportedEncodings_Uses_Inners()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            Mock<Encoding> mockEncoding = new Mock<Encoding>();\n            Mock<TFormatter> mockFormatter = new Mock<TFormatter>() { CallBase = true };\n            MediaTypeFormatter innerFormatter = mockFormatter.Object;\n            innerFormatter.SupportedEncodings.Clear();\n            innerFormatter.SupportedEncodings.Add(mockEncoding.Object);\n            MediaTypeFormatter tracer = CreateTracer(mockFormatter.Object, request, new TestTraceWriter());\n\n            // Act & Assert\n            Assert.Same(innerFormatter.SupportedEncodings, tracer.SupportedEncodings);\n        }\n\n        [Fact]\n        public void RequiredMemberSelector_Uses_Inners()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            Mock<IRequiredMemberSelector> mockSelector = new Mock<IRequiredMemberSelector>();\n            Mock<TFormatter> mockFormatter = new Mock<TFormatter>() { CallBase = true };\n            MediaTypeFormatter innerFormatter = mockFormatter.Object;\n            innerFormatter.RequiredMemberSelector = mockSelector.Object;\n            MediaTypeFormatter tracer = CreateTracer(mockFormatter.Object, request, new TestTraceWriter());\n\n            // Act & Assert\n            Assert.Same(innerFormatter.RequiredMemberSelector, tracer.RequiredMemberSelector);\n        }\n\n        [Fact]\n        public void GetPerRequestFormatterInstance_SupportedMediaTypes_Uses_Inners()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            Type randomType = typeof(string);\n            MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue(\"text/fake\");\n            Mock<TFormatter> mockFormatter = new Mock<TFormatter>() { CallBase = true };\n            MediaTypeFormatter innerFormatter = mockFormatter.Object;\n            MediaTypeFormatter tracer = CreateTracer(mockFormatter.Object, request, new TestTraceWriter());\n            tracer.SupportedMediaTypes.Add(mediaType);\n\n            // Act\n            MediaTypeFormatter valueReturned = innerFormatter.GetPerRequestFormatterInstance(randomType, request, mediaType);\n\n            // Assert\n            Assert.Same(tracer.SupportedMediaTypes, valueReturned.SupportedMediaTypes);\n            Assert.Same(tracer.SupportedMediaTypes, innerFormatter.SupportedMediaTypes);\n        }\n\n        [Fact]\n        public void GetPerRequestFormatterInstance_MediaTypeMappings_Uses_Inners()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            Type randomType = typeof(string);\n            MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue(\"text/fake\");\n            Mock<MediaTypeMapping> mockMapping = new Mock<MediaTypeMapping>(mediaType);\n            Mock<TFormatter> mockFormatter = new Mock<TFormatter>() { CallBase = true };\n            MediaTypeFormatter innerFormatter = mockFormatter.Object;\n            MediaTypeFormatter tracer = CreateTracer(mockFormatter.Object, request, new TestTraceWriter());\n            tracer.MediaTypeMappings.Add(mockMapping.Object);\n\n            // Act\n            MediaTypeFormatter valueReturned = innerFormatter.GetPerRequestFormatterInstance(randomType, request, mediaType);\n\n            // Assert\n            Assert.Same(tracer.MediaTypeMappings, valueReturned.MediaTypeMappings);\n            Assert.Same(tracer.MediaTypeMappings, innerFormatter.MediaTypeMappings);\n        }\n\n        [Fact]\n        public void GetPerRequestFormatterInstance_SupportedEncodings_Uses_Inners()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            Type randomType = typeof(string);\n            MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue(\"text/fake\");\n            Mock<Encoding> mockEncoding = new Mock<Encoding>();\n            Mock<TFormatter> mockFormatter = new Mock<TFormatter>() { CallBase = true };\n            MediaTypeFormatter innerFormatter = mockFormatter.Object;\n            MediaTypeFormatter tracer = CreateTracer(mockFormatter.Object, request, new TestTraceWriter());\n            tracer.SupportedEncodings.Add(mockEncoding.Object);\n\n            // Act\n            MediaTypeFormatter valueReturned = innerFormatter.GetPerRequestFormatterInstance(randomType, request, mediaType);\n\n            // Assert\n            Assert.Same(tracer.SupportedEncodings, valueReturned.SupportedEncodings);\n            Assert.Same(tracer.SupportedEncodings, innerFormatter.SupportedEncodings);\n        }\n\n        [Fact]\n        public void GetPerRequestFormatterInstance_RequiredMemberSelector_Uses_Inners()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            Type randomType = typeof(string);\n            MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue(\"text/fake\");\n            Mock<IRequiredMemberSelector> mockSelector = new Mock<IRequiredMemberSelector>();\n            Mock<TFormatter> mockFormatter = new Mock<TFormatter>() { CallBase = true };\n            MediaTypeFormatter innerFormatter = mockFormatter.Object;\n            MediaTypeFormatter tracer = CreateTracer(mockFormatter.Object, request, new TestTraceWriter());\n            tracer.RequiredMemberSelector = mockSelector.Object;\n\n            // Act\n            MediaTypeFormatter valueReturned = innerFormatter.GetPerRequestFormatterInstance(randomType, request, mediaType);\n\n            // Assert\n            Assert.Same(tracer.RequiredMemberSelector, valueReturned.RequiredMemberSelector);\n            Assert.Same(tracer.RequiredMemberSelector, innerFormatter.RequiredMemberSelector);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/MessageHandlerTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Reflection;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Services;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class MessageHandlerTracerTest\n    {\n        [Fact]\n        public async Task SendAsync_Traces_And_Invokes_Inner()\n        {\n            // Arrange\n            HttpResponseMessage response = new HttpResponseMessage();\n            MockDelegatingHandler mockHandler = new MockDelegatingHandler((rqst, cancellation) =>\n                                                 Task.FromResult<HttpResponseMessage>(response));\n\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            MessageHandlerTracer tracer = new MessageHandlerTracer(mockHandler, traceWriter);\n            MockHttpMessageHandler mockInnerHandler = new MockHttpMessageHandler((rqst, cancellation) =>\n                                     Task.FromResult<HttpResponseMessage>(response));\n            tracer.InnerHandler = mockInnerHandler;\n\n            HttpRequestMessage request = new HttpRequestMessage();\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, TraceCategories.MessageHandlersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"SendAsync\" },\n                new TraceRecord(request, TraceCategories.MessageHandlersCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = \"SendAsync\" }\n            };\n\n            MethodInfo method = typeof(DelegatingHandler).GetMethod(\"SendAsync\",\n                                                                     BindingFlags.Public | BindingFlags.NonPublic |\n                                                                     BindingFlags.Instance);\n\n            // Act\n            Task<HttpResponseMessage> task = method.Invoke(tracer, new object[] { request, CancellationToken.None }) as Task<HttpResponseMessage>;\n            HttpResponseMessage actualResponse = await task;\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(response, actualResponse);\n        }\n\n        [Fact]\n        public void SendAsync_Traces_And_Throws_When_Inner_Throws()\n        {\n            // Arrange\n            InvalidOperationException exception = new InvalidOperationException(\"test\");\n            MockDelegatingHandler mockHandler = new MockDelegatingHandler((rqst, cancellation) => { throw exception; });\n\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            MessageHandlerTracer tracer = new MessageHandlerTracer(mockHandler, traceWriter);\n\n            // DelegatingHandlers require an InnerHandler to run.  We create a mock one to simulate what\n            // would happen when a DelegatingHandler executing after the tracer throws.\n            MockHttpMessageHandler mockInnerHandler = new MockHttpMessageHandler((rqst, cancellation) => { throw exception; });\n            tracer.InnerHandler = mockInnerHandler;\n\n            HttpRequestMessage request = new HttpRequestMessage();\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, TraceCategories.MessageHandlersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"SendAsync\" },\n                new TraceRecord(request, TraceCategories.MessageHandlersCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = \"SendAsync\" }\n            };\n\n            MethodInfo method = typeof(DelegatingHandler).GetMethod(\"SendAsync\",\n                                                                     BindingFlags.Public | BindingFlags.NonPublic |\n                                                                     BindingFlags.Instance);\n\n            // Act\n            Exception thrown =\n                Assert.Throws<TargetInvocationException>(\n                    () => method.Invoke(tracer, new object[] { request, CancellationToken.None }));\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(exception, thrown.InnerException);\n            Assert.Same(exception, traceWriter.Traces[1].Exception);\n        }\n\n        [Fact]\n        public async Task SendAsync_Traces_And_Faults_When_Inner_Faults()\n        {\n            // Arrange\n            InvalidOperationException exception = new InvalidOperationException(\"test\");\n            TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();\n            tcs.TrySetException(exception);\n            MockDelegatingHandler mockHandler = new MockDelegatingHandler((rqst, cancellation) => { return tcs.Task; });\n\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            MessageHandlerTracer tracer = new MessageHandlerTracer(mockHandler, traceWriter);\n\n            // DelegatingHandlers require an InnerHandler to run.  We create a mock one to simulate what\n            // would happen when a DelegatingHandler executing after the tracer returns a Task that throws.\n            MockHttpMessageHandler mockInnerHandler = new MockHttpMessageHandler((rqst, cancellation) => { return tcs.Task; });\n            tracer.InnerHandler = mockInnerHandler;\n\n            HttpRequestMessage request = new HttpRequestMessage();\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, TraceCategories.MessageHandlersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = \"SendAsync\" },\n                new TraceRecord(request, TraceCategories.MessageHandlersCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = \"SendAsync\" }\n            };\n\n            MethodInfo method = typeof(DelegatingHandler).GetMethod(\"SendAsync\",\n                                                                     BindingFlags.Public | BindingFlags.NonPublic |\n                                                                     BindingFlags.Instance);\n\n            // Act\n            Task<HttpResponseMessage> task =\n                method.Invoke(tracer, new object[] { request, CancellationToken.None }) as Task<HttpResponseMessage>;\n\n            // Assert\n            Exception thrown = await Assert.ThrowsAsync<InvalidOperationException>(() => task);\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(exception, thrown);\n            Assert.Same(exception, traceWriter.Traces[1].Exception);\n        }\n\n\n        // DelegatingHandler cannot be mocked with Moq\n        private class MockDelegatingHandler : DelegatingHandler\n        {\n            private Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> _callback;\n\n            public MockDelegatingHandler(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> callback)\n                : base()\n            {\n                _callback = callback;\n            }\n\n            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n            {\n                return _callback(request, cancellationToken);\n            }\n        }\n\n        // HttpMessageHandler cannot be mocked with Moq\n        private class MockHttpMessageHandler : HttpMessageHandler\n        {\n            private Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> _callback;\n\n            public MockHttpMessageHandler(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> callback)\n                : base()\n            {\n                _callback = callback;\n            }\n\n            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n            {\n                return _callback(request, cancellationToken);\n            }\n        }\n\n        [Fact]\n        public void Inner_Property_On_MessageHandlerTracer_Returns_DelegatingHandler()\n        {\n            // Arrange\n            DelegatingHandler expectedInner = new Mock<DelegatingHandler>().Object;\n            MessageHandlerTracer productUnderTest = new MessageHandlerTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            DelegatingHandler actualInner = productUnderTest.Inner;\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n\n        [Fact]\n        public void Decorator_GetInner_On_MessageHandlerTracer_Returns_DelegatingHandler()\n        {\n            // Arrange\n            DelegatingHandler expectedInner = new Mock<DelegatingHandler>().Object;\n            MessageHandlerTracer productUnderTest = new MessageHandlerTracer(expectedInner, new TestTraceWriter());\n\n            // Act\n            DelegatingHandler actualInner = Decorator.GetInner(productUnderTest as DelegatingHandler);\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/OverrideFilterTracerTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.ObjectModel;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Services;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class OverrideFilterTracerTests\n    {\n        [Fact]\n        public void InnerFilter_IsSpecifiedInstance()\n        {\n            // Arrange\n            IOverrideFilter expectedInnerFilter = CreateDummyInnerFilter();\n            ITraceWriter traceWriter = CreateDummyTraceWriter();\n            FilterTracer product = CreateProductUnderTest(expectedInnerFilter, traceWriter);\n\n            // Act\n            IFilter innerFilter = product.InnerFilter;\n\n            // Assert\n            Assert.Same(expectedInnerFilter, innerFilter);\n        }\n\n        [Fact]\n        public void Filter_IsSpecifiedInstance()\n        {\n            // Arrange\n            IOverrideFilter expectedInnerFilter = CreateDummyInnerFilter();\n            ITraceWriter traceWriter = CreateDummyTraceWriter();\n            IDecorator<IOverrideFilter> product = CreateProductUnderTest(expectedInnerFilter, traceWriter);\n\n            // Act\n            IOverrideFilter innerFilter = product.Inner;\n\n            // Assert\n            Assert.Same(expectedInnerFilter, innerFilter);\n        }\n\n        [Fact]\n        public void TraceWriter_IsSpecifiedInstance()\n        {\n            // Arrange\n            IOverrideFilter innerFilter = CreateDummyInnerFilter();\n            ITraceWriter expectedTraceWriter = CreateDummyTraceWriter();\n            FilterTracer product = CreateProductUnderTest(innerFilter, expectedTraceWriter);\n\n            // Act\n            ITraceWriter traceWriter = product.TraceWriter;\n\n            // Assert\n            Assert.Same(expectedTraceWriter, traceWriter);\n        }\n\n        [Fact]\n        public void FiltersToOverride_IsInnerFilterSpecifiedInstance()\n        {\n            // Arrange\n            Type expectedFiltersToOverride = typeof(IActionFilter);\n            IOverrideFilter innerFilter = CreateStubInnerFilter(expectedFiltersToOverride);\n            ITraceWriter traceWriter = CreateDummyTraceWriter();\n            IOverrideFilter product = CreateProductUnderTest(innerFilter, traceWriter);\n\n            // Act\n            Type filtersToOverride = product.FiltersToOverride;\n\n            // Assert\n            Assert.Same(expectedFiltersToOverride, filtersToOverride);\n        }\n\n        private static IOverrideFilter CreateDummyInnerFilter()\n        {\n            return new Mock<IOverrideFilter>(MockBehavior.Strict).Object;\n        }\n\n        private static ITraceWriter CreateDummyTraceWriter()\n        {\n            return new Mock<ITraceWriter>(MockBehavior.Strict).Object;\n        }\n\n        private static OverrideFilterTracer CreateProductUnderTest(IOverrideFilter innerFilter,\n            ITraceWriter traceWriter)\n        {\n            return new OverrideFilterTracer(innerFilter, traceWriter);\n        }\n\n        private static IOverrideFilter CreateStubInnerFilter(Type filtersToOverride)\n        {\n            Mock<IOverrideFilter> mock = new Mock<IOverrideFilter>();\n            mock.Setup(f => f.FiltersToOverride).Returns(filtersToOverride);\n            return mock.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/ReadWriteMediaTypeFormatterTracerTestBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    // This abstract base for MediaTypeFormatterTracers extends the core tests\n    // by adding read/write tests.  BufferedMediaTypeFormatter sealed its async\n    // read and write methods and they cannot be overridden by mocks.  This\n    // abstract base is used for all MediaTypeFormatters whose read/write methods\n    // can be overridden.\n    public abstract class ReadWriteMediaTypeFormatterTracerTestBase<TFormatter> : MediaTypeFormatterTracerTestBase<TFormatter>\n        where TFormatter : MediaTypeFormatter\n    {\n        [Fact]\n        public async Task ReadFromStreamAsync_Traces()\n        {\n            // Arrange\n            Mock<TFormatter> mockFormatter = new Mock<TFormatter>() { CallBase = true };\n            mockFormatter.Setup(f => f.ReadFromStreamAsync(It.IsAny<Type>(), It.IsAny<Stream>(), It.IsAny<HttpContent>(), It.IsAny<IFormatterLogger>()))\n                .Returns(Task.FromResult<object>(\"sampleValue\"));\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.Content = new StringContent(\"\");\n            MediaTypeFormatter tracer = CreateTracer(mockFormatter.Object, request, traceWriter);\n\n            TraceRecord[] expectedTraces = new TraceRecord[]\n                {\n                    new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info)\n                        { Kind = TraceKind.Begin, Operation = \"ReadFromStreamAsync\" },\n                    new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info)\n                        { Kind = TraceKind.End, Operation = \"ReadFromStreamAsync\" }\n                };\n\n            // Act\n            Task<object> task = tracer.ReadFromStreamAsync(typeof(string), new MemoryStream(), request.Content, null);\n            string result = (await task) as string;\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Equal(\"sampleValue\", result);\n        }\n\n        [Fact]\n        public void ReadFromStreamAsync_Traces_And_Throws_When_Inner_Throws()\n        {\n            // Arrange\n            InvalidOperationException exception = new InvalidOperationException(\"test\");\n            Mock<TFormatter> mockFormatter = new Mock<TFormatter>() { CallBase = true };\n            mockFormatter.Setup(\n                f => f.ReadFromStreamAsync(It.IsAny<Type>(), It.IsAny<Stream>(), It.IsAny<HttpContent>(), It.IsAny<IFormatterLogger>())).Throws(exception);\n\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.Content = new StringContent(\"\");\n            MediaTypeFormatter tracer = CreateTracer(mockFormatter.Object, request, traceWriter);\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info)\n                    { Kind = TraceKind.Begin, Operation = \"ReadFromStreamAsync\" },\n                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Error)\n                    { Kind = TraceKind.End, Operation = \"ReadFromStreamAsync\" }\n            };\n\n            // Act\n            Exception thrown = Assert.Throws<InvalidOperationException>(() => tracer.ReadFromStreamAsync(typeof(string), new MemoryStream(), request.Content, null));\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(exception, thrown);\n            Assert.Same(exception, traceWriter.Traces[1].Exception);\n        }\n\n        [Fact]\n        public async Task ReadFromStreamAsync_Traces_And_Faults_When_Inner_Faults()\n        {\n            // Arrange\n            InvalidOperationException exception = new InvalidOperationException(\"test\");\n            Mock<TFormatter> mockFormatter = new Mock<TFormatter>() { CallBase = true };\n            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();\n            tcs.TrySetException(exception);\n\n            mockFormatter.Setup(f => f.ReadFromStreamAsync(It.IsAny<Type>(), It.IsAny<Stream>(), It.IsAny<HttpContent>(), It.IsAny<IFormatterLogger>()))\n                .Returns(tcs.Task);\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.Content = new StringContent(\"\");\n            MediaTypeFormatter tracer = CreateTracer(mockFormatter.Object, request, traceWriter);\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info)\n                    { Kind = TraceKind.Begin, Operation = \"ReadFromStreamAsync\" },\n                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Error)\n                    { Kind = TraceKind.End, Operation = \"ReadFromStreamAsync\" }\n            };\n\n            // Act\n            Task<object> task = tracer.ReadFromStreamAsync(typeof(string), new MemoryStream(), request.Content, null);\n\n            // Assert\n            Exception thrown = await Assert.ThrowsAsync<InvalidOperationException>(() => task);\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(exception, thrown);\n            Assert.Same(exception, traceWriter.Traces[1].Exception);\n        }\n\n        [Fact]\n        public async Task WriteToStreamAsync_Traces()\n        {\n            // Arrange\n            Mock<TFormatter> mockFormatter = new Mock<TFormatter>() { CallBase = true };\n            mockFormatter.Setup(f => f.WriteToStreamAsync(It.IsAny<Type>(), It.IsAny<Object>(), It.IsAny<Stream>(), It.IsAny<HttpContent>(), It.IsAny<TransportContext>()))\n                .Returns(TaskHelpers.Completed());\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.Content = new StringContent(\"\");\n            MediaTypeFormatter tracer = CreateTracer(mockFormatter.Object, request, traceWriter);\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info)\n                    { Kind = TraceKind.Begin, Operation = \"WriteToStreamAsync\" },\n                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info)\n                    { Kind = TraceKind.End, Operation = \"WriteToStreamAsync\" }\n            };\n\n            // Act\n            await tracer.WriteToStreamAsync(typeof(string), \"sampleValue\", new MemoryStream(), request.Content, transportContext: null);\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n        }\n\n        [Fact]\n        public void WriteToStreamAsync_Traces_And_Throws_When_Inner_Throws()\n        {\n            // Arrange\n            InvalidOperationException exception = new InvalidOperationException(\"test\");\n            Mock<TFormatter> mockFormatter = new Mock<TFormatter>() { CallBase = true };\n            mockFormatter.Setup(f => f.WriteToStreamAsync(It.IsAny<Type>(), It.IsAny<Object>(), It.IsAny<Stream>(),\n                                                         It.IsAny<HttpContent>(), It.IsAny<TransportContext>()))\n                .Throws(exception);\n\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.Content = new StringContent(\"\");\n            MediaTypeFormatter tracer = CreateTracer(mockFormatter.Object, request, traceWriter);\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info)\n                    { Kind = TraceKind.Begin, Operation = \"WriteToStreamAsync\" },\n                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Error)\n                    { Kind = TraceKind.End, Operation = \"WriteToStreamAsync\" }\n            };\n\n            // Act\n            Exception thrown = Assert.Throws<InvalidOperationException>(() => tracer.WriteToStreamAsync(typeof(string), \"sampleValue\", new MemoryStream(), request.Content, transportContext: null));\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(exception, thrown);\n            Assert.Same(exception, traceWriter.Traces[1].Exception);\n        }\n\n        [Fact]\n        public async Task WriteToStreamAsync_Traces_And_Faults_When_Inner_Faults()\n        {\n            // Arrange\n            InvalidOperationException exception = new InvalidOperationException(\"test\");\n            Mock<TFormatter> mockFormatter = new Mock<TFormatter>() { CallBase = true };\n            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();\n            tcs.TrySetException(exception);\n\n            mockFormatter.Setup(f => f.WriteToStreamAsync(It.IsAny<Type>(), It.IsAny<Object>(), It.IsAny<Stream>(), It.IsAny<HttpContent>(), It.IsAny<TransportContext>()))\n                .Returns(tcs.Task);\n\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.Content = new StringContent(\"\");\n            MediaTypeFormatter tracer = CreateTracer(mockFormatter.Object, request, traceWriter);\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info)\n                    { Kind = TraceKind.Begin, Operation = \"WriteToStreamAsync\" },\n                new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Error)\n                    { Kind = TraceKind.End, Operation = \"WriteToStreamAsync\" }\n            };\n\n            // Act\n            Task task = tracer.WriteToStreamAsync(typeof(string), \"sampleValue\", new MemoryStream(), request.Content, transportContext: null);\n\n            // Assert\n            Exception thrown = await Assert.ThrowsAsync<InvalidOperationException>(() => task);\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(exception, thrown);\n            Assert.Same(exception, traceWriter.Traces[1].Exception);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/RequestMessageHandlerTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Reflection;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class RequestMessageHandlerTracerTest\n    {\n        [Fact]\n        public async Task SendAsync_Traces_And_Invokes_Inner()\n        {\n            // Arrange\n            HttpResponseMessage response = new HttpResponseMessage();\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            RequestMessageHandlerTracer tracer = new RequestMessageHandlerTracer(traceWriter);\n            MockHttpMessageHandler mockInnerHandler = new MockHttpMessageHandler((rqst, cancellation) =>\n                                     Task.FromResult<HttpResponseMessage>(response));\n            tracer.InnerHandler = mockInnerHandler;\n\n            HttpRequestMessage request = new HttpRequestMessage();\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, TraceCategories.RequestCategory, TraceLevel.Info) { Kind = TraceKind.Begin },\n                new TraceRecord(request, TraceCategories.RequestCategory, TraceLevel.Info) { Kind = TraceKind.End }\n            };\n\n            MethodInfo method = typeof(DelegatingHandler).GetMethod(\"SendAsync\",\n                                                                     BindingFlags.Public | BindingFlags.NonPublic |\n                                                                     BindingFlags.Instance);\n\n            // Act\n            Task<HttpResponseMessage> task = method.Invoke(tracer, new object[] { request, CancellationToken.None }) as Task<HttpResponseMessage>;\n            HttpResponseMessage actualResponse = await task;\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(response, actualResponse);\n        }\n\n        [Fact]\n        public void SendAsync_Traces_And_Throws_When_Inner_Throws()\n        {\n            // Arrange\n            InvalidOperationException exception = new InvalidOperationException(\"test\");\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            RequestMessageHandlerTracer tracer = new RequestMessageHandlerTracer(traceWriter);\n\n            // DelegatingHandlers require an InnerHandler to run.  We create a mock one to simulate what\n            // would happen when a DelegatingHandler executing after the tracer throws.\n            MockHttpMessageHandler mockInnerHandler = new MockHttpMessageHandler((rqst, cancellation) => { throw exception; });\n            tracer.InnerHandler = mockInnerHandler;\n\n            HttpRequestMessage request = new HttpRequestMessage();\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, TraceCategories.RequestCategory, TraceLevel.Info) { Kind = TraceKind.Begin },\n                new TraceRecord(request, TraceCategories.RequestCategory, TraceLevel.Error) { Kind = TraceKind.End }\n            };\n\n            MethodInfo method = typeof(DelegatingHandler).GetMethod(\"SendAsync\",\n                                                                     BindingFlags.Public | BindingFlags.NonPublic |\n                                                                     BindingFlags.Instance);\n\n            // Act\n            Exception thrown =\n                Assert.Throws<TargetInvocationException>(\n                    () => method.Invoke(tracer, new object[] { request, CancellationToken.None }));\n\n            // Assert\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(exception, thrown.InnerException);\n            Assert.Same(exception, traceWriter.Traces[1].Exception);\n        }\n\n        [Fact]\n        public async Task SendAsync_Traces_And_Faults_When_Inner_Faults()\n        {\n            // Arrange\n            InvalidOperationException exception = new InvalidOperationException(\"test\");\n            TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();\n            tcs.TrySetException(exception);\n            TestTraceWriter traceWriter = new TestTraceWriter();\n            RequestMessageHandlerTracer tracer = new RequestMessageHandlerTracer(traceWriter);\n\n            // DelegatingHandlers require an InnerHandler to run.  We create a mock one to simulate what\n            // would happen when a DelegatingHandler executing after the tracer returns a Task that throws.\n            MockHttpMessageHandler mockInnerHandler = new MockHttpMessageHandler((rqst, cancellation) => { return tcs.Task; });\n            tracer.InnerHandler = mockInnerHandler;\n\n            HttpRequestMessage request = new HttpRequestMessage();\n            TraceRecord[] expectedTraces = new TraceRecord[]\n            {\n                new TraceRecord(request, TraceCategories.RequestCategory, TraceLevel.Info) { Kind = TraceKind.Begin },\n                new TraceRecord(request, TraceCategories.RequestCategory, TraceLevel.Error) { Kind = TraceKind.End }\n            };\n\n            MethodInfo method = typeof(DelegatingHandler).GetMethod(\"SendAsync\",\n                                                                     BindingFlags.Public | BindingFlags.NonPublic |\n                                                                     BindingFlags.Instance);\n\n            // Act\n            Task<HttpResponseMessage> task =\n                method.Invoke(tracer, new object[] { request, CancellationToken.None }) as Task<HttpResponseMessage>;\n\n            // Assert\n            Exception thrown = await Assert.ThrowsAsync<InvalidOperationException>(() => task);\n            Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());\n            Assert.Same(exception, thrown);\n            Assert.Same(exception, traceWriter.Traces[1].Exception);\n        }\n\n\n        // DelegatingHandler cannot be mocked with Moq\n        private class MockDelegatingHandler : DelegatingHandler\n        {\n            private Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> _callback;\n\n            public MockDelegatingHandler(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> callback)\n                : base()\n            {\n                _callback = callback;\n            }\n\n            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n            {\n                return _callback(request, cancellationToken);\n            }\n        }\n\n        // HttpMessageHandler cannot be mocked with Moq\n        private class MockHttpMessageHandler : HttpMessageHandler\n        {\n            private Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> _callback;\n\n            public MockHttpMessageHandler(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> callback)\n                : base()\n            {\n                _callback = callback;\n            }\n\n            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n            {\n                return _callback(request, cancellationToken);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Tracing/Tracers/XmlMediaTypeFormatterTracerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Web.Http.Services;\nusing Microsoft.TestCommon;\nusing Moq;\nusing Moq.Protected;\n\nnamespace System.Web.Http.Tracing.Tracers\n{\n    public class XmlMediaTypeFormatterTracerTest : ReadWriteMediaTypeFormatterTracerTestBase<XmlMediaTypeFormatter>\n    {\n        public override MediaTypeFormatter CreateTracer(XmlMediaTypeFormatter formatter, HttpRequestMessage request, ITraceWriter traceWriter)\n        {\n            return new XmlMediaTypeFormatterTracer(formatter, traceWriter, request);\n        }\n\n        [Fact]\n        public void UseXmlSerializer_Uses_Inners()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            XmlMediaTypeFormatter innerFormatter = new XmlMediaTypeFormatter();\n            innerFormatter.UseXmlSerializer = !innerFormatter.UseXmlSerializer;\n            XmlMediaTypeFormatterTracer tracer = new XmlMediaTypeFormatterTracer(innerFormatter, new TestTraceWriter(), request);\n\n            // Act & Assert\n            Assert.Equal(innerFormatter.UseXmlSerializer, tracer.UseXmlSerializer);\n        }\n\n        [Fact]\n        public void MaxDepth_Uses_Inners()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            XmlMediaTypeFormatter innerFormatter = new XmlMediaTypeFormatter();\n            innerFormatter.MaxDepth = innerFormatter.MaxDepth + 1;\n            XmlMediaTypeFormatterTracer tracer = new XmlMediaTypeFormatterTracer(innerFormatter, new TestTraceWriter(), request);\n\n            // Act & Assert\n            Assert.Equal(innerFormatter.MaxDepth, tracer.MaxDepth);\n        }\n\n        [Fact]\n        public void Indent_Uses_Inners()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            XmlMediaTypeFormatter innerFormatter = new XmlMediaTypeFormatter();\n            innerFormatter.Indent = !innerFormatter.Indent;\n            XmlMediaTypeFormatterTracer tracer = new XmlMediaTypeFormatterTracer(innerFormatter, new TestTraceWriter(), request);\n\n            // Act & Assert\n            Assert.Equal(innerFormatter.Indent, tracer.Indent);\n        }\n\n        [Fact]\n        public void Inner_Property_On_XmlMediaTypeFormatterTracer_Returns_XmlMediaTypeFormatter()\n        {\n            // Arrange\n            XmlMediaTypeFormatter expectedInner = new XmlMediaTypeFormatter();\n            XmlMediaTypeFormatterTracer productUnderTest = new XmlMediaTypeFormatterTracer(expectedInner, new TestTraceWriter(), new HttpRequestMessage());\n\n            // Act\n            XmlMediaTypeFormatter actualInner = productUnderTest.Inner;\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n\n        [Fact]\n        public void Decorator_GetInner_On_XmlMediaTypeFormatterTracer_Returns_XmlMediaTypeFormatter()\n        {\n            // Arrange\n            XmlMediaTypeFormatter expectedInner = new XmlMediaTypeFormatter();\n            XmlMediaTypeFormatterTracer productUnderTest = new XmlMediaTypeFormatterTracer(expectedInner, new TestTraceWriter(), new HttpRequestMessage());\n\n            // Act\n            XmlMediaTypeFormatter actualInner = Decorator.GetInner(productUnderTest as XmlMediaTypeFormatter);\n\n            // Assert\n            Assert.Same(expectedInner, actualInner);\n        }\n\n        [Fact]\n        public void CreateXmlReader_Calls_CreateXmlReaderOnInner()\n        {\n            // Arrange\n            Stream stream = new Mock<Stream>().Object;\n            HttpContent content = new StringContent(\"\");\n            Mock<XmlMediaTypeFormatter> formatter = new Mock<XmlMediaTypeFormatter>();\n            XmlMediaTypeFormatterTracer tracer = CreateTracer(formatter.Object);\n\n            // Act\n            tracer.InvokeCreateXmlReader(stream, content);\n\n            // Assert\n            formatter.Protected().Verify(\"CreateXmlReader\", Times.Once(), stream, content);\n        }\n\n        [Fact]\n        public void CreateXmlWriter_Calls_CreateXmlWriterOnInner()\n        {\n            // Arrange\n            Stream stream = new Mock<Stream>().Object;\n            HttpContent content = new StringContent(\"\");\n            Mock<XmlMediaTypeFormatter> formatter = new Mock<XmlMediaTypeFormatter>();\n            XmlMediaTypeFormatterTracer tracer = CreateTracer(formatter.Object);\n\n            // Act\n            tracer.InvokeCreateXmlWriter(stream, content);\n\n            // Assert\n            formatter.Protected().Verify(\"CreateXmlWriter\", Times.Once(), stream, content);\n        }\n\n        [Fact]\n        public void GetDeserializer_Calls_GetDeserializerOnInner()\n        {\n            // Arrange\n            Type type = new Mock<Type>().Object;\n            HttpContent content = new StringContent(\"\");\n            Mock<XmlMediaTypeFormatter> formatter = new Mock<XmlMediaTypeFormatter>();\n            XmlMediaTypeFormatterTracer tracer = CreateTracer(formatter.Object);\n\n            // Act\n            tracer.InvokeGetDeserializer(type, content);\n\n            // Assert\n            formatter.Protected().Verify(\"GetDeserializer\", Times.Once(), type, content);\n        }\n\n        [Fact]\n        public void GetSerializer_Calls_GetSerializerOnInner()\n        {\n            // Arrange\n            Type type = new Mock<Type>().Object;\n            object value = new object();\n            HttpContent content = new StringContent(\"\");\n            Mock<XmlMediaTypeFormatter> formatter = new Mock<XmlMediaTypeFormatter>();\n            XmlMediaTypeFormatterTracer tracer = CreateTracer(formatter.Object);\n\n            // Act\n            tracer.InvokeGetSerializer(type, value, content);\n\n            // Assert\n            formatter.Protected().Verify(\"GetSerializer\", Times.Once(), type, value, content);\n        }\n\n        private static XmlMediaTypeFormatterTracer CreateTracer(XmlMediaTypeFormatter inner)\n        {\n            ITraceWriter traceWriter = new TestTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage();\n            return new XmlMediaTypeFormatterTracer(inner, traceWriter, request);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Util/ContextUtil.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Filters;\nusing System.Web.Http.Routing;\nusing Moq;\n\nnamespace System.Web.Http\n{\n    internal static class ContextUtil\n    {\n        public static HttpControllerContext CreateControllerContext(HttpConfiguration configuration = null, IHttpController instance = null, IHttpRouteData routeData = null, HttpRequestMessage request = null)\n        {\n            HttpConfiguration config = configuration ?? new HttpConfiguration();\n            IHttpRouteData route = routeData ?? new HttpRouteData(new HttpRoute());\n            HttpRequestMessage req = request ?? new HttpRequestMessage();\n            req.SetConfiguration(config);\n            req.SetRouteData(route);\n\n            HttpControllerContext context = new HttpControllerContext(config, route, req);\n            if (instance != null)\n            {\n                context.Controller = instance;\n            }\n            context.ControllerDescriptor = CreateControllerDescriptor(config);\n\n            return context;\n        }\n\n        public static HttpActionContext CreateActionContext(HttpControllerContext controllerContext = null, HttpActionDescriptor actionDescriptor = null)\n        {\n            HttpControllerContext context = controllerContext ?? ContextUtil.CreateControllerContext();\n            HttpActionDescriptor descriptor = actionDescriptor ?? CreateActionDescriptor();\n            descriptor.ControllerDescriptor = context.ControllerDescriptor;\n            return new HttpActionContext(context, descriptor);\n        }\n\n        public static HttpActionContext GetHttpActionContext(HttpRequestMessage request)\n        {\n            HttpActionContext actionContext = CreateActionContext();\n            actionContext.ControllerContext.Request = request;\n            return actionContext;\n        }\n\n        public static HttpActionExecutedContext GetActionExecutedContext(HttpRequestMessage request, HttpResponseMessage response)\n        {\n            HttpActionContext actionContext = CreateActionContext();\n            actionContext.ControllerContext.Request = request;\n            HttpActionExecutedContext actionExecutedContext = new HttpActionExecutedContext(actionContext, null) { Response = response };\n            return actionExecutedContext;\n        }\n\n        public static HttpControllerDescriptor CreateControllerDescriptor(HttpConfiguration config = null)\n        {\n            if (config == null)\n            {\n                config = new HttpConfiguration();\n            }\n            return new HttpControllerDescriptor() { Configuration = config, ControllerName = \"FooController\" };\n        }\n\n        public static HttpActionDescriptor CreateActionDescriptor()\n        {\n            var mock = new Mock<HttpActionDescriptor>() { CallBase = true };\n            mock.SetupGet(d => d.ActionName).Returns(\"Bar\");\n            return mock.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Util/SimpleHttpValueProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Web.Http.ValueProviders;\n\nnamespace System.Web.Http.Util\n{\n    public sealed class SimpleHttpValueProvider : Dictionary<string, object>, IValueProvider\n    {\n        private readonly CultureInfo _culture;\n\n        public SimpleHttpValueProvider()\n            : this(null)\n        {\n        }\n\n        public SimpleHttpValueProvider(CultureInfo culture)\n            : base(StringComparer.OrdinalIgnoreCase)\n        {\n            _culture = culture ?? CultureInfo.InvariantCulture;\n        }\n\n        // copied from ValueProviderUtil\n        public bool ContainsPrefix(string prefix)\n        {\n            foreach (string key in Keys)\n            {\n                if (key != null)\n                {\n                    if (prefix.Length == 0)\n                    {\n                        return true; // shortcut - non-null key matches empty prefix\n                    }\n\n                    if (key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))\n                    {\n                        if (key.Length == prefix.Length)\n                        {\n                            return true; // exact match\n                        }\n                        else\n                        {\n                            switch (key[prefix.Length])\n                            {\n                                case '.': // known separator characters\n                                case '[':\n                                    return true;\n                            }\n                        }\n                    }\n                }\n            }\n\n            return false; // nothing found\n        }\n\n        public ValueProviderResult GetValue(string key)\n        {\n            object rawValue;\n            if (TryGetValue(key, out rawValue))\n            {\n                return new ValueProviderResult(rawValue, Convert.ToString(rawValue, _culture), _culture);\n            }\n            else\n            {\n                // value not found\n                return null;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Validation/DefaultBodyModelValidatorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Metadata.Providers;\nusing System.Web.Http.ModelBinding;\nusing System.Xml.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Validation\n{\n    public class DefaultBodyModelValidatorTest\n    {\n        private static Person LonelyPerson;\n\n        static DefaultBodyModelValidatorTest()\n        {\n            LonelyPerson = new Person() { Name = \"Reallllllllly Long Name\" };\n            LonelyPerson.Friend = LonelyPerson;\n        }\n\n        public static IEnumerable<object[]> ValidationErrors\n        {\n            get\n            {\n                return new TheoryDataSet<object, Type, Dictionary<string, string>>()\n                {\n                    // Primitives\n                    { null, typeof(Person), new Dictionary<string, string>() },\n                    { 14, typeof(int), new Dictionary<string, string>() },\n                    { \"foo\", typeof(string), new Dictionary<string, string>() },\n\n                    // Object Traversal : make sure we can traverse the object graph without throwing\n                    { new ValueType() { Reference = \"ref\", Value = 256}, typeof(ValueType), new Dictionary<string, string>()},\n                    { new ReferenceType() { Reference = \"ref\", Value = 256}, typeof(ReferenceType), new Dictionary<string, string>()},\n\n                    // Classes\n                    { new Person() { Name = \"Rick\", Profession = \"Astronaut\" }, typeof(Person), new Dictionary<string, string>() },\n                    { new Person(), typeof(Person), new Dictionary<string, string>()\n                        {\n                            { \"Name\", \"The Name field is required.\" },\n                            { \"Profession\", \"The Profession field is required.\" }\n                        }\n                    },\n\n                    { new Person() { Name = \"Rick\", Friend = new Person() }, typeof(Person), new Dictionary<string, string>()\n                        {\n                            { \"Profession\", \"The Profession field is required.\" },\n                            { \"Friend.Name\", \"The Name field is required.\" },\n                            { \"Friend.Profession\", \"The Profession field is required.\" }\n                        }\n                    },\n\n                    // Collections\n                    { new Person[] { new Person(), new Person() }, typeof(Person[]), new Dictionary<string, string>()\n                        {\n                            { \"[0].Name\", \"The Name field is required.\" },\n                            { \"[0].Profession\", \"The Profession field is required.\" },\n                            { \"[1].Name\", \"The Name field is required.\" },\n                            { \"[1].Profession\", \"The Profession field is required.\" }\n                        }\n                    },\n\n                    { new List<Person> { new Person(), new Person() }, typeof(Person[]), new Dictionary<string, string>()\n                        {\n                            { \"[0].Name\", \"The Name field is required.\" },\n                            { \"[0].Profession\", \"The Profession field is required.\" },\n                            { \"[1].Name\", \"The Name field is required.\" },\n                            { \"[1].Profession\", \"The Profession field is required.\" }\n                        }\n                    },\n\n                    { new Dictionary<string, Person> { { \"Joe\", new Person() } , { \"Mark\", new Person() } }, typeof(Dictionary<string, Person>), new Dictionary<string, string>()\n                        {\n                            { \"[0].Value.Name\", \"The Name field is required.\" },\n                            { \"[0].Value.Profession\", \"The Profession field is required.\" },\n                            { \"[1].Value.Name\", \"The Name field is required.\" },\n                            { \"[1].Value.Profession\", \"The Profession field is required.\" }\n                        }\n                    },\n\n                    // IValidatableObject's\n                    { new ValidatableModel(), typeof(ValidatableModel), new Dictionary<string, string>()\n                        {\n                            { \"\", \"Error1\" },\n                            { \"Property1\", \"Error2\" },\n                            { \"Property2\", \"Error3\" },\n                            { \"Property3\", \"Error3\" }\n                        }\n                    },\n                    { new[] { new ValidatableModel() }, typeof(ValidatableModel[]), new Dictionary<string, string>()\n                        {\n                            { \"[0]\", \"Error1\" },\n                            { \"[0].Property1\", \"Error2\" },\n                            { \"[0].Property2\", \"Error3\" },\n                            { \"[0].Property3\", \"Error3\" }\n                        }\n                    },\n\n                    // Testing we don't blow up on cycles\n                    { LonelyPerson, typeof(Person), new Dictionary<string, string>()\n                        {\n                            { \"Name\", \"The field Name must be a string with a maximum length of 10.\" },\n                            { \"Profession\", \"The Profession field is required.\" }\n                        }\n                    },\n\n                    // Testing that we don't bubble up exceptions when property getters throw\n                    { new Uri(\"/api/values\", UriKind.Relative), typeof(Uri), new Dictionary<string, string>() },\n\n                    // Testing that excluded types don't result in any errors\n                    { typeof(string), typeof(Type), new Dictionary<string, string>() },\n                    { new byte[] { (byte)'a', (byte)'b' }, typeof(byte[]), new Dictionary<string, string>() },\n                    { XElement.Parse(\"<xml>abc</xml>\"), typeof(XElement), new Dictionary<string, string>() }\n                };\n            }\n        }\n\n        [Theory]\n        [ReplaceCulture]\n        [PropertyData(\"ValidationErrors\")]\n        public void ExpectedValidationErrorsRaised(object model, Type type, Dictionary<string, string> expectedErrors)\n        {\n            // Arrange\n            ModelMetadataProvider metadataProvider = new DataAnnotationsModelMetadataProvider();\n            HttpActionContext actionContext = ContextUtil.CreateActionContext();\n\n            // Act\n            Assert.DoesNotThrow(() =>\n                new DefaultBodyModelValidator().Validate(model, type, metadataProvider, actionContext, string.Empty)\n            );\n\n            // Assert\n            Dictionary<string, string> actualErrors = new Dictionary<string, string>();\n            foreach (KeyValuePair<string, ModelState> keyStatePair in actionContext.ModelState)\n            {\n                foreach (ModelError error in keyStatePair.Value.Errors)\n                {\n                    actualErrors.Add(keyStatePair.Key, error.ErrorMessage);\n                }\n            }\n\n            Assert.Equal(expectedErrors.Count, actualErrors.Count);\n            foreach (KeyValuePair<string, string> keyErrorPair in expectedErrors)\n            {\n                Assert.Contains(keyErrorPair.Key, actualErrors.Keys);\n                Assert.Equal(keyErrorPair.Value, actualErrors[keyErrorPair.Key]);\n            }\n        }\n\n        [Fact]\n        public void MultipleValidationErrorsOnSameMemberReported()\n        {\n            // Arrange\n            ModelMetadataProvider metadataProvider = new DataAnnotationsModelMetadataProvider();\n            HttpActionContext actionContext = ContextUtil.CreateActionContext();\n            object model = new Address() { Street = \"Microsoft Way\" };\n\n            // Act\n            Assert.DoesNotThrow(() =>\n                new DefaultBodyModelValidator().Validate(model, typeof(Address), metadataProvider, actionContext, string.Empty)\n            );\n\n            // Assert\n            Assert.Contains(\"Street\", actionContext.ModelState.Keys);\n            ModelState streetState = actionContext.ModelState[\"Street\"];\n            Assert.Equal(2, streetState.Errors.Count);\n        }\n\n        [Fact]\n        public void ExcludedTypes_AreNotValidated()\n        {\n            // Arrange\n            ModelMetadataProvider metadataProvider = new DataAnnotationsModelMetadataProvider();\n            HttpActionContext actionContext = ContextUtil.CreateActionContext();\n            Mock<DefaultBodyModelValidator> mockValidator = new Mock<DefaultBodyModelValidator>();\n            mockValidator.CallBase = true;\n            mockValidator.Setup(validator => validator.ShouldValidateType(typeof(Person))).Returns(false);\n\n            // Act\n            mockValidator.Object.Validate(new Person(), typeof(Person), metadataProvider, actionContext, string.Empty);\n\n            // Assert\n            Assert.True(actionContext.ModelState.IsValid);\n        }\n\n        [Fact]\n        public void ExcludedPropertyTypes_AreShallowValidated()\n        {\n            // Arrange\n            ModelMetadataProvider metadataProvider = new DataAnnotationsModelMetadataProvider();\n            HttpActionContext actionContext = ContextUtil.CreateActionContext();\n            Mock<DefaultBodyModelValidator> mockValidator = new Mock<DefaultBodyModelValidator>();\n            mockValidator.CallBase = true;\n            mockValidator.Setup(validator => validator.ShouldValidateType(typeof(Person))).Returns(false);\n\n            // Act\n            mockValidator.Object.Validate(new Pet(), typeof(Pet), metadataProvider, actionContext, string.Empty);\n\n            // Assert\n            Assert.False(actionContext.ModelState.IsValid);\n            ModelState modelState = actionContext.ModelState[\"Owner\"];\n            Assert.Single(modelState.Errors);\n        }\n\n        [Fact]\n        public void Validate_DoesNotUseOverridden_GetHashCodeOrEquals()\n        {\n            // Arrange\n            ModelMetadataProvider metadataProvider = new DataAnnotationsModelMetadataProvider();\n            HttpActionContext actionContext = ContextUtil.CreateActionContext();\n            DefaultBodyModelValidator validator = new DefaultBodyModelValidator();\n            object instance = new[] { new TypeThatOverridesEquals { Funny = \"hehe\" }, new TypeThatOverridesEquals { Funny = \"hehe\" } };\n\n            // Act & Assert\n            Assert.DoesNotThrow(\n                () => validator.Validate(instance, typeof(TypeThatOverridesEquals[]), metadataProvider, actionContext, String.Empty));\n        }\n\n        public class Person\n        {\n            [Required]\n            [StringLength(10)]\n            public string Name { get; set; }\n\n            [Required]\n            public string Profession { get; set; }\n\n            public Person Friend { get; set; }\n        }\n\n        public class Address\n        {\n            [StringLength(5)]\n            [RegularExpression(\"hehehe\")]\n            public string Street { get; set; }\n        }\n\n        public struct ValueType\n        {\n            public int Value;\n            public string Reference;\n        }\n\n        public class ReferenceType\n        {\n            public static string StaticProperty { get { return \"static\"; } }\n            public int Value;\n            public string Reference;\n        }\n\n        public class Pet\n        {\n            [Required]\n            public Person Owner { get; set; }\n        }\n\n        public class ValidatableModel : IValidatableObject\n        {\n            public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)\n            {\n                yield return new ValidationResult(\"Error1\", new string[] { });\n                yield return new ValidationResult(\"Error2\", new[] { \"Property1\" });\n                yield return new ValidationResult(\"Error3\", new[] { \"Property2\", \"Property3\" });\n            }\n        }\n\n        public class TypeThatOverridesEquals\n        {\n            [StringLength(2)]\n            public string Funny { get; set; }\n\n            public override bool Equals(object obj)\n            {\n                throw new InvalidOperationException();\n            }\n\n            public override int GetHashCode()\n            {\n                throw new InvalidOperationException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Validation/ModelStateFormatterLoggerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Formatting;\nusing System.Web.Http.ModelBinding;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Validation\n{\n    public class ModelStateFormatterLoggerTest\n    {\n        [Fact]\n        public void LogErrorAddsErrorToModelState()\n        {\n            ModelStateDictionary modelState = new ModelStateDictionary();\n            string prefix = \"prefix\";\n            IFormatterLogger formatterLogger = new ModelStateFormatterLogger(modelState, prefix);\n\n            formatterLogger.LogError(\"property\", \"error\");\n\n            Assert.True(modelState.ContainsKey(\"prefix.property\"));\n            ModelError error = Assert.Single(modelState[\"prefix.property\"].Errors);\n            Assert.Equal(\"error\", error.ErrorMessage);\n        }\n\n        [Fact]\n        public void LogErrorAddsExceptionToModelState()\n        {\n            ModelStateDictionary modelState = new ModelStateDictionary();\n            string prefix = \"prefix\";\n            IFormatterLogger formatterLogger = new ModelStateFormatterLogger(modelState, prefix);\n\n            Exception e = new Exception(\"error\");\n\n            formatterLogger.LogError(\"property\", e);\n\n            Assert.True(modelState.ContainsKey(\"prefix.property\"));\n            ModelError error = Assert.Single(modelState[\"prefix.property\"].Errors);\n            Assert.Equal(e, error.Exception);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Validation/ModelValidationNodeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Metadata.Providers;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Validation\n{\n    public class ModelValidationNodeTest\n    {\n        [Fact]\n        public void ConstructorSetsCollectionInstance()\n        {\n            // Arrange\n            ModelMetadata metadata = GetModelMetadata();\n            string modelStateKey = \"someKey\";\n            ModelValidationNode[] childNodes = new[]\n            {\n                new ModelValidationNode(metadata, \"someKey0\"),\n                new ModelValidationNode(metadata, \"someKey1\")\n            };\n\n            // Act\n            ModelValidationNode node = new ModelValidationNode(metadata, modelStateKey, childNodes);\n\n            // Assert\n            Assert.Equal(childNodes, node.ChildNodes.ToArray());\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfModelMetadataIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                () => new ModelValidationNode(null, \"someKey\"),\n                \"modelMetadata\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfModelStateKeyIsNull()\n        {\n            // Arrange\n            ModelMetadata metadata = GetModelMetadata();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                () => new ModelValidationNode(metadata, null),\n                \"modelStateKey\");\n        }\n\n        [Fact]\n        public void PropertiesAreSet()\n        {\n            // Arrange\n            ModelMetadata metadata = GetModelMetadata();\n            string modelStateKey = \"someKey\";\n\n            // Act\n            ModelValidationNode node = new ModelValidationNode(metadata, modelStateKey);\n\n            // Assert\n            Assert.Equal(metadata, node.ModelMetadata);\n            Assert.Equal(modelStateKey, node.ModelStateKey);\n            Assert.NotNull(node.ChildNodes);\n            Assert.Empty(node.ChildNodes);\n        }\n\n        [Fact]\n        public void CombineWith()\n        {\n            // Arrange\n            List<string> log = new List<string>();\n\n            ModelValidationNode[] allChildNodes = new[]\n            {\n                new ModelValidationNode(GetModelMetadata(), \"key1\"),\n                new ModelValidationNode(GetModelMetadata(), \"key2\"),\n                new ModelValidationNode(GetModelMetadata(), \"key3\"),\n            };\n\n            ModelValidationNode parentNode1 = new ModelValidationNode(GetModelMetadata(), \"parent1\");\n            parentNode1.ChildNodes.Add(allChildNodes[0]);\n            parentNode1.Validating += (sender, e) => log.Add(\"Validating parent1.\");\n            parentNode1.Validated += (sender, e) => log.Add(\"Validated parent1.\");\n\n            ModelValidationNode parentNode2 = new ModelValidationNode(GetModelMetadata(), \"parent2\");\n            parentNode2.ChildNodes.Add(allChildNodes[1]);\n            parentNode2.ChildNodes.Add(allChildNodes[2]);\n            parentNode2.Validating += (sender, e) => log.Add(\"Validating parent2.\");\n            parentNode2.Validated += (sender, e) => log.Add(\"Validated parent2.\");\n\n            // Act\n            parentNode1.CombineWith(parentNode2);\n            parentNode1.Validate(ContextUtil.CreateActionContext());\n\n            // Assert\n            Assert.Equal(new[] { \"Validating parent1.\", \"Validating parent2.\", \"Validated parent1.\", \"Validated parent2.\" }, log.ToArray());\n            Assert.Equal(allChildNodes, parentNode1.ChildNodes.ToArray());\n        }\n\n        [Fact]\n        public void CombineWith_OtherNodeIsSuppressed_DoesNothing()\n        {\n            // Arrange\n            List<string> log = new List<string>();\n\n            ModelValidationNode[] allChildNodes = new[]\n            {\n                new ModelValidationNode(GetModelMetadata(), \"key1\"),\n                new ModelValidationNode(GetModelMetadata(), \"key2\"),\n                new ModelValidationNode(GetModelMetadata(), \"key3\"),\n            };\n\n            ModelValidationNode[] expectedChildNodes = new[]\n            {\n                allChildNodes[0]\n            };\n\n            ModelValidationNode parentNode1 = new ModelValidationNode(GetModelMetadata(), \"parent1\");\n            parentNode1.ChildNodes.Add(allChildNodes[0]);\n            parentNode1.Validating += (sender, e) => log.Add(\"Validating parent1.\");\n            parentNode1.Validated += (sender, e) => log.Add(\"Validated parent1.\");\n\n            ModelValidationNode parentNode2 = new ModelValidationNode(GetModelMetadata(), \"parent2\");\n            parentNode2.ChildNodes.Add(allChildNodes[1]);\n            parentNode2.ChildNodes.Add(allChildNodes[2]);\n            parentNode2.Validating += (sender, e) => log.Add(\"Validating parent2.\");\n            parentNode2.Validated += (sender, e) => log.Add(\"Validated parent2.\");\n            parentNode2.SuppressValidation = true;\n\n            // Act\n            parentNode1.CombineWith(parentNode2);\n            parentNode1.Validate(ContextUtil.CreateActionContext());\n\n            // Assert\n            Assert.Equal(new[] { \"Validating parent1.\", \"Validated parent1.\" }, log.ToArray());\n            Assert.Equal(expectedChildNodes, parentNode1.ChildNodes.ToArray());\n        }\n\n        [Fact]\n        public void Validate_Ordering()\n        {\n            // Proper order of invocation:\n            // 1. OnValidating()\n            // 2. Child validators\n            // 3. This validator\n            // 4. OnValidated()\n\n            // Arrange\n            List<string> log = new List<string>();\n            LoggingValidatableObject model = new LoggingValidatableObject(log);\n            ModelMetadata modelMetadata = GetModelMetadata(model);\n            ModelMetadata childMetadata = new EmptyModelMetadataProvider().GetMetadataForProperty(() => model, model.GetType(), \"ValidStringProperty\");\n            ModelValidationNode node = new ModelValidationNode(modelMetadata, \"theKey\");\n            node.Validating += (sender, e) => log.Add(\"In OnValidating()\");\n            node.Validated += (sender, e) => log.Add(\"In OnValidated()\");\n            node.ChildNodes.Add(new ModelValidationNode(childMetadata, \"theKey.ValidStringProperty\"));\n\n            // Act\n            node.Validate(ContextUtil.CreateActionContext());\n\n            // Assert\n            Assert.Equal(new[] { \"In OnValidating()\", \"In LoggingValidatonAttribute.IsValid()\", \"In IValidatableObject.Validate()\", \"In OnValidated()\" }, log.ToArray());\n        }\n\n        [Fact]\n        public void Validate_SkipsRemainingValidationIfModelStateIsInvalid()\n        {\n            // Because a property validator fails, the model validator shouldn't run\n\n            // Arrange\n            List<string> log = new List<string>();\n            LoggingValidatableObject model = new LoggingValidatableObject(log);\n            ModelMetadata modelMetadata = GetModelMetadata(model);\n            ModelMetadata childMetadata = new EmptyModelMetadataProvider().GetMetadataForProperty(() => model, model.GetType(), \"InvalidStringProperty\");\n            ModelValidationNode node = new ModelValidationNode(modelMetadata, \"theKey\");\n            node.ChildNodes.Add(new ModelValidationNode(childMetadata, \"theKey.InvalidStringProperty\"));\n            node.Validating += (sender, e) => log.Add(\"In OnValidating()\");\n            node.Validated += (sender, e) => log.Add(\"In OnValidated()\");\n            HttpActionContext context = ContextUtil.CreateActionContext();\n\n            // Act\n            node.Validate(context);\n\n            // Assert\n            Assert.Equal(new[] { \"In OnValidating()\", \"In IValidatableObject.Validate()\", \"In OnValidated()\" }, log.ToArray());\n            Assert.Equal(\"Sample error message\", context.ModelState[\"theKey.InvalidStringProperty\"].Errors[0].ErrorMessage);\n        }\n\n        [Fact]\n        public void Validate_SkipsValidationIfHandlerCancels()\n        {\n            // Arrange\n            List<string> log = new List<string>();\n            LoggingValidatableObject model = new LoggingValidatableObject(log);\n            ModelMetadata modelMetadata = GetModelMetadata(model);\n            ModelValidationNode node = new ModelValidationNode(modelMetadata, \"theKey\");\n            node.Validating += (sender, e) =>\n            {\n                log.Add(\"In OnValidating()\");\n                e.Cancel = true;\n            };\n            node.Validated += (sender, e) => log.Add(\"In OnValidated()\");\n\n            // Act\n            node.Validate(ContextUtil.CreateActionContext());\n\n            // Assert\n            Assert.Equal(new[] { \"In OnValidating()\" }, log.ToArray());\n        }\n\n        [Fact]\n        public void Validate_SkipsValidationIfSuppressed()\n        {\n            // Arrange\n            List<string> log = new List<string>();\n            LoggingValidatableObject model = new LoggingValidatableObject(log);\n            ModelMetadata modelMetadata = GetModelMetadata(model);\n            ModelValidationNode node = new ModelValidationNode(modelMetadata, \"theKey\")\n            {\n                SuppressValidation = true\n            };\n\n            node.Validating += (sender, e) => log.Add(\"In OnValidating()\");\n            node.Validated += (sender, e) => log.Add(\"In OnValidated()\");\n\n            // Act\n            node.Validate(ContextUtil.CreateActionContext());\n\n            // Assert\n            Assert.Empty(log);\n        }\n\n        [Fact]\n        public void Validate_ThrowsIfControllerContextIsNull()\n        {\n            // Arrange\n            ModelValidationNode node = new ModelValidationNode(GetModelMetadata(), \"someKey\");\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                () => node.Validate(null),\n                \"actionContext\");\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void Validate_ValidateAllProperties_AddsValidationErrors()\n        {\n            // Arrange\n            ValidateAllPropertiesModel model = new ValidateAllPropertiesModel\n            {\n                RequiredString = null /* error */,\n                RangedInt = 0 /* error */,\n                ValidString = \"dog\"\n            };\n\n            ModelMetadata modelMetadata = GetModelMetadata(model);\n            HttpActionContext context = ContextUtil.CreateActionContext();\n            ModelValidationNode node = new ModelValidationNode(modelMetadata, \"theKey\")\n            {\n                ValidateAllProperties = true\n            };\n            context.ModelState.AddModelError(\"theKey.RequiredString.Dummy\", \"existing Error Text\");\n\n            // Act\n            node.Validate(context);\n\n            // Assert\n            Assert.Null(context.ModelState[\"theKey.RequiredString\"]);\n            Assert.Equal(\"existing Error Text\", context.ModelState[\"theKey.RequiredString.Dummy\"].Errors[0].ErrorMessage);\n            Assert.Equal(\"The field RangedInt must be between 10 and 30.\", context.ModelState[\"theKey.RangedInt\"].Errors[0].ErrorMessage);\n            Assert.Null(context.ModelState[\"theKey.ValidString\"]);\n            Assert.Null(context.ModelState[\"theKey\"]);\n        }\n\n        private static ModelMetadata GetModelMetadata()\n        {\n            return new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(object));\n        }\n\n        private static ModelMetadata GetModelMetadata(object o)\n        {\n            return new DataAnnotationsModelMetadataProvider().GetMetadataForType(() => o, o.GetType());\n        }\n\n        private sealed class LoggingValidatableObject : IValidatableObject\n        {\n            private readonly IList<string> _log;\n\n            public LoggingValidatableObject(IList<string> log)\n            {\n                _log = log;\n            }\n\n            [LoggingValidation]\n            public string ValidStringProperty { get; set; }\n            public string InvalidStringProperty { get; set; }\n\n            public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)\n            {\n                _log.Add(\"In IValidatableObject.Validate()\");\n                yield return new ValidationResult(\"Sample error message\", new[] { \"InvalidStringProperty\" });\n            }\n\n            private sealed class LoggingValidationAttribute : ValidationAttribute\n            {\n                protected override ValidationResult IsValid(object value, ValidationContext validationContext)\n                {\n                    LoggingValidatableObject lvo = (LoggingValidatableObject)value;\n                    lvo._log.Add(\"In LoggingValidatonAttribute.IsValid()\");\n                    return ValidationResult.Success;\n                }\n            }\n        }\n\n        private class ValidateAllPropertiesModel\n        {\n            [Required]\n            public string RequiredString { get; set; }\n\n            [Range(10, 30)]\n            public int RangedInt { get; set; }\n\n            [RegularExpression(\"dog\")]\n            public string ValidString { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Validation/ModelValidationRequiredMemberSelectorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Net.Http.Formatting;\nusing System.Reflection;\nusing System.Runtime.Serialization;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Validation\n{\n    public class ModelValidationRequiredMemberSelectorTest\n    {\n        [Theory]\n        [InlineData(\"CustomerID\", true)]\n        [InlineData(\"ID\", true)]\n        [InlineData(\"ItemID\", true)]\n        [InlineData(\"UselessInfo\", false)]\n        public void IsRequiredMember_RecognizesRequiredMembers(string propertyName, bool isRequired)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            IRequiredMemberSelector selector = new ModelValidationRequiredMemberSelector(config.Services.GetModelMetadataProvider(), config.Services.GetModelValidatorProviders());\n\n            Assert.Equal(isRequired, selector.IsRequiredMember(typeof(PurchaseOrder).GetProperty(propertyName)));\n        }\n\n        [Theory]\n        [InlineData(\"StringProperty\")]\n        [InlineData(\"NullableProperty\")]\n        [InlineData(\"CollectionProperty\")]\n        public void IsRequiredMember_ReturnsFalse_ForNullableProperties(string propertyName)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            IRequiredMemberSelector selector = new ModelValidationRequiredMemberSelector(config.Services.GetModelMetadataProvider(), config.Services.GetModelValidatorProviders());\n\n            Assert.False(selector.IsRequiredMember(typeof(NullableProperties).GetProperty(propertyName)));\n        }\n\n\n        [Theory]\n        [InlineData(\"ProtectedGet\")]\n        [InlineData(\"NoGet\")]\n        [InlineData(\"Internal\")]\n        public void IsRequiredMember_ReturnsFalse_ForInvalidProperties(string propertyName)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            IRequiredMemberSelector selector = new ModelValidationRequiredMemberSelector(config.Services.GetModelMetadataProvider(), config.Services.GetModelValidatorProviders());\n            PropertyInfo propertyInfo = typeof(BadProperties).GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);\n\n            Assert.False(selector.IsRequiredMember(propertyInfo));\n        }\n\n        [DataContract]\n        public class PurchaseOrder\n        {\n            [DataMember(IsRequired = true)]\n            public int ID { get; set; }\n\n            [Required]\n            public int CustomerID { get; set; }\n\n            [Required]\n            [DataMember(IsRequired = true)]\n            public int ItemID { get; set; }\n\n            public int UselessInfo { get; set; }\n        }\n\n        public class NullableProperties\n        {\n            [Required]\n            public string StringProperty { get; set; }\n\n            [Required]\n            public Nullable<int> NullableProperty { get; set; }\n\n            [Required]\n            public List<int> CollectionProperty { get; set; }\n        }\n\n        public class BadProperties\n        {\n            public int ProtectedGet\n            {\n                protected get;\n                set;\n            }\n\n            public int NoGet\n            {\n                set { }\n            }\n\n            internal int Internal\n            {\n                get;\n                set;\n            }\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Test/Validation/ModelValidationResultTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Validation\n{\n    public class ModelValidationResultTest\n    {\n        [Fact]\n        public void MemberNameProperty()\n        {\n            // Arrange\n            ModelValidationResult result = new ModelValidationResult();\n\n            // Act & assert\n            MemberHelper.TestStringProperty(result, \"MemberName\", String.Empty);\n        }\n\n        [Fact]\n        public void MessageProperty()\n        {\n            // Arrange\n            ModelValidationResult result = new ModelValidationResult();\n\n            // Act & assert\n            MemberHelper.TestStringProperty(result, \"Message\", String.Empty);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Validation/ModelValidatorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Metadata.Providers;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Validation\n{\n    public class ModelValidatorTest\n    {\n        private static DataAnnotationsModelMetadataProvider _metadataProvider = new DataAnnotationsModelMetadataProvider();\n        private static IEnumerable<ModelValidatorProvider> _noValidatorProviders = Enumerable.Empty<ModelValidatorProvider>();\n\n        [Fact]\n        public void ConstructorGuards()\n        {\n            // Arrange\n            ModelMetadata metadata = _metadataProvider.GetMetadataForType(null, typeof(object));\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => new TestableModelValidator(validatorProviders: null),\n                \"validatorProviders\");\n        }\n\n        [Fact]\n        public void ValuesSet()\n        {\n            // Arrange\n            ModelMetadata metadata = _metadataProvider.GetMetadataForProperty(() => 15, typeof(string), \"Length\");\n\n            // Act\n            TestableModelValidator validator = new TestableModelValidator(_noValidatorProviders);\n\n            // Assert\n            Assert.Same(_noValidatorProviders, validator.ValidatorProviders);\n        }\n\n        [Fact]\n        public void IsRequiredFalseByDefault()\n        {\n            // Arrange\n            ModelMetadata metadata = _metadataProvider.GetMetadataForProperty(() => 15, typeof(string), \"Length\");\n\n            // Act\n            TestableModelValidator validator = new TestableModelValidator(_noValidatorProviders);\n\n            // Assert\n            Assert.False(validator.IsRequired);\n        }\n\n        [Fact]\n        public void GetModelValidator_DoesNotReadPropertyValues()\n        {\n            // Arrange\n            IEnumerable<ModelValidatorProvider> validatorProviders = new[] { new ObservableModelValidatorProvider() };\n            ObservableModel model = new ObservableModel();\n            ModelMetadata metadata = new EmptyModelMetadataProvider().GetMetadataForType(() => model, typeof(ObservableModel));\n\n            // Act\n            ModelValidator validator = ModelValidator.GetModelValidator(validatorProviders);\n            ModelValidationResult[] results = validator.Validate(metadata, model).ToArray();\n\n            // Assert\n            Assert.False(model.PropertyWasRead());\n        }\n\n        private class ObservableModelValidatorProvider : ModelValidatorProvider\n        {\n            public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders)\n            {\n                return new ModelValidator[] { new ObservableModelValidator(validatorProviders) };\n            }\n\n            private class ObservableModelValidator : ModelValidator\n            {\n                public ObservableModelValidator(IEnumerable<ModelValidatorProvider> validatorProviders)\n                    : base(validatorProviders)\n                {\n                }\n\n                public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container)\n                {\n                    return Enumerable.Empty<ModelValidationResult>();\n                }\n            }\n        }\n\n        private class ObservableModel\n        {\n            private bool _propertyWasRead;\n\n            public int TheProperty\n            {\n                get\n                {\n                    _propertyWasRead = true;\n                    return 42;\n                }\n            }\n\n            public bool PropertyWasRead()\n            {\n                return _propertyWasRead;\n            }\n        }\n\n        private class TestableModelValidator : ModelValidator\n        {\n            public TestableModelValidator(IEnumerable<ModelValidatorProvider> validatorProviders)\n                : base(validatorProviders)\n            {\n            }\n\n            public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Validation/Providers/AssociatedValidatorProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Metadata.Providers;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Validation.Providers\n{\n    public class AssociatedValidatorProviderTest\n    {\n        private static DataAnnotationsModelMetadataProvider _metadataProvider = new DataAnnotationsModelMetadataProvider();\n        private static IEnumerable<ModelValidatorProvider> _noValidatorProviders = Enumerable.Empty<ModelValidatorProvider>();\n\n        [Fact]\n        public void GetValidatorsGuardClauses()\n        {\n            // Arrange\n            ModelMetadata metadata = _metadataProvider.GetMetadataForType(null, typeof(object));\n            Mock<AssociatedValidatorProvider> provider = new Mock<AssociatedValidatorProvider> { CallBase = true };\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => provider.Object.GetValidators(metadata: null, validatorProviders: _noValidatorProviders),\n                \"metadata\");\n            Assert.ThrowsArgumentNull(\n                () => provider.Object.GetValidators(metadata, validatorProviders: null),\n                \"validatorProviders\");\n        }\n\n        [Fact]\n        public void GetValidatorsForPropertyWithLocalAttributes()\n        {\n            // Arrange\n            IEnumerable<Attribute> callbackAttributes = null;\n            ModelMetadata metadata = _metadataProvider.GetMetadataForProperty(null, typeof(PropertyModel), \"LocalAttributes\");\n            Mock<TestableAssociatedValidatorProvider> provider = new Mock<TestableAssociatedValidatorProvider> { CallBase = true };\n            provider.Setup(p => p.AbstractGetValidators(metadata, _noValidatorProviders, It.IsAny<IEnumerable<Attribute>>()))\n                    .Callback<ModelMetadata, IEnumerable<ModelValidatorProvider>, IEnumerable<Attribute>>((m, c, attributes) => callbackAttributes = attributes)\n                    .Returns(() => null)\n                    .Verifiable();\n\n            // Act\n            provider.Object.GetValidators(metadata, _noValidatorProviders);\n\n            // Assert\n            provider.Verify();\n            Assert.Contains(callbackAttributes, a => a is RequiredAttribute);\n        }\n\n        [Fact]\n        public void GetValidatorsForPropertyWithMetadataAttributes()\n        {\n            // Arrange\n            IEnumerable<Attribute> callbackAttributes = null;\n            ModelMetadata metadata = _metadataProvider.GetMetadataForProperty(null, typeof(PropertyModel), \"MetadataAttributes\");\n            Mock<TestableAssociatedValidatorProvider> provider = new Mock<TestableAssociatedValidatorProvider> { CallBase = true };\n            provider.Setup(p => p.AbstractGetValidators(metadata, _noValidatorProviders, It.IsAny<IEnumerable<Attribute>>()))\n                    .Callback<ModelMetadata, IEnumerable<ModelValidatorProvider>, IEnumerable<Attribute>>((m, c, attributes) => callbackAttributes = attributes)\n                    .Returns(() => null)\n                    .Verifiable();\n\n            // Act\n            provider.Object.GetValidators(metadata, _noValidatorProviders);\n\n            // Assert\n            provider.Verify();\n            Assert.Contains(callbackAttributes, a => a is RangeAttribute);\n        }\n\n        [Fact]\n        public void GetValidatorsForPropertyWithMixedAttributes()\n        {\n            // Arrange\n            IEnumerable<Attribute> callbackAttributes = null;\n            ModelMetadata metadata = _metadataProvider.GetMetadataForProperty(null, typeof(PropertyModel), \"MixedAttributes\");\n            Mock<TestableAssociatedValidatorProvider> provider = new Mock<TestableAssociatedValidatorProvider> { CallBase = true };\n            provider.Setup(p => p.AbstractGetValidators(metadata, _noValidatorProviders, It.IsAny<IEnumerable<Attribute>>()))\n                    .Callback<ModelMetadata, IEnumerable<ModelValidatorProvider>, IEnumerable<Attribute>>((m, c, attributes) => callbackAttributes = attributes)\n                    .Returns(() => null)\n                    .Verifiable();\n\n            // Act\n            provider.Object.GetValidators(metadata, _noValidatorProviders);\n\n            // Assert\n            provider.Verify();\n            Assert.Contains(callbackAttributes, a => a is RangeAttribute);\n            Assert.Contains(callbackAttributes, a => a is RequiredAttribute);\n        }\n\n        [MetadataType(typeof(Metadata))]\n        private class PropertyModel\n        {\n            [Required]\n            public int LocalAttributes { get; set; }\n\n            public string MetadataAttributes { get; set; }\n\n            [Required]\n            public double MixedAttributes { get; set; }\n\n            private class Metadata\n            {\n                [Range(10, 100)]\n                public object MetadataAttributes { get; set; }\n\n                [Range(10, 100)]\n                public object MixedAttributes { get; set; }\n            }\n        }\n\n        public abstract class TestableAssociatedValidatorProvider : AssociatedValidatorProvider\n        {\n            protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders, IEnumerable<Attribute> attributes)\n            {\n                return AbstractGetValidators(metadata, validatorProviders, attributes);\n            }\n\n            public abstract IEnumerable<ModelValidator> AbstractGetValidators(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders, IEnumerable<Attribute> attributes);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Validation/Providers/DataAnnotationsModelValidatorProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Metadata.Providers;\nusing System.Web.Http.Validation.Validators;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.Validation.Providers\n{\n    public class DataAnnotationsModelValidatorProviderTest\n    {\n        private static DataAnnotationsModelMetadataProvider _metadataProvider = new DataAnnotationsModelMetadataProvider();\n        private static IEnumerable<ModelValidatorProvider> _noValidatorProviders = Enumerable.Empty<ModelValidatorProvider>();\n\n        // Validation attribute adapter registration\n\n        private class MyValidationAttribute : ValidationAttribute\n        {\n            public override bool IsValid(object value)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class MyValidationAttributeAdapter : DataAnnotationsModelValidator\n        {\n            public MyValidationAttributeAdapter(IEnumerable<ModelValidatorProvider> validatorProviders, ValidationAttribute attribute)\n                : base(validatorProviders, attribute)\n            {\n            }\n        }\n\n        private class MyValidationAttributeAdapterBadCtor : ModelValidator\n        {\n            public MyValidationAttributeAdapterBadCtor(IEnumerable<ModelValidatorProvider> validatorProviders)\n                : base(validatorProviders)\n            {\n            }\n\n            public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class MyDefaultValidationAttributeAdapter : DataAnnotationsModelValidator\n        {\n            public MyDefaultValidationAttributeAdapter(IEnumerable<ModelValidatorProvider> validatorProviders, ValidationAttribute attribute)\n                : base(validatorProviders, attribute)\n            {\n            }\n        }\n\n        [MyValidation]\n        private class MyValidatedClass\n        {\n        }\n\n        [Fact]\n        public void RegisterAdapter()\n        {\n            // Arrange\n            var provider = new DataAnnotationsModelValidatorProvider();\n            provider.AttributeFactories = new Dictionary<Type, DataAnnotationsModelValidationFactory>();\n\n            // Act\n            provider.RegisterAdapter(typeof(MyValidationAttribute), typeof(MyValidationAttributeAdapter));\n\n            // Assert\n            var type = provider.AttributeFactories.Keys.Single();\n            Assert.Equal(typeof(MyValidationAttribute), type);\n\n            var factory = provider.AttributeFactories.Values.Single();\n            var metadata = _metadataProvider.GetMetadataForType(() => null, typeof(object));\n            var attribute = new MyValidationAttribute();\n            var validator = factory(_noValidatorProviders, attribute);\n            Assert.IsType<MyValidationAttributeAdapter>(validator);\n        }\n\n        [Fact]\n        public void RegisterAdapterGuardClauses()\n        {\n            var provider = new DataAnnotationsModelValidatorProvider();\n\n            // Attribute type cannot be null\n            Assert.ThrowsArgumentNull(\n                () => provider.RegisterAdapter(null, typeof(MyValidationAttributeAdapter)),\n                \"attributeType\");\n\n            // Adapter type cannot be null\n            Assert.ThrowsArgumentNull(\n                () => provider.RegisterAdapter(typeof(MyValidationAttribute), null),\n                \"adapterType\");\n\n            // Validation attribute must derive from ValidationAttribute\n            Assert.ThrowsArgument(\n                () => provider.RegisterAdapter(typeof(object), typeof(MyValidationAttributeAdapter)),\n                \"attributeType\",\n                \"The type Object must derive from ValidationAttribute\");\n\n            // Adapter must derive from ModelValidator\n            Assert.ThrowsArgument(\n                () => provider.RegisterAdapter(typeof(MyValidationAttribute), typeof(object)),\n                \"adapterType\",\n                \"The type Object must derive from ModelValidator\");\n\n            // Adapter must have the expected constructor\n            Assert.ThrowsArgument(\n                () => provider.RegisterAdapter(typeof(MyValidationAttribute), typeof(MyValidationAttributeAdapterBadCtor)),\n                \"adapterType\",\n                \"The type MyValidationAttributeAdapterBadCtor must have a public constructor which accepts three parameters of types ModelMetadata, IEnumerable<ModelValidatorProvider>, and MyValidationAttribute\");\n        }\n\n        [Fact]\n        public void RegisterAdapterFactory()\n        {\n            // Arrange\n            var provider = new DataAnnotationsModelValidatorProvider();\n            provider.AttributeFactories = new Dictionary<Type, DataAnnotationsModelValidationFactory>();\n            DataAnnotationsModelValidationFactory factory = delegate { return null; };\n\n            // Act\n            provider.RegisterAdapterFactory(typeof(MyValidationAttribute), factory);\n\n            // Assert\n            var type = provider.AttributeFactories.Keys.Single();\n            Assert.Equal(typeof(MyValidationAttribute), type);\n            Assert.Same(factory, provider.AttributeFactories.Values.Single());\n        }\n\n        [Fact]\n        public void RegisterAdapterFactoryGuardClauses()\n        {\n            var provider = new DataAnnotationsModelValidatorProvider();\n            DataAnnotationsModelValidationFactory factory = (validatorProviders, attribute) => null;\n\n            // Attribute type cannot be null\n            Assert.ThrowsArgumentNull(\n                () => provider.RegisterAdapterFactory(null, factory),\n                \"attributeType\");\n\n            // Factory cannot be null\n            Assert.ThrowsArgumentNull(\n                () => provider.RegisterAdapterFactory(typeof(MyValidationAttribute), null),\n                \"factory\");\n\n            // Validation attribute must derive from ValidationAttribute\n            Assert.ThrowsArgument(\n                () => provider.RegisterAdapterFactory(typeof(object), factory),\n                \"attributeType\",\n                \"The type Object must derive from ValidationAttribute\");\n        }\n\n        [Fact]\n        public void RegisterDefaultAdapter()\n        {\n            // Arrange\n            var provider = new DataAnnotationsModelValidatorProvider();\n            var metadata = _metadataProvider.GetMetadataForType(() => null, typeof(MyValidatedClass));\n            provider.RegisterDefaultAdapter(typeof(MyDefaultValidationAttributeAdapter));\n\n            // Act\n            var result = provider.GetValidators(metadata, _noValidatorProviders).Single();\n\n            // Assert\n            Assert.IsType<MyDefaultValidationAttributeAdapter>(result);\n        }\n\n        [Fact]\n        public void RegisterDefaultAdapterGuardClauses()\n        {\n            var provider = new DataAnnotationsModelValidatorProvider();\n\n            // Adapter type cannot be null\n            Assert.ThrowsArgumentNull(\n                () => provider.RegisterDefaultAdapter(null),\n                \"adapterType\");\n\n            // Adapter must derive from ModelValidator\n            Assert.ThrowsArgument(\n                () => provider.RegisterDefaultAdapter(typeof(object)),\n                \"adapterType\",\n                \"The type Object must derive from ModelValidator\");\n\n            // Adapter must have the expected constructor\n            Assert.ThrowsArgument(\n                () => provider.RegisterDefaultAdapter(typeof(MyValidationAttributeAdapterBadCtor)),\n                \"adapterType\",\n                \"The type MyValidationAttributeAdapterBadCtor must have a public constructor which accepts three parameters of types ModelMetadata, IEnumerable<ModelValidatorProvider>, and ValidationAttribute\");\n        }\n\n        [Fact]\n        public void RegisterDefaultAdapterFactory()\n        {\n            // Arrange\n            var provider = new DataAnnotationsModelValidatorProvider();\n            var metadata = _metadataProvider.GetMetadataForType(() => null, typeof(MyValidatedClass));\n            ModelValidator validator = new Mock<ModelValidator>(_noValidatorProviders).Object;\n            DataAnnotationsModelValidationFactory factory = delegate { return validator; };\n            provider.RegisterDefaultAdapterFactory(factory);\n\n            // Act\n            var result = provider.GetValidators(metadata, _noValidatorProviders).Single();\n\n            // Assert\n            Assert.Same(validator, result);\n        }\n\n        [Fact]\n        public void RegisterDefaultAdapterFactoryGuardClauses()\n        {\n            var provider = new DataAnnotationsModelValidatorProvider();\n\n            // Factory cannot be null\n            Assert.ThrowsArgumentNull(\n                () => provider.RegisterDefaultAdapterFactory(null),\n                \"factory\");\n        }\n\n        // IValidatableObject adapter registration\n\n        private class MyValidatableAdapter : ModelValidator\n        {\n            public MyValidatableAdapter(IEnumerable<ModelValidatorProvider> validatorProviders)\n                : base(validatorProviders)\n            {\n            }\n\n            public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class MyValidatableAdapterBadCtor : ModelValidator\n        {\n            public MyValidatableAdapterBadCtor(IEnumerable<ModelValidatorProvider> validatorProviders, int unused)\n                : base(validatorProviders)\n            {\n            }\n\n            public override IEnumerable<ModelValidationResult> Validate(ModelMetadata metadata, object container)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class MyValidatableClass : IValidatableObject\n        {\n            public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        [Fact]\n        public void RegisterValidatableObjectAdapter()\n        {\n            // Arrange\n            var provider = new DataAnnotationsModelValidatorProvider();\n            provider.ValidatableFactories = new Dictionary<Type, DataAnnotationsValidatableObjectAdapterFactory>();\n            IValidatableObject validatable = new Mock<IValidatableObject>().Object;\n\n            // Act\n            provider.RegisterValidatableObjectAdapter(validatable.GetType(), typeof(MyValidatableAdapter));\n\n            // Assert\n            var type = provider.ValidatableFactories.Keys.Single();\n            Assert.Equal(validatable.GetType(), type);\n\n            var factory = provider.ValidatableFactories.Values.Single();\n            var metadata = _metadataProvider.GetMetadataForType(() => null, typeof(object));\n            var validator = factory(_noValidatorProviders);\n            Assert.IsType<MyValidatableAdapter>(validator);\n        }\n\n        [Fact]\n        public void RegisterValidatableObjectAdapterGuardClauses()\n        {\n            var provider = new DataAnnotationsModelValidatorProvider();\n\n            // Attribute type cannot be null\n            Assert.ThrowsArgumentNull(\n                () => provider.RegisterValidatableObjectAdapter(null, typeof(MyValidatableAdapter)),\n                \"modelType\");\n\n            // Adapter type cannot be null\n            Assert.ThrowsArgumentNull(\n                () => provider.RegisterValidatableObjectAdapter(typeof(MyValidatableClass), null),\n                \"adapterType\");\n\n            // Validation attribute must derive from ValidationAttribute\n            Assert.ThrowsArgument(\n                () => provider.RegisterValidatableObjectAdapter(typeof(object), typeof(MyValidatableAdapter)),\n                \"modelType\",\n                \"The type Object must derive from IValidatableObject.\");\n\n            // Adapter must derive from ModelValidator\n            Assert.ThrowsArgument(\n                () => provider.RegisterValidatableObjectAdapter(typeof(MyValidatableClass), typeof(object)),\n                \"adapterType\",\n                \"The type Object must derive from ModelValidator\");\n\n            // Adapter must have the expected constructor\n            Assert.ThrowsArgument(\n                () => provider.RegisterValidatableObjectAdapter(typeof(MyValidatableClass), typeof(MyValidatableAdapterBadCtor)),\n                \"adapterType\",\n                \"The type MyValidatableAdapterBadCtor must have a public constructor which accepts two parameters of types ModelMetadata and IEnumerable<ModelValidatorProvider>\");\n        }\n\n        [Fact]\n        public void RegisterValidatableObjectAdapterFactory()\n        {\n            // Arrange\n            var provider = new DataAnnotationsModelValidatorProvider();\n            provider.ValidatableFactories = new Dictionary<Type, DataAnnotationsValidatableObjectAdapterFactory>();\n            DataAnnotationsValidatableObjectAdapterFactory factory = delegate { return null; };\n\n            // Act\n            provider.RegisterValidatableObjectAdapterFactory(typeof(MyValidatableClass), factory);\n\n            // Assert\n            var type = provider.ValidatableFactories.Keys.Single();\n            Assert.Equal(typeof(MyValidatableClass), type);\n            Assert.Same(factory, provider.ValidatableFactories.Values.Single());\n        }\n\n        [Fact]\n        public void RegisterValidatableObjectAdapterFactoryGuardClauses()\n        {\n            var provider = new DataAnnotationsModelValidatorProvider();\n            DataAnnotationsValidatableObjectAdapterFactory factory = (context) => null;\n\n            // Attribute type cannot be null\n            Assert.ThrowsArgumentNull(\n                () => provider.RegisterValidatableObjectAdapterFactory(null, factory),\n                \"modelType\");\n\n            // Factory cannot be null\n            Assert.ThrowsArgumentNull(\n                () => provider.RegisterValidatableObjectAdapterFactory(typeof(MyValidatableClass), null),\n                \"factory\");\n\n            // Validation attribute must derive from ValidationAttribute\n            Assert.ThrowsArgument(\n                () => provider.RegisterValidatableObjectAdapterFactory(typeof(object), factory),\n                \"modelType\",\n                \"The type Object must derive from IValidatableObject\");\n        }\n\n        [Fact]\n        public void RegisterDefaultValidatableObjectAdapter()\n        {\n            // Arrange\n            var provider = new DataAnnotationsModelValidatorProvider();\n            var metadata = _metadataProvider.GetMetadataForType(() => null, typeof(MyValidatableClass));\n            provider.RegisterDefaultValidatableObjectAdapter(typeof(MyValidatableAdapter));\n\n            // Act\n            var result = provider.GetValidators(metadata, _noValidatorProviders).Single();\n\n            // Assert\n            Assert.IsType<MyValidatableAdapter>(result);\n        }\n\n        [Fact]\n        public void RegisterDefaultValidatableObjectAdapterGuardClauses()\n        {\n            var provider = new DataAnnotationsModelValidatorProvider();\n\n            // Adapter type cannot be null\n            Assert.ThrowsArgumentNull(\n                () => provider.RegisterDefaultValidatableObjectAdapter(null),\n                \"adapterType\");\n\n            // Adapter must derive from ModelValidator\n            Assert.ThrowsArgument(\n                () => provider.RegisterDefaultValidatableObjectAdapter(typeof(object)),\n                \"adapterType\",\n                \"The type Object must derive from ModelValidator\");\n\n            // Adapter must have the expected constructor\n            Assert.ThrowsArgument(\n                () => provider.RegisterDefaultValidatableObjectAdapter(typeof(MyValidatableAdapterBadCtor)),\n                \"adapterType\",\n                \"The type MyValidatableAdapterBadCtor must have a public constructor which accepts two parameters of types ModelMetadata and IEnumerable<ModelValidatorProvider>\");\n        }\n\n        [Fact]\n        public void RegisterDefaultValidatableObjectAdapterFactory()\n        {\n            // Arrange\n            var provider = new DataAnnotationsModelValidatorProvider();\n            var metadata = _metadataProvider.GetMetadataForType(() => null, typeof(MyValidatableClass));\n            ModelValidator validator = new Mock<ModelValidator>(_noValidatorProviders).Object;\n            DataAnnotationsValidatableObjectAdapterFactory factory = delegate { return validator; };\n            provider.RegisterDefaultValidatableObjectAdapterFactory(factory);\n\n            // Act\n            var result = provider.GetValidators(metadata, _noValidatorProviders).Single();\n\n            // Assert\n            Assert.Same(validator, result);\n        }\n\n        [Fact]\n        public void RegisterDefaultValidatableObjectAdapterFactoryGuardClauses()\n        {\n            var provider = new DataAnnotationsModelValidatorProvider();\n\n            // Factory cannot be null\n            Assert.ThrowsArgumentNull(\n                () => provider.RegisterDefaultValidatableObjectAdapterFactory(null),\n                \"factory\");\n        }\n\n        // Default adapter factory for unknown attribute type\n\n        [Fact]\n        public void UnknownValidationAttributeGetsDefaultAdapter()\n        {\n            // Arrange\n            var provider = new DataAnnotationsModelValidatorProvider();\n            var metadata = _metadataProvider.GetMetadataForType(() => null, typeof(DummyClassWithDummyValidationAttribute));\n\n            // Act\n            IEnumerable<ModelValidator> validators = provider.GetValidators(metadata, _noValidatorProviders);\n\n            // Assert\n            var validator = validators.Single();\n            Assert.IsType<DataAnnotationsModelValidator>(validator);\n        }\n\n        private class DummyValidationAttribute : ValidationAttribute\n        {\n        }\n\n        [DummyValidation]\n        private class DummyClassWithDummyValidationAttribute\n        {\n        }\n\n        // Default IValidatableObject adapter factory\n\n        [Fact]\n        public void IValidatableObjectGetsAValidator()\n        {\n            // Arrange\n            var provider = new DataAnnotationsModelValidatorProvider();\n            var mockValidatable = new Mock<IValidatableObject>();\n            var metadata = _metadataProvider.GetMetadataForType(() => null, mockValidatable.Object.GetType());\n\n            // Act\n            IEnumerable<ModelValidator> validators = provider.GetValidators(metadata, _noValidatorProviders);\n\n            // Assert\n            Assert.Single(validators);\n        }\n\n        // Integration with metadata system\n\n        [Fact]\n        public void DoesNotReadPropertyValue()\n        {\n            // Arrange\n            var provider = new DataAnnotationsModelValidatorProvider();\n            var model = new ObservableModel();\n            ModelMetadata metadata = _metadataProvider.GetMetadataForProperty(() => model.TheProperty, typeof(ObservableModel), \"TheProperty\");\n\n            // Act\n            ModelValidator[] validators = provider.GetValidators(metadata, _noValidatorProviders).ToArray();\n            ModelValidationResult[] results = validators.SelectMany(o => o.Validate(metadata, model)).ToArray();\n\n            // Assert\n            Assert.Empty(validators);\n            Assert.False(model.PropertyWasRead());\n        }\n\n        private class ObservableModel\n        {\n            private bool _propertyWasRead;\n\n            public string TheProperty\n            {\n                get\n                {\n                    _propertyWasRead = true;\n                    return \"Hello\";\n                }\n            }\n\n            public bool PropertyWasRead()\n            {\n                return _propertyWasRead;\n            }\n        }\n\n        private class BaseModel\n        {\n            public virtual string MyProperty { get; set; }\n        }\n\n        private class DerivedModel : BaseModel\n        {\n            [StringLength(10)]\n            public override string MyProperty\n            {\n                get { return base.MyProperty; }\n                set { base.MyProperty = value; }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Validation/Providers/DataMemberModelValidatorProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Runtime.Serialization;\nusing System.Web.Http.Metadata.Providers;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Validation.Providers\n{\n    public class DataMemberModelValidatorProviderTest\n    {\n        private static DataAnnotationsModelMetadataProvider _metadataProvider = new DataAnnotationsModelMetadataProvider();\n\n        [Fact]\n        public void ClassWithoutAttributes_NoValidator()\n        {\n            // Arrange\n            var provider = new DataMemberModelValidatorProvider();\n            var metadata = _metadataProvider.GetMetadataForProperty(() => null, typeof(ClassWithoutAttributes), \"TheProperty\");\n\n            // Act\n            IEnumerable<ModelValidator> validators = provider.GetValidators(metadata, new[] { provider });\n\n            // Assert\n            Assert.Empty(validators);\n        }\n\n        class ClassWithoutAttributes\n        {\n            public int TheProperty { get; set; }\n        }\n\n        [Fact]\n        public void ClassWithDataMemberIsRequiredTrue_Validator()\n        {\n            // Arrange\n            var provider = new DataMemberModelValidatorProvider();\n            var metadata = _metadataProvider.GetMetadataForProperty(() => null, typeof(ClassWithDataMemberIsRequiredTrue), \"TheProperty\");\n\n            // Act\n            IEnumerable<ModelValidator> validators = provider.GetValidators(metadata, new[] { provider });\n\n            // Assert\n            ModelValidator validator = Assert.Single(validators);\n            Assert.True(validator.IsRequired);\n        }\n\n        [DataContract]\n        class ClassWithDataMemberIsRequiredTrue\n        {\n            [DataMember(IsRequired = true)]\n            public int TheProperty { get; set; }\n        }\n\n        [Fact]\n        public void ClassWithDataMemberIsRequiredFalse_NoValidator()\n        {\n            // Arrange\n            var provider = new DataMemberModelValidatorProvider();\n            var metadata = _metadataProvider.GetMetadataForProperty(() => null, typeof(ClassWithDataMemberIsRequiredFalse), \"TheProperty\");\n\n            // Act\n            IEnumerable<ModelValidator> validators = provider.GetValidators(metadata, new[] { provider });\n\n            // Assert\n            Assert.Empty(validators);\n        }\n\n        [DataContract]\n        class ClassWithDataMemberIsRequiredFalse\n        {\n            [DataMember(IsRequired = false)]\n            public int TheProperty { get; set; }\n        }\n\n        [Fact]\n        public void ClassWithDataMemberIsRequiredTrueWithoutDataContract_NoValidator()\n        {\n            // Arrange\n            var provider = new DataMemberModelValidatorProvider();\n            var metadata = _metadataProvider.GetMetadataForProperty(() => null, typeof(ClassWithDataMemberIsRequiredTrueWithoutDataContract), \"TheProperty\");\n\n            // Act\n            IEnumerable<ModelValidator> validators = provider.GetValidators(metadata, new[] { provider });\n\n            // Assert\n            Assert.Empty(validators);\n        }\n\n        class ClassWithDataMemberIsRequiredTrueWithoutDataContract\n        {\n            [DataMember(IsRequired = true)]\n            public int TheProperty { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Validation/Providers/InvalidModelValidatorProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing System.Runtime.Serialization;\nusing System.Web.Http.Metadata.Providers;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Validation.Providers\n{\n    public class InvalidModelValidatorProviderTest\n    {\n        private static DataAnnotationsModelMetadataProvider _metadataProvider = new DataAnnotationsModelMetadataProvider();\n        private static IEnumerable<ModelValidatorProvider> _noValidatorProviders = Enumerable.Empty<ModelValidatorProvider>();\n\n        [Fact]\n        public void GetValidatorsReturnsNothingForValidModel()\n        {\n            InvalidModelValidatorProvider validatorProvider = new InvalidModelValidatorProvider();\n\n            IEnumerable<ModelValidator> validators = validatorProvider.GetValidators(_metadataProvider.GetMetadataForType(null, typeof(ValidModel)), _noValidatorProviders);\n\n            Assert.Empty(validators);\n        }\n\n        [Fact]\n        public void GetValidatorsReturnsInvalidModelValidatorsForInvalidModelType()\n        {\n            InvalidModelValidatorProvider validatorProvider = new InvalidModelValidatorProvider();\n\n            IEnumerable<ModelValidator> validators = validatorProvider.GetValidators(_metadataProvider.GetMetadataForType(null, typeof(InvalidModel)), _noValidatorProviders);\n\n            Assert.Equal(2, validators.Count());\n            Assert.Throws<InvalidOperationException>(() => validators.ElementAt(0).Validate(null, null),\n                \"Non-public property 'Internal' on type 'System.Web.Http.Validation.Providers.InvalidModelValidatorProviderTest+InvalidModel' is attributed with one or more validation attributes. Validation attributes on non-public properties are not supported. Consider using a public property for validation instead.\");\n            Assert.Throws<InvalidOperationException>(() => validators.ElementAt(1).Validate(null, null),\n                \"Field 'Field' on type 'System.Web.Http.Validation.Providers.InvalidModelValidatorProviderTest+InvalidModel' is attributed with one or more validation attributes. Validation attributes on fields are not supported. Consider using a public property for validation instead.\");\n        }\n\n        [Fact]\n        public void GetValidatorsReturnsInvalidModelValidatorsForInvalidModelProperty()\n        {\n            InvalidModelValidatorProvider validatorProvider = new InvalidModelValidatorProvider();\n\n            IEnumerable<ModelValidator> validators = validatorProvider.GetValidators(_metadataProvider.GetMetadataForProperty(null, typeof(InvalidModel), \"Value\"), _noValidatorProviders);\n\n            ModelValidator validator = Assert.Single(validators);\n            Assert.Throws<InvalidOperationException>(() => validator.Validate(null, null),\n                \"Property 'Value' on type 'System.Web.Http.Validation.Providers.InvalidModelValidatorProviderTest+InvalidModel' is invalid. Value-typed properties marked as [Required] must also be marked with [DataMember(IsRequired=true)] to be recognized as required. Consider attributing the declaring type with [DataContract] and the property with [DataMember(IsRequired=true)].\");\n        }\n\n        [DataContract]\n        public class ValidModel\n        {\n            [Required]\n            [DataMember]\n            [StringLength(10)]\n            public string Ref { get; set; }\n\n            [DataMember]\n            internal string Internal { get; set; }\n\n            [Required]\n            [DataMember(IsRequired=true)]\n            public int Value { get; set; }\n\n            public string Field;\n        }\n\n        public class InvalidModel\n        {\n            [Required]\n            public string Ref { get; set; }\n\n            [StringLength(10)]\n            [RegularExpression(\"pattern\")]\n            internal string Internal { get; set; }\n\n            [Required]\n            public int Value { get; set; }\n\n            [StringLength(10)]\n            public string Field;\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Test/Validation/ReferenceEqualityComparerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Validation\n{\n    public class ReferenceEqualityComparerTest\n    {\n        [Fact]\n        public void Equals_ReturnsTrue_ForSameObject()\n        {\n            object o = new object();\n            Assert.True(ReferenceEqualityComparer.Instance.Equals(o, o));\n        }\n\n        [Fact]\n        public void Equals_ReturnsFalse_ForDifferentObject()\n        {\n            Object o1 = new Object();\n            Object o2 = new Object();\n\n            Assert.False(ReferenceEqualityComparer.Instance.Equals(o1, o2));\n        }\n\n        [Fact]\n        public void Equals_DoesntCall_OverriddenEqualsOnTheType()\n        {\n            TypeThatOverridesEquals t1 = new TypeThatOverridesEquals();\n            TypeThatOverridesEquals t2 = new TypeThatOverridesEquals();\n\n            Assert.DoesNotThrow(() => ReferenceEqualityComparer.Instance.Equals(t1, t2));\n        }\n\n        [Fact]\n        public void Equals_ReturnsFalse_ValueType()\n        {\n            Assert.False(ReferenceEqualityComparer.Instance.Equals(42, 42));\n        }\n\n        [Fact]\n        public void Equals_NullEqualsNull()\n        {\n            var comparer = ReferenceEqualityComparer.Instance;\n            Assert.True(comparer.Equals(null, null));\n        }\n\n        [Fact]\n        public void GetHashCode_ReturnsSameValueForSameObject()\n        {\n            object o = new object();\n            var comparer = ReferenceEqualityComparer.Instance;\n            Assert.Equal(comparer.GetHashCode(o), comparer.GetHashCode(o));\n        }\n\n        [Fact]\n        public void GetHashCode_DoesNotThrowForNull()\n        {\n            var comparer = ReferenceEqualityComparer.Instance;\n            Assert.DoesNotThrow(() => comparer.GetHashCode(null));\n        }\n\n        private class TypeThatOverridesEquals\n        {\n            public override bool Equals(object obj)\n            {\n                throw new InvalidOperationException();\n            }\n\n            public override int GetHashCode()\n            {\n                throw new InvalidOperationException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Validation/Validators/DataAnnotationsModelValidatorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing System.Web.Http.Metadata;\nusing System.Web.Http.Metadata.Providers;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\nusing Moq;\nusing Moq.Protected;\n\nnamespace System.Web.Http.Validation.Validators\n{\n    public class DataAnnotationsModelValidatorTest\n    {\n        private static DataAnnotationsModelMetadataProvider _metadataProvider = new DataAnnotationsModelMetadataProvider();\n        private static IEnumerable<ModelValidatorProvider> _noValidatorProviders = Enumerable.Empty<ModelValidatorProvider>();\n\n        [Fact]\n        public void ConstructorGuards()\n        {\n            // Arrange\n            ModelMetadata metadata = _metadataProvider.GetMetadataForType(null, typeof(object));\n            var attribute = new RequiredAttribute();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => new DataAnnotationsModelValidator(null, attribute),\n                \"validatorProviders\");\n            Assert.ThrowsArgumentNull(\n                () => new DataAnnotationsModelValidator(_noValidatorProviders, null),\n                \"attribute\");\n        }\n\n        [Fact]\n        public void ValuesSet()\n        {\n            // Arrange\n            ModelMetadata metadata = _metadataProvider.GetMetadataForProperty(() => 15, typeof(string), \"Length\");\n            var attribute = new RequiredAttribute();\n\n            // Act\n            var validator = new DataAnnotationsModelValidator(_noValidatorProviders, attribute);\n\n            // Assert\n            Assert.Same(attribute, validator.Attribute);\n        }\n\n        public static TheoryDataSet<NameValueCollection> FalseAppSettingsData\n        {\n            get\n            {\n                return new TheoryDataSet<NameValueCollection>\n                {\n                    new NameValueCollection(),\n                    new NameValueCollection\n                    {\n                        { DataAnnotationsModelValidator.UseLegacyValidationMemberNameKey, \"false\" },\n                    },\n                    new NameValueCollection\n                    {\n                        { DataAnnotationsModelValidator.UseLegacyValidationMemberNameKey, \"False\" },\n                    },\n                    new NameValueCollection\n                    {\n                        { DataAnnotationsModelValidator.UseLegacyValidationMemberNameKey, \"false\" },\n                        { DataAnnotationsModelValidator.UseLegacyValidationMemberNameKey, \"true\" },\n                    },\n                    new NameValueCollection\n                    {\n                        { DataAnnotationsModelValidator.UseLegacyValidationMemberNameKey, \"garbage\" },\n                    },\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"FalseAppSettingsData\")]\n        public void GetUseLegacyValidationMemberName_ReturnsFalse(NameValueCollection appSettings)\n        {\n            // Arrange & Act\n            var result = DataAnnotationsModelValidator.GetUseLegacyValidationMemberName(appSettings);\n\n            // Assert\n            Assert.False(result);\n        }\n\n        public static TheoryDataSet<NameValueCollection> TrueAppSettingsData\n        {\n            get\n            {\n                return new TheoryDataSet<NameValueCollection>\n                {\n                    new NameValueCollection\n                    {\n                        { DataAnnotationsModelValidator.UseLegacyValidationMemberNameKey, \"true\" },\n                    },\n                    new NameValueCollection\n                    {\n                        { DataAnnotationsModelValidator.UseLegacyValidationMemberNameKey, \"True\" },\n                    },\n                    new NameValueCollection\n                    {\n                        { DataAnnotationsModelValidator.UseLegacyValidationMemberNameKey, \"true\" },\n                        { DataAnnotationsModelValidator.UseLegacyValidationMemberNameKey, \"false\" },\n                    },\n                    new NameValueCollection\n                    {\n                        { DataAnnotationsModelValidator.UseLegacyValidationMemberNameKey, \"true\" },\n                        { DataAnnotationsModelValidator.UseLegacyValidationMemberNameKey, \"false\" },\n                        { DataAnnotationsModelValidator.UseLegacyValidationMemberNameKey, \"garbage\" },\n                    },\n                    new NameValueCollection\n                    {\n                        { DataAnnotationsModelValidator.UseLegacyValidationMemberNameKey, \"True\" },\n                        { DataAnnotationsModelValidator.UseLegacyValidationMemberNameKey, \"garbage\" },\n                    },\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"TrueAppSettingsData\")]\n        public void GetUseLegacyValidationMemberName_ReturnsTrue(NameValueCollection appSettings)\n        {\n            // Arrange & Act\n            var result = DataAnnotationsModelValidator.GetUseLegacyValidationMemberName(appSettings);\n\n            // Assert\n            Assert.True(result);\n        }\n\n        public static TheoryDataSet<ModelMetadata, string> ValidateSetsMemberNamePropertyDataSet\n        {\n            get\n            {\n                return new TheoryDataSet<ModelMetadata, string>\n                {\n                    {\n                        _metadataProvider.GetMetadataForProperty(() => 15, typeof(string), \"Length\"),\n                        \"Length\"\n                    },\n                    {\n                        _metadataProvider.GetMetadataForProperty(() => string.Empty, typeof(AnnotatedModel), \"Name\"),\n                        \"Name\"\n                    },\n                    {\n                        _metadataProvider.GetMetadataForType(() => new object(), typeof(SampleModel)),\n                        \"SampleModel\"\n                    },\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"ValidateSetsMemberNamePropertyDataSet\")]\n        public void ValidateSetsMemberNamePropertyOfValidationContextForProperties(ModelMetadata metadata, string expectedMemberName)\n        {\n            // Arrange\n            var attribute = new Mock<ValidationAttribute> { CallBase = true };\n            attribute.Protected()\n                     .Setup<ValidationResult>(\"IsValid\", ItExpr.IsAny<object>(), ItExpr.IsAny<ValidationContext>())\n                     .Callback((object o, ValidationContext context) =>\n                     {\n                         Assert.Equal(expectedMemberName, context.MemberName);\n                     })\n                     .Returns(ValidationResult.Success)\n                     .Verifiable();\n            DataAnnotationsModelValidator validator = new DataAnnotationsModelValidator(_noValidatorProviders, attribute.Object);\n\n            // Act\n            IEnumerable<ModelValidationResult> results = validator.Validate(metadata, container: null);\n\n            // Assert\n            Assert.Empty(results);\n            attribute.VerifyAll();\n        }\n\n        [Fact]\n        public void ValidateSetsMemberNameProperty_UsingDisplayName()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(ValidateSetsMemberNameProperty_UsingDisplayName_Inner);\n        }\n\n        private static void ValidateSetsMemberNameProperty_UsingDisplayName_Inner()\n        {\n            // Arrange\n            DataAnnotationsModelValidator.UseLegacyValidationMemberName = true;\n            var expectedMemberName = \"Annotated Name\";\n            var attribute = new Mock<ValidationAttribute> { CallBase = true };\n            attribute\n                .Protected()\n                .Setup<ValidationResult>(\"IsValid\", ItExpr.IsAny<object>(), ItExpr.IsAny<ValidationContext>())\n                .Callback((object o, ValidationContext context) =>\n                {\n                    Assert.Equal(expectedMemberName, context.MemberName);\n                })\n                .Returns(ValidationResult.Success)\n                .Verifiable();\n            var validator = new DataAnnotationsModelValidator(_noValidatorProviders, attribute.Object);\n            var metadata = _metadataProvider.GetMetadataForProperty(() => string.Empty, typeof(AnnotatedModel), \"Name\");\n\n            // Act\n            var results = validator.Validate(metadata, container: null);\n\n            // Assert\n            Assert.Empty(results);\n            attribute.VerifyAll();\n        }\n\n        // Confirm explicit false setting does not change Validate(...)'s behavior from its default.\n        [Fact]\n        public void ValidateSetsMemberNameProperty_NotUsingDisplayName()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(ValidateSetsMemberNameProperty_NotUsingDisplayName_Inner);\n        }\n\n        private static void ValidateSetsMemberNameProperty_NotUsingDisplayName_Inner()\n        {\n            // Arrange\n            DataAnnotationsModelValidator.UseLegacyValidationMemberName = false;\n            var expectedMemberName = \"Name\";\n            var attribute = new Mock<ValidationAttribute> { CallBase = true };\n            attribute\n                .Protected()\n                .Setup<ValidationResult>(\"IsValid\", ItExpr.IsAny<object>(), ItExpr.IsAny<ValidationContext>())\n                .Callback((object o, ValidationContext context) =>\n                {\n                    Assert.Equal(expectedMemberName, context.MemberName);\n                })\n                .Returns(ValidationResult.Success)\n                .Verifiable();\n            var validator = new DataAnnotationsModelValidator(_noValidatorProviders, attribute.Object);\n            var metadata = _metadataProvider.GetMetadataForProperty(() => string.Empty, typeof(AnnotatedModel), \"Name\");\n\n            // Act\n            var results = validator.Validate(metadata, container: null);\n\n            // Assert\n            Assert.Empty(results);\n            attribute.VerifyAll();\n        }\n\n        public static TheoryDataSet<ModelMetadata, string> ValidateSetsDisplayNamePropertyDataSet\n        {\n            get\n            {\n                return new TheoryDataSet<ModelMetadata, string>\n                {\n                    {\n                        _metadataProvider.GetMetadataForProperty(() => 15, typeof(string), \"Length\"),\n                        \"Length\"\n                    },\n                    {\n                        _metadataProvider.GetMetadataForProperty(() => string.Empty, typeof(AnnotatedModel), \"Name\"),\n                        \"Annotated Name\"\n                    },\n                    {\n                        _metadataProvider.GetMetadataForType(() => new object(), typeof(SampleModel)),\n                        \"SampleModel\"\n                    },\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"ValidateSetsDisplayNamePropertyDataSet\")]\n        public void ValidateSetsDisplayNamePropertyOfValidationContextAsExpected(\n            ModelMetadata metadata,\n            string expectedDisplayName)\n        {\n            // Arrange\n            var attribute = new Mock<ValidationAttribute>\n            {\n                CallBase = true,\n            };\n            attribute\n                .Protected()\n                .Setup<ValidationResult>(\"IsValid\", ItExpr.IsAny<object>(), ItExpr.IsAny<ValidationContext>())\n                .Callback(\n                    (object o, ValidationContext context) => Assert.Equal(expectedDisplayName, context.DisplayName))\n                .Returns(ValidationResult.Success)\n                .Verifiable();\n            DataAnnotationsModelValidator validator = new DataAnnotationsModelValidator(\n                _noValidatorProviders,\n                attribute.Object);\n\n            // Act\n            IEnumerable<ModelValidationResult> results = validator.Validate(metadata, container: null);\n\n            // Assert\n            Assert.Empty(results);\n            attribute.VerifyAll();\n        }\n\n        [Fact]\n        public void ValidateWithIsValidTrue()\n        {\n            // Arrange\n            ModelMetadata metadata = _metadataProvider.GetMetadataForProperty(() => 15, typeof(string), \"Length\");\n            Mock<ValidationAttribute> attribute = new Mock<ValidationAttribute> { CallBase = true };\n            attribute.Setup(a => a.IsValid(metadata.Model)).Returns(true);\n            DataAnnotationsModelValidator validator = new DataAnnotationsModelValidator(_noValidatorProviders, attribute.Object);\n\n            // Act\n            IEnumerable<ModelValidationResult> result = validator.Validate(metadata, null);\n\n            // Assert\n            Assert.Empty(result);\n        }\n\n        [Fact]\n        public void ValidateWithIsValidFalse()\n        {\n            // Arrange\n            ModelMetadata metadata = _metadataProvider.GetMetadataForProperty(() => 15, typeof(string), \"Length\");\n            Mock<ValidationAttribute> attribute = new Mock<ValidationAttribute> { CallBase = true };\n            attribute.Setup(a => a.IsValid(metadata.Model)).Returns(false);\n            DataAnnotationsModelValidator validator = new DataAnnotationsModelValidator(_noValidatorProviders, attribute.Object);\n\n            // Act\n            IEnumerable<ModelValidationResult> result = validator.Validate(metadata, null);\n\n            // Assert\n            var validationResult = result.Single();\n            Assert.Equal(\"\", validationResult.MemberName);\n            Assert.Equal(attribute.Object.FormatErrorMessage(\"Length\"), validationResult.Message);\n        }\n\n        [Fact]\n        public void ValidatateWithValidationResultSuccess()\n        {\n            // Arrange\n            ModelMetadata metadata = _metadataProvider.GetMetadataForProperty(() => 15, typeof(string), \"Length\");\n            Mock<ValidationAttribute> attribute = new Mock<ValidationAttribute> { CallBase = true };\n            attribute.Protected()\n                     .Setup<ValidationResult>(\"IsValid\", ItExpr.IsAny<object>(), ItExpr.IsAny<ValidationContext>())\n                     .Returns(ValidationResult.Success);\n            DataAnnotationsModelValidator validator = new DataAnnotationsModelValidator(_noValidatorProviders, attribute.Object);\n\n            // Act\n            IEnumerable<ModelValidationResult> result = validator.Validate(metadata, null);\n\n            // Assert\n            Assert.Empty(result);\n        }\n\n        [Fact]\n        public void ValidateReturnsSingleValidationResultIfMemberNameSequenceIsEmpty()\n        {\n            // Arrange\n            const string errorMessage = \"Some error message\";\n            ModelMetadata metadata = _metadataProvider.GetMetadataForProperty(() => 15, typeof(string), \"Length\");\n            Mock<ValidationAttribute> attribute = new Mock<ValidationAttribute> { CallBase = true };\n            attribute.Protected()\n                     .Setup<ValidationResult>(\"IsValid\", ItExpr.IsAny<object>(), ItExpr.IsAny<ValidationContext>())\n                     .Returns(new ValidationResult(errorMessage, memberNames: null));\n            var validator = new DataAnnotationsModelValidator(_noValidatorProviders, attribute.Object);\n\n            // Act\n            IEnumerable<ModelValidationResult> results = validator.Validate(metadata, container: null);\n\n            // Assert\n            ModelValidationResult validationResult = Assert.Single(results);\n            Assert.Equal(errorMessage, validationResult.Message);\n            Assert.Empty(validationResult.MemberName);\n        }\n\n        [Fact]\n        public void ValidateReturnsSingleValidationResultIfOneMemberNameIsSpecified()\n        {\n            // Arrange\n            const string errorMessage = \"A different error message\";\n            ModelMetadata metadata = _metadataProvider.GetMetadataForType(() => new object(), typeof(object));\n            Mock<ValidationAttribute> attribute = new Mock<ValidationAttribute> { CallBase = true };\n            attribute.Protected()\n                     .Setup<ValidationResult>(\"IsValid\", ItExpr.IsAny<object>(), ItExpr.IsAny<ValidationContext>())\n                     .Returns(new ValidationResult(errorMessage, new[] { \"FirstName\" }));\n            var validator = new DataAnnotationsModelValidator(_noValidatorProviders, attribute.Object);\n\n            // Act\n            IEnumerable<ModelValidationResult> results = validator.Validate(metadata, container: null);\n\n            // Assert\n            ModelValidationResult validationResult = Assert.Single(results);\n            Assert.Equal(errorMessage, validationResult.Message);\n            Assert.Equal(\"FirstName\", validationResult.MemberName);\n        }\n\n        [Fact]\n        public void ValidateReturnsMemberNameIfItIsDifferentFromDisplayName()\n        {\n            // Arrange\n            ModelMetadata metadata = _metadataProvider.GetMetadataForType(() => new SampleModel(), typeof(SampleModel));\n            Mock<ValidationAttribute> attribute = new Mock<ValidationAttribute> { CallBase = true };\n            attribute.Protected()\n                     .Setup<ValidationResult>(\"IsValid\", ItExpr.IsAny<object>(), ItExpr.IsAny<ValidationContext>())\n                     .Returns(new ValidationResult(\"Name error\", new[] { \"Name\" }));\n            DataAnnotationsModelValidator validator = new DataAnnotationsModelValidator(_noValidatorProviders, attribute.Object);\n\n            // Act\n            IEnumerable<ModelValidationResult> results = validator.Validate(metadata, container: null);\n\n            // Assert\n            ModelValidationResult validationResult = Assert.Single(results);\n            Assert.Equal(\"Name\", validationResult.MemberName);\n        }\n\n        [Fact]\n        public void IsRequiredTests()\n        {\n            // Arrange\n            ModelMetadata metadata = _metadataProvider.GetMetadataForProperty(() => 15, typeof(string), \"Length\");\n\n            // Act & Assert\n            Assert.False(new DataAnnotationsModelValidator(_noValidatorProviders, new RangeAttribute(10, 20)).IsRequired);\n            Assert.True(new DataAnnotationsModelValidator(_noValidatorProviders, new RequiredAttribute()).IsRequired);\n            Assert.True(new DataAnnotationsModelValidator(_noValidatorProviders, new DerivedRequiredAttribute()).IsRequired);\n        }\n\n        class DerivedRequiredAttribute : RequiredAttribute\n        {\n        }\n\n        class SampleModel\n        {\n            public string Name { get; set; }\n        }\n\n        private class AnnotatedModel\n        {\n            [Display(Name = \"Annotated Name\")]\n            public string Name { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/Validation/Validators/ErrorModelValidatorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Http.Metadata.Providers;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Validation.Validators\n{\n    public class ErrorModelValidatorTest\n    {\n        private static DataAnnotationsModelMetadataProvider _metadataProvider = new DataAnnotationsModelMetadataProvider();\n        private static IEnumerable<ModelValidatorProvider> _noValidatorProviders = Enumerable.Empty<ModelValidatorProvider>();\n\n        [Fact]\n        public void ConstructorGuards()\n        {\n            Assert.ThrowsArgumentNull(\n                () => new ErrorModelValidator(validatorProviders: null, errorMessage: \"error\"),\n                \"validatorProviders\");\n            Assert.ThrowsArgumentNull(\n                () => new ErrorModelValidator(validatorProviders: _noValidatorProviders, errorMessage: null),\n                \"errorMessage\");\n        }\n\n        [Fact]\n        public void ValidateThrowsException()\n        {\n            ErrorModelValidator validator = new ErrorModelValidator(_noValidatorProviders, \"error\");\n\n            Assert.Throws<InvalidOperationException>(() => validator.Validate(null, null), \"error\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ValueProviders/Providers/ElementalValueProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ValueProviders.Providers\n{\n    public class ElementalValueProviderTest\n    {\n        [Theory]\n        [InlineData(\"MyProperty\", \"MyProperty\")]\n        [InlineData(\"MyProperty.SubProperty\", \"MyProperty\")]\n        [InlineData(\"MyProperty[0]\", \"MyProperty\")]\n        public void ContainsPrefix_ReturnsTrue_IfElementNameStartsWithPrefix(string elementName, string prefix)\n        {\n            // Arrange\n            CultureInfo culture = new CultureInfo(\"en-US\");\n            ElementalValueProvider elementalValueProvider = new ElementalValueProvider(elementName,\n                                                                                       new object(),\n                                                                                       culture);\n\n            // Act\n            bool containsPrefix = elementalValueProvider.ContainsPrefix(prefix);\n\n            // Assert\n            Assert.True(containsPrefix);\n        }\n\n        [Theory]\n        [InlineData(\"MyProperty\", \"MyProperty1\")]\n        [InlineData(\"MyPropertyTest\", \"MyProperty\")]\n        [InlineData(\"Random\", \"MyProperty\")]\n        public void ContainsPrefix_ReturnsFalse_IfElementCannotSpecifyValuesForPrefix(string elementName, string prefix)\n        {\n            // Arrange\n            CultureInfo culture = new CultureInfo(\"en-US\");\n            ElementalValueProvider elementalValueProvider = new ElementalValueProvider(elementName,\n                                                                                       new object(),\n                                                                                       culture);\n\n            // Act\n            bool containsPrefix = elementalValueProvider.ContainsPrefix(prefix);\n\n            // Assert\n            Assert.False(containsPrefix);\n        }\n\n        [Fact]\n        public void GetValue_NameDoesNotMatch_ReturnsNull()\n        {\n            // Arrange\n            CultureInfo culture = CultureInfo.GetCultureInfo(\"fr-FR\");\n            DateTime rawValue = new DateTime(2001, 1, 2);\n            ElementalValueProvider valueProvider = new ElementalValueProvider(\"foo\", rawValue, culture);\n\n            // Act\n            ValueProviderResult vpResult = valueProvider.GetValue(\"bar\");\n\n            // Assert\n            Assert.Null(vpResult);\n        }\n\n        [Theory]\n        [InlineData(\"foo\")]\n        [InlineData(\"FOO\")]\n        [InlineData(\"FoO\")]\n        public void GetValue_NameMatches_ReturnsValueProviderResult(string name)\n        {\n            // Arrange\n            CultureInfo culture = CultureInfo.GetCultureInfo(\"fr-FR\");\n            DateTime rawValue = new DateTime(2001, 1, 2);\n            ElementalValueProvider valueProvider = new ElementalValueProvider(\"foo\", rawValue, culture);\n\n            // Act\n            ValueProviderResult vpResult = valueProvider.GetValue(name);\n\n            // Assert\n            Assert.NotNull(vpResult);\n            Assert.Equal(rawValue, vpResult.RawValue);\n            Assert.Equal(\"02/01/2001 00:00:00\", vpResult.AttemptedValue);\n            Assert.Equal(culture, vpResult.Culture);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ValueProviders/Providers/NameValuePairsValueProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ValueProviders.Providers\n{\n    public class NameValuePairsValueProviderTest\n    {\n        private static readonly IEnumerable<KeyValuePair<string, string>> _backingStore = new KeyValuePair<string, string>[]\n        {\n            new KeyValuePair<string, string>(\"foo\", \"fooValue1\"),\n            new KeyValuePair<string, string>(\"foo\", \"fooValue2\"),\n            new KeyValuePair<string, string>(\"bar.baz\", \"someOtherValue\"),\n            new KeyValuePair<string, string>(\"null_value\", null),\n            new KeyValuePair<string, string>(\"prefix.null_value\", null)\n        };\n\n        [Fact]\n        public void Constructor_GuardClauses()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                () => new NameValuePairsValueProvider(values: (IEnumerable<KeyValuePair<string, string>>)null, culture: CultureInfo.InvariantCulture),\n                \"values\");\n\n            Assert.ThrowsArgumentNull(\n                () => new NameValuePairsValueProvider(valuesFactory: null, culture: CultureInfo.InvariantCulture),\n                \"valuesFactory\");\n        }\n\n        [Fact]\n        public void ContainsPrefix_GuardClauses()\n        {\n            // Arrange\n            var valueProvider = new NameValuePairsValueProvider(_backingStore, null);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                () => valueProvider.ContainsPrefix(null),\n                \"prefix\");\n        }\n\n        [Fact]\n        public void ContainsPrefix_WithEmptyCollection_ReturnsFalseForEmptyPrefix()\n        {\n            // Arrange\n            var valueProvider = new NameValuePairsValueProvider(Enumerable.Empty<KeyValuePair<string, string>>(), null);\n\n            // Act\n            bool result = valueProvider.ContainsPrefix(\"\");\n\n            // Assert\n            Assert.False(result);\n        }\n\n        [Fact]\n        public void ContainsPrefix_WithNonEmptyCollection_ReturnsTrueForEmptyPrefix()\n        {\n            // Arrange\n            var valueProvider = new NameValuePairsValueProvider(_backingStore, null);\n\n            // Act\n            bool result = valueProvider.ContainsPrefix(\"\");\n\n            // Assert\n            Assert.True(result);\n        }\n\n        [Fact]\n        public void ContainsPrefix_WithNonEmptyCollection_ReturnsTrueForKnownPrefixes()\n        {\n            // Arrange\n            var valueProvider = new NameValuePairsValueProvider(_backingStore, null);\n\n            // Act & Assert\n            Assert.True(valueProvider.ContainsPrefix(\"foo\"));\n            Assert.True(valueProvider.ContainsPrefix(\"bar\"));\n            Assert.True(valueProvider.ContainsPrefix(\"bar.baz\"));\n        }\n\n        [Fact]\n        public void ContainsPrefix_WithNonEmptyCollection_ReturnsFalseForUnknownPrefix()\n        {\n            // Arrange\n            var valueProvider = new NameValuePairsValueProvider(_backingStore, null);\n\n            // Act\n            bool result = valueProvider.ContainsPrefix(\"biff\");\n\n            // Assert\n            Assert.False(result);\n        }\n\n        [Fact]\n        public void GetKeysFromPrefix_GuardClauses()\n        {\n            // Arrange\n            var valueProvider = new NameValuePairsValueProvider(_backingStore, null);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                () => valueProvider.GetKeysFromPrefix(null),\n                \"prefix\");\n        }\n\n        [Fact]\n        public void GetKeysFromPrefix_EmptyPrefix_ReturnsAllPrefixes()\n        {\n            // Arrange\n            var valueProvider = new NameValuePairsValueProvider(_backingStore, null);\n\n            // Act\n            IDictionary<string, string> result = valueProvider.GetKeysFromPrefix(\"\");\n\n            // Assert\n            Assert.Equal<KeyValuePair<string, string>>(\n                result.OrderBy(kvp => kvp.Key),\n                new Dictionary<string, string> { { \"bar\", \"bar\" }, { \"foo\", \"foo\" }, { \"null_value\", \"null_value\" }, { \"prefix\", \"prefix\" } });\n        }\n\n        [Fact]\n        public void GetKeysFromPrefix_UnknownPrefix_ReturnsEmptyDictionary()\n        {\n            // Arrange\n            var valueProvider = new NameValuePairsValueProvider(_backingStore, null);\n\n            // Act\n            IDictionary<string, string> result = valueProvider.GetKeysFromPrefix(\"abc\");\n\n            // Assert\n            Assert.Empty(result);\n        }\n\n        [Fact]\n        public void GetKeysFromPrefix_KnownPrefix_ReturnsMatchingItems()\n        {\n            // Arrange\n            var valueProvider = new NameValuePairsValueProvider(_backingStore, null);\n\n            // Act\n            IDictionary<string, string> result = valueProvider.GetKeysFromPrefix(\"bar\");\n\n            // Assert\n            KeyValuePair<string, string> kvp = Assert.Single(result);\n            Assert.Equal(\"baz\", kvp.Key);\n            Assert.Equal(\"bar.baz\", kvp.Value);\n        }\n\n        [Fact]\n        public void GetValue_GuardClauses()\n        {\n            // Arrange\n            var valueProvider = new NameValuePairsValueProvider(_backingStore, null);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                () => valueProvider.GetValue(null),\n                \"key\");\n        }\n\n        [Fact]\n        public void GetValue_SingleValue()\n        {\n            // Arrange\n            var culture = CultureInfo.GetCultureInfo(\"fr-FR\");\n            var valueProvider = new NameValuePairsValueProvider(_backingStore, culture);\n\n            // Act\n            ValueProviderResult vpResult = valueProvider.GetValue(\"bar.baz\");\n\n            // Assert\n            Assert.NotNull(vpResult);\n            Assert.Equal(\"someOtherValue\", vpResult.RawValue);\n            Assert.Equal(\"someOtherValue\", vpResult.AttemptedValue);\n            Assert.Equal(culture, vpResult.Culture);\n        }\n\n        [Fact]\n        public void GetValue_MultiValue()\n        {\n            // Arrange\n            var culture = CultureInfo.GetCultureInfo(\"fr-FR\");\n            var valueProvider = new NameValuePairsValueProvider(_backingStore, culture);\n\n            // Act\n            ValueProviderResult vpResult = valueProvider.GetValue(\"foo\");\n\n            // Assert\n            Assert.NotNull(vpResult);\n            Assert.Equal(new List<string>() { \"fooValue1\", \"fooValue2\" }, (List<string>)vpResult.RawValue);\n            Assert.Equal(\"fooValue1,fooValue2\", vpResult.AttemptedValue);\n            Assert.Equal(culture, vpResult.Culture);\n        }\n\n        [Theory]\n        [InlineData(\"null_value\")]\n        [InlineData(\"prefix.null_value\")]\n        public void GetValue_NullValue(string key)\n        {\n            // Arrange\n            var culture = CultureInfo.GetCultureInfo(\"fr-FR\");\n            var valueProvider = new NameValuePairsValueProvider(_backingStore, culture);\n\n            // Act\n            ValueProviderResult vpResult = valueProvider.GetValue(key);\n\n            // Assert\n            Assert.NotNull(vpResult);\n            Assert.Null(vpResult.RawValue);\n            Assert.Null(vpResult.AttemptedValue);\n            Assert.Equal(culture, vpResult.Culture);\n        }\n\n        [Fact]\n        public void GetValue_NullMultipleValue()\n        {\n            // Arrange\n            var backingStore = new KeyValuePair<string, string>[]\n            {\n                new KeyValuePair<string, string>(\"key\", null),\n                new KeyValuePair<string, string>(\"key\", null),\n                new KeyValuePair<string, string>(\"key\", \"value\")\n            };\n            var culture = CultureInfo.GetCultureInfo(\"fr-FR\");\n            var valueProvider = new NameValuePairsValueProvider(backingStore, culture);\n\n            // Act\n            ValueProviderResult vpResult = valueProvider.GetValue(\"key\");\n\n            // Assert\n            Assert.Equal(new[] { null, null, \"value\" }, vpResult.RawValue as IEnumerable<string>);\n            Assert.Equal(\",,value\", vpResult.AttemptedValue);\n        }\n\n        [Fact]\n        public void GetValue_ReturnsNullIfKeyNotFound()\n        {\n            // Arrange\n            var valueProvider = new NameValuePairsValueProvider(_backingStore, null);\n\n            // Act\n            ValueProviderResult vpResult = valueProvider.GetValue(\"bar\");\n\n            // Assert\n            Assert.Null(vpResult);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ValueProviders/Providers/QueryStringValueProviderFactoryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ValueProviders.Providers\n{\n    public class QueryStringValueProviderFactoryTest\n    {\n        private readonly QueryStringValueProviderFactory _factory = new QueryStringValueProviderFactory();\n\n        [Fact]\n        public void GetValueProvider_WhenActionContextParameterIsNull_Throws()\n        {\n            Assert.ThrowsArgumentNull(() => _factory.GetValueProvider(actionContext: null), \"actionContext\");\n        }\n\n        [Fact]\n        public void GetValueProvider_ReturnsQueryStringValueProviderInstaceWithInvariantCulture()\n        {\n            var controllerContext = new HttpControllerContext() { Request = new HttpRequestMessage() };\n            var context = new HttpActionContext() { ControllerContext = controllerContext };\n\n            IValueProvider result = _factory.GetValueProvider(context);\n\n            var valueProvider = Assert.IsType<QueryStringValueProvider>(result);\n            Assert.Equal(CultureInfo.InvariantCulture, valueProvider.Culture);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ValueProviders/Providers/QueryStringValueProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Net.Http;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ValueProviders.Providers\n{\n    public class QueryStringValueProviderTest\n    {\n        private NameValueCollection ParseQueryString(Uri uri)\n        {\n            HttpRequestMessage request = new HttpRequestMessage { RequestUri = uri };\n            NameValueCollection nameValuePairs = new NameValueCollection();\n            foreach (KeyValuePair<string, string> keyValuePair in request.GetQueryNameValuePairs())\n            {\n                nameValuePairs.Add(keyValuePair.Key, keyValuePair.Value);\n            }\n            return nameValuePairs;\n        }\n\n        [Fact]\n        public void ParseQueryString_Null()\n        {\n            // Act\n            NameValueCollection result = ParseQueryString(null);\n\n            // Assert\n            Assert.Empty(result);\n        }\n\n        [Fact]\n        public void ParseQueryString_SingleNamelessValue()\n        {\n            // Arrange\n            Uri uri = new Uri(\"http://localhost/?key\");\n\n            // Act\n            NameValueCollection result = ParseQueryString(uri);\n\n            // Assert\n            string key = Assert.Single(result) as string;\n            Assert.Equal(\"key\", key);\n            Assert.Equal(\"\", result[key]);\n        }\n\n        [Fact]\n        public void ParseQueryString_SingleNamedValue()\n        {\n            // Arrange\n            Uri uri = new Uri(\"http://localhost/?key1=value1\");\n\n            // Act\n            NameValueCollection result = ParseQueryString(uri);\n\n            // Assert\n            string key = Assert.Single(result) as string;\n            Assert.Equal(\"key1\", key);\n            Assert.Equal(\"value1\", result[key]);\n        }\n\n        [Fact]\n        public void ParseQueryString_TwoNamedValues()\n        {\n            // Arrange\n            Uri uri = new Uri(\"http://localhost/?key1=value1&key2=value2\");\n\n            // Act\n            NameValueCollection result = ParseQueryString(uri);\n\n            // Assert\n            Assert.Equal(2, result.Count);\n            Assert.Equal(\"value1\", result[\"key1\"]);\n            Assert.Equal(\"value2\", result[\"key2\"]);\n        }\n\n        [Fact]\n        public void ParseQueryString_MixedNamedAndUnnamedValues()\n        {\n            // Arrange\n            Uri uri = new Uri(\"http://localhost/?key1=value1&key2\");\n\n            // Act\n            NameValueCollection result = ParseQueryString(uri);\n\n            // Assert\n            Assert.Equal(2, result.Count);\n            Assert.Equal(\"value1\", result[\"key1\"]);\n            Assert.Equal(\"\", result[\"key2\"]);\n            Assert.Null(result[\"\"]);\n        }\n\n        [Fact]\n        public void ParseQueryString_MultipleValuesForSingleName()\n        {\n            // Arrange\n            Uri uri = new Uri(\"http://localhost/?key1=value1&key1=value2\");\n\n            // Act\n            NameValueCollection result = ParseQueryString(uri);\n\n            // Assert\n            Assert.Equal(\"value1,value2\", result[\"key1\"]);\n            Assert.Equal(new[] { \"value1\", \"value2\" }, result.GetValues(\"key1\"));\n        }\n\n        [Fact]\n        public void ParseQueryString_LeadingAmpersand()\n        {\n            // Arrange\n            Uri uri = new Uri(\"http://localhost/?&key1=value1\");\n\n            // Act\n            NameValueCollection result = ParseQueryString(uri);\n\n            // Assert\n            Assert.Equal(2, result.Count);\n            Assert.Equal(\"value1\", result[\"key1\"]);\n            Assert.Equal(\"\", result[\"\"]);\n        }\n\n        [Fact]\n        public void ParseQueryString_IntermediateDoubleAmpersand()\n        {\n            // Arrange\n            Uri uri = new Uri(\"http://localhost/?key1=value1&&key2=value2\");\n\n            // Act\n            NameValueCollection result = ParseQueryString(uri);\n\n            // Assert\n            Assert.Equal(3, result.Count);\n            Assert.Equal(\"value1\", result[\"key1\"]);\n            Assert.Equal(\"value2\", result[\"key2\"]);\n            Assert.Equal(\"\", result[\"\"]);\n        }\n\n        [Fact]\n        public void ParseQueryString_TrailingAmpersand()\n        {\n            // Arrange\n            Uri uri = new Uri(\"http://localhost/?key1=value1&\");\n\n            // Act\n            NameValueCollection result = ParseQueryString(uri);\n\n            // Assert\n            Assert.Equal(2, result.Count);\n            Assert.Equal(\"value1\", result[\"key1\"]);\n            Assert.Equal(\"\", result[\"\"]);\n        }\n\n        [Fact]\n        public void ParseQueryString_EncodedUrlValues()\n        {\n            // Arrange\n            Uri uri = new Uri(\"http://localhost/?key%31=value%31\");\n\n            // Act\n            NameValueCollection result = ParseQueryString(uri);\n\n            // Assert\n            Assert.Single(result);\n            Assert.Equal(\"value1\", result[\"key1\"]);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ValueProviders/Providers/RouteDataValueProviderFactoryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Net.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.ValueProviders.Providers\n{\n    public class RouteDataValueProviderFactoryTest\n    {\n        private readonly RouteDataValueProviderFactory _factory = new RouteDataValueProviderFactory();\n\n        [Fact]\n        public void GetValueProvider_WhenActionContextParameterIsNull_Throws()\n        {\n            Assert.ThrowsArgumentNull(() => _factory.GetValueProvider(actionContext: null), \"actionContext\");\n        }\n\n        [Fact]\n        public void GetValueProvider_ReturnsQueryStringValueProviderInstaceWithInvariantCulture()\n        {\n            var routeData = new Mock<IHttpRouteData>();\n            routeData.Setup(r => r.Values).Returns(() => new Dictionary<string, object>());\n            var controllerContext = new HttpControllerContext() { Request = new HttpRequestMessage(), RouteData = routeData.Object };\n            var context = new HttpActionContext() { ControllerContext = controllerContext };\n\n            IValueProvider result = _factory.GetValueProvider(context);\n\n            var valueProvider = Assert.IsType<RouteDataValueProvider>(result);\n            Assert.Equal(CultureInfo.InvariantCulture, valueProvider.Culture);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ValueProviders/Providers/RouteDataValueProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Http.Routing;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ValueProviders.Providers\n{\n    public class RouteDataValueProviderTest\n    {\n        [Fact]\n        public void GetRouteValues_Returns_RouteValues()\n        {\n            // Arrange\n            HttpRouteData routeData = new HttpRouteData(new HttpRoute());\n            routeData.Values.Add(\"key1\", \"value1\");\n            routeData.Values.Add(\"key2\", \"value2\");\n\n            // Act\n            IEnumerable<KeyValuePair<string, string>> result = RouteDataValueProvider.GetRouteValues(routeData);\n\n            // Assert\n            Assert.Equal(result, new Dictionary<string, string> { { \"key1\", \"value1\" }, { \"key2\", \"value2\" } });\n        }\n\n        [Fact]\n        public void GetRouteValues_IfRouteDataHasNullValue_ReturnsKeyValuePairWithNullValue()\n        {\n            // Arrange\n            HttpRouteData routeData = new HttpRouteData(new HttpRoute());\n            routeData.Values.Add(\"key\", null);\n\n            // Act\n            IEnumerable<KeyValuePair<string, string>> result = RouteDataValueProvider.GetRouteValues(routeData);\n\n            // Assert\n            Assert.Equal(result, new[] { new KeyValuePair<string, string>(\"key\", null) });\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Test/ValueProviders/ValueProviderResultTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.ValueProviders\n{\n    public class ValueProviderResultTest\n    {\n        [Fact]\n        public void ConvertTo_ReturnsNullForReferenceTypes_WhenValueIsNull()\n        {\n            var valueProviderResult = new ValueProviderResult(null, null, CultureInfo.InvariantCulture);\n\n            var convertedValue = valueProviderResult.ConvertTo(typeof(string));\n\n            Assert.Null(convertedValue);\n        }\n\n        [Fact]\n        public void ConvertTo_ReturnsDefaultForValueTypes_WhenValueIsNull()\n        {\n            var valueProviderResult = new ValueProviderResult(null, null, CultureInfo.InvariantCulture);\n\n            var convertedValue = valueProviderResult.ConvertTo(typeof(int));\n\n            Assert.Equal(0, convertedValue);\n        }\n\n        [Fact]\n        public void ConvertTo_PopulatesArray_WhenSingleNeedsToBeConvertedToArray()\n        {\n            // Arrange\n            var valueProviderResult = new ValueProviderResult(DayOfWeek.Friday, \"It's Friday!\", CultureInfo.InvariantCulture);\n\n            // Act\n            var convertedValue = (DayOfWeek[])valueProviderResult.ConvertTo(typeof(DayOfWeek[]));\n\n            // Assert\n            Assert.Single(convertedValue, DayOfWeek.Friday);\n        }\n\n        [Fact]\n        public void ConvertTo_PopulatesArray_WhenSourceArrayNeedsToBeConvertedToArray()\n        {\n            // Arrange\n            string[] values = new[] { \"3\", \"2\", \"1\" };\n            var valueProviderResult = new ValueProviderResult(values, values.ToString(), CultureInfo.InvariantCulture);\n\n            // Act\n            var convertedValue = valueProviderResult.ConvertTo(typeof(int[]));\n\n            // Assert\n            Assert.Equal(new[] { 3, 2, 1 }, convertedValue);\n        }\n\n        [Fact]\n        public void ConvertTo_PopulatesArray_WhenListNeedsToBeConvertedToArray()\n        {\n            // Arrange\n            List<string> values = new List<string> { \"-1\", \"0\", \"1\" };\n            var valueProviderResult = new ValueProviderResult(values, values.ToString(), CultureInfo.InvariantCulture);\n\n            // Act\n            var convertedValue = valueProviderResult.ConvertTo(typeof(int[]));\n\n            // Assert\n            Assert.IsType<int[]>(convertedValue);\n            Assert.Equal(new[] { -1, 0, 1 }, convertedValue);\n        }\n\n        public static TheoryDataSet<IList, object> SingleValueBoundToArrayData\n        {\n            get\n            {\n                return new TheoryDataSet<IList, object>\n                {\n                    { new List<string> { \"Foo\", \"Bar\" }, \"Foo\" },\n                    { new string[] { \"baz\", \"qux\" }, \"baz\" },\n                    { new List<int> { -17, 34 }, -17 },\n                    { new string[] { \"30\", \"15\" }, 30 }\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"SingleValueBoundToArrayData\")]\n        public void ConvertTo_ReturnsFirstValue_WhenSequenceNeedsToConvertedToSingleValue(IList value, object expected)\n        {\n            // Arrange\n            var valueProviderResult = new ValueProviderResult(value, value.ToString(), CultureInfo.InvariantCulture);\n\n            // Act\n            var convertedValue = valueProviderResult.ConvertTo(expected.GetType());\n\n            // Assert\n            Assert.Equal(expected, convertedValue);\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.Test/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Castle.Core\" version=\"5.1.1\" targetFramework=\"net462\" />\n  <package id=\"Moq\" version=\"4.18.4\" targetFramework=\"net462\" />\n  <package id=\"Newtonsoft.Json\" version=\"13.0.1\" targetFramework=\"net462\" />\n  <package id=\"xunit\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.abstractions\" version=\"2.0.3\" targetFramework=\"net462\" />\n  <package id=\"xunit.analyzers\" version=\"1.1.0\" targetFramework=\"net462\" />\n  <package id=\"xunit.assert\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.execution\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.runner.visualstudio\" version=\"2.4.5\" targetFramework=\"net462\" developmentDependency=\"true\" />\n</packages>"
  },
  {
    "path": "test/System.Web.Http.Tracing.Test/HttpConfigurationTracingExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.Tracing;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Test\n{\n    public class HttpConfigurationTracingExtensionsTest\n    {\n        [Fact]\n        public void EnableSystemDiagnosticsTracing_Adds_TraceWriter()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            SystemDiagnosticsTraceWriter returnedTraceWriter = config.EnableSystemDiagnosticsTracing();\n            ITraceWriter setTraceWriter = config.Services.GetService(typeof(ITraceWriter)) as ITraceWriter;\n\n            Assert.ReferenceEquals(returnedTraceWriter, setTraceWriter);\n        }\n\n        [Fact]\n        public void EnableSystemDiagnosticsTracing_ThrowsIfNull()\n        {\n            Assert.ThrowsArgumentNull(() => HttpConfigurationTracingExtensions.EnableSystemDiagnosticsTracing(null), \"configuration\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Tracing.Test/System.Web.Http.Tracing.Test.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props\" Condition=\"Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" />\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" />\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{F87FD911-4A97-4057-8EAE-1CB96B9A1937}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>System.Web.Http.Tracing.Test</RootNamespace>\n    <AssemblyName>System.Web.Http.Tracing.Test</AssemblyName>\n    <OutputPath>..\\..\\bin\\$(Configuration)\\Test\\</OutputPath>\n    <NuGetPackageImportStamp>\n    </NuGetPackageImportStamp>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Newtonsoft.Json.13.0.1\\lib\\net45\\Newtonsoft.Json.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Net.Http\" />\n    <Reference Include=\"System.Net.Http.WebRequest\" />\n    <Reference Include=\"System.Xml\" />\n    <Reference Include=\"xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.abstractions.2.0.3\\lib\\net35\\xunit.abstractions.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.assert, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.assert.2.4.2\\lib\\netstandard1.1\\xunit.assert.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.core, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.core.2.4.2\\lib\\net452\\xunit.core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.execution.desktop, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.execution.2.4.2\\lib\\net452\\xunit.execution.desktop.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"HttpConfigurationTracingExtensionsTest.cs\" />\n    <Compile Include=\"SystemDiagnosticsTraceWriterTest.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\..\\src\\System.Net.Http.Formatting\\System.Net.Http.Formatting.csproj\">\n      <Project>{668e9021-ce84-49d9-98fb-df125a9fcdb0}</Project>\n      <Name>System.Net.Http.Formatting</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Http.Tracing\\System.Web.Http.Tracing.csproj\">\n      <Project>{6E81EF98-8F5C-4EED-8B37-456991CA56FD}</Project>\n      <Name>System.Web.Http.Tracing</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Http\\System.Web.Http.csproj\">\n      <Project>{ddc1ce0c-486e-4e35-bb3b-eab61f8f9440}</Project>\n      <Name>System.Web.Http</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\">\n      <Project>{fccc4cb7-baf7-4a57-9f89-e5766fe536c0}</Project>\n      <Name>Microsoft.TestCommon</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <Service Include=\"{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Analyzer Include=\"..\\..\\packages\\xunit.analyzers.1.1.0\\analyzers\\dotnet\\cs\\xunit.analyzers.dll\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  <Target Name=\"EnsureNuGetPackageBuildImports\" BeforeTargets=\"PrepareForBuild\">\n    <PropertyGroup>\n      <ErrorText>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}.</ErrorText>\n    </PropertyGroup>\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props'))\" />\n  </Target>\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" />\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.\n       Other similar extension points exist, see Microsoft.Common.targets.\n  <Target Name=\"BeforeBuild\">\n  </Target>\n  <Target Name=\"AfterBuild\">\n  </Target>\n  -->\n</Project>"
  },
  {
    "path": "test/System.Web.Http.Tracing.Test/SystemDiagnosticsTraceWriterTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Web.Http.ModelBinding;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.Tracing.Diagnostics.Test\n{\n    public class SystemDiagnosticsTraceWriterTest\n    {\n        // Duplicates of constants in HttpError\n        private const string MessageKey = \"Message\";\n        private const string MessageDetailKey = \"MessageDetail\";\n        private const string ModelStateKey = \"ModelState\";\n        private const string ExceptionMessageKey = \"ExceptionMessage\";\n        private const string ExceptionTypeKey = \"ExceptionType\";\n        private const string StackTraceKey = \"StackTrace\";\n        private const string InnerExceptionKey = \"InnerException\";\n\n        [Fact]\n        public void Ctor_Initializes_Properties()\n        {\n            // Arrange\n            SystemDiagnosticsTraceWriter writer = new SystemDiagnosticsTraceWriter();\n\n            // Act & Assert\n            Assert.False(writer.IsVerbose);\n            Assert.Equal(TraceLevel.Info, writer.MinimumLevel);\n            Assert.Null(writer.TraceSource);\n        }\n\n        [Fact]\n        public void TraceSource_Accepts_Custom_TraceSource()\n        {\n            // Arrange\n            SystemDiagnosticsTraceWriter writer = new SystemDiagnosticsTraceWriter();\n            TraceSource traceSource = new TraceSource(\"CustomTraceSource\");\n\n            // Act\n            writer.TraceSource = traceSource;\n\n            // Assert\n            Assert.Equal(traceSource, writer.TraceSource);\n        }\n\n        [Fact]\n        public void TraceSource_Accepts_Null_TraceSource()\n        {\n            // Arrange\n            SystemDiagnosticsTraceWriter writer = new SystemDiagnosticsTraceWriter();\n\n            // Act\n            writer.TraceSource = null;\n\n            // Assert\n            Assert.Null(writer.TraceSource);\n        }\n\n        [Theory]\n        [InlineData(TraceLevel.Debug)]\n        [InlineData(TraceLevel.Info)]\n        [InlineData(TraceLevel.Warn)]\n        [InlineData(TraceLevel.Error)]\n        [InlineData(TraceLevel.Fatal)]\n        public void MinimumLevel_Setter_Accepts_All_Legal_Levels(TraceLevel level)\n        {\n            // Arrange\n            SystemDiagnosticsTraceWriter writer = new SystemDiagnosticsTraceWriter();\n\n            // Act\n            writer.MinimumLevel = level;\n\n            // Assert\n            Assert.Equal(level, writer.MinimumLevel);\n        }\n\n        [Theory]\n        [InlineData(TraceLevel.Off - 1)]\n        [InlineData(TraceLevel.Fatal + 1)]\n        public void MinimumLevel_Setter_Throws_With_Bad_Level(TraceLevel level)\n        {\n            // Arrange & Act & Assert\n            ArgumentOutOfRangeException exception = Assert.Throws<ArgumentOutOfRangeException>(() => { new SystemDiagnosticsTraceWriter().MinimumLevel = level; });\n            Assert.Equal(\"value\", exception.ParamName);\n            Assert.Contains(\"The TraceLevel property must be a value between TraceLevel.Off and TraceLevel.Fatal, inclusive.\", exception.Message);\n            Assert.Equal(level, exception.ActualValue);\n        }\n\n        [Fact]\n        public void Trace_Throws_With_Null_Category()\n        {\n            // Arrange\n            SystemDiagnosticsTraceWriter writer = new SystemDiagnosticsTraceWriter();\n\n            // Act & Assert\n            ArgumentNullException exception = Assert.Throws<ArgumentNullException>(\n                                                () => writer.Trace(new HttpRequestMessage(),\n                                                                    null,\n                                                                    TraceLevel.Info,\n                                                                    (tr) => { }));\n            Assert.Equal(\"category\", exception.ParamName);\n        }\n\n        [Fact]\n        public void Trace_Throws_With_Null_TraceAction()\n        {\n            // Arrange\n            SystemDiagnosticsTraceWriter writer = new SystemDiagnosticsTraceWriter();\n\n            // Act & Assert\n            ArgumentNullException exception = Assert.Throws<ArgumentNullException>(\n                                                () => writer.Trace(new HttpRequestMessage(),\n                                                                    \"MyCategory\",\n                                                                    TraceLevel.Info,\n                                                                    traceAction: null));\n            Assert.Equal(\"traceAction\", exception.ParamName);\n        }\n\n        [Theory]\n        [InlineData(TraceLevel.Off - 1)]\n        [InlineData(TraceLevel.Fatal + 1)]\n        public void Trace_Throws_With_Illegal_Level(TraceLevel level)\n        {\n            // Arrange\n            SystemDiagnosticsTraceWriter writer = new SystemDiagnosticsTraceWriter();\n\n            // Act & Assert\n            ArgumentOutOfRangeException exception = Assert.Throws<ArgumentOutOfRangeException>(\n                                                () => writer.Trace(new HttpRequestMessage(),\n                                                                    \"MyCategory\",\n                                                                    level,\n                                                                    (tr) => { }));\n            Assert.Equal(\"level\", exception.ParamName);\n            Assert.Contains(\"The TraceLevel property must be a value between TraceLevel.Off and TraceLevel.Fatal, inclusive.\", exception.Message);\n            Assert.Equal(level, exception.ActualValue);\n        }\n\n        [Fact]\n        public void Trace_Writes_To_Custom_TraceSource()\n        {\n            // Arrange\n            SystemDiagnosticsTraceWriter writer = CreateTraceWriter();\n\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(\"http://localhost\"),\n                Method = HttpMethod.Get\n            };\n\n            // Act\n            writer.Info(request, \"TestCategory\", \"TestMessage\");\n\n            // Assert\n            Assert.Equal(\"Message='TestMessage'\", ((TestTraceListener)writer.TraceSource.Listeners[0]).Messages[0]);\n        }\n\n        [Theory]\n        [InlineData(TraceLevel.Debug, TraceEventType.Verbose)]\n        [InlineData(TraceLevel.Info, TraceEventType.Information)]\n        [InlineData(TraceLevel.Warn, TraceEventType.Warning)]\n        [InlineData(TraceLevel.Error, TraceEventType.Error)]\n        [InlineData(TraceLevel.Fatal, TraceEventType.Critical)]\n        public void Trace_Writes_Correct_EventType_To_TraceListeners(TraceLevel level, TraceEventType diagnosticLevel)\n        {\n            // Arrange\n            SystemDiagnosticsTraceWriter writer = CreateTraceWriter();\n            writer.MinimumLevel = level;\n\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(\"http://localhost\"),\n                Method = HttpMethod.Get\n            };\n\n            // Act\n            writer.Trace(request, \"TestCategory\", level, (tr) => { tr.Message = \"TestMessage\"; });\n\n            // Assert\n            Assert.Equal(diagnosticLevel, ((TestTraceListener)writer.TraceSource.Listeners[0]).TraceEventType);\n        }\n\n        [Theory]\n        [InlineData(TraceLevel.Debug)]\n        [InlineData(TraceLevel.Info)]\n        [InlineData(TraceLevel.Warn)]\n        [InlineData(TraceLevel.Error)]\n        [InlineData(TraceLevel.Fatal)]\n        public void Trace_Verbose_Writes_Correct_Message_To_TraceListeners_With_All_Fields_Set(TraceLevel level)\n        {\n            // Arrange\n            SystemDiagnosticsTraceWriter writer = CreateTraceWriter();\n            writer.MinimumLevel = level;\n            writer.IsVerbose = true;\n\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(\"http://localhost\"),\n                Method = HttpMethod.Get\n            };\n\n            InvalidOperationException exception = new InvalidOperationException(\"TestException\");\n\n            // Act\n            writer.Trace(request, \"TestCategory\", level, (tr) =>\n            {\n                tr.Message = \"TestMessage\";\n                tr.Operation = \"TestOperation\";\n                tr.Operator = \"TestOperator\";\n                tr.Status = HttpStatusCode.Accepted;\n                tr.Exception = exception;\n            });\n\n            // Assert\n            string expected = String.Format(\"Level={0}, Kind=Trace, Category='TestCategory', Id={1}, Message='TestMessage', Operation=TestOperator.TestOperation, Status=202 (Accepted), Exception={2}\",\n                                                level.ToString(),\n                                                request.GetCorrelationId().ToString(),\n                                                exception.ToString());\n\n            string actual = ((TestTraceListener)writer.TraceSource.Listeners[0]).Messages[0].Trim();\n            string timePrefix = \"] \";\n            actual = actual.Substring(actual.IndexOf(timePrefix) + timePrefix.Length);\n            Assert.Equal(expected, actual);\n        }\n\n        [Theory]\n        [InlineData(TraceLevel.Debug)]\n        [InlineData(TraceLevel.Info)]\n        [InlineData(TraceLevel.Warn)]\n        [InlineData(TraceLevel.Error)]\n        [InlineData(TraceLevel.Fatal)]\n        public void Trace_Brief_Writes_Correct_Message_To_TraceListeners_With_All_Fields_Set(TraceLevel level)\n        {\n            // Arrange\n            SystemDiagnosticsTraceWriter writer = CreateTraceWriter();\n            writer.MinimumLevel = level;\n\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(\"http://localhost\"),\n                Method = HttpMethod.Get\n            };\n\n            InvalidOperationException exception = new InvalidOperationException(\"TestException\");\n\n            // Act\n            writer.Trace(request, \"TestCategory\", level, (tr) =>\n            {\n                tr.Message = \"TestMessage\";\n                tr.Operation = \"TestOperation\";\n                tr.Operator = \"TestOperator\";\n                tr.Status = HttpStatusCode.Accepted;\n                tr.Exception = exception;\n            });\n\n            // Assert\n            string expected = \"Message='TestMessage', Operation=TestOperator.TestOperation, Status=202 (Accepted), Exception=System.InvalidOperationException: TestException\";\n            string actual = ((TestTraceListener)writer.TraceSource.Listeners[0]).Messages[0].Trim();\n            Assert.Equal(expected, actual);\n        }\n\n        [Fact]\n        public void Trace_Verbose_Writes_Correct_Message_To_TraceListeners_With_Only_Required_Fields_Set()\n        {\n            // Arrange\n            SystemDiagnosticsTraceWriter writer = CreateTraceWriter();\n            writer.IsVerbose = true;\n\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(\"http://localhost\"),\n                Method = HttpMethod.Get\n            };\n\n            InvalidOperationException exception = new InvalidOperationException(\"TestException\");\n\n            // Act\n            writer.Info(request, \"TestCategory\", String.Empty);\n\n            // Assert\n            string expected = String.Format(\"Level=Info, Kind=Trace, Category='TestCategory', Id={0}\",\n                                            request.GetCorrelationId().ToString());\n\n            string actual = ((TestTraceListener)writer.TraceSource.Listeners[0]).Messages[0].Trim();\n            string timePrefix = \"] \";\n            actual = actual.Substring(actual.IndexOf(timePrefix) + timePrefix.Length);\n            Assert.Equal(expected, actual);\n        }\n\n        [Fact]\n        public void Trace_Brief_Writes_Correct_Message_To_TraceListeners_With_Only_Required_Fields_Set()\n        {\n            // Arrange\n            SystemDiagnosticsTraceWriter writer = CreateTraceWriter();\n\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(\"http://localhost\"),\n                Method = HttpMethod.Get\n            };\n\n            InvalidOperationException exception = new InvalidOperationException(\"TestException\");\n\n            // Act\n            writer.Info(request, \"TestCategory\", \"TestMessage\");\n\n            // Assert\n            string expected = \"Message='TestMessage'\";\n            string actual = ((TestTraceListener)writer.TraceSource.Listeners[0]).Messages[0].Trim();\n            Assert.Equal(expected, actual);\n        }\n\n        [Fact]\n        public void Trace_Brief_Trace_Does_Not_Trace_When_No_Data()\n        {\n            // Arrange\n            SystemDiagnosticsTraceWriter writer = CreateTraceWriter();\n\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(\"http://localhost\"),\n                Method = HttpMethod.Get\n            };\n\n            InvalidOperationException exception = new InvalidOperationException(\"TestException\");\n\n            // Act\n            writer.Trace(request, \"TestCategory\", TraceLevel.Info, (tr) => { });\n\n            // Assert\n            Assert.Equal(0, ((TestTraceListener)writer.TraceSource.Listeners[0]).Messages.Count);\n        }\n\n        [Fact]\n        public void Trace_Brief_Trace_Does_Not_Trace_BeginKind()\n        {\n            // Arrange\n            SystemDiagnosticsTraceWriter writer = CreateTraceWriter();\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(\"http://localhost\"),\n                Method = HttpMethod.Get\n            };\n\n            InvalidOperationException exception = new InvalidOperationException(\"TestException\");\n\n            // Act\n            writer.Trace(request, \"TestCategory\", TraceLevel.Info, (tr) => { tr.Kind = TraceKind.Begin; tr.Message = \"TestMessage\"; });\n\n            // Assert\n            Assert.Equal(0, ((TestTraceListener)writer.TraceSource.Listeners[0]).Messages.Count);\n        }\n\n        [Theory]\n        [InlineData(TraceLevel.Debug)]\n        [InlineData(TraceLevel.Info)]\n        [InlineData(TraceLevel.Warn)]\n        [InlineData(TraceLevel.Error)]\n        [InlineData(TraceLevel.Fatal)]\n        public void Trace_Does_Not_Trace_Below_Minimum_Level(TraceLevel level)\n        {\n            // Arrange\n            SystemDiagnosticsTraceWriter writer = CreateTraceWriter();\n            writer.MinimumLevel = level;\n\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(\"http://localhost\"),\n                Method = HttpMethod.Get\n            };\n\n            InvalidOperationException exception = new InvalidOperationException(\"TestException\");\n\n            // Act\n            writer.Trace(request, \"TestCategory\", level - 1, (tr) => { });\n\n            // Assert\n            Assert.Equal(0, ((TestTraceListener)writer.TraceSource.Listeners[0]).Messages.Count);\n        }\n\n        [Fact]\n        public void Trace_Traces_Warning_EventType_When_Translates_HttpResponseException_Error()\n        {\n            // Arrange\n            SystemDiagnosticsTraceWriter writer = CreateTraceWriter();\n            writer.IsVerbose = true;\n\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(\"http://localhost\"),\n                Method = HttpMethod.Get\n            };\n\n            HttpResponseMessage response = request.CreateErrorResponse(HttpStatusCode.BadRequest, \"bad request\");\n            HttpResponseException responseException = new HttpResponseException(response);\n\n            // Act\n            writer.Error(request, \"TestCategory\", responseException);\n\n            // Assert\n            Assert.Equal(TraceEventType.Warning, ((TestTraceListener)writer.TraceSource.Listeners[0]).TraceEventType);\n        }\n\n        [Fact]\n        void Format_Throws_With_Null_TraceRecord()\n        {\n            // Arrange & Act & Assert\n            ArgumentNullException exception =\n                Assert.Throws<ArgumentNullException>(\n                () => { new SystemDiagnosticsTraceWriter().Format(null); });\n\n            Assert.Equal(\"traceRecord\", exception.ParamName);\n        }\n\n        [Theory]\n        [InlineData(TraceLevel.Debug)]\n        [InlineData(TraceLevel.Info)]\n        [InlineData(TraceLevel.Warn)]\n        [InlineData(TraceLevel.Error)]\n        [InlineData(TraceLevel.Fatal)]\n        public void Format_Verbose_Builds_Trace_With_All_TraceRecord_Properties(TraceLevel level)\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(\"http://localhost\"),\n                Method = HttpMethod.Get\n            };\n\n            InvalidOperationException exception;\n            try\n            {\n                // Want the full stack trace in the payload\n                throw new InvalidOperationException(\"TestException\");\n            }\n            catch (InvalidOperationException ex)\n            {\n                exception = ex;\n            }\n\n            TraceRecord traceRecord = new TraceRecord(request, \"TestCategory\", level)\n            {\n                Message = \"TestMessage\",\n                Operation = \"TestOperation\",\n                Operator = \"TestOperator\",\n                Status = HttpStatusCode.Accepted,\n                Exception = exception\n            };\n\n            // Act\n            string formattedTrace = new SystemDiagnosticsTraceWriter() { IsVerbose = true }.Format(traceRecord);\n\n            // Assert\n            AssertContainsExactly(formattedTrace,\n                                new Dictionary<string, string>\n                                    {\n                                        { \"Level\", level.ToString() },\n                                        { \"Kind\", TraceKind.Trace.ToString() },\n                                        { \"Category\", \"'TestCategory'\"},\n                                        { \"Id\", request.GetCorrelationId().ToString() },\n                                        { \"Message\", \"'TestMessage'\" },\n                                        { \"Operation\", \"TestOperator.TestOperation\" },\n                                        { \"Status\", \"202 (Accepted)\" },\n                                        { \"Exception\", exception.ToString() },\n                                    });\n\n        }\n\n        [Fact]\n        public void Format_Builds_Trace_With_Null_Fields()\n        {\n            // Arrange\n            TraceRecord traceRecord = new TraceRecord(request: null, category: null, level: TraceLevel.Info)\n            {\n                Message = null,\n                Operation = null,\n                Operator = null,\n            };\n\n            // Act\n            string formattedTrace = new SystemDiagnosticsTraceWriter() { IsVerbose = true }.Format(traceRecord);\n\n            // Assert\n            AssertContainsExactly(formattedTrace,\n                                new Dictionary<string, string>\n                                    {\n                                        { \"Level\", TraceLevel.Info.ToString() },\n                                        { \"Kind\", TraceKind.Trace.ToString() },\n                                        { \"Id\", new Guid().ToString() }\n                                    });\n\n        }\n\n        [Fact]\n        public void Format_Delegates_To_FormatRequestEnvelope_Begin()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(\"http://localhost\"),\n                Method = HttpMethod.Get\n            };\n\n            TraceRecord traceRecord = new TraceRecord(request, \"System.Web.Http.Request\", TraceLevel.Info)\n            {\n                Kind = TraceKind.Begin,\n            };\n\n            // Act\n            string actualTrace = new SystemDiagnosticsTraceWriter() { IsVerbose = true }.Format(traceRecord);\n\n            // Assert\n            string timePrefix = \"] \";\n            actualTrace = actualTrace.Substring(actualTrace.IndexOf(timePrefix) + timePrefix.Length);\n            string expectedTrace = String.Format(\"Request received, Method=GET, Url=http://localhost/, Id={0}\", traceRecord.RequestId.ToString());\n            Assert.Equal(expectedTrace, actualTrace);\n        }\n\n        [Fact]\n        public void Format_Verbose_Delegates_To_FormatRequestEnvelope_End()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(\"http://localhost\"),\n                Method = HttpMethod.Get\n            };\n\n            TraceRecord traceRecord = new TraceRecord(request, \"System.Web.Http.Request\", TraceLevel.Info)\n            {\n                Kind = TraceKind.End,\n            };\n\n            // Act\n            string actualTrace = new SystemDiagnosticsTraceWriter() { IsVerbose = true }.Format(traceRecord);\n\n            // Assert\n            string timePrefix = \"] \";\n            actualTrace = actualTrace.Substring(actualTrace.IndexOf(timePrefix) + timePrefix.Length);\n            string expectedTrace = String.Format(\"Sending response, Method=GET, Url=http://localhost/, Id={0}\", traceRecord.RequestId.ToString());\n            Assert.Equal(expectedTrace, actualTrace);\n        }\n\n        [Fact]\n        void FormatRequestEnvelope_Throws_With_Null_TraceRecord()\n        {\n            // Arrange & Act & Assert\n            ArgumentNullException exception =\n                Assert.Throws<ArgumentNullException>(\n                () => { new SystemDiagnosticsTraceWriter().FormatRequestEnvelope(null); });\n\n            Assert.Equal(\"traceRecord\", exception.ParamName);\n        }\n\n        [Fact]\n        public void FormatRequestEnvelope_Verbose_Builds_Correct_Begin_Trace_With_Only_Required_Fields()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(\"http://localhost\"),\n                Method = HttpMethod.Get\n            };\n\n            TraceRecord traceRecord = new TraceRecord(request, \"System.Web.Http.Request\", TraceLevel.Info)\n            {\n                Kind = TraceKind.Begin,\n            };\n\n            // Act\n            string actualTrace = new SystemDiagnosticsTraceWriter() { IsVerbose = true }.FormatRequestEnvelope(traceRecord);\n\n            // Assert\n            string timePrefix = \"] \";\n            actualTrace = actualTrace.Substring(actualTrace.IndexOf(timePrefix) + timePrefix.Length);\n            string expectedTrace = String.Format(\"Request received, Method=GET, Url=http://localhost/, Id={0}\", traceRecord.RequestId.ToString());\n            Assert.Equal(expectedTrace, actualTrace);\n        }\n\n        [Fact]\n        public void FormatRequestEnvelope_Verbose_Builds_Correct_Begin_Trace_With_All_Fields()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(\"http://localhost\"),\n                Method = HttpMethod.Get\n            };\n\n            Exception exception = null;\n            try\n            {\n                throw new InvalidOperationException(\"ExceptionMessage\");\n            }\n            catch (Exception ex)\n            {\n                exception = ex;\n            }\n\n            TraceRecord traceRecord = new TraceRecord(request, \"System.Web.Http.Request\", TraceLevel.Info)\n            {\n                Kind = TraceKind.Begin,\n                Message = \"EnvelopeMessage\",\n                Exception = exception\n            };\n\n            // Act\n            string actualTrace = new SystemDiagnosticsTraceWriter() { IsVerbose = true }.FormatRequestEnvelope(traceRecord);\n\n            // Assert\n            string timePrefix = \"] \";\n            actualTrace = actualTrace.Substring(actualTrace.IndexOf(timePrefix) + timePrefix.Length);\n            string expectedTrace = String.Format(\"Request received, Method=GET, Url=http://localhost/, Id={0}, Message='EnvelopeMessage', Exception={1}\",\n                                                traceRecord.RequestId.ToString(),\n                                                exception.ToString().Trim());\n            Assert.Equal(expectedTrace, actualTrace);\n        }\n\n        [Fact]\n        public void FormatRequestEnvelope_Verbose_Builds_Correct_Begin_Trace_With_Null_Fields()\n        {\n            // Arrange\n            TraceRecord traceRecord = new TraceRecord(request: null, category: null, level: TraceLevel.Info)\n            {\n                Kind = TraceKind.Begin,\n            };\n\n            // Act\n            string actualTrace = new SystemDiagnosticsTraceWriter() { IsVerbose = true }.FormatRequestEnvelope(traceRecord);\n\n            // Assert\n            string timePrefix = \"] \";\n            actualTrace = actualTrace.Substring(actualTrace.IndexOf(timePrefix) + timePrefix.Length);\n            string expectedTrace = String.Format(\"Request received, Id={0}\", traceRecord.RequestId.ToString());\n            Assert.Equal(expectedTrace, actualTrace);\n        }\n\n        [Fact]\n        public void FormatRequestEnvelope_Verbose_Builds_Correct_End_Trace_With_Only_Required_Fields()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(\"http://localhost\"),\n                Method = HttpMethod.Get\n            };\n\n            TraceRecord traceRecord = new TraceRecord(request, \"System.Web.Http.Request\", TraceLevel.Info)\n            {\n                Kind = TraceKind.End,\n                Status = HttpStatusCode.Accepted\n            };\n\n            // Act\n            string actualTrace = new SystemDiagnosticsTraceWriter() { IsVerbose = true }.FormatRequestEnvelope(traceRecord);\n\n            // Assert\n            string timePrefix = \"] \";\n            actualTrace = actualTrace.Substring(actualTrace.IndexOf(timePrefix) + timePrefix.Length);\n            string expectedTrace = String.Format(\"Sending response, Status=202 (Accepted), Method=GET, Url=http://localhost/, Id={0}\", traceRecord.RequestId.ToString());\n            Assert.Equal(expectedTrace, actualTrace);\n        }\n\n        [Fact]\n        public void FormatRequestEnvelope_Verbose_Builds_Correct_End_Trace_With_All_Fields()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(\"http://localhost\"),\n                Method = HttpMethod.Get\n            };\n\n            Exception exception = null;\n            try\n            {\n                throw new InvalidOperationException(\"ExceptionMessage\");\n            }\n            catch (Exception ex)\n            {\n                exception = ex;\n            }\n\n            TraceRecord traceRecord = new TraceRecord(request, \"System.Web.Http.Request\", TraceLevel.Info)\n            {\n                Kind = TraceKind.End,\n                Status = HttpStatusCode.Accepted,\n                Message = \"EnvelopeMessage\",\n                Exception = exception\n            };\n\n            // Act\n            string actualTrace = new SystemDiagnosticsTraceWriter() { IsVerbose = true }.FormatRequestEnvelope(traceRecord);\n\n            // Assert\n            string timePrefix = \"] \";\n            actualTrace = actualTrace.Substring(actualTrace.IndexOf(timePrefix) + timePrefix.Length);\n            string expectedTrace = String.Format(\"Sending response, Status=202 (Accepted), Method=GET, Url=http://localhost/, Id={0}, Message={1}, Exception={2}\",\n                                                    traceRecord.RequestId.ToString(),\n                                                    \"'EnvelopeMessage'\",\n                                                    exception.ToString().Trim());\n            Assert.Equal(expectedTrace, actualTrace);\n        }\n\n        [Fact]\n        public void FormatRequestEnvelope_Verbose_Builds_Correct_End_Trace_With_Null_Fields()\n        {\n            // Arrange\n            TraceRecord traceRecord = new TraceRecord(request: null, category: null, level: TraceLevel.Info)\n            {\n                Kind = TraceKind.End,\n            };\n\n            // Act\n            string actualTrace = new SystemDiagnosticsTraceWriter() { IsVerbose = true }.FormatRequestEnvelope(traceRecord);\n\n            // Assert\n            string timePrefix = \"] \";\n            actualTrace = actualTrace.Substring(actualTrace.IndexOf(timePrefix) + timePrefix.Length);\n            string expectedTrace = String.Format(\"Sending response, Id={0}\", traceRecord.RequestId.ToString());\n            Assert.Equal(expectedTrace, actualTrace);\n        }\n\n        [Fact]\n        void TranslateHttpResponseException_Throws_With_Null_TraceRecord()\n        {\n            // Arrange & Act & Assert\n            ArgumentNullException exception =\n                Assert.Throws<ArgumentNullException>(\n                    () => { new SystemDiagnosticsTraceWriter().TranslateHttpResponseException(null); });\n\n            Assert.Equal(\"traceRecord\", exception.ParamName);\n        }\n\n        [Fact]\n        public void TranslateHttpResponseException_Copies_Status_From_Response()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(\"http://localhost\"),\n                Method = HttpMethod.Get\n            };\n\n            TraceRecord traceRecord = new TraceRecord(request, \"MyCategory\", TraceLevel.Error)\n            {\n                Exception = new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest))\n            };\n\n            // Act\n            new SystemDiagnosticsTraceWriter().TranslateHttpResponseException(traceRecord);\n\n            // Assert\n            Assert.Equal(HttpStatusCode.BadRequest, traceRecord.Status);\n        }\n\n        [Fact]\n        public void TranslateHttpResponseException_Maps_Client_Error_To_Warning()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(\"http://localhost\"),\n                Method = HttpMethod.Get\n            };\n\n            TraceRecord traceRecord = new TraceRecord(request, \"MyCategory\", TraceLevel.Error)\n            {\n                Exception = new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest))\n            };\n\n\n            // Act\n            new SystemDiagnosticsTraceWriter().TranslateHttpResponseException(traceRecord);\n\n            // Assert\n            Assert.Equal(TraceLevel.Warn, traceRecord.Level);\n        }\n\n        [Fact]\n        public void TranslateHttpResponseException_Maps_Non_Errors_To_Info()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(\"http://localhost\"),\n                Method = HttpMethod.Get\n            };\n\n            TraceRecord traceRecord = new TraceRecord(request, \"MyCategory\", TraceLevel.Error)\n            {\n                Exception = new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Moved))\n            };\n\n\n            // Act\n            new SystemDiagnosticsTraceWriter().TranslateHttpResponseException(traceRecord);\n\n            // Assert\n            Assert.Equal(TraceLevel.Info, traceRecord.Level);\n        }\n\n        [Fact]\n        public void TranslateHttpResponseException_Does_Not_Alter_Server_Errors()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(\"http://localhost\"),\n                Method = HttpMethod.Get\n            };\n\n            TraceRecord traceRecord = new TraceRecord(request, \"MyCategory\", TraceLevel.Error)\n            {\n                Exception = new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError))\n            };\n\n\n            // Act\n            new SystemDiagnosticsTraceWriter().TranslateHttpResponseException(traceRecord);\n\n            // Assert\n            Assert.Equal(TraceLevel.Error, traceRecord.Level);\n        }\n\n        [Fact]\n        public void TranslateHttpResponseException_Unpacks_Empty_HttpError()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(\"http://localhost\"),\n                Method = HttpMethod.Get\n            };\n\n            HttpError httpError = new HttpError();\n            HttpResponseMessage errorResponse = request.CreateResponse(HttpStatusCode.BadRequest);\n            errorResponse.Content = new ObjectContent<HttpError>(httpError, new JsonMediaTypeFormatter());\n\n            TraceRecord traceRecord = new TraceRecord(request, \"MyCategory\", TraceLevel.Error)\n            {\n                Exception = new HttpResponseException(errorResponse)\n            };\n\n\n            // Act\n            new SystemDiagnosticsTraceWriter().TranslateHttpResponseException(traceRecord);\n\n            // Assert\n            Assert.Equal(0, ParseTrace(traceRecord.Message).Count);\n        }\n\n        [Fact]\n        public void TranslateHttpResponseException_Unpacks_HttpError_With_All_Fields_Set()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(\"http://localhost\"),\n                Method = HttpMethod.Get\n            };\n\n            Exception exception = null;\n            try\n            {\n                throw new InvalidOperationException(\"ExpectedExceptionMessage\");\n            }\n            catch (Exception ex)\n            {\n                exception = ex;\n            }\n\n            HttpError httpError = new HttpError(exception, includeErrorDetail: true);\n            httpError.Message = \"ExpectedUserMessage\";\n            httpError[MessageDetailKey] = \"ExpectedDetailMessage\";\n\n            HttpResponseMessage errorResponse = request.CreateResponse(HttpStatusCode.BadRequest);\n            errorResponse.Content = new ObjectContent<HttpError>(httpError, new JsonMediaTypeFormatter());\n\n            TraceRecord traceRecord = new TraceRecord(request, \"MyCategory\", TraceLevel.Error)\n            {\n                Exception = new HttpResponseException(errorResponse)\n            };\n\n\n            // Act\n            new SystemDiagnosticsTraceWriter().TranslateHttpResponseException(traceRecord);\n\n            // Assert\n            Assert.Equal(TraceLevel.Warn, traceRecord.Level);\n\n            AssertContainsExactly(traceRecord.Message, new Dictionary<string, string>()\n            {\n                { \"UserMessage\", \"'ExpectedUserMessage'\" },\n                { \"MessageDetail\", \"'ExpectedDetailMessage'\" },\n                { \"ExceptionType\", \"'System.InvalidOperationException'\" },\n                { \"ExceptionMessage\", \"'ExpectedExceptionMessage'\" },\n                { \"StackTrace\", exception.StackTrace.Trim() }\n            });\n        }\n\n        [Fact]\n        public void TranslateHttpResponseException_Unpacks_HttpError_With_Inner_Exceptions()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(\"http://localhost\"),\n                Method = HttpMethod.Get\n            };\n\n            Exception exception1 = null;\n            Exception exception2 = null;\n            Exception exception3 = null;\n\n            try\n            {\n                throw new NotSupportedException(\"ExpectedExceptionMessage3\");\n            }\n            catch (Exception ex)\n            {\n                exception3 = ex;\n            }\n\n            try\n            {\n                throw new NotImplementedException(\"ExpectedExceptionMessage2\", exception3);\n            }\n            catch (Exception ex)\n            {\n                exception2 = ex;\n            }\n\n            try\n            {\n                throw new InvalidOperationException(\"ExpectedExceptionMessage1\", exception2);\n            }\n            catch (Exception ex)\n            {\n                exception1 = ex;\n            }\n\n            HttpError httpError = new HttpError(exception1, includeErrorDetail: true);\n            httpError.Message = \"ExpectedUserMessage\";\n            httpError[MessageDetailKey] = \"ExpectedDetailMessage\";\n\n            HttpResponseMessage errorResponse = request.CreateResponse(HttpStatusCode.BadRequest);\n            errorResponse.Content = new ObjectContent<HttpError>(httpError, new JsonMediaTypeFormatter());\n\n            TraceRecord traceRecord = new TraceRecord(request, \"System.Web.Http.Request\", TraceLevel.Error)\n            {\n                Exception = new HttpResponseException(errorResponse)\n            };\n\n\n            // Act\n            new SystemDiagnosticsTraceWriter().TranslateHttpResponseException(traceRecord);\n\n            // Assert\n            Assert.Equal(TraceLevel.Warn, traceRecord.Level);\n\n            AssertContainsExactly(traceRecord.Message, new Dictionary<string, string>()\n            {\n                { \"UserMessage\", \"'ExpectedUserMessage'\" },\n                { \"MessageDetail\", \"'ExpectedDetailMessage'\" },\n\n                { \"ExceptionType\", \"'System.InvalidOperationException'\" },\n                { \"ExceptionMessage\", \"'ExpectedExceptionMessage1'\" },\n                { \"StackTrace\", exception1.StackTrace.Trim() },\n\n                { \"ExceptionType[1]\", \"'System.NotImplementedException'\" },\n                { \"ExceptionMessage[1]\", \"'ExpectedExceptionMessage2'\" },\n                { \"StackTrace[1]\", exception2.StackTrace.Trim() },\n\n                { \"ExceptionType[2]\", \"'System.NotSupportedException'\" },\n                { \"ExceptionMessage[2]\", \"'ExpectedExceptionMessage3'\" },\n                { \"StackTrace[2]\", exception3.StackTrace.Trim() }\n\n            });\n        }\n\n        [Fact]\n        public void TranslateHttpResponseException_HiddenInAggregateException_UnpackTheMostSevere()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(\"http://localhost\"),\n                Method = HttpMethod.Get\n            };\n\n            var ex500 = new HttpResponseException(HttpStatusCode.InternalServerError);\n            var ex503 = new HttpResponseException(HttpStatusCode.ServiceUnavailable);\n            var ex401 = new HttpResponseException(HttpStatusCode.Unauthorized);\n            var ex503IsWithinMe = new Exception(\"I have 503 inside me\", ex503);\n\n            var aggregate = new AggregateException(ex500, ex503IsWithinMe, ex401);\n\n            HttpError httpError = new HttpError(aggregate, includeErrorDetail: true);\n            HttpResponseMessage errorResponse = request.CreateResponse(HttpStatusCode.ServiceUnavailable);\n            errorResponse.Content = new ObjectContent<HttpError>(httpError, new JsonMediaTypeFormatter());\n\n            TraceRecord traceRecord = new TraceRecord(request, \"System.Web.Http.Request\", TraceLevel.Error)\n            {\n                Exception = new HttpResponseException(errorResponse)\n            };\n\n            // Act\n            new SystemDiagnosticsTraceWriter().TranslateHttpResponseException(traceRecord);\n\n            // Assert\n            Assert.Equal(TraceLevel.Error, traceRecord.Level);\n            Assert.Equal(HttpStatusCode.ServiceUnavailable, traceRecord.Status);\n        }\n\n        [Fact]\n        public void TranslateHttpResponseException_Unpacks_ModelState_Errors()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(\"http://localhost\"),\n                Method = HttpMethod.Get\n            };\n\n            ModelStateDictionary modelStateDictionary = new ModelStateDictionary();\n            ModelState modelState1 = new ModelState();\n            modelState1.Errors.Add(\"modelState1.Error1\");\n            modelState1.Errors.Add(\"modelState1.Error2\");\n            modelStateDictionary[\"key1\"] = modelState1;\n\n            ModelState modelState2 = new ModelState();\n            modelState2.Errors.Add(\"modelState2.Error1\");\n            modelState2.Errors.Add(\"modelState2.Error2\");\n            modelStateDictionary[\"key2\"] = modelState2;\n\n            HttpError httpError = new HttpError(modelStateDictionary, includeErrorDetail: true);\n            HttpResponseMessage errorResponse = request.CreateResponse(HttpStatusCode.BadRequest);\n            errorResponse.Content = new ObjectContent<HttpError>(httpError, new JsonMediaTypeFormatter());\n\n            TraceRecord traceRecord = new TraceRecord(request, \"System.Web.Http.Request\", TraceLevel.Error)\n            {\n                Exception = new HttpResponseException(errorResponse)\n            };\n\n            // Act\n            new SystemDiagnosticsTraceWriter().TranslateHttpResponseException(traceRecord);\n\n            // Assert\n            Assert.Equal(TraceLevel.Warn, traceRecord.Level);\n\n            string message = ExtractModelStateErrorString(traceRecord.Message);\n\n            AssertContainsExactly(message, new Dictionary<string, string>()\n            {\n                { \"key1\", \"[modelState1.Error1, modelState1.Error2]\" },\n                { \"key2\", \"[modelState2.Error1, modelState2.Error2]\" },\n            });\n        }\n\n        [Fact]\n        public void TranslateHttpResponseException_Unpacks_HttpError_With_No_Fields_Set()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(\"http://localhost\"),\n                Method = HttpMethod.Get\n            };\n\n            Exception exception = null;\n            try\n            {\n                throw new InvalidOperationException(\"ExpectedExceptionMessage\");\n            }\n            catch (Exception ex)\n            {\n                exception = ex;\n            }\n\n            HttpError httpError = new HttpError();\n            HttpResponseMessage errorResponse = request.CreateResponse(HttpStatusCode.BadRequest);\n            errorResponse.Content = new ObjectContent<HttpError>(httpError, new JsonMediaTypeFormatter());\n\n            TraceRecord traceRecord = new TraceRecord(request, \"System.Web.Http.Request\", TraceLevel.Error)\n            {\n                Exception = new HttpResponseException(errorResponse)\n            };\n\n            // Act\n            new SystemDiagnosticsTraceWriter().TranslateHttpResponseException(traceRecord);\n\n            // Assert\n            Assert.Equal(TraceLevel.Warn, traceRecord.Level);\n            Assert.Equal(string.Empty, traceRecord.Message);\n        }\n\n        private static void AssertContainsExactly(string trace, IDictionary<string, string> expected)\n        {\n            IDictionary<string, string> actual = ParseTrace(trace);\n            Assert.Equal(expected.Count, actual.Count);\n            foreach (string key in expected.Keys)\n            {\n                Assert.True(actual.ContainsKey(key), String.Format(\"Missing {0} field\", key));\n                Assert.Equal(expected[key], actual[key]);\n            }\n        }\n\n        private static IDictionary<string, string> ParseTrace(string trace)\n        {\n            Dictionary<string, string> traces = new Dictionary<string, string>();\n            string[] splits = trace.Split('=');\n            for (int i = 0; i < splits.Length - 1; i++)\n            {\n                // Line is either \"key\" or \"value key\" -- get the key part\n                string[] nextSplit = splits[i].Split(' ');\n                if (nextSplit.Length < 1)\n                {\n                    continue;\n                }\n                string key = nextSplit[nextSplit.Length - 1].Trim();\n\n                string value;\n\n                // Last item containing name takes entire remaining text\n                if (i == splits.Length - 2)\n                {\n                    value = splits[i + 1].Trim();\n                }\n                else\n                {\n                    // Next line is \"value, nextKey\" -- get the value part\n                    int lastCommaPos = splits[i + 1].LastIndexOf(\", \");\n                    if (lastCommaPos < 0)\n                    {\n                        continue;\n                    }\n\n                    value = splits[i + 1].Substring(0, lastCommaPos).Trim();\n                }\n\n                traces[key] = value;\n            }\n\n            return traces;\n        }\n\n        private static string ExtractModelStateErrorString(string message)\n        {\n            string modelStatePrefix = \"ModelStateError=[\";\n            int modelStatePrefixPos = message.IndexOf(modelStatePrefix);\n            Assert.True(modelStatePrefixPos >= 0);\n            int lastBracketPos = message.LastIndexOf(\"]\");\n            Assert.True(lastBracketPos > modelStatePrefixPos);\n\n            int startPos = modelStatePrefixPos + modelStatePrefix.Length;\n\n            return message.Substring(startPos, lastBracketPos - startPos);\n        }\n\n        // Helper to create a new SystemDiagnosticsTraceWriter configured\n        // to use a custom TraceSource to write its traces to a TestTraceListener.\n        private static SystemDiagnosticsTraceWriter CreateTraceWriter()\n        {\n            TestTraceListener testTraceListener = new TestTraceListener();\n            TraceSource testTraceSource = new TraceSource(\"TestTraceSource\", SourceLevels.All);\n            testTraceSource.Listeners.Clear();\n            testTraceSource.Listeners.Add(testTraceListener);\n\n            SystemDiagnosticsTraceWriter writer = new SystemDiagnosticsTraceWriter();\n            writer.TraceSource = testTraceSource;\n            return writer;\n        }\n\n        // Test spy used to capture test traces\n        class TestTraceListener : TraceListener\n        {\n            private List<string> _messages = new List<string>();\n\n            public IList<string> Messages { get { return _messages; } }\n\n            public string SourceName { get; set; }\n\n            public int? Id { get; set; }\n\n            public TraceEventType TraceEventType { get; set; }\n\n            public override void Write(string message)\n            {\n                _messages.Add(message);\n            }\n\n            public override void WriteLine(string message)\n            {\n                Write(message + Environment.NewLine);\n            }\n\n            public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)\n            {\n                _messages.Add(message);\n                SourceName = source;\n                Id = id;\n                TraceEventType = eventType;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.Tracing.Test/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Newtonsoft.Json\" version=\"13.0.1\" targetFramework=\"net462\" />\n  <package id=\"xunit\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.abstractions\" version=\"2.0.3\" targetFramework=\"net462\" />\n  <package id=\"xunit.analyzers\" version=\"1.1.0\" targetFramework=\"net462\" />\n  <package id=\"xunit.assert\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.execution\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.runner.visualstudio\" version=\"2.4.5\" targetFramework=\"net462\" developmentDependency=\"true\" />\n</packages>"
  },
  {
    "path": "test/System.Web.Http.WebHost.Test/BatchingTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Batch;\nusing System.Web.Http.WebHost.Routing;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.WebHost\n{\n    public class BatchingTest\n    {\n        // Regression test for Codeplex-2103\n        //\n        // When batching is used in web host, we need to wrap the HttpRequestMessages in an HttpContextBase\n        // adapter and pass system to system.web. In 2103 there were bugs in this wrapper, and we weren't \n        // following the contract with respect to %-encoding.\n        [Fact]\n        public async Task WebHost_Batching_WithSpecialCharactersInUrl()\n        {\n            // Arrange\n            var handler = new SuccessMessageHandler();\n\n            var routeCollection = new HostedHttpRouteCollection(new RouteCollection(), \"/\");\n            routeCollection.Add(\"default\", routeCollection.CreateRoute(\n                \"values/  space\",\n                defaults: null,\n                constraints: null,\n                dataTokens: null,\n                handler: handler));\n\n            var configuration = new HttpConfiguration(routeCollection);\n\n            var server = new HttpServer(configuration);\n\n            var batchHandler = new DefaultHttpBatchHandler(server);\n            var request = new HttpRequestMessage\n            {\n                Content = new MultipartContent(\"mixed\")\n                {\n                    new HttpMessageContent(new HttpRequestMessage(HttpMethod.Post, \"http://contoso.com/values/  space\"))\n                }\n            };\n\n            // Arrange\n            var response = await batchHandler.ProcessBatchAsync(request, CancellationToken.None);\n\n            // Assert\n            Assert.Equal(HttpStatusCode.OK, response.StatusCode);\n            Assert.True(handler.IsCalled);\n        }\n\n        private class SuccessMessageHandler : HttpMessageHandler\n        {\n            public bool IsCalled { get; private set; }\n\n            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n            {\n                IsCalled = true;\n                return Task.FromResult(request.CreateResponse(HttpStatusCode.OK));\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.WebHost.Test/GlobalConfigurationTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.WebHost;\nusing System.Web.Http.WebHost.Routing;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http\n{\n    public class GlobalConfigurationTest\n    {\n        [Fact]\n        public void ConfigurationRouteCollection_IsHostedHttpRouteCollection()\n        {\n            // Arrange\n            HttpConfiguration configuration = GlobalConfiguration.Configuration;\n            Assert.NotNull(configuration); // Guard\n\n            // Act\n            HttpRouteCollection routes = configuration.Routes;\n\n            // Assert\n            Assert.IsType<HostedHttpRouteCollection>(routes);\n            // Note that there is currently no easy way to test that it references RouteTable.Routes.\n        }\n\n        [Theory]\n        [InlineData(typeof(IAssembliesResolver), typeof(WebHostAssembliesResolver))]\n        [InlineData(typeof(IHttpControllerTypeResolver), typeof(WebHostHttpControllerTypeResolver))]\n        [InlineData(typeof(IHostBufferPolicySelector), typeof(WebHostBufferPolicySelector))]\n        [InlineData(typeof(IExceptionHandler), typeof(WebHostExceptionHandler))]\n        public void ConfigurationService_IsWebHost(Type serviceInterfaceType, Type expectedImplementationType)\n        {\n            // Arrange\n            HttpConfiguration configuration = GlobalConfiguration.Configuration;\n            Assert.NotNull(configuration); // Guard\n            Assert.NotNull(configuration.Services); // Guard\n\n            // Act\n            object service = configuration.Services.GetService(serviceInterfaceType);\n\n            // Assert\n            Assert.IsType(expectedImplementationType, service);\n        }\n\n        [Fact]\n        public void ExceptionHandler_WrapsDefaultExceptionHandler()\n        {\n            // Arrange\n            HttpConfiguration configuration = GlobalConfiguration.Configuration;\n            Assert.NotNull(configuration); // Guard\n            Assert.NotNull(configuration.Services); // Guard\n\n            Type defaultExceptionHandlerType;\n\n            using (HttpConfiguration standardConfiguration = new HttpConfiguration())\n            {\n                defaultExceptionHandlerType = standardConfiguration.Services.GetExceptionHandler().GetType();\n            }\n\n            // Act\n            object service = configuration.Services.GetService(typeof(IExceptionHandler));\n\n            // Assert\n            WebHostExceptionHandler typedHandler = Assert.IsType<WebHostExceptionHandler>(service); // Guard\n            Assert.IsType(defaultExceptionHandlerType, typedHandler.InnerHandler);\n        }\n\n        [Fact]\n        public void DefaultHandler_IsHttpRoutingDispatcher()\n        {\n            // Act\n            HttpMessageHandler handler = GlobalConfiguration.DefaultHandler;\n\n            // Assert\n            Assert.IsType<HttpRoutingDispatcher>(handler);\n            // Note that there is currently no easy way to test it references GlobalConfiguration.Configuration.\n        }\n\n        [Fact]\n        public void DefaultServer_ReferencesConfiguration()\n        {\n            // Act\n            HttpServer server = GlobalConfiguration.DefaultServer;\n\n            // Assert\n            Assert.NotNull(server);\n            Assert.Same(GlobalConfiguration.Configuration, server.Configuration);\n        }\n\n        [Fact]\n        public void DefaultServer_ReferencesDefaultHandler()\n        {\n            // Act\n            HttpServer server = GlobalConfiguration.DefaultServer;\n\n            // Assert\n            Assert.NotNull(server);\n            Assert.Same(GlobalConfiguration.DefaultHandler, server.Dispatcher);\n        }\n\n        [Fact]\n        public void Configure_Throws_WhenConfigurationCallbackIsNull()\n        {\n            // Arrange\n            using (new GlobalConfigurationContext())\n            {\n                // Act & Assert\n                Assert.ThrowsArgumentNull(() => { GlobalConfiguration.Configure(null); }, \"configurationCallback\");\n            }\n        }\n\n        [Fact]\n        public void Configure_CallsCallbackOnceWithGlobalConfiguration()\n        {\n            // Arrange\n            using (new GlobalConfigurationContext())\n            {\n                int calls = 0;\n                HttpConfiguration configuration = null;\n                Action<HttpConfiguration> callback = (c) =>\n                {\n                    calls++;\n                    configuration = c;\n                };\n\n                // Act\n                GlobalConfiguration.Configure(callback);\n\n                // Assert\n                Assert.Equal(1, calls);\n                Assert.Same(GlobalConfiguration.Configuration, configuration);\n            }\n        }\n\n        [Fact]\n        public void Configure_CallsConfigurationEnsureInitialized()\n        {\n            // Arrange\n            using (new GlobalConfigurationContext())\n            {\n                bool initialized = false;\n                GlobalConfiguration.Configuration.Initializer = (c) =>\n                {\n                    initialized = true;\n                };\n                Action<HttpConfiguration> callback = (ignore) => { };\n\n                // Act\n                GlobalConfiguration.Configure(callback);\n\n                // Assert\n                Assert.True(initialized);\n            }\n        }\n\n        private sealed class GlobalConfigurationContext : IDisposable\n        {\n            bool disposed;\n\n            public void Dispose()\n            {\n                if (!disposed)\n                {\n                    GlobalConfiguration.Reset();\n                    disposed = true;\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.WebHost.Test/HttpControllerHandlerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Diagnostics.Contracts;\nusing System.IO;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Reflection;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.Results;\nusing System.Web.Http.WebHost.Routing;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\nusing Newtonsoft.Json.Linq;\n\nnamespace System.Web.Http.WebHost\n{\n    public class HttpControllerHandlerTest\n    {\n        public static TheoryDataSet<HttpMethod> AllHttpMethods\n        {\n            get\n            {\n                return new TheoryDataSet<HttpMethod>\n                {\n                    HttpMethod.Get,\n                    HttpMethod.Post,\n                    HttpMethod.Put,\n                    HttpMethod.Delete,\n                    HttpMethod.Head,\n                    HttpMethod.Options,\n                    HttpMethod.Trace\n                };\n            }\n        }\n\n        public static TheoryDataSet<HttpMethod> HttpMethodsWithContent\n        {\n            get\n            {\n                return new TheoryDataSet<HttpMethod>\n                {\n                    HttpMethod.Post,\n                    HttpMethod.Put,\n                    HttpMethod.Delete,\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"AllHttpMethods\")]\n        public void ConvertRequest_Creates_HttpRequestMessage_For_All_HttpMethods(HttpMethod httpMethod)\n        {\n            // Arrange\n            HttpContextBase contextBase = CreateStubContextBase(httpMethod.Method, new MemoryStream());\n\n            // Act\n            HttpRequestMessage request = HttpControllerHandler.ConvertRequest(contextBase);\n\n            // Assert\n            Assert.Equal(httpMethod, request.Method);\n        }\n\n        [Fact]\n        public void ConvertRequest_DoesNotAddContentLength()\n        {\n            // Arrange\n            HttpContextBase contextBase = CreateStubContextBase(\"Get\", new MemoryStream());\n\n            // Act\n            HttpRequestMessage request = HttpControllerHandler.ConvertRequest(contextBase);\n\n            // Assert\n            var headers = request.Content.Headers;\n            Assert.NotNull(headers);\n            Assert.Null(headers.ContentLength);\n\n            IEnumerable<string> unused;\n            Assert.False(headers.TryGetValues(\"Content-Length\", out unused));\n        }\n\n        [Fact]\n        public void ConvertRequest_Copies_Headers_And_Content_Headers()\n        {\n            // Arrange\n            HttpContextBase contextBase = CreateStubContextBase(\"Get\", new MemoryStream());\n            HttpRequestBase requestBase = contextBase.Request;\n            NameValueCollection nameValues = requestBase.Headers;\n            nameValues[\"myHeader\"] = \"myValue\";\n            nameValues[\"Content-Type\"] = \"application/mine\";\n\n            // Act\n            HttpRequestMessage request = HttpControllerHandler.ConvertRequest(contextBase);\n            string[] headerValues = request.Headers.GetValues(\"myHeader\").ToArray();\n\n            // Assert\n            Assert.Equal(\"myValue\", headerValues[0]);\n            Assert.Equal(\"application/mine\", request.Content.Headers.ContentType.MediaType);\n        }\n\n        [Theory]\n        [PropertyData(\"HttpMethodsWithContent\")]\n        public void ConvertRequest_Creates_Request_With_Content_For_Content_Methods(HttpMethod httpMethod)\n        {\n            // Arrange\n            HttpContextBase contextBase = CreateStubContextBase(httpMethod.Method, new MemoryStream());\n\n            // Act\n            HttpRequestMessage actualRequest = HttpControllerHandler.ConvertRequest(contextBase);\n\n            // Assert\n            Assert.NotNull(actualRequest.Content);\n        }\n\n        [Fact]\n        public async Task ConvertRequest_Uses_HostBufferPolicySelector_To_Select_Buffered_Stream()\n        {\n            // Arrange\n            HttpContextBase contextMock = CreateStubContextBase(\"Post\", new MemoryStream(new byte[] { 5 }));\n            MemoryStream memoryStream = new MemoryStream();\n\n            // Act\n            HttpRequestMessage actualRequest = HttpControllerHandler.ConvertRequest(contextMock);\n            await actualRequest.Content.CopyToAsync(memoryStream);\n            byte[] actualBuffer = memoryStream.GetBuffer();\n\n            // Assert\n            Assert.Equal(5, actualBuffer[0]);\n        }\n\n        [Fact]\n        public void ConvertRequest_AddsOwinEnvironment_WhenPresentInHttpContext()\n        {\n            // Arrange\n            using (MemoryStream ignoreStream = new MemoryStream())\n            {\n                HttpRequestBase stubRequest = CreateStubRequestBase(\"IgnoreMethod\", ignoreStream);\n                IDictionary<string, object> expectedEnvironment = new Dictionary<string, object>();\n                IDictionary items = new Hashtable\n                {\n                    { HttpControllerHandler.OwinEnvironmentHttpContextKey, expectedEnvironment }\n                };\n                HttpContextBase context = CreateStubContextBase(stubRequest, items);\n\n                // Act\n                using (HttpRequestMessage actualRequest = HttpControllerHandler.ConvertRequest(context))\n                {\n                    IDictionary<string, object> environment = actualRequest.GetOwinEnvironment();\n\n                    // Assert\n                    Assert.Same(expectedEnvironment, environment);\n                }\n            }\n        }\n\n        [Fact]\n        public void ConvertRequest_DoesNotAddOwinEnvironment_WhenNotPresentInHttpContext()\n        {\n            // Arrange\n            using (MemoryStream ignoreStream = new MemoryStream())\n            {\n                HttpRequestBase stubRequest = CreateStubRequestBase(\"IgnoreMethod\", ignoreStream);\n                IDictionary items = new Hashtable();\n                HttpContextBase context = CreateStubContextBase(stubRequest, items);\n\n                // Act\n                using (HttpRequestMessage actualRequest = HttpControllerHandler.ConvertRequest(context))\n                {\n                    // Assert\n                    object ignore;\n                    bool found = actualRequest.Properties.TryGetValue(HttpControllerHandler.OwinEnvironmentKey,\n                        out ignore);\n                    Assert.False(found);\n                }\n            }\n        }\n\n        [Fact]\n        public void ConvertRequest_DoesNotAddOwinEnvironment_WhenItemsIsNull()\n        {\n            // Arrange\n            using (MemoryStream ignoreStream = new MemoryStream())\n            {\n                HttpRequestBase stubRequest = CreateStubRequestBase(\"IgnoreMethod\", ignoreStream);\n                IDictionary items = null;\n                HttpContextBase context = CreateStubContextBase(stubRequest, items);\n\n                // Act\n                using (HttpRequestMessage actualRequest = HttpControllerHandler.ConvertRequest(context))\n                {\n                    // Assert\n                    object ignore;\n                    bool found = actualRequest.Properties.TryGetValue(HttpControllerHandler.OwinEnvironmentKey,\n                        out ignore);\n                    Assert.False(found);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task ConvertRequest_DoesLazyGetInputStream()\n        {\n            bool inputStreamCalled = false;\n            HttpRequestBase stubRequest = CreateFakeRequestBase(() =>\n            {\n                inputStreamCalled = true;\n                return new MemoryStream();\n            }, buffered: true);\n            HttpContextBase context = CreateStubContextBase(request: stubRequest, items: null);\n\n            HttpRequestMessage actualRequest = HttpControllerHandler.ConvertRequest(context);\n\n            Assert.False(inputStreamCalled);\n            var contentStream = await actualRequest.Content.ReadAsStreamAsync();\n            Assert.True(inputStreamCalled);\n        }\n\n        [Fact]\n        public async Task ConvertRequest_UsesRequestInputStream_InClassicMode()\n        {\n            // Arrange\n            string input = \"Hello world\";\n            var stream = new MemoryStream(Encoding.UTF8.GetBytes(input));\n            HttpRequestBase fakeRequest = CreateFakeRequestBase(() => stream, buffered: true);\n            HttpContextBase context = CreateStubContextBase(request: fakeRequest, items: null);\n            Mock<HttpRequestBase> mockRequest = Mock.Get<HttpRequestBase>(fakeRequest);\n\n            // Act\n            fakeRequest.InputStream.Position = 10;\n            HttpRequestMessage actualRequest = HttpControllerHandler.ConvertRequest(context);\n            string result = await actualRequest.Content.ReadAsStringAsync();\n\n            // Assert\n            // Verify that the InputStream was reset when reading the content.\n            Assert.Equal(input, result);\n            mockRequest.Verify(r => r.InputStream, Times.AtLeastOnce());\n            mockRequest.Verify(r => r.GetBufferedInputStream(), Times.Never());\n        }\n\n        [Fact]\n        public async Task ConvertRequest_UsesBufferedInputStream_IfReadEntityBodyModeIsNone()\n        {\n            // Arrange\n            HttpRequestBase stubRequest = CreateFakeRequestBase(() => new MemoryStream(), buffered: true);\n            HttpContextBase context = CreateStubContextBase(request: stubRequest, items: null);\n            Mock<HttpRequestBase> mockRequest = Mock.Get<HttpRequestBase>(stubRequest);\n\n            // Act\n            HttpRequestMessage actualRequest = HttpControllerHandler.ConvertRequest(context);\n            await actualRequest.Content.ReadAsStreamAsync();\n\n            // Assert\n            mockRequest.Verify(r => r.InputStream, Times.Never());\n            mockRequest.Verify(r => r.GetBufferedInputStream(), Times.AtLeastOnce());\n        }\n\n        [Fact]\n        public Task ConvertRequest_WithBufferedPolicy_ThrowsIfRequestHasBeenPartiallyRead()\n        {\n            // Arrange\n            var stream = new MemoryStream(new byte[16]);\n            HttpRequestBase fakeRequest = CreateFakeRequestBase(() => stream, buffered: true);\n            HttpContextBase context = CreateStubContextBase(request: fakeRequest, items: null);\n\n            // Act\n            fakeRequest.GetBufferedInputStream().Position = 4;\n            HttpRequestMessage actualRequest = HttpControllerHandler.ConvertRequest(context);\n\n            // Assert\n            return Assert.ThrowsAsync<InvalidOperationException>(() => actualRequest.Content.ReadAsStringAsync());\n        }\n\n        [Fact]\n        public async Task ConvertRequest_WithBufferedPolicy_ReturnsInputStreamIfBufferedStreamWasFullyRead()\n        {\n            // Arrange\n            string inputStreamMessage = \"This is from input stream\";\n            var bufferedStream = new MemoryStream(new byte[16]);\n            var inputStream = new MemoryStream(Encoding.UTF8.GetBytes(inputStreamMessage));\n            HttpRequestBase fakeRequest = CreateFakeRequestBase(() => bufferedStream, buffered: true);\n            HttpContextBase context = CreateStubContextBase(request: fakeRequest, items: null);\n            Mock<HttpRequestBase> mockRequest = Mock.Get<HttpRequestBase>(fakeRequest);\n            mockRequest.SetupGet(f => f.InputStream)\n                       .Returns(inputStream)\n                       .Verifiable();\n\n            // Act\n            bufferedStream.Seek(0, SeekOrigin.End);\n            new StreamReader(fakeRequest.GetBufferedInputStream()).ReadToEnd();\n            HttpRequestMessage actualRequest = HttpControllerHandler.ConvertRequest(context);\n            string result = await actualRequest.Content.ReadAsStringAsync();\n\n            // Assert\n            Assert.Equal(inputStreamMessage, result);\n        }\n\n        [Fact]\n        public async Task ConvertRequest_DoesLazyGetBufferlessInputStream_IfRequestStreamHasNotBeenRead()\n        {\n            // Arrange\n            bool inputStreamCalled = false;\n            var hostBufferPolicy = new Mock<IHostBufferPolicySelector>();\n            hostBufferPolicy.Setup(c => c.UseBufferedInputStream(It.IsAny<object>()))\n                                          .Returns(false);\n            hostBufferPolicy.Setup(c => c.UseBufferedOutputStream(It.IsAny<HttpResponseMessage>()))\n                                          .Returns(true);\n\n            HttpRequestBase stubRequest = CreateFakeRequestBase(() =>\n                {\n                    inputStreamCalled = true;\n                    return new MemoryStream();\n                }, buffered: false);\n            HttpContextBase context = HttpControllerHandlerTest.CreateStubContextBase(request: stubRequest, items: null);\n\n            // Act\n            HttpRequestMessage actualRequest = HttpControllerHandler.ConvertRequest(context, hostBufferPolicy.Object);\n\n            // Assert\n            Assert.False(inputStreamCalled);\n            Stream contentStream = await actualRequest.Content.ReadAsStreamAsync();\n            Assert.True(inputStreamCalled);\n        }\n\n        [Fact]\n        public Task ConvertRequest_WithBufferlessPolicy_ThrowsIfRequestStreamHasBeenReadInClassicMode()\n        {\n            // Arrange\n            var hostBufferPolicy = new Mock<IHostBufferPolicySelector>();\n            hostBufferPolicy.Setup(c => c.UseBufferedInputStream(It.IsAny<object>()))\n                                          .Returns(false);\n            hostBufferPolicy.Setup(c => c.UseBufferedOutputStream(It.IsAny<HttpResponseMessage>()))\n                                          .Returns(true);\n\n            var stream = new MemoryStream(8);\n            HttpRequestBase stubRequest = CreateFakeRequestBase(() => stream, buffered: false);\n            HttpContextBase context = HttpControllerHandlerTest.CreateStubContextBase(request: stubRequest, items: null);\n\n            // Act\n            context.Request.InputStream.Position = 2;\n            HttpRequestMessage actualRequest = HttpControllerHandler.ConvertRequest(context, hostBufferPolicy.Object);\n\n            // Assert\n            return Assert.ThrowsAsync<InvalidOperationException>(() => actualRequest.Content.ReadAsStreamAsync(),\n                 \"Unable to read the entity body in Bufferless mode. The request stream has already been buffered.\");\n        }\n\n        [Fact]\n        public Task ConvertRequest_WithBufferlessPolicy_ThrowsIfRequestStreamHasBeenReadInBufferedMode()\n        {\n            // Arrange\n            var hostBufferPolicy = new Mock<IHostBufferPolicySelector>();\n            hostBufferPolicy.Setup(c => c.UseBufferedInputStream(It.IsAny<object>()))\n                                          .Returns(false);\n            hostBufferPolicy.Setup(c => c.UseBufferedOutputStream(It.IsAny<HttpResponseMessage>()))\n                                          .Returns(true);\n\n            var stream = new MemoryStream(8);\n            HttpRequestBase stubRequest = CreateFakeRequestBase(() => stream, buffered: false);\n            HttpContextBase context = HttpControllerHandlerTest.CreateStubContextBase(request: stubRequest, items: null);\n\n            // Act\n            context.Request.GetBufferedInputStream();\n            HttpRequestMessage message = HttpControllerHandler.ConvertRequest(context, hostBufferPolicy.Object);\n\n            // Assert\n            return Assert.ThrowsAsync<InvalidOperationException>(() => message.Content.ReadAsStringAsync(),\n                 \"Unable to read the entity body. The request stream has already been read in 'Buffered' mode.\");\n        }\n\n        [Fact]\n        public Task ConvertRequest_WithBufferlessPolicy_ThrowsIfRequestStreamHasBeenRead()\n        {\n            // Arrange\n            var hostBufferPolicy = new Mock<IHostBufferPolicySelector>();\n            hostBufferPolicy.Setup(c => c.UseBufferedInputStream(It.IsAny<object>()))\n                                          .Returns(false);\n            hostBufferPolicy.Setup(c => c.UseBufferedOutputStream(It.IsAny<HttpResponseMessage>()))\n                                          .Returns(true);\n\n            var stream = new MemoryStream(new byte[16]);\n            HttpRequestBase stubRequest = CreateFakeRequestBase(() => stream, buffered: false);\n            HttpContextBase context = HttpControllerHandlerTest.CreateStubContextBase(request: stubRequest, items: null);\n\n            // Act\n            context.Request.GetBufferlessInputStream().Position = 4;\n            HttpRequestMessage message = HttpControllerHandler.ConvertRequest(context, hostBufferPolicy.Object);\n\n            // Assert\n            return Assert.ThrowsAsync<InvalidOperationException>(() => message.Content.ReadAsStringAsync(),\n                 \"Unable to read the entity body. A portion of the request stream has already been read.\");\n        }\n\n        [Fact]\n        public void ConvertRequest_AddsWebHostHttpRequestContext()\n        {\n            // Arrange\n            Mock<HttpRequestBase> requestBaseMock = new Mock<HttpRequestBase>(MockBehavior.Strict);\n            requestBaseMock.Setup(r => r.HttpMethod).Returns(\"IGNORED\");\n            requestBaseMock.Setup(r => r.Url).Returns(new Uri(\"http://ignore\"));\n            requestBaseMock.Setup(r => r.Headers).Returns(new NameValueCollection());\n            requestBaseMock.Setup(r => r.ReadEntityBodyMode).Returns(ReadEntityBodyMode.None);\n            HttpRequestBase requestBase = requestBaseMock.Object;\n            Mock<HttpContextBase> contextBaseMock = new Mock<HttpContextBase>(MockBehavior.Strict);\n            contextBaseMock.Setup(c => c.Request).Returns(requestBase);\n            contextBaseMock.Setup(c => c.Items).Returns((IDictionary)null);\n            HttpContextBase contextBase = contextBaseMock.Object;\n\n            // Act\n            using (HttpRequestMessage expectedRequest = HttpControllerHandler.ConvertRequest(contextBase))\n            {\n                // Assert\n                HttpRequestContext context = expectedRequest.GetRequestContext();\n                WebHostHttpRequestContext typedContext = Assert.IsType<WebHostHttpRequestContext>(context);\n                Assert.Same(contextBase, typedContext.Context);\n                Assert.Same(requestBase, typedContext.WebRequest);\n                Assert.Same(expectedRequest, typedContext.Request);\n            }\n        }\n\n        [Fact]\n        public async Task CopyResponseAsync_IfResponseHasNoCacheControlDefined_SetsNoCacheCacheabilityOnAspNetResponse()\n        {\n            // Arrange\n            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>() { DefaultValue = DefaultValue.Mock };\n            HttpRequestMessage request = new HttpRequestMessage();\n            HttpResponseMessage response = new HttpResponseMessage();\n\n            // Act\n            await CopyResponseAsync(contextMock.Object, request, response);\n\n            // Assert\n            contextMock.Verify(c => c.Response.Cache.SetCacheability(HttpCacheability.NoCache));\n        }\n\n        [Fact]\n        public async Task CopyResponseAsync_IfResponseHasCacheControlDefined_DoesNotSetCacheCacheabilityOnAspNetResponse()\n        {\n            // Arrange\n            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>() { DefaultValue = DefaultValue.Mock };\n            HttpRequestMessage request = new HttpRequestMessage();\n            HttpResponseMessage response = new HttpResponseMessage();\n            response.Headers.CacheControl = new CacheControlHeaderValue { Public = true };\n\n            // Act\n            await CopyResponseAsync(contextMock.Object, request, response);\n\n            // Assert\n            contextMock.Verify(c => c.Response.Cache.SetCacheability(HttpCacheability.NoCache), Times.Never());\n        }\n\n        [Fact]\n        public async Task ProcessRequestAsync_DisposesRequestAndResponse()\n        {\n            // Arrange\n            Mock<HttpResponseBase> responseMock = new Mock<HttpResponseBase>() { DefaultValue = DefaultValue.Mock };\n            responseMock.SetupGet(r => r.OutputStream).Returns(Stream.Null);\n            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>() { DefaultValue = DefaultValue.Mock };\n            contextMock.SetupGet(hcb => hcb.Response).Returns(responseMock.Object);\n            IDictionary items = new Dictionary<object, object>();\n            contextMock.SetupGet((hcb) => hcb.Items).Returns(items);\n            HttpContextBase context = contextMock.Object;\n\n            HttpRequestMessage request = new HttpRequestMessage();\n            context.SetHttpRequestMessage(request);\n            SpyDisposable spy = new SpyDisposable();\n            request.RegisterForDispose(spy);\n            HttpResponseMessage response = new HttpResponseMessage();\n\n            Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> sendAsync = (r, c) =>\n                Task.FromResult(response);\n\n            using (HttpMessageHandler handler = new LambdaHttpMessageHandler(sendAsync))\n            {\n                HttpControllerHandler product = new HttpControllerHandler(\n                    new Mock<RouteData>(MockBehavior.Strict).Object, handler);\n\n                // Act\n                await product.ProcessRequestAsyncCore(context);\n\n                // Assert\n                Assert.True(spy.Disposed);\n                Assert.ThrowsObjectDisposed(() => request.Method = HttpMethod.Get, typeof(HttpRequestMessage).FullName);\n                Assert.ThrowsObjectDisposed(() => response.StatusCode = HttpStatusCode.OK, typeof(HttpResponseMessage).FullName);\n            }\n        }\n\n        [Fact]\n        public async Task ProcessRequestAsync_DisposesRequestAndResponseWithContent()\n        {\n            // Arrange\n            Mock<HttpResponseBase> responseMock = new Mock<HttpResponseBase>() { DefaultValue = DefaultValue.Mock };\n            responseMock.SetupGet(r => r.OutputStream).Returns(Stream.Null);\n            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>() { DefaultValue = DefaultValue.Mock };\n            contextMock.SetupGet(hcb => hcb.Response).Returns(responseMock.Object);\n            IDictionary items = new Dictionary<object, object>();\n            contextMock.SetupGet((hcb) => hcb.Items).Returns(items);\n            HttpContextBase context = contextMock.Object;\n\n            HttpRequestMessage request = new HttpRequestMessage() { Content = new StringContent(\"request\") };\n            context.SetHttpRequestMessage(request);\n            SpyDisposable spy = new SpyDisposable();\n            request.RegisterForDispose(spy);\n            HttpResponseMessage response = new HttpResponseMessage() { Content = new StringContent(\"response\") };\n\n            Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> sendAsync = (r, c) =>\n                Task.FromResult(response);\n\n            using (HttpMessageHandler handler = new LambdaHttpMessageHandler(sendAsync))\n            {\n                HttpControllerHandler product = new HttpControllerHandler(\n                    new Mock<RouteData>(MockBehavior.Strict).Object, handler);\n\n                // Act\n                await product.ProcessRequestAsyncCore(context);\n\n                // Assert\n                Assert.True(spy.Disposed);\n                Assert.ThrowsObjectDisposed(() => request.Method = HttpMethod.Get, typeof(HttpRequestMessage).FullName);\n                Assert.ThrowsObjectDisposed(() => response.StatusCode = HttpStatusCode.OK, typeof(HttpResponseMessage).FullName);\n            }\n        }\n\n        [Fact]\n        public async Task ProcessRequestAsync_IfHandlerFaults_DisposesRequest()\n        {\n            // Arrange\n            Mock<HttpResponseBase> responseMock = new Mock<HttpResponseBase>();\n            responseMock.SetupGet(r => r.OutputStream).Returns(Stream.Null);\n            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>() { DefaultValue = DefaultValue.Mock };\n            contextMock.SetupGet(hcb => hcb.Response).Returns(responseMock.Object);\n            IDictionary items = new Dictionary<object, object>();\n            contextMock.SetupGet((hcb) => hcb.Items).Returns(items);\n            HttpContextBase context = contextMock.Object;\n\n            HttpRequestMessage request = new HttpRequestMessage();\n            context.SetHttpRequestMessage(request);\n            SpyDisposable spy = new SpyDisposable();\n            request.RegisterForDispose(spy);\n\n            Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> sendAsync = (r, c) =>\n                CreateFaultedTask<HttpResponseMessage>(CreateException());\n\n            using (HttpMessageHandler handler = new LambdaHttpMessageHandler(sendAsync))\n            {\n                HttpControllerHandler product = new HttpControllerHandler(\n                    new Mock<RouteData>(MockBehavior.Strict).Object, handler);\n\n                // Act & Assert\n                await Assert.ThrowsAsync<EncoderFallbackException>(() => product.ProcessRequestAsyncCore(context));\n\n                Assert.True(spy.Disposed);\n                Assert.ThrowsObjectDisposed(() => request.Method = HttpMethod.Get, typeof(HttpRequestMessage).FullName);\n            }\n        }\n\n        [Fact]\n        public void SuppressFormsAuthenticationRedirect_DoesntRequireSuppressRedirect()\n        {\n            // Arrange\n            Mock<HttpResponseBase> responseMock = new Mock<HttpResponseBase>();\n            responseMock.SetupGet(r => r.StatusCode).Returns(200);\n            responseMock.SetupSet(r => r.SuppressFormsAuthenticationRedirect = It.IsAny<bool>()).Verifiable();\n            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>() { DefaultValue = DefaultValue.Mock };\n            IDictionary contextItems = new Hashtable();\n            contextMock.SetupGet(hcb => hcb.Response).Returns(responseMock.Object);\n            contextMock.SetupGet(hcb => hcb.Items).Returns(contextItems);\n\n            // Act\n            HttpControllerHandler.EnsureSuppressFormsAuthenticationRedirect(contextMock.Object);\n\n            // Assert\n            responseMock.VerifySet(r => r.SuppressFormsAuthenticationRedirect = It.IsAny<bool>(), Times.Never);\n        }\n\n        [Fact]\n        public void SuppressFormsAuthenticationRedirect_RequireSuppressRedirect()\n        {\n            // Arrange\n            bool suppressFormsAuthenticationRedirect = false;\n            Mock<HttpResponseBase> responseMock = new Mock<HttpResponseBase>();\n            responseMock.SetupGet(r => r.StatusCode).Returns(401);\n            responseMock.SetupSet<bool>(r => r.SuppressFormsAuthenticationRedirect = It.IsAny<bool>())\n                .Callback(value => suppressFormsAuthenticationRedirect = value)\n                .Verifiable();\n            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>() { DefaultValue = DefaultValue.Mock };\n            IDictionary contextItems = new Hashtable();\n            contextMock.SetupGet(hcb => hcb.Response).Returns(responseMock.Object);\n            contextMock.SetupGet(hcb => hcb.Items).Returns(contextItems);\n\n            // Act\n            HttpControllerHandler.EnsureSuppressFormsAuthenticationRedirect(contextMock.Object);\n\n            // Assert\n            responseMock.VerifySet(r => r.SuppressFormsAuthenticationRedirect = It.IsAny<bool>(), Times.Once);\n            Assert.True(suppressFormsAuthenticationRedirect);\n        }\n\n        [Fact]\n        public async Task CopyResponseAsync_Creates_Correct_HttpResponseBase()\n        {\n            // Arrange\n            MemoryStream memoryStream = new MemoryStream();\n            Mock<HttpContextBase> contextMock = CreateMockHttpContextBaseForResponse(memoryStream);\n            HttpResponseBase responseBase = contextMock.Object.Response;\n            HttpRequestMessage request = new HttpRequestMessage();\n            HttpResponseMessage response = new HttpResponseMessage() { RequestMessage = request };\n            response.Content = new ObjectContent<string>(\"hello\", new JsonMediaTypeFormatter());\n\n            // Act\n            await CopyResponseAsync(contextMock.Object, request, response);\n\n            // Assert preparation -- deserialize the response\n            memoryStream.Seek(0L, SeekOrigin.Begin);\n            string responseString = null;\n            using (var streamReader = new StreamReader(memoryStream))\n            {\n                responseString = streamReader.ReadToEnd();\n            }\n\n            // Assert\n            Assert.Equal((int)HttpStatusCode.OK, responseBase.StatusCode);\n            Assert.StartsWith(JsonMediaTypeFormatter.DefaultMediaType.MediaType, responseBase.Headers[\"Content-Type\"]);\n            Assert.Equal(\"\\\"hello\\\"\", responseString);\n        }\n\n        [Fact]\n        public async Task CopyResponseAsync_IfTransferEncodingChunkedAndContentLengthAreBothSet_IgnoresContentLength()\n        {\n            // Arrange\n            HttpResponseBase responseBase = CreateMockHttpResponseBaseForResponse(Stream.Null).Object;\n            HttpContextBase contextBase = CreateStubContextBase(responseBase);\n\n            using (HttpRequestMessage request = new HttpRequestMessage())\n            using (HttpResponseMessage response = new HttpResponseMessage() { RequestMessage = request })\n            {\n                response.Headers.TransferEncodingChunked = true;\n                response.Content = new StringContent(\"SomeContent\");\n                Assert.NotNull(response.Content.Headers.ContentLength); // Guard; added by System.Net.Http.\n\n                // Act\n                await CopyResponseAsync(contextBase, request, response);\n\n                // Assert\n                Assert.DoesNotContain(\"Content-Length\", responseBase.Headers.OfType<string>());\n            }\n        }\n\n        [Fact]\n        public async Task CopyResponseAsync_IfTransferEncodingIsJustChunked_DoesNotCopyHeaderToHost()\n        {\n            // Arrange\n            HttpResponseBase responseBase = CreateMockHttpResponseBaseForResponse(Stream.Null).Object;\n            HttpContextBase contextBase = CreateStubContextBase(responseBase);\n\n            using (HttpRequestMessage request = new HttpRequestMessage())\n            using (HttpResponseMessage response = new HttpResponseMessage() { RequestMessage = request })\n            {\n                response.Headers.TransferEncodingChunked = true;\n\n                // Act\n                await CopyResponseAsync(contextBase, request, response);\n\n                // Assert\n                Assert.DoesNotContain(\"Transfer-Encoding\", responseBase.Headers.OfType<string>());\n            }\n        }\n\n        [Fact]\n        public async Task CopyResponseAsync_IfTransferEncodingIsIdentity_CopiesHeaderToHost()\n        {\n            // Arrange\n            HttpResponseBase responseBase = CreateMockHttpResponseBaseForResponse(Stream.Null).Object;\n            HttpContextBase contextBase = CreateStubContextBase(responseBase);\n\n            using (HttpRequestMessage request = new HttpRequestMessage())\n            using (HttpResponseMessage response = new HttpResponseMessage() { RequestMessage = request })\n            {\n                response.Headers.TransferEncoding.Add(new TransferCodingHeaderValue(\"identity\"));\n\n                // Act\n                await CopyResponseAsync(contextBase, request, response);\n\n                // Assert\n                Assert.Contains(\"Transfer-Encoding\", responseBase.Headers.OfType<string>());\n                Assert.Equal(new string[] { \"identity\" }, responseBase.Headers.GetValues(\"Transfer-Encoding\"));\n            }\n        }\n\n        [Fact]\n        public async Task CopyResponseAsync_IfTransferEncodingIsIdentityChunked_CopiesHeaderToHost()\n        {\n            // Arrange\n            HttpResponseBase responseBase = CreateMockHttpResponseBaseForResponse(Stream.Null).Object;\n            HttpContextBase contextBase = CreateStubContextBase(responseBase);\n\n            using (HttpRequestMessage request = new HttpRequestMessage())\n            using (HttpResponseMessage response = new HttpResponseMessage() { RequestMessage = request })\n            {\n                response.Headers.TransferEncoding.Add(new TransferCodingHeaderValue(\"identity\"));\n                response.Headers.TransferEncodingChunked = true;\n                Assert.Equal(\"identity, chunked\", response.Headers.TransferEncoding.ToString()); // Guard\n\n                // Act\n                await CopyResponseAsync(contextBase, request, response);\n\n                // Assert\n                Assert.Contains(\"Transfer-Encoding\", responseBase.Headers.OfType<string>());\n                Assert.Equal(new string[] { \"identity\", \"chunked\" },\n                    responseBase.Headers.GetValues(\"Transfer-Encoding\"));\n            }\n        }\n\n        [Fact]\n        public async Task CopyResponseAsync_IfTransferEncodingIsChunked_DisablesResponseBuffering()\n        {\n            // Arrange\n            HttpResponseBase responseBase = CreateMockHttpResponseBaseForResponse(Stream.Null).Object;\n            HttpContextBase contextBase = CreateStubContextBase(responseBase);\n\n            using (HttpRequestMessage request = new HttpRequestMessage())\n            using (HttpResponseMessage response = new HttpResponseMessage() { RequestMessage = request })\n            {\n                response.Headers.TransferEncodingChunked = true;\n                response.Content = new ObjectContent(typeof(string), String.Empty, new JsonMediaTypeFormatter());\n\n                // Act\n                await CopyResponseAsync(contextBase, request, response);\n\n                // Assert\n                Assert.False(responseBase.BufferOutput);\n            }\n        }\n\n        [Fact]\n        public async Task CopyResponseAsync_IfHandlerIsDefault_Returns_Error_Response_When_Formatter_Write_Task_Faults()\n        {\n            // Arrange\n            Mock<JsonMediaTypeFormatter> formatterMock = new Mock<JsonMediaTypeFormatter>() { CallBase = true };\n            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();\n            try\n            {\n                // to capture stack trace inside this method\n                throw new NotSupportedException(\"Expected error\");\n            }\n            catch (Exception ex)\n            {\n                tcs.SetException(ex);\n            }\n\n            formatterMock.Setup(m => m.WriteToStreamAsync(It.IsAny<Type>(),\n                                                          It.IsAny<object>(),\n                                                          It.IsAny<Stream>(),\n                                                          It.IsAny<HttpContent>(),\n                                                          It.IsAny<TransportContext>())).Returns(tcs.Task);\n\n            MemoryStream memoryStream = new MemoryStream();\n            Mock<HttpContextBase> contextMock = CreateMockHttpContextBaseForResponse(memoryStream);\n            HttpResponseBase responseBase = contextMock.Object.Response;\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.SetIsLocal(new Lazy<bool>(() => true));\n            HttpResponseMessage response = new HttpResponseMessage() { RequestMessage = request };\n            response.Content = new ObjectContent<string>(\"hello\", formatterMock.Object);\n            IExceptionLogger exceptionLogger = CreateStubExceptionLogger();\n            IExceptionHandler exceptionHandler = ExceptionServices.GetHandler(GlobalConfiguration.Configuration);\n\n            // Act\n            await HttpControllerHandler.CopyResponseAsync(contextMock.Object, request, response, exceptionLogger,\n                exceptionHandler, CancellationToken.None);\n\n            // Assert preparation -- deserialize the HttpError response\n            HttpError httpError = null;\n            memoryStream.Seek(0L, SeekOrigin.Begin);\n            using (StreamContent content = new StreamContent(memoryStream))\n            {\n                content.Headers.ContentType = JsonMediaTypeFormatter.DefaultMediaType;\n                httpError = await content.ReadAsAsync<HttpError>();\n            }\n\n            // Assert\n            Assert.Equal((int)HttpStatusCode.InternalServerError, responseBase.StatusCode);\n            Assert.StartsWith(JsonMediaTypeFormatter.DefaultMediaType.MediaType, responseBase.Headers[\"Content-Type\"]);\n            Assert.Equal(\"An error has occurred.\", httpError[\"Message\"]);\n            Assert.Equal(\"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.\", httpError[\"ExceptionMessage\"]);\n            Assert.Equal(typeof(InvalidOperationException).FullName, httpError[\"ExceptionType\"]);\n            Assert.True(httpError.ContainsKey(\"StackTrace\"));\n\n            HttpError innerError = (httpError[\"InnerException\"] as JObject).ToObject<HttpError>();\n            Assert.NotNull(innerError);\n            Assert.Equal(typeof(NotSupportedException).FullName, innerError[\"ExceptionType\"].ToString());\n            Assert.Equal(\"Expected error\", innerError[\"ExceptionMessage\"]);\n            Assert.Contains(MethodInfo.GetCurrentMethod().Name, innerError[\"StackTrace\"].ToString());\n        }\n\n        [Fact]\n        public async Task CopyResponseAsync_IfHandlerIsDefault_Returns_Error_Response_When_Formatter_Write_Throws_Immediately()\n        {\n            // Arrange\n            Mock<JsonMediaTypeFormatter> formatterMock = new Mock<JsonMediaTypeFormatter>() { CallBase = true };\n            formatterMock.Setup(m => m.WriteToStreamAsync(It.IsAny<Type>(),\n                                                          It.IsAny<object>(),\n                                                          It.IsAny<Stream>(),\n                                                          It.IsAny<HttpContent>(),\n                                                          It.IsAny<TransportContext>())).Throws(new NotSupportedException(\"Expected error\"));\n\n            MemoryStream memoryStream = new MemoryStream();\n            Mock<HttpContextBase> contextMock = CreateMockHttpContextBaseForResponse(memoryStream);\n            HttpResponseBase responseBase = contextMock.Object.Response;\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.SetIsLocal(new Lazy<bool>(() => true));\n            HttpResponseMessage response = new HttpResponseMessage() { RequestMessage = request };\n            response.Content = new ObjectContent<string>(\"hello\", formatterMock.Object);\n            IExceptionLogger exceptionLogger = CreateStubExceptionLogger();\n            IExceptionHandler exceptionHandler = ExceptionServices.GetHandler(GlobalConfiguration.Configuration);\n\n            // Act\n            await HttpControllerHandler.CopyResponseAsync(contextMock.Object, request, response, exceptionLogger, exceptionHandler, CancellationToken.None);\n\n            // Assert preparation -- deserialize the HttpError response\n            HttpError httpError = null;\n            memoryStream.Seek(0L, SeekOrigin.Begin);\n            using (StreamContent content = new StreamContent(memoryStream))\n            {\n                content.Headers.ContentType = JsonMediaTypeFormatter.DefaultMediaType;\n                httpError = await content.ReadAsAsync<HttpError>();\n            }\n\n            // Assert\n            Assert.Equal((int)HttpStatusCode.InternalServerError, responseBase.StatusCode);\n            Assert.StartsWith(JsonMediaTypeFormatter.DefaultMediaType.MediaType, responseBase.Headers[\"Content-Type\"]);\n            Assert.Equal(\"An error has occurred.\", httpError[\"Message\"]);\n            Assert.Equal(\"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.\", httpError[\"ExceptionMessage\"]);\n            Assert.Equal(typeof(InvalidOperationException).FullName, httpError[\"ExceptionType\"]);\n            Assert.True(httpError.ContainsKey(\"StackTrace\"));\n\n            HttpError innerError = (httpError[\"InnerException\"] as JObject).ToObject<HttpError>();\n            Assert.NotNull(innerError);\n            Assert.Equal(typeof(NotSupportedException).FullName, innerError[\"ExceptionType\"].ToString());\n            Assert.Equal(\"Expected error\", innerError[\"ExceptionMessage\"]);\n            Assert.Contains(\"System.Net.Http.HttpContent.CopyToAsync\", innerError[\"StackTrace\"].ToString());\n        }\n\n        [Fact]\n        public async Task CopyResponseAsync_Returns_User_Response_When_Formatter_Write_Throws_HttpResponseException_With_No_Content()\n        {\n            // Arrange\n            HttpResponseMessage errorResponse = new HttpResponseMessage(HttpStatusCode.MethodNotAllowed);\n            errorResponse.Headers.Add(\"myHeader\", \"myValue\");\n\n            Mock<JsonMediaTypeFormatter> formatterMock = new Mock<JsonMediaTypeFormatter>() { CallBase = true };\n            formatterMock.Setup(m => m.WriteToStreamAsync(It.IsAny<Type>(),\n                                                          It.IsAny<object>(),\n                                                          It.IsAny<Stream>(),\n                                                          It.IsAny<HttpContent>(),\n                                                          It.IsAny<TransportContext>())).Throws(new HttpResponseException(errorResponse));\n\n            MemoryStream memoryStream = new MemoryStream();\n            Mock<HttpContextBase> contextMock = CreateMockHttpContextBaseForResponse(memoryStream);\n            HttpResponseBase responseBase = contextMock.Object.Response;\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.SetIsLocal(new Lazy<bool>(() => true));\n            HttpResponseMessage response = new HttpResponseMessage() { RequestMessage = request };\n            response.Content = new ObjectContent<string>(\"hello\", formatterMock.Object);\n\n            // Act\n            await CopyResponseAsync(contextMock.Object, request, response);\n            memoryStream.Seek(0L, SeekOrigin.Begin);\n\n            // Assert\n            Assert.Equal((int)errorResponse.StatusCode, responseBase.StatusCode);\n            Assert.Equal(0, memoryStream.Length);\n            Assert.Equal(\"myValue\", responseBase.Headers[\"myHeader\"]);\n            Assert.Null(responseBase.Headers[\"Content-Type\"]);\n        }\n\n        [Fact]\n        public async Task CopyResponseAsync_Returns_User_Response_When_Formatter_Write_Throws_HttpResponseException_With_Content()\n        {\n            // Arrange\n            HttpResponseMessage errorResponse = new HttpResponseMessage(HttpStatusCode.MethodNotAllowed);\n            errorResponse.Headers.Add(\"myHeader\", \"myValue\");\n            errorResponse.Content = new StringContent(\"user message\", Encoding.UTF8, \"application/fake\");\n\n            Mock<JsonMediaTypeFormatter> formatterMock = new Mock<JsonMediaTypeFormatter>() { CallBase = true };\n            formatterMock.Setup(m => m.WriteToStreamAsync(It.IsAny<Type>(),\n                                                          It.IsAny<object>(),\n                                                          It.IsAny<Stream>(),\n                                                          It.IsAny<HttpContent>(),\n                                                          It.IsAny<TransportContext>())).Throws(new HttpResponseException(errorResponse));\n\n            MemoryStream memoryStream = new MemoryStream();\n            Mock<HttpContextBase> contextMock = CreateMockHttpContextBaseForResponse(memoryStream);\n            HttpResponseBase responseBase = contextMock.Object.Response;\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.SetIsLocal(new Lazy<bool>(() => true));\n            HttpResponseMessage response = new HttpResponseMessage() { RequestMessage = request };\n            response.Content = new ObjectContent<string>(\"hello\", formatterMock.Object);\n\n            // Act\n            await CopyResponseAsync(contextMock.Object, request, response);\n\n            // Assert preparation -- deserialize the response\n\n            memoryStream.Seek(0L, SeekOrigin.Begin);\n            string responseContent = null;\n            using (var streamReader = new StreamReader(memoryStream))\n            {\n                responseContent = streamReader.ReadToEnd();\n            }\n\n            // Assert\n            Assert.Equal((int)errorResponse.StatusCode, responseBase.StatusCode);\n            Assert.StartsWith(\"application/fake\", responseBase.Headers[\"Content-Type\"]);\n            Assert.Equal(\"user message\", responseContent);\n            Assert.Equal(\"myValue\", responseBase.Headers[\"myHeader\"]);\n        }\n\n        [Fact]\n        public async Task CopyResponseAsync_Returns_InternalServerError_And_No_Content_When_Formatter_Write_Task_Faults_During_Error_Response()\n        {\n            // Arrange\n            Mock<JsonMediaTypeFormatter> formatterMock = new Mock<JsonMediaTypeFormatter>() { CallBase = true };\n            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();\n            tcs.SetException(new NotSupportedException(\"Expected error\"));\n\n            // This formatter throws on any write attempt\n            formatterMock.Setup(m => m.WriteToStreamAsync(It.IsAny<Type>(),\n                                                            It.IsAny<object>(),\n                                                            It.IsAny<Stream>(),\n                                                            It.IsAny<HttpContent>(),\n                                                            It.IsAny<TransportContext>())).Returns(tcs.Task);\n\n            // Create a local config to hook to the request to condition\n            // the formatter selection for the error response\n            HttpConfiguration config = new HttpConfiguration();\n            config.Formatters.Clear();\n            config.Formatters.Add(formatterMock.Object);\n\n            MemoryStream memoryStream = new MemoryStream();\n            Mock<HttpContextBase> contextMock = CreateMockHttpContextBaseForResponse(memoryStream);\n            HttpResponseBase responseBase = contextMock.Object.Response;\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.SetIsLocal(new Lazy<bool>(() => true));\n            request.SetConfiguration(config);\n            HttpResponseMessage response = new HttpResponseMessage() { RequestMessage = request };\n            response.Content = new ObjectContent<string>(\"hello\", formatterMock.Object);\n            IExceptionLogger exceptionLogger = CreateStubExceptionLogger();\n            IExceptionHandler exceptionHandler = ExceptionServices.GetHandler(GlobalConfiguration.Configuration);\n\n            // Act\n            await HttpControllerHandler.CopyResponseAsync(contextMock.Object, request, response, exceptionLogger,\n                exceptionHandler, CancellationToken.None);\n\n            // Assert\n            Assert.Equal((int)HttpStatusCode.InternalServerError, responseBase.StatusCode);\n            Assert.Equal(0, memoryStream.Length);\n            Assert.Null(responseBase.Headers[\"Content-Type\"]);\n        }\n\n        [Fact]\n        public async Task CopyResponseAsync_Returns_InternalServerError_And_No_Content_When_Formatter_Write_Throws_Immediately_During_Error_Response()\n        {\n            // Arrange\n            Mock<JsonMediaTypeFormatter> formatterMock = new Mock<JsonMediaTypeFormatter>() { CallBase = true };\n\n            // This formatter throws on any write attempt\n            formatterMock.Setup(m => m.WriteToStreamAsync(It.IsAny<Type>(),\n                                                            It.IsAny<object>(),\n                                                            It.IsAny<Stream>(),\n                                                            It.IsAny<HttpContent>(),\n                                                            It.IsAny<TransportContext>())).Throws(new NotSupportedException(\"Expected error\"));\n\n            // Create a local config to hook to the request to condition\n            // the formatter selection for the error response\n            HttpConfiguration config = new HttpConfiguration();\n            config.Formatters.Clear();\n            config.Formatters.Add(formatterMock.Object);\n\n            MemoryStream memoryStream = new MemoryStream();\n            Mock<HttpContextBase> contextMock = CreateMockHttpContextBaseForResponse(memoryStream);\n            HttpResponseBase responseBase = contextMock.Object.Response;\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.SetIsLocal(new Lazy<bool>(() => true));\n            request.SetConfiguration(config);\n            HttpResponseMessage response = new HttpResponseMessage() { RequestMessage = request };\n            response.Content = new ObjectContent<string>(\"hello\", formatterMock.Object);\n            IExceptionLogger exceptionLogger = CreateStubExceptionLogger();\n            IExceptionHandler exceptionHandler = ExceptionServices.GetHandler(GlobalConfiguration.Configuration);\n\n            // Act\n            await HttpControllerHandler.CopyResponseAsync(contextMock.Object, request, response, exceptionLogger,\n                exceptionHandler, CancellationToken.None);\n\n            // Assert\n            Assert.Equal((int)HttpStatusCode.InternalServerError, responseBase.StatusCode);\n            Assert.Equal(0, memoryStream.Length);\n            Assert.Null(responseBase.Headers[\"Content-Type\"]);\n        }\n\n        [Fact]\n        public async Task CopyResponseAsync_Returns_InternalServerError_And_No_Content_When_Content_Negotiation_Cannot_Find_Formatter_For_Error_Response()\n        {\n            // Create a content negotiator that works attempting a normal response but fails when creating the error response.\n            Mock<IContentNegotiator> negotiatorMock = new Mock<IContentNegotiator>() { CallBase = true };\n            negotiatorMock.Setup(m => m.Negotiate(It.IsAny<Type>(), It.IsAny<HttpRequestMessage>(), It.IsAny<IEnumerable<MediaTypeFormatter>>()))\n                .Returns((Type t, HttpRequestMessage r, IEnumerable<MediaTypeFormatter> f) =>\n                    {\n                        ContentNegotiationResult result = t == typeof(HttpError)\n                            ? null\n                            : new ContentNegotiationResult(f.First(), JsonMediaTypeFormatter.DefaultMediaType);\n                        return result;\n                    });\n\n            // Arrange\n            Mock<JsonMediaTypeFormatter> formatterMock = new Mock<JsonMediaTypeFormatter>() { CallBase = true };\n\n            // This formatter throws on any write attempt\n            formatterMock.Setup(m => m.WriteToStreamAsync(It.IsAny<Type>(),\n                                                            It.IsAny<object>(),\n                                                            It.IsAny<Stream>(),\n                                                            It.IsAny<HttpContent>(),\n                                                            It.IsAny<TransportContext>())).Throws(new NotSupportedException(\"Expected error\"));\n\n            // Create a local config to hook to the request to condition\n            // the formatter selection for the error response\n            HttpConfiguration config = new HttpConfiguration();\n            config.Formatters.Clear();\n            config.Formatters.Add(formatterMock.Object);\n            config.Services.Replace(typeof(IContentNegotiator), negotiatorMock.Object);\n\n            MemoryStream memoryStream = new MemoryStream();\n            Mock<HttpContextBase> contextMock = CreateMockHttpContextBaseForResponse(memoryStream);\n            HttpResponseBase responseBase = contextMock.Object.Response;\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.SetIsLocal(new Lazy<bool>(() => true));\n            request.SetConfiguration(config);\n            HttpResponseMessage response = new HttpResponseMessage() { RequestMessage = request };\n            response.Content = new ObjectContent<string>(\"hello\", formatterMock.Object);\n            IExceptionLogger exceptionLogger = CreateStubExceptionLogger();\n            IExceptionHandler exceptionHandler = ExceptionServices.GetHandler(GlobalConfiguration.Configuration);\n\n            // Act\n            await HttpControllerHandler.CopyResponseAsync(contextMock.Object, request, response, exceptionLogger,\n                exceptionHandler, CancellationToken.None);\n\n            // Assert\n            Assert.Equal((int)HttpStatusCode.InternalServerError, responseBase.StatusCode);\n            Assert.Equal(0, memoryStream.Length);\n            Assert.Null(responseBase.Headers[\"Content-Type\"]);\n        }\n\n        [Fact]\n        public async Task CopyResponseAsync_Returns_InternalServerError_And_No_Content_When_No_Content_Negotiator_For_Error_Response()\n        {\n            // Arrange\n            Mock<JsonMediaTypeFormatter> formatterMock = new Mock<JsonMediaTypeFormatter>() { CallBase = true };\n\n            // This formatter throws on any write attempt\n            formatterMock.Setup(m => m.WriteToStreamAsync(It.IsAny<Type>(),\n                                                            It.IsAny<object>(),\n                                                            It.IsAny<Stream>(),\n                                                            It.IsAny<HttpContent>(),\n                                                            It.IsAny<TransportContext>())).Throws(new NotSupportedException(\"Expected error\"));\n\n            // Create a local config to hook to the request to condition\n            // the formatter selection for the error response\n            HttpConfiguration config = new HttpConfiguration();\n            config.Formatters.Clear();\n            config.Formatters.Add(formatterMock.Object);\n            config.Services.Replace(typeof(IContentNegotiator), null /*negotiatorMock.Object*/);\n\n            MemoryStream memoryStream = new MemoryStream();\n            Mock<HttpContextBase> contextMock = CreateMockHttpContextBaseForResponse(memoryStream);\n            HttpResponseBase responseBase = contextMock.Object.Response;\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.SetIsLocal(new Lazy<bool>(() => true));\n            request.SetConfiguration(config);\n            HttpResponseMessage response = new HttpResponseMessage() { RequestMessage = request };\n            response.Content = new ObjectContent<string>(\"hello\", formatterMock.Object);\n            IExceptionLogger exceptionLogger = CreateStubExceptionLogger();\n            IExceptionHandler exceptionHandler = ExceptionServices.GetHandler(GlobalConfiguration.Configuration);\n\n            // Act\n            await HttpControllerHandler.CopyResponseAsync(contextMock.Object, request, response, exceptionLogger,\n                exceptionHandler, CancellationToken.None);\n\n            // Assert\n            Assert.Equal((int)HttpStatusCode.InternalServerError, responseBase.StatusCode);\n            Assert.Equal(0, memoryStream.Length);\n            Assert.Null(responseBase.Headers[\"Content-Type\"]);\n        }\n\n        [Fact]\n        public async Task CopyResponseAsync_Returns_InternalServerError_And_No_Content_For_Null_HttpResponseMessage()\n        {\n            // Arrange\n            MemoryStream memoryStream = new MemoryStream();\n            Mock<HttpContextBase> contextMock = CreateMockHttpContextBaseForResponse(memoryStream);\n            HttpResponseBase responseBase = contextMock.Object.Response;\n            HttpRequestMessage request = new HttpRequestMessage();\n\n            // Act\n            await CopyResponseAsync(contextMock.Object, request: new HttpRequestMessage(), response: null);\n\n            // Assert\n            Assert.Equal((int)HttpStatusCode.InternalServerError, responseBase.StatusCode);\n            Assert.Equal(0, memoryStream.Length);\n            Assert.Null(responseBase.Headers[\"Content-Type\"]);\n        }\n\n        [Fact]\n        public async Task WriteStreamedResponseContentAsync_Aborts_When_Formatter_Write_Throws_Immediately()\n        {\n            // Arrange\n            Mock<JsonMediaTypeFormatter> formatterMock = new Mock<JsonMediaTypeFormatter>() { CallBase = true };\n            formatterMock.Setup(m => m.WriteToStreamAsync(It.IsAny<Type>(),\n                                                          It.IsAny<object>(),\n                                                          It.IsAny<Stream>(),\n                                                          It.IsAny<HttpContent>(),\n                                                          It.IsAny<TransportContext>())).Throws(new NotSupportedException(\"Expected error\"));\n\n            MemoryStream memoryStream = new MemoryStream();\n\n            Mock<HttpRequestBase> requestBaseMock = new Mock<HttpRequestBase>();\n            requestBaseMock.Setup(m => m.Abort()).Verifiable();\n            HttpRequestBase requestBase = requestBaseMock.Object;\n            HttpResponseBase responseBase = CreateMockHttpResponseBaseForResponse(memoryStream).Object;\n            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>() { DefaultValue = DefaultValue.Mock };\n            contextMock.SetupGet(m => m.Response).Returns(responseBase);\n            HttpContextBase contextBase = CreateStubContextBase(requestBase, responseBase);\n\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.SetIsLocal(new Lazy<bool>(() => true));\n            HttpResponseMessage response = new HttpResponseMessage() { RequestMessage = request };\n            response.Content = new ObjectContent<string>(\"hello\", formatterMock.Object);\n\n            // Act\n            await WriteStreamedResponseContentAsync(contextBase, request, response);\n\n            // Assert\n            requestBaseMock.Verify();\n        }\n\n        [Fact]\n        public async Task WriteStreamedResponseContentAsync_Aborts_When_Formatter_Write_Faults()\n        {\n            // Arrange\n            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();\n            tcs.TrySetException(new NotSupportedException(\"Expected error\"));\n\n            Mock<JsonMediaTypeFormatter> formatterMock = new Mock<JsonMediaTypeFormatter>() { CallBase = true };\n            formatterMock.Setup(m => m.WriteToStreamAsync(It.IsAny<Type>(),\n                                                          It.IsAny<object>(),\n                                                          It.IsAny<Stream>(),\n                                                          It.IsAny<HttpContent>(),\n                                                          It.IsAny<TransportContext>())).Returns(tcs.Task);\n\n            MemoryStream memoryStream = new MemoryStream();\n\n            Mock<HttpRequestBase> requestBaseMock = new Mock<HttpRequestBase>();\n            requestBaseMock.Setup(m => m.Abort()).Verifiable();\n            HttpRequestBase requestBase = requestBaseMock.Object;\n            HttpResponseBase responseBase = CreateMockHttpResponseBaseForResponse(memoryStream).Object;\n            HttpContextBase contextBase = CreateStubContextBase(requestBase, responseBase);\n\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.SetIsLocal(new Lazy<bool>(() => true));\n            HttpResponseMessage response = new HttpResponseMessage() { RequestMessage = request };\n            response.Content = new ObjectContent<string>(\"hello\", formatterMock.Object);\n\n            // Act\n            await WriteStreamedResponseContentAsync(contextBase, request, response);\n\n            // Assert\n            requestBaseMock.Verify();\n        }\n\n        [Fact]\n        public async Task WriteStreamedResponseContentAsync_IfCopyToAsyncThrows_CallsExceptionLogger()\n        {\n            // Arrange\n            Exception expectedException = CreateException();\n\n            Mock<IExceptionLogger> mock = new Mock<IExceptionLogger>(MockBehavior.Strict);\n            mock\n                .Setup(l => l.LogAsync(It.IsAny<ExceptionLoggerContext>(), It.IsAny<CancellationToken>()))\n                .Returns(Task.FromResult(0));\n            IExceptionLogger logger = mock.Object;\n\n            using (HttpRequestMessage expectedRequest = new HttpRequestMessage())\n            using (HttpResponseMessage expectedResponse = new HttpResponseMessage())\n            using (CancellationTokenSource tokenSource = new CancellationTokenSource())\n            {\n                expectedResponse.Content = CreateFaultingContent(expectedException);\n\n                HttpRequestBase requestBase = CreateStubRequestBase();\n                HttpResponseBase responseBase = CreateStubResponseBase(Stream.Null);\n                HttpContextBase contextBase = CreateStubContextBase(requestBase, responseBase);\n                CancellationToken expectedCancellationToken = tokenSource.Token;\n\n                // Act\n                await HttpControllerHandler.WriteStreamedResponseContentAsync(contextBase, expectedRequest,\n                    expectedResponse, logger, expectedCancellationToken);\n\n                // Assert\n                mock.Verify(l => l.LogAsync(It.Is<ExceptionLoggerContext>(c =>\n                    c.ExceptionContext != null\n                    && c.ExceptionContext.Exception == expectedException\n                    && c.ExceptionContext.CatchBlock == WebHostExceptionCatchBlocks.HttpControllerHandlerStreamContent\n                    && c.ExceptionContext.Request == expectedRequest\n                    && c.ExceptionContext.Response == expectedResponse\n                    ), expectedCancellationToken), Times.Once());\n            }\n        }\n\n        [Fact]\n        public async Task WriteStreamedResponseContentAsync_IfCopyToAsyncCancells_DoesNotCallExceptionLogger()\n        {\n            // Arrange\n            Exception expectedException = new OperationCanceledException();\n\n            Mock<IExceptionLogger> mock = new Mock<IExceptionLogger>(MockBehavior.Strict);\n            IExceptionLogger logger = mock.Object;\n\n            using (HttpRequestMessage expectedRequest = new HttpRequestMessage())\n            using (HttpResponseMessage expectedResponse = new HttpResponseMessage())\n            using (CancellationTokenSource tokenSource = new CancellationTokenSource())\n            {\n                expectedResponse.Content = CreateFaultingContent(expectedException);\n\n                HttpRequestBase requestBase = CreateStubRequestBase();\n                HttpResponseBase responseBase = CreateStubResponseBase(Stream.Null);\n                HttpContextBase contextBase = CreateStubContextBase(requestBase, responseBase);\n                CancellationToken expectedCancellationToken = tokenSource.Token;\n\n                // Act & Assert\n                await Assert.ThrowsAsync<OperationCanceledException>(\n                    () => HttpControllerHandler.WriteStreamedResponseContentAsync(\n                        contextBase,\n                        expectedRequest,\n                        expectedResponse,\n                        logger,\n                        expectedCancellationToken));\n            }\n        }\n\n        [Fact]\n        public async Task WriteBufferedResponseContentAsync_IfCopyToAsyncThrows_CallsExceptionServices()\n        {\n            // Arrange\n            Exception expectedException = CreateException();\n\n            Mock<IExceptionLogger> loggerMock = CreateStubExceptionLoggerMock();\n            IExceptionLogger logger = loggerMock.Object;\n            Mock<IExceptionHandler> handlerMock = CreateStubExceptionHandlerMock();\n            IExceptionHandler handler = handlerMock.Object;\n\n            using (HttpRequestMessage expectedRequest = new HttpRequestMessage())\n            using (HttpResponseMessage expectedResponse = new HttpResponseMessage())\n            using (CancellationTokenSource tokenSource = new CancellationTokenSource())\n            {\n                expectedResponse.Content = CreateFaultingContent(expectedException);\n\n                HttpRequestBase requestBase = CreateStubRequestBase();\n                HttpResponseBase responseBase = CreateStubResponseBase(Stream.Null);\n                HttpContextBase contextBase = CreateStubContextBase(requestBase, responseBase);\n                CancellationToken expectedCancellationToken = tokenSource.Token;\n\n                // Act & Assert\n                await Assert.ThrowsAsync<EncoderFallbackException>(\n                    () => HttpControllerHandler.WriteBufferedResponseContentAsync(\n                        contextBase,\n                        expectedRequest,\n                        expectedResponse,\n                        logger,\n                        handler,\n                        expectedCancellationToken));\n\n                Func<ExceptionContext, bool> exceptionContextMatches = (c) =>\n                    c != null\n                    && c.Exception == expectedException\n                    && c.CatchBlock == WebHostExceptionCatchBlocks.HttpControllerHandlerBufferContent\n                    && c.Request == expectedRequest\n                    && c.Response == expectedResponse;\n\n                loggerMock.Verify(l => l.LogAsync(It.Is<ExceptionLoggerContext>(c =>\n                    exceptionContextMatches(c.ExceptionContext)), expectedCancellationToken), Times.Once());\n                handlerMock.Verify(l => l.HandleAsync(It.Is<ExceptionHandlerContext>(c =>\n                    exceptionContextMatches(c.ExceptionContext)), expectedCancellationToken), Times.Once());\n            }\n        }\n\n        [Fact]\n        public async Task WriteBufferedResponseContentAsync_IfCopyToAsyncCancels_DoesNotCallExceptionServices()\n        {\n            // Arrange\n            Exception expectedException = new OperationCanceledException();\n\n            Mock<IExceptionLogger> loggerMock = new Mock<IExceptionLogger>(MockBehavior.Strict);\n            IExceptionLogger logger = loggerMock.Object;\n            Mock<IExceptionHandler> handlerMock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n            IExceptionHandler handler = handlerMock.Object;\n\n            using (HttpRequestMessage expectedRequest = new HttpRequestMessage())\n            using (HttpResponseMessage expectedResponse = new HttpResponseMessage())\n            using (CancellationTokenSource tokenSource = new CancellationTokenSource())\n            {\n                expectedResponse.Content = CreateFaultingContent(expectedException);\n\n                HttpRequestBase requestBase = CreateStubRequestBase();\n                HttpResponseBase responseBase = CreateStubResponseBase(Stream.Null);\n                HttpContextBase contextBase = CreateStubContextBase(requestBase, responseBase);\n                CancellationToken expectedCancellationToken = tokenSource.Token;\n\n                // Act & Assert\n                await Assert.ThrowsAsync<OperationCanceledException>(\n                    () => HttpControllerHandler.WriteBufferedResponseContentAsync(\n                        contextBase,\n                        expectedRequest,\n                        expectedResponse,\n                        logger,\n                        handler,\n                        expectedCancellationToken));\n            }\n        }\n\n        [Fact]\n        public async Task WriteBufferedResponseContentAsync_IfCopyToAsyncThrowsAndHandlerHandles_ReturnsCompletedTask()\n        {\n            // Arrange\n            HttpStatusCode expectedStatusCode = HttpStatusCode.ExpectationFailed;\n\n            using (HttpRequestMessage request = new HttpRequestMessage())\n            using (HttpResponseMessage response = new HttpResponseMessage())\n            {\n                IExceptionLogger logger = CreateStubExceptionLogger();\n                Mock<IExceptionHandler> handlerMock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n                handlerMock\n                    .Setup(h => h.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                    .Returns<ExceptionHandlerContext, CancellationToken>((c, i) =>\n                    {\n                        c.Result = new StatusCodeResult(expectedStatusCode, request);\n                        return Task.FromResult(0);\n                    });\n                IExceptionHandler handler = handlerMock.Object;\n\n                response.Content = CreateFaultingContent(CreateException());\n\n                int statusCode = 0;\n                HttpRequestBase requestBase = CreateStubRequestBase();\n                Mock<HttpResponseBase> responseBaseMock = new Mock<HttpResponseBase>();\n                responseBaseMock.Setup(r => r.OutputStream).Returns(Stream.Null);\n                responseBaseMock.SetupSet(r => r.StatusCode = It.IsAny<int>()).Callback<int>((c) => statusCode = c);\n                HttpResponseBase responseBase = responseBaseMock.Object;\n                HttpContextBase contextBase = CreateStubContextBase(requestBase, responseBase);\n                CancellationToken expectedCancellationToken = CancellationToken.None;\n\n                // Act\n                await HttpControllerHandler.WriteBufferedResponseContentAsync(contextBase, request,\n                    response, logger, handler, expectedCancellationToken);\n\n                // Assert\n                Assert.Equal((int)expectedStatusCode, statusCode);\n            }\n        }\n\n        [Fact]\n        public async Task WriteBufferedResponseContentAsync_IfCopyToAsyncThrowsAndHandlerDoesNotHandle_PropagatesFault()\n        {\n            // Arrange\n            Exception expectedException = CreateExceptionWithCallStack();\n            string expectedStackTrace = expectedException.StackTrace;\n\n            using (HttpRequestMessage request = new HttpRequestMessage())\n            using (HttpResponseMessage response = new HttpResponseMessage())\n            {\n                IExceptionLogger logger = CreateStubExceptionLogger();\n                IExceptionHandler handler = CreateStubExceptionHandler();\n\n                response.Content = CreateFaultingContent(expectedException);\n\n                HttpRequestBase requestBase = CreateStubRequestBase();\n                HttpResponseBase responseBase = CreateStubResponseBase(Stream.Null);\n                HttpContextBase contextBase = CreateStubContextBase(requestBase, responseBase);\n                CancellationToken expectedCancellationToken = CancellationToken.None;\n\n                // Act & Assert\n                var exception = await Assert.ThrowsAsync<EncoderFallbackException>(\n                    () => HttpControllerHandler.WriteBufferedResponseContentAsync(\n                        contextBase,\n                        request,\n                        response,\n                        logger,\n                        handler,\n                        expectedCancellationToken));\n\n                Assert.Same(expectedException, exception);\n                Assert.NotNull(exception.StackTrace);\n                Assert.StartsWith(expectedStackTrace, exception.StackTrace);\n            }\n        }\n\n        [Fact]\n        public async Task WriteBufferedResponseContentAsync_IfCopyToAsyncOnErrorResponseThrows_CallsExceptionLogger()\n        {\n            // Arrange\n            Exception expectedOriginalException = CreateException();\n            Exception expectedErrorException = CreateException();\n\n            using (HttpRequestMessage expectedRequest = new HttpRequestMessage())\n            using (HttpResponseMessage expectedOriginalResponse = new HttpResponseMessage())\n            using (HttpResponseMessage expectedErrorResponse = new HttpResponseMessage())\n            using (CancellationTokenSource tokenSource = new CancellationTokenSource())\n            {\n                expectedOriginalResponse.Content = CreateFaultingContent(expectedOriginalException);\n                expectedErrorResponse.Content = CreateFaultingContent(expectedErrorException);\n\n                Mock<IExceptionLogger> loggerMock = CreateStubExceptionLoggerMock();\n                IExceptionLogger logger = loggerMock.Object;\n                Mock<IExceptionHandler> handlerMock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n                handlerMock\n                    .Setup(h => h.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                    .Returns<ExceptionHandlerContext, CancellationToken>((c, i) =>\n                    {\n                        c.Result = new ResponseMessageResult(expectedErrorResponse);\n                        return Task.FromResult(0);\n                    });\n                IExceptionHandler handler = handlerMock.Object;\n\n                HttpRequestBase requestBase = CreateStubRequestBase();\n                HttpResponseBase responseBase = CreateStubResponseBase(Stream.Null);\n                HttpContextBase contextBase = CreateStubContextBase(requestBase, responseBase);\n                CancellationToken expectedCancellationToken = tokenSource.Token;\n\n                // Act\n                await HttpControllerHandler.WriteBufferedResponseContentAsync(contextBase, expectedRequest,\n                    expectedOriginalResponse, logger, handler, expectedCancellationToken);\n\n                // Assert\n                loggerMock.Verify(l => l.LogAsync(It.Is<ExceptionLoggerContext>(c =>\n                    c.ExceptionContext != null\n                    && c.ExceptionContext.Exception == expectedOriginalException\n                    && c.ExceptionContext.CatchBlock == WebHostExceptionCatchBlocks.HttpControllerHandlerBufferContent\n                    && c.ExceptionContext.Request == expectedRequest\n                    && c.ExceptionContext.Response == expectedOriginalResponse),\n                    expectedCancellationToken), Times.Once());\n                loggerMock.Verify(l => l.LogAsync(It.Is<ExceptionLoggerContext>(c =>\n                    c.ExceptionContext != null\n                    && c.ExceptionContext.Exception == expectedErrorException\n                    && c.ExceptionContext.CatchBlock == WebHostExceptionCatchBlocks.HttpControllerHandlerBufferError\n                    && c.ExceptionContext.Request == expectedRequest\n                    && c.ExceptionContext.Response == expectedErrorResponse),\n                    expectedCancellationToken), Times.Once());\n            }\n        }\n\n        [Fact]\n        public async Task WriteBufferedResponseContentAsync_IfCopyToAsyncOnErrorResponseCancels_DoesNotCallCallsExceptionLogger()\n        {\n            // Arrange\n            Exception expectedOriginalException = CreateException();\n            Exception expectedErrorException = new OperationCanceledException();\n\n            using (HttpRequestMessage expectedRequest = new HttpRequestMessage())\n            using (HttpResponseMessage expectedOriginalResponse = new HttpResponseMessage())\n            using (HttpResponseMessage expectedErrorResponse = new HttpResponseMessage())\n            using (CancellationTokenSource tokenSource = new CancellationTokenSource())\n            {\n                expectedOriginalResponse.Content = CreateFaultingContent(expectedOriginalException);\n                expectedErrorResponse.Content = CreateFaultingContent(expectedErrorException);\n\n                Mock<IExceptionLogger> loggerMock = CreateStubExceptionLoggerMock();\n                IExceptionLogger logger = loggerMock.Object;\n                Mock<IExceptionHandler> handlerMock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n                handlerMock\n                    .Setup(h => h.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                    .Returns<ExceptionHandlerContext, CancellationToken>((c, i) =>\n                    {\n                        c.Result = new ResponseMessageResult(expectedErrorResponse);\n                        return Task.FromResult(0);\n                    });\n                IExceptionHandler handler = handlerMock.Object;\n\n                HttpRequestBase requestBase = CreateStubRequestBase();\n                HttpResponseBase responseBase = CreateStubResponseBase(Stream.Null);\n                HttpContextBase contextBase = CreateStubContextBase(requestBase, responseBase);\n                CancellationToken expectedCancellationToken = tokenSource.Token;\n\n                // Act & Assert\n                await Assert.ThrowsAsync<OperationCanceledException>(\n                    () => HttpControllerHandler.WriteBufferedResponseContentAsync(\n                        contextBase,\n                        expectedRequest,\n                        expectedOriginalResponse,\n                        logger,\n                        handler,\n                        expectedCancellationToken));\n\n                loggerMock.Verify(l => l.LogAsync(It.Is<ExceptionLoggerContext>(c =>\n                    c.ExceptionContext != null\n                    && c.ExceptionContext.Exception == expectedOriginalException\n                    && c.ExceptionContext.CatchBlock == WebHostExceptionCatchBlocks.HttpControllerHandlerBufferContent\n                    && c.ExceptionContext.Request == expectedRequest\n                    && c.ExceptionContext.Response == expectedOriginalResponse),\n                    expectedCancellationToken), Times.Once());\n                loggerMock.Verify(l => l.LogAsync(It.Is<ExceptionLoggerContext>(c =>\n                    c.ExceptionContext != null\n                    && c.ExceptionContext.Exception == expectedErrorException\n                    && c.ExceptionContext.CatchBlock == WebHostExceptionCatchBlocks.HttpControllerHandlerBufferError\n                    && c.ExceptionContext.Request == expectedRequest\n                    && c.ExceptionContext.Response == expectedErrorResponse),\n                    expectedCancellationToken), Times.Never());\n            }\n        }\n\n        [Fact]\n        public async Task PrepareHeadersAsync_IfTryComputeLengthThrows_CallsExceptionLogger()\n        {\n            // Arrange\n            HttpResponseBase responseBase = CreateStubResponseBase();\n            Exception expectedException = CreateException();\n\n            using (HttpRequestMessage expectedRequest = new HttpRequestMessage())\n            using (HttpResponseMessage expectedResponse = new HttpResponseMessage())\n            using (CancellationTokenSource tokenSource = new CancellationTokenSource())\n            {\n                expectedResponse.Content = CreateThrowingContent(expectedException);\n\n                Mock<IExceptionLogger> loggerMock = CreateStubExceptionLoggerMock();\n                IExceptionLogger logger = loggerMock.Object;\n\n                CancellationToken expectedCancellationToken = tokenSource.Token;\n\n                // Act\n                await HttpControllerHandler.PrepareHeadersAsync(responseBase, expectedRequest, expectedResponse,\n                    logger, expectedCancellationToken);\n\n                // Assert\n                loggerMock.Verify(l => l.LogAsync(It.Is<ExceptionLoggerContext>(c =>\n                    c.ExceptionContext != null\n                    && c.ExceptionContext.Exception == expectedException\n                    && c.ExceptionContext.CatchBlock == WebHostExceptionCatchBlocks.HttpControllerHandlerComputeContentLength\n                    && c.ExceptionContext.Request == expectedRequest\n                    && c.ExceptionContext.Response == expectedResponse),\n                    expectedCancellationToken), Times.Once());\n            }\n        }\n\n        [Fact]\n        public async Task PrepareHeadersAsync_IfTryComputeLengthThrows_SetsEmptyErrorResponseAndReturnsFalse()\n        {\n            // Arrange\n            Mock<HttpResponseBase> responseBaseMock = new Mock<HttpResponseBase>(MockBehavior.Strict);\n            responseBaseMock.Setup(r => r.Clear());\n            responseBaseMock.Setup(r => r.ClearHeaders());\n            int statusCode = 0;\n            responseBaseMock.SetupSet((r) => r.StatusCode = It.IsAny<int>()).Callback<int>((s) => statusCode = s);\n            bool suppressContent = false;\n            responseBaseMock.SetupSet((r) => r.SuppressContent = It.IsAny<bool>()).Callback<bool>((s) => suppressContent = s);\n            HttpResponseBase responseBase = responseBaseMock.Object;\n\n            using (HttpRequestMessage request = new HttpRequestMessage())\n            using (HttpResponseMessage response = new HttpResponseMessage())\n            {\n                response.Content = CreateThrowingContent(CreateException());\n                IExceptionLogger logger = CreateStubExceptionLogger();\n                CancellationToken cancellationToken = CancellationToken.None;\n\n                // Act\n                bool result = await HttpControllerHandler.PrepareHeadersAsync(responseBase, request, response, logger,\n                    cancellationToken);\n\n                // Assert\n                responseBaseMock.Verify(r => r.Clear(), Times.Once());\n                responseBaseMock.Verify(r => r.ClearHeaders(), Times.Once());\n                Assert.Equal(500, statusCode);\n                Assert.True(suppressContent);\n                Assert.False(result);\n            }\n        }\n\n        [Fact]\n        public async Task GetBufferedStream_ReadAsString_GetsSeekableInputStream()\n        {\n            // Arrange\n            using (MemoryStream nonSeekable = new MemoryStream())\n            using (MemoryStream seekable = new MemoryStream())\n            {\n                var request = CreateStubRequestBaseMock(\"IgnoreMethod\", nonSeekable, seekable);\n                var context = CreateStubContextBase(request.Object);\n\n                using (HttpRequestMessage actualRequest = HttpControllerHandler.ConvertRequest(context))\n                {\n                    // Guard\n                    request.Verify(r => r.GetBufferedInputStream(), Times.Never());\n                    request.Verify(r => r.InputStream, Times.Never());\n\n                    // Act\n                    var content = await actualRequest.Content.ReadAsStringAsync();\n\n                    // Assert\n                    request.Verify(r => r.GetBufferedInputStream(), Times.Once());\n                    request.Verify(r => r.InputStream, Times.Once());\n                }\n            }\n        }\n\n        [Fact]\n        public async Task GetBufferedStream_ReadAsStream_DoesNotGetSeekableInputStream()\n        {\n            // Arrange\n            using (MemoryStream nonSeekable = new MemoryStream())\n            using (MemoryStream seekable = new MemoryStream())\n            {\n                var request = CreateStubRequestBaseMock(\"IgnoreMethod\", nonSeekable, seekable);\n                var context = CreateStubContextBase(request.Object);\n\n                using (HttpRequestMessage actualRequest = HttpControllerHandler.ConvertRequest(context))\n                {\n                    // Guard\n                    request.Verify(r => r.GetBufferedInputStream(), Times.Never());\n                    request.Verify(r => r.InputStream, Times.Never());\n\n                    // Act\n                    var stream = await actualRequest.Content.ReadAsStreamAsync();\n\n                    // Assert\n                    request.Verify(r => r.GetBufferedInputStream(), Times.Once());\n                    request.Verify(r => r.InputStream, Times.Never());\n                }\n            }\n        }\n\n        [Fact]\n        public async Task GetBufferedStream_ReadAsStream_ThenSeek_GetsSeekableInputStream()\n        {\n            // Arrange\n            string content = \"Hello, World!\";\n            using (MemoryStream nonSeekable = new MemoryStream(Encoding.UTF8.GetBytes(content)))\n            using (MemoryStream seekable = new MemoryStream(Encoding.UTF8.GetBytes(content)))\n            {\n                var request = CreateStubRequestBaseMock(\"IgnoreMethod\", nonSeekable, seekable);\n                var context = CreateStubContextBase(request.Object);\n\n                using (HttpRequestMessage actualRequest = HttpControllerHandler.ConvertRequest(context))\n                {\n                    var stream = await actualRequest.Content.ReadAsStreamAsync();\n\n                    // Guard\n                    request.Verify(r => r.GetBufferedInputStream(), Times.Once());\n                    request.Verify(r => r.InputStream, Times.Never());\n\n                    // Act\n                    stream.Seek(1L, SeekOrigin.Begin);\n\n                    // Assert\n                    request.Verify(r => r.GetBufferedInputStream(), Times.Once());\n                    request.Verify(r => r.InputStream, Times.Once());\n                }\n            }\n        }\n\n        [Fact]\n        public async Task GetBufferedStream_EndToEnd_ReadContentTwice()\n        {\n            // Arrange\n            string content = \"Hello, World!\";\n            using (MemoryStream nonSeekable = new MemoryStream(Encoding.UTF8.GetBytes(content)))\n            using (MemoryStream seekable = new MemoryStream(Encoding.UTF8.GetBytes(content)))\n            {\n                var request = CreateStubRequestBaseMock(\"IgnoreMethod\", nonSeekable, seekable);\n                var context = CreateStubContextBase(request.Object);\n\n                using (HttpRequestMessage actualRequest = HttpControllerHandler.ConvertRequest(context))\n                {\n                    // Act\n                    var actual1 = await actualRequest.Content.ReadAsStringAsync();\n                    var actual2 = await actualRequest.Content.ReadAsStringAsync();\n\n                    // Assert\n                    Assert.Equal(content, actual1);\n                    Assert.Equal(content, actual2);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task GetBufferedStream_EndToEnd_ReadContentThenSeekThenRead()\n        {\n            // Arrange\n            string content = \"Hello, World!\";\n            using (MemoryStream nonSeekable = new MemoryStream(Encoding.UTF8.GetBytes(content)))\n            using (MemoryStream seekable = new MemoryStream(Encoding.UTF8.GetBytes(content)))\n            {\n                var request = CreateStubRequestBaseMock(\"IgnoreMethod\", nonSeekable, seekable);\n                var context = CreateStubContextBase(request.Object);\n\n                using (HttpRequestMessage actualRequest = HttpControllerHandler.ConvertRequest(context))\n                {\n                    // Act\n                    var actual1 = await actualRequest.Content.ReadAsStringAsync();\n\n                    var stream = await actualRequest.Content.ReadAsStreamAsync();\n                    stream.Seek(0, SeekOrigin.Begin);\n\n                    string actual2;\n                    using (var reader = new StreamReader(stream))\n                    {\n                        actual2 = await reader.ReadToEndAsync();\n                    }\n\n                    // Assert\n                    Assert.Equal(content, actual1);\n                    Assert.Equal(content, actual2);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task GetBufferedStream_EndToEnd_SeekThenRead()\n        {\n            // Arrange\n            string content = \"Hello, World!\";\n            using (MemoryStream nonSeekable = new MemoryStream(Encoding.UTF8.GetBytes(content)))\n            using (MemoryStream seekable = new MemoryStream(Encoding.UTF8.GetBytes(content)))\n            {\n                var request = CreateStubRequestBaseMock(\"IgnoreMethod\", nonSeekable, seekable);\n                var context = CreateStubContextBase(request.Object);\n\n                using (HttpRequestMessage actualRequest = HttpControllerHandler.ConvertRequest(context))\n                {\n                    // Act\n                    var stream = await actualRequest.Content.ReadAsStreamAsync();\n                    stream.Seek(1L, SeekOrigin.Begin);\n                    stream.Seek(0L, SeekOrigin.Begin);\n\n                    var actual = await actualRequest.Content.ReadAsStringAsync();\n\n                    // Assert\n                    Assert.Equal(content, actual);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task ProcessRequestAsync_Cancels_AbortsRequest()\n        {\n            // Arrange\n            var request = CreateStubRequestBaseMock(\"Ignore\", new MemoryStream(), new MemoryStream());\n            request.Setup(r => r.Abort()).Verifiable();\n\n            var context = CreateStubContextBase(request.Object);\n\n            var messageHandler = new LambdaHttpMessageHandler((r, ct) => { throw new OperationCanceledException(); });\n\n            var handler = new HttpControllerHandler(new RouteData(), messageHandler);\n\n            // Act\n            await handler.ProcessRequestAsyncCore(context);\n\n            // Assert\n            request.Verify(r => r.Abort(), Times.Once());\n        }\n\n        private static Task CopyResponseAsync(HttpContextBase contextBase, HttpRequestMessage request, HttpResponseMessage response)\n        {\n            IExceptionLogger exceptionLogger = CreateDummyExceptionLogger();\n            IExceptionHandler exceptionHandler = CreateDummyExceptionHandler();\n            CancellationToken cancellationToken = CancellationToken.None;\n\n            return HttpControllerHandler.CopyResponseAsync(contextBase, request, response, exceptionLogger,\n                exceptionHandler, cancellationToken);\n        }\n\n        private static IExceptionHandler CreateDummyExceptionHandler()\n        {\n            return new Mock<IExceptionHandler>(MockBehavior.Strict).Object;\n        }\n\n        private static IExceptionLogger CreateDummyExceptionLogger()\n        {\n            return new Mock<IExceptionLogger>(MockBehavior.Strict).Object;\n        }\n\n        private static Exception CreateException()\n        {\n            return new EncoderFallbackException();\n        }\n\n        private static Exception CreateExceptionWithCallStack()\n        {\n            try\n            {\n                throw CreateException();\n            }\n            catch (Exception exception)\n            {\n                return exception;\n            }\n        }\n\n        private static Task<T> CreateFaultedTask<T>(Exception exception)\n        {\n            TaskCompletionSource<T> source = new TaskCompletionSource<T>();\n            source.SetException(exception);\n            return source.Task;\n        }\n\n        private static HttpContent CreateFaultingContent(Exception exception)\n        {\n            return new FaultingHttpContent(exception);\n        }\n\n        private static HttpContextBase CreateStubContextBase(string httpMethod, Stream bufferedStream)\n        {\n            HttpRequestBase request = CreateStubRequestBase(httpMethod, bufferedStream);\n            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>() { DefaultValue = DefaultValue.Mock };\n            contextMock.SetupGet(m => m.Request).Returns(request);\n            return contextMock.Object;\n        }\n\n        internal static HttpContextBase CreateStubContextBase(HttpRequestBase request)\n        {\n            return CreateStubContextBase(request, new Hashtable());\n        }\n\n        internal static HttpContextBase CreateStubContextBase(HttpRequestBase request, IDictionary items)\n        {\n            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>() { DefaultValue = DefaultValue.Mock };\n            contextMock.SetupGet(m => m.Request).Returns(request);\n            contextMock.SetupGet(m => m.Items).Returns(items);\n            return contextMock.Object;\n        }\n\n        private static HttpContextBase CreateStubContextBase(HttpRequestBase request, HttpResponseBase response)\n        {\n            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>();\n            contextMock.SetupGet(m => m.Request).Returns(request);\n            contextMock.SetupGet(m => m.Response).Returns(response);\n            return contextMock.Object;\n        }\n\n        private static HttpContextBase CreateStubContextBase(HttpResponseBase response)\n        {\n            Mock<HttpContextBase> mock = new Mock<HttpContextBase>(MockBehavior.Strict);\n            mock.SetupGet(m => m.Response).Returns(response);\n            return mock.Object;\n        }\n\n        private static IExceptionHandler CreateStubExceptionHandler()\n        {\n            return CreateStubExceptionHandlerMock().Object;\n        }\n\n        private static Mock<IExceptionHandler> CreateStubExceptionHandlerMock()\n        {\n            Mock<IExceptionHandler> mock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n            mock\n                .Setup(h => h.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                .Returns(Task.FromResult(0));\n            return mock;\n        }\n\n        private static IExceptionLogger CreateStubExceptionLogger()\n        {\n            return CreateStubExceptionLoggerMock().Object;\n        }\n\n        private static Mock<IExceptionLogger> CreateStubExceptionLoggerMock()\n        {\n            Mock<IExceptionLogger> mock = new Mock<IExceptionLogger>(MockBehavior.Strict);\n            mock\n                .Setup(l => l.LogAsync(It.IsAny<ExceptionLoggerContext>(), It.IsAny<CancellationToken>()))\n                .Returns(Task.FromResult(0));\n            return mock;\n        }\n\n        private static HttpRequestBase CreateStubRequestBase()\n        {\n            return new Mock<HttpRequestBase>().Object;\n        }\n\n        private static HttpRequestBase CreateStubRequestBase(string httpMethod, Stream bufferedStream)\n        {\n            return CreateStubRequestBaseMock(httpMethod, bufferedStream, bufferedStream).Object;\n        }\n\n        private static Mock<HttpRequestBase> CreateStubRequestBaseMock(string httpMethod, Stream nonSeekableStream, Stream seekableStream)\n        {\n            Mock<HttpRequestBase> requestBaseMock = new Mock<HttpRequestBase>() { CallBase = true };\n            requestBaseMock.SetupGet(m => m.HttpMethod).Returns(httpMethod);\n            requestBaseMock.SetupGet(m => m.Url).Returns(new Uri(\"Http://localhost\"));\n            requestBaseMock.SetupGet(m => m.Headers).Returns(new NameValueCollection());\n            requestBaseMock.SetupGet(m => m.ReadEntityBodyMode).Returns(ReadEntityBodyMode.None);\n\n            requestBaseMock.Setup(m => m.GetBufferedInputStream()).Returns(nonSeekableStream).Verifiable();\n            requestBaseMock.SetupGet(m => m.InputStream).Returns(seekableStream).Verifiable();\n\n            requestBaseMock.Setup(m => m.GetBufferlessInputStream()).Throws<InvalidOperationException>();\n\n            return requestBaseMock;\n        }\n\n        internal static HttpRequestBase CreateFakeRequestBase(Func<Stream> getStream, bool buffered)\n        {\n            var readEntityBodyMode = ReadEntityBodyMode.None;\n            Mock<HttpRequestBase> requestBaseMock = new Mock<HttpRequestBase>() { CallBase = true };\n            requestBaseMock.SetupGet(m => m.HttpMethod).Returns(\"GET\");\n            requestBaseMock.SetupGet(m => m.Url).Returns(new Uri(\"Http://localhost\"));\n            requestBaseMock.SetupGet(m => m.Headers).Returns(new NameValueCollection());\n            requestBaseMock.Setup(r => r.ReadEntityBodyMode).Returns(() => readEntityBodyMode);\n\n            requestBaseMock.Setup(m => m.GetBufferedInputStream()).Returns(() =>\n            {\n                if (readEntityBodyMode == ReadEntityBodyMode.None || readEntityBodyMode == ReadEntityBodyMode.Buffered)\n                {\n                    readEntityBodyMode = ReadEntityBodyMode.Buffered;\n                    return getStream();\n                }\n                throw new InvalidOperationException();\n            });\n\n            requestBaseMock.SetupGet(m => m.InputStream).Returns(() =>\n            {\n                if (readEntityBodyMode == ReadEntityBodyMode.None || readEntityBodyMode == ReadEntityBodyMode.Classic)\n                {\n                    readEntityBodyMode = ReadEntityBodyMode.Classic;\n                    return getStream();\n                }\n                else if (readEntityBodyMode == ReadEntityBodyMode.Buffered)\n                {\n                    Stream stream = getStream();\n                    if (stream.Position == stream.Length)\n                    {\n                        return stream;\n                    }\n                }\n                throw new InvalidOperationException();\n            });\n\n            requestBaseMock.Setup(m => m.GetBufferlessInputStream()).Returns(() =>\n            {\n                if (readEntityBodyMode == ReadEntityBodyMode.None || readEntityBodyMode == ReadEntityBodyMode.Bufferless)\n                {\n                    readEntityBodyMode = ReadEntityBodyMode.Bufferless;\n                    return getStream();\n                }\n                throw new InvalidOperationException();\n            });\n            return requestBaseMock.Object;\n        }\n\n        private static HttpResponseBase CreateStubResponseBase()\n        {\n            return new Mock<HttpResponseBase>().Object;\n        }\n\n        private static HttpResponseBase CreateStubResponseBase(Stream outputStream)\n        {\n            Mock<HttpResponseBase> responseBaseMock = new Mock<HttpResponseBase>();\n            responseBaseMock.Setup(r => r.OutputStream).Returns(outputStream);\n            return responseBaseMock.Object;\n        }\n\n        private static Mock<HttpResponseBase> CreateMockHttpResponseBaseForResponse(Stream outputStream)\n        {\n            NameValueCollection testHeaders = new NameValueCollection();\n\n            Mock<HttpResponseBase> responseBaseMock = new Mock<HttpResponseBase>() { DefaultValue = DefaultValue.Mock };\n            responseBaseMock.Setup(m => m.OutputStream).Returns(outputStream);\n            responseBaseMock.Setup(m => m.Headers).Returns(testHeaders);\n            responseBaseMock.Setup(m => m.AppendHeader(It.IsAny<string>(), It.IsAny<string>())).Callback<string, string>((s, v) => testHeaders.Add(s, v));\n            responseBaseMock.Setup(m => m.ClearHeaders()).Callback(() => testHeaders.Clear());\n            responseBaseMock.Setup(m => m.Clear()).Callback(() => testHeaders.Clear());\n            responseBaseMock.SetupProperty(m => m.StatusCode);\n            responseBaseMock.SetupProperty(m => m.BufferOutput);\n\n            return responseBaseMock;\n        }\n\n        private static Mock<HttpContextBase> CreateMockHttpContextBaseForResponse(Stream outputStream)\n        {\n            NameValueCollection testHeaders = new NameValueCollection();\n\n            Mock<HttpResponseBase> responseBaseMock = CreateMockHttpResponseBaseForResponse(outputStream);\n            HttpResponseBase responseBase = responseBaseMock.Object;\n            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>() { DefaultValue = DefaultValue.Mock };\n            contextMock.SetupGet(m => m.Response).Returns(responseBase);\n\n            return contextMock;\n        }\n\n        private static HttpContent CreateThrowingContent(Exception exception)\n        {\n            return new ThrowingHttpContent(exception);\n        }\n\n        private static Task WriteStreamedResponseContentAsync(HttpContextBase contextBase, HttpRequestMessage request,\n            HttpResponseMessage response)\n        {\n            IExceptionLogger exceptionLogger = CreateStubExceptionLogger();\n            CancellationToken cancellationToken = CancellationToken.None;\n\n            return HttpControllerHandler.WriteStreamedResponseContentAsync(contextBase, request, response,\n                exceptionLogger, cancellationToken);\n        }\n\n        private class FaultingHttpContent : HttpContent\n        {\n            private readonly Exception _exception;\n\n            public FaultingHttpContent(Exception exception)\n            {\n                Contract.Assert(exception != null);\n                _exception = exception;\n            }\n\n            protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)\n            {\n                return CreateFaultedTask<object>(_exception);\n            }\n\n            protected override bool TryComputeLength(out long length)\n            {\n                length = 0;\n                return false;\n            }\n        }\n\n        private class LambdaHttpMessageHandler : HttpMessageHandler\n        {\n            private readonly Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> _sendAsync;\n\n            public LambdaHttpMessageHandler(\n                Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> sendAsync)\n            {\n                Contract.Assert(sendAsync != null);\n                _sendAsync = sendAsync;\n            }\n\n            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n            {\n                return _sendAsync.Invoke(request, cancellationToken);\n            }\n        }\n\n        private sealed class SpyDisposable : IDisposable\n        {\n            public bool Disposed { get; private set; }\n\n            public void Dispose()\n            {\n                Disposed = true;\n            }\n        }\n\n        private class ThrowingHttpContent : HttpContent\n        {\n            private readonly Exception _exception;\n\n            public ThrowingHttpContent(Exception exception)\n            {\n                Contract.Assert(exception != null);\n                _exception = exception;\n\n            }\n            protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)\n            {\n                throw _exception;\n            }\n\n            protected override bool TryComputeLength(out long length)\n            {\n                throw _exception;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.WebHost.Test/HttpRequestMessageExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Web.Http.Hosting;\n\nnamespace System.Web.Http\n{\n    internal static class HttpRequestMessageExtensions\n    {\n        public static void SetIsLocal(this HttpRequestMessage request, Lazy<bool> isLocal)\n        {\n            if (request == null)\n            {\n                throw new ArgumentNullException(\"request\");\n            }\n\n            request.Properties[HttpPropertyKeys.IsLocalKey] = isLocal;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.WebHost.Test/Properties/AssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\n\n[assembly: CLSCompliant(false)]\n"
  },
  {
    "path": "test/System.Web.Http.WebHost.Test/RouteCollectionExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http\n{\n    public class RouteCollectionExtensionsTest\n    {\n        [Fact]\n        public void IsCorrectType()\n        {\n            Assert.Type.HasProperties(typeof(RouteCollectionExtensions), TypeAssert.TypeProperties.IsStatic | TypeAssert.TypeProperties.IsPublicVisibleClass);\n        }\n\n        [Fact]\n        public void MapHttpRoute1ThrowsOnNullRouteCollection()\n        {\n            Assert.ThrowsArgumentNull(() => RouteCollectionExtensions.MapHttpRoute(null, \"\", \"\", null), \"routes\");\n        }\n\n        [Fact]\n        public void MapHttpRoute1CreatesRoute()\n        {\n            // Arrange\n            RouteCollection routes = new RouteCollection();\n            object defaults = new { d1 = \"D1\" };\n\n            // Act\n            Route route = routes.MapHttpRoute(\"name\", \"template\", defaults);\n\n            // Assert\n            Assert.NotNull(route);\n            Assert.Equal(\"template\", route.Url);\n            Assert.Single(route.Defaults);\n            Assert.Equal(\"D1\", route.Defaults[\"d1\"]);\n            Assert.Same(route, routes[\"name\"]);\n        }\n\n        [Fact]\n        public void MapHttpRoute1WithDefaultsAsDictionaryCreatesRoute()\n        {\n            // Arrange\n            RouteCollection routes = new RouteCollection();\n            object defaults = new Dictionary<string, object> { { \"d1\", \"D1\" } };\n\n            // Act\n            Route route = routes.MapHttpRoute(\"name\", \"template\", defaults);\n\n            // Assert\n            Assert.NotNull(route);\n            Assert.Equal(\"template\", route.Url);\n            Assert.Single(route.Defaults);\n            Assert.Equal(\"D1\", route.Defaults[\"d1\"]);\n            Assert.Same(route, routes[\"name\"]);\n        }\n\n        [Fact]\n        public void MapHttpRoute2ThrowsOnNullRouteCollection()\n        {\n            Assert.ThrowsArgumentNull(() => RouteCollectionExtensions.MapHttpRoute(null, \"\", \"\", null, null), \"routes\");\n        }\n\n        [Fact]\n        public void MapHttpRoute2CreatesRoute()\n        {\n            // Arrange\n            RouteCollection routes = new RouteCollection();\n            object defaults = new { d1 = \"D1\" };\n            object constraints = new { c1 = \"C1\" };\n\n            // Act\n            Route route = routes.MapHttpRoute(\"name\", \"template\", defaults, constraints);\n\n            // Assert\n            Assert.NotNull(route);\n            Assert.Equal(\"template\", route.Url);\n            Assert.Single(route.Defaults);\n            Assert.Equal(\"D1\", route.Defaults[\"d1\"]);\n            Assert.Single(route.Constraints);\n            Assert.Equal(\"C1\", route.Constraints[\"c1\"]);\n            Assert.Same(route, routes[\"name\"]);\n        }\n\n        [Fact]\n        public void MapHttpRoute2WithDefaultsAndConstraintsAsDictionaryCreatesRoute()\n        {\n            // Arrange\n            RouteCollection routes = new RouteCollection();\n            object defaults = new Dictionary<string, object> { { \"d1\", \"D1\" } };\n            object constraints = new Dictionary<string, object> { { \"c1\", \"C1\" } };\n\n            // Act\n            Route route = routes.MapHttpRoute(\"name\", \"template\", defaults, constraints);\n\n            // Assert\n            Assert.NotNull(route);\n            Assert.Equal(\"template\", route.Url);\n            Assert.Single(route.Defaults);\n            Assert.Equal(\"D1\", route.Defaults[\"d1\"]);\n            Assert.Single(route.Constraints);\n            Assert.Equal(\"C1\", route.Constraints[\"c1\"]);\n            Assert.Same(route, routes[\"name\"]);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.WebHost.Test/Routing/HostedHttpRouteCollectionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.IO;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Dispatcher;\nusing System.Web.Http.Hosting;\nusing System.Web.Http.Routing;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\nusing Moq.Protected;\n\nnamespace System.Web.Http.WebHost.Routing\n{\n    public class HostedHttpRouteCollectionTest\n    {\n        RouteCollection _aspNetRoutes;\n        HostedHttpRouteCollection _webApiRoutes;\n\n        public HostedHttpRouteCollectionTest()\n        {\n            _aspNetRoutes = new RouteCollection();\n            _webApiRoutes = new HostedHttpRouteCollection(_aspNetRoutes);\n        }\n\n        [Fact]\n        public void Constructor_GuardClauses()\n        {\n            Assert.ThrowsArgumentNull(() => new HostedHttpRouteCollection(routeCollection: null), \"routeCollection\");\n        }\n\n        [Fact]\n        public void Add_WithHostedHttpRoute_RegistersInnerRouteWithAspNetRouteCollection()\n        {\n            var route = new HostedHttpRoute(\"uri\", null, null, null, null);\n\n            _webApiRoutes.Add(\"name\", route);\n\n            var httpWebRoute = Assert.IsType<HttpWebRoute>(_aspNetRoutes[\"name\"]);\n            Assert.Same(route.OriginalRoute, httpWebRoute);\n            Assert.Same(route, httpWebRoute.HttpRoute);\n        }\n\n        [Fact]\n        public void Add_WithNonHostedHttpRoute_WrapsCustomRouteWithHttpWebRoute()\n        {\n            var route = new Mock<IHttpRoute>().Object;\n\n            _webApiRoutes.Add(\"name\", route);\n\n            var httpWebRoute = Assert.IsType<HttpWebRoute>(_aspNetRoutes[\"name\"]);\n            Assert.Same(route, httpWebRoute.HttpRoute);\n        }\n\n        [Fact]\n        public void Clear_RemovesAllValuesFromAspNetRouteCollection()\n        {\n            _aspNetRoutes.Add(new Mock<RouteBase>().Object);\n\n            _webApiRoutes.Clear();\n\n            Assert.Empty(_aspNetRoutes);\n        }\n\n        [Fact]\n        public void Contains_OnlyMatchesRegisteredHttpRouteInstances()\n        {\n            var route = new Mock<IHttpRoute>().Object;\n            _webApiRoutes.Add(\"bar\", route);\n\n            Assert.True(_webApiRoutes.Contains(route));\n            Assert.False(_webApiRoutes.Contains(new Mock<IHttpRoute>().Object));\n        }\n\n        [Fact]\n        public void ContainsKey_MatchesAllRoutesInAspNetRouteCollection()\n        {\n            _aspNetRoutes.Add(\"foo\", new Mock<RouteBase>().Object);\n            _webApiRoutes.Add(\"bar\", new Mock<IHttpRoute>().Object);\n\n            Assert.True(_webApiRoutes.ContainsKey(\"foo\"));\n            Assert.True(_webApiRoutes.ContainsKey(\"bar\"));\n        }\n\n        [Fact]\n        public void Count_ReturnsCountOfAllRoutesInAspNetRouteCollection()\n        {\n            _aspNetRoutes.Add(\"foo\", new Mock<RouteBase>().Object);\n            _webApiRoutes.Add(\"bar\", new Mock<IHttpRoute>().Object);\n\n            Assert.Equal(2, _webApiRoutes.Count);\n        }\n\n        [Fact]\n        public void CreateRoute_CreatesHostedHttpRoute()\n        {\n            var defaults = new HttpRouteValueDictionary { { \"Foo\", \"Bar\" } };\n            var constraints = new HttpRouteValueDictionary { { \"Bar\", \"Baz\" } };\n            var dataTokens = new HttpRouteValueDictionary { { \"Baz\", \"Biff\" } };\n            var handler = new Mock<HttpMessageHandler>().Object;\n\n            IHttpRoute result = _webApiRoutes.CreateRoute(\"uri\", defaults, constraints, dataTokens, handler);\n\n            Assert.IsType<HostedHttpRoute>(result);\n            Assert.Equal(\"Bar\", result.Defaults[\"Foo\"]);\n            Assert.Equal(\"Baz\", result.Constraints[\"Bar\"]);\n            Assert.Equal(\"Biff\", result.DataTokens[\"Baz\"]);\n            Assert.Same(handler, result.Handler);\n        }\n\n        [Fact]\n        public void Enumerating_OnlyIncludesHttpRoutes()\n        {\n            var aspNetRoute = new Mock<RouteBase>().Object;\n            _aspNetRoutes.Add(\"foo\", aspNetRoute);\n            var httpRoute = new Mock<IHttpRoute>().Object;\n            _webApiRoutes.Add(\"bar\", httpRoute);\n\n            List<object> objects = new List<object>(_webApiRoutes);\n\n            Assert.Contains(httpRoute, objects);\n            Assert.DoesNotContain(aspNetRoute, objects);\n        }\n\n        [Fact]\n        public void GetRouteData_GuardClauses()\n        {\n            Assert.ThrowsArgumentNull(() => _webApiRoutes.GetRouteData(request: null), \"request\");\n        }\n\n        [Fact]\n        public void GetRouteData_WithHttpContext_UnmatchedRoute_ReturnsNull()\n        {\n            var request = new HttpRequestMessage();\n            request.SetHttpContext(CreateHttpContext(\"~/api2\"));\n            IHttpRoute route = _webApiRoutes.CreateRoute(\"api\", null, null);\n            _webApiRoutes.Add(\"default\", route);\n\n            IHttpRouteData result = _webApiRoutes.GetRouteData(request);\n\n            Assert.Null(result);\n        }\n\n        [Fact]\n        public void GetRouteData_WithHttpContext_MatchedRoute_ReturnsRouteData()\n        {\n            var request = new HttpRequestMessage();\n            request.SetHttpContext(CreateHttpContext(\"~/api\"));\n            IHttpRoute route = _webApiRoutes.CreateRoute(\"api\", null, null);\n            _webApiRoutes.Add(\"default\", route);\n\n            IHttpRouteData result = _webApiRoutes.GetRouteData(request);\n\n            Assert.Same(route, result.Route);\n        }\n\n        [Fact]\n        public void SendAsync_CallsDefaultHandlerWhenCustomASPNETRoute()\n        {\n            // Arrange\n            var mockHandler = new Mock<HttpMessageHandler>();\n            var config = new HttpConfiguration();\n            var request = new HttpRequestMessage(HttpMethod.Get, \"http://localhost/api/controllerName\");\n            request.SetConfiguration(config);\n            HttpDomainRoute domainRoute = new HttpDomainRoute(\"test\", new { controller = \"Values\", action = \"GetTenant\" });\n            request.SetRouteData(new HostedHttpRouteData(domainRoute.GetRouteData(null)));\n            var dispatcher = new HttpRoutingDispatcher(config, defaultHandler: mockHandler.Object);\n            var invoker = new HttpMessageInvoker(dispatcher);\n\n            // Act\n            invoker.SendAsync(request, CancellationToken.None);\n\n            // Assert\n            mockHandler.Protected().Verify(\"SendAsync\", Times.Once(), request, CancellationToken.None);\n        }\n\n        [Fact]\n        public void GetVirtualPath_GuardClauses()\n        {\n            Assert.ThrowsArgumentNull(() => _webApiRoutes.GetVirtualPath(request: null, name: null, values: null), \"request\");\n        }\n\n        [Fact]\n        public void GetVirtualPath_ReturnsVirtualPathData()\n        {\n            var request = new HttpRequestMessage();\n            request.SetHttpContext(CreateHttpContext(\"~/api\", \"APP PATH MODIFIER RETURN VALUE\"));\n            var config = new HttpConfiguration(_webApiRoutes);\n            IHttpRoute route = _webApiRoutes.CreateRoute(\"api\", null, null);\n            _webApiRoutes.Add(\"default\", route);\n            request.SetRouteData(_webApiRoutes.GetRouteData(request));\n            request.SetConfiguration(config);\n\n            IHttpVirtualPathData result = _webApiRoutes.GetVirtualPath(request, null, new HttpRouteValueDictionary { { \"httproute\", true } });\n\n            Assert.NotNull(result);\n            Assert.Same(route, result.Route);\n            Assert.Equal(\"APP PATH MODIFIER RETURN VALUE\", result.VirtualPath);\n        }\n\n        [Fact]\n        public void Indexer_ForHttpRoute_ReturnsRoute()\n        {\n            var route = new Mock<IHttpRoute>().Object;\n            _webApiRoutes.Add(\"foo\", route);\n\n            var result = _webApiRoutes[\"foo\"];\n\n            Assert.NotNull(result);\n            Assert.Same(route, result);\n        }\n\n        [Fact]\n        public void Indexer_ForAspNetRoute_Throws()\n        {\n            _aspNetRoutes.Add(\"foo\", new Mock<RouteBase>().Object);\n\n            Assert.Throws<KeyNotFoundException>(() => _webApiRoutes[\"foo\"], \"The given key was not present in the dictionary.\");\n        }\n\n        [Fact]\n        public void Indexer_ForUnknownRoute_Throws()\n        {\n            Assert.Throws<KeyNotFoundException>(() => _webApiRoutes[\"foo\"], \"The given key was not present in the dictionary.\");\n        }\n\n        [Fact]\n        public void UnsupportedFunctions()\n        {\n            Assert.Throws<NotSupportedException>(() => _webApiRoutes.CopyTo((IHttpRoute[])null, 0), \"This operation is only supported by directly calling it on 'RouteCollection'.\");\n\n            Assert.Throws<NotSupportedException>(() => _webApiRoutes.CopyTo((KeyValuePair<string, IHttpRoute>[])null, 0), \"This operation is not supported by 'HostedHttpRouteCollection'.\");\n            Assert.Throws<NotSupportedException>(() => _webApiRoutes.Insert(0, null, null), \"This operation is not supported by 'HostedHttpRouteCollection'.\");\n            Assert.Throws<NotSupportedException>(() => _webApiRoutes.Remove(null), \"This operation is not supported by 'HostedHttpRouteCollection'.\");\n        }\n\n        [Fact]\n        public void ConvertHttpRouteDataToRouteDataRunsCustomHttpRoute()\n        {\n            // Arrange\n            DomainHttpRoute route = new DomainHttpRoute(\"myDomain\", \"api/{controller}/{action}\", new { controller = \"Values\", action = \"GetTenant\" });\n            HostedHttpRouteCollection collection = new HostedHttpRouteCollection(new RouteCollection());\n            collection.Add(\"domainRoute\", route);\n            HttpRequestMessage request = CreateHttpRequestMessageWithContext();\n            IHttpRouteData httpRouteData = collection.GetRouteData(request);\n\n            // Act\n            RouteData routeData = httpRouteData.ToRouteData();\n\n            // Assert\n            Assert.NotNull(routeData.Values);\n            Assert.Equal(3, routeData.Values.Count);\n            Assert.Equal(\"controllerName\", routeData.Values[\"controller\"]);\n            Assert.Equal(\"actionName\", routeData.Values[\"action\"]);\n            Assert.Equal(\"myDomain\", routeData.Values[\"domain\"]);\n        }\n\n        [Fact]\n        public void CustomHttpRouteGetVitualPathRunsCustomHttpRoute()\n        {\n            // Arrange\n            DomainHttpRoute route = new DomainHttpRoute(\"myDomain\", \"api/{controller}/{action}\", new { controller = \"SomeValue\", action = \"SomeAction\" });\n            HostedHttpRouteCollection collection = new HostedHttpRouteCollection(new RouteCollection());\n            collection.Add(\"domainRoute\", route);\n            HttpRequestMessage request = CreateHttpRequestMessageWithContext();\n            HttpRouteValueDictionary routeValues = new HttpRouteValueDictionary()\n                {\n                    {\"controller\", \"controllerName\"},\n                    {\"action\", \"actionName\"},\n                    {\"httproute\", true}\n                };\n\n            request.SetRouteData(new HttpRouteData(route, routeValues));\n\n            // Act\n            IHttpVirtualPathData httpvPathData = collection.GetVirtualPath(request, \"domainRoute\", routeValues);\n\n            // Assert\n            Assert.NotNull(httpvPathData);\n            Assert.Equal(\"/api/controllerName/actionNameFromDomain\", httpvPathData.VirtualPath);\n        }\n\n        [Fact]\n        public void IgnoreRoute_GetVirtualPathReturnsNull()\n        {\n            // Arrange\n            DomainHttpRoute route = new DomainHttpRoute(\"myDomain\", \"api/{controller}/{action}\", new { controller = \"SomeValue\", action = \"SomeAction\" });\n            HostedHttpRouteCollection collection = new HostedHttpRouteCollection(new RouteCollection());\n            collection.IgnoreRoute(\"domainRoute\", route.RouteTemplate);\n            HttpRequestMessage request = CreateHttpRequestMessageWithContext();\n            HttpRouteValueDictionary routeValues = new HttpRouteValueDictionary()\n                {\n                    {\"controller\", \"controllerName\"},\n                    {\"action\", \"actionName\"},\n                    {\"httproute\", true}\n                };\n\n            request.SetRouteData(new HttpRouteData(route, routeValues));\n\n            // Act\n            IHttpVirtualPathData httpvPathData = collection.GetVirtualPath(request, \"domainRoute\", routeValues);\n\n            // Assert\n            // Altough it contains the ignore route, GetVirtualPath from the ignored route will always return null.\n            Assert.Equal(1, collection.Count);\n            Assert.Null(httpvPathData);\n        }\n\n        [Theory]\n        [InlineData(\"people/\")]\n        [InlineData(\"people/1\")]\n        [InlineData(\"people/literal\")]\n        [InlineData(\"people/name?id=20\")]\n        public async Task IgnoreRoute_GetSoft404IfRouteIgnored(string requestPath)\n        {\n            var request = CreateHttpRequestMessageWithContext(requestPath);\n\n            var response = await SubmitRequestAsync(request);\n\n            Assert.Equal(Net.HttpStatusCode.NotFound, response.StatusCode);\n            Assert.True(response.RequestMessage.Properties.ContainsKey(HttpPropertyKeys.NoRouteMatched));\n        }\n\n        [Fact]\n        public void CreateRoute_ValidatesConstraintType_IHttpRouteConstraint()\n        {\n            // Arrange\n            var routes = new MockHostedHttpRouteCollection(new RouteCollection());\n\n            var constraint = new CustomHttpConstraint();\n            var constraints = new HttpRouteValueDictionary();\n            constraints.Add(\"custom\", constraint);\n\n            // Act\n            var route = routes.CreateRoute(\"{controller}/{id}\", null, constraints);\n\n            // Assert\n            Assert.NotNull(route.Constraints[\"custom\"]);\n\n            Assert.Equal(1, routes.TimesValidateConstraintCalled);\n        }\n\n        [Fact]\n        public void CreateRoute_ValidatesConstraintType_IRouteConstraint()\n        {\n            // Arrange\n            var routes = new MockHostedHttpRouteCollection(new RouteCollection());\n\n            var constraint = new CustomConstraint();\n            var constraints = new HttpRouteValueDictionary();\n            constraints.Add(\"custom\", constraint);\n\n            // Act\n            var route = routes.CreateRoute(\"{controller}/{id}\", null, constraints);\n\n            // Assert\n            Assert.NotNull(route.Constraints[\"custom\"]);\n            Assert.Equal(1, routes.TimesValidateConstraintCalled);\n        }\n\n        [Fact]\n        public void CreateRoute_ValidatesConstraintType_StringRegex()\n        {\n            // Arrange\n            var routes = new MockHostedHttpRouteCollection(new RouteCollection());\n\n            var constraint = \"product|products\";\n            var constraints = new HttpRouteValueDictionary();\n            constraints.Add(\"custom\", constraint);\n\n            // Act\n            var route = routes.CreateRoute(\"{controller}/{id}\", null, constraints);\n\n            // Assert\n            Assert.NotNull(route.Constraints[\"custom\"]);\n            Assert.Equal(1, routes.TimesValidateConstraintCalled);\n        }\n\n        [Fact]\n        public void CreateRoute_ValidatesConstraintType_InvalidType()\n        {\n            // Arrange\n            var routes = new HostedHttpRouteCollection(new RouteCollection());\n\n            var constraint = new Uri(\"http://localhost/\");\n            var constraints = new HttpRouteValueDictionary();\n            constraints.Add(\"custom\", constraint);\n\n            string expectedMessage =\n                \"The constraint entry 'custom' on the route with route template '{controller}/{id}' \" +\n                \"must have a string value or be of a type which implements 'System.Web.Http.Routing.IHttpRouteConstraint' or 'System.Web.Routing.IRouteConstraint'.\";\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(() => routes.CreateRoute(\"{controller}/{id}\", null, constraints), expectedMessage);\n        }\n\n        [Theory]\n        [InlineData(\"values/10\")]\n        [InlineData(\"values/15\")]\n        [InlineData(\"values/20\")]\n        public async Task IgnoreRoute_WithConstraints_GetSoft404IfRouteIgnored(string requestPath)\n        {\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, \"http://localhost/constraint/\" + requestPath);\n            request.SetConfiguration(new HttpConfiguration());\n            request.SetHttpContext(CreateHttpContext(\"~/constraint\"));\n\n            var response = await SubmitRequestAsync(request);\n\n            Assert.Equal(Net.HttpStatusCode.NotFound, response.StatusCode);\n            Assert.True(response.RequestMessage.Properties.ContainsKey(HttpPropertyKeys.NoRouteMatched));\n        }\n\n        [Theory]\n        [InlineData(\"values/1\")]\n        [InlineData(\"values/25\")]\n        [InlineData(\"values/40\")]\n        public async Task IgnoreRoute_WithConstraints_GetValueIfNotIgnored(string requestPath)\n        {\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, \"http://localhost/constraint/\" + requestPath);\n            request.SetConfiguration(new HttpConfiguration());\n            request.SetHttpContext(CreateHttpContext(\"~/constraint\"));\n\n            var response = await SubmitRequestAsync(request);\n\n            Assert.Equal(Net.HttpStatusCode.OK, response.StatusCode);\n            Assert.Equal(String.Concat(\"values/\", await response.Content.ReadAsStringAsync()), requestPath);\n        }\n\n        public class CustomIgnoreRouteConstraint : IHttpRouteConstraint\n        {\n            public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName,\n                IDictionary<string, object> values, HttpRouteDirection routeDirection)\n            {\n                long id;\n                if (values.ContainsKey(\"id\")\n                    && Int64.TryParse(values[\"id\"].ToString(), out id)\n                    && (id == 10 || id == 15 || id == 20))\n                {\n                    return true;\n                }\n\n                return false;\n            }\n        }\n\n        private static async Task<HttpResponseMessage> SubmitRequestAsync(HttpRequestMessage request)\n        {\n            HttpConfiguration config = new HttpConfiguration(new HostedHttpRouteCollection(new RouteCollection()));\n            config.Routes.IgnoreRoute(\"Bar\", \"api/{*pathInfo}\");\n            config.Routes.IgnoreRoute(\"Constraints\", \"constraint/values/{id}\", constraints: new { constraint = new CustomIgnoreRouteConstraint() });\n            config.Routes.MapHttpRoute(\"DefaultApi\", \"api/{controller}/{action}\");\n            config.MapHttpAttributeRoutes();\n\n            HttpResponseMessage response;\n            HttpServer server = new HttpServer(config);\n            using (HttpMessageInvoker client = new HttpMessageInvoker(server))\n            {\n                response = await client.SendAsync(request, CancellationToken.None);\n            }\n\n            return response;\n        }\n\n        [RoutePrefix(\"constraint\")]\n        public class IgnoreRouteWithConstraintsTestController : ApiController\n        {\n            [Route(\"values/{id:int}\")]\n            public int Get(int id)\n            {\n               return id;\n            }\n        }\n\n        private static T GetContentValue<T>(HttpResponseMessage response)\n        {\n            T value;\n            response.TryGetContentValue<T>(out value);\n            return value;\n        }\n\n        private static HttpRequestMessage CreateHttpRequestMessageWithContext(string requestPath = \"controllerName/actionName\")\n        {\n            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, \"http://localhost/api/\" + requestPath);\n            request.SetConfiguration(new HttpConfiguration());\n            request.SetHttpContext(CreateHttpContext(\"~/api\"));\n\n            return request;\n        }\n\n        private static HttpContextBase CreateHttpContext(string relativeUrl, string appPathModifierReturnValue = \"\")\n        {\n            var mockContext = new Mock<HttpContextBase>();\n\n            mockContext.SetupGet(c => c.Request.ApplicationPath).Returns(String.Empty);\n            mockContext.SetupGet(c => c.Request.AppRelativeCurrentExecutionFilePath).Returns(relativeUrl);\n            mockContext.SetupGet(c => c.Request.PathInfo).Returns(\"\");\n            mockContext.SetupGet(c => c.Items).Returns(new Dictionary<string, object>());\n            mockContext.SetupGet(c => c.Request.HttpMethod).Returns(\"GET\");\n            mockContext.SetupGet(c => c.Request.InputStream).Returns(new MemoryStream());\n            mockContext.SetupGet(c => c.Request.Headers).Returns(new NameValueCollection());\n            mockContext.SetupGet(c => c.Request.ApplicationPath).Returns(\"/\");\n\n            if (appPathModifierReturnValue == string.Empty)\n            {\n                mockContext.Setup(c => c.Response.ApplyAppPathModifier(It.IsAny<string>()))\n                               .Returns((string s) => { return s; });\n            }\n            else\n            {\n                mockContext.Setup(c => c.Response.ApplyAppPathModifier(It.IsAny<string>()))\n                             .Returns(appPathModifierReturnValue);\n            }\n\n            return mockContext.Object;\n        }\n\n        public class HttpDomainRoute : Route\n        {\n            public HttpDomainRoute(string routeTemplate, object defaults, object constraints = null)\n                : base(routeTemplate, new RouteValueDictionary(defaults), new RouteValueDictionary(constraints), new RouteValueDictionary(), HttpControllerRouteHandler.Instance)\n            {\n            }\n\n            public override RouteData GetRouteData(HttpContextBase context)\n            {\n                RouteData data = new RouteData(this, RouteHandler);\n                data.Values.Add(\"domain\", \"customer\");\n                return data;\n            }\n\n            public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)\n            {\n                return base.GetVirtualPath(requestContext, values);\n            }\n        }\n\n        public class DomainHttpRoute : HttpRoute\n        {\n            public DomainHttpRoute(string domain, string routeTemplate, object defaults, object constraints = null)\n                : base(routeTemplate, new HttpRouteValueDictionary(defaults), new HttpRouteValueDictionary(constraints))\n            {\n                Domain = domain;\n            }\n\n            public string Domain { get; set; }\n\n            public override IHttpRouteData GetRouteData(string virtualPathRoot, System.Net.Http.HttpRequestMessage request)\n            {\n                // Route data\n                IHttpRouteData data = base.GetRouteData(virtualPathRoot, request);\n                data.Values.Add(\"domain\", Domain);\n                return data;\n            }\n\n            public override IHttpVirtualPathData GetVirtualPath(System.Net.Http.HttpRequestMessage request, IDictionary<string, object> values)\n            {\n                // customize the action token\n                values[\"action\"] = \"actionNameFromDomain\";\n\n                return base.GetVirtualPath(request, values);\n            }\n        }\n\n        private class CustomHttpConstraint : IHttpRouteConstraint\n        {\n            public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class CustomConstraint : IRouteConstraint\n        {\n            public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class MockHostedHttpRouteCollection : HostedHttpRouteCollection\n        {\n            public MockHostedHttpRouteCollection(RouteCollection routes)\n                : base(routes)\n            {\n            }\n\n            public int TimesValidateConstraintCalled\n            {\n                get;\n                private set;\n            }\n\n            protected override void ValidateConstraint(string routeTemplate, string name, object constraint)\n            {\n                TimesValidateConstraintCalled++;\n                base.ValidateConstraint(routeTemplate, name, constraint);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.WebHost.Test/Routing/HostedUrlHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Web.Mvc;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\nusing UrlHelper = System.Web.Http.Routing.UrlHelper;\n\nnamespace System.Web.Http.WebHost.Routing\n{\n    public class HostedUrlHelperTest\n    {\n        [Theory]\n        [InlineData(WhichRoute.ApiRoute1)]\n        [InlineData(WhichRoute.ApiRoute2)]\n        [InlineData(WhichRoute.WebRoute1)]\n        public void UrlHelper_GeneratesApiUrl_ForMatchingData(WhichRoute whichRoute)\n        {\n            // Mixed mode app with Web API generating URLs to other APIs\n            var url = GetUrlHelperForMixedApp(whichRoute);\n\n            string generatedUrl = url.Route(\"apiroute2\", new { controller = \"something\", action = \"someaction\", id = 789 });\n\n            Assert.Equal(\"$APP$/SOMEAPP/api/something/someaction\", generatedUrl);\n        }\n\n        [Theory]\n        [InlineData(WhichRoute.ApiRoute1)]\n        [InlineData(WhichRoute.ApiRoute2)]\n        [InlineData(WhichRoute.WebRoute1)]\n        public void UrlHelper_GeneratesNonApiUrl_ForMatchingData(WhichRoute whichRoute)\n        {\n            // Mixed mode app with Web API generating URLs to other non-API routes\n            var url = GetUrlHelperForMixedApp(whichRoute);\n\n            string generatedUrl = url.Route(\"webroute1\", new { controller = \"something\", action = \"someaction\", id = 789 });\n\n            Assert.Equal(\"$APP$/SOMEAPP/something/someaction/789\", generatedUrl);\n        }\n\n        [Theory]\n        [InlineData(WhichRoute.ApiRoute1)]\n        [InlineData(WhichRoute.ApiRoute2)]\n        [InlineData(WhichRoute.WebRoute1)]\n        public void UrlHelper_GeneratesNullUrl_ForDataNotMatching(WhichRoute whichRoute)\n        {\n            // Mixed mode app with Web API generating URLs to other non-API routes\n            var url = GetUrlHelperForMixedApp(whichRoute);\n\n            string generatedUrl = url.Route(\"webroute1\", new { foo = \"bar\" });\n\n            Assert.Null(generatedUrl);\n        }\n\n        [Theory]\n        [InlineData(WhichRoute.ApiRoute1)]\n        [InlineData(WhichRoute.ApiRoute2)]\n        [InlineData(WhichRoute.WebRoute1)]\n        public void UrlHelper_SkipsApiRoutesAndMatchesMvcUrl_ForMatchingData(WhichRoute whichRoute)\n        {\n            // Mixed mode app with MVC generating URLs to other MVC URLs\n            RouteCollection routes;\n            RequestContext requestContext;\n            var url = GetUrlHelperForMixedApp(whichRoute, out routes, out requestContext);\n\n            // Note: This is generating a URL the \"hard\" way because it's simulating what a regular MVC\n            // app would do when generating a URL. If we went through the Web API functionality it wouldn't\n            // be testing what would really happen in a mixed app.\n            VirtualPathData virtualPathData = routes.GetVirtualPath(requestContext, new RouteValueDictionary(new { controller = \"something\", action = \"someaction\", id = 789 }));\n\n            Assert.NotNull(virtualPathData);\n\n            string generatedUrl = virtualPathData.VirtualPath;\n\n            Assert.Equal(\"$APP$/SOMEAPP/something/someaction/789\", generatedUrl);\n        }\n\n        [Theory]\n        [InlineData(WhichRoute.ApiRoute1)]\n        [InlineData(WhichRoute.ApiRoute2)]\n        [InlineData(WhichRoute.WebRoute1)]\n        public void UrlHelper_MvcAppGeneratesApiRoute_WithSpecialHttpRouteKey(WhichRoute whichRoute)\n        {\n            // Mixed mode app with MVC generating URLs to Web APIs\n            RouteCollection routes;\n            RequestContext requestContext;\n            var url = GetUrlHelperForMixedApp(whichRoute, out routes, out requestContext);\n\n            // Note: This is generating a URL the \"hard\" way because it's simulating what a regular MVC\n            // app would do when generating a URL. If we went through the Web API functionality it wouldn't\n            // be testing what would really happen in a mixed app.\n            VirtualPathData virtualPathData = routes.GetVirtualPath(requestContext, new RouteValueDictionary(new { controller = \"something\", action = \"someotheraction\", id = 789, httproute = true }));\n\n            Assert.NotNull(virtualPathData);\n\n            string generatedUrl = virtualPathData.VirtualPath;\n\n            Assert.Equal(\"$APP$/SOMEAPP/api/something/someotheraction\", generatedUrl);\n        }\n\n        [Theory]\n        [InlineData(\"httproute\")]\n        [InlineData(\"httpRoute\")]\n        [InlineData(\"HTTPROUTE\")]\n        [InlineData(\"hTtProuTE\")]\n        public void UrlHelper_DoesntAddDuplicateHttpRoute_ForHttpRouteInDifferentCasing(string httpRoute)\n        {\n            // Mixed mode app with MVC generating URLs to Web APIs\n            RouteCollection routes;\n            RequestContext requestContext;\n            var url = GetUrlHelperForMixedApp(WhichRoute.ApiRoute1, out routes, out requestContext);\n\n            string generatedUrl = url.Route(\"apiroute1\", new Dictionary<string, object> { { \"controller\", \"something\" }, { \"id\", 789 }, { httpRoute, true } });\n\n            Assert.Equal(\"$APP$/SOMEAPP/api/something/789\", generatedUrl);\n        }\n\n        private static UrlHelper GetUrlHelperForMixedApp(WhichRoute whichRoute)\n        {\n            RouteCollection routes;\n            RequestContext requestContext;\n            return GetUrlHelperForMixedApp(whichRoute, out routes, out requestContext);\n        }\n\n        private static UrlHelper GetUrlHelperForMixedApp(WhichRoute whichRoute, out RouteCollection routes, out RequestContext requestContext)\n        {\n            routes = new RouteCollection();\n\n            HttpRequestMessage request = new HttpRequestMessage();\n            var mockHttpContext = new Mock<HttpContextBase>();\n            var mockHttpRequest = new Mock<HttpRequestBase>();\n            mockHttpRequest.SetupGet<string>(x => x.ApplicationPath).Returns(\"/SOMEAPP/\");\n            var mockHttpResponse = new Mock<HttpResponseBase>();\n            mockHttpResponse.Setup<string>(x => x.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(x => \"$APP$\" + x);\n            mockHttpContext.SetupGet<HttpRequestBase>(x => x.Request).Returns(mockHttpRequest.Object);\n            mockHttpContext.SetupGet<HttpResponseBase>(x => x.Response).Returns(mockHttpResponse.Object);\n            request.Properties[\"MS_HttpContext\"] = mockHttpContext.Object;\n\n            // Set up routes\n            var hostedRoutes = new HostedHttpRouteCollection(routes);\n            Route apiRoute1 = routes.MapHttpRoute(\"apiroute1\", \"api/{controller}/{id}\", new { action = \"someaction\" });\n            Route apiRoute2 = routes.MapHttpRoute(\"apiroute2\", \"api/{controller}/{action}\", new { id = 789 });\n            Route webRoute1 = routes.MapRoute(\"webroute1\", \"{controller}/{action}/{id}\");\n            request.SetConfiguration(new HttpConfiguration(hostedRoutes));\n\n            RouteData routeData = new RouteData();\n            routeData.Values.Add(\"controller\", \"people\");\n            routeData.Values.Add(\"id\", \"123\");\n\n            // Specify which route we came in on (e.g. what request matching the incoming URL) because\n            // it can affect the generated URL due to the ambient route data.\n            switch (whichRoute)\n            {\n                case WhichRoute.ApiRoute1:\n                    routeData.Route = apiRoute1;\n                    break;\n                case WhichRoute.ApiRoute2:\n                    routeData.Route = apiRoute2;\n                    break;\n                case WhichRoute.WebRoute1:\n                    routeData.Route = webRoute1;\n                    break;\n                default:\n                    throw new ArgumentException(\"Invalid route specified.\", \"whichRoute\");\n            }\n            request.SetRouteData(new HostedHttpRouteData(routeData));\n\n            requestContext = new RequestContext(mockHttpContext.Object, routeData);\n\n            return request.GetUrlHelper();\n        }\n\n        public enum WhichRoute\n        {\n            ApiRoute1,\n            ApiRoute2,\n            WebRoute1,\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.WebHost.Test/Routing/HttpContextBaseExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.IO;\nusing System.Net.Http;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.WebHost.Routing\n{\n    public class HttpContextBaseExtensionsTest\n    {\n        [Fact]\n        public void GetOrCreateHttpRequestMessageFromHttpContextCopiesHeaders()\n        {\n            // Arrange\n            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>();\n            Dictionary<string, object> items = new Dictionary<string, object>();\n            contextMock.Setup(o => o.Items).Returns(items);\n            var requestMock = new Mock<HttpRequestBase>();\n            requestMock.Setup(r => r.HttpMethod).Returns(\"GET\");\n            requestMock.Setup(r => r.InputStream).Returns(new MemoryStream());\n            NameValueCollection col = new NameValueCollection();\n            col.Add(\"customHeader\", \"customHeaderValue\");\n            requestMock.Setup(r => r.Headers).Returns(col);\n            contextMock.Setup(o => o.Request).Returns(requestMock.Object);\n\n            // Act\n            contextMock.Object.GetOrCreateHttpRequestMessage();\n\n            // Assert\n            HttpRequestMessage request = contextMock.Object.GetHttpRequestMessage();\n            Assert.NotNull(request);\n            Assert.Equal(HttpMethod.Get, request.Method);\n            IEnumerable<string> headerValues;\n            Assert.True(request.Headers.TryGetValues(\"customHeader\", out headerValues));\n            string headerValue = Assert.Single(headerValues);\n            Assert.Equal(\"customHeaderValue\", headerValue);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.WebHost.Test/Routing/HttpRequestMessageWrapperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing System.Net.Http;\nusing System.Web.Http.Hosting;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.WebHost.Routing\n{\n    public class HttpRequestMessageWrapperTest\n    {\n        public static TheoryDataSet<string, string, string> AppRelativeCurrentExecutionFilePathData\n        {\n            get\n            {\n                // string virtualPathRoot, string requestUri, string expectedPath\n                return new TheoryDataSet<string, string, string>\n                {\n                    { \"/\", \"http://localhost/path\", \"~/path\" },\n                    { \"/\", \"http://localhost/path.ext\", \"~/path.ext\" },\n                    { \"/\", \"http://localhost/path.ext?query=value\", \"~/path.ext\" },\n\n                    { \"/\", \"http://localhost/path/\", \"~/path\" },\n                    { \"/\", \"http://localhost/path.ext/\", \"~/path.ext\" },\n                    { \"/\", \"http://localhost/path.ext/?query=value\", \"~/path.ext\" },\n\n                    { \"/path1\", \"http://localhost/path1/path2\", \"~/path2\" },\n                    { \"/path1\", \"http://localhost/path1/path2.ext\", \"~/path2.ext\" },\n                    { \"/path1\", \"http://localhost/path1/path2.ext?query=value\", \"~/path2.ext\" },\n\n                    { \"/path1\", \"http://localhost/path1/path2/\", \"~/path2\" },\n                    { \"/path1\", \"http://localhost/path1/path2.ext/\", \"~/path2.ext\" },\n                    { \"/path1\", \"http://localhost/path1/path2.ext/?query=value\", \"~/path2.ext\" },\n\n                    { \"/path1\", \"http://localhost/path1/path2/path3\", \"~/path2/path3\" },\n                    { \"/path1\", \"http://localhost/path1/path2/path3.ext\", \"~/path2/path3.ext\" },\n                    { \"/path1\", \"http://localhost/path1/path2/path3.ext?query=value\", \"~/path2/path3.ext\" },\n\n                    { \"/path1\", \"http://localhost/path1/path2/path3/\", \"~/path2/path3\" },\n                    { \"/path1\", \"http://localhost/path1/path2/path3.ext/\", \"~/path2/path3.ext\" },\n                    { \"/path1\", \"http://localhost/path1/path2/path3.ext/?query=value\", \"~/path2/path3.ext\" },\n\n                    { \"/path1\", \"http://localhost/PATH1/path2/path3/\", \"~/path2/path3\" },\n                    { \"/path1\", \"http://localhost/PATH1/PATH2/path3.ext/\", \"~/PATH2/path3.ext\" },\n                    { \"/path1\", \"http://localhost/PATH1/PATH2/PATH3.ext/?query=value\", \"~/PATH2/PATH3.ext\" },\n\n                    // urls should be unencoded - /path1/path2 /path3.ext instead of /path1/path2%20/path3.ext\n                    { \"/path1\", \"http://localhost/PATH1/path2 /path3/\", \"~/path2 /path3\" },\n                    { \"/path1\", \"http://localhost/PATH1/PATH2 /path3.ext/\", \"~/PATH2 /path3.ext\" },\n                    { \"/path1\", \"http://localhost/PATH1/PATH2 /PATH3.ext/?query=value\", \"~/PATH2 /PATH3.ext\" },\n                };\n            }\n        }\n\n        public static TheoryDataSet<string, string, string> FilePathData\n        {\n            get\n            {\n                // string virtualPathRoot, string requestUri, string expectedPath\n                return new TheoryDataSet<string, string, string>\n                {\n                    { \"/\", \"http://localhost/path\", \"/path\" },\n                    { \"/\", \"http://localhost/path.ext\", \"/path.ext\" },\n                    { \"/\", \"http://localhost/path.ext?query=value\", \"/path.ext\" },\n\n                    { \"/\", \"http://localhost/path/\", \"/path\" },\n                    { \"/\", \"http://localhost/path.ext/\", \"/path.ext\" },\n                    { \"/\", \"http://localhost/path.ext/?query=value\", \"/path.ext\" },\n\n                    { \"/path1\", \"http://localhost/path1/path2\", \"/path1/path2\" },\n                    { \"/path1\", \"http://localhost/path1/path2.ext\", \"/path1/path2.ext\" },\n                    { \"/path1\", \"http://localhost/path1/path2.ext?query=value\", \"/path1/path2.ext\" },\n\n                    { \"/path1\", \"http://localhost/path1/path2/\", \"/path1/path2\" },\n                    { \"/path1\", \"http://localhost/path1/path2.ext/\", \"/path1/path2.ext\" },\n                    { \"/path1\", \"http://localhost/path1/path2.ext/?query=value\", \"/path1/path2.ext\" },\n\n                    { \"/path1\", \"http://localhost/path1/path2/path3\", \"/path1/path2/path3\" },\n                    { \"/path1\", \"http://localhost/path1/path2/path3.ext\", \"/path1/path2/path3.ext\" },\n                    { \"/path1\", \"http://localhost/path1/path2/path3.ext?query=value\", \"/path1/path2/path3.ext\" },\n\n                    { \"/path1\", \"http://localhost/path1/path2/path3/\", \"/path1/path2/path3\" },\n                    { \"/path1\", \"http://localhost/path1/path2/path3.ext/\", \"/path1/path2/path3.ext\" },\n                    { \"/path1\", \"http://localhost/path1/path2/path3.ext/?query=value\", \"/path1/path2/path3.ext\" },\n\n                    // urls should be unescaped - /path1/path2 /path3.ext instead of /path1/path2%20/path3.ext\n                    { \"/path1\", \"http://localhost/path1/path2 /path3/\", \"/path1/path2 /path3\" },\n                    { \"/path1\", \"http://localhost/path1/path2 /path3.ext/\", \"/path1/path2 /path3.ext\" },\n                    { \"/path1\", \"http://localhost/path1/path2 /path3.ext/?query=value\", \"/path1/path2 /path3.ext\" },\n                };\n            }\n        }\n\n        [Fact]\n        public void Constructor_GuardClauses()\n        {\n            HttpRequestMessage request = new HttpRequestMessage();\n            Assert.ThrowsArgumentNull(() => new HttpRequestMessageWrapper(virtualPathRoot: null, httpRequest: request), \"virtualPathRoot\");\n            Assert.ThrowsArgumentNull(() => new HttpRequestMessageWrapper(String.Empty, httpRequest: null), \"httpRequest\");\n        }\n\n        [Theory]\n        [InlineData(\"\")]\n        [InlineData(\"/\")]\n        [InlineData(\"/path\")]\n        [InlineData(\"/path1/path2\")]\n        public void ApplicationPath_DelegatesToHttpRequestMessage(string applicationPath)\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            HttpRequestMessageWrapper wrapper = new HttpRequestMessageWrapper(applicationPath, request);\n\n            // Act\n            string actualApplicationPath = wrapper.ApplicationPath;\n\n            // Assert\n            Assert.Equal(applicationPath, actualApplicationPath);\n        }\n\n        [Theory]\n        [PropertyData(\"AppRelativeCurrentExecutionFilePathData\")]\n        public void AppRelativeCurrentExecutionFilePath_DelegatesToHttpRequestMessage(string virtualPathRoot, string requestUri, string expectedPath)\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(requestUri),\n            };\n            HttpRequestMessageWrapper wrapper = new HttpRequestMessageWrapper(virtualPathRoot, request);\n\n            // Act\n            string actualPath = wrapper.AppRelativeCurrentExecutionFilePath;\n\n            // Assert\n            Assert.Equal(expectedPath, actualPath);\n        }\n\n        [Theory]\n        [PropertyData(\"FilePathData\")]\n        public void CurrentExecutionFilePath_DelegatesToHttpRequestMessage(string virtualPathRoot, string requestUri, string expectedPath)\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(requestUri),\n            };\n            HttpRequestMessageWrapper wrapper = new HttpRequestMessageWrapper(virtualPathRoot, request);\n\n            // Act\n            string actualPath = wrapper.CurrentExecutionFilePath;\n\n            // Assert\n            Assert.Equal(expectedPath, actualPath);\n        }\n\n        [Theory]\n        [PropertyData(\"FilePathData\")]\n        public void FilePath_DelegatesToHttpRequestMessage(string virtualPathRoot, string requestUri, string expectedPath)\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = new Uri(requestUri),\n            };\n            HttpRequestMessageWrapper wrapper = new HttpRequestMessageWrapper(virtualPathRoot, request);\n\n            // Act\n            string actualPath = wrapper.FilePath;\n\n            // Assert\n            Assert.Equal(expectedPath, actualPath);\n        }\n\n        [Fact]\n        public void HttpMethod_DelegatesToHttpRequestMessage()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                Method = new HttpMethod(\"DELETE\")\n            };\n            HttpRequestMessageWrapper wrapper = new HttpRequestMessageWrapper(\"/\", request);\n\n            // Act\n            string actualMethod = wrapper.HttpMethod;\n\n            // Assert\n            Assert.Equal(\"DELETE\", actualMethod);\n        }\n\n        [Fact]\n        public void RequestType_DelegatesToHttpRequestMessage()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                Method = new HttpMethod(\"DELETE\")\n            };\n            HttpRequestMessageWrapper wrapper = new HttpRequestMessageWrapper(\"/\", request);\n\n            // Act\n            string actualRequestType = wrapper.RequestType;\n\n            // Assert\n            Assert.Equal(\"DELETE\", actualRequestType);\n        }\n\n        [Fact]\n        public void Path_DelegatesToHttpRequestMessage()\n        {\n            // Arrange\n            Uri requestUri = new Uri(\"http://localhost/some/path?query=value\");\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = requestUri\n            };\n            HttpRequestMessageWrapper wrapper = new HttpRequestMessageWrapper(\"/\", request);\n\n            // Act\n            string actualPath = wrapper.Path;\n\n            // Assert\n            Assert.Equal(\"/some/path\", actualPath);\n        }\n\n        [Fact]\n        public void Path_DelegatesToHttpRequestMessage_DoesNotEncode()\n        {\n            // Arrange\n            Uri requestUri = new Uri(\"http://localhost/some /path?query=value\");\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = requestUri\n            };\n            HttpRequestMessageWrapper wrapper = new HttpRequestMessageWrapper(\"/\", request);\n\n            // Act\n            string actualPath = wrapper.Path;\n\n            // Assert\n            Assert.Equal(\"/some /path\", actualPath);\n        }\n\n        [Theory]\n        [InlineData(\"http://www.example.com\")]\n        [InlineData(\"http://www.example.com?query\")]\n        [InlineData(\"http://www.example.com?query=value\")]\n        public void QueryString_DelegatesToHttpRequestMessage(string requestUri)\n        {\n            // Arrange\n            Uri reqUri = new Uri(requestUri);\n            NameValueCollection expectedQueryString = reqUri.ParseQueryString();\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = reqUri\n            };\n            HttpRequestMessageWrapper wrapper = new HttpRequestMessageWrapper(\"/\", request);\n\n            // Act\n            NameValueCollection actualQuery = wrapper.QueryString;\n\n            // Assert\n            Assert.Equal(expectedQueryString.ToString(), actualQuery.ToString());\n        }\n\n        [Fact]\n        public void RawUrl_DelegatesToHttpRequestMessage()\n        {\n            // Arrange\n            Uri requestUri = new Uri(\"http://localhost/some/path?query=value\");\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = requestUri\n            };\n            HttpRequestMessageWrapper wrapper = new HttpRequestMessageWrapper(\"/\", request);\n\n            // Act\n            string actualRawUrl = wrapper.RawUrl;\n\n            // Assert\n            Assert.Equal(\"/some/path?query=value\", actualRawUrl);\n        }\n\n        [Fact]\n        public void RawUrl_DelegatesToHttpRequestMessage_DoesNotEncode()\n        {\n            // Arrange\n            Uri requestUri = new Uri(\"http://localhost/some /path?query=value\");\n            HttpRequestMessage request = new HttpRequestMessage\n            {\n                RequestUri = requestUri\n            };\n            HttpRequestMessageWrapper wrapper = new HttpRequestMessageWrapper(\"/\", request);\n\n            // Act\n            string actualRawUrl = wrapper.RawUrl;\n\n            // Assert\n            Assert.Equal(\"/some /path?query=value\", actualRawUrl);\n        }\n\n        [Fact]\n        public void IsLocal_Call_To_HttpRequestMessageExtension_Method()\n        {\n            // Arrange\n            HttpRequestMessage request = new HttpRequestMessage();\n            request.SetIsLocal(new Lazy<bool>(() => true));\n            HttpRequestMessageWrapper wrapper = new HttpRequestMessageWrapper(\"/\", request);\n\n            // Act\n            bool isLocal = wrapper.IsLocal;\n\n            // Assert\n            Assert.True(isLocal);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.WebHost.Test/Routing/HttpRouteExceptionHandlerTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.IO;\nusing System.Net;\nusing System.Net.Http;\nusing System.Runtime.ExceptionServices;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Results;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.WebHost.Routing\n{\n    public class HttpRouteExceptionHandlerTests\n    {\n        [Fact]\n        public void ExceptionInfo_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            ExceptionDispatchInfo expectedExceptionInfo = CreateExceptionInfo();\n            IExceptionLogger logger = CreateDummyLogger();\n            IExceptionHandler handler = CreateDummyHandler();\n            HttpRouteExceptionHandler product = CreateProductUnderTest(expectedExceptionInfo, logger, handler);\n\n            // Act\n            ExceptionDispatchInfo exceptionInfo = product.ExceptionInfo;\n\n            // Assert\n            Assert.Same(exceptionInfo, expectedExceptionInfo);\n        }\n\n        [Fact]\n        public void ExceptionLogger_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            ExceptionDispatchInfo exceptionInfo = CreateExceptionInfo();\n            IExceptionLogger expectedLogger = CreateDummyLogger();\n            IExceptionHandler handler = CreateDummyHandler();\n            HttpRouteExceptionHandler product = CreateProductUnderTest(exceptionInfo, expectedLogger, handler);\n\n            // Act\n            IExceptionLogger logger = product.ExceptionLogger;\n\n            // Assert\n            Assert.Same(expectedLogger, logger);\n        }\n\n        [Fact]\n        public void ExceptionHandler_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            ExceptionDispatchInfo exceptionInfo = CreateExceptionInfo();\n            IExceptionLogger logger = CreateDummyLogger();\n            IExceptionHandler expectedHandler = CreateDummyHandler();\n            HttpRouteExceptionHandler product = CreateProductUnderTest(exceptionInfo, logger, expectedHandler);\n\n            // Act\n            IExceptionHandler handler = product.ExceptionHandler;\n\n            // Assert\n            Assert.Same(expectedHandler, handler);\n        }\n\n        [Fact]\n        public void ExceptionInfo_IfUsingExceptionInfoConstructor_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            ExceptionDispatchInfo expectedExceptionInfo = CreateExceptionInfo();\n            HttpRouteExceptionHandler product = CreateProductUnderTest(expectedExceptionInfo);\n\n            // Act\n            ExceptionDispatchInfo exceptionInfo = product.ExceptionInfo;\n\n            // Assert\n            Assert.Same(exceptionInfo, expectedExceptionInfo);\n        }\n\n        [Fact]\n        public void ExceptionLogger_IfUsingExceptionInfoConstructor_ReturnsExceptionServicesInstance()\n        {\n            // Arrange\n            ExceptionDispatchInfo exceptionInfo = CreateExceptionInfo();\n            HttpRouteExceptionHandler product = CreateProductUnderTest(exceptionInfo);\n\n            // Act\n            IExceptionLogger logger = product.ExceptionLogger;\n\n            // Assert\n            IExceptionLogger expectedLogger = ExceptionServices.GetLogger(GlobalConfiguration.Configuration);\n            Assert.Same(expectedLogger, logger);\n        }\n\n        [Fact]\n        public void ExceptionHandler_IfUsingExceptionInfoConstructor_ReturnsExceptionServicesInstance()\n        {\n            // Arrange\n            ExceptionDispatchInfo exceptionInfo = CreateExceptionInfo();\n            HttpRouteExceptionHandler product = CreateProductUnderTest(exceptionInfo);\n\n            // Act\n            IExceptionHandler handler = product.ExceptionHandler;\n\n            // Assert\n            IExceptionHandler expectedHandler = ExceptionServices.GetHandler(GlobalConfiguration.Configuration);\n            Assert.Same(expectedHandler, handler);\n        }\n\n        [Fact]\n        public async Task ProcessRequestAsync_IfExceptionIsHttpResponseException_UsesExceptionResponse()\n        {\n            // Arrange\n            HttpStatusCode expectedStatusCode = HttpStatusCode.Forbidden;\n\n            using (HttpResponseMessage response = CreateResponse(expectedStatusCode))\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                ExceptionDispatchInfo exceptionInfo = CreateExceptionInfo(new HttpResponseException(response));\n                IExceptionLogger logger = CreateDummyLogger();\n                IExceptionHandler handler = CreateDummyHandler();\n\n                HttpRouteExceptionHandler product = CreateProductUnderTest(exceptionInfo, logger, handler);\n\n                int statusCode = 0;\n                Mock<HttpResponseBase> responseBaseMock = new Mock<HttpResponseBase>();\n                responseBaseMock.SetupSet(r => r.StatusCode = It.IsAny<int>()).Callback<int>((s) => statusCode = s);\n                responseBaseMock.SetupGet(r => r.Cache).Returns(() => new Mock<HttpCachePolicyBase>().Object);\n                HttpResponseBase responseBase = responseBaseMock.Object;\n                HttpContextBase contextBase = CreateStubContextBase(responseBase);\n                contextBase.SetHttpRequestMessage(request);\n\n                // Act\n                await product.ProcessRequestAsync(contextBase);\n\n                // Assert\n                Assert.Equal((int)expectedStatusCode, statusCode);\n            }\n        }\n\n        [Fact]\n        public async Task ProcessRequestAsync_IfExceptionIsNotHttpResponseException_CallsExceptionServices()\n        {\n            // Arrange\n            Exception expectedException = CreateException();\n            ExceptionDispatchInfo exceptionInfo = CreateExceptionInfo(expectedException);\n\n            Mock<IExceptionLogger> loggerMock = CreateStubExceptionLoggerMock();\n            IExceptionLogger logger = loggerMock.Object;\n            Mock<IExceptionHandler> handlerMock = CreateStubExceptionHandlerMock();\n            IExceptionHandler handler = handlerMock.Object;\n\n            HttpRouteExceptionHandler product = CreateProductUnderTest(exceptionInfo, logger, handler);\n\n            HttpResponseBase responseBase = CreateStubResponseBase();\n            HttpContextBase contextBase = CreateStubContextBase(responseBase);\n\n            using (HttpRequestMessage expectedRequest = new HttpRequestMessage())\n            {\n                contextBase.SetHttpRequestMessage(expectedRequest);\n\n                // Act & Assert\n                await Assert.ThrowsAsync<Exception>(() => product.ProcessRequestAsync(contextBase));\n\n                Func<ExceptionContext, bool> exceptionContextMatches = (c) =>\n                    c != null\n                    && c.Exception == expectedException\n                    && c.CatchBlock == WebHostExceptionCatchBlocks.HttpWebRoute\n                    && c.Request == expectedRequest;\n\n                loggerMock.Verify(l => l.LogAsync(It.Is<ExceptionLoggerContext>(c =>\n                    exceptionContextMatches(c.ExceptionContext)), CancellationToken.None), Times.Once());\n                handlerMock.Verify(l => l.HandleAsync(It.Is<ExceptionHandlerContext>(c =>\n                    exceptionContextMatches(c.ExceptionContext)), CancellationToken.None), Times.Once());\n            }\n        }\n\n        [Fact]\n        public async Task ProcessRequestAsync_IfHandlerHandles_UsesHandlerResult()\n        {\n            // Arrange\n            ExceptionDispatchInfo exceptionInfo = CreateExceptionInfo();\n\n            IExceptionLogger logger = CreateStubExceptionLogger();\n\n            HttpStatusCode expectedStatusCode = HttpStatusCode.Ambiguous;\n            Mock<IExceptionHandler> handlerMock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n            handlerMock\n                .Setup(h => h.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                .Returns<ExceptionHandlerContext, CancellationToken>((c, i) =>\n                {\n                    c.Result = new StatusCodeResult(expectedStatusCode, new HttpRequestMessage());\n                    return Task.FromResult(0);\n                });\n            IExceptionHandler handler = handlerMock.Object;\n\n            HttpRouteExceptionHandler product = CreateProductUnderTest(exceptionInfo, logger, handler);\n\n            int statusCode = 0;\n            Mock<HttpResponseBase> responseBaseMock = new Mock<HttpResponseBase>();\n            responseBaseMock.SetupSet(r => r.StatusCode = It.IsAny<int>()).Callback<int>((c) => statusCode = c);\n            responseBaseMock.SetupGet(r => r.Cache).Returns(() => new Mock<HttpCachePolicyBase>().Object);\n            HttpResponseBase responseBase = responseBaseMock.Object;\n            HttpContextBase contextBase = CreateStubContextBase(responseBase);\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                contextBase.SetHttpRequestMessage(request);\n\n                // Act\n                await product.ProcessRequestAsync(contextBase);\n\n                // Assert\n                Assert.Equal((int)expectedStatusCode, statusCode);\n            }\n        }\n\n        [Fact]\n        public async Task ProcessRequestAsync_IfHandlerDoesNotHandle_ReturnsTaskPropagatingException()\n        {\n            // Arrange\n            Exception expectedException = CreateExceptionWithCallStack();\n            string expectedStackTrace = expectedException.StackTrace;\n            ExceptionDispatchInfo exceptionInfo = CreateExceptionInfo(expectedException);\n\n            IExceptionLogger logger = CreateStubExceptionLogger();\n            IExceptionHandler handler = CreateStubExceptionHandler();\n\n            HttpRouteExceptionHandler product = CreateProductUnderTest(exceptionInfo, logger, handler);\n\n            HttpResponseBase responseBase = CreateStubResponseBase();\n            HttpContextBase contextBase = CreateStubContextBase(responseBase);\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                contextBase.SetHttpRequestMessage(request);\n\n                // Act & Assert\n                var exception = await Assert.ThrowsAsync<Exception>(() => product.ProcessRequestAsync(contextBase));\n\n                Assert.Same(expectedException, exception);\n                Assert.NotNull(exception.StackTrace);\n                Assert.StartsWith(expectedStackTrace, exception.StackTrace);\n            }\n\n        }\n\n        [Fact]\n        public async Task ProcessRequestAsync_IfCopyToAsyncOnErrorResponseThrows_CallsExceptionLogger()\n        {\n            // Arrange\n            Exception expectedOriginalException = CreateException();\n            ExceptionDispatchInfo exceptionInfo = CreateExceptionInfo(expectedOriginalException);\n\n            Mock<IExceptionLogger> loggerMock = CreateStubExceptionLoggerMock();\n            IExceptionLogger logger = loggerMock.Object;\n\n            Exception expectedErrorException = CreateException();\n\n            using (HttpResponseMessage expectedErrorResponse = new HttpResponseMessage())\n            using (HttpRequestMessage expectedRequest = new HttpRequestMessage())\n            {\n                expectedErrorResponse.Content = CreateFaultingContent(expectedErrorException);\n\n                Mock<IExceptionHandler> handlerMock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n                handlerMock\n                    .Setup(h => h.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                    .Returns<ExceptionHandlerContext, CancellationToken>((c, i) =>\n                    {\n                        c.Result = new ResponseMessageResult(expectedErrorResponse);\n                        return Task.FromResult(0);\n                    });\n                IExceptionHandler handler = handlerMock.Object;\n\n                HttpRouteExceptionHandler product = CreateProductUnderTest(exceptionInfo, logger, handler);\n\n                HttpResponseBase responseBase = CreateStubResponseBase(Stream.Null);\n                HttpContextBase contextBase = CreateStubContextBase(responseBase);\n                contextBase.SetHttpRequestMessage(expectedRequest);\n\n                // Act\n                await product.ProcessRequestAsync(contextBase);\n\n                // Assert\n                loggerMock.Verify(l => l.LogAsync(It.Is<ExceptionLoggerContext>(c =>\n                    c.ExceptionContext != null\n                    && c.ExceptionContext.Exception == expectedOriginalException\n                    && c.ExceptionContext.CatchBlock == WebHostExceptionCatchBlocks.HttpWebRoute\n                    && c.ExceptionContext.Request == expectedRequest),\n                    CancellationToken.None), Times.Once());\n                loggerMock.Verify(l => l.LogAsync(It.Is<ExceptionLoggerContext>(c =>\n                    c.ExceptionContext != null\n                    && c.ExceptionContext.Exception == expectedErrorException\n                    && c.ExceptionContext.CatchBlock == WebHostExceptionCatchBlocks.HttpControllerHandlerBufferError\n                    && c.ExceptionContext.Request == expectedRequest\n                    && c.ExceptionContext.Response == expectedErrorResponse),\n                    CancellationToken.None), Times.Once());\n            }\n        }\n\n        [Fact]\n        public async Task ProcessRequestAsync_IfExceptionIsHttpResponseException_DisposesRequestAndResponse()\n        {\n            // Arrange\n            using (HttpResponseMessage response = CreateResponse())\n            using (HttpRequestMessage request = CreateRequest())\n            using (SpyDisposable spy = new SpyDisposable())\n            {\n                request.RegisterForDispose(spy);\n\n                ExceptionDispatchInfo exceptionInfo = CreateExceptionInfo(new HttpResponseException(response));\n                IExceptionLogger logger = CreateDummyLogger();\n                IExceptionHandler handler = CreateDummyHandler();\n\n                HttpRouteExceptionHandler product = CreateProductUnderTest(exceptionInfo, logger, handler);\n\n                Mock<HttpResponseBase> responseBaseMock = new Mock<HttpResponseBase>();\n                responseBaseMock.SetupGet(r => r.Cache).Returns(() => new Mock<HttpCachePolicyBase>().Object);\n                HttpResponseBase responseBase = responseBaseMock.Object;\n                HttpContextBase contextBase = CreateStubContextBase(responseBase);\n                contextBase.SetHttpRequestMessage(request);\n\n                // Act\n                await product.ProcessRequestAsync(contextBase);\n\n                // Assert\n                Assert.True(spy.Disposed);\n                Assert.ThrowsObjectDisposed(() => request.Method = HttpMethod.Get,\n                    typeof(HttpRequestMessage).FullName);\n                Assert.ThrowsObjectDisposed(() => response.StatusCode = HttpStatusCode.OK,\n                    typeof(HttpResponseMessage).FullName);\n            }\n        }\n\n        [Fact]\n        public async Task ProcessRequestAsync_IfExceptionIsNotHttpResponseException_DisposesRequest()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            using (SpyDisposable spy = new SpyDisposable())\n            {\n                request.RegisterForDispose(spy);\n\n                ExceptionDispatchInfo exceptionInfo = CreateExceptionInfo(CreateException());\n                Mock<IExceptionLogger> loggerMock = new Mock<IExceptionLogger>(MockBehavior.Strict);\n                loggerMock\n                    .Setup(l => l.LogAsync(It.IsAny<ExceptionLoggerContext>(), It.IsAny<CancellationToken>()))\n                    .Returns(Task.FromResult(0));\n                Mock<IExceptionHandler> handlerMock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n                handlerMock\n                    .Setup(h => h.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                    .Returns(Task.FromResult(0));\n\n                HttpRouteExceptionHandler product = CreateProductUnderTest(exceptionInfo, loggerMock.Object, handlerMock.Object);\n\n                Mock<HttpResponseBase> responseBaseMock = new Mock<HttpResponseBase>();\n                responseBaseMock.SetupGet(r => r.Cache).Returns(() => new Mock<HttpCachePolicyBase>().Object);\n                HttpResponseBase responseBase = responseBaseMock.Object;\n                HttpContextBase contextBase = CreateStubContextBase(responseBase);\n                contextBase.SetHttpRequestMessage(request);\n\n                // Act & Assert\n                await Assert.ThrowsAsync<Exception>(() => product.ProcessRequestAsync(contextBase));\n\n                Assert.True(spy.Disposed);\n                Assert.ThrowsObjectDisposed(() => request.Method = HttpMethod.Get,\n                    typeof(HttpRequestMessage).FullName);\n            }\n        }\n\n        // This scenario emulates what would happen if a route throws OperationCanceledException.\n        [Fact]\n        public async Task ProcessRequestAsync_RouteCanceled_CancelsRequest()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                ExceptionDispatchInfo exceptionInfo = CreateExceptionInfo(new OperationCanceledException());\n                IExceptionLogger logger = CreateDummyLogger();\n                IExceptionHandler handler = CreateDummyHandler();\n\n                HttpRouteExceptionHandler product = CreateProductUnderTest(exceptionInfo, logger, handler);\n\n                Mock<HttpRequestBase> requestBase = new Mock<HttpRequestBase>(MockBehavior.Strict);\n                requestBase.Setup(r => r.Abort()).Verifiable();\n\n                Mock<HttpResponseBase> responseBase = new Mock<HttpResponseBase>(MockBehavior.Strict);\n\n                HttpContextBase contextBase = CreateStubContextBase(requestBase.Object, responseBase.Object);\n                contextBase.SetHttpRequestMessage(request);\n\n                // Act\n                await product.ProcessRequestAsync(contextBase);\n\n                // Assert\n                requestBase.Verify(r => r.Abort(), Times.Once());\n            }\n        }\n\n        // This scenario emulates what would happen if the request is canceled while trying to handle an http response exception\n        // thrown by routing.\n        [Fact]\n        public async Task ProcessRequestAsync_WritingResponseCanceled_CancelsRequest()\n        {\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                ExceptionDispatchInfo exceptionInfo = CreateExceptionInfo(new HttpResponseException(HttpStatusCode.OK));\n                IExceptionLogger logger = CreateDummyLogger();\n                IExceptionHandler handler = CreateDummyHandler();\n\n                HttpRouteExceptionHandler product = CreateProductUnderTest(exceptionInfo, logger, handler);\n\n                Mock<HttpRequestBase> requestBase = new Mock<HttpRequestBase>(MockBehavior.Strict);\n                requestBase.Setup(r => r.Abort()).Verifiable();\n\n                Mock<HttpResponseBase> responseBase = new Mock<HttpResponseBase>(MockBehavior.Strict);\n                responseBase.SetupSet(r => r.StatusCode = It.IsAny<int>()).Throws(new OperationCanceledException());\n\n                HttpContextBase contextBase = CreateStubContextBase(requestBase.Object, responseBase.Object);\n                contextBase.SetHttpRequestMessage(request);\n\n                // Act\n                await product.ProcessRequestAsync(contextBase);\n\n                // Assert\n                requestBase.Verify(r => r.Abort(), Times.Once());\n            }\n        }\n\n        private static IExceptionHandler CreateDummyHandler()\n        {\n            return new Mock<IExceptionHandler>(MockBehavior.Strict).Object;\n        }\n\n        private static IExceptionLogger CreateDummyLogger()\n        {\n            return new Mock<IExceptionLogger>(MockBehavior.Strict).Object;\n        }\n\n        private static Exception CreateException()\n        {\n            return new Exception();\n        }\n\n        private static Exception CreateExceptionWithCallStack()\n        {\n            try\n            {\n                throw CreateException();\n            }\n            catch (Exception exception)\n            {\n                return exception;\n            }\n        }\n\n        private static ExceptionDispatchInfo CreateExceptionInfo()\n        {\n            return CreateExceptionInfo(CreateException());\n        }\n\n        private static ExceptionDispatchInfo CreateExceptionInfo(Exception exception)\n        {\n            return ExceptionDispatchInfo.Capture(exception);\n        }\n\n        private static HttpContent CreateFaultingContent(Exception exception)\n        {\n            return new FaultingHttpContent(exception);\n        }\n\n        private static HttpRouteExceptionHandler CreateProductUnderTest(ExceptionDispatchInfo exceptionInfo)\n        {\n            return new HttpRouteExceptionHandler(exceptionInfo);\n        }\n\n        private static HttpRouteExceptionHandler CreateProductUnderTest(ExceptionDispatchInfo exceptionInfo,\n            IExceptionLogger exceptionLogger, IExceptionHandler exceptionHandler)\n        {\n            return new HttpRouteExceptionHandler(exceptionInfo, exceptionLogger, exceptionHandler);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private static HttpResponseMessage CreateResponse()\n        {\n            return new HttpResponseMessage();\n        }\n\n        private static HttpResponseMessage CreateResponse(HttpStatusCode statusCode)\n        {\n            return new HttpResponseMessage(statusCode);\n        }\n\n        private static HttpContextBase CreateStubContextBase(HttpResponseBase response)\n        {\n            return CreateStubContextBase(request: null, response: response);\n        }\n\n        private static HttpContextBase CreateStubContextBase(HttpRequestBase request, HttpResponseBase response)\n        {\n            Mock<HttpContextBase> mock = new Mock<HttpContextBase>();\n            mock.SetupGet(m => m.Request).Returns(request);\n            mock.SetupGet(m => m.Response).Returns(response);\n\n            IDictionary items = new Dictionary<object, object>();\n            mock.SetupGet(m => m.Items).Returns(items);\n\n            return mock.Object;\n        }\n\n        private static IExceptionHandler CreateStubExceptionHandler()\n        {\n            return CreateStubExceptionHandlerMock().Object;\n        }\n\n        private static Mock<IExceptionHandler> CreateStubExceptionHandlerMock()\n        {\n            Mock<IExceptionHandler> mock = new Mock<IExceptionHandler>(MockBehavior.Strict);\n            mock\n                .Setup(h => h.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                .Returns(Task.FromResult(0));\n            return mock;\n        }\n\n        private static IExceptionLogger CreateStubExceptionLogger()\n        {\n            return CreateStubExceptionLoggerMock().Object;\n        }\n\n        private static Mock<IExceptionLogger> CreateStubExceptionLoggerMock()\n        {\n            Mock<IExceptionLogger> mock = new Mock<IExceptionLogger>(MockBehavior.Strict);\n            mock\n                .Setup(l => l.LogAsync(It.IsAny<ExceptionLoggerContext>(), It.IsAny<CancellationToken>()))\n                .Returns(Task.FromResult(0));\n            return mock;\n        }\n\n        private static HttpResponseBase CreateStubResponseBase()\n        {\n            return new Mock<HttpResponseBase>().Object;\n        }\n\n        private static HttpResponseBase CreateStubResponseBase(Stream outputStream)\n        {\n            Mock<HttpResponseBase> mock = new Mock<HttpResponseBase>();\n            mock.Setup(r => r.OutputStream).Returns(outputStream);\n            return mock.Object;\n        }\n\n        private class FaultingHttpContent : HttpContent\n        {\n            private readonly Exception _exception;\n\n            public FaultingHttpContent(Exception exception)\n            {\n                Contract.Assert(exception != null);\n                _exception = exception;\n            }\n\n            protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)\n            {\n                return CreateFaultedTask(_exception);\n            }\n\n            protected override bool TryComputeLength(out long length)\n            {\n                length = 0;\n                return false;\n            }\n\n            private static Task CreateFaultedTask(Exception exception)\n            {\n                TaskCompletionSource<object> source = new TaskCompletionSource<object>();\n                source.SetException(exception);\n                return source.Task;\n            }\n        }\n\n        private sealed class SpyDisposable : IDisposable\n        {\n            public bool Disposed { get; private set; }\n\n            public void Dispose()\n            {\n                Disposed = true;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.WebHost.Test/Routing/HttpRouteExceptionRouteHandlerTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Runtime.ExceptionServices;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.WebHost.Routing\n{\n    public class HttpRouteExceptionRouteHandlerTests\n    {\n        [Fact]\n        public void ExceptionInfo_ReturnsSpecifiedInstance()\n        {\n            // Arrange\n            ExceptionDispatchInfo expectedExceptionInfo = CreateExceptionInfo();\n            HttpRouteExceptionRouteHandler product = CreateProductUnderTest(expectedExceptionInfo);\n\n            // Act\n            ExceptionDispatchInfo exceptionInfo = product.ExceptionInfo;\n\n            // Assert\n            Assert.Same(exceptionInfo, expectedExceptionInfo);\n        }\n\n        [Fact]\n        public void GetHttpHandler_ReturnsExceptionHandlerWithExceptionInfo()\n        {\n            // Arrange\n            ExceptionDispatchInfo expectedExceptionInfo = CreateExceptionInfo();\n            IRouteHandler product = CreateProductUnderTest(expectedExceptionInfo);\n            RequestContext requestContext = null;\n\n            // Act\n            IHttpHandler handler = product.GetHttpHandler(requestContext);\n\n            // Assert\n            HttpRouteExceptionHandler typedHandler = Assert.IsType<HttpRouteExceptionHandler>(handler);\n            Assert.Same(expectedExceptionInfo, typedHandler.ExceptionInfo);\n        }\n\n        private static ExceptionDispatchInfo CreateExceptionInfo()\n        {\n            return ExceptionDispatchInfo.Capture(new Exception());\n        }\n\n        private static HttpRouteExceptionRouteHandler CreateProductUnderTest(ExceptionDispatchInfo exceptionInfo)\n        {\n            return new HttpRouteExceptionRouteHandler(exceptionInfo);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.WebHost.Test/Routing/HttpWebRouteTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Net.Http;\nusing System.Runtime.ExceptionServices;\nusing System.Web.Http.Routing;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.WebHost.Routing\n{\n    public class HttpWebRouteTests\n    {\n        [Fact]\n        public void GetRouteData_IfHttpRouteGetRouteDataThrows_RoutesToExceptionHandler()\n        {\n            // Arrange\n            Exception expectedException = CreateException();\n            IHttpRoute route = CreateThrowingRoute(expectedException);\n\n            HttpWebRoute product = CreateProductUnderTest(route);\n\n            HttpRequestBase requestBase = CreateStubRequestBase(\"GET\");\n            HttpContextBase contextBase = CreateStubContextBase(requestBase);\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                contextBase.SetHttpRequestMessage(request);\n\n                // Act\n                RouteData routeData = product.GetRouteData(contextBase);\n\n                // Assert\n                Assert.NotNull(routeData);\n                Assert.Same(product, routeData.Route);\n                HttpRouteExceptionRouteHandler typedHandler = Assert.IsType<HttpRouteExceptionRouteHandler>(routeData.RouteHandler);\n                ExceptionDispatchInfo exceptionInfo = typedHandler.ExceptionInfo;\n                Assert.NotNull(exceptionInfo); // Guard\n                Assert.Same(expectedException, exceptionInfo.SourceException);\n            }\n        }\n\n        private static Exception CreateException()\n        {\n            return new NotFiniteNumberException();\n        }\n\n        private static HttpWebRoute CreateProductUnderTest(IHttpRoute httpRoute)\n        {\n            return new HttpWebRoute(null, null, null, null, null, httpRoute);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private static HttpContextBase CreateStubContextBase(HttpRequestBase request)\n        {\n            Mock<HttpContextBase> mock = new Mock<HttpContextBase>();\n            mock.SetupGet(m => m.Request).Returns(request);\n            IDictionary items = new Dictionary<object, object>();\n            mock.SetupGet(m => m.Items).Returns(items);\n            return mock.Object;\n        }\n\n        private static HttpRequestBase CreateStubRequestBase(string httpMethod)\n        {\n            return new Mock<HttpRequestBase>().Object;\n        }\n\n        private static IHttpRoute CreateThrowingRoute(Exception exception)\n        {\n            Mock<IHttpRoute> mock = new Mock<IHttpRoute>(MockBehavior.Strict);\n            mock\n                .Setup(m => m.GetRouteData(It.IsAny<string>(), It.IsAny<HttpRequestMessage>()))\n                .Throws(exception);\n            return mock.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.WebHost.Test/SeekableBufferedRequestStreamTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.WebHost\n{\n    public class SeekableBufferedRequestStreamTest\n    {\n        private const string Content = \"Hello, World!\";\n\n        /// <summary>\n        /// Chosen to require multiple reads.\n        /// </summary>\n        private const int BufferSize = 3;\n\n        [Fact]\n        public void ReadToEnd_WithRead_SwapsStreams()\n        {\n            // Arrange\n            var nonSeekable = CreateNonSeekableStream(Content);\n            var seekable = CreateSeekableStream(Content);\n            var stream = CreateStream(nonSeekable, seekable);\n\n            // Act\n            byte[] buffer = new byte[BufferSize];\n            while (stream.Read(buffer, 0, buffer.Length) > 0)\n            {\n                // Guard\n                Assert.Same(nonSeekable, stream.InnerStream);\n            }\n\n            // Assert\n            Assert.Same(seekable, stream.InnerStream);\n        }\n\n        [Fact]\n        public void ReadToEnd_WithBeginRead_SwapsStreams()\n        {\n            // Arrange\n            var nonSeekable = CreateNonSeekableStream(Content);\n            var seekable = CreateSeekableStream(Content);\n            var stream = CreateStream(nonSeekable, seekable);\n\n            // Act\n            byte[] buffer = new byte[BufferSize];\n            while (stream.EndRead(stream.BeginRead(buffer, 0, buffer.Length, null, null)) > 0)\n            {\n                // Guard\n                Assert.Same(nonSeekable, stream.InnerStream);\n            }\n\n            // Assert\n            Assert.Same(seekable, stream.InnerStream);\n        }\n\n        [Fact]\n        public async Task ReadToEnd_WithReadAsync_SwapsStreams()\n        {\n            // Arrange\n            var nonSeekable = CreateNonSeekableStream(Content);\n            var seekable = CreateSeekableStream(Content);\n            var stream = CreateStream(nonSeekable, seekable);\n\n            // Act\n            byte[] buffer = new byte[BufferSize];\n            while (await stream.ReadAsync(buffer, 0, buffer.Length) > 0)\n            {\n                // Guard\n                Assert.Same(nonSeekable, stream.InnerStream);\n            }\n\n            // Assert\n            Assert.Same(seekable, stream.InnerStream);\n        }\n\n        [Fact]\n        public void ReadToEnd_WithReadByte_SwapsStreams()\n        {\n            // Arrange\n            var nonSeekable = CreateNonSeekableStream(Content);\n            var seekable = CreateSeekableStream(Content);\n            var stream = CreateStream(nonSeekable, seekable);\n\n            // Act\n            while (stream.ReadByte() > 0)\n            {\n                // Guard\n                Assert.Same(nonSeekable, stream.InnerStream);\n            }\n\n            // Assert\n            Assert.Same(seekable, stream.InnerStream);\n        }\n\n        [Fact]\n        public void SwapStream_PreservesPosition()\n        {\n            // Arrange\n            var nonSeekable = CreateNonSeekableStream(Content);\n            var seekable = CreateSeekableStream(Content);\n            var stream = CreateStream(nonSeekable, seekable);\n\n            stream.ReadByte();\n\n            // Guard\n            Assert.Same(nonSeekable, stream.InnerStream);\n            Assert.Equal(1L, stream.Position);\n\n            stream.Seek(2L, SeekOrigin.Begin);\n\n            // Assert\n            Assert.Equal(2L, stream.Position);\n            Assert.Same(seekable, stream.InnerStream);\n        }\n\n        [Fact]\n        public void Seek_SwapsStreams()\n        {\n            // Arrange\n            var nonSeekable = CreateNonSeekableStream(Content);\n            var seekable = CreateSeekableStream(Content);\n            var stream = CreateStream(nonSeekable, seekable);\n\n            // Guard\n            Assert.Same(nonSeekable, stream.InnerStream);\n\n            // Act\n            stream.Seek(1L, SeekOrigin.Begin);\n\n            // Assert\n            Assert.Same(seekable, stream.InnerStream);\n        }\n\n        [Fact]\n        public void Seek_NoOpBegin()\n        {\n            // Arrange\n            var nonSeekable = CreateNonSeekableStream(Content);\n            var seekable = CreateSeekableStream(Content);\n            var stream = CreateStream(nonSeekable, seekable);\n\n            for (int i = 0; i < 3; i++)\n            {\n                stream.ReadByte();\n            }\n\n            // Act\n            stream.Seek(3L, SeekOrigin.Begin);\n\n            // Assert\n            Assert.Same(nonSeekable, stream.InnerStream);\n        }\n\n        [Fact]\n        public void Seek_NoOpCurent()\n        {\n            // Arrange\n            var nonSeekable = CreateNonSeekableStream(Content);\n            var seekable = CreateSeekableStream(Content);\n            var stream = CreateStream(nonSeekable, seekable);\n\n            for (int i = 0; i < 3; i++)\n            {\n                stream.ReadByte();\n            }\n\n            // Act\n            stream.Seek(0L, SeekOrigin.Current);\n\n            // Assert\n            Assert.Same(nonSeekable, stream.InnerStream);\n        }\n\n        [Fact]\n        public void Seek_NoOpEnd()\n        {\n            // Arrange\n            var nonSeekable = CreateNonSeekableStream(Content);\n            var seekable = CreateSeekableStream(Content);\n            var stream = CreateStream(nonSeekable, seekable);\n\n            for (int i = 0; i < 3; i++)\n            {\n                stream.ReadByte();\n            }\n\n            // Act\n            stream.Seek(stream.Position - stream.Length, SeekOrigin.End);\n\n            // Assert\n            Assert.Same(nonSeekable, stream.InnerStream);\n        }\n\n        [Fact]\n        public void Dispose_DoesNotDisposeInnerStreams()\n        {\n            // Arrange\n            var nonSeekable = CreateNonSeekableStream(Content);\n            var seekable = CreateSeekableStream(Content);\n            var stream = CreateStream(nonSeekable, seekable);\n\n            // Act\n            stream.Dispose();\n\n            // Assert\n            Assert.False(stream.CanRead);\n            Assert.True(nonSeekable.CanRead);\n            Assert.True(seekable.CanRead);\n        }\n\n        [Fact]\n        public void Seek_ThrowsOnInvalidSeekOrigin()\n        {\n            // Arrange\n            var nonSeekable = CreateNonSeekableStream(Content);\n            var seekable = CreateSeekableStream(Content);\n            var stream = CreateStream(nonSeekable, seekable);\n\n            var origin = (SeekOrigin)5;\n\n            var message = \n                \"The value of argument 'origin' (\" + (int)origin + \") is invalid for Enum type \" +\n                \"'SeekOrigin'.\" + Environment.NewLine +\n                \"Parameter name: origin\";\n\n            // Act & Assert\n            Assert.Throws<InvalidEnumArgumentException>(() => stream.Seek(0L, origin), message);\n        }\n\n        private Stream CreateSeekableStream(string content)\n        {\n            return new MemoryStream(Encoding.UTF8.GetBytes(content));\n        }\n\n        private Stream CreateNonSeekableStream(string content)\n        {\n            return new NonSeekableStream(Encoding.UTF8.GetBytes(content));\n        }\n\n        private AccessibleStreamWrapper CreateStream(Stream stream1, Stream stream2)\n        {\n            // Guards\n            Assert.False(stream1.CanSeek);\n            Assert.True(stream2.CanSeek);\n\n            var request = new Mock<HttpRequestBase>();\n            request.Setup(r => r.GetBufferedInputStream()).Returns(stream1);\n            request.SetupGet(r => r.InputStream).Returns(stream2);\n\n            return new AccessibleStreamWrapper(request.Object);\n        }\n\n        private class AccessibleStreamWrapper : SeekableBufferedRequestStream\n        {\n            public AccessibleStreamWrapper(HttpRequestBase request)\n                : base(request)\n            {\n            }\n\n            public new Stream InnerStream\n            {\n                get\n                {\n                    return base.InnerStream;\n                }\n            }\n        }\n\n        private class NonSeekableStream : MemoryStream\n        {\n            public NonSeekableStream()\n            {\n            }\n\n            public NonSeekableStream(byte[] bytes)\n                : base(bytes)\n            {\n            }\n\n            public override bool CanSeek\n            {\n                get\n                {\n                    return false;\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.WebHost.Test/SuppressFormsAuthRedirectHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.WebHost\n{\n    public class SuppressFormsAuthRedirectHelperTest\n    {\n        [Theory]\n        [InlineData(\"false\", false)]\n        [InlineData(\"true\", true)]\n        [InlineData(\"\", true)]\n        [InlineData(\"foo\", true)]\n        public void GetDisabled_ParsesAppSettings(string setting, bool expected)\n        {\n            Assert.Equal(expected, SuppressFormsAuthRedirectHelper.GetEnabled(new NameValueCollection() { { SuppressFormsAuthRedirectHelper.AppSettingsSuppressFormsAuthenticationRedirectKey, setting } }));\n        }\n\n        [Fact]\n        public void PreApplicationStartCode_IsValid()\n        {\n#pragma warning disable 0618 // System.Web.Http.WebHost.PreApplicationStartCode is obsolete\n            Type preApplicationStartType = typeof(PreApplicationStartCode);\n#pragma warning restore\n            PreAppStartTestHelper.TestPreAppStartClass(preApplicationStartType);\n            object[] attrs = preApplicationStartType.GetCustomAttributes(typeof(ObsoleteAttribute), true);\n            Assert.Single(attrs);\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Http.WebHost.Test/System.Web.Http.WebHost.Test.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props\" Condition=\"Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" />\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" />\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{EA62944F-BD25-4730-9405-9BE8FF5BEACD}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>System.Web.Http.WebHost</RootNamespace>\n    <AssemblyName>System.Web.Http.WebHost.Test</AssemblyName>\n    <OutputPath>..\\..\\bin\\$(Configuration)\\Test\\</OutputPath>\n    <NuGetPackageImportStamp>\n    </NuGetPackageImportStamp>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Castle.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Castle.Core.5.1.1\\lib\\net462\\Castle.Core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Moq, Version=4.18.0.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Moq.4.18.4\\lib\\net462\\Moq.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Newtonsoft.Json.13.0.1\\lib\\net45\\Newtonsoft.Json.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Net.Http\" />\n    <Reference Include=\"System.Net.Http.WebRequest\" />\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"System.Xml\" />\n    <Reference Include=\"xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.abstractions.2.0.3\\lib\\net35\\xunit.abstractions.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.assert, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.assert.2.4.2\\lib\\netstandard1.1\\xunit.assert.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.core, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.core.2.4.2\\lib\\net452\\xunit.core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.execution.desktop, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.execution.2.4.2\\lib\\net452\\xunit.execution.desktop.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"BatchingTest.cs\" />\n    <Compile Include=\"Routing\\HttpRouteExceptionHandlerTests.cs\" />\n    <Compile Include=\"Routing\\HttpRouteExceptionRouteHandlerTests.cs\" />\n    <Compile Include=\"Routing\\HttpWebRouteTests.cs\" />\n    <Compile Include=\"SeekableBufferedRequestStreamTest.cs\" />\n    <Compile Include=\"WebHostExceptionCatchBlocksTests.cs\" />\n    <Compile Include=\"WebHostExceptionHandlerTests.cs\" />\n    <Compile Include=\"WebHostHttpRequestContextTests.cs\" />\n    <Compile Include=\"GlobalConfigurationTest.cs\" />\n    <Compile Include=\"HttpRequestMessageExtensions.cs\" />\n    <Compile Include=\"Routing\\HttpContextBaseExtensionsTest.cs\" />\n    <Compile Include=\"Routing\\HttpRequestMessageWrapperTest.cs\" />\n    <Compile Include=\"Routing\\HostedHttpRouteCollectionTest.cs\" />\n    <Compile Include=\"WebHostBufferPolicySelectorTest.cs\" />\n    <Compile Include=\"HttpControllerHandlerTest.cs\" />\n    <Compile Include=\"RouteCollectionExtensionsTest.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"Routing\\HostedUrlHelperTest.cs\" />\n    <Compile Include=\"SuppressFormsAuthRedirectHelperTest.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\..\\src\\System.Net.Http.Formatting\\System.Net.Http.Formatting.csproj\">\n      <Project>{668E9021-CE84-49D9-98FB-DF125A9FCDB0}</Project>\n      <Name>System.Net.Http.Formatting</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Http.Owin\\System.Web.Http.Owin.csproj\">\n      <Project>{66dd7cd7-c68f-4d0e-9f3d-3b58c49d1467}</Project>\n      <Name>System.Web.Http.Owin</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Http.WebHost\\System.Web.Http.WebHost.csproj\">\n      <Project>{A0187BC2-8325-4BB2-8697-7F955CF4173E}</Project>\n      <Name>System.Web.Http.WebHost</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Http\\System.Web.Http.csproj\">\n      <Project>{DDC1CE0C-486E-4E35-BB3B-EAB61F8F9440}</Project>\n      <Name>System.Web.Http</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Mvc\\System.Web.Mvc.csproj\">\n      <Project>{3D3FFD8A-624D-4E9B-954B-E1C105507975}</Project>\n      <Name>System.Web.Mvc</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\">\n      <Project>{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}</Project>\n      <Name>Microsoft.TestCommon</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <Service Include=\"{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Analyzer Include=\"..\\..\\packages\\xunit.analyzers.1.1.0\\analyzers\\dotnet\\cs\\xunit.analyzers.dll\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  <Target Name=\"EnsureNuGetPackageBuildImports\" BeforeTargets=\"PrepareForBuild\">\n    <PropertyGroup>\n      <ErrorText>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}.</ErrorText>\n    </PropertyGroup>\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props'))\" />\n  </Target>\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" />\n</Project>"
  },
  {
    "path": "test/System.Web.Http.WebHost.Test/WebHostBufferPolicySelectorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Text;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.WebHost\n{\n    public class WebHostBufferPolicySelectorTest\n    {\n        private const string testString = \"testString\";\n\n        public static TheoryDataSet<HttpContent, bool> OutputBufferingTestData\n        {\n            get\n            {\n                Mock<Stream> mockStream = new Mock<Stream>() { CallBase = true };\n                return new TheoryDataSet<HttpContent, bool>()\n                {\n                    // Known length HttpContents other than OC should not buffer\n                    { new StringContent(testString), false },\n                    { new ByteArrayContent(Encoding.UTF8.GetBytes(testString)), false },\n                    { new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes(testString))), false },\n\n                    // StreamContent (unknown length) should not buffer\n                    { new StreamContent(mockStream.Object), false },\n\n                    // PushStreamContent (unknown length) should not buffer\n                    { new PushStreamContent((stream, headers, context) => {}), false },\n\n                    // ObjectContent (unknown length) should buffer\n                    { new ObjectContent<string>(testString, new XmlMediaTypeFormatter()), true }\n                };\n            }\n        }\n\n        public static TheoryDataSet<HttpContent> OutputBufferingTestData_NoExpectedResult\n        {\n            get\n            {\n                var dataSet = new TheoryDataSet<HttpContent>();\n                foreach (var item in OutputBufferingTestData)\n                {\n                    dataSet.Add((HttpContent)item[0]);\n                }\n\n                return dataSet;\n            }\n        }\n\n        [Fact]\n        void UseBufferedInputStream_Returns_True()\n        {\n            // Arrange\n            Mock<HttpContextBase> mockContext = new Mock<HttpContextBase>() { CallBase = true };\n\n            // Act & Assert\n            Assert.True(new WebHostBufferPolicySelector().UseBufferedInputStream(mockContext.Object));\n        }\n\n        [Fact]\n        void UseBufferedInputStream_ThrowsOnNull()\n        {\n            WebHostBufferPolicySelector selector = new WebHostBufferPolicySelector();\n            Assert.ThrowsArgumentNull(() => selector.UseBufferedInputStream(null), \"hostContext\");\n        }\n\n        [Fact]\n        void UseBufferedInputStream_Can_Be_Overridden()\n        {\n            // Arrange\n            Mock<WebHostBufferPolicySelector> mockSelector = new Mock<WebHostBufferPolicySelector>();\n            mockSelector.Setup((w) => w.UseBufferedInputStream(It.IsAny<HttpContextBase>())).Returns(false);\n            Mock<HttpContextBase> mockContext = new Mock<HttpContextBase>() { CallBase = true };\n\n            // Act & Assert\n            Assert.False(mockSelector.Object.UseBufferedInputStream(mockContext.Object));\n        }\n\n        [Fact]\n        public void UseBufferedOutputStream_ThrowsOnNull()\n        {\n            WebHostBufferPolicySelector selector = new WebHostBufferPolicySelector();\n            Assert.ThrowsArgumentNull(() => selector.UseBufferedOutputStream(null), \"response\");\n        }\n\n        [Theory]\n        [PropertyData(\"OutputBufferingTestData\")]\n        public void UseBufferedOutputStream_ReturnsCorrectValue(HttpContent content, bool expectedResult)\n        {\n            // Arrange\n            WebHostBufferPolicySelector selector = new WebHostBufferPolicySelector();\n            HttpResponseMessage response = new HttpResponseMessage();\n            response.Content = content;\n\n            // Act\n            bool actualResult = selector.UseBufferedOutputStream(response);\n\n            // Assert\n            Assert.Equal(expectedResult, actualResult);\n        }\n\n        [Theory]\n        [PropertyData(\"OutputBufferingTestData_NoExpectedResult\")]\n        public void UseBufferedOutputStream_CausesContentLengthHeaderToBeSet(HttpContent content)\n        {\n            // Arrange & Act\n            WebHostBufferPolicySelector selector = new WebHostBufferPolicySelector();\n            HttpResponseMessage response = new HttpResponseMessage();\n            response.Content = content;\n\n            selector.UseBufferedOutputStream(response);\n\n            IEnumerable<string> contentLengthEnumerable;\n            bool isContentLengthInHeaders = content.Headers.TryGetValues(\"Content-Length\", out contentLengthEnumerable);\n            string[] contentLengthStrings = isContentLengthInHeaders ? contentLengthEnumerable.ToArray() : new string[0];\n            long? contentLength = content.Headers.ContentLength;\n\n            // Assert\n            if (contentLength.HasValue && contentLength.Value >= 0)\n            {\n                // Setting the header is HttpContentHeader's responsibility, but we assert\n                // it has happened here because it is UseBufferedOutputStream's responsibility\n                // to cause that to happen. HttpControllerHandler relies on this.\n                Assert.True(isContentLengthInHeaders);\n                Assert.Equal(contentLength.Value, long.Parse(contentLengthStrings[0]));\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.WebHost.Test/WebHostExceptionCatchBlocksTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http.ExceptionHandling;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Http.WebHost\n{\n    public class WebHostExceptionCatchBlocksTests\n    {\n        [Fact]\n        public void HttpControllerHandlerBufferContent_IsSpecifiedValue()\n        {\n            // Act\n            ExceptionContextCatchBlock catchBlock = WebHostExceptionCatchBlocks.HttpControllerHandlerBufferContent;\n\n            // Assert\n            ExceptionContextCatchBlock expected =\n                new ExceptionContextCatchBlock(\"HttpControllerHandler.BufferContent\", isTopLevel: true,\n                    callsHandler: true);\n            AssertEqual(expected, catchBlock);\n        }\n\n        [Fact]\n        public void HttpControllerHandlerBufferContent_IsSameInstance()\n        {\n            // Arrange\n            ExceptionContextCatchBlock first = WebHostExceptionCatchBlocks.HttpControllerHandlerBufferContent;\n\n            // Act\n            ExceptionContextCatchBlock second = WebHostExceptionCatchBlocks.HttpControllerHandlerBufferContent;\n\n            // Assert\n            Assert.Same(first, second);\n        }\n\n        [Fact]\n        public void HttpControllerHandlerBufferError_IsSpecifiedValue()\n        {\n            // Act\n            ExceptionContextCatchBlock catchBlock = WebHostExceptionCatchBlocks.HttpControllerHandlerBufferError;\n\n            // Assert\n            ExceptionContextCatchBlock expected =\n                new ExceptionContextCatchBlock(\"HttpControllerHandler.BufferError\", isTopLevel: true,\n                    callsHandler: false);\n            AssertEqual(expected, catchBlock);\n        }\n\n        [Fact]\n        public void HttpControllerHandlerBufferError_IsSameInstance()\n        {\n            // Arrange\n            ExceptionContextCatchBlock first = WebHostExceptionCatchBlocks.HttpControllerHandlerBufferError;\n\n            // Act\n            ExceptionContextCatchBlock second = WebHostExceptionCatchBlocks.HttpControllerHandlerBufferError;\n\n            // Assert\n            Assert.Same(first, second);\n        }\n\n        [Fact]\n        public void HttpControllerHandlerComputeContentLength_IsSpecifiedValue()\n        {\n            // Act\n            ExceptionContextCatchBlock catchBlock = WebHostExceptionCatchBlocks.HttpControllerHandlerComputeContentLength;\n\n            // Assert\n            ExceptionContextCatchBlock expected =\n                new ExceptionContextCatchBlock(\"HttpControllerHandler.ComputeContentLength\", isTopLevel: true,\n                    callsHandler: false);\n            AssertEqual(expected, catchBlock);\n        }\n\n        [Fact]\n        public void HttpControllerHandlerComputeContentLength_IsSameInstance()\n        {\n            // Arrange\n            ExceptionContextCatchBlock first = WebHostExceptionCatchBlocks.HttpControllerHandlerComputeContentLength;\n\n            // Act\n            ExceptionContextCatchBlock second = WebHostExceptionCatchBlocks.HttpControllerHandlerComputeContentLength;\n\n            // Assert\n            Assert.Same(first, second);\n        }\n\n        [Fact]\n        public void HttpControllerHandlerStreamContent_IsSpecifiedValue()\n        {\n            // Act\n            ExceptionContextCatchBlock catchBlock = WebHostExceptionCatchBlocks.HttpControllerHandlerStreamContent;\n\n            // Assert\n            ExceptionContextCatchBlock expected =\n                new ExceptionContextCatchBlock(\"HttpControllerHandler.StreamContent\", isTopLevel: true,\n                    callsHandler: false);\n            AssertEqual(expected, catchBlock);\n        }\n\n        [Fact]\n        public void HttpControllerHandlerStreamContent_IsSameInstance()\n        {\n            // Arrange\n            ExceptionContextCatchBlock first = WebHostExceptionCatchBlocks.HttpControllerHandlerStreamContent;\n\n            // Act\n            ExceptionContextCatchBlock second = WebHostExceptionCatchBlocks.HttpControllerHandlerStreamContent;\n\n            // Assert\n            Assert.Same(first, second);\n        }\n\n        [Fact]\n        public void HttpWebRoute_IsSpecifiedValue()\n        {\n            // Act\n            ExceptionContextCatchBlock catchBlock = WebHostExceptionCatchBlocks.HttpWebRoute;\n\n            // Assert\n            ExceptionContextCatchBlock expected =\n                new ExceptionContextCatchBlock(\"HttpWebRoute\", isTopLevel: true, callsHandler: true);\n            AssertEqual(expected, catchBlock);\n        }\n\n        [Fact]\n        public void HttpWebRoute_IsSameInstance()\n        {\n            // Arrange\n            ExceptionContextCatchBlock first = WebHostExceptionCatchBlocks.HttpWebRoute;\n\n            // Act\n            ExceptionContextCatchBlock second = WebHostExceptionCatchBlocks.HttpWebRoute;\n\n            // Assert\n            Assert.Same(first, second);\n        }\n\n        private static void AssertEqual(ExceptionContextCatchBlock expected, ExceptionContextCatchBlock actual)\n        {\n            if (expected == null)\n            {\n                Assert.Null(actual);\n                return;\n            }\n\n            Assert.NotNull(actual);\n            Assert.Equal(expected.Name, actual.Name);\n            Assert.Equal(expected.IsTopLevel, actual.IsTopLevel);\n            Assert.Equal(expected.CallsHandler, actual.CallsHandler);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.WebHost.Test/WebHostExceptionHandlerTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.ExceptionHandling;\nusing System.Web.Http.Results;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.WebHost\n{\n    public class WebHostExceptionHandlerTests\n    {\n        [Fact]\n        public void InnerHandler_IsSpecifiedInstance()\n        {\n            // Arrange\n            IExceptionHandler expectedHandler = CreateDummyHandler();\n            WebHostExceptionHandler product = CreateProductUnderTest(expectedHandler);\n\n            // Act\n            IExceptionHandler handler = product.InnerHandler;\n\n            // Assert\n            Assert.Same(expectedHandler, handler);\n        }\n\n        [Fact]\n        public void HandleAsync_DelegatesToInnerHandler()\n        {\n            // Arrange\n            Task expectedTask = CreateTask();\n            Mock<IExceptionHandler> mock = new Mock<IExceptionHandler>();\n            mock\n                .Setup(h => h.HandleAsync(It.IsAny<ExceptionHandlerContext>(), It.IsAny<CancellationToken>()))\n                .Returns(expectedTask);\n            IExceptionHandler innerHandler = mock.Object;\n\n            IExceptionHandler product = CreateProductUnderTest(innerHandler);\n\n            ExceptionHandlerContext expectedContext = CreateContext();\n\n            using (CancellationTokenSource tokenSource = CreateCancellationTokenSource())\n            {\n                CancellationToken expectedCancellationToken = tokenSource.Token;\n\n                // Act\n                Task task = product.HandleAsync(expectedContext, expectedCancellationToken);\n\n                // Assert\n                mock.Verify(h => h.HandleAsync(expectedContext, expectedCancellationToken), Times.Once());\n                Assert.Same(expectedTask, task);\n            }\n        }\n\n        [Fact]\n        public void HandleAsync_IfContextIsNull_Throws()\n        {\n            // Arrange\n            IExceptionHandler innerHandler = CreateDummyHandler();\n            IExceptionHandler product = CreateProductUnderTest(innerHandler);\n\n            ExceptionHandlerContext context = null;\n            CancellationToken cancellationToken = CancellationToken.None;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => product.HandleAsync(context, cancellationToken), \"context\");\n        }\n\n        [Fact]\n        public async Task HandleAsync_IfCatchBlockIsWebHostBufferedContent_HandlesWithCustomException()\n        {\n            IExceptionHandler innerHandler = CreateDummyHandler();\n            IExceptionHandler product = CreateProductUnderTest(innerHandler);\n\n            // Arrange\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            using (HttpResponseMessage originalResponse = CreateResponse())\n            {\n                originalResponse.Content = new StringContent(\"Error\");\n                originalResponse.Content.Headers.ContentType = new MediaTypeHeaderValue(\"text/plain\");\n                expectedRequest.SetRequestContext(new HttpRequestContext { IncludeErrorDetail = true });\n                ExceptionHandlerContext context = CreateValidContext(expectedRequest,\n                    WebHostExceptionCatchBlocks.HttpControllerHandlerBufferContent);\n                context.ExceptionContext.Response = originalResponse;\n                CancellationToken cancellationToken = CancellationToken.None;\n\n                // Act\n                await product.HandleAsync(context, cancellationToken);\n\n                // Assert\n                IHttpActionResult result = context.Result;\n                ResponseMessageResult typedResult = Assert.IsType<ResponseMessageResult>(result);\n\n                using (HttpResponseMessage response = typedResult.Response)\n                using (HttpResponseMessage expectedResponse = expectedRequest.CreateErrorResponse(\n                    HttpStatusCode.InternalServerError, new InvalidOperationException(\"The 'StringContent' type \" +\n                        \"failed to serialize the response body for content type 'text/plain'.\",\n                        context.ExceptionContext.Exception)))\n                {\n                    AssertErrorResponse(expectedResponse, response);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task HandleAsync_IfCatchBlockIsWebHostBufferedContent_WithoutContentType_HandlesWithCustomException()\n        {\n            IExceptionHandler innerHandler = CreateDummyHandler();\n            IExceptionHandler product = CreateProductUnderTest(innerHandler);\n\n            // Arrange\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            using (HttpResponseMessage originalResponse = CreateResponse())\n            {\n                originalResponse.Content = new StringContent(\"Error\");\n                originalResponse.Content.Headers.ContentType = null;\n                expectedRequest.SetRequestContext(new HttpRequestContext { IncludeErrorDetail = true });\n                ExceptionHandlerContext context = CreateValidContext(expectedRequest,\n                    WebHostExceptionCatchBlocks.HttpControllerHandlerBufferContent);\n                context.ExceptionContext.Response = originalResponse;\n                CancellationToken cancellationToken = CancellationToken.None;\n\n                // Act\n                await product.HandleAsync(context, cancellationToken);\n\n                // Assert\n                IHttpActionResult result = context.Result;\n                ResponseMessageResult typedResult = Assert.IsType<ResponseMessageResult>(result);\n\n                using (HttpResponseMessage response = typedResult.Response)\n                using (HttpResponseMessage expectedResponse = expectedRequest.CreateErrorResponse(\n                    HttpStatusCode.InternalServerError, new InvalidOperationException(\n                        \"The 'StringContent' type failed to serialize the response body.\",\n                        context.ExceptionContext.Exception)))\n                {\n                    AssertErrorResponse(expectedResponse, response);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task HandleAsync_IfCatchBlockIsWebHostBufferedContent_WithFailedNegotiation_HandlesWithCustomException()\n        {\n            IExceptionHandler innerHandler = CreateDummyHandler();\n            IExceptionHandler product = CreateProductUnderTest(innerHandler);\n\n            // Arrange\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            using (HttpResponseMessage originalResponse = CreateResponse())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            {\n                configuration.Formatters.Clear();\n\n                originalResponse.Content = new StringContent(\"Error\");\n                expectedRequest.SetRequestContext(new HttpRequestContext\n                {\n                    IncludeErrorDetail = true,\n                    Configuration = configuration\n                });\n                ExceptionHandlerContext context = CreateValidContext(expectedRequest,\n                    WebHostExceptionCatchBlocks.HttpControllerHandlerBufferContent);\n                context.ExceptionContext.Response = originalResponse;\n                CancellationToken cancellationToken = CancellationToken.None;\n\n                // Act\n                await product.HandleAsync(context, cancellationToken);\n\n                // Assert\n                IHttpActionResult result = context.Result;\n                ResponseMessageResult typedResult = Assert.IsType<ResponseMessageResult>(result);\n                using (HttpResponseMessage response = typedResult.Response)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n                    Assert.Null(response.Content);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public async Task HandleAsync_IfCatchBlockIsWebHostBufferedContent_WithCreateException_HandlesWithCustomException()\n        {\n            IExceptionHandler innerHandler = CreateDummyHandler();\n            IExceptionHandler product = CreateProductUnderTest(innerHandler);\n\n            // Arrange\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            using (HttpResponseMessage originalResponse = CreateResponse())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            {\n                configuration.Services.Clear(typeof(IContentNegotiator));\n\n                originalResponse.Content = new StringContent(\"Error\");\n                expectedRequest.SetRequestContext(new HttpRequestContext\n                {\n                    IncludeErrorDetail = true,\n                    Configuration = configuration\n                });\n                ExceptionHandlerContext context = CreateValidContext(expectedRequest,\n                    WebHostExceptionCatchBlocks.HttpControllerHandlerBufferContent);\n                context.ExceptionContext.Response = originalResponse;\n                CancellationToken cancellationToken = CancellationToken.None;\n\n                // Act\n                await product.HandleAsync(context, cancellationToken);\n\n                // Assert\n                IHttpActionResult result = context.Result;\n                ResponseMessageResult typedResult = Assert.IsType<ResponseMessageResult>(result);\n                using (HttpResponseMessage response = typedResult.Response)\n                {\n                    Assert.NotNull(response);\n                    Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);\n                    Assert.NotNull(response.Content);\n                    Assert.Equal(0L, response.Content.Headers.ContentLength);\n                    Assert.Same(expectedRequest, response.RequestMessage);\n                }\n            }\n        }\n\n        [Fact]\n        public void HandleAsync_IfCatchBlockIsWebHostBufferedContent_AndRequestIsNull_Throws()\n        {\n            IExceptionHandler innerHandler = CreateDummyHandler();\n            IExceptionHandler product = CreateProductUnderTest(innerHandler);\n\n            // Arrange\n            using (HttpResponseMessage response = CreateResponse())\n            {\n                ExceptionHandlerContext context = CreateContext(\n                    CreateMinimalValidExceptionContext(WebHostExceptionCatchBlocks.HttpControllerHandlerBufferContent));\n\n                Assert.Null(context.ExceptionContext.Request); // Guard\n                CancellationToken cancellationToken = CancellationToken.None;\n\n                // Act & Assert\n                Assert.ThrowsArgument(() => product.HandleAsync(context, cancellationToken), \"context\",\n                    \"ExceptionContext.Request must not be null.\");\n            }\n        }\n\n        [Fact]\n        public void HandleAsync_IfCatchBlockIsWebHostBufferedContent_AndResponseIsNull_Throws()\n        {\n            IExceptionHandler innerHandler = CreateDummyHandler();\n            IExceptionHandler product = CreateProductUnderTest(innerHandler);\n\n            // Arrange\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                ExceptionHandlerContext context = CreateValidContext(request,\n                    WebHostExceptionCatchBlocks.HttpControllerHandlerBufferContent);\n                Assert.Null(context.ExceptionContext.Response); // Guard\n                CancellationToken cancellationToken = CancellationToken.None;\n\n                // Act & Assert\n                Assert.ThrowsArgument(() => product.HandleAsync(context, cancellationToken), \"context\",\n                    \"ExceptionContext.Response must not be null.\");\n            }\n        }\n\n        [Fact]\n        public void HandleAsync_IfCatchBlockIsWebHostBufferedContent_AndResponseContentIsNull_Throws()\n        {\n            // Arrange\n            IExceptionHandler innerHandler = CreateDummyHandler();\n            IExceptionHandler product = CreateProductUnderTest(innerHandler);\n\n            using (HttpRequestMessage request = CreateRequest())\n            using (HttpResponseMessage response = CreateResponse())\n            {\n                ExceptionHandlerContext context = CreateValidContext(request,\n                    WebHostExceptionCatchBlocks.HttpControllerHandlerBufferContent);\n                context.ExceptionContext.Response = response;\n                Assert.Null(context.ExceptionContext.Request.Content); // Guard\n                CancellationToken cancellationToken = CancellationToken.None;\n\n                // Act & Assert\n                Assert.ThrowsArgument(() => product.HandleAsync(context, cancellationToken), \"context\",\n                    \"HttpResponseMessage.Content must not be null.\");\n            }\n        }\n\n        private static void AssertErrorResponse(HttpResponseMessage expected, HttpResponseMessage actual)\n        {\n            Assert.NotNull(expected); // Guard\n            ObjectContent<HttpError> expectedContent = Assert.IsType<ObjectContent<HttpError>>(expected.Content); // Guard\n            Assert.NotNull(expectedContent.Formatter); // Guard\n\n            Assert.NotNull(actual);\n            Assert.Equal(expected.StatusCode, actual.StatusCode);\n            ObjectContent<HttpError> actualContent = Assert.IsType<ObjectContent<HttpError>>(actual.Content);\n            Assert.NotNull(actualContent.Formatter);\n            Assert.Same(expectedContent.Formatter.GetType(), actualContent.Formatter.GetType());\n            Assert.Equal(Flatten(expectedContent.Value), Flatten(actualContent.Value));\n            Assert.Same(expected.RequestMessage, actual.RequestMessage);\n        }\n\n        private static object Flatten(object obj)\n        {\n            IDictionary<string, object> dictionary = obj as IDictionary<string, object>;\n\n            if (dictionary == null)\n            {\n                return obj;\n            }\n\n            IDictionary<string, object> flattened = new Dictionary<string, object>();\n            AddValues(dictionary, null, flattened);\n            return flattened;\n        }\n\n        private static void AddValues(IDictionary<string, object> source, string prefix,\n            IDictionary<string, object> destination)\n        {\n            foreach (string key in source.Keys)\n            {\n                object value = source[key];\n                IDictionary<string, object> dictionaryValue = value as IDictionary<string, object>;\n\n                string prefixedKey = prefix != null ? prefix + \".\" + key : key;\n\n                if (dictionaryValue != null)\n                {\n                    destination.Add(prefixedKey, \"<Flattened>\");\n                    AddValues(dictionaryValue, prefixedKey, destination);\n                }\n                else\n                {\n                    destination.Add(prefixedKey, value);\n                }\n            }\n        }\n\n        private static CancellationTokenSource CreateCancellationTokenSource()\n        {\n            return new CancellationTokenSource();\n        }\n\n        private static HttpConfiguration CreateConfiguration()\n        {\n            return new HttpConfiguration();\n        }\n\n        private static ExceptionHandlerContext CreateContext()\n        {\n            return CreateContext(new ExceptionContext(new Exception(), ExceptionCatchBlocks.HttpServer));\n        }\n\n        private static ExceptionHandlerContext CreateContext(ExceptionContext exceptionContext)\n        {\n            return new ExceptionHandlerContext(exceptionContext);\n        }\n\n        private static IExceptionHandler CreateDummyHandler()\n        {\n            return new Mock<IExceptionHandler>(MockBehavior.Strict).Object;\n        }\n\n        private static IHttpActionResult CreateDummyResult()\n        {\n            return new Mock<IHttpActionResult>(MockBehavior.Strict).Object;\n        }\n\n        private static WebHostExceptionHandler CreateProductUnderTest(IExceptionHandler innerHandler)\n        {\n            return new WebHostExceptionHandler(innerHandler);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private static HttpResponseMessage CreateResponse()\n        {\n            return new HttpResponseMessage();\n        }\n\n        private static Task CreateTask()\n        {\n            TaskCompletionSource<object> source = new TaskCompletionSource<object>();\n            return source.Task;\n        }\n\n        private static ExceptionHandlerContext CreateValidContext(HttpRequestMessage request,\n            ExceptionContextCatchBlock catchBlock)\n        {\n            return CreateContext(CreateMinimalValidExceptionContext(catchBlock, request));\n        }\n\n        private static ExceptionContext CreateMinimalValidExceptionContext(ExceptionContextCatchBlock catchBlock, HttpRequestMessage request = null)\n        {\n            return new ExceptionContext(new InvalidOperationException(), catchBlock)\n                        {\n                            Request = request,\n                        };\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.WebHost.Test/WebHostHttpRequestContextTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http;\nusing System.Security.Cryptography.X509Certificates;\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Http.WebHost\n{\n    public class WebHostHttpRequestContextTests\n    {\n        private const string Base64Certificate = \"MIFRMIFHAgEAMAIGADAJMQcwBQYAEwFhMB4XDTEzMDkxMDE5NTQ0OVoXDTM5MTIzMT\" +\n            \"IzNTk1OVowCTEHMAUGABMBYTCBBzACBgADgQAwAgYAA4EA\";\n\n        [Fact]\n        public void ContextGet_ReturnsProvidedInstance()\n        {\n            // Arrange\n            HttpContextBase expectedWebContext = CreateDummyWebContext();\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                WebHostHttpRequestContext context = CreateProductUnderTest(expectedWebContext, webRequest, request);\n\n                // Act\n                HttpContextBase webContext = context.Context;\n\n                // Assert\n                Assert.Same(expectedWebContext, webContext);\n            }\n        }\n\n        [Fact]\n        public void WebRequestGet_ReturnsProvidedInstance()\n        {\n            // Arrange\n            HttpContextBase webContext = CreateDummyWebContext();\n            HttpRequestBase expectedWebRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                WebHostHttpRequestContext context = CreateProductUnderTest(webContext, expectedWebRequest, request);\n\n                // Act\n                HttpRequestBase webRequest = context.WebRequest;\n\n                // Assert\n                Assert.Same(expectedWebRequest, webRequest);\n            }\n        }\n\n        [Fact]\n        public void RequestGet_ReturnsProvidedInstance()\n        {\n            // Arrange\n            HttpContextBase webContext = CreateDummyWebContext();\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                WebHostHttpRequestContext context = CreateProductUnderTest(webContext, webRequest, expectedRequest);\n\n                // Act\n                HttpRequestMessage request = context.Request;\n\n                // Assert\n                Assert.Same(expectedRequest, request);\n            }\n        }\n\n        [Fact]\n        public void ClientCertificateGet_ReturnsNull_WhenRequestBaseClientCertificateIsNull()\n        {\n            // Arrange\n            HttpContextBase webContext = CreateDummyWebContext();\n            Mock<HttpRequestBase> webRequestMock = new Mock<HttpRequestBase>(MockBehavior.Strict);\n            webRequestMock.Setup(r => r.ClientCertificate).Returns((HttpClientCertificate)null);\n            HttpRequestBase webRequest = webRequestMock.Object;\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n\n                // Act\n                X509Certificate2 certificate = context.ClientCertificate;\n\n                // Assert\n                Assert.Null(certificate);\n            }\n        }\n\n        [Fact]\n        public void ClientCertificateGet_ReturnsNull_WhenRequestBaseClientCertificateCertificateIsNull()\n        {\n            // Arrange\n            HttpContextBase webContext = CreateDummyWebContext();\n            HttpClientCertificate clientCertificate = CreateHttpClientCertificate(null);\n            HttpRequestBase webRequest = CreateStubWebRequest(clientCertificate);\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n\n                // Act\n                X509Certificate2 certificate = context.ClientCertificate;\n\n                // Assert\n                Assert.Null(certificate);\n            }\n        }\n\n        [Fact]\n        public void ClientCertificateGet_ReturnsNull_WhenRequestBaseClientCertificateCertificateIsEmpty()\n        {\n            // Arrange\n            HttpContextBase webContext = CreateDummyWebContext();\n            HttpClientCertificate clientCertificate = CreateHttpClientCertificate(new byte[0]);\n            HttpRequestBase webRequest = CreateStubWebRequest(clientCertificate);\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n\n                // Act\n                X509Certificate2 certificate = context.ClientCertificate;\n\n                // Assert\n                Assert.Null(certificate);\n            }\n        }\n\n        [Fact]\n        public void ClientCertificateGet_ReturnsRequestBaseClientCertificate()\n        {\n            // Arrange\n            byte[] expectedCertificateBytes = Convert.FromBase64String(Base64Certificate);\n            HttpContextBase webContext = CreateDummyWebContext();\n            HttpClientCertificate clientCertificate = CreateHttpClientCertificate(expectedCertificateBytes);\n            HttpRequestBase webRequest = CreateStubWebRequest(clientCertificate);\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n\n                // Act\n                X509Certificate2 certificate = context.ClientCertificate;\n\n                // Assert\n                Assert.NotNull(certificate);\n                Assert.Equal(expectedCertificateBytes, certificate.RawData);\n            }\n        }\n\n        [Fact]\n        public void ClientCertificateSet_UpdatesClientCertificate()\n        {\n            // Arrange\n            HttpContextBase webContext = CreateDummyWebContext();\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n                X509Certificate2 expectedCertificate = CreateCertificate();\n\n                // Act\n                context.ClientCertificate = expectedCertificate;\n\n                // Assert\n                X509Certificate2 certificate = context.ClientCertificate;\n                Assert.Same(expectedCertificate, certificate);\n            }\n        }\n\n        [Fact]\n        public void ClientCertificateSet_UpdatesClientCertificate_WhenNull()\n        {\n            // Arrange\n            HttpContextBase webContext = CreateDummyWebContext();\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n\n                // Act\n                context.ClientCertificate = null;\n\n                // Assert\n                X509Certificate2 certificate = context.ClientCertificate;\n                Assert.Null(certificate);\n            }\n        }\n\n        [Fact]\n        public void ConfigurationGet_ReturnsGlobalConfiguration_ByDefault()\n        {\n            // Arrange\n            HttpContextBase webContext = CreateDummyWebContext();\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n\n                // Act\n                HttpConfiguration configuration = context.Configuration;\n\n                // Assert\n                Assert.Same(GlobalConfiguration.Configuration, configuration);\n            }\n        }\n\n        [Fact]\n        public void ConfigurationSet_UpdatesConfiguration()\n        {\n            // Arrange\n            HttpContextBase webContext = CreateDummyWebContext();\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            using (HttpConfiguration expectedConfiguration = CreateConfiguration())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n\n                // Act\n                context.Configuration = expectedConfiguration;\n\n                // Assert\n                HttpConfiguration configuration = context.Configuration;\n                Assert.Same(expectedConfiguration, configuration);\n            }\n        }\n\n        [Fact]\n        public void ConfigurationSet_UpdatesConfiguration_WhenNull()\n        {\n            // Arrange\n            HttpContextBase webContext = CreateDummyWebContext();\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n\n                // Act\n                context.Configuration = null;\n\n                // Assert\n                HttpConfiguration configuration = context.Configuration;\n                Assert.Null(configuration);\n            }\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void IncludeErrorDetailGet_ReturnsNoCustomErrorEnabled_WhenUnconfigured(bool expectedIncludeErrorDetail)\n        {\n            // Arrange\n            Mock<HttpContextBase> webContextMock = new Mock<HttpContextBase>(MockBehavior.Strict);\n            webContextMock.Setup(r => r.IsCustomErrorEnabled).Returns(!expectedIncludeErrorDetail);\n            HttpContextBase webContext = webContextMock.Object;\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n                context.Configuration = null;\n\n                // Act\n                bool includeErrorDetail = context.IncludeErrorDetail;\n\n                // Assert\n                Assert.Equal(expectedIncludeErrorDetail, includeErrorDetail);\n            }\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void IncludeErrorDetailGet_ReturnsNoCustomErrorEnabled_ForDefaultPolicy(bool expectedIncludeErrorDetail)\n        {\n            // Arrange\n            Mock<HttpContextBase> webContextMock = new Mock<HttpContextBase>(MockBehavior.Strict);\n            webContextMock.Setup(r => r.IsCustomErrorEnabled).Returns(!expectedIncludeErrorDetail);\n            HttpContextBase webContext = webContextMock.Object;\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n                context.Configuration = configuration;\n                configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Default;\n\n                // Act\n                bool includeErrorDetail = context.IncludeErrorDetail;\n\n                // Assert\n                Assert.Equal(expectedIncludeErrorDetail, includeErrorDetail);\n            }\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void IncludeErrorDetailGet_ReturnsIsLocal_ForLocalOnlyPolicy(bool expectedIncludeErrorDetail)\n        {\n            // Arrange\n            HttpContextBase webContext = CreateDummyWebContext();\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n                context.Configuration = configuration;\n                configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.LocalOnly;\n                context.IsLocal = expectedIncludeErrorDetail;\n\n                // Act\n                bool includeErrorDetail = context.IncludeErrorDetail;\n\n                // Assert\n                Assert.Equal(expectedIncludeErrorDetail, includeErrorDetail);\n            }\n        }\n\n        [Fact]\n        public void IncludeErrorDetailGet_ReturnsTrue_ForAlwaysPolicy()\n        {\n            // Arrange\n            HttpContextBase webContext = CreateDummyWebContext();\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n                context.Configuration = configuration;\n                configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;\n\n                // Act\n                bool includeErrorDetail = context.IncludeErrorDetail;\n\n                // Assert\n                Assert.True(includeErrorDetail);\n            }\n        }\n\n        [Fact]\n        public void IncludeErrorDetailGet_ReturnsFalse_ForNeverPolicy()\n        {\n            // Arrange\n            HttpContextBase webContext = CreateDummyWebContext();\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n                context.Configuration = configuration;\n                configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Never;\n\n                // Act\n                bool includeErrorDetail = context.IncludeErrorDetail;\n\n                // Assert\n                Assert.False(includeErrorDetail);\n            }\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void IncludeErrorDetailSet_UpdatesIncludeErrorDetail(bool expectedIncludeErrorDetail)\n        {\n            // Arrange\n            HttpContextBase webContext = CreateDummyWebContext();\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n\n                // Act\n                context.IncludeErrorDetail = expectedIncludeErrorDetail;\n\n                // Assert\n                bool includeErrorDetail = context.IncludeErrorDetail;\n                Assert.Equal(expectedIncludeErrorDetail, includeErrorDetail);\n            }\n        }\n\n        [Theory]\n        [InlineData(true, IncludeErrorDetailPolicy.Never)]\n        [InlineData(false, IncludeErrorDetailPolicy.Always)]\n        public void IncludeErrorDetailSet_OverridesPolicy(bool expected, IncludeErrorDetailPolicy policy)\n        {\n            // Arrange\n            HttpContextBase webContext = CreateDummyWebContext();\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n                context.Configuration = configuration;\n                configuration.IncludeErrorDetailPolicy = policy;\n\n                // Act\n                context.IncludeErrorDetail = expected;\n\n                // Assert\n                bool includeErrorDetail = context.IncludeErrorDetail;\n                Assert.Equal(expected, includeErrorDetail);\n            }\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void IncludeErrorDetailGet_ReturnsFirstObservedValue(bool expectedIncludeErrorDetail)\n        {\n            // Arrange\n            HttpContextBase webContext = CreateDummyWebContext();\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            using (HttpConfiguration configuration = CreateConfiguration())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n                context.Configuration = configuration;\n                configuration.IncludeErrorDetailPolicy = expectedIncludeErrorDetail\n                    ? IncludeErrorDetailPolicy.Always : IncludeErrorDetailPolicy.Never;\n                bool ignore = context.IncludeErrorDetail;\n                configuration.IncludeErrorDetailPolicy = expectedIncludeErrorDetail\n                    ? IncludeErrorDetailPolicy.Never : IncludeErrorDetailPolicy.Always;\n\n                // Act\n                bool includeErrorDetail = context.IncludeErrorDetail;\n\n                // Assert\n                Assert.Equal(expectedIncludeErrorDetail, includeErrorDetail);\n            }\n        }\n\n        [Fact]\n        public void IsLocalGet_ReturnsFalse_ByDefault()\n        {\n            // Arrange\n            HttpContextBase webContext = CreateDummyWebContext();\n            HttpRequestBase webRequest = new Mock<HttpRequestBase>().Object;\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n\n                // Act\n                bool isLocal = context.IsLocal;\n\n                // Assert\n                Assert.False(isLocal);\n            }\n        }\n\n        [Theory]\n        [InlineData(false)]\n        [InlineData(true)]\n        public void IsLocal_ReturnsWebRequestIsLocalValue(bool expectedIsLocal)\n        {\n            // Arrange\n            HttpContextBase webContext = CreateDummyWebContext();\n            Mock<HttpRequestBase> webRequestMock = new Mock<HttpRequestBase>(MockBehavior.Strict);\n            webRequestMock.Setup(r => r.IsLocal).Returns(expectedIsLocal);\n            HttpRequestBase webRequest = webRequestMock.Object;\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n\n                // Act\n                bool isLocal = context.IsLocal;\n\n                // Assert\n                Assert.Equal(expectedIsLocal, isLocal);\n            }\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void IsLocalSet_UpdatesIsLocal(bool expectedIsLocal)\n        {\n            // Arrange\n            HttpContextBase webContext = CreateDummyWebContext();\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n\n                // Act\n                context.IsLocal = expectedIsLocal;\n\n                // Assert\n                bool isLocal = context.IsLocal;\n                Assert.Equal(expectedIsLocal, isLocal);\n            }\n        }\n\n        [Theory]\n        [InlineData(true)]\n        [InlineData(false)]\n        public void IsLocalGet_ReturnsFirstObservedValue(bool expectedIsLocal)\n        {\n            // Arrange\n            bool currentWebRequestIsLocal = expectedIsLocal;\n            HttpContextBase webContext = CreateDummyWebContext();\n            Mock<HttpRequestBase> webRequestMock = new Mock<HttpRequestBase>(MockBehavior.Strict);\n            webRequestMock.Setup(r => r.IsLocal).Returns(() => currentWebRequestIsLocal);\n            HttpRequestBase webRequest = webRequestMock.Object;\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n                bool ignore = context.IsLocal;\n                currentWebRequestIsLocal = !expectedIsLocal;\n\n                // Act\n                bool isLocal = context.IsLocal;\n\n                // Assert\n                Assert.Equal(expectedIsLocal, isLocal);\n            }\n        }\n\n        [Fact]\n        public void PrincipalGet_ReturnsWebContextUser()\n        {\n            // Arrange\n            IPrincipal expectedPrincipal = CreateDummyPrincipal();\n            Mock<HttpContextBase> webContextMock = new Mock<HttpContextBase>(MockBehavior.Strict);\n            webContextMock.Setup(r => r.User).Returns(expectedPrincipal);\n            HttpContextBase webContext = webContextMock.Object;\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n\n                // Act\n                IPrincipal principal = context.Principal;\n\n                // Assert\n                Assert.Same(expectedPrincipal, principal);\n            }\n        }\n\n        [Fact]\n        [RestoreThreadPrincipal]\n        public void PrincipalSet_UpdatesWebContextUser()\n        {\n            // Arrange\n            Mock<HttpContextBase> webContextMock = new Mock<HttpContextBase>(MockBehavior.Strict);\n            IPrincipal principal = null;\n            webContextMock.SetupSet(r => r.User = It.IsAny<IPrincipal>()).Callback<IPrincipal>(\n                value => { principal = value; });\n            HttpContextBase webContext = webContextMock.Object;\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n                IPrincipal expectedPrincipal = CreateDummyPrincipal();\n\n                // Act\n                context.Principal = expectedPrincipal;\n\n                // Assert\n                Assert.Same(expectedPrincipal, principal);\n            }\n        }\n\n        [Fact]\n        [RestoreThreadPrincipal]\n        public void PrincipalSet_UpdatesThreadCurrentPrincipal()\n        {\n            // Arrange\n            HttpContextBase webContext = new Mock<HttpContextBase>().Object;\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n                IPrincipal expectedPrincipal = CreateDummyPrincipal();\n\n                // Act\n                context.Principal = expectedPrincipal;\n\n                // Assert\n                IPrincipal principal = Thread.CurrentPrincipal;\n                Assert.Same(expectedPrincipal, principal);\n            }\n        }\n\n        [Fact]\n        public void UrlGet_ReturnsUrlHelperForRequest()\n        {\n            // Arrange\n            HttpContextBase webContext = CreateDummyWebContext();\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage expectedRequest = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, expectedRequest);\n\n                // Act\n                UrlHelper url = context.Url;\n\n                // Assert\n                Assert.NotNull(url);\n                Assert.Same(expectedRequest, url.Request);\n            }\n        }\n\n        [Fact]\n        public void UrlGet_ReturnsSameInstance()\n        {\n            // Arrange\n            HttpContextBase webContext = CreateDummyWebContext();\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n                UrlHelper firstUrl = context.Url;\n\n                // Act\n                UrlHelper url = context.Url;\n\n                // Assert\n                Assert.Same(firstUrl, url);\n            }\n        }\n\n        [Fact]\n        public void UrlSet_UpdatesUrl()\n        {\n            // Arrange\n            HttpContextBase webContext = CreateDummyWebContext();\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n                UrlHelper expectedUrl = CreateDummyUrlHelper();\n\n                // Act\n                context.Url = expectedUrl;\n\n                // Assert\n                UrlHelper url = context.Url;\n                Assert.Same(expectedUrl, url);\n            }\n        }\n\n        [Fact]\n        public void UrlSet_UpdatesUrl_WhenNull()\n        {\n            // Arrange\n            HttpContextBase webContext = CreateDummyWebContext();\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n\n                // Act\n                context.Url = null;\n\n                // Assert\n                UrlHelper url = context.Url;\n                Assert.Null(url);\n            }\n        }\n\n        [Fact]\n        public void VirtualPathRootGet_ReturnsNull_ByDefault()\n        {\n            // Arrange\n            HttpContextBase webContext = CreateDummyWebContext();\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n\n                // Act\n                string virtualPathRoot = context.VirtualPathRoot;\n\n                // Assert\n                Assert.Null(virtualPathRoot);\n            }\n        }\n\n        [Fact]\n        public void VirtualPathRootGet_ReturnsNull_WhenConfigurationIsNull()\n        {\n            // Arrange\n            HttpContextBase webContext = CreateDummyWebContext();\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n                context.Configuration = null;\n\n                // Act\n                string virtualPathRoot = context.VirtualPathRoot;\n\n                // Assert\n                Assert.Null(virtualPathRoot);\n            }\n        }\n\n        [Fact]\n        public void VirtualPathRootGet_ReturnsConfigurationVirtualPathRoot()\n        {\n            // Arrange\n            string expectedVirtualPathRoot = \"/foo\";\n            HttpContextBase webContext = CreateDummyWebContext();\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            using (HttpConfiguration configuration = CreateConfiguration(expectedVirtualPathRoot))\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n                context.Configuration = configuration;\n\n                // Act\n                string virtualPathRoot = context.VirtualPathRoot;\n\n                // Assert\n                Assert.Equal(expectedVirtualPathRoot, virtualPathRoot);\n            }\n        }\n\n        [Theory]\n        [InlineData(\"a b\")]\n        [InlineData(\"/a b\")]\n        [InlineData(\"/a%20b\")]\n        public void VirtualPathRootGet_ReturnsUnescapedConfigurationVirtualPathRoot(string configurationVirtualPathRoot)\n        {\n            // Arrange\n            var expectedVirtualPathRoot = \"/a b\";\n            var webContext = CreateDummyWebContext();\n            var webRequest = CreateDummyWebRequest();\n\n            using (var request = CreateRequest())\n            using (var configuration = CreateConfiguration(configurationVirtualPathRoot))\n            {\n                var context = CreateProductUnderTest(webContext, webRequest, request);\n                context.Configuration = configuration;\n\n                // Act\n                var virtualPathRoot = context.VirtualPathRoot;\n\n                // Assert\n                Assert.Equal(expectedVirtualPathRoot, virtualPathRoot);\n            }\n        }\n\n        [Fact]\n        public void VirtualPathRootSet_UpdatesVirtualPathRoot()\n        {\n            // Arrange\n            HttpContextBase webContext = CreateDummyWebContext();\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n                string expectedVirtualPathRoot = \"foo\";\n\n                // Act\n                context.VirtualPathRoot = expectedVirtualPathRoot;\n\n                // Assert\n                string virtualPathRoot = context.VirtualPathRoot;\n                Assert.Same(expectedVirtualPathRoot, virtualPathRoot);\n            }\n        }\n\n        [Fact]\n        public void VirtualPathRootSet_UpdatesVirtualPathRoot_WhenNull()\n        {\n            // Arrange\n            HttpContextBase webContext = CreateDummyWebContext();\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            using (HttpConfiguration configuration = CreateConfiguration(\"/other\"))\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n                context.Configuration = configuration;\n\n                // Act\n                context.VirtualPathRoot = null;\n\n                // Assert\n                string virtualPathRoot = context.VirtualPathRoot;\n                Assert.Null(virtualPathRoot);\n            }\n        }\n\n        [Fact]\n        public void VirtualPathRootGet_ReturnsFirstObservedConfigurationVirtualPathRoot()\n        {\n            // Arrange\n            string expectedVirtualPathRoot = \"/foo\";\n            HttpContextBase webContext = CreateDummyWebContext();\n            HttpRequestBase webRequest = CreateDummyWebRequest();\n\n            using (HttpRequestMessage request = CreateRequest())\n            using (HttpConfiguration configuration = CreateConfiguration(expectedVirtualPathRoot))\n            using (HttpConfiguration otherConfiguration = CreateConfiguration(\"/other\"))\n            {\n                HttpRequestContext context = CreateProductUnderTest(webContext, webRequest, request);\n                context.Configuration = configuration;\n                string ignore = context.VirtualPathRoot;\n                context.Configuration = otherConfiguration;\n\n                // Act\n                string virtualPathRoot = context.VirtualPathRoot;\n\n                // Assert\n                Assert.Equal(expectedVirtualPathRoot, virtualPathRoot);\n            }\n        }\n\n        private static X509Certificate2 CreateCertificate()\n        {\n            return new X509Certificate2();\n        }\n\n        private static HttpConfiguration CreateConfiguration()\n        {\n            return new HttpConfiguration();\n        }\n\n        private static HttpConfiguration CreateConfiguration(string virtualPathRoot)\n        {\n            return new HttpConfiguration(new HttpRouteCollection(virtualPathRoot));\n        }\n\n        private static HttpContextBase CreateDummyWebContext()\n        {\n            return new Mock<HttpContextBase>(MockBehavior.Strict).Object;\n        }\n\n        private static HttpRequestBase CreateDummyWebRequest()\n        {\n            return new Mock<HttpRequestBase>(MockBehavior.Strict).Object;\n        }\n\n        private static IPrincipal CreateDummyPrincipal()\n        {\n            return new Mock<IPrincipal>(MockBehavior.Strict).Object;\n        }\n\n        private static UrlHelper CreateDummyUrlHelper()\n        {\n            return new Mock<UrlHelper>(MockBehavior.Strict).Object;\n        }\n\n        private static HttpClientCertificate CreateHttpClientCertificate(byte[] bytes)\n        {\n            Mock<HttpWorkerRequest> workerRequestMock = new Mock<HttpWorkerRequest>();\n            workerRequestMock.Setup(wr => wr.GetRawUrl()).Returns(\"/\");\n            workerRequestMock.Setup(wr => wr.GetServerVariable(\"CERT_FLAGS\")).Returns(\"1\");\n            workerRequestMock.Setup(wr => wr.GetClientCertificate()).Returns(bytes);\n            HttpContext context = new HttpContext(workerRequestMock.Object);\n            return context.Request.ClientCertificate;\n        }\n\n        private static WebHostHttpRequestContext CreateProductUnderTest(HttpContextBase contextBase,\n            HttpRequestBase requestBase, HttpRequestMessage request)\n        {\n            return new WebHostHttpRequestContext(contextBase, requestBase, request);\n        }\n\n        private static HttpRequestMessage CreateRequest()\n        {\n            return new HttpRequestMessage();\n        }\n\n        private static HttpRequestBase CreateStubWebRequest(HttpClientCertificate clientCertificate)\n        {\n            Mock<HttpRequestBase> mock = new Mock<HttpRequestBase>(MockBehavior.Strict);\n            mock.Setup(r => r.ClientCertificate).Returns(clientCertificate);\n            return mock.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Http.WebHost.Test/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Castle.Core\" version=\"5.1.1\" targetFramework=\"net462\" />\n  <package id=\"Moq\" version=\"4.18.4\" targetFramework=\"net462\" />\n  <package id=\"Newtonsoft.Json\" version=\"13.0.1\" targetFramework=\"net462\" />\n  <package id=\"xunit\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.abstractions\" version=\"2.0.3\" targetFramework=\"net462\" />\n  <package id=\"xunit.analyzers\" version=\"1.1.0\" targetFramework=\"net462\" />\n  <package id=\"xunit.assert\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.execution\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.runner.visualstudio\" version=\"2.4.5\" targetFramework=\"net462\" developmentDependency=\"true\" />\n</packages>"
  },
  {
    "path": "test/System.Web.Mvc.Test/Ajax/Test/AjaxExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.IO;\nusing System.Threading;\nusing System.Web.Mvc.Html;\nusing System.Web.Routing;\nusing System.Web.WebPages.Scope;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\nusing Moq;\n\nnamespace System.Web.Mvc.Ajax.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")]\n    public class AjaxExtensionsTest : IDisposable\n    {\n        // Guards\n\n        [Fact]\n        public void ActionLinkWithNullOrEmptyLinkTextThrows()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { MvcHtmlString actionLink = ajaxHelper.ActionLink(String.Empty, String.Empty, null, null, null, null); },\n                \"linkText\");\n        }\n\n        [Fact]\n        public void RouteLinkWithNullOrEmptyLinkTextThrows()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { MvcHtmlString actionLink = ajaxHelper.RouteLink(String.Empty, String.Empty, null, null, null); },\n                \"linkText\");\n        }\n\n        // Form context setup and cleanup\n\n        [Fact]\n        public void BeginFormSetsAndRestoresToDefault()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper();\n\n            ajaxHelper.ViewContext.FormContext = null;\n            FormContext defaultFormContext = ajaxHelper.ViewContext.FormContext;\n\n            // Act & assert - push\n            MvcForm theForm = ajaxHelper.BeginForm(new AjaxOptions());\n            Assert.NotNull(ajaxHelper.ViewContext.FormContext);\n            Assert.NotEqual(defaultFormContext, ajaxHelper.ViewContext.FormContext);\n\n            // Act & assert - pop\n            theForm.Dispose();\n            Assert.Equal(defaultFormContext, ajaxHelper.ViewContext.FormContext);\n        }\n\n        [Fact]\n        public void DisposeWritesClosingFormTag()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper();\n            AjaxOptions ajaxOptions = new AjaxOptions { UpdateTargetId = \"some-id\" };\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(\"Action\", \"Controller\", ajaxOptions);\n            form.Dispose();\n\n            // Assert\n            Assert.EndsWith(\"</form>\", writer.ToString());\n        }\n\n        // GlobalizationScript\n\n        [Fact]\n        public void GlobalizationScriptWithNullCultureInfoThrows()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { ajaxHelper.GlobalizationScript(null); },\n                \"cultureInfo\");\n        }\n\n        [Fact]\n        public void GlobalizationScriptUsesCurrentCultureAsDefault()\n        {\n            CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;\n\n            try\n            {\n                // Arrange\n                AjaxHelper ajaxHelper = GetAjaxHelper();\n                AjaxHelper.GlobalizationScriptPath = null;\n                Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(\"en-GB\");\n\n                // Act\n                MvcHtmlString globalizationScript = ajaxHelper.GlobalizationScript();\n\n                // Assert\n                Assert.Equal(@\"<script src=\"\"~/Scripts/Globalization/en-GB.js\"\" type=\"\"text/javascript\"\"></script>\", globalizationScript.ToHtmlString());\n            }\n            finally\n            {\n                Thread.CurrentThread.CurrentCulture = currentCulture;\n            }\n        }\n\n        [Fact]\n        public void GlobalizationScriptWithCultureInfo()\n        {\n            CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;\n\n            try\n            {\n                // Arrange\n                AjaxHelper ajaxHelper = GetAjaxHelper();\n                AjaxHelper.GlobalizationScriptPath = null;\n                Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(\"en-GB\");\n\n                // Act\n                MvcHtmlString globalizationScript = ajaxHelper.GlobalizationScript(CultureInfo.GetCultureInfo(\"en-CA\"));\n\n                // Assert\n                Assert.Equal(@\"<script src=\"\"~/Scripts/Globalization/en-CA.js\"\" type=\"\"text/javascript\"\"></script>\", globalizationScript.ToHtmlString());\n            }\n            finally\n            {\n                Thread.CurrentThread.CurrentCulture = currentCulture;\n            }\n        }\n\n        [Fact]\n        public void GlobalizationScriptEncodesSource()\n        {\n            // Arrange\n            Mock<CultureInfo> xssCulture = new Mock<CultureInfo>(\"en-US\");\n            xssCulture.Setup(culture => culture.Name).Returns(\"evil.example.com/<script>alert('XSS!')</script>\");\n            string globalizationPath = \"~/Scripts&Globalization\";\n            string expectedScriptTag = @\"<script src=\"\"~/Scripts&amp;Globalization/evil.example.com%2f%3cscript%3ealert(%27XSS!%27)%3c%2fscript%3e.js\"\" type=\"\"text/javascript\"\"></script>\";\n\n            // Act\n            MvcHtmlString globalizationScript = AjaxExtensions.GlobalizationScriptHelper(globalizationPath, xssCulture.Object);\n\n            // Assert\n            Assert.Equal(expectedScriptTag, globalizationScript.ToHtmlString());\n        }\n\n        [Fact]\n        public void GlobalizationScriptWithNullCultureName()\n        {\n            // Arrange\n            Mock<CultureInfo> xssCulture = new Mock<CultureInfo>(\"en-US\");\n            xssCulture.Setup(culture => culture.Name).Returns((string)null);\n\n            AjaxHelper ajaxHelper = GetAjaxHelper();\n            AjaxHelper.GlobalizationScriptPath = null;\n\n            // Act\n            MvcHtmlString globalizationScript = ajaxHelper.GlobalizationScript(xssCulture.Object);\n\n            // Assert\n            Assert.Equal(@\"<script src=\"\"~/Scripts/Globalization/.js\"\" type=\"\"text/javascript\"\"></script>\", globalizationScript.ToHtmlString());\n        }\n\n        // ActionLink (traditional JavaScript)\n\n        [Fact]\n        public void ActionLinkWithNullActionName()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.ActionLink(\"linkText\", null, new AjaxOptions());\n\n            // Assert\n            Assert.Equal(@\"<a href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/home/oldaction\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace });\"\">linkText</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithNullActionName_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.ActionLink(\"linkText\", null, new AjaxOptions());\n\n            // Assert\n            Assert.Equal(@\"<a data-ajax=\"\"true\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/home/oldaction\"\">linkText</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithNullActionNameAndNullOptions()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.ActionLink(\"linkText\", null, null);\n\n            // Assert\n            Assert.Equal(@\"<a href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/home/oldaction\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace });\"\">linkText</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithNullActionNameAndNullOptions_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.ActionLink(\"linkText\", null, null);\n\n            // Assert\n            Assert.Equal(@\"<a data-ajax=\"\"true\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/home/oldaction\"\">linkText</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLink()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.ActionLink(\"linkText\", \"Action\", new AjaxOptions());\n\n            // Assert\n            Assert.Equal(@\"<a href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/home/Action\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace });\"\">linkText</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLink_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.ActionLink(\"linkText\", \"Action\", new AjaxOptions());\n\n            // Assert\n            Assert.Equal(@\"<a data-ajax=\"\"true\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/home/Action\"\">linkText</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkAnonymousValues()\n        {\n            // Arrange\n            AjaxHelper helper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            object values = new { controller = \"Controller\" };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = helper.ActionLink(\"Some Text\", \"Action\", values, options);\n\n            // Assert\n            Assert.Equal(@\"<a href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: &#39;update-div&#39; });\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkAnonymousValues_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper helper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            object values = new { controller = \"Controller\" };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = helper.ActionLink(\"Some Text\", \"Action\", values, options);\n\n            // Assert\n            Assert.Equal(@\"<a data-ajax=\"\"true\"\" data-ajax-mode=\"\"replace\"\" data-ajax-update=\"\"#update-div\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkAnonymousValuesAndAttributes()\n        {\n            // Arrange\n            AjaxHelper helper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            object htmlAttributes = new { foo = \"bar\", baz = \"quux\", foo_bar = \"baz_quux\" };\n            object values = new { controller = \"Controller\" };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = helper.ActionLink(\"Some Text\", \"Action\", values, options, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"quux\"\" foo=\"\"bar\"\" foo-bar=\"\"baz_quux\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: &#39;update-div&#39; });\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkAnonymousValuesAndAttributes_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper helper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            object htmlAttributes = new { foo = \"bar\", baz = \"quux\", foo_bar = \"baz_quux\" };\n            object values = new { controller = \"Controller\" };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = helper.ActionLink(\"Some Text\", \"Action\", values, options, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"quux\"\" data-ajax=\"\"true\"\" data-ajax-mode=\"\"replace\"\" data-ajax-update=\"\"#update-div\"\" foo=\"\"bar\"\" foo-bar=\"\"baz_quux\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkTypedValues()\n        {\n            // Arrange\n            AjaxHelper helper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            RouteValueDictionary values = new RouteValueDictionary\n            {\n                { \"controller\", \"Controller\" }\n            };\n\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = helper.ActionLink(\"Some Text\", \"Action\", values, options);\n\n            // Assert\n            Assert.Equal(@\"<a href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: &#39;update-div&#39; });\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkTypedValues_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper helper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            RouteValueDictionary values = new RouteValueDictionary\n            {\n                { \"controller\", \"Controller\" }\n            };\n\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = helper.ActionLink(\"Some Text\", \"Action\", values, options);\n\n            // Assert\n            Assert.Equal(@\"<a data-ajax=\"\"true\"\" data-ajax-mode=\"\"replace\"\" data-ajax-update=\"\"#update-div\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkTypedValuesAndAttributes()\n        {\n            // Arrange\n            AjaxHelper helper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            RouteValueDictionary values = new RouteValueDictionary\n            {\n                { \"controller\", \"Controller\" }\n            };\n            Dictionary<string, object> htmlAttributes = new Dictionary<string, object>\n            {\n                { \"foo\", \"bar\" },\n                { \"baz\", \"quux\" },\n                { \"foo_bar\", \"baz_quux\" }\n            };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = helper.ActionLink(\"Some Text\", \"Action\", values, options, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"quux\"\" foo=\"\"bar\"\" foo_bar=\"\"baz_quux\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: &#39;update-div&#39; });\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkTypedValuesAndAttributes_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper helper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            RouteValueDictionary values = new RouteValueDictionary\n            {\n                { \"controller\", \"Controller\" }\n            };\n            Dictionary<string, object> htmlAttributes = new Dictionary<string, object>\n            {\n                { \"foo\", \"bar\" },\n                { \"baz\", \"quux\" },\n                { \"foo_bar\", \"baz_quux\" }\n            };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = helper.ActionLink(\"Some Text\", \"Action\", values, options, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"quux\"\" data-ajax=\"\"true\"\" data-ajax-mode=\"\"replace\"\" data-ajax-update=\"\"#update-div\"\" foo=\"\"bar\"\" foo_bar=\"\"baz_quux\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkController()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.ActionLink(\"linkText\", \"Action\", \"Controller\", new AjaxOptions());\n\n            // Assert\n            Assert.Equal(@\"<a href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace });\"\">linkText</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkController_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.ActionLink(\"linkText\", \"Action\", \"Controller\", new AjaxOptions());\n\n            // Assert\n            Assert.Equal(@\"<a data-ajax=\"\"true\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\">linkText</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkControllerAnonymousValues()\n        {\n            // Arrange\n            AjaxHelper helper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            object values = new { id = 5 };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = helper.ActionLink(\"Some Text\", \"Action\", \"Controller\", values, options);\n\n            // Assert\n            Assert.Equal(@\"<a href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action/5\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: &#39;update-div&#39; });\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkControllerAnonymousValues_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper helper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            object values = new { id = 5 };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = helper.ActionLink(\"Some Text\", \"Action\", \"Controller\", values, options);\n\n            // Assert\n            Assert.Equal(@\"<a data-ajax=\"\"true\"\" data-ajax-mode=\"\"replace\"\" data-ajax-update=\"\"#update-div\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action/5\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkControllerAnonymousValuesAndAttributes()\n        {\n            // Arrange\n            AjaxHelper helper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            object htmlAttributes = new { foo = \"bar\", baz = \"quux\", foo_bar = \"baz_quux\" };\n            object values = new { id = 5 };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = helper.ActionLink(\"Some Text\", \"Action\", \"Controller\", values, options, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"quux\"\" foo=\"\"bar\"\" foo-bar=\"\"baz_quux\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action/5\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: &#39;update-div&#39; });\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkControllerAnonymousValuesAndAttributes_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper helper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            object htmlAttributes = new { foo = \"bar\", baz = \"quux\", foo_bar = \"baz_quux\" };\n            object values = new { id = 5 };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = helper.ActionLink(\"Some Text\", \"Action\", \"Controller\", values, options, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"quux\"\" data-ajax=\"\"true\"\" data-ajax-mode=\"\"replace\"\" data-ajax-update=\"\"#update-div\"\" foo=\"\"bar\"\" foo-bar=\"\"baz_quux\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action/5\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkControllerTypedValues()\n        {\n            // Arrange\n            AjaxHelper helper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            RouteValueDictionary values = new RouteValueDictionary\n            {\n                { \"id\", 5 }\n            };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = helper.ActionLink(\"Some Text\", \"Action\", \"Controller\", values, options);\n\n            // Assert\n            Assert.Equal(@\"<a href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action/5\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: &#39;update-div&#39; });\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkControllerTypedValues_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper helper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            RouteValueDictionary values = new RouteValueDictionary\n            {\n                { \"id\", 5 }\n            };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = helper.ActionLink(\"Some Text\", \"Action\", \"Controller\", values, options);\n\n            // Assert\n            Assert.Equal(@\"<a data-ajax=\"\"true\"\" data-ajax-mode=\"\"replace\"\" data-ajax-update=\"\"#update-div\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action/5\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkControllerTypedValuesAndAttributes()\n        {\n            // Arrange\n            AjaxHelper helper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            RouteValueDictionary values = new RouteValueDictionary\n            {\n                { \"id\", 5 }\n            };\n            Dictionary<string, object> htmlAttributes = new Dictionary<string, object>\n            {\n                { \"foo\", \"bar\" },\n                { \"baz\", \"quux\" },\n                { \"foo_bar\", \"baz_quux\" }\n            };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = helper.ActionLink(\"Some Text\", \"Action\", \"Controller\", values, options, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"quux\"\" foo=\"\"bar\"\" foo_bar=\"\"baz_quux\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action/5\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: &#39;update-div&#39; });\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkControllerTypedValuesAndAttributes_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper helper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            RouteValueDictionary values = new RouteValueDictionary\n            {\n                { \"id\", 5 }\n            };\n            Dictionary<string, object> htmlAttributes = new Dictionary<string, object>\n            {\n                { \"foo\", \"bar\" },\n                { \"baz\", \"quux\" },\n                { \"foo_bar\", \"baz_quux\" }\n            };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = helper.ActionLink(\"Some Text\", \"Action\", \"Controller\", values, options, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"quux\"\" data-ajax=\"\"true\"\" data-ajax-mode=\"\"replace\"\" data-ajax-update=\"\"#update-div\"\" foo=\"\"bar\"\" foo_bar=\"\"baz_quux\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action/5\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithOptions()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.ActionLink(\"linkText\", \"Action\", \"Controller\", new AjaxOptions { UpdateTargetId = \"some-id\" });\n\n            // Assert\n            Assert.Equal(@\"<a href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: &#39;some-id&#39; });\"\">linkText</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithOptions_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"some-id\" };\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.ActionLink(\"linkText\", \"Action\", \"Controller\", options);\n\n            // Assert\n            Assert.Equal(@\"<a data-ajax=\"\"true\"\" data-ajax-mode=\"\"replace\"\" data-ajax-update=\"\"#some-id\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\">linkText</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithNullHostName()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.ActionLink(\"linkText\", \"Action\", \"Controller\",\n                                                             null, null, null, null, new AjaxOptions { UpdateTargetId = \"some-id\" }, null);\n\n            // Assert\n            Assert.Equal(@\"<a href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: &#39;some-id&#39; });\"\">linkText</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithNullHostName_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.ActionLink(\"linkText\", \"Action\", \"Controller\",\n                                                             null, null, null, null, new AjaxOptions { UpdateTargetId = \"some-id\" }, null);\n\n            // Assert\n            Assert.Equal(@\"<a data-ajax=\"\"true\"\" data-ajax-mode=\"\"replace\"\" data-ajax-update=\"\"#some-id\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\">linkText</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithProtocol()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.ActionLink(\"linkText\", \"Action\", \"Controller\", \"https\", null, null, null, new AjaxOptions { UpdateTargetId = \"some-id\" }, null);\n\n            // Assert\n            Assert.Equal(@\"<a href=\"\"https://foo.bar.baz\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: &#39;some-id&#39; });\"\">linkText</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithProtocol_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.ActionLink(\"linkText\", \"Action\", \"Controller\", \"https\", null, null, null, new AjaxOptions { UpdateTargetId = \"some-id\" }, null);\n\n            // Assert\n            Assert.Equal(@\"<a data-ajax=\"\"true\"\" data-ajax-mode=\"\"replace\"\" data-ajax-update=\"\"#some-id\"\" href=\"\"https://foo.bar.baz\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\">linkText</a>\", actionLink.ToHtmlString());\n        }\n\n        // RouteLink\n\n        [Fact]\n        public void RouteLinkWithNullOptions()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n\n            // Act\n            MvcHtmlString routeLink = ajaxHelper.RouteLink(\"Some Text\", new RouteValueDictionary(), null);\n\n            // Assert\n            Assert.Equal(@\"<a href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/home/oldaction\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace });\"\">Some Text</a>\", routeLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkWithNullOptions_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n\n            // Act\n            MvcHtmlString routeLink = ajaxHelper.RouteLink(\"Some Text\", new RouteValueDictionary(), null);\n\n            // Assert\n            Assert.Equal(@\"<a data-ajax=\"\"true\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/home/oldaction\"\">Some Text</a>\", routeLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkAnonymousValues()\n        {\n            // Arrange\n            AjaxHelper helper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            object values = new\n            {\n                action = \"Action\",\n                controller = \"Controller\"\n            };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString routeLink = helper.RouteLink(\"Some Text\", values, options);\n\n            // Assert\n            Assert.Equal(@\"<a href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: &#39;update-div&#39; });\"\">Some Text</a>\", routeLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkAnonymousValues_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper helper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            object values = new\n            {\n                action = \"Action\",\n                controller = \"Controller\"\n            };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString routeLink = helper.RouteLink(\"Some Text\", values, options);\n\n            // Assert\n            Assert.Equal(@\"<a data-ajax=\"\"true\"\" data-ajax-mode=\"\"replace\"\" data-ajax-update=\"\"#update-div\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\">Some Text</a>\", routeLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkAnonymousValuesAndAttributes()\n        {\n            // Arrange\n            AjaxHelper helper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            object htmlAttributes = new\n            {\n                foo = \"bar\",\n                baz = \"quux\",\n                foo_bar = \"baz_quux\"\n            };\n            object values = new\n            {\n                action = \"Action\",\n                controller = \"Controller\"\n            };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = helper.RouteLink(\"Some Text\", values, options, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"quux\"\" foo=\"\"bar\"\" foo-bar=\"\"baz_quux\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: &#39;update-div&#39; });\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkAnonymousValuesAndAttributes_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper helper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            object htmlAttributes = new\n            {\n                foo = \"bar\",\n                baz = \"quux\",\n                foo_bar = \"baz_quux\"\n            };\n            object values = new\n            {\n                action = \"Action\",\n                controller = \"Controller\"\n            };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = helper.RouteLink(\"Some Text\", values, options, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"quux\"\" data-ajax=\"\"true\"\" data-ajax-mode=\"\"replace\"\" data-ajax-update=\"\"#update-div\"\" foo=\"\"bar\"\" foo-bar=\"\"baz_quux\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkTypedValues()\n        {\n            // Arrange\n            AjaxHelper helper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            RouteValueDictionary values = new RouteValueDictionary\n            {\n                { \"controller\", \"Controller\" },\n                { \"action\", \"Action\" }\n            };\n\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = helper.RouteLink(\"Some Text\", values, options);\n\n            // Assert\n            Assert.Equal(@\"<a href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: &#39;update-div&#39; });\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkTypedValues_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper helper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            RouteValueDictionary values = new RouteValueDictionary\n            {\n                { \"controller\", \"Controller\" },\n                { \"action\", \"Action\" }\n            };\n\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = helper.RouteLink(\"Some Text\", values, options);\n\n            // Assert\n            Assert.Equal(@\"<a data-ajax=\"\"true\"\" data-ajax-mode=\"\"replace\"\" data-ajax-update=\"\"#update-div\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkTypedValuesAndAttributes()\n        {\n            // Arrange\n            AjaxHelper helper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            RouteValueDictionary values = new RouteValueDictionary\n            {\n                { \"controller\", \"Controller\" },\n                { \"action\", \"Action\" }\n            };\n            Dictionary<string, object> htmlAttributes = new Dictionary<string, object>\n            {\n                { \"foo\", \"bar\" },\n                { \"baz\", \"quux\" },\n                { \"foo_bar\", \"baz_quux\" }\n            };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = helper.RouteLink(\"Some Text\", values, options, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"quux\"\" foo=\"\"bar\"\" foo_bar=\"\"baz_quux\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: &#39;update-div&#39; });\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkTypedValuesAndAttributes_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper helper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            RouteValueDictionary values = new RouteValueDictionary\n            {\n                { \"controller\", \"Controller\" },\n                { \"action\", \"Action\" }\n            };\n            Dictionary<string, object> htmlAttributes = new Dictionary<string, object>\n            {\n                { \"foo\", \"bar\" },\n                { \"baz\", \"quux\" },\n                { \"foo_bar\", \"baz_quux\" }\n            };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = helper.RouteLink(\"Some Text\", values, options, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"quux\"\" data-ajax=\"\"true\"\" data-ajax-mode=\"\"replace\"\" data-ajax-update=\"\"#update-div\"\" foo=\"\"bar\"\" foo_bar=\"\"baz_quux\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkNamedRoute()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.RouteLink(\"linkText\", \"namedroute\", new AjaxOptions());\n\n            // Assert\n            Assert.Equal(@\"<a href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/named/home/oldaction\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace });\"\">linkText</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkNamedRoute_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.RouteLink(\"linkText\", \"namedroute\", new AjaxOptions());\n\n            // Assert\n            Assert.Equal(@\"<a data-ajax=\"\"true\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/named/home/oldaction\"\">linkText</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkNamedRouteAnonymousAttributes()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            object htmlAttributes = new\n            {\n                foo = \"bar\",\n                baz = \"quux\",\n                foo_bar = \"baz_quux\"\n            };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.RouteLink(\"Some Text\", \"namedroute\", options, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"quux\"\" foo=\"\"bar\"\" foo-bar=\"\"baz_quux\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/named/home/oldaction\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: &#39;update-div&#39; });\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkNamedRouteAnonymousAttributes_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            object htmlAttributes = new\n            {\n                foo = \"bar\",\n                baz = \"quux\",\n                foo_bar = \"baz_quux\"\n            };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.RouteLink(\"Some Text\", \"namedroute\", options, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"quux\"\" data-ajax=\"\"true\"\" data-ajax-mode=\"\"replace\"\" data-ajax-update=\"\"#update-div\"\" foo=\"\"bar\"\" foo-bar=\"\"baz_quux\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/named/home/oldaction\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkNamedRouteTypedAttributes()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            Dictionary<string, object> htmlAttributes = new Dictionary<string, object> { { \"foo\", \"bar\" }, { \"baz\", \"quux\" }, { \"foo_bar\", \"baz_quux\" } };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.RouteLink(\"Some Text\", \"namedroute\", options, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"quux\"\" foo=\"\"bar\"\" foo_bar=\"\"baz_quux\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/named/home/oldaction\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: &#39;update-div&#39; });\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkNamedRouteTypedAttributes_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            Dictionary<string, object> htmlAttributes = new Dictionary<string, object> { { \"foo\", \"bar\" }, { \"baz\", \"quux\" }, { \"foo_bar\", \"baz_quux\" } };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.RouteLink(\"Some Text\", \"namedroute\", options, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"quux\"\" data-ajax=\"\"true\"\" data-ajax-mode=\"\"replace\"\" data-ajax-update=\"\"#update-div\"\" foo=\"\"bar\"\" foo_bar=\"\"baz_quux\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/named/home/oldaction\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkNamedRouteWithAnonymousValues()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            object values = new\n            {\n                action = \"Action\",\n                controller = \"Controller\"\n            };\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.RouteLink(\"linkText\", \"namedroute\", values, new AjaxOptions());\n\n            // Assert\n            Assert.Equal(@\"<a href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/named/Controller/Action\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace });\"\">linkText</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkNamedRouteWithAnonymousValues_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            object values = new\n            {\n                action = \"Action\",\n                controller = \"Controller\"\n            };\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.RouteLink(\"linkText\", \"namedroute\", values, new AjaxOptions());\n\n            // Assert\n            Assert.Equal(@\"<a data-ajax=\"\"true\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/named/Controller/Action\"\">linkText</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkNamedRouteAnonymousValuesAndAttributes()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            object values = new\n            {\n                action = \"Action\",\n                controller = \"Controller\"\n            };\n\n            object htmlAttributes = new\n            {\n                foo = \"bar\",\n                baz = \"quux\",\n                foo_bar = \"baz_quux\"\n            };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.RouteLink(\"Some Text\", \"namedroute\", values, options, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"quux\"\" foo=\"\"bar\"\" foo-bar=\"\"baz_quux\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/named/Controller/Action\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: &#39;update-div&#39; });\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkNamedRouteAnonymousValuesAndAttributes_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            object values = new\n            {\n                action = \"Action\",\n                controller = \"Controller\"\n            };\n\n            object htmlAttributes = new\n            {\n                foo = \"bar\",\n                baz = \"quux\",\n                foo_bar = \"baz_quux\"\n            };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.RouteLink(\"Some Text\", \"namedroute\", values, options, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"quux\"\" data-ajax=\"\"true\"\" data-ajax-mode=\"\"replace\"\" data-ajax-update=\"\"#update-div\"\" foo=\"\"bar\"\" foo-bar=\"\"baz_quux\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/named/Controller/Action\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkNamedRouteWithTypedValues()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            RouteValueDictionary values = new RouteValueDictionary\n            {\n                { \"controller\", \"Controller\" },\n                { \"action\", \"Action\" }\n            };\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.RouteLink(\"linkText\", \"namedroute\", values, new AjaxOptions());\n\n            // Assert\n            Assert.Equal(@\"<a href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/named/Controller/Action\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace });\"\">linkText</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkNamedRouteWithTypedValues_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            RouteValueDictionary values = new RouteValueDictionary\n            {\n                { \"controller\", \"Controller\" },\n                { \"action\", \"Action\" }\n            };\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.RouteLink(\"linkText\", \"namedroute\", values, new AjaxOptions());\n\n            // Assert\n            Assert.Equal(@\"<a data-ajax=\"\"true\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/named/Controller/Action\"\">linkText</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkNamedRouteTypedValuesAndAttributes()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            RouteValueDictionary values = new RouteValueDictionary\n            {\n                { \"controller\", \"Controller\" },\n                { \"action\", \"Action\" }\n            };\n\n            Dictionary<string, object> htmlAttributes = new Dictionary<string, object> { { \"foo\", \"bar\" }, { \"baz\", \"quux\" }, { \"foo_bar\", \"baz_quux\" } };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.RouteLink(\"Some Text\", \"namedroute\", values, options, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"quux\"\" foo=\"\"bar\"\" foo_bar=\"\"baz_quux\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/named/Controller/Action\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: &#39;update-div&#39; });\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkNamedRouteTypedValuesAndAttributes_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            RouteValueDictionary values = new RouteValueDictionary\n            {\n                { \"controller\", \"Controller\" },\n                { \"action\", \"Action\" }\n            };\n\n            Dictionary<string, object> htmlAttributes = new Dictionary<string, object> { { \"foo\", \"bar\" }, { \"baz\", \"quux\" }, { \"foo_bar\", \"baz_quux\" } };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.RouteLink(\"Some Text\", \"namedroute\", values, options, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"quux\"\" data-ajax=\"\"true\"\" data-ajax-mode=\"\"replace\"\" data-ajax-update=\"\"#update-div\"\" foo=\"\"bar\"\" foo_bar=\"\"baz_quux\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/named/Controller/Action\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkNamedRouteNullValuesAndAttributes()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            Dictionary<string, object> htmlAttributes = new Dictionary<string, object> { { \"foo\", \"bar\" }, { \"baz\", \"quux\" }, { \"foo_bar\", \"baz_quux\" } };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.RouteLink(\"Some Text\", \"namedroute\", null, options, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"quux\"\" foo=\"\"bar\"\" foo_bar=\"\"baz_quux\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/named/home/oldaction\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: &#39;update-div&#39; });\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkNamedRouteNullValuesAndAttributes_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            Dictionary<string, object> htmlAttributes = new Dictionary<string, object> { { \"foo\", \"bar\" }, { \"baz\", \"quux\" }, { \"foo_bar\", \"baz_quux\" } };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.RouteLink(\"Some Text\", \"namedroute\", null, options, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"quux\"\" data-ajax=\"\"true\"\" data-ajax-mode=\"\"replace\"\" data-ajax-update=\"\"#update-div\"\" foo=\"\"bar\"\" foo_bar=\"\"baz_quux\"\" href=\"\"\" + MvcHelper.AppPathModifier + @\"/app/named/home/oldaction\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkWithHostName()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            Dictionary<string, object> htmlAttributes = new Dictionary<string, object> { { \"foo\", \"bar\" }, { \"baz\", \"quux\" }, { \"foo_bar\", \"baz_quux\" } };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.RouteLink(\"Some Text\", \"namedroute\", null, \"baz.bar.foo\", null, null, options, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"quux\"\" foo=\"\"bar\"\" foo_bar=\"\"baz_quux\"\" href=\"\"http://baz.bar.foo\" + MvcHelper.AppPathModifier + @\"/app/named/home/oldaction\"\" onclick=\"\"Sys.Mvc.AsyncHyperlink.handleClick(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: &#39;update-div&#39; });\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkWithHostName_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            Dictionary<string, object> htmlAttributes = new Dictionary<string, object> { { \"foo\", \"bar\" }, { \"baz\", \"quux\" }, { \"foo_bar\", \"baz_quux\" } };\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"update-div\" };\n\n            // Act\n            MvcHtmlString actionLink = ajaxHelper.RouteLink(\"Some Text\", \"namedroute\", null, \"baz.bar.foo\", null, null, options, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"quux\"\" data-ajax=\"\"true\"\" data-ajax-mode=\"\"replace\"\" data-ajax-update=\"\"#update-div\"\" foo=\"\"bar\"\" foo_bar=\"\"baz_quux\"\" href=\"\"http://baz.bar.foo\" + MvcHelper.AppPathModifier + @\"/app/named/home/oldaction\"\">Some Text</a>\", actionLink.ToHtmlString());\n        }\n\n        // BeginForm\n\n        [Fact]\n        public void BeginFormOnlyWithNullOptions()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(null);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"/rawUrl\"\" method=\"\"post\"\" onclick=\"\"Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));\"\" onsubmit=\"\"Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace });\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormOnlyWithNullOptions_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(null);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"/rawUrl\"\" data-ajax=\"\"true\"\" method=\"\"post\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormWithNullActionName()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            AjaxOptions ajaxOptions = new AjaxOptions();\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(null, ajaxOptions);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/home/oldaction\"\" method=\"\"post\"\" onclick=\"\"Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));\"\" onsubmit=\"\"Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace });\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormWithNullActionName_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            AjaxOptions ajaxOptions = new AjaxOptions();\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(null, ajaxOptions);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/home/oldaction\"\" data-ajax=\"\"true\"\" method=\"\"post\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormWithNullOptions()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            AjaxOptions ajaxOptions = new AjaxOptions();\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(\"Action\", \"Controller\", null);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\" method=\"\"post\"\" onclick=\"\"Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));\"\" onsubmit=\"\"Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace });\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormWithNullOptions_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            AjaxOptions ajaxOptions = new AjaxOptions();\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(\"Action\", \"Controller\", null);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\" data-ajax=\"\"true\"\" method=\"\"post\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginForm()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            AjaxOptions ajaxOptions = new AjaxOptions();\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(ajaxOptions);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"/rawUrl\"\" method=\"\"post\"\" onclick=\"\"Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));\"\" onsubmit=\"\"Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace });\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginForm_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            AjaxOptions ajaxOptions = new AjaxOptions();\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(ajaxOptions);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"/rawUrl\"\" data-ajax=\"\"true\"\" method=\"\"post\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormAction()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            AjaxOptions ajaxOptions = new AjaxOptions();\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(\"Action\", ajaxOptions);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/home/Action\"\" method=\"\"post\"\" onclick=\"\"Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));\"\" onsubmit=\"\"Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace });\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormAction_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            AjaxOptions ajaxOptions = new AjaxOptions();\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(\"Action\", ajaxOptions);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/home/Action\"\" data-ajax=\"\"true\"\" method=\"\"post\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormAnonymousValues()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            AjaxOptions ajaxOptions = new AjaxOptions();\n            object values = new { controller = \"Controller\" };\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(\"Action\", values, ajaxOptions);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\" method=\"\"post\"\" onclick=\"\"Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));\"\" onsubmit=\"\"Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace });\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormAnonymousValues_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            AjaxOptions ajaxOptions = new AjaxOptions();\n            object values = new { controller = \"Controller\" };\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(\"Action\", values, ajaxOptions);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\" data-ajax=\"\"true\"\" method=\"\"post\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormAnonymousValuesAndAttributes()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            AjaxOptions ajaxOptions = new AjaxOptions { UpdateTargetId = \"some-id\" };\n            object values = new { controller = \"Controller\" };\n            object htmlAttributes = new { method = \"get\", foo_bar = \"baz_quux\" };\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(\"Action\", values, ajaxOptions, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\" foo-bar=\"\"baz_quux\"\" method=\"\"get\"\" onclick=\"\"Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));\"\" onsubmit=\"\"Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: &#39;some-id&#39; });\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormAnonymousValuesAndAttributes_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            AjaxOptions ajaxOptions = new AjaxOptions { UpdateTargetId = \"some-id\" };\n            object values = new { controller = \"Controller\" };\n            object htmlAttributes = new { method = \"get\", foo_bar = \"baz_quux\" };\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(\"Action\", values, ajaxOptions, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\" data-ajax=\"\"true\"\" data-ajax-mode=\"\"replace\"\" data-ajax-update=\"\"#some-id\"\" foo-bar=\"\"baz_quux\"\" method=\"\"get\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormTypedValues()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            AjaxOptions ajaxOptions = new AjaxOptions();\n            RouteValueDictionary values = new RouteValueDictionary\n            {\n                { \"controller\", \"Controller\" }\n            };\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(\"Action\", values, ajaxOptions);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\" method=\"\"post\"\" onclick=\"\"Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));\"\" onsubmit=\"\"Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace });\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormTypedValues_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            AjaxOptions ajaxOptions = new AjaxOptions();\n            RouteValueDictionary values = new RouteValueDictionary\n            {\n                { \"controller\", \"Controller\" }\n            };\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(\"Action\", values, ajaxOptions);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\" data-ajax=\"\"true\"\" method=\"\"post\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormTypedValuesAndAttributes()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            AjaxOptions ajaxOptions = new AjaxOptions { UpdateTargetId = \"some-id\" };\n            RouteValueDictionary values = new RouteValueDictionary\n            {\n                { \"controller\", \"Controller\" }\n            };\n            Dictionary<string, object> htmlAttributes = new Dictionary<string, object>\n            {\n                { \"method\", \"get\" },\n                { \"foo_bar\", \"baz_quux\" }\n            };\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(\"Action\", values, ajaxOptions, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\" foo_bar=\"\"baz_quux\"\" method=\"\"get\"\" onclick=\"\"Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));\"\" onsubmit=\"\"Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: &#39;some-id&#39; });\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormTypedValuesAndAttributes_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            AjaxOptions ajaxOptions = new AjaxOptions { UpdateTargetId = \"some-id\" };\n            RouteValueDictionary values = new RouteValueDictionary\n            {\n                { \"controller\", \"Controller\" }\n            };\n            Dictionary<string, object> htmlAttributes = new Dictionary<string, object>\n            {\n                { \"method\", \"get\" },\n                { \"foo_bar\", \"baz_quux\" }\n            };\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(\"Action\", values, ajaxOptions, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\" data-ajax=\"\"true\"\" data-ajax-mode=\"\"replace\"\" data-ajax-update=\"\"#some-id\"\" foo_bar=\"\"baz_quux\"\" method=\"\"get\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormController()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            AjaxOptions ajaxOptions = new AjaxOptions();\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(\"Action\", \"Controller\", ajaxOptions);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\" method=\"\"post\"\" onclick=\"\"Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));\"\" onsubmit=\"\"Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace });\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormController_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            AjaxOptions ajaxOptions = new AjaxOptions();\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(\"Action\", \"Controller\", ajaxOptions);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\" data-ajax=\"\"true\"\" method=\"\"post\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormControllerAnonymousValues()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            AjaxOptions ajaxOptions = new AjaxOptions();\n            object values = new { id = 5 };\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(\"Action\", \"Controller\", values, ajaxOptions);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action/5\"\" method=\"\"post\"\" onclick=\"\"Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));\"\" onsubmit=\"\"Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace });\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormControllerAnonymousValues_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            AjaxOptions ajaxOptions = new AjaxOptions();\n            object values = new { id = 5 };\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(\"Action\", \"Controller\", values, ajaxOptions);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action/5\"\" data-ajax=\"\"true\"\" method=\"\"post\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormControllerAnonymousValuesAndAttributes()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            AjaxOptions ajaxOptions = new AjaxOptions();\n            object values = new { id = 5 };\n            object htmlAttributes = new { method = \"get\", foo_bar = \"baz_quux\" };\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(\"Action\", \"Controller\", values, ajaxOptions, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action/5\"\" foo-bar=\"\"baz_quux\"\" method=\"\"get\"\" onclick=\"\"Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));\"\" onsubmit=\"\"Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace });\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormControllerAnonymousValuesAndAttributes_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            AjaxOptions ajaxOptions = new AjaxOptions();\n            object values = new { id = 5 };\n            object htmlAttributes = new { method = \"get\", foo_bar = \"baz_quux\" };\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(\"Action\", \"Controller\", values, ajaxOptions, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action/5\"\" data-ajax=\"\"true\"\" foo-bar=\"\"baz_quux\"\" method=\"\"get\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormControllerTypedValues()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            AjaxOptions ajaxOptions = new AjaxOptions();\n            RouteValueDictionary values = new RouteValueDictionary\n            {\n                { \"id\", 5 }\n            };\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(\"Action\", \"Controller\", values, ajaxOptions);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action/5\"\" method=\"\"post\"\" onclick=\"\"Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));\"\" onsubmit=\"\"Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace });\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormControllerTypedValues_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            AjaxOptions ajaxOptions = new AjaxOptions();\n            RouteValueDictionary values = new RouteValueDictionary\n            {\n                { \"id\", 5 }\n            };\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(\"Action\", \"Controller\", values, ajaxOptions);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action/5\"\" data-ajax=\"\"true\"\" method=\"\"post\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormControllerTypedValuesAndAttributes()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            AjaxOptions ajaxOptions = new AjaxOptions();\n            RouteValueDictionary values = new RouteValueDictionary\n            {\n                { \"id\", 5 }\n            };\n            Dictionary<string, object> htmlAttributes = new Dictionary<string, object>\n            {\n                { \"method\", \"get\" },\n                { \"foo_bar\", \"baz_quux\" }\n            };\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(\"Action\", \"Controller\", values, ajaxOptions, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action/5\"\" foo_bar=\"\"baz_quux\"\" method=\"\"get\"\" onclick=\"\"Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));\"\" onsubmit=\"\"Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace });\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormControllerTypedValuesAndAttributes_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            AjaxOptions ajaxOptions = new AjaxOptions();\n            RouteValueDictionary values = new RouteValueDictionary\n            {\n                { \"id\", 5 }\n            };\n            Dictionary<string, object> htmlAttributes = new Dictionary<string, object>\n            {\n                { \"method\", \"get\" },\n                { \"foo_bar\", \"baz_quux\" }\n            };\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(\"Action\", \"Controller\", values, ajaxOptions, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action/5\"\" data-ajax=\"\"true\"\" foo_bar=\"\"baz_quux\"\" method=\"\"get\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormWithTargetId()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            AjaxOptions ajaxOptions = new AjaxOptions { UpdateTargetId = \"some-id\" };\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(\"Action\", \"Controller\", ajaxOptions);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\" method=\"\"post\"\" onclick=\"\"Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));\"\" onsubmit=\"\"Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: &#39;some-id&#39; });\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormWithTargetId_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            AjaxOptions ajaxOptions = new AjaxOptions { UpdateTargetId = \"some-id\" };\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginForm(\"Action\", \"Controller\", ajaxOptions);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/Controller/Action\"\" data-ajax=\"\"true\"\" data-ajax-mode=\"\"replace\"\" data-ajax-update=\"\"#some-id\"\" method=\"\"post\"\">\", writer.ToString());\n        }\n\n        // BeginRouteForm\n\n        [Fact]\n        public void BeginRouteForm()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            AjaxOptions ajaxOptions = new AjaxOptions();\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginRouteForm(\"namedroute\", ajaxOptions);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/named/home/oldaction\"\" method=\"\"post\"\" onclick=\"\"Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));\"\" onsubmit=\"\"Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace });\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginRouteForm_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            AjaxOptions ajaxOptions = new AjaxOptions();\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginRouteForm(\"namedroute\", ajaxOptions);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/named/home/oldaction\"\" data-ajax=\"\"true\"\" method=\"\"post\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginRouteFormAnonymousValues()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            AjaxOptions ajaxOptions = new AjaxOptions();\n            AjaxHelper poes = GetAjaxHelper(unobtrusiveJavaScript: false);\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginRouteForm(\"namedroute\", null, ajaxOptions);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/named/home/oldaction\"\" method=\"\"post\"\" onclick=\"\"Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));\"\" onsubmit=\"\"Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace });\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginRouteFormAnonymousValues_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            AjaxOptions ajaxOptions = new AjaxOptions();\n            AjaxHelper poes = GetAjaxHelper(unobtrusiveJavaScript: true);\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginRouteForm(\"namedroute\", null, ajaxOptions);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/named/home/oldaction\"\" data-ajax=\"\"true\"\" method=\"\"post\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginRouteFormAnonymousValuesAndAttributes()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            AjaxOptions ajaxOptions = new AjaxOptions { UpdateTargetId = \"some-id\" };\n            object htmlAttributes = new { method = \"get\", foo_bar = \"baz_quux\" };\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginRouteForm(\"namedroute\", null, ajaxOptions, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/named/home/oldaction\"\" foo-bar=\"\"baz_quux\"\" method=\"\"get\"\" onclick=\"\"Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));\"\" onsubmit=\"\"Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: &#39;some-id&#39; });\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginRouteFormAnonymousValuesAndAttributes_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            AjaxOptions ajaxOptions = new AjaxOptions { UpdateTargetId = \"some-id\" };\n            object htmlAttributes = new { method = \"get\", foo_bar = \"baz_quux\" };\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginRouteForm(\"namedroute\", null, ajaxOptions, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/named/home/oldaction\"\" data-ajax=\"\"true\"\" data-ajax-mode=\"\"replace\"\" data-ajax-update=\"\"#some-id\"\" foo-bar=\"\"baz_quux\"\" method=\"\"get\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginRouteFormCanUseNamedRouteWithoutSpecifyingDefaults()\n        {\n            // DevDiv 217072: Non-mvc specific helpers should not give default values for controller and action\n\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            ajaxHelper.RouteCollection.MapRoute(\"MyRouteName\", \"any/url\", new { controller = \"Charlie\" });\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginRouteForm(\"MyRouteName\", new AjaxOptions());\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/any/url\"\" method=\"\"post\"\" onclick=\"\"Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));\"\" onsubmit=\"\"Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace });\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginRouteFormCanUseNamedRouteWithoutSpecifyingDefaults_Unobtrusive()\n        {\n            // DevDiv 217072: Non-mvc specific helpers should not give default values for controller and action\n\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            ajaxHelper.RouteCollection.MapRoute(\"MyRouteName\", \"any/url\", new { controller = \"Charlie\" });\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginRouteForm(\"MyRouteName\", new AjaxOptions());\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/any/url\"\" data-ajax=\"\"true\"\" method=\"\"post\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginRouteFormTypedValues()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            AjaxOptions ajaxOptions = new AjaxOptions();\n            RouteValueDictionary values = new RouteValueDictionary();\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginRouteForm(\"namedroute\", values, ajaxOptions);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/named/home/oldaction\"\" method=\"\"post\"\" onclick=\"\"Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));\"\" onsubmit=\"\"Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace });\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginRouteFormTypedValues_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            AjaxOptions ajaxOptions = new AjaxOptions();\n            RouteValueDictionary values = new RouteValueDictionary();\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginRouteForm(\"namedroute\", values, ajaxOptions);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/named/home/oldaction\"\" data-ajax=\"\"true\"\" method=\"\"post\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginRouteFormTypedValuesAndAttributes()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: false);\n            Dictionary<string, object> htmlAttributes = new Dictionary<string, object> { { \"method\", \"get\" }, { \"foo_bar\", \"baz_quux\" } };\n            AjaxOptions ajaxOptions = new AjaxOptions { UpdateTargetId = \"some-id\" };\n            RouteValueDictionary values = new RouteValueDictionary();\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginRouteForm(\"namedroute\", values, ajaxOptions, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/named/home/oldaction\"\" foo_bar=\"\"baz_quux\"\" method=\"\"get\"\" onclick=\"\"Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));\"\" onsubmit=\"\"Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: &#39;some-id&#39; });\"\">\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginRouteFormTypedValuesAndAttributes_Unobtrusive()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper(unobtrusiveJavaScript: true);\n            Dictionary<string, object> htmlAttributes = new Dictionary<string, object> { { \"method\", \"get\" }, { \"foo_bar\", \"baz_quux\" } };\n            AjaxOptions ajaxOptions = new AjaxOptions { UpdateTargetId = \"some-id\" };\n            RouteValueDictionary values = new RouteValueDictionary();\n            StringWriter writer = new StringWriter();\n            ajaxHelper.ViewContext.Writer = writer;\n\n            // Act\n            IDisposable form = ajaxHelper.BeginRouteForm(\"namedroute\", values, ajaxOptions, htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/app/named/home/oldaction\"\" data-ajax=\"\"true\"\" data-ajax-mode=\"\"replace\"\" data-ajax-update=\"\"#some-id\"\" foo_bar=\"\"baz_quux\"\" method=\"\"get\"\">\", writer.ToString());\n        }\n\n        // Helpers\n\n        private static AjaxHelper GetAjaxHelper(bool unobtrusiveJavaScript = false)\n        {\n            var mockRequest = new Mock<HttpRequestBase>();\n            mockRequest.Setup(o => o.Url).Returns(new Uri(\"http://foo.bar.baz\"));\n            mockRequest.Setup(o => o.RawUrl).Returns(\"/rawUrl\");\n            mockRequest.Setup(o => o.PathInfo).Returns(String.Empty);\n            mockRequest.Setup(o => o.ApplicationPath).Returns(\"/app/\");\n\n            var mockResponse = new Mock<HttpResponseBase>();\n            mockResponse.Setup(o => o.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(r => MvcHelper.AppPathModifier + r);\n\n            var mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(o => o.Request).Returns(mockRequest.Object);\n            mockHttpContext.Setup(o => o.Session).Returns((HttpSessionStateBase)null);\n            mockHttpContext.Setup(o => o.Items).Returns(new Hashtable());\n            mockHttpContext.Setup(o => o.Response).Returns(mockResponse.Object);\n\n            var routes = new RouteCollection();\n            routes.MapRoute(\"default\", \"{controller}/{action}/{id}\", new { id = \"defaultid\" });\n            routes.MapRoute(\"namedroute\", \"named/{controller}/{action}/{id}\", new { id = \"defaultid\" });\n\n            var routeData = new RouteData();\n            routeData.Values.Add(\"controller\", \"home\");\n            routeData.Values.Add(\"action\", \"oldaction\");\n\n            var viewContext = new ViewContext()\n            {\n                HttpContext = mockHttpContext.Object,\n                RouteData = routeData,\n                UnobtrusiveJavaScriptEnabled = unobtrusiveJavaScript,\n                Writer = TextWriter.Null\n            };\n\n            return new AjaxHelper(viewContext, new Mock<IViewDataContainer>().Object, routes);\n        }\n\n        public void Dispose()\n        {\n            // Reset ScopeStorage (written via e.g. ViewContext.UnobtrusiveJavaScriptEnabled) between tests to avoid unexpected interactions.\n            ScopeStorage.CurrentProvider = new StaticScopeStorageProvider();\n            ScopeStorage.GlobalScope.Clear();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Ajax/Test/AjaxOptionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Ajax.Test\n{\n    public class AjaxOptionsTest\n    {\n        [Fact]\n        public void InsertionModeProperty()\n        {\n            // Arrange\n            AjaxOptions options = new AjaxOptions();\n\n            // Act & Assert\n            MemberHelper.TestEnumProperty(options, \"InsertionMode\", InsertionMode.Replace, false);\n        }\n\n        [Fact]\n        public void InsertionModePropertyExceptionText()\n        {\n            // Arrange\n            AjaxOptions options = new AjaxOptions();\n\n            // Act & Assert\n            Assert.ThrowsArgumentOutOfRange(\n                delegate { options.InsertionMode = (InsertionMode)4; },\n                \"value\",\n                @\"Specified argument was out of the range of valid values.\");\n        }\n\n        [Fact]\n        public void InsertionModeStringTests()\n        {\n            // Act & Assert\n            Assert.Equal(\"Sys.Mvc.InsertionMode.replace\", new AjaxOptions { InsertionMode = InsertionMode.Replace }.InsertionModeString);\n            Assert.Equal(\"Sys.Mvc.InsertionMode.insertAfter\", new AjaxOptions { InsertionMode = InsertionMode.InsertAfter }.InsertionModeString);\n            Assert.Equal(\"Sys.Mvc.InsertionMode.insertBefore\", new AjaxOptions { InsertionMode = InsertionMode.InsertBefore }.InsertionModeString);\n        }\n\n        [Theory]\n        [InlineData(InsertionMode.Replace, \"replace\")]\n        [InlineData(InsertionMode.InsertAfter, \"after\")]\n        [InlineData(InsertionMode.InsertBefore, \"before\")]\n        [InlineData(InsertionMode.ReplaceWith, \"replace-with\")]\n        public void InsertionModeUnobtrusiveTests(InsertionMode mode, string expected)\n        {\n            // Arrange\n            AjaxOptions options = new AjaxOptions { InsertionMode = mode };\n\n            // Act\n            string result = options.InsertionModeUnobtrusive;\n\n            // Assert\n            Assert.Equal(expected, result);\n        }\n\n        [Fact]\n        public void HttpMethodProperty()\n        {\n            // Arrange\n            AjaxOptions options = new AjaxOptions();\n\n            // Act & Assert\n            MemberHelper.TestStringProperty(options, \"HttpMethod\", String.Empty);\n        }\n\n        [Fact]\n        public void OnBeginProperty()\n        {\n            // Arrange\n            AjaxOptions options = new AjaxOptions();\n\n            // Act & Assert\n            MemberHelper.TestStringProperty(options, \"OnBegin\", String.Empty);\n        }\n\n        [Fact]\n        public void OnFailureProperty()\n        {\n            // Arrange\n            AjaxOptions options = new AjaxOptions();\n\n            // Act & Assert\n            MemberHelper.TestStringProperty(options, \"OnFailure\", String.Empty);\n        }\n\n        [Fact]\n        public void OnSuccessProperty()\n        {\n            // Arrange\n            AjaxOptions options = new AjaxOptions();\n\n            // Act & Assert\n            MemberHelper.TestStringProperty(options, \"OnSuccess\", String.Empty);\n        }\n\n        [Fact]\n        public void ToJavascriptStringWithEmptyOptions()\n        {\n            string s = (new AjaxOptions()).ToJavascriptString();\n            Assert.Equal(\"{ insertionMode: Sys.Mvc.InsertionMode.replace }\", s);\n        }\n\n        [Fact]\n        public void ToJavascriptString()\n        {\n            // Arrange\n            AjaxOptions options = new AjaxOptions\n            {\n                InsertionMode = InsertionMode.InsertBefore,\n                Confirm = \"confirm\",\n                HttpMethod = \"POST\",\n                LoadingElementId = \"loadingElement\",\n                UpdateTargetId = \"someId\",\n                Url = \"http://someurl.com\",\n                OnBegin = \"some_begin_function\",\n                OnComplete = \"some_complete_function\",\n                OnFailure = \"some_failure_function\",\n                OnSuccess = \"some_success_function\",\n            };\n\n            // Act\n            string s = options.ToJavascriptString();\n\n            // Assert\n            Assert.Equal(\"{ insertionMode: Sys.Mvc.InsertionMode.insertBefore, \" +\n                         \"confirm: 'confirm', \" +\n                         \"httpMethod: 'POST', \" +\n                         \"loadingElementId: 'loadingElement', \" +\n                         \"updateTargetId: 'someId', \" +\n                         \"url: 'http://someurl.com', \" +\n                         \"onBegin: Function.createDelegate(this, some_begin_function), \" +\n                         \"onComplete: Function.createDelegate(this, some_complete_function), \" +\n                         \"onFailure: Function.createDelegate(this, some_failure_function), \" +\n                         \"onSuccess: Function.createDelegate(this, some_success_function) }\", s);\n        }\n\n        [Fact]\n        public void ToJavascriptStringEscapesQuotesCorrectly()\n        {\n            // Arrange\n            AjaxOptions options = new AjaxOptions\n            {\n                InsertionMode = InsertionMode.InsertBefore,\n                Confirm = @\"\"\"confirm\"\"\",\n                HttpMethod = \"POST\",\n                LoadingElementId = \"loading'Element'\",\n                UpdateTargetId = \"someId\",\n                Url = \"http://someurl.com\",\n                OnBegin = \"some_begin_function\",\n                OnComplete = \"some_complete_function\",\n                OnFailure = \"some_failure_function\",\n                OnSuccess = \"some_success_function\",\n            };\n\n            // Act\n            string s = options.ToJavascriptString();\n\n            // Assert\n            Assert.Equal(\"{ insertionMode: Sys.Mvc.InsertionMode.insertBefore, \" +\n                         @\"confirm: '\"\"confirm\"\"', \" +\n                         \"httpMethod: 'POST', \" +\n                         @\"loadingElementId: 'loading\\'Element\\'', \" +\n                         \"updateTargetId: 'someId', \" +\n                         \"url: 'http://someurl.com', \" +\n                         \"onBegin: Function.createDelegate(this, some_begin_function), \" +\n                         \"onComplete: Function.createDelegate(this, some_complete_function), \" +\n                         \"onFailure: Function.createDelegate(this, some_failure_function), \" +\n                         \"onSuccess: Function.createDelegate(this, some_success_function) }\", s);\n        }\n\n        [Theory]\n        [InlineData(false)]\n        [InlineData(true)]\n        public void ToJavascriptStringIgnoresAllowCache(bool allowCache)\n        {\n            // Arrange\n            AjaxOptions options = new AjaxOptions\n            {\n                InsertionMode = InsertionMode.InsertAfter,\n                UpdateTargetId = \"someId\",\n                Url = \"http://someurl.com\",\n                OnComplete = \"some_complete_function\",\n                AllowCache = allowCache\n            };\n\n            // Act\n            string s = options.ToJavascriptString();\n\n            // Assert\n            Assert.Equal(\"{ insertionMode: Sys.Mvc.InsertionMode.insertAfter, \" +\n                         \"updateTargetId: 'someId', \" +\n                         \"url: 'http://someurl.com', \" +\n                         \"onComplete: Function.createDelegate(this, some_complete_function) }\", s);\n        }\n\n        [Fact]\n        public void ToJavascriptStringWithOnlyUpdateTargetId()\n        {\n            // Arrange\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"someId\" };\n\n            // Act\n            string s = options.ToJavascriptString();\n\n            // Assert\n            Assert.Equal(\"{ insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: 'someId' }\", s);\n        }\n\n        [Fact]\n        public void ToJavascriptStringWithUpdateTargetIdAndExplicitInsertionMode()\n        {\n            // Arrange\n            AjaxOptions options = new AjaxOptions { InsertionMode = InsertionMode.InsertAfter, UpdateTargetId = \"someId\" };\n\n            // Act\n            string s = options.ToJavascriptString();\n\n            // Assert\n            Assert.Equal(\"{ insertionMode: Sys.Mvc.InsertionMode.insertAfter, updateTargetId: 'someId' }\", s);\n        }\n\n        [Fact]\n        public void ToUnobtrusiveHtmlAttributesWithEmptyOptions()\n        {\n            // Arrange\n            AjaxOptions options = new AjaxOptions();\n\n            // Act\n            IDictionary<string, object> attributes = options.ToUnobtrusiveHtmlAttributes();\n\n            // Assert\n            Assert.Single(attributes);\n            Assert.Equal(\"true\", attributes[\"data-ajax\"]);\n        }\n\n        [Fact]\n        public void ToUnobtrusiveHtmlAttributes()\n        {\n            // Arrange\n            AjaxOptions options = new AjaxOptions\n            {\n                InsertionMode = InsertionMode.InsertBefore,\n                Confirm = \"confirm\",\n                HttpMethod = \"POST\",\n                LoadingElementId = \"loadingElement\",\n                LoadingElementDuration = 450,\n                UpdateTargetId = \"someId\",\n                Url = \"http://someurl.com\",\n                OnBegin = \"some_begin_function\",\n                OnComplete = \"some_complete_function\",\n                OnFailure = \"some_failure_function\",\n                OnSuccess = \"some_success_function\",\n            };\n\n            // Act\n            var attributes = options.ToUnobtrusiveHtmlAttributes();\n\n            // Assert\n            Assert.Equal(12, attributes.Count);\n            Assert.Equal(\"true\", attributes[\"data-ajax\"]);\n            Assert.Equal(\"confirm\", attributes[\"data-ajax-confirm\"]);\n            Assert.Equal(\"POST\", attributes[\"data-ajax-method\"]);\n            Assert.Equal(\"#loadingElement\", attributes[\"data-ajax-loading\"]);\n            Assert.Equal(450, attributes[\"data-ajax-loading-duration\"]);\n            Assert.Equal(\"http://someurl.com\", attributes[\"data-ajax-url\"]);\n            Assert.Equal(\"#someId\", attributes[\"data-ajax-update\"]);\n            Assert.Equal(\"before\", attributes[\"data-ajax-mode\"]);\n            Assert.Equal(\"some_begin_function\", attributes[\"data-ajax-begin\"]);\n            Assert.Equal(\"some_complete_function\", attributes[\"data-ajax-complete\"]);\n            Assert.Equal(\"some_failure_function\", attributes[\"data-ajax-failure\"]);\n            Assert.Equal(\"some_success_function\", attributes[\"data-ajax-success\"]);\n        }\n\n        [Fact]\n        public void ToUnobtrusiveHtmlAttributesWithAllowCache()\n        {\n            // Arrange\n            AjaxOptions options = new AjaxOptions\n            {\n                UpdateTargetId = \"someId\",\n                HttpMethod = \"GET\",\n                AllowCache = true,\n                Url = \"http://someurl.com\",\n                OnComplete = \"some_complete_function\"\n            };\n\n            // Act\n            var attributes = options.ToUnobtrusiveHtmlAttributes();\n\n            // Assert\n            Assert.Equal(7, attributes.Count);\n            Assert.Equal(\"true\", attributes[\"data-ajax\"]);\n            Assert.Equal(\"GET\", attributes[\"data-ajax-method\"]);\n            Assert.Equal(\"http://someurl.com\", attributes[\"data-ajax-url\"]);\n            Assert.Equal(\"#someId\", attributes[\"data-ajax-update\"]);\n            Assert.Equal(\"true\", attributes[\"data-ajax-cache\"]);\n            Assert.Equal(\"replace\", attributes[\"data-ajax-mode\"]);\n            Assert.Equal(\"some_complete_function\", attributes[\"data-ajax-complete\"]);\n        }\n\n        [Fact]\n        public void ToUnobtrusiveHtmlAttributesWithOnlyUpdateTargetId()\n        {\n            // Arrange\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = \"someId\" };\n\n            // Act\n            var attributes = options.ToUnobtrusiveHtmlAttributes();\n\n            // Assert\n            Assert.Equal(3, attributes.Count);\n            Assert.Equal(\"true\", attributes[\"data-ajax\"]);\n            Assert.Equal(\"#someId\", attributes[\"data-ajax-update\"]);\n            Assert.Equal(\"replace\", attributes[\"data-ajax-mode\"]); // Only added when UpdateTargetId is set\n        }\n\n\n        [Theory]\n        [InlineData(\"foo.bar\", \"#foo\\\\.bar\")]\n        [InlineData(\"baz:bar\", \"#baz\\\\:bar\")]\n        [InlineData(\"qux[zot]\", \"#qux\\\\[zot\\\\]\")]\n        [InlineData(\"foo[:zot].\", \"#foo\\\\[\\\\:zot\\\\]\\\\.\")]\n        public void ToUnobtrusiveHtmlAttributesEscapesClientSideIdentifiers(string id, string expected)\n        {\n            // Arrange\n            AjaxOptions options = new AjaxOptions { UpdateTargetId = id, LoadingElementId = id };\n\n            // Act\n            var attributes = options.ToUnobtrusiveHtmlAttributes();\n\n            // Assert\n            Assert.Equal(expected, attributes[\"data-ajax-update\"]);\n            Assert.Equal(expected, attributes[\"data-ajax-loading\"]);\n        }\n\n        [Theory]\n        [InlineData(InsertionMode.InsertAfter, \"after\")]\n        [InlineData(InsertionMode.ReplaceWith, \"replace-with\")]\n        public void ToUnobtrusiveHtmlAttributesWithUpdateTargetIdAndExplicitInsertionMode(InsertionMode mode, string expectedMode)\n        {\n            // Arrange\n            AjaxOptions options = new AjaxOptions\n            {\n                InsertionMode = mode,\n                UpdateTargetId = \"someId\"\n            };\n\n            // Act\n            var attributes = options.ToUnobtrusiveHtmlAttributes();\n\n            // Assert\n            Assert.Equal(3, attributes.Count);\n            Assert.Equal(\"true\", attributes[\"data-ajax\"]);\n            Assert.Equal(\"#someId\", attributes[\"data-ajax-update\"]);\n            Assert.Equal(expectedMode, attributes[\"data-ajax-mode\"]);\n        }\n\n        [Fact]\n        public void UpdateTargetIdProperty()\n        {\n            // Arrange\n            AjaxOptions options = new AjaxOptions();\n\n            // Act & Assert\n            MemberHelper.TestStringProperty(options, \"UpdateTargetId\", String.Empty);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Async/Test/AsyncActionDescriptorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Async.Test\n{\n    public class AsyncActionDescriptorTest\n    {\n        [Fact]\n        public void SynchronousExecuteThrows()\n        {\n            // Arrange\n            AsyncActionDescriptor actionDescriptor = new TestableAsyncActionDescriptor();\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => actionDescriptor.Execute(new Mock<ControllerContext>().Object, parameters: null),\n                \"The asynchronous action method 'testAction' cannot be executed synchronously.\"\n                );\n        }\n\n        private class TestableAsyncActionDescriptor : AsyncActionDescriptor\n        {\n            public override string ActionName\n            {\n                get { return \"testAction\"; }\n            }\n\n            public override ControllerDescriptor ControllerDescriptor\n            {\n                get { throw new NotImplementedException(); }\n            }\n\n            public override IAsyncResult BeginExecute(ControllerContext controllerContext, IDictionary<string, object> parameters, AsyncCallback callback, object state)\n            {\n                throw new NotImplementedException();\n            }\n\n            public override object EndExecute(IAsyncResult asyncResult)\n            {\n                throw new NotImplementedException();\n            }\n\n            public override ParameterDescriptor[] GetParameters()\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Async/Test/AsyncActionMethodSelectorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Async.Test\n{\n    public class AsyncActionMethodSelectorTest\n    {\n        [Fact]\n        public void AliasedMethodsProperty()\n        {\n            // Arrange\n            Type controllerType = typeof(MethodLocatorController);\n\n            // Act\n            AsyncActionMethodSelector selector = new AsyncActionMethodSelector(controllerType);\n\n            // Assert\n            Assert.Equal(3, selector.AliasedMethods.Length);\n\n            List<MethodInfo> sortedAliasedMethods = selector.AliasedMethods.OrderBy(methodInfo => methodInfo.Name).ToList();\n            Assert.Equal(\"Bar\", sortedAliasedMethods[0].Name);\n            Assert.Equal(\"FooRenamed\", sortedAliasedMethods[1].Name);\n            Assert.Equal(\"Renamed\", sortedAliasedMethods[2].Name);\n        }\n\n        [Fact]\n        public void ControllerTypeProperty()\n        {\n            // Arrange\n            Type controllerType = typeof(MethodLocatorController);\n            AsyncActionMethodSelector selector = new AsyncActionMethodSelector(controllerType);\n\n            // Act & Assert\n            Assert.Same(controllerType, selector.ControllerType);\n        }\n\n        [Fact]\n        public void FindAction_DoesNotMatchAsyncMethod()\n        {\n            // Arrange\n            Type controllerType = typeof(MethodLocatorController);\n            AsyncActionMethodSelector selector = new AsyncActionMethodSelector(controllerType);\n\n            // Act\n            ActionDescriptorCreator creator = selector.FindAction(new ControllerContext(), \"EventPatternAsync\");\n\n            // Assert\n            Assert.Null(creator);\n        }\n\n        [Fact]\n        public void FindAction_DoesNotMatchCompletedMethod()\n        {\n            // Arrange\n            Type controllerType = typeof(MethodLocatorController);\n            AsyncActionMethodSelector selector = new AsyncActionMethodSelector(controllerType);\n\n            // Act\n            ActionDescriptorCreator creator = selector.FindAction(new ControllerContext(), \"EventPatternCompleted\");\n\n            // Assert\n            Assert.Null(creator);\n        }\n\n        [Fact]\n        public void FindAction_ReturnsMatchingMethodIfOneMethodMatches()\n        {\n            // Arrange\n            Type controllerType = typeof(SelectionAttributeController);\n            AsyncActionMethodSelector selector = new AsyncActionMethodSelector(controllerType);\n\n            // Act\n            ActionDescriptorCreator creator = selector.FindAction(new ControllerContext(), \"OneMatch\");\n            ActionDescriptor actionDescriptor = creator(\"someName\", new Mock<ControllerDescriptor>().Object);\n\n            // Assert\n            var castActionDescriptor = Assert.IsType<ReflectedActionDescriptor>(actionDescriptor);\n            Assert.Equal(\"OneMatch\", castActionDescriptor.MethodInfo.Name);\n            Assert.Equal(typeof(string), castActionDescriptor.MethodInfo.GetParameters()[0].ParameterType);\n        }\n\n        [Fact]\n        public void FindAction_ReturnsMethodWithActionSelectionAttributeIfMultipleMethodsMatchRequest()\n        {\n            // DevDiv Bugs 212062: If multiple action methods match a request, we should match only the methods with an\n            // [ActionMethod] attribute since we assume those methods are more specific.\n\n            // Arrange\n            Type controllerType = typeof(SelectionAttributeController);\n            AsyncActionMethodSelector selector = new AsyncActionMethodSelector(controllerType);\n\n            // Act\n            ActionDescriptorCreator creator = selector.FindAction(new ControllerContext(), \"ShouldMatchMethodWithSelectionAttribute\");\n            ActionDescriptor actionDescriptor = creator(\"someName\", new Mock<ControllerDescriptor>().Object);\n\n            // Assert\n            var castActionDescriptor = Assert.IsType<ReflectedActionDescriptor>(actionDescriptor);\n            Assert.Equal(\"MethodHasSelectionAttribute1\", castActionDescriptor.MethodInfo.Name);\n        }\n\n        [Fact]\n        public void FindAction_ReturnsNullIfNoMethodMatches()\n        {\n            // Arrange\n            Type controllerType = typeof(SelectionAttributeController);\n            AsyncActionMethodSelector selector = new AsyncActionMethodSelector(controllerType);\n\n            // Act\n            ActionDescriptorCreator creator = selector.FindAction(new ControllerContext(), \"ZeroMatch\");\n\n            // Assert\n            Assert.Null(creator);\n        }\n\n        [Fact]\n        public void FindAction_ThrowsIfMultipleMethodsMatch()\n        {\n            // Arrange\n            Type controllerType = typeof(SelectionAttributeController);\n            AsyncActionMethodSelector selector = new AsyncActionMethodSelector(controllerType);\n\n            // Act & veriy\n            Assert.Throws<AmbiguousMatchException>(\n                delegate { selector.FindAction(new ControllerContext(), \"TwoMatch\"); },\n                \"The current request for action 'TwoMatch' on controller type 'SelectionAttributeController' is ambiguous between the following action methods:\" + Environment.NewLine\n              + \"Void TwoMatch2() on type System.Web.Mvc.Async.Test.AsyncActionMethodSelectorTest+SelectionAttributeController\" + Environment.NewLine\n              + \"Void TwoMatch() on type System.Web.Mvc.Async.Test.AsyncActionMethodSelectorTest+SelectionAttributeController\");\n        }\n\n        [Fact]\n        public void FindActionMethod_Asynchronous()\n        {\n            // Arrange\n            Type controllerType = typeof(MethodLocatorController);\n            AsyncActionMethodSelector selector = new AsyncActionMethodSelector(controllerType);\n\n            // Act\n            ActionDescriptorCreator creator = selector.FindAction(new ControllerContext(), \"EventPattern\");\n            ActionDescriptor actionDescriptor = creator(\"someName\", new Mock<ControllerDescriptor>().Object);\n\n            // Assert\n            var castActionDescriptor = Assert.IsType<ReflectedAsyncActionDescriptor>(actionDescriptor);\n            Assert.Equal(\"EventPatternAsync\", castActionDescriptor.AsyncMethodInfo.Name);\n            Assert.Equal(\"EventPatternCompleted\", castActionDescriptor.CompletedMethodInfo.Name);\n        }\n\n        [Fact]\n        public void FindActionMethod_Task()\n        {\n            // Arrange\n            Type controllerType = typeof(MethodLocatorController);\n            AsyncActionMethodSelector selector = new AsyncActionMethodSelector(controllerType);\n\n            // Act\n            ActionDescriptorCreator creator = selector.FindAction(new ControllerContext(), \"TaskPattern\");\n            ActionDescriptor actionDescriptor = creator(\"someName\", new Mock<ControllerDescriptor>().Object);\n\n            // Assert\n            var castActionDescriptor = Assert.IsType<TaskAsyncActionDescriptor>(actionDescriptor);\n            Assert.Equal(\"TaskPattern\", castActionDescriptor.TaskMethodInfo.Name);\n            Assert.Equal(typeof(Task), castActionDescriptor.TaskMethodInfo.ReturnType);\n        }\n\n        [Fact]\n        public void FindActionMethod_GenericTask()\n        {\n            // Arrange\n            Type controllerType = typeof(MethodLocatorController);\n            AsyncActionMethodSelector selector = new AsyncActionMethodSelector(controllerType);\n\n            // Act\n            ActionDescriptorCreator creator = selector.FindAction(new ControllerContext(), \"GenericTaskPattern\");\n            ActionDescriptor actionDescriptor = creator(\"someName\", new Mock<ControllerDescriptor>().Object);\n\n            // Assert\n            var castActionDescriptor = Assert.IsType<TaskAsyncActionDescriptor>(actionDescriptor);\n            Assert.Equal(\"GenericTaskPattern\", castActionDescriptor.TaskMethodInfo.Name);\n            Assert.Equal(typeof(Task<string>), castActionDescriptor.TaskMethodInfo.ReturnType);\n        }\n\n        [Fact]\n        public void FindActionMethod_Asynchronous_ThrowsIfCompletionMethodNotFound()\n        {\n            // Arrange\n            Type controllerType = typeof(MethodLocatorController);\n            AsyncActionMethodSelector selector = new AsyncActionMethodSelector(controllerType);\n\n            // Act & assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { ActionDescriptorCreator creator = selector.FindAction(new ControllerContext(), \"EventPatternWithoutCompletionMethod\"); },\n                @\"Could not locate a method named 'EventPatternWithoutCompletionMethodCompleted' on controller type System.Web.Mvc.Async.Test.AsyncActionMethodSelectorTest+MethodLocatorController.\");\n        }\n\n        [Fact]\n        public void FindActionMethod_Asynchronous_ThrowsIfMultipleCompletedMethodsMatched()\n        {\n            // Arrange\n            Type controllerType = typeof(MethodLocatorController);\n            AsyncActionMethodSelector selector = new AsyncActionMethodSelector(controllerType);\n\n            // Act & assert\n            Assert.Throws<AmbiguousMatchException>(\n                delegate { ActionDescriptorCreator creator = selector.FindAction(new ControllerContext(), \"EventPatternAmbiguous\"); },\n                \"Lookup for method 'EventPatternAmbiguousCompleted' on controller type 'MethodLocatorController' failed because of an ambiguity between the following methods:\" + Environment.NewLine\n              + \"Void EventPatternAmbiguousCompleted(Int32) on type System.Web.Mvc.Async.Test.AsyncActionMethodSelectorTest+MethodLocatorController\" + Environment.NewLine\n              + \"Void EventPatternAmbiguousCompleted(System.String) on type System.Web.Mvc.Async.Test.AsyncActionMethodSelectorTest+MethodLocatorController\");\n        }\n\n        [Fact]\n        public void FindAction_NullContext_Throws()\n        {\n            // Arrange\n            Type controllerType = typeof(MethodLocatorController);\n            AsyncActionMethodSelector selector = new AsyncActionMethodSelector(controllerType);\n\n            // Act & Assert\n            Assert.Throws<ArgumentNullException>(() => selector.FindAction(null, \"Action\"));\n        }\n\n        [Fact]\n        public void NonAliasedMethodsProperty()\n        {\n            // Arrange\n            Type controllerType = typeof(MethodLocatorController);\n\n            // Act\n            AsyncActionMethodSelector selector = new AsyncActionMethodSelector(controllerType);\n\n            // Assert\n            Assert.Equal(6, selector.NonAliasedMethods.Count);\n\n            List<MethodInfo> sortedMethods = selector.NonAliasedMethods[\"foo\"].OrderBy(method => method.GetParameters().Length).ToList();\n            Assert.Equal(\"Foo\", sortedMethods[0].Name);\n            Assert.Empty(sortedMethods[0].GetParameters());\n            Assert.Equal(\"Foo\", sortedMethods[1].Name);\n            Assert.Equal(typeof(string), sortedMethods[1].GetParameters()[0].ParameterType);\n\n            MethodInfo methodInfo = Assert.Single(selector.NonAliasedMethods[\"EventPattern\"]);\n            Assert.Equal(\"EventPatternAsync\", methodInfo.Name);\n            methodInfo = Assert.Single(selector.NonAliasedMethods[\"EventPatternAmbiguous\"]);\n            Assert.Equal(\"EventPatternAmbiguousAsync\", methodInfo.Name);\n            methodInfo = Assert.Single(selector.NonAliasedMethods[\"EventPatternWithoutCompletionMethod\"]);\n            Assert.Equal(\"EventPatternWithoutCompletionMethodAsync\", methodInfo.Name);\n\n            methodInfo = Assert.Single(selector.NonAliasedMethods[\"TaskPattern\"]);\n            Assert.Equal(\"TaskPattern\", methodInfo.Name);\n            methodInfo = Assert.Single(selector.NonAliasedMethods[\"GenericTaskPattern\"]);\n            Assert.Equal(\"GenericTaskPattern\", methodInfo.Name);\n        }\n\n        private class MethodLocatorController : Controller\n        {\n            public void Foo()\n            {\n            }\n\n            public void Foo(string s)\n            {\n            }\n\n            [ActionName(\"Foo\")]\n            public void FooRenamed()\n            {\n            }\n\n            [ActionName(\"Bar\")]\n            public void Bar()\n            {\n            }\n\n            [ActionName(\"PrivateVoid\")]\n            private void PrivateVoid()\n            {\n            }\n\n            protected void ProtectedVoidAction()\n            {\n            }\n\n            public static void StaticMethod()\n            {\n            }\n\n            public void EventPatternAsync()\n            {\n            }\n\n            public void EventPatternCompleted()\n            {\n            }\n\n            public void EventPatternWithoutCompletionMethodAsync()\n            {\n            }\n\n            public void EventPatternAmbiguousAsync()\n            {\n            }\n\n            public void EventPatternAmbiguousCompleted(int i)\n            {\n            }\n\n            public void EventPatternAmbiguousCompleted(string s)\n            {\n            }\n\n            public Task TaskPattern()\n            {\n                return Task.Factory.StartNew(() => \"foo\");\n            }\n\n            public Task<string> GenericTaskPattern()\n            {\n                return Task.Factory.StartNew(() => \"foo\");\n            }\n\n            [ActionName(\"RenamedCompleted\")]\n            public void Renamed()\n            {\n            }\n\n            // ensure that methods inheriting from Controller or a base class are not matched\n            [ActionName(\"Blah\")]\n            protected override void ExecuteCore()\n            {\n                throw new NotImplementedException();\n            }\n\n            public string StringProperty { get; set; }\n\n#pragma warning disable 0067\n            public event EventHandler<EventArgs> SomeEvent;\n#pragma warning restore 0067\n        }\n\n        private class SelectionAttributeController : Controller\n        {\n            [Match(false)]\n            public void OneMatch()\n            {\n            }\n\n            public void OneMatch(string s)\n            {\n            }\n\n            public void TwoMatch()\n            {\n            }\n\n            [ActionName(\"TwoMatch\")]\n            public void TwoMatch2()\n            {\n            }\n\n            [Match(true), ActionName(\"ShouldMatchMethodWithSelectionAttribute\")]\n            public void MethodHasSelectionAttribute1()\n            {\n            }\n\n            [ActionName(\"ShouldMatchMethodWithSelectionAttribute\")]\n            public void MethodDoesNotHaveSelectionAttribute1()\n            {\n            }\n\n            private class MatchAttribute : ActionMethodSelectorAttribute\n            {\n                private bool _match;\n\n                public MatchAttribute(bool match)\n                {\n                    _match = match;\n                }\n\n                public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)\n                {\n                    return _match;\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Async/Test/AsyncControllerActionInvokerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Threading;\nusing System.Web.Mvc.Filters;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Async.Test\n{\n    public class AsyncControllerActionInvokerTest\n    {\n        [Fact]\n        public void InvokeAction_ActionNotFound()\n        {\n            // Arrange\n            ControllerContext controllerContext = GetControllerContext();\n            AsyncControllerActionInvoker invoker = new AsyncControllerActionInvoker();\n\n            // Act\n            IAsyncResult asyncResult = invoker.BeginInvokeAction(controllerContext, \"ActionNotFound\", null, null);\n            bool retVal = invoker.EndInvokeAction(asyncResult);\n\n            // Assert\n            Assert.False(retVal);\n        }\n\n        [Fact]\n        public void InvokeAction_ActionThrowsException_Handled()\n        {\n            // Arrange\n            ControllerContext controllerContext = GetControllerContext();\n            AsyncControllerActionInvoker invoker = new AsyncControllerActionInvoker();\n\n            // Act & assert\n            IAsyncResult asyncResult = invoker.BeginInvokeAction(controllerContext, \"ActionThrowsExceptionAndIsHandled\", null, null);\n            Assert.Null(((TestController)controllerContext.Controller).Log); // Result filter shouldn't have executed yet\n\n            bool retVal = invoker.EndInvokeAction(asyncResult);\n            Assert.True(retVal);\n            Assert.Equal(\"From exception filter\", ((TestController)controllerContext.Controller).Log);\n        }\n\n        [Fact]\n        public void InvokeAction_ActionThrowsException_NotHandled()\n        {\n            // Arrange\n            ControllerContext controllerContext = GetControllerContext();\n            AsyncControllerActionInvoker invoker = new AsyncControllerActionInvoker();\n\n            // Act & assert\n            Assert.Throws<Exception>(\n                delegate { invoker.BeginInvokeAction(controllerContext, \"ActionThrowsExceptionAndIsNotHandled\", null, null); },\n                @\"Some exception text.\");\n        }\n\n        [Fact]\n        public void InvokeAction_ActionThrowsException_ThreadAbort()\n        {\n            // Arrange\n            ControllerContext controllerContext = GetControllerContext();\n            AsyncControllerActionInvoker invoker = new AsyncControllerActionInvoker();\n\n            // Act & assert\n            Assert.Throws<ThreadAbortException>(\n                delegate { invoker.BeginInvokeAction(controllerContext, \"ActionCallsThreadAbort\", null, null); });\n        }\n\n        [Fact]\n        public void InvokeAction_AuthenticationFilterShortCircuits()\n        {\n            // Arrange\n            ControllerContext controllerContext = GetControllerContext();\n            AsyncControllerActionInvoker invoker = new AsyncControllerActionInvoker();\n\n            // Act\n            IAsyncResult asyncResult = invoker.BeginInvokeAction(controllerContext, \"AuthenticationFilterShortCircuits\", null, null);\n            bool retVal = invoker.EndInvokeAction(asyncResult);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Equal(\"From authentication filter\", ((TestController)controllerContext.Controller).Log);\n        }\n\n        [Fact]\n        public void InvokeAction_AuthenticationFilterChallenges()\n        {\n            // Arrange\n            ControllerContext controllerContext = GetControllerContext();\n            AsyncControllerActionInvoker invoker = new AsyncControllerActionInvoker();\n\n            // Act\n            IAsyncResult asyncResult = invoker.BeginInvokeAction(controllerContext, \"AuthenticationFilterChallenges\", null, null);\n            bool retVal = invoker.EndInvokeAction(asyncResult);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Equal(\"From authentication filter challenge\", ((TestController)controllerContext.Controller).Log);\n        }\n\n        [Fact]\n        public void InvokeAction_AuthenticationFilterShortCircuitsAndChallenges()\n        {\n            // Arrange\n            ControllerContext controllerContext = GetControllerContext();\n            AsyncControllerActionInvoker invoker = new AsyncControllerActionInvoker();\n\n            // Act\n            IAsyncResult asyncResult = invoker.BeginInvokeAction(controllerContext, \"AuthenticationFilterShortCircuitsAndChallenges\", null, null);\n            bool retVal = invoker.EndInvokeAction(asyncResult);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Equal(\"From authentication filter challenge\", ((TestController)controllerContext.Controller).Log);\n        }\n\n        [Fact]\n        public void InvokeAction_AuthorizationFilterShortCircuits()\n        {\n            // Arrange\n            ControllerContext controllerContext = GetControllerContext();\n            AsyncControllerActionInvoker invoker = new AsyncControllerActionInvoker();\n\n            // Act\n            IAsyncResult asyncResult = invoker.BeginInvokeAction(controllerContext, \"AuthorizationFilterShortCircuits\", null, null);\n            bool retVal = invoker.EndInvokeAction(asyncResult);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Equal(\"From authorization filter\", ((TestController)controllerContext.Controller).Log);\n        }\n\n        [Fact]\n        public void InvokeAction_AuthorizationFilterShortCircuitsAndChallenges()\n        {\n            // Arrange\n            ControllerContext controllerContext = GetControllerContext();\n            AsyncControllerActionInvoker invoker = new AsyncControllerActionInvoker();\n\n            // Act\n            IAsyncResult asyncResult = invoker.BeginInvokeAction(controllerContext, \"AuthorizationFilterShortCircuitsAndChallenges\", null, null);\n            bool retVal = invoker.EndInvokeAction(asyncResult);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Equal(\"From authentication filter challenge\", ((TestController)controllerContext.Controller).Log);\n        }\n\n        [Fact]\n        public void InvokeAction_NormalAction()\n        {\n            // Arrange\n            ControllerContext controllerContext = GetControllerContext();\n            AsyncControllerActionInvoker invoker = new AsyncControllerActionInvoker();\n\n            // Act\n            IAsyncResult asyncResult = invoker.BeginInvokeAction(controllerContext, \"NormalAction\", null, null);\n            bool retVal = invoker.EndInvokeAction(asyncResult);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Equal(\"From action\", ((TestController)controllerContext.Controller).Log);\n        }\n\n        [Fact]\n        public void InvokeAction_OverrideFindAction()\n        {\n            // Arrange\n            ControllerContext controllerContext = GetControllerContext();\n            AsyncControllerActionInvoker invoker = new AsyncControllerActionInvokerWithCustomFindAction();\n\n            // Act\n            IAsyncResult asyncResult = invoker.BeginInvokeAction(controllerContext, actionName: \"Non-ExistantAction\", callback: null, state: null);\n            bool retVal = invoker.EndInvokeAction(asyncResult);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Equal(\"From action\", ((TestController)controllerContext.Controller).Log);\n        }\n\n        [Fact]\n        public void InvokeAction_RequestValidationFails()\n        {\n            // Arrange\n            ControllerContext controllerContext = GetControllerContext(passesRequestValidation: false);\n            AsyncControllerActionInvoker invoker = new AsyncControllerActionInvoker();\n\n            // Act & assert\n            Assert.Throws<HttpRequestValidationException>(\n                delegate { invoker.BeginInvokeAction(controllerContext, \"NormalAction\", null, null); });\n        }\n\n        [Fact]\n        public void InvokeAction_ResultThrowsException_Handled()\n        {\n            // Arrange\n            ControllerContext controllerContext = GetControllerContext();\n            AsyncControllerActionInvoker invoker = new AsyncControllerActionInvoker();\n\n            // Act & assert\n            IAsyncResult asyncResult = invoker.BeginInvokeAction(controllerContext, \"ResultThrowsExceptionAndIsHandled\", null, null);\n            bool retVal = invoker.EndInvokeAction(asyncResult);\n\n            Assert.True(retVal);\n            Assert.Equal(\"From exception filter\", ((TestController)controllerContext.Controller).Log);\n        }\n\n        [Fact]\n        public void InvokeAction_ResultThrowsException_NotHandled()\n        {\n            // Arrange\n            ControllerContext controllerContext = GetControllerContext();\n            AsyncControllerActionInvoker invoker = new AsyncControllerActionInvoker();\n\n            // Act & assert\n            IAsyncResult asyncResult = invoker.BeginInvokeAction(controllerContext, \"ResultThrowsExceptionAndIsNotHandled\", null, null);\n            Assert.Throws<Exception>(\n                delegate { invoker.EndInvokeAction(asyncResult); },\n                @\"Some exception text.\");\n        }\n\n        [Fact]\n        public void InvokeAction_ResultThrowsException_ThreadAbort()\n        {\n            // Arrange\n            ControllerContext controllerContext = GetControllerContext();\n            AsyncControllerActionInvoker invoker = new AsyncControllerActionInvoker();\n\n            // Act & assert\n            IAsyncResult asyncResult = invoker.BeginInvokeAction(controllerContext, \"ResultCallsThreadAbort\", null, null);\n            Assert.Throws<ThreadAbortException>(\n                delegate { invoker.EndInvokeAction(asyncResult); });\n        }\n\n        [Fact]\n        public void InvokeAction_ThrowsIfActionNameIsEmpty()\n        {\n            // Arrange\n            AsyncControllerActionInvoker invoker = new AsyncControllerActionInvoker();\n\n            // Act & assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { invoker.BeginInvokeAction(new ControllerContext(), \"\", null, null); }, \"actionName\");\n        }\n\n        [Fact]\n        public void InvokeAction_ThrowsIfActionNameIsNull()\n        {\n            // Arrange\n            AsyncControllerActionInvoker invoker = new AsyncControllerActionInvoker();\n\n            // Act & assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { invoker.BeginInvokeAction(new ControllerContext(), null, null, null); }, \"actionName\");\n        }\n\n        [Fact]\n        public void InvokeAction_ThrowsIfControllerContextIsNull()\n        {\n            // Arrange\n            AsyncControllerActionInvoker invoker = new AsyncControllerActionInvoker();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { invoker.BeginInvokeAction(null, \"someAction\", null, null); }, \"controllerContext\");\n        }\n\n        [Fact]\n        public void InvokeActionMethod_AsynchronousDescriptor()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            Dictionary<string, object> parameters = new Dictionary<string, object>();\n            using (MockAsyncResult innerAsyncResult = new MockAsyncResult())\n            {\n                ActionResult expectedResult = new ViewResult();\n\n                Mock<AsyncActionDescriptor> mockActionDescriptor = new Mock<AsyncActionDescriptor>();\n                mockActionDescriptor.Setup(d => d.BeginExecute(controllerContext, parameters, It.IsAny<AsyncCallback>(), It.IsAny<object>())).Returns(innerAsyncResult);\n                mockActionDescriptor.Setup(d => d.EndExecute(innerAsyncResult)).Returns(expectedResult);\n\n                AsyncControllerActionInvoker invoker = new AsyncControllerActionInvoker();\n\n                // Act\n                IAsyncResult asyncResult = invoker.BeginInvokeActionMethod(controllerContext, mockActionDescriptor.Object, parameters, null, null);\n                ActionResult returnedResult = invoker.EndInvokeActionMethod(asyncResult);\n\n                // Assert\n                Assert.Equal(expectedResult, returnedResult);\n            }\n        }\n\n        [Fact]\n        public void InvokeActionMethod_SynchronousDescriptor()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            Dictionary<string, object> parameters = new Dictionary<string, object>();\n            ActionResult expectedResult = new ViewResult();\n\n            Mock<ActionDescriptor> mockActionDescriptor = new Mock<ActionDescriptor>();\n            mockActionDescriptor.Setup(d => d.Execute(controllerContext, parameters)).Returns(expectedResult);\n\n            AsyncControllerActionInvoker invoker = new AsyncControllerActionInvoker();\n\n            // Act\n            IAsyncResult asyncResult = invoker.BeginInvokeActionMethod(controllerContext, mockActionDescriptor.Object, parameters, null, null);\n            ActionResult returnedResult = invoker.EndInvokeActionMethod(asyncResult);\n\n            // Assert\n            Assert.Equal(expectedResult, returnedResult);\n        }\n\n        [Fact]\n        public void BeginInvokeActionMethodWithFilters_BeginExecuteThrowsOnActionExecutingException_Handled()\n        {\n            // Arrange\n            ActionResult expectedResult = new ViewResult();\n            Exception expectedException = new Exception(\"Some exception text.\");\n            bool onActionExecutingWasCalled = false;\n            bool onActionExecutedWasCalled = false;\n            ActionFilterImpl actionFilter = new ActionFilterImpl()\n            {\n                OnActionExecutingImpl = filterContext => { onActionExecutingWasCalled = true; },\n                OnActionExecutedImpl = filterContext =>\n                {\n                    onActionExecutedWasCalled = true;\n                    Assert.Same(expectedException, filterContext.Exception);\n                    filterContext.ExceptionHandled = true;\n                    filterContext.Result = expectedResult;\n                }\n            };\n            Func<IAsyncResult> beginExecute = delegate\n            {\n                throw expectedException;\n            };\n\n            // Act\n            ActionResult result = BeginInvokeActionMethodWithFiltersBeginTester(beginExecute, actionFilter);\n\n            // Assert\n            Assert.True(onActionExecutingWasCalled);\n            Assert.True(onActionExecutedWasCalled);\n            Assert.Equal(expectedResult, result);\n        }\n\n        [Fact]\n        public void BeginInvokeActionMethodWithFilters_BeginExecuteThrowsOnActionExecutingException_HandledByEarlier()\n        {\n            // Arrange\n            ActionResult expectedResult = new ViewResult();\n            List<string> actionLog = new List<string>();\n            Exception exception = new Exception(\"Some exception text.\");\n            Func<IAsyncResult> beginExecute = delegate\n            {\n                actionLog.Add(\"BeginExecute\");\n                throw exception;\n            };\n            ActionFilterImpl filter1 = new ActionFilterImpl()\n            {\n                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) { actionLog.Add(\"OnActionExecuting1\"); },\n                OnActionExecutedImpl = delegate(ActionExecutedContext filterContext)\n                {\n                    actionLog.Add(\"OnActionExecuted1\");\n                    Assert.Same(exception, filterContext.Exception);\n                    filterContext.ExceptionHandled = true;\n                    filterContext.Result = expectedResult;\n                }\n            };\n            ActionFilterImpl filter2 = new ActionFilterImpl()\n            {\n                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) { actionLog.Add(\"OnActionExecuting2\"); },\n                OnActionExecutedImpl = delegate(ActionExecutedContext filterContext) { actionLog.Add(\"OnActionExecuted2\"); }\n            };\n\n            // Act\n            ActionResult result = BeginInvokeActionMethodWithFiltersBeginTester(beginExecute, filter1, filter2);\n\n            // Assert\n            Assert.Equal(new[] { \"OnActionExecuting1\", \"OnActionExecuting2\", \"BeginExecute\", \"OnActionExecuted2\", \"OnActionExecuted1\" }, actionLog.ToArray());\n            Assert.Equal(expectedResult, result);\n        }\n\n        [Fact]\n        public void BeginInvokeActionMethodWithFilters_BeginExecuteThrowsOnActionExecutingException_HandledByLater()\n        {\n            // Arrange\n            List<string> actionLog = new List<string>();\n            Exception exception = new Exception(\"Some exception text.\");\n            ActionResult expectedResult = new ViewResult();\n            Func<IAsyncResult> beginExecute = delegate\n            {\n                actionLog.Add(\"BeginExecute\");\n                throw exception;\n            };\n            ActionFilterImpl filter1 = new ActionFilterImpl()\n            {\n                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) { actionLog.Add(\"OnActionExecuting1\"); },\n                OnActionExecutedImpl = delegate(ActionExecutedContext filterContext) { actionLog.Add(\"OnActionExecuted1\"); }\n            };\n            ActionFilterImpl filter2 = new ActionFilterImpl()\n            {\n                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) { actionLog.Add(\"OnActionExecuting2\"); },\n                OnActionExecutedImpl = delegate(ActionExecutedContext filterContext)\n                {\n                    actionLog.Add(\"OnActionExecuted2\");\n                    Assert.Same(exception, filterContext.Exception);\n                    filterContext.ExceptionHandled = true;\n                    filterContext.Result = expectedResult;\n                }\n            };\n\n            // Act\n            ActionResult result = BeginInvokeActionMethodWithFiltersBeginTester(beginExecute, filter1, filter2);\n\n            // Assert\n            Assert.Equal(new[] { \"OnActionExecuting1\", \"OnActionExecuting2\", \"BeginExecute\", \"OnActionExecuted2\", \"OnActionExecuted1\" }, actionLog.ToArray());\n            Assert.Equal(expectedResult, result);\n        }\n\n        [Fact]\n        public void BeginInvokeActionMethodWithFilters_BeginExecuteThrowsOnActionExecutingException_NotHandled()\n        {\n            // Arrange\n            string expectedExceptionText = \"Some exception text.\";\n            Exception expectedException = new Exception(expectedExceptionText);\n            bool onActionExecutingWasCalled = false;\n            bool onActionExecutedWasCalled = false;\n            ActionFilterImpl actionFilter = new ActionFilterImpl()\n            {\n                OnActionExecutingImpl = filterContext => { onActionExecutingWasCalled = true; },\n                OnActionExecutedImpl = filterContext => { onActionExecutedWasCalled = true; }\n            };\n            Func<IAsyncResult> beginExecute = delegate\n            {\n                throw expectedException;\n            };\n\n            // Act & assert\n            Assert.Throws<Exception>(\n                delegate\n                {\n                    BeginInvokeActionMethodWithFiltersBeginTester(beginExecute, actionFilter);\n                },\n                expectedExceptionText);\n\n            // Assert\n            Assert.True(onActionExecutingWasCalled);\n            Assert.True(onActionExecutedWasCalled);\n        }\n\n        [Fact]\n        public void BeginInvokeActionMethodWithFilters_BeginExecuteThrowsOnActionExecutingException_ThreadAbort()\n        {\n            // Arrange\n            bool onActionExecutingWasCalled = false;\n            bool onActionExecutedWasCalled = false;\n            ActionFilterImpl actionFilter = new ActionFilterImpl()\n            {\n                OnActionExecutingImpl = filterContext => { onActionExecutingWasCalled = true; },\n                OnActionExecutedImpl = filterContext =>\n                {\n                    onActionExecutedWasCalled = true;\n                    Thread.ResetAbort();\n                }\n            };\n            Func<IAsyncResult> beginExecute = delegate\n            {\n                Thread.CurrentThread.Abort();\n                return null;\n            };\n\n            // Act & assert\n            Assert.Throws<ThreadAbortException>(\n                delegate\n                {\n                    BeginInvokeActionMethodWithFiltersBeginTester(beginExecute, actionFilter);\n                });\n\n            // Assert\n            Assert.True(onActionExecutingWasCalled);\n            Assert.True(onActionExecutedWasCalled);\n        }\n\n        [Fact]\n        public void BeginInvokeActionMethodWithFilters_EndExecuteThrowsOnActionExecutedException_Handled()\n        {\n            // Arrange\n            ViewResult expectedResult = new ViewResult();\n            Exception exepctedException = new Exception(\"Some exception message.\");\n            bool actionCalled = false;\n            bool onActionExecutedCalled = false;\n            ActionFilterImpl actionFilter = new ActionFilterImpl()\n            {\n                OnActionExecutedImpl = (filterContext) =>\n                {\n                    onActionExecutedCalled = true;\n                    Assert.Same(exepctedException, filterContext.Exception);\n                    filterContext.ExceptionHandled = true;\n                    filterContext.Result = expectedResult;\n                }\n            };\n            Func<ActionResult> action = () =>\n            {\n                actionCalled = true;\n                throw exepctedException;\n            };\n\n            using (var mockResult = new MockAsyncResult())\n            {\n                // Act\n                ActionResult result = BeginInvokeActionMethodWithFiltersEndTester(mockResult, action, actionFilter);\n\n                // Assert\n                Assert.True(actionCalled);\n                Assert.True(onActionExecutedCalled);\n                Assert.Equal(expectedResult, result);\n            }\n        }\n\n        [Fact]\n        public void BeginInvokeActionMethodWithFilters_EndExecuteThrowsOnActionExecutedException_HandledByEarlier()\n        {\n            // Arrange\n            List<string> actionLog = new List<string>();\n            Exception exception = new Exception(\"Some exception message.\");\n            ViewResult expectedResult = new ViewResult();\n            Func<ActionResult> action = delegate\n            {\n                actionLog.Add(\"EndExecute\");\n                throw exception;\n\n            };\n            ActionFilterImpl filter1 = new ActionFilterImpl()\n            {\n                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) { actionLog.Add(\"OnActionExecuting1\"); },\n                OnActionExecutedImpl = delegate(ActionExecutedContext filterContext)\n                {\n                    actionLog.Add(\"OnActionExecuted1\");\n                    Assert.Same(exception, filterContext.Exception);\n                    filterContext.ExceptionHandled = true;\n                    filterContext.Result = expectedResult;\n                }\n            };\n            ActionFilterImpl filter2 = new ActionFilterImpl()\n            {\n                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) { actionLog.Add(\"OnActionExecuting2\"); },\n                OnActionExecutedImpl = delegate(ActionExecutedContext filterContext) { actionLog.Add(\"OnActionExecuted2\"); }\n            };\n\n            using (var mockResult = new MockAsyncResult())\n            {\n                // Act\n                ActionResult result = BeginInvokeActionMethodWithFiltersEndTester(mockResult, action, filter1, filter2);\n\n                // Assert\n                Assert.Equal(new[] { \"OnActionExecuting1\", \"OnActionExecuting2\", \"EndExecute\", \"OnActionExecuted2\", \"OnActionExecuted1\" }, actionLog.ToArray());\n                Assert.Equal(expectedResult, result);\n            }\n        }\n\n        [Fact]\n        public void BeginInvokeActionMethodWithFilters_EndExecuteThrowsOnActionExecutedException_HandledByLater()\n        {\n            // Arrange\n            List<string> actionLog = new List<string>();\n            Exception exception = new Exception(\"Some exception message.\");\n            ActionResult expectedResult = new ViewResult();\n            Func<ActionResult> action = delegate\n            {\n                actionLog.Add(\"EndExecute\");\n                throw exception;\n\n            };\n            ActionFilterImpl filter1 = new ActionFilterImpl()\n            {\n                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) { actionLog.Add(\"OnActionExecuting1\"); },\n                OnActionExecutedImpl = delegate(ActionExecutedContext filterContext) { actionLog.Add(\"OnActionExecuted1\"); }\n            };\n            ActionFilterImpl filter2 = new ActionFilterImpl()\n            {\n                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) { actionLog.Add(\"OnActionExecuting2\"); },\n                OnActionExecutedImpl = delegate(ActionExecutedContext filterContext)\n                {\n                    actionLog.Add(\"OnActionExecuted2\");\n                    Assert.Same(exception, filterContext.Exception);\n                    filterContext.ExceptionHandled = true;\n                    filterContext.Result = expectedResult;\n                }\n            };\n\n            using (var mockResult = new MockAsyncResult())\n            {\n                // Act\n                ActionResult result = BeginInvokeActionMethodWithFiltersEndTester(mockResult, action, filter1, filter2);\n\n                // Assert\n                Assert.Equal(new[] { \"OnActionExecuting1\", \"OnActionExecuting2\", \"EndExecute\", \"OnActionExecuted2\", \"OnActionExecuted1\" }, actionLog.ToArray());\n                Assert.Equal(expectedResult, result);\n            }\n        }\n\n        [Fact]\n        public void BeginInvokeActionMethodWithFilters_EndExecuteThrowsOnActionExecutedException_NotHandled()\n        {\n            // Arrange\n            bool onActionExecutedWasCalled = false;\n            string expectedExceptionText = \"Some exception text.\";\n            ActionFilterImpl actionFilter = new ActionFilterImpl()\n            {\n                OnActionExecutedImpl = filterContext => { onActionExecutedWasCalled = true; }\n            };\n            Func<ActionResult> action = delegate\n            {\n                throw new Exception(expectedExceptionText);\n            };\n\n            using (var mockResult = new MockAsyncResult())\n            {\n                // Act & assert\n                Assert.Throws<Exception>(\n                    () => BeginInvokeActionMethodWithFiltersEndTester(mockResult, action, actionFilter),\n                    expectedExceptionText);\n\n                // Assert\n                Assert.True(onActionExecutedWasCalled);\n            }\n        }\n\n        [Fact]\n        public void BeginInvokeActionMethodWithFilters_EndExecuteThrowsOnActionExecutedException_ThreadAbort()\n        {\n            // Arrange\n            bool onActionExecutedWasCalled = false;\n            ActionFilterImpl actionFilter = new ActionFilterImpl()\n            {\n                OnActionExecutedImpl = filterContext =>\n                {\n                    onActionExecutedWasCalled = true;\n                    Thread.ResetAbort();\n                }\n            };\n            Func<ActionResult> action = delegate\n            {\n                Thread.CurrentThread.Abort();\n                return null;\n            };\n\n            using (var mockResult = new MockAsyncResult())\n            {\n                // Act & assert\n                Assert.Throws<ThreadAbortException>(\n                    () => BeginInvokeActionMethodWithFiltersEndTester(mockResult, action, actionFilter));\n\n                // Assert\n                Assert.True(onActionExecutedWasCalled);\n            }\n        }\n\n        [Fact]\n        public void BeginInvokeActionMethodWithFilters_NormalExecutionNotCanceled()\n        {\n            // Arrange\n            bool onActionExecutingWasCalled = false;\n            bool onActionExecutedWasCalled = false;\n            using (MockAsyncResult innerAsyncResult = new MockAsyncResult())\n            {\n                ActionFilterImpl actionFilter = new ActionFilterImpl()\n                {\n                    OnActionExecutingImpl = _ => { onActionExecutingWasCalled = true; },\n                    OnActionExecutedImpl = _ => { onActionExecutedWasCalled = true; }\n                };\n                Func<IAsyncResult> beginExecute = delegate\n                {\n                    return innerAsyncResult;\n                };\n\n                // Act\n                ActionResult result = BeginInvokeActionMethodWithFiltersBeginTester(beginExecute, actionFilter);\n\n                // Assert\n                Assert.True(onActionExecutingWasCalled);\n                Assert.True(onActionExecutedWasCalled);\n            }\n        }\n\n        [Fact]\n        public void BeginInvokeActionMethodWithFilters_OnActionExecutingSetsResult()\n        {\n            // Arrange\n            ActionResult expectedResult = new ViewResult();\n            ActionResult overriddenResult = new ViewResult();\n            bool onActionExecutingWasCalled = false;\n            bool onActionExecutedWasCalled = false;\n            ActionFilterImpl actionFilter = new ActionFilterImpl()\n            {\n                OnActionExecutingImpl = filterContext =>\n                {\n                    onActionExecutingWasCalled = true;\n                    filterContext.Result = expectedResult;\n                },\n                OnActionExecutedImpl = _ => { onActionExecutedWasCalled = true; }\n            };\n            Func<ActionResult> endExecute = delegate\n            {\n                return overriddenResult;\n            };\n\n            using (var mockResult = new MockAsyncResult())\n            {\n                // Act\n                ActionResult result = BeginInvokeActionMethodWithFiltersTester(() => mockResult, endExecute, checkBegin: false, checkEnd: false, filters: new IActionFilter[] { actionFilter });\n\n                // Assert\n                Assert.True(onActionExecutingWasCalled);\n                Assert.False(onActionExecutedWasCalled);\n                Assert.Equal(expectedResult, result);\n            }\n        }\n\n        [Fact]\n        public void BeginInvokeActionMethodWithFilters_FiltersOrderedCorrectly()\n        {\n            // Arrange\n            List<string> actionLog = new List<string>();\n            ActionResult actionResult = new ViewResult();\n            Func<ActionResult> continuation = delegate\n            {\n                actionLog.Add(\"Continuation\");\n                return actionResult;\n\n            };\n            ActionFilterImpl filter1 = new ActionFilterImpl()\n            {\n                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) { actionLog.Add(\"OnActionExecuting1\"); },\n                OnActionExecutedImpl = delegate(ActionExecutedContext filterContext) { actionLog.Add(\"OnActionExecuted1\"); }\n            };\n            ActionFilterImpl filter2 = new ActionFilterImpl()\n            {\n                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) { actionLog.Add(\"OnActionExecuting2\"); },\n                OnActionExecutedImpl = delegate(ActionExecutedContext filterContext) { actionLog.Add(\"OnActionExecuted2\"); }\n            };\n\n            using (var mockResult = new MockAsyncResult())\n            {\n                // Act\n                ActionResult result = BeginInvokeActionMethodWithFiltersEndTester(mockResult, continuation, filter1, filter2);\n\n                // Assert\n                Assert.Equal(new[] { \"OnActionExecuting1\", \"OnActionExecuting2\", \"Continuation\", \"OnActionExecuted2\", \"OnActionExecuted1\" }, actionLog.ToArray());\n                Assert.Equal(actionResult, result);\n            }\n        }\n\n        [Fact]\n        public void BeginInvokeActionMethodWithFilters_ShortCircuited()\n        {\n            // Arrange\n            List<string> actionLog = new List<string>();\n            ActionResult shortCircuitResult = new ViewResult();\n            ActionResult executeResult = new ViewResult();\n            ActionFilterImpl filter1 = new ActionFilterImpl()\n            {\n                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) { actionLog.Add(\"OnActionExecuting1\"); },\n                OnActionExecutedImpl = delegate(ActionExecutedContext filterContext) { actionLog.Add(\"OnActionExecuted1\"); }\n            };\n            ActionFilterImpl filter2 = new ActionFilterImpl()\n            {\n                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext)\n                {\n                    actionLog.Add(\"OnActionExecuting2\");\n                    filterContext.Result = shortCircuitResult;\n                },\n                OnActionExecutedImpl = delegate(ActionExecutedContext filterContext) { actionLog.Add(\"OnActionExecuted2\"); }\n            };\n            Func<ActionResult> endExecute = () =>\n            {\n                actionLog.Add(\"ExecuteCalled\");\n                return executeResult;\n            };\n\n            using (var asyncResult = new MockAsyncResult())\n            {\n                // Act\n                ActionResult result = BeginInvokeActionMethodWithFiltersTester(() => asyncResult, endExecute, checkBegin: false, checkEnd: false, filters: new IActionFilter[] { filter1, filter2 });\n\n                // Assert\n                Assert.Equal(new[] { \"OnActionExecuting1\", \"OnActionExecuting2\", \"OnActionExecuted1\" }, actionLog.ToArray());\n                Assert.Equal(shortCircuitResult, result);\n            }\n        }\n\n        private ActionResult BeginInvokeActionMethodWithFiltersBeginTester(Func<IAsyncResult> beginFunction, params IActionFilter[] filters)\n        {\n            return BeginInvokeActionMethodWithFiltersTester(beginFunction, () => new Mock<ActionResult>().Object, checkBegin: true, checkEnd: false, filters: filters);\n        }\n\n        private ActionResult BeginInvokeActionMethodWithFiltersEndTester(IAsyncResult asyncResult, Func<ActionResult> endFunction, params IActionFilter[] filters)\n        {\n            return BeginInvokeActionMethodWithFiltersTester(() => asyncResult, endFunction, checkBegin: true, checkEnd: true, filters: filters);\n        }\n\n        private ActionResult BeginInvokeActionMethodWithFiltersTester(Func<IAsyncResult> beginFunction, Func<ActionResult> endFunction, bool checkBegin, bool checkEnd, IActionFilter[] filters)\n        {\n            AsyncControllerActionInvoker invoker = new AsyncControllerActionInvoker();\n            ControllerContext controllerContext = new ControllerContext();\n            Dictionary<string, object> parameters = new Dictionary<string, object>();\n            Mock<AsyncActionDescriptor> mockActionDescriptor = new Mock<AsyncActionDescriptor>();\n            bool endExecuteCalled = false;\n            bool beginExecuteCalled = false;\n            Func<ActionResult> endExecute = () =>\n            {\n                endExecuteCalled = true;\n                return endFunction();\n            };\n            Func<IAsyncResult> beingExecute = () =>\n            {\n                beginExecuteCalled = true;\n                return beginFunction();\n            };\n\n            mockActionDescriptor.Setup(d => d.BeginExecute(controllerContext, parameters, It.IsAny<AsyncCallback>(), It.IsAny<object>())).Returns(beingExecute);\n            mockActionDescriptor.Setup(d => d.EndExecute(It.IsAny<IAsyncResult>())).Returns(endExecute);\n\n            IAsyncResult outerAsyncResult = null;\n            try\n            {\n                outerAsyncResult = invoker.BeginInvokeActionMethodWithFilters(controllerContext, filters, mockActionDescriptor.Object, parameters, null, null);\n            }\n            catch (Exception ex)\n            {\n                if (checkEnd)\n                {\n                    // Testing end, so not expecting exception thrown from begin\n                    Assert.NotNull(ex);\n                }\n                else\n                {\n                    throw ex;\n                }\n            }\n\n            Assert.NotNull(outerAsyncResult);\n            Assert.Equal(checkBegin, beginExecuteCalled);\n            Assert.False(endExecuteCalled);\n\n            ActionExecutedContext postContext = invoker.EndInvokeActionMethodWithFilters(outerAsyncResult);\n\n            Assert.NotNull(postContext);\n            if (checkEnd)\n            {\n                Assert.True(endExecuteCalled);\n            }\n            return postContext.Result;\n        }\n\n        private static ActionExecutingContext GetActionExecutingContext()\n        {\n            return new ActionExecutingContext(new ControllerContext(), new Mock<ActionDescriptor>().Object, new Dictionary<string, object>());\n        }\n\n        private static ControllerContext GetControllerContext(bool passesRequestValidation = true)\n        {\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            if (passesRequestValidation)\n            {\n#pragma warning disable 618\n                mockHttpContext.Setup(o => o.Request.ValidateInput()).AtMostOnce();\n#pragma warning restore 618\n            }\n            else\n            {\n                mockHttpContext.Setup(o => o.Request.ValidateInput()).Throws(new HttpRequestValidationException());\n            }\n\n            return new ControllerContext()\n            {\n                Controller = new TestController(),\n                HttpContext = mockHttpContext.Object\n            };\n        }\n\n        private class ActionFilterImpl : IActionFilter, IResultFilter\n        {\n            public Action<ActionExecutingContext> OnActionExecutingImpl { get; set; }\n\n            public void OnActionExecuting(ActionExecutingContext filterContext)\n            {\n                if (OnActionExecutingImpl != null)\n                {\n                    OnActionExecutingImpl(filterContext);\n                }\n            }\n\n            public Action<ActionExecutedContext> OnActionExecutedImpl { get; set; }\n\n            public void OnActionExecuted(ActionExecutedContext filterContext)\n            {\n                if (OnActionExecutedImpl != null)\n                {\n                    OnActionExecutedImpl(filterContext);\n                }\n            }\n\n            public Action<ResultExecutingContext> OnResultExecutingImpl { get; set; }\n\n            public void OnResultExecuting(ResultExecutingContext filterContext)\n            {\n                if (OnResultExecutingImpl != null)\n                {\n                    OnResultExecutingImpl(filterContext);\n                }\n            }\n\n            public Action<ResultExecutedContext> OnResultExecutedImpl { get; set; }\n\n            public void OnResultExecuted(ResultExecutedContext filterContext)\n            {\n                if (OnResultExecutedImpl != null)\n                {\n                    OnResultExecutedImpl(filterContext);\n                }\n            }\n        }\n\n        public class AsyncControllerActionInvokerHelper : AsyncControllerActionInvoker\n        {\n            public AsyncControllerActionInvokerHelper()\n            {\n                DescriptorCache = new ControllerDescriptorCache();\n            }\n\n            protected override ControllerDescriptor GetControllerDescriptor(ControllerContext controllerContext)\n            {\n                return PublicGetControllerDescriptor(controllerContext);\n            }\n\n            public virtual ControllerDescriptor PublicGetControllerDescriptor(ControllerContext controllerContext)\n            {\n                return base.GetControllerDescriptor(controllerContext);\n            }\n\n            protected override ExceptionContext InvokeExceptionFilters(ControllerContext controllerContext, IList<IExceptionFilter> filters, Exception exception)\n            {\n                return PublicInvokeExceptionFilters(controllerContext, filters, exception);\n            }\n\n            public virtual ExceptionContext PublicInvokeExceptionFilters(ControllerContext controllerContext, IList<IExceptionFilter> filters, Exception exception)\n            {\n                return base.InvokeExceptionFilters(controllerContext, filters, exception);\n            }\n\n            protected override void InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)\n            {\n                PublicInvokeActionResult(controllerContext, actionResult);\n            }\n\n            public virtual void PublicInvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)\n            {\n                base.InvokeActionResult(controllerContext, actionResult);\n            }\n\n            protected override FilterInfo GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)\n            {\n                return PublicGetFilters(controllerContext, actionDescriptor);\n            }\n\n            public virtual FilterInfo PublicGetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)\n            {\n                return base.GetFilters(controllerContext, actionDescriptor);\n            }\n\n            public virtual AuthenticationContext PublicInvokeAuthenticationFilters(ControllerContext controllerContext, IList<IAuthenticationFilter> filters, ActionDescriptor actionDescriptor)\n            {\n                return base.InvokeAuthenticationFilters(controllerContext, filters, actionDescriptor);\n            }\n\n            protected override AuthenticationContext InvokeAuthenticationFilters(ControllerContext controllerContext, IList<IAuthenticationFilter> filters, ActionDescriptor actionDescriptor)\n            {\n                return PublicInvokeAuthenticationFilters(controllerContext, filters, actionDescriptor);\n            }\n\n            public virtual AuthenticationChallengeContext PublicInvokeAuthenticationFiltersChallenge(ControllerContext controllerContext, IList<IAuthenticationFilter> filters, ActionDescriptor actionDescriptor, ActionResult result)\n            {\n                return base.InvokeAuthenticationFiltersChallenge(controllerContext, filters, actionDescriptor, result);\n            }\n\n            protected override AuthenticationChallengeContext InvokeAuthenticationFiltersChallenge(ControllerContext controllerContext, IList<IAuthenticationFilter> filters, ActionDescriptor actionDescriptor, ActionResult result)\n            {\n                return PublicInvokeAuthenticationFiltersChallenge(controllerContext, filters, actionDescriptor, result);\n            }\n\n            protected override AuthorizationContext InvokeAuthorizationFilters(ControllerContext controllerContext, IList<IAuthorizationFilter> filters, ActionDescriptor actionDescriptor)\n            {\n                return PublicInvokeAuthorizationFilters(controllerContext, filters, actionDescriptor);\n            }\n\n            public virtual AuthorizationContext PublicInvokeAuthorizationFilters(ControllerContext controllerContext, IList<IAuthorizationFilter> filters, ActionDescriptor actionDescriptor)\n            {\n                return base.InvokeAuthorizationFilters(controllerContext, filters, actionDescriptor);\n            }\n\n            protected override ActionDescriptor FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, string actionName)\n            {\n                return PublicFindAction(controllerContext, controllerDescriptor, actionName);\n            }\n\n            public virtual ActionDescriptor PublicFindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, string actionName)\n            {\n                return base.FindAction(controllerContext, controllerDescriptor, actionName);\n            }\n\n            protected override IDictionary<string, object> GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor)\n            {\n                return PublicGetParameterValues(controllerContext, actionDescriptor);\n            }\n\n            public virtual IDictionary<string, object> PublicGetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor)\n            {\n                return base.GetParameterValues(controllerContext, actionDescriptor);\n            }\n        }\n\n        public class AsyncControllerActionInvokerWithCustomFindAction : AsyncControllerActionInvoker\n        {\n            protected override ActionDescriptor FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, string actionName)\n            {\n                return base.FindAction(controllerContext, controllerDescriptor, \"NormalAction\");\n            }\n        }\n\n        [ResetThreadAbort]\n        private class TestController : AsyncController\n        {\n            public string Log;\n\n            public ActionResult ActionCallsThreadAbortAsync()\n            {\n                Thread.CurrentThread.Abort();\n                return null;\n            }\n\n            public ActionResult ActionCallsThreadAbortCompleted()\n            {\n                return null;\n            }\n\n            public ActionResult ResultCallsThreadAbort()\n            {\n                return new ActionResultWhichCallsThreadAbort();\n            }\n\n            public ActionResult NormalAction()\n            {\n                return new LoggingActionResult(\"From action\");\n            }\n\n            [AuthenticationFilterReturnsResult]\n            public void AuthenticationFilterShortCircuits()\n            {\n            }\n\n            [AuthenticationFilterChallengeSetsResult]\n            public void AuthenticationFilterChallenges()\n            {\n            }\n\n            [AuthenticationFilterReturnsResult]\n            [AuthenticationFilterChallengeSetsResult]\n            public void AuthenticationFilterShortCircuitsAndChallenges()\n            {\n            }\n\n            [AuthorizationFilterReturnsResult]\n            public void AuthorizationFilterShortCircuits()\n            {\n            }\n\n            [AuthenticationFilterChallengeSetsResult]\n            [AuthorizationFilterReturnsResult]\n            public void AuthorizationFilterShortCircuitsAndChallenges()\n            {\n            }\n\n            [CustomExceptionFilterHandlesError]\n            public void ActionThrowsExceptionAndIsHandledAsync()\n            {\n                throw new Exception(\"Some exception text.\");\n            }\n\n            public void ActionThrowsExceptionAndIsHandledCompleted()\n            {\n            }\n\n            [CustomExceptionFilterDoesNotHandleError]\n            public void ActionThrowsExceptionAndIsNotHandledAsync()\n            {\n                throw new Exception(\"Some exception text.\");\n            }\n\n            public void ActionThrowsExceptionAndIsNotHandledCompleted()\n            {\n            }\n\n            [CustomExceptionFilterHandlesError]\n            public ActionResult ResultThrowsExceptionAndIsHandled()\n            {\n                return new ActionResultWhichThrowsException();\n            }\n\n            [CustomExceptionFilterDoesNotHandleError]\n            public ActionResult ResultThrowsExceptionAndIsNotHandled()\n            {\n                return new ActionResultWhichThrowsException();\n            }\n\n            private class AuthenticationFilterChallengeSetsResultAttribute : FilterAttribute, IAuthenticationFilter\n            {\n                public void OnAuthentication(AuthenticationContext filterContext)\n                {\n                }\n\n                public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)\n                {\n                    filterContext.Result = new LoggingActionResult(\"From authentication filter challenge\");\n                }\n            }\n\n            private class AuthenticationFilterReturnsResultAttribute : FilterAttribute, IAuthenticationFilter\n            {\n                public void OnAuthentication(AuthenticationContext filterContext)\n                {\n                    filterContext.Result = new LoggingActionResult(\"From authentication filter\");\n                }\n\n                public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)\n                {\n                }\n            }\n\n            private class AuthorizationFilterReturnsResultAttribute : FilterAttribute, IAuthorizationFilter\n            {\n                public void OnAuthorization(AuthorizationContext filterContext)\n                {\n                    filterContext.Result = new LoggingActionResult(\"From authorization filter\");\n                }\n            }\n\n            private class CustomExceptionFilterDoesNotHandleErrorAttribute : FilterAttribute, IExceptionFilter\n            {\n                public void OnException(ExceptionContext filterContext)\n                {\n                }\n            }\n\n            private class CustomExceptionFilterHandlesErrorAttribute : FilterAttribute, IExceptionFilter\n            {\n                public void OnException(ExceptionContext filterContext)\n                {\n                    filterContext.ExceptionHandled = true;\n                    filterContext.Result = new LoggingActionResult(\"From exception filter\");\n                }\n            }\n\n            private class ActionResultWhichCallsThreadAbort : ActionResult\n            {\n                public override void ExecuteResult(ControllerContext context)\n                {\n                    Thread.CurrentThread.Abort();\n                }\n            }\n\n            private class ActionResultWhichThrowsException : ActionResult\n            {\n                public override void ExecuteResult(ControllerContext context)\n                {\n                    throw new Exception(\"Some exception text.\");\n                }\n            }\n        }\n\n        private class ResetThreadAbortAttribute : ActionFilterAttribute\n        {\n            public override void OnActionExecuted(ActionExecutedContext filterContext)\n            {\n                try\n                {\n                    Thread.ResetAbort();\n                }\n                catch (ThreadStateException)\n                {\n                    // thread wasn't being aborted\n                }\n            }\n\n            public override void OnResultExecuted(ResultExecutedContext filterContext)\n            {\n                try\n                {\n                    Thread.ResetAbort();\n                }\n                catch (ThreadStateException)\n                {\n                    // thread wasn't being aborted\n                }\n            }\n        }\n\n        private class LoggingActionResult : ActionResult\n        {\n            private readonly string _logText;\n\n            public LoggingActionResult(string logText)\n            {\n                _logText = logText;\n            }\n\n            public override void ExecuteResult(ControllerContext context)\n            {\n                ((TestController)context.Controller).Log = _logText;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Async/Test/AsyncManagerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Async.Test\n{\n    public class AsyncManagerTest\n    {\n        [Fact]\n        public void FinishEvent_ExplicitCallToFinishMethod()\n        {\n            // Arrange\n            AsyncManager helper = new AsyncManager();\n\n            bool delegateCalled = false;\n            helper.Finished += delegate { delegateCalled = true; };\n\n            // Act\n            helper.Finish();\n\n            // Assert\n            Assert.True(delegateCalled);\n        }\n\n        [Fact]\n        public void FinishEvent_LinkedToOutstandingOperationsCompletedEvent()\n        {\n            // Arrange\n            AsyncManager helper = new AsyncManager();\n\n            bool delegateCalled = false;\n            helper.Finished += delegate { delegateCalled = true; };\n\n            // Act\n            helper.OutstandingOperations.Increment();\n            helper.OutstandingOperations.Decrement();\n\n            // Assert\n            Assert.True(delegateCalled);\n        }\n\n        [Fact]\n        public void OutstandingOperationsProperty()\n        {\n            // Act\n            AsyncManager helper = new AsyncManager();\n\n            // Assert\n            Assert.NotNull(helper.OutstandingOperations);\n        }\n\n        [Fact]\n        public void ParametersProperty()\n        {\n            // Act\n            AsyncManager helper = new AsyncManager();\n\n            // Assert\n            Assert.NotNull(helper.Parameters);\n        }\n\n        [Fact]\n        public void Sync()\n        {\n            // Arrange\n            Mock<SynchronizationContext> mockSyncContext = new Mock<SynchronizationContext>();\n            mockSyncContext\n                .Setup(c => c.Send(It.IsAny<SendOrPostCallback>(), null))\n                .Callback(\n                    delegate(SendOrPostCallback d, object state) { d(state); });\n\n            AsyncManager helper = new AsyncManager(mockSyncContext.Object);\n            bool wasCalled = false;\n\n            // Act\n            helper.Sync(() => { wasCalled = true; });\n\n            // Assert\n            Assert.True(wasCalled);\n        }\n\n        [Fact]\n        public void TimeoutProperty()\n        {\n            // Arrange\n            int setValue = 50;\n            AsyncManager helper = new AsyncManager();\n\n            // Act\n            int defaultTimeout = helper.Timeout;\n            helper.Timeout = setValue;\n            int newTimeout = helper.Timeout;\n\n            // Assert\n            Assert.Equal(45000, defaultTimeout);\n            Assert.Equal(setValue, newTimeout);\n        }\n\n        [Fact]\n        public void TimeoutPropertyThrowsIfDurationIsOutOfRange()\n        {\n            // Arrange\n            int timeout = -30;\n            AsyncManager helper = new AsyncManager();\n\n            // Act & assert\n            Assert.ThrowsArgumentOutOfRange(\n                delegate { helper.Timeout = timeout; }, \"value\",\n                @\"The timeout value must be non-negative or Timeout.Infinite.\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Async/Test/AsyncResultWrapperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Async.Test\n{\n    public class AsyncResultWrapperTest\n    {\n        [Fact]\n        public void Begin_AsynchronousCompletion()\n        {\n            // Arrange\n            AsyncCallback capturedCallback = null;\n            IAsyncResult resultGivenToCallback = null;\n            using (MockAsyncResult innerResult = new MockAsyncResult())\n            {\n                // Act\n                IAsyncResult outerResult = AsyncResultWrapper.Begin<object>(\n                    ar => { resultGivenToCallback = ar; },\n                    null,\n                    (callback, callbackState, state) =>\n                    {\n                        capturedCallback = callback;\n                        return innerResult;\n                    },\n                    (ar, state) => { },\n                    null);\n\n                capturedCallback(innerResult);\n\n                // Assert\n                Assert.Equal(outerResult, resultGivenToCallback);\n            }\n        }\n\n        [Fact]\n        public void Begin_AsynchronousCompletionWithState()\n        {\n            // Arrange\n            using (MockAsyncResult innerResult = new MockAsyncResult())\n            {\n                object invokeState = new object();\n                object capturedBeginState = null;\n                object capturedEndState = null;\n\n                // Act\n                IAsyncResult outerResult = AsyncResultWrapper.Begin(\n                    null,\n                    null,\n                    (AsyncCallback callback, object callbackState, object innerInvokeState) =>\n                    {\n                        capturedBeginState = innerInvokeState;\n                        return innerResult;\n                    },\n                    (IAsyncResult result, object innerInvokeState) =>\n                    {\n                        capturedEndState = innerInvokeState;\n                    },\n                    invokeState,\n                    null,\n                    Timeout.Infinite);\n                AsyncResultWrapper.End(outerResult);\n\n                // Assert\n                Assert.Same(invokeState, capturedBeginState);\n                Assert.Same(invokeState, capturedEndState);\n            }\n        }\n\n        [Fact]\n        public void Begin_AsynchronousCompletionWithStateAndResult()\n        {\n            // Arrange\n            using (MockAsyncResult innerResult = new MockAsyncResult())\n            {\n                object invokeState = new object();\n                object capturedBeginState = null;\n                object capturedEndState = null;\n                object expectedRetun = new object();\n\n                // Act\n                IAsyncResult outerResult = AsyncResultWrapper.Begin(\n                    null,\n                    null,\n                    (AsyncCallback callback, object callbackState, object innerInvokeState) =>\n                    {\n                        capturedBeginState = innerInvokeState;\n                        return innerResult;\n                    },\n                    (IAsyncResult result, object innerInvokeState) =>\n                    {\n                        capturedEndState = innerInvokeState;\n                        return expectedRetun;\n                    },\n                    invokeState,\n                    null,\n                    Timeout.Infinite);\n                object endResult = AsyncResultWrapper.End<object>(outerResult);\n\n                // Assert\n                Assert.Same(expectedRetun, endResult);\n                Assert.Same(invokeState, capturedBeginState);\n                Assert.Same(invokeState, capturedEndState);\n            }\n        }\n\n        [Fact]\n        public void Begin_ReturnsAsyncResultWhichWrapsInnerResult()\n        {\n            // Arrange\n            MockAsyncResult innerResult = new MockAsyncResult()\n            {\n                AsyncState = \"inner state\",\n                CompletedSynchronously = true,\n                IsCompleted = true\n            };\n\n            using (innerResult)\n            {\n                // Act\n                IAsyncResult outerResult = AsyncResultWrapper.Begin<object>(\n                    null, \"outer state\",\n                    (callback, callbackState, state) => innerResult,\n                    (ar, state) => { },\n                    null);\n\n                // Assert\n                Assert.Equal(innerResult.AsyncState, outerResult.AsyncState);\n                Assert.Null(outerResult.AsyncWaitHandle);\n                Assert.Equal(innerResult.CompletedSynchronously, outerResult.CompletedSynchronously);\n                Assert.Equal(innerResult.IsCompleted, outerResult.IsCompleted);\n            }\n        }\n\n        [Fact]\n        public void Begin_SynchronousCompletion()\n        {\n            // Arrange\n            IAsyncResult resultGivenToCallback = null;\n            using (MockAsyncResult innerResult = new MockAsyncResult())\n            {\n                // Act\n                IAsyncResult outerResult = AsyncResultWrapper.Begin<object>(\n                    ar => { resultGivenToCallback = ar; },\n                    null,\n                    (callback, callbackState, state) =>\n                    {\n                        callback(innerResult);\n                        return innerResult;\n                    },\n                    (ar, state) => { },\n                    null);\n\n                // Assert\n                Assert.Equal(outerResult, resultGivenToCallback);\n            }\n        }\n\n        [Fact]\n        public void Begin_AsynchronousButAlreadyCompleted()\n        {\n            // Arrange\n            Mock<IAsyncResult> innerResultMock = new Mock<IAsyncResult>();\n            innerResultMock.Setup(ir => ir.CompletedSynchronously).Returns(false);\n            innerResultMock.Setup(ir => ir.IsCompleted).Returns(true);\n\n            // Act\n            IAsyncResult outerResult = AsyncResultWrapper.Begin<object>(\n                null,\n                null,\n                (callback, callbackState, state) =>\n                {\n                    callback(innerResultMock.Object);\n                    return innerResultMock.Object;\n                },\n                (ar, state) => { },\n                null);\n\n            // Assert\n            Assert.True(outerResult.CompletedSynchronously);\n        }\n\n        [Fact]\n        public void Begin_WithCallbackSyncContext_CallsSendIfOperationCompletedAsynchronously()\n        {\n            // Arrange\n            MockAsyncResult asyncResult = new MockAsyncResult()\n            {\n                CompletedSynchronously = false,\n                IsCompleted = false\n            };\n\n            using (asyncResult)\n            {\n                bool originalCallbackCalled = false;\n                IAsyncResult passedAsyncResult = null;\n                AsyncCallback passedCallback = null;\n                AsyncCallback originalCallback = ar =>\n                {\n                    originalCallbackCalled = true;\n                    passedAsyncResult = ar;\n                };\n                object originalState = new object();\n                DummySynchronizationContext syncContext = new DummySynchronizationContext();\n\n                // Act\n                IAsyncResult outerResult = AsyncResultWrapper.Begin<object>(\n                     originalCallback,\n                     originalState,\n                     (callback, callbackState, state) =>\n                     {\n                         passedCallback = callback;\n                         asyncResult.AsyncState = callbackState;\n                         return asyncResult;\n                     },\n                     (ar, state) =>\n                     {\n                         asyncResult.IsCompleted = true;\n                         passedCallback(ar);\n                     },\n                     null,\n                     callbackSyncContext: syncContext);\n                AsyncResultWrapper.End(outerResult);\n\n                // Assert\n                Assert.True(originalCallbackCalled);\n                Assert.False(passedAsyncResult.CompletedSynchronously);\n                Assert.True(passedAsyncResult.IsCompleted);\n                Assert.Same(originalState, passedAsyncResult.AsyncState);\n                Assert.True(syncContext.SendCalled);\n            }\n        }\n\n        [Fact]\n        public void Begin_WithCallbackSyncContext_DoesNotCallSendIfOperationCompletedSynchronously()\n        {\n            // Arrange\n            MockAsyncResult asyncResult = new MockAsyncResult()\n            {\n                CompletedSynchronously = true,\n                IsCompleted = true\n            };\n\n            using (asyncResult)\n            {\n                bool originalCallbackCalled = false;\n                IAsyncResult passedAsyncResult = null;\n                AsyncCallback originalCallback = ar =>\n                {\n                    passedAsyncResult = ar;\n                    originalCallbackCalled = true;\n                };\n                object originalState = new object();\n\n                DummySynchronizationContext syncContext = new DummySynchronizationContext();\n\n                // Act\n                IAsyncResult outerResult = AsyncResultWrapper.Begin<object>(\n                    originalCallback,\n                    originalState,\n                    (callback, callbackState, state) =>\n                    {\n                        asyncResult.AsyncState = callbackState;\n                        return asyncResult;\n                    },\n                    (ar, state) => { },\n                    null,\n                    callbackSyncContext: syncContext);\n\n                // Assert\n                Assert.True(originalCallbackCalled);\n                Assert.True(passedAsyncResult.CompletedSynchronously);\n                Assert.True(passedAsyncResult.IsCompleted);\n                Assert.Same(originalState, passedAsyncResult.AsyncState);\n                Assert.False(syncContext.SendCalled);\n            }\n        }\n\n        [Fact]\n        public void Begin_WithCallbackSyncContext_ThrowsAsyncEvenIfSendContextCaptures()\n        {\n            // Arrange\n            InvalidOperationException exception = new InvalidOperationException(\"Some exception text.\");\n            CapturingSynchronizationContext capturingSyncContext = new CapturingSynchronizationContext();\n            MockAsyncResult asyncResult = new MockAsyncResult()\n            {\n                CompletedSynchronously = false,\n                IsCompleted = true\n            };\n\n            using (asyncResult)\n            {\n                bool originalCallbackCalled = false;\n                IAsyncResult passedAsyncResult = null;\n                AsyncCallback passedCallback = null;\n                AsyncCallback originalCallback = ar =>\n                {\n                    passedAsyncResult = ar;\n                    originalCallbackCalled = true;\n                    throw exception;\n                };\n\n                // Act & Assert\n                IAsyncResult outerResult = AsyncResultWrapper.Begin<object>(\n                     originalCallback,\n                     null,\n                     (callback, callbackState, state) =>\n                     {\n                         passedCallback = callback;\n                         asyncResult.AsyncState = callbackState;\n                         return asyncResult;\n                     },\n                     (ar, state) =>\n                     {\n                         asyncResult.IsCompleted = true;\n                         passedCallback(ar);\n                     },\n                     null,\n                     callbackSyncContext: capturingSyncContext);\n                SynchronousOperationException thrownException = Assert.Throws<SynchronousOperationException>(\n                    delegate\n                    {\n                        AsyncResultWrapper.End(outerResult);\n                    },\n                    @\"An operation that crossed a synchronization context failed. See the inner exception for more information.\");\n\n                // Assert\n                Assert.Equal(exception, thrownException.InnerException);\n                Assert.True(originalCallbackCalled);\n                Assert.False(passedAsyncResult.CompletedSynchronously);\n                Assert.True(capturingSyncContext.SendCalled);\n            }\n        }\n\n        [Fact]\n        public void Begin_WithCallbackSyncContext_ThrowsSynchronous()\n        {\n            // Arrange\n            InvalidOperationException exception = new InvalidOperationException(\"Some exception text.\");\n            CapturingSynchronizationContext capturingSyncContext = new CapturingSynchronizationContext();\n            MockAsyncResult asyncResult = new MockAsyncResult()\n            {\n                CompletedSynchronously = true,\n                IsCompleted = true\n            };\n\n            using (asyncResult)\n            {\n                bool originalCallbackCalled = false;\n                IAsyncResult passedAsyncResult = null;\n                AsyncCallback originalCallback = ar =>\n                {\n                    passedAsyncResult = ar;\n                    originalCallbackCalled = true;\n                    throw exception;\n                };\n\n                // Act & Assert\n                InvalidOperationException thrownException = Assert.Throws<InvalidOperationException>(\n                    delegate\n                    {\n                        AsyncResultWrapper.Begin<object>(\n                            originalCallback,\n                            null,\n                            (callback, callbackState, state) =>\n                            {\n                                asyncResult.AsyncState = callbackState;\n                                return asyncResult;\n                            },\n                            (ar, state) => { },\n                            null,\n                            callbackSyncContext: capturingSyncContext);\n                    },\n                    exception.Message);\n\n                // Assert\n                Assert.Equal(exception, thrownException);\n                Assert.True(originalCallbackCalled);\n                Assert.True(passedAsyncResult.CompletedSynchronously);\n                Assert.False(capturingSyncContext.SendCalled);\n            }\n        }\n\n        [Fact]\n        public void BeginSynchronous_Action()\n        {\n            // Arrange\n            bool actionCalled = false;\n\n            // Act\n            IAsyncResult asyncResult = AsyncResultWrapper.BeginSynchronous(callback: null, state: null, action: delegate { actionCalled = true; }, tag: null);\n            AsyncResultWrapper.End(asyncResult);\n\n            // Assert\n            Assert.True(actionCalled);\n            Assert.True(asyncResult.IsCompleted);\n            Assert.True(asyncResult.CompletedSynchronously);\n        }\n\n        [Fact]\n        public void BeginSynchronous_Func()\n        {\n            object expectedReturn = new object();\n            object expectedState = new object();\n            object expectedCallbackState = new object();\n            bool funcCalled = false;\n            bool asyncCalledbackCalled = false;\n\n            // Act\n            IAsyncResult asyncResult = AsyncResultWrapper.BeginSynchronous(\n                callback: (innerIAsyncResult) =>\n                {\n                    asyncCalledbackCalled = true;\n                    Assert.NotNull(innerIAsyncResult);\n                    Assert.Same(expectedCallbackState, innerIAsyncResult.AsyncState);\n                    Assert.True(innerIAsyncResult.IsCompleted);\n                    Assert.True(innerIAsyncResult.CompletedSynchronously);\n                },\n                callbackState: expectedCallbackState,\n                func: (innerIAsyncResult, innerState) =>\n                {\n                    funcCalled = true;\n                    Assert.NotNull(innerIAsyncResult);\n                    Assert.Same(expectedCallbackState, innerIAsyncResult.AsyncState);\n                    Assert.Same(expectedState, innerState);\n                    Assert.True(innerIAsyncResult.IsCompleted);\n                    Assert.True(innerIAsyncResult.CompletedSynchronously);\n                    return expectedReturn;\n                },\n                funcState: expectedState,\n                tag: null);\n            object retVal = AsyncResultWrapper.End<object>(asyncResult);\n\n            // Assert\n            Assert.Same(expectedReturn, retVal);\n            Assert.True(asyncResult.IsCompleted);\n            Assert.True(asyncResult.CompletedSynchronously);\n            Assert.True(funcCalled);\n            Assert.True(asyncCalledbackCalled);\n        }\n\n        [Fact]\n        public void End_ExecutesStoredDelegateAndReturnsValue()\n        {\n            // Arrange\n            using (var mockResult = new MockAsyncResult())\n            {\n                IAsyncResult asyncResult = AsyncResultWrapper.Begin(\n                    null, null,\n                    (callback, state) => mockResult,\n                    ar => 42);\n\n                // Act\n                int returned = AsyncResultWrapper.End<int>(asyncResult);\n\n                // Assert\n                Assert.Equal(42, returned);\n            }\n        }\n\n        [Fact]\n        public void End_ThrowsIfAsyncResultIsIncorrectType()\n        {\n            // Arrange\n            using (var mockResult = new MockAsyncResult())\n            {\n                IAsyncResult asyncResult = AsyncResultWrapper.Begin<object>(\n                    null, null,\n                    (callback, callbackState, state) => mockResult,\n                    (ar, state) => { },\n                    null);\n\n                // Act & assert\n                Assert.Throws<ArgumentException>(\n                    delegate { AsyncResultWrapper.End<int>(asyncResult); },\n                    \"The provided IAsyncResult is not valid for this method.\" + Environment.NewLine\n                  + \"Parameter name: asyncResult\");\n            }\n        }\n\n        [Fact]\n        public void End_ThrowsIfAsyncResultIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { AsyncResultWrapper.End(null); }, \"asyncResult\");\n        }\n\n        [Fact]\n        public void End_ThrowsIfAsyncResultTagMismatch()\n        {\n            // Arrange\n            using (var mockResult = new MockAsyncResult())\n            {\n                IAsyncResult asyncResult = AsyncResultWrapper.Begin<object>(\n                    null, null,\n                    (callback, callbackState, state) => mockResult,\n                    (ar, state) => { },\n                    null,\n                    \"some tag\");\n\n                // Act & assert\n                Assert.Throws<ArgumentException>(\n                    delegate { AsyncResultWrapper.End(asyncResult, \"some other tag\"); },\n                    \"The provided IAsyncResult is not valid for this method.\" + Environment.NewLine\n                  + \"Parameter name: asyncResult\");\n            }\n        }\n\n        [Fact]\n        public void End_ThrowsIfCalledTwiceOnSameAsyncResult()\n        {\n            // Arrange\n            using (var mockResult = new MockAsyncResult())\n            {\n                IAsyncResult asyncResult = AsyncResultWrapper.Begin<object>(\n                null, null,\n                (callback, callbackState, state) => mockResult,\n                (ar, state) => { },\n                null);\n\n                // Act & assert\n                AsyncResultWrapper.End(asyncResult);\n                Assert.Throws<InvalidOperationException>(\n                    delegate { AsyncResultWrapper.End(asyncResult); },\n                    \"The provided IAsyncResult has already been consumed.\");\n            }\n        }\n\n        [Fact]\n        public void TimedOut()\n        {\n            // Arrange\n            using (ManualResetEvent waitHandle = new ManualResetEvent(false /* initialState */))\n            {\n                AsyncCallback callback = ar => { waitHandle.Set(); };\n\n                // Act & assert\n                using (var mockResult = new MockAsyncResult())\n                {\n                    IAsyncResult asyncResult = AsyncResultWrapper.Begin<object>(\n                    callback, null,\n                    (innerCallback, callbackState, state) => mockResult,\n                    (ar, state) => { Assert.True(false, \"This callback should never execute since we timed out.\"); },\n                    null,\n                    null, 0);\n\n                    // wait for the timeout\n                    waitHandle.WaitOne();\n\n                    Assert.True(asyncResult.IsCompleted);\n                    Assert.Throws<TimeoutException>(\n                        delegate { AsyncResultWrapper.End(asyncResult); });\n                }\n            }\n        }\n\n        private class DummySynchronizationContext : SynchronizationContext\n        {\n            public bool SendCalled { get; private set; }\n\n            public override void Send(SendOrPostCallback d, object state)\n            {\n                SendCalled = true;\n                base.Send(d, state);\n            }\n        }\n\n        private class CapturingSynchronizationContext : SynchronizationContext\n        {\n            public bool SendCalled { get; private set; }\n\n            public override void Send(SendOrPostCallback d, object state)\n            {\n                try\n                {\n                    SendCalled = true;\n                    d(state);\n                }\n                catch\n                {\n                    // swallow exceptions, just like AspNetSynchronizationContext\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Async/Test/MockAsyncResult.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\n\nnamespace System.Web.Mvc.Async.Test\n{\n    public class MockAsyncResult : IAsyncResult, IDisposable\n    {\n        private volatile object _asyncState;\n        private volatile ManualResetEvent _asyncWaitHandle = new ManualResetEvent(false);\n        private volatile bool _completedSynchronously;\n        private volatile bool _isCompleted;\n\n        public object AsyncState\n        {\n            get { return _asyncState; }\n            set { _asyncState = value; }\n        }\n\n        public ManualResetEvent AsyncWaitHandle\n        {\n            get { return _asyncWaitHandle; }\n            set { _asyncWaitHandle = value; }\n        }\n\n        public bool CompletedSynchronously\n        {\n            get { return _completedSynchronously; }\n            set { _completedSynchronously = value; }\n        }\n\n        public bool IsCompleted\n        {\n            get { return _isCompleted; }\n            set { _isCompleted = value; }\n        }\n\n        public void Dispose()\n        {\n            _asyncWaitHandle.Dispose();\n        }\n\n        #region IAsyncResult Members\n\n        WaitHandle IAsyncResult.AsyncWaitHandle\n        {\n            get { return _asyncWaitHandle; }\n        }\n\n        #endregion\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Async/Test/OperationCounterTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Async.Test\n{\n    public class OperationCounterTest\n    {\n        [Fact]\n        public void CompletedEvent()\n        {\n            // Arrange\n            bool premature = true;\n            bool eventFired = false;\n            OperationCounter ops = new OperationCounter();\n            ops.Completed += (sender, eventArgs) =>\n            {\n                if (premature)\n                {\n                    Assert.True(false, \"Event fired too early!\");\n                }\n                if (eventFired)\n                {\n                    Assert.True(false, \"Event fired multiple times.\");\n                }\n\n                Assert.Equal(ops, sender);\n                Assert.Equal(eventArgs, EventArgs.Empty);\n                eventFired = true;\n            };\n\n            // Act & assert\n            ops.Increment(); // should not fire event (will throw exception)\n            premature = false;\n\n            ops.Decrement(); // should fire event\n            Assert.True(eventFired);\n\n            ops.Increment(); // should not fire event (will throw exception)\n        }\n\n        [Fact]\n        public void CountStartsAtZero()\n        {\n            // Arrange\n            OperationCounter ops = new OperationCounter();\n\n            // Act & assert\n            Assert.Equal(0, ops.Count);\n        }\n\n        [Fact]\n        public void DecrementWithIntegerArgument()\n        {\n            // Arrange\n            OperationCounter ops = new OperationCounter();\n\n            // Act\n            int returned = ops.Decrement(3);\n            int newCount = ops.Count;\n\n            // Assert\n            Assert.Equal(-3, returned);\n            Assert.Equal(-3, newCount);\n        }\n\n        [Fact]\n        public void DecrementWithNoArguments()\n        {\n            // Arrange\n            OperationCounter ops = new OperationCounter();\n\n            // Act\n            int returned = ops.Decrement();\n            int newCount = ops.Count;\n\n            // Assert\n            Assert.Equal(-1, returned);\n            Assert.Equal(-1, newCount);\n        }\n\n        [Fact]\n        public void IncrementWithIntegerArgument()\n        {\n            // Arrange\n            OperationCounter ops = new OperationCounter();\n\n            // Act\n            int returned = ops.Increment(3);\n            int newCount = ops.Count;\n\n            // Assert\n            Assert.Equal(3, returned);\n            Assert.Equal(3, newCount);\n        }\n\n        [Fact]\n        public void IncrementWithNoArguments()\n        {\n            // Arrange\n            OperationCounter ops = new OperationCounter();\n\n            // Act\n            int returned = ops.Increment();\n            int newCount = ops.Count;\n\n            // Assert\n            Assert.Equal(1, returned);\n            Assert.Equal(1, newCount);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Async/Test/ReflectedAsyncActionDescriptorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Reflection;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Async.Test\n{\n    public class ReflectedAsyncActionDescriptorTest\n    {\n        private readonly MethodInfo _asyncMethod = typeof(ExecuteController).GetMethod(\"FooAsync\");\n        private readonly MethodInfo _completedMethod = typeof(ExecuteController).GetMethod(\"FooCompleted\");\n\n        [Fact]\n        public void Constructor_SetsProperties()\n        {\n            // Arrange\n            string actionName = \"SomeAction\";\n            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;\n\n            // Act\n            ReflectedAsyncActionDescriptor ad = new ReflectedAsyncActionDescriptor(_asyncMethod, _completedMethod, actionName, cd);\n\n            // Assert\n            Assert.Equal(_asyncMethod, ad.AsyncMethodInfo);\n            Assert.Equal(_completedMethod, ad.CompletedMethodInfo);\n            Assert.Equal(actionName, ad.ActionName);\n            Assert.Equal(cd, ad.ControllerDescriptor);\n        }\n\n        [Fact]\n        public void Constructor_ThrowsIfActionNameIsEmpty()\n        {\n            // Arrange\n            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;\n\n            // Act & assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { new ReflectedAsyncActionDescriptor(_asyncMethod, _completedMethod, \"\", cd); }, \"actionName\");\n        }\n\n        [Fact]\n        public void Constructor_ThrowsIfActionNameIsNull()\n        {\n            // Arrange\n            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;\n\n            // Act & assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { new ReflectedAsyncActionDescriptor(_asyncMethod, _completedMethod, null, cd); }, \"actionName\");\n        }\n\n        [Fact]\n        public void Constructor_ThrowsIfAsyncMethodInfoIsInvalid()\n        {\n            // Arrange\n            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;\n            MethodInfo getHashCodeMethod = typeof(object).GetMethod(\"GetHashCode\");\n\n            // Act & assert\n            Assert.Throws<ArgumentException>(\n                delegate { new ReflectedAsyncActionDescriptor(getHashCodeMethod, _completedMethod, \"SomeAction\", cd); },\n                \"Cannot create a descriptor for instance method 'Int32 GetHashCode()' on type 'System.Object' because the type does not derive from ControllerBase.\" + Environment.NewLine\n              + \"Parameter name: asyncMethodInfo\");\n        }\n\n        [Fact]\n        public void Constructor_ThrowsIfAsyncMethodInfoIsNull()\n        {\n            // Arrange\n            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ReflectedAsyncActionDescriptor(null, _completedMethod, \"SomeAction\", cd); }, \"asyncMethodInfo\");\n        }\n\n        [Fact]\n        public void Constructor_ThrowsIfCompletedMethodInfoIsInvalid()\n        {\n            // Arrange\n            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;\n            MethodInfo getHashCodeMethod = typeof(object).GetMethod(\"GetHashCode\");\n\n            // Act & assert\n            Assert.Throws<ArgumentException>(\n                delegate { new ReflectedAsyncActionDescriptor(_asyncMethod, getHashCodeMethod, \"SomeAction\", cd); },\n                \"Cannot create a descriptor for instance method 'Int32 GetHashCode()' on type 'System.Object' because the type does not derive from ControllerBase.\" + Environment.NewLine\n              + \"Parameter name: completedMethodInfo\");\n        }\n\n        [Fact]\n        public void Constructor_ThrowsIfCompletedMethodInfoIsNull()\n        {\n            // Arrange\n            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ReflectedAsyncActionDescriptor(_asyncMethod, null, \"SomeAction\", cd); }, \"completedMethodInfo\");\n        }\n\n        [Fact]\n        public void Constructor_ThrowsIfControllerDescriptorIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ReflectedAsyncActionDescriptor(_asyncMethod, _completedMethod, \"SomeAction\", null); }, \"controllerDescriptor\");\n        }\n\n        [Fact]\n        public void Execute()\n        {\n            // Arrange\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(c => c.Controller).Returns(new ExecuteController());\n            ControllerContext controllerContext = mockControllerContext.Object;\n\n            Dictionary<string, object> parameters = new Dictionary<string, object>()\n            {\n                { \"id1\", 42 }\n            };\n\n            ReflectedAsyncActionDescriptor ad = GetActionDescriptor(_asyncMethod, _completedMethod);\n\n            using (SignalContainer<object> resultContainer = new SignalContainer<object>())\n            {\n                AsyncCallback callback = ar =>\n                {\n                    object o = ad.EndExecute(ar);\n                    resultContainer.Signal(o);\n                };\n\n                // Act\n                ad.BeginExecute(controllerContext, parameters, callback, null);\n                object retVal = resultContainer.Wait();\n\n                // Assert\n                Assert.Equal(\"Hello world: 42\", retVal);\n            }\n        }\n\n        [Fact]\n        public void Execute_ThrowsIfControllerContextIsNull()\n        {\n            // Arrange\n            ReflectedAsyncActionDescriptor ad = GetActionDescriptor(_asyncMethod, _completedMethod);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { ad.BeginExecute(null, new Dictionary<string, object>(), null, null); }, \"controllerContext\");\n        }\n\n        [Fact]\n        public void Execute_ThrowsIfControllerIsNotAsyncManagerContainer()\n        {\n            // Arrange\n            ReflectedAsyncActionDescriptor ad = GetActionDescriptor(_asyncMethod, _completedMethod);\n            ControllerContext controllerContext = new ControllerContext()\n            {\n                Controller = new RegularSyncController()\n            };\n\n            // Act & assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { ad.BeginExecute(controllerContext, new Dictionary<string, object>(), null, null); },\n                \"The controller of type 'System.Web.Mvc.Async.Test.ReflectedAsyncActionDescriptorTest+RegularSyncController' must subclass AsyncController or implement the IAsyncManagerContainer interface.\");\n        }\n\n        [Fact]\n        public void Execute_ThrowsIfParametersIsNull()\n        {\n            // Arrange\n            ReflectedAsyncActionDescriptor ad = GetActionDescriptor(_asyncMethod, _completedMethod);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { ad.BeginExecute(new ControllerContext(), null, null, null); }, \"parameters\");\n        }\n\n        [Fact]\n        public void GetCustomAttributes()\n        {\n            // Arrange\n            ReflectedAsyncActionDescriptor ad = GetActionDescriptor(_asyncMethod, _completedMethod);\n\n            // Act\n            object[] attributes = ad.GetCustomAttributes(true /* inherit */);\n\n            // Assert\n            object attribute = Assert.Single(attributes);\n            Assert.IsType<AuthorizeAttribute>(attribute);\n        }\n\n        [Fact]\n        public void GetCustomAttributes_FilterByType()\n        {\n            // Shouldn't match attributes on the Completed() method, only the Async() method\n\n            // Arrange\n            ReflectedAsyncActionDescriptor ad = GetActionDescriptor(_asyncMethod, _completedMethod);\n\n            // Act\n            object[] attributes = ad.GetCustomAttributes(typeof(OutputCacheAttribute), true /* inherit */);\n\n            // Assert\n            Assert.Empty(attributes);\n        }\n\n        [Fact]\n        public void GetParameters()\n        {\n            // Arrange\n            ParameterInfo pInfo = _asyncMethod.GetParameters()[0];\n            ReflectedAsyncActionDescriptor ad = GetActionDescriptor(_asyncMethod, _completedMethod);\n\n            // Act\n            ParameterDescriptor[] pDescsFirstCall = ad.GetParameters();\n            ParameterDescriptor[] pDescsSecondCall = ad.GetParameters();\n\n            // Assert\n            Assert.NotSame(pDescsFirstCall, pDescsSecondCall);\n            Assert.Equal(pDescsFirstCall, pDescsSecondCall);\n\n            ParameterDescriptor parameterDescriptor = Assert.Single(pDescsFirstCall);\n            ReflectedParameterDescriptor pDesc = Assert.IsType<ReflectedParameterDescriptor>(parameterDescriptor);\n\n            Assert.NotNull(pDesc);\n            Assert.Same(ad, pDesc.ActionDescriptor);\n            Assert.Same(pInfo, pDesc.ParameterInfo);\n        }\n\n        [Fact]\n        public void GetSelectors()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n            Mock<MethodInfo> mockMethod = new Mock<MethodInfo>();\n\n            Mock<ActionMethodSelectorAttribute> mockAttr = new Mock<ActionMethodSelectorAttribute>();\n            mockAttr.Setup(attr => attr.IsValidForRequest(controllerContext, mockMethod.Object)).Returns(true).Verifiable();\n            mockMethod.Setup(m => m.GetCustomAttributes(typeof(ActionMethodSelectorAttribute), true)).Returns(new ActionMethodSelectorAttribute[] { mockAttr.Object });\n\n            ReflectedAsyncActionDescriptor ad = GetActionDescriptor(mockMethod.Object, _completedMethod);\n\n            // Act\n            ICollection<ActionSelector> selectors = ad.GetSelectors();\n            bool executedSuccessfully = selectors.All(s => s(controllerContext));\n\n            // Assert\n            Assert.Single(selectors);\n            Assert.True(executedSuccessfully);\n            mockAttr.Verify();\n        }\n\n        [Fact]\n        public void IsDefined()\n        {\n            // Arrange\n            ReflectedAsyncActionDescriptor ad = GetActionDescriptor(_asyncMethod, _completedMethod);\n\n            // Act\n            bool isDefined = ad.IsDefined(typeof(AuthorizeAttribute), true /* inherit */);\n\n            // Assert\n            Assert.True(isDefined);\n        }\n\n        private static ReflectedAsyncActionDescriptor GetActionDescriptor(MethodInfo asyncMethod, MethodInfo completedMethod)\n        {\n            return new ReflectedAsyncActionDescriptor(asyncMethod, completedMethod, \"someName\", new Mock<ControllerDescriptor>().Object, false /* validateMethod */)\n            {\n                DispatcherCache = new ActionMethodDispatcherCache()\n            };\n        }\n\n        private class ExecuteController : AsyncController\n        {\n            private Func<object, string> _func;\n\n            [Authorize]\n            public void FooAsync(int id1)\n            {\n                _func = o => Convert.ToString(o, CultureInfo.InvariantCulture) + id1.ToString(CultureInfo.InvariantCulture);\n                AsyncManager.Parameters[\"id2\"] = \"Hello world: \";\n                AsyncManager.Finish();\n            }\n\n            [OutputCache]\n            public string FooCompleted(string id2)\n            {\n                return _func(id2);\n            }\n\n            public string FooWithBool(bool id2)\n            {\n                return _func(id2);\n            }\n\n            public string FooWithException(Exception id2)\n            {\n                return _func(id2);\n            }\n        }\n\n        private class RegularSyncController : ControllerBase\n        {\n            protected override void ExecuteCore()\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Async/Test/ReflectedAsyncControllerDescriptorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Async.Test\n{\n    public class ReflectedAsyncControllerDescriptorTest\n    {\n        [Fact]\n        public void ConstructorSetsControllerTypeProperty()\n        {\n            // Arrange\n            Type controllerType = typeof(string);\n\n            // Act\n            ReflectedAsyncControllerDescriptor cd = new ReflectedAsyncControllerDescriptor(controllerType);\n\n            // Assert\n            Assert.Same(controllerType, cd.ControllerType);\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfControllerTypeIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ReflectedAsyncControllerDescriptor(null); }, \"controllerType\");\n        }\n\n        [Fact]\n        public void FindActionReturnsActionDescriptorIfFound()\n        {\n            // Arrange\n            Type controllerType = typeof(MyController);\n            MethodInfo asyncMethodInfo = controllerType.GetMethod(\"FooAsync\");\n            MethodInfo completedMethodInfo = controllerType.GetMethod(\"FooCompleted\");\n            ReflectedAsyncControllerDescriptor cd = new ReflectedAsyncControllerDescriptor(controllerType);\n\n            // Act\n            ActionDescriptor ad = cd.FindAction(new ControllerContext(), \"NewName\");\n\n            // Assert\n            Assert.Equal(\"NewName\", ad.ActionName);\n            var castAd = Assert.IsType<ReflectedAsyncActionDescriptor>(ad);\n\n            Assert.Same(asyncMethodInfo, castAd.AsyncMethodInfo);\n            Assert.Same(completedMethodInfo, castAd.CompletedMethodInfo);\n            Assert.Same(cd, ad.ControllerDescriptor);\n        }\n\n        [Fact]\n        public void FindActionReturnsNullIfNoActionFound()\n        {\n            // Arrange\n            Type controllerType = typeof(MyController);\n            ReflectedAsyncControllerDescriptor cd = new ReflectedAsyncControllerDescriptor(controllerType);\n\n            // Act\n            ActionDescriptor ad = cd.FindAction(new ControllerContext(), \"NonExistent\");\n\n            // Assert\n            Assert.Null(ad);\n        }\n\n        [Fact]\n        public void FindActionThrowsIfActionNameIsEmpty()\n        {\n            // Arrange\n            Type controllerType = typeof(MyController);\n            ReflectedAsyncControllerDescriptor cd = new ReflectedAsyncControllerDescriptor(controllerType);\n\n            // Act & assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { cd.FindAction(new ControllerContext(), \"\"); }, \"actionName\");\n        }\n\n        [Fact]\n        public void FindActionThrowsIfActionNameIsNull()\n        {\n            // Arrange\n            Type controllerType = typeof(MyController);\n            ReflectedAsyncControllerDescriptor cd = new ReflectedAsyncControllerDescriptor(controllerType);\n\n            // Act & assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { cd.FindAction(new ControllerContext(), null); }, \"actionName\");\n        }\n\n        [Fact]\n        public void FindActionThrowsIfControllerContextIsNull()\n        {\n            // Arrange\n            Type controllerType = typeof(MyController);\n            ReflectedAsyncControllerDescriptor cd = new ReflectedAsyncControllerDescriptor(controllerType);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { cd.FindAction(null, \"someName\"); }, \"controllerContext\");\n        }\n\n        [Fact]\n        public void GetCanonicalActionsReturnsEmptyArray()\n        {\n            // this method does nothing by default\n\n            // Arrange\n            Type controllerType = typeof(MyController);\n            ReflectedAsyncControllerDescriptor cd = new ReflectedAsyncControllerDescriptor(controllerType);\n\n            // Act\n            ActionDescriptor[] canonicalActions = cd.GetCanonicalActions();\n\n            // Assert\n            Assert.Empty(canonicalActions);\n        }\n\n        [Fact]\n        public void GetCustomAttributesCallsTypeGetCustomAttributes()\n        {\n            // Arrange\n            object[] expected = new object[0];\n            Mock<Type> mockType = new Mock<Type>();\n            mockType.Setup(t => t.GetCustomAttributes(true)).Returns(expected);\n            ReflectedAsyncControllerDescriptor cd = new ReflectedAsyncControllerDescriptor(mockType.Object);\n\n            // Act\n            object[] returned = cd.GetCustomAttributes(true);\n\n            // Assert\n            Assert.Same(expected, returned);\n        }\n\n        [Fact]\n        public void GetCustomAttributesWithAttributeTypeCallsTypeGetCustomAttributes()\n        {\n            // Arrange\n            object[] expected = new object[0];\n            Mock<Type> mockType = new Mock<Type>();\n            mockType.Setup(t => t.GetCustomAttributes(typeof(ObsoleteAttribute), true)).Returns(expected);\n            ReflectedAsyncControllerDescriptor cd = new ReflectedAsyncControllerDescriptor(mockType.Object);\n\n            // Act\n            object[] returned = cd.GetCustomAttributes(typeof(ObsoleteAttribute), true);\n\n            // Assert\n            Assert.Same(expected, returned);\n        }\n\n        [Fact]\n        public void IsDefinedCallsTypeIsDefined()\n        {\n            // Arrange\n            Mock<Type> mockType = new Mock<Type>();\n            mockType.Setup(t => t.IsDefined(typeof(ObsoleteAttribute), true)).Returns(true);\n            ReflectedAsyncControllerDescriptor cd = new ReflectedAsyncControllerDescriptor(mockType.Object);\n\n            // Act\n            bool isDefined = cd.IsDefined(typeof(ObsoleteAttribute), true);\n\n            // Assert\n            Assert.True(isDefined);\n        }\n\n        private class MyController : AsyncController\n        {\n            [ActionName(\"NewName\")]\n            public void FooAsync()\n            {\n            }\n\n            public void FooCompleted()\n            {\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Async/Test/SignalContainer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\n\nnamespace System.Web.Mvc.Async.Test\n{\n    public sealed class SignalContainer<T>: IDisposable\n    {\n        private volatile object _item;\n        private readonly AutoResetEvent _waitHandle = new AutoResetEvent(false /* initialState */);\n\n        public void Signal(T item)\n        {\n            _item = item;\n            _waitHandle.Set();\n        }\n\n        public T Wait()\n        {\n            _waitHandle.WaitOne();\n            return (T)_item;\n        }\n\n        public void Dispose()\n        {\n            _waitHandle.Dispose();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Async/Test/SimpleAsyncResultTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Async.Test\n{\n    public class SimpleAsyncResultTest\n    {\n        [Fact]\n        public void AsyncStateProperty()\n        {\n            // Arrange\n            string expected = \"Hello!\";\n            SimpleAsyncResult asyncResult = new SimpleAsyncResult(expected);\n\n            // Act\n            object asyncState = asyncResult.AsyncState;\n\n            // Assert\n            Assert.Equal(expected, asyncState);\n        }\n\n        [Fact]\n        public void AsyncWaitHandleProperty()\n        {\n            // Arrange\n            SimpleAsyncResult asyncResult = new SimpleAsyncResult(null);\n\n            // Act\n            WaitHandle asyncWaitHandle = asyncResult.AsyncWaitHandle;\n\n            // Assert\n            Assert.Null(asyncWaitHandle);\n        }\n\n        [Fact]\n        public void CompletedSynchronouslyProperty()\n        {\n            // Arrange\n            SimpleAsyncResult asyncResult = new SimpleAsyncResult(null);\n\n            // Act\n            bool completedSynchronously = asyncResult.CompletedSynchronously;\n\n            // Assert\n            Assert.False(completedSynchronously);\n        }\n\n        [Fact]\n        public void IsCompletedProperty()\n        {\n            // Arrange\n            SimpleAsyncResult asyncResult = new SimpleAsyncResult(null);\n\n            // Act\n            bool isCompleted = asyncResult.IsCompleted;\n\n            // Assert\n            Assert.False(isCompleted);\n        }\n\n        [Fact]\n        public void MarkCompleted_AsynchronousCompletion()\n        {\n            // Arrange\n            SimpleAsyncResult asyncResult = new SimpleAsyncResult(null);\n\n            bool callbackWasCalled = false;\n            AsyncCallback callback = ar =>\n            {\n                callbackWasCalled = true;\n                Assert.Equal(asyncResult, ar);\n                Assert.True(ar.IsCompleted);\n                Assert.False(ar.CompletedSynchronously);\n            };\n\n            // Act & assert\n            asyncResult.MarkCompleted(false, callback);\n            Assert.True(callbackWasCalled);\n        }\n\n        [Fact]\n        public void MarkCompleted_SynchronousCompletion()\n        {\n            // Arrange\n            SimpleAsyncResult asyncResult = new SimpleAsyncResult(null);\n\n            bool callbackWasCalled = false;\n            AsyncCallback callback = ar =>\n            {\n                callbackWasCalled = true;\n                Assert.Equal(asyncResult, ar);\n                Assert.True(ar.IsCompleted);\n                Assert.True(ar.CompletedSynchronously);\n            };\n\n            // Act & assert\n            asyncResult.MarkCompleted(true, callback);\n            Assert.True(callbackWasCalled);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Async/Test/SingleEntryGateTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Async.Test\n{\n    public class SingleEntryGateTest\n    {\n        [Fact]\n        public void TryEnterShouldBeTrueForFirstCallAndFalseForSubsequentCalls()\n        {\n            // Arrange\n            SingleEntryGate gate = new SingleEntryGate();\n\n            // Act\n            bool firstCall = gate.TryEnter();\n            bool secondCall = gate.TryEnter();\n            bool thirdCall = gate.TryEnter();\n\n            // Assert\n            Assert.True(firstCall);\n            Assert.False(secondCall);\n            Assert.False(thirdCall);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Async/Test/SynchronizationContextUtilTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Async.Test\n{\n    public class SynchronizationContextUtilTest\n    {\n        [Fact]\n        public void SyncWithAction()\n        {\n            // Arrange\n            bool actionWasCalled = false;\n            bool sendWasCalled = false;\n\n            Mock<SynchronizationContext> mockSyncContext = new Mock<SynchronizationContext>();\n            mockSyncContext\n                .Setup(sc => sc.Send(It.IsAny<SendOrPostCallback>(), null))\n                .Callback(\n                    delegate(SendOrPostCallback d, object state)\n                    {\n                        sendWasCalled = true;\n                        d(state);\n                    });\n\n            // Act\n            SynchronizationContextUtil.Sync(mockSyncContext.Object, () => { actionWasCalled = true; });\n\n            // Assert\n            Assert.True(actionWasCalled);\n            Assert.True(sendWasCalled);\n        }\n\n        [Fact]\n        public void SyncWithActionCapturesException()\n        {\n            // Arrange\n            InvalidOperationException exception = new InvalidOperationException(\"Some exception text.\");\n\n            Mock<SynchronizationContext> mockSyncContext = new Mock<SynchronizationContext>();\n            mockSyncContext\n                .Setup(sc => sc.Send(It.IsAny<SendOrPostCallback>(), null))\n                .Callback(\n                    delegate(SendOrPostCallback d, object state)\n                    {\n                        try\n                        {\n                            d(state);\n                        }\n                        catch\n                        {\n                            // swallow exceptions, just like AspNetSynchronizationContext\n                        }\n                    });\n\n            // Act & assert\n            SynchronousOperationException thrownException = Assert.Throws<SynchronousOperationException>(\n                delegate { SynchronizationContextUtil.Sync(mockSyncContext.Object, () => { throw exception; }); },\n                @\"An operation that crossed a synchronization context failed. See the inner exception for more information.\");\n\n            Assert.Equal(exception, thrownException.InnerException);\n        }\n\n        [Fact]\n        public void SyncWithFunc()\n        {\n            // Arrange\n            bool sendWasCalled = false;\n\n            Mock<SynchronizationContext> mockSyncContext = new Mock<SynchronizationContext>();\n            mockSyncContext\n                .Setup(sc => sc.Send(It.IsAny<SendOrPostCallback>(), null))\n                .Callback(\n                    delegate(SendOrPostCallback d, object state)\n                    {\n                        sendWasCalled = true;\n                        d(state);\n                    });\n\n            // Act\n            int retVal = SynchronizationContextUtil.Sync(mockSyncContext.Object, () => 42);\n\n            // Assert\n            Assert.Equal(42, retVal);\n            Assert.True(sendWasCalled);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Async/Test/SynchronousOperationExceptionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Runtime.Serialization.Formatters.Binary;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Async.Test\n{\n    public class SynchronousOperationExceptionTest\n    {\n        [Fact]\n        public void ConstructorWithMessageAndInnerExceptionParameter()\n        {\n            // Arrange\n            Exception innerException = new Exception();\n\n            // Act\n            SynchronousOperationException ex = new SynchronousOperationException(\"the message\", innerException);\n\n            // Assert\n            Assert.Equal(\"the message\", ex.Message);\n            Assert.Equal(innerException, ex.InnerException);\n        }\n\n        [Fact]\n        public void ConstructorWithMessageParameter()\n        {\n            // Act\n            SynchronousOperationException ex = new SynchronousOperationException(\"the message\");\n\n            // Assert\n            Assert.Equal(\"the message\", ex.Message);\n        }\n\n        [Fact]\n        public void ConstructorWithoutParameters()\n        {\n            // Act & assert\n            Assert.Throws<SynchronousOperationException>(\n                delegate { throw new SynchronousOperationException(); });\n        }\n\n        [Fact]\n        public void TypeIsSerializable()\n        {\n            // Arrange\n            MemoryStream ms = new MemoryStream();\n            BinaryFormatter formatter = new BinaryFormatter();\n            SynchronousOperationException ex = new SynchronousOperationException(\"the message\", new Exception(\"inner exception\"));\n\n            // Act\n            formatter.Serialize(ms, ex);\n            ms.Position = 0;\n            SynchronousOperationException deserialized = formatter.Deserialize(ms) as SynchronousOperationException;\n\n            // Assert\n            Assert.NotNull(deserialized);\n            Assert.Equal(\"the message\", deserialized.Message);\n            Assert.NotNull(deserialized.InnerException);\n            Assert.Equal(\"inner exception\", deserialized.InnerException.Message);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Async/Test/TaskAsyncActionDescriptorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Async.Test\n{\n    public class TaskAsyncActionDescriptorTest\n    {\n        private readonly MethodInfo _taskMethod = typeof(ExecuteController).GetMethod(\"SimpleTask\");\n\n        [Fact]\n        public void Constructor_SetsProperties()\n        {\n            // Arrange\n            string actionName = \"SomeAction\";\n            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;\n\n            // Act\n            TaskAsyncActionDescriptor ad = new TaskAsyncActionDescriptor(_taskMethod, actionName, cd);\n\n            // Assert\n            Assert.Equal(_taskMethod, ad.TaskMethodInfo);\n            Assert.Equal(actionName, ad.ActionName);\n            Assert.Equal(cd, ad.ControllerDescriptor);\n        }\n\n        [Fact]\n        public void Constructor_ThrowsIfActionNameIsEmpty()\n        {\n            // Arrange\n            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;\n\n            // Act & assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { new TaskAsyncActionDescriptor(_taskMethod, \"\", cd); }, \"actionName\");\n        }\n\n        [Fact]\n        public void Constructor_ThrowsIfActionNameIsNull()\n        {\n            // Arrange\n            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;\n\n            // Act & assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { new TaskAsyncActionDescriptor(_taskMethod, null, cd); }, \"actionName\");\n        }\n\n        [Fact]\n        public void Constructor_ThrowsIfTaskMethodInfoIsInvalid()\n        {\n            // Arrange\n            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;\n            MethodInfo getHashCodeMethod = typeof(object).GetMethod(\"GetHashCode\");\n\n            // Act & assert\n            Assert.Throws<ArgumentException>(\n                delegate { new TaskAsyncActionDescriptor(getHashCodeMethod, \"SomeAction\", cd); },\n                \"Cannot create a descriptor for instance method 'Int32 GetHashCode()' on type 'System.Object' because the type does not derive from ControllerBase.\" + Environment.NewLine\n              + \"Parameter name: taskMethodInfo\");\n        }\n\n        [Fact]\n        public void Constructor_ThrowsIfTaskMethodInfoIsNull()\n        {\n            // Arrange\n            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new TaskAsyncActionDescriptor(null, \"SomeAction\", cd); }, \"taskMethodInfo\");\n        }\n\n        [Fact]\n        public void Constructor_ThrowsIfControllerDescriptorIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new TaskAsyncActionDescriptor(_taskMethod, \"SomeAction\", null); }, \"controllerDescriptor\");\n        }\n\n        [Fact]\n        public void ExecuteTask()\n        {\n            // Arrange\n            TaskAsyncActionDescriptor actionDescriptor = GetActionDescriptor(GetExecuteControllerMethodInfo(\"SimpleTask\"));\n\n            Dictionary<string, object> parameters = new Dictionary<string, object>()\n            {\n                { \"doWork\", true }\n            };\n\n            ControllerContext controllerContext = GetControllerContext();\n\n            // Act\n            object retVal = ExecuteHelper(actionDescriptor, parameters, controllerContext);\n\n            // Assert\n            Assert.Null(retVal);\n            Assert.True((controllerContext.Controller as ExecuteController).WorkDone);\n        }\n\n        [Fact]\n        public void ExecuteTaskGeneric()\n        {\n            // Arrange\n            TaskAsyncActionDescriptor actionDescriptor = GetActionDescriptor(GetExecuteControllerMethodInfo(\"GenericTask\"));\n\n            Dictionary<string, object> parameters = new Dictionary<string, object>()\n            {\n                { \"taskId\", \"foo\" }\n            };\n\n            // Act\n            object retVal = ExecuteHelper(actionDescriptor, parameters);\n\n            // Assert\n            Assert.Equal(\"foo\", retVal);\n        }\n\n        [Fact]\n        public void ExecuteTaskPreservesStackTraceOnException()\n        {\n            // Arrange\n            TaskAsyncActionDescriptor actionDescriptor = GetActionDescriptor(GetExecuteControllerMethodInfo(\"SimpleTaskException\"));\n\n            Dictionary<string, object> parameters = new Dictionary<string, object>()\n            {\n                { \"doWork\", true }\n            };\n\n            // Act\n            IAsyncResult result = actionDescriptor.BeginExecute(GetControllerContext(), parameters, null, null);\n\n            // Assert\n            InvalidOperationException ex = Assert.Throws<InvalidOperationException>(\n                () => actionDescriptor.EndExecute(result),\n                \"Test exception from action\"\n                );\n\n            Assert.Contains(\"System.Web.Mvc.Async.Test.TaskAsyncActionDescriptorTest.ExecuteController.\", ex.StackTrace);\n        }\n\n        [Fact]\n        public void ExecuteTaskGenericPreservesStackTraceOnException()\n        {\n            // Arrange\n            TaskAsyncActionDescriptor actionDescriptor = GetActionDescriptor(GetExecuteControllerMethodInfo(\"GenericTaskException\"));\n\n            Dictionary<string, object> parameters = new Dictionary<string, object>()\n            {\n                { \"taskId\", \"foo\" },\n                { \"throwException\", true }\n            };\n\n            // Act\n            IAsyncResult result = actionDescriptor.BeginExecute(GetControllerContext(), parameters, null, null);\n\n            // Assert\n            InvalidOperationException ex = Assert.Throws<InvalidOperationException>(\n                () => actionDescriptor.EndExecute(result),\n                \"Test exception from action\"\n                );\n\n            Assert.Contains(\"System.Web.Mvc.Async.Test.TaskAsyncActionDescriptorTest.ExecuteController.\", ex.StackTrace);\n        }\n\n        [Fact]\n        public void ExecuteTaskOfPrivateT()\n        {\n            // Arrange\n            TaskAsyncActionDescriptor actionDescriptor = GetActionDescriptor(GetExecuteControllerMethodInfo(\"TaskOfPrivateT\"));\n            ControllerContext controllerContext = GetControllerContext();\n\n            Dictionary<string, object> parameters = new Dictionary<string, object>();\n\n            // Act\n            object retVal = ExecuteHelper(actionDescriptor, parameters, controllerContext);\n\n            // Assert\n            Assert.Null(retVal);\n            Assert.True((controllerContext.Controller as ExecuteController).WorkDone);\n        }\n\n        [Fact]\n        public void ExecuteTaskPreservesState()\n        {\n            // Arrange\n            TaskAsyncActionDescriptor actionDescriptor = GetActionDescriptor(GetExecuteControllerMethodInfo(\"SimpleTask\"));\n\n            Dictionary<string, object> parameters = new Dictionary<string, object>()\n            {\n                { \"doWork\", true }\n            };\n\n            ControllerContext controllerContext = GetControllerContext();\n\n            // Act\n            TaskWrapperAsyncResult result = (TaskWrapperAsyncResult)actionDescriptor.BeginExecute(GetControllerContext(), parameters, callback: null, state: \"state\");\n\n            // Assert\n            Assert.Equal(\"state\", result.AsyncState);\n        }\n\n        [Fact]\n        public void ExecuteTaskWithNullParameterAndTimeout()\n        {\n            // Arrange\n            TaskAsyncActionDescriptor actionDescriptor = GetActionDescriptor(GetExecuteControllerMethodInfo(\"TaskTimeoutWithNullParam\"));\n\n            Dictionary<string, object> token = new Dictionary<string, object>()\n            {\n                { \"nullParam\", null },\n                { \"cancellationToken\", new CancellationToken() }\n            };\n\n            // Act & assert\n            Assert.Throws<TimeoutException>(\n                () => actionDescriptor.EndExecute(actionDescriptor.BeginExecute(GetControllerContext(0), parameters: token, callback: null, state: null)),\n                \"The operation has timed out.\"\n                );\n        }\n\n        [Fact]\n        public void ExecuteWithInfiniteTimeout()\n        {\n            // Arrange\n            TaskAsyncActionDescriptor actionDescriptor = GetActionDescriptor(GetExecuteControllerMethodInfo(\"TaskWithInfiniteTimeout\"));\n            ControllerContext controllerContext = GetControllerContext(Timeout.Infinite);\n\n            Dictionary<string, object> parameters = new Dictionary<string, object>()\n            {\n                { \"cancellationToken\", new CancellationToken() }\n            };\n\n            // Act\n            object retVal = ExecuteHelper(actionDescriptor, parameters);\n\n            // Assert\n            Assert.Equal(\"Task Completed\", retVal);\n        }\n\n        [Fact]\n        public void ExecuteTaskWithImmediateTimeout()\n        {\n            // Arrange\n            TaskAsyncActionDescriptor actionDescriptor = GetActionDescriptor(GetExecuteControllerMethodInfo(\"TaskTimeout\"));\n\n            Dictionary<string, object> token = new Dictionary<string, object>()\n            {\n                { \"cancellationToken\", new CancellationToken() }\n            };\n\n            // Act & assert\n            Assert.Throws<TimeoutException>(\n                () => actionDescriptor.EndExecute(actionDescriptor.BeginExecute(GetControllerContext(0), parameters: token, callback: null, state: null)),\n                \"The operation has timed out.\"\n                );\n        }\n\n        [Fact]\n        public void ExecuteTaskWithTimeout()\n        {\n            // Arrange\n            TaskAsyncActionDescriptor actionDescriptor = GetActionDescriptor(GetExecuteControllerMethodInfo(\"TaskTimeout\"));\n\n            Dictionary<string, object> token = new Dictionary<string, object>()\n            {\n                { \"cancellationToken\", new CancellationToken() }\n            };\n\n            // Act & assert\n            Assert.Throws<TimeoutException>(\n                () => actionDescriptor.EndExecute(actionDescriptor.BeginExecute(GetControllerContext(2000), parameters: token, callback: null, state: null)),\n                \"The operation has timed out.\"\n                );\n        }\n\n        [Fact]\n        public void SynchronousExecuteThrows()\n        {\n            // Arrange\n            TaskAsyncActionDescriptor actionDescriptor = GetActionDescriptor(GetExecuteControllerMethodInfo(\"SimpleTask\"));\n\n            // Act & assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { actionDescriptor.Execute(new ControllerContext(), new Dictionary<string, object>()); }, \"The asynchronous action method 'someName' returns a Task, which cannot be executed synchronously.\");\n        }\n\n        [Fact]\n        public void Execute_ThrowsIfControllerContextIsNull()\n        {\n            // Arrange\n            TaskAsyncActionDescriptor ad = GetActionDescriptor(_taskMethod);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { ad.BeginExecute(null, new Dictionary<string, object>(), null, null); }, \"controllerContext\");\n        }\n\n        [Fact]\n        public void Execute_ThrowsIfControllerIsNotAsyncManagerContainer()\n        {\n            // Arrange\n            TaskAsyncActionDescriptor ad = GetActionDescriptor(_taskMethod);\n            ControllerContext controllerContext = new ControllerContext()\n            {\n                Controller = new RegularSyncController()\n            };\n\n            Dictionary<string, object> parameters = new Dictionary<string, object>()\n            {\n                { \"doWork\", true }\n            };\n\n            // Act & assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { ad.BeginExecute(controllerContext, parameters, null, null); },\n                @\"The controller of type 'System.Web.Mvc.Async.Test.TaskAsyncActionDescriptorTest+RegularSyncController' must subclass AsyncController or implement the IAsyncManagerContainer interface.\");\n        }\n\n        [Fact]\n        public void Execute_ThrowsIfParametersIsNull()\n        {\n            // Arrange\n            TaskAsyncActionDescriptor ad = GetActionDescriptor(_taskMethod);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { ad.BeginExecute(new ControllerContext(), null, null, null); }, \"parameters\");\n        }\n\n        [Fact]\n        public void GetCustomAttributesCallsMethodInfoGetCustomAttributes()\n        {\n            // Arrange\n            object[] expected = new object[0];\n            Mock<MethodInfo> mockMethod = new Mock<MethodInfo>();\n            mockMethod.Setup(mi => mi.GetCustomAttributes(true)).Returns(expected);\n            TaskAsyncActionDescriptor ad = new TaskAsyncActionDescriptor(mockMethod.Object, \"someName\", new Mock<ControllerDescriptor>().Object, validateMethod: false)\n            {\n                DispatcherCache = new ActionMethodDispatcherCache()\n            };\n\n            // Act\n            object[] returned = ad.GetCustomAttributes(true);\n\n            // Assert\n            Assert.Same(expected, returned);\n        }\n\n        [Fact]\n        public void GetCustomAttributesWithAttributeTypeCallsMethodInfoGetCustomAttributes()\n        {\n            // Arrange\n            object[] expected = new object[0];\n            Mock<MethodInfo> mockMethod = new Mock<MethodInfo>();\n            mockMethod.Setup(mi => mi.GetCustomAttributes(typeof(ObsoleteAttribute), true)).Returns(expected);\n            TaskAsyncActionDescriptor ad = new TaskAsyncActionDescriptor(mockMethod.Object, \"someName\", new Mock<ControllerDescriptor>().Object, validateMethod: false)\n            {\n                DispatcherCache = new ActionMethodDispatcherCache()\n            };\n\n            // Act\n            object[] returned = ad.GetCustomAttributes(typeof(ObsoleteAttribute), true);\n\n            // Assert\n            Assert.Same(expected, returned);\n        }\n\n        [Fact]\n        public void GetParameters()\n        {\n            // Arrange\n            ParameterInfo pInfo = _taskMethod.GetParameters()[0];\n            TaskAsyncActionDescriptor ad = GetActionDescriptor(_taskMethod);\n\n            // Act\n            ParameterDescriptor[] pDescsFirstCall = ad.GetParameters();\n            ParameterDescriptor[] pDescsSecondCall = ad.GetParameters();\n\n            // Assert\n            Assert.NotSame(pDescsFirstCall, pDescsSecondCall); // Should get a new array every time\n            Assert.Equal(pDescsFirstCall, pDescsSecondCall);\n\n            ParameterDescriptor parameterDescriptor = Assert.Single(pDescsFirstCall);\n            ReflectedParameterDescriptor pDesc = Assert.IsType<ReflectedParameterDescriptor>(parameterDescriptor);\n\n            Assert.NotNull(pDesc);\n            Assert.Same(ad, pDesc.ActionDescriptor);\n            Assert.Same(pInfo, pDesc.ParameterInfo);\n        }\n\n        [Fact]\n        public void GetSelectors()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n            Mock<MethodInfo> mockMethod = new Mock<MethodInfo>();\n\n            Mock<ActionMethodSelectorAttribute> mockAttr = new Mock<ActionMethodSelectorAttribute>();\n            mockAttr.Setup(attr => attr.IsValidForRequest(controllerContext, mockMethod.Object)).Returns(true).Verifiable();\n            mockMethod.Setup(m => m.GetCustomAttributes(typeof(ActionMethodSelectorAttribute), true)).Returns(new ActionMethodSelectorAttribute[] { mockAttr.Object });\n\n            TaskAsyncActionDescriptor ad = new TaskAsyncActionDescriptor(mockMethod.Object, \"someName\", new Mock<ControllerDescriptor>().Object, validateMethod: false)\n            {\n                DispatcherCache = new ActionMethodDispatcherCache()\n            };\n\n            // Act\n            ICollection<ActionSelector> selectors = ad.GetSelectors();\n            bool executedSuccessfully = selectors.All(s => s(controllerContext));\n\n            // Assert\n            Assert.Single(selectors);\n            Assert.True(executedSuccessfully);\n            mockAttr.Verify();\n        }\n\n        [Fact]\n        public void IsDefined()\n        {\n            // Arrange\n            TaskAsyncActionDescriptor ad = GetActionDescriptor(_taskMethod);\n\n            // Act\n            bool isDefined = ad.IsDefined(typeof(AuthorizeAttribute), inherit: true);\n\n            // Assert\n            Assert.True(isDefined);\n        }\n\n        public static object ExecuteHelper(TaskAsyncActionDescriptor actionDescriptor, Dictionary<string, object> parameters, ControllerContext controllerContext = null)\n        {\n            using (SignalContainer<object> resultContainer = new SignalContainer<object>())\n            {\n                AsyncCallback callback = ar =>\n                {\n                    object o = actionDescriptor.EndExecute(ar);\n                    resultContainer.Signal(o);\n                };\n\n                actionDescriptor.BeginExecute(controllerContext ?? GetControllerContext(), parameters, callback, state: null);\n                return resultContainer.Wait();\n            }\n        }\n\n        private static TaskAsyncActionDescriptor GetActionDescriptor(MethodInfo taskMethod)\n        {\n            return new TaskAsyncActionDescriptor(taskMethod, \"someName\", new Mock<ControllerDescriptor>().Object)\n            {\n                DispatcherCache = new ActionMethodDispatcherCache()\n            };\n        }\n\n        private static ControllerContext GetControllerContext(int timeout = 45 * 1000)\n        {\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            ExecuteController controller = new ExecuteController();\n            controller.AsyncManager.Timeout = timeout;\n            mockControllerContext.Setup(c => c.Controller).Returns(controller);\n            return mockControllerContext.Object;\n        }\n\n        private static MethodInfo GetExecuteControllerMethodInfo(string methodName)\n        {\n            return typeof(ExecuteController).GetMethod(methodName);\n        }\n\n        private class ExecuteController : AsyncController\n        {\n            public bool WorkDone { get; set; }\n\n            public Task<ActionResult> ReturnedTask { get; set; }\n\n            public Task<string> GenericTask(string taskId)\n            {\n                return Task.Factory.StartNew(() => taskId);\n            }\n\n            public Task<string> GenericTaskException(string taskId, bool throwException)\n            {\n                return Task.Factory.StartNew(() =>\n                {\n                    if (throwException)\n                    {\n                        ThrowException();\n                    }\n                    ;\n                    return taskId;\n                });\n            }\n\n            private void ThrowException()\n            {\n                throw new InvalidOperationException(\"Test exception from action\");\n            }\n\n            [Authorize]\n            public Task SimpleTask(bool doWork)\n            {\n                return Task.Factory.StartNew(() => { WorkDone = doWork; });\n            }\n\n            public Task SimpleTaskException(bool doWork)\n            {\n                return Task.Factory.StartNew(() => { ThrowException(); });\n            }\n\n            public Task<ActionResult> TaskTimeoutWithNullParam(Object nullParam, CancellationToken cancellationToken)\n            {\n                return TaskTimeout(cancellationToken);\n            }\n\n            public Task<string> TaskWithInfiniteTimeout(CancellationToken cancellationToken)\n            {\n                return Task.Factory.StartNew(() => \"Task Completed\");\n            }\n\n            public Task<ActionResult> TaskTimeout(CancellationToken cancellationToken)\n            {\n                TaskCompletionSource<ActionResult> completionSource = new TaskCompletionSource<ActionResult>();\n                cancellationToken.Register(() => completionSource.TrySetCanceled());\n                ReturnedTask = completionSource.Task;\n                return ReturnedTask;\n            }\n\n            public Task TaskOfPrivateT()\n            {\n                var completionSource = new TaskCompletionSource<PrivateObject>();\n                completionSource.SetResult(new PrivateObject());\n                WorkDone = true;\n                return completionSource.Task;\n            }\n\n            private class PrivateObject\n            {\n                public override string ToString()\n                {\n                    return \"Private Object\";\n                }\n            }\n        }\n\n        // Controller is async, so derive from ControllerBase to get sync behavior.\n        private class RegularSyncController : ControllerBase\n        {\n            protected override void ExecuteCore()\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Async/Test/TaskWrapperAsyncResultTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Async.Test\n{\n    public class TaskWrapperAsyncResultTest\n    {\n        [Fact]\n        public void PropertiesHaveCorrectValues()\n        {\n            // Arrange\n            Mock<MyTask> mockTask = new Mock<MyTask>();\n            WaitHandle waitHandle = new Mock<WaitHandle>().Object;\n\n            mockTask.Setup(o => o.AsyncState).Returns(10);\n            mockTask.Setup(o => o.AsyncWaitHandle).Returns(waitHandle);\n            mockTask.Setup(o => o.CompletedSynchronously).Returns(true);\n            mockTask.Setup(o => o.IsCompleted).Returns(true);\n\n            // Act\n            TaskWrapperAsyncResult taskWrapper = new TaskWrapperAsyncResult(mockTask.Object, asyncState: 20);\n\n            // Assert\n            Assert.Equal(20, taskWrapper.AsyncState);\n            Assert.Equal(waitHandle, taskWrapper.AsyncWaitHandle);\n            Assert.True(taskWrapper.CompletedSynchronously);\n            Assert.True(taskWrapper.IsCompleted);\n            Assert.Equal(mockTask.Object, taskWrapper.Task);\n        }\n\n        // Assists in mocking a Task by passing a dummy action to the Task constructor [which defers execution]\n        public class MyTask : Task, IAsyncResult\n        {\n            public MyTask()\n                : base(() => { })\n            {\n            }\n\n            public new virtual object AsyncState\n            {\n                get { throw new NotImplementedException(); }\n            }\n\n            public virtual WaitHandle AsyncWaitHandle\n            {\n                get { throw new NotImplementedException(); }\n            }\n\n            public virtual bool CompletedSynchronously\n            {\n                get { throw new NotImplementedException(); }\n            }\n\n            public new virtual bool IsCompleted\n            {\n                get { throw new NotImplementedException(); }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Async/Test/TriggerListenerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Async.Test\n{\n    public class TriggerListenerTest\n    {\n        [Fact]\n        public void PerformTest()\n        {\n            // Arrange\n            int count = 0;\n            TriggerListener listener = new TriggerListener();\n            Trigger trigger = listener.CreateTrigger();\n\n            // Act & assert (hasn't fired yet)\n            listener.SetContinuation(() => { count++; });\n            listener.Activate();\n            Assert.Equal(0, count);\n\n            // Act & assert (fire it, get the callback)\n            trigger.Fire();\n            Assert.Equal(1, count);\n\n            // Act & assert (fire again, but no callback since it already fired)\n            Trigger trigger2 = listener.CreateTrigger();\n            trigger2.Fire();\n            Assert.Equal(1, count);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/ExpressionUtil/Test/BinaryExpressionFingerprintTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq.Expressions;\nusing System.Reflection;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.ExpressionUtil.Test\n{\n    public class BinaryExpressionFingerprintTest\n    {\n        [Fact]\n        public void Properties()\n        {\n            // Arrange\n            ExpressionType expectedNodeType = ExpressionType.Add;\n            Type expectedType = typeof(DateTime);\n            MethodInfo expectedMethod = typeof(DateTime).GetMethod(\"op_Addition\", new Type[] { typeof(DateTime), typeof(TimeSpan) });\n\n            // Act\n            BinaryExpressionFingerprint fingerprint = new BinaryExpressionFingerprint(expectedNodeType, expectedType, expectedMethod);\n\n            // Assert\n            Assert.Equal(expectedNodeType, fingerprint.NodeType);\n            Assert.Equal(expectedType, fingerprint.Type);\n            Assert.Equal(expectedMethod, fingerprint.Method);\n        }\n\n        [Fact]\n        public void Comparison_Equality()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Add;\n            Type type = typeof(DateTime);\n            MethodInfo method = typeof(DateTime).GetMethod(\"op_Addition\", new Type[] { typeof(DateTime), typeof(TimeSpan) });\n\n            // Act\n            BinaryExpressionFingerprint fingerprint1 = new BinaryExpressionFingerprint(nodeType, type, method);\n            BinaryExpressionFingerprint fingerprint2 = new BinaryExpressionFingerprint(nodeType, type, method);\n\n            // Assert\n            Assert.Equal(fingerprint1, fingerprint2);\n            Assert.Equal(fingerprint1.GetHashCode(), fingerprint2.GetHashCode());\n        }\n\n        [Fact]\n        public void Comparison_Inequality_FingerprintType()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Add;\n            Type type = typeof(DateTime);\n            MethodInfo method = typeof(DateTime).GetMethod(\"op_Addition\", new Type[] { typeof(DateTime), typeof(TimeSpan) });\n\n            // Act\n            BinaryExpressionFingerprint fingerprint1 = new BinaryExpressionFingerprint(nodeType, type, method);\n            DummyExpressionFingerprint fingerprint2 = new DummyExpressionFingerprint(nodeType, type);\n\n            // Assert\n            Assert.NotEqual<ExpressionFingerprint>(fingerprint1, fingerprint2);\n        }\n\n        [Fact]\n        public void Comparison_Inequality_Method()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Add;\n            Type type = typeof(DateTime);\n            MethodInfo method = typeof(DateTime).GetMethod(\"op_Addition\", new Type[] { typeof(DateTime), typeof(TimeSpan) });\n\n            // Act\n            BinaryExpressionFingerprint fingerprint1 = new BinaryExpressionFingerprint(nodeType, type, method);\n            BinaryExpressionFingerprint fingerprint2 = new BinaryExpressionFingerprint(nodeType, type, null /* method */);\n\n            // Assert\n            Assert.NotEqual(fingerprint1, fingerprint2);\n        }\n\n        [Fact]\n        public void Comparison_Inequality_Type()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Add;\n            Type type = typeof(DateTime);\n            MethodInfo method = typeof(DateTime).GetMethod(\"op_Addition\", new Type[] { typeof(DateTime), typeof(TimeSpan) });\n\n            // Act\n            BinaryExpressionFingerprint fingerprint1 = new BinaryExpressionFingerprint(nodeType, type, method);\n            BinaryExpressionFingerprint fingerprint2 = new BinaryExpressionFingerprint(nodeType, typeof(object), method);\n\n            // Assert\n            Assert.NotEqual(fingerprint1, fingerprint2);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/ExpressionUtil/Test/CachedExpressionCompilerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq.Expressions;\nusing System.Reflection;\nusing System.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.ExpressionUtil.Test\n{\n    public class CachedExpressionCompilerTest\n    {\n        private delegate Func<TIn, TOut> Compiler<TIn, TOut>(Expression<Func<TIn, TOut>> expr);\n\n        [Fact]\n        public void Compiler_CompileFromConstLookup()\n        {\n            // Arrange\n            Expression<Func<string, int>> expr = model => 42;\n            var compiler = GetCompilerMethod<string, int>(\"CompileFromConstLookup\");\n\n            // Act\n            var func = compiler(expr);\n            int result = func(\"any model\");\n\n            // Assert\n            Assert.Equal(42, result);\n        }\n\n        [Fact]\n        public void Compiler_CompileFromFingerprint()\n        {\n            // Arrange\n            Expression<Func<string, int>> expr = s => 20 * s.Length;\n            var compiler = GetCompilerMethod<string, int>(\"CompileFromFingerprint\");\n\n            // Act\n            var func = compiler(expr);\n            int result = func(\"hello\");\n\n            // Assert\n            Assert.Equal(100, result);\n        }\n\n        [Fact]\n        public void Compiler_CompileFromIdentityFunc()\n        {\n            // Arrange\n            Expression<Func<string, string>> expr = model => model;\n            var compiler = GetCompilerMethod<string, string>(\"CompileFromIdentityFunc\");\n\n            // Act\n            var func = compiler(expr);\n            string result = func(\"hello\");\n\n            // Assert\n            Assert.Equal(\"hello\", result);\n        }\n\n        [Fact]\n        public void Compiler_CompileFromMemberAccess_CapturedLocal()\n        {\n            // Arrange\n            string capturedLocal = \"goodbye\";\n            Expression<Func<string, string>> expr = _ => capturedLocal;\n            var compiler = GetCompilerMethod<string, string>(\"CompileFromMemberAccess\");\n\n            // Act\n            var func = compiler(expr);\n            string result = func(\"hello\");\n\n            // Assert\n            Assert.Equal(\"goodbye\", result);\n        }\n\n        [Fact]\n        public void Compiler_CompileFromMemberAccess_ParameterInstanceMember()\n        {\n            // Arrange\n            Expression<Func<string, int>> expr = s => s.Length;\n            var compiler = GetCompilerMethod<string, int>(\"CompileFromMemberAccess\");\n\n            // Act\n            var func = compiler(expr);\n            int result = func(\"hello\");\n\n            // Assert\n            Assert.Equal(5, result);\n        }\n\n        [Fact]\n        public void Compiler_CompileFromMemberAccess_StaticMember()\n        {\n            // Arrange\n            Expression<Func<string, string>> expr = _ => String.Empty;\n            var compiler = GetCompilerMethod<string, string>(\"CompileFromMemberAccess\");\n\n            // Act\n            var func = compiler(expr);\n            string result = func(\"hello\");\n\n            // Assert\n            Assert.Equal(\"\", result);\n        }\n\n        [Fact]\n        public void Compiler_CompileSlow()\n        {\n            // Arrange\n            Expression<Func<string, string>> expr = s => new StringBuilder(s).ToString();\n            var compiler = GetCompilerMethod<string, string>(\"CompileSlow\");\n\n            // Act\n            var func = compiler(expr);\n            string result = func(\"hello\");\n\n            // Assert\n            Assert.Equal(\"hello\", result);\n        }\n\n        [Fact]\n        public void Process()\n        {\n            // Arrange\n            Expression<Func<string, string>> expr = s => new StringBuilder(s).ToString();\n\n            // Act\n            var func = CachedExpressionCompiler.Process(expr);\n            string result = func(\"hello\");\n\n            // Assert\n            Assert.Equal(\"hello\", result);\n        }\n\n        // helper to create a delegate to a private method on the compiler\n        private static Compiler<TIn, TOut> GetCompilerMethod<TIn, TOut>(string methodName)\n        {\n            Type openCompilerType = typeof(CachedExpressionCompiler).GetNestedType(\"Compiler`2\", BindingFlags.NonPublic);\n            Type closedCompilerType = openCompilerType.MakeGenericType(typeof(TIn), typeof(TOut));\n            MethodInfo targetMethod = closedCompilerType.GetMethod(methodName, BindingFlags.Static | BindingFlags.NonPublic);\n            return (Compiler<TIn, TOut>)Delegate.CreateDelegate(typeof(Compiler<TIn, TOut>), targetMethod);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/ExpressionUtil/Test/ConditionalExpressionFingerprintTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq.Expressions;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.ExpressionUtil.Test\n{\n    public class ConditionalExpressionFingerprintTest\n    {\n        [Fact]\n        public void Properties()\n        {\n            // Arrange\n            ExpressionType expectedNodeType = ExpressionType.Conditional;\n            Type expectedType = typeof(object);\n\n            // Act\n            ConditionalExpressionFingerprint fingerprint = new ConditionalExpressionFingerprint(expectedNodeType, expectedType);\n\n            // Assert\n            Assert.Equal(expectedNodeType, fingerprint.NodeType);\n            Assert.Equal(expectedType, fingerprint.Type);\n        }\n\n        [Fact]\n        public void Comparison_Equality()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Conditional;\n            Type type = typeof(object);\n\n            // Act\n            ConditionalExpressionFingerprint fingerprint1 = new ConditionalExpressionFingerprint(nodeType, type);\n            ConditionalExpressionFingerprint fingerprint2 = new ConditionalExpressionFingerprint(nodeType, type);\n\n            // Assert\n            Assert.Equal(fingerprint1, fingerprint2);\n            Assert.Equal(fingerprint1.GetHashCode(), fingerprint2.GetHashCode());\n        }\n\n        [Fact]\n        public void Comparison_Inequality_FingerprintType()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Conditional;\n            Type type = typeof(object);\n\n            // Act\n            ConditionalExpressionFingerprint fingerprint1 = new ConditionalExpressionFingerprint(nodeType, type);\n            DummyExpressionFingerprint fingerprint2 = new DummyExpressionFingerprint(nodeType, type);\n\n            // Assert\n            Assert.NotEqual<ExpressionFingerprint>(fingerprint1, fingerprint2);\n        }\n\n        [Fact]\n        public void Comparison_Inequality_Type()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Conditional;\n            Type type = typeof(object);\n\n            // Act\n            ConditionalExpressionFingerprint fingerprint1 = new ConditionalExpressionFingerprint(nodeType, type);\n            ConditionalExpressionFingerprint fingerprint2 = new ConditionalExpressionFingerprint(nodeType, typeof(string));\n\n            // Assert\n            Assert.NotEqual(fingerprint1, fingerprint2);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/ExpressionUtil/Test/ConstantExpressionFingerprintTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq.Expressions;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.ExpressionUtil.Test\n{\n    public class ConstantExpressionFingerprintTest\n    {\n        [Fact]\n        public void Properties()\n        {\n            // Arrange\n            ExpressionType expectedNodeType = ExpressionType.Constant;\n            Type expectedType = typeof(object);\n\n            // Act\n            ConstantExpressionFingerprint fingerprint = new ConstantExpressionFingerprint(expectedNodeType, expectedType);\n\n            // Assert\n            Assert.Equal(expectedNodeType, fingerprint.NodeType);\n            Assert.Equal(expectedType, fingerprint.Type);\n        }\n\n        [Fact]\n        public void Comparison_Equality()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Constant;\n            Type type = typeof(object);\n\n            // Act\n            ConstantExpressionFingerprint fingerprint1 = new ConstantExpressionFingerprint(nodeType, type);\n            ConstantExpressionFingerprint fingerprint2 = new ConstantExpressionFingerprint(nodeType, type);\n\n            // Assert\n            Assert.Equal(fingerprint1, fingerprint2);\n            Assert.Equal(fingerprint1.GetHashCode(), fingerprint2.GetHashCode());\n        }\n\n        [Fact]\n        public void Comparison_Inequality_FingerprintType()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Constant;\n            Type type = typeof(object);\n\n            // Act\n            ConstantExpressionFingerprint fingerprint1 = new ConstantExpressionFingerprint(nodeType, type);\n            DummyExpressionFingerprint fingerprint2 = new DummyExpressionFingerprint(nodeType, type);\n\n            // Assert\n            Assert.NotEqual<ExpressionFingerprint>(fingerprint1, fingerprint2);\n        }\n\n        [Fact]\n        public void Comparison_Inequality_Type()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Constant;\n            Type type = typeof(object);\n\n            // Act\n            ConstantExpressionFingerprint fingerprint1 = new ConstantExpressionFingerprint(nodeType, type);\n            ConstantExpressionFingerprint fingerprint2 = new ConstantExpressionFingerprint(nodeType, typeof(string));\n\n            // Assert\n            Assert.NotEqual(fingerprint1, fingerprint2);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/ExpressionUtil/Test/DefaultExpressionFingerprintTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq.Expressions;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.ExpressionUtil.Test\n{\n    public class DefaultExpressionFingerprintTest\n    {\n        [Fact]\n        public void Properties()\n        {\n            // Arrange\n            ExpressionType expectedNodeType = ExpressionType.Default;\n            Type expectedType = typeof(object);\n\n            // Act\n            DefaultExpressionFingerprint fingerprint = new DefaultExpressionFingerprint(expectedNodeType, expectedType);\n\n            // Assert\n            Assert.Equal(expectedNodeType, fingerprint.NodeType);\n            Assert.Equal(expectedType, fingerprint.Type);\n        }\n\n        [Fact]\n        public void Comparison_Equality()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Default;\n            Type type = typeof(object);\n\n            // Act\n            DefaultExpressionFingerprint fingerprint1 = new DefaultExpressionFingerprint(nodeType, type);\n            DefaultExpressionFingerprint fingerprint2 = new DefaultExpressionFingerprint(nodeType, type);\n\n            // Assert\n            Assert.Equal(fingerprint1, fingerprint2);\n            Assert.Equal(fingerprint1.GetHashCode(), fingerprint2.GetHashCode());\n        }\n\n        [Fact]\n        public void Comparison_Inequality_FingerprintType()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Default;\n            Type type = typeof(object);\n\n            // Act\n            DefaultExpressionFingerprint fingerprint1 = new DefaultExpressionFingerprint(nodeType, type);\n            DummyExpressionFingerprint fingerprint2 = new DummyExpressionFingerprint(nodeType, type);\n\n            // Assert\n            Assert.NotEqual<ExpressionFingerprint>(fingerprint1, fingerprint2);\n        }\n\n        [Fact]\n        public void Comparison_Inequality_NodeType()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Default;\n            Type type = typeof(object);\n\n            // Act\n            DefaultExpressionFingerprint fingerprint1 = new DefaultExpressionFingerprint(nodeType, type);\n            DefaultExpressionFingerprint fingerprint2 = new DefaultExpressionFingerprint(nodeType, typeof(string));\n\n            // Assert\n            Assert.NotEqual(fingerprint1, fingerprint2);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/ExpressionUtil/Test/DummyExpressionFingerprint.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq.Expressions;\n\nnamespace System.Web.Mvc.ExpressionUtil.Test\n{\n    // Represents an ExpressionFingerprint that is of the wrong type.\n    internal sealed class DummyExpressionFingerprint : ExpressionFingerprint\n    {\n        public DummyExpressionFingerprint(ExpressionType nodeType, Type type)\n            : base(nodeType, type)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/ExpressionUtil/Test/ExpressionFingerprintTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq.Expressions;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.ExpressionUtil.Test\n{\n    public class ExpressionFingerprintTest\n    {\n        [Fact]\n        public void Comparison_Equality()\n        {\n            // Act\n            DummyExpressionFingerprint fingerprint1 = new DummyExpressionFingerprint(ExpressionType.Default, typeof(object));\n            DummyExpressionFingerprint fingerprint2 = new DummyExpressionFingerprint(ExpressionType.Default, typeof(object));\n\n            // Assert\n            Assert.Equal(fingerprint1, fingerprint2);\n            Assert.Equal(fingerprint1.GetHashCode(), fingerprint2.GetHashCode());\n        }\n\n        [Fact]\n        public void Comparison_Inequality_NodeType()\n        {\n            // Act\n            DummyExpressionFingerprint fingerprint1 = new DummyExpressionFingerprint(ExpressionType.Default, typeof(object));\n            DummyExpressionFingerprint fingerprint2 = new DummyExpressionFingerprint(ExpressionType.Parameter, typeof(object));\n\n            // Assert\n            Assert.NotEqual(fingerprint1, fingerprint2);\n        }\n\n        [Fact]\n        public void Comparison_Inequality_Type()\n        {\n            // Act\n            DummyExpressionFingerprint fingerprint1 = new DummyExpressionFingerprint(ExpressionType.Default, typeof(object));\n            DummyExpressionFingerprint fingerprint2 = new DummyExpressionFingerprint(ExpressionType.Default, typeof(string));\n\n            // Assert\n            Assert.NotEqual(fingerprint1, fingerprint2);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/ExpressionUtil/Test/FingerprintingExpressionVisitorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Linq.Expressions;\nusing System.Reflection;\nusing System.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.ExpressionUtil.Test\n{\n    public class FingerprintingExpressionVisitorTest\n    {\n        private const ExpressionFingerprint _nullFingerprint = null;\n\n        [Fact]\n        public void TypeOverridesAllMethods()\n        {\n            // Ensures that the FingerprintingExpressionVisitor type overrides all VisitXxx methods so that\n            // it can properly set the \"I gave up\" flag when it encounters an Expression it's not familiar\n            // with.\n\n            var methodsOnExpressionVisitorRequiringOverride = typeof(ExpressionVisitor).GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance).Where(mi => mi.IsVirtual).Select(mi => mi.GetBaseDefinition()).Where(mi => mi.DeclaringType == typeof(ExpressionVisitor));\n            var methodsOnFingerprintingExpressionVisitor = typeof(FingerprintingExpressionVisitor).GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance).Where(mi => mi.DeclaringType == typeof(FingerprintingExpressionVisitor));\n\n            var missingMethods = methodsOnExpressionVisitorRequiringOverride.Except(methodsOnFingerprintingExpressionVisitor.Select(mi => mi.GetBaseDefinition())).ToArray();\n            if (missingMethods.Length != 0)\n            {\n                StringBuilder sb = new StringBuilder(\"The following methods are declared on ExpressionVisitor and must be overridden on FingerprintingExpressionVisitor:\");\n                foreach (MethodInfo method in missingMethods)\n                {\n                    sb.AppendLine();\n                    sb.Append(method);\n                }\n                Assert.True(false, sb.ToString());\n            }\n        }\n\n        [Fact]\n        public void Visit_Null()\n        {\n            // Arrange\n\n            // fingerprints as [ NULL ]\n            Expression expr = null;\n\n            // Act\n            List<object> capturedConstants;\n            ExpressionFingerprintChain fingerprint = FingerprintingExpressionVisitor.GetFingerprintChain(expr, out capturedConstants);\n\n            // Assert\n            Assert.Empty(capturedConstants);\n            AssertChainEquals(fingerprint, _nullFingerprint);\n        }\n\n        [Fact]\n        public void Visit_Unknown()\n        {\n            // Arrange\n\n            // if we fingerprinted ctors, would fingerprint as [ NEW(StringBuilder(int)):StringBuilder, PARAM(0):int ]\n            // but since we don't fingerprint ctors, should just return null (signaling failure)\n            Expression expr = (Expression<Func<int, StringBuilder>>)(capacity => new StringBuilder(capacity));\n\n            // Act\n            List<object> capturedConstants;\n            ExpressionFingerprintChain fingerprint = FingerprintingExpressionVisitor.GetFingerprintChain(expr, out capturedConstants);\n\n            // Assert\n            Assert.Null(fingerprint); // Can't fingerprint ctor\n            Assert.Null(capturedConstants); // Can't fingerprint ctor\n        }\n\n        [Fact]\n        public void VisitBinary()\n        {\n            // Arrange\n\n            // fingerprints as [ OP_GREATERTHAN:bool, CONST:int, CONST:int ]\n            Expression expr = Expression.MakeBinary(ExpressionType.GreaterThan, Expression.Constant(42), Expression.Constant(84));\n\n            // Act\n            List<object> capturedConstants;\n            ExpressionFingerprintChain fingerprint = FingerprintingExpressionVisitor.GetFingerprintChain(expr, out capturedConstants);\n\n            // Assert\n            Assert.Equal(new object[] { 42, 84 }, capturedConstants.ToArray());\n            AssertChainEquals(fingerprint,\n                              new BinaryExpressionFingerprint(ExpressionType.GreaterThan, typeof(bool), null /* method */),\n                              new ConstantExpressionFingerprint(ExpressionType.Constant, typeof(int)),\n                              new ConstantExpressionFingerprint(ExpressionType.Constant, typeof(int)));\n        }\n\n        [Fact]\n        public void VisitConditional()\n        {\n            // Arrange\n\n            // fingerprints as [ CONDITIONAL:int, CONST:bool, CONST:int, CONST:int ]\n            Expression expr = Expression.Condition(Expression.Constant(true), Expression.Constant(42), Expression.Constant(84));\n\n            // Act\n            List<object> capturedConstants;\n            ExpressionFingerprintChain fingerprint = FingerprintingExpressionVisitor.GetFingerprintChain(expr, out capturedConstants);\n\n            // Assert\n            Assert.Equal(new object[] { true, 42, 84 }, capturedConstants.ToArray());\n            AssertChainEquals(fingerprint,\n                              new ConditionalExpressionFingerprint(ExpressionType.Conditional, typeof(int)),\n                              new ConstantExpressionFingerprint(ExpressionType.Constant, typeof(bool)),\n                              new ConstantExpressionFingerprint(ExpressionType.Constant, typeof(int)),\n                              new ConstantExpressionFingerprint(ExpressionType.Constant, typeof(int)));\n        }\n\n        [Fact]\n        public void VisitConstant()\n        {\n            // Arrange\n\n            // fingerprints as [ CONST:int ]\n            Expression expr = Expression.Constant(42);\n\n            // Act\n            List<object> capturedConstants;\n            ExpressionFingerprintChain fingerprint = FingerprintingExpressionVisitor.GetFingerprintChain(expr, out capturedConstants);\n\n            // Assert\n            Assert.Equal(new object[] { 42 }, capturedConstants.ToArray());\n            AssertChainEquals(fingerprint,\n                              new ConstantExpressionFingerprint(ExpressionType.Constant, typeof(int)));\n        }\n\n        [Fact]\n        public void VisitDefault()\n        {\n            // Arrange\n\n            // fingerprints as [ DEFAULT:int ]\n            Expression expr = Expression.Default(typeof(int));\n\n            // Act\n            List<object> capturedConstants;\n            ExpressionFingerprintChain fingerprint = FingerprintingExpressionVisitor.GetFingerprintChain(expr, out capturedConstants);\n\n            // Assert\n            Assert.Empty(capturedConstants);\n            AssertChainEquals(fingerprint, new DefaultExpressionFingerprint(ExpressionType.Default, typeof(int)));\n        }\n\n        [Fact]\n        public void VisitIndex()\n        {\n            // Arrange\n\n            // fingerprints as [ INDEX:object, PARAM(0):object[], CONST:int ]\n            Expression expr = Expression.MakeIndex(Expression.Parameter(typeof(object[])), null /* indexer */, new Expression[] { Expression.Constant(42) });\n\n            // Act\n            List<object> capturedConstants;\n            ExpressionFingerprintChain fingerprint = FingerprintingExpressionVisitor.GetFingerprintChain(expr, out capturedConstants);\n\n            // Assert\n            Assert.Equal(new object[] { 42 }, capturedConstants.ToArray());\n            AssertChainEquals(fingerprint,\n                              new IndexExpressionFingerprint(ExpressionType.Index, typeof(object), null /* indexer */),\n                              new ParameterExpressionFingerprint(ExpressionType.Parameter, typeof(object[]), 0 /* parameterIndex */),\n                              new ConstantExpressionFingerprint(ExpressionType.Constant, typeof(int)));\n        }\n\n        [Fact]\n        public void VisitLambda()\n        {\n            // Arrange\n\n            // fingerprints as [ LAMBDA:Func<string, int>, CONST:int, PARAM(0):string ]\n            Expression expr = (Expression<Func<string, int>>)(x => 42);\n\n            // Act\n            List<object> capturedConstants;\n            ExpressionFingerprintChain fingerprint = FingerprintingExpressionVisitor.GetFingerprintChain(expr, out capturedConstants);\n\n            // Assert\n            Assert.Equal(new object[] { 42 }, capturedConstants.ToArray());\n            AssertChainEquals(fingerprint,\n                              new LambdaExpressionFingerprint(ExpressionType.Lambda, typeof(Func<string, int>)),\n                              new ConstantExpressionFingerprint(ExpressionType.Constant, typeof(int)),\n                              new ParameterExpressionFingerprint(ExpressionType.Parameter, typeof(string), 0 /* parameterIndex */));\n        }\n\n        [Fact]\n        public void VisitMember()\n        {\n            // Arrange\n\n            // fingerprints as [ MEMBER(String.Empty):string, NULL ]\n            Expression expr = Expression.Field(null, typeof(string), \"Empty\");\n\n            // Act\n            List<object> capturedConstants;\n            ExpressionFingerprintChain fingerprint = FingerprintingExpressionVisitor.GetFingerprintChain(expr, out capturedConstants);\n\n            // Assert\n            Assert.Empty(capturedConstants);\n            AssertChainEquals(fingerprint,\n                              new MemberExpressionFingerprint(ExpressionType.MemberAccess, typeof(string), typeof(string).GetField(\"Empty\")),\n                              _nullFingerprint);\n        }\n\n        [Fact]\n        public void VisitMethodCall()\n        {\n            // Arrange\n\n            // fingerprints as [ CALL(GC.KeepAlive):void, NULL, PARAM(0):object ]\n            Expression expr = Expression.Call(typeof(GC).GetMethod(\"KeepAlive\"), Expression.Parameter(typeof(object)));\n\n            // Act\n            List<object> capturedConstants;\n            ExpressionFingerprintChain fingerprint = FingerprintingExpressionVisitor.GetFingerprintChain(expr, out capturedConstants);\n\n            // Assert\n            Assert.Empty(capturedConstants);\n            AssertChainEquals(fingerprint,\n                              new MethodCallExpressionFingerprint(ExpressionType.Call, typeof(void), typeof(GC).GetMethod(\"KeepAlive\")),\n                              _nullFingerprint,\n                              new ParameterExpressionFingerprint(ExpressionType.Parameter, typeof(object), 0 /* parameterIndex */));\n        }\n\n        [Fact]\n        public void VisitParameter()\n        {\n            // Arrange\n\n            // fingerprints as [ LAMBDA:Func<int, int, int>, OP_ADD:int, OP_ADD:int, OP_ADD:int, PARAM(0):int, PARAM(0):int, PARAM(1):int, PARAM(0):int, PARAM(1):int, PARAM(0):int ]\n            // (note that the parameters are out of order since 'y' is used first, but this is ok due\n            // to preservation of alpha equivalence within the VisitParameter method.)\n            Expression expr = (Expression<Func<int, int, int>>)((x, y) => y + y + x + y);\n\n            // Act\n            List<object> capturedConstants;\n            ExpressionFingerprintChain fingerprint = FingerprintingExpressionVisitor.GetFingerprintChain(expr, out capturedConstants);\n\n            // Assert\n            Assert.Empty(capturedConstants);\n            AssertChainEquals(fingerprint,\n                              new LambdaExpressionFingerprint(ExpressionType.Lambda, typeof(Func<int, int, int>)),\n                              new BinaryExpressionFingerprint(ExpressionType.Add, typeof(int), null /* method */),\n                              new BinaryExpressionFingerprint(ExpressionType.Add, typeof(int), null /* method */),\n                              new BinaryExpressionFingerprint(ExpressionType.Add, typeof(int), null /* method */),\n                              new ParameterExpressionFingerprint(ExpressionType.Parameter, typeof(int), 0 /* parameterIndex */),\n                              new ParameterExpressionFingerprint(ExpressionType.Parameter, typeof(int), 0 /* parameterIndex */),\n                              new ParameterExpressionFingerprint(ExpressionType.Parameter, typeof(int), 1 /* parameterIndex */),\n                              new ParameterExpressionFingerprint(ExpressionType.Parameter, typeof(int), 0 /* parameterIndex */),\n                              new ParameterExpressionFingerprint(ExpressionType.Parameter, typeof(int), 1 /* parameterIndex */),\n                              new ParameterExpressionFingerprint(ExpressionType.Parameter, typeof(int), 0 /* parameterIndex */));\n        }\n\n        [Fact]\n        public void VisitTypeBinary()\n        {\n            // Arrange\n\n            // fingerprints as [ TYPEIS(DateTime):bool, CONST:string ]\n            Expression expr = Expression.TypeIs(Expression.Constant(\"hello\"), typeof(DateTime));\n\n            // Act\n            List<object> capturedConstants;\n            ExpressionFingerprintChain fingerprint = FingerprintingExpressionVisitor.GetFingerprintChain(expr, out capturedConstants);\n\n            // Assert\n            Assert.Equal(new object[] { \"hello\" }, capturedConstants.ToArray());\n            AssertChainEquals(fingerprint,\n                              new TypeBinaryExpressionFingerprint(ExpressionType.TypeIs, typeof(bool), typeof(DateTime)),\n                              new ConstantExpressionFingerprint(ExpressionType.Constant, typeof(string)));\n        }\n\n        [Fact]\n        public void VisitUnary()\n        {\n            // Arrange\n\n            // fingerprints as [ OP_NOT:int, PARAM:int ]\n            Expression expr = Expression.Not(Expression.Parameter(typeof(int)));\n\n            // Act\n            List<object> capturedConstants;\n            ExpressionFingerprintChain fingerprint = FingerprintingExpressionVisitor.GetFingerprintChain(expr, out capturedConstants);\n\n            // Assert\n            Assert.Empty(capturedConstants);\n            AssertChainEquals(fingerprint,\n                              new UnaryExpressionFingerprint(ExpressionType.Not, typeof(int), null /* method */),\n                              new ParameterExpressionFingerprint(ExpressionType.Parameter, typeof(int), 0 /* parameterIndex */));\n        }\n\n        internal static void AssertChainEquals(ExpressionFingerprintChain fingerprintChain, params ExpressionFingerprint[] expectedElements)\n        {\n            ExpressionFingerprintChain newChain = new ExpressionFingerprintChain();\n            newChain.Elements.AddRange(expectedElements);\n            Assert.Equal(fingerprintChain, newChain);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/ExpressionUtil/Test/HoistingExpressionVisitorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq.Expressions;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.ExpressionUtil.Test\n{\n    public class HoistingExpressionVisitorTest\n    {\n        [Fact]\n        public void Hoist()\n        {\n            // Arrange\n            Expression<Func<string, int>> expr = s => (2 * s.Length) + 1;\n\n            // Act\n            Expression<Hoisted<string, int>> hoisted = HoistingExpressionVisitor<string, int>.Hoist(expr);\n\n            // Assert\n            // new expression should be (s, capturedConstants) => (int)(capturedConstants[0]) * s.Length + (int)(capturedConstants[1])\n            // with fingerprint [ LAMBDA:Hoisted<string, int>, OP_ADD:int, OP_MULTIPLY:int, OP_CAST:int, INDEX(List<object>.get_Item):object, PARAM(0):List<object>, CONST:int, MEMBER(String.Length):int, PARAM(1):string, OP_CAST:int, INDEX(List<object>.get_Item):object, PARAM(0):List<object>, CONST:int, PARAM(1):string, PARAM(0):List<object> ]\n\n            List<object> capturedConstants;\n            ExpressionFingerprintChain fingerprint = FingerprintingExpressionVisitor.GetFingerprintChain(hoisted, out capturedConstants);\n\n            Assert.Equal(new object[] { 0, 1 }, capturedConstants.ToArray()); // these are constants from the hoisted expression (array indexes), not the original expression\n            FingerprintingExpressionVisitorTest.AssertChainEquals(\n                fingerprint,\n                new LambdaExpressionFingerprint(ExpressionType.Lambda, typeof(Hoisted<string, int>)),\n                new BinaryExpressionFingerprint(ExpressionType.Add, typeof(int), null /* method */),\n                new BinaryExpressionFingerprint(ExpressionType.Multiply, typeof(int), null /* method */),\n                new UnaryExpressionFingerprint(ExpressionType.Convert, typeof(int), null /* method */),\n                new IndexExpressionFingerprint(ExpressionType.Index, typeof(object), typeof(List<object>).GetProperty(\"Item\")),\n                new ParameterExpressionFingerprint(ExpressionType.Parameter, typeof(List<object>), 0 /* parameterIndex */),\n                new ConstantExpressionFingerprint(ExpressionType.Constant, typeof(int)),\n                new MemberExpressionFingerprint(ExpressionType.MemberAccess, typeof(int), typeof(string).GetProperty(\"Length\")),\n                new ParameterExpressionFingerprint(ExpressionType.Parameter, typeof(string), 1 /* parameterIndex */),\n                new UnaryExpressionFingerprint(ExpressionType.Convert, typeof(int), null /* method */),\n                new IndexExpressionFingerprint(ExpressionType.Index, typeof(object), typeof(List<object>).GetProperty(\"Item\")),\n                new ParameterExpressionFingerprint(ExpressionType.Parameter, typeof(List<object>), 0 /* parameterIndex */),\n                new ConstantExpressionFingerprint(ExpressionType.Constant, typeof(int)),\n                new ParameterExpressionFingerprint(ExpressionType.Parameter, typeof(string), 1 /* parameterIndex */),\n                new ParameterExpressionFingerprint(ExpressionType.Parameter, typeof(List<object>), 0 /* parameterIndex */));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/ExpressionUtil/Test/IndexExpressionFingerprintTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq.Expressions;\nusing System.Reflection;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.ExpressionUtil.Test\n{\n    public class IndexExpressionFingerprintTest\n    {\n        [Fact]\n        public void Properties()\n        {\n            // Arrange\n            ExpressionType expectedNodeType = ExpressionType.Index;\n            Type expectedType = typeof(char);\n            PropertyInfo expectedIndexer = typeof(string).GetProperty(\"Chars\");\n\n            // Act\n            IndexExpressionFingerprint fingerprint = new IndexExpressionFingerprint(expectedNodeType, expectedType, expectedIndexer);\n\n            // Assert\n            Assert.Equal(expectedNodeType, fingerprint.NodeType);\n            Assert.Equal(expectedType, fingerprint.Type);\n            Assert.Equal(expectedIndexer, fingerprint.Indexer);\n        }\n\n        [Fact]\n        public void Comparison_Equality()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Index;\n            Type type = typeof(char);\n            PropertyInfo indexer = typeof(string).GetProperty(\"Chars\");\n\n            // Act\n            IndexExpressionFingerprint fingerprint1 = new IndexExpressionFingerprint(nodeType, type, indexer);\n            IndexExpressionFingerprint fingerprint2 = new IndexExpressionFingerprint(nodeType, type, indexer);\n\n            // Assert\n            Assert.Equal(fingerprint1, fingerprint2);\n            Assert.Equal(fingerprint1.GetHashCode(), fingerprint2.GetHashCode());\n        }\n\n        [Fact]\n        public void Comparison_Inequality_FingerprintType()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Index;\n            Type type = typeof(char);\n            PropertyInfo indexer = typeof(string).GetProperty(\"Chars\");\n\n            // Act\n            IndexExpressionFingerprint fingerprint1 = new IndexExpressionFingerprint(nodeType, type, indexer);\n            DummyExpressionFingerprint fingerprint2 = new DummyExpressionFingerprint(nodeType, type);\n\n            // Assert\n            Assert.NotEqual<ExpressionFingerprint>(fingerprint1, fingerprint2);\n        }\n\n        [Fact]\n        public void Comparison_Inequality_Indexer()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Index;\n            Type type = typeof(char);\n            PropertyInfo indexer = typeof(string).GetProperty(\"Chars\");\n\n            // Act\n            IndexExpressionFingerprint fingerprint1 = new IndexExpressionFingerprint(nodeType, type, indexer);\n            IndexExpressionFingerprint fingerprint2 = new IndexExpressionFingerprint(nodeType, type, null /* indexer */);\n\n            // Assert\n            Assert.NotEqual(fingerprint1, fingerprint2);\n        }\n\n        [Fact]\n        public void Comparison_Inequality_Type()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Index;\n            Type type = typeof(char);\n            PropertyInfo indexer = typeof(string).GetProperty(\"Chars\");\n\n            // Act\n            IndexExpressionFingerprint fingerprint1 = new IndexExpressionFingerprint(nodeType, type, indexer);\n            IndexExpressionFingerprint fingerprint2 = new IndexExpressionFingerprint(nodeType, typeof(object), indexer);\n\n            // Assert\n            Assert.NotEqual(fingerprint1, fingerprint2);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/ExpressionUtil/Test/LambdaExpressionFingerprintTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq.Expressions;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.ExpressionUtil.Test\n{\n    public class LambdaExpressionFingerprintTest\n    {\n        [Fact]\n        public void Properties()\n        {\n            // Arrange\n            ExpressionType expectedNodeType = ExpressionType.Lambda;\n            Type expectedType = typeof(Action<object>);\n\n            // Act\n            LambdaExpressionFingerprint fingerprint = new LambdaExpressionFingerprint(expectedNodeType, expectedType);\n\n            // Assert\n            Assert.Equal(expectedNodeType, fingerprint.NodeType);\n            Assert.Equal(expectedType, fingerprint.Type);\n        }\n\n        [Fact]\n        public void Comparison_Equality()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Lambda;\n            Type type = typeof(Action<object>);\n\n            // Act\n            LambdaExpressionFingerprint fingerprint1 = new LambdaExpressionFingerprint(nodeType, type);\n            LambdaExpressionFingerprint fingerprint2 = new LambdaExpressionFingerprint(nodeType, type);\n\n            // Assert\n            Assert.Equal(fingerprint1, fingerprint2);\n            Assert.Equal(fingerprint1.GetHashCode(), fingerprint2.GetHashCode());\n        }\n\n        [Fact]\n        public void Comparison_Inequality_FingerprintType()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Lambda;\n            Type type = typeof(Action<object>);\n\n            // Act\n            LambdaExpressionFingerprint fingerprint1 = new LambdaExpressionFingerprint(nodeType, type);\n            DummyExpressionFingerprint fingerprint2 = new DummyExpressionFingerprint(nodeType, type);\n\n            // Assert\n            Assert.NotEqual<ExpressionFingerprint>(fingerprint1, fingerprint2);\n        }\n\n        [Fact]\n        public void Comparison_Inequality_NodeType()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Lambda;\n            Type type = typeof(Action<object>);\n\n            // Act\n            LambdaExpressionFingerprint fingerprint1 = new LambdaExpressionFingerprint(nodeType, type);\n            LambdaExpressionFingerprint fingerprint2 = new LambdaExpressionFingerprint(nodeType, typeof(Action));\n\n            // Assert\n            Assert.NotEqual(fingerprint1, fingerprint2);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/ExpressionUtil/Test/MemberExpressionFingerprintTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq.Expressions;\nusing System.Reflection;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.ExpressionUtil.Test\n{\n    public class MemberExpressionFingerprintTest\n    {\n        [Fact]\n        public void Properties()\n        {\n            // Arrange\n            ExpressionType expectedNodeType = ExpressionType.MemberAccess;\n            Type expectedType = typeof(int);\n            MemberInfo expectedMember = typeof(TimeSpan).GetProperty(\"Seconds\");\n\n            // Act\n            MemberExpressionFingerprint fingerprint = new MemberExpressionFingerprint(expectedNodeType, expectedType, expectedMember);\n\n            // Assert\n            Assert.Equal(expectedNodeType, fingerprint.NodeType);\n            Assert.Equal(expectedType, fingerprint.Type);\n            Assert.Equal(expectedMember, fingerprint.Member);\n        }\n\n        [Fact]\n        public void Comparison_Equality()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.MemberAccess;\n            Type type = typeof(int);\n            MemberInfo member = typeof(TimeSpan).GetProperty(\"Seconds\");\n\n            // Act\n            MemberExpressionFingerprint fingerprint1 = new MemberExpressionFingerprint(nodeType, type, member);\n            MemberExpressionFingerprint fingerprint2 = new MemberExpressionFingerprint(nodeType, type, member);\n\n            // Assert\n            Assert.Equal(fingerprint1, fingerprint2);\n            Assert.Equal(fingerprint1.GetHashCode(), fingerprint2.GetHashCode());\n        }\n\n        [Fact]\n        public void Comparison_Inequality_FingerprintType()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.MemberAccess;\n            Type type = typeof(int);\n            MemberInfo member = typeof(TimeSpan).GetProperty(\"Seconds\");\n\n            // Act\n            MemberExpressionFingerprint fingerprint1 = new MemberExpressionFingerprint(nodeType, type, member);\n            DummyExpressionFingerprint fingerprint2 = new DummyExpressionFingerprint(nodeType, type);\n\n            // Assert\n            Assert.NotEqual<ExpressionFingerprint>(fingerprint1, fingerprint2);\n        }\n\n        [Fact]\n        public void Comparison_Inequality_Member()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.MemberAccess;\n            Type type = typeof(int);\n            MemberInfo member = typeof(TimeSpan).GetProperty(\"Seconds\");\n\n            // Act\n            MemberExpressionFingerprint fingerprint1 = new MemberExpressionFingerprint(nodeType, type, member);\n            MemberExpressionFingerprint fingerprint2 = new MemberExpressionFingerprint(nodeType, type, null /* member */);\n\n            // Assert\n            Assert.NotEqual(fingerprint1, fingerprint2);\n        }\n\n        [Fact]\n        public void Comparison_Inequality_Type()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.MemberAccess;\n            Type type = typeof(int);\n            MemberInfo member = typeof(TimeSpan).GetProperty(\"Seconds\");\n\n            // Act\n            MemberExpressionFingerprint fingerprint1 = new MemberExpressionFingerprint(nodeType, type, member);\n            MemberExpressionFingerprint fingerprint2 = new MemberExpressionFingerprint(nodeType, typeof(object), member);\n\n            // Assert\n            Assert.NotEqual(fingerprint1, fingerprint2);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/ExpressionUtil/Test/MethodCallExpressionFingerprintTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq.Expressions;\nusing System.Reflection;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.ExpressionUtil.Test\n{\n    public class MethodCallExpressionFingerprintTest\n    {\n        [Fact]\n        public void Properties()\n        {\n            // Arrange\n            ExpressionType expectedNodeType = ExpressionType.Call;\n            Type expectedType = typeof(string);\n            MethodInfo expectedMethod = typeof(string).GetMethod(\"Intern\");\n\n            // Act\n            MethodCallExpressionFingerprint fingerprint = new MethodCallExpressionFingerprint(expectedNodeType, expectedType, expectedMethod);\n\n            // Assert\n            Assert.Equal(expectedNodeType, fingerprint.NodeType);\n            Assert.Equal(expectedType, fingerprint.Type);\n            Assert.Equal(expectedMethod, fingerprint.Method);\n        }\n\n        [Fact]\n        public void Comparison_Equality()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Call;\n            Type type = typeof(string);\n            MethodInfo method = typeof(string).GetMethod(\"Intern\");\n\n            // Act\n            MethodCallExpressionFingerprint fingerprint1 = new MethodCallExpressionFingerprint(nodeType, type, method);\n            MethodCallExpressionFingerprint fingerprint2 = new MethodCallExpressionFingerprint(nodeType, type, method);\n\n            // Assert\n            Assert.Equal(fingerprint1, fingerprint2);\n            Assert.Equal(fingerprint1.GetHashCode(), fingerprint2.GetHashCode());\n        }\n\n        [Fact]\n        public void Comparison_Inequality_FingerprintType()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Call;\n            Type type = typeof(string);\n            MethodInfo method = typeof(string).GetMethod(\"Intern\");\n\n            // Act\n            MethodCallExpressionFingerprint fingerprint1 = new MethodCallExpressionFingerprint(nodeType, type, method);\n            DummyExpressionFingerprint fingerprint2 = new DummyExpressionFingerprint(nodeType, type);\n\n            // Assert\n            Assert.NotEqual<ExpressionFingerprint>(fingerprint1, fingerprint2);\n        }\n\n        [Fact]\n        public void Comparison_Inequality_Method()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Call;\n            Type type = typeof(string);\n            MethodInfo method = typeof(string).GetMethod(\"Intern\");\n\n            // Act\n            MethodCallExpressionFingerprint fingerprint1 = new MethodCallExpressionFingerprint(nodeType, type, method);\n            MethodCallExpressionFingerprint fingerprint2 = new MethodCallExpressionFingerprint(nodeType, type, null /* method */);\n\n            // Assert\n            Assert.NotEqual(fingerprint1, fingerprint2);\n        }\n\n        [Fact]\n        public void Comparison_Inequality_Type()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Call;\n            Type type = typeof(string);\n            MethodInfo method = typeof(string).GetMethod(\"Intern\");\n\n            // Act\n            MethodCallExpressionFingerprint fingerprint1 = new MethodCallExpressionFingerprint(nodeType, type, method);\n            MethodCallExpressionFingerprint fingerprint2 = new MethodCallExpressionFingerprint(nodeType, typeof(object), method);\n\n            // Assert\n            Assert.NotEqual(fingerprint1, fingerprint2);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/ExpressionUtil/Test/ParameterExpressionFingerprintTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq.Expressions;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.ExpressionUtil.Test\n{\n    public class ParameterExpressionFingerprintTest\n    {\n        [Fact]\n        public void Properties()\n        {\n            // Arrange\n            ExpressionType expectedNodeType = ExpressionType.Parameter;\n            Type expectedType = typeof(object);\n            int expectedParameterIndex = 1;\n\n            // Act\n            ParameterExpressionFingerprint fingerprint = new ParameterExpressionFingerprint(expectedNodeType, expectedType, expectedParameterIndex);\n\n            // Assert\n            Assert.Equal(expectedNodeType, fingerprint.NodeType);\n            Assert.Equal(expectedType, fingerprint.Type);\n            Assert.Equal(expectedParameterIndex, fingerprint.ParameterIndex);\n        }\n\n        [Fact]\n        public void Comparison_Equality()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Parameter;\n            Type type = typeof(object);\n            int parameterIndex = 1;\n\n            // Act\n            ParameterExpressionFingerprint fingerprint1 = new ParameterExpressionFingerprint(nodeType, type, parameterIndex);\n            ParameterExpressionFingerprint fingerprint2 = new ParameterExpressionFingerprint(nodeType, type, parameterIndex);\n\n            // Assert\n            Assert.Equal(fingerprint1, fingerprint2);\n            Assert.Equal(fingerprint1.GetHashCode(), fingerprint2.GetHashCode());\n        }\n\n        [Fact]\n        public void Comparison_Inequality_FingerprintType()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Parameter;\n            Type type = typeof(object);\n            int parameterIndex = 1;\n\n            // Act\n            ParameterExpressionFingerprint fingerprint1 = new ParameterExpressionFingerprint(nodeType, type, parameterIndex);\n            DummyExpressionFingerprint fingerprint2 = new DummyExpressionFingerprint(nodeType, type);\n\n            // Assert\n            Assert.NotEqual<ExpressionFingerprint>(fingerprint1, fingerprint2);\n        }\n\n        [Fact]\n        public void Comparison_Inequality_Method()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Parameter;\n            Type type = typeof(object);\n            int parameterIndex = 1;\n\n            // Act\n            ParameterExpressionFingerprint fingerprint1 = new ParameterExpressionFingerprint(nodeType, type, parameterIndex);\n            ParameterExpressionFingerprint fingerprint2 = new ParameterExpressionFingerprint(nodeType, type, -1 /* parameterIndex */);\n\n            // Assert\n            Assert.NotEqual(fingerprint1, fingerprint2);\n        }\n\n        [Fact]\n        public void Comparison_Inequality_Type()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Parameter;\n            Type type = typeof(object);\n            int parameterIndex = 1;\n\n            // Act\n            ParameterExpressionFingerprint fingerprint1 = new ParameterExpressionFingerprint(nodeType, type, parameterIndex);\n            ParameterExpressionFingerprint fingerprint2 = new ParameterExpressionFingerprint(nodeType, typeof(string), parameterIndex);\n\n            // Assert\n            Assert.NotEqual(fingerprint1, fingerprint2);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/ExpressionUtil/Test/TypeBinaryExpressionFingerprintTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq.Expressions;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.ExpressionUtil.Test\n{\n    public class TypeBinaryExpressionFingerprintTest\n    {\n        [Fact]\n        public void Properties()\n        {\n            // Arrange\n            ExpressionType expectedNodeType = ExpressionType.TypeIs;\n            Type expectedType = typeof(bool);\n            Type expectedTypeOperand = typeof(object);\n\n            // Act\n            TypeBinaryExpressionFingerprint fingerprint = new TypeBinaryExpressionFingerprint(expectedNodeType, expectedType, expectedTypeOperand);\n\n            // Assert\n            Assert.Equal(expectedNodeType, fingerprint.NodeType);\n            Assert.Equal(expectedType, fingerprint.Type);\n            Assert.Equal(expectedTypeOperand, fingerprint.TypeOperand);\n        }\n\n        [Fact]\n        public void Comparison_Equality()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.TypeIs;\n            Type type = typeof(bool);\n            Type typeOperand = typeof(object);\n\n            // Act\n            TypeBinaryExpressionFingerprint fingerprint1 = new TypeBinaryExpressionFingerprint(nodeType, type, typeOperand);\n            TypeBinaryExpressionFingerprint fingerprint2 = new TypeBinaryExpressionFingerprint(nodeType, type, typeOperand);\n\n            // Assert\n            Assert.Equal(fingerprint1, fingerprint2);\n            Assert.Equal(fingerprint1.GetHashCode(), fingerprint2.GetHashCode());\n        }\n\n        [Fact]\n        public void Comparison_Inequality_FingerprintType()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.TypeIs;\n            Type type = typeof(bool);\n            Type typeOperand = typeof(object);\n\n            // Act\n            TypeBinaryExpressionFingerprint fingerprint1 = new TypeBinaryExpressionFingerprint(nodeType, type, typeOperand);\n            DummyExpressionFingerprint fingerprint2 = new DummyExpressionFingerprint(nodeType, type);\n\n            // Assert\n            Assert.NotEqual<ExpressionFingerprint>(fingerprint1, fingerprint2);\n        }\n\n        [Fact]\n        public void Comparison_Inequality_TypeOperand()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.TypeIs;\n            Type type = typeof(bool);\n            Type typeOperand = typeof(object);\n\n            // Act\n            TypeBinaryExpressionFingerprint fingerprint1 = new TypeBinaryExpressionFingerprint(nodeType, type, typeOperand);\n            TypeBinaryExpressionFingerprint fingerprint2 = new TypeBinaryExpressionFingerprint(nodeType, type, typeof(string) /* typeOperand */);\n\n            // Assert\n            Assert.NotEqual(fingerprint1, fingerprint2);\n        }\n\n        [Fact]\n        public void Comparison_Inequality_Type()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.TypeIs;\n            Type type = typeof(bool);\n            Type typeOperand = typeof(object);\n\n            // Act\n            TypeBinaryExpressionFingerprint fingerprint1 = new TypeBinaryExpressionFingerprint(nodeType, type, typeOperand);\n            TypeBinaryExpressionFingerprint fingerprint2 = new TypeBinaryExpressionFingerprint(nodeType, typeof(object), typeOperand);\n\n            // Assert\n            Assert.NotEqual(fingerprint1, fingerprint2);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/ExpressionUtil/Test/UnaryExpressionFingerprintTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq.Expressions;\nusing System.Reflection;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.ExpressionUtil.Test\n{\n    public class UnaryExpressionFingerprintTest\n    {\n        [Fact]\n        public void Properties()\n        {\n            // Arrange\n            ExpressionType expectedNodeType = ExpressionType.Not;\n            Type expectedType = typeof(int);\n            MethodInfo expectedMethod = typeof(object).GetMethod(\"GetHashCode\");\n\n            // Act\n            UnaryExpressionFingerprint fingerprint = new UnaryExpressionFingerprint(expectedNodeType, expectedType, expectedMethod);\n\n            // Assert\n            Assert.Equal(expectedNodeType, fingerprint.NodeType);\n            Assert.Equal(expectedType, fingerprint.Type);\n            Assert.Equal(expectedMethod, fingerprint.Method);\n        }\n\n        [Fact]\n        public void Comparison_Equality()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Not;\n            Type type = typeof(int);\n            MethodInfo method = typeof(object).GetMethod(\"GetHashCode\");\n\n            // Act\n            UnaryExpressionFingerprint fingerprint1 = new UnaryExpressionFingerprint(nodeType, type, method);\n            UnaryExpressionFingerprint fingerprint2 = new UnaryExpressionFingerprint(nodeType, type, method);\n\n            // Assert\n            Assert.Equal(fingerprint1, fingerprint2);\n            Assert.Equal(fingerprint1.GetHashCode(), fingerprint2.GetHashCode());\n        }\n\n        [Fact]\n        public void Comparison_Inequality_FingerprintType()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Not;\n            Type type = typeof(int);\n            MethodInfo method = typeof(object).GetMethod(\"GetHashCode\");\n\n            // Act\n            UnaryExpressionFingerprint fingerprint1 = new UnaryExpressionFingerprint(nodeType, type, method);\n            DummyExpressionFingerprint fingerprint2 = new DummyExpressionFingerprint(nodeType, type);\n\n            // Assert\n            Assert.NotEqual<ExpressionFingerprint>(fingerprint1, fingerprint2);\n        }\n\n        [Fact]\n        public void Comparison_Inequality_Method()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Not;\n            Type type = typeof(int);\n            MethodInfo method = typeof(object).GetMethod(\"GetHashCode\");\n\n            // Act\n            UnaryExpressionFingerprint fingerprint1 = new UnaryExpressionFingerprint(nodeType, type, method);\n            UnaryExpressionFingerprint fingerprint2 = new UnaryExpressionFingerprint(nodeType, type, null /* method */);\n\n            // Assert\n            Assert.NotEqual(fingerprint1, fingerprint2);\n        }\n\n        [Fact]\n        public void Comparison_Inequality_Type()\n        {\n            // Arrange\n            ExpressionType nodeType = ExpressionType.Not;\n            Type type = typeof(int);\n            MethodInfo method = typeof(object).GetMethod(\"GetHashCode\");\n\n            // Act\n            UnaryExpressionFingerprint fingerprint1 = new UnaryExpressionFingerprint(nodeType, type, method);\n            UnaryExpressionFingerprint fingerprint2 = new UnaryExpressionFingerprint(nodeType, typeof(object), method);\n\n            // Assert\n            Assert.NotEqual(fingerprint1, fingerprint2);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Html/Test/ChildActionExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Web.Mvc.Properties;\nusing System.Web.Mvc.Routing;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Html.Test\n{\n    public class ChildActionExtensionsTest\n    {\n        private Mock<HtmlHelper> _htmlHelper;\n        private Mock<HttpContextBase> _httpContext;\n        private Mock<RouteBase> _route;\n        private Mock<IViewDataContainer> _viewDataContainer;\n         \n        private RouteData _originalRouteData;\n        private RouteCollection _routes;\n        private ViewContext _viewContext;\n        private VirtualPathData _virtualPathData;\n\n        public ChildActionExtensionsTest()\n        {\n            _route = new Mock<RouteBase>();\n            _route.Setup(r => r.GetVirtualPath(It.IsAny<RequestContext>(), It.IsAny<RouteValueDictionary>()))\n                .Returns(() => _virtualPathData);\n\n            _virtualPathData = new VirtualPathData(_route.Object, \"~/VirtualPath\");\n\n            _routes = new RouteCollection();\n            _routes.Add(_route.Object);\n\n            _originalRouteData = new RouteData();\n\n            string returnValue = \"\";\n            _httpContext = new Mock<HttpContextBase>();\n            _httpContext.Setup(hc => hc.Request.ApplicationPath).Returns(\"~\");\n            _httpContext.Setup(hc => hc.Response.ApplyAppPathModifier(It.IsAny<string>()))\n                .Callback<string>(s => returnValue = s)\n                .Returns(() => returnValue);\n            _httpContext.Setup(hc => hc.Server.Execute(It.IsAny<IHttpHandler>(), It.IsAny<TextWriter>(), It.IsAny<bool>()));\n\n            _viewContext = new ViewContext\n            {\n                RequestContext = new RequestContext(_httpContext.Object, _originalRouteData)\n            };\n\n            _viewDataContainer = new Mock<IViewDataContainer>();\n\n            _htmlHelper = new Mock<HtmlHelper>(_viewContext, _viewDataContainer.Object, _routes);\n        }\n\n        [Fact]\n        public void GuardClauses()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => ChildActionExtensions.ActionHelper(null /* htmlHelper */, \"abc\", null /* controllerName */, null /* routeValues */, null /* textWriter */),\n                \"htmlHelper\"\n                );\n\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => ChildActionExtensions.ActionHelper(_htmlHelper.Object, null /* actionName */, null /* controllerName */, null /* routeValues */, null /* textWriter */),\n                \"actionName\"\n                );\n\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => ChildActionExtensions.ActionHelper(_htmlHelper.Object, String.Empty /* actionName */, null /* controllerName */, null /* routeValues */, null /* textWriter */),\n                \"actionName\"\n                );\n        }\n\n        [Fact]\n        public void ServerExecuteCalledWithWrappedChildActionMvcHandler()\n        {\n            // Arrange\n            IHttpHandler callbackHandler = null;\n            TextWriter callbackTextWriter = null;\n            bool callbackPreserveForm = false;\n            _httpContext.Setup(hc => hc.Server.Execute(It.IsAny<IHttpHandler>(), It.IsAny<TextWriter>(), It.IsAny<bool>()))\n                .Callback<IHttpHandler, TextWriter, bool>(\n                    (handler, textWriter, preserveForm) =>\n                    {\n                        callbackHandler = handler;\n                        callbackTextWriter = textWriter;\n                        callbackPreserveForm = preserveForm;\n                    });\n            TextWriter stringWriter = new StringWriter();\n\n            // Act\n            ChildActionExtensions.ActionHelper(_htmlHelper.Object, \"actionName\", null /* controllerName */, null /* routeValues */, stringWriter);\n\n            // Assert\n            Assert.NotNull(callbackHandler);\n            HttpHandlerUtil.ServerExecuteHttpHandlerWrapper wrapper = callbackHandler as HttpHandlerUtil.ServerExecuteHttpHandlerWrapper;\n            Assert.NotNull(wrapper);\n            Assert.NotNull(wrapper.InnerHandler);\n            ChildActionExtensions.ChildActionMvcHandler childHandler = wrapper.InnerHandler as ChildActionExtensions.ChildActionMvcHandler;\n            Assert.NotNull(childHandler);\n            Assert.Same(stringWriter, callbackTextWriter);\n            Assert.True(callbackPreserveForm);\n        }\n\n        [Fact]\n        public void RouteDataTokensIncludesParentActionViewContext()\n        {\n            // Arrange\n            MvcHandler mvcHandler = null;\n            _httpContext.Setup(hc => hc.Server.Execute(It.IsAny<IHttpHandler>(), It.IsAny<TextWriter>(), It.IsAny<bool>()))\n                .Callback<IHttpHandler, TextWriter, bool>((handler, _, __) => mvcHandler = (MvcHandler)((HttpHandlerUtil.ServerExecuteHttpHandlerWrapper)handler).InnerHandler);\n\n            // Act\n            ChildActionExtensions.ActionHelper(_htmlHelper.Object, \"actionName\", null /* controllerName */, null /* routeValues */, null /* textWriter */);\n\n            // Assert\n            Assert.Same(_viewContext, mvcHandler.RequestContext.RouteData.DataTokens[ControllerContext.ParentActionViewContextToken]);\n        }\n\n        [Fact]\n        public void RouteValuesIncludeNewActionName()\n        {\n            // Arrange\n            MvcHandler mvcHandler = null;\n            _httpContext.Setup(hc => hc.Server.Execute(It.IsAny<IHttpHandler>(), It.IsAny<TextWriter>(), It.IsAny<bool>()))\n                .Callback<IHttpHandler, TextWriter, bool>((handler, _, __) => mvcHandler = (MvcHandler)((HttpHandlerUtil.ServerExecuteHttpHandlerWrapper)handler).InnerHandler);\n\n            // Act\n            ChildActionExtensions.ActionHelper(_htmlHelper.Object, \"actionName\", null /* controllerName */, null /* routeValues */, null /* textWriter */);\n\n            // Assert\n            RouteData routeData = mvcHandler.RequestContext.RouteData;\n            Assert.Equal(\"actionName\", routeData.Values[\"action\"]);\n        }\n\n        [Fact]\n        public void RouteValuesIncludeOldControllerNameWhenControllerNameIsNullOrEmpty()\n        {\n            // Arrange\n            _originalRouteData.Values[\"controller\"] = \"oldController\";\n            MvcHandler mvcHandler = null;\n            _httpContext.Setup(hc => hc.Server.Execute(It.IsAny<IHttpHandler>(), It.IsAny<TextWriter>(), It.IsAny<bool>()))\n                .Callback<IHttpHandler, TextWriter, bool>((handler, _, __) => mvcHandler = (MvcHandler)((HttpHandlerUtil.ServerExecuteHttpHandlerWrapper)handler).InnerHandler);\n\n            // Act\n            ChildActionExtensions.ActionHelper(_htmlHelper.Object, \"actionName\", null /* controllerName */, null /* routeValues */, null /* textWriter */);\n\n            // Assert\n            RouteData routeData = mvcHandler.RequestContext.RouteData;\n            Assert.Equal(\"oldController\", routeData.Values[\"controller\"]);\n        }\n\n        [Fact]\n        public void RouteValuesIncludeNewControllerNameWhenControllNameIsNotEmpty()\n        {\n            // Arrange\n            _originalRouteData.Values[\"controller\"] = \"oldController\";\n            MvcHandler mvcHandler = null;\n            _httpContext.Setup(hc => hc.Server.Execute(It.IsAny<IHttpHandler>(), It.IsAny<TextWriter>(), It.IsAny<bool>()))\n                .Callback<IHttpHandler, TextWriter, bool>((handler, _, __) => mvcHandler = (MvcHandler)((HttpHandlerUtil.ServerExecuteHttpHandlerWrapper)handler).InnerHandler);\n\n            // Act\n            ChildActionExtensions.ActionHelper(_htmlHelper.Object, \"actionName\", \"newController\", null /* routeValues */, null /* textWriter */);\n\n            // Assert\n            RouteData routeData = mvcHandler.RequestContext.RouteData;\n            Assert.Equal(\"newController\", routeData.Values[\"controller\"]);\n        }\n\n        [Fact]\n        public void PassedRouteValuesOverrideParentRequestRouteValues()\n        {\n            // Arrange\n            _originalRouteData.Values[\"name1\"] = \"value1\";\n            _originalRouteData.Values[\"name2\"] = \"value2\";\n            MvcHandler mvcHandler = null;\n            _httpContext.Setup(hc => hc.Server.Execute(It.IsAny<IHttpHandler>(), It.IsAny<TextWriter>(), It.IsAny<bool>()))\n                .Callback<IHttpHandler, TextWriter, bool>((handler, _, __) => mvcHandler = (MvcHandler)((HttpHandlerUtil.ServerExecuteHttpHandlerWrapper)handler).InnerHandler);\n\n            // Act\n            ChildActionExtensions.ActionHelper(_htmlHelper.Object, \"actionName\", null /* controllerName */, new RouteValueDictionary { { \"name2\", \"newValue2\" } }, null /* textWriter */);\n\n            // Assert\n            RouteData routeData = mvcHandler.RequestContext.RouteData;\n            Assert.Equal(\"value1\", routeData.Values[\"name1\"]);\n            Assert.Equal(\"newValue2\", routeData.Values[\"name2\"]);\n\n            Assert.Equal(\"newValue2\", (routeData.Values[ChildActionValueProvider.ChildActionValuesKey] as DictionaryValueProvider<object>).GetValue(\"name2\").RawValue);\n        }\n\n        [Fact]\n        public void NoChildActionValuesDictionaryCreatedIfNoRouteValuesPassed()\n        {\n            // Arrange\n            MvcHandler mvcHandler = null;\n            _httpContext.Setup(hc => hc.Server.Execute(It.IsAny<IHttpHandler>(), It.IsAny<TextWriter>(), It.IsAny<bool>()))\n                .Callback<IHttpHandler, TextWriter, bool>((handler, _, __) => mvcHandler = (MvcHandler)((HttpHandlerUtil.ServerExecuteHttpHandlerWrapper)handler).InnerHandler);\n\n            // Act\n            ChildActionExtensions.ActionHelper(_htmlHelper.Object, \"actionName\", null /* controllerName */, null, null /* textWriter */);\n\n            // Assert\n            RouteData routeData = mvcHandler.RequestContext.RouteData;\n            Assert.Null(routeData.Values[ChildActionValueProvider.ChildActionValuesKey]);\n        }\n\n        [Fact]\n        public void RouteValuesDoesNotIncludeExplicitlyPassedAreaName()\n        {\n            // Arrange\n            Route route = _routes.MapRoute(\"my-area\", \"my-area\");\n            route.DataTokens[\"area\"] = \"myArea\";\n            MvcHandler mvcHandler = null;\n            _httpContext.Setup(hc => hc.Server.Execute(It.IsAny<IHttpHandler>(), It.IsAny<TextWriter>(), It.IsAny<bool>()))\n                .Callback<IHttpHandler, TextWriter, bool>((handler, _, __) => mvcHandler = (MvcHandler)((HttpHandlerUtil.ServerExecuteHttpHandlerWrapper)handler).InnerHandler);\n\n            // Act\n            ChildActionExtensions.ActionHelper(_htmlHelper.Object, \"actionName\", null /* controllerName */, new RouteValueDictionary { { \"area\", \"myArea\" } }, null /* textWriter */);\n\n            // Assert\n            RouteData routeData = mvcHandler.RequestContext.RouteData;\n            Assert.False(routeData.Values.ContainsKey(\"area\"));\n            Assert.Null((routeData.Values[ChildActionValueProvider.ChildActionValuesKey] as DictionaryValueProvider<object>).GetValue(\"area\"));\n        }\n\n        [Fact]\n        public void RouteValuesIncludeExplicitlyPassedAreaNameIfAreasNotInUse()\n        {\n            // Arrange\n            Route route = _routes.MapRoute(\"my-area\", \"my-area\");\n            MvcHandler mvcHandler = null;\n            _httpContext.Setup(hc => hc.Server.Execute(It.IsAny<IHttpHandler>(), It.IsAny<TextWriter>(), It.IsAny<bool>()))\n                .Callback<IHttpHandler, TextWriter, bool>((handler, _, __) => mvcHandler = (MvcHandler)((HttpHandlerUtil.ServerExecuteHttpHandlerWrapper)handler).InnerHandler);\n\n            // Act\n            ChildActionExtensions.ActionHelper(_htmlHelper.Object, \"actionName\", null /* controllerName */, new RouteValueDictionary { { \"area\", \"myArea\" } }, null /* textWriter */);\n\n            // Assert\n            RouteData routeData = mvcHandler.RequestContext.RouteData;\n            Assert.True(routeData.Values.ContainsKey(\"area\"));\n            Assert.Equal(\"myArea\", (routeData.Values[ChildActionValueProvider.ChildActionValuesKey] as DictionaryValueProvider<object>).GetValue(\"area\").RawValue);\n        }\n\n        [Fact]\n        public void NoMatchingRouteThrows()\n        {\n            // Arrange\n            _routes.Clear();\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => ChildActionExtensions.ActionHelper(_htmlHelper.Object, \"actionName\", null /* controllerName */, null /* routeValues */, null /* textWriter */),\n                MvcResources.Common_NoRouteMatched\n                );\n        }\n\n        [Fact]\n        public void ActionHelper_ChildAction_WithControllerDirectRoute()\n        {\n            // Arrange\n            AttributeRoutingMapper.MapAttributeRoutes(_routes, new Type[] { typeof(DirectRouteController) });\n            \n            MvcHandler mvcHandler = null;\n            _httpContext.Setup(hc => hc.Server.Execute(It.IsAny<IHttpHandler>(), It.IsAny<TextWriter>(), It.IsAny<bool>()))\n                .Callback<IHttpHandler, TextWriter, bool>((handler, _, __) => mvcHandler = (MvcHandler)((HttpHandlerUtil.ServerExecuteHttpHandlerWrapper)handler).InnerHandler);\n\n            // Act\n            ChildActionExtensions.ActionHelper(_htmlHelper.Object, \"Action\", null /* controllerName */, null /* routeValues */, null /* textWriter */);\n\n            // Assert\n            RouteData routeData = mvcHandler.RequestContext.RouteData;\n            Assert.Equal(\"Action\", routeData.Values[\"action\"]);\n        }\n\n        [Fact]\n        public void ActionHelper_ChildAction_WithActionDirectRoute()\n        {\n            // Arrange\n            AttributeRoutingMapper.MapAttributeRoutes(_routes, new Type[] { typeof(DirectRouteActionController) });\n\n            MvcHandler mvcHandler = null;\n            _httpContext.Setup(hc => hc.Server.Execute(It.IsAny<IHttpHandler>(), It.IsAny<TextWriter>(), It.IsAny<bool>()))\n                .Callback<IHttpHandler, TextWriter, bool>((handler, _, __) => mvcHandler = (MvcHandler)((HttpHandlerUtil.ServerExecuteHttpHandlerWrapper)handler).InnerHandler);\n\n            // Act\n            ChildActionExtensions.ActionHelper(_htmlHelper.Object, \"Action\", null /* controllerName */, null /* routeValues */, null /* textWriter */);\n\n            // Assert\n            RouteData routeData = mvcHandler.RequestContext.RouteData;\n            Assert.Equal(\"Action\", routeData.Values[\"action\"]);\n        }\n\n        [Route(\"controller/{action}\")]\n        private class DirectRouteController : Controller\n        {\n            public void Action()\n            {\n            }\n        }\n        \n        private class DirectRouteActionController : Controller\n        {\n            [Route(\"controller/Action\")]\n            public void Action()\n            {\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Html/Test/DefaultDisplayTemplatesTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Data.Objects.DataClasses;\nusing System.Globalization;\nusing System.IO;\nusing System.Web.UI.WebControls;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\nusing Moq;\n\nnamespace System.Web.Mvc.Html.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")] // Uses ModelMetadataProviders.Current\n    public class DefaultDisplayTemplatesTest\n    {\n        // BooleanTemplate\n\n        [Fact]\n        public void BooleanTemplateTests()\n        {\n            // Boolean values\n\n            Assert.Equal(\n                \"<input checked=\\\"checked\\\" class=\\\"check-box\\\" disabled=\\\"disabled\\\" type=\\\"checkbox\\\" />\",\n                DefaultDisplayTemplates.BooleanTemplate(MakeHtmlHelper<bool>(true)));\n\n            Assert.Equal(\n                \"<input class=\\\"check-box\\\" disabled=\\\"disabled\\\" type=\\\"checkbox\\\" />\",\n                DefaultDisplayTemplates.BooleanTemplate(MakeHtmlHelper<bool>(false)));\n\n            Assert.Equal(\n                \"<input class=\\\"check-box\\\" disabled=\\\"disabled\\\" type=\\\"checkbox\\\" />\",\n                DefaultDisplayTemplates.BooleanTemplate(MakeHtmlHelper<bool>(null)));\n\n            // Nullable<Boolean> values\n\n            Assert.Equal(\n                \"<select class=\\\"tri-state list-box\\\" disabled=\\\"disabled\\\"><option value=\\\"\\\">Not Set</option><option selected=\\\"selected\\\" value=\\\"true\\\">True</option><option value=\\\"false\\\">False</option></select>\",\n                DefaultDisplayTemplates.BooleanTemplate(MakeHtmlHelper<Nullable<bool>>(true)));\n\n            Assert.Equal(\n                \"<select class=\\\"tri-state list-box\\\" disabled=\\\"disabled\\\"><option value=\\\"\\\">Not Set</option><option value=\\\"true\\\">True</option><option selected=\\\"selected\\\" value=\\\"false\\\">False</option></select>\",\n                DefaultDisplayTemplates.BooleanTemplate(MakeHtmlHelper<Nullable<bool>>(false)));\n\n            Assert.Equal(\n                \"<select class=\\\"tri-state list-box\\\" disabled=\\\"disabled\\\"><option selected=\\\"selected\\\" value=\\\"\\\">Not Set</option><option value=\\\"true\\\">True</option><option value=\\\"false\\\">False</option></select>\",\n                DefaultDisplayTemplates.BooleanTemplate(MakeHtmlHelper<Nullable<bool>>(null)));\n        }\n\n        // CollectionTemplate\n\n        private static string CollectionSpyCallback(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string templateName, DataBoundControlMode mode, object additionalViewData)\n        {\n            return String.Format(CultureInfo.InvariantCulture,\n                                 Environment.NewLine + \"Model = {0}, ModelType = {1}, PropertyName = {2}, HtmlFieldName = {3}, TemplateName = {4}, Mode = {5}, TemplateInfo.HtmlFieldPrefix = {6}, AdditionalViewData = {7}\",\n                                 metadata.Model ?? \"(null)\",\n                                 metadata.ModelType == null ? \"(null)\" : metadata.ModelType.FullName,\n                                 metadata.PropertyName ?? \"(null)\",\n                                 htmlFieldName == String.Empty ? \"(empty)\" : htmlFieldName ?? \"(null)\",\n                                 templateName ?? \"(null)\",\n                                 mode,\n                                 html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix,\n                                 AnonymousObject.Inspect(additionalViewData));\n        }\n\n        [Fact]\n        public void CollectionTemplateWithNullModel()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper<object>(null);\n\n            // Act\n            string result = DefaultDisplayTemplates.CollectionTemplate(html, CollectionSpyCallback);\n\n            // Assert\n            Assert.Equal(String.Empty, result);\n        }\n\n        [Fact]\n        public void CollectionTemplateNonEnumerableModelThrows()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper<object>(new object());\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => DefaultDisplayTemplates.CollectionTemplate(html, CollectionSpyCallback),\n                \"The Collection template was used with an object of type 'System.Object', which does not implement System.IEnumerable.\"\n                );\n        }\n\n        [Fact]\n        public void CollectionTemplateWithSingleItemCollectionWithoutPrefix()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper<List<string>>(new List<string> { \"foo\" });\n            html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = null;\n\n            // Act\n            string result = DefaultDisplayTemplates.CollectionTemplate(html, CollectionSpyCallback);\n\n            // Assert\n            Assert.Equal(\n                Environment.NewLine\n              + \"Model = foo, ModelType = System.String, PropertyName = (null), HtmlFieldName = [0], TemplateName = (null), Mode = ReadOnly, TemplateInfo.HtmlFieldPrefix = , AdditionalViewData = (null)\",\n                result);\n        }\n\n        [Fact]\n        public void CollectionTemplateWithSingleItemCollectionWithPrefix()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper<List<string>>(new List<string> { \"foo\" });\n            html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"ModelProperty\";\n\n            // Act\n            string result = DefaultDisplayTemplates.CollectionTemplate(html, CollectionSpyCallback);\n\n            // Assert\n            Assert.Equal(\n                Environment.NewLine\n              + \"Model = foo, ModelType = System.String, PropertyName = (null), HtmlFieldName = ModelProperty[0], TemplateName = (null), Mode = ReadOnly, TemplateInfo.HtmlFieldPrefix = , AdditionalViewData = (null)\",\n                result);\n        }\n\n        [Fact]\n        public void CollectionTemplateWithMultiItemCollection()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper<List<string>>(new List<string> { \"foo\", \"bar\", \"baz\" });\n            html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = null;\n\n            // Act\n            string result = DefaultDisplayTemplates.CollectionTemplate(html, CollectionSpyCallback);\n\n            // Assert\n            Assert.Equal(\n                Environment.NewLine\n              + \"Model = foo, ModelType = System.String, PropertyName = (null), HtmlFieldName = [0], TemplateName = (null), Mode = ReadOnly, TemplateInfo.HtmlFieldPrefix = , AdditionalViewData = (null)\" + Environment.NewLine\n              + \"Model = bar, ModelType = System.String, PropertyName = (null), HtmlFieldName = [1], TemplateName = (null), Mode = ReadOnly, TemplateInfo.HtmlFieldPrefix = , AdditionalViewData = (null)\" + Environment.NewLine\n              + \"Model = baz, ModelType = System.String, PropertyName = (null), HtmlFieldName = [2], TemplateName = (null), Mode = ReadOnly, TemplateInfo.HtmlFieldPrefix = , AdditionalViewData = (null)\",\n                result);\n        }\n\n        [Fact]\n        public void CollectionTemplateNullITemInWeaklyTypedCollectionUsesModelTypeOfString()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper<ArrayList>(new ArrayList { null });\n            html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = null;\n\n            // Act\n            string result = DefaultDisplayTemplates.CollectionTemplate(html, CollectionSpyCallback);\n\n            // Assert\n            Assert.Equal(\n                Environment.NewLine\n              + \"Model = (null), ModelType = System.String, PropertyName = (null), HtmlFieldName = [0], TemplateName = (null), Mode = ReadOnly, TemplateInfo.HtmlFieldPrefix = , AdditionalViewData = (null)\",\n                result);\n        }\n\n        [Fact]\n        public void CollectionTemplateNullItemInStronglyTypedCollectionUsesModelTypeFromIEnumerable()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper<List<IHttpHandler>>(new List<IHttpHandler> { null });\n            html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = null;\n\n            // Act\n            string result = DefaultDisplayTemplates.CollectionTemplate(html, CollectionSpyCallback);\n\n            // Assert\n            Assert.Equal(\n                Environment.NewLine\n              + \"Model = (null), ModelType = System.Web.IHttpHandler, PropertyName = (null), HtmlFieldName = [0], TemplateName = (null), Mode = ReadOnly, TemplateInfo.HtmlFieldPrefix = , AdditionalViewData = (null)\",\n                result);\n        }\n\n        [Fact]\n        public void CollectionTemplateUsesRealObjectTypes()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper<List<object>>(new List<object> { 1, 2.3, \"Hello World\" });\n            html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = null;\n\n            // Act\n            string result = DefaultDisplayTemplates.CollectionTemplate(html, CollectionSpyCallback);\n\n            // Assert\n            Assert.Equal(\n                Environment.NewLine\n              + \"Model = 1, ModelType = System.Int32, PropertyName = (null), HtmlFieldName = [0], TemplateName = (null), Mode = ReadOnly, TemplateInfo.HtmlFieldPrefix = , AdditionalViewData = (null)\" + Environment.NewLine\n              + \"Model = 2.3, ModelType = System.Double, PropertyName = (null), HtmlFieldName = [1], TemplateName = (null), Mode = ReadOnly, TemplateInfo.HtmlFieldPrefix = , AdditionalViewData = (null)\" + Environment.NewLine\n              + \"Model = Hello World, ModelType = System.String, PropertyName = (null), HtmlFieldName = [2], TemplateName = (null), Mode = ReadOnly, TemplateInfo.HtmlFieldPrefix = , AdditionalViewData = (null)\",\n                result);\n        }\n\n        [Fact]\n        public void CollectionTemplateNullItemInCollectionOfNullableValueTypesDoesNotDiscardNullable()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper<List<int?>>(new List<int?> { 1, null, 2 });\n            html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = null;\n\n            // Act\n            string result = DefaultDisplayTemplates.CollectionTemplate(html, CollectionSpyCallback);\n\n            // Assert\n            Assert.Equal(\n                Environment.NewLine\n              + \"Model = 1, ModelType = System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], PropertyName = (null), HtmlFieldName = [0], TemplateName = (null), Mode = ReadOnly, TemplateInfo.HtmlFieldPrefix = , AdditionalViewData = (null)\" + Environment.NewLine\n              + \"Model = (null), ModelType = System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], PropertyName = (null), HtmlFieldName = [1], TemplateName = (null), Mode = ReadOnly, TemplateInfo.HtmlFieldPrefix = , AdditionalViewData = (null)\" + Environment.NewLine\n              + \"Model = 2, ModelType = System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], PropertyName = (null), HtmlFieldName = [2], TemplateName = (null), Mode = ReadOnly, TemplateInfo.HtmlFieldPrefix = , AdditionalViewData = (null)\",\n                result);\n        }\n\n        // DecimalTemplate\n\n        [Fact]\n        public void DecimalTemplateTests()\n        {\n            Assert.Equal(\n                String.Format(CultureInfo.CurrentCulture, \"{0:0.00}\", 12.35M),\n                DefaultDisplayTemplates.DecimalTemplate(MakeHtmlHelper<decimal>(12.3456M)));\n\n            Assert.Equal(\n                \"Formatted Value\",\n                DefaultDisplayTemplates.DecimalTemplate(MakeHtmlHelper<decimal>(12.3456M, \"Formatted Value\")));\n\n            Assert.Equal(\n                \"&lt;script&gt;alert(&#39;XSS!&#39;)&lt;/script&gt;\",\n                DefaultDisplayTemplates.DecimalTemplate(MakeHtmlHelper<decimal>(12.3456M, \"<script>alert('XSS!')</script>\")));\n        }\n\n        // EmailAddressTemplate\n\n        [Fact]\n        public void EmailAddressTemplateTests()\n        {\n            Assert.Equal(\n                \"<a href=\\\"mailto:foo@bar.com\\\">foo@bar.com</a>\",\n                DefaultDisplayTemplates.EmailAddressTemplate(MakeHtmlHelper<string>(\"foo@bar.com\")));\n\n            Assert.Equal(\n                \"<a href=\\\"mailto:foo@bar.com\\\">The FooBar User</a>\",\n                DefaultDisplayTemplates.EmailAddressTemplate(MakeHtmlHelper<string>(\"foo@bar.com\", \"The FooBar User\")));\n\n            Assert.Equal(\n                \"<a href=\\\"mailto:&lt;script>alert(&#39;XSS!&#39;)&lt;/script>\\\">&lt;script&gt;alert(&#39;XSS!&#39;)&lt;/script&gt;</a>\",\n                DefaultDisplayTemplates.EmailAddressTemplate(MakeHtmlHelper<string>(\"<script>alert('XSS!')</script>\")));\n\n            Assert.Equal(\n                \"<a href=\\\"mailto:&lt;script>alert(&#39;XSS!&#39;)&lt;/script>\\\">&lt;b&gt;Encode me!&lt;/b&gt;</a>\",\n                DefaultDisplayTemplates.EmailAddressTemplate(MakeHtmlHelper<string>(\"<script>alert('XSS!')</script>\", \"<b>Encode me!</b>\")));\n        }\n\n        // HiddenInputTemplate\n\n        [Fact]\n        public void HiddenInputTemplateTests()\n        {\n            Assert.Equal(\n                \"Hidden Value\",\n                DefaultDisplayTemplates.HiddenInputTemplate(MakeHtmlHelper<string>(\"Hidden Value\")));\n\n            Assert.Equal(\n                \"&lt;b&gt;Encode me!&lt;/b&gt;\",\n                DefaultDisplayTemplates.HiddenInputTemplate(MakeHtmlHelper<string>(\"<script>alert('XSS!')</script>\", \"<b>Encode me!</b>\")));\n\n            var helperWithInvisibleHtml = MakeHtmlHelper<string>(\"<script>alert('XSS!')</script>\", \"<b>Encode me!</b>\");\n            helperWithInvisibleHtml.ViewData.ModelMetadata.HideSurroundingHtml = true;\n            Assert.Equal(\n                String.Empty,\n                DefaultDisplayTemplates.HiddenInputTemplate(helperWithInvisibleHtml));\n        }\n\n        // HtmlTemplate\n\n        [Fact]\n        public void HtmlTemplateTests()\n        {\n            Assert.Equal(\n                \"Hello, world!\",\n                DefaultDisplayTemplates.HtmlTemplate(MakeHtmlHelper<string>(\"\", \"Hello, world!\")));\n\n            Assert.Equal(\n                \"<b>Hello, world!</b>\",\n                DefaultDisplayTemplates.HtmlTemplate(MakeHtmlHelper<string>(\"\", \"<b>Hello, world!</b>\")));\n        }\n\n        // ObjectTemplate\n\n        private static string SpyCallback(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string templateName, DataBoundControlMode mode, object additionalViewData)\n        {\n            return String.Format(\"Model = {0}, ModelType = {1}, PropertyName = {2}, HtmlFieldName = {3}, TemplateName = {4}, Mode = {5}, AdditionalViewData = {6}\",\n                                 metadata.Model ?? \"(null)\",\n                                 metadata.ModelType == null ? \"(null)\" : metadata.ModelType.FullName,\n                                 metadata.PropertyName ?? \"(null)\",\n                                 htmlFieldName == String.Empty ? \"(empty)\" : htmlFieldName ?? \"(null)\",\n                                 templateName ?? \"(null)\",\n                                 mode,\n                                 AnonymousObject.Inspect(additionalViewData));\n        }\n\n        class ObjectTemplateModel\n        {\n            public ObjectTemplateModel()\n            {\n                ComplexInnerModel = new object();\n            }\n\n            public string Property1 { get; set; }\n            public string Property2 { get; set; }\n            public object ComplexInnerModel { get; set; }\n        }\n\n        [Fact]\n        public void ObjectTemplateDisplaysSimplePropertiesOnObjectByDefault()\n        {\n            string expected =\n                \"<div class=\\\"display-label\\\">Property1</div>\" + Environment.NewLine\n              + \"<div class=\\\"display-field\\\">Model = p1, ModelType = System.String, PropertyName = Property1, HtmlFieldName = Property1, TemplateName = (null), Mode = ReadOnly, AdditionalViewData = (null)</div>\" + Environment.NewLine\n              + \"<div class=\\\"display-label\\\">Property2</div>\" + Environment.NewLine\n              + \"<div class=\\\"display-field\\\">Model = (null), ModelType = System.String, PropertyName = Property2, HtmlFieldName = Property2, TemplateName = (null), Mode = ReadOnly, AdditionalViewData = (null)</div>\" + Environment.NewLine;\n\n            // Arrange\n            ObjectTemplateModel model = new ObjectTemplateModel { Property1 = \"p1\", Property2 = null };\n            HtmlHelper html = MakeHtmlHelper<ObjectTemplateModel>(model);\n\n            // Act\n            string result = DefaultDisplayTemplates.ObjectTemplate(html, SpyCallback);\n\n            // Assert\n            Assert.Equal(expected, result);\n        }\n\n        [Fact]\n        public void ObjectTemplateWithDisplayNameMetadata()\n        {\n            string expected =\n                \"<div class=\\\"display-field\\\">Model = (null), ModelType = System.String, PropertyName = Property1, HtmlFieldName = Property1, TemplateName = (null), Mode = ReadOnly, AdditionalViewData = (null)</div>\" + Environment.NewLine\n              + \"<div class=\\\"display-label\\\">Custom display name</div>\" + Environment.NewLine\n              + \"<div class=\\\"display-field\\\">Model = (null), ModelType = System.String, PropertyName = Property2, HtmlFieldName = Property2, TemplateName = (null), Mode = ReadOnly, AdditionalViewData = (null)</div>\" + Environment.NewLine;\n\n            // Arrange\n            ObjectTemplateModel model = new ObjectTemplateModel();\n            HtmlHelper html = MakeHtmlHelper<ObjectTemplateModel>(model);\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            Func<object> accessor = () => model;\n            Mock<ModelMetadata> metadata = new Mock<ModelMetadata>(provider.Object, null, accessor, typeof(ObjectTemplateModel), null);\n            ModelMetadata prop1Metadata = new ModelMetadata(provider.Object, typeof(ObjectTemplateModel), null, typeof(string), \"Property1\") { DisplayName = String.Empty };\n            ModelMetadata prop2Metadata = new ModelMetadata(provider.Object, typeof(ObjectTemplateModel), null, typeof(string), \"Property2\") { DisplayName = \"Custom display name\" };\n            html.ViewData.ModelMetadata = metadata.Object;\n            metadata.Setup(p => p.Properties).Returns(() => new[] { prop1Metadata, prop2Metadata });\n\n            // Act\n            string result = DefaultDisplayTemplates.ObjectTemplate(html, SpyCallback);\n\n            // Assert\n            Assert.Equal(expected, result);\n        }\n\n        [Fact]\n        public void ObjectTemplateWithShowForDisplayMetadata()\n        {\n            string expected =\n                \"<div class=\\\"display-label\\\">Property1</div>\" + Environment.NewLine\n              + \"<div class=\\\"display-field\\\">Model = (null), ModelType = System.String, PropertyName = Property1, HtmlFieldName = Property1, TemplateName = (null), Mode = ReadOnly, AdditionalViewData = (null)</div>\" + Environment.NewLine;\n\n            // Arrange\n            ObjectTemplateModel model = new ObjectTemplateModel();\n            HtmlHelper html = MakeHtmlHelper<ObjectTemplateModel>(model);\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            Func<object> accessor = () => model;\n            Mock<ModelMetadata> metadata = new Mock<ModelMetadata>(provider.Object, null, accessor, typeof(ObjectTemplateModel), null);\n            ModelMetadata prop1Metadata = new ModelMetadata(provider.Object, typeof(ObjectTemplateModel), null, typeof(string), \"Property1\") { ShowForDisplay = true };\n            ModelMetadata prop2Metadata = new ModelMetadata(provider.Object, typeof(ObjectTemplateModel), null, typeof(string), \"Property2\") { ShowForDisplay = false };\n            html.ViewData.ModelMetadata = metadata.Object;\n            metadata.Setup(p => p.Properties).Returns(() => new[] { prop1Metadata, prop2Metadata });\n\n            // Act\n            string result = DefaultDisplayTemplates.ObjectTemplate(html, SpyCallback);\n\n            // Assert\n            Assert.Equal(expected, result);\n        }\n\n        [Fact]\n        public void ObjectTemplatePreventsRecursionOnModelValue()\n        {\n            string expected =\n                \"<div class=\\\"display-label\\\">Property2</div>\" + Environment.NewLine\n              + \"<div class=\\\"display-field\\\">Model = propValue2, ModelType = System.String, PropertyName = Property2, HtmlFieldName = Property2, TemplateName = (null), Mode = ReadOnly, AdditionalViewData = (null)</div>\" + Environment.NewLine;\n\n            // Arrange\n            ObjectTemplateModel model = new ObjectTemplateModel();\n            HtmlHelper html = MakeHtmlHelper<ObjectTemplateModel>(model);\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            Func<object> accessor = () => model;\n            Mock<ModelMetadata> metadata = new Mock<ModelMetadata>(provider.Object, null, accessor, typeof(ObjectTemplateModel), null);\n            ModelMetadata prop1Metadata = new ModelMetadata(provider.Object, typeof(ObjectTemplateModel), () => \"propValue1\", typeof(string), \"Property1\");\n            ModelMetadata prop2Metadata = new ModelMetadata(provider.Object, typeof(ObjectTemplateModel), () => \"propValue2\", typeof(string), \"Property2\");\n            html.ViewData.ModelMetadata = metadata.Object;\n            metadata.Setup(p => p.Properties).Returns(() => new[] { prop1Metadata, prop2Metadata });\n            html.ViewData.TemplateInfo.VisitedObjects.Add(\"propValue1\");\n\n            // Act\n            string result = DefaultDisplayTemplates.ObjectTemplate(html, SpyCallback);\n\n            // Assert\n            Assert.Equal(expected, result);\n        }\n\n        [Fact]\n        public void ObjectTemplatePreventsRecursionOnModelTypeForNullModelValues()\n        {\n            string expected =\n                \"<div class=\\\"display-label\\\">Property2</div>\" + Environment.NewLine\n              + \"<div class=\\\"display-field\\\">Model = propValue2, ModelType = System.String, PropertyName = Property2, HtmlFieldName = Property2, TemplateName = (null), Mode = ReadOnly, AdditionalViewData = (null)</div>\" + Environment.NewLine;\n\n            // Arrange\n            ObjectTemplateModel model = new ObjectTemplateModel();\n            HtmlHelper html = MakeHtmlHelper<ObjectTemplateModel>(model);\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            Func<object> accessor = () => model;\n            Mock<ModelMetadata> metadata = new Mock<ModelMetadata>(provider.Object, null, accessor, typeof(ObjectTemplateModel), null);\n            ModelMetadata prop1Metadata = new ModelMetadata(provider.Object, typeof(ObjectTemplateModel), null, typeof(string), \"Property1\");\n            ModelMetadata prop2Metadata = new ModelMetadata(provider.Object, typeof(ObjectTemplateModel), () => \"propValue2\", typeof(string), \"Property2\");\n            html.ViewData.ModelMetadata = metadata.Object;\n            metadata.Setup(p => p.Properties).Returns(() => new[] { prop1Metadata, prop2Metadata });\n            html.ViewData.TemplateInfo.VisitedObjects.Add(typeof(string));\n\n            // Act\n            string result = DefaultDisplayTemplates.ObjectTemplate(html, SpyCallback);\n\n            // Assert\n            Assert.Equal(expected, result);\n        }\n\n        [Fact]\n        public void ObjectTemplateDisplaysNullDisplayTextWhenObjectIsNull()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper<ObjectTemplateModel>(null);\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(ObjectTemplateModel));\n            metadata.NullDisplayText = \"(null value)\";\n            html.ViewData.ModelMetadata = metadata;\n\n            // Act\n            string result = DefaultDisplayTemplates.ObjectTemplate(html, SpyCallback);\n\n            // Assert\n            Assert.Equal(metadata.NullDisplayText, result);\n        }\n\n        [Theory]\n        [PropertyData(\"ConditionallyHtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void ObjectTemplateDisplaysSimpleDisplayTextWhenTemplateDepthGreaterThanOne(\n            string text,\n            bool htmlEncode,\n            string expectedResult)\n        {\n            // Arrange\n            ObjectTemplateModel model = new ObjectTemplateModel();\n            HtmlHelper html = MakeHtmlHelper<ObjectTemplateModel>(model);\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, typeof(ObjectTemplateModel));\n            metadata.SimpleDisplayText = text;\n            metadata.HtmlEncode = htmlEncode;\n\n            html.ViewData.ModelMetadata = metadata;\n            html.ViewData.TemplateInfo.VisitedObjects.Add(\"foo\");\n            html.ViewData.TemplateInfo.VisitedObjects.Add(\"bar\");\n\n            // Act\n            string result = DefaultDisplayTemplates.ObjectTemplate(html, SpyCallback);\n\n            // Assert\n            Assert.Equal(expectedResult, result);\n        }\n\n        [Fact]\n        public void ObjectTemplateWithHiddenHtml()\n        {\n            string expected = \"Model = propValue1, ModelType = System.String, PropertyName = Property1, HtmlFieldName = Property1, TemplateName = (null), Mode = ReadOnly, AdditionalViewData = (null)\";\n\n            // Arrange\n            ObjectTemplateModel model = new ObjectTemplateModel();\n            HtmlHelper html = MakeHtmlHelper<ObjectTemplateModel>(model);\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            Func<object> accessor = () => model;\n            Mock<ModelMetadata> metadata = new Mock<ModelMetadata>(provider.Object, null, accessor, typeof(ObjectTemplateModel), null);\n            ModelMetadata prop1Metadata = new ModelMetadata(provider.Object, typeof(ObjectTemplateModel), () => \"propValue1\", typeof(string), \"Property1\") { HideSurroundingHtml = true };\n            html.ViewData.ModelMetadata = metadata.Object;\n            metadata.Setup(p => p.Properties).Returns(() => new[] { prop1Metadata });\n\n            // Act\n            string result = DefaultDisplayTemplates.ObjectTemplate(html, SpyCallback);\n\n            // Assert\n            Assert.Equal(expected, result);\n        }\n\n        [Fact]\n        public void ObjectTemplateAllPropertiesFromEntityObjectAreHidden()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper<ObjectTemplateModel>(new MyEntityObject());\n\n            // Act\n            string result = DefaultDisplayTemplates.ObjectTemplate(html, SpyCallback);\n\n            // Assert\n            Assert.Equal(String.Empty, result);\n        }\n\n        private class MyEntityObject : EntityObject\n        {\n        }\n\n        // StringTemplate\n\n        [Fact]\n        public void StringTemplateTests()\n        {\n            Assert.Equal(\n                \"Hello, world!\",\n                DefaultDisplayTemplates.StringTemplate(MakeHtmlHelper<string>(\"\", \"Hello, world!\")));\n\n            Assert.Equal(\n                \"&lt;b&gt;Hello, world!&lt;/b&gt;\",\n                DefaultDisplayTemplates.StringTemplate(MakeHtmlHelper<string>(\"\", \"<b>Hello, world!</b>\")));\n        }\n\n        // UrlTemplate\n\n        [Fact]\n        public void UrlTemplateTests()\n        {\n            Assert.Equal(\n                \"<a href=\\\"http://www.microsoft.com/testing.aspx?value1=foo&amp;value2=bar\\\">http://www.microsoft.com/testing.aspx?value1=foo&amp;value2=bar</a>\",\n                DefaultDisplayTemplates.UrlTemplate(MakeHtmlHelper<string>(\"http://www.microsoft.com/testing.aspx?value1=foo&value2=bar\")));\n\n            Assert.Equal(\n                \"<a href=\\\"http://www.microsoft.com/testing.aspx?value1=foo&amp;value2=bar\\\">&lt;b&gt;Microsoft!&lt;/b&gt;</a>\",\n                DefaultDisplayTemplates.UrlTemplate(MakeHtmlHelper<string>(\"http://www.microsoft.com/testing.aspx?value1=foo&value2=bar\", \"<b>Microsoft!</b>\")));\n        }\n\n        // Helpers\n\n        private HtmlHelper MakeHtmlHelper<TModel>(object model)\n        {\n            return MakeHtmlHelper<TModel>(model, model);\n        }\n\n        private HtmlHelper MakeHtmlHelper<TModel>(object model, object formattedModelValue)\n        {\n            ViewDataDictionary viewData = new ViewDataDictionary(model);\n            viewData.TemplateInfo.HtmlFieldPrefix = \"FieldPrefix\";\n            viewData.TemplateInfo.FormattedModelValue = formattedModelValue;\n            viewData.ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => model, typeof(TModel));\n\n            ViewContext viewContext = new ViewContext(new ControllerContext(), new DummyView(), viewData, new TempDataDictionary(), new StringWriter());\n\n            return new HtmlHelper(viewContext, new SimpleViewDataContainer(viewData));\n        }\n\n        private class DummyView : IView\n        {\n            public void Render(ViewContext viewContext, TextWriter writer)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Html/Test/DefaultEditorTemplatesTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Data.Linq;\nusing System.Data.Objects.DataClasses;\nusing System.Drawing;\nusing System.Globalization;\nusing System.IO;\nusing System.Web.UI.WebControls;\nusing System.Web.WebPages.Scope;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\nusing Moq;\n\nnamespace System.Web.Mvc.Html.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")]\n    public class DefaultEditorTemplatesTest : IDisposable\n    {\n        // BooleanTemplate\n\n        [Fact]\n        public void BooleanTemplateTests()\n        {\n            // Boolean values\n\n            Assert.Equal(\n                \"<input checked=\\\"checked\\\" class=\\\"check-box\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"checkbox\\\" value=\\\"true\\\" /><input name=\\\"FieldPrefix\\\" type=\\\"hidden\\\" value=\\\"false\\\" />\",\n                DefaultEditorTemplates.BooleanTemplate(MakeHtmlHelper<bool>(true)));\n\n            Assert.Equal(\n                \"<input class=\\\"check-box\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"checkbox\\\" value=\\\"true\\\" /><input name=\\\"FieldPrefix\\\" type=\\\"hidden\\\" value=\\\"false\\\" />\",\n                DefaultEditorTemplates.BooleanTemplate(MakeHtmlHelper<bool>(false)));\n\n            Assert.Equal(\n                \"<input class=\\\"check-box\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"checkbox\\\" value=\\\"true\\\" /><input name=\\\"FieldPrefix\\\" type=\\\"hidden\\\" value=\\\"false\\\" />\",\n                DefaultEditorTemplates.BooleanTemplate(MakeHtmlHelper<bool>(null)));\n\n            // Nullable<Boolean> values\n\n            Assert.Equal(\n                \"<select class=\\\"list-box tri-state\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\"><option value=\\\"\\\">Not Set</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"true\\\">True</option>\" + Environment.NewLine\n              + \"<option value=\\\"false\\\">False</option>\" + Environment.NewLine\n              + \"</select>\",\n                DefaultEditorTemplates.BooleanTemplate(MakeHtmlHelper<Nullable<bool>>(true)));\n\n            Assert.Equal(\n                \"<select class=\\\"list-box tri-state\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\"><option value=\\\"\\\">Not Set</option>\" + Environment.NewLine\n              + \"<option value=\\\"true\\\">True</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"false\\\">False</option>\" + Environment.NewLine\n              + \"</select>\",\n                DefaultEditorTemplates.BooleanTemplate(MakeHtmlHelper<Nullable<bool>>(false)));\n\n            Assert.Equal(\n                \"<select class=\\\"list-box tri-state\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\"><option selected=\\\"selected\\\" value=\\\"\\\">Not Set</option>\" + Environment.NewLine\n              + \"<option value=\\\"true\\\">True</option>\" + Environment.NewLine\n              + \"<option value=\\\"false\\\">False</option>\" + Environment.NewLine\n              + \"</select>\",\n                DefaultEditorTemplates.BooleanTemplate(MakeHtmlHelper<Nullable<bool>>(null)));\n        }\n\n        public static TheoryDataSet<object, string> BooleanTemplateHtmlAttributeData\n        {\n            get\n            {\n                return new TheoryDataSet<object, string>\n                {\n                    {\n                        new { @class = \"form-control\" },\n                        \"<input checked=\\\"checked\\\" class=\\\"form-control check-box\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"checkbox\\\" value=\\\"true\\\" /><input name=\\\"FieldPrefix\\\" type=\\\"hidden\\\" value=\\\"false\\\" />\"\n                    },\n                    {\n                        new { @class = \"form-control\", custom = \"foo\" },\n                        \"<input checked=\\\"checked\\\" class=\\\"form-control check-box\\\" custom=\\\"foo\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"checkbox\\\" value=\\\"true\\\" /><input name=\\\"FieldPrefix\\\" type=\\\"hidden\\\" value=\\\"false\\\" />\"\n                    }\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"BooleanTemplateHtmlAttributeData\")]\n        public void BooleanTemplate_AddsHtmlAttributes(object htmlAttributes, string expectedHtml)\n        {\n            var htmlHelper = MakeHtmlHelper<bool>(true);\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = htmlAttributes;\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.BooleanTemplate(htmlHelper));\n        }\n\n        [Theory]\n        [PropertyData(\"BooleanTemplateHtmlAttributeData\")]\n        public void BooleanTemplate_AddsHtmlAttributesDictionary(object htmlAttributes, string expectedHtml)\n        {\n            var htmlHelper = MakeHtmlHelper<bool>(true);\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.BooleanTemplate(htmlHelper));\n        }\n\n        // CollectionTemplate\n\n        private static string CollectionSpyCallback(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string templateName, DataBoundControlMode mode, object additionalViewData)\n        {\n            return String.Format(CultureInfo.InvariantCulture,\n                                 Environment.NewLine + \"Model = {0}, ModelType = {1}, PropertyName = {2}, HtmlFieldName = {3}, TemplateName = {4}, Mode = {5}, TemplateInfo.HtmlFieldPrefix = {6}, AdditionalViewData = {7}\",\n                                 metadata.Model ?? \"(null)\",\n                                 metadata.ModelType == null ? \"(null)\" : metadata.ModelType.FullName,\n                                 metadata.PropertyName ?? \"(null)\",\n                                 htmlFieldName == String.Empty ? \"(empty)\" : htmlFieldName ?? \"(null)\",\n                                 templateName ?? \"(null)\",\n                                 mode,\n                                 html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix,\n                                 AnonymousObject.Inspect(additionalViewData));\n        }\n\n        [Fact]\n        public void CollectionTemplateWithNullModel()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper<object>(null);\n\n            // Act\n            string result = DefaultEditorTemplates.CollectionTemplate(html, CollectionSpyCallback);\n\n            // Assert\n            Assert.Equal(String.Empty, result);\n        }\n\n        [Fact]\n        public void CollectionTemplateNonEnumerableModelThrows()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper<object>(new object());\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => DefaultEditorTemplates.CollectionTemplate(html, CollectionSpyCallback),\n                \"The Collection template was used with an object of type 'System.Object', which does not implement System.IEnumerable.\"\n                );\n        }\n\n        [Fact]\n        public void CollectionTemplateWithSingleItemCollectionWithoutPrefix()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper<List<string>>(new List<string> { \"foo\" });\n            html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = null;\n\n            // Act\n            string result = DefaultEditorTemplates.CollectionTemplate(html, CollectionSpyCallback);\n\n            // Assert\n            Assert.Equal(\n                Environment.NewLine\n              + \"Model = foo, ModelType = System.String, PropertyName = (null), HtmlFieldName = [0], TemplateName = (null), Mode = Edit, TemplateInfo.HtmlFieldPrefix = , AdditionalViewData = (null)\",\n                result);\n        }\n\n        [Fact]\n        public void CollectionTemplateWithSingleItemCollectionWithPrefix()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper<List<string>>(new List<string> { \"foo\" });\n            html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"ModelProperty\";\n\n            // Act\n            string result = DefaultEditorTemplates.CollectionTemplate(html, CollectionSpyCallback);\n\n            // Assert\n            Assert.Equal(\n                Environment.NewLine\n              + \"Model = foo, ModelType = System.String, PropertyName = (null), HtmlFieldName = ModelProperty[0], TemplateName = (null), Mode = Edit, TemplateInfo.HtmlFieldPrefix = , AdditionalViewData = (null)\",\n                result);\n        }\n\n        [Fact]\n        public void CollectionTemplateWithMultiItemCollection()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper<List<string>>(new List<string> { \"foo\", \"bar\", \"baz\" });\n            html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = null;\n\n            // Act\n            string result = DefaultEditorTemplates.CollectionTemplate(html, CollectionSpyCallback);\n\n            // Assert\n            Assert.Equal(\n                Environment.NewLine\n              + \"Model = foo, ModelType = System.String, PropertyName = (null), HtmlFieldName = [0], TemplateName = (null), Mode = Edit, TemplateInfo.HtmlFieldPrefix = , AdditionalViewData = (null)\" + Environment.NewLine\n              + \"Model = bar, ModelType = System.String, PropertyName = (null), HtmlFieldName = [1], TemplateName = (null), Mode = Edit, TemplateInfo.HtmlFieldPrefix = , AdditionalViewData = (null)\" + Environment.NewLine\n              + \"Model = baz, ModelType = System.String, PropertyName = (null), HtmlFieldName = [2], TemplateName = (null), Mode = Edit, TemplateInfo.HtmlFieldPrefix = , AdditionalViewData = (null)\",\n                result);\n        }\n\n        [Fact]\n        public void CollectionTemplateNullITemInWeaklyTypedCollectionUsesModelTypeOfString()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper<ArrayList>(new ArrayList { null });\n            html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = null;\n\n            // Act\n            string result = DefaultEditorTemplates.CollectionTemplate(html, CollectionSpyCallback);\n\n            // Assert\n            Assert.Equal(\n                Environment.NewLine\n              + \"Model = (null), ModelType = System.String, PropertyName = (null), HtmlFieldName = [0], TemplateName = (null), Mode = Edit, TemplateInfo.HtmlFieldPrefix = , AdditionalViewData = (null)\",\n                result);\n        }\n\n        [Fact]\n        public void CollectionTemplateNullItemInStronglyTypedCollectionUsesModelTypeFromIEnumerable()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper<List<IHttpHandler>>(new List<IHttpHandler> { null });\n            html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = null;\n\n            // Act\n            string result = DefaultEditorTemplates.CollectionTemplate(html, CollectionSpyCallback);\n\n            // Assert\n            Assert.Equal(\n                Environment.NewLine\n              + \"Model = (null), ModelType = System.Web.IHttpHandler, PropertyName = (null), HtmlFieldName = [0], TemplateName = (null), Mode = Edit, TemplateInfo.HtmlFieldPrefix = , AdditionalViewData = (null)\",\n                result);\n        }\n\n        [Fact]\n        public void CollectionTemplateUsesRealObjectTypes()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper<List<object>>(new List<object> { 1, 2.3, \"Hello World\" });\n            html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = null;\n\n            // Act\n            string result = DefaultEditorTemplates.CollectionTemplate(html, CollectionSpyCallback);\n\n            // Assert\n            Assert.Equal(\n                Environment.NewLine\n              + \"Model = 1, ModelType = System.Int32, PropertyName = (null), HtmlFieldName = [0], TemplateName = (null), Mode = Edit, TemplateInfo.HtmlFieldPrefix = , AdditionalViewData = (null)\" + Environment.NewLine\n              + \"Model = 2.3, ModelType = System.Double, PropertyName = (null), HtmlFieldName = [1], TemplateName = (null), Mode = Edit, TemplateInfo.HtmlFieldPrefix = , AdditionalViewData = (null)\" + Environment.NewLine\n              + \"Model = Hello World, ModelType = System.String, PropertyName = (null), HtmlFieldName = [2], TemplateName = (null), Mode = Edit, TemplateInfo.HtmlFieldPrefix = , AdditionalViewData = (null)\",\n                result);\n        }\n\n        [Fact]\n        public void CollectionTemplateNullItemInCollectionOfNullableValueTypesDoesNotDiscardNullable()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper<List<int?>>(new List<int?> { 1, null, 2 });\n            html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = null;\n\n            // Act\n            string result = DefaultEditorTemplates.CollectionTemplate(html, CollectionSpyCallback);\n\n            // Assert\n            Assert.Equal(\n                Environment.NewLine\n              + \"Model = 1, ModelType = System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], PropertyName = (null), HtmlFieldName = [0], TemplateName = (null), Mode = Edit, TemplateInfo.HtmlFieldPrefix = , AdditionalViewData = (null)\" + Environment.NewLine\n              + \"Model = (null), ModelType = System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], PropertyName = (null), HtmlFieldName = [1], TemplateName = (null), Mode = Edit, TemplateInfo.HtmlFieldPrefix = , AdditionalViewData = (null)\" + Environment.NewLine\n              + \"Model = 2, ModelType = System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], PropertyName = (null), HtmlFieldName = [2], TemplateName = (null), Mode = Edit, TemplateInfo.HtmlFieldPrefix = , AdditionalViewData = (null)\",\n                result);\n        }\n\n        [Fact]\n        public void CollectionTemplate_AddsHtmlAttributes()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper<List<string>>(new List<string> { \"foo\", \"bar\", \"baz\" });\n            html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = null;\n            html.ViewContext.ViewBag.htmlAttributes = new { @class = \"form-control\", foo = \"bar\" };\n\n            // Act\n            string result = RunWithoutViewEngine(() =>\n                DefaultEditorTemplates.CollectionTemplate(html));\n\n            // Assert\n            Assert.Equal(\n                \"<input class=\\\"form-control text-box single-line\\\" foo=\\\"bar\\\" name=\\\"[0]\\\" type=\\\"text\\\" value=\\\"foo\\\" />\"\n              + \"<input class=\\\"form-control text-box single-line\\\" foo=\\\"bar\\\" name=\\\"[1]\\\" type=\\\"text\\\" value=\\\"bar\\\" />\"\n              + \"<input class=\\\"form-control text-box single-line\\\" foo=\\\"bar\\\" name=\\\"[2]\\\" type=\\\"text\\\" value=\\\"baz\\\" />\",\n                result);\n        }\n\n        // DecimalTemplate\n\n        [Fact]\n        public void DecimalTemplateTests()\n        {\n            Assert.Equal(\n                String.Format(\n                    CultureInfo.CurrentCulture,\n                    \"<input class=\\\"text-box single-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"text\\\" value=\\\"{0:0.00}\\\" />\",\n                    12.35M),\n                DefaultEditorTemplates.DecimalTemplate(MakeHtmlHelper<decimal>(12.3456M)));\n\n            Assert.Equal(\n                \"<input class=\\\"text-box single-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"text\\\" value=\\\"Formatted Value\\\" />\",\n                DefaultEditorTemplates.DecimalTemplate(MakeHtmlHelper<decimal>(12.3456M, \"Formatted Value\")));\n\n            Assert.Equal(\n                \"<input class=\\\"text-box single-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"text\\\" value=\\\"&lt;script>alert(&#39;XSS!&#39;)&lt;/script>\\\" />\",\n                DefaultEditorTemplates.DecimalTemplate(MakeHtmlHelper<decimal>(12.3456M, \"<script>alert('XSS!')</script>\")));\n        }\n\n        public static TheoryDataSet<object, string> DecimalTemplateHtmlAttributeData\n        {\n            get\n            {\n                return new TheoryDataSet<object, string>\n                {\n                    {\n                        new { @class = \"form-control\" },\n                        \"<input class=\\\"form-control text-box single-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"text\\\" value=\\\"12.30\\\" />\"\n                    },\n                    {\n                        new { @class = \"form-control\", custom = \"foo\" },\n                        \"<input class=\\\"form-control text-box single-line\\\" custom=\\\"foo\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"text\\\" value=\\\"12.30\\\" />\"\n                    }\n                };\n            }\n        }\n\n        [Theory]\n        [ReplaceCulture]\n        [PropertyData(\"DecimalTemplateHtmlAttributeData\")]\n        public void DecimalTemplate_AddsHtmlAttributes(object htmlAttributes, string expectedHtml)\n        {\n            var htmlHelper = MakeHtmlHelper<decimal>(12.30);\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = htmlAttributes;\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.DecimalTemplate(htmlHelper));\n        }\n\n        [Theory]\n        [ReplaceCulture]\n        [PropertyData(\"DecimalTemplateHtmlAttributeData\")]\n        public void DecimalTemplate_AddsHtmlAttributesDictionary(object htmlAttributes, string expectedHtml)\n        {\n            var htmlHelper = MakeHtmlHelper<decimal>(12.30);\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.DecimalTemplate(htmlHelper));\n        }\n\n        // HiddenInputTemplate\n\n        [Fact]\n        public void HiddenInputTemplateTests()\n        {\n            Assert.Equal(\n                \"Hidden Value<input id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"hidden\\\" value=\\\"Hidden Value\\\" />\",\n                DefaultEditorTemplates.HiddenInputTemplate(MakeHtmlHelper<string>(\"Hidden Value\")));\n\n            Assert.Equal(\n                \"&lt;script&gt;alert(&#39;XSS!&#39;)&lt;/script&gt;<input id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"hidden\\\" value=\\\"&lt;script>alert(&#39;XSS!&#39;)&lt;/script>\\\" />\",\n                DefaultEditorTemplates.HiddenInputTemplate(MakeHtmlHelper<string>(\"<script>alert('XSS!')</script>\")));\n\n            var helperWithInvisibleHtml = MakeHtmlHelper<string>(\"<script>alert('XSS!')</script>\", \"<b>Encode me!</b>\");\n            helperWithInvisibleHtml.ViewData.ModelMetadata.HideSurroundingHtml = true;\n            Assert.Equal(\n                \"<input id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"hidden\\\" value=\\\"&lt;script>alert(&#39;XSS!&#39;)&lt;/script>\\\" />\",\n                DefaultEditorTemplates.HiddenInputTemplate(helperWithInvisibleHtml));\n\n            byte[] byteValues = { 1, 2, 3, 4, 5 };\n\n            Assert.Equal(\n                \"&quot;AQIDBAU=&quot;<input id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"hidden\\\" value=\\\"AQIDBAU=\\\" />\",\n                DefaultEditorTemplates.HiddenInputTemplate(MakeHtmlHelper<Binary>(new Binary(byteValues))));\n\n            Assert.Equal(\n                \"System.Byte[]<input id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"hidden\\\" value=\\\"AQIDBAU=\\\" />\",\n                DefaultEditorTemplates.HiddenInputTemplate(MakeHtmlHelper<byte[]>(byteValues)));\n        }\n\n        public static TheoryDataSet<object, string> HiddenInputTemplateHtmlAttributeData\n        {\n            get\n            {\n                return new TheoryDataSet<object, string>\n                {\n                    {\n                        new { @class = \"form-control\" },\n                        \"Hidden Value<input class=\\\"form-control\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"hidden\\\" value=\\\"Hidden Value\\\" />\"\n                    },\n                    {\n                        new { @class = \"form-control\", custom = \"foo\" },\n                        \"Hidden Value<input class=\\\"form-control\\\" custom=\\\"foo\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"hidden\\\" value=\\\"Hidden Value\\\" />\"\n                    }\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"HiddenInputTemplateHtmlAttributeData\")]\n        public void HiddenInputTemplate_AddsHtmlAttributes(object htmlAttributes, string expectedHtml)\n        {\n            var htmlHelper = MakeHtmlHelper<string>(\"Hidden Value\");\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = htmlAttributes;\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.HiddenInputTemplate(htmlHelper));\n        }\n\n        [Theory]\n        [PropertyData(\"HiddenInputTemplateHtmlAttributeData\")]\n        public void HiddenInputTemplate_AddsHtmlAttributesDictionary(object htmlAttributes, string expectedHtml)\n        {\n            var htmlHelper = MakeHtmlHelper<string>(\"Hidden Value\");\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.HiddenInputTemplate(htmlHelper));\n        }\n\n        // MultilineText\n\n        [Fact]\n        public void MultilineTextTemplateTests()\n        {\n            Assert.Equal(\n                \"<textarea class=\\\"text-box multi-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\">\" + Environment.NewLine\n              + \"Multiple\" + Environment.NewLine\n              + \"Line\" + Environment.NewLine\n              + \"Value!</textarea>\",\n                DefaultEditorTemplates.MultilineTextTemplate(MakeHtmlHelper<string>(\"\", \"Multiple\" + Environment.NewLine + \"Line\" + Environment.NewLine + \"Value!\")));\n\n            Assert.Equal(\n                \"<textarea class=\\\"text-box multi-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\">\" + Environment.NewLine\n              + \"&lt;script&gt;alert(&#39;XSS!&#39;)&lt;/script&gt;</textarea>\",\n                DefaultEditorTemplates.MultilineTextTemplate(MakeHtmlHelper<string>(\"\", \"<script>alert('XSS!')</script>\")));\n        }\n\n        public static TheoryDataSet<object, string> MultilineTextTemplateHtmlAttributeData\n        {\n            get\n            {\n                return new TheoryDataSet<object, string>\n                {\n                    {\n                        new { @class = \"form-control\" },\n                        \"<textarea class=\\\"form-control text-box multi-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\">\" + Environment.NewLine\n                      + \"Multiple\" + Environment.NewLine\n                      + \"Line\" + Environment.NewLine\n                      + \"Value!</textarea>\"\n                    },\n                    {\n                        new { @class = \"form-control\", custom = \"foo\" },\n                        \"<textarea class=\\\"form-control text-box multi-line\\\" custom=\\\"foo\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\">\" + Environment.NewLine\n                      + \"Multiple\" + Environment.NewLine\n                      + \"Line\" + Environment.NewLine\n                      + \"Value!</textarea>\"\n                    }\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"MultilineTextTemplateHtmlAttributeData\")]\n        public void MultilineTextTemplate_AddsHtmlAttributes(object htmlAttributes, string expectedHtml)\n        {\n            var htmlHelper = MakeHtmlHelper<string>(\"\", \"Multiple\" + Environment.NewLine + \"Line\" + Environment.NewLine + \"Value!\");\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = htmlAttributes;\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.MultilineTextTemplate(htmlHelper));\n        }\n\n        [Theory]\n        [PropertyData(\"MultilineTextTemplateHtmlAttributeData\")]\n        public void MultilineTextTemplate_AddsHtmlAttributesDictionary(object htmlAttributes, string expectedHtml)\n        {\n            var htmlHelper = MakeHtmlHelper<string>(\"\", \"Multiple\" + Environment.NewLine + \"Line\" + Environment.NewLine + \"Value!\");\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.MultilineTextTemplate(htmlHelper));\n        }\n\n        // ObjectTemplate\n\n        private static string SpyCallback(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string templateName, DataBoundControlMode mode, object additionalViewData)\n        {\n            return String.Format(\"Model = {0}, ModelType = {1}, PropertyName = {2}, HtmlFieldName = {3}, TemplateName = {4}, Mode = {5}, AdditionalViewData = {6}\",\n                                 metadata.Model ?? \"(null)\",\n                                 metadata.ModelType == null ? \"(null)\" : metadata.ModelType.FullName,\n                                 metadata.PropertyName ?? \"(null)\",\n                                 htmlFieldName == String.Empty ? \"(empty)\" : htmlFieldName ?? \"(null)\",\n                                 templateName ?? \"(null)\",\n                                 mode,\n                                 AnonymousObject.Inspect(additionalViewData));\n        }\n\n        private class ObjectTemplateModel\n        {\n            public ObjectTemplateModel()\n            {\n                ComplexInnerModel = new object();\n            }\n\n            public string Property1 { get; set; }\n\n            public string Property2 { get; set; }\n\n            public object ComplexInnerModel { get; set; }\n        }\n\n        [Fact]\n        public void ObjectTemplateEditsSimplePropertiesOnObjectByDefault()\n        {\n            string expected =\n                \"<div class=\\\"editor-label\\\"><label for=\\\"FieldPrefix_Property1\\\">Property1</label></div>\" + Environment.NewLine\n              + \"<div class=\\\"editor-field\\\">Model = p1, ModelType = System.String, PropertyName = Property1, HtmlFieldName = Property1, TemplateName = (null), Mode = Edit, AdditionalViewData = (null) </div>\" + Environment.NewLine\n              + \"<div class=\\\"editor-label\\\"><label for=\\\"FieldPrefix_Property2\\\">Property2</label></div>\" + Environment.NewLine\n              + \"<div class=\\\"editor-field\\\">Model = (null), ModelType = System.String, PropertyName = Property2, HtmlFieldName = Property2, TemplateName = (null), Mode = Edit, AdditionalViewData = (null) </div>\" + Environment.NewLine;\n\n            // Arrange\n            ObjectTemplateModel model = new ObjectTemplateModel { Property1 = \"p1\", Property2 = null };\n            HtmlHelper html = MakeHtmlHelper<ObjectTemplateModel>(model);\n\n            // Act\n            string result = DefaultEditorTemplates.ObjectTemplate(html, SpyCallback);\n\n            // Assert\n            Assert.Equal(expected, result);\n        }\n\n        [Fact]\n        public void ObjectTemplate_AddsHtmlAttributes()\n        {\n            string expected =\n                \"<div class=\\\"editor-label\\\"><label for=\\\"FieldPrefix_Property1\\\">Property1</label></div>\" + Environment.NewLine\n              + \"<div class=\\\"editor-field\\\"><input class=\\\"form-control text-box single-line\\\" foo=\\\"bar\\\" id=\\\"FieldPrefix_Property1\\\" name=\\\"FieldPrefix.Property1\\\" type=\\\"text\\\" value=\\\"p1\\\" /> </div>\" + Environment.NewLine\n              + \"<div class=\\\"editor-label\\\"><label for=\\\"FieldPrefix_Property2\\\">Property2</label></div>\" + Environment.NewLine\n              + \"<div class=\\\"editor-field\\\"><input class=\\\"form-control text-box single-line\\\" foo=\\\"bar\\\" id=\\\"FieldPrefix_Property2\\\" name=\\\"FieldPrefix.Property2\\\" type=\\\"text\\\" value=\\\"\\\" /> </div>\" + Environment.NewLine;\n\n            // Arrange\n            ObjectTemplateModel model = new ObjectTemplateModel { Property1 = \"p1\", Property2 = null };\n            HtmlHelper html = MakeHtmlHelper<ObjectTemplateModel>(model);\n            html.ViewContext.ViewBag.htmlAttributes = new { @class = \"form-control\", foo = \"bar\" };\n\n            // Act\n            string result = RunWithoutViewEngine(() =>\n                DefaultEditorTemplates.ObjectTemplate(html));\n\n            // Assert\n            Assert.Equal(expected, result);\n        }\n\n        [Fact]\n        public void ObjectTemplateWithModelError()\n        {\n            string expected =\n                \"<div class=\\\"editor-label\\\"><label for=\\\"FieldPrefix_Property1\\\">Property1</label></div>\" + Environment.NewLine\n              + \"<div class=\\\"editor-field\\\">Model = p1, ModelType = System.String, PropertyName = Property1, HtmlFieldName = Property1, TemplateName = (null), Mode = Edit, AdditionalViewData = (null) <span class=\\\"field-validation-error\\\">Error Message</span></div>\" + Environment.NewLine\n              + \"<div class=\\\"editor-label\\\"><label for=\\\"FieldPrefix_Property2\\\">Property2</label></div>\" + Environment.NewLine\n              + \"<div class=\\\"editor-field\\\">Model = (null), ModelType = System.String, PropertyName = Property2, HtmlFieldName = Property2, TemplateName = (null), Mode = Edit, AdditionalViewData = (null) </div>\" + Environment.NewLine;\n\n            // Arrange\n            ObjectTemplateModel model = new ObjectTemplateModel { Property1 = \"p1\", Property2 = null };\n            HtmlHelper html = MakeHtmlHelper<ObjectTemplateModel>(model);\n            html.ViewData.ModelState.AddModelError(\"FieldPrefix.Property1\", \"Error Message\");\n\n            // Act\n            string result = DefaultEditorTemplates.ObjectTemplate(html, SpyCallback);\n\n            // Assert\n            Assert.Equal(expected, result);\n        }\n\n        [Fact]\n        public void ObjectTemplateWithDisplayNameMetadata()\n        {\n            string expected =\n                \"<div class=\\\"editor-field\\\">Model = (null), ModelType = System.String, PropertyName = Property1, HtmlFieldName = Property1, TemplateName = (null), Mode = Edit, AdditionalViewData = (null) </div>\" + Environment.NewLine\n              + \"<div class=\\\"editor-label\\\"><label for=\\\"FieldPrefix_Property2\\\">Custom display name</label></div>\" + Environment.NewLine\n              + \"<div class=\\\"editor-field\\\">Model = (null), ModelType = System.String, PropertyName = Property2, HtmlFieldName = Property2, TemplateName = (null), Mode = Edit, AdditionalViewData = (null) </div>\" + Environment.NewLine;\n\n            // Arrange\n            ObjectTemplateModel model = new ObjectTemplateModel();\n            HtmlHelper html = MakeHtmlHelper<ObjectTemplateModel>(model);\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            Func<object> accessor = () => model;\n            Mock<ModelMetadata> metadata = new Mock<ModelMetadata>(provider.Object, null, accessor, typeof(ObjectTemplateModel), null);\n            ModelMetadata prop1Metadata = new ModelMetadata(provider.Object, typeof(ObjectTemplateModel), null, typeof(string), \"Property1\") { DisplayName = String.Empty };\n            ModelMetadata prop2Metadata = new ModelMetadata(provider.Object, typeof(ObjectTemplateModel), null, typeof(string), \"Property2\") { DisplayName = \"Custom display name\" };\n            html.ViewData.ModelMetadata = metadata.Object;\n            metadata.Setup(p => p.Properties).Returns(() => new[] { prop1Metadata, prop2Metadata });\n\n            // Act\n            string result = DefaultEditorTemplates.ObjectTemplate(html, SpyCallback);\n\n            // Assert\n            Assert.Equal(expected, result);\n        }\n\n        [Fact]\n        public void ObjectTemplateWithShowForEditorMetadata()\n        {\n            string expected =\n                \"<div class=\\\"editor-label\\\"><label for=\\\"FieldPrefix_Property1\\\">Property1</label></div>\" + Environment.NewLine\n              + \"<div class=\\\"editor-field\\\">Model = (null), ModelType = System.String, PropertyName = Property1, HtmlFieldName = Property1, TemplateName = (null), Mode = Edit, AdditionalViewData = (null) </div>\" + Environment.NewLine;\n\n            // Arrange\n            ObjectTemplateModel model = new ObjectTemplateModel();\n            HtmlHelper html = MakeHtmlHelper<ObjectTemplateModel>(model);\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            Func<object> accessor = () => model;\n            Mock<ModelMetadata> metadata = new Mock<ModelMetadata>(provider.Object, null, accessor, typeof(ObjectTemplateModel), null);\n            ModelMetadata prop1Metadata = new ModelMetadata(provider.Object, typeof(ObjectTemplateModel), null, typeof(string), \"Property1\") { ShowForEdit = true };\n            ModelMetadata prop2Metadata = new ModelMetadata(provider.Object, typeof(ObjectTemplateModel), null, typeof(string), \"Property2\") { ShowForEdit = false };\n            html.ViewData.ModelMetadata = metadata.Object;\n            metadata.Setup(p => p.Properties).Returns(() => new[] { prop1Metadata, prop2Metadata });\n\n            // Act\n            string result = DefaultEditorTemplates.ObjectTemplate(html, SpyCallback);\n\n            // Assert\n            Assert.Equal(expected, result);\n        }\n\n        [Fact]\n        public void ObjectTemplatePreventsRecursionOnModelValue()\n        {\n            string expected =\n                \"<div class=\\\"editor-label\\\"><label for=\\\"FieldPrefix_Property2\\\">Property2</label></div>\" + Environment.NewLine\n              + \"<div class=\\\"editor-field\\\">Model = propValue2, ModelType = System.String, PropertyName = Property2, HtmlFieldName = Property2, TemplateName = (null), Mode = Edit, AdditionalViewData = (null) </div>\" + Environment.NewLine;\n\n            // Arrange\n            ObjectTemplateModel model = new ObjectTemplateModel();\n            HtmlHelper html = MakeHtmlHelper<ObjectTemplateModel>(model);\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            Func<object> accessor = () => model;\n            Mock<ModelMetadata> metadata = new Mock<ModelMetadata>(provider.Object, null, accessor, typeof(ObjectTemplateModel), null);\n            ModelMetadata prop1Metadata = new ModelMetadata(provider.Object, typeof(ObjectTemplateModel), () => \"propValue1\", typeof(string), \"Property1\");\n            ModelMetadata prop2Metadata = new ModelMetadata(provider.Object, typeof(ObjectTemplateModel), () => \"propValue2\", typeof(string), \"Property2\");\n            html.ViewData.ModelMetadata = metadata.Object;\n            metadata.Setup(p => p.Properties).Returns(() => new[] { prop1Metadata, prop2Metadata });\n            html.ViewData.TemplateInfo.VisitedObjects.Add(\"propValue1\");\n\n            // Act\n            string result = DefaultEditorTemplates.ObjectTemplate(html, SpyCallback);\n\n            // Assert\n            Assert.Equal(expected, result);\n        }\n\n        [Fact]\n        public void ObjectTemplatePreventsRecursionOnModelTypeForNullModelValues()\n        {\n            string expected =\n                \"<div class=\\\"editor-label\\\"><label for=\\\"FieldPrefix_Property2\\\">Property2</label></div>\" + Environment.NewLine\n              + \"<div class=\\\"editor-field\\\">Model = propValue2, ModelType = System.String, PropertyName = Property2, HtmlFieldName = Property2, TemplateName = (null), Mode = Edit, AdditionalViewData = (null) </div>\" + Environment.NewLine;\n\n            // Arrange\n            ObjectTemplateModel model = new ObjectTemplateModel();\n            HtmlHelper html = MakeHtmlHelper<ObjectTemplateModel>(model);\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            Func<object> accessor = () => model;\n            Mock<ModelMetadata> metadata = new Mock<ModelMetadata>(provider.Object, null, accessor, typeof(ObjectTemplateModel), null);\n            ModelMetadata prop1Metadata = new ModelMetadata(provider.Object, typeof(ObjectTemplateModel), null, typeof(string), \"Property1\");\n            ModelMetadata prop2Metadata = new ModelMetadata(provider.Object, typeof(ObjectTemplateModel), () => \"propValue2\", typeof(string), \"Property2\");\n            html.ViewData.ModelMetadata = metadata.Object;\n            metadata.Setup(p => p.Properties).Returns(() => new[] { prop1Metadata, prop2Metadata });\n            html.ViewData.TemplateInfo.VisitedObjects.Add(typeof(string));\n\n            // Act\n            string result = DefaultEditorTemplates.ObjectTemplate(html, SpyCallback);\n\n            // Assert\n            Assert.Equal(expected, result);\n        }\n\n        [Fact]\n        public void ObjectTemplateDisplaysNullDisplayTextWithNullModelAndTemplateDepthGreaterThanOne()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper<ObjectTemplateModel>(null);\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(ObjectTemplateModel));\n            metadata.NullDisplayText = \"Null Display Text\";\n            metadata.SimpleDisplayText = \"Simple Display Text\";\n            html.ViewData.ModelMetadata = metadata;\n            html.ViewData.TemplateInfo.VisitedObjects.Add(\"foo\");\n            html.ViewData.TemplateInfo.VisitedObjects.Add(\"bar\");\n\n            // Act\n            string result = DefaultEditorTemplates.ObjectTemplate(html, SpyCallback);\n\n            // Assert\n            Assert.Equal(metadata.NullDisplayText, result);\n        }\n\n        [Theory]\n        [PropertyData(\"ConditionallyHtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void ObjectTemplateDisplaysSimpleDisplayTextWithNonNullModelTemplateDepthGreaterThanOne(\n            string simpleDisplayText,\n            bool htmlEncode,\n            string expectedResult)\n        {\n            // Arrange\n            ObjectTemplateModel model = new ObjectTemplateModel();\n            HtmlHelper html = MakeHtmlHelper<ObjectTemplateModel>(model);\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, typeof(ObjectTemplateModel));\n            html.ViewData.ModelMetadata = metadata;\n            metadata.NullDisplayText = \"Null Display Text\";\n            metadata.SimpleDisplayText = simpleDisplayText;\n            metadata.HtmlEncode = htmlEncode;\n\n            html.ViewData.TemplateInfo.VisitedObjects.Add(\"foo\");\n            html.ViewData.TemplateInfo.VisitedObjects.Add(\"bar\");\n\n            // Act\n            string result = DefaultEditorTemplates.ObjectTemplate(html, SpyCallback);\n\n            // Assert\n            Assert.Equal(expectedResult, result);\n        }\n\n        // PasswordTemplate\n\n        [Fact]\n        public void PasswordTemplateTests()\n        {\n            Assert.Equal(\n                \"<input class=\\\"text-box single-line password\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"password\\\" />\",\n                DefaultEditorTemplates.PasswordTemplate(MakeHtmlHelper<string>(\"Value\")));\n\n            Assert.Equal(\n                \"<input class=\\\"text-box single-line password\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"password\\\" />\",\n                DefaultEditorTemplates.PasswordTemplate(MakeHtmlHelper<string>(\"<script>alert('XSS!')</script>\")));\n        }\n\n        [Fact]\n        public void PasswordTemplate_ReturnsInputElement_IgnoresValues()\n        {\n            // Arrange\n            var expected = \"<input class=\\\"text-box single-line password\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" \" +\n                \"type=\\\"password\\\" />\";\n\n            // Template ignores Model and FormattedModelValue.\n            var helper = MakeHtmlHelper<string>(model: \"Model string\", formattedModelValue: \"Formatted string\");\n\n            var viewData = helper.ViewData;\n            var templateInfo = viewData.TemplateInfo;\n            templateInfo.HtmlFieldPrefix = \"FieldPrefix\";\n\n            // Template ignores ModelState and ViewData.\n            var valueProviderResult = new ValueProviderResult(\n                \"Raw model string\",\n                \"Attempted model string\",\n                CultureInfo.InvariantCulture);\n            viewData.ModelState.SetModelValue(\"FieldPrefix\", valueProviderResult);\n            viewData[\"FieldPrefix\"] = \"ViewData string\";\n\n            // Act\n            var result = DefaultEditorTemplates.PasswordTemplate(helper);\n\n            // Assert\n            Assert.Equal(expected, result);\n        }\n\n        [Fact]\n        public void PasswordTemplate_ReturnsInputElement_UsesHtmlAttributes()\n        {\n            // Arrange\n            var expected = \"<input class=\\\"super text-box single-line password\\\" id=\\\"FieldPrefix\\\" \" +\n                \"name=\\\"FieldPrefix\\\" type=\\\"password\\\" value=\\\"Html attributes string\\\" />\";\n            var helper = MakeHtmlHelper<string>(model: null);\n            var viewData = helper.ViewData;\n            var templateInfo = viewData.TemplateInfo;\n            templateInfo.HtmlFieldPrefix = \"FieldPrefix\";\n\n            viewData[\"htmlAttributes\"] = new { @class = \"super\", value = \"Html attributes string\" };\n\n            // Act\n            var result = DefaultEditorTemplates.PasswordTemplate(helper);\n\n            // Assert\n            Assert.Equal(expected, result);\n        }\n\n        public static TheoryDataSet<object, string> PasswordTemplateHtmlAttributeData\n        {\n            get\n            {\n                return new TheoryDataSet<object, string>\n                {\n                    {\n                        new { @class = \"form-control\" },\n                        \"<input class=\\\"form-control text-box single-line password\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"password\\\" />\"\n                    },\n                    {\n                        new { @class = \"form-control\", custom = \"foo\" },\n                        \"<input class=\\\"form-control text-box single-line password\\\" custom=\\\"foo\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"password\\\" />\"\n                    }\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"PasswordTemplateHtmlAttributeData\")]\n        public void PasswordTemplate_AddsHtmlAttributes(object htmlAttributes, string expectedHtml)\n        {\n            var htmlHelper = MakeHtmlHelper<string>(\"Value\");\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = htmlAttributes;\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.PasswordTemplate(htmlHelper));\n        }\n\n        [Theory]\n        [PropertyData(\"PasswordTemplateHtmlAttributeData\")]\n        public void PasswordTemplate_AddsHtmlAttributesDictionary(object htmlAttributes, string expectedHtml)\n        {\n            var htmlHelper = MakeHtmlHelper<string>(\"Value\");\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.PasswordTemplate(htmlHelper));\n        }\n\n        [Fact]\n        public void ObjectTemplateWithHiddenHtml()\n        {\n            string expected = \"Model = propValue1, ModelType = System.String, PropertyName = Property1, HtmlFieldName = Property1, TemplateName = (null), Mode = Edit, AdditionalViewData = (null)\";\n\n            // Arrange\n            ObjectTemplateModel model = new ObjectTemplateModel();\n            HtmlHelper html = MakeHtmlHelper<ObjectTemplateModel>(model);\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            Func<object> accessor = () => model;\n            Mock<ModelMetadata> metadata = new Mock<ModelMetadata>(provider.Object, null, accessor, typeof(ObjectTemplateModel), null);\n            ModelMetadata prop1Metadata = new ModelMetadata(provider.Object, typeof(ObjectTemplateModel), () => \"propValue1\", typeof(string), \"Property1\") { HideSurroundingHtml = true };\n            html.ViewData.ModelMetadata = metadata.Object;\n            metadata.Setup(p => p.Properties).Returns(() => new[] { prop1Metadata });\n\n            // Act\n            string result = DefaultEditorTemplates.ObjectTemplate(html, SpyCallback);\n\n            // Assert\n            Assert.Equal(expected, result);\n        }\n\n        [Fact]\n        public void ObjectTemplateAllPropertiesFromEntityObjectAreHidden()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper<ObjectTemplateModel>(new MyEntityObject());\n\n            // Act\n            string result = DefaultEditorTemplates.ObjectTemplate(html, SpyCallback);\n\n            // Assert\n            Assert.Equal(String.Empty, result);\n        }\n\n        private class MyEntityObject : EntityObject\n        {\n        }\n\n        // StringTemplate\n\n        [Fact]\n        public void StringTemplateTests()\n        {\n            Assert.Equal(\n                \"<input class=\\\"text-box single-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"text\\\" value=\\\"Value\\\" />\",\n                DefaultEditorTemplates.StringTemplate(MakeHtmlHelper<string>(\"Value\")));\n\n            Assert.Equal(\n                \"<input class=\\\"text-box single-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"text\\\" value=\\\"&lt;script>alert(&#39;XSS!&#39;)&lt;/script>\\\" />\",\n                DefaultEditorTemplates.StringTemplate(MakeHtmlHelper<string>(\"<script>alert('XSS!')</script>\")));\n        }\n\n        public static TheoryDataSet<object, string> StringTemplateHtmlAttributeData\n        {\n            get\n            {\n                return new TheoryDataSet<object, string>\n                {\n                    {\n                        new { @class = \"form-control\" },\n                        \"<input class=\\\"form-control text-box single-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"text\\\" value=\\\"Value\\\" />\"\n                    },\n                    {\n                        new { @class = \"form-control\", custom = \"foo\" },\n                        \"<input class=\\\"form-control text-box single-line\\\" custom=\\\"foo\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"text\\\" value=\\\"Value\\\" />\"\n                    }\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"StringTemplateHtmlAttributeData\")]\n        public void StringTemplate_AddsHtmlAttributes(object htmlAttributes, string expectedHtml)\n        {\n            var htmlHelper = MakeHtmlHelper<string>(\"Value\");\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = htmlAttributes;\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.StringTemplate(htmlHelper));\n        }\n\n        [Theory]\n        [PropertyData(\"StringTemplateHtmlAttributeData\")]\n        public void StringTemplate_AddsHtmlAttributesDictionary(object htmlAttributes, string expectedHtml)\n        {\n            var htmlHelper = MakeHtmlHelper<string>(\"Value\");\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.StringTemplate(htmlHelper));\n        }\n\n        // PhoneNumberInputTemplate\n\n        [Fact]\n        public void PhoneNumberInputTemplateTests()\n        {\n            Assert.Equal(\n                \"<input class=\\\"text-box single-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"tel\\\" value=\\\"Value\\\" />\",\n                DefaultEditorTemplates.PhoneNumberInputTemplate(MakeHtmlHelper<string>(\"Value\")));\n\n            Assert.Equal(\n                \"<input class=\\\"text-box single-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"tel\\\" value=\\\"&lt;script>alert(&#39;XSS!&#39;)&lt;/script>\\\" />\",\n                DefaultEditorTemplates.PhoneNumberInputTemplate(MakeHtmlHelper<string>(\"<script>alert('XSS!')</script>\")));\n        }\n\n        public static TheoryDataSet<object, string> PhoneNumberInputTemplateHtmlAttributeData\n        {\n            get\n            {\n                return new TheoryDataSet<object, string>\n                {\n                    {\n                        new { @class = \"form-control\" },\n                        \"<input class=\\\"form-control text-box single-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"tel\\\" value=\\\"Value\\\" />\"\n                    },\n                    {\n                        new { @class = \"form-control\", custom = \"foo\" },\n                        \"<input class=\\\"form-control text-box single-line\\\" custom=\\\"foo\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"tel\\\" value=\\\"Value\\\" />\"\n                    }\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"PhoneNumberInputTemplateHtmlAttributeData\")]\n        public void PhoneNumberInputTemplate_AddsHtmlAttributes(object htmlAttributes, string expectedHtml)\n        {\n            var htmlHelper = MakeHtmlHelper<string>(\"Value\");\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = htmlAttributes;\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.PhoneNumberInputTemplate(htmlHelper));\n        }\n\n        [Theory]\n        [PropertyData(\"PhoneNumberInputTemplateHtmlAttributeData\")]\n        public void PhoneNumberInputTemplate_AddsHtmlAttributesDictionary(object htmlAttributes, string expectedHtml)\n        {\n            var htmlHelper = MakeHtmlHelper<string>(\"Value\");\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.PhoneNumberInputTemplate(htmlHelper));\n        }\n\n        // UrlInputTemplate\n\n        [Fact]\n        public void UrlInputTemplateTests()\n        {\n            Assert.Equal(\n                \"<input class=\\\"text-box single-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"url\\\" value=\\\"Value\\\" />\",\n                DefaultEditorTemplates.UrlInputTemplate(MakeHtmlHelper<string>(\"Value\")));\n\n            Assert.Equal(\n                \"<input class=\\\"text-box single-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"url\\\" value=\\\"&lt;script>alert(&#39;XSS!&#39;)&lt;/script>\\\" />\",\n                DefaultEditorTemplates.UrlInputTemplate(MakeHtmlHelper<string>(\"<script>alert('XSS!')</script>\")));\n        }\n\n        public static TheoryDataSet<object, string> UrlInputTemplateHtmlAttributeData\n        {\n            get\n            {\n                return new TheoryDataSet<object, string>\n                {\n                    {\n                        new { @class = \"form-control\" },\n                        \"<input class=\\\"form-control text-box single-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"url\\\" value=\\\"Value\\\" />\"\n                    },\n                    {\n                        new { @class = \"form-control\", custom = \"foo\" },\n                        \"<input class=\\\"form-control text-box single-line\\\" custom=\\\"foo\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"url\\\" value=\\\"Value\\\" />\"\n                    }\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"UrlInputTemplateHtmlAttributeData\")]\n        public void UrlInputTemplate_AddsHtmlAttributes(object htmlAttributes, string expectedHtml)\n        {\n            var htmlHelper = MakeHtmlHelper<string>(\"Value\");\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = htmlAttributes;\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.UrlInputTemplate(htmlHelper));\n        }\n\n        [Theory]\n        [PropertyData(\"UrlInputTemplateHtmlAttributeData\")]\n        public void UrlInputTemplate_AddsHtmlAttributesDictionary(object htmlAttributes, string expectedHtml)\n        {\n            var htmlHelper = MakeHtmlHelper<string>(\"Value\");\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.UrlInputTemplate(htmlHelper));\n        }\n\n        // EmailAddressInputTemplate\n\n        [Fact]\n        public void EmailAddressTemplateTests()\n        {\n            Assert.Equal(\n                \"<input class=\\\"text-box single-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"email\\\" value=\\\"Value\\\" />\",\n                DefaultEditorTemplates.EmailAddressInputTemplate(MakeHtmlHelper<string>(\"Value\")));\n\n            Assert.Equal(\n                \"<input class=\\\"text-box single-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"email\\\" value=\\\"&lt;script>alert(&#39;XSS!&#39;)&lt;/script>\\\" />\",\n                DefaultEditorTemplates.EmailAddressInputTemplate(MakeHtmlHelper<string>(\"<script>alert('XSS!')</script>\")));\n        }\n\n        public static TheoryDataSet<object, string> EmailAddressInputTemplateHtmlAttributeData\n        {\n            get\n            {\n                return new TheoryDataSet<object, string>\n                {\n                    {\n                        new { @class = \"form-control\" },\n                        \"<input class=\\\"form-control text-box single-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"email\\\" value=\\\"Value\\\" />\"\n                    },\n                    {\n                        new { @class = \"form-control\", custom = \"foo\" },\n                        \"<input class=\\\"form-control text-box single-line\\\" custom=\\\"foo\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"email\\\" value=\\\"Value\\\" />\"\n                    }\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"EmailAddressInputTemplateHtmlAttributeData\")]\n        public void EmailAddressInputTemplate_AddsHtmlAttributes(object htmlAttributes, string expectedHtml)\n        {\n            var htmlHelper = MakeHtmlHelper<string>(\"Value\");\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = htmlAttributes;\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.EmailAddressInputTemplate(htmlHelper));\n        }\n\n        [Theory]\n        [PropertyData(\"EmailAddressInputTemplateHtmlAttributeData\")]\n        public void EmailAddressInputTemplate_AddsHtmlAttributesDictionary(object htmlAttributes, string expectedHtml)\n        {\n            var htmlHelper = MakeHtmlHelper<string>(\"Value\");\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.EmailAddressInputTemplate(htmlHelper));\n        }\n\n        [Fact]\n        public void DateTimeInputTemplateTests()\n        {\n            var type = \"datetime\";\n            Assert.Equal(\n                GetExpectedInputTag(type, \"Value\"),\n                DefaultEditorTemplates.DateTimeInputTemplate(MakeHtmlHelper<string>(\"Value\")));\n\n            Assert.Equal(\n                GetExpectedInputTag(type, \"&lt;script>alert(&#39;XSS!&#39;)&lt;/script>\"),\n                DefaultEditorTemplates.DateTimeInputTemplate(MakeHtmlHelper<string>(\"<script>alert('XSS!')</script>\")));\n\n            var epocInLocalTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).ToLocalTime();\n            var helper = MakeHtmlHelper<DateTime>(epocInLocalTime);\n\n            Assert.Equal(\n                GetExpectedInputTag(type, epocInLocalTime.ToString(CultureInfo.CurrentCulture)),\n                DefaultEditorTemplates.DateTimeInputTemplate(helper));\n\n            helper.Html5DateRenderingMode = Html5DateRenderingMode.Rfc3339;\n\n            Assert.Equal(\n                GetExpectedInputTag(type, epocInLocalTime.ToString(\"yyyy-MM-ddTHH:mm:ss.fffK\")),\n                DefaultEditorTemplates.DateTimeInputTemplate(helper));\n\n            // Override FormattedModelValue and let helper think this string came from a default [DataType] attribute.\n            helper.ViewData.TemplateInfo.FormattedModelValue = \"Another string\";\n\n            Assert.Equal(\n                GetExpectedInputTag(type, epocInLocalTime.ToString(\"yyyy-MM-ddTHH:mm:ss.fffK\")),\n                DefaultEditorTemplates.DateTimeInputTemplate(helper));\n\n            // Override again but tell helper this string was explicitly user-provided.\n            helper.ViewData.ModelMetadata.HasNonDefaultEditFormat = true;\n            helper.ViewData.TemplateInfo.FormattedModelValue = \"Another string\";\n\n            Assert.Equal(\n                GetExpectedInputTag(type, \"Another string\"),\n                DefaultEditorTemplates.DateTimeInputTemplate(helper));\n        }\n\n        public static TheoryDataSet<object, string> DateTimeInputTemplateHtmlAttributeData\n        {\n            get\n            {\n                return new TheoryDataSet<object, string>\n                {\n                    {\n                        new { @class = \"form-control\" },\n                        \"<input class=\\\"form-control text-box single-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"datetime\\\" value=\\\"Value\\\" />\"\n                    },\n                    {\n                        new { @class = \"form-control\", custom = \"foo\" },\n                        \"<input class=\\\"form-control text-box single-line\\\" custom=\\\"foo\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"datetime\\\" value=\\\"Value\\\" />\"\n                    }\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"DateTimeInputTemplateHtmlAttributeData\")]\n        public void DateTimeInputTemplate_AddsHtmlAttributes(object htmlAttributes, string expectedHtml)\n        {\n            var htmlHelper = MakeHtmlHelper<DateTime>(\"Value\");\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = htmlAttributes;\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.DateTimeInputTemplate(htmlHelper));\n        }\n\n        [Theory]\n        [PropertyData(\"DateTimeInputTemplateHtmlAttributeData\")]\n        public void DateTimeInputTemplate_AddsHtmlAttributesDictionary(object htmlAttributes, string expectedHtml)\n        {\n            var htmlHelper = MakeHtmlHelper<DateTime>(\"Value\");\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.DateTimeInputTemplate(htmlHelper));\n        }\n\n        [Fact]\n        public void DateTimeLocalInputTemplateTests()\n        {\n            var type = \"datetime-local\";\n            Assert.Equal(\n                GetExpectedInputTag(type, \"Value\"),\n                DefaultEditorTemplates.DateTimeLocalInputTemplate(MakeHtmlHelper<string>(\"Value\")));\n\n            Assert.Equal(\n                GetExpectedInputTag(type, \"&lt;script>alert(&#39;XSS!&#39;)&lt;/script>\"),\n                DefaultEditorTemplates.DateTimeLocalInputTemplate(MakeHtmlHelper<string>(\"<script>alert('XSS!')</script>\")));\n\n            var epocInLocalTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).ToLocalTime();\n            var helper = MakeHtmlHelper<DateTime>(epocInLocalTime);\n\n            Assert.Equal(\n                GetExpectedInputTag(type, epocInLocalTime.ToString(CultureInfo.CurrentCulture)),\n                DefaultEditorTemplates.DateTimeLocalInputTemplate(helper));\n\n            helper.Html5DateRenderingMode = Html5DateRenderingMode.Rfc3339;\n\n            Assert.Equal(\n                GetExpectedInputTag(type, epocInLocalTime.ToString(\"yyyy-MM-ddTHH:mm:ss.fff\")),\n                DefaultEditorTemplates.DateTimeLocalInputTemplate(helper));\n\n            // Override FormattedModelValue and let helper think this string came from a default [DataType] attribute.\n            helper.ViewData.TemplateInfo.FormattedModelValue = \"Another string\";\n\n            Assert.Equal(\n                GetExpectedInputTag(type, epocInLocalTime.ToString(\"yyyy-MM-ddTHH:mm:ss.fff\")),\n                DefaultEditorTemplates.DateTimeLocalInputTemplate(helper));\n\n            // Override again but tell helper this string was explicitly user-provided.\n            helper.ViewData.ModelMetadata.HasNonDefaultEditFormat = true;\n            helper.ViewData.TemplateInfo.FormattedModelValue = \"Another string\";\n\n            Assert.Equal(\n                GetExpectedInputTag(type, \"Another string\"),\n                DefaultEditorTemplates.DateTimeLocalInputTemplate(helper));\n        }\n\n        public static TheoryDataSet<object, string> DateTimeLocalInputTemplateHtmlAttributeData\n        {\n            get\n            {\n                return new TheoryDataSet<object, string>\n                {\n                    {\n                        new { @class = \"form-control\" },\n                        \"<input class=\\\"form-control text-box single-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"datetime-local\\\" value=\\\"Value\\\" />\"\n                    },\n                    {\n                        new { @class = \"form-control\", custom = \"foo\" },\n                        \"<input class=\\\"form-control text-box single-line\\\" custom=\\\"foo\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"datetime-local\\\" value=\\\"Value\\\" />\"\n                    }\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"DateTimeLocalInputTemplateHtmlAttributeData\")]\n        public void DateTimeLocalInputTemplate_AddsHtmlAttributes(object htmlAttributes, string expectedHtml)\n        {\n            var htmlHelper = MakeHtmlHelper<DateTime>(\"Value\");\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = htmlAttributes;\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.DateTimeLocalInputTemplate(htmlHelper));\n        }\n\n        [Theory]\n        [PropertyData(\"DateTimeLocalInputTemplateHtmlAttributeData\")]\n        public void DateTimeLocalInputTemplate_AddsHtmlAttributesDictionary(object htmlAttributes, string expectedHtml)\n        {\n            var htmlHelper = MakeHtmlHelper<DateTime>(\"Value\");\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.DateTimeLocalInputTemplate(htmlHelper));\n        }\n\n        [Fact]\n        public void DateInputTemplateTests()\n        {\n            var type = \"date\";\n            Assert.Equal(\n                GetExpectedInputTag(type, \"Value\"),\n                DefaultEditorTemplates.DateInputTemplate(MakeHtmlHelper<string>(\"Value\")));\n\n            Assert.Equal(\n                GetExpectedInputTag(type, \"&lt;script>alert(&#39;XSS!&#39;)&lt;/script>\"),\n                DefaultEditorTemplates.DateInputTemplate(MakeHtmlHelper<string>(\"<script>alert('XSS!')</script>\")));\n\n            var epocInLocalTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).ToLocalTime();\n            var helper = MakeHtmlHelper<DateTime>(epocInLocalTime);\n\n            Assert.Equal(\n                GetExpectedInputTag(type, epocInLocalTime.ToString(CultureInfo.CurrentCulture)),\n                DefaultEditorTemplates.DateInputTemplate(helper));\n\n            helper.Html5DateRenderingMode = Html5DateRenderingMode.Rfc3339;\n\n            Assert.Equal(\n                GetExpectedInputTag(type, epocInLocalTime.ToString(\"yyyy-MM-dd\")),\n                DefaultEditorTemplates.DateInputTemplate(helper));\n\n            // Override FormattedModelValue and let helper think this string came from a default [DataType] attribute.\n            helper.ViewData.TemplateInfo.FormattedModelValue = \"Another string\";\n\n            Assert.Equal(\n                GetExpectedInputTag(type, epocInLocalTime.ToString(\"yyyy-MM-dd\")),\n                DefaultEditorTemplates.DateInputTemplate(helper));\n\n            // Override again but tell helper this string was explicitly user-provided.\n            helper.ViewData.ModelMetadata.HasNonDefaultEditFormat = true;\n            helper.ViewData.TemplateInfo.FormattedModelValue = \"Another string\";\n\n            Assert.Equal(\n                GetExpectedInputTag(type, \"Another string\"),\n                DefaultEditorTemplates.DateInputTemplate(helper));\n        }\n\n        public static TheoryDataSet<object, string> DateInputTemplateHtmlAttributeData\n        {\n            get\n            {\n                return new TheoryDataSet<object, string>\n                {\n                    {\n                        new { @class = \"form-control\" },\n                        \"<input class=\\\"form-control text-box single-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"date\\\" value=\\\"Value\\\" />\"\n                    },\n                    {\n                        new { @class = \"form-control\", custom = \"foo\" },\n                        \"<input class=\\\"form-control text-box single-line\\\" custom=\\\"foo\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"date\\\" value=\\\"Value\\\" />\"\n                    }\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"DateInputTemplateHtmlAttributeData\")]\n        public void DateInputTemplate_AddsHtmlAttributes(object htmlAttributes, string expectedHtml)\n        {\n            var htmlHelper = MakeHtmlHelper<DateTime>(\"Value\");\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = htmlAttributes;\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.DateInputTemplate(htmlHelper));\n        }\n\n        [Theory]\n        [PropertyData(\"DateInputTemplateHtmlAttributeData\")]\n        public void DateInputTemplate_AddsHtmlAttributesDictionary(object htmlAttributes, string expectedHtml)\n        {\n            var htmlHelper = MakeHtmlHelper<DateTime>(\"Value\");\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.DateInputTemplate(htmlHelper));\n        }\n\n        [Fact]\n        public void TimeInputTemplateTests()\n        {\n            var type = \"time\";\n            Assert.Equal(\n                GetExpectedInputTag(type, \"Value\"),\n                DefaultEditorTemplates.TimeInputTemplate(MakeHtmlHelper<string>(\"Value\")));\n\n            Assert.Equal(\n                GetExpectedInputTag(type, \"&lt;script>alert(&#39;XSS!&#39;)&lt;/script>\"),\n                DefaultEditorTemplates.TimeInputTemplate(MakeHtmlHelper<string>(\"<script>alert('XSS!')</script>\")));\n\n            var epocInLocalTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).ToLocalTime();\n            var helper = MakeHtmlHelper<DateTime>(epocInLocalTime);\n\n            Assert.Equal(\n                GetExpectedInputTag(type, epocInLocalTime.ToString(CultureInfo.CurrentCulture)),\n                DefaultEditorTemplates.TimeInputTemplate(helper));\n\n            helper.Html5DateRenderingMode = Html5DateRenderingMode.Rfc3339;\n\n            Assert.Equal(\n                GetExpectedInputTag(type, epocInLocalTime.ToString(\"HH:mm:ss.fff\")),\n                DefaultEditorTemplates.TimeInputTemplate(helper));\n\n            // Override FormattedModelValue and let helper think this string came from a default [DataType] attribute.\n            helper.ViewData.TemplateInfo.FormattedModelValue = \"Another string\";\n\n            Assert.Equal(\n                GetExpectedInputTag(type, epocInLocalTime.ToString(\"HH:mm:ss.fff\")),\n                DefaultEditorTemplates.TimeInputTemplate(helper));\n\n            // Override again but tell helper this string was explicitly user-provided.\n            helper.ViewData.ModelMetadata.HasNonDefaultEditFormat = true;\n            helper.ViewData.TemplateInfo.FormattedModelValue = \"Another string\";\n\n            Assert.Equal(\n                GetExpectedInputTag(type, \"Another string\"),\n                DefaultEditorTemplates.TimeInputTemplate(helper));\n        }\n\n        public static TheoryDataSet<object, string> TimeInputTemplateHtmlAttributeData\n        {\n            get\n            {\n                return new TheoryDataSet<object, string>\n                {\n                    {\n                        new { @class = \"form-control\" },\n                        \"<input class=\\\"form-control text-box single-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"time\\\" value=\\\"Value\\\" />\"\n                    },\n                    {\n                        new { @class = \"form-control\", custom = \"foo\" },\n                        \"<input class=\\\"form-control text-box single-line\\\" custom=\\\"foo\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"time\\\" value=\\\"Value\\\" />\"\n                    }\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"TimeInputTemplateHtmlAttributeData\")]\n        public void TimeInputTemplate_AddsHtmlAttributes(object htmlAttributes, string expectedHtml)\n        {\n            var htmlHelper = MakeHtmlHelper<DateTime>(\"Value\");\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = htmlAttributes;\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.TimeInputTemplate(htmlHelper));\n        }\n\n        [Theory]\n        [PropertyData(\"TimeInputTemplateHtmlAttributeData\")]\n        public void TimeInputTemplate_AddsHtmlAttributesDictionary(object htmlAttributes, string expectedHtml)\n        {\n            var htmlHelper = MakeHtmlHelper<DateTime>(\"Value\");\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.TimeInputTemplate(htmlHelper));\n        }\n\n        // NumberInputTemplate\n\n        [Fact]\n        public void NumberInputTemplateTests()\n        {\n            Assert.Equal(\n                \"<input class=\\\"text-box single-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"number\\\" value=\\\"Value\\\" />\",\n                DefaultEditorTemplates.NumberInputTemplate(MakeHtmlHelper<string>(\"Value\")));\n\n            Assert.Equal(\n                \"<input class=\\\"text-box single-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"number\\\" value=\\\"&lt;script>alert(&#39;XSS!&#39;)&lt;/script>\\\" />\",\n                DefaultEditorTemplates.NumberInputTemplate(MakeHtmlHelper<string>(\"<script>alert('XSS!')</script>\")));\n        }\n\n        public static TheoryDataSet<object, string> NumberInputTemplateHtmlAttributeData\n        {\n            get\n            {\n                return new TheoryDataSet<object, string>\n                {\n                    {\n                        new { @class = \"form-control\" },\n                        \"<input class=\\\"form-control text-box single-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"number\\\" value=\\\"10\\\" />\"\n                    },\n                    {\n                        new { @class = \"form-control\", custom = \"foo\" },\n                        \"<input class=\\\"form-control text-box single-line\\\" custom=\\\"foo\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"number\\\" value=\\\"10\\\" />\"\n                    }\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"NumberInputTemplateHtmlAttributeData\")]\n        public void NumberInputTemplate_AddsHtmlAttributes(object htmlAttributes, string expectedHtml)\n        {\n            var htmlHelper = MakeHtmlHelper<int>(10);\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = htmlAttributes;\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.NumberInputTemplate(htmlHelper));\n        }\n\n        [Theory]\n        [PropertyData(\"NumberInputTemplateHtmlAttributeData\")]\n        public void NumberInputTemplate_AddsHtmlAttributesDictionary(object htmlAttributes, string expectedHtml)\n        {\n            var htmlHelper = MakeHtmlHelper<int>(10);\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.NumberInputTemplate(htmlHelper));\n        }\n\n        // ColorInputTemplate\n\n        [Fact]\n        public void ColorInputTemplateTests()\n        {\n            Assert.Equal(\n                \"<input class=\\\"text-box single-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"color\\\" value=\\\"#33F4CC\\\" />\",\n                DefaultEditorTemplates.ColorInputTemplate(MakeHtmlHelper<string>(\"#33F4CC\")));\n\n            var color = Color.FromArgb(0x33, 0xf4, 0xcc);\n            Assert.Equal(\n                \"<input class=\\\"text-box single-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"color\\\" value=\\\"#33F4CC\\\" />\",\n                DefaultEditorTemplates.ColorInputTemplate(MakeHtmlHelper<Color>(color)));\n\n            Assert.Equal(\n                \"<input class=\\\"text-box single-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"color\\\" value=\\\"&lt;script>alert(&#39;XSS!&#39;)&lt;/script>\\\" />\",\n                DefaultEditorTemplates.ColorInputTemplate(MakeHtmlHelper<string>(\"<script>alert('XSS!')</script>\")));\n        }\n\n        public static TheoryDataSet<object, string> ColorInputTemplateHtmlAttributeData\n        {\n            get\n            {\n                return new TheoryDataSet<object, string>\n                {\n                    {\n                        new { @class = \"form-control\" },\n                        \"<input class=\\\"form-control text-box single-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"color\\\" value=\\\"#33F4CC\\\" />\"\n                    },\n                    {\n                        new { @class = \"form-control\", custom = \"foo\" },\n                        \"<input class=\\\"form-control text-box single-line\\\" custom=\\\"foo\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"color\\\" value=\\\"#33F4CC\\\" />\"\n                    }\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"ColorInputTemplateHtmlAttributeData\")]\n        public void ColorInputTemplate_AddsHtmlAttributes(object htmlAttributes, string expectedHtml)\n        {\n            var color = Color.FromArgb(0x33, 0xf4, 0xcc);\n            var htmlHelper = MakeHtmlHelper<Color>(color);\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = htmlAttributes;\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.ColorInputTemplate(htmlHelper));\n        }\n\n        [Theory]\n        [PropertyData(\"ColorInputTemplateHtmlAttributeData\")]\n        public void ColorInputTemplate_AddsHtmlAttributesDictionary(object htmlAttributes, string expectedHtml)\n        {\n            var color = Color.FromArgb(0x33, 0xf4, 0xcc);\n            var htmlHelper = MakeHtmlHelper<Color>(color);\n            htmlHelper.ViewContext.ViewBag.htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);\n            Assert.Equal(\n                expectedHtml,\n                DefaultEditorTemplates.ColorInputTemplate(htmlHelper));\n        }\n\n        // Helpers\n\n        private static string GetExpectedInputTag(string type, string value)\n        {\n            return string.Format(\"<input class=\\\"text-box single-line\\\" id=\\\"FieldPrefix\\\" name=\\\"FieldPrefix\\\" type=\\\"{0}\\\" value=\\\"{1}\\\" />\", type, value);\n        }\n\n        private HtmlHelper MakeHtmlHelper<TModel>(object model)\n        {\n            return MakeHtmlHelper<TModel>(model, model);\n        }\n\n        private HtmlHelper MakeHtmlHelper<TModel>(object model, object formattedModelValue)\n        {\n            ViewDataDictionary viewData = new ViewDataDictionary(model);\n            viewData.TemplateInfo.HtmlFieldPrefix = \"FieldPrefix\";\n            viewData.TemplateInfo.FormattedModelValue = formattedModelValue;\n            viewData.ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => model, typeof(TModel));\n\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(o => o.Items).Returns(new Hashtable());\n\n            ViewContext viewContext = new ViewContext(new ControllerContext { HttpContext = mockHttpContext.Object }, new DummyView(), viewData, new TempDataDictionary(), new StringWriter())\n            {\n                HttpContext = mockHttpContext.Object\n            };\n\n            // A new helper instance, is executing within a new scope, so it needs to be reset.\n            ScopeStorage.CurrentProvider.CurrentScope = new ScopeStorageDictionary();\n\n            return new HtmlHelper(viewContext, new SimpleViewDataContainer(viewData));\n        }\n\n        private class DummyView : IView\n        {\n            public void Render(ViewContext viewContext, TextWriter writer)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private string RunWithoutViewEngine(Func<string> testCode)\n        {\n            lock (ViewEngines.Engines)\n            {\n                List<IViewEngine> viewEngines = new List<IViewEngine>(ViewEngines.Engines);\n                ViewEngines.Engines.Clear();\n\n                try\n                {\n                    return testCode();\n                }\n                finally\n                {\n                    foreach (var engine in viewEngines)\n                    {\n                        ViewEngines.Engines.Add(engine);\n                    }\n                }\n            }\n        }\n\n        public void Dispose()\n        {\n            // Reset ScopeStorage (written via e.g. ScopeStorage.CurrentProvider.CurrentScope) between tests to avoid unexpected interactions.\n            ScopeStorage.CurrentProvider = new StaticScopeStorageProvider();\n            ScopeStorage.GlobalScope.Clear();\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Mvc.Test/Html/Test/DisplayExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\nusing Moq;\n\nnamespace System.Web.Mvc.Html.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")]\n    public class DisplayExtensionsTest\n    {\n        [Fact]\n        public void DisplayNullExpressionThrows()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => MvcHelper.GetHtmlHelper().Display(expression: null),\n                \"expression\");\n        }\n\n        [Theory]\n        [PropertyData(\"ConditionallyHtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void CollectionTemplateWrappingObjectTemplate_EncodesSimpleDisplayTextOfItems_IfHtmlEncode(\n            string text,\n            bool htmlEncode,\n            string expectedResult)\n        {\n            // Arrange\n            var innerModel = new ObjectTemplateModel\n            {\n                Property1 = text,           // SimpleDisplayText uses first property by default.\n            };\n            var model = new[] { innerModel, innerModel, };\n            var viewData = new ViewDataDictionary<ObjectTemplateModel[]>(model);\n            var html = MvcHelper.GetHtmlHelper(viewData);\n\n            // GetHtmlHelper does not mock enough of the ViewContext for TemplateHelpers use.\n            var viewContext = Mock.Get(html.ViewContext);\n            viewContext.Setup(c => c.TempData).Returns(new TempDataDictionary());\n            viewContext.Setup(c => c.View).Returns(new DummyView());\n            viewContext.Setup(c => c.Writer).Returns(TextWriter.Null);\n\n            // Developers might need to do something similar (including MetadataOverrideScope or another approach\n            // replacing ModelMetadataProviders.Current) since for example [DisplayFormat] cannot be applied to a class.\n            var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => null, typeof(ObjectTemplateModel));\n            metadata.HtmlEncode = htmlEncode;\n\n            string displayResult;\n            string displayForResult;\n            string displayForModelResult;\n            using (new TemplateHelpersSafeScope())\n            {\n                using (new MetadataOverrideScope(metadata))\n                {\n                    // Act\n                    displayResult = html.Display(\"\").ToHtmlString();\n                    displayForResult = html.DisplayFor(m => m).ToHtmlString();\n                    displayForModelResult = html.DisplayForModel().ToHtmlString();\n                }\n            }\n\n            // Assert\n            Assert.Equal(expectedResult + expectedResult, displayResult);\n            Assert.Equal(expectedResult + expectedResult, displayForResult);\n            Assert.Equal(expectedResult + expectedResult, displayForModelResult);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeAndHtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void EmailTemplate_AttributeAndHtmlEncodes(\n            string text,\n            bool htmlEncode,\n            string attributeEncodedText,\n            string htmlEncodedText)\n        {\n            // Arrange\n            var expectedResult = \"<a href=\\\"mailto:\" + attributeEncodedText + \"\\\">\" + htmlEncodedText + \"</a>\";\n            var viewData = new ViewDataDictionary<string>(text);\n            var html = MvcHelper.GetHtmlHelper(viewData);\n\n            var viewContext = Mock.Get(html.ViewContext);\n            viewContext.Setup(c => c.TempData).Returns(new TempDataDictionary());\n            viewContext.Setup(c => c.View).Returns(new DummyView());\n            viewContext.Setup(c => c.Writer).Returns(TextWriter.Null);\n\n            var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => null, typeof(string));\n            metadata.TemplateHint = \"EmailAddress\";\n            metadata.HtmlEncode = htmlEncode;\n\n            string displayResult;\n            string displayForResult;\n            string displayForModelResult;\n            using (new TemplateHelpersSafeScope())\n            {\n                using (new MetadataOverrideScope(metadata))\n                {\n                    // Act\n                    displayResult = html.Display(\"\").ToHtmlString();\n                    displayForResult = html.DisplayFor(m => m).ToHtmlString();\n                    displayForModelResult = html.DisplayForModel().ToHtmlString();\n                }\n            }\n\n            // Assert\n            Assert.Equal(expectedResult, displayResult);\n            Assert.Equal(expectedResult, displayForResult);\n            Assert.Equal(expectedResult, displayForModelResult);\n        }\n\n        [Theory]\n        [PropertyData(\"ConditionallyHtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void HtmlOrStringTemplate_HtmlEncodesValue_IfHtmlEncode(\n            string text,\n            bool htmlEncode,\n            string expectedResult)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(text);\n            var html = MvcHelper.GetHtmlHelper(viewData);\n\n            var viewContext = Mock.Get(html.ViewContext);\n            viewContext.Setup(c => c.TempData).Returns(new TempDataDictionary());\n            viewContext.Setup(c => c.View).Returns(new DummyView());\n            viewContext.Setup(c => c.Writer).Returns(TextWriter.Null);\n\n            var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => null, typeof(string));\n            metadata.TemplateHint = htmlEncode ? \"String\" : \"Html\";\n\n            string displayResult;\n            string displayForResult;\n            string displayForModelResult;\n            using (new TemplateHelpersSafeScope())\n            {\n                using (new MetadataOverrideScope(metadata))\n                {\n                    // Act\n                    displayResult = html.Display(\"\").ToHtmlString();\n                    displayForResult = html.DisplayFor(m => m).ToHtmlString();\n                    displayForModelResult = html.DisplayForModel().ToHtmlString();\n                }\n            }\n\n            // Assert\n            Assert.Equal(expectedResult, displayResult);\n            Assert.Equal(expectedResult, displayForResult);\n            Assert.Equal(expectedResult, displayForModelResult);\n        }\n\n        // Inconsistent but long-standing behavior.\n        [Theory]\n        [PropertyData(\"HtmlEncodedData_JustText\", PropertyType = typeof(EncodedDataSets))]\n        public void ObjectTemplate_DoesNotEncodeNullDisplayText(string text)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<ObjectTemplateModel>(model: null);\n            var html = MvcHelper.GetHtmlHelper(viewData);\n\n            var viewContext = Mock.Get(html.ViewContext);\n            viewContext.Setup(c => c.TempData).Returns(new TempDataDictionary());\n            viewContext.Setup(c => c.View).Returns(new DummyView());\n            viewContext.Setup(c => c.Writer).Returns(TextWriter.Null);\n\n            var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => null, typeof(ObjectTemplateModel));\n            metadata.NullDisplayText = text;\n\n            string displayResult;\n            string displayForResult;\n            string displayForModelResult;\n            using (new TemplateHelpersSafeScope())\n            {\n                using (new MetadataOverrideScope(metadata))\n                {\n                    // Act\n                    displayResult = html.Display(\"\").ToHtmlString();\n                    displayForResult = html.DisplayFor(m => m).ToHtmlString();\n                    displayForModelResult = html.DisplayForModel().ToHtmlString();\n                }\n            }\n\n            // Assert\n            Assert.Equal(text, displayResult);\n            Assert.Equal(text, displayForResult);\n            Assert.Equal(text, displayForModelResult);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeAndHtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void UrlTemplate_AttributeAndHtmlEncodes(\n            string text,\n            bool htmlEncode,\n            string attributeEncodedText,\n            string htmlEncodedText)\n        {\n            // Arrange\n            var expectedResult = \"<a href=\\\"\" + attributeEncodedText + \"\\\">\" + htmlEncodedText + \"</a>\";\n            var viewData = new ViewDataDictionary<string>(text);\n            var html = MvcHelper.GetHtmlHelper(viewData);\n\n            var viewContext = Mock.Get(html.ViewContext);\n            viewContext.Setup(c => c.TempData).Returns(new TempDataDictionary());\n            viewContext.Setup(c => c.View).Returns(new DummyView());\n            viewContext.Setup(c => c.Writer).Returns(TextWriter.Null);\n\n            var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => null, typeof(string));\n            metadata.TemplateHint = \"Url\";\n            metadata.HtmlEncode = htmlEncode;\n\n            string displayResult;\n            string displayForResult;\n            string displayForModelResult;\n            using (new TemplateHelpersSafeScope())\n            {\n                using (new MetadataOverrideScope(metadata))\n                {\n                    // Act\n                    displayResult = html.Display(\"\").ToHtmlString();\n                    displayForResult = html.DisplayFor(m => m).ToHtmlString();\n                    displayForModelResult = html.DisplayForModel().ToHtmlString();\n                }\n            }\n\n            // Assert\n            Assert.Equal(expectedResult, displayResult);\n            Assert.Equal(expectedResult, displayForResult);\n            Assert.Equal(expectedResult, displayForModelResult);\n        }\n\n        [Fact]\n        public void Display_FindsViewDataMember()\n        {\n            // Arrange\n            var model = new ObjectTemplateModel { Property1 = \"Model string\" };\n            var viewData = new ViewDataDictionary<ObjectTemplateModel>(model);\n            viewData[\"Property1\"] = \"ViewData string\";\n            var html = MvcHelper.GetHtmlHelper(viewData);\n\n            var viewContext = Mock.Get(html.ViewContext);\n            viewContext.Setup(c => c.TempData).Returns(new TempDataDictionary());\n            viewContext.Setup(c => c.View).Returns(new DummyView());\n            viewContext.Setup(c => c.Writer).Returns(TextWriter.Null);\n\n            MvcHtmlString result;\n            using (new TemplateHelpersSafeScope())\n            {\n                // Act\n                result = html.Display(\"Property1\");\n            }\n\n            // Assert\n            Assert.Equal(\"ViewData string\", result.ToString());\n        }\n\n        [Fact]\n        public void DisplayFor_FindsModel()\n        {\n            var model = new ObjectTemplateModel { Property1 = \"Model string\" };\n            var viewData = new ViewDataDictionary<ObjectTemplateModel>(model);\n            viewData[\"Property1\"] = \"ViewData string\";\n            var html = MvcHelper.GetHtmlHelper(viewData);\n\n            var viewContext = Mock.Get(html.ViewContext);\n            viewContext.Setup(c => c.TempData).Returns(new TempDataDictionary());\n            viewContext.Setup(c => c.View).Returns(new DummyView());\n            viewContext.Setup(c => c.Writer).Returns(TextWriter.Null);\n\n            MvcHtmlString result;\n            using (new TemplateHelpersSafeScope())\n            {\n                // Act\n                result = html.DisplayFor(m => m.Property1);\n            }\n\n            // Assert\n            Assert.Equal(\"Model string\", result.ToString());\n        }\n\n        [Fact]\n        public void Display_FindsModel_IfNoViewDataMember()\n        {\n            // Arrange\n            var model = new ObjectTemplateModel { Property1 = \"Model string\" };\n            var viewData = new ViewDataDictionary<ObjectTemplateModel>(model);\n            var html = MvcHelper.GetHtmlHelper(viewData);\n\n            var viewContext = Mock.Get(html.ViewContext);\n            viewContext.Setup(c => c.TempData).Returns(new TempDataDictionary());\n            viewContext.Setup(c => c.View).Returns(new DummyView());\n            viewContext.Setup(c => c.Writer).Returns(TextWriter.Null);\n\n            MvcHtmlString result;\n            using (new TemplateHelpersSafeScope())\n            {\n                // Act\n                result = html.Display(\"Property1\");\n            }\n\n            // Assert\n            Assert.Equal(\"Model string\", result.ToString());\n        }\n\n        [Fact]\n        public void DisplayFor_FindsModel_EvenIfNull()\n        {\n            var model = new ObjectTemplateModel();\n            var viewData = new ViewDataDictionary<ObjectTemplateModel>(model);\n            viewData[\"Property1\"] = \"ViewData string\";\n            var html = MvcHelper.GetHtmlHelper(viewData);\n\n            var viewContext = Mock.Get(html.ViewContext);\n            viewContext.Setup(c => c.TempData).Returns(new TempDataDictionary());\n            viewContext.Setup(c => c.View).Returns(new DummyView());\n            viewContext.Setup(c => c.Writer).Returns(TextWriter.Null);\n\n            MvcHtmlString result;\n            using (new TemplateHelpersSafeScope())\n            {\n                // Act\n                result = html.DisplayFor(m => m.Property1);\n            }\n\n            // Assert\n            Assert.Empty(result.ToString());\n        }\n\n        private class ObjectTemplateModel\n        {\n            public string Property1 { get; set; }\n            public string Property2 { get; set; }\n        }\n\n        private class DummyView : IView\n        {\n            public void Render(ViewContext viewContext, TextWriter writer)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Html/Test/DisplayNameExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq.Expressions;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\nusing Moq;\n\nnamespace System.Web.Mvc.Html.Test\n{\n    public class DisplayNameExtensionsTest\n    {\n        [Fact]\n        public void DisplayNameNullExpressionThrows()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => MvcHelper.GetHtmlHelper().DisplayName(expression: null),\n                \"expression\");\n        }\n\n        [Fact]\n        public void DisplayNameWithNoModelMetadataDisplayNameOverride()\n        {\n            // Act\n            MvcHtmlString result = MvcHelper.GetHtmlHelper().DisplayNameInternal(\"PropertyName\", new MetadataHelper().MetadataProvider.Object);\n\n            // Assert\n            Assert.Equal(\"PropertyName\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void DisplayNameUsesMetadataForDisplayText()\n        {\n            // Arrange\n            MetadataHelper metadataHelper = new MetadataHelper();\n            metadataHelper.Metadata.Setup(m => m.DisplayName).Returns(\"Custom display name from metadata\");\n\n            // Act\n            MvcHtmlString result = MvcHelper.GetHtmlHelper().DisplayNameInternal(\"PropertyName\", metadataHelper.MetadataProvider.Object);\n\n            // Assert\n            Assert.Equal(\"Custom display name from metadata\", result.ToHtmlString());\n        }\n\n        private sealed class Model\n        {\n            public string PropertyName { get; set; }\n        }\n\n        [Fact]\n        public void DisplayNameConsultsMetadataProviderForMetadataAboutProperty()\n        {\n            // Arrange\n            Model model = new Model { PropertyName = \"propertyValue\" };\n\n            ViewDataDictionary viewData = new ViewDataDictionary();\n            Mock<ViewContext> viewContext = new Mock<ViewContext>();\n            viewContext.Setup(c => c.ViewData).Returns(viewData);\n\n            Mock<IViewDataContainer> viewDataContainer = new Mock<IViewDataContainer>();\n            viewDataContainer.Setup(c => c.ViewData).Returns(viewData);\n\n            HtmlHelper<Model> html = new HtmlHelper<Model>(viewContext.Object, viewDataContainer.Object);\n            viewData.Model = model;\n\n            MetadataHelper metadataHelper = new MetadataHelper();\n\n            metadataHelper.MetadataProvider.Setup(p => p.GetMetadataForProperty(It.IsAny<Func<object>>(), typeof(Model), \"PropertyName\"))\n                .Returns(metadataHelper.Metadata.Object)\n                .Verifiable();\n\n            // Act\n            html.DisplayNameInternal(\"PropertyName\", metadataHelper.MetadataProvider.Object);\n\n            // Assert\n            metadataHelper.MetadataProvider.Verify();\n        }\n\n        [Fact]\n        public void DisplayNameUsesMetadataForPropertyName()\n        {\n            // Arrange\n            MetadataHelper metadataHelper = new MetadataHelper();\n\n            metadataHelper.Metadata = new Mock<ModelMetadata>(metadataHelper.MetadataProvider.Object, null, null, typeof(object), \"Custom property name from metadata\");\n            metadataHelper.MetadataProvider.Setup(p => p.GetMetadataForType(It.IsAny<Func<object>>(), It.IsAny<Type>()))\n                .Returns(metadataHelper.Metadata.Object);\n\n            // Act\n            MvcHtmlString result = MvcHelper.GetHtmlHelper().DisplayNameInternal(\"PropertyName\", metadataHelper.MetadataProvider.Object);\n\n            // Assert\n            Assert.Equal(\"Custom property name from metadata\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void DisplayNameForNullExpressionThrows()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => MvcHelper.GetHtmlHelper().DisplayNameFor((Expression<Func<Object, Object>>)null),\n                \"expression\");\n\n            Assert.ThrowsArgumentNull(\n                () => GetEnumerableHtmlHelper().DisplayNameFor((Expression<Func<Foo, Object>>)null),\n                \"expression\");\n        }\n\n        [Fact]\n        public void DisplayNameForNonMemberExpressionThrows()\n        {\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => MvcHelper.GetHtmlHelper().DisplayNameFor(model => new { foo = \"Bar\" }),\n                \"Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.\");\n\n            Assert.Throws<InvalidOperationException>(\n                () => GetEnumerableHtmlHelper().DisplayNameFor((Expression<Func<IEnumerable<Foo>, object>>)(model => new { foo = \"Bar\" })),\n                \"Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.\");\n        }\n\n        [Fact]\n        public void DisplayNameForWithNoModelMetadataDisplayNameOverride()\n        {\n            // Arrange\n            string unknownKey = \"this is a dummy parameter value\";\n\n            // Act\n            MvcHtmlString result = MvcHelper.GetHtmlHelper().DisplayNameFor(model => unknownKey);\n            MvcHtmlString enumerableResult = GetEnumerableHtmlHelper().DisplayNameFor((Expression<Func<IEnumerable<Foo>, string>>)(model => unknownKey));\n\n            // Assert\n            Assert.Equal(\"unknownKey\", result.ToHtmlString());\n            Assert.Equal(\"unknownKey\", enumerableResult.ToHtmlString());\n        }\n\n        [Fact]\n        public void DisplayNameForUsesModelMetadata()\n        {\n            // Arrange\n            MetadataHelper metadataHelper = new MetadataHelper();\n\n            metadataHelper.Metadata.Setup(m => m.DisplayName).Returns(\"Custom display name from metadata\");\n            string unknownKey = \"this is a dummy parameter value\";\n\n            // Act\n            MvcHtmlString result = MvcHelper.GetHtmlHelper().DisplayNameForInternal(model => unknownKey, metadataHelper.MetadataProvider.Object);\n            MvcHtmlString enumerableResult = GetEnumerableHtmlHelper().DisplayNameForInternal(model => model.Bar, metadataHelper.MetadataProvider.Object);\n\n            // Assert\n            Assert.Equal(\"Custom display name from metadata\", result.ToHtmlString());\n            Assert.Equal(\"Custom display name from metadata\", enumerableResult.ToHtmlString());\n        }\n\n        [Fact]\n        public void DisplayNameForEmptyDisplayNameReturnsEmptyName()\n        {\n            // Arrange\n            MetadataHelper metadataHelper = new MetadataHelper();\n\n            metadataHelper.Metadata.Setup(m => m.DisplayName).Returns(String.Empty);\n            string unknownKey = \"this is a dummy parameter value\";\n\n            // Act\n            MvcHtmlString result = MvcHelper.GetHtmlHelper().DisplayNameForInternal(model => unknownKey, metadataHelper.MetadataProvider.Object);\n            MvcHtmlString enumerableResult = GetEnumerableHtmlHelper().DisplayNameForInternal(model => model.Bar, metadataHelper.MetadataProvider.Object);\n\n            // Assert\n            Assert.Equal(String.Empty, result.ToHtmlString());\n            Assert.Equal(String.Empty, enumerableResult.ToHtmlString());\n        }\n\n        [Fact]\n        public void DisplayNameForModelUsesModelMetadata()\n        {\n            // Arrange\n            ViewDataDictionary viewData = new ViewDataDictionary();\n            Mock<ModelMetadata> metadata = new MetadataHelper().Metadata;\n            metadata.Setup(m => m.DisplayName).Returns(\"Custom display name from metadata\");\n\n            viewData.ModelMetadata = metadata.Object;\n            viewData.TemplateInfo.HtmlFieldPrefix = \"Prefix\";\n\n            // Act\n            MvcHtmlString result = MvcHelper.GetHtmlHelper(viewData).DisplayNameForModel();\n\n            // Assert\n            Assert.Equal(\"Custom display name from metadata\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void DisplayNameForWithNestedClass()\n        {\n            // Arrange\n            ViewDataDictionary viewData = new ViewDataDictionary();\n            Mock<ViewContext> viewContext = new Mock<ViewContext>();\n            viewContext.Setup(c => c.ViewData).Returns(viewData);\n\n            Mock<IViewDataContainer> viewDataContainer = new Mock<IViewDataContainer>();\n            viewDataContainer.Setup(c => c.ViewData).Returns(viewData);\n\n            HtmlHelper<NestedProduct> html = new HtmlHelper<NestedProduct>(viewContext.Object, viewDataContainer.Object);\n\n            // Act\n            MvcHtmlString result = html.DisplayNameForInternal(nested => nested.product.Id, new MetadataHelper().MetadataProvider.Object);\n\n            //Assert\n            Assert.Equal(\"Id\", result.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"HtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void DisplayNameHelpers_EncodeValue(string text, bool htmlEncode, string expectedResult)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<Cart>(model: null);\n            viewData.ModelMetadata.DisplayName = text;\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            var nameResult = helper.DisplayName(\"\").ToHtmlString();\n            var nameForResult = helper.DisplayNameFor(m => m).ToHtmlString();\n            var nameForModelResult = helper.DisplayNameForModel().ToHtmlString();\n\n            // Assert\n            Assert.Equal(expectedResult, nameResult);\n            Assert.Equal(expectedResult, nameForResult);\n            Assert.Equal(expectedResult, nameForModelResult);\n        }\n\n        private class Product\n        {\n            public int Id { get; set; }\n        }\n\n        private class Cart\n        {\n            public Product[] Products { get; set; }\n        }\n\n        private class NestedProduct\n        {\n            public Product product = new Product();\n        }\n\n        private sealed class Foo\n        {\n            public string Bar { get; set; }\n        }\n\n        private static HtmlHelper<IEnumerable<Foo>> GetEnumerableHtmlHelper()\n        {\n            return MvcHelper.GetHtmlHelper(new ViewDataDictionary<IEnumerable<Foo>>());\n        }\n\n        private sealed class MetadataHelper\n        {\n            public Mock<ModelMetadata> Metadata { get; set; }\n            public Mock<ModelMetadataProvider> MetadataProvider { get; set; }\n\n            public MetadataHelper()\n            {\n                MetadataProvider = new Mock<ModelMetadataProvider>();\n                Metadata = new Mock<ModelMetadata>(MetadataProvider.Object, null, null, typeof(object), null);\n\n                MetadataProvider.Setup(p => p.GetMetadataForProperties(It.IsAny<object>(), It.IsAny<Type>()))\n                    .Returns(new ModelMetadata[0]);\n                MetadataProvider.Setup(p => p.GetMetadataForProperty(It.IsAny<Func<object>>(), It.IsAny<Type>(), It.IsAny<string>()))\n                    .Returns(Metadata.Object);\n                MetadataProvider.Setup(p => p.GetMetadataForType(It.IsAny<Func<object>>(), It.IsAny<Type>()))\n                    .Returns(Metadata.Object);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Html/Test/DisplayTextExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel.DataAnnotations;\nusing System.Globalization;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace System.Web.Mvc.Html.Test\n{\n    public class DisplayTextExtensionsTest\n    {\n        [Fact]\n        public void DisplayText_ThrowsArgumentNull_IfNameNull()\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<OverriddenToStringModel>(model: null);\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act & Assert\n            // Note ArgumentNullException uses incorrect parameter name.\n            Assert.ThrowsArgumentNull(\n                () => helper.DisplayText(name: null),\n                \"expression\");\n        }\n\n        [Fact]\n        public void DisplayTextFor_ThrowsArgumentNull_IfExpressionNull()\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<OverriddenToStringModel>(model: null);\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => helper.DisplayTextFor<OverriddenToStringModel, string>(expression: null),\n                \"expression\");\n        }\n\n        [Fact]\n        public void DisplayText_ReturnsEmpty_IfValueNull()\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<OverriddenToStringModel>(model: null);\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString result = helper.DisplayText(\"\");\n\n            // Assert\n            Assert.Empty(result.ToHtmlString());\n        }\n\n        [Fact]\n        public void DisplayTextFor_ReturnsEmpty_IfValueNull()\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<OverriddenToStringModel>(model: null);\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString result = helper.DisplayTextFor(m => m);\n\n            // Assert\n            Assert.Empty(result.ToHtmlString());\n        }\n\n        [Fact]\n        public void DisplayText_ReturnsNullDisplayText_IfSetAndValueNull()\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<OverriddenToStringModel>(model: null);\n            viewData.ModelMetadata.NullDisplayText = \"Null display Text\";\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString result = helper.DisplayText(\"\");\n\n            // Assert\n            Assert.Equal(\"Null display Text\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void DisplayTextFor_ReturnsNullDisplayText_IfSetAndValueNull()\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<OverriddenToStringModel>(model: null);\n            viewData.ModelMetadata.NullDisplayText = \"Null display Text\";\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString result = helper.DisplayTextFor(m => m);\n\n            // Assert\n            Assert.Equal(\"Null display Text\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void DisplayText_ReturnsValue_IfNameEmpty()\n        {\n            // Arrange\n            var model = new OverriddenToStringModel(\"Model value\");\n            var viewData = new ViewDataDictionary<OverriddenToStringModel>(model);\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString result = helper.DisplayText(\"\");\n\n            // Assert\n            Assert.Equal(\"Model value\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void DisplayText_ReturnsEmpty_IfNameNotFound()\n        {\n            // Arrange\n            var model = new OverriddenToStringModel(\"Model value\");\n            var viewData = new ViewDataDictionary<OverriddenToStringModel>(model);\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString result = helper.DisplayText(\"NonExistentProperty\");\n\n            // Assert\n            Assert.Empty(result.ToHtmlString());\n        }\n\n        [Fact]\n        public void DisplayTextFor_ReturnsValue_IfIdentityExpression()\n        {\n            // Arrange\n            var model = new OverriddenToStringModel(\"Model value\");\n            var viewData = new ViewDataDictionary<OverriddenToStringModel>(model);\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString result = helper.DisplayTextFor(m => m);\n\n            // Assert\n            Assert.Equal(\"Model value\", result.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"ConditionallyHtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void DisplayText_HonoursHtmlEncode_IfOverridden(string text, bool htmlEncode, string expectedResult)\n        {\n            // Arrange\n            var model = new OverriddenToStringModel(text);\n            var viewData = new ViewDataDictionary<OverriddenToStringModel>(model);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString result = helper.DisplayText(\"\");\n\n            // Assert\n            Assert.Equal(expectedResult, result.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"ConditionallyHtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void DisplayTextFor_HonoursHtmlEncode_IfOverridden(string text, bool htmlEncode, string expectedResult)\n        {\n            // Arrange\n            var model = new OverriddenToStringModel(text);\n            var viewData = new ViewDataDictionary<OverriddenToStringModel>(model);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString result = helper.DisplayTextFor(m => m);\n\n            // Assert\n            Assert.Equal(expectedResult, result.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"ConditionallyHtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void DisplayText_HonoursHtmlEncode_ForProperty(string text, bool htmlEncode, string expectedResult)\n        {\n            // Arrange\n            var model = new DontHtmlEncodeModel\n            {\n                Encoded = text,\n                NotEncoded = text,\n            };\n            var viewData = new ViewDataDictionary<DontHtmlEncodeModel>(model);\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            var propertyName = htmlEncode ? \"Encoded\" : \"NotEncoded\";\n\n            // Act\n            MvcHtmlString result = helper.DisplayText(propertyName);\n\n            // Assert\n            Assert.Equal(expectedResult, result.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"ConditionallyHtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void DisplayTextFor_HonoursHtmlEncode_ForProperty(string text, bool htmlEncode, string expectedResult)\n        {\n            // Arrange\n            var model = new DontHtmlEncodeModel\n            {\n                Encoded = text,\n                NotEncoded = text,\n            };\n            var viewData = new ViewDataDictionary<DontHtmlEncodeModel>(model);\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString result;\n            if (htmlEncode)\n            {\n                result = helper.DisplayTextFor(m => m.Encoded);\n            }\n            else\n            {\n                result = helper.DisplayTextFor(m => m.NotEncoded);\n            }\n\n            // Assert\n            Assert.Equal(expectedResult, result.ToHtmlString());\n        }\n\n        [Fact]\n        public void DisplayText_ReturnsSimpleDisplayText_IfSetAndValueNonNull()\n        {\n            // Arrange\n            var model = new OverriddenToStringModel(\"ignored text\");\n            var viewData = new ViewDataDictionary<OverriddenToStringModel>(model);\n            viewData.ModelMetadata.SimpleDisplayText = \"Simple display text\";\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString result = helper.DisplayText(\"\");\n\n            // Assert\n            Assert.Equal(\"Simple display text\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void DisplayTextFor_ReturnsSimpleDisplayText_IfSetAndValueNonNull()\n        {\n            // Arrange\n            var model = new OverriddenToStringModel(\"ignored text\");\n            var viewData = new ViewDataDictionary<OverriddenToStringModel>(model);\n            viewData.ModelMetadata.SimpleDisplayText = \"Simple display text\";\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString result = helper.DisplayTextFor(m => m);\n\n            // Assert\n            Assert.Equal(\"Simple display text\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void DisplayText_ReturnsPropertyValue_IfNameFound()\n        {\n            // Arrange\n            var model = new OverriddenToStringModel(\"ignored text\")\n            {\n                Name = \"Property value\",\n            };\n            var viewData = new ViewDataDictionary<OverriddenToStringModel>(model);\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString result = helper.DisplayText(\"Name\");\n\n            // Assert\n            Assert.Equal(\"Property value\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void DisplayTextFor_ReturnsPropertyValue_IfPropertyExpression()\n        {\n            // Arrange\n            var model = new OverriddenToStringModel(\"ignored text\")\n            {\n                Name = \"Property value\",\n            };\n            var viewData = new ViewDataDictionary<OverriddenToStringModel>(model);\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString result = helper.DisplayTextFor(m => m.Name);\n\n            // Assert\n            Assert.Equal(\"Property value\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void DisplayText_ReturnsViewDataEntry()\n        {\n            // Arrange\n            var model = new OverriddenToStringModel(\"Model value\")\n            {\n                Name = \"Property value\",\n            };\n            var viewData = new ViewDataDictionary<OverriddenToStringModel>(model)\n            {\n                { \"Name\", \"View data dictionary value\" },\n            };\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString result = helper.DisplayText(\"Name\");\n\n            // Assert\n            Assert.Equal(\"View data dictionary value\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void DisplayTextFor_IgnoresViewDataEntry()\n        {\n            // Arrange\n            var model = new OverriddenToStringModel(\"Model value\")\n            {\n                Name = \"Property value\",\n            };\n            var viewData = new ViewDataDictionary<OverriddenToStringModel>(model)\n            {\n                { \"Name\", \"View data dictionary value\" },\n            };\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString result = helper.DisplayTextFor(m => m.Name);\n\n            // Assert\n            Assert.Equal(\"Property value\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void DisplayText_ReturnsModelStateEntry()\n        {\n            // Arrange\n            var model = new OverriddenToStringModel(\"Model value\")\n            {\n                Name = \"Property value\",\n            };\n            var viewData = new ViewDataDictionary<OverriddenToStringModel>(model)\n            {\n                { \"Name\", \"View data dictionary value\" },\n            };\n            viewData.TemplateInfo.HtmlFieldPrefix = \"FieldPrefix\";\n\n            var modelState = new ModelState();\n            modelState.Value = new ValueProviderResult(\n                rawValue: new string[] { \"Attempted name value\" },\n                attemptedValue: \"Attempted name value\",\n                culture: CultureInfo.InvariantCulture);\n            viewData.ModelState[\"FieldPrefix.Name\"] = modelState;\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString result = helper.DisplayText(\"Name\");\n\n            // Assert\n            Assert.Equal(\"View data dictionary value\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void DisplayTextFor_IgnoresModelStateEntry()\n        {\n            // Arrange\n            var model = new OverriddenToStringModel(\"Model value\")\n            {\n                Name = \"Property value\",\n            };\n            var viewData = new ViewDataDictionary<OverriddenToStringModel>(model)\n            {\n                { \"Name\", \"View data dictionary value\" },\n            };\n            viewData.TemplateInfo.HtmlFieldPrefix = \"FieldPrefix\";\n\n            var modelState = new ModelState();\n            modelState.Value = new ValueProviderResult(\n                rawValue: new string[] { \"Attempted name value\" },\n                attemptedValue: \"Attempted name value\",\n                culture: CultureInfo.InvariantCulture);\n            viewData.ModelState[\"FieldPrefix.Name\"] = modelState;\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString result = helper.DisplayTextFor(m => m.Name);\n\n            // Assert\n            Assert.Equal(\"Property value\", result.ToHtmlString());\n        }\n\n        private sealed class DontHtmlEncodeModel\n        {\n            public string Encoded { get; set; }\n\n            [DisplayFormat(HtmlEncode = false)]\n            public string NotEncoded { get; set; }\n        }\n\n        // ModelMetadata.SimpleDisplayText returns ToString() displayForModelResult if that method has been overridden.\n        private sealed class OverriddenToStringModel\n        {\n            private readonly string _simpleDisplayText;\n\n            public OverriddenToStringModel(string simpleDisplayText)\n            {\n                _simpleDisplayText = simpleDisplayText;\n            }\n\n            public string Name { get; set; }\n\n            public override string ToString()\n            {\n                return _simpleDisplayText;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Html/Test/EditorExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\nusing Moq;\n\nnamespace System.Web.Mvc.Html.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")]\n    public class EditorExtensionsTest\n    {\n        [Fact]\n        public void EditorNullExpressionThrows()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => MvcHelper.GetHtmlHelper().Editor(expression: null),\n                \"expression\");\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData_NoHtmlEncode\", PropertyType = typeof(EncodedDataSets))]\n        public void BooleanTemplate_AttributeEncodes_AddedHtmlAttributes(string text, string htmlEncodedText)\n        {\n            // Arrange\n            var expectedResult = \"<input attribute=\\\"\" +\n                htmlEncodedText +\n                \"\\\" checked=\\\"checked\\\" class=\\\"check-box\\\" id=\\\"Prefix\\\" name=\\\"Prefix\\\" type=\\\"checkbox\\\" \" +\n                \"value=\\\"true\\\" />\" +\n                \"<input name=\\\"Prefix\\\" type=\\\"hidden\\\" value=\\\"false\\\" />\";\n            var viewData = new ViewDataDictionary<bool>(true);\n            viewData.Add(\"htmlAttributes\", new { attribute = text, });\n            viewData.TemplateInfo.HtmlFieldPrefix = \"Prefix\";\n\n            var html = MvcHelper.GetHtmlHelper(viewData);\n\n            var viewContext = Mock.Get(html.ViewContext);\n            viewContext.Setup(c => c.TempData).Returns(new TempDataDictionary());\n            viewContext.Setup(c => c.View).Returns(new DummyView());\n            viewContext.Setup(c => c.Writer).Returns(TextWriter.Null);\n\n            string editorResult;\n            string editorForResult;\n            string editorForModelResult;\n            using (new TemplateHelpersSafeScope())\n            {\n                // Act\n                editorResult = html.Editor(\"\").ToHtmlString();\n                editorForResult = html.EditorFor(m => m).ToHtmlString();\n                editorForModelResult = html.EditorForModel().ToHtmlString();\n            }\n\n            // Assert\n            Assert.Equal(expectedResult, editorResult);\n            Assert.Equal(expectedResult, editorForResult);\n            Assert.Equal(expectedResult, editorForModelResult);\n        }\n\n        [Theory]\n        [PropertyData(\"ConditionallyHtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void CollectionTemplateWrappingObjectTemplate_EncodesSimpleDisplayTextOfItems_IfHtmlEncode(\n            string text,\n            bool htmlEncode,\n            string expectedResult)\n        {\n            // Arrange\n            var innerModel = new ObjectTemplateModel\n            {\n                Property1 = text,           // SimpleDisplayText uses first property by default.\n            };\n            var model = new[] { innerModel, innerModel, };\n            var viewData = new ViewDataDictionary<ObjectTemplateModel[]>(model);\n            var html = MvcHelper.GetHtmlHelper(viewData);\n\n            // GetHtmlHelper does not mock enough of the ViewContext for TemplateHelpers use.\n            var viewContext = Mock.Get(html.ViewContext);\n            viewContext.Setup(c => c.TempData).Returns(new TempDataDictionary());\n            viewContext.Setup(c => c.View).Returns(new DummyView());\n            viewContext.Setup(c => c.Writer).Returns(TextWriter.Null);\n\n            // Developers might need to do something similar (including MetadataOverrideScope or another approach\n            // replacing ModelMetadataProviders.Current) since for example [DisplayFormat] cannot be applied to a class.\n            var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => null, typeof(ObjectTemplateModel));\n            metadata.HtmlEncode = htmlEncode;\n\n            string editorResult;\n            string editorForResult;\n            string editorForModelResult;\n            using (new TemplateHelpersSafeScope())\n            {\n                using (new MetadataOverrideScope(metadata))\n                {\n                    // Act\n                    editorResult = html.Editor(\"\").ToHtmlString();\n                    editorForResult = html.EditorFor(m => m).ToHtmlString();\n                    editorForModelResult = html.EditorForModel().ToHtmlString();\n                }\n            }\n\n            // Assert\n            Assert.Equal(expectedResult + expectedResult, editorResult);\n            Assert.Equal(expectedResult + expectedResult, editorForResult);\n            Assert.Equal(expectedResult + expectedResult, editorForModelResult);\n        }\n\n        // Inconsistent but long-standing behavior.\n        [Theory]\n        [PropertyData(\"ConditionallyHtmlEncodedData_NoEncodedText\", PropertyType = typeof(EncodedDataSets))]\n        public void CollectionTemplateWrappingObjectTemplate_DoesNotEncodeNullDisplayText_IfNull(\n            string text,\n            bool htmlEncode)\n        {\n            // Arrange\n            var model = new[] { (ObjectTemplateModel)null, };\n            var viewData = new ViewDataDictionary<ObjectTemplateModel[]>(model);\n            var html = MvcHelper.GetHtmlHelper(viewData);\n\n            // GetHtmlHelper does not mock enough of the ViewContext for TemplateHelpers use.\n            var viewContext = Mock.Get(html.ViewContext);\n            viewContext.Setup(c => c.TempData).Returns(new TempDataDictionary());\n            viewContext.Setup(c => c.View).Returns(new DummyView());\n            viewContext.Setup(c => c.Writer).Returns(TextWriter.Null);\n\n            // Developers might need to do something similar (including MetadataOverrideScope or another approach\n            // replacing ModelMetadataProviders.Current) since for example [DisplayFormat] cannot be applied to a class.\n            var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => null, typeof(ObjectTemplateModel));\n            metadata.HtmlEncode = htmlEncode;\n            metadata.NullDisplayText = text;\n\n            string editorResult;\n            string editorForResult;\n            string editorForModelResult;\n            using (new TemplateHelpersSafeScope())\n            {\n                using (new MetadataOverrideScope(metadata))\n                {\n                    // Act\n                    editorResult = html.Editor(\"\").ToHtmlString();\n                    editorForResult = html.EditorFor(m => m).ToHtmlString();\n                    editorForModelResult = html.EditorForModel().ToHtmlString();\n                }\n            }\n\n            // Assert\n            Assert.Equal(text, editorResult);\n            Assert.Equal(text, editorForResult);\n            Assert.Equal(text, editorForModelResult);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData_NoHtmlEncode\", PropertyType = typeof(EncodedDataSets))]\n        public void StringTemplate_AttributeEncodes_AddedHtmlAttributes(string text, string htmlEncodedText)\n        {\n            // Arrange\n            var expectedResult = \"<input attribute=\\\"\" +\n                htmlEncodedText +\n                \"\\\" class=\\\"text-box single-line\\\" id=\\\"Prefix\\\" name=\\\"Prefix\\\" type=\\\"text\\\" value=\\\"string\\\" />\";\n            var viewData = new ViewDataDictionary<string>(\"string\");\n            viewData.Add(\"htmlAttributes\", new { attribute = text, });\n            viewData.TemplateInfo.HtmlFieldPrefix = \"Prefix\";\n\n            var html = MvcHelper.GetHtmlHelper(viewData);\n\n            var viewContext = Mock.Get(html.ViewContext);\n            viewContext.Setup(c => c.TempData).Returns(new TempDataDictionary());\n            viewContext.Setup(c => c.View).Returns(new DummyView());\n            viewContext.Setup(c => c.Writer).Returns(TextWriter.Null);\n\n            string editorResult;\n            string editorForResult;\n            string editorForModelResult;\n            using (new TemplateHelpersSafeScope())\n            {\n                // Act\n                editorResult = html.Editor(\"\").ToHtmlString();\n                editorForResult = html.EditorFor(m => m).ToHtmlString();\n                editorForModelResult = html.EditorForModel().ToHtmlString();\n            }\n\n            // Assert\n            Assert.Equal(expectedResult, editorResult);\n            Assert.Equal(expectedResult, editorForResult);\n            Assert.Equal(expectedResult, editorForModelResult);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData_NoHtmlEncode\", PropertyType = typeof(EncodedDataSets))]\n        public void StringTemplate_AttributeEncodesText(string text, string htmlEncodedText)\n        {\n            // Arrange\n            var expectedResult =\n                \"<input class=\\\"text-box single-line\\\" id=\\\"Prefix\\\" name=\\\"Prefix\\\" type=\\\"text\\\" value=\\\"\" +\n                    htmlEncodedText +\n                    \"\\\" />\";\n            var viewData = new ViewDataDictionary<string>(text);\n            viewData.TemplateInfo.HtmlFieldPrefix = \"Prefix\";\n\n            var html = MvcHelper.GetHtmlHelper(viewData);\n\n            var viewContext = Mock.Get(html.ViewContext);\n            viewContext.Setup(c => c.TempData).Returns(new TempDataDictionary());\n            viewContext.Setup(c => c.View).Returns(new DummyView());\n            viewContext.Setup(c => c.Writer).Returns(TextWriter.Null);\n\n            string editorResult;\n            string editorForResult;\n            string editorForModelResult;\n            using (new TemplateHelpersSafeScope())\n            {\n                // Act\n                editorResult = html.Editor(\"\").ToHtmlString();\n                editorForResult = html.EditorFor(m => m).ToHtmlString();\n                editorForModelResult = html.EditorForModel().ToHtmlString();\n            }\n\n            // Assert\n            Assert.Equal(expectedResult, editorResult);\n            Assert.Equal(expectedResult, editorForResult);\n            Assert.Equal(expectedResult, editorForModelResult);\n        }\n\n        [Fact]\n        public void Editor_FindsViewDataMember()\n        {\n            // Arrange\n            var model = new ObjectTemplateModel { Property1 = \"Model string\" };\n            var viewData = new ViewDataDictionary<ObjectTemplateModel>(model);\n            viewData[\"Property1\"] = \"ViewData string\";\n            var html = MvcHelper.GetHtmlHelper(viewData);\n\n            var viewContext = Mock.Get(html.ViewContext);\n            viewContext.Setup(c => c.TempData).Returns(new TempDataDictionary());\n            viewContext.Setup(c => c.View).Returns(new DummyView());\n            viewContext.Setup(c => c.Writer).Returns(TextWriter.Null);\n\n            MvcHtmlString result;\n            using (new TemplateHelpersSafeScope())\n            {\n                // Act\n                result = html.Editor(\"Property1\");\n            }\n\n            // Assert\n            Assert.Equal(\n                \"<input class=\\\"text-box single-line\\\" id=\\\"Property1\\\" name=\\\"Property1\\\" type=\\\"text\\\" value=\\\"ViewData string\\\" />\",\n                result.ToString());\n        }\n\n        [Fact]\n        public void EditorFor_FindsModel()\n        {\n            var model = new ObjectTemplateModel { Property1 = \"Model string\" };\n            var viewData = new ViewDataDictionary<ObjectTemplateModel>(model);\n            viewData[\"Property1\"] = \"ViewData string\";\n            var html = MvcHelper.GetHtmlHelper(viewData);\n\n            var viewContext = Mock.Get(html.ViewContext);\n            viewContext.Setup(c => c.TempData).Returns(new TempDataDictionary());\n            viewContext.Setup(c => c.View).Returns(new DummyView());\n            viewContext.Setup(c => c.Writer).Returns(TextWriter.Null);\n\n            MvcHtmlString result;\n            using (new TemplateHelpersSafeScope())\n            {\n                // Act\n                result = html.EditorFor(m => m.Property1);\n            }\n\n            // Assert\n            Assert.Equal(\n                \"<input class=\\\"text-box single-line\\\" id=\\\"Property1\\\" name=\\\"Property1\\\" type=\\\"text\\\" value=\\\"Model string\\\" />\",\n                result.ToString());\n        }\n\n        [Fact]\n        public void Editor_FindsModel_IfNoViewDataMember()\n        {\n            // Arrange\n            var model = new ObjectTemplateModel { Property1 = \"Model string\" };\n            var viewData = new ViewDataDictionary<ObjectTemplateModel>(model);\n            var html = MvcHelper.GetHtmlHelper(viewData);\n\n            var viewContext = Mock.Get(html.ViewContext);\n            viewContext.Setup(c => c.TempData).Returns(new TempDataDictionary());\n            viewContext.Setup(c => c.View).Returns(new DummyView());\n            viewContext.Setup(c => c.Writer).Returns(TextWriter.Null);\n\n            MvcHtmlString result;\n            using (new TemplateHelpersSafeScope())\n            {\n                // Act\n                result = html.Editor(\"Property1\");\n            }\n\n            // Assert\n            Assert.Equal(\n                \"<input class=\\\"text-box single-line\\\" id=\\\"Property1\\\" name=\\\"Property1\\\" type=\\\"text\\\" value=\\\"Model string\\\" />\",\n                result.ToString());\n        }\n\n        [Fact]\n        public void EditorFor_FindsModel_EvenIfNull()\n        {\n            var model = new ObjectTemplateModel();\n            var viewData = new ViewDataDictionary<ObjectTemplateModel>(model);\n            viewData[\"Property1\"] = \"ViewData string\";\n            var html = MvcHelper.GetHtmlHelper(viewData);\n\n            var viewContext = Mock.Get(html.ViewContext);\n            viewContext.Setup(c => c.TempData).Returns(new TempDataDictionary());\n            viewContext.Setup(c => c.View).Returns(new DummyView());\n            viewContext.Setup(c => c.Writer).Returns(TextWriter.Null);\n\n            MvcHtmlString result;\n            using (new TemplateHelpersSafeScope())\n            {\n                // Act\n                result = html.EditorFor(m => m.Property1);\n            }\n\n            // Assert\n            Assert.Equal(\n                \"<input class=\\\"text-box single-line\\\" id=\\\"Property1\\\" name=\\\"Property1\\\" type=\\\"text\\\" value=\\\"\\\" />\",\n                result.ToString());\n        }\n\n        private class ObjectTemplateModel\n        {\n            public string Property1 { get; set; }\n            public string Property2 { get; set; }\n        }\n\n        private class DummyView : IView\n        {\n            public void Render(ViewContext viewContext, TextWriter writer)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Html/Test/EncodedDataSets.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Html.Test\n{\n    public static class EncodedDataSets\n    {\n        private static readonly List<StringSet> StringSets = new List<StringSet>\n        {\n            // Needs extra URL-escaping due to routing special cases.\n            new StringSet(\"&'\\\"\", \"&amp;&#39;&quot;\", \"&amp;&#39;&quot;\", \"___\", \"%26&#39;%22\"),\n\n            // High ASCII\n            new StringSet(\" ¡ÿĀ\", \" ¡ÿĀ\", \"&#160;&#161;&#255;Ā\", \"____\"),\n\n            // Surrogate pair, Ugaritic letter beta, &x10381;\n            new StringSet(\"\\xD800\\xDF81\", \"𐎁\", \"&#66433;\", \"__\"),\n\n            new StringSet(\n                \"<blink>text</blink>\",\n                \"&lt;blink>text&lt;/blink>\",\n                \"&lt;blink&gt;text&lt;/blink&gt;\",\n                \"_blink_text__blink_\"),\n\n            // Remaining examples are only id-sanitized, not attribute- or HTML-encoded.\n            new StringSet(\"Simple Display Text\", \"Simple Display Text\", \"Simple Display Text\", \"Simple_Display_Text\"),\n            new StringSet(\"Chinese西雅图Chars\", \"Chinese西雅图Chars\", \"Chinese西雅图Chars\", \"Chinese___Chars\"), // Seattle\n            new StringSet(\n                \"Unicode؃Format؃Char\", // class Cf\n                \"Unicode؃Format؃Char\",\n                \"Unicode؃Format؃Char\",\n                \"Unicode_Format_Char\"),\n            new StringSet(\n                \"UnicodeῼTitlecaseῼChar\", // class Lt\n                \"UnicodeῼTitlecaseῼChar\",\n                \"UnicodeῼTitlecaseῼChar\",\n                \"Unicode_Titlecase_Char\"),\n            new StringSet(\n                \"UnicodeःCombiningःChar\", // class Mc\n                \"UnicodeःCombiningःChar\",\n                \"UnicodeःCombiningःChar\",\n                \"Unicode_Combining_Char\"),\n        };\n\n        public static TheoryDataSet<string, bool, string, string> AttributeAndHtmlEncodedData\n        {\n            get\n            {\n                var result = new TheoryDataSet<string, bool, string, string>();\n                foreach (var stringSet in StringSets)\n                {\n                    // Same results whether ModelMetadata.HtmlEncode is true or false.\n                    result.Add(\n                        stringSet.Text,\n                        false,\n                        stringSet.AttributeEncodedText,\n                        stringSet.HtmlEncodedText);\n                    result.Add(\n                        stringSet.Text,\n                        true,\n                        stringSet.AttributeEncodedText,\n                        stringSet.HtmlEncodedText);\n                }\n\n                return result;\n            }\n        }\n\n        public static TheoryDataSet<string, bool, string> AttributeEncodedData\n        {\n            get\n            {\n                var result = new TheoryDataSet<string, bool, string>();\n                foreach (var stringSet in StringSets)\n                {\n                    // Same results whether ModelMetadata.HtmlEncode is true or false.\n                    result.Add(stringSet.Text, false, stringSet.AttributeEncodedText);\n                    result.Add(stringSet.Text, true, stringSet.AttributeEncodedText);\n                }\n\n                return result;\n            }\n        }\n\n        public static TheoryDataSet<string, bool> AttributeEncodedData_NoEncodedText\n        {\n            get\n            {\n                var dataSet = new TheoryDataSet<string, bool>();\n                foreach (var stringSet in StringSets)\n                {\n                    dataSet.Add(stringSet.Text, false);\n                    dataSet.Add(stringSet.Text, true);\n                }\n\n                return dataSet;\n            }\n        }\n\n        public static TheoryDataSet<string, string> AttributeEncodedData_NoHtmlEncode\n        {\n            get\n            {\n                var dataSet = new TheoryDataSet<string, string>();\n                foreach (var stringSet in StringSets)\n                {\n                    dataSet.Add(stringSet.Text, stringSet.AttributeEncodedText);\n                }\n\n                return dataSet;\n            }\n        }\n\n        public static TheoryDataSet<string, bool, string> ConditionallyHtmlEncodedData\n        {\n            get\n            {\n                var result = new TheoryDataSet<string, bool, string>();\n                foreach (var stringSet in StringSets)\n                {\n                    result.Add(stringSet.Text, false, stringSet.Text);\n                    result.Add(stringSet.Text, true, stringSet.HtmlEncodedText);\n                }\n\n                return result;\n            }\n        }\n\n        public static TheoryDataSet<string, bool> ConditionallyHtmlEncodedData_NoEncodedText\n        {\n            get\n            {\n                var dataSet = new TheoryDataSet<string, bool>();\n                foreach (var stringSet in StringSets)\n                {\n                    dataSet.Add(stringSet.Text, false);\n                    dataSet.Add(stringSet.Text, true);\n                }\n\n                return dataSet;\n            }\n        }\n\n        public static TheoryDataSet<string, bool, string> HtmlEncodedData\n        {\n            get\n            {\n                var result = new TheoryDataSet<string, bool, string>();\n                foreach (var stringSet in StringSets)\n                {\n                    // Same results whether ModelMetadata.HtmlEncode is true or false.\n                    result.Add(stringSet.Text, false, stringSet.HtmlEncodedText);\n                    result.Add(stringSet.Text, true, stringSet.HtmlEncodedText);\n                }\n\n                return result;\n            }\n        }\n\n        public static TheoryDataSet<string, string> HtmlEncodedData_NoHtmlEncode\n        {\n            get\n            {\n                var dataSet = new TheoryDataSet<string, string>();\n                foreach (var stringSet in StringSets)\n                {\n                    dataSet.Add(stringSet.Text, stringSet.HtmlEncodedText);\n                }\n\n                return dataSet;\n            }\n        }\n\n        public static TheoryDataSet<string> HtmlEncodedData_JustText\n        {\n            get\n            {\n                var dataSet = new TheoryDataSet<string>();\n                foreach (var stringSet in StringSets)\n                {\n                    dataSet.Add(stringSet.Text);\n                }\n\n                return dataSet;\n            }\n        }\n\n        public static TheoryDataSet<string, bool, string> IdEncodedData\n        {\n            get\n            {\n                var result = new TheoryDataSet<string, bool, string>();\n                foreach (var encodedString in StringSets)\n                {\n                    // Same results whether ModelMetadata.HtmlEncode is true or false.\n                    // Add leading 'a' to avoid sanitizing to an empty string.\n                    result.Add(\"a\" + encodedString.Text, false, \"a\" + encodedString.IdEncodedText);\n                    result.Add(\"a\" + encodedString.Text, true, \"a\" + encodedString.IdEncodedText);\n                }\n\n                return result;\n            }\n        }\n\n        public static TheoryDataSet<string, string> IdEncodedData_NoHtmlEncode\n        {\n            get\n            {\n                var result = new TheoryDataSet<string, string>();\n                foreach (var encodedString in StringSets)\n                {\n                    // Add leading 'a' to avoid sanitizing to an empty string.\n                    result.Add(\"a\" + encodedString.Text, \"a\" + encodedString.IdEncodedText);\n                }\n\n                return result;\n            }\n        }\n\n        public static TheoryDataSet<string, bool, string> UrlEncodedData\n        {\n            get\n            {\n                var result = new TheoryDataSet<string, bool, string>();\n                foreach (var encodedString in StringSets)\n                {\n                    // Same results whether ModelMetadata.HtmlEncode is true or false.\n                    result.Add(encodedString.Text, false, encodedString.UrlEncodedText);\n                    result.Add(encodedString.Text, true, encodedString.UrlEncodedText);\n                }\n\n                return result;\n            }\n        }\n\n        public static TheoryDataSet<string, string> UrlEncodedData_NoHtmlEncode\n        {\n            get\n            {\n                var result = new TheoryDataSet<string, string>();\n                foreach (var encodedString in StringSets)\n                {\n                    result.Add(encodedString.Text, encodedString.UrlEncodedText);\n                }\n\n                return result;\n            }\n        }\n\n        private class StringSet\n        {\n            public StringSet(string text, string attributeEncodedText, string htmlEncodedText, string idEncodedText)\n                : this(text, attributeEncodedText, htmlEncodedText, idEncodedText, Uri.EscapeUriString(text))\n            {\n            }\n\n            public StringSet(\n                string text,\n                string attributeEncodedText,\n                string htmlEncodedText,\n                string idEncodedText,\n                string urlEncodedText)\n            {\n                Contract.Assert(!String.IsNullOrEmpty(text));\n                Contract.Assert(!String.IsNullOrEmpty(attributeEncodedText));\n                Contract.Assert(!String.IsNullOrEmpty(htmlEncodedText));\n                Contract.Assert(!String.IsNullOrEmpty(idEncodedText));\n                Contract.Assert(!String.IsNullOrEmpty(urlEncodedText));\n\n                // Override default UrlEncodedText.\n                Text = text;\n                AttributeEncodedText = attributeEncodedText;\n                HtmlEncodedText = htmlEncodedText;\n                IdEncodedText = idEncodedText;\n                UrlEncodedText = urlEncodedText;\n            }\n\n            public string Text { get; private set; }\n\n            public string AttributeEncodedText { get; private set; }\n\n            public string HtmlEncodedText { get; private set; }\n\n            public string IdEncodedText { get; private set; }\n\n            public string UrlEncodedText { get; private set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Html/Test/EnumHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Web.Script.Serialization;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Html.Test\n{\n    public class EnumHelperTest\n    {\n        private static JavaScriptSerializer _serializer = new JavaScriptSerializer();\n\n        // IsValidForEnumHelper()\n\n        public static TheoryDataSet<Type, bool> IsValidForEnumHelperData\n        {\n            get\n            {\n                return new TheoryDataSet<Type, bool>\n                {\n                    { typeof(int), false },\n                    { typeof(int?), false },\n                    { typeof(EnumHelperTest), false },\n                    { typeof(Enum), false },\n                    { typeof(EnumWithDisplay), true },\n                    { typeof(EnumWithoutAnything), true },\n                    { typeof(EnumWithoutZero?), true },\n                    { typeof(EnumWithFlags), false },\n                    { typeof(EnumWithFlags?), false },\n                };\n            }\n        }\n\n        [Theory]\n        [InlineData(null, false)]\n        [PropertyData(\"IsValidForEnumHelperData\")]\n        public void IsValidForEnumHelperWithTypeIsSuccessful(Type type, bool expected)\n        {\n            // Arrange & Act\n            bool isValid = EnumHelper.IsValidForEnumHelper(type);\n\n            // Assert\n            Assert.Equal(expected, isValid);\n        }\n\n        [Fact]\n        public void IsValidForEnumHelperWithNullMetadataIsSuccessful()\n        {\n            // Arrange & Act\n            bool isValid = EnumHelper.IsValidForEnumHelper((ModelMetadata)null);\n\n            // Assert\n            Assert.False(isValid);\n        }\n\n        // No way to run a test with non-null ModelMetadata and null ModelType\n        [Theory]\n        [PropertyData(\"IsValidForEnumHelperData\")]\n        public void IsValidForEnumHelperWithMetadataIsSuccessful(Type type, bool expected)\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            ModelMetadata metadata = new ModelMetadata(provider.Object, null, null, type, null);\n\n            // Act\n            bool isValid = EnumHelper.IsValidForEnumHelper(metadata);\n\n            // Assert\n            Assert.Equal(expected, isValid);\n        }\n\n        // GetSelectList()\n\n        public static TheoryDataSet<Type, string> GetSelectListIsSuccessfulData\n        {\n            get\n            {\n                return new TheoryDataSet<Type, string>\n                {\n                    { typeof(EnumWithDisplay),\n                        \"[{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"First\\\",\\\"Value\\\":\\\"0\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Second\\\",\\\"Value\\\":\\\"1\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Third\\\",\\\"Value\\\":\\\"2\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Fourth\\\",\\\"Value\\\":\\\"3\\\"}]\" },\n                    { typeof(EnumWithDuplicates),\n                        \"[{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"First\\\",\\\"Value\\\":\\\"0\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Second\\\",\\\"Value\\\":\\\"1\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Third\\\",\\\"Value\\\":\\\"1\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Fourth\\\",\\\"Value\\\":\\\"2\\\"}]\" },\n                    { typeof(EnumWithGaps),\n                        \"[{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"First\\\",\\\"Value\\\":\\\"0\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Second\\\",\\\"Value\\\":\\\"2\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Third\\\",\\\"Value\\\":\\\"4\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Fourth\\\",\\\"Value\\\":\\\"6\\\"}]\" },\n                    { typeof(EnumWithoutAnything), \"[]\" },\n                    { typeof(EnumWithoutZero),\n                        \"[{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"First\\\",\\\"Value\\\":\\\"12\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Second\\\",\\\"Value\\\":\\\"13\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Third\\\",\\\"Value\\\":\\\"14\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Fourth\\\",\\\"Value\\\":\\\"15\\\"}]\" },\n                    { typeof(EnumWithReversedValues),\n                        \"[{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"First\\\",\\\"Value\\\":\\\"3\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Second\\\",\\\"Value\\\":\\\"2\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Third\\\",\\\"Value\\\":\\\"1\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Fourth\\\",\\\"Value\\\":\\\"0\\\"}]\" },\n                    { typeof(EnumWithReversedValues?),\n                        \"[{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"\\\",\\\"Value\\\":\\\"\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"First\\\",\\\"Value\\\":\\\"3\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Second\\\",\\\"Value\\\":\\\"2\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Third\\\",\\\"Value\\\":\\\"1\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Fourth\\\",\\\"Value\\\":\\\"0\\\"}]\" },\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"GetSelectListIsSuccessfulData\")]\n        public void GetSelectListWithTypeIsSuccessful(Type type, string expected)\n        {\n            // Arrange & Act\n            IList<SelectListItem> selectList = EnumHelper.GetSelectList(type);\n\n            // Assert\n            Assert.Equal(expected, SelectListToString(selectList));\n        }\n\n        [Theory]\n        [PropertyData(\"GetSelectListIsSuccessfulData\")]\n        public void GetSelectListWithMetadataIsSuccessful(Type type, string expected)\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            ModelMetadata metadata = new ModelMetadata(provider.Object, null, null, type, null);\n\n            // Act\n            IList<SelectListItem> selectList = EnumHelper.GetSelectList(metadata);\n\n            // Assert\n            Assert.Equal(expected, SelectListToString(selectList));\n        }\n\n        public static TheoryDataSet<Type, Enum, string> GetSelectListWithEnumIsSuccessfulData\n        {\n            get\n            {\n                return new TheoryDataSet<Type, Enum, string>\n                {\n                    { typeof(EnumWithDisplay?), EnumWithDisplay.Zero,\n                        \"[{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"\\\",\\\"Value\\\":\\\"\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":true,\\\"Text\\\":\\\"First\\\",\\\"Value\\\":\\\"0\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Second\\\",\\\"Value\\\":\\\"1\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Third\\\",\\\"Value\\\":\\\"2\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Fourth\\\",\\\"Value\\\":\\\"3\\\"}]\" },\n                    { typeof(EnumWithDuplicates), EnumWithDuplicates.Second, // Same value as EnumWithDuplicates.Third\n                        \"[{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"First\\\",\\\"Value\\\":\\\"0\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Second\\\",\\\"Value\\\":\\\"1\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":true,\\\"Text\\\":\\\"Third\\\",\\\"Value\\\":\\\"1\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Fourth\\\",\\\"Value\\\":\\\"2\\\"}]\" },\n                    { typeof(EnumWithGaps?), EnumWithGaps.Third,\n                        \"[{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"\\\",\\\"Value\\\":\\\"\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"First\\\",\\\"Value\\\":\\\"0\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Second\\\",\\\"Value\\\":\\\"2\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":true,\\\"Text\\\":\\\"Third\\\",\\\"Value\\\":\\\"4\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Fourth\\\",\\\"Value\\\":\\\"6\\\"}]\" },\n                    { typeof(EnumWithoutAnything), (EnumWithoutAnything)0,\n                        \"[{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":true,\\\"Text\\\":\\\"\\\",\\\"Value\\\":\\\"0\\\"}]\" },\n                    { typeof(EnumWithoutZero), EnumWithoutZero.Fourth,\n                        \"[{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"First\\\",\\\"Value\\\":\\\"12\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Second\\\",\\\"Value\\\":\\\"13\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Third\\\",\\\"Value\\\":\\\"14\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":true,\\\"Text\\\":\\\"Fourth\\\",\\\"Value\\\":\\\"15\\\"}]\" },\n                    { typeof(EnumWithoutZero), (EnumWithoutZero)0,\n                        \"[{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":true,\\\"Text\\\":\\\"\\\",\\\"Value\\\":\\\"0\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"First\\\",\\\"Value\\\":\\\"12\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Second\\\",\\\"Value\\\":\\\"13\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Third\\\",\\\"Value\\\":\\\"14\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Fourth\\\",\\\"Value\\\":\\\"15\\\"}]\" },\n                    { typeof(EnumWithReversedValues?), (EnumWithReversedValues)32,\n                        \"[{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":true,\\\"Text\\\":\\\"\\\",\\\"Value\\\":\\\"32\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"First\\\",\\\"Value\\\":\\\"3\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Second\\\",\\\"Value\\\":\\\"2\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Third\\\",\\\"Value\\\":\\\"1\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Fourth\\\",\\\"Value\\\":\\\"0\\\"}]\" },\n                    { typeof(EnumWithDisplay?), null,\n                        \"[{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":true,\\\"Text\\\":\\\"\\\",\\\"Value\\\":\\\"\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"First\\\",\\\"Value\\\":\\\"0\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Second\\\",\\\"Value\\\":\\\"1\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Third\\\",\\\"Value\\\":\\\"2\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Fourth\\\",\\\"Value\\\":\\\"3\\\"}]\" },\n                    { typeof(EnumWithDuplicates), null,\n                        \"[{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":true,\\\"Text\\\":\\\"First\\\",\\\"Value\\\":\\\"0\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Second\\\",\\\"Value\\\":\\\"1\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Third\\\",\\\"Value\\\":\\\"1\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Fourth\\\",\\\"Value\\\":\\\"2\\\"}]\" },\n                    { typeof(EnumWithoutZero), null,\n                        \"[{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":true,\\\"Text\\\":\\\"\\\",\\\"Value\\\":\\\"0\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"First\\\",\\\"Value\\\":\\\"12\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Second\\\",\\\"Value\\\":\\\"13\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Third\\\",\\\"Value\\\":\\\"14\\\"},\" +\n                        \"{\\\"Disabled\\\":false,\\\"Group\\\":null,\\\"Selected\\\":false,\\\"Text\\\":\\\"Fourth\\\",\\\"Value\\\":\\\"15\\\"}]\" },\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"GetSelectListWithEnumIsSuccessfulData\")]\n        public void GetSelectListWithTypeAndEnumIsSuccessful(Type type, Enum value, string expected)\n        {\n            // Arrange & Act\n            IList<SelectListItem> selectList = EnumHelper.GetSelectList(type, value);\n\n            // Assert\n            Assert.Equal(expected, SelectListToString(selectList));\n        }\n\n        [Theory]\n        [PropertyData(\"GetSelectListWithEnumIsSuccessfulData\")]\n        public void GetSelectListWithMetadataAndEnumIsSuccessful(Type type, Enum value, string expected)\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            ModelMetadata metadata = new ModelMetadata(provider.Object, null, null, type, null);\n\n            // Act\n            IList<SelectListItem> selectList = EnumHelper.GetSelectList(metadata, value);\n\n            // Assert\n            Assert.Equal(expected, SelectListToString(selectList));\n        }\n\n        [Fact]\n        public void GetSelectListWithTypeThrowsArgumentNull()\n        {\n            // Arrange & Act & Assert\n            Assert.ThrowsArgumentNull(() => EnumHelper.GetSelectList((Type)null), \"type\");\n        }\n\n        [Fact]\n        public void GetSelectListWithMetadataThrowsArgumentNull()\n        {\n            // Arrange & Act & Assert\n            Assert.ThrowsArgumentNull(() => EnumHelper.GetSelectList((ModelMetadata)null), \"metadata\");\n        }\n\n        [Fact]\n        public void GetSelectListWithTypeAndEnumThrowsArgumentNull()\n        {\n            // Arrange & Act & Assert\n            Assert.ThrowsArgumentNull(() => EnumHelper.GetSelectList((Type)null, EnumWithDisplay.Two), \"type\");\n        }\n\n        [Fact]\n        public void GetSelectListWithMetadataAndEnumThrowsArgumentNull()\n        {\n            // Arrange & Act & Assert\n            Assert.ThrowsArgumentNull(() => EnumHelper.GetSelectList((ModelMetadata)null, EnumWithDisplay.Two), \"metadata\");\n        }\n\n        public static TheoryDataSet<Type> GetSelectListThrowsArgumentData\n        {\n            get\n            {\n                return new TheoryDataSet<Type>\n                {\n                    { typeof(int) },\n                    { typeof(int?) },\n                    { typeof(EnumHelperTest) },\n                    { typeof(Enum) },\n                    { typeof(EnumWithFlags) },\n                    { typeof(EnumWithFlags?) },\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"GetSelectListThrowsArgumentData\")]\n        public void GetSelectListWithTypeThrowsArgument(Type type)\n        {\n            // Arrange & Act & Assert\n            Assert.ThrowsArgument(() => EnumHelper.GetSelectList(type), \"type\");\n        }\n\n        // No way to run a test with non-null ModelMetadata and null ModelType\n        [Theory]\n        [PropertyData(\"GetSelectListThrowsArgumentData\")]\n        public void GetSelectListWithMetadataThrowsArgument(Type type)\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            ModelMetadata metadata = new ModelMetadata(provider.Object, null, null, type, null);\n\n            // Act & Assert\n            Assert.ThrowsArgument(() => EnumHelper.GetSelectList(metadata), \"metadata\");\n        }\n\n        [Theory]\n        [PropertyData(\"GetSelectListThrowsArgumentData\")]\n        public void GetSelectListWithTypeAndEnumThrowsArgument(Type type)\n        {\n            // Arrange & Act & Assert\n            Assert.ThrowsArgument(() => EnumHelper.GetSelectList(type, EnumWithDisplay.Two), \"type\");\n        }\n\n        // No way to run a test with non-null ModelMetadata and null ModelType\n        [Theory]\n        [PropertyData(\"GetSelectListThrowsArgumentData\")]\n        public void GetSelectListWithMetadataAndEnumThrowsArgument(Type type)\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            ModelMetadata metadata = new ModelMetadata(provider.Object, null, null, type, null);\n\n            // Act & Assert\n            Assert.ThrowsArgument(() => EnumHelper.GetSelectList(metadata, EnumWithDisplay.Two), \"metadata\");\n        }\n\n        [Fact]\n        public void GetSelectListWithTypeAndEnumThrowsArgumentOnMismatch()\n        {\n            // Arrange & Act & Assert\n            Assert.ThrowsArgument(() => EnumHelper.GetSelectList(typeof(EnumWithDuplicates), EnumWithDisplay.Two),\n                paramName: \"value\",\n                exceptionMessage: \"Invalid value parameter type \" +\n                \"'System.Web.Mvc.Html.Test.EnumHelperTest+EnumWithDisplay'. Must match type parameter \" +\n                \"'System.Web.Mvc.Html.Test.EnumHelperTest+EnumWithDuplicates'.\" + Environment.NewLine +\n                \"Parameter name: value\");\n        }\n\n        [Fact]\n        public void GetSelectListWithMetadataAndEnumThrowsArgumentOnMismatch()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            ModelMetadata metadata = new ModelMetadata(provider.Object, null, null, typeof(EnumWithDuplicates), null);\n\n            // Act & Assert\n            Assert.ThrowsArgument(() => EnumHelper.GetSelectList(metadata, EnumWithDisplay.Two), paramName: \"value\",\n                exceptionMessage: \"Invalid value parameter type \" +\n                \"'System.Web.Mvc.Html.Test.EnumHelperTest+EnumWithDisplay'. Must match type parameter \" +\n                \"'System.Web.Mvc.Html.Test.EnumHelperTest+EnumWithDuplicates'.\" + Environment.NewLine +\n                \"Parameter name: value\");\n        }\n\n        // helpers\n\n        private static string SelectListToString(IList<SelectListItem> selectList)\n        {\n            return _serializer.Serialize(selectList);\n        }\n\n        // enum definitions\n\n        private enum EnumWithDisplay : byte\n        {\n            [Display(Name=\"First\")]\n            Zero,\n            [Display(Name = \"Second\")]\n            One,\n            [Display(Name = \"Third\")]\n            Two,\n            [Display(Name = \"Fourth\")]\n            Three,\n        }\n\n        private enum EnumWithoutAnything : byte\n        {\n        }\n\n        private enum EnumWithoutZero : byte\n        {\n            First = 12,\n            Second,\n            Third,\n            Fourth,\n        }\n\n        private enum EnumWithDuplicates : byte\n        {\n            First,\n            Second,\n            Third = 1,\n            Fourth,\n        }\n\n        private enum EnumWithGaps : byte\n        {\n            First,\n            Second = 2,\n            Third = 4,\n            Fourth = 6,\n        }\n\n        private enum EnumWithReversedValues : byte\n        {\n            First = 3,\n            Second = 2,\n            Third = 1,\n            Fourth = 0,\n        }\n\n        [Flags]\n        private enum EnumWithFlags : byte\n        {\n            First = 1,\n            Second = 2,\n            Third = 4,\n            Fourth = 8,\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Html/Test/FormExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Specialized;\nusing System.IO;\nusing System.Web.Routing;\nusing System.Web.WebPages.Scope;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\nusing Moq;\n\nnamespace System.Web.Mvc.Html.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")]\n    public class FormExtensionsTest : IDisposable\n    {\n        private static void BeginFormHelper(Func<HtmlHelper, MvcForm> beginForm, string expectedFormTag)\n        {\n            // Arrange\n            StringWriter writer;\n            HtmlHelper htmlHelper = GetFormHelper(out writer);\n\n            // Act\n            IDisposable formDisposable = beginForm(htmlHelper);\n            formDisposable.Dispose();\n\n            // Assert\n            Assert.Equal(expectedFormTag + \"</form>\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormParameterDictionaryMerging()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginForm(\"bar\", \"foo\", FormMethod.Get, new RouteValueDictionary(new { method = \"post\" })),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/foo/bar\"\" method=\"\"get\"\">\");\n        }\n\n        [Fact]\n        public void BeginFormSetsAndRestoresToDefault()\n        {\n            // Arrange\n            StringWriter writer;\n            HtmlHelper htmlHelper = GetFormHelper(out writer);\n\n            htmlHelper.ViewContext.FormContext = null;\n            FormContext defaultFormContext = htmlHelper.ViewContext.FormContext;\n\n            // Act & assert - push\n            MvcForm theForm = htmlHelper.BeginForm();\n            Assert.NotNull(htmlHelper.ViewContext.FormContext);\n            Assert.NotEqual(defaultFormContext, htmlHelper.ViewContext.FormContext);\n\n            // Act & assert - pop\n            theForm.Dispose();\n            Assert.Equal(defaultFormContext, htmlHelper.ViewContext.FormContext);\n            Assert.Equal(@\"<form action=\"\"/some/path\"\" method=\"\"post\"\"></form>\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormWithClientValidationEnabled()\n        {\n            // Arrange\n            StringWriter writer;\n            HtmlHelper htmlHelper = GetFormHelper(out writer);\n\n            htmlHelper.ViewContext.ClientValidationEnabled = true;\n            htmlHelper.ViewContext.FormContext = null;\n            FormContext defaultFormContext = htmlHelper.ViewContext.FormContext;\n\n            // Act & assert - push\n            MvcForm theForm = htmlHelper.BeginForm();\n            Assert.NotNull(htmlHelper.ViewContext.FormContext);\n            Assert.NotEqual(defaultFormContext, htmlHelper.ViewContext.FormContext);\n            Assert.Equal(\"form_id\", htmlHelper.ViewContext.FormContext.FormId);\n\n            // Act & assert - pop\n            theForm.Dispose();\n            Assert.Equal(defaultFormContext, htmlHelper.ViewContext.FormContext);\n            Assert.Equal(@\"<form action=\"\"/some/path\"\" id=\"\"form_id\"\" method=\"\"post\"\"></form><script type=\"\"text/javascript\"\">\n//<![CDATA[\nif (!window.mvcClientValidationMetadata) { window.mvcClientValidationMetadata = []; }\nwindow.mvcClientValidationMetadata.push({\"\"Fields\"\":[],\"\"FormId\"\":\"\"form_id\"\",\"\"ReplaceValidationSummary\"\":false});\n//]]>\n</script>\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormWithClientValidationAndUnobtrusiveJavaScriptEnabled()\n        {\n            // Arrange\n            StringWriter writer;\n            HtmlHelper htmlHelper = GetFormHelper(out writer);\n\n            htmlHelper.ViewContext.ClientValidationEnabled = true;\n            htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled = true;\n\n            // Act & assert - push\n            MvcForm theForm = htmlHelper.BeginForm();\n            Assert.Null(htmlHelper.ViewContext.FormContext.FormId);\n\n            // Act & assert - pop\n            theForm.Dispose();\n            Assert.Equal(@\"<form action=\"\"/some/path\"\" method=\"\"post\"\"></form>\", writer.ToString());\n        }\n\n        [Fact]\n        public void BeginFormWithActionControllerInvalidFormMethodHtmlValues()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginForm(\"bar\", \"foo\", (FormMethod)2, new RouteValueDictionary(new { baz = \"baz\" })),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/foo/bar\"\" baz=\"\"baz\"\" method=\"\"post\"\">\");\n        }\n\n        [Fact]\n        public void BeginFormWithActionController()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginForm(\"bar\", \"foo\"),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/foo/bar\"\" method=\"\"post\"\">\");\n        }\n\n        [Theory]\n        [PropertyData(\"UrlEncodedData_NoHtmlEncode\", PropertyType = typeof(EncodedDataSets))]\n        public void BeginFormWithActionController_UrlEncodesAction(\n            string text,\n            string expectedText)\n        {\n            BeginFormHelper(\n                helper => helper.BeginForm(text, \"controller\"),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + \"/controller/\" + expectedText + @\"\"\" method=\"\"post\"\">\");\n        }\n\n        [Theory]\n        [PropertyData(\"UrlEncodedData_NoHtmlEncode\", PropertyType = typeof(EncodedDataSets))]\n        public void BeginFormWithActionController_UrlEncodesController(\n            string text,\n            string expectedText)\n        {\n            BeginFormHelper(\n                helper => helper.BeginForm(\"action\", text),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + \"/\" + expectedText + @\"/action\"\" method=\"\"post\"\">\");\n        }\n\n        [Fact]\n        public void BeginFormWithActionControllerFormMethodHtmlDictionary()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginForm(\"bar\", \"foo\", FormMethod.Get, new RouteValueDictionary(new { baz = \"baz\" })),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/foo/bar\"\" baz=\"\"baz\"\" method=\"\"get\"\">\");\n        }\n\n        [Fact]\n        public void BeginFormWithActionControllerFormMethodHtmlValues()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginForm(\"bar\", \"foo\", FormMethod.Get, new { baz = \"baz\" }),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/foo/bar\"\" baz=\"\"baz\"\" method=\"\"get\"\">\");\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData_NoHtmlEncode\", PropertyType = typeof(EncodedDataSets))]\n        public void BeginFormWithActionControllerFormMethodHtmlValues_AttributeEncodes_AddedHtmlAttributes(\n            string text,\n            string expectedText)\n        {\n            BeginFormHelper(\n                helper => helper.BeginForm(\"action\", \"controller\", FormMethod.Get, new { attribute = text }),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/controller/action\"\" attribute=\"\"\" +\n                    expectedText +\n                    @\"\"\" method=\"\"get\"\">\");\n        }\n\n        [Fact]\n        public void BeginFormWithActionControllerFormMethodHtmlValuesWithUnderscores()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginForm(\"bar\", \"foo\", FormMethod.Get, new { data_test = \"value\" }),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/foo/bar\"\" data-test=\"\"value\"\" method=\"\"get\"\">\");\n        }\n\n        [Fact]\n        public void BeginFormWithActionControllerRouteDictionaryFormMethodHtmlDictionary()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginForm(\"bar\", \"foo\", new RouteValueDictionary(new { id = \"id\" }), FormMethod.Get, new RouteValueDictionary(new { baz = \"baz\" })),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/foo/bar/id\"\" baz=\"\"baz\"\" method=\"\"get\"\">\");\n        }\n\n        [Fact]\n        public void BeginFormWithActionControllerRouteValuesFormMethodHtmlValues()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginForm(\"bar\", \"foo\", new { id = \"id\" }, FormMethod.Get, new { baz = \"baz\" }),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/foo/bar/id\"\" baz=\"\"baz\"\" method=\"\"get\"\">\");\n        }\n\n        [Fact]\n        public void BeginFormWithActionControllerRouteValuesFormMethodHtmlValuesWithUnderscores()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginForm(\"bar\", \"foo\", new { id = \"id\" }, FormMethod.Get, new { foo_baz = \"baz\" }),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/foo/bar/id\"\" foo-baz=\"\"baz\"\" method=\"\"get\"\">\");\n        }\n\n        [Fact]\n        public void BeginFormWithActionControllerNullRouteValuesFormMethodNullHtmlValues()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginForm(\"bar\", \"foo\", null, FormMethod.Get, null),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/foo/bar\"\" method=\"\"get\"\">\");\n        }\n\n        [Fact]\n        public void BeginFormWithRouteValues()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginForm(new { action = \"someOtherAction\", id = \"id\" }),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/home/someOtherAction/id\"\" method=\"\"post\"\">\");\n        }\n\n        [Fact]\n        public void BeginFormWithRouteDictionary()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginForm(new RouteValueDictionary { { \"action\", \"someOtherAction\" }, { \"id\", \"id\" } }),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/home/someOtherAction/id\"\" method=\"\"post\"\">\");\n        }\n\n        [Fact]\n        public void BeginFormWithActionControllerRouteValues()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginForm(\"myAction\", \"myController\", new { id = \"id\", pageNum = \"123\" }),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/myController/myAction/id?pageNum=123\"\" method=\"\"post\"\">\");\n        }\n\n        [Fact]\n        public void BeginFormWithActionControllerRouteDictionary()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginForm(\"myAction\", \"myController\", new RouteValueDictionary { { \"pageNum\", \"123\" }, { \"id\", \"id\" } }),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/myController/myAction/id?pageNum=123\"\" method=\"\"post\"\">\");\n        }\n\n        [Fact]\n        public void BeginFormWithActionControllerMethod()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginForm(\"myAction\", \"myController\", FormMethod.Get),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/myController/myAction\"\" method=\"\"get\"\">\");\n        }\n\n        [Fact]\n        public void BeginFormWithActionControllerRouteValuesMethod()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginForm(\"myAction\", \"myController\", new { id = \"id\", pageNum = \"123\" }, FormMethod.Get),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/myController/myAction/id?pageNum=123\"\" method=\"\"get\"\">\");\n        }\n\n        [Fact]\n        public void BeginFormWithActionControllerRouteDictionaryMethod()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginForm(\"myAction\", \"myController\", new RouteValueDictionary { { \"pageNum\", \"123\" }, { \"id\", \"id\" } }, FormMethod.Get),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/myController/myAction/id?pageNum=123\"\" method=\"\"get\"\">\");\n        }\n\n        [Fact]\n        public void BeginFormWithNoParams()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginForm(),\n                @\"<form action=\"\"/some/path\"\" method=\"\"post\"\">\");\n        }\n\n        [Fact]\n        public void BeginRouteFormWithRouteNameInvalidFormMethodHtmlValues()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginRouteForm(\"namedroute\", (FormMethod)2, new RouteValueDictionary(new { baz = \"baz\" })),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/named/home/oldaction\"\" baz=\"\"baz\"\" method=\"\"post\"\">\");\n        }\n\n        [Fact]\n        public void BeginRouteFormWithRouteName()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginRouteForm(\"namedroute\"),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/named/home/oldaction\"\" method=\"\"post\"\">\");\n        }\n\n        [Fact]\n        public void BeginRouteFormWithRouteNameFormMethodHtmlDictionary()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginRouteForm(\"namedroute\", FormMethod.Get, new RouteValueDictionary(new { baz = \"baz\" })),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/named/home/oldaction\"\" baz=\"\"baz\"\" method=\"\"get\"\">\");\n        }\n\n        [Fact]\n        public void BeginRouteFormWithRouteNameFormMethodHtmlValues()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginRouteForm(\"namedroute\", FormMethod.Get, new { baz = \"baz\" }),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/named/home/oldaction\"\" baz=\"\"baz\"\" method=\"\"get\"\">\");\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData_NoHtmlEncode\", PropertyType = typeof(EncodedDataSets))]\n        public void BeginRouteFormWithRouteNameFormMethodHtmlValues_AttributeEncodes_AddedHtmlAttributes(\n            string text,\n            string expectedText)\n        {\n            BeginFormHelper(\n                helper => helper.BeginRouteForm(\"namedroute\", FormMethod.Get, new { attribute = text }),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/named/home/oldaction\"\" attribute=\"\"\" +\n                    expectedText +\n                    @\"\"\" method=\"\"get\"\">\");\n        }\n\n        [Fact]\n        public void BeginRouteFormWithRouteNameFormMethodHtmlValuesWithUnderscores()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginRouteForm(\"namedroute\", FormMethod.Get, new { foo_baz = \"baz\" }),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/named/home/oldaction\"\" foo-baz=\"\"baz\"\" method=\"\"get\"\">\");\n        }\n\n        [Fact]\n        public void BeginRouteFormWithRouteNameRouteDictionaryFormMethodHtmlDictionary()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginRouteForm(\"namedroute\", new RouteValueDictionary(new { id = \"id\" }), FormMethod.Get, new RouteValueDictionary(new { baz = \"baz\" })),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/named/home/oldaction/id\"\" baz=\"\"baz\"\" method=\"\"get\"\">\");\n        }\n\n        [Fact]\n        public void BeginRouteFormWithRouteNameRouteValuesFormMethodHtmlValues()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginRouteForm(\"namedroute\", new { id = \"id\" }, FormMethod.Get, new { baz = \"baz\" }),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/named/home/oldaction/id\"\" baz=\"\"baz\"\" method=\"\"get\"\">\");\n        }\n\n        [Fact]\n        public void BeginRouteFormWithRouteNameRouteValuesFormMethodHtmlValuesWithUnderscores()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginRouteForm(\"namedroute\", new { id = \"id\" }, FormMethod.Get, new { foo_baz = \"baz\" }),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/named/home/oldaction/id\"\" foo-baz=\"\"baz\"\" method=\"\"get\"\">\");\n        }\n\n        [Fact]\n        public void BeginRouteFormWithRouteNameNullRouteValuesFormMethodNullHtmlValues()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginRouteForm(\"namedroute\", null, FormMethod.Get, null),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/named/home/oldaction\"\" method=\"\"get\"\">\");\n        }\n\n        [Fact]\n        public void BeginRouteFormWithRouteValues()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginRouteForm(new { action = \"someOtherAction\", id = \"id\" }),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/home/someOtherAction/id\"\" method=\"\"post\"\">\");\n        }\n\n        [Fact]\n        public void BeginRouteFormWithRouteDictionary()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginRouteForm(new RouteValueDictionary { { \"action\", \"someOtherAction\" }, { \"id\", \"id\" } }),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/home/someOtherAction/id\"\" method=\"\"post\"\">\");\n        }\n\n        [Fact]\n        public void BeginRouteFormWithRouteNameRouteValues()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginRouteForm(\"namedroute\", new { id = \"id\", pageNum = \"123\" }),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/named/home/oldaction/id?pageNum=123\"\" method=\"\"post\"\">\");\n        }\n\n        [Fact]\n        public void BeginRouteFormWithActionControllerRouteDictionary()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginRouteForm(\"namedroute\", new RouteValueDictionary { { \"pageNum\", \"123\" }, { \"id\", \"id\" } }),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/named/home/oldaction/id?pageNum=123\"\" method=\"\"post\"\">\");\n        }\n\n        [Fact]\n        public void BeginRouteFormCanUseNamedRouteWithoutSpecifyingDefaults()\n        {\n            // DevDiv 217072: Non-mvc specific helpers should not give default values for controller and action\n\n            BeginFormHelper(\n                htmlHelper =>\n                {\n                    htmlHelper.RouteCollection.MapRoute(\"MyRouteName\", \"any/url\", new { controller = \"Charlie\" });\n                    return htmlHelper.BeginRouteForm(\"MyRouteName\");\n                }, @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/any/url\"\" method=\"\"post\"\">\");\n        }\n\n        [Fact]\n        public void BeginRouteFormWithActionControllerMethod()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginRouteForm(\"namedroute\", FormMethod.Get),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/named/home/oldaction\"\" method=\"\"get\"\">\");\n        }\n\n        [Fact]\n        public void BeginRouteFormWithActionControllerRouteValuesMethod()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginRouteForm(\"namedroute\", new { id = \"id\", pageNum = \"123\" }, FormMethod.Get),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/named/home/oldaction/id?pageNum=123\"\" method=\"\"get\"\">\");\n        }\n\n        [Fact]\n        public void BeginRouteFormWithActionControllerRouteDictionaryMethod()\n        {\n            BeginFormHelper(\n                htmlHelper => htmlHelper.BeginRouteForm(\"namedroute\", new RouteValueDictionary { { \"pageNum\", \"123\" }, { \"id\", \"id\" } }, FormMethod.Get),\n                @\"<form action=\"\"\" + MvcHelper.AppPathModifier + @\"/named/home/oldaction/id?pageNum=123\"\" method=\"\"get\"\">\");\n        }\n\n        [Fact]\n        public void EndFormWritesCloseTag()\n        {\n            // Arrange\n            StringWriter writer;\n            HtmlHelper htmlHelper = GetFormHelper(out writer);\n\n            // Act\n            htmlHelper.EndForm();\n\n            // Assert\n            Assert.Equal(\"</form>\", writer.ToString());\n        }\n\n        private static HtmlHelper GetFormHelper(out StringWriter writer)\n        {\n            Mock<ViewContext> mockViewContext = new Mock<ViewContext>() { CallBase = true };\n            mockViewContext.Setup(c => c.HttpContext.Request.Url).Returns(new Uri(\"http://www.contoso.com/some/path\"));\n            mockViewContext.Setup(c => c.HttpContext.Request.RawUrl).Returns(\"/some/path\");\n            mockViewContext.Setup(c => c.HttpContext.Request.ApplicationPath).Returns(\"/\");\n            mockViewContext.Setup(c => c.HttpContext.Request.Path).Returns(\"/\");\n            mockViewContext.Setup(c => c.HttpContext.Request.ServerVariables).Returns((NameValueCollection)null);\n            mockViewContext.Setup(c => c.HttpContext.Response.Write(It.IsAny<string>())).Throws(new Exception(\"Should not be called\"));\n            mockViewContext.Setup(c => c.HttpContext.Items).Returns(new Hashtable());\n            mockViewContext.Setup(c => c.HttpContext.GetService(It.IsAny<Type>())).Returns(null);\n\n            writer = new StringWriter();\n            mockViewContext.Setup(c => c.Writer).Returns(writer);\n\n            mockViewContext.Setup(c => c.HttpContext.Response.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(r => MvcHelper.AppPathModifier + r);\n\n            RouteCollection rt = new RouteCollection();\n            rt.Add(new Route(\"{controller}/{action}/{id}\", null) { Defaults = new RouteValueDictionary(new { id = \"defaultid\" }) });\n            rt.Add(\"namedroute\", new Route(\"named/{controller}/{action}/{id}\", null) { Defaults = new RouteValueDictionary(new { id = \"defaultid\" }) });\n            RouteData rd = new RouteData();\n            rd.Values.Add(\"controller\", \"home\");\n            rd.Values.Add(\"action\", \"oldaction\");\n\n            mockViewContext.Setup(c => c.RouteData).Returns(rd);\n            HtmlHelper helper = new HtmlHelper(mockViewContext.Object, new Mock<IViewDataContainer>().Object, rt);\n            helper.ViewContext.FormIdGenerator = () => \"form_id\";\n            return helper;\n        }\n\n        public void Dispose()\n        {\n            // Reset ScopeStorage (written via e.g. ViewContext.ClientValidationEnabled) between tests to avoid unexpected interactions.\n            ScopeStorage.CurrentProvider = new StaticScopeStorageProvider();\n            ScopeStorage.GlobalScope.Clear();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Html/Test/InputExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel.DataAnnotations;\nusing System.Data.Linq;\nusing System.Linq.Expressions;\nusing System.Web.Mvc.Test;\nusing System.Web.Routing;\nusing System.Web.WebPages.Scope;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace System.Web.Mvc.Html.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")]\n    public class InputExtensionsTest : IDisposable\n    {\n        // CheckBox\n\n        [Fact]\n        public void CheckBoxDictionaryOverridesImplicitParameters()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetCheckBoxViewData());\n\n            // Act\n            MvcHtmlString html = helper.CheckBox(\"baz\", new { @checked = \"checked\", value = \"false\" });\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"baz\"\" name=\"\"baz\"\" type=\"\"checkbox\"\" value=\"\"false\"\" />\" +\n                         @\"<input name=\"\"baz\"\" type=\"\"hidden\"\" value=\"\"false\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckBoxExplicitParametersOverrideDictionary()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = helper.CheckBox(\"foo\", true /* isChecked */, new { @checked = \"unchecked\", value = \"false\" });\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" value=\"\"false\"\" />\" +\n                         @\"<input name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"false\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckBoxShouldNotCopyAttributesForHidden()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = helper.CheckBox(\"foo\", true /* isChecked */, new { id = \"myID\" });\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"myID\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" value=\"\"true\"\" />\" +\n                         @\"<input name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"false\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckBoxWithEmptyNameThrows()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetCheckBoxViewData());\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { helper.CheckBox(String.Empty); },\n                \"name\");\n        }\n\n        [Fact]\n        public void CheckBoxWithInvalidBooleanThrows()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetCheckBoxViewData());\n\n            // Act & Assert\n            Assert.Throws<FormatException>(\n                delegate { helper.CheckBox(\"bar\"); },\n                \"String was not recognized as a valid Boolean.\");\n        }\n\n        [Fact]\n        public void CheckBoxCheckedWithOnlyName()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = helper.CheckBox(\"foo\", true /* isChecked */);\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" value=\"\"true\"\" />\" +\n                         @\"<input name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"false\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckBoxShouldRespectModelStateAttemptedValue()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetCheckBoxViewData());\n            helper.ViewData.ModelState.SetModelValue(\"foo\", HtmlHelperTest.GetValueProviderResult(\"false\", \"false\"));\n\n            // Act\n            MvcHtmlString html = helper.CheckBox(\"foo\");\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" value=\"\"true\"\" />\" +\n                         @\"<input name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"false\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckBoxWithOnlyName()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetCheckBoxViewData());\n\n            // Act\n            MvcHtmlString html = helper.CheckBox(\"foo\");\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" value=\"\"true\"\" />\" +\n                         @\"<input name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"false\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckBoxWithOnlyName_Unobtrusive()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetCheckBoxViewData());\n            helper.ViewContext.ClientValidationEnabled = true;\n            helper.ViewContext.UnobtrusiveJavaScriptEnabled = true;\n            helper.ViewContext.FormContext = new FormContext();\n            helper.ClientValidationRuleFactory = (name, metadata) => new[] { new ModelClientValidationRule { ValidationType = \"type\", ErrorMessage = \"error\" } };\n\n            // Act\n            MvcHtmlString html = helper.CheckBox(\"foo\");\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" data-val=\"\"true\"\" data-val-type=\"\"error\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" value=\"\"true\"\" />\" +\n                         @\"<input name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"false\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckBoxWithNameAndObjectAttribute()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetCheckBoxViewData());\n\n            // Act\n            MvcHtmlString html = helper.CheckBox(\"foo\", _attributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazObjValue\"\" checked=\"\"checked\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" value=\"\"true\"\" />\" +\n                         @\"<input name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"false\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckBoxWithNameAndObjectAttributeWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetCheckBoxViewData());\n\n            // Act\n            MvcHtmlString html = helper.CheckBox(\"foo\", _attributesObjectUnderscoresDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" foo-baz=\"\"BazObjValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" value=\"\"true\"\" />\" +\n                         @\"<input name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"false\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckBoxWithObjectAttribute()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = helper.CheckBox(\"foo\", false /* isChecked */, _attributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazObjValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" value=\"\"true\"\" />\" +\n                         @\"<input name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"false\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckBoxWithObjectAttributeWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = helper.CheckBox(\"foo\", false /* isChecked */, _attributesObjectUnderscoresDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input foo-baz=\"\"BazObjValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" value=\"\"true\"\" />\" +\n                         @\"<input name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"false\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckBoxWithAttributeDictionary()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = helper.CheckBox(\"foo\", false /* isChecked */, _attributesDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" value=\"\"true\"\" />\" +\n                         @\"<input name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"false\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckBoxWithPrefix()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.CheckBox(\"foo\", false /* isChecked */, _attributesDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"MyPrefix_foo\"\" name=\"\"MyPrefix.foo\"\" type=\"\"checkbox\"\" value=\"\"true\"\" />\" +\n                         @\"<input name=\"\"MyPrefix.foo\"\" type=\"\"hidden\"\" value=\"\"false\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckBoxWithPrefixAndEmptyName()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.CheckBox(\"\", false /* isChecked */, _attributesDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"MyPrefix\"\" name=\"\"MyPrefix\"\" type=\"\"checkbox\"\" value=\"\"true\"\" />\" +\n                         @\"<input name=\"\"MyPrefix\"\" type=\"\"hidden\"\" value=\"\"false\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void CheckBox_AttributeEncodes_AddedHtmlAttributes(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            var result = helper.CheckBox(name: \"name\", htmlAttributes: new { attribute = text, }).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                @\"<input attribute=\"\"\" +\n                    encodedText +\n                    @\"\"\" id=\"\"name\"\" name=\"\"name\"\" type=\"\"checkbox\"\" value=\"\"true\"\" />\" +\n                @\"<input name=\"\"name\"\" type=\"\"hidden\"\" value=\"\"false\"\" />\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void CheckBox_AttributeEncodes_Name(string text, bool htmlEncode, string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            // htmlAttributes included only to avoid special-cased renaming done for id attribute.\n            var result = helper.CheckBox(text, htmlAttributes: new { id = \"id\", }).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                @\"<input id=\"\"id\"\" name=\"\"\" + encodedText + @\"\"\" type=\"\"checkbox\"\" value=\"\"true\"\" />\" +\n                @\"<input name=\"\"\" + encodedText + @\"\"\" type=\"\"hidden\"\" value=\"\"false\"\" />\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void CheckBox_AttributeEncodes_Prefix(string text, bool htmlEncode, string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.TemplateInfo.HtmlFieldPrefix = text;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            // htmlAttributes included only to avoid special-cased renaming done for id attribute.\n            var result = helper.CheckBox(name: String.Empty, htmlAttributes: new { id = \"id\", }).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                @\"<input id=\"\"id\"\" name=\"\"\" + encodedText + @\"\"\" type=\"\"checkbox\"\" value=\"\"true\"\" />\" +\n                @\"<input name=\"\"\" + encodedText + @\"\"\" type=\"\"hidden\"\" value=\"\"false\"\" />\",\n                result);\n        }\n\n        // No need for CheckBox_AttributeEncodes_Value() because CheckBox value is always true and hidden value\n        // is always false.\n\n        // CheckBoxFor\n\n        [Fact]\n        public void CheckBoxForWitNullExpressionThrows()\n        {\n            // Arrange\n            HtmlHelper<FooBarBazModel> helper = MvcHelper.GetHtmlHelper(GetCheckBoxViewData());\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => helper.CheckBoxFor(null),\n                \"expression\");\n        }\n\n        [Fact]\n        public void CheckBoxForWithInvalidBooleanThrows()\n        {\n            // Arrange\n            HtmlHelper<FooBarBazModel> helper = MvcHelper.GetHtmlHelper(GetCheckBoxViewData());\n\n            // Act & Assert\n            Assert.Throws<FormatException>(\n                () => helper.CheckBoxFor(m => m.bar), // \"bar\" in ViewData isn't a valid boolean\n                \"String was not recognized as a valid Boolean.\");\n        }\n\n        [Fact]\n        public void CheckBoxForDictionaryOverridesImplicitParameters()\n        {\n            // Arrange\n            HtmlHelper<FooBarBazModel> helper = MvcHelper.GetHtmlHelper(GetCheckBoxViewData());\n\n            // Act\n            MvcHtmlString html = helper.CheckBoxFor(m => m.baz, new { @checked = \"checked\", value = \"false\" });\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"baz\"\" name=\"\"baz\"\" type=\"\"checkbox\"\" value=\"\"false\"\" />\" +\n                         @\"<input name=\"\"baz\"\" type=\"\"hidden\"\" value=\"\"false\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckBoxForShouldNotCopyAttributesForHidden()\n        {\n            // Arrange\n            HtmlHelper<FooBarBazModel> helper = MvcHelper.GetHtmlHelper(GetCheckBoxViewData());\n\n            // Act\n            MvcHtmlString html = helper.CheckBoxFor(m => m.foo, new { id = \"myID\" });\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"myID\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" value=\"\"true\"\" />\" +\n                         @\"<input name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"false\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckBoxForCheckedWithOnlyName()\n        {\n            // Arrange\n            HtmlHelper<FooBarBazModel> helper = MvcHelper.GetHtmlHelper(GetCheckBoxViewData());\n\n            // Act\n            MvcHtmlString html = helper.CheckBoxFor(m => m.foo);\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" value=\"\"true\"\" />\" +\n                         @\"<input name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"false\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckBoxForCheckedWithOnlyName_Unobtrusive()\n        {\n            // Arrange\n            HtmlHelper<FooBarBazModel> helper = MvcHelper.GetHtmlHelper(GetCheckBoxViewData());\n            helper.ViewContext.ClientValidationEnabled = true;\n            helper.ViewContext.UnobtrusiveJavaScriptEnabled = true;\n            helper.ViewContext.FormContext = new FormContext();\n            helper.ClientValidationRuleFactory = (name, metadata) => new[] { new ModelClientValidationRule { ValidationType = \"type\", ErrorMessage = \"error\" } };\n\n            // Act\n            MvcHtmlString html = helper.CheckBoxFor(m => m.foo);\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" data-val=\"\"true\"\" data-val-type=\"\"error\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" value=\"\"true\"\" />\" +\n                         @\"<input name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"false\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckBoxForShouldRespectModelStateAttemptedValue()\n        {\n            // Arrange\n            HtmlHelper<FooBarBazModel> helper = MvcHelper.GetHtmlHelper(GetCheckBoxViewData());\n            helper.ViewContext.ViewData.ModelState.SetModelValue(\"foo\", HtmlHelperTest.GetValueProviderResult(\"false\", \"false\"));\n\n            // Act\n            MvcHtmlString html = helper.CheckBoxFor(m => m.foo);\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" value=\"\"true\"\" />\" +\n                         @\"<input name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"false\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckBoxForWithObjectAttribute()\n        {\n            // Arrange\n            HtmlHelper<FooBarBazModel> helper = MvcHelper.GetHtmlHelper(GetCheckBoxViewData());\n\n            // Act\n            MvcHtmlString html = helper.CheckBoxFor(m => m.foo, _attributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazObjValue\"\" checked=\"\"checked\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" value=\"\"true\"\" />\" +\n                         @\"<input name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"false\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckBoxForWithObjectAttributeWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper<FooBarBazModel> helper = MvcHelper.GetHtmlHelper(GetCheckBoxViewData());\n\n            // Act\n            MvcHtmlString html = helper.CheckBoxFor(m => m.foo, _attributesObjectUnderscoresDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" foo-baz=\"\"BazObjValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" value=\"\"true\"\" />\" +\n                         @\"<input name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"false\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckBoxForWithAttributeDictionary()\n        {\n            // Arrange\n            HtmlHelper<FooBarBazModel> helper = MvcHelper.GetHtmlHelper(GetCheckBoxViewData());\n\n            // Act\n            MvcHtmlString html = helper.CheckBoxFor(m => m.foo, _attributesDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" checked=\"\"checked\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" value=\"\"true\"\" />\" +\n                         @\"<input name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"false\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckBoxForWithPrefix()\n        {\n            // Arrange\n            HtmlHelper<FooBarBazModel> helper = MvcHelper.GetHtmlHelper(GetCheckBoxViewData());\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.CheckBoxFor(m => m.foo, _attributesDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"MyPrefix_foo\"\" name=\"\"MyPrefix.foo\"\" type=\"\"checkbox\"\" value=\"\"true\"\" />\" +\n                         @\"<input name=\"\"MyPrefix.foo\"\" type=\"\"hidden\"\" value=\"\"false\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void CheckBoxFor_AttributeEncodes_AddedHtmlAttributes(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            var dummy = false;\n\n            // Act\n            var result = helper.CheckBoxFor(m => dummy, htmlAttributes: new { attribute = text, }).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                @\"<input attribute=\"\"\" +\n                    encodedText +\n                    @\"\"\" id=\"\"dummy\"\" name=\"\"dummy\"\" type=\"\"checkbox\"\" value=\"\"true\"\" />\" +\n                @\"<input name=\"\"dummy\"\" type=\"\"hidden\"\" value=\"\"false\"\" />\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void CheckBoxFor_AttributeEncodes_Prefix(string text, bool htmlEncode, string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.TemplateInfo.HtmlFieldPrefix = text;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            var dummy = false;\n\n            // Act\n            // htmlAttributes included only to avoid special-cased renaming done for id attribute.\n            var result = helper.CheckBoxFor(m => dummy, htmlAttributes: new { id = \"id\", }).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                @\"<input id=\"\"id\"\" name=\"\"\" + encodedText + @\".dummy\"\" type=\"\"checkbox\"\" value=\"\"true\"\" />\" +\n                @\"<input name=\"\"\" + encodedText + @\".dummy\"\" type=\"\"hidden\"\" value=\"\"false\"\" />\",\n                result);\n        }\n\n        // No need for CheckBoxFor_AttributeEncodes_Value() because CheckBox value is always true and hidden value\n        // is always false.\n\n        // Culture tests\n\n        [Fact]\n        [ReplaceCulture]\n        public void InputHelpersUseCurrentCultureToConvertValueParameter()\n        {\n            // Arrange\n            DateTime dt = new DateTime(1900, 1, 1, 0, 0, 0);\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary { { \"foo\", dt } });\n\n            var tests = new[]\n            {\n                // Hidden(name)\n                new\n                {\n                    Html = @\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"01/01/1900 00:00:00\"\" />\",\n                    Action = new Func<MvcHtmlString>(() => helper.Hidden(\"foo\"))\n                },\n                // Hidden(name, value)\n                new\n                {\n                    Html = @\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"01/01/1900 00:00:00\"\" />\",\n                    Action = new Func<MvcHtmlString>(() => helper.Hidden(\"foo\", dt))\n                },\n                // Hidden(name, value, htmlAttributes)\n                new\n                {\n                    Html = @\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"01/01/1900 00:00:00\"\" />\",\n                    Action = new Func<MvcHtmlString>(() => helper.Hidden(\"foo\", dt, null))\n                },\n                // Hidden(name, value, htmlAttributes)\n                new\n                {\n                    Html = @\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"01/01/1900 00:00:00\"\" />\",\n                    Action = new Func<MvcHtmlString>(() => helper.Hidden(\"foo\", dt, new RouteValueDictionary()))\n                },\n                // RadioButton(name, value)\n                new\n                {\n                    Html = @\"<input checked=\"\"checked\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"01/01/1900 00:00:00\"\" />\",\n                    Action = new Func<MvcHtmlString>(() => helper.RadioButton(\"foo\", dt))\n                },\n                // RadioButton(name, value, isChecked)\n                new\n                {\n                    Html = @\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"01/01/1900 00:00:00\"\" />\",\n                    Action = new Func<MvcHtmlString>(() => helper.RadioButton(\"foo\", dt, false))\n                },\n                // RadioButton(name, value, htmlAttributes)\n                new\n                {\n                    Html = @\"<input checked=\"\"checked\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"01/01/1900 00:00:00\"\" />\",\n                    Action = new Func<MvcHtmlString>(() => helper.RadioButton(\"foo\", dt, null))\n                },\n                // RadioButton(name, value)\n                new\n                {\n                    Html = @\"<input checked=\"\"checked\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"01/01/1900 00:00:00\"\" />\",\n                    Action = new Func<MvcHtmlString>(() => helper.RadioButton(\"foo\", dt, new RouteValueDictionary()))\n                },\n                // RadioButton(name, value, isChecked, htmlAttributes)\n                new\n                {\n                    Html = @\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"01/01/1900 00:00:00\"\" />\",\n                    Action = new Func<MvcHtmlString>(() => helper.RadioButton(\"foo\", dt, false, null))\n                },\n                // RadioButton(name, value, isChecked, htmlAttributes)\n                new\n                {\n                    Html = @\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"01/01/1900 00:00:00\"\" />\",\n                    Action = new Func<MvcHtmlString>(() => helper.RadioButton(\"foo\", dt, false, new RouteValueDictionary()))\n                },\n                // TextBox(name)\n                new\n                {\n                    Html = @\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"01/01/1900 00:00:00\"\" />\",\n                    Action = new Func<MvcHtmlString>(() => helper.TextBox(\"foo\"))\n                },\n                // TextBox(name, value)\n                new\n                {\n                    Html = @\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"01/01/1900 00:00:00\"\" />\",\n                    Action = new Func<MvcHtmlString>(() => helper.TextBox(\"foo\", dt))\n                },\n                // TextBox(name, value, hmtlAttributes)\n                new\n                {\n                    Html = @\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"01/01/1900 00:00:00\"\" />\",\n                    Action = new Func<MvcHtmlString>(() => helper.TextBox(\"foo\", dt, (object)null))\n                },\n                // TextBox(name, value, hmtlAttributes)\n                new\n                {\n                    Html = @\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"01/01/1900 00:00:00\"\" />\",\n                    Action = new Func<MvcHtmlString>(() => helper.TextBox(\"foo\", dt, new RouteValueDictionary()))\n                }\n            };\n\n            // Act && Assert\n            foreach (var test in tests)\n            {\n                Assert.Equal(test.Html, test.Action().ToHtmlString());\n            }\n        }\n\n        // Hidden\n\n        [Fact]\n        public void HiddenWithByteArrayValueRendersBase64EncodedValue()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString result = htmlHelper.Hidden(\"ProductName\", ByteArrayModelBinderTest.Base64TestBytes);\n\n            // Assert\n            Assert.Equal(\"<input id=\\\"ProductName\\\" name=\\\"ProductName\\\" type=\\\"hidden\\\" value=\\\"Fys1\\\" />\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenWithBinaryArrayValueRendersBase64EncodedValue()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString result = htmlHelper.Hidden(\"ProductName\", new Binary(new byte[] { 23, 43, 53 }));\n\n            // Assert\n            Assert.Equal(\"<input id=\\\"ProductName\\\" name=\\\"ProductName\\\" type=\\\"hidden\\\" value=\\\"Fys1\\\" />\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenWithEmptyNameThrows()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { helper.Hidden(String.Empty); },\n                \"name\");\n        }\n\n        [Fact]\n        public void HiddenWithExplicitValue()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n\n            // Act\n            MvcHtmlString html = helper.Hidden(\"foo\", \"DefaultFoo\", null);\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"DefaultFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenWithExplicitValueAndAttributesDictionary()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n\n            // Act\n            MvcHtmlString html = helper.Hidden(\"foo\", \"DefaultFoo\", _attributesDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"DefaultFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenWithExplicitValueAndAttributesObject()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n\n            // Act\n            MvcHtmlString html = helper.Hidden(\"foo\", \"DefaultFoo\", _attributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazObjValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"DefaultFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenWithExplicitValueAndAttributesObjectWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n\n            // Act\n            MvcHtmlString html = helper.Hidden(\"foo\", \"DefaultFoo\", _attributesObjectUnderscoresDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input foo-baz=\"\"BazObjValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"DefaultFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenWithExplicitValueNull()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n\n            // Act\n            MvcHtmlString html = helper.Hidden(\"foo\", (string)null /* value */, (object)null /* htmlAttributes */);\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"ViewDataFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenWithImplicitValue()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n\n            // Act\n            MvcHtmlString html = helper.Hidden(\"foo\");\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"ViewDataFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenWithImplicitValueAndAttributesDictionary()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n\n            // Act\n            MvcHtmlString html = helper.Hidden(\"foo\", null, _attributesDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"ViewDataFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenWithImplicitValueAndAttributesDictionaryReturnsEmptyValueIfNotFound()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n\n            // Act\n            MvcHtmlString html = helper.Hidden(\"keyNotFound\", null, _attributesDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"keyNotFound\"\" name=\"\"keyNotFound\"\" type=\"\"hidden\"\" value=\"\"\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenWithImplicitValueAndAttributesObject()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n\n            // Act\n            MvcHtmlString html = helper.Hidden(\"foo\", null, _attributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazObjValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"ViewDataFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenWithNameAndValue()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n\n            // Act\n            MvcHtmlString html = helper.Hidden(\"foo\", \"fooValue\");\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"fooValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenWithPrefix()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.Hidden(\"foo\", \"fooValue\");\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"MyPrefix_foo\"\" name=\"\"MyPrefix.foo\"\" type=\"\"hidden\"\" value=\"\"fooValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenWithPrefixAndEmptyName()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.Hidden(\"\", \"fooValue\");\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"MyPrefix\"\" name=\"\"MyPrefix\"\" type=\"\"hidden\"\" value=\"\"fooValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenWithNullNameThrows()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { helper.Hidden(null /* name */); },\n                \"name\");\n        }\n\n        [Fact]\n        public void HiddenWithViewDataErrors()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetHiddenViewDataWithErrors());\n\n            // Act\n            MvcHtmlString html = helper.Hidden(\"foo\", null, _attributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazObjValue\"\" class=\"\"input-validation-error\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"AttemptedValueFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenWithViewDataErrorsAndCustomClass()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetHiddenViewDataWithErrors());\n\n            // Act\n            MvcHtmlString html = helper.Hidden(\"foo\", null, new { @class = \"foo-class\" });\n\n            // Assert\n            Assert.Equal(@\"<input class=\"\"input-validation-error foo-class\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"AttemptedValueFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void Hidden_AttributeEncodes_AddedHtmlAttributes(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            var result = helper.Hidden(name: \"name\", value: null, htmlAttributes: new { attribute = text, })\n                .ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                @\"<input attribute=\"\"\" + encodedText + @\"\"\" id=\"\"name\"\" name=\"\"name\"\" type=\"\"hidden\"\" value=\"\"\"\" />\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void Hidden_AttributeEncodes_Name(string text, bool htmlEncode, string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            // htmlAttributes included only to avoid special-cased renaming done for id attribute.\n            var result = helper.Hidden(text, value: null, htmlAttributes: new { id = \"id\", }).ToHtmlString();\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"id\"\" name=\"\"\" + encodedText + @\"\"\" type=\"\"hidden\"\" value=\"\"\"\" />\", result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void Hidden_AttributeEncodes_Prefix(string text, bool htmlEncode, string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.TemplateInfo.HtmlFieldPrefix = text;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            // htmlAttributes included only to avoid special-cased renaming done for id attribute.\n            var result = helper.Hidden(name: String.Empty, value: null, htmlAttributes: new { id = \"id\", })\n                .ToHtmlString();\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"id\"\" name=\"\"\" + encodedText + @\"\"\" type=\"\"hidden\"\" value=\"\"\"\" />\", result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void Hidden_AttributeEncodes_Value(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            var result = helper.Hidden(\"name\", value: text).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                @\"<input id=\"\"name\"\" name=\"\"name\"\" type=\"\"hidden\"\" value=\"\"\" + encodedText + @\"\"\" />\",\n                result);\n        }\n\n        // HiddenFor\n\n        [Fact]\n        public void HiddenForWithNullExpressionThrows()\n        {\n            // Arrange\n            HtmlHelper<HiddenModel> helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => helper.HiddenFor<HiddenModel, object>(null),\n                \"expression\"\n                );\n        }\n\n        [Fact]\n        public void HiddenForWithStringValue()\n        {\n            // Arrange\n            HtmlHelper<HiddenModel> helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n            helper.ViewData.Model.foo = \"DefaultFoo\";\n\n            // Act\n            MvcHtmlString html = helper.HiddenFor(m => m.foo);\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"DefaultFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenForWithByteArrayValueRendersBase64EncodedValue()\n        {\n            // Arrange\n            HtmlHelper<HiddenModel> helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n            helper.ViewData.Model.bytes = ByteArrayModelBinderTest.Base64TestBytes;\n\n            // Act\n            MvcHtmlString result = helper.HiddenFor(m => m.bytes);\n\n            // Assert\n            Assert.Equal(\"<input id=\\\"bytes\\\" name=\\\"bytes\\\" type=\\\"hidden\\\" value=\\\"Fys1\\\" />\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenForWithBinaryValueRendersBase64EncodedValue()\n        {\n            // Arrange\n            HtmlHelper<HiddenModel> helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n            helper.ViewData.Model.binary = new Binary(new byte[] { 23, 43, 53 });\n\n            // Act\n            MvcHtmlString result = helper.HiddenFor(m => m.binary);\n\n            // Assert\n            Assert.Equal(\"<input id=\\\"binary\\\" name=\\\"binary\\\" type=\\\"hidden\\\" value=\\\"Fys1\\\" />\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenForWithAttributesDictionary()\n        {\n            // Arrange\n            HtmlHelper<HiddenModel> helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n            helper.ViewData.Model.foo = \"DefaultFoo\";\n\n            // Act\n            MvcHtmlString html = helper.HiddenFor(m => m.foo, _attributesDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"DefaultFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenForWithAttributesObject()\n        {\n            // Arrange\n            HtmlHelper<HiddenModel> helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n            helper.ViewData.Model.foo = \"DefaultFoo\";\n\n            // Act\n            MvcHtmlString html = helper.HiddenFor(m => m.foo, _attributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazObjValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"DefaultFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenForWithAttributesObjectWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper<HiddenModel> helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n            helper.ViewData.Model.foo = \"DefaultFoo\";\n\n            // Act\n            MvcHtmlString html = helper.HiddenFor(m => m.foo, _attributesObjectUnderscoresDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input foo-baz=\"\"BazObjValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"DefaultFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenForWithPrefix()\n        {\n            // Arrange\n            HtmlHelper<HiddenModel> helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n            helper.ViewData.Model.foo = \"fooValue\";\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.HiddenFor(m => m.foo);\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"MyPrefix_foo\"\" name=\"\"MyPrefix.foo\"\" type=\"\"hidden\"\" value=\"\"fooValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenForWithPrefixAndEmptyName()\n        {\n            // Arrange\n            HtmlHelper<HiddenModel> helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.HiddenFor(m => m);\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"MyPrefix\"\" name=\"\"MyPrefix\"\" type=\"\"hidden\"\" value=\"\"{ foo = (null) }\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenForWithViewDataErrors()\n        {\n            // Arrange\n            HtmlHelper<HiddenModel> helper = MvcHelper.GetHtmlHelper(GetHiddenViewDataWithErrors());\n\n            // Act\n            MvcHtmlString html = helper.HiddenFor(m => m.foo, _attributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazObjValue\"\" class=\"\"input-validation-error\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"AttemptedValueFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenForWithViewDataErrorsAndCustomClass()\n        {\n            // Arrange\n            HtmlHelper<HiddenModel> helper = MvcHelper.GetHtmlHelper(GetHiddenViewDataWithErrors());\n\n            // Act\n            MvcHtmlString html = helper.HiddenFor(m => m.foo, new { @class = \"foo-class\" });\n\n            // Assert\n            Assert.Equal(@\"<input class=\"\"input-validation-error foo-class\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"AttemptedValueFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void HiddenFor_AttributeEncodes_AddedHtmlAttributes(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.TemplateInfo.HtmlFieldPrefix = \"name\";\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            var result = helper.HiddenFor(m => m, htmlAttributes: new { attribute = text, }).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                @\"<input attribute=\"\"\" + encodedText + @\"\"\" id=\"\"name\"\" name=\"\"name\"\" type=\"\"hidden\"\" value=\"\"\"\" />\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void HiddenFor_AttributeEncodes_Prefix(string text, bool htmlEncode, string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.TemplateInfo.HtmlFieldPrefix = text;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            // htmlAttributes included only to avoid special-cased renaming done for id attribute.\n            var result = helper.HiddenFor(m => m, htmlAttributes: new { id = \"id\", }).ToHtmlString();\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"id\"\" name=\"\"\" + encodedText + @\"\"\" type=\"\"hidden\"\" value=\"\"\"\" />\", result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void HiddenFor_AttributeEncodes_Value(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            var result = helper.HiddenFor(m => text).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                @\"<input id=\"\"text\"\" name=\"\"text\"\" type=\"\"hidden\"\" value=\"\"\" + encodedText + @\"\"\" />\",\n                result);\n        }\n\n        // Password\n\n        [Fact]\n        public void PasswordWithEmptyNameThrows()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetPasswordViewData());\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { helper.Password(String.Empty); },\n                \"name\");\n        }\n\n        [Fact]\n        public void PasswordDictionaryOverridesImplicitParameters()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetPasswordViewData());\n\n            // Act\n            MvcHtmlString html = helper.Password(\"foo\", \"Some Value\", new { type = \"fooType\" });\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"fooType\"\" value=\"\"Some Value\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordExplicitParametersOverrideDictionary()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetPasswordViewData());\n\n            // Act\n            MvcHtmlString html = helper.Password(\"foo\", \"Some Value\", new { value = \"Another Value\", name = \"bar\" });\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" value=\"\"Some Value\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordWithExplicitValue()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetPasswordViewData());\n\n            // Act\n            MvcHtmlString html = helper.Password(\"foo\", \"DefaultFoo\", (object)null);\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" value=\"\"DefaultFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordWithExplicitValue_Unobtrusive()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetPasswordViewData());\n            helper.ViewContext.ClientValidationEnabled = true;\n            helper.ViewContext.UnobtrusiveJavaScriptEnabled = true;\n            helper.ViewContext.FormContext = new FormContext();\n            helper.ClientValidationRuleFactory = (name, metadata) => new[] { new ModelClientValidationRule { ValidationType = \"type\", ErrorMessage = \"error\" } };\n\n            // Act\n            MvcHtmlString html = helper.Password(\"foo\", \"DefaultFoo\", (object)null);\n\n            // Assert\n            Assert.Equal(@\"<input data-val=\"\"true\"\" data-val-type=\"\"error\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" value=\"\"DefaultFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordWithExplicitValueAndAttributesDictionary()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetPasswordViewData());\n\n            // Act\n            MvcHtmlString html = helper.Password(\"foo\", \"DefaultFoo\", _attributesDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" value=\"\"DefaultFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordWithExplicitValueAndAttributesObject()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetPasswordViewData());\n\n            // Act\n            MvcHtmlString html = helper.Password(\"foo\", \"DefaultFoo\", _attributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazObjValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" value=\"\"DefaultFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordWithExplicitValueNull()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetPasswordViewData());\n\n            // Act\n            MvcHtmlString html = helper.Password(\"foo\", (string)null /* value */, (object)null);\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordWithImplicitValue()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetPasswordViewData());\n\n            // Act\n            MvcHtmlString html = helper.Password(\"foo\");\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordWithImplicitValueAndAttributesDictionary()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetPasswordViewData());\n\n            // Act\n            MvcHtmlString html = helper.Password(\"foo\", null, _attributesDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordWithImplicitValueAndAttributesDictionaryReturnsEmptyValueIfNotFound()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetPasswordViewData());\n\n            // Act\n            MvcHtmlString html = helper.Password(\"keyNotFound\", null, _attributesDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"keyNotFound\"\" name=\"\"keyNotFound\"\" type=\"\"password\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordWithImplicitValueAndAttributesObject()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetPasswordViewData());\n\n            // Act\n            MvcHtmlString html = helper.Password(\"foo\", null, _attributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazObjValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordWithImplicitValueAndAttributesObjectWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetPasswordViewData());\n\n            // Act\n            MvcHtmlString html = helper.Password(\"foo\", null, _attributesObjectUnderscoresDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input foo-baz=\"\"BazObjValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordWithNameAndValue()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n\n            // Act\n            MvcHtmlString html = helper.Password(\"foo\", \"fooValue\");\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" value=\"\"fooValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordWithPrefix()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.Password(\"foo\", \"fooValue\");\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"MyPrefix_foo\"\" name=\"\"MyPrefix.foo\"\" type=\"\"password\"\" value=\"\"fooValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordWithPrefixAndEmptyName()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.Password(\"\", \"fooValue\");\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"MyPrefix\"\" name=\"\"MyPrefix\"\" type=\"\"password\"\" value=\"\"fooValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordWithNullNameThrows()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetPasswordViewData());\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { helper.Password(null /* name */); },\n                \"name\");\n        }\n\n        [Fact]\n        public void PasswordWithViewDataErrors()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetPasswordViewDataWithErrors());\n\n            // Act\n            MvcHtmlString html = helper.Password(\"foo\", null, _attributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazObjValue\"\" class=\"\"input-validation-error\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordWithViewDataErrorsAndCustomClass()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetPasswordViewDataWithErrors());\n\n            // Act\n            MvcHtmlString html = helper.Password(\"foo\", null, new { @class = \"foo-class\" });\n\n            // Assert\n            Assert.Equal(@\"<input class=\"\"input-validation-error foo-class\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" />\", html.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void Password_AttributeEncodes_AddedHtmlAttributes(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            var result = helper.Password(name: \"name\", value: null, htmlAttributes: new { attribute = text, })\n                .ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                @\"<input attribute=\"\"\" + encodedText + @\"\"\" id=\"\"name\"\" name=\"\"name\"\" type=\"\"password\"\" />\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void Password_AttributeEncodes_Name(string text, bool htmlEncode, string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            // htmlAttributes included only to avoid special-cased renaming done for id attribute.\n            var result = helper.Password(text, value: null, htmlAttributes: new { id = \"id\", }).ToHtmlString();\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"id\"\" name=\"\"\" + encodedText + @\"\"\" type=\"\"password\"\" />\", result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void Password_AttributeEncodes_Prefix(string text, bool htmlEncode, string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.TemplateInfo.HtmlFieldPrefix = text;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            // htmlAttributes included only to avoid special-cased renaming done for id attribute.\n            var result = helper.Password(name: String.Empty, value: null, htmlAttributes: new { id = \"id\", })\n                .ToHtmlString();\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"id\"\" name=\"\"\" + encodedText + @\"\"\" type=\"\"password\"\" />\", result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void Password_AttributeEncodes_Value(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            var result = helper.Password(\"name\", value: text).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                @\"<input id=\"\"name\"\" name=\"\"name\"\" type=\"\"password\"\" value=\"\"\" + encodedText + @\"\"\" />\",\n                result);\n        }\n\n        // PasswordFor\n\n        [Fact]\n        public void PasswordForWithNullExpressionThrows()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(GetPasswordViewData());\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => helper.PasswordFor<FooModel, object>(null),\n                \"expression\");\n        }\n\n        [Fact]\n        public void PasswordForDictionaryOverridesImplicitParameters()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(GetPasswordViewData());\n\n            // Act\n            MvcHtmlString html = helper.PasswordFor(m => m.foo, new { type = \"fooType\" });\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"fooType\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordForExpressionNameOverridesDictionary()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(GetPasswordViewData());\n\n            // Act\n            MvcHtmlString html = helper.PasswordFor(m => m.foo, new { name = \"bar\" });\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordForWithImplicitValue()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(GetPasswordViewData());\n\n            // Act\n            MvcHtmlString html = helper.PasswordFor(m => m.foo);\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordForWithImplicitValue_Unobtrusive()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(GetPasswordViewData());\n            helper.ViewContext.ClientValidationEnabled = true;\n            helper.ViewContext.UnobtrusiveJavaScriptEnabled = true;\n            helper.ViewContext.FormContext = new FormContext();\n            helper.ClientValidationRuleFactory = (name, metadata) => new[] { new ModelClientValidationRule { ValidationType = \"type\", ErrorMessage = \"error\" } };\n\n            // Act\n            MvcHtmlString html = helper.PasswordFor(m => m.foo);\n\n            // Assert\n            Assert.Equal(@\"<input data-val=\"\"true\"\" data-val-type=\"\"error\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordForWithDeepValueWithNullModel_Unobtrusive()\n        { // Dev10 Bug #936192\n            // Arrange\n            HtmlHelper<DeepContainerModel> helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary<DeepContainerModel>());\n            helper.ViewContext.ClientValidationEnabled = true;\n            helper.ViewContext.UnobtrusiveJavaScriptEnabled = true;\n            helper.ViewContext.FormContext = new FormContext();\n\n            using (new CultureReplacer(\"en-US\", \"en-US\"))\n            {\n                // Act\n                MvcHtmlString html = helper.PasswordFor(m => m.contained.foo);\n\n                // Assert\n                Assert.Equal(@\"<input data-val=\"\"true\"\" data-val-required=\"\"The foo field is required.\"\" id=\"\"contained_foo\"\" name=\"\"contained.foo\"\" type=\"\"password\"\" />\", html.ToHtmlString());\n            }\n        }\n\n        [Fact]\n        public void PasswordForWithAttributesDictionary()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(GetPasswordViewData());\n\n            // Act\n            MvcHtmlString html = helper.PasswordFor(m => m.foo, _attributesDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordForWithAttributesObject()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(GetPasswordViewData());\n\n            // Act\n            MvcHtmlString html = helper.PasswordFor(m => m.foo, _attributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazObjValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordForWithAttributesObjectWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(GetPasswordViewData());\n\n            // Act\n            MvcHtmlString html = helper.PasswordFor(m => m.foo, _attributesObjectUnderscoresDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input foo-baz=\"\"BazObjValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordForWithPrefix()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(GetPasswordViewData());\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.PasswordFor(m => m.foo);\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"MyPrefix_foo\"\" name=\"\"MyPrefix.foo\"\" type=\"\"password\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordForWithViewDataErrors()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(GetPasswordViewDataWithErrors());\n\n            // Act\n            MvcHtmlString html = helper.PasswordFor(m => m.foo, _attributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazObjValue\"\" class=\"\"input-validation-error\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordForWithViewDataErrorsAndCustomClass()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(GetPasswordViewDataWithErrors());\n\n            // Act\n            MvcHtmlString html = helper.PasswordFor(m => m.foo, new { @class = \"foo-class\" });\n\n            // Assert\n            Assert.Equal(@\"<input class=\"\"input-validation-error foo-class\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" />\", html.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void PasswordFor_AttributeEncodes_AddedHtmlAttributes(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.TemplateInfo.HtmlFieldPrefix = \"name\";\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            var result = helper.PasswordFor(m => m, htmlAttributes: new { attribute = text, }).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                @\"<input attribute=\"\"\" + encodedText + @\"\"\" id=\"\"name\"\" name=\"\"name\"\" type=\"\"password\"\" />\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void PasswordFor_AttributeEncodes_Prefix(string text, bool htmlEncode, string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.TemplateInfo.HtmlFieldPrefix = text;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            // htmlAttributes included only to avoid special-cased renaming done for id attribute.\n            var result = helper.PasswordFor(m => m, htmlAttributes: new { id = \"id\", }).ToHtmlString();\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"id\"\" name=\"\"\" + encodedText + @\"\"\" type=\"\"password\"\" />\", result);\n        }\n\n        // No need for PasswordFor_AttributeEncodes_Value() because PasswordFor() always uses a null value.\n\n        // RadioButton\n\n        [Fact]\n        public void RadioButtonDictionaryOverridesImplicitParameters()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n\n            // Act\n            MvcHtmlString html = helper.RadioButton(\"bar\", \"ViewDataBar\", new { @checked = \"chucked\", value = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"chucked\"\" id=\"\"bar\"\" name=\"\"bar\"\" type=\"\"radio\"\" value=\"\"ViewDataBar\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonExplicitParametersOverrideDictionary()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n\n            // Act\n            MvcHtmlString html = helper.RadioButton(\"bar\", \"ViewDataBar\", false, new { @checked = \"checked\", value = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"bar\"\" name=\"\"bar\"\" type=\"\"radio\"\" value=\"\"ViewDataBar\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonShouldRespectModelStateAttemptedValue()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n            helper.ViewData.ModelState.SetModelValue(\"foo\", HtmlHelperTest.GetValueProviderResult(\"ModelStateFoo\", \"ModelStateFoo\"));\n\n            // Act\n            MvcHtmlString html = helper.RadioButton(\"foo\", \"ModelStateFoo\", false, new { @checked = \"checked\", value = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"ModelStateFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonValueParameterAlwaysRendered()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n\n            // Act\n            MvcHtmlString html = helper.RadioButton(\"foo\", \"ViewDataFoo\");\n            MvcHtmlString html2 = helper.RadioButton(\"foo\", \"fooValue2\");\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"ViewDataFoo\"\" />\", html.ToHtmlString());\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"fooValue2\"\" />\", html2.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonWithEmptyNameThrows()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { helper.RadioButton(String.Empty, \"value\"); },\n                \"name\");\n        }\n\n        [Fact]\n        public void RadioButtonWithNullValueThrows()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { helper.RadioButton(\"foo\", null); },\n                \"value\");\n        }\n\n        [Fact]\n        public void RadioButtonWithNameAndValue()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n\n            // Act\n            MvcHtmlString html = helper.RadioButton(\"foo\", \"ViewDataFoo\");\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"ViewDataFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonWithNameAndValue_Unobtrusive()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n            helper.ViewContext.ClientValidationEnabled = true;\n            helper.ViewContext.UnobtrusiveJavaScriptEnabled = true;\n            helper.ViewContext.FormContext = new FormContext();\n            helper.ClientValidationRuleFactory = (name, metadata) => new[] { new ModelClientValidationRule { ValidationType = \"type\", ErrorMessage = \"error\" } };\n\n            // Act\n            MvcHtmlString html = helper.RadioButton(\"foo\", \"ViewDataFoo\");\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" data-val=\"\"true\"\" data-val-type=\"\"error\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"ViewDataFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonWithPrefix()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.RadioButton(\"foo\", \"ViewDataFoo\");\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"MyPrefix_foo\"\" name=\"\"MyPrefix.foo\"\" type=\"\"radio\"\" value=\"\"ViewDataFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonWithPrefixAndEmptyName()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.RadioButton(\"\", \"ViewDataFoo\");\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"MyPrefix\"\" name=\"\"MyPrefix\"\" type=\"\"radio\"\" value=\"\"ViewDataFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonWithNameAndValueNotMatched()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n\n            // Act\n            MvcHtmlString html = helper.RadioButton(\"foo\", \"fooValue\");\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"fooValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonWithNameValueUnchecked()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n\n            // Act\n            MvcHtmlString html = helper.RadioButton(\"bar\", \"barValue\", false /* isChecked */);\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"bar\"\" name=\"\"bar\"\" type=\"\"radio\"\" value=\"\"barValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonWithNameValueChecked()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n\n            // Act\n            MvcHtmlString html = helper.RadioButton(\"bar\", \"barValue\", true /* isChecked */);\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"bar\"\" name=\"\"bar\"\" type=\"\"radio\"\" value=\"\"barValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonWithObjectAttribute()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n\n            // Act\n            MvcHtmlString html = helper.RadioButton(\"foo\", \"fooValue\", _attributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazObjValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"fooValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonWithObjectAttributeWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n\n            // Act\n            MvcHtmlString html = helper.RadioButton(\"foo\", \"fooValue\", _attributesObjectUnderscoresDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input foo-baz=\"\"BazObjValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"fooValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonWithAttributeDictionary()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n\n            // Act\n            MvcHtmlString html = helper.RadioButton(\"bar\", \"barValue\", _attributesDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"bar\"\" name=\"\"bar\"\" type=\"\"radio\"\" value=\"\"barValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonWithValueUnchecked()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n\n            // Act\n            MvcHtmlString html = helper.RadioButton(\"foo\", \"bar\", false /* isChecked */);\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"bar\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonWithValueAndObjectAttributeUnchecked()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n\n            // Act\n            MvcHtmlString html = helper.RadioButton(\"foo\", \"bar\", false /* isChecked */, _attributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazObjValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"bar\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonWithValueAndObjectAttributeWithUnderscoresUnchecked()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n\n            // Act\n            MvcHtmlString html = helper.RadioButton(\"foo\", \"bar\", false /* isChecked */, _attributesObjectUnderscoresDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input foo-baz=\"\"BazObjValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"bar\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonWithValueAndAttributeDictionaryUnchecked()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n\n            // Act\n            MvcHtmlString html = helper.RadioButton(\"foo\", \"bar\", false /* isChecked */, _attributesDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"bar\"\" />\", html.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void RadioButton_AttributeEncodes_AddedHtmlAttributes(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            var result = helper.RadioButton(name: \"name\", value: \"value\", htmlAttributes: new { attribute = text, })\n                .ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                @\"<input attribute=\"\"\" + encodedText + @\"\"\" id=\"\"name\"\" name=\"\"name\"\" type=\"\"radio\"\" value=\"\"value\"\" />\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void RadioButton_AttributeEncodes_Name(string text, bool htmlEncode, string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            // htmlAttributes included only to avoid special-cased renaming done for id attribute.\n            var result = helper.RadioButton(text, value: \"value\", htmlAttributes: new { id = \"id\", })\n                .ToHtmlString();\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"id\"\" name=\"\"\" + encodedText + @\"\"\" type=\"\"radio\"\" value=\"\"value\"\" />\", result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void RadioButton_AttributeEncodes_Prefix(string text, bool htmlEncode, string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.TemplateInfo.HtmlFieldPrefix = text;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            // htmlAttributes included only to avoid special-cased renaming done for id attribute.\n            var result = helper.RadioButton(name: String.Empty, value: String.Empty, htmlAttributes: new { id = \"id\", })\n                .ToHtmlString();\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"id\"\" name=\"\"\" + encodedText + @\"\"\" type=\"\"radio\"\" value=\"\"\"\" />\", result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void RadioButton_AttributeEncodes_Value(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            var result = helper.RadioButton(\"name\", value: text).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                @\"<input id=\"\"name\"\" name=\"\"name\"\" type=\"\"radio\"\" value=\"\"\" + encodedText + @\"\"\" />\",\n                result);\n        }\n\n        // RadioButtonFor\n\n        [Fact]\n        public void RadioButtonForWithNullExpressionThrows()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => helper.RadioButtonFor<FooBarModel, object>(null, \"value\"),\n                \"expression\");\n        }\n\n        [Fact]\n        public void RadioButtonForWithNullValueThrows()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => helper.RadioButtonFor(m => m.foo, null),\n                \"value\");\n        }\n\n        [Fact]\n        public void RadioButtonForDictionaryOverridesImplicitParameters()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n\n            // Act\n            MvcHtmlString html = helper.RadioButtonFor(m => m.bar, \"ViewDataBar\", new { @checked = \"chucked\", value = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"chucked\"\" id=\"\"bar\"\" name=\"\"bar\"\" type=\"\"radio\"\" value=\"\"ViewDataBar\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonForShouldRespectModelStateAttemptedValue()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n            helper.ViewData.ModelState.SetModelValue(\"foo\", HtmlHelperTest.GetValueProviderResult(\"ModelStateFoo\", \"ModelStateFoo\"));\n\n            // Act\n            MvcHtmlString html = helper.RadioButtonFor(m => m.foo, \"ModelStateFoo\", new { @checked = \"checked\", value = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"ModelStateFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonForValueParameterAlwaysRendered()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n\n            // Act & Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"ViewDataFoo\"\" />\",\n                         helper.RadioButtonFor(m => m.foo, \"ViewDataFoo\").ToHtmlString());\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"fooValue2\"\" />\",\n                         helper.RadioButtonFor(m => m.foo, \"fooValue2\").ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonForWithNameAndValue()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n\n            // Act\n            MvcHtmlString html = helper.RadioButtonFor(m => m.foo, \"ViewDataFoo\");\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"ViewDataFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonForWithNestedNameAndValue()\n        {\n            // Arrange\n            HtmlHelper<string> helper = MvcHelper.GetHtmlHelper(GetRadioButtonNestedAndUnsetViewData());\n\n            // Act\n            MvcHtmlString html = helper.RadioButtonFor(m => m, \"ViewItemFoo\");\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"ViewItemFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonForWithNameAndValue_Unobtrusive()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n            helper.ViewContext.ClientValidationEnabled = true;\n            helper.ViewContext.UnobtrusiveJavaScriptEnabled = true;\n            helper.ViewContext.FormContext = new FormContext();\n            helper.ClientValidationRuleFactory = (name, metadata) => new[] { new ModelClientValidationRule { ValidationType = \"type\", ErrorMessage = \"error\" } };\n\n            // Act\n            MvcHtmlString html = helper.RadioButtonFor(m => m.foo, \"ViewDataFoo\");\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" data-val=\"\"true\"\" data-val-type=\"\"error\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"ViewDataFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonForWithPrefix()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.RadioButtonFor(m => m.foo, \"ViewDataFoo\");\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"MyPrefix_foo\"\" name=\"\"MyPrefix.foo\"\" type=\"\"radio\"\" value=\"\"ViewDataFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonForWithNameAndValueNotMatched()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n\n            // Act\n            MvcHtmlString html = helper.RadioButtonFor(m => m.foo, \"fooValue\");\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"fooValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonForWithObjectAttribute()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n\n            // Act\n            MvcHtmlString html = helper.RadioButtonFor(m => m.foo, \"fooValue\", _attributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazObjValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"fooValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonForWithObjectAttributeWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n\n            // Act\n            MvcHtmlString html = helper.RadioButtonFor(m => m.foo, \"fooValue\", _attributesObjectUnderscoresDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input foo-baz=\"\"BazObjValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"fooValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonForWithAttributeDictionary()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetRadioButtonViewData());\n\n            // Act\n            MvcHtmlString html = helper.RadioButtonFor(m => m.bar, \"barValue\", _attributesDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"bar\"\" name=\"\"bar\"\" type=\"\"radio\"\" value=\"\"barValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void RadioButtonFor_AttributeEncodes_AddedHtmlAttributes(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.TemplateInfo.HtmlFieldPrefix = \"name\";\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            var result = helper.RadioButtonFor(m => m, value: String.Empty, htmlAttributes: new { attribute = text, })\n                .ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                @\"<input attribute=\"\"\" + encodedText + @\"\"\" id=\"\"name\"\" name=\"\"name\"\" type=\"\"radio\"\" value=\"\"\"\" />\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void RadioButtonFor_AttributeEncodes_Prefix(string text, bool htmlEncode, string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.TemplateInfo.HtmlFieldPrefix = text;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            // htmlAttributes included only to avoid special-cased renaming done for id attribute.\n            var result = helper.RadioButtonFor(m => m, value: String.Empty, htmlAttributes: new { id = \"id\", })\n                .ToHtmlString();\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"id\"\" name=\"\"\" + encodedText + @\"\"\" type=\"\"radio\"\" value=\"\"\"\" />\", result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void RadioButtonFor_AttributeEncodes_Value(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.TemplateInfo.HtmlFieldPrefix = \"name\";\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            var result = helper.RadioButtonFor(m => m, value: text).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                @\"<input id=\"\"name\"\" name=\"\"name\"\" type=\"\"radio\"\" value=\"\"\" + encodedText + @\"\"\" />\",\n                result);\n        }\n\n        // TextBox\n\n        [Fact]\n        public void TextBoxDictionaryOverridesImplicitValues()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextBoxViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextBox(\"foo\", \"DefaultFoo\", new { type = \"fooType\" });\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"fooType\"\" value=\"\"DefaultFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxExplicitParametersOverrideDictionaryValues()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextBoxViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextBox(\"foo\", \"DefaultFoo\", new { value = \"Some other value\" });\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"DefaultFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxWithDotReplacementForId()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextBoxViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextBox(\"foo.bar.baz\", null);\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo_bar_baz\"\" name=\"\"foo.bar.baz\"\" type=\"\"text\"\" value=\"\"\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxWithEmptyNameThrows()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextBoxViewData());\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { helper.TextBox(String.Empty); },\n                \"name\");\n        }\n\n        [Fact]\n        public void TextBoxWithExplicitValue()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextBoxViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextBox(\"foo\", \"DefaultFoo\", (object)null);\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"DefaultFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxWithExplicitValue_Unobtrusive()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextBoxViewData());\n            helper.ViewContext.ClientValidationEnabled = true;\n            helper.ViewContext.UnobtrusiveJavaScriptEnabled = true;\n            helper.ViewContext.FormContext = new FormContext();\n            helper.ClientValidationRuleFactory = (name, metadata) => new[] { new ModelClientValidationRule { ValidationType = \"type\", ErrorMessage = \"error\" } };\n\n            // Act\n            MvcHtmlString html = helper.TextBox(\"foo\", \"DefaultFoo\", (object)null);\n\n            // Assert\n            Assert.Equal(@\"<input data-val=\"\"true\"\" data-val-type=\"\"error\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"DefaultFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxWithExplicitValueAndAttributesDictionary()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextBoxViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextBox(\"foo\", \"DefaultFoo\", _attributesDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"DefaultFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxWithExplicitValueAndAttributesObject()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextBoxViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextBox(\"foo\", \"DefaultFoo\", _attributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazObjValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"DefaultFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxWithExplicitValueNull()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextBoxViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextBox(\"foo\", (string)null /* value */, (object)null);\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"ViewDataFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxWithImplicitValue()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextBoxViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextBox(\"foo\");\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"ViewDataFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxWithImplicitValueAndAttributesDictionary()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextBoxViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextBox(\"foo\", null, _attributesDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"ViewDataFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxWithImplicitValueAndAttributesDictionaryReturnsEmptyValueIfNotFound()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextBoxViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextBox(\"keyNotFound\", null, _attributesDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"keyNotFound\"\" name=\"\"keyNotFound\"\" type=\"\"text\"\" value=\"\"\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxWithImplicitValueAndAttributesObject()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextBoxViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextBox(\"foo\", null, _attributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazObjValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"ViewDataFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxWithImplicitValueAndAttributesObjectWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextBoxViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextBox(\"foo\", null, _attributesObjectUnderscoresDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input foo-baz=\"\"BazObjValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"ViewDataFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxWithNullNameThrows()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextBoxViewData());\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { helper.TextBox(null /* name */); },\n                \"name\");\n        }\n\n        [Fact]\n        public void TextBoxWithNameAndValue()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextBox(\"foo\", \"fooValue\");\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"fooValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxWithPrefix()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.TextBox(\"foo\", \"fooValue\");\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"MyPrefix_foo\"\" name=\"\"MyPrefix.foo\"\" type=\"\"text\"\" value=\"\"fooValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxWithPrefixAndEmptyName()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetHiddenViewData());\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.TextBox(\"\", \"fooValue\");\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"MyPrefix\"\" name=\"\"MyPrefix\"\" type=\"\"text\"\" value=\"\"fooValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxWithViewDataErrors()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextBoxViewDataWithErrors());\n\n            // Act\n            MvcHtmlString html = helper.TextBox(\"foo\", null, _attributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazObjValue\"\" class=\"\"input-validation-error\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"AttemptedValueFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxWithViewDataErrorsAndCustomClass()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextBoxViewDataWithErrors());\n\n            // Act\n            MvcHtmlString html = helper.TextBox(\"foo\", null, new { @class = \"foo-class\" });\n\n            // Assert\n            Assert.Equal(@\"<input class=\"\"input-validation-error foo-class\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"AttemptedValueFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void TextBox_AttributeEncodes_AddedHtmlAttributes(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            var result = helper.TextBox(name: \"name\", value: null, htmlAttributes: new { attribute = text, })\n                .ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                @\"<input attribute=\"\"\" + encodedText + @\"\"\" id=\"\"name\"\" name=\"\"name\"\" type=\"\"text\"\" value=\"\"\"\" />\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void TextBox_AttributeEncodes_Format(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            var result = helper.TextBox(\"name\", value: String.Empty, format: text).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                @\"<input id=\"\"name\"\" name=\"\"name\"\" type=\"\"text\"\" value=\"\"\" + encodedText + @\"\"\" />\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void TextBox_AttributeEncodes_Name(string text, bool htmlEncode, string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            // htmlAttributes included only to avoid special-cased renaming done for id attribute.\n            var result = helper.TextBox(text, value: null, htmlAttributes: new { id = \"id\", }).ToHtmlString();\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"id\"\" name=\"\"\" + encodedText + @\"\"\" type=\"\"text\"\" value=\"\"\"\" />\", result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void TextBox_AttributeEncodes_Prefix(string text, bool htmlEncode, string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.TemplateInfo.HtmlFieldPrefix = text;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            // htmlAttributes included only to avoid special-cased renaming done for id attribute.\n            var result = helper.TextBox(name: String.Empty, value: null, htmlAttributes: new { id = \"id\", })\n                .ToHtmlString();\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"id\"\" name=\"\"\" + encodedText + @\"\"\" type=\"\"text\"\" value=\"\"\"\" />\", result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void TextBox_AttributeEncodes_Value(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            var result = helper.TextBox(\"name\", value: text).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                @\"<input id=\"\"name\"\" name=\"\"name\"\" type=\"\"text\"\" value=\"\"\" + encodedText + @\"\"\" />\",\n                result);\n        }\n\n        // TextBoxFor\n\n        [Fact]\n        public void TextBoxForWithNullExpressionThrows()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetTextBoxViewData());\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => helper.TextBoxFor<FooBarModel, object>(null /* expression */),\n                \"expression\"\n                );\n        }\n\n        [Fact]\n        public void TextBoxForWithSimpleExpression()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetTextBoxViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextBoxFor(m => m.foo);\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"ViewItemFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxForWithSimpleExpression_Unobtrusive()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetTextBoxViewData());\n            helper.ViewContext.ClientValidationEnabled = true;\n            helper.ViewContext.UnobtrusiveJavaScriptEnabled = true;\n            helper.ViewContext.FormContext = new FormContext();\n            helper.ClientValidationRuleFactory = (name, metadata) => new[] { new ModelClientValidationRule { ValidationType = \"type\", ErrorMessage = \"error\" } };\n\n            // Act\n            MvcHtmlString html = helper.TextBoxFor(m => m.foo);\n\n            // Assert\n            Assert.Equal(@\"<input data-val=\"\"true\"\" data-val-type=\"\"error\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"ViewItemFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxForWithAttributesDictionary()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetTextBoxViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextBoxFor(m => m.foo, _attributesDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"ViewItemFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxForWithAttributesObject()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetTextBoxViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextBoxFor(m => m.foo, _attributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazObjValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"ViewItemFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxForWithAttributesObjectWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetTextBoxViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextBoxFor(m => m.foo, _attributesObjectUnderscoresDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input foo-baz=\"\"BazObjValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"ViewItemFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxForWithPrefix()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetTextBoxViewData());\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.TextBoxFor(m => m.foo);\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"MyPrefix_foo\"\" name=\"\"MyPrefix.foo\"\" type=\"\"text\"\" value=\"\"ViewItemFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxForWithPrefixAndEmptyName()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetTextBoxViewData());\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.TextBoxFor(m => m);\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"MyPrefix\"\" name=\"\"MyPrefix\"\" type=\"\"text\"\" value=\"\"{ foo = ViewItemFoo, bar = ViewItemBar }\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxForWithErrors()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetTextBoxViewDataWithErrors());\n\n            // Act\n            MvcHtmlString html = helper.TextBoxFor(m => m.foo, _attributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazObjValue\"\" class=\"\"input-validation-error\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"AttemptedValueFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxForWithErrorsAndCustomClass()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetTextBoxViewDataWithErrors());\n\n            // Act\n            MvcHtmlString html = helper.TextBoxFor(m => m.foo, new { @class = \"foo-class\" });\n\n            // Assert\n            Assert.Equal(@\"<input class=\"\"input-validation-error foo-class\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"AttemptedValueFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void TextBoxHelpersFormatValue()\n        {\n            // Arrange\n            DateTime dt = new DateTime(1900, 1, 1, 0, 0, 0);\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary { { \"viewDataDate\", dt } });\n\n            ViewDataDictionary<DateModel> viewData = new ViewDataDictionary<DateModel>() { Model = new DateModel { date = dt } };\n            HtmlHelper<DateModel> dateModelhelper = MvcHelper.GetHtmlHelper(viewData);\n\n            var tests = new[]\n            {\n                // TextBox(name, value, format)\n                new\n                {\n                    Html = @\"<input id=\"\"viewDataDate\"\" name=\"\"viewDataDate\"\" type=\"\"text\"\" value=\"\"-01/01/1900 00:00:00-\"\" />\",\n                    Action = new Func<MvcHtmlString>(() => helper.TextBox(\"viewDataDate\", null, \"-{0}-\"))\n                },\n                // TextBox(name, value, format)\n                new\n                {\n                    Html = @\"<input id=\"\"date\"\" name=\"\"date\"\" type=\"\"text\"\" value=\"\"-01/01/1900 00:00:00-\"\" />\",\n                    Action = new Func<MvcHtmlString>(() => helper.TextBox(\"date\", dt, \"-{0}-\"))\n                },\n                // TextBox(name, value, format, hmtlAttributes)\n                new\n                {\n                    Html = @\"<input id=\"\"date\"\" name=\"\"date\"\" type=\"\"text\"\" value=\"\"-01/01/1900 00:00:00-\"\" />\",\n                    Action = new Func<MvcHtmlString>(() => helper.TextBox(\"date\", dt, \"-{0}-\", (object)null))\n                },\n                // TextBox(name, value, format, hmtlAttributes)\n                new\n                {\n                    Html = @\"<input id=\"\"date\"\" name=\"\"date\"\" type=\"\"text\"\" value=\"\"-01/01/1900 00:00:00-\"\" />\",\n                    Action = new Func<MvcHtmlString>(() => helper.TextBox(\"date\", dt, \"-{0}-\", new RouteValueDictionary()))\n                },\n                // TextBoxFor(expression, format)\n                new\n                {\n                    Html = @\"<input id=\"\"date\"\" name=\"\"date\"\" type=\"\"text\"\" value=\"\"-01/01/1900 00:00:00-\"\" />\",\n                    Action = new Func<MvcHtmlString>(() => dateModelhelper.TextBoxFor(m => m.date, \"-{0}-\"))\n                },\n                // TextBoxFor(expression, format, hmtlAttributes)\n                new\n                {\n                    Html = @\"<input id=\"\"date\"\" name=\"\"date\"\" type=\"\"text\"\" value=\"\"-01/01/1900 00:00:00-\"\" />\",\n                    Action = new Func<MvcHtmlString>(() => dateModelhelper.TextBoxFor(m => m.date, \"-{0}-\", (object)null))\n                },\n                // TextBoxFor(expression, format, hmtlAttributes)\n                new\n                {\n                    Html = @\"<input id=\"\"date\"\" name=\"\"date\"\" type=\"\"text\"\" value=\"\"-01/01/1900 00:00:00-\"\" />\",\n                    Action = new Func<MvcHtmlString>(() => dateModelhelper.TextBoxFor(m => m.date, \"-{0}-\", new RouteValueDictionary()))\n                }\n            };\n\n            // Act && Assert\n            foreach (var test in tests)\n            {\n                Assert.Equal(test.Html, test.Action().ToHtmlString());\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void TextBoxFor_AttributeEncodes_AddedHtmlAttributes(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.TemplateInfo.HtmlFieldPrefix = \"name\";\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            var result = helper.TextBoxFor(m => m, htmlAttributes: new { attribute = text, }).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                @\"<input attribute=\"\"\" + encodedText + @\"\"\" id=\"\"name\"\" name=\"\"name\"\" type=\"\"text\"\" value=\"\"\"\" />\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void TextBoxFor_AttributeEncodes_Format(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: String.Empty);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.TemplateInfo.HtmlFieldPrefix = \"name\";\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            var result = helper.TextBoxFor(m => m, format: text).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                @\"<input id=\"\"name\"\" name=\"\"name\"\" type=\"\"text\"\" value=\"\"\" + encodedText + @\"\"\" />\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void TextBoxFor_AttributeEncodes_Prefix(string text, bool htmlEncode, string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.TemplateInfo.HtmlFieldPrefix = text;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            // htmlAttributes included only to avoid special-cased renaming done for id attribute.\n            var result = helper.TextBoxFor(m => m, htmlAttributes: new { id = \"id\", }).ToHtmlString();\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"id\"\" name=\"\"\" + encodedText + @\"\"\" type=\"\"text\"\" value=\"\"\"\" />\", result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void TextBoxFor_AttributeEncodes_Value(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            var result = helper.TextBoxFor(m => text).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                @\"<input id=\"\"text\"\" name=\"\"text\"\" type=\"\"text\"\" value=\"\"\" + encodedText + @\"\"\" />\",\n                result);\n        }\n\n        // MODELS\n        private class FooModel\n        {\n            public string foo { get; set; }\n\n            public override string ToString()\n            {\n                return String.Format(\"{{ foo = {0} }}\", foo ?? \"(null)\");\n            }\n        }\n\n        private class FooBarModel : FooModel\n        {\n            public string bar { get; set; }\n\n            public override string ToString()\n            {\n                return String.Format(\"{{ foo = {0}, bar = {1} }}\", foo ?? \"(null)\", bar ?? \"(null)\");\n            }\n        }\n\n        private class FooBarBazModel\n        {\n            public bool foo { get; set; }\n            public bool bar { get; set; }\n            public bool baz { get; set; }\n\n            public override string ToString()\n            {\n                return String.Format(\"{{ foo = {0}, bar = {1}, baz = {2} }}\", foo, bar, baz);\n            }\n        }\n\n        private class ShallowModel\n        {\n            [Required]\n            public string foo { get; set; }\n        }\n\n        private class DeepContainerModel\n        {\n            public ShallowModel contained { get; set; }\n        }\n\n        private class HiddenModel : FooModel\n        {\n            public byte[] bytes { get; set; }\n            public Binary binary { get; set; }\n        }\n\n        private class DateModel\n        {\n            public DateTime date { get; set; }\n        }\n\n        // CHECKBOX\n        private static ViewDataDictionary<FooBarBazModel> GetCheckBoxViewData()\n        {\n            ViewDataDictionary<FooBarBazModel> viewData = new ViewDataDictionary<FooBarBazModel> { { \"foo\", true }, { \"bar\", \"NotTrue\" }, { \"baz\", false } };\n            return viewData;\n        }\n\n        // HIDDEN\n        private static ViewDataDictionary<HiddenModel> GetHiddenViewData()\n        {\n            return new ViewDataDictionary<HiddenModel>(new HiddenModel()) { { \"foo\", \"ViewDataFoo\" } };\n        }\n\n        private static ViewDataDictionary<HiddenModel> GetHiddenViewDataWithErrors()\n        {\n            ViewDataDictionary<HiddenModel> viewData = new ViewDataDictionary<HiddenModel> { { \"foo\", \"ViewDataFoo\" } };\n            viewData.Model = new HiddenModel();\n            ModelState modelStateFoo = new ModelState();\n            modelStateFoo.Errors.Add(new ModelError(\"foo error 1\"));\n            modelStateFoo.Errors.Add(new ModelError(\"foo error 2\"));\n            viewData.ModelState[\"foo\"] = modelStateFoo;\n            modelStateFoo.Value = HtmlHelperTest.GetValueProviderResult(\"AttemptedValueFoo\", \"AttemptedValueFoo\");\n\n            return viewData;\n        }\n\n        // PASSWORD\n        private static ViewDataDictionary<FooModel> GetPasswordViewData()\n        {\n            return new ViewDataDictionary<FooModel> { { \"foo\", \"ViewDataFoo\" } };\n        }\n\n        private static ViewDataDictionary<FooModel> GetPasswordViewDataWithErrors()\n        {\n            ViewDataDictionary<FooModel> viewData = new ViewDataDictionary<FooModel> { { \"foo\", \"ViewDataFoo\" } };\n            ModelState modelStateFoo = new ModelState();\n            modelStateFoo.Errors.Add(new ModelError(\"foo error 1\"));\n            modelStateFoo.Errors.Add(new ModelError(\"foo error 2\"));\n            viewData.ModelState[\"foo\"] = modelStateFoo;\n            modelStateFoo.Value = HtmlHelperTest.GetValueProviderResult(\"AttemptedValueFoo\", \"AttemptedValueFoo\");\n\n            return viewData;\n        }\n\n        // RADIO\n        private static ViewDataDictionary<FooBarModel> GetRadioButtonViewData()\n        {\n            ViewDataDictionary<FooBarModel> viewData = new ViewDataDictionary<FooBarModel> { { \"foo\", \"ViewDataFoo\" } };\n            viewData.Model = new FooBarModel { foo = \"ViewItemFoo\", bar = \"ViewItemBar\" };\n            ModelState modelState = new ModelState();\n            modelState.Value = HtmlHelperTest.GetValueProviderResult(\"ViewDataFoo\", \"ViewDataFoo\");\n            viewData.ModelState[\"foo\"] = modelState;\n\n            return viewData;\n        }\n\n        private static ViewDataDictionary<string> GetRadioButtonNestedAndUnsetViewData()\n        {\n            ViewDataDictionary<FooBarModel> viewData = new ViewDataDictionary<FooBarModel> { };\n            viewData.Model = new FooBarModel { foo = \"ViewItemFoo\", bar = \"ViewItemBar\" };\n\n\n            Expression<Func<FooBarModel, string>> containedExpression = m => m.foo;\n\n            var metadata = ModelMetadata.FromLambdaExpression(containedExpression, viewData);\n            var htmlFieldName = ExpressionHelper.GetExpressionText(containedExpression);\n\n\n            ViewDataDictionary nestedViewData = new ViewDataDictionary(viewData)\n            {\n                Model = metadata.Model,\n                ModelMetadata = metadata,\n                TemplateInfo = new TemplateInfo\n                {\n                    HtmlFieldPrefix = viewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName),\n                }\n            };\n\n            return new ViewDataDictionary<string>(nestedViewData);\n        }\n\n        // TEXTBOX\n        private static readonly RouteValueDictionary _attributesDictionary = new RouteValueDictionary(new { baz = \"BazValue\" });\n        private static readonly object _attributesObjectDictionary = new { baz = \"BazObjValue\" };\n        private static readonly object _attributesObjectUnderscoresDictionary = new { foo_baz = \"BazObjValue\" };\n\n        private static ViewDataDictionary<FooBarModel> GetTextBoxViewData()\n        {\n            ViewDataDictionary<FooBarModel> viewData = new ViewDataDictionary<FooBarModel> { { \"foo\", \"ViewDataFoo\" } };\n            viewData.Model = new FooBarModel { foo = \"ViewItemFoo\", bar = \"ViewItemBar\" };\n\n            return viewData;\n        }\n\n        private static ViewDataDictionary<FooBarModel> GetTextBoxViewDataWithErrors()\n        {\n            ViewDataDictionary<FooBarModel> viewData = new ViewDataDictionary<FooBarModel> { { \"foo\", \"ViewDataFoo\" } };\n            viewData.Model = new FooBarModel { foo = \"ViewItemFoo\", bar = \"ViewItemBar\" };\n            ModelState modelStateFoo = new ModelState();\n            modelStateFoo.Errors.Add(new ModelError(\"foo error 1\"));\n            modelStateFoo.Errors.Add(new ModelError(\"foo error 2\"));\n            viewData.ModelState[\"foo\"] = modelStateFoo;\n            modelStateFoo.Value = HtmlHelperTest.GetValueProviderResult(new string[] { \"AttemptedValueFoo\" }, \"AttemptedValueFoo\");\n\n            return viewData;\n        }\n\n        public void Dispose()\n        {\n            // Reset ScopeStorage (written via e.g. ViewContext.ClientValidationEnabled) between tests to avoid unexpected interactions.\n            ScopeStorage.CurrentProvider = new StaticScopeStorageProvider();\n            ScopeStorage.GlobalScope.Clear();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Html/Test/LabelExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq.Expressions;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Html.Test\n{\n    public class LabelExtensionsTest\n    {\n        Mock<ModelMetadataProvider> metadataProvider;\n        Mock<ModelMetadata> metadata;\n        ViewDataDictionary viewData;\n        Mock<ViewContext> viewContext;\n        Mock<IViewDataContainer> viewDataContainer;\n        HtmlHelper<object> html;\n\n        public LabelExtensionsTest()\n        {\n            metadataProvider = new Mock<ModelMetadataProvider>();\n            metadata = new Mock<ModelMetadata>(metadataProvider.Object, null, null, typeof(object), null);\n            viewData = new ViewDataDictionary();\n\n            viewContext = new Mock<ViewContext>();\n            viewContext.Setup(c => c.ViewData).Returns(viewData);\n\n            viewDataContainer = new Mock<IViewDataContainer>();\n            viewDataContainer.Setup(c => c.ViewData).Returns(viewData);\n\n            html = new HtmlHelper<object>(viewContext.Object, viewDataContainer.Object);\n\n            metadataProvider.Setup(p => p.GetMetadataForProperties(It.IsAny<object>(), It.IsAny<Type>()))\n                .Returns(new ModelMetadata[0]);\n            metadataProvider.Setup(p => p.GetMetadataForProperty(It.IsAny<Func<object>>(), It.IsAny<Type>(), It.IsAny<string>()))\n                .Returns(metadata.Object);\n            metadataProvider.Setup(p => p.GetMetadataForType(It.IsAny<Func<object>>(), It.IsAny<Type>()))\n                .Returns(metadata.Object);\n        }\n\n        // Label tests\n\n        [Fact]\n        public void LabelNullExpressionThrows()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => html.Label(null),\n                \"expression\");\n        }\n\n        [Fact]\n        public void LabelViewDataNotFound()\n        {\n            // Act\n            MvcHtmlString result = html.Label(\"PropertyName\", null, null, metadataProvider.Object);\n\n            // Assert\n            Assert.Equal(@\"<label for=\"\"PropertyName\"\">PropertyName</label>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void LabelViewDataNull()\n        {\n            // Act\n            viewData[\"PropertyName\"] = null;\n            MvcHtmlString result = html.Label(\"PropertyName\", null, null, metadataProvider.Object);\n\n            // Assert\n            Assert.Equal(@\"<label for=\"\"PropertyName\"\">PropertyName</label>\", result.ToHtmlString());\n        }\n\n        class Model\n        {\n            public string PropertyName { get; set; }\n        }\n\n        [Fact]\n        public void LabelViewDataFromPropertyGetsActualPropertyType()\n        {\n            // Arrange\n            Model model = new Model { PropertyName = \"propertyValue\" };\n            HtmlHelper<Model> html = new HtmlHelper<Model>(viewContext.Object, viewDataContainer.Object);\n            viewData.Model = model;\n            metadataProvider.Setup(p => p.GetMetadataForProperty(It.IsAny<Func<object>>(), typeof(Model), \"PropertyName\"))\n                .Returns(metadata.Object)\n                .Verifiable();\n\n            // Act\n            html.Label(\"PropertyName\", null, null, metadataProvider.Object);\n\n            // Assert\n            metadataProvider.Verify();\n        }\n\n        [Fact]\n        public void LabelUsesTemplateInfoPrefix()\n        {\n            // Arrange\n            viewData.TemplateInfo.HtmlFieldPrefix = \"Prefix\";\n\n            // Act\n            MvcHtmlString result = html.Label(\"PropertyName\", null, null, metadataProvider.Object);\n\n            // Assert\n            Assert.Equal(@\"<label for=\"\"Prefix_PropertyName\"\">PropertyName</label>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void LabelUsesLabelTextBeforeMetadata()\n        {\n            // Arrange\n            metadata = new Mock<ModelMetadata>(metadataProvider.Object, null, null, typeof(object), \"Custom property name from metadata\");\n            metadataProvider.Setup(p => p.GetMetadataForType(It.IsAny<Func<object>>(), It.IsAny<Type>()))\n                .Returns(metadata.Object);\n\n            //Act\n            MvcHtmlString result = html.Label(\"PropertyName\", \"Label Text\", null, metadataProvider.Object);\n\n            // Assert\n            Assert.Equal(@\"<label for=\"\"PropertyName\"\">Label Text</label>\", result.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"HtmlEncodedData_NoHtmlEncode\", PropertyType = typeof(EncodedDataSets))]\n        public void Label_HtmlEncodes_LabelText(string text, string expectedText)\n        {\n            // Arrange & Act\n            var result =\n                html.Label(\"PropertyName\", text, htmlAttributes: null, metadataProvider: metadataProvider.Object);\n\n            // Assert\n            Assert.Equal(@\"<label for=\"\"PropertyName\"\">\" + expectedText + \"</label>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void LabelUsesMetadataForDisplayTextWhenLabelTextIsNull()\n        {\n            // Arrange\n            metadata.Setup(m => m.DisplayName).Returns(\"Custom display name from metadata\");\n\n            // Act\n            MvcHtmlString result = html.Label(\"PropertyName\", null, null, metadataProvider.Object);\n\n            // Assert\n            Assert.Equal(@\"<label for=\"\"PropertyName\"\">Custom display name from metadata</label>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void LabelUsesMetadataForPropertyNameWhenDisplayNameIsNull()\n        {\n            // Arrange\n            metadata = new Mock<ModelMetadata>(metadataProvider.Object, null, null, typeof(object), \"Custom property name from metadata\");\n            metadataProvider.Setup(p => p.GetMetadataForType(It.IsAny<Func<object>>(), It.IsAny<Type>()))\n                .Returns(metadata.Object);\n\n            // Act\n            MvcHtmlString result = html.Label(\"PropertyName\", null, null, metadataProvider.Object);\n\n            // Assert\n            Assert.Equal(@\"<label for=\"\"PropertyName\"\">Custom property name from metadata</label>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void LabelEmptyDisplayNameReturnsEmptyLabelText()\n        {\n            // Arrange\n            metadata.Setup(m => m.DisplayName).Returns(String.Empty);\n\n            // Act\n            MvcHtmlString result = html.Label(\"PropertyName\", null, null, metadataProvider.Object);\n\n            // Assert\n            Assert.Equal(String.Empty, result.ToHtmlString());\n        }\n\n        [Fact]\n        public void LabelWithAnonymousValues()\n        {\n            // Act\n            MvcHtmlString result = html.Label(\"PropertyName\", null, new { @for = \"attrFor\" }, metadataProvider.Object);\n\n            // Assert\n            Assert.Equal(@\"<label for=\"\"attrFor\"\">PropertyName</label>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void LabelWithAnonymousValuesAndLabelText()\n        {\n            // Act\n            MvcHtmlString result = html.Label(\"PropertyName\", \"Label Text\", new { @for = \"attrFor\" }, metadataProvider.Object);\n\n            // Assert\n            Assert.Equal(@\"<label for=\"\"attrFor\"\">Label Text</label>\", result.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData_NoHtmlEncode\", PropertyType = typeof(EncodedDataSets))]\n        public void LabelWithAnonymousValues_AttributeEncodes_AddedHtmlAttributes(string text, string expectedText)\n        {\n            // Arrange & Act\n            var result = html.Label(\"PropertyName\", \"text\", new { attribute = text }, metadataProvider.Object);\n\n            // Assert\n            Assert.Equal(\n                @\"<label attribute=\"\"\" + expectedText + @\"\"\" for=\"\"PropertyName\"\">text</label>\",\n                result.ToHtmlString());\n        }\n\n        [Fact]\n        public void LabelWithTypedAttributes()\n        {\n            // Arrange\n            Dictionary<string, object> htmlAttributes = new Dictionary<string, object>\n            {\n                { \"foo\", \"bar\" },\n                { \"quux\", \"baz\" }\n            };\n\n            // Act\n            MvcHtmlString result = html.Label(\"PropertyName\", null, htmlAttributes, metadataProvider.Object);\n\n            // Assert\n            Assert.Equal(@\"<label foo=\"\"bar\"\" for=\"\"PropertyName\"\" quux=\"\"baz\"\">PropertyName</label>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void LabelWithTypedAttributesAndLabelText()\n        {\n            // Arrange\n            Dictionary<string, object> htmlAttributes = new Dictionary<string, object>\n            {\n                { \"foo\", \"bar\" },\n                { \"quux\", \"baz\" }\n            };\n\n            // Act\n            MvcHtmlString result = html.Label(\"PropertyName\", \"Label Text\", htmlAttributes, metadataProvider.Object);\n\n            // Assert\n            Assert.Equal(@\"<label foo=\"\"bar\"\" for=\"\"PropertyName\"\" quux=\"\"baz\"\">Label Text</label>\", result.ToHtmlString());\n        }\n\n        // LabelFor tests\n\n        [Fact]\n        public void LabelForNullExpressionThrows()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => html.LabelFor((Expression<Func<Object, Object>>)null),\n                \"expression\");\n        }\n\n        [Fact]\n        public void LabelForNonMemberExpressionThrows()\n        {\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => html.LabelFor(model => new { foo = \"Bar\" }, null, null, metadataProvider.Object),\n                \"Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.\");\n        }\n\n        [Fact]\n        public void LabelForViewDataNotFound()\n        {\n            // Arrange\n            string unknownKey = \"this is a dummy parameter value\";\n\n            // Act\n            MvcHtmlString result = html.LabelFor(model => unknownKey, null, null, metadataProvider.Object);\n\n            // Assert\n            Assert.Equal(@\"<label for=\"\"unknownKey\"\">unknownKey</label>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void LabelForUsesTemplateInfoPrefix()\n        {\n            // Arrange\n            viewData.TemplateInfo.HtmlFieldPrefix = \"Prefix\";\n            string unknownKey = \"this is a dummy parameter value\";\n\n            // Act\n            MvcHtmlString result = html.LabelFor(model => unknownKey, null, null, metadataProvider.Object);\n\n            // Assert\n            Assert.Equal(@\"<label for=\"\"Prefix_unknownKey\"\">unknownKey</label>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void LabelForUsesLabelTextBeforeModelMetadata()\n        {\n            // Arrange\n            metadata.Setup(m => m.DisplayName).Returns(\"Custom display name from metadata\");\n            string unknownKey = \"this is a dummy parameter value\";\n\n            //Act\n            MvcHtmlString result = html.LabelFor(model => unknownKey, \"Label Text\", null, metadataProvider.Object);\n\n            // Assert\n            Assert.Equal(@\"<label for=\"\"unknownKey\"\">Label Text</label>\", result.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"HtmlEncodedData_NoHtmlEncode\", PropertyType = typeof(EncodedDataSets))]\n        public void LabelFor_HtmlEncodes_LabelText(string text, string expectedText)\n        {\n            // Arrange\n            var dummy = \"this is a dummy parameter value\";\n\n            // Arrange & Act\n            var result =\n                html.LabelFor(m => dummy, text, htmlAttributes: null, metadataProvider: metadataProvider.Object);\n\n            // Assert\n            Assert.Equal(@\"<label for=\"\"dummy\"\">\" + expectedText + \"</label>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void LabelForUsesModelMetadata()\n        {\n            // Arrange\n            metadata.Setup(m => m.DisplayName).Returns(\"Custom display name from metadata\");\n            string unknownKey = \"this is a dummy parameter value\";\n\n            // Act\n            MvcHtmlString result = html.LabelFor(model => unknownKey, null, null, metadataProvider.Object);\n\n            // Assert\n            Assert.Equal(@\"<label for=\"\"unknownKey\"\">Custom display name from metadata</label>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void LabelForEmptyDisplayNameReturnsEmptyLabelText()\n        {\n            // Arrange\n            metadata.Setup(m => m.DisplayName).Returns(String.Empty);\n            string unknownKey = \"this is a dummy parameter value\";\n\n            // Act\n            MvcHtmlString result = html.LabelFor(model => unknownKey, null, null, metadataProvider.Object);\n\n            // Assert\n            Assert.Equal(String.Empty, result.ToHtmlString());\n        }\n\n        [Fact]\n        public void LabelForWithAnonymousValues()\n        {\n            //Arrange\n            string unknownKey = \"this is a dummy parameter value\";\n\n            // Act\n            MvcHtmlString result = html.LabelFor(model => unknownKey, null, new { @for = \"attrFor\" }, metadataProvider.Object);\n\n            // Assert\n            Assert.Equal(@\"<label for=\"\"attrFor\"\">unknownKey</label>\", result.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData_NoHtmlEncode\", PropertyType = typeof(EncodedDataSets))]\n        public void LabeForlWithAnonymousValues_AttributeEncodes_AddedHtmlAttributes(string text, string expectedText)\n        {\n            // Arrange\n            var dummy = \"this is a dummy parameter value\";\n\n            // Act\n            var result =\n                html.LabelFor(m => dummy, \"text\", new { attribute = text }, metadataProvider.Object);\n\n            // Assert\n            Assert.Equal(\n                @\"<label attribute=\"\"\" + expectedText + @\"\"\" for=\"\"dummy\"\">text</label>\",\n                result.ToHtmlString());\n        }\n\n        [Fact]\n        public void LabelForWithAnonymousValuesAndLabelText()\n        {\n            //Arrange\n            string unknownKey = \"this is a dummy parameter value\";\n\n            // Act\n            MvcHtmlString result = html.LabelFor(model => unknownKey, \"Label Text\", new { @for = \"attrFor\" }, metadataProvider.Object);\n\n            // Assert\n            Assert.Equal(@\"<label for=\"\"attrFor\"\">Label Text</label>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void LabelForWithTypedAttributes()\n        {\n            //Arrange\n            string unknownKey = \"this is a dummy parameter value\";\n\n            Dictionary<string, object> htmlAttributes = new Dictionary<string, object>\n            {\n                { \"foo\", \"bar\" },\n                { \"quux\", \"baz\" }\n            };\n\n            // Act\n            MvcHtmlString result = html.LabelFor(model => unknownKey, null, htmlAttributes, metadataProvider.Object);\n\n            // Assert\n            Assert.Equal(@\"<label foo=\"\"bar\"\" for=\"\"unknownKey\"\" quux=\"\"baz\"\">unknownKey</label>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void LabelForWithTypedAttributesAndLabelText()\n        {\n            //Arrange\n            string unknownKey = \"this is a dummy parameter value\";\n\n            Dictionary<string, object> htmlAttributes = new Dictionary<string, object>\n            {\n                { \"foo\", \"bar\" },\n                { \"quux\", \"baz\" }\n            };\n\n            // Act\n            MvcHtmlString result = html.LabelFor(model => unknownKey, \"Label Text\", htmlAttributes, metadataProvider.Object);\n\n            // Assert\n            Assert.Equal(@\"<label foo=\"\"bar\"\" for=\"\"unknownKey\"\" quux=\"\"baz\"\">Label Text</label>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void LabelForWithNestedClass()\n        { // Dev10 Bug #936323\n            // Arrange\n            HtmlHelper<NestedProduct> html = new HtmlHelper<NestedProduct>(viewContext.Object, viewDataContainer.Object);\n\n            // Act\n            MvcHtmlString result = html.LabelFor(nested => nested.product.Id, null, null, metadataProvider.Object);\n\n            //Assert\n            Assert.Equal(@\"<label for=\"\"product_Id\"\">Id</label>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void LabelForWithArrayExpression()\n        { // Dev10 Bug #905780\n            // Arrange\n            HtmlHelper<Cart> html = new HtmlHelper<Cart>(viewContext.Object, viewDataContainer.Object);\n\n            // Act\n            MvcHtmlString result = html.LabelFor(cart => cart.Products[0].Id, null, null, metadataProvider.Object);\n\n            // Assert\n            Assert.Equal(@\"<label for=\"\"Products_0__Id\"\">Id</label>\", result.ToHtmlString());\n        }\n\n        private class Product\n        {\n            public int Id { get; set; }\n        }\n\n        private class Cart\n        {\n            public Product[] Products { get; set; }\n        }\n\n        private class NestedProduct\n        {\n            public Product product = new Product();\n        }\n\n        // LabelForModel tests\n\n        [Fact]\n        public void LabelForModelUsesLabelTextBeforeModelMetadata()\n        {\n            // Arrange\n            viewData.ModelMetadata = metadata.Object;\n            viewData.TemplateInfo.HtmlFieldPrefix = \"Prefix\";\n            metadata.Setup(m => m.DisplayName).Returns(\"Custom display name from metadata\");\n\n            // Act\n            MvcHtmlString result = html.LabelForModel(\"Label Text\");\n\n            // Assert\n            Assert.Equal(@\"<label for=\"\"Prefix\"\">Label Text</label>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void LabelForModelUsesModelMetadata()\n        {\n            // Arrange\n            viewData.ModelMetadata = metadata.Object;\n            viewData.TemplateInfo.HtmlFieldPrefix = \"Prefix\";\n            metadata.Setup(m => m.DisplayName).Returns(\"Custom display name from metadata\");\n\n            // Act\n            MvcHtmlString result = html.LabelForModel();\n\n            // Assert\n            Assert.Equal(@\"<label for=\"\"Prefix\"\">Custom display name from metadata</label>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void LabelForModelWithAnonymousValues()\n        {\n            //Arrange\n            viewData.ModelMetadata = metadata.Object;\n            viewData.TemplateInfo.HtmlFieldPrefix = \"Prefix\";\n            metadata.Setup(m => m.DisplayName).Returns(\"Custom display name from metadata\");\n\n            // Act\n            MvcHtmlString result = html.LabelForModel(new { @for = \"attrFor\" });\n\n            // Assert\n            Assert.Equal(@\"<label for=\"\"attrFor\"\">Custom display name from metadata</label>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void LabelForModelWithAnonymousValuesAndLabelText()\n        {\n            //Arrange\n            viewData.ModelMetadata = metadata.Object;\n            viewData.TemplateInfo.HtmlFieldPrefix = \"Prefix\";\n            metadata.Setup(m => m.DisplayName).Returns(\"Custom display name from metadata\");\n\n            // Act\n            MvcHtmlString result = html.LabelForModel(\"Label Text\", new { @for = \"attrFor\" });\n\n            // Assert\n            Assert.Equal(@\"<label for=\"\"attrFor\"\">Label Text</label>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void LabelForModelWithTypedAttributes()\n        {\n            //Arrange\n            viewData.ModelMetadata = metadata.Object;\n            viewData.TemplateInfo.HtmlFieldPrefix = \"Prefix\";\n            metadata.Setup(m => m.DisplayName).Returns(\"Custom display name from metadata\");\n\n            Dictionary<string, object> htmlAttributes = new Dictionary<string, object>\n            {\n                { \"foo\", \"bar\" },\n                { \"quux\", \"baz\" }\n            };\n\n            // Act\n            MvcHtmlString result = html.LabelForModel(htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<label foo=\"\"bar\"\" for=\"\"Prefix\"\" quux=\"\"baz\"\">Custom display name from metadata</label>\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void LabelForModelWithTypedAttributesAndLabelText()\n        {\n            //Arrange\n            viewData.ModelMetadata = metadata.Object;\n            viewData.TemplateInfo.HtmlFieldPrefix = \"Prefix\";\n            metadata.Setup(m => m.DisplayName).Returns(\"Custom display name from metadata\");\n\n            Dictionary<string, object> htmlAttributes = new Dictionary<string, object>\n            {\n                { \"foo\", \"bar\" },\n                { \"quux\", \"baz\" }\n            };\n\n            // Act\n            MvcHtmlString result = html.LabelForModel(\"Label Text\", htmlAttributes);\n\n            // Assert\n            Assert.Equal(@\"<label foo=\"\"bar\"\" for=\"\"Prefix\"\" quux=\"\"baz\"\">Label Text</label>\", result.ToHtmlString());\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Html/Test/LinkExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace System.Web.Mvc.Html.Test\n{\n    public class LinkExtensionsTest\n    {\n        private const string AppPathModifier = MvcHelper.AppPathModifier;\n\n        [Fact]\n        public void ActionLink()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.ActionLink(\"linktext\", \"newaction\");\n\n            // Assert\n            Assert.Equal(@\"<a href=\"\"\" + AppPathModifier + @\"/app/home/newaction\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"UrlEncodedData_NoHtmlEncode\", PropertyType = typeof(EncodedDataSets))]\n        public void ActionLink_UrlEncodesAction(string text, string expectedText)\n        {\n            // Arrange\n            var helper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            var result = helper.ActionLink(linkText: \"link\", actionName: text);\n\n            // Assert\n            Assert.Equal(\n                @\"<a href=\"\"\" + AppPathModifier + @\"/app/home/\" + expectedText + @\"\"\">link</a>\",\n                result.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkDictionaryOverridesImplicitValues()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.ActionLink(\"linktext\", \"newaction\", null, new { href = \"http://foo.com\" });\n\n            // Assert\n            Assert.Equal(@\"<a href=\"\"http://foo.com\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkExplictValuesOverrideDictionary()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.ActionLink(\"linktext\", \"explicitAction\", new { action = \"dictionaryAction\" }, null);\n\n            // Assert\n            Assert.Equal(@\"<a href=\"\"\" + AppPathModifier + @\"/app/home/explicitAction\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkParametersNeedEscaping()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.ActionLink(\"linktext<&>\\\"\", \"new action<&>\\\"\");\n\n            // Assert\n            Assert.Equal(@\"<a href=\"\"\" + AppPathModifier + @\"/app/home/new%20action%3C%26%3E%22\"\">linktext&lt;&amp;&gt;&quot;</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithActionNameAndValueDictionary()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.ActionLink(\"linktext\", \"newaction\", new RouteValueDictionary(new { controller = \"home2\" }));\n\n            // Assert\n            Assert.Equal(@\"<a href=\"\"\" + AppPathModifier + @\"/app/home2/newaction\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithActionNameAndValueObject()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.ActionLink(\"linktext\", \"newaction\", new { controller = \"home2\" });\n\n            // Assert\n            Assert.Equal(@\"<a href=\"\"\" + AppPathModifier + @\"/app/home2/newaction\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithControllerName()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.ActionLink(\"linktext\", \"newaction\", \"home2\");\n\n            // Assert\n            Assert.Equal(@\"<a href=\"\"\" + AppPathModifier + @\"/app/home2/newaction\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"UrlEncodedData_NoHtmlEncode\", PropertyType = typeof(EncodedDataSets))]\n        public void ActionLinkWithControllerName_UrlEncodesController(string text, string expectedText)\n        {\n            // Arrange\n            var helper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            var result = helper.ActionLink(linkText: \"link\", actionName: \"newAction\", controllerName: text);\n\n            // Assert\n            Assert.Equal(\n                @\"<a href=\"\"\" + AppPathModifier + @\"/app/\" + expectedText + @\"/newAction\"\">link</a>\",\n                result.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithControllerNameAndDictionary()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.ActionLink(\"linktext\", \"newaction\", \"home2\", new RouteValueDictionary(new { id = \"someid\" }), new RouteValueDictionary(new { baz = \"baz\" }));\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"baz\"\" href=\"\"\" + AppPathModifier + @\"/app/home2/newaction/someid\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithControllerNameAndObjectProperties()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.ActionLink(\"linktext\", \"newaction\", \"home2\", new { id = \"someid\" }, new { baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"baz\"\" href=\"\"\" + AppPathModifier + @\"/app/home2/newaction/someid\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData_NoHtmlEncode\", PropertyType = typeof(EncodedDataSets))]\n        public void ActionLinkWithControllerNameAndObjectProperties_AttributeEncodes_AddedHtmlAttributes(\n            string text,\n            string expectedText)\n        {\n            // Arrange\n            var helper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            var result =\n                helper.ActionLink(\"text\", \"action\", \"controller\", routeValues: null, htmlAttributes: new { attribute = text });\n\n            // Assert\n            Assert.Equal(\n                @\"<a attribute=\"\"\" + expectedText + @\"\"\" href=\"\"\" + AppPathModifier + @\"/app/controller/action\"\">text</a>\",\n                result.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithControllerNameAndObjectPropertiesWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.ActionLink(\"linktext\", \"newaction\", \"home2\", new { id = \"someid\" }, new { foo_baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<a foo-baz=\"\"baz\"\" href=\"\"\" + AppPathModifier + @\"/app/home2/newaction/someid\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithDictionary()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.ActionLink(\"linktext\", \"newaction\", new RouteValueDictionary(new { Controller = \"home2\", id = \"someid\" }), new RouteValueDictionary(new { baz = \"baz\" }));\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"baz\"\" href=\"\"\" + AppPathModifier + @\"/app/home2/newaction/someid\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithFragment()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.ActionLink(\"linktext\", \"newaction\", \"home2\", \"http\", \"foo.bar.com\", \"foo\", new { id = \"someid\" }, new { baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"baz\"\" href=\"\"http://foo.bar.com\" + AppPathModifier + @\"/app/home2/newaction/someid#foo\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithFragmentAndAttributesWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.ActionLink(\"linktext\", \"newaction\", \"home2\", \"http\", \"foo.bar.com\", \"foo\", new { id = \"someid\" }, new { foo_baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<a foo-baz=\"\"baz\"\" href=\"\"http://foo.bar.com\" + AppPathModifier + @\"/app/home2/newaction/someid#foo\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithNullHostname()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.ActionLink(\"linktext\", \"newaction\", \"home2\", \"https\", null /* hostName */, \"foo\", new { id = \"someid\" }, new { baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"baz\"\" href=\"\"https://localhost\" + AppPathModifier + @\"/app/home2/newaction/someid#foo\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithNullProtocolAndFragment()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.ActionLink(\"linktext\", \"newaction\", \"home2\", null /* protocol */, \"foo.bar.com\", null /* fragment */, new { id = \"someid\" }, new { baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"baz\"\" href=\"\"http://foo.bar.com\" + AppPathModifier + @\"/app/home2/newaction/someid\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithNullProtocolNullHostNameAndNullFragment()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.ActionLink(\"linktext\", \"newaction\", \"home2\", null /* protocol */, null /* hostName */, null /* fragment */, new { id = \"someid\" }, new { baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"baz\"\" href=\"\"\" + AppPathModifier + @\"/app/home2/newaction/someid\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithObjectProperties()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.ActionLink(\"linktext\", \"newaction\", new { Controller = \"home2\", id = \"someid\" }, new { baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"baz\"\" href=\"\"\" + AppPathModifier + @\"/app/home2/newaction/someid\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithObjectPropertiesWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.ActionLink(\"linktext\", \"newaction\", new { Controller = \"home2\", id = \"someid\" }, new { foo_baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<a foo-baz=\"\"baz\"\" href=\"\"\" + AppPathModifier + @\"/app/home2/newaction/someid\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithProtocol()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.ActionLink(\"linktext\", \"newaction\", \"home2\", \"https\", \"foo.bar.com\", null /* fragment */, new { id = \"someid\" }, new { baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"baz\"\" href=\"\"https://foo.bar.com\" + AppPathModifier + @\"/app/home2/newaction/someid\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithProtocolAndFragment()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.ActionLink(\"linktext\", \"newaction\", \"home2\", \"https\", \"foo.bar.com\", \"foo\", new { id = \"someid\" }, new { baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"baz\"\" href=\"\"https://foo.bar.com\" + AppPathModifier + @\"/app/home2/newaction/someid#foo\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithDefaultPort()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(Uri.UriSchemeHttps, -1);\n\n            // Act\n            MvcHtmlString html = htmlHelper.ActionLink(\"linktext\", \"newaction\", \"home2\", \"https\", \"foo.bar.com\", \"foo\", new { id = \"someid\" }, new { baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"baz\"\" href=\"\"https://foo.bar.com\" + AppPathModifier + @\"/app/home2/newaction/someid#foo\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithDifferentPortProtocols()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(Uri.UriSchemeHttp, -1);\n\n            // Act\n            MvcHtmlString html = htmlHelper.ActionLink(\"linktext\", \"newaction\", \"home2\", \"https\", \"foo.bar.com\", \"foo\", new { id = \"someid\" }, new { baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"baz\"\" href=\"\"https://foo.bar.com\" + AppPathModifier + @\"/app/home2/newaction/someid#foo\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithNonDefaultPortAndDifferentProtocol()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(Uri.UriSchemeHttp, 32768);\n\n            // Act\n            MvcHtmlString html = htmlHelper.ActionLink(\"linktext\", \"newaction\", \"home2\", \"https\", \"foo.bar.com\", \"foo\", new { id = \"someid\" }, new { baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"baz\"\" href=\"\"https://foo.bar.com\" + AppPathModifier + @\"/app/home2/newaction/someid#foo\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ActionLinkWithNonDefaultPortAndSameProtocol()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(Uri.UriSchemeHttp, 32768);\n\n            // Act\n            MvcHtmlString html = htmlHelper.ActionLink(\"linktext\", \"newaction\", \"home2\", \"http\", \"foo.bar.com\", \"foo\", new { id = \"someid\" }, new { baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"baz\"\" href=\"\"http://foo.bar.com:32768\" + AppPathModifier + @\"/app/home2/newaction/someid#foo\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void LinkGenerationDoesNotChangeProvidedDictionary()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n            RouteValueDictionary valuesDictionary = new RouteValueDictionary();\n\n            // Act\n            htmlHelper.ActionLink(\"linkText\", \"actionName\", valuesDictionary, new RouteValueDictionary());\n\n            // Assert\n            Assert.Empty(valuesDictionary);\n            Assert.False(valuesDictionary.ContainsKey(\"action\"));\n        }\n\n        [Fact]\n        public void ActionLinkProducesLowercaseUrls()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n            htmlHelper.RouteCollection.LowercaseUrls = true;\n\n            // Act\n            MvcHtmlString html = htmlHelper.ActionLink(\"about\", \"About\", \"Home\");\n\n            // Assert\n            Assert.True(html.ToHtmlString() == html.ToHtmlString().ToLowerInvariant());\n        }\n\n        [Fact]\n        public void ActionLinkProducesLowercaseUrlsAfterRegisteringAnArea()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n            MyAreaRegistration myArea = new MyAreaRegistration();\n            myArea.CreateContextAndRegister(htmlHelper.RouteCollection, null);\n            htmlHelper.RouteCollection.LowercaseUrls = true;\n\n            // Act\n            MvcHtmlString html = htmlHelper.ActionLink(\"about\", \"About\", \"Home\");\n\n            // Assert\n            Assert.True(html.ToHtmlString() == html.ToHtmlString().ToLowerInvariant());\n        }\n\n        [Fact]\n        public void NullOrEmptyStringParameterThrows()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n            var tests = new[]\n            {\n                // ActionLink(string linkText, string actionName)\n                new { Parameter = \"linkText\", Action = new Action(() => htmlHelper.ActionLink(String.Empty, \"actionName\")) },\n                // ActionLink(string linkText, string actionName, object routeValues, object htmlAttributes)\n                new { Parameter = \"linkText\", Action = new Action(() => htmlHelper.ActionLink(String.Empty, \"actionName\", new Object(), null /* htmlAttributes */)) },\n                // ActionLink(string linkText, string actionName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes)\n                new { Parameter = \"linkText\", Action = new Action(() => htmlHelper.ActionLink(String.Empty, \"actionName\", new RouteValueDictionary(), new RouteValueDictionary())) },\n                // ActionLink(string linkText, string actionName, string controllerName)\n                new { Parameter = \"linkText\", Action = new Action(() => htmlHelper.ActionLink(String.Empty, \"actionName\", \"controllerName\")) },\n                // ActionLink(string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes)\n                new { Parameter = \"linkText\", Action = new Action(() => htmlHelper.ActionLink(String.Empty, \"actionName\", \"controllerName\", new Object(), null /* htmlAttributes */)) },\n                // ActionLink(string linkText, string actionName, string controllerName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes)\n                new { Parameter = \"linkText\", Action = new Action(() => htmlHelper.ActionLink(String.Empty, \"actionName\", \"controllerName\", new RouteValueDictionary(), new RouteValueDictionary())) },\n                // ActionLink(string linkText, string actionName, string controllerName, string protocol, string hostName, string fragment, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes)\n                new { Parameter = \"linkText\", Action = new Action(() => htmlHelper.ActionLink(String.Empty, \"actionName\", \"controllerName\", null, null, null, new RouteValueDictionary(), new RouteValueDictionary())) },\n                // RouteLink(string linkText, object routeValues, object htmlAttributes)\n                new { Parameter = \"linkText\", Action = new Action(() => htmlHelper.RouteLink(String.Empty, new Object(), null /* htmlAttributes */)) },\n                // RouteLink(string linkText, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes)\n                new { Parameter = \"linkText\", Action = new Action(() => htmlHelper.RouteLink(String.Empty, new RouteValueDictionary(), new RouteValueDictionary())) },\n                // RouteLink(string linkText, string routeName, object routeValues)\n                new { Parameter = \"linkText\", Action = new Action(() => htmlHelper.RouteLink(String.Empty, \"routeName\", null /* routeValues */)) },\n                // RouteLink(string linkText, string routeName, RouteValueDictionary routeValues)\n                new { Parameter = \"linkText\", Action = new Action(() => htmlHelper.RouteLink(String.Empty, \"routeName\", new RouteValueDictionary() /* routeValues */)) },\n                // RouteLink(string linkText, string routeName)\n                new { Parameter = \"linkText\", Action = new Action(() => htmlHelper.RouteLink(String.Empty, (string)null /* routeName */)) },\n                // RouteLink(string linkText, object routeValues)\n                new { Parameter = \"linkText\", Action = new Action(() => htmlHelper.RouteLink(String.Empty, (object)null /* routeValues */)) },\n                // RouteLink(string linkText, RouteValueDictionary routeValues)\n                new { Parameter = \"linkText\", Action = new Action(() => htmlHelper.RouteLink(String.Empty, new RouteValueDictionary() /* routeValues */)) },\n                // RouteLink(string linkText, string routeName, object routeValues, object htmlAttributes)\n                new { Parameter = \"linkText\", Action = new Action(() => htmlHelper.RouteLink(String.Empty, \"routeName\", new Object(), null /* htmlAttributes */)) },\n                // RouteLink(string linkText, string routeName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes)\n                new { Parameter = \"linkText\", Action = new Action(() => htmlHelper.RouteLink(String.Empty, \"routeName\", new RouteValueDictionary(), new RouteValueDictionary())) },\n                // RouteLink(string linkText, string routeName, string protocol, string hostName, string fragment, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes)\n                new { Parameter = \"linkText\", Action = new Action(() => htmlHelper.RouteLink(String.Empty, \"routeName\", null, null, null, new RouteValueDictionary(), new RouteValueDictionary())) },\n            };\n\n            // Act & Assert\n            foreach (var test in tests)\n            {\n                Assert.ThrowsArgumentNullOrEmpty(test.Action, test.Parameter);\n            }\n        }\n\n        [Fact]\n        public void RouteLinkCanUseNamedRouteWithoutSpecifyingDefaults()\n        {\n            // DevDiv 217072: Non-mvc specific helpers should not give default values for controller and action\n\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n            htmlHelper.RouteCollection.MapRoute(\"MyRouteName\", \"any/url\", new { controller = \"Charlie\" });\n\n            // Act\n            MvcHtmlString html = htmlHelper.RouteLink(\"linktext\", \"MyRouteName\", null /* routeValues */);\n\n            // Assert\n            Assert.Equal(@\"<a href=\"\"\" + AppPathModifier + @\"/app/any/url\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkWithDictionary()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.RouteLink(\"linktext\", new RouteValueDictionary(new { Action = \"newaction\", Controller = \"home2\", id = \"someid\" }), new RouteValueDictionary(new { baz = \"baz\" }));\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"baz\"\" href=\"\"\" + AppPathModifier + @\"/app/home2/newaction/someid\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkWithFragment()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.RouteLink(\"linktext\", \"namedroute\", \"http\", \"foo.bar.com\", \"foo\", new { Action = \"newaction\", Controller = \"home2\", id = \"someid\" }, new { baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"baz\"\" href=\"\"http://foo.bar.com\" + AppPathModifier + @\"/app/named/home2/newaction/someid#foo\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkWithFragmentAndAttributesWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.RouteLink(\"linktext\", \"namedroute\", \"http\", \"foo.bar.com\", \"foo\", new { Action = \"newaction\", Controller = \"home2\", id = \"someid\" }, new { foo_baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<a foo-baz=\"\"baz\"\" href=\"\"http://foo.bar.com\" + AppPathModifier + @\"/app/named/home2/newaction/someid#foo\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkWithLinkTextAndRouteName()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n            htmlHelper.RouteCollection.MapRoute(\"MyRouteName\", \"any/url\", new { controller = \"Charlie\" });\n\n            // Act\n            MvcHtmlString html = htmlHelper.RouteLink(\"linktext\", \"MyRouteName\");\n\n            // Assert\n            Assert.Equal(@\"<a href=\"\"\" + AppPathModifier + @\"/app/any/url\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkWithObjectProperties()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.RouteLink(\"linktext\", new { Action = \"newaction\", Controller = \"home2\", id = \"someid\" }, new { baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"baz\"\" href=\"\"\" + AppPathModifier + @\"/app/home2/newaction/someid\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData_NoHtmlEncode\", PropertyType = typeof(EncodedDataSets))]\n        public void RouteLinkWithObjectProperties_AttributeEncodes_AddedHtmlAttributes(\n            string text,\n            string expectedText)\n        {\n            // Arrange\n            var helper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            var result = helper.RouteLink(\"text\", routeValues: null, htmlAttributes: new { attribute = text });\n\n            // Assert\n            Assert.Equal(\n                @\"<a attribute=\"\"\" + expectedText + @\"\"\" href=\"\"\" + AppPathModifier + @\"/app/home/oldaction\"\">text</a>\",\n                result.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkWithObjectPropertiesWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.RouteLink(\"linktext\", new { Action = \"newaction\", Controller = \"home2\", id = \"someid\" }, new { foo_baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<a foo-baz=\"\"baz\"\" href=\"\"\" + AppPathModifier + @\"/app/home2/newaction/someid\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkWithProtocol()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.RouteLink(\"linktext\", \"namedroute\", \"https\", \"foo.bar.com\", null /* fragment */, new { Action = \"newaction\", Controller = \"home2\", id = \"someid\" }, new { baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"baz\"\" href=\"\"https://foo.bar.com\" + AppPathModifier + @\"/app/named/home2/newaction/someid\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkWithProtocolAndFragment()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.RouteLink(\"linktext\", \"namedroute\", \"https\", \"foo.bar.com\", \"foo\", new { Action = \"newaction\", Controller = \"home2\", id = \"someid\" }, new { baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"baz\"\" href=\"\"https://foo.bar.com\" + AppPathModifier + @\"/app/named/home2/newaction/someid#foo\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkWithRouteNameAndDefaults()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.RouteLink(\"linktext\", \"namedroute\", new { Action = \"newaction\" });\n\n            // Assert\n            Assert.Equal(@\"<a href=\"\"\" + AppPathModifier + @\"/app/named/home/newaction\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkWithRouteNameAndDictionary()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.RouteLink(\"linktext\", \"namedroute\", new RouteValueDictionary(new { Action = \"newaction\", Controller = \"home2\", id = \"someid\" }), new RouteValueDictionary());\n\n            // Assert\n            Assert.Equal(@\"<a href=\"\"\" + AppPathModifier + @\"/app/named/home2/newaction/someid\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkWithRouteNameAndObjectProperties()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.RouteLink(\"linktext\", \"namedroute\", new { Action = \"newaction\", Controller = \"home2\", id = \"someid\" }, new { baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<a baz=\"\"baz\"\" href=\"\"\" + AppPathModifier + @\"/app/named/home2/newaction/someid\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RouteLinkWithRouteNameAndObjectPropertiesWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = htmlHelper.RouteLink(\"linktext\", \"namedroute\", new { Action = \"newaction\", Controller = \"home2\", id = \"someid\" }, new { foo_baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(@\"<a foo-baz=\"\"baz\"\" href=\"\"\" + AppPathModifier + @\"/app/named/home2/newaction/someid\"\">linktext</a>\", html.ToHtmlString());\n        }\n\n        // Class for the ActionLinkProducesLowercaseUrlsAfterRegisteringAnArea test\n        private class MyAreaRegistration : AreaRegistration\n        {\n            public override string AreaName\n            {\n                get\n                {\n                    return \"MyArea\";\n                }\n            }\n\n            public override void RegisterArea(AreaRegistrationContext context)\n            {\n                context.MapRoute(\n                    \"MyArea_default\",\n                    \"MyArea/{controller}/{action}/{id}\",\n                    new { action = \"Index\", id = UrlParameter.Optional }\n                );\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Html/Test/MetadataOverrideScope.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Moq;\n\nnamespace System.Web.Mvc.Html.Test\n{\n    /// <summary>\n    /// <para>\n    /// A scope within which the <see cref=\"ModelMetadata\"/> for a single <see cref=\"Type\"/> is overridden.  Could be\n    /// used for example to ensure the metadata for <see cref=\"Exception\"/> includes an additional property or\n    /// has a non-<c>null</c> <see cref=\"ModelMetadata.DisplayName\"/>.\n    /// </para>\n    /// <para>\n    /// Notes: Does _not_ override the metadata for subclasses of the given <see cref=\"Type\"/>.  And callers should\n    /// override (likely, mock) the metadata of the containing <see cref=\"Type\"/> when changing the metadata of a\n    /// property e.g. modifying <see cref=\"ModelMetadata.IsRequired\"/>.\n    /// </para>\n    /// </summary>\n    public class MetadataOverrideScope : IDisposable\n    {\n        private static readonly DataAnnotationsModelMetadataProvider AnnotationsProvider =\n            new DataAnnotationsModelMetadataProvider();\n\n        private readonly ModelMetadataProvider _oldMetadataProvider;\n        private readonly ModelMetadata _metadata;\n        private readonly Type _modelType;\n\n        public MetadataOverrideScope(ModelMetadata metadata)\n        {\n            if (metadata == null)\n            {\n                throw new ArgumentNullException(\"metadata\");\n            }\n            if (metadata.ModelType == null)\n            {\n                throw new ArgumentException(\"Need ModelType\", \"metadata\");\n            }\n\n            _oldMetadataProvider = ModelMetadataProviders.Current;\n            _metadata = metadata;\n            _modelType = metadata.ModelType;\n\n            // Mock a ModelMetadataProvider which delegates to the old one in most cases.  No need to special-case\n            // GetMetadataForProperties() because product code uses it only within ModelMetadata.Properties and our\n            // metadata instance will call _oldMetadataProvider there.\n            var metadataProvider = new Mock<ModelMetadataProvider>();\n            metadataProvider\n                .Setup(p => p.GetMetadataForProperties(It.IsAny<object>(), It.IsAny<Type>()))\n                .Returns((object container, Type containerType) =>\n                    _oldMetadataProvider.GetMetadataForProperties(container, containerType));\n            metadataProvider\n                .Setup(p => p.GetMetadataForType(It.IsAny<Func<object>>(), It.IsAny<Type>()))\n                .Returns((Func<object> modelAccessor, Type modelType) =>\n                    _oldMetadataProvider.GetMetadataForType(modelAccessor, modelType));\n\n            // When metadata for _modelType is requested, then return a clone of the provided metadata instance.\n            // GetMetadataForProperty() is important because the static discovery methods (e.g.\n            // ModelMetadata.FromLambdaExpression) use it.\n            metadataProvider\n                .Setup(p => p.GetMetadataForType(It.IsAny<Func<object>>(), _modelType))\n                .Returns((Func<object> modelAccessor, Type modelType) => GetMetadataForType(modelAccessor, modelType));\n            metadataProvider\n                .Setup(p =>\n                    p.GetMetadataForProperty(It.IsAny<Func<object>>(), It.IsAny<Type>(), It.IsAny<string>()))\n                .Returns((Func<object> modelAccessor, Type containerType, string propertyName) =>\n                    GetMetadataForProperty(modelAccessor, containerType, propertyName));\n\n            // Calls to GetMetadataForProperties for the modelType are incorrect because _metadata.Provider must\n            // reference _oldMetadataProvider and not this mock.\n            metadataProvider\n                .Setup(p => p.GetMetadataForProperty(It.IsAny<Func<object>>(), _modelType, It.IsAny<string>()))\n                .Throws<InvalidOperationException>();\n\n            // Finally make our ModelMetadataProvider visible everywhere.\n            ModelMetadataProviders.Current = metadataProvider.Object;\n        }\n\n        public void Dispose()\n        {\n            ModelMetadataProviders.Current = _oldMetadataProvider;\n        }\n\n        private ModelMetadata GetMetadataForType(Func<object> modelAccessor, Type modelType)\n        {\n            return CloneMetadata(modelAccessor);\n        }\n\n        private ModelMetadata GetMetadataForProperty(\n            Func<object> modelAccessor,\n            Type containerType,\n            string propertyName)\n        {\n            var propertyMetadata =\n                _oldMetadataProvider.GetMetadataForProperty(modelAccessor, containerType, propertyName);\n            if (propertyMetadata == null)\n            {\n                return null;\n            }\n\n            if (propertyMetadata.ModelType == _modelType)\n            {\n                return CloneMetadata(() => propertyMetadata.Model);\n            }\n\n            return propertyMetadata;\n        }\n\n        private ModelMetadata CloneMetadata(Func<object> modelAccessor)\n        {\n            var cachedMetadata = _metadata as CachedDataAnnotationsModelMetadata;\n            var annotationsMetadata = _metadata as DataAnnotationsModelMetadata;\n            ModelMetadata clonedMetadata;\n            if (cachedMetadata != null)\n            {\n                clonedMetadata = new CachedDataAnnotationsModelMetadata(cachedMetadata, modelAccessor);\n            }\n            else if (annotationsMetadata != null)\n            {\n                var provider = (_oldMetadataProvider as DataAnnotationsModelMetadataProvider) ?? AnnotationsProvider;\n                clonedMetadata = new DataAnnotationsModelMetadata(\n                    provider,\n                    annotationsMetadata.ContainerType,\n                    modelAccessor,\n                    _modelType,\n                    annotationsMetadata.PropertyName,\n                    displayColumnAttribute: null);      // Copying SimpleDisplayText below compensates for null here.\n            }\n            else\n            {\n                clonedMetadata = new ModelMetadata(\n                    _oldMetadataProvider,\n                    _metadata.ContainerType,\n                    modelAccessor,\n                    _modelType,\n                    _metadata.PropertyName);\n            }\n\n            // Undo all the lazy-initialization of ModelMetadata and CachedDataAnnotationsModelMetadata...\n            clonedMetadata.Container = _metadata.Container;        // May be incorrect.\n            clonedMetadata.ConvertEmptyStringToNull = _metadata.ConvertEmptyStringToNull;\n            clonedMetadata.DataTypeName = _metadata.DataTypeName;\n            clonedMetadata.Description = _metadata.Description;\n            clonedMetadata.DisplayFormatString = _metadata.DisplayFormatString;\n            clonedMetadata.DisplayName = _metadata.DisplayName;\n            clonedMetadata.EditFormatString = _metadata.EditFormatString;\n            clonedMetadata.HasNonDefaultEditFormat = _metadata.HasNonDefaultEditFormat;\n            clonedMetadata.HideSurroundingHtml = _metadata.HideSurroundingHtml;\n            clonedMetadata.HtmlEncode = _metadata.HtmlEncode;\n            clonedMetadata.IsReadOnly = _metadata.IsReadOnly;\n            clonedMetadata.IsRequired = _metadata.IsRequired;\n            clonedMetadata.NullDisplayText = _metadata.NullDisplayText;\n            clonedMetadata.Order = _metadata.Order;\n            clonedMetadata.RequestValidationEnabled = _metadata.RequestValidationEnabled;\n            clonedMetadata.ShortDisplayName = _metadata.ShortDisplayName;\n            clonedMetadata.ShowForDisplay = _metadata.ShowForDisplay;\n            clonedMetadata.ShowForEdit = _metadata.ShowForEdit;\n            clonedMetadata.SimpleDisplayText = _metadata.SimpleDisplayText;\n            clonedMetadata.TemplateHint = _metadata.TemplateHint;\n            clonedMetadata.Watermark = _metadata.Watermark;\n            foreach (var keyValuePair in _metadata.AdditionalValues)\n            {\n                clonedMetadata.AdditionalValues.Add(keyValuePair.Key, keyValuePair.Value);\n            }\n\n            return clonedMetadata;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Html/Test/MvcFormTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.IO;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Html.Test\n{\n    public class MvcFormTest\n    {\n        [Fact]\n        public void ConstructorWithNullViewContextThrows()\n        {\n            Assert.ThrowsArgumentNull(\n                delegate { new MvcForm((ViewContext)null); },\n                \"viewContext\");\n        }\n\n        [Fact]\n        public void DisposeRendersCloseFormTag()\n        {\n            // Arrange\n            StringWriter writer = new StringWriter();\n            ViewContext viewContext = GetViewContext(writer);\n\n            MvcForm form = new MvcForm(viewContext);\n\n            // Act\n            form.Dispose();\n\n            // Assert\n            Assert.Equal(\"</form>\", writer.ToString());\n        }\n\n        [Fact]\n        public void EndFormRendersCloseFormTag()\n        {\n            // Arrange\n            StringWriter writer = new StringWriter();\n            ViewContext viewContext = GetViewContext(writer);\n\n            MvcForm form = new MvcForm(viewContext);\n\n            // Act\n            form.EndForm();\n\n            // Assert\n            Assert.Equal(\"</form>\", writer.ToString());\n        }\n\n        [Fact]\n        public void DisposeTwiceRendersCloseFormTagOnce()\n        {\n            // Arrange\n            StringWriter writer = new StringWriter();\n            ViewContext viewContext = GetViewContext(writer);\n\n            MvcForm form = new MvcForm(viewContext);\n\n            // Act\n            form.Dispose();\n            form.Dispose();\n\n            // Assert\n            Assert.Equal(\"</form>\", writer.ToString());\n        }\n\n        [Fact]\n        public void EndFormTwiceRendersCloseFormTagOnce()\n        {\n            // Arrange\n            StringWriter writer = new StringWriter();\n            ViewContext viewContext = GetViewContext(writer);\n\n            MvcForm form = new MvcForm(viewContext);\n\n            // Act\n            form.EndForm();\n            form.EndForm();\n\n            // Assert\n            Assert.Equal(\"</form>\", writer.ToString());\n        }\n\n        private static ViewContext GetViewContext(TextWriter writer)\n        {\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(o => o.Items).Returns(new Hashtable());\n\n            return new ViewContext()\n            {\n                HttpContext = mockHttpContext.Object,\n                Writer = writer\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Html/Test/NameExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace System.Web.Mvc.Html.Test\n{\n    public class NameExtensionsTest\n    {\n        [Fact]\n        public void NonStronglyTypedWithNoPrefix()\n        {\n            // Arrange\n            HtmlHelper html = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n\n            // Act & Assert\n            Assert.Equal(\"\", html.IdForModel().ToHtmlString());\n            Assert.Equal(\"foo\", html.Id(\"foo\").ToHtmlString());\n            Assert.Equal(\"foo_bar\", html.Id(\"foo.bar\").ToHtmlString());\n            Assert.Equal(String.Empty, html.Id(\"<script>alert(\\\"XSS!\\\")</script>\").ToHtmlString());\n\n            Assert.Equal(\"\", html.NameForModel().ToHtmlString());\n            Assert.Equal(\"foo\", html.Name(\"foo\").ToHtmlString());\n            Assert.Equal(\"foo.bar\", html.Name(\"foo.bar\").ToHtmlString());\n            Assert.Equal(\"&lt;script>alert(&quot;XSS!&quot;)&lt;/script>\", html.Name(\"<script>alert(\\\"XSS!\\\")</script>\").ToHtmlString());\n        }\n\n        [Fact]\n        public void NonStronglyTypedWithPrefix()\n        {\n            // Arrange\n            HtmlHelper html = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            html.ViewData.TemplateInfo.HtmlFieldPrefix = \"prefix\";\n\n            // Act & Assert\n            Assert.Equal(\"prefix\", html.IdForModel().ToHtmlString());\n            Assert.Equal(\"prefix_foo\", html.Id(\"foo\").ToHtmlString());\n            Assert.Equal(\"prefix_foo_bar\", html.Id(\"foo.bar\").ToHtmlString());\n\n            Assert.Equal(\"prefix\", html.NameForModel().ToHtmlString());\n            Assert.Equal(\"prefix.foo\", html.Name(\"foo\").ToHtmlString());\n            Assert.Equal(\"prefix.foo.bar\", html.Name(\"foo.bar\").ToHtmlString());\n        }\n\n        [Fact]\n        public void StronglyTypedWithNoPrefix()\n        {\n            // Arrange\n            HtmlHelper<OuterClass> html = MvcHelper.GetHtmlHelper(new ViewDataDictionary<OuterClass>());\n\n            // Act & Assert\n            Assert.Equal(\"IntValue\", html.IdFor(m => m.IntValue).ToHtmlString());\n            Assert.Equal(\"Inner_StringValue\", html.IdFor(m => m.Inner.StringValue).ToHtmlString());\n\n            Assert.Equal(\"IntValue\", html.NameFor(m => m.IntValue).ToHtmlString());\n            Assert.Equal(\"Inner.StringValue\", html.NameFor(m => m.Inner.StringValue).ToHtmlString());\n        }\n\n        [Fact]\n        public void StronglyTypedWithPrefix()\n        {\n            // Arrange\n            HtmlHelper<OuterClass> html = MvcHelper.GetHtmlHelper(new ViewDataDictionary<OuterClass>());\n            html.ViewData.TemplateInfo.HtmlFieldPrefix = \"prefix\";\n\n            // Act & Assert\n            Assert.Equal(\"prefix_IntValue\", html.IdFor(m => m.IntValue).ToHtmlString());\n            Assert.Equal(\"prefix_Inner_StringValue\", html.IdFor(m => m.Inner.StringValue).ToHtmlString());\n\n            Assert.Equal(\"prefix.IntValue\", html.NameFor(m => m.IntValue).ToHtmlString());\n            Assert.Equal(\"prefix.Inner.StringValue\", html.NameFor(m => m.Inner.StringValue).ToHtmlString());\n        }\n\n        // Regression test for codeplex #554 - editor templates for collections would add an extra dot to the\n        // generated name.\n        [Fact]\n        public void StronglyTypedCollectionWithPrefix()\n        {\n            // Arrange\n            HtmlHelper<List<OuterClass>> html = MvcHelper.GetHtmlHelper(new ViewDataDictionary<List<OuterClass>>());\n            html.ViewData.TemplateInfo.HtmlFieldPrefix = \"prefix\";\n\n            // Act & Assert\n            Assert.Equal(\"prefix_0__IntValue\", html.IdFor(m => m[0].IntValue).ToHtmlString());\n            Assert.Equal(\"prefix_0__Inner_StringValue\", html.IdFor(m => m[0].Inner.StringValue).ToHtmlString());\n\n            Assert.Equal(\"prefix[0].IntValue\", html.NameFor(m => m[0].IntValue).ToHtmlString());\n            Assert.Equal(\"prefix[0].Inner.StringValue\", html.NameFor(m => m[0].Inner.StringValue).ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"IdEncodedData_NoHtmlEncode\", PropertyType = typeof(EncodedDataSets))]\n        public void Id_IdEncodes_PropertyName(string text, string expectedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            var helper = MvcHelper.GetHtmlHelper<string>(viewData);\n\n            // Act\n            var result = helper.Id(text);\n\n            // Assert\n            Assert.Equal(expectedText, result.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"IdEncodedData_NoHtmlEncode\", PropertyType = typeof(EncodedDataSets))]\n        public void IdHelpers_IdEncode_Prefix(string text, string expectedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.TemplateInfo.HtmlFieldPrefix = text;\n            var helper = MvcHelper.GetHtmlHelper<string>(viewData);\n\n            // Act\n            var idResult = helper.Id(\"\");\n            var idForResult = helper.IdFor(m => m);\n            var idForModelResult = helper.IdForModel();\n\n\n            // Assert\n            Assert.Equal(expectedText, idResult.ToHtmlString());\n            Assert.Equal(expectedText, idForResult.ToHtmlString());\n            Assert.Equal(expectedText, idForModelResult.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData_NoHtmlEncode\", PropertyType = typeof(EncodedDataSets))]\n        public void Name_AttributeEncodes_PropertyName(string text, string expectedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            var helper = MvcHelper.GetHtmlHelper<string>(viewData);\n\n            // Act\n            var result = helper.Name(text);\n\n            // Assert\n            Assert.Equal(expectedText, result.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData_NoHtmlEncode\", PropertyType = typeof(EncodedDataSets))]\n        public void NameHelpers_AttributeEncode_Prefix(string text, string expectedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.TemplateInfo.HtmlFieldPrefix = text;\n            var helper = MvcHelper.GetHtmlHelper<string>(viewData);\n\n            // Act\n            var nameResult = helper.Name(\"\");\n            var nameForResult = helper.NameFor(m => m);\n            var nameForModelResult = helper.NameForModel();\n\n\n            // Assert\n            Assert.Equal(expectedText, nameResult.ToHtmlString());\n            Assert.Equal(expectedText, nameForResult.ToHtmlString());\n            Assert.Equal(expectedText, nameForModelResult.ToHtmlString());\n        }\n\n        private sealed class OuterClass\n        {\n            public InnerClass Inner { get; set; }\n            public int IntValue { get; set; }\n        }\n\n        private sealed class InnerClass\n        {\n            public string StringValue { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Html/Test/PartialExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Html.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")]\n    public class PartialExtensionsTest\n    {\n        [Fact]\n        public void PartialWithViewName()\n        {\n            // Arrange\n            RenderPartialExtensionsTest.SpyHtmlHelper helper = RenderPartialExtensionsTest.SpyHtmlHelper.Create();\n\n            // Act\n            MvcHtmlString result = helper.Partial(\"partial-view\");\n\n            // Assert\n            Assert.Equal(\"partial-view\", helper.RenderPartialInternal_PartialViewName);\n            Assert.Same(helper.ViewData, helper.RenderPartialInternal_ViewData);\n            Assert.Null(helper.RenderPartialInternal_Model);\n            Assert.IsType<StringWriter>(helper.RenderPartialInternal_Writer);\n            Assert.Same(ViewEngines.Engines, helper.RenderPartialInternal_ViewEngineCollection);\n            Assert.Equal(\"This is the result of the view\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void PartialWithViewNameAndViewData()\n        {\n            // Arrange\n            RenderPartialExtensionsTest.SpyHtmlHelper helper = RenderPartialExtensionsTest.SpyHtmlHelper.Create();\n            ViewDataDictionary viewData = new ViewDataDictionary();\n\n            // Act\n            MvcHtmlString result = helper.Partial(\"partial-view\", viewData);\n\n            // Assert\n            Assert.Equal(\"partial-view\", helper.RenderPartialInternal_PartialViewName);\n            Assert.Same(viewData, helper.RenderPartialInternal_ViewData);\n            Assert.Null(helper.RenderPartialInternal_Model);\n            Assert.IsType<StringWriter>(helper.RenderPartialInternal_Writer);\n            Assert.Same(ViewEngines.Engines, helper.RenderPartialInternal_ViewEngineCollection);\n            Assert.Equal(\"This is the result of the view\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void PartialWithViewNameAndModel()\n        {\n            // Arrange\n            RenderPartialExtensionsTest.SpyHtmlHelper helper = RenderPartialExtensionsTest.SpyHtmlHelper.Create();\n            object model = new object();\n\n            // Act\n            MvcHtmlString result = helper.Partial(\"partial-view\", model);\n\n            // Assert\n            Assert.Equal(\"partial-view\", helper.RenderPartialInternal_PartialViewName);\n            Assert.Same(helper.ViewData, helper.RenderPartialInternal_ViewData);\n            Assert.Same(model, helper.RenderPartialInternal_Model);\n            Assert.IsType<StringWriter>(helper.RenderPartialInternal_Writer);\n            Assert.Same(ViewEngines.Engines, helper.RenderPartialInternal_ViewEngineCollection);\n            Assert.Equal(\"This is the result of the view\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void PartialWithViewNameAndModelAndViewData()\n        {\n            // Arrange\n            RenderPartialExtensionsTest.SpyHtmlHelper helper = RenderPartialExtensionsTest.SpyHtmlHelper.Create();\n            object model = new object();\n            ViewDataDictionary viewData = new ViewDataDictionary();\n\n            // Act\n            MvcHtmlString result = helper.Partial(\"partial-view\", model, viewData);\n\n            // Assert\n            Assert.Equal(\"partial-view\", helper.RenderPartialInternal_PartialViewName);\n            Assert.Same(viewData, helper.RenderPartialInternal_ViewData);\n            Assert.Same(model, helper.RenderPartialInternal_Model);\n            Assert.IsType<StringWriter>(helper.RenderPartialInternal_Writer);\n            Assert.Same(ViewEngines.Engines, helper.RenderPartialInternal_ViewEngineCollection);\n            Assert.Equal(\"This is the result of the view\", result.ToHtmlString());\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Html/Test/RenderPartialExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Html.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")]\n    public class RenderPartialExtensionsTest\n    {\n        [Fact]\n        public void RenderPartialWithViewName()\n        {\n            // Arrange\n            SpyHtmlHelper helper = SpyHtmlHelper.Create();\n\n            // Act\n            helper.RenderPartial(\"partial-view\");\n\n            // Assert\n            Assert.Equal(\"partial-view\", helper.RenderPartialInternal_PartialViewName);\n            Assert.Same(helper.ViewData, helper.RenderPartialInternal_ViewData);\n            Assert.Null(helper.RenderPartialInternal_Model);\n            Assert.Same(helper.ViewContext.Writer, helper.RenderPartialInternal_Writer);\n            Assert.Same(ViewEngines.Engines, helper.RenderPartialInternal_ViewEngineCollection);\n        }\n\n        [Fact]\n        public void RenderPartialWithViewNameAndViewData()\n        {\n            // Arrange\n            SpyHtmlHelper helper = SpyHtmlHelper.Create();\n            ViewDataDictionary viewData = new ViewDataDictionary();\n\n            // Act\n            helper.RenderPartial(\"partial-view\", viewData);\n\n            // Assert\n            Assert.Equal(\"partial-view\", helper.RenderPartialInternal_PartialViewName);\n            Assert.Same(viewData, helper.RenderPartialInternal_ViewData);\n            Assert.Null(helper.RenderPartialInternal_Model);\n            Assert.Same(helper.ViewContext.Writer, helper.RenderPartialInternal_Writer);\n            Assert.Same(ViewEngines.Engines, helper.RenderPartialInternal_ViewEngineCollection);\n        }\n\n        [Fact]\n        public void RenderPartialWithViewNameAndModel()\n        {\n            // Arrange\n            SpyHtmlHelper helper = SpyHtmlHelper.Create();\n            object model = new object();\n\n            // Act\n            helper.RenderPartial(\"partial-view\", model);\n\n            // Assert\n            Assert.Equal(\"partial-view\", helper.RenderPartialInternal_PartialViewName);\n            Assert.Same(helper.ViewData, helper.RenderPartialInternal_ViewData);\n            Assert.Same(model, helper.RenderPartialInternal_Model);\n            Assert.Same(helper.ViewContext.Writer, helper.RenderPartialInternal_Writer);\n            Assert.Same(ViewEngines.Engines, helper.RenderPartialInternal_ViewEngineCollection);\n        }\n\n        [Fact]\n        public void RenderPartialWithViewNameAndModelAndViewData()\n        {\n            // Arrange\n            SpyHtmlHelper helper = SpyHtmlHelper.Create();\n            object model = new object();\n            ViewDataDictionary viewData = new ViewDataDictionary();\n\n            // Act\n            helper.RenderPartial(\"partial-view\", model, viewData);\n\n            // Assert\n            Assert.Equal(\"partial-view\", helper.RenderPartialInternal_PartialViewName);\n            Assert.Same(viewData, helper.RenderPartialInternal_ViewData);\n            Assert.Same(model, helper.RenderPartialInternal_Model);\n            Assert.Same(helper.ViewContext.Writer, helper.RenderPartialInternal_Writer);\n            Assert.Same(ViewEngines.Engines, helper.RenderPartialInternal_ViewEngineCollection);\n        }\n\n        internal class SpyHtmlHelper : HtmlHelper\n        {\n            public string RenderPartialInternal_PartialViewName;\n            public ViewDataDictionary RenderPartialInternal_ViewData;\n            public object RenderPartialInternal_Model;\n            public TextWriter RenderPartialInternal_Writer;\n            public ViewEngineCollection RenderPartialInternal_ViewEngineCollection;\n\n            SpyHtmlHelper(ViewContext viewContext, IViewDataContainer viewDataContainer)\n                : base(viewContext, viewDataContainer)\n            {\n            }\n\n            public static SpyHtmlHelper Create()\n            {\n                ViewDataDictionary viewData = new ViewDataDictionary();\n\n                Mock<ViewContext> mockViewContext = new Mock<ViewContext>();\n                mockViewContext.Setup(c => c.HttpContext.Response.Output).Throws(new Exception(\"Response.Output should never be called.\"));\n                mockViewContext.Setup(c => c.ViewData).Returns(viewData);\n                mockViewContext.Setup(c => c.Writer).Returns(new StringWriter());\n\n                Mock<IViewDataContainer> container = new Mock<IViewDataContainer>();\n                container.Setup(c => c.ViewData).Returns(viewData);\n\n                return new SpyHtmlHelper(mockViewContext.Object, container.Object);\n            }\n\n            internal override void RenderPartialInternal(string partialViewName, ViewDataDictionary viewData, object model,\n                                                         TextWriter writer, ViewEngineCollection viewEngineCollection)\n            {\n                RenderPartialInternal_PartialViewName = partialViewName;\n                RenderPartialInternal_ViewData = viewData;\n                RenderPartialInternal_Model = model;\n                RenderPartialInternal_Writer = writer;\n                RenderPartialInternal_ViewEngineCollection = viewEngineCollection;\n\n                writer.Write(\"This is the result of the view\");\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Html/Test/SelectExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Globalization;\nusing System.Linq;\nusing System.Reflection;\nusing System.Web.Mvc.Test;\nusing System.Web.WebPages.Scope;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace System.Web.Mvc.Html.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")]\n    public class SelectExtensionsTest : IDisposable\n    {\n        private static readonly ViewDataDictionary<FooModel> _listBoxViewData = new ViewDataDictionary<FooModel> { { \"foo\", new[] { \"Bravo\" } } };\n        private static readonly ViewDataDictionary<FooModel> _dropDownListViewData = new ViewDataDictionary<FooModel> { { \"foo\", \"Bravo\" } };\n        private static readonly ViewDataDictionary<FooContainerModel> _nestedDropDownListViewData = new ViewDataDictionary<FooContainerModel> { { \"foo\", \"Bravo\" } };\n        private static readonly ViewDataDictionary<NonIEnumerableModel> _nonIEnumerableViewData = new ViewDataDictionary<NonIEnumerableModel> { { \"foo\", 1 } };\n        private static readonly ViewDataDictionary<EnumModel> _enumDropDownListViewData = new ViewDataDictionary<EnumModel>\n        {\n            { \"WithDisplay\", EnumWithDisplay.Two },\n            { \"WithDuplicates\", EnumWithDuplicates.Second },\n            { \"WithFlags\", EnumWithFlags.Second },\n        };\n        private static readonly SelectList _selectList = new SelectList(\n            new[]\n            {\n                new { Text = \"UFO\", Value = \"ufo\", Category = \"\" }, /* Empty Group */\n                new { Text = \"Volvo\", Value = \"volvo\", Category = \"Swedish Cars\" },\n                new { Text = \"Mercedes-Benz\", Value = \"mercedes-benz\", Category = \"German Cars\" },\n                new { Text = \"Saab\", Value = \"saab\", Category = \"Swedish Cars\" },\n                new { Text = \"Audi\", Value = \"audi\", Category = \"German Cars\" },\n                new { Text = \"Other\", Value = \"other\", Category = (string) null }, /* Another Empty Group */\n                new { Text = \"Unknown\", Value = \"unknown\", Category = \" \" } /* Unnamed Group */\n            }, \"Value\", \"Text\", \"Category\", (object) \"audi\");\n        private static readonly MultiSelectList _multiSelectList = new MultiSelectList(\n            new[]\n            {\n                new { Text = \"UFO\", Value = \"ufo\", Category = \"\" }, /* Empty Group */\n                new { Text = \"Volvo\", Value = \"volvo\", Category = \"Swedish Cars\" },\n                new { Text = \"Mercedes-Benz\", Value = \"mercedes-benz\", Category = \"German Cars\" },\n                new { Text = \"Saab\", Value = \"saab\", Category = \"Swedish Cars\" },\n                new { Text = \"Audi\", Value = \"audi\", Category = \"German Cars\" },\n                new { Text = \"Other\", Value = \"other\", Category = (string) null }, /* Another Empty Group */\n                new { Text = \"Unknown\", Value = \"unknown\", Category = \" \" } /* Unnamed Group */\n            }, \"Value\", \"Text\", \"Category\", new[] { \"audi\", \"volvo\" });\n\n        private static ViewDataDictionary GetViewDataWithSelectList()\n        {\n            ViewDataDictionary viewData = new ViewDataDictionary();\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleAnonymousObjects(), \"Letter\", \"FullWord\", \"C\");\n            viewData[\"foo\"] = selectList;\n            viewData[\"foo.bar\"] = selectList;\n            return viewData;\n        }\n\n        private static List<SelectListItem> GroupedItems_WithDisabled\n        {\n            get\n            {\n                List<SelectListItem> items = new List<SelectListItem>();\n                SelectListGroup disabledGroup = new SelectListGroup { Disabled = true, Name = \"DisabledGroup\" };\n                items.Add(new SelectListItem() { Text = \"Alice\", Value = \"a\" });\n                items.Add(new SelectListItem() { Text = \"Bob\", Value = \"b\", Group = disabledGroup });\n                items.Add(new SelectListItem() { Text = \"Charlie\", Value = \"c\", Group = disabledGroup });\n                items.Add(new SelectListItem() { Text = \"David\", Value = \"d\", Disabled = true });\n\n                return items;\n            }\n        }\n\n        // DropDownList\n\n        private static List<SelectListItem> GroupedItems\n        {\n            get\n            {\n                List<SelectListItem> items = new List<SelectListItem>();\n                SelectListGroup swedish = new SelectListGroup { Name = \"Swedish Cars\" };\n                SelectListGroup german = new SelectListGroup { Name = \"German Cars\" };\n                SelectListGroup unnamed = new SelectListGroup();\n                items.Add(new SelectListItem() { Text = \"other1\", Value = \"other1\" });\n                items.Add(new SelectListItem() { Text = \"other2\", Value = \"other2\" });\n                items.Add(new SelectListItem() { Group = swedish, Text = \"Volvo\", Value = \"volvo\" });\n                items.Add(new SelectListItem() { Text = \"other3\", Value = \"other3\" });\n                items.Add(new SelectListItem() { Group = unnamed, Text = \"other4\", Value = \"other4\" });\n                items.Add(new SelectListItem() { Group = unnamed, Text = \"other5\", Value = \"other5\" });\n                items.Add(new SelectListItem() { Group = german, Text = \"Mercedes-Benz\", Value = \"mercedes-benz\" });\n                items.Add(new SelectListItem() { Group = swedish, Text = \"Saab\", Value = \"saab\", Selected = true });\n                items.Add(new SelectListItem() { Group = german, Text = \"Audi\", Value = \"audi\", Disabled = true });\n                items.Add(new SelectListItem() { Text = \"other6\", Value = \"other6\" });\n\n                return items;\n            }\n        }\n\n        [Fact]\n        void DropDownList_WithGroups()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n            const string expectedDropDownListHtml = @\"<select id=\"\"List\"\" name=\"\"List\"\"><option value=\"\"other1\"\">other1</option>\n<option value=\"\"other2\"\">other2</option>\n<optgroup label=\"\"Swedish Cars\"\">\n<option value=\"\"volvo\"\">Volvo</option>\n<option selected=\"\"selected\"\" value=\"\"saab\"\">Saab</option>\n</optgroup>\n<option value=\"\"other3\"\">other3</option>\n<optgroup>\n<option value=\"\"other4\"\">other4</option>\n<option value=\"\"other5\"\">other5</option>\n</optgroup>\n<optgroup label=\"\"German Cars\"\">\n<option value=\"\"mercedes-benz\"\">Mercedes-Benz</option>\n<option disabled=\"\"disabled\"\" value=\"\"audi\"\">Audi</option>\n</optgroup>\n<option value=\"\"other6\"\">other6</option>\n</select>\";\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"List\", GroupedItems);\n\n            // Assert\n            Assert.Equal(expectedDropDownListHtml, html.ToHtmlString());\n        }\n\n        [Fact]\n        void DropDownList_WithGroups_WithDisabled()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n            const string expectedDropDownListHtml = @\"<select id=\"\"List\"\" name=\"\"List\"\"><option value=\"\"a\"\">Alice</option>\n<optgroup disabled=\"\"disabled\"\" label=\"\"DisabledGroup\"\">\n<option value=\"\"b\"\">Bob</option>\n<option value=\"\"c\"\">Charlie</option>\n</optgroup>\n<option disabled=\"\"disabled\"\" value=\"\"d\"\">David</option>\n</select>\";\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"List\", GroupedItems_WithDisabled);\n\n            // Assert\n            Assert.Equal(expectedDropDownListHtml, html.ToHtmlString());\n        }\n\n\n        [Fact]\n        void DropDownList_SelectList_WithGroups()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n            const string expectedDropDownListHtml = @\"<select id=\"\"List\"\" name=\"\"List\"\"><option value=\"\"ufo\"\">UFO</option>\n<optgroup label=\"\"Swedish Cars\"\">\n<option value=\"\"volvo\"\">Volvo</option>\n<option value=\"\"saab\"\">Saab</option>\n</optgroup>\n<optgroup label=\"\"German Cars\"\">\n<option value=\"\"mercedes-benz\"\">Mercedes-Benz</option>\n<option selected=\"\"selected\"\" value=\"\"audi\"\">Audi</option>\n</optgroup>\n<option value=\"\"other\"\">Other</option>\n<optgroup label=\"\" \"\">\n<option value=\"\"unknown\"\">Unknown</option>\n</optgroup>\n</select>\";\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"List\", _selectList);\n\n            // Assert\n            Assert.Equal(expectedDropDownListHtml, html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListUsesExplicitValueIfNotProvidedInViewData()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleAnonymousObjects(), \"Letter\", \"FullWord\", \"C\");\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"foo\", selectList, (string)null /* optionLabel */);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" name=\\\"foo\\\"><option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListUsesExplicitValueIfNotProvidedInViewData_Unobtrusive()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            helper.ViewContext.ClientValidationEnabled = true;\n            helper.ViewContext.UnobtrusiveJavaScriptEnabled = true;\n            helper.ViewContext.FormContext = new FormContext();\n            helper.ClientValidationRuleFactory = (name, metadata) => new[] { new ModelClientValidationRule { ValidationType = \"type\", ErrorMessage = \"error\" } };\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleAnonymousObjects(), \"Letter\", \"FullWord\", \"C\");\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"foo\", selectList, (string)null /* optionLabel */);\n\n            // Assert\n            Assert.Equal(\n                \"<select data-val=\\\"true\\\" data-val-type=\\\"error\\\" id=\\\"foo\\\" name=\\\"foo\\\"><option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListUsesViewDataDefaultValue()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(_dropDownListViewData);\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings(), \"Charlie\");\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"foo\", selectList, (string)null /* optionLabel */);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListUsesViewDataDefaultValueNoOptionLabel()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(_dropDownListViewData);\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings(), \"Charlie\");\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"foo\", selectList);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListWithAttributesDictionary()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings());\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"foo\", selectList, null /* optionLabel */, HtmlHelperTest.AttributesDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazValue\\\" id=\\\"foo\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListWithEmptyNameThrows()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { helper.DropDownList(String.Empty, (SelectList)null /* selectList */, (string)null /* optionLabel */); },\n                \"name\");\n        }\n\n        [Fact]\n        public void DropDownListWithErrors()\n        {\n            // Arrange\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings(), new[] { \"Charlie\" });\n            ViewDataDictionary viewData = GetViewDataWithErrors();\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"foo\", selectList, null /* optionLabel */, HtmlHelperTest.AttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazObjValue\\\" class=\\\"input-validation-error\\\" id=\\\"foo\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListWithErrorsAndCustomClass()\n        {\n            // Arrange\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings());\n            ViewDataDictionary viewData = GetViewDataWithErrors();\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"foo\", selectList, null /* optionLabel */, new { @class = \"foo-class\" });\n\n            // Assert\n            Assert.Equal(\n                \"<select class=\\\"input-validation-error foo-class\\\" id=\\\"foo\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListWithNullNameThrows()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { helper.DropDownList(null /* name */, (SelectList)null /* selectList */, (string)null /* optionLabel */); },\n                \"name\");\n        }\n\n        [Fact]\n        public void DropDownListWithNullSelectListUsesViewData()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n            helper.ViewData[\"foo\"] = new MultiSelectList(MultiSelectListTest.GetSampleStrings(), new[] { \"Charlie\" });\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"foo\");\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListWithObjectDictionary()\n        {\n            // Arrange\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings());\n            ViewDataDictionary viewData = new ViewDataDictionary();\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"foo\", selectList, null /* optionLabel */, HtmlHelperTest.AttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazObjValue\\\" id=\\\"foo\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListWithObjectDictionaryWithUnderscores()\n        {\n            // Arrange\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings());\n            ViewDataDictionary viewData = new ViewDataDictionary();\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"foo\", selectList, null /* optionLabel */, HtmlHelperTest.AttributesObjectUnderscoresDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select foo-baz=\\\"BazObjValue\\\" id=\\\"foo\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListWithObjectDictionaryAndSelectList()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings());\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"foo\", selectList, null /* optionLabel */, HtmlHelperTest.AttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazObjValue\\\" id=\\\"foo\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListWithObjectDictionaryAndSelectListNoOptionLabel()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings());\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"foo\", selectList, HtmlHelperTest.AttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazObjValue\\\" id=\\\"foo\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListWithObjectDictionaryWithUnderscoresAndSelectListNoOptionLabel()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings());\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"foo\", selectList, HtmlHelperTest.AttributesObjectUnderscoresDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select foo-baz=\\\"BazObjValue\\\" id=\\\"foo\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListWithObjectDictionaryAndEmptyOptionLabel()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings());\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"foo\", selectList, String.Empty /* optionLabel */, HtmlHelperTest.AttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazObjValue\\\" id=\\\"foo\\\" name=\\\"foo\\\"><option value=\\\"\\\"></option>\" + Environment.NewLine\n              + \"<option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListWithObjectDictionaryAndTitle()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings());\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"foo\", selectList, \"[Select Something]\", HtmlHelperTest.AttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazObjValue\\\" id=\\\"foo\\\" name=\\\"foo\\\"><option value=\\\"\\\">[Select Something]</option>\" + Environment.NewLine\n              + \"<option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListUsesViewDataSelectList()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetViewDataWithSelectList());\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"foo\", (string)null /* optionLabel */);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" name=\\\"foo\\\"><option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListUsesModelState()\n        {\n            // Arrange\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings());\n            ViewDataDictionary viewData = GetViewDataWithErrors();\n            viewData[\"foo\"] = selectList;\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"foo\");\n\n            // Assert\n            Assert.Equal(\n                \"<select class=\\\"input-validation-error\\\" id=\\\"foo\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListUsesViewDataSelectListNoOptionLabel()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetViewDataWithSelectList());\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"foo\");\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" name=\\\"foo\\\"><option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListWithDotReplacementForId()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetViewDataWithSelectList());\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"foo.bar\");\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo_bar\\\" name=\\\"foo.bar\\\"><option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListWithIEnumerableSelectListItem()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary { { \"foo\", MultiSelectListTest.GetSampleIEnumerableObjects() } };\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(vdd);\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"foo\");\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" name=\\\"foo\\\"><option value=\\\"123456789\\\">John</option>\" + Environment.NewLine\n              + \"<option value=\\\"987654321\\\">Jane</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"111111111\\\">Joe</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListWithIEnumerableSelectListItemSelectsDefaultFromViewData()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary { { \"foo\", \"123456789\" } };\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(vdd);\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"foo\", MultiSelectListTest.GetSampleIEnumerableObjects());\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" name=\\\"foo\\\"><option selected=\\\"selected\\\" value=\\\"123456789\\\">John</option>\" + Environment.NewLine\n              + \"<option value=\\\"987654321\\\">Jane</option>\" + Environment.NewLine\n              + \"<option value=\\\"111111111\\\">Joe</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListWithIEnumerableOfSelectListItemMatchesEnumName()\n        {\n            // Arrange\n            ViewDataDictionary<EnumWithDisplay> vdd = new ViewDataDictionary<EnumWithDisplay>\n            {\n                { \"foo\", EnumWithDisplay.Three }\n            };\n            HtmlHelper<EnumWithDisplay> helper = MvcHelper.GetHtmlHelper(vdd);\n\n            // Act\n            MvcHtmlString html =\n                helper.DropDownList(\"foo\", GetSelectListWithNamedValuesForEnumWithDisplay(includeEmpty: false));\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" name=\\\"foo\\\">\" +\n                \"<option value=\\\"Zero\\\">Zero</option>\" + Environment.NewLine +\n                \"<option value=\\\"One\\\">One</option>\" + Environment.NewLine +\n                \"<option value=\\\"Two\\\">Two</option>\" + Environment.NewLine +\n                \"<option selected=\\\"selected\\\" value=\\\"Three\\\">Three</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListWithIEnumerableOfSelectListItemMatchesEnumValue()\n        {\n            // Arrange\n            ViewDataDictionary<EnumWithDisplay> vdd = new ViewDataDictionary<EnumWithDisplay>\n            {\n                { \"foo\", EnumWithDisplay.Three }\n            };\n            HtmlHelper<EnumWithDisplay> helper = MvcHelper.GetHtmlHelper(vdd);\n\n            // Act\n            MvcHtmlString html =\n                helper.DropDownList(\"foo\", GetSelectListWithNumericValuesForEnumWithDisplay(includeEmpty: false));\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" name=\\\"foo\\\">\" +\n                \"<option value=\\\"0\\\">Zero</option>\" + Environment.NewLine +\n                \"<option value=\\\"1\\\">One</option>\" + Environment.NewLine +\n                \"<option value=\\\"2\\\">Two</option>\" + Environment.NewLine +\n                \"<option selected=\\\"selected\\\" value=\\\"3\\\">Three</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListWithListOfSelectListItemSelectsDefaultFromViewData()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary { { \"foo\", \"123456789\" } };\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(vdd);\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"foo\", MultiSelectListTest.GetSampleListObjects());\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" name=\\\"foo\\\"><option selected=\\\"selected\\\" value=\\\"123456789\\\">John</option>\" + Environment.NewLine\n              + \"<option value=\\\"987654321\\\">Jane</option>\" + Environment.NewLine\n              + \"<option value=\\\"111111111\\\">Joe</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListWithListOfSelectListItem()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary { { \"foo\", MultiSelectListTest.GetSampleListObjects() } };\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(vdd);\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"foo\");\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" name=\\\"foo\\\"><option value=\\\"123456789\\\">John</option>\" + Environment.NewLine\n              + \"<option value=\\\"987654321\\\">Jane</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"111111111\\\">Joe</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListWithNullViewDataValueThrows()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n\n            // Act\n            Assert.Throws<InvalidOperationException>(\n                delegate { helper.DropDownList(\"foo\", (string)null /* optionLabel */); },\n                \"There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'foo'.\");\n        }\n\n        [Fact]\n        public void DropDownListWithWrongViewDataTypeValueThrows()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary { { \"foo\", 123 } });\n\n            // Act\n            Assert.Throws<InvalidOperationException>(\n                delegate { helper.DropDownList(\"foo\", (string)null /* optionLabel */); },\n                \"The ViewData item that has the key 'foo' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.\");\n        }\n\n        [Fact]\n        public void DropDownListWithPrefix()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings());\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"foo\", selectList, HtmlHelperTest.AttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazObjValue\\\" id=\\\"MyPrefix_foo\\\" name=\\\"MyPrefix.foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListWithPrefixAndEmptyName()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings());\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"\", selectList, HtmlHelperTest.AttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazObjValue\\\" id=\\\"MyPrefix\\\" name=\\\"MyPrefix\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListWithPrefixAndNullSelectListUsesViewData()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n            helper.ViewData[\"foo\"] = new MultiSelectList(MultiSelectListTest.GetSampleStrings(), new[] { \"Charlie\" });\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.DropDownList(\"foo\");\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"MyPrefix_foo\\\" name=\\\"MyPrefix.foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData_NoHtmlEncode\", PropertyType = typeof(EncodedDataSets))]\n        public void DropDownList_AttributeEncodes_AddedHtmlAttributes(string text, string encodedText)\n        {\n            // Arrange\n            var selectList = new List<SelectListItem>\n            {\n                new SelectListItem { Text = \"text\", },\n            };\n            var helper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            var result =\n                helper.DropDownList(name: \"name\", selectList: selectList, htmlAttributes: new { attribute = text, })\n                .ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<select attribute=\\\"\" +\n                    encodedText +\n                    \"\\\" id=\\\"name\\\" name=\\\"name\\\"><option>text</option>\" +\n                    Environment.NewLine +\n                    \"</select>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData_NoHtmlEncode\", PropertyType = typeof(EncodedDataSets))]\n        public void DropDownList_AttributeEncodes_Name(string text, string encodedText)\n        {\n            // Arrange\n            var selectList = new List<SelectListItem>\n            {\n                new SelectListItem { Text = \"text\", },\n            };\n            var helper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            // htmlAttributes included only to avoid special-cased renaming done for id attribute.\n            var result =\n                helper.DropDownList(name: text, selectList: selectList, htmlAttributes: new { id = \"id\", })\n                .ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"id\\\" name=\\\"\" +\n                    encodedText +\n                    \"\\\"><option>text</option>\" +\n                    Environment.NewLine +\n                    \"</select>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData_NoHtmlEncode\", PropertyType = typeof(EncodedDataSets))]\n        public void DropDownList_AttributeEncodes_OptGroupLabel(string text, string encodedText)\n        {\n            // Arrange\n            var selectList = new List<SelectListItem>\n            {\n                new SelectListItem { Group = new SelectListGroup { Name = text, }, Text = \"text\", },\n            };\n            var helper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            var result = helper.DropDownList(name: \"name\", selectList: selectList).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"name\\\" name=\\\"name\\\"><optgroup label=\\\"\" +\n                    encodedText +\n                    \"\\\">\" +\n                    Environment.NewLine +\n                    \"<option>text</option>\" +\n                    Environment.NewLine +\n                    \"</optgroup>\" +\n                    Environment.NewLine +\n                    \"</select>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"HtmlEncodedData_NoHtmlEncode\", PropertyType = typeof(EncodedDataSets))]\n        public void DropDownList_HtmlEncodes_OptionLabel(string text, string encodedText)\n        {\n            // Arrange\n            var selectList = new List<SelectListItem>\n            {\n                new SelectListItem { Text = \"text\", },\n            };\n            var helper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            var result = helper.DropDownList(name: \"name\", selectList: selectList, optionLabel: text).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"name\\\" name=\\\"name\\\"><option value=\\\"\\\">\" +\n                    encodedText +\n                    \"</option>\" +\n                    Environment.NewLine +\n                    \"<option>text</option>\" +\n                    Environment.NewLine +\n                    \"</select>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData_NoHtmlEncode\", PropertyType = typeof(EncodedDataSets))]\n        public void DropDownList_AttributeEncodes_Prefix(string text, string encodedText)\n        {\n            // Arrange\n            var selectList = new List<SelectListItem>\n            {\n                new SelectListItem { Text = \"text\", },\n            };\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.TemplateInfo.HtmlFieldPrefix = text;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            // htmlAttributes included only to avoid special-cased renaming done for id attribute.\n            var result =\n                helper.DropDownList(name: String.Empty, selectList: selectList, htmlAttributes: new { id = \"id\", })\n                .ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"id\\\" name=\\\"\" +\n                    encodedText +\n                    \"\\\"><option>text</option>\" +\n                    Environment.NewLine +\n                    \"</select>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"HtmlEncodedData_NoHtmlEncode\", PropertyType = typeof(EncodedDataSets))]\n        public void DropDownList_HtmlEncodes_Text(string text, string encodedText)\n        {\n            // Arrange\n            var selectList = new List<SelectListItem>\n            {\n                new SelectListItem { Text = text, },\n            };\n            var helper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            var result = helper.DropDownList(name: \"name\", selectList: selectList).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"name\\\" name=\\\"name\\\"><option>\" +\n                    encodedText +\n                    \"</option>\" +\n                    Environment.NewLine +\n                    \"</select>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData_NoHtmlEncode\", PropertyType = typeof(EncodedDataSets))]\n        public void DropDownList_AttributeEncodes_Value(string text, string encodedText)\n        {\n            // Arrange\n            var selectList = new List<SelectListItem>\n            {\n                new SelectListItem { Text = \"text\", Value = text },\n            };\n            var helper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            var result = helper.DropDownList(name: \"name\", selectList: selectList).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"name\\\" name=\\\"name\\\"><option value=\\\"\" +\n                    encodedText +\n                    \"\\\">text</option>\" +\n                    Environment.NewLine +\n                    \"</select>\",\n                result);\n        }\n\n        // DropDownListFor\n\n        [Fact]\n        void DropDownListFor_WithGroups()\n        {\n            // Arrange\n            ViewDataDictionary<FooModel> dict = new ViewDataDictionary<FooModel>();\n            dict.Add(\"foo\", \"volvo\");\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(dict);\n            const string expectedListBox = @\"<select id=\"\"foo\"\" name=\"\"foo\"\"><option value=\"\"\"\">Cars</option>\n<option value=\"\"other1\"\">other1</option>\n<option value=\"\"other2\"\">other2</option>\n<optgroup label=\"\"Swedish Cars\"\">\n<option selected=\"\"selected\"\" value=\"\"volvo\"\">Volvo</option>\n<option value=\"\"saab\"\">Saab</option>\n</optgroup>\n<option value=\"\"other3\"\">other3</option>\n<optgroup>\n<option value=\"\"other4\"\">other4</option>\n<option value=\"\"other5\"\">other5</option>\n</optgroup>\n<optgroup label=\"\"German Cars\"\">\n<option value=\"\"mercedes-benz\"\">Mercedes-Benz</option>\n<option disabled=\"\"disabled\"\" value=\"\"audi\"\">Audi</option>\n</optgroup>\n<option value=\"\"other6\"\">other6</option>\n</select>\";\n\n            // Act\n            MvcHtmlString html = helper.DropDownListFor(m => m.foo, GroupedItems, optionLabel: \"Cars\");\n\n            // Assert\n            Assert.Equal(expectedListBox, html.ToHtmlString());\n        }\n\n        [Fact]\n        void DropDownListFor_WithGroups_WithDisabled()\n        {\n            // Arrange\n            ViewDataDictionary<FooModel> dict = new ViewDataDictionary<FooModel>();\n            dict.Add(\"foo\", \"d\");\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(dict);\n            const string expectedListBox = @\"<select id=\"\"foo\"\" name=\"\"foo\"\"><option value=\"\"\"\">Options</option>\n<option value=\"\"a\"\">Alice</option>\n<optgroup disabled=\"\"disabled\"\" label=\"\"DisabledGroup\"\">\n<option value=\"\"b\"\">Bob</option>\n<option value=\"\"c\"\">Charlie</option>\n</optgroup>\n<option disabled=\"\"disabled\"\" selected=\"\"selected\"\" value=\"\"d\"\">David</option>\n</select>\";\n\n            // Act\n            MvcHtmlString html = helper.DropDownListFor(m => m.foo, GroupedItems_WithDisabled, optionLabel: \"Options\");\n\n            // Assert\n            Assert.Equal(expectedListBox, html.ToHtmlString());\n        }\n\n        [Fact]\n        void DropDownListFor_SelectList_WithGroups()\n        {\n            // Arrange\n            ViewDataDictionary<FooModel> dict = new ViewDataDictionary<FooModel>();\n            dict.Add(\"foo\", \"volvo\");\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(dict);\n            const string expectedListBox = @\"<select id=\"\"foo\"\" name=\"\"foo\"\"><option value=\"\"\"\">options...</option>\n<option value=\"\"ufo\"\">UFO</option>\n<optgroup label=\"\"Swedish Cars\"\">\n<option selected=\"\"selected\"\" value=\"\"volvo\"\">Volvo</option>\n<option value=\"\"saab\"\">Saab</option>\n</optgroup>\n<optgroup label=\"\"German Cars\"\">\n<option value=\"\"mercedes-benz\"\">Mercedes-Benz</option>\n<option value=\"\"audi\"\">Audi</option>\n</optgroup>\n<option value=\"\"other\"\">Other</option>\n<optgroup label=\"\" \"\">\n<option value=\"\"unknown\"\">Unknown</option>\n</optgroup>\n</select>\";\n\n            // Act\n            MvcHtmlString html = helper.DropDownListFor(m => m.foo, _selectList, optionLabel: \"options...\");\n\n            // Assert\n            Assert.Equal(expectedListBox, html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListForWithNullExpressionThrows()\n        {\n            // Arrange\n            HtmlHelper<object> helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary<object>());\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleAnonymousObjects(), \"Letter\", \"FullWord\", \"C\");\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => helper.DropDownListFor<object, object>(null /* expression */, selectList),\n                \"expression\"\n                );\n        }\n\n        [Fact]\n        public void DropDownListForUsesExplicitValueIfNotProvidedInViewData()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary<FooModel>());\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleAnonymousObjects(), \"Letter\", \"FullWord\", \"C\");\n\n            // Act\n            MvcHtmlString html = helper.DropDownListFor(m => m.foo, selectList, (string)null /* optionLabel */);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" name=\\\"foo\\\"><option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListForUsesExplicitValueIfNotProvidedInViewData_Unobtrusive()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary<FooModel>());\n            helper.ViewContext.ClientValidationEnabled = true;\n            helper.ViewContext.UnobtrusiveJavaScriptEnabled = true;\n            helper.ViewContext.FormContext = new FormContext();\n            helper.ClientValidationRuleFactory = (name, metadata) => new[] { new ModelClientValidationRule { ValidationType = \"type\", ErrorMessage = \"error\" } };\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleAnonymousObjects(), \"Letter\", \"FullWord\", \"C\");\n\n            // Act\n            MvcHtmlString html = helper.DropDownListFor(m => m.foo, selectList, (string)null /* optionLabel */);\n\n            // Assert\n            Assert.Equal(\n                \"<select data-val=\\\"true\\\" data-val-type=\\\"error\\\" id=\\\"foo\\\" name=\\\"foo\\\"><option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListForWithEnumerableModel_Unobtrusive()\n        {\n            // Arrange\n            HtmlHelper<IEnumerable<RequiredModel>> helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary<IEnumerable<RequiredModel>>());\n            helper.ViewContext.ClientValidationEnabled = true;\n            helper.ViewContext.UnobtrusiveJavaScriptEnabled = true;\n            helper.ViewContext.FormContext = new FormContext();\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleAnonymousObjects(), \"Letter\", \"FullWord\", \"C\");\n\n            using (new CultureReplacer(\"en-US\", \"en-US\"))\n            {\n                // Act\n                MvcHtmlString html = helper.DropDownListFor(m => m.ElementAt(0).foo, selectList);\n\n                // Assert\n                Assert.Equal(\n                    \"<select data-val=\\\"true\\\" data-val-required=\\\"The foo field is required.\\\" id=\\\"MyPrefix_foo\\\" name=\\\"MyPrefix.foo\\\"><option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n                  + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n                  + \"<option selected=\\\"selected\\\" value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n                  + \"</select>\",\n                    html.ToHtmlString());\n            }\n        }\n\n        [Fact]\n        public void DropDownListForUsesViewDataDefaultValue()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(_dropDownListViewData);\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings(), \"Charlie\");\n\n            // Act\n            MvcHtmlString html = helper.DropDownListFor(m => m.foo, selectList, (string)null /* optionLabel */);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListForUsesViewDataDefaultValueNoOptionLabel()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(_dropDownListViewData);\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings(), \"Charlie\");\n\n            // Act\n            MvcHtmlString html = helper.DropDownListFor(m => m.foo, selectList);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListForUsesLambdaDefaultValue()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(_dropDownListViewData);\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings());\n\n            // Act\n            MvcHtmlString html = helper.DropDownListFor(m => m.foo, selectList);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n        \n        [Fact]\n        public void DropDownListForUsesLambdaDefaultValueWhenNested()\n        {\n            // Arrange\n            FooModel model = new FooModel { foo = \"Bravo\" };\n            ViewDataDictionary<FooModel> viewData = new ViewDataDictionary<FooModel>(model);\n            ViewDataDictionary<string> nestedViewData = MvcHelper.GetNestedViewData(viewData, m => m.foo);\n            HtmlHelper<string> helper = MvcHelper.GetHtmlHelper(nestedViewData);\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings());\n\n            // Act\n            MvcHtmlString html = helper.DropDownListFor(m => m, selectList);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListForUsesLambdaDefaultValueFromViewDataWhenNested()\n        {\n            // Arrange\n            ViewDataDictionary<FooModel> nestedViewData = MvcHelper.GetNestedViewData(_nestedDropDownListViewData, m => m.inner);\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(nestedViewData);\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings());\n\n            // Act\n            MvcHtmlString html = helper.DropDownListFor(m => m.foo, selectList);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"inner_foo\\\" name=\\\"inner.foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListForUsesLambdaDefaultValueWithNullSelectListUsesViewData()\n        {\n            // Arrange\n            FooModel model = new FooModel { foo = \"Bravo\" };\n            ViewDataDictionary<FooModel> vdd = new ViewDataDictionary<FooModel>(model)\n            {\n                { \"foo\", new SelectList(MultiSelectListTest.GetSampleStrings()) }\n            };\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(vdd);\n\n            // Act\n            MvcHtmlString html = helper.DropDownListFor(m => m.foo, selectList: null);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListForUsesLambdaDefaultValueWithNullSelectListUsesViewDataWhenNested()\n        {\n            // Arrange\n            FooContainerModel model = new FooContainerModel { inner = new FooModel { foo = \"Bravo\" } };\n            ViewDataDictionary<FooContainerModel> vdd = new ViewDataDictionary<FooContainerModel>(model)\n            {\n                { \"foo\", new SelectList(MultiSelectListTest.GetSampleStrings()) }\n            };\n\n            ViewDataDictionary<FooModel> nestedViewData = MvcHelper.GetNestedViewData(vdd, m => m.inner);\n\n\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(nestedViewData);\n\n            // Act\n            MvcHtmlString html = helper.DropDownListFor(m => m.foo, selectList: null);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"inner_foo\\\" name=\\\"inner.foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListForWithAttributesDictionary()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary<FooModel>());\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings());\n\n            // Act\n            MvcHtmlString html = helper.DropDownListFor(m => m.foo, selectList, null /* optionLabel */, HtmlHelperTest.AttributesDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazValue\\\" id=\\\"foo\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListForWithErrors()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetViewDataWithErrors());\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings(), new[] { \"Charlie\" });\n\n            // Act\n            MvcHtmlString html = helper.DropDownListFor(m => m.foo, selectList, null /* optionLabel */, HtmlHelperTest.AttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazObjValue\\\" class=\\\"input-validation-error\\\" id=\\\"foo\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListForWithErrorsAndCustomClass()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetViewDataWithErrors());\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings());\n\n            // Act\n            MvcHtmlString html = helper.DropDownListFor(m => m.foo, selectList, null /* optionLabel */, new { @class = \"foo-class\" });\n\n            // Assert\n            Assert.Equal(\n                \"<select class=\\\"input-validation-error foo-class\\\" id=\\\"foo\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListForWithObjectDictionary()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary<FooModel>());\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings());\n\n            // Act\n            MvcHtmlString html = helper.DropDownListFor(m => m.foo, selectList, null /* optionLabel */, HtmlHelperTest.AttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazObjValue\\\" id=\\\"foo\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListForWithObjectDictionaryWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary<FooModel>());\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings());\n\n            // Act\n            MvcHtmlString html = helper.DropDownListFor(m => m.foo, selectList, null /* optionLabel */, HtmlHelperTest.AttributesObjectUnderscoresDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select foo-baz=\\\"BazObjValue\\\" id=\\\"foo\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListForWithObjectDictionaryAndSelectListNoOptionLabel()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary<FooModel>());\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings());\n\n            // Act\n            MvcHtmlString html = helper.DropDownListFor(m => m.foo, selectList, HtmlHelperTest.AttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazObjValue\\\" id=\\\"foo\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListForWithObjectDictionaryWithUnderscoresAndSelectListNoOptionLabel()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary<FooModel>());\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings());\n\n            // Act\n            MvcHtmlString html = helper.DropDownListFor(m => m.foo, selectList, HtmlHelperTest.AttributesObjectUnderscoresDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select foo-baz=\\\"BazObjValue\\\" id=\\\"foo\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListForWithObjectDictionaryAndEmptyOptionLabel()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary<FooModel>());\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings());\n\n            // Act\n            MvcHtmlString html = helper.DropDownListFor(m => m.foo, selectList, String.Empty /* optionLabel */, HtmlHelperTest.AttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazObjValue\\\" id=\\\"foo\\\" name=\\\"foo\\\"><option value=\\\"\\\"></option>\" + Environment.NewLine\n              + \"<option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListForWithObjectDictionaryAndTitle()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary<FooModel>());\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings());\n\n            // Act\n            MvcHtmlString html = helper.DropDownListFor(m => m.foo, selectList, \"[Select Something]\", HtmlHelperTest.AttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazObjValue\\\" id=\\\"foo\\\" name=\\\"foo\\\"><option value=\\\"\\\">[Select Something]</option>\" + Environment.NewLine\n              + \"<option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListForWithIEnumerableSelectListItemSelectsDefaultFromViewData()\n        {\n            // Arrange\n            ViewDataDictionary<FooModel> vdd = new ViewDataDictionary<FooModel> { { \"foo\", \"123456789\" } };\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(vdd);\n\n            // Act\n            MvcHtmlString html = helper.DropDownListFor(m => m.foo, MultiSelectListTest.GetSampleIEnumerableObjects());\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" name=\\\"foo\\\"><option selected=\\\"selected\\\" value=\\\"123456789\\\">John</option>\" + Environment.NewLine\n              + \"<option value=\\\"987654321\\\">Jane</option>\" + Environment.NewLine\n              + \"<option value=\\\"111111111\\\">Joe</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListForWithListOfSelectListItemSelectsDefaultFromViewData()\n        {\n            // Arrange\n            ViewDataDictionary<FooModel> vdd = new ViewDataDictionary<FooModel> { { \"foo\", \"123456789\" } };\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(vdd);\n\n            // Act\n            MvcHtmlString html = helper.DropDownListFor(m => m.foo, MultiSelectListTest.GetSampleListObjects());\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" name=\\\"foo\\\"><option selected=\\\"selected\\\" value=\\\"123456789\\\">John</option>\" + Environment.NewLine\n              + \"<option value=\\\"987654321\\\">Jane</option>\" + Environment.NewLine\n              + \"<option value=\\\"111111111\\\">Joe</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListForWithPrefix()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary<FooModel>());\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings());\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.DropDownListFor(m => m.foo, selectList, HtmlHelperTest.AttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazObjValue\\\" id=\\\"MyPrefix_foo\\\" name=\\\"MyPrefix.foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListForWithPrefixAndEmptyName()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary<FooModel>());\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings());\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.DropDownListFor(m => m, selectList, HtmlHelperTest.AttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazObjValue\\\" id=\\\"MyPrefix\\\" name=\\\"MyPrefix\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListForWithPrefixAndIEnumerableSelectListItemSelectsDefaultFromViewData()\n        {\n            // Arrange\n            ViewDataDictionary<FooModel> vdd = new ViewDataDictionary<FooModel> { { \"foo\", \"123456789\" } };\n            vdd.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(vdd);\n\n            // Act\n            MvcHtmlString html = helper.DropDownListFor(m => m.foo, MultiSelectListTest.GetSampleIEnumerableObjects());\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"MyPrefix_foo\\\" name=\\\"MyPrefix.foo\\\"><option selected=\\\"selected\\\" value=\\\"123456789\\\">John</option>\" + Environment.NewLine\n              + \"<option value=\\\"987654321\\\">Jane</option>\" + Environment.NewLine\n              + \"<option value=\\\"111111111\\\">Joe</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        // EnumDropDownListFor\n\n        [Fact]\n        public void EnumDropDownListForWithNullExpressionThrowsArgumentNull()\n        {\n            // Arrange\n            HtmlHelper<EnumWithDisplay> helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary<EnumWithDisplay>());\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => helper.EnumDropDownListFor<EnumWithDisplay, EnumWithDisplay>(null),\n                \"expression\");\n        }\n\n        [Fact]\n        public void EnumDropDownListForWithUnsupportedExpressionThrowsInvalidOperation()\n        {\n            // Arrange\n            IEnumerable<EnumModel> model = new List<EnumModel>\n            {\n                new EnumModel { WithDisplay = EnumWithDisplay.One, },\n                new EnumModel { WithDisplay = EnumWithDisplay.Two, },\n            };\n            ViewDataDictionary<IEnumerable<EnumModel>> viewData = new ViewDataDictionary<IEnumerable<EnumModel>>(model);\n            HtmlHelper<IEnumerable<EnumModel>> helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => helper.EnumDropDownListFor(m => m.Select((item) => item.WithDisplay).First()),\n                exceptionMessage: \"Templates can be used only with field access, property access, \" +\n                \"single-dimension array index, or single-parameter custom indexer expressions.\");\n        }\n\n        [Fact]\n        public void EnumDropDownListForWithIntExpressionTypeThrowsArgument()\n        {\n            // Arrange\n            ViewDataDictionary<int> viewData = new ViewDataDictionary<int>\n            {\n                TemplateInfo = new TemplateInfo { HtmlFieldPrefix = \"MyExpression\", },\n            };\n            HtmlHelper<int> helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act & Assert\n            Assert.ThrowsArgument(() => helper.EnumDropDownListFor(model => model), paramName: \"expression\",\n                exceptionMessage: \"Return type 'System.Int32' is not supported.\" + Environment.NewLine +\n                \"Parameter name: expression\");\n        }\n\n        [Fact]\n        public void EnumDropDownListForWithUnsupportedExpressionTypeThrowsArgument()\n        {\n            // Arrange\n            ViewDataDictionary<EnumWithFlags> viewData = new ViewDataDictionary<EnumWithFlags>\n            {\n                TemplateInfo = new TemplateInfo { HtmlFieldPrefix = \"MyExpression\", },\n            };\n            HtmlHelper<EnumWithFlags> helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act & Assert\n            Assert.ThrowsArgument(() => helper.EnumDropDownListFor(model => model), paramName: \"expression\",\n                exceptionMessage: \"Return type 'System.Web.Mvc.Html.Test.SelectExtensionsTest+EnumWithFlags' is not \" +\n                \"supported. Type must not have a 'Flags' attribute.\" + Environment.NewLine +\n                \"Parameter name: expression\");\n        }\n\n        // Like EnumDropDownListForWithUnsupportedExpressionTypeThrowsArgument but using EnumModel\n        [Fact]\n        public void EnumDropDownListForWithUnsupportedPropertyTypeThrowsArgument()\n        {\n            // Arrange\n            HtmlHelper<EnumModel> helper = MvcHelper.GetHtmlHelper(_enumDropDownListViewData);\n\n            // Act & Assert\n            Assert.ThrowsArgument(() => helper.EnumDropDownListFor(m => m.WithFlags), paramName: \"expression\",\n                exceptionMessage: \"Return type 'System.Web.Mvc.Html.Test.SelectExtensionsTest+EnumWithFlags' is not \" +\n                \"supported. Type must not have a 'Flags' attribute.\" + Environment.NewLine +\n                \"Parameter name: expression\");\n        }\n\n        [Fact]\n        public void EnumDropDownListforIsSuccessfulIfNoValueProvided()\n        {\n            // Arrange\n            ViewDataDictionary<EnumWithDisplay> viewData = new ViewDataDictionary<EnumWithDisplay>\n            {\n                TemplateInfo = new TemplateInfo { HtmlFieldPrefix = \"MyExpression\", },\n            };\n            HtmlHelper<EnumWithDisplay> helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString html = helper.EnumDropDownListFor(model => model, optionLabel: null);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"MyExpression\\\" name=\\\"MyExpression\\\">\" +\n                \"<option selected=\\\"selected\\\" value=\\\"0\\\">First</option>\" + Environment.NewLine +\n                \"<option value=\\\"1\\\">Second</option>\" + Environment.NewLine +\n                \"<option value=\\\"2\\\">Third</option>\" + Environment.NewLine +\n                \"<option value=\\\"3\\\">Fourth</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void EnumDropDownListForIsSuccessfulIfNoValueProvidedAndEnumEmpty()\n        {\n            // Arrange\n            ViewDataDictionary<EnumWithoutAnything> viewData = new ViewDataDictionary<EnumWithoutAnything>\n            {\n                TemplateInfo = new TemplateInfo { HtmlFieldPrefix = \"MyExpression\", },\n            };\n            HtmlHelper<EnumWithoutAnything> helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString html = helper.EnumDropDownListFor(model => model, optionLabel: null);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"MyExpression\\\" name=\\\"MyExpression\\\">\" +\n                \"<option selected=\\\"selected\\\" value=\\\"0\\\"></option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void EnumDropDownListForUsesModelValueIfNotProvidedInViewData()\n        {\n            // Arrange\n            ViewDataDictionary<EnumWithDisplay> viewData = new ViewDataDictionary<EnumWithDisplay>(EnumWithDisplay.Two)\n            {\n                TemplateInfo = new TemplateInfo { HtmlFieldPrefix = \"MyExpression\", },\n            };\n            HtmlHelper<EnumWithDisplay> helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString html = helper.EnumDropDownListFor(model => model, optionLabel: null);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"MyExpression\\\" name=\\\"MyExpression\\\">\" +\n                \"<option value=\\\"0\\\">First</option>\" + Environment.NewLine +\n                \"<option value=\\\"1\\\">Second</option>\" + Environment.NewLine +\n                \"<option selected=\\\"selected\\\" value=\\\"2\\\">Third</option>\" + Environment.NewLine +\n                \"<option value=\\\"3\\\">Fourth</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void EnumDropDownListForUsesModelValueIfNotProvidedInViewData_EnumModel()\n        {\n            // Arrange\n            EnumModel model = new EnumModel { WithDisplay = EnumWithDisplay.Two, };\n            HtmlHelper<EnumModel> helper =\n                MvcHelper.GetHtmlHelper(new ViewDataDictionary<EnumModel>(model));\n\n            // Act\n            MvcHtmlString html = helper.EnumDropDownListFor(m => m.WithDisplay, optionLabel: null);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"WithDisplay\\\" name=\\\"WithDisplay\\\">\" +\n                \"<option value=\\\"0\\\">First</option>\" + Environment.NewLine +\n                \"<option value=\\\"1\\\">Second</option>\" + Environment.NewLine +\n                \"<option selected=\\\"selected\\\" value=\\\"2\\\">Third</option>\" + Environment.NewLine +\n                \"<option value=\\\"3\\\">Fourth</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void EnumDropDownListForUsesModelValueIfNotProvidedInViewData_EnumWithoutAnything()\n        {\n            // Arrange\n            EnumModel model = new EnumModel { WithoutAnything = (EnumWithoutAnything)23, };\n            HtmlHelper<EnumModel> helper =\n                MvcHelper.GetHtmlHelper(new ViewDataDictionary<EnumModel>(model));\n\n            // Act\n            MvcHtmlString html = helper.EnumDropDownListFor(m => m.WithoutAnything, optionLabel: \"My Label\");\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"WithoutAnything\\\" name=\\\"WithoutAnything\\\">\" +\n                \"<option selected=\\\"selected\\\" value=\\\"23\\\">My Label</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void EnumDropDownListForUsesModelValueIfNotProvidedInViewData_Unobtrusive()\n        {\n            // Arrange\n            EnumModel model = new EnumModel { WithDisplay = EnumWithDisplay.Two, };\n            HtmlHelper<EnumModel> helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary<EnumModel>(model));\n            helper.ViewContext.ClientValidationEnabled = true;\n            helper.ViewContext.UnobtrusiveJavaScriptEnabled = true;\n            helper.ViewContext.FormContext = new FormContext();\n            helper.ClientValidationRuleFactory = (name, metadata) =>\n                new[] { new ModelClientValidationRule { ValidationType = \"type\", ErrorMessage = \"error\" } };\n\n            // Act\n            MvcHtmlString html = helper.EnumDropDownListFor(m => m.WithDisplay, optionLabel: null);\n\n            // Assert\n            Assert.Equal(\n                \"<select data-val=\\\"true\\\" data-val-type=\\\"error\\\" id=\\\"WithDisplay\\\" name=\\\"WithDisplay\\\">\" +\n                \"<option value=\\\"0\\\">First</option>\" + Environment.NewLine +\n                \"<option value=\\\"1\\\">Second</option>\" + Environment.NewLine +\n                \"<option selected=\\\"selected\\\" value=\\\"2\\\">Third</option>\" + Environment.NewLine +\n                \"<option value=\\\"3\\\">Fourth</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void EnumDropDownListForUsesViewDataDefaultValue()\n        {\n            // Arrange\n            HtmlHelper<EnumModel> helper = MvcHelper.GetHtmlHelper(_enumDropDownListViewData);\n\n            // Act\n            MvcHtmlString html = helper.EnumDropDownListFor(m => m.WithDisplay, optionLabel: null);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"WithDisplay\\\" name=\\\"WithDisplay\\\">\" +\n                \"<option value=\\\"0\\\">First</option>\" + Environment.NewLine +\n                \"<option value=\\\"1\\\">Second</option>\" + Environment.NewLine +\n                \"<option selected=\\\"selected\\\" value=\\\"2\\\">Third</option>\" + Environment.NewLine +\n                \"<option value=\\\"3\\\">Fourth</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void EnumDropDownListForUsesViewDataDefaultValue_Duplicates()\n        {\n            // Arrange\n            HtmlHelper<EnumModel> helper = MvcHelper.GetHtmlHelper(_enumDropDownListViewData);\n\n            // Act\n            MvcHtmlString html = helper.EnumDropDownListFor(m => m.WithDuplicates, optionLabel: null);\n\n            // Assert\n            // TODO: https://aspnetwebstack.codeplex.com/workitem/1349 covers incorrect multi-select in this case\n            Assert.Equal(\n                \"<select id=\\\"WithDuplicates\\\" name=\\\"WithDuplicates\\\">\" +\n                \"<option value=\\\"0\\\">First</option>\" + Environment.NewLine +\n                \"<option selected=\\\"selected\\\" value=\\\"1\\\">Second</option>\" + Environment.NewLine +\n                \"<option selected=\\\"selected\\\" value=\\\"1\\\">Third</option>\" + Environment.NewLine +\n                \"<option value=\\\"2\\\">Fourth</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void EnumDropDownListForUsesViewDataDefaultValue_Unrecognized()\n        {\n            // Arrange\n            ViewDataDictionary<EnumModel> viewData = new ViewDataDictionary<EnumModel>(_enumDropDownListViewData);\n            viewData[\"WithDisplay\"] = (EnumWithDisplay)34;\n            HtmlHelper<EnumModel> helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString html = helper.EnumDropDownListFor(m => m.WithDisplay, optionLabel: null);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"WithDisplay\\\" name=\\\"WithDisplay\\\">\" +\n                \"<option selected=\\\"selected\\\" value=\\\"34\\\"></option>\" + Environment.NewLine +\n                \"<option value=\\\"0\\\">First</option>\" + Environment.NewLine +\n                \"<option value=\\\"1\\\">Second</option>\" + Environment.NewLine +\n                \"<option value=\\\"2\\\">Third</option>\" + Environment.NewLine +\n                \"<option value=\\\"3\\\">Fourth</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void EnumDropDownListForUsesViewDataDefaultValue_NullableIsNull()\n        {\n            // Arrange\n            HtmlHelper<EnumModel> helper = MvcHelper.GetHtmlHelper(_enumDropDownListViewData);\n\n            // Act\n            MvcHtmlString html = helper.EnumDropDownListFor(m => m.WithNullable, optionLabel: null);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"WithNullable\\\" name=\\\"WithNullable\\\">\" +\n                \"<option selected=\\\"selected\\\" value=\\\"\\\"></option>\" + Environment.NewLine +\n                \"<option value=\\\"0\\\">First</option>\" + Environment.NewLine +\n                \"<option value=\\\"1\\\">Second</option>\" + Environment.NewLine +\n                \"<option value=\\\"2\\\">Third</option>\" + Environment.NewLine +\n                \"<option value=\\\"3\\\">Fourth</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void EnumDropDownListForUsesViewDataDefaultValue_NullableNotNull()\n        {\n            // Arrange\n            ViewDataDictionary<EnumModel> viewData = new ViewDataDictionary<EnumModel>(_enumDropDownListViewData);\n            viewData[\"WithNullable\"] = EnumWithDisplay.Three;\n            HtmlHelper<EnumModel> helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString html = helper.EnumDropDownListFor(m => m.WithNullable, optionLabel: null);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"WithNullable\\\" name=\\\"WithNullable\\\">\" +\n                \"<option value=\\\"\\\"></option>\" + Environment.NewLine +\n                \"<option value=\\\"0\\\">First</option>\" + Environment.NewLine +\n                \"<option value=\\\"1\\\">Second</option>\" + Environment.NewLine +\n                \"<option value=\\\"2\\\">Third</option>\" + Environment.NewLine +\n                \"<option selected=\\\"selected\\\" value=\\\"3\\\">Fourth</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void EnumDropDownListForUsesViewDataDefaultValue_NullableUnrecognized()\n        {\n            // Arrange\n            ViewDataDictionary<EnumModel> viewData = new ViewDataDictionary<EnumModel>(_enumDropDownListViewData);\n            viewData[\"WithNullable\"] = (EnumWithDisplay)34;\n            HtmlHelper<EnumModel> helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString html = helper.EnumDropDownListFor(m => m.WithNullable, optionLabel: null);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"WithNullable\\\" name=\\\"WithNullable\\\">\" +\n                \"<option selected=\\\"selected\\\" value=\\\"34\\\"></option>\" + Environment.NewLine +\n                \"<option value=\\\"0\\\">First</option>\" + Environment.NewLine +\n                \"<option value=\\\"1\\\">Second</option>\" + Environment.NewLine +\n                \"<option value=\\\"2\\\">Third</option>\" + Environment.NewLine +\n                \"<option value=\\\"3\\\">Fourth</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void EnumDropDownListForUsesViewDataDefaultValueNoOptionLabel()\n        {\n            // Arrange\n            HtmlHelper<EnumModel> helper = MvcHelper.GetHtmlHelper(_enumDropDownListViewData);\n\n            // Act\n            MvcHtmlString html = helper.EnumDropDownListFor(m => m.WithDisplay);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"WithDisplay\\\" name=\\\"WithDisplay\\\">\" +\n                \"<option value=\\\"0\\\">First</option>\" + Environment.NewLine +\n                \"<option value=\\\"1\\\">Second</option>\" + Environment.NewLine +\n                \"<option selected=\\\"selected\\\" value=\\\"2\\\">Third</option>\" + Environment.NewLine +\n                \"<option value=\\\"3\\\">Fourth</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void EnumDropDownListForWithTitle()\n        {\n            // Arrange\n            HtmlHelper<EnumModel> helper = MvcHelper.GetHtmlHelper(_enumDropDownListViewData);\n\n            // Act\n            MvcHtmlString html = helper.EnumDropDownListFor(m => m.WithDisplay, optionLabel: \"[Select Something]\");\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"WithDisplay\\\" name=\\\"WithDisplay\\\">\" +\n                \"<option value=\\\"\\\">[Select Something]</option>\" + Environment.NewLine +\n                \"<option value=\\\"0\\\">First</option>\" + Environment.NewLine +\n                \"<option value=\\\"1\\\">Second</option>\" + Environment.NewLine +\n                \"<option selected=\\\"selected\\\" value=\\\"2\\\">Third</option>\" + Environment.NewLine +\n                \"<option value=\\\"3\\\">Fourth</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void EnumDropDownListForWithTitle_Unrecognized()\n        {\n            // Arrange\n            ViewDataDictionary<EnumModel> viewData = new ViewDataDictionary<EnumModel>(_enumDropDownListViewData);\n            viewData[\"WithDisplay\"] = (EnumWithDisplay)34;\n            HtmlHelper<EnumModel> helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString html = helper.EnumDropDownListFor(m => m.WithDisplay, optionLabel: \"[Select Something]\");\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"WithDisplay\\\" name=\\\"WithDisplay\\\">\" +\n                \"<option selected=\\\"selected\\\" value=\\\"34\\\">[Select Something]</option>\" + Environment.NewLine +\n                \"<option value=\\\"0\\\">First</option>\" + Environment.NewLine +\n                \"<option value=\\\"1\\\">Second</option>\" + Environment.NewLine +\n                \"<option value=\\\"2\\\">Third</option>\" + Environment.NewLine +\n                \"<option value=\\\"3\\\">Fourth</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void EnumDropDownListForWithTitle_NullableNull()\n        {\n            // Arrange\n            HtmlHelper<EnumModel> helper = MvcHelper.GetHtmlHelper(_enumDropDownListViewData);\n\n            // Act\n            MvcHtmlString html = helper.EnumDropDownListFor(m => m.WithNullable, optionLabel: \"[Select Something]\");\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"WithNullable\\\" name=\\\"WithNullable\\\">\" +\n                \"<option selected=\\\"selected\\\" value=\\\"\\\">[Select Something]</option>\" + Environment.NewLine +\n                \"<option value=\\\"0\\\">First</option>\" + Environment.NewLine +\n                \"<option value=\\\"1\\\">Second</option>\" + Environment.NewLine +\n                \"<option value=\\\"2\\\">Third</option>\" + Environment.NewLine +\n                \"<option value=\\\"3\\\">Fourth</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void EnumDropDownListForWithTitle_NullableNotNull()\n        {\n            // Arrange\n            ViewDataDictionary<EnumModel> viewData = new ViewDataDictionary<EnumModel>(_enumDropDownListViewData);\n            viewData[\"WithNullable\"] = EnumWithDisplay.Three;\n            HtmlHelper<EnumModel> helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString html = helper.EnumDropDownListFor(m => m.WithNullable, optionLabel: \"[Select Something]\");\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"WithNullable\\\" name=\\\"WithNullable\\\">\" +\n                \"<option value=\\\"\\\">[Select Something]</option>\" + Environment.NewLine +\n                \"<option value=\\\"0\\\">First</option>\" + Environment.NewLine +\n                \"<option value=\\\"1\\\">Second</option>\" + Environment.NewLine +\n                \"<option value=\\\"2\\\">Third</option>\" + Environment.NewLine +\n                \"<option selected=\\\"selected\\\" value=\\\"3\\\">Fourth</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void EnumDropDownListForWithTitle_NullableUnrecognized()\n        {\n            // Arrange\n            ViewDataDictionary<EnumModel> viewData = new ViewDataDictionary<EnumModel>(_enumDropDownListViewData);\n            viewData[\"WithNullable\"] = (EnumWithDisplay)34;\n            HtmlHelper<EnumModel> helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString html = helper.EnumDropDownListFor(m => m.WithNullable, optionLabel: \"[Select Something]\");\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"WithNullable\\\" name=\\\"WithNullable\\\">\" +\n                \"<option selected=\\\"selected\\\" value=\\\"34\\\">[Select Something]</option>\" + Environment.NewLine +\n                \"<option value=\\\"0\\\">First</option>\" + Environment.NewLine +\n                \"<option value=\\\"1\\\">Second</option>\" + Environment.NewLine +\n                \"<option value=\\\"2\\\">Third</option>\" + Environment.NewLine +\n                \"<option value=\\\"3\\\">Fourth</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void EnumDropDownListForWithAttributesDictionary()\n        {\n            // Arrange\n            HtmlHelper<EnumModel> helper = MvcHelper.GetHtmlHelper(_enumDropDownListViewData);\n\n            // Act\n            MvcHtmlString html = helper.EnumDropDownListFor(m => m.WithDisplay,\n                htmlAttributes: HtmlHelperTest.AttributesDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazValue\\\" id=\\\"WithDisplay\\\" name=\\\"WithDisplay\\\">\" +\n                \"<option value=\\\"0\\\">First</option>\" + Environment.NewLine +\n                \"<option value=\\\"1\\\">Second</option>\" + Environment.NewLine +\n                \"<option selected=\\\"selected\\\" value=\\\"2\\\">Third</option>\" + Environment.NewLine +\n                \"<option value=\\\"3\\\">Fourth</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void EnumDropDownListForWithAttributesDictionaryAndTitle()\n        {\n            // Arrange\n            HtmlHelper<EnumModel> helper = MvcHelper.GetHtmlHelper(_enumDropDownListViewData);\n\n            // Act\n            MvcHtmlString html = helper.EnumDropDownListFor(m => m.WithDisplay, optionLabel: \"[Select Something]\",\n                htmlAttributes: HtmlHelperTest.AttributesDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazValue\\\" id=\\\"WithDisplay\\\" name=\\\"WithDisplay\\\">\" +\n                \"<option value=\\\"\\\">[Select Something]</option>\" + Environment.NewLine +\n                \"<option value=\\\"0\\\">First</option>\" + Environment.NewLine +\n                \"<option value=\\\"1\\\">Second</option>\" + Environment.NewLine +\n                \"<option selected=\\\"selected\\\" value=\\\"2\\\">Third</option>\" + Environment.NewLine +\n                \"<option value=\\\"3\\\">Fourth</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void EnumDropDownListForWithErrors()\n        {\n            // Arrange\n            ViewDataDictionary<EnumModel> viewData = new ViewDataDictionary<EnumModel>(_enumDropDownListViewData);\n            ModelState modelState = new ModelState\n            {\n                Errors = { new ModelError(\"WithDisplay error 1\"), new ModelError(\"WithDisplay error 2\"), },\n            };\n            viewData.ModelState[\"WithDisplay\"] = modelState;\n\n            HtmlHelper<EnumModel> helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString html = helper.EnumDropDownListFor(m => m.WithDisplay,\n                htmlAttributes: HtmlHelperTest.AttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazObjValue\\\" class=\\\"input-validation-error\\\" id=\\\"WithDisplay\\\" name=\\\"WithDisplay\\\">\" +\n                \"<option value=\\\"0\\\">First</option>\" + Environment.NewLine +\n                \"<option value=\\\"1\\\">Second</option>\" + Environment.NewLine +\n                \"<option selected=\\\"selected\\\" value=\\\"2\\\">Third</option>\" + Environment.NewLine +\n                \"<option value=\\\"3\\\">Fourth</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void EnumDropDownListForWithErrorsAndValue()\n        {\n            // Arrange\n            ViewDataDictionary<EnumModel> viewData = new ViewDataDictionary<EnumModel>(_enumDropDownListViewData);\n            ModelState modelState = new ModelState\n            {\n                Errors = { new ModelError(\"WithDisplay error 1\"), new ModelError(\"WithDisplay error 2\"), },\n                Value = new ValueProviderResult(new string[] { \"1\", }, \"1\", null),\n            };\n            viewData.ModelState[\"WithDisplay\"] = modelState;\n\n            HtmlHelper<EnumModel> helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString html = helper.EnumDropDownListFor(m => m.WithDisplay,\n                htmlAttributes: HtmlHelperTest.AttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazObjValue\\\" class=\\\"input-validation-error\\\" id=\\\"WithDisplay\\\" name=\\\"WithDisplay\\\">\" +\n                \"<option value=\\\"0\\\">First</option>\" + Environment.NewLine +\n                \"<option selected=\\\"selected\\\" value=\\\"1\\\">Second</option>\" + Environment.NewLine +\n                \"<option value=\\\"2\\\">Third</option>\" + Environment.NewLine +\n                \"<option value=\\\"3\\\">Fourth</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void EnumDropDownListForWithObjectDictionaryWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper<EnumModel> helper = MvcHelper.GetHtmlHelper(_enumDropDownListViewData);\n\n            // Act\n            MvcHtmlString html = helper.EnumDropDownListFor(m => m.WithDisplay, optionLabel: null,\n                htmlAttributes: HtmlHelperTest.AttributesObjectUnderscoresDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select foo-baz=\\\"BazObjValue\\\" id=\\\"WithDisplay\\\" name=\\\"WithDisplay\\\">\" +\n                \"<option value=\\\"0\\\">First</option>\" + Environment.NewLine +\n                \"<option value=\\\"1\\\">Second</option>\" + Environment.NewLine +\n                \"<option selected=\\\"selected\\\" value=\\\"2\\\">Third</option>\" + Environment.NewLine +\n                \"<option value=\\\"3\\\">Fourth</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void EnumDropDownListForWithObjectDictionaryWithUnderscoresNoOptionLabel()\n        {\n            // Arrange\n            HtmlHelper<EnumModel> helper = MvcHelper.GetHtmlHelper(_enumDropDownListViewData);\n\n            // Act\n            MvcHtmlString html = helper.EnumDropDownListFor(m => m.WithDisplay,\n                htmlAttributes: HtmlHelperTest.AttributesObjectUnderscoresDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select foo-baz=\\\"BazObjValue\\\" id=\\\"WithDisplay\\\" name=\\\"WithDisplay\\\">\" +\n                \"<option value=\\\"0\\\">First</option>\" + Environment.NewLine +\n                \"<option value=\\\"1\\\">Second</option>\" + Environment.NewLine +\n                \"<option selected=\\\"selected\\\" value=\\\"2\\\">Third</option>\" + Environment.NewLine +\n                \"<option value=\\\"3\\\">Fourth</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void EnumDropDownListForWithObjectDictionaryAndEmptyOptionLabel()\n        {\n            // Arrange\n            HtmlHelper<EnumModel> helper = MvcHelper.GetHtmlHelper(_enumDropDownListViewData);\n\n            // Act\n            MvcHtmlString html = helper.EnumDropDownListFor(m => m.WithDisplay, optionLabel: String.Empty,\n                htmlAttributes: HtmlHelperTest.AttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazObjValue\\\" id=\\\"WithDisplay\\\" name=\\\"WithDisplay\\\">\" +\n                \"<option value=\\\"\\\"></option>\" + Environment.NewLine +\n                \"<option value=\\\"0\\\">First</option>\" + Environment.NewLine +\n                \"<option value=\\\"1\\\">Second</option>\" + Environment.NewLine +\n                \"<option selected=\\\"selected\\\" value=\\\"2\\\">Third</option>\" + Environment.NewLine +\n                \"<option value=\\\"3\\\">Fourth</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void EnumDropDownListForWithObjectDictionaryAndTitle()\n        {\n            // Arrange\n            HtmlHelper<EnumModel> helper = MvcHelper.GetHtmlHelper(_enumDropDownListViewData);\n\n            // Act\n            MvcHtmlString html = helper.EnumDropDownListFor(m => m.WithDisplay, optionLabel: \"[Select Something]\",\n                htmlAttributes: HtmlHelperTest.AttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazObjValue\\\" id=\\\"WithDisplay\\\" name=\\\"WithDisplay\\\">\" +\n                \"<option value=\\\"\\\">[Select Something]</option>\" + Environment.NewLine +\n                \"<option value=\\\"0\\\">First</option>\" + Environment.NewLine +\n                \"<option value=\\\"1\\\">Second</option>\" + Environment.NewLine +\n                \"<option selected=\\\"selected\\\" value=\\\"2\\\">Third</option>\" + Environment.NewLine +\n                \"<option value=\\\"3\\\">Fourth</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void EnumDropDownListForWithPrefix()\n        {\n            // Arrange\n            ViewDataDictionary<EnumModel> viewData = new ViewDataDictionary<EnumModel>(_enumDropDownListViewData)\n            {\n                TemplateInfo = new TemplateInfo { HtmlFieldPrefix = \"MyPrefix\", },\n            };\n            HtmlHelper<EnumModel> helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString html = helper.EnumDropDownListFor(m => m.WithDisplay,\n                htmlAttributes: HtmlHelperTest.AttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazObjValue\\\" id=\\\"MyPrefix_WithDisplay\\\" name=\\\"MyPrefix.WithDisplay\\\">\" +\n                \"<option value=\\\"0\\\">First</option>\" + Environment.NewLine +\n                \"<option value=\\\"1\\\">Second</option>\" + Environment.NewLine +\n                \"<option selected=\\\"selected\\\" value=\\\"2\\\">Third</option>\" + Environment.NewLine +\n                \"<option value=\\\"3\\\">Fourth</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void EnumDropDownListForWithPrefixAndEmptyName()\n        {\n            // Arrange\n            ViewDataDictionary<EnumWithDisplay> viewData = new ViewDataDictionary<EnumWithDisplay>(EnumWithDisplay.Two)\n            {\n                TemplateInfo = new TemplateInfo { HtmlFieldPrefix = \"MyPrefix\", },\n            };\n            HtmlHelper<EnumWithDisplay> helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString html = helper.EnumDropDownListFor(m => m,\n                htmlAttributes: HtmlHelperTest.AttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazObjValue\\\" id=\\\"MyPrefix\\\" name=\\\"MyPrefix\\\">\" +\n                \"<option value=\\\"0\\\">First</option>\" + Environment.NewLine +\n                \"<option value=\\\"1\\\">Second</option>\" + Environment.NewLine +\n                \"<option selected=\\\"selected\\\" value=\\\"2\\\">Third</option>\" + Environment.NewLine +\n                \"<option value=\\\"3\\\">Fourth</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        // ListBox\n\n        [Fact]\n        void ListBox_WithGroups()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n            const string expectedListBox = @\"<select id=\"\"List\"\" multiple=\"\"multiple\"\" name=\"\"List\"\"><option value=\"\"other1\"\">other1</option>\n<option value=\"\"other2\"\">other2</option>\n<optgroup label=\"\"Swedish Cars\"\">\n<option value=\"\"volvo\"\">Volvo</option>\n<option selected=\"\"selected\"\" value=\"\"saab\"\">Saab</option>\n</optgroup>\n<option value=\"\"other3\"\">other3</option>\n<optgroup>\n<option value=\"\"other4\"\">other4</option>\n<option value=\"\"other5\"\">other5</option>\n</optgroup>\n<optgroup label=\"\"German Cars\"\">\n<option value=\"\"mercedes-benz\"\">Mercedes-Benz</option>\n<option disabled=\"\"disabled\"\" value=\"\"audi\"\">Audi</option>\n</optgroup>\n<option value=\"\"other6\"\">other6</option>\n</select>\";\n\n            // Act\n            MvcHtmlString html = helper.ListBox(\"List\", GroupedItems);\n\n            // Assert\n            Assert.Equal(expectedListBox, html.ToHtmlString());\n        }\n\n        [Fact]\n        void ListBox_WithGroups_WithDisabled()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n            const string expectedListBox = @\"<select id=\"\"List\"\" multiple=\"\"multiple\"\" name=\"\"List\"\"><option value=\"\"a\"\">Alice</option>\n<optgroup disabled=\"\"disabled\"\" label=\"\"DisabledGroup\"\">\n<option value=\"\"b\"\">Bob</option>\n<option value=\"\"c\"\">Charlie</option>\n</optgroup>\n<option disabled=\"\"disabled\"\" value=\"\"d\"\">David</option>\n</select>\";\n\n            // Act\n            MvcHtmlString html = helper.ListBox(\"List\", GroupedItems_WithDisabled);\n\n            // Assert\n            Assert.Equal(expectedListBox, html.ToHtmlString());\n        }\n\n        [Fact]\n        void ListBox_MultiSelectList_WithGroups()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n            const string expectedListBox = @\"<select id=\"\"List\"\" multiple=\"\"multiple\"\" name=\"\"List\"\"><option value=\"\"ufo\"\">UFO</option>\n<optgroup label=\"\"Swedish Cars\"\">\n<option selected=\"\"selected\"\" value=\"\"volvo\"\">Volvo</option>\n<option value=\"\"saab\"\">Saab</option>\n</optgroup>\n<optgroup label=\"\"German Cars\"\">\n<option value=\"\"mercedes-benz\"\">Mercedes-Benz</option>\n<option selected=\"\"selected\"\" value=\"\"audi\"\">Audi</option>\n</optgroup>\n<option value=\"\"other\"\">Other</option>\n<optgroup label=\"\" \"\">\n<option value=\"\"unknown\"\">Unknown</option>\n</optgroup>\n</select>\";\n\n            // Act\n            MvcHtmlString html = helper.ListBox(\"List\", _multiSelectList);\n\n            // Assert\n            Assert.Equal(expectedListBox, html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxUsesExplicitValueIfNotProvidedInViewData()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            MultiSelectList selectList = new MultiSelectList(MultiSelectListTest.GetSampleAnonymousObjects(), \"Letter\", \"FullWord\", new[] { \"A\", \"C\" });\n\n            // Act\n            MvcHtmlString html = helper.ListBox(\"foo\", selectList);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option selected=\\\"selected\\\" value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxUsesExplicitValueIfNotProvidedInViewData_Unobtrusive()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            helper.ViewContext.ClientValidationEnabled = true;\n            helper.ViewContext.UnobtrusiveJavaScriptEnabled = true;\n            helper.ViewContext.FormContext = new FormContext();\n            helper.ClientValidationRuleFactory = (name, metadata) => new[] { new ModelClientValidationRule { ValidationType = \"type\", ErrorMessage = \"error\" } };\n            MultiSelectList selectList = new MultiSelectList(MultiSelectListTest.GetSampleAnonymousObjects(), \"Letter\", \"FullWord\", new[] { \"A\", \"C\" });\n\n            // Act\n            MvcHtmlString html = helper.ListBox(\"foo\", selectList);\n\n            // Assert\n            Assert.Equal(\n                \"<select data-val=\\\"true\\\" data-val-type=\\\"error\\\" id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option selected=\\\"selected\\\" value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxUsesViewDataDefaultValue()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(_listBoxViewData);\n            MultiSelectList selectList = new MultiSelectList(MultiSelectListTest.GetSampleStrings(), new[] { \"Charlie\" });\n\n            // Act\n            MvcHtmlString html = helper.ListBox(\"foo\", selectList);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithErrors()\n        {\n            // Arrange\n            ViewDataDictionary viewData = GetViewDataWithErrors();\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(viewData);\n            MultiSelectList list = new MultiSelectList(MultiSelectListTest.GetSampleStrings(), new[] { \"Charlie\" });\n\n            // Act\n            MvcHtmlString html = helper.ListBox(\"foo\", list);\n\n            // Assert\n            Assert.Equal(\n                \"<select class=\\\"input-validation-error\\\" id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithErrorsAndCustomClass()\n        {\n            // Arrange\n            ViewDataDictionary viewData = GetViewDataWithErrors();\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(viewData);\n            MultiSelectList selectList = new MultiSelectList(MultiSelectListTest.GetSampleStrings(), new[] { \"Charlie\" });\n\n            // Act\n            MvcHtmlString html = helper.ListBox(\"foo\", selectList, new { @class = \"foo-class\" });\n\n            // Assert\n            Assert.Equal(\n                \"<select class=\\\"input-validation-error foo-class\\\" id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithNameOnly()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n            helper.ViewData[\"foo\"] = new MultiSelectList(MultiSelectListTest.GetSampleStrings(), new[] { \"Charlie\" });\n\n            // Act\n            MvcHtmlString html = helper.ListBox(\"foo\");\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithAttributesDictionary()\n        {\n            // Arrange\n            ViewDataDictionary viewData = new ViewDataDictionary();\n            MultiSelectList selectList = new MultiSelectList(MultiSelectListTest.GetSampleStrings());\n            //viewData[\"foo\"] = selectList;\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString html = helper.ListBox(\"foo\", selectList, HtmlHelperTest.AttributesDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazValue\\\" id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithAttributesDictionaryAndMultiSelectList()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            MultiSelectList selectList = new MultiSelectList(MultiSelectListTest.GetSampleStrings());\n\n            // Act\n            MvcHtmlString html = helper.ListBox(\"foo\", selectList, HtmlHelperTest.AttributesDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazValue\\\" id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithAttributesDictionaryOverridesName()\n        {\n            // DevDiv Bugs #217602:\n            // SelectInternal() should override the user-provided 'name' attribute\n\n            // Arrange\n            ViewDataDictionary viewData = new ViewDataDictionary();\n            MultiSelectList selectList = new MultiSelectList(MultiSelectListTest.GetSampleStrings());\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            MvcHtmlString html = helper.ListBox(\"foo\", selectList, new { myAttr = \"myValue\", name = \"theName\" });\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" multiple=\\\"multiple\\\" myAttr=\\\"myValue\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithEmptyNameThrows()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { helper.ListBox(String.Empty, (MultiSelectList)null /* selectList */); },\n                \"name\");\n        }\n\n        [Fact]\n        public void ListBoxWithNullNameThrows()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { helper.ListBox(null /* name */, (MultiSelectList)null /* selectList */); },\n                \"name\");\n        }\n\n        [Fact]\n        public void ListBoxWithNullSelectListUsesViewData()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n            helper.ViewData[\"foo\"] = new MultiSelectList(MultiSelectListTest.GetSampleStrings(), new[] { \"Charlie\" });\n\n            // Act\n            MvcHtmlString html = helper.ListBox(\"foo\", null);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithObjectDictionary()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            MultiSelectList selectList = new MultiSelectList(MultiSelectListTest.GetSampleStrings());\n\n            // Act\n            MvcHtmlString html = helper.ListBox(\"foo\", selectList, HtmlHelperTest.AttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazObjValue\\\" id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithObjectDictionaryWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            MultiSelectList selectList = new MultiSelectList(MultiSelectListTest.GetSampleStrings());\n\n            // Act\n            MvcHtmlString html = helper.ListBox(\"foo\", selectList, HtmlHelperTest.AttributesObjectUnderscoresDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select foo-baz=\\\"BazObjValue\\\" id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithIEnumerableSelectListItem()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary { { \"foo\", MultiSelectListTest.GetSampleIEnumerableObjects() } };\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(vdd);\n\n            // Act\n            MvcHtmlString html = helper.ListBox(\"foo\");\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option value=\\\"123456789\\\">John</option>\" + Environment.NewLine\n              + \"<option value=\\\"987654321\\\">Jane</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"111111111\\\">Joe</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithIEnumerableOfSelectListItemMatchesEnumName()\n        {\n            // Arrange\n            ViewDataDictionary<IEnumerable<EnumWithDisplay?>> vdd = new ViewDataDictionary<IEnumerable<EnumWithDisplay?>>\n            {\n                { \"foo\", new EnumWithDisplay?[] { EnumWithDisplay.One, null, EnumWithDisplay.Three, }}\n            };\n            HtmlHelper<IEnumerable<EnumWithDisplay?>> helper = MvcHelper.GetHtmlHelper(vdd);\n\n            // Act\n            MvcHtmlString html =\n                helper.ListBox(\"foo\", GetSelectListWithNamedValuesForEnumWithDisplay(includeEmpty: true));\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\">\" +\n                \"<option selected=\\\"selected\\\" value=\\\"\\\"></option>\" + Environment.NewLine +\n                \"<option value=\\\"Zero\\\">Zero</option>\" + Environment.NewLine +\n                \"<option selected=\\\"selected\\\" value=\\\"One\\\">One</option>\" + Environment.NewLine +\n                \"<option value=\\\"Two\\\">Two</option>\" + Environment.NewLine +\n                \"<option selected=\\\"selected\\\" value=\\\"Three\\\">Three</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithIEnumerableOfSelectListItemMatchesEnumValue()\n        {\n            // Arrange\n            ViewDataDictionary<IEnumerable<EnumWithDisplay?>> vdd = new ViewDataDictionary<IEnumerable<EnumWithDisplay?>>\n            {\n                { \"foo\", new EnumWithDisplay?[] { EnumWithDisplay.One, null, EnumWithDisplay.Three, }}\n            };\n            HtmlHelper<IEnumerable<EnumWithDisplay?>> helper = MvcHelper.GetHtmlHelper(vdd);\n\n            // Act\n            MvcHtmlString html =\n                helper.ListBox(\"foo\", GetSelectListWithNumericValuesForEnumWithDisplay(includeEmpty: true));\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\">\" +\n                \"<option selected=\\\"selected\\\" value=\\\"\\\"></option>\" + Environment.NewLine +\n                \"<option value=\\\"0\\\">Zero</option>\" + Environment.NewLine +\n                \"<option selected=\\\"selected\\\" value=\\\"1\\\">One</option>\" + Environment.NewLine +\n                \"<option value=\\\"2\\\">Two</option>\" + Environment.NewLine +\n                \"<option selected=\\\"selected\\\" value=\\\"3\\\">Three</option>\" + Environment.NewLine +\n                \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxThrowsWhenExpressionDoesNotEvaluateToIEnumerable()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary { { \"foo\", 123456789 } };\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(vdd);\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => helper.ListBox(\"foo\", MultiSelectListTest.GetSampleIEnumerableObjects()),\n                \"The parameter 'expression' must evaluate to an IEnumerable when multiple selection is allowed.\"\n                );\n        }\n\n        [Fact]\n        public void ListBoxThrowsWhenExpressionEvaluatesToString()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary { { \"foo\", \"123456789\" } };\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(vdd);\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => helper.ListBox(\"foo\", MultiSelectListTest.GetSampleIEnumerableObjects()),\n                \"The parameter 'expression' must evaluate to an IEnumerable when multiple selection is allowed.\"\n                );\n        }\n\n        [Fact]\n        public void ListBoxWithListOfSelectListItemSelectsDefaultFromViewData()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary { { \"foo\", new string[] { \"123456789\", \"111111111\" } } };\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(vdd);\n\n            // Act\n            MvcHtmlString html = helper.ListBox(\"foo\", MultiSelectListTest.GetSampleListObjects());\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option selected=\\\"selected\\\" value=\\\"123456789\\\">John</option>\" + Environment.NewLine\n              + \"<option value=\\\"987654321\\\">Jane</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"111111111\\\">Joe</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithListOfSelectListItem()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary { { \"foo\", MultiSelectListTest.GetSampleListObjects() } };\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(vdd);\n\n            // Act\n            MvcHtmlString html = helper.ListBox(\"foo\");\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option value=\\\"123456789\\\">John</option>\" + Environment.NewLine\n              + \"<option value=\\\"987654321\\\">Jane</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"111111111\\\">Joe</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithPrefix()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            MultiSelectList selectList = new MultiSelectList(MultiSelectListTest.GetSampleStrings());\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.ListBox(\"foo\", selectList, HtmlHelperTest.AttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazObjValue\\\" id=\\\"MyPrefix_foo\\\" multiple=\\\"multiple\\\" name=\\\"MyPrefix.foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithPrefixAndEmptyName()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            MultiSelectList selectList = new MultiSelectList(MultiSelectListTest.GetSampleStrings());\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.ListBox(\"\", selectList, HtmlHelperTest.AttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazObjValue\\\" id=\\\"MyPrefix\\\" multiple=\\\"multiple\\\" name=\\\"MyPrefix\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithPrefixAndNullSelectListUsesViewData()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n            helper.ViewData[\"foo\"] = new MultiSelectList(MultiSelectListTest.GetSampleStrings(), new[] { \"Charlie\" });\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.ListBox(\"foo\");\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"MyPrefix_foo\\\" multiple=\\\"multiple\\\" name=\\\"MyPrefix.foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        // ListBoxFor\n\n        [Fact]\n        void ListBoxFor_WithGroups()\n        {\n            // Arrange\n            ViewDataDictionary<FooArrayModel> dict = new ViewDataDictionary<FooArrayModel>();\n            dict.Add(\"foo\", new[] { \"volvo\", \"audi\" });\n            HtmlHelper<FooArrayModel> helper = MvcHelper.GetHtmlHelper(dict);\n            const string expectedListBox = @\"<select id=\"\"foo\"\" multiple=\"\"multiple\"\" name=\"\"foo\"\"><option value=\"\"other1\"\">other1</option>\n<option value=\"\"other2\"\">other2</option>\n<optgroup label=\"\"Swedish Cars\"\">\n<option selected=\"\"selected\"\" value=\"\"volvo\"\">Volvo</option>\n<option value=\"\"saab\"\">Saab</option>\n</optgroup>\n<option value=\"\"other3\"\">other3</option>\n<optgroup>\n<option value=\"\"other4\"\">other4</option>\n<option value=\"\"other5\"\">other5</option>\n</optgroup>\n<optgroup label=\"\"German Cars\"\">\n<option value=\"\"mercedes-benz\"\">Mercedes-Benz</option>\n<option disabled=\"\"disabled\"\" selected=\"\"selected\"\" value=\"\"audi\"\">Audi</option>\n</optgroup>\n<option value=\"\"other6\"\">other6</option>\n</select>\";\n\n            // Act\n            MvcHtmlString html = helper.ListBoxFor(m => m.foo, GroupedItems);\n\n            // Assert\n            Assert.Equal(expectedListBox, html.ToHtmlString());\n        }\n\n        [Fact]\n        void ListBoxFor_WithGroups_WithDisabled()\n        {\n            // Arrange\n            ViewDataDictionary<FooArrayModel> dict = new ViewDataDictionary<FooArrayModel>();\n            dict.Add(\"foo\", new[] { \"a\", \"d\" });\n            HtmlHelper<FooArrayModel> helper = MvcHelper.GetHtmlHelper(dict);\n            const string expectedListBox = @\"<select id=\"\"foo\"\" multiple=\"\"multiple\"\" name=\"\"foo\"\"><option selected=\"\"selected\"\" value=\"\"a\"\">Alice</option>\n<optgroup disabled=\"\"disabled\"\" label=\"\"DisabledGroup\"\">\n<option value=\"\"b\"\">Bob</option>\n<option value=\"\"c\"\">Charlie</option>\n</optgroup>\n<option disabled=\"\"disabled\"\" selected=\"\"selected\"\" value=\"\"d\"\">David</option>\n</select>\";\n\n            // Act\n            MvcHtmlString html = helper.ListBoxFor(m => m.foo, GroupedItems_WithDisabled);\n\n            // Assert\n            Assert.Equal(expectedListBox, html.ToHtmlString());\n        }\n\n        [Fact]\n        void ListBoxFor_MultiSelectList_WithGroups()\n        {\n            // Arrange\n            ViewDataDictionary<FooArrayModel> dict = new ViewDataDictionary<FooArrayModel>();\n            dict.Add(\"foo\", new[] { \"mercedes-benz\", \"audi\" });\n            HtmlHelper<FooArrayModel> helper = MvcHelper.GetHtmlHelper(dict);\n            const string expectedListBox = @\"<select id=\"\"foo\"\" multiple=\"\"multiple\"\" name=\"\"foo\"\"><option value=\"\"ufo\"\">UFO</option>\n<optgroup label=\"\"Swedish Cars\"\">\n<option value=\"\"volvo\"\">Volvo</option>\n<option value=\"\"saab\"\">Saab</option>\n</optgroup>\n<optgroup label=\"\"German Cars\"\">\n<option selected=\"\"selected\"\" value=\"\"mercedes-benz\"\">Mercedes-Benz</option>\n<option selected=\"\"selected\"\" value=\"\"audi\"\">Audi</option>\n</optgroup>\n<option value=\"\"other\"\">Other</option>\n<optgroup label=\"\" \"\">\n<option value=\"\"unknown\"\">Unknown</option>\n</optgroup>\n</select>\";\n\n            // Act\n            MvcHtmlString html = helper.ListBoxFor(m => m.foo, _multiSelectList);\n\n            // Assert\n            Assert.Equal(expectedListBox, html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxForWithNullExpressionThrows()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary<FooModel>());\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => helper.ListBoxFor<FooModel, object>(null, null),\n                \"expression\");\n        }\n\n        [Fact]\n        public void ListBoxForUsesExplicitValueIfNotProvidedInViewData()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary<FooModel>());\n            MultiSelectList selectList = new MultiSelectList(MultiSelectListTest.GetSampleAnonymousObjects(), \"Letter\", \"FullWord\", new[] { \"A\", \"C\" });\n\n            // Act\n            MvcHtmlString html = helper.ListBoxFor(m => m.foo, selectList);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option selected=\\\"selected\\\" value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxForUsesExplicitValueIfNotProvidedInViewData_Unobtrusive()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary<FooModel>());\n            helper.ViewContext.ClientValidationEnabled = true;\n            helper.ViewContext.UnobtrusiveJavaScriptEnabled = true;\n            helper.ViewContext.FormContext = new FormContext();\n            helper.ClientValidationRuleFactory = (name, metadata) => new[] { new ModelClientValidationRule { ValidationType = \"type\", ErrorMessage = \"error\" } };\n            MultiSelectList selectList = new MultiSelectList(MultiSelectListTest.GetSampleAnonymousObjects(), \"Letter\", \"FullWord\", new[] { \"A\", \"C\" });\n\n            // Act\n            MvcHtmlString html = helper.ListBoxFor(m => m.foo, selectList);\n\n            // Assert\n            Assert.Equal(\n                \"<select data-val=\\\"true\\\" data-val-type=\\\"error\\\" id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option selected=\\\"selected\\\" value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void ListBoxForWithEnumerableModel_Unobtrusive()\n        {\n            // Arrange\n            HtmlHelper<IEnumerable<RequiredModel>> helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary<IEnumerable<RequiredModel>>());\n            helper.ViewContext.ClientValidationEnabled = true;\n            helper.ViewContext.UnobtrusiveJavaScriptEnabled = true;\n            helper.ViewContext.FormContext = new FormContext();\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            MultiSelectList selectList = new MultiSelectList(MultiSelectListTest.GetSampleAnonymousObjects(), \"Letter\",\n                \"FullWord\", new[] { \"C\" });\n\n            // Act\n            MvcHtmlString html = helper.ListBoxFor(m => m.ElementAt(0).foo, selectList);\n\n            // Assert\n            Assert.Equal(\n                \"<select data-val=\\\"true\\\" data-val-required=\\\"The foo field is required.\\\" id=\\\"MyPrefix_foo\\\" multiple=\\\"multiple\\\" name=\\\"MyPrefix.foo\\\"><option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxForUsesViewDataDefaultValue()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(_listBoxViewData);\n            MultiSelectList selectList = new MultiSelectList(MultiSelectListTest.GetSampleStrings(), new[] { \"Charlie\" });\n\n            // Act\n            MvcHtmlString html = helper.ListBoxFor(m => m.foo, selectList);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxForUsesLambdaDefaultValue()\n        {\n            // Arrange\n            FooArrayModel model = new FooArrayModel { foo = new[] { \"Bravo\" } };\n            HtmlHelper<FooArrayModel> helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary<FooArrayModel>(model));\n            SelectList selectList = new SelectList(MultiSelectListTest.GetSampleStrings());\n\n            // Act\n            MvcHtmlString html = helper.ListBoxFor(m => m.foo, selectList);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxForUsesLambdaDefaultValueWithNullSelectListUsesViewData()\n        {\n            // Arrange\n            FooArrayModel model = new FooArrayModel { foo = new[] { \"Bravo\" } };\n            ViewDataDictionary<FooArrayModel> vdd = new ViewDataDictionary<FooArrayModel>(model)\n            {\n                { \"foo\", new MultiSelectList(MultiSelectListTest.GetSampleStrings()) }\n            };\n            HtmlHelper<FooArrayModel> helper = MvcHelper.GetHtmlHelper(vdd);\n\n            // Act\n            MvcHtmlString html = helper.ListBoxFor(m => m.foo, selectList: null);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxForWithErrors()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetViewDataWithErrors());\n            MultiSelectList list = new MultiSelectList(MultiSelectListTest.GetSampleStrings(), new[] { \"Charlie\" });\n\n            // Act\n            MvcHtmlString html = helper.ListBoxFor(m => m.foo, list);\n\n            // Assert\n            Assert.Equal(\n                \"<select class=\\\"input-validation-error\\\" id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxForWithErrorsAndCustomClass()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetViewDataWithErrors());\n            MultiSelectList selectList = new MultiSelectList(MultiSelectListTest.GetSampleStrings(), new[] { \"Charlie\" });\n\n            // Act\n            MvcHtmlString html = helper.ListBoxFor(m => m.foo, selectList, new { @class = \"foo-class\" });\n\n            // Assert\n            Assert.Equal(\n                \"<select class=\\\"input-validation-error foo-class\\\" id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxForWithAttributesDictionary()\n        {\n            // Arrange\n            MultiSelectList selectList = new MultiSelectList(MultiSelectListTest.GetSampleStrings());\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary<FooModel>());\n\n            // Act\n            MvcHtmlString html = helper.ListBoxFor(m => m.foo, selectList, HtmlHelperTest.AttributesDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazValue\\\" id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxForWithAttributesDictionaryOverridesName()\n        {\n            // DevDiv Bugs #217602:\n            // SelectInternal() should override the user-provided 'name' attribute\n\n            // Arrange\n            MultiSelectList selectList = new MultiSelectList(MultiSelectListTest.GetSampleStrings());\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary<FooModel>());\n\n            // Act\n            MvcHtmlString html = helper.ListBoxFor(m => m.foo, selectList, new { myAttr = \"myValue\", name = \"theName\" });\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" multiple=\\\"multiple\\\" myAttr=\\\"myValue\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxForWithNullSelectListUsesViewData()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary<FooModel>());\n            helper.ViewContext.ViewData[\"foo\"] = new MultiSelectList(MultiSelectListTest.GetSampleStrings(), new[] { \"Charlie\" });\n\n            // Act\n            MvcHtmlString html = helper.ListBoxFor(m => m.foo, null);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxForWithObjectDictionary()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary<FooModel>());\n            MultiSelectList selectList = new MultiSelectList(MultiSelectListTest.GetSampleStrings());\n\n            // Act\n            MvcHtmlString html = helper.ListBoxFor(m => m.foo, selectList, HtmlHelperTest.AttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazObjValue\\\" id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxForWithObjectDictionaryWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary<FooModel>());\n            MultiSelectList selectList = new MultiSelectList(MultiSelectListTest.GetSampleStrings());\n\n            // Act\n            MvcHtmlString html = helper.ListBoxFor(m => m.foo, selectList, HtmlHelperTest.AttributesObjectUnderscoresDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select foo-baz=\\\"BazObjValue\\\" id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxForWithIEnumerableSelectListItem()\n        {\n            // Arrange\n            ViewDataDictionary<FooModel> vdd = new ViewDataDictionary<FooModel> { { \"foo\", MultiSelectListTest.GetSampleIEnumerableObjects() } };\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(vdd);\n\n            // Act\n            MvcHtmlString html = helper.ListBoxFor(m => m.foo, null);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option value=\\\"123456789\\\">John</option>\" + Environment.NewLine\n              + \"<option value=\\\"987654321\\\">Jane</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"111111111\\\">Joe</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxForThrowsWhenExpressionDoesNotEvaluateToIEnumerable()\n        {\n            // Arrange\n            ViewDataDictionary<NonIEnumerableModel> vdd = new ViewDataDictionary<NonIEnumerableModel> { { \"foo\", 123456789 } };\n            HtmlHelper<NonIEnumerableModel> helper = MvcHelper.GetHtmlHelper(vdd);\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => helper.ListBoxFor(m => m.foo, MultiSelectListTest.GetSampleIEnumerableObjects()),\n                \"The parameter 'expression' must evaluate to an IEnumerable when multiple selection is allowed.\"\n                );\n        }\n\n        [Fact]\n        public void ListBoxForThrowsWhenExpressionEvaluatesToString()\n        {\n            // Arrange\n            ViewDataDictionary<FooModel> vdd = new ViewDataDictionary<FooModel> { { \"foo\", \"123456789\" } };\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(vdd);\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => helper.ListBoxFor(m => m.foo, MultiSelectListTest.GetSampleIEnumerableObjects()),\n                \"The parameter 'expression' must evaluate to an IEnumerable when multiple selection is allowed.\"\n                );\n        }\n\n        [Fact]\n        public void ListBoxForWithListOfSelectListItemSelectsDefaultFromViewData()\n        {\n            // Arrange\n            ViewDataDictionary<FooModel> vdd = new ViewDataDictionary<FooModel> { { \"foo\", new string[] { \"123456789\", \"111111111\" } } };\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(vdd);\n\n            // Act\n            MvcHtmlString html = helper.ListBoxFor(m => m.foo, MultiSelectListTest.GetSampleListObjects());\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option selected=\\\"selected\\\" value=\\\"123456789\\\">John</option>\" + Environment.NewLine\n              + \"<option value=\\\"987654321\\\">Jane</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"111111111\\\">Joe</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxForWithListOfSelectListItem()\n        {\n            // Arrange\n            ViewDataDictionary<FooModel> vdd = new ViewDataDictionary<FooModel> { { \"foo\", MultiSelectListTest.GetSampleListObjects() } };\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(vdd);\n\n            // Act\n            MvcHtmlString html = helper.ListBoxFor(m => m.foo, null);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option value=\\\"123456789\\\">John</option>\" + Environment.NewLine\n              + \"<option value=\\\"987654321\\\">Jane</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"111111111\\\">Joe</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxForWithPrefix()\n        {\n            // Arrange\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(new ViewDataDictionary<FooModel>());\n            MultiSelectList selectList = new MultiSelectList(MultiSelectListTest.GetSampleStrings());\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.ListBoxFor(m => m.foo, selectList, HtmlHelperTest.AttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<select baz=\\\"BazObjValue\\\" id=\\\"MyPrefix_foo\\\" multiple=\\\"multiple\\\" name=\\\"MyPrefix.foo\\\"><option>Alpha</option>\" + Environment.NewLine\n              + \"<option>Bravo</option>\" + Environment.NewLine\n              + \"<option>Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxForWithPrefixAndListOfSelectListItemSelectsDefaultFromViewData()\n        {\n            // Arrange\n            ViewDataDictionary<FooModel> vdd = new ViewDataDictionary<FooModel> { { \"foo\", new string[] { \"123456789\", \"111111111\" } } };\n            HtmlHelper<FooModel> helper = MvcHelper.GetHtmlHelper(vdd);\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.ListBoxFor(m => m.foo, MultiSelectListTest.GetSampleListObjects());\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"MyPrefix_foo\\\" multiple=\\\"multiple\\\" name=\\\"MyPrefix.foo\\\"><option selected=\\\"selected\\\" value=\\\"123456789\\\">John</option>\" + Environment.NewLine\n              + \"<option value=\\\"987654321\\\">Jane</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"111111111\\\">Joe</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        // Culture tests\n\n        [Fact]\n        [ReplaceCulture]\n        public void SelectHelpersUseCurrentCultureToConvertValues()\n        {\n            // Arrange\n            HtmlHelper defaultValueHelper = MvcHelper.GetHtmlHelper(new ViewDataDictionary\n            {\n                { \"foo\", new[] { new DateTime(1900, 1, 1, 0, 0, 1) } },\n                { \"bar\", new DateTime(1900, 1, 1, 0, 0, 1) }\n            });\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n            SelectList selectList = new SelectList(GetSampleCultureAnonymousObjects(), \"Date\", \"FullWord\", new DateTime(1900, 1, 1, 0, 0, 0));\n\n            var tests = new[]\n            {\n                // DropDownList(name, selectList, optionLabel)\n                new\n                {\n                    Html = \"<select id=\\\"foo\\\" name=\\\"foo\\\"><option selected=\\\"selected\\\" value=\\\"01/01/1900 00:00:00\\\">Alpha</option>\" + Environment.NewLine\n                         + \"<option value=\\\"01/01/1900 00:00:01\\\">Bravo</option>\" + Environment.NewLine\n                         + \"<option value=\\\"01/01/1900 00:00:02\\\">Charlie</option>\" + Environment.NewLine\n                         + \"</select>\",\n                    Action = new Func<MvcHtmlString>(() => helper.DropDownList(\"foo\", selectList, (string)null))\n                },\n                // DropDownList(name, selectList, optionLabel) (With default value selected from ViewData)\n                new\n                {\n                    Html = \"<select id=\\\"bar\\\" name=\\\"bar\\\"><option value=\\\"01/01/1900 00:00:00\\\">Alpha</option>\" + Environment.NewLine\n                         + \"<option selected=\\\"selected\\\" value=\\\"01/01/1900 00:00:01\\\">Bravo</option>\" + Environment.NewLine\n                         + \"<option value=\\\"01/01/1900 00:00:02\\\">Charlie</option>\" + Environment.NewLine\n                         + \"</select>\",\n                    Action = new Func<MvcHtmlString>(() => defaultValueHelper.DropDownList(\"bar\", selectList, (string)null))\n                },\n                // ListBox(name, selectList)\n                new\n                {\n                    Html = \"<select id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option selected=\\\"selected\\\" value=\\\"01/01/1900 00:00:00\\\">Alpha</option>\" + Environment.NewLine\n                         + \"<option value=\\\"01/01/1900 00:00:01\\\">Bravo</option>\" + Environment.NewLine\n                         + \"<option value=\\\"01/01/1900 00:00:02\\\">Charlie</option>\" + Environment.NewLine\n                         + \"</select>\",\n                    Action = new Func<MvcHtmlString>(() => helper.ListBox(\"foo\", selectList))\n                },\n                // ListBox(name, selectList) (With default value selected from ViewData)\n                new\n                {\n                    Html = \"<select id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\"><option value=\\\"01/01/1900 00:00:00\\\">Alpha</option>\" + Environment.NewLine\n                         + \"<option selected=\\\"selected\\\" value=\\\"01/01/1900 00:00:01\\\">Bravo</option>\" + Environment.NewLine\n                         + \"<option value=\\\"01/01/1900 00:00:02\\\">Charlie</option>\" + Environment.NewLine\n                         + \"</select>\",\n                    Action = new Func<MvcHtmlString>(() => defaultValueHelper.ListBox(\"foo\", selectList))\n                }\n            };\n\n            // Act && Assert\n            foreach (var test in tests)\n            {\n                Assert.Equal(test.Html, test.Action().ToHtmlString());\n            }\n        }\n\n        // Helpers\n\n        // Value and Text is constant name in all returned SelectListItem objects.\n        private static IEnumerable<SelectListItem> GetSelectListWithNamedValuesForEnumWithDisplay(bool includeEmpty)\n        {\n            IList<SelectListItem> selectList = new List<SelectListItem>();\n            if (includeEmpty)\n            {\n                // Similar to what we might generate for a Nullable<T>\n                selectList.Add(new SelectListItem { Text = String.Empty, Value = String.Empty, });\n            }\n\n            foreach (string name in Enum.GetNames(typeof(EnumWithDisplay)))\n            {\n                selectList.Add(new SelectListItem { Text = name, Value = name, });\n            }\n\n            return selectList;\n        }\n\n        // Value is numeric value while Text is constant name in all returned SelectListItem objects.\n        private static IEnumerable<SelectListItem> GetSelectListWithNumericValuesForEnumWithDisplay(bool includeEmpty)\n        {\n            IList<SelectListItem> selectList = new List<SelectListItem>();\n            if (includeEmpty)\n            {\n                // Similar to what we might generate for a Nullable<T>\n                selectList.Add(new SelectListItem { Text = String.Empty, Value = String.Empty, });\n            }\n\n            foreach (FieldInfo field in typeof(EnumWithDisplay).GetFields(\n                BindingFlags.DeclaredOnly | BindingFlags.GetField | BindingFlags.Public | BindingFlags.Static))\n            {\n                string name = field.Name;\n                object value = field.GetRawConstantValue();\n                selectList.Add(new SelectListItem { Text = name, Value = value.ToString(), });\n            }\n\n            return selectList;\n        }\n\n        private class FooContainerModel\n        {\n            public FooModel inner { get; set; }\n        }\n        private class FooModel\n        {\n            public string foo { get; set; }\n        }\n\n        private class FooBarModel : FooModel\n        {\n            public string bar { get; set; }\n        }\n\n        private class FooArrayModel\n        {\n            public string[] foo { get; set; }\n        }\n\n        private class NonIEnumerableModel\n        {\n            public int foo { get; set; }\n        }\n\n        private static ViewDataDictionary<FooBarModel> GetViewDataWithErrors()\n        {\n            ViewDataDictionary<FooBarModel> viewData = new ViewDataDictionary<FooBarModel> { { \"foo\", \"ViewDataFoo\" } };\n            viewData.Model = new FooBarModel { foo = \"ViewItemFoo\", bar = \"ViewItemBar\" };\n\n            ModelState modelStateFoo = new ModelState();\n            modelStateFoo.Errors.Add(new ModelError(\"foo error 1\"));\n            modelStateFoo.Errors.Add(new ModelError(\"foo error 2\"));\n            viewData.ModelState[\"foo\"] = modelStateFoo;\n            modelStateFoo.Value = new ValueProviderResult(new string[] { \"Bravo\", \"Charlie\" }, \"Bravo\", CultureInfo.InvariantCulture);\n\n            return viewData;\n        }\n\n        internal static IEnumerable GetSampleCultureAnonymousObjects()\n        {\n            return new[]\n            {\n                new { Date = new DateTime(1900, 1, 1, 0, 0, 0), FullWord = \"Alpha\" },\n                new { Date = new DateTime(1900, 1, 1, 0, 0, 1), FullWord = \"Bravo\" },\n                new { Date = new DateTime(1900, 1, 1, 0, 0, 2), FullWord = \"Charlie\" }\n            };\n        }\n\n        private class RequiredModel\n        {\n            [Required]\n            public string foo { get; set; }\n        }\n\n        private class EnumModel\n        {\n            public EnumWithDisplay WithDisplay { get; set; }\n            public EnumWithDuplicates WithDuplicates { get; set; }\n            public EnumWithFlags WithFlags { get; set; }\n            public EnumWithDisplay? WithNullable { get; set; }\n            public EnumWithoutAnything WithoutAnything { get; set; }\n        }\n\n        // enum definitions\n\n        private enum EnumWithDisplay : byte\n        {\n            [Display(Name = \"First\")]\n            Zero,\n            [Display(Name = \"Second\")]\n            One,\n            [Display(Name = \"Third\")]\n            Two,\n            [Display(Name = \"Fourth\")]\n            Three,\n        }\n\n        private enum EnumWithDuplicates : byte\n        {\n            First,\n            Second,\n            Third = 1,\n            Fourth,\n        }\n\n        private enum EnumWithoutAnything : byte\n        {\n        }\n\n        [Flags]\n        private enum EnumWithFlags : byte\n        {\n            First = 1,\n            Second = 2,\n            Third = 4,\n            Fourth = 8,\n        }\n\n        public void Dispose()\n        {\n            // Reset ScopeStorage (written via e.g. ViewContext.ClientValidationEnabled) between tests to avoid unexpected interactions.\n            ScopeStorage.CurrentProvider = new StaticScopeStorageProvider();\n            ScopeStorage.GlobalScope.Clear();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Html/Test/TemplateHelpersSafeScope.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.WebPages.Scope;\nusing Moq;\n\nnamespace System.Web.Mvc.Html.Test\n{\n    /// <summary>\n    /// A scope within which it is safe to invoke <see cref=\"TemplateHelpers\"/> methods. For example\n    /// <see cref=\"TemplateHelpers.ExecuteTemplate()\"/> invokes <code>ViewEngines.Engines.FindPartialView()</code> and\n    /// clones the current <see cref=\"ViewContext\"/>.\n    /// </summary>\n    /// <remarks>Similar to TemplateHelpersTest.MockViewEngine but FindPartialView() succeed there and fail here. In\n    /// addition TemplateHelpersTest tests do not continue far enough to need the transient scope.\n    /// </remarks>\n    public class TemplateHelpersSafeScope : IDisposable\n    {\n        private readonly List<IViewEngine> _oldEngines;\n        private IDisposable _transientScope;\n\n        public TemplateHelpersSafeScope()\n        {\n            // Copying an HtmlHelper instance reads and writes the current StorageScope.\n            // Ensure that's not the global scope.\n            _transientScope = ScopeStorage.CreateTransientScope();\n\n            // Do not want templates to check disk for anything.\n            var engine = new Mock<IViewEngine>(MockBehavior.Strict);\n            engine\n                .Setup(e => e.FindPartialView(It.IsAny<ControllerContext>(), It.IsAny<string>(), It.IsAny<bool>()))\n                .Returns(new ViewEngineResult(Enumerable.Empty<string>()));\n\n            _oldEngines = ViewEngines.Engines.ToList();\n            ViewEngines.Engines.Clear();\n            ViewEngines.Engines.Add(engine.Object);\n        }\n\n        public void Dispose()\n        {\n            ViewEngines.Engines.Clear();\n            foreach (var oldEngine in _oldEngines)\n            {\n                ViewEngines.Engines.Add(oldEngine);\n            }\n\n            using (_transientScope)\n            {\n                _transientScope = null;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Html/Test/TemplateHelpersTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Net;\nusing System.Threading;\nusing System.Web.Routing;\nusing System.Web.UI.WebControls;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\nusing Moq;\n\nnamespace System.Web.Mvc.Html.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")]\n    public class TemplateHelpersTest\n    {\n        // ExecuteTemplate\n\n        private class ExecuteTemplateModel\n        {\n            public string MyProperty { get; set; }\n            public Nullable<int> MyNullableProperty { get; set; }\n        }\n\n        [Fact]\n        public void ExecuteTemplateCallsGetViewNamesWithProvidedTemplateNameAndMetadataInformation()\n        {\n            using (new MockViewEngine())\n            {\n                // Arrange\n                HtmlHelper html = MakeHtmlHelper(new ExecuteTemplateModel());\n                ModelMetadata metadata = ModelMetadata.FromStringExpression(\"MyProperty\", html.ViewData);\n                metadata.TemplateHint = \"templateHint\";\n                metadata.DataTypeName = \"dataType\";\n                string[] hints = null;\n\n                // Act\n                TemplateHelpers.ExecuteTemplate(\n                    html, MakeViewData(html, metadata), \"templateName\", DataBoundControlMode.ReadOnly,\n                    (_metadata, _hints) =>\n                    {\n                        hints = _hints;\n                        return new[] { \"String\" };\n                    },\n                    TemplateHelpers.GetDefaultActions);\n\n                // Assert\n                Assert.NotNull(hints);\n                Assert.Equal(3, hints.Length);\n                Assert.Equal(\"templateName\", hints[0]);\n                Assert.Equal(\"templateHint\", hints[1]);\n                Assert.Equal(\"dataType\", hints[2]);\n            }\n        }\n\n        [Fact]\n        public void ExecuteTemplateUsesViewFromViewEngineInReadOnlyMode()\n        {\n            using (MockViewEngine engine = new MockViewEngine())\n            {\n                // Arrange\n                HtmlHelper html = MakeHtmlHelper(new ExecuteTemplateModel { MyProperty = \"Hello\" });\n                ModelMetadata metadata = ModelMetadata.FromStringExpression(\"MyProperty\", html.ViewData);\n                ViewContext callbackViewContext = null;\n                engine.Engine.Setup(e => e.FindPartialView(html.ViewContext, \"DisplayTemplates/String\", true))\n                    .Returns(new ViewEngineResult(engine.View.Object, engine.Engine.Object))\n                    .Verifiable();\n                engine.View.Setup(v => v.Render(It.IsAny<ViewContext>(), It.IsAny<TextWriter>()))\n                    .Callback<ViewContext, TextWriter>((vc, tw) =>\n                    {\n                        callbackViewContext = vc;\n                        tw.Write(\"View Text\");\n                    })\n                    .Verifiable();\n                ViewDataDictionary viewData = MakeViewData(html, metadata);\n\n                // Act\n                string result = TemplateHelpers.ExecuteTemplate(\n                    html, viewData, \"templateName\", DataBoundControlMode.ReadOnly,\n                    delegate { return new[] { \"String\" }; },\n                    TemplateHelpers.GetDefaultActions);\n\n                // Assert\n                engine.Engine.Verify();\n                engine.View.Verify();\n                Assert.Equal(\"View Text\", result);\n                Assert.Same(engine.View.Object, callbackViewContext.View);\n                Assert.Same(viewData, callbackViewContext.ViewData);\n                Assert.Same(html.ViewContext.TempData, callbackViewContext.TempData);\n                TemplateHelpers.ActionCacheViewItem cacheItem = TemplateHelpers.GetActionCache(html)[\"DisplayTemplates/String\"] as TemplateHelpers.ActionCacheViewItem;\n                Assert.NotNull(cacheItem);\n                Assert.Equal(\"DisplayTemplates/String\", cacheItem.ViewName);\n            }\n        }\n\n        [Fact]\n        public void ExecuteTemplateUsesViewFromViewEngineInEditMode()\n        {\n            using (MockViewEngine engine = new MockViewEngine())\n            {\n                // Arrange\n                HtmlHelper html = MakeHtmlHelper(new ExecuteTemplateModel { MyProperty = \"Hello\" });\n                ModelMetadata metadata = ModelMetadata.FromStringExpression(\"MyProperty\", html.ViewData);\n                ViewContext callbackViewContext = null;\n                engine.Engine.Setup(e => e.FindPartialView(html.ViewContext, \"EditorTemplates/String\", true))\n                    .Returns(new ViewEngineResult(engine.View.Object, engine.Engine.Object))\n                    .Verifiable();\n                engine.View.Setup(v => v.Render(It.IsAny<ViewContext>(), It.IsAny<TextWriter>()))\n                    .Callback<ViewContext, TextWriter>((vc, tw) =>\n                    {\n                        callbackViewContext = vc;\n                        tw.Write(\"View Text\");\n                    })\n                    .Verifiable();\n                ViewDataDictionary viewData = MakeViewData(html, metadata);\n\n                // Act\n                string result = TemplateHelpers.ExecuteTemplate(\n                    html, viewData, \"templateName\", DataBoundControlMode.Edit,\n                    delegate { return new[] { \"String\" }; },\n                    TemplateHelpers.GetDefaultActions);\n\n                // Assert\n                engine.Engine.Verify();\n                engine.View.Verify();\n                Assert.Equal(\"View Text\", result);\n                Assert.Same(engine.View.Object, callbackViewContext.View);\n                Assert.Same(viewData, callbackViewContext.ViewData);\n                Assert.Same(html.ViewContext.TempData, callbackViewContext.TempData);\n                TemplateHelpers.ActionCacheViewItem cacheItem = TemplateHelpers.GetActionCache(html)[\"EditorTemplates/String\"] as TemplateHelpers.ActionCacheViewItem;\n                Assert.NotNull(cacheItem);\n                Assert.Equal(\"EditorTemplates/String\", cacheItem.ViewName);\n            }\n        }\n\n        [Fact]\n        public void ExecuteTemplateUsesViewFromDefaultActionsInReadOnlyMode()\n        {\n            using (MockViewEngine engine = new MockViewEngine())\n            {\n                // Arrange\n                HtmlHelper html = MakeHtmlHelper(new ExecuteTemplateModel { MyProperty = \"Hello\" });\n                ModelMetadata metadata = ModelMetadata.FromStringExpression(\"MyProperty\", html.ViewData);\n                engine.Engine.Setup(e => e.FindPartialView(html.ViewContext, \"DisplayTemplates/String\", It.IsAny<bool>()))\n                    .Returns(new ViewEngineResult(new string[0]))\n                    .Verifiable();\n                ViewDataDictionary viewData = MakeViewData(html, metadata);\n\n                // Act\n                TemplateHelpers.ExecuteTemplate(\n                    html, viewData, \"templateName\", DataBoundControlMode.ReadOnly,\n                    delegate { return new[] { \"String\" }; },\n                    TemplateHelpers.GetDefaultActions);\n\n                // Assert\n                engine.Engine.Verify();\n                TemplateHelpers.ActionCacheCodeItem cacheItem = TemplateHelpers.GetActionCache(html)[\"DisplayTemplates/String\"] as TemplateHelpers.ActionCacheCodeItem;\n                Assert.NotNull(cacheItem);\n                Assert.Equal(DefaultDisplayTemplates.StringTemplate, cacheItem.Action);\n            }\n        }\n\n        [Fact]\n        public void ExecuteTemplateUsesViewFromDefaultActionsInEditMode()\n        {\n            using (MockViewEngine engine = new MockViewEngine())\n            {\n                // Arrange\n                HtmlHelper html = MakeHtmlHelper(new ExecuteTemplateModel { MyProperty = \"Hello\" });\n                ModelMetadata metadata = ModelMetadata.FromStringExpression(\"MyProperty\", html.ViewData);\n                engine.Engine.Setup(e => e.FindPartialView(html.ViewContext, \"EditorTemplates/String\", It.IsAny<bool>()))\n                    .Returns(new ViewEngineResult(new string[0]))\n                    .Verifiable();\n                ViewDataDictionary viewData = MakeViewData(html, metadata);\n\n                // Act\n                TemplateHelpers.ExecuteTemplate(\n                    html, viewData, \"templateName\", DataBoundControlMode.Edit,\n                    delegate { return new[] { \"String\" }; },\n                    TemplateHelpers.GetDefaultActions);\n\n                // Assert\n                engine.Engine.Verify();\n                TemplateHelpers.ActionCacheCodeItem cacheItem = TemplateHelpers.GetActionCache(html)[\"EditorTemplates/String\"] as TemplateHelpers.ActionCacheCodeItem;\n                Assert.NotNull(cacheItem);\n                Assert.Equal(DefaultEditorTemplates.StringTemplate, cacheItem.Action);\n            }\n        }\n\n        [Fact]\n        public void ExecuteTemplatePrefersExistingActionCacheItem()\n        {\n            using (MockViewEngine engine = new MockViewEngine())\n            {\n                // Arrange\n                HtmlHelper html = MakeHtmlHelper(new ExecuteTemplateModel { MyProperty = \"Hello\" });\n                ModelMetadata metadata = ModelMetadata.FromStringExpression(\"MyProperty\", html.ViewData);\n                ViewDataDictionary viewData = MakeViewData(html, metadata);\n                TemplateHelpers.GetActionCache(html).Add(\"EditorTemplates/String\",\n                                                         new TemplateHelpers.ActionCacheCodeItem { Action = _ => \"Action Text\" });\n\n                // Act\n                string result = TemplateHelpers.ExecuteTemplate(\n                    html, viewData, \"templateName\", DataBoundControlMode.Edit,\n                    delegate { return new[] { \"String\" }; },\n                    TemplateHelpers.GetDefaultActions);\n\n                // Assert\n                engine.Engine.Verify();\n                engine.Engine.Verify(e => e.FindPartialView(It.IsAny<ControllerContext>(), It.IsAny<string>(), It.IsAny<bool>()), Times.Never());\n                Assert.Equal(\"Action Text\", result);\n            }\n        }\n\n        [Fact]\n        public void ExecuteTemplateThrowsWhenNoTemplatesMatch()\n        {\n            using (new MockViewEngine())\n            {\n                // Arrange\n                HtmlHelper html = MakeHtmlHelper(new ExecuteTemplateModel { MyProperty = \"Hello\" });\n                ModelMetadata metadata = ModelMetadata.FromStringExpression(\"MyProperty\", html.ViewData);\n                ViewDataDictionary viewData = MakeViewData(html, metadata);\n\n                // Act & Assert\n                Assert.Throws<InvalidOperationException>(\n                    () => TemplateHelpers.ExecuteTemplate(html, viewData, \"templateName\", DataBoundControlMode.Edit, delegate { return new string[0]; }, TemplateHelpers.GetDefaultActions),\n                    \"Unable to locate an appropriate template for type System.String.\");\n            }\n        }\n\n        [Fact]\n        public void ExecuteTemplateCreatesNewHtmlHelperWithCorrectViewDataForDefaultAction()\n        {\n            using (MockViewEngine engine = new MockViewEngine(false))\n            {\n                // Arrange\n                HtmlHelper html = MakeHtmlHelper(new ExecuteTemplateModel { MyProperty = \"Hello\" });\n                ModelMetadata metadata = ModelMetadata.FromStringExpression(\"MyProperty\", html.ViewData);\n                ViewDataDictionary viewData = MakeViewData(html, metadata);\n                HtmlHelper passedHtmlHelper = null;\n\n                // Act\n                TemplateHelpers.ExecuteTemplate(\n                    html, viewData, \"templateName\", DataBoundControlMode.Edit,\n                    delegate { return new[] { \"String\" }; },\n                    delegate\n                    {\n                        return new Dictionary<string, Func<HtmlHelper, string>>\n                        {\n                            {\n                                \"String\", _htmlHelper =>\n                                {\n                                    passedHtmlHelper = _htmlHelper;\n                                    return \"content\";\n                                }\n                                }\n                        };\n                    });\n\n                // Assert\n                Assert.NotNull(passedHtmlHelper);\n                Assert.Same(passedHtmlHelper.ViewData, passedHtmlHelper.ViewContext.ViewData);\n                Assert.NotSame(html.ViewData, passedHtmlHelper.ViewData);\n            }\n        }\n\n        [Fact]\n        public void ExecuteTemplateCreatesNewHtmlHelperWithCorrectViewDataForCachedAction()\n        {\n            using (MockViewEngine engine = new MockViewEngine())\n            {\n                // Arrange\n                HtmlHelper html = MakeHtmlHelper(new ExecuteTemplateModel { MyProperty = \"Hello\" });\n                ModelMetadata metadata = ModelMetadata.FromStringExpression(\"MyProperty\", html.ViewData);\n                ViewDataDictionary viewData = MakeViewData(html, metadata);\n                HtmlHelper passedHtmlHelper = null;\n                TemplateHelpers.GetActionCache(html).Add(\n                    \"EditorTemplates/String\",\n                    new TemplateHelpers.ActionCacheCodeItem\n                    {\n                        Action = _htmlHelper =>\n                        {\n                            passedHtmlHelper = _htmlHelper;\n                            return \"content\";\n                        }\n                    });\n\n                // Act\n                string result = TemplateHelpers.ExecuteTemplate(\n                    html, viewData, \"templateName\", DataBoundControlMode.Edit,\n                    delegate { return new[] { \"String\" }; },\n                    TemplateHelpers.GetDefaultActions);\n\n                // Assert\n                Assert.NotNull(passedHtmlHelper);\n                Assert.Same(passedHtmlHelper.ViewData, passedHtmlHelper.ViewContext.ViewData);\n                Assert.NotSame(html.ViewData, passedHtmlHelper.ViewData);\n            }\n        }\n\n        // GetActionCache\n\n        [Fact]\n        public void CacheIsCreatedIfNotPresent()\n        {\n            // Arrange\n            Hashtable items = new Hashtable();\n            Mock<HttpContextBase> context = new Mock<HttpContextBase>();\n            context.Setup(c => c.Items).Returns(items);\n            Mock<ViewContext> viewContext = new Mock<ViewContext>();\n            viewContext.Setup(c => c.HttpContext).Returns(context.Object);\n            Mock<IViewDataContainer> viewDataContainer = new Mock<IViewDataContainer>();\n            HtmlHelper helper = new HtmlHelper(viewContext.Object, viewDataContainer.Object);\n\n            // Act\n            Dictionary<string, TemplateHelpers.ActionCacheItem> cache = TemplateHelpers.GetActionCache(helper);\n\n            // Assert\n            Assert.NotNull(cache);\n            Assert.Empty(cache);\n            Assert.Contains((object)cache, items.Values.OfType<object>());\n        }\n\n        [Fact]\n        public void CacheIsReusedIfPresent()\n        {\n            // Arrange\n            Hashtable items = new Hashtable();\n            Mock<HttpContextBase> context = new Mock<HttpContextBase>();\n            context.Setup(c => c.Items).Returns(items);\n            Mock<ViewContext> viewContext = new Mock<ViewContext>();\n            viewContext.Setup(c => c.HttpContext).Returns(context.Object);\n            Mock<IViewDataContainer> viewDataContainer = new Mock<IViewDataContainer>();\n            HtmlHelper helper = new HtmlHelper(viewContext.Object, viewDataContainer.Object);\n\n            // Act\n            Dictionary<string, TemplateHelpers.ActionCacheItem> cache1 = TemplateHelpers.GetActionCache(helper);\n            Dictionary<string, TemplateHelpers.ActionCacheItem> cache2 = TemplateHelpers.GetActionCache(helper);\n\n            // Assert\n            Assert.NotNull(cache1);\n            Assert.Same(cache1, cache2);\n        }\n\n        // GetViewNames\n\n        // Sample value types; some special cases below as well e.g. GetViewNamesFullOrderingOfString()\n        [Theory]\n        [InlineData(typeof(bool), \"Boolean\")]\n        [InlineData(typeof(byte), \"Byte\")]\n        [InlineData(typeof(char), \"Char\")]\n        [InlineData(typeof(DateTime), \"DateTime\")]\n        [InlineData(typeof(decimal), \"Decimal\")]\n        [InlineData(typeof(double), \"Double\")]\n        [InlineData(typeof(float), \"Single\")]\n        [InlineData(typeof(Guid), \"Guid\")]\n        [InlineData(typeof(TimeSpan), \"TimeSpan\")]\n        [InlineData(typeof(int), \"Int32\")]\n        [InlineData(typeof(ulong), \"UInt64\")]\n        public void GetViewNamesFullOrderingOfBuiltInValueType(Type type, string expectedTypeName)\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(null, type);\n\n            // Act\n            List<string> result = TemplateHelpers.GetViewNames(metadata, \"UIHint\", \"DataType\").ToList();\n\n            // Assert\n            Assert.Equal(4, result.Count);\n            Assert.Equal(\"UIHint\", result[0]);\n            Assert.Equal(\"DataType\", result[1]);\n            Assert.Equal(expectedTypeName, result[2]);\n            Assert.Equal(\"String\", result[3]);\n        }\n\n        [Fact]\n        public void GetViewNamesFullOrderingOfComplexType()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(HttpWebRequest));\n\n            // Act\n            List<string> result = TemplateHelpers.GetViewNames(metadata, \"UIHint\", \"DataType\").ToList();\n\n            // Assert\n            Assert.Equal(6, result.Count);\n            Assert.Equal(\"UIHint\", result[0]);\n            Assert.Equal(\"DataType\", result[1]);\n            Assert.Equal(\"HttpWebRequest\", result[2]);\n            Assert.Equal(\"WebRequest\", result[3]);\n            Assert.Equal(\"MarshalByRefObject\", result[4]);\n            Assert.Equal(\"Object\", result[5]);\n        }\n\n        [Fact]\n        public void GetViewNamesFullOrderingOfInterface()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(IDisposable));\n\n            // Act\n            List<string> result = TemplateHelpers.GetViewNames(metadata, \"UIHint\", \"DataType\").ToList();\n\n            // Assert\n            Assert.Equal(4, result.Count);\n            Assert.Equal(\"UIHint\", result[0]);\n            Assert.Equal(\"DataType\", result[1]);\n            Assert.Equal(\"IDisposable\", result[2]);\n            Assert.Equal(\"Object\", result[3]);\n        }\n\n        [Fact]\n        public void GetViewNamesFullOrderingOfComplexTypeThatImplementsIEnumerable()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(List<int>));\n\n            // Act\n            List<string> result = TemplateHelpers.GetViewNames(metadata, \"UIHint\", \"DataType\").ToList();\n\n            // Assert\n            Assert.Equal(5, result.Count);\n            Assert.Equal(\"UIHint\", result[0]);\n            Assert.Equal(\"DataType\", result[1]);\n            Assert.Equal(\"List`1\", result[2]);\n            Assert.Equal(\"Collection\", result[3]);\n            Assert.Equal(\"Object\", result[4]);\n        }\n\n        [Fact]\n        public void GetViewNamesFullOrderingOfInterfaceThatRequiresIEnumerable()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(IList<int>));\n\n            // Act\n            List<string> result = TemplateHelpers.GetViewNames(metadata, \"UIHint\", \"DataType\").ToList();\n\n            // Assert\n            Assert.Equal(5, result.Count);\n            Assert.Equal(\"UIHint\", result[0]);\n            Assert.Equal(\"DataType\", result[1]);\n            Assert.Equal(\"IList`1\", result[2]);\n            Assert.Equal(\"Collection\", result[3]);\n            Assert.Equal(\"Object\", result[4]);\n        }\n\n        [Fact]\n        public void GetViewNamesFullOrderingOfString()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(String));\n\n            // Act\n            List<string> result = TemplateHelpers.GetViewNames(metadata, \"UIHint\", \"DataType\").ToList();\n\n            // Assert\n            Assert.Equal(3, result.Count);\n            Assert.Equal(\"UIHint\", result[0]);\n            Assert.Equal(\"DataType\", result[1]);\n            Assert.Equal(\"String\", result[2]);\n        }\n\n        [Fact]\n        public void GetViewNamesFullOrderingOfEnumStruct()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(StringSplitOptions));\n\n            // Act\n            List<string> result = TemplateHelpers.GetViewNames(metadata, \"UIHint\", \"DataType\").ToList();\n\n            // Assert\n            Assert.Equal(5, result.Count);\n            Assert.Equal(\"UIHint\", result[0]);\n            Assert.Equal(\"DataType\", result[1]);\n            Assert.Equal(\"StringSplitOptions\", result[2]);\n            Assert.Equal(\"Enum\", result[3]);\n            Assert.Equal(\"String\", result[4]);\n        }\n\n        [Fact]\n        public void GetViewNamesFullOrderingOfEnumType()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(Enum));\n\n            // Act\n            List<string> result = TemplateHelpers.GetViewNames(metadata, \"UIHint\", \"DataType\").ToList();\n\n            // Assert\n            Assert.Equal(4, result.Count);\n            Assert.Equal(\"UIHint\", result[0]);\n            Assert.Equal(\"DataType\", result[1]);\n            Assert.Equal(\"Enum\", result[2]);\n            Assert.Equal(\"String\", result[3]);\n        }\n\n        [Fact]\n        public void GetViewNamesFullOrderingOfDateTimeOffset()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(DateTimeOffset));\n\n            // Act\n            List<string> result = TemplateHelpers.GetViewNames(metadata, \"UIHint\", \"DataType\").ToList();\n\n            // Assert\n            Assert.Equal(5, result.Count);\n            Assert.Equal(\"UIHint\", result[0]);\n            Assert.Equal(\"DataType\", result[1]);\n            Assert.Equal(\"DateTimeOffset\", result[2]);\n            Assert.Equal(\"DateTime\", result[3]);\n            Assert.Equal(\"String\", result[4]);\n        }\n\n        [Fact]\n        public void GetViewNamesNullUIHintNotIncludedInList()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(Object));\n\n            // Act\n            List<string> result = TemplateHelpers.GetViewNames(metadata, null, \"DataType\").ToList();\n\n            // Assert\n            Assert.Equal(2, result.Count);\n            Assert.Equal(\"DataType\", result[0]);\n            Assert.Equal(\"Object\", result[1]);\n        }\n\n        [Fact]\n        public void GetViewNamesNullDataTypeNotIncludedInList()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(Object));\n\n            // Act\n            List<string> result = TemplateHelpers.GetViewNames(metadata, \"UIHint\", null).ToList();\n\n            // Assert\n            Assert.Equal(2, result.Count);\n            Assert.Equal(\"UIHint\", result[0]);\n            Assert.Equal(\"Object\", result[1]);\n        }\n\n        [Fact]\n        public void GetViewNamesConvertsNullableOfTIntoT()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(Nullable<int>));\n\n            // Act\n            List<string> result = TemplateHelpers.GetViewNames(metadata, null, null).ToList();\n\n            // Assert\n            Assert.Equal(2, result.Count);\n            Assert.Equal(\"Int32\", result[0]);\n            Assert.Equal(\"String\", result[1]);\n        }\n\n        // Template\n\n        private class TemplateModel\n        {\n            public object MyProperty { get; set; }\n        }\n\n        [Fact]\n        public void TemplateNullExpressionThrows()\n        {\n            // Arrange\n            HtmlHelper<object> html = MakeHtmlHelper<object>(null);\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => TemplateHelpers.Template(html, null, \"templateName\", \"htmlFieldName\", DataBoundControlMode.ReadOnly,\n                                               null /* additionalViewData */, TemplateHelperSpy),\n                \"expression\");\n        }\n\n        [Fact]\n        public void TemplateDataNotFound()\n        {\n            // Arrange\n            HtmlHelper<object> html = MakeHtmlHelper<object>(null);\n\n            // Act\n            string result = TemplateHelpers.Template(html, \"UnknownObject\", \"templateName\", null, DataBoundControlMode.ReadOnly,\n                                                     null /* additionalViewData */, TemplateHelperSpy);\n\n            // Assert\n            Assert.Equal(\"Model = (null), ModelType = System.String, RealModelType = System.String, PropertyName = (null), HtmlFieldName = UnknownObject, TemplateName = templateName, Mode = ReadOnly, AdditionalViewData = (null)\", result);\n        }\n\n        [Fact]\n        public void TemplateHtmlFieldNameReplacesExpression()\n        {\n            // Arrange\n            HtmlHelper<object> html = MakeHtmlHelper<object>(null);\n\n            // Act\n            string result = TemplateHelpers.Template(html, \"UnknownObject\", \"templateName\", \"htmlFieldName\", DataBoundControlMode.ReadOnly,\n                                                     new { foo = \"Bar\" }, TemplateHelperSpy);\n\n            // Assert\n            Assert.Equal(\"Model = (null), ModelType = System.String, RealModelType = System.String, PropertyName = (null), HtmlFieldName = htmlFieldName, TemplateName = templateName, Mode = ReadOnly, AdditionalViewData = { foo: Bar }\", result);\n        }\n\n        [Fact]\n        public void TemplateDataFoundInViewDataDictionaryHasNoPropertyName()\n        {\n            // Arrange\n            HtmlHelper<object> html = MakeHtmlHelper<object>(null);\n            html.ViewContext.ViewData[\"Key\"] = 42;\n\n            // Act\n            string result = TemplateHelpers.Template(html, \"Key\", null, null, DataBoundControlMode.Edit, null /* additionalViewData */, TemplateHelperSpy);\n\n            // Assert\n            Assert.Equal(\"Model = 42, ModelType = System.Int32, RealModelType = System.Int32, PropertyName = (null), HtmlFieldName = Key, TemplateName = (null), Mode = Edit, AdditionalViewData = (null)\", result);\n        }\n\n        [Fact]\n        public void TemplateDataFoundInViewDataDictionarySubPropertyHasPropertyName()\n        {\n            // Arrange\n            HtmlHelper<object> html = MakeHtmlHelper<object>(null);\n            html.ViewContext.ViewData[\"Key\"] = new TemplateModel { MyProperty = \"Hello!\" };\n\n            // Act\n            string result = TemplateHelpers.Template(html, \"Key.MyProperty\", null, null, DataBoundControlMode.ReadOnly,\n                                                     null /* additionalViewData */, TemplateHelperSpy);\n\n            // Assert\n            Assert.Equal(\"Model = Hello!, ModelType = System.Object, RealModelType = System.String, PropertyName = MyProperty, HtmlFieldName = Key.MyProperty, TemplateName = (null), Mode = ReadOnly, AdditionalViewData = (null)\", result);\n        }\n\n        [Fact]\n        public void TemplateDataFoundInModelHasPropertyName()\n        {\n            // Arrange\n            HtmlHelper<TemplateModel> html = MakeHtmlHelper<TemplateModel>(new TemplateModel { MyProperty = \"Hello!\" });\n\n            // Act\n            string result = TemplateHelpers.Template(html, \"MyProperty\", null, null, DataBoundControlMode.ReadOnly,\n                                                     null /* additionalViewData */, TemplateHelperSpy);\n\n            // Assert\n            Assert.Equal(\"Model = Hello!, ModelType = System.Object, RealModelType = System.String, PropertyName = MyProperty, HtmlFieldName = MyProperty, TemplateName = (null), Mode = ReadOnly, AdditionalViewData = (null)\", result);\n        }\n\n        [Fact]\n        public void TemplateNullDataFoundInModelHasPropertyTypeInsteadOfActualModelType()\n        {\n            // Arrange\n            HtmlHelper<TemplateModel> html = MakeHtmlHelper<TemplateModel>(new TemplateModel());\n\n            // Act\n            string result = TemplateHelpers.Template(html, \"MyProperty\", null, null, DataBoundControlMode.ReadOnly,\n                                                     null /* additionalViewData */, TemplateHelperSpy);\n\n            // Assert\n            Assert.Equal(\"Model = (null), ModelType = System.Object, RealModelType = System.Object, PropertyName = MyProperty, HtmlFieldName = MyProperty, TemplateName = (null), Mode = ReadOnly, AdditionalViewData = (null)\", result);\n        }\n\n        // TemplateFor\n\n        private class TemplateForModel\n        {\n            public int MyField = 0;\n            public object MyProperty { get; set; }\n            public Nullable<int> MyNullableProperty { get; set; }\n        }\n\n        [Fact]\n        public void TemplateForNonUnsupportedExpressionTypeThrows()\n        {\n            // Arrange\n            HtmlHelper<TemplateForModel> html = MakeHtmlHelper<TemplateForModel>(null);\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => TemplateHelpers.TemplateFor(html, model => new Object(), \"templateName\", \"htmlFieldName\", DataBoundControlMode.ReadOnly,\n                                                  null /* additionalViewData */, TemplateHelperSpy),\n                \"Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.\");\n        }\n\n        [Fact]\n        public void TemplateForWithNonNullExpression()\n        {\n            // Arrange\n            HtmlHelper<TemplateForModel> html = MakeHtmlHelper(new TemplateForModel { MyProperty = \"Hello!\" });\n\n            // Act\n            string result = TemplateHelpers.TemplateFor(html, model => model.MyProperty, \"templateName\", null, DataBoundControlMode.ReadOnly,\n                                                        new { foo = \"Bar\" }, TemplateHelperSpy);\n\n            // Assert\n            Assert.Equal(\"Model = Hello!, ModelType = System.Object, RealModelType = System.String, PropertyName = MyProperty, HtmlFieldName = MyProperty, TemplateName = templateName, Mode = ReadOnly, AdditionalViewData = { foo: Bar }\", result);\n        }\n\n        [Fact]\n        public void TemplateForHtmlFieldNameReplacesExpression()\n        {\n            // Arrange\n            HtmlHelper<TemplateForModel> html = MakeHtmlHelper(new TemplateForModel { MyProperty = \"Hello!\" });\n\n            // Act\n            string result = TemplateHelpers.TemplateFor(html, model => model.MyProperty, \"templateName\", \"htmlFieldName\",\n                                                        DataBoundControlMode.ReadOnly, null /* additionalViewData */, TemplateHelperSpy);\n\n            // Assert\n            Assert.Equal(\"Model = Hello!, ModelType = System.Object, RealModelType = System.String, PropertyName = MyProperty, HtmlFieldName = htmlFieldName, TemplateName = templateName, Mode = ReadOnly, AdditionalViewData = (null)\", result);\n        }\n\n        [Fact]\n        public void TemplateForNullModelStillRetainsTypeInformation()\n        {\n            // Arrange\n            HtmlHelper<TemplateForModel> html = MakeHtmlHelper<TemplateForModel>(null);\n\n            // Act\n            string result = TemplateHelpers.TemplateFor(html, model => model.MyProperty, null, null, DataBoundControlMode.ReadOnly,\n                                                        null /* additionalViewData */, TemplateHelperSpy);\n\n            // Assert\n            Assert.Equal(\"Model = (null), ModelType = System.Object, RealModelType = System.Object, PropertyName = MyProperty, HtmlFieldName = MyProperty, TemplateName = (null), Mode = ReadOnly, AdditionalViewData = (null)\", result);\n        }\n\n        [Fact]\n        public void TemplateForNullPropertyStillRetainsTypeInformation()\n        {\n            // Arrange\n            HtmlHelper<TemplateForModel> html = MakeHtmlHelper(new TemplateForModel());\n\n            // Act\n            string result = TemplateHelpers.TemplateFor(html, model => model.MyProperty, null, null, DataBoundControlMode.ReadOnly,\n                                                        null /* additionalViewData */, TemplateHelperSpy);\n\n            // Assert\n            Assert.Equal(\"Model = (null), ModelType = System.Object, RealModelType = System.Object, PropertyName = MyProperty, HtmlFieldName = MyProperty, TemplateName = (null), Mode = ReadOnly, AdditionalViewData = (null)\", result);\n        }\n\n        [Fact]\n        public void TemplateForNullableValueTYpePropertyRetainsNullableValueTYpeForNullPropertyValue()\n        {\n            // Arrange\n            HtmlHelper<TemplateForModel> html = MakeHtmlHelper(new TemplateForModel());\n\n            // Act\n            string result = TemplateHelpers.TemplateFor(html, model => model.MyNullableProperty, null, null, DataBoundControlMode.ReadOnly,\n                                                        null /* additionalViewData */, TemplateHelperSpy);\n\n            // Assert\n            Assert.Equal(\"Model = (null), ModelType = System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], RealModelType = System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], PropertyName = MyNullableProperty, HtmlFieldName = MyNullableProperty, TemplateName = (null), Mode = ReadOnly, AdditionalViewData = (null)\", result);\n        }\n\n        [Fact]\n        public void TemplateForNullableValueTypePropertyRetainsNullableValueTypeForNonNullPropertyValue()\n        {\n            // Arrange\n            HtmlHelper<TemplateForModel> html = MakeHtmlHelper(new TemplateForModel { MyNullableProperty = 42 });\n\n            // Act\n            string result = TemplateHelpers.TemplateFor(html, model => model.MyNullableProperty, null, null, DataBoundControlMode.ReadOnly,\n                                                        null /* additionalViewData */, TemplateHelperSpy);\n\n            // Assert\n            Assert.Equal(\"Model = 42, ModelType = System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], RealModelType = System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], PropertyName = MyNullableProperty, HtmlFieldName = MyNullableProperty, TemplateName = (null), Mode = ReadOnly, AdditionalViewData = (null)\", result);\n        }\n\n        [Fact]\n        public void TemplateForWithParameterExpression()\n        {\n            // Arrange\n            HtmlHelper<TemplateForModel> html = MakeHtmlHelper(new TemplateForModel());\n\n            // Act\n            string result = TemplateHelpers.TemplateFor(html, model => model, null, null, DataBoundControlMode.ReadOnly,\n                                                        null /* additionalViewData */, TemplateHelperSpy);\n\n            // Assert\n            Assert.Equal(\"Model = System.Web.Mvc.Html.Test.TemplateHelpersTest+TemplateForModel, ModelType = System.Web.Mvc.Html.Test.TemplateHelpersTest+TemplateForModel, RealModelType = System.Web.Mvc.Html.Test.TemplateHelpersTest+TemplateForModel, PropertyName = (null), HtmlFieldName = (empty), TemplateName = (null), Mode = ReadOnly, AdditionalViewData = (null)\", result);\n        }\n\n        [Fact]\n        public void TemplateForWithFieldExpression()\n        {\n            // Arrange\n            HtmlHelper<TemplateForModel> html = MakeHtmlHelper(new TemplateForModel { MyField = 42 });\n\n            // Act\n            string result = TemplateHelpers.TemplateFor(html, model => model.MyField, null, null, DataBoundControlMode.ReadOnly,\n                                                        null /* additionalViewData */, TemplateHelperSpy);\n\n            // Assert\n            Assert.Equal(\"Model = 42, ModelType = System.Int32, RealModelType = System.Int32, PropertyName = (null), HtmlFieldName = MyField, TemplateName = (null), Mode = ReadOnly, AdditionalViewData = (null)\", result);\n        }\n\n        // TemplateHelper\n\n        private class TemplateHelperModel\n        {\n            public string MyProperty { get; set; }\n        }\n\n        [Fact]\n        public void TemplateHelperNonNullNonEmptyStringModel()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper(new TemplateHelperModel { MyProperty = \"Hello\" });\n            ModelMetadata metadata = ModelMetadata.FromStringExpression(\"MyProperty\", html.ViewData);\n\n            // Act\n            string result = TemplateHelpers.TemplateHelper(html, metadata, \"htmlFieldName\", \"templateName\", DataBoundControlMode.ReadOnly,\n                                                           null /* additionalViewData */, ExecuteTemplateSpy);\n\n            // Assert\n            Assert.Equal(\"Model = Hello, ModelType = System.String, RealModelType = System.String, PropertyName = MyProperty, FormattedModelValue = Hello, HtmlFieldPrefix = FieldPrefix.htmlFieldName, TemplateName = templateName, Mode = ReadOnly\", result);\n        }\n\n        [Fact]\n        public void TemplateHelperEmptyStringModel()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper(new TemplateHelperModel { MyProperty = \"\" });\n            ModelMetadata metadata = ModelMetadata.FromStringExpression(\"MyProperty\", html.ViewData);\n            metadata.ConvertEmptyStringToNull = false;\n\n            // Act\n            string result = TemplateHelpers.TemplateHelper(html, metadata, \"htmlFieldName\", \"templateName\", DataBoundControlMode.ReadOnly,\n                                                           null /* additionalViewData */, ExecuteTemplateSpy);\n\n            // Assert\n            Assert.Equal(\"Model = , ModelType = System.String, RealModelType = System.String, PropertyName = MyProperty, FormattedModelValue = , HtmlFieldPrefix = FieldPrefix.htmlFieldName, TemplateName = templateName, Mode = ReadOnly\", result);\n        }\n\n        [Fact]\n        public void TemplateHelperConvertsEmptyStringsToNull()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper(new TemplateHelperModel { MyProperty = \"\" });\n            ModelMetadata metadata = ModelMetadata.FromStringExpression(\"MyProperty\", html.ViewData);\n            metadata.ConvertEmptyStringToNull = true;\n\n            // Act\n            string result = TemplateHelpers.TemplateHelper(html, metadata, \"htmlFieldName\", \"templateName\", DataBoundControlMode.ReadOnly,\n                                                           null /* additionalViewData */, ExecuteTemplateSpy);\n\n            // Assert\n            Assert.Equal(\"Model = (null), ModelType = System.String, RealModelType = System.String, PropertyName = MyProperty, FormattedModelValue = , HtmlFieldPrefix = FieldPrefix.htmlFieldName, TemplateName = templateName, Mode = ReadOnly\", result);\n        }\n\n        [Fact]\n        public void TemplateHelperConvertsNullModelsToNullDisplayTextInReadOnlyMode()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper(new TemplateHelperModel());\n            ModelMetadata metadata = ModelMetadata.FromStringExpression(\"MyProperty\", html.ViewData);\n            metadata.NullDisplayText = \"NullDisplayText\";\n\n            // Act\n            string result = TemplateHelpers.TemplateHelper(html, metadata, \"htmlFieldName\", \"templateName\", DataBoundControlMode.ReadOnly,\n                                                           null /* additionalViewData */, ExecuteTemplateSpy);\n\n            // Assert\n            Assert.Equal(\"Model = (null), ModelType = System.String, RealModelType = System.String, PropertyName = MyProperty, FormattedModelValue = NullDisplayText, HtmlFieldPrefix = FieldPrefix.htmlFieldName, TemplateName = templateName, Mode = ReadOnly\", result);\n        }\n\n        [Fact]\n        public void TemplateHelperDoesNotConvertNullModelsToNullDisplayTextInEditMode()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper(new TemplateHelperModel());\n            ModelMetadata metadata = ModelMetadata.FromStringExpression(\"MyProperty\", html.ViewData);\n            metadata.NullDisplayText = \"NullDisplayText\";\n\n            // Act\n            string result = TemplateHelpers.TemplateHelper(html, metadata, \"htmlFieldName\", \"templateName\", DataBoundControlMode.Edit,\n                                                           null /* additionalViewData */, ExecuteTemplateSpy);\n\n            // Assert\n            Assert.Equal(\"Model = (null), ModelType = System.String, RealModelType = System.String, PropertyName = MyProperty, FormattedModelValue = , HtmlFieldPrefix = FieldPrefix.htmlFieldName, TemplateName = templateName, Mode = Edit\", result);\n        }\n\n        [Fact]\n        public void TemplateHelperAppliesDisplayFormatStringInReadOnlyMode()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper(new TemplateHelperModel { MyProperty = \"Hello\" });\n            ModelMetadata metadata = ModelMetadata.FromStringExpression(\"MyProperty\", html.ViewData);\n            metadata.DisplayFormatString = \"{0} world!\";\n\n            // Act\n            string result = TemplateHelpers.TemplateHelper(html, metadata, \"htmlFieldName\", \"templateName\", DataBoundControlMode.ReadOnly,\n                                                           null /* additionalViewData */, ExecuteTemplateSpy);\n\n            // Assert\n            Assert.Equal(\"Model = Hello, ModelType = System.String, RealModelType = System.String, PropertyName = MyProperty, FormattedModelValue = Hello world!, HtmlFieldPrefix = FieldPrefix.htmlFieldName, TemplateName = templateName, Mode = ReadOnly\", result);\n        }\n\n        [Fact]\n        public void TemplateHelperDoesNotApplyDisplayFormatStringInReadOnlyModeForNullModel()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper(new TemplateHelperModel());\n            ModelMetadata metadata = ModelMetadata.FromStringExpression(\"MyProperty\", html.ViewData);\n            metadata.DisplayFormatString = \"{0} world!\";\n\n            // Act\n            string result = TemplateHelpers.TemplateHelper(html, metadata, \"htmlFieldName\", \"templateName\", DataBoundControlMode.ReadOnly,\n                                                           null /* additionalViewData */, ExecuteTemplateSpy);\n\n            // Assert\n            Assert.Equal(\"Model = (null), ModelType = System.String, RealModelType = System.String, PropertyName = MyProperty, FormattedModelValue = , HtmlFieldPrefix = FieldPrefix.htmlFieldName, TemplateName = templateName, Mode = ReadOnly\", result);\n        }\n\n        [Fact]\n        public void TemplateHelperAppliesEditFormatStringInEditMode()\n        {\n            HtmlHelper html = MakeHtmlHelper(new TemplateHelperModel { MyProperty = \"Hello\" });\n            ModelMetadata metadata = ModelMetadata.FromStringExpression(\"MyProperty\", html.ViewData);\n            metadata.EditFormatString = \"{0} world!\";\n\n            // Act\n            string result = TemplateHelpers.TemplateHelper(html, metadata, \"htmlFieldName\", \"templateName\", DataBoundControlMode.Edit,\n                                                           null /* additionalViewData */, ExecuteTemplateSpy);\n\n            // Assert\n            Assert.Equal(\"Model = Hello, ModelType = System.String, RealModelType = System.String, PropertyName = MyProperty, FormattedModelValue = Hello world!, HtmlFieldPrefix = FieldPrefix.htmlFieldName, TemplateName = templateName, Mode = Edit\", result);\n        }\n\n        [Fact]\n        public void TemplateHelperDoesNotApplyEditFormatStringInEditModeForNullModel()\n        {\n            // Arrange\n            HtmlHelper html = MakeHtmlHelper(new TemplateHelperModel());\n            ModelMetadata metadata = ModelMetadata.FromStringExpression(\"MyProperty\", html.ViewData);\n            metadata.EditFormatString = \"{0} world!\";\n\n            // Act\n            string result = TemplateHelpers.TemplateHelper(html, metadata, \"htmlFieldName\", \"templateName\", DataBoundControlMode.Edit,\n                                                           null /* additionalViewData */, ExecuteTemplateSpy);\n\n            // Assert\n            Assert.Equal(\"Model = (null), ModelType = System.String, RealModelType = System.String, PropertyName = MyProperty, FormattedModelValue = , HtmlFieldPrefix = FieldPrefix.htmlFieldName, TemplateName = templateName, Mode = Edit\", result);\n        }\n\n        [Fact]\n        public void TemplateHelperAddsNonNullModelToVisitedObjects()\n        { // DDB #224750\n            HtmlHelper html = MakeHtmlHelper(new TemplateHelperModel { MyProperty = \"Hello\" });\n            ModelMetadata metadata = ModelMetadata.FromStringExpression(\"MyProperty\", html.ViewData);\n            ViewDataDictionary viewData = null;\n\n            // Act\n            TemplateHelpers.TemplateHelper(\n                html, metadata, \"htmlFieldName\", \"templateName\", DataBoundControlMode.ReadOnly, null /* additionalViewData */,\n                (_html, _viewData, _templateName, _mode, _getViews, _getDefaultActions) =>\n                {\n                    viewData = _viewData;\n                    return String.Empty;\n                });\n\n            // Assert\n            Assert.NotNull(viewData);\n            Assert.Contains(\"Hello\", viewData.TemplateInfo.VisitedObjects);\n        }\n\n        [Fact]\n        public void TemplateHelperAddsNullModelsTypeToVisitedObjects()\n        { // DDB #224750\n            HtmlHelper html = MakeHtmlHelper(new TemplateHelperModel());\n            ModelMetadata metadata = ModelMetadata.FromStringExpression(\"MyProperty\", html.ViewData);\n            ViewDataDictionary viewData = null;\n\n            // Act\n            TemplateHelpers.TemplateHelper(\n                html, metadata, \"htmlFieldName\", \"templateName\", DataBoundControlMode.ReadOnly, null /* additionalViewData */,\n                (_html, _viewData, _templateName, _mode, _getViews, _getDefaultActions) =>\n                {\n                    viewData = _viewData;\n                    return String.Empty;\n                });\n\n            // Assert\n            Assert.NotNull(viewData);\n            Assert.Contains(typeof(string), viewData.TemplateInfo.VisitedObjects);\n        }\n\n        [Fact]\n        public void TemplateHelperReturnsEmptyStringForAlreadyVisitedObject()\n        { // DDB #224750\n            HtmlHelper html = MakeHtmlHelper(new TemplateHelperModel { MyProperty = \"Hello\" });\n            ModelMetadata metadata = ModelMetadata.FromStringExpression(\"MyProperty\", html.ViewData);\n            html.ViewData.TemplateInfo.VisitedObjects.Add(\"Hello\");\n\n            // Act\n            string result = TemplateHelpers.TemplateHelper(html, metadata, \"htmlFieldName\", \"templateName\", DataBoundControlMode.ReadOnly,\n                                                           null /* additionalViewData */);\n\n            // Assert\n            Assert.Equal(String.Empty, result);\n        }\n\n        [Fact]\n        public void TemplateHelperReturnsEmptyStringForAlreadyVisitedType()\n        { // DDB #224750\n            HtmlHelper html = MakeHtmlHelper(new TemplateHelperModel());\n            ModelMetadata metadata = ModelMetadata.FromStringExpression(\"MyProperty\", html.ViewData);\n            html.ViewData.TemplateInfo.VisitedObjects.Add(typeof(string));\n\n            // Act\n            string result = TemplateHelpers.TemplateHelper(html, metadata, \"htmlFieldName\", \"templateName\", DataBoundControlMode.ReadOnly,\n                                                           null /* additionalViewData */);\n\n            // Assert\n            Assert.Equal(String.Empty, result);\n        }\n\n        [Fact]\n        public void TemplateHelperPreservesSameInstanceOfModelMetadata()\n        { // DDB #225858\n            HtmlHelper html = MakeHtmlHelper(new TemplateHelperModel());\n            ModelMetadata metadata = ModelMetadata.FromStringExpression(\"MyProperty\", html.ViewData);\n            ViewDataDictionary callbackViewData = null;\n\n            // Act\n            string result = TemplateHelpers.TemplateHelper(html, metadata, \"htmlFieldName\", \"templateName\", DataBoundControlMode.ReadOnly,\n                                                           null /* additionalViewData */,\n                                                           (_html, _viewData, _templateName, _mode, _getViewNames, _getDefaultActions) =>\n                                                           {\n                                                               callbackViewData = _viewData;\n                                                               return String.Empty;\n                                                           });\n\n            // Assert\n            Assert.NotNull(callbackViewData);\n            Assert.Same(metadata, callbackViewData.ModelMetadata);\n        }\n\n        [Fact]\n        public void TemplateHelperFormatsValuesUsingCurrentCulture()\n        {\n            CultureInfo existingCulture = Thread.CurrentThread.CurrentCulture;\n\n            try\n            {\n                // Arrange\n                Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(\"es-MX\");\n                HtmlHelper html = MakeHtmlHelper(new { MyProperty = new DateTime(2009, 11, 18, 16, 12, 8, DateTimeKind.Utc) });\n                ModelMetadata metadata = ModelMetadata.FromStringExpression(\"MyProperty\", html.ViewData);\n                metadata.DisplayFormatString = \"{0:F}\";\n\n                // Act\n                string result = TemplateHelpers.TemplateHelper(html, metadata, \"htmlFieldName\", \"templateName\", DataBoundControlMode.ReadOnly,\n                                                               null /* additionalViewData */, ExecuteTemplateSpy);\n\n                // Assert\n                Assert.Equal(\"Model = 18/11/2009 04:12:08 p. m., ModelType = System.DateTime, RealModelType = System.DateTime, PropertyName = MyProperty, FormattedModelValue = miércoles, 18 de noviembre de 2009 04:12:08 p. m., HtmlFieldPrefix = FieldPrefix.htmlFieldName, TemplateName = templateName, Mode = ReadOnly\", result);\n            }\n            finally\n            {\n                Thread.CurrentThread.CurrentCulture = existingCulture;\n            }\n        }\n\n        [Fact]\n        public void TemplateHelperPreservesExistingViewData()\n        {\n            HtmlHelper html = MakeHtmlHelper(new TemplateHelperModel());\n            html.ViewData[\"Foo\"] = \"Bar\";\n            html.ViewData[\"Baz\"] = 42;\n            ModelMetadata metadata = ModelMetadata.FromStringExpression(\"MyProperty\", html.ViewData);\n            ViewDataDictionary callbackViewData = null;\n\n            // Act\n            string result = TemplateHelpers.TemplateHelper(html, metadata, \"htmlFieldName\", \"templateName\", DataBoundControlMode.ReadOnly,\n                                                           null /* additionalViewData */,\n                                                           (_html, _viewData, _templateName, _mode, _getViewNames, _getDefaultActions) =>\n                                                           {\n                                                               callbackViewData = _viewData;\n                                                               return String.Empty;\n                                                           });\n\n            // Assert\n            Assert.NotSame(html.ViewData, callbackViewData);\n            Assert.Equal(2, callbackViewData.Count);\n            Assert.Equal(\"Bar\", callbackViewData[\"Foo\"]);\n            Assert.Equal(42, callbackViewData[\"Baz\"]);\n        }\n\n        [Fact]\n        public void TemplateHelperMergesAdditionalViewData()\n        {\n            HtmlHelper html = MakeHtmlHelper(new TemplateHelperModel());\n            html.ViewData[\"Foo\"] = \"Bar\";\n            html.ViewData[\"Baz\"] = 42;\n            ModelMetadata metadata = ModelMetadata.FromStringExpression(\"MyProperty\", html.ViewData);\n            ViewDataDictionary callbackViewData = null;\n\n            // Act\n            string result = TemplateHelpers.TemplateHelper(html, metadata, \"htmlFieldName\", \"templateName\", DataBoundControlMode.ReadOnly,\n                                                           new { foo = \"New Foo\", hello = \"World!\" },\n                                                           (_html, _viewData, _templateName, _mode, _getViewNames, _getDefaultActions) =>\n                                                           {\n                                                               callbackViewData = _viewData;\n                                                               return String.Empty;\n                                                           });\n\n            // Assert\n            Assert.NotSame(html.ViewData, callbackViewData);\n            Assert.Equal(3, callbackViewData.Count);\n            Assert.Equal(\"New Foo\", callbackViewData[\"Foo\"]);\n            Assert.Equal(42, callbackViewData[\"Baz\"]);\n            Assert.Equal(\"World!\", callbackViewData[\"Hello\"]);\n        }\n\n        // Helpers\n\n        private static string ExecuteTemplateSpy(HtmlHelper html, ViewDataDictionary viewData, string templateName, DataBoundControlMode mode,\n                                                 TemplateHelpers.GetViewNamesDelegate getViewNames, TemplateHelpers.GetDefaultActionsDelegate getDefaultActions)\n        {\n            Assert.Same(viewData.Model, viewData.ModelMetadata.Model);\n            Assert.Equal<TemplateHelpers.GetViewNamesDelegate>(TemplateHelpers.GetViewNames, getViewNames);\n            Assert.Equal<TemplateHelpers.GetDefaultActionsDelegate>(TemplateHelpers.GetDefaultActions, getDefaultActions);\n\n            return String.Format(\"Model = {0}, ModelType = {1}, RealModelType = {2}, PropertyName = {3}, FormattedModelValue = {4}, HtmlFieldPrefix = {5}, TemplateName = {6}, Mode = {7}\",\n                                 viewData.ModelMetadata.Model ?? \"(null)\",\n                                 viewData.ModelMetadata.ModelType == null ? \"(null)\" : viewData.ModelMetadata.ModelType.FullName,\n                                 viewData.ModelMetadata.RealModelType == null ? \"(null)\" : viewData.ModelMetadata.RealModelType.FullName,\n                                 viewData.ModelMetadata.PropertyName ?? \"(null)\",\n                                 viewData.TemplateInfo.FormattedModelValue ?? \"(null)\",\n                                 viewData.TemplateInfo.HtmlFieldPrefix == \"\" ? \"(empty)\" : viewData.TemplateInfo.HtmlFieldPrefix ?? \"(null)\",\n                                 templateName ?? \"(null)\",\n                                 mode);\n        }\n\n        private static string TemplateHelperSpy(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string templateName, DataBoundControlMode mode,\n                                                object additionalViewData)\n        {\n            return String.Format(\"Model = {0}, ModelType = {1}, RealModelType = {2}, PropertyName = {3}, HtmlFieldName = {4}, TemplateName = {5}, Mode = {6}, AdditionalViewData = {7}\",\n                                 metadata.Model ?? \"(null)\",\n                                 metadata.ModelType == null ? \"(null)\" : metadata.ModelType.FullName,\n                                 metadata.RealModelType == null ? \"(null)\" : metadata.RealModelType.FullName,\n                                 metadata.PropertyName ?? \"(null)\",\n                                 htmlFieldName == String.Empty ? \"(empty)\" : htmlFieldName ?? \"(null)\",\n                                 templateName ?? \"(null)\",\n                                 mode,\n                                 AnonymousObject.Inspect(additionalViewData));\n        }\n\n        private HtmlHelper<TModel> MakeHtmlHelper<TModel>(TModel model)\n        {\n            return MakeHtmlHelper<TModel>(model, model);\n        }\n\n        private HtmlHelper<TModel> MakeHtmlHelper<TModel>(TModel model, object formattedModelValue)\n        {\n            ViewDataDictionary viewData = new ViewDataDictionary(model);\n            viewData.TemplateInfo.HtmlFieldPrefix = \"FieldPrefix\";\n            viewData.TemplateInfo.FormattedModelValue = formattedModelValue;\n            viewData.ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(() => model, typeof(TModel));\n\n            Mock<HttpContextBase> httpContext = new Mock<HttpContextBase>();\n            httpContext.Setup(c => c.Items).Returns(new Hashtable());\n\n            Mock<ViewContext> viewContext = new Mock<ViewContext> { CallBase = true };\n            viewContext.Setup(c => c.View).Returns(new DummyView());\n            viewContext.Setup(c => c.ViewData).Returns(viewData);\n            viewContext.Setup(c => c.HttpContext).Returns(httpContext.Object);\n            viewContext.Setup(c => c.RouteData).Returns(new RouteData());\n            viewContext.Setup(c => c.TempData).Returns(new TempDataDictionary());\n            viewContext.Setup(c => c.Writer).Returns(TextWriter.Null);\n\n            return new HtmlHelper<TModel>(viewContext.Object, new SimpleViewDataContainer(viewData));\n        }\n\n        private ViewDataDictionary MakeViewData(HtmlHelper html, ModelMetadata metadata)\n        {\n            return new ViewDataDictionary(html.ViewDataContainer.ViewData)\n            {\n                Model = metadata.Model,\n                ModelMetadata = metadata,\n                TemplateInfo = new TemplateInfo\n                {\n                    FormattedModelValue = metadata.Model,\n                    HtmlFieldPrefix = \"FieldPrefix\",\n                }\n            };\n        }\n\n        private class DummyView : IView\n        {\n            public void Render(ViewContext viewContext, TextWriter writer)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class MockViewEngine : IDisposable\n        {\n            List<IViewEngine> oldEngines;\n\n            public MockViewEngine(bool returnView = true)\n            {\n                oldEngines = ViewEngines.Engines.ToList();\n\n                View = new Mock<IView>();\n\n                Engine = new Mock<IViewEngine>();\n\n                Engine.Setup(e => e.FindPartialView(It.IsAny<ControllerContext>(), It.IsAny<string>(), It.IsAny<bool>()))\n                    .Returns(returnView ? new ViewEngineResult(View.Object, Engine.Object) : new ViewEngineResult(new string[0]));\n\n                ViewEngines.Engines.Clear();\n                ViewEngines.Engines.Add(Engine.Object);\n            }\n\n            public void Dispose()\n            {\n                ViewEngines.Engines.Clear();\n\n                foreach (IViewEngine engine in oldEngines)\n                {\n                    ViewEngines.Engines.Add(engine);\n                }\n            }\n\n            public Mock<IViewEngine> Engine { get; set; }\n\n            public Mock<IView> View { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Html/Test/TextAreaExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc.Test;\nusing System.Web.Routing;\nusing System.Web.WebPages.Scope;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace System.Web.Mvc.Html.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")]\n    public class TextAreaExtensionsTest : IDisposable\n    {\n        private static readonly RouteValueDictionary _textAreaAttributesDictionary = new RouteValueDictionary(new { rows = \"15\", cols = \"12\" });\n        private static readonly object _textAreaAttributesObjectDictionary = new { rows = \"15\", cols = \"12\" };\n        private static readonly object _textAreaAttributesObjectUnderscoresDictionary = new { rows = \"15\", cols = \"12\", foo_bar = \"baz\" };\n\n        private class TextAreaModel\n        {\n            public string foo { get; set; }\n            public string bar { get; set; }\n        }\n\n        private static ViewDataDictionary<TextAreaModel> GetTextAreaViewData()\n        {\n            ViewDataDictionary<TextAreaModel> viewData = new ViewDataDictionary<TextAreaModel> { { \"foo\", \"ViewDataFoo\" } };\n            viewData.Model = new TextAreaModel { foo = \"ViewItemFoo\", bar = \"ViewItemBar\" };\n            return viewData;\n        }\n\n        private static ViewDataDictionary<TextAreaModel> GetTextAreaViewDataWithErrors()\n        {\n            ViewDataDictionary<TextAreaModel> viewData = new ViewDataDictionary<TextAreaModel> { { \"foo\", \"ViewDataFoo\" } };\n            viewData.Model = new TextAreaModel { foo = \"ViewItemFoo\", bar = \"ViewItemBar\" };\n\n            ModelState modelStateFoo = new ModelState();\n            modelStateFoo.Errors.Add(new ModelError(\"foo error 1\"));\n            modelStateFoo.Errors.Add(new ModelError(\"foo error 2\"));\n            viewData.ModelState[\"foo\"] = modelStateFoo;\n            modelStateFoo.Value = HtmlHelperTest.GetValueProviderResult(new string[] { \"AttemptedValueFoo\" }, \"AttemptedValueFoo\");\n\n            return viewData;\n        }\n\n        // TextArea\n\n        [Fact]\n        public void TextAreaParameterDictionaryMerging()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = helper.TextArea(\"foo\", new { rows = \"30\" });\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"20\\\" id=\\\"foo\\\" name=\\\"foo\\\" rows=\\\"30\\\">\" + Environment.NewLine\n              + \"</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaParameterDictionaryMerging_Unobtrusive()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n            helper.ViewContext.ClientValidationEnabled = true;\n            helper.ViewContext.UnobtrusiveJavaScriptEnabled = true;\n            helper.ViewContext.FormContext = new FormContext();\n            helper.ClientValidationRuleFactory = (name, metadata) => new[] { new ModelClientValidationRule { ValidationType = \"type\", ErrorMessage = \"error\" } };\n\n            // Act\n            MvcHtmlString html = helper.TextArea(\"foo\", new { rows = \"30\" });\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"20\\\" data-val=\\\"true\\\" data-val-type=\\\"error\\\" id=\\\"foo\\\" name=\\\"foo\\\" rows=\\\"30\\\">\" + Environment.NewLine\n              + \"</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaParameterDictionaryMergingExplicitParameters()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = helper.TextArea(\"foo\", \"bar\", 10, 25, new { rows = \"30\" });\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"25\\\" id=\\\"foo\\\" name=\\\"foo\\\" rows=\\\"10\\\">\" + Environment.NewLine\n              + \"bar</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaParameterDictionaryMergingExplicitParametersWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = helper.TextArea(\"foo\", \"bar\", 10, 25, new { rows = \"30\", foo_bar = \"baz\" });\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"25\\\" foo-bar=\\\"baz\\\" id=\\\"foo\\\" name=\\\"foo\\\" rows=\\\"10\\\">\" + Environment.NewLine\n              + \"bar</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaWithEmptyNameThrows()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { helper.TextArea(String.Empty); },\n                \"name\");\n        }\n\n        [Fact]\n        public void TextAreaWithOutOfRangeColsThrows()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n\n            // Act & Assert\n            Assert.ThrowsArgumentOutOfRange(\n                delegate { helper.TextArea(\"Foo\", null /* value */, 0, -1, null /* htmlAttributes */); },\n                \"columns\",\n                \"The value must be greater than or equal to zero.\");\n        }\n\n        [Fact]\n        public void TextAreaWithOutOfRangeRowsThrows()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n\n            // Act & Assert\n            Assert.ThrowsArgumentOutOfRange(\n                delegate { helper.TextArea(\"Foo\", null /* value */, -1, 0, null /* htmlAttributes */); },\n                \"rows\",\n                \"The value must be greater than or equal to zero.\");\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void TextArea_AttributeEncodes_Name(string text, bool htmlEncode, string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            // htmlAttributes included only to avoid special-cased renaming done for id attribute.\n            var result = helper.TextArea(name: text, htmlAttributes: new { id = \"id\", }).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"20\\\" id=\\\"id\\\" name=\\\"\" +\n                    encodedText +\n                    \"\\\" rows=\\\"2\\\">\" +\n                    Environment.NewLine +\n                    \"</textarea>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void TextArea_AttributeEncodes_Prefix(string text, bool htmlEncode, string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.TemplateInfo.HtmlFieldPrefix = text;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            // htmlAttributes included only to avoid special-cased renaming done for id attribute.\n            var result = helper.TextArea(name: String.Empty, htmlAttributes: new { id = \"id\", }).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"20\\\" id=\\\"id\\\" name=\\\"\" +\n                    encodedText +\n                    \"\\\" rows=\\\"2\\\">\" +\n                    Environment.NewLine +\n                    \"</textarea>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"HtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void TextArea_HtmlEncodes_Value(string text, bool htmlEncode, string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(text);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.TemplateInfo.HtmlFieldPrefix = \"Prefix\";\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            var result = helper.TextArea(\"\").ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"20\\\" id=\\\"Prefix\\\" name=\\\"Prefix\\\" rows=\\\"2\\\">\" +\n                    Environment.NewLine +\n                    encodedText +\n                    \"</textarea>\",\n                result);\n        }\n\n        [Fact]\n        public void TextAreaWithExplicitValue()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            MvcHtmlString html = helper.TextArea(\"foo\", \"bar\");\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"20\\\" id=\\\"foo\\\" name=\\\"foo\\\" rows=\\\"2\\\">\" + Environment.NewLine\n              + \"bar</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"HtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void TextAreaWithExplicitValue_HtmlEncodes_Value(string text, bool htmlEncode, string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            var result = helper.TextArea(\"name\", text).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"20\\\" id=\\\"name\\\" name=\\\"name\\\" rows=\\\"2\\\">\" +\n                    Environment.NewLine +\n                    encodedText +\n                    \"</textarea>\",\n                result);\n        }\n\n        [Fact]\n        public void TextAreaWithDefaultAttributes()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextAreaViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextArea(\"foo\");\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"20\\\" id=\\\"foo\\\" name=\\\"foo\\\" rows=\\\"2\\\">\" + Environment.NewLine\n              + \"ViewDataFoo</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaWithZeroRowsAndColumns()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextAreaViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextArea(\"foo\", null, 0, 0, null);\n\n            // Assert\n            Assert.Equal(\n                \"<textarea id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"ViewDataFoo</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaWithDotReplacementForId()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextAreaViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextArea(\"foo.bar.baz\");\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"20\\\" id=\\\"foo_bar_baz\\\" name=\\\"foo.bar.baz\\\" rows=\\\"2\\\">\" + Environment.NewLine\n              + \"</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaWithObjectAttributes()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextAreaViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextArea(\"foo\", _textAreaAttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"12\\\" id=\\\"foo\\\" name=\\\"foo\\\" rows=\\\"15\\\">\" + Environment.NewLine\n              + \"ViewDataFoo</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void TextAreaWithObjectAttributes_AttributeEncodes_AddedHtmlAttributes(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.TemplateInfo.HtmlFieldPrefix = \"Prefix\";\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            var result = helper.TextArea(name: \"\", htmlAttributes: new { attribute = text, }).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<textarea attribute=\\\"\" +\n                    encodedText +\n                    \"\\\" cols=\\\"20\\\" id=\\\"Prefix\\\" name=\\\"Prefix\\\" rows=\\\"2\\\">\" +\n                    Environment.NewLine +\n                    \"</textarea>\",\n                result);\n        }\n\n        [Fact]\n        public void TextAreaWithObjectAttributesWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextAreaViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextArea(\"foo\", _textAreaAttributesObjectUnderscoresDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"12\\\" foo-bar=\\\"baz\\\" id=\\\"foo\\\" name=\\\"foo\\\" rows=\\\"15\\\">\" + Environment.NewLine\n              + \"ViewDataFoo</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaWithDictionaryAttributes()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextAreaViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextArea(\"foo\", _textAreaAttributesDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"12\\\" id=\\\"foo\\\" name=\\\"foo\\\" rows=\\\"15\\\">\" + Environment.NewLine\n              + \"ViewDataFoo</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaWithExplicitValueAndObjectAttributes()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextAreaViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextArea(\"foo\", \"Hello World\", _textAreaAttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"12\\\" id=\\\"foo\\\" name=\\\"foo\\\" rows=\\\"15\\\">\" + Environment.NewLine\n              + \"Hello World</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaWithExplicitValueAndObjectAttributesWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextAreaViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextArea(\"foo\", \"Hello World\", _textAreaAttributesObjectUnderscoresDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"12\\\" foo-bar=\\\"baz\\\" id=\\\"foo\\\" name=\\\"foo\\\" rows=\\\"15\\\">\" + Environment.NewLine\n              + \"Hello World</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaWithExplicitValueAndDictionaryAttributes()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextAreaViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextArea(\"foo\", \"<Hello World>\", _textAreaAttributesDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"12\\\" id=\\\"foo\\\" name=\\\"foo\\\" rows=\\\"15\\\">\" + Environment.NewLine\n              + \"&lt;Hello World&gt;</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaWithNoValueAndObjectAttributes()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextAreaViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextArea(\"baz\", _textAreaAttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"12\\\" id=\\\"baz\\\" name=\\\"baz\\\" rows=\\\"15\\\">\" + Environment.NewLine\n              + \"</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaWithNullValue()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextAreaViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextArea(\"foo\", null, null);\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"20\\\" id=\\\"foo\\\" name=\\\"foo\\\" rows=\\\"2\\\">\" + Environment.NewLine\n              + \"ViewDataFoo</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaWithViewDataErrors()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextAreaViewDataWithErrors());\n\n            // Act\n            MvcHtmlString html = helper.TextArea(\"foo\", _textAreaAttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<textarea class=\\\"input-validation-error\\\" cols=\\\"12\\\" id=\\\"foo\\\" name=\\\"foo\\\" rows=\\\"15\\\">\" + Environment.NewLine\n              + \"AttemptedValueFoo</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaWithViewDataErrorsAndCustomClass()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper(GetTextAreaViewDataWithErrors());\n\n            // Act\n            MvcHtmlString html = helper.TextArea(\"foo\", new { @class = \"foo-class\" });\n\n            // Assert\n            Assert.Equal(\n                \"<textarea class=\\\"input-validation-error foo-class\\\" cols=\\\"20\\\" id=\\\"foo\\\" name=\\\"foo\\\" rows=\\\"2\\\">\" + Environment.NewLine\n              + \"AttemptedValueFoo</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaWithPrefix()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.TextArea(\"foo\", \"bar\");\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"20\\\" id=\\\"MyPrefix_foo\\\" name=\\\"MyPrefix.foo\\\" rows=\\\"2\\\">\" + Environment.NewLine\n              + \"bar</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaWithPrefixAndEmptyName()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.TextArea(\"\", \"bar\");\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"20\\\" id=\\\"MyPrefix\\\" name=\\\"MyPrefix\\\" rows=\\\"2\\\">\" + Environment.NewLine\n              + \"bar</textarea>\",\n                html.ToHtmlString());\n        }\n\n        // TextAreaFor\n\n        [Fact]\n        public void TextAreaForWithNullExpression()\n        {\n            // Arrange\n            HtmlHelper<TextAreaModel> helper = MvcHelper.GetHtmlHelper(GetTextAreaViewData());\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => helper.TextAreaFor<TextAreaModel, object>(null),\n                \"expression\"\n                );\n        }\n\n        [Fact]\n        public void TextAreaForWithOutOfRangeColsThrows()\n        {\n            // Arrange\n            HtmlHelper<TextAreaModel> helper = MvcHelper.GetHtmlHelper(GetTextAreaViewData());\n\n            // Act & Assert\n            Assert.ThrowsArgumentOutOfRange(\n                () => helper.TextAreaFor(m => m.foo, 0, -1, null /* htmlAttributes */),\n                \"columns\",\n                \"The value must be greater than or equal to zero.\"\n                );\n        }\n\n        [Fact]\n        public void TextAreaForWithOutOfRangeRowsThrows()\n        {\n            // Arrange\n            HtmlHelper<TextAreaModel> helper = MvcHelper.GetHtmlHelper(GetTextAreaViewData());\n\n            // Act & Assert\n            Assert.ThrowsArgumentOutOfRange(\n                () => helper.TextAreaFor(m => m.foo, -1, 0, null /* htmlAttributes */),\n                \"rows\",\n                \"The value must be greater than or equal to zero.\"\n                );\n        }\n\n        [Fact]\n        public void TextAreaForParameterDictionaryMerging()\n        {\n            // Arrange\n            HtmlHelper<TextAreaModel> helper = MvcHelper.GetHtmlHelper(GetTextAreaViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextAreaFor(m => m.foo, new { rows = \"30\" });\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"20\\\" id=\\\"foo\\\" name=\\\"foo\\\" rows=\\\"30\\\">\" + Environment.NewLine\n              + \"ViewItemFoo</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaForParameterDictionaryMerging_Unobtrusive()\n        {\n            // Arrange\n            HtmlHelper<TextAreaModel> helper = MvcHelper.GetHtmlHelper(GetTextAreaViewData());\n            helper.ViewContext.ClientValidationEnabled = true;\n            helper.ViewContext.UnobtrusiveJavaScriptEnabled = true;\n            helper.ViewContext.FormContext = new FormContext();\n            ModelMetadata modelMetadata = null;\n            helper.ClientValidationRuleFactory = (name, metadata) => {\n                modelMetadata = metadata;\n                return new[] { new ModelClientValidationRule { ValidationType = \"type\", ErrorMessage = \"error\" } };\n            };\n\n            // Act\n            MvcHtmlString html = helper.TextAreaFor(m => m.foo, new { rows = \"30\" });\n\n            // Assert\n            Assert.NotNull(modelMetadata);\n            Assert.Equal(\"foo\", modelMetadata.PropertyName);\n            Assert.Equal(\n                \"<textarea cols=\\\"20\\\" data-val=\\\"true\\\" data-val-type=\\\"error\\\" id=\\\"foo\\\" name=\\\"foo\\\" rows=\\\"30\\\">\" + Environment.NewLine\n              + \"ViewItemFoo</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaForWithDefaultAttributes()\n        {\n            // Arrange\n            HtmlHelper<TextAreaModel> helper = MvcHelper.GetHtmlHelper(GetTextAreaViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextAreaFor(m => m.foo);\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"20\\\" id=\\\"foo\\\" name=\\\"foo\\\" rows=\\\"2\\\">\" + Environment.NewLine\n              + \"ViewItemFoo</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaForWithZeroRowsAndColumns()\n        {\n            // Arrange\n            HtmlHelper<TextAreaModel> helper = MvcHelper.GetHtmlHelper(GetTextAreaViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextAreaFor(m => m.foo, 0, 0, null);\n\n            // Assert\n            Assert.Equal(\n                \"<textarea id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"ViewItemFoo</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void TextAreaFor_AttributeEncodes_Prefix(string text, bool htmlEncode, string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.TemplateInfo.HtmlFieldPrefix = text;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            // htmlAttributes included only to avoid special-cased renaming done for id attribute.\n            var result = helper.TextAreaFor(m => m, htmlAttributes: new { id = \"id\", }).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"20\\\" id=\\\"id\\\" name=\\\"\" +\n                    encodedText +\n                    \"\\\" rows=\\\"2\\\">\" +\n                    Environment.NewLine +\n                    \"</textarea>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"HtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void TextAreaFor_HtmlEncodes_Value(string text, bool htmlEncode, string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(text);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            var result = helper.TextAreaFor(m => text).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"20\\\" id=\\\"text\\\" name=\\\"text\\\" rows=\\\"2\\\">\" +\n                    Environment.NewLine +\n                    encodedText +\n                    \"</textarea>\",\n                result);\n        }\n\n        [Fact]\n        public void TextAreaForWithObjectAttributes()\n        {\n            // Arrange\n            HtmlHelper<TextAreaModel> helper = MvcHelper.GetHtmlHelper(GetTextAreaViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextAreaFor(m => m.foo, _textAreaAttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"12\\\" id=\\\"foo\\\" name=\\\"foo\\\" rows=\\\"15\\\">\" + Environment.NewLine\n              + \"ViewItemFoo</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void TextAreaForWithObjectAttributes_AttributeEncodes_AddedHtmlAttributes(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.TemplateInfo.HtmlFieldPrefix = \"Prefix\";\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            var result = helper.TextAreaFor(m => m, htmlAttributes: new { attribute = text, }).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<textarea attribute=\\\"\" +\n                    encodedText +\n                    \"\\\" cols=\\\"20\\\" id=\\\"Prefix\\\" name=\\\"Prefix\\\" rows=\\\"2\\\">\" +\n                    Environment.NewLine +\n                    \"</textarea>\",\n                result);\n        }\n\n        [Fact]\n        public void TextAreaForWithObjectAttributesWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper<TextAreaModel> helper = MvcHelper.GetHtmlHelper(GetTextAreaViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextAreaFor(m => m.foo, _textAreaAttributesObjectUnderscoresDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"12\\\" foo-bar=\\\"baz\\\" id=\\\"foo\\\" name=\\\"foo\\\" rows=\\\"15\\\">\" + Environment.NewLine\n              + \"ViewItemFoo</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaForWithDictionaryAttributes()\n        {\n            // Arrange\n            HtmlHelper<TextAreaModel> helper = MvcHelper.GetHtmlHelper(GetTextAreaViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextAreaFor(m => m.foo, _textAreaAttributesDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"12\\\" id=\\\"foo\\\" name=\\\"foo\\\" rows=\\\"15\\\">\" + Environment.NewLine\n              + \"ViewItemFoo</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaForWithViewDataErrors()\n        {\n            // Arrange\n            HtmlHelper<TextAreaModel> helper = MvcHelper.GetHtmlHelper(GetTextAreaViewDataWithErrors());\n\n            // Act\n            MvcHtmlString html = helper.TextAreaFor(m => m.foo, _textAreaAttributesObjectDictionary);\n\n            // Assert\n            Assert.Equal(\n                \"<textarea class=\\\"input-validation-error\\\" cols=\\\"12\\\" id=\\\"foo\\\" name=\\\"foo\\\" rows=\\\"15\\\">\" + Environment.NewLine\n              + \"AttemptedValueFoo</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaForWithViewDataErrorsAndCustomClass()\n        {\n            // Arrange\n            HtmlHelper<TextAreaModel> helper = MvcHelper.GetHtmlHelper(GetTextAreaViewDataWithErrors());\n\n            // Act\n            MvcHtmlString html = helper.TextAreaFor(m => m.foo, new { @class = \"foo-class\" });\n\n            // Assert\n            Assert.Equal(\n                \"<textarea class=\\\"input-validation-error foo-class\\\" cols=\\\"20\\\" id=\\\"foo\\\" name=\\\"foo\\\" rows=\\\"2\\\">\" + Environment.NewLine\n              + \"AttemptedValueFoo</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaForWithPrefix()\n        {\n            // Arrange\n            HtmlHelper<TextAreaModel> helper = MvcHelper.GetHtmlHelper(GetTextAreaViewData());\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.TextAreaFor(m => m.foo);\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"20\\\" id=\\\"MyPrefix_foo\\\" name=\\\"MyPrefix.foo\\\" rows=\\\"2\\\">\" + Environment.NewLine\n              + \"ViewItemFoo</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaForWithPrefixAndEmptyName()\n        {\n            // Arrange\n            HtmlHelper<TextAreaModel> helper = MvcHelper.GetHtmlHelper(GetTextAreaViewData());\n            helper.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = \"MyPrefix\";\n\n            // Act\n            MvcHtmlString html = helper.TextAreaFor(m => m);\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"20\\\" id=\\\"MyPrefix\\\" name=\\\"MyPrefix\\\" rows=\\\"2\\\">\" + Environment.NewLine\n              + \"System.Web.Mvc.Html.Test.TextAreaExtensionsTest+TextAreaModel</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaForParameterDictionaryMergingWithObjectValues()\n        {\n            // Arrange\n            HtmlHelper<TextAreaModel> helper = MvcHelper.GetHtmlHelper(GetTextAreaViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextAreaFor(m => m.foo, 10, 25, new { rows = \"30\" });\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"25\\\" id=\\\"foo\\\" name=\\\"foo\\\" rows=\\\"10\\\">\" + Environment.NewLine\n              + \"ViewItemFoo</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaForParameterDictionaryMergingWithObjectValuesWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper<TextAreaModel> helper = MvcHelper.GetHtmlHelper(GetTextAreaViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextAreaFor(m => m.foo, 10, 25, new { rows = \"30\", foo_bar = \"baz\" });\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"25\\\" foo-bar=\\\"baz\\\" id=\\\"foo\\\" name=\\\"foo\\\" rows=\\\"10\\\">\" + Environment.NewLine\n              + \"ViewItemFoo</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaForParameterDictionaryMergingWithDictionaryValues()\n        {\n            // Arrange\n            HtmlHelper<TextAreaModel> helper = MvcHelper.GetHtmlHelper(GetTextAreaViewData());\n\n            // Act\n            MvcHtmlString html = helper.TextAreaFor(m => m.foo, 10, 25, new RouteValueDictionary(new { rows = \"30\" }));\n\n            // Assert\n            Assert.Equal(\n                \"<textarea cols=\\\"25\\\" id=\\\"foo\\\" name=\\\"foo\\\" rows=\\\"10\\\">\" + Environment.NewLine\n              + \"ViewItemFoo</textarea>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaHelperDoesNotEncodeInnerHtmlPrefix()\n        {\n            // Arrange\n            HtmlHelper helper = MvcHelper.GetHtmlHelper();\n            ModelMetadata metadata = ModelMetadata.FromStringExpression(\"foo\", helper.ViewData);\n            metadata.Model = \"<model>\";\n\n            // Act\n            MvcHtmlString html = TextAreaExtensions.TextAreaHelper(helper, metadata, \"testEncoding\", rowsAndColumns: null,\n                                                                   htmlAttributes: null, innerHtmlPrefix: \"<prefix>\");\n\n            // Assert\n            Assert.Equal(\"<textarea id=\\\"testEncoding\\\" name=\\\"testEncoding\\\"><prefix>&lt;model&gt;</textarea>\", html.ToHtmlString());\n        }\n\n        public void Dispose()\n        {\n            // Reset ScopeStorage (written via e.g. ViewContext.ClientValidationEnabled) between tests to avoid unexpected interactions.\n            ScopeStorage.CurrentProvider = new StaticScopeStorageProvider();\n            ScopeStorage.GlobalScope.Clear();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Html/Test/ValidationExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing System.Web.Routing;\nusing System.Web.WebPages.Scope;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\nusing Moq;\n\nnamespace System.Web.Mvc.Html.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")]\n    public class ValidationExtensionsTest : IDisposable\n    {\n        // Validate\n\n        [Fact]\n        public void Validate_AddsClientValidationMetadata()\n        {\n            var originalProviders = ModelValidatorProviders.Providers.ToArray();\n            ModelValidatorProviders.Providers.Clear();\n\n            try\n            {\n                // Arrange\n                HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n                FormContext formContext = new FormContext()\n                {\n                    FormId = \"form_id\"\n                };\n                htmlHelper.ViewContext.ClientValidationEnabled = true;\n                htmlHelper.ViewContext.FormContext = formContext;\n\n                ModelClientValidationRule[] expectedValidationRules = new ModelClientValidationRule[]\n                {\n                    new ModelClientValidationRule() { ValidationType = \"ValidationRule1\" },\n                    new ModelClientValidationRule() { ValidationType = \"ValidationRule2\" }\n                };\n\n                Mock<ModelValidator> mockValidator = new Mock<ModelValidator>(ModelMetadata.FromStringExpression(\"\", htmlHelper.ViewContext.ViewData), htmlHelper.ViewContext);\n                mockValidator.Setup(v => v.GetClientValidationRules())\n                    .Returns(expectedValidationRules);\n                Mock<ModelValidatorProvider> mockValidatorProvider = new Mock<ModelValidatorProvider>();\n                mockValidatorProvider.Setup(vp => vp.GetValidators(It.IsAny<ModelMetadata>(), It.IsAny<ControllerContext>()))\n                    .Returns(new[] { mockValidator.Object });\n                ModelValidatorProviders.Providers.Add(mockValidatorProvider.Object);\n\n                // Act\n                htmlHelper.Validate(\"baz\");\n\n                // Assert\n                Assert.NotNull(formContext.GetValidationMetadataForField(\"baz\"));\n                Assert.Equal(expectedValidationRules, formContext.FieldValidators[\"baz\"].ValidationRules.ToArray());\n            }\n            finally\n            {\n                ModelValidatorProviders.Providers.Clear();\n                foreach (var provider in originalProviders)\n                {\n                    ModelValidatorProviders.Providers.Add(provider);\n                }\n            }\n        }\n\n        [Fact]\n        public void Validate_DoesNothingIfClientValidationIsNotEnabled()\n        {\n            // Arrange\n            HtmlHelper<ValidationModel> htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n            htmlHelper.ViewContext.FormContext = new FormContext();\n            htmlHelper.ViewContext.ClientValidationEnabled = false;\n\n            // Act\n            htmlHelper.Validate(\"foo\");\n\n            // Assert\n            Assert.Empty(htmlHelper.ViewContext.FormContext.FieldValidators);\n        }\n\n        [Fact]\n        public void Validate_DoesNothingIfUnobtrusiveJavaScriptIsEnabled()\n        {\n            // Arrange\n            HtmlHelper<ValidationModel> htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n            htmlHelper.ViewContext.FormContext = new FormContext();\n            htmlHelper.ViewContext.ClientValidationEnabled = true;\n            htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled = true;\n\n            // Act\n            htmlHelper.Validate(\"foo\");\n\n            // Assert\n            Assert.Empty(htmlHelper.ViewContext.FormContext.FieldValidators);\n        }\n\n        [Fact]\n        public void Validate_ThrowsIfModelNameIsNull()\n        {\n            // Arrange\n            HtmlHelper<ValidationModel> htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { htmlHelper.Validate((string)null /* modelName */); }, \"modelName\");\n        }\n\n        [Fact]\n        public void ValidateFor_AddsClientValidationMetadata()\n        {\n            var originalProviders = ModelValidatorProviders.Providers.ToArray();\n            ModelValidatorProviders.Providers.Clear();\n\n            try\n            {\n                // Arrange\n                HtmlHelper<ValidationModel> htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n                FormContext formContext = new FormContext()\n                {\n                    FormId = \"form_id\"\n                };\n                htmlHelper.ViewContext.ClientValidationEnabled = true;\n                htmlHelper.ViewContext.FormContext = formContext;\n\n                ModelClientValidationRule[] expectedValidationRules = new ModelClientValidationRule[]\n                {\n                    new ModelClientValidationRule() { ValidationType = \"ValidationRule1\" },\n                    new ModelClientValidationRule() { ValidationType = \"ValidationRule2\" }\n                };\n\n                Mock<ModelValidator> mockValidator = new Mock<ModelValidator>(ModelMetadata.FromStringExpression(\"\", htmlHelper.ViewContext.ViewData), htmlHelper.ViewContext);\n                mockValidator.Setup(v => v.GetClientValidationRules())\n                    .Returns(expectedValidationRules);\n                Mock<ModelValidatorProvider> mockValidatorProvider = new Mock<ModelValidatorProvider>();\n                mockValidatorProvider.Setup(vp => vp.GetValidators(It.IsAny<ModelMetadata>(), It.IsAny<ControllerContext>()))\n                    .Returns(new[] { mockValidator.Object });\n                ModelValidatorProviders.Providers.Add(mockValidatorProvider.Object);\n\n                // Act\n                htmlHelper.ValidateFor(m => m.baz);\n\n                // Assert\n                Assert.NotNull(formContext.GetValidationMetadataForField(\"baz\"));\n                Assert.Equal(expectedValidationRules, formContext.FieldValidators[\"baz\"].ValidationRules.ToArray());\n            }\n            finally\n            {\n                ModelValidatorProviders.Providers.Clear();\n                foreach (var provider in originalProviders)\n                {\n                    ModelValidatorProviders.Providers.Add(provider);\n                }\n            }\n        }\n\n        // ValidationMessage\n\n        [Fact]\n        public void ValidationMessageAllowsEmptyModelName()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary();\n            vdd.ModelState.AddModelError(\"\", \"some error text\");\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(vdd);\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessage(\"\");\n\n            // Assert\n            Assert.Equal(\"<span class=\\\"field-validation-error\\\">some error text</span>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageReturnsNullForNullModelState()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithNullModelState());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessage(\"foo\");\n\n            // Assert\n            Assert.Null(html);\n        }\n\n        [Fact]\n        public void ValidationMessageReturnsFirstErrorWithMessage()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessage(\"foo\");\n\n            // Assert\n            Assert.Equal(\"<span class=\\\"field-validation-error\\\">foo error &lt;1&gt;</span>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageReturnsGenericMessageInsteadOfExceptionText()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessage(\"quux\");\n\n            // Assert\n            Assert.Equal(\"<span class=\\\"field-validation-error\\\">The value &#39;quuxValue&#39; is invalid.</span>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageReturnsNullForInvalidName()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessage(\"boo\");\n\n            // Assert\n            Assert.Null(html);\n        }\n\n        [Fact]\n        public void ValidationMessageReturnsWithObjectAttributes()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessage(\"foo\", new { bar = \"bar\" });\n\n            // Assert\n            Assert.Equal(\"<span bar=\\\"bar\\\" class=\\\"field-validation-error\\\">foo error &lt;1&gt;</span>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageReturnsWithObjectAttributesWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessage(\"foo\", new { foo_bar = \"bar\" });\n\n            // Assert\n            Assert.Equal(\"<span class=\\\"field-validation-error\\\" foo-bar=\\\"bar\\\">foo error &lt;1&gt;</span>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageReturnsWithCustomMessage()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessage(\"foo\", \"bar error\");\n\n            // Assert\n            Assert.Equal(\"<span class=\\\"field-validation-error\\\">bar error</span>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageReturnsWithCustomMessageAndObjectAttributes()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessage(\"foo\", \"bar error\", new { baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(\"<span baz=\\\"baz\\\" class=\\\"field-validation-error\\\">bar error</span>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageReturnsWithCustomMessageAndObjectAttributesWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessage(\"foo\", \"bar error\", new { foo_baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(\"<span class=\\\"field-validation-error\\\" foo-baz=\\\"baz\\\">bar error</span>\", html.ToHtmlString());\n        }\n\n\n        [Fact]\n        public void ValidationMessageWithOverriddenTag_UsesGivenTag()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n            htmlHelper.SetValidationMessageElement(\"label\");\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessage(\"foo\", \"bar error\");\n\n            // Assert\n            Assert.Equal(\n                \"<label class=\\\"field-validation-error\\\">bar error</label>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageWithOverriddenTag_SetPropertyInValidationMessageElement_UsesGivenTag()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n            htmlHelper.ViewContext.ValidationMessageElement = \"label\";\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessage(\"foo\", \"bar error\");\n\n            // Assert\n            Assert.Equal(\n                \"<label class=\\\"field-validation-error\\\">bar error</label>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageWithCustomTag()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessage(\"foo\", \"bar error\", \"label\");\n\n            // Assert\n            Assert.Equal(\n                \"<label class=\\\"field-validation-error\\\">bar error</label>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageWithObjectAttributesWithCustomTag()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessage(\"foo\", \"bar error\", new { baz = \"baz\"}, \"label\");\n\n            // Assert\n            Assert.Equal(\n                \"<label baz=\\\"baz\\\" class=\\\"field-validation-error\\\">bar error</label>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageWithAttributesDictionaryWithCustomTag()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n            RouteValueDictionary htmlAttributes = new RouteValueDictionary();\n            htmlAttributes[\"baz\"] = \"baz\";\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessage(\"foo\", \"bar error\", htmlAttributes, \"label\");\n\n            // Assert\n            Assert.Equal(\n                \"<label baz=\\\"baz\\\" class=\\\"field-validation-error\\\">bar error</label>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageWithoutMessageWithAttributesDictionaryWithCustomTag()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n            RouteValueDictionary htmlAttributes = new RouteValueDictionary();\n            htmlAttributes[\"baz\"] = \"baz\";\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessage(\"foo\", htmlAttributes, \"label\");\n\n            // Assert\n            Assert.Equal(\n                \"<label baz=\\\"baz\\\" class=\\\"field-validation-error\\\">foo error &lt;1&gt;</label>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageWithoutMessageWithObjectAttributesWithCustomTag()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessage(\"foo\", new { bar = \"bar\", baz = \"baz\"}, \"label\");\n\n            // Assert\n            Assert.Equal(\n                \"<label bar=\\\"bar\\\" baz=\\\"baz\\\" class=\\\"field-validation-error\\\">foo error &lt;1&gt;</label>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageThrowsIfModelNameIsNull()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { htmlHelper.ValidationMessage(null); }, \"modelName\");\n        }\n\n        [Fact]\n        public void ValidationMessageWithClientValidation_DefaultMessage_Valid()\n        {\n            var originalProviders = ModelValidatorProviders.Providers.ToArray();\n            ModelValidatorProviders.Providers.Clear();\n\n            try\n            {\n                // Arrange\n                HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n                FormContext formContext = new FormContext();\n                htmlHelper.ViewContext.ClientValidationEnabled = true;\n                htmlHelper.ViewContext.FormContext = formContext;\n\n                ModelClientValidationRule[] expectedValidationRules = new ModelClientValidationRule[]\n                {\n                    new ModelClientValidationRule() { ValidationType = \"ValidationRule1\" },\n                    new ModelClientValidationRule() { ValidationType = \"ValidationRule2\" }\n                };\n\n                Mock<ModelValidator> mockValidator = new Mock<ModelValidator>(ModelMetadata.FromStringExpression(\"\", htmlHelper.ViewContext.ViewData), htmlHelper.ViewContext);\n                mockValidator.Setup(v => v.GetClientValidationRules())\n                    .Returns(expectedValidationRules);\n                Mock<ModelValidatorProvider> mockValidatorProvider = new Mock<ModelValidatorProvider>();\n                mockValidatorProvider.Setup(vp => vp.GetValidators(It.IsAny<ModelMetadata>(), It.IsAny<ControllerContext>()))\n                    .Returns(new[] { mockValidator.Object });\n                ModelValidatorProviders.Providers.Add(mockValidatorProvider.Object);\n\n                // Act\n                MvcHtmlString html = htmlHelper.ValidationMessage(\"baz\"); // 'baz' is valid\n\n                // Assert\n                Assert.Equal(\"<span class=\\\"field-validation-valid\\\" id=\\\"baz_validationMessage\\\"></span>\", html.ToHtmlString());\n                Assert.NotNull(formContext.GetValidationMetadataForField(\"baz\"));\n                Assert.Equal(\"baz_validationMessage\", formContext.FieldValidators[\"baz\"].ValidationMessageId);\n                Assert.True(formContext.FieldValidators[\"baz\"].ReplaceValidationMessageContents);\n                Assert.Equal(expectedValidationRules, formContext.FieldValidators[\"baz\"].ValidationRules.ToArray());\n            }\n            finally\n            {\n                ModelValidatorProviders.Providers.Clear();\n                foreach (var provider in originalProviders)\n                {\n                    ModelValidatorProviders.Providers.Add(provider);\n                }\n            }\n        }\n\n        [Fact]\n        public void ValidationMessageWithClientValidation_DefaultMessage_Valid_Unobtrusive()\n        {\n            var originalProviders = ModelValidatorProviders.Providers.ToArray();\n            ModelValidatorProviders.Providers.Clear();\n\n            try\n            {\n                // Arrange\n                HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n                FormContext formContext = new FormContext();\n                htmlHelper.ViewContext.ClientValidationEnabled = true;\n                htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled = true;\n                htmlHelper.ViewContext.FormContext = formContext;\n\n                ModelClientValidationRule[] expectedValidationRules = new ModelClientValidationRule[]\n                {\n                    new ModelClientValidationRule() { ValidationType = \"ValidationRule1\" },\n                    new ModelClientValidationRule() { ValidationType = \"ValidationRule2\" }\n                };\n\n                Mock<ModelValidator> mockValidator = new Mock<ModelValidator>(ModelMetadata.FromStringExpression(\"\", htmlHelper.ViewContext.ViewData), htmlHelper.ViewContext);\n                mockValidator.Setup(v => v.GetClientValidationRules())\n                    .Returns(expectedValidationRules);\n                Mock<ModelValidatorProvider> mockValidatorProvider = new Mock<ModelValidatorProvider>();\n                mockValidatorProvider.Setup(vp => vp.GetValidators(It.IsAny<ModelMetadata>(), It.IsAny<ControllerContext>()))\n                    .Returns(new[] { mockValidator.Object });\n                ModelValidatorProviders.Providers.Add(mockValidatorProvider.Object);\n\n                // Act\n                MvcHtmlString html = htmlHelper.ValidationMessage(\"baz\"); // 'baz' is valid\n\n                // Assert\n                Assert.Equal(\"<span class=\\\"field-validation-valid\\\" data-valmsg-for=\\\"baz\\\" data-valmsg-replace=\\\"true\\\"></span>\", html.ToHtmlString());\n            }\n            finally\n            {\n                ModelValidatorProviders.Providers.Clear();\n                foreach (var provider in originalProviders)\n                {\n                    ModelValidatorProviders.Providers.Add(provider);\n                }\n            }\n        }\n\n        [Fact]\n        public void ValidationMessageWithClientValidation_ExplicitMessage_Valid()\n        {\n            var originalProviders = ModelValidatorProviders.Providers.ToArray();\n            ModelValidatorProviders.Providers.Clear();\n\n            try\n            {\n                // Arrange\n                HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n                FormContext formContext = new FormContext();\n                htmlHelper.ViewContext.ClientValidationEnabled = true;\n                htmlHelper.ViewContext.FormContext = formContext;\n\n                ModelClientValidationRule[] expectedValidationRules = new ModelClientValidationRule[]\n                {\n                    new ModelClientValidationRule() { ValidationType = \"ValidationRule1\" },\n                    new ModelClientValidationRule() { ValidationType = \"ValidationRule2\" }\n                };\n\n                Mock<ModelValidator> mockValidator = new Mock<ModelValidator>(ModelMetadata.FromStringExpression(\"\", htmlHelper.ViewContext.ViewData), htmlHelper.ViewContext);\n                mockValidator.Setup(v => v.GetClientValidationRules())\n                    .Returns(expectedValidationRules);\n                Mock<ModelValidatorProvider> mockValidatorProvider = new Mock<ModelValidatorProvider>();\n                mockValidatorProvider.Setup(vp => vp.GetValidators(It.IsAny<ModelMetadata>(), It.IsAny<ControllerContext>()))\n                    .Returns(new[] { mockValidator.Object });\n                ModelValidatorProviders.Providers.Add(mockValidatorProvider.Object);\n\n                // Act\n                MvcHtmlString html = htmlHelper.ValidationMessage(\"baz\", \"some explicit message\"); // 'baz' is valid\n\n                // Assert\n                Assert.Equal(\"<span class=\\\"field-validation-valid\\\" id=\\\"baz_validationMessage\\\">some explicit message</span>\", html.ToHtmlString());\n                Assert.NotNull(formContext.GetValidationMetadataForField(\"baz\"));\n                Assert.Equal(\"baz_validationMessage\", formContext.FieldValidators[\"baz\"].ValidationMessageId);\n                Assert.False(formContext.FieldValidators[\"baz\"].ReplaceValidationMessageContents);\n                Assert.Equal(expectedValidationRules, formContext.FieldValidators[\"baz\"].ValidationRules.ToArray());\n            }\n            finally\n            {\n                ModelValidatorProviders.Providers.Clear();\n                foreach (var provider in originalProviders)\n                {\n                    ModelValidatorProviders.Providers.Add(provider);\n                }\n            }\n        }\n\n        [Fact]\n        public void ValidationMessageWithClientValidation_ExplicitMessage_Valid_Unobtrusive()\n        {\n            var originalProviders = ModelValidatorProviders.Providers.ToArray();\n            ModelValidatorProviders.Providers.Clear();\n\n            try\n            {\n                // Arrange\n                HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n                FormContext formContext = new FormContext();\n                htmlHelper.ViewContext.ClientValidationEnabled = true;\n                htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled = true;\n                htmlHelper.ViewContext.FormContext = formContext;\n\n                ModelClientValidationRule[] expectedValidationRules = new ModelClientValidationRule[]\n                {\n                    new ModelClientValidationRule() { ValidationType = \"ValidationRule1\" },\n                    new ModelClientValidationRule() { ValidationType = \"ValidationRule2\" }\n                };\n\n                Mock<ModelValidator> mockValidator = new Mock<ModelValidator>(ModelMetadata.FromStringExpression(\"\", htmlHelper.ViewContext.ViewData), htmlHelper.ViewContext);\n                mockValidator.Setup(v => v.GetClientValidationRules())\n                    .Returns(expectedValidationRules);\n                Mock<ModelValidatorProvider> mockValidatorProvider = new Mock<ModelValidatorProvider>();\n                mockValidatorProvider.Setup(vp => vp.GetValidators(It.IsAny<ModelMetadata>(), It.IsAny<ControllerContext>()))\n                    .Returns(new[] { mockValidator.Object });\n                ModelValidatorProviders.Providers.Add(mockValidatorProvider.Object);\n\n                // Act\n                MvcHtmlString html = htmlHelper.ValidationMessage(\"baz\", \"some explicit message\"); // 'baz' is valid\n\n                // Assert\n                Assert.Equal(\"<span class=\\\"field-validation-valid\\\" data-valmsg-for=\\\"baz\\\" data-valmsg-replace=\\\"false\\\">some explicit message</span>\", html.ToHtmlString());\n            }\n            finally\n            {\n                ModelValidatorProviders.Providers.Clear();\n                foreach (var provider in originalProviders)\n                {\n                    ModelValidatorProviders.Providers.Add(provider);\n                }\n            }\n        }\n\n        [Fact]\n        public void ValidationMessageWithModelStateAndNoErrors()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessage(\"baz\");\n\n            // Assert\n            Assert.Null(html);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationMessage_AttributeEncodes_AddedHtmlAttributes(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript();\n\n            // Act\n            var result = helper.ValidationMessage(modelName: \"name\", htmlAttributes: new { attribute = text, })\n                .ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<span attribute=\\\"\" +\n                    encodedText +\n                    \"\\\" class=\\\"field-validation-valid\\\" data-valmsg-for=\\\"name\\\" data-valmsg-replace=\\\"true\\\">\" +\n                    \"</span>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"HtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationMessage_HtmlEncodes_Message(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript();\n\n            // Act\n            var result = helper.ValidationMessage(modelName: \"name\", validationMessage: text).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<span class=\\\"field-validation-valid\\\" data-valmsg-for=\\\"name\\\" data-valmsg-replace=\\\"false\\\">\" +\n                    encodedText +\n                    \"</span>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"HtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationMessage_HtmlEncodes_ModelStateAttemptedValue(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.ModelState.AddModelError(key: \"name\", errorMessage: null);\n            var valueProvider = new ValueProviderResult(rawValue: null, attemptedValue: text, culture: null);\n            viewData.ModelState.SetModelValue(key: \"name\", value: valueProvider);\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript();\n\n            // Act\n            var result = helper.ValidationMessage(modelName: \"name\").ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<span class=\\\"field-validation-error\\\" data-valmsg-for=\\\"name\\\" data-valmsg-replace=\\\"true\\\">The value &#39;\" +\n                    encodedText +\n                    \"&#39; is invalid.</span>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"HtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationMessage_HtmlEncodes_ModelStateError(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.ModelState.AddModelError(\"name\", text);\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript();\n\n            // Act\n            var result = helper.ValidationMessage(modelName: \"name\").ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<span class=\\\"field-validation-error\\\" data-valmsg-for=\\\"name\\\" data-valmsg-replace=\\\"true\\\">\" +\n                    encodedText +\n                    \"</span>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationMessage_AttributeEncodes_Name(string text, bool htmlEncode, string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript();\n\n            // Act\n            var result = helper.ValidationMessage(modelName: text).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<span class=\\\"field-validation-valid\\\" data-valmsg-for=\\\"\" +\n                    encodedText +\n                    \"\\\" data-valmsg-replace=\\\"true\\\"></span>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationMessage_AttributeEncodes_Prefix(string text, bool htmlEncode, string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.TemplateInfo.HtmlFieldPrefix = text;\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript();\n\n            // Act\n            var result = helper.ValidationMessage(modelName: String.Empty).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<span class=\\\"field-validation-valid\\\" data-valmsg-for=\\\"\" +\n                    encodedText +\n                    \"\\\" data-valmsg-replace=\\\"true\\\"></span>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData_NoEncodedText\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationMessage_DoesNotEncode_Tag(string text, bool htmlEncode)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript();\n\n            // Act\n            var result = helper.ValidationMessage(modelName: \"name\", validationMessage: null, tag: text).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<\" +\n                    text +\n                    \" class=\\\"field-validation-valid\\\" data-valmsg-for=\\\"name\\\" data-valmsg-replace=\\\"true\\\"></\" +\n                    text +\n                    \">\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationMessageNonUnobtrusive_AttributeEncodes_AddedHtmlAttributes(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript(enabled: false);\n\n            // Act\n            var result = helper.ValidationMessage(modelName: \"name\", htmlAttributes: new { attribute = text, })\n                .ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<span attribute=\\\"\" +\n                    encodedText +\n                    \"\\\" class=\\\"field-validation-valid\\\" id=\\\"name_validationMessage\\\">\" +\n                    \"</span>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"HtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationMessageNonUnobtrusive_HtmlEncodes_Message(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript(enabled: false);\n\n            // Act\n            var result = helper.ValidationMessage(modelName: \"name\", validationMessage: text).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<span class=\\\"field-validation-valid\\\" id=\\\"name_validationMessage\\\">\" + encodedText + \"</span>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"HtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationMessageNonUnobtrusive_HtmlEncodes_ModelStateAttemptedValue(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.ModelState.AddModelError(key: \"name\", errorMessage: null);\n            var valueProvider = new ValueProviderResult(rawValue: null, attemptedValue: text, culture: null);\n            viewData.ModelState.SetModelValue(key: \"name\", value: valueProvider);\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript(enabled: false);\n\n            // Act\n            var result = helper.ValidationMessage(modelName: \"name\").ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<span class=\\\"field-validation-error\\\" id=\\\"name_validationMessage\\\">The value &#39;\" +\n                    encodedText +\n                    \"&#39; is invalid.</span>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"HtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationMessageNonUnobtrusive_HtmlEncodes_ModelStateError(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.ModelState.AddModelError(\"name\", text);\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript(enabled: false);\n\n            // Act\n            var result = helper.ValidationMessage(modelName: \"name\").ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<span class=\\\"field-validation-error\\\" id=\\\"name_validationMessage\\\">\" + encodedText + \"</span>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"IdEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationMessageNonUnobtrusive_IdEncodes_Name(string text, bool htmlEncode, string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript(enabled: false);\n\n            // Act\n            var result = helper.ValidationMessage(modelName: text).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<span class=\\\"field-validation-valid\\\" id=\\\"\" + encodedText + \"_validationMessage\\\"></span>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"IdEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationMessageNonUnobtrusive_IdEncodes_Prefix(string text, bool htmlEncode, string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.TemplateInfo.HtmlFieldPrefix = text;\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript(enabled: false);\n\n            // Act\n            var result = helper.ValidationMessage(modelName: String.Empty).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<span class=\\\"field-validation-valid\\\" id=\\\"\" + encodedText + \"_validationMessage\\\"></span>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData_NoEncodedText\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationMessageNonUnobtrusive_DoesNotEncode_Tag(string text, bool htmlEncode)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript(enabled: false);\n\n            // Act\n            var result = helper.ValidationMessage(modelName: \"name\", validationMessage: null, tag: text).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<\" + text + \" class=\\\"field-validation-valid\\\" id=\\\"name_validationMessage\\\"></\" + text + \">\",\n                result);\n        }\n\n        // ValidationMessageFor\n\n        [Fact]\n        public void ValidationMessageForThrowsIfExpressionIsNull()\n        {\n            // Arrange\n            HtmlHelper<object> htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => htmlHelper.ValidationMessageFor<object, object>(null),\n                \"expression\"\n                );\n        }\n\n        [Fact]\n        public void ValidationMessageForReturnsNullIfModelStateIsNull()\n        {\n            // Arrange\n            HtmlHelper<ValidationModel> htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithNullModelState());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessageFor(m => m.foo);\n\n            // Assert\n            Assert.Null(html);\n        }\n\n        [Fact]\n        public void ValidationMessageForReturnsFirstErrorWithErrorMessage()\n        {\n            // Arrange\n            HtmlHelper<ValidationModel> htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessageFor(m => m.foo);\n\n            // Assert\n            Assert.Equal(\"<span class=\\\"field-validation-error\\\">foo error &lt;1&gt;</span>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageForReturnsGenericMessageInsteadOfExceptionText()\n        {\n            // Arrange\n            HtmlHelper<ValidationModel> htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessageFor(m => m.quux);\n\n            // Assert\n            Assert.Equal(\"<span class=\\\"field-validation-error\\\">The value &#39;quuxValue&#39; is invalid.</span>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageForReturnsWithObjectAttributes()\n        {\n            // Arrange\n            HtmlHelper<ValidationModel> htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessageFor(m => m.foo, null /* validationMessage */, new { bar = \"bar\" });\n\n            // Assert\n            Assert.Equal(\"<span bar=\\\"bar\\\" class=\\\"field-validation-error\\\">foo error &lt;1&gt;</span>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageForReturnsWithObjectAttributesWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper<ValidationModel> htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessageFor(m => m.foo, null /* validationMessage */, new { foo_bar = \"bar\" });\n\n            // Assert\n            Assert.Equal(\"<span class=\\\"field-validation-error\\\" foo-bar=\\\"bar\\\">foo error &lt;1&gt;</span>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageForReturnsWithCustomMessage()\n        {\n            // Arrange\n            HtmlHelper<ValidationModel> htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessageFor(m => m.foo, \"bar error\");\n\n            // Assert\n            Assert.Equal(\"<span class=\\\"field-validation-error\\\">bar error</span>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageForReturnsWithCustomMessageAndObjectAttributes()\n        {\n            // Arrange\n            HtmlHelper<ValidationModel> htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessageFor(m => m.foo, \"bar error\", new { baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(\"<span baz=\\\"baz\\\" class=\\\"field-validation-error\\\">bar error</span>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageForWithOverriddenTag_UsesGivenTag()\n        {\n            // Arrange\n            HtmlHelper<ValidationModel> htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n            htmlHelper.SetValidationMessageElement(\"label\");\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessageFor(m => m.foo, \"bar error\");\n\n            // Assert\n            Assert.Equal(\"<label class=\\\"field-validation-error\\\">bar error</label>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageForWithCustomTag()\n        {\n            // Arrange\n            HtmlHelper<ValidationModel> htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessageFor(m => m.foo, \"bar error\", \"label\");\n\n            // Assert\n            Assert.Equal(\"<label class=\\\"field-validation-error\\\">bar error</label>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageForWithDictionaryAndCustomTag()\n        {\n            // Arrange\n            HtmlHelper<ValidationModel> htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n            RouteValueDictionary htmlAttributes = new RouteValueDictionary();\n            htmlAttributes[\"class\"] = \"my-class\";\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessageFor(m => m.foo, \"bar error\", htmlAttributes, \"label\");\n\n            // Assert\n            Assert.Equal(\"<label class=\\\"field-validation-error my-class\\\">bar error</label>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageForWithObjectAttributesAndCustomTag()\n        {\n            // Arrange\n            HtmlHelper<ValidationModel> htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessageFor(m => m.foo, \"bar error\", new { @class = \"baz\" }, \"label\");\n\n            // Assert\n            Assert.Equal(\"<label class=\\\"field-validation-error baz\\\">bar error</label>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageForWithClientValidation()\n        {\n            var originalProviders = ModelValidatorProviders.Providers.ToArray();\n            ModelValidatorProviders.Providers.Clear();\n\n            try\n            {\n                // Arrange\n                HtmlHelper<ValidationModel> htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n                FormContext formContext = new FormContext();\n                htmlHelper.ViewContext.ClientValidationEnabled = true;\n                htmlHelper.ViewContext.FormContext = formContext;\n\n                ModelClientValidationRule[] expectedValidationRules = new ModelClientValidationRule[]\n                {\n                    new ModelClientValidationRule() { ValidationType = \"ValidationRule1\" },\n                    new ModelClientValidationRule() { ValidationType = \"ValidationRule2\" }\n                };\n\n                Mock<ModelValidator> mockValidator = new Mock<ModelValidator>(ModelMetadata.FromStringExpression(\"\", htmlHelper.ViewContext.ViewData), htmlHelper.ViewContext);\n                mockValidator.Setup(v => v.GetClientValidationRules())\n                    .Returns(expectedValidationRules);\n                Mock<ModelValidatorProvider> mockValidatorProvider = new Mock<ModelValidatorProvider>();\n                mockValidatorProvider.Setup(vp => vp.GetValidators(It.IsAny<ModelMetadata>(), It.IsAny<ControllerContext>()))\n                    .Returns(new[] { mockValidator.Object });\n                ModelValidatorProviders.Providers.Add(mockValidatorProvider.Object);\n\n                // Act\n                MvcHtmlString html = htmlHelper.ValidationMessageFor(m => m.baz);\n\n                // Assert\n                Assert.Equal(\"<span class=\\\"field-validation-valid\\\" id=\\\"baz_validationMessage\\\"></span>\", html.ToHtmlString());\n                Assert.NotNull(formContext.GetValidationMetadataForField(\"baz\"));\n                Assert.Equal(\"baz_validationMessage\", formContext.FieldValidators[\"baz\"].ValidationMessageId);\n                Assert.Equal(expectedValidationRules, formContext.FieldValidators[\"baz\"].ValidationRules.ToArray());\n            }\n            finally\n            {\n                ModelValidatorProviders.Providers.Clear();\n                foreach (var provider in originalProviders)\n                {\n                    ModelValidatorProviders.Providers.Add(provider);\n                }\n            }\n        }\n\n        [Fact]\n        public void ValidationMessageForWithClientValidation_Unobtrusive()\n        {\n            var originalProviders = ModelValidatorProviders.Providers.ToArray();\n            ModelValidatorProviders.Providers.Clear();\n\n            try\n            {\n                // Arrange\n                HtmlHelper<ValidationModel> htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n                FormContext formContext = new FormContext();\n                htmlHelper.ViewContext.ClientValidationEnabled = true;\n                htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled = true;\n                htmlHelper.ViewContext.FormContext = formContext;\n\n                ModelClientValidationRule[] expectedValidationRules = new ModelClientValidationRule[]\n                {\n                    new ModelClientValidationRule() { ValidationType = \"ValidationRule1\" },\n                    new ModelClientValidationRule() { ValidationType = \"ValidationRule2\" }\n                };\n\n                Mock<ModelValidator> mockValidator = new Mock<ModelValidator>(ModelMetadata.FromStringExpression(\"\", htmlHelper.ViewContext.ViewData), htmlHelper.ViewContext);\n                mockValidator.Setup(v => v.GetClientValidationRules())\n                    .Returns(expectedValidationRules);\n                Mock<ModelValidatorProvider> mockValidatorProvider = new Mock<ModelValidatorProvider>();\n                mockValidatorProvider.Setup(vp => vp.GetValidators(It.IsAny<ModelMetadata>(), It.IsAny<ControllerContext>()))\n                    .Returns(new[] { mockValidator.Object });\n                ModelValidatorProviders.Providers.Add(mockValidatorProvider.Object);\n\n                // Act\n                MvcHtmlString html = htmlHelper.ValidationMessageFor(m => m.baz);\n\n                // Assert\n                Assert.Equal(\"<span class=\\\"field-validation-valid\\\" data-valmsg-for=\\\"baz\\\" data-valmsg-replace=\\\"true\\\"></span>\", html.ToHtmlString());\n            }\n            finally\n            {\n                ModelValidatorProviders.Providers.Clear();\n                foreach (var provider in originalProviders)\n                {\n                    ModelValidatorProviders.Providers.Add(provider);\n                }\n            }\n        }\n\n        [Fact]\n        public void ValidationMessageForWithModelStateAndNoErrors()\n        {\n            // Arrange\n            HtmlHelper<ValidationModel> htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessageFor(m => m.baz);\n\n            // Assert\n            Assert.Null(html);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationMessageFor_AttributeEncodes_AddedHtmlAttributes(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript();\n            string name = null;\n\n            // Act\n            var result =\n                helper.ValidationMessageFor(m => name, validationMessage: null, htmlAttributes: new { attribute = text, })\n                .ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<span attribute=\\\"\" +\n                    encodedText +\n                    \"\\\" class=\\\"field-validation-valid\\\" data-valmsg-for=\\\"name\\\" data-valmsg-replace=\\\"true\\\">\" +\n                    \"</span>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"HtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationMessageFor_HtmlEncodes_Message(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript();\n            string name = null;\n\n            // Act\n            var result = helper.ValidationMessageFor(m => name, validationMessage: text).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<span class=\\\"field-validation-valid\\\" data-valmsg-for=\\\"name\\\" data-valmsg-replace=\\\"false\\\">\" +\n                    encodedText +\n                    \"</span>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"HtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationMessageFor_HtmlEncodes_ModelStateAttemptedValue(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.ModelState.AddModelError(key: \"name\", errorMessage: null);\n            var valueProvider = new ValueProviderResult(rawValue: null, attemptedValue: text, culture: null);\n            viewData.ModelState.SetModelValue(key: \"name\", value: valueProvider);\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript();\n            string name = null;\n\n            // Act\n            var result = helper.ValidationMessageFor(m => name).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<span class=\\\"field-validation-error\\\" data-valmsg-for=\\\"name\\\" data-valmsg-replace=\\\"true\\\">The value &#39;\" +\n                    encodedText +\n                    \"&#39; is invalid.</span>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"HtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationMessageFor_HtmlEncodes_ModelStateError(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.ModelState.AddModelError(\"name\", text);\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript();\n            string name = null;\n\n            // Act\n            var result = helper.ValidationMessageFor(m => name).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<span class=\\\"field-validation-error\\\" data-valmsg-for=\\\"name\\\" data-valmsg-replace=\\\"true\\\">\" +\n                    encodedText +\n                    \"</span>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationMessageFor_AttributeEncodes_Prefix(string text, bool htmlEncode, string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.TemplateInfo.HtmlFieldPrefix = text;\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript();\n            string name = null;\n\n            // Act\n            var result = helper.ValidationMessageFor(m => name).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<span class=\\\"field-validation-valid\\\" data-valmsg-for=\\\"\" +\n                    encodedText +\n                    \".name\\\" data-valmsg-replace=\\\"true\\\"></span>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData_NoEncodedText\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationMessageFor_DoesNotEncode_Tag(string text, bool htmlEncode)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript();\n            string name = null;\n\n            // Act\n            var result = helper.ValidationMessageFor(m => name, validationMessage: null, tag: text).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<\" +\n                    text +\n                    \" class=\\\"field-validation-valid\\\" data-valmsg-for=\\\"name\\\" data-valmsg-replace=\\\"true\\\"></\" +\n                    text +\n                    \">\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationMessageForNonUnobtrusive_AttributeEncodes_AddedHtmlAttributes(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript(enabled: false);\n            string name = null;\n\n            // Act\n            var result = helper.ValidationMessageFor(\n                    m => name,\n                    validationMessage: null,\n                    htmlAttributes: new { attribute = text, })\n                .ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<span attribute=\\\"\" +\n                    encodedText +\n                    \"\\\" class=\\\"field-validation-valid\\\" id=\\\"name_validationMessage\\\">\" +\n                    \"</span>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"HtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationMessageForNonUnobtrusive_HtmlEncodes_Message(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript(enabled: false);\n            string name = null;\n\n            // Act\n            var result = helper.ValidationMessageFor(m => name, validationMessage: text).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<span class=\\\"field-validation-valid\\\" id=\\\"name_validationMessage\\\">\" + encodedText + \"</span>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"HtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationMessageForNonUnobtrusive_HtmlEncodes_ModelStateAttemptedValue(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.ModelState.AddModelError(key: \"name\", errorMessage: null);\n            var valueProvider = new ValueProviderResult(rawValue: null, attemptedValue: text, culture: null);\n            viewData.ModelState.SetModelValue(key: \"name\", value: valueProvider);\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript(enabled: false);\n            string name = null;\n\n            // Act\n            var result = helper.ValidationMessageFor(m => name).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<span class=\\\"field-validation-error\\\" id=\\\"name_validationMessage\\\">The value &#39;\" +\n                    encodedText +\n                    \"&#39; is invalid.</span>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"HtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationMessageForNonUnobtrusive_HtmlEncodes_ModelStateError(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.ModelState.AddModelError(\"name\", text);\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript(enabled: false);\n            string name = null;\n\n            // Act\n            var result = helper.ValidationMessageFor(m => name).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<span class=\\\"field-validation-error\\\" id=\\\"name_validationMessage\\\">\" + encodedText + \"</span>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"IdEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationMessageForNonUnobtrusive_IdEncodes_Prefix(string text, bool htmlEncode, string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.TemplateInfo.HtmlFieldPrefix = text;\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript(enabled: false);\n            string name = null;\n\n            // Act\n            var result = helper.ValidationMessageFor(m => name).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<span class=\\\"field-validation-valid\\\" id=\\\"\" + encodedText + \"_name_validationMessage\\\"></span>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData_NoEncodedText\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationMessageForNonUnobtrusive_DoesNotEncode_Tag(string text, bool htmlEncode)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript(enabled: false);\n            string name = null;\n\n            // Act\n            var result = helper.ValidationMessageFor(m => name, validationMessage: null, tag: text).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<\" + text + \" class=\\\"field-validation-valid\\\" id=\\\"name_validationMessage\\\"></\" + text + \">\",\n                result);\n        }\n\n        // ValidationSummary\n\n        [Fact]\n        public void ValidationSummary()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationSummary();\n\n            // Assert\n            Assert.Equal(\n                \"<div class=\\\"validation-summary-errors\\\"><ul><li>foo error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>foo error 2</li>\" + Environment.NewLine\n              + \"<li>bar error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>bar error 2</li>\" + Environment.NewLine\n              + \"</ul></div>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationSummaryAddsIdIfClientValidationEnabled()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n            htmlHelper.ViewContext.FormContext = new FormContext();\n            htmlHelper.ViewContext.ClientValidationEnabled = true;\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationSummary();\n\n            // Assert\n            Assert.Equal(\n                \"<div class=\\\"validation-summary-errors\\\" id=\\\"validationSummary\\\"><ul><li>foo error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>foo error 2</li>\" + Environment.NewLine\n              + \"<li>bar error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>bar error 2</li>\" + Environment.NewLine\n              + \"</ul></div>\",\n                html.ToHtmlString());\n            Assert.Equal(\"validationSummary\", htmlHelper.ViewContext.FormContext.ValidationSummaryId);\n        }\n\n        [Fact]\n        public void ValidationSummaryDoesNotAddIdIfUnobtrusiveJavaScriptEnabled()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n            htmlHelper.ViewContext.FormContext = new FormContext();\n            htmlHelper.ViewContext.ClientValidationEnabled = true;\n            htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled = true;\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationSummary();\n\n            // Assert\n            Assert.Equal(\n                \"<div class=\\\"validation-summary-errors\\\" data-valmsg-summary=\\\"true\\\"><ul><li>foo error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>foo error 2</li>\" + Environment.NewLine\n              + \"<li>bar error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>bar error 2</li>\" + Environment.NewLine\n              + \"</ul></div>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationSummaryWithDictionary()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n            RouteValueDictionary htmlAttributes = new RouteValueDictionary();\n            htmlAttributes[\"class\"] = \"my-class\";\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationSummary(null /* message */, htmlAttributes);\n\n            // Assert\n            Assert.Equal(\n                \"<div class=\\\"validation-summary-errors my-class\\\"><ul><li>foo error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>foo error 2</li>\" + Environment.NewLine\n              + \"<li>bar error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>bar error 2</li>\" + Environment.NewLine\n              + \"</ul></div>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationSummaryWithDictionaryAndMessage()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n            RouteValueDictionary htmlAttributes = new RouteValueDictionary();\n            htmlAttributes[\"class\"] = \"my-class\";\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationSummary(\"This is my message.\", htmlAttributes);\n\n            // Assert\n            Assert.Equal(\n                \"<div class=\\\"validation-summary-errors my-class\\\"><span>This is my message.</span>\" + Environment.NewLine\n              + \"<ul><li>foo error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>foo error 2</li>\" + Environment.NewLine\n              + \"<li>bar error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>bar error 2</li>\" + Environment.NewLine\n              + \"</ul></div>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationSummaryWithNoErrors_ReturnsNullIfClientValidationDisabled()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationSummary();\n\n            // Assert\n            Assert.Null(html);\n        }\n\n        [Fact]\n        public void ValidationSummaryWithNoErrors_EmptyUlIfClientValidationEnabled()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n            htmlHelper.ViewContext.ClientValidationEnabled = true;\n            htmlHelper.ViewContext.FormContext = new FormContext();\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationSummary();\n\n            // Assert\n            Assert.Equal(\n                \"<div class=\\\"validation-summary-valid\\\" id=\\\"validationSummary\\\"><ul><li style=\\\"display:none\\\"></li>\" + Environment.NewLine\n              + \"</ul></div>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationSummaryWithObjectAttributes()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationSummary(null /* message */, new { baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(\n                \"<div baz=\\\"baz\\\" class=\\\"validation-summary-errors\\\"><ul><li>foo error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>foo error 2</li>\" + Environment.NewLine\n              + \"<li>bar error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>bar error 2</li>\" + Environment.NewLine\n              + \"</ul></div>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationSummaryWithObjectAttributesWithUnderscores()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationSummary(null /* message */, new { foo_baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(\n                \"<div class=\\\"validation-summary-errors\\\" foo-baz=\\\"baz\\\"><ul><li>foo error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>foo error 2</li>\" + Environment.NewLine\n              + \"<li>bar error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>bar error 2</li>\" + Environment.NewLine\n              + \"</ul></div>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationSummaryWithObjectAttributesAndMessage()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationSummary(\"This is my message.\", new { baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(\n                \"<div baz=\\\"baz\\\" class=\\\"validation-summary-errors\\\"><span>This is my message.</span>\" + Environment.NewLine\n              + \"<ul><li>foo error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>foo error 2</li>\" + Environment.NewLine\n              + \"<li>bar error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>bar error 2</li>\" + Environment.NewLine\n              + \"</ul></div>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationSummaryWithNoModelErrors()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationSummary(true /* excludePropertyErrors */, \"This is my message.\");\n\n            // Assert\n            Assert.Equal(\n                \"<div class=\\\"validation-summary-errors\\\"><span>This is my message.</span>\" + Environment.NewLine\n              + \"<ul><li style=\\\"display:none\\\"></li>\" + Environment.NewLine\n              + \"</ul></div>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationSummaryWithOnlyModelErrors()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelAndPropertyErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationSummary(true /* excludePropertyErrors */, \"This is my message.\");\n\n            // Assert\n            Assert.Equal(\n                \"<div class=\\\"validation-summary-errors\\\"><span>This is my message.</span>\" + Environment.NewLine\n              + \"<ul><li>Something is wrong.</li>\" + Environment.NewLine\n              + \"<li>Something else is also wrong.</li>\" + Environment.NewLine\n              + \"</ul></div>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationSummaryWithOnlyModelErrorsAndPrefix()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors(\"MyPrefix\"));\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationSummary(true /* excludePropertyErrors */, \"This is my message.\");\n\n            // Assert\n            Assert.Equal(\n                \"<div class=\\\"validation-summary-errors\\\"><span>This is my message.</span>\" + Environment.NewLine\n              + \"<ul><li style=\\\"display:none\\\"></li>\" + Environment.NewLine\n              + \"</ul></div>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationSummaryWithOverriddenHeadingTag_UsesGivenTag()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n            htmlHelper.SetValidationSummaryMessageElement(\"h4\");\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationSummary(true /* excludePropertyErrors */, \"This is my message.\");\n\n            // Assert\n            Assert.Equal(\n                \"<div class=\\\"validation-summary-errors\\\"><h4>This is my message.</h4>\" + Environment.NewLine\n              + \"<ul><li style=\\\"display:none\\\"></li>\" + Environment.NewLine\n              + \"</ul></div>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationSummaryWithCustomHeadingTag()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationSummary(true /* excludePropertyErrors */, \"This is my message.\", \"h2\");\n\n            // Assert\n            Assert.Equal(\n                \"<div class=\\\"validation-summary-errors\\\"><h2>This is my message.</h2>\" + Environment.NewLine\n              + \"<ul><li style=\\\"display:none\\\"></li>\" + Environment.NewLine\n              + \"</ul></div>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationSummaryWithDictionaryAndMessageWithCustomHeadingTag()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n            RouteValueDictionary htmlAttributes = new RouteValueDictionary();\n            htmlAttributes[\"class\"] = \"my-class\";\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationSummary(\"This is my message.\", htmlAttributes, \"h2\");\n\n            // Assert\n            Assert.Equal(\n                \"<div class=\\\"validation-summary-errors my-class\\\"><h2>This is my message.</h2>\" + Environment.NewLine\n              + \"<ul><li>foo error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>foo error 2</li>\" + Environment.NewLine\n              + \"<li>bar error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>bar error 2</li>\" + Environment.NewLine\n              + \"</ul></div>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationSummaryWithObjectAttributesAndMessageWithCustomHeadingTag()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationSummary(\"This is my message.\", new { baz = \"baz\" }, \"h2\");\n\n            // Assert\n            Assert.Equal(\n                \"<div baz=\\\"baz\\\" class=\\\"validation-summary-errors\\\"><h2>This is my message.</h2>\" + Environment.NewLine\n              + \"<ul><li>foo error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>foo error 2</li>\" + Environment.NewLine\n              + \"<li>bar error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>bar error 2</li>\" + Environment.NewLine\n              + \"</ul></div>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageWithPrefix()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelErrors(\"MyPrefix\"));\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationMessage(\"foo\");\n\n            // Assert\n            Assert.Equal(\"<span class=\\\"field-validation-error\\\">foo error &lt;1&gt;</span>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationErrorOrdering()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(GetViewDataWithModelWithDisplayOrderErrors());\n\n            // Act\n            MvcHtmlString html = htmlHelper.ValidationSummary();\n\n            // Assert\n            Assert.Equal(\n                \"<div class=\\\"validation-summary-errors\\\"><ul><li>Error 1</li>\" + Environment.NewLine\n              + \"<li>Error 2</li>\" + Environment.NewLine\n              + \"<li>Error 3</li>\" + Environment.NewLine\n              + \"<li>Error 4</li>\" + Environment.NewLine\n              + \"</ul></div>\",\n                html.ToHtmlString());\n\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationSummary_AttributeEncodes_AddedHtmlAttributes(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript(enabled: false);\n\n            // Act\n            var result = helper.ValidationSummary(\n                    excludePropertyErrors: true,\n                    message: null,\n                    htmlAttributes: new { attribute = text, })\n                .ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<div attribute=\\\"\" +\n                    encodedText +\n                    \"\\\" class=\\\"validation-summary-valid\\\" id=\\\"validationSummary\\\"><ul><li style=\\\"display:none\\\"></li>\" +\n                    Environment.NewLine +\n                    \"</ul></div>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"HtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationSummary_HtmlEncodes_Message(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript(enabled: false);\n\n            // Act\n            var result = helper.ValidationSummary(message: text).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<div class=\\\"validation-summary-valid\\\" id=\\\"validationSummary\\\"><span>\" +\n                    encodedText +\n                    \"</span>\" +\n                    Environment.NewLine +\n                    \"<ul><li style=\\\"display:none\\\"></li>\" +\n                    Environment.NewLine +\n                    \"</ul></div>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"HtmlEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationSummary_HtmlEncodes_ModelStateError(\n            string text,\n            bool htmlEncode,\n            string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            viewData.ModelState.AddModelError(\"\", text);\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript(enabled: false);\n\n            // Act\n            var result = helper.ValidationSummary().ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<div class=\\\"validation-summary-errors\\\" id=\\\"validationSummary\\\"><ul><li>\" +\n                    encodedText +\n                    \"</li>\" +\n                    Environment.NewLine +\n                    \"</ul></div>\",\n                result);\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData_NoEncodedText\", PropertyType = typeof(EncodedDataSets))]\n        public void ValidationSummary_DoesNotEncode_Tag(string text, bool htmlEncode)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(model: null);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n            helper.EnableClientValidation();\n            helper.EnableUnobtrusiveJavaScript(enabled: false);\n\n            // Act\n            var result = helper.ValidationSummary(message: \"message\", headingTag: text).ToHtmlString();\n\n            // Assert\n            Assert.Equal(\n                \"<div class=\\\"validation-summary-valid\\\" id=\\\"validationSummary\\\"><\" +\n                    text +\n                    \">message</\" +\n                    text +\n                    \">\" +\n                    Environment.NewLine +\n                    \"<ul><li style=\\\"display:none\\\"></li>\" +\n                    Environment.NewLine +\n                    \"</ul></div>\",\n                result);\n        }\n\n        private class ValidationModel\n        {\n            public string foo { get; set; }\n            public string bar { get; set; }\n            public string baz { get; set; }\n            public string quux { get; set; }\n        }\n\n        public class ModelWithOrdering\n        {\n            [Required]\n            [Display(Order = 2)]\n            public int Second { get; set; }\n\n            [Required]\n            [Display(Order = 1)]\n            public string First { get; set; }\n\n            [Required]\n            [Display(Order = 4)]\n            public string Fourth { get; set; }\n\n            [Required]\n            [Display(Order = 3)]\n            public string Third { get; set; }\n        }\n\n        private static ViewDataDictionary<ValidationModel> GetViewDataWithNullModelState()\n        {\n            ViewDataDictionary<ValidationModel> viewData = new ViewDataDictionary<ValidationModel>();\n            viewData.ModelState[\"foo\"] = null;\n            return viewData;\n        }\n\n        private static ViewDataDictionary<ValidationModel> GetViewDataWithModelErrors()\n        {\n            ViewDataDictionary<ValidationModel> viewData = new ViewDataDictionary<ValidationModel>();\n            ModelState modelStateFoo = new ModelState();\n            ModelState modelStateBar = new ModelState();\n            ModelState modelStateBaz = new ModelState();\n\n            modelStateFoo.Errors.Add(new ModelError(new InvalidOperationException(\"foo error from exception\")));\n            modelStateFoo.Errors.Add(new ModelError(\"foo error <1>\"));\n            modelStateFoo.Errors.Add(new ModelError(\"foo error 2\"));\n            modelStateBar.Errors.Add(new ModelError(\"bar error <1>\"));\n            modelStateBar.Errors.Add(new ModelError(\"bar error 2\"));\n\n            viewData.ModelState[\"foo\"] = modelStateFoo;\n            viewData.ModelState[\"bar\"] = modelStateBar;\n            viewData.ModelState[\"baz\"] = modelStateBaz;\n\n            viewData.ModelState.SetModelValue(\"quux\", new ValueProviderResult(null, \"quuxValue\", null));\n            viewData.ModelState.AddModelError(\"quux\", new InvalidOperationException(\"Some error text.\"));\n            return viewData;\n        }\n\n        private static ViewDataDictionary<ValidationModel> GetViewDataWithModelAndPropertyErrors()\n        {\n            ViewDataDictionary<ValidationModel> viewData = new ViewDataDictionary<ValidationModel>();\n            ModelState modelStateFoo = new ModelState();\n            ModelState modelStateBar = new ModelState();\n            ModelState modelStateBaz = new ModelState();\n            modelStateFoo.Errors.Add(new ModelError(\"foo error <1>\"));\n            modelStateFoo.Errors.Add(new ModelError(\"foo error 2\"));\n            modelStateBar.Errors.Add(new ModelError(\"bar error <1>\"));\n            modelStateBar.Errors.Add(new ModelError(\"bar error 2\"));\n            viewData.ModelState[\"foo\"] = modelStateFoo;\n            viewData.ModelState[\"bar\"] = modelStateBar;\n            viewData.ModelState[\"baz\"] = modelStateBaz;\n            viewData.ModelState.SetModelValue(\"quux\", new ValueProviderResult(null, \"quuxValue\", null));\n            viewData.ModelState.AddModelError(\"quux\", new InvalidOperationException(\"Some error text.\"));\n            viewData.ModelState.AddModelError(String.Empty, \"Something is wrong.\");\n            viewData.ModelState.AddModelError(String.Empty, \"Something else is also wrong.\");\n            return viewData;\n        }\n\n        private static ViewDataDictionary<ValidationModel> GetViewDataWithModelErrors(string prefix)\n        {\n            ViewDataDictionary<ValidationModel> viewData = new ViewDataDictionary<ValidationModel>();\n            viewData.TemplateInfo.HtmlFieldPrefix = prefix;\n            ModelState modelStateFoo = new ModelState();\n            ModelState modelStateBar = new ModelState();\n            ModelState modelStateBaz = new ModelState();\n            modelStateFoo.Errors.Add(new ModelError(\"foo error <1>\"));\n            modelStateFoo.Errors.Add(new ModelError(\"foo error 2\"));\n            modelStateBar.Errors.Add(new ModelError(\"bar error <1>\"));\n            modelStateBar.Errors.Add(new ModelError(\"bar error 2\"));\n            viewData.ModelState[prefix + \".foo\"] = modelStateFoo;\n            viewData.ModelState[prefix + \".bar\"] = modelStateBar;\n            viewData.ModelState[prefix + \".baz\"] = modelStateBaz;\n            viewData.ModelState.SetModelValue(prefix + \".quux\", new ValueProviderResult(null, \"quuxValue\", null));\n            viewData.ModelState.AddModelError(prefix + \".quux\", new InvalidOperationException(\"Some error text.\"));\n            return viewData;\n        }\n\n        private static ViewDataDictionary<ModelWithOrdering> GetViewDataWithModelWithDisplayOrderErrors()\n        {\n            ViewDataDictionary<ModelWithOrdering> viewData = new ViewDataDictionary<ModelWithOrdering>();\n\n            var model = new ModelWithOrdering();\n\n            // Error names for each property on ModelWithOrdering.\n            viewData.ModelState.AddModelError(\"First\", \"Error 1\");\n            viewData.ModelState.AddModelError(\"Second\", \"Error 2\");\n            viewData.ModelState.AddModelError(\"Third\", \"Error 3\");\n            viewData.ModelState.AddModelError(\"Fourth\", \"Error 4\");\n\n            return viewData;\n        }\n\n        public void Dispose()\n        {\n            // Reset ScopeStorage (written via e.g. ViewContext.ClientValidationEnabled) between tests to avoid unexpected interactions.\n            ScopeStorage.CurrentProvider = new StaticScopeStorageProvider();\n            ScopeStorage.GlobalScope.Clear();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Html/Test/ValueExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc.Test;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace System.Web.Mvc.Html.Test\n{\n    public class ValueExtensionsTest\n    {\n        // Value\n\n        [Fact]\n        public void ValueWithNullNameThrows()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetValueViewData());\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => helper.Value(name: null),\n                \"name\"\n                );\n        }\n\n        [Fact]\n        public void ValueGetsValueFromViewData()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetValueViewData());\n\n            // Act\n            MvcHtmlString html = helper.Value(\"foo\");\n\n            // Assert\n            Assert.Equal(\"ViewDataFoo\", html.ToHtmlString());\n        }\n\n        // ValueFor\n\n        [Fact]\n        public void ValueForWithNullExpressionThrows()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetValueViewData());\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => helper.ValueFor<FooBarModel, object>(expression: null),\n                \"expression\"\n                );\n        }\n\n        [Fact]\n        public void ValueForGetsExpressionValueFromViewDataModel()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetValueViewData());\n\n            // Act\n            MvcHtmlString html = helper.ValueFor(m => m.foo);\n\n            // Assert\n            Assert.Equal(\"ViewItemFoo\", html.ToHtmlString());\n        }\n\n        // All Value Helpers including ValueForModel\n\n        [Fact]\n        public void ValueHelpersWithErrorsGetValueFromModelState()\n        {\n            // Arrange\n            ViewDataDictionary<FooBarModel> viewDataWithErrors = new ViewDataDictionary<FooBarModel> { { \"foo\", \"ViewDataFoo\" } };\n            viewDataWithErrors.Model = new FooBarModel() { foo = \"ViewItemFoo\", bar = \"ViewItemBar\" };\n            viewDataWithErrors.TemplateInfo.HtmlFieldPrefix = \"FieldPrefix\";\n\n            ModelState modelStateFoo = new ModelState();\n            modelStateFoo.Value = HtmlHelperTest.GetValueProviderResult(new string[] { \"AttemptedValueFoo\" }, \"AttemptedValueFoo\");\n            viewDataWithErrors.ModelState[\"FieldPrefix.foo\"] = modelStateFoo;\n\n            ModelState modelStateFooBar = new ModelState();\n            modelStateFooBar.Value = HtmlHelperTest.GetValueProviderResult(new string[] { \"AttemptedValueFooBar\" }, \"AttemptedValueFooBar\");\n            viewDataWithErrors.ModelState[\"FieldPrefix\"] = modelStateFooBar;\n\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(viewDataWithErrors);\n\n            // Act & Assert\n            Assert.Equal(\"AttemptedValueFoo\", helper.Value(\"foo\").ToHtmlString());\n            Assert.Equal(\"AttemptedValueFoo\", helper.ValueFor(m => m.foo).ToHtmlString());\n            Assert.Equal(\"AttemptedValueFooBar\", helper.ValueForModel().ToHtmlString());\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void ValueHelpersWithEmptyNameConvertModelValueUsingCurrentCulture()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetValueViewData());\n            string expectedModelValue = \"{ foo = ViewItemFoo, bar = 01/01/1900 00:00:00 }\";\n\n            // Act & Assert\n            Assert.Equal(expectedModelValue, helper.Value(name: String.Empty).ToHtmlString());\n            Assert.Equal(expectedModelValue, helper.ValueFor(m => m).ToHtmlString());\n            Assert.Equal(expectedModelValue, helper.ValueForModel().ToHtmlString());\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void ValueHelpersFormatValue()\n        {\n            // Arrange\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(GetValueViewData());\n            string expectedModelValue = \"-{ foo = ViewItemFoo, bar = 01/01/1900 00:00:00 }-\";\n            string expectedBarValue = \"-01/01/1900 00:00:00-\";\n\n            // Act & Assert\n            Assert.Equal(expectedModelValue, helper.ValueForModel(\"-{0}-\").ToHtmlString());\n            Assert.Equal(expectedBarValue, helper.Value(\"bar\", \"-{0}-\").ToHtmlString());\n            Assert.Equal(expectedBarValue, helper.ValueFor(m => m.bar, \"-{0}-\").ToHtmlString());\n        }\n\n        [Fact]\n        public void ValueHelpersEncodeValue()\n        {\n            // Arrange\n            ViewDataDictionary<FooBarModel> viewData = new ViewDataDictionary<FooBarModel> { { \"foo\", @\"ViewDataFoo <\"\">\" } };\n            viewData.Model = new FooBarModel { foo = @\"ViewItemFoo <\"\">\" };\n\n            ModelState modelStateFoo = new ModelState();\n            modelStateFoo.Value = HtmlHelperTest.GetValueProviderResult(new string[] { @\"AttemptedValueBar <\"\">\" }, @\"AttemptedValueBar <\"\">\");\n            viewData.ModelState[\"bar\"] = modelStateFoo;\n\n            HtmlHelper<FooBarModel> helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act & Assert\n            Assert.Equal(\"&lt;{ foo = ViewItemFoo &lt;&quot;>, bar = (null) }\", helper.ValueForModel(\"<{0}\").ToHtmlString());\n            Assert.Equal(\"&lt;ViewDataFoo &lt;&quot;>\", helper.Value(\"foo\", \"<{0}\").ToHtmlString());\n            Assert.Equal(\"&lt;ViewItemFoo &lt;&quot;>\", helper.ValueFor(m => m.foo, \"<{0}\").ToHtmlString());\n            Assert.Equal(\"AttemptedValueBar &lt;&quot;>\", helper.ValueFor(m => m.bar).ToHtmlString());\n        }\n\n        [Theory]\n        [PropertyData(\"AttributeEncodedData\", PropertyType = typeof(EncodedDataSets))]\n        public void ValueHelpers_AttributeEncode_Value(string text, bool htmlEncode, string encodedText)\n        {\n            // Arrange\n            var viewData = new ViewDataDictionary<string>(text);\n            viewData.ModelMetadata.HtmlEncode = htmlEncode;\n            var helper = MvcHelper.GetHtmlHelper(viewData);\n\n            // Act\n            var valueResult = helper.Value(\"\").ToHtmlString();\n            var valueForResult = helper.ValueFor(m => m).ToHtmlString();\n            var valueForModelResult = helper.ValueForModel().ToHtmlString();\n\n            // Assert\n            Assert.Equal(encodedText, valueResult);\n            Assert.Equal(encodedText, valueForResult);\n            Assert.Equal(encodedText, valueForModelResult);\n        }\n\n        private sealed class FooBarModel\n        {\n            public string foo { get; set; }\n            public object bar { get; set; }\n\n            public override string ToString()\n            {\n                return String.Format(\"{{ foo = {0}, bar = {1} }}\", foo ?? \"(null)\", bar ?? \"(null)\");\n            }\n        }\n\n        private static ViewDataDictionary<FooBarModel> GetValueViewData()\n        {\n            ViewDataDictionary<FooBarModel> viewData = new ViewDataDictionary<FooBarModel> { { \"foo\", \"ViewDataFoo\" } };\n            viewData.Model = new FooBarModel { foo = \"ViewItemFoo\", bar = new DateTime(1900, 1, 1, 0, 0, 0) };\n\n            return viewData;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Properties/AssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\n\n[assembly: CLSCompliant(false)]"
  },
  {
    "path": "test/System.Web.Mvc.Test/Properties/Resources.Designer.cs",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:4.0.30319.34003\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace System.Web.Properties {\n    using System;\n    \n    \n    /// <summary>\n    ///   A strongly-typed resource class, for looking up localized strings, etc.\n    /// </summary>\n    // This class was auto-generated by the StronglyTypedResourceBuilder\n    // class via a tool like ResGen or Visual Studio.\n    // To add or remove a member, edit your .ResX file then rerun ResGen\n    // with the /str option, or rebuild your VS project.\n    [global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"System.Resources.Tools.StronglyTypedResourceBuilder\", \"4.0.0.0\")]\n    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]\n    internal class Resources {\n        \n        private static global::System.Resources.ResourceManager resourceMan;\n        \n        private static global::System.Globalization.CultureInfo resourceCulture;\n        \n        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(\"Microsoft.Performance\", \"CA1811:AvoidUncalledPrivateCode\")]\n        internal Resources() {\n        }\n        \n        /// <summary>\n        ///   Returns the cached ResourceManager instance used by this class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Resources.ResourceManager ResourceManager {\n            get {\n                if (object.ReferenceEquals(resourceMan, null)) {\n                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager(\"System.Web.Properties.Resources\", typeof(Resources).Assembly);\n                    resourceMan = temp;\n                }\n                return resourceMan;\n            }\n        }\n        \n        /// <summary>\n        ///   Overrides the current thread's CurrentUICulture property for all\n        ///   resource lookups using this strongly typed resource class.\n        /// </summary>\n        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]\n        internal static global::System.Globalization.CultureInfo Culture {\n            get {\n                return resourceCulture;\n            }\n            set {\n                resourceCulture = value;\n            }\n        }\n        \n        /// <summary>\n        ///   Looks up a localized string similar to Hello &apos;{0}&apos;, goodbye &apos;{1}&apos;..\n        /// </summary>\n        internal static string CompareAttributeTestResource {\n            get {\n                return ResourceManager.GetString(\"CompareAttributeTestResource\", resourceCulture);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Properties/Resources.resx",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <!-- \n    Microsoft ResX Schema \n    \n    Version 2.0\n    \n    The primary goals of this format is to allow a simple XML format \n    that is mostly human readable. The generation and parsing of the \n    various data types are done through the TypeConverter classes \n    associated with the data types.\n    \n    Example:\n    \n    ... ado.net/XML headers & schema ...\n    <resheader name=\"resmimetype\">text/microsoft-resx</resheader>\n    <resheader name=\"version\">2.0</resheader>\n    <resheader name=\"reader\">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>\n    <resheader name=\"writer\">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>\n    <data name=\"Name1\"><value>this is my long string</value><comment>this is a comment</comment></data>\n    <data name=\"Color1\" type=\"System.Drawing.Color, System.Drawing\">Blue</data>\n    <data name=\"Bitmap1\" mimetype=\"application/x-microsoft.net.object.binary.base64\">\n        <value>[base64 mime encoded serialized .NET Framework object]</value>\n    </data>\n    <data name=\"Icon1\" type=\"System.Drawing.Icon, System.Drawing\" mimetype=\"application/x-microsoft.net.object.bytearray.base64\">\n        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>\n        <comment>This is a comment</comment>\n    </data>\n                \n    There are any number of \"resheader\" rows that contain simple \n    name/value pairs.\n    \n    Each data row contains a name, and value. The row also contains a \n    type or mimetype. Type corresponds to a .NET class that support \n    text/value conversion through the TypeConverter architecture. \n    Classes that don't support this are serialized and stored with the \n    mimetype set.\n    \n    The mimetype is used for serialized objects, and tells the \n    ResXResourceReader how to depersist the object. This is currently not \n    extensible. For a given mimetype the value must be set accordingly:\n    \n    Note - application/x-microsoft.net.object.binary.base64 is the format \n    that the ResXResourceWriter will generate, however the reader can \n    read any of the formats listed below.\n    \n    mimetype: application/x-microsoft.net.object.binary.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter\n            : and then encoded with base64 encoding.\n    \n    mimetype: application/x-microsoft.net.object.soap.base64\n    value   : The object must be serialized with \n            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter\n            : and then encoded with base64 encoding.\n\n    mimetype: application/x-microsoft.net.object.bytearray.base64\n    value   : The object must be serialized into a byte array \n            : using a System.ComponentModel.TypeConverter\n            : and then encoded with base64 encoding.\n    -->\n  <xsd:schema id=\"root\" xmlns=\"\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\n    <xsd:import namespace=\"http://www.w3.org/XML/1998/namespace\" />\n    <xsd:element name=\"root\" msdata:IsDataSet=\"true\">\n      <xsd:complexType>\n        <xsd:choice maxOccurs=\"unbounded\">\n          <xsd:element name=\"metadata\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" use=\"required\" type=\"xsd:string\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"assembly\">\n            <xsd:complexType>\n              <xsd:attribute name=\"alias\" type=\"xsd:string\" />\n              <xsd:attribute name=\"name\" type=\"xsd:string\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"data\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n                <xsd:element name=\"comment\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"2\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" msdata:Ordinal=\"1\" />\n              <xsd:attribute name=\"type\" type=\"xsd:string\" msdata:Ordinal=\"3\" />\n              <xsd:attribute name=\"mimetype\" type=\"xsd:string\" msdata:Ordinal=\"4\" />\n              <xsd:attribute ref=\"xml:space\" />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name=\"resheader\">\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name=\"value\" type=\"xsd:string\" minOccurs=\"0\" msdata:Ordinal=\"1\" />\n              </xsd:sequence>\n              <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\" />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n  <resheader name=\"resmimetype\">\n    <value>text/microsoft-resx</value>\n  </resheader>\n  <resheader name=\"version\">\n    <value>2.0</value>\n  </resheader>\n  <resheader name=\"reader\">\n    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <resheader name=\"writer\">\n    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>\n  </resheader>\n  <data name=\"CompareAttributeTestResource\" xml:space=\"preserve\">\n    <value>Hello '{0}', goodbye '{1}'.</value>\n  </data>\n</root>"
  },
  {
    "path": "test/System.Web.Mvc.Test/Razor/Test/MvcCSharpRazorCodeGeneratorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.Collections.Generic;\nusing System.Web.Razor;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Razor.Test\n{\n    public class MvcCSharpRazorCodeGeneratorTest\n    {\n        [Fact]\n        public void Constructor()\n        {\n            // Arrange\n            Mock<RazorEngineHost> mockHost = new Mock<RazorEngineHost>();\n\n            // Act\n            var generator = new MvcCSharpRazorCodeGenerator(\"FooClass\", \"Root.Namespace\", \"SomeSourceFile.cshtml\", mockHost.Object);\n\n            // Assert\n            Assert.Equal(\"FooClass\", generator.ClassName);\n            Assert.Equal(\"Root.Namespace\", generator.RootNamespaceName);\n            Assert.Equal(\"SomeSourceFile.cshtml\", generator.SourceFileName);\n            Assert.Same(mockHost.Object, generator.Host);\n        }\n\n        [Fact]\n        public void Constructor_DoesNotSetBaseTypeForNonMvcHost()\n        {\n            // Arrange\n            Mock<RazorEngineHost> mockHost = new Mock<RazorEngineHost>();\n            mockHost.SetupGet(h => h.NamespaceImports).Returns(new HashSet<string>());\n\n            // Act\n            var generator = new MvcCSharpRazorCodeGenerator(\"FooClass\", \"Root.Namespace\", \"SomeSourceFile.cshtml\", mockHost.Object);\n\n            // Assert\n            Assert.Empty(generator.Context.GeneratedClass.BaseTypes);\n        }\n\n        [Fact]\n        public void Constructor_DoesNotSetBaseTypeForSpecialPage()\n        {\n            // Arrange\n            Mock<MvcWebPageRazorHost> mockHost = new Mock<MvcWebPageRazorHost>(\"_viewStart.cshtml\", \"_viewStart.cshtml\");\n            mockHost.SetupGet(h => h.NamespaceImports).Returns(new HashSet<string>());\n\n            // Act\n            var generator = new MvcCSharpRazorCodeGenerator(\"FooClass\", \"Root.Namespace\", \"_viewStart.cshtml\", mockHost.Object);\n\n            // Assert\n            Assert.Empty(generator.Context.GeneratedClass.BaseTypes);\n        }\n\n        [Fact]\n        public void Constructor_SetsBaseTypeForRegularPage()\n        {\n            // Arrange\n            Mock<MvcWebPageRazorHost> mockHost = new Mock<MvcWebPageRazorHost>(\"SomeSourceFile.cshtml\", \"SomeSourceFile.cshtml\") { CallBase = true };\n            mockHost.SetupGet(h => h.NamespaceImports).Returns(new HashSet<string>());\n\n            // Act\n            var generator = new MvcCSharpRazorCodeGenerator(\"FooClass\", \"Root.Namespace\", \"SomeSourceFile.cshtml\", mockHost.Object);\n\n            // Assert\n            var baseType = Assert.IsType<CodeTypeReference>(Assert.Single(generator.Context.GeneratedClass.BaseTypes));\n            Assert.Equal(\"System.Web.Mvc.WebViewPage<dynamic>\", baseType.BaseType);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Razor/Test/MvcCSharpRazorCodeParserTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Razor;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Razor.Test\n{\n    public class MvcCSharpRazorCodeParserTest\n    {\n        [Fact]\n        public void Constructor_AddsModelKeyword()\n        {\n            var parser = new TestMvcCSharpRazorCodeParser();\n\n            Assert.True(parser.HasDirective(\"model\"));\n        }\n\n        [Fact]\n        public void ParseModelKeyword_HandlesSingleInstance()\n        {\n            // Arrange + Act\n            var document = \"@model    Foo\";\n            var spans = ParseDocument(document);\n\n            // Assert\n            var factory = SpanFactory.CreateCsHtml();\n            var expectedSpans = new Span[]\n            {\n                factory.EmptyHtml(),\n                factory.CodeTransition(SyntaxConstants.TransitionString)\n                    .Accepts(AcceptedCharacters.None),\n                factory.MetaCode(\"model \")\n                    .Accepts(AcceptedCharacters.None),\n                factory.Code(\"   Foo\")\n                    .As(new SetModelTypeCodeGenerator(\"Foo\", \"{0}<{1}>\"))\n            };\n            Assert.Equal(expectedSpans, spans.ToArray());\n        }\n\n        [Fact]\n        public void ParseModelKeyword_HandlesNullableTypes()\n        {\n            // Arrange + Act\n            var document = \"@model Foo?\\r\\nBar\";\n            var spans = ParseDocument(document);\n\n            // Assert\n            var factory = SpanFactory.CreateCsHtml();\n            var expectedSpans = new Span[]\n            {\n                factory.EmptyHtml(),\n                factory.CodeTransition(SyntaxConstants.TransitionString)\n                    .Accepts(AcceptedCharacters.None),\n                factory.MetaCode(\"model \")\n                    .Accepts(AcceptedCharacters.None),\n                factory.Code(\"Foo?\\r\\n\")\n                    .As(new SetModelTypeCodeGenerator(\"Foo?\", \"{0}<{1}>\")),\n                factory.Markup(\"Bar\")\n                    .With(new MarkupCodeGenerator())\n            };\n            Assert.Equal(expectedSpans, spans.ToArray());\n        }\n\n        [Fact]\n        public void ParseModelKeyword_HandlesArrays()\n        {\n            // Arrange + Act\n            var document = \"@model Foo[[]][]\\r\\nBar\";\n            var spans = ParseDocument(document);\n\n            // Assert\n            var factory = SpanFactory.CreateCsHtml();\n            var expectedSpans = new Span[]\n            {\n                factory.EmptyHtml(),\n                factory.CodeTransition(SyntaxConstants.TransitionString)\n                    .Accepts(AcceptedCharacters.None),\n                factory.MetaCode(\"model \")\n                    .Accepts(AcceptedCharacters.None),\n                factory.Code(\"Foo[[]][]\\r\\n\")\n                    .As(new SetModelTypeCodeGenerator(\"Foo[[]][]\", \"{0}<{1}>\")),\n                factory.Markup(\"Bar\")\n                    .With(new MarkupCodeGenerator())\n            };\n            Assert.Equal(expectedSpans, spans.ToArray());\n        }\n\n        [Fact]\n        public void ParseModelKeyword_HandlesVSTemplateSyntax()\n        {\n            // Arrange + Act\n            var document = \"@model $rootnamespace$.MyModel\";\n            var spans = ParseDocument(document);\n\n            // Assert\n            var factory = SpanFactory.CreateCsHtml();\n            var expectedSpans = new Span[]\n            {\n                factory.EmptyHtml(),\n                factory.CodeTransition(SyntaxConstants.TransitionString)\n                    .Accepts(AcceptedCharacters.None),\n                factory.MetaCode(\"model \")\n                    .Accepts(AcceptedCharacters.None),\n                factory.Code(\"$rootnamespace$.MyModel\")\n                    .As(new SetModelTypeCodeGenerator(\"$rootnamespace$.MyModel\", \"{0}<{1}>\"))\n            };\n            Assert.Equal(expectedSpans, spans.ToArray());\n        }\n\n        [Fact]\n        public void ParseModelKeyword_ErrorOnMissingModelType()\n        {\n            // Arrange + Act\n            List<RazorError> errors = new List<RazorError>();\n            var document = \"@model   \";\n            var spans = ParseDocument(document, errors);\n\n            // Assert\n            var factory = SpanFactory.CreateCsHtml();\n            var expectedSpans = new Span[]\n            {\n                factory.EmptyHtml(),\n                factory.CodeTransition(SyntaxConstants.TransitionString)\n                    .Accepts(AcceptedCharacters.None),\n                factory.MetaCode(\"model \")\n                    .Accepts(AcceptedCharacters.None),\n                factory.Code(\"  \")\n                    .As(new SetModelTypeCodeGenerator(String.Empty, \"{0}<{1}>\")),\n            };\n            var expectedErrors = new[]\n            {\n                new RazorError(\"The 'model' keyword must be followed by a type name on the same line.\", new SourceLocation(9, 0, 9), 1)\n            };\n            Assert.Equal(expectedSpans, spans.ToArray());\n            Assert.Equal(expectedErrors, errors.ToArray());\n        }\n\n        [Fact]\n        public void ParseModelKeyword_ErrorOnMultipleModelStatements()\n        {\n            // Arrange + Act\n            List<RazorError> errors = new List<RazorError>();\n            var document =\n                \"@model Foo\" + Environment.NewLine\n              + \"@model Bar\";\n            var spans = ParseDocument(document, errors);\n\n            // Assert\n            var factory = SpanFactory.CreateCsHtml();\n            var expectedSpans = new Span[]\n            {\n                factory.EmptyHtml(),\n                factory.CodeTransition(SyntaxConstants.TransitionString)\n                    .Accepts(AcceptedCharacters.None),\n                factory.MetaCode(\"model \")\n                    .Accepts(AcceptedCharacters.None),\n                factory.Code(\"Foo\\r\\n\")\n                    .As(new SetModelTypeCodeGenerator(\"Foo\", \"{0}<{1}>\")),\n                factory.CodeTransition(SyntaxConstants.TransitionString)\n                    .Accepts(AcceptedCharacters.None),\n                factory.MetaCode(\"model \")\n                    .Accepts(AcceptedCharacters.None),\n                factory.Code(\"Bar\")\n                    .As(new SetModelTypeCodeGenerator(\"Bar\", \"{0}<{1}>\"))\n            };\n\n            var expectedErrors = new[]\n            {\n                new RazorError(\"Only one 'model' statement is allowed in a file.\", new SourceLocation(18, 1, 6), 1)\n            };\n            expectedSpans.Zip(spans, (exp, span) => new { expected = exp, span = span }).ToList().ForEach(i => Assert.Equal(i.expected, i.span));\n            Assert.Equal(expectedSpans, spans.ToArray());\n            Assert.Equal(expectedErrors, errors.ToArray());\n        }\n\n        [Fact]\n        public void ParseModelKeyword_ErrorOnModelFollowedByInherits()\n        {\n            // Arrange + Act\n            List<RazorError> errors = new List<RazorError>();\n            var document =\n                \"@model Foo\" + Environment.NewLine\n              + \"@inherits Bar\";\n            var spans = ParseDocument(document, errors);\n\n            // Assert\n            var factory = SpanFactory.CreateCsHtml();\n            var expectedSpans = new Span[]\n            {\n                factory.EmptyHtml(),\n                factory.CodeTransition(SyntaxConstants.TransitionString)\n                    .Accepts(AcceptedCharacters.None),\n                factory.MetaCode(\"model \")\n                    .Accepts(AcceptedCharacters.None),\n                factory.Code(\"Foo\\r\\n\")\n                    .As(new SetModelTypeCodeGenerator(\"Foo\", \"{0}<{1}>\")),\n                factory.CodeTransition(SyntaxConstants.TransitionString)\n                    .Accepts(AcceptedCharacters.None),\n                factory.MetaCode(\"inherits \")\n                    .Accepts(AcceptedCharacters.None),\n                factory.Code(\"Bar\")\n                    .As(new SetBaseTypeCodeGenerator(\"Bar\"))\n            };\n\n            var expectedErrors = new[]\n            {\n                new RazorError(\"The 'inherits' keyword is not allowed when a 'model' keyword is used.\", new SourceLocation(21, 1, 9), 1)\n            };\n            expectedSpans.Zip(spans, (exp, span) => new { expected = exp, span = span }).ToList().ForEach(i => Assert.Equal(i.expected, i.span));\n            Assert.Equal(expectedSpans, spans.ToArray());\n            Assert.Equal(expectedErrors, errors.ToArray());\n        }\n\n        [Fact]\n        public void ParseModelKeyword_ErrorOnInheritsFollowedByModel()\n        {\n            // Arrange + Act\n            List<RazorError> errors = new List<RazorError>();\n            var document =\n                \"@inherits Bar\" + Environment.NewLine\n              + \"@model Foo\";\n            var spans = ParseDocument(document, errors);\n\n            // Assert\n            var factory = SpanFactory.CreateCsHtml();\n            var expectedSpans = new Span[]\n            {\n                factory.EmptyHtml(),\n                factory.CodeTransition(SyntaxConstants.TransitionString)\n                    .Accepts(AcceptedCharacters.None),\n                factory.MetaCode(\"inherits \")\n                    .Accepts(AcceptedCharacters.None),\n                factory.Code(\"Bar\" + Environment.NewLine)\n                    .As(new SetBaseTypeCodeGenerator(\"Bar\")),\n                factory.CodeTransition(SyntaxConstants.TransitionString)\n                    .Accepts(AcceptedCharacters.None),\n                factory.MetaCode(\"model \")\n                    .Accepts(AcceptedCharacters.None),\n                factory.Code(\"Foo\")\n                    .As(new SetModelTypeCodeGenerator(\"Foo\", \"{0}<{1}>\"))\n            };\n\n            var expectedErrors = new[]\n            {\n                new RazorError(\"The 'inherits' keyword is not allowed when a 'model' keyword is used.\", new SourceLocation(9, 0, 9), 1)\n            };\n            expectedSpans.Zip(spans, (exp, span) => new { expected = exp, span = span }).ToList().ForEach(i => Assert.Equal(i.expected, i.span));\n            Assert.Equal(expectedSpans, spans.ToArray());\n            Assert.Equal(expectedErrors, errors.ToArray());\n        }\n\n        private static List<Span> ParseDocument(string documentContents, IList<RazorError> errors = null)\n        {\n            errors = errors ?? new List<RazorError>();\n            var markupParser = new HtmlMarkupParser();\n            var codeParser = new TestMvcCSharpRazorCodeParser();\n            var context = new ParserContext(new SeekableTextReader(documentContents), codeParser, markupParser, markupParser);\n            codeParser.Context = context;\n            markupParser.Context = context;\n            markupParser.ParseDocument();\n\n            ParserResults results = context.CompleteParse();\n            foreach (RazorError error in results.ParserErrors)\n            {\n                errors.Add(error);\n            }\n            return results.Document.Flatten().ToList();\n        }\n\n        private sealed class TestMvcCSharpRazorCodeParser : MvcCSharpRazorCodeParser\n        {\n            public bool HasDirective(string directive)\n            {\n                Action handler;\n                return TryGetDirectiveHandler(directive, out handler);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Razor/Test/MvcVBRazorCodeParserTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Razor;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Razor.Test\n{\n    public class MvcVBRazorCodeParserTest\n    {\n        [Fact]\n        public void Constructor_AddsModelKeyword()\n        {\n            var parser = new MvcVBRazorCodeParser();\n\n            Assert.True(parser.IsDirectiveDefined(MvcVBRazorCodeParser.ModelTypeKeyword));\n        }\n\n        [Fact]\n        public void ParseModelKeyword_HandlesSingleInstance()\n        {\n            // Arrange + Act\n            var document = \"@ModelType    Foo\";\n            var spans = ParseDocument(document);\n\n            // Assert\n            var factory = SpanFactory.CreateVbHtml();\n            var expectedSpans = new Span[]\n            {\n                factory.EmptyHtml(),\n                factory.CodeTransition(SyntaxConstants.TransitionString)\n                    .Accepts(AcceptedCharacters.None),\n                factory.MetaCode(\"ModelType    \")\n                    .Accepts(AcceptedCharacters.None),\n                factory.Code(\"Foo\")\n                    .As(new SetModelTypeCodeGenerator(\"Foo\", \"{0}(Of {1})\"))\n            };\n            Assert.Equal(expectedSpans, spans.ToArray());\n        }\n\n        [Fact]\n        public void ParseModelKeyword_HandlesNullableTypes()\n        {\n            // Arrange + Act\n            var document = \"@ModelType Foo?\\r\\nBar\";\n            var spans = ParseDocument(document);\n\n            // Assert\n            var factory = SpanFactory.CreateVbHtml();\n            var expectedSpans = new Span[]\n            {\n                factory.EmptyHtml(),\n                factory.CodeTransition(SyntaxConstants.TransitionString)\n                    .Accepts(AcceptedCharacters.None),\n                factory.MetaCode(\"ModelType \")\n                    .Accepts(AcceptedCharacters.None),\n                factory.Code(\"Foo?\\r\\n\")\n                    .As(new SetModelTypeCodeGenerator(\"Foo?\", \"{0}(Of {1})\")),\n                factory.Markup(\"Bar\")\n            };\n            Assert.Equal(expectedSpans, spans.ToArray());\n        }\n\n        [Fact]\n        public void ParseModelKeyword_HandlesArrays()\n        {\n            // Arrange + Act\n            var document = \"@ModelType Foo(())()\\r\\nBar\";\n            var spans = ParseDocument(document);\n\n            // Assert\n            var factory = SpanFactory.CreateVbHtml();\n            var expectedSpans = new Span[]\n            {\n                factory.EmptyHtml(),\n                factory.CodeTransition(SyntaxConstants.TransitionString)\n                    .Accepts(AcceptedCharacters.None),\n                factory.MetaCode(\"ModelType \")\n                    .Accepts(AcceptedCharacters.None),\n                factory.Code(\"Foo(())()\\r\\n\")\n                    .As(new SetModelTypeCodeGenerator(\"Foo(())()\", \"{0}(Of {1})\")),\n                factory.Markup(\"Bar\")\n            };\n            Assert.Equal(expectedSpans, spans.ToArray());\n        }\n\n        [Fact]\n        public void ParseModelKeyword_HandlesVSTemplateSyntax()\n        {\n            // Arrange + Act\n            var document = \"@ModelType $rootnamespace$.MyModel\";\n            var spans = ParseDocument(document);\n\n            // Assert\n            var factory = SpanFactory.CreateVbHtml();\n            var expectedSpans = new Span[]\n            {\n                factory.EmptyHtml(),\n                factory.CodeTransition(SyntaxConstants.TransitionString)\n                    .Accepts(AcceptedCharacters.None),\n                factory.MetaCode(\"ModelType \")\n                    .Accepts(AcceptedCharacters.None),\n                factory.Code(\"$rootnamespace$.MyModel\")\n                    .As(new SetModelTypeCodeGenerator(\"$rootnamespace$.MyModel\", \"{0}(Of {1})\"))\n            };\n            Assert.Equal(expectedSpans, spans.ToArray());\n        }\n\n        [Fact]\n        public void ParseModelKeyword_ErrorOnMissingModelType()\n        {\n            // Arrange + Act\n            List<RazorError> errors = new List<RazorError>();\n            var document = \"@ModelType   \";\n            var spans = ParseDocument(document, errors);\n\n            // Assert\n            var factory = SpanFactory.CreateVbHtml();\n            var expectedSpans = new Span[]\n            {\n                factory.EmptyHtml(),\n                factory.CodeTransition(SyntaxConstants.TransitionString)\n                    .Accepts(AcceptedCharacters.None),\n                factory.MetaCode(\"ModelType   \")\n                    .Accepts(AcceptedCharacters.None),\n                factory.EmptyVB()\n                    .As(new SetModelTypeCodeGenerator(String.Empty, \"{0}(Of {1})\"))\n                    .Accepts(AcceptedCharacters.Any)\n            };\n            var expectedErrors = new[]\n            {\n                new RazorError(\"The 'ModelType' keyword must be followed by a type name on the same line.\", new SourceLocation(10, 0, 10), 1)\n            };\n            Assert.Equal(expectedSpans, spans.ToArray());\n            Assert.Equal(expectedErrors, errors.ToArray());\n        }\n\n        [Fact]\n        public void ParseModelKeyword_DoesNotAcceptNewlineIfInDesignTimeMode()\n        {\n            // Arrange + Act\n            List<RazorError> errors = new List<RazorError>();\n            var document = \"@ModelType foo\\r\\n\";\n            var spans = ParseDocument(document, errors, designTimeMode: true);\n\n            // Assert\n            var factory = SpanFactory.CreateVbHtml();\n            var expectedSpans = new Span[]\n            {\n                factory.EmptyHtml(),\n                factory.CodeTransition(SyntaxConstants.TransitionString)\n                    .Accepts(AcceptedCharacters.None),\n                factory.MetaCode(\"ModelType \")\n                    .Accepts(AcceptedCharacters.None),\n                factory.Code(\"foo\")\n                    .As(new SetModelTypeCodeGenerator(\"foo\", \"{0}(Of {1})\"))\n                    .Accepts(AcceptedCharacters.Any),\n                factory.Markup(\"\\r\\n\")\n            };\n            Assert.Equal(expectedSpans, spans.ToArray());\n            Assert.Empty(errors);\n        }\n\n        [Fact]\n        public void ParseModelKeyword_ErrorOnMultipleModelStatements()\n        {\n            // Arrange + Act\n            List<RazorError> errors = new List<RazorError>();\n            var document =\n                \"@ModelType Foo\" + Environment.NewLine\n              + \"@ModelType Bar\";\n            var spans = ParseDocument(document, errors);\n\n            // Assert\n            var factory = SpanFactory.CreateVbHtml();\n            var expectedSpans = new Span[]\n            {\n                factory.EmptyHtml(),\n                factory.CodeTransition(SyntaxConstants.TransitionString)\n                    .Accepts(AcceptedCharacters.None),\n                factory.MetaCode(\"ModelType \")\n                    .Accepts(AcceptedCharacters.None),\n                factory.Code(\"Foo\\r\\n\")\n                    .As(new SetModelTypeCodeGenerator(\"Foo\", \"{0}(Of {1})\")),\n                factory.CodeTransition(SyntaxConstants.TransitionString)\n                    .Accepts(AcceptedCharacters.None),\n                factory.MetaCode(\"ModelType \")\n                    .Accepts(AcceptedCharacters.None),\n                factory.Code(\"Bar\")\n                    .As(new SetModelTypeCodeGenerator(\"Bar\", \"{0}(Of {1})\"))\n            };\n\n            var expectedErrors = new[]\n            {\n                new RazorError(\"Only one 'ModelType' statement is allowed in a file.\", new SourceLocation(26, 1, 10), 1)\n            };\n            expectedSpans.Zip(spans, (exp, span) => new { expected = exp, span = span }).ToList().ForEach(i => Assert.Equal(i.expected, i.span));\n            Assert.Equal(expectedSpans, spans.ToArray());\n            Assert.Equal(expectedErrors, errors.ToArray());\n        }\n\n        [Fact]\n        public void ParseModelKeyword_ErrorOnModelFollowedByInherits()\n        {\n            // Arrange + Act\n            List<RazorError> errors = new List<RazorError>();\n            var document =\n                \"@ModelType Foo\" + Environment.NewLine\n              + \"@Inherits Bar\";\n            var spans = ParseDocument(document, errors);\n\n            // Assert\n            var factory = SpanFactory.CreateVbHtml();\n            var expectedSpans = new Span[]\n            {\n                factory.EmptyHtml(),\n                factory.CodeTransition(SyntaxConstants.TransitionString)\n                    .Accepts(AcceptedCharacters.None),\n                factory.MetaCode(\"ModelType \")\n                    .Accepts(AcceptedCharacters.None),\n                factory.Code(\"Foo\\r\\n\")\n                    .As(new SetModelTypeCodeGenerator(\"Foo\", \"{0}(Of {1})\")),\n                factory.CodeTransition(SyntaxConstants.TransitionString)\n                    .Accepts(AcceptedCharacters.None),\n                factory.MetaCode(\"Inherits \")\n                    .Accepts(AcceptedCharacters.None),\n                factory.Code(\"Bar\")\n                    .As(new SetBaseTypeCodeGenerator(\"Bar\"))\n            };\n\n            var expectedErrors = new[]\n            {\n                new RazorError(\"The 'inherits' keyword is not allowed when a 'ModelType' keyword is used.\", new SourceLocation(25, 1, 9), 1)\n            };\n            expectedSpans.Zip(spans, (exp, span) => new { expected = exp, span = span }).ToList().ForEach(i => Assert.Equal(i.expected, i.span));\n            Assert.Equal(expectedSpans, spans.ToArray());\n            Assert.Equal(expectedErrors, errors.ToArray());\n        }\n\n        [Fact]\n        public void ParseModelKeyword_ErrorOnInheritsFollowedByModel()\n        {\n            // Arrange + Act\n            List<RazorError> errors = new List<RazorError>();\n            var document =\n                \"@Inherits Bar\" + Environment.NewLine\n              + \"@ModelType Foo\";\n            var spans = ParseDocument(document, errors);\n\n            // Assert\n            var factory = SpanFactory.CreateVbHtml();\n            var expectedSpans = new Span[]\n            {\n                factory.EmptyHtml(),\n                factory.CodeTransition(SyntaxConstants.TransitionString)\n                    .Accepts(AcceptedCharacters.None),\n                factory.MetaCode(\"Inherits \")\n                    .Accepts(AcceptedCharacters.None),\n                factory.Code(\"Bar\\r\\n\")\n                    .AsBaseType(\"Bar\"),\n                factory.CodeTransition(SyntaxConstants.TransitionString)\n                    .Accepts(AcceptedCharacters.None),\n                factory.MetaCode(\"ModelType \")\n                    .Accepts(AcceptedCharacters.None),\n                factory.Code(\"Foo\")\n                    .As(new SetModelTypeCodeGenerator(\"Foo\", \"{0}(Of {1})\"))\n            };\n\n            var expectedErrors = new[]\n            {\n                new RazorError(\"The 'inherits' keyword is not allowed when a 'ModelType' keyword is used.\", new SourceLocation(9, 0, 9), 1)\n            };\n            expectedSpans.Zip(spans, (exp, span) => new { expected = exp, span = span }).ToList().ForEach(i => Assert.Equal(i.expected, i.span));\n            Assert.Equal(expectedSpans, spans.ToArray());\n            Assert.Equal(expectedErrors, errors.ToArray());\n        }\n\n        private static List<Span> ParseDocument(string documentContents, List<RazorError> errors = null, bool designTimeMode = false)\n        {\n            errors = errors ?? new List<RazorError>();\n            var markupParser = new HtmlMarkupParser();\n            var codeParser = new MvcVBRazorCodeParser();\n            var context = new ParserContext(new SeekableTextReader(documentContents), codeParser, markupParser, markupParser);\n            context.DesignTimeMode = designTimeMode;\n            codeParser.Context = context;\n            markupParser.Context = context;\n            markupParser.ParseDocument();\n\n            ParserResults results = context.CompleteParse();\n            foreach (RazorError error in results.ParserErrors)\n            {\n                errors.Add(error);\n            }\n            return results.Document.Flatten().ToList();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Razor/Test/MvcWebPageRazorHostTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Razor.Test\n{\n    public class MvcWebPageRazorHostTest\n    {\n        [Fact]\n        public void Constructor()\n        {\n            MvcWebPageRazorHost host = new MvcWebPageRazorHost(\"foo.cshtml\", \"bar\");\n\n            Assert.Equal(\"foo.cshtml\", host.VirtualPath);\n            Assert.Equal(\"bar\", host.PhysicalPath);\n            Assert.Equal(typeof(WebViewPage).FullName, host.DefaultBaseClass);\n        }\n\n        [Fact]\n        public void ConstructorRemovesUnwantedNamespaceImports()\n        {\n            MvcWebPageRazorHost host = new MvcWebPageRazorHost(\"foo.cshtml\", \"bar\");\n\n            Assert.False(host.NamespaceImports.Contains(\"System.Web.WebPages.Html\"));\n\n            // Even though MVC no longer needs to remove the following two namespaces\n            // (because they are no longer imported by System.Web.WebPages), we want\n            // to make sure that they don't get introduced again by default.\n            Assert.False(host.NamespaceImports.Contains(\"WebMatrix.Data\"));\n            Assert.False(host.NamespaceImports.Contains(\"WebMatrix.WebData\"));\n        }\n\n#if VB_ENABLED\n        [Fact]\n        public void DecorateGodeGenerator_ReplacesVBCodeGeneratorWithMvcSpecificOne() {\n            // Arrange\n            MvcWebPageRazorHost host = new MvcWebPageRazorHost(\"foo.vbhtml\", \"bar\");\n            var generator = new VBRazorCodeGenerator(\"someClass\", \"root.name\", \"foo.vbhtml\", host);\n\n            // Act\n            var result = host.DecorateCodeGenerator(generator);\n\n            // Assert\n            Assert.IsType<MvcVBRazorCodeGenerator>(result);\n            Assert.Equal(\"someClass\", result.ClassName);\n            Assert.Equal(\"root.name\", result.RootNamespaceName);\n            Assert.Equal(\"foo.vbhtml\", result.SourceFileName);\n            Assert.Same(host, result.Host);\n        }\n#endif\n\n        [Fact]\n        public void DecorateGodeGenerator_ReplacesCSharpCodeGeneratorWithMvcSpecificOne()\n        {\n            // Arrange\n            MvcWebPageRazorHost host = new MvcWebPageRazorHost(\"foo.cshtml\", \"bar\");\n            var generator = new CSharpRazorCodeGenerator(\"someClass\", \"root.name\", \"foo.cshtml\", host);\n\n            // Act\n            var result = host.DecorateCodeGenerator(generator);\n\n            // Assert\n            Assert.IsType<MvcCSharpRazorCodeGenerator>(result);\n            Assert.Equal(\"someClass\", result.ClassName);\n            Assert.Equal(\"root.name\", result.RootNamespaceName);\n            Assert.Equal(\"foo.cshtml\", result.SourceFileName);\n            Assert.Same(host, result.Host);\n        }\n\n        [Fact]\n        public void DecorateCodeParser_ThrowsOnNull()\n        {\n            MvcWebPageRazorHost host = new MvcWebPageRazorHost(\"foo.cshtml\", \"bar\");\n            Assert.ThrowsArgumentNull(delegate() { host.DecorateCodeParser(null); }, \"incomingCodeParser\");\n        }\n\n        [Fact]\n        public void DecorateCodeParser_ReplacesCSharpCodeParserWithMvcSpecificOne()\n        {\n            // Arrange\n            MvcWebPageRazorHost host = new MvcWebPageRazorHost(\"foo.cshtml\", \"bar\");\n            var parser = new CSharpCodeParser();\n\n            // Act\n            var result = host.DecorateCodeParser(parser);\n\n            // Assert\n            Assert.IsType<MvcCSharpRazorCodeParser>(result);\n        }\n\n#if VB_ENABLED\n        [Fact]\n        public void DecorateCodeParser_ReplacesVBCodeParserWithMvcSpecificOne() {\n            // Arrange\n            MvcWebPageRazorHost host = new MvcWebPageRazorHost(\"foo.vbhtml\", \"bar\");\n            var parser = new VBCodeParser();\n\n            // Act\n            var result = host.DecorateCodeParser(parser);\n\n            // Assert\n            Assert.IsType<MvcVBRazorCodeParser>(result);\n        }\n#endif\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Routing/AttributeRoutingLinkGenerationTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Routing.Test\n{\n    public class AttributeRoutingLinkGenerationTest\n    {\n        [Fact]\n        public void GenerateLink_ToArea_ControllerRoute_WithPrefix()\n        {\n            // Arrange\n            Type[] controllerTypes = new Type[] { typeof(AreaWithPrefixWithControllerRouteController) };\n            RouteCollection routes = MapControllers(controllerTypes);\n            RequestContext requestContext = GetRequestContext();\n\n            RouteValueDictionary values = new RouteValueDictionary()\n            {\n                { \"controller\", \"AreaWithPrefixWithControllerRoute\" },\n                { \"action\", \"A1\" },\n                { \"area\", \"Administration\" }\n            };\n\n            // Act\n            VirtualPathData vpd = routes.GetVirtualPathForArea(requestContext, values);\n\n            // Assert\n            Assert.NotNull(vpd);\n            Assert.Equal(\"/Admin/Home/A1\", vpd.VirtualPath);\n        }\n\n        [Fact]\n        public void GenerateLink_ToArea_ActionRoute_WithPrefix()\n        {\n            // Arrange\n            Type[] controllerTypes = new Type[] { typeof(AreaWithPrefixWithControllerRouteController) };\n            RouteCollection routes = MapControllers(controllerTypes);\n            RequestContext requestContext = GetRequestContext();\n\n            RouteValueDictionary values = new RouteValueDictionary()\n            {\n                { \"controller\", \"AreaWithPrefixWithControllerRoute\" },\n                { \"action\", \"A2\" },\n                { \"area\", \"Administration\" }\n            };\n\n            // Act\n            VirtualPathData vpd = routes.GetVirtualPathForArea(requestContext, values);\n\n            // Assert\n            Assert.NotNull(vpd);\n            Assert.Equal(\"/Admin\", vpd.VirtualPath);\n        }\n\n        [Fact]\n        public void GenerateLink_ToArea_ActionRoute_WithPrefix_WithinController()\n        {\n            // Arrange\n            Type[] controllerTypes = new Type[] { typeof(AreaWithPrefixWithControllerRouteController) };\n            RouteCollection routes = MapControllers(controllerTypes);\n            RequestContext requestContext = GetRequestContext();\n\n            requestContext.RouteData.DataTokens.Add(\"area\", \"Administration\");\n            requestContext.RouteData.DataTokens.Add(\"controller\", \"AreaWithPrefixWithControllerRoute\");\n\n            RouteValueDictionary values = new RouteValueDictionary()\n            {\n                { \"action\", \"A2\" },\n            };\n\n            // Act\n            VirtualPathData vpd = routes.GetVirtualPathForArea(requestContext, values);\n\n            // Assert\n            Assert.NotNull(vpd);\n            Assert.Equal(\"/Admin\", vpd.VirtualPath);\n        }\n\n        [Fact]\n        public void GenerateLink_ToController_PrefersActionRoute()\n        {\n            // Arrange\n            Type[] controllerTypes = new Type[] { typeof(MixedRoutingController) };\n            RouteCollection routes = MapControllers(controllerTypes);\n            RequestContext requestContext = GetRequestContext();\n\n            requestContext.RouteData.DataTokens.Add(\"controller\", \"MixedRouting\");\n\n            RouteValueDictionary values = new RouteValueDictionary()\n            {\n                { \"action\", \"A2\" },\n            };\n\n            // Act\n            VirtualPathData vpd = routes.GetVirtualPathForArea(requestContext, values);\n\n            // Assert\n            Assert.NotNull(vpd);\n            Assert.Equal(\"/A2\", vpd.VirtualPath);\n            Assert.True(((Route)vpd.Route).GetTargetIsAction());\n        }\n\n        [Fact]\n        public void GenerateLink_ToController_PrefersControllerRouteWithOrder()\n        {\n            // Arrange\n            Type[] controllerTypes = new Type[] { typeof(MixedRoutingWithOrderController) };\n            RouteCollection routes = MapControllers(controllerTypes);\n            RequestContext requestContext = GetRequestContext();\n\n            requestContext.RouteData.DataTokens.Add(\"controller\", \"MixedRoutingWithOrder\");\n\n            RouteValueDictionary values = new RouteValueDictionary()\n            {\n                { \"action\", \"A2\" },\n            };\n\n            // Act\n            VirtualPathData vpd = routes.GetVirtualPathForArea(requestContext, values);\n\n            // Assert\n            Assert.NotNull(vpd);\n            Assert.Equal(\"/mixedroutingwithorder/A2\", vpd.VirtualPath);\n            Assert.False(((Route)vpd.Route).GetTargetIsAction());\n        }\n\n        /// <summary>\n        /// This test validates that these routes aren't overly greedy. We don't want the route\n        /// for C2 to match when we're looking for C1.\n        /// </summary>\n        [Theory]\n        [InlineData(typeof(Controller1Controller), typeof(Controller2Controller))]\n        [InlineData(typeof(Controller2Controller), typeof(Controller1Controller))]\n        public void GenerateLink_MultiplControllerRoutesMatch(Type c1, Type c2)\n        {\n            // Arrange\n            Type[] controllerTypes = new Type[] { c1, c2 };\n            RouteCollection routes = MapControllers(controllerTypes);\n            RequestContext requestContext = GetRequestContext();\n\n            RouteValueDictionary values = new RouteValueDictionary()\n            {\n                { \"action\", \"A1\" },\n                { \"controller\", \"Controller1\" }\n            };\n\n            // Act\n            VirtualPathData vpd = routes.GetVirtualPathForArea(requestContext, values);\n\n            // Assert\n            Assert.NotNull(vpd);\n            Assert.Equal(\"/c1/A1\", vpd.VirtualPath);\n        }\n\n        private static RequestContext GetRequestContext()\n        {\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(c => c.Request.ApplicationPath).Returns(\"/\");\n            mockHttpContext.Setup(c => c.Response.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(virtualPath => virtualPath);\n\n            return new RequestContext(mockHttpContext.Object, new RouteData());\n        }\n\n        private RouteCollection MapControllers(Type[] types)\n        {\n            RouteCollection routes = new RouteCollection();\n            AttributeRoutingMapper.MapAttributeRoutes(routes, types);\n            return routes;\n        }\n\n        [Route(\"Home/{action}\")]\n        [RouteArea(\"Administration\", AreaPrefix = \"Admin\")]\n        private class AreaWithPrefixWithControllerRouteController : Controller\n        {\n            public void A1()\n            {\n            }\n\n            [Route]\n            public void A2()\n            {\n            }\n        }\n\n        [Route(\"c1/{action}\")]\n        private class Controller1Controller : Controller\n        {\n            public void A1()\n            {\n            }\n        }\n\n        [Route(\"c2/{action}\")]\n        private class Controller2Controller : Controller\n        {\n            public void A1()\n            {\n            }\n        }\n\n        [Route(\"mixedrouting/{action}\")]\n        private class MixedRoutingController : Controller\n        {\n            public void A1()\n            {\n            }\n\n            // The catch-all parameter is here to make sure this route has a worse precedence\n            // than the controller-level route.\n            [Route(\"A2/{*params}\")]\n            public void A2()\n            {\n            }\n        }\n\n        [Route(\"mixedroutingwithorder/{action}\")]\n        private class MixedRoutingWithOrderController : Controller\n        {\n            public void A1()\n            {\n            }\n\n            // The order makes this 'worse' than the controller level route - if a user does this it's likely\n            // because they have two actions with the same name.\n            [Route(\"A2/{*params}\", Order=55)]\n            public void A2()\n            {\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Routing/AttributeRoutingMapperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Routing\n{\n    public class AttributeRoutingMapperTest\n    {\n        [Fact]\n        public void MapMvcAttributeRoutes_DoesNotTryToInferRouteNames()\n        {\n            var controllerType = typeof(MyController);\n\n            var routeEntries = AttributeRoutingMapper.GetAttributeRoutes(controllerType);\n\n            var routeEntry = Assert.Single(routeEntries);\n            Assert.Null(routeEntry.Name);\n        }\n\n        [Fact]\n        public void MapMvcAttributeRoutes_RespectsActionNameAttribute()\n        {\n            // Arrange\n            var controllerType = typeof(MyController);\n\n            // Act\n            var routeEntries = AttributeRoutingMapper.GetAttributeRoutes(controllerType);\n\n            // Assert\n            var routeEntry = Assert.Single(routeEntries);\n            Assert.Equal(\"ActionName\", routeEntry.Route.Defaults[\"action\"]);\n        }\n\n        [Fact]\n        public void MapMvcAttributeRoutes_WithControllerRoute()\n        {\n            // Arrange\n            var controllerType = typeof(AnotherController);\n\n            // Act\n            var entries = AttributeRoutingMapper.GetAttributeRoutes(controllerType);\n\n            // Assert\n            var controllerEntry = Assert.Single(entries, r => !r.Route.Defaults.ContainsKey(\"action\"));\n            Assert.Same(controllerType, controllerEntry.Route.GetTargetControllerDescriptor().ControllerType);\n\n            var actionMethods = controllerEntry.Route.GetTargetActionDescriptors().ToArray();\n            Assert.Equal(2, actionMethods.Length);\n            Assert.Single(actionMethods, a => a.ActionName == \"RegularAction\");\n            Assert.Single(actionMethods, a => a.ActionName == \"AnotherAction\");\n        }\n\n        [Fact]\n        public void MapMvcAttributeRoutes_WithControllerRoute_AndNoReachableActions()\n        {\n            // Arrange\n            var controllerType = typeof(NoActionsController);\n\n            // Act\n            var entries = AttributeRoutingMapper.GetAttributeRoutes(controllerType);\n\n            // Assert\n            Assert.Empty(entries);\n        }\n\n        [Fact]\n        public void MapMvcAttributeRoutes_WithControllerRoute_ExcludesAttributeRoute()\n        {\n            // Arrange\n            var controllerType = typeof(MixedRoutingController);\n\n            // Act\n            var entries = AttributeRoutingMapper.GetAttributeRoutes(controllerType);\n\n            // Assert\n            var controllerEntry = Assert.Single(entries, r => !r.Route.Defaults.ContainsKey(\"action\"));\n            Assert.Same(controllerType, controllerEntry.Route.GetTargetControllerDescriptor().ControllerType);\n\n            var actionMethods = controllerEntry.Route.GetTargetActionDescriptors().ToArray();\n            Assert.Single(actionMethods);\n            Assert.Single(actionMethods, a => a.ActionName == \"GoodAction\");\n\n            var actionEntry = Assert.Single(entries, r => r.Route.Defaults.ContainsKey(\"action\"));\n            Assert.Equal(\"DirectRouteAction\", Assert.Single(actionEntry.Route.GetTargetActionDescriptors()).ActionName);\n        }\n\n        [Fact]\n        public void MapMvcAttributeRoutes_SetsTargetIsAction()\n        {\n            // Arrange\n            var controllerType = typeof(MixedRoutingController);\n\n            // Act\n            var entries = AttributeRoutingMapper.GetAttributeRoutes(controllerType);\n\n            // Assert\n            var controllerEntry = Assert.Single(entries, r => !r.Route.Defaults.ContainsKey(\"action\"));\n            Assert.False(controllerEntry.Route.GetTargetIsAction());\n\n            var actionEntry = Assert.Single(entries, r => r.Route.Defaults.ContainsKey(\"action\"));\n            Assert.True(actionEntry.Route.GetTargetIsAction());\n        }\n\n        [Fact]\n        public void MapMvcAttributeRoutes_ValidatesConstraints()\n        {\n            // Arrange\n            var controllerType = typeof(InvalidConstraintController);\n\n            string expectedMessage =\n                \"The constraint entry 'custom' on the route with route template 'invalidconstraint/{action}' \" +\n                \"must have a string value or be of a type which implements 'System.Web.Routing.IRouteConstraint'.\";\n\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(() => AttributeRoutingMapper.GetAttributeRoutes(controllerType), expectedMessage);\n        }\n\n        [InvalidConstraintRoute(\"invalidconstraint/{action}\")]\n        public class InvalidConstraintController : Controller\n        {\n            public void A1()\n            {\n            }\n        }\n\n        public class InvalidConstraintRouteAttribute : RouteFactoryAttribute\n        {\n            public InvalidConstraintRouteAttribute(string template)\n                : base(template)\n            {\n            }\n\n            public override RouteValueDictionary Constraints\n            {\n                get\n                {\n                    var result = new RouteValueDictionary();\n                    result.Add(\"custom\", new Uri(\"http://localhost\"));\n                    return result;\n                }\n            }\n        }\n\n        public class MyController : Controller\n        {\n            [HttpGet]\n            [Route(\"\")]\n            [ActionName(\"ActionName\")]\n            public void MethodName()\n            {\n            }\n        }\n\n        [Route(\"controller/{action}\")]\n        public class AnotherController : Controller\n        {\n            public void RegularAction()\n            {\n            }\n\n            public void AnotherAction()\n            {\n            }\n        }\n\n        [Route(\"controller/{action}\")]\n        public class NoActionsController : Controller\n        {\n        }\n\n        [Route(\"controller/{action}\")]\n        public class MixedRoutingController : Controller\n        {\n            [Route(\"Yep\")]\n            public void DirectRouteAction()\n            {\n            }\n\n            public void GoodAction()\n            {\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Routing/AttributeRoutingTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Specialized;\nusing System.IO;\nusing System.Reflection;\nusing System.Web.Mvc;\nusing System.Web.Mvc.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Routing\n{\n    public class AttributeRoutingTest\n    {\n        internal const string ResultKey = \"MS_Test_Result\";\n\n        [Theory]\n        [InlineData(typeof(DerivedController), \"~/BaseMethodWithRoute\", \"BaseMethodWithRoute\")]\n        [InlineData(typeof(DerivedController), \"~/BaseVirtualMethodWithRoute\", \"BaseVirtualMethodWithRoute\")]\n        [InlineData(typeof(DerivedController), \"~/BaseVirtualMethodWithRouteToBeOverridenWithRoute\", \"BaseVirtualMethodWithRouteToBeOverridenWithRoute\")]\n        [InlineData(typeof(DerivedController), \"~/DerivedMethodWithRoute\", \"DerivedMethodWithRoute\")]\n        [InlineData(typeof(DerivedController), \"~/BaseVirtualMethodToBeOverridenWithRoute_Derived\", \"BaseVirtualMethodToBeOverridenWithRoute_Derived\")]\n        [InlineData(typeof(DerivedController), \"~/BaseVirtualMethodWithRouteToBeOverridenWithRoute_Derived\", \"BaseVirtualMethodWithRouteToBeOverridenWithRoute_Derived\")]\n        [InlineData(typeof(DerivedController), \"~/BaseMethodWithRouteWithName\", \"BaseMethodWithRouteWithName\")]\n        [InlineData(typeof(DerivedPrefixController), \"~/BaseMethodWithRoute\", \"BaseMethodWithRoute\")]\n        [InlineData(typeof(DerivedPrefixController), \"~/BaseVirtualMethodWithRoute\", \"BaseVirtualMethodWithRoute\")]\n        [InlineData(typeof(DerivedPrefixController), \"~/BaseVirtualMethodWithRouteToBeOverridenWithRoute\", \"BaseVirtualMethodWithRouteToBeOverridenWithRoute\")]\n        [InlineData(typeof(DerivedPrefixController), \"~/derived/DerivedMethodWithRoute\", \"DerivedMethodWithRoute\")]\n        [InlineData(typeof(DerivedPrefixController), \"~/derived/BaseVirtualMethodToBeOverridenWithRoute_Derived\", \"BaseVirtualMethodToBeOverridenWithRoute_Derived\")]\n        [InlineData(typeof(DerivedPrefixController), \"~/derived/BaseVirtualMethodWithRouteToBeOverridenWithRoute_Derived\", \"BaseVirtualMethodWithRouteToBeOverridenWithRoute_Derived\")]\n        [InlineData(typeof(DerivedFromBasePrefixController), \"~/base/BaseMethodWithRoute\", \"BaseMethodWithRoute\")]\n        [InlineData(typeof(DerivedFromBasePrefixController), \"~/base/BaseVirtualMethodWithRoute\", \"BaseVirtualMethodWithRoute\")]\n        [InlineData(typeof(DerivedFromBasePrefixController), \"~/base/BaseVirtualMethodWithRouteToBeOverridenWithRoute\", \"BaseVirtualMethodWithRouteToBeOverridenWithRoute\")]\n        [InlineData(typeof(DerivedFromBasePrefixController), \"~/DerivedMethodWithRoute\", \"DerivedMethodWithRoute\")]\n        [InlineData(typeof(DerivedFromBasePrefixController), \"~/BaseVirtualMethodToBeOverridenWithRoute_Derived\", \"BaseVirtualMethodToBeOverridenWithRoute_Derived\")]\n        [InlineData(typeof(DerivedFromBasePrefixController), \"~/BaseVirtualMethodWithRouteToBeOverridenWithRoute_Derived\", \"BaseVirtualMethodWithRouteToBeOverridenWithRoute_Derived\")]\n        [InlineData(typeof(DerivedWithPrefixFromBasePrefixController), \"~/base/BaseMethodWithRoute\", \"BaseMethodWithRoute\")]\n        [InlineData(typeof(DerivedWithPrefixFromBasePrefixController), \"~/base/BaseVirtualMethodWithRoute\", \"BaseVirtualMethodWithRoute\")]\n        [InlineData(typeof(DerivedWithPrefixFromBasePrefixController), \"~/base/BaseVirtualMethodWithRouteToBeOverridenWithRoute\", \"BaseVirtualMethodWithRouteToBeOverridenWithRoute\")]\n        [InlineData(typeof(DerivedWithPrefixFromBasePrefixController), \"~/derived/DerivedMethodWithRoute\", \"DerivedMethodWithRoute\")]\n        [InlineData(typeof(DerivedWithPrefixFromBasePrefixController), \"~/derived/BaseVirtualMethodToBeOverridenWithRoute_Derived\", \"BaseVirtualMethodToBeOverridenWithRoute_Derived\")]\n        [InlineData(typeof(DerivedWithPrefixFromBasePrefixController), \"~/derived/BaseVirtualMethodWithRouteToBeOverridenWithRoute_Derived\", \"BaseVirtualMethodWithRouteToBeOverridenWithRoute_Derived\")]\n        [InlineData(typeof(DerivedFromBaseRouteController), \"~/BaseMethodWithRoute\", \"BaseMethodWithRoute\")]\n        [InlineData(typeof(DerivedFromBaseRouteController), \"~/base/BaseVirtualMethodToBeOverridenWithRoute\", \"BaseVirtualMethodToBeOverridenWithRoute\")]\n        [InlineData(typeof(DerivedFromBaseRouteController), \"~/BaseVirtualMethodWithRoute\", \"BaseVirtualMethodWithRoute\")]\n        [InlineData(typeof(DerivedFromBaseRouteController), \"~/BaseVirtualMethodWithRouteToBeOverridenWithRoute\", \"BaseVirtualMethodWithRouteToBeOverridenWithRoute\")]\n        [InlineData(typeof(DerivedFromBaseRouteController), \"~/DerivedMethodWithRoute\", \"DerivedMethodWithRoute\")]\n        [InlineData(typeof(DerivedFromBaseRouteController), \"~/BaseVirtualMethodToBeOverridenWithRoute_Derived\", \"BaseVirtualMethodToBeOverridenWithRoute_Derived\")]\n        [InlineData(typeof(DerivedFromBaseRouteWithRouteController), \"~/derivedwithroute/BaseMethodWithRoute\", \"BaseMethodWithRoute\")]\n        [InlineData(typeof(DerivedFromBaseRouteWithRouteController), \"~/derivedwithroute/BaseVirtualMethodToBeOverridenWithRoute\", \"BaseVirtualMethodToBeOverridenWithRoute\")]\n        [InlineData(typeof(DerivedFromBaseRouteWithRouteController), \"~/derivedwithroute/BaseVirtualMethodWithRoute\", \"BaseVirtualMethodWithRoute\")]\n        [InlineData(typeof(DerivedFromBaseRouteWithRouteController), \"~/derivedwithroute/BaseVirtualMethodWithRouteToBeOverridenWithRoute\", \"BaseVirtualMethodWithRouteToBeOverridenWithRoute\")]\n        public void AttributeRouting_WithInheritance_MethodOverrides(Type derivedController, string path, string expectedAction)\n        {\n            // Arrange\n            var controllerTypes = new[] { derivedController, derivedController.BaseType };\n            var routes = new RouteCollection();\n            AttributeRoutingMapper.MapAttributeRoutes(routes, controllerTypes);\n\n            HttpContextBase context = GetContext(path);\n            RouteData routeData = routes.GetRouteData(context);\n            RequestContext requestContext = new RequestContext(context, routeData);\n            MvcHandler handler = new MvcHandler(requestContext);\n            handler.ControllerBuilder.SetControllerFactory(GetControllerFactory(controllerTypes));\n\n            // Act\n            handler.ProcessRequest(context);\n\n            // Assert\n            ContentResult result = Assert.IsType<ContentResult>(context.Items[ResultKey]);\n            Assert.Equal(expectedAction, result.Content);\n        }\n\n        [Theory]\n        [InlineData(typeof(DerivedController), \"~/BaseMethodWithRouteTypo\")]\n        [InlineData(typeof(DerivedController), \"~/derived/BaseMethodWithRoute\")]\n        [InlineData(typeof(DerivedPrefixController), \"~/derived/BaseVirtualMethodWithRoute\")]\n        [InlineData(typeof(DerivedWithPrefixFromBasePrefixController), \"~/derived/BaseVirtualMethodWithRoute\")]\n        public void AttributeRouting_WithInheritance_InvalidPaths(Type derivedController, string path)\n        {\n            // Arrange\n            var controllerTypes = new[] { derivedController, derivedController.BaseType };\n            var routes = new RouteCollection();\n            AttributeRoutingMapper.MapAttributeRoutes(routes, controllerTypes);\n            HttpContextBase context = GetContext(path);\n\n            // Act\n            RouteData routeData = routes.GetRouteData(context);\n\n            // Assert\n            Assert.Null(routeData);\n        }\n\n        [Theory]\n        [InlineData(typeof(MethodOverloadsController), \"~/Get1\", \"Get1\")]\n        [InlineData(typeof(MethodOverloadsController), \"~/Get2?id=42\", \"Get2_42\")]\n        public void AttributeRouting_MethodOverloads_WithDifferentActionNames(Type controllerType, string path, string expectedAction)\n        {\n            // Arrange\n            var controllerTypes = new[] { controllerType };\n            var routes = new RouteCollection();\n            AttributeRoutingMapper.MapAttributeRoutes(routes, controllerTypes);\n\n            HttpContextBase context = GetContext(path);\n            RouteData routeData = routes.GetRouteData(context);\n            RequestContext requestContext = new RequestContext(context, routeData);\n            MvcHandler handler = new MvcHandler(requestContext);\n            handler.ControllerBuilder.SetControllerFactory(GetControllerFactory(controllerTypes));\n\n            // Act\n            handler.ProcessRequest(context);\n\n            // Assert\n            ContentResult result = Assert.IsType<ContentResult>(context.Items[ResultKey]);\n            Assert.Equal(expectedAction, result.Content);\n        }\n\n        [Theory]\n        [InlineData(typeof(MethodOverloadsController), \"~/GetAmbiguous?id=42\")]\n        public void AttributeRouting_AmbiguousActions_ThrowsAmbiguousException(Type controllerType, string path)\n        {\n            // Arrange\n            var controllerTypes = new[] { controllerType };\n            var routes = new RouteCollection();\n            AttributeRoutingMapper.MapAttributeRoutes(routes, controllerTypes);\n\n            HttpContextBase context = GetContext(path);\n            RouteData routeData = routes.GetRouteData(context);\n            RequestContext requestContext = new RequestContext(context, routeData);\n            MvcHandler handler = new MvcHandler(requestContext);\n            handler.ControllerBuilder.SetControllerFactory(GetControllerFactory(controllerTypes));\n\n            Assert.Throws<AmbiguousMatchException>(() => handler.ProcessRequest(context));\n        }\n\n        [Theory]\n        [InlineData(typeof(MixedRoutingController), \"~/GetWithRoute\", \"GetWithRoute\")]\n        [InlineData(typeof(MixedRoutingController), \"~/standard/GetWithoutRoute\", \"GetWithoutRoute\")]\n        [InlineData(typeof(MixedRoutingController), \"~/standard/GetWithRoute\", null)]\n        [InlineData(typeof(MixedRoutingWithPrefixController), \"~/prefix/GetWithRoute\", \"GetWithRoute\")]\n        [InlineData(typeof(MixedRoutingWithPrefixController), \"~/standard/GetWithoutRoute\", \"GetWithoutRoute\")]\n        [InlineData(typeof(MixedRoutingWithPrefixController), \"~/standard/GetWithRoute\", null)]\n        [InlineData(typeof(MixedRoutingWithRouteonController), \"~/GetWithRoute\", \"GetWithRoute\")]\n        [InlineData(typeof(MixedRoutingWithRouteonController), \"~/GetWithoutRoute\", \"GetWithoutRoute\")]\n        [InlineData(typeof(MixedRoutingWithRouteonController), \"~/standard/GetWithoutRoute\", null)]\n        [InlineData(typeof(MixedRoutingWithRouteonController), \"~/standard/GetWithRoute\", null)]\n        public void AttributeRouting_MixedWithGeneralRouting(Type controllerType, string path, string expectedAction)\n        {\n            // Arrange\n            var controllerTypes = new[] { controllerType };\n            var routes = new RouteCollection();\n            object defaults = new { controller = controllerType.Name.Substring(0, controllerType.Name.Length - 10) };\n            routes.Add(new Route(\"standard/{action}\", new RouteValueDictionary(defaults), null));\n            AttributeRoutingMapper.MapAttributeRoutes(routes, controllerTypes);\n\n            HttpContextBase context = GetContext(path);\n            RouteData routeData = routes.GetRouteData(context);\n            RequestContext requestContext = new RequestContext(context, routeData);\n            MvcHandler handler = new MvcHandler(requestContext);\n            handler.ControllerBuilder.SetControllerFactory(GetControllerFactory(controllerTypes));\n\n            if (expectedAction == null)\n            {\n                // Act & Assert\n                Assert.Throws<HttpException>(() => handler.ProcessRequest(context));\n            }\n            else\n            {\n                // Act\n                handler.ProcessRequest(context);\n\n                // Assert\n                ContentResult result = Assert.IsType<ContentResult>(context.Items[ResultKey]);\n                Assert.Equal(expectedAction, result.Content);\n            }\n        }\n\n        [Theory]\n        [InlineData(typeof(ActionMethodSelectorsController), \"~/Action1\", \"Action1(int)\")]\n        [InlineData(typeof(ActionMethodSelectorsController), \"~/DoesntRun\", null)]\n        public void AttributeRouting_WithActionMethodSelectors(Type controllerType, string path, string expectedAction)\n        {\n            // Arrange\n            var controllerTypes = new[] { controllerType };\n            var routes = new RouteCollection();\n            AttributeRoutingMapper.MapAttributeRoutes(routes, controllerTypes);\n\n            HttpContextBase context = GetContext(path);\n            RouteData routeData = routes.GetRouteData(context);\n            RequestContext requestContext = new RequestContext(context, routeData);\n            MvcHandler handler = new MvcHandler(requestContext);\n            handler.ControllerBuilder.SetControllerFactory(GetControllerFactory(controllerTypes));\n\n            if (expectedAction == null)\n            {\n                // Act & Assert\n                Assert.Throws<HttpException>(() => handler.ProcessRequest(context));\n            }\n            else\n            {\n                // Act\n                handler.ProcessRequest(context);\n\n                // Assert\n                ContentResult result = Assert.IsType<ContentResult>(context.Items[ResultKey]);\n                Assert.Equal(expectedAction, result.Content);\n            }\n        }\n\n        [Theory]\n        [InlineData(typeof(ActionNameSelectorsController), \"~/SpecialName\", \"Action2()\")]\n        [InlineData(typeof(ActionNameSelectorsController), \"~/AnotherSpecialName\", \"Action3()\")]\n        public void AttributeRouting_WithActionNameSelectors(Type controllerType, string path, string expectedAction)\n        {\n            // Arrange\n            var controllerTypes = new[] { controllerType };\n            var routes = new RouteCollection();\n            AttributeRoutingMapper.MapAttributeRoutes(routes, controllerTypes);\n\n            HttpContextBase context = GetContext(path);\n            RouteData routeData = routes.GetRouteData(context);\n            RequestContext requestContext = new RequestContext(context, routeData);\n            MvcHandler handler = new MvcHandler(requestContext);\n            handler.ControllerBuilder.SetControllerFactory(GetControllerFactory(controllerTypes));\n\n            if (expectedAction == null)\n            {\n                // Act & Assert\n                Assert.Throws<HttpException>(() => handler.ProcessRequest(context));\n            }\n            else\n            {\n                // Act\n                handler.ProcessRequest(context);\n\n                // Assert\n                ContentResult result = Assert.IsType<ContentResult>(context.Items[ResultKey]);\n                Assert.Equal(expectedAction, result.Content);\n            }\n        }\n\n        [Fact]\n        public void AttributeRouting_OptionalParametersGetRemoved()\n        {\n            // Arrange\n            var controllerTypes = new[] { typeof(OptionalParameterController) };\n            var routes = new RouteCollection();\n            AttributeRoutingMapper.MapAttributeRoutes(routes, controllerTypes);\n\n            HttpContextBase context = GetContext(\"~/Create\");\n            RouteData routeData = routes.GetRouteData(context);\n            RequestContext requestContext = new RequestContext(context, routeData);\n            MvcHandler handler = new MvcHandler(requestContext);\n            handler.ControllerBuilder.SetControllerFactory(GetControllerFactory(controllerTypes));\n\n            // Act\n            handler.ProcessRequest(context);\n\n            // Assert\n            ContentResult result = Assert.IsType<ContentResult>(context.Items[ResultKey]);\n            Assert.Equal(\"Create()\", result.Content);\n\n            // The request context should be updated to to contain the routedata of the direct route\n            Assert.Equal(\"{action}/{id}\", ((Route)requestContext.RouteData.Route).Url);\n            Assert.Null(requestContext.RouteData.Values[\"id\"]);\n        }\n\n        [Theory]\n        [InlineData(\"~/Home1/Index\", \"Home1.Index()\")]\n        [InlineData(\"~/Home2/Index\", \"Home2.Index()\")]\n        public void AttributeRouting_WithSameControllerName(string path, string expectedAction)\n        {\n            // Arrange\n            var controllerTypes = new[]\n            {\n                typeof(ControllersWithTheSameName.NS1.HomeController),\n                typeof(ControllersWithTheSameName.NS2.HomeController),\n            };\n\n            var routes = new RouteCollection();\n            AttributeRoutingMapper.MapAttributeRoutes(routes, controllerTypes);\n\n            HttpContextBase context = GetContext(path);\n            RouteData routeData = routes.GetRouteData(context);\n            RequestContext requestContext = new RequestContext(context, routeData);\n            MvcHandler handler = new MvcHandler(requestContext);\n            handler.ControllerBuilder.SetControllerFactory(GetControllerFactory(controllerTypes));\n\n            // Act\n            handler.ProcessRequest(context);\n\n            // Assert\n            ContentResult result = Assert.IsType<ContentResult>(context.Items[ResultKey]);\n            Assert.Equal(expectedAction, result.Content);\n        }\n\n        [Theory]\n        [InlineData(\"~/NS1Home/Introduction\", \"Home.Index()\")]\n        [InlineData(\"~/NS2Account/PeopleList\", \"Account.Index()\")]\n        [InlineData(\"~/Default/Unknown\", \"Default.Index()\")]\n        public void AttributeRouting_WithCustomizedRoutePrefixAttribute(string path, string expectedAction)\n        {\n            // Arrange\n            var controllerTypes = new[]\n            {\n                typeof(ControllersWithCustomizedRoutePrefixAttribute.NS1.HomeController),\n                typeof(ControllersWithCustomizedRoutePrefixAttribute.NS2.AccountController),\n                typeof(ControllersWithCustomizedRoutePrefixAttribute.NS3.OtherController),\n            };\n\n            var routes = new RouteCollection();\n            AttributeRoutingMapper.MapAttributeRoutes(routes, controllerTypes);\n\n            HttpContextBase context = GetContext(path);\n            RouteData routeData = routes.GetRouteData(context);\n            RequestContext requestContext = new RequestContext(context, routeData);\n            MvcHandler handler = new MvcHandler(requestContext);\n            handler.ControllerBuilder.SetControllerFactory(GetControllerFactory(controllerTypes));\n\n            // Act\n            handler.ProcessRequest(context);\n\n            // Assert\n            ContentResult result = Assert.IsType<ContentResult>(context.Items[ResultKey]);\n            Assert.Equal(expectedAction, result.Content);\n        }\n\n        [Fact]\n        public void AttributeRouting_WithMultipleCustomizedRoutePrefixAttribute_ThrowsInvalidOperationException()\n        {\n            // Arrange\n            var controllerTypes = new[]\n            {\n                typeof(ControllersWithCustomizedRoutePrefixAttribute.Invalid.HomeController)\n            };\n\n            var routes = new RouteCollection();\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(() => AttributeRoutingMapper.MapAttributeRoutes(routes, controllerTypes),\n                \"Only one route prefix attribute is supported. Remove extra attributes from the controller of type 'System.Web.Routing.ControllersWithCustomizedRoutePrefixAttribute.Invalid.HomeController'.\");\n        }\n\n        [Fact]\n        public void AttributeRouting_WithNullPrefix_ThrowsInvalidOperationException()\n        {\n            // Arrange\n            var controllerTypes = new[]\n            {\n                typeof(ControllersWithCustomizedRoutePrefixAttribute.Invalid.AccountController)\n            };\n\n            var routes = new RouteCollection();\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(() => AttributeRoutingMapper.MapAttributeRoutes(routes, controllerTypes),\n                \"The property 'prefix' from route prefix attribute on controller of type 'System.Web.Routing.ControllersWithCustomizedRoutePrefixAttribute.Invalid.AccountController' cannot be null.\");\n        }\n\n        private IControllerFactory GetControllerFactory(Type[] controllerTypes)\n        {\n            return new DefaultControllerFactory\n            {\n                BuildManager = new MockBuildManager(controllerTypes),\n                ControllerTypeCache = new ControllerTypeCache()\n            };\n        }\n\n        private HttpContextBase GetContext(string url)\n        {\n            Uri uri = new Uri(\"http://localhost/\" + url.Substring(2));\n\n            NameValueCollection queryString = HttpUtility.ParseQueryString(uri.Query);\n\n            Mock<UnvalidatedRequestValuesBase> unvalidatedRequest = new Mock<UnvalidatedRequestValuesBase>();\n            unvalidatedRequest.Setup(u => u.Form).Returns(new NameValueCollection());\n            unvalidatedRequest.Setup(u => u.QueryString).Returns(queryString);\n\n            // mock HttpRequest\n            Mock<HttpRequestBase> requestMock = new Mock<HttpRequestBase>();\n            requestMock.Setup(request => request.Url).Returns(uri);\n            requestMock.Setup(request => request.HttpMethod).Returns(\"GET\");\n            requestMock.Setup(request => request.Form).Returns(new NameValueCollection());\n            requestMock.Setup(request => request.ServerVariables).Returns(new NameValueCollection());\n            requestMock.Setup(request => request.AppRelativeCurrentExecutionFilePath).Returns(\"~\" + uri.AbsolutePath);\n            requestMock.Setup(request => request.Unvalidated).Returns(unvalidatedRequest.Object);\n            requestMock.Setup(request => request.ContentType).Returns(\"\");\n            requestMock.Setup(request => request.QueryString).Returns(queryString);\n            requestMock.Setup(request => request.Files).Returns(new Mock<HttpFileCollectionBase>().Object);\n\n            // mock HttpResponse\n            Mock<HttpResponseBase> responseBase = new Mock<HttpResponseBase>();\n\n            // mock HttpContext\n            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>();\n            contextMock.Setup(context => context.Items).Returns(new Hashtable());\n            contextMock.Setup(context => context.Request).Returns(requestMock.Object);\n            contextMock.Setup(context => context.Response).Returns(responseBase.Object);\n            return contextMock.Object;\n        }\n\n        private class MockBuildManager : IBuildManager\n        {\n            private Assembly[] _assemblies;\n\n            public MockBuildManager(Type[] types)\n            {\n                MockAssembly assembly = new MockAssembly(types);\n                _assemblies = new Assembly[] { assembly };\n            }\n\n            public bool FileExists(string virtualPath)\n            {\n                throw new NotImplementedException();\n            }\n\n            public Type GetCompiledType(string virtualPath)\n            {\n                throw new NotImplementedException();\n            }\n\n            public ICollection GetReferencedAssemblies()\n            {\n                return _assemblies;\n            }\n\n            public Stream ReadCachedFile(string fileName)\n            {\n                return null;\n            }\n\n            public Stream CreateCachedFile(string fileName)\n            {\n                return null;\n            }\n\n            private sealed class MockAssembly : Assembly\n            {\n                Type[] _types;\n\n                public MockAssembly(params Type[] types)\n                {\n                    _types = types;\n                }\n\n                public override Type[] GetTypes()\n                {\n                    return _types;\n                }\n            }\n        }\n    }\n\n    // stores the response from the action on the request context for later inspection.\n    public class ResponseStoringController : Controller\n    {\n        protected override void OnActionExecuting(ActionExecutingContext filterContext)\n        {\n            // use the per-instance cache to avoid timing issues.\n            filterContext.ActionDescriptor.DispatcherCache = new ActionMethodDispatcherCache();\n            base.OnActionExecuting(filterContext);\n        }\n\n        protected override void OnActionExecuted(ActionExecutedContext filterContext)\n        {\n            filterContext.RequestContext.HttpContext.Items[AttributeRoutingTest.ResultKey] = filterContext.Result;\n        }\n    }\n\n    #region Inheritance Controllers\n\n    public class BaseController : ResponseStoringController\n    {\n        [Route(\"BaseMethodWithRoute\")]\n        public string BaseMethodWithRoute()\n        {\n            return \"BaseMethodWithRoute\";\n        }\n\n        [Route(\"BaseMethodWithRouteWithName\", Name = \"BaseMethodWithRouteWithName\")]\n        public string BaseMethodWithRouteWithName()\n        {\n            return \"BaseMethodWithRouteWithName\";\n        }\n\n        public virtual string BaseVirtualMethodToBeOverridenWithRoute()\n        {\n            return \"BaseVirtualMethodToBeOverridenWithRoute\";\n        }\n\n        [Route(\"BaseVirtualMethodWithRoute\")]\n        public virtual string BaseVirtualMethodWithRoute()\n        {\n            return \"BaseVirtualMethodWithRoute\";\n        }\n\n        [Route(\"BaseVirtualMethodWithRouteToBeOverridenWithRoute\")]\n        public virtual string BaseVirtualMethodWithRouteToBeOverridenWithRoute()\n        {\n            return \"BaseVirtualMethodWithRouteToBeOverridenWithRoute\";\n        }\n    }\n\n    [RoutePrefix(\"base\")]\n    public class BasePrefixController : ResponseStoringController\n    {\n        [Route(\"BaseMethodWithRoute\")]\n        public string BaseMethodWithRoute()\n        {\n            return \"BaseMethodWithRoute\";\n        }\n\n        public virtual string BaseVirtualMethodToBeOverridenWithRoute()\n        {\n            return \"BaseVirtualMethodToBeOverridenWithRoute\";\n        }\n\n        [Route(\"BaseVirtualMethodWithRoute\")]\n        public virtual string BaseVirtualMethodWithRoute()\n        {\n            return \"BaseVirtualMethodWithRoute\";\n        }\n\n        [Route(\"BaseVirtualMethodWithRouteToBeOverridenWithRoute\")]\n        public virtual string BaseVirtualMethodWithRouteToBeOverridenWithRoute()\n        {\n            return \"BaseVirtualMethodWithRouteToBeOverridenWithRoute\";\n        }\n    }\n\n    [Route(\"base/{action}\")]\n    public class BaseRouteController : ResponseStoringController\n    {\n        [Route(\"BaseMethodWithRoute\")]\n        public string BaseMethodWithRoute()\n        {\n            return \"BaseMethodWithRoute\";\n        }\n\n        public virtual string BaseVirtualMethodToBeOverridenWithRoute()\n        {\n            return \"BaseVirtualMethodToBeOverridenWithRoute\";\n        }\n\n        [Route(\"BaseVirtualMethodWithRoute\")]\n        public virtual string BaseVirtualMethodWithRoute()\n        {\n            return \"BaseVirtualMethodWithRoute\";\n        }\n\n        [Route(\"BaseVirtualMethodWithRouteToBeOverridenWithRoute\")]\n        public virtual string BaseVirtualMethodWithRouteToBeOverridenWithRoute()\n        {\n            return \"BaseVirtualMethodWithRouteToBeOverridenWithRoute\";\n        }\n    }\n\n    public class DerivedController : BaseController\n    {\n        [Route(\"DerivedMethodWithRoute\")]\n        public string DerivedMethodWithRoute()\n        {\n            return \"DerivedMethodWithRoute\";\n        }\n\n        public override string BaseVirtualMethodWithRoute()\n        {\n            return \"BaseVirtualMethodWithRoute_Derived\";\n        }\n\n        [Route(\"BaseVirtualMethodToBeOverridenWithRoute_Derived\")]\n        public override string BaseVirtualMethodToBeOverridenWithRoute()\n        {\n            return \"BaseVirtualMethodToBeOverridenWithRoute_Derived\";\n        }\n\n        [Route(\"BaseVirtualMethodWithRouteToBeOverridenWithRoute_Derived\")]\n        public override string BaseVirtualMethodWithRouteToBeOverridenWithRoute()\n        {\n            return \"BaseVirtualMethodWithRouteToBeOverridenWithRoute_Derived\";\n        }\n    }\n\n    public class DerivedFromBasePrefixController : BasePrefixController\n    {\n        [Route(\"DerivedMethodWithRoute\")]\n        public string DerivedMethodWithRoute()\n        {\n            return \"DerivedMethodWithRoute\";\n        }\n\n        public override string BaseVirtualMethodWithRoute()\n        {\n            return \"BaseVirtualMethodWithRoute_Derived\";\n        }\n\n        [Route(\"BaseVirtualMethodToBeOverridenWithRoute_Derived\")]\n        public override string BaseVirtualMethodToBeOverridenWithRoute()\n        {\n            return \"BaseVirtualMethodToBeOverridenWithRoute_Derived\";\n        }\n\n        [Route(\"BaseVirtualMethodWithRouteToBeOverridenWithRoute_Derived\")]\n        public override string BaseVirtualMethodWithRouteToBeOverridenWithRoute()\n        {\n            return \"BaseVirtualMethodWithRouteToBeOverridenWithRoute_Derived\";\n        }\n    }\n\n    [RoutePrefix(\"derived\")]\n    public class DerivedPrefixController : BaseController\n    {\n        [Route(\"DerivedMethodWithRoute\")]\n        public string DerivedMethodWithRoute()\n        {\n            return \"DerivedMethodWithRoute\";\n        }\n\n        public override string BaseVirtualMethodWithRoute()\n        {\n            return \"BaseVirtualMethodWithRoute_Derived\";\n        }\n\n        [Route(\"BaseVirtualMethodToBeOverridenWithRoute_Derived\")]\n        public override string BaseVirtualMethodToBeOverridenWithRoute()\n        {\n            return \"BaseVirtualMethodToBeOverridenWithRoute_Derived\";\n        }\n\n        [Route(\"BaseVirtualMethodWithRouteToBeOverridenWithRoute_Derived\")]\n        public override string BaseVirtualMethodWithRouteToBeOverridenWithRoute()\n        {\n            return \"BaseVirtualMethodWithRouteToBeOverridenWithRoute_Derived\";\n        }\n    }\n\n    [RoutePrefix(\"derived\")]\n    public class DerivedWithPrefixFromBasePrefixController : BasePrefixController\n    {\n        [Route(\"DerivedMethodWithRoute\")]\n        public string DerivedMethodWithRoute()\n        {\n            return \"DerivedMethodWithRoute\";\n        }\n\n        public override string BaseVirtualMethodWithRoute()\n        {\n            return \"BaseVirtualMethodWithRoute_Derived\";\n        }\n\n        [Route(\"BaseVirtualMethodToBeOverridenWithRoute_Derived\")]\n        public override string BaseVirtualMethodToBeOverridenWithRoute()\n        {\n            return \"BaseVirtualMethodToBeOverridenWithRoute_Derived\";\n        }\n\n        [Route(\"BaseVirtualMethodWithRouteToBeOverridenWithRoute_Derived\")]\n        public override string BaseVirtualMethodWithRouteToBeOverridenWithRoute()\n        {\n            return \"BaseVirtualMethodWithRouteToBeOverridenWithRoute_Derived\";\n        }\n    }\n\n    public class DerivedFromBaseRouteController : BaseRouteController\n    {\n        [Route(\"DerivedMethodWithRoute\")]\n        public string DerivedMethodWithRoute()\n        {\n            return \"DerivedMethodWithRoute\";\n        }\n\n        public override string BaseVirtualMethodWithRoute()\n        {\n            return \"BaseVirtualMethodWithRoute_Derived\";\n        }\n\n        [Route(\"BaseVirtualMethodToBeOverridenWithRoute_Derived\")]\n        public override string BaseVirtualMethodToBeOverridenWithRoute()\n        {\n            return \"BaseVirtualMethodToBeOverridenWithRoute_Derived\";\n        }\n\n        [Route(\"BaseVirtualMethodWithRouteToBeOverridenWithRoute_Derived\")]\n        public override string BaseVirtualMethodWithRouteToBeOverridenWithRoute()\n        {\n            return \"BaseVirtualMethodWithRouteToBeOverridenWithRoute_Derived\";\n        }\n    }\n\n    [Route(\"derivedwithroute/{action}\")]\n    public class DerivedFromBaseRouteWithRouteController : BaseRouteController\n    {\n    }\n\n    #endregion\n\n    public class MethodOverloadsController : ResponseStoringController\n    {\n        [Route(\"Get1\")]\n        public string Get()\n        {\n            return \"Get1\";\n        }\n\n        [Route(\"Get2\")]\n        public string Get(int id)\n        {\n            return \"Get2_\" + id;\n        }\n\n        [Route(\"GetAmbiguous\")]\n        public string GetAmbiguous(int id)\n        {\n            return \"GetAmbiguous_Int\";\n        }\n\n        [Route(\"GetAmbiguous\")]\n        public string GetAmbiguous(string id)\n        {\n            return \"GetAmbiguous_String\";\n        }\n    }\n\n    public class MixedRoutingController : ResponseStoringController\n    {\n        public string GetWithoutRoute()\n        {\n            return \"GetWithoutRoute\";\n        }\n\n        [Route(\"GetWithRoute\")]\n        public string GetWithRoute()\n        {\n            return \"GetWithRoute\";\n        }\n    }\n\n    [RoutePrefix(\"prefix\")]\n    public class MixedRoutingWithPrefixController : ResponseStoringController\n    {\n        public string GetWithoutRoute()\n        {\n            return \"GetWithoutRoute\";\n        }\n\n        [Route(\"GetWithRoute\")]\n        public string GetWithRoute()\n        {\n            return \"GetWithRoute\";\n        }\n    }\n\n    [Route(\"{action}\")]\n    public class MixedRoutingWithRouteonController : ResponseStoringController\n    {\n        public string GetWithoutRoute()\n        {\n            return \"GetWithoutRoute\";\n        }\n\n        [Route(\"GetWithRoute\")]\n        public string GetWithRoute()\n        {\n            return \"GetWithRoute\";\n        }\n    }\n\n    [Route(\"{action}\")]\n    public class ActionMethodSelectorsController : ResponseStoringController\n    {\n        public string Action1()\n        {\n            return \"Action1()\";\n        }\n\n        // This is a 'better' action than Action1() because it has a selector\n        [BoolActionMethodSelector(true)]\n        public string Action1(int id = 0)\n        {\n            return \"Action1(int)\";\n        }\n\n        // All ActionMethodSelectors need to return true\n        [BoolActionMethodSelector(true)]\n        [BoolActionMethodSelector(false)]\n        public string DoesntRun()\n        {\n            return \"DoesntRun\";\n        }\n    }\n\n    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)]\n    public class BoolActionMethodSelectorAttribute : ActionMethodSelectorAttribute\n    {\n        public BoolActionMethodSelectorAttribute(bool value)\n        {\n            Value = value;\n        }\n\n        private bool Value\n        {\n            get;\n            set;\n        }\n\n        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)\n        {\n            return Value;\n        }\n    }\n\n    [Route(\"{action}\")]\n    public class ActionNameSelectorsController : ResponseStoringController\n    {\n        [StringActionNameSelector(\"SpecialName\")]\n        public string Action1()\n        {\n            return \"Action1()\";\n        }\n\n        // This is 'better' because it has an action selector also\n        [HttpGet]\n        [StringActionNameSelector(\"SpecialName\")]\n        public string Action2()\n        {\n            return \"Action2()\";\n        }\n\n        [StringActionNameSelector(\"AnotherSpecialName\")]\n        public string Action3()\n        {\n            return \"Action3()\";\n        }\n    }\n\n    /// <summary>\n    /// A 'custom' implementation similar to ActionNameAttribute - using a custom attribute for tests\n    /// because ActionNameAttribute is special cased by the ActionDescriptor class.\n    /// </summary>\n    public class StringActionNameSelectorAttribute : ActionNameSelectorAttribute\n    {\n        public StringActionNameSelectorAttribute(string actionName)\n        {\n            ActionName = actionName;\n        }\n\n        private string ActionName\n        {\n            get;\n            set;\n        }\n\n        public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)\n        {\n            return String.Equals(actionName, ActionName, StringComparison.OrdinalIgnoreCase);\n        }\n    }\n\n    [Route(\"{action}/{id?}\")]\n    public class OptionalParameterController : ResponseStoringController\n    {\n        public string Create()\n        {\n            return \"Create()\";\n        }\n    }\n\n    namespace ControllersWithTheSameName\n    {\n        namespace NS1\n        {\n            [Route(\"Home1/{action}\")]\n            public class HomeController : ResponseStoringController\n            {\n                public ActionResult Index()\n                {\n                    return Content(\"Home1.Index()\");\n                }\n            }\n        }\n\n        namespace NS2\n        {\n            [Route(\"Home2/{action}\")]\n            public class HomeController : ResponseStoringController\n            {\n                public ActionResult Index()\n                {\n                    return Content(\"Home2.Index()\");\n                }\n            }\n        }\n    }\n\n    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]\n    public class CustomizedRoutePrefixAttribute : Attribute, IRoutePrefix\n    {\n        public CustomizedRoutePrefixAttribute(Type controller)\n        {\n            if (controller == null)\n            {\n                throw Error.ArgumentNull(\"prefix\");\n            }\n\n            if (controller.Equals(typeof(ControllersWithCustomizedRoutePrefixAttribute.NS1.HomeController)))\n            {\n                Prefix = \"NS1Home\";\n            }\n            else if (controller.Equals(typeof(ControllersWithCustomizedRoutePrefixAttribute.NS2.AccountController)))\n            {\n                Prefix = \"NS2Account\";\n            }\n            else\n            {\n                Prefix = \"Default\";\n            }\n        }\n\n        public string Prefix { get; private set; }\n    }\n\n    public class ExtendedRoutePrefixAttribute : RoutePrefixAttribute\n    {\n    }\n\n    namespace ControllersWithCustomizedRoutePrefixAttribute\n    {\n        namespace NS1\n        {\n            [CustomizedRoutePrefix(typeof(HomeController))]\n            public class HomeController : ResponseStoringController\n            {\n                [Route(\"Introduction\")]\n                public ActionResult Index()\n                {\n                    return Content(\"Home.Index()\");\n                }\n            }\n        }\n\n        namespace NS2\n        {\n            [CustomizedRoutePrefix(typeof(AccountController))]\n            public class AccountController : ResponseStoringController\n            {\n                [Route(\"PeopleList\")]\n                public ActionResult Index()\n                {\n                    return Content(\"Account.Index()\");\n                }\n            }\n        }\n\n        namespace NS3\n        {\n            [CustomizedRoutePrefix(typeof(OtherController))]\n            public class OtherController : ResponseStoringController\n            {\n                [Route(\"Unknown\")]\n                public ActionResult Index()\n                {\n                    return Content(\"Default.Index()\");\n                }\n            }\n        }\n\n        namespace Invalid\n        {\n            [CustomizedRoutePrefix(typeof(HomeController))]\n            [RoutePrefix(\"InvalidExtraPrefix\")]\n            public class HomeController : ResponseStoringController\n            {\n                [Route(\"Introduction\")]\n                public ActionResult Index()\n                {\n                    return Content(\"Home.Index()\");\n                }\n            }\n\n            [ExtendedRoutePrefixAttribute]\n            public class AccountController : ResponseStoringController\n            {\n                [Route(\"AnyRoute\")]\n                public ActionResult Index()\n                {\n                    return Content(\"Account.Index()\");\n                }\n            }\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Mvc.Test/Routing/DefaultDirectRouteProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Web.Mvc;\nusing System.Web.Mvc.Async;\nusing System.Web.Mvc.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Routing\n{\n    public class DefaultDirectRouteProviderTest\n    {\n        [Fact]\n        public void CreateRouteEntry_IfDirectRouteProviderReturnsNull_Throws()\n        {\n            // Arrange\n            string areaPrefix = null;\n            string controllerPrefix = null;\n            IDirectRouteFactory factory = CreateStubRouteFactory(null);\n            ControllerDescriptor controllerDescriptor = CreateStubControllerDescriptor(\"IgnoreController\");\n            ActionDescriptor actionDescriptor = CreateStubActionDescriptor(controllerDescriptor, \"IgnoreAction\");\n            IReadOnlyCollection<ActionDescriptor> actions = new ActionDescriptor[] { actionDescriptor };\n            IInlineConstraintResolver constraintResolver =\n                new Mock<IInlineConstraintResolver>(MockBehavior.Strict).Object;\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(() => DefaultDirectRouteProvider.CreateRouteEntry(areaPrefix,\n                controllerPrefix, factory, actions, constraintResolver, targetIsAction: false),\n                \"IDirectRouteFactory.CreateRoute must not return null.\");\n        }\n\n        [Fact]\n        public void CreateRouteEntry_IfDirectRouteProviderReturnsRouteWithoutActionDescriptors_Throws()\n        {\n            // Arrange\n            string areaPrefix = null;\n            string controllerPrefix = null;\n            Route route = new Route(url: null, routeHandler: null);\n            Assert.Null(route.GetTargetActionDescriptors()); // Guard\n            RouteEntry entry = new RouteEntry(name: null, route: route);\n            IDirectRouteFactory factory = CreateStubRouteFactory(entry);\n            ControllerDescriptor controllerDescriptor = CreateStubControllerDescriptor(\"IgnoreController\");\n            ActionDescriptor actionDescriptor = CreateStubActionDescriptor(controllerDescriptor, \"IgnoreAction\");\n            IReadOnlyCollection<ActionDescriptor> actions = new ActionDescriptor[] { actionDescriptor };\n            IInlineConstraintResolver constraintResolver =\n                new Mock<IInlineConstraintResolver>(MockBehavior.Strict).Object;\n\n            // Act & Assert\n            string expectedMessage = \"The route does not have any associated action descriptors. Routing requires \" +\n                \"that each direct route map to a non-empty set of actions.\";\n            Assert.Throws<InvalidOperationException>(() => DefaultDirectRouteProvider.CreateRouteEntry(areaPrefix,\n                controllerPrefix, factory, actions, constraintResolver, targetIsAction: false), expectedMessage);\n        }\n\n        [Fact]\n        public void CreateRouteEntry_IfDirectRouteProviderReturnsRouteWithEmptyActionDescriptors_Throws()\n        {\n            // Arrange\n            string areaPrefix = null;\n            string controllerPrefix = null;\n            Route route = new Route(url: null, routeHandler: null);\n            route.DataTokens = new RouteValueDictionary();\n            route.DataTokens.Add(RouteDataTokenKeys.Actions, new ActionDescriptor[0]);\n            ActionDescriptor[] originalActions = route.GetTargetActionDescriptors();\n            Assert.NotNull(originalActions); // Guard\n            Assert.Empty(originalActions); // Guard\n            RouteEntry entry = new RouteEntry(name: null, route: route);\n            IDirectRouteFactory factory = CreateStubRouteFactory(entry);\n            ControllerDescriptor controllerDescriptor = CreateStubControllerDescriptor(\"IgnoreController\");\n            ActionDescriptor actionDescriptor = CreateStubActionDescriptor(controllerDescriptor, \"IgnoreAction\");\n            IReadOnlyCollection<ActionDescriptor> actions = new ActionDescriptor[] { actionDescriptor };\n            IInlineConstraintResolver constraintResolver =\n                new Mock<IInlineConstraintResolver>(MockBehavior.Strict).Object;\n\n            // Act & Assert\n            string expectedMessage = \"The route does not have any associated action descriptors. Routing requires \" +\n                \"that each direct route map to a non-empty set of actions.\";\n            Assert.Throws<InvalidOperationException>(() => DefaultDirectRouteProvider.CreateRouteEntry(areaPrefix,\n                controllerPrefix, factory, actions, constraintResolver, targetIsAction: false), expectedMessage);\n        }\n\n        [Fact]\n        public void CreateRouteEntry_IfDirectRouteProviderReturnsRouteWithHandler_Throws()\n        {\n            // Arrange\n            string areaPrefix = null;\n            string controllerPrefix = null;\n            ControllerDescriptor controllerDescriptor = CreateStubControllerDescriptor(\"IgnoreController\");\n            ActionDescriptor actionDescriptor = CreateStubActionDescriptor(controllerDescriptor, \"IgnoreAction\");\n            Route route = new Route(url: null, routeHandler: null);\n            route.DataTokens = new RouteValueDictionary();\n            route.DataTokens.Add(RouteDataTokenKeys.Actions, new ActionDescriptor[] { actionDescriptor });\n            route.RouteHandler = new Mock<IRouteHandler>(MockBehavior.Strict).Object;\n            ActionDescriptor[] originalActions = route.GetTargetActionDescriptors();\n            RouteEntry entry = new RouteEntry(name: null, route: route);\n            IDirectRouteFactory factory = CreateStubRouteFactory(entry);\n            IReadOnlyCollection<ActionDescriptor> actions = new ActionDescriptor[] { actionDescriptor };\n            IInlineConstraintResolver constraintResolver =\n                new Mock<IInlineConstraintResolver>(MockBehavior.Strict).Object;\n\n            // Act & Assert\n            string expectedMessage = \"Direct routing does not support per-route route handlers.\";\n            Assert.Throws<InvalidOperationException>(() => DefaultDirectRouteProvider.CreateRouteEntry(areaPrefix,\n                controllerPrefix, factory, actions, constraintResolver, targetIsAction: false), expectedMessage);\n        }\n\n        private static ActionDescriptor CreateStubActionDescriptor(ControllerDescriptor controllerDescriptor, string actionName)\n        {\n            Mock<ActionDescriptor> mock = new Mock<ActionDescriptor>(MockBehavior.Strict);\n            mock.SetupGet(d => d.ControllerDescriptor).Returns(controllerDescriptor);\n            mock.SetupGet(d => d.ActionName).Returns(actionName);\n            return mock.Object;\n        }\n\n        private static ControllerDescriptor CreateStubControllerDescriptor(string controllerName)\n        {\n            Mock<ControllerDescriptor> mock = new Mock<ControllerDescriptor>(MockBehavior.Strict);\n            mock.SetupGet(d => d.ControllerName).Returns(controllerName);\n            return mock.Object;\n        }\n\n        private static IDirectRouteFactory CreateStubRouteFactory(RouteEntry entry)\n        {\n            Mock<IDirectRouteFactory> mock = new Mock<IDirectRouteFactory>(MockBehavior.Strict);\n            mock.Setup(p => p.CreateRoute(It.IsAny<DirectRouteFactoryContext>())).Returns(entry);\n            return mock.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Routing/DirectRouteCandidateTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq.Expressions;\nusing System.Reflection;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Routing.Test\n{\n    public class DirectRouteCandidateTest\n    {\n        [Fact]\n        public void SelectBestCandidate_ReturnsNullOnEmptyList()\n        {\n            // Arrange & Act\n            DirectRouteCandidate actual = DirectRouteCandidate.SelectBestCandidate(new List<DirectRouteCandidate>(), new ControllerContext());\n\n            // Assert\n            Assert.Null(actual);\n        }\n\n        [Fact]\n        public void SelectBestCandidate_SelectByActionName()\n        {\n            // Arrange\n            Type controllerType = typeof(TestController);\n            ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerType);\n\n            RouteData routeData = new RouteData();\n            routeData.Values[\"action\"] = \"Action1\";\n\n            DirectRouteCandidate better = new DirectRouteCandidate()\n            {\n                ActionDescriptor = ActionDescriptorFrom<TestController>(c => c.Action1()),\n                ControllerDescriptor = controllerDescriptor,\n                RouteData = routeData,\n            };\n\n            DirectRouteCandidate worse = new DirectRouteCandidate()\n            {\n                ActionDescriptor = ActionDescriptorFrom<TestController>(c => c.Action2()),\n                ControllerDescriptor = controllerDescriptor,\n                RouteData = routeData,\n            };\n\n            List<DirectRouteCandidate> candidates = new List<DirectRouteCandidate>()\n            {\n                better, \n                worse,\n            };\n\n            // Act\n            DirectRouteCandidate actual = DirectRouteCandidate.SelectBestCandidate(candidates, new ControllerContext());\n\n            // Assert\n            Assert.Same(better, actual);\n        }\n\n        [Fact]\n        public void SelectBestCandidate_SelectByActionNameSelector_UsesActionName()\n        {\n            // Arrange\n            Type controllerType = typeof(TestController);\n            ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerType);\n\n            RouteData routeData = new RouteData();\n            routeData.Values[\"action\"] = \"Action1\";\n\n            DirectRouteCandidate better = new DirectRouteCandidate()\n            {\n                ActionDescriptor = ActionDescriptorFrom<TestController>(c => c.Action1()),\n                ActionNameSelectors = new ActionNameSelector[] { (context, name) => name == \"Action1\" },\n                ControllerDescriptor = controllerDescriptor,\n                RouteData = routeData,\n            };\n\n            DirectRouteCandidate worse = new DirectRouteCandidate()\n            {\n                ActionDescriptor = ActionDescriptorFrom<TestController>(c => c.Action2()),\n                ActionNameSelectors = new ActionNameSelector[] { (context, name) => name == \"Action2\" },\n                ControllerDescriptor = controllerDescriptor,\n                RouteData = routeData,\n            };\n\n            List<DirectRouteCandidate> candidates = new List<DirectRouteCandidate>()\n            {\n                better, \n                worse,\n            };\n\n            // Act\n            DirectRouteCandidate actual = DirectRouteCandidate.SelectBestCandidate(candidates, new ControllerContext());\n\n            // Assert\n            Assert.Same(better, actual);\n        }\n\n        [Fact]\n        public void SelectBestCandidate_SelectByActionNameSelector_RouteProvidesName()\n        {\n            // Arrange\n            Type controllerType = typeof(TestController);\n            ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerType);\n\n            RouteData routeData = new RouteData();\n            routeData.Values[\"action\"] = \"Action1\";\n\n            DirectRouteCandidate better = new DirectRouteCandidate()\n            {\n                ActionDescriptor = ActionDescriptorFrom<TestController>(c => c.Action2()),\n                ActionNameSelectors = new ActionNameSelector[] { (context, name) => name == \"Action1\" },\n                ControllerDescriptor = controllerDescriptor,\n                RouteData = routeData,\n            };\n\n            DirectRouteCandidate worse = new DirectRouteCandidate()\n            {\n                ActionDescriptor = ActionDescriptorFrom<TestController>(c => c.Action2()),\n                ControllerDescriptor = controllerDescriptor,\n                RouteData = routeData,\n            };\n\n            List<DirectRouteCandidate> candidates = new List<DirectRouteCandidate>()\n            {\n                better, \n                worse,\n            };\n\n            // Act\n            DirectRouteCandidate actual = DirectRouteCandidate.SelectBestCandidate(candidates, new ControllerContext());\n\n            // Assert\n            Assert.Same(better, actual);\n        }\n\n        [Fact]\n        public void SelectBestCandidate_ExcludesFailedActionSelectors()\n        {\n            // Arrange\n            Type controllerType = typeof(TestController);\n            ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerType);\n\n            DirectRouteCandidate better = new DirectRouteCandidate()\n            {\n                ActionDescriptor = ActionDescriptorFrom<TestController>(c => c.Action1()),\n                ControllerDescriptor = controllerDescriptor,\n                Order = 1,\n                RouteData = new RouteData(),\n            };\n\n            DirectRouteCandidate worse = new DirectRouteCandidate()\n            {\n                ActionDescriptor = ActionDescriptorFrom<TestController>(c => c.Action1()),\n                ActionSelectors = new ActionSelector[] { (context) => false, },\n                ControllerDescriptor = controllerDescriptor,\n                Order = 0,\n                RouteData = new RouteData(),\n            };\n\n            List<DirectRouteCandidate> candidates = new List<DirectRouteCandidate>()\n            {\n                better, \n                worse,\n            };\n\n            // Act\n            DirectRouteCandidate actual = DirectRouteCandidate.SelectBestCandidate(candidates, new ControllerContext());\n\n            // Assert\n            Assert.Same(better, actual);\n        }\n\n        [Fact]\n        public void SelectBestCandidate_ExcludesFailedActionSelectors_NoneValid()\n        {\n            // Arrange\n            Type controllerType = typeof(TestController);\n            ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerType);\n\n            DirectRouteCandidate better = new DirectRouteCandidate()\n            {\n                ActionDescriptor = ActionDescriptorFrom<TestController>(c => c.Action1()),\n                ActionSelectors = new ActionSelector[] { (context) => false, },\n                ControllerDescriptor = controllerDescriptor,\n                Order = 0,\n                RouteData = new RouteData(),\n            };\n\n            DirectRouteCandidate worse = new DirectRouteCandidate()\n            {\n                ActionDescriptor = ActionDescriptorFrom<TestController>(c => c.Action1()),\n                ActionSelectors = new ActionSelector[] { (context) => false, },\n                ControllerDescriptor = controllerDescriptor,\n                Order = 1,\n                RouteData = new RouteData(),\n            };\n\n            List<DirectRouteCandidate> candidates = new List<DirectRouteCandidate>()\n            {\n                better, \n                worse,\n            };\n\n            // Act\n            DirectRouteCandidate actual = DirectRouteCandidate.SelectBestCandidate(candidates, new ControllerContext());\n\n            // Assert\n            Assert.Null(actual);\n        }\n\n        [Fact]\n        public void SelectBestCandidate_ChoosesByActionSelector()\n        {\n            // Arrange\n            Type controllerType = typeof(TestController);\n            ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerType);\n\n            DirectRouteCandidate better = new DirectRouteCandidate()\n            {\n                ActionDescriptor = ActionDescriptorFrom<TestController>(c => c.Action1()),\n                ActionSelectors = new ActionSelector[] { (context) => true },\n                ControllerDescriptor = controllerDescriptor,\n                RouteData = new RouteData(),\n            };\n\n            DirectRouteCandidate worse = new DirectRouteCandidate()\n            {\n                ActionDescriptor = ActionDescriptorFrom<TestController>(c => c.Action1()),\n                ControllerDescriptor = controllerDescriptor,\n                RouteData = new RouteData(),\n            };\n\n            List<DirectRouteCandidate> candidates = new List<DirectRouteCandidate>()\n            {\n                better, \n                worse,\n            };\n\n            // Act\n            DirectRouteCandidate actual = DirectRouteCandidate.SelectBestCandidate(candidates, new ControllerContext());\n\n            // Assert\n            Assert.Same(better, actual);\n        }\n\n        [Fact]\n        public void SelectBestCandidate_ChoosesByOrder()\n        {\n            // Arrange\n            Type controllerType = typeof(TestController);\n            ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerType);\n\n            DirectRouteCandidate better = new DirectRouteCandidate()\n            {\n                ActionDescriptor = ActionDescriptorFrom<TestController>(c => c.Action1()),\n                ControllerDescriptor = controllerDescriptor,\n                Order = 0,\n                RouteData = new RouteData(),\n            };\n\n            DirectRouteCandidate worse = new DirectRouteCandidate()\n            {\n                ActionDescriptor = ActionDescriptorFrom<TestController>(c => c.Action1()),\n                ControllerDescriptor = controllerDescriptor,\n                Order = 1,\n                RouteData = new RouteData(),\n            };\n\n            List<DirectRouteCandidate> candidates = new List<DirectRouteCandidate>()\n            {\n                better, \n                worse,\n            };\n\n            // Act\n            DirectRouteCandidate actual = DirectRouteCandidate.SelectBestCandidate(candidates, new ControllerContext());\n\n            // Assert\n            Assert.Same(better, actual);\n        }\n\n        [Fact]\n        public void SelectBestCandidate_ChoosesByOrder_WithActionSelectors()\n        {\n            // Arrange\n            Type controllerType = typeof(TestController);\n            ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerType);\n\n            DirectRouteCandidate better = new DirectRouteCandidate()\n            {\n                ActionDescriptor = ActionDescriptorFrom<TestController>(c => c.Action1()),\n                ActionSelectors = new ActionSelector[] { (context) => true },\n                ControllerDescriptor = controllerDescriptor,\n                Order = 0,\n                RouteData = new RouteData(),\n            };\n\n            DirectRouteCandidate worse = new DirectRouteCandidate()\n            {\n                ActionDescriptor = ActionDescriptorFrom<TestController>(c => c.Action1()),\n                ActionSelectors = new ActionSelector[] { (context) => true },\n                ControllerDescriptor = controllerDescriptor,\n                Order = 1,\n                RouteData = new RouteData(),\n            };\n\n            List<DirectRouteCandidate> candidates = new List<DirectRouteCandidate>()\n            {\n                better, \n                worse,\n            };\n\n            // Act\n            DirectRouteCandidate actual = DirectRouteCandidate.SelectBestCandidate(candidates, new ControllerContext());\n\n            // Assert\n            Assert.Same(better, actual);\n        }\n\n        [Fact]\n        public void SelectBestCandidate_ChoosesByOrder_AfterActionSelectors()\n        {\n            // Arrange\n            Type controllerType = typeof(TestController);\n            ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerType);\n\n            DirectRouteCandidate better = new DirectRouteCandidate()\n            {\n                ActionDescriptor = ActionDescriptorFrom<TestController>(c => c.Action1()),\n                ActionSelectors = new ActionSelector[] { (context) => true },\n                ControllerDescriptor = controllerDescriptor,\n                Order = 1,\n                RouteData = new RouteData(),\n            };\n\n            DirectRouteCandidate worse = new DirectRouteCandidate()\n            {\n                ActionDescriptor = ActionDescriptorFrom<TestController>(c => c.Action1()),\n                ActionSelectors = new ActionSelector[] { (context) => false },\n                ControllerDescriptor = controllerDescriptor,\n                Order = 0,\n                RouteData = new RouteData(),\n            };\n\n            List<DirectRouteCandidate> candidates = new List<DirectRouteCandidate>()\n            {\n                better, \n                worse,\n            };\n\n            // Act\n            DirectRouteCandidate actual = DirectRouteCandidate.SelectBestCandidate(candidates, new ControllerContext());\n\n            // Assert\n            Assert.Same(better, actual);\n        }\n\n        [Fact]\n        public void SelectBestCandidate_ChoosesByPrecedence()\n        {\n            // Arrange\n            Type controllerType = typeof(TestController);\n            ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerType);\n\n            DirectRouteCandidate better = new DirectRouteCandidate()\n            {\n                ActionDescriptor = ActionDescriptorFrom<TestController>(c => c.Action1()),\n                ControllerDescriptor = controllerDescriptor,\n                Order = 0,\n                Precedence = 1,\n                RouteData = new RouteData(),\n            };\n\n            DirectRouteCandidate worse = new DirectRouteCandidate()\n            {\n                ActionDescriptor = ActionDescriptorFrom<TestController>(c => c.Action1()),\n                ControllerDescriptor = controllerDescriptor,\n                Order = 0,\n                Precedence = 2,\n                RouteData = new RouteData(),\n            };\n\n            List<DirectRouteCandidate> candidates = new List<DirectRouteCandidate>()\n            {\n                better, \n                worse,\n            };\n\n            // Act\n            DirectRouteCandidate actual = DirectRouteCandidate.SelectBestCandidate(candidates, new ControllerContext());\n\n            // Assert\n            Assert.Same(better, actual);\n        }\n\n        [Fact]\n        public void SelectBestCandidate_ChoosesByPrecedence_WithActionSelectors()\n        {\n            // Arrange\n            Type controllerType = typeof(TestController);\n            ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerType);\n\n            DirectRouteCandidate better = new DirectRouteCandidate()\n            {\n                ActionDescriptor = ActionDescriptorFrom<TestController>(c => c.Action1()),\n                ActionSelectors = new ActionSelector[] { (context) => true },\n                ControllerDescriptor = controllerDescriptor,\n                Order = 0,\n                Precedence = 1,\n                RouteData = new RouteData(),\n            };\n\n            DirectRouteCandidate worse = new DirectRouteCandidate()\n            {\n                ActionDescriptor = ActionDescriptorFrom<TestController>(c => c.Action1()),\n                ActionSelectors = new ActionSelector[] { (context) => true },\n                ControllerDescriptor = controllerDescriptor,\n                Order = 0,\n                Precedence = 2,\n                RouteData = new RouteData(),\n            };\n\n            List<DirectRouteCandidate> candidates = new List<DirectRouteCandidate>()\n            {\n                better, \n                worse,\n            };\n\n            // Act\n            DirectRouteCandidate actual = DirectRouteCandidate.SelectBestCandidate(candidates, new ControllerContext());\n\n            // Assert\n            Assert.Same(better, actual);\n        }\n\n        [Fact]\n        public void SelectBestCandidate_Ambiguity()\n        {\n            // Arrange\n            Type controllerType = typeof(TestController);\n            ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerType);\n\n            DirectRouteCandidate candidate1 = new DirectRouteCandidate()\n            {\n                ActionDescriptor = new ReflectedActionDescriptor(controllerType.GetMethod(\"Action1\"), \"Action1\", controllerDescriptor),\n                ActionSelectors = new ActionSelector[] { (context) => true },\n                ControllerDescriptor = controllerDescriptor,\n                Order = 0,\n                Precedence = 1,\n                RouteData = new RouteData(),\n            };\n\n            DirectRouteCandidate candidate2 = new DirectRouteCandidate()\n            {\n                ActionDescriptor = new ReflectedActionDescriptor(controllerType.GetMethod(\"Action2\"), \"Action2\", controllerDescriptor),\n                ActionSelectors = new ActionSelector[] { (context) => true },\n                ControllerDescriptor = controllerDescriptor,\n                Order = 0,\n                Precedence = 1,\n                RouteData = new RouteData(),\n            };\n\n            List<DirectRouteCandidate> candidates = new List<DirectRouteCandidate>()\n            {\n                candidate1, \n                candidate2,\n            };\n\n            string message = \n                \"The current request is ambiguous between the following action methods:\" + Environment.NewLine +\n                \"Void Action1() on type System.Web.Mvc.Routing.Test.DirectRouteCandidateTest+TestController\" + Environment.NewLine +\n                \"Void Action2() on type System.Web.Mvc.Routing.Test.DirectRouteCandidateTest+TestController\";\n\n            // Act & Assert\n            Assert.Throws<AmbiguousMatchException>(() => DirectRouteCandidate.SelectBestCandidate(candidates, new ControllerContext()), message);\n        }\n\n        private static ActionDescriptor ActionDescriptorFrom<T>(Expression<Action<T>> methodCall)\n        {\n            var method = ((MethodCallExpression)methodCall.Body).Method;\n\n            var controllerType = method.DeclaringType;\n            var controllerDescriptor = new ReflectedControllerDescriptor(controllerType);\n\n            return new ReflectedActionDescriptor(method, method.Name, controllerDescriptor);\n        }\n\n        private class TestController : Controller\n        {\n            [Route(\"cool\")]\n            public void Action1()\n            {\n            }\n\n            [Route(\"cool\")]\n            public void Action2()\n            {\n            }\n        }\n\n        [Route(\"controller/{action\")]\n        private class ClassLevelTestController : Controller\n        {\n            public void Action1()\n            {\n            }\n\n            public void Action2()\n            {\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Routing/DirectRouteTestHelpers.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing System.Linq.Expressions;\nusing System.Web.Mvc;\nusing System.Web.Mvc.Async;\nusing System.Web.Mvc.Routing;\n\nnamespace System.Web.Routing.Test\n{\n    internal static class DirectRouteTestHelpers\n    {\n        public static RouteCollectionRoute BuildDirectRouteFromMethod<T>(Expression<Action<T>> methodCall)\n        {\n            SubRouteCollection collector = new SubRouteCollection();\n            AddDirectRouteFromMethod(collector, methodCall);\n            return new RouteCollectionRoute(collector);\n        }\n\n        public static void AddDirectRouteFromMethod<T>(SubRouteCollection collector, Expression<Action<T>> methodCall)\n        {\n            var method = ((MethodCallExpression)methodCall.Body).Method;\n            var attributes = method.GetCustomAttributes(false).OfType<IRouteInfoProvider>();\n\n            var controllerDescriptor = new ReflectedAsyncControllerDescriptor(method.DeclaringType);\n            var actionDescriptor = new ReflectedActionDescriptor(method, method.Name, controllerDescriptor);\n\n            foreach (var attribute in attributes)\n            {\n                var subRoute = new Route(attribute.Template, routeHandler: null);\n                subRoute.SetTargetActionDescriptors(new ActionDescriptor[] { actionDescriptor });\n                collector.Add(new RouteEntry(null, subRoute));\n            }\n        }\n\n        public static RouteCollectionRoute BuildDirectRouteFromController<T>()\n        {\n            SubRouteCollection collector = new SubRouteCollection();\n            AddDirectRouteFromController<T>(collector);\n            return new RouteCollectionRoute(collector);\n        }\n\n        public static void AddDirectRouteFromController<T>(SubRouteCollection collector)\n        {\n            var controllerType = typeof(T);\n            AttributeRoutingMapper.AddRouteEntries(\n                collector, \n                new Type[] { controllerType },\n                new DefaultInlineConstraintResolver(),\n                new DefaultDirectRouteProvider());\n        }\n\n        public static void AddDirectRouteMatches(this RouteData routeData, Func<RouteBase, RouteData, bool> selector = null)\n        {\n            RouteCollectionRoute route = (RouteCollectionRoute)routeData.Route;\n\n            List<RouteData> matches = new List<RouteData>();\n            foreach (var subRoute in route)\n            {\n                RouteData match = new RouteData() { Route = subRoute };\n                bool isMatch = selector == null ? true : selector(subRoute, match);\n                if (isMatch)\n                {\n                    matches.Add(match);\n                }\n            }\n\n            if (matches.Any())\n            {\n                routeData.SetDirectRouteMatches(matches);\n            }\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Mvc.Test/Routing/RouteAttributeTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Routing\n{\n    public class RouteAttributeTests\n    {\n        [Fact]\n        public void Template_EmptyString_Ok()\n        {\n            new RouteAttribute(\"\");\n        }\n\n        [Fact]\n        public void Template_Null_NotOk()\n        {\n            Assert.Throws<ArgumentNullException>(() => new RouteAttribute(null));\n        }\n\n        [Fact]\n        public void EmptyCtor_Is_EmptyString()\n        {\n            RouteAttribute attr = new RouteAttribute();\n\n            Assert.Equal(String.Empty, attr.Template);\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Mvc.Test/Routing/RouteCollectionAttributeRoutingExtensionsTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Mvc;\nusing System.Web.Mvc.Routing;\nusing System.Web.Mvc.Routing.Constraints;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Routing\n{\n    public class RouteCollectionAttributeRoutingExtensionsTests\n    {\n        [Fact]\n        public void MapMvcAttributeRoutes_MapRouteAttributes()\n        {\n            // Arrange\n            var controllerTypes = new[] { typeof(SimpleRoutingController) };\n            var routes = new RouteCollection();\n\n            // Act\n            AttributeRoutingMapper.MapAttributeRoutes(routes, controllerTypes);\n\n            // Assert\n            var expectedResults = new List<Tuple<string, string>>\n             {\n                 new Tuple<string, string>(\"getme\", \"GetMe\"),\n                 new Tuple<string, string>(\"postme\", \"PostMe\"),\n                 new Tuple<string, string>(\"getorpostme\", \"GetOrPostMe\"),\n                 new Tuple<string, string>(\"routeme\", \"RouteMe\"),\n                 new Tuple<string, string>(\"once\", \"FoolMe\"),\n                 new Tuple<string, string>(\"twice\", \"FoolMe\"),\n                 new Tuple<string, string>(\"twice\", \"FoolMe\"),\n             };\n\n            foreach (var expected in expectedResults)\n            {\n                var url = expected.Item1;\n                var methodName = expected.Item2;\n\n                var attributeRoutes = GetAttributeRoutes(routes);\n                Route route = attributeRoutes.Cast<Route>().Single(r => r.Url == url);\n                Assert.Equal(methodName, Assert.Single(route.GetTargetActionDescriptors()).ActionName);\n            }\n        }\n\n        [Fact]\n        public void MapMvcAttributeRoutes_CustomConstraintResolver()\n        {\n            // Arrange\n            var controllerTypes = new[] { typeof(FruitConstraintController) };\n            var routes = new RouteCollection();\n\n            // Act\n            AttributeRoutingMapper.MapAttributeRoutes(routes, controllerTypes, new FruitConstraintResolver());\n\n            // Assert\n            var attributeRoutes = GetAttributeRoutes(routes);\n            Assert.Equal(1, attributeRoutes.Count);\n            Route route = (Route)attributeRoutes.Single();\n\n            Assert.Equal(\"fruits/{apple}\", route.Url);\n            Assert.IsAssignableFrom<FruitConstraint>(route.Constraints[\"apple\"]);\n        }\n\n        [Fact]\n        public void MapMvcAttributeRoutes_WithInlineConstraints_ParseConstraintsDefaultsAndOptionals()\n        {\n            // Arrange\n            var controllerTypes = new[] { typeof(SimpleRoutingController) };\n            var routes = new RouteCollection();\n\n            // Act\n            AttributeRoutingMapper.MapAttributeRoutes(routes, controllerTypes);\n\n            // Assert\n            var attributeRoutes = GetAttributeRoutes(routes);\n            Route route = attributeRoutes.Cast<Route>().Single(r => r.GetTargetActionDescriptors().Single().ActionName == \"Parameterized\");\n            Assert.NotNull(route);\n\n            Assert.Equal(\"i/{have}/{id}/{defaultsto}/{name}\", route.Url);\n            Assert.IsAssignableFrom<IntRouteConstraint>(route.Constraints[\"id\"]);\n            Assert.Equal(\"VAL\", route.Defaults[\"defaultsto\"]);\n            Assert.Equal(\"\", route.Defaults[\"name\"].ToString());\n        }\n\n        [Fact]\n        public void MapMvcAttributeRoutes_WithPrefixedController()\n        {\n            // Arrange\n            var controllerTypes = new[] { typeof(PrefixedController) };\n            var routes = new RouteCollection();\n\n            // Act\n            AttributeRoutingMapper.MapAttributeRoutes(routes, controllerTypes);\n\n            // Assert\n            var attributeRoutes = GetAttributeRoutes(routes);\n            Assert.Equal(1, attributeRoutes.Count);\n\n            Route route = (Route)attributeRoutes.Single();\n            Assert.Equal(\"prefpref/getme\", route.Url);\n            Assert.Equal(\"GetMe\", Assert.Single(route.GetTargetActionDescriptors()).ActionName);\n        }\n\n        [Fact]\n        public void RoutePrefixAttribute_IsSingleInstance()\n        {\n            var attr = typeof(RoutePrefixAttribute);\n            var attrs = attr.GetCustomAttributes(typeof(AttributeUsageAttribute), false);\n            var usage = (AttributeUsageAttribute)attrs[0];\n\n            Assert.Equal(AttributeTargets.Class, usage.ValidOn);\n            Assert.False(usage.AllowMultiple); // only 1 per class\n            Assert.False(usage.Inherited); // RoutePrefix is not inherited.\n        }\n\n        [Fact]\n        public void MapMvcAttributeRoutes_WithArea()\n        {\n            // Arrange\n            var controllerTypes = new[] { typeof(PugetSoundController) };\n            var routes = new RouteCollection();\n\n            // Act\n            AttributeRoutingMapper.MapAttributeRoutes(routes, controllerTypes);\n\n            // Assert\n            var attributeRoutes = GetAttributeRoutes(routes);\n            Assert.Equal(1, attributeRoutes.Count);\n\n            Route route = (Route)attributeRoutes.Single();\n\n            Assert.Equal(\"puget-sound/getme\", route.Url);\n            Assert.Equal(\"PugetSound\", route.DataTokens[\"area\"]);\n            Assert.Equal((object)false, route.DataTokens[\"usenamespacefallback\"]);\n            Assert.Equal(\"GetMe\", Assert.Single(route.GetTargetActionDescriptors()).ActionName);\n            Assert.Equal(typeof(PugetSoundController).Namespace, ((string[])route.DataTokens[\"namespaces\"])[0]);\n        }\n\n        [Fact]\n        public void MapMvcAttributeRoutes_WithPrefixedArea()\n        {\n            // Arrange\n            var controllerTypes = new[] { typeof(PrefixedPugetSoundController) };\n            var routes = new RouteCollection();\n\n            // Act\n            AttributeRoutingMapper.MapAttributeRoutes(routes, controllerTypes);\n\n            // Assert\n            var attributeRoutes = GetAttributeRoutes(routes);\n            Assert.Equal(1, attributeRoutes.Count);\n\n            Route route = (Route)attributeRoutes.Single();\n\n            Assert.Equal(\"puget-sound/prefpref/getme\", route.Url);\n            Assert.Equal(\"PugetSound\", route.DataTokens[\"area\"]);\n            Assert.Equal((object)false, route.DataTokens[\"usenamespacefallback\"]);\n            Assert.Equal(\"GetMe\", Assert.Single(route.GetTargetActionDescriptors()).ActionName);\n            Assert.Equal(typeof(PrefixedPugetSoundController).Namespace, ((string[])route.DataTokens[\"namespaces\"])[0]);\n        }\n\n        [Theory]\n        [InlineData(null, null, \"\", \"\")]\n        [InlineData(null, null, \"whatever\", \"whatever\")]\n        [InlineData(null, \"\", \"\", \"\")]\n        [InlineData(null, \"\", \"whatever\", \"whatever\")]\n        [InlineData(null, \"pref\", \"\", \"pref\")]\n        [InlineData(null, \"pref\", \"whatever\", \"pref/whatever\")]\n        [InlineData(\"\", null, \"\", \"\")]\n        [InlineData(\"\", null, \"whatever\", \"whatever\")]\n        [InlineData(\"\", \"\", \"\", \"\")]\n        [InlineData(\"\", \"\", \"whatever\", \"whatever\")]\n        [InlineData(\"\", \"pref\", \"\", \"pref\")]\n        [InlineData(\"\", \"pref\", \"whatever\", \"pref/whatever\")]\n        [InlineData(\"puget-sound\", null, \"\", \"puget-sound\")]\n        [InlineData(\"puget-sound\", null, \"whatever\", \"puget-sound/whatever\")]\n        [InlineData(\"puget-sound\", \"\", \"\", \"puget-sound\")]\n        [InlineData(\"puget-sound\", \"\", \"whatever\", \"puget-sound/whatever\")]\n        [InlineData(\"puget-sound\", \"pref\", \"\", \"puget-sound/pref\")]\n        [InlineData(\"puget-sound\", \"pref\", \"whatever\", \"puget-sound/pref/whatever\")]\n        [InlineData(null, null, \"~/whatever\", \"whatever\")]\n        [InlineData(\"puget-sound\", \"pref\", \"~/\", \"\")]\n        [InlineData(\"puget-sound\", \"pref\", \"~/whatever\", \"whatever\")]\n        [InlineData(\"puget-sound\", null, \"~/whatever\", \"whatever\")]\n        [InlineData(null, \"pref\", \"~/whatever\", \"whatever\")]\n        public void BuildRouteTemplate(string areaPrefix, string prefix, string template, string expected)\n        {\n            var result = DirectRouteFactoryContext.BuildRouteTemplate(areaPrefix, prefix, template);\n\n            Assert.Equal(expected, result);\n        }\n\n        [Theory]\n        [InlineData(typeof(Bad1Controller), \"The route prefix '/pref' on the controller named 'Bad1' cannot begin or end with a forward slash.\")]\n        [InlineData(typeof(Bad2Controller), \"The route prefix 'pref/' on the controller named 'Bad2' cannot begin or end with a forward slash.\")]\n        [InlineData(typeof(Bad3Controller), \"The route template '/getme' on the action named 'GetMe' on the controller named 'Bad3' cannot begin with a forward slash.\")]\n        [InlineData(typeof(Bad4Controller), null)]\n        [InlineData(typeof(Bad5Controller), \"The route template '/puget-sound/getme' on the action named 'GetMe' on the controller named 'Bad5' cannot begin with a forward slash.\")]\n        [InlineData(typeof(Bad6Controller), \"The prefix 'puget-sound/' of the route area named 'PugetSound' on the controller named 'Bad6' cannot end with a forward slash.\")]\n        public void TemplatesAreValidated(Type controllerType, string expectedErrorMessage)\n        {\n            // Arrange\n            var controllerTypes = new[] { controllerType };\n            var routes = new RouteCollection();\n\n            // Act & Assert\n            if (expectedErrorMessage == null)\n            {\n                Assert.DoesNotThrow(() => AttributeRoutingMapper.MapAttributeRoutes(routes, controllerTypes));\n            }\n            else\n            {\n                Assert.Throws<InvalidOperationException>(() => AttributeRoutingMapper.MapAttributeRoutes(routes, controllerTypes), expectedErrorMessage);\n            }\n        }\n\n        private class SimpleRoutingController : Controller\n        {\n            [Route(\"getme\")]\n            [HttpGet]\n            public ActionResult GetMe()\n            {\n                throw new NotImplementedException();\n            }\n\n            [HttpPost]\n            [Route(\"postme\")]\n            public ActionResult PostMe()\n            {\n                throw new NotImplementedException();\n            }\n\n            [Route(\"routeme\")]\n            public ActionResult RouteMe()\n            {\n                throw new NotImplementedException();\n            }\n\n            [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]\n            [Route(\"getorpostme\")]\n            public ActionResult GetOrPostMe()\n            {\n                throw new NotImplementedException();\n            }\n\n            [HttpGet]\n            [Route(\"once\")]\n            [Route(\"twice\")]\n            public ActionResult FoolMe()\n            {\n                throw new NotImplementedException(\"Shame on you!\");\n            }\n\n            [HttpGet]\n            [Route(\"i/{have}/{id:int}/{defaultsto=VAL}/{name?}\")]\n            public ActionResult Parameterized(string have, int id, string optional)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        [RoutePrefix(\"prefpref\")]\n        private class PrefixedController : Controller\n        {\n            [HttpGet]\n            [Route(\"getme\")]\n            public ActionResult GetMe()\n            {\n                throw new NotImplementedException();\n            }\n\n            public ActionResult IDontGetARoute()\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        [RouteArea(\"PugetSound\", AreaPrefix = \"puget-sound\")]\n        private class PugetSoundController : Controller\n        {\n            [HttpGet]\n            [Route(\"getme\")]\n            public ActionResult GetMe()\n            {\n                throw new NotImplementedException();\n            }\n\n            public ActionResult IDontGetARoute()\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        [RouteArea(\"PugetSound\", AreaPrefix = \"puget-sound\")]\n        [RoutePrefix(\"prefpref\")]\n        private class PrefixedPugetSoundController : Controller\n        {\n            [HttpGet]\n            [Route(\"getme\")]\n            public ActionResult GetMe()\n            {\n                throw new NotImplementedException();\n            }\n\n            public ActionResult IDontGetARoute()\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        [RoutePrefix(\"/pref\")]\n        private class Bad1Controller : Controller\n        {\n            [HttpGet]\n            [Route(\"getme\")]\n            public ActionResult GetMe()\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        [RoutePrefix(\"pref/\")]\n        private class Bad2Controller : Controller\n        {\n            [HttpGet]\n            [Route(\"getme\")]\n            public ActionResult GetMe()\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class Bad3Controller : Controller\n        {\n            [HttpGet]\n            [Route(\"/getme\")]\n            public ActionResult GetMe()\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class Bad4Controller : Controller\n        {\n            [HttpGet]\n            [Route(\"getme/\")]\n            public ActionResult GetMe()\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        [RouteArea(\"PugetSound\", AreaPrefix = \"/puget-sound\")]\n        private class Bad5Controller : Controller\n        {\n            [HttpGet]\n            [Route(\"getme\")]\n            public ActionResult GetMe()\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        [RouteArea(\"PugetSound\", AreaPrefix = \"puget-sound/\")]\n        private class Bad6Controller : Controller\n        {\n            [HttpGet]\n            [Route(\"getme\")]\n            public ActionResult GetMe()\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class FruitConstraintController : Controller\n        {\n            [HttpGet]\n            [Route(\"fruits/{apple:fruit}\")]\n            public ActionResult Eat(string apple)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        class FruitConstraint : IRouteConstraint\n        {\n            public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values,\n                              RouteDirection routeDirection)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        class FruitConstraintResolver : IInlineConstraintResolver\n        {\n            public IRouteConstraint ResolveConstraint(string inlineConstraint)\n            {\n                if (inlineConstraint == \"fruit\")\n                {\n                    return new FruitConstraint();\n                }\n\n                throw new InvalidOperationException();\n            }\n        }\n\n        private IReadOnlyCollection<RouteBase> GetAttributeRoutes(RouteCollection routes)\n        {\n            return routes.OfType<IReadOnlyCollection<RouteBase>>().Single();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/System.Web.Mvc.Test.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props\" Condition=\"Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" />\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" />\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{8AC2A2E4-2F11-4D40-A887-62E2583A65E6}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>System.Web</RootNamespace>\n    <AssemblyName>System.Web.Mvc.Test</AssemblyName>\n    <OutputPath>..\\..\\bin\\$(Configuration)\\Test\\</OutputPath>\n    <DefineConstants>$(DefineConstants);ASPNETMVC</DefineConstants>\n    <!-- Temporarily disable Obsolete Warnings as Errors -->\n    <NoWarn>0618</NoWarn>\n    <NuGetPackageImportStamp>\n    </NuGetPackageImportStamp>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Castle.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Castle.Core.5.1.1\\lib\\net462\\Castle.Core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"Moq, Version=4.18.0.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Moq.4.18.4\\lib\\net462\\Moq.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Newtonsoft.Json.13.0.1\\lib\\net45\\Newtonsoft.Json.dll</HintPath>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.ComponentModel.DataAnnotations\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Data.Entity\" />\n    <Reference Include=\"System.Data.Linq\" />\n    <Reference Include=\"System.Drawing\" />\n    <Reference Include=\"System.Runtime.Caching\" />\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"System.Web.Abstractions\" />\n    <Reference Include=\"System.Web.Extensions\" />\n    <Reference Include=\"xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.abstractions.2.0.3\\lib\\net35\\xunit.abstractions.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.assert, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.assert.2.4.2\\lib\\netstandard1.1\\xunit.assert.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.core, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.core.2.4.2\\lib\\net452\\xunit.core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.execution.desktop, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.execution.2.4.2\\lib\\net452\\xunit.execution.desktop.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\Common\\AttributeListTest.cs\">\n      <Link>Common\\AttributeListTest.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\RouteFactoryAttributeTests.cs\">\n      <Link>Routing\\RouteFactoryAttributeTests.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\RoutePrecedenceTests.cs\">\n      <Link>Routing\\RoutePrecedenceTests.cs</Link>\n    </Compile>\n    <Compile Include=\"Async\\Test\\TaskAsyncActionDescriptorTest.cs\" />\n    <Compile Include=\"Async\\Test\\TaskWrapperAsyncResultTest.cs\" />\n    <Compile Include=\"Html\\Test\\DisplayExtensionsTest.cs\" />\n    <Compile Include=\"Html\\Test\\DisplayNameExtensionsTest.cs\" />\n    <Compile Include=\"Html\\Test\\DisplayTextExtensionsTest.cs\" />\n    <Compile Include=\"Html\\Test\\EditorExtensionsTest.cs\" />\n    <Compile Include=\"Html\\Test\\EncodedDataSets.cs\" />\n    <Compile Include=\"Html\\Test\\EnumHelperTest.cs\" />\n    <Compile Include=\"Html\\Test\\MetadataOverrideScope.cs\" />\n    <Compile Include=\"Html\\Test\\NameExtensionsTest.cs\" />\n    <Compile Include=\"Html\\Test\\TemplateHelpersSafeScope.cs\" />\n    <Compile Include=\"Html\\Test\\ValueExtensionsTest.cs\" />\n    <Compile Include=\"Test\\CopyOnWriteDictionaryTest.cs\" />\n    <Compile Include=\"Test\\JQueryFormValueProviderFactoryTest.cs\" />\n    <Compile Include=\"Razor\\Test\\MvcCSharpRazorCodeGeneratorTest.cs\" />\n    <Compile Include=\"Properties\\Resources.Designer.cs\">\n      <AutoGen>True</AutoGen>\n      <DesignTime>True</DesignTime>\n      <DependentUpon>Resources.resx</DependentUpon>\n    </Compile>\n    <Compile Include=\"Routing\\AttributeRoutingLinkGenerationTest.cs\" />\n    <Compile Include=\"Routing\\AttributeRoutingMapperTest.cs\" />\n    <Compile Include=\"Routing\\AttributeRoutingTest.cs\" />\n    <Compile Include=\"..\\Common\\Routing\\DirectRouteBuilderTests.cs\">\n      <Link>Routing\\DirectRouteBuilderTests.cs</Link>\n    </Compile>\n    <Compile Include=\"Routing\\DefaultDirectRouteProviderTest.cs\" />\n    <Compile Include=\"Routing\\DirectRouteCandidateTest.cs\" />\n    <Compile Include=\"Routing\\DirectRouteTestHelpers.cs\" />\n    <Compile Include=\"Routing\\RouteAttributeTests.cs\" />\n    <Compile Include=\"..\\Common\\Routing\\RouteConstraintsTests.cs\">\n      <Link>Routing\\RouteConstraintsTests.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\DefaultInlineConstraintResolverTest.cs\">\n      <Link>Routing\\DefaultInlineConstraintResolverTest.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\Routing\\InlineRouteTemplateParserTests.cs\">\n      <Link>Routing\\InlineRouteTemplateParserTests.cs</Link>\n    </Compile>\n    <Compile Include=\"Routing\\RouteCollectionAttributeRoutingExtensionsTests.cs\" />\n    <Compile Include=\"..\\Common\\Routing\\SubRouteCollectionTest.cs\">\n      <Link>Routing\\SubRouteCollectionTest.cs</Link>\n    </Compile>\n    <Compile Include=\"Test\\AjaxHelperOfTModelTest.cs\" />\n    <Compile Include=\"Test\\CancellationTokenModelBinderTest.cs\" />\n    <Compile Include=\"Test\\CachedAssociatedMetadataProviderTest.cs\" />\n    <Compile Include=\"Test\\CachedDataAnnotationsModelMetadataProviderTest.cs\" />\n    <Compile Include=\"Test\\ChildActionValueProviderFactoryTest.cs\" />\n    <Compile Include=\"ExpressionUtil\\Test\\BinaryExpressionFingerprintTest.cs\" />\n    <Compile Include=\"ExpressionUtil\\Test\\CachedExpressionCompilerTest.cs\" />\n    <Compile Include=\"ExpressionUtil\\Test\\ConditionalExpressionFingerprintTest.cs\" />\n    <Compile Include=\"ExpressionUtil\\Test\\ConstantExpressionFingerprintTest.cs\" />\n    <Compile Include=\"ExpressionUtil\\Test\\DefaultExpressionFingerprintTest.cs\" />\n    <Compile Include=\"ExpressionUtil\\Test\\DummyExpressionFingerprint.cs\" />\n    <Compile Include=\"ExpressionUtil\\Test\\ExpressionFingerprintTest.cs\" />\n    <Compile Include=\"ExpressionUtil\\Test\\FingerprintingExpressionVisitorTest.cs\" />\n    <Compile Include=\"ExpressionUtil\\Test\\HoistingExpressionVisitorTest.cs\" />\n    <Compile Include=\"ExpressionUtil\\Test\\IndexExpressionFingerprintTest.cs\" />\n    <Compile Include=\"ExpressionUtil\\Test\\LambdaExpressionFingerprintTest.cs\" />\n    <Compile Include=\"ExpressionUtil\\Test\\MemberExpressionFingerprintTest.cs\" />\n    <Compile Include=\"ExpressionUtil\\Test\\MethodCallExpressionFingerprintTest.cs\" />\n    <Compile Include=\"ExpressionUtil\\Test\\ParameterExpressionFingerprintTest.cs\" />\n    <Compile Include=\"ExpressionUtil\\Test\\TypeBinaryExpressionFingerprintTest.cs\" />\n    <Compile Include=\"ExpressionUtil\\Test\\UnaryExpressionFingerprintTest.cs\" />\n    <Compile Include=\"Test\\AdditionalMetadataAttributeTest.cs\" />\n    <Compile Include=\"Test\\BuildManagerCompiledViewTest.cs\" />\n    <Compile Include=\"Test\\BuildManagerViewEngineTest.cs\" />\n    <Compile Include=\"Test\\CompareAttributeTest.cs\" />\n    <Compile Include=\"Test\\CompareAttributeAdapterTest.cs\" />\n    <Compile Include=\"Test\\MinLengthAttributeAdapterTest.cs\" />\n    <Compile Include=\"Test\\OverrideResultFiltersAttributeTests.cs\" />\n    <Compile Include=\"Test\\OverrideAuthenticationAttributeTests.cs\" />\n    <Compile Include=\"Test\\OverrideAuthorizationAttributeTests.cs\" />\n    <Compile Include=\"Test\\OverrideExceptionFiltersAttributeTests.cs\" />\n    <Compile Include=\"Test\\DataAnnotationsModelMetadataProviderTestBase.cs\" />\n    <Compile Include=\"Test\\DataTypeUtilTest.cs\" />\n    <Compile Include=\"Test\\FilterInfoTest.cs\" />\n    <Compile Include=\"Test\\AllowHtmlAttributeTest.cs\" />\n    <Compile Include=\"Test\\HtmlHelperOfTModelTest.cs\" />\n    <Compile Include=\"Test\\HttpHeadAttributeTest.cs\" />\n    <Compile Include=\"Test\\HttpOptionsAttributeTest.cs\" />\n    <Compile Include=\"Test\\HttpPatchAttributeTest.cs\" />\n    <Compile Include=\"Test\\MockableUnvalidatedRequestValues.cs\" />\n    <Compile Include=\"Test\\DescriptorUtilTest.cs\" />\n    <Compile Include=\"Razor\\Test\\MvcVBRazorCodeParserTest.cs\" />\n    <Compile Include=\"Test\\ModelBinderProviderCollectionTest.cs\" />\n    <Compile Include=\"Test\\ModelBinderProvidersTest.cs\" />\n    <Compile Include=\"Razor\\Test\\MvcWebPageRazorHostTest.cs\" />\n    <Compile Include=\"Ajax\\Test\\AjaxExtensionsTest.cs\" />\n    <Compile Include=\"Ajax\\Test\\AjaxOptionsTest.cs\" />\n    <Compile Include=\"Async\\Test\\AsyncActionMethodSelectorTest.cs\" />\n    <Compile Include=\"Async\\Test\\AsyncControllerActionInvokerTest.cs\" />\n    <Compile Include=\"Async\\Test\\AsyncActionDescriptorTest.cs\" />\n    <Compile Include=\"Test\\AsyncControllerTest.cs\" />\n    <Compile Include=\"Async\\Test\\SynchronousOperationExceptionTest.cs\" />\n    <Compile Include=\"Async\\Test\\AsyncManagerTest.cs\" />\n    <Compile Include=\"Async\\Test\\AsyncResultWrapperTest.cs\" />\n    <Compile Include=\"Test\\AsyncTimeoutAttributeTest.cs\" />\n    <Compile Include=\"Test\\ClientDataTypeModelValidatorProviderTest.cs\" />\n    <Compile Include=\"Test\\ControllerInstanceFilterProviderTest.cs\" />\n    <Compile Include=\"Test\\OverrideActionFiltersAttributeTests.cs\" />\n    <Compile Include=\"Test\\OverrideFiltersAttributeTests.cs\" />\n    <Compile Include=\"Test\\PreApplicationStartCodeTest.cs\" />\n    <Compile Include=\"Test\\RemoteAttributeTest.cs\" />\n    <Compile Include=\"Test\\MaxLengthAttributeAdapterTest.cs\" />\n    <Compile Include=\"Test\\UrlHelperTest.cs\" />\n    <Compile Include=\"Test\\UrlParameterTest.cs\" />\n    <Compile Include=\"Test\\ViewStartPageTest.cs\" />\n    <Compile Include=\"Test\\RazorViewEngineTest.cs\" />\n    <Compile Include=\"Test\\RazorViewTest.cs\" />\n    <Compile Include=\"Test\\DynamicViewDataDictionaryTest.cs\" />\n    <Compile Include=\"Test\\FilterAttributeFilterProviderTest.cs\" />\n    <Compile Include=\"Test\\FilterProviderCollectionTest.cs\" />\n    <Compile Include=\"Test\\FilterProvidersTest.cs\" />\n    <Compile Include=\"Test\\FilterTest.cs\" />\n    <Compile Include=\"Test\\GlobalFilterCollectionTest.cs\" />\n    <Compile Include=\"Test\\HttpFileCollectionValueProviderFactoryTest.cs\" />\n    <Compile Include=\"Test\\HttpNotFoundResultTest.cs\" />\n    <Compile Include=\"Test\\HttpStatusCodeResultTest.cs\" />\n    <Compile Include=\"Test\\JsonValueProviderFactoryTest.cs\" />\n    <Compile Include=\"Razor\\Test\\MvcCSharpRazorCodeParserTest.cs\" />\n    <Compile Include=\"Test\\MultiServiceResolverTest.cs\" />\n    <Compile Include=\"Test\\DependencyResolverTest.cs\" />\n    <Compile Include=\"Test\\MvcWebRazorHostFactoryTest.cs\" />\n    <Compile Include=\"Test\\RangeAttributeAdapterTest.cs\" />\n    <Compile Include=\"Test\\RegularExpressionAttributeAdapterTest.cs\" />\n    <Compile Include=\"Test\\RequiredAttributeAdapterTest.cs\" />\n    <Compile Include=\"Test\\RouteDataValueProviderFactoryTest.cs\" />\n    <Compile Include=\"Test\\QueryStringValueProviderFactoryTest.cs\" />\n    <Compile Include=\"Test\\FormValueProviderFactoryTest.cs\" />\n    <Compile Include=\"Test\\SingleServiceResolverTest.cs\" />\n    <Compile Include=\"Test\\StringLengthAttributeAdapterTest.cs\" />\n    <Compile Include=\"Test\\ValidatableObjectAdapterTest.cs\" />\n    <Compile Include=\"Test\\ValueProviderFactoryCollectionTest.cs\" />\n    <Compile Include=\"Test\\TypeCacheUtilTest.cs\" />\n    <Compile Include=\"Test\\TypeCacheSerializerTest.cs\" />\n    <Compile Include=\"Test\\NoAsyncTimeoutAttributeTest.cs\" />\n    <Compile Include=\"Async\\Test\\OperationCounterTest.cs\" />\n    <Compile Include=\"Async\\Test\\ReflectedAsyncActionDescriptorTest.cs\" />\n    <Compile Include=\"Async\\Test\\ReflectedAsyncControllerDescriptorTest.cs\" />\n    <Compile Include=\"Async\\Test\\SignalContainer.cs\" />\n    <Compile Include=\"Async\\Test\\TriggerListenerTest.cs\" />\n    <Compile Include=\"Async\\Test\\MockAsyncResult.cs\" />\n    <Compile Include=\"Async\\Test\\SimpleAsyncResultTest.cs\" />\n    <Compile Include=\"Async\\Test\\SynchronizationContextUtilTest.cs\" />\n    <Compile Include=\"Html\\Test\\ChildActionExtensionsTest.cs\" />\n    <Compile Include=\"Html\\Test\\DefaultDisplayTemplatesTest.cs\" />\n    <Compile Include=\"Html\\Test\\DefaultEditorTemplatesTest.cs\" />\n    <Compile Include=\"Html\\Test\\FormExtensionsTest.cs\" />\n    <Compile Include=\"Html\\Test\\InputExtensionsTest.cs\" />\n    <Compile Include=\"Html\\Test\\LabelExtensionsTest.cs\" />\n    <Compile Include=\"Html\\Test\\LinkExtensionsTest.cs\" />\n    <Compile Include=\"Html\\Test\\MvcFormTest.cs\" />\n    <Compile Include=\"Html\\Test\\PartialExtensionsTest.cs\" />\n    <Compile Include=\"Html\\Test\\RenderPartialExtensionsTest.cs\" />\n    <Compile Include=\"Html\\Test\\SelectExtensionsTest.cs\" />\n    <Compile Include=\"Html\\Test\\TemplateHelpersTest.cs\" />\n    <Compile Include=\"Html\\Test\\TextAreaExtensionsTest.cs\" />\n    <Compile Include=\"Html\\Test\\ValidationExtensionsTest.cs\" />\n    <Compile Include=\"Test\\ActionExecutedContextTest.cs\" />\n    <Compile Include=\"Test\\ActionExecutingContextTest.cs\" />\n    <Compile Include=\"Test\\AssociatedValidatorProviderTest.cs\" />\n    <Compile Include=\"Test\\BindAttributeTest.cs\" />\n    <Compile Include=\"Test\\AssociatedMetadataProviderTest.cs\" />\n    <Compile Include=\"Test\\ByteArrayModelBinderTest.cs\" />\n    <Compile Include=\"Test\\ChildActionOnlyAttributeTest.cs\" />\n    <Compile Include=\"Test\\ControllerBaseTest.cs\" />\n    <Compile Include=\"Test\\ActionMethodSelectorTest.cs\" />\n    <Compile Include=\"Test\\ActionNameAttributeTest.cs\" />\n    <Compile Include=\"Test\\AcceptVerbsAttributeTest.cs\" />\n    <Compile Include=\"Test\\ControllerContextTest.cs\" />\n    <Compile Include=\"Test\\AuthorizationContextTest.cs\" />\n    <Compile Include=\"Test\\ParameterInfoUtilTest.cs\" />\n    <Compile Include=\"Test\\ModelValidationResultTest.cs\" />\n    <Compile Include=\"Test\\HttpHandlerUtilTest.cs\" />\n    <Compile Include=\"Test\\ValueProviderFactoriesTest.cs\" />\n    <Compile Include=\"Test\\ValueProviderCollectionTest.cs\" />\n    <Compile Include=\"Test\\HttpFileCollectionValueProviderTest.cs\" />\n    <Compile Include=\"Test\\DictionaryValueProviderTest.cs\" />\n    <Compile Include=\"Test\\NameValueCollectionValueProviderTest.cs\" />\n    <Compile Include=\"Test\\ValueProviderUtilTest.cs\" />\n    <Compile Include=\"Test\\DataErrorInfoModelValidatorProviderTest.cs\" />\n    <Compile Include=\"Test\\ModelValidatorProviderCollectionTest.cs\" />\n    <Compile Include=\"Test\\HttpVerbAttributeHelper.cs\" />\n    <Compile Include=\"Test\\HttpDeleteAttributeTest.cs\" />\n    <Compile Include=\"Test\\HttpPutAttributeTest.cs\" />\n    <Compile Include=\"Test\\HttpGetAttributeTest.cs\" />\n    <Compile Include=\"Test\\DataAnnotationsModelValidatorTest.cs\" />\n    <Compile Include=\"Test\\EmptyModelValidatorProviderTest.cs\" />\n    <Compile Include=\"Test\\ModelValidatorProvidersTest.cs\" />\n    <Compile Include=\"Test\\ModelValidatorTest.cs\" />\n    <Compile Include=\"Test\\MvcHtmlStringTest.cs\" />\n    <Compile Include=\"Test\\DataAnnotationsModelValidatorProviderTest.cs\" />\n    <Compile Include=\"Test\\ExpressionHelperTest.cs\" />\n    <Compile Include=\"Test\\FormContextTest.cs\" />\n    <Compile Include=\"Test\\FieldValidationMetadataTest.cs\" />\n    <Compile Include=\"Test\\ModelClientValidationRuleTest.cs\" />\n    <Compile Include=\"Test\\RequireHttpsAttributeTest.cs\" />\n    <Compile Include=\"Test\\HttpRequestExtensionsTest.cs\" />\n    <Compile Include=\"Test\\DataAnnotationsModelMetadataProviderTest.cs\" />\n    <Compile Include=\"Test\\ModelMetadataProvidersTest.cs\" />\n    <Compile Include=\"Test\\ModelMetadataTest.cs\" />\n    <Compile Include=\"Test\\AreaHelpersTest.cs\" />\n    <Compile Include=\"Test\\AreaRegistrationContextTest.cs\" />\n    <Compile Include=\"Test\\AreaRegistrationTest.cs\" />\n    <Compile Include=\"Async\\Test\\SingleEntryGateTest.cs\" />\n    <Compile Include=\"Test\\HttpPostAttributeTest.cs\" />\n    <Compile Include=\"Test\\LinqBinaryModelBinderTest.cs\" />\n    <Compile Include=\"Test\\MockHelpers.cs\" />\n    <Compile Include=\"Test\\ExceptionContextTest.cs\" />\n    <Compile Include=\"Test\\ModelBindingContextTest.cs\" />\n    <Compile Include=\"Test\\ResultExecutedContextTest.cs\" />\n    <Compile Include=\"Test\\ResultExecutingContextTest.cs\" />\n    <Compile Include=\"Test\\ValidateAntiForgeryTokenAttributeTest.cs\" />\n    <Compile Include=\"Test\\DictionaryHelpersTest.cs\" />\n    <Compile Include=\"Test\\AjaxRequestExtensionsTest.cs\" />\n    <Compile Include=\"Test\\JavaScriptResultTest.cs\" />\n    <Compile Include=\"Test\\ModelBinderDictionaryTest.cs\" />\n    <Compile Include=\"Test\\DefaultViewLocationCacheTest.cs\" />\n    <Compile Include=\"Test\\FormCollectionTest.cs\" />\n    <Compile Include=\"Test\\HttpPostedFileBaseModelBinderTest.cs\" />\n    <Compile Include=\"Test\\ValidateInputAttributeTest.cs\" />\n    <Compile Include=\"Test\\FileContentResultTest.cs\" />\n    <Compile Include=\"Test\\FilePathResultTest.cs\" />\n    <Compile Include=\"Test\\FileResultTest.cs\" />\n    <Compile Include=\"Test\\FileStreamResultTest.cs\" />\n    <Compile Include=\"Test\\ControllerDescriptorTest.cs\" />\n    <Compile Include=\"Test\\ControllerDescriptorCacheTest.cs\" />\n    <Compile Include=\"Test\\ReaderWriterCacheTest.cs\" />\n    <Compile Include=\"Test\\ReflectedParameterBindingInfoTest.cs\" />\n    <Compile Include=\"Test\\ParameterBindingInfoTest.cs\" />\n    <Compile Include=\"Test\\ReflectedControllerDescriptorTest.cs\" />\n    <Compile Include=\"Test\\ActionDescriptorTest.cs\" />\n    <Compile Include=\"Test\\ReflectedActionDescriptorTest.cs\" />\n    <Compile Include=\"Test\\ReflectedParameterDescriptorTest.cs\" />\n    <Compile Include=\"Test\\ParameterDescriptorTest.cs\" />\n    <Compile Include=\"Test\\DefaultModelBinderTest.cs\" />\n    <Compile Include=\"Test\\ValueProviderDictionaryTest.cs\" />\n    <Compile Include=\"Test\\ValueProviderResultTest.cs\" />\n    <Compile Include=\"Test\\ModelBinderAttributeTest.cs\" />\n    <Compile Include=\"Test\\ModelBindersTest.cs\" />\n    <Compile Include=\"Test\\ViewContextTest.cs\" />\n    <Compile Include=\"Test\\ViewDataInfoTest.cs\" />\n    <Compile Include=\"Test\\ViewEngineResultTest.cs\" />\n    <Compile Include=\"Test\\NonActionAttributeTest.cs\" />\n    <Compile Include=\"Test\\ModelStateDictionaryTest.cs\" />\n    <Compile Include=\"Test\\ModelStateTest.cs\" />\n    <Compile Include=\"Test\\ModelErrorCollectionTest.cs\" />\n    <Compile Include=\"Test\\ModelErrorTest.cs\" />\n    <Compile Include=\"Test\\AjaxHelperTest.cs\" />\n    <Compile Include=\"Test\\AuthorizeAttributeTest.cs\" />\n    <Compile Include=\"Test\\ControllerActionInvokerTest.cs\" />\n    <Compile Include=\"Test\\ActionFilterAttributeTest.cs\" />\n    <Compile Include=\"Test\\ControllerBuilderTest.cs\" />\n    <Compile Include=\"Test\\ControllerTest.cs\" />\n    <Compile Include=\"Test\\ContentResultTest.cs\" />\n    <Compile Include=\"Test\\ActionMethodDispatcherTest.cs\" />\n    <Compile Include=\"Test\\ActionMethodDispatcherCacheTest.cs\" />\n    <Compile Include=\"Test\\PartialViewResultTest.cs\" />\n    <Compile Include=\"Test\\ViewEngineCollectionTest.cs\" />\n    <Compile Include=\"Test\\ViewMasterPageControlBuilderTest.cs\" />\n    <Compile Include=\"Test\\ViewPageControlBuilderTest.cs\" />\n    <Compile Include=\"Test\\ViewTypeParserFilterTest.cs\" />\n    <Compile Include=\"Test\\ViewResultBaseTest.cs\" />\n    <Compile Include=\"Test\\ViewUserControlControlBuilderTest.cs\" />\n    <Compile Include=\"Test\\VirtualPathProviderViewEngineTest.cs\" />\n    <Compile Include=\"Test\\WebFormViewTest.cs\" />\n    <Compile Include=\"Test\\MvcHttpHandlerTest.cs\" />\n    <Compile Include=\"Test\\HandleErrorAttributeTest.cs\" />\n    <Compile Include=\"Test\\HandleErrorInfoTest.cs\" />\n    <Compile Include=\"Test\\HttpUnauthorizedResultTest.cs\" />\n    <Compile Include=\"Test\\SessionStateTempDataProviderTest.cs\" />\n    <Compile Include=\"Test\\OutputCacheAttributeTest.cs\" />\n    <Compile Include=\"Test\\JsonResultTest.cs\" />\n    <Compile Include=\"Test\\NameValueCollectionExtensionsTest.cs\" />\n    <Compile Include=\"Test\\MockBuildManager.cs\" />\n    <Compile Include=\"Test\\DefaultControllerFactoryTest.cs\" />\n    <Compile Include=\"Test\\HtmlHelperTest.cs\" />\n    <Compile Include=\"Test\\MultiSelectListTest.cs\" />\n    <Compile Include=\"Test\\MvcHandlerTest.cs\" />\n    <Compile Include=\"Test\\MvcRouteHandlerTest.cs\" />\n    <Compile Include=\"Test\\MvcTestHelper.cs\" />\n    <Compile Include=\"Test\\RedirectResultTest.cs\" />\n    <Compile Include=\"Test\\RedirectToRouteResultTest.cs\" />\n    <Compile Include=\"Test\\RouteCollectionExtensionsTest.cs\" />\n    <Compile Include=\"Test\\SelectListTest.cs\" />\n    <Compile Include=\"Test\\TempDataDictionaryTest.cs\" />\n    <Compile Include=\"Test\\TypeHelpersTest.cs\" />\n    <Compile Include=\"Test\\ViewDataDictionaryTest.cs\" />\n    <Compile Include=\"Test\\ViewEnginesTest.cs\" />\n    <Compile Include=\"Test\\ViewMasterPageTest.cs\" />\n    <Compile Include=\"Test\\ViewPageTest.cs\" />\n    <Compile Include=\"Test\\ViewResultTest.cs\" />\n    <Compile Include=\"Test\\ViewUserControlTest.cs\" />\n    <Compile Include=\"Test\\WebFormViewEngineTest.cs\" />\n    <Compile Include=\"Util\\AnonymousObject.cs\" />\n    <Compile Include=\"Util\\DictionaryHelper.cs\" />\n    <Compile Include=\"Util\\HttpContextHelpers.cs\" />\n    <Compile Include=\"Util\\MvcHelper.cs\" />\n    <Compile Include=\"Util\\Resolver.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"Util\\SimpleValueProvider.cs\" />\n    <Compile Include=\"Util\\SimpleViewDataContainer.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Http\\System.Web.Http.csproj\">\n      <Project>{DDC1CE0C-486E-4E35-BB3B-EAB61F8F9440}</Project>\n      <Name>System.Web.Http</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Mvc\\System.Web.Mvc.csproj\">\n      <Project>{3D3FFD8A-624D-4E9B-954B-E1C105507975}</Project>\n      <Name>System.Web.Mvc</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Razor\\System.Web.Razor.csproj\">\n      <Project>{8F18041B-9410-4C36-A9C5-067813DF5F31}</Project>\n      <Name>System.Web.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.WebPages.Razor\\System.Web.WebPages.Razor.csproj\">\n      <Project>{0939B11A-FE4E-4BA1-8AD6-D97741EE314F}</Project>\n      <Name>System.Web.WebPages.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.WebPages\\System.Web.WebPages.csproj\">\n      <Project>{76EFA9C5-8D7E-4FDF-B710-E20F8B6B00D2}</Project>\n      <Name>System.Web.WebPages</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\">\n      <Project>{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}</Project>\n      <Name>Microsoft.TestCommon</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\System.Web.Razor.Test\\System.Web.Razor.Test.csproj\">\n      <Project>{0BB62A1D-E6B5-49FA-9E3C-6AF679A66DFE}</Project>\n      <Name>System.Web.Razor.Test</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Service Include=\"{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"Properties\\Resources.resx\">\n      <Generator>ResXFileCodeGenerator</Generator>\n      <LastGenOutput>Resources.Designer.cs</LastGenOutput>\n    </EmbeddedResource>\n  </ItemGroup>\n  <ItemGroup>\n    <Analyzer Include=\"..\\..\\packages\\xunit.analyzers.1.1.0\\analyzers\\dotnet\\cs\\xunit.analyzers.dll\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\n  <Target Name=\"EnsureNuGetPackageBuildImports\" BeforeTargets=\"PrepareForBuild\">\n    <PropertyGroup>\n      <ErrorText>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}.</ErrorText>\n    </PropertyGroup>\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props'))\" />\n  </Target>\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" />\n</Project>"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/AcceptVerbsAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Collections.Specialized;\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class AcceptVerbsAttributeTest\n    {\n        private const string _invalidEnumFormatString = @\"The enum '{0}' did not produce the correct array.\nExpected: {1}\nActual: {2}\";\n\n        [Fact]\n        public void ConstructorThrowsIfVerbsIsEmpty()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { new AcceptVerbsAttribute(new string[0]); }, \"verbs\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfVerbsIsNull()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { new AcceptVerbsAttribute((string[])null); }, \"verbs\");\n        }\n\n        [Fact]\n        public void EnumToArray()\n        {\n            // Arrange\n            IDictionary<string, HttpVerbs> enumValues = EnumToDictionary<HttpVerbs>();\n            var allCombinations = EnumerableToCombinations(enumValues);\n\n            // Act & assert\n            foreach (var combination in allCombinations)\n            {\n                // generate all the names + values in this combination\n                List<string> aggrNames = new List<string>();\n                HttpVerbs aggrValues = (HttpVerbs)0;\n                foreach (var entry in combination)\n                {\n                    aggrNames.Add(entry.Key);\n                    aggrValues |= entry.Value;\n                }\n\n                // get the resulting array\n                string[] array = AcceptVerbsAttribute.EnumToArray(aggrValues);\n                var aggrNamesOrdered = aggrNames.OrderBy(name => name, StringComparer.OrdinalIgnoreCase);\n                var arrayOrdered = array.OrderBy(name => name, StringComparer.OrdinalIgnoreCase);\n                bool match = aggrNamesOrdered.SequenceEqual(arrayOrdered, StringComparer.OrdinalIgnoreCase);\n\n                if (!match)\n                {\n                    string message = String.Format(_invalidEnumFormatString, aggrValues,\n                                                   aggrNames.Aggregate((a, b) => a + \", \" + b),\n                                                   array.Aggregate((a, b) => a + \", \" + b));\n                    Assert.True(false, message);\n                }\n            }\n        }\n\n        [Fact]\n        public void IsValidForRequestReturnsFalseIfHttpVerbIsNotInVerbsCollection()\n        {\n            // Arrange\n            AcceptVerbsAttribute attr = new AcceptVerbsAttribute(\"get\", \"post\");\n            ControllerContext context = GetControllerContextWithHttpVerb(\"HEAD\");\n\n            // Act\n            bool result = attr.IsValidForRequest(context, null);\n\n            // Assert\n            Assert.False(result);\n        }\n\n        [Fact]\n        public void IsValidForRequestReturnsTrueIfHttpVerbIsInVerbsCollection()\n        {\n            // Arrange\n            AcceptVerbsAttribute attr = new AcceptVerbsAttribute(\"get\", \"post\");\n            ControllerContext context = GetControllerContextWithHttpVerb(\"POST\");\n\n            // Act\n            bool result = attr.IsValidForRequest(context, null);\n\n            // Assert\n            Assert.True(result);\n        }\n\n        [Fact]\n        public void IsValidForRequestReturnsTrueIfHttpVerbIsOverridden()\n        {\n            // Arrange\n            AcceptVerbsAttribute attr = new AcceptVerbsAttribute(\"put\");\n            ControllerContext context = GetControllerContextWithHttpVerb(\"POST\", \"PUT\", null, null);\n\n            // Act\n            bool result = attr.IsValidForRequest(context, null);\n\n            // Assert\n            Assert.True(result);\n        }\n\n        [Fact]\n        public void IsValidForRequestThrowsIfControllerContextIsNull()\n        {\n            // Arrange\n            AcceptVerbsAttribute attr = new AcceptVerbsAttribute(\"get\", \"post\");\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { attr.IsValidForRequest(null, null); }, \"controllerContext\");\n        }\n\n        [Fact]\n        public void VerbsPropertyFromEnumConstructor()\n        {\n            // Arrange\n            AcceptVerbsAttribute attr = new AcceptVerbsAttribute(HttpVerbs.Get | HttpVerbs.Post);\n\n            // Act\n            ReadOnlyCollection<string> collection = attr.Verbs as ReadOnlyCollection<string>;\n\n            // Assert\n            Assert.NotNull(collection);\n            Assert.Equal(2, collection.Count);\n            Assert.Equal(\"GET\", collection[0]);\n            Assert.Equal(\"POST\", collection[1]);\n        }\n\n        [Fact]\n        public void VerbsPropertyFromStringArrayConstructor()\n        {\n            // Arrange\n            AcceptVerbsAttribute attr = new AcceptVerbsAttribute(\"get\", \"post\");\n\n            // Act\n            ReadOnlyCollection<string> collection = attr.Verbs as ReadOnlyCollection<string>;\n\n            // Assert\n            Assert.NotNull(collection);\n            Assert.Equal(2, collection.Count);\n            Assert.Equal(\"get\", collection[0]);\n            Assert.Equal(\"post\", collection[1]);\n        }\n\n        internal static ControllerContext GetControllerContextWithHttpVerb(string httpRequestVerb)\n        {\n            return GetControllerContextWithHttpVerb(httpRequestVerb, null, null, null);\n        }\n\n        internal static ControllerContext GetControllerContextWithHttpVerb(string httpRequestVerb, string httpHeaderVerb, string httpFormVerb, string httpQueryStringVerb)\n        {\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(c => c.HttpContext.Request.HttpMethod).Returns(httpRequestVerb);\n\n            NameValueCollection headers = new NameValueCollection();\n            if (!String.IsNullOrEmpty(httpHeaderVerb))\n            {\n                headers.Add(HttpRequestExtensions.XHttpMethodOverrideKey, httpHeaderVerb);\n            }\n            mockControllerContext.Setup(c => c.HttpContext.Request.Headers).Returns(headers);\n\n            NameValueCollection form = new NameValueCollection();\n            if (!String.IsNullOrEmpty(httpFormVerb))\n            {\n                form.Add(HttpRequestExtensions.XHttpMethodOverrideKey, httpFormVerb);\n            }\n            mockControllerContext.Setup(c => c.HttpContext.Request.Form).Returns(form);\n\n            NameValueCollection queryString = new NameValueCollection();\n            if (!String.IsNullOrEmpty(httpQueryStringVerb))\n            {\n                queryString.Add(HttpRequestExtensions.XHttpMethodOverrideKey, httpQueryStringVerb);\n            }\n            mockControllerContext.Setup(c => c.HttpContext.Request.QueryString).Returns(queryString);\n\n            return mockControllerContext.Object;\n        }\n\n        private static IDictionary<string, TEnum> EnumToDictionary<TEnum>()\n        {\n            // Arrange\n            var values = Enum.GetValues(typeof(TEnum)).Cast<TEnum>();\n            return values.ToDictionary(value => Enum.GetName(typeof(TEnum), value), value => value);\n        }\n\n        private static IEnumerable<ICollection<T>> EnumerableToCombinations<T>(IEnumerable<T> elements)\n        {\n            List<T> allElements = elements.ToList();\n\n            int maxCount = 1 << allElements.Count;\n            for (int idxCombination = 0; idxCombination < maxCount; idxCombination++)\n            {\n                List<T> thisCollection = new List<T>();\n                for (int idxBit = 0; idxBit < 32; idxBit++)\n                {\n                    bool bitActive = (((uint)idxCombination >> idxBit) & 1) != 0;\n                    if (bitActive)\n                    {\n                        thisCollection.Add(allElements[idxBit]);\n                    }\n                }\n                yield return thisCollection;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ActionDescriptorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Linq;\nusing System.Reflection;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ActionDescriptorTest\n    {\n        [Fact]\n        public void ExtractParameterOrDefaultFromDictionary_ReturnsDefaultParameterValueIfMismatch()\n        {\n            // Arrange\n            Dictionary<string, object> dictionary = new Dictionary<string, object>()\n            {\n                { \"stringParameterWithDefaultValue\", 42 }\n            };\n\n            // Act\n            object value = ActionDescriptor.ExtractParameterOrDefaultFromDictionary(ParameterExtractionController.StringParameterWithDefaultValue, dictionary);\n\n            // Assert\n            Assert.Equal(\"hello\", value);\n        }\n\n        [Fact]\n        public void ExtractParameterOrDefaultFromDictionary_ReturnsDefaultTypeValueIfNoMatchAndNoDefaultParameterValue()\n        {\n            // Arrange\n            Dictionary<string, object> dictionary = new Dictionary<string, object>();\n\n            // Act\n            object value = ActionDescriptor.ExtractParameterOrDefaultFromDictionary(ParameterExtractionController.IntParameter, dictionary);\n\n            // Assert\n            Assert.Equal(0, value);\n        }\n\n        [Fact]\n        public void ExtractParameterOrDefaultFromDictionary_ReturnsDictionaryValueIfTypeMatch()\n        {\n            // Arrange\n            Dictionary<string, object> dictionary = new Dictionary<string, object>()\n            {\n                { \"stringParameterNoDefaultValue\", \"someValue\" }\n            };\n\n            // Act\n            object value = ActionDescriptor.ExtractParameterOrDefaultFromDictionary(ParameterExtractionController.StringParameterNoDefaultValue, dictionary);\n\n            // Assert\n            Assert.Equal(\"someValue\", value);\n        }\n\n        [Fact]\n        public void GetCustomAttributesReturnsEmptyArrayOfAttributeType()\n        {\n            // Arrange\n            ActionDescriptor ad = GetActionDescriptor();\n\n            // Act\n            ObsoleteAttribute[] attrs = (ObsoleteAttribute[])ad.GetCustomAttributes(typeof(ObsoleteAttribute), true);\n\n            // Assert\n            Assert.Empty(attrs);\n        }\n\n        [Fact]\n        public void GetCustomAttributesThrowsIfAttributeTypeIsNull()\n        {\n            // Arrange\n            ActionDescriptor ad = GetActionDescriptor();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { ad.GetCustomAttributes(null /* attributeType */, true); }, \"attributeType\");\n        }\n\n        [Fact]\n        public void GetCustomAttributesWithoutAttributeTypeCallsGetCustomAttributesWithAttributeType()\n        {\n            // Arrange\n            object[] expected = new object[0];\n            Mock<ActionDescriptor> mockDescriptor = new Mock<ActionDescriptor>() { CallBase = true };\n            mockDescriptor.Setup(d => d.GetCustomAttributes(typeof(object), true)).Returns(expected);\n            ActionDescriptor ad = mockDescriptor.Object;\n\n            // Act\n            object[] returned = ad.GetCustomAttributes(true /* inherit */);\n\n            // Assert\n            Assert.Same(expected, returned);\n        }\n\n        [Fact]\n        public void GetFilterAttributes_CallsGetCustomAttributes()\n        {\n            // Arrange\n            var mockDescriptor = new Mock<ActionDescriptor>() { CallBase = true };\n            mockDescriptor.Setup(d => d.GetCustomAttributes(typeof(FilterAttribute), true)).Returns(new object[] { new Mock<FilterAttribute>().Object }).Verifiable();\n\n            // Act\n            var result = mockDescriptor.Object.GetFilterAttributes(true).ToList();\n\n            // Assert\n            mockDescriptor.Verify();\n            Assert.Single(result);\n        }\n\n        [Fact]\n        public void GetSelectorsReturnsEmptyCollection()\n        {\n            // Arrange\n            ActionDescriptor ad = GetActionDescriptor();\n\n            // Act\n            ICollection<ActionSelector> selectors = ad.GetSelectors();\n\n            // Assert\n            Assert.IsType<ActionSelector[]>(selectors);\n            Assert.Empty(selectors);\n        }\n\n        [Fact]\n        public void IsDefinedReturnsFalse()\n        {\n            // Arrange\n            ActionDescriptor ad = GetActionDescriptor();\n\n            // Act\n            bool isDefined = ad.IsDefined(typeof(object), true);\n\n            // Assert\n            Assert.False(isDefined);\n        }\n\n        [Fact]\n        public void IsDefinedThrowsIfAttributeTypeIsNull()\n        {\n            // Arrange\n            ActionDescriptor ad = GetActionDescriptor();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { ad.IsDefined(null /* attributeType */, true); }, \"attributeType\");\n        }\n\n        [Fact]\n        public void UniqueId_SameTypeControllerDescriptorAndActionName_SameID()\n        {\n            // Arrange\n            var controllerDescriptor = new Mock<ControllerDescriptor>().Object;\n\n            var descriptor1 = new Mock<ActionDescriptor> { CallBase = true };\n            descriptor1.SetupGet(d => d.ControllerDescriptor).Returns(controllerDescriptor);\n            descriptor1.SetupGet(d => d.ActionName).Returns(\"Action1\");\n\n            var descriptor2 = new Mock<ActionDescriptor> { CallBase = true };\n            descriptor2.SetupGet(d => d.ControllerDescriptor).Returns(controllerDescriptor);\n            descriptor2.SetupGet(d => d.ActionName).Returns(\"Action1\");\n\n            // Act\n            var id1 = descriptor1.Object.UniqueId;\n            var id2 = descriptor2.Object.UniqueId;\n\n            // Assert\n            Assert.Equal(id1, id2);\n        }\n\n        [Fact]\n        public void UniqueId_VariesWithActionName()\n        {\n            // Arrange\n            var controllerDescriptor = new Mock<ControllerDescriptor>().Object;\n\n            var descriptor1 = new Mock<ActionDescriptor> { CallBase = true };\n            descriptor1.SetupGet(d => d.ControllerDescriptor).Returns(controllerDescriptor);\n            descriptor1.SetupGet(d => d.ActionName).Returns(\"Action1\");\n\n            var descriptor2 = new Mock<ActionDescriptor> { CallBase = true };\n            descriptor2.SetupGet(d => d.ControllerDescriptor).Returns(controllerDescriptor);\n            descriptor2.SetupGet(d => d.ActionName).Returns(\"Action2\");\n\n            // Act\n            var id1 = descriptor1.Object.UniqueId;\n            var id2 = descriptor2.Object.UniqueId;\n\n            // Assert\n            Assert.NotEqual(id1, id2);\n        }\n\n        [Fact]\n        public void UniqueId_VariesWithControllerDescriptorsUniqueId()\n        {\n            // Arrange\n            var controllerDescriptor1 = new Mock<ControllerDescriptor>();\n            controllerDescriptor1.SetupGet(cd => cd.UniqueId).Returns(\"1\");\n            var descriptor1 = new Mock<ActionDescriptor> { CallBase = true };\n            descriptor1.SetupGet(d => d.ControllerDescriptor).Returns(controllerDescriptor1.Object);\n            descriptor1.SetupGet(d => d.ActionName).Returns(\"Action1\");\n\n            var controllerDescriptor2 = new Mock<ControllerDescriptor>();\n            controllerDescriptor2.SetupGet(cd => cd.UniqueId).Returns(\"2\");\n            var descriptor2 = new Mock<ActionDescriptor> { CallBase = true };\n            descriptor2.SetupGet(d => d.ControllerDescriptor).Returns(controllerDescriptor2.Object);\n            descriptor2.SetupGet(d => d.ActionName).Returns(\"Action1\");\n\n            // Act\n            var id1 = descriptor1.Object.UniqueId;\n            var id2 = descriptor2.Object.UniqueId;\n\n            // Assert\n            Assert.NotEqual(id1, id2);\n        }\n\n        [Fact]\n        public void UniqueId_VariesWithActionDescriptorType()\n        {\n            // Arrange\n            var descriptor1 = new BaseDescriptor();\n            var descriptor2 = new DerivedDescriptor();\n\n            // Act\n            var id1 = descriptor1.UniqueId;\n            var id2 = descriptor2.UniqueId;\n\n            // Assert\n            Assert.NotEqual(id1, id2);\n        }\n\n        class BaseDescriptor : ActionDescriptor\n        {\n            static ControllerDescriptor controllerDescriptor = new Mock<ControllerDescriptor>().Object;\n\n            public override string ActionName\n            {\n                get { return \"ActionName\"; }\n            }\n\n            public override ControllerDescriptor ControllerDescriptor\n            {\n                get { return controllerDescriptor; }\n            }\n\n            public override object Execute(ControllerContext controllerContext, IDictionary<string, object> parameters)\n            {\n                throw new NotImplementedException();\n            }\n\n            public override ParameterDescriptor[] GetParameters()\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        class DerivedDescriptor : BaseDescriptor\n        {\n        }\n\n        private static ActionDescriptor GetActionDescriptor()\n        {\n            Mock<ActionDescriptor> mockDescriptor = new Mock<ActionDescriptor>() { CallBase = true };\n            return mockDescriptor.Object;\n        }\n\n        private class ParameterExtractionController : Controller\n        {\n            public static readonly ParameterInfo IntParameter = typeof(ParameterExtractionController).GetMethod(\"SomeMethod\").GetParameters()[0];\n            public static readonly ParameterInfo StringParameterNoDefaultValue = typeof(ParameterExtractionController).GetMethod(\"SomeMethod\").GetParameters()[1];\n            public static readonly ParameterInfo StringParameterWithDefaultValue = typeof(ParameterExtractionController).GetMethod(\"SomeMethod\").GetParameters()[2];\n\n            public void SomeMethod(int intParameter, string stringParameterNoDefaultValue, [DefaultValue(\"hello\")] string stringParameterWithDefaultValue)\n            {\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ActionExecutedContextTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ActionExecutedContextTest\n    {\n        [Fact]\n        public void ConstructorThrowsIfActionDescriptorIsNull()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n            ActionDescriptor actionDescriptor = null;\n            bool canceled = true;\n            Exception exception = null;\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ActionExecutedContext(controllerContext, actionDescriptor, canceled, exception); }, \"actionDescriptor\");\n        }\n\n        [Fact]\n        public void PropertiesAreSetByConstructor()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n            ActionDescriptor actionDescriptor = new Mock<ActionDescriptor>().Object;\n            bool canceled = true;\n            Exception exception = new Exception();\n\n            // Act\n            ActionExecutedContext actionExecutedContext = new ActionExecutedContext(controllerContext, actionDescriptor, canceled, exception);\n\n            // Assert\n            Assert.Equal(actionDescriptor, actionExecutedContext.ActionDescriptor);\n            Assert.Equal(canceled, actionExecutedContext.Canceled);\n            Assert.Equal(exception, actionExecutedContext.Exception);\n        }\n\n        [Fact]\n        public void ResultProperty()\n        {\n            // Arrange\n            ActionExecutedContext actionExecutedContext = new Mock<ActionExecutedContext>().Object;\n\n            // Act & assert\n            MemberHelper.TestPropertyWithDefaultInstance(actionExecutedContext, \"Result\", new ViewResult(), EmptyResult.Instance);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ActionExecutingContextTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ActionExecutingContextTest\n    {\n        [Fact]\n        public void ConstructorThrowsIfActionDescriptorIsNull()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n            ActionDescriptor actionDescriptor = null;\n            Dictionary<string, object> actionParameters = new Dictionary<string, object>();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ActionExecutingContext(controllerContext, actionDescriptor, actionParameters); }, \"actionDescriptor\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfActionParametersIsNull()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n            ActionDescriptor actionDescriptor = new Mock<ActionDescriptor>().Object;\n            Dictionary<string, object> actionParameters = null;\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ActionExecutingContext(controllerContext, actionDescriptor, actionParameters); }, \"actionParameters\");\n        }\n\n        [Fact]\n        public void PropertiesAreSetByConstructor()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n            ActionDescriptor actionDescriptor = new Mock<ActionDescriptor>().Object;\n            Dictionary<string, object> actionParameters = new Dictionary<string, object>();\n\n            // Act\n            ActionExecutingContext actionExecutingContext = new ActionExecutingContext(controllerContext, actionDescriptor, actionParameters);\n\n            // Assert\n            Assert.Equal(actionDescriptor, actionExecutingContext.ActionDescriptor);\n            Assert.Equal(actionParameters, actionExecutingContext.ActionParameters);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ActionFilterAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ActionFilterAttributeTest\n    {\n        [Fact]\n        public void DefaultOrderIsNegativeOne()\n        {\n            // Act\n            var attr = new EmptyActionFilterAttribute();\n\n            // Assert\n            Assert.Equal(-1, attr.Order);\n        }\n\n        [Fact]\n        public void OrderIsSetCorrectly()\n        {\n            // Act\n            var attr = new EmptyActionFilterAttribute() { Order = 98052 };\n\n            // Assert\n            Assert.Equal(98052, attr.Order);\n        }\n\n        [Fact]\n        public void SpecifyingInvalidOrderThrows()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentOutOfRange(\n                delegate { new EmptyActionFilterAttribute() { Order = -2 }; },\n                \"value\",\n                \"Order must be greater than or equal to -1.\");\n        }\n\n        private class EmptyActionFilterAttribute : ActionFilterAttribute\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ActionMethodDispatcherCacheTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ActionMethodDispatcherCacheTest\n    {\n        [Fact]\n        public void GetDispatcher()\n        {\n            // Arrange\n            MethodInfo methodInfo = typeof(object).GetMethod(\"ToString\");\n            ActionMethodDispatcherCache cache = new ActionMethodDispatcherCache();\n\n            // Act\n            ActionMethodDispatcher dispatcher1 = cache.GetDispatcher(methodInfo);\n            ActionMethodDispatcher dispatcher2 = cache.GetDispatcher(methodInfo);\n\n            // Assert\n            Assert.Same(methodInfo, dispatcher1.MethodInfo);\n            Assert.Same(dispatcher1, dispatcher2);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ActionMethodDispatcherTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ActionMethodDispatcherTest\n    {\n        [Fact]\n        public void ExecuteWithNormalActionMethod()\n        {\n            // Arrange\n            DispatcherController controller = new DispatcherController();\n            object[] parameters = new object[] { 5, \"some string\", new DateTime(2001, 1, 1) };\n            MethodInfo methodInfo = typeof(DispatcherController).GetMethod(\"NormalAction\");\n            ActionMethodDispatcher dispatcher = new ActionMethodDispatcher(methodInfo);\n\n            // Act\n            object returnValue = dispatcher.Execute(controller, parameters);\n\n            // Assert\n            var stringResult = Assert.IsType<string>(returnValue);\n            Assert.Equal(\"Hello from NormalAction!\", stringResult);\n\n            Assert.Equal(5, controller._i);\n            Assert.Equal(\"some string\", controller._s);\n            Assert.Equal(new DateTime(2001, 1, 1), controller._dt);\n        }\n\n        [Fact]\n        public void ExecuteWithParameterlessActionMethod()\n        {\n            // Arrange\n            DispatcherController controller = new DispatcherController();\n            object[] parameters = new object[0];\n            MethodInfo methodInfo = typeof(DispatcherController).GetMethod(\"ParameterlessAction\");\n            ActionMethodDispatcher dispatcher = new ActionMethodDispatcher(methodInfo);\n\n            // Act\n            object returnValue = dispatcher.Execute(controller, parameters);\n\n            // Assert\n            var intResult = Assert.IsType<int>(returnValue);\n            Assert.Equal(53, intResult);\n        }\n\n        [Fact]\n        public void ExecuteWithStaticActionMethod()\n        {\n            // Arrange\n            DispatcherController controller = new DispatcherController();\n            object[] parameters = new object[0];\n            MethodInfo methodInfo = typeof(DispatcherController).GetMethod(\"StaticAction\");\n            ActionMethodDispatcher dispatcher = new ActionMethodDispatcher(methodInfo);\n\n            // Act\n            object returnValue = dispatcher.Execute(controller, parameters);\n\n            // Assert\n            var intResult = Assert.IsType<int>(returnValue);\n            Assert.Equal(89, intResult);\n        }\n\n        [Fact]\n        public void ExecuteWithVoidActionMethod()\n        {\n            // Arrange\n            DispatcherController controller = new DispatcherController();\n            object[] parameters = new object[] { 5, \"some string\", new DateTime(2001, 1, 1) };\n            MethodInfo methodInfo = typeof(DispatcherController).GetMethod(\"VoidAction\");\n            ActionMethodDispatcher dispatcher = new ActionMethodDispatcher(methodInfo);\n\n            // Act\n            object returnValue = dispatcher.Execute(controller, parameters);\n\n            // Assert\n            Assert.Null(returnValue);\n            Assert.Equal(5, controller._i);\n            Assert.Equal(\"some string\", controller._s);\n            Assert.Equal(new DateTime(2001, 1, 1), controller._dt);\n        }\n\n        [Fact]\n        public void MethodInfoProperty()\n        {\n            // Arrange\n            MethodInfo original = typeof(object).GetMethod(\"ToString\");\n            ActionMethodDispatcher dispatcher = new ActionMethodDispatcher(original);\n\n            // Act\n            MethodInfo returned = dispatcher.MethodInfo;\n\n            // Assert\n            Assert.Same(original, returned);\n        }\n\n        private class DispatcherController : Controller\n        {\n            public int _i;\n            public string _s;\n            public DateTime _dt;\n\n            public object NormalAction(int i, string s, DateTime dt)\n            {\n                VoidAction(i, s, dt);\n                return \"Hello from NormalAction!\";\n            }\n\n            public int ParameterlessAction()\n            {\n                return 53;\n            }\n\n            public void VoidAction(int i, string s, DateTime dt)\n            {\n                _i = i;\n                _s = s;\n                _dt = dt;\n            }\n\n            public static int StaticAction()\n            {\n                return 89;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ActionMethodSelectorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Linq.Expressions;\nusing System.Reflection;\nusing System.Reflection.Emit;\nusing System.Web.Mvc.Routing;\nusing System.Web.Routing;\nusing System.Web.Routing.Test;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ActionMethodSelectorTest\n    {\n        [Fact]\n        public void AliasedMethodsProperty()\n        {\n            // Arrange\n            Type controllerType = typeof(MethodLocatorController);\n\n            // Act\n            ActionMethodSelector selector = new ActionMethodSelector(controllerType);\n\n            // Assert\n            Assert.Equal(2, selector.AliasedMethods.Length);\n\n            List<MethodInfo> sortedAliasedMethods = selector.AliasedMethods.OrderBy(methodInfo => methodInfo.Name).ToList();\n            Assert.Equal(\"Bar\", sortedAliasedMethods[0].Name);\n            Assert.Equal(\"FooRenamed\", sortedAliasedMethods[1].Name);\n        }\n\n        [Fact]\n        public void ControllerTypeProperty()\n        {\n            // Arrange\n            Type controllerType = typeof(MethodLocatorController);\n            ActionMethodSelector selector = new ActionMethodSelector(controllerType);\n\n            // Act & Assert\n            Assert.Same(controllerType, selector.ControllerType);\n        }\n\n        [Fact]\n        public void FindActionMethodReturnsMatchingMethodIfOneMethodMatches()\n        {\n            // Arrange\n            Type controllerType = typeof(SelectionAttributeController);\n            ActionMethodSelector selector = new ActionMethodSelector(controllerType);\n\n            // Act\n            MethodInfo matchedMethod = selector.FindActionMethod(new ControllerContext(), \"OneMatch\");\n\n            // Assert\n            Assert.Equal(\"OneMatch\", matchedMethod.Name);\n            Assert.Equal(typeof(string), matchedMethod.GetParameters()[0].ParameterType);\n        }\n\n        [Fact]\n        public void FindActionMethodReturnsMethodWithActionSelectionAttributeIfMultipleMethodsMatchRequest()\n        {\n            // DevDiv Bugs 212062: If multiple action methods match a request, we should match only the methods with an\n            // [ActionMethod] attribute since we assume those methods are more specific.\n\n            // Arrange\n            Type controllerType = typeof(SelectionAttributeController);\n            ActionMethodSelector selector = new ActionMethodSelector(controllerType);\n\n            // Act\n            MethodInfo matchedMethod = selector.FindActionMethod(new ControllerContext(), \"ShouldMatchMethodWithSelectionAttribute\");\n\n            // Assert\n            Assert.Equal(\"MethodHasSelectionAttribute1\", matchedMethod.Name);\n        }\n\n        [Fact]\n        public void FindActionMethodReturnsMethodWithoutAttributeWhenOthersOptOut()\n        {\n            // Arrange\n            Type controllerType = typeof(ControllerMatchMiddleNoAttribute);\n            ActionMethodSelector selector = new ActionMethodSelector(controllerType);\n\n            // Act\n            MethodInfo matchedMethod = selector.FindActionMethod(new ControllerContext(), \"MiddleMatch\");\n\n            // Assert\n            Assert.Equal(\"MiddleMatch\", matchedMethod.Name);\n        }\n\n        [Fact]\n        public void FindActionMethodReturnsMethodWithAttributeWhenOthersOptOutAndNoAttribute()\n        {\n            // Arrange\n            Type controllerType = typeof(ControllerMatchMiddleWithAttribute);\n            ActionMethodSelector selector = new ActionMethodSelector(controllerType);\n\n            // Act\n            MethodInfo matchedMethod = selector.FindActionMethod(new ControllerContext(), \"MiddleMatch\");\n\n            // Assert\n            Assert.Equal(\"MiddleMatch\", matchedMethod.Name);\n        }\n\n        [Fact]\n        public void FindActionMethodReturnsMethodMultipleMatchesOverOneOptOut()\n        {\n            // Arrange\n            Type controllerType = typeof(ControllerMatchMultipleAttributes);\n            ActionMethodSelector selector = new ActionMethodSelector(controllerType);\n\n            // Act\n            MethodInfo matchedMethod = selector.FindActionMethod(new ControllerContext(), \"Match\");\n\n            // Assert\n            Assert.Equal(\"Match\", matchedMethod.Name);\n        }\n\n        [Fact]\n        public void FindActionMethodReturnsNullIfNoMethodMatches()\n        {\n            // Arrange\n            Type controllerType = typeof(SelectionAttributeController);\n            ActionMethodSelector selector = new ActionMethodSelector(controllerType);\n\n            // Act\n            MethodInfo matchedMethod = selector.FindActionMethod(new ControllerContext(), \"ZeroMatch\");\n\n            // Assert\n            Assert.Null(matchedMethod);\n        }\n\n        [Fact]\n        public void FindActionMethod_IgnoresDirectRouteAttributedMethods()\n        {\n            // Arrange\n            Type controllerType = typeof(WithRoutingAttributeController);\n            ActionMethodSelector selector = new ActionMethodSelector(controllerType);\n\n            // This simulates what AttributeRoutingMapper will do\n            selector.StandardRouteMethods.Remove(controllerType.GetMethod(\"ActionWithoutRoute\"));\n            selector.StandardRouteMethods.Remove(controllerType.GetMethod(\"DirectRouteOnly\"));\n\n            // Act\n            MethodInfo matchedMethod = selector.FindActionMethod(new ControllerContext(), \"Action\");\n\n            // Assert\n            Assert.NotNull(matchedMethod);\n            Assert.Equal(\"Action\", matchedMethod.Name);\n        }\n\n        [Fact]\n        public void FindActionMethod_IgnoresDirectRouteAttributedMethods_NoMatch()\n        {\n            // Arrange\n            Type controllerType = typeof(WithRoutingAttributeController);\n            ActionMethodSelector selector = new ActionMethodSelector(controllerType);\n\n            // This simulates what AttributeRoutingMapper will do\n            selector.StandardRouteMethods.Remove(controllerType.GetMethod(\"ActionWithoutRoute\"));\n            selector.StandardRouteMethods.Remove(controllerType.GetMethod(\"DirectRouteOnly\"));\n\n            // Act\n            MethodInfo matchedMethod = selector.FindActionMethod(new ControllerContext(), \"DirectRouteOnly\");\n\n            // Assert\n            Assert.Null(matchedMethod);\n        }\n\n        [Fact]\n        public void FindActionMethodThrowsIfMultipleMethodsMatch()\n        {\n            // Arrange\n            Type controllerType = typeof(SelectionAttributeController);\n            ActionMethodSelector selector = new ActionMethodSelector(controllerType);\n\n            // Act & veriy\n            Assert.Throws<AmbiguousMatchException>(\n                delegate { selector.FindActionMethod(new ControllerContext(), \"TwoMatch\"); },\n                \"The current request for action 'TwoMatch' on controller type 'SelectionAttributeController' is ambiguous between the following action methods:\" + Environment.NewLine\n              + \"Void TwoMatch2() on type System.Web.Mvc.Test.ActionMethodSelectorTest+SelectionAttributeController\" + Environment.NewLine\n              + \"Void TwoMatch() on type System.Web.Mvc.Test.ActionMethodSelectorTest+SelectionAttributeController\");\n        }\n\n        [Fact]\n        public void NonAliasedMethodsProperty()\n        {\n            // Arrange\n            Type controllerType = typeof(MethodLocatorController);\n\n            // Act\n            ActionMethodSelector selector = new ActionMethodSelector(controllerType);\n\n            // Assert\n            Assert.Single(selector.NonAliasedMethods);\n\n            List<MethodInfo> sortedMethods = selector.NonAliasedMethods[\"foo\"].OrderBy(methodInfo => methodInfo.GetParameters().Length).ToList();\n            Assert.Equal(\"Foo\", sortedMethods[0].Name);\n            Assert.Empty(sortedMethods[0].GetParameters());\n            Assert.Equal(\"Foo\", sortedMethods[1].Name);\n            Assert.Equal(typeof(string), sortedMethods[1].GetParameters()[0].ParameterType);\n        }\n\n        private class MethodLocatorController : Controller\n        {\n            public void Foo()\n            {\n            }\n\n            public void Foo(string s)\n            {\n            }\n\n            [ActionName(\"Foo\")]\n            public void FooRenamed()\n            {\n            }\n\n            [ActionName(\"Bar\")]\n            public void Bar()\n            {\n            }\n\n            [ActionName(\"PrivateVoid\")]\n            private void PrivateVoid()\n            {\n            }\n\n            protected void ProtectedVoidAction()\n            {\n            }\n\n            public static void StaticMethod()\n            {\n            }\n\n            // ensure that methods inheriting from Controller or a base class are not matched\n            [ActionName(\"Blah\")]\n            protected override void ExecuteCore()\n            {\n                throw new NotImplementedException();\n            }\n\n            public string StringProperty { get; set; }\n\n#pragma warning disable 0067\n            public event EventHandler<EventArgs> SomeEvent;\n#pragma warning restore 0067\n        }\n\n        private class ControllerMatchMiddleNoAttribute : Controller\n        {\n            [Match(false)]\n            [ActionName(\"MiddleMatch\")]\n            public void SkipMatchBefore()\n            {\n            }\n\n            public void MiddleMatch()\n            {\n            }\n\n            [Match(false)]\n            [ActionName(\"MiddleMatch\")]\n            public void SkipMatchAfter()\n            {\n            }\n        }\n\n        private class ControllerMatchMultipleAttributes : Controller\n        {\n            [Match(false)]\n            [Match(true)]\n            [ActionName(\"Match\")]\n            public void SkipMatchBeforeOneOptOut()\n            {\n            }\n\n            [Match(true)]\n            [Match(true)]\n            public void Match()\n            {\n            }\n\n            [ActionName(\"Match\")]\n            public void SkipMatchAfterNoAttribute()\n            {\n            }\n        }\n\n        private class ControllerMatchMiddleWithAttribute : Controller\n        {\n            [Match(false)]\n            [ActionName(\"MiddleMatch\")]\n            public void SkipMatchBeforeNonMatch()\n            {\n            }\n\n            [ActionName(\"MiddleMatch\")]\n            public void SkipMatchBeforeNoSelection()\n            {\n            }\n\n            [Match(true)]\n            public void MiddleMatch()\n            {\n            }\n\n            [ActionName(\"MiddleMatch\")]\n            public void SkipMatchAfterNoSelection()\n            {\n            }\n\n            [Match(false)]\n            [ActionName(\"MiddleMatch\")]\n            public void SkipMatchAfterNonMatch()\n            {\n            }\n        }\n\n        private class SelectionAttributeController : Controller\n        {\n            [Match(false)]\n            public void OneMatch()\n            {\n            }\n\n            public void OneMatch(string s)\n            {\n            }\n\n            public void TwoMatch()\n            {\n            }\n\n            [ActionName(\"TwoMatch\")]\n            public void TwoMatch2()\n            {\n            }\n\n            [Match(true), ActionName(\"ShouldMatchMethodWithSelectionAttribute\")]\n            public void MethodHasSelectionAttribute1()\n            {\n            }\n\n            [ActionName(\"ShouldMatchMethodWithSelectionAttribute\")]\n            public void MethodDoesNotHaveSelectionAttribute1()\n            {\n            }\n        }\n\n        private class WithRoutingAttributeController : Controller\n        {\n            [Route(\"route\")]\n            [ActionName(\"Action\")] // to make things confusing\n            public void ActionWithoutRoute()\n            {\n            }\n\n            public void Action()\n            {\n            }\n\n            [Route(\"routeonly\")]\n            public void DirectRouteOnly()\n            {\n            }\n        }\n\n        [AttributeUsage(AttributeTargets.All, AllowMultiple = true)]\n        private class MatchAttribute : ActionMethodSelectorAttribute\n        {\n            private bool _match;\n\n            public MatchAttribute(bool match)\n            {\n                _match = match;\n            }\n\n            public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)\n            {\n                return _match;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ActionNameAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ActionNameAttributeTest\n    {\n        [Fact]\n        public void ConstructorThrowsIfNameIsEmpty()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { new ActionNameAttribute(String.Empty); }, \"name\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfNameIsNull()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { new ActionNameAttribute(null); }, \"name\");\n        }\n\n        [Fact]\n        public void IsValidForRequestReturnsFalseIfGivenNameDoesNotMatch()\n        {\n            // Arrange\n            ActionNameAttribute attr = new ActionNameAttribute(\"Bar\");\n\n            // Act\n            bool returned = attr.IsValidName(null, \"foo\", null);\n\n            // Assert\n            Assert.False(returned);\n        }\n\n        [Fact]\n        public void IsValidForRequestReturnsTrueIfGivenNameMatches()\n        {\n            // Arrange\n            ActionNameAttribute attr = new ActionNameAttribute(\"Bar\");\n\n            // Act\n            bool returned = attr.IsValidName(null, \"bar\", null);\n\n            // Assert\n            Assert.True(returned);\n        }\n\n        [Fact]\n        public void NameProperty()\n        {\n            // Arrange\n            ActionNameAttribute attr = new ActionNameAttribute(\"someName\");\n\n            // Act & Assert\n            Assert.Equal(\"someName\", attr.Name);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/AdditionalMetadataAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class AdditionalMetadataAttributeTest\n    {\n        [Fact]\n        public void GuardClauses()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                () => new AdditionalMetadataAttribute(null, new object()),\n                \"name\");\n\n            AdditionalMetadataAttribute attr = new AdditionalMetadataAttribute(\"key\", null);\n            Assert.ThrowsArgumentNull(\n                () => attr.OnMetadataCreated(null),\n                \"metadata\");\n        }\n\n        [Fact]\n        public void OnMetaDataCreatedSetsAdditionalValue()\n        {\n            // Arrange\n            string name = \"name\";\n            object value = new object();\n\n            ModelMetadata modelMetadata = new ModelMetadata(new Mock<ModelMetadataProvider>().Object, null, null, typeof(object), null);\n            AdditionalMetadataAttribute attr = new AdditionalMetadataAttribute(name, value);\n\n            // Act\n            attr.OnMetadataCreated(modelMetadata);\n\n            // Assert\n            Assert.Equal(modelMetadata.AdditionalValues[name], value);\n            Assert.Equal(attr.Name, name);\n            Assert.Equal(attr.Value, value);\n        }\n\n        [Fact]\n        public void MultipleAttributesCanSetValuesOnMetadata()\n        {\n            // Arrange\n            string name1 = \"name1\";\n            string name2 = \"name2\";\n\n            object value1 = new object();\n            object value2 = new object();\n            object value3 = new object();\n\n            ModelMetadata modelMetadata = new ModelMetadata(new Mock<ModelMetadataProvider>().Object, null, null, typeof(object), null);\n            AdditionalMetadataAttribute attr1 = new AdditionalMetadataAttribute(name1, value1);\n            AdditionalMetadataAttribute attr2 = new AdditionalMetadataAttribute(name2, value2);\n            AdditionalMetadataAttribute attr3 = new AdditionalMetadataAttribute(name1, value3);\n\n            // Act\n            attr1.OnMetadataCreated(modelMetadata);\n            attr2.OnMetadataCreated(modelMetadata);\n            attr3.OnMetadataCreated(modelMetadata);\n\n            // Assert\n            Assert.Equal(2, modelMetadata.AdditionalValues.Count);\n            Assert.Equal(modelMetadata.AdditionalValues[name1], value3);\n            Assert.Equal(modelMetadata.AdditionalValues[name2], value2);\n\n            Assert.NotEqual(attr1.TypeId, attr2.TypeId);\n            Assert.NotEqual(attr2.TypeId, attr3.TypeId);\n            Assert.NotEqual(attr3.TypeId, attr1.TypeId);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/AjaxHelperOfTModelTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class AjaxHelperOfTModelTest\n    {\n        [Fact]\n        public void ViewBagAndViewDataStayInSync()\n        {\n            // Arrange\n            Mock<IViewDataContainer> viewDataContainer = new Mock<IViewDataContainer>();\n            ViewDataDictionary viewDataDictionary = new ViewDataDictionary() { { \"A\", 1 } };\n            viewDataContainer.Setup(container => container.ViewData).Returns(viewDataDictionary);\n\n            // Act\n            AjaxHelper<object> ajaxHelper = new AjaxHelper<object>(new Mock<ViewContext>().Object, viewDataContainer.Object);\n            ajaxHelper.ViewData[\"B\"] = 2;\n            ajaxHelper.ViewBag.C = 3;\n\n            // Assert\n\n            // Original ViewData should not be modified by redfined ViewData and ViewBag\n            AjaxHelper nonGenericAjaxHelper = ajaxHelper;\n            Assert.Single(nonGenericAjaxHelper.ViewData.Keys);\n            Assert.Equal(1, nonGenericAjaxHelper.ViewData[\"A\"]);\n            Assert.Equal(1, nonGenericAjaxHelper.ViewBag.A);\n\n            // Redefined ViewData and ViewBag should be in sync\n            Assert.Equal(3, ajaxHelper.ViewData.Keys.Count);\n\n            Assert.Equal(1, ajaxHelper.ViewData[\"A\"]);\n            Assert.Equal(2, ajaxHelper.ViewData[\"B\"]);\n            Assert.Equal(3, ajaxHelper.ViewData[\"C\"]);\n\n            Assert.Equal(1, ajaxHelper.ViewBag.A);\n            Assert.Equal(2, ajaxHelper.ViewBag.B);\n            Assert.Equal(3, ajaxHelper.ViewBag.C);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/AjaxHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class AjaxHelperTest\n    {\n        [Fact]\n        public void ConstructorWithNullViewContextThrows()\n        {\n            // Assert\n            Assert.ThrowsArgumentNull(\n                delegate { AjaxHelper ajaxHelper = new AjaxHelper(null, new Mock<IViewDataContainer>().Object); },\n                \"viewContext\");\n        }\n\n        [Fact]\n        public void ConstructorWithNullViewDataContainerThrows()\n        {\n            // Assert\n            Assert.ThrowsArgumentNull(\n                delegate { AjaxHelper ajaxHelper = new AjaxHelper(new Mock<ViewContext>().Object, null); },\n                \"viewDataContainer\");\n        }\n\n        [Fact]\n        public void ConstructorSetsProperties1()\n        {\n            // Arrange\n            ViewContext viewContext = new Mock<ViewContext>().Object;\n            IViewDataContainer vdc = new Mock<IViewDataContainer>().Object;\n\n            // Act\n            AjaxHelper ajaxHelper = new AjaxHelper(viewContext, vdc);\n\n            // Assert\n            Assert.Equal(viewContext, ajaxHelper.ViewContext);\n            Assert.Equal(vdc, ajaxHelper.ViewDataContainer);\n            Assert.Equal(RouteTable.Routes, ajaxHelper.RouteCollection);\n        }\n\n        [Fact]\n        public void ConstructorSetsProperties2()\n        {\n            // Arrange\n            ViewContext viewContext = new Mock<ViewContext>().Object;\n            IViewDataContainer vdc = new Mock<IViewDataContainer>().Object;\n            RouteCollection rc = new RouteCollection();\n\n            // Act\n            AjaxHelper ajaxHelper = new AjaxHelper(viewContext, vdc, rc);\n\n            // Assert\n            Assert.Equal(viewContext, ajaxHelper.ViewContext);\n            Assert.Equal(vdc, ajaxHelper.ViewDataContainer);\n            Assert.Equal(rc, ajaxHelper.RouteCollection);\n        }\n\n        [Fact]\n        public void GenericHelperConstructorSetsProperties1()\n        {\n            // Arrange\n            ViewContext viewContext = new Mock<ViewContext>().Object;\n            ViewDataDictionary<Controller> vdd = new ViewDataDictionary<Controller>(new Mock<Controller>().Object);\n            Mock<IViewDataContainer> vdc = new Mock<IViewDataContainer>();\n            vdc.Setup(v => v.ViewData).Returns(vdd);\n\n            // Act\n            AjaxHelper<Controller> ajaxHelper = new AjaxHelper<Controller>(viewContext, vdc.Object);\n\n            // Assert\n            Assert.Equal(viewContext, ajaxHelper.ViewContext);\n            Assert.Equal(vdc.Object, ajaxHelper.ViewDataContainer);\n            Assert.Equal(RouteTable.Routes, ajaxHelper.RouteCollection);\n            Assert.Equal(vdd.Model, ajaxHelper.ViewData.Model);\n        }\n\n        [Fact]\n        public void GenericHelperConstructorSetsProperties2()\n        {\n            // Arrange\n            ViewContext viewContext = new Mock<ViewContext>().Object;\n            ViewDataDictionary<Controller> vdd = new ViewDataDictionary<Controller>(new Mock<Controller>().Object);\n            Mock<IViewDataContainer> vdc = new Mock<IViewDataContainer>();\n            vdc.Setup(v => v.ViewData).Returns(vdd);\n            RouteCollection rc = new RouteCollection();\n\n            // Act\n            AjaxHelper<Controller> ajaxHelper = new AjaxHelper<Controller>(viewContext, vdc.Object, rc);\n\n            // Assert\n            Assert.Equal(viewContext, ajaxHelper.ViewContext);\n            Assert.Equal(vdc.Object, ajaxHelper.ViewDataContainer);\n            Assert.Equal(rc, ajaxHelper.RouteCollection);\n            Assert.Equal(vdd.Model, ajaxHelper.ViewData.Model);\n        }\n\n        [Fact]\n        public void GlobalizationScriptPathPropertyDefault()\n        {\n            try\n            {\n                // Act\n                AjaxHelper.GlobalizationScriptPath = null;\n\n                // Assert\n                Assert.Equal(\"~/Scripts/Globalization\", AjaxHelper.GlobalizationScriptPath);\n            }\n            finally\n            {\n                AjaxHelper.GlobalizationScriptPath = null;\n            }\n        }\n\n        [Fact]\n        public void GlobalizationScriptPathPropertySet()\n        {\n            try\n            {\n                // Act\n                AjaxHelper.GlobalizationScriptPath = \"/Foo/Bar\";\n\n                // Assert\n                Assert.Equal(\"/Foo/Bar\", AjaxHelper.GlobalizationScriptPath);\n            }\n            finally\n            {\n                AjaxHelper.GlobalizationScriptPath = null;\n            }\n        }\n\n        [Fact]\n        public void JavaScriptStringEncodeReturnsEmptyStringIfMessageIsEmpty()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper();\n\n            // Act\n            string encoded = ajaxHelper.JavaScriptStringEncode(String.Empty);\n\n            // Assert\n            Assert.Equal(String.Empty, encoded);\n        }\n\n        [Fact]\n        public void JavaScriptStringEncodeReturnsEncodedMessage()\n        {\n            // Arrange\n            string message = \"I said, \\\"Hello, world!\\\"\\nHow are you?\";\n            AjaxHelper ajaxHelper = GetAjaxHelper();\n\n            // Act\n            string encoded = ajaxHelper.JavaScriptStringEncode(message);\n\n            // Assert\n            Assert.Equal(@\"I said, \\\"\"Hello, world!\\\"\"\\nHow are you?\", encoded);\n        }\n\n        [Fact]\n        public void JavaScriptStringEncodeReturnsNullIfMessageIsNull()\n        {\n            // Arrange\n            AjaxHelper ajaxHelper = GetAjaxHelper();\n\n            // Act\n            string encoded = ajaxHelper.JavaScriptStringEncode(null /* message */);\n\n            // Assert\n            Assert.Null(encoded);\n        }\n\n        [Fact]\n        public void ViewBagProperty_ReflectsViewData()\n        {\n            // Arrange\n            ViewDataDictionary viewDataDictionary = new ViewDataDictionary() { { \"A\", 1 } };\n            Mock<IViewDataContainer> viewDataContainer = new Mock<IViewDataContainer>();\n            viewDataContainer.Setup(container => container.ViewData).Returns(viewDataDictionary);\n\n            // Act\n            AjaxHelper ajaxHelper = new AjaxHelper(new Mock<ViewContext>().Object, viewDataContainer.Object);\n\n            // Assert\n            Assert.Equal(1, ajaxHelper.ViewBag.A);\n        }\n\n        [Fact]\n        public void ViewBagProperty_ReflectsNewViewDataContainerInstance()\n        {\n            // Arrange\n            ViewDataDictionary viewDataDictionary = new ViewDataDictionary() { { \"A\", 1 } };\n            Mock<IViewDataContainer> viewDataContainer = new Mock<IViewDataContainer>();\n            viewDataContainer.Setup(container => container.ViewData).Returns(viewDataDictionary);\n\n            ViewDataDictionary otherViewDataDictionary = new ViewDataDictionary() { { \"A\", 2 } };\n            Mock<IViewDataContainer> otherViewDataContainer = new Mock<IViewDataContainer>();\n            otherViewDataContainer.Setup(container => container.ViewData).Returns(otherViewDataDictionary);\n\n            AjaxHelper ajaxHelper = new AjaxHelper(new Mock<ViewContext>().Object, viewDataContainer.Object, new RouteCollection());\n\n            // Act\n            ajaxHelper.ViewDataContainer = otherViewDataContainer.Object;\n\n            // Assert\n            Assert.Equal(2, ajaxHelper.ViewBag.A);\n        }\n\n        [Fact]\n        public void ViewBag_PropagatesChangesToViewData()\n        {\n            // Arrange\n            ViewDataDictionary viewDataDictionary = new ViewDataDictionary() { { \"A\", 1 } };\n            Mock<IViewDataContainer> viewDataContainer = new Mock<IViewDataContainer>();\n            viewDataContainer.Setup(container => container.ViewData).Returns(viewDataDictionary);\n\n            AjaxHelper ajaxHelper = new AjaxHelper(new Mock<ViewContext>().Object, viewDataContainer.Object, new RouteCollection());\n\n            // Act\n            ajaxHelper.ViewBag.A = \"foo\";\n            ajaxHelper.ViewBag.B = 2;\n\n            // Assert\n            Assert.Equal(\"foo\", ajaxHelper.ViewData[\"A\"]);\n            Assert.Equal(2, ajaxHelper.ViewData[\"B\"]);\n        }\n\n        private static AjaxHelper GetAjaxHelper()\n        {\n            ViewContext viewContext = new Mock<ViewContext>().Object;\n            IViewDataContainer viewDataContainer = new Mock<IViewDataContainer>().Object;\n            return new AjaxHelper(viewContext, viewDataContainer);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/AjaxRequestExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class AjaxRequestExtensionsTest\n    {\n        [Fact]\n        public void IsAjaxRequestWithNullRequestThrows()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { AjaxRequestExtensions.IsAjaxRequest(null); }, \"request\");\n        }\n\n        [Fact]\n        public void IsAjaxRequestWithKeyIsTrue()\n        {\n            // Arrange\n            Mock<HttpRequestBase> mockRequest = new Mock<HttpRequestBase>();\n            mockRequest.Setup(r => r[\"X-Requested-With\"]).Returns(\"XMLHttpRequest\").Verifiable();\n            HttpRequestBase request = mockRequest.Object;\n\n            // Act\n            bool retVal = AjaxRequestExtensions.IsAjaxRequest(request);\n\n            // Assert\n            Assert.True(retVal);\n            mockRequest.Verify();\n        }\n\n        [Fact]\n        public void IsAjaxRequestWithoutKeyOrHeaderIsFalse()\n        {\n            // Arrange\n            Mock<HttpRequestBase> mockRequest = new Mock<HttpRequestBase>();\n            NameValueCollection headerCollection = new NameValueCollection();\n            mockRequest.Setup(r => r.Headers).Returns(headerCollection).Verifiable();\n            mockRequest.Setup(r => r[\"X-Requested-With\"]).Returns((string)null).Verifiable();\n            HttpRequestBase request = mockRequest.Object;\n\n            // Act\n            bool retVal = AjaxRequestExtensions.IsAjaxRequest(request);\n\n            // Assert\n            Assert.False(retVal);\n            mockRequest.Verify();\n        }\n\n        [Fact]\n        public void IsAjaxRequestReturnsTrueIfHeaderSet()\n        {\n            // Arrange\n            Mock<HttpRequestBase> mockRequest = new Mock<HttpRequestBase>();\n            NameValueCollection headerCollection = new NameValueCollection();\n            headerCollection[\"X-Requested-With\"] = \"XMLHttpRequest\";\n            mockRequest.Setup(r => r.Headers).Returns(headerCollection).Verifiable();\n            HttpRequestBase request = mockRequest.Object;\n\n            // Act\n            bool retVal = AjaxRequestExtensions.IsAjaxRequest(request);\n\n            // Assert\n            Assert.True(retVal);\n            mockRequest.Verify();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/AllowHtmlAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class AllowHtmlAttributeTest\n    {\n        [Fact]\n        public void OnMetadataCreated_ThrowsIfMetadataIsNull()\n        {\n            // Arrange\n            AllowHtmlAttribute attr = new AllowHtmlAttribute();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { attr.OnMetadataCreated(null); }, \"metadata\");\n        }\n\n        [Fact]\n        public void OnMetadataCreated()\n        {\n            // Arrange\n            ModelMetadata modelMetadata = new ModelMetadata(new Mock<ModelMetadataProvider>().Object, null, null, typeof(object), \"SomeProperty\");\n            AllowHtmlAttribute attr = new AllowHtmlAttribute();\n\n            // Act\n            bool originalValue = modelMetadata.RequestValidationEnabled;\n            attr.OnMetadataCreated(modelMetadata);\n            bool newValue = modelMetadata.RequestValidationEnabled;\n\n            // Assert\n            Assert.True(originalValue);\n            Assert.False(newValue);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/AreaHelpersTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class AreaHelpersTest\n    {\n        [Fact]\n        public void GetAreaNameFromAreaRouteCollectionRoute()\n        {\n            // Arrange\n            RouteCollection routes = new RouteCollection();\n            AreaRegistrationContext context = new AreaRegistrationContext(\"area_name\", routes);\n            Route route = context.MapRoute(null, \"the_url\");\n\n            // Act\n            string areaName = AreaHelpers.GetAreaName(route);\n\n            // Assert\n            Assert.Equal(\"area_name\", areaName);\n        }\n\n        [Fact]\n        public void GetAreaNameFromIAreaAssociatedItem()\n        {\n            // Arrange\n            CustomRouteWithArea route = new CustomRouteWithArea();\n\n            // Act\n            string areaName = AreaHelpers.GetAreaName(route);\n\n            // Assert\n            Assert.Equal(\"area_name\", areaName);\n        }\n\n        [Fact]\n        public void GetAreaNameFromRouteData()\n        {\n            // Arrange\n            RouteData routeData = new RouteData();\n            routeData.DataTokens[\"area\"] = \"area_name\";\n\n            // Act\n            string areaName = AreaHelpers.GetAreaName(routeData);\n\n            // Assert\n            Assert.Equal(\"area_name\", areaName);\n        }\n\n        [Fact]\n        public void GetAreaNameFromRouteDataFallsBackToRoute()\n        {\n            // Arrange\n            RouteCollection routes = new RouteCollection();\n            AreaRegistrationContext context = new AreaRegistrationContext(\"area_name\", routes);\n            Route route = context.MapRoute(null, \"the_url\");\n            RouteData routeData = new RouteData(route, new MvcRouteHandler());\n\n            // Act\n            string areaName = AreaHelpers.GetAreaName(routeData);\n\n            // Assert\n            Assert.Equal(\"area_name\", areaName);\n        }\n\n        [Fact]\n        public void GetAreaNameReturnsNullIfRouteNotAreaAware()\n        {\n            // Arrange\n            Route route = new Route(\"the_url\", new MvcRouteHandler());\n\n            // Act\n            string areaName = AreaHelpers.GetAreaName(route);\n\n            // Assert\n            Assert.Null(areaName);\n        }\n\n        private class CustomRouteWithArea : RouteBase, IRouteWithArea\n        {\n            public string Area\n            {\n                get { return \"area_name\"; }\n            }\n\n            public override RouteData GetRouteData(HttpContextBase httpContext)\n            {\n                throw new NotImplementedException();\n            }\n\n            public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/AreaRegistrationContextTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class AreaRegistrationContextTest\n    {\n        [Fact]\n        public void ConstructorSetsProperties()\n        {\n            // Arrange\n            string areaName = \"the_area\";\n            RouteCollection routes = new RouteCollection();\n\n            // Act\n            AreaRegistrationContext context = new AreaRegistrationContext(areaName, routes);\n\n            // Assert\n            Assert.Equal(areaName, context.AreaName);\n            Assert.Same(routes, context.Routes);\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfAreaNameIsEmpty()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { new AreaRegistrationContext(\"\", new RouteCollection()); }, \"areaName\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfAreaNameIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { new AreaRegistrationContext(null, new RouteCollection()); }, \"areaName\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfRoutesIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new AreaRegistrationContext(\"the_area\", null); }, \"routes\");\n        }\n\n        [Fact]\n        public void MapRouteWithEmptyStringNamespaces()\n        {\n            // Arrange\n            string[] implicitNamespaces = new string[] { \"implicit_1\", \"implicit_2\" };\n            string[] explicitNamespaces = new string[0];\n\n            RouteCollection routes = new RouteCollection();\n            AreaRegistrationContext context = new AreaRegistrationContext(\"the_area\", routes);\n            ReplaceCollectionContents(context.Namespaces, implicitNamespaces);\n\n            // Act\n            Route route = context.MapRoute(\"the_name\", \"the_url\", explicitNamespaces);\n\n            // Assert\n            Assert.Equal(route, routes[\"the_name\"]);\n            Assert.Equal(\"the_area\", route.DataTokens[\"area\"]);\n            Assert.Equal((object)true, route.DataTokens[\"UseNamespaceFallback\"]);\n            Assert.Null(route.DataTokens[\"namespaces\"]);\n        }\n\n        [Fact]\n        public void MapRouteWithExplicitNamespaces()\n        {\n            // Arrange\n            string[] implicitNamespaces = new string[] { \"implicit_1\", \"implicit_2\" };\n            string[] explicitNamespaces = new string[] { \"explicit_1\", \"explicit_2\" };\n\n            RouteCollection routes = new RouteCollection();\n            AreaRegistrationContext context = new AreaRegistrationContext(\"the_area\", routes);\n            ReplaceCollectionContents(context.Namespaces, implicitNamespaces);\n\n            // Act\n            Route route = context.MapRoute(\"the_name\", \"the_url\", explicitNamespaces);\n\n            // Assert\n            Assert.Equal(route, routes[\"the_name\"]);\n            Assert.Equal(\"the_area\", route.DataTokens[\"area\"]);\n            Assert.Equal((object)false, route.DataTokens[\"UseNamespaceFallback\"]);\n            Assert.Equal(explicitNamespaces, (string[])route.DataTokens[\"namespaces\"]);\n        }\n\n        [Fact]\n        public void MapRouteWithImplicitNamespaces()\n        {\n            // Arrange\n            string[] implicitNamespaces = new string[] { \"implicit_1\", \"implicit_2\" };\n            string[] explicitNamespaces = new string[] { \"explicit_1\", \"explicit_2\" };\n\n            RouteCollection routes = new RouteCollection();\n            AreaRegistrationContext context = new AreaRegistrationContext(\"the_area\", routes);\n            ReplaceCollectionContents(context.Namespaces, implicitNamespaces);\n\n            // Act\n            Route route = context.MapRoute(\"the_name\", \"the_url\");\n\n            // Assert\n            Assert.Equal(route, routes[\"the_name\"]);\n            Assert.Equal(\"the_area\", route.DataTokens[\"area\"]);\n            Assert.Equal((object)false, route.DataTokens[\"UseNamespaceFallback\"]);\n            Assert.Equal(implicitNamespaces, (string[])route.DataTokens[\"namespaces\"]);\n        }\n\n        [Fact]\n        public void MapRouteWithoutNamespaces()\n        {\n            // Arrange\n            RouteCollection routes = new RouteCollection();\n            AreaRegistrationContext context = new AreaRegistrationContext(\"the_area\", routes);\n\n            // Act\n            Route route = context.MapRoute(\"the_name\", \"the_url\");\n\n            // Assert\n            Assert.Equal(route, routes[\"the_name\"]);\n            Assert.Equal(\"the_area\", route.DataTokens[\"area\"]);\n            Assert.Null(route.DataTokens[\"namespaces\"]);\n            Assert.Equal((object)true, route.DataTokens[\"UseNamespaceFallback\"]);\n        }\n\n        private static void ReplaceCollectionContents(ICollection<string> collectionToReplace, IEnumerable<string> newContents)\n        {\n            collectionToReplace.Clear();\n            foreach (string item in newContents)\n            {\n                collectionToReplace.Add(item);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/AreaRegistrationTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class AreaRegistrationTest\n    {\n        [Fact]\n        public void CreateContextAndRegister()\n        {\n            // Arrange\n            string[] expectedNamespaces = new string[] { \"System.Web.Mvc.Test.*\" };\n\n            RouteCollection routes = new RouteCollection();\n            MyAreaRegistration registration = new MyAreaRegistration();\n\n            // Act\n            registration.CreateContextAndRegister(routes, \"some state\");\n\n            // Assert\n            Assert.Equal(expectedNamespaces, registration.Namespaces);\n            Assert.Equal(\"some state\", registration.State);\n        }\n\n        [Fact]\n        public void RegisterAllAreas()\n        {\n            // Arrange\n            string[] expectedLoadedAreas = new string[] { \"AreaRegistrationTest_AreaRegistration\" };\n            AnnotatedRouteCollection routes = new AnnotatedRouteCollection();\n            MockBuildManager buildManager = new MockBuildManager(new Assembly[] { typeof(AreaRegistrationTest).Assembly });\n\n            // Act\n            AreaRegistration.RegisterAllAreas(routes, buildManager, null);\n\n            // Assert\n            Assert.Equal(expectedLoadedAreas, routes._areasLoaded.ToArray());\n        }\n\n        private class MyAreaRegistration : AreaRegistration\n        {\n            public string[] Namespaces;\n            public object State;\n\n            public override string AreaName\n            {\n                get { return \"my_area\"; }\n            }\n\n            public override void RegisterArea(AreaRegistrationContext context)\n            {\n                Namespaces = context.Namespaces.ToArray();\n                State = context.State;\n            }\n        }\n    }\n\n    public class AnnotatedRouteCollection : RouteCollection\n    {\n        public List<string> _areasLoaded = new List<string>();\n    }\n\n    public abstract class AreaRegistrationTest_AbstractAreaRegistration : AreaRegistration\n    {\n        public override string AreaName\n        {\n            get { return \"the_area\"; }\n        }\n\n        public override void RegisterArea(AreaRegistrationContext context)\n        {\n            ((AnnotatedRouteCollection)context.Routes)._areasLoaded.Add(\"AreaRegistrationTest_AbstractAreaRegistration\");\n        }\n    }\n\n    public class AreaRegistrationTest_AreaRegistration : AreaRegistrationTest_AbstractAreaRegistration\n    {\n        public override void RegisterArea(AreaRegistrationContext context)\n        {\n            ((AnnotatedRouteCollection)context.Routes)._areasLoaded.Add(\"AreaRegistrationTest_AreaRegistration\");\n        }\n    }\n\n    public class AreaRegistrationTest_NoConstructorAreaRegistration : AreaRegistrationTest_AreaRegistration\n    {\n        private AreaRegistrationTest_NoConstructorAreaRegistration()\n        {\n        }\n\n        public override void RegisterArea(AreaRegistrationContext context)\n        {\n            ((AnnotatedRouteCollection)context.Routes)._areasLoaded.Add(\"AreaRegistrationTest_NoConstructorAreaRegistration\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/AssociatedMetadataProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class AssociatedMetadataProviderTest\n    {\n        // FilterAttributes\n\n        [Fact]\n        public void ReadOnlyAttributeIsFilteredOffWhenContainerTypeIsViewPage()\n        {\n            // Arrange\n            TestableAssociatedMetadataProvider provider = new TestableAssociatedMetadataProvider();\n\n            // Act\n            provider.GetMetadataForProperty(() => null, typeof(ViewPage<PropertyModel>), \"Model\");\n\n            // Assert\n            CreateMetadataParams parms = provider.CreateMetadataLog.Single();\n            Assert.DoesNotContain(parms.Attributes, a => a is ReadOnlyAttribute);\n        }\n\n        [Fact]\n        public void ReadOnlyAttributeIsFilteredOffWhenContainerTypeIsViewUserControl()\n        {\n            // Arrange\n            TestableAssociatedMetadataProvider provider = new TestableAssociatedMetadataProvider();\n\n            // Act\n            provider.GetMetadataForProperty(() => null, typeof(ViewUserControl<PropertyModel>), \"Model\");\n\n            // Assert\n            CreateMetadataParams parms = provider.CreateMetadataLog.Single();\n            Assert.DoesNotContain(parms.Attributes, a => a is ReadOnlyAttribute);\n        }\n\n        [Fact]\n        public void ReadOnlyAttributeIsPreservedForReadOnlyModelProperties()\n        {\n            // Arrange\n            TestableAssociatedMetadataProvider provider = new TestableAssociatedMetadataProvider();\n\n            // Act\n            provider.GetMetadataForProperty(() => null, typeof(ModelWithReadOnlyProperty), \"ReadOnlyProperty\");\n\n            // Assert\n            CreateMetadataParams parms = provider.CreateMetadataLog.Single();\n            Assert.Contains(parms.Attributes, a => a is ReadOnlyAttribute);\n        }\n\n        // GetMetadataForProperties\n\n        [Fact]\n        public void GetMetadataForPropertiesNullContainerTypeThrows()\n        {\n            // Arrange\n            TestableAssociatedMetadataProvider provider = new TestableAssociatedMetadataProvider();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => provider.GetMetadataForProperties(new Object(), null),\n                \"containerType\");\n        }\n\n        [Fact]\n        public void GetMetadataForPropertiesCreatesMetadataForAllPropertiesOnModelWithPropertyValues()\n        {\n            // Arrange\n            PropertyModel model = new PropertyModel { LocalAttributes = 42, MetadataAttributes = \"hello\", MixedAttributes = 21.12 };\n            TestableAssociatedMetadataProvider provider = new TestableAssociatedMetadataProvider();\n\n            // Act\n            provider.GetMetadataForProperties(model, typeof(PropertyModel)).ToList(); // Call ToList() to force the lazy evaluation to evaluate\n\n            // Assert\n            CreateMetadataParams local =\n                provider.CreateMetadataLog.Single(m => m.ContainerType == typeof(PropertyModel) &&\n                                                       m.PropertyName == \"LocalAttributes\");\n            Assert.Equal(typeof(int), local.ModelType);\n            Assert.Equal(42, local.Model);\n            Assert.Contains(local.Attributes, a => a is RequiredAttribute);\n\n            CreateMetadataParams metadata =\n                provider.CreateMetadataLog.Single(m => m.ContainerType == typeof(PropertyModel) &&\n                                                       m.PropertyName == \"MetadataAttributes\");\n            Assert.Equal(typeof(string), metadata.ModelType);\n            Assert.Equal(\"hello\", metadata.Model);\n            Assert.Contains(metadata.Attributes, a => a is RangeAttribute);\n\n            CreateMetadataParams mixed =\n                provider.CreateMetadataLog.Single(m => m.ContainerType == typeof(PropertyModel) &&\n                                                       m.PropertyName == \"MixedAttributes\");\n            Assert.Equal(typeof(double), mixed.ModelType);\n            Assert.Equal(21.12, mixed.Model);\n            Assert.Contains(mixed.Attributes, a => a is RequiredAttribute);\n            Assert.Contains(mixed.Attributes, a => a is RangeAttribute);\n        }\n\n        [Fact]\n        public void GetMetadataForPropertiesContainerTest()\n        {\n            // Arrange\n            PropertyModel model = new PropertyModel { LocalAttributes = 42, MetadataAttributes = \"hello\", MixedAttributes = 21.12 };\n            EmptyModelMetadataProvider provider = new EmptyModelMetadataProvider();\n\n            // Act\n            List<ModelMetadata> metadata = provider.GetMetadataForProperties(model, typeof(PropertyModel)).ToList();\n\n            // Assert\n            Assert.Equal(3, metadata.Count());\n            Assert.Same(model, metadata[0].Container);\n            Assert.Same(model, metadata[1].Container);\n            Assert.Same(model, metadata[2].Container);\n        }\n\n        [Fact]\n        public void GetMetadataForPropertyWithNullContainerReturnsMetadataWithNullValuesForProperties()\n        {\n            // Arrange\n            TestableAssociatedMetadataProvider provider = new TestableAssociatedMetadataProvider();\n\n            // Act\n            provider.GetMetadataForProperties(null, typeof(PropertyModel)).ToList(); // Call ToList() to force the lazy evaluation to evaluate\n\n            // Assert\n            Assert.True(provider.CreateMetadataLog.Any());\n            foreach (var parms in provider.CreateMetadataLog)\n            {\n                Assert.Null(parms.Model);\n            }\n        }\n\n        // GetMetadataForProperty\n\n        [Fact]\n        public void GetMetadataForPropertyNullContainerTypeThrows()\n        {\n            // Arrange\n            TestableAssociatedMetadataProvider provider = new TestableAssociatedMetadataProvider();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => provider.GetMetadataForProperty(null /* model */, null /* containerType */, \"propertyName\"),\n                \"containerType\");\n        }\n\n        [Fact]\n        public void GetMetadataForPropertyNullOrEmptyPropertyNameThrows()\n        {\n            // Arrange\n            TestableAssociatedMetadataProvider provider = new TestableAssociatedMetadataProvider();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => provider.GetMetadataForProperty(null /* model */, typeof(object), null /* propertyName */),\n                \"propertyName\");\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => provider.GetMetadataForProperty(null, typeof(object), String.Empty),\n                \"propertyName\");\n        }\n\n        [Fact]\n        public void GetMetadataForPropertyInvalidPropertyNameThrows()\n        {\n            // Arrange\n            TestableAssociatedMetadataProvider provider = new TestableAssociatedMetadataProvider();\n\n            // Act & Assert\n            Assert.Throws<ArgumentException>(\n                () => provider.GetMetadataForProperty(null, typeof(object), \"BadPropertyName\"),\n                \"The property System.Object.BadPropertyName could not be found.\");\n        }\n\n        [Fact]\n        public void GetMetadataForPropertyWithLocalAttributes()\n        {\n            // Arrange\n            TestableAssociatedMetadataProvider provider = new TestableAssociatedMetadataProvider();\n            ModelMetadata metadata = new ModelMetadata(provider, typeof(PropertyModel), null, typeof(int), \"LocalAttributes\");\n            provider.CreateMetadataReturnValue = metadata;\n\n            // Act\n            ModelMetadata result = provider.GetMetadataForProperty(null, typeof(PropertyModel), \"LocalAttributes\");\n\n            // Assert\n            Assert.Same(metadata, result);\n            Assert.Contains(provider.CreateMetadataLog.Single().Attributes, a => a is RequiredAttribute);\n        }\n\n        [Fact]\n        public void GetMetadataForPropertyWithMetadataAttributes()\n        {\n            // Arrange\n            TestableAssociatedMetadataProvider provider = new TestableAssociatedMetadataProvider();\n            ModelMetadata metadata = new ModelMetadata(provider, typeof(PropertyModel), null, typeof(string), \"MetadataAttributes\");\n            provider.CreateMetadataReturnValue = metadata;\n\n            // Act\n            ModelMetadata result = provider.GetMetadataForProperty(null, typeof(PropertyModel), \"MetadataAttributes\");\n\n            // Assert\n            Assert.Same(metadata, result);\n            CreateMetadataParams parms = provider.CreateMetadataLog.Single(p => p.PropertyName == \"MetadataAttributes\");\n            Assert.Contains(parms.Attributes, a => a is RangeAttribute);\n        }\n\n        [Fact]\n        public void GetMetadataForPropertyWithMixedAttributes()\n        {\n            // Arrange\n            TestableAssociatedMetadataProvider provider = new TestableAssociatedMetadataProvider();\n            ModelMetadata metadata = new ModelMetadata(provider, typeof(PropertyModel), null, typeof(double), \"MixedAttributes\");\n            provider.CreateMetadataReturnValue = metadata;\n\n            // Act\n            ModelMetadata result = provider.GetMetadataForProperty(null, typeof(PropertyModel), \"MixedAttributes\");\n\n            // Assert\n            Assert.Same(metadata, result);\n            CreateMetadataParams parms = provider.CreateMetadataLog.Single(p => p.PropertyName == \"MixedAttributes\");\n            Assert.Contains(parms.Attributes, a => a is RequiredAttribute);\n            Assert.Contains(parms.Attributes, a => a is RangeAttribute);\n        }\n\n        // GetMetadataForType\n\n        [Fact]\n        public void GetMetadataForTypeNullModelTypeThrows()\n        {\n            // Arrange\n            TestableAssociatedMetadataProvider provider = new TestableAssociatedMetadataProvider();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => provider.GetMetadataForType(() => new Object(), null),\n                \"modelType\");\n        }\n\n        [Fact]\n        public void GetMetadataForTypeIncludesAttributesOnType()\n        {\n            TestableAssociatedMetadataProvider provider = new TestableAssociatedMetadataProvider();\n            ModelMetadata metadata = new ModelMetadata(provider, null, null, typeof(TypeModel), null);\n            provider.CreateMetadataReturnValue = metadata;\n\n            // Act\n            ModelMetadata result = provider.GetMetadataForType(null, typeof(TypeModel));\n\n            // Assert\n            Assert.Same(metadata, result);\n            CreateMetadataParams parms = provider.CreateMetadataLog.Single(p => p.ModelType == typeof(TypeModel));\n            Assert.Contains(parms.Attributes, a => a is ReadOnlyAttribute);\n        }\n\n        [AdditionalMetadata(\"ClassName\", \"ClassValue\")]\n        class ClassWithAdditionalMetadata\n        {\n            [AdditionalMetadata(\"PropertyName\", \"PropertyValue\")]\n            public int MyProperty { get; set; }\n        }\n\n        [Fact]\n        public void MetadataAwareAttributeCanModifyTypeMetadata()\n        {\n            // Arrange\n            TestableAssociatedMetadataProvider provider = new TestableAssociatedMetadataProvider();\n            provider.CreateMetadataReturnValue = new ModelMetadata(provider, null, null, typeof(ClassWithAdditionalMetadata), null);\n\n            // Act\n            ModelMetadata metadata = provider.GetMetadataForType(null, typeof(ClassWithAdditionalMetadata));\n\n            // Assert\n            var kvp = metadata.AdditionalValues.Single();\n            Assert.Equal(\"ClassName\", kvp.Key);\n            Assert.Equal(\"ClassValue\", kvp.Value);\n        }\n\n        [Fact]\n        public void MetadataAwareAttributeCanModifyPropertyMetadata()\n        {\n            // Arrange\n            TestableAssociatedMetadataProvider provider = new TestableAssociatedMetadataProvider();\n            provider.CreateMetadataReturnValue = new ModelMetadata(provider, typeof(ClassWithAdditionalMetadata), null, typeof(int), \"MyProperty\");\n\n            // Act\n            ModelMetadata metadata = provider.GetMetadataForProperty(null, typeof(ClassWithAdditionalMetadata), \"MyProperty\");\n\n            // Assert\n            var kvp = metadata.AdditionalValues.Single();\n            Assert.Equal(\"PropertyName\", kvp.Key);\n            Assert.Equal(\"PropertyValue\", kvp.Value);\n        }\n\n        // Helpers\n\n        [MetadataType(typeof(Metadata))]\n        private class PropertyModel\n        {\n            [Required]\n            public int LocalAttributes { get; set; }\n\n            public string MetadataAttributes { get; set; }\n\n            [Required]\n            public double MixedAttributes { get; set; }\n\n            private class Metadata\n            {\n                [Range(10, 100)]\n                public object MetadataAttributes { get; set; }\n\n                [Range(10, 100)]\n                public object MixedAttributes { get; set; }\n            }\n        }\n\n        private class ModelWithReadOnlyProperty\n        {\n            public int ReadOnlyProperty { get; private set; }\n        }\n\n        [ReadOnly(true)]\n        private class TypeModel\n        {\n        }\n\n        class TestableAssociatedMetadataProvider : AssociatedMetadataProvider\n        {\n            public List<CreateMetadataParams> CreateMetadataLog = new List<CreateMetadataParams>();\n            public ModelMetadata CreateMetadataReturnValue = null;\n\n            protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType,\n                                                            Func<object> modelAccessor, Type modelType,\n                                                            string propertyName)\n            {\n                CreateMetadataLog.Add(new CreateMetadataParams\n                {\n                    Attributes = attributes,\n                    ContainerType = containerType,\n                    Model = modelAccessor == null ? null : modelAccessor(),\n                    ModelType = modelType,\n                    PropertyName = propertyName\n                });\n\n                return CreateMetadataReturnValue;\n            }\n        }\n\n        class CreateMetadataParams\n        {\n            public IEnumerable<Attribute> Attributes { get; set; }\n            public Type ContainerType { get; set; }\n            public object Model { get; set; }\n            public Type ModelType { get; set; }\n            public string PropertyName { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/AssociatedValidatorProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")] // Uses ModelMetadataProviders.Current\n    public class AssociatedValidatorProviderTest\n    {\n        [Fact]\n        public void GetValidatorsGuardClauses()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(object));\n            Mock<AssociatedValidatorProvider> provider = new Mock<AssociatedValidatorProvider> { CallBase = true };\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => provider.Object.GetValidators(null, new ControllerContext()),\n                \"metadata\");\n            Assert.ThrowsArgumentNull(\n                () => provider.Object.GetValidators(metadata, null),\n                \"context\");\n        }\n\n        [Fact]\n        public void GetValidatorsForPropertyWithLocalAttributes()\n        {\n            // Arrange\n            IEnumerable<Attribute> callbackAttributes = null;\n            ControllerContext context = new ControllerContext();\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(null, typeof(PropertyModel), \"LocalAttributes\");\n            Mock<TestableAssociatedValidatorProvider> provider = new Mock<TestableAssociatedValidatorProvider> { CallBase = true };\n            provider.Setup(p => p.AbstractGetValidators(metadata, context, It.IsAny<IEnumerable<Attribute>>()))\n                .Callback<ModelMetadata, ControllerContext, IEnumerable<Attribute>>((m, c, attributes) => callbackAttributes = attributes)\n                .Returns(() => null)\n                .Verifiable();\n\n            // Act\n            provider.Object.GetValidators(metadata, context);\n\n            // Assert\n            provider.Verify();\n            Assert.Contains(callbackAttributes, a => a is RequiredAttribute);\n        }\n\n        [Fact]\n        public void GetValidatorsForPropertyWithMetadataAttributes()\n        {\n            // Arrange\n            IEnumerable<Attribute> callbackAttributes = null;\n            ControllerContext context = new ControllerContext();\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(null, typeof(PropertyModel), \"MetadataAttributes\");\n            Mock<TestableAssociatedValidatorProvider> provider = new Mock<TestableAssociatedValidatorProvider> { CallBase = true };\n            provider.Setup(p => p.AbstractGetValidators(metadata, context, It.IsAny<IEnumerable<Attribute>>()))\n                .Callback<ModelMetadata, ControllerContext, IEnumerable<Attribute>>((m, c, attributes) => callbackAttributes = attributes)\n                .Returns(() => null)\n                .Verifiable();\n\n            // Act\n            provider.Object.GetValidators(metadata, context);\n\n            // Assert\n            provider.Verify();\n            Assert.Contains(callbackAttributes, a => a is RangeAttribute);\n        }\n\n        [Fact]\n        public void GetValidatorsForPropertyWithMixedAttributes()\n        {\n            // Arrange\n            IEnumerable<Attribute> callbackAttributes = null;\n            ControllerContext context = new ControllerContext();\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(null, typeof(PropertyModel), \"MixedAttributes\");\n            Mock<TestableAssociatedValidatorProvider> provider = new Mock<TestableAssociatedValidatorProvider> { CallBase = true };\n            provider.Setup(p => p.AbstractGetValidators(metadata, context, It.IsAny<IEnumerable<Attribute>>()))\n                .Callback<ModelMetadata, ControllerContext, IEnumerable<Attribute>>((m, c, attributes) => callbackAttributes = attributes)\n                .Returns(() => null)\n                .Verifiable();\n\n            // Act\n            provider.Object.GetValidators(metadata, context);\n\n            // Assert\n            provider.Verify();\n            Assert.Contains(callbackAttributes, a => a is RangeAttribute);\n            Assert.Contains(callbackAttributes, a => a is RequiredAttribute);\n        }\n\n        [MetadataType(typeof(Metadata))]\n        private class PropertyModel\n        {\n            [Required]\n            public int LocalAttributes { get; set; }\n\n            public string MetadataAttributes { get; set; }\n\n            [Required]\n            public double MixedAttributes { get; set; }\n\n            private class Metadata\n            {\n                [Range(10, 100)]\n                public object MetadataAttributes { get; set; }\n\n                [Range(10, 100)]\n                public object MixedAttributes { get; set; }\n            }\n        }\n\n        public abstract class TestableAssociatedValidatorProvider : AssociatedValidatorProvider\n        {\n            protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)\n            {\n                return AbstractGetValidators(metadata, context, attributes);\n            }\n\n            // Hoist access\n            public abstract IEnumerable<ModelValidator> AbstractGetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/AsyncControllerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Mvc.Async;\nusing System.Web.Mvc.Async.Test;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class AsyncControllerTest\n    {\n        [Fact]\n        public void ActionInvokerProperty()\n        {\n            // Arrange\n            EmptyController controller = new EmptyController();\n\n            // Act\n            IActionInvoker invoker = controller.ActionInvoker;\n\n            // Assert\n            Assert.IsType<AsyncControllerActionInvoker>(invoker);\n        }\n\n        [Fact]\n        public void AsyncManagerProperty()\n        {\n            // Arrange\n            EmptyController controller = new EmptyController();\n\n            // Act\n            AsyncManager asyncManager = controller.AsyncManager;\n\n            // Assert\n            Assert.NotNull(asyncManager);\n        }\n\n        [Fact]\n        public void Execute_ThrowsIfCalledMoreThanOnce()\n        {\n            // Arrange\n            IAsyncController controller = new EmptyController();\n            RequestContext requestContext = GetRequestContext(\"SomeAction\");\n\n            // Act & assert\n            controller.BeginExecute(requestContext, null, null);\n            Assert.Throws<InvalidOperationException>(\n                delegate { controller.BeginExecute(requestContext, null, null); },\n                @\"A single instance of controller 'System.Web.Mvc.Test.AsyncControllerTest+EmptyController' cannot be used to handle multiple requests. If a custom controller factory is in use, make sure that it creates a new instance of the controller for each request.\");\n        }\n\n        [Fact]\n        public void Execute_ThrowsIfRequestContextIsNull()\n        {\n            // Arrange\n            IAsyncController controller = new EmptyController();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { controller.BeginExecute(null, null, null); }, \"requestContext\");\n        }\n\n        [Fact]\n        public void ExecuteCore_Asynchronous_ActionFound()\n        {\n            // Arrange\n            using (MockAsyncResult innerAsyncResult = new MockAsyncResult())\n            {\n                Mock<IAsyncActionInvoker> mockActionInvoker = new Mock<IAsyncActionInvoker>();\n                mockActionInvoker.Setup(o => o.BeginInvokeAction(It.IsAny<ControllerContext>(), \"SomeAction\", It.IsAny<AsyncCallback>(), It.IsAny<object>())).Returns(innerAsyncResult);\n                mockActionInvoker.Setup(o => o.EndInvokeAction(innerAsyncResult)).Returns(true);\n\n                RequestContext requestContext = GetRequestContext(\"SomeAction\");\n                EmptyController controller = new EmptyController()\n                {\n                    ActionInvoker = mockActionInvoker.Object\n                };\n\n                // Act & assert\n                IAsyncResult outerAsyncResult = ((IAsyncController)controller).BeginExecute(requestContext, null, null);\n                Assert.False(controller.TempDataSaved);\n\n                ((IAsyncController)controller).EndExecute(outerAsyncResult);\n                Assert.True(controller.TempDataSaved);\n                Assert.False(controller.HandleUnknownActionCalled);\n            }\n        }\n\n        [Fact]\n        public void ExecuteCore_Asynchronous_ActionNotFound()\n        {\n            // Arrange\n            using (MockAsyncResult innerAsyncResult = new MockAsyncResult())\n            {\n                Mock<IAsyncActionInvoker> mockActionInvoker = new Mock<IAsyncActionInvoker>();\n                mockActionInvoker.Setup(o => o.BeginInvokeAction(It.IsAny<ControllerContext>(), \"SomeAction\", It.IsAny<AsyncCallback>(), It.IsAny<object>())).Returns(innerAsyncResult);\n                mockActionInvoker.Setup(o => o.EndInvokeAction(innerAsyncResult)).Returns(false);\n\n                RequestContext requestContext = GetRequestContext(\"SomeAction\");\n                EmptyController controller = new EmptyController()\n                {\n                    ActionInvoker = mockActionInvoker.Object\n                };\n\n                // Act & assert\n                IAsyncResult outerAsyncResult = ((IAsyncController)controller).BeginExecute(requestContext, null, null);\n                Assert.False(controller.TempDataSaved);\n\n                ((IAsyncController)controller).EndExecute(outerAsyncResult);\n                Assert.True(controller.TempDataSaved);\n                Assert.True(controller.HandleUnknownActionCalled);\n            }\n        }\n\n        [Fact]\n        public void ExecuteCore_Synchronous_ActionFound()\n        {\n            // Arrange\n            using (MockAsyncResult innerAsyncResult = new MockAsyncResult())\n            {\n                Mock<IActionInvoker> mockActionInvoker = new Mock<IActionInvoker>();\n                mockActionInvoker.Setup(o => o.InvokeAction(It.IsAny<ControllerContext>(), \"SomeAction\")).Returns(true);\n\n                RequestContext requestContext = GetRequestContext(\"SomeAction\");\n                EmptyController controller = new EmptyController()\n                {\n                    ActionInvoker = mockActionInvoker.Object\n                };\n\n                // Act & assert\n                IAsyncResult outerAsyncResult = ((IAsyncController)controller).BeginExecute(requestContext, null, null);\n                Assert.False(controller.TempDataSaved);\n\n                ((IAsyncController)controller).EndExecute(outerAsyncResult);\n                Assert.True(controller.TempDataSaved);\n                Assert.False(controller.HandleUnknownActionCalled);\n            }\n        }\n\n        [Fact]\n        public void ExecuteCore_Synchronous_ActionNotFound()\n        {\n            // Arrange\n            using (MockAsyncResult innerAsyncResult = new MockAsyncResult())\n            {\n                Mock<IActionInvoker> mockActionInvoker = new Mock<IActionInvoker>();\n                mockActionInvoker.Setup(o => o.InvokeAction(It.IsAny<ControllerContext>(), \"SomeAction\")).Returns(false);\n\n                RequestContext requestContext = GetRequestContext(\"SomeAction\");\n                EmptyController controller = new EmptyController()\n                {\n                    ActionInvoker = mockActionInvoker.Object\n                };\n\n                // Act & assert\n                IAsyncResult outerAsyncResult = ((IAsyncController)controller).BeginExecute(requestContext, null, null);\n                Assert.False(controller.TempDataSaved);\n\n                ((IAsyncController)controller).EndExecute(outerAsyncResult);\n                Assert.True(controller.TempDataSaved);\n                Assert.True(controller.HandleUnknownActionCalled);\n            }\n        }\n\n        [Fact]\n        public void ExecuteCore_SavesTempDataOnException()\n        {\n            // Arrange\n            Mock<IAsyncActionInvoker> mockActionInvoker = new Mock<IAsyncActionInvoker>();\n            mockActionInvoker\n                .Setup(o => o.BeginInvokeAction(It.IsAny<ControllerContext>(), \"SomeAction\", It.IsAny<AsyncCallback>(), It.IsAny<object>()))\n                .Throws(new Exception(\"Some exception text.\"));\n\n            RequestContext requestContext = GetRequestContext(\"SomeAction\");\n            EmptyController controller = new EmptyController()\n            {\n                ActionInvoker = mockActionInvoker.Object\n            };\n\n            // Act & assert\n            Assert.Throws<Exception>(\n                delegate { ((IAsyncController)controller).BeginExecute(requestContext, null, null); },\n                @\"Some exception text.\");\n            Assert.True(controller.TempDataSaved);\n        }\n\n        [Fact]\n        public void CreateActionInvokerCallsIntoResolverInstance()\n        {\n            // Controller uses an IDependencyResolver to create an IActionInvoker.\n            var controller = new EmptyController();\n            Mock<IDependencyResolver> resolverMock = new Mock<IDependencyResolver>();\n            Mock<IAsyncActionInvoker> actionInvokerMock = new Mock<IAsyncActionInvoker>();\n            resolverMock.Setup(r => r.GetService(typeof(IAsyncActionInvoker))).Returns(actionInvokerMock.Object);\n            controller.Resolver = resolverMock.Object;\n\n            var ai = controller.CreateActionInvoker();\n\n            resolverMock.Verify(r => r.GetService(typeof(IAsyncActionInvoker)), Times.Once());\n            Assert.Same(actionInvokerMock.Object, ai);\n        }\n\n        [Fact]\n        public void CreateActionInvokerCallsIntoResolverInstanceAndCreatesANewOneIfNecessary()\n        {\n            // If IDependencyResolver is set, but empty, falls back and still creates.\n            var controller = new EmptyController();\n            Mock<IDependencyResolver> resolverMock = new Mock<IDependencyResolver>();\n            resolverMock.Setup(r => r.GetService(typeof(IAsyncActionInvoker))).Returns(null);\n            resolverMock.Setup(r => r.GetService(typeof(IActionInvoker))).Returns(null);\n            controller.Resolver = resolverMock.Object;\n\n            var ai = controller.CreateActionInvoker();\n\n            resolverMock.Verify(r => r.GetService(typeof(IAsyncActionInvoker)), Times.Once());\n            resolverMock.Verify(r => r.GetService(typeof(IActionInvoker)), Times.Once());\n            Assert.NotNull(ai);\n        }\n\n\n        private static RequestContext GetRequestContext(string actionName)\n        {\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            RouteData routeData = new RouteData();\n            routeData.Values[\"action\"] = actionName;\n\n            return new RequestContext(mockHttpContext.Object, routeData);\n        }\n\n        private class EmptyController : AsyncController\n        {\n            public bool TempDataSaved;\n            public bool HandleUnknownActionCalled;\n\n            protected override ITempDataProvider CreateTempDataProvider()\n            {\n                return new DummyTempDataProvider();\n            }\n\n            protected override void HandleUnknownAction(string actionName)\n            {\n                HandleUnknownActionCalled = true;\n            }\n\n            // Test can expose protected method as public.\n            public new IActionInvoker CreateActionInvoker()\n            {\n                return base.CreateActionInvoker();\n            }\n\n\n            private class DummyTempDataProvider : ITempDataProvider\n            {\n                public IDictionary<string, object> LoadTempData(ControllerContext controllerContext)\n                {\n                    return new TempDataDictionary();\n                }\n\n                public void SaveTempData(ControllerContext controllerContext, IDictionary<string, object> values)\n                {\n                    ((EmptyController)controllerContext.Controller).TempDataSaved = true;\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/AsyncTimeoutAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class AsyncTimeoutAttributeTest\n    {\n        [Fact]\n        public void ConstructorThrowsIfDurationIsOutOfRange()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentOutOfRange(() => new AsyncTimeoutAttribute(-1000), \"duration\",\n                @\"The timeout value must be non-negative or Timeout.Infinite.\");\n        }\n\n        [Fact]\n        public void DurationProperty()\n        {\n            // Act\n            AsyncTimeoutAttribute attr = new AsyncTimeoutAttribute(45);\n\n            // Assert\n            Assert.Equal(45, attr.Duration);\n        }\n\n        [Fact]\n        public void OnActionExecutingSetsTimeoutPropertyOnController()\n        {\n            // Arrange\n            AsyncTimeoutAttribute attr = new AsyncTimeoutAttribute(45);\n\n            MyAsyncController controller = new MyAsyncController();\n            controller.AsyncManager.Timeout = 0;\n\n            ActionExecutingContext filterContext = new ActionExecutingContext()\n            {\n                Controller = controller\n            };\n\n            // Act\n            attr.OnActionExecuting(filterContext);\n\n            // Assert\n            Assert.Equal(45, controller.AsyncManager.Timeout);\n        }\n\n        [Fact]\n        public void OnActionExecutingThrowsIfControllerIsNotAsyncManagerContainer()\n        {\n            // Arrange\n            AsyncTimeoutAttribute attr = new AsyncTimeoutAttribute(45);\n\n            ActionExecutingContext filterContext = new ActionExecutingContext()\n            {\n                Controller = new MyController()\n            };\n\n            // Act & assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { attr.OnActionExecuting(filterContext); },\n                @\"The controller of type 'System.Web.Mvc.Test.AsyncTimeoutAttributeTest+MyController' must subclass AsyncController or implement the IAsyncManagerContainer interface.\");\n        }\n\n        [Fact]\n        public void OnActionExecutingThrowsIfFilterContextIsNull()\n        {\n            // Arrange\n            AsyncTimeoutAttribute attr = new AsyncTimeoutAttribute(45);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { attr.OnActionExecuting(null); }, \"filterContext\");\n        }\n\n        private class MyController : ControllerBase\n        {\n            protected override void ExecuteCore()\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class MyAsyncController : AsyncController\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/AuthorizationContextTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class AuthorizationContextTest\n    {\n        [Fact]\n        public void ConstructorThrowsIfActionDescriptorIsNull()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n            ActionDescriptor actionDescriptor = null;\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new AuthorizationContext(controllerContext, actionDescriptor); }, \"actionDescriptor\");\n        }\n\n        [Fact]\n        public void PropertiesAreSetByConstructor()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n            ActionDescriptor actionDescriptor = new Mock<ActionDescriptor>().Object;\n\n            // Act\n            AuthorizationContext authorizationContext = new AuthorizationContext(controllerContext, actionDescriptor);\n\n            // Assert\n            Assert.Equal(actionDescriptor, authorizationContext.ActionDescriptor);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/AuthorizeAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Linq;\nusing System.Reflection;\nusing System.Security.Principal;\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class AuthorizeAttributeTest\n    {\n        [Fact]\n        public void AuthorizeAttributeReturnsUniqueTypeIDs()\n        {\n            // Arrange\n            AuthorizeAttribute attr1 = new AuthorizeAttribute();\n            AuthorizeAttribute attr2 = new AuthorizeAttribute();\n\n            // Assert\n            Assert.NotEqual(attr1.TypeId, attr2.TypeId);\n        }\n\n        [Authorize(Roles = \"foo\")]\n        [Authorize(Roles = \"bar\")]\n        private class ClassWithMultipleAuthorizeAttributes\n        {\n        }\n\n        [Fact]\n        public void CanRetrieveMultipleAuthorizeAttributesFromOneClass()\n        {\n            // Arrange\n            ClassWithMultipleAuthorizeAttributes @class = new ClassWithMultipleAuthorizeAttributes();\n\n            // Act\n            IEnumerable<AuthorizeAttribute> attributes = TypeDescriptor.GetAttributes(@class).OfType<AuthorizeAttribute>();\n\n            // Assert\n            Assert.Equal(2, attributes.Count());\n            Assert.Contains(attributes, a => a.Roles == \"foo\");\n            Assert.Contains(attributes, a => a.Roles == \"bar\");\n        }\n\n        [Fact]\n        public void AuthorizeCoreReturnsFalseIfNameDoesNotMatch()\n        {\n            // Arrange\n            AuthorizeAttributeHelper helper = new AuthorizeAttributeHelper() { Users = \"SomeName\" };\n\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(c => c.User.Identity.IsAuthenticated).Returns(true);\n            mockHttpContext.Setup(c => c.User.Identity.Name).Returns(\"SomeOtherName\");\n\n            // Act\n            bool retVal = helper.PublicAuthorizeCore(mockHttpContext.Object);\n\n            // Assert\n            Assert.False(retVal);\n        }\n\n        [Fact]\n        public void AuthorizeCoreReturnsFalseIfRoleDoesNotMatch()\n        {\n            // Arrange\n            AuthorizeAttributeHelper helper = new AuthorizeAttributeHelper() { Roles = \"SomeRole\" };\n\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(c => c.User.Identity.IsAuthenticated).Returns(true);\n            mockHttpContext.Setup(c => c.User.IsInRole(\"SomeRole\")).Returns(false).Verifiable();\n\n            // Act\n            bool retVal = helper.PublicAuthorizeCore(mockHttpContext.Object);\n\n            // Assert\n            Assert.False(retVal);\n            mockHttpContext.Verify();\n        }\n\n        [Fact]\n        public void AuthorizeCoreReturnsFalseIfUserIsUnauthenticated()\n        {\n            // Arrange\n            AuthorizeAttributeHelper helper = new AuthorizeAttributeHelper();\n\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(c => c.User.Identity.IsAuthenticated).Returns(false);\n\n            // Act\n            bool retVal = helper.PublicAuthorizeCore(mockHttpContext.Object);\n\n            // Assert\n            Assert.False(retVal);\n        }\n\n        [Fact]\n        public void AuthorizeCoreReturnsTrueIfUserIsAuthenticatedAndNamesOrRolesSpecified()\n        {\n            // Arrange\n            AuthorizeAttributeHelper helper = new AuthorizeAttributeHelper() { Users = \"SomeUser, SomeOtherUser\", Roles = \"SomeRole, SomeOtherRole\" };\n\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(c => c.User.Identity.IsAuthenticated).Returns(true);\n            mockHttpContext.Setup(c => c.User.Identity.Name).Returns(\"SomeUser\");\n            mockHttpContext.Setup(c => c.User.IsInRole(\"SomeRole\")).Returns(false).Verifiable();\n            mockHttpContext.Setup(c => c.User.IsInRole(\"SomeOtherRole\")).Returns(true).Verifiable();\n\n            // Act\n            bool retVal = helper.PublicAuthorizeCore(mockHttpContext.Object);\n\n            // Assert\n            Assert.True(retVal);\n            mockHttpContext.Verify();\n        }\n\n        [Fact]\n        public void AuthorizeCoreReturnsTrueIfUserIsAuthenticatedAndNoNamesOrRolesSpecified()\n        {\n            // Arrange\n            AuthorizeAttributeHelper helper = new AuthorizeAttributeHelper();\n\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(c => c.User.Identity.IsAuthenticated).Returns(true);\n\n            // Act\n            bool retVal = helper.PublicAuthorizeCore(mockHttpContext.Object);\n\n            // Assert\n            Assert.True(retVal);\n        }\n\n        [Fact]\n        public void AuthorizeCoreThrowsIfHttpContextIsNull()\n        {\n            // Arrange\n            AuthorizeAttributeHelper helper = new AuthorizeAttributeHelper();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { helper.PublicAuthorizeCore((HttpContextBase)null); }, \"httpContext\");\n        }\n\n        [Fact]\n        public void OnAuthorizationCallsHandleUnauthorizedRequestIfUserUnauthorized()\n        {\n            // Arrange\n            CustomFailAuthorizeAttribute attr = new CustomFailAuthorizeAttribute();\n\n            Mock<AuthorizationContext> mockAuthContext = new Mock<AuthorizationContext>();\n            mockAuthContext.Setup(c => c.HttpContext.User.Identity.IsAuthenticated).Returns(false);\n            mockAuthContext.Setup(c => c.HttpContext.Items).Returns(new Hashtable());\n            mockAuthContext.Setup(c => c.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false);\n            AuthorizationContext authContext = mockAuthContext.Object;\n\n            // Act\n            attr.OnAuthorization(authContext);\n\n            // Assert\n            Assert.Equal(CustomFailAuthorizeAttribute.ExpectedResult, authContext.Result);\n        }\n\n        [Fact]\n        public void OnAuthorizationFailedSetsHttpUnauthorizedResultIfUserUnauthorized()\n        {\n            // Arrange\n            Mock<AuthorizeAttributeHelper> mockHelper = new Mock<AuthorizeAttributeHelper>() { CallBase = true };\n            mockHelper.Setup(h => h.PublicAuthorizeCore(It.IsAny<HttpContextBase>())).Returns(false);\n            AuthorizeAttributeHelper helper = mockHelper.Object;\n\n            AuthorizationContext filterContext = new Mock<AuthorizationContext>() { DefaultValue = DefaultValue.Mock }.Object;\n\n            // Act\n            helper.OnAuthorization(filterContext);\n\n            // Assert\n            Assert.IsType<HttpUnauthorizedResult>(filterContext.Result);\n        }\n\n        [Fact]\n        public void OnAuthorizationHooksCacheValidationIfUserAuthorized()\n        {\n            // Arrange\n            Mock<AuthorizeAttributeHelper> mockHelper = new Mock<AuthorizeAttributeHelper>() { CallBase = true };\n            mockHelper.Setup(h => h.PublicAuthorizeCore(It.IsAny<HttpContextBase>())).Returns(true);\n            AuthorizeAttributeHelper helper = mockHelper.Object;\n\n            MethodInfo callbackMethod = typeof(AuthorizeAttribute).GetMethod(\"CacheValidateHandler\", BindingFlags.Instance | BindingFlags.NonPublic);\n            Mock<AuthorizationContext> mockFilterContext = new Mock<AuthorizationContext>();\n            mockFilterContext.Setup(c => c.HttpContext.Response.Cache.SetProxyMaxAge(new TimeSpan(0))).Verifiable();\n            mockFilterContext.Setup(c => c.HttpContext.Items).Returns(new Hashtable());\n            mockFilterContext\n                .Setup(c => c.HttpContext.Response.Cache.AddValidationCallback(It.IsAny<HttpCacheValidateHandler>(), null /* data */))\n                .Callback(\n                    delegate(HttpCacheValidateHandler handler, object data)\n                    {\n                        Assert.Equal(helper, handler.Target);\n                        Assert.Equal(callbackMethod, handler.Method);\n                    })\n                .Verifiable();\n            mockFilterContext.Setup(c => c.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(false);\n            AuthorizationContext filterContext = mockFilterContext.Object;\n\n            // Act\n            helper.OnAuthorization(filterContext);\n\n            // Assert\n            mockFilterContext.Verify();\n        }\n\n        [Fact]\n        public void OnAuthorizationThrowsIfFilterContextIsNull()\n        {\n            // Arrange\n            AuthorizeAttribute attr = new AuthorizeAttribute();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { attr.OnAuthorization(null); }, \"filterContext\");\n        }\n\n        [Fact]\n        public void OnAuthorizationReturnsWithNoResultIfAllowAnonymousAttributeIsDefinedOnAction()\n        {\n            // Arrange\n            Mock<AuthorizeAttributeHelper> mockHelper = new Mock<AuthorizeAttributeHelper>() { CallBase = true };\n            AuthorizeAttributeHelper helper = mockHelper.Object;\n\n            Mock<AuthorizationContext> mockFilterContext = new Mock<AuthorizationContext>();\n            mockFilterContext.Setup(c => c.HttpContext.Items).Returns(new Hashtable());\n            mockFilterContext.Setup(c => c.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(true);\n\n            // Act\n            helper.OnAuthorization(mockFilterContext.Object);\n\n            // Assert\n            Assert.Null(mockFilterContext.Object.Result);\n            mockHelper.Verify(h => h.PublicAuthorizeCore(It.IsAny<HttpContextBase>()), Times.Never());\n        }\n\n        [Fact]\n        public void OnAuthorizationReturnsWithNoResultIfAllowAnonymousAttributeIsDefinedOnController()\n        {\n            // Arrange\n            Mock<AuthorizeAttributeHelper> mockHelper = new Mock<AuthorizeAttributeHelper>() { CallBase = true };\n            AuthorizeAttributeHelper helper = mockHelper.Object;\n\n            Mock<AuthorizationContext> mockFilterContext = new Mock<AuthorizationContext>();\n            mockFilterContext.Setup(c => c.HttpContext.Items).Returns(new Hashtable());\n            mockFilterContext.Setup(c => c.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)).Returns(true);\n\n            // Act\n            helper.OnAuthorization(mockFilterContext.Object);\n\n            // Assert\n            Assert.Null(mockFilterContext.Object.Result);\n            mockHelper.Verify(h => h.PublicAuthorizeCore(It.IsAny<HttpContextBase>()), Times.Never());\n        }\n\n        [Fact]\n        public void OnCacheAuthorizationReturnsIgnoreRequestIfUserIsUnauthorized()\n        {\n            // Arrange\n            Mock<AuthorizeAttributeHelper> mockHelper = new Mock<AuthorizeAttributeHelper>() { CallBase = true };\n            mockHelper.Setup(h => h.PublicAuthorizeCore(It.IsAny<HttpContextBase>())).Returns(false);\n            AuthorizeAttributeHelper helper = mockHelper.Object;\n\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(c => c.User).Returns(new Mock<IPrincipal>().Object);\n\n            // Act\n            HttpValidationStatus validationStatus = helper.PublicOnCacheAuthorization(mockHttpContext.Object);\n\n            // Assert\n            Assert.Equal(HttpValidationStatus.IgnoreThisRequest, validationStatus);\n        }\n\n        [Fact]\n        public void OnCacheAuthorizationReturnsValidIfUserIsAuthorized()\n        {\n            // Arrange\n            Mock<AuthorizeAttributeHelper> mockHelper = new Mock<AuthorizeAttributeHelper>() { CallBase = true };\n            mockHelper.Setup(h => h.PublicAuthorizeCore(It.IsAny<HttpContextBase>())).Returns(true);\n            AuthorizeAttributeHelper helper = mockHelper.Object;\n\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(c => c.User).Returns(new Mock<IPrincipal>().Object);\n\n            // Act\n            HttpValidationStatus validationStatus = helper.PublicOnCacheAuthorization(mockHttpContext.Object);\n\n            // Assert\n            Assert.Equal(HttpValidationStatus.Valid, validationStatus);\n        }\n\n        [Fact]\n        public void OnCacheAuthorizationThrowsIfHttpContextIsNull()\n        {\n            // Arrange\n            AuthorizeAttributeHelper helper = new AuthorizeAttributeHelper();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { helper.PublicOnCacheAuthorization(null); }, \"httpContext\");\n        }\n\n        [Fact]\n        public void RolesProperty()\n        {\n            // Arrange\n            AuthorizeAttribute attr = new AuthorizeAttribute();\n\n            // Act & assert\n            MemberHelper.TestStringProperty(attr, \"Roles\", String.Empty);\n        }\n\n        [Fact]\n        public void UsersProperty()\n        {\n            // Arrange\n            AuthorizeAttribute attr = new AuthorizeAttribute();\n\n            // Act & assert\n            MemberHelper.TestStringProperty(attr, \"Users\", String.Empty);\n        }\n\n        public class AuthorizeAttributeHelper : AuthorizeAttribute\n        {\n            public virtual bool PublicAuthorizeCore(HttpContextBase httpContext)\n            {\n                return base.AuthorizeCore(httpContext);\n            }\n\n            protected override bool AuthorizeCore(HttpContextBase httpContext)\n            {\n                return PublicAuthorizeCore(httpContext);\n            }\n\n            public virtual HttpValidationStatus PublicOnCacheAuthorization(HttpContextBase httpContext)\n            {\n                return base.OnCacheAuthorization(httpContext);\n            }\n\n            protected override HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext)\n            {\n                return PublicOnCacheAuthorization(httpContext);\n            }\n        }\n\n        public class CustomFailAuthorizeAttribute : AuthorizeAttribute\n        {\n            public static readonly ActionResult ExpectedResult = new ContentResult();\n\n            protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)\n            {\n                filterContext.Result = ExpectedResult;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/BindAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class BindAttributeTest\n    {\n        [Fact]\n        public void PrefixProperty()\n        {\n            // Arrange\n            BindAttribute attr = new BindAttribute { Prefix = \"somePrefix\" };\n\n            // Act & assert\n            Assert.Equal(\"somePrefix\", attr.Prefix);\n        }\n\n        [Fact]\n        public void PrefixPropertyDefaultsToNull()\n        {\n            // Arrange\n            BindAttribute attr = new BindAttribute();\n\n            // Act & assert\n            Assert.Null(attr.Prefix);\n        }\n\n        [Fact]\n        public void IncludePropertyDefaultsToEmptyString()\n        {\n            // Arrange\n            BindAttribute attr = new BindAttribute { Include = null };\n\n            // Act & assert\n            Assert.Equal(String.Empty, attr.Include);\n        }\n\n        [Fact]\n        public void ExcludePropertyDefaultsToEmptyString()\n        {\n            // Arrange\n            BindAttribute attr = new BindAttribute { Exclude = null };\n\n            // Act & assert\n            Assert.Equal(String.Empty, attr.Exclude);\n        }\n\n        [Fact]\n        public void IsPropertyAllowedReturnsFalseForBlacklistedPropertiesIfBindPropertiesIsExclude()\n        {\n            // Setup\n            BindAttribute attr = new BindAttribute { Exclude = \"FOO,BAZ\" };\n\n            // Act & assert\n            Assert.False(attr.IsPropertyAllowed(\"foo\"));\n            Assert.True(attr.IsPropertyAllowed(\"bar\"));\n            Assert.False(attr.IsPropertyAllowed(\"baz\"));\n        }\n\n        [Fact]\n        public void IsPropertyAllowedReturnsTrueAlwaysIfBindPropertiesIsAll()\n        {\n            // Setup\n            BindAttribute attr = new BindAttribute();\n\n            // Act & assert\n            Assert.True(attr.IsPropertyAllowed(\"foo\"));\n            Assert.True(attr.IsPropertyAllowed(\"bar\"));\n            Assert.True(attr.IsPropertyAllowed(\"baz\"));\n        }\n\n        [Fact]\n        public void IsPropertyAllowedReturnsTrueForWhitelistedPropertiesIfBindPropertiesIsInclude()\n        {\n            // Setup\n            BindAttribute attr = new BindAttribute { Include = \"FOO,BAR\" };\n\n            // Act & assert\n            Assert.True(attr.IsPropertyAllowed(\"foo\"));\n            Assert.True(attr.IsPropertyAllowed(\"bar\"));\n            Assert.False(attr.IsPropertyAllowed(\"baz\"));\n        }\n\n        [Fact]\n        public void IsPropertyAllowedReturnsFalseForBlacklistOverridingWhitelistedProperties()\n        {\n            // Setup\n            BindAttribute attr = new BindAttribute { Include = \"FOO,BAR\", Exclude = \"bar,QUx\" };\n\n            // Act & assert\n            Assert.True(attr.IsPropertyAllowed(\"foo\"));\n            Assert.False(attr.IsPropertyAllowed(\"bar\"));\n            Assert.False(attr.IsPropertyAllowed(\"baz\"));\n            Assert.False(attr.IsPropertyAllowed(\"qux\"));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/BuildManagerCompiledViewTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class CompiledTypeViewTest\n    {\n        [Fact]\n        public void GuardClauses()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => new TestableBuildManagerCompiledView(new ControllerContext(), String.Empty),\n                \"viewPath\"\n                );\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => new TestableBuildManagerCompiledView(new ControllerContext(), null),\n                \"viewPath\"\n                );\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => new TestableBuildManagerCompiledView(null, \"view path\"),\n                \"controllerContext\"\n                );\n        }\n\n        [Fact]\n        public void RenderWithNullContextThrows()\n        {\n            // Arrange\n            TestableBuildManagerCompiledView view = new TestableBuildManagerCompiledView(new ControllerContext(), \"~/view\");\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => view.Render(null, new Mock<TextWriter>().Object),\n                \"viewContext\"\n                );\n        }\n\n        [Fact]\n        public void RenderWithNullViewInstanceThrows()\n        {\n            // Arrange\n            ViewContext context = new Mock<ViewContext>().Object;\n            MockBuildManager buildManager = new MockBuildManager(\"view path\", compiledType: null);\n            TestableBuildManagerCompiledView view = new TestableBuildManagerCompiledView(new ControllerContext(), \"view path\");\n            view.BuildManager = buildManager;\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => view.Render(context, new Mock<TextWriter>().Object),\n                \"The view found at 'view path' was not created.\"\n                );\n        }\n\n        [Fact]\n        public void ViewPathProperty()\n        {\n            // Act\n            BuildManagerCompiledView view = new TestableBuildManagerCompiledView(new ControllerContext(), \"view path\");\n\n            // Assert\n            Assert.Equal(\"view path\", view.ViewPath);\n        }\n\n        [Fact]\n        public void ViewCreationConsultsSetActivator()\n        {\n            // Arrange\n            object viewInstance = new object();\n            Mock<IViewPageActivator> activator = new Mock<IViewPageActivator>(MockBehavior.Strict);\n            ControllerContext controllerContext = new ControllerContext();\n            activator.Setup(a => a.Create(controllerContext, typeof(object))).Returns(viewInstance).Verifiable();\n            MockBuildManager buildManager = new MockBuildManager(\"view path\", typeof(object));\n            BuildManagerCompiledView view = new TestableBuildManagerCompiledView(controllerContext, \"view path\", activator.Object) { BuildManager = buildManager };\n\n            // Act\n            view.Render(new Mock<ViewContext>().Object, new Mock<TextWriter>().Object);\n\n            // Assert\n            activator.Verify();\n        }\n\n        [Fact]\n        public void ViewCreationDelegatesToDependencyResolverWhenActivatorIsNull()\n        {\n            // Arrange\n            var viewInstance = new object();\n            var controllerContext = new ControllerContext();\n            var buildManager = new MockBuildManager(\"view path\", typeof(object));\n            var dependencyResolver = new Mock<IDependencyResolver>(MockBehavior.Strict);\n            dependencyResolver.Setup(dr => dr.GetService(typeof(object))).Returns(viewInstance).Verifiable();\n            var view = new TestableBuildManagerCompiledView(controllerContext, \"view path\", dependencyResolver: dependencyResolver.Object) { BuildManager = buildManager };\n\n            // Act\n            view.Render(new Mock<ViewContext>().Object, new Mock<TextWriter>().Object);\n\n            // Assert\n            dependencyResolver.Verify();\n        }\n\n        [Fact]\n        public void ViewCreationDelegatesToActivatorCreateInstanceWhenDependencyResolverReturnsNull()\n        {\n            // Arrange\n            var controllerContext = new ControllerContext();\n            var buildManager = new MockBuildManager(\"view path\", typeof(NoParameterlessCtor));\n            var dependencyResolver = new Mock<IDependencyResolver>();\n            var view = new TestableBuildManagerCompiledView(controllerContext, \"view path\", dependencyResolver: dependencyResolver.Object) { BuildManager = buildManager };\n\n            // Act & Assert, confirming type name and full stack are available in Exception\n            // Depend on the fact that Activator.CreateInstance cannot create an object without a parameterless ctor\n            MissingMethodException ex = Assert.Throws<MissingMethodException>(\n                () => view.Render(new Mock<ViewContext>().Object, new Mock<TextWriter>().Object),\n                \"No parameterless constructor defined for this object. Object type 'System.Web.Mvc.Test.CompiledTypeViewTest+NoParameterlessCtor'.\");\n            Assert.Contains(\"System.Activator.CreateInstance(\", ex.ToString());\n        }\n\n        private class NoParameterlessCtor\n        {\n            public NoParameterlessCtor(int x)\n            {\n            }\n        }\n\n        private sealed class TestableBuildManagerCompiledView : BuildManagerCompiledView\n        {\n            public TestableBuildManagerCompiledView(ControllerContext controllerContext, string viewPath, IViewPageActivator viewPageActivator = null, IDependencyResolver dependencyResolver = null)\n                : base(controllerContext, viewPath, viewPageActivator, dependencyResolver)\n            {\n            }\n\n            protected override void RenderView(ViewContext viewContext, TextWriter writer, object instance)\n            {\n                return;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/BuildManagerViewEngineTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Web.Hosting;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class BuildManagerViewEngineTest\n    {\n        [Fact]\n        public void BuildManagerProperty()\n        {\n            // Arrange\n            var engine = new TestableBuildManagerViewEngine();\n            var buildManagerMock = new MockBuildManager(expectedVirtualPath: null, compiledType: null);\n\n            // Act\n            engine.BuildManager = buildManagerMock;\n\n            // Assert\n            Assert.Same(engine.BuildManager, buildManagerMock);\n        }\n\n        [Fact]\n        public void FileExistsReturnsTrueForExistingPath()\n        {\n            // Arrange\n            string testPath = \"/Path.txt\";\n            var engine = new TestableBuildManagerViewEngine(pathProvider: CreatePathProvider(testPath));\n\n            // Act\n            bool result = engine.FileExists(testPath);\n\n            // Assert\n            Assert.True(result);\n        }\n\n        [Fact]\n        public void FileExistsDoesNotQueryBuildManagerIfAppIsNotPrecompiledNonUpdateable()\n        {\n            // Arrange\n            string testPath = \"/Path.txt\";\n            var engine = new TestableBuildManagerViewEngine(pathProvider: CreatePathProvider(\"some random path\"));\n            var buildManagerMock = new Mock<MockBuildManager>();\n            engine.BuildManager = buildManagerMock.Object;\n\n            // Act\n            bool result = engine.FileExists(testPath);\n\n            // Assert\n            buildManagerMock.Verify(b => b.FileExists(It.IsAny<string>()), Times.Never());\n            Assert.False(result);\n        }\n\n        [Fact]\n        public void FileExistsQueriesBuildManagerForFilesThatPathProviderDoesNotFindWhenRunningInPrecompiledNonUpdateableApp()\n        {\n            // Arrange\n            string testPath = \"/Path.txt\";\n            var engine = new TestableBuildManagerViewEngine(pathProvider: CreatePathProvider(\"some random path\"));\n            engine.SetIsPrecompiledNonUpdateableSite(true);\n            var buildManagerMock = new MockBuildManager(testPath, typeof(object));\n            engine.BuildManager = buildManagerMock;\n\n            // Act\n            bool result = engine.FileExists(testPath);\n\n            // Assert\n            Assert.True(result);\n        }\n\n        [Fact]\n        public void FileExistsReturnsFalseWhenBuildManagerFileExistsReturnsFalse()\n        {\n            // Arrange\n            var engine = new TestableBuildManagerViewEngine(pathProvider: CreatePathProvider());\n            var buildManagerMock = new MockBuildManager(\"some path\", false);\n            engine.BuildManager = buildManagerMock;\n\n            // Act\n            bool result = engine.FileExists(\"some path\");\n\n            // Assert\n            Assert.False(result);\n        }\n\n        [Fact]\n        public void FileExistsReturnsTrueForExistingPath_VPPRegistrationChanging()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                // Arrange\n                AppDomainUtils.SetAppData();\n                new HostingEnvironment();\n\n                // Expect null beforeProvider since hosting environment hasn't been initialized\n                VirtualPathProvider beforeProvider = HostingEnvironment.VirtualPathProvider;\n                string testPath = \"/Path.txt\";\n                VirtualPathProvider afterProvider = CreatePathProvider(testPath);\n                Mock<VirtualPathProvider> mockProvider = Mock.Get(afterProvider);\n\n                TestableBuildManagerViewEngine engine = new TestableBuildManagerViewEngine();\n\n                // Act\n                VirtualPathProvider beforeEngineProvider = engine.VirtualPathProvider;\n                HostingEnvironment.RegisterVirtualPathProvider(afterProvider);\n\n                bool result = engine.FileExists(testPath);\n                VirtualPathProvider afterEngineProvider = engine.VirtualPathProvider;\n\n                // Assert\n                Assert.True(result);\n                Assert.Equal(beforeProvider, beforeEngineProvider);\n                Assert.Equal(afterProvider, afterEngineProvider);\n\n                mockProvider.Verify();\n                mockProvider.Verify(c => c.FileExists(It.IsAny<String>()), Times.Once());\n            });\n        }\n\n        [Fact]\n        public void FileExistsReturnsFalseForNonExistentPath()\n        {\n            // Arrange\n            string matchingPath = \"/Path.txt\";\n            string nonMatchingPath = \"/PathOther.txt\";\n            var engine = new TestableBuildManagerViewEngine(pathProvider: CreatePathProvider(matchingPath))\n            {\n                BuildManager = new MockBuildManager(nonMatchingPath, fileExists: false)\n            };\n\n            // Act\n            bool result = engine.FileExists(nonMatchingPath);\n\n            // Assert\n            Assert.False(result);\n        }\n\n        [Fact]\n        public void ViewPageActivatorConsultsSetActivatorResolver()\n        {\n            // Arrange\n            Mock<IViewPageActivator> activator = new Mock<IViewPageActivator>();\n\n            // Act\n            TestableBuildManagerViewEngine engine = new TestableBuildManagerViewEngine(activator.Object);\n\n            //Assert\n            Assert.Equal(activator.Object, engine.ViewPageActivator);\n        }\n\n        [Fact]\n        public void ViewPageActivatorDelegatesToActivatorResolver()\n        {\n            // Arrange\n            var activator = new Mock<IViewPageActivator>();\n            var activatorResolver = new Resolver<IViewPageActivator> { Current = activator.Object };\n\n            // Act\n            TestableBuildManagerViewEngine engine = new TestableBuildManagerViewEngine(activatorResolver: activatorResolver);\n\n            // Assert\n            Assert.Equal(activator.Object, engine.ViewPageActivator);\n        }\n\n        [Fact]\n        public void ViewPageActivatorDelegatesToDependencyResolverWhenActivatorResolverIsNull()\n        {\n            // Arrange\n            var viewInstance = new object();\n            var controllerContext = new ControllerContext();\n            var buildManager = new MockBuildManager(\"view path\", typeof(object));\n            var dependencyResolver = new Mock<IDependencyResolver>(MockBehavior.Strict);\n            dependencyResolver.Setup(dr => dr.GetService(typeof(object))).Returns(viewInstance).Verifiable();\n\n            // Act\n            TestableBuildManagerViewEngine engine = new TestableBuildManagerViewEngine(dependencyResolver: dependencyResolver.Object);\n            engine.ViewPageActivator.Create(controllerContext, typeof(object));\n\n            // Assert\n            dependencyResolver.Verify();\n        }\n\n        [Fact]\n        public void ViewPageActivatorDelegatesToActivatorCreateInstanceWhenDependencyResolverReturnsNull()\n        {\n            // Arrange\n            var controllerContext = new ControllerContext();\n            var buildManager = new MockBuildManager(\"view path\", typeof(NoParameterlessCtor));\n            var dependencyResolver = new Mock<IDependencyResolver>();\n\n            var engine = new TestableBuildManagerViewEngine(dependencyResolver: dependencyResolver.Object);\n\n            // Act & Assert, confirming type name and full stack are available in Exception\n            // Depend on the fact that Activator.CreateInstance cannot create an object without a parameterless ctor\n            MissingMethodException ex = Assert.Throws<MissingMethodException>(\n                () => engine.ViewPageActivator.Create(controllerContext, typeof(NoParameterlessCtor)),\n                \"No parameterless constructor defined for this object. Object type 'System.Web.Mvc.Test.BuildManagerViewEngineTest+NoParameterlessCtor'.\");\n            Assert.Contains(\"System.Activator.CreateInstance(\", ex.InnerException.StackTrace);\n        }\n\n        [Fact]\n        public void ActivatorResolverAndDependencyResolverAreNeverCalledWhenViewPageActivatorIsPassedInContstructor()\n        {\n            // Arrange\n            var controllerContext = new ControllerContext();\n            var expectedController = new Goodcontroller();\n\n            Mock<IViewPageActivator> activator = new Mock<IViewPageActivator>();\n\n            var resolverActivator = new Mock<IViewPageActivator>(MockBehavior.Strict);\n            var activatorResolver = new Resolver<IViewPageActivator> { Current = resolverActivator.Object };\n\n            var dependencyResolver = new Mock<IDependencyResolver>(MockBehavior.Strict);\n\n            //Act\n            var engine = new TestableBuildManagerViewEngine(activator.Object, activatorResolver, dependencyResolver.Object);\n\n            //Assert\n            Assert.Same(activator.Object, engine.ViewPageActivator);\n        }\n\n        private static VirtualPathProvider CreatePathProvider(params string[] files)\n        {\n            var vpp = new Mock<VirtualPathProvider>();\n            vpp.Setup(c => c.FileExists(It.IsAny<string>())).Returns<string>(p => files.Contains(p, StringComparer.OrdinalIgnoreCase));\n            return vpp.Object;\n        }\n\n        private class NoParameterlessCtor\n        {\n            public NoParameterlessCtor(int x)\n            {\n            }\n        }\n\n        private class TestableBuildManagerViewEngine : BuildManagerViewEngine\n        {\n            private bool _isPrecompiledNonUpdateableSite;\n\n            public TestableBuildManagerViewEngine()\n                : base()\n            {\n            }\n\n            public TestableBuildManagerViewEngine(IViewPageActivator viewPageActivator)\n                : base(viewPageActivator)\n            {\n            }\n\n            public TestableBuildManagerViewEngine(IViewPageActivator viewPageActivator = null, IResolver<IViewPageActivator> activatorResolver = null, IDependencyResolver dependencyResolver = null, VirtualPathProvider pathProvider = null)\n                : base(viewPageActivator, activatorResolver, dependencyResolver, pathProvider)\n            {\n            }\n\n            public new IViewPageActivator ViewPageActivator\n            {\n                get { return base.ViewPageActivator; }\n            }\n\n            public new VirtualPathProvider VirtualPathProvider\n            {\n                get { return base.VirtualPathProvider; }\n            }\n\n            protected override bool IsPrecompiledNonUpdateableSite\n            {\n                get { return _isPrecompiledNonUpdateableSite; }\n            }\n\n            protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)\n            {\n                throw new NotImplementedException();\n            }\n\n            protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)\n            {\n                throw new NotImplementedException();\n            }\n\n            public bool FileExists(string virtualPath)\n            {\n                return base.FileExists(null, virtualPath);\n            }\n\n            internal void SetIsPrecompiledNonUpdateableSite(bool value)\n            {\n                _isPrecompiledNonUpdateableSite = value;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ByteArrayModelBinderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ByteArrayModelBinderTest\n    {\n        internal const string Base64TestString = \"Fys1\";\n        internal static readonly byte[] Base64TestBytes = new byte[] { 23, 43, 53 };\n\n        [Fact]\n        public void BindModelWithNonExistentValueReturnsNull()\n        {\n            // Arrange\n            SimpleValueProvider valueProvider = new SimpleValueProvider()\n            {\n                { \"foo\", null }\n            };\n\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelName = \"foo\",\n                ValueProvider = valueProvider\n            };\n\n            ByteArrayModelBinder binder = new ByteArrayModelBinder();\n\n            // Act\n            object binderResult = binder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.Null(binderResult);\n        }\n\n        [Fact]\n        public void BinderWithEmptyStringValueReturnsNull()\n        {\n            // Arrange\n            SimpleValueProvider valueProvider = new SimpleValueProvider()\n            {\n                { \"foo\", \"\" }\n            };\n\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelName = \"foo\",\n                ValueProvider = valueProvider\n            };\n\n            ByteArrayModelBinder binder = new ByteArrayModelBinder();\n\n            // Act\n            object binderResult = binder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.Null(binderResult);\n        }\n\n        [Fact]\n        public void BindModelThrowsIfBindingContextIsNull()\n        {\n            // Arrange\n            ByteArrayModelBinder binder = new ByteArrayModelBinder();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { binder.BindModel(null, null); }, \"bindingContext\");\n        }\n\n        [Fact]\n        public void BindModelWithBase64QuotedValueReturnsByteArray()\n        {\n            // Arrange\n            string base64Value = Base64TestString;\n            SimpleValueProvider valueProvider = new SimpleValueProvider()\n            {\n                { \"foo\", \"\\\"\" + base64Value + \"\\\"\" }\n            };\n\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelName = \"foo\",\n                ValueProvider = valueProvider\n            };\n\n            ByteArrayModelBinder binder = new ByteArrayModelBinder();\n\n            // Act\n            byte[] boundValue = binder.BindModel(null, bindingContext) as byte[];\n\n            // Assert\n            Assert.Equal(Base64TestBytes, boundValue);\n        }\n\n        [Fact]\n        public void BindModelWithBase64UnquotedValueReturnsByteArray()\n        {\n            // Arrange\n            string base64Value = Base64TestString;\n            SimpleValueProvider valueProvider = new SimpleValueProvider()\n            {\n                { \"foo\", base64Value }\n            };\n\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelName = \"foo\",\n                ValueProvider = valueProvider\n            };\n\n            ByteArrayModelBinder binder = new ByteArrayModelBinder();\n\n            // Act\n            byte[] boundValue = binder.BindModel(null, bindingContext) as byte[];\n\n            // Assert\n            Assert.Equal(Base64TestBytes, boundValue);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/CachedAssociatedMetadataProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Runtime.Caching;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class CachedAssociatedMetadataProviderTest\n    {\n        [Fact]\n        public void GetMetadataForPropertyInvalidPropertyNameThrows()\n        {\n            // Arrange\n            MockableCachedAssociatedMetadataProvider provider = new MockableCachedAssociatedMetadataProvider();\n\n            // Act & Assert\n            Assert.Throws<ArgumentException>(\n                () => provider.GetMetadataForProperty(null, typeof(object), \"BadPropertyName\"),\n                \"The property System.Object.BadPropertyName could not be found.\");\n        }\n\n        [Fact]\n        public void GetCacheKey_ResultsForTypesDoNotCollide()\n        {\n            // Arrange\n            var provider = new MockableCachedAssociatedMetadataProvider();\n            var keys = new List<string>();\n\n            // Act\n            keys.Add(provider.GetCacheKey(typeof(string)));\n            keys.Add(provider.GetCacheKey(typeof(int)));\n            keys.Add(provider.GetCacheKey(typeof(Nullable<int>)));\n            keys.Add(provider.GetCacheKey(typeof(Nullable<bool>)));\n            keys.Add(provider.GetCacheKey(typeof(List<string>)));\n            keys.Add(provider.GetCacheKey(typeof(List<bool>)));\n\n            // Assert\n            Assert.Equal(keys.Distinct().Count(), keys.Count);\n        }\n\n        [Fact]\n        public void GetCacheKey_ResultsForTypesAndPropertiesDoNotCollide()\n        {\n            // Arrange\n            var provider = new MockableCachedAssociatedMetadataProvider();\n            var keys = new List<string>();\n\n            // Act\n            keys.Add(provider.GetCacheKey(typeof(string), \"Foo\"));\n            keys.Add(provider.GetCacheKey(typeof(string), \"Bar\"));\n            keys.Add(provider.GetCacheKey(typeof(int), \"Foo\"));\n            keys.Add(provider.GetCacheKey(typeof(Nullable<int>), \"Foo\"));\n            keys.Add(provider.GetCacheKey(typeof(Nullable<bool>), \"Foo\"));\n            keys.Add(provider.GetCacheKey(typeof(List<string>), \"Count\"));\n            keys.Add(provider.GetCacheKey(typeof(List<bool>), \"Count\"));\n            keys.Add(provider.GetCacheKey(typeof(Foo), \"BarBaz\"));\n            keys.Add(provider.GetCacheKey(typeof(FooBar), \"Baz\"));\n\n            // Assert\n            Assert.Equal(keys.Distinct().Count(), keys.Count);\n        }\n\n        private class Foo\n        {\n        }\n\n        private class FooBar\n        {\n        }\n\n        // GetMetadataForProperty\n\n        [Fact]\n        public void GetMetadataForPropertyCreatesPrototypeMetadataAndAddsItToCache()\n        {\n            // Arrange\n            var provider = new Mock<MockableCachedAssociatedMetadataProvider> { CallBase = true };\n\n            // Act\n            provider.Object.GetMetadataForProperty(() => 3, typeof(string), \"Length\");\n\n            // Assert\n            provider.Verify(p => p.CreateMetadataPrototypeImpl(It.IsAny<IEnumerable<Attribute>>(),\n                                                               typeof(string) /* containerType */,\n                                                               typeof(int) /* modelType */,\n                                                               \"Length\" /* propertyName */));\n            provider.Object.Cache.Verify(c => c.Add(provider.Object.GetCacheKey(typeof(string), \"Length\"),\n                                                    provider.Object.PrototypeMetadata,\n                                                    provider.Object.CacheItemPolicy, null));\n        }\n\n        [Fact]\n        public void GetMetadataForPropertyCreatesRealMetadataFromPrototype()\n        {\n            // Arrange\n            Func<object> accessor = () => 3;\n            var provider = new Mock<MockableCachedAssociatedMetadataProvider> { CallBase = true };\n\n            // Act\n            provider.Object.GetMetadataForProperty(accessor, typeof(string), \"Length\");\n\n            // Assert\n            provider.Verify(p => p.CreateMetadataFromPrototypeImpl(provider.Object.PrototypeMetadata, accessor));\n        }\n\n        [Fact]\n        public void MetaDataAwareAttributesForPropertyAreAppliedToMetadata()\n        {\n            // Arrange\n            MemoryCache memoryCache = new MemoryCache(\"testCache\");\n            MockableCachedAssociatedMetadataProvider provider = new MockableCachedAssociatedMetadataProvider(memoryCache);\n\n            // Act\n            ModelMetadata metadata = provider.GetMetadataForProperty(null, typeof(ClassWithMetaDataAwareAttributes), \"PropertyWithAdditionalValue\");\n\n            // Assert\n            Assert.True(metadata.AdditionalValues[\"baz\"].Equals(\"biz\"));\n        }\n\n        [Fact]\n        public void GetMetadataForPropertyTwiceOnlyCreatesAndCachesPrototypeOnce()\n        {\n            // Arrange\n            Func<object> accessor = () => 3;\n            var provider = new Mock<MockableCachedAssociatedMetadataProvider> { CallBase = true };\n\n            // Act\n            provider.Object.GetMetadataForProperty(accessor, typeof(string), \"Length\");\n            provider.Object.GetMetadataForProperty(accessor, typeof(string), \"Length\");\n\n            // Assert\n            provider.Verify(p => p.CreateMetadataPrototypeImpl(It.IsAny<IEnumerable<Attribute>>(),\n                                                               typeof(string) /* containerType */,\n                                                               typeof(int) /* modelType */,\n                                                               \"Length\" /* propertyName */),\n                            Times.Once());\n\n            provider.Verify(p => p.CreateMetadataFromPrototypeImpl(provider.Object.PrototypeMetadata, accessor),\n                            Times.Exactly(2));\n\n            provider.Object.Cache.Verify(c => c.Add(provider.Object.GetCacheKey(typeof(string), \"Length\"),\n                                                    provider.Object.PrototypeMetadata,\n                                                    provider.Object.CacheItemPolicy, null),\n                                         Times.Once());\n        }\n\n        // GetMetadataForType\n\n        [Fact]\n        public void GetMetadataForTypeCreatesPrototypeMetadataAndAddsItToCache()\n        {\n            // Arrange\n            var provider = new Mock<MockableCachedAssociatedMetadataProvider> { CallBase = true };\n\n            // Act\n            provider.Object.GetMetadataForType(() => \"foo\", typeof(string));\n\n            // Assert\n            provider.Verify(p => p.CreateMetadataPrototypeImpl(It.IsAny<IEnumerable<Attribute>>(),\n                                                               null /* containerType */,\n                                                               typeof(string) /* modelType */,\n                                                               null /* propertyName */));\n            provider.Object.Cache.Verify(c => c.Add(provider.Object.GetCacheKey(typeof(string), null),\n                                                    provider.Object.PrototypeMetadata,\n                                                    provider.Object.CacheItemPolicy, null));\n        }\n\n        [Fact]\n        public void GetMetadataForTypeCreatesRealMetadataFromPrototype()\n        {\n            // Arrange\n            Func<object> accessor = () => \"foo\";\n            var provider = new Mock<MockableCachedAssociatedMetadataProvider> { CallBase = true };\n\n            // Act\n            provider.Object.GetMetadataForType(accessor, typeof(string));\n\n            // Assert\n            provider.Verify(p => p.CreateMetadataFromPrototypeImpl(provider.Object.PrototypeMetadata, accessor));\n        }\n\n        [Fact]\n        public void MetaDataAwareAttributesForTypeAreAppliedToMetadata()\n        {\n            // Arrange\n            MemoryCache memoryCache = new MemoryCache(\"testCache\");\n            MockableCachedAssociatedMetadataProvider provider = new MockableCachedAssociatedMetadataProvider(memoryCache);\n\n            // Act\n            ModelMetadata metadata = provider.GetMetadataForType(null, typeof(ClassWithMetaDataAwareAttributes));\n\n            // Assert\n            Assert.True(metadata.AdditionalValues[\"foo\"].Equals(\"bar\"));\n        }\n\n        [Fact]\n        public void GetMetadataForTypeTwiceOnlyCreatesAndCachesPrototypeOnce()\n        {\n            // Arrange\n            Func<object> accessor = () => \"foo\";\n            var provider = new Mock<MockableCachedAssociatedMetadataProvider> { CallBase = true };\n\n            // Act\n            provider.Object.GetMetadataForType(accessor, typeof(string));\n            provider.Object.GetMetadataForType(accessor, typeof(string));\n\n            // Assert\n            provider.Verify(p => p.CreateMetadataPrototypeImpl(It.IsAny<IEnumerable<Attribute>>(),\n                                                               null /* containerType */,\n                                                               typeof(string) /* modelType */,\n                                                               null /* propertyName */),\n                            Times.Once());\n\n            provider.Verify(p => p.CreateMetadataFromPrototypeImpl(provider.Object.PrototypeMetadata, accessor),\n                            Times.Exactly(2));\n\n            provider.Object.Cache.Verify(c => c.Add(provider.Object.GetCacheKey(typeof(string), null),\n                                                    provider.Object.PrototypeMetadata,\n                                                    provider.Object.CacheItemPolicy, null),\n                                         Times.Once());\n        }\n\n        // Helpers\n\n        public class MockableCachedAssociatedMetadataProvider : CachedAssociatedMetadataProvider<ModelMetadata>\n        {\n            public Mock<MemoryCache> Cache;\n            public ModelMetadata PrototypeMetadata;\n            public ModelMetadata RealMetadata;\n\n            public MockableCachedAssociatedMetadataProvider()\n                : this(null)\n            {\n            }\n\n            public MockableCachedAssociatedMetadataProvider(MemoryCache memoryCache = null)\n            {\n                Cache = new Mock<MemoryCache>(\"MockMemoryCache\", null) { CallBase = true };\n                PrototypeMetadata = new ModelMetadata(this, null, null, typeof(string), null);\n                RealMetadata = new ModelMetadata(this, null, null, typeof(string), null);\n\n                PrototypeCache = memoryCache ?? Cache.Object;\n            }\n\n            public virtual ModelMetadata CreateMetadataPrototypeImpl(IEnumerable<Attribute> attributes, Type containerType, Type modelType, string propertyName)\n            {\n                return PrototypeMetadata;\n            }\n\n            public virtual ModelMetadata CreateMetadataFromPrototypeImpl(ModelMetadata prototype, Func<object> modelAccessor)\n            {\n                return RealMetadata;\n            }\n\n            protected override ModelMetadata CreateMetadataPrototype(IEnumerable<Attribute> attributes, Type containerType, Type modelType, string propertyName)\n            {\n                return CreateMetadataPrototypeImpl(attributes, containerType, modelType, propertyName);\n            }\n\n            protected override ModelMetadata CreateMetadataFromPrototype(ModelMetadata prototype, Func<object> modelAccessor)\n            {\n                return CreateMetadataFromPrototypeImpl(prototype, modelAccessor);\n            }\n        }\n\n        [AdditionalMetadata(\"foo\", \"bar\")]\n        private class ClassWithMetaDataAwareAttributes\n        {\n            [AdditionalMetadata(\"baz\", \"biz\")]\n            public string PropertyWithAdditionalValue { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/CachedDataAnnotationsModelMetadataProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc.Test\n{\n    public class CachedDataAnnotationsModelMetadataProviderTest : DataAnnotationsModelMetadataProviderTestBase\n    {\n        protected override AssociatedMetadataProvider MakeProvider()\n        {\n            return new CachedDataAnnotationsModelMetadataProvider();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/CancellationTokenModelBinderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class CancellationTokenModelBinderTest\n    {\n        [Fact]\n        public void BinderReturnsDefaultCancellationToken()\n        {\n            // Arrange\n            CancellationTokenModelBinder binder = new CancellationTokenModelBinder();\n\n            // Act\n            object binderResult = binder.BindModel(controllerContext: null, bindingContext: null);\n\n            // Assert\n            Assert.Equal(default(CancellationToken), binderResult);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ChildActionOnlyAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ChildActionOnlyAttributeTest\n    {\n        [Fact]\n        public void GuardClause()\n        {\n            // Arrange\n            ChildActionOnlyAttribute attr = new ChildActionOnlyAttribute();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => attr.OnAuthorization(null /* filterContext */),\n                \"filterContext\"\n                );\n        }\n\n        [Fact]\n        public void DoesNothingForChildRequest()\n        {\n            // Arrange\n            ChildActionOnlyAttribute attr = new ChildActionOnlyAttribute();\n            Mock<AuthorizationContext> context = new Mock<AuthorizationContext>();\n            context.Setup(c => c.IsChildAction).Returns(true);\n\n            // Act\n            attr.OnAuthorization(context.Object);\n\n            // Assert\n            Assert.Null(context.Object.Result);\n        }\n\n        [Fact]\n        public void ThrowsIfNotChildRequest()\n        {\n            // Arrange\n            ChildActionOnlyAttribute attr = new ChildActionOnlyAttribute();\n            Mock<AuthorizationContext> context = new Mock<AuthorizationContext>();\n            context.Setup(c => c.IsChildAction).Returns(false);\n            context.Setup(c => c.ActionDescriptor.ActionName).Returns(\"some name\");\n\n            // Act & assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { attr.OnAuthorization(context.Object); },\n                @\"The action 'some name' is accessible only by a child request.\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ChildActionValueProviderFactoryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ExpiicitRouteDataValueProviderFactoryTest\n    {\n        [Fact]\n        public void GetValueProviderReturnsChildActionValue()\n        {\n            // Arrange\n            ChildActionValueProviderFactory factory = new ChildActionValueProviderFactory();\n\n            ControllerContext controllerContext = new ControllerContext();\n            controllerContext.RouteData = new RouteData();\n\n            string conflictingKey = \"conflictingKey\";\n\n            controllerContext.RouteData.Values[\"conflictingKey\"] = 43;\n\n            DictionaryValueProvider<object> explictValueDictionary = new DictionaryValueProvider<object>(new RouteValueDictionary { { conflictingKey, 42 } }, CultureInfo.InvariantCulture);\n            controllerContext.RouteData.Values[ChildActionValueProvider.ChildActionValuesKey] = explictValueDictionary;\n\n            // Act\n            IValueProvider valueProvider = factory.GetValueProvider(controllerContext);\n\n            // Assert\n            Assert.Equal(typeof(ChildActionValueProvider), valueProvider.GetType());\n            ValueProviderResult vpResult = valueProvider.GetValue(conflictingKey);\n\n            Assert.NotNull(vpResult);\n            Assert.Equal(42, vpResult.RawValue);\n            Assert.Equal(\"42\", vpResult.AttemptedValue);\n            Assert.Equal(CultureInfo.InvariantCulture, vpResult.Culture);\n        }\n\n        [Fact]\n        public void GetValueProviderReturnsNullIfNoChildActionDictionary()\n        {\n            // Arrange\n            ChildActionValueProviderFactory factory = new ChildActionValueProviderFactory();\n\n            ControllerContext controllerContext = new ControllerContext();\n            controllerContext.RouteData = new RouteData();\n            controllerContext.RouteData.Values[\"forty-two\"] = 42;\n\n            // Act\n            IValueProvider valueProvider = factory.GetValueProvider(controllerContext);\n\n            // Assert\n            Assert.Equal(typeof(ChildActionValueProvider), valueProvider.GetType());\n            ValueProviderResult vpResult = valueProvider.GetValue(\"forty-two\");\n\n            Assert.Null(vpResult);\n        }\n\n        [Fact]\n        public void GetValueProviderReturnsNullIfKeyIsNotInChildActionDictionary()\n        {\n            // Arrange\n            ChildActionValueProviderFactory factory = new ChildActionValueProviderFactory();\n\n            ControllerContext controllerContext = new ControllerContext();\n            controllerContext.RouteData = new RouteData();\n            controllerContext.RouteData.Values[\"forty-two\"] = 42;\n\n            DictionaryValueProvider<object> explictValueDictionary = new DictionaryValueProvider<object>(new RouteValueDictionary { { \"forty-three\", 42 } }, CultureInfo.CurrentUICulture);\n            controllerContext.RouteData.Values[ChildActionValueProvider.ChildActionValuesKey] = explictValueDictionary;\n\n            // Act\n            IValueProvider valueProvider = factory.GetValueProvider(controllerContext);\n\n            // Assert\n            Assert.Equal(typeof(ChildActionValueProvider), valueProvider.GetType());\n            ValueProviderResult vpResult = valueProvider.GetValue(\"forty-two\");\n\n            Assert.Null(vpResult);\n        }\n\n        [Fact]\n        public void GetValueProvider_ThrowsIfControllerContextIsNull()\n        {\n            // Arrange\n            RouteDataValueProviderFactory factory = new RouteDataValueProviderFactory();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { factory.GetValueProvider(null); }, \"controllerContext\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ClientDataTypeModelValidatorProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ClientDataTypeModelValidatorProviderTest\n    {\n        private static readonly ModelMetadataProvider _metadataProvider = new DataAnnotationsModelMetadataProvider();\n        private static readonly ModelValidatorProvider _validatorProvider = new ClientDataTypeModelValidatorProvider();\n\n        private bool ReturnsValidator<TValidator>(string propertyName)\n        {\n            ModelMetadata metadata = _metadataProvider.GetMetadataForProperty(null, typeof(SampleModel), propertyName);\n            IEnumerable<ModelValidator> validators = _validatorProvider.GetValidators(metadata, new ControllerContext());\n            return validators.Any(v => v is TValidator);\n        }\n\n        [Theory]\n        [InlineData(\"Byte\"), InlineData(\"SByte\"), InlineData(\"Int16\"), InlineData(\"UInt16\")]\n        [InlineData(\"Int32\"), InlineData(\"UInt32\"), InlineData(\"Int64\"), InlineData(\"UInt64\")]\n        [InlineData(\"Single\"), InlineData(\"Double\"), InlineData(\"Decimal\"), InlineData(\"NullableInt32\")]\n        public void GetValidators_NumericValidatorTypes(string propertyName)\n        {\n            // Act & assert\n            Assert.True(ReturnsValidator<ClientDataTypeModelValidatorProvider.NumericModelValidator>(propertyName));\n        }\n\n        [Theory]\n        [InlineData(\"String\"), InlineData(\"Object\"), InlineData(\"DateTime\"), InlineData(\"NullableDateTime\")]\n        public void GetValidators_NonNumericValidatorTypes(string propertyName)\n        {\n            // Act & assert\n            Assert.False(ReturnsValidator<ClientDataTypeModelValidatorProvider.NumericModelValidator>(propertyName));\n        }\n\n        [Theory]\n        [InlineData(\"DateTime\"), InlineData(\"NullableDateTime\")]\n        public void GetValidators_DateTimeValidatorTypes(string propertyName)\n        {\n            // Act & assert\n            Assert.True(ReturnsValidator<ClientDataTypeModelValidatorProvider.DateModelValidator>(propertyName));\n        }\n\n        [Theory]\n        [InlineData(\"Int32\"), InlineData(\"NullableInt32\"), InlineData(\"String\"), InlineData(\"Object\"), InlineData(\"Time\")]\n        public void GetValidators_NonDateTimeValidatorTypes(string propertyName)\n        {\n            // Act & assert\n            Assert.False(ReturnsValidator<ClientDataTypeModelValidatorProvider.DateModelValidator>(propertyName));\n        }\n\n        [Fact]\n        public void GuardClauses()\n        {\n            // Arrange\n            ModelMetadata metadata = _metadataProvider.GetMetadataForType(null, typeof(SampleModel));\n\n            // Act & assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => new ClientDataTypeModelValidatorProvider.ClientModelValidator(metadata, new ControllerContext(), \"testValidationType\", errorMessage: null),\n                \"errorMessage\");\n\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => new ClientDataTypeModelValidatorProvider.ClientModelValidator(metadata, new ControllerContext(), \"testValidationType\", errorMessage: String.Empty),\n                \"errorMessage\");\n\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => new ClientDataTypeModelValidatorProvider.ClientModelValidator(metadata, new ControllerContext(), validationType: null, errorMessage: \"testErrorMessage\"),\n                \"validationType\");\n\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => new ClientDataTypeModelValidatorProvider.ClientModelValidator(metadata, new ControllerContext(), validationType: String.Empty, errorMessage: \"testErrorMessage\"),\n                \"validationType\");\n        }\n\n        [Fact]\n        public void GetValidators_ThrowsIfContextIsNull()\n        {\n            // Arrange\n            ModelMetadata metadata = _metadataProvider.GetMetadataForType(null, typeof(SampleModel));\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                () => _validatorProvider.GetValidators(metadata, null),\n                \"context\");\n        }\n\n        [Fact]\n        public void GetValidators_ThrowsIfMetadataIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                () => _validatorProvider.GetValidators(null, new ControllerContext()),\n                \"metadata\");\n        }\n\n        [Fact]\n        public void NumericValidator_GetClientValidationRules()\n        {\n            // Arrange\n            ModelMetadata metadata = _metadataProvider.GetMetadataForProperty(null, typeof(SampleModel), \"Int32\");\n            var validator = new ClientDataTypeModelValidatorProvider.NumericModelValidator(metadata, new ControllerContext());\n\n            // Act\n            ModelClientValidationRule[] rules = validator.GetClientValidationRules().ToArray();\n\n            // Assert\n            ModelClientValidationRule rule = Assert.Single(rules);\n            Assert.Equal(\"number\", rule.ValidationType);\n            Assert.Empty(rule.ValidationParameters);\n            Assert.Equal(\"The field Int32 must be a number.\", rule.ErrorMessage);\n        }\n\n        [Fact]\n        public void DateValidator_GetClientValidationRules()\n        {\n            // Arrange\n            ModelMetadata metadata = _metadataProvider.GetMetadataForProperty(null, typeof(SampleModel), \"DateTime\");\n            var validator = new ClientDataTypeModelValidatorProvider.DateModelValidator(metadata, new ControllerContext());\n\n            // Act\n            ModelClientValidationRule[] rules = validator.GetClientValidationRules().ToArray();\n\n            // Assert\n            ModelClientValidationRule rule = Assert.Single(rules);\n            Assert.Equal(\"date\", rule.ValidationType);\n            Assert.Empty(rule.ValidationParameters);\n            Assert.Equal(\"The field DateTime must be a date.\", rule.ErrorMessage);\n        }\n\n        [Fact]\n        public void ClientModelValidator_Validate_DoesNotReadPropertyValue()\n        {\n            // Arrange\n            ObservableModel model = new ObservableModel();\n            ModelMetadata metadata = _metadataProvider.GetMetadataForProperty(() => model.TheProperty, typeof(ObservableModel), \"TheProperty\");\n            ControllerContext controllerContext = new ControllerContext();\n\n            // Act\n            ModelValidator[] validators = new ClientDataTypeModelValidatorProvider().GetValidators(metadata, controllerContext).ToArray();\n            ModelValidationResult[] results = validators.SelectMany(o => o.Validate(model)).ToArray();\n\n            // Assert\n            Assert.Equal(new Type[] { typeof(ClientDataTypeModelValidatorProvider.NumericModelValidator) }, Array.ConvertAll(validators, o => o.GetType()));\n            Assert.Empty(results);\n            Assert.False(model.PropertyWasRead());\n        }\n\n        [Fact]\n        public void ClientModelValidator_Validate_ReturnsEmptyCollection()\n        {\n            // Arrange\n            ModelMetadata metadata = _metadataProvider.GetMetadataForType(null, typeof(object));\n            var validator = new ClientDataTypeModelValidatorProvider.ClientModelValidator(metadata, new ControllerContext(), \"testValidationType\", \"testErrorMessage\");\n\n            // Act\n            IEnumerable<ModelValidationResult> result = validator.Validate(null);\n\n            // Assert\n            Assert.Empty(result);\n        }\n\n        private class SampleModel\n        {\n            // these should have 'numeric' validators associated with them\n            public byte Byte { get; set; }\n            public sbyte SByte { get; set; }\n            public short Int16 { get; set; }\n            public ushort UInt16 { get; set; }\n            public int Int32 { get; set; }\n            public uint UInt32 { get; set; }\n            public long Int64 { get; set; }\n            public ulong UInt64 { get; set; }\n            public float Single { get; set; }\n            public double Double { get; set; }\n            public decimal Decimal { get; set; }\n\n            // this should also have a 'numeric' validator\n            public int? NullableInt32 { get; set; }\n\n            // this should have a 'date' validator associated with it\n            public DateTime DateTime { get; set; }\n\n            // this should also have a 'date' validator associated with it\n            public DateTime? NullableDateTime { get; set; }\n\n            [DataType(DataType.Time)]\n            public DateTime Time { get; set; }\n\n            // these shouldn't have any validators\n            public string String { get; set; }\n            public object Object { get; set; }\n        }\n\n        private class ObservableModel\n        {\n            private bool _propertyWasRead;\n\n            public int TheProperty\n            {\n                get\n                {\n                    _propertyWasRead = true;\n                    return 42;\n                }\n            }\n\n            public bool PropertyWasRead()\n            {\n                return _propertyWasRead;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/CompareAttributeAdapterTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing AnnotationsCompareAttribute = System.ComponentModel.DataAnnotations.CompareAttribute;\nusing MyResources = System.Web.Properties.Resources;\n\nnamespace System.Web.Mvc.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")] // Uses ModelMetadataProviders.Current\n    public class CompareAttributeAdapterTest\n    {\n        [Fact]\n        [ReplaceCulture]\n        public void ClientRulesWithCompareAttribute_ErrorMessageUsesDisplayName()\n        {\n            // Arrange\n            var metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => null, typeof(PropertyDisplayNameModel), \"MyProperty\");\n            var context = new ControllerContext();\n            var attribute = new AnnotationsCompareAttribute(\"OtherProperty\");\n            var adapter = new CompareAttributeAdapter(metadata, context, attribute);\n\n            // Act\n            var rules = adapter.GetClientValidationRules()\n                .OrderBy(r => r.ValidationType)\n                .ToArray();\n\n            // Assert\n            ModelClientValidationRule rule = Assert.Single(rules);\n            Assert.Equal(\"'MyPropertyDisplayName' and 'OtherPropertyDisplayName' do not match.\", rule.ErrorMessage);\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void ClientRulesWithCompareAttribute_ErrorMessageUsesPropertyName()\n        {\n            // Arrange\n            var metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => null, typeof(PropertyNameModel), \"MyProperty\");\n            var context = new ControllerContext();\n            var attribute = new AnnotationsCompareAttribute(\"OtherProperty\");\n            var adapter = new CompareAttributeAdapter(metadata, context, attribute);\n\n            // Act\n            var rules = adapter.GetClientValidationRules()\n                .OrderBy(r => r.ValidationType)\n                .ToArray();\n\n            // Assert\n            ModelClientValidationRule rule = Assert.Single(rules);\n            Assert.Equal(\"'MyProperty' and 'OtherProperty' do not match.\", rule.ErrorMessage);\n        }\n\n        [Fact]\n        public void ClientRulesWithCompareAttribute_ErrorMessageUsesOverride()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => null, typeof(PropertyNameModel), \"MyProperty\");\n            ControllerContext context = new ControllerContext();\n            AnnotationsCompareAttribute attribute = new AnnotationsCompareAttribute(\"OtherProperty\")\n            {\n                ErrorMessage = \"Hello '{0}', goodbye '{1}'.\",\n            };\n            ModelValidator adapter = new CompareAttributeAdapter(metadata, context, attribute);\n\n            // Act\n            ModelClientValidationRule[] rules = adapter.GetClientValidationRules()\n                .OrderBy(r => r.ValidationType)\n                .ToArray();\n\n            // Assert\n            ModelClientValidationRule rule = Assert.Single(rules);\n            Assert.Equal(\"Hello 'MyProperty', goodbye 'OtherProperty'.\", rule.ErrorMessage);\n        }\n\n        [Fact]\n        public void ClientRulesWithCompareAttribute_ErrorMessageUsesResourceOverride()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => null, typeof(PropertyNameModel), \"MyProperty\");\n            ControllerContext context = new ControllerContext();\n            AnnotationsCompareAttribute attribute = new AnnotationsCompareAttribute(\"OtherProperty\")\n            {\n                ErrorMessageResourceName = \"CompareAttributeTestResource\",\n                ErrorMessageResourceType = typeof(MyResources),\n            };\n            ModelValidator adapter = new CompareAttributeAdapter(metadata, context, attribute);\n\n            // Act\n            ModelClientValidationRule[] rules = adapter.GetClientValidationRules()\n                .OrderBy(r => r.ValidationType)\n                .ToArray();\n\n            // Assert\n            ModelClientValidationRule rule = Assert.Single(rules);\n            Assert.Equal(\"Hello 'MyProperty', goodbye 'OtherProperty'.\", rule.ErrorMessage);\n        }\n\n        private class PropertyDisplayNameModel\n        {\n            [DisplayName(\"MyPropertyDisplayName\")]\n            public string MyProperty { get; set; }\n\n            [DisplayName(\"OtherPropertyDisplayName\")]\n            public string OtherProperty { get; set; }\n        }\n\n        private class PropertyNameModel\n        {\n            public string MyProperty { get; set; }\n\n            public string OtherProperty { get; set; }\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/CompareAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")] // Uses ModelMetadataProviders.Current\n    public class CompareAttributeTest\n    {\n        [Fact]\n        public void GuardClauses()\n        {\n            //Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { new CompareAttribute(null); }, \"otherProperty\");\n\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { CompareAttribute.FormatPropertyForClientValidation(null); }, \"property\");\n        }\n\n        [Fact]\n        public void FormatPropertyForClientValidationPrependsStarDot()\n        {\n            string prepended = CompareAttribute.FormatPropertyForClientValidation(\"test\");\n            Assert.Equal(\"*.test\", prepended);\n        }\n\n        [Fact]\n        public void ValidateDoesNotThrowWhenComparedObjectsAreEqual()\n        {\n            object otherObject = new CompareObject(\"test\");\n            CompareObject currentObject = new CompareObject(\"test\");\n            ValidationContext testContext = new ValidationContext(otherObject, null, null);\n\n            CompareAttribute attr = new CompareAttribute(\"CompareProperty\");\n            attr.Validate(currentObject.CompareProperty, testContext);\n        }\n\n        [Fact]\n        public void ValidateThrowsWhenComparedObjectsAreNotEqual()\n        {\n            CompareObject currentObject = new CompareObject(\"a\");\n            object otherObject = new CompareObject(\"b\");\n\n            ValidationContext testContext = new ValidationContext(otherObject, null, null);\n            testContext.DisplayName = \"CurrentProperty\";\n\n            CompareAttribute attr = new CompareAttribute(\"CompareProperty\");\n            Assert.Throws<ValidationException>(\n                delegate { attr.Validate(currentObject.CompareProperty, testContext); }, \"'CurrentProperty' and 'CompareProperty' do not match.\");\n        }\n\n        [Fact]\n        public void ValidateThrowsWithOtherPropertyDisplayName()\n        {\n            CompareObject currentObject = new CompareObject(\"a\");\n            object otherObject = new CompareObject(\"b\");\n\n            ValidationContext testContext = new ValidationContext(otherObject, null, null);\n            testContext.DisplayName = \"CurrentProperty\";\n\n            CompareAttribute attr = new CompareAttribute(\"ComparePropertyWithDisplayName\");\n            Assert.Throws<ValidationException>(\n                delegate { attr.Validate(currentObject.CompareProperty, testContext); }, \"'CurrentProperty' and 'DisplayName' do not match.\");\n        }\n\n        [Fact]\n        public void ValidateUsesSetDisplayName()\n        {\n            CompareObject currentObject = new CompareObject(\"a\");\n            object otherObject = new CompareObject(\"b\");\n\n            ValidationContext testContext = new ValidationContext(otherObject, null, null);\n            testContext.DisplayName = \"CurrentProperty\";\n\n            CompareAttribute attr = new CompareAttribute(\"ComparePropertyWithDisplayName\");\n            attr.OtherPropertyDisplayName = \"SetDisplayName\";\n\n            Assert.Throws<ValidationException>(\n                delegate { attr.Validate(currentObject.CompareProperty, testContext); }, \"'CurrentProperty' and 'SetDisplayName' do not match.\");\n        }\n\n        [Fact]\n        public void ValidateThrowsWhenPropertyNameIsUnknown()\n        {\n            CompareObject currentObject = new CompareObject(\"a\");\n            object otherObject = new CompareObject(\"b\");\n\n            ValidationContext testContext = new ValidationContext(otherObject, null, null);\n            testContext.DisplayName = \"CurrentProperty\";\n\n            CompareAttribute attr = new CompareAttribute(\"UnknownPropertyName\");\n            Assert.Throws<ValidationException>(\n                () => attr.Validate(currentObject.CompareProperty, testContext),\n                \"Could not find a property named UnknownPropertyName.\"\n                );\n        }\n\n        [Fact]\n        public void GetClientValidationRulesReturnsModelClientValidationEqualToRule()\n        {\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            Mock<ModelMetadata> metadata = new Mock<ModelMetadata>(provider.Object, null, null, typeof(string), null);\n            metadata.Setup(m => m.DisplayName).Returns(\"CurrentProperty\");\n\n            CompareAttribute attr = new CompareAttribute(\"CompareProperty\");\n            List<ModelClientValidationRule> ruleList = new List<ModelClientValidationRule>(attr.GetClientValidationRules(metadata.Object, null));\n\n            ModelClientValidationRule rule = Assert.Single(ruleList);\n            ModelClientValidationEqualToRule actualRule = Assert.IsType<ModelClientValidationEqualToRule>(rule);\n\n            Assert.Equal(\"'CurrentProperty' and 'CompareProperty' do not match.\", actualRule.ErrorMessage);\n            Assert.Equal(\"equalto\", actualRule.ValidationType);\n            Assert.Equal(\"*.CompareProperty\", actualRule.ValidationParameters[\"other\"]);\n        }\n\n        [Fact]\n        public void ModelClientValidationEqualToRuleErrorMessageUsesOtherPropertyDisplayName()\n        {\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            ModelMetadata metadata = new ModelMetadata(provider.Object, typeof(CompareObject), null, typeof(string), null);\n            metadata.DisplayName = \"CurrentProperty\";\n\n            CompareAttribute attr = new CompareAttribute(\"ComparePropertyWithDisplayName\");\n            List<ModelClientValidationRule> ruleList = new List<ModelClientValidationRule>(attr.GetClientValidationRules(metadata, null));\n\n            ModelClientValidationRule rule = Assert.Single(ruleList);\n            ModelClientValidationEqualToRule actualRule = Assert.IsType<ModelClientValidationEqualToRule>(rule);\n\n            Assert.Equal(\"'CurrentProperty' and 'DisplayName' do not match.\", actualRule.ErrorMessage);\n            Assert.Equal(\"equalto\", actualRule.ValidationType);\n            Assert.Equal(\"*.ComparePropertyWithDisplayName\", actualRule.ValidationParameters[\"other\"]);\n        }\n\n        [Fact]\n        public void ModelClientValidationEqualToRuleUsesSetDisplayName()\n        {\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            ModelMetadata metadata = new ModelMetadata(provider.Object, typeof(CompareObject), null, typeof(string), null);\n            metadata.DisplayName = \"CurrentProperty\";\n\n            CompareAttribute attr = new CompareAttribute(\"ComparePropertyWithDisplayName\");\n            attr.OtherPropertyDisplayName = \"SetDisplayName\";\n\n            List<ModelClientValidationRule> ruleList = new List<ModelClientValidationRule>(attr.GetClientValidationRules(metadata, null));\n            ModelClientValidationRule rule = Assert.Single(ruleList);\n            ModelClientValidationEqualToRule actualRule = Assert.IsType<ModelClientValidationEqualToRule>(rule);\n\n            Assert.Equal(\"'CurrentProperty' and 'SetDisplayName' do not match.\", actualRule.ErrorMessage);\n        }\n\n        [Fact]\n        public void CompareAttributeCanBeDerivedFromAndOverrideIsValid()\n        {\n            object otherObject = new CompareObject(\"a\");\n            CompareObject currentObject = new CompareObject(\"b\");\n            ValidationContext testContext = new ValidationContext(otherObject, null, null);\n\n            DerivedCompareAttribute attr = new DerivedCompareAttribute(\"CompareProperty\");\n            attr.Validate(currentObject.CompareProperty, testContext);\n        }\n\n        private class DerivedCompareAttribute : CompareAttribute\n        {\n            public DerivedCompareAttribute(string otherProperty)\n                : base(otherProperty)\n            {\n            }\n\n            public override bool IsValid(object value)\n            {\n                return false;\n            }\n\n            protected override ValidationResult IsValid(object value, ValidationContext context)\n            {\n                return null;\n            }\n        }\n\n        private class CompareObject\n        {\n            public string CompareProperty { get; set; }\n\n            [Display(Name = \"DisplayName\")]\n            public string ComparePropertyWithDisplayName { get; set; }\n\n            public CompareObject(string otherValue)\n            {\n                CompareProperty = otherValue;\n                ComparePropertyWithDisplayName = otherValue;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ContentResultTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Text;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ContentResultTest\n    {\n        [Fact]\n        public void AllPropertiesDefaultToNull()\n        {\n            // Act\n            ContentResult result = new ContentResult();\n\n            // Assert\n            Assert.Null(result.Content);\n            Assert.Null(result.ContentEncoding);\n            Assert.Null(result.ContentType);\n        }\n\n        [Fact]\n        public void EmptyContentTypeIsNotOutput()\n        {\n            // Arrange\n            string content = \"Some content.\";\n            Encoding contentEncoding = Encoding.UTF8;\n\n            // Arrange expectations\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>(MockBehavior.Strict);\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentEncoding = contentEncoding).Verifiable();\n            mockControllerContext.Setup(c => c.HttpContext.Response.Write(content)).Verifiable();\n\n            ContentResult result = new ContentResult\n            {\n                Content = content,\n                ContentType = String.Empty,\n                ContentEncoding = contentEncoding\n            };\n\n            // Act\n            result.ExecuteResult(mockControllerContext.Object);\n\n            // Assert\n            mockControllerContext.Verify();\n        }\n\n        [Fact]\n        public void ExecuteResult()\n        {\n            // Arrange\n            string content = \"Some content.\";\n            string contentType = \"Some content type.\";\n            Encoding contentEncoding = Encoding.UTF8;\n\n            // Arrange expectations\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>(MockBehavior.Strict);\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType = contentType).Verifiable();\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentEncoding = contentEncoding).Verifiable();\n            mockControllerContext.Setup(c => c.HttpContext.Response.Write(content)).Verifiable();\n\n            ContentResult result = new ContentResult\n            {\n                Content = content,\n                ContentType = contentType,\n                ContentEncoding = contentEncoding\n            };\n\n            // Act\n            result.ExecuteResult(mockControllerContext.Object);\n\n            // Assert\n            mockControllerContext.Verify();\n        }\n\n        [Fact]\n        public void ExecuteResultWithNullContextThrows()\n        {\n            Assert.ThrowsArgumentNull(\n                delegate { new ContentResult().ExecuteResult(null /* context */); }, \"context\");\n        }\n\n        [Fact]\n        public void NullContentIsNotOutput()\n        {\n            // Arrange\n            string contentType = \"Some content type.\";\n            Encoding contentEncoding = Encoding.UTF8;\n\n            // Arrange expectations\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType = contentType).Verifiable();\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentEncoding = contentEncoding).Verifiable();\n\n            ContentResult result = new ContentResult\n            {\n                ContentType = contentType,\n                ContentEncoding = contentEncoding\n            };\n\n            // Act\n            result.ExecuteResult(mockControllerContext.Object);\n\n            // Assert\n            mockControllerContext.Verify();\n        }\n\n        [Fact]\n        public void NullContentEncodingIsNotOutput()\n        {\n            // Arrange\n            string content = \"Some content.\";\n            string contentType = \"Some content type.\";\n\n            // Arrange expectations\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>(MockBehavior.Strict);\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType = contentType).Verifiable();\n            mockControllerContext.Setup(c => c.HttpContext.Response.Write(content)).Verifiable();\n\n            ContentResult result = new ContentResult\n            {\n                Content = content,\n                ContentType = contentType,\n            };\n\n            // Act\n            result.ExecuteResult(mockControllerContext.Object);\n\n            // Assert\n            mockControllerContext.Verify();\n        }\n\n        [Fact]\n        public void NullContentTypeIsNotOutput()\n        {\n            // Arrange\n            string content = \"Some content.\";\n            Encoding contentEncoding = Encoding.UTF8;\n\n            // Arrange expectations\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>(MockBehavior.Strict);\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentEncoding = contentEncoding).Verifiable();\n            mockControllerContext.Setup(c => c.HttpContext.Response.Write(content)).Verifiable();\n\n            ContentResult result = new ContentResult\n            {\n                Content = content,\n                ContentEncoding = contentEncoding\n            };\n\n            // Act\n            result.ExecuteResult(mockControllerContext.Object);\n\n            // Assert\n            mockControllerContext.Verify();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ControllerActionInvokerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Linq;\nusing System.Reflection;\nusing System.Security.Claims;\nusing System.Security.Principal;\nusing System.Threading;\nusing System.Web.Mvc.Filters;\nusing System.Web.Routing;\nusing System.Web.Routing.Test;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")] // Uses ModelMetadataProviders.Current\n    public class ControllerActionInvokerTest\n    {\n        [Fact]\n        public void CreateActionResultWithActionResultParameterReturnsParameterUnchanged()\n        {\n            // Arrange\n            ControllerActionInvokerHelper invoker = new ControllerActionInvokerHelper();\n            ActionResult originalResult = new JsonResult();\n\n            // Act\n            ActionResult returnedActionResult = invoker.PublicCreateActionResult(null, null, originalResult);\n\n            // Assert\n            Assert.Same(originalResult, returnedActionResult);\n        }\n\n        [Fact]\n        public void CreateActionResultWithNullParameterReturnsEmptyResult()\n        {\n            // Arrange\n            ControllerActionInvokerHelper invoker = new ControllerActionInvokerHelper();\n\n            // Act\n            ActionResult returnedActionResult = invoker.PublicCreateActionResult(null, null, null);\n\n            // Assert\n            Assert.IsType<EmptyResult>(returnedActionResult);\n        }\n\n        [Fact]\n        public void CreateActionResultWithObjectParameterReturnsContentResult()\n        {\n            // Arrange\n            ControllerActionInvokerHelper invoker = new ControllerActionInvokerHelper();\n            object originalReturnValue = new CultureReflector();\n\n            // Act\n            ActionResult returnedActionResult = invoker.PublicCreateActionResult(null, null, originalReturnValue);\n\n            // Assert\n            ContentResult contentResult = Assert.IsType<ContentResult>(returnedActionResult);\n            Assert.Equal(\"ivl\", contentResult.Content);\n        }\n\n        [Fact]\n        public void FindAction()\n        {\n            // Arrange\n            EmptyController controller = new EmptyController();\n            ControllerContext controllerContext = GetControllerContext(controller);\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            ActionDescriptor expectedAd = new Mock<ActionDescriptor>().Object;\n            Mock<ControllerDescriptor> mockCd = new Mock<ControllerDescriptor>();\n            mockCd.Setup(cd => cd.FindAction(controllerContext, \"someAction\")).Returns(expectedAd);\n\n            // Act\n            ActionDescriptor returnedAd = helper.PublicFindAction(controllerContext, mockCd.Object, \"someAction\");\n\n            // Assert\n            Assert.Equal(expectedAd, returnedAd);\n        }\n\n        [Fact]\n        public void FindActionDoesNotMatchConstructor()\n        {\n            // FindActionMethod() shouldn't match special-named methods like type constructors.\n\n            // Arrange\n            Controller controller = new FindMethodController();\n            ControllerContext context = GetControllerContext(controller);\n            ControllerDescriptor cd = new ReflectedControllerDescriptor(typeof(FindMethodController));\n\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            // Act\n            ActionDescriptor ad = helper.PublicFindAction(context, cd, \".ctor\");\n            ActionDescriptor ad2 = helper.PublicFindAction(context, cd, \"FindMethodController\");\n\n            // Assert\n            Assert.Null(ad);\n            Assert.Null(ad2);\n        }\n\n        [Fact]\n        public void FindActionDoesNotMatchEvent()\n        {\n            // FindActionMethod() should skip methods that aren't publicly visible.\n\n            // Arrange\n            Controller controller = new FindMethodController();\n            ControllerContext context = GetControllerContext(controller);\n            ControllerDescriptor cd = new ReflectedControllerDescriptor(typeof(FindMethodController));\n\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            // Act\n            ActionDescriptor ad = helper.PublicFindAction(context, cd, \"add_Event\");\n\n            // Assert\n            Assert.Null(ad);\n        }\n\n        [Fact]\n        public void FindActionDoesNotMatchInternalMethod()\n        {\n            // FindActionMethod() should skip methods that aren't publicly visible.\n\n            // Arrange\n            Controller controller = new FindMethodController();\n            ControllerContext context = GetControllerContext(controller);\n            ControllerDescriptor cd = new ReflectedControllerDescriptor(typeof(FindMethodController));\n\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            // Act\n            ActionDescriptor ad = helper.PublicFindAction(context, cd, \"InternalMethod\");\n\n            // Assert\n            Assert.Null(ad);\n        }\n\n        [Fact]\n        public void FindActionDoesNotMatchMethodsDefinedOnControllerType()\n        {\n            // FindActionMethod() shouldn't match methods originally defined on the Controller type, e.g. Dispose().\n\n            // Arrange\n            Controller controller = new BlankController();\n            ControllerDescriptor cd = new ReflectedControllerDescriptor(typeof(BlankController));\n            ControllerContext context = GetControllerContext(controller);\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n            var methods = typeof(Controller).GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);\n\n            // Act & Assert\n            foreach (var method in methods)\n            {\n                bool wasFound = true;\n                try\n                {\n                    ActionDescriptor ad = helper.PublicFindAction(context, cd, method.Name);\n                    wasFound = (ad != null);\n                }\n                finally\n                {\n                    Assert.False(wasFound, \"FindAction() should return false for methods defined on the Controller class: \" + method);\n                }\n            }\n        }\n\n        [Fact]\n        public void FindActionDoesNotMatchMethodsDefinedOnObjectType()\n        {\n            // FindActionMethod() shouldn't match methods originally defined on the Object type, e.g. ToString().\n\n            // Arrange\n            Controller controller = new FindMethodController();\n            ControllerContext context = GetControllerContext(controller);\n            ControllerDescriptor cd = new ReflectedControllerDescriptor(typeof(FindMethodController));\n\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            // Act\n            ActionDescriptor ad = helper.PublicFindAction(context, cd, \"ToString\");\n\n            // Assert\n            Assert.Null(ad);\n        }\n\n        [Fact]\n        public void FindActionDoesNotMatchNonActionMethod()\n        {\n            // FindActionMethod() should respect the [NonAction] attribute.\n\n            // Arrange\n            Controller controller = new FindMethodController();\n            ControllerContext context = GetControllerContext(controller);\n            ControllerDescriptor cd = new ReflectedControllerDescriptor(typeof(FindMethodController));\n\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            // Act\n            ActionDescriptor ad = helper.PublicFindAction(context, cd, \"NonActionMethod\");\n\n            // Assert\n            Assert.Null(ad);\n        }\n\n        [Fact]\n        public void FindActionDoesNotMatchOverriddenNonActionMethod()\n        {\n            // FindActionMethod() should trace the method's inheritance chain looking for the [NonAction] attribute.\n\n            // Arrange\n            Controller controller = new DerivedFindMethodController();\n            ControllerContext context = GetControllerContext(controller);\n            ControllerDescriptor cd = new ReflectedControllerDescriptor(typeof(DerivedFindMethodController));\n\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            // Act\n            ActionDescriptor ad = helper.PublicFindAction(context, cd, \"InternalMethod\");\n\n            // Assert\n            Assert.Null(ad);\n        }\n\n        [Fact]\n        public void FindActionDoesNotMatchPrivateMethod()\n        {\n            // FindActionMethod() should skip methods that aren't publicly visible.\n\n            // Arrange\n            Controller controller = new FindMethodController();\n            ControllerContext context = GetControllerContext(controller);\n            ControllerDescriptor cd = new ReflectedControllerDescriptor(typeof(FindMethodController));\n\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            // Act\n            ActionDescriptor ad = helper.PublicFindAction(context, cd, \"PrivateMethod\");\n\n            // Assert\n            Assert.Null(ad);\n        }\n\n        [Fact]\n        public void FindActionDoesNotMatchProperty()\n        {\n            // FindActionMethod() shouldn't match special-named methods like property getters.\n\n            // Arrange\n            Controller controller = new FindMethodController();\n            ControllerContext context = GetControllerContext(controller);\n            ControllerDescriptor cd = new ReflectedControllerDescriptor(typeof(FindMethodController));\n\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            // Act\n            ActionDescriptor ad = helper.PublicFindAction(context, cd, \"get_Property\");\n\n            // Assert\n            Assert.Null(ad);\n        }\n\n        [Fact]\n        public void FindActionDoesNotMatchProtectedMethod()\n        {\n            // FindActionMethod() should skip methods that aren't publicly visible.\n\n            // Arrange\n            Controller controller = new FindMethodController();\n            ControllerContext context = GetControllerContext(controller);\n            ControllerDescriptor cd = new ReflectedControllerDescriptor(typeof(FindMethodController));\n\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            // Act\n            ActionDescriptor ad = helper.PublicFindAction(context, cd, \"ProtectedMethod\");\n\n            // Assert\n            Assert.Null(ad);\n        }\n\n        [Fact]\n        public void FindActionIsCaseInsensitive()\n        {\n            // Arrange\n            Controller controller = new FindMethodController();\n            ControllerContext context = GetControllerContext(controller);\n            ControllerDescriptor cd = new ReflectedControllerDescriptor(typeof(FindMethodController));\n            MethodInfo expectedMethodInfo = typeof(FindMethodController).GetMethod(\"ValidActionMethod\");\n\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            // Act\n            ActionDescriptor ad1 = helper.PublicFindAction(context, cd, \"validactionmethod\");\n            ActionDescriptor ad2 = helper.PublicFindAction(context, cd, \"VALIDACTIONMETHOD\");\n\n            // Assert\n            ReflectedActionDescriptor rad1 = Assert.IsType<ReflectedActionDescriptor>(ad1);\n            Assert.Same(expectedMethodInfo, rad1.MethodInfo);\n            ReflectedActionDescriptor rad2 = Assert.IsType<ReflectedActionDescriptor>(ad2);\n            Assert.Same(expectedMethodInfo, rad2.MethodInfo);\n        }\n\n        [Fact]\n        public void FindActionMatchesActionMethodWithClosedGenerics()\n        {\n            // FindActionMethod() should work with generic methods as long as there are no open types.\n\n            // Arrange\n            Controller controller = new GenericFindMethodController<int>();\n            ControllerContext context = GetControllerContext(controller);\n            ControllerDescriptor cd = new ReflectedControllerDescriptor(typeof(GenericFindMethodController<int>));\n            MethodInfo expectedMethodInfo = typeof(GenericFindMethodController<int>).GetMethod(\"ClosedGenericMethod\");\n\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            // Act\n            ActionDescriptor ad = helper.PublicFindAction(context, cd, \"ClosedGenericMethod\");\n\n            // Assert\n            ReflectedActionDescriptor rad = Assert.IsType<ReflectedActionDescriptor>(ad);\n            Assert.Same(expectedMethodInfo, rad.MethodInfo);\n        }\n\n        [Fact]\n        public void FindActionMatchesNewActionMethodsHidingNonActionMethods()\n        {\n            // FindActionMethod() should stop looking for [NonAction] in the method's inheritance chain when it sees\n            // that a method in a derived class hides the a method in the base class.\n\n            // Arrange\n            Controller controller = new DerivedFindMethodController();\n            ControllerContext context = GetControllerContext(controller);\n            ControllerDescriptor cd = new ReflectedControllerDescriptor(typeof(DerivedFindMethodController));\n            MethodInfo expectedMethodInfo = typeof(DerivedFindMethodController).GetMethod(\"DerivedIsActionMethod\");\n\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            // Act\n            ActionDescriptor ad = helper.PublicFindAction(context, cd, \"DerivedIsActionMethod\");\n\n            // Assert\n            ReflectedActionDescriptor rad = Assert.IsType<ReflectedActionDescriptor>(ad);\n            Assert.Same(expectedMethodInfo, rad.MethodInfo);\n        }\n\n        [Fact]\n        public void GetControllerDescriptor()\n        {\n            // Arrange\n            EmptyController controller = new EmptyController();\n            ControllerContext controllerContext = GetControllerContext(controller);\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            // Act\n            ControllerDescriptor cd = helper.PublicGetControllerDescriptor(controllerContext);\n\n            // Assert\n            Assert.IsType<ReflectedControllerDescriptor>(cd);\n            Assert.Equal(typeof(EmptyController), cd.ControllerType);\n        }\n\n        [Fact]\n        public void GetFiltersSplitsFilterObjectsIntoFilterInfo()\n        {\n            // Arrange\n            IActionFilter actionFilter = new Mock<IActionFilter>().Object;\n            IResultFilter resultFilter = new Mock<IResultFilter>().Object;\n            IAuthorizationFilter authorizationFilter = new Mock<IAuthorizationFilter>().Object;\n            IAuthenticationFilter authenticationFilter = new Mock<IAuthenticationFilter>().Object;\n            IExceptionFilter exFilter = new Mock<IExceptionFilter>().Object;\n            object noneOfTheAbove = new object();\n            ControllerActionInvokerHelper invoker = new ControllerActionInvokerHelper(actionFilter, authorizationFilter, authenticationFilter, exFilter, resultFilter, noneOfTheAbove);\n            ControllerContext context = new ControllerContext();\n            ActionDescriptor descriptor = new Mock<ActionDescriptor>().Object;\n\n            // Act\n            FilterInfo result = invoker.PublicGetFilters(context, descriptor);\n\n            // Assert\n            Assert.Same(actionFilter, result.ActionFilters.Single());\n            Assert.Same(authorizationFilter, result.AuthorizationFilters.Single());\n            Assert.Same(authenticationFilter, result.AuthenticationFilters.Single());\n            Assert.Same(exFilter, result.ExceptionFilters.Single());\n            Assert.Same(resultFilter, result.ResultFilters.Single());\n        }\n\n        [Fact]\n        public void GetParameterValueAllowsAllSubpropertiesIfBindAttributeNotSpecified()\n        {\n            // Arrange\n            CustomConverterController controller = new CustomConverterController();\n            ControllerContext controllerContext = GetControllerContext(controller);\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            ParameterInfo paramWithoutBindAttribute = typeof(CustomConverterController).GetMethod(\"ParameterWithoutBindAttribute\").GetParameters()[0];\n            ReflectedParameterDescriptor pd = new ReflectedParameterDescriptor(paramWithoutBindAttribute, new Mock<ActionDescriptor>().Object);\n\n            // Act\n            object valueWithoutBindAttribute = helper.PublicGetParameterValue(controllerContext, pd);\n\n            // Assert\n            Assert.Equal(\"foo=True&bar=True\", valueWithoutBindAttribute);\n        }\n\n        [Fact]\n        public void GetParameterValueResolvesConvertersInCorrectOrderOfPrecedence()\n        {\n            // Order of precedence:\n            //   1. Attributes on the parameter itself\n            //   2. Query the global converter provider\n\n            // Arrange\n            CustomConverterController controller = new CustomConverterController();\n            Dictionary<string, object> values = new Dictionary<string, object> { { \"foo\", \"fooValue\" } };\n            ControllerContext controllerContext = GetControllerContext(controller, values);\n            controller.ControllerContext = controllerContext;\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            ParameterInfo paramWithOneConverter = typeof(CustomConverterController).GetMethod(\"ParameterHasOneConverter\").GetParameters()[0];\n            ReflectedParameterDescriptor pdOneConverter = new ReflectedParameterDescriptor(paramWithOneConverter, new Mock<ActionDescriptor>().Object);\n            ParameterInfo paramWithNoConverters = typeof(CustomConverterController).GetMethod(\"ParameterHasNoConverters\").GetParameters()[0];\n            ReflectedParameterDescriptor pdNoConverters = new ReflectedParameterDescriptor(paramWithNoConverters, new Mock<ActionDescriptor>().Object);\n\n            // Act\n            object valueWithOneConverter = helper.PublicGetParameterValue(controllerContext, pdOneConverter);\n            object valueWithNoConverters = helper.PublicGetParameterValue(controllerContext, pdNoConverters);\n\n            // Assert\n            Assert.Equal(\"foo_String\", valueWithOneConverter);\n            Assert.Equal(\"fooValue\", valueWithNoConverters);\n        }\n\n        [Fact]\n        public void GetParameterValueRespectsBindAttribute()\n        {\n            // Arrange\n            CustomConverterController controller = new CustomConverterController();\n            ControllerContext controllerContext = GetControllerContext(controller);\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            ParameterInfo paramWithBindAttribute = typeof(CustomConverterController).GetMethod(\"ParameterHasBindAttribute\").GetParameters()[0];\n            ReflectedParameterDescriptor pd = new ReflectedParameterDescriptor(paramWithBindAttribute, new Mock<ActionDescriptor>().Object);\n\n            // Act\n            object valueWithBindAttribute = helper.PublicGetParameterValue(controllerContext, pd);\n\n            // Assert\n            Assert.Equal(\"foo=True&bar=False\", valueWithBindAttribute);\n        }\n\n        [Fact]\n        public void GetParameterValueRespectsBindAttributePrefix()\n        {\n            // Arrange\n            CustomConverterController controller = new CustomConverterController();\n            Dictionary<string, object> values = new Dictionary<string, object> { { \"foo\", \"fooValue\" }, { \"bar\", \"barValue\" } };\n            ControllerContext controllerContext = GetControllerContext(controller, values);\n            controller.ControllerContext = controllerContext;\n\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            ParameterInfo paramWithFieldPrefix = typeof(CustomConverterController).GetMethod(\"ParameterHasFieldPrefix\").GetParameters()[0];\n            ReflectedParameterDescriptor pd = new ReflectedParameterDescriptor(paramWithFieldPrefix, new Mock<ActionDescriptor>().Object);\n\n            // Act\n            object parameterValue = helper.PublicGetParameterValue(controllerContext, pd);\n\n            // Assert\n            Assert.Equal(\"barValue\", parameterValue);\n        }\n\n        [Fact]\n        public void GetParameterValueRespectsBindAttributePrefixOnComplexType()\n        {\n            // Arrange\n            CustomConverterController controller = new CustomConverterController();\n            Dictionary<string, object> values = new Dictionary<string, object> { { \"intprop\", \"123\" }, { \"stringprop\", \"hello\" } };\n            ControllerContext controllerContext = GetControllerContext(controller, values);\n            controller.ControllerContext = controllerContext;\n\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            ParameterInfo paramWithFieldPrefix = typeof(CustomConverterController).GetMethod(\"ParameterHasPrefixAndComplexType\").GetParameters()[0];\n            ReflectedParameterDescriptor pd = new ReflectedParameterDescriptor(paramWithFieldPrefix, new Mock<ActionDescriptor>().Object);\n\n            // Act\n            MySimpleModel parameterValue = helper.PublicGetParameterValue(controllerContext, pd) as MySimpleModel;\n\n            // Assert\n            Assert.Null(parameterValue);\n        }\n\n        [Fact]\n        public void GetParameterValueRespectsBindAttributeNullPrefix()\n        {\n            // Arrange\n            CustomConverterController controller = new CustomConverterController();\n            Dictionary<string, object> values = new Dictionary<string, object> { { \"foo\", \"fooValue\" }, { \"bar\", \"barValue\" } };\n            ControllerContext controllerContext = GetControllerContext(controller, values);\n            controller.ControllerContext = controllerContext;\n\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            ParameterInfo paramWithFieldPrefix = typeof(CustomConverterController).GetMethod(\"ParameterHasNullFieldPrefix\").GetParameters()[0];\n            ReflectedParameterDescriptor pd = new ReflectedParameterDescriptor(paramWithFieldPrefix, new Mock<ActionDescriptor>().Object);\n\n            // Act\n            object parameterValue = helper.PublicGetParameterValue(controllerContext, pd);\n\n            // Assert\n            Assert.Equal(\"fooValue\", parameterValue);\n        }\n\n        [Fact]\n        public void GetParameterValueRespectsBindAttributeNullPrefixOnComplexType()\n        {\n            // Arrange\n            CustomConverterController controller = new CustomConverterController();\n            Dictionary<string, object> values = new Dictionary<string, object> { { \"intprop\", \"123\" }, { \"stringprop\", \"hello\" } };\n            ControllerContext controllerContext = GetControllerContext(controller, values);\n            controller.ControllerContext = controllerContext;\n\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            ParameterInfo paramWithFieldPrefix = typeof(CustomConverterController).GetMethod(\"ParameterHasNoPrefixAndComplexType\").GetParameters()[0];\n            ReflectedParameterDescriptor pd = new ReflectedParameterDescriptor(paramWithFieldPrefix, new Mock<ActionDescriptor>().Object);\n\n            // Act\n            MySimpleModel parameterValue = helper.PublicGetParameterValue(controllerContext, pd) as MySimpleModel;\n\n            // Assert\n            Assert.NotNull(parameterValue);\n            Assert.Equal(123, parameterValue.IntProp);\n            Assert.Equal(\"hello\", parameterValue.StringProp);\n        }\n\n        [Fact]\n        public void GetParameterValueRespectsBindAttributeEmptyPrefix()\n        {\n            // Arrange\n            CustomConverterController controller = new CustomConverterController();\n            Dictionary<string, object> values = new Dictionary<string, object> { { \"foo\", \"fooValue\" }, { \"bar\", \"barValue\" }, { \"intprop\", \"123\" }, { \"stringprop\", \"hello\" } };\n            ControllerContext controllerContext = GetControllerContext(controller, values);\n            controller.ControllerContext = controllerContext;\n\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            ParameterInfo paramWithFieldPrefix = typeof(CustomConverterController).GetMethod(\"ParameterHasEmptyFieldPrefix\").GetParameters()[0];\n            ReflectedParameterDescriptor pd = new ReflectedParameterDescriptor(paramWithFieldPrefix, new Mock<ActionDescriptor>().Object);\n\n            // Act\n            MySimpleModel parameterValue = helper.PublicGetParameterValue(controllerContext, pd) as MySimpleModel;\n\n            // Assert\n            Assert.NotNull(parameterValue);\n            Assert.Equal(123, parameterValue.IntProp);\n            Assert.Equal(\"hello\", parameterValue.StringProp);\n        }\n\n        [Fact]\n        public void GetParameterValueRespectsDefaultValueAttribute()\n        {\n            // Arrange\n            CustomConverterController controller = new CustomConverterController();\n            ControllerContext controllerContext = GetControllerContext(controller);\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n            controller.ValueProvider = new SimpleValueProvider();\n\n            ParameterInfo paramWithDefaultValueAttribute = typeof(CustomConverterController).GetMethod(\"ParameterHasDefaultValueAttribute\").GetParameters()[0];\n            ReflectedParameterDescriptor pd = new ReflectedParameterDescriptor(paramWithDefaultValueAttribute, new Mock<ActionDescriptor>().Object);\n\n            // Act\n            object valueWithDefaultValueAttribute = helper.PublicGetParameterValue(controllerContext, pd);\n\n            // Assert\n            Assert.Equal(42, valueWithDefaultValueAttribute);\n        }\n\n        [Fact]\n        public void GetParameterValueReturnsNullIfCannotConvertNonRequiredParameter()\n        {\n            // Arrange\n            Dictionary<string, object> dict = new Dictionary<string, object>()\n            {\n                { \"id\", DateTime.Now } // cannot convert DateTime to Nullable<int>\n            };\n            var controller = new ParameterTestingController();\n            ControllerContext context = GetControllerContext(controller, dict);\n            controller.ControllerContext = context;\n\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n            MethodInfo mi = typeof(ParameterTestingController).GetMethod(\"TakesNullableInt\");\n            ParameterInfo[] pis = mi.GetParameters();\n            ReflectedParameterDescriptor pd = new ReflectedParameterDescriptor(pis[0], new Mock<ActionDescriptor>().Object);\n\n            // Act\n            object oValue = helper.PublicGetParameterValue(context, pd);\n\n            // Assert\n            Assert.Null(oValue);\n        }\n\n        [Fact]\n        public void GetParameterValueReturnsNullIfNullableTypeValueNotFound()\n        {\n            // Arrange\n            var controller = new ParameterTestingController();\n            ControllerContext context = GetControllerContext(controller);\n            controller.ControllerContext = context;\n            controller.ValueProvider = new SimpleValueProvider();\n\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n            MethodInfo mi = typeof(ParameterTestingController).GetMethod(\"TakesNullableInt\");\n            ParameterInfo[] pis = mi.GetParameters();\n            ReflectedParameterDescriptor pd = new ReflectedParameterDescriptor(pis[0], new Mock<ActionDescriptor>().Object);\n\n            // Act\n            object oValue = helper.PublicGetParameterValue(context, pd);\n\n            // Assert\n            Assert.Null(oValue);\n        }\n\n        [Fact]\n        public void GetParameterValueReturnsNullIfReferenceTypeValueNotFound()\n        {\n            // Arrange\n            var controller = new ParameterTestingController();\n            ControllerContext context = GetControllerContext(controller);\n            controller.ControllerContext = context;\n            controller.ValueProvider = new SimpleValueProvider();\n\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n            MethodInfo mi = typeof(ParameterTestingController).GetMethod(\"Foo\");\n            ParameterInfo[] pis = mi.GetParameters();\n            ReflectedParameterDescriptor pd = new ReflectedParameterDescriptor(pis[0], new Mock<ActionDescriptor>().Object);\n\n            // Act\n            object oValue = helper.PublicGetParameterValue(context, pd);\n\n            // Assert\n            Assert.Null(oValue);\n        }\n\n        [Fact]\n        public void GetParameterValuesCallsGetParameterValue()\n        {\n            // Arrange\n            ControllerBase controller = new ParameterTestingController();\n            IDictionary<string, object> dict = new Dictionary<string, object>();\n            ControllerContext context = GetControllerContext(controller);\n            MethodInfo mi = typeof(ParameterTestingController).GetMethod(\"Foo\");\n            ReflectedActionDescriptor ad = new ReflectedActionDescriptor(mi, \"Foo\", new Mock<ControllerDescriptor>().Object);\n            ParameterDescriptor[] pds = ad.GetParameters();\n\n            Mock<ControllerActionInvokerHelper> mockHelper = new Mock<ControllerActionInvokerHelper>() { CallBase = true };\n            mockHelper.Setup(h => h.PublicGetParameterValue(context, pds[0])).Returns(\"Myfoo\").Verifiable();\n            mockHelper.Setup(h => h.PublicGetParameterValue(context, pds[1])).Returns(\"Mybar\").Verifiable();\n            mockHelper.Setup(h => h.PublicGetParameterValue(context, pds[2])).Returns(\"Mybaz\").Verifiable();\n            ControllerActionInvokerHelper helper = mockHelper.Object;\n\n            // Act\n            IDictionary<string, object> parameters = helper.PublicGetParameterValues(context, ad);\n\n            // Assert\n            Assert.Equal(3, parameters.Count);\n            Assert.Equal(\"Myfoo\", parameters[\"foo\"]);\n            Assert.Equal(\"Mybar\", parameters[\"bar\"]);\n            Assert.Equal(\"Mybaz\", parameters[\"baz\"]);\n            mockHelper.Verify();\n        }\n\n        [Fact]\n        public void GetParameterValuesReturnsEmptyDictionaryForParameterlessMethod()\n        {\n            // Arrange\n            var controller = new ParameterTestingController();\n            ControllerContext context = GetControllerContext(controller);\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n            MethodInfo mi = typeof(ParameterTestingController).GetMethod(\"Parameterless\");\n            ReflectedActionDescriptor ad = new ReflectedActionDescriptor(mi, \"Parameterless\", new Mock<ControllerDescriptor>().Object);\n\n            // Act\n            IDictionary<string, object> parameters = helper.PublicGetParameterValues(context, ad);\n\n            // Assert\n            Assert.Empty(parameters);\n        }\n\n        [Fact]\n        public void GetParameterValuesReturnsValuesForParametersInOrder()\n        {\n            // We need to hook into GetParameterValue() to make sure that GetParameterValues() is calling it.\n\n            // Arrange\n            var controller = new ParameterTestingController();\n            Dictionary<string, object> dict = new Dictionary<string, object>()\n            {\n                { \"foo\", \"MyFoo\" },\n                { \"bar\", \"MyBar\" },\n                { \"baz\", \"MyBaz\" }\n            };\n            ControllerContext context = GetControllerContext(controller, dict);\n            controller.ControllerContext = context;\n\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n            MethodInfo mi = typeof(ParameterTestingController).GetMethod(\"Foo\");\n            ReflectedActionDescriptor ad = new ReflectedActionDescriptor(mi, \"Foo\", new Mock<ControllerDescriptor>().Object);\n\n            // Act\n            IDictionary<string, object> parameters = helper.PublicGetParameterValues(context, ad);\n\n            // Assert\n            Assert.Equal(3, parameters.Count);\n            Assert.Equal(\"MyFoo\", parameters[\"foo\"]);\n            Assert.Equal(\"MyBar\", parameters[\"bar\"]);\n            Assert.Equal(\"MyBaz\", parameters[\"baz\"]);\n        }\n\n        [Fact]\n        public void GetParameterValueUsesControllerValueProviderAsValueProvider()\n        {\n            // Arrange\n            Dictionary<string, object> values = new Dictionary<string, object>()\n            {\n                { \"foo\", \"fooValue\" }\n            };\n\n            CustomConverterController controller = new CustomConverterController();\n            ControllerContext controllerContext = GetControllerContext(controller, values);\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            ParameterInfo parameter = typeof(CustomConverterController).GetMethod(\"ParameterHasNoConverters\").GetParameters()[0];\n            ReflectedParameterDescriptor pd = new ReflectedParameterDescriptor(parameter, new Mock<ActionDescriptor>().Object);\n\n            // Act\n            object parameterValue = helper.PublicGetParameterValue(controllerContext, pd);\n\n            // Assert\n            Assert.Equal(\"fooValue\", parameterValue);\n        }\n\n        [Fact]\n        public void InvokeAction()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n\n            ControllerContext context = GetControllerContext(controller);\n            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;\n            ActionDescriptor ad = new Mock<ActionDescriptor>().Object;\n            FilterInfo filterInfo = new FilterInfo();\n\n            IDictionary<string, object> parameters = new Dictionary<string, object>();\n            MethodInfo methodInfo = typeof(object).GetMethod(\"ToString\");\n            ActionResult actionResult = new EmptyResult();\n            ActionExecutedContext postContext = new ActionExecutedContext(context, ad, false /* canceled */, null /* exception */)\n            {\n                Result = actionResult\n            };\n            ActionResult challengeResult = new EmptyResult();\n            AuthenticationContext authenticationContext = new AuthenticationContext();\n            AuthorizationContext authorizationContext = new AuthorizationContext();\n            AuthenticationChallengeContext authenticationChallengeContext = new AuthenticationChallengeContext() { Result = challengeResult };\n\n            Mock<ControllerActionInvokerHelper> mockHelper = new Mock<ControllerActionInvokerHelper>() { CallBase = true };\n            mockHelper.Setup(h => h.PublicGetControllerDescriptor(context)).Returns(cd).Verifiable();\n            mockHelper.Setup(h => h.PublicFindAction(context, cd, \"SomeMethod\")).Returns(ad).Verifiable();\n            mockHelper.Setup(h => h.PublicGetFilters(context, ad)).Returns(filterInfo).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeAuthenticationFilters(context, filterInfo.AuthenticationFilters, ad)).Returns(authenticationContext).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeAuthorizationFilters(context, filterInfo.AuthorizationFilters, ad)).Returns(authorizationContext).Verifiable();\n            mockHelper.Setup(h => h.PublicGetParameterValues(context, ad)).Returns(parameters).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeActionMethodWithFilters(context, filterInfo.ActionFilters, ad, parameters)).Returns(postContext).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeAuthenticationFiltersChallenge(context, filterInfo.AuthenticationFilters, ad, actionResult)).Returns(authenticationChallengeContext).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeActionResultWithFilters(context, filterInfo.ResultFilters, challengeResult)).Returns((ResultExecutedContext)null).Verifiable();\n            ControllerActionInvokerHelper helper = mockHelper.Object;\n\n            // Act\n            bool retVal = helper.InvokeAction(context, \"SomeMethod\");\n            Assert.True(retVal);\n            mockHelper.Verify();\n        }\n\n        [Fact]\n        public void InvokeActionCallsValidateRequestIfAsked()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            controller.ValidateRequest = true;\n            bool validateInputWasCalled = false;\n\n            ControllerContext context = GetControllerContext(controller, null, validateInputCallback: () => { validateInputWasCalled = true; });\n            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;\n            ActionDescriptor ad = new Mock<ActionDescriptor>().Object;\n            FilterInfo filterInfo = new FilterInfo();\n            AuthenticationContext authenticationContext = new AuthenticationContext();\n            AuthorizationContext authorizationContext = new AuthorizationContext();\n\n            Mock<ControllerActionInvokerHelper> mockHelper = new Mock<ControllerActionInvokerHelper>();\n            mockHelper.CallBase = true;\n            mockHelper.Setup(h => h.PublicGetControllerDescriptor(context)).Returns(cd).Verifiable();\n            mockHelper.Setup(h => h.PublicFindAction(context, cd, \"SomeMethod\")).Returns(ad).Verifiable();\n            mockHelper.Setup(h => h.PublicGetFilters(context, ad)).Returns(filterInfo).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeAuthenticationFilters(context, filterInfo.AuthenticationFilters, ad)).Returns(authenticationContext).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeAuthorizationFilters(context, filterInfo.AuthorizationFilters, ad)).Returns(authorizationContext).Verifiable();\n            ControllerActionInvokerHelper helper = mockHelper.Object;\n\n            // Act\n            helper.InvokeAction(context, \"SomeMethod\");\n\n            // Assert\n            Assert.True(validateInputWasCalled);\n            mockHelper.Verify();\n        }\n\n        [Fact]\n        public void InvokeActionDoesNotCallValidateRequestForChildActions()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            controller.ValidateRequest = true;\n\n            ControllerContext context = GetControllerContext(controller, null);\n            Mock.Get<ControllerContext>(context).SetupGet(c => c.IsChildAction).Returns(true);\n            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;\n            ActionDescriptor ad = new Mock<ActionDescriptor>().Object;\n            FilterInfo filterInfo = new FilterInfo();\n            AuthenticationContext authenticationContext = new AuthenticationContext();\n            AuthorizationContext authorizationContext = new AuthorizationContext();\n\n            Mock<ControllerActionInvokerHelper> mockHelper = new Mock<ControllerActionInvokerHelper>();\n            mockHelper.CallBase = true;\n            mockHelper.Setup(h => h.PublicGetControllerDescriptor(context)).Returns(cd).Verifiable();\n            mockHelper.Setup(h => h.PublicFindAction(context, cd, \"SomeMethod\")).Returns(ad).Verifiable();\n            mockHelper.Setup(h => h.PublicGetFilters(context, ad)).Returns(filterInfo).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeAuthenticationFilters(context, filterInfo.AuthenticationFilters, ad)).Returns(authenticationContext).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeAuthorizationFilters(context, filterInfo.AuthorizationFilters, ad)).Returns(authorizationContext).Verifiable();\n            ControllerActionInvokerHelper helper = mockHelper.Object;\n\n            // Act\n            helper.InvokeAction(context, \"SomeMethod\"); // No exception thrown\n\n            // Assert\n            mockHelper.Verify();\n        }\n\n        [Fact]\n        public void InvokeActionMethodFilterWhereContinuationThrowsExceptionAndIsHandled()\n        {\n            // Arrange\n            List<string> actions = new List<string>();\n            MethodInfo mi = typeof(object).GetMethod(\"ToString\");\n            Dictionary<string, object> parameters = new Dictionary<string, object>();\n            Exception exception = new Exception();\n            ActionDescriptor action = new Mock<ActionDescriptor>().Object;\n\n            ActionFilterImpl filter = new ActionFilterImpl()\n            {\n                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) { actions.Add(\"OnActionExecuting\"); },\n                OnActionExecutedImpl = delegate(ActionExecutedContext filterContext)\n                {\n                    actions.Add(\"OnActionExecuted\");\n                    Assert.Same(exception, filterContext.Exception);\n                    Assert.Same(action, filterContext.ActionDescriptor);\n                    Assert.False(filterContext.ExceptionHandled);\n                    filterContext.ExceptionHandled = true;\n                }\n            };\n            Func<ActionExecutedContext> continuation = delegate\n            {\n                actions.Add(\"Continuation\");\n                throw exception;\n            };\n\n            ActionExecutingContext context = new ActionExecutingContext(GetControllerContext(new EmptyController()), action, parameters);\n\n            // Act\n            ActionExecutedContext result = ControllerActionInvoker.InvokeActionMethodFilter(filter, context, continuation);\n\n            // Assert\n            Assert.Equal(3, actions.Count);\n            Assert.Equal(\"OnActionExecuting\", actions[0]);\n            Assert.Equal(\"Continuation\", actions[1]);\n            Assert.Equal(\"OnActionExecuted\", actions[2]);\n            Assert.Same(exception, result.Exception);\n            Assert.Same(action, result.ActionDescriptor);\n            Assert.True(result.ExceptionHandled);\n        }\n\n        [Fact]\n        public void InvokeActionMethodFilterWhereContinuationThrowsExceptionAndIsNotHandled()\n        {\n            // Arrange\n            List<string> actions = new List<string>();\n            Dictionary<string, object> parameters = new Dictionary<string, object>();\n            ActionDescriptor action = new Mock<ActionDescriptor>().Object;\n\n            ActionFilterImpl filter = new ActionFilterImpl()\n            {\n                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) { actions.Add(\"OnActionExecuting\"); },\n                OnActionExecutedImpl = delegate(ActionExecutedContext filterContext)\n                {\n                    Assert.NotNull(filterContext.Exception);\n                    Assert.Equal(\"Some exception message.\", filterContext.Exception.Message);\n                    Assert.Same(action, filterContext.ActionDescriptor);\n                    actions.Add(\"OnActionExecuted\");\n                }\n            };\n            Func<ActionExecutedContext> continuation = delegate\n            {\n                actions.Add(\"Continuation\");\n                throw new Exception(\"Some exception message.\");\n            };\n\n            ActionExecutingContext context = new ActionExecutingContext(GetControllerContext(new EmptyController()), action, parameters);\n\n            // Act & Assert\n            Assert.Throws<Exception>(\n                delegate { ControllerActionInvoker.InvokeActionMethodFilter(filter, context, continuation); },\n                \"Some exception message.\");\n            Assert.Equal(3, actions.Count);\n            Assert.Equal(\"OnActionExecuting\", actions[0]);\n            Assert.Equal(\"Continuation\", actions[1]);\n            Assert.Equal(\"OnActionExecuted\", actions[2]);\n        }\n\n        [Fact]\n        public void InvokeActionMethodFilterWhereContinuationThrowsThreadAbortException()\n        {\n            // Arrange\n            List<string> actions = new List<string>();\n            ActionResult actionResult = new EmptyResult();\n            ActionDescriptor action = new Mock<ActionDescriptor>().Object;\n\n            ActionFilterImpl filter = new ActionFilterImpl()\n            {\n                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) { actions.Add(\"OnActionExecuting\"); },\n                OnActionExecutedImpl = delegate(ActionExecutedContext filterContext)\n                {\n                    Thread.ResetAbort();\n                    actions.Add(\"OnActionExecuted\");\n                    Assert.Null(filterContext.Exception);\n                    Assert.False(filterContext.ExceptionHandled);\n                    Assert.Same(action, filterContext.ActionDescriptor);\n                }\n            };\n            Func<ActionExecutedContext> continuation = delegate\n            {\n                actions.Add(\"Continuation\");\n                Thread.CurrentThread.Abort();\n                return null;\n            };\n\n            ActionExecutingContext context = new ActionExecutingContext(new Mock<ControllerContext>().Object, action, new Dictionary<string, object>());\n\n            // Act & Assert\n            Assert.Throws<ThreadAbortException>(\n                delegate { ControllerActionInvoker.InvokeActionMethodFilter(filter, context, continuation); },\n                \"Thread was being aborted.\");\n            Assert.Equal(3, actions.Count);\n            Assert.Equal(\"OnActionExecuting\", actions[0]);\n            Assert.Equal(\"Continuation\", actions[1]);\n            Assert.Equal(\"OnActionExecuted\", actions[2]);\n        }\n\n        [Fact]\n        public void InvokeActionMethodFilterWhereOnActionExecutingCancels()\n        {\n            // Arrange\n            bool wasCalled = false;\n            ActionDescriptor ad = new Mock<ActionDescriptor>().Object;\n            Dictionary<string, object> parameters = new Dictionary<string, object>();\n\n            ActionResult actionResult = new EmptyResult();\n            ActionDescriptor action = new Mock<ActionDescriptor>().Object;\n\n            ActionFilterImpl filter = new ActionFilterImpl()\n            {\n                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext)\n                {\n                    Assert.False(wasCalled);\n                    wasCalled = true;\n                    filterContext.Result = actionResult;\n                },\n            };\n            Func<ActionExecutedContext> continuation = delegate\n            {\n                Assert.True(false, \"The continuation should not be called.\");\n                return null;\n            };\n\n            ActionExecutingContext context = new ActionExecutingContext(GetControllerContext(new EmptyController()), action, parameters);\n\n            // Act\n            ActionExecutedContext result = ControllerActionInvoker.InvokeActionMethodFilter(filter, context, continuation);\n\n            // Assert\n            Assert.True(wasCalled);\n            Assert.Null(result.Exception);\n            Assert.True(result.Canceled);\n            Assert.Same(actionResult, result.Result);\n            Assert.Same(action, result.ActionDescriptor);\n        }\n\n        [Fact]\n        public void InvokeActionMethodFilterWithNormalControlFlow()\n        {\n            // Arrange\n            List<string> actions = new List<string>();\n            Dictionary<string, object> parameters = new Dictionary<string, object>();\n            ActionDescriptor action = new Mock<ActionDescriptor>().Object;\n\n            ActionExecutingContext preContext = new ActionExecutingContext(GetControllerContext(new EmptyController()), action, parameters);\n            Mock<ActionExecutedContext> mockPostContext = new Mock<ActionExecutedContext>();\n\n            ActionFilterImpl filter = new ActionFilterImpl()\n            {\n                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext)\n                {\n                    Assert.Same(parameters, filterContext.ActionParameters);\n                    Assert.Null(filterContext.Result);\n                    actions.Add(\"OnActionExecuting\");\n                },\n                OnActionExecutedImpl = delegate(ActionExecutedContext filterContext)\n                {\n                    Assert.Equal(mockPostContext.Object, filterContext);\n                    actions.Add(\"OnActionExecuted\");\n                }\n            };\n            Func<ActionExecutedContext> continuation = delegate\n            {\n                actions.Add(\"Continuation\");\n                return mockPostContext.Object;\n            };\n\n            // Act\n            ActionExecutedContext result = ControllerActionInvoker.InvokeActionMethodFilter(filter, preContext, continuation);\n\n            // Assert\n            Assert.Equal(3, actions.Count);\n            Assert.Equal(\"OnActionExecuting\", actions[0]);\n            Assert.Equal(\"Continuation\", actions[1]);\n            Assert.Equal(\"OnActionExecuted\", actions[2]);\n            Assert.Same(result, mockPostContext.Object);\n        }\n\n        [Fact]\n        public void InvokeActionInvokesExceptionFiltersAndExecutesResultIfExceptionHandled()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n\n            ControllerContext context = GetControllerContext(controller);\n            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;\n            ActionDescriptor ad = new Mock<ActionDescriptor>().Object;\n            FilterInfo filterInfo = new FilterInfo();\n\n            AuthenticationContext authenticationContext = new AuthenticationContext();\n            Exception exception = new Exception();\n            ActionResult actionResult = new EmptyResult();\n            ExceptionContext exContext = new ExceptionContext(context, exception)\n            {\n                ExceptionHandled = true,\n                Result = actionResult\n            };\n\n            Mock<ControllerActionInvokerHelper> mockHelper = new Mock<ControllerActionInvokerHelper>() { CallBase = true };\n            mockHelper.Setup(h => h.PublicGetControllerDescriptor(context)).Returns(cd).Verifiable();\n            mockHelper.Setup(h => h.PublicFindAction(context, cd, \"SomeMethod\")).Returns(ad).Verifiable();\n            mockHelper.Setup(h => h.PublicGetFilters(context, ad)).Returns(filterInfo).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeAuthenticationFilters(context, filterInfo.AuthenticationFilters, ad)).Throws(exception).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeExceptionFilters(context, filterInfo.ExceptionFilters, exception)).Returns(exContext).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeActionResult(context, actionResult)).Verifiable();\n            ControllerActionInvokerHelper helper = mockHelper.Object;\n\n            // Act\n            bool retVal = helper.InvokeAction(context, \"SomeMethod\");\n            Assert.True(retVal);\n            mockHelper.Verify();\n        }\n\n        [Fact]\n        public void InvokeActionInvokesExceptionFiltersAndRethrowsExceptionIfNotHandled()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n\n            ControllerContext context = GetControllerContext(controller);\n            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;\n            ActionDescriptor ad = new Mock<ActionDescriptor>().Object;\n            FilterInfo filterInfo = new FilterInfo();\n\n            AuthenticationContext authenticationContext = new AuthenticationContext();\n            Exception exception = new Exception();\n            ExceptionContext exContext = new ExceptionContext(context, exception);\n\n            Mock<ControllerActionInvokerHelper> mockHelper = new Mock<ControllerActionInvokerHelper>() { CallBase = true };\n            mockHelper.Setup(h => h.PublicGetControllerDescriptor(context)).Returns(cd).Verifiable();\n            mockHelper.Setup(h => h.PublicFindAction(context, cd, \"SomeMethod\")).Returns(ad).Verifiable();\n            mockHelper.Setup(h => h.PublicGetFilters(context, ad)).Returns(filterInfo).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeAuthenticationFilters(context, filterInfo.AuthenticationFilters, ad)).Returns(authenticationContext).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeAuthorizationFilters(context, filterInfo.AuthorizationFilters, ad)).Throws(exception).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeExceptionFilters(context, filterInfo.ExceptionFilters, exception)).Returns(exContext).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeActionResult(context, It.IsAny<ActionResult>())).Callback(delegate { Assert.True(false, \"InvokeActionResult() shouldn't be called if the exception was unhandled by filters.\"); });\n            ControllerActionInvokerHelper helper = mockHelper.Object;\n\n            // Act\n            Exception thrownException = Assert.Throws<Exception>(\n                delegate { helper.InvokeAction(context, \"SomeMethod\"); });\n\n            // Assert\n            Assert.Same(exception, thrownException);\n            mockHelper.Verify();\n        }\n\n        [Fact]\n        public void InvokeActionInvokesResultIfAuthenticationFilterReturnsResult()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n\n            ControllerContext context = GetControllerContext(controller);\n            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;\n            ActionDescriptor ad = new Mock<ActionDescriptor>().Object;\n            FilterInfo filterInfo = new FilterInfo();\n\n            ActionResult actionResult = new EmptyResult();\n            AuthenticationContext authenticationContext = new AuthenticationContext() { Result = actionResult };\n            ActionResult challengeActionResult = new EmptyResult();\n            AuthenticationChallengeContext authenticationChallengeContext = new AuthenticationChallengeContext() { Result = challengeActionResult };\n\n            Mock<ControllerActionInvokerHelper> mockHelper = new Mock<ControllerActionInvokerHelper>() { CallBase = true };\n            mockHelper.Setup(h => h.PublicGetControllerDescriptor(context)).Returns(cd).Verifiable();\n            mockHelper.Setup(h => h.PublicFindAction(context, cd, \"SomeMethod\")).Returns(ad).Verifiable();\n            mockHelper.Setup(h => h.PublicGetFilters(context, ad)).Returns(filterInfo).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeAuthenticationFilters(context, filterInfo.AuthenticationFilters, ad)).Returns(authenticationContext).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeAuthenticationFiltersChallenge(context, filterInfo.AuthenticationFilters, ad, actionResult)).Returns(authenticationChallengeContext).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeActionResult(context, challengeActionResult)).Verifiable();\n            ControllerActionInvokerHelper helper = mockHelper.Object;\n\n            // Act\n            bool retVal = helper.InvokeAction(context, \"SomeMethod\");\n            Assert.True(retVal);\n            mockHelper.Verify();\n        }\n\n        [Fact]\n        public void InvokeActionInvokesResultIfAuthorizationFilterReturnsResult()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n\n            ControllerContext context = GetControllerContext(controller);\n            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;\n            ActionDescriptor ad = new Mock<ActionDescriptor>().Object;\n            FilterInfo filterInfo = new FilterInfo();\n\n            ActionResult actionResult = new EmptyResult();\n            AuthenticationContext authenticationContext = new AuthenticationContext();\n            AuthorizationContext authorizationContext = new AuthorizationContext() { Result = actionResult };\n            ActionResult challengeResult = new EmptyResult();\n            AuthenticationChallengeContext authenticationChallengeContext = new AuthenticationChallengeContext() { Result = challengeResult };\n\n            Mock<ControllerActionInvokerHelper> mockHelper = new Mock<ControllerActionInvokerHelper>() { CallBase = true };\n            mockHelper.Setup(h => h.PublicGetControllerDescriptor(context)).Returns(cd).Verifiable();\n            mockHelper.Setup(h => h.PublicFindAction(context, cd, \"SomeMethod\")).Returns(ad).Verifiable();\n            mockHelper.Setup(h => h.PublicGetFilters(context, ad)).Returns(filterInfo).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeAuthenticationFilters(context, filterInfo.AuthenticationFilters, ad)).Returns(authenticationContext).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeAuthorizationFilters(context, filterInfo.AuthorizationFilters, ad)).Returns(authorizationContext).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeAuthenticationFiltersChallenge(context, filterInfo.AuthenticationFilters, ad, actionResult)).Returns(authenticationChallengeContext).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeActionResult(context, challengeResult)).Verifiable();\n            ControllerActionInvokerHelper helper = mockHelper.Object;\n\n            // Act\n            bool retVal = helper.InvokeAction(context, \"SomeMethod\");\n            Assert.True(retVal);\n            mockHelper.Verify();\n        }\n\n        [Fact]\n        public void InvokeActionMethod()\n        {\n            // Arrange\n            EmptyController controller = new EmptyController();\n            ControllerContext controllerContext = GetControllerContext(controller);\n            Dictionary<string, object> parameters = new Dictionary<string, object>();\n\n            ActionResult expectedResult = new Mock<ActionResult>().Object;\n\n            Mock<ActionDescriptor> mockAd = new Mock<ActionDescriptor>();\n            mockAd.Setup(ad => ad.Execute(controllerContext, parameters)).Returns(\"hello world\");\n\n            Mock<ControllerActionInvokerHelper> mockHelper = new Mock<ControllerActionInvokerHelper>() { CallBase = true };\n            mockHelper.Setup(h => h.PublicCreateActionResult(controllerContext, mockAd.Object, \"hello world\")).Returns(expectedResult);\n            ControllerActionInvokerHelper helper = mockHelper.Object;\n\n            // Act\n            ActionResult returnedResult = helper.PublicInvokeActionMethod(controllerContext, mockAd.Object, parameters);\n\n            // Assert\n            Assert.Same(expectedResult, returnedResult);\n        }\n\n        [Fact]\n        public void InvokeActionMethodWithFiltersOrdersFiltersCorrectly()\n        {\n            // Arrange\n            List<string> actions = new List<string>();\n            Dictionary<string, object> parameters = new Dictionary<string, object>();\n            ActionResult actionResult = new EmptyResult();\n\n            ActionFilterImpl filter1 = new ActionFilterImpl()\n            {\n                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) { actions.Add(\"OnActionExecuting1\"); },\n                OnActionExecutedImpl = delegate(ActionExecutedContext filterContext) { actions.Add(\"OnActionExecuted1\"); }\n            };\n            ActionFilterImpl filter2 = new ActionFilterImpl()\n            {\n                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) { actions.Add(\"OnActionExecuting2\"); },\n                OnActionExecutedImpl = delegate(ActionExecutedContext filterContext) { actions.Add(\"OnActionExecuted2\"); }\n            };\n            Func<ActionResult> continuation = delegate\n            {\n                actions.Add(\"Continuation\");\n                return new EmptyResult();\n            };\n            ControllerBase controller = new ContinuationController(continuation);\n            ControllerContext context = GetControllerContext(controller);\n            ActionDescriptor actionDescriptor = new ReflectedActionDescriptor(ContinuationController.GoMethod, \"someName\", new Mock<ControllerDescriptor>().Object);\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n            List<IActionFilter> filters = new List<IActionFilter>() { filter1, filter2 };\n\n            // Act\n            helper.PublicInvokeActionMethodWithFilters(context, filters, actionDescriptor, parameters);\n\n            // Assert\n            Assert.Equal(5, actions.Count);\n            Assert.Equal(\"OnActionExecuting1\", actions[0]);\n            Assert.Equal(\"OnActionExecuting2\", actions[1]);\n            Assert.Equal(\"Continuation\", actions[2]);\n            Assert.Equal(\"OnActionExecuted2\", actions[3]);\n            Assert.Equal(\"OnActionExecuted1\", actions[4]);\n        }\n\n        [Fact]\n        public void InvokeActionMethodWithFiltersPassesArgumentsCorrectly()\n        {\n            // Arrange\n            bool wasCalled = false;\n            MethodInfo mi = ContinuationController.GoMethod;\n            Dictionary<string, object> parameters = new Dictionary<string, object>();\n            ActionResult actionResult = new EmptyResult();\n            ActionFilterImpl filter = new ActionFilterImpl()\n            {\n                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext)\n                {\n                    Assert.Same(parameters, filterContext.ActionParameters);\n                    Assert.False(wasCalled);\n                    wasCalled = true;\n                    filterContext.Result = actionResult;\n                }\n            };\n            Func<ActionResult> continuation = delegate\n            {\n                Assert.True(false, \"Continuation should not be called.\");\n                return null;\n            };\n            ControllerBase controller = new ContinuationController(continuation);\n            ControllerContext context = GetControllerContext(controller);\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n            ActionDescriptor actionDescriptor = new ReflectedActionDescriptor(ContinuationController.GoMethod, \"someName\", new Mock<ControllerDescriptor>().Object);\n            List<IActionFilter> filters = new List<IActionFilter>() { filter };\n\n            // Act\n            ActionExecutedContext result = helper.PublicInvokeActionMethodWithFilters(context, filters, actionDescriptor, parameters);\n\n            // Assert\n            Assert.True(wasCalled);\n            Assert.Null(result.Exception);\n            Assert.False(result.ExceptionHandled);\n            Assert.Same(actionResult, result.Result);\n            Assert.Same(actionDescriptor, result.ActionDescriptor);\n        }\n\n        [Fact]\n        public void InvokeActionPropagatesThreadAbortException()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n\n            ControllerContext context = GetControllerContext(controller);\n            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;\n            ActionDescriptor ad = new Mock<ActionDescriptor>().Object;\n            FilterInfo filterInfo = new FilterInfo();\n\n            ActionResult actionResult = new EmptyResult();\n            ActionExecutedContext postContext = new ActionExecutedContext(context, ad, false /* canceled */, null /* exception */)\n            {\n                Result = actionResult\n            };\n            AuthenticationContext authenticationContext = new AuthenticationContext();\n            AuthorizationContext authorizationContext = new AuthorizationContext() { Result = actionResult };\n\n            Mock<ControllerActionInvokerHelper> mockHelper = new Mock<ControllerActionInvokerHelper>() { CallBase = true };\n            mockHelper.Setup(h => h.PublicGetControllerDescriptor(context)).Returns(cd).Verifiable();\n            mockHelper.Setup(h => h.PublicFindAction(context, cd, \"SomeMethod\")).Returns(ad).Verifiable();\n            mockHelper.Setup(h => h.PublicGetFilters(context, ad)).Returns(filterInfo).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeAuthenticationFilters(context, filterInfo.AuthenticationFilters, ad)).Returns(authenticationContext).Verifiable();\n            mockHelper\n                .Setup(h => h.PublicInvokeAuthorizationFilters(context, filterInfo.AuthorizationFilters, ad))\n                .Returns(\n                    delegate(ControllerContext cc, IList<IAuthorizationFilter> f, ActionDescriptor a)\n                    {\n                        Thread.CurrentThread.Abort();\n                        return null;\n                    });\n            ControllerActionInvokerHelper helper = mockHelper.Object;\n\n            bool wasAborted = false;\n\n            // Act\n            try\n            {\n                helper.InvokeAction(context, \"SomeMethod\");\n            }\n            catch (ThreadAbortException)\n            {\n                wasAborted = true;\n                Thread.ResetAbort();\n            }\n\n            // Assert\n            Assert.True(wasAborted);\n            mockHelper.Verify();\n        }\n\n        [Fact]\n        public void InvokeActionReturnsFalseIfMethodNotFound()\n        {\n            // Arrange\n            var controller = new BlankController();\n            ControllerContext context = GetControllerContext(controller);\n            ControllerActionInvoker invoker = new ControllerActionInvoker();\n\n            // Act\n            bool retVal = invoker.InvokeAction(context, \"foo\");\n\n            // Assert\n            Assert.False(retVal);\n        }\n\n        [Fact]\n        public void InvokeActionThrowsIfControllerContextIsNull()\n        {\n            // Arrange\n            ControllerActionInvoker invoker = new ControllerActionInvoker();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { invoker.InvokeAction(null, \"actionName\"); }, \"controllerContext\");\n        }\n\n        [Fact]\n        public void InvokeActionWithEmptyActionNameThrows()\n        {\n            // Arrange\n            var controller = new BasicMethodInvokeController();\n            ControllerContext context = GetControllerContext(controller);\n            ControllerActionInvoker invoker = new ControllerActionInvoker();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { invoker.InvokeAction(context, String.Empty); },\n                \"actionName\");\n        }\n\n        [Fact]\n        public void InvokeActionWithNullActionNameThrows()\n        {\n            // Arrange\n            var controller = new BasicMethodInvokeController();\n            ControllerContext context = GetControllerContext(controller);\n            ControllerActionInvoker invoker = new ControllerActionInvoker();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { invoker.InvokeAction(context, null /* actionName */); },\n                \"actionName\");\n        }\n\n        [Fact]\n        public void InvokeActionWithResultExceptionInvokesExceptionFiltersAndExecutesResultIfExceptionHandled()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n\n            ControllerContext context = GetControllerContext(controller);\n            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;\n            ActionDescriptor ad = new Mock<ActionDescriptor>().Object;\n            IDictionary<string, object> parameters = new Dictionary<string, object>();\n            FilterInfo filterInfo = new FilterInfo();\n            AuthenticationContext authenticationContext = new AuthenticationContext();\n            AuthorizationContext authorizationContext = new AuthorizationContext();\n            AuthenticationChallengeContext authenticationChallengeContext = new AuthenticationChallengeContext();\n\n            Exception exception = new Exception();\n            ActionResult actionResult = new EmptyResult();\n            ActionExecutedContext postContext = new ActionExecutedContext(context, ad, false /* canceled */, null /* exception */)\n            {\n                Result = actionResult\n            };\n            ExceptionContext exContext = new ExceptionContext(context, exception)\n            {\n                ExceptionHandled = true,\n                Result = actionResult\n            };\n\n            Mock<ControllerActionInvokerHelper> mockHelper = new Mock<ControllerActionInvokerHelper>() { CallBase = true };\n            mockHelper.Setup(h => h.PublicGetControllerDescriptor(context)).Returns(cd).Verifiable();\n            mockHelper.Setup(h => h.PublicFindAction(context, cd, \"SomeMethod\")).Returns(ad).Verifiable();\n            mockHelper.Setup(h => h.PublicGetFilters(context, ad)).Returns(filterInfo).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeAuthenticationFilters(context, filterInfo.AuthenticationFilters, ad)).Returns(authenticationContext).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeAuthorizationFilters(context, filterInfo.AuthorizationFilters, ad)).Returns(authorizationContext).Verifiable();\n            mockHelper.Setup(h => h.PublicGetParameterValues(context, ad)).Returns(parameters).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeActionMethodWithFilters(context, filterInfo.ActionFilters, ad, parameters)).Returns(postContext).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeActionResultWithFilters(context, filterInfo.ResultFilters, actionResult)).Throws(exception).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeAuthenticationFiltersChallenge(context, filterInfo.AuthenticationFilters, ad, actionResult)).Returns(authenticationChallengeContext).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeExceptionFilters(context, filterInfo.ExceptionFilters, exception)).Returns(exContext).Verifiable();\n            mockHelper.Setup(h => h.PublicInvokeActionResult(context, actionResult)).Verifiable();\n            ControllerActionInvokerHelper helper = mockHelper.Object;\n\n            // Act\n            bool retVal = helper.InvokeAction(context, \"SomeMethod\");\n            Assert.True(retVal, \"InvokeAction() should return True on success.\");\n            mockHelper.Verify();\n        }\n\n        [Fact]\n        public void InvokeAuthorizationFilters()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            ActionDescriptor ad = new Mock<ActionDescriptor>().Object;\n            ControllerContext controllerContext = GetControllerContext(controller);\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            List<AuthorizationFilterHelper> callQueue = new List<AuthorizationFilterHelper>();\n            AuthorizationFilterHelper filter1 = new AuthorizationFilterHelper(callQueue);\n            AuthorizationFilterHelper filter2 = new AuthorizationFilterHelper(callQueue);\n            IAuthorizationFilter[] filters = new IAuthorizationFilter[] { filter1, filter2 };\n\n            // Act\n            AuthorizationContext postContext = helper.PublicInvokeAuthorizationFilters(controllerContext, filters, ad);\n\n            // Assert\n            Assert.Equal(ad, postContext.ActionDescriptor);\n            Assert.Equal(2, callQueue.Count);\n            Assert.Same(filter1, callQueue[0]);\n            Assert.Same(filter2, callQueue[1]);\n        }\n\n        [Fact]\n        public void InvokeAuthorizationFiltersStopsExecutingIfResultProvided()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            ActionDescriptor ad = new Mock<ActionDescriptor>().Object;\n            ControllerContext controllerContext = GetControllerContext(controller);\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n            ActionResult result = new EmptyResult();\n\n            List<AuthorizationFilterHelper> callQueue = new List<AuthorizationFilterHelper>();\n            AuthorizationFilterHelper filter1 = new AuthorizationFilterHelper(callQueue) { ShortCircuitResult = result };\n            AuthorizationFilterHelper filter2 = new AuthorizationFilterHelper(callQueue);\n            IAuthorizationFilter[] filters = new IAuthorizationFilter[] { filter1, filter2 };\n\n            // Act\n            AuthorizationContext postContext = helper.PublicInvokeAuthorizationFilters(controllerContext, filters, ad);\n\n            // Assert\n            Assert.Equal(ad, postContext.ActionDescriptor);\n            Assert.Same(result, postContext.Result);\n            AuthorizationFilterHelper resultFilter = Assert.Single(callQueue);\n            Assert.Same(filter1, resultFilter);\n        }\n\n        [Fact]\n        public void InvokeAuthenticationFilters()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            ActionDescriptor ad = new Mock<ActionDescriptor>().Object;\n            ControllerContext controllerContext = GetControllerContext(controller);\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            List<AuthenticationFilterHelper> callQueue = new List<AuthenticationFilterHelper>();\n            AuthenticationFilterHelper filter1 = new AuthenticationFilterHelper(callQueue);\n            AuthenticationFilterHelper filter2 = new AuthenticationFilterHelper(callQueue);\n            IAuthenticationFilter[] filters = new IAuthenticationFilter[] { filter1, filter2 };\n            AuthenticationContext postContext;\n\n            using (new ThreadCurrentPrincipalContext())\n            {\n                // Act\n                postContext = helper.PublicInvokeAuthenticationFilters(controllerContext, filters, ad);\n            }\n\n            // Assert\n            Assert.Same(ad, postContext.ActionDescriptor);\n            Assert.Same(controller, postContext.Controller);\n            Assert.Equal(2, callQueue.Count);\n            Assert.Same(filter1, callQueue[0]);\n            Assert.Same(filter2, callQueue[1]);\n        }\n\n        [Fact]\n        public void InvokeAuthenticationFiltersProvidesHttpContextUserAsPrincipalInFilterContext()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            ActionDescriptor ad = new Mock<ActionDescriptor>().Object;\n            ControllerContext controllerContext = GetControllerContext(controller);\n            IPrincipal principal = new ClaimsPrincipal();\n            controllerContext.HttpContext.User = principal;\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            List<AuthenticationFilterHelper> callQueue = new List<AuthenticationFilterHelper>();\n            AuthenticationFilterHelper filter = new AuthenticationFilterHelper(callQueue);\n            IAuthenticationFilter[] filters = new IAuthenticationFilter[] { filter };\n            AuthenticationContext postContext;\n\n            using (new ThreadCurrentPrincipalContext())\n            {\n                // Act\n                postContext = helper.PublicInvokeAuthenticationFilters(controllerContext, filters, ad);\n            }\n\n            // Assert\n            Assert.Same(ad, postContext.ActionDescriptor);\n            Assert.Same(controller, postContext.Controller);\n            AuthenticationFilterHelper actualHelper = Assert.Single(callQueue);\n            Assert.Same(filter, actualHelper);\n            Assert.Same(principal, postContext.Principal);\n        }\n\n        [Fact]\n        public void InvokeAuthenticationFiltersStopsExecutingIfResultProvided()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            ActionDescriptor ad = new Mock<ActionDescriptor>().Object;\n            ControllerContext controllerContext = GetControllerContext(controller);\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n            ActionResult result = new EmptyResult();\n\n            List<AuthenticationFilterHelper> callQueue = new List<AuthenticationFilterHelper>();\n            AuthenticationFilterHelper filter1 = new AuthenticationFilterHelper(callQueue) { ShortCircuitResult = result };\n            AuthenticationFilterHelper filter2 = new AuthenticationFilterHelper(callQueue);\n            IAuthenticationFilter[] filters = new IAuthenticationFilter[] { filter1, filter2 };\n            AuthenticationContext postContext;\n\n            using (new ThreadCurrentPrincipalContext())\n            {\n                // Act\n                postContext = helper.PublicInvokeAuthenticationFilters(controllerContext, filters, ad);\n            }\n\n            // Assert\n            Assert.Same(ad, postContext.ActionDescriptor);\n            Assert.Same(controller, postContext.Controller);\n            Assert.Same(result, postContext.Result);\n            AuthenticationFilterHelper resultFilter = Assert.Single(callQueue);\n            Assert.Same(filter1, resultFilter);\n        }\n\n        [Fact]\n        public void InvokeAuthenticationFiltersSetsHttpContextUserWhenPrincipalIsProvided()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            ActionDescriptor ad = new Mock<ActionDescriptor>().Object;\n            ControllerContext controllerContext = GetControllerContext(controller);\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n            IPrincipal principal = new ClaimsPrincipal();\n\n            List<AuthenticationFilterHelper> callQueue = new List<AuthenticationFilterHelper>();\n            AuthenticationFilterHelper filter = new AuthenticationFilterHelper(callQueue) { Principal = principal };\n            IAuthenticationFilter[] filters = new IAuthenticationFilter[] { filter };\n            AuthenticationContext postContext;\n\n            using (new ThreadCurrentPrincipalContext())\n            {\n                // Act\n                postContext = helper.PublicInvokeAuthenticationFilters(controllerContext, filters, ad);\n            }\n\n            // Assert\n            Assert.Same(ad, postContext.ActionDescriptor);\n            Assert.Same(controller, postContext.Controller);\n            Assert.Same(principal, postContext.HttpContext.User);\n            AuthenticationFilterHelper resultFilter = Assert.Single(callQueue);\n            Assert.Same(filter, resultFilter);\n        }\n\n        [Fact]\n        public void InvokeAuthenticationFiltersSetsThreadCurrentPrincipalWhenPrincipalIsProvided()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            ActionDescriptor ad = new Mock<ActionDescriptor>().Object;\n            ControllerContext controllerContext = GetControllerContext(controller);\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n            IPrincipal principal = new ClaimsPrincipal();\n\n            List<AuthenticationFilterHelper> callQueue = new List<AuthenticationFilterHelper>();\n            AuthenticationFilterHelper filter = new AuthenticationFilterHelper(callQueue) { Principal = principal };\n            IAuthenticationFilter[] filters = new IAuthenticationFilter[] { filter };\n\n            using (new ThreadCurrentPrincipalContext())\n            {\n                // Act\n                AuthenticationContext postContext = helper.PublicInvokeAuthenticationFilters(controllerContext, filters, ad);\n\n                // Assert\n                Assert.Same(ad, postContext.ActionDescriptor);\n                Assert.Same(controller, postContext.Controller);\n                Assert.Same(principal, Thread.CurrentPrincipal);\n                AuthenticationFilterHelper resultFilter = Assert.Single(callQueue);\n                Assert.Same(filter, resultFilter);\n            }\n        }\n\n        [Fact]\n        public void InvokeAuthenticationFiltersDoesNotSetThreadCurrentPrincipalWhenPrincipalIsUnchanged()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            ActionDescriptor ad = new Mock<ActionDescriptor>().Object;\n            ControllerContext controllerContext = GetControllerContext(controller);\n            IPrincipal principal = new ClaimsPrincipal();\n            controllerContext.HttpContext.User = principal;\n            Assert.NotSame(controllerContext.HttpContext.User, Thread.CurrentPrincipal); // Guard\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            List<AuthenticationFilterHelper> callQueue = new List<AuthenticationFilterHelper>();\n            AuthenticationFilterHelper filter = new AuthenticationFilterHelper(callQueue);\n            IAuthenticationFilter[] filters = new IAuthenticationFilter[] { filter };\n\n            using (new ThreadCurrentPrincipalContext())\n            {\n                // Act\n                AuthenticationContext postContext = helper.PublicInvokeAuthenticationFilters(controllerContext, filters, ad);\n\n                // Assert\n                Assert.Same(ad, postContext.ActionDescriptor);\n                Assert.Same(controller, postContext.Controller);\n                Assert.NotSame(controllerContext.HttpContext.User, Thread.CurrentPrincipal);\n                AuthenticationFilterHelper resultFilter = Assert.Single(callQueue);\n                Assert.Same(filter, resultFilter);\n            }\n        }\n\n        [Fact]\n        public void InvokeAuthenticationFiltersChallenge()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            ActionDescriptor ad = new Mock<ActionDescriptor>().Object;\n            ControllerContext controllerContext = GetControllerContext(controller);\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            List<AuthenticationFilterHelper> callQueue = new List<AuthenticationFilterHelper>();\n            AuthenticationFilterHelper filter1 = new AuthenticationFilterHelper(callQueue);\n            AuthenticationFilterHelper filter2 = new AuthenticationFilterHelper(callQueue);\n            IAuthenticationFilter[] filters = new IAuthenticationFilter[] { filter1, filter2 };\n            ActionResult result = new EmptyResult();\n\n            // Act\n            AuthenticationChallengeContext postContext = helper.PublicInvokeAuthenticationFiltersChallenge(controllerContext, filters, ad, result);\n\n            // Assert\n            Assert.Same(ad, postContext.ActionDescriptor);\n            Assert.Same(controller, postContext.Controller);\n            Assert.Same(result, postContext.Result);\n            Assert.Equal(2, callQueue.Count);\n            Assert.Same(filter1, callQueue[0]);\n            Assert.Same(filter2, callQueue[1]);\n        }\n\n        [Fact]\n        public void InvokeExceptionFilters()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            Exception exception = new Exception();\n            ControllerContext controllerContext = GetControllerContext(controller);\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            List<ExceptionFilterHelper> callQueue = new List<ExceptionFilterHelper>();\n            ExceptionFilterHelper filter1 = new ExceptionFilterHelper(callQueue);\n            ExceptionFilterHelper filter2 = new ExceptionFilterHelper(callQueue);\n            IExceptionFilter[] filters = new IExceptionFilter[] { filter1, filter2 };\n\n            // Act\n            ExceptionContext postContext = helper.PublicInvokeExceptionFilters(controllerContext, filters, exception);\n\n            // Assert\n            Assert.Same(exception, postContext.Exception);\n            Assert.False(postContext.ExceptionHandled);\n            Assert.Same(filter1.ContextPassed, filter2.ContextPassed);\n            Assert.Equal(2, callQueue.Count);\n            Assert.Same(filter2, callQueue[0]); // Exception filters are executed in reverse order\n            Assert.Same(filter1, callQueue[1]);\n        }\n\n        [Fact]\n        public void InvokeExceptionFiltersContinuesExecutingIfExceptionHandled()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            Exception exception = new Exception();\n            ControllerContext controllerContext = GetControllerContext(controller);\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            List<ExceptionFilterHelper> callQueue = new List<ExceptionFilterHelper>();\n            ExceptionFilterHelper filter1 = new ExceptionFilterHelper(callQueue) { ShouldHandleException = true };\n            ExceptionFilterHelper filter2 = new ExceptionFilterHelper(callQueue);\n            IExceptionFilter[] filters = new IExceptionFilter[] { filter1, filter2 };\n\n            // Act\n            ExceptionContext postContext = helper.PublicInvokeExceptionFilters(controllerContext, filters, exception);\n\n            // Assert\n            Assert.Same(exception, postContext.Exception);\n            Assert.True(postContext.ExceptionHandled);\n            Assert.Same(filter1.ContextPassed, filter2.ContextPassed);\n            Assert.Equal(2, callQueue.Count);\n            Assert.Same(filter2, callQueue[0]); // Exception filters are executed in reverse order\n            Assert.Same(filter1, callQueue[1]);\n        }\n\n        [Fact]\n        public void InvokeActionResultWithFiltersOrdersFiltersCorrectly()\n        {\n            // Arrange\n            List<string> actions = new List<string>();\n            ActionFilterImpl filter1 = new ActionFilterImpl()\n            {\n                OnResultExecutingImpl = delegate(ResultExecutingContext filterContext) { actions.Add(\"OnResultExecuting1\"); },\n                OnResultExecutedImpl = delegate(ResultExecutedContext filterContext) { actions.Add(\"OnResultExecuted1\"); }\n            };\n            ActionFilterImpl filter2 = new ActionFilterImpl()\n            {\n                OnResultExecutingImpl = delegate(ResultExecutingContext filterContext) { actions.Add(\"OnResultExecuting2\"); },\n                OnResultExecutedImpl = delegate(ResultExecutedContext filterContext) { actions.Add(\"OnResultExecuted2\"); }\n            };\n            Action continuation = delegate { actions.Add(\"Continuation\"); };\n            ActionResult actionResult = new ContinuationResult(continuation);\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            ControllerContext context = GetControllerContext(controller);\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n            List<IResultFilter> filters = new List<IResultFilter>() { filter1, filter2 };\n\n            // Act\n            helper.PublicInvokeActionResultWithFilters(context, filters, actionResult);\n\n            // Assert\n            Assert.Equal(5, actions.Count);\n            Assert.Equal(\"OnResultExecuting1\", actions[0]);\n            Assert.Equal(\"OnResultExecuting2\", actions[1]);\n            Assert.Equal(\"Continuation\", actions[2]);\n            Assert.Equal(\"OnResultExecuted2\", actions[3]);\n            Assert.Equal(\"OnResultExecuted1\", actions[4]);\n        }\n\n        [Fact]\n        public void InvokeActionResultWithFiltersPassesArgumentsCorrectly()\n        {\n            // Arrange\n            bool wasCalled = false;\n            Action continuation = delegate { Assert.True(false, \"Continuation should not be called.\"); };\n            ActionResult actionResult = new ContinuationResult(continuation);\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            ControllerContext context = GetControllerContext(controller);\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n            ActionFilterImpl filter = new ActionFilterImpl()\n            {\n                OnResultExecutingImpl = delegate(ResultExecutingContext filterContext)\n                {\n                    Assert.Same(actionResult, filterContext.Result);\n                    Assert.False(wasCalled);\n                    wasCalled = true;\n                    filterContext.Cancel = true;\n                }\n            };\n\n            List<IResultFilter> filters = new List<IResultFilter>() { filter };\n\n            // Act\n            ResultExecutedContext result = helper.PublicInvokeActionResultWithFilters(context, filters, actionResult);\n\n            // Assert\n            Assert.True(wasCalled);\n            Assert.Null(result.Exception);\n            Assert.False(result.ExceptionHandled);\n            Assert.Same(actionResult, result.Result);\n        }\n\n        [Fact]\n        public void InvokeActionResultWithFiltersPassesSameContextObjectToInnerFilters()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            ControllerContext context = GetControllerContext(controller);\n\n            ResultExecutingContext storedContext = null;\n            ActionResult result = new EmptyResult();\n            List<IResultFilter> filters = new List<IResultFilter>()\n            {\n                new ActionFilterImpl()\n                {\n                    OnResultExecutingImpl = delegate(ResultExecutingContext ctx)\n                    {\n                        Assert.NotNull(ctx);\n                        storedContext = ctx;\n                    },\n                    OnResultExecutedImpl = delegate { }\n                },\n                new ActionFilterImpl()\n                {\n                    OnResultExecutingImpl = delegate(ResultExecutingContext ctx)\n                    {\n                        Assert.NotNull(ctx);\n                        Assert.Same(storedContext, ctx);\n                    },\n                    OnResultExecutedImpl = delegate { }\n                },\n            };\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            // Act\n            ResultExecutedContext postContext = helper.PublicInvokeActionResultWithFilters(context, filters, result);\n\n            // Assert\n            Assert.Same(result, postContext.Result);\n        }\n\n        [Fact]\n        public void InvokeActionResultWithFiltersWhereContinuationThrowsExceptionAndIsHandled()\n        {\n            // Arrange\n            List<string> actions = new List<string>();\n            Exception exception = new Exception();\n            Action continuation = delegate\n            {\n                actions.Add(\"Continuation\");\n                throw exception;\n            };\n            ActionResult actionResult = new ContinuationResult(continuation);\n            ActionFilterImpl filter = new ActionFilterImpl()\n            {\n                OnResultExecutingImpl = delegate(ResultExecutingContext filterContext) { actions.Add(\"OnResultExecuting\"); },\n                OnResultExecutedImpl = delegate(ResultExecutedContext filterContext)\n                {\n                    actions.Add(\"OnResultExecuted\");\n                    Assert.Same(actionResult, filterContext.Result);\n                    Assert.Same(exception, filterContext.Exception);\n                    Assert.False(filterContext.ExceptionHandled);\n                    filterContext.ExceptionHandled = true;\n                }\n            };\n\n            Mock<ResultExecutingContext> mockResultExecutingContext = new Mock<ResultExecutingContext>() { DefaultValue = DefaultValue.Mock };\n            mockResultExecutingContext.Setup(c => c.Result).Returns(actionResult);\n            List<IResultFilter> filters = new List<IResultFilter>() { filter, };\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            // Act\n            ResultExecutedContext result = helper.PublicInvokeActionResultWithFilters(mockResultExecutingContext.Object, filters, actionResult);\n\n            // Assert\n            Assert.Equal(3, actions.Count);\n            Assert.Equal(\"OnResultExecuting\", actions[0]);\n            Assert.Equal(\"Continuation\", actions[1]);\n            Assert.Equal(\"OnResultExecuted\", actions[2]);\n            Assert.Same(exception, result.Exception);\n            Assert.True(result.ExceptionHandled);\n            Assert.Same(actionResult, result.Result);\n        }\n\n        [Fact]\n        public void InvokeActionResultWithFiltersWhereContinuationThrowsExceptionAndIsNotHandled()\n        {\n            // Arrange\n            List<string> actions = new List<string>();\n            Action continuation = delegate\n            {\n                actions.Add(\"Continuation\");\n                throw new Exception(\"Some exception message.\");\n            };\n            ActionResult actionResult = new ContinuationResult(continuation);\n            ActionFilterImpl filter = new ActionFilterImpl()\n            {\n                OnResultExecutingImpl = delegate(ResultExecutingContext filterContext) { actions.Add(\"OnResultExecuting\"); },\n                OnResultExecutedImpl = delegate(ResultExecutedContext filterContext) { actions.Add(\"OnResultExecuted\"); }\n            };\n            Mock<ResultExecutingContext> mockResultExecutingContext = new Mock<ResultExecutingContext>() { DefaultValue = DefaultValue.Mock };\n            mockResultExecutingContext.Setup(c => c.Result).Returns(actionResult);\n            List<IResultFilter> filters = new List<IResultFilter>() { filter, };\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            // Act & Assert\n            Assert.Throws<Exception>(\n                delegate { helper.PublicInvokeActionResultWithFilters(mockResultExecutingContext.Object, filters, actionResult); },\n                \"Some exception message.\");\n            Assert.Equal(3, actions.Count);\n            Assert.Equal(\"OnResultExecuting\", actions[0]);\n            Assert.Equal(\"Continuation\", actions[1]);\n            Assert.Equal(\"OnResultExecuted\", actions[2]);\n        }\n\n        [Fact]\n        public void InvokeActionResultWithFiltersWhereContinuationThrowsThreadAbortException()\n        {\n            // Arrange\n            List<string> actions = new List<string>();\n\n            Action continuation = delegate\n            {\n                actions.Add(\"Continuation\");\n                Thread.CurrentThread.Abort();\n            };\n            ActionResult actionResult = new ContinuationResult(continuation);\n            Mock<ResultExecutingContext> mockPreContext = new Mock<ResultExecutingContext>() { DefaultValue = DefaultValue.Mock };\n            mockPreContext.Setup(c => c.Result).Returns(actionResult);\n            ActionFilterImpl filter = new ActionFilterImpl()\n            {\n                OnResultExecutingImpl = delegate(ResultExecutingContext filterContext) { actions.Add(\"OnResultExecuting\"); },\n                OnResultExecutedImpl = delegate(ResultExecutedContext filterContext)\n                {\n                    Thread.ResetAbort();\n                    actions.Add(\"OnResultExecuted\");\n                    Assert.Same(actionResult, filterContext.Result);\n                    Assert.Null(filterContext.Exception);\n                    Assert.False(filterContext.ExceptionHandled);\n                }\n            };\n            List<IResultFilter> filters = new List<IResultFilter>() { filter, };\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            // Act & Assert\n            Assert.Throws<ThreadAbortException>(\n                delegate { helper.PublicInvokeActionResultWithFilters(mockPreContext.Object, filters, actionResult); },\n                \"Thread was being aborted.\");\n            Assert.Equal(3, actions.Count);\n            Assert.Equal(\"OnResultExecuting\", actions[0]);\n            Assert.Equal(\"Continuation\", actions[1]);\n            Assert.Equal(\"OnResultExecuted\", actions[2]);\n        }\n\n        [Fact]\n        public void InvokeActionResultWithFiltersWhereContinuationThrowsUnhandledWithMultipleFilters()\n        {\n            // Arrange\n            List<string> actions = new List<string>();\n            string expectedExceptionMessage = \"Some exception message.\";\n            Action continuation = delegate\n            {\n                actions.Add(\"Continuation\");\n                throw new Exception(expectedExceptionMessage);\n            };\n            ActionFilterImpl filter1 = new ActionFilterImpl()\n            {\n                OnResultExecutingImpl = delegate(ResultExecutingContext filterContext)\n                {\n                    actions.Add(\"OnResultExecuting1\");\n                },\n                OnResultExecutedImpl = delegate(ResultExecutedContext filterContext)\n                {\n                    actions.Add(\"OnResultExecuted1\");\n                    Assert.NotNull(filterContext.Exception);\n                    Assert.Equal(filterContext.Exception.Message, expectedExceptionMessage);\n                }\n            };\n            ActionFilterImpl filter2 = new ActionFilterImpl()\n            {\n                OnResultExecutingImpl = delegate(ResultExecutingContext filterContext)\n                {\n                    actions.Add(\"OnResultExecuting2\");\n                },\n                OnResultExecutedImpl = delegate(ResultExecutedContext filterContext)\n                {\n                    actions.Add(\"OnResultExecuted2\");\n                    Assert.NotNull(filterContext.Exception);\n                    Assert.Equal(filterContext.Exception.Message, expectedExceptionMessage);\n                }\n            };\n            ActionResult actionResult = new ContinuationResult(continuation);\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            ControllerContext context = GetControllerContext(controller);\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n            List<IResultFilter> filters = new List<IResultFilter>() { filter1, filter2 };\n\n            // Act\n            Assert.Throws<Exception>(\n                delegate { helper.PublicInvokeActionResultWithFilters(context, filters, actionResult); },\n                expectedExceptionMessage);\n\n            // Assert\n            Assert.Equal(5, actions.Count);\n            Assert.Equal(\"OnResultExecuting1\", actions[0]);\n            Assert.Equal(\"OnResultExecuting2\", actions[1]);\n            Assert.Equal(\"Continuation\", actions[2]);\n            Assert.Equal(\"OnResultExecuted2\", actions[3]);\n            Assert.Equal(\"OnResultExecuted1\", actions[4]);\n        }\n\n        [Fact]\n        public void InvokeActionResultWithFiltersWhereContinuationThrowsHandledByEarlierFilter()\n        {\n            // Arrange\n            List<string> actions = new List<string>();\n            Exception exception = new Exception();\n            Action continuation = delegate\n            {\n                actions.Add(\"Continuation\");\n                throw exception;\n            };\n            ActionFilterImpl filter1 = new ActionFilterImpl()\n            {\n                OnResultExecutingImpl = delegate(ResultExecutingContext filterContext)\n                {\n                    actions.Add(\"OnResultExecuting1\");\n                },\n                OnResultExecutedImpl = delegate(ResultExecutedContext filterContext)\n                {\n                    actions.Add(\"OnResultExecuted1\");\n                    filterContext.ExceptionHandled = true;\n                    Assert.Same(exception, filterContext.Exception);\n                }\n            };\n            ActionFilterImpl filter2 = new ActionFilterImpl()\n            {\n                OnResultExecutingImpl = delegate(ResultExecutingContext filterContext)\n                {\n                    actions.Add(\"OnResultExecuting2\");\n                },\n                OnResultExecutedImpl = delegate(ResultExecutedContext filterContext)\n                {\n                    actions.Add(\"OnResultExecuted2\");\n                    Assert.Same(exception, filterContext.Exception);\n                }\n            };\n            ActionResult actionResult = new ContinuationResult(continuation);\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            ControllerContext context = GetControllerContext(controller);\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n            List<IResultFilter> filters = new List<IResultFilter>() { filter1, filter2 };\n\n            // Act\n            ResultExecutedContext result = helper.PublicInvokeActionResultWithFilters(context, filters, actionResult);\n\n            // Assert\n            Assert.Equal(5, actions.Count);\n            Assert.Equal(\"OnResultExecuting1\", actions[0]);\n            Assert.Equal(\"OnResultExecuting2\", actions[1]);\n            Assert.Equal(\"Continuation\", actions[2]);\n            Assert.Equal(\"OnResultExecuted2\", actions[3]);\n            Assert.Equal(\"OnResultExecuted1\", actions[4]);\n            Assert.Same(exception, result.Exception);\n            Assert.True(result.ExceptionHandled);\n            Assert.Same(actionResult, result.Result);\n        }\n\n        [Fact]\n        public void InvokeActionResultWithFiltersWhereContinuationThrowsHandledByLaterFilter()\n        {\n            // Arrange\n            List<string> actions = new List<string>();\n            Exception exception = new Exception();\n            Action continuation = delegate\n            {\n                actions.Add(\"Continuation\");\n                throw exception;\n            };\n            ActionFilterImpl filter1 = new ActionFilterImpl()\n            {\n                OnResultExecutingImpl = delegate(ResultExecutingContext filterContext)\n                {\n                    actions.Add(\"OnResultExecuting1\");\n                },\n                OnResultExecutedImpl = delegate(ResultExecutedContext filterContext)\n                {\n                    actions.Add(\"OnResultExecuted1\");\n                    Assert.True(filterContext.ExceptionHandled);\n                }\n            };\n            ActionFilterImpl filter2 = new ActionFilterImpl()\n            {\n                OnResultExecutingImpl = delegate(ResultExecutingContext filterContext)\n                {\n                    actions.Add(\"OnResultExecuting2\");\n                },\n                OnResultExecutedImpl = delegate(ResultExecutedContext filterContext)\n                {\n                    actions.Add(\"OnResultExecuted2\");\n                    Assert.Same(exception, filterContext.Exception);\n                    filterContext.ExceptionHandled = true;\n                }\n            };\n            ActionResult actionResult = new ContinuationResult(continuation);\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            ControllerContext context = GetControllerContext(controller);\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n            List<IResultFilter> filters = new List<IResultFilter>() { filter1, filter2 };\n\n            // Act\n            ResultExecutedContext result = helper.PublicInvokeActionResultWithFilters(context, filters, actionResult);\n\n            // Assert\n            Assert.Equal(5, actions.Count);\n            Assert.Equal(\"OnResultExecuting1\", actions[0]);\n            Assert.Equal(\"OnResultExecuting2\", actions[1]);\n            Assert.Equal(\"Continuation\", actions[2]);\n            Assert.Equal(\"OnResultExecuted2\", actions[3]);\n            Assert.Equal(\"OnResultExecuted1\", actions[4]);\n            Assert.Same(exception, result.Exception);\n            Assert.True(result.ExceptionHandled);\n            Assert.Same(actionResult, result.Result);\n        }\n\n        [Fact]\n        public void InvokeActionResultWithFiltersWhereCancelled()\n        {\n            // Arrange\n            bool wasCalled = false;\n            MethodInfo mi = typeof(object).GetMethod(\"ToString\");\n            object[] paramValues = new object[0];\n            ActionFilterImpl filter = new ActionFilterImpl()\n            {\n                OnResultExecutingImpl = delegate(ResultExecutingContext filterContext)\n                {\n                    Assert.False(wasCalled);\n                    wasCalled = true;\n                    filterContext.Cancel = true;\n                },\n            };\n            Action continuation = delegate\n            {\n                Assert.True(false, \"The continuation should not be called.\");\n            };\n            ActionResult actionResult = new ContinuationResult(continuation);\n\n            Mock<ResultExecutingContext> mockResultExecutingContext = new Mock<ResultExecutingContext>() { DefaultValue = DefaultValue.Mock };\n            mockResultExecutingContext.Setup(c => c.Result).Returns(actionResult);\n            List<IResultFilter> filters = new List<IResultFilter>() { filter, };\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            // Act\n            ResultExecutedContext result = helper.PublicInvokeActionResultWithFilters(mockResultExecutingContext.Object, filters, actionResult);\n\n            // Assert\n            Assert.True(wasCalled);\n            Assert.Null(result.Exception);\n            Assert.True(result.Canceled);\n            Assert.Same(actionResult, result.Result);\n        }\n\n        [Fact]\n        public void InvokeActionResultWithFiltersWhereCancelledByEarlierFilter()\n        {\n            // Arrange\n            List<string> actions = new List<string>();\n            ActionFilterImpl filter1 = new ActionFilterImpl()\n            {\n                OnResultExecutingImpl = delegate(ResultExecutingContext filterContext)\n                {\n                    actions.Add(\"OnResultExecuting1\");\n                    filterContext.Cancel = true;\n                },\n                OnResultExecutedImpl = delegate(ResultExecutedContext filterContext)\n                {\n                    actions.Add(\"OnResultExecuted1\");\n                }\n            };\n            ActionFilterImpl filter2 = new ActionFilterImpl()\n            {\n                OnResultExecutingImpl = delegate(ResultExecutingContext filterContext)\n                {\n                    actions.Add(\"OnResultExecuting2\");\n                },\n                OnResultExecutedImpl = delegate(ResultExecutedContext filterContext)\n                {\n                    actions.Add(\"OnResultExecuted2\");\n                }\n            };\n            Action continuation = delegate\n            {\n                actions.Add(\"Continuation\");\n            };\n            ActionResult actionResult = new ContinuationResult(continuation);\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            ControllerContext context = GetControllerContext(controller);\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n            List<IResultFilter> filters = new List<IResultFilter>() { filter1, filter2 };\n\n            // Act\n            ResultExecutedContext result = helper.PublicInvokeActionResultWithFilters(context, filters, actionResult);\n\n            // Assert\n            string action = Assert.Single(actions);\n            Assert.Equal(\"OnResultExecuting1\", action);\n            Assert.Null(result.Exception);\n            Assert.True(result.Canceled);\n            Assert.Same(actionResult, result.Result);\n        }\n\n        [Fact]\n        public void InvokeActionResultWithFiltersWhereCancelledByLaterFilter()\n        {\n            // Arrange\n            List<string> actions = new List<string>();\n            ActionFilterImpl filter1 = new ActionFilterImpl()\n            {\n                OnResultExecutingImpl = delegate(ResultExecutingContext filterContext)\n                {\n                    actions.Add(\"OnResultExecuting1\");\n                },\n                OnResultExecutedImpl = delegate(ResultExecutedContext filterContext)\n                {\n                    actions.Add(\"OnResultExecuted1\");\n                    Assert.True(filterContext.Canceled);\n                }\n            };\n            ActionFilterImpl filter2 = new ActionFilterImpl()\n            {\n                OnResultExecutingImpl = delegate(ResultExecutingContext filterContext)\n                {\n                    actions.Add(\"OnResultExecuting2\");\n                    filterContext.Cancel = true;\n                },\n                OnResultExecutedImpl = delegate(ResultExecutedContext filterContext)\n                {\n                    actions.Add(\"OnResultExecuted2\");\n                }\n            };\n            Action continuation = delegate\n            {\n                actions.Add(\"Continuation\");\n            };\n            ActionResult actionResult = new ContinuationResult(continuation);\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            ControllerContext context = GetControllerContext(controller);\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n            List<IResultFilter> filters = new List<IResultFilter>() { filter1, filter2 };\n\n            // Act\n            ResultExecutedContext result = helper.PublicInvokeActionResultWithFilters(context, filters, actionResult);\n\n            // Assert\n            Assert.Equal(3, actions.Count);\n            Assert.Equal(\"OnResultExecuting1\", actions[0]);\n            Assert.Equal(\"OnResultExecuting2\", actions[1]);\n            Assert.Equal(\"OnResultExecuted1\", actions[2]);\n            Assert.Null(result.Exception);\n            Assert.True(result.Canceled);\n            Assert.Same(actionResult, result.Result);\n        }\n\n        [Fact]\n        public void InvokeActionResultWithFiltersWithNormalControlFlow()\n        {\n            // Arrange\n            List<string> actions = new List<string>();\n            Action continuation = delegate\n            {\n                actions.Add(\"Continuation\");\n            };\n            ActionResult actionResult = new ContinuationResult(continuation);\n            ActionFilterImpl filter = new ActionFilterImpl()\n            {\n                OnResultExecutingImpl = delegate(ResultExecutingContext filterContext)\n                {\n                    Assert.Same(actionResult, filterContext.Result);\n                    Assert.False(filterContext.Cancel);\n                    actions.Add(\"OnResultExecuting\");\n                },\n                OnResultExecutedImpl = delegate(ResultExecutedContext filterContext)\n                {\n                    Assert.Same(actionResult, filterContext.Result);\n                    Assert.False(filterContext.Canceled);\n                    Assert.Null(filterContext.Exception);\n                    Assert.False(filterContext.ExceptionHandled);\n                    actions.Add(\"OnResultExecuted\");\n                }\n            };\n            Mock<ResultExecutingContext> mockResultExecutingContext = new Mock<ResultExecutingContext>();\n            mockResultExecutingContext.Setup(c => c.Result).Returns(actionResult);\n            List<IResultFilter> filters = new List<IResultFilter>() { filter, };\n            ControllerActionInvokerHelper helper = new ControllerActionInvokerHelper();\n\n            // Act\n            ResultExecutedContext result = helper.PublicInvokeActionResultWithFilters(mockResultExecutingContext.Object, filters, actionResult);\n\n            // Assert\n            Assert.Equal(3, actions.Count);\n            Assert.Equal(\"OnResultExecuting\", actions[0]);\n            Assert.Equal(\"Continuation\", actions[1]);\n            Assert.Equal(\"OnResultExecuted\", actions[2]);\n            Assert.Same(result.Result, actionResult);\n        }\n\n        [Fact]\n        public void InvokeMethodCallsOverriddenCreateActionResult()\n        {\n            // Arrange\n            CustomResultInvokerController controller = new CustomResultInvokerController();\n            ControllerContext context = GetControllerContext(controller);\n            CustomResultInvoker helper = new CustomResultInvoker();\n            MethodInfo mi = typeof(CustomResultInvokerController).GetMethod(\"ReturnCustomResult\");\n            ReflectedActionDescriptor ad = new ReflectedActionDescriptor(mi, \"ReturnCustomResult\", new Mock<ControllerDescriptor>().Object);\n            IDictionary<string, object> parameters = new Dictionary<string, object>();\n\n            // Act\n            ActionResult actionResult = helper.PublicInvokeActionMethod(context, ad, parameters);\n\n            // Assert (arg got passed to method + back correctly)\n            CustomResult customResult = Assert.IsType<CustomResult>(actionResult);\n            Assert.Equal(\"abc123\", customResult.ReturnValue);\n        }\n\n        [Fact]\n        public void FindAction_MultipleMethodsSameActionOneWithRouteAttributeAndRouteWasMatched_ReturnsMethodWithRoutingAttribute()\n        {\n            // Arrange\n            Type controllerType = typeof(WithRoutingAttributeController);\n            ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerType);\n\n            var context = new ControllerContext();\n            context.RouteData = new RouteData();\n            context.RouteData.Route = DirectRouteTestHelpers.BuildDirectRouteFromMethod<WithRoutingAttributeController>(c => c.Action());\n            context.RouteData.AddDirectRouteMatches();\n\n            var actionInvoker = new ControllerActionInvokerHelper();\n\n            // Act\n            ActionDescriptor actionDescriptor = actionInvoker.PublicFindAction(context, controllerDescriptor, actionName: null);\n\n            var matchedMethod = ((ReflectedActionDescriptor)actionDescriptor).MethodInfo;\n\n            // Assert\n            Assert.Equal(typeof(WithRoutingAttributeController).GetMethod(\"Action\"), matchedMethod);\n        }\n\n        [Fact]\n        public void FindAction_ControllerLevelDirectRoute_FindsMatch()\n        {\n            // Arrange\n            Type controllerType = typeof(AttributeRoutingOnTheController);\n            ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerType);\n\n            var context = new ControllerContext();\n            context.RouteData = new RouteData();\n            context.RouteData.Route = DirectRouteTestHelpers.BuildDirectRouteFromController<AttributeRoutingOnTheController>();\n\n            // Simulate a match that binds the action parameter\n            context.RouteData.AddDirectRouteMatches((r, rd) => { rd.Values.Add(\"action\", \"Action1\"); return true; });\n\n            ControllerActionInvokerHelper invoker = new ControllerActionInvokerHelper();\n\n            // Act\n            ActionDescriptor actionDescriptor = invoker.PublicFindAction(context, controllerDescriptor, actionName: null);\n\n            var matchedMethod = ((ReflectedActionDescriptor)actionDescriptor).MethodInfo;\n\n            // Assert\n            Assert.Equal(typeof(AttributeRoutingOnTheController).GetMethod(\"Action1\"), matchedMethod);\n        }\n\n        [Fact]\n        public void FindAction_ControllerLevelDirectRoute_NoMatch()\n        {\n            // Arrange\n            Type controllerType = typeof(AttributeRoutingOnTheController);\n            ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerType);\n\n            var context = new ControllerContext();\n            context.RouteData = new RouteData();\n            context.RouteData.Route = DirectRouteTestHelpers.BuildDirectRouteFromController<AttributeRoutingOnTheController>();\n\n            // Simulate a match that binds the action parameter\n            context.RouteData.AddDirectRouteMatches((r, rd) => { rd.Values.Add(\"action\", \"Action3\"); return true; });\n\n            ControllerActionInvokerHelper invoker = new ControllerActionInvokerHelper();\n\n            // Act\n            ActionDescriptor actionDescriptor = invoker.PublicFindAction(context, controllerDescriptor, actionName: null);\n\n            // Assert\n            Assert.Null(actionDescriptor);\n        }\n\n        [Fact]\n        public void FindAction_ControllerLevelDirectRoute_AmbiguousMatch()\n        {\n            // Arrange\n            Type controllerType = typeof(AttributeRoutingOnTheController);\n            ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerType);\n\n            var context = new ControllerContext();\n            context.RouteData = new RouteData();\n            context.RouteData.Route = DirectRouteTestHelpers.BuildDirectRouteFromController<AttributeRoutingOnTheController>();\n\n            // Simulate a match that binds the action parameter\n            context.RouteData.AddDirectRouteMatches((r, rd) => { rd.Values.Add(\"action\", \"Action2\"); return true; });\n\n            ControllerActionInvokerHelper invoker = new ControllerActionInvokerHelper();\n\n            // Act & Assert\n            Assert.Throws<AmbiguousMatchException>(() => invoker.PublicFindAction(context, controllerDescriptor, actionName: null));\n        }\n\n        [Fact]\n        public void FindActionMethod_MultipleMethodsSameActionOneWithRouteAttributeAndRouteWasMatched_ReturnsMethodWithRoutingAttribute()\n        {\n            // Arrange\n            Type controllerType = typeof(WithRoutingAttributeController);\n            ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controllerType);\n\n            var context = new ControllerContext();\n            context.RouteData = new RouteData();\n            context.RouteData.Route = DirectRouteTestHelpers.BuildDirectRouteFromMethod<WithRoutingAttributeController>(c => c.Action());\n            context.RouteData.AddDirectRouteMatches();\n\n            ControllerActionInvokerHelper invoker = new ControllerActionInvokerHelper();\n\n            // Act\n            ActionDescriptor actionDescriptor = invoker.PublicFindAction(context, controllerDescriptor, actionName: null);\n            MethodInfo matchedMethod = ((ReflectedActionDescriptor)actionDescriptor).MethodInfo;\n\n            // Assert\n            Assert.Equal(\"Action\", matchedMethod.Name);\n        }\n\n        private static ControllerContext GetControllerContext(ControllerBase controller)\n        {\n            return GetControllerContext(controller, null);\n        }\n\n        private static ControllerContext GetControllerContext(ControllerBase controller, IDictionary<string, object> values, Action validateInputCallback = null)\n        {\n            SimpleValueProvider valueProvider = new SimpleValueProvider();\n            controller.ValueProvider = valueProvider;\n            if (values != null)\n            {\n                foreach (var entry in values)\n                {\n                    valueProvider[entry.Key] = entry.Value;\n                }\n            }\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.SetupGet(c => c.RouteData).Returns(new RouteData());\n            mockControllerContext.SetupGet(c => c.HttpContext.Session).Returns((HttpSessionStateBase)null);\n            mockControllerContext.SetupProperty(c => c.HttpContext.User);\n\n            mockControllerContext.Setup(c => c.HttpContext.Request.ValidateInput()).Callback(() =>\n            {\n                if (!controller.ValidateRequest)\n                {\n                    Assert.True(false, \"ValidateRequest() should not be called if the controller opted out.\");\n                }\n                if (validateInputCallback != null)\n                {\n                    // signal to caller that ValidateInput was called\n                    validateInputCallback();\n                }\n            });\n\n            mockControllerContext.Setup(c => c.Controller).Returns(controller);\n            return mockControllerContext.Object;\n        }\n\n        private class ActionFilterImpl : IActionFilter, IResultFilter\n        {\n            public Action<ActionExecutingContext> OnActionExecutingImpl { get; set; }\n\n            public void OnActionExecuting(ActionExecutingContext filterContext)\n            {\n                OnActionExecutingImpl(filterContext);\n            }\n\n            public Action<ActionExecutedContext> OnActionExecutedImpl { get; set; }\n\n            public void OnActionExecuted(ActionExecutedContext filterContext)\n            {\n                OnActionExecutedImpl(filterContext);\n            }\n\n            public Action<ResultExecutingContext> OnResultExecutingImpl { get; set; }\n\n            public void OnResultExecuting(ResultExecutingContext filterContext)\n            {\n                OnResultExecutingImpl(filterContext);\n            }\n\n            public Action<ResultExecutedContext> OnResultExecutedImpl { get; set; }\n\n            public void OnResultExecuted(ResultExecutedContext filterContext)\n            {\n                OnResultExecutedImpl(filterContext);\n            }\n        }\n\n        // This controller serves only to test vanilla method invocation - nothing exciting here\n        private class BasicMethodInvokeController : Controller\n        {\n            public ActionResult ReturnsRenderView(object viewItem)\n            {\n                return View(\"ReturnsRenderView\", viewItem);\n            }\n        }\n\n        private class BlankController : Controller\n        {\n        }\n\n        private sealed class CustomResult : ActionResult\n        {\n            public object ReturnValue { get; set; }\n\n            public override void ExecuteResult(ControllerContext context)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private sealed class CustomResultInvokerController : Controller\n        {\n            public object ReturnCustomResult()\n            {\n                return \"abc123\";\n            }\n        }\n\n        private sealed class CustomResultInvoker : ControllerActionInvokerHelper\n        {\n            protected override ActionResult CreateActionResult(ControllerContext controllerContext, ActionDescriptor actionDescriptor, object actionReturnValue)\n            {\n                return new CustomResult\n                {\n                    ReturnValue = actionReturnValue\n                };\n            }\n        }\n\n        private class ContinuationController : Controller\n        {\n            private Func<ActionResult> _continuation;\n\n            public ContinuationController(Func<ActionResult> continuation)\n            {\n                _continuation = continuation;\n            }\n\n            public ActionResult Go()\n            {\n                return _continuation();\n            }\n\n            public static MethodInfo GoMethod\n            {\n                get { return typeof(ContinuationController).GetMethod(\"Go\"); }\n            }\n        }\n\n        private class ContinuationResult : ActionResult\n        {\n            private Action _continuation;\n\n            public ContinuationResult(Action continuation)\n            {\n                _continuation = continuation;\n            }\n\n            public override void ExecuteResult(ControllerContext context)\n            {\n                _continuation();\n            }\n        }\n\n        private class EmptyController : Controller\n        {\n        }\n\n        // This controller serves to test the default action method matching mechanism\n        private class FindMethodController : Controller\n        {\n            public ActionResult ValidActionMethod()\n            {\n                return null;\n            }\n\n            [NonAction]\n            public virtual ActionResult NonActionMethod()\n            {\n                return null;\n            }\n\n            [NonAction]\n            public ActionResult DerivedIsActionMethod()\n            {\n                return null;\n            }\n\n            public ActionResult MethodOverloaded()\n            {\n                return null;\n            }\n\n            public ActionResult MethodOverloaded(string s)\n            {\n                return null;\n            }\n\n            public void WrongReturnType()\n            {\n            }\n\n            protected ActionResult ProtectedMethod()\n            {\n                return null;\n            }\n\n            private ActionResult PrivateMethod()\n            {\n                return null;\n            }\n\n            internal ActionResult InternalMethod()\n            {\n                return null;\n            }\n\n            public override string ToString()\n            {\n                // originally defined on Object\n                return base.ToString();\n            }\n\n            public ActionResult Property\n            {\n                get { return null; }\n            }\n\n#pragma warning disable 0067\n            // CS0067: Event declared but never used. We use reflection to access this member.\n            public event EventHandler Event;\n#pragma warning restore 0067\n        }\n\n        private class DerivedFindMethodController : FindMethodController\n        {\n            public override ActionResult NonActionMethod()\n            {\n                return base.NonActionMethod();\n            }\n\n            // FindActionMethod() should accept this as a valid method since [NonAction] doesn't appear\n            // in its inheritance chain.\n            public new ActionResult DerivedIsActionMethod()\n            {\n                return base.DerivedIsActionMethod();\n            }\n        }\n\n        // Similar to FindMethodController, but tests generics support specifically\n        private class GenericFindMethodController<T> : Controller\n        {\n            public ActionResult ClosedGenericMethod(T t)\n            {\n                return null;\n            }\n\n            public ActionResult OpenGenericMethod<U>(U t)\n            {\n                return null;\n            }\n        }\n\n        // Allows for testing parameter conversions, etc.\n        private class ParameterTestingController : Controller\n        {\n            public ParameterTestingController()\n            {\n                Values = new Dictionary<string, object>();\n            }\n\n            public IDictionary<string, object> Values { get; private set; }\n\n            public void Foo(string foo, string bar, string baz)\n            {\n                Values[\"foo\"] = foo;\n                Values[\"bar\"] = bar;\n                Values[\"baz\"] = baz;\n            }\n\n            public void HasOutParam(out string foo)\n            {\n                foo = null;\n            }\n\n            public void HasRefParam(ref string foo)\n            {\n            }\n\n            public void Parameterless()\n            {\n            }\n\n            public void TakesInt(int id)\n            {\n                Values[\"id\"] = id;\n            }\n\n            public ActionResult TakesNullableInt(int? id)\n            {\n                Values[\"id\"] = id;\n                return null;\n            }\n\n            public void TakesString(string id)\n            {\n            }\n\n            public void TakesDateTime(DateTime id)\n            {\n            }\n        }\n\n        // Provides access to the protected members of ControllerActionInvoker\n        public class ControllerActionInvokerHelper : ControllerActionInvoker\n        {\n            public ControllerActionInvokerHelper()\n            {\n                // set instance caches to prevent modifying global test application state\n                DescriptorCache = new ControllerDescriptorCache();\n            }\n\n            public ControllerActionInvokerHelper(params object[] filters)\n                : base(filters)\n            {\n                // set instance caches to prevent modifying global test application state\n                DescriptorCache = new ControllerDescriptorCache();\n            }\n\n            public virtual ActionResult PublicCreateActionResult(ControllerContext controllerContext, ActionDescriptor actionDescriptor, object actionReturnValue)\n            {\n                return base.CreateActionResult(controllerContext, actionDescriptor, actionReturnValue);\n            }\n\n            protected override ActionResult CreateActionResult(ControllerContext controllerContext, ActionDescriptor actionDescriptor, object actionReturnValue)\n            {\n                return PublicCreateActionResult(controllerContext, actionDescriptor, actionReturnValue);\n            }\n\n            public virtual ActionDescriptor PublicFindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, string actionName)\n            {\n                return base.FindAction(controllerContext, controllerDescriptor, actionName);\n            }\n\n            protected override ActionDescriptor FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, string actionName)\n            {\n                return PublicFindAction(controllerContext, controllerDescriptor, actionName);\n            }\n\n            public virtual ControllerDescriptor PublicGetControllerDescriptor(ControllerContext controllerContext)\n            {\n                return base.GetControllerDescriptor(controllerContext);\n            }\n\n            protected override ControllerDescriptor GetControllerDescriptor(ControllerContext controllerContext)\n            {\n                return PublicGetControllerDescriptor(controllerContext);\n            }\n\n            public virtual FilterInfo PublicGetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)\n            {\n                return base.GetFilters(controllerContext, actionDescriptor);\n            }\n\n            protected override FilterInfo GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)\n            {\n                return PublicGetFilters(controllerContext, actionDescriptor);\n            }\n\n            public virtual object PublicGetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor)\n            {\n                return base.GetParameterValue(controllerContext, parameterDescriptor);\n            }\n\n            protected override object GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor)\n            {\n                return PublicGetParameterValue(controllerContext, parameterDescriptor);\n            }\n\n            public virtual IDictionary<string, object> PublicGetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor)\n            {\n                return base.GetParameterValues(controllerContext, actionDescriptor);\n            }\n\n            protected override IDictionary<string, object> GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor)\n            {\n                return PublicGetParameterValues(controllerContext, actionDescriptor);\n            }\n\n            public virtual ActionResult PublicInvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters)\n            {\n                return base.InvokeActionMethod(controllerContext, actionDescriptor, parameters);\n            }\n\n            protected override ActionResult InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters)\n            {\n                return PublicInvokeActionMethod(controllerContext, actionDescriptor, parameters);\n            }\n\n            public virtual ActionExecutedContext PublicInvokeActionMethodWithFilters(ControllerContext controllerContext, IList<IActionFilter> filters, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters)\n            {\n                return base.InvokeActionMethodWithFilters(controllerContext, filters, actionDescriptor, parameters);\n            }\n\n            protected override ActionExecutedContext InvokeActionMethodWithFilters(ControllerContext controllerContext, IList<IActionFilter> filters, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters)\n            {\n                return PublicInvokeActionMethodWithFilters(controllerContext, filters, actionDescriptor, parameters);\n            }\n\n            public virtual void PublicInvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)\n            {\n                base.InvokeActionResult(controllerContext, actionResult);\n            }\n\n            protected override void InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)\n            {\n                PublicInvokeActionResult(controllerContext, actionResult);\n            }\n\n            public virtual ResultExecutedContext PublicInvokeActionResultWithFilters(ControllerContext controllerContext, IList<IResultFilter> filters, ActionResult actionResult)\n            {\n                return base.InvokeActionResultWithFilters(controllerContext, filters, actionResult);\n            }\n\n            protected override ResultExecutedContext InvokeActionResultWithFilters(ControllerContext controllerContext, IList<IResultFilter> filters, ActionResult actionResult)\n            {\n                return PublicInvokeActionResultWithFilters(controllerContext, filters, actionResult);\n            }\n\n            public virtual AuthorizationContext PublicInvokeAuthorizationFilters(ControllerContext controllerContext, IList<IAuthorizationFilter> filters, ActionDescriptor actionDescriptor)\n            {\n                return base.InvokeAuthorizationFilters(controllerContext, filters, actionDescriptor);\n            }\n\n            protected override AuthorizationContext InvokeAuthorizationFilters(ControllerContext controllerContext, IList<IAuthorizationFilter> filters, ActionDescriptor actionDescriptor)\n            {\n                return PublicInvokeAuthorizationFilters(controllerContext, filters, actionDescriptor);\n            }\n\n            public virtual AuthenticationContext PublicInvokeAuthenticationFilters(ControllerContext controllerContext, IList<IAuthenticationFilter> filters, ActionDescriptor actionDescriptor)\n            {\n                return base.InvokeAuthenticationFilters(controllerContext, filters, actionDescriptor);\n            }\n\n            protected override AuthenticationContext InvokeAuthenticationFilters(ControllerContext controllerContext, IList<IAuthenticationFilter> filters, ActionDescriptor actionDescriptor)\n            {\n                return PublicInvokeAuthenticationFilters(controllerContext, filters, actionDescriptor);\n            }\n\n            public virtual AuthenticationChallengeContext PublicInvokeAuthenticationFiltersChallenge(ControllerContext controllerContext, IList<IAuthenticationFilter> filters, ActionDescriptor actionDescriptor, ActionResult result)\n            {\n                return base.InvokeAuthenticationFiltersChallenge(controllerContext, filters, actionDescriptor, result);\n            }\n\n            protected override AuthenticationChallengeContext InvokeAuthenticationFiltersChallenge(ControllerContext controllerContext, IList<IAuthenticationFilter> filters, ActionDescriptor actionDescriptor, ActionResult result)\n            {\n                return PublicInvokeAuthenticationFiltersChallenge(controllerContext, filters, actionDescriptor, result);\n            }\n\n            public virtual ExceptionContext PublicInvokeExceptionFilters(ControllerContext controllerContext, IList<IExceptionFilter> filters, Exception exception)\n            {\n                return base.InvokeExceptionFilters(controllerContext, filters, exception);\n            }\n\n            protected override ExceptionContext InvokeExceptionFilters(ControllerContext controllerContext, IList<IExceptionFilter> filters, Exception exception)\n            {\n                return PublicInvokeExceptionFilters(controllerContext, filters, exception);\n            }\n        }\n\n        public class AuthorizationFilterHelper : IAuthorizationFilter\n        {\n            private IList<AuthorizationFilterHelper> _callQueue;\n            public ActionResult ShortCircuitResult;\n\n            public AuthorizationFilterHelper(IList<AuthorizationFilterHelper> callQueue)\n            {\n                _callQueue = callQueue;\n            }\n\n            public void OnAuthorization(AuthorizationContext filterContext)\n            {\n                _callQueue.Add(this);\n                if (ShortCircuitResult != null)\n                {\n                    filterContext.Result = ShortCircuitResult;\n                }\n            }\n        }\n\n        public class AuthenticationFilterHelper : IAuthenticationFilter\n        {\n            private IList<AuthenticationFilterHelper> _callQueue;\n            public ActionResult ShortCircuitResult;\n            public IPrincipal Principal;\n\n            public AuthenticationFilterHelper(IList<AuthenticationFilterHelper> callQueue)\n            {\n                _callQueue = callQueue;\n            }\n\n            public void OnAuthentication(AuthenticationContext filterContext)\n            {\n                _callQueue.Add(this);\n                if (ShortCircuitResult != null)\n                {\n                    filterContext.Result = ShortCircuitResult;\n                }\n                if (Principal != null)\n                {\n                    filterContext.Principal = Principal;\n                }\n            }\n\n            public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)\n            {\n                _callQueue.Add(this);\n            }\n        }\n\n        public class ExceptionFilterHelper : IExceptionFilter\n        {\n            private IList<ExceptionFilterHelper> _callQueue;\n            public bool ShouldHandleException;\n            public ExceptionContext ContextPassed;\n\n            public ExceptionFilterHelper(IList<ExceptionFilterHelper> callQueue)\n            {\n                _callQueue = callQueue;\n            }\n\n            public void OnException(ExceptionContext filterContext)\n            {\n                _callQueue.Add(this);\n                if (ShouldHandleException)\n                {\n                    filterContext.ExceptionHandled = true;\n                }\n                ContextPassed = filterContext;\n            }\n        }\n\n        private class CustomConverterController : Controller\n        {\n            public void ParameterWithoutBindAttribute([PredicateReflector] string someParam)\n            {\n            }\n\n            public void ParameterHasBindAttribute([Bind(Include = \"foo\"), PredicateReflector] string someParam)\n            {\n            }\n\n            public void ParameterHasDefaultValueAttribute([DefaultValue(42)] int foo)\n            {\n            }\n\n            public void ParameterHasFieldPrefix([Bind(Prefix = \"bar\")] string foo)\n            {\n            }\n\n            public void ParameterHasNullFieldPrefix([Bind(Include = \"whatever\")] string foo)\n            {\n            }\n\n            public void ParameterHasEmptyFieldPrefix([Bind(Prefix = \"\")] MySimpleModel foo)\n            {\n            }\n\n            public void ParameterHasNoPrefixAndComplexType(MySimpleModel foo)\n            {\n            }\n\n            public void ParameterHasPrefixAndComplexType([Bind(Prefix = \"badprefix\")] MySimpleModel foo)\n            {\n            }\n\n            public void ParameterHasNoConverters(string foo)\n            {\n            }\n\n            public void ParameterHasOneConverter([MyCustomConverter] string foo)\n            {\n            }\n\n            public void ParameterHasTwoConverters([MyCustomConverter, MyCustomConverter] string foo)\n            {\n            }\n        }\n\n        public class MySimpleModel\n        {\n            public int IntProp { get; set; }\n            public string StringProp { get; set; }\n        }\n\n        [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = true, Inherited = false)]\n        private class PredicateReflectorAttribute : CustomModelBinderAttribute\n        {\n            public override IModelBinder GetBinder()\n            {\n                return new MyConverter();\n            }\n\n            private class MyConverter : IModelBinder\n            {\n                public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)\n                {\n                    string s = String.Format(\"foo={0}&bar={1}\", bindingContext.PropertyFilter(\"foo\"), bindingContext.PropertyFilter(\"bar\"));\n                    return s;\n                }\n            }\n        }\n\n        [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = true, Inherited = false)]\n        private class MyCustomConverterAttribute : CustomModelBinderAttribute\n        {\n            public override IModelBinder GetBinder()\n            {\n                return new MyConverter();\n            }\n\n            private class MyConverter : IModelBinder\n            {\n                public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)\n                {\n                    string s = bindingContext.ModelName + \"_\" + bindingContext.ModelType.Name;\n                    return s;\n                }\n            }\n        }\n\n        // helper class for making sure that we're performing culture-invariant string conversions\n        public class CultureReflector : IFormattable\n        {\n            string IFormattable.ToString(string format, IFormatProvider formatProvider)\n            {\n                CultureInfo cInfo = (CultureInfo)formatProvider;\n                return cInfo.ThreeLetterISOLanguageName;\n            }\n        }\n\n        private sealed class ThreadCurrentPrincipalContext : IDisposable\n        {\n            private readonly IPrincipal _originalPrincipal;\n\n            private bool _disposed;\n\n            public ThreadCurrentPrincipalContext()\n            {\n                _originalPrincipal = Thread.CurrentPrincipal;\n            }\n\n            public void Dispose()\n            {\n                if (!_disposed)\n                {\n                    Thread.CurrentPrincipal = _originalPrincipal;\n                    _disposed = true;\n                }\n            }\n        }\n\n        private class WithRoutingAttributeController : Controller\n        {\n            [Route(\"route\")]\n            [ActionName(\"Action\")] // to make things confusing\n            public void ActionWithoutRoute()\n            {\n            }\n\n            [Route(\"route\")]\n            public void Action()\n            {\n            }\n        }\n\n        [Route(\"controller/{action}\")]\n        private class AttributeRoutingOnTheController : Controller\n        {\n            public void Action1()\n            {\n            }\n\n            public void Action2()\n            {\n            }\n\n            public void Action2(string name)\n            {\n            }\n        }\n\n        private class MatchAttribute : ActionMethodSelectorAttribute\n        {\n            private bool _match;\n\n            public MatchAttribute(bool match)\n            {\n                _match = match;\n            }\n\n            public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)\n            {\n                return _match;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ControllerBaseTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Web.Routing;\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ControllerBaseTest\n    {\n        [Fact]\n        public void ExecuteCallsControllerBaseExecute()\n        {\n            // Arrange\n            RequestContext requestContext = new RequestContext(HttpContextHelpers.GetMockHttpContext().Object, new RouteData());\n\n            Mock<ControllerBaseHelper> mockController = new Mock<ControllerBaseHelper>() { CallBase = true };\n            mockController.Setup(c => c.PublicInitialize(requestContext)).Verifiable();\n            mockController.Setup(c => c.PublicExecuteCore()).Verifiable();\n            IController controller = mockController.Object;\n\n            // Act\n            controller.Execute(requestContext);\n\n            // Assert\n            mockController.Verify();\n        }\n\n        [Fact]\n        public void ExecuteThrowsIfCalledTwice()\n        {\n            // Arrange\n            EmptyControllerBase controller = new EmptyControllerBase();\n            RequestContext requestContext = new RequestContext(HttpContextHelpers.GetMockHttpContext().Object, new RouteData());\n\n            // Act\n            ((IController)controller).Execute(requestContext); // first call\n            Assert.Throws<InvalidOperationException>(\n                delegate\n                {\n                    ((IController)controller).Execute(requestContext); // second call\n                },\n                @\"A single instance of controller 'System.Web.Mvc.Test.ControllerBaseTest+EmptyControllerBase' cannot be used to handle multiple requests. If a custom controller factory is in use, make sure that it creates a new instance of the controller for each request.\");\n\n            // Assert\n            Assert.Equal(1, controller.NumTimesExecuteCoreCalled);\n        }\n\n        [Fact]\n        public void ExecuteThrowsIfRequestContextIsNull()\n        {\n            // Arrange\n            IController controller = new ControllerBaseHelper();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { controller.Execute(null); }, \"requestContext\");\n        }\n\n        [Fact]\n        public void ExecuteThrowsIfRequestContextHttpContextIsNull()\n        {\n            //Arrange\n            IController controller = new ControllerBaseHelper();\n\n            //Act & Assert\n            Assert.Throws<ArgumentException>(\n                delegate { controller.Execute(new Mock<RequestContext>().Object); }, \"Cannot execute Controller with a null HttpContext.\\r\\nParameter name: requestContext\");\n        }\n\n        [Fact]\n        public void InitializeSetsControllerContext()\n        {\n            // Arrange\n            ControllerBaseHelper helper = new ControllerBaseHelper();\n            RequestContext requestContext = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData());\n\n            // Act\n            helper.PublicInitialize(requestContext);\n\n            // Assert\n            Assert.Same(requestContext.HttpContext, helper.ControllerContext.HttpContext);\n            Assert.Same(requestContext.RouteData, helper.ControllerContext.RouteData);\n            Assert.Same(helper, helper.ControllerContext.Controller);\n        }\n\n        [Fact]\n        public void TempDataProperty()\n        {\n            // Arrange\n            ControllerBase controller = new ControllerBaseHelper();\n\n            // Act & Assert\n            MemberHelper.TestPropertyWithDefaultInstance(controller, \"TempData\", new TempDataDictionary());\n        }\n\n        [Fact]\n        public void TempDataReturnsParentTempDataWhenInChildRequest()\n        {\n            // Arrange\n            TempDataDictionary tempData = new TempDataDictionary();\n            ViewContext viewContext = new ViewContext { TempData = tempData };\n            RouteData routeData = new RouteData();\n            routeData.DataTokens[ControllerContext.ParentActionViewContextToken] = viewContext;\n            RequestContext requestContext = new RequestContext(new Mock<HttpContextBase>().Object, routeData);\n            ControllerBaseHelper controller = new ControllerBaseHelper();\n            controller.PublicInitialize(requestContext);\n\n            // Act\n            TempDataDictionary result = controller.TempData;\n\n            // Assert\n            Assert.Same(result, tempData);\n        }\n\n        [Fact]\n        public void ValidateRequestProperty()\n        {\n            // Arrange\n            ControllerBase controller = new ControllerBaseHelper();\n\n            // Act & assert\n            MemberHelper.TestBooleanProperty(controller, \"ValidateRequest\", true /* initialValue */, false /* testDefaultValue */);\n        }\n\n        [Fact]\n        public void ValueProviderProperty()\n        {\n            // Arrange\n            ControllerBase controller = new ControllerBaseHelper();\n            IValueProvider valueProvider = new SimpleValueProvider();\n\n            // Act & assert\n            ValueProviderFactory[] originalFactories = ValueProviderFactories.Factories.ToArray();\n            try\n            {\n                ValueProviderFactories.Factories.Clear();\n                MemberHelper.TestPropertyWithDefaultInstance(controller, \"ValueProvider\", valueProvider);\n            }\n            finally\n            {\n                foreach (ValueProviderFactory factory in originalFactories)\n                {\n                    ValueProviderFactories.Factories.Add(factory);\n                }\n            }\n        }\n\n        [Fact]\n        public void ViewDataProperty()\n        {\n            // Arrange\n            ControllerBase controller = new ControllerBaseHelper();\n\n            // Act & Assert\n            MemberHelper.TestPropertyWithDefaultInstance(controller, \"ViewData\", new ViewDataDictionary());\n        }\n\n        [Fact]\n        public void ViewBagProperty_ReflectsViewData()\n        {\n            // Arrange\n            ControllerBase controller = new ControllerBaseHelper();\n            controller.ViewData[\"A\"] = 1;\n\n            // Act & Assert\n            Assert.NotNull(controller.ViewBag);\n            Assert.Equal(1, controller.ViewBag.A);\n        }\n\n        [Fact]\n        public void ViewBagProperty_ReflectsNewViewDataInstance()\n        {\n            // Arrange\n            ControllerBase controller = new ControllerBaseHelper();\n            controller.ViewData[\"A\"] = 1;\n            controller.ViewData = new ViewDataDictionary() { { \"A\", \"bar\" } };\n\n            // Act & Assert\n            Assert.Equal(\"bar\", controller.ViewBag.A);\n        }\n\n        [Fact]\n        public void ViewBag_PropagatesChangesToViewData()\n        {\n            // Arrange\n            ControllerBase controller = new ControllerBaseHelper();\n            controller.ViewData[\"A\"] = 1;\n\n            // Act\n            controller.ViewBag.A = \"foo\";\n            controller.ViewBag.B = 2;\n\n            // Assert\n            Assert.Equal(\"foo\", controller.ViewData[\"A\"]);\n            Assert.Equal(2, controller.ViewData[\"B\"]);\n        }\n\n        public class ControllerBaseHelper : ControllerBase\n        {\n            protected override void Initialize(RequestContext requestContext)\n            {\n                PublicInitialize(requestContext);\n            }\n\n            public virtual void PublicInitialize(RequestContext requestContext)\n            {\n                base.Initialize(requestContext);\n            }\n\n            protected override void ExecuteCore()\n            {\n                PublicExecuteCore();\n            }\n\n            public virtual void PublicExecuteCore()\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class EmptyControllerBase : ControllerBase\n        {\n            public int NumTimesExecuteCoreCalled = 0;\n\n            protected override void ExecuteCore()\n            {\n                NumTimesExecuteCoreCalled++;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ControllerBuilderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Routing;\nusing System.Web.SessionState;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ControllerBuilderTest\n    {\n        [Fact]\n        public void ControllerBuilderReturnsDefaultControllerBuilderByDefault()\n        {\n            // Arrange\n            ControllerBuilder cb = new ControllerBuilder();\n\n            // Act\n            IControllerFactory cf = cb.GetControllerFactory();\n\n            // Assert\n            Assert.IsType<DefaultControllerFactory>(cf);\n        }\n\n        [Fact]\n        public void CreateControllerWithFactoryThatCannotBeCreatedThrows()\n        {\n            // Arrange\n            ControllerBuilder cb = new ControllerBuilder();\n            cb.SetControllerFactory(typeof(ControllerFactoryThrowsFromConstructor));\n\n            // Act\n            Assert.Throws<InvalidOperationException>(\n                delegate\n                {\n                    RequestContext reqContext = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData());\n                    reqContext.RouteData.Values[\"controller\"] = \"foo\";\n                    MvcHandlerWithNoVersionHeader handler = new MvcHandlerWithNoVersionHeader(reqContext)\n                    {\n                        ControllerBuilder = cb\n                    };\n                    handler.ProcessRequest(reqContext.HttpContext);\n                },\n                \"An error occurred when trying to create the IControllerFactory 'System.Web.Mvc.Test.ControllerBuilderTest+ControllerFactoryThrowsFromConstructor'. Make sure that the controller factory has a public parameterless constructor.\");\n        }\n\n        [Fact]\n        public void CreateControllerWithFactoryThatReturnsNullThrows()\n        {\n            // Arrange\n            ControllerBuilder cb = new ControllerBuilder();\n            cb.SetControllerFactory(typeof(ControllerFactoryReturnsNull));\n\n            // Act\n            Assert.Throws<InvalidOperationException>(\n                delegate\n                {\n                    RequestContext reqContext = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData());\n                    reqContext.RouteData.Values[\"controller\"] = \"boo\";\n                    MvcHandlerWithNoVersionHeader handler = new MvcHandlerWithNoVersionHeader(reqContext)\n                    {\n                        ControllerBuilder = cb\n                    };\n                    handler.ProcessRequest(reqContext.HttpContext);\n                },\n                \"The IControllerFactory 'System.Web.Mvc.Test.ControllerBuilderTest+ControllerFactoryReturnsNull' did not return a controller for the name 'boo'.\");\n        }\n\n        [Fact]\n        public void CreateControllerWithFactoryThatThrowsDoesNothingSpecial()\n        {\n            // Arrange\n            ControllerBuilder cb = new ControllerBuilder();\n            cb.SetControllerFactory(typeof(ControllerFactoryThrows));\n\n            // Act\n            Assert.Throws<Exception>(\n                delegate\n                {\n                    RequestContext reqContext = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData());\n                    reqContext.RouteData.Values[\"controller\"] = \"foo\";\n                    MvcHandlerWithNoVersionHeader handler = new MvcHandlerWithNoVersionHeader(reqContext)\n                    {\n                        ControllerBuilder = cb\n                    };\n                    handler.ProcessRequest(reqContext.HttpContext);\n                },\n                \"ControllerFactoryThrows\");\n        }\n\n        [Fact]\n        public void CreateControllerWithFactoryInstanceReturnsInstance()\n        {\n            // Arrange\n            ControllerBuilder cb = new ControllerBuilder();\n            DefaultControllerFactory factory = new DefaultControllerFactory();\n            cb.SetControllerFactory(factory);\n\n            // Act\n            IControllerFactory cf = cb.GetControllerFactory();\n\n            // Assert\n            Assert.Same(factory, cf);\n        }\n\n        [Fact]\n        public void CreateControllerWithFactoryTypeReturnsValidType()\n        {\n            // Arrange\n            ControllerBuilder cb = new ControllerBuilder();\n            cb.SetControllerFactory(typeof(MockControllerFactory));\n\n            // Act\n            IControllerFactory cf = cb.GetControllerFactory();\n\n            // Assert\n            Assert.IsType<MockControllerFactory>(cf);\n        }\n\n        [Fact]\n        public void SetControllerFactoryInstanceWithNullThrows()\n        {\n            ControllerBuilder cb = new ControllerBuilder();\n            Assert.ThrowsArgumentNull(\n                delegate { cb.SetControllerFactory((IControllerFactory)null); },\n                \"controllerFactory\");\n        }\n\n        [Fact]\n        public void SetControllerFactoryTypeWithNullThrows()\n        {\n            ControllerBuilder cb = new ControllerBuilder();\n            Assert.ThrowsArgumentNull(\n                delegate { cb.SetControllerFactory((Type)null); },\n                \"controllerFactoryType\");\n        }\n\n        [Fact]\n        public void SetControllerFactoryTypeWithNonFactoryTypeThrows()\n        {\n            ControllerBuilder cb = new ControllerBuilder();\n            Assert.Throws<ArgumentException>(\n                delegate { cb.SetControllerFactory(typeof(int)); },\n                \"The controller factory type 'System.Int32' must implement the IControllerFactory interface.\\r\\nParameter name: controllerFactoryType\");\n        }\n\n        [Fact]\n        public void DefaultControllerFactoryIsDefaultControllerFactory()\n        {\n            // Arrange\n            ControllerBuilder builder = new ControllerBuilder();\n\n            // Act\n            IControllerFactory returnedControllerFactory = builder.GetControllerFactory();\n\n            //Assert\n            Assert.Equal(typeof(DefaultControllerFactory), returnedControllerFactory.GetType());\n        }\n\n        [Fact]\n        public void SettingControllerFactoryReturnsSetFactory()\n        {\n            // Arrange\n            ControllerBuilder builder = new ControllerBuilder();\n            Mock<IControllerFactory> setFactory = new Mock<IControllerFactory>();\n\n            // Act\n            builder.SetControllerFactory(setFactory.Object);\n\n            // Assert\n            Assert.Same(setFactory.Object, builder.GetControllerFactory());\n        }\n\n        [Fact]\n        public void ControllerBuilderGetControllerFactoryDelegatesToResolver()\n        {\n            //Arrange\n            Mock<IControllerFactory> factory = new Mock<IControllerFactory>();\n            Resolver<IControllerFactory> resolver = new Resolver<IControllerFactory> { Current = factory.Object };\n            ControllerBuilder builder = new ControllerBuilder(resolver);\n\n            //Act\n            IControllerFactory result = builder.GetControllerFactory();\n\n            //Assert\n            Assert.Same(factory.Object, result);\n        }\n\n        public class ControllerFactoryThrowsFromConstructor : IControllerFactory\n        {\n            public ControllerFactoryThrowsFromConstructor()\n            {\n                throw new Exception(\"ControllerFactoryThrowsFromConstructor\");\n            }\n\n            public IController CreateController(RequestContext context, string controllerName)\n            {\n                return null;\n            }\n\n            public SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName)\n            {\n                return SessionStateBehavior.Default;\n            }\n\n            public void ReleaseController(IController controller)\n            {\n            }\n        }\n\n        public class ControllerFactoryReturnsNull : IControllerFactory\n        {\n            public IController CreateController(RequestContext context, string controllerName)\n            {\n                return null;\n            }\n\n            public SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName)\n            {\n                return SessionStateBehavior.Default;\n            }\n\n            public void ReleaseController(IController controller)\n            {\n            }\n        }\n\n        public class ControllerFactoryThrows : IControllerFactory\n        {\n            public IController CreateController(RequestContext context, string controllerName)\n            {\n                throw new Exception(\"ControllerFactoryThrows\");\n            }\n\n            public SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName)\n            {\n                return SessionStateBehavior.Default;\n            }\n\n            public void ReleaseController(IController controller)\n            {\n            }\n        }\n\n        public class MockControllerFactory : IControllerFactory\n        {\n            public IController CreateController(RequestContext context, string controllerName)\n            {\n                throw new NotImplementedException();\n            }\n\n            public SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName)\n            {\n                return SessionStateBehavior.Default;\n            }\n\n            public void ReleaseController(IController controller)\n            {\n            }\n        }\n\n        private sealed class MvcHandlerWithNoVersionHeader : MvcHandler\n        {\n            public MvcHandlerWithNoVersionHeader(RequestContext requestContext)\n                : base(requestContext)\n            {\n            }\n\n            protected internal override void AddVersionHeader(HttpContextBase httpContext)\n            {\n                // Don't try to set the version header for the unit tests\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ControllerContextTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Web.Routing;\nusing System.Web.TestUtil;\nusing System.Web.WebPages;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ControllerContextTest\n    {\n        [Fact]\n        public void ConstructorThrowsIfControllerIsNull()\n        {\n            // Arrange\n            RequestContext requestContext = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData());\n            Controller controller = null;\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ControllerContext(requestContext, controller); }, \"controller\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfRequestContextIsNull()\n        {\n            // Arrange\n            RequestContext requestContext = null;\n            Controller controller = new Mock<Controller>().Object;\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ControllerContext(requestContext, controller); }, \"requestContext\");\n        }\n\n        [Fact]\n        public void ConstructorWithHttpContextAndRouteData()\n        {\n            // Arrange\n            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;\n            RouteData routeData = new RouteData();\n            Controller controller = new Mock<Controller>().Object;\n\n            // Act\n            ControllerContext controllerContext = new ControllerContext(httpContext, routeData, controller);\n\n            // Assert\n            Assert.Equal(httpContext, controllerContext.HttpContext);\n            Assert.Equal(routeData, controllerContext.RouteData);\n            Assert.Equal(controller, controllerContext.Controller);\n        }\n\n        [Fact]\n        public void ControllerProperty()\n        {\n            // Arrange\n            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;\n            RouteData routeData = new RouteData();\n            Controller controller = new Mock<Controller>().Object;\n\n            // Act\n            ControllerContext controllerContext = new ControllerContext(httpContext, routeData, controller);\n\n            // Assert\n            Assert.Equal(controller, controllerContext.Controller);\n        }\n\n        [Fact]\n        public void CopyConstructorSetsProperties()\n        {\n            // Arrange\n            Mock<HttpContextBase> httpContext = new Mock<HttpContextBase>();\n            httpContext.Setup(c => c.Items).Returns(new Hashtable());\n\n            RequestContext requestContext = new RequestContext(httpContext.Object, new RouteData());\n            Controller controller = new Mock<Controller>().Object;\n            var displayMode = new DefaultDisplayMode(\"test\");\n\n            ControllerContext innerControllerContext = new ControllerContext(requestContext, controller);\n            innerControllerContext.DisplayMode = displayMode;\n\n            // Act\n            ControllerContext outerControllerContext = new SubclassedControllerContext(innerControllerContext);\n\n            // Assert\n            Assert.Equal(requestContext, outerControllerContext.RequestContext);\n            Assert.Equal(controller, outerControllerContext.Controller);\n\n            // We don't actually set DisplayMode but verify it is identical to the inner controller context.\n            Assert.Equal(displayMode, outerControllerContext.DisplayMode);\n        }\n\n        [Fact]\n        public void DisplayModeDelegatesToHttpContext()\n        {\n            // Arrange\n            IDisplayMode testDisplayMode = new DefaultDisplayMode(\"test\");\n            Mock<HttpContextBase> httpContext = new Mock<HttpContextBase>();\n            httpContext.Setup(c => c.Items).Returns(new Hashtable());\n            Controller controller = new Mock<Controller>().Object;\n            ControllerContext controllerContext = new ControllerContext(httpContext.Object, new RouteData(), controller);\n            ControllerContext controllerContextWithIdenticalContext = new ControllerContext(httpContext.Object, new RouteData(), controller);\n\n            // Act\n            controllerContext.DisplayMode = testDisplayMode;\n\n            // Assert\n            Assert.Same(testDisplayMode, controllerContext.DisplayMode);\n            Assert.Same(testDisplayMode, controllerContextWithIdenticalContext.DisplayMode);\n        }\n\n        [Fact]\n        public void CopyConstructorThrowsIfControllerContextIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new SubclassedControllerContext(null); }, \"controllerContext\");\n        }\n\n        [Fact]\n        public void HttpContextPropertyGetSetBehavior()\n        {\n            // Arrange\n            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;\n            ControllerContext controllerContext = new ControllerContext();\n\n            // Act & assert\n            MemberHelper.TestPropertyValue(controllerContext, \"HttpContext\", httpContext);\n        }\n\n        [Fact]\n        public void HttpContextPropertyReturnsEmptyHttpContextIfRequestContextNotPresent()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n\n            // Act\n            HttpContextBase httpContext = controllerContext.HttpContext;\n            HttpContextBase httpContext2 = controllerContext.HttpContext;\n\n            // Assert\n            Assert.NotNull(httpContext);\n            Assert.Equal(httpContext, httpContext2);\n        }\n\n        [Fact]\n        public void HttpContextPropertyReturnsRequestContextHttpContextIfPresent()\n        {\n            // Arrange\n            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;\n            RouteData routeData = new RouteData();\n            RequestContext requestContext = new RequestContext(httpContext, routeData);\n            Controller controller = new Mock<Controller>().Object;\n\n            // Act\n            ControllerContext controllerContext = new ControllerContext(requestContext, controller);\n\n            // Assert\n            Assert.Equal(httpContext, controllerContext.HttpContext);\n        }\n\n        [Fact]\n        public void RequestContextPropertyCreatesDummyHttpContextAndRouteDataIfNecessary()\n        {\n            // Arrange\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(c => c.HttpContext).Returns((HttpContextBase)null);\n            mockControllerContext.Setup(c => c.RouteData).Returns((RouteData)null);\n            ControllerContext controllerContext = mockControllerContext.Object;\n\n            // Act\n            RequestContext requestContext = controllerContext.RequestContext;\n            RequestContext requestContext2 = controllerContext.RequestContext;\n\n            // Assert\n            Assert.Equal(requestContext, requestContext2);\n            Assert.NotNull(requestContext.HttpContext);\n            Assert.NotNull(requestContext.RouteData);\n        }\n\n        [Fact]\n        public void RequestContextPropertyUsesExistingHttpContextAndRouteData()\n        {\n            // Arrange\n            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;\n            RouteData routeData = new RouteData();\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(c => c.HttpContext).Returns(httpContext);\n            mockControllerContext.Setup(c => c.RouteData).Returns(routeData);\n            ControllerContext controllerContext = mockControllerContext.Object;\n\n            // Act\n            RequestContext requestContext = controllerContext.RequestContext;\n            RequestContext requestContext2 = controllerContext.RequestContext;\n\n            // Assert\n            Assert.Equal(requestContext, requestContext2);\n            Assert.Equal(httpContext, requestContext.HttpContext);\n            Assert.Equal(routeData, requestContext.RouteData);\n        }\n\n        [Fact]\n        public void RouteDataPropertyGetSetBehavior()\n        {\n            // Arrange\n            RouteData routeData = new RouteData();\n            ControllerContext controllerContext = new ControllerContext();\n\n            // Act & assert\n            MemberHelper.TestPropertyValue(controllerContext, \"RouteData\", routeData);\n        }\n\n        [Fact]\n        public void RouteDataPropertyReturnsEmptyRouteDataIfRequestContextNotPresent()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n\n            // Act\n            RouteData routeData = controllerContext.RouteData;\n            RouteData routeData2 = controllerContext.RouteData;\n\n            // Assert\n            Assert.Equal(routeData, routeData2);\n            Assert.Empty(routeData.Values);\n        }\n\n        [Fact]\n        public void RouteDataPropertyReturnsRequestContextRouteDataIfPresent()\n        {\n            // Arrange\n            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;\n            RouteData routeData = new RouteData();\n            RequestContext requestContext = new RequestContext(httpContext, routeData);\n            Controller controller = new Mock<Controller>().Object;\n\n            // Act\n            ControllerContext controllerContext = new ControllerContext(requestContext, controller);\n\n            // Assert\n            Assert.Equal(routeData, controllerContext.RouteData);\n        }\n\n        [Fact]\n        public void IsChildActionReturnsFalseByDefault()\n        {\n            // Arrange\n            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;\n            RouteData routeData = new RouteData();\n            RequestContext requestContext = new RequestContext(httpContext, routeData);\n            Controller controller = new Mock<Controller>().Object;\n            ControllerContext controllerContext = new ControllerContext(requestContext, controller);\n\n            // Act\n            bool result = controllerContext.IsChildAction;\n\n            // Assert\n            Assert.False(result);\n        }\n\n        [Fact]\n        public void IsChildActionReturnsTrueWhenRouteDataTokenIsSet()\n        {\n            // Arrange\n            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;\n            ViewContext viewContext = new ViewContext();\n            RouteData routeData = new RouteData();\n            routeData.DataTokens[ControllerContext.ParentActionViewContextToken] = viewContext;\n            RequestContext requestContext = new RequestContext(httpContext, routeData);\n            Controller controller = new Mock<Controller>().Object;\n            ControllerContext controllerContext = new ControllerContext(requestContext, controller);\n\n            // Act\n            bool result = controllerContext.IsChildAction;\n\n            // Assert\n            Assert.True(result);\n            Assert.Same(viewContext, controllerContext.ParentActionViewContext);\n        }\n\n        public static ControllerContext CreateEmptyContext()\n        {\n            return new ControllerContext(new Mock<HttpContextBase>().Object, new RouteData(), new Mock<Controller>().Object);\n        }\n\n        private class SubclassedControllerContext : ControllerContext\n        {\n            public SubclassedControllerContext(ControllerContext controllerContext)\n                : base(controllerContext)\n            {\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ControllerDescriptorCacheTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ControllerDescriptorCacheTest\n    {\n        [Fact]\n        public void GetDescriptorCaches()\n        {\n            // Arrange\n            Type controllerType = typeof(object);\n            ControllerDescriptorCache cache = new ControllerDescriptorCache();\n\n            // Act\n            ControllerDescriptor descriptor1 = cache.GetDescriptor(controllerType, () => new ReflectedControllerDescriptor(controllerType));\n            ControllerDescriptor descriptor2 = cache.GetDescriptor(controllerType, () => new ReflectedControllerDescriptor(controllerType));\n\n            // Assert\n            Assert.Same(controllerType, descriptor1.ControllerType);\n            Assert.Same(descriptor1, descriptor2);\n        }\n\n        [Fact]\n        public void GetDescriptorWithArgumentCaches()\n        {\n            // Arrange\n            Type controllerType = typeof(object);\n            ControllerDescriptorCache cache = new ControllerDescriptorCache();\n            object argument = new object();\n\n            // Act\n            ControllerDescriptor descriptor1 = cache.GetDescriptor(\n                controllerType,\n                (object innerState) =>\n                {\n                    Assert.Same(argument, innerState);\n                    return new ReflectedControllerDescriptor(controllerType);\n                },\n                argument);\n            ControllerDescriptor descriptor2 = cache.GetDescriptor(\n                controllerType,\n                (object innerState) =>\n                {\n                    Assert.Same(argument, innerState);\n                    return new ReflectedControllerDescriptor(controllerType);\n                },\n                argument);\n\n            // Assert\n            Assert.Same(controllerType, descriptor1.ControllerType);\n            Assert.Same(descriptor1, descriptor2);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ControllerDescriptorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ControllerDescriptorTest\n    {\n        [Fact]\n        public void ControllerNamePropertyReturnsControllerTypeName()\n        {\n            // Arrange\n            ControllerDescriptor cd = GetControllerDescriptor(typeof(object));\n\n            // Act\n            string name = cd.ControllerName;\n\n            // Assert\n            Assert.Equal(\"Object\", name);\n        }\n\n        [Fact]\n        public void ControllerNamePropertyReturnsControllerTypeNameWithoutControllerSuffix()\n        {\n            // Arrange\n            Mock<Type> mockType = new Mock<Type>();\n            mockType.Setup(t => t.Name).Returns(\"somecontroller\");\n            ControllerDescriptor cd = GetControllerDescriptor(mockType.Object);\n\n            // Act\n            string name = cd.ControllerName;\n\n            // Assert\n            Assert.Equal(\"some\", name);\n        }\n\n        [Fact]\n        public void GetCustomAttributesReturnsEmptyArrayOfAttributeType()\n        {\n            // Arrange\n            ControllerDescriptor cd = GetControllerDescriptor();\n\n            // Act\n            ObsoleteAttribute[] attrs = (ObsoleteAttribute[])cd.GetCustomAttributes(typeof(ObsoleteAttribute), true);\n\n            // Assert\n            Assert.Empty(attrs);\n        }\n\n        [Fact]\n        public void GetCustomAttributesThrowsIfAttributeTypeIsNull()\n        {\n            // Arrange\n            ControllerDescriptor cd = GetControllerDescriptor();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { cd.GetCustomAttributes(null /* attributeType */, true); }, \"attributeType\");\n        }\n\n        [Fact]\n        public void GetCustomAttributesWithoutAttributeTypeCallsGetCustomAttributesWithAttributeType()\n        {\n            // Arrange\n            object[] expected = new object[0];\n            Mock<ControllerDescriptor> mockDescriptor = new Mock<ControllerDescriptor>() { CallBase = true };\n            mockDescriptor.Setup(d => d.GetCustomAttributes(typeof(object), true)).Returns(expected);\n            ControllerDescriptor cd = mockDescriptor.Object;\n\n            // Act\n            object[] returned = cd.GetCustomAttributes(true /* inherit */);\n\n            // Assert\n            Assert.Same(expected, returned);\n        }\n\n        [Fact]\n        public void GetFilterAttributes_CallsGetCustomAttributes()\n        {\n            // Arrange\n            var mockDescriptor = new Mock<ControllerDescriptor>() { CallBase = true };\n            mockDescriptor.Setup(d => d.GetCustomAttributes(typeof(FilterAttribute), true)).Returns(new object[] { new Mock<FilterAttribute>().Object }).Verifiable();\n\n            // Act\n            var result = mockDescriptor.Object.GetFilterAttributes(true).ToList();\n\n            // Assert\n            mockDescriptor.Verify();\n            Assert.Single(result);\n        }\n\n        [Fact]\n        public void IsDefinedReturnsFalse()\n        {\n            // Arrange\n            ControllerDescriptor cd = GetControllerDescriptor();\n\n            // Act\n            bool isDefined = cd.IsDefined(typeof(object), true);\n\n            // Assert\n            Assert.False(isDefined);\n        }\n\n        [Fact]\n        public void IsDefinedThrowsIfAttributeTypeIsNull()\n        {\n            // Arrange\n            ControllerDescriptor cd = GetControllerDescriptor();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { cd.IsDefined(null /* attributeType */, true); }, \"attributeType\");\n        }\n\n        private static ControllerDescriptor GetControllerDescriptor()\n        {\n            return GetControllerDescriptor(null);\n        }\n\n        private static ControllerDescriptor GetControllerDescriptor(Type controllerType)\n        {\n            Mock<ControllerDescriptor> mockDescriptor = new Mock<ControllerDescriptor>() { CallBase = true };\n            mockDescriptor.Setup(d => d.ControllerType).Returns(controllerType);\n            return mockDescriptor.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ControllerInstanceFilterProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ControllerInstanceFilterProviderTest\n    {\n        [Fact]\n        public void GetFiltersWithNullControllerReturnsEmptyCollection()\n        {\n            // Arrange\n            var context = new ControllerContext();\n            var descriptor = new Mock<ActionDescriptor>().Object;\n            var provider = new ControllerInstanceFilterProvider();\n\n            // Act\n            IEnumerable<Filter> result = provider.GetFilters(context, descriptor);\n\n            // Assert\n            Assert.Empty(result);\n        }\n\n        [Fact]\n        public void GetFiltersWithControllerReturnsWrappedController()\n        {\n            // Arrange\n            var controller = new Mock<ControllerBase>().Object;\n            var context = new ControllerContext { Controller = controller };\n            var descriptor = new Mock<ActionDescriptor>().Object;\n            var provider = new ControllerInstanceFilterProvider();\n\n            // Act\n            IEnumerable<Filter> result = provider.GetFilters(context, descriptor);\n\n            // Assert\n            Filter filter = result.Single();\n            Assert.Same(controller, filter.Instance);\n            Assert.Equal(Int32.MinValue, filter.Order);\n            Assert.Equal(FilterScope.First, filter.Scope);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ControllerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.ComponentModel.DataAnnotations;\nusing System.IO;\nusing System.Reflection;\nusing System.Security.Principal;\nusing System.Text;\nusing System.Web.Mvc.Async;\nusing System.Web.Profile;\nusing System.Web.Routing;\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\nusing Moq;\nusing Moq.Protected;\n\nnamespace System.Web.Mvc.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")]\n    public class ControllerTest\n    {\n        [Fact]\n        public void ActionInvokerProperty()\n        {\n            // Arrange\n            Controller controller = new EmptyController();\n\n            // Act & Assert\n            MemberHelper.TestPropertyWithDefaultInstance(controller, \"ActionInvoker\", new ControllerActionInvoker());\n        }\n\n        [Fact]\n        public void ContentWithContentString()\n        {\n            // Arrange\n            Controller controller = new EmptyController();\n            string content = \"Some content\";\n\n            // Act\n            ContentResult result = controller.Content(content);\n\n            // Assert\n            Assert.Equal(content, result.Content);\n        }\n\n        [Fact]\n        public void ContentWithContentStringAndContentType()\n        {\n            // Arrange\n            Controller controller = new EmptyController();\n            string content = \"Some content\";\n            string contentType = \"Some content type\";\n\n            // Act\n            ContentResult result = controller.Content(content, contentType);\n\n            // Assert\n            Assert.Equal(content, result.Content);\n            Assert.Equal(contentType, result.ContentType);\n        }\n\n        [Fact]\n        public void ContentWithContentStringAndContentTypeAndEncoding()\n        {\n            // Arrange\n            Controller controller = new EmptyController();\n            string content = \"Some content\";\n            string contentType = \"Some content type\";\n            Encoding contentEncoding = Encoding.UTF8;\n\n            // Act\n            ContentResult result = controller.Content(content, contentType, contentEncoding);\n\n            // Assert\n            Assert.Equal(content, result.Content);\n            Assert.Equal(contentType, result.ContentType);\n            Assert.Same(contentEncoding, result.ContentEncoding);\n        }\n\n        [Fact]\n        public void ContextProperty()\n        {\n            var controller = new EmptyController();\n            MemberHelper.TestPropertyValue(controller, \"ControllerContext\", new Mock<ControllerContext>().Object);\n        }\n\n        [Fact]\n        public void HttpContextProperty()\n        {\n            var c = new EmptyController();\n            Assert.Null(c.HttpContext);\n\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(cc => cc.Controller).Returns(c);\n            mockControllerContext.Setup(cc => cc.HttpContext).Returns(mockHttpContext.Object);\n\n            c.ControllerContext = mockControllerContext.Object;\n            Assert.Equal(mockHttpContext.Object, c.HttpContext);\n        }\n\n        [Fact]\n        public void HttpNotFound()\n        {\n            // Arrange\n            var c = new EmptyController();\n\n            // Act\n            HttpNotFoundResult result = c.HttpNotFound();\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Null(result.StatusDescription);\n            Assert.Equal(404, result.StatusCode);\n        }\n\n        [Fact]\n        public void HttpNotFoundWithNullStatusDescription()\n        {\n            // Arrange\n            var c = new EmptyController();\n\n            // Act\n            HttpNotFoundResult result = c.HttpNotFound(statusDescription: null);\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Null(result.StatusDescription);\n            Assert.Equal(404, result.StatusCode);\n        }\n\n        [Fact]\n        public void HttpNotFoundWithStatusDescription()\n        {\n            // Arrange\n            var c = new EmptyController();\n\n            // Act\n            HttpNotFoundResult result = c.HttpNotFound(statusDescription: \"I lost it\");\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Equal(\"I lost it\", result.StatusDescription);\n            Assert.Equal(404, result.StatusCode);\n        }\n\n        [Fact]\n        public void ModelStateProperty()\n        {\n            // Arrange\n            Controller controller = new EmptyController();\n\n            // Act & assert\n            Assert.Same(controller.ViewData.ModelState, controller.ModelState);\n        }\n\n        [Fact]\n        public void ProfileProperty()\n        {\n            var c = new EmptyController();\n            Assert.Null(c.Profile);\n\n            Mock<ProfileBase> mockProfile = new Mock<ProfileBase>();\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(cc => cc.Controller).Returns(c);\n            mockControllerContext.Setup(cc => cc.HttpContext.Profile).Returns(mockProfile.Object);\n\n            c.ControllerContext = mockControllerContext.Object;\n            Assert.Equal(mockProfile.Object, c.Profile);\n        }\n\n        [Fact]\n        public void RequestProperty()\n        {\n            var c = new EmptyController();\n            Assert.Null(c.Request);\n\n            Mock<HttpRequestBase> mockHttpRequest = new Mock<HttpRequestBase>();\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(cc => cc.Controller).Returns(c);\n            mockControllerContext.Setup(cc => cc.HttpContext.Request).Returns(mockHttpRequest.Object);\n\n            c.ControllerContext = mockControllerContext.Object;\n            Assert.Equal(mockHttpRequest.Object, c.Request);\n        }\n\n        [Fact]\n        public void ResponseProperty()\n        {\n            var c = new EmptyController();\n            Assert.Null(c.Request);\n\n            Mock<HttpResponseBase> mockHttpResponse = new Mock<HttpResponseBase>();\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(cc => cc.Controller).Returns(c);\n            mockControllerContext.Setup(cc => cc.HttpContext.Response).Returns(mockHttpResponse.Object);\n\n            c.ControllerContext = mockControllerContext.Object;\n            Assert.Equal(mockHttpResponse.Object, c.Response);\n        }\n\n        [Fact]\n        public void ServerProperty()\n        {\n            var c = new EmptyController();\n            Assert.Null(c.Request);\n\n            Mock<HttpServerUtilityBase> mockServerUtility = new Mock<HttpServerUtilityBase>();\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(cc => cc.Controller).Returns(c);\n            mockControllerContext.Setup(cc => cc.HttpContext.Server).Returns(mockServerUtility.Object);\n\n            c.ControllerContext = mockControllerContext.Object;\n            Assert.Equal(mockServerUtility.Object, c.Server);\n        }\n\n        [Fact]\n        public void SessionProperty()\n        {\n            var c = new EmptyController();\n            Assert.Null(c.Request);\n\n            Mock<HttpSessionStateBase> mockSessionState = new Mock<HttpSessionStateBase>();\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(cc => cc.Controller).Returns(c);\n            mockControllerContext.Setup(cc => cc.HttpContext.Session).Returns(mockSessionState.Object);\n\n            c.ControllerContext = mockControllerContext.Object;\n            Assert.Same(mockSessionState.Object, c.Session);\n        }\n\n        [Fact]\n        public void UrlProperty()\n        {\n            // Arrange\n            EmptyController controller = new EmptyController();\n            RequestContext requestContext = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData());\n\n            // Act\n            controller.PublicInitialize(requestContext);\n\n            // Assert\n            Assert.NotNull(controller.Url);\n        }\n\n        [Fact]\n        public void UserProperty()\n        {\n            var c = new EmptyController();\n            Assert.Null(c.Request);\n\n            Mock<IPrincipal> mockUser = new Mock<IPrincipal>();\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(cc => cc.Controller).Returns(c);\n            mockControllerContext.Setup(cc => cc.HttpContext.User).Returns(mockUser.Object);\n\n            c.ControllerContext = mockControllerContext.Object;\n            Assert.Equal(mockUser.Object, c.User);\n        }\n\n        [Fact]\n        public void RouteDataProperty()\n        {\n            var c = new EmptyController();\n            Assert.Null(c.Request);\n\n            RouteData rd = new RouteData();\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(cc => cc.Controller).Returns(c);\n            mockControllerContext.Setup(cc => cc.RouteData).Returns(rd);\n\n            c.ControllerContext = mockControllerContext.Object;\n            Assert.Equal(rd, c.RouteData);\n        }\n\n        [Fact]\n        public void ControllerMethodsDoNotHaveNonActionAttribute()\n        {\n            var methods = typeof(Controller).GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);\n            foreach (var method in methods)\n            {\n                var attrs = method.GetCustomAttributes(typeof(NonActionAttribute), true /* inherit */);\n                Assert.True(attrs.Length == 0, \"Methods on the Controller class should not be marked [NonAction]: \" + method);\n            }\n        }\n\n        [Fact]\n        public void DisposeCallsProtectedDisposingMethod()\n        {\n            // Arrange\n            Mock<Controller> mockController = new Mock<Controller>();\n            mockController.Protected().Setup(\"Dispose\", exactParameterMatch: true, args: true).Verifiable();\n            Controller controller = mockController.Object;\n\n            // Act\n            controller.Dispose();\n\n            // Assert\n            mockController.Verify();\n        }\n\n        [Fact]\n        public void ExecuteWithUnknownAction()\n        {\n            // Arrange\n            UnknownActionController controller = new UnknownActionController();\n            // We need a provider since Controller.Execute is called\n            controller.TempDataProvider = new EmptyTempDataProvider();\n            ControllerContext context = GetControllerContext(\"Foo\");\n\n            Mock<IActionInvoker> mockInvoker = new Mock<IActionInvoker>();\n            mockInvoker.Setup(o => o.InvokeAction(context, \"Foo\")).Returns(false);\n            controller.ActionInvoker = mockInvoker.Object;\n\n            // Act\n            ((IController)controller).Execute(context.RequestContext);\n\n            // Assert\n            Assert.True(controller.WasCalled);\n        }\n\n        [Fact]\n        public void FileWithContents()\n        {\n            // Arrange\n            EmptyController controller = new EmptyController();\n            byte[] fileContents = new byte[0];\n\n            // Act\n            FileContentResult result = controller.File(fileContents, \"someContentType\");\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Same(fileContents, result.FileContents);\n            Assert.Equal(\"someContentType\", result.ContentType);\n            Assert.Equal(String.Empty, result.FileDownloadName);\n        }\n\n        [Fact]\n        public void FileWithContentsAndFileDownloadName()\n        {\n            // Arrange\n            EmptyController controller = new EmptyController();\n            byte[] fileContents = new byte[0];\n\n            // Act\n            FileContentResult result = controller.File(fileContents, \"someContentType\", \"someDownloadName\");\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Same(fileContents, result.FileContents);\n            Assert.Equal(\"someContentType\", result.ContentType);\n            Assert.Equal(\"someDownloadName\", result.FileDownloadName);\n        }\n\n        [Fact]\n        public void FileWithPath()\n        {\n            // Arrange\n            EmptyController controller = new EmptyController();\n\n            // Act\n            FilePathResult result = controller.File(\"somePath\", \"someContentType\");\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Equal(\"somePath\", result.FileName);\n            Assert.Equal(\"someContentType\", result.ContentType);\n            Assert.Equal(String.Empty, result.FileDownloadName);\n        }\n\n        [Fact]\n        public void FileWithPathAndFileDownloadName()\n        {\n            // Arrange\n            EmptyController controller = new EmptyController();\n\n            // Act\n            FilePathResult result = controller.File(\"somePath\", \"someContentType\", \"someDownloadName\");\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Equal(\"somePath\", result.FileName);\n            Assert.Equal(\"someContentType\", result.ContentType);\n            Assert.Equal(\"someDownloadName\", result.FileDownloadName);\n        }\n\n        [Fact]\n        public void FileWithStream()\n        {\n            // Arrange\n            EmptyController controller = new EmptyController();\n            Stream fileStream = Stream.Null;\n\n            // Act\n            FileStreamResult result = controller.File(fileStream, \"someContentType\");\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Same(fileStream, result.FileStream);\n            Assert.Equal(\"someContentType\", result.ContentType);\n            Assert.Equal(String.Empty, result.FileDownloadName);\n        }\n\n        [Fact]\n        public void FileWithStreamAndFileDownloadName()\n        {\n            // Arrange\n            EmptyController controller = new EmptyController();\n            Stream fileStream = Stream.Null;\n\n            // Act\n            FileStreamResult result = controller.File(fileStream, \"someContentType\", \"someDownloadName\");\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Same(fileStream, result.FileStream);\n            Assert.Equal(\"someContentType\", result.ContentType);\n            Assert.Equal(\"someDownloadName\", result.FileDownloadName);\n        }\n\n        [Fact]\n        public void HandleUnknownActionThrows()\n        {\n            var controller = new EmptyController();\n            Assert.Throws<HttpException>(\n                delegate { controller.HandleUnknownAction(\"UnknownAction\"); },\n                \"A public action method 'UnknownAction' was not found on controller 'System.Web.Mvc.Test.ControllerTest+EmptyController'.\");\n        }\n\n        /// <summary>\n        /// This is a scenario for attribute routing, we don't have a single action nameat this point\n        /// </summary>\n        [Fact]\n        public void HandleUnknownAction_NoActionName_Throws()\n        {\n            var controller = new EmptyController();\n            Assert.Throws<HttpException>(\n                delegate { controller.HandleUnknownAction(null); },\n                \"No matching action was found on controller 'System.Web.Mvc.Test.ControllerTest+EmptyController'. \" +\n                \"This can happen when a controller uses RouteAttribute for routing, but no action on that controller matches the request.\");\n        }\n\n        [Fact]\n        public void JavaScript()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n            string script = \"alert('foo');\";\n\n            // Act\n            JavaScriptResult result = controller.JavaScript(script);\n\n            // Assert\n            Assert.Equal(script, result.Script);\n        }\n\n        [Fact]\n        public void PartialView()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n\n            // Act\n            PartialViewResult result = controller.PartialView();\n\n            // Assert\n            Assert.Same(controller.TempData, result.TempData);\n            Assert.Same(controller.ViewData, result.ViewData);\n            Assert.Same(ViewEngines.Engines, result.ViewEngineCollection);\n        }\n\n        [Fact]\n        public void PartialView_Model()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n            object model = new object();\n\n            // Act\n            PartialViewResult result = controller.PartialView(model);\n\n            // Assert\n            Assert.Same(model, result.ViewData.Model);\n            Assert.Same(controller.TempData, result.TempData);\n            Assert.Same(controller.ViewData, result.ViewData);\n        }\n\n        [Fact]\n        public void PartialView_ViewName()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n\n            // Act\n            PartialViewResult result = controller.PartialView(\"Some partial view\");\n\n            // Assert\n            Assert.Equal(\"Some partial view\", result.ViewName);\n            Assert.Same(controller.TempData, result.TempData);\n            Assert.Same(controller.ViewData, result.ViewData);\n        }\n\n        [Fact]\n        public void PartialView_ViewName_Model()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n            object model = new object();\n\n            // Act\n            PartialViewResult result = controller.PartialView(\"Some partial view\", model);\n\n            // Assert\n            Assert.Equal(\"Some partial view\", result.ViewName);\n            Assert.Same(model, result.ViewData.Model);\n            Assert.Same(controller.TempData, result.TempData);\n            Assert.Same(controller.ViewData, result.ViewData);\n        }\n\n        [Fact]\n        public void PartialView_ViewEngineCollection()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n            ViewEngineCollection viewEngines = new ViewEngineCollection();\n            controller.ViewEngineCollection = viewEngines;\n\n            // Act\n            PartialViewResult result = controller.PartialView();\n\n            // Assert\n            Assert.Same(viewEngines, result.ViewEngineCollection);\n        }\n\n        [Fact]\n        public void RedirectToActionClonesRouteValueDictionary()\n        {\n            // The RedirectToAction() method should clone the provided dictionary, then operate on the clone.\n            // The original dictionary should remain unmodified throughout the helper's execution.\n\n            // Arrange\n            Controller controller = GetEmptyController();\n            RouteValueDictionary values = new RouteValueDictionary(new { Action = \"SomeAction\", Controller = \"SomeController\" });\n\n            // Act\n            controller.RedirectToAction(\"SomeOtherAction\", \"SomeOtherController\", values);\n\n            // Assert\n            Assert.Equal(2, values.Count);\n            Assert.Equal(\"SomeAction\", values[\"action\"]);\n            Assert.Equal(\"SomeController\", values[\"controller\"]);\n        }\n\n        [Fact]\n        public void RedirectToActionOverwritesActionDictionaryKey()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n            object values = new { Action = \"SomeAction\" };\n\n            // Act\n            RedirectToRouteResult result = controller.RedirectToAction(\"SomeOtherAction\", values);\n            RouteValueDictionary newValues = result.RouteValues;\n\n            // Assert\n            Assert.Equal(\"SomeOtherAction\", newValues[\"action\"]);\n        }\n\n        [Fact]\n        public void RedirectToActionOverwritesControllerDictionaryKeyIfSpecified()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n            object values = new { Action = \"SomeAction\", Controller = \"SomeController\" };\n\n            // Act\n            RedirectToRouteResult result = controller.RedirectToAction(\"SomeOtherAction\", \"SomeOtherController\", values);\n            RouteValueDictionary newValues = result.RouteValues;\n\n            // Assert\n            Assert.Equal(\"SomeOtherController\", newValues[\"controller\"]);\n        }\n\n        [Fact]\n        public void RedirectToActionPreservesControllerDictionaryKeyIfNotSpecified()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n            object values = new { Controller = \"SomeController\" };\n\n            // Act\n            RedirectToRouteResult result = controller.RedirectToAction(\"SomeOtherAction\", values);\n            RouteValueDictionary newValues = result.RouteValues;\n\n            // Assert\n            Assert.Equal(\"SomeController\", newValues[\"controller\"]);\n        }\n\n        [Fact]\n        public void RedirectToActionWithActionName()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n\n            // Act\n            RedirectToRouteResult result = controller.RedirectToAction(\"SomeOtherAction\");\n\n            // Assert\n            Assert.Equal(\"\", result.RouteName);\n            Assert.Equal(\"SomeOtherAction\", result.RouteValues[\"action\"]);\n            Assert.False(result.Permanent);\n        }\n\n        [Fact]\n        public void RedirectToActionWithActionNameAndControllerName()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n\n            // Act\n            RedirectToRouteResult result = controller.RedirectToAction(\"SomeOtherAction\", \"SomeOtherController\");\n\n            // Assert\n            Assert.Equal(\"\", result.RouteName);\n            Assert.Equal(\"SomeOtherAction\", result.RouteValues[\"action\"]);\n            Assert.Equal(\"SomeOtherController\", result.RouteValues[\"controller\"]);\n            Assert.False(result.Permanent);\n        }\n\n        [Fact]\n        public void RedirectToActionWithActionNameAndControllerNameAndValuesDictionary()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n            RouteValueDictionary values = new RouteValueDictionary(new { Foo = \"SomeFoo\" });\n\n            // Act\n            RedirectToRouteResult result = controller.RedirectToAction(\"SomeOtherAction\", \"SomeOtherController\", values);\n\n            // Assert\n            Assert.Equal(\"\", result.RouteName);\n            Assert.Equal(\"SomeOtherAction\", result.RouteValues[\"action\"]);\n            Assert.Equal(\"SomeOtherController\", result.RouteValues[\"controller\"]);\n            Assert.Equal(\"SomeFoo\", result.RouteValues[\"foo\"]);\n            Assert.False(result.Permanent);\n        }\n\n        [Fact]\n        public void RedirectToActionWithActionNameAndControllerNameAndValuesObject()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n            object values = new { Foo = \"SomeFoo\" };\n\n            // Act\n            RedirectToRouteResult result = controller.RedirectToAction(\"SomeOtherAction\", \"SomeOtherController\", values);\n\n            // Assert\n            Assert.Equal(\"\", result.RouteName);\n            Assert.Equal(\"SomeOtherAction\", result.RouteValues[\"action\"]);\n            Assert.Equal(\"SomeOtherController\", result.RouteValues[\"controller\"]);\n            Assert.Equal(\"SomeFoo\", result.RouteValues[\"foo\"]);\n            Assert.False(result.Permanent);\n        }\n\n        [Fact]\n        public void RedirectToActionSelectsCurrentControllerByDefault()\n        {\n            // Arrange\n            TestRouteController controller = new TestRouteController();\n            controller.ControllerContext = GetControllerContext(\"SomeAction\", \"TestRoute\");\n\n            // Act\n            RedirectToRouteResult route = controller.Index() as RedirectToRouteResult;\n\n            // Assert\n            Assert.Equal(\"SomeAction\", route.RouteValues[\"action\"]);\n            Assert.Equal(\"TestRoute\", route.RouteValues[\"controller\"]);\n        }\n\n        [Fact]\n        public void RedirectToActionDictionaryOverridesDefaultControllerName()\n        {\n            // Arrange\n            TestRouteController controller = new TestRouteController();\n            object values = new { controller = \"SomeOtherController\" };\n            controller.ControllerContext = GetControllerContext(\"SomeAction\", \"TestRoute\");\n\n            // Act\n            RedirectToRouteResult route = controller.RedirectToAction(\"SomeOtherAction\", values);\n\n            // Assert\n            Assert.Equal(\"SomeOtherAction\", route.RouteValues[\"action\"]);\n            Assert.Equal(\"SomeOtherController\", route.RouteValues[\"controller\"]);\n        }\n\n        [Fact]\n        public void RedirectToActionSimpleOverridesCallLegacyMethod()\n        {\n            // The simple overrides need to call RedirectToAction(string, string, RouteValueDictionary) to maintain backwards compat\n\n            // Arrange\n            int invocationCount = 0;\n            Mock<Controller> controllerMock = new Mock<Controller>();\n            controllerMock.Setup(c => c.RedirectToAction(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<RouteValueDictionary>())).Callback(() => { invocationCount++; });\n\n            Controller controller = controllerMock.Object;\n\n            // Act\n            controller.RedirectToAction(\"SomeAction\");\n            controller.RedirectToAction(\"SomeAction\", (object)null);\n            controller.RedirectToAction(\"SomeAction\", (RouteValueDictionary)null);\n            controller.RedirectToAction(\"SomeAction\", \"SomeController\");\n            controller.RedirectToAction(\"SomeAction\", \"SomeController\", (object)null);\n\n            // Assert\n            Assert.Equal(5, invocationCount);\n        }\n\n        [Fact]\n        public void RedirectToActionWithActionNameAndValuesDictionary()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n            RouteValueDictionary values = new RouteValueDictionary(new { Foo = \"SomeFoo\" });\n\n            // Act\n            RedirectToRouteResult result = controller.RedirectToAction(\"SomeOtherAction\", values);\n\n            // Assert\n            Assert.Equal(\"\", result.RouteName);\n            Assert.Equal(\"SomeOtherAction\", result.RouteValues[\"action\"]);\n            Assert.Equal(\"SomeFoo\", result.RouteValues[\"foo\"]);\n            Assert.False(result.Permanent);\n        }\n\n        [Fact]\n        public void RedirectToActionWithActionNameAndValuesObject()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n            object values = new { Foo = \"SomeFoo\" };\n\n            // Act\n            RedirectToRouteResult result = controller.RedirectToAction(\"SomeOtherAction\", values);\n\n            // Assert\n            Assert.Equal(\"\", result.RouteName);\n            Assert.Equal(\"SomeOtherAction\", result.RouteValues[\"action\"]);\n            Assert.Equal(\"SomeFoo\", result.RouteValues[\"foo\"]);\n            Assert.False(result.Permanent);\n        }\n\n        [Fact]\n        public void RedirectToActionWithNullRouteValueDictionary()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n\n            // Act\n            RedirectToRouteResult result = controller.RedirectToAction(\"SomeOtherAction\", (RouteValueDictionary)null);\n            RouteValueDictionary newValues = result.RouteValues;\n\n            // Assert\n            Assert.Single(newValues);\n            Assert.Equal(\"SomeOtherAction\", newValues[\"action\"]);\n            Assert.False(result.Permanent);\n        }\n\n        [Fact]\n        public void RedirectToActionPermanent()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n\n            // Act\n            RedirectToRouteResult result = controller.RedirectToActionPermanent(\"SomeOtherAction\");\n\n            // Assert\n            Assert.True(result.Permanent);\n            Assert.Equal(\"SomeOtherAction\", result.RouteValues[\"action\"]);\n            Assert.Null(result.RouteValues[\"controller\"]);\n        }\n\n        [Fact]\n        public void RedirectToActionPermanentWithObjectDictionary()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n\n            // Act\n            RedirectToRouteResult result = controller.RedirectToActionPermanent(\"SomeOtherAction\", controllerName: \"SomeController\", routeValues: new { foo = \"bar\" });\n\n            // Assert\n            Assert.True(result.Permanent);\n            Assert.Equal(\"SomeOtherAction\", result.RouteValues[\"action\"]);\n            Assert.Equal(\"bar\", result.RouteValues[\"foo\"]);\n            Assert.Equal(\"SomeController\", result.RouteValues[\"controller\"]);\n        }\n\n        [Fact]\n        public void RedirectToActionPermanentWithRouteValueDictionary()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n\n            // Act\n            RedirectToRouteResult result = controller.RedirectToActionPermanent(\"SomeOtherAction\", routeValues: new RouteValueDictionary(new { foo = \"bar\" }));\n\n            // Assert\n            Assert.True(result.Permanent);\n            Assert.Equal(\"SomeOtherAction\", result.RouteValues[\"action\"]);\n            Assert.Equal(\"bar\", result.RouteValues[\"foo\"]);\n        }\n\n        [Fact]\n        public void RedirectToRouteSimpleOverridesCallLegacyMethod()\n        {\n            // The simple overrides need to call RedirectToRoute(string, RouteValueDictionary) to maintain backwards compat\n\n            // Arrange\n            int invocationCount = 0;\n            Mock<Controller> controllerMock = new Mock<Controller>();\n            controllerMock.Setup(c => c.RedirectToRoute(It.IsAny<string>(), It.IsAny<RouteValueDictionary>())).Callback(() => { invocationCount++; });\n\n            Controller controller = controllerMock.Object;\n\n            // Act\n            controller.RedirectToRoute(\"SomeRoute\");\n            controller.RedirectToRoute(\"SomeRoute\", (object)null);\n            controller.RedirectToRoute((object)null);\n            controller.RedirectToRoute((RouteValueDictionary)null);\n\n            // Assert\n            Assert.Equal(4, invocationCount);\n        }\n\n        [Fact]\n        public void RedirectToRouteWithNullRouteValueDictionary()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n\n            // Act\n            RedirectToRouteResult result = controller.RedirectToRoute((RouteValueDictionary)null);\n\n            // Assert\n            Assert.Empty(result.RouteValues);\n            Assert.False(result.Permanent);\n        }\n\n        [Fact]\n        public void RedirectToRouteWithObjectDictionary()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n            var values = new { Foo = \"MyFoo\" };\n\n            // Act\n            RedirectToRouteResult result = controller.RedirectToRoute(values);\n\n            // Assert\n            Assert.Single(result.RouteValues);\n            Assert.Equal(\"MyFoo\", result.RouteValues[\"Foo\"]);\n            Assert.False(result.Permanent);\n        }\n\n        [Fact]\n        public void RedirectToRouteWithRouteValueDictionary()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n            RouteValueDictionary values = new RouteValueDictionary() { { \"Foo\", \"MyFoo\" } };\n\n            // Act\n            RedirectToRouteResult result = controller.RedirectToRoute(values);\n\n            // Assert\n            Assert.Single(result.RouteValues);\n            Assert.Equal(\"MyFoo\", result.RouteValues[\"Foo\"]);\n            Assert.NotSame(values, result.RouteValues);\n            Assert.False(result.Permanent);\n        }\n\n        [Fact]\n        public void RedirectToRouteWithName()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n\n            // Act\n            RedirectToRouteResult result = controller.RedirectToRoute(\"foo\");\n\n            // Assert\n            Assert.Empty(result.RouteValues);\n            Assert.Equal(\"foo\", result.RouteName);\n            Assert.False(result.Permanent);\n        }\n\n        [Fact]\n        public void RedirectToRouteWithNameAndNullRouteValueDictionary()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n\n            // Act\n            RedirectToRouteResult result = controller.RedirectToRoute(\"foo\", (RouteValueDictionary)null);\n\n            // Assert\n            Assert.Empty(result.RouteValues);\n            Assert.Equal(\"foo\", result.RouteName);\n            Assert.False(result.Permanent);\n        }\n\n        [Fact]\n        public void RedirectToRouteWithNullNameAndNullRouteValueDictionary()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n\n            // Act\n            RedirectToRouteResult result = controller.RedirectToRoute(null, (RouteValueDictionary)null);\n\n            // Assert\n            Assert.Empty(result.RouteValues);\n            Assert.Equal(String.Empty, result.RouteName);\n            Assert.False(result.Permanent);\n        }\n\n        [Fact]\n        public void RedirectToRouteWithNameAndObjectDictionary()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n            var values = new { Foo = \"MyFoo\" };\n\n            // Act\n            RedirectToRouteResult result = controller.RedirectToRoute(\"foo\", values);\n\n            // Assert\n            Assert.Single(result.RouteValues);\n            Assert.Equal(\"MyFoo\", result.RouteValues[\"Foo\"]);\n            Assert.Equal(\"foo\", result.RouteName);\n            Assert.False(result.Permanent);\n        }\n\n        [Fact]\n        public void RedirectToRouteWithNameAndRouteValueDictionary()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n            RouteValueDictionary values = new RouteValueDictionary() { { \"Foo\", \"MyFoo\" } };\n\n            // Act\n            RedirectToRouteResult result = controller.RedirectToRoute(\"foo\", values);\n\n            // Assert\n            Assert.Single(result.RouteValues);\n            Assert.Equal(\"MyFoo\", result.RouteValues[\"Foo\"]);\n            Assert.NotSame(values, result.RouteValues);\n            Assert.Equal(\"foo\", result.RouteName);\n            Assert.False(result.Permanent);\n        }\n\n        [Fact]\n        public void RedirectToRoutePermanentWithObjectDictionary()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n\n            // Act\n            RedirectToRouteResult result = controller.RedirectToRoutePermanent(routeValues: new { Foo = \"Bar\" });\n\n            // Assert\n            Assert.True(result.Permanent);\n            Assert.Equal(\"Bar\", result.RouteValues[\"Foo\"]);\n        }\n\n        [Fact]\n        public void RedirectToRoutePermanentWithRouteValueDictionary()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n\n            // Act\n            RedirectToRouteResult result = controller.RedirectToRoutePermanent(routeValues: new RouteValueDictionary(new { Foo = \"Bar\" }));\n\n            // Assert\n            Assert.True(result.Permanent);\n            Assert.Equal(\"Bar\", result.RouteValues[\"Foo\"]);\n        }\n\n        [Fact]\n        public void RedirectReturnsCorrectActionResult()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n\n            // Act & Assert\n            var result = controller.Redirect(\"http://www.contoso.com/\");\n\n            // Assert\n            Assert.Equal(\"http://www.contoso.com/\", result.Url);\n            Assert.False(result.Permanent);\n        }\n\n        [Fact]\n        public void RedirectPermanentReturnsCorrectActionResult()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n\n            // Act & Assert\n            var result = controller.RedirectPermanent(\"http://www.contoso.com/\");\n\n            // Assert\n            Assert.Equal(\"http://www.contoso.com/\", result.Url);\n            Assert.True(result.Permanent);\n        }\n\n        [Fact]\n        public void RedirectWithEmptyUrlThrows()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { controller.Redirect(String.Empty); },\n                \"url\");\n        }\n\n        [Fact]\n        public void RedirectPermanentWithEmptyUrlThrows()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { controller.RedirectPermanent(String.Empty); },\n                \"url\");\n        }\n\n        [Fact]\n        public void RedirectWithNullUrlThrows()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { controller.Redirect(url: null); },\n                \"url\");\n        }\n\n        [Fact]\n        public void RedirectPermanentWithNullUrlThrows()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { controller.RedirectPermanent(url: null); },\n                \"url\");\n        }\n\n        [Fact]\n        public void View()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n\n            // Act\n            ViewResult result = controller.View();\n\n            // Assert\n            Assert.Same(controller.ViewData, result.ViewData);\n            Assert.Same(controller.TempData, result.TempData);\n            Assert.Same(ViewEngines.Engines, result.ViewEngineCollection);\n        }\n\n        [Fact]\n        public void View_Model()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n            object viewItem = new object();\n\n            // Act\n            ViewResult result = controller.View(viewItem);\n\n            // Assert\n            Assert.Same(viewItem, result.ViewData.Model);\n            Assert.Same(controller.TempData, result.TempData);\n        }\n\n        [Fact]\n        public void View_ViewName()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n\n            // Act\n            ViewResult result = controller.View(\"Foo\");\n\n            // Assert\n            Assert.Equal(\"Foo\", result.ViewName);\n            Assert.Same(controller.ViewData, result.ViewData);\n            Assert.Same(controller.TempData, result.TempData);\n        }\n\n        [Fact]\n        public void View_ViewName_Model()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n            object viewItem = new object();\n\n            // Act\n            ViewResult result = controller.View(\"Foo\", viewItem);\n\n            // Assert\n            Assert.Equal(\"Foo\", result.ViewName);\n            Assert.Same(viewItem, result.ViewData.Model);\n            Assert.Same(controller.TempData, result.TempData);\n        }\n\n        [Fact]\n        public void View_ViewName_MasterViewName()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n\n            // Act\n            ViewResult result = controller.View(\"Foo\", \"Bar\");\n\n            // Assert\n            Assert.Equal(\"Foo\", result.ViewName);\n            Assert.Equal(\"Bar\", result.MasterName);\n            Assert.Same(controller.ViewData, result.ViewData);\n            Assert.Same(controller.TempData, result.TempData);\n        }\n\n        [Fact]\n        public void View_ViewName_MasterViewName_Model()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n            object viewItem = new object();\n\n            // Act\n            ViewResult result = controller.View(\"Foo\", \"Bar\", viewItem);\n\n            // Assert\n            Assert.Equal(\"Foo\", result.ViewName);\n            Assert.Equal(\"Bar\", result.MasterName);\n            Assert.Same(viewItem, result.ViewData.Model);\n            Assert.Same(controller.TempData, result.TempData);\n        }\n\n        [Fact]\n        public void View_View()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n            IView view = new Mock<IView>().Object;\n\n            // Act\n            ViewResult result = controller.View(view);\n\n            // Assert\n            Assert.Same(result.View, view);\n            Assert.Same(controller.ViewData, result.ViewData);\n            Assert.Same(controller.TempData, result.TempData);\n        }\n\n        [Fact]\n        public void View_View_Model()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n            IView view = new Mock<IView>().Object;\n            object model = new object();\n\n            // Act\n            ViewResult result = controller.View(view, model);\n\n            // Assert\n            Assert.Same(result.View, view);\n            Assert.Same(controller.ViewData, result.ViewData);\n            Assert.Same(controller.TempData, result.TempData);\n            Assert.Same(model, result.ViewData.Model);\n        }\n\n        [Fact]\n        public void View_ViewEngineCollection()\n        {\n            // Arrange\n            Controller controller = GetEmptyController();\n            ViewEngineCollection viewEngines = new ViewEngineCollection();\n            controller.ViewEngineCollection = viewEngines;\n\n            // Act\n            ViewResult result = controller.View();\n\n            // Assert\n            Assert.Same(viewEngines, result.ViewEngineCollection);\n        }\n\n        internal static void AddRequestParams(Mock<HttpRequestBase> requestMock, object paramValues)\n        {\n            PropertyDescriptorCollection props = TypeDescriptor.GetProperties(paramValues);\n            foreach (PropertyDescriptor prop in props)\n            {\n                requestMock.Setup(o => o[It.Is<string>(item => String.Equals(prop.Name, item, StringComparison.OrdinalIgnoreCase))]).Returns((string)prop.GetValue(paramValues));\n            }\n        }\n\n        [Fact]\n        public void TempDataGreetUserWithNoUserIDRedirects()\n        {\n            // Arrange\n            TempDataHomeController tempDataHomeController = new TempDataHomeController();\n\n            // Act\n            RedirectToRouteResult result = tempDataHomeController.GreetUser() as RedirectToRouteResult;\n            RouteValueDictionary values = result.RouteValues;\n\n            // Assert\n            Assert.True(values.ContainsKey(\"action\"));\n            Assert.Equal(\"ErrorPage\", values[\"action\"]);\n            Assert.Empty(tempDataHomeController.TempData);\n        }\n\n        [Fact]\n        public void TempDataGreetUserWithUserIDCopiesToViewDataAndRenders()\n        {\n            // Arrange\n            TempDataHomeController tempDataHomeController = new TempDataHomeController();\n            tempDataHomeController.TempData[\"UserID\"] = \"TestUserID\";\n\n            // Act\n            ViewResult result = tempDataHomeController.GreetUser() as ViewResult;\n            ViewDataDictionary viewData = tempDataHomeController.ViewData;\n\n            // Assert\n            Assert.Equal(\"GreetUser\", result.ViewName);\n            Assert.NotNull(viewData);\n            Assert.True(viewData.ContainsKey(\"NewUserID\"));\n            Assert.Equal(\"TestUserID\", viewData[\"NewUserID\"]);\n        }\n\n        [Fact]\n        public void TempDataIndexSavesUserIDAndRedirects()\n        {\n            // Arrange\n            TempDataHomeController tempDataHomeController = new TempDataHomeController();\n\n            // Act\n            RedirectToRouteResult result = tempDataHomeController.Index() as RedirectToRouteResult;\n            RouteValueDictionary values = result.RouteValues;\n\n            // Assert\n            Assert.True(values.ContainsKey(\"action\"));\n            Assert.Equal(\"GreetUser\", values[\"action\"]);\n\n            Assert.True(tempDataHomeController.TempData.ContainsKey(\"UserID\"));\n            Assert.Equal(\"user123\", tempDataHomeController.TempData[\"UserID\"]);\n        }\n\n        [Fact]\n        public void TempDataSavedWhenControllerThrows()\n        {\n            // Arrange\n            BrokenController controller = new BrokenController() { ValidateRequest = false };\n            Mock<HttpContextBase> mockContext = HttpContextHelpers.GetMockHttpContext();\n            HttpSessionStateBase session = GetEmptySession();\n            mockContext.Setup(o => o.Session).Returns(session);\n            RouteData rd = new RouteData();\n            rd.Values.Add(\"action\", \"Crash\");\n            controller.ControllerContext = new ControllerContext(mockContext.Object, rd, controller);\n\n            // Assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { ((IController)controller).Execute(controller.ControllerContext.RequestContext); });\n            Assert.NotNull(mockContext.Object.Session[SessionStateTempDataProvider.TempDataSessionStateKey]);\n            TempDataDictionary tempData = new TempDataDictionary();\n            tempData.Load(controller.ControllerContext, controller.TempDataProvider);\n            Assert.Equal(\"Value1\", tempData[\"Key1\"]);\n        }\n\n        [Fact]\n        public void TempDataMovedToPreviousTempDataInDestinationController()\n        {\n            // Arrange\n            Mock<Controller> mockController = new Mock<Controller>() { CallBase = true };\n            Mock<HttpContextBase> mockContext = new Mock<HttpContextBase>();\n            HttpSessionStateBase session = GetEmptySession();\n            mockContext.Setup(o => o.Session).Returns(session);\n            mockController.Object.ControllerContext = new ControllerContext(mockContext.Object, new RouteData(), mockController.Object);\n\n            // Act\n            mockController.Object.TempData.Add(\"Key\", \"Value\");\n            mockController.Object.TempData.Save(mockController.Object.ControllerContext, mockController.Object.TempDataProvider);\n\n            // Assert\n            Assert.True(mockController.Object.TempData.ContainsKey(\"Key\"));\n            Assert.True(mockController.Object.TempData.ContainsValue(\"Value\"));\n\n            // Instantiate \"destination\" controller with the same session state and see that it gets the temp data\n            Mock<Controller> mockDestinationController = new Mock<Controller>() { CallBase = true };\n            Mock<HttpContextBase> mockDestinationContext = new Mock<HttpContextBase>();\n            mockDestinationContext.Setup(o => o.Session).Returns(session);\n            mockDestinationController.Object.ControllerContext = new ControllerContext(mockDestinationContext.Object, new RouteData(), mockDestinationController.Object);\n            mockDestinationController.Object.TempData.Load(mockDestinationController.Object.ControllerContext, mockDestinationController.Object.TempDataProvider);\n\n            // Assert\n            Assert.True(mockDestinationController.Object.TempData.ContainsKey(\"Key\"));\n\n            // Act\n            mockDestinationController.Object.TempData[\"NewKey\"] = \"NewValue\";\n            Assert.True(mockDestinationController.Object.TempData.ContainsKey(\"NewKey\"));\n            mockDestinationController.Object.TempData.Save(mockDestinationController.Object.ControllerContext, mockDestinationController.Object.TempDataProvider);\n\n            // Instantiate \"second destination\" controller with the same session state and see that it gets the temp data\n            Mock<Controller> mockSecondDestinationController = new Mock<Controller>() { CallBase = true };\n            Mock<HttpContextBase> mockSecondDestinationContext = new Mock<HttpContextBase>();\n            mockSecondDestinationContext.Setup(o => o.Session).Returns(session);\n            mockSecondDestinationController.Object.ControllerContext = new ControllerContext(mockSecondDestinationContext.Object, new RouteData(), mockSecondDestinationController.Object);\n            mockSecondDestinationController.Object.TempData.Load(mockSecondDestinationController.Object.ControllerContext, mockSecondDestinationController.Object.TempDataProvider);\n\n            // Assert\n            Assert.True(mockSecondDestinationController.Object.TempData.ContainsKey(\"Key\"));\n            Assert.True(mockSecondDestinationController.Object.TempData.ContainsKey(\"NewKey\"));\n        }\n\n        [Fact]\n        public void TempDataRemovesKeyWhenRead()\n        {\n            // Arrange\n            Mock<Controller> mockController = new Mock<Controller>() { CallBase = true };\n            Mock<HttpContextBase> mockContext = new Mock<HttpContextBase>();\n            HttpSessionStateBase session = GetEmptySession();\n            mockContext.Setup(o => o.Session).Returns(session);\n            mockController.Object.ControllerContext = new ControllerContext(mockContext.Object, new RouteData(), mockController.Object);\n\n            // Act\n            mockController.Object.TempData.Add(\"Key\", \"Value\");\n            mockController.Object.TempData.Save(mockController.Object.ControllerContext, mockController.Object.TempDataProvider);\n\n            // Assert\n            Assert.True(mockController.Object.TempData.ContainsKey(\"Key\"));\n            Assert.True(mockController.Object.TempData.ContainsValue(\"Value\"));\n\n            // Instantiate \"destination\" controller with the same session state and see that it gets the temp data\n            Mock<Controller> mockDestinationController = new Mock<Controller>() { CallBase = true };\n            Mock<HttpContextBase> mockDestinationContext = new Mock<HttpContextBase>();\n            mockDestinationContext.Setup(o => o.Session).Returns(session);\n            mockDestinationController.Object.ControllerContext = new ControllerContext(mockDestinationContext.Object, new RouteData(), mockDestinationController.Object);\n            mockDestinationController.Object.TempData.Load(mockDestinationController.Object.ControllerContext, mockDestinationController.Object.TempDataProvider);\n\n            // Assert\n            Assert.True(mockDestinationController.Object.TempData.ContainsKey(\"Key\"));\n\n            // Act\n            object value = mockDestinationController.Object.TempData[\"Key\"];\n            mockDestinationController.Object.TempData.Save(mockDestinationController.Object.ControllerContext, mockDestinationController.Object.TempDataProvider);\n\n            // Instantiate \"second destination\" controller with the same session state and see that it gets the temp data\n            Mock<Controller> mockSecondDestinationController = new Mock<Controller>() { CallBase = true };\n            Mock<HttpContextBase> mockSecondDestinationContext = new Mock<HttpContextBase>();\n            mockSecondDestinationContext.Setup(o => o.Session).Returns(session);\n            mockSecondDestinationController.Object.ControllerContext = new ControllerContext(mockSecondDestinationContext.Object, new RouteData(), mockSecondDestinationController.Object);\n            mockSecondDestinationController.Object.TempData.Load(mockSecondDestinationController.Object.ControllerContext, mockSecondDestinationController.Object.TempDataProvider);\n\n            // Assert\n            Assert.False(mockSecondDestinationController.Object.TempData.ContainsKey(\"Key\"));\n        }\n\n        [Fact]\n        public void TempDataValidForSingleControllerWhenSessionStateDisabled()\n        {\n            // Arrange\n            Mock<Controller> mockController = new Mock<Controller>();\n            Mock<HttpContextBase> mockContext = new Mock<HttpContextBase>();\n            HttpSessionStateBase session = null;\n            mockContext.Setup(o => o.Session).Returns(session);\n            mockController.Object.ControllerContext = new ControllerContext(mockContext.Object, new RouteData(), mockController.Object);\n            mockController.Object.TempData = new TempDataDictionary();\n\n            // Act\n            mockController.Object.TempData[\"Key\"] = \"Value\";\n\n            // Assert\n            Assert.True(mockController.Object.TempData.ContainsKey(\"Key\"));\n        }\n\n        [Fact]\n        public void TryUpdateModelCallsModelBinderForModel()\n        {\n            // Arrange\n            MyModel myModel = new MyModelSubclassed();\n            IValueProvider valueProvider = new SimpleValueProvider();\n\n            Controller controller = new EmptyController();\n            controller.ControllerContext = GetControllerContext(\"someAction\");\n\n            // Act\n            bool returned = controller.TryUpdateModel(myModel, \"somePrefix\", new[] { \"prop1\", \"prop2\" }, null, valueProvider);\n\n            // Assert\n            Assert.True(returned);\n            Assert.Equal(valueProvider, myModel.BindingContext.ValueProvider);\n            Assert.Equal(\"somePrefix\", myModel.BindingContext.ModelName);\n            Assert.Equal(controller.ModelState, myModel.BindingContext.ModelState);\n            Assert.Equal(typeof(MyModel), myModel.BindingContext.ModelType);\n            Assert.True(myModel.BindingContext.PropertyFilter(\"prop1\"));\n            Assert.True(myModel.BindingContext.PropertyFilter(\"prop2\"));\n            Assert.False(myModel.BindingContext.PropertyFilter(\"prop3\"));\n        }\n\n        [Fact]\n        public void TryUpdateModelReturnsFalseIfModelStateInvalid()\n        {\n            // Arrange\n            MyModel myModel = new MyModelSubclassed();\n\n            Controller controller = new EmptyController();\n            controller.ModelState.AddModelError(\"key\", \"some exception message\");\n\n            // Act\n            bool returned = controller.TryUpdateModel(myModel, new SimpleValueProvider());\n\n            // Assert\n            Assert.False(returned);\n        }\n\n        [Fact]\n        public void TryUpdateModelSuppliesControllerValueProviderIfNoValueProviderSpecified()\n        {\n            // Arrange\n            MyModel myModel = new MyModelSubclassed();\n            IValueProvider valueProvider = new SimpleValueProvider();\n\n            Controller controller = new EmptyController();\n            controller.ValueProvider = valueProvider;\n\n            // Act\n            bool returned = controller.TryUpdateModel(myModel, \"somePrefix\", new[] { \"prop1\", \"prop2\" });\n\n            // Assert\n            Assert.True(returned);\n            Assert.Equal(valueProvider, myModel.BindingContext.ValueProvider);\n        }\n\n        [Fact]\n        public void TryUpdateModelSuppliesEmptyModelNameIfNoPrefixSpecified()\n        {\n            // Arrange\n            MyModel myModel = new MyModelSubclassed();\n            Controller controller = new EmptyController();\n\n            // Act\n            bool returned = controller.TryUpdateModel(myModel, new[] { \"prop1\", \"prop2\" }, new SimpleValueProvider());\n\n            // Assert\n            Assert.True(returned);\n            Assert.Equal(String.Empty, myModel.BindingContext.ModelName);\n        }\n\n        [Fact]\n        public void TryUpdateModelThrowsIfModelIsNull()\n        {\n            // Arrange\n            Controller controller = new EmptyController();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { controller.TryUpdateModel<object>(null, new SimpleValueProvider()); }, \"model\");\n        }\n\n        [Fact]\n        public void TryUpdateModelThrowsIfValueProviderIsNull()\n        {\n            // Arrange\n            Controller controller = new EmptyController();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { controller.TryUpdateModel(new object(), null, null, null, null); }, \"valueProvider\");\n        }\n\n        [Fact]\n        public void UpdateModelReturnsIfModelStateValid()\n        {\n            // Arrange\n            MyModel myModel = new MyModelSubclassed();\n            Controller controller = new EmptyController();\n\n            // Act\n            controller.UpdateModel(myModel, new SimpleValueProvider());\n\n            // Assert\n            // nothing to do - if we got here, the test passed\n        }\n\n        [Fact]\n        public void TryUpdateModelWithoutBindPropertiesImpliesAllPropertiesAreUpdateable()\n        {\n            // Arrange\n            MyModel myModel = new MyModelSubclassed();\n            Controller controller = new EmptyController();\n\n            // Act\n            bool returned = controller.TryUpdateModel(myModel, \"somePrefix\", new SimpleValueProvider());\n\n            // Assert\n            Assert.True(returned);\n            Assert.True(myModel.BindingContext.PropertyFilter(\"prop1\"));\n            Assert.True(myModel.BindingContext.PropertyFilter(\"prop2\"));\n            Assert.True(myModel.BindingContext.PropertyFilter(\"prop3\"));\n        }\n\n        [Fact]\n        public void UpdateModelSuppliesControllerValueProviderIfNoValueProviderSpecified()\n        {\n            // Arrange\n            MyModel myModel = new MyModelSubclassed();\n            IValueProvider valueProvider = new SimpleValueProvider();\n\n            Controller controller = new EmptyController() { ValueProvider = valueProvider };\n\n            // Act\n            controller.UpdateModel(myModel, \"somePrefix\", new[] { \"prop1\", \"prop2\" });\n\n            // Assert\n            Assert.Equal(valueProvider, myModel.BindingContext.ValueProvider);\n        }\n\n        [Fact]\n        public void UpdateModelThrowsIfModelStateInvalid()\n        {\n            // Arrange\n            MyModel myModel = new MyModelSubclassed();\n\n            Controller controller = new EmptyController();\n            controller.ModelState.AddModelError(\"key\", \"some exception message\");\n\n            // Act & assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { controller.UpdateModel(myModel, new SimpleValueProvider()); },\n                \"The model of type 'System.Web.Mvc.Test.ControllerTest+MyModel' could not be updated.\");\n        }\n\n        [Fact]\n        public void UpdateModelWithoutBindPropertiesImpliesAllPropertiesAreUpdateable()\n        {\n            // Arrange\n            MyModel myModel = new MyModelSubclassed();\n            Controller controller = new EmptyController();\n\n            // Act\n            controller.UpdateModel(myModel, \"somePrefix\", new SimpleValueProvider());\n\n            // Assert\n            Assert.True(myModel.BindingContext.PropertyFilter(\"prop1\"));\n            Assert.True(myModel.BindingContext.PropertyFilter(\"prop2\"));\n            Assert.True(myModel.BindingContext.PropertyFilter(\"prop3\"));\n        }\n\n        [Fact]\n        public void Json()\n        {\n            // Arrange\n            MyModel model = new MyModel();\n            Controller controller = new EmptyController();\n\n            // Act\n            JsonResult result = controller.Json(model);\n\n            // Assert\n            Assert.Same(model, result.Data);\n            Assert.Null(result.ContentType);\n            Assert.Null(result.ContentEncoding);\n            Assert.Equal(JsonRequestBehavior.DenyGet, result.JsonRequestBehavior);\n        }\n\n        [Fact]\n        public void JsonWithContentType()\n        {\n            // Arrange\n            MyModel model = new MyModel();\n            Controller controller = new EmptyController();\n\n            // Act\n            JsonResult result = controller.Json(model, \"text/xml\");\n\n            // Assert\n            Assert.Same(model, result.Data);\n            Assert.Equal(\"text/xml\", result.ContentType);\n            Assert.Null(result.ContentEncoding);\n            Assert.Equal(JsonRequestBehavior.DenyGet, result.JsonRequestBehavior);\n        }\n\n        [Fact]\n        public void JsonWithContentTypeAndEncoding()\n        {\n            // Arrange\n            MyModel model = new MyModel();\n            Controller controller = new EmptyController();\n\n            // Act\n            JsonResult result = controller.Json(model, \"text/xml\", Encoding.UTF32);\n\n            // Assert\n            Assert.Same(model, result.Data);\n            Assert.Equal(\"text/xml\", result.ContentType);\n            Assert.Equal(Encoding.UTF32, result.ContentEncoding);\n            Assert.Equal(JsonRequestBehavior.DenyGet, result.JsonRequestBehavior);\n        }\n\n        [Fact]\n        public void JsonWithBehavior()\n        {\n            // Arrange\n            MyModel model = new MyModel();\n            Controller controller = new EmptyController();\n\n            // Act\n            JsonResult result = controller.Json(model, JsonRequestBehavior.AllowGet);\n\n            // Assert\n            Assert.Same(model, result.Data);\n            Assert.Null(result.ContentType);\n            Assert.Null(result.ContentEncoding);\n            Assert.Equal(JsonRequestBehavior.AllowGet, result.JsonRequestBehavior);\n        }\n\n        [Fact]\n        public void JsonWithContentTypeAndBehavior()\n        {\n            // Arrange\n            MyModel model = new MyModel();\n            Controller controller = new EmptyController();\n\n            // Act\n            JsonResult result = controller.Json(model, \"text/xml\", JsonRequestBehavior.AllowGet);\n\n            // Assert\n            Assert.Same(model, result.Data);\n            Assert.Equal(\"text/xml\", result.ContentType);\n            Assert.Null(result.ContentEncoding);\n            Assert.Equal(JsonRequestBehavior.AllowGet, result.JsonRequestBehavior);\n        }\n\n        [Fact]\n        public void JsonWithContentTypeAndEncodingAndBehavior()\n        {\n            // Arrange\n            MyModel model = new MyModel();\n            Controller controller = new EmptyController();\n\n            // Act\n            JsonResult result = controller.Json(model, \"text/xml\", Encoding.UTF32, JsonRequestBehavior.AllowGet);\n\n            // Assert\n            Assert.Same(model, result.Data);\n            Assert.Equal(\"text/xml\", result.ContentType);\n            Assert.Equal(Encoding.UTF32, result.ContentEncoding);\n            Assert.Equal(JsonRequestBehavior.AllowGet, result.JsonRequestBehavior);\n        }\n\n        [Fact]\n        public void ExecuteDoesNotCallTempDataLoadOrSave()\n        {\n            // Arrange\n            TempDataDictionary tempData = new TempDataDictionary();\n            ViewContext viewContext = new ViewContext { TempData = tempData };\n            RouteData routeData = new RouteData();\n            routeData.DataTokens[ControllerContext.ParentActionViewContextToken] = viewContext;\n            routeData.Values[\"action\"] = \"SimpleAction\";\n            RequestContext requestContext = new RequestContext(HttpContextHelpers.GetMockHttpContext().Object, routeData);\n            // Strict == no default implementations == calls to Load & Save are not allowed\n            Mock<ITempDataProvider> tempDataProvider = new Mock<ITempDataProvider>(MockBehavior.Strict);\n            SimpleController controller = new SimpleController();\n            controller.ValidateRequest = false;\n\n            // Act\n            ((IController)controller).Execute(requestContext);\n\n            // Assert\n            tempDataProvider.Verify();\n        }\n\n        // Model validation\n\n        [Fact]\n        public void TryValidateModelGuardClauses()\n        {\n            // Arrange\n            Controller controller = new SimpleController();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => controller.TryValidateModel(null),\n                \"model\");\n        }\n\n        [Fact]\n        public void TryValidateModelWithValidModel()\n        {\n            // Arrange\n            Controller controller = new SimpleController();\n            TryValidateModelModel model = new TryValidateModelModel { IntegerProperty = 15 };\n\n            // Act\n            bool result = controller.TryValidateModel(model);\n\n            // Assert\n            Assert.True(result);\n            Assert.True(controller.ModelState.IsValid);\n        }\n\n        [Fact]\n        public void TryValidateModelWithInvalidModel()\n        {\n            // Arrange\n            Controller controller = new SimpleController();\n            TryValidateModelModel model = new TryValidateModelModel { IntegerProperty = 5 };\n\n            // Act\n            bool result = controller.TryValidateModel(model, \"Prefix\");\n\n            // Assert\n            Assert.False(result);\n            Assert.Equal(\"Out of range!\", controller.ModelState[\"Prefix.IntegerProperty\"].Errors[0].ErrorMessage);\n        }\n\n        [Fact]\n        public void ValidateModelGuardClauses()\n        {\n            // Arrange\n            Controller controller = new SimpleController();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => controller.ValidateModel(null),\n                \"model\");\n        }\n\n        [Fact]\n        public void ValidateModelWithValidModel()\n        {\n            // Arrange\n            Controller controller = new SimpleController();\n            TryValidateModelModel model = new TryValidateModelModel { IntegerProperty = 15 };\n\n            // Act\n            controller.ValidateModel(model);\n\n            // Assert\n            Assert.True(controller.ModelState.IsValid);\n        }\n\n        [Fact]\n        public void ValidateModelWithInvalidModel()\n        {\n            // Arrange\n            Controller controller = new SimpleController();\n            TryValidateModelModel model = new TryValidateModelModel { IntegerProperty = 5 };\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => controller.ValidateModel(model, \"Prefix\"),\n                \"The model of type '\" + model.GetType().FullName + \"' is not valid.\");\n\n            Assert.Equal(\"Out of range!\", controller.ModelState[\"Prefix.IntegerProperty\"].Errors[0].ErrorMessage);\n        }\n\n        [Fact]\n        public void ValidateControllerUsesCachedResolver()\n        {\n            var controller = new EmptyController();\n\n            var resolver = controller.Resolver;\n\n            Assert.Equal(DependencyResolver.CurrentCache.GetType(), resolver.GetType());\n        }\n\n\n        [Fact]\n        public void CreateActionInvokerCallsAsyncActionInvokerFactoryCreateInstance()\n        {\n            // Controller uses an IDependencyResolver and an IAsyncActionInvokerFactory\n            // to create an IAsyncActionInvoker.\n            // Arrange\n            var controller = new EmptyController();\n            Mock<IDependencyResolver> resolverMock = new Mock<IDependencyResolver>();\n            Mock<IAsyncActionInvoker> asyncActionInvokerMock = new Mock<IAsyncActionInvoker>();\n            Mock<IAsyncActionInvokerFactory> asyncActionInvokerFactoryMock = new Mock<IAsyncActionInvokerFactory>();\n            asyncActionInvokerFactoryMock.Setup(a => a.CreateInstance()).Returns(asyncActionInvokerMock.Object);\n            resolverMock.Setup(r => r.GetService(typeof(IAsyncActionInvokerFactory)))\n                .Returns(asyncActionInvokerFactoryMock.Object);\n            resolverMock.Setup(r => r.GetService(typeof(IActionInvokerFactory)))\n                .Returns((IActionInvokerFactory)null);\n            controller.Resolver = resolverMock.Object;\n\n            // Act\n            var ai = controller.CreateActionInvoker();\n\n            // Assert\n            resolverMock.Verify(r => r.GetService(typeof(IAsyncActionInvokerFactory)), Times.Once());\n            resolverMock.Verify(r => r.GetService(typeof(IActionInvokerFactory)), Times.Never());\n            Assert.Same(asyncActionInvokerMock.Object, ai);\n        }\n\n        [Fact]\n        public void CreateActionInvokerCallsActionInvokerFactoryCreateInstance()\n        {\n            // Controller uses an IDependencyResolver and an IActionInvokerFactory to create an IActionInvoker.\n            // Arrange\n            var controller = new EmptyController();\n            Mock<IDependencyResolver> resolverMock = new Mock<IDependencyResolver>();\n            Mock<IActionInvoker> actionInvokerMock = new Mock<IActionInvoker>();\n            Mock<IActionInvokerFactory> actionInvokerFactoryMock = new Mock<IActionInvokerFactory>();\n            actionInvokerFactoryMock.Setup(a => a.CreateInstance()).Returns(actionInvokerMock.Object);\n            resolverMock.Setup(r => r.GetService(typeof(IAsyncActionInvokerFactory)))\n                .Returns((IAsyncActionInvokerFactory)null);\n            resolverMock.Setup(r => r.GetService(typeof(IActionInvokerFactory)))\n                .Returns(actionInvokerFactoryMock.Object);\n            controller.Resolver = resolverMock.Object;\n\n            // Act\n            var ai = controller.CreateActionInvoker();\n\n            // Assert\n            resolverMock.Verify(r => r.GetService(typeof(IAsyncActionInvokerFactory)), Times.Once());\n            resolverMock.Verify(r => r.GetService(typeof(IActionInvokerFactory)), Times.Once());\n            Assert.Same(actionInvokerMock.Object, ai);\n        }\n\n        [Fact]\n        public void CreateActionInvokerCallsIntoResolverInstance()\n        {\n            // Controller uses an IDependencyResolver to create an IActionInvoker.\n            var controller = new EmptyController();\n            Mock<IDependencyResolver> resolverMock = new Mock<IDependencyResolver>();\n            Mock<IAsyncActionInvoker> actionInvokerMock = new Mock<IAsyncActionInvoker>();\n            resolverMock.Setup(r => r.GetService(typeof(IAsyncActionInvoker))).Returns(actionInvokerMock.Object);\n            controller.Resolver = resolverMock.Object;\n\n            var ai = controller.CreateActionInvoker();\n\n            resolverMock.Verify(r => r.GetService(typeof(IAsyncActionInvoker)), Times.Once());\n            Assert.Same(actionInvokerMock.Object, ai);\n        }\n\n        [Fact]\n        public void CreateActionInvokerCallsIntoResolverInstanceAndCreatesANewOneIfNecessary()\n        {\n            // If IDependencyResolver is set, but empty, falls back and still creates.\n            var controller = new EmptyController();\n            Mock<IDependencyResolver> resolverMock = new Mock<IDependencyResolver>();\n            resolverMock.Setup(r => r.GetService(typeof(IAsyncActionInvoker))).Returns(null);\n            controller.Resolver = resolverMock.Object;\n\n            IActionInvoker ai = controller.CreateActionInvoker();\n\n            resolverMock.Verify(r => r.GetService(typeof(IAsyncActionInvoker)), Times.Once());\n            Assert.NotNull(ai);\n        }\n\n        [Fact]\n        public void CreateTempProviderWithResolver()\n        {\n            // Controller uses an IDependencyResolver to create an ITempDataProvider.\n            var controller = new EmptyController();\n            Mock<IDependencyResolver> resolverMock = new Mock<IDependencyResolver>();\n            Mock<ITempDataProvider> tempMock = new Mock<ITempDataProvider>();\n            resolverMock.Setup(r => r.GetService(typeof(ITempDataProvider))).Returns(tempMock.Object);\n            controller.Resolver = resolverMock.Object;\n\n            ITempDataProvider temp = controller.CreateTempDataProvider();\n\n            resolverMock.Verify(r => r.GetService(typeof(ITempDataProvider)), Times.Once());\n            Assert.Same(tempMock.Object, temp);\n        }\n\n        [Fact]\n        public void CreateTempProviderWithResolver_ITempDataProviderFactory()\n        {\n            // Controller uses an IDependencyResolver and an ITempDataProviderFactory to create an ITempDataProvider.\n            // Arrange\n            var controller = new EmptyController();\n            Mock<IDependencyResolver> resolverMock = new Mock<IDependencyResolver>();\n            Mock<ITempDataProvider> tempMock = new Mock<ITempDataProvider>();\n            Mock<ITempDataProviderFactory> factoryMock = new Mock<ITempDataProviderFactory>();\n            factoryMock.Setup(f => f.CreateInstance()).Returns(tempMock.Object);\n            resolverMock.Setup(r => r.GetService(typeof(ITempDataProvider))).Returns(tempMock.Object);\n            resolverMock.Setup(r => r.GetService(typeof(ITempDataProviderFactory))).Returns(factoryMock.Object);\n            controller.Resolver = resolverMock.Object;\n\n            // Act\n            ITempDataProvider temp = controller.CreateTempDataProvider();\n\n            // Assert\n            // Times.Once() and Times.Never() confirm the order.\n            resolverMock.Verify(r => r.GetService(typeof(ITempDataProviderFactory)), Times.Once());\n            resolverMock.Verify(r => r.GetService(typeof(ITempDataProvider)), Times.Never());\n            Assert.Same(tempMock.Object, temp);\n        }\n\n        [Fact]\n        public void CanMock_UrlHelper()\n        {\n            // Arrange\n            var controller = new UrlHelperController();\n            Mock<UrlHelper> urlHelper = new Mock<UrlHelper>();\n            urlHelper.Setup(u => u.Action(\"SimpleAction\", new { ID = 42 })).Verifiable();\n            controller.Url = urlHelper.Object;\n\n            // Act\n            controller.SimpleAction();\n\n            // Assert\n            urlHelper.Verify();\n        }\n\n        private class TryValidateModelModel\n        {\n            [Range(10, 20, ErrorMessage = \"Out of range!\")]\n            public int IntegerProperty { get; set; }\n        }\n\n        // Helpers\n\n        private class UrlHelperController : Controller\n        {\n            public string SimpleAction()\n            {\n                return Url.Action(\"SimpleAction\", new { ID = 42 });\n            }\n        }\n\n        private class SimpleController : Controller\n        {\n            public SimpleController()\n            {\n                ControllerContext = new ControllerContext { Controller = this };\n            }\n\n            public void SimpleAction()\n            {\n            }\n        }\n\n        private static ControllerContext GetControllerContext(string actionName)\n        {\n            RouteData rd = new RouteData();\n            rd.Values[\"action\"] = actionName;\n\n            Mock<HttpContextBase> mockHttpContext = HttpContextHelpers.GetMockHttpContext();\n            mockHttpContext.Setup(c => c.Session).Returns((HttpSessionStateBase)null);\n\n            return new ControllerContext(mockHttpContext.Object, rd, new Mock<Controller>().Object);\n        }\n\n        private static ControllerContext GetControllerContext(string actionName, string controllerName)\n        {\n            RouteData rd = new RouteData();\n            rd.Values[\"action\"] = actionName;\n            rd.Values[\"controller\"] = controllerName;\n\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(c => c.Session).Returns((HttpSessionStateBase)null);\n\n            return new ControllerContext(mockHttpContext.Object, rd, new Mock<Controller>().Object);\n        }\n\n        private static Controller GetEmptyController()\n        {\n            ControllerContext context = GetControllerContext(\"Foo\");\n            var controller = new EmptyController()\n            {\n                ControllerContext = context,\n                RouteCollection = new RouteCollection(),\n                TempData = new TempDataDictionary(),\n                TempDataProvider = new SessionStateTempDataProvider()\n            };\n            return controller;\n        }\n\n        private static HttpSessionStateBase GetEmptySession()\n        {\n            HttpSessionStateMock mockSession = new HttpSessionStateMock();\n            return mockSession;\n        }\n\n        private sealed class HttpSessionStateMock : HttpSessionStateBase\n        {\n            private Hashtable _sessionData = new Hashtable(StringComparer.OrdinalIgnoreCase);\n\n            public override void Remove(string name)\n            {\n                Assert.Equal(SessionStateTempDataProvider.TempDataSessionStateKey, name);\n                _sessionData.Remove(name);\n            }\n\n            public override object this[string name]\n            {\n                get\n                {\n                    Assert.Equal(SessionStateTempDataProvider.TempDataSessionStateKey, name);\n                    return _sessionData[name];\n                }\n                set\n                {\n                    Assert.Equal(SessionStateTempDataProvider.TempDataSessionStateKey, name);\n                    _sessionData[name] = value;\n                }\n            }\n        }\n\n        public class Person\n        {\n            public string Name { get; set; }\n            public int Age { get; set; }\n        }\n\n        private class EmptyController : Controller\n        {\n            public new void HandleUnknownAction(string actionName)\n            {\n                base.HandleUnknownAction(actionName);\n            }\n\n            public void PublicInitialize(RequestContext requestContext)\n            {\n                base.Initialize(requestContext);\n            }\n\n            // Test can expose protected method as public.\n            public new IActionInvoker CreateActionInvoker()\n            {\n                return base.CreateActionInvoker();\n            }\n\n            public new ITempDataProvider CreateTempDataProvider()\n            {\n                return base.CreateTempDataProvider();\n            }\n        }\n\n\n        private sealed class UnknownActionController : Controller\n        {\n            public bool WasCalled;\n\n            protected override void HandleUnknownAction(string actionName)\n            {\n                WasCalled = true;\n            }\n        }\n\n        private sealed class TempDataHomeController : Controller\n        {\n            public ActionResult Index()\n            {\n                // Save UserID into TempData and redirect to greeting page\n                TempData[\"UserID\"] = \"user123\";\n                return RedirectToAction(\"GreetUser\");\n            }\n\n            public ActionResult GreetUser()\n            {\n                // Check that the UserID is present. If it's not\n                // there, redirect to error page. If it is, show\n                // the greet user view.\n                if (!TempData.ContainsKey(\"UserID\"))\n                {\n                    return RedirectToAction(\"ErrorPage\");\n                }\n                ViewData[\"NewUserID\"] = TempData[\"UserID\"];\n                return View(\"GreetUser\");\n            }\n        }\n\n        public class BrokenController : Controller\n        {\n            public BrokenController()\n            {\n                ActionInvoker = new ControllerActionInvoker()\n                {\n                    DescriptorCache = new ControllerDescriptorCache()\n                };\n            }\n\n            public ActionResult Crash()\n            {\n                TempData[\"Key1\"] = \"Value1\";\n                throw new InvalidOperationException(\"Crashing....\");\n            }\n        }\n\n        private sealed class TestRouteController : Controller\n        {\n            public ActionResult Index()\n            {\n                return RedirectToAction(\"SomeAction\");\n            }\n        }\n\n        [ModelBinder(typeof(MyModelBinder))]\n        private class MyModel\n        {\n            public ControllerContext ControllerContext;\n            public ModelBindingContext BindingContext;\n        }\n\n        private class MyModelSubclassed : MyModel\n        {\n        }\n\n        private class MyModelBinder : IModelBinder\n        {\n            public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)\n            {\n                MyModel myModel = (MyModel)bindingContext.Model;\n                myModel.ControllerContext = controllerContext;\n                myModel.BindingContext = bindingContext;\n                return myModel;\n            }\n        }\n    }\n\n    internal class EmptyTempDataProvider : ITempDataProvider\n    {\n        public void SaveTempData(ControllerContext controllerContext, IDictionary<string, object> values)\n        {\n        }\n\n        public IDictionary<string, object> LoadTempData(ControllerContext controllerContext)\n        {\n            return new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/CopyOnWriteDictionaryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class CopyOnWriteDictionaryTest\n    {\n        [Fact]\n        public void ReadOperation_DelegatesToSourceDictionary_IfNoMutationsArePerformed()\n        {\n            // Arrange\n            var values = new List<object>();\n            var enumerator = Mock.Of<IEnumerator<KeyValuePair<string, object>>>();\n            var sourceDictionary = new Mock<IDictionary<string, object>>(MockBehavior.Strict);\n            sourceDictionary.SetupGet(d => d.Count)\n                            .Returns(100)\n                            .Verifiable();\n            sourceDictionary.SetupGet(d => d.Values)\n                            .Returns(values)\n                            .Verifiable();\n            sourceDictionary.Setup(d => d.ContainsKey(\"test-key\"))\n                            .Returns(value: true)\n                            .Verifiable();\n            sourceDictionary.Setup(d => d.GetEnumerator())\n                            .Returns(enumerator)\n                            .Verifiable();\n            sourceDictionary.Setup(d => d[\"key2\"])\n                            .Returns(\"key2-value\")\n                            .Verifiable();\n            object value;\n            sourceDictionary.Setup(d => d.TryGetValue(\"different-key\", out value))\n                            .Returns(false)\n                            .Verifiable();\n\n            var copyOnWriteDictionary = new CopyOnWriteDictionary<string, object>(sourceDictionary.Object,\n                                                                                  StringComparer.OrdinalIgnoreCase);\n\n            // Act and Assert\n            Assert.Equal(\"key2-value\", copyOnWriteDictionary[\"key2\"]);\n            Assert.Equal(100, copyOnWriteDictionary.Count);\n            Assert.Same(values, copyOnWriteDictionary.Values);\n            Assert.True(copyOnWriteDictionary.ContainsKey(\"test-key\"));\n            Assert.Same(enumerator, copyOnWriteDictionary.GetEnumerator());\n            Assert.False(copyOnWriteDictionary.TryGetValue(\"different-key\", out value));\n            sourceDictionary.Verify();\n        }\n\n        [Fact]\n        public void ReadOperation_DoesNotDelegateToSourceDictionary_OnceAValueIsChanged()\n        {\n            // Arrange\n            var values = new List<object>();\n            var sourceDictionary = new Dictionary<string, object>\n            {\n                { \"key1\", \"value1\" },\n                { \"key2\", \"value2\" }\n            };\n            var copyOnWriteDictionary = new CopyOnWriteDictionary<string, object>(sourceDictionary,\n                                                                                  StringComparer.OrdinalIgnoreCase);\n\n            // Act\n            copyOnWriteDictionary[\"key2\"] = \"value3\";\n\n            // Assert\n            Assert.Equal(\"value2\", sourceDictionary[\"key2\"]);\n            Assert.Equal(2, copyOnWriteDictionary.Count);\n            Assert.Equal(\"value1\", copyOnWriteDictionary[\"key1\"]);\n            Assert.Equal(\"value3\", copyOnWriteDictionary[\"key2\"]);\n        }\n\n        [Fact]\n        public void ReadOperation_DoesNotDelegateToSourceDictionary_OnceDictionaryIsModified()\n        {\n            // Arrange\n            var values = new List<object>();\n            var sourceDictionary = new Dictionary<string, object>\n            {\n                { \"key1\", \"value1\" },\n                { \"key2\", \"value2\" }\n            };\n            var copyOnWriteDictionary = new CopyOnWriteDictionary<string, object>(sourceDictionary,\n                                                                                  StringComparer.OrdinalIgnoreCase);\n\n            // Act\n            copyOnWriteDictionary.Add(\"key3\", \"value3\");\n            copyOnWriteDictionary.Remove(\"key1\");\n\n            // Assert\n            Assert.Equal(2, sourceDictionary.Count);\n            Assert.Equal(\"value1\", sourceDictionary[\"key1\"]);\n            Assert.Equal(2, copyOnWriteDictionary.Count);\n            Assert.Equal(\"value2\", copyOnWriteDictionary[\"KeY2\"]);\n            Assert.Equal(\"value3\", copyOnWriteDictionary[\"key3\"]);\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/DataAnnotationsModelMetadataProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc.Test\n{\n    public class DataAnnotationsModelMetadataProviderTest : DataAnnotationsModelMetadataProviderTestBase\n    {\n        protected override AssociatedMetadataProvider MakeProvider()\n        {\n            return new DataAnnotationsModelMetadataProvider();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/DataAnnotationsModelMetadataProviderTestBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public abstract class DataAnnotationsModelMetadataProviderTestBase\n    {\n        protected abstract AssociatedMetadataProvider MakeProvider();\n\n        [Fact]\n        public void GetMetadataForPropertiesSetTypesAndPropertyNames()\n        {\n            // Arrange\n            var provider = MakeProvider();\n\n            // Act\n            IEnumerable<ModelMetadata> result = provider.GetMetadataForProperties(\"foo\", typeof(string));\n\n            // Assert\n            Assert.Contains(result, m => m.ModelType == typeof(int)\n                                        && m.PropertyName == \"Length\"\n                                        && (int)m.Model == 3);\n        }\n\n        [Fact]\n        public void GetMetadataForPropertySetsTypeAndPropertyName()\n        {\n            // Arrange\n            var provider = MakeProvider();\n\n            // Act\n            ModelMetadata result = provider.GetMetadataForProperty(null, typeof(string), \"Length\");\n\n            // Assert\n            Assert.Equal(typeof(int), result.ModelType);\n            Assert.Equal(\"Length\", result.PropertyName);\n        }\n\n        [Fact]\n        public void GetMetadataForTypeSetsTypeWithNullPropertyName()\n        {\n            // Arrange\n            var provider = MakeProvider();\n\n            // Act\n            ModelMetadata result = provider.GetMetadataForType(null, typeof(string));\n\n            // Assert\n            Assert.Equal(typeof(string), result.ModelType);\n            Assert.Null(result.PropertyName);\n        }\n\n        // [HiddenInput] tests\n\n        class HiddenModel\n        {\n            public int NoAttribute { get; set; }\n\n            [HiddenInput]\n            public int DefaultHidden { get; set; }\n\n            [HiddenInput(DisplayValue = false)]\n            public int HiddenWithDisplayValueFalse { get; set; }\n\n            [HiddenInput]\n            [UIHint(\"CustomUIHint\")]\n            public int HiddenAndUIHint { get; set; }\n        }\n\n        [Fact]\n        public void HiddenAttributeSetsTemplateHintAndHideSurroundingHtml()\n        {\n            // Arrange\n            var provider = MakeProvider();\n\n            // Act & Assert\n            ModelMetadata noAttributeMetadata = provider.GetMetadataForProperty(null, typeof(HiddenModel), \"NoAttribute\");\n            Assert.Null(noAttributeMetadata.TemplateHint);\n            Assert.False(noAttributeMetadata.HideSurroundingHtml);\n\n            ModelMetadata defaultHiddenMetadata = provider.GetMetadataForProperty(null, typeof(HiddenModel), \"DefaultHidden\");\n            Assert.Equal(\"HiddenInput\", defaultHiddenMetadata.TemplateHint);\n            Assert.False(defaultHiddenMetadata.HideSurroundingHtml);\n\n            ModelMetadata hiddenWithDisplayValueFalseMetadata = provider.GetMetadataForProperty(null, typeof(HiddenModel), \"HiddenWithDisplayValueFalse\");\n            Assert.Equal(\"HiddenInput\", hiddenWithDisplayValueFalseMetadata.TemplateHint);\n            Assert.True(hiddenWithDisplayValueFalseMetadata.HideSurroundingHtml);\n\n            // [UIHint] overrides the template hint from [Hidden]\n            Assert.Equal(\"CustomUIHint\", provider.GetMetadataForProperty(null, typeof(HiddenModel), \"HiddenAndUIHint\").TemplateHint);\n        }\n\n        // [UIHint] tests\n\n        class UIHintModel\n        {\n            public int NoAttribute { get; set; }\n\n            [UIHint(\"MyCustomTemplate\")]\n            public int DefaultUIHint { get; set; }\n\n            [UIHint(\"MyMvcTemplate\", \"MVC\")]\n            public int MvcUIHint { get; set; }\n\n            [UIHint(\"MyWebFormsTemplate\", \"WebForms\")]\n            public int NoMvcUIHint { get; set; }\n\n            [UIHint(\"MyDefaultTemplate\")]\n            [UIHint(\"MyWebFormsTemplate\", \"WebForms\")]\n            [UIHint(\"MyMvcTemplate\", \"MVC\")]\n            public int MultipleUIHint { get; set; }\n        }\n\n        [Fact]\n        public void UIHintAttributeSetsTemplateHint()\n        {\n            // Arrange\n            var provider = MakeProvider();\n\n            // Act & Assert\n            Assert.Null(provider.GetMetadataForProperty(null, typeof(UIHintModel), \"NoAttribute\").TemplateHint);\n            Assert.Equal(\"MyCustomTemplate\", provider.GetMetadataForProperty(null, typeof(UIHintModel), \"DefaultUIHint\").TemplateHint);\n            Assert.Equal(\"MyMvcTemplate\", provider.GetMetadataForProperty(null, typeof(UIHintModel), \"MvcUIHint\").TemplateHint);\n            Assert.Null(provider.GetMetadataForProperty(null, typeof(UIHintModel), \"NoMvcUIHint\").TemplateHint);\n\n            Assert.Equal(\"MyMvcTemplate\", provider.GetMetadataForProperty(null, typeof(UIHintModel), \"MultipleUIHint\").TemplateHint);\n        }\n\n        // [DataType] tests\n\n        const string DerivedDataTypeAttributeFormatString = \"Time is {0:HH:mm}\";\n\n        class DerivedDataTypeAttribute : DataTypeAttribute\n        {\n            public DerivedDataTypeAttribute()\n                : base(DataType.Time)\n            {\n                DisplayFormat = new DisplayFormatAttribute\n                {\n                    ApplyFormatInEditMode = true,\n                    DataFormatString = DerivedDataTypeAttributeFormatString,\n                };\n            }\n        }\n\n        class DataTypeModel\n        {\n            public int NoAttribute { get; set; }\n\n            [DataType(DataType.EmailAddress)]\n            public int EmailAddressProperty { get; set; }\n\n            [DataType(\"CustomDataType\")]\n            public int CustomDataTypeProperty { get; set; }\n\n            [DataType(DataType.Date)]\n            public DateTime DateProperty { get; set; }\n\n            [DerivedDataType]\n            public DateTime TimeProperty { get; set; }\n        }\n\n        [Fact]\n        public void DataTypeAttributeSetsDataTypeName()\n        {\n            // Arrange\n            var provider = MakeProvider();\n\n            // Act & Assert\n            Assert.Null(provider.GetMetadataForProperty(null, typeof(DataTypeModel), \"NoAttribute\").DataTypeName);\n            Assert.Equal(\"EmailAddress\", provider.GetMetadataForProperty(null, typeof(DataTypeModel), \"EmailAddressProperty\").DataTypeName);\n            Assert.Equal(\"CustomDataType\", provider.GetMetadataForProperty(null, typeof(DataTypeModel), \"CustomDataTypeProperty\").DataTypeName);\n            Assert.Equal(\"Date\", provider.GetMetadataForProperty(null, typeof(DataTypeModel), \"DateProperty\").DataTypeName);\n            Assert.Equal(\"Time\", provider.GetMetadataForProperty(null, typeof(DataTypeModel), \"TimeProperty\").DataTypeName);\n        }\n\n        [Theory]\n        [InlineData(\"NoAttribute\", null)]\n        [InlineData(\"EmailAddressProperty\", null)]\n        [InlineData(\"CustomDataTypeProperty\", null)]\n        [InlineData(\"DateProperty\", \"{0:d}\")] // DataType.Date default format\n        [InlineData(\"TimeProperty\", DerivedDataTypeAttributeFormatString)]\n        public void DataTypeAttributeSetsDisplayFormats(string propertyName, string formatString)\n        {\n            // Arrange\n            var provider = MakeProvider();\n\n            // Act\n            string displayFormat = provider.GetMetadataForProperty(null, typeof(DataTypeModel), propertyName).DisplayFormatString;\n            string editFormat = provider.GetMetadataForProperty(null, typeof(DataTypeModel), propertyName).EditFormatString;\n\n            // Assert\n            Assert.Equal(formatString, displayFormat);\n            Assert.Equal(formatString, editFormat);\n        }\n\n        [Theory]\n        [InlineData(\"NoAttribute\", false)]\n        [InlineData(\"EmailAddressProperty\", false)]\n        [InlineData(\"CustomDataTypeProperty\", false)]\n        [InlineData(\"DateProperty\", false)] // Uses DataType.Date default format\n        [InlineData(\"TimeProperty\", true)]\n        public void DataTypeAttributeSetsHasNonDefaultEditFormat(string propertyName, bool expectedNonDefaultEditFormat)\n        {\n            // Arrange\n            var provider = MakeProvider();\n\n            // Act\n            bool hasNonDefaultEditFormat = provider.GetMetadataForProperty(null, typeof(DataTypeModel), propertyName).HasNonDefaultEditFormat;\n\n            // Assert\n            Assert.Equal(expectedNonDefaultEditFormat, hasNonDefaultEditFormat);\n        }\n\n        // [ReadOnly] & [Editable] tests\n\n        class ReadOnlyModel\n        {\n            public int NoAttributes { get; set; }\n\n            [ReadOnly(true)]\n            public int ReadOnlyAttribute { get; set; }\n\n            [Editable(false)]\n            public int EditableAttribute { get; set; }\n\n            [ReadOnly(true)]\n            [Editable(true)]\n            public int BothAttributes { get; set; }\n\n            // Editable trumps ReadOnly\n        }\n\n        [Fact]\n        public void ReadOnlyTests()\n        {\n            // Arrange\n            var provider = MakeProvider();\n\n            // Act & Assert\n            Assert.False(provider.GetMetadataForProperty(null, typeof(ReadOnlyModel), \"NoAttributes\").IsReadOnly);\n            Assert.True(provider.GetMetadataForProperty(null, typeof(ReadOnlyModel), \"ReadOnlyAttribute\").IsReadOnly);\n            Assert.True(provider.GetMetadataForProperty(null, typeof(ReadOnlyModel), \"EditableAttribute\").IsReadOnly);\n            Assert.False(provider.GetMetadataForProperty(null, typeof(ReadOnlyModel), \"BothAttributes\").IsReadOnly);\n        }\n\n        // [DisplayFormat] tests\n\n        class DisplayFormatModel\n        {\n            public int NoAttribute { get; set; }\n\n            [DisplayFormat(NullDisplayText = \"(null value)\")]\n            public int NullDisplayText { get; set; }\n\n            [DisplayFormat(DataFormatString = \"Data {0} format\")]\n            public int DisplayFormatString { get; set; }\n\n            [DisplayFormat(DataFormatString = \"Data {0} format\", ApplyFormatInEditMode = true)]\n            public int DisplayAndEditFormatString { get; set; }\n\n            [DisplayFormat(ConvertEmptyStringToNull = true)]\n            public int ConvertEmptyStringToNullTrue { get; set; }\n\n            [DisplayFormat(ConvertEmptyStringToNull = false)]\n            public int ConvertEmptyStringToNullFalse { get; set; }\n\n            [DataType(DataType.Currency)]\n            public int DataTypeWithoutDisplayFormatOverride { get; set; }\n\n            [DataType(DataType.Currency)]\n            [DisplayFormat(DataFormatString = \"format override\", ApplyFormatInEditMode = true)]\n            public int DataTypeWithDisplayFormatOverride { get; set; }\n\n            [DisplayFormat(HtmlEncode = true)]\n            public int HtmlEncodeTrue { get; set; }\n\n            [DisplayFormat(HtmlEncode = false)]\n            public int HtmlEncodeFalse { get; set; }\n\n            [DataType(DataType.Currency)]\n            [DisplayFormat(HtmlEncode = false)]\n            public int HtmlEncodeFalseWithDataType { get; set; }\n\n            // DataType trumps DisplayFormat.HtmlEncode\n        }\n\n        [Fact]\n        public void DisplayFormatAttributetSetsNullDisplayText()\n        {\n            // Arrange\n            var provider = MakeProvider();\n\n            // Act & Assert\n            Assert.Null(provider.GetMetadataForProperty(null, typeof(DisplayFormatModel), \"NoAttribute\").NullDisplayText);\n            Assert.Equal(\"(null value)\", provider.GetMetadataForProperty(null, typeof(DisplayFormatModel), \"NullDisplayText\").NullDisplayText);\n        }\n\n        [Fact]\n        public void DisplayFormatAttributeSetsDisplayFormatString()\n        {\n            // Arrange\n            var provider = MakeProvider();\n\n            // Act & Assert\n            Assert.Null(provider.GetMetadataForProperty(null, typeof(DisplayFormatModel), \"NoAttribute\").DisplayFormatString);\n            Assert.Equal(\"Data {0} format\", provider.GetMetadataForProperty(null, typeof(DisplayFormatModel), \"DisplayFormatString\").DisplayFormatString);\n            Assert.Equal(\"Data {0} format\", provider.GetMetadataForProperty(null, typeof(DisplayFormatModel), \"DisplayAndEditFormatString\").DisplayFormatString);\n        }\n\n        [Fact]\n        public void DisplayFormatAttributeSetEditFormatString()\n        {\n            // Arrange\n            var provider = MakeProvider();\n\n            // Act & Assert\n            Assert.Null(provider.GetMetadataForProperty(null, typeof(DisplayFormatModel), \"NoAttribute\").EditFormatString);\n            Assert.Null(provider.GetMetadataForProperty(null, typeof(DisplayFormatModel), \"DisplayFormatString\").EditFormatString);\n            Assert.Equal(\"Data {0} format\", provider.GetMetadataForProperty(null, typeof(DisplayFormatModel), \"DisplayAndEditFormatString\").EditFormatString);\n        }\n\n        [Fact]\n        public void DisplayFormatAttributeSetsConvertEmptyStringToNull()\n        {\n            // Arrange\n            var provider = MakeProvider();\n\n            // Act & Assert\n            Assert.True(provider.GetMetadataForProperty(null, typeof(DisplayFormatModel), \"NoAttribute\").ConvertEmptyStringToNull);\n            Assert.True(provider.GetMetadataForProperty(null, typeof(DisplayFormatModel), \"ConvertEmptyStringToNullTrue\").ConvertEmptyStringToNull);\n            Assert.False(provider.GetMetadataForProperty(null, typeof(DisplayFormatModel), \"ConvertEmptyStringToNullFalse\").ConvertEmptyStringToNull);\n        }\n\n        [Fact]\n        public void DataTypeWithoutDisplayFormatOverrideUsesDataTypesDisplayFormat()\n        {\n            // Arrange\n            var provider = MakeProvider();\n\n            // Act\n            string result = provider.GetMetadataForProperty(null, typeof(DisplayFormatModel), \"DataTypeWithoutDisplayFormatOverride\").DisplayFormatString;\n\n            // Assert\n            Assert.Equal(\"{0:C}\", result); // Currency's default format string\n        }\n\n        [Fact]\n        public void DataTypeWithDisplayFormatOverrideUsesDisplayFormatOverride()\n        {\n            // Arrange\n            var provider = MakeProvider();\n\n            // Act\n            string result = provider.GetMetadataForProperty(null, typeof(DisplayFormatModel), \"DataTypeWithDisplayFormatOverride\").DisplayFormatString;\n\n            // Assert\n            Assert.Equal(\"format override\", result);\n        }\n\n        [Fact]\n        public void DataTypeInfluencedByDisplayFormatAttributeHtmlEncode()\n        {\n            // Arrange\n            var provider = MakeProvider();\n\n            // Act & Assert\n            Assert.Null(provider.GetMetadataForProperty(null, typeof(DisplayFormatModel), \"NoAttribute\").DataTypeName);\n            Assert.Null(provider.GetMetadataForProperty(null, typeof(DisplayFormatModel), \"HtmlEncodeTrue\").DataTypeName);\n            Assert.Equal(\"Html\", provider.GetMetadataForProperty(null, typeof(DisplayFormatModel), \"HtmlEncodeFalse\").DataTypeName);\n            Assert.Equal(\"Currency\", provider.GetMetadataForProperty(null, typeof(DisplayFormatModel), \"HtmlEncodeFalseWithDataType\").DataTypeName);\n        }\n\n        [Theory]\n        [InlineData(\"NoAttribute\", false)]\n        [InlineData(\"NullDisplayText\", false)]\n        [InlineData(\"DisplayFormatString\", false)]\n        [InlineData(\"DisplayAndEditFormatString\", true)]\n        [InlineData(\"ConvertEmptyStringToNullTrue\", false)]\n        [InlineData(\"ConvertEmptyStringToNullFalse\", false)]\n        [InlineData(\"DataTypeWithoutDisplayFormatOverride\", false)]\n        [InlineData(\"DataTypeWithDisplayFormatOverride\", true)]\n        [InlineData(\"HtmlEncodeTrue\", false)]\n        [InlineData(\"HtmlEncodeFalse\", false)]\n        [InlineData(\"HtmlEncodeFalseWithDataType\", false)]\n        public void DisplayFormatSetsHasNonDefaultEditFormat(string propertyName, bool expectedHasNonDefaultEditFormat)\n        {\n            // Arrange\n            AssociatedMetadataProvider provider = MakeProvider();\n\n            // Act\n            bool hasNonDefaultEditFormat = provider.GetMetadataForProperty(null, typeof(DisplayFormatModel), propertyName).HasNonDefaultEditFormat;\n\n            // Assert\n            Assert.Equal(expectedHasNonDefaultEditFormat, hasNonDefaultEditFormat);\n        }\n\n        [Theory]\n        [InlineData(\"NoAttribute\", true)]\n        [InlineData(\"HtmlEncodeTrue\", true)]\n        [InlineData(\"HtmlEncodeFalse\", false)]\n        [InlineData(\"HtmlEncodeFalseWithDataType\", false)]\n        public void DisplayFormatSetsHtmlEncode(string propertyName, bool expectedHtmlEncode)\n        {\n            // Arrange\n            AssociatedMetadataProvider provider = MakeProvider();\n\n            // Act\n            bool htmlEncode = provider.GetMetadataForProperty(null, typeof(DisplayFormatModel), propertyName).HtmlEncode;\n\n            // Assert\n            Assert.Equal(expectedHtmlEncode, htmlEncode);\n        }\n\n        // [ScaffoldColumn] tests\n\n        class ScaffoldColumnModel\n        {\n            public int NoAttribute { get; set; }\n\n            [ScaffoldColumn(true)]\n            public int ScaffoldColumnTrue { get; set; }\n\n            [ScaffoldColumn(false)]\n            public int ScaffoldColumnFalse { get; set; }\n        }\n\n        [Fact]\n        public void ScaffoldColumnAttributeSetsShowForDisplay()\n        {\n            // Arrange\n            var provider = MakeProvider();\n\n            // Act & Assert\n            Assert.True(provider.GetMetadataForProperty(null, typeof(ScaffoldColumnModel), \"NoAttribute\").ShowForDisplay);\n            Assert.True(provider.GetMetadataForProperty(null, typeof(ScaffoldColumnModel), \"ScaffoldColumnTrue\").ShowForDisplay);\n            Assert.False(provider.GetMetadataForProperty(null, typeof(ScaffoldColumnModel), \"ScaffoldColumnFalse\").ShowForDisplay);\n        }\n\n        [Fact]\n        public void ScaffoldColumnAttributeSetsShowForEdit()\n        {\n            // Arrange\n            var provider = MakeProvider();\n\n            // Act & Assert\n            Assert.True(provider.GetMetadataForProperty(null, typeof(ScaffoldColumnModel), \"NoAttribute\").ShowForEdit);\n            Assert.True(provider.GetMetadataForProperty(null, typeof(ScaffoldColumnModel), \"ScaffoldColumnTrue\").ShowForEdit);\n            Assert.False(provider.GetMetadataForProperty(null, typeof(ScaffoldColumnModel), \"ScaffoldColumnFalse\").ShowForEdit);\n        }\n\n        // [DisplayColumn] tests\n\n        [DisplayColumn(\"NoPropertyWithThisName\")]\n        class UnknownDisplayColumnModel\n        {\n        }\n\n        [Fact]\n        public void SimpleDisplayNameWithUnknownDisplayColumnThrows()\n        {\n            // Arrange\n            var provider = MakeProvider();\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => provider.GetMetadataForType(() => new UnknownDisplayColumnModel(), typeof(UnknownDisplayColumnModel)).SimpleDisplayText,\n                typeof(UnknownDisplayColumnModel).FullName + \" has a DisplayColumn attribute for NoPropertyWithThisName, but property NoPropertyWithThisName does not exist.\");\n        }\n\n        [DisplayColumn(\"WriteOnlyProperty\")]\n        class WriteOnlyDisplayColumnModel\n        {\n            public int WriteOnlyProperty\n            {\n                set { }\n            }\n        }\n\n        [DisplayColumn(\"PrivateReadPublicWriteProperty\")]\n        class PrivateReadPublicWriteDisplayColumnModel\n        {\n            public int PrivateReadPublicWriteProperty { private get; set; }\n        }\n\n        [Fact]\n        public void SimpleDisplayTextForTypeWithWriteOnlyDisplayColumnThrows()\n        {\n            // Arrange\n            var provider = MakeProvider();\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => provider.GetMetadataForType(() => new WriteOnlyDisplayColumnModel(), typeof(WriteOnlyDisplayColumnModel)).SimpleDisplayText,\n                typeof(WriteOnlyDisplayColumnModel).FullName + \" has a DisplayColumn attribute for WriteOnlyProperty, but property WriteOnlyProperty does not have a public getter.\");\n\n            Assert.Throws<InvalidOperationException>(\n                () => provider.GetMetadataForType(() => new PrivateReadPublicWriteDisplayColumnModel(), typeof(PrivateReadPublicWriteDisplayColumnModel)).SimpleDisplayText,\n                typeof(PrivateReadPublicWriteDisplayColumnModel).FullName + \" has a DisplayColumn attribute for PrivateReadPublicWriteProperty, but property PrivateReadPublicWriteProperty does not have a public getter.\");\n        }\n\n        [DisplayColumn(\"DisplayColumnProperty\")]\n        class SimpleDisplayTextAttributeModel\n        {\n            public int FirstProperty\n            {\n                get { return 42; }\n            }\n\n            [ScaffoldColumn(false)]\n            public string DisplayColumnProperty { get; set; }\n        }\n\n        class SimpleDisplayTextAttributeModelContainer\n        {\n            [DisplayFormat(NullDisplayText = \"This is the null display text\")]\n            public SimpleDisplayTextAttributeModel Inner { get; set; }\n        }\n\n        [Fact]\n        public void SimpleDisplayTextForNonNullClassWithNonNullDisplayColumnValue()\n        {\n            // Arrange\n            string expected = \"Custom property display value\";\n            var provider = MakeProvider();\n            var model = new SimpleDisplayTextAttributeModel { DisplayColumnProperty = expected };\n            var metadata = provider.GetMetadataForType(() => model, typeof(SimpleDisplayTextAttributeModel));\n\n            // Act\n            string result = metadata.SimpleDisplayText;\n\n            // Assert\n            Assert.Equal(expected, result);\n        }\n\n        [Fact]\n        public void SimpleDisplayTextForNullClassRevertsToDefaultBehavior()\n        {\n            // Arrange\n            var provider = MakeProvider();\n            var metadata = provider.GetMetadataForProperty(null, typeof(SimpleDisplayTextAttributeModelContainer), \"Inner\");\n\n            // Act\n            string result = metadata.SimpleDisplayText;\n\n            // Assert\n            Assert.Equal(\"This is the null display text\", result);\n        }\n\n        [Fact]\n        public void SimpleDisplayTextForNonNullClassWithNullDisplayColumnValueRevertsToDefaultBehavior()\n        {\n            // Arrange\n            var provider = MakeProvider();\n            var model = new SimpleDisplayTextAttributeModel();\n            var metadata = provider.GetMetadataForType(() => model, typeof(SimpleDisplayTextAttributeModel));\n\n            // Act\n            string result = metadata.SimpleDisplayText;\n\n            // Assert\n            Assert.Equal(\"42\", result); // Falls back to the default logic of first property value\n        }\n\n        // [Required] tests\n\n        class IsRequiredModel\n        {\n            public int NonNullableWithout { get; set; }\n\n            public string NullableWithout { get; set; }\n\n            [Required]\n            public string NullableWith { get; set; }\n        }\n\n        [Fact]\n        public void IsRequiredTests()\n        {\n            // Arrange\n            var provider = MakeProvider();\n\n            // Act & Assert\n            Assert.True(provider.GetMetadataForProperty(null, typeof(IsRequiredModel), \"NonNullableWithout\").IsRequired);\n            Assert.False(provider.GetMetadataForProperty(null, typeof(IsRequiredModel), \"NullableWithout\").IsRequired);\n            Assert.True(provider.GetMetadataForProperty(null, typeof(IsRequiredModel), \"NullableWith\").IsRequired);\n        }\n\n        // [Display] & [DisplayName] tests\n\n        class DisplayModel\n        {\n            public int NoAttribute { get; set; }\n\n            // Description\n\n            [Display]\n            public int DescriptionNotSet { get; set; }\n\n            [Display(Description = \"Description text\")]\n            public int DescriptionSet { get; set; }\n\n            // DisplayName\n\n            [DisplayName(\"Value from DisplayName\")]\n            public int DisplayNameAttributeNoDisplayAttribute { get; set; }\n\n            [Display]\n            public int DisplayAttributeNameNotSet { get; set; }\n\n            [Display(Name = \"Non empty name\")]\n            public int DisplayAttributeNonEmptyName { get; set; }\n\n            [Display]\n            [DisplayName(\"Value from DisplayName\")]\n            public int BothAttributesNameNotSet { get; set; }\n\n            [Display(Name = \"Value from Display\")]\n            [DisplayName(\"Value from DisplayName\")]\n            public int BothAttributes { get; set; }\n\n            // Display trumps DisplayName\n\n            // Order\n\n            [Display]\n            public int OrderNotSet { get; set; }\n\n            [Display(Order = 2112)]\n            public int OrderSet { get; set; }\n\n            // ShortDisplayName\n\n            [Display]\n            public int ShortNameNotSet { get; set; }\n\n            [Display(ShortName = \"Short name\")]\n            public int ShortNameSet { get; set; }\n\n            // Watermark\n\n            [Display]\n            public int PromptNotSet { get; set; }\n\n            [Display(Prompt = \"Enter stuff here\")]\n            public int PromptSet { get; set; }\n        }\n\n        [Fact]\n        public void DescriptionTests()\n        {\n            // Arrange\n            var provider = MakeProvider();\n\n            // Act & Assert\n            Assert.Null(provider.GetMetadataForProperty(null, typeof(DisplayModel), \"NoAttribute\").Description);\n            Assert.Null(provider.GetMetadataForProperty(null, typeof(DisplayModel), \"DescriptionNotSet\").Description);\n            Assert.Equal(\"Description text\", provider.GetMetadataForProperty(null, typeof(DisplayModel), \"DescriptionSet\").Description);\n        }\n\n        [Fact]\n        public void DisplayNameTests()\n        {\n            // Arrange\n            var provider = MakeProvider();\n\n            // Act & Assert\n            Assert.Null(provider.GetMetadataForProperty(null, typeof(DisplayModel), \"NoAttribute\").DisplayName);\n            Assert.Equal(\"Value from DisplayName\", provider.GetMetadataForProperty(null, typeof(DisplayModel), \"DisplayNameAttributeNoDisplayAttribute\").DisplayName);\n            Assert.Null(provider.GetMetadataForProperty(null, typeof(DisplayModel), \"DisplayAttributeNameNotSet\").DisplayName);\n            Assert.Equal(\"Non empty name\", provider.GetMetadataForProperty(null, typeof(DisplayModel), \"DisplayAttributeNonEmptyName\").DisplayName);\n            Assert.Equal(\"Value from DisplayName\", provider.GetMetadataForProperty(null, typeof(DisplayModel), \"BothAttributesNameNotSet\").DisplayName);\n            Assert.Equal(\"Value from Display\", provider.GetMetadataForProperty(null, typeof(DisplayModel), \"BothAttributes\").DisplayName);\n        }\n\n        [Fact]\n        public void OrderTests()\n        {\n            // Arrange\n            var provider = MakeProvider();\n\n            // Act & Assert\n            Assert.Equal(10000, provider.GetMetadataForProperty(null, typeof(DisplayModel), \"NoAttribute\").Order);\n            Assert.Equal(10000, provider.GetMetadataForProperty(null, typeof(DisplayModel), \"OrderNotSet\").Order);\n            Assert.Equal(2112, provider.GetMetadataForProperty(null, typeof(DisplayModel), \"OrderSet\").Order);\n        }\n\n        [Fact]\n        public void ShortDisplayNameTests()\n        {\n            // Arrange\n            var provider = MakeProvider();\n\n            // Act & Assert\n            Assert.Null(provider.GetMetadataForProperty(null, typeof(DisplayModel), \"NoAttribute\").ShortDisplayName);\n            Assert.Null(provider.GetMetadataForProperty(null, typeof(DisplayModel), \"ShortNameNotSet\").ShortDisplayName);\n            Assert.Equal(\"Short name\", provider.GetMetadataForProperty(null, typeof(DisplayModel), \"ShortNameSet\").ShortDisplayName);\n        }\n\n        [Fact]\n        public void WatermarkTests()\n        {\n            // Arrange\n            var provider = MakeProvider();\n\n            // Act & Assert\n            Assert.Null(provider.GetMetadataForProperty(null, typeof(DisplayModel), \"NoAttribute\").Watermark);\n            Assert.Null(provider.GetMetadataForProperty(null, typeof(DisplayModel), \"PromptNotSet\").Watermark);\n            Assert.Equal(\"Enter stuff here\", provider.GetMetadataForProperty(null, typeof(DisplayModel), \"PromptSet\").Watermark);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/DataAnnotationsModelValidatorProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing System.Web.Security;\nusing Microsoft.TestCommon;\nusing Moq;\nusing DataAnnotationsCompareAttribute = System.ComponentModel.DataAnnotations.CompareAttribute;\n\nnamespace System.Web.Mvc.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")] // Uses ModelMetadataProviders.Current\n    public class DataAnnotationsModelValidatorProviderTest\n    {\n        // Validation attribute adapter registration\n\n        private class MyValidationAttribute : ValidationAttribute\n        {\n            public override bool IsValid(object value)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class MyValidationAttributeAdapter : DataAnnotationsModelValidator<MyValidationAttribute>\n        {\n            public MyValidationAttributeAdapter(ModelMetadata metadata, ControllerContext context, MyValidationAttribute attribute)\n                : base(metadata, context, attribute)\n            {\n            }\n        }\n\n        private class MyValidationAttributeAdapterBadCtor : ModelValidator\n        {\n            public MyValidationAttributeAdapterBadCtor(ModelMetadata metadata, ControllerContext context)\n                : base(metadata, context)\n            {\n            }\n\n            public override IEnumerable<ModelValidationResult> Validate(object container)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class MyDefaultValidationAttributeAdapter : DataAnnotationsModelValidator\n        {\n            public MyDefaultValidationAttributeAdapter(ModelMetadata metadata, ControllerContext context, ValidationAttribute attribute)\n                : base(metadata, context, attribute)\n            {\n            }\n        }\n\n        [MyValidation]\n        private class MyValidatedClass\n        {\n        }\n\n        [Fact]\n        public void RegisterAdapter()\n        {\n            var oldFactories = DataAnnotationsModelValidatorProvider.AttributeFactories;\n\n            try\n            {\n                // Arrange\n                DataAnnotationsModelValidatorProvider.AttributeFactories = new Dictionary<Type, DataAnnotationsModelValidationFactory>();\n\n                // Act\n                DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyValidationAttribute), typeof(MyValidationAttributeAdapter));\n\n                // Assert\n                var type = DataAnnotationsModelValidatorProvider.AttributeFactories.Keys.Single();\n                Assert.Equal(typeof(MyValidationAttribute), type);\n\n                var factory = DataAnnotationsModelValidatorProvider.AttributeFactories.Values.Single();\n                var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => null, typeof(object));\n                var context = new ControllerContext();\n                var attribute = new MyValidationAttribute();\n                var validator = factory(metadata, context, attribute);\n                Assert.IsType<MyValidationAttributeAdapter>(validator);\n            }\n            finally\n            {\n                DataAnnotationsModelValidatorProvider.AttributeFactories = oldFactories;\n            }\n        }\n\n        [Fact]\n        public void RegisterAdapterGuardClauses()\n        {\n            // Attribute type cannot be null\n            Assert.ThrowsArgumentNull(\n                () => DataAnnotationsModelValidatorProvider.RegisterAdapter(null, typeof(MyValidationAttributeAdapter)),\n                \"attributeType\");\n\n            // Adapter type cannot be null\n            Assert.ThrowsArgumentNull(\n                () => DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyValidationAttribute), null),\n                \"adapterType\");\n\n            // Validation attribute must derive from ValidationAttribute\n            Assert.Throws<ArgumentException>(\n                () => DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(object), typeof(MyValidationAttributeAdapter)),\n                \"The type System.Object must derive from System.ComponentModel.DataAnnotations.ValidationAttribute\\r\\nParameter name: attributeType\");\n\n            // Adapter must derive from ModelValidator\n            Assert.Throws<ArgumentException>(\n                () => DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyValidationAttribute), typeof(object)),\n                \"The type System.Object must derive from System.Web.Mvc.ModelValidator\\r\\nParameter name: adapterType\");\n\n            // Adapter must have the expected constructor\n            Assert.Throws<ArgumentException>(\n                () => DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyValidationAttribute), typeof(MyValidationAttributeAdapterBadCtor)),\n                \"The type System.Web.Mvc.Test.DataAnnotationsModelValidatorProviderTest+MyValidationAttributeAdapterBadCtor must have a public constructor which accepts three parameters of types System.Web.Mvc.ModelMetadata, System.Web.Mvc.ControllerContext, and System.Web.Mvc.Test.DataAnnotationsModelValidatorProviderTest+MyValidationAttribute\\r\\nParameter name: adapterType\");\n        }\n\n        [Fact]\n        public void RegisterAdapterFactory()\n        {\n            var oldFactories = DataAnnotationsModelValidatorProvider.AttributeFactories;\n\n            try\n            {\n                // Arrange\n                DataAnnotationsModelValidatorProvider.AttributeFactories = new Dictionary<Type, DataAnnotationsModelValidationFactory>();\n                DataAnnotationsModelValidationFactory factory = delegate { return null; };\n\n                // Act\n                DataAnnotationsModelValidatorProvider.RegisterAdapterFactory(typeof(MyValidationAttribute), factory);\n\n                // Assert\n                var type = DataAnnotationsModelValidatorProvider.AttributeFactories.Keys.Single();\n                Assert.Equal(typeof(MyValidationAttribute), type);\n                Assert.Same(factory, DataAnnotationsModelValidatorProvider.AttributeFactories.Values.Single());\n            }\n            finally\n            {\n                DataAnnotationsModelValidatorProvider.AttributeFactories = oldFactories;\n            }\n        }\n\n        [Fact]\n        public void RegisterAdapterFactoryGuardClauses()\n        {\n            DataAnnotationsModelValidationFactory factory = (metadata, context, attribute) => null;\n\n            // Attribute type cannot be null\n            Assert.ThrowsArgumentNull(\n                () => DataAnnotationsModelValidatorProvider.RegisterAdapterFactory(null, factory),\n                \"attributeType\");\n\n            // Factory cannot be null\n            Assert.ThrowsArgumentNull(\n                () => DataAnnotationsModelValidatorProvider.RegisterAdapterFactory(typeof(MyValidationAttribute), null),\n                \"factory\");\n\n            // Validation attribute must derive from ValidationAttribute\n            Assert.Throws<ArgumentException>(\n                () => DataAnnotationsModelValidatorProvider.RegisterAdapterFactory(typeof(object), factory),\n                \"The type System.Object must derive from System.ComponentModel.DataAnnotations.ValidationAttribute\\r\\nParameter name: attributeType\");\n        }\n\n        [Fact]\n        public void RegisterDefaultAdapter()\n        {\n            var oldFactory = DataAnnotationsModelValidatorProvider.DefaultAttributeFactory;\n\n            try\n            {\n                // Arrange\n                var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => null, typeof(MyValidatedClass));\n                var context = new ControllerContext();\n                DataAnnotationsModelValidatorProvider.RegisterDefaultAdapter(typeof(MyDefaultValidationAttributeAdapter));\n\n                // Act\n                var result = new DataAnnotationsModelValidatorProvider().GetValidators(metadata, context).Single();\n\n                // Assert\n                Assert.IsType<MyDefaultValidationAttributeAdapter>(result);\n            }\n            finally\n            {\n                DataAnnotationsModelValidatorProvider.DefaultAttributeFactory = oldFactory;\n            }\n        }\n\n        [Fact]\n        public void RegisterDefaultAdapterGuardClauses()\n        {\n            // Adapter type cannot be null\n            Assert.ThrowsArgumentNull(\n                () => DataAnnotationsModelValidatorProvider.RegisterDefaultAdapter(null),\n                \"adapterType\");\n\n            // Adapter must derive from ModelValidator\n            Assert.Throws<ArgumentException>(\n                () => DataAnnotationsModelValidatorProvider.RegisterDefaultAdapter(typeof(object)),\n                \"The type System.Object must derive from System.Web.Mvc.ModelValidator\\r\\nParameter name: adapterType\");\n\n            // Adapter must have the expected constructor\n            Assert.Throws<ArgumentException>(\n                () => DataAnnotationsModelValidatorProvider.RegisterDefaultAdapter(typeof(MyValidationAttributeAdapterBadCtor)),\n                \"The type System.Web.Mvc.Test.DataAnnotationsModelValidatorProviderTest+MyValidationAttributeAdapterBadCtor must have a public constructor which accepts three parameters of types System.Web.Mvc.ModelMetadata, System.Web.Mvc.ControllerContext, and System.ComponentModel.DataAnnotations.ValidationAttribute\\r\\nParameter name: adapterType\");\n        }\n\n        [Fact]\n        public void RegisterDefaultAdapterFactory()\n        {\n            var oldFactory = DataAnnotationsModelValidatorProvider.DefaultAttributeFactory;\n\n            try\n            {\n                // Arrange\n                var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => null, typeof(MyValidatedClass));\n                var context = new ControllerContext();\n                ModelValidator validator = new Mock<ModelValidator>(metadata, context).Object;\n                DataAnnotationsModelValidationFactory factory = delegate { return validator; };\n                DataAnnotationsModelValidatorProvider.RegisterDefaultAdapterFactory(factory);\n\n                // Act\n                var result = new DataAnnotationsModelValidatorProvider().GetValidators(metadata, context).Single();\n\n                // Assert\n                Assert.Same(validator, result);\n            }\n            finally\n            {\n                DataAnnotationsModelValidatorProvider.DefaultAttributeFactory = oldFactory;\n            }\n        }\n\n        [Fact]\n        public void RegisterDefaultAdapterFactoryGuardClauses()\n        {\n            // Factory cannot be null\n            Assert.ThrowsArgumentNull(\n                () => DataAnnotationsModelValidatorProvider.RegisterDefaultAdapterFactory(null),\n                \"factory\");\n        }\n\n        // IValidatableObject adapter registration\n\n        private class MyValidatableAdapter : ModelValidator\n        {\n            public MyValidatableAdapter(ModelMetadata metadata, ControllerContext context)\n                : base(metadata, context)\n            {\n            }\n\n            public override IEnumerable<ModelValidationResult> Validate(object container)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class MyValidatableAdapterBadCtor : ModelValidator\n        {\n            public MyValidatableAdapterBadCtor(ModelMetadata metadata, ControllerContext context, int unused)\n                : base(metadata, context)\n            {\n            }\n\n            public override IEnumerable<ModelValidationResult> Validate(object container)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class MyValidatableClass : IValidatableObject\n        {\n            public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        [Fact]\n        public void RegisterValidatableObjectAdapter()\n        {\n            var oldFactories = DataAnnotationsModelValidatorProvider.ValidatableFactories;\n\n            try\n            {\n                // Arrange\n                DataAnnotationsModelValidatorProvider.ValidatableFactories = new Dictionary<Type, DataAnnotationsValidatableObjectAdapterFactory>();\n                IValidatableObject validatable = new Mock<IValidatableObject>().Object;\n\n                // Act\n                DataAnnotationsModelValidatorProvider.RegisterValidatableObjectAdapter(validatable.GetType(), typeof(MyValidatableAdapter));\n\n                // Assert\n                var type = DataAnnotationsModelValidatorProvider.ValidatableFactories.Keys.Single();\n                Assert.Equal(validatable.GetType(), type);\n\n                var factory = DataAnnotationsModelValidatorProvider.ValidatableFactories.Values.Single();\n                var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => null, typeof(object));\n                var context = new ControllerContext();\n                var validator = factory(metadata, context);\n                Assert.IsType<MyValidatableAdapter>(validator);\n            }\n            finally\n            {\n                DataAnnotationsModelValidatorProvider.ValidatableFactories = oldFactories;\n            }\n        }\n\n        [Fact]\n        public void RegisterValidatableObjectAdapterGuardClauses()\n        {\n            // Attribute type cannot be null\n            Assert.ThrowsArgumentNull(\n                () => DataAnnotationsModelValidatorProvider.RegisterValidatableObjectAdapter(null, typeof(MyValidatableAdapter)),\n                \"modelType\");\n\n            // Adapter type cannot be null\n            Assert.ThrowsArgumentNull(\n                () => DataAnnotationsModelValidatorProvider.RegisterValidatableObjectAdapter(typeof(MyValidatableClass), null),\n                \"adapterType\");\n\n            // Validation attribute must derive from ValidationAttribute\n            Assert.Throws<ArgumentException>(\n                () => DataAnnotationsModelValidatorProvider.RegisterValidatableObjectAdapter(typeof(object), typeof(MyValidatableAdapter)),\n                \"The type System.Object must derive from System.ComponentModel.DataAnnotations.IValidatableObject\\r\\nParameter name: modelType\");\n\n            // Adapter must derive from ModelValidator\n            Assert.Throws<ArgumentException>(\n                () => DataAnnotationsModelValidatorProvider.RegisterValidatableObjectAdapter(typeof(MyValidatableClass), typeof(object)),\n                \"The type System.Object must derive from System.Web.Mvc.ModelValidator\\r\\nParameter name: adapterType\");\n\n            // Adapter must have the expected constructor\n            Assert.Throws<ArgumentException>(\n                () => DataAnnotationsModelValidatorProvider.RegisterValidatableObjectAdapter(typeof(MyValidatableClass), typeof(MyValidatableAdapterBadCtor)),\n                \"The type System.Web.Mvc.Test.DataAnnotationsModelValidatorProviderTest+MyValidatableAdapterBadCtor must have a public constructor which accepts two parameters of types System.Web.Mvc.ModelMetadata and System.Web.Mvc.ControllerContext.\\r\\nParameter name: adapterType\");\n        }\n\n        [Fact]\n        public void RegisterValidatableObjectAdapterFactory()\n        {\n            var oldFactories = DataAnnotationsModelValidatorProvider.ValidatableFactories;\n\n            try\n            {\n                // Arrange\n                DataAnnotationsModelValidatorProvider.ValidatableFactories = new Dictionary<Type, DataAnnotationsValidatableObjectAdapterFactory>();\n                DataAnnotationsValidatableObjectAdapterFactory factory = delegate { return null; };\n\n                // Act\n                DataAnnotationsModelValidatorProvider.RegisterValidatableObjectAdapterFactory(typeof(MyValidatableClass), factory);\n\n                // Assert\n                var type = DataAnnotationsModelValidatorProvider.ValidatableFactories.Keys.Single();\n                Assert.Equal(typeof(MyValidatableClass), type);\n                Assert.Same(factory, DataAnnotationsModelValidatorProvider.ValidatableFactories.Values.Single());\n            }\n            finally\n            {\n                DataAnnotationsModelValidatorProvider.ValidatableFactories = oldFactories;\n            }\n        }\n\n        [Fact]\n        public void RegisterValidatableObjectAdapterFactoryGuardClauses()\n        {\n            DataAnnotationsValidatableObjectAdapterFactory factory = (metadata, context) => null;\n\n            // Attribute type cannot be null\n            Assert.ThrowsArgumentNull(\n                () => DataAnnotationsModelValidatorProvider.RegisterValidatableObjectAdapterFactory(null, factory),\n                \"modelType\");\n\n            // Factory cannot be null\n            Assert.ThrowsArgumentNull(\n                () => DataAnnotationsModelValidatorProvider.RegisterValidatableObjectAdapterFactory(typeof(MyValidatableClass), null),\n                \"factory\");\n\n            // Validation attribute must derive from ValidationAttribute\n            Assert.Throws<ArgumentException>(\n                () => DataAnnotationsModelValidatorProvider.RegisterValidatableObjectAdapterFactory(typeof(object), factory),\n                \"The type System.Object must derive from System.ComponentModel.DataAnnotations.IValidatableObject\\r\\nParameter name: modelType\");\n        }\n\n        [Fact]\n        public void RegisterDefaultValidatableObjectAdapter()\n        {\n            var oldFactory = DataAnnotationsModelValidatorProvider.DefaultValidatableFactory;\n\n            try\n            {\n                // Arrange\n                var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => null, typeof(MyValidatableClass));\n                var context = new ControllerContext();\n                DataAnnotationsModelValidatorProvider.RegisterDefaultValidatableObjectAdapter(typeof(MyValidatableAdapter));\n\n                // Act\n                var result = new DataAnnotationsModelValidatorProvider().GetValidators(metadata, context).Single();\n\n                // Assert\n                Assert.IsType<MyValidatableAdapter>(result);\n            }\n            finally\n            {\n                DataAnnotationsModelValidatorProvider.DefaultValidatableFactory = oldFactory;\n            }\n        }\n\n        [Fact]\n        public void RegisterDefaultValidatableObjectAdapterGuardClauses()\n        {\n            // Adapter type cannot be null\n            Assert.ThrowsArgumentNull(\n                () => DataAnnotationsModelValidatorProvider.RegisterDefaultValidatableObjectAdapter(null),\n                \"adapterType\");\n\n            // Adapter must derive from ModelValidator\n            Assert.Throws<ArgumentException>(\n                () => DataAnnotationsModelValidatorProvider.RegisterDefaultValidatableObjectAdapter(typeof(object)),\n                \"The type System.Object must derive from System.Web.Mvc.ModelValidator\\r\\nParameter name: adapterType\");\n\n            // Adapter must have the expected constructor\n            Assert.Throws<ArgumentException>(\n                () => DataAnnotationsModelValidatorProvider.RegisterDefaultValidatableObjectAdapter(typeof(MyValidatableAdapterBadCtor)),\n                \"The type System.Web.Mvc.Test.DataAnnotationsModelValidatorProviderTest+MyValidatableAdapterBadCtor must have a public constructor which accepts two parameters of types System.Web.Mvc.ModelMetadata and System.Web.Mvc.ControllerContext.\\r\\nParameter name: adapterType\");\n        }\n\n        [Fact]\n        public void RegisterDefaultValidatableObjectAdapterFactory()\n        {\n            var oldFactory = DataAnnotationsModelValidatorProvider.DefaultValidatableFactory;\n\n            try\n            {\n                // Arrange\n                var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => null, typeof(MyValidatableClass));\n                var context = new ControllerContext();\n                ModelValidator validator = new Mock<ModelValidator>(metadata, context).Object;\n                DataAnnotationsValidatableObjectAdapterFactory factory = delegate { return validator; };\n                DataAnnotationsModelValidatorProvider.RegisterDefaultValidatableObjectAdapterFactory(factory);\n\n                // Act\n                var result = new DataAnnotationsModelValidatorProvider().GetValidators(metadata, context).Single();\n\n                // Assert\n                Assert.Same(validator, result);\n            }\n            finally\n            {\n                DataAnnotationsModelValidatorProvider.DefaultValidatableFactory = oldFactory;\n            }\n        }\n\n        [Fact]\n        public void RegisterDefaultValidatableObjectAdapterFactoryGuardClauses()\n        {\n            // Factory cannot be null\n            Assert.ThrowsArgumentNull(\n                () => DataAnnotationsModelValidatorProvider.RegisterDefaultValidatableObjectAdapterFactory(null),\n                \"factory\");\n        }\n\n        // Pre-configured adapters\n\n        public static TheoryDataSet<Type, ValidationAttribute, Type, string> KnownAdapterTypeData\n        {\n            get\n            {\n                return new TheoryDataSet<Type, ValidationAttribute, Type, string>\n                {\n                    { typeof(RangeAttribute), new RangeAttribute(1, 100), typeof(RangeAttributeAdapter), null },\n                    { typeof(RegularExpressionAttribute), new RegularExpressionAttribute(\"abc\"), typeof(RegularExpressionAttributeAdapter), null },\n                    { typeof(RequiredAttribute), new RequiredAttribute(), typeof(RequiredAttributeAdapter), null },\n                    { typeof(StringLengthAttribute), new StringLengthAttribute(6), typeof(StringLengthAttributeAdapter), null },\n                    { typeof(MaxLengthAttribute), new MaxLengthAttribute(), typeof(MaxLengthAttributeAdapter), null },\n                    { typeof(MinLengthAttribute), new MinLengthAttribute(1), typeof(MinLengthAttributeAdapter), null },\n                    { typeof(MembershipPasswordAttribute), new MembershipPasswordAttribute(), typeof(MembershipPasswordAttributeAdapter), null },\n                    { typeof(DataAnnotationsCompareAttribute), new DataAnnotationsCompareAttribute(\"other\"), typeof(CompareAttributeAdapter), null },\n                    { typeof(FileExtensionsAttribute), new FileExtensionsAttribute(), typeof(FileExtensionsAttributeAdapter), null },\n                    { typeof(CreditCardAttribute), new CreditCardAttribute(), typeof(DataTypeAttributeAdapter), \"creditcard\" },\n                    { typeof(EmailAddressAttribute), new EmailAddressAttribute(), typeof(DataTypeAttributeAdapter), \"email\" },\n                    { typeof(PhoneAttribute), new PhoneAttribute(), typeof(DataTypeAttributeAdapter), \"phone\" },\n                    { typeof(UrlAttribute), new UrlAttribute(), typeof(DataTypeAttributeAdapter), \"url\" },\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"KnownAdapterTypeData\")]\n        public void AdapterForKnownTypeRegistered(Type attributeType, ValidationAttribute validationAttr,\n            Type expectedAdapterType, string expectedRuleName)\n        {\n            // Arrange\n            var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => null, typeof(object));\n            var context = new ControllerContext();\n            var adapters = DataAnnotationsModelValidatorProvider.AttributeFactories;\n            var adapterFactory = adapters.Single(kvp => kvp.Key == attributeType).Value;\n\n            // Act\n            var adapter = adapterFactory(metadata, context, validationAttr);\n\n            // Assert\n            Assert.IsType(expectedAdapterType, adapter);\n            if (expectedRuleName != null)\n            {\n                DataTypeAttributeAdapter dataTypeAdapter = adapter as DataTypeAttributeAdapter;\n                Assert.NotNull(dataTypeAdapter);\n                Assert.Equal(expectedRuleName, dataTypeAdapter.RuleName);\n            }\n        }\n\n        // Default adapter factory for unknown attribute type\n\n        [Fact]\n        public void UnknownValidationAttributeGetsDefaultAdapter()\n        {\n            // Arrange\n            var provider = new DataAnnotationsModelValidatorProvider();\n            var context = new ControllerContext();\n            var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => null, typeof(DummyClassWithDummyValidationAttribute));\n\n            // Act\n            IEnumerable<ModelValidator> validators = provider.GetValidators(metadata, context);\n\n            // Assert\n            var validator = validators.Single();\n            Assert.IsType<DataAnnotationsModelValidator>(validator);\n        }\n\n        private class DummyValidationAttribute : ValidationAttribute\n        {\n        }\n\n        [DummyValidation]\n        private class DummyClassWithDummyValidationAttribute\n        {\n        }\n\n        // Default IValidatableObject adapter factory\n\n        [Fact]\n        public void IValidatableObjectGetsAValidator()\n        {\n            // Arrange\n            var provider = new DataAnnotationsModelValidatorProvider();\n            var mockValidatable = new Mock<IValidatableObject>();\n            var context = new ControllerContext();\n            var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => null, mockValidatable.Object.GetType());\n\n            // Act\n            IEnumerable<ModelValidator> validators = provider.GetValidators(metadata, context);\n\n            // Assert\n            Assert.Single(validators);\n        }\n\n        // Implicit [Required] attribute\n\n        [Fact]\n        public void ReferenceTypesDontGetImplicitRequiredAttribute()\n        {\n            // Arrange\n            var provider = new DataAnnotationsModelValidatorProvider();\n            var context = new ControllerContext();\n            var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => null, typeof(string));\n\n            // Act\n            IEnumerable<ModelValidator> validators = provider.GetValidators(metadata, context);\n\n            // Assert\n            Assert.Empty(validators);\n        }\n\n        [Fact]\n        public void NonNullableValueTypesGetImplicitRequiredAttribute()\n        {\n            // Arrange\n            var provider = new DataAnnotationsModelValidatorProvider();\n            var context = new ControllerContext();\n            var metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => null, typeof(DummyRequiredAttributeHelperClass), \"WithoutAttribute\");\n\n            // Act\n            IEnumerable<ModelValidator> validators = provider.GetValidators(metadata, context);\n\n            // Assert\n            ModelValidator validator = validators.Single();\n            ModelClientValidationRule rule = validator.GetClientValidationRules().Single();\n            Assert.IsType<ModelClientValidationRequiredRule>(rule);\n        }\n\n        [Fact]\n        public void NonNullableValueTypesWithExplicitRequiredAttributeDoesntGetImplictRequiredAttribute()\n        {\n            // Arrange\n            var provider = new DataAnnotationsModelValidatorProvider();\n            var context = new ControllerContext();\n            var metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => null, typeof(DummyRequiredAttributeHelperClass), \"WithAttribute\");\n\n            // Act\n            IEnumerable<ModelValidator> validators = provider.GetValidators(metadata, context);\n\n            // Assert\n            ModelValidator validator = validators.Single();\n            ModelClientValidationRule rule = validator.GetClientValidationRules().Single();\n            Assert.IsType<ModelClientValidationRequiredRule>(rule);\n            Assert.Equal(\"Custom Required Message\", rule.ErrorMessage);\n        }\n\n        [Fact]\n        public void NonNullableValueTypeDoesntGetImplicitRequiredAttributeWhenFlagIsOff()\n        {\n            DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;\n\n            try\n            {\n                // Arrange\n                var provider = new DataAnnotationsModelValidatorProvider();\n                var context = new ControllerContext();\n                var metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => null, typeof(DummyRequiredAttributeHelperClass), \"WithoutAttribute\");\n\n                // Act\n                IEnumerable<ModelValidator> validators = provider.GetValidators(metadata, context);\n\n                // Assert\n                Assert.Empty(validators);\n            }\n            finally\n            {\n                DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = true;\n            }\n        }\n\n        private class DummyRequiredAttributeHelperClass\n        {\n            [Required(ErrorMessage = \"Custom Required Message\")]\n            public int WithAttribute { get; set; }\n\n            public int WithoutAttribute { get; set; }\n        }\n\n        // Integration with metadata system\n\n        [Fact]\n        public void DoesNotReadPropertyValue()\n        {\n            // Arrange\n            ObservableModel model = new ObservableModel();\n            ModelMetadata metadata = new DataAnnotationsModelMetadataProvider().GetMetadataForProperty(() => model.TheProperty, typeof(ObservableModel), \"TheProperty\");\n            ControllerContext controllerContext = new ControllerContext();\n\n            // Act\n            ModelValidator[] validators = new DataAnnotationsModelValidatorProvider().GetValidators(metadata, controllerContext).ToArray();\n            ModelValidationResult[] results = validators.SelectMany(o => o.Validate(model)).ToArray();\n\n            // Assert\n            Assert.Empty(validators);\n            Assert.False(model.PropertyWasRead());\n        }\n\n        private class ObservableModel\n        {\n            private bool _propertyWasRead;\n\n            public string TheProperty\n            {\n                get\n                {\n                    _propertyWasRead = true;\n                    return \"Hello\";\n                }\n            }\n\n            public bool PropertyWasRead()\n            {\n                return _propertyWasRead;\n            }\n        }\n\n        private class BaseModel\n        {\n            public virtual string MyProperty { get; set; }\n        }\n\n        private class DerivedModel : BaseModel\n        {\n            [StringLength(10)]\n            public override string MyProperty\n            {\n                get { return base.MyProperty; }\n                set { base.MyProperty = value; }\n            }\n\n            [MinLength(2)]\n            [MaxLength(4)]\n            public List<DateTime> MinMaxProperty { get; set; }\n        }\n\n        [Fact]\n        public void GetValidatorsReturnsClientValidatorForDerivedTypeAppliedAgainstBaseTypeViaFromLambdaExpression()\n        { // Dev10 Bug #868619\n            // Arrange\n            var provider = new DataAnnotationsModelValidatorProvider();\n            var context = new ControllerContext();\n            var viewdata = new ViewDataDictionary<DerivedModel>();\n            var metadata = ModelMetadata.FromLambdaExpression(m => m.MyProperty, viewdata); // Bug is in FromLambdaExpression\n\n            // Act\n            IEnumerable<ModelValidator> validators = provider.GetValidators(metadata, context);\n\n            // Assert\n            ModelValidator validator = validators.Single();\n            ModelClientValidationRule clientRule = validator.GetClientValidationRules().Single();\n            Assert.IsType<ModelClientValidationStringLengthRule>(clientRule);\n            Assert.Equal(10, clientRule.ValidationParameters[\"max\"]);\n        }\n\n        [Fact]\n        public void GetValidatorsReturnsValidationRulesForPropertiesWithMinAndMaxLength()\n        { // Dev10 Bug #868619\n            // Arrange\n            var provider = new DataAnnotationsModelValidatorProvider();\n            var context = new ControllerContext();\n            var viewdata = new ViewDataDictionary<DerivedModel>();\n            var metadata = ModelMetadata.FromLambdaExpression(m => m.MinMaxProperty, viewdata);\n\n            // Act\n            IEnumerable<ModelValidator> validators = provider.GetValidators(metadata, context);\n\n            // Assert\n            ModelClientValidationRule[] clientRule = validators.SelectMany(v => v.GetClientValidationRules())\n                                                               .OrderBy(t => t.GetType().Name)\n                                                               .ToArray();\n            Assert.IsType<ModelClientValidationMaxLengthRule>(clientRule[0]);\n            Assert.IsType<ModelClientValidationMinLengthRule>(clientRule[1]);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/DataAnnotationsModelValidatorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\nusing Moq.Protected;\n\nnamespace System.Web.Mvc.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")] // Uses ModelMetadataProviders.Current\n    public class DataAnnotationsModelValidatorTest\n    {\n        [Fact]\n        public void ConstructorGuards()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(object));\n            ControllerContext context = new ControllerContext();\n            RequiredAttribute attribute = new RequiredAttribute();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => new DataAnnotationsModelValidator(null, context, attribute),\n                \"metadata\");\n            Assert.ThrowsArgumentNull(\n                () => new DataAnnotationsModelValidator(metadata, null, attribute),\n                \"controllerContext\");\n            Assert.ThrowsArgumentNull(\n                () => new DataAnnotationsModelValidator(metadata, context, null),\n                \"attribute\");\n        }\n\n        [Fact]\n        public void ValuesSet()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => 15, typeof(string), \"Length\");\n            ControllerContext context = new ControllerContext();\n            RequiredAttribute attribute = new RequiredAttribute();\n\n            // Act\n            DataAnnotationsModelValidator validator = new DataAnnotationsModelValidator(metadata, context, attribute);\n\n            // Assert\n            Assert.Same(attribute, validator.Attribute);\n            Assert.Equal(attribute.FormatErrorMessage(\"Length\"), validator.ErrorMessage);\n        }\n\n        public static TheoryDataSet<ModelMetadata, string> ValidateSetsMemberNamePropertyDataSet\n        {\n            get\n            {\n                return new TheoryDataSet<ModelMetadata, string>\n                {\n                    {\n                        ModelMetadataProviders.Current.GetMetadataForProperty(() => 15, typeof(string), \"Length\"),\n                        \"Length\"\n                    },\n                    {\n                        ModelMetadataProviders.Current.GetMetadataForType(() => new object(), typeof(SampleModel)),\n                        \"SampleModel\"\n                    }\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"ValidateSetsMemberNamePropertyDataSet\")]\n        public void ValidateSetsMemberNamePropertyOfValidationContextForProperties(ModelMetadata metadata, string expectedMemberName)\n        {\n            // Arrange\n            metadata.DisplayName = \"Some-random-name\";\n            ControllerContext context = new ControllerContext();\n            var attribute = new Mock<ValidationAttribute> { CallBase = true };\n            attribute.Protected()\n                     .Setup<ValidationResult>(\"IsValid\", ItExpr.IsAny<object>(), ItExpr.IsAny<ValidationContext>())\n                     .Callback((object o, ValidationContext validationContext) =>\n                     {\n                         Assert.Equal(expectedMemberName, validationContext.MemberName);\n                     })\n                     .Returns(ValidationResult.Success)\n                     .Verifiable();\n            DataAnnotationsModelValidator validator = new DataAnnotationsModelValidator(metadata, context, attribute.Object);\n\n            // Act\n            IEnumerable<ModelValidationResult> results = validator.Validate(container: null);\n\n            // Assert\n            Assert.Empty(results);\n            attribute.VerifyAll();\n        }\n\n        [Fact]\n        public void NoClientRulesByDefault()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => 15, typeof(string), \"Length\");\n            ControllerContext context = new ControllerContext();\n            RequiredAttribute attribute = new RequiredAttribute();\n\n            // Act\n            DataAnnotationsModelValidator validator = new DataAnnotationsModelValidator(metadata, context, attribute);\n\n            // Assert\n            Assert.Empty(validator.GetClientValidationRules());\n        }\n\n        [Fact]\n        public void ValidateWithIsValidTrue()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => 15, typeof(string), \"Length\");\n            ControllerContext context = new ControllerContext();\n            Mock<ValidationAttribute> attribute = new Mock<ValidationAttribute> { CallBase = true };\n            attribute.Setup(a => a.IsValid(metadata.Model)).Returns(true);\n            DataAnnotationsModelValidator validator = new DataAnnotationsModelValidator(metadata, context, attribute.Object);\n\n            // Act\n            IEnumerable<ModelValidationResult> result = validator.Validate(null);\n\n            // Assert\n            Assert.Empty(result);\n        }\n\n        [Fact]\n        public void ValidateWithIsValidFalse()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => 15, typeof(string), \"Length\");\n            ControllerContext context = new ControllerContext();\n            Mock<ValidationAttribute> attribute = new Mock<ValidationAttribute> { CallBase = true };\n            attribute.Setup(a => a.IsValid(metadata.Model)).Returns(false);\n            DataAnnotationsModelValidator validator = new DataAnnotationsModelValidator(metadata, context, attribute.Object);\n\n            // Act\n            IEnumerable<ModelValidationResult> result = validator.Validate(null);\n\n            // Assert\n            var validationResult = result.Single();\n            Assert.Equal(\"\", validationResult.MemberName);\n            Assert.Equal(attribute.Object.FormatErrorMessage(\"Length\"), validationResult.Message);\n        }\n\n        [Fact]\n        public void ValidatateWithValidationResultSuccess()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => 15, typeof(string), \"Length\");\n            ControllerContext context = new ControllerContext();\n            Mock<ValidationAttribute> attribute = new Mock<ValidationAttribute> { CallBase = true };\n            attribute.Protected()\n                .Setup<ValidationResult>(\"IsValid\", ItExpr.IsAny<object>(), ItExpr.IsAny<ValidationContext>())\n                .Returns(ValidationResult.Success);\n            DataAnnotationsModelValidator validator = new DataAnnotationsModelValidator(metadata, context, attribute.Object);\n\n            // Act\n            IEnumerable<ModelValidationResult> result = validator.Validate(null);\n\n            // Assert\n            Assert.Empty(result);\n        }\n\n        [Fact]\n        public void ValidateReturnsSingleValidationResultIfMemberNameSequenceIsEmpty()\n        {\n            // Arrange\n            const string errorMessage = \"Some error message\";\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => 15, typeof(string), \"Length\");\n            ControllerContext context = new ControllerContext();\n            Mock<ValidationAttribute> attribute = new Mock<ValidationAttribute> { CallBase = true };\n            attribute.Protected()\n                     .Setup<ValidationResult>(\"IsValid\", ItExpr.IsAny<object>(), ItExpr.IsAny<ValidationContext>())\n                     .Returns(new ValidationResult(errorMessage, memberNames: null));\n            var validator = new DataAnnotationsModelValidator(metadata, context, attribute.Object);\n\n            // Act\n            IEnumerable<ModelValidationResult> results = validator.Validate(container: null);\n\n            // Assert\n            ModelValidationResult validationResult = Assert.Single(results);\n            Assert.Equal(errorMessage, validationResult.Message);\n            Assert.Empty(validationResult.MemberName);\n        }\n\n        [Fact]\n        public void ValidateReturnsSingleValidationResultIfOneMemberNameIsSpecified()\n        {\n            // Arrange\n            const string errorMessage = \"A different error message\";\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(() => new object(), typeof(object));\n            ControllerContext context = new ControllerContext();\n            Mock<ValidationAttribute> attribute = new Mock<ValidationAttribute> { CallBase = true };\n            attribute.Protected()\n                     .Setup<ValidationResult>(\"IsValid\", ItExpr.IsAny<object>(), ItExpr.IsAny<ValidationContext>())\n                     .Returns(new ValidationResult(errorMessage, new[] { \"FirstName\" }));\n            var validator = new DataAnnotationsModelValidator(metadata, context, attribute.Object);\n\n            // Act\n            IEnumerable<ModelValidationResult> results = validator.Validate(container: null);\n\n            // Assert\n            ModelValidationResult validationResult = Assert.Single(results);\n            Assert.Equal(errorMessage, validationResult.Message);\n            Assert.Equal(\"FirstName\", validationResult.MemberName);\n        }\n\n        [Fact]\n        public void ValidateReturnsMemberNameIfItIsDifferentFromDisplayName()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(() => new SampleModel(), typeof(SampleModel));\n            ControllerContext context = new ControllerContext();\n            Mock<ValidationAttribute> attribute = new Mock<ValidationAttribute> { CallBase = true };\n            attribute.Protected()\n                     .Setup<ValidationResult>(\"IsValid\", ItExpr.IsAny<object>(), ItExpr.IsAny<ValidationContext>())\n                     .Returns(new ValidationResult(\"Name error\", new[] { \"Name\" }));\n            DataAnnotationsModelValidator validator = new DataAnnotationsModelValidator(metadata, context, attribute.Object);\n\n            // Act\n            IEnumerable<ModelValidationResult> results = validator.Validate(container: null);\n\n            // Assert\n            ModelValidationResult validationResult = Assert.Single(results);\n            Assert.Equal(\"Name\", validationResult.MemberName);\n        }\n\n        [Fact]\n        public void IsRequiredTests()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => 15, typeof(string), \"Length\");\n            ControllerContext context = new ControllerContext();\n\n            // Act & Assert\n            Assert.False(new DataAnnotationsModelValidator(metadata, context, new RangeAttribute(10, 20)).IsRequired);\n            Assert.True(new DataAnnotationsModelValidator(metadata, context, new RequiredAttribute()).IsRequired);\n            Assert.True(new DataAnnotationsModelValidator(metadata, context, new DerivedRequiredAttribute()).IsRequired);\n        }\n\n        [Fact]\n        public void AttributeWithIClientValidatableGetsClientValidationRules()\n        {\n            // Arrange\n            var expected = new ModelClientValidationStringLengthRule(\"Error\", 1, 10);\n            var context = new ControllerContext();\n            var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => null, typeof(string));\n            var attribute = new Mock<ValidationAttribute> { CallBase = true };\n            attribute.As<IClientValidatable>()\n                .Setup(cv => cv.GetClientValidationRules(metadata, context))\n                .Returns(new[] { expected })\n                .Verifiable();\n            var validator = new DataAnnotationsModelValidator(metadata, context, attribute.Object);\n\n            // Act\n            ModelClientValidationRule actual = validator.GetClientValidationRules().Single();\n\n            // Assert\n            attribute.Verify();\n            Assert.Same(expected, actual);\n        }\n\n        class DerivedRequiredAttribute : RequiredAttribute\n        {\n        }\n\n        class SampleModel\n        {\n            public string Name { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/DataErrorInfoModelValidatorProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class DataErrorInfoModelValidatorProviderTest\n    {\n        private static readonly EmptyModelMetadataProvider _metadataProvider = new EmptyModelMetadataProvider();\n\n        [Fact]\n        public void GetValidatorsReturnsEmptyCollectionIfTypeNotIDataErrorInfo()\n        {\n            // Arrange\n            DataErrorInfoModelValidatorProvider validatorProvider = new DataErrorInfoModelValidatorProvider();\n            object model = new object();\n            ModelMetadata metadata = _metadataProvider.GetMetadataForType(() => model, typeof(object));\n\n            // Act\n            ModelValidator[] validators = validatorProvider.GetValidators(metadata, new ControllerContext()).ToArray();\n\n            // Assert\n            Assert.Empty(validators);\n        }\n\n        [Fact]\n        public void GetValidatorsReturnsValidatorForIDataErrorInfoProperty()\n        {\n            // Arrange\n            DataErrorInfoModelValidatorProvider validatorProvider = new DataErrorInfoModelValidatorProvider();\n            DataErrorInfo1 model = new DataErrorInfo1();\n            ModelMetadata metadata = _metadataProvider.GetMetadataForProperty(() => model, typeof(DataErrorInfo1), \"SomeStringProperty\");\n            Type[] expectedTypes = new Type[]\n            {\n                typeof(DataErrorInfoModelValidatorProvider.DataErrorInfoPropertyModelValidator)\n            };\n\n            // Act\n            Type[] actualTypes = validatorProvider.GetValidators(metadata, new ControllerContext()).Select(v => v.GetType()).ToArray();\n\n            // Assert\n            Assert.Equal(expectedTypes, actualTypes);\n        }\n\n        [Fact]\n        public void GetValidatorsReturnsValidatorForIDataErrorInfoRootType()\n        {\n            // Arrange\n            DataErrorInfoModelValidatorProvider validatorProvider = new DataErrorInfoModelValidatorProvider();\n            DataErrorInfo1 model = new DataErrorInfo1();\n            ModelMetadata metadata = _metadataProvider.GetMetadataForType(() => model, typeof(DataErrorInfo1));\n            Type[] expectedTypes = new Type[]\n            {\n                typeof(DataErrorInfoModelValidatorProvider.DataErrorInfoClassModelValidator)\n            };\n\n            // Act\n            Type[] actualTypes = validatorProvider.GetValidators(metadata, new ControllerContext()).Select(v => v.GetType()).ToArray();\n\n            // Assert\n            Assert.Equal(expectedTypes, actualTypes);\n        }\n\n        [Fact]\n        public void GetValidatorsThrowsIfContextIsNull()\n        {\n            // Arrange\n            DataErrorInfoModelValidatorProvider validatorProvider = new DataErrorInfoModelValidatorProvider();\n            ModelMetadata metadata = _metadataProvider.GetMetadataForType(null, typeof(DataErrorInfo1));\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { validatorProvider.GetValidators(metadata, null); }, \"context\");\n        }\n\n        [Fact]\n        public void GetValidatorsThrowsIfMetadataIsNull()\n        {\n            // Arrange\n            DataErrorInfoModelValidatorProvider validatorProvider = new DataErrorInfoModelValidatorProvider();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { validatorProvider.GetValidators(null, new ControllerContext()); }, \"metadata\");\n        }\n\n        [Fact]\n        public void ClassValidator_Validate_IDataErrorInfoModelWithError()\n        {\n            // Arrange\n            DataErrorInfo1 model = new DataErrorInfo1()\n            {\n                Error = \"This is an error message.\"\n            };\n            ModelMetadata metadata = _metadataProvider.GetMetadataForType(() => model, typeof(DataErrorInfo1));\n\n            var validator = new DataErrorInfoModelValidatorProvider.DataErrorInfoClassModelValidator(metadata, new ControllerContext());\n\n            // Act\n            ModelValidationResult[] result = validator.Validate(null).ToArray();\n\n            // Assert\n            ModelValidationResult modelValidationResult = Assert.Single(result);\n            Assert.Equal(\"This is an error message.\", modelValidationResult.Message);\n        }\n\n        [Fact]\n        public void ClassValidator_Validate_IDataErrorInfoModelWithNoErrorReturnsEmptyResults()\n        {\n            // Arrange\n            DataErrorInfo1 model = new DataErrorInfo1();\n            ModelMetadata metadata = _metadataProvider.GetMetadataForType(() => model, typeof(DataErrorInfo1));\n\n            var validator = new DataErrorInfoModelValidatorProvider.DataErrorInfoClassModelValidator(metadata, new ControllerContext());\n\n            // Act\n            ModelValidationResult[] result = validator.Validate(null).ToArray();\n\n            // Assert\n            Assert.Empty(result);\n        }\n\n        [Fact]\n        public void ClassValidator_Validate_NonIDataErrorInfoModelReturnsEmptyResults()\n        {\n            // Arrange\n            object model = new object();\n            ModelMetadata metadata = _metadataProvider.GetMetadataForType(() => model, typeof(object));\n\n            var validator = new DataErrorInfoModelValidatorProvider.DataErrorInfoClassModelValidator(metadata, new ControllerContext());\n\n            // Act\n            ModelValidationResult[] result = validator.Validate(null).ToArray();\n\n            // Assert\n            Assert.Empty(result);\n        }\n\n        [Fact]\n        public void PropertyValidator_Validate_IDataErrorInfoSkipsErrorProperty()\n        {\n            // Arrange\n            DataErrorInfo1 container = new DataErrorInfo1();\n            container[\"Error\"] = \"This should never be shown.\";\n            ModelMetadata metadata = _metadataProvider.GetMetadataForProperty(() => container, typeof(DataErrorInfo1), \"Error\");\n\n            var validator = new DataErrorInfoModelValidatorProvider.DataErrorInfoPropertyModelValidator(metadata, new ControllerContext());\n\n            // Act\n            ModelValidationResult[] result = validator.Validate(container).ToArray();\n\n            // Assert\n            Assert.Empty(result);\n        }\n\n        [Fact]\n        public void PropertyValidator_Validate_DoesNotReadPropertyValue()\n        {\n            // Arrange\n            ObservableModel model = new ObservableModel();\n            ModelMetadata metadata = _metadataProvider.GetMetadataForProperty(() => model.TheProperty, typeof(ObservableModel), \"TheProperty\");\n            ControllerContext controllerContext = new ControllerContext();\n\n            // Act\n            ModelValidator[] validators = new DataErrorInfoModelValidatorProvider().GetValidators(metadata, controllerContext).ToArray();\n            ModelValidationResult[] results = validators.SelectMany(o => o.Validate(model)).ToArray();\n\n            // Assert\n            Assert.Equal(new[] { typeof(DataErrorInfoModelValidatorProvider.DataErrorInfoPropertyModelValidator) }, Array.ConvertAll(validators, o => o.GetType()));\n            Assert.Equal(new[] { \"TheProperty\" }, model.GetColumnNamesPassed().ToArray());\n            Assert.Empty(results);\n            Assert.False(model.PropertyWasRead());\n        }\n\n        [Fact]\n        public void PropertyValidator_Validate_IDataErrorInfoContainerWithError()\n        {\n            // Arrange\n            DataErrorInfo1 container = new DataErrorInfo1();\n            container[\"SomeStringProperty\"] = \"This is an error message.\";\n            ModelMetadata metadata = _metadataProvider.GetMetadataForProperty(() => container, typeof(DataErrorInfo1), \"SomeStringProperty\");\n\n            var validator = new DataErrorInfoModelValidatorProvider.DataErrorInfoPropertyModelValidator(metadata, new ControllerContext());\n\n            // Act\n            ModelValidationResult[] result = validator.Validate(container).ToArray();\n\n            // Assert\n            ModelValidationResult modelValidationResult = Assert.Single(result);\n            Assert.Equal(\"This is an error message.\", modelValidationResult.Message);\n        }\n\n        [Fact]\n        public void PropertyValidator_Validate_IDataErrorInfoContainerWithNoErrorReturnsEmptyResults()\n        {\n            // Arrange\n            DataErrorInfo1 container = new DataErrorInfo1();\n            ModelMetadata metadata = _metadataProvider.GetMetadataForProperty(() => container, typeof(DataErrorInfo1), \"SomeStringProperty\");\n\n            var validator = new DataErrorInfoModelValidatorProvider.DataErrorInfoPropertyModelValidator(metadata, new ControllerContext());\n\n            // Act\n            ModelValidationResult[] result = validator.Validate(container).ToArray();\n\n            // Assert\n            Assert.Empty(result);\n        }\n\n        [Fact]\n        public void PropertyValidator_Validate_NonIDataErrorInfoContainerReturnsEmptyResults()\n        {\n            // Arrange\n            DataErrorInfo1 container = new DataErrorInfo1();\n            container[\"SomeStringProperty\"] = \"This is an error message.\";\n            ModelMetadata metadata = _metadataProvider.GetMetadataForProperty(() => container, typeof(DataErrorInfo1), \"SomeStringProperty\");\n\n            var validator = new DataErrorInfoModelValidatorProvider.DataErrorInfoPropertyModelValidator(metadata, new ControllerContext());\n\n            // Act\n            ModelValidationResult[] result = validator.Validate(new object()).ToArray();\n\n            // Assert\n            Assert.Empty(result);\n        }\n\n        private class DataErrorInfo1 : IDataErrorInfo\n        {\n            private readonly Dictionary<string, string> _errors = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);\n\n            public string SomeStringProperty { get; set; }\n\n            public string Error { get; set; }\n\n            public string this[string columnName]\n            {\n                get\n                {\n                    string outVal;\n                    _errors.TryGetValue(columnName, out outVal);\n                    return outVal;\n                }\n                set { _errors[columnName] = value; }\n            }\n        }\n\n        private class ObservableModel : IDataErrorInfo\n        {\n            private bool _propertyWasRead;\n            private readonly List<string> _columnNamesPassed = new List<string>();\n\n            public int TheProperty\n            {\n                get\n                {\n                    _propertyWasRead = true;\n                    return 42;\n                }\n            }\n\n            public bool PropertyWasRead()\n            {\n                return _propertyWasRead;\n            }\n\n            public string Error\n            {\n                get { throw new NotImplementedException(); }\n            }\n\n            public string this[string columnName]\n            {\n                get\n                {\n                    _columnNamesPassed.Add(columnName);\n                    return null;\n                }\n            }\n\n            public List<string> GetColumnNamesPassed()\n            {\n                return _columnNamesPassed;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/DataTypeUtilTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel.DataAnnotations;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class DataTypeUtilTest\n    {\n        private class DerivedDataTypeAttribute : DataTypeAttribute\n        {\n            public DerivedDataTypeAttribute(DataType dataType)\n                : base(dataType)\n            {\n            }\n\n            public override string GetDataTypeName()\n            {\n                return \"DerivedTypeName\";\n            }\n        }\n\n        [Fact]\n        public void VirtualDataTypeNameCallsAttributeGetDataTypeName()\n        {\n            // Arrange\n            DataTypeAttribute derivedAttr = new DerivedDataTypeAttribute(DataType.Html);\n            string expectedTypeName = derivedAttr.GetDataTypeName();\n\n            // Act\n            string actualTypeName = DataTypeUtil.ToDataTypeName(derivedAttr);\n\n            // Assert\n            Assert.Equal(expectedTypeName, actualTypeName);\n        }\n\n        [Fact]\n        public void DataTypeAttributeDoesNotCallAttributeGetDataTypeName()\n        {\n            // Arrange\n            Func<DataTypeAttribute, Boolean> isDataTypeAttribute = t => (t as DataTypeAttribute) != null;\n\n            foreach (DataType dataTypeValue in Enum.GetValues(typeof(DataType)))\n            {\n                if (dataTypeValue != DataType.Custom)\n                {\n                    Mock<DataTypeAttribute> dataType = new Mock<DataTypeAttribute>(dataTypeValue);\n\n                    // Act\n                    string actualTypeName = DataTypeUtil.ToDataTypeName(dataType.Object, dta => dta as DataTypeAttribute != null);\n\n                    // Assert\n                    Assert.Equal(dataTypeValue.ToString(), actualTypeName);\n                    dataType.Verify(dt => dt.GetDataTypeName(), Times.Never());\n                }\n            }\n        }\n\n        [Fact]\n        public void CustomDataTypeNameCallsAttributeGetDataTypeName()\n        {\n            // Arrange\n            Func<DataTypeAttribute, Boolean> isDataTypeAttribute = t => (t as DataTypeAttribute) != null;\n\n            Mock<DataTypeAttribute> customDataType = new Mock<DataTypeAttribute>(DataType.Custom);\n            customDataType.Setup(c => c.GetDataTypeName()).Returns(\"CustomTypeName\").Verifiable();\n\n            // Act\n            string actualTypeName = DataTypeUtil.ToDataTypeName(customDataType.Object);\n\n            // Assert\n            customDataType.Verify(c => c.GetDataTypeName(), Times.Once());\n            Assert.Equal(\"CustomTypeName\", actualTypeName);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/DefaultControllerFactoryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Web.Mvc.Routing;\nusing System.Web.Routing;\nusing System.Web.Routing.Test;\nusing System.Web.SessionState;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class DefaultControllerFactoryTest\n    {\n        static DefaultControllerFactoryTest()\n        {\n            MvcTestHelper.CreateMvcAssemblies();\n        }\n\n        [Fact]\n        public void CreateAmbiguousControllerException_RouteWithoutUrl()\n        {\n            // Arrange\n            RouteBase route = new Mock<RouteBase>().Object;\n\n            Type[] matchingTypes = new Type[]\n            {\n                typeof(object),\n                typeof(string)\n            };\n\n            // Act\n            InvalidOperationException exception = DefaultControllerFactory.CreateAmbiguousControllerException(route, \"Foo\", matchingTypes);\n\n            // Assert\n            Assert.Equal(\n                \"Multiple types were found that match the controller named 'Foo'. This can happen if the route that services this request does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces' parameter.\" + Environment.NewLine\n              + Environment.NewLine\n              + \"The request for 'Foo' has found the following matching controllers:\" + Environment.NewLine\n              + \"System.Object\" + Environment.NewLine\n              + \"System.String\",\n                exception.Message);\n        }\n\n        [Fact]\n        public void CreateAmbiguousControllerException_RouteWithUrl()\n        {\n            // Arrange\n            RouteBase route = new Route(\"{controller}/blah\", new Mock<IRouteHandler>().Object);\n\n            Type[] matchingTypes = new Type[]\n            {\n                typeof(object),\n                typeof(string)\n            };\n\n            // Act\n            InvalidOperationException exception = DefaultControllerFactory.CreateAmbiguousControllerException(route, \"Foo\", matchingTypes);\n\n            // Assert\n            Assert.Equal(\n                \"Multiple types were found that match the controller named 'Foo'. This can happen if the route that services this request ('{controller}/blah') does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces' parameter.\" + Environment.NewLine\n              + Environment.NewLine\n              + \"The request for 'Foo' has found the following matching controllers:\" + Environment.NewLine\n              + \"System.Object\" + Environment.NewLine\n              + \"System.String\",\n                exception.Message);\n        }\n\n        [Fact]\n        public void CreateControllerWithNullContextThrows()\n        {\n            // Arrange\n            DefaultControllerFactory factory = new DefaultControllerFactory();\n\n            // Act\n            Assert.ThrowsArgumentNull(\n                delegate\n                {\n                    ((IControllerFactory)factory).CreateController(\n                        null,\n                        \"foo\");\n                },\n                \"requestContext\");\n        }\n\n        [Fact]\n        public void CreateControllerWithEmptyControllerNameThrows()\n        {\n            // Arrange\n            DefaultControllerFactory factory = new DefaultControllerFactory();\n\n            // Act\n            Assert.Throws<ArgumentException>(\n                delegate\n                {\n                    ((IControllerFactory)factory).CreateController(\n                        new RequestContext(new Mock<HttpContextBase>().Object, new RouteData()),\n                        String.Empty);\n                },\n                \"Value cannot be null or empty.\\r\\nParameter name: controllerName\");\n        }\n\n        [Fact]\n        public void CreateControllerReturnsControllerInstance()\n        {\n            // Arrange\n            RequestContext requestContext = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData());\n            Mock<DefaultControllerFactory> factoryMock = new Mock<DefaultControllerFactory>();\n            factoryMock.CallBase = true;\n            factoryMock.Setup(o => o.GetControllerType(requestContext, \"moo\")).Returns(typeof(DummyController));\n\n            // Act\n            IController controller = ((IControllerFactory)factoryMock.Object).CreateController(requestContext, \"moo\");\n\n            // Assert\n            Assert.IsType<DummyController>(controller);\n        }\n\n        [Fact]\n        public void CreateControllerCanReturnNull()\n        {\n            // Arrange\n            RequestContext requestContext = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData());\n            Mock<DefaultControllerFactory> factoryMock = new Mock<DefaultControllerFactory>();\n            factoryMock.Setup(o => o.GetControllerType(requestContext, \"moo\")).Returns(typeof(DummyController));\n            factoryMock.Setup(o => o.GetControllerInstance(requestContext, typeof(DummyController))).Returns((ControllerBase)null);\n\n            // Act\n            IController controller = ((IControllerFactory)factoryMock.Object).CreateController(requestContext, \"moo\");\n\n            // Assert\n            Assert.Null(controller);\n        }\n\n        [Fact]\n        public void DisposeControllerFactoryWithDisposableController()\n        {\n            // Arrange\n            IControllerFactory factory = new DefaultControllerFactory();\n            Mock<ControllerBase> mockController = new Mock<ControllerBase>();\n            Mock<IDisposable> mockDisposable = mockController.As<IDisposable>();\n            mockDisposable.Setup(d => d.Dispose()).Verifiable();\n\n            // Act\n            factory.ReleaseController(mockController.Object);\n\n            // Assert\n            mockDisposable.Verify();\n        }\n\n        [Fact]\n        public void GetControllerInstanceThrowsIfControllerTypeIsNull()\n        {\n            // Arrange\n            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>();\n            Mock<HttpRequestBase> requestMock = new Mock<HttpRequestBase>();\n            contextMock.Setup(o => o.Request).Returns(requestMock.Object);\n            requestMock.Setup(o => o.Path).Returns(\"somepath\");\n            RequestContext requestContext = new RequestContext(contextMock.Object, new RouteData());\n            Mock<DefaultControllerFactory> factoryMock = new Mock<DefaultControllerFactory> { CallBase = true };\n            factoryMock.Setup(o => o.GetControllerType(requestContext, \"moo\")).Returns((Type)null);\n\n            // Act\n            Assert.ThrowsHttpException(\n                delegate { ((IControllerFactory)factoryMock.Object).CreateController(requestContext, \"moo\"); },\n                \"The controller for path 'somepath' was not found or does not implement IController.\",\n                404);\n        }\n\n        [Fact]\n        public void GetControllerInstanceThrowsIfControllerTypeIsNotControllerBase()\n        {\n            // Arrange\n            RequestContext requestContext = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData());\n            DefaultControllerFactory factory = new DefaultControllerFactory();\n\n            // Act\n            Assert.Throws<ArgumentException>(\n                delegate { factory.GetControllerInstance(requestContext, typeof(int)); },\n                \"The controller type 'System.Int32' must implement IController.\\r\\nParameter name: controllerType\");\n        }\n\n        [Fact]\n        public void GetControllerInstanceWithBadConstructorThrows()\n        {\n            // Arrange\n            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>();\n            RequestContext requestContext = new RequestContext(contextMock.Object, new RouteData());\n            Mock<DefaultControllerFactory> factoryMock = new Mock<DefaultControllerFactory>();\n            factoryMock.CallBase = true;\n            factoryMock.Setup(o => o.GetControllerType(requestContext, \"moo\")).Returns(typeof(DummyControllerThrows));\n\n            // Act\n            Exception ex = Assert.Throws<InvalidOperationException>(\n                delegate { ((IControllerFactory)factoryMock.Object).CreateController(requestContext, \"moo\"); },\n                \"An error occurred when trying to create a controller of type 'System.Web.Mvc.Test.DefaultControllerFactoryTest+DummyControllerThrows'. Make sure that the controller has a parameterless public constructor.\");\n\n            Assert.Equal(\"constructor\", ex.InnerException.InnerException.Message);\n        }\n\n        [Fact]\n        public void GetControllerSessionBehaviorGuardClauses()\n        {\n            // Arrange\n            RequestContext requestContext = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData());\n            IControllerFactory factory = new DefaultControllerFactory();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => factory.GetControllerSessionBehavior(null, \"controllerName\"),\n                \"requestContext\"\n                );\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => factory.GetControllerSessionBehavior(requestContext, null),\n                \"controllerName\"\n                );\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => factory.GetControllerSessionBehavior(requestContext, \"\"),\n                \"controllerName\"\n                );\n        }\n\n        [Fact]\n        public void GetControllerSessionBehaviorReturnsDefaultForNullControllerType()\n        {\n            // Arrange\n            var factory = new DefaultControllerFactory();\n\n            // Act\n            SessionStateBehavior result = factory.GetControllerSessionBehavior(null, null);\n\n            // Assert\n            Assert.Equal(SessionStateBehavior.Default, result);\n        }\n\n        [Fact]\n        public void GetControllerSessionBehaviorReturnsDefaultForControllerWithoutAttribute()\n        {\n            // Arrange\n            var factory = new DefaultControllerFactory();\n\n            // Act\n            SessionStateBehavior result = factory.GetControllerSessionBehavior(null, typeof(object));\n\n            // Assert\n            Assert.Equal(SessionStateBehavior.Default, result);\n        }\n\n        [Fact]\n        public void GetControllerSessionBehaviorReturnsAttributeValueFromController()\n        {\n            // Arrange\n            var factory = new DefaultControllerFactory();\n\n            // Act\n            SessionStateBehavior result = factory.GetControllerSessionBehavior(null, typeof(MyReadOnlyController));\n\n            // Assert\n            Assert.Equal(SessionStateBehavior.ReadOnly, result);\n        }\n\n        [SessionState(SessionStateBehavior.ReadOnly)]\n        class MyReadOnlyController\n        {\n        }\n\n        [Fact]\n        public void GetControllerTypeWithEmptyControllerNameThrows()\n        {\n            // Arrange\n            RequestContext requestContext = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData());\n            DefaultControllerFactory factory = new DefaultControllerFactory();\n\n            // Act\n            Assert.Throws<ArgumentException>(\n                delegate { factory.GetControllerType(requestContext, String.Empty); },\n                \"Value cannot be null or empty.\\r\\nParameter name: controllerName\");\n        }\n\n        [Fact]\n        public void GetControllerTypeForNoAssemblies()\n        {\n            // Arrange\n            RequestContext requestContext = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData());\n            DefaultControllerFactory factory = new DefaultControllerFactory();\n            MockBuildManager buildManagerMock = new MockBuildManager(new Assembly[] { });\n            ControllerTypeCache controllerTypeCache = new ControllerTypeCache();\n\n            factory.BuildManager = buildManagerMock;\n            factory.ControllerTypeCache = controllerTypeCache;\n\n            // Act\n            Type controllerType = factory.GetControllerType(requestContext, \"sometype\");\n\n            // Assert\n            Assert.Null(controllerType);\n            Assert.Equal(0, controllerTypeCache.Count);\n        }\n\n        [Fact]\n        public void GetControllerTypeForOneAssembly()\n        {\n            // Arrange\n            RequestContext requestContext = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData());\n            DefaultControllerFactory factory = GetDefaultControllerFactory(\"ns1a.ns1b\", \"ns2a.ns2b\");\n            MockBuildManager buildManagerMock = new MockBuildManager(new Assembly[] { Assembly.Load(\"MvcAssembly1\") });\n            ControllerTypeCache controllerTypeCache = new ControllerTypeCache();\n\n            factory.BuildManager = buildManagerMock;\n            factory.ControllerTypeCache = controllerTypeCache;\n\n            // Act\n            Type c1Type = factory.GetControllerType(requestContext, \"C1\");\n            Type c2Type = factory.GetControllerType(requestContext, \"c2\");\n\n            // Assert\n            Assembly asm1 = Assembly.Load(\"MvcAssembly1\");\n            Type verifiedC1 = asm1.GetType(\"NS1a.NS1b.C1Controller\");\n            Type verifiedC2 = asm1.GetType(\"NS2a.NS2b.C2Controller\");\n            Assert.Equal(verifiedC1, c1Type);\n            Assert.Equal(verifiedC2, c2Type);\n            Assert.Equal(2, controllerTypeCache.Count);\n        }\n\n        [Fact]\n        public void GetControllerTypeForManyAssemblies()\n        {\n            // Arrange\n            RequestContext requestContext = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData());\n            DefaultControllerFactory factory = GetDefaultControllerFactory(\"ns1a.ns1b\", \"ns2a.ns2b\", \"ns3a.ns3b\", \"ns4a.ns4b\");\n            MockBuildManager buildManagerMock = new MockBuildManager(new Assembly[] { Assembly.Load(\"MvcAssembly1\"), Assembly.Load(\"MvcAssembly2\") });\n            ControllerTypeCache controllerTypeCache = new ControllerTypeCache();\n\n            factory.BuildManager = buildManagerMock;\n            factory.ControllerTypeCache = controllerTypeCache;\n\n            // Act\n            Type c1Type = factory.GetControllerType(requestContext, \"C1\");\n            Type c2Type = factory.GetControllerType(requestContext, \"C2\");\n            Type c3Type = factory.GetControllerType(requestContext, \"c3\"); // lower case\n            Type c4Type = factory.GetControllerType(requestContext, \"c4\"); // lower case\n\n            // Assert\n            Assembly asm1 = Assembly.Load(\"MvcAssembly1\");\n            Type verifiedC1 = asm1.GetType(\"NS1a.NS1b.C1Controller\");\n            Type verifiedC2 = asm1.GetType(\"NS2a.NS2b.C2Controller\");\n            Assembly asm2 = Assembly.Load(\"MvcAssembly2\");\n            Type verifiedC3 = asm2.GetType(\"NS3a.NS3b.C3Controller\");\n            Type verifiedC4 = asm2.GetType(\"NS4a.NS4b.C4Controller\");\n            Assert.NotNull(verifiedC1);\n            Assert.NotNull(verifiedC2);\n            Assert.NotNull(verifiedC3);\n            Assert.NotNull(verifiedC4);\n            Assert.Equal(verifiedC1, c1Type);\n            Assert.Equal(verifiedC2, c2Type);\n            Assert.Equal(verifiedC3, c3Type);\n            Assert.Equal(verifiedC4, c4Type);\n            Assert.Equal(4, controllerTypeCache.Count);\n        }\n\n        [Fact]\n        public void GetControllerTypeDoesNotThrowIfSameControllerMatchedMultipleNamespaces()\n        {\n            // both namespaces \"ns3a\" and \"ns3a.ns3b\" will match a controller type, but it's actually\n            // the same type. in this case, we shouldn't throw.\n\n            // Arrange\n            RequestContext requestContext = GetRequestContextWithNamespaces(\"ns3a\", \"ns3a.ns3b\");\n            requestContext.RouteData.DataTokens[\"UseNamespaceFallback\"] = false;\n            DefaultControllerFactory factory = GetDefaultControllerFactory(\"ns1a.ns1b\", \"ns2a.ns2b\");\n            MockBuildManager buildManagerMock = new MockBuildManager(new Assembly[] { Assembly.Load(\"MvcAssembly3\") });\n            ControllerTypeCache controllerTypeCache = new ControllerTypeCache();\n\n            factory.BuildManager = buildManagerMock;\n            factory.ControllerTypeCache = controllerTypeCache;\n\n            // Act\n            Type c1Type = factory.GetControllerType(requestContext, \"C1\");\n\n            // Assert\n            Assembly asm3 = Assembly.Load(\"MvcAssembly3\");\n            Type verifiedC1 = asm3.GetType(\"NS3a.NS3b.C1Controller\");\n            Assert.NotNull(verifiedC1);\n            Assert.Equal(verifiedC1, c1Type);\n        }\n\n        [Fact]\n        public void GetControllerTypeForAssembliesWithSameTypeNamesInDifferentNamespaces()\n        {\n            // Arrange\n            RequestContext requestContext = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData());\n            DefaultControllerFactory factory = GetDefaultControllerFactory(\"ns1a.ns1b\", \"ns2a.ns2b\");\n            MockBuildManager buildManagerMock = new MockBuildManager(new Assembly[] { Assembly.Load(\"MvcAssembly1\"), Assembly.Load(\"MvcAssembly3\") });\n            ControllerTypeCache controllerTypeCache = new ControllerTypeCache();\n\n            factory.BuildManager = buildManagerMock;\n            factory.ControllerTypeCache = controllerTypeCache;\n\n            // Act\n            Type c1Type = factory.GetControllerType(requestContext, \"C1\");\n            Type c2Type = factory.GetControllerType(requestContext, \"C2\");\n\n            // Assert\n            Assembly asm1 = Assembly.Load(\"MvcAssembly1\");\n            Type verifiedC1 = asm1.GetType(\"NS1a.NS1b.C1Controller\");\n            Type verifiedC2 = asm1.GetType(\"NS2a.NS2b.C2Controller\");\n            Assert.NotNull(verifiedC1);\n            Assert.NotNull(verifiedC2);\n            Assert.Equal(verifiedC1, c1Type);\n            Assert.Equal(verifiedC2, c2Type);\n            Assert.Equal(4, controllerTypeCache.Count);\n        }\n\n        [Fact]\n        public void GetControllerTypeForAssembliesWithSameTypeNamesInDifferentNamespacesThrowsIfAmbiguous()\n        {\n            // Arrange\n            RequestContext requestContext = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData());\n            DefaultControllerFactory factory = GetDefaultControllerFactory(\"ns1a.ns1b\", \"ns3a.ns3b\");\n            MockBuildManager buildManagerMock = new MockBuildManager(new Assembly[] { Assembly.Load(\"MvcAssembly1\"), Assembly.Load(\"MvcAssembly3\") });\n            ControllerTypeCache controllerTypeCache = new ControllerTypeCache();\n\n            factory.BuildManager = buildManagerMock;\n            factory.ControllerTypeCache = controllerTypeCache;\n\n            // Act\n            Assert.Throws<InvalidOperationException>(\n                delegate { factory.GetControllerType(requestContext, \"C1\"); },\n                \"Multiple types were found that match the controller named 'C1'. This can happen if the route that services this request does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces' parameter.\" + Environment.NewLine\n              + Environment.NewLine\n              + \"The request for 'C1' has found the following matching controllers:\" + Environment.NewLine\n              + \"NS1a.NS1b.C1Controller\" + Environment.NewLine\n              + \"NS3a.NS3b.C1Controller\");\n\n            // Assert\n            Assert.Equal(4, controllerTypeCache.Count);\n        }\n\n        [Fact]\n        public void GetControllerTypeForAssembliesWithSameTypeNamesInSameNamespaceThrows()\n        {\n            // Arrange\n            RequestContext requestContext = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData());\n            DefaultControllerFactory factory = GetDefaultControllerFactory(\"ns1a.ns1b\");\n            MockBuildManager buildManagerMock = new MockBuildManager(new Assembly[] { Assembly.Load(\"MvcAssembly1\"), Assembly.Load(\"MvcAssembly4\") });\n            ControllerTypeCache controllerTypeCache = new ControllerTypeCache();\n\n            factory.BuildManager = buildManagerMock;\n            factory.ControllerTypeCache = controllerTypeCache;\n\n            // Act\n            Assert.Throws<InvalidOperationException>(\n                delegate { factory.GetControllerType(requestContext, \"C1\"); },\n                \"Multiple types were found that match the controller named 'C1'. This can happen if the route that services this request does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces' parameter.\" + Environment.NewLine\n              + Environment.NewLine\n              + \"The request for 'C1' has found the following matching controllers:\" + Environment.NewLine\n              + \"NS1a.NS1b.C1Controller\" + Environment.NewLine\n              + \"NS1a.NS1b.C1Controller\");\n\n            // Assert\n            Assert.Equal(4, controllerTypeCache.Count);\n        }\n\n        [Fact]\n        public void GetControllerTypeSearchesAllNamespacesAsLastResort()\n        {\n            // Arrange\n            RequestContext requestContext = GetRequestContextWithNamespaces(\"ns3a.ns3b\");\n            DefaultControllerFactory factory = GetDefaultControllerFactory(\"ns1a.ns1b\");\n            MockBuildManager buildManagerMock = new MockBuildManager(new Assembly[] { Assembly.Load(\"MvcAssembly1\") });\n            ControllerTypeCache controllerTypeCache = new ControllerTypeCache();\n\n            factory.BuildManager = buildManagerMock;\n            factory.ControllerTypeCache = controllerTypeCache;\n\n            // Act\n            Type c2Type = factory.GetControllerType(requestContext, \"C2\");\n\n            // Assert\n            Assembly asm1 = Assembly.Load(\"MvcAssembly1\");\n            Type verifiedC2 = asm1.GetType(\"NS2a.NS2b.C2Controller\");\n            Assert.NotNull(verifiedC2);\n            Assert.Equal(verifiedC2, c2Type);\n            Assert.Equal(2, controllerTypeCache.Count);\n        }\n\n        [Fact]\n        public void GetControllerTypeSearchesOnlyRouteDefinedNamespacesIfRequested()\n        {\n            // Arrange\n            RequestContext requestContext = GetRequestContextWithNamespaces(\"ns3a.ns3b\");\n            requestContext.RouteData.DataTokens[\"UseNamespaceFallback\"] = false;\n            DefaultControllerFactory factory = GetDefaultControllerFactory(\"ns1a.ns1b\", \"ns2a.ns2b\");\n            MockBuildManager buildManagerMock = new MockBuildManager(new Assembly[] { Assembly.Load(\"MvcAssembly1\"), Assembly.Load(\"MvcAssembly3\") });\n            ControllerTypeCache controllerTypeCache = new ControllerTypeCache();\n\n            factory.BuildManager = buildManagerMock;\n            factory.ControllerTypeCache = controllerTypeCache;\n\n            // Act\n            Type c1Type = factory.GetControllerType(requestContext, \"C1\");\n            Type c2Type = factory.GetControllerType(requestContext, \"C2\");\n\n            // Assert\n            Assembly asm3 = Assembly.Load(\"MvcAssembly3\");\n            Type verifiedC1 = asm3.GetType(\"NS3a.NS3b.C1Controller\");\n            Assert.NotNull(verifiedC1);\n            Assert.Equal(verifiedC1, c1Type);\n            Assert.Null(c2Type);\n        }\n\n        [Fact]\n        public void GetControllerTypeSearchesRouteDefinedNamespacesBeforeApplicationDefinedNamespaces()\n        {\n            // Arrange\n            RequestContext requestContext = GetRequestContextWithNamespaces(\"ns3a.ns3b\");\n            DefaultControllerFactory factory = GetDefaultControllerFactory(\"ns1a.ns1b\", \"ns2a.ns2b\");\n            MockBuildManager buildManagerMock = new MockBuildManager(new Assembly[] { Assembly.Load(\"MvcAssembly1\"), Assembly.Load(\"MvcAssembly3\") });\n            ControllerTypeCache controllerTypeCache = new ControllerTypeCache();\n\n            factory.BuildManager = buildManagerMock;\n            factory.ControllerTypeCache = controllerTypeCache;\n\n            // Act\n            Type c1Type = factory.GetControllerType(requestContext, \"C1\");\n            Type c2Type = factory.GetControllerType(requestContext, \"C2\");\n\n            // Assert\n            Assembly asm1 = Assembly.Load(\"MvcAssembly1\");\n            Type verifiedC2 = asm1.GetType(\"NS2a.NS2b.C2Controller\");\n            Assembly asm3 = Assembly.Load(\"MvcAssembly3\");\n            Type verifiedC1 = asm3.GetType(\"NS3a.NS3b.C1Controller\");\n            Assert.NotNull(verifiedC1);\n            Assert.NotNull(verifiedC2);\n            Assert.Equal(verifiedC1, c1Type);\n            Assert.Equal(verifiedC2, c2Type);\n            Assert.Equal(4, controllerTypeCache.Count);\n        }\n\n        [Fact]\n        public void GetControllerTypeThatDoesntExist()\n        {\n            // Arrange\n            RequestContext requestContext = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData());\n            DefaultControllerFactory factory = GetDefaultControllerFactory(\"ns1a.ns1b\", \"ns2a.ns2b\", \"ns3a.ns3b\", \"ns4a.ns4b\");\n            MockBuildManager buildManagerMock = new MockBuildManager(new Assembly[] { Assembly.Load(\"MvcAssembly1\"), Assembly.Load(\"MvcAssembly2\"), Assembly.Load(\"MvcAssembly3\"), Assembly.Load(\"MvcAssembly4\") });\n            ControllerTypeCache controllerTypeCache = new ControllerTypeCache();\n\n            factory.BuildManager = buildManagerMock;\n            factory.ControllerTypeCache = controllerTypeCache;\n\n            // Act\n            Type randomType1 = factory.GetControllerType(requestContext, \"Cx\");\n            Type randomType2 = factory.GetControllerType(requestContext, \"Cy\");\n            Type randomType3 = factory.GetControllerType(requestContext, \"Foo.Bar\");\n            Type randomType4 = factory.GetControllerType(requestContext, \"C1Controller\");\n\n            // Assert\n            Assert.Null(randomType1);\n            Assert.Null(randomType2);\n            Assert.Null(randomType3);\n            Assert.Null(randomType4);\n            Assert.Equal(8, controllerTypeCache.Count);\n        }\n\n        [Fact]\n        public void IsControllerType()\n        {\n            // Act\n            bool isController1 = ControllerTypeCache.IsControllerType(null);\n            bool isController2 = ControllerTypeCache.IsControllerType(typeof(NonPublicController));\n            bool isController3 = ControllerTypeCache.IsControllerType(typeof(MisspelledKontroller));\n            bool isController4 = ControllerTypeCache.IsControllerType(typeof(AbstractController));\n            bool isController5 = ControllerTypeCache.IsControllerType(typeof(NonIControllerController));\n            bool isController6 = ControllerTypeCache.IsControllerType(typeof(Goodcontroller));\n\n            // Assert\n            Assert.False(isController1);\n            Assert.False(isController2);\n            Assert.False(isController3);\n            Assert.False(isController4);\n            Assert.False(isController5);\n            Assert.True(isController6);\n        }\n\n        [Theory]\n        [InlineData(null, false)]\n        [InlineData(\"\", true)]\n        [InlineData(\"Dummy\", false)]\n        [InlineData(\"Dummy.*\", true)]\n        [InlineData(\"Dummy.Controller.*\", false)]\n        [InlineData(\"Dummy.Controllers\", true)]\n        [InlineData(\"Dummy.Controllers.*\", true)]\n        [InlineData(\"Dummy.Controllers*\", false)]\n        public void IsNamespaceMatch(string testNamespace, bool expectedResult)\n        {\n            // Act & Assert\n            Assert.Equal(expectedResult, ControllerTypeCache.IsNamespaceMatch(testNamespace, \"Dummy.Controllers\"));\n        }\n\n        [Fact]\n        public void GetControllerInstanceConsultsSetControllerActivator()\n        {\n            //Arrange\n            Mock<IControllerActivator> activator = new Mock<IControllerActivator>();\n            DefaultControllerFactory factory = new DefaultControllerFactory(activator.Object);\n            RequestContext context = new RequestContext();\n\n            //Act\n            factory.GetControllerInstance(context, typeof(Goodcontroller));\n\n            //Assert\n            activator.Verify(l => l.Create(context, typeof(Goodcontroller)));\n        }\n\n        [Fact]\n        public void GetControllerDelegatesToActivatorResolver()\n        {\n            //Arrange\n            var context = new RequestContext();\n            var expectedController = new Goodcontroller();\n            var resolverActivator = new Mock<IControllerActivator>();\n            resolverActivator.Setup(a => a.Create(context, typeof(Goodcontroller))).Returns(expectedController);\n            var activatorResolver = new Resolver<IControllerActivator> { Current = resolverActivator.Object };\n            var factory = new DefaultControllerFactory(null, activatorResolver, null);\n\n            //Act\n            IController returnedController = factory.GetControllerInstance(context, typeof(Goodcontroller));\n\n            //Assert\n            Assert.Same(returnedController, expectedController);\n        }\n\n        [Fact]\n        public void GetControllerDelegatesToDependencyResolveWhenActivatorResolverIsNull()\n        {\n            // Arrange\n            var context = new RequestContext();\n            var expectedController = new Goodcontroller();\n            var dependencyResolver = new Mock<IDependencyResolver>(MockBehavior.Strict);\n            dependencyResolver.Setup(dr => dr.GetService(typeof(Goodcontroller))).Returns(expectedController);\n            var factory = new DefaultControllerFactory(null, null, dependencyResolver.Object);\n\n            // Act\n            IController returnedController = factory.GetControllerInstance(context, typeof(Goodcontroller));\n\n            // Assert\n            Assert.Same(returnedController, expectedController);\n        }\n\n        [Fact]\n        public void GetControllerDelegatesToActivatorCreateInstanceWhenDependencyResolverReturnsNull()\n        {\n            // Arrange\n            var context = new RequestContext();\n            var dependencyResolver = new Mock<IDependencyResolver>();\n            var factory = new DefaultControllerFactory(null, null, dependencyResolver.Object);\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => factory.GetControllerInstance(context, typeof(NoParameterlessCtor)),\n                \"An error occurred when trying to create a controller of type 'System.Web.Mvc.Test.DefaultControllerFactoryTest+NoParameterlessCtor'. Make sure that the controller has a parameterless public constructor.\"\n                );\n        }\n\n        [Fact]\n        public void ActivatorResolverAndDependencyResolverAreNeverCalledWhenControllerActivatorIsPassedInConstructor()\n        {\n            // Arrange\n            var context = new RequestContext();\n            var expectedController = new Goodcontroller();\n\n            Mock<IControllerActivator> activator = new Mock<IControllerActivator>();\n            activator.Setup(a => a.Create(context, typeof(Goodcontroller))).Returns(expectedController);\n\n            var resolverActivator = new Mock<IControllerActivator>(MockBehavior.Strict);\n            var activatorResolver = new Resolver<IControllerActivator> { Current = resolverActivator.Object };\n\n            var dependencyResolver = new Mock<IDependencyResolver>(MockBehavior.Strict);\n\n            //Act\n            var factory = new DefaultControllerFactory(activator.Object, activatorResolver, dependencyResolver.Object);\n            IController returnedController = factory.GetControllerInstance(context, typeof(Goodcontroller));\n\n            //Assert\n            Assert.Same(returnedController, expectedController);\n        }\n\n        [Fact]\n        public void GetControllerType_WithMatchedDirectRoute_UseTargetMethodType()\n        {\n            // Arrange\n            var requestContext = new RequestContext();\n            requestContext.RouteData = new RouteData();\n            requestContext.RouteData.Route = DirectRouteTestHelpers.BuildDirectRouteFromMethod<WithRoutingAttributeController>(c => c.Action());\n            requestContext.RouteData.AddDirectRouteMatches();\n\n            var expectedControllerType = typeof(WithRoutingAttributeController);\n\n            var controllerActivator = new Mock<IControllerActivator>(MockBehavior.Strict).Object;\n            var activatorResolver = new Resolver<IControllerActivator>();\n\n            var factory = new DefaultControllerFactory(controllerActivator, activatorResolver, null);\n\n            // Act\n            // if it would not get the controller type from the DirectRoute, then it would not \n            // be able to find any controller\n            var type = factory.GetControllerType(requestContext, controllerName: null);\n\n            // Assert\n            Assert.Equal(expectedControllerType, type);\n        }\n\n        [Fact]\n        public void GetControllerType_WithMatchedDirectRoute_UseControllerDescriptorType()\n        {\n            // Arrange\n            var requestContext = new RequestContext();\n            requestContext.RouteData = new RouteData();\n            requestContext.RouteData.Route = DirectRouteTestHelpers.BuildDirectRouteFromController<AttributeRouteAtControllerLevelController>();\n            requestContext.RouteData.AddDirectRouteMatches();\n\n            var expectedControllerType = typeof(AttributeRouteAtControllerLevelController);\n\n            var controllerActivator = new Mock<IControllerActivator>(MockBehavior.Strict).Object;\n            var activatorResolver = new Resolver<IControllerActivator>();\n\n            var factory = new DefaultControllerFactory(controllerActivator, activatorResolver, null);\n\n            // Act\n            // if it would not get the controller type from the DirectRoute, then it would not \n            // be able to find any controller\n            var type = factory.GetControllerType(requestContext, controllerName: null);\n\n            // Assert\n            Assert.Equal(expectedControllerType, type);\n        }\n\n        [Fact]\n        public void GetControllerType_WithMultipleDirectRouteControllers_ThrowsInvalidOperationException()\n        {\n            // Arrange\n            var requestContext = new RequestContext();\n            requestContext.RouteData = new RouteData();\n            SubRouteCollection subRoutes = new SubRouteCollection();\n            DirectRouteTestHelpers.AddDirectRouteFromController<AttributeRouteAtControllerLevelController>(subRoutes);\n            DirectRouteTestHelpers.AddDirectRouteFromMethod<WithRoutingAttributeController>(subRoutes, c => c.Action());\n            requestContext.RouteData.Route = new RouteCollectionRoute(subRoutes);\n            requestContext.RouteData.AddDirectRouteMatches();\n\n            var controllerActivator = new Mock<IControllerActivator>(MockBehavior.Strict).Object;\n            var activatorResolver = new Resolver<IControllerActivator>();\n\n            var factory = new DefaultControllerFactory(controllerActivator, activatorResolver, null);\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(() => factory.GetControllerType(requestContext, controllerName: null));\n        }\n\n        class NoParameterlessCtor : IController\n        {\n            public NoParameterlessCtor(int x)\n            {\n            }\n\n            public void Execute(RequestContext requestContext)\n            {\n            }\n        }\n\n        private static DefaultControllerFactory GetDefaultControllerFactory(params string[] namespaces)\n        {\n            ControllerBuilder builder = new ControllerBuilder();\n            builder.DefaultNamespaces.UnionWith(namespaces);\n            return new DefaultControllerFactory() { ControllerBuilder = builder };\n        }\n\n        private static RequestContext GetRequestContextWithNamespaces(params string[] namespaces)\n        {\n            RouteData routeData = new RouteData();\n            routeData.DataTokens[\"namespaces\"] = namespaces;\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            RequestContext requestContext = new RequestContext(mockHttpContext.Object, routeData);\n            return requestContext;\n        }\n\n        private sealed class DummyController : ControllerBase\n        {\n            protected override void ExecuteCore()\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private sealed class DummyControllerThrows : IController\n        {\n            public DummyControllerThrows()\n            {\n                throw new Exception(\"constructor\");\n            }\n\n            #region IController Members\n\n            void IController.Execute(RequestContext requestContext)\n            {\n                throw new NotImplementedException();\n            }\n\n            #endregion\n        }\n\n        public interface IDisposableController : IController, IDisposable\n        {\n        }\n    }\n\n    // BAD: type isn't public\n    internal class NonPublicController : Controller\n    {\n    }\n\n    // BAD: type doesn't end with 'Controller'\n    public class MisspelledKontroller : Controller\n    {\n    }\n\n    // BAD: type is abstract\n    public abstract class AbstractController : Controller\n    {\n    }\n\n    // BAD: type doesn't implement IController\n    public class NonIControllerController\n    {\n    }\n\n    // GOOD: 'Controller' suffix should be case-insensitive\n    public class Goodcontroller : Controller\n    {\n    }\n\n    public class WithRoutingAttributeController : Controller\n    {\n        [Route(\"route\")]\n        public void Action()\n        {\n        }\n    }\n\n    [Route(\"cool/{action}\")]\n    public class AttributeRouteAtControllerLevelController : Controller\n    {\n        public void Action()\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/DefaultModelBinderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.ComponentModel.DataAnnotations;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\nusing Moq;\nusing Moq.Protected;\n\nnamespace System.Web.Mvc.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")] // Uses ModelMetadataProviders.Current\n    public class DefaultModelBinderTest\n    {\n        [Fact]\n        public void BindComplexElementalModelReturnsIfOnModelUpdatingReturnsFalse()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n\n            MyModel model = new MyModel() { ReadWriteProperty = 3 };\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),\n            };\n\n            Mock<DefaultModelBinderHelper> mockHelper = new Mock<DefaultModelBinderHelper>() { CallBase = true };\n            mockHelper.Setup(b => b.PublicOnModelUpdating(controllerContext, It.IsAny<ModelBindingContext>())).Returns(false);\n            DefaultModelBinderHelper helper = mockHelper.Object;\n\n            // Act\n            helper.BindComplexElementalModel(controllerContext, bindingContext, model);\n\n            // Assert\n            Assert.Equal(3, model.ReadWriteProperty);\n            mockHelper.Verify();\n            mockHelper.Verify(b => b.PublicGetModelProperties(controllerContext, It.IsAny<ModelBindingContext>()), Times.Never());\n            mockHelper.Verify(b => b.PublicBindProperty(controllerContext, It.IsAny<ModelBindingContext>(), It.IsAny<PropertyDescriptor>()), Times.Never());\n        }\n\n        [Fact]\n        public void BindComplexModelCanBindArrays()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(int[])),\n                ModelName = \"foo\",\n                PropertyFilter = _ => false,\n                ValueProvider = new SimpleValueProvider()\n                {\n                    { \"foo[0]\", null },\n                    { \"foo[1]\", null },\n                    { \"foo[2]\", null }\n                }\n            };\n\n            Mock<IModelBinder> mockInnerBinder = new Mock<IModelBinder>();\n            mockInnerBinder\n                .Setup(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ModelBindingContext bc)\n                    {\n                        Assert.Equal(controllerContext, cc);\n                        Assert.Equal(typeof(int), bc.ModelType);\n                        Assert.Equal(bindingContext.ModelState, bc.ModelState);\n                        Assert.Equal(bindingContext.PropertyFilter, bc.PropertyFilter);\n                        Assert.Equal(bindingContext.ValueProvider, bc.ValueProvider);\n                        return Int32.Parse(bc.ModelName.Substring(4, 1), CultureInfo.InvariantCulture);\n                    });\n\n            DefaultModelBinder binder = new DefaultModelBinder()\n            {\n                Binders = new ModelBinderDictionary()\n                {\n                    { typeof(int), mockInnerBinder.Object }\n                }\n            };\n\n            // Act\n            object newModel = binder.BindComplexModel(controllerContext, bindingContext);\n\n            // Assert\n            var newIntArray = Assert.IsType<int[]>(newModel);\n            Assert.Equal(new[] { 0, 1, 2 }, newIntArray);\n        }\n\n        [Fact]\n        public void BindComplexModelCanBindCollections()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(IList<int>)),\n                ModelName = \"foo\",\n                PropertyFilter = _ => false,\n                ValueProvider = new SimpleValueProvider()\n                {\n                    { \"foo[0]\", null },\n                    { \"foo[1]\", null },\n                    { \"foo[2]\", null }\n                }\n            };\n\n            Mock<IModelBinder> mockInnerBinder = new Mock<IModelBinder>();\n            mockInnerBinder\n                .Setup(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ModelBindingContext bc)\n                    {\n                        Assert.Equal(controllerContext, cc);\n                        Assert.Equal(typeof(int), bc.ModelType);\n                        Assert.Equal(bindingContext.ModelState, bc.ModelState);\n                        Assert.Equal(bindingContext.PropertyFilter, bc.PropertyFilter);\n                        Assert.Equal(bindingContext.ValueProvider, bc.ValueProvider);\n                        return Int32.Parse(bc.ModelName.Substring(4, 1), CultureInfo.InvariantCulture);\n                    });\n\n            DefaultModelBinder binder = new DefaultModelBinder()\n            {\n                Binders = new ModelBinderDictionary()\n                {\n                    { typeof(int), mockInnerBinder.Object }\n                }\n            };\n\n            // Act\n            object newModel = binder.BindComplexModel(controllerContext, bindingContext);\n\n            // Assert\n            var modelAsList = Assert.IsAssignableFrom<IList<int>>(newModel);\n            Assert.Equal(new[] { 0, 1, 2 }, modelAsList.ToArray());\n        }\n\n        [Fact]\n        public void BindComplexModelCanBindDictionariesWithDotsNotation()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(IDictionary<string, CountryState>)),\n                ModelName = \"countries\",\n                PropertyFilter = _ => true,\n                ValueProvider = new DictionaryValueProvider<object>(new Dictionary<string, object>()\n                {\n                    { \"countries.CA.Name\", \"Canada\" },\n                    { \"countries.CA.States[0]\", \"Québec\" },\n                    { \"countries.CA.States[1]\", \"British Columbia\" },\n                    { \"countries.US.Name\", \"United States\" },\n                    { \"countries.US.States[0]\", \"Washington\" },\n                    { \"countries.US.States[1]\", \"Oregon\" }\n                }, CultureInfo.CurrentCulture)\n            };\n\n            DefaultModelBinder binder = new DefaultModelBinder();\n\n            // Act\n            object newModel = binder.BindComplexModel(controllerContext, bindingContext);\n\n            // Assert\n            var modelAsDictionary = Assert.IsAssignableFrom<IDictionary<string, CountryState>>(newModel);\n            Assert.Equal(2, modelAsDictionary.Count);\n            Assert.Equal(\"Canada\", modelAsDictionary[\"CA\"].Name);\n            Assert.Equal(\"United States\", modelAsDictionary[\"US\"].Name);\n            Assert.Equal(2, modelAsDictionary[\"CA\"].States.Count());\n            Assert.Contains(\"Québec\", modelAsDictionary[\"CA\"].States);\n            Assert.Contains(\"British Columbia\", modelAsDictionary[\"CA\"].States);\n            Assert.Equal(2, modelAsDictionary[\"US\"].States.Count());\n            Assert.Contains(\"Washington\", modelAsDictionary[\"US\"].States);\n            Assert.Contains(\"Oregon\", modelAsDictionary[\"US\"].States);\n        }\n\n        [Fact]\n        public void BindComplexModelCanBindDictionariesWithBracketsNotation()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(IDictionary<string, CountryState>)),\n                ModelName = \"countries\",\n                PropertyFilter = _ => true,\n                ValueProvider = new DictionaryValueProvider<object>(new Dictionary<string, object>()\n                {\n                    { \"countries[CA].Name\", \"Canada\" },\n                    { \"countries[CA].States[0]\", \"Québec\" },\n                    { \"countries[CA].States[1]\", \"British Columbia\" },\n                    { \"countries[US].Name\", \"United States\" },\n                    { \"countries[US].States[0]\", \"Washington\" },\n                    { \"countries[US].States[1]\", \"Oregon\" }\n                }, CultureInfo.CurrentCulture)\n            };\n\n            DefaultModelBinder binder = new DefaultModelBinder();\n\n            // Act\n            object newModel = binder.BindComplexModel(controllerContext, bindingContext);\n\n            // Assert\n            var modelAsDictionary = Assert.IsAssignableFrom<IDictionary<string, CountryState>>(newModel);\n            Assert.Equal(2, modelAsDictionary.Count);\n            Assert.Equal(\"Canada\", modelAsDictionary[\"CA\"].Name);\n            Assert.Equal(\"United States\", modelAsDictionary[\"US\"].Name);\n            Assert.Equal(2, modelAsDictionary[\"CA\"].States.Count());\n            Assert.Contains(\"Québec\", modelAsDictionary[\"CA\"].States);\n            Assert.Contains(\"British Columbia\", modelAsDictionary[\"CA\"].States);\n            Assert.Equal(2, modelAsDictionary[\"US\"].States.Count());\n            Assert.Contains(\"Washington\", modelAsDictionary[\"US\"].States);\n            Assert.Contains(\"Oregon\", modelAsDictionary[\"US\"].States);\n        }\n\n        [Fact]\n        public void BindComplexModelCanBindDictionariesWithBracketsAndDotsNotation()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(IDictionary<string, CountryState>)),\n                ModelName = \"countries\",\n                PropertyFilter = _ => true,\n                ValueProvider = new DictionaryValueProvider<object>(new Dictionary<string, object>()\n                {\n                    { \"countries[CA].Name\", \"Canada\" },\n                    { \"countries[CA].States[0]\", \"Québec\" },\n                    { \"countries.CA.States[1]\", \"British Columbia\" },\n                    { \"countries.US.Name\", \"United States\" },\n                    { \"countries.US.States[0]\", \"Washington\" },\n                    { \"countries.US.States[1]\", \"Oregon\" }\n                }, CultureInfo.CurrentCulture)\n            };\n\n            DefaultModelBinder binder = new DefaultModelBinder();\n\n            // Act\n            object newModel = binder.BindComplexModel(controllerContext, bindingContext);\n\n            // Assert\n            var modelAsDictionary = Assert.IsAssignableFrom<IDictionary<string, CountryState>>(newModel);\n            Assert.Equal(2, modelAsDictionary.Count);\n            Assert.Equal(\"Canada\", modelAsDictionary[\"CA\"].Name);\n            Assert.Equal(\"United States\", modelAsDictionary[\"US\"].Name);\n            string state = Assert.Single(modelAsDictionary[\"CA\"].States);\n            Assert.Contains(\"Québec\", state);\n\n            // We do not accept double notation for a same entry, so we can't find that state.\n            Assert.DoesNotContain(\"British Columbia\", state);\n            Assert.Equal(2, modelAsDictionary[\"US\"].States.Count());\n            Assert.Contains(\"Washington\", modelAsDictionary[\"US\"].States);\n            Assert.Contains(\"Oregon\", modelAsDictionary[\"US\"].States);\n        }\n\n        [Fact]\n        public void BindComplexModelCanBindDictionaries()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(IDictionary<int, string>)),\n                ModelName = \"foo\",\n                PropertyFilter = _ => false,\n                ValueProvider = new SimpleValueProvider()\n                {\n                    { \"foo[0].key\", null }, { \"foo[0].value\", null },\n                    { \"foo[1].key\", null }, { \"foo[1].value\", null },\n                    { \"foo[2].key\", null }, { \"foo[2].value\", null }\n                }\n            };\n\n            Mock<IModelBinder> mockIntBinder = new Mock<IModelBinder>();\n            mockIntBinder\n                .Setup(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ModelBindingContext bc)\n                    {\n                        Assert.Equal(controllerContext, cc);\n                        Assert.Equal(typeof(int), bc.ModelType);\n                        Assert.Equal(bindingContext.ModelState, bc.ModelState);\n                        Assert.Equal(new ModelBindingContext().PropertyFilter, bc.PropertyFilter);\n                        Assert.Equal(bindingContext.ValueProvider, bc.ValueProvider);\n                        return Int32.Parse(bc.ModelName.Substring(4, 1), CultureInfo.InvariantCulture) + 10;\n                    });\n\n            Mock<IModelBinder> mockStringBinder = new Mock<IModelBinder>();\n            mockStringBinder\n                .Setup(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ModelBindingContext bc)\n                    {\n                        Assert.Equal(controllerContext, cc);\n                        Assert.Equal(typeof(string), bc.ModelType);\n                        Assert.Equal(bindingContext.ModelState, bc.ModelState);\n                        Assert.Equal(bindingContext.PropertyFilter, bc.PropertyFilter);\n                        Assert.Equal(bindingContext.ValueProvider, bc.ValueProvider);\n                        return (Int32.Parse(bc.ModelName.Substring(4, 1), CultureInfo.InvariantCulture) + 10) + \"Value\";\n                    });\n\n            DefaultModelBinder binder = new DefaultModelBinder()\n            {\n                Binders = new ModelBinderDictionary()\n                {\n                    { typeof(int), mockIntBinder.Object },\n                    { typeof(string), mockStringBinder.Object }\n                }\n            };\n\n            // Act\n            object newModel = binder.BindComplexModel(controllerContext, bindingContext);\n\n            // Assert\n            var modelAsDictionary = Assert.IsAssignableFrom<IDictionary<int, string>>(newModel);\n            Assert.Equal(3, modelAsDictionary.Count);\n            Assert.Equal(\"10Value\", modelAsDictionary[10]);\n            Assert.Equal(\"11Value\", modelAsDictionary[11]);\n            Assert.Equal(\"12Value\", modelAsDictionary[12]);\n        }\n\n        [Fact]\n        public void BindComplexModelCanBindObjects()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n\n            ModelWithoutBindAttribute model = new ModelWithoutBindAttribute()\n            {\n                Foo = \"FooPreValue\",\n                Bar = \"BarPreValue\",\n                Baz = \"BazPreValue\",\n            };\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),\n                ValueProvider = new SimpleValueProvider() { { \"Foo\", null }, { \"Bar\", null } }\n            };\n\n            Mock<IModelBinder> mockInnerBinder = new Mock<IModelBinder>();\n            mockInnerBinder\n                .Setup(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ModelBindingContext bc)\n                    {\n                        Assert.Equal(controllerContext, cc);\n                        Assert.Equal(bindingContext.ValueProvider, bc.ValueProvider);\n                        return bc.ModelName + \"PostValue\";\n                    });\n\n            DefaultModelBinder binder = new DefaultModelBinder()\n            {\n                Binders = new ModelBinderDictionary()\n                {\n                    { typeof(string), mockInnerBinder.Object }\n                }\n            };\n\n            // Act\n            object updatedModel = binder.BindComplexModel(controllerContext, bindingContext);\n\n            // Assert\n            Assert.Same(model, updatedModel);\n            Assert.Equal(\"FooPostValue\", model.Foo);\n            Assert.Equal(\"BarPostValue\", model.Bar);\n            Assert.Equal(\"BazPreValue\", model.Baz);\n        }\n\n        [Fact]\n        public void BindComplexModelReturnsNullArrayIfNoValuesProvided()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(int[])),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider() { { \"foo\", null } }\n            };\n\n            Mock<IModelBinder> mockInnerBinder = new Mock<IModelBinder>();\n            mockInnerBinder\n                .Setup(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ModelBindingContext bc) { return Int32.Parse(bc.ModelName.Substring(4, 1), CultureInfo.InvariantCulture); });\n\n            DefaultModelBinder binder = new DefaultModelBinder()\n            {\n                Binders = new ModelBinderDictionary()\n                {\n                    { typeof(int), mockInnerBinder.Object }\n                }\n            };\n\n            // Act\n            object newModel = binder.BindComplexModel(null, bindingContext);\n\n            // Assert\n            Assert.Null(newModel);\n        }\n\n        [Fact]\n        public void BindComplexModelWhereModelTypeContainsBindAttribute()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n\n            ModelWithBindAttribute model = new ModelWithBindAttribute()\n            {\n                Foo = \"FooPreValue\",\n                Bar = \"BarPreValue\",\n                Baz = \"BazPreValue\",\n            };\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),\n                ValueProvider = new SimpleValueProvider() { { \"Foo\", null }, { \"Bar\", null } }\n            };\n\n            Mock<IModelBinder> mockInnerBinder = new Mock<IModelBinder>();\n            mockInnerBinder\n                .Setup(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ModelBindingContext bc)\n                    {\n                        Assert.Equal(controllerContext, cc);\n                        Assert.Equal(bindingContext.ValueProvider, bc.ValueProvider);\n                        return bc.ModelName + \"PostValue\";\n                    });\n\n            DefaultModelBinder binder = new DefaultModelBinder()\n            {\n                Binders = new ModelBinderDictionary()\n                {\n                    { typeof(string), mockInnerBinder.Object }\n                }\n            };\n\n            // Act\n            binder.BindComplexModel(controllerContext, bindingContext);\n\n            // Assert\n            Assert.Equal(\"FooPreValue\", model.Foo);\n            Assert.Equal(\"BarPostValue\", model.Bar);\n            Assert.Equal(\"BazPreValue\", model.Baz);\n        }\n\n        [Fact]\n        public void BindComplexModelWhereModelTypeDoesNotContainBindAttribute()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n\n            ModelWithoutBindAttribute model = new ModelWithoutBindAttribute()\n            {\n                Foo = \"FooPreValue\",\n                Bar = \"BarPreValue\",\n                Baz = \"BazPreValue\",\n            };\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),\n                ValueProvider = new SimpleValueProvider() { { \"Foo\", null }, { \"Bar\", null } }\n            };\n\n            Mock<IModelBinder> mockInnerBinder = new Mock<IModelBinder>();\n            mockInnerBinder\n                .Setup(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ModelBindingContext bc)\n                    {\n                        Assert.Equal(controllerContext, cc);\n                        Assert.Equal(bindingContext.ValueProvider, bc.ValueProvider);\n                        return bc.ModelName + \"PostValue\";\n                    });\n\n            DefaultModelBinder binder = new DefaultModelBinder()\n            {\n                Binders = new ModelBinderDictionary()\n                {\n                    { typeof(string), mockInnerBinder.Object }\n                }\n            };\n\n            // Act\n            binder.BindComplexModel(controllerContext, bindingContext);\n\n            // Assert\n            Assert.Equal(\"FooPostValue\", model.Foo);\n            Assert.Equal(\"BarPostValue\", model.Bar);\n            Assert.Equal(\"BazPreValue\", model.Baz);\n        }\n\n        // BindModel tests\n\n        [Fact]\n        public void BindModelCanBindObjects()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n\n            ModelWithoutBindAttribute model = new ModelWithoutBindAttribute()\n            {\n                Foo = \"FooPreValue\",\n                Bar = \"BarPreValue\",\n                Baz = \"BazPreValue\",\n            };\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),\n                ValueProvider = new SimpleValueProvider() { { \"Foo\", null }, { \"Bar\", null } }\n            };\n\n            Mock<IModelBinder> mockInnerBinder = new Mock<IModelBinder>();\n            mockInnerBinder\n                .Setup(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ModelBindingContext bc)\n                    {\n                        Assert.Equal(controllerContext, cc);\n                        Assert.Equal(bindingContext.ValueProvider, bc.ValueProvider);\n                        return bc.ModelName + \"PostValue\";\n                    });\n\n            DefaultModelBinder binder = new DefaultModelBinder()\n            {\n                Binders = new ModelBinderDictionary()\n                {\n                    { typeof(string), mockInnerBinder.Object }\n                }\n            };\n\n            // Act\n            object updatedModel = binder.BindModel(controllerContext, bindingContext);\n\n            // Assert\n            Assert.Same(model, updatedModel);\n            Assert.Equal(\"FooPostValue\", model.Foo);\n            Assert.Equal(\"BarPostValue\", model.Bar);\n            Assert.Equal(\"BazPreValue\", model.Baz);\n        }\n\n        [Fact]\n        public void BindModelCanBindSimpleTypes()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(int)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider()\n                {\n                    { \"foo\", \"42\" }\n                }\n            };\n\n            DefaultModelBinder binder = new DefaultModelBinder();\n\n            // Act\n            object updatedModel = binder.BindModel(new ControllerContext(), bindingContext);\n\n            // Assert\n            Assert.Equal(42, updatedModel);\n        }\n\n        [Fact]\n        public void BindModel_PerformsValidationByDefault()\n        {\n            // Arrange\n            ModelMetadata metadata = new DataAnnotationsModelMetadataProvider().GetMetadataForType(null, typeof(string));\n\n            ControllerContext controllerContext = new ControllerContext();\n            controllerContext.Controller = new SimpleController();\n\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = metadata,\n                ModelName = \"foo\",\n                ValueProvider = new CustomUnvalidatedValueProvider()\n            };\n\n            DefaultModelBinder binder = new DefaultModelBinder();\n\n            // Act\n            object updatedModel = binder.BindModel(controllerContext, bindingContext);\n\n            // Assert\n            Assert.Equal(\"fooValidated\", updatedModel);\n        }\n\n        [Fact]\n        public void BindModel_SkipsValidationIfControllerOptsOut()\n        {\n            // Arrange\n            ModelMetadata metadata = new DataAnnotationsModelMetadataProvider().GetMetadataForType(null, typeof(string));\n\n            ControllerContext controllerContext = new ControllerContext();\n            controllerContext.Controller = new SimpleController();\n            controllerContext.Controller.ValidateRequest = false;\n\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = metadata,\n                ModelName = \"foo\",\n                ValueProvider = new CustomUnvalidatedValueProvider()\n            };\n\n            DefaultModelBinder binder = new DefaultModelBinder();\n\n            // Act\n            object updatedModel = binder.BindModel(controllerContext, bindingContext);\n\n            // Assert\n            Assert.Equal(\"fooUnvalidated\", updatedModel);\n        }\n\n        [Fact]\n        public void BindModel_SkipsValidationIfModelOptsOut()\n        {\n            // Arrange\n            ModelMetadata metadata = new DataAnnotationsModelMetadataProvider().GetMetadataForType(null, typeof(string));\n            metadata.RequestValidationEnabled = false;\n\n            ControllerContext controllerContext = new ControllerContext();\n            controllerContext.Controller = new SimpleController();\n\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = metadata,\n                ModelName = \"foo\",\n                ValueProvider = new CustomUnvalidatedValueProvider()\n            };\n\n            DefaultModelBinder binder = new DefaultModelBinder();\n\n            // Act\n            object updatedModel = binder.BindModel(controllerContext, bindingContext);\n\n            // Assert\n            Assert.Equal(\"fooUnvalidated\", updatedModel);\n        }\n\n        [Fact]\n        public void BindModelReturnsNullIfKeyNotFound()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(int)),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider()\n            };\n\n            DefaultModelBinder binder = new DefaultModelBinder();\n\n            // Act\n            object returnedModel = binder.BindModel(new ControllerContext(), bindingContext);\n\n            // Assert\n            Assert.Null(returnedModel);\n        }\n\n        [Fact]\n        public void BindModelThrowsIfBindingContextIsNull()\n        {\n            // Arrange\n            DefaultModelBinder binder = new DefaultModelBinder();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { binder.BindModel(new ControllerContext(), null); }, \"bindingContext\");\n        }\n\n        [Fact]\n        public void BindModelValuesCanBeOverridden()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => new ModelWithoutBindAttribute(), typeof(ModelWithoutBindAttribute)),\n                ModelName = \"\",\n                ValueProvider = new SimpleValueProvider()\n                {\n                    { \"foo\", \"FooPostValue\" },\n                    { \"bar\", \"BarPostValue\" },\n                    { \"baz\", \"BazPostValue\" }\n                }\n            };\n            Mock<DefaultModelBinder> binder = new Mock<DefaultModelBinder> { CallBase = true };\n            binder.Protected().Setup<object>(\"GetPropertyValue\",\n                                             ItExpr.IsAny<ControllerContext>(), ItExpr.IsAny<ModelBindingContext>(),\n                                             ItExpr.IsAny<PropertyDescriptor>(), ItExpr.IsAny<IModelBinder>())\n                .Returns(\"Hello, world!\");\n\n            // Act\n            ModelWithoutBindAttribute model = (ModelWithoutBindAttribute)binder.Object.BindModel(new ControllerContext(), bindingContext);\n\n            // Assert\n            Assert.Equal(\"Hello, world!\", model.Bar);\n            Assert.Equal(\"Hello, world!\", model.Baz);\n            Assert.Equal(\"Hello, world!\", model.Foo);\n        }\n\n        [Fact]\n        public void BindModelWithTypeConversionErrorUpdatesModelStateMessage()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => new PropertyTestingModel(), typeof(PropertyTestingModel)),\n                ModelName = \"\",\n                ValueProvider = new SimpleValueProvider()\n                {\n                    { \"IntReadWrite\", \"foo\" }\n                },\n            };\n            DefaultModelBinder binder = new DefaultModelBinder();\n\n            // Act\n            PropertyTestingModel model = (PropertyTestingModel)binder.BindModel(new ControllerContext(), bindingContext);\n\n            // Assert\n            ModelState modelState = bindingContext.ModelState[\"IntReadWrite\"];\n            Assert.NotNull(modelState);\n            ModelError error = Assert.Single(modelState.Errors);\n            Assert.Equal(\"The value 'foo' is not valid for IntReadWrite.\", error.ErrorMessage);\n        }\n\n        [Fact]\n        public void BindModelWithPrefix()\n        {\n            // Arrange\n            ModelWithoutBindAttribute model = new ModelWithoutBindAttribute()\n            {\n                Foo = \"FooPreValue\",\n                Bar = \"BarPreValue\",\n                Baz = \"BazPreValue\",\n            };\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),\n                ModelName = \"prefix\",\n                ValueProvider = new SimpleValueProvider()\n                {\n                    { \"prefix.foo\", \"FooPostValue\" },\n                    { \"prefix.bar\", \"BarPostValue\" }\n                }\n            };\n\n            DefaultModelBinder binder = new DefaultModelBinder();\n\n            // Act\n            object updatedModel = binder.BindModel(new ControllerContext(), bindingContext);\n\n            // Assert\n            Assert.Same(model, updatedModel);\n            Assert.Equal(\"FooPostValue\", model.Foo);\n            Assert.Equal(\"BarPostValue\", model.Bar);\n            Assert.Equal(\"BazPreValue\", model.Baz);\n        }\n\n        [Fact]\n        public void BindModelWithPrefixAndFallback()\n        {\n            // Arrange\n            ModelWithoutBindAttribute model = new ModelWithoutBindAttribute()\n            {\n                Foo = \"FooPreValue\",\n                Bar = \"BarPreValue\",\n                Baz = \"BazPreValue\",\n            };\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                FallbackToEmptyPrefix = true,\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),\n                ModelName = \"prefix\",\n                ValueProvider = new SimpleValueProvider()\n                {\n                    { \"foo\", \"FooPostValue\" },\n                    { \"bar\", \"BarPostValue\" }\n                }\n            };\n\n            DefaultModelBinder binder = new DefaultModelBinder();\n\n            // Act\n            object updatedModel = binder.BindModel(new ControllerContext(), bindingContext);\n\n            // Assert\n            Assert.Same(model, updatedModel);\n            Assert.Equal(\"FooPostValue\", model.Foo);\n            Assert.Equal(\"BarPostValue\", model.Bar);\n            Assert.Equal(\"BazPreValue\", model.Baz);\n        }\n\n        [Fact]\n        public void BindModelWithPrefixReturnsNullIfFallbackNotSpecifiedAndValueProviderContainsNoEntries()\n        {\n            // Arrange\n            ModelWithoutBindAttribute model = new ModelWithoutBindAttribute()\n            {\n                Foo = \"FooPreValue\",\n                Bar = \"BarPreValue\",\n                Baz = \"BazPreValue\",\n            };\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),\n                ModelName = \"prefix\",\n                ValueProvider = new SimpleValueProvider()\n                {\n                    { \"foo\", \"FooPostValue\" },\n                    { \"bar\", \"BarPostValue\" }\n                }\n            };\n\n            DefaultModelBinder binder = new DefaultModelBinder();\n\n            // Act\n            object updatedModel = binder.BindModel(new ControllerContext(), bindingContext);\n\n            // Assert\n            Assert.Null(updatedModel);\n        }\n\n        [Fact]\n        public void BindModelReturnsNullIfSimpleTypeNotFound()\n        {\n            // DevDiv 216165: ModelBinders should not try and instantiate simple types\n\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(string)),\n                ModelName = \"prefix\",\n                ValueProvider = new SimpleValueProvider()\n                {\n                    { \"prefix.foo\", \"foo\" },\n                    { \"prefix.bar\", \"bar\" }\n                }\n            };\n\n            DefaultModelBinder binder = new DefaultModelBinder();\n\n            // Act\n            object updatedModel = binder.BindModel(new ControllerContext(), bindingContext);\n\n            // Assert\n            Assert.Null(updatedModel);\n        }\n\n        // BindProperty tests\n\n        [Fact]\n        public void BindPropertyCanUpdateComplexReadOnlyProperties()\n        {\n            // Arrange\n            // the Customer type contains a single read-only Address property\n            Customer model = new Customer();\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),\n                ValueProvider = new SimpleValueProvider() { { \"Address\", null } }\n            };\n\n            Mock<IModelBinder> mockInnerBinder = new Mock<IModelBinder>();\n            mockInnerBinder\n                .Setup(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ModelBindingContext bc)\n                    {\n                        Address address = (Address)bc.Model;\n                        address.Street = \"1 Microsoft Way\";\n                        address.Zip = \"98052\";\n                        return address;\n                    });\n\n            PropertyDescriptor pd = TypeDescriptor.GetProperties(model)[\"Address\"];\n            DefaultModelBinderHelper helper = new DefaultModelBinderHelper()\n            {\n                Binders = new ModelBinderDictionary()\n                {\n                    { typeof(Address), mockInnerBinder.Object }\n                }\n            };\n\n            // Act\n            helper.PublicBindProperty(new ControllerContext(), bindingContext, pd);\n\n            // Assert\n            Assert.Equal(\"1 Microsoft Way\", model.Address.Street);\n            Assert.Equal(\"98052\", model.Address.Zip);\n        }\n\n        [Fact]\n        public void BindPropertyDoesNothingIfValueProviderContainsNoEntryForProperty()\n        {\n            // Arrange\n            MyModel2 model = new MyModel2() { IntReadWrite = 3 };\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),\n                ValueProvider = new SimpleValueProvider()\n            };\n\n            PropertyDescriptor pd = TypeDescriptor.GetProperties(model)[\"IntReadWrite\"];\n            DefaultModelBinderHelper helper = new DefaultModelBinderHelper();\n\n            // Act\n            helper.PublicBindProperty(new ControllerContext(), bindingContext, pd);\n\n            // Assert\n            Assert.Equal(3, model.IntReadWrite);\n        }\n\n        [Fact]\n        public void BindProperty()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n            MyModel2 model = new MyModel2() { IntReadWrite = 3 };\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),\n                ValueProvider = new SimpleValueProvider()\n                {\n                    { \"IntReadWrite\", \"42\" }\n                }\n            };\n\n            PropertyDescriptor pd = TypeDescriptor.GetProperties(model)[\"IntReadWrite\"];\n\n            Mock<DefaultModelBinderHelper> mockHelper = new Mock<DefaultModelBinderHelper>() { CallBase = true };\n            mockHelper.Setup(b => b.PublicOnPropertyValidating(controllerContext, bindingContext, pd, 42)).Returns(true).Verifiable();\n            mockHelper.Setup(b => b.PublicSetProperty(controllerContext, bindingContext, pd, 42)).Verifiable();\n            mockHelper.Setup(b => b.PublicOnPropertyValidated(controllerContext, bindingContext, pd, 42)).Verifiable();\n            DefaultModelBinderHelper helper = mockHelper.Object;\n\n            // Act\n            helper.PublicBindProperty(controllerContext, bindingContext, pd);\n\n            // Assert\n            mockHelper.Verify();\n        }\n\n        [Fact]\n        public void BindPropertyReturnsIfOnPropertyValidatingReturnsFalse()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n            MyModel2 model = new MyModel2() { IntReadWrite = 3 };\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),\n                ValueProvider = new SimpleValueProvider()\n                {\n                    { \"IntReadWrite\", \"42\" }\n                }\n            };\n\n            PropertyDescriptor pd = TypeDescriptor.GetProperties(model)[\"IntReadWrite\"];\n\n            Mock<DefaultModelBinderHelper> mockHelper = new Mock<DefaultModelBinderHelper>() { CallBase = true };\n            mockHelper.Setup(b => b.PublicOnPropertyValidating(controllerContext, bindingContext, pd, 42)).Returns(false);\n            DefaultModelBinderHelper helper = mockHelper.Object;\n\n            // Act\n            helper.PublicBindProperty(controllerContext, bindingContext, pd);\n\n            // Assert\n            Assert.Equal(3, model.IntReadWrite);\n            mockHelper.Verify();\n            mockHelper.Verify(b => b.PublicSetProperty(controllerContext, bindingContext, pd, 42), Times.Never());\n            mockHelper.Verify(b => b.PublicOnPropertyValidated(controllerContext, bindingContext, pd, 42), Times.Never());\n        }\n\n        [Fact]\n        public void BindPropertySetsPropertyToNullIfUserLeftTextEntryFieldBlankForOptionalValue()\n        {\n            // Arrange\n            MyModel2 model = new MyModel2() { NullableIntReadWrite = 8 };\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),\n                ValueProvider = new SimpleValueProvider() { { \"NullableIntReadWrite\", null } }\n            };\n\n            Mock<IModelBinder> mockInnerBinder = new Mock<IModelBinder>();\n            mockInnerBinder.Setup(b => b.BindModel(new ControllerContext(), It.IsAny<ModelBindingContext>())).Returns((object)null);\n\n            PropertyDescriptor pd = TypeDescriptor.GetProperties(model)[\"NullableIntReadWrite\"];\n            DefaultModelBinderHelper helper = new DefaultModelBinderHelper()\n            {\n                Binders = new ModelBinderDictionary()\n                {\n                    { typeof(int?), mockInnerBinder.Object }\n                }\n            };\n\n            // Act\n            helper.PublicBindProperty(new ControllerContext(), bindingContext, pd);\n\n            // Assert\n            Assert.Empty(bindingContext.ModelState);\n            Assert.Null(model.NullableIntReadWrite);\n        }\n\n        [Fact]\n        public void BindPropertyUpdatesPropertyOnFailureIfInnerBinderReturnsNonNullObject()\n        {\n            // Arrange\n            MyModel2 model = new MyModel2() { IntReadWriteNonNegative = 8 };\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),\n                ValueProvider = new SimpleValueProvider() { { \"IntReadWriteNonNegative\", null } }\n            };\n\n            Mock<IModelBinder> mockInnerBinder = new Mock<IModelBinder>();\n            mockInnerBinder\n                .Setup(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ModelBindingContext bc)\n                    {\n                        bc.ModelState.AddModelError(\"IntReadWriteNonNegative\", \"Some error text.\");\n                        return 4;\n                    });\n\n            PropertyDescriptor pd = TypeDescriptor.GetProperties(model)[\"IntReadWriteNonNegative\"];\n            DefaultModelBinderHelper helper = new DefaultModelBinderHelper()\n            {\n                Binders = new ModelBinderDictionary()\n                {\n                    { typeof(int), mockInnerBinder.Object }\n                }\n            };\n\n            // Act\n            helper.PublicBindProperty(new ControllerContext(), bindingContext, pd);\n\n            // Assert\n            Assert.False(bindingContext.ModelState.IsValidField(\"IntReadWriteNonNegative\"));\n            var error = Assert.Single(bindingContext.ModelState[\"IntReadWriteNonNegative\"].Errors);\n            Assert.Equal(\"Some error text.\", error.ErrorMessage);\n            Assert.Equal(4, model.IntReadWriteNonNegative);\n        }\n\n        [Fact]\n        public void BindPropertyUpdatesPropertyOnSuccess()\n        {\n            // Arrange\n            // Effectively, this is just testing updating a single property named \"IntReadWrite\"\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n\n            MyModel2 model = new MyModel2() { IntReadWrite = 3 };\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),\n                ModelName = \"foo\",\n                ModelState = new ModelStateDictionary() { { \"blah\", new ModelState() } },\n                ValueProvider = new SimpleValueProvider() { { \"foo.IntReadWrite\", null } }\n            };\n\n            Mock<IModelBinder> mockInnerBinder = new Mock<IModelBinder>();\n            mockInnerBinder\n                .Setup(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ModelBindingContext bc)\n                    {\n                        Assert.Equal(controllerContext, cc);\n                        Assert.Equal(3, bc.Model);\n                        Assert.Equal(typeof(int), bc.ModelType);\n                        Assert.Equal(\"foo.IntReadWrite\", bc.ModelName);\n                        Assert.Equal(new ModelBindingContext().PropertyFilter, bc.PropertyFilter);\n                        Assert.Equal(bindingContext.ModelState, bc.ModelState);\n                        Assert.Equal(bindingContext.ValueProvider, bc.ValueProvider);\n                        return 4;\n                    });\n\n            PropertyDescriptor pd = TypeDescriptor.GetProperties(model)[\"IntReadWrite\"];\n            DefaultModelBinderHelper helper = new DefaultModelBinderHelper()\n            {\n                Binders = new ModelBinderDictionary()\n                {\n                    { typeof(int), mockInnerBinder.Object }\n                }\n            };\n\n            // Act\n            helper.PublicBindProperty(controllerContext, bindingContext, pd);\n\n            // Assert\n            Assert.Equal(4, model.IntReadWrite);\n        }\n\n        [Theory]\n        [InlineData(typeof(OverflowException))]\n        [InlineData(typeof(FormatException))]\n        public void BindPropertyReplaceErrorMessages(Type exceptionType)\n        {\n            // Arrange\n            const string propertyName = \"IntReadWriteNonNegative\";\n            MyModel2 model = new MyModel2() { IntReadWriteNonNegative = 8 };\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),\n                ValueProvider = new SimpleValueProvider() { { propertyName, null } }\n            };\n\n            Mock<IModelBinder> mockInnerBinder = new Mock<IModelBinder>();\n            mockInnerBinder\n                .Setup(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ModelBindingContext bc)\n                    {\n                        bc.ModelState.AddModelError(propertyName, new Exception(\"\", (Exception) Activator.CreateInstance(exceptionType)));\n                        bc.ModelState[propertyName].Value = new ValueProviderResult(8, \"8\", CultureInfo.InvariantCulture);\n                        return 4;\n                    });\n\n            PropertyDescriptor pd = TypeDescriptor.GetProperties(model)[propertyName];\n            DefaultModelBinderHelper helper = new DefaultModelBinderHelper()\n            {\n                Binders = new ModelBinderDictionary()\n                {\n                    { typeof(int), mockInnerBinder.Object }\n                }\n            };\n\n            // Act\n            helper.PublicBindProperty(new ControllerContext(), bindingContext, pd);\n\n            // Assert\n            Assert.False(bindingContext.ModelState.IsValidField(propertyName));\n            var error = Assert.Single(bindingContext.ModelState[propertyName].Errors);\n            Assert.Equal(\"The value '8' is not valid for \" + propertyName + \".\", error.ErrorMessage);\n            Assert.Equal(4, model.IntReadWriteNonNegative);\n        }\n\n        [Theory]\n        [InlineData(typeof(MissingMemberException))]\n        [InlineData(typeof(IndexOutOfRangeException))]\n        public void BindPropertyNotShowErrorMessage(Type exceptionType)\n        {\n            // Arrange\n            const string propertyName = \"IntReadWriteNonNegative\";\n            MyModel2 model = new MyModel2() { IntReadWriteNonNegative = 8 };\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),\n                ValueProvider = new SimpleValueProvider() { { propertyName, null } }\n            };\n\n            Mock<IModelBinder> mockInnerBinder = new Mock<IModelBinder>();\n            mockInnerBinder\n                .Setup(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ModelBindingContext bc)\n                    {\n                        bc.ModelState.AddModelError(propertyName, new Exception(\"\", (Exception)Activator.CreateInstance(exceptionType)));\n                        bc.ModelState[propertyName].Value = new ValueProviderResult(8, \"8\", CultureInfo.InvariantCulture);\n                        return 4;\n                    });\n\n            PropertyDescriptor pd = TypeDescriptor.GetProperties(model)[propertyName];\n            DefaultModelBinderHelper helper = new DefaultModelBinderHelper()\n            {\n                Binders = new ModelBinderDictionary()\n                {\n                    { typeof(int), mockInnerBinder.Object }\n                }\n            };\n\n            // Act\n            helper.PublicBindProperty(new ControllerContext(), bindingContext, pd);\n\n            // Assert\n            Assert.False(bindingContext.ModelState.IsValidField(propertyName));\n            var error = Assert.Single(bindingContext.ModelState[propertyName].Errors);\n            Assert.Equal(String.Empty, error.ErrorMessage);\n            Assert.Equal(4, model.IntReadWriteNonNegative);\n        }\n\n        // BindSimpleModel tests\n\n        [Fact]\n        public void BindSimpleModelCanReturnArrayTypes()\n        {\n            // Arrange\n            ValueProviderResult result = new ValueProviderResult(42, null, null);\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(int[])),\n                ModelName = \"foo\",\n            };\n\n            DefaultModelBinder binder = new DefaultModelBinder();\n\n            // Act\n            object returnedValue = binder.BindSimpleModel(null, bindingContext, result);\n\n            // Assert\n            var returnedValueAsIntArray = Assert.IsType<int[]>(returnedValue);\n            var returnedInt = Assert.Single(returnedValueAsIntArray);\n            Assert.Equal(42, returnedInt);\n        }\n\n        [Fact]\n        public void BindSimpleModelCanReturnCollectionTypes()\n        {\n            // Arrange\n            ValueProviderResult result = new ValueProviderResult(new string[] { \"42\", \"82\" }, null, null);\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(IEnumerable<int>)),\n                ModelName = \"foo\",\n            };\n\n            DefaultModelBinder binder = new DefaultModelBinder();\n\n            // Act\n            object returnedValue = binder.BindSimpleModel(null, bindingContext, result);\n\n            // Assert\n            var returnedValueAsList = Assert.IsAssignableFrom<IEnumerable<int>>(returnedValue).ToList();\n            Assert.Equal(2, returnedValueAsList.Count);\n            Assert.Equal(42, returnedValueAsList[0]);\n            Assert.Equal(82, returnedValueAsList[1]);\n        }\n\n        [Fact]\n        public void BindSimpleModelCanReturnElementalTypes()\n        {\n            // Arrange\n            ValueProviderResult result = new ValueProviderResult(\"42\", null, null);\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(int)),\n                ModelName = \"foo\",\n            };\n\n            DefaultModelBinder binder = new DefaultModelBinder();\n\n            // Act\n            object returnedValue = binder.BindSimpleModel(null, bindingContext, result);\n\n            // Assert\n            Assert.Equal(42, returnedValue);\n        }\n\n        [Fact]\n        public void BindSimpleModelCanReturnStrings()\n        {\n            // Arrange\n            ValueProviderResult result = new ValueProviderResult(new object[] { \"42\" }, null, null);\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(string)),\n                ModelName = \"foo\",\n            };\n\n            DefaultModelBinder binder = new DefaultModelBinder();\n\n            // Act\n            object returnedValue = binder.BindSimpleModel(null, bindingContext, result);\n\n            // Assert\n            Assert.Equal(\"42\", returnedValue);\n        }\n\n        [Fact]\n        public void BindSimpleModelChecksValueProviderResultRawValueType()\n        {\n            // Arrange\n            ValueProviderResult result = new ValueProviderResult(new MemoryStream(), null, null);\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(Stream)),\n                ModelName = \"foo\",\n            };\n\n            DefaultModelBinder binder = new DefaultModelBinder();\n\n            // Act\n            object returnedValue = binder.BindSimpleModel(null, bindingContext, result);\n\n            // Assert\n            Assert.Equal(result, bindingContext.ModelState[\"foo\"].Value);\n            Assert.Same(result.RawValue, returnedValue);\n        }\n\n        [Fact]\n        public void BindSimpleModelPropagatesErrorsOnFailure()\n        {\n            // Arrange\n            ValueProviderResult result = new ValueProviderResult(\"invalid\", null, null);\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(int)),\n                ModelName = \"foo\",\n            };\n\n            DefaultModelBinder binder = new DefaultModelBinder();\n\n            // Act\n            object returnedValue = binder.BindSimpleModel(null, bindingContext, result);\n\n            // Assert\n            Assert.False(bindingContext.ModelState.IsValidField(\"foo\"));\n            InvalidOperationException exception = Assert.IsType<InvalidOperationException>(bindingContext.ModelState[\"foo\"].Errors[0].Exception);\n            Assert.Equal(\"The parameter conversion from type 'System.String' to type 'System.Int32' failed. See the inner exception for more information.\", exception.Message);\n            Assert.Null(returnedValue);\n        }\n\n        [Fact]\n        public void CreateComplexElementalModelBindingContext_ReadsBindAttributeFromBuddyClass()\n        {\n            // Arrange\n            ModelBindingContext originalBindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(CreateComplexElementalModelBindingContext_ReadsBindAttributeFromBuddyClass_Model)),\n                ModelName = \"someName\",\n                ValueProvider = new SimpleValueProvider()\n            };\n\n            DefaultModelBinder binder = new DefaultModelBinder();\n\n            // Act\n            ModelBindingContext newBindingContext = binder.CreateComplexElementalModelBindingContext(new ControllerContext(), originalBindingContext, null);\n\n            // Assert\n            Assert.True(newBindingContext.PropertyFilter(\"foo\"));\n            Assert.False(newBindingContext.PropertyFilter(\"bar\"));\n        }\n\n        [MetadataType(typeof(CreateComplexElementalModelBindingContext_ReadsBindAttributeFromBuddyClass_Model_BuddyClass))]\n        private class CreateComplexElementalModelBindingContext_ReadsBindAttributeFromBuddyClass_Model\n        {\n            [Bind(Include = \"foo\")]\n            private class CreateComplexElementalModelBindingContext_ReadsBindAttributeFromBuddyClass_Model_BuddyClass\n            {\n            }\n        }\n\n        [Fact]\n        public void CreateInstanceCreatesModelInstance()\n        {\n            // Arrange\n            DefaultModelBinderHelper helper = new DefaultModelBinderHelper();\n\n            // Act\n            object modelObj = helper.PublicCreateModel(null, null, typeof(Guid));\n\n            // Assert\n            Assert.Equal(Guid.Empty, modelObj);\n        }\n\n        [Fact]\n        public void CreateInstanceCreatesModelInstanceForGenericICollection()\n        {\n            // Arrange\n            DefaultModelBinderHelper helper = new DefaultModelBinderHelper();\n\n            // Act\n            object modelObj = helper.PublicCreateModel(null, null, typeof(ICollection<Guid>));\n\n            // Assert\n            Assert.IsAssignableFrom<ICollection<Guid>>(modelObj);\n        }\n\n        [Fact]\n        public void CreateInstanceCreatesModelInstanceForGenericIDictionary()\n        {\n            // Arrange\n            DefaultModelBinderHelper helper = new DefaultModelBinderHelper();\n\n            // Act\n            object modelObj = helper.PublicCreateModel(null, null, typeof(IDictionary<string, Guid>));\n\n            // Assert\n            Assert.IsAssignableFrom<IDictionary<string, Guid>>(modelObj);\n        }\n\n        [Fact]\n        public void CreateInstanceCreatesModelInstanceForGenericIEnumerable()\n        {\n            // Arrange\n            DefaultModelBinderHelper helper = new DefaultModelBinderHelper();\n\n            // Act\n            object modelObj = helper.PublicCreateModel(null, null, typeof(IEnumerable<Guid>));\n\n            // Assert\n            Assert.IsAssignableFrom<ICollection<Guid>>(modelObj);\n        }\n\n        [Fact]\n        public void CreateInstanceCreatesModelInstanceForGenericIList()\n        {\n            // Arrange\n            DefaultModelBinderHelper helper = new DefaultModelBinderHelper();\n\n            // Act\n            object modelObj = helper.PublicCreateModel(null, null, typeof(IList<Guid>));\n\n            // Assert\n            Assert.IsAssignableFrom<IList<Guid>>(modelObj);\n        }\n\n        [Fact]\n        public void CreateInstanceCreatesModelInstanceForGenericIListWithoutParameterlessConstructor()\n        {\n            // Arrange\n            DefaultModelBinderHelper helper = new DefaultModelBinderHelper();\n\n            // Act\n            // No need for type parameter to have a parameterless constructor\n            object modelObject = helper.PublicCreateModel(null, null, typeof(IList<NoParameterlessCtor>));\n\n            // Assert\n            Assert.IsAssignableFrom<IList<NoParameterlessCtor>>(modelObject);\n        }\n\n        [Fact]\n        public void CreateInstanceThrowsWithoutParameterlessConstructor()\n        {\n            // Arrange\n            DefaultModelBinderHelper helper = new DefaultModelBinderHelper();\n\n            // Act & Assert, confirming type name and full stack are available in Exception\n            MissingMethodException exception = Assert.Throws<MissingMethodException>(\n                () => helper.PublicCreateModel(null, null, typeof(NoParameterlessCtor)),\n                \"No parameterless constructor defined for this object. Object type 'System.Web.Mvc.Test.DefaultModelBinderTest+NoParameterlessCtor'.\");\n            Assert.Contains(\"System.Activator.CreateInstance(\", exception.ToString());\n        }\n\n        [Fact]\n        public void CreateSubIndexNameReturnsPrefixPlusIndex()\n        {\n            // Arrange\n            DefaultModelBinderHelper helper = new DefaultModelBinderHelper();\n\n            // Act\n            string newName = helper.PublicCreateSubIndexName(\"somePrefix\", 2);\n\n            // Assert\n            Assert.Equal(\"somePrefix[2]\", newName);\n        }\n\n        [Fact]\n        public void CreateSubPropertyNameReturnsPrefixPlusPropertyName()\n        {\n            // Arrange\n            DefaultModelBinderHelper helper = new DefaultModelBinderHelper();\n\n            // Act\n            string newName = helper.PublicCreateSubPropertyName(\"somePrefix\", \"someProperty\");\n\n            // Assert\n            Assert.Equal(\"somePrefix.someProperty\", newName);\n        }\n\n        [Fact]\n        public void CreateSubPropertyNameReturnsPropertyNameIfPrefixIsEmpty()\n        {\n            // Arrange\n            DefaultModelBinderHelper helper = new DefaultModelBinderHelper();\n\n            // Act\n            string newName = helper.PublicCreateSubPropertyName(String.Empty, \"someProperty\");\n\n            // Assert\n            Assert.Equal(\"someProperty\", newName);\n        }\n\n        [Fact]\n        public void CreateSubPropertyNameReturnsPropertyNameIfPrefixIsNull()\n        {\n            // Arrange\n            DefaultModelBinderHelper helper = new DefaultModelBinderHelper();\n\n            // Act\n            string newName = helper.PublicCreateSubPropertyName(null, \"someProperty\");\n\n            // Assert\n            Assert.Equal(\"someProperty\", newName);\n        }\n\n        [Fact]\n        public void GetFilteredModelPropertiesFiltersNonUpdateableProperties()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(PropertyTestingModel)),\n                PropertyFilter = new BindAttribute() { Exclude = \"Blacklisted\" }.IsPropertyAllowed\n            };\n\n            DefaultModelBinderHelper helper = new DefaultModelBinderHelper();\n\n            // Act\n            PropertyDescriptorCollection properties = new PropertyDescriptorCollection(helper.PublicGetFilteredModelProperties(null, bindingContext).ToArray());\n\n            // Assert\n            Assert.NotNull(properties[\"StringReadWrite\"]);\n            Assert.Null(properties[\"StringReadOnly\"]);\n            Assert.NotNull(properties[\"IntReadWrite\"]);\n            Assert.Null(properties[\"IntReadOnly\"]);\n            Assert.NotNull(properties[\"ArrayReadWrite\"]);\n            Assert.Null(properties[\"ArrayReadOnly\"]);\n            Assert.NotNull(properties[\"AddressReadWrite\"]);\n            Assert.NotNull(properties[\"AddressReadOnly\"]);\n            Assert.NotNull(properties[\"Whitelisted\"]);\n            Assert.Null(properties[\"Blacklisted\"]);\n            Assert.Equal(6, properties.Count);\n        }\n\n        [Fact]\n        public void GetModelPropertiesReturnsUnfilteredPropertyList()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(PropertyTestingModel)),\n                PropertyFilter = new BindAttribute() { Exclude = \"Blacklisted\" }.IsPropertyAllowed\n            };\n\n            DefaultModelBinderHelper helper = new DefaultModelBinderHelper();\n\n            // Act\n            PropertyDescriptorCollection properties = helper.PublicGetModelProperties(null, bindingContext);\n\n            // Assert\n            Assert.NotNull(properties[\"StringReadWrite\"]);\n            Assert.NotNull(properties[\"StringReadOnly\"]);\n            Assert.NotNull(properties[\"IntReadWrite\"]);\n            Assert.NotNull(properties[\"IntReadOnly\"]);\n            Assert.NotNull(properties[\"ArrayReadWrite\"]);\n            Assert.NotNull(properties[\"ArrayReadOnly\"]);\n            Assert.NotNull(properties[\"AddressReadWrite\"]);\n            Assert.NotNull(properties[\"AddressReadOnly\"]);\n            Assert.NotNull(properties[\"Whitelisted\"]);\n            Assert.NotNull(properties[\"Blacklisted\"]);\n            Assert.Equal(10, properties.Count);\n        }\n\n        [Fact]\n        public void IsModelValidWithNullBindingContextThrows()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => DefaultModelBinderHelper.PublicIsModelValid(null),\n                \"bindingContext\");\n        }\n\n        [Fact]\n        public void IsModelValidReturnsModelStateIsValidWhenModelNameIsEmpty()\n        {\n            // Arrange\n            ModelBindingContext contextWithNoErrors = new ModelBindingContext { ModelName = \"\" };\n            ModelBindingContext contextWithErrors = new ModelBindingContext { ModelName = \"\" };\n            contextWithErrors.ModelState.AddModelError(\"foo\", \"bar\");\n\n            // Act & Assert\n            Assert.True(DefaultModelBinderHelper.PublicIsModelValid(contextWithNoErrors));\n            Assert.False(DefaultModelBinderHelper.PublicIsModelValid(contextWithErrors));\n        }\n\n        [Fact]\n        public void IsModelValidReturnsValidityOfSubModelStateWhenModelNameIsNotEmpty()\n        {\n            // Arrange\n            ModelBindingContext contextWithNoErrors = new ModelBindingContext { ModelName = \"foo\" };\n            ModelBindingContext contextWithErrors = new ModelBindingContext { ModelName = \"foo\" };\n            contextWithErrors.ModelState.AddModelError(\"foo.bar\", \"baz\");\n            ModelBindingContext contextWithUnrelatedErrors = new ModelBindingContext { ModelName = \"foo\" };\n            contextWithUnrelatedErrors.ModelState.AddModelError(\"biff\", \"baz\");\n\n            // Act & Assert\n            Assert.True(DefaultModelBinderHelper.PublicIsModelValid(contextWithNoErrors));\n            Assert.False(DefaultModelBinderHelper.PublicIsModelValid(contextWithErrors));\n            Assert.True(DefaultModelBinderHelper.PublicIsModelValid(contextWithUnrelatedErrors));\n        }\n\n        [Fact]\n        public void OnModelUpdatingReturnsTrue()\n        {\n            // By default, this method does nothing, so we just want to make sure it returns true\n\n            // Arrange\n            DefaultModelBinderHelper helper = new DefaultModelBinderHelper();\n\n            // Act\n            bool returned = helper.PublicOnModelUpdating(null, null);\n\n            // Arrange\n            Assert.True(returned);\n        }\n\n        // OnModelUpdated tests\n\n        [Fact]\n        public void OnModelUpdatedCalledWhenOnModelUpdatingReturnsTrue()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => new ModelWithoutBindAttribute(), typeof(ModelWithoutBindAttribute)),\n                ModelName = \"\",\n                ValueProvider = new SimpleValueProvider()\n            };\n            Mock<DefaultModelBinder> binder = new Mock<DefaultModelBinder> { CallBase = true };\n            binder.Protected().Setup<bool>(\"OnModelUpdating\",\n                                           ItExpr.IsAny<ControllerContext>(), ItExpr.IsAny<ModelBindingContext>())\n                .Returns(true);\n            binder.Protected().Setup(\"OnModelUpdated\",\n                                     ItExpr.IsAny<ControllerContext>(), ItExpr.IsAny<ModelBindingContext>())\n                .Verifiable();\n\n            // Act\n            binder.Object.BindModel(new ControllerContext(), bindingContext);\n\n            // Assert\n            binder.Verify();\n        }\n\n        [Fact]\n        public void OnModelUpdatedNotCalledWhenOnModelUpdatingReturnsFalse()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => new ModelWithoutBindAttribute(), typeof(ModelWithoutBindAttribute)),\n                ModelName = \"\",\n                ValueProvider = new SimpleValueProvider()\n            };\n            Mock<DefaultModelBinder> binder = new Mock<DefaultModelBinder> { CallBase = true };\n            binder.Protected().Setup<bool>(\"OnModelUpdating\",\n                                           ItExpr.IsAny<ControllerContext>(), ItExpr.IsAny<ModelBindingContext>())\n                .Returns(false);\n\n            // Act\n            binder.Object.BindModel(new ControllerContext(), bindingContext);\n\n            // Assert\n            binder.Verify();\n            binder.Protected().Verify(\"OnModelUpdated\", Times.Never(),\n                                      ItExpr.IsAny<ControllerContext>(), ItExpr.IsAny<ModelBindingContext>());\n        }\n\n        [Fact]\n        public void OnModelUpdatedDoesntAddNewMessagesWhenMessagesAlreadyExist()\n        {\n            // Arrange\n            var binder = new TestableDefaultModelBinder<SetPropertyModel>();\n            binder.Context.ModelState.AddModelError(BASE_MODEL_NAME + \".NonNullableStringWithAttribute\", \"Some pre-existing error\");\n\n            // Act\n            binder.OnModelUpdated();\n\n            // Assert\n            var modelState = binder.Context.ModelState[BASE_MODEL_NAME + \".NonNullableStringWithAttribute\"];\n            var error = Assert.Single(modelState.Errors);\n            Assert.Equal(\"Some pre-existing error\", error.ErrorMessage);\n        }\n\n        [Fact]\n        public void OnPropertyValidatingNotCalledOnPropertiesWithErrors()\n        {\n            // Arrange\n            ModelWithoutBindAttribute model = new ModelWithoutBindAttribute();\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),\n                ModelName = \"\",\n                ValueProvider = new SimpleValueProvider()\n                {\n                    { \"foo\", \"foo\" }\n                },\n            };\n            bindingContext.ModelState.AddModelError(\"foo\", \"Pre-existing error\");\n            Mock<DefaultModelBinder> binder = new Mock<DefaultModelBinder> { CallBase = true };\n\n            // Act\n            binder.Object.BindModel(new ControllerContext(), bindingContext);\n\n            // Assert\n            binder.Verify();\n            binder.Protected().Verify(\"OnPropertyValidating\", Times.Never(),\n                                      ItExpr.IsAny<ControllerContext>(), ItExpr.IsAny<ModelBindingContext>(),\n                                      ItExpr.IsAny<PropertyDescriptor>(), ItExpr.IsAny<object>());\n        }\n\n        public class ExtraValueModel\n        {\n            public int RequiredValue { get; set; }\n        }\n\n        [Fact]\n        public void ExtraValueRequiredMessageNotAddedForAlreadyInvalidProperty()\n        {\n            // Arrange\n            DefaultModelBinder binder = new DefaultModelBinder();\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(MyModel)),\n                ModelName = \"theModel\",\n                ValueProvider = new SimpleValueProvider()\n            };\n            bindingContext.ModelState.AddModelError(\"theModel.ReadWriteProperty\", \"Existing Error Message\");\n\n            // Act\n            binder.BindModel(new ControllerContext(), bindingContext);\n\n            // Assert\n            ModelState modelState = bindingContext.ModelState[\"theModel.ReadWriteProperty\"];\n            var error = Assert.Single(modelState.Errors);\n            Assert.Equal(\"Existing Error Message\", error.ErrorMessage);\n        }\n\n        [Fact]\n        public void OnPropertyValidatingReturnsTrueOnSuccess()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(MyModel)),\n                ModelName = \"theModel\"\n            };\n\n            PropertyDescriptor property = TypeDescriptor.GetProperties(typeof(MyModel))[\"ReadWriteProperty\"];\n            DefaultModelBinderHelper helper = new DefaultModelBinderHelper();\n            bindingContext.PropertyMetadata[\"ReadWriteProperty\"].Model = 42;\n\n            // Act\n            bool returned = helper.PublicOnPropertyValidating(new ControllerContext(), bindingContext, property, 42);\n\n            // Assert\n            Assert.True(returned);\n            Assert.Empty(bindingContext.ModelState);\n        }\n\n        [Fact]\n        public void UpdateCollectionCreatesDefaultEntriesForInvalidElements()\n        {\n            // Arrange\n            List<int> model = new List<int>() { 4, 5, 6, 7, 8 };\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider()\n                {\n                    { \"foo[0]\", null },\n                    { \"foo[1]\", null },\n                    { \"foo[2]\", null }\n                }\n            };\n\n            Mock<IModelBinder> mockInnerBinder = new Mock<IModelBinder>();\n            mockInnerBinder\n                .Setup(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ModelBindingContext bc)\n                    {\n                        int fooIdx = Int32.Parse(bc.ModelName.Substring(4, 1), CultureInfo.InvariantCulture);\n                        return (fooIdx == 1) ? (object)null : fooIdx;\n                    });\n\n            DefaultModelBinder binder = new DefaultModelBinder()\n            {\n                Binders = new ModelBinderDictionary()\n                {\n                    { typeof(int), mockInnerBinder.Object }\n                }\n            };\n\n            // Act\n            object updatedModel = binder.UpdateCollection(null, bindingContext, typeof(int));\n\n            // Assert\n            Assert.Equal(3, model.Count);\n            Assert.False(bindingContext.ModelState.IsValidField(\"foo[1]\"));\n            Assert.Equal(\"A value is required.\", bindingContext.ModelState[\"foo[1]\"].Errors[0].ErrorMessage);\n            Assert.Equal(0, model[0]);\n            Assert.Equal(0, model[1]);\n            Assert.Equal(2, model[2]);\n        }\n\n        [Fact]\n        public void UpdateCollectionReturnsModifiedCollectionOnSuccess_ExplicitIndex()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n\n            List<int> model = new List<int>() { 4, 5, 6, 7, 8 };\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),\n                ModelName = \"foo\",\n                PropertyFilter = _ => false,\n                ValueProvider = new SimpleValueProvider()\n                {\n                    { \"foo.index\", new string[] { \"alpha\", \"bravo\", \"charlie\" } }, // 'bravo' will be skipped\n                    { \"foo[alpha]\", \"10\" },\n                    { \"foo[charlie]\", \"30\" }\n                }\n            };\n\n            DefaultModelBinder binder = new DefaultModelBinder();\n\n            // Act\n            object updatedModel = binder.UpdateCollection(controllerContext, bindingContext, typeof(int));\n\n            // Assert\n            Assert.Same(model, updatedModel);\n            Assert.Equal(2, model.Count);\n            Assert.Equal(10, model[0]);\n            Assert.Equal(30, model[1]);\n        }\n\n        [Fact]\n        public void UpdateCollectionReturnsModifiedCollectionOnSuccess_ZeroBased()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n\n            List<int> model = new List<int>() { 4, 5, 6, 7, 8 };\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),\n                ModelName = \"foo\",\n                PropertyFilter = _ => false,\n                ValueProvider = new SimpleValueProvider()\n                {\n                    { \"foo[0]\", null },\n                    { \"foo[1]\", null },\n                    { \"foo[2]\", null }\n                }\n            };\n\n            Mock<IModelBinder> mockInnerBinder = new Mock<IModelBinder>();\n            mockInnerBinder\n                .Setup(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ModelBindingContext bc)\n                    {\n                        Assert.Equal(controllerContext, cc);\n                        Assert.Equal(typeof(int), bc.ModelType);\n                        Assert.Equal(bindingContext.ModelState, bc.ModelState);\n                        Assert.Equal(bindingContext.PropertyFilter, bc.PropertyFilter);\n                        Assert.Equal(bindingContext.ValueProvider, bc.ValueProvider);\n                        return Int32.Parse(bc.ModelName.Substring(4, 1), CultureInfo.InvariantCulture);\n                    });\n\n            DefaultModelBinder binder = new DefaultModelBinder()\n            {\n                Binders = new ModelBinderDictionary()\n                {\n                    { typeof(int), mockInnerBinder.Object }\n                }\n            };\n\n            // Act\n            object updatedModel = binder.UpdateCollection(controllerContext, bindingContext, typeof(int));\n\n            // Assert\n            Assert.Same(model, updatedModel);\n            Assert.Equal(3, model.Count);\n            Assert.Equal(0, model[0]);\n            Assert.Equal(1, model[1]);\n            Assert.Equal(2, model[2]);\n        }\n\n        [Fact]\n        public void UpdateCollectionReturnsNullIfZeroIndexNotFound()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ValueProvider = new SimpleValueProvider()\n            };\n            DefaultModelBinder binder = new DefaultModelBinder();\n\n            // Act\n            object updatedModel = binder.UpdateCollection(null, bindingContext, typeof(object));\n\n            // Assert\n            Assert.Null(updatedModel);\n        }\n\n        [Fact]\n        public void UpdateDictionaryCreatesDefaultEntriesForInvalidValues()\n        {\n            // Arrange\n            Dictionary<string, int> model = new Dictionary<string, int>\n            {\n                { \"one\", 1 },\n                { \"two\", 2 }\n            };\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider()\n                {\n                    { \"foo[0].key\", null }, { \"foo[0].value\", null },\n                    { \"foo[1].key\", null }, { \"foo[1].value\", null },\n                    { \"foo[2].key\", null }, { \"foo[2].value\", null }\n                }\n            };\n\n            Mock<IModelBinder> mockStringBinder = new Mock<IModelBinder>();\n            mockStringBinder\n                .Setup(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ModelBindingContext bc) { return (Int32.Parse(bc.ModelName.Substring(4, 1), CultureInfo.InvariantCulture) + 10) + \"Value\"; });\n\n            Mock<IModelBinder> mockIntBinder = new Mock<IModelBinder>();\n            mockIntBinder\n                .Setup(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ModelBindingContext bc)\n                    {\n                        int fooIdx = Int32.Parse(bc.ModelName.Substring(4, 1), CultureInfo.InvariantCulture);\n                        return (fooIdx == 1) ? (object)null : fooIdx;\n                    });\n\n            DefaultModelBinder binder = new DefaultModelBinder()\n            {\n                Binders = new ModelBinderDictionary()\n                {\n                    { typeof(string), mockStringBinder.Object },\n                    { typeof(int), mockIntBinder.Object }\n                }\n            };\n\n            // Act\n            object updatedModel = binder.UpdateDictionary(null, bindingContext, typeof(string), typeof(int));\n\n            // Assert\n            Assert.Equal(3, model.Count);\n            Assert.False(bindingContext.ModelState.IsValidField(\"foo[1].value\"));\n            Assert.Equal(\"A value is required.\", bindingContext.ModelState[\"foo[1].value\"].Errors[0].ErrorMessage);\n            Assert.Equal(0, model[\"10Value\"]);\n            Assert.Equal(0, model[\"11Value\"]);\n            Assert.Equal(2, model[\"12Value\"]);\n        }\n\n        [Fact]\n        public void UpdateDictionaryReturnsModifiedDictionaryOnSuccess_ExplicitIndex()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n\n            Dictionary<int, string> model = new Dictionary<int, string>\n            {\n                { 1, \"one\" },\n                { 2, \"two\" }\n            };\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),\n                ModelName = \"foo\",\n                PropertyFilter = _ => false,\n                ValueProvider = new SimpleValueProvider()\n                {\n                    { \"foo.index\", new string[] { \"alpha\", \"bravo\", \"charlie\" } }, // 'bravo' will be skipped\n                    { \"foo[alpha].key\", \"10\" }, { \"foo[alpha].value\", \"ten\" },\n                    { \"foo[charlie].key\", \"30\" }, { \"foo[charlie].value\", \"thirty\" }\n                }\n            };\n\n            DefaultModelBinder binder = new DefaultModelBinder();\n\n            // Act\n            object updatedModel = binder.UpdateDictionary(controllerContext, bindingContext, typeof(int), typeof(string));\n\n            // Assert\n            Assert.Same(model, updatedModel);\n            Assert.Equal(2, model.Count);\n            Assert.Equal(\"ten\", model[10]);\n            Assert.Equal(\"thirty\", model[30]);\n        }\n\n        [Fact]\n        public void UpdateDictionaryReturnsModifiedDictionaryOnSuccess_ZeroBased()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n\n            Dictionary<int, string> model = new Dictionary<int, string>\n            {\n                { 1, \"one\" },\n                { 2, \"two\" }\n            };\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),\n                ModelName = \"foo\",\n                PropertyFilter = _ => false,\n                ValueProvider = new SimpleValueProvider()\n                {\n                    { \"foo[0].key\", null }, { \"foo[0].value\", null },\n                    { \"foo[1].key\", null }, { \"foo[1].value\", null },\n                    { \"foo[2].key\", null }, { \"foo[2].value\", null }\n                }\n            };\n\n            Mock<IModelBinder> mockIntBinder = new Mock<IModelBinder>();\n            mockIntBinder\n                .Setup(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ModelBindingContext bc)\n                    {\n                        Assert.Equal(controllerContext, cc);\n                        Assert.Equal(typeof(int), bc.ModelType);\n                        Assert.Equal(bindingContext.ModelState, bc.ModelState);\n                        Assert.Equal(new ModelBindingContext().PropertyFilter, bc.PropertyFilter);\n                        Assert.Equal(bindingContext.ValueProvider, bc.ValueProvider);\n                        return Int32.Parse(bc.ModelName.Substring(4, 1), CultureInfo.InvariantCulture) + 10;\n                    });\n\n            Mock<IModelBinder> mockStringBinder = new Mock<IModelBinder>();\n            mockStringBinder\n                .Setup(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ModelBindingContext bc)\n                    {\n                        Assert.Equal(controllerContext, cc);\n                        Assert.Equal(typeof(string), bc.ModelType);\n                        Assert.Equal(bindingContext.ModelState, bc.ModelState);\n                        Assert.Equal(bindingContext.PropertyFilter, bc.PropertyFilter);\n                        Assert.Equal(bindingContext.ValueProvider, bc.ValueProvider);\n                        return (Int32.Parse(bc.ModelName.Substring(4, 1), CultureInfo.InvariantCulture) + 10) + \"Value\";\n                    });\n\n            DefaultModelBinder binder = new DefaultModelBinder()\n            {\n                Binders = new ModelBinderDictionary()\n                {\n                    { typeof(int), mockIntBinder.Object },\n                    { typeof(string), mockStringBinder.Object }\n                }\n            };\n\n            // Act\n            object updatedModel = binder.UpdateDictionary(controllerContext, bindingContext, typeof(int), typeof(string));\n\n            // Assert\n            Assert.Same(model, updatedModel);\n            Assert.Equal(3, model.Count);\n            Assert.Equal(\"10Value\", model[10]);\n            Assert.Equal(\"11Value\", model[11]);\n            Assert.Equal(\"12Value\", model[12]);\n        }\n\n        [Fact]\n        public void UpdateDictionaryReturnsEmptyDictionaryIfNoValidElementsFound()\n        {\n            // Arrange\n            Mock<ControllerContext> mockController = new Mock<ControllerContext>();\n\n            mockController\n                .Setup(c => c.RouteData)\n                .Returns(\n                    delegate()\n                    {\n                        RouteData routeData = new RouteData();\n                        routeData.Values[\"controller\"] = \"controller\";\n                        return routeData;\n                    }\n            );\n\n            ControllerContext controllerContext = mockController.Object;\n\n            Dictionary<int, string> model = new Dictionary<int, string>();\n\n            RouteDataValueProviderFactory routeDataFactory = new RouteDataValueProviderFactory();\n\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),\n                ValueProvider = routeDataFactory.GetValueProvider(controllerContext)\n            };\n\n            DefaultModelBinder binder = new DefaultModelBinder();\n\n            // Act\n            Dictionary<int, string> updatedModel = binder.UpdateDictionary(controllerContext, bindingContext, typeof(int), typeof(string)) as Dictionary<int, string>;\n\n            // Assert\n            Assert.NotNull(updatedModel);\n            Assert.Empty(updatedModel);\n        }\n\n        [Fact]\n        public void UpdateDictionarySkipsInvalidKeys()\n        {\n            // Arrange\n            Dictionary<int, string> model = new Dictionary<int, string>\n            {\n                { 1, \"one\" },\n                { 2, \"two\" }\n            };\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),\n                ModelName = \"foo\",\n                ValueProvider = new SimpleValueProvider()\n                {\n                    { \"foo[0].key\", null }, { \"foo[0].value\", null },\n                    { \"foo[1].key\", null }, { \"foo[1].value\", null },\n                    { \"foo[2].key\", null }, { \"foo[2].value\", null }\n                }\n            };\n\n            Mock<IModelBinder> mockIntBinder = new Mock<IModelBinder>();\n            mockIntBinder\n                .Setup(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ModelBindingContext bc)\n                    {\n                        int fooIdx = Int32.Parse(bc.ModelName.Substring(4, 1), CultureInfo.InvariantCulture);\n                        return (fooIdx == 1) ? (object)null : fooIdx;\n                    });\n\n            Mock<IModelBinder> mockStringBinder = new Mock<IModelBinder>();\n            mockStringBinder\n                .Setup(b => b.BindModel(It.IsAny<ControllerContext>(), It.IsAny<ModelBindingContext>()))\n                .Returns(\n                    delegate(ControllerContext cc, ModelBindingContext bc) { return (Int32.Parse(bc.ModelName.Substring(4, 1), CultureInfo.InvariantCulture) + 10) + \"Value\"; });\n\n            DefaultModelBinder binder = new DefaultModelBinder()\n            {\n                Binders = new ModelBinderDictionary()\n                {\n                    { typeof(int), mockIntBinder.Object },\n                    { typeof(string), mockStringBinder.Object }\n                }\n            };\n\n            // Act\n            object updatedModel = binder.UpdateDictionary(null, bindingContext, typeof(int), typeof(string));\n\n            // Assert\n            Assert.Equal(2, model.Count);\n            Assert.False(bindingContext.ModelState.IsValidField(\"foo[1].key\"));\n            Assert.Equal(\"A value is required.\", bindingContext.ModelState[\"foo[1].key\"].Errors[0].ErrorMessage);\n            Assert.Equal(\"10Value\", model[0]);\n            Assert.Equal(\"12Value\", model[2]);\n        }\n\n        [ModelBinder(typeof(DefaultModelBinder))]\n        private class MyModel\n        {\n            public int ReadOnlyProperty\n            {\n                get { return 4; }\n            }\n\n            public int ReadWriteProperty { get; set; }\n            public int ReadWriteProperty2 { get; set; }\n        }\n\n        private class MyClassWithoutConverter\n        {\n        }\n\n        [Bind(Exclude = \"Alpha,Echo\")]\n        private class MyOtherModel\n        {\n            public string Alpha { get; set; }\n            public string Bravo { get; set; }\n            public string Charlie { get; set; }\n            public string Delta { get; set; }\n            public string Echo { get; set; }\n            public string Foxtrot { get; set; }\n        }\n\n        public class Customer\n        {\n            private Address _address = new Address();\n\n            public Address Address\n            {\n                get { return _address; }\n            }\n        }\n\n        public class Address\n        {\n            public string Street { get; set; }\n            public string Zip { get; set; }\n        }\n\n        public class IntegerContainer\n        {\n            public int Integer { get; set; }\n            public int? NullableInteger { get; set; }\n        }\n\n        [TypeConverter(typeof(CultureAwareConverter))]\n        public class StringContainer\n        {\n            public StringContainer(string value)\n            {\n                Value = value;\n            }\n\n            public string Value { get; private set; }\n        }\n\n        private class CultureAwareConverter : TypeConverter\n        {\n            public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)\n            {\n                return (sourceType == typeof(string));\n            }\n\n            public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)\n            {\n                return (destinationType == typeof(string));\n            }\n\n            public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)\n            {\n                string stringValue = value as string;\n                if (stringValue == null || stringValue.Length < 3)\n                {\n                    throw new Exception(\"Value must have at least 3 characters.\");\n                }\n                return new StringContainer(AppendCultureName(stringValue, culture));\n            }\n\n            public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)\n            {\n                StringContainer container = value as StringContainer;\n                if (container.Value == null || container.Value.Length < 3)\n                {\n                    throw new Exception(\"Value must have at least 3 characters.\");\n                }\n\n                return AppendCultureName(container.Value, culture);\n            }\n\n            private static string AppendCultureName(string value, CultureInfo culture)\n            {\n                string cultureName = (!String.IsNullOrEmpty(culture.Name)) ? culture.Name : culture.ThreeLetterWindowsLanguageName;\n                return value + \" (\" + cultureName + \")\";\n            }\n        }\n\n        [ModelBinder(typeof(MyStringModelBinder))]\n        private class MyStringModel\n        {\n            public string Value { get; set; }\n        }\n\n        private class MyStringModelBinder : IModelBinder\n        {\n            public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)\n            {\n                MyStringModel castModel = bindingContext.Model as MyStringModel;\n                if (castModel != null)\n                {\n                    castModel.Value += \"_Update\";\n                }\n                else\n                {\n                    castModel = new MyStringModel() { Value = bindingContext.ModelName + \"_Create\" };\n                }\n                return castModel;\n            }\n        }\n\n        private class CustomUnvalidatedValueProvider : IUnvalidatedValueProvider\n        {\n            public ValueProviderResult GetValue(string key, bool skipValidation)\n            {\n                string newValue = key + ((skipValidation) ? \"Unvalidated\" : \"Validated\");\n                return new ValueProviderResult(newValue, newValue, null);\n            }\n\n            public bool ContainsPrefix(string prefix)\n            {\n                return true;\n            }\n\n            public ValueProviderResult GetValue(string key)\n            {\n                return GetValue(key, skipValidation: false);\n            }\n        }\n\n        private class SimpleController : Controller\n        {\n        }\n\n        public class DefaultModelBinderHelper : DefaultModelBinder\n        {\n            public virtual void PublicBindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor property)\n            {\n                base.BindProperty(controllerContext, bindingContext, property);\n            }\n\n            protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor property)\n            {\n                PublicBindProperty(controllerContext, bindingContext, property);\n            }\n\n            public virtual object PublicCreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)\n            {\n                return base.CreateModel(controllerContext, bindingContext, modelType);\n            }\n\n            protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)\n            {\n                return PublicCreateModel(controllerContext, bindingContext, modelType);\n            }\n\n            public virtual IEnumerable<PropertyDescriptor> PublicGetFilteredModelProperties(ControllerContext controllerContext, ModelBindingContext bindingContext)\n            {\n                return base.GetFilteredModelProperties(controllerContext, bindingContext);\n            }\n\n            public virtual PropertyDescriptorCollection PublicGetModelProperties(ControllerContext controllerContext, ModelBindingContext bindingContext)\n            {\n                return base.GetModelProperties(controllerContext, bindingContext);\n            }\n\n            protected override PropertyDescriptorCollection GetModelProperties(ControllerContext controllerContext, ModelBindingContext bindingContext)\n            {\n                return PublicGetModelProperties(controllerContext, bindingContext);\n            }\n\n            public string PublicCreateSubIndexName(string prefix, int indexName)\n            {\n                return CreateSubIndexName(prefix, indexName);\n            }\n\n            public string PublicCreateSubPropertyName(string prefix, string propertyName)\n            {\n                return CreateSubPropertyName(prefix, propertyName);\n            }\n\n            public static bool PublicIsModelValid(ModelBindingContext bindingContext)\n            {\n                return IsModelValid(bindingContext);\n            }\n\n            public virtual bool PublicOnModelUpdating(ControllerContext controllerContext, ModelBindingContext bindingContext)\n            {\n                return base.OnModelUpdating(controllerContext, bindingContext);\n            }\n\n            protected override bool OnModelUpdating(ControllerContext controllerContext, ModelBindingContext bindingContext)\n            {\n                return PublicOnModelUpdating(controllerContext, bindingContext);\n            }\n\n            public virtual void PublicOnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)\n            {\n                base.OnModelUpdated(controllerContext, bindingContext);\n            }\n\n            protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)\n            {\n                PublicOnModelUpdated(controllerContext, bindingContext);\n            }\n\n            public virtual bool PublicOnPropertyValidating(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor property, object value)\n            {\n                return base.OnPropertyValidating(controllerContext, bindingContext, property, value);\n            }\n\n            protected override bool OnPropertyValidating(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor property, object value)\n            {\n                return PublicOnPropertyValidating(controllerContext, bindingContext, property, value);\n            }\n\n            public virtual void PublicOnPropertyValidated(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor property, object value)\n            {\n                base.OnPropertyValidated(controllerContext, bindingContext, property, value);\n            }\n\n            protected override void OnPropertyValidated(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor property, object value)\n            {\n                PublicOnPropertyValidated(controllerContext, bindingContext, property, value);\n            }\n\n            public virtual void PublicSetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor property, object value)\n            {\n                base.SetProperty(controllerContext, bindingContext, property, value);\n            }\n\n            protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor property, object value)\n            {\n                PublicSetProperty(controllerContext, bindingContext, property, value);\n            }\n        }\n\n        private class MyModel2\n        {\n            private int _intReadWriteNonNegative;\n\n            public int IntReadOnly\n            {\n                get { return 4; }\n            }\n\n            public int IntReadWrite { get; set; }\n\n            public int IntReadWriteNonNegative\n            {\n                get { return _intReadWriteNonNegative; }\n                set\n                {\n                    if (value < 0)\n                    {\n                        throw new ArgumentOutOfRangeException(\"value\", \"Value must be non-negative.\");\n                    }\n                    _intReadWriteNonNegative = value;\n                }\n            }\n\n            public int? NullableIntReadWrite { get; set; }\n        }\n\n        [Bind(Exclude = \"Foo\")]\n        private class ModelWithBindAttribute : ModelWithoutBindAttribute\n        {\n        }\n\n        private class ModelWithoutBindAttribute\n        {\n            public string Foo { get; set; }\n            public string Bar { get; set; }\n            public string Baz { get; set; }\n        }\n\n        private class PropertyTestingModel\n        {\n            public string StringReadWrite { get; set; }\n            public string StringReadOnly { get; private set; }\n            public int IntReadWrite { get; set; }\n            public int IntReadOnly { get; private set; }\n            public object[] ArrayReadWrite { get; set; }\n            public object[] ArrayReadOnly { get; private set; }\n            public Address AddressReadWrite { get; set; }\n            public Address AddressReadOnly { get; private set; }\n            public string Whitelisted { get; set; }\n            public string Blacklisted { get; set; }\n        }\n\n        // --------------------------------------------------------------------------------\n        //  DataAnnotations tests\n\n        public const string BASE_MODEL_NAME = \"BaseModelName\";\n\n        // GetModelProperties tests\n\n        [MetadataType(typeof(Metadata))]\n        class GetModelPropertiesModel\n        {\n            [Required]\n            public int LocalAttributes { get; set; }\n\n            public int MetadataAttributes { get; set; }\n\n            [Required]\n            public int MixedAttributes { get; set; }\n\n            class Metadata\n            {\n                [Range(10, 100)]\n                public int MetadataAttributes { get; set; }\n\n                [Range(10, 100)]\n                public int MixedAttributes { get; set; }\n            }\n        }\n\n        [Fact]\n        public void GetModelPropertiesWithLocalAttributes()\n        {\n            // Arrange\n            TestableDefaultModelBinder<GetModelPropertiesModel> modelBinder = new TestableDefaultModelBinder<GetModelPropertiesModel>();\n\n            // Act\n            PropertyDescriptor property = modelBinder.GetModelProperties()\n                .Cast<PropertyDescriptor>()\n                .Where(pd => pd.Name == \"LocalAttributes\")\n                .Single();\n\n            // Assert\n            Assert.Contains(property.Attributes.Cast<Attribute>(), a => a is RequiredAttribute);\n        }\n\n        [Fact]\n        public void GetModelPropertiesWithMetadataAttributes()\n        {\n            // Arrange\n            TestableDefaultModelBinder<GetModelPropertiesModel> modelBinder = new TestableDefaultModelBinder<GetModelPropertiesModel>();\n\n            // Act\n            PropertyDescriptor property = modelBinder.GetModelProperties()\n                .Cast<PropertyDescriptor>()\n                .Where(pd => pd.Name == \"MetadataAttributes\")\n                .Single();\n\n            // Assert\n            Assert.Contains(property.Attributes.Cast<Attribute>(), a => a is RangeAttribute);\n        }\n\n        [Fact]\n        public void GetModelPropertiesWithMixedAttributes()\n        {\n            // Arrange\n            TestableDefaultModelBinder<GetModelPropertiesModel> modelBinder = new TestableDefaultModelBinder<GetModelPropertiesModel>();\n\n            // Act\n            PropertyDescriptor property = modelBinder.GetModelProperties()\n                .Cast<PropertyDescriptor>()\n                .Where(pd => pd.Name == \"MixedAttributes\")\n                .Single();\n\n            // Assert\n            Assert.Contains(property.Attributes.Cast<Attribute>(), a => a is RequiredAttribute);\n            Assert.Contains(property.Attributes.Cast<Attribute>(), a => a is RangeAttribute);\n        }\n\n        // GetPropertyValue tests\n\n        class GetPropertyValueModel\n        {\n            public string NoAttribute { get; set; }\n\n            [DisplayFormat(ConvertEmptyStringToNull = false)]\n            public string AttributeWithoutConversion { get; set; }\n\n            [DisplayFormat(ConvertEmptyStringToNull = true)]\n            public string AttributeWithConversion { get; set; }\n        }\n\n        [Fact]\n        public void GetPropertyValueWithNoAttributeConvertsEmptyStringToNull()\n        {\n            // Arrange\n            TestableDefaultModelBinder<GetPropertyValueModel> binder = new TestableDefaultModelBinder<GetPropertyValueModel>();\n            binder.Context.ModelMetadata = binder.Context.PropertyMetadata[\"NoAttribute\"];\n\n            // Act\n            object result = binder.GetPropertyValue(\"NoAttribute\", String.Empty);\n\n            // Assert\n            Assert.Null(result);\n        }\n\n        [Fact]\n        public void GetPropertyValueWithFalseAttributeDoesNotConvertEmptyStringToNull()\n        {\n            // Arrange\n            TestableDefaultModelBinder<GetPropertyValueModel> binder = new TestableDefaultModelBinder<GetPropertyValueModel>();\n            binder.Context.ModelMetadata = binder.Context.PropertyMetadata[\"AttributeWithoutConversion\"];\n\n            // Act\n            object result = binder.GetPropertyValue(\"AttributeWithoutConversion\", String.Empty);\n\n            // Assert\n            Assert.Equal(String.Empty, result);\n        }\n\n        [Fact]\n        public void GetPropertyValueWithTrueAttributeConvertsEmptyStringToNull()\n        {\n            // Arrange\n            TestableDefaultModelBinder<GetPropertyValueModel> binder = new TestableDefaultModelBinder<GetPropertyValueModel>();\n            binder.Context.ModelMetadata = binder.Context.PropertyMetadata[\"AttributeWithConversion\"];\n\n            // Act\n            object result = binder.GetPropertyValue(\"AttributeWithConversion\", String.Empty);\n\n            // Assert\n            Assert.Null(result);\n        }\n\n        // OnModelUpdated tests\n\n        [Fact]\n        public void OnModelUpdatedPassesNullContainerToValidate()\n        {\n            Mock<ModelValidatorProvider> provider = null;\n\n            try\n            {\n                // Arrange\n                ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(object));\n                ControllerContext context = new ControllerContext();\n                Mock<ModelValidator> validator = new Mock<ModelValidator>(metadata, context);\n                provider = new Mock<ModelValidatorProvider>();\n                provider.Setup(p => p.GetValidators(It.IsAny<ModelMetadata>(), It.IsAny<ControllerContext>()))\n                    .Returns(new ModelValidator[] { validator.Object });\n                ModelValidatorProviders.Providers.Add(provider.Object);\n                object model = new object();\n                TestableDefaultModelBinder<object> modelBinder = new TestableDefaultModelBinder<object>(model);\n\n                // Act\n                modelBinder.OnModelUpdated();\n\n                // Assert\n                validator.Verify(v => v.Validate(null));\n            }\n            finally\n            {\n                if (provider != null)\n                {\n                    ModelValidatorProviders.Providers.Remove(provider.Object);\n                }\n            }\n        }\n\n        public class MinMaxValidationAttribute : ValidationAttribute\n        {\n            public MinMaxValidationAttribute()\n                : base(\"Minimum must be less than or equal to Maximum\")\n            {\n            }\n\n            public override bool IsValid(object value)\n            {\n                OnModelUpdatedModelMultipleParameters model = (OnModelUpdatedModelMultipleParameters)value;\n                return model.Minimum <= model.Maximum;\n            }\n        }\n\n        [MinMaxValidation]\n        public class OnModelUpdatedModelMultipleParameters\n        {\n            public int Minimum { get; set; }\n            public int Maximum { get; set; }\n        }\n\n        [Fact]\n        public void OnModelUpdatedWithValidationAttributeMultipleParameters()\n        {\n            // Arrange\n            OnModelUpdatedModelMultipleParameters model = new OnModelUpdatedModelMultipleParameters { Minimum = 250, Maximum = 100 };\n            TestableDefaultModelBinder<OnModelUpdatedModelMultipleParameters> modelBinder = new TestableDefaultModelBinder<OnModelUpdatedModelMultipleParameters>(model);\n\n            // Act\n            modelBinder.OnModelUpdated();\n\n            // Assert\n            Assert.Single(modelBinder.ModelState);\n            ModelState stateModel = modelBinder.ModelState[BASE_MODEL_NAME];\n            Assert.NotNull(stateModel);\n            ModelError error = Assert.Single(stateModel.Errors);\n            Assert.Equal(\"Minimum must be less than or equal to Maximum\", error.ErrorMessage);\n        }\n\n        [Fact]\n        public void OnModelUpdatedWithInvalidPropertyValidationWillNotRunEntityLevelValidation()\n        {\n            // Arrange\n            OnModelUpdatedModelMultipleParameters model = new OnModelUpdatedModelMultipleParameters { Minimum = 250, Maximum = 100 };\n            TestableDefaultModelBinder<OnModelUpdatedModelMultipleParameters> modelBinder = new TestableDefaultModelBinder<OnModelUpdatedModelMultipleParameters>(model);\n            modelBinder.ModelState.AddModelError(BASE_MODEL_NAME + \".Minimum\", \"The minimum value was invalid.\");\n\n            // Act\n            modelBinder.OnModelUpdated();\n\n            // Assert\n            Assert.Null(modelBinder.ModelState[BASE_MODEL_NAME]);\n        }\n\n        public class AlwaysInvalidAttribute : ValidationAttribute\n        {\n            public AlwaysInvalidAttribute()\n            {\n            }\n\n            public AlwaysInvalidAttribute(string message)\n                : base(message)\n            {\n            }\n\n            public override bool IsValid(object value)\n            {\n                return false;\n            }\n        }\n\n        [AlwaysInvalid(\"The object just isn't right\")]\n        public class OnModelUpdatedModelNoParameters\n        {\n        }\n\n        [Fact]\n        public void OnModelUpdatedWithValidationAttributeNoParameters()\n        {\n            // Arrange\n            TestableDefaultModelBinder<OnModelUpdatedModelNoParameters> modelBinder = new TestableDefaultModelBinder<OnModelUpdatedModelNoParameters>();\n\n            // Act\n            modelBinder.OnModelUpdated();\n\n            // Assert\n            Assert.Single(modelBinder.ModelState);\n            ModelState stateModel = modelBinder.ModelState[BASE_MODEL_NAME];\n            Assert.NotNull(stateModel);\n            ModelError error = Assert.Single(stateModel.Errors);\n            Assert.Equal(\"The object just isn't right\", error.ErrorMessage);\n        }\n\n        [AlwaysInvalid]\n        public class OnModelUpdatedModelNoValidationResult\n        {\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void OnModelUpdatedWithValidationAttributeNoValidationMessage()\n        {\n            // Arrange\n            TestableDefaultModelBinder<OnModelUpdatedModelNoValidationResult> modelBinder = new TestableDefaultModelBinder<OnModelUpdatedModelNoValidationResult>();\n\n            // Act\n            modelBinder.OnModelUpdated();\n\n            // Assert\n            Assert.Single(modelBinder.ModelState);\n            ModelState stateModel = modelBinder.ModelState[BASE_MODEL_NAME];\n            Assert.NotNull(stateModel);\n            ModelError error = Assert.Single(stateModel.Errors);\n            Assert.Equal(\"The field OnModelUpdatedModelNoValidationResult is invalid.\", error.ErrorMessage);\n        }\n\n        [Fact]\n        public void OnModelUpdatedDoesNotPlaceErrorMessagesInModelStateWhenSubPropertiesHaveErrors()\n        {\n            // Arrange\n            TestableDefaultModelBinder<OnModelUpdatedModelNoValidationResult> modelBinder = new TestableDefaultModelBinder<OnModelUpdatedModelNoValidationResult>();\n            modelBinder.ModelState.AddModelError(\"Foo.Bar\", \"Foo.Bar is invalid\");\n            modelBinder.Context.ModelName = \"Foo\";\n\n            // Act\n            modelBinder.OnModelUpdated();\n\n            // Assert\n            Assert.Null(modelBinder.ModelState[\"Foo\"]);\n        }\n\n        // OnPropertyValidating tests\n\n        class OnPropertyValidatingModel\n        {\n            public string NotValidated { get; set; }\n\n            [Range(10, 65)]\n            public int RangedInteger { get; set; }\n\n            [Required(ErrorMessage = \"Custom Required Message\")]\n            public int RequiredInteger { get; set; }\n        }\n\n        [Fact]\n        public void OnPropertyValidatingWithoutValidationAttribute()\n        {\n            // Arrange\n            TestableDefaultModelBinder<OnPropertyValidatingModel> modelBinder = new TestableDefaultModelBinder<OnPropertyValidatingModel>();\n\n            // Act\n            modelBinder.OnPropertyValidating(\"NotValidated\", 42);\n\n            // Assert\n            Assert.Empty(modelBinder.ModelState);\n        }\n\n        [Fact]\n        public void OnPropertyValidatingWithValidationAttributePassing()\n        {\n            // Arrange\n            TestableDefaultModelBinder<OnPropertyValidatingModel> modelBinder = new TestableDefaultModelBinder<OnPropertyValidatingModel>();\n            modelBinder.Context.PropertyMetadata[\"RangedInteger\"].Model = 42;\n\n            // Act\n            bool result = modelBinder.OnPropertyValidating(\"RangedInteger\", 42);\n\n            // Assert\n            Assert.True(result);\n            Assert.Empty(modelBinder.ModelState);\n        }\n\n        // SetProperty tests\n\n        [Fact]\n        public void SetPropertyWithRequiredOnValueTypeOnlyResultsInSingleMessage()\n        { // DDB #225150\n            // Arrange\n            TestableDefaultModelBinder<OnPropertyValidatingModel> modelBinder = new TestableDefaultModelBinder<OnPropertyValidatingModel>();\n            modelBinder.Context.ModelMetadata.Model = new OnPropertyValidatingModel();\n\n            // Act\n            modelBinder.SetProperty(\"RequiredInteger\", null);\n\n            // Assert\n            ModelState modelState = modelBinder.ModelState[BASE_MODEL_NAME + \".RequiredInteger\"];\n            ModelError modelStateError = modelState.Errors.Single();\n            Assert.Equal(\"Custom Required Message\", modelStateError.ErrorMessage);\n        }\n\n        [Fact]\n        public void SetPropertyAddsDefaultMessageForNonBindableNonNullableValueTypes()\n        {\n            DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;\n\n            try\n            {\n                // Arrange\n                TestableDefaultModelBinder<List<String>> modelBinder = new TestableDefaultModelBinder<List<String>>();\n                modelBinder.Context.ModelMetadata.Model = null;\n\n                // Act\n                modelBinder.SetProperty(\"Count\", null);\n\n                // Assert\n                ModelState modelState = modelBinder.ModelState[BASE_MODEL_NAME + \".Count\"];\n                ModelError modelStateError = modelState.Errors.Single();\n                Assert.Equal(\"A value is required.\", modelStateError.ErrorMessage);\n            }\n            finally\n            {\n                DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = true;\n            }\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void SetPropertyCreatesValueRequiredErrorIfNecessary()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => new MyModel(), typeof(MyModel)),\n                ModelName = \"theModel\",\n            };\n\n            PropertyDescriptor property = TypeDescriptor.GetProperties(typeof(MyModel))[\"ReadWriteProperty\"];\n            DefaultModelBinderHelper helper = new DefaultModelBinderHelper();\n\n            // Act\n            helper.PublicSetProperty(new ControllerContext(), bindingContext, property, null);\n\n            // Assert\n            Assert.Equal(\"The ReadWriteProperty field is required.\", bindingContext.ModelState[\"theModel.ReadWriteProperty\"].Errors[0].ErrorMessage);\n        }\n\n        [Fact]\n        public void SetPropertyWithThrowingSetter()\n        {\n            // Arrange\n            TestableDefaultModelBinder<SetPropertyModel> binder = new TestableDefaultModelBinder<SetPropertyModel>();\n\n            // Act\n            binder.SetProperty(\"NonNullableString\", null);\n\n            // Assert\n            ModelState modelState = binder.Context.ModelState[BASE_MODEL_NAME + \".NonNullableString\"];\n            ModelError error = Assert.Single(modelState.Errors);\n            Assert.IsType<ArgumentNullException>(error.Exception);\n        }\n\n        [Fact]\n        public void SetPropertyWithNullValueAndThrowingSetterWithRequiredAttribute()\n        { // DDB #227809\n            // Arrange\n            TestableDefaultModelBinder<SetPropertyModel> binder = new TestableDefaultModelBinder<SetPropertyModel>();\n\n            // Act\n            binder.SetProperty(\"NonNullableStringWithAttribute\", null);\n\n            // Assert\n            ModelState modelState = binder.Context.ModelState[BASE_MODEL_NAME + \".NonNullableStringWithAttribute\"];\n            var error = Assert.Single(modelState.Errors);\n            Assert.Equal(\"My custom required message\", error.ErrorMessage);\n        }\n\n        [Fact]\n        public void SetPropertyDoesNothingIfPropertyIsReadOnly()\n        {\n            // Arrange\n            MyModel model = new MyModel();\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),\n                ModelName = \"theModel\"\n            };\n\n            PropertyDescriptor property = TypeDescriptor.GetProperties(model)[\"ReadOnlyProperty\"];\n            DefaultModelBinderHelper helper = new DefaultModelBinderHelper();\n\n            // Act\n            helper.PublicSetProperty(new ControllerContext(), bindingContext, property, 42);\n\n            // Assert\n            Assert.Empty(bindingContext.ModelState);\n        }\n\n        [Fact]\n        public void SetPropertySuccess()\n        {\n            // Arrange\n            TestableDefaultModelBinder<SetPropertyModel> binder = new TestableDefaultModelBinder<SetPropertyModel>();\n\n            // Act\n            binder.SetProperty(\"NullableString\", \"The new value\");\n\n            // Assert\n            Assert.Equal(\"The new value\", ((SetPropertyModel)binder.Context.Model).NullableString);\n            Assert.Empty(binder.Context.ModelState);\n        }\n\n        class SetPropertyModel\n        {\n            public string NullableString { get; set; }\n\n            public string NonNullableString\n            {\n                get { return null; }\n                set\n                {\n                    if (value == null)\n                    {\n                        throw new ArgumentNullException(\"value\");\n                    }\n                }\n            }\n\n            [Required(ErrorMessage = \"My custom required message\")]\n            public string NonNullableStringWithAttribute\n            {\n                get { return null; }\n                set\n                {\n                    if (value == null)\n                    {\n                        throw new ArgumentNullException(\"value\");\n                    }\n                }\n            }\n        }\n\n        // Helper methods\n\n        static PropertyDescriptor GetProperty<T>(string propertyName)\n        {\n            return TypeDescriptor.GetProperties(typeof(T))\n                .Cast<PropertyDescriptor>()\n                .Where(p => p.Name == propertyName)\n                .Single();\n        }\n\n        static ICustomTypeDescriptor GetType<T>()\n        {\n            return TypeDescriptor.GetProvider(typeof(T)).GetTypeDescriptor(typeof(T));\n        }\n\n        // Helper classes\n\n        class TestableDefaultModelBinder<TModel> : DefaultModelBinder\n            where TModel : new()\n        {\n            public TestableDefaultModelBinder()\n                : this(new TModel())\n            {\n            }\n\n            public TestableDefaultModelBinder(TModel model)\n            {\n                ModelState = new ModelStateDictionary();\n\n                Context = new ModelBindingContext();\n                Context.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, typeof(TModel));\n                Context.ModelName = BASE_MODEL_NAME;\n                Context.ModelState = ModelState;\n            }\n\n            public ModelBindingContext Context { get; private set; }\n\n            public ModelStateDictionary ModelState { get; set; }\n\n            public void BindProperty(string propertyName)\n            {\n                base.BindProperty(new ControllerContext(), Context, GetProperty<TModel>(propertyName));\n            }\n\n            public PropertyDescriptorCollection GetModelProperties()\n            {\n                return base.GetModelProperties(new ControllerContext(), Context);\n            }\n\n            public object GetPropertyValue(string propertyName, object existingValue)\n            {\n                Mock<IModelBinder> mockModelBinder = new Mock<IModelBinder>();\n                mockModelBinder.Setup(b => b.BindModel(It.IsAny<ControllerContext>(), Context)).Returns(existingValue);\n                return base.GetPropertyValue(new ControllerContext(), Context, GetProperty<TModel>(propertyName), mockModelBinder.Object);\n            }\n\n            public bool OnPropertyValidating(string propertyName, object value)\n            {\n                return base.OnPropertyValidating(new ControllerContext(), Context, GetProperty<TModel>(propertyName), value);\n            }\n\n            public void OnPropertyValidated(string propertyName, object value)\n            {\n                base.OnPropertyValidated(new ControllerContext(), Context, GetProperty<TModel>(propertyName), value);\n            }\n\n            public void OnModelUpdated()\n            {\n                base.OnModelUpdated(new ControllerContext(), Context);\n            }\n\n            public void SetProperty(string propertyName, object value)\n            {\n                base.SetProperty(new ControllerContext(), Context, GetProperty<TModel>(propertyName), value);\n            }\n        }\n\n        private class CountryState\n        {\n            public string Name { get; set; }\n\n            public IEnumerable<string> States { get; set; }\n        }\n\n        private class NoParameterlessCtor\n        {\n            private NoParameterlessCtor()\n            {\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/DefaultViewLocationCacheTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class DefaultViewLocationCacheTest\n    {\n        [Fact]\n        public void TimeSpanProperty()\n        {\n            // Arrange\n            TimeSpan timeSpan = new TimeSpan(0, 20, 0);\n            DefaultViewLocationCache viewCache = new DefaultViewLocationCache(timeSpan);\n\n            // Assert\n            Assert.Equal(timeSpan.Ticks, viewCache.TimeSpan.Ticks);\n        }\n\n        [Fact]\n        public void ConstructorAssignsDefaultTimeSpan()\n        {\n            // Arrange\n            DefaultViewLocationCache viewLocationCache = new DefaultViewLocationCache();\n            TimeSpan timeSpan = new TimeSpan(0, 15, 0);\n\n            // Assert\n            Assert.Equal(timeSpan.Ticks, viewLocationCache.TimeSpan.Ticks);\n        }\n\n        [Fact]\n        public void ConstructorWithNegativeTimeSpanThrows()\n        {\n            // Assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { new DefaultViewLocationCache(new TimeSpan(-1, 0, 0)); },\n                \"The number of ticks for the TimeSpan value must be greater than or equal to 0.\");\n        }\n\n        [Fact]\n        public void GetViewLocationThrowsWithNullHttpContext()\n        {\n            // Arrange\n            DefaultViewLocationCache viewLocationCache = new DefaultViewLocationCache();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { string viewLocation = viewLocationCache.GetViewLocation(null /* httpContext */, \"foo\"); },\n                \"httpContext\");\n        }\n\n        [Fact]\n        public void InsertViewLocationThrowsWithNullHttpContext()\n        {\n            // Arrange\n            DefaultViewLocationCache viewLocationCache = new DefaultViewLocationCache();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { viewLocationCache.InsertViewLocation(null /* httpContext */, \"foo\", \"fooPath\"); },\n                \"httpContext\");\n        }\n\n        [Fact]\n        public void NullViewLocationCacheReturnsNullLocations()\n        {\n            // Act\n            DefaultViewLocationCache.Null.InsertViewLocation(null /* httpContext */, \"foo\", \"fooPath\");\n\n            // Assert\n            Assert.Null(DefaultViewLocationCache.Null.GetViewLocation(null /* httpContext */, \"foo\"));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/DependencyResolverTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class DependencyResolverTest\n    {\n        [Fact]\n        public void GuardClauses()\n        {\n            // Arrange\n            var resolver = new DependencyResolver();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => resolver.InnerSetResolver((IDependencyResolver)null),\n                \"resolver\");\n            Assert.ThrowsArgumentNull(\n                () => resolver.InnerSetResolver((object)null),\n                \"commonServiceLocator\");\n            Assert.ThrowsArgumentNull(\n                () => resolver.InnerSetResolver(null, type => null),\n                \"getService\");\n            Assert.ThrowsArgumentNull(\n                () => resolver.InnerSetResolver(type => null, null),\n                \"getServices\");\n        }\n\n        [Fact]\n        public void DefaultServiceLocatorBehaviorTests()\n        {\n            // Arrange\n            var resolver = new DependencyResolver();\n\n            // Act & Assert\n            Assert.NotNull(resolver.InnerCurrent.GetService<object>()); // Concrete type\n            Assert.Null(resolver.InnerCurrent.GetService<ModelMetadataProvider>()); // Abstract type\n            Assert.Null(resolver.InnerCurrent.GetService<IDisposable>()); // Interface\n            Assert.Null(resolver.InnerCurrent.GetService(typeof(List<>))); // Open generic\n        }\n\n        [Fact]\n        public void DefaultServiceLocatorResolvesNewInstances()\n        {\n            // Arrange\n            var resolver = new DependencyResolver();\n\n            // Act\n            object obj1 = resolver.InnerCurrent.GetService<object>();\n            object obj2 = resolver.InnerCurrent.GetService<object>();\n\n            // Assert\n            Assert.NotSame(obj1, obj2);\n        }\n\n        public class MockableResolver\n        {\n            public virtual object Get(Type type)\n            {\n                throw new NotImplementedException();\n            }\n\n            public virtual IEnumerable<object> GetAll(Type type)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        [Fact]\n        public void ResolverPassesCallsToDelegateBasedResolver()\n        {\n            // Arrange\n            var resolver = new DependencyResolver();\n            var mockResolver = new Mock<MockableResolver>();\n            resolver.InnerSetResolver(mockResolver.Object.Get, mockResolver.Object.GetAll);\n\n            // Act & Assert\n            resolver.InnerCurrent.GetService(typeof(object));\n            mockResolver.Verify(r => r.Get(typeof(object)));\n\n            resolver.InnerCurrent.GetServices(typeof(string));\n            mockResolver.Verify(r => r.GetAll(typeof(string)));\n        }\n\n        public class MockableCommonServiceLocator\n        {\n            public virtual object GetInstance(Type type)\n            {\n                throw new NotImplementedException();\n            }\n\n            public virtual IEnumerable<object> GetAllInstances(Type type)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        [Fact]\n        public void ResolverPassesCallsToICommonServiceLocator()\n        {\n            // Arrange\n            var resolver = new DependencyResolver();\n            var mockResolver = new Mock<MockableCommonServiceLocator>();\n            resolver.InnerSetResolver(mockResolver.Object);\n\n            // Act & Assert\n            resolver.InnerCurrent.GetService(typeof(object));\n            mockResolver.Verify(r => r.GetInstance(typeof(object)));\n\n            resolver.InnerCurrent.GetServices(typeof(string));\n            mockResolver.Verify(r => r.GetAllInstances(typeof(string)));\n        }\n\n        class MissingGetInstance\n        {\n            public IEnumerable<object> GetAllInstances(Type type)\n            {\n                return null;\n            }\n        }\n\n        class MissingGetAllInstances\n        {\n            public object GetInstance(Type type)\n            {\n                return null;\n            }\n        }\n\n        class GetInstanceHasWrongSignature\n        {\n            public string GetInstance(Type type)\n            {\n                return null;\n            }\n\n            public IEnumerable<object> GetAllInstances(Type type)\n            {\n                return null;\n            }\n        }\n\n        class GetAllInstancesHasWrongSignature\n        {\n            public object GetInstance(Type type)\n            {\n                return null;\n            }\n\n            public IEnumerable<string> GetAllInstances(Type type)\n            {\n                return null;\n            }\n        }\n\n        [Fact]\n        public void ValidationOfCommonServiceLocatorTests()\n        {\n            // Arrange\n            var resolver = new DependencyResolver();\n\n            // Act & Assert\n            Assert.Throws<ArgumentException>(\n                () => resolver.InnerSetResolver(new MissingGetInstance()),\n                \"The type System.Web.Mvc.Test.DependencyResolverTest+MissingGetInstance does not appear to implement Microsoft.Practices.ServiceLocation.IServiceLocator.\" + Environment.NewLine\n              + \"Parameter name: commonServiceLocator\");\n            Assert.Throws<ArgumentException>(\n                () => resolver.InnerSetResolver(new MissingGetAllInstances()),\n                \"The type System.Web.Mvc.Test.DependencyResolverTest+MissingGetAllInstances does not appear to implement Microsoft.Practices.ServiceLocation.IServiceLocator.\" + Environment.NewLine\n              + \"Parameter name: commonServiceLocator\");\n            Assert.Throws<ArgumentException>(\n                () => resolver.InnerSetResolver(new GetInstanceHasWrongSignature()),\n                \"The type System.Web.Mvc.Test.DependencyResolverTest+GetInstanceHasWrongSignature does not appear to implement Microsoft.Practices.ServiceLocation.IServiceLocator.\" + Environment.NewLine\n              + \"Parameter name: commonServiceLocator\");\n            Assert.Throws<ArgumentException>(\n                () => resolver.InnerSetResolver(new GetAllInstancesHasWrongSignature()),\n                \"The type System.Web.Mvc.Test.DependencyResolverTest+GetAllInstancesHasWrongSignature does not appear to implement Microsoft.Practices.ServiceLocation.IServiceLocator.\" + Environment.NewLine\n              + \"Parameter name: commonServiceLocator\");\n        }\n\n\n\n        [Fact]\n        public void DependencyResolverCache()\n        {\n            // Verify that when we ask for an interface twice, it only queries the underlying resolver once.\n            var resolver = new DependencyResolver();\n\n            Mock<IDependencyResolver> resolverMock = new Mock<IDependencyResolver>();\n            resolverMock.Setup(r => r.GetService(typeof(object))).Returns(() => new object());\n            resolverMock.Setup(r => r.GetService(typeof(int))).Returns(15);\n\n            resolver.InnerSetResolver(resolverMock.Object);\n\n            object result1 = resolver.InnerCurrentCache.GetService(typeof(object)); // 1st call\n            object otherResult = resolver.InnerCurrentCache.GetService(typeof(int)); // 2nd call\n            object result2 = resolver.InnerCurrentCache.GetService(typeof(object)); // Cached result from 1st call\n\n\n            resolverMock.Verify(r => r.GetService(typeof(object)), Times.Once());\n            resolverMock.Verify(r => r.GetService(typeof(int)), Times.Once());\n            Assert.Same(result1, result2);\n            Assert.Equal(15, otherResult);\n        }\n\n        [Fact]\n        public void ClearDependencyResolverCache()\n        {\n            // Verify that when we ask for an interface twice, it only queries the underlying resolver once.\n            var resolver = new DependencyResolver();\n\n            Mock<IDependencyResolver> resolverMock = new Mock<IDependencyResolver>();\n            resolverMock.Setup(r => r.GetService(typeof(object))).Returns(() => new object());\n            resolverMock.Setup(r => r.GetService(typeof(int))).Returns(15);\n\n            resolver.InnerSetResolver(resolverMock.Object);\n\n            object result1 = resolver.InnerCurrentCache.GetService(typeof(object)); // 1st call\n            object otherResult = resolver.InnerCurrentCache.GetService(typeof(int)); // 2nd call\n            resolver.InnerSetResolver(resolverMock.Object); // This will clear the cache\n            object result2 = resolver.InnerCurrentCache.GetService(typeof(object)); // 3rd call\n\n\n            resolverMock.Verify(r => r.GetService(typeof(object)), Times.Exactly(2));\n            resolverMock.Verify(r => r.GetService(typeof(int)), Times.Once());\n            Assert.NotSame(result1, result2);\n            Assert.Equal(15, otherResult);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/DescriptorUtilTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class DescriptorUtilTest\n    {\n        [Fact]\n        public void AppendUniqueId_FromIUniquelyIdentifiable()\n        {\n            // Arrange\n            CustomUniquelyIdentifiable custom = new CustomUniquelyIdentifiable(\"hello-world\");\n            StringBuilder builder = new StringBuilder();\n\n            // Act\n            DescriptorUtil.AppendUniqueId(builder, custom);\n\n            // Assert\n            Assert.Equal(\"[11]hello-world\", builder.ToString());\n        }\n\n        [Fact]\n        public void AppendUniqueId_FromMemberInfo()\n        {\n            // Arrange\n            string moduleVersionId = typeof(DescriptorUtilTest).Module.ModuleVersionId.ToString();\n            string metadataToken = typeof(DescriptorUtilTest).MetadataToken.ToString();\n            string expected = String.Format(\"[{0}]{1}[{2}]{3}\", moduleVersionId.Length, moduleVersionId, metadataToken.Length, metadataToken);\n            StringBuilder builder = new StringBuilder();\n\n            // Act\n            DescriptorUtil.AppendUniqueId(builder, typeof(DescriptorUtilTest));\n\n            // Assert\n            Assert.Equal(expected, builder.ToString());\n        }\n\n        [Fact]\n        public void CreateUniqueId_FromSimpleTypes()\n        {\n            // Act\n            string retVal = DescriptorUtil.CreateUniqueId(\"foo\", null, 12345);\n\n            // Assert\n            Assert.Equal(\"[3]foo[-1][5]12345\", retVal);\n        }\n\n        private sealed class CustomUniquelyIdentifiable : IUniquelyIdentifiable\n        {\n            public CustomUniquelyIdentifiable(string uniqueId)\n            {\n                UniqueId = uniqueId;\n            }\n\n            public string UniqueId { get; private set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/DictionaryHelpersTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class DictionaryHelpersTest\n    {\n        [Fact]\n        public void DoesAnyKeyHavePrefixFailure()\n        {\n            // Arrange\n            Dictionary<string, object> dict = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase)\n            {\n                { \"FOOBAR\", 42 }\n            };\n\n            // Act\n            bool wasPrefixFound = DictionaryHelpers.DoesAnyKeyHavePrefix(dict, \"foo\");\n\n            // Assert\n            Assert.False(wasPrefixFound);\n        }\n\n        [Fact]\n        public void DoesAnyKeyHavePrefixSuccess()\n        {\n            // Arrange\n            Dictionary<string, object> dict = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase)\n            {\n                { \"FOO.BAR\", 42 }\n            };\n\n            // Act\n            bool wasPrefixFound = DictionaryHelpers.DoesAnyKeyHavePrefix(dict, \"foo\");\n\n            // Assert\n            Assert.True(wasPrefixFound);\n        }\n\n        [Fact]\n        public void FindKeysWithPrefix()\n        {\n            // Arrange\n            Dictionary<string, string> dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)\n            {\n                { \"FOO\", \"fooValue\" },\n                { \"FOOBAR\", \"foobarValue\" },\n                { \"FOO.BAR\", \"foo.barValue\" },\n                { \"FOO[0]\", \"foo[0]Value\" },\n                { \"BAR\", \"barValue\" }\n            };\n\n            // Act\n            var matchingEntries = DictionaryHelpers.FindKeysWithPrefix(dict, \"foo\");\n\n            // Assert\n            var matchingEntriesList = matchingEntries.OrderBy(entry => entry.Key).ToList();\n            Assert.Equal(3, matchingEntriesList.Count);\n            Assert.Equal(\"foo\", matchingEntriesList[0].Key);\n            Assert.Equal(\"fooValue\", matchingEntriesList[0].Value);\n            Assert.Equal(\"FOO.BAR\", matchingEntriesList[1].Key);\n            Assert.Equal(\"foo.barValue\", matchingEntriesList[1].Value);\n            Assert.Equal(\"FOO[0]\", matchingEntriesList[2].Key);\n            Assert.Equal(\"foo[0]Value\", matchingEntriesList[2].Value);\n        }\n\n        [Fact]\n        public void GetOrDefaultMissing()\n        {\n            Dictionary<string, int> dict = new Dictionary<string, int>();\n            int @default = 15;\n\n            int value = dict.GetOrDefault(\"two\", @default);\n\n            Assert.Equal(15, @default);\n        }\n\n        [Fact]\n        public void GetOrDefaultPresent()\n        {\n            Dictionary<string, int> dict = new Dictionary<string, int>() { { \"one\", 1 } };\n\n            int value = dict.GetOrDefault(\"one\", -999);\n\n            Assert.Equal(1, 1);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/DictionaryValueProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class DictionaryValueProviderTest\n    {\n        private static readonly Dictionary<string, object> _backingStore = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase)\n        {\n            { \"forty.two\", 42 },\n            { \"nineteen.eighty.four\", new DateTime(1984, 1, 1) }\n        };\n\n        [Fact]\n        public void Constructor_ThrowsIfDictionaryIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new DictionaryValueProvider<object>(null, CultureInfo.InvariantCulture); }, \"dictionary\");\n        }\n\n        [Fact]\n        public void ContainsPrefix()\n        {\n            // Arrange\n            DictionaryValueProvider<object> valueProvider = new DictionaryValueProvider<object>(_backingStore, null);\n\n            // Act\n            bool result = valueProvider.ContainsPrefix(\"forty\");\n\n            // Assert\n            Assert.True(result);\n        }\n\n        [Fact]\n        public void ContainsPrefix_DoesNotContainEmptyPrefixIfBackingStoreIsEmpty()\n        {\n            // Arrange\n            DictionaryValueProvider<object> valueProvider = new DictionaryValueProvider<object>(new Dictionary<string, object>(), null);\n\n            // Act\n            bool result = valueProvider.ContainsPrefix(\"\");\n\n            // Assert\n            Assert.False(result);\n        }\n\n        [Fact]\n        public void ContainsPrefix_ThrowsIfPrefixIsNull()\n        {\n            // Arrange\n            DictionaryValueProvider<object> valueProvider = new DictionaryValueProvider<object>(_backingStore, null);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { valueProvider.ContainsPrefix(null); }, \"prefix\");\n        }\n\n        [Fact]\n        public void GetValue()\n        {\n            // Arrange\n            CultureInfo culture = CultureInfo.GetCultureInfo(\"fr-FR\");\n            DictionaryValueProvider<object> valueProvider = new DictionaryValueProvider<object>(_backingStore, culture);\n\n            // Act\n            ValueProviderResult vpResult = valueProvider.GetValue(\"nineteen.eighty.four\");\n\n            // Assert\n            Assert.NotNull(vpResult);\n            Assert.Equal(new DateTime(1984, 1, 1), vpResult.RawValue);\n            Assert.Equal(\"01/01/1984 00:00:00\", vpResult.AttemptedValue);\n            Assert.Equal(culture, vpResult.Culture);\n        }\n\n        [Fact]\n        public void GetValue_ReturnsNullIfKeyNotFound()\n        {\n            // Arrange\n            DictionaryValueProvider<object> valueProvider = new DictionaryValueProvider<object>(_backingStore, null);\n\n            // Act\n            ValueProviderResult vpResult = valueProvider.GetValue(\"nineteen.eighty\");\n\n            // Assert\n            Assert.Null(vpResult);\n        }\n\n        [Fact]\n        public void GetValue_ThrowsIfKeyIsNull()\n        {\n            // Arrange\n            DictionaryValueProvider<object> valueProvider = new DictionaryValueProvider<object>(_backingStore, null);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { valueProvider.GetValue(null); }, \"key\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/DynamicViewDataDictionaryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Dynamic;\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class DynamicViewDataDictionaryTest\n    {\n        [Fact]\n        public void Get_OnExistingProperty_ReturnsValue()\n        {\n            // Arrange\n            ViewDataDictionary vd = new ViewDataDictionary()\n            {\n                { \"Prop\", \"Value\" }\n            };\n            dynamic dynamicVD = new DynamicViewDataDictionary(() => vd);\n\n            // Act\n            object value = dynamicVD.Prop;\n\n            // Assert\n            Assert.IsType<string>(value);\n            Assert.Equal(\"Value\", value);\n        }\n\n        [Fact]\n        public void Get_OnNonExistentProperty_ReturnsNull()\n        {\n            // Arrange\n            ViewDataDictionary vd = new ViewDataDictionary();\n            dynamic dynamicVD = new DynamicViewDataDictionary(() => vd);\n\n            // Act\n            object value = dynamicVD.Prop;\n\n            // Assert\n            Assert.Null(value);\n        }\n\n        [Fact]\n        public void Set_OnExistingProperty_OverridesValue()\n        {\n            // Arrange\n            ViewDataDictionary vd = new ViewDataDictionary()\n            {\n                { \"Prop\", \"Value\" }\n            };\n            dynamic dynamicVD = new DynamicViewDataDictionary(() => vd);\n\n            // Act\n            dynamicVD.Prop = \"NewValue\";\n\n            // Assert\n            Assert.Equal(\"NewValue\", dynamicVD.Prop);\n            Assert.Equal(\"NewValue\", vd[\"Prop\"]);\n        }\n\n        [Fact]\n        public void Set_OnNonExistentProperty_SetsValue()\n        {\n            // Arrange\n            ViewDataDictionary vd = new ViewDataDictionary();\n            dynamic dynamicVD = new DynamicViewDataDictionary(() => vd);\n\n            // Act\n            dynamicVD.Prop = \"NewValue\";\n\n            // Assert\n            Assert.Equal(\"NewValue\", dynamicVD.Prop);\n            Assert.Equal(\"NewValue\", vd[\"Prop\"]);\n        }\n\n        [Fact]\n        public void TryGetMember_OnExistingProperty_ReturnsValueAndSucceeds()\n        {\n            // Arrange\n            object result = null;\n            ViewDataDictionary vd = new ViewDataDictionary()\n            {\n                { \"Prop\", \"Value\" }\n            };\n            DynamicViewDataDictionary dynamicVD = new DynamicViewDataDictionary(() => vd);\n            Mock<GetMemberBinder> binderMock = new Mock<GetMemberBinder>(\"Prop\", /* ignoreCase */ false);\n\n            // Act\n            bool success = dynamicVD.TryGetMember(binderMock.Object, out result);\n\n            // Assert\n            Assert.True(success);\n            Assert.Equal(\"Value\", result);\n        }\n\n        [Fact]\n        public void TryGetMember_OnNonExistentProperty_ReturnsNullAndSucceeds()\n        {\n            // Arrange\n            object result = null;\n            ViewDataDictionary vd = new ViewDataDictionary();\n            DynamicViewDataDictionary dynamicVD = new DynamicViewDataDictionary(() => vd);\n            Mock<GetMemberBinder> binderMock = new Mock<GetMemberBinder>(\"Prop\", /* ignoreCase */ false);\n\n            // Act\n            bool success = dynamicVD.TryGetMember(binderMock.Object, out result);\n\n            // Assert\n            Assert.True(success);\n            Assert.Null(result);\n        }\n\n        [Fact]\n        public void TrySetMember_OnExistingProperty_OverridesValueAndSucceeds()\n        {\n            // Arrange\n            ViewDataDictionary vd = new ViewDataDictionary()\n            {\n                { \"Prop\", \"Value\" }\n            };\n            DynamicViewDataDictionary dynamicVD = new DynamicViewDataDictionary(() => vd);\n            Mock<SetMemberBinder> binderMock = new Mock<SetMemberBinder>(\"Prop\", /* ignoreCase */ false);\n\n            // Act\n            bool success = dynamicVD.TrySetMember(binderMock.Object, \"NewValue\");\n\n            // Assert\n            Assert.True(success);\n            Assert.Equal(\"NewValue\", ((dynamic)dynamicVD).Prop);\n            Assert.Equal(\"NewValue\", vd[\"Prop\"]);\n        }\n\n        [Fact]\n        public void TrySetMember_OnNonExistentProperty_SetsValueAndSucceeds()\n        {\n            // Arrange\n            ViewDataDictionary vd = new ViewDataDictionary();\n            DynamicViewDataDictionary dynamicVD = new DynamicViewDataDictionary(() => vd);\n            Mock<SetMemberBinder> binderMock = new Mock<SetMemberBinder>(\"Prop\", /* ignoreCase */ false);\n\n            // Act\n            bool success = dynamicVD.TrySetMember(binderMock.Object, \"NewValue\");\n\n            // Assert\n            Assert.True(success);\n            Assert.Equal(\"NewValue\", ((dynamic)dynamicVD).Prop);\n            Assert.Equal(\"NewValue\", vd[\"Prop\"]);\n        }\n\n        [Fact]\n        public void GetDynamicMemberNames_ReturnsEmptyListForEmptyViewDataDictionary()\n        {\n            // Arrange\n            ViewDataDictionary vd = new ViewDataDictionary();\n            DynamicViewDataDictionary dvd = new DynamicViewDataDictionary(() => vd);\n\n            // Act\n            IEnumerable<string> result = dvd.GetDynamicMemberNames();\n\n            // Assert\n            Assert.Empty(result);\n        }\n\n        [Fact]\n        public void GetDynamicMemberNames_ReturnsKeyNamesForFilledViewDataDictionary()\n        {\n            // Arrange\n            ViewDataDictionary vd = new ViewDataDictionary()\n            {\n                { \"Prop1\", 1 },\n                { \"Prop2\", 2 }\n            };\n            DynamicViewDataDictionary dvd = new DynamicViewDataDictionary(() => vd);\n\n            // Act\n            var result = dvd.GetDynamicMemberNames();\n\n            // Assert\n            Assert.Equal(new[] { \"Prop1\", \"Prop2\" }, result.OrderBy(s => s).ToArray());\n        }\n\n        [Fact]\n        public void GetDynamicMemberNames_ReflectsChangesToUnderlyingViewDataDictionary()\n        {\n            // Arrange\n            ViewDataDictionary vd = new ViewDataDictionary();\n            vd[\"OldProp\"] = 123;\n            DynamicViewDataDictionary dvd = new DynamicViewDataDictionary(() => vd);\n            vd[\"NewProp\"] = \"somevalue\";\n\n            // Act\n            var result = dvd.GetDynamicMemberNames();\n\n            // Assert\n            Assert.Equal(new[] { \"NewProp\", \"OldProp\" }, result.OrderBy(s => s).ToArray());\n        }\n\n        [Fact]\n        public void GetDynamicMemberNames_ReflectsChangesToDynamicObject()\n        {\n            // Arrange\n            ViewDataDictionary vd = new ViewDataDictionary();\n            vd[\"OldProp\"] = 123;\n            DynamicViewDataDictionary dvd = new DynamicViewDataDictionary(() => vd);\n            ((dynamic)dvd).NewProp = \"foo\";\n\n            // Act\n            var result = dvd.GetDynamicMemberNames();\n\n            // Assert\n            Assert.Equal(new[] { \"NewProp\", \"OldProp\" }, result.OrderBy(s => s).ToArray());\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/EmptyModelValidatorProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class EmptyModelValidatorProviderTest\n    {\n        [Fact]\n        public void ReturnsNoValidators()\n        {\n            // Arrange\n            EmptyModelValidatorProvider provider = new EmptyModelValidatorProvider();\n\n            // Act\n            IEnumerable<ModelValidator> result = provider.GetValidators(null, null);\n\n            // Assert\n            Assert.Empty(result);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ExceptionContextTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ExceptionContextTest\n    {\n        [Fact]\n        public void ConstructorThrowsIfExceptionIsNull()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n            Exception exception = null;\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ExceptionContext(controllerContext, exception); }, \"exception\");\n        }\n\n        [Fact]\n        public void ExceptionProperty()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n            Exception exception = new Exception();\n\n            // Act\n            ExceptionContext exceptionContext = new ExceptionContext(controllerContext, exception);\n\n            // Assert\n            Assert.Equal(exception, exceptionContext.Exception);\n        }\n\n        [Fact]\n        public void ResultProperty()\n        {\n            // Arrange\n            ExceptionContext exceptionContext = new Mock<ExceptionContext>().Object;\n\n            // Act & assert\n            MemberHelper.TestPropertyWithDefaultInstance(exceptionContext, \"Result\", new ViewResult(), EmptyResult.Instance);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ExpressionHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq.Expressions;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ExpressionHelperTest\n    {\n        [Fact]\n        public void StringBasedExpressionTests()\n        {\n            ViewDataDictionary vdd = new ViewDataDictionary();\n\n            // Uses the given expression as the expression text\n            Assert.Equal(\"?\", ExpressionHelper.GetExpressionText(\"?\"));\n\n            // Exactly \"Model\" (case-insensitive) is turned into empty string\n            Assert.Equal(String.Empty, ExpressionHelper.GetExpressionText(\"Model\"));\n            Assert.Equal(String.Empty, ExpressionHelper.GetExpressionText(\"mOdEl\"));\n\n            // Beginning with \"Model\" is untouched\n            Assert.Equal(\"Model.Foo\", ExpressionHelper.GetExpressionText(\"Model.Foo\"));\n        }\n\n        [Fact]\n        public void LambdaBasedExpressionTextTests()\n        {\n            // \"Model\" at the front of the expression is excluded (case insensitively)\n            DummyContactModel Model = null;\n            Assert.Equal(String.Empty, ExpressionHelper.GetExpressionText(Lambda<object, DummyContactModel>(m => Model)));\n            Assert.Equal(\"FirstName\", ExpressionHelper.GetExpressionText(Lambda<object, string>(m => Model.FirstName)));\n\n            DummyContactModel mOdeL = null;\n            Assert.Equal(String.Empty, ExpressionHelper.GetExpressionText(Lambda<object, DummyContactModel>(m => mOdeL)));\n            Assert.Equal(\"FirstName\", ExpressionHelper.GetExpressionText(Lambda<object, string>(m => mOdeL.FirstName)));\n\n            // Model property of model is passed through\n            Assert.Equal(\"Model\", ExpressionHelper.GetExpressionText(Lambda<DummyModelContainer, DummyContactModel>(m => m.Model)));\n\n            // \"Model\" in the middle of the expression is not excluded\n            DummyModelContainer container = null;\n            Assert.Equal(\"container.Model\", ExpressionHelper.GetExpressionText(Lambda<object, DummyContactModel>(m => container.Model)));\n            Assert.Equal(\"container.Model.FirstName\", ExpressionHelper.GetExpressionText(Lambda<object, string>(m => container.Model.FirstName)));\n\n            // The parameter is excluded\n            Assert.Equal(String.Empty, ExpressionHelper.GetExpressionText(Lambda<DummyContactModel, DummyContactModel>(m => m)));\n            Assert.Equal(\"FirstName\", ExpressionHelper.GetExpressionText(Lambda<DummyContactModel, string>(m => m.FirstName)));\n\n            // Integer indexer is included and properly computed from captured values\n            int x = 2;\n            Assert.Equal(\"container.Model[42].Length\", ExpressionHelper.GetExpressionText(Lambda<object, int>(m => container.Model[x * 21].Length)));\n            Assert.Equal(\"[42]\", ExpressionHelper.GetExpressionText(Lambda<int[], int>(m => m[x * 21])));\n\n            // String indexer is included and properly computed from captured values\n            string y = \"Hello world\";\n            Assert.Equal(\"container.Model[Hello].Length\", ExpressionHelper.GetExpressionText(Lambda<object, int>(m => container.Model[y.Substring(0, 5)].Length)));\n\n            // Back to back indexer is included\n            Assert.Equal(\"container.Model[1024][2]\", ExpressionHelper.GetExpressionText(Lambda<object, char>(m => container.Model[x * 512][x])));\n\n            // Multi-parameter indexer is excluded\n            Assert.Equal(\"Length\", ExpressionHelper.GetExpressionText(Lambda<object, int>(m => container.Model[42, \"Hello World\"].Length)));\n\n            // Single array indexer is included\n            Assert.Equal(\"container.Model.Array[1024]\", ExpressionHelper.GetExpressionText(Lambda<object, int>(m => container.Model.Array[x * 512])));\n\n            // Double array indexer is excluded\n            Assert.Equal(\"\", ExpressionHelper.GetExpressionText(Lambda<object, int>(m => container.Model.DoubleArray[1, 2])));\n\n            // Non-indexer method call is excluded\n            Assert.Equal(\"Length\", ExpressionHelper.GetExpressionText(Lambda<object, int>(m => container.Model.Method().Length)));\n\n            // Lambda expression which involves indexer which references lambda parameter throws\n            Assert.Throws<InvalidOperationException>(\n                () => ExpressionHelper.GetExpressionText(Lambda<string, char>(s => s[s.Length - 4])),\n                \"The expression compiler was unable to evaluate the indexer expression '(s.Length - 4)' because it references the model parameter 's' which is unavailable.\");\n        }\n\n        public static TheoryDataSet<LambdaExpression, string> ComplicatedLambdaExpressions\n        {\n            get\n            {\n                var collection = new List<DummyModelContainer>();\n                var index = 20;\n                var data = new TheoryDataSet<LambdaExpression, string>\n                {\n\n                    {\n                        Lambda((List<DummyModelContainer> m) => collection[10].Model.FirstName),\n                        \"collection[10].Model.FirstName\"\n                    },\n                    {\n                        Lambda((List<DummyModelContainer> m) => m[10].Model.FirstName),\n                        \"[10].Model.FirstName\"\n                    },\n                    {\n                        Lambda((List<DummyModelContainer> m) => collection[index].Model.FirstName),\n                        \"collection[20].Model.FirstName\"\n                    },\n                    {\n                        Lambda((List<DummyModelContainer> m) => m[index].Model.FirstName),\n                        \"[20].Model.FirstName\"\n                    },\n                };\n\n                return data;\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"ComplicatedLambdaExpressions\")]\n        public void GetExpressionText_WithComplicatedLambdaExpressions_ReturnsExpectedText(\n            LambdaExpression expression,\n            string expectedText)\n        {\n            // Arrange & Act\n            var result = ExpressionHelper.GetExpressionText(expression);\n\n            // Assert\n            Assert.Equal(expectedText, result);\n        }\n\n        [Fact]\n        public void GetExpressionText_WithinALoop_ReturnsExpectedText()\n        {\n            // Arrange 0\n            var collection = new List<DummyModelContainer>();\n\n            for (var i = 0; i < 2; i++)\n            {\n                // Arrange 1\n                var expectedText = string.Format(\"collection[{0}].Model.FirstName\", i);\n\n                // Act 1\n                var result = ExpressionHelper.GetExpressionText(Lambda(\n                    (List<DummyModelContainer> m) => collection[i].Model.FirstName));\n\n                // Assert 1\n                Assert.Equal(expectedText, result);\n\n                // Arrange 2\n                expectedText = string.Format(\"[{0}].Model.FirstName\", i);\n\n                // Act 2\n                result = ExpressionHelper.GetExpressionText(Lambda(\n                    (List<DummyModelContainer> m) => m[i].Model.FirstName));\n\n                // Assert 2\n                Assert.Equal(expectedText, result);\n            }\n        }\n\n        // Helpers\n\n        private static LambdaExpression Lambda<T1, T2>(Expression<Func<T1, T2>> expression)\n        {\n            return expression;\n        }\n\n        class DummyContactModel\n        {\n            public string FirstName { get; set; }\n\n            public string this[int index]\n            {\n                get { return index.ToString(); }\n            }\n\n            public string this[string index]\n            {\n                get { return index; }\n            }\n\n            public string this[int index, string index2]\n            {\n                get { return index2; }\n            }\n\n            public int[] Array { get; set; }\n\n            public int[,] DoubleArray { get; set; }\n\n            public string Method()\n            {\n                return String.Empty;\n            }\n        }\n\n        class DummyModelContainer\n        {\n            public DummyContactModel Model { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/FieldValidationMetadataTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class FieldValidationMetadataTest\n    {\n        [Fact]\n        public void FieldNameProperty()\n        {\n            // Arrange\n            FieldValidationMetadata metadata = new FieldValidationMetadata();\n\n            // Act & assert\n            MemberHelper.TestStringProperty(metadata, \"FieldName\", String.Empty);\n        }\n\n        [Fact]\n        public void ValidationRulesProperty()\n        {\n            // Arrange\n            FieldValidationMetadata metadata = new FieldValidationMetadata();\n\n            // Act\n            ICollection<ModelClientValidationRule> validationRules = metadata.ValidationRules;\n\n            // Assert\n            Assert.NotNull(validationRules);\n            Assert.Empty(validationRules);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/FileContentResultTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class FileContentResultTest\n    {\n        [Fact]\n        public void ConstructorSetsFileContentsProperty()\n        {\n            // Arrange\n            byte[] fileContents = new byte[0];\n\n            // Act\n            FileContentResult result = new FileContentResult(fileContents, \"contentType\");\n\n            // Assert\n            Assert.Same(fileContents, result.FileContents);\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfFileContentsIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new FileContentResult(null, \"contentType\"); }, \"fileContents\");\n        }\n\n        [Fact]\n        public void WriteFileCopiesBufferToOutputStream()\n        {\n            // Arrange\n            byte[] buffer = new byte[] { 1, 2, 3, 4, 5 };\n\n            Mock<Stream> mockOutputStream = new Mock<Stream>();\n            mockOutputStream.Setup(s => s.Write(buffer, 0, buffer.Length)).Verifiable();\n            Mock<HttpResponseBase> mockResponse = new Mock<HttpResponseBase>();\n            mockResponse.Setup(r => r.OutputStream).Returns(mockOutputStream.Object);\n\n            FileContentResultHelper helper = new FileContentResultHelper(buffer, \"application/octet-stream\");\n\n            // Act\n            helper.PublicWriteFile(mockResponse.Object);\n\n            // Assert\n            mockOutputStream.Verify();\n            mockResponse.Verify();\n        }\n\n        private class FileContentResultHelper : FileContentResult\n        {\n            public FileContentResultHelper(byte[] fileContents, string contentType)\n                : base(fileContents, contentType)\n            {\n            }\n\n            public void PublicWriteFile(HttpResponseBase response)\n            {\n                WriteFile(response);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/FilePathResultTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class FilePathResultTest\n    {\n        [Fact]\n        public void ConstructorSetsFileNameProperty()\n        {\n            // Act\n            FilePathResult result = new FilePathResult(\"someFile\", \"contentType\");\n\n            // Assert\n            Assert.Equal(\"someFile\", result.FileName);\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfFileNameIsEmpty()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { new FilePathResult(String.Empty, \"contentType\"); }, \"fileName\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfFileNameIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { new FilePathResult(null, \"contentType\"); }, \"fileName\");\n        }\n\n        [Fact]\n        public void WriteFileTransmitsFileToOutputStream()\n        {\n            // Arrange\n            Mock<HttpResponseBase> mockResponse = new Mock<HttpResponseBase>();\n            mockResponse.Setup(r => r.TransmitFile(\"someFile\")).Verifiable();\n\n            FilePathResultHelper helper = new FilePathResultHelper(\"someFile\", \"application/octet-stream\");\n\n            // Act\n            helper.PublicWriteFile(mockResponse.Object);\n\n            // Assert\n            mockResponse.Verify();\n        }\n\n        private class FilePathResultHelper : FilePathResult\n        {\n            public FilePathResultHelper(string fileName, string contentType)\n                : base(fileName, contentType)\n            {\n            }\n\n            public void PublicWriteFile(HttpResponseBase response)\n            {\n                WriteFile(response);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/FileResultTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Mime;\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class FileResultTest\n    {\n        [Fact]\n        public void ConstructorSetsContentTypeProperty()\n        {\n            // Act\n            FileResult result = new EmptyFileResult(\"someContentType\");\n\n            // Assert\n            Assert.Equal(\"someContentType\", result.ContentType);\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfContentTypeIsEmpty()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { new EmptyFileResult(String.Empty); }, \"contentType\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfContentTypeIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { new EmptyFileResult(null); }, \"contentType\");\n        }\n\n        [Fact]\n        public void ContentDispositionHeaderIsEncodedCorrectly()\n        {\n            // See comment in FileResult.cs detailing how the FileDownloadName should be encoded.\n\n            // Arrange\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>(MockBehavior.Strict);\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType = \"application/my-type\").Verifiable();\n            mockControllerContext.Setup(c => c.HttpContext.Response.AddHeader(\"Content-Disposition\", @\"attachment; filename=\"\"some\\\\file\"\"\")).Verifiable();\n\n            EmptyFileResult result = new EmptyFileResult(\"application/my-type\")\n            {\n                FileDownloadName = @\"some\\file\"\n            };\n\n            // Act\n            result.ExecuteResult(mockControllerContext.Object);\n\n            // Assert\n            Assert.True(result.WasWriteFileCalled);\n            mockControllerContext.Verify();\n        }\n\n        [Fact]\n        public void ContentDispositionHeaderIsEncodedCorrectlyForUnicodeCharacters()\n        {\n            // Arrange\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>(MockBehavior.Strict);\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType = \"application/my-type\").Verifiable();\n            mockControllerContext.Setup(c => c.HttpContext.Response.AddHeader(\"Content-Disposition\", @\"attachment; filename*=UTF-8''ABCXYZabcxyz012789!%40%23$%25%5E&%2A%28%29-%3D_+.:~%CE%94\")).Verifiable();\n\n            EmptyFileResult result = new EmptyFileResult(\"application/my-type\")\n            {\n                FileDownloadName = \"ABCXYZabcxyz012789!@#$%^&*()-=_+.:~Δ\"\n            };\n\n            // Act\n            result.ExecuteResult(mockControllerContext.Object);\n\n            // Assert\n            Assert.True(result.WasWriteFileCalled);\n            mockControllerContext.Verify();\n        }\n\n        [Fact]\n        public void ExecuteResultDoesNotSetContentDispositionIfNotSpecified()\n        {\n            // Arrange\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType = \"application/my-type\").Verifiable();\n\n            EmptyFileResult result = new EmptyFileResult(\"application/my-type\");\n\n            // Act\n            result.ExecuteResult(mockControllerContext.Object);\n\n            // Assert\n            Assert.True(result.WasWriteFileCalled);\n            mockControllerContext.Verify();\n        }\n\n        [Fact]\n        public void ExecuteResultSetsContentDispositionIfSpecified()\n        {\n            // Arrange\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>(MockBehavior.Strict);\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType = \"application/my-type\").Verifiable();\n            mockControllerContext.Setup(c => c.HttpContext.Response.AddHeader(\"Content-Disposition\", \"attachment; filename=filename.ext\")).Verifiable();\n\n            EmptyFileResult result = new EmptyFileResult(\"application/my-type\")\n            {\n                FileDownloadName = \"filename.ext\"\n            };\n\n            // Act\n            result.ExecuteResult(mockControllerContext.Object);\n\n            // Assert\n            Assert.True(result.WasWriteFileCalled);\n            mockControllerContext.Verify();\n        }\n\n        [Fact]\n        public void ExecuteResultThrowsIfContextIsNull()\n        {\n            // Arrange\n            FileResult result = new EmptyFileResult();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { result.ExecuteResult(null); }, \"context\");\n        }\n\n        [Fact]\n        public void FileDownloadNameProperty()\n        {\n            // Arrange\n            FileResult result = new EmptyFileResult();\n\n            // Act & assert\n            MemberHelper.TestStringProperty(result, \"FileDownloadName\", String.Empty);\n        }\n\n        public static TheoryDataSet<string, string> ContentDispositionData\n        {\n            get\n            {\n                return new TheoryDataSet<string, string>\n                {\n                    { \"09aAzZ\", \"attachment; filename=09aAzZ\" },\n                    { \" \", \"attachment; filename=\\\" \\\"\" },\n                    { \"a b\", \"attachment; filename=\\\"a b\\\"\" },\n                    { \"a\\tb\", \"attachment; filename=\\\"a\\tb\\\"\" },\n                    { \"a\\nb\", PlatformInfo.Platform == Platform.Net40 ? \"attachment; filename=\\\"a\\\\\\nb\\\"\" : \"attachment; filename=\\\"=?utf-8?B?YQpi?=\\\"\" },\n                    { \"a.b\", \"attachment; filename=a.b\" },\n                    { \"-\", \"attachment; filename=-\" },\n                    { \"_\", \"attachment; filename=_\" },\n                    { \":\", \"attachment; filename=\\\":\\\"\" },\n                    { \": :\", \"attachment; filename=\\\": :\\\"\" },\n                    { \"~\", \"attachment; filename=~\" },\n                    { \"$\", \"attachment; filename=$\" },\n                    { \"&\", \"attachment; filename=&\" },\n                    { \"+\", \"attachment; filename=+\" },\n                    { \"@\", \"attachment; filename=\\\"@\\\"\" },\n                    { \"\\\"\", \"attachment; filename=\\\"\\\\\\\"\\\"\" },\n                    { \"#\", \"attachment; filename=#\" },\n                    { \"résumé.txt\", \"attachment; filename*=UTF-8''r%C3%A9sum%C3%A9.txt\" },\n                    { \"Δ\", \"attachment; filename*=UTF-8''%CE%94\" },\n                    { \"Δ\\t\", \"attachment; filename*=UTF-8''%CE%94%09\" },\n                    { \"ABCXYZabcxyz012789!@#$%^&*()-=_+.:~Δ\", @\"attachment; filename*=UTF-8''ABCXYZabcxyz012789!%40%23$%25%5E&%2A%28%29-%3D_+.:~%CE%94\" },\n                };\n            }\n        }\n\n        [Theory, PropertyData(\"ContentDispositionData\")]\n        public void GetHeaderValue_Produces_Correct_ContentDisposition(string input, string expectedOutput)\n        {\n            // Arrange & Act\n            string actual = FileResult.ContentDispositionUtil.GetHeaderValue(input);\n\n            // Assert\n            Assert.Equal(expectedOutput, actual);\n        }\n\n        private class EmptyFileResult : FileResult\n        {\n            public bool WasWriteFileCalled;\n\n            public EmptyFileResult()\n                : this(MediaTypeNames.Application.Octet)\n            {\n            }\n\n            public EmptyFileResult(string contentType)\n                : base(contentType)\n            {\n            }\n\n            protected override void WriteFile(HttpResponseBase response)\n            {\n                WasWriteFileCalled = true;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/FileStreamResultTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class FileStreamResultTest\n    {\n        private static readonly Random _random = new Random();\n\n        [Fact]\n        public void ConstructorSetsFileStreamProperty()\n        {\n            // Arrange\n            Stream stream = new MemoryStream();\n\n            // Act\n            FileStreamResult result = new FileStreamResult(stream, \"contentType\");\n\n            // Assert\n            Assert.Same(stream, result.FileStream);\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfFileStreamIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new FileStreamResult(null, \"contentType\"); }, \"fileStream\");\n        }\n\n        [Fact]\n        public void WriteFileCopiesProvidedStreamToOutputStream()\n        {\n            // Arrange\n            int byteLen = 0x1234;\n            byte[] originalBytes = GetRandomByteArray(byteLen);\n            MemoryStream originalStream = new MemoryStream(originalBytes);\n            MemoryStream outStream = new MemoryStream();\n\n            Mock<HttpResponseBase> mockResponse = new Mock<HttpResponseBase>();\n            mockResponse.Setup(r => r.OutputStream).Returns(outStream);\n\n            FileStreamResultHelper helper = new FileStreamResultHelper(originalStream, \"application/octet-stream\");\n\n            // Act\n            helper.PublicWriteFile(mockResponse.Object);\n\n            // Assert\n            byte[] outBytes = outStream.ToArray();\n            Assert.True(originalBytes.SequenceEqual(outBytes));\n            mockResponse.Verify();\n        }\n\n        private static byte[] GetRandomByteArray(int length)\n        {\n            byte[] bytes = new byte[length];\n            _random.NextBytes(bytes);\n            return bytes;\n        }\n\n        private class FileStreamResultHelper : FileStreamResult\n        {\n            public FileStreamResultHelper(Stream fileStream, string contentType)\n                : base(fileStream, contentType)\n            {\n            }\n\n            public void PublicWriteFile(HttpResponseBase response)\n            {\n                WriteFile(response);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/FilterAttributeFilterProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class FilterAttributeFilterProviderTest\n    {\n        [Fact]\n        public void GetFilters_WithNullController_ReturnsEmptyList()\n        {\n            // Arrange\n            var context = new ControllerContext();\n            var descriptor = new Mock<ActionDescriptor>().Object;\n            var provider = new FilterAttributeFilterProvider();\n\n            // Act\n            IEnumerable<Filter> result = provider.GetFilters(context, descriptor);\n\n            // Assert\n            Assert.Empty(result);\n        }\n\n        [MyFilter(Order = 2112)]\n        private class ControllerWithTypeAttribute : Controller\n        {\n        }\n\n        [Fact]\n        public void GetFilters_IncludesAttributesOnControllerType()\n        {\n            // Arrange\n            var context = new ControllerContext { Controller = new ControllerWithTypeAttribute() };\n            var controllerDescriptorMock = new Mock<ControllerDescriptor>();\n            controllerDescriptorMock.Setup(cd => cd.GetFilterAttributes(It.IsAny<bool>()))\n                .Returns(new FilterAttribute[] { new MyFilterAttribute { Order = 2112 } });\n            var actionDescriptorMock = new Mock<ActionDescriptor>();\n            actionDescriptorMock.Setup(ad => ad.ControllerDescriptor).Returns(controllerDescriptorMock.Object);\n            var provider = new FilterAttributeFilterProvider();\n\n            // Act\n            Filter filter = provider.GetFilters(context, actionDescriptorMock.Object).Single();\n\n            // Assert\n            MyFilterAttribute attrib = filter.Instance as MyFilterAttribute;\n            Assert.NotNull(attrib);\n            Assert.Equal(FilterScope.Controller, filter.Scope);\n            Assert.Equal(2112, filter.Order);\n        }\n\n        private class ControllerWithActionAttribute : Controller\n        {\n            [MyFilter(Order = 1234)]\n            public ActionResult MyActionMethod()\n            {\n                return null;\n            }\n        }\n\n        [Fact]\n        public void GetFilters_IncludesAttributesOnActionMethod()\n        {\n            // Arrange\n            var context = new ControllerContext { Controller = new ControllerWithActionAttribute() };\n            var controllerDescriptor = new ReflectedControllerDescriptor(context.Controller.GetType());\n            var action = context.Controller.GetType().GetMethod(\"MyActionMethod\");\n            var actionDescriptor = new ReflectedActionDescriptor(action, \"MyActionMethod\", controllerDescriptor);\n            var provider = new FilterAttributeFilterProvider();\n\n            // Act\n            Filter filter = provider.GetFilters(context, actionDescriptor).Single();\n\n            // Assert\n            MyFilterAttribute attrib = filter.Instance as MyFilterAttribute;\n            Assert.NotNull(attrib);\n            Assert.Equal(FilterScope.Action, filter.Scope);\n            Assert.Equal(1234, filter.Order);\n        }\n\n        private abstract class BaseController : Controller\n        {\n            public ActionResult MyActionMethod()\n            {\n                return null;\n            }\n        }\n\n        [MyFilter]\n        private class DerivedController : BaseController\n        {\n        }\n\n        [Fact]\n        public void GetFilters_IncludesTypeAttributesFromDerivedTypeWhenMethodIsOnBaseClass()\n        { // DDB #208062\n            // Arrange\n            var context = new ControllerContext { Controller = new DerivedController() };\n            var controllerDescriptor = new ReflectedControllerDescriptor(context.Controller.GetType());\n            var action = context.Controller.GetType().GetMethod(\"MyActionMethod\");\n            var actionDescriptor = new ReflectedActionDescriptor(action, \"MyActionMethod\", controllerDescriptor);\n            var provider = new FilterAttributeFilterProvider();\n\n            // Act\n            IEnumerable<Filter> filters = provider.GetFilters(context, actionDescriptor);\n\n            // Assert\n            Assert.NotNull(filters.Select(f => f.Instance).Cast<MyFilterAttribute>().Single());\n        }\n\n        private class MyFilterAttribute : FilterAttribute\n        {\n        }\n\n        [Fact]\n        public void GetFilters_RetrievesCachedAttributesByDefault()\n        {\n            // Arrange\n            var provider = new FilterAttributeFilterProvider();\n            var context = new ControllerContext { Controller = new DerivedController() };\n            var controllerDescriptorMock = new Mock<ControllerDescriptor>();\n            controllerDescriptorMock.Setup(cd => cd.GetFilterAttributes(true)).Returns(Enumerable.Empty<FilterAttribute>()).Verifiable();\n            var actionDescriptorMock = new Mock<ActionDescriptor>();\n            actionDescriptorMock.Setup(ad => ad.GetFilterAttributes(true)).Returns(Enumerable.Empty<FilterAttribute>()).Verifiable();\n            actionDescriptorMock.Setup(ad => ad.ControllerDescriptor).Returns(controllerDescriptorMock.Object);\n\n            // Act\n            var result = provider.GetFilters(context, actionDescriptorMock.Object).ToList();\n\n            // Assert\n            controllerDescriptorMock.Verify();\n            actionDescriptorMock.Verify();\n        }\n\n        [Fact]\n        public void GetFilters_RetrievesNonCachedAttributesWhenConfiguredNotTo()\n        {\n            // Arrange\n            var provider = new FilterAttributeFilterProvider(false);\n            var context = new ControllerContext { Controller = new DerivedController() };\n            var controllerDescriptorMock = new Mock<ControllerDescriptor>();\n            controllerDescriptorMock.Setup(cd => cd.GetFilterAttributes(false)).Returns(Enumerable.Empty<FilterAttribute>()).Verifiable();\n            var actionDescriptorMock = new Mock<ActionDescriptor>();\n            actionDescriptorMock.Setup(ad => ad.GetFilterAttributes(false)).Returns(Enumerable.Empty<FilterAttribute>()).Verifiable();\n            actionDescriptorMock.Setup(ad => ad.ControllerDescriptor).Returns(controllerDescriptorMock.Object);\n\n            // Act\n            var result = provider.GetFilters(context, actionDescriptorMock.Object).ToList();\n\n            // Assert\n            controllerDescriptorMock.Verify();\n            actionDescriptorMock.Verify();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/FilterInfoTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Mvc.Filters;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class FilterInfoTest\n    {\n        [Fact]\n        public void Constructor_Default()\n        {\n            // Arrange + Act\n            FilterInfo filterInfo = new FilterInfo();\n\n            // Assert\n            Assert.Empty(filterInfo.ActionFilters);\n            Assert.Empty(filterInfo.AuthorizationFilters);\n            Assert.Empty(filterInfo.AuthenticationFilters);\n            Assert.Empty(filterInfo.ExceptionFilters);\n            Assert.Empty(filterInfo.ResultFilters);\n        }\n\n        [Fact]\n        public void Constructor_PopulatesFilterCollections()\n        {\n            // Arrange\n            IActionFilter expectedActionFilter = CreateDummyActionFilter();\n            IAuthorizationFilter expectedAuthorizationFilter = CreateDummyAuthorizationFilter();\n            IAuthenticationFilter expectedAuthenticationFilter = CreateDummyAuthenticationFilter();\n            IExceptionFilter expectedExceptionFilter = CreateDummyExceptionFilter();\n            IResultFilter expectedResultFilter = CreateDummyResultFilter();\n\n            List<Filter> filters = new List<Filter>()\n            {\n                CreateFilter(expectedActionFilter),\n                CreateFilter(expectedAuthorizationFilter),\n                CreateFilter(expectedAuthenticationFilter),\n                CreateFilter(expectedExceptionFilter),\n                CreateFilter(expectedResultFilter),\n            };\n\n            // Act\n            FilterInfo filterInfo = new FilterInfo(filters);\n\n            // Assert\n            Assert.Same(expectedActionFilter, filterInfo.ActionFilters.SingleOrDefault());\n            Assert.Same(expectedAuthorizationFilter, filterInfo.AuthorizationFilters.SingleOrDefault());\n            Assert.Same(expectedAuthenticationFilter, filterInfo.AuthenticationFilters.SingleOrDefault());\n            Assert.Same(expectedExceptionFilter, filterInfo.ExceptionFilters.SingleOrDefault());\n            Assert.Same(expectedResultFilter, filterInfo.ResultFilters.SingleOrDefault());\n        }\n\n        [Fact]\n        public void Constructor_IteratesOverFiltersOnlyOnce()\n        {\n            // Arrange\n            var filtersMock = new Mock<IEnumerable<Filter>>();\n            filtersMock.Setup(f => f.GetEnumerator()).Returns(new List<Filter>().GetEnumerator());\n\n            // Act\n            FilterInfo filterInfo = new FilterInfo(filtersMock.Object);\n\n            // Assert\n            filtersMock.Verify(f => f.GetEnumerator(), Times.Once());\n        }\n\n        [Fact]\n        public void ActionFilters_ReturnsAllActionFilters_WhenOverrideScopeIsFirst()\n        {\n            // Arrange\n            IActionFilter expectedFirstFilter = CreateDummyActionFilter();\n            Filter firstFilter = CreateFilter(expectedFirstFilter, FilterScope.First);\n            IActionFilter expectedGlobalFilter = CreateDummyActionFilter();\n            Filter globalFilter = CreateFilter(expectedGlobalFilter, FilterScope.Global);\n            IActionFilter expectedControllerFilter = CreateDummyActionFilter();\n            Filter controllerFilter = CreateFilter(expectedControllerFilter, FilterScope.Controller);\n            IActionFilter expectedActionFilter = CreateDummyActionFilter();\n            Filter actionFilter = CreateFilter(expectedActionFilter, FilterScope.Action);\n            IActionFilter expectedLastFilter = CreateDummyActionFilter();\n            Filter lastFilter = CreateFilter(expectedLastFilter, FilterScope.Last);\n            Filter overrideFilter = CreateFilter(CreateOverride(typeof(IActionFilter)), FilterScope.First);\n            IEnumerable<Filter> filters = new Filter[] { firstFilter, globalFilter, controllerFilter, actionFilter,\n                lastFilter, overrideFilter };\n            FilterInfo product = CreateProductUnderTest(filters);\n\n            // Act\n            IList<IActionFilter> actionFilters = product.ActionFilters;\n\n            // Assert\n            Assert.NotNull(actionFilters);\n            Assert.Equal(5, actionFilters.Count);\n            Assert.Same(expectedFirstFilter, actionFilters[0]);\n            Assert.Same(expectedGlobalFilter, actionFilters[1]);\n            Assert.Same(expectedControllerFilter, actionFilters[2]);\n            Assert.Same(expectedActionFilter, actionFilters[3]);\n            Assert.Same(expectedLastFilter, actionFilters[4]);\n        }\n\n        [Fact]\n        public void ActionFilters_ReturnsGlobalAndBelowActionFilters_WhenOverrideScopeIsGlobal()\n        {\n            // Arrange\n            Filter firstFilter = CreateFilter(CreateDummyActionFilter(), FilterScope.First);\n            IActionFilter expectedGlobalFilter = CreateDummyActionFilter();\n            Filter globalFilter = CreateFilter(expectedGlobalFilter, FilterScope.Global);\n            IActionFilter expectedControllerFilter = CreateDummyActionFilter();\n            Filter controllerFilter = CreateFilter(expectedControllerFilter, FilterScope.Controller);\n            IActionFilter expectedActionFilter = CreateDummyActionFilter();\n            Filter actionFilter = CreateFilter(expectedActionFilter, FilterScope.Action);\n            IActionFilter expectedLastFilter = CreateDummyActionFilter();\n            Filter lastFilter = CreateFilter(expectedLastFilter, FilterScope.Last);\n            Filter overrideFilter = CreateFilter(CreateOverride(typeof(IActionFilter)), FilterScope.Global);\n            IEnumerable<Filter> filters = new Filter[] { firstFilter, globalFilter, controllerFilter, actionFilter,\n                lastFilter, overrideFilter };\n            FilterInfo product = CreateProductUnderTest(filters);\n\n            // Act\n            IList<IActionFilter> actionFilters = product.ActionFilters;\n\n            // Assert\n            Assert.NotNull(actionFilters);\n            Assert.Equal(4, actionFilters.Count);\n            Assert.Same(expectedGlobalFilter, actionFilters[0]);\n            Assert.Same(expectedControllerFilter, actionFilters[1]);\n            Assert.Same(expectedActionFilter, actionFilters[2]);\n            Assert.Same(expectedLastFilter, actionFilters[3]);\n        }\n\n        [Fact]\n        public void ActionFilters_ReturnsControllerAndBelowActionFilters_WhenOverrideScopeIsController()\n        {\n            // Arrange\n            Filter firstFilter = CreateFilter(CreateDummyActionFilter(), FilterScope.First);\n            Filter globalFilter = CreateFilter(CreateDummyActionFilter(), FilterScope.Global);\n            IActionFilter expectedControllerFilter = CreateDummyActionFilter();\n            Filter controllerFilter = CreateFilter(expectedControllerFilter, FilterScope.Controller);\n            IActionFilter expectedActionFilter = CreateDummyActionFilter();\n            Filter actionFilter = CreateFilter(expectedActionFilter, FilterScope.Action);\n            IActionFilter expectedLastFilter = CreateDummyActionFilter();\n            Filter lastFilter = CreateFilter(expectedLastFilter, FilterScope.Last);\n            Filter overrideFilter = CreateFilter(CreateOverride(typeof(IActionFilter)), FilterScope.Controller);\n            IEnumerable<Filter> filters = new Filter[] { firstFilter, globalFilter, controllerFilter, actionFilter,\n                lastFilter, overrideFilter };\n            FilterInfo product = CreateProductUnderTest(filters);\n\n            // Act\n            IList<IActionFilter> actionFilters = product.ActionFilters;\n\n            // Assert\n            Assert.NotNull(actionFilters);\n            Assert.Equal(3, actionFilters.Count);\n            Assert.Same(expectedControllerFilter, actionFilters[0]);\n            Assert.Same(expectedActionFilter, actionFilters[1]);\n            Assert.Same(expectedLastFilter, actionFilters[2]);\n        }\n\n        [Fact]\n        public void ActionFilters_ReturnsActionScopeAndBelowActionFilters_WhenOverrideScopeIsAction()\n        {\n            // Arrange\n            Filter firstFilter = CreateFilter(CreateDummyActionFilter(), FilterScope.First);\n            Filter globalFilter = CreateFilter(CreateDummyActionFilter(), FilterScope.Global);\n            Filter controllerFilter = CreateFilter(CreateDummyActionFilter(), FilterScope.Controller);\n            IActionFilter expectedActionFilter = CreateDummyActionFilter();\n            Filter actionFilter = CreateFilter(expectedActionFilter, FilterScope.Action);\n            IActionFilter expectedLastFilter = CreateDummyActionFilter();\n            Filter lastFilter = CreateFilter(expectedLastFilter, FilterScope.Last);\n            Filter overrideFilter = CreateFilter(CreateOverride(typeof(IActionFilter)), FilterScope.Action);\n            IEnumerable<Filter> filters = new Filter[] { firstFilter, globalFilter, controllerFilter, actionFilter,\n                lastFilter, overrideFilter };\n            FilterInfo product = CreateProductUnderTest(filters);\n\n            // Act\n            IList<IActionFilter> actionFilters = product.ActionFilters;\n\n            // Assert\n            Assert.NotNull(actionFilters);\n            Assert.Equal(2, actionFilters.Count);\n            Assert.Same(expectedActionFilter, actionFilters[0]);\n            Assert.Same(expectedLastFilter, actionFilters[1]);\n        }\n\n        [Fact]\n        public void ActionFilters_ReturnLastActionFilters_WhenOverrideScopeIsLast()\n        {\n            // Arrange\n            Filter firstFilter = CreateFilter(CreateDummyActionFilter(), FilterScope.First);\n            Filter globalFilter = CreateFilter(CreateDummyActionFilter(), FilterScope.Global);\n            Filter controllerFilter = CreateFilter(CreateDummyActionFilter(), FilterScope.Controller);\n            Filter actionFilter = CreateFilter(CreateDummyActionFilter(), FilterScope.Action);\n            IActionFilter expectedLastFilter = CreateDummyActionFilter();\n            Filter lastFilter = CreateFilter(expectedLastFilter, FilterScope.Last);\n            Filter overrideFilter = CreateFilter(CreateOverride(typeof(IActionFilter)), FilterScope.Last);\n            IEnumerable<Filter> filters = new Filter[] { firstFilter, globalFilter, controllerFilter, actionFilter,\n                lastFilter, overrideFilter };\n            FilterInfo product = CreateProductUnderTest(filters);\n\n            // Act\n            IList<IActionFilter> actionFilters = product.ActionFilters;\n\n            // Assert\n            Assert.NotNull(actionFilters);\n            Assert.Equal(1, actionFilters.Count);\n            Assert.Same(expectedLastFilter, actionFilters[0]);\n        }\n\n        [Fact]\n        public void ActionFilters_ReturnsAllActionFilters_WhenOtherFilterIsOverriddenAtActionLevel()\n        {\n            // Arrange\n            IActionFilter expectedFirstFilter = CreateDummyActionFilter();\n            Filter firstFilter = CreateFilter(expectedFirstFilter, FilterScope.First);\n            IActionFilter expectedGlobalFilter = CreateDummyActionFilter();\n            Filter globalFilter = CreateFilter(expectedGlobalFilter, FilterScope.Global);\n            IActionFilter expectedControllerFilter = CreateDummyActionFilter();\n            Filter controllerFilter = CreateFilter(expectedControllerFilter, FilterScope.Controller);\n            IActionFilter expectedActionFilter = CreateDummyActionFilter();\n            Filter actionFilter = CreateFilter(expectedActionFilter, FilterScope.Action);\n            IActionFilter expectedLastFilter = CreateDummyActionFilter();\n            Filter lastFilter = CreateFilter(expectedLastFilter, FilterScope.Last);\n            Filter overrideFilter = CreateFilter(CreateOverride(typeof(object)), FilterScope.Action);\n            IEnumerable<Filter> filters = new Filter[] { firstFilter, globalFilter, controllerFilter, actionFilter,\n                lastFilter, overrideFilter };\n            FilterInfo product = CreateProductUnderTest(filters);\n\n            // Act\n            IList<IActionFilter> actionFilters = product.ActionFilters;\n\n            // Assert\n            Assert.NotNull(actionFilters);\n            Assert.Equal(5, actionFilters.Count);\n            Assert.Same(expectedFirstFilter, actionFilters[0]);\n            Assert.Same(expectedGlobalFilter, actionFilters[1]);\n            Assert.Same(expectedControllerFilter, actionFilters[2]);\n            Assert.Same(expectedActionFilter, actionFilters[3]);\n            Assert.Same(expectedLastFilter, actionFilters[4]);\n        }\n\n        [Fact]\n        public void AuthorizationFilters_ReturnsLastAuthorizationFilters_WhenOverrideScopeIsLast()\n        {\n            // Arrange\n            Filter firstFilter = CreateFilter(CreateDummyAuthorizationFilter(), FilterScope.First);\n            Filter globalFilter = CreateFilter(CreateDummyAuthorizationFilter(), FilterScope.Global);\n            Filter controllerFilter = CreateFilter(CreateDummyAuthorizationFilter(), FilterScope.Controller);\n            Filter actionFilter = CreateFilter(CreateDummyAuthorizationFilter(), FilterScope.Action);\n            IAuthorizationFilter expectedLastFilter = CreateDummyAuthorizationFilter();\n            Filter lastFilter = CreateFilter(expectedLastFilter, FilterScope.Last);\n            Filter overrideFilter = CreateFilter(CreateOverride(typeof(IAuthorizationFilter)), FilterScope.Last);\n            IEnumerable<Filter> filters = new Filter[] { firstFilter, globalFilter, controllerFilter, actionFilter,\n                lastFilter, overrideFilter };\n            FilterInfo product = CreateProductUnderTest(filters);\n\n            // Act\n            IList<IAuthorizationFilter> authorizationFilters = product.AuthorizationFilters;\n\n            // Assert\n            Assert.NotNull(authorizationFilters);\n            Assert.Equal(1, authorizationFilters.Count);\n            Assert.Same(expectedLastFilter, authorizationFilters[0]);\n        }\n\n        [Fact]\n        public void AuthenticationFilters_ReturnsLastAuthenticationFilters_WhenOverrideScopeIsLast()\n        {\n            // Arrange\n            Filter firstFilter = CreateFilter(CreateDummyAuthenticationFilter(), FilterScope.First);\n            Filter globalFilter = CreateFilter(CreateDummyAuthenticationFilter(), FilterScope.Global);\n            Filter controllerFilter = CreateFilter(CreateDummyAuthenticationFilter(), FilterScope.Controller);\n            Filter actionFilter = CreateFilter(CreateDummyAuthenticationFilter(), FilterScope.Action);\n            IAuthenticationFilter expectedLastFilter = CreateDummyAuthenticationFilter();\n            Filter lastFilter = CreateFilter(expectedLastFilter, FilterScope.Last);\n            Filter overrideFilter = CreateFilter(CreateOverride(typeof(IAuthenticationFilter)), FilterScope.Last);\n            IEnumerable<Filter> filters = new Filter[] { firstFilter, globalFilter, controllerFilter, actionFilter,\n                lastFilter, overrideFilter };\n            FilterInfo product = CreateProductUnderTest(filters);\n\n            // Act\n            IList<IAuthenticationFilter> authenticationFilters = product.AuthenticationFilters;\n\n            // Assert\n            Assert.NotNull(authenticationFilters);\n            Assert.Equal(1, authenticationFilters.Count);\n            Assert.Same(expectedLastFilter, authenticationFilters[0]);\n        }\n\n        [Fact]\n        public void ExceptionFilters_ReturnsLastExceptionFilters_WhenOverrideScopeIsLast()\n        {\n            // Arrange\n            Filter firstFilter = CreateFilter(CreateDummyExceptionFilter(), FilterScope.First);\n            Filter globalFilter = CreateFilter(CreateDummyExceptionFilter(), FilterScope.Global);\n            Filter controllerFilter = CreateFilter(CreateDummyExceptionFilter(), FilterScope.Controller);\n            Filter actionFilter = CreateFilter(CreateDummyExceptionFilter(), FilterScope.Action);\n            IExceptionFilter expectedLastFilter = CreateDummyExceptionFilter();\n            Filter lastFilter = CreateFilter(expectedLastFilter, FilterScope.Last);\n            Filter overrideFilter = CreateFilter(CreateOverride(typeof(IExceptionFilter)), FilterScope.Last);\n            IEnumerable<Filter> filters = new Filter[] { firstFilter, globalFilter, controllerFilter, actionFilter,\n                lastFilter, overrideFilter };\n            FilterInfo product = CreateProductUnderTest(filters);\n\n            // Act\n            IList<IExceptionFilter> exceptionFilters = product.ExceptionFilters;\n\n            // Assert\n            Assert.NotNull(exceptionFilters);\n            Assert.Equal(1, exceptionFilters.Count);\n            Assert.Same(expectedLastFilter, exceptionFilters[0]);\n        }\n\n        [Fact]\n        public void ResultFilters_ReturnsLastResultFilters_WhenOverrideScopeIsLast()\n        {\n            // Arrange\n            Filter firstFilter = CreateFilter(CreateDummyResultFilter(), FilterScope.First);\n            Filter globalFilter = CreateFilter(CreateDummyResultFilter(), FilterScope.Global);\n            Filter controllerFilter = CreateFilter(CreateDummyResultFilter(), FilterScope.Controller);\n            Filter actionFilter = CreateFilter(CreateDummyResultFilter(), FilterScope.Action);\n            IResultFilter expectedLastFilter = CreateDummyResultFilter();\n            Filter lastFilter = CreateFilter(expectedLastFilter, FilterScope.Last);\n            Filter overrideFilter = CreateFilter(CreateOverride(typeof(IResultFilter)), FilterScope.Last);\n            IEnumerable<Filter> filters = new Filter[] { firstFilter, globalFilter, controllerFilter, actionFilter,\n                lastFilter, overrideFilter };\n            FilterInfo product = CreateProductUnderTest(filters);\n\n            // Act\n            IList<IResultFilter> resultFilters = product.ResultFilters;\n\n            // Assert\n            Assert.NotNull(resultFilters);\n            Assert.Equal(1, resultFilters.Count);\n            Assert.Same(expectedLastFilter, resultFilters[0]);\n        }\n\n        [Fact]\n        public void FilterImplementingMultipleType_WhereOneTypeIsOverridden_AppearsOnlyInTheOtherList()\n        {\n            // Arrange\n            object expectedInstance = new ActionAndExceptionFilter();\n            Filter actionAndExceptionFilter = CreateFilter(expectedInstance, FilterScope.Global);\n            Filter overrideExceptionFilter = CreateFilter(CreateOverride(typeof(IExceptionFilter)),\n                FilterScope.Action);\n            IEnumerable<Filter> filters = new Filter[] { actionAndExceptionFilter, overrideExceptionFilter };\n            FilterInfo product = CreateProductUnderTest(filters);\n\n            // Act\n            IList<IActionFilter> actionFilters = product.ActionFilters;\n            IList<IExceptionFilter> exceptionFilters = product.ExceptionFilters;\n\n            // Assert\n            Assert.NotNull(actionFilters);\n            Assert.Equal(1, actionFilters.Count);\n            Assert.Same(expectedInstance, actionFilters[0]);\n            Assert.NotNull(exceptionFilters);\n            Assert.Equal(0, exceptionFilters.Count);\n        }\n\n        private static IActionFilter CreateDummyActionFilter()\n        {\n            return new Mock<IActionFilter>(MockBehavior.Strict).Object;\n        }\n\n        private static IAuthenticationFilter CreateDummyAuthenticationFilter()\n        {\n            return new Mock<IAuthenticationFilter>(MockBehavior.Strict).Object;\n        }\n\n        private static IAuthorizationFilter CreateDummyAuthorizationFilter()\n        {\n            return new Mock<IAuthorizationFilter>(MockBehavior.Strict).Object;\n        }\n\n        private static IExceptionFilter CreateDummyExceptionFilter()\n        {\n            return new Mock<IExceptionFilter>(MockBehavior.Strict).Object;\n        }\n\n        private static IResultFilter CreateDummyResultFilter()\n        {\n            return new Mock<IResultFilter>(MockBehavior.Strict).Object;\n        }\n\n        private static IEnumerable<Filter> CreateEmptyFilters()\n        {\n            return new Filter[0];\n        }\n\n        private static IOverrideFilter CreateOverride(Type filtersToOverride)\n        {\n            Mock<IOverrideFilter> mock = new Mock<IOverrideFilter>();\n            mock.Setup(f => f.FiltersToOverride).Returns(filtersToOverride);\n            return mock.Object;\n        }\n\n        private static FilterInfo CreateProductUnderTest(IEnumerable<Filter> filters)\n        {\n            return new FilterInfo(filters);\n        }\n\n        private static Filter CreateFilter(object instance)\n        {\n            return CreateFilter(instance, FilterScope.Global);\n        }\n\n        private static Filter CreateFilter(object instance, FilterScope scope)\n        {\n            return new Filter(instance, scope, null);\n        }\n\n        private class ActionAndExceptionFilter : IActionFilter, IExceptionFilter\n        {\n            public void OnActionExecuting(ActionExecutingContext filterContext)\n            {\n                throw new NotImplementedException();\n            }\n\n            public void OnActionExecuted(ActionExecutedContext filterContext)\n            {\n                throw new NotImplementedException();\n            }\n\n            public void OnException(ExceptionContext filterContext)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/FilterProviderCollectionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class FilterProviderCollectionTest\n    {\n        [Fact]\n        public void GuardClauses()\n        {\n            // Arrange\n            var context = new ControllerContext();\n            var descriptor = new Mock<ActionDescriptor>().Object;\n            var collection = new FilterProviderCollection();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => collection.GetFilters(null, descriptor),\n                \"controllerContext\"\n                );\n            Assert.ThrowsArgumentNull(\n                () => collection.GetFilters(context, null),\n                \"actionDescriptor\"\n                );\n        }\n\n        [Fact]\n        public void FilterProviderCollectionCombinedItemsCaches()\n        {\n            // Arrange\n            var providers = new IFilterProvider[] \n            {\n                new Mock<IFilterProvider>(MockBehavior.Strict).Object, \n                new Mock<IFilterProvider>(MockBehavior.Strict).Object\n            };\n            var collection = new FilterProviderCollection(providers);\n\n            // Act\n            IFilterProvider[] combined1 = collection.CombinedItems;\n            IFilterProvider[] combined2 = collection.CombinedItems;\n\n            // Assert\n            Assert.Equal(providers, combined1);\n            Assert.Same(combined1, combined2);\n        }\n\n        [Fact]\n        public void FilterProviderCollectionCombinedItemsClearResetsCache()\n        {\n            TestCacheReset((collection) => collection.Clear());\n        }\n\n        [Fact]\n        public void FilterProviderCollectionCombinedItemsInsertResetsCache()\n        {\n            TestCacheReset((collection) => collection.Insert(0, new Mock<IFilterProvider>(MockBehavior.Strict).Object));\n        }\n\n        [Fact]\n        public void FilterProviderCollectionCombinedItemsRemoveResetsCache()\n        {\n            TestCacheReset((collection) => collection.RemoveAt(0));\n        }\n\n        [Fact]\n        public void FilterProviderCollectionCombinedItemsSetResetsCache()\n        {\n            TestCacheReset((collection) => collection[0] = new Mock<IFilterProvider>(MockBehavior.Strict).Object);\n        }\n\n        private static void TestCacheReset(Action<FilterProviderCollection> mutatingAction)\n        {\n            // Arrange\n            var providers = new List<IFilterProvider>() \n            {\n                new Mock<IFilterProvider>(MockBehavior.Strict).Object, \n                new Mock<IFilterProvider>(MockBehavior.Strict).Object\n            };\n            var collection = new FilterProviderCollection(providers);\n\n            // Act\n            mutatingAction(collection);\n\n            IFilterProvider[] combined = collection.CombinedItems;\n\n            // Assert\n            Assert.Equal(providers, combined);\n        }\n\n        [Fact]\n        public void FilterProviderCollectionCombinedItemsDelegatesToResolver()\n        {\n            // Arrange\n            var firstProvider = new Mock<IFilterProvider>();\n            var secondProvider = new Mock<IFilterProvider>();\n            var thirdProvider = new Mock<IFilterProvider>();\n            var dependencyProviders = new IFilterProvider[] { firstProvider.Object, secondProvider.Object };\n            var collectionProviders = new IFilterProvider[] { thirdProvider.Object };\n            var expectedProviders = new IFilterProvider[] { firstProvider.Object, secondProvider.Object, thirdProvider.Object };\n\n            Mock<IDependencyResolver> resolver = new Mock<IDependencyResolver>();\n            resolver.Setup(r => r.GetServices(typeof(IFilterProvider))).Returns(dependencyProviders);\n\n            var providers = new FilterProviderCollection(collectionProviders, resolver.Object);\n\n            // Act\n            IFilterProvider[] combined = providers.CombinedItems;\n\n            // Assert\n            Assert.Equal(expectedProviders, combined);\n        }\n\n        [Fact]\n        public void GetFiltersUsesRegisteredProviders()\n        {\n            // Arrange\n            var context = new ControllerContext();\n            var descriptor = new Mock<ActionDescriptor>().Object;\n            var filter = new Filter(new Object(), FilterScope.Action, null);\n            var provider = new Mock<IFilterProvider>(MockBehavior.Strict);\n            var collection = new FilterProviderCollection(new[] { provider.Object });\n            provider.Setup(p => p.GetFilters(context, descriptor)).Returns(new[] { filter });\n\n            // Act\n            IEnumerable<Filter> result = collection.GetFilters(context, descriptor);\n\n            // Assert\n            Assert.Same(filter, result.Single());\n        }\n\n        [Fact]\n        public void GetFiltersDelegatesToResolver()\n        {\n            // Arrange\n            var context = new ControllerContext();\n            var descriptor = new Mock<ActionDescriptor>().Object;\n            var filter = new Filter(new Object(), FilterScope.Action, null);\n            var provider = new Mock<IFilterProvider>(MockBehavior.Strict);\n            provider.Setup(p => p.GetFilters(context, descriptor)).Returns(new[] { filter });\n\n            Mock<IDependencyResolver> resolver = new Mock<IDependencyResolver>();\n            resolver.Setup(r => r.GetServices(typeof(IFilterProvider))).Returns(new[] { provider.Object });\n\n\n            var collection = new FilterProviderCollection(new IFilterProvider[0], resolver.Object);\n\n            // Act\n            IEnumerable<Filter> result = collection.GetFilters(context, descriptor);\n\n            // Assert\n            Assert.Same(filter, result.Single());\n        }\n\n        [Fact]\n        public void GetFiltersSortsFiltersByOrderFirstThenScope()\n        {\n            // Arrange\n            var context = new ControllerContext();\n            var descriptor = new Mock<ActionDescriptor>().Object;\n            var actionFilter = new Filter(new Object(), FilterScope.Action, null);\n            var controllerFilter = new Filter(new Object(), FilterScope.Controller, null);\n            var globalFilter = new Filter(new Object(), FilterScope.Global, null);\n            var earlyActionFilter = new Filter(new Object(), FilterScope.Action, -100);\n            var lateGlobalFilter = new Filter(new Object(), FilterScope.Global, 100);\n            var provider = new Mock<IFilterProvider>(MockBehavior.Strict);\n            var collection = new FilterProviderCollection(new[] { provider.Object });\n            provider.Setup(p => p.GetFilters(context, descriptor))\n                .Returns(new[] { actionFilter, controllerFilter, globalFilter, earlyActionFilter, lateGlobalFilter });\n\n            // Act\n            Filter[] result = collection.GetFilters(context, descriptor).ToArray();\n\n            // Assert\n            Assert.Equal(5, result.Length);\n            Assert.Same(earlyActionFilter, result[0]);\n            Assert.Same(globalFilter, result[1]);\n            Assert.Same(controllerFilter, result[2]);\n            Assert.Same(actionFilter, result[3]);\n            Assert.Same(lateGlobalFilter, result[4]);\n        }\n\n        [AttributeUsage(AttributeTargets.All, AllowMultiple = false)]\n        private class AllowMultipleFalseAttribute : FilterAttribute\n        {\n        }\n\n        [Fact]\n        public void GetFiltersIncludesLastFilterOnlyWithAttributeUsageAllowMultipleFalse()\n        { // DDB #222988\n            // Arrange\n            var context = new ControllerContext();\n            var descriptor = new Mock<ActionDescriptor>().Object;\n            var globalFilter = new Filter(new AllowMultipleFalseAttribute(), FilterScope.Global, null);\n            var controllerFilter = new Filter(new AllowMultipleFalseAttribute(), FilterScope.Controller, null);\n            var actionFilter = new Filter(new AllowMultipleFalseAttribute(), FilterScope.Action, null);\n            var provider = new Mock<IFilterProvider>(MockBehavior.Strict);\n            var collection = new FilterProviderCollection(new[] { provider.Object });\n            provider.Setup(p => p.GetFilters(context, descriptor))\n                .Returns(new[] { controllerFilter, actionFilter, globalFilter });\n\n            // Act\n            IEnumerable<Filter> result = collection.GetFilters(context, descriptor);\n\n            // Assert\n            Assert.Same(actionFilter, result.Single());\n        }\n\n        [AttributeUsage(AttributeTargets.All, AllowMultiple = true)]\n        private class AllowMultipleTrueAttribute : FilterAttribute\n        {\n        }\n\n        [Fact]\n        public void GetFiltersIncludesAllFiltersWithAttributeUsageAllowMultipleTrue()\n        { // DDB #222988\n            // Arrange\n            var context = new ControllerContext();\n            var descriptor = new Mock<ActionDescriptor>().Object;\n            var globalFilter = new Filter(new AllowMultipleTrueAttribute(), FilterScope.Global, null);\n            var controllerFilter = new Filter(new AllowMultipleTrueAttribute(), FilterScope.Controller, null);\n            var actionFilter = new Filter(new AllowMultipleTrueAttribute(), FilterScope.Action, null);\n            var provider = new Mock<IFilterProvider>(MockBehavior.Strict);\n            var collection = new FilterProviderCollection(new[] { provider.Object });\n            provider.Setup(p => p.GetFilters(context, descriptor))\n                .Returns(new[] { controllerFilter, actionFilter, globalFilter });\n\n            // Act\n            List<Filter> result = collection.GetFilters(context, descriptor).ToList();\n\n            // Assert\n            Assert.Same(globalFilter, result[0]);\n            Assert.Same(controllerFilter, result[1]);\n            Assert.Same(actionFilter, result[2]);\n        }\n\n        private class AllowMultipleCustomFilter : MvcFilter\n        {\n            public AllowMultipleCustomFilter(bool allowMultiple)\n                : base(allowMultiple, -1)\n            {\n            }\n        }\n\n        [Fact]\n        public void GetFiltersIncludesLastFilterOnlyWithCustomFilterAllowMultipleFalse()\n        { // DDB #222988\n            // Arrange\n            var context = new ControllerContext();\n            var descriptor = new Mock<ActionDescriptor>().Object;\n            var globalFilter = new Filter(new AllowMultipleCustomFilter(false), FilterScope.Global, null);\n            var controllerFilter = new Filter(new AllowMultipleCustomFilter(false), FilterScope.Controller, null);\n            var actionFilter = new Filter(new AllowMultipleCustomFilter(false), FilterScope.Action, null);\n            var provider = new Mock<IFilterProvider>(MockBehavior.Strict);\n            var collection = new FilterProviderCollection(new[] { provider.Object });\n            provider.Setup(p => p.GetFilters(context, descriptor))\n                .Returns(new[] { controllerFilter, actionFilter, globalFilter });\n\n            // Act\n            IEnumerable<Filter> result = collection.GetFilters(context, descriptor);\n\n            // Assert\n            Assert.Same(actionFilter, result.Single());\n        }\n\n        [Fact]\n        public void GetFiltersIncludesAllFiltersWithCustomFilterAllowMultipleTrue()\n        { // DDB #222988\n            // Arrange\n            var context = new ControllerContext();\n            var descriptor = new Mock<ActionDescriptor>().Object;\n            var globalFilter = new Filter(new AllowMultipleCustomFilter(true), FilterScope.Global, null);\n            var controllerFilter = new Filter(new AllowMultipleCustomFilter(true), FilterScope.Controller, null);\n            var actionFilter = new Filter(new AllowMultipleCustomFilter(true), FilterScope.Action, null);\n            var provider = new Mock<IFilterProvider>(MockBehavior.Strict);\n            var collection = new FilterProviderCollection(new[] { provider.Object });\n            provider.Setup(p => p.GetFilters(context, descriptor))\n                .Returns(new[] { controllerFilter, actionFilter, globalFilter });\n\n            // Act\n            List<Filter> result = collection.GetFilters(context, descriptor).ToList();\n\n            // Assert\n            Assert.Same(globalFilter, result[0]);\n            Assert.Same(controllerFilter, result[1]);\n            Assert.Same(actionFilter, result[2]);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/FilterProvidersTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class FilterProvidersTest\n    {\n        [Fact]\n        public void DefaultFilterProviders()\n        {\n            // Assert\n            Assert.NotNull(FilterProviders.Providers.Single(fp => fp is GlobalFilterCollection));\n            Assert.NotNull(FilterProviders.Providers.Single(fp => fp is FilterAttributeFilterProvider));\n            Assert.NotNull(FilterProviders.Providers.Single(fp => fp is ControllerInstanceFilterProvider));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/FilterTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class FilterTest\n    {\n        [Fact]\n        public void GuardClause()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => new Filter(null, FilterScope.Action, null),\n                \"instance\"\n                );\n        }\n\n        [Fact]\n        public void FilterDoesNotImplementIOrderedFilter()\n        {\n            // Arrange\n            var filterInstance = new object();\n\n            // Act\n            var filter = new Filter(filterInstance, FilterScope.Action, null);\n\n            // Assert\n            Assert.Same(filterInstance, filter.Instance);\n            Assert.Equal(FilterScope.Action, filter.Scope);\n            Assert.Equal(Filter.DefaultOrder, filter.Order);\n        }\n\n        [Fact]\n        public void FilterImplementsIOrderedFilter()\n        {\n            // Arrange\n            var filterInstance = new Mock<IMvcFilter>();\n            filterInstance.SetupGet(f => f.Order).Returns(42);\n\n            // Act\n            var filter = new Filter(filterInstance.Object, FilterScope.Controller, null);\n\n            // Assert\n            Assert.Same(filterInstance.Object, filter.Instance);\n            Assert.Equal(FilterScope.Controller, filter.Scope);\n            Assert.Equal(42, filter.Order);\n        }\n\n        [Fact]\n        public void ExplicitOrderOverridesIOrderedFilter()\n        {\n            // Arrange\n            var filterInstance = new Mock<IMvcFilter>();\n            filterInstance.SetupGet(f => f.Order).Returns(42);\n\n            // Act\n            var filter = new Filter(filterInstance.Object, FilterScope.Controller, 2112);\n\n            // Assert\n            Assert.Same(filterInstance.Object, filter.Instance);\n            Assert.Equal(FilterScope.Controller, filter.Scope);\n            Assert.Equal(2112, filter.Order);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/FormCollectionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing System.Globalization;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class FormCollectionTest\n    {\n        [Fact]\n        public void ConstructorCopiesProvidedCollection()\n        {\n            // Arrange\n            NameValueCollection nvc = new NameValueCollection()\n            {\n                { \"foo\", \"fooValue\" },\n                { \"bar\", \"barValue\" }\n            };\n\n            // Act\n            FormCollection formCollection = new FormCollection(nvc);\n\n            // Assert\n            Assert.Equal(2, formCollection.Count);\n            Assert.Equal(\"fooValue\", formCollection[\"foo\"]);\n            Assert.Equal(\"barValue\", formCollection[\"bar\"]);\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfCollectionIsNull()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { new FormCollection(null); }, \"collection\");\n        }\n\n        [Fact]\n        public void ConstructorUsesValidatedValuesWhenControllerIsNull()\n        {\n            // Arrange\n            var values = new NameValueCollection()\n            {\n                { \"foo\", \"fooValue\" },\n                { \"bar\", \"barValue\" }\n            };\n\n            // Act\n            var result = new FormCollection(controller: null,\n                                            validatedValuesThunk: () => values,\n                                            unvalidatedValuesThunk: () => { throw new NotImplementedException(); });\n\n            // Assert\n            Assert.Equal(2, result.Count);\n            Assert.Equal(\"fooValue\", result[\"foo\"]);\n            Assert.Equal(\"barValue\", result[\"bar\"]);\n        }\n\n        [Fact]\n        public void ConstructorUsesValidatedValuesWhenControllerValidateRequestIsTrue()\n        {\n            // Arrange\n            var values = new NameValueCollection()\n            {\n                { \"foo\", \"fooValue\" },\n                { \"bar\", \"barValue\" }\n            };\n            var controller = new Mock<ControllerBase>().Object;\n            controller.ValidateRequest = true;\n\n            // Act\n            var result = new FormCollection(controller,\n                                            validatedValuesThunk: () => values,\n                                            unvalidatedValuesThunk: () => { throw new NotImplementedException(); });\n\n            // Assert\n            Assert.Equal(2, result.Count);\n            Assert.Equal(\"fooValue\", result[\"foo\"]);\n            Assert.Equal(\"barValue\", result[\"bar\"]);\n        }\n\n        [Fact]\n        public void ConstructorUsesUnvalidatedValuesWhenControllerValidateRequestIsFalse()\n        {\n            // Arrange\n            var values = new NameValueCollection()\n            {\n                { \"foo\", \"fooValue\" },\n                { \"bar\", \"barValue\" }\n            };\n            var controller = new Mock<ControllerBase>().Object;\n            controller.ValidateRequest = false;\n\n            // Act\n            var result = new FormCollection(controller,\n                                            validatedValuesThunk: () => { throw new NotImplementedException(); },\n                                            unvalidatedValuesThunk: () => values);\n\n            // Assert\n            Assert.Equal(2, result.Count);\n            Assert.Equal(\"fooValue\", result[\"foo\"]);\n            Assert.Equal(\"barValue\", result[\"bar\"]);\n        }\n\n        [Fact]\n        public void CustomBinderBindModelReturnsFormCollection()\n        {\n            // Arrange\n            NameValueCollection nvc = new NameValueCollection() { { \"foo\", \"fooValue\" }, { \"bar\", \"barValue\" } };\n            IModelBinder binder = ModelBinders.Binders.GetBinder(typeof(FormCollection));\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(c => c.HttpContext.Request.Form).Returns(nvc);\n\n            // Act\n            FormCollection formCollection = (FormCollection)binder.BindModel(mockControllerContext.Object, null);\n\n            // Assert\n            Assert.NotNull(formCollection);\n            Assert.Equal(2, formCollection.Count);\n            Assert.Equal(\"fooValue\", nvc[\"foo\"]);\n            Assert.Equal(\"barValue\", nvc[\"bar\"]);\n        }\n\n        [Fact]\n        public void CustomBinderBindModelThrowsIfControllerContextIsNull()\n        {\n            // Arrange\n            IModelBinder binder = ModelBinders.Binders.GetBinder(typeof(FormCollection));\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { binder.BindModel(null, null); }, \"controllerContext\");\n        }\n\n        [Fact]\n        public void GetValue_ThrowsIfNameIsNull()\n        {\n            // Arrange\n            FormCollection formCollection = new FormCollection();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { formCollection.GetValue(null); }, \"name\");\n        }\n\n        [Fact]\n        public void GetValue_KeyDoesNotExist_ReturnsNull()\n        {\n            // Arrange\n            FormCollection formCollection = new FormCollection();\n\n            // Act\n            ValueProviderResult vpResult = formCollection.GetValue(\"\");\n\n            // Assert\n            Assert.Null(vpResult);\n        }\n\n        [Fact]\n        public void GetValue_KeyExists_ReturnsResult()\n        {\n            // Arrange\n            FormCollection formCollection = new FormCollection()\n            {\n                { \"foo\", \"1\" },\n                { \"foo\", \"2\" }\n            };\n\n            // Act\n            ValueProviderResult vpResult = formCollection.GetValue(\"foo\");\n\n            // Assert\n            Assert.NotNull(vpResult);\n            Assert.Equal(new[] { \"1\", \"2\" }, (string[])vpResult.RawValue);\n            Assert.Equal(\"1,2\", vpResult.AttemptedValue);\n            Assert.Equal(CultureInfo.CurrentCulture, vpResult.Culture);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/FormContextTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class FormContextTest\n    {\n        [Fact]\n        public void FieldValidatorsProperty()\n        {\n            // Arrange\n            FormContext context = new FormContext();\n\n            // Act\n            IDictionary<String, FieldValidationMetadata> fieldValidators = context.FieldValidators;\n\n            // Assert\n            Assert.NotNull(fieldValidators);\n            Assert.Empty(fieldValidators);\n        }\n\n        [Fact]\n        public void ReplaceValidationSummaryProperty()\n        {\n            // Arrange\n            FormContext context = new FormContext();\n\n            // Act & Assert\n            MemberHelper.TestBooleanProperty(context, \"ReplaceValidationSummary\", false, false);\n        }\n\n        [Fact]\n        public void GetJsonValidationMetadata_NoValidationSummary()\n        {\n            // Arrange\n            FormContext context = new FormContext() { FormId = \"theFormId\" };\n\n            ModelClientValidationRule rule = new ModelClientValidationRule() { ValidationType = \"ValidationType1\", ErrorMessage = \"Error Message\" };\n            rule.ValidationParameters[\"theParam\"] = new { FirstName = \"John\", LastName = \"Doe\", Age = 32 };\n            FieldValidationMetadata metadata = new FieldValidationMetadata() { FieldName = \"theFieldName\", ValidationMessageId = \"theFieldName_ValidationMessage\" };\n            metadata.ValidationRules.Add(rule);\n            context.FieldValidators[\"theFieldName\"] = metadata;\n\n            // Act\n            string jsonMetadata = context.GetJsonValidationMetadata();\n\n            // Assert\n            string expected = @\"{\"\"Fields\"\":[{\"\"FieldName\"\":\"\"theFieldName\"\",\"\"ReplaceValidationMessageContents\"\":false,\"\"ValidationMessageId\"\":\"\"theFieldName_ValidationMessage\"\",\"\"ValidationRules\"\":[{\"\"ErrorMessage\"\":\"\"Error Message\"\",\"\"ValidationParameters\"\":{\"\"theParam\"\":{\"\"FirstName\"\":\"\"John\"\",\"\"LastName\"\":\"\"Doe\"\",\"\"Age\"\":32}},\"\"ValidationType\"\":\"\"ValidationType1\"\"}]}],\"\"FormId\"\":\"\"theFormId\"\",\"\"ReplaceValidationSummary\"\":false}\";\n            Assert.Equal(expected, jsonMetadata);\n        }\n\n        [Fact]\n        public void GetJsonValidationMetadata_ValidationSummary()\n        {\n            // Arrange\n            FormContext context = new FormContext() { FormId = \"theFormId\", ValidationSummaryId = \"validationSummary\" };\n\n            ModelClientValidationRule rule = new ModelClientValidationRule() { ValidationType = \"ValidationType1\", ErrorMessage = \"Error Message\" };\n            rule.ValidationParameters[\"theParam\"] = new { FirstName = \"John\", LastName = \"Doe\", Age = 32 };\n            FieldValidationMetadata metadata = new FieldValidationMetadata() { FieldName = \"theFieldName\", ValidationMessageId = \"theFieldName_ValidationMessage\" };\n            metadata.ValidationRules.Add(rule);\n            context.FieldValidators[\"theFieldName\"] = metadata;\n\n            // Act\n            string jsonMetadata = context.GetJsonValidationMetadata();\n\n            // Assert\n            string expected = @\"{\"\"Fields\"\":[{\"\"FieldName\"\":\"\"theFieldName\"\",\"\"ReplaceValidationMessageContents\"\":false,\"\"ValidationMessageId\"\":\"\"theFieldName_ValidationMessage\"\",\"\"ValidationRules\"\":[{\"\"ErrorMessage\"\":\"\"Error Message\"\",\"\"ValidationParameters\"\":{\"\"theParam\"\":{\"\"FirstName\"\":\"\"John\"\",\"\"LastName\"\":\"\"Doe\"\",\"\"Age\"\":32}},\"\"ValidationType\"\":\"\"ValidationType1\"\"}]}],\"\"FormId\"\":\"\"theFormId\"\",\"\"ReplaceValidationSummary\"\":false,\"\"ValidationSummaryId\"\":\"\"validationSummary\"\"}\";\n            Assert.Equal(expected, jsonMetadata);\n        }\n\n        [Fact]\n        public void GetValidationMetadataForField_Create_CreatesNewMetadataIfNotFound()\n        {\n            // Arrange\n            FormContext context = new FormContext();\n\n            // Act\n            FieldValidationMetadata result = context.GetValidationMetadataForField(\"fieldName\", true /* createIfNotFound */);\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Equal(\"fieldName\", result.FieldName);\n\n            Assert.Single(context.FieldValidators);\n            Assert.Equal(result, context.FieldValidators[\"fieldName\"]);\n        }\n\n        [Fact]\n        public void GetValidationMetadataForField_NoCreate_ReturnsMetadataIfFound()\n        {\n            // Arrange\n            FormContext context = new FormContext();\n            FieldValidationMetadata metadata = new FieldValidationMetadata();\n            context.FieldValidators[\"fieldName\"] = metadata;\n\n            // Act\n            FieldValidationMetadata result = context.GetValidationMetadataForField(\"fieldName\");\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Equal(metadata, result);\n        }\n\n        [Fact]\n        public void GetValidationMetadataForField_NoCreate_ReturnsNullIfNotFound()\n        {\n            // Arrange\n            FormContext context = new FormContext();\n\n            // Act\n            FieldValidationMetadata result = context.GetValidationMetadataForField(\"fieldName\");\n\n            // Assert\n            Assert.Null(result);\n        }\n\n        [Fact]\n        public void GetValidationMetadataForFieldThrowsIfFieldNameIsEmpty()\n        {\n            // Arrange\n            FormContext context = new FormContext();\n\n            // Act & assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { context.GetValidationMetadataForField(String.Empty); }, \"fieldName\");\n        }\n\n        [Fact]\n        public void GetValidationMetadataForFieldThrowsIfFieldNameIsNull()\n        {\n            // Arrange\n            FormContext context = new FormContext();\n\n            // Act & assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { context.GetValidationMetadataForField(null); }, \"fieldName\");\n        }\n\n        // RenderedField\n\n        [Fact]\n        public void RenderedFieldIsFalseByDefault()\n        {\n            // Arrange\n            var context = new FormContext();\n\n            // Act\n            bool result = context.RenderedField(Guid.NewGuid().ToString());\n\n            // Assert\n            Assert.False(result);\n        }\n\n        [Fact]\n        public void CanSetRenderedFieldToBeTrue()\n        {\n            // Arrange\n            var context = new FormContext();\n            var name = Guid.NewGuid().ToString();\n            context.RenderedField(name, true);\n\n            // Act\n            bool result = context.RenderedField(name);\n\n            // Assert\n            Assert.True(result);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/FormValueProviderFactoryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing System.Globalization;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class FormValueProviderFactoryTest\n    {\n        private static readonly NameValueCollection _backingStore = new NameValueCollection()\n        {\n            { \"foo\", \"fooValue\" }\n        };\n\n        private static readonly NameValueCollection _unvalidatedBackingStore = new NameValueCollection()\n        {\n            { \"foo\", \"fooUnvalidated\" }\n        };\n\n        [Fact]\n        public void GetValueProvider()\n        {\n            // Arrange\n            Mock<MockableUnvalidatedRequestValues> mockUnvalidatedValues = new Mock<MockableUnvalidatedRequestValues>();\n            FormValueProviderFactory factory = new FormValueProviderFactory(_ => mockUnvalidatedValues.Object);\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(o => o.HttpContext.Request.Form).Returns(_backingStore);\n\n            // Act\n            IValueProvider valueProvider = factory.GetValueProvider(mockControllerContext.Object);\n\n            // Assert\n            Assert.Equal(typeof(FormValueProvider), valueProvider.GetType());\n            ValueProviderResult vpResult = valueProvider.GetValue(\"foo\");\n\n            Assert.NotNull(vpResult);\n            Assert.Equal(\"fooValue\", vpResult.AttemptedValue);\n            Assert.Equal(CultureInfo.CurrentCulture, vpResult.Culture);\n        }\n\n        [Fact]\n        public void GetValueProvider_GetValue_SkipValidation()\n        {\n            // Arrange\n            Mock<MockableUnvalidatedRequestValues> mockUnvalidatedValues = new Mock<MockableUnvalidatedRequestValues>();\n            mockUnvalidatedValues.Setup(o => o.Form).Returns(_unvalidatedBackingStore);\n            FormValueProviderFactory factory = new FormValueProviderFactory(_ => mockUnvalidatedValues.Object);\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(o => o.HttpContext.Request.Form).Returns(_backingStore);\n\n            // Act\n            IUnvalidatedValueProvider valueProvider = (IUnvalidatedValueProvider)factory.GetValueProvider(mockControllerContext.Object);\n\n            // Assert\n            Assert.Equal(typeof(FormValueProvider), valueProvider.GetType());\n            ValueProviderResult vpResult = valueProvider.GetValue(\"foo\", skipValidation: true);\n\n            Assert.NotNull(vpResult);\n            Assert.Equal(\"fooUnvalidated\", vpResult.AttemptedValue);\n            Assert.Equal(CultureInfo.CurrentCulture, vpResult.Culture);\n        }\n\n        [Fact]\n        public void GetValueProvider_ThrowsIfControllerContextIsNull()\n        {\n            // Arrange\n            FormValueProviderFactory factory = new FormValueProviderFactory();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { factory.GetValueProvider(null); }, \"controllerContext\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/GlobalFilterCollectionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class GlobalFilterCollectionTest\n    {\n        private GlobalFilterCollection _collection = new GlobalFilterCollection();\n        private object _filterInstance = GetFilterInstance<IActionFilter>();\n\n        public static IEnumerable<object[]> AddRejectsNonFilterInstancesData\n        {\n            get\n            {\n                return new List<object[]>\n                {\n                    new object[] { \"string\", },\n                    new object[] { 42, },\n                    new object[] { new System.Web.Http.AuthorizeAttribute(), },\n                };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"AddRejectsNonFilterInstancesData\")]\n        public void AddRejectsNonFilterInstances(object instance)\n        {\n            // Act + Assert\n            Assert.Throws<InvalidOperationException>(() =>\n            {\n                _collection.Add(instance);\n            }, \"The given filter instance must implement one or more of the following filter interfaces: System.Web.Mvc.IAuthorizationFilter, System.Web.Mvc.IActionFilter, System.Web.Mvc.IResultFilter, System.Web.Mvc.IExceptionFilter, System.Web.Mvc.Filters.IAuthenticationFilter.\");\n        }\n\n        [Fact]\n        public void AddAcceptsFilterInstances()\n        {\n            // Arrange\n            var filters = new object[] {\n                GetFilterInstance<IActionFilter>(),\n                GetFilterInstance<IAuthorizationFilter>(),\n                GetFilterInstance<IResultFilter>(),\n                GetFilterInstance<IExceptionFilter>() \n            }.ToList();\n\n            // Act\n            filters.ForEach(f => _collection.Add(f));\n\n            // Assert\n            Assert.Equal(filters, _collection.Select(i => i.Instance));\n        }\n\n        [Fact]\n        public void AddPlacesFilterInGlobalScope()\n        {\n            // Act\n            _collection.Add(_filterInstance);\n\n            // Assert\n            Filter filter = Assert.Single(_collection);\n            Assert.Same(_filterInstance, filter.Instance);\n            Assert.Equal(FilterScope.Global, filter.Scope);\n            Assert.Equal(-1, filter.Order);\n        }\n\n        [Fact]\n        public void AddWithOrderPlacesFilterInGlobalScope()\n        {\n            // Act\n            _collection.Add(_filterInstance, 42);\n\n            // Assert\n            Filter filter = Assert.Single(_collection);\n            Assert.Same(_filterInstance, filter.Instance);\n            Assert.Equal(FilterScope.Global, filter.Scope);\n            Assert.Equal(42, filter.Order);\n        }\n\n        [Fact]\n        public void ContainsFindsFilterByInstance()\n        {\n            // Arrange\n            _collection.Add(_filterInstance);\n\n            // Act\n            bool result = _collection.Contains(_filterInstance);\n\n            // Assert\n            Assert.True(result);\n        }\n\n        [Fact]\n        public void RemoveDeletesFilterByInstance()\n        {\n            // Arrange\n            _collection.Add(_filterInstance);\n\n            // Act\n            _collection.Remove(_filterInstance);\n\n            // Assert\n            Assert.Empty(_collection);\n        }\n\n        [Fact]\n        public void CollectionIsIFilterProviderWhichReturnsAllFilters()\n        {\n            // Arrange\n            var context = new ControllerContext();\n            var descriptor = new Mock<ActionDescriptor>().Object;\n            _collection.Add(_filterInstance);\n            var provider = (IFilterProvider)_collection;\n\n            // Act\n            IEnumerable<Filter> result = provider.GetFilters(context, descriptor);\n\n            // Assert\n            Filter filter = Assert.Single(result);\n            Assert.Same(_filterInstance, filter.Instance);\n        }\n\n        private static TFilter GetFilterInstance<TFilter>() where TFilter : class\n        {\n            return new Mock<TFilter>().Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/HandleErrorAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Linq;\nusing System.Web.Routing;\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class HandleErrorAttributeTest\n    {\n        [Fact]\n        public void HandleErrorAttributeReturnsUniqueTypeIDs()\n        {\n            // Arrange\n            HandleErrorAttribute attr1 = new HandleErrorAttribute();\n            HandleErrorAttribute attr2 = new HandleErrorAttribute();\n\n            // Assert\n            Assert.NotEqual(attr1.TypeId, attr2.TypeId);\n        }\n\n        [HandleError(View = \"foo\")]\n        [HandleError(View = \"bar\")]\n        private class ClassWithMultipleHandleErrorAttributes\n        {\n        }\n\n        [Fact]\n        public void CanRetrieveMultipleAuthorizeAttributesFromOneClass()\n        {\n            // Arrange\n            ClassWithMultipleHandleErrorAttributes @class = new ClassWithMultipleHandleErrorAttributes();\n\n            // Act\n            IEnumerable<HandleErrorAttribute> attributes = TypeDescriptor.GetAttributes(@class).OfType<HandleErrorAttribute>();\n\n            // Assert\n            Assert.Equal(2, attributes.Count());\n            Assert.Contains(attributes, a => a.View == \"foo\");\n            Assert.Contains(attributes, a => a.View == \"bar\");\n        }\n\n        [Fact]\n        public void ExceptionTypeProperty()\n        {\n            // Arrange\n            HandleErrorAttribute attr = new HandleErrorAttribute();\n\n            // Act\n            Type origType = attr.ExceptionType;\n            attr.ExceptionType = typeof(SystemException);\n            Type newType = attr.ExceptionType;\n\n            // Assert\n            Assert.Equal(typeof(Exception), origType);\n            Assert.Equal(typeof(SystemException), attr.ExceptionType);\n        }\n\n        [Fact]\n        public void ExceptionTypePropertyWithNonExceptionTypeThrows()\n        {\n            // Arrange\n            HandleErrorAttribute attr = new HandleErrorAttribute();\n\n            // Act & Assert\n            Assert.Throws<ArgumentException>(\n                delegate { attr.ExceptionType = typeof(string); },\n                \"The type 'System.String' does not inherit from Exception.\");\n        }\n\n        [Fact]\n        public void ExceptionTypePropertyWithNullValueThrows()\n        {\n            // Arrange\n            HandleErrorAttribute attr = new HandleErrorAttribute();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { attr.ExceptionType = null; }, \"value\");\n        }\n\n        [Fact]\n        public void MasterProperty()\n        {\n            // Arrange\n            HandleErrorAttribute attr = new HandleErrorAttribute();\n\n            // Act & Assert\n            MemberHelper.TestStringProperty(attr, \"Master\", String.Empty);\n        }\n\n        [Fact]\n        public void OnException()\n        {\n            // Arrange\n            HandleErrorAttribute attr = new HandleErrorAttribute()\n            {\n                View = \"SomeView\",\n                Master = \"SomeMaster\",\n                ExceptionType = typeof(ArgumentException)\n            };\n            Exception exception = new ArgumentNullException();\n\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>(MockBehavior.Strict);\n            mockHttpContext.Setup(c => c.IsCustomErrorEnabled).Returns(true);\n            mockHttpContext.Setup(c => c.Session).Returns((HttpSessionStateBase)null);\n            mockHttpContext.Setup(c => c.Response.Clear()).Verifiable();\n            mockHttpContext.SetupSet(c => c.Response.StatusCode = 500).Verifiable();\n            mockHttpContext.SetupSet(c => c.Response.TrySkipIisCustomErrors = true).Verifiable();\n\n            TempDataDictionary tempData = new TempDataDictionary();\n            IViewEngine viewEngine = new Mock<IViewEngine>().Object;\n            Controller controller = new Mock<Controller>().Object;\n            controller.TempData = tempData;\n\n            ExceptionContext context = GetExceptionContext(mockHttpContext.Object, controller, exception);\n\n            // Exception\n            attr.OnException(context);\n\n            // Assert\n            mockHttpContext.Verify();\n            ViewResult viewResult = context.Result as ViewResult;\n            Assert.NotNull(viewResult);\n            Assert.Equal(tempData, viewResult.TempData);\n            Assert.Equal(\"SomeView\", viewResult.ViewName);\n            Assert.Equal(\"SomeMaster\", viewResult.MasterName);\n\n            HandleErrorInfo viewData = viewResult.ViewData.Model as HandleErrorInfo;\n            Assert.NotNull(viewData);\n            Assert.Same(exception, viewData.Exception);\n            Assert.Equal(\"SomeController\", viewData.ControllerName);\n            Assert.Equal(\"SomeAction\", viewData.ActionName);\n        }\n\n        [Fact]\n        public void OnExceptionWithCustomErrorsDisabledDoesNothing()\n        {\n            // Arrange\n            HandleErrorAttribute attr = new HandleErrorAttribute();\n            ActionResult result = new EmptyResult();\n            ExceptionContext context = GetExceptionContext(GetHttpContext(false), null, new Exception());\n            context.Result = result;\n\n            // Exception\n            attr.OnException(context);\n\n            // Assert\n            Assert.Same(result, context.Result);\n        }\n\n        [Fact]\n        public void OnExceptionWithExceptionHandledDoesNothing()\n        {\n            // Arrange\n            HandleErrorAttribute attr = new HandleErrorAttribute();\n            ActionResult result = new EmptyResult();\n            ExceptionContext context = GetExceptionContext(GetHttpContext(), null, new Exception());\n            context.Result = result;\n            context.ExceptionHandled = true;\n\n            // Exception\n            attr.OnException(context);\n\n            // Assert\n            Assert.Same(result, context.Result);\n        }\n\n        [Fact]\n        public void OnExceptionWithNon500ExceptionDoesNothing()\n        {\n            // Arrange\n            HandleErrorAttribute attr = new HandleErrorAttribute();\n            ActionResult result = new EmptyResult();\n            ExceptionContext context = GetExceptionContext(GetHttpContext(), null, new HttpException(404, \"Some Exception\"));\n            context.Result = result;\n\n            // Exception\n            attr.OnException(context);\n\n            // Assert\n            Assert.Same(result, context.Result);\n        }\n\n        [Fact]\n        public void OnExceptionWithNullFilterContextThrows()\n        {\n            // Arrange\n            HandleErrorAttribute attr = new HandleErrorAttribute();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { attr.OnException(null /* filterContext */); }, \"filterContext\");\n        }\n\n        [Fact]\n        public void OnExceptionWithWrongExceptionTypeDoesNothing()\n        {\n            // Arrange\n            HandleErrorAttribute attr = new HandleErrorAttribute() { ExceptionType = typeof(ArgumentException) };\n            ActionResult result = new EmptyResult();\n            ExceptionContext context = GetExceptionContext(GetHttpContext(), null, new InvalidCastException());\n            context.Result = result;\n\n            // Exception\n            attr.OnException(context);\n\n            // Assert\n            Assert.Same(result, context.Result);\n        }\n\n        [Fact]\n        public void ViewProperty()\n        {\n            // Arrange\n            HandleErrorAttribute attr = new HandleErrorAttribute();\n\n            // Act & Assert\n            MemberHelper.TestStringProperty(attr, \"View\", \"Error\", nullAndEmptyReturnValue: \"Error\");\n        }\n\n        private static ExceptionContext GetExceptionContext(HttpContextBase httpContext, ControllerBase controller, Exception exception)\n        {\n            RouteData rd = new RouteData();\n            rd.Values[\"controller\"] = \"SomeController\";\n            rd.Values[\"action\"] = \"SomeAction\";\n\n            Mock<ExceptionContext> mockExceptionContext = new Mock<ExceptionContext>();\n            mockExceptionContext.Setup(c => c.Controller).Returns(controller);\n            mockExceptionContext.Setup(c => c.Exception).Returns(exception);\n            mockExceptionContext.Setup(c => c.RouteData).Returns(rd);\n            mockExceptionContext.Setup(c => c.HttpContext).Returns(httpContext);\n            return mockExceptionContext.Object;\n        }\n\n        private static HttpContextBase GetHttpContext()\n        {\n            return GetHttpContext(true);\n        }\n\n        private static HttpContextBase GetHttpContext(bool isCustomErrorEnabled)\n        {\n            Mock<HttpContextBase> mockContext = new Mock<HttpContextBase>(MockBehavior.Strict);\n            mockContext.Setup(c => c.IsCustomErrorEnabled).Returns(isCustomErrorEnabled);\n            return mockContext.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/HandleErrorInfoTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class HandleErrorInfoTest\n    {\n        [Fact]\n        public void ConstructorSetsProperties()\n        {\n            // Arrange\n            Exception exception = new Exception();\n            string controller = \"SomeController\";\n            string action = \"SomeAction\";\n\n            // Act\n            HandleErrorInfo viewData = new HandleErrorInfo(exception, controller, action);\n\n            // Assert\n            Assert.Same(exception, viewData.Exception);\n            Assert.Equal(controller, viewData.ControllerName);\n            Assert.Equal(action, viewData.ActionName);\n        }\n\n        [Fact]\n        public void ConstructorWithEmptyActionThrows()\n        {\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { new HandleErrorInfo(new Exception(), \"SomeController\", String.Empty); }, \"actionName\");\n        }\n\n        [Fact]\n        public void ConstructorWithEmptyControllerThrows()\n        {\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { new HandleErrorInfo(new Exception(), String.Empty, \"SomeAction\"); }, \"controllerName\");\n        }\n\n        [Fact]\n        public void ConstructorWithNullActionThrows()\n        {\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { new HandleErrorInfo(new Exception(), \"SomeController\", null /* action */); }, \"actionName\");\n        }\n\n        [Fact]\n        public void ConstructorWithNullControllerThrows()\n        {\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { new HandleErrorInfo(new Exception(), null /* controller */, \"SomeAction\"); }, \"controllerName\");\n        }\n\n        [Fact]\n        public void ConstructorWithNullExceptionThrows()\n        {\n            Assert.ThrowsArgumentNull(\n                delegate { new HandleErrorInfo(null /* exception */, \"SomeController\", \"SomeAction\"); }, \"exception\");\n        }\n\n        [Fact]\n        public void ErrorHandlingDoesNotFireIfCalledInChildAction()\n        {\n            // Arrange\n            HandleErrorAttribute attr = new HandleErrorAttribute();\n            Mock<ExceptionContext> context = new Mock<ExceptionContext>();\n            context.Setup(c => c.IsChildAction).Returns(true);\n\n            // Act\n            attr.OnException(context.Object);\n\n            // Assert\n            Assert.IsType<EmptyResult>(context.Object.Result);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/HtmlHelperOfTModelTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class HtmlHelperOfTModelTest\n    {\n        [Fact]\n        public void StronglyTypedViewBagAndStronglyTypedViewDataStayInSync()\n        {\n            // Arrange\n            Mock<IViewDataContainer> viewDataContainer = new Mock<IViewDataContainer>();\n            ViewDataDictionary viewDataDictionary = new ViewDataDictionary() { { \"A\", 1 } };\n            viewDataContainer.Setup(container => container.ViewData).Returns(viewDataDictionary);\n\n            // Act\n            HtmlHelper<object> htmlHelper = new HtmlHelper<object>(new Mock<ViewContext>().Object, viewDataContainer.Object);\n            htmlHelper.ViewData[\"B\"] = 2;\n            htmlHelper.ViewBag.C = 3;\n\n            // Assert\n\n            // Original ViewData should not be modified by redfined ViewData and ViewBag\n            HtmlHelper baseHelper = (HtmlHelper)htmlHelper;\n            Assert.Single(baseHelper.ViewData.Keys);\n            Assert.Equal(1, baseHelper.ViewData[\"A\"]);\n            Assert.Equal(1, baseHelper.ViewBag.A);\n\n            // Redefined ViewData and ViewBag should be in sync\n            Assert.Equal(3, htmlHelper.ViewData.Keys.Count);\n\n            Assert.Equal(1, htmlHelper.ViewData[\"A\"]);\n            Assert.Equal(2, htmlHelper.ViewData[\"B\"]);\n            Assert.Equal(3, htmlHelper.ViewData[\"C\"]);\n\n            Assert.Equal(1, htmlHelper.ViewBag.A);\n            Assert.Equal(2, htmlHelper.ViewBag.B);\n            Assert.Equal(3, htmlHelper.ViewBag.C);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/HtmlHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Web.Routing;\nusing System.Web.WebPages.Scope;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")]\n    public class HtmlHelperTest : IDisposable\n    {\n        public static readonly RouteValueDictionary AttributesDictionary = new RouteValueDictionary(new { baz = \"BazValue\" });\n        public static readonly object AttributesObjectDictionary = new { baz = \"BazObjValue\" };\n        public static readonly object AttributesObjectUnderscoresDictionary = new { foo_baz = \"BazObjValue\" };\n\n        // Constructor\n\n        [Fact]\n        public void ConstructorGuardClauses()\n        {\n            // Arrange\n            var viewContext = new Mock<ViewContext>().Object;\n            var viewDataContainer = MvcHelper.GetViewDataContainer(null);\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => new HtmlHelper(null, viewDataContainer),\n                \"viewContext\"\n                );\n            Assert.ThrowsArgumentNull(\n                () => new HtmlHelper(viewContext, null),\n                \"viewDataContainer\"\n                );\n            Assert.ThrowsArgumentNull(\n                () => new HtmlHelper(viewContext, viewDataContainer, null),\n                \"routeCollection\"\n                );\n        }\n\n        [Fact]\n        public void PropertiesAreSet()\n        {\n            // Arrange\n            var viewContext = new Mock<ViewContext>().Object;\n            var viewData = new ViewDataDictionary<String>(\"The Model\");\n            var routes = new RouteCollection();\n            var mockViewDataContainer = new Mock<IViewDataContainer>();\n            mockViewDataContainer.Setup(vdc => vdc.ViewData).Returns(viewData);\n\n            // Act\n            var htmlHelper = new HtmlHelper(viewContext, mockViewDataContainer.Object, routes);\n\n            // Assert\n            Assert.Equal(viewContext, htmlHelper.ViewContext);\n            Assert.Equal(mockViewDataContainer.Object, htmlHelper.ViewDataContainer);\n            Assert.Equal(routes, htmlHelper.RouteCollection);\n            Assert.Equal(viewData.Model, htmlHelper.ViewData.Model);\n        }\n\n        [Fact]\n        public void DefaultRouteCollectionIsRouteTableRoutes()\n        {\n            // Arrange\n            var viewContext = new Mock<ViewContext>().Object;\n            var viewDataContainer = new Mock<IViewDataContainer>().Object;\n\n            // Act\n            var htmlHelper = new HtmlHelper(viewContext, viewDataContainer);\n\n            // Assert\n            Assert.Equal(RouteTable.Routes, htmlHelper.RouteCollection);\n        }\n\n        // AnonymousObjectToHtmlAttributes tests\n\n        [Fact]\n        public void ConvertsUnderscoresInNamesToDashes()\n        {\n            // Arrange\n            var attributes = new { foo = \"Bar\", baz_bif = \"pow_wow\" };\n\n            // Act\n            RouteValueDictionary result = HtmlHelper.AnonymousObjectToHtmlAttributes(attributes);\n\n            // Assert\n            Assert.Equal(2, result.Count);\n            Assert.Equal(\"Bar\", result[\"foo\"]);\n            Assert.Equal(\"pow_wow\", result[\"baz-bif\"]);\n        }\n\n        // AttributeEncode\n\n        [Fact]\n        public void AttributeEncodeObject()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            string encodedHtml = htmlHelper.AttributeEncode((object)@\"<\"\">\");\n\n            // Assert\n            Assert.Equal(\"&lt;&quot;>\", encodedHtml);\n        }\n\n        [Fact]\n        public void AttributeEncodeObjectNull()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            string encodedHtml = htmlHelper.AttributeEncode((object)null);\n\n            // Assert\n            Assert.Equal(\"\", encodedHtml);\n        }\n\n        [Fact]\n        public void AttributeEncodeString()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            string encodedHtml = htmlHelper.AttributeEncode(@\"<\"\">\");\n\n            // Assert\n            Assert.Equal(\"&lt;&quot;>\", encodedHtml);\n        }\n\n        [Fact]\n        public void AttributeEncodeStringNull()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            string encodedHtml = htmlHelper.AttributeEncode((string)null);\n\n            // Assert\n            Assert.Equal(\"\", encodedHtml);\n        }\n\n        // EnableClientValidation\n\n        [Fact]\n        public void EnableClientValidation()\n        {\n            // Arrange\n            var mockViewContext = new Mock<ViewContext>();\n            var viewDataContainer = new Mock<IViewDataContainer>().Object;\n            var htmlHelper = new HtmlHelper(mockViewContext.Object, viewDataContainer);\n\n            // Act\n            htmlHelper.EnableClientValidation();\n\n            // Act & assert\n            mockViewContext.VerifySet(vc => vc.ClientValidationEnabled = true);\n        }\n\n        // EnableUnobtrusiveJavaScript\n\n        [Fact]\n        public void EnableUnobtrusiveJavaScript()\n        {\n            // Arrange\n            var mockViewContext = new Mock<ViewContext>();\n            var viewDataContainer = new Mock<IViewDataContainer>().Object;\n            var htmlHelper = new HtmlHelper(mockViewContext.Object, viewDataContainer);\n\n            // Act\n            htmlHelper.EnableUnobtrusiveJavaScript();\n\n            // Act & assert\n            mockViewContext.VerifySet(vc => vc.UnobtrusiveJavaScriptEnabled = true);\n        }\n\n        // Encode\n\n        [Fact]\n        public void EncodeObject()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            string encodedHtml = htmlHelper.Encode((object)\"<br />\");\n\n            // Assert\n            Assert.Equal(\"&lt;br /&gt;\", encodedHtml);\n        }\n\n        [Fact]\n        public void EncodeObjectNull()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            string encodedHtml = htmlHelper.Encode((object)null);\n\n            // Assert\n            Assert.Equal(\"\", encodedHtml);\n        }\n\n        [Fact]\n        public void EncodeString()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            string encodedHtml = htmlHelper.Encode(\"<br />\");\n\n            // Assert\n            Assert.Equal(\"&lt;br /&gt;\", encodedHtml);\n        }\n\n        [Fact]\n        public void EncodeStringNull()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();\n\n            // Act\n            string encodedHtml = htmlHelper.Encode((string)null);\n\n            // Assert\n            Assert.Equal(\"\", encodedHtml);\n        }\n\n        // GetModelStateValue\n\n        [Fact]\n        public void GetModelStateValueReturnsNullIfModelStateHasNoValue()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary();\n            vdd.ModelState.AddModelError(\"foo\", \"some error text\"); // didn't call SetModelValue()\n\n            HtmlHelper helper = new HtmlHelper(new ViewContext(), new SimpleViewDataContainer(vdd));\n\n            // Act\n            object retVal = helper.GetModelStateValue(\"foo\", typeof(object));\n\n            // Assert\n            Assert.Null(retVal);\n        }\n\n        [Fact]\n        public void GetModelStateValueReturnsNullIfModelStateKeyNotPresent()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary();\n            HtmlHelper helper = new HtmlHelper(new ViewContext(), new SimpleViewDataContainer(vdd));\n\n            // Act\n            object retVal = helper.GetModelStateValue(\"key_not_present\", typeof(object));\n\n            // Assert\n            Assert.Null(retVal);\n        }\n\n        // GenerateIdFromName\n\n        [Fact]\n        public void GenerateIdFromNameTests()\n        {\n            // Guard clauses\n            Assert.ThrowsArgumentNull(\n                () => HtmlHelper.GenerateIdFromName(null),\n                \"name\"\n                );\n            Assert.ThrowsArgumentNull(\n                () => HtmlHelper.GenerateIdFromName(null, \"?\"),\n                \"name\"\n                );\n            Assert.ThrowsArgumentNull(\n                () => HtmlHelper.GenerateIdFromName(\"?\", null),\n                \"idAttributeDotReplacement\"\n                );\n\n            // Default replacement tests\n            Assert.Equal(\"\", HtmlHelper.GenerateIdFromName(\"\"));\n            Assert.Equal(\"Foo\", HtmlHelper.GenerateIdFromName(\"Foo\"));\n            Assert.Equal(\"Foo_Bar\", HtmlHelper.GenerateIdFromName(\"Foo.Bar\"));\n            Assert.Equal(\"Foo_Bar_Baz\", HtmlHelper.GenerateIdFromName(\"Foo.Bar.Baz\"));\n            Assert.Null(HtmlHelper.GenerateIdFromName(\"1Foo\"));\n            Assert.Equal(\"Foo_0_\", HtmlHelper.GenerateIdFromName(\"Foo[0]\"));\n\n            // Custom replacement tests\n            Assert.Equal(\"\", HtmlHelper.GenerateIdFromName(\"\", \"?\"));\n            Assert.Equal(\"Foo\", HtmlHelper.GenerateIdFromName(\"Foo\", \"?\"));\n            Assert.Equal(\"Foo?Bar\", HtmlHelper.GenerateIdFromName(\"Foo.Bar\", \"?\"));\n            Assert.Equal(\"Foo?Bar?Baz\", HtmlHelper.GenerateIdFromName(\"Foo.Bar.Baz\", \"?\"));\n            Assert.Equal(\"FooBarBaz\", HtmlHelper.GenerateIdFromName(\"Foo.Bar.Baz\", \"\"));\n            Assert.Null(HtmlHelper.GenerateIdFromName(\"1Foo\", \"?\"));\n            Assert.Equal(\"Foo?0?\", HtmlHelper.GenerateIdFromName(\"Foo[0]\", \"?\"));\n        }\n\n        // RenderPartialInternal\n\n        [Fact]\n        public void NullPartialViewNameThrows()\n        {\n            // Arrange\n            TestableHtmlHelper helper = TestableHtmlHelper.Create();\n            ViewDataDictionary viewData = new ViewDataDictionary();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => helper.RenderPartialInternal(null /* partialViewName */, null /* viewData */, null /* model */, TextWriter.Null),\n                \"partialViewName\");\n        }\n\n        [Fact]\n        public void EmptyPartialViewNameThrows()\n        {\n            // Arrange\n            TestableHtmlHelper helper = TestableHtmlHelper.Create();\n            ViewDataDictionary viewData = new ViewDataDictionary();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => helper.RenderPartialInternal(String.Empty /* partialViewName */, null /* viewData */, null /* model */, TextWriter.Null),\n                \"partialViewName\");\n        }\n\n        [Fact]\n        public void EngineLookupSuccessCallsRender()\n        {\n            // Arrange\n            TestableHtmlHelper helper = TestableHtmlHelper.Create();\n            TextWriter writer = helper.ViewContext.Writer;\n            Mock<IViewEngine> engine = new Mock<IViewEngine>(MockBehavior.Strict);\n            Mock<IView> view = new Mock<IView>(MockBehavior.Strict);\n            engine\n                .Setup(e => e.FindPartialView(It.IsAny<ControllerContext>(), \"partial-view\", It.IsAny<bool>()))\n                .Returns(new ViewEngineResult(view.Object, engine.Object))\n                .Verifiable();\n            view\n                .Setup(v => v.Render(It.IsAny<ViewContext>(), writer))\n                .Callback<ViewContext, TextWriter>(\n                    (viewContext, _) =>\n                    {\n                        Assert.Same(helper.ViewContext.View, viewContext.View);\n                        Assert.Same(helper.ViewContext.TempData, viewContext.TempData);\n                    })\n                .Verifiable();\n\n            // Act\n            helper.RenderPartialInternal(\"partial-view\", null /* viewData */, null /* model */, writer, engine.Object);\n\n            // Assert\n            engine.Verify();\n            view.Verify();\n        }\n\n        [Fact]\n        public void EngineLookupFailureThrows()\n        {\n            // Arrange\n            TestableHtmlHelper helper = TestableHtmlHelper.Create();\n            Mock<IViewEngine> engine = new Mock<IViewEngine>(MockBehavior.Strict);\n            engine\n                .Setup(e => e.FindPartialView(It.IsAny<ControllerContext>(), \"partial-view\", It.IsAny<bool>()))\n                .Returns(new ViewEngineResult(new[] { \"location1\", \"location2\" }))\n                .Verifiable();\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => helper.RenderPartialInternal(\"partial-view\", null /* viewData */, null /* model */, TextWriter.Null, engine.Object),\n                \"The partial view 'partial-view' was not found or no view engine supports the searched locations. The following locations were searched:\" + Environment.NewLine\n              + \"location1\" + Environment.NewLine\n              + \"location2\");\n\n            engine.Verify();\n        }\n\n        [Fact]\n        public void RenderPartialInternalWithNullModelAndNullViewData()\n        {\n            // Arrange\n            object model = new object();\n            TestableHtmlHelper helper = TestableHtmlHelper.Create();\n            helper.ViewData[\"Foo\"] = \"Bar\";\n            helper.ViewData.Model = model;\n            Mock<IViewEngine> engine = new Mock<IViewEngine>(MockBehavior.Strict);\n            Mock<IView> view = new Mock<IView>(MockBehavior.Strict);\n            engine\n                .Setup(e => e.FindPartialView(It.IsAny<ControllerContext>(), \"partial-view\", It.IsAny<bool>()))\n                .Returns(new ViewEngineResult(view.Object, engine.Object))\n                .Verifiable();\n            view\n                .Setup(v => v.Render(It.IsAny<ViewContext>(), TextWriter.Null))\n                .Callback<ViewContext, TextWriter>(\n                    (viewContext, writer) =>\n                    {\n                        Assert.NotSame(helper.ViewData, viewContext.ViewData); // New view data instance\n                        Assert.Equal(\"Bar\", viewContext.ViewData[\"Foo\"]); // Copy of the existing view data\n                        Assert.Same(model, viewContext.ViewData.Model); // Keep existing model\n                    })\n                .Verifiable();\n\n            // Act\n            helper.RenderPartialInternal(\"partial-view\", null /* viewData */, null /* model */, TextWriter.Null, engine.Object);\n\n            // Assert\n            engine.Verify();\n            view.Verify();\n        }\n\n        [Fact]\n        public void RenderPartialInternalWithNonNullModelAndNullViewData()\n        {\n            // Arrange\n            object model = new object();\n            object newModel = new object();\n            TestableHtmlHelper helper = TestableHtmlHelper.Create();\n            helper.ViewData[\"Foo\"] = \"Bar\";\n            helper.ViewData.Model = model;\n            Mock<IViewEngine> engine = new Mock<IViewEngine>(MockBehavior.Strict);\n            Mock<IView> view = new Mock<IView>(MockBehavior.Strict);\n            engine\n                .Setup(e => e.FindPartialView(It.IsAny<ControllerContext>(), \"partial-view\", It.IsAny<bool>()))\n                .Returns(new ViewEngineResult(view.Object, engine.Object))\n                .Verifiable();\n            view\n                .Setup(v => v.Render(It.IsAny<ViewContext>(), TextWriter.Null))\n                .Callback<ViewContext, TextWriter>(\n                    (viewContext, writer) =>\n                    {\n                        Assert.NotSame(helper.ViewData, viewContext.ViewData); // New view data instance\n                        Assert.Empty(viewContext.ViewData); // Empty (not copied)\n                        Assert.Same(newModel, viewContext.ViewData.Model); // New model\n                    })\n                .Verifiable();\n\n            // Act\n            helper.RenderPartialInternal(\"partial-view\", null /* viewData */, newModel, TextWriter.Null, engine.Object);\n\n            // Assert\n            engine.Verify();\n            view.Verify();\n        }\n\n        [Fact]\n        public void RenderPartialInternalWithNullModelAndNonNullViewData()\n        {\n            // Arrange\n            object model = new object();\n            object vddModel = new object();\n            ViewDataDictionary vdd = new ViewDataDictionary();\n            vdd[\"Baz\"] = \"Biff\";\n            vdd.Model = vddModel;\n            TestableHtmlHelper helper = TestableHtmlHelper.Create();\n            helper.ViewData[\"Foo\"] = \"Bar\";\n            helper.ViewData.Model = model;\n            Mock<IViewEngine> engine = new Mock<IViewEngine>(MockBehavior.Strict);\n            Mock<IView> view = new Mock<IView>(MockBehavior.Strict);\n            engine\n                .Setup(e => e.FindPartialView(It.IsAny<ControllerContext>(), \"partial-view\", It.IsAny<bool>()))\n                .Returns(new ViewEngineResult(view.Object, engine.Object))\n                .Verifiable();\n            view\n                .Setup(v => v.Render(It.IsAny<ViewContext>(), TextWriter.Null))\n                .Callback<ViewContext, TextWriter>(\n                    (viewContext, writer) =>\n                    {\n                        Assert.NotSame(helper.ViewData, viewContext.ViewData); // New view data instance\n                        Assert.Single(viewContext.ViewData); // Copy of the passed view data, not original view data\n                        Assert.Equal(\"Biff\", viewContext.ViewData[\"Baz\"]);\n                        Assert.Same(vddModel, viewContext.ViewData.Model); // Keep model from passed view data, not original view data\n                    })\n                .Verifiable();\n\n            // Act\n            helper.RenderPartialInternal(\"partial-view\", vdd, null /* model */, TextWriter.Null, engine.Object);\n\n            // Assert\n            engine.Verify();\n            view.Verify();\n        }\n\n        [Fact]\n        public void RenderPartialInternalWithNonNullModelAndNonNullViewData()\n        {\n            // Arrange\n            object model = new object();\n            object vddModel = new object();\n            object newModel = new object();\n            ViewDataDictionary vdd = new ViewDataDictionary();\n            vdd[\"Baz\"] = \"Biff\";\n            vdd.Model = vddModel;\n            TestableHtmlHelper helper = TestableHtmlHelper.Create();\n            helper.ViewData[\"Foo\"] = \"Bar\";\n            helper.ViewData.Model = model;\n            Mock<IViewEngine> engine = new Mock<IViewEngine>(MockBehavior.Strict);\n            Mock<IView> view = new Mock<IView>(MockBehavior.Strict);\n            engine\n                .Setup(e => e.FindPartialView(It.IsAny<ControllerContext>(), \"partial-view\", It.IsAny<bool>()))\n                .Returns(new ViewEngineResult(view.Object, engine.Object))\n                .Verifiable();\n            view\n                .Setup(v => v.Render(It.IsAny<ViewContext>(), TextWriter.Null))\n                .Callback<ViewContext, TextWriter>(\n                    (viewContext, writer) =>\n                    {\n                        Assert.NotSame(helper.ViewData, viewContext.ViewData); // New view data instance\n                        Assert.Single(viewContext.ViewData); // Copy of the passed view data, not original view data\n                        Assert.Equal(\"Biff\", viewContext.ViewData[\"Baz\"]);\n                        Assert.Same(newModel, viewContext.ViewData.Model); // New model\n                    })\n                .Verifiable();\n\n            // Act\n            helper.RenderPartialInternal(\"partial-view\", vdd, newModel, TextWriter.Null, engine.Object);\n\n            // Assert\n            engine.Verify();\n            view.Verify();\n        }\n\n        // HttpMethodOverride\n\n        [Fact]\n        public void HttpMethodOverrideGuardClauses()\n        {\n            // Arrange\n            var viewContext = new Mock<ViewContext>().Object;\n            var viewDataContainer = MvcHelper.GetViewDataContainer(null);\n            var htmlHelper = new HtmlHelper(viewContext, viewDataContainer);\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => htmlHelper.HttpMethodOverride(null),\n                \"httpMethod\"\n                );\n            Assert.Throws<ArgumentException>(\n                () => htmlHelper.HttpMethodOverride((HttpVerbs)10000),\n                \"The specified HttpVerbs value is not supported. The supported values are Delete, Head, Put, Options, and Patch.\" + Environment.NewLine\n              + \"Parameter name: httpVerb\"\n                );\n            Assert.Throws<ArgumentException>(\n                () => htmlHelper.HttpMethodOverride(HttpVerbs.Get),\n                \"The specified HttpVerbs value is not supported. The supported values are Delete, Head, Put, Options, and Patch.\" + Environment.NewLine\n              + \"Parameter name: httpVerb\"\n                );\n            Assert.Throws<ArgumentException>(\n                () => htmlHelper.HttpMethodOverride(HttpVerbs.Post),\n                \"The specified HttpVerbs value is not supported. The supported values are Delete, Head, Put, Options, and Patch.\" + Environment.NewLine\n              + \"Parameter name: httpVerb\"\n                );\n            Assert.Throws<ArgumentException>(\n                () => htmlHelper.HttpMethodOverride(\"gEt\"),\n                \"The GET and POST HTTP methods are not supported.\" + Environment.NewLine\n              + \"Parameter name: httpMethod\"\n                );\n            Assert.Throws<ArgumentException>(\n                () => htmlHelper.HttpMethodOverride(\"pOsT\"),\n                \"The GET and POST HTTP methods are not supported.\" + Environment.NewLine\n              + \"Parameter name: httpMethod\"\n                );\n        }\n\n        [Fact]\n        public void HttpMethodOverrideWithMethodRendersHiddenField()\n        {\n            // Arrange\n            var viewContext = new Mock<ViewContext>().Object;\n            var viewDataContainer = MvcHelper.GetViewDataContainer(null);\n            var htmlHelper = new HtmlHelper(viewContext, viewDataContainer);\n\n            // Act\n            MvcHtmlString hiddenField = htmlHelper.HttpMethodOverride(\"PUT\");\n\n            // Assert\n            Assert.Equal(@\"<input name=\"\"X-HTTP-Method-Override\"\" type=\"\"hidden\"\" value=\"\"PUT\"\" />\", hiddenField.ToHtmlString());\n        }\n\n        [Fact]\n        public void HttpMethodOverrideWithVerbRendersHiddenField()\n        {\n            // Arrange\n            var viewContext = new Mock<ViewContext>().Object;\n            var viewDataContainer = MvcHelper.GetViewDataContainer(null);\n            var htmlHelper = new HtmlHelper(viewContext, viewDataContainer);\n\n            // Act\n            MvcHtmlString hiddenField = htmlHelper.HttpMethodOverride(HttpVerbs.Delete);\n\n            // Assert\n            Assert.Equal(@\"<input name=\"\"X-HTTP-Method-Override\"\" type=\"\"hidden\"\" value=\"\"DELETE\"\" />\", hiddenField.ToHtmlString());\n        }\n\n        [Fact]\n        public void ViewBagProperty_ReflectsViewData()\n        {\n            // Arrange\n            Mock<IViewDataContainer> viewDataContainer = new Mock<IViewDataContainer>();\n            ViewDataDictionary viewDataDictionary = new ViewDataDictionary() { { \"A\", 1 } };\n            viewDataContainer.Setup(container => container.ViewData).Returns(viewDataDictionary);\n\n            // Act\n            HtmlHelper htmlHelper = new HtmlHelper(new Mock<ViewContext>().Object, viewDataContainer.Object);\n\n            // Assert\n            Assert.Equal(1, htmlHelper.ViewBag.A);\n        }\n\n        [Fact]\n        public void ViewBagProperty_ReflectsNewViewDataContainerInstance()\n        {\n            // Arrange\n            ViewDataDictionary viewDataDictionary = new ViewDataDictionary() { { \"A\", 1 } };\n            Mock<IViewDataContainer> viewDataContainer = new Mock<IViewDataContainer>();\n            viewDataContainer.Setup(container => container.ViewData).Returns(viewDataDictionary);\n\n            ViewDataDictionary otherViewDataDictionary = new ViewDataDictionary() { { \"A\", 2 } };\n            Mock<IViewDataContainer> otherViewDataContainer = new Mock<IViewDataContainer>();\n            otherViewDataContainer.Setup(container => container.ViewData).Returns(otherViewDataDictionary);\n\n            HtmlHelper htmlHelper = new HtmlHelper(new Mock<ViewContext>().Object, viewDataContainer.Object, new RouteCollection());\n\n            // Act\n            htmlHelper.ViewDataContainer = otherViewDataContainer.Object;\n\n            // Assert\n            Assert.Equal(2, htmlHelper.ViewBag.A);\n        }\n\n        [Fact]\n        public void ViewBag_PropagatesChangesToViewData()\n        {\n            // Arrange\n            ViewDataDictionary viewDataDictionary = new ViewDataDictionary() { { \"A\", 1 } };\n            Mock<IViewDataContainer> viewDataContainer = new Mock<IViewDataContainer>();\n            viewDataContainer.Setup(container => container.ViewData).Returns(viewDataDictionary);\n\n            HtmlHelper htmlHelper = new HtmlHelper(new Mock<ViewContext>().Object, viewDataContainer.Object, new RouteCollection());\n\n            // Act\n            htmlHelper.ViewBag.A = \"foo\";\n            htmlHelper.ViewBag.B = 2;\n\n            // Assert\n            Assert.Equal(\"foo\", htmlHelper.ViewData[\"A\"]);\n            Assert.Equal(2, htmlHelper.ViewData[\"B\"]);\n        }\n\n        // Unobtrusive validation attributes\n\n        [Fact]\n        public void GetUnobtrusiveValidationAttributesReturnsEmptySetWhenClientValidationIsNotEnabled()\n        {\n            // Arrange\n            var formContext = new FormContext();\n            formContext.RenderedField(\"foobar\", true);\n            var viewContext = new Mock<ViewContext>();\n            viewContext.SetupGet(vc => vc.FormContext).Returns(formContext);\n            var viewDataContainer = MvcHelper.GetViewDataContainer(new ViewDataDictionary());\n            var htmlHelper = new HtmlHelper(viewContext.Object, viewDataContainer);\n\n            // Act\n            IDictionary<string, object> result = htmlHelper.GetUnobtrusiveValidationAttributes(\"foobar\");\n\n            // Assert\n            Assert.Empty(result);\n        }\n\n        [Fact]\n        public void GetUnobtrusiveValidationAttributesReturnsEmptySetWhenUnobtrusiveJavaScriptIsNotEnabled()\n        {\n            // Arrange\n            var formContext = new FormContext();\n            formContext.RenderedField(\"foobar\", true);\n            var viewContext = new Mock<ViewContext>();\n            viewContext.SetupGet(vc => vc.FormContext).Returns(formContext);\n            viewContext.SetupGet(vc => vc.ClientValidationEnabled).Returns(true);\n            var viewDataContainer = MvcHelper.GetViewDataContainer(new ViewDataDictionary());\n            var htmlHelper = new HtmlHelper(viewContext.Object, viewDataContainer);\n\n            // Act\n            IDictionary<string, object> result = htmlHelper.GetUnobtrusiveValidationAttributes(\"foobar\");\n\n            // Assert\n            Assert.Empty(result);\n        }\n\n        [Fact]\n        public void GetUnobtrusiveValidationAttributesReturnsEmptySetWhenFieldHasAlreadyBeenRendered()\n        {\n            // Arrange\n            var formContext = new FormContext();\n            formContext.RenderedField(\"foobar\", true);\n            var viewContext = new Mock<ViewContext>();\n            viewContext.SetupGet(vc => vc.FormContext).Returns(formContext);\n            viewContext.SetupGet(vc => vc.ClientValidationEnabled).Returns(true);\n            viewContext.SetupGet(vc => vc.UnobtrusiveJavaScriptEnabled).Returns(true);\n            var viewDataContainer = MvcHelper.GetViewDataContainer(new ViewDataDictionary());\n            var htmlHelper = new HtmlHelper(viewContext.Object, viewDataContainer);\n\n            // Act\n            IDictionary<string, object> result = htmlHelper.GetUnobtrusiveValidationAttributes(\"foobar\");\n\n            // Assert\n            Assert.Empty(result);\n        }\n\n        [Fact]\n        public void GetUnobtrusiveValidationAttributesReturnsEmptySetAndSetsFieldAsRenderedForFieldWithNoClientRules()\n        {\n            // Arrange\n            var formContext = new FormContext();\n            var viewContext = new Mock<ViewContext>();\n            viewContext.SetupGet(vc => vc.FormContext).Returns(formContext);\n            viewContext.SetupGet(vc => vc.ClientValidationEnabled).Returns(true);\n            viewContext.SetupGet(vc => vc.UnobtrusiveJavaScriptEnabled).Returns(true);\n            var viewDataContainer = MvcHelper.GetViewDataContainer(new ViewDataDictionary());\n            var htmlHelper = new HtmlHelper(viewContext.Object, viewDataContainer);\n            htmlHelper.ClientValidationRuleFactory = delegate { return Enumerable.Empty<ModelClientValidationRule>(); };\n\n            // Act\n            IDictionary<string, object> result = htmlHelper.GetUnobtrusiveValidationAttributes(\"foobar\");\n\n            // Assert\n            Assert.Empty(result);\n            Assert.True(formContext.RenderedField(\"foobar\"));\n        }\n\n        [Fact]\n        public void GetUnobtrusiveValidationAttributesIncludesDataValTrueWithNonEmptyClientRuleList()\n        {\n            // Arrange\n            var formContext = new FormContext();\n            var viewContext = new Mock<ViewContext>();\n            viewContext.SetupGet(vc => vc.FormContext).Returns(formContext);\n            viewContext.SetupGet(vc => vc.ClientValidationEnabled).Returns(true);\n            viewContext.SetupGet(vc => vc.UnobtrusiveJavaScriptEnabled).Returns(true);\n            var viewDataContainer = MvcHelper.GetViewDataContainer(new ViewDataDictionary());\n            var htmlHelper = new HtmlHelper(viewContext.Object, viewDataContainer);\n            htmlHelper.ClientValidationRuleFactory = delegate { return new[] { new ModelClientValidationRule { ValidationType = \"type\" } }; };\n\n            // Act\n            IDictionary<string, object> result = htmlHelper.GetUnobtrusiveValidationAttributes(\"foobar\");\n\n            // Assert\n            Assert.Equal(\"true\", result[\"data-val\"]);\n        }\n\n        [Fact]\n        public void GetUnobtrusiveValidationAttributesWithEmptyMessage()\n        {\n            // Arrange\n            var formContext = new FormContext();\n            var viewContext = new Mock<ViewContext>();\n            viewContext.SetupGet(vc => vc.FormContext).Returns(formContext);\n            viewContext.SetupGet(vc => vc.ClientValidationEnabled).Returns(true);\n            viewContext.SetupGet(vc => vc.UnobtrusiveJavaScriptEnabled).Returns(true);\n            var viewDataContainer = MvcHelper.GetViewDataContainer(new ViewDataDictionary());\n            var htmlHelper = new HtmlHelper(viewContext.Object, viewDataContainer);\n            htmlHelper.ClientValidationRuleFactory = delegate { return new[] { new ModelClientValidationRule { ValidationType = \"type\" } }; };\n\n            // Act\n            IDictionary<string, object> result = htmlHelper.GetUnobtrusiveValidationAttributes(\"foobar\");\n\n            // Assert\n            Assert.Equal(\"\", result[\"data-val-type\"]);\n        }\n\n        [Fact]\n        public void GetUnobtrusiveValidationAttributesMessageIsNotHtmlEncoded()\n        {\n            // Arrange\n            var formContext = new FormContext();\n            var viewContext = new Mock<ViewContext>();\n            viewContext.SetupGet(vc => vc.FormContext).Returns(formContext);\n            viewContext.SetupGet(vc => vc.ClientValidationEnabled).Returns(true);\n            viewContext.SetupGet(vc => vc.UnobtrusiveJavaScriptEnabled).Returns(true);\n            var viewDataContainer = MvcHelper.GetViewDataContainer(new ViewDataDictionary());\n            var htmlHelper = new HtmlHelper(viewContext.Object, viewDataContainer);\n            htmlHelper.ClientValidationRuleFactory = delegate { return new[] { new ModelClientValidationRule { ValidationType = \"type\", ErrorMessage = \"<script>alert('xss')</script>\" } }; };\n\n            // Act\n            IDictionary<string, object> result = htmlHelper.GetUnobtrusiveValidationAttributes(\"foobar\");\n\n            // Assert\n            Assert.Equal(\"<script>alert('xss')</script>\", result[\"data-val-type\"]);\n        }\n\n        [Fact]\n        public void GetUnobtrusiveValidationAttributesWithMessageAndParameters()\n        {\n            // Arrange\n            var formContext = new FormContext();\n            var viewContext = new Mock<ViewContext>();\n            viewContext.SetupGet(vc => vc.FormContext).Returns(formContext);\n            viewContext.SetupGet(vc => vc.ClientValidationEnabled).Returns(true);\n            viewContext.SetupGet(vc => vc.UnobtrusiveJavaScriptEnabled).Returns(true);\n            var viewDataContainer = MvcHelper.GetViewDataContainer(new ViewDataDictionary());\n            var htmlHelper = new HtmlHelper(viewContext.Object, viewDataContainer);\n            htmlHelper.ClientValidationRuleFactory = delegate\n            {\n                ModelClientValidationRule rule = new ModelClientValidationRule { ValidationType = \"type\", ErrorMessage = \"error\" };\n                rule.ValidationParameters[\"foo\"] = \"bar\";\n                rule.ValidationParameters[\"baz\"] = \"biff\";\n                return new[] { rule };\n            };\n\n            // Act\n            IDictionary<string, object> result = htmlHelper.GetUnobtrusiveValidationAttributes(\"foobar\");\n\n            // Assert\n            Assert.Equal(\"error\", result[\"data-val-type\"]);\n            Assert.Equal(\"bar\", result[\"data-val-type-foo\"]);\n            Assert.Equal(\"biff\", result[\"data-val-type-baz\"]);\n        }\n\n        [Fact]\n        public void GetUnobtrusiveValidationAttributesWithTwoClientRules()\n        {\n            // Arrange\n            var formContext = new FormContext();\n            var viewContext = new Mock<ViewContext>();\n            viewContext.SetupGet(vc => vc.FormContext).Returns(formContext);\n            viewContext.SetupGet(vc => vc.ClientValidationEnabled).Returns(true);\n            viewContext.SetupGet(vc => vc.UnobtrusiveJavaScriptEnabled).Returns(true);\n            var viewDataContainer = MvcHelper.GetViewDataContainer(new ViewDataDictionary());\n            var htmlHelper = new HtmlHelper(viewContext.Object, viewDataContainer);\n            htmlHelper.ClientValidationRuleFactory = delegate\n            {\n                ModelClientValidationRule rule1 = new ModelClientValidationRule { ValidationType = \"type\", ErrorMessage = \"error\" };\n                rule1.ValidationParameters[\"foo\"] = \"bar\";\n                rule1.ValidationParameters[\"baz\"] = \"biff\";\n                ModelClientValidationRule rule2 = new ModelClientValidationRule { ValidationType = \"othertype\", ErrorMessage = \"othererror\" };\n                rule2.ValidationParameters[\"true3\"] = \"false4\";\n                return new[] { rule1, rule2 };\n            };\n\n            // Act\n            IDictionary<string, object> result = htmlHelper.GetUnobtrusiveValidationAttributes(\"foobar\");\n\n            // Assert\n            Assert.Equal(\"error\", result[\"data-val-type\"]);\n            Assert.Equal(\"bar\", result[\"data-val-type-foo\"]);\n            Assert.Equal(\"biff\", result[\"data-val-type-baz\"]);\n            Assert.Equal(\"othererror\", result[\"data-val-othertype\"]);\n            Assert.Equal(\"false4\", result[\"data-val-othertype-true3\"]);\n        }\n\n        [Fact]\n        public void GetUnobtrusiveValidationAttributesUsesShortNameForModelMetadataLookup()\n        {\n            // Arrange\n            string passedName = null;\n            var formContext = new FormContext();\n            var viewContext = new Mock<ViewContext>();\n            var viewData = new ViewDataDictionary();\n            viewContext.SetupGet(vc => vc.FormContext).Returns(formContext);\n            viewContext.SetupGet(vc => vc.ClientValidationEnabled).Returns(true);\n            viewContext.SetupGet(vc => vc.UnobtrusiveJavaScriptEnabled).Returns(true);\n            viewData.TemplateInfo.HtmlFieldPrefix = \"Prefix\";\n            var viewDataContainer = MvcHelper.GetViewDataContainer(viewData);\n            var htmlHelper = new HtmlHelper(viewContext.Object, viewDataContainer);\n            htmlHelper.ClientValidationRuleFactory = (name, _) =>\n            {\n                passedName = name;\n                return Enumerable.Empty<ModelClientValidationRule>();\n            };\n\n            // Act\n            htmlHelper.GetUnobtrusiveValidationAttributes(\"foobar\");\n\n            // Assert\n            Assert.Equal(\"foobar\", passedName);\n        }\n\n        [Fact]\n        public void GetUnobtrusiveValidationAttributeUsesViewDataForModelMetadataLookup()\n        {\n            // Arrange\n            var formContext = new FormContext();\n            var viewContext = new Mock<ViewContext>();\n            var viewData = new ViewDataDictionary<MyModel>();\n            viewContext.SetupGet(vc => vc.FormContext).Returns(formContext);\n            viewContext.SetupGet(vc => vc.ClientValidationEnabled).Returns(true);\n            viewContext.SetupGet(vc => vc.UnobtrusiveJavaScriptEnabled).Returns(true);\n            viewData.TemplateInfo.HtmlFieldPrefix = \"Prefix\";\n            var viewDataContainer = MvcHelper.GetViewDataContainer(viewData);\n            var htmlHelper = new HtmlHelper(viewContext.Object, viewDataContainer);\n\n            // Act\n            IDictionary<string, object> result = htmlHelper.GetUnobtrusiveValidationAttributes(\"MyProperty\");\n\n            // Assert\n            Assert.Equal(2, result.Count);\n            Assert.Equal(\"true\", result[\"data-val\"]);\n            Assert.Equal(\"My required message\", result[\"data-val-required\"]);\n        }\n\n        class MyModel\n        {\n            [Required(ErrorMessage = \"My required message\")]\n            public object MyProperty { get; set; }\n        }\n\n        [Fact]\n        public void GetUnobtrusiveValidationAttributesMarksRenderedFieldsWithFullName()\n        {\n            // Arrange\n            var formContext = new FormContext();\n            var viewContext = new Mock<ViewContext>();\n            var viewData = new ViewDataDictionary();\n            viewContext.SetupGet(vc => vc.FormContext).Returns(formContext);\n            viewContext.SetupGet(vc => vc.ClientValidationEnabled).Returns(true);\n            viewContext.SetupGet(vc => vc.UnobtrusiveJavaScriptEnabled).Returns(true);\n            viewData.TemplateInfo.HtmlFieldPrefix = \"Prefix\";\n            var viewDataContainer = MvcHelper.GetViewDataContainer(viewData);\n            var htmlHelper = new HtmlHelper(viewContext.Object, viewDataContainer);\n\n            // Act\n            htmlHelper.GetUnobtrusiveValidationAttributes(\"foobar\");\n\n            // Assert\n            Assert.False(formContext.RenderedField(\"foobar\"));\n            Assert.True(formContext.RenderedField(\"Prefix.foobar\"));\n        }\n\n        [Fact]\n        public void GetUnobtrusiveValidationAttributesGuardClauses()\n        {\n            // Arrange\n            var formContext = new FormContext();\n            var viewContext = new Mock<ViewContext>();\n            viewContext.SetupGet(vc => vc.FormContext).Returns(formContext);\n            viewContext.SetupGet(vc => vc.ClientValidationEnabled).Returns(true);\n            viewContext.SetupGet(vc => vc.UnobtrusiveJavaScriptEnabled).Returns(true);\n            var viewDataContainer = MvcHelper.GetViewDataContainer(new ViewDataDictionary());\n            var htmlHelper = new HtmlHelper(viewContext.Object, viewDataContainer);\n\n            // Act & Assert\n            AssertBadClientValidationRule(htmlHelper, \"Validation type names in unobtrusive client validation rules cannot be empty. Client rule type: System.Web.Mvc.ModelClientValidationRule\", new ModelClientValidationRule());\n            AssertBadClientValidationRule(htmlHelper, \"Validation type names in unobtrusive client validation rules must consist of only lowercase letters. Invalid name: \\\"OnlyLowerCase\\\", client rule type: System.Web.Mvc.ModelClientValidationRule\", new ModelClientValidationRule { ValidationType = \"OnlyLowerCase\" });\n            AssertBadClientValidationRule(htmlHelper, \"Validation type names in unobtrusive client validation rules must consist of only lowercase letters. Invalid name: \\\"nonumb3rs\\\", client rule type: System.Web.Mvc.ModelClientValidationRule\", new ModelClientValidationRule { ValidationType = \"nonumb3rs\" });\n            AssertBadClientValidationRule(htmlHelper, \"Validation type names in unobtrusive client validation rules must be unique. The following validation type was seen more than once: rule\", new ModelClientValidationRule { ValidationType = \"rule\" }, new ModelClientValidationRule { ValidationType = \"rule\" });\n\n            var emptyParamName = new ModelClientValidationRule { ValidationType = \"type\" };\n            emptyParamName.ValidationParameters[\"\"] = \"foo\";\n            AssertBadClientValidationRule(htmlHelper, \"Validation parameter names in unobtrusive client validation rules cannot be empty. Client rule type: System.Web.Mvc.ModelClientValidationRule\", emptyParamName);\n\n            var paramNameMixedCase = new ModelClientValidationRule { ValidationType = \"type\" };\n            paramNameMixedCase.ValidationParameters[\"MixedCase\"] = \"foo\";\n            AssertBadClientValidationRule(htmlHelper, \"Validation parameter names in unobtrusive client validation rules must start with a lowercase letter and consist of only lowercase letters or digits. Validation parameter name: MixedCase, client rule type: System.Web.Mvc.ModelClientValidationRule\", paramNameMixedCase);\n\n            var paramNameStartsWithNumber = new ModelClientValidationRule { ValidationType = \"type\" };\n            paramNameStartsWithNumber.ValidationParameters[\"2112\"] = \"foo\";\n            AssertBadClientValidationRule(htmlHelper, \"Validation parameter names in unobtrusive client validation rules must start with a lowercase letter and consist of only lowercase letters or digits. Validation parameter name: 2112, client rule type: System.Web.Mvc.ModelClientValidationRule\", paramNameStartsWithNumber);\n        }\n\n        [Fact]\n        public void RawReturnsWrapperMarkup()\n        {\n            // Arrange\n            var viewContext = new Mock<ViewContext>().Object;\n            var viewDataContainer = new Mock<IViewDataContainer>().Object;\n            var htmlHelper = new HtmlHelper(viewContext, viewDataContainer);\n            string markup = \"<b>bold</b>\";\n\n            // Act\n            IHtmlString markupHtml = htmlHelper.Raw(markup);\n\n            // Assert\n            Assert.Equal(\"<b>bold</b>\", markupHtml.ToString());\n            Assert.Equal(\"<b>bold</b>\", markupHtml.ToHtmlString());\n        }\n\n        [Fact]\n        public void RawAllowsNullValue()\n        {\n            // Arrange\n            var viewContext = new Mock<ViewContext>().Object;\n            var viewDataContainer = new Mock<IViewDataContainer>().Object;\n            var htmlHelper = new HtmlHelper(viewContext, viewDataContainer);\n\n            // Act\n            IHtmlString markupHtml = htmlHelper.Raw(null);\n\n            // Assert\n            Assert.Null(markupHtml.ToString());\n            Assert.Null(markupHtml.ToHtmlString());\n        }\n\n        [Fact]\n        public void RawAllowsNullObjectValue()\n        {\n            // Arrange\n            var viewContext = new Mock<ViewContext>().Object;\n            var viewDataContainer = new Mock<IViewDataContainer>().Object;\n            var htmlHelper = new HtmlHelper(viewContext, viewDataContainer);\n\n            // Act\n            IHtmlString markupHtml = htmlHelper.Raw((object)null);\n\n            // Assert\n            Assert.Null(markupHtml.ToString());\n            Assert.Null(markupHtml.ToHtmlString());\n        }\n\n        [Fact]\n        public void RawAllowsEmptyValue()\n        {\n            // Arrange\n            var viewContext = new Mock<ViewContext>().Object;\n            var viewDataContainer = new Mock<IViewDataContainer>().Object;\n            var htmlHelper = new HtmlHelper(viewContext, viewDataContainer);\n\n            // Act\n            IHtmlString markupHtml = htmlHelper.Raw(\"\");\n\n            // Assert\n            Assert.Equal(\"\", markupHtml.ToString());\n            Assert.Equal(\"\", markupHtml.ToHtmlString());\n        }\n\n        [Fact]\n        public void RawReturnsWrapperMarkupOfObject()\n        {\n            // Arrange\n            var viewContext = new Mock<ViewContext>().Object;\n            var viewDataContainer = new Mock<IViewDataContainer>().Object;\n            var htmlHelper = new HtmlHelper(viewContext, viewDataContainer);\n            ObjectWithWrapperMarkup obj = new ObjectWithWrapperMarkup();\n\n            // Act\n            IHtmlString markupHtml = htmlHelper.Raw(obj);\n\n            // Assert\n            Assert.Equal(\"<b>boldFromObject</b>\", markupHtml.ToString());\n            Assert.Equal(\"<b>boldFromObject</b>\", markupHtml.ToHtmlString());\n        }\n\n        [Fact]\n        public void EvalStringAndFormatValueWithNullValueReturnsEmptyString()\n        {\n            // Arrange\n            var htmlHelper = MvcHelper.GetHtmlHelper(new ViewDataDictionary());\n\n            // Act & Assert\n            Assert.Equal(String.Empty, htmlHelper.FormatValue(null, \"-{0}-\"));\n            Assert.Equal(String.Empty, htmlHelper.EvalString(\"nonExistant\"));\n            Assert.Equal(String.Empty, htmlHelper.EvalString(\"nonExistant\", \"-{0}-\"));\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void EvalStringAndFormatValueUseCurrentCulture()\n        {\n            // Arrange\n            DateTime dt = new DateTime(1900, 1, 1, 0, 0, 0);\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(new ViewDataDictionary() { { \"date\", dt } });\n            string expectedFormattedDate = \"-01/01/1900 00:00:00-\";\n\n            // Act && Assert\n            Assert.Equal(expectedFormattedDate, htmlHelper.FormatValue(dt, \"-{0}-\"));\n            Assert.Equal(expectedFormattedDate, htmlHelper.EvalString(\"date\", \"-{0}-\"));\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void EvalStringAndFormatValueWithEmptyFormatConvertsValueToString()\n        {\n            // Arrange\n            DateTime dt = new DateTime(1900, 1, 1, 0, 0, 0);\n            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper(new ViewDataDictionary() { { \"date\", dt } });\n            string expectedUnformattedDate = \"01/01/1900 00:00:00\";\n\n            // Act && Assert\n            Assert.Equal(expectedUnformattedDate, htmlHelper.FormatValue(dt, String.Empty));\n            Assert.Equal(expectedUnformattedDate, htmlHelper.EvalString(\"date\", String.Empty));\n            Assert.Equal(expectedUnformattedDate, htmlHelper.EvalString(\"date\"));\n        }\n\n\n        [Fact]\n        public void ObjectToDictionaryWithAnonymousTypeLooksUpProperties()\n        {\n            // Arrange\n            object obj = new { _test = \"value\", oth_er = 1 };\n\n            // Act\n            IDictionary<string, object> dictValues = HtmlHelper.ObjectToDictionary(obj);\n\n            // Assert\n            Assert.NotNull(dictValues);\n            Assert.Equal(2, dictValues.Count);\n            Assert.Equal(\"value\", dictValues[\"_test\"]);\n            Assert.Equal(1, dictValues[\"oth_er\"]);\n        }\n\n        // SetValidationSummaryMessageElement\n\n        [Fact]\n        public void SetValidationSummaryMessageElement()\n        {\n            // Arrange\n            var mockViewContext = new Mock<ViewContext>();\n            var viewDataContainer = new Mock<IViewDataContainer>().Object;\n            var htmlHelper = new HtmlHelper(mockViewContext.Object, viewDataContainer);\n\n            // Act\n            htmlHelper.SetValidationSummaryMessageElement(\"label\");\n\n            // Act & assert\n            mockViewContext.VerifySet(vc => vc.ValidationSummaryMessageElement = \"label\");\n        }\n\n        [Fact]\n        public void SetValidationMessageElement()\n        {\n            // Arrange\n            var mockViewContext = new Mock<ViewContext>();\n            var viewDataContainer = new Mock<IViewDataContainer>().Object;\n            var htmlHelper = new HtmlHelper(mockViewContext.Object, viewDataContainer);\n\n            // Act\n            htmlHelper.SetValidationMessageElement(\"label\");\n\n            // Act & assert\n            mockViewContext.VerifySet(vc => vc.ValidationMessageElement = \"label\");\n        }\n\n        private class ObjectWithWrapperMarkup\n        {\n            public override string ToString()\n            {\n                return \"<b>boldFromObject</b>\";\n            }\n        }\n\n        // Helpers\n\n        private static void AssertBadClientValidationRule(HtmlHelper htmlHelper, string expectedMessage, params ModelClientValidationRule[] rules)\n        {\n            htmlHelper.ClientValidationRuleFactory = delegate { return rules; };\n            Assert.Throws<InvalidOperationException>(\n                () => htmlHelper.GetUnobtrusiveValidationAttributes(Guid.NewGuid().ToString()),\n                expectedMessage\n                );\n        }\n\n        internal static ValueProviderResult GetValueProviderResult(object rawValue, string attemptedValue)\n        {\n            return new ValueProviderResult(rawValue, attemptedValue, CultureInfo.InvariantCulture);\n        }\n\n        private class TestableHtmlHelper : HtmlHelper\n        {\n            TestableHtmlHelper(ViewContext viewContext, IViewDataContainer viewDataContainer)\n                : base(viewContext, viewDataContainer)\n            {\n            }\n\n            public static TestableHtmlHelper Create()\n            {\n                ViewDataDictionary viewData = new ViewDataDictionary();\n\n                Mock<ViewContext> mockViewContext = new Mock<ViewContext>();\n                mockViewContext.Setup(c => c.HttpContext.Response.Output).Throws(new Exception(\"Response.Output should never be called.\"));\n                mockViewContext.SetupGet(c => c.TempData).Returns(new TempDataDictionary());\n                mockViewContext.SetupGet(c => c.View).Returns(Mock.Of<IView>());\n                mockViewContext.Setup(c => c.ViewData).Returns(viewData);\n                mockViewContext.Setup(c => c.Writer).Returns(new StringWriter());\n\n                Mock<IViewDataContainer> container = new Mock<IViewDataContainer>();\n                container.Setup(c => c.ViewData).Returns(viewData);\n\n                return new TestableHtmlHelper(mockViewContext.Object, container.Object);\n            }\n\n            public void RenderPartialInternal(string partialViewName,\n                                              ViewDataDictionary viewData,\n                                              object model,\n                                              TextWriter writer,\n                                              params IViewEngine[] engines)\n            {\n                base.RenderPartialInternal(partialViewName, viewData, model, writer, new ViewEngineCollection(engines));\n            }\n        }\n\n        public void Dispose()\n        {\n            // Reset ScopeStorage (written via e.g. htmlHelper.SetValidationSummaryMessageElement()) between tests to avoid unexpected interactions.\n            ScopeStorage.CurrentProvider = new StaticScopeStorageProvider();\n            ScopeStorage.GlobalScope.Clear();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/HttpDeleteAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class HttpDeleteAttributeTest\n    {\n        [Fact]\n        public void IsValidForRequestReturnsFalseIfHttpVerbIsNotPost()\n        {\n            HttpVerbAttributeHelper.TestHttpVerbAttributeWithInvalidVerb<HttpDeleteAttribute>(\"POST\");\n        }\n\n        [Fact]\n        public void IsValidForRequestReturnsTrueIfHttpVerbIsPost()\n        {\n            HttpVerbAttributeHelper.TestHttpVerbAttributeWithValidVerb<HttpDeleteAttribute>(\"DELETE\");\n        }\n\n        [Fact]\n        public void IsValidForRequestThrowsIfControllerContextIsNull()\n        {\n            HttpVerbAttributeHelper.TestHttpVerbAttributeNullControllerContext<HttpDeleteAttribute>();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/HttpFileCollectionValueProviderFactoryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class HttpFileCollectionValueProviderFactoryTest\n    {\n        [Fact]\n        public void GetValueProvider()\n        {\n            // Arrange\n            HttpFileCollectionValueProviderFactory factory = new HttpFileCollectionValueProviderFactory();\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(o => o.HttpContext.Request.Files.Count).Returns(0);\n\n            // Act\n            IValueProvider valueProvider = factory.GetValueProvider(mockControllerContext.Object);\n\n            // Assert\n            Assert.IsType<HttpFileCollectionValueProvider>(valueProvider);\n        }\n\n        [Fact]\n        public void GetValueProvider_ThrowsIfControllerContextIsNull()\n        {\n            // Arrange\n            HttpFileCollectionValueProviderFactory factory = new HttpFileCollectionValueProviderFactory();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { factory.GetValueProvider(null); }, \"controllerContext\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/HttpFileCollectionValueProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class HttpFileCollectionValueProviderTest\n    {\n        private static readonly KeyValuePair<string, HttpPostedFileBase>[] _allFiles = new KeyValuePair<string, HttpPostedFileBase>[]\n        {\n            new KeyValuePair<string, HttpPostedFileBase>(\"foo\", new MockHttpPostedFile(42, \"fooFile1\")),\n            new KeyValuePair<string, HttpPostedFileBase>(\"foo\", null),\n            new KeyValuePair<string, HttpPostedFileBase>(\"foo\", new MockHttpPostedFile(0, \"\") /* empty */),\n            new KeyValuePair<string, HttpPostedFileBase>(\"foo\", new MockHttpPostedFile(100, \"fooFile2\")),\n            new KeyValuePair<string, HttpPostedFileBase>(\"bar.baz\", new MockHttpPostedFile(200, \"barBazFile\"))\n        };\n\n        [Fact]\n        public void ContainsPrefix()\n        {\n            // Arrange\n            HttpFileCollectionValueProvider valueProvider = GetValueProvider();\n\n            // Act\n            bool result = valueProvider.ContainsPrefix(\"bar\");\n\n            // Assert\n            Assert.True(result);\n        }\n\n        [Fact]\n        public void ContainsPrefix_DoesNotContainEmptyPrefixIfBackingStoreIsEmpty()\n        {\n            // Arrange\n            HttpFileCollectionValueProvider valueProvider = GetEmptyValueProvider();\n\n            // Act\n            bool result = valueProvider.ContainsPrefix(\"\");\n\n            // Assert\n            Assert.False(result);\n        }\n\n        [Fact]\n        public void ContainsPrefix_ThrowsIfPrefixIsNull()\n        {\n            // Arrange\n            HttpFileCollectionValueProvider valueProvider = GetValueProvider();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { valueProvider.ContainsPrefix(null); }, \"prefix\");\n        }\n\n        [Fact]\n        public void GetValue()\n        {\n            // Arrange\n            HttpFileCollectionValueProvider valueProvider = GetValueProvider();\n\n            // Act\n            ValueProviderResult vpResult = valueProvider.GetValue(\"foo\");\n\n            // Assert\n            Assert.NotNull(vpResult);\n\n            HttpPostedFileBase[] expectedRawValues = (from el in _allFiles\n                                                      where el.Key == \"foo\"\n                                                      let file = el.Value\n                                                      let hasContent = (file != null && file.ContentLength > 0 && !String.IsNullOrEmpty(file.FileName))\n                                                      select (hasContent) ? file : null).ToArray();\n            Assert.Equal(expectedRawValues, (HttpPostedFileBase[])vpResult.RawValue);\n            Assert.Equal(\"System.Web.HttpPostedFileBase[]\", vpResult.AttemptedValue);\n            Assert.Equal(CultureInfo.InvariantCulture, vpResult.Culture);\n        }\n\n        [Fact]\n        public void GetValue_ReturnsNullIfKeyNotFound()\n        {\n            // Arrange\n            HttpFileCollectionValueProvider valueProvider = GetValueProvider();\n\n            // Act\n            ValueProviderResult vpResult = valueProvider.GetValue(\"bar\");\n\n            // Assert\n            Assert.Null(vpResult);\n        }\n\n        [Fact]\n        public void GetValue_ThrowsIfKeyIsNull()\n        {\n            // Arrange\n            HttpFileCollectionValueProvider valueProvider = GetValueProvider();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { valueProvider.GetValue(null); }, \"key\");\n        }\n\n        private static HttpFileCollectionValueProvider GetEmptyValueProvider()\n        {\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(o => o.HttpContext.Request.Files.Count).Returns(0);\n            return new HttpFileCollectionValueProvider(mockControllerContext.Object);\n        }\n\n        private static HttpFileCollectionValueProvider GetValueProvider()\n        {\n            Mock<HttpFileCollectionBase> mockFileCollection = new Mock<HttpFileCollectionBase>();\n            mockFileCollection.SetupGet(c => c.Count).Returns(_allFiles.Length);\n            mockFileCollection.SetupGet(c => c.AllKeys).Returns(_allFiles.Select(f => f.Key).ToArray());\n            for (int i = 0; i < _allFiles.Length; i++)\n            {\n                int j = i;\n                mockFileCollection.SetupGet(c => c[j]).Returns(_allFiles[j].Value);\n            }\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.SetupGet(o => o.HttpContext.Request.Files).Returns(mockFileCollection.Object);\n\n            return new HttpFileCollectionValueProvider(mockControllerContext.Object);\n        }\n\n        private sealed class MockHttpPostedFile : HttpPostedFileBase\n        {\n            private readonly int _contentLength;\n            private readonly string _fileName;\n\n            public MockHttpPostedFile(int contentLength, string fileName)\n            {\n                _contentLength = contentLength;\n                _fileName = fileName;\n            }\n\n            public override int ContentLength\n            {\n                get { return _contentLength; }\n            }\n\n            public override string FileName\n            {\n                get { return _fileName; }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/HttpGetAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class HttpGetAttributeTest\n    {\n        [Fact]\n        public void IsValidForRequestReturnsFalseIfHttpVerbIsNotPost()\n        {\n            HttpVerbAttributeHelper.TestHttpVerbAttributeWithInvalidVerb<HttpGetAttribute>(\"DELETE\");\n        }\n\n        [Fact]\n        public void IsValidForRequestReturnsTrueIfHttpVerbIsPost()\n        {\n            HttpVerbAttributeHelper.TestHttpVerbAttributeWithValidVerb<HttpGetAttribute>(\"GET\");\n        }\n\n        [Fact]\n        public void IsValidForRequestThrowsIfControllerContextIsNull()\n        {\n            HttpVerbAttributeHelper.TestHttpVerbAttributeNullControllerContext<HttpGetAttribute>();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/HttpHandlerUtilTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Web.Hosting;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class HttpHandlerUtilTest\n    {\n        [Fact]\n        public void WrapForServerExecute_BeginProcessRequest_DelegatesCorrectly()\n        {\n            // Arrange\n            IAsyncResult expectedResult = new Mock<IAsyncResult>().Object;\n            AsyncCallback cb = delegate { };\n\n            HttpContext httpContext = GetHttpContext();\n            Mock<IHttpAsyncHandler> mockHttpHandler = new Mock<IHttpAsyncHandler>();\n            mockHttpHandler.Setup(o => o.BeginProcessRequest(httpContext, cb, \"extraData\")).Returns(expectedResult);\n\n            IHttpAsyncHandler wrapper = (IHttpAsyncHandler)HttpHandlerUtil.WrapForServerExecute(mockHttpHandler.Object);\n\n            // Act\n            IAsyncResult actualResult = wrapper.BeginProcessRequest(httpContext, cb, \"extraData\");\n\n            // Assert\n            Assert.Equal(expectedResult, actualResult);\n        }\n\n        [Fact]\n        public void WrapForServerExecute_EndProcessRequest_DelegatesCorrectly()\n        {\n            // Arrange\n            IAsyncResult asyncResult = new Mock<IAsyncResult>().Object;\n\n            HttpContext httpContext = GetHttpContext();\n            Mock<IHttpAsyncHandler> mockHttpHandler = new Mock<IHttpAsyncHandler>();\n            mockHttpHandler.Setup(o => o.EndProcessRequest(asyncResult)).Verifiable();\n\n            IHttpAsyncHandler wrapper = (IHttpAsyncHandler)HttpHandlerUtil.WrapForServerExecute(mockHttpHandler.Object);\n\n            // Act\n            wrapper.EndProcessRequest(asyncResult);\n\n            // Assert\n            mockHttpHandler.Verify();\n        }\n\n        [Fact]\n        public void WrapForServerExecute_ProcessRequest_DelegatesCorrectly()\n        {\n            // Arrange\n            HttpContext httpContext = GetHttpContext();\n            Mock<IHttpHandler> mockHttpHandler = new Mock<IHttpHandler>();\n            mockHttpHandler.Setup(o => o.ProcessRequest(httpContext)).Verifiable();\n\n            IHttpHandler wrapper = HttpHandlerUtil.WrapForServerExecute(mockHttpHandler.Object);\n\n            // Act\n            wrapper.ProcessRequest(httpContext);\n\n            // Assert\n            mockHttpHandler.Verify();\n        }\n\n        [Fact]\n        public void WrapForServerExecute_ProcessRequest_PropagatesExceptionsIfNotHttpException()\n        {\n            // Arrange\n            HttpContext httpContext = GetHttpContext();\n            Mock<IHttpHandler> mockHttpHandler = new Mock<IHttpHandler>();\n            mockHttpHandler.Setup(o => o.ProcessRequest(httpContext)).Throws(new InvalidOperationException(\"Some exception.\"));\n\n            IHttpHandler wrapper = HttpHandlerUtil.WrapForServerExecute(mockHttpHandler.Object);\n\n            // Act & assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { wrapper.ProcessRequest(httpContext); },\n                @\"Some exception.\");\n        }\n\n        [Fact]\n        public void WrapForServerExecute_ProcessRequest_PropagatesHttpExceptionIfStatusCode500()\n        {\n            // Arrange\n            HttpContext httpContext = GetHttpContext();\n            Mock<IHttpHandler> mockHttpHandler = new Mock<IHttpHandler>();\n            mockHttpHandler.Setup(o => o.ProcessRequest(httpContext)).Throws(new HttpException(500, \"Some exception.\"));\n\n            IHttpHandler wrapper = HttpHandlerUtil.WrapForServerExecute(mockHttpHandler.Object);\n\n            // Act & assert\n            Assert.ThrowsHttpException(\n                delegate { wrapper.ProcessRequest(httpContext); },\n                @\"Some exception.\",\n                500);\n        }\n\n        [Fact]\n        public void WrapForServerExecute_ProcessRequest_WrapsHttpExceptionIfStatusCodeNot500()\n        {\n            // Arrange\n            HttpContext httpContext = GetHttpContext();\n            Mock<IHttpHandler> mockHttpHandler = new Mock<IHttpHandler>();\n            mockHttpHandler.Setup(o => o.ProcessRequest(httpContext)).Throws(new HttpException(404, \"Some exception.\"));\n\n            IHttpHandler wrapper = HttpHandlerUtil.WrapForServerExecute(mockHttpHandler.Object);\n\n            // Act & assert\n            HttpException outerException = Assert.ThrowsHttpException(\n                delegate { wrapper.ProcessRequest(httpContext); },\n                @\"Execution of the child request failed. Please examine the InnerException for more information.\",\n                500);\n\n            HttpException innerException = outerException.InnerException as HttpException;\n            Assert.NotNull(innerException);\n            Assert.Equal(404, innerException.GetHttpCode());\n            Assert.Equal(\"Some exception.\", innerException.Message);\n        }\n\n        [Fact]\n        public void WrapForServerExecute_ReturnsIHttpAsyncHandler()\n        {\n            // Arrange\n            IHttpAsyncHandler httpHandler = new Mock<IHttpAsyncHandler>().Object;\n\n            // Act\n            IHttpHandler wrapper = HttpHandlerUtil.WrapForServerExecute(httpHandler);\n\n            // Assert\n            Assert.True(wrapper is IHttpAsyncHandler);\n        }\n\n        [Fact]\n        public void WrapForServerExecute_ReturnsIHttpHandler()\n        {\n            // Arrange\n            IHttpHandler httpHandler = new Mock<IHttpHandler>().Object;\n\n            // Act\n            IHttpHandler wrapper = HttpHandlerUtil.WrapForServerExecute(httpHandler);\n\n            // Assert\n            Assert.False(wrapper is IHttpAsyncHandler);\n        }\n\n        private static HttpContext GetHttpContext()\n        {\n            return new HttpContext(new SimpleWorkerRequest(\"/\", \"/\", \"Page\", \"Query\", TextWriter.Null));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/HttpHeadAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class HttpHeadAttributeTest\n    {\n        [Fact]\n        public void IsValidForRequestReturnsFalseIfHttpVerbIsNotHead()\n        {\n            HttpVerbAttributeHelper.TestHttpVerbAttributeWithInvalidVerb<HttpHeadAttribute>(\"GET\");\n        }\n\n        [Fact]\n        public void IsValidForRequestReturnsTrueIfHttpVerbIsHead()\n        {\n            HttpVerbAttributeHelper.TestHttpVerbAttributeWithValidVerb<HttpHeadAttribute>(\"HEAD\");\n        }\n\n        [Fact]\n        public void IsValidForRequestThrowsIfControllerContextIsNull()\n        {\n            HttpVerbAttributeHelper.TestHttpVerbAttributeNullControllerContext<HttpHeadAttribute>();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/HttpNotFoundResultTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class HttpNotFoundResultTest\n    {\n        [Fact]\n        public void ExecuteResult()\n        {\n            // Arrange\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.StatusCode = 404).Verifiable();\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.StatusDescription = \"Some description\").Verifiable();\n\n            HttpNotFoundResult result = new HttpNotFoundResult(\"Some description\");\n\n            // Act\n            result.ExecuteResult(mockControllerContext.Object);\n\n            // Assert\n            mockControllerContext.Verify();\n        }\n\n        [Fact]\n        public void StatusCode()\n        {\n            Assert.Equal(404, new HttpNotFoundResult().StatusCode);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/HttpOptionsAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class HttpOptionsAttributeTest\n    {\n        [Fact]\n        public void IsValidForRequestReturnsFalseIfHttpVerbIsNotOptions()\n        {\n            HttpVerbAttributeHelper.TestHttpVerbAttributeWithInvalidVerb<HttpOptionsAttribute>(\"GET\");\n        }\n\n        [Fact]\n        public void IsValidForRequestReturnsTrueIfHttpVerbIsOptions()\n        {\n            HttpVerbAttributeHelper.TestHttpVerbAttributeWithValidVerb<HttpOptionsAttribute>(\"OPTIONS\");\n        }\n\n        [Fact]\n        public void IsValidForRequestThrowsIfControllerContextIsNull()\n        {\n            HttpVerbAttributeHelper.TestHttpVerbAttributeNullControllerContext<HttpOptionsAttribute>();\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/HttpPatchAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test {\n    public class HttpPatchAttributeTest \n    {\n        [Fact]\n        public void IsValidForRequestReturnsFalseIfHttpVerbIsNotPatch() \n        {\n            HttpVerbAttributeHelper.TestHttpVerbAttributeWithInvalidVerb<HttpPatchAttribute>(\"GET\");\n        }\n\n        [Fact]\n        public void IsValidForRequestReturnsTrueIfHttpVerbIsPatch() \n        {\n            HttpVerbAttributeHelper.TestHttpVerbAttributeWithValidVerb<HttpPatchAttribute>(\"PATCH\");\n        }\n\n        [Fact]\n        public void IsValidForRequestThrowsIfControllerContextIsNull()\n        {\n            HttpVerbAttributeHelper.TestHttpVerbAttributeNullControllerContext<HttpPatchAttribute>();\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/HttpPostAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class HttpPostAttributeTest\n    {\n        [Fact]\n        public void IsValidForRequestReturnsFalseIfHttpVerbIsNotPost()\n        {\n            HttpVerbAttributeHelper.TestHttpVerbAttributeWithInvalidVerb<HttpPostAttribute>(\"DELETE\");\n        }\n\n        [Fact]\n        public void IsValidForRequestReturnsTrueIfHttpVerbIsPost()\n        {\n            HttpVerbAttributeHelper.TestHttpVerbAttributeWithValidVerb<HttpPostAttribute>(\"POST\");\n        }\n\n        [Fact]\n        public void IsValidForRequestThrowsIfControllerContextIsNull()\n        {\n            HttpVerbAttributeHelper.TestHttpVerbAttributeNullControllerContext<HttpPostAttribute>();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/HttpPostedFileBaseModelBinderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class HttpPostedFileBaseModelBinderTest\n    {\n        [Fact]\n        public void BindModelReturnsEmptyResultIfEmptyFileInputElementInPost()\n        {\n            // Arrange\n            Mock<HttpPostedFileBase> mockFile = new Mock<HttpPostedFileBase>();\n            mockFile.Setup(f => f.ContentLength).Returns(0);\n            mockFile.Setup(f => f.FileName).Returns(String.Empty);\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.SetupGet(c => c.HttpContext.Request.Files[\"fileName\"]).Returns(mockFile.Object);\n\n            HttpPostedFileBaseModelBinder binder = new HttpPostedFileBaseModelBinder();\n            ModelBindingContext bindingContext = new ModelBindingContext() { ModelName = \"fileName\" };\n\n            // Act\n            object result = binder.BindModel(mockControllerContext.Object, bindingContext);\n\n            // Assert\n            Assert.Null(result);\n        }\n\n        [Fact]\n        public void BindModelReturnsNullIfNoFileInputElementInPost()\n        {\n            // Arrange\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(c => c.HttpContext.Request.Files[\"fileName\"]).Returns((HttpPostedFileBase)null);\n\n            HttpPostedFileBaseModelBinder binder = new HttpPostedFileBaseModelBinder();\n            ModelBindingContext bindingContext = new ModelBindingContext() { ModelName = \"fileName\" };\n\n            // Act\n            object result = binder.BindModel(mockControllerContext.Object, bindingContext);\n\n            // Assert\n            Assert.Null(result);\n        }\n\n        [Fact]\n        public void BindModelReturnsResultIfFileFound()\n        {\n            // Arrange\n            Mock<HttpPostedFileBase> mockFile = new Mock<HttpPostedFileBase>();\n            mockFile.Setup(f => f.ContentLength).Returns(1234);\n            mockFile.Setup(f => f.FileName).Returns(\"somefile\");\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.SetupGet(c => c.HttpContext.Request.Files[\"fileName\"]).Returns(mockFile.Object);\n\n            HttpPostedFileBaseModelBinder binder = new HttpPostedFileBaseModelBinder();\n            ModelBindingContext bindingContext = new ModelBindingContext() { ModelName = \"fileName\" };\n\n            // Act\n            object result = binder.BindModel(mockControllerContext.Object, bindingContext);\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Same(mockFile.Object, result);\n        }\n\n        [Fact]\n        public void BindModelThrowsIfBindingContextIsNull()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n            HttpPostedFileBaseModelBinder binder = new HttpPostedFileBaseModelBinder();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { binder.BindModel(controllerContext, null); }, \"bindingContext\");\n        }\n\n        [Fact]\n        public void BindModelThrowsIfControllerContextIsNull()\n        {\n            // Arrange\n            HttpPostedFileBaseModelBinder binder = new HttpPostedFileBaseModelBinder();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { binder.BindModel(null, null); }, \"controllerContext\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/HttpPutAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class HttpPutAttributeTest\n    {\n        [Fact]\n        public void IsValidForRequestReturnsFalseIfHttpVerbIsNotPost()\n        {\n            HttpVerbAttributeHelper.TestHttpVerbAttributeWithInvalidVerb<HttpPutAttribute>(\"GET\");\n        }\n\n        [Fact]\n        public void IsValidForRequestReturnsTrueIfHttpVerbIsPost()\n        {\n            HttpVerbAttributeHelper.TestHttpVerbAttributeWithValidVerb<HttpPutAttribute>(\"PUT\");\n        }\n\n        [Fact]\n        public void IsValidForRequestThrowsIfControllerContextIsNull()\n        {\n            HttpVerbAttributeHelper.TestHttpVerbAttributeNullControllerContext<HttpPutAttribute>();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/HttpRequestExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class HttpRequestExtensionsTest\n    {\n        [Fact]\n        public void GetHttpMethodOverrideWithNullRequestThrows()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => HttpRequestExtensions.GetHttpMethodOverride(null),\n                \"request\"\n                );\n        }\n\n        [Theory]\n        [InlineData(\"GET\", \"PUT\", null, null, \"GET\")] // Cannot override GET with header PUT\n        [InlineData(\"GET\", null, \"PUT\", null, \"GET\")] // Cannot override GET with form PUT\n        [InlineData(\"GET\", null, null, \"PUT\", \"GET\")] // Cannot override GET with query string PUT\n        [InlineData(\"PUT\", \"GET\", null, null, \"PUT\")] // Cannot override PUT with GET\n        [InlineData(\"PUT\", \"POST\", null, null, \"PUT\")] // Cannot override PUT with POST\n        [InlineData(\"POST\", \"GET\", null, null, \"POST\")] // Cannot override POST with GET\n        [InlineData(\"POST\", \"POST\", null, null, \"POST\")] // Cannot override POST with POST\n        [InlineData(\"POST\", \"PUT\", null, null, \"PUT\")] // Can override POST with header PUT\n        [InlineData(\"POST\", null, \"PUT\", null, \"PUT\")] // Can override POST with form PUT\n        [InlineData(\"POST\", null, null, \"PUT\", \"PUT\")] // Can override POST with query string PUT\n        [InlineData(\"POST\", \"PUT\", \"BOGUS\", null, \"PUT\")] // Header override wins over form override\n        [InlineData(\"POST\", \"PUT\", null, \"BOGUS\", \"PUT\")] // Header override wins over query string override\n        [InlineData(\"POST\", null, \"PUT\", \"BOGUS\", \"PUT\")] // Form override wins over query string override\n        public void TestHttpMethodOverride(string httpRequestVerb,\n                                           string httpHeaderVerb,\n                                           string httpFormVerb,\n                                           string httpQueryStringVerb,\n                                           string expectedMethod)\n        {\n            // Arrange\n            ControllerContext context = AcceptVerbsAttributeTest.GetControllerContextWithHttpVerb(httpRequestVerb, httpHeaderVerb, httpFormVerb, httpQueryStringVerb);\n\n            // Act\n            string methodOverride = context.RequestContext.HttpContext.Request.GetHttpMethodOverride();\n\n            // Assert\n            Assert.Equal(expectedMethod, methodOverride);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/HttpStatusCodeResultTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class HttpStatusCodeResultTest\n    {\n        [Fact]\n        public void ExecuteResult()\n        {\n            // Arrange\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.StatusCode = 666).Verifiable();\n\n            HttpStatusCodeResult result = new HttpStatusCodeResult(666);\n\n            // Act\n            result.ExecuteResult(mockControllerContext.Object);\n\n            // Assert\n            mockControllerContext.Verify();\n        }\n\n        [Fact]\n        public void ExecuteResultWithDescription()\n        {\n            // Arrange\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.StatusCode = 666).Verifiable();\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.StatusDescription = \"Foo Bar\").Verifiable();\n            HttpStatusCodeResult result = new HttpStatusCodeResult(666, \"Foo Bar\");\n\n            // Act\n            result.ExecuteResult(mockControllerContext.Object);\n\n            // Assert\n            mockControllerContext.Verify();\n        }\n\n        [Fact]\n        public void ExecuteResultWithNullContextThrows()\n        {\n            // Act and Assert\n            Assert.ThrowsArgumentNull(delegate { new HttpStatusCodeResult(1).ExecuteResult(context: null); }, \"context\");\n        }\n\n        [Fact]\n        public void StatusCode()\n        {\n            // Assert\n            Assert.Equal(123, new HttpStatusCodeResult(123).StatusCode);\n            Assert.Equal(234, new HttpStatusCodeResult(234, \"foobar\").StatusCode);\n        }\n\n        [Fact]\n        public void StatusDescription()\n        {\n            // Assert\n            Assert.Null(new HttpStatusCodeResult(123).StatusDescription);\n            Assert.Equal(\"foobar\", new HttpStatusCodeResult(234, \"foobar\").StatusDescription);\n        }\n\n        [Fact]\n        public void HttpStatusCodeAndStatusDescription()\n        {\n            // Arrange\n            int unusedStatusCode = 306;\n\n            // Act\n            HttpStatusCodeResult result = new HttpStatusCodeResult(HttpStatusCode.Unused, \"foobar\");\n\n            // Assert\n            Assert.Equal(unusedStatusCode, result.StatusCode);\n            Assert.Equal(\"foobar\", result.StatusDescription);\n        }\n\n        [Fact]\n        public void ExecuteResultWithHttpStatusCode()\n        {\n            // Arrange\n            int unusedStatusCode = 306;\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.StatusCode = unusedStatusCode).Verifiable();\n\n            HttpStatusCodeResult result = new HttpStatusCodeResult(HttpStatusCode.Unused);\n\n            // Act\n            result.ExecuteResult(mockControllerContext.Object);\n\n            // Assert\n            mockControllerContext.Verify();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/HttpUnauthorizedResultTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class HttpUnauthorizedResultTest\n    {\n        [Fact]\n        public void ExecuteResult()\n        {\n            // Arrange\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.StatusCode = 401).Verifiable();\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.StatusDescription = \"Some description\").Verifiable();\n\n            HttpUnauthorizedResult result = new HttpUnauthorizedResult(\"Some description\");\n\n            // Act\n            result.ExecuteResult(mockControllerContext.Object);\n\n            // Assert\n            mockControllerContext.Verify();\n        }\n\n        [Fact]\n        public void StatusCode()\n        {\n            Assert.Equal(401, new HttpUnauthorizedResult().StatusCode);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/HttpVerbAttributeHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    internal static class HttpVerbAttributeHelper\n    {\n        internal static void TestHttpVerbAttributeNullControllerContext<THttpVerb>()\n            where THttpVerb : ActionMethodSelectorAttribute, new()\n        {\n            // Arrange\n            ActionMethodSelectorAttribute attribute = new THttpVerb();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { attribute.IsValidForRequest(null, null); }, \"controllerContext\");\n        }\n\n        internal static void TestHttpVerbAttributeWithValidVerb<THttpVerb>(string validVerb)\n            where THttpVerb : ActionMethodSelectorAttribute, new()\n        {\n            // Arrange\n            ActionMethodSelectorAttribute attribute = new THttpVerb();\n            ControllerContext context = AcceptVerbsAttributeTest.GetControllerContextWithHttpVerb(validVerb);\n\n            // Act\n            bool result = attribute.IsValidForRequest(context, null);\n\n            // Assert\n            Assert.True(result);\n        }\n\n        internal static void TestHttpVerbAttributeWithInvalidVerb<THttpVerb>(string invalidVerb)\n            where THttpVerb : ActionMethodSelectorAttribute, new()\n        {\n            // Arrange\n            ActionMethodSelectorAttribute attribute = new THttpVerb();\n            ControllerContext context = AcceptVerbsAttributeTest.GetControllerContextWithHttpVerb(invalidVerb);\n\n            // Act\n            bool result = attribute.IsValidForRequest(context, null);\n\n            // Assert\n            Assert.False(result);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/JQueryFormValueProviderFactoryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing System.Globalization;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class JQueryFormValueProviderFactoryTest\n    {\n        private static readonly NameValueCollection _backingStore = new NameValueCollection()\n        {\n            { \"foo\", \"fooValue\" },\n            { \"fooArray[0][bar1]\", \"fooArrayValue\"}\n        };\n\n        private static readonly NameValueCollection _unvalidatedBackingStore = new NameValueCollection()\n        {\n            { \"foo\", \"fooUnvalidated\" },\n            { \"fooArray[0][bar1][0][nested]\", \"fooNestedUnvalidatedValue\" }\n        };\n\n        [Fact]\n        public void GetValueProvider()\n        {\n            // Arrange\n            Mock<MockableUnvalidatedRequestValues> mockUnvalidatedValues = new Mock<MockableUnvalidatedRequestValues>();\n            JQueryFormValueProviderFactory factory = \n                        new JQueryFormValueProviderFactory(_ => mockUnvalidatedValues.Object);\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(o => o.HttpContext.Request.Form).Returns(_backingStore);\n\n            // Act\n            IValueProvider valueProvider = factory.GetValueProvider(mockControllerContext.Object);\n\n            // Assert\n            Assert.Equal(typeof(JQueryFormValueProvider), valueProvider.GetType());\n            ValueProviderResult vpResult = valueProvider.GetValue(\"fooArray[0].bar1\");\n\n            Assert.NotNull(vpResult);\n            Assert.Equal(\"fooArrayValue\", vpResult.AttemptedValue);\n            Assert.Equal(CultureInfo.CurrentCulture, vpResult.Culture);\n        }\n\n        [Fact]\n        public void GetValueProvider_GetValue_SkipValidation()\n        {\n            // Arrange\n            Mock<MockableUnvalidatedRequestValues> mockUnvalidatedValues = new Mock<MockableUnvalidatedRequestValues>();\n            mockUnvalidatedValues.Setup(o => o.Form).Returns(_unvalidatedBackingStore);\n            JQueryFormValueProviderFactory factory = \n                        new JQueryFormValueProviderFactory(_ => mockUnvalidatedValues.Object);\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(o => o.HttpContext.Request.Form).Returns(_backingStore);\n\n            // Act\n            IUnvalidatedValueProvider valueProvider = \n                        (IUnvalidatedValueProvider)factory.GetValueProvider(mockControllerContext.Object);\n\n            // Assert\n            Assert.Equal(typeof(JQueryFormValueProvider), valueProvider.GetType());\n            ValueProviderResult vpResult = valueProvider.GetValue(\"fooArray[0].bar1[0].nested\", skipValidation: true);\n\n            Assert.NotNull(vpResult);\n            Assert.Equal(\"fooNestedUnvalidatedValue\", vpResult.AttemptedValue);\n            Assert.Equal(CultureInfo.CurrentCulture, vpResult.Culture);\n        }\n\n        [Fact]\n        public void GetValueProvider_ThrowsIfControllerContextIsNull()\n        {\n            // Arrange\n            JQueryFormValueProviderFactory factory = new JQueryFormValueProviderFactory();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { factory.GetValueProvider(null); }, \"controllerContext\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/JavaScriptResultTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class JavaScriptResultTest\n    {\n        [Fact]\n        public void AllPropertiesDefaultToNull()\n        {\n            // Act\n            JavaScriptResult result = new JavaScriptResult();\n\n            // Assert\n            Assert.Null(result.Script);\n        }\n\n        [Fact]\n        public void ExecuteResult()\n        {\n            // Arrange\n            string script = \"alert('foo');\";\n            string contentType = \"application/x-javascript\";\n\n            // Arrange expectations\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>(MockBehavior.Strict);\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType = contentType).Verifiable();\n            mockControllerContext.Setup(c => c.HttpContext.Response.Write(script)).Verifiable();\n\n            JavaScriptResult result = new JavaScriptResult\n            {\n                Script = script\n            };\n\n            // Act\n            result.ExecuteResult(mockControllerContext.Object);\n\n            // Assert\n            mockControllerContext.Verify();\n        }\n\n        [Fact]\n        public void ExecuteResultWithNullContextThrows()\n        {\n            Assert.ThrowsArgumentNull(\n                delegate { new JavaScriptResult().ExecuteResult(null /* context */); }, \"context\");\n        }\n\n        [Fact]\n        public void NullScriptIsNotOutput()\n        {\n            // Arrange\n            string contentType = \"application/x-javascript\";\n\n            // Arrange expectations\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType = contentType).Verifiable();\n\n            JavaScriptResult result = new JavaScriptResult();\n\n            // Act\n            result.ExecuteResult(mockControllerContext.Object);\n\n            // Assert\n            mockControllerContext.Verify();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/JsonResultTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Text;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class JsonResultTest\n    {\n        private static readonly object _jsonData = new object[] { 1, 2, \"three\", \"four\" };\n        private static readonly string _jsonSerializedData = \"[1,2,\\\"three\\\",\\\"four\\\"]\";\n\n        [Fact]\n        public void PropertyDefaults()\n        {\n            // Act\n            JsonResult result = new JsonResult();\n\n            // Assert\n            Assert.Null(result.Data);\n            Assert.Null(result.ContentEncoding);\n            Assert.Null(result.ContentType);\n            Assert.Null(result.MaxJsonLength);\n            Assert.Null(result.RecursionLimit);\n            Assert.Equal(JsonRequestBehavior.DenyGet, result.JsonRequestBehavior);\n        }\n\n        [Fact]\n        public void EmptyContentTypeRendersDefault()\n        {\n            // Arrange\n            object data = _jsonData;\n            Encoding contentEncoding = Encoding.UTF8;\n\n            // Arrange expectations\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>(MockBehavior.Strict);\n            mockControllerContext.SetupGet(c => c.HttpContext.Request.HttpMethod).Returns(\"POST\").Verifiable();\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType = \"application/json\").Verifiable();\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentEncoding = contentEncoding).Verifiable();\n            mockControllerContext.Setup(c => c.HttpContext.Response.Write(_jsonSerializedData)).Verifiable();\n\n            JsonResult result = new JsonResult\n            {\n                Data = data,\n                ContentType = String.Empty,\n                ContentEncoding = contentEncoding\n            };\n\n            // Act\n            result.ExecuteResult(mockControllerContext.Object);\n\n            // Assert\n            mockControllerContext.Verify();\n        }\n\n        [Fact]\n        public void ExecuteResult()\n        {\n            // Arrange\n            object data = _jsonData;\n            string contentType = \"Some content type.\";\n            Encoding contentEncoding = Encoding.UTF8;\n\n            // Arrange expectations\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>(MockBehavior.Strict);\n            mockControllerContext.SetupGet(c => c.HttpContext.Request.HttpMethod).Returns(\"POST\").Verifiable();\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType = contentType).Verifiable();\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentEncoding = contentEncoding).Verifiable();\n            mockControllerContext.Setup(c => c.HttpContext.Response.Write(_jsonSerializedData)).Verifiable();\n\n            JsonResult result = new JsonResult\n            {\n                Data = data,\n                ContentType = contentType,\n                ContentEncoding = contentEncoding\n            };\n\n            // Act\n            result.ExecuteResult(mockControllerContext.Object);\n\n            // Assert\n            mockControllerContext.Verify();\n        }\n\n        [Fact]\n        public void ExecuteResultWithNullContextThrows()\n        {\n            Assert.ThrowsArgumentNull(\n                delegate { new JsonResult().ExecuteResult(null /* context */); }, \"context\");\n        }\n\n        [Fact]\n        public void NullContentIsNotOutput()\n        {\n            // Arrange\n            string contentType = \"Some content type.\";\n            Encoding contentEncoding = Encoding.UTF8;\n\n            // Arrange expectations\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>(MockBehavior.Strict);\n            mockControllerContext.SetupGet(c => c.HttpContext.Request.HttpMethod).Returns(\"POST\").Verifiable();\n\n            // Though most other tests run fine with SetupSet(c => c.HttpContext.Response.ContentType = ...), this\n            // one does not. Explicitly ensure Response property is not null.\n            var response = new Mock<HttpResponseBase>(MockBehavior.Strict);\n            response.SetupSet(r => r.ContentType = contentType).Verifiable();\n            response.SetupSet(r => r.ContentEncoding = contentEncoding).Verifiable();\n            mockControllerContext.SetupGet(c => c.HttpContext.Response).Returns(response.Object);\n\n            JsonResult result = new JsonResult\n            {\n                ContentType = contentType,\n                ContentEncoding = contentEncoding\n            };\n\n            // Act\n            result.ExecuteResult(mockControllerContext.Object);\n\n            // Assert\n            mockControllerContext.Verify();\n            response.Verify();\n        }\n\n        [Fact]\n        public void NullContentEncodingIsNotOutput()\n        {\n            // Arrange\n            object data = _jsonData;\n            string contentType = \"Some content type.\";\n\n            // Arrange expectations\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>(MockBehavior.Strict);\n            mockControllerContext.SetupGet(c => c.HttpContext.Request.HttpMethod).Returns(\"POST\").Verifiable();\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType = contentType).Verifiable();\n            mockControllerContext.Setup(c => c.HttpContext.Response.Write(_jsonSerializedData)).Verifiable();\n\n            JsonResult result = new JsonResult\n            {\n                Data = data,\n                ContentType = contentType,\n            };\n\n            // Act\n            result.ExecuteResult(mockControllerContext.Object);\n\n            // Assert\n            mockControllerContext.Verify();\n        }\n\n        [Fact]\n        public void NullContentTypeRendersDefault()\n        {\n            // Arrange\n            object data = _jsonData;\n            Encoding contentEncoding = Encoding.UTF8;\n\n            // Arrange expectations\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>(MockBehavior.Strict);\n            mockControllerContext.SetupGet(c => c.HttpContext.Request.HttpMethod).Returns(\"POST\").Verifiable();\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType = \"application/json\").Verifiable();\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentEncoding = contentEncoding).Verifiable();\n            mockControllerContext.Setup(c => c.HttpContext.Response.Write(_jsonSerializedData)).Verifiable();\n\n            JsonResult result = new JsonResult\n            {\n                Data = data,\n                ContentEncoding = contentEncoding\n            };\n\n            // Act\n            result.ExecuteResult(mockControllerContext.Object);\n\n            // Assert\n            mockControllerContext.Verify();\n        }\n\n        [Fact]\n        public void NullMaxJsonLengthDefaultIsUsed()\n        {\n            // Arrange\n            string data = new String('1', 2100000);\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>(MockBehavior.Strict);\n            mockControllerContext.SetupGet(c => c.HttpContext.Request.HttpMethod).Returns(\"POST\");\n\n            // Though most other tests run fine with SetupSet(c => c.HttpContext.Response.ContentType = ...), this\n            // one does not. Explicitly ensure Response property is not null.\n            var response = new Mock<HttpResponseBase>(MockBehavior.Strict);\n            response.SetupSet(r => r.ContentType = \"application/json\");\n            mockControllerContext.SetupGet(c => c.HttpContext.Response).Returns(response.Object);\n\n            JsonResult result = new JsonResult\n            {\n                Data = data\n            };\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => result.ExecuteResult(mockControllerContext.Object),\n                \"Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.\");\n        }\n\n        [Fact]\n        public void MaxJsonLengthIsPassedToSerializer()\n        {\n            // Arrange\n            string data = new String('1', 2100000);\n            string jsonData = \"\\\"\" + data + \"\\\"\";\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.SetupGet(c => c.HttpContext.Request.HttpMethod).Returns(\"POST\").Verifiable();\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType = \"application/json\").Verifiable();\n            mockControllerContext.Setup(c => c.HttpContext.Response.Write(jsonData)).Verifiable();\n\n            JsonResult result = new JsonResult\n            {\n                Data = data,\n                MaxJsonLength = 2200000\n            };\n\n            // Act\n            result.ExecuteResult(mockControllerContext.Object);\n\n            // Assert\n            mockControllerContext.Verify();\n        }\n\n        [Fact]\n        public void RecursionLimitIsPassedToSerilizer()\n        {\n            // Arrange\n            Tuple<string, Tuple<string, Tuple<string, string>>> data =\n                new Tuple<string, Tuple<string, Tuple<string, string>>>(\"key1\",\n                                                                        new Tuple<string, Tuple<string, string>>(\"key2\",\n                                                                                                                 new Tuple<string, string>(\"key3\", \"value\")\n                                                                            )\n                    );\n            string jsonData = \"{\\\"Item1\\\":\\\"key1\\\",\\\"Item2\\\":{\\\"Item1\\\":\\\"key2\\\",\\\"Item2\\\":{\\\"Item1\\\":\\\"key3\\\",\\\"Item2\\\":\\\"value\\\"}}}\";\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.SetupGet(c => c.HttpContext.Request.HttpMethod).Returns(\"POST\").Verifiable();\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType = \"application/json\").Verifiable();\n            mockControllerContext.Setup(c => c.HttpContext.Response.Write(jsonData)).Verifiable();\n\n            JsonResult result = new JsonResult\n            {\n                Data = data,\n                RecursionLimit = 2\n            };\n\n            // Act & Assert\n            Assert.Throws<ArgumentException>(\n                () => result.ExecuteResult(mockControllerContext.Object),\n                \"RecursionLimit exceeded.\");\n        }\n\n        [Fact]\n        public void NullRecursionLimitDefaultIsUsed()\n        {\n            // Arrange\n            Tuple<string, Tuple<string, Tuple<string, string>>> data =\n                new Tuple<string, Tuple<string, Tuple<string, string>>>(\"key1\",\n                                                                        new Tuple<string, Tuple<string, string>>(\"key2\",\n                                                                                                                 new Tuple<string, string>(\"key3\", \"value\")\n                                                                            )\n                    );\n            string jsonData = \"{\\\"Item1\\\":\\\"key1\\\",\\\"Item2\\\":{\\\"Item1\\\":\\\"key2\\\",\\\"Item2\\\":{\\\"Item1\\\":\\\"key3\\\",\\\"Item2\\\":\\\"value\\\"}}}\";\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.SetupGet(c => c.HttpContext.Request.HttpMethod).Returns(\"POST\").Verifiable();\n            mockControllerContext.SetupSet(c => c.HttpContext.Response.ContentType = \"application/json\").Verifiable();\n            mockControllerContext.Setup(c => c.HttpContext.Response.Write(jsonData)).Verifiable();\n\n            JsonResult result = new JsonResult\n            {\n                Data = data\n            };\n\n            // Act\n            result.ExecuteResult(mockControllerContext.Object);\n\n            // Assert\n            mockControllerContext.Verify();\n        }\n\n        [Fact]\n        public void GetRequestBlocked()\n        {\n            // Arrange expectations\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>(MockBehavior.Strict);\n            mockControllerContext.SetupGet(c => c.HttpContext.Request.HttpMethod).Returns(\"GET\").Verifiable();\n\n            JsonResult result = new JsonResult();\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => result.ExecuteResult(mockControllerContext.Object),\n                \"This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.\");\n\n            mockControllerContext.Verify();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/JsonValueProviderFactoryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.IO;\nusing System.Text;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class JsonValueProviderFactoryTest\n    {\n        [Fact]\n        public void GetValueProvider_NullControllerContext_ThrowsException()\n        {\n            JsonValueProviderFactory factory = new JsonValueProviderFactory();\n\n            Assert.ThrowsArgumentNull(delegate() { factory.GetValueProvider(controllerContext: null); }, \"controllerContext\");\n        }\n\n        [Fact]\n        public void GetValueProvider_SimpleArrayJsonObject()\n        {\n            const string jsonString = @\"\n[ \"\"abc\"\", null, \"\"foobar\"\" ]\n\";\n            ControllerContext cc = GetJsonEnabledControllerContext(jsonString);\n            JsonValueProviderFactory factory = new JsonValueProviderFactory();\n\n            // Act & assert\n            IValueProvider valueProvider = factory.GetValueProvider(cc);\n            Assert.True(valueProvider.ContainsPrefix(\"[0]\"));\n            Assert.True(valueProvider.ContainsPrefix(\"[2]\"));\n            Assert.False(valueProvider.ContainsPrefix(\"[3]\"));\n\n            ValueProviderResult vpResult1 = valueProvider.GetValue(\"[0]\");\n            Assert.Equal(\"abc\", vpResult1.AttemptedValue);\n            Assert.Equal(CultureInfo.CurrentCulture, vpResult1.Culture);\n\n            // null values should exist in the backing store as actual entries\n            ValueProviderResult vpResult2 = valueProvider.GetValue(\"[1]\");\n            Assert.NotNull(vpResult2);\n            Assert.Null(vpResult2.RawValue);\n        }\n\n        [Fact]\n        public void GetValueProvider_SimpleDictionaryJsonObject()\n        {\n            const string jsonString = @\"\n{   \"\"FirstName\"\":\"\"John\"\",\n    \"\"LastName\"\": \"\"Doe\"\"\n}\";\n\n            ControllerContext cc = GetJsonEnabledControllerContext(jsonString);\n            JsonValueProviderFactory factory = new JsonValueProviderFactory();\n\n            // Act & assert\n            IValueProvider valueProvider = factory.GetValueProvider(cc);\n            Assert.True(valueProvider.ContainsPrefix(\"firstname\"));\n\n            ValueProviderResult vpResult1 = valueProvider.GetValue(\"firstname\");\n            Assert.Equal(\"John\", vpResult1.AttemptedValue);\n            Assert.Equal(CultureInfo.CurrentCulture, vpResult1.Culture);\n        }\n\n        [Fact]\n        public void GetValueProvider_ComplexJsonObject()\n        {\n            // Arrange\n            const string jsonString = @\"\n[\n  { \n    \"\"BillingAddress\"\": {\n      \"\"Street\"\": \"\"1 Microsoft Way\"\",\n      \"\"City\"\": \"\"Redmond\"\",\n      \"\"State\"\": \"\"WA\"\",\n      \"\"ZIP\"\": 98052 },\n    \"\"ShippingAddress\"\": { \n      \"\"Street\"\": \"\"123 Anywhere Ln\"\",\n      \"\"City\"\": \"\"Anytown\"\",\n      \"\"State\"\": \"\"ZZ\"\",\n      \"\"ZIP\"\": 99999 }\n  },\n  { \n    \"\"Enchiladas\"\": [ \"\"Delicious\"\", \"\"Nutritious\"\"]\n  }\n]\n\";\n\n            ControllerContext cc = GetJsonEnabledControllerContext(jsonString);\n            JsonValueProviderFactory factory = new JsonValueProviderFactory();\n\n            // Act & assert\n            IValueProvider valueProvider = factory.GetValueProvider(cc);\n            Assert.NotNull(valueProvider);\n\n            Assert.True(valueProvider.ContainsPrefix(\"[0].billingaddress\"));\n            Assert.Null(valueProvider.GetValue(\"[0].billingaddress\"));\n\n            Assert.True(valueProvider.ContainsPrefix(\"[0].billingaddress.street\"));\n            Assert.NotNull(valueProvider.GetValue(\"[0].billingaddress.street\"));\n\n            ValueProviderResult vpResult1 = valueProvider.GetValue(\"[1].enchiladas[0]\");\n            Assert.NotNull(vpResult1);\n            Assert.Equal(\"Delicious\", vpResult1.AttemptedValue);\n            Assert.Equal(CultureInfo.CurrentCulture, vpResult1.Culture);\n        }\n\n        [Fact]\n        public void GetValueProvider_NoJsonBody_ReturnsNull()\n        {\n            // Arrange\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(o => o.HttpContext.Request.ContentType).Returns(\"application/json\");\n            mockControllerContext.Setup(o => o.HttpContext.Request.InputStream).Returns(new MemoryStream());\n\n            JsonValueProviderFactory factory = new JsonValueProviderFactory();\n\n            // Act\n            IValueProvider valueProvider = factory.GetValueProvider(mockControllerContext.Object);\n\n            // Assert\n            Assert.Null(valueProvider);\n        }\n\n        [Fact]\n        public void GetValueProvider_NotJsonRequest_ReturnsNull()\n        {\n            // Arrange\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(o => o.HttpContext.Request.ContentType).Returns(\"not JSON\");\n\n            JsonValueProviderFactory factory = new JsonValueProviderFactory();\n\n            // Act\n            IValueProvider valueProvider = factory.GetValueProvider(mockControllerContext.Object);\n\n            // Assert\n            Assert.Null(valueProvider);\n        }\n\n        private static ControllerContext GetJsonEnabledControllerContext(string jsonString)\n        {\n            byte[] jsonBytes = Encoding.UTF8.GetBytes(jsonString);\n            MemoryStream jsonStream = new MemoryStream(jsonBytes);\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(o => o.HttpContext.Request.ContentType).Returns(\"application/json\");\n            mockControllerContext.Setup(o => o.HttpContext.Request.InputStream).Returns(jsonStream);\n            return mockControllerContext.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/LinqBinaryModelBinderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Data.Linq;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace System.Web.Mvc.Test\n{\n    public class LinqBinaryModelBinderTest\n    {\n        [Fact]\n        public void BindModelWithNonExistentValueReturnsNull()\n        {\n            // Arrange\n            SimpleValueProvider valueProvider = new SimpleValueProvider()\n            {\n                { \"foo\", null }\n            };\n\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelName = \"foo\",\n                ValueProvider = valueProvider\n            };\n\n            LinqBinaryModelBinder binder = new LinqBinaryModelBinder();\n\n            // Act\n            object binderResult = binder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.Null(binderResult);\n        }\n\n        [Fact]\n        public void BinderWithEmptyStringValueReturnsNull()\n        {\n            // Arrange\n            SimpleValueProvider valueProvider = new SimpleValueProvider()\n            {\n                { \"foo\", \"\" }\n            };\n\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelName = \"foo\",\n                ValueProvider = valueProvider\n            };\n\n            LinqBinaryModelBinder binder = new LinqBinaryModelBinder();\n\n            // Act\n            object binderResult = binder.BindModel(null, bindingContext);\n\n            // Assert\n            Assert.Null(binderResult);\n        }\n\n        [Fact]\n        public void BindModelThrowsIfBindingContextIsNull()\n        {\n            // Arrange\n            LinqBinaryModelBinder binder = new LinqBinaryModelBinder();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { binder.BindModel(null, null); }, \"bindingContext\");\n        }\n\n        [Fact]\n        public void BindModelWithBase64QuotedValueReturnsBinary()\n        {\n            // Arrange\n            string base64Value = ByteArrayModelBinderTest.Base64TestString;\n\n            SimpleValueProvider valueProvider = new SimpleValueProvider()\n            {\n                { \"foo\", \"\\\"\" + base64Value + \"\\\"\" }\n            };\n\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelName = \"foo\",\n                ValueProvider = valueProvider\n            };\n\n            LinqBinaryModelBinder binder = new LinqBinaryModelBinder();\n\n            // Act\n            Binary boundValue = binder.BindModel(null, bindingContext) as Binary;\n\n            // Assert\n            Assert.Equal(ByteArrayModelBinderTest.Base64TestBytes, boundValue);\n        }\n\n        [Fact]\n        public void BindModelWithBase64UnquotedValueReturnsBinary()\n        {\n            // Arrange\n            string base64Value = ByteArrayModelBinderTest.Base64TestString;\n            SimpleValueProvider valueProvider = new SimpleValueProvider()\n            {\n                { \"foo\", base64Value }\n            };\n\n            ModelBindingContext bindingContext = new ModelBindingContext()\n            {\n                ModelName = \"foo\",\n                ValueProvider = valueProvider\n            };\n\n            LinqBinaryModelBinder binder = new LinqBinaryModelBinder();\n\n            // Act\n            Binary boundValue = binder.BindModel(null, bindingContext) as Binary;\n\n            // Assert\n            Assert.Equal(ByteArrayModelBinderTest.Base64TestBytes, boundValue);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/MaxLengthAttributeAdapterTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel.DataAnnotations;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")] // Uses ModelMetadataProviders.Current\n    public class MaxLengthAttributeAdapterTest\n    {\n        [Fact]\n        [ReplaceCulture]\n        public void ClientRulesWithMaxLengthAttribute()\n        {\n            // Arrange\n            var metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => null, typeof(string), \"Length\");\n            var context = new ControllerContext();\n            var attribute = new MaxLengthAttribute(10);\n            var adapter = new MaxLengthAttributeAdapter(metadata, context, attribute);\n\n            // Act\n            var rules = adapter.GetClientValidationRules();\n\n            // Assert\n            ModelClientValidationRule rule = Assert.Single(rules);\n            Assert.Equal(\"maxlength\", rule.ValidationType);\n            Assert.Equal(1, rule.ValidationParameters.Count);\n            Assert.Equal(10, rule.ValidationParameters[\"max\"]);\n            Assert.Equal(\"The field Length must be a string or array type with a maximum length of '10'.\", rule.ErrorMessage);\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void ClientRulesWithMaxLengthAttributeAndCustomMessage()\n        {\n            // Arrange\n            string propertyName = \"Length\";\n            string message = \"{0} must be at most {1}\";\n            var metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => null, typeof(string[]), propertyName);\n            var context = new ControllerContext();\n            var attribute = new MaxLengthAttribute(5) { ErrorMessage = message };\n            var adapter = new MaxLengthAttributeAdapter(metadata, context, attribute);\n\n            // Act\n            var rules = adapter.GetClientValidationRules();\n\n            // Assert\n            ModelClientValidationRule rule = Assert.Single(rules);\n            Assert.Equal(\"maxlength\", rule.ValidationType);\n            Assert.Equal(1, rule.ValidationParameters.Count);\n            Assert.Equal(5, rule.ValidationParameters[\"max\"]);\n            Assert.Equal(\"Length must be at most 5\", rule.ErrorMessage);\n        }\n\n\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/MinLengthAttributeAdapterTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel.DataAnnotations;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")] // Uses ModelMetadataProviders.Current\n    public class MinLengthAttributeAdapterTest\n    {\n        [Fact]\n        [ReplaceCulture]\n        public void ClientRulesWithMinLengthAttribute()\n        {\n            // Arrange\n            var metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => null, typeof(string), \"Length\");\n            var context = new ControllerContext();\n            var attribute = new MinLengthAttribute(6);\n            var adapter = new MinLengthAttributeAdapter(metadata, context, attribute);\n\n            // Act\n            var rules = adapter.GetClientValidationRules();\n\n            // Assert\n            ModelClientValidationRule rule = Assert.Single(rules);\n            Assert.Equal(\"minlength\", rule.ValidationType);\n            Assert.Equal(1, rule.ValidationParameters.Count);\n            Assert.Equal(6, rule.ValidationParameters[\"min\"]);\n            Assert.Equal(\"The field Length must be a string or array type with a minimum length of '6'.\", rule.ErrorMessage);\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void ClientRulesWithMinLengthAttributeAndCustomMessage()\n        {\n            // Arrange\n            string propertyName = \"Length\";\n            string message = \"Array must have at least {1} items.\";\n            var metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => null, typeof(int[]), propertyName);\n            var context = new ControllerContext();\n            var attribute = new MinLengthAttribute(2) { ErrorMessage = message };\n            var adapter = new MinLengthAttributeAdapter(metadata, context, attribute);\n\n            // Act\n            var rules = adapter.GetClientValidationRules();\n\n            // Assert\n            ModelClientValidationRule rule = Assert.Single(rules);\n            Assert.Equal(\"minlength\", rule.ValidationType);\n            Assert.Equal(1, rule.ValidationParameters.Count);\n            Assert.Equal(2, rule.ValidationParameters[\"min\"]);\n            Assert.Equal(\"Array must have at least 2 items.\", rule.ErrorMessage);\n        }\n\n\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/MockBuildManager.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Reflection;\n\nnamespace System.Web.Mvc.Test\n{\n    // Custom mock IBuildManager since the mock framework doesn't support mocking internal types\n    public class MockBuildManager : IBuildManager\n    {\n        private Assembly[] _referencedAssemblies;\n\n        private Type _compiledType;\n        private string _expectedVirtualPath;\n        private bool _fileExists = true;\n\n        public readonly Dictionary<string, Stream> CachedFileStore = new Dictionary<string, Stream>(StringComparer.OrdinalIgnoreCase);\n\n        public MockBuildManager()\n            : this(new Assembly[] { typeof(MockBuildManager).Assembly })\n        {\n        }\n\n        public MockBuildManager(Assembly[] referencedAssemblies)\n        {\n            _referencedAssemblies = referencedAssemblies;\n        }\n\n        public MockBuildManager(string expectedVirtualPath, bool fileExists)\n        {\n            _expectedVirtualPath = expectedVirtualPath;\n            _fileExists = fileExists;\n        }\n\n        public MockBuildManager(string expectedVirtualPath, Type compiledType)\n        {\n            _expectedVirtualPath = expectedVirtualPath;\n            _compiledType = compiledType;\n        }\n\n        public virtual bool FileExists(string virtualPath)\n        {\n            if (_expectedVirtualPath == virtualPath)\n            {\n                return _fileExists;\n            }\n\n            throw new InvalidOperationException(\"Unexpected call to IBuildManager.FileExists()\");\n        }\n\n        public Type GetCompiledType(string virtualPath)\n        {\n            if (_expectedVirtualPath == virtualPath)\n            {\n                return _compiledType;\n            }\n\n            throw new InvalidOperationException(\"Unexpected call to IBuildManager.GetCompiledType()\");\n        }\n\n        public virtual ICollection GetReferencedAssemblies()\n        {\n            return _referencedAssemblies;\n        }\n\n        public virtual Stream ReadCachedFile(string fileName)\n        {\n            Stream stream;\n            CachedFileStore.TryGetValue(fileName, out stream);\n            return stream;\n        }\n\n        public virtual Stream CreateCachedFile(string fileName)\n        {\n            MemoryStream stream = new MemoryStream();\n            CachedFileStore[fileName] = stream;\n            return stream;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/MockHelpers.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\nusing Moq.Language.Flow;\n\nnamespace System.Web.Mvc.Test\n{\n    public static class MockHelpers\n    {\n        public static ISetup<HttpContextBase> ExpectMvcVersionResponseHeader(this Mock<HttpContextBase> mock)\n        {\n            Version mvcVersion = VersionTestHelper.GetVersionFromAssembly(\"System.Web.Mvc\", typeof(Controller));\n\n            string majorMinor = mvcVersion.Major + \".\" + mvcVersion.Minor;\n            return mock.Setup(r => r.Response.AppendHeader(MvcHandler.MvcVersionHeaderName, majorMinor));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/MockableUnvalidatedRequestValues.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\n\nnamespace System.Web.Mvc.Test\n{\n    public abstract class MockableUnvalidatedRequestValues : IUnvalidatedRequestValues\n    {\n        public abstract NameValueCollection Form { get; }\n        public abstract NameValueCollection QueryString { get; }\n        public abstract string this[string key] { get; }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ModelBinderAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ModelBinderAttributeTest\n    {\n        [Fact]\n        public void ConstructorWithInvalidBinderTypeThrows()\n        {\n            // Arrange\n            Type badType = typeof(string);\n\n            // Act & Assert\n            Assert.Throws<ArgumentException>(\n                delegate { new ModelBinderAttribute(badType); },\n                \"The type 'System.String' does not implement the IModelBinder interface.\\r\\nParameter name: binderType\");\n        }\n\n        [Fact]\n        public void ConstructorWithNullBinderTypeThrows()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ModelBinderAttribute(null); }, \"binderType\");\n        }\n\n        [Fact]\n        public void BinderTypeProperty()\n        {\n            // Arrange\n            Type binderType = typeof(GoodConverter);\n            ModelBinderAttribute attr = new ModelBinderAttribute(binderType);\n\n            // Act & Assert\n            Assert.Same(binderType, attr.BinderType);\n        }\n\n        [Fact]\n        public void GetBinder()\n        {\n            // Arrange\n            ModelBinderAttribute attr = new ModelBinderAttribute(typeof(GoodConverter));\n\n            // Act\n            IModelBinder binder = attr.GetBinder();\n\n            // Assert\n            Assert.IsType<GoodConverter>(binder);\n        }\n\n        [Fact]\n        public void GetBinderWithBadConstructorThrows()\n        {\n            // Arrange\n            ModelBinderAttribute attr = new ModelBinderAttribute(typeof(BadConverter));\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { attr.GetBinder(); },\n                \"An error occurred when trying to create the IModelBinder 'System.Web.Mvc.Test.ModelBinderAttributeTest+BadConverter'. Make sure that the binder has a public parameterless constructor.\");\n        }\n\n        private class GoodConverter : IModelBinder\n        {\n            public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class BadConverter : IModelBinder\n        {\n            // no public parameterless constructor\n            public BadConverter(string s)\n            {\n            }\n\n            public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ModelBinderDictionaryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ModelBinderDictionaryTest\n    {\n        [Fact]\n        public void DefaultBinderIsInstanceOfDefaultModelBinder()\n        {\n            // Arrange\n            ModelBinderDictionary binders = new ModelBinderDictionary();\n\n            // Act\n            IModelBinder defaultBinder = binders.DefaultBinder;\n\n            // Assert\n            Assert.IsType<DefaultModelBinder>(defaultBinder);\n        }\n\n        [Fact]\n        public void DefaultBinderProperty()\n        {\n            // Arrange\n            ModelBinderDictionary binders = new ModelBinderDictionary();\n            IModelBinder binder = new Mock<IModelBinder>().Object;\n\n            // Act & assert\n            MemberHelper.TestPropertyWithDefaultInstance(binders, \"DefaultBinder\", binder);\n        }\n\n        [Fact]\n        public void DictionaryInterface()\n        {\n            // Arrange\n            DictionaryHelper<Type, IModelBinder> helper = new DictionaryHelper<Type, IModelBinder>()\n            {\n                Creator = () => new ModelBinderDictionary(),\n                SampleKeys = new Type[] { typeof(object), typeof(string), typeof(int), typeof(long), typeof(long) },\n                SampleValues = new IModelBinder[] { new DefaultModelBinder(), new DefaultModelBinder(), new DefaultModelBinder(), new DefaultModelBinder(), new DefaultModelBinder() },\n                ThrowOnKeyNotFound = false\n            };\n\n            // Act & assert\n            helper.Execute();\n        }\n\n        [Fact]\n        public void GetBinderConsultsProviders()\n        {\n            // Arrange\n            Type modelType = typeof(string);\n            IModelBinder expectedBinderFromProvider = new Mock<IModelBinder>().Object;\n\n            Mock<IModelBinderProvider> locatedProvider = new Mock<IModelBinderProvider>();\n            locatedProvider.Setup(p => p.GetBinder(modelType))\n                .Returns(expectedBinderFromProvider);\n\n            Mock<IModelBinderProvider> secondProvider = new Mock<IModelBinderProvider>();\n\n            ModelBinderProviderCollection providers = new ModelBinderProviderCollection(new IModelBinderProvider[] { locatedProvider.Object, secondProvider.Object });\n            ModelBinderDictionary binders = new ModelBinderDictionary(providers);\n\n            // Act\n            IModelBinder returnedBinder = binders.GetBinder(modelType);\n\n            // Assert\n            Assert.Same(expectedBinderFromProvider, returnedBinder);\n        }\n\n        [Fact]\n        public void GetBinderDoesNotReturnDefaultBinderIfAskedNotTo()\n        {\n            // Proper order of precedence:\n            // 1. Binder registered in the global table\n            // 2. Binder attribute defined on the type\n            // 3. <null>\n\n            // Arrange\n            IModelBinder registeredFirstBinder = new Mock<IModelBinder>().Object;\n            ModelBinderDictionary binders = new ModelBinderDictionary()\n            {\n                { typeof(MyFirstConvertibleType), registeredFirstBinder }\n            };\n\n            // Act\n            IModelBinder binder1 = binders.GetBinder(typeof(MyFirstConvertibleType), false /* fallbackToDefault */);\n            IModelBinder binder2 = binders.GetBinder(typeof(MySecondConvertibleType), false /* fallbackToDefault */);\n            IModelBinder binder3 = binders.GetBinder(typeof(object), false /* fallbackToDefault */);\n\n            // Assert\n            Assert.Same(registeredFirstBinder, binder1);\n            Assert.IsType<MySecondBinder>(binder2);\n            Assert.Null(binder3);\n        }\n\n        [Fact]\n        public void GetBinderResolvesBindersWithCorrectPrecedence()\n        {\n            // Proper order of precedence:\n            // 1. Binder registered in the global table\n            // 2. Binder attribute defined on the type\n            // 3. Default binder\n\n            // Arrange\n            IModelBinder registeredFirstBinder = new Mock<IModelBinder>().Object;\n            ModelBinderDictionary binders = new ModelBinderDictionary()\n            {\n                { typeof(MyFirstConvertibleType), registeredFirstBinder }\n            };\n\n            IModelBinder defaultBinder = new Mock<IModelBinder>().Object;\n            binders.DefaultBinder = defaultBinder;\n\n            // Act\n            IModelBinder binder1 = binders.GetBinder(typeof(MyFirstConvertibleType));\n            IModelBinder binder2 = binders.GetBinder(typeof(MySecondConvertibleType));\n            IModelBinder binder3 = binders.GetBinder(typeof(object));\n\n            // Assert\n            Assert.Same(registeredFirstBinder, binder1);\n            Assert.IsType<MySecondBinder>(binder2);\n            Assert.Same(defaultBinder, binder3);\n        }\n\n        [Fact]\n        public void GetBinderThrowsIfModelTypeContainsMultipleAttributes()\n        {\n            // Arrange\n            ModelBinderDictionary binders = new ModelBinderDictionary();\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { binders.GetBinder(typeof(ConvertibleTypeWithSeveralBinders), true /* fallbackToDefault */); },\n                \"The type 'System.Web.Mvc.Test.ModelBinderDictionaryTest+ConvertibleTypeWithSeveralBinders' contains multiple attributes that inherit from CustomModelBinderAttribute.\");\n        }\n\n        [Fact]\n        public void GetBinderThrowsIfModelTypeIsNull()\n        {\n            // Arrange\n            ModelBinderDictionary binders = new ModelBinderDictionary();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { binders.GetBinder(null); }, \"modelType\");\n        }\n\n        [ModelBinder(typeof(MyFirstBinder))]\n        private class MyFirstConvertibleType\n        {\n        }\n\n        private class MyFirstBinder : IModelBinder\n        {\n            public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        [ModelBinder(typeof(MySecondBinder))]\n        private class MySecondConvertibleType\n        {\n        }\n\n        private class MySecondBinder : IModelBinder\n        {\n            public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        [ModelBinder(typeof(MySecondBinder))]\n        [MySubclassedBinder]\n        private class ConvertibleTypeWithSeveralBinders\n        {\n        }\n\n        private class MySubclassedBinderAttribute : CustomModelBinderAttribute\n        {\n            public override IModelBinder GetBinder()\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ModelBinderProviderCollectionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ModelBinderProviderCollectionTest\n    {\n        [Fact]\n        public void GuardClause()\n        {\n            // Arrange\n            var collection = new ModelBinderProviderCollection();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => collection.GetBinder(null),\n                \"modelType\"\n                );\n        }\n\n        [Fact]\n        public void ModelBinderProviderCollectionCombinedItemsCaches()\n        {\n            // Arrange\n            var providers = new IModelBinderProvider[] \n            {\n                new Mock<IModelBinderProvider>(MockBehavior.Strict).Object, \n                new Mock<IModelBinderProvider>(MockBehavior.Strict).Object\n            };\n            var collection = new ModelBinderProviderCollection(providers);\n\n            // Act\n            var combined1 = collection.CombinedItems;\n            var combined2 = collection.CombinedItems;\n\n            // Assert\n            Assert.Equal(providers, combined1);\n            Assert.Same(combined1, combined2);\n        }\n\n        [Fact]\n        public void ModelBinderProviderCollectionCombinedItemsClearResetsCache()\n        {\n            TestCacheReset((collection) => collection.Clear());\n        }\n\n        [Fact]\n        public void ModelBinderProviderCollectionCombinedItemsInsertResetsCache()\n        {\n            TestCacheReset((collection) => collection.Insert(0, new Mock<IModelBinderProvider>(MockBehavior.Strict).Object));\n        }\n\n        [Fact]\n        public void ModelBinderProviderCollectionCombinedItemsRemoveResetsCache()\n        {\n            TestCacheReset((collection) => collection.RemoveAt(0));\n        }\n\n        [Fact]\n        public void ModelBinderProviderCollectionCombinedItemsSetResetsCache()\n        {\n            TestCacheReset((collection) => collection[0] = new Mock<IModelBinderProvider>(MockBehavior.Strict).Object);\n        }\n\n        private static void TestCacheReset(Action<ModelBinderProviderCollection> mutatingAction)\n        {\n            // Arrange\n            var providers = new List<IModelBinderProvider>() \n            {\n                new Mock<IModelBinderProvider>(MockBehavior.Strict).Object, \n                new Mock<IModelBinderProvider>(MockBehavior.Strict).Object\n            };\n            var collection = new ModelBinderProviderCollection(providers);\n\n            // Act\n            mutatingAction(collection);\n\n            IModelBinderProvider[] combined = collection.CombinedItems;\n\n            // Assert\n            Assert.Equal(providers, combined);\n        }\n\n        [Fact]\n        public void ModelBinderProviderCollectionCombinedItemsDelegatesToResolver()\n        {\n            // Arrange\n            var firstProvider = new Mock<IModelBinderProvider>();\n            var secondProvider = new Mock<IModelBinderProvider>();\n            var thirdProvider = new Mock<IModelBinderProvider>();\n            var dependencyProviders = new IModelBinderProvider[] { firstProvider.Object, secondProvider.Object };\n            var collectionProviders = new IModelBinderProvider[] { thirdProvider.Object };\n            var expectedProviders = new IModelBinderProvider[] { firstProvider.Object, secondProvider.Object, thirdProvider.Object };\n\n            var resolver = new Mock<IDependencyResolver>();\n            resolver.Setup(r => r.GetServices(typeof(IModelBinderProvider))).Returns(dependencyProviders);\n\n            var providers = new ModelBinderProviderCollection(collectionProviders, resolver.Object);\n\n            // Act\n            IModelBinderProvider[] combined = providers.CombinedItems;\n\n            // Assert\n            Assert.Equal(expectedProviders, combined);\n        }\n\n        [Fact]\n        public void GetBinderUsesRegisteredProviders()\n        {\n            // Arrange\n            var testType = typeof(string);\n            var expectedBinder = new Mock<IModelBinder>().Object;\n\n            var provider = new Mock<IModelBinderProvider>(MockBehavior.Strict);\n            provider.Setup(p => p.GetBinder(testType)).Returns(expectedBinder);\n            var collection = new ModelBinderProviderCollection(new[] { provider.Object });\n\n            // Act\n            IModelBinder returnedBinder = collection.GetBinder(testType);\n\n            // Assert\n            Assert.Same(expectedBinder, returnedBinder);\n        }\n\n        [Fact]\n        public void GetBinderReturnsValueFromFirstSuccessfulBinderProvider()\n        {\n            // Arrange\n            var testType = typeof(string);\n            IModelBinder nullModelBinder = null;\n            IModelBinder expectedBinder = new Mock<IModelBinder>().Object;\n            IModelBinder secondMatchingBinder = new Mock<IModelBinder>().Object;\n\n            var provider1 = new Mock<IModelBinderProvider>();\n            provider1.Setup(p => p.GetBinder(testType)).Returns(nullModelBinder);\n\n            var provider2 = new Mock<IModelBinderProvider>(MockBehavior.Strict);\n            provider2.Setup(p => p.GetBinder(testType)).Returns(expectedBinder);\n\n            var provider3 = new Mock<IModelBinderProvider>(MockBehavior.Strict);\n            provider3.Setup(p => p.GetBinder(testType)).Returns(secondMatchingBinder);\n\n            var collection = new ModelBinderProviderCollection(new[] { provider1.Object, provider2.Object, provider3.Object });\n\n            // Act\n            IModelBinder returnedBinder = collection.GetBinder(testType);\n\n            // Assert\n            Assert.Same(expectedBinder, returnedBinder);\n        }\n\n        [Fact]\n        public void GetBinderReturnsNullWhenNoSuccessfulBinderProviders()\n        {\n            // Arrange\n            var testType = typeof(string);\n            IModelBinder nullModelBinder = null;\n\n            var provider1 = new Mock<IModelBinderProvider>();\n            provider1.Setup(p => p.GetBinder(testType)).Returns(nullModelBinder);\n\n            var provider2 = new Mock<IModelBinderProvider>(MockBehavior.Strict);\n            provider2.Setup(p => p.GetBinder(testType)).Returns(nullModelBinder);\n\n            var collection = new ModelBinderProviderCollection(new[] { provider1.Object, provider2.Object });\n\n            // Act\n            IModelBinder returnedBinder = collection.GetBinder(testType);\n\n            // Assert\n            Assert.Null(returnedBinder);\n        }\n\n        [Fact]\n        public void GetBinderDelegatesToResolver()\n        {\n            // Arrange\n            Type modelType = typeof(string);\n            IModelBinder expectedBinder = new Mock<IModelBinder>().Object;\n\n            Mock<IModelBinderProvider> locatedProvider = new Mock<IModelBinderProvider>();\n            locatedProvider.Setup(p => p.GetBinder(modelType))\n                .Returns(expectedBinder);\n\n            Mock<IModelBinderProvider> secondProvider = new Mock<IModelBinderProvider>();\n            Mock<IModelBinderProvider> thirdProvider = new Mock<IModelBinderProvider>();\n            IModelBinderProvider[] dependencyProviders = new IModelBinderProvider[] { locatedProvider.Object, secondProvider.Object };\n            IModelBinderProvider[] collectionProviders = new IModelBinderProvider[] { thirdProvider.Object };\n\n            Mock<IDependencyResolver> resolver = new Mock<IDependencyResolver>();\n            resolver.Setup(r => r.GetServices(typeof(IModelBinderProvider))).Returns(dependencyProviders);\n\n            ModelBinderProviderCollection providers = new ModelBinderProviderCollection(collectionProviders, resolver.Object);\n\n            // Act\n            IModelBinder returnedBinder = providers.GetBinder(modelType);\n\n            // Assert\n            Assert.Same(expectedBinder, returnedBinder);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ModelBinderProvidersTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ModelBinderProvidersTest\n    {\n        [Fact]\n        public void CollectionDefaults()\n        {\n            // Act\n            Type[] actualTypes = ModelBinderProviders.BinderProviders.Select(b => b.GetType()).ToArray();\n\n            // Assert\n            Assert.Equal(Enumerable.Empty<Type>(), actualTypes);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ModelBindersTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel.DataAnnotations;\nusing System.Data.Linq;\nusing System.Reflection;\nusing System.Threading;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ModelBindersTest\n    {\n        [Fact]\n        public void BindersPropertyIsNotNull()\n        {\n            // Arrange & Act\n            ModelBinderDictionary binders = ModelBinders.Binders;\n\n            // Assert\n            Assert.NotNull(binders);\n        }\n\n        [Fact]\n        public void DefaultModelBinders()\n        {\n            // Act\n            ModelBinderDictionary binders = ModelBinders.Binders;\n\n            // Assert\n            Assert.Equal(4, binders.Count);\n            Assert.True(binders.ContainsKey(typeof(byte[])));\n            Assert.IsType<ByteArrayModelBinder>(binders[typeof(byte[])]);\n            Assert.True(binders.ContainsKey(typeof(HttpPostedFileBase)));\n            Assert.IsType<HttpPostedFileBaseModelBinder>(binders[typeof(HttpPostedFileBase)]);\n            Assert.True(binders.ContainsKey(typeof(Binary)));\n            Assert.IsType<LinqBinaryModelBinder>(binders[typeof(Binary)]);\n            Assert.True(binders.ContainsKey(typeof(CancellationToken)));\n            Assert.IsType<CancellationTokenModelBinder>(binders[typeof(CancellationToken)]);\n        }\n\n        [Fact]\n        public void GetBindersFromAttributes_ReadsModelBinderAttributeFromBuddyClass()\n        {\n            Action<Type> errorAction = (Type t) => { throw new InvalidOperationException(); };\n            // Act\n            IModelBinder binder = ModelBinders.GetBinderFromAttributes(typeof(SampleModel), errorAction);\n\n            // Assert\n            Assert.IsType<SampleModelBinder>(binder);\n        }\n\n        [Fact]\n        public void GetBindersFromAttributes_NullIfGetCustomAttributesReturnsNull()\n        {\n            // Arrange\n            var provider = new Mock<ICustomAttributeProvider>(MockBehavior.Strict);\n            bool inherit = true;\n            provider.Setup(p => p.GetCustomAttributes(typeof(CustomModelBinderAttribute), inherit)).Returns((object[])null);\n            Action<ICustomAttributeProvider> errorAction = (ICustomAttributeProvider t) => { throw new InvalidOperationException(); };\n\n            // Act\n            IModelBinder binder = ModelBinders.GetBinderFromAttributes(provider.Object, errorAction);\n\n            // Assert\n            Assert.Null(binder);\n        }\n\n        [MetadataType(typeof(SampleModel_Buddy))]\n        private class SampleModel\n        {\n            [ModelBinder(typeof(SampleModelBinder))]\n            private class SampleModel_Buddy\n            {\n            }\n        }\n\n        private class SampleModelBinder : IModelBinder\n        {\n            public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ModelBindingContextTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\n\nnamespace System.Web.Mvc.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")] // Uses ModelMetadataProviders.Current\n    public class ModelBindingContextTest\n    {\n        [Fact]\n        public void CopyConstructor()\n        {\n            // Arrange\n            ModelBindingContext originalBindingContext = new ModelBindingContext()\n            {\n                FallbackToEmptyPrefix = true,\n                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(object)),\n                ModelName = \"theName\",\n                ModelState = new ModelStateDictionary(),\n                PropertyFilter = _ => false,\n                ValueProvider = new SimpleValueProvider()\n            };\n\n            // Act\n            ModelBindingContext newBindingContext = new ModelBindingContext(originalBindingContext);\n\n            // Assert\n            Assert.False(newBindingContext.FallbackToEmptyPrefix);\n            Assert.Null(newBindingContext.ModelMetadata);\n            Assert.Equal(\"\", newBindingContext.ModelName);\n            Assert.Equal(originalBindingContext.ModelState, newBindingContext.ModelState);\n            Assert.True(newBindingContext.PropertyFilter(\"foo\"));\n            Assert.Equal(originalBindingContext.ValueProvider, newBindingContext.ValueProvider);\n        }\n\n        [Fact]\n        public void ModelNameProperty()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext();\n\n            // Act & assert\n            MemberHelper.TestStringProperty(bindingContext, \"ModelName\", String.Empty);\n        }\n\n        [Fact]\n        public void ModelStateProperty()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext();\n            ModelStateDictionary modelState = new ModelStateDictionary();\n\n            // Act & assert\n            MemberHelper.TestPropertyWithDefaultInstance(bindingContext, \"ModelState\", modelState);\n        }\n\n        [Fact]\n        public void PropertyFilterPropertyDefaultInstanceReturnsTrueForAnyInput()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext();\n\n            // Act\n            Predicate<string> propertyFilter = bindingContext.PropertyFilter;\n\n            // Assert\n            // We can't test all inputs, but at least this gives us high confidence that we ignore the parameter by default\n            Assert.True(propertyFilter(null));\n            Assert.True(propertyFilter(String.Empty));\n            Assert.True(propertyFilter(\"Foo\"));\n        }\n\n        [Fact]\n        public void PropertyFilterPropertyReturnsDefaultInstance()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext();\n            Predicate<string> propertyFilter = _ => true;\n\n            // Act & assert\n            MemberHelper.TestPropertyWithDefaultInstance(bindingContext, \"PropertyFilter\", propertyFilter);\n        }\n\n        [Fact]\n        public void ModelAndModelTypeAreFedFromModelMetadata()\n        {\n            // Act\n            ModelBindingContext bindingContext = new ModelBindingContext\n            {\n                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => 42, typeof(int))\n            };\n\n            // Assert\n            Assert.Equal(42, bindingContext.Model);\n            Assert.Equal(typeof(int), bindingContext.ModelType);\n        }\n\n        [Fact]\n        public void ModelIsNotSettable()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext();\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => bindingContext.Model = \"foo\",\n                \"This property setter is obsolete, because its value is derived from ModelMetadata.Model now.\");\n        }\n\n        [Fact]\n        public void ModelTypeIsNotSettable()\n        {\n            // Arrange\n            ModelBindingContext bindingContext = new ModelBindingContext();\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => bindingContext.ModelType = typeof(string),\n                \"This property setter is obsolete, because its value is derived from ModelMetadata.Model now.\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ModelClientValidationRuleTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ModelClientValidationRuleTest\n    {\n        [Fact]\n        public void ValidationParametersProperty()\n        {\n            // Arrange\n            ModelClientValidationRule rule = new ModelClientValidationRule();\n\n            // Act\n            IDictionary<string, object> parameters = rule.ValidationParameters;\n\n            // Assert\n            Assert.NotNull(parameters);\n            Assert.Empty(parameters);\n        }\n\n        [Fact]\n        public void ValidationTypeProperty()\n        {\n            // Arrange\n            ModelClientValidationRule rule = new ModelClientValidationRule();\n\n            // Act & assert\n            MemberHelper.TestStringProperty(rule, \"ValidationType\", String.Empty);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ModelErrorCollectionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ModelErrorCollectionTest\n    {\n        [Fact]\n        public void AddWithExceptionArgument()\n        {\n            // Arrange\n            ModelErrorCollection collection = new ModelErrorCollection();\n            Exception ex = new Exception(\"some message\");\n\n            // Act\n            collection.Add(ex);\n\n            // Assert\n            ModelError modelError = Assert.Single(collection);\n            Assert.Same(ex, modelError.Exception);\n        }\n\n        [Fact]\n        public void AddWithStringArgument()\n        {\n            // Arrange\n            ModelErrorCollection collection = new ModelErrorCollection();\n\n            // Act\n            collection.Add(\"some message\");\n\n            // Assert\n            ModelError modelError = Assert.Single(collection);\n            Assert.Equal(\"some message\", modelError.ErrorMessage);\n            Assert.Null(modelError.Exception);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ModelErrorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ModelErrorTest\n    {\n        [Fact]\n        public void ConstructorThrowsIfExceptionIsNull()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ModelError((Exception)null); }, \"exception\");\n        }\n\n        [Fact]\n        public void ConstructorWithExceptionAndStringArguments()\n        {\n            // Arrange\n            Exception ex = new Exception(\"some message\");\n\n            // Act\n            ModelError modelError = new ModelError(ex, \"some other message\");\n\n            // Assert\n            Assert.Equal(\"some other message\", modelError.ErrorMessage);\n            Assert.Same(ex, modelError.Exception);\n        }\n\n        [Fact]\n        public void ConstructorWithExceptionArgument()\n        {\n            // Arrange\n            Exception ex = new Exception(\"some message\");\n\n            // Act\n            ModelError modelError = new ModelError(ex);\n\n            // Assert\n            Assert.Equal(String.Empty, modelError.ErrorMessage);\n            Assert.Same(ex, modelError.Exception);\n        }\n\n        [Fact]\n        public void ConstructorWithNullStringArgumentCreatesEmptyStringErrorMessage()\n        {\n            // Act\n            ModelError modelError = new ModelError((string)null);\n\n            // Assert\n            Assert.Equal(String.Empty, modelError.ErrorMessage);\n        }\n\n        [Fact]\n        public void ConstructorWithStringArgument()\n        {\n            // Act\n            ModelError modelError = new ModelError(\"some message\");\n\n            // Assert\n            Assert.Equal(\"some message\", modelError.ErrorMessage);\n            Assert.Null(modelError.Exception);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ModelMetadataProvidersTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ModelMetadataProvidersTest\n    {\n        [Fact]\n        public void DefaultModelMetadataProviderIsCachedDataAnnotations()\n        {\n            // Arrange\n            ModelMetadataProviders providers = new ModelMetadataProviders();\n\n            // Act\n            ModelMetadataProvider provider = providers.CurrentInternal;\n\n            // Assert\n            Assert.IsType<CachedDataAnnotationsModelMetadataProvider>(provider);\n        }\n\n        [Fact]\n        public void SettingModelMetadataProviderReturnsSetProvider()\n        {\n            // Arrange\n            ModelMetadataProviders providers = new ModelMetadataProviders();\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n\n            // Act\n            providers.CurrentInternal = provider.Object;\n\n            // Assert\n            Assert.Same(provider.Object, providers.CurrentInternal);\n        }\n\n        [Fact]\n        public void SettingNullModelMetadataProviderUsesEmptyModelMetadataProvider()\n        {\n            // Arrange\n            ModelMetadataProviders providers = new ModelMetadataProviders();\n\n            // Act\n            providers.CurrentInternal = null;\n\n            // Assert\n            Assert.IsType<EmptyModelMetadataProvider>(providers.CurrentInternal);\n        }\n\n        [Fact]\n        public void ModelMetadataProvidersCurrentDelegatesToResolver()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            Resolver<ModelMetadataProvider> resolver = new Resolver<ModelMetadataProvider> { Current = provider.Object };\n            ModelMetadataProviders providers = new ModelMetadataProviders(resolver);\n\n            // Act\n            ModelMetadataProvider result = providers.CurrentInternal;\n\n            // Assert\n            Assert.Same(provider.Object, result);\n        }\n\n        private class Resolver<T> : IResolver<T>\n        {\n            public T Current { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ModelMetadataTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing System.Linq.Expressions;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")] // Uses ModelMetadataProviders.Current\n    public class ModelMetadataTest\n    {\n        // Guard clauses\n\n        [Fact]\n        public void NullProviderThrows()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => new ModelMetadata(null /* provider */, null /* containerType */, null /* model */, typeof(object), null /* propertyName */),\n                \"provider\");\n        }\n\n        [Fact]\n        public void NullTypeThrows()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => new ModelMetadata(provider.Object, null /* containerType */, null /* model */, null /* modelType */, null /* propertyName */),\n                \"modelType\");\n        }\n\n        // Constructor\n\n        [Fact]\n        public void DefaultValues()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n\n            // Act\n            ModelMetadata metadata = new ModelMetadata(provider.Object, typeof(Exception), () => \"model\", typeof(string), \"propertyName\");\n\n            // Assert\n            Assert.Equal(typeof(Exception), metadata.ContainerType);\n            Assert.True(metadata.ConvertEmptyStringToNull);\n            Assert.Null(metadata.DataTypeName);\n            Assert.Null(metadata.Description);\n            Assert.Null(metadata.DisplayFormatString);\n            Assert.Null(metadata.DisplayName);\n            Assert.Null(metadata.EditFormatString);\n            Assert.False(metadata.HasNonDefaultEditFormat);\n            Assert.False(metadata.HideSurroundingHtml);\n            Assert.True(metadata.HtmlEncode);\n            Assert.Equal(\"model\", metadata.Model);\n            Assert.Equal(typeof(string), metadata.ModelType);\n            Assert.Null(metadata.NullDisplayText);\n            Assert.Equal(10000, metadata.Order);\n            Assert.Equal(\"propertyName\", metadata.PropertyName);\n            Assert.False(metadata.IsReadOnly);\n            Assert.True(metadata.RequestValidationEnabled);\n            Assert.Null(metadata.ShortDisplayName);\n            Assert.True(metadata.ShowForDisplay);\n            Assert.True(metadata.ShowForEdit);\n            Assert.Null(metadata.TemplateHint);\n            Assert.Null(metadata.Watermark);\n        }\n\n        // IsComplexType\n\n        struct IsComplexTypeModel\n        {\n        }\n\n        [Fact]\n        public void IsComplexTypeTests()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n\n            // Act & Assert\n            Assert.True(new ModelMetadata(provider.Object, null, null, typeof(Object), null).IsComplexType);\n            Assert.False(new ModelMetadata(provider.Object, null, null, typeof(string), null).IsComplexType);\n            Assert.True(new ModelMetadata(provider.Object, null, null, typeof(IDisposable), null).IsComplexType);\n            Assert.False(new ModelMetadata(provider.Object, null, null, typeof(Nullable<int>), null).IsComplexType);\n            Assert.False(new ModelMetadata(provider.Object, null, null, typeof(int), null).IsComplexType);\n            Assert.True(new ModelMetadata(provider.Object, null, null, typeof(IsComplexTypeModel), null).IsComplexType);\n            Assert.True(new ModelMetadata(provider.Object, null, null, typeof(Nullable<IsComplexTypeModel>), null).IsComplexType);\n        }\n\n        // IsNullableValueType\n\n        [Fact]\n        public void IsNullableValueTypeTests()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n\n            // Act & Assert\n            Assert.False(new ModelMetadata(provider.Object, null, null, typeof(string), null).IsNullableValueType);\n            Assert.False(new ModelMetadata(provider.Object, null, null, typeof(IDisposable), null).IsNullableValueType);\n            Assert.True(new ModelMetadata(provider.Object, null, null, typeof(Nullable<int>), null).IsNullableValueType);\n            Assert.False(new ModelMetadata(provider.Object, null, null, typeof(int), null).IsNullableValueType);\n        }\n\n        // IsRequired\n\n        [Fact]\n        public void IsRequiredTests()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n\n            // Act & Assert\n            Assert.False(new ModelMetadata(provider.Object, null, null, typeof(string), null).IsRequired); // Reference type not required\n            Assert.False(new ModelMetadata(provider.Object, null, null, typeof(IDisposable), null).IsRequired); // Interface not required\n            Assert.False(new ModelMetadata(provider.Object, null, null, typeof(Nullable<int>), null).IsRequired); // Nullable value type not required\n            Assert.True(new ModelMetadata(provider.Object, null, null, typeof(int), null).IsRequired); // Value type required\n            Assert.True(new ModelMetadata(provider.Object, null, null, typeof(DayOfWeek), null).IsRequired); // Enum (implicit value type) is required\n        }\n\n        // Properties\n\n        [Fact]\n        public void PropertiesCallsProvider()\n        {\n            // Arrange\n            Type modelType = typeof(string);\n            List<ModelMetadata> propertyMetadata = new List<ModelMetadata>();\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            ModelMetadata metadata = new ModelMetadata(provider.Object, null, null, modelType, null);\n            provider.Setup(p => p.GetMetadataForProperties(null, modelType))\n                .Returns(propertyMetadata)\n                .Verifiable();\n\n            // Act\n            IEnumerable<ModelMetadata> result = metadata.Properties;\n\n            // Assert\n            Assert.Equal(propertyMetadata, result.ToList());\n            provider.Verify();\n        }\n\n        [Fact]\n        public void PropertiesUsesRealModelTypeRatherThanPassedModelType()\n        {\n            // Arrange\n            string model = \"String Value\";\n            Expression<Func<object, object>> accessor = _ => model;\n            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(accessor, new ViewDataDictionary<object>());\n\n            // Act\n            IEnumerable<ModelMetadata> result = metadata.Properties;\n\n            // Assert\n            Assert.Equal(\"Length\", result.Single().PropertyName);\n        }\n\n        [Fact]\n        public void PropertiesAreSortedByOrder()\n        {\n            // Arrange\n            Type modelType = typeof(string);\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            List<ModelMetadata> propertyMetadata = new List<ModelMetadata>\n            {\n                new ModelMetadata(provider.Object, null, () => 1, typeof(int), null) { Order = 20 },\n                new ModelMetadata(provider.Object, null, () => 2, typeof(int), null) { Order = 30 },\n                new ModelMetadata(provider.Object, null, () => 3, typeof(int), null) { Order = 10 },\n            };\n            ModelMetadata metadata = new ModelMetadata(provider.Object, null, null, modelType, null);\n            provider.Setup(p => p.GetMetadataForProperties(null, modelType))\n                .Returns(propertyMetadata)\n                .Verifiable();\n\n            // Act\n            List<ModelMetadata> result = metadata.Properties.ToList();\n\n            // Assert\n            Assert.Equal(3, result.Count);\n            Assert.Equal(3, result[0].Model);\n            Assert.Equal(1, result[1].Model);\n            Assert.Equal(2, result[2].Model);\n        }\n\n        [Fact]\n        public void PropertiesListGetsResetWhenModelGetsReset()\n        { // Dev10 Bug #923263\n            // Arrange\n            var provider = new DataAnnotationsModelMetadataProvider();\n            var metadata = new ModelMetadata(provider, null, () => new Class1(), typeof(Class1), null);\n\n            // Act\n            ModelMetadata[] originalProps = metadata.Properties.ToArray();\n            metadata.Model = new Class2();\n            ModelMetadata[] newProps = metadata.Properties.ToArray();\n\n            // Assert\n            ModelMetadata originalProp = Assert.Single(originalProps);\n            Assert.Equal(typeof(string), originalProp.ModelType);\n            Assert.Equal(\"Prop1\", originalProp.PropertyName);\n            ModelMetadata newProp = Assert.Single(newProps);\n            Assert.Equal(typeof(int), newProp.ModelType);\n            Assert.Equal(\"Prop2\", newProp.PropertyName);\n        }\n\n        class Class1\n        {\n            public string Prop1 { get; set; }\n        }\n\n        class Class2\n        {\n            public int Prop2 { get; set; }\n        }\n\n        // SimpleDisplayText\n\n        [Fact]\n        public void SimpleDisplayTextReturnsNullDisplayTextForNullModel()\n        {\n            // Arrange\n            string nullText = \"(null)\";\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            ModelMetadata metadata = new ModelMetadata(provider.Object, null, null, typeof(object), null) { NullDisplayText = nullText };\n\n            // Act\n            string result = metadata.SimpleDisplayText;\n\n            // Assert\n            Assert.Equal(nullText, result);\n        }\n\n        private class SimpleDisplayTextModelWithToString\n        {\n            public override string ToString()\n            {\n                return \"Custom ToString Value\";\n            }\n        }\n\n        [Fact]\n        public void SimpleDisplayTextReturnsToStringValueWhenOverridden()\n        {\n            // Arrange\n            SimpleDisplayTextModelWithToString model = new SimpleDisplayTextModelWithToString();\n            EmptyModelMetadataProvider provider = new EmptyModelMetadataProvider();\n            ModelMetadata metadata = new ModelMetadata(provider, null, () => model, typeof(SimpleDisplayTextModelWithToString), null);\n\n            // Act\n            string result = metadata.SimpleDisplayText;\n\n            // Assert\n            Assert.Equal(model.ToString(), result);\n        }\n\n        private class SimpleDisplayTextModelWithoutToString\n        {\n            public string FirstProperty { get; set; }\n\n            public int SecondProperty { get; set; }\n        }\n\n        [Fact]\n        public void SimpleDisplayTextReturnsFirstPropertyValueForNonNullModel()\n        {\n            // Arrange\n            SimpleDisplayTextModelWithoutToString model = new SimpleDisplayTextModelWithoutToString\n            {\n                FirstProperty = \"First Property Value\"\n            };\n            EmptyModelMetadataProvider provider = new EmptyModelMetadataProvider();\n            ModelMetadata metadata = new ModelMetadata(provider, null, () => model, typeof(SimpleDisplayTextModelWithoutToString), null);\n\n            // Act\n            string result = metadata.SimpleDisplayText;\n\n            // Assert\n            Assert.Equal(model.FirstProperty, result);\n        }\n\n        [Fact]\n        public void SimpleDisplayTextReturnsFirstPropertyNullDisplayTextForNonNullModelWithNullDisplayColumnPropertyValue()\n        {\n            // Arrange\n            SimpleDisplayTextModelWithoutToString model = new SimpleDisplayTextModelWithoutToString();\n            EmptyModelMetadataProvider propertyProvider = new EmptyModelMetadataProvider();\n            ModelMetadata propertyMetadata = propertyProvider.GetMetadataForProperty(() => model.FirstProperty, typeof(SimpleDisplayTextModelWithoutToString), \"FirstProperty\");\n            propertyMetadata.NullDisplayText = \"Null Display Text\";\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            provider.Setup(p => p.GetMetadataForProperties(model, typeof(SimpleDisplayTextModelWithoutToString)))\n                .Returns(new[] { propertyMetadata });\n            ModelMetadata metadata = new ModelMetadata(provider.Object, null, () => model, typeof(SimpleDisplayTextModelWithoutToString), null);\n\n            // Act\n            string result = metadata.SimpleDisplayText;\n\n            // Assert\n            Assert.Equal(propertyMetadata.NullDisplayText, result);\n        }\n\n        private class SimpleDisplayTextModelWithNoProperties\n        {\n        }\n\n        [Fact]\n        public void SimpleDisplayTextReturnsEmptyStringForNonNullModelWithNoVisibleProperties()\n        {\n            // Arrange\n            SimpleDisplayTextModelWithNoProperties model = new SimpleDisplayTextModelWithNoProperties();\n            EmptyModelMetadataProvider provider = new EmptyModelMetadataProvider();\n            ModelMetadata metadata = new ModelMetadata(provider, null, () => model, typeof(SimpleDisplayTextModelWithNoProperties), null);\n\n            // Act\n            string result = metadata.SimpleDisplayText;\n\n            // Assert\n            Assert.Equal(String.Empty, result);\n        }\n\n        private class ObjectWithToStringOverride\n        {\n            private string _toStringValue;\n\n            public ObjectWithToStringOverride(string toStringValue)\n            {\n                _toStringValue = toStringValue;\n            }\n\n            public override string ToString()\n            {\n                return _toStringValue;\n            }\n        }\n\n        [Fact]\n        public void SimpleDisplayTextReturnsToStringOfModelForNonNullModel()\n        {\n            // Arrange\n            string toStringText = \"text from ToString()\";\n            ObjectWithToStringOverride model = new ObjectWithToStringOverride(toStringText);\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            ModelMetadata metadata = new ModelMetadata(provider.Object, null, () => model, typeof(ObjectWithToStringOverride), null);\n\n            // Act\n            string result = metadata.SimpleDisplayText;\n\n            // Assert\n            Assert.Equal(toStringText, result);\n        }\n\n        [Fact]\n        public void SimpleDisplayTextReturnsEmptyStringForNonNullModelWithToStringNull()\n        {\n            // Arrange\n            string toStringText = null;\n            ObjectWithToStringOverride model = new ObjectWithToStringOverride(toStringText);\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            ModelMetadata metadata = new ModelMetadata(provider.Object, null, () => model, typeof(ObjectWithToStringOverride), null);\n\n            // Act\n            string result = metadata.SimpleDisplayText;\n\n            // Assert\n            Assert.Equal(String.Empty, result);\n        }\n\n        // FromStringExpression()\n\n        [Fact]\n        public void FromStringExpressionGuardClauses()\n        {\n            // Null expression throws\n            Assert.ThrowsArgumentNull(\n                () => ModelMetadata.FromStringExpression(null, new ViewDataDictionary()),\n                \"expression\");\n\n            // Null view data dictionary throws\n            Assert.ThrowsArgumentNull(\n                () => ModelMetadata.FromStringExpression(\"expression\", null),\n                \"viewData\");\n        }\n\n        [Fact]\n        public void FromStringExpressionEmptyExpressionReturnsExistingModelMetadata()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            ModelMetadata metadata = new ModelMetadata(provider.Object, null, null, typeof(object), null);\n            ViewDataDictionary viewData = new ViewDataDictionary();\n            viewData.ModelMetadata = metadata;\n\n            // Act\n            ModelMetadata result = ModelMetadata.FromStringExpression(String.Empty, viewData, provider.Object);\n\n            // Assert\n            Assert.Same(metadata, result);\n        }\n\n        [Fact]\n        public void FromStringExpressionItemNotFoundInViewData()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            ViewDataDictionary viewData = new ViewDataDictionary();\n            provider.Setup(p => p.GetMetadataForType(It.IsAny<Func<object>>(), It.IsAny<Type>()))\n                .Callback<Func<object>, Type>((accessor, type) =>\n                {\n                    Assert.Null(accessor);\n                    Assert.Equal(typeof(string), type); // Don't know the type, must fall back on string\n                })\n                .Returns(() => null)\n                .Verifiable();\n\n            // Act\n            ModelMetadata.FromStringExpression(\"UnknownObject\", viewData, provider.Object);\n\n            // Assert\n            provider.Verify();\n        }\n\n        [Fact]\n        public void FromStringExpressionNullItemFoundAtRootOfViewData()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            ViewDataDictionary viewData = new ViewDataDictionary();\n            viewData[\"Object\"] = null;\n            provider.Setup(p => p.GetMetadataForType(It.IsAny<Func<object>>(), It.IsAny<Type>()))\n                .Callback<Func<object>, Type>((accessor, type) =>\n                {\n                    Assert.Null(accessor());\n                    Assert.Equal(typeof(string), type); // Don't know the type, must fall back on string\n                })\n                .Returns(() => null)\n                .Verifiable();\n\n            // Act\n            ModelMetadata.FromStringExpression(\"Object\", viewData, provider.Object);\n\n            // Assert\n            provider.Verify();\n        }\n\n        [Fact]\n        public void FromStringExpressionNonNullItemFoundAtRootOfViewData()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            object model = new object();\n            ViewDataDictionary viewData = new ViewDataDictionary();\n            viewData[\"Object\"] = model;\n            provider.Setup(p => p.GetMetadataForType(It.IsAny<Func<object>>(), It.IsAny<Type>()))\n                .Callback<Func<object>, Type>((accessor, type) =>\n                {\n                    Assert.Same(model, accessor());\n                    Assert.Equal(typeof(object), type);\n                })\n                .Returns(() => null)\n                .Verifiable();\n\n            // Act\n            ModelMetadata.FromStringExpression(\"Object\", viewData, provider.Object);\n\n            // Assert\n            provider.Verify();\n        }\n\n        [Fact]\n        public void FromStringExpressionNullItemFoundOnPropertyOfItemInViewData()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            DummyModelContainer model = new DummyModelContainer();\n            ViewDataDictionary viewData = new ViewDataDictionary();\n            viewData[\"Object\"] = model;\n            provider.Setup(p => p.GetMetadataForProperty(It.IsAny<Func<object>>(), It.IsAny<Type>(), It.IsAny<string>()))\n                .Callback<Func<object>, Type, string>((accessor, type, propertyName) =>\n                {\n                    Assert.Null(accessor());\n                    Assert.Equal(typeof(DummyModelContainer), type);\n                    Assert.Equal(\"Model\", propertyName);\n                })\n                .Returns(() => null)\n                .Verifiable();\n\n            // Act\n            ModelMetadata.FromStringExpression(\"Object.Model\", viewData, provider.Object);\n\n            // Assert\n            provider.Verify();\n        }\n\n        [Fact]\n        public void FromStringExpressionNonNullItemFoundOnPropertyOfItemInViewData()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            DummyModelContainer model = new DummyModelContainer { Model = new DummyContactModel() };\n            ViewDataDictionary viewData = new ViewDataDictionary();\n            viewData[\"Object\"] = model;\n            provider.Setup(p => p.GetMetadataForProperty(It.IsAny<Func<object>>(), It.IsAny<Type>(), It.IsAny<string>()))\n                .Callback<Func<object>, Type, string>((accessor, type, propertyName) =>\n                {\n                    Assert.Same(model.Model, accessor());\n                    Assert.Equal(typeof(DummyModelContainer), type);\n                    Assert.Equal(\"Model\", propertyName);\n                })\n                .Returns(() => null)\n                .Verifiable();\n\n            // Act\n            ModelMetadata.FromStringExpression(\"Object.Model\", viewData, provider.Object);\n\n            // Assert\n            provider.Verify();\n        }\n\n        [Fact]\n        public void FromStringExpressionContainerTest()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            DummyModelContainer model = new DummyModelContainer { Model = new DummyContactModel() };\n            ViewDataDictionary viewData = new ViewDataDictionary();\n            viewData[\"Object\"] = model;\n            provider.Setup(p => p.GetMetadataForProperty(It.IsAny<Func<object>>(), It.IsAny<Type>(), It.IsAny<string>()))\n                .Returns<Func<object>, Type, string>((accessor, type, propertyName) =>\n                {\n                    return new ModelMetadata(provider.Object, model.GetType(), accessor, type, propertyName);\n                });\n\n            // Act\n            ModelMetadata metadata = ModelMetadata.FromStringExpression(\"Object.Model\", viewData, provider.Object);\n\n            // Assert\n            Assert.Same(model, metadata.Container);\n        }\n\n        [Fact]\n        public void FromStringExpressionWithNullModelButValidModelMetadataShouldReturnProperPropertyMetadata()\n        {\n            // Arrange\n            ViewDataDictionary viewData = new ViewDataDictionary();\n            viewData.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(DummyContactModel));\n\n            // Act\n            ModelMetadata result = ModelMetadata.FromStringExpression(\"NullableIntValue\", viewData);\n\n            // Assert\n            Assert.Null(result.Model);\n            Assert.Equal(typeof(Nullable<int>), result.ModelType);\n            Assert.Equal(\"NullableIntValue\", result.PropertyName);\n            Assert.Equal(typeof(DummyContactModel), result.ContainerType);\n        }\n\n        [Fact]\n        public void FromStringExpressionValueInModelProperty()\n        {\n            // Arrange\n            DummyContactModel model = new DummyContactModel { FirstName = \"John\" };\n            ViewDataDictionary viewData = new ViewDataDictionary(model);\n\n            // Act\n            ModelMetadata metadata = ModelMetadata.FromStringExpression(\"FirstName\", viewData);\n\n            // Assert\n            Assert.Equal(\"John\", metadata.Model);\n        }\n\n        [Fact]\n        public void FromStringExpressionValueInViewDataOverridesValueFromModelProperty()\n        {\n            // Arrange\n            DummyContactModel model = new DummyContactModel { FirstName = \"John\" };\n            ViewDataDictionary viewData = new ViewDataDictionary(model);\n            viewData[\"FirstName\"] = \"Jim\";\n\n            // Act\n            ModelMetadata metadata = ModelMetadata.FromStringExpression(\"FirstName\", viewData);\n\n            // Assert\n            Assert.Equal(\"Jim\", metadata.Model);\n            Assert.Null(metadata.Container);\n        }\n\n        // FromLambdaExpression()\n\n        [Fact]\n        public void FromLambdaExpressionGuardClauseTests()\n        {\n            // Null expression throws\n            Assert.ThrowsArgumentNull(\n                () => ModelMetadata.FromLambdaExpression<string, object>(null, new ViewDataDictionary<string>()),\n                \"expression\");\n\n            // Null view data throws\n            Assert.ThrowsArgumentNull(\n                () => ModelMetadata.FromLambdaExpression<string, object>(m => m, null),\n                \"viewData\");\n\n            // Unsupported expression type throws\n            Assert.Throws<InvalidOperationException>(\n                () => ModelMetadata.FromLambdaExpression<string, object>(m => new Object(), new ViewDataDictionary<string>()),\n                \"Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.\");\n        }\n\n        [Fact]\n        public void FromLambdaExpressionModelIdentityExpressionReturnsExistingModelMetadata()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            ModelMetadata metadata = new ModelMetadata(provider.Object, null, null, typeof(object), null);\n            ViewDataDictionary<object> viewData = new ViewDataDictionary<object>();\n            viewData.ModelMetadata = metadata;\n\n            // Act\n            ModelMetadata result = ModelMetadata.FromLambdaExpression<object, object>(m => m, viewData, provider.Object);\n\n            // Assert\n            Assert.Same(metadata, result);\n        }\n\n        [Fact]\n        public void FromLambdaExpressionPropertyExpressionFromParameter()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            DummyContactModel model = new DummyContactModel { FirstName = \"Test\" };\n            ViewDataDictionary<DummyContactModel> viewData = new ViewDataDictionary<DummyContactModel>(model);\n            provider.Setup(p => p.GetMetadataForProperty(It.IsAny<Func<object>>(), It.IsAny<Type>(), It.IsAny<string>()))\n                .Callback<Func<object>, Type, string>((accessor, type, propertyName) =>\n                {\n                    Assert.Equal(\"Test\", accessor());\n                    Assert.Equal(typeof(DummyContactModel), type);\n                    Assert.Equal(\"FirstName\", propertyName);\n                })\n                .Returns(() => null)\n                .Verifiable();\n\n            // Act\n            ModelMetadata.FromLambdaExpression<DummyContactModel, string>(m => m.FirstName, viewData, provider.Object);\n\n            // Assert\n            provider.Verify();\n        }\n\n        [Fact]\n        public void FromLambdaExpressionPropertyExpressionFromClosureValue()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            DummyContactModel model = new DummyContactModel { FirstName = \"Test\" };\n            ViewDataDictionary<object> viewData = new ViewDataDictionary<object>();\n            provider.Setup(p => p.GetMetadataForProperty(It.IsAny<Func<object>>(), It.IsAny<Type>(), It.IsAny<string>()))\n                .Callback<Func<object>, Type, string>((accessor, type, propertyName) =>\n                {\n                    Assert.Equal(\"Test\", accessor());\n                    Assert.Equal(typeof(DummyContactModel), type);\n                    Assert.Equal(\"FirstName\", propertyName);\n                })\n                .Returns(() => null)\n                .Verifiable();\n\n            // Act\n            ModelMetadata.FromLambdaExpression<object, string>(m => model.FirstName, viewData, provider.Object);\n\n            // Assert\n            provider.Verify();\n        }\n\n        [Fact]\n        public void FromLambdaExpressionFieldExpressionFromParameter()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            DummyContactModel model = new DummyContactModel { IntField = 42 };\n            ViewDataDictionary<DummyContactModel> viewData = new ViewDataDictionary<DummyContactModel>(model);\n            provider.Setup(p => p.GetMetadataForType(It.IsAny<Func<object>>(), It.IsAny<Type>()))\n                .Callback<Func<object>, Type>((accessor, type) =>\n                {\n                    Assert.Equal(42, accessor());\n                    Assert.Equal(typeof(int), type);\n                })\n                .Returns(() => null)\n                .Verifiable();\n\n            // Act\n            ModelMetadata.FromLambdaExpression<DummyContactModel, int>(m => m.IntField, viewData, provider.Object);\n\n            // Assert\n            provider.Verify();\n        }\n\n        [Fact]\n        public void FromLambdaExpressionFieldExpressionFromFieldOfClosureValue()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            DummyContactModel model = new DummyContactModel { IntField = 42 };\n            ViewDataDictionary<object> viewData = new ViewDataDictionary<object>();\n            provider.Setup(p => p.GetMetadataForType(It.IsAny<Func<object>>(), It.IsAny<Type>()))\n                .Callback<Func<object>, Type>((accessor, type) =>\n                {\n                    Assert.Equal(42, accessor());\n                    Assert.Equal(typeof(int), type);\n                })\n                .Returns(() => null)\n                .Verifiable();\n\n            // Act\n            ModelMetadata.FromLambdaExpression<object, int>(m => model.IntField, viewData, provider.Object);\n\n            // Assert\n            provider.Verify();\n        }\n\n        [Fact]\n        public void FromLambdaExpressionFieldExpressionFromClosureValue()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            DummyContactModel model = new DummyContactModel();\n            ViewDataDictionary<object> viewData = new ViewDataDictionary<object>();\n            provider.Setup(p => p.GetMetadataForType(It.IsAny<Func<object>>(), It.IsAny<Type>()))\n                .Callback<Func<object>, Type>((accessor, type) =>\n                {\n                    Assert.Same(model, accessor());\n                    Assert.Equal(typeof(DummyContactModel), type);\n                })\n                .Returns(() => null)\n                .Verifiable();\n\n            // Act\n            ModelMetadata.FromLambdaExpression<object, DummyContactModel>(m => model, viewData, provider.Object);\n\n            // Assert\n            provider.Verify();\n        }\n\n        [Fact]\n        public void FromLambdaExpressionSingleParameterClassIndexer()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            DummyContactModel model = new DummyContactModel();\n            ViewDataDictionary<DummyContactModel> viewData = new ViewDataDictionary<DummyContactModel>(model);\n            provider.Setup(p => p.GetMetadataForType(It.IsAny<Func<object>>(), It.IsAny<Type>()))\n                .Callback<Func<object>, Type>((accessor, type) =>\n                {\n                    Assert.Equal(\"Indexed into 42\", accessor());\n                    Assert.Equal(typeof(string), type);\n                })\n                .Returns(() => null)\n                .Verifiable();\n\n            // Act\n            ModelMetadata.FromLambdaExpression<DummyContactModel, string>(m => m[42], viewData, provider.Object);\n\n            // Assert\n            provider.Verify();\n        }\n\n        [Fact]\n        public void FromLambdaExpressionSingleDimensionArrayIndex()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            DummyContactModel model = new DummyContactModel { Array = new[] { 4, 8, 15, 16, 23, 42 } };\n            ViewDataDictionary<DummyContactModel> viewData = new ViewDataDictionary<DummyContactModel>(model);\n            provider.Setup(p => p.GetMetadataForType(It.IsAny<Func<object>>(), It.IsAny<Type>()))\n                .Callback<Func<object>, Type>((accessor, type) =>\n                {\n                    Assert.Equal(16, accessor());\n                    Assert.Equal(typeof(int), type);\n                })\n                .Returns(() => null)\n                .Verifiable();\n\n            // Act\n            ModelMetadata.FromLambdaExpression<DummyContactModel, int>(m => m.Array[3], viewData, provider.Object);\n\n            // Assert\n            provider.Verify();\n        }\n\n        [Fact]\n        public void FromLambdaExpressionNullReferenceExceptionsInPropertyExpressionPreserveAllExpressionInformation()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            ViewDataDictionary<DummyContactModel> viewData = new ViewDataDictionary<DummyContactModel>();\n            provider.Setup(p => p.GetMetadataForProperty(It.IsAny<Func<object>>(), It.IsAny<Type>(), It.IsAny<string>()))\n                .Callback<Func<object>, Type, string>((accessor, type, propertyName) =>\n                {\n                    Assert.Null(accessor());\n                    Assert.Equal(typeof(DummyContactModel), type);\n                    Assert.Equal(\"FirstName\", propertyName);\n                })\n                .Returns(() => null)\n                .Verifiable();\n\n            // Act\n            ModelMetadata.FromLambdaExpression<DummyContactModel, string>(m => m.FirstName, viewData, provider.Object);\n\n            // Assert\n            provider.Verify();\n        }\n\n        [Fact]\n        public void FromLambdaExpressionSetsContainerTypeToDerivedMostType()\n        { // Dev10 Bug #868619\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            DerivedModel derivedModel = new DerivedModel();\n            ViewDataDictionary<DerivedModel> viewData = new ViewDataDictionary<DerivedModel>(derivedModel);\n            provider.Setup(p => p.GetMetadataForProperty(It.IsAny<Func<object>>(), It.IsAny<Type>(), It.IsAny<string>()))\n                .Callback<Func<object>, Type, string>((accessor, type, propertyName) =>\n                {\n                    Assert.Null(accessor());\n                    Assert.Equal(derivedModel.GetType(), type);\n                    Assert.Equal(\"MyProperty\", propertyName);\n                })\n                .Returns<Func<object>, Type, string>((accessor, type, propertyName) =>\n                {\n                    return new ModelMetadata(provider.Object, derivedModel.GetType(), accessor, type, propertyName);\n                })\n                .Verifiable();\n\n            // Act\n            ModelMetadata metadata = ModelMetadata.FromLambdaExpression<DerivedModel, string>(m => m.MyProperty, viewData, provider.Object);\n\n            // Assert\n            provider.Verify();\n            Assert.Same(derivedModel, metadata.Container);\n        }\n\n        [Fact]\n        public void FromLambdaExpressionSetsContainerWithoutObjectInViewData()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            DerivedModel derivedModel = new DerivedModel();\n            ViewDataDictionary<DerivedModel> viewData = new ViewDataDictionary<DerivedModel>();\n            provider.Setup(p => p.GetMetadataForProperty(It.IsAny<Func<object>>(), It.IsAny<Type>(), It.IsAny<string>()))\n                .Callback<Func<object>, Type, string>((accessor, type, propertyName) =>\n                {\n                    Assert.Null(accessor());\n                    Assert.Equal(derivedModel.GetType(), type);\n                    Assert.Equal(\"MyProperty\", propertyName);\n                })\n                .Returns<Func<object>, Type, string>((accessor, type, propertyName) =>\n                {\n                    return new ModelMetadata(provider.Object, derivedModel.GetType(), accessor, type, propertyName);\n                })\n                .Verifiable();\n\n            // Act\n            ModelMetadata metadata = ModelMetadata.FromLambdaExpression<DerivedModel, string>(m => m.MyProperty, viewData, provider.Object);\n\n            // Assert\n            provider.Verify();\n            Assert.Null(metadata.Container);\n        }\n\n        private class BaseModel\n        {\n            public virtual string MyProperty { get; set; }\n        }\n\n        private class DerivedModel : BaseModel\n        {\n            [Required]\n            public override string MyProperty\n            {\n                get { return base.MyProperty; }\n                set { base.MyProperty = value; }\n            }\n        }\n\n        // GetDisplayName()\n\n        [Fact]\n        public void ReturnsDisplayNameWhenSet()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            ModelMetadata metadata = new ModelMetadata(provider.Object, null, null, typeof(object), \"PropertyName\") { DisplayName = \"Display Name\" };\n\n            // Act\n            string result = metadata.GetDisplayName();\n\n            // Assert\n            Assert.Equal(\"Display Name\", result);\n        }\n\n        [Fact]\n        public void ReturnsPropertyNameWhenSetAndDisplayNameIsNull()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            ModelMetadata metadata = new ModelMetadata(provider.Object, null, null, typeof(object), \"PropertyName\");\n\n            // Act\n            string result = metadata.GetDisplayName();\n\n            // Assert\n            Assert.Equal(\"PropertyName\", result);\n        }\n\n        [Fact]\n        public void ReturnsTypeNameWhenPropertyNameAndDisplayNameAreNull()\n        {\n            // Arrange\n            Mock<ModelMetadataProvider> provider = new Mock<ModelMetadataProvider>();\n            ModelMetadata metadata = new ModelMetadata(provider.Object, null, null, typeof(object), null);\n\n            // Act\n            string result = metadata.GetDisplayName();\n\n            // Assert\n            Assert.Equal(\"Object\", result);\n        }\n\n        // Helpers\n\n        private class DummyContactModel\n        {\n            public int IntField = 0;\n            public string FirstName { get; set; }\n            public string LastName { get; set; }\n            public Nullable<int> NullableIntValue { get; set; }\n            public int[] Array { get; set; }\n\n            public string this[int index]\n            {\n                get { return \"Indexed into \" + index; }\n            }\n        }\n\n        private class DummyModelContainer\n        {\n            public DummyContactModel Model { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ModelStateDictionaryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.IO;\nusing System.Runtime.Serialization.Formatters.Binary;\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ModelStateDictionaryTest\n    {\n        [Fact]\n        public void AddModelErrorCreatesModelStateIfNotPresent()\n        {\n            // Arrange\n            ModelStateDictionary dictionary = new ModelStateDictionary();\n\n            // Act\n            dictionary.AddModelError(\"some key\", \"some error\");\n\n            // Assert\n            KeyValuePair<string, ModelState> kvp = Assert.Single(dictionary);\n            Assert.Equal(\"some key\", kvp.Key);\n            ModelError error = Assert.Single(kvp.Value.Errors);\n            Assert.Equal(\"some error\", error.ErrorMessage);\n        }\n\n        [Fact]\n        public void AddModelErrorThrowsIfKeyIsNull()\n        {\n            // Arrange\n            ModelStateDictionary dictionary = new ModelStateDictionary();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { dictionary.AddModelError(null, (string)null); }, \"key\");\n        }\n\n        [Fact]\n        public void AddModelErrorUsesExistingModelStateIfPresent()\n        {\n            // Arrange\n            ModelStateDictionary dictionary = new ModelStateDictionary();\n            dictionary.AddModelError(\"some key\", \"some error\");\n            Exception ex = new Exception();\n\n            // Act\n            dictionary.AddModelError(\"some key\", ex);\n\n            // Assert\n            KeyValuePair<string, ModelState> kvp = Assert.Single(dictionary);\n            Assert.Equal(\"some key\", kvp.Key);\n\n            Assert.Equal(2, kvp.Value.Errors.Count);\n            Assert.Equal(\"some error\", kvp.Value.Errors[0].ErrorMessage);\n            Assert.Same(ex, kvp.Value.Errors[1].Exception);\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfDictionaryIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ModelStateDictionary((ModelStateDictionary)null); }, \"dictionary\");\n        }\n\n        [Fact]\n        public void ConstructorWithDictionaryParameter()\n        {\n            // Arrange\n            ModelStateDictionary oldDictionary = new ModelStateDictionary()\n            {\n                { \"foo\", new ModelState() { Value = HtmlHelperTest.GetValueProviderResult(\"bar\", \"bar\") } }\n            };\n\n            // Act\n            ModelStateDictionary newDictionary = new ModelStateDictionary(oldDictionary);\n\n            // Assert\n            Assert.Single(newDictionary);\n            Assert.Equal(\"bar\", newDictionary[\"foo\"].Value.ConvertTo(typeof(string)));\n        }\n\n        [Fact]\n        public void ConstructorWithDictionaryParameterUsesCopyOnWriteDictionary()\n        {\n            // Arrange\n            ModelStateDictionary oldDictionary = new ModelStateDictionary();\n\n            // Act\n            ModelStateDictionary newDictionary = new ModelStateDictionary(oldDictionary);\n\n            // Assert\n            Assert.IsType<Dictionary<string, ModelState>>(oldDictionary.InnerDictionary);\n            Assert.IsType<CopyOnWriteDictionary<string, ModelState>>(newDictionary.InnerDictionary);\n        }\n\n        [Fact]\n        public void DictionaryInterface()\n        {\n            // Arrange\n            DictionaryHelper<string, ModelState> helper = new DictionaryHelper<string, ModelState>()\n            {\n                Creator = () => new ModelStateDictionary(),\n                Comparer = StringComparer.OrdinalIgnoreCase,\n                SampleKeys = new string[] { \"foo\", \"bar\", \"baz\", \"quux\", \"QUUX\" },\n                SampleValues = new ModelState[] { new ModelState(), new ModelState(), new ModelState(), new ModelState(), new ModelState() },\n                ThrowOnKeyNotFound = false\n            };\n\n            // Act & assert\n            helper.Execute();\n        }\n\n        [Fact]\n        public void DictionaryIsSerializable()\n        {\n            // Arrange\n            MemoryStream stream = new MemoryStream();\n            BinaryFormatter formatter = new BinaryFormatter();\n\n            ModelStateDictionary originalDict = new ModelStateDictionary();\n            originalDict.AddModelError(\"foo\", new InvalidOperationException(\"Some invalid operation.\"));\n            originalDict.AddModelError(\"foo\", new InvalidOperationException(\"Some other invalid operation.\"));\n            originalDict.AddModelError(\"bar\", \"Some exception text.\");\n            originalDict.SetModelValue(\"baz\", new ValueProviderResult(\"rawValue\", \"attemptedValue\", CultureInfo.GetCultureInfo(\"fr-FR\")));\n\n            // Act\n            formatter.Serialize(stream, originalDict);\n            stream.Position = 0;\n            ModelStateDictionary deserializedDict = formatter.Deserialize(stream) as ModelStateDictionary;\n\n            // Assert\n            Assert.NotNull(deserializedDict);\n            Assert.Equal(3, deserializedDict.Count);\n\n            ModelState foo = deserializedDict[\"FOO\"];\n            InvalidOperationException exception0 = Assert.IsType<InvalidOperationException>(foo.Errors[0].Exception);\n            Assert.Equal(\"Some invalid operation.\", exception0.Message);\n            InvalidOperationException exception1 = Assert.IsType<InvalidOperationException>(foo.Errors[1].Exception);\n            Assert.Equal(\"Some other invalid operation.\", exception1.Message);\n\n            ModelState bar = deserializedDict[\"BAR\"];\n            Assert.Equal(\"Some exception text.\", bar.Errors[0].ErrorMessage);\n\n            ModelState baz = deserializedDict[\"BAZ\"];\n            Assert.Equal(\"rawValue\", baz.Value.RawValue);\n            Assert.Equal(\"attemptedValue\", baz.Value.AttemptedValue);\n            Assert.Equal(CultureInfo.GetCultureInfo(\"fr-FR\"), baz.Value.Culture);\n        }\n\n        [Fact]\n        public void IsValidFieldReturnsFalseIfDictionaryDoesNotContainKey()\n        {\n            // Arrange\n            ModelStateDictionary msd = new ModelStateDictionary();\n\n            // Act\n            bool isValid = msd.IsValidField(\"foo\");\n\n            // Assert\n            Assert.True(isValid);\n        }\n\n        [Fact]\n        public void IsValidFieldReturnsFalseIfKeyChildContainsErrors()\n        {\n            // Arrange\n            ModelStateDictionary msd = new ModelStateDictionary();\n            msd.AddModelError(\"foo.bar\", \"error text\");\n\n            // Act\n            bool isValid = msd.IsValidField(\"foo\");\n\n            // Assert\n            Assert.False(isValid);\n        }\n\n        [Fact]\n        public void IsValidFieldReturnsFalseIfKeyContainsErrors()\n        {\n            // Arrange\n            ModelStateDictionary msd = new ModelStateDictionary();\n            msd.AddModelError(\"foo\", \"error text\");\n\n            // Act\n            bool isValid = msd.IsValidField(\"foo\");\n\n            // Assert\n            Assert.False(isValid);\n        }\n\n        [Fact]\n        public void IsValidFieldReturnsTrueIfModelStateDoesNotContainErrors()\n        {\n            // Arrange\n            ModelStateDictionary msd = new ModelStateDictionary()\n            {\n                { \"foo\", new ModelState() { Value = new ValueProviderResult(null, null, null) } }\n            };\n\n            // Act\n            bool isValid = msd.IsValidField(\"foo\");\n\n            // Assert\n            Assert.True(isValid);\n        }\n\n        [Fact]\n        public void IsValidFieldThrowsIfKeyIsNull()\n        {\n            // Arrange\n            ModelStateDictionary msd = new ModelStateDictionary();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { msd.IsValidField(null); }, \"key\");\n        }\n\n        [Fact]\n        public void IsValidPropertyReturnsFalseIfErrors()\n        {\n            // Arrange\n            ModelState errorState = new ModelState() { Value = HtmlHelperTest.GetValueProviderResult(\"quux\", \"quux\") };\n            errorState.Errors.Add(\"some error\");\n            ModelStateDictionary dictionary = new ModelStateDictionary()\n            {\n                { \"foo\", new ModelState() { Value = HtmlHelperTest.GetValueProviderResult(\"bar\", \"bar\") } },\n                { \"baz\", errorState }\n            };\n\n            // Act\n            bool isValid = dictionary.IsValid;\n\n            // Assert\n            Assert.False(isValid);\n        }\n\n        [Fact]\n        public void IsValidPropertyReturnsTrueIfNoErrors()\n        {\n            // Arrange\n            ModelStateDictionary dictionary = new ModelStateDictionary()\n            {\n                { \"foo\", new ModelState() { Value = HtmlHelperTest.GetValueProviderResult(\"bar\", \"bar\") } },\n                { \"baz\", new ModelState() { Value = HtmlHelperTest.GetValueProviderResult(\"quux\", \"bar\") } }\n            };\n\n            // Act\n            bool isValid = dictionary.IsValid;\n\n            // Assert\n            Assert.True(isValid);\n        }\n\n        [Fact]\n        public void MergeCopiesDictionaryEntries()\n        {\n            // Arrange\n            ModelStateDictionary fooDict = new ModelStateDictionary() { { \"foo\", new ModelState() } };\n            ModelStateDictionary barDict = new ModelStateDictionary() { { \"bar\", new ModelState() } };\n\n            // Act\n            fooDict.Merge(barDict);\n\n            // Assert\n            Assert.Equal(2, fooDict.Count);\n            Assert.Equal(barDict[\"bar\"], fooDict[\"bar\"]);\n        }\n\n        [Fact]\n        public void MergeDoesNothingIfParameterIsNull()\n        {\n            // Arrange\n            ModelStateDictionary fooDict = new ModelStateDictionary() { { \"foo\", new ModelState() } };\n\n            // Act\n            fooDict.Merge(null);\n\n            // Assert\n            Assert.Single(fooDict);\n            Assert.True(fooDict.ContainsKey(\"foo\"));\n        }\n\n        [Fact]\n        public void SetAttemptedValueCreatesModelStateIfNotPresent()\n        {\n            // Arrange\n            ModelStateDictionary dictionary = new ModelStateDictionary();\n\n            // Act\n            dictionary.SetModelValue(\"some key\", HtmlHelperTest.GetValueProviderResult(\"some value\", \"some value\"));\n\n            // Assert\n            Assert.Single(dictionary);\n            ModelState modelState = dictionary[\"some key\"];\n\n            Assert.Empty(modelState.Errors);\n            Assert.Equal(\"some value\", modelState.Value.ConvertTo(typeof(string)));\n        }\n\n        [Fact]\n        public void SetAttemptedValueUsesExistingModelStateIfPresent()\n        {\n            // Arrange\n            ModelStateDictionary dictionary = new ModelStateDictionary();\n            dictionary.AddModelError(\"some key\", \"some error\");\n            Exception ex = new Exception();\n\n            // Act\n            dictionary.SetModelValue(\"some key\", HtmlHelperTest.GetValueProviderResult(\"some value\", \"some value\"));\n\n            // Assert\n            Assert.Single(dictionary);\n            ModelState modelState = dictionary[\"some key\"];\n\n            ModelError error = Assert.Single(modelState.Errors);\n            Assert.Equal(\"some error\", error.ErrorMessage);\n            Assert.Equal(\"some value\", modelState.Value.ConvertTo(typeof(string)));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ModelStateTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ModelStateTest\n    {\n        [Fact]\n        public void ErrorsProperty()\n        {\n            // Arrange\n            ModelState modelState = new ModelState();\n\n            // Act & Assert\n            Assert.NotNull(modelState.Errors);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ModelValidationResultTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ModelValidationResultTest\n    {\n        [Fact]\n        public void MemberNameProperty()\n        {\n            // Arrange\n            ModelValidationResult result = new ModelValidationResult();\n\n            // Act & assert\n            MemberHelper.TestStringProperty(result, \"MemberName\", String.Empty);\n        }\n\n        [Fact]\n        public void MessageProperty()\n        {\n            // Arrange\n            ModelValidationResult result = new ModelValidationResult();\n\n            // Act & assert\n            MemberHelper.TestStringProperty(result, \"Message\", String.Empty);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ModelValidatorProviderCollectionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ModelValidatorProviderCollectionTest\n    {\n        [Fact]\n        public void ListWrappingConstructor()\n        {\n            // Arrange\n            List<ModelValidatorProvider> list = new List<ModelValidatorProvider>()\n            {\n                new Mock<ModelValidatorProvider>().Object, new Mock<ModelValidatorProvider>().Object\n            };\n\n            // Act\n            ModelValidatorProviderCollection collection = new ModelValidatorProviderCollection(list);\n\n            // Assert\n            Assert.Equal(list, collection.ToList());\n        }\n\n        [Fact]\n        public void ListWrappingConstructorThrowsIfListIsNull()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ModelValidatorProviderCollection((IList<ModelValidatorProvider>)null); },\n                \"list\");\n        }\n\n        [Fact]\n        public void DefaultConstructor()\n        {\n            // Act\n            ModelValidatorProviderCollection collection = new ModelValidatorProviderCollection();\n\n            // Assert\n            Assert.Empty(collection);\n        }\n\n        [Fact]\n        public void AddNullModelValidatorProviderThrows()\n        {\n            // Arrange\n            ModelValidatorProviderCollection collection = new ModelValidatorProviderCollection();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { collection.Add(null); },\n                \"item\");\n        }\n\n        [Fact]\n        public void ModelValidatorProviderCollectionCombinedItemsCaches()\n        {\n            // Arrange\n            var providers = new ModelValidatorProvider[] \n            {\n                new Mock<ModelValidatorProvider>(MockBehavior.Strict).Object, \n                new Mock<ModelValidatorProvider>(MockBehavior.Strict).Object\n            };\n            var collection = new ModelValidatorProviderCollection(providers);\n\n            // Act\n            var combined1 = collection.CombinedItems;\n            var combined2 = collection.CombinedItems;\n\n            // Assert\n            Assert.Equal(providers, combined1);\n            Assert.Same(combined1, combined2);\n        }\n\n        [Fact]\n        public void ModelValidatorProviderCollectionCombinedItemsClearResetsCache()\n        {\n            TestCacheReset((collection) => collection.Clear());\n        }\n\n        [Fact]\n        public void ModelValidatorProviderCollectionCombinedItemsInsertResetsCache()\n        {\n            TestCacheReset((collection) => collection.Insert(0, new Mock<ModelValidatorProvider>(MockBehavior.Strict).Object));\n        }\n\n        [Fact]\n        public void ModelValidatorProviderCollectionCombinedItemsRemoveResetsCache()\n        {\n            TestCacheReset((collection) => collection.RemoveAt(0));\n        }\n\n        [Fact]\n        public void ModelValidatorProviderCollectionCombinedItemsSetResetsCache()\n        {\n            TestCacheReset((collection) => collection[0] = new Mock<ModelValidatorProvider>(MockBehavior.Strict).Object);\n        }\n\n        private static void TestCacheReset(Action<ModelValidatorProviderCollection> mutatingAction)\n        {\n            // Arrange\n            var providers = new List<ModelValidatorProvider>() \n            {\n                new Mock<ModelValidatorProvider>(MockBehavior.Strict).Object, \n                new Mock<ModelValidatorProvider>(MockBehavior.Strict).Object\n            };\n            var collection = new ModelValidatorProviderCollection(providers);\n\n            // Act\n            mutatingAction(collection);\n\n            ModelValidatorProvider[] combined = collection.CombinedItems;\n\n            // Assert\n            Assert.Equal(providers, combined);\n        }\n\n        [Fact]\n        public void ModelBinderValidatorCollectionCombinedItemsDelegatesToResolver()\n        {\n            // Arrange\n            var firstProvider = new Mock<ModelValidatorProvider>();\n            var secondProvider = new Mock<ModelValidatorProvider>();\n            var thirdProvider = new Mock<ModelValidatorProvider>();\n            var dependencyProviders = new ModelValidatorProvider[] { firstProvider.Object, secondProvider.Object };\n            var collectionProviders = new ModelValidatorProvider[] { thirdProvider.Object };\n            var expectedProviders = new ModelValidatorProvider[] { firstProvider.Object, secondProvider.Object, thirdProvider.Object };\n\n            var resolver = new Mock<IDependencyResolver>();\n            resolver.Setup(r => r.GetServices(typeof(ModelValidatorProvider))).Returns(dependencyProviders);\n\n            var providers = new ModelValidatorProviderCollection(collectionProviders, resolver.Object);\n\n            // Act\n            ModelValidatorProvider[] combined = providers.CombinedItems;\n\n            // Assert\n            Assert.Equal(expectedProviders, combined);\n        }\n\n        [Fact]\n        public void SetItem()\n        {\n            // Arrange\n            ModelValidatorProviderCollection collection = new ModelValidatorProviderCollection();\n            collection.Add(new Mock<ModelValidatorProvider>().Object);\n\n            ModelValidatorProvider newProvider = new Mock<ModelValidatorProvider>().Object;\n\n            // Act\n            collection[0] = newProvider;\n\n            // Assert\n            ModelValidatorProvider provider = Assert.Single(collection);\n            Assert.Equal(newProvider, provider);\n        }\n\n        [Fact]\n        public void SetNullModelValidatorProviderThrows()\n        {\n            // Arrange\n            ModelValidatorProviderCollection collection = new ModelValidatorProviderCollection();\n            collection.Add(new Mock<ModelValidatorProvider>().Object);\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { collection[0] = null; },\n                \"item\");\n        }\n\n        [Fact]\n        public void GetValidators()\n        {\n            // Arrange\n            ModelMetadata metadata = GetMetadata();\n            ControllerContext controllerContext = new ControllerContext();\n\n            ModelValidator[] allValidators = new ModelValidator[]\n            {\n                new SimpleModelValidator(),\n                new SimpleModelValidator(),\n                new SimpleModelValidator(),\n                new SimpleModelValidator(),\n                new SimpleModelValidator()\n            };\n\n            Mock<ModelValidatorProvider> provider1 = new Mock<ModelValidatorProvider>();\n            provider1.Setup(p => p.GetValidators(metadata, controllerContext)).Returns(new ModelValidator[]\n            {\n                allValidators[0], allValidators[1]\n            });\n\n            Mock<ModelValidatorProvider> provider2 = new Mock<ModelValidatorProvider>();\n            provider2.Setup(p => p.GetValidators(metadata, controllerContext)).Returns(new ModelValidator[]\n            {\n                allValidators[2], allValidators[3], allValidators[4]\n            });\n\n            ModelValidatorProviderCollection collection = new ModelValidatorProviderCollection();\n            collection.Add(provider1.Object);\n            collection.Add(provider2.Object);\n\n            // Act\n            IEnumerable<ModelValidator> returnedValidators = collection.GetValidators(metadata, controllerContext);\n\n            // Assert\n            Assert.Equal(allValidators, returnedValidators.ToArray());\n        }\n\n        [Fact]\n        public void GetValidatorsDelegatesToResolver()\n        {\n            // Arrange\n            ModelValidator[] allValidators = new ModelValidator[]\n            {\n                new SimpleModelValidator(),\n                new SimpleModelValidator(),\n                new SimpleModelValidator(),\n                new SimpleModelValidator()\n            };\n\n            ModelMetadata metadata = GetMetadata();\n            ControllerContext controllerContext = new ControllerContext();\n\n            Mock<ModelValidatorProvider> resolverProvider1 = new Mock<ModelValidatorProvider>();\n            resolverProvider1.Setup(p => p.GetValidators(metadata, controllerContext)).Returns(new ModelValidator[]\n            {\n                allValidators[0], allValidators[1]\n            });\n\n            Mock<ModelValidatorProvider> resolverprovider2 = new Mock<ModelValidatorProvider>();\n            resolverprovider2.Setup(p => p.GetValidators(metadata, controllerContext)).Returns(new ModelValidator[]\n            {\n                allValidators[2], allValidators[3]\n            });\n\n            var resolver = new Mock<IDependencyResolver>();\n            resolver.Setup(r => r.GetServices(typeof(ModelValidatorProvider))).Returns(new ModelValidatorProvider[] { resolverProvider1.Object, resolverprovider2.Object });\n\n            ModelValidatorProviderCollection collection = new ModelValidatorProviderCollection(new ModelValidatorProvider[0], resolver.Object);\n\n            // Act\n            IEnumerable<ModelValidator> returnedValidators = collection.GetValidators(metadata, controllerContext);\n\n            // Assert\n            Assert.Equal(allValidators, returnedValidators.ToArray());\n        }\n\n        private static ModelMetadata GetMetadata()\n        {\n            ModelMetadataProvider provider = new EmptyModelMetadataProvider();\n            return provider.GetMetadataForType(null, typeof(object));\n        }\n\n        private sealed class SimpleModelValidator : ModelValidator\n        {\n            public SimpleModelValidator()\n                : base(GetMetadata(), new ControllerContext())\n            {\n            }\n\n            public override IEnumerable<ModelValidationResult> Validate(object container)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ModelValidatorProvidersTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ModelValidatorProvidersTest\n    {\n        [Fact]\n        public void CollectionDefaults()\n        {\n            // Arrange\n            Type[] expectedTypes = new Type[]\n            {\n                typeof(DataAnnotationsModelValidatorProvider),\n                typeof(DataErrorInfoModelValidatorProvider),\n                typeof(ClientDataTypeModelValidatorProvider)\n            };\n\n            // Act\n            Type[] actualTypes = ModelValidatorProviders.Providers.Select(p => p.GetType()).ToArray();\n\n            // Assert\n            Assert.Equal(expectedTypes, actualTypes);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ModelValidatorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")] // Uses ModelMetadataProviders.Current\n    public class ModelValidatorTest\n    {\n        [Fact]\n        public void ConstructorGuards()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(object));\n            ControllerContext context = new ControllerContext();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => new TestableModelValidator(null, context),\n                \"metadata\");\n            Assert.ThrowsArgumentNull(\n                () => new TestableModelValidator(metadata, null),\n                \"controllerContext\");\n        }\n\n        [Fact]\n        public void ValuesSet()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => 15, typeof(string), \"Length\");\n            ControllerContext context = new ControllerContext();\n\n            // Act\n            TestableModelValidator validator = new TestableModelValidator(metadata, context);\n\n            // Assert\n            Assert.Same(context, validator.ControllerContext);\n            Assert.Same(metadata, validator.Metadata);\n        }\n\n        [Fact]\n        public void NoClientRulesByDefault()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => 15, typeof(string), \"Length\");\n            ControllerContext context = new ControllerContext();\n\n            // Act\n            TestableModelValidator validator = new TestableModelValidator(metadata, context);\n\n            // Assert\n            Assert.Empty(validator.GetClientValidationRules());\n        }\n\n        [Fact]\n        public void IsRequiredFalseByDefault()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => 15, typeof(string), \"Length\");\n            ControllerContext context = new ControllerContext();\n\n            // Act\n            TestableModelValidator validator = new TestableModelValidator(metadata, context);\n\n            // Assert\n            Assert.False(validator.IsRequired);\n        }\n\n        [Fact]\n        public void GetModelValidator_DoesNotReadPropertyValues()\n        {\n            ModelValidatorProvider[] originalProviders = ModelValidatorProviders.Providers.ToArray();\n            try\n            {\n                // Arrange\n                ModelValidatorProviders.Providers.Clear();\n                ModelValidatorProviders.Providers.Add(new ObservableModelValidatorProvider());\n\n                ObservableModel model = new ObservableModel();\n                ModelMetadata metadata = new EmptyModelMetadataProvider().GetMetadataForType(() => model, typeof(ObservableModel));\n                ControllerContext controllerContext = new ControllerContext();\n\n                // Act\n                ModelValidator validator = ModelValidator.GetModelValidator(metadata, controllerContext);\n                ModelValidationResult[] results = validator.Validate(model).ToArray();\n\n                // Assert\n                Assert.False(model.PropertyWasRead());\n            }\n            finally\n            {\n                ModelValidatorProviders.Providers.Clear();\n                foreach (ModelValidatorProvider provider in originalProviders)\n                {\n                    ModelValidatorProviders.Providers.Add(provider);\n                }\n            }\n        }\n\n        private class ObservableModelValidatorProvider : ModelValidatorProvider\n        {\n            public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context)\n            {\n                return new ModelValidator[] { new ObservableModelValidator(metadata, context) };\n            }\n\n            private class ObservableModelValidator : ModelValidator\n            {\n                public ObservableModelValidator(ModelMetadata metadata, ControllerContext controllerContext)\n                    : base(metadata, controllerContext)\n                {\n                }\n\n                public override IEnumerable<ModelValidationResult> Validate(object container)\n                {\n                    return Enumerable.Empty<ModelValidationResult>();\n                }\n            }\n        }\n\n        private class ObservableModel\n        {\n            private bool _propertyWasRead;\n\n            public int TheProperty\n            {\n                get\n                {\n                    _propertyWasRead = true;\n                    return 42;\n                }\n            }\n\n            public bool PropertyWasRead()\n            {\n                return _propertyWasRead;\n            }\n        }\n\n        [Fact]\n        public void GetModelValidatorWithTypeLevelValidator()\n        {\n            // Arrange\n            ControllerContext context = new ControllerContext();\n            DataErrorInfo1 model = new DataErrorInfo1 { Error = \"Some Type Error\" };\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());\n            ModelValidator validator = ModelValidator.GetModelValidator(metadata, context);\n\n            // Act\n            ModelValidationResult result = validator.Validate(null).Single();\n\n            // Assert\n            Assert.Equal(String.Empty, result.MemberName);\n            Assert.Equal(\"Some Type Error\", result.Message);\n        }\n\n        [Fact]\n        public void GetModelValidatorWithPropertyLevelValidator()\n        {\n            // Arrange\n            ControllerContext context = new ControllerContext();\n            DataErrorInfo1 model = new DataErrorInfo1();\n            model[\"SomeStringProperty\"] = \"Some Property Error\";\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());\n            ModelValidator validator = ModelValidator.GetModelValidator(metadata, context);\n\n            // Act\n            ModelValidationResult result = validator.Validate(null).Single();\n\n            // Assert\n            Assert.Equal(\"SomeStringProperty\", result.MemberName);\n            Assert.Equal(\"Some Property Error\", result.Message);\n        }\n\n        [Fact]\n        public void GetModelValidatorWithFailedPropertyValidatorsPreventsTypeValidatorFromRunning()\n        {\n            // Arrange\n            ControllerContext context = new ControllerContext();\n            DataErrorInfo1 model = new DataErrorInfo1 { Error = \"Some Type Error\" };\n            model[\"SomeStringProperty\"] = \"Some Property Error\";\n            model[\"SomeOtherStringProperty\"] = \"Some Other Property Error\";\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());\n            ModelValidator validator = ModelValidator.GetModelValidator(metadata, context);\n\n            // Act\n            List<ModelValidationResult> result = validator.Validate(null).ToList();\n\n            // Assert\n            Assert.Equal(2, result.Count);\n            Assert.Equal(\"SomeStringProperty\", result[0].MemberName);\n            Assert.Equal(\"Some Property Error\", result[0].Message);\n            Assert.Equal(\"SomeOtherStringProperty\", result[1].MemberName);\n            Assert.Equal(\"Some Other Property Error\", result[1].Message);\n        }\n\n        private class TestableModelValidator : ModelValidator\n        {\n            public TestableModelValidator(ModelMetadata metadata, ControllerContext context)\n                : base(metadata, context)\n            {\n            }\n\n            public override IEnumerable<ModelValidationResult> Validate(object container)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class DataErrorInfo1 : IDataErrorInfo\n        {\n            private readonly Dictionary<string, string> _errors = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);\n\n            public string SomeStringProperty { get; set; }\n\n            public string SomeOtherStringProperty { get; set; }\n\n            public string Error { get; set; }\n\n            public string this[string columnName]\n            {\n                get\n                {\n                    string outVal;\n                    _errors.TryGetValue(columnName, out outVal);\n                    return outVal;\n                }\n                set { _errors[columnName] = value; }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/MultiSelectListTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class MultiSelectListTest\n    {\n        [Fact]\n        public void Constructor1SetsProperties()\n        {\n            // Arrange\n            IEnumerable items = new object[0];\n\n            // Act\n            MultiSelectList multiSelect = new MultiSelectList(items);\n\n            // Assert\n            Assert.Same(items, multiSelect.Items);\n            Assert.Null(multiSelect.DataValueField);\n            Assert.Null(multiSelect.DataTextField);\n            Assert.Null(multiSelect.SelectedValues);\n        }\n\n        [Fact]\n        public void Constructor2SetsProperties()\n        {\n            // Arrange\n            IEnumerable items = new object[0];\n            IEnumerable selectedValues = new object[0];\n\n            // Act\n            MultiSelectList multiSelect = new MultiSelectList(items, selectedValues);\n\n            // Assert\n            Assert.Same(items, multiSelect.Items);\n            Assert.Null(multiSelect.DataValueField);\n            Assert.Null(multiSelect.DataTextField);\n            Assert.Same(selectedValues, multiSelect.SelectedValues);\n        }\n\n        [Fact]\n        public void Constructor3SetsProperties_SelectedValues_DisabledValues()\n        {\n            // Arrange\n            IEnumerable items = new[] { \"A\", \"B\", \"C\" };\n            IEnumerable selectedValues = new[] { \"A\", \"C\" };\n            IEnumerable disabledValues = new[] { \"B\", \"C\" };\n\n            // Act\n            MultiSelectList multiSelect = new MultiSelectList(items, selectedValues, disabledValues);\n\n            // Assert\n            Assert.Same(items, multiSelect.Items);\n            Assert.Equal(selectedValues, multiSelect.SelectedValues);\n            Assert.Equal(disabledValues, multiSelect.DisabledValues);\n            Assert.Null(multiSelect.DataTextField);\n            Assert.Null(multiSelect.DataValueField);\n        }\n\n        [Fact]\n        public void Constructor3SetsProperties_Value_Text()\n        {\n            // Arrange\n            IEnumerable items = new object[0];\n\n            // Act\n            MultiSelectList multiSelect = new MultiSelectList(items, \"SomeValueField\", \"SomeTextField\");\n\n            // Assert\n            Assert.Same(items, multiSelect.Items);\n            Assert.Equal(\"SomeValueField\", multiSelect.DataValueField);\n            Assert.Equal(\"SomeTextField\", multiSelect.DataTextField);\n            Assert.Null(multiSelect.SelectedValues);\n        }\n\n        [Fact]\n        public void Constructor4SetsProperties()\n        {\n            // Arrange\n            IEnumerable items = new object[0];\n            IEnumerable selectedValues = new object[0];\n\n            // Act\n            MultiSelectList multiSelect = new MultiSelectList(items, \"SomeValueField\", \"SomeTextField\", selectedValues);\n\n            // Assert\n            Assert.Same(items, multiSelect.Items);\n            Assert.Equal(\"SomeValueField\", multiSelect.DataValueField);\n            Assert.Equal(\"SomeTextField\", multiSelect.DataTextField);\n            Assert.Same(selectedValues, multiSelect.SelectedValues);\n        }\n\n        [Fact]\n        public void Constructor_SetsProperties_Items_SelectedValues_DisabledValues_Groups()\n        {\n            // Arrange\n            MultiSelectList multiSelect = new MultiSelectList(GetSampleAnonymousObjectsWithGroups(),\n                \"Letter\", \"FullWord\", \"Group\",\n                selectedValues: new[] { \"A\", \"C\", \"T\" },\n                disabledValues: new[] { \"C\" },\n                disabledGroups: null);\n\n            // Act\n            IList<SelectListItem> listItems = multiSelect.GetListItems();\n\n            // Assert\n            Assert.Equal(3, listItems.Count);\n\n            Assert.Equal(\"A\", listItems[0].Value);\n            Assert.Equal(\"Alpha\", listItems[0].Text);\n            Assert.True(listItems[0].Selected);\n            Assert.False(listItems[0].Disabled);\n\n            Assert.Equal(\"B\", listItems[1].Value);\n            Assert.Equal(\"Bravo\", listItems[1].Text);\n            Assert.False(listItems[1].Selected);\n            Assert.False(listItems[1].Disabled);\n\n            Assert.Equal(\"C\", listItems[2].Value);\n            Assert.Equal(\"Charlie\", listItems[2].Text);\n            Assert.True(listItems[2].Selected);\n            Assert.True(listItems[2].Disabled);\n\n            Assert.Equal(\"AB\", listItems[0].Group.Name);\n            Assert.Equal(\"AB\", listItems[1].Group.Name);\n            Assert.Equal(\"C\", listItems[2].Group.Name);\n        }\n\n        [Fact]\n        public void Constructor_SetsProperties_Items_SelectedValues_DisabledValues_Groups_DisabledGroups()\n        {\n            // Arrange\n            object[] disabledValues = { \"C\" };\n            object[] disabledGroups = { \"AB\" };\n            MultiSelectList multiSelect = new MultiSelectList(GetSampleAnonymousObjectsWithGroups(),\n                \"Letter\", \"FullWord\", \"Group\",\n                selectedValues: new[] { \"A\", \"C\", \"T\" },\n                disabledValues: disabledValues,\n                disabledGroups: disabledGroups);\n\n            // Act\n            IList<SelectListItem> listItems = multiSelect.GetListItems();\n\n            // Assert\n            // Count of Items and Groups\n            Assert.Equal(3, listItems.Count);\n\n            // Getters\n            Assert.Same(disabledValues, multiSelect.DisabledValues);\n            Assert.Same(disabledGroups, multiSelect.DisabledGroups);\n\n            // Item A\n            Assert.Equal(\"A\", listItems[0].Value);\n            Assert.Equal(\"Alpha\", listItems[0].Text);\n            Assert.True(listItems[0].Selected);\n            Assert.False(listItems[0].Disabled);\n\n            // Item B\n            Assert.Equal(\"B\", listItems[1].Value);\n            Assert.Equal(\"Bravo\", listItems[1].Text);\n            Assert.False(listItems[1].Selected);\n            Assert.False(listItems[1].Disabled);\n\n            // Item C\n            Assert.Equal(\"C\", listItems[2].Value);\n            Assert.Equal(\"Charlie\", listItems[2].Text);\n            Assert.True(listItems[2].Selected);\n            Assert.True(listItems[2].Disabled);\n\n            // Group AB\n            Assert.Equal(\"AB\", listItems[0].Group.Name);\n            Assert.Equal(\"AB\", listItems[1].Group.Name);\n            Assert.True(listItems[0].Group.Disabled);\n            Assert.Same(listItems[0].Group, listItems[1].Group);\n\n            // Group C is disabled.\n            Assert.Equal(\"C\", listItems[2].Group.Name);\n            Assert.False(listItems[2].Group.Disabled);\n        }\n\n        [Fact]\n        public void Constructor_SetsProperties_Items_Value_Text_SelectedValues_DisabledValues_Groups()\n        {\n            // Arrange\n            IEnumerable items = new object[0];\n            IEnumerable selectedValues = new object[0];\n            IEnumerable disabledValues = new object[0];\n\n            // Act\n            MultiSelectList multiSelect = new MultiSelectList(items, \"SomeValueField\", \"SomeTextField\", \"SomeGroupField\",\n                selectedValues,\n                disabledValues);\n\n            // Assert\n            Assert.Same(items, multiSelect.Items);\n            Assert.Equal(\"SomeValueField\", multiSelect.DataValueField);\n            Assert.Equal(\"SomeTextField\", multiSelect.DataTextField);\n            Assert.Equal(\"SomeGroupField\", multiSelect.DataGroupField);\n            Assert.Same(selectedValues, multiSelect.SelectedValues);\n            Assert.Equal(disabledValues, multiSelect.DisabledValues);\n        }\n\n        [Fact]\n        public void DataGroupFieldSetByCtor()\n        {\n            // Arrange\n            IEnumerable items = new object[0];\n            IEnumerable selectedValues = new object[0];\n\n            // Act\n            MultiSelectList multiSelect = new MultiSelectList(items, \"SomeValueField\", \"SomeTextField\", \"SomeGroupField\",\n                selectedValues);\n\n            // Assert\n            Assert.Same(items, multiSelect.Items);\n            Assert.Equal(\"SomeValueField\", multiSelect.DataValueField);\n            Assert.Equal(\"SomeTextField\", multiSelect.DataTextField);\n            Assert.Same(selectedValues, multiSelect.SelectedValues);\n            Assert.Equal(\"SomeGroupField\", multiSelect.DataGroupField);\n        }\n\n        [Fact]\n        public void Constructor_SetsProperties_Items_Value_Text_SelectedValues_DisabledValues()\n        {\n            // Arrange\n            object[] disabledValues = { \"C\" };\n            MultiSelectList multiSelect = new MultiSelectList(GetSampleAnonymousObjectsWithGroups(),\n                \"Letter\", \"FullWord\",\n                new[] { \"A\", \"C\", \"T\" },\n                disabledValues);\n\n            // Act\n            IList<SelectListItem> listItems = multiSelect.GetListItems();\n\n            // Assert\n            // Count of Items\n            Assert.Equal(3, listItems.Count);\n\n            // Getters\n            Assert.Same(disabledValues, multiSelect.DisabledValues);\n\n            // Item A\n            Assert.Equal(\"A\", listItems[0].Value);\n            Assert.Equal(\"Alpha\", listItems[0].Text);\n            Assert.True(listItems[0].Selected);\n            Assert.False(listItems[0].Disabled);\n\n            // Item B\n            Assert.Equal(\"B\", listItems[1].Value);\n            Assert.Equal(\"Bravo\", listItems[1].Text);\n            Assert.False(listItems[1].Selected);\n            Assert.False(listItems[1].Disabled);\n\n            // Item C\n            Assert.Equal(\"C\", listItems[2].Value);\n            Assert.Equal(\"Charlie\", listItems[2].Text);\n            Assert.True(listItems[2].Selected);\n            Assert.True(listItems[2].Disabled);\n\n            Assert.Equal(disabledValues, multiSelect.DisabledValues);\n        }\n\n        [Fact]\n        public void ConstructorWithNullItemsThrows()\n        {\n            Assert.ThrowsArgumentNull(\n                delegate { new MultiSelectList(null /* items */, \"dataValueField\", \"dataTextField\", null /* selectedValues */); }, \"items\");\n        }\n\n        [Fact]\n        public void GetListItemsThrowsOnBindingFailure()\n        {\n            // Arrange\n            MultiSelectList multiSelect = new MultiSelectList(GetSampleFieldObjects(),\n                                                              \"Text\", \"Value\", new string[] { \"A\", \"C\", \"T\" });\n\n            // Assert\n            Assert.ThrowsHttpException(\n                delegate { IList<SelectListItem> listItems = multiSelect.GetListItems(); }, \"DataBinding: 'System.Web.Mvc.Test.MultiSelectListTest+Item' does not contain a property with the name 'Text'.\", 500);\n        }\n\n        [Fact]\n        public void GetListItemsWithoutValueField()\n        {\n            // Arrange\n            MultiSelectList multiSelect = new MultiSelectList(GetSampleStrings());\n\n            // Act\n            IList<SelectListItem> listItems = multiSelect.GetListItems();\n\n            // Assert\n            Assert.Equal(3, listItems.Count);\n            Assert.Null(listItems[0].Value);\n            Assert.Equal(\"Alpha\", listItems[0].Text);\n            Assert.False(listItems[0].Selected);\n            Assert.Null(listItems[1].Value);\n            Assert.Equal(\"Bravo\", listItems[1].Text);\n            Assert.False(listItems[1].Selected);\n            Assert.Null(listItems[2].Value);\n            Assert.Equal(\"Charlie\", listItems[2].Text);\n            Assert.False(listItems[2].Selected);\n        }\n\n        [Fact]\n        public void GetListItemsWithoutValueFieldWithSelections()\n        {\n            // Arrange\n            MultiSelectList multiSelect = new MultiSelectList(GetSampleStrings(), new string[] { \"Alpha\", \"Charlie\", \"Tango\" });\n\n            // Act\n            IList<SelectListItem> listItems = multiSelect.GetListItems();\n\n            // Assert\n            Assert.Equal(3, listItems.Count);\n            Assert.Null(listItems[0].Value);\n            Assert.Equal(\"Alpha\", listItems[0].Text);\n            Assert.True(listItems[0].Selected);\n            Assert.Null(listItems[1].Value);\n            Assert.Equal(\"Bravo\", listItems[1].Text);\n            Assert.False(listItems[1].Selected);\n            Assert.Null(listItems[2].Value);\n            Assert.Equal(\"Charlie\", listItems[2].Text);\n            Assert.True(listItems[2].Selected);\n        }\n\n        [Fact]\n        public void GetListItemsWithValueField()\n        {\n            // Arrange\n            MultiSelectList multiSelect = new MultiSelectList(GetSampleAnonymousObjects(), \"Letter\", \"FullWord\");\n\n            // Act\n            IList<SelectListItem> listItems = multiSelect.GetListItems();\n\n            // Assert\n            Assert.Equal(3, listItems.Count);\n            Assert.Equal(\"A\", listItems[0].Value);\n            Assert.Equal(\"Alpha\", listItems[0].Text);\n            Assert.False(listItems[0].Selected);\n            Assert.Equal(\"B\", listItems[1].Value);\n            Assert.Equal(\"Bravo\", listItems[1].Text);\n            Assert.False(listItems[1].Selected);\n            Assert.Equal(\"C\", listItems[2].Value);\n            Assert.Equal(\"Charlie\", listItems[2].Text);\n            Assert.False(listItems[2].Selected);\n        }\n\n        [Fact]\n        public void GetListItemsWithGroupField()\n        {\n            // Arrange\n            MultiSelectList multiSelect = new MultiSelectList(GetSampleAnonymousObjectsWithGroups(),\n                                                              \"Letter\",\n                                                              \"FullWord\",\n                                                              \"Group\");\n\n            // Act\n            IList<SelectListItem> listItems = multiSelect.GetListItems();\n\n            // Assert\n            Assert.Equal(3, listItems.Count);\n            Assert.Equal(\"A\", listItems[0].Value);\n            Assert.Equal(\"Alpha\", listItems[0].Text);\n            Assert.False(listItems[0].Selected);\n            Assert.Equal(\"B\", listItems[1].Value);\n            Assert.Equal(\"Bravo\", listItems[1].Text);\n            Assert.False(listItems[1].Selected);\n            Assert.Equal(\"C\", listItems[2].Value);\n            Assert.Equal(\"Charlie\", listItems[2].Text);\n            Assert.False(listItems[2].Selected);\n            Assert.Equal(\"AB\", listItems[0].Group.Name);\n            Assert.Equal(\"AB\", listItems[1].Group.Name);\n            Assert.Equal(\"C\", listItems[2].Group.Name);\n        }\n\n        [Fact]\n        public void GetListItemsWithValueFieldWithSelections()\n        {\n            // Arrange\n            MultiSelectList multiSelect = new MultiSelectList(GetSampleAnonymousObjects(),\n                                                              \"Letter\", \"FullWord\", new string[] { \"A\", \"C\", \"T\" });\n\n            // Act\n            IList<SelectListItem> listItems = multiSelect.GetListItems();\n\n            // Assert\n            Assert.Equal(3, listItems.Count);\n            Assert.Equal(\"A\", listItems[0].Value);\n            Assert.Equal(\"Alpha\", listItems[0].Text);\n            Assert.True(listItems[0].Selected);\n            Assert.Equal(\"B\", listItems[1].Value);\n            Assert.Equal(\"Bravo\", listItems[1].Text);\n            Assert.False(listItems[1].Selected);\n            Assert.Equal(\"C\", listItems[2].Value);\n            Assert.Equal(\"Charlie\", listItems[2].Text);\n            Assert.True(listItems[2].Selected);\n        }\n\n        [Fact]\n        public void GetListItemsWithValueFieldWithSelectionsWithGroupField()\n        {\n            // Arrange\n            MultiSelectList multiSelect = new MultiSelectList(GetSampleAnonymousObjectsWithGroups(),\n                \"Letter\", \"FullWord\", \"Group\", new string[] { \"A\", \"C\", \"T\" });\n\n            // Act\n            IList<SelectListItem> listItems = multiSelect.GetListItems();\n\n            // Assert\n            Assert.Equal(3, listItems.Count);\n            Assert.Equal(\"A\", listItems[0].Value);\n            Assert.Equal(\"Alpha\", listItems[0].Text);\n            Assert.True(listItems[0].Selected);\n            Assert.Equal(\"B\", listItems[1].Value);\n            Assert.Equal(\"Bravo\", listItems[1].Text);\n            Assert.False(listItems[1].Selected);\n            Assert.Equal(\"C\", listItems[2].Value);\n            Assert.Equal(\"Charlie\", listItems[2].Text);\n            Assert.True(listItems[2].Selected);\n            Assert.Equal(\"AB\", listItems[0].Group.Name);\n            Assert.Equal(\"AB\", listItems[1].Group.Name);\n            Assert.Equal(\"C\", listItems[2].Group.Name);\n        }\n\n        [Fact]\n        public void IEnumerableWithAnonymousObjectsAndTextValueFields()\n        {\n            // Arrange\n            MultiSelectList multiSelect = new MultiSelectList(GetSampleAnonymousObjects(),\n                                                              \"Letter\", \"FullWord\", new string[] { \"A\", \"C\", \"T\" });\n\n            // Act\n            IEnumerator enumerator = multiSelect.GetEnumerator();\n            enumerator.MoveNext();\n            SelectListItem firstItem = enumerator.Current as SelectListItem;\n            SelectListItem lastItem = null;\n\n            while (enumerator.MoveNext())\n            {\n                lastItem = enumerator.Current as SelectListItem;\n            }\n\n            // Assert\n            Assert.True(firstItem != null);\n            Assert.Equal(\"Alpha\", firstItem.Text);\n            Assert.Equal(\"A\", firstItem.Value);\n            Assert.True(firstItem.Selected);\n\n            Assert.True(lastItem != null);\n            Assert.Equal(\"Charlie\", lastItem.Text);\n            Assert.Equal(\"C\", lastItem.Value);\n            Assert.True(lastItem.Selected);\n        }\n\n        internal static IEnumerable GetSampleAnonymousObjects()\n        {\n            return new[]\n            {\n                new { Letter = 'A', FullWord = \"Alpha\" },\n                new { Letter = 'B', FullWord = \"Bravo\" },\n                new { Letter = 'C', FullWord = \"Charlie\" }\n            };\n        }\n\n        internal static IEnumerable GetSampleAnonymousObjectsWithGroups()\n        {\n            return new[]\n            {\n                new { Letter = 'A', FullWord = \"Alpha\", Group = \"AB\" },\n                new { Letter = 'B', FullWord = \"Bravo\", Group = \"AB\" },\n                new { Letter = 'C', FullWord = \"Charlie\", Group = \"C\" },\n            };\n        }\n\n        internal static IEnumerable GetSampleFieldObjects()\n        {\n            return new[]\n            {\n                new Item { Text = \"A\", Value = \"Alpha\" },\n                new Item { Text = \"B\", Value = \"Bravo\" },\n                new Item { Text = \"C\", Value = \"Charlie\" }\n            };\n        }\n\n        internal static List<SelectListItem> GetSampleListObjects()\n        {\n            List<SelectListItem> list = new List<SelectListItem>();\n            string selectedSSN = \"111111111\";\n\n            foreach (Person person in GetSamplePeople())\n            {\n                list.Add(new SelectListItem\n                {\n                    Text = person.FirstName,\n                    Value = person.SSN,\n                    Selected = String.Equals(person.SSN, selectedSSN)\n                });\n            }\n            return list;\n        }\n\n        internal static IEnumerable<SelectListItem> GetSampleIEnumerableObjects()\n        {\n            Person[] people = GetSamplePeople();\n\n            string selectedSSN = \"111111111\";\n            IEnumerable<SelectListItem> list = from person in people\n                                               select new SelectListItem\n                                               {\n                                                   Text = person.FirstName,\n                                                   Value = person.SSN,\n                                                   Selected = String.Equals(person.SSN, selectedSSN)\n                                               };\n            return list;\n        }\n\n        internal static IEnumerable GetSampleStrings()\n        {\n            return new string[] { \"Alpha\", \"Bravo\", \"Charlie\" };\n        }\n\n        internal static Person[] GetSamplePeople()\n        {\n            return new Person[]\n            {\n                new Person\n                {\n                    FirstName = \"John\",\n                    SSN = \"123456789\"\n                },\n                new Person\n                {\n                    FirstName = \"Jane\",\n                    SSN = \"987654321\"\n                },\n                new Person\n                {\n                    FirstName = \"Joe\",\n                    SSN = \"111111111\"\n                }\n            };\n        }\n\n        internal class Item\n        {\n            public string Text;\n            public string Value;\n        }\n\n        internal class Person\n        {\n            public string FirstName { get; set; }\n\n            public string SSN { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/MultiServiceResolverTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class MultiServiceResolverTest\n    {\n        [Fact]\n        public void GetCombinedPrependsFromResolver()\n        {\n            // Arrange\n            IEnumerable<TestProvider> providersFromServiceLocation = GetProvidersFromService();\n            IList<TestProvider> providersFromItemsThunk = GetProvidersFromItemsThunk().ToList();\n            IEnumerable<TestProvider> expectedProviders = providersFromServiceLocation.Concat(providersFromItemsThunk);\n\n            Mock<IDependencyResolver> resolver = new Mock<IDependencyResolver>();\n            resolver.Setup(r => r.GetServices(typeof(TestProvider)))\n                .Returns(providersFromServiceLocation);\n\n            // Act\n            IEnumerable<TestProvider> returnedProviders = MultiServiceResolver.GetCombined<TestProvider>(providersFromItemsThunk, resolver.Object);\n\n            // Assert\n            Assert.Equal(expectedProviders.ToList(), returnedProviders.ToList());\n        }\n\n        [Fact]\n        public void CurrentReturnsCurrentItemsWhenResolverReturnsNoInstances()\n        {\n            // Arrange\n            IList<TestProvider> providersFromItemsThunk = GetProvidersFromItemsThunk().ToList();\n\n            // Act\n            IEnumerable<TestProvider> returnedProviders = MultiServiceResolver.GetCombined<TestProvider>(providersFromItemsThunk, null);\n\n            // Assert\n            Assert.Equal(providersFromItemsThunk.ToList(), returnedProviders.ToList());\n        }\n\n        [Fact]\n        public void CurrentPropagatesExceptionWhenResolverThrowsNonActivationException()\n        {\n            // Arrange\n            Mock<IDependencyResolver> resolver = new Mock<IDependencyResolver>(MockBehavior.Strict);\n\n            // Act & Assert\n            var ex = Assert.Throws<MockException>(\n                () => MultiServiceResolver.GetCombined<TestProvider>(null, resolver.Object));\n            Assert.Equal(\n                \"IDependencyResolver.GetServices(System.Web.Mvc.Test.MultiServiceResolverTest+TestProvider) invocation failed with mock behavior Strict.\" +\n                Environment.NewLine +\n                \"All invocations on the mock must have a corresponding setup.\",\n                ex.Message,\n                ignoreLineEndingDifferences: true);\n        }\n\n        private class TestProvider\n        {\n        }\n\n        private IEnumerable<TestProvider> GetProvidersFromService()\n        {\n            return new TestProvider[]\n            {\n                new TestProvider(),\n                new TestProvider()\n            };\n        }\n\n        private IEnumerable<TestProvider> GetProvidersFromItemsThunk()\n        {\n            return new TestProvider[]\n            {\n                new TestProvider(),\n                new TestProvider()\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/MvcHandlerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc.Async;\nusing System.Web.Mvc.Async.Test;\nusing System.Web.Routing;\nusing System.Web.SessionState;\nusing Microsoft.TestCommon;\nusing Moq;\nusing Moq.Protected;\n\nnamespace System.Web.Mvc.Test\n{\n    public class MvcHandlerTest\n    {\n        [Fact]\n        public void ConstructorWithNullRequestContextThrows()\n        {\n            Assert.ThrowsArgumentNull(\n                delegate { new MvcHandler(null); },\n                \"requestContext\");\n        }\n\n        [Fact]\n        public void ProcessRequestWithRouteWithoutControllerThrows()\n        {\n            // Arrange\n            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>();\n            contextMock.ExpectMvcVersionResponseHeader().Verifiable();\n            RouteData rd = new RouteData();\n            MvcHandler mvcHandler = new MvcHandler(new RequestContext(contextMock.Object, rd));\n\n            // Act\n            Assert.Throws<InvalidOperationException>(\n                delegate { mvcHandler.ProcessRequest(contextMock.Object); },\n                \"The RouteData must contain an item named 'controller' with a non-empty string value.\");\n\n            // Assert\n            contextMock.Verify();\n        }\n\n        [Fact]\n        public void ProcessRequestAddsServerHeaderCallsExecute()\n        {\n            // Arrange\n            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>();\n            contextMock.ExpectMvcVersionResponseHeader().Verifiable();\n\n            RouteData rd = new RouteData();\n            rd.Values.Add(\"controller\", \"foo\");\n            RequestContext requestContext = new RequestContext(contextMock.Object, rd);\n            MvcHandler mvcHandler = new MvcHandler(requestContext);\n\n            Mock<ControllerBase> controllerMock = new Mock<ControllerBase>();\n            controllerMock.As<IController>().CallBase = true;\n            controllerMock.Protected().Setup(\"Execute\", requestContext).Verifiable();\n\n            ControllerBuilder cb = new ControllerBuilder();\n            Mock<IControllerFactory> controllerFactoryMock = new Mock<IControllerFactory>();\n            controllerFactoryMock.Setup(o => o.CreateController(requestContext, \"foo\")).Returns(controllerMock.Object);\n            controllerFactoryMock.Setup(o => o.ReleaseController(controllerMock.Object));\n            cb.SetControllerFactory(controllerFactoryMock.Object);\n            mvcHandler.ControllerBuilder = cb;\n\n            // Act\n            mvcHandler.ProcessRequest(contextMock.Object);\n\n            // Assert\n            contextMock.Verify();\n            controllerMock.Verify();\n        }\n\n        [Fact]\n        public void ProcessRequestRemovesOptionalParametersFromRouteValueDictionary()\n        {\n            // Arrange\n            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>();\n            contextMock.ExpectMvcVersionResponseHeader();\n\n            RouteData rd = new RouteData();\n            rd.Values.Add(\"controller\", \"foo\");\n            rd.Values.Add(\"optional\", UrlParameter.Optional);\n            RequestContext requestContext = new RequestContext(contextMock.Object, rd);\n            MvcHandler mvcHandler = new MvcHandler(requestContext);\n\n            Mock<ControllerBase> controllerMock = new Mock<ControllerBase>();\n            controllerMock.As<IController>().CallBase = true;\n            controllerMock.Protected().Setup(\"Execute\", requestContext).Verifiable();\n\n            ControllerBuilder cb = new ControllerBuilder();\n            Mock<IControllerFactory> controllerFactoryMock = new Mock<IControllerFactory>();\n            controllerFactoryMock.Setup(o => o.CreateController(requestContext, \"foo\")).Returns(controllerMock.Object);\n            controllerFactoryMock.Setup(o => o.ReleaseController(controllerMock.Object));\n            cb.SetControllerFactory(controllerFactoryMock.Object);\n            mvcHandler.ControllerBuilder = cb;\n\n            // Act\n            mvcHandler.ProcessRequest(contextMock.Object);\n\n            // Assert\n            controllerMock.Verify();\n            Assert.False(rd.Values.ContainsKey(\"optional\"));\n        }\n\n        [Fact]\n        public void ProcessRequestWithDisabledServerHeaderOnlyCallsExecute()\n        {\n            bool oldResponseHeaderValue = MvcHandler.DisableMvcResponseHeader;\n            try\n            {\n                // Arrange\n                MvcHandler.DisableMvcResponseHeader = true;\n                Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>();\n\n                RouteData rd = new RouteData();\n                rd.Values.Add(\"controller\", \"foo\");\n                RequestContext requestContext = new RequestContext(contextMock.Object, rd);\n                MvcHandler mvcHandler = new MvcHandler(requestContext);\n\n                Mock<ControllerBase> controllerMock = new Mock<ControllerBase>();\n                controllerMock.As<IController>().CallBase = true;\n                controllerMock.Protected().Setup(\"Execute\", requestContext).Verifiable();\n\n                ControllerBuilder cb = new ControllerBuilder();\n                Mock<IControllerFactory> controllerFactoryMock = new Mock<IControllerFactory>();\n                controllerFactoryMock.Setup(o => o.CreateController(requestContext, \"foo\")).Returns(controllerMock.Object);\n                controllerFactoryMock.Setup(o => o.ReleaseController(controllerMock.Object));\n                cb.SetControllerFactory(controllerFactoryMock.Object);\n                mvcHandler.ControllerBuilder = cb;\n\n                // Act\n                mvcHandler.ProcessRequest(contextMock.Object);\n\n                // Assert\n                controllerMock.Verify();\n            }\n            finally\n            {\n                MvcHandler.DisableMvcResponseHeader = oldResponseHeaderValue;\n            }\n        }\n\n        [Fact]\n        public void ProcessRequestDisposesControllerIfExecuteDoesNotThrowException()\n        {\n            // Arrange\n            Mock<ControllerBase> mockController = new Mock<ControllerBase>();\n            mockController.As<IDisposable>().Setup(c => c.Dispose()); // so that Verify can be called on Dispose later\n            mockController.As<IController>().CallBase = true;\n            mockController.Protected().Setup(\"Execute\", ItExpr.IsAny<RequestContext>()).Verifiable();\n\n            ControllerBuilder builder = new ControllerBuilder();\n            builder.SetControllerFactory(new SimpleControllerFactory(mockController.Object));\n\n            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>();\n            contextMock.ExpectMvcVersionResponseHeader().Verifiable();\n            RequestContext requestContext = new RequestContext(contextMock.Object, new RouteData());\n            requestContext.RouteData.Values[\"controller\"] = \"fooController\";\n            MvcHandler handler = new MvcHandler(requestContext)\n            {\n                ControllerBuilder = builder\n            };\n\n            // Act\n            handler.ProcessRequest(requestContext.HttpContext);\n\n            // Assert\n            mockController.Verify();\n            contextMock.Verify();\n            mockController.As<IDisposable>().Verify(d => d.Dispose(), Times.AtMostOnce());\n        }\n\n        [Fact]\n        public void ProcessRequestDisposesControllerIfExecuteThrowsException()\n        {\n            // Arrange\n            Mock<ControllerBase> mockController = new Mock<ControllerBase>();\n            mockController.As<IDisposable>().Setup(d => d.Dispose()); // so that Verify can be called on Dispose later\n            mockController.As<IController>().CallBase = true;\n            mockController.Protected().Setup(\"Execute\", ItExpr.IsAny<RequestContext>()).Throws(new Exception(\"some exception\"));\n\n            ControllerBuilder builder = new ControllerBuilder();\n            builder.SetControllerFactory(new SimpleControllerFactory(mockController.Object));\n\n            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>();\n            contextMock.ExpectMvcVersionResponseHeader().Verifiable();\n            RequestContext requestContext = new RequestContext(contextMock.Object, new RouteData());\n            requestContext.RouteData.Values[\"controller\"] = \"fooController\";\n            MvcHandler handler = new MvcHandler(requestContext)\n            {\n                ControllerBuilder = builder\n            };\n\n            // Act\n            Assert.Throws<Exception>(\n                delegate { handler.ProcessRequest(requestContext.HttpContext); },\n                \"some exception\");\n\n            // Assert\n            mockController.Verify();\n            contextMock.Verify();\n            mockController.As<IDisposable>().Verify(d => d.Dispose(), Times.AtMostOnce());\n        }\n\n        [Fact]\n        public void ProcessRequestAsync_AsyncController_DisposesControllerOnException()\n        {\n            // Arrange\n            Mock<IAsyncController> mockController = new Mock<IAsyncController>();\n            mockController.Setup(o => o.BeginExecute(It.IsAny<RequestContext>(), It.IsAny<AsyncCallback>(), It.IsAny<object>())).Throws(new Exception(\"Some exception text.\"));\n            mockController.As<IDisposable>().Setup(o => o.Dispose()).Verifiable();\n\n            MvcHandler handler = GetMvcHandler(mockController.Object);\n\n            // Act & assert\n            Assert.Throws<Exception>(\n                delegate { handler.BeginProcessRequest(handler.RequestContext.HttpContext, null, null); },\n                @\"Some exception text.\");\n\n            mockController.Verify();\n        }\n\n        [Fact]\n        public void ProcessRequestAsync_AsyncController_NormalExecution()\n        {\n            // Arrange\n            using (MockAsyncResult innerAsyncResult = new MockAsyncResult())\n            {\n                bool disposeWasCalled = false;\n\n                Mock<IAsyncController> mockController = new Mock<IAsyncController>();\n                mockController.Setup(o => o.BeginExecute(It.IsAny<RequestContext>(), It.IsAny<AsyncCallback>(), It.IsAny<object>())).Returns(innerAsyncResult);\n                mockController.As<IDisposable>().Setup(o => o.Dispose()).Callback(delegate { disposeWasCalled = true; });\n\n                MvcHandler handler = GetMvcHandler(mockController.Object);\n\n                // Act & assert\n                IAsyncResult outerAsyncResult = handler.BeginProcessRequest(handler.RequestContext.HttpContext, null, null);\n                Assert.False(disposeWasCalled);\n\n                handler.EndProcessRequest(outerAsyncResult);\n                Assert.True(disposeWasCalled);\n                mockController.Verify(o => o.EndExecute(innerAsyncResult), Times.AtMostOnce());\n            }\n        }\n\n        [Fact]\n        public void ProcessRequestAsync_SyncController_NormalExecution()\n        {\n            // Arrange\n            bool executeWasCalled = false;\n            bool disposeWasCalled = false;\n\n            Mock<IController> mockController = new Mock<IController>();\n            mockController.Setup(o => o.Execute(It.IsAny<RequestContext>())).Callback(delegate { executeWasCalled = true; });\n            mockController.As<IDisposable>().Setup(o => o.Dispose()).Callback(delegate { disposeWasCalled = true; });\n\n            MvcHandler handler = GetMvcHandler(mockController.Object);\n\n            // Act & assert\n            IAsyncResult outerAsyncResult = handler.BeginProcessRequest(handler.RequestContext.HttpContext, null, null);\n            Assert.False(executeWasCalled);\n            Assert.False(disposeWasCalled);\n\n            handler.EndProcessRequest(outerAsyncResult);\n            Assert.True(executeWasCalled);\n            Assert.True(disposeWasCalled);\n        }\n\n        // Test that execute is called on a  user controller that derives from Controller\n        [Fact]\n        public void ProcessRequestAsync_SyncController_NormalExecution2()\n        {\n            // Arrange\n            MyCustomerController controller = new MyCustomerController();\n\n            MvcHandler handler = GetMvcHandler(controller);\n            handler.RequestContext.RouteData.Values[\"action\"] = \"Widget\";\n\n            // Act\n            IAsyncResult outerAsyncResult = handler.BeginProcessRequest(handler.RequestContext.HttpContext, null, null);\n            handler.EndProcessRequest(outerAsyncResult);\n\n            // Assert\n            Assert.Equal(1, controller.Called);\n        }\n\n        private class EmptyActionInvoker : IActionInvoker\n        {\n            public bool InvokeAction(ControllerContext controllerContext, string actionName)\n            {\n                return true; // action handled.\n            }\n        }\n\n        // Class that captures how an end-user would override and use a Controller\n        private class MyCustomerController : Controller\n        {\n            public int Called { get; set; }\n\n            protected override void ExecuteCore()\n            {\n                this.Called++;\n            }\n\n            protected override IActionInvoker CreateActionInvoker()\n            {\n                // The default action invoker relies on too much state (like having an HttpRequestContext), so stub it out.\n                return new EmptyActionInvoker();\n            }\n\n            // Workaround.\n            protected override bool DisableAsyncSupport\n            {\n                get\n                {\n                    return true; // ensure ExecuteCore still gets called.\n                }\n            }\n        }\n\n        private static MvcHandler GetMvcHandler(IController controller)\n        {\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(o => o.Response.AddHeader(\"X-AspNetMvc-Version\", \"2.0\"));\n\n            RouteData routeData = new RouteData();\n            routeData.Values[\"controller\"] = \"SomeController\";\n            RequestContext requestContext = new RequestContext(mockHttpContext.Object, routeData);\n\n            ControllerBuilder controllerBuilder = new ControllerBuilder();\n            controllerBuilder.SetControllerFactory(new SimpleControllerFactory(controller));\n\n            return new MvcHandler(requestContext)\n            {\n                ControllerBuilder = controllerBuilder\n            };\n        }\n\n        private class SimpleControllerFactory : IControllerFactory\n        {\n            private IController _instance;\n\n            public SimpleControllerFactory(IController instance)\n            {\n                _instance = instance;\n            }\n\n            public IController CreateController(RequestContext context, string controllerName)\n            {\n                return _instance;\n            }\n\n            public SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName)\n            {\n                return SessionStateBehavior.Default;\n            }\n\n            public void ReleaseController(IController controller)\n            {\n                IDisposable disposable = controller as IDisposable;\n                if (disposable != null)\n                {\n                    disposable.Dispose();\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/MvcHtmlStringTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class MvcHtmlStringTest\n    {\n        // IsNullOrEmpty\n\n        [Fact]\n        public void IsNullOrEmptyTests()\n        {\n            // Act & Assert\n            Assert.True(MvcHtmlString.IsNullOrEmpty(null));\n            Assert.True(MvcHtmlString.IsNullOrEmpty(MvcHtmlString.Empty));\n            Assert.True(MvcHtmlString.IsNullOrEmpty(MvcHtmlString.Create(\"\")));\n            Assert.False(MvcHtmlString.IsNullOrEmpty(MvcHtmlString.Create(\" \")));\n        }\n\n        // ToHtmlString\n\n        [Fact]\n        public void ToHtmlStringReturnsOriginalString()\n        {\n            // Arrange\n            MvcHtmlString htmlString = MvcHtmlString.Create(\"some value\");\n\n            // Act\n            string retVal = htmlString.ToHtmlString();\n\n            // Assert\n            Assert.Equal(\"some value\", retVal);\n        }\n\n        // ToString\n\n        [Fact]\n        public void ToStringReturnsOriginalString()\n        {\n            // Arrange\n            MvcHtmlString htmlString = MvcHtmlString.Create(\"some value\");\n\n            // Act\n            string retVal = htmlString.ToString();\n\n            // Assert\n            Assert.Equal(\"some value\", retVal);\n        }\n\n        [Fact]\n        public void ToStringReturnsEmptyStringIfOriginalStringWasNull()\n        {\n            // Arrange\n            MvcHtmlString htmlString = MvcHtmlString.Create(null);\n\n            // Act\n            string retVal = htmlString.ToString();\n\n            // Assert\n            Assert.Equal(\"\", retVal);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/MvcHttpHandlerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class MvcHttpHandlerTest\n    {\n        [Fact]\n        public void ConstructorDoesNothing()\n        {\n            new MvcHttpHandler();\n        }\n\n        [Fact]\n        public void VerifyAndProcessRequestWithNullHandlerThrows()\n        {\n            // Arrange\n            PublicMvcHttpHandler handler = new PublicMvcHttpHandler();\n\n            // Act\n            Assert.ThrowsArgumentNull(\n                delegate { handler.PublicVerifyAndProcessRequest(null, null); },\n                \"httpHandler\");\n        }\n\n        [Fact]\n        public void ProcessRequestCallsExecute()\n        {\n            // Arrange\n            PublicMvcHttpHandler handler = new PublicMvcHttpHandler();\n            Mock<IHttpHandler> mockTargetHandler = new Mock<IHttpHandler>();\n            mockTargetHandler.Setup(h => h.ProcessRequest(It.IsAny<HttpContext>())).Verifiable();\n\n            // Act\n            handler.PublicVerifyAndProcessRequest(mockTargetHandler.Object, null);\n\n            // Assert\n            mockTargetHandler.Verify();\n        }\n\n        private sealed class DummyHttpHandler : IHttpHandler\n        {\n            bool IHttpHandler.IsReusable\n            {\n                get { throw new NotImplementedException(); }\n            }\n\n            void IHttpHandler.ProcessRequest(HttpContext context)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private sealed class PublicMvcHttpHandler : MvcHttpHandler\n        {\n            public void PublicVerifyAndProcessRequest(IHttpHandler httpHandler, HttpContextBase httpContext)\n            {\n                base.VerifyAndProcessRequest(httpHandler, httpContext);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/MvcRouteHandlerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Routing;\nusing System.Web.SessionState;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class MvcRouteHandlerTest\n    {\n        [Fact]\n        public void GetHttpHandlerReturnsMvcHandlerWithRouteData()\n        {\n            // Arrange\n            var routeData = new RouteData();\n            routeData.Values[\"controller\"] = \"controllerName\";\n            var context = new RequestContext(new Mock<HttpContextBase>().Object, routeData);\n            var controllerFactory = new Mock<IControllerFactory>();\n            controllerFactory.Setup(f => f.GetControllerSessionBehavior(context, \"controllerName\"))\n                .Returns(SessionStateBehavior.Default)\n                .Verifiable();\n            IRouteHandler rh = new MvcRouteHandler(controllerFactory.Object);\n\n            // Act\n            IHttpHandler httpHandler = rh.GetHttpHandler(context);\n\n            // Assert\n            MvcHandler h = httpHandler as MvcHandler;\n            Assert.NotNull(h);\n            Assert.Equal(context, h.RequestContext);\n        }\n\n        [Fact]\n        public void GetHttpHandlerAsksControllerFactoryForSessionBehaviorOfController()\n        {\n            // Arrange\n            var httpContext = new Mock<HttpContextBase>();\n            var routeData = new RouteData();\n            routeData.Values[\"controller\"] = \"controllerName\";\n            var requestContext = new RequestContext(httpContext.Object, routeData);\n            var controllerFactory = new Mock<IControllerFactory>();\n            controllerFactory.Setup(f => f.GetControllerSessionBehavior(requestContext, \"controllerName\"))\n                .Returns(SessionStateBehavior.ReadOnly)\n                .Verifiable();\n            IRouteHandler routeHandler = new MvcRouteHandler(controllerFactory.Object);\n\n            // Act\n            routeHandler.GetHttpHandler(requestContext);\n\n            // Assert\n            controllerFactory.Verify();\n            httpContext.Verify(c => c.SetSessionStateBehavior(SessionStateBehavior.ReadOnly));\n        }\n\n        [Fact]\n        public void GetHttpHandlerThrowsIfTheRouteValuesDoesNotIncludeAControllerName()\n        {\n            // Arrange\n            var httpContext = new Mock<HttpContextBase>();\n            var routeData = new RouteData();\n            var requestContext = new RequestContext(httpContext.Object, routeData);\n            IRouteHandler routeHandler = new MvcRouteHandler();\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => routeHandler.GetHttpHandler(requestContext),\n                \"The matched route does not include a 'controller' route value, which is required.\"\n                );\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/MvcTestHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing System.Reflection.Emit;\n\nnamespace System.Web.Mvc.Test\n{\n    internal static class MvcTestHelper\n    {\n        private static bool _mvcAssembliesCreated;\n\n        public static void CreateMvcAssemblies()\n        {\n            // Only create MVC assemblies once per appdomain. This method is called from the static ctor of several\n            // test classes.\n            if (_mvcAssembliesCreated)\n            {\n                return;\n            }\n\n            CreateMvcTestAssembly1();\n            CreateMvcTestAssembly2();\n            CreateMvcTestAssembly3();\n            CreateMvcTestAssembly4();\n\n            _mvcAssembliesCreated = true;\n        }\n\n        private static void CreateMvcTestAssembly1()\n        {\n            AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(\n                new AssemblyName(\"MvcAssembly1\"),\n                AssemblyBuilderAccess.Save);\n            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(\n                \"MvcAssembly1\", \"MvcAssembly1.dll\");\n\n            CreateController(moduleBuilder, \"NS1a.NS1b.C1Controller\");\n            CreateController(moduleBuilder, \"NS2a.NS2b.C2Controller\");\n\n            assemblyBuilder.Save(\"MvcAssembly1.dll\");\n        }\n\n        private static void CreateMvcTestAssembly2()\n        {\n            AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(\n                new AssemblyName(\"MvcAssembly2\"),\n                AssemblyBuilderAccess.Save);\n            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(\n                \"MvcAssembly2\", \"MvcAssembly2.dll\");\n\n            CreateController(moduleBuilder, \"NS3a.NS3b.C3Controller\");\n            CreateController(moduleBuilder, \"NS4a.NS4b.C4Controller\");\n\n            assemblyBuilder.Save(\"MvcAssembly2.dll\");\n        }\n\n        private static void CreateMvcTestAssembly3()\n        {\n            AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(\n                new AssemblyName(\"MvcAssembly3\"),\n                AssemblyBuilderAccess.Save);\n            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(\n                \"MvcAssembly3\", \"MvcAssembly3.dll\");\n\n            // Type names (but not namespaces) are the same as those in TestAssembly1\n            CreateController(moduleBuilder, \"NS3a.NS3b.C1Controller\");\n            CreateController(moduleBuilder, \"NS4a.NS4b.C2Controller\");\n\n            assemblyBuilder.Save(\"MvcAssembly3.dll\");\n        }\n\n        private static void CreateMvcTestAssembly4()\n        {\n            AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(\n                new AssemblyName(\"MvcAssembly4\"),\n                AssemblyBuilderAccess.Save);\n            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(\n                \"MvcAssembly4\", \"MvcAssembly4.dll\");\n\n            // Namespaces and type names are the same as those in TestAssembly1\n            CreateController(moduleBuilder, \"NS1a.NS1b.C1Controller\");\n            CreateController(moduleBuilder, \"NS2a.NS2b.C2Controller\");\n\n            assemblyBuilder.Save(\"MvcAssembly4.dll\");\n        }\n\n        private static void CreateController(ModuleBuilder moduleBuilder, string typeName)\n        {\n            //namespace {namespace} {\n            //    public class {typename} : ControllerBase {\n            //        protected virtual void ExecuteCore() {\n            //            return;\n            //        }\n            //    }\n            //}\n\n            TypeBuilder controllerTypeBuilder = moduleBuilder.DefineType(typeName, TypeAttributes.Class | TypeAttributes.Public, typeof(ControllerBase));\n            MethodBuilder executeMethodBuilder = controllerTypeBuilder.DefineMethod(\"ExecuteCore\", MethodAttributes.Family | MethodAttributes.Virtual, typeof(void), Type.EmptyTypes);\n            executeMethodBuilder.GetILGenerator().Emit(OpCodes.Ret);\n            controllerTypeBuilder.DefineMethodOverride(executeMethodBuilder, typeof(ControllerBase).GetMethod(\"ExecuteCore\", BindingFlags.Instance | BindingFlags.NonPublic));\n            controllerTypeBuilder.CreateType();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/MvcWebRazorHostFactoryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc.Razor;\nusing System.Web.WebPages.Razor;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class MvcWebRazorHostFactoryTest\n    {\n        [Fact]\n        public void Constructor()\n        {\n            new MvcWebRazorHostFactory();\n\n            // All is cool\n        }\n\n        [Fact]\n        public void CreateHost_ReplacesRegularHostWithMvcSpecificOne()\n        {\n            // Arrange\n            MvcWebRazorHostFactory factory = new MvcWebRazorHostFactory();\n\n            // Act\n            WebPageRazorHost result = factory.CreateHost(\"foo.cshtml\", null);\n\n            // Assert\n            Assert.IsType<MvcWebPageRazorHost>(result);\n        }\n\n        [Fact]\n        public void CreateHost_DoesNotChangeAppStartFileHost()\n        {\n            // Arrange\n            MvcWebRazorHostFactory factory = new MvcWebRazorHostFactory();\n\n            // Act\n            WebPageRazorHost result = factory.CreateHost(\"_appstart.cshtml\", null);\n\n            // Assert\n            Assert.IsNotType<MvcWebPageRazorHost>(result);\n        }\n\n        [Fact]\n        public void CreateHost_DoesNotChangePageStartFileHost()\n        {\n            // Arrange\n            MvcWebRazorHostFactory factory = new MvcWebRazorHostFactory();\n\n            // Act\n            WebPageRazorHost result = factory.CreateHost(\"_pagestart.cshtml\", null);\n\n            // Assert\n            Assert.IsNotType<MvcWebPageRazorHost>(result);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/NameValueCollectionExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class NameValueCollectionExtensionsTest\n    {\n        [Fact]\n        public void CopyTo()\n        {\n            // Arrange\n            NameValueCollection collection = GetCollection();\n            IDictionary<string, object> dictionary = GetDictionary();\n\n            // Act\n            collection.CopyTo(dictionary);\n\n            // Assert\n            Assert.Equal(3, dictionary.Count);\n            Assert.Equal(\"FooDictionary\", dictionary[\"foo\"]);\n            Assert.Equal(\"BarDictionary\", dictionary[\"bar\"]);\n            Assert.Equal(\"BazCollection\", dictionary[\"baz\"]);\n        }\n\n        [Fact]\n        public void CopyToReplaceExisting()\n        {\n            // Arrange\n            NameValueCollection collection = GetCollection();\n            IDictionary<string, object> dictionary = GetDictionary();\n\n            // Act\n            collection.CopyTo(dictionary, true /* replaceExisting */);\n\n            // Assert\n            Assert.Equal(3, dictionary.Count);\n            Assert.Equal(\"FooCollection\", dictionary[\"foo\"]);\n            Assert.Equal(\"BarDictionary\", dictionary[\"bar\"]);\n            Assert.Equal(\"BazCollection\", dictionary[\"baz\"]);\n        }\n\n        [Fact]\n        public void CopyToWithNullCollectionThrows()\n        {\n            Assert.ThrowsArgumentNull(\n                delegate { NameValueCollectionExtensions.CopyTo(null /* collection */, null /* destination */); }, \"collection\");\n        }\n\n        [Fact]\n        public void CopyToWithNullDestinationThrows()\n        {\n            // Arrange\n            NameValueCollection collection = GetCollection();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { collection.CopyTo(null /* destination */); }, \"destination\");\n        }\n\n        private static NameValueCollection GetCollection()\n        {\n            return new NameValueCollection\n            {\n                { \"Foo\", \"FooCollection\" },\n                { \"Baz\", \"BazCollection\" }\n            };\n        }\n\n        private static IDictionary<string, object> GetDictionary()\n        {\n            return new RouteValueDictionary(new { Foo = \"FooDictionary\", Bar = \"BarDictionary\" });\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/NameValueCollectionValueProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing System.Globalization;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class NameValueCollectionValueProviderTest\n    {\n        private static readonly NameValueCollection _backingStore = new NameValueCollection()\n        {\n            { \"foo\", \"fooValue1\" },\n            { \"foo\", \"fooValue2\" },\n            { \"bar.baz\", \"someOtherValue\" }\n        };\n\n        [Fact]\n        public void Constructor_ThrowsIfCollectionIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new NameValueCollectionValueProvider(null, CultureInfo.InvariantCulture); }, \"collection\");\n        }\n\n        [Fact]\n        public void ContainsPrefix()\n        {\n            // Arrange\n            NameValueCollectionValueProvider valueProvider = new NameValueCollectionValueProvider(_backingStore, null);\n\n            // Act\n            bool result = valueProvider.ContainsPrefix(\"bar\");\n\n            // Assert\n            Assert.True(result);\n        }\n\n        [Fact]\n        public void ContainsPrefix_DoesNotContainEmptyPrefixIfBackingStoreIsEmpty()\n        {\n            // Arrange\n            NameValueCollectionValueProvider valueProvider = new NameValueCollectionValueProvider(new NameValueCollection(), null);\n\n            // Act\n            bool result = valueProvider.ContainsPrefix(\"\");\n\n            // Assert\n            Assert.False(result);\n        }\n\n        [Fact]\n        public void ContainsPrefix_ThrowsIfPrefixIsNull()\n        {\n            // Arrange\n            NameValueCollectionValueProvider valueProvider = new NameValueCollectionValueProvider(_backingStore, null);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { valueProvider.ContainsPrefix(null); }, \"prefix\");\n        }\n\n        [Fact]\n        public void GetValue()\n        {\n            // Arrange\n            CultureInfo culture = CultureInfo.GetCultureInfo(\"fr-FR\");\n            NameValueCollectionValueProvider valueProvider = new NameValueCollectionValueProvider(_backingStore, culture);\n\n            // Act\n            ValueProviderResult vpResult = valueProvider.GetValue(\"foo\");\n\n            // Assert\n            Assert.NotNull(vpResult);\n            Assert.Equal(_backingStore.GetValues(\"foo\"), (string[])vpResult.RawValue);\n            Assert.Equal(\"fooValue1,fooValue2\", vpResult.AttemptedValue);\n            Assert.Equal(culture, vpResult.Culture);\n        }\n\n        [Fact]\n        public void GetValue_NonValidating()\n        {\n            // Arrange\n            NameValueCollection unvalidatedCollection = new NameValueCollection()\n            {\n                { \"foo\", \"fooValue3\" },\n                { \"foo\", \"fooValue4\" }\n            };\n\n            CultureInfo culture = CultureInfo.GetCultureInfo(\"fr-FR\");\n            NameValueCollectionValueProvider valueProvider = new NameValueCollectionValueProvider(_backingStore, unvalidatedCollection, culture);\n\n            // Act\n            ValueProviderResult vpResult = valueProvider.GetValue(\"foo\", skipValidation: true);\n\n            // Assert\n            Assert.NotNull(vpResult);\n            Assert.Equal(new[] { \"fooValue3\", \"fooValue4\" }, (string[])vpResult.RawValue);\n            Assert.Equal(\"fooValue3,fooValue4\", vpResult.AttemptedValue);\n            Assert.Equal(culture, vpResult.Culture);\n        }\n\n        [Fact]\n        public void GetValue_NonValidating_NoUnvalidatedCollectionSpecified_UsesDefaultCollectionValue()\n        {\n            // Arrange\n            CultureInfo culture = CultureInfo.GetCultureInfo(\"fr-FR\");\n            NameValueCollectionValueProvider valueProvider = new NameValueCollectionValueProvider(_backingStore, null, culture);\n\n            // Act\n            ValueProviderResult vpResult = valueProvider.GetValue(\"foo\", skipValidation: true);\n\n            // Assert\n            Assert.NotNull(vpResult);\n            Assert.Equal(_backingStore.GetValues(\"foo\"), (string[])vpResult.RawValue);\n            Assert.Equal(\"fooValue1,fooValue2\", vpResult.AttemptedValue);\n            Assert.Equal(culture, vpResult.Culture);\n        }\n\n        [Theory]\n        [InlineData(\"foo\", \"fooValue\", \"foo\", \"fooValue\")]\n        [InlineData(\"fooArray[0][bar1][bar3]\", \"barValue1\", \"fooArray[0].bar1.bar3\", \"barValue1\")]\n        [InlineData(\"fooArray[0][bar2]\", \"barValue2\", \"fooArray[0].bar2\", \"barValue2\")]\n        [InlineData(\n            \"fooArray[1][bar1][0][nested]\", \"nestedArrayValue\", \"fooArray[1].bar1[0].nested\", \"nestedArrayValue\")]\n        [InlineData(\"fooArray[2].bar1\", \"noSquareBracesValue\", \"fooArray[2].bar1\", \"noSquareBracesValue\")]\n        [InlineData(\"foo.bar\", \"fooBarValue\", \"foo.bar\", \"fooBarValue\")]\n        public void GetValue_NonValidating_WithArraysInCollection(\n                            string name, string value, string index, string expectedAttemptedValue)\n        {\n            // Arrange\n            string[] expectedRawValue = new[] { expectedAttemptedValue };\n            NameValueCollection unvalidatedCollection = new NameValueCollection();\n            unvalidatedCollection.Add(name, value);\n\n            CultureInfo culture = CultureInfo.GetCultureInfo(\"fr-FR\");\n            NameValueCollectionValueProvider valueProvider = \n                    new NameValueCollectionValueProvider(_backingStore, unvalidatedCollection, culture, true);\n\n            // Act\n            ValueProviderResult vpResult = valueProvider.GetValue(index, skipValidation: true);\n            \n            // Asserts\n            Assert.NotNull(vpResult);\n            Assert.Equal(culture, vpResult.Culture);\n            Assert.Equal(expectedRawValue, (string[])vpResult.RawValue);\n            Assert.Equal(expectedAttemptedValue, vpResult.AttemptedValue);\n        }\n\n        [Fact]\n        public void GetValue_NonValidating_WithArraysInCollection_Error()\n        {\n            // Arrange\n            NameValueCollection unvalidatedCollection = new NameValueCollection()\n            {\n                { \"foo\", \"fooValue3\" },\n                { \"fooArray[0][bar1\", \"barValue1\" }\n            };\n\n            NameValueCollectionValueProvider valueProvider =\n                new NameValueCollectionValueProvider(\n                                    _backingStore,\n                                    unvalidatedCollection,\n                                    culture: null,\n                                    jQueryToMvcRequestNormalizationRequired: true);\n\n            // Act & Assert\n            Assert.ThrowsArgument(\n                () => valueProvider.GetValue(\"foo\", skipValidation: true),\n                \"key\",\n                \"The key is invalid JQuery syntax because it is missing a closing bracket.\");\n        }\n\n        [Fact]\n        public void GetValue_ReturnsNullIfKeyNotFound()\n        {\n            // Arrange\n            NameValueCollectionValueProvider valueProvider = new NameValueCollectionValueProvider(_backingStore, null);\n\n            // Act\n            ValueProviderResult vpResult = valueProvider.GetValue(\"bar\");\n\n            // Assert\n            Assert.Null(vpResult);\n        }\n\n        [Fact]\n        public void GetValue_ThrowsIfKeyIsNull()\n        {\n            // Arrange\n            NameValueCollectionValueProvider valueProvider = new NameValueCollectionValueProvider(_backingStore, null);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { valueProvider.GetValue(null); }, \"key\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/NoAsyncTimeoutAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class NoAsyncTimeoutAttributeTest\n    {\n        [Fact]\n        public void DurationPropertyIsZero()\n        {\n            // Act\n            AsyncTimeoutAttribute attr = new NoAsyncTimeoutAttribute();\n\n            // Assert\n            Assert.Equal(Timeout.Infinite, attr.Duration);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/NonActionAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class NonActionAttributeTest\n    {\n        [Fact]\n        public void InValidActionForRequestReturnsFalse()\n        {\n            // Arrange\n            NonActionAttribute attr = new NonActionAttribute();\n\n            // Act & Assert\n            Assert.False(attr.IsValidForRequest(null, null));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/OutputCacheAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Web.TestUtil;\nusing System.Web.UI;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class OutputCacheAttributeTest\n    {\n        [Fact]\n        public void CacheProfileProperty()\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute();\n\n            // Act & assert\n            MemberHelper.TestStringProperty(attr, \"CacheProfile\", String.Empty);\n        }\n\n        [Fact]\n        public void CacheSettingsProperty()\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute()\n            {\n                CacheProfile = \"SomeProfile\",\n                Duration = 50,\n                Location = OutputCacheLocation.Downstream,\n                NoStore = true,\n                SqlDependency = \"SomeSqlDependency\",\n                VaryByContentEncoding = \"SomeContentEncoding\",\n                VaryByCustom = \"SomeCustom\",\n                VaryByHeader = \"SomeHeader\",\n                VaryByParam = \"SomeParam\",\n            };\n\n            // Act\n            OutputCacheParameters cacheSettings = attr.CacheSettings;\n\n            // Assert\n            Assert.Equal(\"SomeProfile\", cacheSettings.CacheProfile);\n            Assert.Equal(50, cacheSettings.Duration);\n            Assert.Equal(OutputCacheLocation.Downstream, cacheSettings.Location);\n            Assert.True(cacheSettings.NoStore);\n            Assert.Equal(\"SomeSqlDependency\", cacheSettings.SqlDependency);\n            Assert.Equal(\"SomeContentEncoding\", cacheSettings.VaryByContentEncoding);\n            Assert.Equal(\"SomeCustom\", cacheSettings.VaryByCustom);\n            Assert.Equal(\"SomeHeader\", cacheSettings.VaryByHeader);\n            Assert.Equal(\"SomeParam\", cacheSettings.VaryByParam);\n        }\n\n        [Fact]\n        public void DurationProperty()\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute();\n\n            // Act & assert\n            MemberHelper.TestInt32Property(attr, \"Duration\", 10, 20);\n        }\n\n        [Fact]\n        public void LocationProperty()\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute();\n\n            // Act & assert\n            MemberHelper.TestPropertyValue(attr, \"Location\", OutputCacheLocation.ServerAndClient);\n        }\n\n        [Fact]\n        public void NoStoreProperty()\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute();\n\n            // Act & assert\n            MemberHelper.TestBooleanProperty(attr, \"NoStore\", false /* initialValue */, false /* testDefaultValue */);\n        }\n\n        [Fact]\n        public void OnResultExecutingThrowsIfFilterContextIsNull()\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { attr.OnResultExecuting(null); }, \"filterContext\");\n        }\n\n        [Theory]\n        [InlineData(0)]\n        [InlineData(-1)]\n        public void OnActionExecuting_Throws_IfDurationIsNotPositive(int duration)\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute();\n            attr.Duration = duration;\n            Mock<ActionExecutingContext> context = new Mock<ActionExecutingContext>();\n            context.Setup(c => c.IsChildAction).Returns(true);\n\n            // Act & assert\n            Assert.Throws<InvalidOperationException>(\n                () => attr.OnActionExecuting(context.Object),\n                \"Duration must be a positive number.\");\n        }\n\n        [Theory]\n        [InlineData(null)]\n        [InlineData(\"\")]\n        public void OnActionExecuting_Throws_IfVaryByParamIsNullOrEmptyAndDurationIsPositive(string varyByParam)\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute();\n            attr.Duration = 1;\n            attr.VaryByParam = varyByParam;\n            Mock<ActionExecutingContext> context = new Mock<ActionExecutingContext>();\n            context.Setup(c => c.IsChildAction).Returns(true);\n\n            // Act & assert\n            Assert.Throws<InvalidOperationException>(\n                () => attr.OnActionExecuting(context.Object),\n                \"VaryByParam must be '*', 'none', or a semicolon-delimited list of keys.\");\n        }\n\n        [Fact]\n        public void OnActionExecuting_Throws_IfCacheProfileSet()\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute();\n            attr.CacheProfile = \"something\";\n            Mock<ActionExecutingContext> context = new Mock<ActionExecutingContext>();\n            context.Setup(c => c.IsChildAction).Returns(true);\n\n            // Act & assert\n            Assert.Throws<InvalidOperationException>(\n                () => attr.OnActionExecuting(context.Object),\n                \"OutputCacheAttribute for child actions only supports Duration, VaryByCustom, and VaryByParam values. Please do not set CacheProfile, Location, NoStore, SqlDependency, VaryByContentEncoding, or VaryByHeader values for child actions.\");\n        }\n\n        [Fact]\n        public void SqlDependencyProperty()\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute();\n\n            // Act & assert\n            MemberHelper.TestStringProperty(attr, \"SqlDependency\", String.Empty);\n        }\n\n        [Fact]\n        public void VaryByContentEncodingProperty()\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute();\n\n            // Act & assert\n            MemberHelper.TestStringProperty(attr, \"VaryByContentEncoding\", String.Empty);\n        }\n\n        [Fact]\n        public void VaryByCustomProperty()\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute();\n\n            // Act & assert\n            MemberHelper.TestStringProperty(attr, \"VaryByCustom\", String.Empty);\n        }\n\n        [Fact]\n        public void VaryByHeaderProperty()\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute();\n\n            // Act & assert\n            MemberHelper.TestStringProperty(attr, \"VaryByHeader\", String.Empty);\n        }\n\n        [Fact]\n        public void VaryByParamProperty()\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute();\n\n            // Act & assert\n            MemberHelper.TestStringProperty(attr, \"VaryByParam\", \"*\");\n        }\n\n        [Fact]\n        public void OutputCacheDoesNotExecuteIfInChildAction()\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute();\n            Mock<ResultExecutingContext> context = new Mock<ResultExecutingContext>();\n            context.Setup(c => c.IsChildAction).Returns(true);\n\n            // Act\n            attr.OnResultExecuting(context.Object);\n\n            // Assert\n            context.Verify();\n            context.Verify(c => c.Result, Times.Never());\n        }\n\n        [Fact]\n        public void OutputCacheDurationDoesNotSetIfInChildAction()\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute();\n            Mock<ActionExecutingContext> context = new Mock<ActionExecutingContext>();\n            context.Setup(c => c.IsChildAction).Returns(true);\n\n            // Act & assert\n            Assert.Throws<InvalidOperationException>(delegate { attr.OnActionExecuting(context.Object); });\n        }\n\n        [Fact]\n        public void OutputCacheLocationSetNoneIfInChildAction()\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute()\n            {\n                Location = OutputCacheLocation.None\n            };\n            Mock<ActionExecutingContext> context = new Mock<ActionExecutingContext>();\n            context.Setup(c => c.IsChildAction).Returns(true);\n\n            // Act & assert\n            Assert.DoesNotThrow(delegate { attr.OnActionExecuting(context.Object); });\n        }\n\n        // GetChildActionUniqueId\n\n        [Fact]\n        public void GetChildActionUniqueId_ReturnsRepeatableValueForIdenticalContext()\n        {\n            // Arrange\n            var attr = new OutputCacheAttribute();\n            var context = new MockActionExecutingContext();\n\n            // Act\n            string result1 = attr.GetChildActionUniqueId(context.Object);\n            string result2 = attr.GetChildActionUniqueId(context.Object);\n\n            // Assert\n            Assert.Equal(result1, result2);\n        }\n\n        [Fact]\n        public void GetChildActionUniqueId_VariesByActionDescriptorsUniqueId()\n        {\n            // Arrange\n            var attr = new OutputCacheAttribute();\n            var context1 = new MockActionExecutingContext();\n            context1.Setup(c => c.ActionDescriptor.UniqueId).Returns(\"1\");\n            var context2 = new MockActionExecutingContext();\n            context2.Setup(c => c.ActionDescriptor.UniqueId).Returns(\"2\");\n\n            // Act\n            string result1 = attr.GetChildActionUniqueId(context1.Object);\n            string result2 = attr.GetChildActionUniqueId(context2.Object);\n\n            // Assert\n            Assert.NotEqual(result1, result2);\n        }\n\n        [Fact]\n        public void GetChildActionUniqueId_VariesByCustom()\n        {\n            // Arrange\n            var attr = new OutputCacheAttribute { VaryByCustom = \"foo\" };\n            var application1 = new Mock<HttpApplication>();\n            application1.Setup(a => a.GetVaryByCustomString(It.IsAny<HttpContext>(), \"foo\")).Returns(\"1\");\n            var context1 = new MockActionExecutingContext();\n            context1.SetupGet(c => c.HttpContext.ApplicationInstance).Returns(application1.Object);\n\n            var application2 = new Mock<HttpApplication>();\n            application2.Setup(a => a.GetVaryByCustomString(It.IsAny<HttpContext>(), \"foo\")).Returns(\"2\");\n            var context2 = new MockActionExecutingContext();\n            context2.SetupGet(c => c.HttpContext.ApplicationInstance).Returns(application2.Object);\n\n            // Act\n            string result1 = attr.GetChildActionUniqueId(context1.Object);\n            string result2 = attr.GetChildActionUniqueId(context2.Object);\n\n            // Assert\n            Assert.Equal(@\"VjXrM/nTu6zOLCi+teZcx7qDQRk/Q+G5ZirKHhH7MOA=\", result1);\n            Assert.Equal(@\"Wi7TLgf052Ao0ZJX890MgynId6jByOf+xZ1G+5RHJUU=\", result2);\n        }\n\n        [Fact]\n        public void GetChildActionUniqueId_VariesByActionParameters_AllParametersByDefault()\n        {\n            // Arrange\n            var attr = new OutputCacheAttribute();\n            var context1 = new MockActionExecutingContext();\n            context1.ActionParameters[\"foo\"] = \"1\";\n            var context2 = new MockActionExecutingContext();\n            context2.ActionParameters[\"foo\"] = \"2\";\n\n            // Act\n            string result1 = attr.GetChildActionUniqueId(context1.Object);\n            string result2 = attr.GetChildActionUniqueId(context2.Object);\n\n            // Assert\n            Assert.Equal(\"tXBiB5qdEzfISoXUUqXAzPcd7y/9Ik6eFqy8w9i3aDw=\", result1);\n            Assert.Equal(\"Bb+E/t8aWfczVF2UFVr+FUpuGYjR/SPhzt71q+oAlHk=\", result2);\n        }\n\n        [Fact]\n        public void GetChildActionUniqueId_DoesNotVaryByActionParametersWhenVaryByParamIsNone()\n        {\n            // Arrange\n            var attr = new OutputCacheAttribute { VaryByParam = \"none\" };\n            var context1 = new MockActionExecutingContext();\n            context1.ActionParameters[\"foo\"] = \"1\";\n            var context2 = new MockActionExecutingContext();\n            context2.ActionParameters[\"foo\"] = \"2\";\n\n            // Act\n            string result1 = attr.GetChildActionUniqueId(context1.Object);\n            string result2 = attr.GetChildActionUniqueId(context2.Object);\n\n            // Assert\n            Assert.Equal(result1, result2);\n            Assert.Equal(\"IA6+zemlkqp8Ye59mwMEMYGo69mUVkAcFLa5z0keL50=\", result1);\n        }\n\n        [Fact]\n        public void GetChildActionUniqueId_VariesByActionParameters_OnlyVariesByTheGivenParameters()\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute { VaryByParam = \"bar\" };\n            MockActionExecutingContext context1 = new MockActionExecutingContext();\n            context1.ActionParameters[\"foo\"] = \"1\";\n            MockActionExecutingContext context2 = new MockActionExecutingContext();\n            context2.ActionParameters[\"foo\"] = \"2\";\n\n            // Act\n            string result1 = attr.GetChildActionUniqueId(context1.Object);\n            string result2 = attr.GetChildActionUniqueId(context2.Object);\n\n            // Assert\n            Assert.Equal(result1, result2);\n            Assert.Equal(\"sx9+LHPOjtSGct8z6Cn4ml+2yKODPojZtrLhrhJofKM=\", result1);\n        }\n\n        [Fact]\n        public void GetChildActionUniqueId_VariesByActionParameters_OnlyVariesByTheGivenParameters_SingleSpecified_Different()\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute { VaryByParam = \"foo\" };\n            MockActionExecutingContext context1 = new MockActionExecutingContext();\n            context1.ActionParameters[\"foo\"] = \"1\";\n            MockActionExecutingContext context2 = new MockActionExecutingContext();\n            context2.ActionParameters[\"foo\"] = \"2\";\n\n            // Act\n            string result1 = attr.GetChildActionUniqueId(context1.Object);\n            string result2 = attr.GetChildActionUniqueId(context2.Object);\n\n            // Assert\n            Assert.Equal(\"tXBiB5qdEzfISoXUUqXAzPcd7y/9Ik6eFqy8w9i3aDw=\", result1);\n            Assert.Equal(\"Bb+E/t8aWfczVF2UFVr+FUpuGYjR/SPhzt71q+oAlHk=\", result2);\n        }\n\n        [Fact]\n        public void GetChildActionUniqueId_VariesByActionParameters_OnlyVariesByTheGivenParameters_SingleSpecified_Same()\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute { VaryByParam = \"foo\" };\n            MockActionExecutingContext context1 = new MockActionExecutingContext();\n            context1.ActionParameters[\"foo\"] = \"1\";\n            MockActionExecutingContext context2 = new MockActionExecutingContext();\n            context2.ActionParameters[\"foo\"] = \"1\";\n\n            // Act\n            string result1 = attr.GetChildActionUniqueId(context1.Object);\n            string result2 = attr.GetChildActionUniqueId(context2.Object);\n\n            // Assert\n            Assert.Equal(\"tXBiB5qdEzfISoXUUqXAzPcd7y/9Ik6eFqy8w9i3aDw=\", result1);\n            Assert.Equal(\"tXBiB5qdEzfISoXUUqXAzPcd7y/9Ik6eFqy8w9i3aDw=\", result2);\n        }\n\n        [Fact]\n        public void GetChildActionUniqueId_VariesByActionParameters_OnlyVariesByTheGivenParameters_MultipleSpecified_Different()\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute { VaryByParam = \"foo;bar;blap\" };\n            MockActionExecutingContext context1 = new MockActionExecutingContext();\n            context1.ActionParameters[\"foo\"] = \"1\";\n            context1.ActionParameters[\"bar\"] = \"2\";\n            MockActionExecutingContext context2 = new MockActionExecutingContext();\n            context2.ActionParameters[\"foo\"] = \"1\";\n            context2.ActionParameters[\"bar\"] = \"3\";\n\n            // Act\n            string result1 = attr.GetChildActionUniqueId(context1.Object);\n            string result2 = attr.GetChildActionUniqueId(context2.Object);\n\n            // Assert\n            Assert.NotEqual(result1, result2);\n        }\n\n        public static TheoryDataSet<ActionExecutingContext, string, string>\n            GetUniqueIdFromActionParameters_ReturnsValuesThatExistInFilterContextData\n        {\n            get\n            {\n                TheoryDataSet<ActionExecutingContext, string, string> theoryData =\n                    new TheoryDataSet<ActionExecutingContext, string, string>();\n\n                MockActionExecutingContext context1 = new MockActionExecutingContext();\n                context1.ActionParameters[\"foo\"] = \"foo-value\";\n                context1.ActionParameters[\"bar\"] = \"bar-value\";\n                context1.ActionParameters[\"blap\"] = \"blap-value\";\n\n                string expected1 = \"[3]FOO[9]foo-value[3]BAR[9]bar-value[4]BLAP[10]blap-value\";\n\n                theoryData.Add(context1.Object, \"foo;bar;blap\", expected1);\n                theoryData.Add(context1.Object, \"foo; bar;  blap;\", expected1);\n                theoryData.Add(context1.Object, \";foo;   bar; blap  \", expected1);\n                theoryData.Add(context1.Object, \"foo; BAR;Blap\", expected1);\n\n                MockActionExecutingContext context2 = new MockActionExecutingContext();\n                context2.ActionParameters[\"test\"] = \"test-value\";\n                context2.ActionParameters[\"shouldnot-exist\"] = \"shouldnot-exist\";\n                context2.ActionParameters[\"test2\"] = \"test2-value\";\n\n                theoryData.Add(context2.Object, \"test;test2\", \"[4]TEST[10]test-value[5]TEST2[11]test2-value\");\n                theoryData.Add(context2.Object, \"test;test3\", \"[4]TEST[10]test-value[5]TEST3[-1]\");\n\n                MockActionExecutingContext context3 = new MockActionExecutingContext();\n                theoryData.Add(context3.Object, \"test1;test2\", \"[5]TEST1[-1][5]TEST2[-1]\");\n\n                return theoryData;\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"GetUniqueIdFromActionParameters_ReturnsValuesThatExistInFilterContextData\")]\n        public static void BuildUniqueIdFromActionParameters_UsesValuesForActionParametersThatExistInVaryByParams(\n            ActionExecutingContext context, string varyByParam, string expected)\n        {\n            // Arrange\n            StringBuilder builder = new StringBuilder();\n            OutputCacheAttribute attribute = new OutputCacheAttribute { VaryByParam = varyByParam };\n\n            // Act\n            attribute.BuildUniqueIdFromActionParameters(builder, context);\n\n            // Assert\n            Assert.Equal(expected, builder.ToString());\n        }\n\n        [Theory]\n        [InlineData(\"Foo;bar\")]\n        [InlineData(\"FOO;bAr\")]\n        [InlineData(\"foo;bar\")]\n        public static void BuildUniqueIdFromActionParameters_LooksUpActionParametersInCaseInsensitiveManner(\n            string varyByParam)\n        {\n            // Arrange\n            MockActionExecutingContext context = new MockActionExecutingContext();\n            Dictionary<string, object> dictionary = new Dictionary<string, object>(StringComparer.Ordinal)\n            {\n                { \"foo\",  \"foo-value\" },\n                { \"Bar\", \"bar-value\" }\n            };\n            context.ActionParameters = dictionary;\n            string expected = \"[3]FOO[9]foo-value[3]BAR[9]bar-value\";\n\n            StringBuilder builder = new StringBuilder();\n            OutputCacheAttribute attribute = new OutputCacheAttribute { VaryByParam = varyByParam };\n\n            // Act\n            attribute.BuildUniqueIdFromActionParameters(builder, context.Object);\n\n            // Assert\n            Assert.Equal(expected, builder.ToString());\n        }\n\n        [Theory]\n        [InlineData(\"none\")]\n        [InlineData(\"NONE\")]\n        [InlineData(\"None\")]\n        public static void BuildUniqueIdFromActionParameters_NoOpsIfVaryByParamIsNone(string varyByParam)\n        {\n            // Arrange\n            StringBuilder builder = new StringBuilder();\n            ActionExecutingContext context = new MockActionExecutingContext().Object;\n            OutputCacheAttribute attribute = new OutputCacheAttribute { VaryByParam = varyByParam };\n\n            // Act\n            attribute.BuildUniqueIdFromActionParameters(builder, context);\n\n            // Assert\n            Assert.Empty(builder.ToString());\n        }\n\n        [Fact]\n        public static void BuildUniqueIdFromActionParameters_UsesAllActionParametersIfStar()\n        {\n            // Arrange\n            OutputCacheAttribute attribute = new OutputCacheAttribute { VaryByParam = \"*\" };\n            StringBuilder builder1 = new StringBuilder();\n            MockActionExecutingContext context1 = new MockActionExecutingContext();\n            context1.ActionParameters[\"test1\"] = \"test1-value\";\n            context1.ActionParameters[\"test2\"] = 3;\n            context1.ActionParameters[\"test3\"] = null;\n            string expected = \"[5]TEST1[11]test1-value[5]TEST2[1]3[5]TEST3[-1]\";\n\n            // Act - 1\n            attribute.BuildUniqueIdFromActionParameters(builder1, context1.Object);\n\n            // Assert - 1\n            Assert.Equal(expected, builder1.ToString());\n\n            // Arrange - 2\n            // Verify that the keys are stable sorted when \"*\" is used.\n            StringBuilder builder2 = new StringBuilder();\n            MockActionExecutingContext context2 = new MockActionExecutingContext();\n            context2.ActionParameters[\"test3\"] = null;\n            context2.ActionParameters[\"test2\"] = 3;\n            context2.ActionParameters[\"test1\"] = \"test1-value\";\n\n            // Act - 2\n            attribute.BuildUniqueIdFromActionParameters(builder2, context2.Object);\n\n            // Assert - 2\n            Assert.Equal(expected, builder2.ToString());\n        }\n\n        [Fact]\n        public static void BuildUniqueIdFromActionParameters_DoesNotCacheTokenizedStringsWhenStar()\n        {\n            // Arrange\n            OutputCacheAttribute attribute = new OutputCacheAttribute { VaryByParam = \"*\" };\n            StringBuilder builder1 = new StringBuilder();\n            MockActionExecutingContext context1 = new MockActionExecutingContext();\n            context1.ActionParameters[\"test1\"] = \"test1-value\";\n            context1.ActionParameters[\"test2\"] = \"Test2-Value\";\n            context1.ActionParameters[\"test3\"] = null;\n            string expected1 = \"[5]TEST1[11]test1-value[5]TEST2[11]Test2-Value[5]TEST3[-1]\";\n\n            // Act - 1\n            attribute.BuildUniqueIdFromActionParameters(builder1, context1.Object);\n\n            // Assert - 1\n            Assert.Equal(expected1, builder1.ToString());\n\n            // Arrange - 2\n            // Verify that the keys are stable sorted when \"*\" is used.\n            StringBuilder builder2 = new StringBuilder();\n            MockActionExecutingContext context2 = new MockActionExecutingContext();\n            context2.ActionParameters[\"Foo\"] = null;\n            context2.ActionParameters[\"bar\"] = \"bar-value\";\n            string expected2 = \"[3]BAR[9]bar-value[3]FOO[-1]\";\n\n            // Act - 2\n            attribute.BuildUniqueIdFromActionParameters(builder2, context2.Object);\n\n            // Assert - 2\n            Assert.Equal(expected2, builder2.ToString());\n        }\n\n        public static IEnumerable<string> VaryByParamWithWhitespaceData = new[]\n        {\n            \"foo;bar;blap\",\n            \"foo; bar; blap\",\n            \";foo; bar; blap\",\n            \"  foo;   bar;  blap\",\n            \"  foo;bar;  blap; \",\n            \"  ;foo;   bar  ;  blap; \",\n        };\n\n        public static IEnumerable<object[]> GetChildActionUniqueId_VariesByActionParametersData\n        {\n            get\n            {\n                return VaryByParamWithWhitespaceData.Select(v => new[] { v });\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"GetChildActionUniqueId_VariesByActionParametersData\")]\n        public void GetChildActionUniqueId_VariesByActionParameters_OnlyVariesByGivenParameters(string varbyParam)\n        {\n            // Arrange\n            string expected = \"z2Fr6HAipKCkLdVkHMdHgeDBJyYutdqqTW07BMO31fQ=\";\n            OutputCacheAttribute attr = new OutputCacheAttribute { VaryByParam = varbyParam };\n            MockActionExecutingContext context1 = new MockActionExecutingContext();\n            context1.ActionParameters[\"foo\"] = \"1\";\n            context1.ActionParameters[\"bar\"] = \"2\";\n            context1.ActionParameters[\"blap\"] = \"3\";\n            context1.ActionParameters[\"xyz\"] = Guid.NewGuid().ToString();\n            context1.ActionParameters[\"some-key\"] = Guid.NewGuid().ToString();\n            MockActionExecutingContext context2 = new MockActionExecutingContext();\n            context2.ActionParameters[\"foo\"] = \"1\";\n            context2.ActionParameters[\"bar\"] = \"2\";\n            context2.ActionParameters[\"blap\"] = \"3\";\n            context2.ActionParameters[\"xyz\"] = Guid.NewGuid().ToString();\n            context2.ActionParameters[\"different-key\"] = Guid.NewGuid().ToString();\n\n            // Act\n            string result1 = attr.GetChildActionUniqueId(context1.Object);\n            string result2 = attr.GetChildActionUniqueId(context2.Object);\n\n            // Assert\n            Assert.Equal(expected, result1);\n            Assert.Equal(expected, result2);\n        }\n\n        public static IEnumerable<object[]> GetChildActionUniqueId_VariesByActionParameters_WithDifferentValuesData\n        {\n            get\n            {\n                return VaryByParamWithWhitespaceData.Select(v => new[] { v, \"20\", \"34\" });\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"GetChildActionUniqueId_VariesByActionParameters_WithDifferentValuesData\")]\n        public void GetChildActionUniqueId_VariesByActionParameters_OnlyVariesByTheGivenParameters_MultipleSpecified_WithDifferentValues(\n            string varyByParam, string value1, string value2)\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute { VaryByParam = varyByParam };\n            MockActionExecutingContext context1 = new MockActionExecutingContext();\n            context1.ActionParameters[\"foo\"] = value1;\n            context1.ActionParameters[\"bar\"] = \"2\";\n            context1.ActionParameters[\"blap\"] = \"3\";\n            context1.ActionParameters[\"xyz\"] = \"abc\";\n            MockActionExecutingContext context2 = new MockActionExecutingContext();\n            context2.ActionParameters[\"foo\"] = value2;\n            context2.ActionParameters[\"bar\"] = \"2\";\n            context2.ActionParameters[\"blap\"] = \"3\";\n            context2.ActionParameters[\"xyz\"] = \"abc\";\n\n            // Act\n            string result1 = attr.GetChildActionUniqueId(context1.Object);\n            string result2 = attr.GetChildActionUniqueId(context2.Object);\n\n            // Assert\n            Assert.Equal(\"WBXQR5lxerJG33HR3XQ9sJsXuKu6eVPgmMqeWMu8t2s=\", result1);\n            Assert.Equal(\"CLMC7fAU4959ECaI79HRFglt7SnNRANMJeYderjF4m8=\", result2);\n        }\n\n        [Theory]\n        [PropertyData(\"GetChildActionUniqueId_VariesByActionParameters_WithDifferentValuesData\")]\n        public void GetChildActionUniqueId_VariesByActionParameters_OnlyVariesByTheGivenParameters_MultipleSpecified_Whitespace_DifferentSecond(\n            string varyByParam, string value1, string value2)\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute { VaryByParam = varyByParam };\n            MockActionExecutingContext context1 = new MockActionExecutingContext();\n            context1.ActionParameters[\"foo\"] = \"1\";\n            context1.ActionParameters[\"bar\"] = value1;\n            context1.ActionParameters[\"blap\"] = \"3\";\n            context1.ActionParameters[\"xyz\"] = \"abc\";\n            MockActionExecutingContext context2 = new MockActionExecutingContext();\n            context2.ActionParameters[\"foo\"] = \"1\";\n            context2.ActionParameters[\"bar\"] = value2;\n            context2.ActionParameters[\"blap\"] = \"3\";\n            context2.ActionParameters[\"xyz\"] = \"abc\";\n\n            // Act\n            string result1 = attr.GetChildActionUniqueId(context1.Object);\n            string result2 = attr.GetChildActionUniqueId(context2.Object);\n\n            // Assert\n            Assert.NotEqual(result1, result2);\n        }\n\n        [Theory]\n        [PropertyData(\"GetChildActionUniqueId_VariesByActionParameters_WithDifferentValuesData\")]\n        public void GetChildActionUniqueId_VariesByActionParameters_OnlyVariesByTheGivenParameters_MultipleSpecified_Whitespace_DifferentThird(\n            string varyByParam, string value1, string value2)\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute { VaryByParam = varyByParam };\n            MockActionExecutingContext context1 = new MockActionExecutingContext();\n            context1.ActionParameters[\"foo\"] = \"1\";\n            context1.ActionParameters[\"bar\"] = \"2\";\n            context1.ActionParameters[\"blap\"] = value1;\n            context1.ActionParameters[\"xyz\"] = \"abc\";\n            MockActionExecutingContext context2 = new MockActionExecutingContext();\n            context2.ActionParameters[\"foo\"] = \"1\";\n            context2.ActionParameters[\"bar\"] = \"2\";\n            context2.ActionParameters[\"blap\"] = value2;\n            context2.ActionParameters[\"xyz\"] = \"abc\";\n\n            // Act\n            string result1 = attr.GetChildActionUniqueId(context1.Object);\n            string result2 = attr.GetChildActionUniqueId(context2.Object);\n\n            // Assert\n            Assert.NotEqual(result1, result2);\n        }\n\n        [Fact]\n        public void GetChildActionUniqueId_VariesByActionParameters_MatchesActionParametersInCaseInsensitiveManner()\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute { VaryByParam = \"foo ; bar ; blap\" };\n            MockActionExecutingContext context1 = new MockActionExecutingContext();\n            context1.ActionParameters[\"foo\"] = \"1\";\n            context1.ActionParameters[\"BAR\"] = \"2\";\n            context1.ActionParameters[\"blap\"] = \"3\";\n            context1.ActionParameters[\"xyz\"] = \"abc\";\n            MockActionExecutingContext context2 = new MockActionExecutingContext();\n            context2.ActionParameters[\"foo\"] = \"1\";\n            context2.ActionParameters[\"bar\"] = \"2\";\n            context2.ActionParameters[\"BLAP\"] = \"3\";\n            context2.ActionParameters[\"xyz\"] = \"abc\";\n\n            // Act\n            string result1 = attr.GetChildActionUniqueId(context1.Object);\n            string result2 = attr.GetChildActionUniqueId(context2.Object);\n\n            // Assert\n            Assert.Equal(result1, result2);\n        }\n\n        [Fact]\n        public void GetChildActionUniqueId_VariesByActionParameters_OnlyVariesByTheGivenParameters_Wildcard_Same()\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute { VaryByParam = \"*\" };\n            MockActionExecutingContext context1 = new MockActionExecutingContext();\n            context1.ActionParameters[\"foo\"] = \"1\";\n            context1.ActionParameters[\"bar\"] = \"2\";\n            context1.ActionParameters[\"blap\"] = \"3\";\n            context1.ActionParameters[\"xyz\"] = \"abc\";\n            MockActionExecutingContext context2 = new MockActionExecutingContext();\n            context2.ActionParameters[\"foo\"] = \"1\";\n            context2.ActionParameters[\"bar\"] = \"2\";\n            context2.ActionParameters[\"blap\"] = \"3\";\n            context2.ActionParameters[\"xyz\"] = \"abc\";\n\n            // Act\n            string result1 = attr.GetChildActionUniqueId(context1.Object);\n            string result2 = attr.GetChildActionUniqueId(context2.Object);\n\n            // Assert\n            Assert.Equal(result1, result2);\n        }\n\n        [Fact]\n        public void GetChildActionUniqueId_VariesByActionParameters_OnlyVariesByTheGivenParameters_Wildcard_CaseOnly_Same()\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute { VaryByParam = \"*\" };\n            MockActionExecutingContext context1 = new MockActionExecutingContext();\n            context1.ActionParameters[\"foo\"] = \"1\";\n            context1.ActionParameters[\"bar\"] = \"2\";\n            context1.ActionParameters[\"BLAP\"] = \"3\";\n            context1.ActionParameters[\"xyz\"] = \"abc\";\n            MockActionExecutingContext context2 = new MockActionExecutingContext();\n            context2.ActionParameters[\"FOO\"] = \"1\";\n            context2.ActionParameters[\"bar\"] = \"2\";\n            context2.ActionParameters[\"blap\"] = \"3\";\n            context2.ActionParameters[\"xyz\"] = \"abc\";\n\n            // Act\n            string result1 = attr.GetChildActionUniqueId(context1.Object);\n            string result2 = attr.GetChildActionUniqueId(context2.Object);\n\n            // Assert\n            Assert.Equal(result1, result2);\n        }\n\n        [Fact]\n        public void GetChildActionUniqueId_VariesByActionParameters_OnlyVariesByTheGivenParameters_Wildcard_Different()\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute { VaryByParam = \"*\" };\n            MockActionExecutingContext context1 = new MockActionExecutingContext();\n            context1.ActionParameters[\"foo\"] = \"1\";\n            context1.ActionParameters[\"bar\"] = \"2\";\n            context1.ActionParameters[\"blap\"] = \"3\";\n            context1.ActionParameters[\"xyz\"] = \"abc\";\n            MockActionExecutingContext context2 = new MockActionExecutingContext();\n            context2.ActionParameters[\"foo\"] = \"1\";\n            context2.ActionParameters[\"bar\"] = \"4\";\n            context2.ActionParameters[\"blap\"] = \"3\";\n            context2.ActionParameters[\"xyz\"] = \"abc\";\n\n            // Act\n            string result1 = attr.GetChildActionUniqueId(context1.Object);\n            string result2 = attr.GetChildActionUniqueId(context2.Object);\n\n            // Assert\n            Assert.NotEqual(result1, result2);\n        }\n\n        [Fact]\n        public void GetChildActionUniqueId_VariesByActionParameters_OnlyVariesByTheGivenParameters_None()\n        {\n            // Arrange\n            OutputCacheAttribute attr = new OutputCacheAttribute { VaryByParam = \"none\" };\n            MockActionExecutingContext context1 = new MockActionExecutingContext();\n            context1.ActionParameters[\"foo\"] = \"1\";\n            MockActionExecutingContext context2 = new MockActionExecutingContext();\n            context2.ActionParameters[\"foo\"] = \"2\";\n\n            // Act\n            string result1 = attr.GetChildActionUniqueId(context1.Object);\n            string result2 = attr.GetChildActionUniqueId(context2.Object);\n\n            // Assert\n            Assert.Equal(result1, result2);\n        }\n\n        [Theory]\n        [InlineData(\"bar\", \"VmmIPvA0bdX40A9EDzcQdDGenn9mW2fLitLhN3Q+q0o=\")]\n        [InlineData(\"*\", \"lRpCzLPVjS7Lwbix/vbtbdUWELWQOxiJaVemFCgM0ew=\")]\n        [InlineData(\"none\", \"IA6+zemlkqp8Ye59mwMEMYGo69mUVkAcFLa5z0keL50=\")]\n        public void GetChildActionUniqueId_ReturnsDifferentValuesIfVaryByParamValueIsModified(string varyByParam, string expected)\n        {\n            // Arrange\n            MockActionExecutingContext context = new MockActionExecutingContext();\n            context.ActionParameters[\"foo\"] = \"1\";\n            context.ActionParameters[\"bar\"] = \"2\";\n\n            OutputCacheAttribute attr = new OutputCacheAttribute { VaryByParam = \"foo\" };\n\n            // Act - 1\n            string result1 = attr.GetChildActionUniqueId(context.Object);\n\n            // Assert - 1\n            Assert.Equal(\"tXBiB5qdEzfISoXUUqXAzPcd7y/9Ik6eFqy8w9i3aDw=\", result1);\n\n            // Act - 2\n            attr.VaryByParam = varyByParam;\n            string result2 = attr.GetChildActionUniqueId(context.Object);\n\n            // Assert - 2\n            Assert.Equal(expected, result2);\n        }\n\n        class MockActionExecutingContext : Mock<ActionExecutingContext>\n        {\n            // StringComparer.OrdinalIgnoreCase matches the behavior of ControllerActionInvoker.\n            public Dictionary<string, object> ActionParameters = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);\n\n            public MockActionExecutingContext()\n            {\n                Setup(c => c.ActionDescriptor.UniqueId).Returns(\"abc123\");\n                Setup(c => c.ActionParameters).Returns(() => ActionParameters);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/OverrideActionFiltersAttributeTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc.Filters;\n\nnamespace System.Web.Mvc.Test\n{\n    public class OverrideActionFiltersAttributeTests : OverrideFiltersAttributeTests\n    {\n        protected override Type ExpectedFiltersToOverride\n        {\n            get { return typeof(IActionFilter); }\n        }\n        \n        protected override Type ProductUnderTestType\n        {\n            get { return typeof(OverrideActionFiltersAttribute); }\n        }\n\n        protected override IOverrideFilter CreateProductUnderTest()\n        {\n            return new OverrideActionFiltersAttribute();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/OverrideAuthenticationAttributeTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc.Filters;\n\nnamespace System.Web.Mvc.Test\n{\n    public class OverrideAuthenticationAttributeTests : OverrideFiltersAttributeTests\n    {\n        protected override Type ExpectedFiltersToOverride\n        {\n            get { return typeof(IAuthenticationFilter); }\n        }\n        \n        protected override Type ProductUnderTestType\n        {\n            get { return typeof(OverrideAuthenticationAttribute); }\n        }\n\n        protected override IOverrideFilter CreateProductUnderTest()\n        {\n            return new OverrideAuthenticationAttribute();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/OverrideAuthorizationAttributeTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc.Filters;\n\nnamespace System.Web.Mvc.Test\n{\n    public class OverrideAuthorizationAttributeTests : OverrideFiltersAttributeTests\n    {\n        protected override Type ExpectedFiltersToOverride\n        {\n            get { return typeof(IAuthorizationFilter); }\n        }\n        \n        protected override Type ProductUnderTestType\n        {\n            get { return typeof(OverrideAuthorizationAttribute); }\n        }\n\n        protected override IOverrideFilter CreateProductUnderTest()\n        {\n            return new OverrideAuthorizationAttribute();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/OverrideExceptionFiltersAttributeTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc.Filters;\n\nnamespace System.Web.Mvc.Test\n{\n    public class OverrideExceptionFiltersAttributeTests : OverrideFiltersAttributeTests\n    {\n        protected override Type ExpectedFiltersToOverride\n        {\n            get { return typeof(IExceptionFilter); }\n        }\n        \n        protected override Type ProductUnderTestType\n        {\n            get { return typeof(OverrideExceptionFiltersAttribute); }\n        }\n\n        protected override IOverrideFilter CreateProductUnderTest()\n        {\n            return new OverrideExceptionFiltersAttribute();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/OverrideFiltersAttributeTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Mvc.Filters;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public abstract class OverrideFiltersAttributeTests\n    {\n        protected abstract Type ProductUnderTestType { get; }\n\n        protected abstract Type ExpectedFiltersToOverride { get; }\n\n        [Fact]\n        public void FiltersToOverride_IsIActionFilter()\n        {\n            // Arrange\n            IOverrideFilter product = CreateProductUnderTest();\n\n            // Act\n            Type filtersToOverride = product.FiltersToOverride;\n\n            // Assert\n            Assert.Same(ExpectedFiltersToOverride, filtersToOverride);\n        }\n\n        [Fact]\n        public void AttributeUsage_IsAsSpecified()\n        {\n            // Act\n            AttributeUsageAttribute usage = (AttributeUsageAttribute)Attribute.GetCustomAttribute(ProductUnderTestType,\n                typeof(AttributeUsageAttribute));\n\n            // Assert\n            Assert.NotNull(usage);\n            Assert.Equal(AttributeTargets.Class | AttributeTargets.Method, usage.ValidOn);\n            Assert.True(usage.Inherited);\n            Assert.False(usage.AllowMultiple);\n        }\n\n        [Fact]\n        public void Integration_FilterAttributeFilterProvider_PassesThroughInstance()\n        {\n            // Arrange\n            object expected = CreateProductUnderTest();\n            FilterAttributeFilterProvider integrator = new FilterAttributeFilterProvider();\n            ActionDescriptor actionDescriptor = CreateActionDescriptor(expected);\n            ControllerContext controllerContext = CreateControllerContext();\n\n            // Act\n            IEnumerable<Filter> filters = integrator.GetFilters(controllerContext, actionDescriptor);\n\n            // Assert\n            Assert.NotNull(filters);\n            Filter filter = Assert.Single(filters);\n            Assert.NotNull(filter);\n            Assert.Same(expected, filter.Instance);\n        }\n\n        private static ActionDescriptor CreateActionDescriptor(object filter)\n        {\n            Mock<ActionDescriptor> mock = new Mock<ActionDescriptor>(MockBehavior.Strict);\n            FilterAttribute attribute = filter as FilterAttribute;\n            mock.Setup(d => d.GetFilterAttributes(It.IsAny<bool>()))\n                .Returns(attribute != null ? new FilterAttribute[] { attribute } : new FilterAttribute[0]);\n            mock.Setup(d => d.ControllerDescriptor).Returns(new Mock<ControllerDescriptor>().Object);\n            return mock.Object;\n        }\n\n        private static ControllerContext CreateControllerContext()\n        {\n            Mock<ControllerContext> mock = new Mock<ControllerContext>();\n            mock.SetupGet(c => c.Controller).Returns(new Mock<ControllerBase>(MockBehavior.Strict).Object);\n            return mock.Object;\n        }\n\n        protected abstract IOverrideFilter CreateProductUnderTest();\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/OverrideResultFiltersAttributeTests.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc.Filters;\n\nnamespace System.Web.Mvc.Test\n{\n    public class OverrideResultFiltersAttributeTests : OverrideFiltersAttributeTests\n    {\n        protected override Type ExpectedFiltersToOverride\n        {\n            get { return typeof(IResultFilter); }\n        }\n        \n        protected override Type ProductUnderTestType\n        {\n            get { return typeof(OverrideResultFiltersAttribute); }\n        }\n\n        protected override IOverrideFilter CreateProductUnderTest()\n        {\n            return new OverrideResultFiltersAttribute();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ParameterBindingInfoTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ParameterBindingInfoTest\n    {\n        [Fact]\n        public void BinderProperty()\n        {\n            // Arrange\n            ParameterBindingInfo bindingInfo = new ParameterBindingInfoHelper();\n\n            // Act & assert\n            Assert.Null(bindingInfo.Binder);\n        }\n\n        [Fact]\n        public void ExcludeProperty()\n        {\n            // Arrange\n            ParameterBindingInfo bindingInfo = new ParameterBindingInfoHelper();\n\n            // Act\n            ICollection<string> exclude = bindingInfo.Exclude;\n\n            // Assert\n            Assert.NotNull(exclude);\n            Assert.Empty(exclude);\n        }\n\n        [Fact]\n        public void IncludeProperty()\n        {\n            // Arrange\n            ParameterBindingInfo bindingInfo = new ParameterBindingInfoHelper();\n\n            // Act\n            ICollection<string> include = bindingInfo.Include;\n\n            // Assert\n            Assert.NotNull(include);\n            Assert.Empty(include);\n        }\n\n        [Fact]\n        public void PrefixProperty()\n        {\n            // Arrange\n            ParameterBindingInfo bindingInfo = new ParameterBindingInfoHelper();\n\n            // Act & assert\n            Assert.Null(bindingInfo.Prefix);\n        }\n\n        private class ParameterBindingInfoHelper : ParameterBindingInfo\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ParameterDescriptorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ParameterDescriptorTest\n    {\n        [Fact]\n        public void BindingInfoProperty()\n        {\n            // Arrange\n            ParameterDescriptor pd = GetParameterDescriptor(typeof(object), \"someName\");\n\n            // Act\n            ParameterBindingInfo bindingInfo = pd.BindingInfo;\n\n            // Assert\n            Assert.IsType(typeof(ParameterDescriptor).GetNestedType(\"EmptyParameterBindingInfo\", BindingFlags.NonPublic),\n                          bindingInfo);\n        }\n\n        [Fact]\n        public void DefaultValuePropertyDefaultsToNull()\n        {\n            // Arrange\n            ParameterDescriptor pd = GetParameterDescriptor();\n\n            // Act\n            object defaultValue = pd.DefaultValue;\n\n            // Assert\n            Assert.Null(defaultValue);\n        }\n\n        [Fact]\n        public void GetCustomAttributesReturnsEmptyArrayOfAttributeType()\n        {\n            // Arrange\n            ParameterDescriptor pd = GetParameterDescriptor();\n\n            // Act\n            ObsoleteAttribute[] attrs = (ObsoleteAttribute[])pd.GetCustomAttributes(typeof(ObsoleteAttribute), true);\n\n            // Assert\n            Assert.Empty(attrs);\n        }\n\n        [Fact]\n        public void GetCustomAttributesThrowsIfAttributeTypeIsNull()\n        {\n            // Arrange\n            ParameterDescriptor pd = GetParameterDescriptor();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { pd.GetCustomAttributes(null /* attributeType */, true); }, \"attributeType\");\n        }\n\n        [Fact]\n        public void GetCustomAttributesWithoutAttributeTypeCallsGetCustomAttributesWithAttributeType()\n        {\n            // Arrange\n            object[] expected = new object[0];\n            Mock<ParameterDescriptor> mockDescriptor = new Mock<ParameterDescriptor>() { CallBase = true };\n            mockDescriptor.Setup(d => d.GetCustomAttributes(typeof(object), true)).Returns(expected);\n            ParameterDescriptor pd = mockDescriptor.Object;\n\n            // Act\n            object[] returned = pd.GetCustomAttributes(true /* inherit */);\n\n            // Assert\n            Assert.Same(expected, returned);\n        }\n\n        [Fact]\n        public void IsDefinedReturnsFalse()\n        {\n            // Arrange\n            ParameterDescriptor pd = GetParameterDescriptor();\n\n            // Act\n            bool isDefined = pd.IsDefined(typeof(object), true);\n\n            // Assert\n            Assert.False(isDefined);\n        }\n\n        [Fact]\n        public void IsDefinedThrowsIfAttributeTypeIsNull()\n        {\n            // Arrange\n            ParameterDescriptor pd = GetParameterDescriptor();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { pd.IsDefined(null /* attributeType */, true); }, \"attributeType\");\n        }\n\n        private static ParameterDescriptor GetParameterDescriptor()\n        {\n            return GetParameterDescriptor(typeof(object), \"someName\");\n        }\n\n        private static ParameterDescriptor GetParameterDescriptor(Type type, string name)\n        {\n            Mock<ParameterDescriptor> mockDescriptor = new Mock<ParameterDescriptor>() { CallBase = true };\n            mockDescriptor.Setup(d => d.ParameterType).Returns(type);\n            mockDescriptor.Setup(d => d.ParameterName).Returns(name);\n            return mockDescriptor.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ParameterInfoUtilTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Linq;\nusing System.Reflection;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ParameterInfoUtilTest\n    {\n        [Fact]\n        public void TryGetDefaultValue_FirstChecksDefaultValue()\n        {\n            // Arrange\n            Mock<ParameterInfo> mockPInfo = new Mock<ParameterInfo>() { DefaultValue = DefaultValue.Mock };\n            mockPInfo.Setup(p => p.DefaultValue).Returns(42);\n            mockPInfo.Setup(p => p.Name).Returns(\"someParameter\");\n\n            // Act\n            object defaultValue;\n            bool retVal = ParameterInfoUtil.TryGetDefaultValue(mockPInfo.Object, out defaultValue);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Equal(42, defaultValue);\n        }\n\n        [Fact]\n        public void TryGetDefaultValue_SecondChecksDefaultValueAttribute()\n        {\n            // Arrange\n            ParameterInfo pInfo = typeof(MyController).GetMethod(\"DefaultValues\").GetParameters()[1]; // hasDefaultValue\n\n            // Act\n            object defaultValue;\n            bool retVal = ParameterInfoUtil.TryGetDefaultValue(pInfo, out defaultValue);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Equal(\"someValue\", defaultValue);\n        }\n\n        [Fact]\n        public void TryGetDefaultValue_RespectsNullDefaultValue()\n        {\n            // Arrange\n            Mock<ParameterInfo> mockPInfo = new Mock<ParameterInfo>() { DefaultValue = DefaultValue.Mock };\n            mockPInfo.Setup(p => p.DefaultValue).Returns(null);\n            mockPInfo.Setup(p => p.Name).Returns(\"someParameter\");\n            mockPInfo\n                .Setup(p => p.GetCustomAttributes(typeof(DefaultValueAttribute[]), false))\n                .Returns(new DefaultValueAttribute[] { new DefaultValueAttribute(42) });\n\n            // Act\n            object defaultValue;\n            bool retVal = ParameterInfoUtil.TryGetDefaultValue(mockPInfo.Object, out defaultValue);\n\n            // Assert\n            Assert.True(retVal);\n            Assert.Null(defaultValue);\n        }\n\n        [Fact]\n        public void TryGetDefaultValue_ReturnsFalseIfNoDefaultValue()\n        {\n            // Arrange\n            ParameterInfo pInfo = typeof(MyController).GetMethod(\"DefaultValues\").GetParameters()[0]; // noDefaultValue\n\n            // Act\n            object defaultValue;\n            bool retVal = ParameterInfoUtil.TryGetDefaultValue(pInfo, out defaultValue);\n\n            // Assert\n            Assert.False(retVal);\n            Assert.Equal(default(object), defaultValue);\n        }\n\n        [Fact]\n        public void TryGetDefaultValue_DefaultValueAttributeParameters()\n        {\n            DefaultValueAttributeHelper<bool>(true, \"boolParam\");\n            DefaultValueAttributeHelper<byte>(42, \"byteParam\");\n            DefaultValueAttributeHelper<char>('a', \"charParam\");\n            DefaultValueAttributeHelper<double>(1.0, \"doubleParam\");\n            DefaultValueAttributeHelper<MyEnum>(MyEnum.All, \"enumParam\");\n            DefaultValueAttributeHelper<float>((float)1.0, \"floatParam\");\n            DefaultValueAttributeHelper<int>(42, \"intParam\");\n            DefaultValueAttributeHelper<long>(42, \"longParam\");\n            DefaultValueAttributeHelper<object>(null, \"objectParam\");\n            DefaultValueAttributeHelper<short>(42, \"shortParam\");\n            DefaultValueAttributeHelper<string>(\"abc\", \"stringParam\");\n            DefaultValueAttributeHelper<DateTime>(new DateTime(2010, 09, 27), \"customParam\");\n        }\n\n        [Fact]\n        public void TryGetDefaultValue_OptionalParameters()\n        {\n            OptionalParamHelper<bool>(true, \"boolParam\");\n            OptionalParamHelper<byte>(42, \"byteParam\");\n            OptionalParamHelper<char>('a', \"charParam\");\n            OptionalParamHelper<double>(1.0, \"doubleParam\");\n            OptionalParamHelper<MyEnum>(MyEnum.All, \"enumParam\");\n            OptionalParamHelper<float>((float)1.0, \"floatParam\");\n            OptionalParamHelper<int>(42, \"intParam\");\n            OptionalParamHelper<long>(42, \"longParam\");\n            OptionalParamHelper<object>(null, \"objectParam\");\n            OptionalParamHelper<short>(42, \"shortParam\");\n            OptionalParamHelper<string>(\"abc\", \"stringParam\");\n        }\n\n        private static void DefaultValueAttributeHelper<TParam>(TParam expectedValue, string paramName)\n        {\n            ParameterTestHelper<TParam>(expectedValue, paramName, \"AttributeDefaultValues\");\n        }\n\n        private static void OptionalParamHelper<TParam>(TParam expectedValue, string paramName)\n        {\n            ParameterTestHelper<TParam>(expectedValue, paramName, \"OptionalParamDefaultValues\");\n        }\n\n        private static void ParameterTestHelper<TParam>(TParam expectedValue, string paramName, string actionMethodName)\n        {\n            ParameterInfo pInfo = typeof(MyController).GetMethod(actionMethodName).GetParameters().Single(p => p.Name == paramName);\n            object returnValueObject;\n            bool result = ParameterInfoUtil.TryGetDefaultValue(pInfo, out returnValueObject);\n\n            Assert.True(result);\n            if (expectedValue != null)\n            {\n                Assert.IsType<TParam>(returnValueObject);\n            }\n            TParam returnValue = (TParam)returnValueObject;\n            Assert.Equal<TParam>(expectedValue, returnValue);\n        }\n\n        private class MyController : Controller\n        {\n            public void DefaultValues(string noDefaultValue, [DefaultValue(\"someValue\")] string hasDefaultValue)\n            {\n            }\n\n            public void AttributeDefaultValues(\n                [DefaultValue(true)] bool boolParam,\n                [DefaultValue((byte)42)] byte byteParam,\n                [DefaultValue('a')] char charParam,\n                [DefaultValue(typeof(DateTime), \"2010-09-27\")] object customParam,\n                [DefaultValue((double)1.0)] double doubleParam,\n                [DefaultValue(MyEnum.All)] MyEnum enumParam,\n                [DefaultValue((float)1.0)] float floatParam,\n                [DefaultValue(42)] int intParam,\n                [DefaultValue((long)42)] long longParam,\n                [DefaultValue(null)] object objectParam,\n                [DefaultValue((short)42)] short shortParam,\n                [DefaultValue(\"abc\")] string stringParam\n                )\n            {\n            }\n\n            public void OptionalParamDefaultValues(\n                bool boolParam = true,\n                byte byteParam = 42,\n                char charParam = 'a',\n                double doubleParam = 1.0,\n                MyEnum enumParam = MyEnum.All,\n                float floatParam = (float)1.0,\n                int intParam = 42,\n                long longParam = 42,\n                object objectParam = null,\n                short shortParam = 42,\n                string stringParam = \"abc\"\n                )\n            {\n            }\n        }\n\n        private enum MyEnum\n        {\n            None = 0,\n            All = 1\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/PartialViewResultTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class PartialViewResultTest\n    {\n        private const string _viewName = \"My cool partial view.\";\n\n        [Fact]\n        public void EmptyViewNameUsesActionNameAsViewName()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            HttpContextBase httpContext = CreateHttpContext();\n            RouteData routeData = new RouteData();\n            routeData.Values[\"action\"] = _viewName;\n            ControllerContext context = new ControllerContext(httpContext, routeData, controller);\n            Mock<IViewEngine> viewEngine = new Mock<IViewEngine>(MockBehavior.Strict);\n            Mock<IView> view = new Mock<IView>(MockBehavior.Strict);\n            List<IViewEngine> viewEngines = new List<IViewEngine>();\n            viewEngines.Add(viewEngine.Object);\n            Mock<ViewEngineCollection> viewEngineCollection = new Mock<ViewEngineCollection>(MockBehavior.Strict, viewEngines);\n            PartialViewResult result = new PartialViewResultHelper { ViewEngineCollection = viewEngineCollection.Object };\n            viewEngine\n                .Setup(e => e.FindPartialView(It.IsAny<ControllerContext>(), _viewName, It.IsAny<bool>()))\n                .Callback<ControllerContext, string, bool>(\n                    (controllerContext, viewName, useCache) =>\n                    {\n                        Assert.Same(httpContext, controllerContext.HttpContext);\n                        Assert.Same(routeData, controllerContext.RouteData);\n                    })\n                .Returns(new ViewEngineResult(view.Object, viewEngine.Object));\n            viewEngineCollection\n                .Setup(e => e.FindPartialView(It.IsAny<ControllerContext>(), _viewName))\n                .Returns(new ViewEngineResult(view.Object, viewEngine.Object));\n            view\n                .Setup(o => o.Render(It.IsAny<ViewContext>(), httpContext.Response.Output))\n                .Callback<ViewContext, TextWriter>(\n                    (viewContext, writer) =>\n                    {\n                        Assert.Same(view.Object, viewContext.View);\n                        Assert.Same(result.ViewData, viewContext.ViewData);\n                        Assert.Same(result.TempData, viewContext.TempData);\n                        Assert.Same(controller, viewContext.Controller);\n                    });\n            viewEngine\n                .Setup(e => e.ReleaseView(context, It.IsAny<IView>()))\n                .Callback<ControllerContext, IView>(\n                    (controllerContext, releasedView) => { Assert.Same(releasedView, view.Object); });\n\n            // Act\n            result.ExecuteResult(context);\n\n            // Assert\n            viewEngine.Verify();\n            viewEngineCollection.Verify();\n            view.Verify();\n        }\n\n        [Fact]\n        public void EngineLookupFailureThrows()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            HttpContextBase httpContext = CreateHttpContext();\n            RouteData routeData = new RouteData();\n            routeData.Values[\"action\"] = _viewName;\n            ControllerContext context = new ControllerContext(httpContext, routeData, controller);\n            Mock<IViewEngine> viewEngine = new Mock<IViewEngine>(MockBehavior.Strict);\n            List<IViewEngine> viewEngines = new List<IViewEngine>();\n            viewEngines.Add(viewEngine.Object);\n            Mock<ViewEngineCollection> viewEngineCollection = new Mock<ViewEngineCollection>(MockBehavior.Strict, viewEngines);\n            PartialViewResult result = new PartialViewResultHelper { ViewEngineCollection = viewEngineCollection.Object };\n            viewEngineCollection\n                .Setup(e => e.FindPartialView(It.IsAny<ControllerContext>(), _viewName))\n                .Returns(new ViewEngineResult(new[] { \"location1\", \"location2\" }));\n            viewEngine\n                .Setup(e => e.FindPartialView(It.IsAny<ControllerContext>(), _viewName, It.IsAny<bool>()))\n                .Callback<ControllerContext, string, bool>(\n                    (controllerContext, viewName, useCache) =>\n                    {\n                        Assert.Same(httpContext, controllerContext.HttpContext);\n                        Assert.Same(routeData, controllerContext.RouteData);\n                    })\n                .Returns(new ViewEngineResult(new[] { \"location1\", \"location2\" }));\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => result.ExecuteResult(context),\n                \"The partial view '\" + _viewName + \"' was not found or no view engine supports the searched locations. The following locations were searched:\" + Environment.NewLine\n              + \"location1\" + Environment.NewLine\n              + \"location2\");\n\n            viewEngine.Verify();\n            viewEngineCollection.Verify();\n        }\n\n        [Fact]\n        public void EngineLookupSuccessRendersView()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            HttpContextBase httpContext = CreateHttpContext();\n            RouteData routeData = new RouteData();\n            ControllerContext context = new ControllerContext(httpContext, routeData, controller);\n            Mock<IViewEngine> viewEngine = new Mock<IViewEngine>(MockBehavior.Strict);\n            List<IViewEngine> viewEngines = new List<IViewEngine>();\n            viewEngines.Add(viewEngine.Object);\n            Mock<ViewEngineCollection> viewEngineCollection = new Mock<ViewEngineCollection>(MockBehavior.Strict, viewEngines);\n            Mock<IView> view = new Mock<IView>(MockBehavior.Strict);\n            PartialViewResult result = new PartialViewResultHelper { ViewEngineCollection = viewEngineCollection.Object, ViewName = _viewName };\n            view\n                .Setup(o => o.Render(It.IsAny<ViewContext>(), httpContext.Response.Output))\n                .Callback<ViewContext, TextWriter>(\n                    (viewContext, writer) =>\n                    {\n                        Assert.Same(view.Object, viewContext.View);\n                        Assert.Same(result.ViewData, viewContext.ViewData);\n                        Assert.Same(result.TempData, viewContext.TempData);\n                        Assert.Same(controller, viewContext.Controller);\n                    });\n            viewEngineCollection\n                .Setup(e => e.FindPartialView(It.IsAny<ControllerContext>(), _viewName))\n                .Returns(new ViewEngineResult(view.Object, viewEngine.Object));\n            viewEngine\n                .Setup(e => e.FindPartialView(It.IsAny<ControllerContext>(), _viewName, It.IsAny<bool>()))\n                .Callback<ControllerContext, string, bool>(\n                    (controllerContext, viewName, useCache) =>\n                    {\n                        Assert.Same(httpContext, controllerContext.HttpContext);\n                        Assert.Same(routeData, controllerContext.RouteData);\n                    })\n                .Returns(new ViewEngineResult(view.Object, viewEngine.Object));\n            viewEngine\n                .Setup(e => e.ReleaseView(context, It.IsAny<IView>()))\n                .Callback<ControllerContext, IView>(\n                    (controllerContext, releasedView) => { Assert.Same(releasedView, view.Object); });\n\n            // Act\n            result.ExecuteResult(context);\n\n            // Assert\n            viewEngineCollection.Verify();\n            viewEngine.Verify();\n            view.Verify();\n        }\n\n        [Fact]\n        public void ExecuteResultWithExplicitViewObject()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            HttpContextBase httpContext = CreateHttpContext();\n            RouteData routeData = new RouteData();\n            routeData.Values[\"action\"] = _viewName;\n            ControllerContext context = new ControllerContext(httpContext, routeData, controller);\n            Mock<IView> view = new Mock<IView>(MockBehavior.Strict);\n            PartialViewResult result = new PartialViewResultHelper { View = view.Object };\n            view\n                .Setup(o => o.Render(It.IsAny<ViewContext>(), httpContext.Response.Output))\n                .Callback<ViewContext, TextWriter>(\n                    (viewContext, writer) =>\n                    {\n                        Assert.Same(view.Object, viewContext.View);\n                        Assert.Same(result.ViewData, viewContext.ViewData);\n                        Assert.Same(result.TempData, viewContext.TempData);\n                        Assert.Same(controller, viewContext.Controller);\n                    });\n\n            // Act\n            result.ExecuteResult(context);\n\n            // Assert\n            view.Verify();\n        }\n\n        private static HttpContextBase CreateHttpContext()\n        {\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(c => c.Response.Output).Returns(TextWriter.Null);\n            return mockHttpContext.Object;\n        }\n\n        private class PartialViewResultHelper : PartialViewResult\n        {\n            public PartialViewResultHelper()\n            {\n                ViewEngineCollection = new ViewEngineCollection(new IViewEngine[] { new WebFormViewEngine() });\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/PreApplicationStartCodeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Reflection;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class PreApplicationStartCodeTest\n    {\n        [Fact]\n        public void PreApplicationStartCodeIsNotBrowsableTest()\n        {\n            PreAppStartTestHelper.TestPreAppStartClass(typeof(PreApplicationStartCode));\n        }\n\n        [Fact]\n        public void PreApplicationStartMethodAttributeTest()\n        {\n            Assembly assembly = typeof(Controller).Assembly;\n            object[] attributes = assembly.GetCustomAttributes(typeof(PreApplicationStartMethodAttribute), true);\n            var preAppStartMethodAttribute = Assert.Single(attributes.Cast<PreApplicationStartMethodAttribute>());\n            Type preAppStartMethodType = preAppStartMethodAttribute.Type;\n            Assert.Equal(typeof(PreApplicationStartCode), preAppStartMethodType);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/QueryStringValueProviderFactoryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing System.Globalization;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class QueryStringValueProviderFactoryTest\n    {\n        private static readonly NameValueCollection _backingStore = new NameValueCollection()\n        {\n            { \"foo\", \"fooValue\" }\n        };\n\n        private static readonly NameValueCollection _unvalidatedBackingStore = new NameValueCollection()\n        {\n            { \"foo\", \"fooUnvalidated\" }\n        };\n\n        [Fact]\n        public void GetValueProvider()\n        {\n            // Arrange\n            Mock<MockableUnvalidatedRequestValues> mockUnvalidatedValues = new Mock<MockableUnvalidatedRequestValues>();\n            QueryStringValueProviderFactory factory = new QueryStringValueProviderFactory(_ => mockUnvalidatedValues.Object);\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(o => o.HttpContext.Request.QueryString).Returns(_backingStore);\n\n            // Act\n            IValueProvider valueProvider = factory.GetValueProvider(mockControllerContext.Object);\n\n            // Assert\n            Assert.Equal(typeof(QueryStringValueProvider), valueProvider.GetType());\n            ValueProviderResult vpResult = valueProvider.GetValue(\"foo\");\n\n            Assert.NotNull(vpResult);\n            Assert.Equal(\"fooValue\", vpResult.AttemptedValue);\n            Assert.Equal(CultureInfo.InvariantCulture, vpResult.Culture);\n        }\n\n        [Fact]\n        public void GetValueProvider_GetValue_SkipValidation()\n        {\n            // Arrange\n            Mock<MockableUnvalidatedRequestValues> mockUnvalidatedValues = new Mock<MockableUnvalidatedRequestValues>();\n            mockUnvalidatedValues.Setup(o => o.QueryString).Returns(_unvalidatedBackingStore);\n            QueryStringValueProviderFactory factory = new QueryStringValueProviderFactory(_ => mockUnvalidatedValues.Object);\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(o => o.HttpContext.Request.QueryString).Returns(_backingStore);\n\n            // Act\n            IUnvalidatedValueProvider valueProvider = (IUnvalidatedValueProvider)factory.GetValueProvider(mockControllerContext.Object);\n\n            // Assert\n            Assert.Equal(typeof(QueryStringValueProvider), valueProvider.GetType());\n            ValueProviderResult vpResult = valueProvider.GetValue(\"foo\", skipValidation: true);\n\n            Assert.NotNull(vpResult);\n            Assert.Equal(\"fooUnvalidated\", vpResult.AttemptedValue);\n            Assert.Equal(CultureInfo.InvariantCulture, vpResult.Culture);\n        }\n\n        [Fact]\n        public void GetValueProvider_ThrowsIfControllerContextIsNull()\n        {\n            // Arrange\n            QueryStringValueProviderFactory factory = new QueryStringValueProviderFactory();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { factory.GetValueProvider(null); }, \"controllerContext\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/RangeAttributeAdapterTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")] // Uses ModelMetadataProviders.Current\n    public class RangeAttributeAdapterTest\n    {\n        [Fact]\n        [ReplaceCulture]\n        public void ClientRulesWithRangeAttribute()\n        {\n            // Arrange\n            var metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => null, typeof(string), \"Length\");\n            var context = new ControllerContext();\n            var attribute = new RangeAttribute(typeof(decimal), \"0\", \"100\");\n            var adapter = new RangeAttributeAdapter(metadata, context, attribute);\n\n            // Act\n            var rules = adapter.GetClientValidationRules()\n                .OrderBy(r => r.ValidationType)\n                .ToArray();\n\n            // Assert\n            ModelClientValidationRule rule = Assert.Single(rules);\n            Assert.Equal(\"range\", rule.ValidationType);\n            Assert.Equal(2, rule.ValidationParameters.Count);\n            Assert.Equal(0m, rule.ValidationParameters[\"min\"]);\n            Assert.Equal(100m, rule.ValidationParameters[\"max\"]);\n            Assert.Equal(@\"The field Length must be between 0 and 100.\", rule.ErrorMessage);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/RazorViewEngineTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class RazorViewEngineTest\n    {\n        [Fact]\n        public void AreaMasterLocationFormats()\n        {\n            // Arrange\n            string[] expected = new[]\n            {\n                \"~/Areas/{2}/Views/{1}/{0}.cshtml\",\n                \"~/Areas/{2}/Views/{1}/{0}.vbhtml\",\n                \"~/Areas/{2}/Views/Shared/{0}.cshtml\",\n                \"~/Areas/{2}/Views/Shared/{0}.vbhtml\"\n            };\n\n            // Act\n            RazorViewEngine viewEngine = new RazorViewEngine();\n\n            // Assert\n            Assert.Equal(expected, viewEngine.AreaMasterLocationFormats);\n        }\n\n        [Fact]\n        public void AreaPartialViewLocationFormats()\n        {\n            // Arrange\n            string[] expected = new[]\n            {\n                \"~/Areas/{2}/Views/{1}/{0}.cshtml\",\n                \"~/Areas/{2}/Views/{1}/{0}.vbhtml\",\n                \"~/Areas/{2}/Views/Shared/{0}.cshtml\",\n                \"~/Areas/{2}/Views/Shared/{0}.vbhtml\"\n            };\n\n            // Act\n            RazorViewEngine viewEngine = new RazorViewEngine();\n\n            // Assert\n            Assert.Equal(expected, viewEngine.AreaPartialViewLocationFormats);\n        }\n\n        [Fact]\n        public void AreaViewLocationFormats()\n        {\n            // Arrange\n            string[] expected = new[]\n            {\n                \"~/Areas/{2}/Views/{1}/{0}.cshtml\",\n                \"~/Areas/{2}/Views/{1}/{0}.vbhtml\",\n                \"~/Areas/{2}/Views/Shared/{0}.cshtml\",\n                \"~/Areas/{2}/Views/Shared/{0}.vbhtml\"\n            };\n\n            // Act\n            RazorViewEngine viewEngine = new RazorViewEngine();\n\n            // Assert\n            Assert.Equal(expected, viewEngine.AreaViewLocationFormats);\n        }\n\n        [Fact]\n        public void RazorViewEngineSetsViewPageActivator()\n        {\n            // Arrange\n            Mock<IViewPageActivator> viewPageActivator = new Mock<IViewPageActivator>();\n            TestableRazorViewEngine viewEngine = new TestableRazorViewEngine(viewPageActivator.Object);\n\n            //Act & Assert\n            Assert.Equal(viewPageActivator.Object, viewEngine.ViewPageActivator);\n        }\n\n        [Fact]\n        public void CreatePartialView_PassesViewPageActivator()\n        {\n            // Arrange\n            Mock<IViewPageActivator> viewPageActivator = new Mock<IViewPageActivator>();\n            TestableRazorViewEngine viewEngine = new TestableRazorViewEngine(viewPageActivator.Object);\n\n            // Act\n            RazorView result = (RazorView)viewEngine.CreatePartialView(\"partial path\");\n\n            // Assert\n            Assert.Equal(viewEngine.ViewPageActivator, result.ViewPageActivator);\n        }\n\n        [Fact]\n        public void CreateView_PassesViewPageActivator()\n        {\n            // Arrange\n            Mock<IViewPageActivator> viewPageActivator = new Mock<IViewPageActivator>();\n            TestableRazorViewEngine viewEngine = new TestableRazorViewEngine(viewPageActivator.Object);\n\n            // Act\n            RazorView result = (RazorView)viewEngine.CreateView(\"partial path\", \"master path\");\n\n            // Assert\n            Assert.Equal(viewEngine.ViewPageActivator, result.ViewPageActivator);\n        }\n\n        [Fact]\n        public void CreatePartialView_ReturnsRazorView()\n        {\n            // Arrange\n            TestableRazorViewEngine viewEngine = new TestableRazorViewEngine();\n\n            // Act\n            RazorView result = (RazorView)viewEngine.CreatePartialView(\"partial path\");\n\n            // Assert\n            Assert.Equal(\"partial path\", result.ViewPath);\n            Assert.Equal(String.Empty, result.LayoutPath);\n            Assert.False(result.RunViewStartPages);\n        }\n\n        [Fact]\n        public void CreateView_ReturnsRazorView()\n        {\n            // Arrange\n            TestableRazorViewEngine viewEngine = new TestableRazorViewEngine()\n            {\n                FileExtensions = new[] { \"cshtml\", \"vbhtml\", \"razor\" }\n            };\n\n            // Act\n            RazorView result = (RazorView)viewEngine.CreateView(\"partial path\", \"master path\");\n\n            // Assert\n            Assert.Equal(\"partial path\", result.ViewPath);\n            Assert.Equal(\"master path\", result.LayoutPath);\n            Assert.Equal(new[] { \"cshtml\", \"vbhtml\", \"razor\" }, result.ViewStartFileExtensions.ToArray());\n            Assert.True(result.RunViewStartPages);\n        }\n\n        [Fact]\n        public void FileExtensionsProperty()\n        {\n            // Arrange\n            string[] expected = new[]\n            {\n                \"cshtml\",\n                \"vbhtml\",\n            };\n\n            // Act\n            RazorViewEngine viewEngine = new RazorViewEngine();\n\n            // Assert\n            Assert.Equal(expected, viewEngine.FileExtensions);\n        }\n\n        [Fact]\n        public void MasterLocationFormats()\n        {\n            // Arrange\n            string[] expected = new[]\n            {\n                \"~/Views/{1}/{0}.cshtml\",\n                \"~/Views/{1}/{0}.vbhtml\",\n                \"~/Views/Shared/{0}.cshtml\",\n                \"~/Views/Shared/{0}.vbhtml\"\n            };\n\n            // Act\n            RazorViewEngine viewEngine = new RazorViewEngine();\n\n            // Assert\n            Assert.Equal(expected, viewEngine.MasterLocationFormats);\n        }\n\n        [Fact]\n        public void PartialViewLocationFormats()\n        {\n            // Arrange\n            string[] expected = new[]\n            {\n                \"~/Views/{1}/{0}.cshtml\",\n                \"~/Views/{1}/{0}.vbhtml\",\n                \"~/Views/Shared/{0}.cshtml\",\n                \"~/Views/Shared/{0}.vbhtml\"\n            };\n\n            // Act\n            RazorViewEngine viewEngine = new RazorViewEngine();\n\n            // Assert\n            Assert.Equal(expected, viewEngine.PartialViewLocationFormats);\n        }\n\n        [Fact]\n        public void ViewLocationFormats()\n        {\n            // Arrange\n            string[] expected = new[]\n            {\n                \"~/Views/{1}/{0}.cshtml\",\n                \"~/Views/{1}/{0}.vbhtml\",\n                \"~/Views/Shared/{0}.cshtml\",\n                \"~/Views/Shared/{0}.vbhtml\"\n            };\n\n            // Act\n            RazorViewEngine viewEngine = new RazorViewEngine();\n\n            // Assert\n            Assert.Equal(expected, viewEngine.ViewLocationFormats);\n        }\n\n        [Fact]\n        public void ViewStartFileName()\n        {\n            Assert.Equal(\"_ViewStart\", RazorViewEngine.ViewStartFileName);\n        }\n\n        private sealed class TestableRazorViewEngine : RazorViewEngine\n        {\n            public TestableRazorViewEngine()\n                : base()\n            {\n            }\n\n            public TestableRazorViewEngine(IViewPageActivator viewPageActivator)\n                : base(viewPageActivator)\n            {\n            }\n\n            public new IViewPageActivator ViewPageActivator\n            {\n                get { return base.ViewPageActivator; }\n            }\n\n            public IView CreatePartialView(string partialPath)\n            {\n                return base.CreatePartialView(new ControllerContext(), partialPath);\n            }\n\n            public IView CreateView(string viewPath, string masterPath)\n            {\n                return base.CreateView(new ControllerContext(), viewPath, masterPath);\n            }\n\n            // This method should remain overridable in derived view engines\n            protected override bool FileExists(ControllerContext controllerContext, string virtualPath)\n            {\n                return base.FileExists(controllerContext, virtualPath);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/RazorViewTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Web.WebPages;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class RazorViewTest\n    {\n        [Fact]\n        public void Constructor_RunViewStartPagesParam()\n        {\n            var context = new ControllerContext();\n            Assert.True(new RazorView(context, \"~/view\", \"~/master\", runViewStartPages: true, viewStartFileExtensions: null).RunViewStartPages);\n            Assert.False(new RazorView(context, \"~/view\", \"~/master\", runViewStartPages: false, viewStartFileExtensions: null).RunViewStartPages);\n            Assert.True(new RazorView(context, \"~/view\", \"~/master\", runViewStartPages: true, viewStartFileExtensions: null, viewPageActivator: new Mock<IViewPageActivator>().Object).RunViewStartPages);\n            Assert.False(new RazorView(context, \"~/view\", \"~/master\", runViewStartPages: false, viewStartFileExtensions: null, viewPageActivator: new Mock<IViewPageActivator>().Object).RunViewStartPages);\n        }\n\n        [Fact]\n        public void ConstructorWithEmptyViewPathThrows()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => new RazorView(new ControllerContext(), String.Empty, \"~/master\", false, Enumerable.Empty<string>()),\n                \"viewPath\"\n                );\n        }\n\n        [Fact]\n        public void ConstructorWithNullViewPathThrows()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => new RazorView(new ControllerContext(), null, \"~/master\", false, Enumerable.Empty<string>()),\n                \"viewPath\"\n                );\n        }\n\n        [Fact]\n        public void ConstructorWithNullControllerContextThrows()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => new RazorView(null, \"view path\", \"~/master\", false, Enumerable.Empty<string>()),\n                \"controllerContext\"\n                );\n        }\n\n        [Fact]\n        public void LayoutPathProperty()\n        {\n            //Arrange\n            ControllerContext controllerContext = new ControllerContext();\n\n            // Act\n            RazorView view = new RazorView(new ControllerContext(), \"view path\", \"master path\", false, Enumerable.Empty<string>());\n\n            // Assert\n            Assert.Equal(\"master path\", view.LayoutPath);\n        }\n\n        [Fact]\n        public void LayoutPathPropertyReturnsEmptyStringIfNullLayoutSpecified()\n        {\n            // Act\n            RazorView view = new RazorView(new ControllerContext(), \"view path\", null, false, Enumerable.Empty<string>());\n\n            // Assert\n            Assert.Equal(String.Empty, view.LayoutPath);\n        }\n\n        [Fact]\n        public void LayoutPathPropertyReturnsEmptyStringIfLayoutNotSpecified()\n        {\n            // Act\n            RazorView view = new RazorView(new ControllerContext(), \"view path\", null, false, Enumerable.Empty<string>());\n\n            // Assert\n            Assert.Equal(String.Empty, view.LayoutPath);\n        }\n\n        [Fact]\n        public void RenderWithNullWriterThrows()\n        {\n            // Arrange\n            RazorView view = new RazorView(new ControllerContext(), \"~/viewPath\", null, false, Enumerable.Empty<string>());\n            Mock<ViewContext> viewContextMock = new Mock<ViewContext>();\n\n            MockBuildManager buildManager = new MockBuildManager(\"~/viewPath\", typeof(object));\n            view.BuildManager = buildManager;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => view.Render(viewContextMock.Object, null),\n                \"writer\"\n                );\n        }\n\n        [Fact]\n        public void RenderWithUnsupportedTypeThrows()\n        {\n            // Arrange\n            ViewContext context = new Mock<ViewContext>().Object;\n            MockBuildManager buildManagerMock = new MockBuildManager(\"view path\", typeof(object));\n            RazorView view = new RazorView(new ControllerContext(), \"view path\", null, false, Enumerable.Empty<string>());\n            view.BuildManager = buildManagerMock;\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => view.Render(context, new Mock<TextWriter>().Object),\n                \"The view at 'view path' must derive from WebViewPage, or WebViewPage<TModel>.\"\n                );\n        }\n\n        [Fact]\n        public void RenderWithViewPageAndNoStartPageLookupRendersView()\n        {\n            // Arrange\n            StubWebViewPage viewPage = new StubWebViewPage();\n            Mock<ViewContext> viewContextMock = new Mock<ViewContext>();\n            viewContextMock.Setup(vc => vc.HttpContext.Items).Returns(new Dictionary<object, object>());\n            viewContextMock.Setup(vc => vc.HttpContext.Request.IsLocal).Returns(false);\n            MockBuildManager buildManager = new MockBuildManager(\"~/viewPath\", typeof(object));\n            Mock<IViewPageActivator> activator = new Mock<IViewPageActivator>(MockBehavior.Strict);\n            ControllerContext controllerContext = new ControllerContext();\n            activator.Setup(l => l.Create(controllerContext, typeof(object))).Returns(viewPage);\n            RazorView view = new RazorView(controllerContext, \"~/viewPath\", null, false, Enumerable.Empty<string>(), activator.Object);\n            view.StartPageLookup = (WebPageRenderingBase p, string n, IEnumerable<string> e) =>\n            {\n                Assert.True(false, \"ViewStart page lookup should not be called\");\n                return null;\n            };\n            view.BuildManager = buildManager;\n\n            // Act\n            view.Render(viewContextMock.Object, new Mock<TextWriter>().Object);\n\n            // Assert\n            Assert.Null(viewPage.Layout);\n            Assert.Equal(\"\", viewPage.OverridenLayoutPath);\n            Assert.Same(viewContextMock.Object, viewPage.ViewContext);\n            Assert.Equal(\"~/viewPath\", viewPage.VirtualPath);\n        }\n\n        [Fact]\n        public void RenderWithViewPageAndStartPageLookupExecutesStartPage()\n        {\n            // Arrange\n            StubWebViewPage viewPage = new StubWebViewPage();\n            Mock<ViewContext> viewContextMock = new Mock<ViewContext>();\n            viewContextMock.Setup(vc => vc.HttpContext.Items).Returns(new Dictionary<object, object>());\n            MockBuildManager buildManager = new MockBuildManager(\"~/viewPath\", typeof(object));\n            Mock<IViewPageActivator> activator = new Mock<IViewPageActivator>(MockBehavior.Strict);\n            ControllerContext controllerContext = new ControllerContext();\n            activator.Setup(l => l.Create(controllerContext, typeof(object))).Returns(viewPage);\n            RazorView view = new RazorView(controllerContext, \"~/viewPath\", null, true, new[] { \"cshtml\" }, activator.Object);\n            Mock<ViewStartPage> startPage = new Mock<ViewStartPage>();\n            startPage.Setup(sp => sp.ExecutePageHierarchy()).Verifiable();\n            view.StartPageLookup = (WebPageRenderingBase page, string fileName, IEnumerable<string> extensions) =>\n            {\n                Assert.Equal(viewPage, page);\n                Assert.Equal(\"_ViewStart\", fileName);\n                Assert.Equal(new[] { \"cshtml\" }, extensions.ToArray());\n                return startPage.Object;\n            };\n            view.BuildManager = buildManager;\n\n            // Act\n            view.Render(viewContextMock.Object, new Mock<TextWriter>().Object);\n\n            // Assert\n            startPage.Verify(sp => sp.ExecutePageHierarchy(), Times.Once());\n        }\n\n        // TODO: This throws in WebPages and needs to be tracked down.\n        [Fact]\n        public void RenderWithViewPageAndLayoutPageRendersView()\n        {\n            // Arrange\n            StubWebViewPage viewPage = new StubWebViewPage();\n            Mock<ViewContext> viewContext = new Mock<ViewContext>();\n            Mock<HttpContextBase> httpContext = new Mock<HttpContextBase>();\n            Mock<HttpRequestBase> httpRequest = new Mock<HttpRequestBase>();\n\n            httpRequest.SetupGet(r => r.IsLocal).Returns(false);\n            httpRequest.SetupGet(r => r.Browser.IsMobileDevice).Returns(false);\n            httpRequest.SetupGet(r => r.Cookies).Returns(new HttpCookieCollection());\n\n            httpContext.SetupGet(c => c.Request).Returns(httpRequest.Object);\n            httpContext.SetupGet(c => c.Response.Cookies).Returns(new HttpCookieCollection());\n            httpContext.SetupGet(c => c.Items).Returns(new Hashtable());\n\n            viewContext.SetupGet(v => v.HttpContext).Returns(httpContext.Object);\n\n            MockBuildManager buildManager = new MockBuildManager(\"~/viewPath\", typeof(object));\n            Mock<IViewPageActivator> activator = new Mock<IViewPageActivator>(MockBehavior.Strict);\n\n            Mock<WebPage> layoutPage = new Mock<WebPage> { CallBase = true };\n            layoutPage.Setup(c => c.Execute()).Callback(() => layoutPage.Object.RenderBody());\n            Mock<IVirtualPathFactory> virtualPathFactory = new Mock<IVirtualPathFactory>(MockBehavior.Strict);\n            virtualPathFactory.Setup(f => f.Exists(\"~/layoutPath\")).Returns(true);\n            virtualPathFactory.Setup(f => f.CreateInstance(\"~/layoutPath\")).Returns(layoutPage.Object);\n            ControllerContext controllerContext = new ControllerContext();\n            activator.Setup(l => l.Create(controllerContext, typeof(object))).Returns(viewPage);\n            RazorView view = new RazorView(controllerContext, \"~/viewPath\", \"~/layoutPath\", false, Enumerable.Empty<string>(), activator.Object);\n            view.BuildManager = buildManager;\n            view.VirtualPathFactory = virtualPathFactory.Object;\n            view.DisplayModeProvider = DisplayModeProvider.Instance;\n\n            // Act\n            view.Render(viewContext.Object, TextWriter.Null);\n\n            // Assert\n            Assert.Equal(\"~/layoutPath\", viewPage.Layout);\n            Assert.Equal(\"~/layoutPath\", viewPage.OverridenLayoutPath);\n            Assert.Same(viewContext.Object, viewPage.ViewContext);\n            Assert.Equal(\"~/viewPath\", viewPage.VirtualPath);\n        }\n\n        public class StubWebViewPage : WebViewPage\n        {\n            public bool InitHelpersCalled;\n            public string ResultLayoutPage;\n            public string ResultOverridenLayoutPath;\n            public ViewContext ResultViewContext;\n            public string ResultVirtualPath;\n\n            public override void Execute()\n            {\n                ResultLayoutPage = Layout;\n                ResultOverridenLayoutPath = OverridenLayoutPath;\n                ResultViewContext = ViewContext;\n                ResultVirtualPath = VirtualPath;\n            }\n\n            public override void InitHelpers()\n            {\n                base.InitHelpers();\n                InitHelpersCalled = true;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ReaderWriterCacheTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ReaderWriterCacheTest\n    {\n        [Fact]\n        public void PublicFetchOrCreateItemCreatesItemIfNotAlreadyInCache()\n        {\n            // Arrange\n            ReaderWriterCacheHelper<int, string> helper = new ReaderWriterCacheHelper<int, string>();\n            Dictionary<int, string> cache = helper.PublicCache;\n\n            // Act\n            string item = helper.PublicFetchOrCreateItem(42, () => \"new\");\n\n            // Assert\n            Assert.Equal(\"new\", cache[42]);\n            Assert.Equal(\"new\", item);\n        }\n\n        [Fact]\n        public void PublicFetchOrCreateItemReturnsExistingItemIfFound()\n        {\n            // Arrange\n            ReaderWriterCacheHelper<int, string> helper = new ReaderWriterCacheHelper<int, string>();\n            Dictionary<int, string> cache = helper.PublicCache;\n            helper.PublicCache[42] = \"original\";\n\n            // Act\n            string item = helper.PublicFetchOrCreateItem(42, () => \"new\");\n\n            // Assert\n            Assert.Equal(\"original\", cache[42]);\n            Assert.Equal(\"original\", item);\n        }\n\n        [Fact]\n        public void PublicFetchOrCreateItemReturnsFirstItemIfTwoThreadsUpdateCacheSimultaneously()\n        {\n            // Arrange\n            ReaderWriterCacheHelper<int, string> helper = new ReaderWriterCacheHelper<int, string>();\n            Dictionary<int, string> cache = helper.PublicCache;\n            Func<string> creator = delegate()\n            {\n                // fake a second thread coming along when we weren't looking\n                string firstItem = helper.PublicFetchOrCreateItem(42, () => \"original\");\n\n                Assert.Equal(\"original\", cache[42]);\n                Assert.Equal(\"original\", firstItem);\n                return \"new\";\n            };\n\n            // Act\n            string secondItem = helper.PublicFetchOrCreateItem(42, creator);\n\n            // Assert\n            Assert.Equal(\"original\", cache[42]);\n            Assert.Equal(\"original\", secondItem);\n        }\n\n        [Fact]\n        public void PublicFetchOrCreateItemPassesArgument()\n        {\n            // Arrange\n            ReaderWriterCacheHelper<int, string> helper = new ReaderWriterCacheHelper<int, string>();\n            Dictionary<int, string> cache = helper.PublicCache;\n\n            // Act\n            string item = helper.PublicFetchOrCreateItem(42, (string argument) => argument, \"new\");\n\n            // Assert\n            Assert.Equal(\"new\", cache[42]);\n            Assert.Equal(\"new\", item);\n        }\n\n        private class ReaderWriterCacheHelper<TKey, TValue> : ReaderWriterCache<TKey, TValue>\n        {\n            public Dictionary<TKey, TValue> PublicCache\n            {\n                get { return Cache; }\n            }\n\n            public TValue PublicFetchOrCreateItem(TKey key, Func<TValue> creator)\n            {\n                return FetchOrCreateItem(key, creator);\n            }\n\n            public TValue PublicFetchOrCreateItem<TArgument>(TKey key, Func<TArgument, TValue> creator, TArgument state)\n            {\n                return FetchOrCreateItem(key, creator, state);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/RedirectResultTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc.Properties;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class RedirectResultTest\n    {\n        private static string _baseUrl = \"http://www.contoso.com/\";\n\n        [Fact]\n        public void ConstructorSetsUrl()\n        {\n            // Act\n            var result = new RedirectResult(_baseUrl);\n\n            // Assert\n            Assert.Same(_baseUrl, result.Url);\n            Assert.False(result.Permanent);\n        }\n\n        [Fact]\n        public void ConstructorSetsUrlAndPermanent()\n        {\n            // Act\n            var result = new RedirectResult(_baseUrl, permanent: true);\n\n            // Assert\n            Assert.Same(_baseUrl, result.Url);\n            Assert.True(result.Permanent);\n        }\n\n        [Fact]\n        public void ConstructorWithEmptyUrlThrows()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { new RedirectResult(String.Empty); },\n                \"url\");\n\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { new RedirectResult(String.Empty, true); },\n                \"url\");\n        }\n\n        [Fact]\n        public void ConstructorWithNullUrlThrows()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { new RedirectResult(url: null); },\n                \"url\");\n\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { new RedirectResult(url: null, permanent: true); },\n                \"url\");\n        }\n\n        [Fact]\n        public void ExecuteResultCallsResponseRedirect()\n        {\n            // Arrange\n            Mock<HttpResponseBase> mockResponse = new Mock<HttpResponseBase>();\n            mockResponse.Setup(o => o.Redirect(_baseUrl, false /* endResponse */)).Verifiable();\n            Mock<HttpContextBase> mockContext = new Mock<HttpContextBase>();\n            mockContext.Setup(o => o.Response).Returns(mockResponse.Object);\n            ControllerContext context = new ControllerContext(mockContext.Object, new RouteData(), new Mock<ControllerBase>().Object);\n            var result = new RedirectResult(_baseUrl);\n\n            // Act\n            result.ExecuteResult(context);\n\n            // Assert\n            mockResponse.Verify();\n        }\n\n        [Fact]\n        public void ExecuteResultWithPermanentCallsResponseRedirectPermanent()\n        {\n            // Arrange\n            Mock<HttpResponseBase> mockResponse = new Mock<HttpResponseBase>();\n            mockResponse.Setup(o => o.RedirectPermanent(_baseUrl, false /* endResponse */)).Verifiable();\n            Mock<HttpContextBase> mockContext = new Mock<HttpContextBase>();\n            mockContext.Setup(o => o.Response).Returns(mockResponse.Object);\n            ControllerContext context = new ControllerContext(mockContext.Object, new RouteData(), new Mock<ControllerBase>().Object);\n            var result = new RedirectResult(_baseUrl, permanent: true);\n\n            // Act\n            result.ExecuteResult(context);\n\n            // Assert\n            mockResponse.Verify();\n        }\n\n        [Fact]\n        public void ExecuteResultWithNullControllerContextThrows()\n        {\n            // Arrange\n            var result = new RedirectResult(_baseUrl);\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { result.ExecuteResult(null /* context */); },\n                \"context\");\n        }\n\n        [Fact]\n        public void RedirectInChildActionThrows()\n        {\n            // Arrange\n            RouteData routeData = new RouteData();\n            routeData.DataTokens[ControllerContext.ParentActionViewContextToken] = new ViewContext();\n            ControllerContext context = new ControllerContext(new Mock<HttpContextBase>().Object, routeData, new Mock<ControllerBase>().Object);\n            RedirectResult result = new RedirectResult(_baseUrl);\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => result.ExecuteResult(context),\n                MvcResources.RedirectAction_CannotRedirectInChildAction\n                );\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/RedirectToRouteResultTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class RedirectToRouteResultTest\n    {\n        [Fact]\n        public void ConstructorWithNullValuesDictionary()\n        {\n            // Act\n            var result = new RedirectToRouteResult(routeValues: null);\n\n            // Assert\n            Assert.NotNull(result.RouteValues);\n            Assert.Empty(result.RouteValues);\n            Assert.Equal(String.Empty, result.RouteName);\n            Assert.False(result.Permanent);\n        }\n\n        [Fact]\n        public void ConstructorSetsValuesDictionary()\n        {\n            // Arrange\n            RouteValueDictionary dict = new RouteValueDictionary();\n\n            // Act\n            var result = new RedirectToRouteResult(dict);\n\n            // Assert\n            Assert.Same(dict, result.RouteValues);\n            Assert.Equal(String.Empty, result.RouteName);\n            Assert.False(result.Permanent);\n        }\n\n        [Fact]\n        public void ConstructorSetsValuesDictionaryAndEmptyName()\n        {\n            // Arrange\n            RouteValueDictionary dict = new RouteValueDictionary();\n\n            // Act\n            var result = new RedirectToRouteResult(null, dict);\n\n            // Assert\n            Assert.Same(dict, result.RouteValues);\n            Assert.Equal(String.Empty, result.RouteName);\n            Assert.False(result.Permanent);\n        }\n\n        [Fact]\n        public void ConstructorSetsValuesDictionaryAndName()\n        {\n            // Arrange\n            RouteValueDictionary dict = new RouteValueDictionary();\n\n            // Act\n            var result = new RedirectToRouteResult(\"foo\", dict);\n\n            // Assert\n            Assert.Same(dict, result.RouteValues);\n            Assert.Equal(\"foo\", result.RouteName);\n            Assert.False(result.Permanent);\n        }\n\n        [Fact]\n        public void ConstructorSetsPermanent()\n        {\n            // Act\n            var result = new RedirectToRouteResult(null, null, true);\n\n            // Assert\n            Assert.True(result.Permanent);\n        }\n\n        [Fact]\n        public void ExecuteResultCallsResponseRedirect()\n        {\n            // Arrange\n            Mock<Controller> mockController = new Mock<Controller>();\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(c => c.HttpContext.Request.ApplicationPath).Returns(\"/somepath\");\n            mockControllerContext.Setup(c => c.HttpContext.Response.ApplyAppPathModifier(It.IsAny<string>())).Returns((string s) => s);\n            mockControllerContext.Setup(c => c.HttpContext.Response.Redirect(\"/somepath/c/a/i\", false)).Verifiable();\n            mockControllerContext.Setup(c => c.Controller).Returns(mockController.Object);\n\n            var values = new { Controller = \"c\", Action = \"a\", Id = \"i\" };\n            RedirectToRouteResult result = new RedirectToRouteResult(new RouteValueDictionary(values))\n            {\n                Routes = new RouteCollection() { new Route(\"{controller}/{action}/{id}\", null) },\n            };\n\n            // Act\n            result.ExecuteResult(mockControllerContext.Object);\n\n            // Assert\n            mockControllerContext.Verify();\n        }\n\n        [Fact]\n        public void ExecuteResultWithPermanentCallsResponseRedirectPermanent()\n        {\n            // Arrange\n            Mock<Controller> mockController = new Mock<Controller>();\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(c => c.HttpContext.Request.ApplicationPath).Returns(\"/somepath\");\n            mockControllerContext.Setup(c => c.HttpContext.Response.ApplyAppPathModifier(It.IsAny<string>())).Returns((string s) => s);\n            mockControllerContext.Setup(c => c.HttpContext.Response.RedirectPermanent(\"/somepath/c/a/i\", false)).Verifiable();\n            mockControllerContext.Setup(c => c.Controller).Returns(mockController.Object);\n\n            var values = new { Controller = \"c\", Action = \"a\", Id = \"i\" };\n            RedirectToRouteResult result = new RedirectToRouteResult(null, new RouteValueDictionary(values), permanent: true)\n            {\n                Routes = new RouteCollection() { new Route(\"{controller}/{action}/{id}\", null) },\n            };\n\n            // Act\n            result.ExecuteResult(mockControllerContext.Object);\n\n            // Assert\n            mockControllerContext.Verify();\n        }\n\n        [Fact]\n        public void ExecuteResultPreservesTempData()\n        {\n            // Arrange\n            TempDataDictionary tempData = new TempDataDictionary();\n            tempData[\"Foo\"] = \"Foo\";\n            tempData[\"Bar\"] = \"Bar\";\n            Mock<Controller> mockController = new Mock<Controller>() { CallBase = true };\n            mockController.Object.TempData = tempData;\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(c => c.HttpContext.Request.ApplicationPath).Returns(\"/somepath\");\n            mockControllerContext.Setup(c => c.HttpContext.Response.ApplyAppPathModifier(It.IsAny<string>())).Returns((string s) => s);\n            mockControllerContext.Setup(c => c.HttpContext.Response.Redirect(\"/somepath/c/a/i\", false)).Verifiable();\n            mockControllerContext.Setup(c => c.Controller).Returns(mockController.Object);\n\n            var values = new { Controller = \"c\", Action = \"a\", Id = \"i\" };\n            RedirectToRouteResult result = new RedirectToRouteResult(new RouteValueDictionary(values))\n            {\n                Routes = new RouteCollection() { new Route(\"{controller}/{action}/{id}\", null) },\n            };\n\n            // Act\n            object value = tempData[\"Foo\"];\n            result.ExecuteResult(mockControllerContext.Object);\n            mockController.Object.TempData.Save(mockControllerContext.Object, new Mock<ITempDataProvider>().Object);\n\n            // Assert\n            Assert.True(tempData.ContainsKey(\"Foo\"));\n            Assert.True(tempData.ContainsKey(\"Bar\"));\n        }\n\n        [Fact]\n        public void ExecuteResultThrowsIfVirtualPathDataIsNull()\n        {\n            // Arrange\n            var result = new RedirectToRouteResult(null)\n            {\n                Routes = new RouteCollection()\n            };\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { result.ExecuteResult(ControllerContextTest.CreateEmptyContext()); },\n                \"No route in the route table matches the supplied values.\");\n        }\n\n        [Fact]\n        public void ExecuteResultWithNullControllerContextThrows()\n        {\n            // Arrange\n            var result = new RedirectToRouteResult(null);\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { result.ExecuteResult(null /* context */); },\n                \"context\");\n        }\n\n        [Fact]\n        public void RoutesPropertyDefaultsToGlobalRouteTable()\n        {\n            // Act\n            var result = new RedirectToRouteResult(new RouteValueDictionary());\n\n            // Assert\n            Assert.Same(RouteTable.Routes, result.Routes);\n        }\n\n        [Fact]\n        public void RedirectInChildActionThrows()\n        {\n            // Arrange\n            RouteData routeData = new RouteData();\n            routeData.DataTokens[ControllerContext.ParentActionViewContextToken] = new ViewContext();\n            ControllerContext context = new ControllerContext(new Mock<HttpContextBase>().Object, routeData, new Mock<ControllerBase>().Object);\n            RedirectToRouteResult result = new RedirectToRouteResult(new RouteValueDictionary());\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => result.ExecuteResult(context),\n                \"Child actions are not allowed to perform redirect actions.\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ReflectedActionDescriptorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Reflection;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ReflectedActionDescriptorTest\n    {\n        private static readonly MethodInfo _int32EqualsIntMethod = typeof(int).GetMethod(\"Equals\", new Type[] { typeof(int) });\n\n        [Fact]\n        public void ConstructorSetsActionNameProperty()\n        {\n            // Arrange\n            string name = \"someName\";\n\n            // Act\n            ReflectedActionDescriptor ad = new ReflectedActionDescriptor(new Mock<MethodInfo>().Object, \"someName\", new Mock<ControllerDescriptor>().Object, false /* validateMethod */);\n\n            // Assert\n            Assert.Equal(name, ad.ActionName);\n        }\n\n        [Fact]\n        public void ConstructorSetsControllerDescriptorProperty()\n        {\n            // Arrange\n            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;\n\n            // Act\n            ReflectedActionDescriptor ad = new ReflectedActionDescriptor(new Mock<MethodInfo>().Object, \"someName\", cd, false /* validateMethod */);\n\n            // Assert\n            Assert.Same(cd, ad.ControllerDescriptor);\n        }\n\n        [Fact]\n        public void ConstructorSetsMethodInfoProperty()\n        {\n            // Arrange\n            MethodInfo methodInfo = new Mock<MethodInfo>().Object;\n\n            // Act\n            ReflectedActionDescriptor ad = new ReflectedActionDescriptor(methodInfo, \"someName\", new Mock<ControllerDescriptor>().Object, false /* validateMethod */);\n\n            // Assert\n            Assert.Same(methodInfo, ad.MethodInfo);\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfActionNameIsEmpty()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { new ReflectedActionDescriptor(new Mock<MethodInfo>().Object, \"\", new Mock<ControllerDescriptor>().Object); }, \"actionName\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfActionNameIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { new ReflectedActionDescriptor(new Mock<MethodInfo>().Object, null, new Mock<ControllerDescriptor>().Object); }, \"actionName\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfControllerDescriptorIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ReflectedActionDescriptor(new Mock<MethodInfo>().Object, \"someName\", null); }, \"controllerDescriptor\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfMethodInfoHasRefParameters()\n        {\n            // Arrange\n            MethodInfo methodInfo = typeof(MyController).GetMethod(\"MethodHasRefParameter\");\n\n            // Act & assert\n            Assert.Throws<ArgumentException>(\n                delegate { new ReflectedActionDescriptor(methodInfo, \"someName\", new Mock<ControllerDescriptor>().Object); },\n                \"Cannot call action method 'Void MethodHasRefParameter(Int32 ByRef)' on controller 'System.Web.Mvc.Test.ReflectedActionDescriptorTest+MyController' because the parameter 'Int32& i' is passed by reference.\" + Environment.NewLine\n              + \"Parameter name: methodInfo\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfMethodInfoHasOutParameters()\n        {\n            // Arrange\n            MethodInfo methodInfo = typeof(MyController).GetMethod(\"MethodHasOutParameter\");\n\n            // Act & assert\n            Assert.Throws<ArgumentException>(\n                delegate { new ReflectedActionDescriptor(methodInfo, \"someName\", new Mock<ControllerDescriptor>().Object); },\n                \"Cannot call action method 'Void MethodHasOutParameter(Int32 ByRef)' on controller 'System.Web.Mvc.Test.ReflectedActionDescriptorTest+MyController' because the parameter 'Int32& i' is passed by reference.\" + Environment.NewLine\n              + \"Parameter name: methodInfo\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfMethodInfoIsInstanceMethodOnNonControllerBaseType()\n        {\n            // Arrange\n            MethodInfo methodInfo = typeof(string).GetMethod(\"Clone\");\n\n            // Act & assert\n            Assert.Throws<ArgumentException>(\n                delegate { new ReflectedActionDescriptor(methodInfo, \"someName\", new Mock<ControllerDescriptor>().Object); },\n                \"Cannot create a descriptor for instance method 'System.Object Clone()' on type 'System.String' because the type does not derive from ControllerBase.\" + Environment.NewLine\n              + \"Parameter name: methodInfo\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfMethodIsStatic()\n        {\n            // Arrange\n            MethodInfo methodInfo = typeof(MyController).GetMethod(\"StaticMethod\");\n\n            // Act & assert\n            Assert.Throws<ArgumentException>(\n                delegate { new ReflectedActionDescriptor(methodInfo, \"someName\", new Mock<ControllerDescriptor>().Object); },\n                \"Cannot call action method 'Void StaticMethod()' on controller 'System.Web.Mvc.Test.ReflectedActionDescriptorTest+MyController' because the action method is a static method.\" + Environment.NewLine\n              + \"Parameter name: methodInfo\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfMethodInfoIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ReflectedActionDescriptor(null, \"someName\", new Mock<ControllerDescriptor>().Object); }, \"methodInfo\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfMethodInfoIsOpenGenericType()\n        {\n            // Arrange\n            MethodInfo methodInfo = typeof(MyController).GetMethod(\"OpenGenericMethod\");\n\n            // Act & assert\n            Assert.Throws<ArgumentException>(\n                delegate { new ReflectedActionDescriptor(methodInfo, \"someName\", new Mock<ControllerDescriptor>().Object); },\n                \"Cannot call action method 'Void OpenGenericMethod[T]()' on controller 'System.Web.Mvc.Test.ReflectedActionDescriptorTest+MyController' because the action method is a generic method.\" + Environment.NewLine\n              + \"Parameter name: methodInfo\");\n        }\n\n        [Fact]\n        public void ExecuteCallsMethodInfoOnSuccess()\n        {\n            // Arrange\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(c => c.Controller).Returns(new ConcatController());\n            Dictionary<string, object> parameters = new Dictionary<string, object>()\n            {\n                { \"a\", \"hello \" },\n                { \"b\", \"world\" }\n            };\n\n            ReflectedActionDescriptor ad = GetActionDescriptor(typeof(ConcatController).GetMethod(\"Concat\"));\n\n            // Act\n            object result = ad.Execute(mockControllerContext.Object, parameters);\n\n            // Assert\n            Assert.Equal(\"hello world\", result);\n        }\n\n        [Fact]\n        public void ExecuteThrowsIfControllerContextIsNull()\n        {\n            // Arrange\n            ReflectedActionDescriptor ad = GetActionDescriptor();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { ad.Execute(null, new Dictionary<string, object>()); }, \"controllerContext\");\n        }\n\n        [Fact]\n        public void ExecuteThrowsIfParametersContainsNullForNonNullableParameter()\n        {\n            // Arrange\n            ReflectedActionDescriptor ad = GetActionDescriptor(_int32EqualsIntMethod);\n            Dictionary<string, object> parameters = new Dictionary<string, object>() { { \"obj\", null } };\n\n            // Act & assert\n            Assert.Throws<ArgumentException>(\n                delegate { ad.Execute(new Mock<ControllerContext>().Object, parameters); },\n                \"The parameters dictionary contains a null entry for parameter 'obj' of non-nullable type 'System.Int32' for method 'Boolean Equals(Int32)' in 'System.Int32'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.\" + Environment.NewLine\n              + \"Parameter name: parameters\");\n        }\n\n        [Fact]\n        public void ExecuteThrowsIfParametersContainsValueOfWrongTypeForParameter()\n        {\n            // Arrange\n            ReflectedActionDescriptor ad = GetActionDescriptor(_int32EqualsIntMethod);\n            Dictionary<string, object> parameters = new Dictionary<string, object>() { { \"obj\", \"notAnInteger\" } };\n\n            // Act & assert\n            Assert.Throws<ArgumentException>(\n                delegate { ad.Execute(new Mock<ControllerContext>().Object, parameters); },\n                \"The parameters dictionary contains an invalid entry for parameter 'obj' for method 'Boolean Equals(Int32)' in 'System.Int32'. The dictionary contains a value of type 'System.String', but the parameter requires a value of type 'System.Int32'.\" + Environment.NewLine\n              + \"Parameter name: parameters\");\n        }\n\n        [Fact]\n        public void ExecuteThrowsIfParametersIsMissingAValue()\n        {\n            // Arrange\n            ReflectedActionDescriptor ad = GetActionDescriptor(_int32EqualsIntMethod);\n            Dictionary<string, object> parameters = new Dictionary<string, object>();\n\n            // Act & assert\n            Assert.Throws<ArgumentException>(\n                delegate { ad.Execute(new Mock<ControllerContext>().Object, parameters); },\n                \"The parameters dictionary does not contain an entry for parameter 'obj' of type 'System.Int32' for method 'Boolean Equals(Int32)' in 'System.Int32'. The dictionary must contain an entry for each parameter, including parameters that have null values.\" + Environment.NewLine\n              + \"Parameter name: parameters\");\n        }\n\n        [Fact]\n        public void ExecuteThrowsIfParametersIsNull()\n        {\n            // Arrange\n            ReflectedActionDescriptor ad = GetActionDescriptor();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { ad.Execute(new Mock<ControllerContext>().Object, null); }, \"parameters\");\n        }\n\n        [Fact]\n        public void GetCustomAttributesCallsMethodInfoGetCustomAttributes()\n        {\n            // Arrange\n            object[] expected = new object[0];\n            Mock<MethodInfo> mockMethod = new Mock<MethodInfo>();\n            mockMethod.Setup(mi => mi.GetCustomAttributes(true)).Returns(expected);\n            ReflectedActionDescriptor ad = GetActionDescriptor(mockMethod.Object);\n\n            // Act\n            object[] returned = ad.GetCustomAttributes(true);\n\n            // Assert\n            Assert.Same(expected, returned);\n        }\n\n        [Fact]\n        public void GetCustomAttributesWithAttributeTypeCallsMethodInfoGetCustomAttributes()\n        {\n            // Arrange\n            object[] expected = new object[0];\n            Mock<MethodInfo> mockMethod = new Mock<MethodInfo>();\n            mockMethod.Setup(mi => mi.GetCustomAttributes(typeof(ObsoleteAttribute), true)).Returns(expected);\n            ReflectedActionDescriptor ad = GetActionDescriptor(mockMethod.Object);\n\n            // Act\n            object[] returned = ad.GetCustomAttributes(typeof(ObsoleteAttribute), true);\n\n            // Assert\n            Assert.Same(expected, returned);\n        }\n\n        [Fact]\n        public void GetParametersWrapsParameterInfos()\n        {\n            // Arrange\n            ParameterInfo pInfo0 = typeof(ConcatController).GetMethod(\"Concat\").GetParameters()[0];\n            ParameterInfo pInfo1 = typeof(ConcatController).GetMethod(\"Concat\").GetParameters()[1];\n            ReflectedActionDescriptor ad = GetActionDescriptor(typeof(ConcatController).GetMethod(\"Concat\"));\n\n            // Act\n            ParameterDescriptor[] pDescsFirstCall = ad.GetParameters();\n            ParameterDescriptor[] pDescsSecondCall = ad.GetParameters();\n\n            // Assert\n            Assert.NotSame(pDescsFirstCall, pDescsSecondCall);\n            Assert.True(pDescsFirstCall.SequenceEqual(pDescsSecondCall));\n            Assert.Equal(2, pDescsFirstCall.Length);\n\n            ReflectedParameterDescriptor pDesc0 = pDescsFirstCall[0] as ReflectedParameterDescriptor;\n            ReflectedParameterDescriptor pDesc1 = pDescsFirstCall[1] as ReflectedParameterDescriptor;\n\n            Assert.NotNull(pDesc0);\n            Assert.Same(ad, pDesc0.ActionDescriptor);\n            Assert.Same(pInfo0, pDesc0.ParameterInfo);\n            Assert.NotNull(pDesc1);\n            Assert.Same(ad, pDesc1.ActionDescriptor);\n            Assert.Same(pInfo1, pDesc1.ParameterInfo);\n        }\n\n        [Fact]\n        public void GetSelectorsWrapsSelectorAttributes()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n            Mock<MethodInfo> mockMethod = new Mock<MethodInfo>();\n\n            Mock<ActionMethodSelectorAttribute> mockAttr = new Mock<ActionMethodSelectorAttribute>();\n            mockAttr.Setup(attr => attr.IsValidForRequest(controllerContext, mockMethod.Object)).Returns(true).Verifiable();\n            mockMethod.Setup(m => m.GetCustomAttributes(typeof(ActionMethodSelectorAttribute), true)).Returns(new ActionMethodSelectorAttribute[] { mockAttr.Object });\n\n            ReflectedActionDescriptor ad = GetActionDescriptor(mockMethod.Object);\n\n            // Act\n            ICollection<ActionSelector> selectors = ad.GetSelectors();\n            bool executedSuccessfully = selectors.All(s => s(controllerContext));\n\n            // Assert\n            Assert.Single(selectors);\n            Assert.True(executedSuccessfully);\n            mockAttr.Verify();\n        }\n\n        [Fact]\n        public void IsDefinedCallsMethodInfoIsDefined()\n        {\n            // Arrange\n            Mock<MethodInfo> mockMethod = new Mock<MethodInfo>();\n            mockMethod.Setup(mi => mi.IsDefined(typeof(ObsoleteAttribute), true)).Returns(true);\n            ReflectedActionDescriptor ad = GetActionDescriptor(mockMethod.Object);\n\n            // Act\n            bool isDefined = ad.IsDefined(typeof(ObsoleteAttribute), true);\n\n            // Assert\n            Assert.True(isDefined);\n        }\n\n        [Fact]\n        public void TryCreateDescriptorReturnsDescriptorOnSuccess()\n        {\n            // Arrange\n            MethodInfo methodInfo = typeof(MyController).GetMethod(\"GoodActionMethod\");\n            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;\n\n            // Act\n            ReflectedActionDescriptor ad = ReflectedActionDescriptor.TryCreateDescriptor(methodInfo, \"someName\", cd);\n\n            // Assert\n            Assert.NotNull(ad);\n            Assert.Same(methodInfo, ad.MethodInfo);\n            Assert.Equal(\"someName\", ad.ActionName);\n            Assert.Same(cd, ad.ControllerDescriptor);\n        }\n\n        [Fact]\n        public void TryCreateDescriptorReturnsNullOnFailure()\n        {\n            // Arrange\n            MethodInfo methodInfo = typeof(MyController).GetMethod(\"OpenGenericMethod\");\n            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;\n\n            // Act\n            ReflectedActionDescriptor ad = ReflectedActionDescriptor.TryCreateDescriptor(methodInfo, \"someName\", cd);\n\n            // Assert\n            Assert.Null(ad);\n        }\n\n        private static ReflectedActionDescriptor GetActionDescriptor()\n        {\n            return GetActionDescriptor(new Mock<MethodInfo>().Object);\n        }\n\n        private static ReflectedActionDescriptor GetActionDescriptor(MethodInfo methodInfo)\n        {\n            return new ReflectedActionDescriptor(methodInfo, \"someName\", new Mock<ControllerDescriptor>().Object, false /* validateMethod */)\n            {\n                DispatcherCache = new ActionMethodDispatcherCache()\n            };\n        }\n\n        private class ConcatController : Controller\n        {\n            public string Concat(string a, string b)\n            {\n                return a + b;\n            }\n        }\n\n        [OutputCache(VaryByParam = \"Class\")]\n        private class OverriddenAttributeController : Controller\n        {\n            [OutputCache(VaryByParam = \"Method\")]\n            public void SomeMethod()\n            {\n            }\n        }\n\n        [KeyedActionFilter(Key = \"BaseClass\", Order = 0)]\n        [KeyedAuthorizationFilter(Key = \"BaseClass\", Order = 0)]\n        [KeyedExceptionFilter(Key = \"BaseClass\", Order = 0)]\n        private class GetMemberChainController : Controller\n        {\n            [KeyedActionFilter(Key = \"BaseMethod\", Order = 0)]\n            [KeyedAuthorizationFilter(Key = \"BaseMethod\", Order = 0)]\n            public virtual void SomeVirtual()\n            {\n            }\n        }\n\n        [KeyedActionFilter(Key = \"DerivedClass\", Order = 1)]\n        private class GetMemberChainDerivedController : GetMemberChainController\n        {\n        }\n\n        [KeyedActionFilter(Key = \"SubderivedClass\", Order = 2)]\n        private class GetMemberChainSubderivedController : GetMemberChainDerivedController\n        {\n            [KeyedActionFilter(Key = \"SubderivedMethod\", Order = 2)]\n            public override void SomeVirtual()\n            {\n            }\n        }\n\n        private abstract class KeyedFilterAttribute : FilterAttribute\n        {\n            public string Key { get; set; }\n        }\n\n        [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]\n        private class KeyedAuthorizationFilterAttribute : KeyedFilterAttribute, IAuthorizationFilter\n        {\n            public void OnAuthorization(AuthorizationContext filterContext)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]\n        private class KeyedExceptionFilterAttribute : KeyedFilterAttribute, IExceptionFilter\n        {\n            public void OnException(ExceptionContext filterContext)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]\n        private class KeyedActionFilterAttribute : KeyedFilterAttribute, IActionFilter, IResultFilter\n        {\n            public void OnActionExecuting(ActionExecutingContext filterContext)\n            {\n                throw new NotImplementedException();\n            }\n\n            public void OnActionExecuted(ActionExecutedContext filterContext)\n            {\n                throw new NotImplementedException();\n            }\n\n            public void OnResultExecuting(ResultExecutingContext filterContext)\n            {\n                throw new NotImplementedException();\n            }\n\n            public void OnResultExecuted(ResultExecutedContext filterContext)\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class MyController : Controller\n        {\n            public void GoodActionMethod()\n            {\n            }\n\n            public static void StaticMethod()\n            {\n            }\n\n            public void OpenGenericMethod<T>()\n            {\n            }\n\n            public void MethodHasOutParameter(out int i)\n            {\n                i = 0;\n            }\n\n            public void MethodHasRefParameter(ref int i)\n            {\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ReflectedControllerDescriptorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Reflection;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ReflectedControllerDescriptorTest\n    {\n        [Fact]\n        public void ConstructorSetsControllerTypeProperty()\n        {\n            // Arrange\n            Type controllerType = typeof(string);\n\n            // Act\n            ReflectedControllerDescriptor cd = new ReflectedControllerDescriptor(controllerType);\n\n            // Assert\n            Assert.Same(controllerType, cd.ControllerType);\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfControllerTypeIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ReflectedControllerDescriptor(null); }, \"controllerType\");\n        }\n\n        [Fact]\n        public void FindActionReturnsActionDescriptorIfFound()\n        {\n            // Arrange\n            Type controllerType = typeof(MyController);\n            MethodInfo targetMethod = controllerType.GetMethod(\"AliasedMethod\");\n            ReflectedControllerDescriptor cd = new ReflectedControllerDescriptor(controllerType);\n\n            // Act\n            ActionDescriptor ad = cd.FindAction(new ControllerContext(), \"NewName\");\n\n            // Assert\n            Assert.Equal(\"NewName\", ad.ActionName);\n            ReflectedActionDescriptor actionDescriptor = Assert.IsType<ReflectedActionDescriptor>(ad);\n            Assert.Same(targetMethod, actionDescriptor.MethodInfo);\n            Assert.Same(cd, ad.ControllerDescriptor);\n        }\n\n        [Fact]\n        public void FindActionReturnsNullIfNoActionFound()\n        {\n            // Arrange\n            Type controllerType = typeof(MyController);\n            ReflectedControllerDescriptor cd = new ReflectedControllerDescriptor(controllerType);\n\n            // Act\n            ActionDescriptor ad = cd.FindAction(new ControllerContext(), \"NonExistent\");\n\n            // Assert\n            Assert.Null(ad);\n        }\n\n        [Fact]\n        public void FindActionThrowsIfActionNameIsEmpty()\n        {\n            // Arrange\n            Type controllerType = typeof(MyController);\n            ReflectedControllerDescriptor cd = new ReflectedControllerDescriptor(controllerType);\n\n            // Act & assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { cd.FindAction(new Mock<ControllerContext>().Object, \"\"); }, \"actionName\");\n        }\n\n        [Fact]\n        public void FindActionThrowsIfActionNameIsNull()\n        {\n            // Arrange\n            Type controllerType = typeof(MyController);\n            ReflectedControllerDescriptor cd = new ReflectedControllerDescriptor(controllerType);\n\n            // Act & assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { cd.FindAction(new Mock<ControllerContext>().Object, null); }, \"actionName\");\n        }\n\n        [Fact]\n        public void FindActionThrowsIfControllerContextIsNull()\n        {\n            // Arrange\n            Type controllerType = typeof(MyController);\n            ReflectedControllerDescriptor cd = new ReflectedControllerDescriptor(controllerType);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { cd.FindAction(null, \"someName\"); }, \"controllerContext\");\n        }\n\n        [Fact]\n        public void GetCanonicalActionsWrapsMethodInfos()\n        {\n            // Arrange\n            Type controllerType = typeof(MyController);\n            MethodInfo mInfo0 = controllerType.GetMethod(\"AliasedMethod\");\n            MethodInfo mInfo1 = controllerType.GetMethod(\"NonAliasedMethod\");\n            ReflectedControllerDescriptor cd = new ReflectedControllerDescriptor(controllerType);\n\n            // Act\n            ActionDescriptor[] aDescsFirstCall = cd.GetCanonicalActions();\n            ActionDescriptor[] aDescsSecondCall = cd.GetCanonicalActions();\n\n            // Assert\n            Assert.NotSame(aDescsFirstCall, aDescsSecondCall);\n            Assert.True(aDescsFirstCall.SequenceEqual(aDescsSecondCall));\n            Assert.Equal(2, aDescsFirstCall.Length);\n\n            ReflectedActionDescriptor aDesc0 = aDescsFirstCall[0] as ReflectedActionDescriptor;\n            ReflectedActionDescriptor aDesc1 = aDescsFirstCall[1] as ReflectedActionDescriptor;\n\n            Assert.NotNull(aDesc0);\n            Assert.Equal(\"AliasedMethod\", aDesc0.ActionName);\n            Assert.Same(mInfo0, aDesc0.MethodInfo);\n            Assert.Same(cd, aDesc0.ControllerDescriptor);\n            Assert.NotNull(aDesc1);\n            Assert.Equal(\"NonAliasedMethod\", aDesc1.ActionName);\n            Assert.Same(mInfo1, aDesc1.MethodInfo);\n            Assert.Same(cd, aDesc1.ControllerDescriptor);\n        }\n\n        [Fact]\n        public void GetCustomAttributesCallsTypeGetCustomAttributes()\n        {\n            // Arrange\n            object[] expected = new object[0];\n            Mock<Type> mockType = new Mock<Type>();\n            mockType.Setup(t => t.GetCustomAttributes(true)).Returns(expected);\n            ReflectedControllerDescriptor cd = new ReflectedControllerDescriptor(mockType.Object);\n\n            // Act\n            object[] returned = cd.GetCustomAttributes(true);\n\n            // Assert\n            Assert.Same(expected, returned);\n        }\n\n        [Fact]\n        public void GetCustomAttributesWithAttributeTypeCallsTypeGetCustomAttributes()\n        {\n            // Arrange\n            object[] expected = new object[0];\n            Mock<Type> mockType = new Mock<Type>();\n            mockType.Setup(t => t.GetCustomAttributes(typeof(ObsoleteAttribute), true)).Returns(expected);\n            ReflectedControllerDescriptor cd = new ReflectedControllerDescriptor(mockType.Object);\n\n            // Act\n            object[] returned = cd.GetCustomAttributes(typeof(ObsoleteAttribute), true);\n\n            // Assert\n            Assert.Same(expected, returned);\n        }\n\n        [Fact]\n        public void IsDefinedCallsTypeIsDefined()\n        {\n            // Arrange\n            Mock<Type> mockType = new Mock<Type>();\n            mockType.Setup(t => t.IsDefined(typeof(ObsoleteAttribute), true)).Returns(true);\n            ReflectedControllerDescriptor cd = new ReflectedControllerDescriptor(mockType.Object);\n\n            // Act\n            bool isDefined = cd.IsDefined(typeof(ObsoleteAttribute), true);\n\n            // Assert\n            Assert.True(isDefined);\n        }\n\n        private class MyController : Controller\n        {\n            [ActionName(\"NewName\")]\n            public void AliasedMethod()\n            {\n            }\n\n            public void NonAliasedMethod()\n            {\n            }\n\n            public void GenericMethod<T>()\n            {\n            }\n\n            private void PrivateMethod()\n            {\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ReflectedParameterBindingInfoTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Reflection;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ReflectedParameterBindingInfoTest\n    {\n        [Fact]\n        public void BinderProperty()\n        {\n            // Arrange\n            ParameterInfo pInfo = typeof(MyController).GetMethod(\"ParameterHasSingleModelBinderAttribute\").GetParameters()[0];\n            ReflectedParameterBindingInfo bindingInfo = new ReflectedParameterBindingInfo(pInfo);\n\n            // Act\n            IModelBinder binder = bindingInfo.Binder;\n\n            // Assert\n            Assert.IsType<MyModelBinder>(binder);\n        }\n\n        [Fact]\n        public void BinderPropertyThrowsIfMultipleBinderAttributesFound()\n        {\n            // Arrange\n            ParameterInfo pInfo = typeof(MyController).GetMethod(\"ParameterHasMultipleModelBinderAttributes\").GetParameters()[0];\n            ReflectedParameterBindingInfo bindingInfo = new ReflectedParameterBindingInfo(pInfo);\n\n            // Act & assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { IModelBinder binder = bindingInfo.Binder; },\n                \"The parameter 'p1' on method 'Void ParameterHasMultipleModelBinderAttributes(System.Object)' contains multiple attributes that inherit from CustomModelBinderAttribute.\");\n        }\n\n        [Fact]\n        public void ExcludeProperty()\n        {\n            // Arrange\n            ParameterInfo pInfo = typeof(MyController).GetMethod(\"ParameterHasBindAttribute\").GetParameters()[0];\n            ReflectedParameterBindingInfo bindingInfo = new ReflectedParameterBindingInfo(pInfo);\n\n            // Act\n            ICollection<string> excludes = bindingInfo.Exclude;\n\n            // Assert\n            Assert.IsType<ReadOnlyCollection<string>>(excludes);\n\n            string[] excludesArray = excludes.ToArray();\n            Assert.Equal(2, excludesArray.Length);\n            Assert.Equal(\"excl_a\", excludesArray[0]);\n            Assert.Equal(\"excl_b\", excludesArray[1]);\n        }\n\n        [Fact]\n        public void ExcludePropertyReturnsEmptyArrayIfNoBindAttributeSpecified()\n        {\n            // Arrange\n            ParameterInfo pInfo = typeof(MyController).GetMethod(\"ParameterHasNoBindAttributes\").GetParameters()[0];\n            ReflectedParameterBindingInfo bindingInfo = new ReflectedParameterBindingInfo(pInfo);\n\n            // Act\n            ICollection<string> excludes = bindingInfo.Exclude;\n\n            // Assert\n            Assert.NotNull(excludes);\n            Assert.Empty(excludes);\n        }\n\n        [Fact]\n        public void IncludeProperty()\n        {\n            // Arrange\n            ParameterInfo pInfo = typeof(MyController).GetMethod(\"ParameterHasBindAttribute\").GetParameters()[0];\n            ReflectedParameterBindingInfo bindingInfo = new ReflectedParameterBindingInfo(pInfo);\n\n            // Act\n            ICollection<string> includes = bindingInfo.Include;\n\n            // Assert\n            Assert.IsType<ReadOnlyCollection<string>>(includes);\n\n            string[] includesArray = includes.ToArray();\n            Assert.Equal(2, includesArray.Length);\n            Assert.Equal(\"incl_a\", includesArray[0]);\n            Assert.Equal(\"incl_b\", includesArray[1]);\n        }\n\n        [Fact]\n        public void IncludePropertyReturnsEmptyArrayIfNoBindAttributeSpecified()\n        {\n            // Arrange\n            ParameterInfo pInfo = typeof(MyController).GetMethod(\"ParameterHasNoBindAttributes\").GetParameters()[0];\n            ReflectedParameterBindingInfo bindingInfo = new ReflectedParameterBindingInfo(pInfo);\n\n            // Act\n            ICollection<string> includes = bindingInfo.Include;\n\n            // Assert\n            Assert.NotNull(includes);\n            Assert.Empty(includes);\n        }\n\n        [Fact]\n        public void PrefixProperty()\n        {\n            // Arrange\n            ParameterInfo pInfo = typeof(MyController).GetMethod(\"ParameterHasBindAttribute\").GetParameters()[0];\n            ReflectedParameterBindingInfo bindingInfo = new ReflectedParameterBindingInfo(pInfo);\n\n            // Act\n            string prefix = bindingInfo.Prefix;\n\n            // Assert\n            Assert.Equal(\"some prefix\", prefix);\n        }\n\n        [Fact]\n        public void PrefixPropertyReturnsNullIfNoBindAttributeSpecified()\n        {\n            // Arrange\n            ParameterInfo pInfo = typeof(MyController).GetMethod(\"ParameterHasNoBindAttributes\").GetParameters()[0];\n            ReflectedParameterBindingInfo bindingInfo = new ReflectedParameterBindingInfo(pInfo);\n\n            // Act\n            string prefix = bindingInfo.Prefix;\n\n            // Assert\n            Assert.Null(prefix);\n        }\n\n        private class MyController : Controller\n        {\n            public void ParameterHasBindAttribute(\n                [Bind(Prefix = \"some prefix\", Include = \"incl_a, incl_b\", Exclude = \"excl_a, excl_b\")] object p1)\n            {\n            }\n\n            public void ParameterHasNoBindAttributes(object p1)\n            {\n            }\n\n            public void ParameterHasSingleModelBinderAttribute([ModelBinder(typeof(MyModelBinder))] object p1)\n            {\n            }\n\n            public void ParameterHasMultipleModelBinderAttributes([MyCustomModelBinder, MyCustomModelBinder] object p1)\n            {\n            }\n        }\n\n        [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = true, Inherited = true)]\n        private class MyCustomModelBinderAttribute : CustomModelBinderAttribute\n        {\n            public override IModelBinder GetBinder()\n            {\n                throw new NotImplementedException();\n            }\n        }\n\n        private class MyModelBinder : IModelBinder\n        {\n            public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ReflectedParameterDescriptorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel;\nusing System.Reflection;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ReflectedParameterDescriptorTest\n    {\n        [Fact]\n        public void ConstructorSetsActionDescriptorProperty()\n        {\n            // Arrange\n            ParameterInfo pInfo = typeof(MyController).GetMethod(\"Foo\").GetParameters()[0];\n            ActionDescriptor ad = new Mock<ActionDescriptor>().Object;\n\n            // Act\n            ReflectedParameterDescriptor pd = new ReflectedParameterDescriptor(pInfo, ad);\n\n            // Assert\n            Assert.Same(ad, pd.ActionDescriptor);\n        }\n\n        [Fact]\n        public void ConstructorSetsParameterInfo()\n        {\n            // Arrange\n            ParameterInfo pInfo = typeof(MyController).GetMethod(\"Foo\").GetParameters()[0];\n\n            // Act\n            ReflectedParameterDescriptor pd = new ReflectedParameterDescriptor(pInfo, new Mock<ActionDescriptor>().Object);\n\n            // Assert\n            Assert.Same(pInfo, pd.ParameterInfo);\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfActionDescriptorIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ReflectedParameterDescriptor(new Mock<ParameterInfo>().Object, null); }, \"actionDescriptor\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfParameterInfoIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ReflectedParameterDescriptor(null, new Mock<ActionDescriptor>().Object); }, \"parameterInfo\");\n        }\n\n        [Fact]\n        public void DefaultValuePropertyDefaultsToNull()\n        {\n            // Arrange\n            ParameterInfo pInfo = typeof(MyController).GetMethod(\"DefaultValues\").GetParameters()[0]; // noDefaultValue\n\n            // Act\n            ReflectedParameterDescriptor pd = GetParameterDescriptor(pInfo);\n\n            // Assert\n            Assert.Null(pd.DefaultValue);\n        }\n\n        [Fact]\n        public void GetCustomAttributesCallsParameterInfoGetCustomAttributes()\n        {\n            // Arrange\n            object[] expected = new object[0];\n            Mock<ParameterInfo> mockParameter = new Mock<ParameterInfo>();\n            mockParameter.Setup(pi => pi.Member).Returns(new Mock<MemberInfo>().Object);\n            mockParameter.Setup(pi => pi.GetCustomAttributes(true)).Returns(expected);\n            ReflectedParameterDescriptor pd = GetParameterDescriptor(mockParameter.Object);\n\n            // Act\n            object[] returned = pd.GetCustomAttributes(true);\n\n            // Assert\n            Assert.Same(expected, returned);\n        }\n\n        [Fact]\n        public void GetCustomAttributesWithAttributeTypeCallsParameterInfoGetCustomAttributes()\n        {\n            // Arrange\n            object[] expected = new object[0];\n            Mock<ParameterInfo> mockParameter = new Mock<ParameterInfo>();\n            mockParameter.Setup(pi => pi.Member).Returns(new Mock<MemberInfo>().Object);\n            mockParameter.Setup(pi => pi.GetCustomAttributes(typeof(ObsoleteAttribute), true)).Returns(expected);\n            ReflectedParameterDescriptor pd = GetParameterDescriptor(mockParameter.Object);\n\n            // Act\n            object[] returned = pd.GetCustomAttributes(typeof(ObsoleteAttribute), true);\n\n            // Assert\n            Assert.Same(expected, returned);\n        }\n\n        [Fact]\n        public void IsDefinedCallsParameterInfoIsDefined()\n        {\n            // Arrange\n            Mock<ParameterInfo> mockParameter = new Mock<ParameterInfo>();\n            mockParameter.Setup(pi => pi.Member).Returns(new Mock<MemberInfo>().Object);\n            mockParameter.Setup(pi => pi.IsDefined(typeof(ObsoleteAttribute), true)).Returns(true);\n            ReflectedParameterDescriptor pd = GetParameterDescriptor(mockParameter.Object);\n\n            // Act\n            bool isDefined = pd.IsDefined(typeof(ObsoleteAttribute), true);\n\n            // Assert\n            Assert.True(isDefined);\n        }\n\n        [Fact]\n        public void ParameterNameProperty()\n        {\n            // Arrange\n            ParameterInfo pInfo = typeof(MyController).GetMethod(\"Foo\").GetParameters()[0];\n\n            // Act\n            ReflectedParameterDescriptor pd = GetParameterDescriptor(pInfo);\n\n            // Assert\n            Assert.Equal(\"s1\", pd.ParameterName);\n        }\n\n        [Fact]\n        public void ParameterTypeProperty()\n        {\n            // Arrange\n            ParameterInfo pInfo = typeof(MyController).GetMethod(\"Foo\").GetParameters()[0];\n\n            // Act\n            ReflectedParameterDescriptor pd = GetParameterDescriptor(pInfo);\n\n            // Assert\n            Assert.Equal(typeof(string), pd.ParameterType);\n        }\n\n        private static ReflectedParameterDescriptor GetParameterDescriptor(ParameterInfo parameterInfo)\n        {\n            return new ReflectedParameterDescriptor(parameterInfo, new Mock<ActionDescriptor>().Object);\n        }\n\n        private class MyController : Controller\n        {\n            public void Foo(string s1)\n            {\n            }\n\n            public void DefaultValues(string noDefaultValue, [DefaultValue(\"someValue\")] string hasDefaultValue)\n            {\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/RegularExpressionAttributeAdapterTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")] // Uses ModelMetadataProviders.Current\n    public class RegularExpressionAttributeAdapterTest\n    {\n        [Fact]\n        [ReplaceCulture]\n        public void ClientRulesWithRegexAttribute()\n        {\n            // Arrange\n            var metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => null, typeof(string), \"Length\");\n            var context = new ControllerContext();\n            var attribute = new RegularExpressionAttribute(\"the_pattern\");\n            var adapter = new RegularExpressionAttributeAdapter(metadata, context, attribute);\n\n            // Act\n            var rules = adapter.GetClientValidationRules()\n                .OrderBy(r => r.ValidationType)\n                .ToArray();\n\n            // Assert\n            ModelClientValidationRule rule = Assert.Single(rules);\n            Assert.Equal(\"regex\", rule.ValidationType);\n            Assert.Single(rule.ValidationParameters);\n            Assert.Equal(\"the_pattern\", rule.ValidationParameters[\"pattern\"]);\n            Assert.Equal(@\"The field Length must match the regular expression 'the_pattern'.\", rule.ErrorMessage);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/RemoteAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")] // Uses ModelMetadataProviders.Current\n    public class RemoteAttributeTest\n    {\n        // Good route name, bad route name\n        // Controller + Action\n\n        [Fact]\n        public void GuardClauses()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => new RemoteAttribute(null, \"controller\"),\n                \"action\");\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => new RemoteAttribute(\"action\", null),\n                \"controller\");\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => new RemoteAttribute(null),\n                \"routeName\");\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => RemoteAttribute.FormatPropertyForClientValidation(String.Empty),\n                \"property\");\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => new RemoteAttribute(\"foo\").FormatAdditionalFieldsForClientValidation(String.Empty),\n                \"property\");\n        }\n\n        [Fact]\n        public void IsValidAlwaysReturnsTrue()\n        {\n            // Act & Assert\n            Assert.True(new RemoteAttribute(\"RouteName\", \"ParameterName\").IsValid(null));\n            Assert.True(new RemoteAttribute(\"ActionName\", \"ControllerName\", \"ParameterName\").IsValid(null));\n        }\n\n        [Fact]\n        public void BadRouteNameThrows()\n        {\n            // Arrange\n            ControllerContext context = new ControllerContext();\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(object));\n            TestableRemoteAttribute attribute = new TestableRemoteAttribute(\"RouteName\");\n\n            // Act & Assert\n            Assert.Throws<ArgumentException>(\n                () => new List<ModelClientValidationRule>(attribute.GetClientValidationRules(metadata, context)),\n                \"A route named 'RouteName' could not be found in the route collection.\\r\\nParameter name: name\");\n        }\n\n        [Fact]\n        public void NoRouteWithActionControllerThrows()\n        {\n            // Arrange\n            ControllerContext context = new ControllerContext();\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(null, typeof(string), \"Length\");\n            TestableRemoteAttribute attribute = new TestableRemoteAttribute(\"Action\", \"Controller\");\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => new List<ModelClientValidationRule>(attribute.GetClientValidationRules(metadata, context)),\n                \"No url for remote validation could be found.\");\n        }\n\n        [Fact]\n        public void GoodRouteNameReturnsCorrectClientData()\n        {\n            // Arrange\n            string url = null;\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(null, typeof(string), \"Length\");\n            TestableRemoteAttribute attribute = new TestableRemoteAttribute(\"RouteName\");\n            attribute.RouteTable.Add(\"RouteName\", new Route(\"my/url\", new MvcRouteHandler()));\n\n            // Act\n            ModelClientValidationRule rule = attribute.GetClientValidationRules(metadata, GetMockControllerContext(url)).Single();\n\n            // Assert\n            Assert.Equal(\"remote\", rule.ValidationType);\n            Assert.Equal(\"'Length' is invalid.\", rule.ErrorMessage);\n            Assert.Equal(2, rule.ValidationParameters.Count);\n            Assert.Equal(\"/my/url\", rule.ValidationParameters[\"url\"]);\n        }\n\n        [Fact]\n        public void ActionControllerReturnsCorrectClientDataWithoutNamedParameters()\n        {\n            // Arrange\n            string url = null;\n\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(null, typeof(string), \"Length\");\n            TestableRemoteAttribute attribute = new TestableRemoteAttribute(\"Action\", \"Controller\");\n            attribute.RouteTable.Add(new Route(\"{controller}/{action}\", new MvcRouteHandler()));\n\n            // Act\n            ModelClientValidationRule rule = attribute.GetClientValidationRules(metadata, GetMockControllerContext(url)).Single();\n\n            // Assert\n            Assert.Equal(\"remote\", rule.ValidationType);\n            Assert.Equal(\"'Length' is invalid.\", rule.ErrorMessage);\n            Assert.Equal(2, rule.ValidationParameters.Count);\n            Assert.Equal(\"/Controller/Action\", rule.ValidationParameters[\"url\"]);\n            Assert.Equal(\"*.Length\", rule.ValidationParameters[\"additionalfields\"]);\n            Assert.Throws<KeyNotFoundException>(\n                () => rule.ValidationParameters[\"type\"],\n                \"The given key was not present in the dictionary.\");\n        }\n\n        [Fact]\n        public void ActionControllerReturnsCorrectClientDataWithNamedParameters()\n        {\n            // Arrange\n            string url = null;\n\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(null, typeof(string), \"Length\");\n            TestableRemoteAttribute attribute = new TestableRemoteAttribute(\"Action\", \"Controller\");\n            attribute.HttpMethod = \"POST\";\n            attribute.AdditionalFields = \"Password,ConfirmPassword\";\n\n            attribute.RouteTable.Add(new Route(\"{controller}/{action}\", new MvcRouteHandler()));\n\n            // Act\n            ModelClientValidationRule rule = attribute.GetClientValidationRules(metadata, GetMockControllerContext(url)).Single();\n\n            // Assert\n            Assert.Equal(\"remote\", rule.ValidationType);\n            Assert.Equal(\"'Length' is invalid.\", rule.ErrorMessage);\n            Assert.Equal(3, rule.ValidationParameters.Count);\n            Assert.Equal(\"/Controller/Action\", rule.ValidationParameters[\"url\"]);\n            Assert.Equal(\"*.Length,*.Password,*.ConfirmPassword\", rule.ValidationParameters[\"additionalfields\"]);\n            Assert.Equal(\"POST\", rule.ValidationParameters[\"type\"]);\n        }\n\n        // Current area is root in this case.\n        [Fact]\n        public void ActionController_RemoteFindsControllerInCurrentArea()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(modelAccessor: null,\n                containerType: typeof(string), propertyName: \"Length\");\n            TestableRemoteAttribute attribute = new TestableRemoteAttribute(\"Action\", \"Controller\");\n            attribute.HttpMethod = \"POST\";\n\n            var context = new AreaRegistrationContext(\"Test\", attribute.RouteTable);\n            context.MapRoute(name: null, url: \"Test/{controller}/{action}\");\n\n            attribute.RouteTable.Add(new Route(\"{controller}/{action}\", new MvcRouteHandler()));\n\n            // Act\n            ModelClientValidationRule rule =\n                attribute.GetClientValidationRules(metadata, GetMockControllerContext(url: null)).Single();\n\n            // Assert\n            Assert.Equal(\"remote\", rule.ValidationType);\n            Assert.Equal(\"/Controller/Action\", rule.ValidationParameters[\"url\"]);\n        }\n\n        [Fact]\n        public void ActionControllerArea_RemoteFindsControllerInNamedArea()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(modelAccessor: null,\n                containerType: typeof(string), propertyName: \"Length\");\n            TestableRemoteAttribute attribute = new TestableRemoteAttribute(\"Action\", \"Controller\", \"Test\");\n            attribute.HttpMethod = \"POST\";\n\n            var context = new AreaRegistrationContext(\"Test\", attribute.RouteTable);\n            context.MapRoute(name: null, url: \"Test/{controller}/{action}\");\n\n            attribute.RouteTable.Add(new Route(\"{controller}/{action}\", new MvcRouteHandler()));\n\n            // Act\n            ModelClientValidationRule rule =\n                attribute.GetClientValidationRules(metadata, GetMockControllerContext(url: null)).Single();\n\n            // Assert\n            Assert.Equal(\"remote\", rule.ValidationType);\n            Assert.Equal(\"/Test/Controller/Action\", rule.ValidationParameters[\"url\"]);\n        }\n\n        // Current area is root in this case.\n        [Fact]\n        public void ActionControllerArea_WithEmptyArea_RemoteFindsControllerInCurrentArea()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(modelAccessor: null,\n                containerType: typeof(string), propertyName: \"Length\");\n            TestableRemoteAttribute attribute = new TestableRemoteAttribute(\"Action\", \"Controller\", \"\");\n            attribute.HttpMethod = \"POST\";\n\n            var context = new AreaRegistrationContext(\"Test\", attribute.RouteTable);\n            context.MapRoute(name: null, url: \"Test/{controller}/{action}\");\n\n            attribute.RouteTable.Add(new Route(\"{controller}/{action}\", new MvcRouteHandler()));\n\n            // Act\n            ModelClientValidationRule rule =\n                attribute.GetClientValidationRules(metadata, GetMockControllerContext(url: null)).Single();\n\n            // Assert\n            Assert.Equal(\"remote\", rule.ValidationType);\n            Assert.Equal(\"/Controller/Action\", rule.ValidationParameters[\"url\"]);\n        }\n\n        // Current area is root in this case.\n        [Fact]\n        public void ActionControllerAreaReference_WithUseCurrent_RemoteFindsControllerInCurrentArea()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(modelAccessor: null,\n                containerType: typeof(string), propertyName: \"Length\");\n            TestableRemoteAttribute attribute = new TestableRemoteAttribute(\"Action\", \"Controller\", AreaReference.UseCurrent);\n            attribute.HttpMethod = \"POST\";\n\n            var context = new AreaRegistrationContext(\"Test\", attribute.RouteTable);\n            context.MapRoute(name: null, url: \"Test/{controller}/{action}\");\n\n            attribute.RouteTable.Add(new Route(\"{controller}/{action}\", new MvcRouteHandler()));\n\n            // Act\n            ModelClientValidationRule rule =\n                attribute.GetClientValidationRules(metadata, GetMockControllerContext(url: null)).Single();\n\n            // Assert\n            Assert.Equal(\"remote\", rule.ValidationType);\n            Assert.Equal(\"/Controller/Action\", rule.ValidationParameters[\"url\"]);\n        }\n\n        [Fact]\n        public void ActionControllerAreaReference_WithUseRoot_RemoteFindsControllerInRoot()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(modelAccessor: null,\n                containerType: typeof(string), propertyName: \"Length\");\n            TestableRemoteAttribute attribute = new TestableRemoteAttribute(\"Action\", \"Controller\", AreaReference.UseRoot);\n            attribute.HttpMethod = \"POST\";\n\n            var context = new AreaRegistrationContext(\"Test\", attribute.RouteTable);\n            context.MapRoute(name: null, url: \"Test/{controller}/{action}\");\n\n            attribute.RouteTable.Add(new Route(\"{controller}/{action}\", new MvcRouteHandler()));\n\n            // Act\n            ModelClientValidationRule rule =\n                attribute.GetClientValidationRules(metadata, GetMockControllerContext(url: null)).Single();\n\n            // Assert\n            Assert.Equal(\"remote\", rule.ValidationType);\n            Assert.Equal(\"/Controller/Action\", rule.ValidationParameters[\"url\"]);\n        }\n\n        // Current area is Test in this case.\n        [Fact]\n        public void ActionController_InArea_RemoteFindsControllerInCurrentArea()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(modelAccessor: null,\n                containerType: typeof(string), propertyName: \"Length\");\n            TestableRemoteAttribute attribute = new TestableRemoteAttribute(\"Action\", \"Controller\");\n            attribute.HttpMethod = \"POST\";\n\n            var context = new AreaRegistrationContext(\"Test\", attribute.RouteTable);\n            context.MapRoute(name: null, url: \"Test/{controller}/{action}\");\n\n            attribute.RouteTable.Add(new Route(\"{controller}/{action}\", new MvcRouteHandler()));\n\n            // Act\n            ModelClientValidationRule rule =\n                attribute.GetClientValidationRules(metadata, GetMockControllerContextWithArea(url: null, areaName: \"Test\"))\n                .Single();\n\n            // Assert\n            Assert.Equal(\"remote\", rule.ValidationType);\n            Assert.Equal(\"/Test/Controller/Action\", rule.ValidationParameters[\"url\"]);\n        }\n\n        // Explicit reference to the Test area.\n        [Fact]\n        public void ActionControllerArea_InSameArea_RemoteFindsControllerInNamedArea()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(modelAccessor: null,\n                containerType: typeof(string), propertyName: \"Length\");\n            TestableRemoteAttribute attribute = new TestableRemoteAttribute(\"Action\", \"Controller\", \"Test\");\n            attribute.HttpMethod = \"POST\";\n\n            var context = new AreaRegistrationContext(\"Test\", attribute.RouteTable);\n            context.MapRoute(name: null, url: \"Test/{controller}/{action}\");\n\n            attribute.RouteTable.Add(new Route(\"{controller}/{action}\", new MvcRouteHandler()));\n\n            // Act\n            ModelClientValidationRule rule =\n                attribute.GetClientValidationRules(metadata, GetMockControllerContextWithArea(url: null, areaName: \"Test\"))\n                .Single();\n\n            // Assert\n            Assert.Equal(\"remote\", rule.ValidationType);\n            Assert.Equal(\"/Test/Controller/Action\", rule.ValidationParameters[\"url\"]);\n        }\n\n        [Fact]\n        public void ActionControllerArea_InArea_RemoteFindsControllerInNamedArea()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(modelAccessor: null,\n                containerType: typeof(string), propertyName: \"Length\");\n            TestableRemoteAttribute attribute = new TestableRemoteAttribute(\"Action\", \"Controller\", \"AnotherArea\");\n            attribute.HttpMethod = \"POST\";\n\n            var context = new AreaRegistrationContext(\"Test\", attribute.RouteTable);\n            context.MapRoute(name: null, url: \"Test/{controller}/{action}\");\n            context = new AreaRegistrationContext(\"AnotherArea\", attribute.RouteTable);\n            context.MapRoute(name: null, url: \"AnotherArea/{controller}/{action}\");\n\n            attribute.RouteTable.Add(new Route(\"{controller}/{action}\", new MvcRouteHandler()));\n\n            // Act\n            ModelClientValidationRule rule =\n                attribute.GetClientValidationRules(metadata, GetMockControllerContextWithArea(url: null, areaName: \"Test\"))\n                .Single();\n\n            // Assert\n            Assert.Equal(\"remote\", rule.ValidationType);\n            Assert.Equal(\"/AnotherArea/Controller/Action\", rule.ValidationParameters[\"url\"]);\n        }\n\n        // Current area is Test in this case.\n        [Fact]\n        public void ActionControllerArea_WithEmptyAreaInArea_RemoteFindsControllerInCurrentArea()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(modelAccessor: null,\n                containerType: typeof(string), propertyName: \"Length\");\n            TestableRemoteAttribute attribute = new TestableRemoteAttribute(\"Action\", \"Controller\", \"\");\n            attribute.HttpMethod = \"POST\";\n\n            var context = new AreaRegistrationContext(\"Test\", attribute.RouteTable);\n            context.MapRoute(name: null, url: \"Test/{controller}/{action}\");\n\n            attribute.RouteTable.Add(new Route(\"{controller}/{action}\", new MvcRouteHandler()));\n\n            // Act\n            ModelClientValidationRule rule =\n                attribute.GetClientValidationRules(metadata, GetMockControllerContextWithArea(url: null, areaName: \"Test\"))\n                .Single();\n\n            // Assert\n            Assert.Equal(\"remote\", rule.ValidationType);\n            Assert.Equal(\"/Test/Controller/Action\", rule.ValidationParameters[\"url\"]);\n        }\n\n        // Current area is Test in this case.\n        [Fact]\n        public void ActionControllerAreaReference_WithUseCurrentInArea_RemoteFindsControllerInCurrentArea()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(modelAccessor: null,\n                containerType: typeof(string), propertyName: \"Length\");\n            TestableRemoteAttribute attribute = new TestableRemoteAttribute(\"Action\", \"Controller\", AreaReference.UseCurrent);\n            attribute.HttpMethod = \"POST\";\n\n            var context = new AreaRegistrationContext(\"Test\", attribute.RouteTable);\n            context.MapRoute(name: null, url: \"Test/{controller}/{action}\");\n\n            attribute.RouteTable.Add(new Route(\"{controller}/{action}\", new MvcRouteHandler()));\n\n            // Act\n            ModelClientValidationRule rule =\n                attribute.GetClientValidationRules(metadata, GetMockControllerContextWithArea(url: null, areaName: \"Test\"))\n                .Single();\n\n            // Assert\n            Assert.Equal(\"remote\", rule.ValidationType);\n            Assert.Equal(\"/Test/Controller/Action\", rule.ValidationParameters[\"url\"]);\n        }\n\n        [Fact]\n        public void ActionControllerAreaReference_WithUseRootInArea_RemoteFindsControllerInRoot()\n        {\n            // Arrange\n            ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForProperty(modelAccessor: null,\n                containerType: typeof(string), propertyName: \"Length\");\n            TestableRemoteAttribute attribute = new TestableRemoteAttribute(\"Action\", \"Controller\", AreaReference.UseRoot);\n            attribute.HttpMethod = \"POST\";\n\n            var context = new AreaRegistrationContext(\"Test\", attribute.RouteTable);\n            context.MapRoute(name: null, url: \"Test/{controller}/{action}\");\n\n            attribute.RouteTable.Add(new Route(\"{controller}/{action}\", new MvcRouteHandler()));\n\n            // Act\n            ModelClientValidationRule rule =\n                attribute.GetClientValidationRules(metadata, GetMockControllerContextWithArea(url: null, areaName: \"Test\"))\n                .Single();\n\n            // Assert\n            Assert.Equal(\"remote\", rule.ValidationType);\n            Assert.Equal(\"/Controller/Action\", rule.ValidationParameters[\"url\"]);\n        }\n\n        private ControllerContext GetMockControllerContext(string url)\n        {\n            Mock<ControllerContext> context = new Mock<ControllerContext>();\n            context.Setup(c => c.HttpContext.Request.ApplicationPath)\n                .Returns(\"/\");\n            context.Setup(c => c.HttpContext.Response.ApplyAppPathModifier(It.IsAny<string>()))\n                .Callback<string>(vpath => url = vpath)\n                .Returns(() => url);\n\n            return context.Object;\n        }\n\n        private ControllerContext GetMockControllerContextWithArea(string url, string areaName)\n        {\n            Mock<ControllerContext> context = new Mock<ControllerContext>();\n            context.Setup(c => c.HttpContext.Request.ApplicationPath)\n                .Returns(\"/\");\n            context.Setup(c => c.HttpContext.Response.ApplyAppPathModifier(It.IsAny<string>()))\n                .Callback<string>(vpath => url = vpath)\n                .Returns(() => url);\n\n            var controllerContext = context.Object;\n\n            controllerContext.RequestContext.RouteData.DataTokens.Add(\"area\", areaName);\n\n            return controllerContext;\n        }\n\n        private class TestableRemoteAttribute : RemoteAttribute\n        {\n            public RouteCollection RouteTable = new RouteCollection();\n\n            public TestableRemoteAttribute(string action, string controller, AreaReference areaReference)\n                : base(action, controller, areaReference)\n            {\n            }\n\n            public TestableRemoteAttribute(string action, string controller, string areaName)\n                : base(action, controller, areaName)\n            {\n            }\n\n            public TestableRemoteAttribute(string action, string controller)\n                : base(action, controller)\n            {\n            }\n\n            public TestableRemoteAttribute(string routeName)\n                : base(routeName)\n            {\n            }\n\n            protected override RouteCollection Routes\n            {\n                get { return RouteTable; }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/RequireHttpsAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class RequireHttpsAttributeTest\n    {\n        [Fact]\n        public void HandleNonHttpsRequestExtensibility()\n        {\n            // Arrange\n            Mock<AuthorizationContext> mockAuthContext = new Mock<AuthorizationContext>();\n            mockAuthContext.Setup(c => c.HttpContext.Request.IsSecureConnection).Returns(false);\n            AuthorizationContext authContext = mockAuthContext.Object;\n\n            RequireHttpsAttribute attr = new MyRequireHttpsAttribute();\n\n            // Act\n            attr.OnAuthorization(authContext);\n            ContentResult result = authContext.Result as ContentResult;\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Equal(\"Custom HandleNonHttpsRequest\", result.Content);\n        }\n\n        [Fact]\n        public void OnAuthorizationDoesNothingIfRequestIsSecure()\n        {\n            // Arrange\n            Mock<AuthorizationContext> mockAuthContext = new Mock<AuthorizationContext>();\n            mockAuthContext.Setup(c => c.HttpContext.Request.IsSecureConnection).Returns(true);\n            AuthorizationContext authContext = mockAuthContext.Object;\n\n            ViewResult result = new ViewResult();\n            authContext.Result = result;\n\n            RequireHttpsAttribute attr = new RequireHttpsAttribute();\n\n            // Act\n            attr.OnAuthorization(authContext);\n\n            // Assert\n            Assert.Same(result, authContext.Result);\n        }\n\n        [Fact]\n        public void OnAuthorizationRedirectsIfRequestIsNotSecureAndMethodIsGet()\n        {\n            // Arrange\n            Mock<AuthorizationContext> mockAuthContext = new Mock<AuthorizationContext>();\n            mockAuthContext.Setup(c => c.HttpContext.Request.HttpMethod).Returns(\"get\");\n            mockAuthContext.Setup(c => c.HttpContext.Request.IsSecureConnection).Returns(false);\n            mockAuthContext.Setup(c => c.HttpContext.Request.RawUrl).Returns(\"/alpha/bravo/charlie?q=quux\");\n            mockAuthContext.Setup(c => c.HttpContext.Request.Url).Returns(new Uri(\"http://www.example.com:8080/foo/bar/baz\"));\n            AuthorizationContext authContext = mockAuthContext.Object;\n\n            RequireHttpsAttribute attr = new RequireHttpsAttribute();\n\n            // Act\n            attr.OnAuthorization(authContext);\n            RedirectResult result = authContext.Result as RedirectResult;\n\n            // Assert\n            Assert.False(attr.Permanent);\n            Assert.NotNull(result);\n            Assert.Equal(\"https://www.example.com/alpha/bravo/charlie?q=quux\", result.Url);\n            Assert.False(result.Permanent);\n        }\n\n        [Theory]\n        [InlineData(false)]\n        [InlineData(true)]\n        public void OnAuthorizationRedirectsIfPermanentConstructorParameterIsAndRequestIsNotSecureAndMethodIsGet(bool permanent)\n        {\n            // Arrange\n            Mock<AuthorizationContext> mockAuthContext = new Mock<AuthorizationContext>();\n            mockAuthContext.Setup(c => c.HttpContext.Request.HttpMethod).Returns(\"get\");\n            mockAuthContext.Setup(c => c.HttpContext.Request.IsSecureConnection).Returns(false);\n            mockAuthContext.Setup(c => c.HttpContext.Request.RawUrl).Returns(\"/alpha/bravo/charlie?q=quux\");\n            mockAuthContext.Setup(c => c.HttpContext.Request.Url).Returns(new Uri(\"http://www.example.com:8080/foo/bar/baz\"));\n            AuthorizationContext authContext = mockAuthContext.Object;\n\n            RequireHttpsAttribute attr = new RequireHttpsAttribute(permanent);\n\n            // Act\n            attr.OnAuthorization(authContext);\n            RedirectResult result = authContext.Result as RedirectResult;\n\n            // Assert\n            Assert.Equal(permanent, attr.Permanent);\n            Assert.NotNull(result);\n            Assert.Equal(\"https://www.example.com/alpha/bravo/charlie?q=quux\", result.Url);\n            Assert.Equal(permanent, result.Permanent);\n        }\n\n        [Fact]\n        public void OnAuthorizationThrowsIfFilterContextIsNull()\n        {\n            // Arrange\n            RequireHttpsAttribute attr = new RequireHttpsAttribute();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { attr.OnAuthorization(null); }, \"filterContext\");\n        }\n\n        [Fact]\n        public void OnAuthorizationThrowsIfRequestIsNotSecureAndMethodIsNotGet()\n        {\n            // Arrange\n            Mock<AuthorizationContext> mockAuthContext = new Mock<AuthorizationContext>();\n            mockAuthContext.Setup(c => c.HttpContext.Request.HttpMethod).Returns(\"post\");\n            mockAuthContext.Setup(c => c.HttpContext.Request.IsSecureConnection).Returns(false);\n            AuthorizationContext authContext = mockAuthContext.Object;\n\n            RequireHttpsAttribute attr = new RequireHttpsAttribute();\n\n            // Act & assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { attr.OnAuthorization(authContext); },\n                @\"The requested resource can only be accessed via SSL.\");\n        }\n\n        private class MyRequireHttpsAttribute : RequireHttpsAttribute\n        {\n            protected override void HandleNonHttpsRequest(AuthorizationContext filterContext)\n            {\n                filterContext.Result = new ContentResult() { Content = \"Custom HandleNonHttpsRequest\" };\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/RequiredAttributeAdapterTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")] // Uses ModelMetadataProviders.Current\n    public class RequiredAttributeAdapterTest\n    {\n        [Fact]\n        [ReplaceCulture]\n        public void ClientRulesWithRequiredAttribute()\n        {\n            // Arrange\n            var metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => null, typeof(string), \"Length\");\n            var context = new ControllerContext();\n            var attribute = new RequiredAttribute();\n            var adapter = new RequiredAttributeAdapter(metadata, context, attribute);\n\n            // Act\n            var rules = adapter.GetClientValidationRules()\n                .OrderBy(r => r.ValidationType)\n                .ToArray();\n\n            // Assert\n            ModelClientValidationRule rule = Assert.Single(rules);\n            Assert.Equal(\"required\", rule.ValidationType);\n            Assert.Empty(rule.ValidationParameters);\n            Assert.Equal(@\"The Length field is required.\", rule.ErrorMessage);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ResultExecutedContextTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ResultExecutedContextTest\n    {\n        [Fact]\n        public void ConstructorThrowsIfControllerDescriptorIsNull()\n        {\n            // Arrange\n            ControllerContext controllerContext = null;\n            ActionResult result = new ViewResult();\n            bool canceled = true;\n            Exception exception = null;\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ResultExecutedContext(controllerContext, result, canceled, exception); }, \"controllerContext\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfResultIsNull()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n            ActionResult result = null;\n            bool canceled = true;\n            Exception exception = null;\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ResultExecutedContext(controllerContext, result, canceled, exception); }, \"result\");\n        }\n\n        [Fact]\n        public void PropertiesAreSetByConstructor()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n            ActionResult result = new ViewResult();\n            bool canceled = true;\n            Exception exception = new Exception();\n\n            // Act\n            ResultExecutedContext resultExecutedContext = new ResultExecutedContext(controllerContext, result, canceled, exception);\n\n            // Assert\n            Assert.Equal(result, resultExecutedContext.Result);\n            Assert.Equal(canceled, resultExecutedContext.Canceled);\n            Assert.Equal(exception, resultExecutedContext.Exception);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ResultExecutingContextTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ResultExecutingContextTest\n    {\n        [Fact]\n        public void ConstructorThrowsIfControllerContextIsNull()\n        {\n            // Arrange\n            ControllerContext controllerContext = null;\n            ActionResult result = new ViewResult();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ResultExecutingContext(controllerContext, result); }, \"controllerContext\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfResultIsNull()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n            ActionResult result = null;\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ResultExecutingContext(controllerContext, result); }, \"result\");\n        }\n\n        [Fact]\n        public void ResultProperty()\n        {\n            // Arrange\n            ControllerContext controllerContext = new Mock<ControllerContext>().Object;\n            ActionResult result = new ViewResult();\n\n            // Act\n            ResultExecutingContext resultExecutingContext = new ResultExecutingContext(controllerContext, result);\n\n            // Assert\n            Assert.Equal(result, resultExecutingContext.Result);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/RouteCollectionExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class RouteCollectionExtensionsTest\n    {\n        private static string[] _nameSpaces = new string[] { \"nsA.nsB.nsC\", \"ns1.ns2.ns3\" };\n\n        [Fact]\n        public void GetVirtualPathForAreaDoesNotStripAreaTokenIfAreasNotInUse()\n        {\n            // Arrange\n            RouteCollection routes = new RouteCollection();\n            routes.MapRoute(\n                \"Default\",\n                \"no-area/{controller}/{action}/{id}\",\n                new { controller = \"Home\", action = \"Index\", id = \"\" }\n                );\n\n            RequestContext requestContext = GetRequestContext(null);\n            RouteValueDictionary values = new RouteValueDictionary()\n            {\n                { \"controller\", \"home\" },\n                { \"action\", \"about\" },\n                { \"area\", \"some-area\" }\n            };\n\n            // Act\n            VirtualPathData vpd = routes.GetVirtualPathForArea(requestContext, values);\n\n            // Assert\n            Assert.NotNull(vpd);\n            Assert.Equal(routes[\"Default\"], vpd.Route);\n\n            // note presence of 'area' query string parameter; RVD should not be modified if areas not in use\n            Assert.Equal(\"/app/no-area/home/about?area=some-area\", vpd.VirtualPath);\n        }\n\n        [Fact]\n        public void GetVirtualPathForAreaForwardsCallIfRouteNameSpecified()\n        {\n            // Arrange\n            RouteCollection routes = GetRouteCollection();\n            RequestContext requestContext = GetRequestContext(null);\n            RouteValueDictionary values = new RouteValueDictionary()\n            {\n                { \"controller\", \"home\" },\n                { \"action\", \"index\" },\n                { \"area\", \"some-area\" }\n            };\n\n            // Act\n            VirtualPathData vpd = routes.GetVirtualPathForArea(requestContext, \"admin_default\", values);\n\n            // Assert\n            Assert.NotNull(vpd);\n            Assert.Equal(routes[\"admin_default\"], vpd.Route);\n\n            // note presence of 'area' query string parameter; RVD should not be modified if route name was provided\n            Assert.Equal(\"/app/admin-area?area=some-area\", vpd.VirtualPath);\n        }\n\n        [Fact]\n        public void GetVirtualPathForAreaThrowsIfRoutesIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { RouteCollectionExtensions.GetVirtualPathForArea(null, null, null); }, \"routes\");\n        }\n\n        [Fact]\n        public void GetVirtualPathForAreaWillJumpBetweenAreasExplicitly()\n        {\n            // Arrange\n            RouteCollection routes = GetRouteCollection();\n            RequestContext requestContext = GetRequestContext(null);\n            RouteValueDictionary values = new RouteValueDictionary()\n            {\n                { \"controller\", \"home\" },\n                { \"action\", \"tenmostrecent\" },\n                { \"tag\", \"some-tag\" },\n                { \"area\", \"blog\" }\n            };\n\n            // Act\n            VirtualPathData vpd = routes.GetVirtualPathForArea(requestContext, values);\n\n            // Assert\n            Assert.NotNull(vpd);\n            Assert.Equal(routes[\"blog_whatsnew\"], vpd.Route);\n            Assert.Equal(\"/app/whats-new/some-tag\", vpd.VirtualPath);\n        }\n\n        [Fact]\n        public void GetVirtualPathForAreaWillNotJumpBetweenAreasImplicitly()\n        {\n            // Arrange\n            RouteCollection routes = GetRouteCollection();\n            RequestContext requestContext = GetRequestContext(\"admin\");\n            RouteValueDictionary values = new RouteValueDictionary()\n            {\n                { \"controller\", \"home\" },\n                { \"action\", \"tenmostrecent\" },\n                { \"tag\", \"some-tag\" }\n            };\n\n            // Act\n            VirtualPathData vpd = routes.GetVirtualPathForArea(requestContext, values);\n\n            // Assert\n            Assert.NotNull(vpd);\n            Assert.Equal(routes[\"admin_default\"], vpd.Route);\n            Assert.Equal(\"/app/admin-area/home/tenmostrecent?tag=some-tag\", vpd.VirtualPath);\n        }\n\n        [Fact]\n        public void MapRoute3()\n        {\n            // Arrange\n            RouteCollection routes = new RouteCollection();\n\n            // Act\n            routes.MapRoute(\"RouteName\", \"SomeUrl\");\n\n            // Assert\n            Route route = Assert.Single(routes.Cast<Route>());\n            Assert.NotNull(route);\n            Assert.Same(route, routes[\"RouteName\"]);\n            Assert.Equal(\"SomeUrl\", route.Url);\n            Assert.IsType<MvcRouteHandler>(route.RouteHandler);\n            Assert.Empty(route.Defaults);\n            Assert.Empty(route.Constraints);\n            Assert.Empty(route.DataTokens);\n        }\n\n        [Fact]\n        public void MapRoute3WithNameSpaces()\n        {\n            // Arrange\n            RouteCollection routes = new RouteCollection();\n            //string[] namespaces = new string[] { \"nsA.nsB.nsC\", \"ns1.ns2.ns3\" };\n\n            // Act\n            routes.MapRoute(\"RouteName\", \"SomeUrl\", _nameSpaces);\n\n            // Assert\n            Route route = Assert.Single(routes.Cast<Route>());\n            Assert.NotNull(route);\n            Assert.NotNull(route.DataTokens);\n            Assert.NotNull(route.DataTokens[\"Namespaces\"]);\n            string[] routeNameSpaces = route.DataTokens[\"Namespaces\"] as string[];\n            Assert.Equal(2, routeNameSpaces.Length);\n            Assert.Same(route, routes[\"RouteName\"]);\n            Assert.Same(routeNameSpaces, _nameSpaces);\n            Assert.Equal(\"SomeUrl\", route.Url);\n            Assert.IsType<MvcRouteHandler>(route.RouteHandler);\n            Assert.Empty(route.Defaults);\n            Assert.Empty(route.Constraints);\n        }\n\n        [Fact]\n        public void MapRoute3WithEmptyNameSpaces()\n        {\n            // Arrange\n            RouteCollection routes = new RouteCollection();\n\n            // Act\n            routes.MapRoute(\"RouteName\", \"SomeUrl\", new string[] { });\n\n            // Assert\n            Route route = Assert.Single(routes.Cast<Route>());\n            Assert.NotNull(route);\n            Assert.Same(route, routes[\"RouteName\"]);\n            Assert.Equal(\"SomeUrl\", route.Url);\n            Assert.IsType<MvcRouteHandler>(route.RouteHandler);\n            Assert.Empty(route.Defaults);\n            Assert.Empty(route.Constraints);\n            Assert.Empty(route.DataTokens);\n        }\n\n        [Fact]\n        public void MapRoute4()\n        {\n            // Arrange\n            RouteCollection routes = new RouteCollection();\n            var defaults = new { Foo = \"DefaultFoo\" };\n\n            // Act\n            routes.MapRoute(\"RouteName\", \"SomeUrl\", defaults);\n\n            // Assert\n            Route route = Assert.Single(routes.Cast<Route>());\n            Assert.NotNull(route);\n            Assert.Same(route, routes[\"RouteName\"]);\n            Assert.Equal(\"SomeUrl\", route.Url);\n            Assert.IsType<MvcRouteHandler>(route.RouteHandler);\n            Assert.Equal(\"DefaultFoo\", route.Defaults[\"Foo\"]);\n            Assert.Empty(route.Constraints);\n            Assert.Empty(route.DataTokens);\n        }\n\n        [Fact]\n        public void MapRoute4WithNameSpaces()\n        {\n            // Arrange\n            RouteCollection routes = new RouteCollection();\n            var defaults = new { Foo = \"DefaultFoo\" };\n\n            // Act\n            routes.MapRoute(\"RouteName\", \"SomeUrl\", defaults, _nameSpaces);\n\n            // Assert\n            Route route = Assert.Single(routes.Cast<Route>());\n            Assert.NotNull(route);\n            Assert.NotNull(route.DataTokens);\n            Assert.NotNull(route.DataTokens[\"Namespaces\"]);\n            string[] routeNameSpaces = route.DataTokens[\"Namespaces\"] as string[];\n            Assert.Equal(2, routeNameSpaces.Length);\n            Assert.Same(route, routes[\"RouteName\"]);\n            Assert.Same(routeNameSpaces, _nameSpaces);\n            Assert.Equal(\"SomeUrl\", route.Url);\n            Assert.IsType<MvcRouteHandler>(route.RouteHandler);\n            Assert.Equal(\"DefaultFoo\", route.Defaults[\"Foo\"]);\n            Assert.Empty(route.Constraints);\n        }\n\n        [Fact]\n        public void MapRoute4WithDefaultsAsDictionary()\n        {\n            // Arrange\n            RouteCollection routes = new RouteCollection();\n            var defaults = new Dictionary<string, object> { { \"Foo\", \"DefaultFoo\" } };\n\n            // Act\n            routes.MapRoute(\"RouteName\", \"SomeUrl\", defaults);\n\n            // Assert\n            Route route = Assert.Single(routes.Cast<Route>());\n            Assert.NotNull(route);\n            Assert.Same(route, routes[\"RouteName\"]);\n            Assert.Equal(\"SomeUrl\", route.Url);\n            Assert.IsType<MvcRouteHandler>(route.RouteHandler);\n            Assert.Equal(\"DefaultFoo\", route.Defaults[\"Foo\"]);\n            Assert.Empty(route.Constraints);\n            Assert.Empty(route.DataTokens);\n        }\n\n        [Fact]\n        public void MapRoute5()\n        {\n            // Arrange\n            RouteCollection routes = new RouteCollection();\n            var defaults = new { Foo = \"DefaultFoo\" };\n            var constraints = new { Foo = \"ConstraintFoo\" };\n\n            // Act\n            routes.MapRoute(\"RouteName\", \"SomeUrl\", defaults, constraints);\n\n            // Assert\n            Route route = Assert.Single(routes.Cast<Route>());\n            Assert.NotNull(route);\n            Assert.Same(route, routes[\"RouteName\"]);\n            Assert.Equal(\"SomeUrl\", route.Url);\n            Assert.IsType<MvcRouteHandler>(route.RouteHandler);\n            Assert.Equal(\"DefaultFoo\", route.Defaults[\"Foo\"]);\n            Assert.Equal(\"ConstraintFoo\", route.Constraints[\"Foo\"]);\n            Assert.Empty(route.DataTokens);\n        }\n\n        [Fact]\n        public void MapRoute5WithDefaultsAndConstraintsAsDictionary()\n        {\n            // Arrange\n            RouteCollection routes = new RouteCollection();\n            var defaults = new Dictionary<string, object> { { \"Foo\", \"DefaultFoo\" } };\n            var constraints = new Dictionary<string, object> { { \"Foo\", \"ConstraintFoo\" } };\n\n            // Act\n            routes.MapRoute(\"RouteName\", \"SomeUrl\", defaults, constraints);\n\n            // Assert\n            Route route = Assert.Single(routes.Cast<Route>());\n            Assert.NotNull(route);\n            Assert.Same(route, routes[\"RouteName\"]);\n            Assert.Equal(\"SomeUrl\", route.Url);\n            Assert.IsType<MvcRouteHandler>(route.RouteHandler);\n            Assert.Equal(\"DefaultFoo\", route.Defaults[\"Foo\"]);\n            Assert.Equal(\"ConstraintFoo\", route.Constraints[\"Foo\"]);\n            Assert.Empty(route.DataTokens);\n        }\n\n        [Fact]\n        public void MapRoute5WithNullRouteCollectionThrows()\n        {\n            Assert.ThrowsArgumentNull(\n                delegate { RouteCollectionExtensions.MapRoute(null, null, null, null, null); },\n                \"routes\");\n        }\n\n        [Fact]\n        public void MapRoute5WithNullUrlThrows()\n        {\n            // Arrange\n            RouteCollection routes = new RouteCollection();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { routes.MapRoute(null, null /* url */, null, null); },\n                \"url\");\n        }\n\n        [Fact]\n        public void IgnoreRoute1WithNullRouteCollectionThrows()\n        {\n            Assert.ThrowsArgumentNull(\n                delegate { RouteCollectionExtensions.IgnoreRoute(null, \"foo\"); },\n                \"routes\");\n        }\n\n        [Fact]\n        public void IgnoreRoute1WithNullUrlThrows()\n        {\n            // Arrange\n            RouteCollection routes = new RouteCollection();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { routes.IgnoreRoute(null); },\n                \"url\");\n        }\n\n        [Fact]\n        public void IgnoreRoute3()\n        {\n            // Arrange\n            RouteCollection routes = new RouteCollection();\n\n            // Act\n            routes.IgnoreRoute(\"SomeUrl\");\n\n            // Assert\n            Route route = Assert.Single(routes.Cast<Route>());\n            Assert.NotNull(route);\n            Assert.Equal(\"SomeUrl\", route.Url);\n            Assert.IsType<StopRoutingHandler>(route.RouteHandler);\n            Assert.Null(route.Defaults);\n            Assert.Empty(route.Constraints);\n        }\n\n        [Fact]\n        public void IgnoreRoute4()\n        {\n            // Arrange\n            RouteCollection routes = new RouteCollection();\n            var constraints = new { Foo = \"DefaultFoo\" };\n\n            // Act\n            routes.IgnoreRoute(\"SomeUrl\", constraints);\n\n            // Assert\n            Route route = Assert.Single(routes.Cast<Route>());\n            Assert.NotNull(route);\n            Assert.Equal(\"SomeUrl\", route.Url);\n            Assert.IsType<StopRoutingHandler>(route.RouteHandler);\n            Assert.Null(route.Defaults);\n            Assert.Single(route.Constraints);\n            Assert.Equal(\"DefaultFoo\", route.Constraints[\"Foo\"]);\n        }\n\n        [Fact]\n        public void IgnoreRouteInternalNeverMatchesUrlGeneration()\n        {\n            // Arrange\n            RouteCollection routes = new RouteCollection();\n            routes.IgnoreRoute(\"SomeUrl\");\n            Route route = routes[0] as Route;\n\n            // Act\n            VirtualPathData vpd = route.GetVirtualPath(new RequestContext(new Mock<HttpContextBase>().Object, new RouteData()), null);\n\n            // Assert\n            Assert.Null(vpd);\n        }\n\n        [Fact]\n        public void MapRoute_ValidatesConstraintType_IRouteConstraint()\n        {\n            // Arrange\n            var routes = new RouteCollection();\n\n            var constraint = new CustomConstraint();\n            var constraints = new RouteValueDictionary();\n            constraints.Add(\"custom\", constraint);\n\n            // Act\n            var route = routes.MapRoute(\"default\", \"{controller}/{id}\", null, constraints);\n\n            // Assert\n            Assert.NotNull(route.Constraints[\"custom\"]);\n        }\n\n        [Fact]\n        public void MapRoute_ValidatesConstraintType_StringRegex()\n        {\n            // Arrange\n            var routes = new RouteCollection();\n\n            // We can't easily mock the ValidateConstraint method because all of this logic is in extension methods,\n            // so we're just assuming here that it was called.\n            var constraint = \"product|products\";\n            var constraints = new RouteValueDictionary();\n            constraints.Add(\"custom\", constraint);\n\n            // Act\n            var route = routes.MapRoute(\"default\", \"{controller}/{id}\", null, constraints);\n\n            // Assert\n            Assert.NotNull(route.Constraints[\"custom\"]);\n        }\n\n        [Fact]\n        public void MapRoute_ValidatesConstraintType_InvalidType()\n        {\n            // Arrange\n            var routes = new RouteCollection();\n\n            // We can't easily mock the ValidateConstraint method because all of this logic is in extension methods,\n            // so we're just assuming here that it was called.\n            var constraint = new Uri(\"http://localhost/\");\n            var constraints = new RouteValueDictionary();\n            constraints.Add(\"custom\", constraint);\n\n            string expectedMessage =\n                \"The constraint entry 'custom' on the route with route template '{controller}/{id}' \" +\n                \"must have a string value or be of a type which implements 'System.Web.Routing.IRouteConstraint'.\";\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(() => routes.MapRoute(\"default\", \"{controller}/{id}\", null, constraints), expectedMessage);\n        }\n\n        [Fact]\n        public void IgnoreRoute_ValidatesConstraintType_InvalidType()\n        {\n            // Arrange\n            var routes = new RouteCollection();\n\n            var constraint = new Uri(\"http://localhost/\");\n            var constraints = new RouteValueDictionary();\n            constraints.Add(\"custom\", constraint);\n\n            string expectedMessage =\n                \"The constraint entry 'custom' on the route with route template '{controller}/{id}' \" +\n                \"must have a string value or be of a type which implements 'System.Web.Routing.IRouteConstraint'.\";\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(() => routes.IgnoreRoute(\"{controller}/{id}\", constraints), expectedMessage);\n        }\n\n        private static RequestContext GetRequestContext(string currentAreaName)\n        {\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(c => c.Request.ApplicationPath).Returns(\"/app\");\n            mockHttpContext.Setup(c => c.Response.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(virtualPath => virtualPath);\n\n            RouteData routeData = new RouteData();\n            routeData.DataTokens[\"area\"] = currentAreaName;\n            return new RequestContext(mockHttpContext.Object, routeData);\n        }\n\n        private static RouteCollection GetRouteCollection()\n        {\n            RouteCollection routes = new RouteCollection();\n            routes.MapRoute(\n                \"Default\",\n                \"no-area/{controller}/{action}/{id}\",\n                new { controller = \"Home\", action = \"Index\", id = \"\" }\n                );\n\n            AreaRegistrationContext blogContext = new AreaRegistrationContext(\"blog\", routes);\n            blogContext.MapRoute(\n                \"Blog_WhatsNew\",\n                \"whats-new/{tag}\",\n                new { controller = \"Home\", action = \"TenMostRecent\", tag = \"\" }\n                );\n            blogContext.MapRoute(\n                \"Blog_Default\",\n                \"blog-area/{controller}/{action}/{id}\",\n                new { controller = \"Home\", action = \"Index\", id = \"\" }\n                );\n\n            AreaRegistrationContext adminContext = new AreaRegistrationContext(\"admin\", routes);\n            adminContext.MapRoute(\n                \"Admin_Default\",\n                \"admin-area/{controller}/{action}/{id}\",\n                new { controller = \"Home\", action = \"Index\", id = \"\" }\n                );\n\n            return routes;\n        }\n\n        private class CustomConstraint : IRouteConstraint\n        {\n            public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/RouteDataValueProviderFactoryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class RouteDataValueProviderFactoryTest\n    {\n        [Fact]\n        public void GetValueProvider()\n        {\n            // Arrange\n            RouteDataValueProviderFactory factory = new RouteDataValueProviderFactory();\n\n            ControllerContext controllerContext = new ControllerContext();\n            controllerContext.RouteData = new RouteData();\n            controllerContext.RouteData.Values[\"forty-two\"] = 42;\n\n            // Act\n            IValueProvider valueProvider = factory.GetValueProvider(controllerContext);\n\n            // Assert\n            Assert.IsType<RouteDataValueProvider>(valueProvider);\n            ValueProviderResult vpResult = valueProvider.GetValue(\"forty-two\");\n\n            Assert.NotNull(vpResult);\n            Assert.Equal(42, vpResult.RawValue);\n            Assert.Equal(\"42\", vpResult.AttemptedValue);\n            Assert.Equal(CultureInfo.InvariantCulture, vpResult.Culture);\n        }\n\n        [Fact]\n        public void GetValueProvider_ThrowsIfControllerContextIsNull()\n        {\n            // Arrange\n            RouteDataValueProviderFactory factory = new RouteDataValueProviderFactory();\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { factory.GetValueProvider(null); }, \"controllerContext\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/SelectListTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class SelectListTest\n    {\n        [Fact]\n        public void Constructor1SetsProperties()\n        {\n            // Arrange\n            IEnumerable items = new object[0];\n\n            // Act\n            SelectList selectList = new SelectList(items);\n\n            // Assert\n            Assert.Same(items, selectList.Items);\n            Assert.Null(selectList.DataValueField);\n            Assert.Null(selectList.DataTextField);\n            Assert.Null(selectList.SelectedValues);\n            Assert.Null(selectList.SelectedValue);\n        }\n\n        [Fact]\n        public void Constructor2SetsProperties_Items_SelectedValue()\n        {\n            // Arrange\n            IEnumerable items = new object[0];\n            object selectedValue = new object();\n\n            // Act\n            SelectList selectList = new SelectList(items, selectedValue);\n            List<object> selectedValues = selectList.SelectedValues.Cast<object>().ToList();\n\n            // Assert\n            Assert.Same(items, selectList.Items);\n            Assert.Null(selectList.DataValueField);\n            Assert.Null(selectList.DataTextField);\n            Assert.Same(selectedValue, selectList.SelectedValue);\n            object resultValue = Assert.Single(selectedValues);\n            Assert.Same(selectedValue, resultValue);\n        }\n\n        [Fact]\n        public void Constructor3SetsProperties_SelectedValue_DisabledValues()\n        {\n            // Arrange\n            IEnumerable items = new[] { \"A\", \"B\", \"C\" };\n            IEnumerable selectedValues = \"A\";\n            IEnumerable disabledValues = new[] { \"B\", \"C\" };\n\n            // Act\n            SelectList multiSelect = new SelectList(items, selectedValues, disabledValues);\n\n            // Assert\n            Assert.Same(items, multiSelect.Items);\n            Assert.Equal(new object[] { selectedValues }, multiSelect.SelectedValues);\n            Assert.Equal(disabledValues, multiSelect.DisabledValues);\n            Assert.Null(multiSelect.DataTextField);\n            Assert.Null(multiSelect.DataValueField);\n        }\n\n        [Fact]\n        public void Constructor3SetsProperties_Value_Text()\n        {\n            // Arrange\n            IEnumerable items = new object[0];\n\n            // Act\n            SelectList selectList = new SelectList(items, \"SomeValueField\", \"SomeTextField\");\n\n            // Assert\n            Assert.Same(items, selectList.Items);\n            Assert.Equal(\"SomeValueField\", selectList.DataValueField);\n            Assert.Equal(\"SomeTextField\", selectList.DataTextField);\n            Assert.Null(selectList.SelectedValues);\n            Assert.Null(selectList.SelectedValue);\n        }\n\n        [Fact]\n        public void Constructor4SetsProperties()\n        {\n            // Arrange\n            IEnumerable items = new object[0];\n            object selectedValue = new object();\n\n            // Act\n            SelectList selectList = new SelectList(items, \"SomeValueField\", \"SomeTextField\", selectedValue);\n            List<object> selectedValues = selectList.SelectedValues.Cast<object>().ToList();\n\n            // Assert\n            Assert.Same(items, selectList.Items);\n            Assert.Equal(\"SomeValueField\", selectList.DataValueField);\n            Assert.Equal(\"SomeTextField\", selectList.DataTextField);\n            Assert.Same(selectedValue, selectList.SelectedValue);\n            object resultValue = Assert.Single(selectedValues);\n            Assert.Same(selectedValue, resultValue);\n        }\n\n        [Fact]\n        public void Constructor_SetsProperties_Items_Value_Text_SelectedValue_DisabledValues()\n        {\n            // Arrange\n            IEnumerable items = new[]\n            {\n                new { Value = \"A\", Text = \"Alice\" },\n                new { Value = \"B\", Text = \"Bravo\" },\n                new { Value = \"C\", Text = \"Charlie\" },\n            };\n            object selectedValue = \"A\";\n            IEnumerable disabledValues = new[] { \"B\", \"C\" };\n\n            // Act\n            SelectList selectList = new SelectList(items,\n                \"Value\",\n                \"Text\",\n                selectedValue,\n                disabledValues);\n            List<object> selectedValues = selectList.SelectedValues.Cast<object>().ToList();\n\n            // Assert\n            Assert.Same(items, selectList.Items);\n            Assert.Equal(\"Value\", selectList.DataValueField);\n            Assert.Equal(\"Text\", selectList.DataTextField);\n            Assert.Same(selectedValue, selectList.SelectedValue);\n            object resultValue = Assert.Single(selectedValues);\n            Assert.Same(selectedValue, resultValue);\n            Assert.Same(disabledValues, selectList.DisabledValues);\n            Assert.Equal(disabledValues, selectList.DisabledValues);\n            Assert.Null(selectList.DataGroupField);\n            Assert.Null(selectList.DisabledGroups);\n        }\n\n        [Fact]\n        public void Constructor_SetsProperties_Items_Value_Text_SelectedValue_Group()\n        {\n            // Arrange\n            IEnumerable items = new[]\n            {\n                new { Value = \"A\", Text = \"Alice\", Group = \"AB\" },\n                new { Value = \"B\", Text = \"Bravo\", Group = \"AB\" },\n                new { Value = \"C\", Text = \"Charlie\", Group = \"C\" },\n            };\n            object selectedValue = \"A\";\n\n            // Act\n            SelectList selectList = new SelectList(items,\n                \"Value\",\n                \"Text\",\n                \"Group\",\n                selectedValue);\n            List<object> selectedValues = selectList.SelectedValues.Cast<object>().ToList();\n\n            // Assert\n            Assert.Same(items, selectList.Items);\n            Assert.Equal(\"Value\", selectList.DataValueField);\n            Assert.Equal(\"Text\", selectList.DataTextField);\n            Assert.Same(selectedValue, selectList.SelectedValue);\n            object resultValue = Assert.Single(selectedValues);\n            Assert.Same(selectedValue, resultValue);\n            Assert.Equal(\"Group\", selectList.DataGroupField);\n        }\n\n        [Fact]\n        public void Constructor_SetsProperties_Items_Value_Text_SelectedValue_Group_DisabledGroups()\n        {\n            // Arrange\n            IEnumerable items = new[]\n            {\n                new { Value = \"A\", Text = \"Alice\", Group = \"AB\" },\n                new { Value = \"B\", Text = \"Bravo\", Group = \"AB\" },\n                new { Value = \"C\", Text = \"Charlie\", Group = \"C\" },\n            };\n            object selectedValue = \"A\";\n            IEnumerable disabledGroups = new[] { \"AB\" };\n\n            // Act\n            SelectList selectList = new SelectList(items,\n                \"Value\",\n                \"Text\",\n                \"Group\",\n                selectedValue,\n                null,\n                disabledGroups);\n            List<object> selectedValues = selectList.SelectedValues.Cast<object>().ToList();\n\n            // Assert\n            Assert.Same(items, selectList.Items);\n            Assert.Equal(\"Value\", selectList.DataValueField);\n            Assert.Equal(\"Text\", selectList.DataTextField);\n            Assert.Same(selectedValue, selectList.SelectedValue);\n            object resultValue = Assert.Single(selectedValues);\n            Assert.Same(selectedValue, resultValue);\n            Assert.Equal(\"Group\", selectList.DataGroupField);\n            Assert.Equal(disabledGroups, selectList.DisabledGroups);\n        }\n\n        [Fact]\n        public void Constructor_SetsProperties_Items_Value_Text_SelectedValue_DisabledValues_Group()\n        {\n            // Arrange\n            IEnumerable items = new[]\n            {\n                new { Value = \"A\", Text = \"Alice\", Group = \"AB\" },\n                new { Value = \"B\", Text = \"Bravo\", Group = \"AB\" },\n                new { Value = \"C\", Text = \"Charlie\", Group = \"C\" },\n            };\n            object selectedValue = \"A\";\n            IEnumerable disabledValues = new[] { \"A\", \"C\" };\n\n            // Act\n            SelectList selectList = new SelectList(items,\n                \"Value\",\n                \"Text\",\n                \"Group\",\n                selectedValue,\n                disabledValues);\n            List<object> selectedValues = selectList.SelectedValues.Cast<object>().ToList();\n\n            // Assert\n            Assert.Same(items, selectList.Items);\n            Assert.Equal(\"Value\", selectList.DataValueField);\n            Assert.Equal(\"Text\", selectList.DataTextField);\n            Assert.Same(selectedValue, selectList.SelectedValue);\n            object resultValue = Assert.Single(selectedValues);\n            Assert.Same(selectedValue, resultValue);\n            Assert.Equal(\"Group\", selectList.DataGroupField);\n            Assert.Same(disabledValues, selectList.DisabledValues);\n        }\n\n        [Fact]\n        public void DataGroupFieldSetByCtor()\n        {\n            // Arrange\n            IEnumerable items = new object[0];\n            object selectedValue = new object();\n\n            // Act\n            SelectList selectList = new SelectList(items, \"SomeValueField\", \"SomeTextField\", \"SomeGroupField\",\n                selectedValue);\n            IEnumerable selectedValues = selectList.SelectedValues;\n\n            // Assert\n            Assert.Same(items, selectList.Items);\n            Assert.Equal(\"SomeValueField\", selectList.DataValueField);\n            Assert.Equal(\"SomeTextField\", selectList.DataTextField);\n            Assert.Equal(\"SomeGroupField\", selectList.DataGroupField);\n            Assert.Same(selectedValue, selectList.SelectedValue);\n            Assert.Single(selectedValues, selectedValue);\n            Assert.Null(selectList.DisabledValues);\n            Assert.Null(selectList.DisabledGroups);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/SessionStateTempDataProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class SessionStateTempDataProviderTest\n    {\n        [Fact]\n        public void Load_NullSession_ReturnsEmptyDictionary()\n        {\n            // Arrange\n            SessionStateTempDataProvider testProvider = new SessionStateTempDataProvider();\n\n            // Act\n            IDictionary<string, object> tempDataDictionary = testProvider.LoadTempData(GetControllerContext());\n\n            // Assert\n            Assert.Empty(tempDataDictionary);\n        }\n\n        [Fact]\n        public void Load_NonNullSession_NoSessionData_ReturnsEmptyDictionary()\n        {\n            // Arrange\n            SessionStateTempDataProvider testProvider = new SessionStateTempDataProvider();\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            Mock<HttpSessionStateBase> mockSessionStateBase = new Mock<HttpSessionStateBase>();\n            mockControllerContext.Setup(c => c.HttpContext.Session).Returns(mockSessionStateBase.Object);\n\n            // Act\n            IDictionary<string, object> result = testProvider.LoadTempData(mockControllerContext.Object);\n\n            // Assert\n            Assert.Empty(result);\n        }\n\n        [Fact]\n        public void Load_NonNullSession_IncorrectSessionDataType_ReturnsEmptyDictionary()\n        {\n            // Arrange\n            SessionStateTempDataProvider testProvider = new SessionStateTempDataProvider();\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            Mock<HttpSessionStateBase> mockSessionStateBase = new Mock<HttpSessionStateBase>();\n            mockControllerContext.Setup(c => c.HttpContext.Session).Returns(mockSessionStateBase.Object);\n            mockSessionStateBase.Setup(ssb => ssb[SessionStateTempDataProvider.TempDataSessionStateKey]).Returns(42);\n\n            // Act\n            IDictionary<string, object> result = testProvider.LoadTempData(mockControllerContext.Object);\n\n            // Assert\n            Assert.Empty(result);\n        }\n\n        [Fact]\n        public void Load_NonNullSession_CorrectSessionDataType_ReturnsSessionData()\n        {\n            // Arrange\n            SessionStateTempDataProvider testProvider = new SessionStateTempDataProvider();\n            Dictionary<string, object> tempData = new Dictionary<string, object> { { \"foo\", \"bar\" } };\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            Mock<HttpSessionStateBase> mockSessionStateBase = new Mock<HttpSessionStateBase>();\n            mockControllerContext.Setup(c => c.HttpContext.Session).Returns(mockSessionStateBase.Object);\n            mockSessionStateBase.Setup(ssb => ssb[SessionStateTempDataProvider.TempDataSessionStateKey]).Returns(tempData);\n\n            // Act\n            var result = testProvider.LoadTempData(mockControllerContext.Object);\n\n            // Assert\n            Assert.Same(tempData, result);\n        }\n\n        [Fact]\n        public void Save_NullSession_NullDictionary_DoesNotThrow()\n        {\n            // Arrange\n            SessionStateTempDataProvider testProvider = new SessionStateTempDataProvider();\n\n            // Act\n            testProvider.SaveTempData(GetControllerContext(), null);\n        }\n\n        [Fact]\n        public void Save_NullSession_EmptyDictionary_DoesNotThrow()\n        {\n            // Arrange\n            SessionStateTempDataProvider testProvider = new SessionStateTempDataProvider();\n\n            // Act\n            testProvider.SaveTempData(GetControllerContext(), new Dictionary<string, object>());\n        }\n\n        [Fact]\n        public void Save_NullSession_NonEmptyDictionary_Throws()\n        {\n            // Arrange\n            SessionStateTempDataProvider testProvider = new SessionStateTempDataProvider();\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { testProvider.SaveTempData(GetControllerContext(), new Dictionary<string, object> { { \"foo\", \"bar\" } }); },\n                \"The SessionStateTempDataProvider class requires session state to be enabled.\");\n        }\n\n        [Fact]\n        public void Save_NonNullSession_TempDataIsDirty_AssignsTempDataDictionaryIntoSession()\n        {\n            // Arrange\n            SessionStateTempDataProvider testProvider = new SessionStateTempDataProvider();\n            Dictionary<string, object> tempData = new Dictionary<string, object> { { \"foo\", \"bar\" } };\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            Mock<HttpSessionStateBase> mockSessionStateBase = new Mock<HttpSessionStateBase>();\n            mockControllerContext.Setup(c => c.HttpContext.Session).Returns(mockSessionStateBase.Object);\n            mockSessionStateBase.SetupSet(ssb => ssb[SessionStateTempDataProvider.TempDataSessionStateKey] = tempData);\n\n            // Act\n            testProvider.SaveTempData(mockControllerContext.Object, tempData);\n\n            // Assert\n            mockSessionStateBase.VerifyAll();\n        }\n\n        [Fact]\n        public void Save_NonNullSession_TempDataIsNotDirty_KeyDoesNotExistInSession_SessionRemainsUntouched()\n        {\n            // Arrange\n            SessionStateTempDataProvider testProvider = new SessionStateTempDataProvider();\n            Dictionary<string, object> tempData = new Dictionary<string, object>();\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>(MockBehavior.Strict);\n            mockControllerContext.Setup(o => o.HttpContext.Session[SessionStateTempDataProvider.TempDataSessionStateKey]).Returns(null);\n\n            // Act\n            testProvider.SaveTempData(mockControllerContext.Object, tempData);\n\n            // Assert\n            mockControllerContext.Verify();\n        }\n\n        [Fact]\n        public void Save_NonNullSession_TempDataIsNotDirty_KeyExistsInSession_KeyRemovedFromSession()\n        {\n            // Arrange\n            SessionStateTempDataProvider testProvider = new SessionStateTempDataProvider();\n            Dictionary<string, object> tempData = new Dictionary<string, object>();\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>(MockBehavior.Strict);\n            mockControllerContext.Setup(o => o.HttpContext.Session[SessionStateTempDataProvider.TempDataSessionStateKey]).Returns(new object());\n            mockControllerContext.Setup(o => o.HttpContext.Session.Remove(SessionStateTempDataProvider.TempDataSessionStateKey)).Verifiable();\n\n            // Act\n            testProvider.SaveTempData(mockControllerContext.Object, tempData);\n\n            // Assert\n            mockControllerContext.Verify();\n        }\n\n        private static ControllerContext GetControllerContext()\n        {\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(c => c.HttpContext.Session).Returns((HttpSessionStateBase)null);\n            return mockControllerContext.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/SingleServiceResolverTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class SingleServiceResolverTest\n    {\n        [Fact]\n        public void ConstructorWithNullThunkArgumentThrows()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { new SingleServiceResolver<TestProvider>(null, null, \"TestProvider.Current\"); },\n                \"currentValueThunk\");\n\n            Assert.ThrowsArgumentNull(\n                delegate { new SingleServiceResolver<TestProvider>(null, null, \"TestProvider.Current\"); },\n                \"currentValueThunk\");\n\n            Assert.ThrowsArgumentNull(\n                delegate { new SingleServiceResolver<TestProvider>(() => null, null, \"TestProvider.Current\"); },\n                \"defaultValue\");\n        }\n\n        [Fact]\n        public void CurrentConsultsResolver()\n        {\n            // Arrange\n            TestProvider providerFromDefaultValue = new TestProvider();\n            TestProvider providerFromServiceLocation = new TestProvider();\n\n            Mock<IDependencyResolver> resolver = new Mock<IDependencyResolver>();\n            resolver.Setup(r => r.GetService(typeof(TestProvider)))\n                .Returns(providerFromServiceLocation);\n\n            SingleServiceResolver<TestProvider> singleResolver = new SingleServiceResolver<TestProvider>(() => null, providerFromDefaultValue, resolver.Object, \"TestProvider.Current\");\n\n            // Act\n            TestProvider returnedProvider = singleResolver.Current;\n\n            // Assert\n            Assert.Equal(providerFromServiceLocation, returnedProvider);\n        }\n\n        [Fact]\n        public void CurrentReturnsCurrentProviderNotDefaultIfSet()\n        {\n            // Arrange\n            TestProvider providerFromDefaultValue = new TestProvider();\n            TestProvider providerFromCurrentValueThunk = null;\n            Mock<IDependencyResolver> resolver = new Mock<IDependencyResolver>();\n            SingleServiceResolver<TestProvider> singleResolver = new SingleServiceResolver<TestProvider>(() => providerFromCurrentValueThunk, providerFromDefaultValue, resolver.Object, \"TestProvider.Current\");\n\n            // Act\n            providerFromCurrentValueThunk = new TestProvider();\n            TestProvider returnedProvider = singleResolver.Current;\n\n            // Assert\n            Assert.Equal(providerFromCurrentValueThunk, returnedProvider);\n            resolver.Verify(r => r.GetService(typeof(TestProvider)));\n        }\n\n        [Fact]\n        public void CurrentCachesResolverResult()\n        {\n            // Arrange\n            TestProvider providerFromDefaultValue = new TestProvider();\n            TestProvider providerFromServiceLocation = new TestProvider();\n\n            Mock<IDependencyResolver> resolver = new Mock<IDependencyResolver>();\n            resolver.Setup(r => r.GetService(typeof(TestProvider)))\n                .Returns(providerFromServiceLocation);\n\n            SingleServiceResolver<TestProvider> singleResolver = new SingleServiceResolver<TestProvider>(() => null, providerFromDefaultValue, resolver.Object, \"TestProvider.Current\");\n\n            // Act\n            TestProvider returnedProvider = singleResolver.Current;\n            TestProvider cachedProvider = singleResolver.Current;\n\n            // Assert\n            Assert.Equal(providerFromServiceLocation, returnedProvider);\n            Assert.Equal(providerFromServiceLocation, cachedProvider);\n            resolver.Verify(r => r.GetService(typeof(TestProvider)), Times.Exactly(1));\n        }\n\n        [Fact]\n        public void CurrentDoesNotQueryResolverAfterReceivingNull()\n        {\n            // Arrange\n            TestProvider providerFromDefaultValue = new TestProvider();\n            TestProvider providerFromCurrentValueThunk = new TestProvider();\n            Mock<IDependencyResolver> resolver = new Mock<IDependencyResolver>();\n            SingleServiceResolver<TestProvider> singleResolver = new SingleServiceResolver<TestProvider>(() => providerFromCurrentValueThunk, providerFromDefaultValue, resolver.Object, \"TestProvider.Current\");\n\n            // Act\n            TestProvider returnedProvider = singleResolver.Current;\n            TestProvider cachedProvider = singleResolver.Current;\n\n            // Assert\n            Assert.Equal(providerFromCurrentValueThunk, returnedProvider);\n            Assert.Equal(providerFromCurrentValueThunk, cachedProvider);\n            resolver.Verify(r => r.GetService(typeof(TestProvider)), Times.Exactly(1));\n        }\n\n        [Fact]\n        public void CurrentReturnsDefaultIfCurrentNotSet()\n        {\n            //Arrange\n            TestProvider providerFromDefaultValue = new TestProvider();\n            Mock<IDependencyResolver> resolver = new Mock<IDependencyResolver>();\n            SingleServiceResolver<TestProvider> singleResolver = new SingleServiceResolver<TestProvider>(() => null, providerFromDefaultValue, resolver.Object, \"TestProvider.Current\");\n\n            //Act\n            TestProvider returnedProvider = singleResolver.Current;\n\n            // Assert\n            Assert.Equal(returnedProvider, providerFromDefaultValue);\n            resolver.Verify(l => l.GetService(typeof(TestProvider)));\n        }\n\n        [Fact]\n        public void CurrentThrowsIfCurrentSetThroughServiceAndSetter()\n        {\n            // Arrange\n            TestProvider providerFromCurrentValueThunk = new TestProvider();\n            TestProvider providerFromServiceLocation = new TestProvider();\n            TestProvider providerFromDefaultValue = new TestProvider();\n            Mock<IDependencyResolver> resolver = new Mock<IDependencyResolver>();\n\n            resolver.Setup(r => r.GetService(typeof(TestProvider)))\n                .Returns(providerFromServiceLocation);\n\n            SingleServiceResolver<TestProvider> singleResolver = new SingleServiceResolver<TestProvider>(() => providerFromCurrentValueThunk, providerFromDefaultValue, resolver.Object, \"TestProvider.Current\");\n\n            //Act & assert\n            Assert.Throws<InvalidOperationException>(\n                () => singleResolver.Current,\n                \"An instance of TestProvider was found in the resolver as well as a custom registered provider in TestProvider.Current. Please set only one or the other.\"\n                );\n        }\n\n        [Fact]\n        public void CurrentPropagatesExceptionWhenResolverThrowsNonActivationException()\n        {\n            // Arrange\n            TestProvider providerFromDefaultValue = new TestProvider();\n            Mock<IDependencyResolver> resolver = new Mock<IDependencyResolver>(MockBehavior.Strict);\n            SingleServiceResolver<TestProvider> singleResolver = new SingleServiceResolver<TestProvider>(() => null, providerFromDefaultValue, resolver.Object, \"TestProvider.Current\");\n\n            // Act & Assert\n            var ex = Assert.Throws<MockException>(() => singleResolver.Current);\n            Assert.Equal(\n                \"IDependencyResolver.GetService(System.Web.Mvc.Test.SingleServiceResolverTest+TestProvider) invocation failed with mock behavior Strict.\" +\n                Environment.NewLine +\n                \"All invocations on the mock must have a corresponding setup.\",\n                ex.Message,\n                ignoreLineEndingDifferences: true);\n        }\n\n        private class TestProvider\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/StringLengthAttributeAdapterTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")] // Uses ModelMetadataProviders.Current\n    public class StringLengthAttributeAdapterTest\n    {\n        [Fact]\n        [ReplaceCulture]\n        public void ClientRulesWithStringLengthAttribute()\n        {\n            // Arrange\n            var metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => null, typeof(string), \"Length\");\n            var context = new ControllerContext();\n            var attribute = new StringLengthAttribute(10) { MinimumLength = 3 };\n            var adapter = new StringLengthAttributeAdapter(metadata, context, attribute);\n\n            // Act\n            var rules = adapter.GetClientValidationRules()\n                .OrderBy(r => r.ValidationType)\n                .ToArray();\n\n            // Assert\n            ModelClientValidationRule rule = Assert.Single(rules);\n            Assert.Equal(\"length\", rule.ValidationType);\n            Assert.Equal(2, rule.ValidationParameters.Count);\n            Assert.Equal(3, rule.ValidationParameters[\"min\"]);\n            Assert.Equal(10, rule.ValidationParameters[\"max\"]);\n            Assert.Equal(\"The field Length must be a string with a minimum length of 3 and a maximum length of 10.\", rule.ErrorMessage);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/TempDataDictionaryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class TempDataDictionaryTest\n    {\n        [Fact]\n        public void CompareIsOrdinalIgnoreCase()\n        {\n            // Arrange\n            TempDataDictionary tempData = new TempDataDictionary();\n            object item = new object();\n\n            // Act\n            tempData[\"Foo\"] = item;\n            object value = tempData[\"FOO\"];\n\n            // Assert\n            Assert.Same(item, value);\n        }\n\n        [Fact]\n        public void EnumeratingDictionaryMarksValuesForDeletion()\n        {\n            // Arrange\n            NullTempDataProvider provider = new NullTempDataProvider();\n            TempDataDictionary tempData = new TempDataDictionary();\n            Mock<ControllerContext> controllerContext = new Mock<ControllerContext>();\n            tempData[\"Foo\"] = \"Foo\";\n            tempData[\"Bar\"] = \"Bar\";\n\n            // Act\n            IEnumerator<KeyValuePair<string, object>> enumerator = tempData.GetEnumerator();\n            while (enumerator.MoveNext())\n            {\n                object value = enumerator.Current;\n            }\n            tempData.Save(controllerContext.Object, provider);\n\n            // Assert\n            Assert.False(tempData.ContainsKey(\"Foo\"));\n            Assert.False(tempData.ContainsKey(\"Bar\"));\n        }\n\n        [Fact]\n        public void EnumeratingTempDataAsIEnmerableMarksValuesForDeletion()\n        {\n            // Arrange\n            NullTempDataProvider provider = new NullTempDataProvider();\n            TempDataDictionary tempData = new TempDataDictionary();\n            Mock<ControllerContext> controllerContext = new Mock<ControllerContext>();\n            tempData[\"Foo\"] = \"Foo\";\n            tempData[\"Bar\"] = \"Bar\";\n\n            // Act\n            IEnumerator enumerator = ((IEnumerable)tempData).GetEnumerator();\n            while (enumerator.MoveNext())\n            {\n                object value = enumerator.Current;\n            }\n            tempData.Save(controllerContext.Object, provider);\n\n            // Assert\n            Assert.False(tempData.ContainsKey(\"Foo\"));\n            Assert.False(tempData.ContainsKey(\"Bar\"));\n        }\n\n        [Fact]\n        public void KeepRetainsAllKeysWhenSavingDictionary()\n        {\n            // Arrange\n            NullTempDataProvider provider = new NullTempDataProvider();\n            TempDataDictionary tempData = new TempDataDictionary();\n            Mock<ControllerContext> controllerContext = new Mock<ControllerContext>();\n            controllerContext.Setup(c => c.HttpContext.Request).Returns(new Mock<HttpRequestBase>().Object);\n            tempData[\"Foo\"] = \"Foo\";\n            tempData[\"Bar\"] = \"Bar\";\n\n            // Act\n            tempData.Keep();\n            tempData.Save(controllerContext.Object, provider);\n\n            // Assert\n            Assert.True(tempData.ContainsKey(\"Foo\"));\n            Assert.True(tempData.ContainsKey(\"Bar\"));\n        }\n\n        [Fact]\n        public void KeepRetainsSpecificKeysWhenSavingDictionary()\n        {\n            // Arrange\n            NullTempDataProvider provider = new NullTempDataProvider();\n            TempDataDictionary tempData = new TempDataDictionary();\n            Mock<ControllerContext> controllerContext = new Mock<ControllerContext>();\n            controllerContext.Setup(c => c.HttpContext.Request).Returns(new Mock<HttpRequestBase>().Object);\n            tempData[\"Foo\"] = \"Foo\";\n            tempData[\"Bar\"] = \"Bar\";\n\n            // Act\n            tempData.Keep(\"Foo\");\n            object value = tempData[\"Bar\"];\n            tempData.Save(controllerContext.Object, provider);\n\n            // Assert\n            Assert.True(tempData.ContainsKey(\"Foo\"));\n            Assert.False(tempData.ContainsKey(\"Bar\"));\n        }\n\n        [Fact]\n        public void LoadAndSaveAreCaseInsensitive()\n        {\n            // Arrange\n            Dictionary<string, object> data = new Dictionary<string, object>();\n            data[\"Foo\"] = \"Foo\";\n            data[\"Bar\"] = \"Bar\";\n            TestTempDataProvider provider = new TestTempDataProvider(data);\n            Mock<ControllerContext> controllerContext = new Mock<ControllerContext>();\n            TempDataDictionary tempData = new TempDataDictionary();\n\n            // Act\n            tempData.Load(controllerContext.Object, provider);\n            object value = tempData[\"FOO\"];\n            tempData.Save(controllerContext.Object, provider);\n\n            // Assert\n            Assert.False(tempData.ContainsKey(\"foo\"));\n            Assert.True(tempData.ContainsKey(\"bar\"));\n        }\n\n        [Fact]\n        public void PeekDoesNotMarkKeyAsRead()\n        {\n            // Arrange\n            NullTempDataProvider provider = new NullTempDataProvider();\n            TempDataDictionary tempData = new TempDataDictionary();\n            Mock<ControllerContext> controllerContext = new Mock<ControllerContext>();\n            tempData[\"Bar\"] = \"barValue\";\n\n            // Act\n            object value = tempData.Peek(\"bar\");\n            tempData.Save(controllerContext.Object, provider);\n\n            // Assert\n            Assert.Equal(\"barValue\", value);\n            Assert.True(tempData.ContainsKey(\"Bar\"));\n        }\n\n        [Fact]\n        public void RemovalOfKeysAreCaseInsensitive()\n        {\n            NullTempDataProvider provider = new NullTempDataProvider();\n            TempDataDictionary tempData = new TempDataDictionary();\n            Mock<ControllerContext> controllerContext = new Mock<ControllerContext>();\n            object fooValue;\n            tempData[\"Foo\"] = \"Foo\";\n            tempData[\"Bar\"] = \"Bar\";\n\n            // Act\n            tempData.TryGetValue(\"foo\", out fooValue);\n            object barValue = tempData[\"bar\"];\n            tempData.Save(controllerContext.Object, provider);\n\n            // Assert\n            Assert.False(tempData.ContainsKey(\"Foo\"));\n            Assert.False(tempData.ContainsKey(\"Boo\"));\n        }\n\n        [Fact]\n        public void SaveRetainsAllKeys()\n        {\n            // Arrange\n            NullTempDataProvider provider = new NullTempDataProvider();\n            TempDataDictionary tempData = new TempDataDictionary();\n            Mock<ControllerContext> controllerContext = new Mock<ControllerContext>();\n            tempData[\"Foo\"] = \"Foo\";\n            tempData[\"Bar\"] = \"Bar\";\n\n            // Act\n            tempData.Save(controllerContext.Object, provider);\n\n            // Assert\n            Assert.True(tempData.ContainsKey(\"Foo\"));\n            Assert.True(tempData.ContainsKey(\"Bar\"));\n        }\n\n        [Fact]\n        public void SaveRemovesKeysThatWereRead()\n        {\n            // Arrange\n            NullTempDataProvider provider = new NullTempDataProvider();\n            TempDataDictionary tempData = new TempDataDictionary();\n            Mock<ControllerContext> controllerContext = new Mock<ControllerContext>();\n            tempData[\"Foo\"] = \"Foo\";\n            tempData[\"Bar\"] = \"Bar\";\n\n            // Act\n            object value = tempData[\"Foo\"];\n            tempData.Save(controllerContext.Object, provider);\n\n            // Assert\n            Assert.False(tempData.ContainsKey(\"Foo\"));\n            Assert.True(tempData.ContainsKey(\"Bar\"));\n        }\n\n        [Fact]\n        public void TempDataIsADictionary()\n        {\n            // Arrange\n            TempDataDictionary tempData = new TempDataDictionary();\n\n            // Act\n            tempData[\"Key1\"] = \"Value1\";\n            tempData.Add(\"Key2\", \"Value2\");\n            ((ICollection<KeyValuePair<string, object>>)tempData).Add(new KeyValuePair<string, object>(\"Key3\", \"Value3\"));\n\n            // Assert (IDictionary)\n            Assert.Equal(3, tempData.Count);\n            Assert.True(tempData.Remove(\"Key1\"));\n            Assert.False(tempData.Remove(\"Key4\"));\n            Assert.True(tempData.ContainsValue(\"Value2\"));\n            Assert.False(tempData.ContainsValue(\"Value1\"));\n            Assert.Null(tempData[\"Key6\"]);\n\n            IEnumerator tempDataEnumerator = tempData.GetEnumerator();\n            tempDataEnumerator.Reset();\n            while (tempDataEnumerator.MoveNext())\n            {\n                KeyValuePair<string, object> pair = (KeyValuePair<string, object>)tempDataEnumerator.Current;\n                Assert.True(((ICollection<KeyValuePair<string, object>>)tempData).Contains(pair));\n            }\n\n            // Assert (ICollection)\n            foreach (string key in tempData.Keys)\n            {\n                Assert.True(((ICollection<KeyValuePair<string, object>>)tempData).Contains(new KeyValuePair<string, object>(key, tempData[key])));\n            }\n\n            foreach (string value in tempData.Values)\n            {\n                Assert.True(tempData.ContainsValue(value));\n            }\n\n            foreach (string key in ((IDictionary<string, object>)tempData).Keys)\n            {\n                Assert.True(tempData.ContainsKey(key));\n            }\n\n            foreach (string value in ((IDictionary<string, object>)tempData).Values)\n            {\n                Assert.True(tempData.ContainsValue(value));\n            }\n\n            KeyValuePair<string, object>[] keyValuePairArray = new KeyValuePair<string, object>[tempData.Count];\n            ((ICollection<KeyValuePair<string, object>>)tempData).CopyTo(keyValuePairArray, 0);\n\n            Assert.False(((ICollection<KeyValuePair<string, object>>)tempData).IsReadOnly);\n\n            Assert.False(((ICollection<KeyValuePair<string, object>>)tempData).Remove(new KeyValuePair<string, object>(\"Key5\", \"Value5\")));\n\n            IEnumerator<KeyValuePair<string, object>> keyValuePairEnumerator = ((ICollection<KeyValuePair<string, object>>)tempData).GetEnumerator();\n            keyValuePairEnumerator.Reset();\n            while (keyValuePairEnumerator.MoveNext())\n            {\n                KeyValuePair<string, object> pair = keyValuePairEnumerator.Current;\n                Assert.True(((ICollection<KeyValuePair<string, object>>)tempData).Contains(pair));\n            }\n\n            // Act\n            tempData.Clear();\n\n            // Assert\n            Assert.Empty(tempData);\n        }\n\n        [Fact]\n        public void TempDataDictionaryCreatesEmptyDictionaryIfProviderReturnsNull()\n        {\n            // Arrange\n            TempDataDictionary tempDataDictionary = new TempDataDictionary();\n            NullTempDataProvider provider = new NullTempDataProvider();\n\n            // Act\n            tempDataDictionary.Load(null /* controllerContext */, provider);\n\n            // Assert\n            Assert.Empty(tempDataDictionary);\n        }\n\n        [Fact]\n        public void TryGetValueMarksKeyForDeletion()\n        {\n            NullTempDataProvider provider = new NullTempDataProvider();\n            TempDataDictionary tempData = new TempDataDictionary();\n            Mock<ControllerContext> controllerContext = new Mock<ControllerContext>();\n            object value;\n            tempData[\"Foo\"] = \"Foo\";\n\n            // Act\n            tempData.TryGetValue(\"Foo\", out value);\n            tempData.Save(controllerContext.Object, provider);\n\n            // Assert\n            Assert.False(tempData.ContainsKey(\"Foo\"));\n        }\n\n        internal class NullTempDataProvider : ITempDataProvider\n        {\n            public void SaveTempData(ControllerContext controllerContext, IDictionary<string, object> values)\n            {\n            }\n\n            public IDictionary<string, object> LoadTempData(ControllerContext controllerContext)\n            {\n                return null;\n            }\n        }\n\n        internal class TestTempDataProvider : ITempDataProvider\n        {\n            private IDictionary<string, object> _data;\n\n            public TestTempDataProvider(IDictionary<string, object> data)\n            {\n                _data = data;\n            }\n\n            public void SaveTempData(ControllerContext controllerContext, IDictionary<string, object> values)\n            {\n            }\n\n            public IDictionary<string, object> LoadTempData(ControllerContext controllerContext)\n            {\n                return _data;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/TypeCacheSerializerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.IO;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class TypeCacheSerializerTest\n    {\n        private static string _expectedDeserializationFormat =\n            \"<?xml version=\\\"1.0\\\" encoding=\\\"utf-16\\\"?>\" + Environment.NewLine\n          + \"<!--This file is automatically generated. Please do not modify the contents of this file.-->\" + Environment.NewLine\n          + \"<typeCache lastModified=\\\"__IGNORED__\\\" mvcVersionId=\\\"{0}\\\">\" + Environment.NewLine\n          + \"  <assembly name=\\\"{1}\\\">\" + Environment.NewLine\n          + \"    <module versionId=\\\"{2}\\\">\" + Environment.NewLine\n          + \"      <type>System.String</type>\" + Environment.NewLine\n          + \"      <type>System.Object</type>\" + Environment.NewLine\n          + \"    </module>\" + Environment.NewLine\n          + \"  </assembly>\" + Environment.NewLine\n          + \"</typeCache>\";\n\n        private static readonly string _mscorlibAsmFullName = typeof(object).Assembly.FullName;\n\n        [Fact]\n        public void DeserializeTypes_ReturnsNullIfModuleVersionIdDoesNotMatch()\n        {\n            // Arrange\n            string expected = String.Format(_expectedDeserializationFormat,\n                                            GetMvidForType(typeof(TypeCacheSerializer)) /* mvcVersionId */,\n                                            _mscorlibAsmFullName /* assembly.name */,\n                                            Guid.Empty /* module.versionId */\n                );\n\n            TypeCacheSerializer serializer = new TypeCacheSerializer();\n            StringReader input = new StringReader(expected);\n\n            // Act\n            List<Type> deserializedTypes = serializer.DeserializeTypes(input);\n\n            // Assert\n            Assert.Null(deserializedTypes);\n        }\n\n        [Fact]\n        public void DeserializeTypes_ReturnsNullIfMvcVersionIdDoesNotMatch()\n        {\n            // Arrange\n            string expected = String.Format(_expectedDeserializationFormat,\n                                            Guid.Empty /* mvcVersionId */,\n                                            _mscorlibAsmFullName /* assembly.name */,\n                                            GetMvidForType(typeof(object)) /* module.versionId */\n                );\n\n            TypeCacheSerializer serializer = new TypeCacheSerializer();\n            StringReader input = new StringReader(expected);\n\n            // Act\n            List<Type> deserializedTypes = serializer.DeserializeTypes(input);\n\n            // Assert\n            Assert.Null(deserializedTypes);\n        }\n\n        [Fact]\n        public void DeserializeTypes_ReturnsNullIfTypeNotFound()\n        {\n            string expectedFormat =\n                \"<?xml version=\\\"1.0\\\" encoding=\\\"utf-16\\\"?>\" + Environment.NewLine\n              + \"<!--This file is automatically generated. Please do not modify the contents of this file.-->\" + Environment.NewLine\n              + \"<typeCache lastModified=\\\"__IGNORED__\\\" mvcVersionId=\\\"{0}\\\">\" + Environment.NewLine\n              + \"  <assembly name=\\\"{1}\\\">\" + Environment.NewLine\n              + \"    <module versionId=\\\"{2}\\\">\" + Environment.NewLine\n              + \"      <type>System.String</type>\" + Environment.NewLine\n              + \"      <type>This.Type.Does.Not.Exist</type>\" + Environment.NewLine\n              + \"    </module>\" + Environment.NewLine\n              + \"  </assembly>\" + Environment.NewLine\n              + \"</typeCache>\";\n\n            // Arrange\n            string expected = String.Format(expectedFormat,\n                                            GetMvidForType(typeof(TypeCacheSerializer)) /* mvcVersionId */,\n                                            _mscorlibAsmFullName /* assembly.name */,\n                                            GetMvidForType(typeof(object)) /* module.versionId */\n                );\n\n            TypeCacheSerializer serializer = new TypeCacheSerializer();\n            StringReader input = new StringReader(expected);\n\n            // Act\n            List<Type> deserializedTypes = serializer.DeserializeTypes(input);\n\n            // Assert\n            Assert.Null(deserializedTypes);\n        }\n\n        [Fact]\n        public void DeserializeTypes_Success()\n        {\n            // Arrange\n            string expected = String.Format(_expectedDeserializationFormat,\n                                            GetMvidForType(typeof(TypeCacheSerializer)) /* mvcVersionId */,\n                                            _mscorlibAsmFullName /* assembly.name */,\n                                            GetMvidForType(typeof(object)) /* module.versionId */\n                );\n\n            TypeCacheSerializer serializer = new TypeCacheSerializer();\n            StringReader input = new StringReader(expected);\n\n            Type[] expectedTypes = new Type[]\n            {\n                typeof(string),\n                typeof(object)\n            };\n\n            // Act\n            List<Type> deserializedTypes = serializer.DeserializeTypes(input);\n\n            // Assert\n            Assert.Equal(expectedTypes, deserializedTypes.ToArray());\n        }\n\n        [Fact]\n        public void SerializeTypes()\n        {\n            // Arrange\n            DateTime expectedDate = new DateTime(2001, 1, 1, 0, 0, 0, DateTimeKind.Utc); // Jan 1, 2001 midnight UTC\n            string expectedFormat =\n                \"<?xml version=\\\"1.0\\\" encoding=\\\"utf-16\\\"?>\" + Environment.NewLine\n              + \"<!--This file is automatically generated. Please do not modify the contents of this file.-->\" + Environment.NewLine\n              + \"<typeCache lastModified=\\\"{0}\\\" mvcVersionId=\\\"{1}\\\">\" + Environment.NewLine\n              + \"  <assembly name=\\\"{2}\\\">\" + Environment.NewLine\n              + \"    <module versionId=\\\"{3}\\\">\" + Environment.NewLine\n              + \"      <type>System.String</type>\" + Environment.NewLine\n              + \"      <type>System.Object</type>\" + Environment.NewLine\n              + \"    </module>\" + Environment.NewLine\n              + \"  </assembly>\" + Environment.NewLine\n              + \"</typeCache>\";\n\n            string expected = String.Format(CultureInfo.InvariantCulture,\n                                            expectedFormat,\n                                            expectedDate /* lastModified */,\n                                            GetMvidForType(typeof(TypeCacheSerializer)) /* mvcVersionId */,\n                                            _mscorlibAsmFullName /* assembly.name */,\n                                            GetMvidForType(typeof(object)) /* module.versionId */\n                );\n\n            Type[] typesToSerialize = new Type[]\n            {\n                typeof(string),\n                typeof(object)\n            };\n\n            TypeCacheSerializer serializer = new TypeCacheSerializer();\n            serializer.CurrentDateOverride = expectedDate;\n\n            StringWriter output = new StringWriter();\n\n            // Act\n            serializer.SerializeTypes(typesToSerialize, output);\n            string outputString = output.ToString();\n\n            // Assert\n            Assert.Equal(expected, outputString);\n        }\n\n        private static Guid GetMvidForType(Type type)\n        {\n            return type.Module.ModuleVersionId;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/TypeCacheUtilTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class TypeCacheUtilTest\n    {\n        [Fact]\n        public void GetFilteredTypesFromAssemblies_FallThrough()\n        {\n            // Arrange\n            Type[] expectedTypes = new Type[]\n            {\n                typeof(TypeCacheValidFoo),\n                typeof(TypeCacheValidBar)\n            };\n\n            string cacheName = \"testCache\";\n            MockBuildManager buildManager = new MockBuildManager();\n            Predicate<Type> predicate = type => type.IsDefined(typeof(TypeCacheMarkerAttribute), true);\n\n            // Act\n            List<Type> returnedTypes = TypeCacheUtil.GetFilteredTypesFromAssemblies(cacheName, predicate, buildManager);\n\n            // Assert\n            Assert.Equal(expectedTypes, returnedTypes.ToArray());\n\n            MemoryStream cachedStream = buildManager.CachedFileStore[cacheName] as MemoryStream;\n            Assert.NotNull(cachedStream);\n            Assert.NotEmpty(cachedStream.ToArray());\n        }\n\n        [Fact]\n        public void SaveToCache_ReadFromCache_ReturnsNullIfTypesAreInvalid()\n        {\n            // SAVING\n\n            // Arrange\n            Type[] expectedTypes = new Type[]\n            {\n                typeof(object),\n                typeof(string)\n            };\n\n            TypeCacheSerializer serializer = new TypeCacheSerializer();\n            string cacheName = \"testCache\";\n            MockBuildManager buildManager = new MockBuildManager();\n\n            // Act\n            TypeCacheUtil.SaveTypesToCache(cacheName, expectedTypes, buildManager, serializer);\n\n            // Assert\n            MemoryStream writeStream = buildManager.CachedFileStore[cacheName] as MemoryStream;\n            Assert.NotNull(writeStream);\n\n            byte[] streamContents = writeStream.ToArray();\n            Assert.NotEmpty(streamContents);\n\n            // READING\n\n            // Arrange\n            MemoryStream readStream = new MemoryStream(streamContents);\n            buildManager.CachedFileStore[cacheName] = readStream;\n\n            // Act\n            List<Type> returnedTypes = TypeCacheUtil.ReadTypesFromCache(cacheName, _ => false /* all types are invalid */, buildManager, serializer);\n\n            // Assert\n            Assert.Null(returnedTypes);\n        }\n\n        [Fact]\n        public void SaveToCache_ReadFromCache_Success()\n        {\n            // SAVING\n\n            // Arrange\n            Type[] expectedTypes = new Type[]\n            {\n                typeof(object),\n                typeof(string)\n            };\n\n            TypeCacheSerializer serializer = new TypeCacheSerializer();\n            string cacheName = \"testCache\";\n            MockBuildManager buildManager = new MockBuildManager();\n\n            // Act\n            TypeCacheUtil.SaveTypesToCache(cacheName, expectedTypes, buildManager, serializer);\n\n            // Assert\n            MemoryStream writeStream = buildManager.CachedFileStore[cacheName] as MemoryStream;\n            Assert.NotNull(writeStream);\n\n            byte[] streamContents = writeStream.ToArray();\n            Assert.NotEmpty(streamContents);\n\n            // READING\n\n            // Arrange\n            MemoryStream readStream = new MemoryStream(streamContents);\n            buildManager.CachedFileStore[cacheName] = readStream;\n\n            // Act\n            List<Type> returnedTypes = TypeCacheUtil.ReadTypesFromCache(cacheName, _ => true /* all types are valid */, buildManager, serializer);\n\n            // Assert\n            Assert.Equal(expectedTypes, returnedTypes.ToArray());\n        }\n    }\n\n    public class TypeCacheMarkerAttribute : Attribute\n    {\n    }\n\n    [TypeCacheMarker]\n    public class TypeCacheValidFoo\n    {\n    }\n\n    [TypeCacheMarker]\n    public class TypeCacheValidBar\n    {\n    }\n\n    [TypeCacheMarker]\n    internal class TypeCacheInvalidInternal\n    {\n    }\n\n    [TypeCacheMarker]\n    public abstract class TypeCacheInvalidAbstract\n    {\n    }\n\n    [TypeCacheMarker]\n    public struct TypeCacheInvalidStruct\n    {\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/TypeHelpersTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class TypeHelpersTest\n    {\n        [Fact]\n        public void CreateDelegateBindsInstanceMethod()\n        {\n            // Act\n            string s = \"Hello, world!\";\n            Func<string, bool> endsWith = TypeHelpers.CreateDelegate<Func<string, bool>>(TypeHelpers.MsCorLibAssembly, \"System.String\", \"EndsWith\", s);\n\n            // Assert\n            Assert.NotNull(endsWith);\n            Assert.True(endsWith(\"world!\"));\n        }\n\n        [Fact]\n        public void CreateDelegateBindsStaticMethod()\n        {\n            // Act\n            Func<object, object, string> concat = TypeHelpers.CreateDelegate<Func<object, object, string>>(TypeHelpers.MsCorLibAssembly, \"System.String\", \"Concat\", null);\n\n            // Assert\n            Assert.NotNull(concat);\n            Assert.Equal(\"45\", concat(4, 5));\n        }\n\n        [Fact]\n        public void CreateDelegateReturnsNullIfTypeDoesNotExist()\n        {\n            // Act\n            Action d = TypeHelpers.CreateDelegate<Action>(TypeHelpers.MsCorLibAssembly, \"System.xyz.TypeDoesNotExist\", \"SomeMethod\", null);\n\n            // Assert\n            Assert.Null(d);\n        }\n\n        [Fact]\n        public void CreateDelegateReturnsNullIfMethodDoesNotExist()\n        {\n            // Act\n            Action d = TypeHelpers.CreateDelegate<Action>(TypeHelpers.MsCorLibAssembly, \"System.String\", \"MethodDoesNotExist\", null);\n\n            // Assert\n            Assert.Null(d);\n        }\n\n        [Fact]\n        public void CreateTryGetValueDelegateReturnsNullForNonDictionaries()\n        {\n            // Arrange\n            object notDictionary = \"Hello, world\";\n\n            // Act\n            TryGetValueDelegate d = TypeHelpers.CreateTryGetValueDelegate(notDictionary.GetType());\n\n            // Assert\n            Assert.Null(d);\n        }\n\n        [Fact]\n        public void CreateTryGetValueDelegateWrapsGenericObjectDictionaries()\n        {\n            // Arrange\n            object dictionary = new Dictionary<object, int>()\n            {\n                { \"theKey\", 42 }\n            };\n\n            // Act\n            TryGetValueDelegate d = TypeHelpers.CreateTryGetValueDelegate(dictionary.GetType());\n\n            object value;\n            bool found = d(dictionary, \"theKey\", out value);\n\n            // Assert\n            Assert.True(found);\n            Assert.Equal(42, value);\n        }\n\n        [Fact]\n        public void CreateTryGetValueDelegateWrapsGenericStringDictionaries()\n        {\n            // Arrange\n            object dictionary = new Dictionary<string, int>()\n            {\n                { \"theKey\", 42 }\n            };\n\n            // Act\n            TryGetValueDelegate d = TypeHelpers.CreateTryGetValueDelegate(dictionary.GetType());\n\n            object value;\n            bool found = d(dictionary, \"theKey\", out value);\n\n            // Assert\n            Assert.True(found);\n            Assert.Equal(42, value);\n        }\n\n        [Fact]\n        public void CreateTryGetValueDelegateWrapsNonGenericDictionaries()\n        {\n            // Arrange\n            object dictionary = new Hashtable()\n            {\n                { \"foo\", 42 }\n            };\n\n            // Act\n            TryGetValueDelegate d = TypeHelpers.CreateTryGetValueDelegate(dictionary.GetType());\n\n            object fooValue;\n            bool fooIsFound = d(dictionary, \"foo\", out fooValue);\n\n            object barValue;\n            bool barIsFound = d(dictionary, \"bar\", out barValue);\n\n            // Assert\n            Assert.True(fooIsFound);\n            Assert.Equal(42, fooValue);\n            Assert.False(barIsFound);\n            Assert.Null(barValue);\n        }\n\n        [Fact]\n        public void GetDefaultValue_NullableValueType()\n        {\n            // Act\n            object defaultValue = TypeHelpers.GetDefaultValue(typeof(int?));\n\n            // Assert\n            Assert.Equal(default(int?), defaultValue);\n        }\n\n        [Fact]\n        public void GetDefaultValue_ReferenceType()\n        {\n            // Act\n            object defaultValue = TypeHelpers.GetDefaultValue(typeof(object));\n\n            // Assert\n            Assert.Equal(default(object), defaultValue);\n        }\n\n        [Fact]\n        public void GetDefaultValue_ValueType()\n        {\n            // Act\n            object defaultValue = TypeHelpers.GetDefaultValue(typeof(int));\n\n            // Assert\n            Assert.Equal(default(int), defaultValue);\n        }\n\n        [Fact]\n        public void IsCompatibleObjectReturnsTrueIfTypeIsNotNullableAndValueIsNull()\n        {\n            // Act\n            bool retVal = TypeHelpers.IsCompatibleObject<int>(null);\n\n            // Assert\n            Assert.False(retVal);\n        }\n\n        [Fact]\n        public void IsCompatibleObjectReturnsFalseIfValueIsIncorrectType()\n        {\n            // Arrange\n            object value = new string[] { \"Hello\", \"world\" };\n\n            // Act\n            bool retVal = TypeHelpers.IsCompatibleObject<int>(value);\n\n            // Assert\n            Assert.False(retVal);\n        }\n\n        [Fact]\n        public void IsCompatibleObjectReturnsTrueIfTypeIsNullableAndValueIsNull()\n        {\n            // Act\n            bool retVal = TypeHelpers.IsCompatibleObject<int?>(null);\n\n            // Assert\n            Assert.True(retVal);\n        }\n\n        [Fact]\n        public void IsCompatibleObjectReturnsTrueIfValueIsOfCorrectType()\n        {\n            // Arrange\n            object value = new string[] { \"Hello\", \"world\" };\n\n            // Act\n            bool retVal = TypeHelpers.IsCompatibleObject<IEnumerable<string>>(value);\n\n            // Assert\n            Assert.True(retVal);\n        }\n\n        [Fact]\n        public void TypeAllowsNullValueReturnsFalseForNonNullableGenericValueType()\n        {\n            Assert.False(TypeHelpers.TypeAllowsNullValue(typeof(KeyValuePair<int, string>)));\n        }\n\n        [Fact]\n        public void TypeAllowsNullValueReturnsFalseForNonNullableGenericValueTypeDefinition()\n        {\n            Assert.False(TypeHelpers.TypeAllowsNullValue(typeof(KeyValuePair<,>)));\n        }\n\n        [Fact]\n        public void TypeAllowsNullValueReturnsFalseForNonNullableValueType()\n        {\n            Assert.False(TypeHelpers.TypeAllowsNullValue(typeof(int)));\n        }\n\n        [Fact]\n        public void TypeAllowsNullValueReturnsTrueForInterfaceType()\n        {\n            Assert.True(TypeHelpers.TypeAllowsNullValue(typeof(IDisposable)));\n        }\n\n        [Fact]\n        public void TypeAllowsNullValueReturnsTrueForNullableType()\n        {\n            Assert.True(TypeHelpers.TypeAllowsNullValue(typeof(int?)));\n        }\n\n        [Fact]\n        public void TypeAllowsNullValueReturnsTrueForReferenceType()\n        {\n            Assert.True(TypeHelpers.TypeAllowsNullValue(typeof(object)));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/UrlHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\nusing Microsoft.Web.UnitTestUtil;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class UrlHelperTest\n    {\n        [Fact]\n        public void IsLocalUrl_RejectsNull()\n        {\n            UrlHelper helper = GetUrlHelperForIsLocalUrl();\n\n            Assert.False(helper.IsLocalUrl(null));\n        }\n\n        [Fact]\n        public void IsLocalUrl_RejectsEmptyString()\n        {\n            UrlHelper helper = GetUrlHelperForIsLocalUrl();\n\n            Assert.False(helper.IsLocalUrl(String.Empty));\n            Assert.False(helper.IsLocalUrl(\" \"));\n        }\n\n        [Fact]\n        public void IsLocalUrl_AcceptsRootedUrls()\n        {\n            UrlHelper helper = GetUrlHelperForIsLocalUrl();\n            Assert.True(helper.IsLocalUrl(\"/fooo\"));\n            Assert.True(helper.IsLocalUrl(\"/www.hackerz.com\"));\n            Assert.True(helper.IsLocalUrl(\"/\"));\n        }\n\n        [Fact]\n        public void IsLocalUrl_AcceptsAppRelativeUrls()\n        {\n            UrlHelper helper = GetUrlHelperForIsLocalUrl();\n            Assert.True(helper.IsLocalUrl(\"~/\"));\n            Assert.True(helper.IsLocalUrl(\"~/foobar.html\"));\n        }\n\n        [Fact]\n        public void IsLocalUrl_RejectsRelativeUrls()\n        {\n            UrlHelper helper = GetUrlHelperForIsLocalUrl();\n            Assert.False(helper.IsLocalUrl(\"foobar.html\"));\n            Assert.False(helper.IsLocalUrl(\"../foobar.html\"));\n            Assert.False(helper.IsLocalUrl(\"fold/foobar.html\"));\n        }\n\n        [Fact]\n        public void IsLocalUrl_RejectValidButUnsafeRelativeUrls()\n        {\n            UrlHelper helper = GetUrlHelperForIsLocalUrl();\n\n            Assert.False(helper.IsLocalUrl(\"http:/foobar.html\"));\n            Assert.False(helper.IsLocalUrl(\"hTtP:foobar.html\"));\n            Assert.False(helper.IsLocalUrl(\"http:/www.hackerz.com\"));\n            Assert.False(helper.IsLocalUrl(\"HtTpS:/www.hackerz.com\"));\n        }\n\n        [Fact]\n        public void IsLocalUrl_RejectsUrlsOnTheSameHost()\n        {\n            UrlHelper helper = GetUrlHelperForIsLocalUrl();\n\n            Assert.False(helper.IsLocalUrl(\"http://www.mysite.com/appDir/foobar.html\"));\n            Assert.False(helper.IsLocalUrl(\"http://WWW.MYSITE.COM\"));\n        }\n\n        [Fact]\n        public void IsLocalUrl_RejectsUrlsOnLocalHost()\n        {\n            UrlHelper helper = GetUrlHelperForIsLocalUrl();\n\n            Assert.False(helper.IsLocalUrl(\"http://localhost/foobar.html\"));\n            Assert.False(helper.IsLocalUrl(\"http://127.0.0.1/foobar.html\"));\n        }\n\n        [Fact]\n        public void IsLocalUrl_RejectsUrlsOnTheSameHostButDifferentScheme()\n        {\n            UrlHelper helper = GetUrlHelperForIsLocalUrl();\n\n            Assert.False(helper.IsLocalUrl(\"https://www.mysite.com/\"));\n        }\n\n        [Fact]\n        public void IsLocalUrl_RejectsUrlsOnDifferentHost()\n        {\n            UrlHelper helper = GetUrlHelperForIsLocalUrl();\n\n            Assert.False(helper.IsLocalUrl(\"http://www.hackerz.com\"));\n            Assert.False(helper.IsLocalUrl(\"https://www.hackerz.com\"));\n            Assert.False(helper.IsLocalUrl(\"hTtP://www.hackerz.com\"));\n            Assert.False(helper.IsLocalUrl(\"HtTpS://www.hackerz.com\"));\n        }\n\n        [Fact]\n        public void IsLocalUrl_RejectsUrlsWithTooManySchemeSeparatorCharacters()\n        {\n            UrlHelper helper = GetUrlHelperForIsLocalUrl();\n\n            Assert.False(helper.IsLocalUrl(\"http://///www.hackerz.com/foobar.html\"));\n            Assert.False(helper.IsLocalUrl(\"https://///www.hackerz.com/foobar.html\"));\n            Assert.False(helper.IsLocalUrl(\"HtTpS://///www.hackerz.com/foobar.html\"));\n\n            Assert.False(helper.IsLocalUrl(\"http:///www.hackerz.com/foobar.html\"));\n            Assert.False(helper.IsLocalUrl(\"http:////www.hackerz.com/foobar.html\"));\n            Assert.False(helper.IsLocalUrl(\"http://///www.hackerz.com/foobar.html\"));\n        }\n\n        [Fact]\n        public void IsLocalUrl_RejectsUrlsWithMissingSchemeName()\n        {\n            UrlHelper helper = GetUrlHelperForIsLocalUrl();\n\n            Assert.False(helper.IsLocalUrl(\"//www.hackerz.com\"));\n            Assert.False(helper.IsLocalUrl(\"//www.hackerz.com/foobar.html\"));\n            Assert.False(helper.IsLocalUrl(\"///www.hackerz.com\"));\n            Assert.False(helper.IsLocalUrl(\"//////www.hackerz.com\"));\n        }\n\n        [Fact]\n        public void IsLocalUrl_RejectsInvalidUrls()\n        {\n            UrlHelper helper = GetUrlHelperForIsLocalUrl();\n\n            Assert.False(helper.IsLocalUrl(@\"http:\\\\www.hackerz.com\"));\n            Assert.False(helper.IsLocalUrl(@\"http:\\\\www.hackerz.com\\\"));\n        }\n\n        [Fact]\n        public void RequestContextProperty()\n        {\n            // Arrange\n            RequestContext requestContext = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData());\n            UrlHelper urlHelper = new UrlHelper(requestContext);\n\n            // Assert\n            Assert.Equal(requestContext, urlHelper.RequestContext);\n        }\n\n        [Fact]\n        public void ConstructorWithNullRequestContextThrows()\n        {\n            // Assert\n            Assert.ThrowsArgumentNull(\n                delegate { new UrlHelper(null); },\n                \"requestContext\");\n        }\n\n        [Fact]\n        public void ConstructorWithNullRouteCollectionThrows()\n        {\n            // Assert\n            Assert.ThrowsArgumentNull(\n                delegate { new UrlHelper(GetRequestContext(), null); },\n                \"routeCollection\");\n        }\n\n        [Fact]\n        public void ActionEmpty()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act\n            string url = urlHelper.Action();\n\n            // Assert\n            Assert.Equal(\"/app/\", url);\n        }\n\n        [Fact]\n        public void Action()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act\n            string url = urlHelper.Action(\"newaction\");\n\n            // Assert\n            Assert.Equal(MvcHelper.AppPathModifier + \"/app/home/newaction\", url);\n        }\n\n        [Fact]\n        public void ActionWithControllerName()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act\n            string url = urlHelper.Action(\"newaction\", \"home2\");\n\n            // Assert\n            Assert.Equal(MvcHelper.AppPathModifier + \"/app/home2/newaction\", url);\n        }\n\n        [Fact]\n        public void ActionWithControllerNameAndDictionary()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act\n            string url = urlHelper.Action(\"newaction\", \"home2\", new RouteValueDictionary(new { id = \"someid\" }));\n\n            // Assert\n            Assert.Equal(MvcHelper.AppPathModifier + \"/app/home2/newaction/someid\", url);\n        }\n\n        [Fact]\n        public void ActionWithControllerNameAndObjectProperties()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act\n            string url = urlHelper.Action(\"newaction\", \"home2\", new { id = \"someid\" });\n\n            // Assert\n            Assert.Equal(MvcHelper.AppPathModifier + \"/app/home2/newaction/someid\", url);\n        }\n\n        [Fact]\n        public void ActionWithDictionary()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act\n            string url = urlHelper.Action(\"newaction\", new RouteValueDictionary(new { Controller = \"home2\", id = \"someid\" }));\n\n            // Assert\n            Assert.Equal(MvcHelper.AppPathModifier + \"/app/home2/newaction/someid\", url);\n        }\n\n        [Fact]\n        public void ActionWithNullActionName()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act\n            string url = urlHelper.Action(null);\n\n            // Assert\n            Assert.Equal(MvcHelper.AppPathModifier + \"/app/home/oldaction\", url);\n        }\n\n        [Fact]\n        public void ActionWithNullProtocol()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act\n            string url = urlHelper.Action(\"newaction\", \"home2\", new { id = \"someid\" }, null /* protocol */);\n\n            // Assert\n            Assert.Equal(MvcHelper.AppPathModifier + \"/app/home2/newaction/someid\", url);\n        }\n\n        [Fact]\n        public void ActionParameterOverridesObjectProperties()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act\n            string url = urlHelper.Action(\"newaction\", new { Action = \"action\" });\n\n            // Assert\n            Assert.Equal(MvcHelper.AppPathModifier + \"/app/home/newaction\", url);\n        }\n\n        [Fact]\n        public void ActionWithObjectProperties()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act\n            string url = urlHelper.Action(\"newaction\", new { Controller = \"home2\", id = \"someid\" });\n\n            // Assert\n            Assert.Equal(MvcHelper.AppPathModifier + \"/app/home2/newaction/someid\", url);\n        }\n\n        [Fact]\n        public void ActionWithProtocol()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act\n            string url = urlHelper.Action(\"newaction\", \"home2\", new { id = \"someid\" }, \"https\");\n\n            // Assert\n            Assert.Equal(\"https://localhost\" + MvcHelper.AppPathModifier + \"/app/home2/newaction/someid\", url);\n        }\n\n        [Fact]\n        public void ActionWithProtocolAndRouteValueDictionary()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act\n            string url = urlHelper.Action(\"newaction\", \"home2\", new RouteValueDictionary(new { id = \"someid\" }), \"https\");\n\n            // Assert\n            Assert.Equal(\"https://localhost\" + MvcHelper.AppPathModifier + \"/app/home2/newaction/someid\", url);\n        }\n\n        [Fact]\n        public void ContentWithAbsolutePath()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act\n            string url = urlHelper.Content(\"/Content/Image.jpg\");\n\n            // Assert\n            Assert.Equal(\"/Content/Image.jpg\", url);\n        }\n\n        [Fact]\n        public void ContentWithAppRelativePath()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act\n            string url = urlHelper.Content(\"~/Content/Image.jpg\");\n\n            // Assert\n            Assert.Equal(\"/app/Content/Image.jpg\", url);\n        }\n\n        [Fact]\n        public void ContentWithEmptyPathThrows()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate() { urlHelper.Content(String.Empty); },\n                \"contentPath\");\n        }\n\n        [Fact]\n        public void ContentWithRelativePath()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act\n            string url = urlHelper.Content(\"Content/Image.jpg\");\n\n            // Assert\n            Assert.Equal(\"Content/Image.jpg\", url);\n        }\n\n        [Fact]\n        public void ContentWithExternalUrl()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act\n            string url = urlHelper.Content(\"http://www.asp.net/App_Themes/Standard/i/logo.png\");\n\n            // Assert\n            Assert.Equal(\"http://www.asp.net/App_Themes/Standard/i/logo.png\", url);\n        }\n\n        [Fact]\n        public void Encode()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act\n            string encodedUrl = urlHelper.Encode(@\"SomeUrl /+\\\");\n\n            // Assert\n            Assert.Equal(\"SomeUrl+%2f%2b%5c\", encodedUrl);\n        }\n\n        [Fact]\n        public void GenerateContentUrlWithNullContentPathThrows()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate() { UrlHelper.GenerateContentUrl(null, null); },\n                \"contentPath\");\n        }\n\n        [Fact]\n        public void GenerateContentUrlWithNullContextThrows()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate() { UrlHelper.GenerateContentUrl(\"Content/foo.png\", null); },\n                \"httpContext\");\n        }\n\n        [Fact]\n        public void GenerateUrlWithNullRequestContextThrows()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate() { UrlHelper.GenerateUrl(null /* routeName */, null /* actionName */, null /* controllerName */, null /* routeValues */, new RouteCollection(), null /* requestContext */, false); },\n                \"requestContext\");\n        }\n\n        [Fact]\n        public void GenerateUrlWithNullRouteCollectionThrows()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate() { UrlHelper.GenerateUrl(null /* routeName */, null /* actionName */, null /* controllerName */, null /* routeValues */, null /* routeCollection */, null /* requestContext */, false); },\n                \"routeCollection\");\n        }\n\n        [Fact]\n        public void GenerateUrlWithEmptyCollectionsReturnsNull()\n        {\n            // Arrange\n            RequestContext requestContext = GetRequestContext();\n\n            // Act\n            string url = UrlHelper.GenerateUrl(null, null, null, null, new RouteCollection(), requestContext, true);\n\n            // Assert\n            Assert.Null(url);\n        }\n\n        [Fact]\n        public void GenerateUrlWithAction()\n        {\n            // Arrange\n            RequestContext requestContext = GetRequestContext(GetRouteData());\n\n            // Act\n            string url = UrlHelper.GenerateUrl(null, \"newaction\", null, null, GetRouteCollection(), requestContext, true);\n\n            // Assert\n            Assert.Equal(MvcHelper.AppPathModifier + \"/app/home/newaction\", url);\n        }\n\n        [Fact]\n        public void GenerateUrlWithActionAndController()\n        {\n            // Arrange\n            RequestContext requestContext = GetRequestContext(GetRouteData());\n\n            // Act\n            string url = UrlHelper.GenerateUrl(null, \"newaction\", \"newcontroller\", null, GetRouteCollection(), requestContext, true);\n\n            // Assert\n            Assert.Equal(MvcHelper.AppPathModifier + \"/app/newcontroller/newaction\", url);\n        }\n\n        [Fact]\n        public void GenerateUrlWithImplicitValues()\n        {\n            // Arrange\n            RequestContext requestContext = GetRequestContext(GetRouteData());\n\n            // Act\n            string url = UrlHelper.GenerateUrl(null, null, null, null, GetRouteCollection(), requestContext, true);\n\n            // Assert\n            Assert.Equal(MvcHelper.AppPathModifier + \"/app/home/oldaction\", url);\n        }\n\n        [Fact]\n        public void RouteUrlCanUseNamedRouteWithoutSpecifyingDefaults()\n        {\n            // DevDiv 217072: Non-mvc specific helpers should not give default values for controller and action\n\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n            urlHelper.RouteCollection.MapRoute(\"MyRouteName\", \"any/url\", new { controller = \"Charlie\" });\n\n            // Act\n            string result = urlHelper.RouteUrl(\"MyRouteName\");\n\n            // Assert\n            Assert.Equal(MvcHelper.AppPathModifier + \"/app/any/url\", result);\n        }\n\n        [Fact]\n        public void RouteUrlWithDictionary()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act\n            string url = urlHelper.RouteUrl(new RouteValueDictionary(new { Action = \"newaction\", Controller = \"home2\", id = \"someid\" }));\n\n            // Assert\n            Assert.Equal(MvcHelper.AppPathModifier + \"/app/home2/newaction/someid\", url);\n        }\n\n        [Fact]\n        public void RouteUrlWithEmptyHostName()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act\n            string url = urlHelper.RouteUrl(\"namedroute\", new RouteValueDictionary(new { Action = \"newaction\", Controller = \"home2\", id = \"someid\" }), \"http\", String.Empty /* hostName */);\n\n            // Assert\n            Assert.Equal(\"http://localhost\" + MvcHelper.AppPathModifier + \"/app/named/home2/newaction/someid\", url);\n        }\n\n        [Fact]\n        public void RouteUrlWithEmptyProtocol()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act\n            string url = urlHelper.RouteUrl(\"namedroute\", new RouteValueDictionary(new { Action = \"newaction\", Controller = \"home2\", id = \"someid\" }), String.Empty /* protocol */, \"foo.bar.com\");\n\n            // Assert\n            Assert.Equal(\"http://foo.bar.com\" + MvcHelper.AppPathModifier + \"/app/named/home2/newaction/someid\", url);\n        }\n\n        [Fact]\n        public void RouteUrlWithNullProtocol()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act\n            string url = urlHelper.RouteUrl(\"namedroute\", new RouteValueDictionary(new { Action = \"newaction\", Controller = \"home2\", id = \"someid\" }), null /* protocol */, \"foo.bar.com\");\n\n            // Assert\n            Assert.Equal(\"http://foo.bar.com\" + MvcHelper.AppPathModifier + \"/app/named/home2/newaction/someid\", url);\n        }\n\n        [Fact]\n        public void RouteUrlWithNullProtocolAndNullHostName()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act\n            string url = urlHelper.RouteUrl(\"namedroute\", new RouteValueDictionary(new { Action = \"newaction\", Controller = \"home2\", id = \"someid\" }), null /* protocol */, null /* hostName */);\n\n            // Assert\n            Assert.Equal(MvcHelper.AppPathModifier + \"/app/named/home2/newaction/someid\", url);\n        }\n\n        [Fact]\n        public void RouteUrlWithObjectProperties()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act\n            string url = urlHelper.RouteUrl(new { Action = \"newaction\", Controller = \"home2\", id = \"someid\" });\n\n            // Assert\n            Assert.Equal(MvcHelper.AppPathModifier + \"/app/home2/newaction/someid\", url);\n        }\n\n        [Fact]\n        public void RouteUrlWithProtocol()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act\n            string url = urlHelper.RouteUrl(\"namedroute\", new { Action = \"newaction\", Controller = \"home2\", id = \"someid\" }, \"https\");\n\n            // Assert\n            Assert.Equal(\"https://localhost\" + MvcHelper.AppPathModifier + \"/app/named/home2/newaction/someid\", url);\n        }\n\n        [Fact]\n        public void RouteUrlWithRouteNameAndDefaults()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act\n            string url = urlHelper.RouteUrl(\"namedroute\");\n\n            // Assert\n            Assert.Equal(MvcHelper.AppPathModifier + \"/app/named/home/oldaction\", url);\n        }\n\n        [Fact]\n        public void RouteUrlWithRouteNameAndDictionary()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act\n            string url = urlHelper.RouteUrl(\"namedroute\", new RouteValueDictionary(new { Action = \"newaction\", Controller = \"home2\", id = \"someid\" }));\n\n            // Assert\n            Assert.Equal(MvcHelper.AppPathModifier + \"/app/named/home2/newaction/someid\", url);\n        }\n\n        [Fact]\n        public void RouteUrlWithRouteNameAndObjectProperties()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act\n            string url = urlHelper.RouteUrl(\"namedroute\", new { Action = \"newaction\", Controller = \"home2\", id = \"someid\" });\n\n            // Assert\n            Assert.Equal(MvcHelper.AppPathModifier + \"/app/named/home2/newaction/someid\", url);\n        }\n\n        [Fact]\n        public void HttpRouteUrlFindsHttpRoute()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n\n            // Act\n            string url = urlHelper.HttpRouteUrl(\"httproute\", new { Action = \"newaction\", Controller = \"home2\", id = \"someid\" });\n\n            // Assert\n            Assert.Equal(MvcHelper.AppPathModifier + \"/app/mock/http/route\", url);\n        }\n\n        [Fact]\n        public void UrlGenerationDoesNotChangeProvidedDictionary()\n        {\n            // Arrange\n            UrlHelper urlHelper = GetUrlHelper();\n            RouteValueDictionary valuesDictionary = new RouteValueDictionary();\n\n            // Act\n            urlHelper.Action(\"actionName\", valuesDictionary);\n\n            // Assert\n            Assert.Empty(valuesDictionary);\n            Assert.False(valuesDictionary.ContainsKey(\"action\"));\n        }\n\n        [Fact]\n        public void UrlGenerationReturnsNullWhenSubsequentSegmentHasValue()\n        { // Dev10 Bug #924729\n            // Arrange\n            RouteCollection routes = new RouteCollection();\n            routes.MapRoute(\"SampleRoute\", \"testing/{a}/{b}/{c}\",\n                            new\n                            {\n                                controller = \"controller\",\n                                action = \"action\",\n                                b = UrlParameter.Optional,\n                                c = UrlParameter.Optional\n                            });\n\n            UrlHelper helper = GetUrlHelper(routeCollection: routes);\n\n            // Act\n            string url = helper.Action(\"action\", \"controller\", new { a = 42, c = 2112 });\n\n            // Assert\n            Assert.Null(url);\n        }\n\n        private static RequestContext GetRequestContext()\n        {\n            HttpContextBase httpcontext = MvcHelper.GetHttpContext(\"/app/\", null, null);\n            RouteData rd = new RouteData();\n            return new RequestContext(httpcontext, rd);\n        }\n\n        private static RequestContext GetRequestContext(RouteData routeData)\n        {\n            HttpContextBase httpcontext = MvcHelper.GetHttpContext(\"/app/\", null, null);\n            return new RequestContext(httpcontext, routeData);\n        }\n\n        private static RouteCollection GetRouteCollection()\n        {\n            RouteCollection rt = new RouteCollection();\n            rt.Add(new Route(\"{controller}/{action}/{id}\", null) { Defaults = new RouteValueDictionary(new { id = \"defaultid\" }) });\n            rt.Add(\"namedroute\", new Route(\"named/{controller}/{action}/{id}\", null) { Defaults = new RouteValueDictionary(new { id = \"defaultid\" }) });\n\n            // Adding a route that recognizes the httproute value for the HttpRouteUrl tests\n            Mock<RouteBase> mockHttpRoute = new Mock<RouteBase>();\n            mockHttpRoute.Setup(mock => mock.GetVirtualPath(It.IsAny<RequestContext>(), It.Is<RouteValueDictionary>(routeValues => routeValues.ContainsKey(\"httproute\"))))\n                .Returns(new VirtualPathData(null, \"mock/http/route\"));\n            rt.Add(\"httproute\", mockHttpRoute.Object);\n\n            return rt;\n        }\n\n        private static RouteData GetRouteData()\n        {\n            RouteData rd = new RouteData();\n            rd.Values.Add(\"controller\", \"home\");\n            rd.Values.Add(\"action\", \"oldaction\");\n            return rd;\n        }\n\n        private static UrlHelper GetUrlHelper()\n        {\n            return GetUrlHelper(GetRouteData(), GetRouteCollection());\n        }\n\n        private static UrlHelper GetUrlHelper(RouteData routeData = null, RouteCollection routeCollection = null)\n        {\n            HttpContextBase httpcontext = MvcHelper.GetHttpContext(\"/app/\", null, null);\n            UrlHelper urlHelper = new UrlHelper(new RequestContext(httpcontext, routeData ?? new RouteData()), routeCollection ?? new RouteCollection());\n            return urlHelper;\n        }\n\n        private static UrlHelper GetUrlHelperForIsLocalUrl()\n        {\n            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>();\n            contextMock.SetupGet(context => context.Request.Url).Returns(new Uri(\"http://www.mysite.com/\"));\n            RequestContext requestContext = new RequestContext(contextMock.Object, new RouteData());\n            UrlHelper helper = new UrlHelper(requestContext);\n            return helper;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/UrlParameterTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class UrlParameterTest\n    {\n        [Fact]\n        public void UrlParameterOptionalToStringReturnsEmptyString()\n        {\n            // Act & Assert\n            Assert.Empty(UrlParameter.Optional.ToString());\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ValidatableObjectAdapterTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")] // Uses ModelMetadataProviders.Current\n    public class ValidatableObjectAdapterTest\n    {\n        // IValidatableObject support\n\n        [Fact]\n        public void NonIValidatableObjectInsideMetadataThrows()\n        {\n            // Arrange\n            var context = new ControllerContext();\n            var validatable = new Mock<IValidatableObject>();\n            var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => 42, typeof(IValidatableObject));\n            var validator = new ValidatableObjectAdapter(metadata, context);\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => validator.Validate(null),\n                \"The model object inside the metadata claimed to be compatible with System.ComponentModel.DataAnnotations.IValidatableObject, but was actually System.Int32.\");\n        }\n\n        [Fact]\n        public void IValidatableObjectGetsAProperlyPopulatedValidationContext()\n        {\n            // Arrange\n            var context = new ControllerContext();\n            var validatable = new Mock<IValidatableObject>();\n            var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => validatable.Object, validatable.Object.GetType());\n            var validator = new ValidatableObjectAdapter(metadata, context);\n            ValidationContext validationContext = null;\n            validatable.Setup(vo => vo.Validate(It.IsAny<ValidationContext>()))\n                .Callback<ValidationContext>(vc => validationContext = vc)\n                .Returns(Enumerable.Empty<ValidationResult>())\n                .Verifiable();\n\n            // Act\n            validator.Validate(null);\n\n            // Assert\n            validatable.Verify();\n            Assert.Same(validatable.Object, validationContext.ObjectInstance);\n            Assert.Null(validationContext.MemberName);\n        }\n\n        [Fact]\n        public void IValidatableObjectWithNoErrors()\n        {\n            // Arrange\n            var context = new ControllerContext();\n            var validatable = new Mock<IValidatableObject>();\n            var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => validatable.Object, validatable.Object.GetType());\n            var validator = new ValidatableObjectAdapter(metadata, context);\n            validatable.Setup(vo => vo.Validate(It.IsAny<ValidationContext>()))\n                .Returns(Enumerable.Empty<ValidationResult>());\n\n            // Act\n            IEnumerable<ModelValidationResult> results = validator.Validate(null);\n\n            // Assert\n            Assert.Empty(results);\n        }\n\n        [Fact]\n        public void IValidatableObjectWithModelLevelError()\n        {\n            // Arrange\n            var context = new ControllerContext();\n            var validatable = new Mock<IValidatableObject>();\n            var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => validatable.Object, validatable.Object.GetType());\n            var validator = new ValidatableObjectAdapter(metadata, context);\n            validatable.Setup(vo => vo.Validate(It.IsAny<ValidationContext>()))\n                .Returns(new ValidationResult[] { new ValidationResult(\"Error Message\") });\n\n            // Act\n            ModelValidationResult result = validator.Validate(null).Single();\n\n            // Assert\n            Assert.Equal(\"Error Message\", result.Message);\n            Assert.Equal(String.Empty, result.MemberName);\n        }\n\n        [Fact]\n        public void IValidatableObjectWithMultipleModelLevelErrors()\n        {\n            // Arrange\n            var context = new ControllerContext();\n            var validatable = new Mock<IValidatableObject>();\n            var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => validatable.Object, validatable.Object.GetType());\n            var validator = new ValidatableObjectAdapter(metadata, context);\n            validatable.Setup(vo => vo.Validate(It.IsAny<ValidationContext>()))\n                .Returns(new ValidationResult[]\n                {\n                    new ValidationResult(\"Error Message 1\"),\n                    new ValidationResult(\"Error Message 2\")\n                });\n\n            // Act\n            ModelValidationResult[] results = validator.Validate(null).ToArray();\n\n            // Assert\n            Assert.Equal(2, results.Length);\n            Assert.Equal(\"Error Message 1\", results[0].Message);\n            Assert.Equal(\"Error Message 2\", results[1].Message);\n        }\n\n        [Fact]\n        public void IValidatableObjectWithMultiPropertyValidationFailure()\n        {\n            // Arrange\n            var context = new ControllerContext();\n            var validatable = new Mock<IValidatableObject>();\n            var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => validatable.Object, validatable.Object.GetType());\n            var validator = new ValidatableObjectAdapter(metadata, context);\n            validatable.Setup(vo => vo.Validate(It.IsAny<ValidationContext>()))\n                .Returns(new[] { new ValidationResult(\"Error Message\", new[] { \"Property1\", \"Property2\" }) })\n                .Verifiable();\n\n            // Act\n            ModelValidationResult[] results = validator.Validate(null).ToArray();\n\n            // Assert\n            validatable.Verify();\n            Assert.Equal(2, results.Length);\n            Assert.Equal(\"Error Message\", results[0].Message);\n            Assert.Equal(\"Property1\", results[0].MemberName);\n            Assert.Equal(\"Error Message\", results[1].Message);\n            Assert.Equal(\"Property2\", results[1].MemberName);\n        }\n\n        [Fact]\n        public void IValidatableObjectWhichIsNullReturnsNoErrors()\n        {\n            // Arrange\n            var context = new ControllerContext();\n            var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => null, typeof(IValidatableObject));\n            var validator = new ValidatableObjectAdapter(metadata, context);\n\n            // Act\n            IEnumerable<ModelValidationResult> results = validator.Validate(null);\n\n            // Assert\n            Assert.Empty(results);\n        }\n\n        [Fact]\n        public void IValidatableObjectWhichReturnsValidationResultSuccessReturnsNoErrors()\n        {\n            // Arrange\n            var context = new ControllerContext();\n            var validatable = new Mock<IValidatableObject>();\n            var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => validatable.Object, validatable.Object.GetType());\n            var validator = new ValidatableObjectAdapter(metadata, context);\n            validatable.Setup(vo => vo.Validate(It.IsAny<ValidationContext>()))\n                .Returns(new[] { ValidationResult.Success })\n                .Verifiable();\n\n            // Act\n            ModelValidationResult[] results = validator.Validate(null).ToArray();\n\n            // Assert\n            validatable.Verify();\n            Assert.Empty(results);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ValidateAntiForgeryTokenAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Helpers;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ValidateAntiForgeryTokenAttributeTest\n    {\n        [Fact]\n        public void OnAuthorization_ThrowsIfFilterContextIsNull()\n        {\n            // Arrange\n            ValidateAntiForgeryTokenAttribute attribute = new ValidateAntiForgeryTokenAttribute();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { attribute.OnAuthorization(null); }, \"filterContext\");\n        }\n\n        [Fact]\n        public void OnAuthorization_ForwardsAttributes()\n        {\n            // Arrange\n            HttpContextBase context = new Mock<HttpContextBase>().Object;\n            Mock<AuthorizationContext> authorizationContextMock = new Mock<AuthorizationContext>();\n            authorizationContextMock.SetupGet(ac => ac.HttpContext).Returns(context);\n            bool validateCalled = false;\n            Action validateMethod = () =>\n            {\n                validateCalled = true;\n            };\n            ValidateAntiForgeryTokenAttribute attribute = new ValidateAntiForgeryTokenAttribute(validateMethod);\n\n            // Act\n            attribute.OnAuthorization(authorizationContextMock.Object);\n\n            // Assert\n            Assert.True(validateCalled);\n        }\n\n        [Fact]\n        public void ValidateThunk_DefaultsToAntiForgeryMethod()\n        {\n            // Arrange\n            ValidateAntiForgeryTokenAttribute attribute = new ValidateAntiForgeryTokenAttribute();\n\n            // Act & Assert\n            Assert.Equal(AntiForgery.Validate, attribute.ValidateAction);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ValidateInputAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ValidateInputAttributeTest\n    {\n        [Fact]\n        public void EnableValidationProperty()\n        {\n            // Act\n            ValidateInputAttribute attrTrue = new ValidateInputAttribute(true);\n            ValidateInputAttribute attrFalse = new ValidateInputAttribute(false);\n\n            // Assert\n            Assert.True(attrTrue.EnableValidation);\n            Assert.False(attrFalse.EnableValidation);\n        }\n\n        [Fact]\n        public void OnAuthorizationSetsControllerValidateRequestToFalse()\n        {\n            // Arrange\n            Controller controller = new EmptyController() { ValidateRequest = true };\n            ValidateInputAttribute attr = new ValidateInputAttribute(enableValidation: false);\n            AuthorizationContext authContext = GetAuthorizationContext(controller);\n\n            // Act\n            attr.OnAuthorization(authContext);\n\n            // Assert\n            Assert.False(controller.ValidateRequest);\n        }\n\n        [Fact]\n        public void OnAuthorizationSetsControllerValidateRequestToTrue()\n        {\n            // Arrange\n            Controller controller = new EmptyController() { ValidateRequest = false };\n            ValidateInputAttribute attr = new ValidateInputAttribute(enableValidation: true);\n            AuthorizationContext authContext = GetAuthorizationContext(controller);\n\n            // Act\n            attr.OnAuthorization(authContext);\n\n            // Assert\n            Assert.True(controller.ValidateRequest);\n        }\n\n        [Fact]\n        public void OnAuthorizationThrowsIfFilterContextIsNull()\n        {\n            // Arrange\n            ValidateInputAttribute attr = new ValidateInputAttribute(true);\n\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { attr.OnAuthorization(null); }, \"filterContext\");\n        }\n\n        private static AuthorizationContext GetAuthorizationContext(ControllerBase controller)\n        {\n            Mock<AuthorizationContext> mockAuthContext = new Mock<AuthorizationContext>();\n            mockAuthContext.Setup(c => c.Controller).Returns(controller);\n            return mockAuthContext.Object;\n        }\n\n        private class EmptyController : Controller\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ValueProviderCollectionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ValueProviderCollectionTest\n    {\n        [Fact]\n        public void ListWrappingConstructor()\n        {\n            // Arrange\n            List<IValueProvider> list = new List<IValueProvider>()\n            {\n                new Mock<IValueProvider>().Object, new Mock<IValueProvider>().Object\n            };\n\n            // Act\n            ValueProviderCollection collection = new ValueProviderCollection(list);\n\n            // Assert\n            Assert.Equal(list, collection.ToList());\n        }\n\n        [Fact]\n        public void ListWrappingConstructorThrowsIfListIsNull()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ValueProviderCollection(null); },\n                \"list\");\n        }\n\n        [Fact]\n        public void DefaultConstructor()\n        {\n            // Act\n            ValueProviderCollection collection = new ValueProviderCollection();\n\n            // Assert\n            Assert.Empty(collection);\n        }\n\n        [Fact]\n        public void AddNullValueProviderThrows()\n        {\n            // Arrange\n            ValueProviderCollection collection = new ValueProviderCollection();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { collection.Add(null); },\n                \"item\");\n        }\n\n        [Fact]\n        public void SetItem()\n        {\n            // Arrange\n            ValueProviderCollection collection = new ValueProviderCollection();\n            collection.Add(new Mock<IValueProvider>().Object);\n\n            IValueProvider newProvider = new Mock<IValueProvider>().Object;\n\n            // Act\n            collection[0] = newProvider;\n\n            // Assert\n            IValueProvider provider = Assert.Single(collection);\n            Assert.Equal(newProvider, provider);\n        }\n\n        [Fact]\n        public void SetNullValueProviderThrows()\n        {\n            // Arrange\n            ValueProviderCollection collection = new ValueProviderCollection();\n            collection.Add(new Mock<IValueProvider>().Object);\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { collection[0] = null; },\n                \"item\");\n        }\n\n        [Fact]\n        public void ContainsPrefix()\n        {\n            // Arrange\n            string prefix = \"somePrefix\";\n\n            Mock<IValueProvider> mockProvider1 = new Mock<IValueProvider>();\n            mockProvider1.Setup(p => p.ContainsPrefix(prefix)).Returns(false);\n            Mock<IValueProvider> mockProvider2 = new Mock<IValueProvider>();\n            mockProvider2.Setup(p => p.ContainsPrefix(prefix)).Returns(true);\n            Mock<IValueProvider> mockProvider3 = new Mock<IValueProvider>();\n            mockProvider3.Setup(p => p.ContainsPrefix(prefix)).Returns(false);\n\n            ValueProviderCollection collection = new ValueProviderCollection()\n            {\n                mockProvider1.Object, mockProvider2.Object, mockProvider3.Object\n            };\n\n            // Act\n            bool retVal = collection.ContainsPrefix(prefix);\n\n            // Assert\n            Assert.True(retVal);\n        }\n\n        [Fact]\n        public void GetValue()\n        {\n            // Arrange\n            string key = \"someKey\";\n\n            Mock<IValueProvider> mockProvider1 = new Mock<IValueProvider>();\n            mockProvider1.Setup(p => p.GetValue(key)).Returns((ValueProviderResult)null);\n            Mock<IValueProvider> mockProvider2 = new Mock<IValueProvider>();\n            mockProvider2.Setup(p => p.GetValue(key)).Returns(new ValueProviderResult(\"2\", \"2\", null));\n            Mock<IValueProvider> mockProvider3 = new Mock<IValueProvider>();\n            mockProvider3.Setup(p => p.GetValue(key)).Returns(new ValueProviderResult(\"3\", \"3\", null));\n\n            ValueProviderCollection collection = new ValueProviderCollection()\n            {\n                mockProvider1.Object, mockProvider2.Object, mockProvider3.Object\n            };\n\n            // Act\n            ValueProviderResult result = collection.GetValue(key);\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Equal(2, result.ConvertTo(typeof(int)));\n        }\n\n        [Fact]\n        public void GetValueFromProvider_NormalProvider_DoNotSkipValidation()\n        {\n            // Arrange\n            ValueProviderResult expectedResult = new ValueProviderResult(\"Success\", \"Success\", null);\n\n            Mock<IValueProvider> mockProvider = new Mock<IValueProvider>();\n            mockProvider.Setup(o => o.GetValue(\"key\")).Returns(expectedResult);\n\n            // Act\n            ValueProviderResult actualResult = ValueProviderCollection.GetValueFromProvider(mockProvider.Object, \"key\", skipValidation: false);\n\n            // Assert\n            Assert.Equal(expectedResult, actualResult);\n        }\n\n        [Fact]\n        public void GetValueFromProvider_NormalProvider_SkipValidation()\n        {\n            // Arrange\n            ValueProviderResult expectedResult = new ValueProviderResult(\"Success\", \"Success\", null);\n\n            Mock<IValueProvider> mockProvider = new Mock<IValueProvider>();\n            mockProvider.Setup(o => o.GetValue(\"key\")).Returns(expectedResult);\n\n            // Act\n            ValueProviderResult actualResult = ValueProviderCollection.GetValueFromProvider(mockProvider.Object, \"key\", skipValidation: true);\n\n            // Assert\n            Assert.Equal(expectedResult, actualResult);\n        }\n\n        [Fact]\n        public void GetValueFromProvider_UnvalidatedProvider_DoNotSkipValidation()\n        {\n            // Arrange\n            ValueProviderResult expectedResult = new ValueProviderResult(\"Success\", \"Success\", null);\n\n            Mock<IUnvalidatedValueProvider> mockProvider = new Mock<IUnvalidatedValueProvider>();\n            mockProvider.Setup(o => o.GetValue(\"key\", false)).Returns(expectedResult);\n\n            // Act\n            ValueProviderResult actualResult = ValueProviderCollection.GetValueFromProvider(mockProvider.Object, \"key\", skipValidation: false);\n\n            // Assert\n            Assert.Equal(expectedResult, actualResult);\n        }\n\n        [Fact]\n        public void GetValueFromProvider_UnvalidatedProvider_SkipValidation()\n        {\n            // Arrange\n            ValueProviderResult expectedResult = new ValueProviderResult(\"Success\", \"Success\", null);\n\n            Mock<IUnvalidatedValueProvider> mockProvider = new Mock<IUnvalidatedValueProvider>();\n            mockProvider.Setup(o => o.GetValue(\"key\", true)).Returns(expectedResult);\n\n            // Act\n            ValueProviderResult actualResult = ValueProviderCollection.GetValueFromProvider(mockProvider.Object, \"key\", skipValidation: true);\n\n            // Assert\n            Assert.Equal(expectedResult, actualResult);\n        }\n\n        [Fact]\n        public void GetValueFromProvider_EnumeratedProvider_GoodPrefix()\n        {\n            // Arrange\n            IDictionary<string, string> expectedResult = new Dictionary<string, string>()\n            {\n                { \"random\", \"random.hello\" }\n            };\n\n            Mock<IEnumerableValueProvider> mockProvider = new Mock<IEnumerableValueProvider>();\n            mockProvider.Setup(o => o.GetKeysFromPrefix(\"prefix\")).Returns(expectedResult);\n\n            ValueProviderCollection providerCollection = new ValueProviderCollection(new List<IValueProvider>() { mockProvider.Object });\n\n            // Act\n            IDictionary<string, string> actualResult = providerCollection.GetKeysFromPrefix(\"prefix\");\n\n            // Assert\n            Assert.Equal(expectedResult, actualResult);\n        }\n\n        [Fact]\n        public void GetValueFromProvider_EnumeratedProvider_NotFound_DoNotReturnNull()\n        {\n            // Arrange\n            IDictionary<string, string> expectedResult = new Dictionary<string, string>()\n            {\n                { \"random\", \"random.hello\" }\n            };\n\n            Mock<IEnumerableValueProvider> mockProvider = new Mock<IEnumerableValueProvider>();\n            mockProvider.Setup(o => o.GetKeysFromPrefix(\"notfound\")).Returns(expectedResult);\n\n            ValueProviderCollection providerCollection = new ValueProviderCollection(new List<IValueProvider>() { mockProvider.Object });\n\n            // Act\n            IDictionary<string, string> actualResult = providerCollection.GetKeysFromPrefix(\"prefix\");\n\n            // Assert\n            Assert.NotNull(actualResult);\n            Assert.Empty(actualResult);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ValueProviderDictionaryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing System.Globalization;\nusing System.Web.Routing;\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\nusing Moq;\n\n#pragma warning disable 0618    // ValueProviderDictionary is now obsolete\n\nnamespace System.Web.Mvc.Test\n{\n    public class ValueProviderDictionaryTest\n    {\n        [Fact]\n        public void ConstructorCreatesEmptyDictionaryIfControllerContextIsNull()\n        {\n            // Act\n            ValueProviderDictionary dict = new ValueProviderDictionary(null);\n\n            // Assert\n            Assert.Empty(dict);\n        }\n\n        [Fact]\n        public void ControllerContextProperty()\n        {\n            // Arrange\n            ControllerContext expected = GetControllerContext();\n            ValueProviderDictionary dict = new ValueProviderDictionary(expected);\n\n            // Act\n            ControllerContext returned = dict.ControllerContext;\n\n            // Assert\n            Assert.Equal(expected, returned);\n        }\n\n        [Fact]\n        public void DictionaryInterface()\n        {\n            // Arrange\n            DictionaryHelper<string, ValueProviderResult> helper = new DictionaryHelper<string, ValueProviderResult>()\n            {\n                Creator = () => new ValueProviderDictionary(null),\n                Comparer = StringComparer.OrdinalIgnoreCase,\n                SampleKeys = new string[] { \"foo\", \"bar\", \"baz\", \"quux\", \"QUUX\" },\n                SampleValues = new ValueProviderResult[]\n                {\n                    new ValueProviderResult(null, null, null),\n                    new ValueProviderResult(null, null, null),\n                    new ValueProviderResult(null, null, null),\n                    new ValueProviderResult(null, null, null),\n                    new ValueProviderResult(null, null, null)\n                },\n                ThrowOnKeyNotFound = false\n            };\n\n            // Act & assert\n            helper.Execute();\n        }\n\n        [Fact]\n        public void AddWithRawValueUsesInvariantCulture()\n        {\n            // Arrange\n            ValueProviderDictionary dict = new ValueProviderDictionary(null);\n\n            // Act\n            dict.Add(\"foo\", 42);\n\n            // Assert\n            ValueProviderResult vpResult = dict[\"foo\"];\n            Assert.Equal(\"42\", vpResult.AttemptedValue);\n            Assert.Equal(42, vpResult.RawValue);\n            Assert.Equal(CultureInfo.InvariantCulture, vpResult.Culture);\n        }\n\n        [Fact]\n        public void NullAndEmptyKeysAreIgnored()\n        {\n            // DevDiv Bugs #216667: Exception thrown when querystring contains name without value\n\n            // Arrange\n            ValueProviderDictionary dict = GetAndPopulateDictionary();\n\n            // Act\n            bool emptyKeyFound = dict.ContainsKey(String.Empty);\n\n            // Assert\n            Assert.False(emptyKeyFound);\n        }\n\n        [Fact]\n        public void ValueFromForm()\n        {\n            // Arrange\n            ValueProviderDictionary dict;\n\n            // Act\n            using (new CultureReplacer(\"fr-FR\"))\n            {\n                dict = GetAndPopulateDictionary();\n            }\n            ValueProviderResult result = dict[\"foo\"];\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Equal(\"fooFromForm\", result.AttemptedValue);\n            string[] stringValues = Assert.IsType<string[]>(result.RawValue);\n            string stringValue = Assert.Single(stringValues);\n            Assert.Equal(\"fooFromForm\", stringValue);\n            Assert.Equal(CultureInfo.GetCultureInfo(\"fr-FR\"), result.Culture);\n        }\n\n        [Fact]\n        public void ValueFromQueryString()\n        {\n            // Arrange\n            ValueProviderDictionary dict;\n\n            // Act\n            using (new CultureReplacer(\"fr-FR\"))\n            {\n                dict = GetAndPopulateDictionary();\n            }\n            ValueProviderResult result = dict[\"baz\"];\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Equal(\"bazFromQueryString\", result.AttemptedValue);\n            string[] stringValues = Assert.IsType<string[]>(result.RawValue);\n            string stringValue = Assert.Single(stringValues);\n            Assert.Equal(\"bazFromQueryString\", stringValue);\n            Assert.Equal(CultureInfo.InvariantCulture, result.Culture);\n        }\n\n        [Fact]\n        public void ValueFromRoute()\n        {\n            // Arrange\n            ValueProviderDictionary dict;\n\n            // Act\n            using (new CultureReplacer(\"fr-FR\"))\n            {\n                dict = GetAndPopulateDictionary();\n            }\n            ValueProviderResult result = dict[\"bar\"];\n\n            // Assert\n            Assert.NotNull(result);\n            Assert.Equal(\"barInRoute\", result.AttemptedValue);\n            Assert.Equal(\"barInRoute\", result.RawValue);\n            Assert.Equal(CultureInfo.InvariantCulture, result.Culture);\n        }\n\n        private static ValueProviderDictionary GetAndPopulateDictionary()\n        {\n            return new ValueProviderDictionary(GetControllerContext());\n        }\n\n        private static ControllerContext GetControllerContext()\n        {\n            NameValueCollection form = new NameValueCollection() { { \"foo\", \"fooFromForm\" } };\n\n            RouteData rd = new RouteData();\n            rd.Values[\"foo\"] = \"fooFromRoute\";\n            rd.Values[\"bar\"] = \"barInRoute\";\n\n            NameValueCollection queryString = new NameValueCollection()\n            {\n                { \"foo\", \"fooFromQueryString\" },\n                { \"bar\", \"barInQueryString\" },\n                { \"baz\", \"bazFromQueryString\" },\n                { null, \"nullValue\" },\n                { \"\", \"emptyStringValue\" }\n            };\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(c => c.HttpContext.Request.Form).Returns(form);\n            mockControllerContext.Setup(c => c.HttpContext.Request.QueryString).Returns(queryString);\n            mockControllerContext.Setup(c => c.RouteData).Returns(rd);\n            return mockControllerContext.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ValueProviderFactoriesTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ValueProviderFactoriesTest\n    {\n        [Fact]\n        public void CollectionDefaults()\n        {\n            // Arrange\n            Type[] expectedTypes = new[]\n            {\n                typeof(ChildActionValueProviderFactory),\n                typeof(FormValueProviderFactory),\n                typeof(JsonValueProviderFactory),\n                typeof(RouteDataValueProviderFactory),\n                typeof(QueryStringValueProviderFactory),\n                typeof(HttpFileCollectionValueProviderFactory),\n                typeof(JQueryFormValueProviderFactory),\n            };\n\n            // Act\n            Type[] actualTypes = ValueProviderFactories.Factories.Select(p => p.GetType()).ToArray();\n\n            // Assert\n            Assert.Equal(expectedTypes, actualTypes);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ValueProviderFactoryCollectionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ValueProviderFactoryCollectionTest\n    {\n        [Fact]\n        public void ListWrappingConstructor()\n        {\n            // Arrange\n            List<ValueProviderFactory> list = new List<ValueProviderFactory>()\n            {\n                new FormValueProviderFactory()\n            };\n\n            // Act\n            ValueProviderFactoryCollection collection = new ValueProviderFactoryCollection(list);\n\n            // Assert\n            Assert.Equal(list, collection.ToList());\n        }\n\n        [Fact]\n        public void ListWrappingConstructorThrowsIfListIsNull()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ValueProviderFactoryCollection(null); },\n                \"list\");\n        }\n\n        [Fact]\n        public void DefaultConstructor()\n        {\n            // Act\n            ValueProviderFactoryCollection collection = new ValueProviderFactoryCollection();\n\n            // Assert\n            Assert.Empty(collection);\n        }\n\n        [Fact]\n        public void AddNullValueProviderFactoryThrows()\n        {\n            // Arrange\n            ValueProviderFactoryCollection collection = new ValueProviderFactoryCollection();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { collection.Add(null); },\n                \"item\");\n        }\n\n        [Fact]\n        public void ValueProviderFactoryCollectionCombinedItemsCaches()\n        {\n            // Arrange\n            var factories = new ValueProviderFactory[]\n            {\n                new Mock<ValueProviderFactory>(MockBehavior.Strict).Object,\n                new Mock<ValueProviderFactory>(MockBehavior.Strict).Object\n            };\n            var collection = new ValueProviderFactoryCollection(factories);\n\n            // Act\n            var combined1 = collection.CombinedItems;\n            var combined2 = collection.CombinedItems;\n\n            // Assert\n            Assert.Equal(factories, combined1);\n            Assert.Same(combined1, combined2);\n        }\n\n        [Fact]\n        public void ValueProviderFactoryCollectionCombinedItemsClearResetsCache()\n        {\n            TestCacheReset((collection) => collection.Clear());\n        }\n\n        [Fact]\n        public void ValueProviderFactoryCollectionCombinedItemsInsertResetsCache()\n        {\n            TestCacheReset((collection) => collection.Insert(0, new Mock<ValueProviderFactory>(MockBehavior.Strict).Object));\n        }\n\n        [Fact]\n        public void ValueProviderFactoryCollectionCombinedItemsRemoveResetsCache()\n        {\n            TestCacheReset((collection) => collection.RemoveAt(0));\n        }\n\n        [Fact]\n        public void ValueProviderFactoryCollectionCombinedItemsSetResetsCache()\n        {\n            TestCacheReset((collection) => collection[0] = new Mock<ValueProviderFactory>(MockBehavior.Strict).Object);\n        }\n\n        private static void TestCacheReset(Action<ValueProviderFactoryCollection> mutatingAction)\n        {\n            // Arrange\n            var providers = new List<ValueProviderFactory>()\n            {\n                new Mock<ValueProviderFactory>(MockBehavior.Strict).Object,\n                new Mock<ValueProviderFactory>(MockBehavior.Strict).Object\n            };\n            var collection = new ValueProviderFactoryCollection(providers);\n\n            // Act\n            mutatingAction(collection);\n\n            ValueProviderFactory[] combined = collection.CombinedItems;\n\n            // Assert\n            Assert.Equal(providers, combined);\n        }\n\n        [Fact]\n        public void ValueProviderFactoryCollectionCombinedItemsDelegatesToResolver()\n        {\n            // Arrange\n            var firstFactory = new Mock<ValueProviderFactory>();\n            var secondFactory = new Mock<ValueProviderFactory>();\n            var thirdFactory = new Mock<ValueProviderFactory>();\n            var dependencyFactories = new ValueProviderFactory[] { firstFactory.Object, secondFactory.Object };\n            var collectionFactories = new ValueProviderFactory[] { thirdFactory.Object };\n            var expectedFactories = new ValueProviderFactory[] { firstFactory.Object, secondFactory.Object, thirdFactory.Object };\n\n            var resolver = new Mock<IDependencyResolver>();\n            resolver.Setup(r => r.GetServices(typeof(ValueProviderFactory))).Returns(dependencyFactories);\n\n            var factories = new ValueProviderFactoryCollection(collectionFactories, resolver.Object);\n\n            // Act\n            ValueProviderFactory[] combined = factories.CombinedItems;\n\n            // Assert\n            Assert.Equal(expectedFactories, combined);\n        }\n\n        [Fact]\n        public void GetValueProvider()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            IValueProvider[] expectedValueProviders = new[]\n            {\n                new Mock<IValueProvider>().Object,\n                new Mock<IValueProvider>().Object\n            };\n\n            Mock<ValueProviderFactory> mockFactory1 = new Mock<ValueProviderFactory>();\n            mockFactory1.Setup(o => o.GetValueProvider(controllerContext)).Returns(expectedValueProviders[0]);\n            Mock<ValueProviderFactory> mockFactory2 = new Mock<ValueProviderFactory>();\n            mockFactory2.Setup(o => o.GetValueProvider(controllerContext)).Returns(expectedValueProviders[1]);\n\n            ValueProviderFactoryCollection factories = new ValueProviderFactoryCollection()\n            {\n                mockFactory1.Object,\n                mockFactory2.Object\n            };\n\n            // Act\n            ValueProviderCollection valueProviders = (ValueProviderCollection)factories.GetValueProvider(controllerContext);\n\n            // Assert\n            Assert.Equal(expectedValueProviders, valueProviders.ToArray());\n        }\n\n        [Fact]\n        public void GetValueProviderDelegatesToResolver()\n        {\n            // Arrange\n            ControllerContext controllerContext = new ControllerContext();\n            IValueProvider[] expectedValueProviders = new[]\n            {\n                new Mock<IValueProvider>().Object,\n                new Mock<IValueProvider>().Object\n            };\n\n            Mock<ValueProviderFactory> mockFactory1 = new Mock<ValueProviderFactory>();\n            mockFactory1.Setup(o => o.GetValueProvider(controllerContext)).Returns(expectedValueProviders[0]);\n            Mock<ValueProviderFactory> mockFactory2 = new Mock<ValueProviderFactory>();\n            mockFactory2.Setup(o => o.GetValueProvider(controllerContext)).Returns(expectedValueProviders[1]);\n\n            var resolver = new Mock<IDependencyResolver>();\n            resolver.Setup(r => r.GetServices(typeof(ValueProviderFactory))).Returns(new[] { mockFactory1.Object, mockFactory2.Object });\n            ValueProviderFactoryCollection factories = new ValueProviderFactoryCollection(new ValueProviderFactory[0], resolver.Object);\n\n            // Act\n            ValueProviderCollection valueProviders = (ValueProviderCollection)factories.GetValueProvider(controllerContext);\n\n            // Assert\n            Assert.Equal(expectedValueProviders, valueProviders.ToArray());\n        }\n\n        [Fact]\n        public void SetItem()\n        {\n            // Arrange\n            ValueProviderFactoryCollection collection = new ValueProviderFactoryCollection();\n            collection.Add(new Mock<ValueProviderFactory>().Object);\n\n            ValueProviderFactory newFactory = new Mock<ValueProviderFactory>().Object;\n\n            // Act\n            collection[0] = newFactory;\n\n            // Assert\n            ValueProviderFactory factory = Assert.Single(collection);\n            Assert.Equal(newFactory, factory);\n        }\n\n        [Fact]\n        public void SetNullValueProviderFactoryThrows()\n        {\n            // Arrange\n            ValueProviderFactoryCollection collection = new ValueProviderFactoryCollection();\n            collection.Add(new Mock<ValueProviderFactory>().Object);\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { collection[0] = null; },\n                \"item\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ValueProviderResultTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ValueProviderResultTest\n    {\n        [Fact]\n        public void ConstructorSetsProperties()\n        {\n            // Arrange\n            object rawValue = new object();\n            string attemptedValue = \"some string\";\n            CultureInfo culture = CultureInfo.GetCultureInfo(\"fr-FR\");\n\n            // Act\n            ValueProviderResult result = new ValueProviderResult(rawValue, attemptedValue, culture);\n\n            // Assert\n            Assert.Same(rawValue, result.RawValue);\n            Assert.Same(attemptedValue, result.AttemptedValue);\n            Assert.Same(culture, result.Culture);\n        }\n\n        [Fact]\n        public void ConvertToCanConvertArraysToArrays()\n        {\n            // Arrange\n            ValueProviderResult vpr = new ValueProviderResult(new int[] { 1, 20, 42 }, \"\", CultureInfo.InvariantCulture);\n\n            // Act\n            string[] converted = (string[])vpr.ConvertTo(typeof(string[]));\n\n            // Assert\n            Assert.NotNull(converted);\n            Assert.Equal(3, converted.Length);\n            Assert.Equal(\"1\", converted[0]);\n            Assert.Equal(\"20\", converted[1]);\n            Assert.Equal(\"42\", converted[2]);\n        }\n\n        [Fact]\n        public void ConvertToCanConvertArraysToSingleElements()\n        {\n            // Arrange\n            ValueProviderResult vpr = new ValueProviderResult(new int[] { 1, 20, 42 }, \"\", CultureInfo.InvariantCulture);\n\n            // Act\n            string converted = (string)vpr.ConvertTo(typeof(string));\n\n            // Assert\n            Assert.Equal(\"1\", converted);\n        }\n\n        [Fact]\n        public void ConvertToCanConvertSingleElementsToArrays()\n        {\n            // Arrange\n            ValueProviderResult vpr = new ValueProviderResult(42, \"\", CultureInfo.InvariantCulture);\n\n            // Act\n            string[] converted = (string[])vpr.ConvertTo(typeof(string[]));\n\n            // Assert\n            Assert.NotNull(converted);\n            string value = Assert.Single(converted);\n            Assert.Equal(\"42\", value);\n        }\n\n        [Fact]\n        public void ConvertToCanConvertSingleElementsToSingleElements()\n        {\n            // Arrange\n            ValueProviderResult vpr = new ValueProviderResult(42, \"\", CultureInfo.InvariantCulture);\n\n            // Act\n            string converted = (string)vpr.ConvertTo(typeof(string));\n\n            // Assert\n            Assert.NotNull(converted);\n            Assert.Equal(\"42\", converted);\n        }\n\n        [Fact]\n        public void ConvertToChecksTypeConverterCanConvertFrom()\n        {\n            // Arrange\n            object original = \"someValue\";\n            ValueProviderResult vpr = new ValueProviderResult(original, null, CultureInfo.GetCultureInfo(\"fr-FR\"));\n\n            // Act\n            DefaultModelBinderTest.StringContainer returned = (DefaultModelBinderTest.StringContainer)vpr.ConvertTo(typeof(DefaultModelBinderTest.StringContainer));\n\n            // Assert\n            Assert.Equal(\"someValue (fr-FR)\", returned.Value);\n        }\n\n        [Fact]\n        public void ConvertingNullStringToNullableIntReturnsNull()\n        {\n            // Arrange\n            object original = null;\n            ValueProviderResult vpr = new ValueProviderResult(original, \"\", CultureInfo.InvariantCulture);\n\n            // Act\n            int? returned = (int?)vpr.ConvertTo(typeof(int?));\n\n            // Assert\n            Assert.Null(returned);\n        }\n\n        [Fact]\n        public void ConvertingWhiteSpaceStringToNullableIntReturnsNull()\n        {\n            // Arrange\n            object original = \" \";\n            ValueProviderResult vpr = new ValueProviderResult(original, \"\", CultureInfo.InvariantCulture);\n\n            // Act\n            int? returned = (int?)vpr.ConvertTo(typeof(int?));\n\n            // Assert\n            Assert.Null(returned);\n        }\n\n        [Fact]\n        public void ConvertToChecksTypeConverterCanConvertTo()\n        {\n            // Arrange\n            object original = new DefaultModelBinderTest.StringContainer(\"someValue\");\n            ValueProviderResult vpr = new ValueProviderResult(original, \"\", CultureInfo.GetCultureInfo(\"en-US\"));\n\n            // Act\n            string returned = (string)vpr.ConvertTo(typeof(string));\n\n            // Assert\n            Assert.Equal(\"someValue (en-US)\", returned);\n        }\n\n        [Fact]\n        public void ConvertToReturnsNullIfArrayElementValueIsNull()\n        {\n            // Arrange\n            ValueProviderResult vpr = new ValueProviderResult(new string[] { null }, null, CultureInfo.InvariantCulture);\n\n            // Act\n            object outValue = vpr.ConvertTo(typeof(int));\n\n            // Assert\n            Assert.Null(outValue);\n        }\n\n        [Fact]\n        public void ConvertToReturnsNullIfTryingToConvertEmptyArrayToSingleElement()\n        {\n            // Arrange\n            ValueProviderResult vpr = new ValueProviderResult(new int[0], \"\", CultureInfo.InvariantCulture);\n\n            // Act\n            object outValue = vpr.ConvertTo(typeof(int));\n\n            // Assert\n            Assert.Null(outValue);\n        }\n\n        [Fact]\n        public void ConvertToReturnsNullIfValueIsEmptyString()\n        {\n            // Arrange\n            ValueProviderResult vpr = new ValueProviderResult(\"\", null, CultureInfo.InvariantCulture);\n\n            // Act\n            object outValue = vpr.ConvertTo(typeof(int));\n\n            // Assert\n            Assert.Null(outValue);\n        }\n\n        [Fact]\n        public void ConvertToReturnsNullIfTrimmedValueIsEmptyString()\n        {\n            // Arrange\n            ValueProviderResult vpr = new ValueProviderResult(\" \\t \\r\\n \", null, CultureInfo.InvariantCulture);\n\n            // Act\n            object outValue = vpr.ConvertTo(typeof(int));\n\n            // Assert\n            Assert.Null(outValue);\n        }\n\n        [Fact]\n        public void ConvertToReturnsNullIfValueIsNull()\n        {\n            // Arrange\n            ValueProviderResult vpr = new ValueProviderResult(null /* rawValue */, null /* attemptedValue */, CultureInfo.InvariantCulture);\n\n            // Act\n            object outValue = vpr.ConvertTo(typeof(int[]));\n\n            // Assert\n            Assert.Null(outValue);\n        }\n\n        [Fact]\n        public void ConvertToReturnsValueIfArrayElementIsIntegerAndDestinationTypeIsEnum()\n        {\n            // Arrange\n            ValueProviderResult vpr = new ValueProviderResult(new object[] { 1 }, null, CultureInfo.InvariantCulture);\n\n            // Act\n            object outValue = vpr.ConvertTo(typeof(MyEnum));\n\n            // Assert\n            Assert.Equal(MyEnum.Value1, outValue);\n        }\n\n        [Fact]\n        public void ConvertToReturnsValueIfArrayElementIsStringValueAndDestinationTypeIsEnum()\n        {\n            // Arrange\n            ValueProviderResult vpr = new ValueProviderResult(new object[] { \"1\" }, null, CultureInfo.InvariantCulture);\n\n            // Act\n            object outValue = vpr.ConvertTo(typeof(MyEnum));\n\n            // Assert\n            Assert.Equal(MyEnum.Value1, outValue);\n        }\n\n        [Fact]\n        public void ConvertToReturnsValueIfArrayElementIsStringKeyAndDestinationTypeIsEnum()\n        {\n            // Arrange\n            ValueProviderResult vpr = new ValueProviderResult(new object[] { \"Value1\" }, null, CultureInfo.InvariantCulture);\n\n            // Act\n            object outValue = vpr.ConvertTo(typeof(MyEnum));\n\n            // Assert\n            Assert.Equal(MyEnum.Value1, outValue);\n        }\n\n        [Fact]\n        public void ConvertToReturnsValueIfElementIsStringAndDestionationIsNullableInteger()\n        {\n            // Arrange\n            ValueProviderResult vpr = new ValueProviderResult(\"12\", null, CultureInfo.InvariantCulture);\n\n            // Act\n            object outValue = vpr.ConvertTo(typeof(int?));\n\n            // Assert\n            Assert.Equal(12, outValue);\n        }\n\n        [Fact]\n        public void ConvertToReturnsValueIfElementIsStringAndDestionationIsNullableDouble()\n        {\n            // Arrange\n            ValueProviderResult vpr = new ValueProviderResult(\"12.5\", null, CultureInfo.InvariantCulture);\n\n            // Act\n            object outValue = vpr.ConvertTo(typeof(double?));\n\n            // Assert\n            Assert.Equal(12.5, outValue);\n        }\n\n        [Fact]\n        public void ConvertToReturnsValueIfElementIsDecimalAndDestionationIsNullableInteger()\n        {\n            // Arrange\n            ValueProviderResult vpr = new ValueProviderResult(12M, null, CultureInfo.InvariantCulture);\n\n            // Act\n            object outValue = vpr.ConvertTo(typeof(int?));\n\n            // Assert\n            Assert.Equal(12, outValue);\n        }\n\n        [Fact]\n        public void ConvertToReturnsValueIfElementIsDecimalAndDestionationIsNullableDouble()\n        {\n            // Arrange\n            ValueProviderResult vpr = new ValueProviderResult(12.5M, null, CultureInfo.InvariantCulture);\n\n            // Act\n            object outValue = vpr.ConvertTo(typeof(double?));\n\n            // Assert\n            Assert.Equal(12.5, outValue);\n        }\n\n        [Fact]\n        public void ConvertToReturnsValueIfElementIsDecimalDoubleAndDestionationIsNullableInteger()\n        {\n            // Arrange\n            ValueProviderResult vpr = new ValueProviderResult(12.5M, null, CultureInfo.InvariantCulture);\n\n            // Act\n            object outValue = vpr.ConvertTo(typeof(int?));\n\n            // Assert\n            Assert.Equal(12, outValue);\n        }\n\n        [Fact]\n        public void ConvertToReturnsValueIfElementIsDecimalDoubleAndDestionationIsNullableLong()\n        {\n            // Arrange\n            ValueProviderResult vpr = new ValueProviderResult(12.5M, null, CultureInfo.InvariantCulture);\n\n            // Act\n            object outValue = vpr.ConvertTo(typeof(long?));\n\n            // Assert\n            Assert.Equal(12L, outValue);\n        }\n\n        [Fact]\n        public void ConvertToReturnsValueIfArrayElementInstanceOfDestinationType()\n        {\n            // Arrange\n            ValueProviderResult vpr = new ValueProviderResult(new object[] { \"some string\" }, null, CultureInfo.InvariantCulture);\n\n            // Act\n            object outValue = vpr.ConvertTo(typeof(string));\n\n            // Assert\n            Assert.Equal(\"some string\", outValue);\n        }\n\n        [Fact]\n        public void ConvertToReturnsValueIfInstanceOfDestinationType()\n        {\n            // Arrange\n            string[] original = new string[] { \"some string\" };\n            ValueProviderResult vpr = new ValueProviderResult(original, null, CultureInfo.InvariantCulture);\n\n            // Act\n            object outValue = vpr.ConvertTo(typeof(string[]));\n\n            // Assert\n            Assert.Same(original, outValue);\n        }\n\n        [Fact]\n        public void ConvertToThrowsIfConverterThrows()\n        {\n            // Arrange\n            ValueProviderResult vpr = new ValueProviderResult(\"x\", null, CultureInfo.InvariantCulture);\n            Type destinationType = typeof(DefaultModelBinderTest.StringContainer);\n\n            // Act & Assert\n            // Will throw since the custom converter assumes the first 5 characters to be digits\n            InvalidOperationException exception = Assert.Throws<InvalidOperationException>(\n                delegate { vpr.ConvertTo(destinationType); },\n                \"The parameter conversion from type 'System.String' to type 'System.Web.Mvc.Test.DefaultModelBinderTest+StringContainer' failed. See the inner exception for more information.\");\n\n            Exception innerException = exception.InnerException;\n            Assert.Equal(\"Value must have at least 3 characters.\", innerException.Message);\n        }\n\n        [Fact]\n        public void ConvertToThrowsIfNoConverterExists()\n        {\n            // Arrange\n            ValueProviderResult vpr = new ValueProviderResult(\"x\", null, CultureInfo.InvariantCulture);\n            Type destinationType = typeof(MyClassWithoutConverter);\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { vpr.ConvertTo(destinationType); },\n                \"The parameter conversion from type 'System.String' to type 'System.Web.Mvc.Test.ValueProviderResultTest+MyClassWithoutConverter' failed because no type converter can convert between these types.\");\n        }\n\n        [Fact]\n        public void ConvertToThrowsIfTypeIsNull()\n        {\n            // Arrange\n            ValueProviderResult vpr = new ValueProviderResult(\"x\", null, CultureInfo.InvariantCulture);\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { vpr.ConvertTo(null); }, \"type\");\n        }\n\n        [Fact]\n        public void ConvertToUsesProvidedCulture()\n        {\n            // Arrange\n            object original = \"someValue\";\n            CultureInfo gbCulture = CultureInfo.GetCultureInfo(\"en-GB\");\n            ValueProviderResult vpr = new ValueProviderResult(original, null, CultureInfo.GetCultureInfo(\"fr-FR\"));\n\n            // Act\n            DefaultModelBinderTest.StringContainer returned = (DefaultModelBinderTest.StringContainer)vpr.ConvertTo(typeof(DefaultModelBinderTest.StringContainer), gbCulture);\n\n            // Assert\n            Assert.Equal(\"someValue (en-GB)\", returned.Value);\n        }\n\n        [Fact]\n        public void CulturePropertyDefaultsToInvariantCulture()\n        {\n            // Arrange\n            ValueProviderResult result = new ValueProviderResult(null, null, null);\n\n            // Act & assert\n            Assert.Same(CultureInfo.InvariantCulture, result.Culture);\n        }\n\n        [Theory]\n        [PropertyData(\"IntrinsicConversionData\")]\n        public void ConvertToCanConvertIntrinsics<T>(object initialValue, T expectedValue)\n        {\n            // Arrange\n            var result = new ValueProviderResult(initialValue, \"\", CultureInfo.InvariantCulture);\n\n            // Act & Assert\n            Assert.Equal(expectedValue, result.ConvertTo(typeof(T)));\n        }\n\n        public static IEnumerable<object[]> IntrinsicConversionData\n        {\n            get\n            {\n                return new TheoryDataSet<object, object>\n                {\n                    { 42, 42M },\n                    { 42, 42L },\n                    { 42, (float)42.0 },\n                    { 42, (double)42.0 },\n                    { 42M, 42 },\n                    { 42L, 42 },\n                    { (float)42.0, 42 },\n                    { (double)42.0, 42 }\n                };\n            }\n        }\n\n        private class MyClassWithoutConverter\n        {\n        }\n\n        private enum MyEnum\n        {\n            Value0 = 0,\n            Value1 = 1\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ValueProviderUtilTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ValueProviderUtilTest\n    {\n        [Fact]\n        public void CollectionContainsPrefix_EmptyCollectionReturnsFalse()\n        {\n            // Arrange\n            string[] collection = new string[0];\n\n            // Act\n            bool retVal = ValueProviderUtil.CollectionContainsPrefix(collection, \"\");\n\n            // Assert\n            Assert.False(retVal);\n        }\n\n        [Fact]\n        public void CollectionContainsPrefix_ExactMatch()\n        {\n            // Arrange\n            string[] collection = new string[] { \"Hello\" };\n\n            // Act\n            bool retVal = ValueProviderUtil.CollectionContainsPrefix(collection, \"Hello\");\n\n            // Assert\n            Assert.True(retVal);\n        }\n\n        [Fact]\n        public void CollectionContainsPrefix_MatchIsCaseInsensitive()\n        {\n            // Arrange\n            string[] collection = new string[] { \"Hello\" };\n\n            // Act\n            bool retVal = ValueProviderUtil.CollectionContainsPrefix(collection, \"hello\");\n\n            // Assert\n            Assert.True(retVal);\n        }\n\n        [Fact]\n        public void CollectionContainsPrefix_MatchIsNotSimpleSubstringMatch()\n        {\n            // Arrange\n            string[] collection = new string[] { \"Hello\" };\n\n            // Act\n            bool retVal = ValueProviderUtil.CollectionContainsPrefix(collection, \"He\");\n\n            // Assert\n            Assert.False(retVal);\n        }\n\n        [Fact]\n        public void CollectionContainsPrefix_NonEmptyCollectionReturnsTrueIfPrefixIsEmptyString()\n        {\n            // Arrange\n            string[] collection = new string[] { \"Hello\" };\n\n            // Act\n            bool retVal = ValueProviderUtil.CollectionContainsPrefix(collection, \"\");\n\n            // Assert\n            Assert.True(retVal);\n        }\n\n        [Fact]\n        public void CollectionContainsPrefix_PrefixBoundaries()\n        {\n            // Arrange\n            string[] collection = new string[] { \"Hello.There[0]\" };\n\n            // Act\n            bool retVal1 = ValueProviderUtil.CollectionContainsPrefix(collection, \"hello\");\n            bool retVal2 = ValueProviderUtil.CollectionContainsPrefix(collection, \"hello.there\");\n\n            // Assert\n            Assert.True(retVal1);\n            Assert.True(retVal2);\n            Assert.True(ValueProviderUtil.CollectionContainsPrefix(collection, \"hello.there[0]\"));\n            Assert.False(ValueProviderUtil.CollectionContainsPrefix(collection, \"hello.there.0\"));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ViewContextTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Web.WebPages.Scope;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")]\n    public class ViewContextTest\n    {\n        [Fact]\n        public void GuardClauses()\n        {\n            // Arrange\n            var controllerContext = new Mock<ControllerContext>().Object;\n            var view = new Mock<IView>().Object;\n            var viewData = new ViewDataDictionary();\n            var tempData = new TempDataDictionary();\n            var writer = new StringWriter();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => new ViewContext(null, view, viewData, tempData, writer),\n                \"controllerContext\"\n                );\n            Assert.ThrowsArgumentNull(\n                () => new ViewContext(controllerContext, null, viewData, tempData, writer),\n                \"view\"\n                );\n            Assert.ThrowsArgumentNull(\n                () => new ViewContext(controllerContext, view, null, tempData, writer),\n                \"viewData\"\n                );\n            Assert.ThrowsArgumentNull(\n                () => new ViewContext(controllerContext, view, viewData, null, writer),\n                \"tempData\"\n                );\n            Assert.ThrowsArgumentNull(\n                () => new ViewContext(controllerContext, view, viewData, tempData, null),\n                \"writer\"\n                );\n        }\n\n        [Fact]\n        public void FormIdGeneratorProperty()\n        {\n            // Arrange\n            var mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(o => o.Items).Returns(new Hashtable());\n            var viewContext = new ViewContext\n            {\n                HttpContext = mockHttpContext.Object\n            };\n\n            // Act\n            string form0Name = viewContext.FormIdGenerator();\n            string form1Name = viewContext.FormIdGenerator();\n            string form2Name = viewContext.FormIdGenerator();\n\n            // Assert\n            Assert.Equal(\"form0\", form0Name);\n            Assert.Equal(\"form1\", form1Name);\n            Assert.Equal(\"form2\", form2Name);\n        }\n\n        [Fact]\n        public void PropertiesAreSet()\n        {\n            // Arrange\n            var mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(o => o.HttpContext.Items).Returns(new Hashtable());\n            var view = new Mock<IView>().Object;\n            var viewData = new ViewDataDictionary();\n            var tempData = new TempDataDictionary();\n            var writer = new StringWriter();\n\n            // Act\n            ViewContext viewContext = new ViewContext(mockControllerContext.Object, view, viewData, tempData, writer);\n\n            // Setting FormContext to null will return the default one later\n            viewContext.FormContext = null;\n\n            // Assert\n            Assert.Equal(view, viewContext.View);\n            Assert.Equal(viewData, viewContext.ViewData);\n            Assert.Equal(tempData, viewContext.TempData);\n            Assert.Equal(writer, viewContext.Writer);\n            Assert.False(viewContext.UnobtrusiveJavaScriptEnabled); // Unobtrusive JavaScript should be off by default\n            Assert.NotNull(viewContext.FormContext); // We get the default FormContext\n            Assert.Equal(\"span\", viewContext.ValidationSummaryMessageElement); // gen a <span/> by default\n            Assert.Equal(\"span\", viewContext.ValidationMessageElement); // gen a <span/> by default\n        }\n\n        [Fact]\n        public void ViewContextUsesScopeThunkForInstanceClientValidationFlag()\n        {\n            // Arrange\n            var scope = new Dictionary<object, object>();\n            var httpContext = new Mock<HttpContextBase>();\n            var viewContext = new ViewContext { ScopeThunk = () => scope, HttpContext = httpContext.Object };\n            httpContext.Setup(c => c.Items).Returns(new Hashtable());\n\n            // Act & Assert\n            Assert.False(viewContext.ClientValidationEnabled);\n            viewContext.ClientValidationEnabled = true;\n            Assert.True(viewContext.ClientValidationEnabled);\n            Assert.Equal((object)true, scope[ViewContext.ClientValidationKeyName]);\n            viewContext.ClientValidationEnabled = false;\n            Assert.False(viewContext.ClientValidationEnabled);\n            Assert.Equal((object)false, scope[ViewContext.ClientValidationKeyName]);\n        }\n\n        [Fact]\n        public void ViewContextUsesScopeThunkForInstanceUnobstrusiveJavaScriptFlag()\n        {\n            // Arrange\n            var scope = new Dictionary<object, object>();\n            var httpContext = new Mock<HttpContextBase>();\n            var viewContext = new ViewContext { ScopeThunk = () => scope, HttpContext = httpContext.Object };\n            httpContext.Setup(c => c.Items).Returns(new Hashtable());\n\n            // Act & Assert\n            Assert.False(viewContext.UnobtrusiveJavaScriptEnabled);\n            viewContext.UnobtrusiveJavaScriptEnabled = true;\n            Assert.True(viewContext.UnobtrusiveJavaScriptEnabled);\n            Assert.Equal((object)true, scope[ViewContext.UnobtrusiveJavaScriptKeyName]);\n            viewContext.UnobtrusiveJavaScriptEnabled = false;\n            Assert.False(viewContext.UnobtrusiveJavaScriptEnabled);\n            Assert.Equal((object)false, scope[ViewContext.UnobtrusiveJavaScriptKeyName]);\n        }\n\n        [Fact]\n        public void ViewContextUsesScopeThunkForValidationSummaryMessageElement()\n        {\n            // Arrange\n            var scope = new Dictionary<object, object>();\n            var httpContext = new Mock<HttpContextBase>();\n            var viewContext = new ViewContext { ScopeThunk = () => scope, HttpContext = httpContext.Object };\n            httpContext.Setup(c => c.Items).Returns(new Hashtable());\n\n            // Act & Assert\n            Assert.Equal(\"span\", viewContext.ValidationSummaryMessageElement);\n            viewContext.ValidationSummaryMessageElement = \"h4\";\n            Assert.Equal(\"h4\", viewContext.ValidationSummaryMessageElement);\n            Assert.Equal(\"h4\", scope[ViewContext.ValidationSummaryMessageElementKeyName]);\n            viewContext.ValidationSummaryMessageElement = \"div\";\n            Assert.Equal(\"div\", viewContext.ValidationSummaryMessageElement);\n            Assert.Equal(\"div\", scope[ViewContext.ValidationSummaryMessageElementKeyName]);\n        }\n\n        [Fact]\n        public void ViewContextUsesScopeThunkForValidationMessageElement()\n        {\n            // Arrange\n            var scope = new Dictionary<object, object>();\n            var httpContext = new Mock<HttpContextBase>();\n            var viewContext = new ViewContext { ScopeThunk = () => scope, HttpContext = httpContext.Object };\n            httpContext.Setup(c => c.Items).Returns(new Hashtable());\n\n            // Act & Assert\n            Assert.Equal(\"span\", viewContext.ValidationMessageElement);\n            viewContext.ValidationMessageElement = \"h4\";\n            Assert.Equal(\"h4\", viewContext.ValidationMessageElement);\n            Assert.Equal(\"h4\", scope[ViewContext.ValidationMessageElementKeyName]);\n            viewContext.ValidationMessageElement = \"div\";\n            Assert.Equal(\"div\", viewContext.ValidationMessageElement);\n            Assert.Equal(\"div\", scope[ViewContext.ValidationMessageElementKeyName]);\n        }\n\n        [Fact]\n        public void ViewContextGlobalValidationMessageElementAffectsLocalOne()\n        {\n            // Arrange\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                var httpContext = new Mock<HttpContextBase>();\n                ScopeStorageDictionary localScope = null;\n                var globalViewContext = new ViewContext\n                {\n                    ScopeThunk = () => ScopeStorage.GlobalScope,\n                    HttpContext = httpContext.Object\n                };\n                var localViewContext = new ViewContext\n                {\n                    ScopeThunk = () =>\n                    {\n                        if (localScope == null)\n                        {\n                            localScope = new ScopeStorageDictionary(ScopeStorage.GlobalScope);\n                        };\n                        return localScope;\n                    },\n                    HttpContext = httpContext.Object\n                };\n                // A ScopeCache object will be stored into the hash table but the ScopeCache class is private,\n                // so we cannot get the validation message element from it for Assert.\n                httpContext.Setup(c => c.Items).Returns(new Hashtable());\n\n                // Act\n                globalViewContext.ValidationMessageElement = \"label\";\n\n                // Assert\n                // Global element was changed from \"span\" to \"label\".\n                Assert.Equal(\"label\", HtmlHelper.ValidationMessageElement);\n                Assert.Equal(\"label\", globalViewContext.ValidationMessageElement);\n                object value;\n                ScopeStorage.GlobalScope.TryGetValue(\"ValidationMessageElement\", out value);\n                Assert.Equal(\"label\", value);\n\n                // Local element was also changed to \"label\".\n                Assert.Equal(\"label\", localViewContext.ValidationMessageElement);\n                localScope.TryGetValue(\"ValidationMessageElement\", out value);\n                Assert.Equal(\"label\", value);\n            });\n        }\n\n        [Fact]\n        public void ViewContextLocalValidationMessageElementDoesNotAffectGlobalOne()\n        {\n            // Arrange\n            ScopeStorageDictionary localScope = null;\n            var httpContext = new Mock<HttpContextBase>();\n            var globalViewContext = new ViewContext\n            {\n                ScopeThunk = () => ScopeStorage.GlobalScope,\n                HttpContext = httpContext.Object\n            };\n            var localViewContext = new ViewContext\n            {\n                ScopeThunk = () =>\n                {\n                    if (localScope == null)\n                    {\n                        localScope = new ScopeStorageDictionary(ScopeStorage.GlobalScope);\n                    }\n                    return localScope;\n                },\n                HttpContext = httpContext.Object\n            };\n            // A ScopeCache object will be stored into the hash table but the ScopeCache class is private,\n            // so we cannot get the validation message element from it for Assert.\n            httpContext.Setup(c => c.Items).Returns(new Hashtable());\n\n            // Act & Assert\n            // Local element will be changed from \"span\" to \"h4\".\n            Assert.Equal(\"span\", localViewContext.ValidationMessageElement);\n            localViewContext.ValidationMessageElement = \"h4\";\n            Assert.Equal(\"h4\", localViewContext.ValidationMessageElement);\n            object value;\n            localScope.TryGetValue(\"ValidationMessageElement\", out value);\n            Assert.Equal(\"h4\", value);\n\n            // Global element is still \"span\".\n            Assert.Equal(\"span\", globalViewContext.ValidationMessageElement);\n            Assert.Empty(ScopeStorage.GlobalScope);\n            Assert.Equal(\"span\", HtmlHelper.ValidationMessageElement);\n        }\n\n        [Fact]\n        public void ViewBagProperty_ReflectsViewData()\n        {\n            // Arrange\n            var mockControllerContext = new Mock<ControllerContext>();\n            var view = new Mock<IView>().Object;\n            var viewData = new ViewDataDictionary() { { \"A\", 1 } };\n\n            // Act\n            ViewContext viewContext = new ViewContext(mockControllerContext.Object, view, viewData, new TempDataDictionary(), new StringWriter());\n\n            // Assert\n            Assert.Equal(1, viewContext.ViewBag.A);\n        }\n\n        [Fact]\n        public void ViewBagProperty_ReflectsNewViewDataInstance()\n        {\n            // Arrange\n            var mockControllerContext = new Mock<ControllerContext>();\n            var view = new Mock<IView>().Object;\n            var viewData = new ViewDataDictionary() { { \"A\", 1 } };\n\n            ViewContext viewContext = new ViewContext(mockControllerContext.Object, view, viewData, new TempDataDictionary(), new StringWriter());\n\n            // Act\n            viewContext.ViewData = new ViewDataDictionary() { { \"A\", \"bar\" } };\n\n            // Assert\n            Assert.Equal(\"bar\", viewContext.ViewBag.A);\n        }\n\n        [Fact]\n        public void ViewBag_PropagatesChangesToViewData()\n        {\n            // Arrange\n            var mockControllerContext = new Mock<ControllerContext>();\n            var view = new Mock<IView>().Object;\n            var viewData = new ViewDataDictionary() { { \"A\", 1 } };\n\n            ViewContext viewContext = new ViewContext(mockControllerContext.Object, view, viewData, new TempDataDictionary(), new StringWriter());\n\n            // Act\n            viewContext.ViewBag.A = \"foo\";\n            viewContext.ViewBag.B = 2;\n\n            // Assert\n            Assert.Equal(\"foo\", viewContext.ViewData[\"A\"]);\n            Assert.Equal(2, viewContext.ViewData[\"B\"]);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ViewDataDictionaryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")] // Uses ModelMetadataProviders.Current\n    public class ViewDataDictionaryTest\n    {\n        [Fact]\n        public void ConstructorThrowsIfDictionaryIsNull()\n        {\n            // Act & assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ViewDataDictionary((ViewDataDictionary)null); }, \"dictionary\");\n        }\n\n        [Fact]\n        public void ConstructorWithViewDataDictionaryCopiesModelAndModelState()\n        {\n            // Arrange\n            ViewDataDictionary originalVdd = new ViewDataDictionary();\n            object model = new object();\n            originalVdd.Model = model;\n            originalVdd[\"foo\"] = \"bar\";\n            originalVdd.ModelState.AddModelError(\"key\", \"error\");\n\n            // Act\n            ViewDataDictionary newVdd = new ViewDataDictionary(originalVdd);\n\n            // Assert\n            Assert.Equal(model, newVdd.Model);\n            Assert.True(newVdd.ModelState.ContainsKey(\"key\"));\n            Assert.Equal(\"error\", newVdd.ModelState[\"key\"].Errors[0].ErrorMessage);\n            Assert.Equal(\"bar\", newVdd[\"foo\"]);\n        }\n\n        [Fact]\n        public void ConstructorWithViewDataDictionaryUsesCopyOnWriteDictionary()\n        {\n            // Arrange\n            ViewDataDictionary originalVdd = new ViewDataDictionary();\n\n            // Act\n            ViewDataDictionary newVdd = new ViewDataDictionary(originalVdd);\n\n            // Assert\n            Assert.IsType<Dictionary<string, object>>(originalVdd.InnerDictionary);\n            Assert.IsType<CopyOnWriteDictionary<string, object>>(newVdd.InnerDictionary);\n        }\n\n        [Fact]\n        public void DictionaryInterface()\n        {\n            // Arrange\n            DictionaryHelper<string, object> helper = new DictionaryHelper<string, object>()\n            {\n                Creator = () => new ViewDataDictionary(),\n                Comparer = StringComparer.OrdinalIgnoreCase,\n                SampleKeys = new string[] { \"foo\", \"bar\", \"baz\", \"quux\", \"QUUX\" },\n                SampleValues = new object[] { 42, \"string value\", new DateTime(2001, 1, 1), new object(), 32m },\n                ThrowOnKeyNotFound = false\n            };\n\n            // Act & assert\n            helper.Execute();\n        }\n\n        [Fact]\n        public void EvalReturnsSimplePropertyValue()\n        {\n            var obj = new { Foo = \"Bar\" };\n            ViewDataDictionary vdd = new ViewDataDictionary(obj);\n\n            Assert.Equal(\"Bar\", vdd.Eval(\"Foo\"));\n        }\n\n        [Fact]\n        public void EvalWithModelAndDictionaryPropertyEvaluatesDictionaryValue()\n        {\n            var obj = new { Foo = new Dictionary<string, object> { { \"Bar\", \"Baz\" } } };\n            ViewDataDictionary vdd = new ViewDataDictionary(obj);\n\n            Assert.Equal(\"Baz\", vdd.Eval(\"Foo.Bar\"));\n        }\n\n        [Fact]\n        public void EvalEvaluatesDictionaryThenModel()\n        {\n            var obj = new { Foo = \"NotBar\" };\n            ViewDataDictionary vdd = new ViewDataDictionary(obj);\n            vdd.Add(\"Foo\", \"Bar\");\n\n            Assert.Equal(\"Bar\", vdd.Eval(\"Foo\"));\n        }\n\n        [Fact]\n        public void EvalReturnsValueOfCompoundExpressionByFollowingObjectPath()\n        {\n            var obj = new { Foo = new { Bar = \"Baz\" } };\n            ViewDataDictionary vdd = new ViewDataDictionary(obj);\n\n            Assert.Equal(\"Baz\", vdd.Eval(\"Foo.Bar\"));\n        }\n\n        [Fact]\n        public void EvalReturnsNullIfExpressionDoesNotMatch()\n        {\n            var obj = new { Foo = new { Biz = \"Baz\" } };\n            ViewDataDictionary vdd = new ViewDataDictionary(obj);\n\n            Assert.Null(vdd.Eval(\"Foo.Bar\"));\n        }\n\n        [Fact]\n        public void EvalReturnsValueJustAdded()\n        {\n            ViewDataDictionary vdd = new ViewDataDictionary();\n            vdd.Add(\"Foo\", \"Blah\");\n\n            Assert.Equal(\"Blah\", vdd.Eval(\"Foo\"));\n        }\n\n        [Fact]\n        public void EvalWithCompoundExpressionReturnsIndexedValue()\n        {\n            ViewDataDictionary vdd = new ViewDataDictionary();\n            vdd.Add(\"Foo.Bar\", \"Baz\");\n\n            Assert.Equal(\"Baz\", vdd.Eval(\"Foo.Bar\"));\n        }\n\n        [Fact]\n        public void EvalWithCompoundExpressionReturnsPropertyOfAddedObject()\n        {\n            ViewDataDictionary vdd = new ViewDataDictionary();\n            vdd.Add(\"Foo\", new { Bar = \"Baz\" });\n\n            Assert.Equal(\"Baz\", vdd.Eval(\"Foo.Bar\"));\n        }\n\n        [Fact]\n        public void EvalWithCompoundIndexExpressionReturnsEval()\n        {\n            ViewDataDictionary vdd = new ViewDataDictionary();\n            vdd.Add(\"Foo.Bar\", new { Baz = \"Quux\" });\n\n            Assert.Equal(\"Quux\", vdd.Eval(\"Foo.Bar.Baz\"));\n        }\n\n        [Fact]\n        public void EvalWithCompoundIndexAndCompoundExpressionReturnsValue()\n        {\n            ViewDataDictionary vdd = new ViewDataDictionary();\n            vdd.Add(\"Foo.Bar\", new { Baz = new { Blah = \"Quux\" } });\n\n            Assert.Equal(\"Quux\", vdd.Eval(\"Foo.Bar.Baz.Blah\"));\n        }\n\n        /// <summary>\n        /// Make sure that dict[\"foo.bar\"] gets chosen before dict[\"foo\"][\"bar\"]\n        /// </summary>\n        [Fact]\n        public void EvalChoosesValueInDictionaryOverOtherValue()\n        {\n            ViewDataDictionary vdd = new ViewDataDictionary();\n            vdd.Add(\"Foo\", new { Bar = \"Not Baz\" });\n            vdd.Add(\"Foo.Bar\", \"Baz\");\n\n            Assert.Equal(\"Baz\", vdd.Eval(\"Foo.Bar\"));\n        }\n\n        /// <summary>\n        /// Make sure that dict[\"foo.bar\"][\"baz\"] gets chosen before dict[\"foo\"][\"bar\"][\"baz\"]\n        /// </summary>\n        [Fact]\n        public void EvalChoosesCompoundValueInDictionaryOverOtherValues()\n        {\n            ViewDataDictionary vdd = new ViewDataDictionary();\n            vdd.Add(\"Foo\", new { Bar = new { Baz = \"Not Quux\" } });\n            vdd.Add(\"Foo.Bar\", new { Baz = \"Quux\" });\n\n            Assert.Equal(\"Quux\", vdd.Eval(\"Foo.Bar.Baz\"));\n        }\n\n        /// <summary>\n        /// Make sure that dict[\"foo.bar\"][\"baz\"] gets chosen before dict[\"foo\"][\"bar.baz\"]\n        /// </summary>\n        [Fact]\n        public void EvalChoosesCompoundValueInDictionaryOverOtherValuesWithCompoundProperty()\n        {\n            ViewDataDictionary vdd = new ViewDataDictionary();\n            vdd.Add(\"Foo\", new Person());\n            vdd.Add(\"Foo.Bar\", new { Baz = \"Quux\" });\n\n            Assert.Equal(\"Quux\", vdd.Eval(\"Foo.Bar.Baz\"));\n        }\n\n        [Fact]\n        public void EvalThrowsIfExpressionIsEmpty()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { vdd.Eval(String.Empty); }, \"expression\");\n        }\n\n        [Fact]\n        public void EvalThrowsIfExpressionIsNull()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                delegate { vdd.Eval(null); }, \"expression\");\n        }\n\n        [Fact]\n        public void EvalWithCompoundExpressionAndDictionarySubExpressionChoosesDictionaryValue()\n        {\n            ViewDataDictionary vdd = new ViewDataDictionary();\n            vdd.Add(\"Foo\", new Dictionary<string, object> { { \"Bar\", \"Baz\" } });\n\n            Assert.Equal(\"Baz\", vdd.Eval(\"Foo.Bar\"));\n        }\n\n        [Fact]\n        public void EvalWithDictionaryAndNoMatchReturnsNull()\n        {\n            ViewDataDictionary vdd = new ViewDataDictionary();\n            vdd.Add(\"Foo\", new Dictionary<string, object> { { \"NotBar\", \"Baz\" } });\n\n            object result = vdd.Eval(\"Foo.Bar\");\n            Assert.Null(result);\n        }\n\n        [Fact]\n        public void EvalWithNestedDictionariesEvalCorrectly()\n        {\n            ViewDataDictionary vdd = new ViewDataDictionary();\n            vdd.Add(\"Foo\", new Dictionary<string, object> { { \"Bar\", new Hashtable { { \"Baz\", \"Quux\" } } } });\n\n            Assert.Equal(\"Quux\", vdd.Eval(\"Foo.Bar.Baz\"));\n        }\n\n        [Fact]\n        public void EvalFormatWithNullValueReturnsEmptyString()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary();\n\n            // Act\n            string formattedValue = vdd.Eval(\"foo\", \"for{0}mat\");\n\n            // Assert\n            Assert.Equal(String.Empty, formattedValue);\n        }\n\n        [Fact]\n        public void EvalFormatWithEmptyFormatReturnsViewData()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary();\n            vdd[\"foo\"] = \"value\";\n\n            // Act\n            string formattedValue = vdd.Eval(\"foo\", \"\");\n\n            // Assert\n            Assert.Equal(\"value\", formattedValue);\n        }\n\n        [Fact]\n        public void EvalFormatWithFormatReturnsFormattedViewData()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary();\n            vdd[\"foo\"] = \"value\";\n\n            // Act\n            string formattedValue = vdd.Eval(\"foo\", \"for{0}mat\");\n\n            // Assert\n            Assert.Equal(\"forvaluemat\", formattedValue);\n        }\n\n        [Fact]\n        public void EvalPropertyNamedModel()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary();\n            vdd[\"Title\"] = \"Home Page\";\n            vdd[\"Message\"] = \"Welcome to ASP.NET MVC!\";\n            vdd.Model = new TheQueryStringParam\n            {\n                Name = \"The Name\",\n                Value = \"The Value\",\n                Model = \"The Model\",\n            };\n\n            // Act\n            object o = vdd.Eval(\"Model\");\n\n            // Assert\n            Assert.Equal(\"The Model\", o);\n        }\n\n        [Fact]\n        public void EvalSubPropertyNamedValueInModel()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary();\n            vdd[\"Title\"] = \"Home Page\";\n            vdd[\"Message\"] = \"Welcome to ASP.NET MVC!\";\n            vdd.Model = new TheQueryStringParam\n            {\n                Name = \"The Name\",\n                Value = \"The Value\",\n                Model = \"The Model\",\n            };\n\n            // Act\n            object o = vdd.Eval(\"Value\");\n\n            // Assert\n            Assert.Equal(\"The Value\", o);\n        }\n\n        [Fact]\n        public void GetViewDataInfoFromDictionary()\n        {\n            // Arrange\n            ViewDataDictionary fooVdd = new ViewDataDictionary()\n            {\n                { \"Bar\", \"barValue\" }\n            };\n            ViewDataDictionary vdd = new ViewDataDictionary()\n            {\n                { \"Foo\", fooVdd }\n            };\n\n            // Act\n            ViewDataInfo info = vdd.GetViewDataInfo(\"foo.bar\");\n\n            // Assert\n            Assert.NotNull(info);\n            Assert.Equal(fooVdd, info.Container);\n            Assert.Equal(\"barValue\", info.Value);\n        }\n\n        [Fact]\n        public void GetViewDataInfoFromDictionaryWithMissingEntry()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary();\n\n            // Act\n            ViewDataInfo info = vdd.GetViewDataInfo(\"foo\");\n\n            // Assert\n            Assert.Null(info);\n        }\n\n        [Fact]\n        public void GetViewDataInfoFromDictionaryWithNullEntry()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary()\n            {\n                { \"Foo\", null }\n            };\n\n            // Act\n            ViewDataInfo info = vdd.GetViewDataInfo(\"foo\");\n\n            // Assert\n            Assert.NotNull(info);\n            Assert.Equal(vdd, info.Container);\n            Assert.Null(info.Value);\n        }\n\n        [Fact]\n        public void GetViewDataInfoFromModel()\n        {\n            // Arrange\n            object model = new { foo = \"fooValue\" };\n            ViewDataDictionary vdd = new ViewDataDictionary(model);\n\n            PropertyDescriptor propDesc = TypeDescriptor.GetProperties(model).Find(\"foo\", true /* ignoreCase */);\n\n            // Act\n            ViewDataInfo info = vdd.GetViewDataInfo(\"foo\");\n\n            // Assert\n            Assert.NotNull(info);\n            Assert.Equal(model, info.Container);\n            Assert.Equal(propDesc, info.PropertyDescriptor);\n            Assert.Equal(\"fooValue\", info.Value);\n        }\n\n        [Fact]\n        public void FabricatesModelMetadataFromModelWhenModelMetadataHasNotBeenSet()\n        {\n            // Arrange\n            object model = new { foo = \"fooValue\", bar = \"barValue\" };\n            ViewDataDictionary vdd = new ViewDataDictionary(model);\n\n            // Act\n            ModelMetadata metadata = vdd.ModelMetadata;\n\n            // Assert\n            Assert.NotNull(metadata);\n            Assert.Equal(model.GetType(), metadata.ModelType);\n        }\n\n        [Fact]\n        public void ReturnsExistingModelMetadata()\n        {\n            // Arrange\n            object model = new { foo = \"fooValue\", bar = \"barValue\" };\n            ModelMetadata originalMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());\n            ViewDataDictionary vdd = new ViewDataDictionary(model) { ModelMetadata = originalMetadata };\n\n            // Act\n            ModelMetadata metadata = vdd.ModelMetadata;\n\n            // Assert\n            Assert.Same(originalMetadata, metadata);\n        }\n\n        [Fact]\n        public void ModelMetadataIsNullIfModelMetadataHasNotBeenSetAndModelIsNull()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary();\n\n            // Act\n            ModelMetadata metadata = vdd.ModelMetadata;\n\n            // Assert\n            Assert.Null(metadata);\n        }\n\n        [Fact]\n        public void ModelMetadataCanBeFabricatedWithNullModelAndGenericViewDataDictionary()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary<Exception>();\n\n            // Act\n            ModelMetadata metadata = vdd.ModelMetadata;\n\n            // Assert\n            Assert.NotNull(metadata);\n            Assert.Equal(typeof(Exception), metadata.ModelType);\n        }\n\n        [Fact]\n        public void ModelSetterThrowsIfValueIsNullAndModelTypeIsNonNullable()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary<int>();\n\n            // Act & assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { vdd.Model = null; },\n                @\"The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type 'System.Int32'.\");\n        }\n\n        [Fact]\n        public void ChangingModelReplacesModelMetadata()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary(new Object());\n            ModelMetadata originalMetadata = vdd.ModelMetadata;\n\n            // Act\n            vdd.Model = \"New Model\";\n\n            // Assert\n            Assert.NotSame(originalMetadata, vdd.ModelMetadata);\n        }\n\n        public class TheQueryStringParam\n        {\n            public string Name { get; set; }\n            public string Value { get; set; }\n            public string Model { get; set; }\n        }\n\n        public class Person : CustomTypeDescriptor\n        {\n            public override PropertyDescriptorCollection GetProperties()\n            {\n                return new PropertyDescriptorCollection(new PersonPropertyDescriptor[] { new PersonPropertyDescriptor() });\n            }\n        }\n\n        public class PersonPropertyDescriptor : PropertyDescriptor\n        {\n            public PersonPropertyDescriptor()\n                : base(\"Bar.Baz\", null)\n            {\n            }\n\n            public override object GetValue(object component)\n            {\n                return \"Quux\";\n            }\n\n            public override bool CanResetValue(object component)\n            {\n                return false;\n            }\n\n            public override Type ComponentType\n            {\n                get { return typeof(Person); }\n            }\n\n            public override bool IsReadOnly\n            {\n                get { return false; }\n            }\n\n            public override Type PropertyType\n            {\n                get { return typeof(string); }\n            }\n\n            public override void ResetValue(object component)\n            {\n            }\n\n            public override void SetValue(object component, object value)\n            {\n            }\n\n            public override bool ShouldSerializeValue(object component)\n            {\n                return true;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ViewDataInfoTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ViewDataInfoTest\n    {\n        [Fact]\n        public void ViewDataInfoDoesNotCallAccessorUntilValuePropertyAccessed()\n        {\n            // Arrange\n            bool called = false;\n            ViewDataInfo vdi = new ViewDataInfo(() =>\n            {\n                called = true;\n                return 21;\n            });\n\n            // Act & Assert\n            Assert.False(called);\n            object result = vdi.Value;\n            Assert.True(called);\n            Assert.Equal(21, result);\n        }\n\n        [Fact]\n        public void AccessorIsOnlyCalledOnce()\n        {\n            // Arrange\n            int callCount = 0;\n            ViewDataInfo vdi = new ViewDataInfo(() =>\n            {\n                ++callCount;\n                return null;\n            });\n\n            // Act & Assert\n            Assert.Equal(0, callCount);\n            object unused;\n            unused = vdi.Value;\n            unused = vdi.Value;\n            unused = vdi.Value;\n            Assert.Equal(1, callCount);\n        }\n\n        [Fact]\n        public void SettingExplicitValueOverridesAccessorMethod()\n        {\n            // Arrange\n            bool called = false;\n            ViewDataInfo vdi = new ViewDataInfo(() =>\n            {\n                called = true;\n                return null;\n            });\n\n            // Act & Assert\n            Assert.False(called);\n            vdi.Value = 42;\n            object result = vdi.Value;\n            Assert.False(called);\n            Assert.Equal(42, result);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ViewEngineCollectionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ViewEngineCollectionTest\n    {\n        [Fact]\n        public void ListWrappingConstructor()\n        {\n            // Arrange\n            List<IViewEngine> list = new List<IViewEngine>() { new Mock<IViewEngine>().Object, new Mock<IViewEngine>().Object };\n\n            // Act\n            ViewEngineCollection collection = new ViewEngineCollection(list);\n\n            // Assert\n            Assert.Equal(2, collection.Count);\n            Assert.Same(list[0], collection[0]);\n            Assert.Same(list[1], collection[1]);\n        }\n\n        [Fact]\n        public void ListWrappingConstructorThrowsIfListIsNull()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ViewEngineCollection((IList<IViewEngine>)null); },\n                \"list\");\n        }\n\n        [Fact]\n        public void DefaultConstructor()\n        {\n            // Act\n            ViewEngineCollection collection = new ViewEngineCollection();\n\n            // Assert\n            Assert.Empty(collection);\n        }\n\n        [Fact]\n        public void ViewEngineCollectionCombinedItemsCaches()\n        {\n            // Arrange\n            var engines = new IViewEngine[] \n            {\n                new Mock<IViewEngine>(MockBehavior.Strict).Object, \n                new Mock<IViewEngine>(MockBehavior.Strict).Object\n            };\n            var collection = new ViewEngineCollection(engines);\n\n            // Act\n            var combined1 = collection.CombinedItems;\n            var combined2 = collection.CombinedItems;\n\n            // Assert\n            Assert.Equal(engines, combined1);\n            Assert.Same(combined1, combined2);\n        }\n\n        [Fact]\n        public void ViewEngineCollectionCombinedItemsClearResetsCache()\n        {\n            TestCacheReset((collection) => collection.Clear());\n        }\n\n        [Fact]\n        public void ViewEngineCollectionCombinedItemsInsertResetsCache()\n        {\n            TestCacheReset((collection) => collection.Insert(0, new Mock<IViewEngine>(MockBehavior.Strict).Object));\n        }\n\n        [Fact]\n        public void ViewEngineCollectionCombinedItemsRemoveResetsCache()\n        {\n            TestCacheReset((collection) => collection.RemoveAt(0));\n        }\n\n        [Fact]\n        public void ViewEngineCollectionCombinedItemsSetResetsCache()\n        {\n            TestCacheReset((collection) => collection[0] = new Mock<IViewEngine>(MockBehavior.Strict).Object);\n        }\n\n        private static void TestCacheReset(Action<ViewEngineCollection> mutatingAction)\n        {\n            // Arrange\n            var providers = new List<IViewEngine>() \n            {\n                new Mock<IViewEngine>(MockBehavior.Strict).Object, \n                new Mock<IViewEngine>(MockBehavior.Strict).Object\n            };\n            var collection = new ViewEngineCollection(providers);\n\n            // Act\n            mutatingAction(collection);\n\n            IViewEngine[] combined = collection.CombinedItems;\n\n            // Assert\n            Assert.Equal(providers, combined);\n        }\n\n        [Fact]\n        public void ViewEngineCollectionCombinedItemsDelegatesToResolver()\n        {\n            // Arrange\n            var firstEngine = new Mock<IViewEngine>();\n            var secondEngine = new Mock<IViewEngine>();\n            var thirdEngine = new Mock<IViewEngine>();\n            var dependencyEngines = new IViewEngine[] { firstEngine.Object, secondEngine.Object };\n            var collectionEngines = new IViewEngine[] { thirdEngine.Object };\n            var expectedEngines = new IViewEngine[] { firstEngine.Object, secondEngine.Object, thirdEngine.Object };\n\n            var resolver = new Mock<IDependencyResolver>();\n            resolver.Setup(r => r.GetServices(typeof(IViewEngine))).Returns(dependencyEngines);\n\n            var engines = new ViewEngineCollection(collectionEngines, resolver.Object);\n\n            // Act\n            IViewEngine[] combined = engines.CombinedItems;\n\n            // Assert\n            Assert.Equal(expectedEngines, combined);\n        }\n\n        [Fact]\n        public void AddNullViewEngineThrows()\n        {\n            // Arrange\n            ViewEngineCollection collection = new ViewEngineCollection();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { collection.Add(null); },\n                \"item\");\n        }\n\n        [Fact]\n        public void SetNullViewEngineThrows()\n        {\n            // Arrange\n            ViewEngineCollection collection = new ViewEngineCollection();\n            collection.Add(new Mock<IViewEngine>().Object);\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { collection[0] = null; },\n                \"item\");\n        }\n\n        [Fact]\n        public void FindPartialViewAggregatesAllSearchedLocationsIfAllEnginesFail()\n        {\n            // Arrange\n            ControllerContext context = new Mock<ControllerContext>().Object;\n            ViewEngineCollection viewEngineCollection = new ViewEngineCollection();\n            Mock<IViewEngine> engine1 = new Mock<IViewEngine>();\n            ViewEngineResult engine1Result = new ViewEngineResult(new[] { \"location1\", \"location2\" });\n            engine1.Setup(e => e.FindPartialView(context, \"partial\", It.IsAny<bool>())).Returns(engine1Result);\n            Mock<IViewEngine> engine2 = new Mock<IViewEngine>();\n            ViewEngineResult engine2Result = new ViewEngineResult(new[] { \"location3\", \"location4\" });\n            engine2.Setup(e => e.FindPartialView(context, \"partial\", It.IsAny<bool>())).Returns(engine2Result);\n            viewEngineCollection.Add(engine1.Object);\n            viewEngineCollection.Add(engine2.Object);\n\n            // Act\n            ViewEngineResult result = viewEngineCollection.FindPartialView(context, \"partial\");\n\n            // Assert\n            Assert.Null(result.View);\n            Assert.Equal(4, result.SearchedLocations.Count());\n            Assert.Contains(\"location1\", result.SearchedLocations);\n            Assert.Contains(\"location2\", result.SearchedLocations);\n            Assert.Contains(\"location3\", result.SearchedLocations);\n            Assert.Contains(\"location4\", result.SearchedLocations);\n        }\n\n        [Fact]\n        public void FindPartialViewFailureWithOneEngine()\n        {\n            // Arrange\n            ControllerContext context = new Mock<ControllerContext>().Object;\n            ViewEngineCollection collection = new ViewEngineCollection();\n            Mock<IViewEngine> engine = new Mock<IViewEngine>();\n            ViewEngineResult engineResult = new ViewEngineResult(new[] { \"location1\", \"location2\" });\n            engine.Setup(e => e.FindPartialView(context, \"partial\", It.IsAny<bool>())).Returns(engineResult);\n            collection.Add(engine.Object);\n\n            // Act\n            ViewEngineResult result = collection.FindPartialView(context, \"partial\");\n\n            // Assert\n            Assert.Null(result.View);\n            Assert.Equal(2, result.SearchedLocations.Count());\n            Assert.Contains(\"location1\", result.SearchedLocations);\n            Assert.Contains(\"location2\", result.SearchedLocations);\n        }\n\n        [Fact]\n        public void FindPartialViewLooksAtCacheFirst()\n        {\n            // Arrange\n            ControllerContext context = new Mock<ControllerContext>().Object;\n            Mock<IViewEngine> engine = new Mock<IViewEngine>();\n            ViewEngineResult engineResult = new ViewEngineResult(new Mock<IView>().Object, engine.Object);\n            engine.Setup(e => e.FindPartialView(context, \"partial\", true)).Returns(engineResult);\n            ViewEngineCollection collection = new ViewEngineCollection()\n            {\n                engine.Object,\n            };\n\n            // Act\n            ViewEngineResult result = collection.FindPartialView(context, \"partial\");\n\n            // Assert\n            Assert.Same(engineResult, result);\n            engine.Verify(e => e.FindPartialView(context, \"partial\", true), Times.Once());\n            engine.Verify(e => e.FindPartialView(context, \"partial\", false), Times.Never());\n        }\n\n        [Fact]\n        public void FindPartialViewLooksAtLocatorIfCacheEmpty()\n        {\n            // Arrange\n            ControllerContext context = new Mock<ControllerContext>().Object;\n            Mock<IViewEngine> engine = new Mock<IViewEngine>();\n            ViewEngineResult engineResult = new ViewEngineResult(new Mock<IView>().Object, engine.Object);\n            engine.Setup(e => e.FindPartialView(context, \"partial\", true)).Returns(new ViewEngineResult(new[] { \"path\" }));\n            engine.Setup(e => e.FindPartialView(context, \"partial\", false)).Returns(engineResult);\n            ViewEngineCollection collection = new ViewEngineCollection()\n            {\n                engine.Object,\n            };\n\n            // Act\n            ViewEngineResult result = collection.FindPartialView(context, \"partial\");\n\n            // Assert\n            Assert.Same(engineResult, result);\n            engine.Verify(e => e.FindPartialView(context, \"partial\", true), Times.Once());\n            engine.Verify(e => e.FindPartialView(context, \"partial\", false), Times.Once());\n        }\n\n        [Fact]\n        public void FindPartialViewIgnoresSearchLocationsFromCache()\n        {\n            // Arrange\n            ControllerContext context = new Mock<ControllerContext>().Object;\n            Mock<IViewEngine> engine = new Mock<IViewEngine>();\n            engine.Setup(e => e.FindPartialView(context, \"partial\", true)).Returns(new ViewEngineResult(new[] { \"cachePath\" }));\n            engine.Setup(e => e.FindPartialView(context, \"partial\", false)).Returns(new ViewEngineResult(new[] { \"locatorPath\" }));\n            ViewEngineCollection collection = new ViewEngineCollection()\n            {\n                engine.Object,\n            };\n\n            // Act\n            ViewEngineResult result = collection.FindPartialView(context, \"partial\");\n\n            // Assert\n            string searchedLocation = Assert.Single(result.SearchedLocations);\n            Assert.Equal(\"locatorPath\", searchedLocation);\n            engine.Verify(e => e.FindPartialView(context, \"partial\", true), Times.Once());\n            engine.Verify(e => e.FindPartialView(context, \"partial\", false), Times.Once());\n        }\n\n        [Fact]\n        public void FindPartialViewIteratesThroughCollectionUntilFindsSuccessfulEngine()\n        {\n            // Arrange\n            ControllerContext context = new Mock<ControllerContext>().Object;\n            ViewEngineCollection collection = new ViewEngineCollection();\n            Mock<IViewEngine> engine1 = new Mock<IViewEngine>();\n            ViewEngineResult engine1Result = new ViewEngineResult(new[] { \"location1\", \"location2\" });\n            engine1.Setup(e => e.FindPartialView(context, \"partial\", It.IsAny<bool>())).Returns(engine1Result);\n            Mock<IViewEngine> engine2 = new Mock<IViewEngine>();\n            ViewEngineResult engine2Result = new ViewEngineResult(new Mock<IView>().Object, engine2.Object);\n            engine2.Setup(e => e.FindPartialView(context, \"partial\", It.IsAny<bool>())).Returns(engine2Result);\n            collection.Add(engine1.Object);\n            collection.Add(engine2.Object);\n\n            // Act\n            ViewEngineResult result = collection.FindPartialView(context, \"partial\");\n\n            // Assert\n            Assert.Same(engine2Result, result);\n        }\n\n        [Fact]\n        public void FindPartialViewRemovesDuplicateSearchedLocationsFromMultipleEngines()\n        {\n            // Arrange\n            ControllerContext context = new Mock<ControllerContext>().Object;\n            Mock<IViewEngine> engine1 = new Mock<IViewEngine>();\n            ViewEngineResult engine1Result = new ViewEngineResult(new[] { \"repeatLocation\", \"location1\" });\n            engine1.Setup(e => e.FindPartialView(context, \"partial\", It.IsAny<bool>())).Returns(engine1Result);\n            Mock<IViewEngine> engine2 = new Mock<IViewEngine>();\n            ViewEngineResult engine2Result = new ViewEngineResult(new[] { \"location2\", \"repeatLocation\" });\n            engine2.Setup(e => e.FindPartialView(context, \"partial\", It.IsAny<bool>())).Returns(engine2Result);\n            ViewEngineCollection viewEngineCollection = new ViewEngineCollection()\n            {\n                engine1.Object,\n                engine2.Object,\n            };\n\n            // Act\n            ViewEngineResult result = viewEngineCollection.FindPartialView(context, \"partial\");\n\n            // Assert\n            var expectedLocations = new[] { \"repeatLocation\", \"location1\", \"location2\" };\n            Assert.Null(result.View);\n            Assert.Equal(expectedLocations, result.SearchedLocations.ToArray());\n        }\n\n        [Fact]\n        public void FindPartialViewReturnsNoViewAndEmptySearchedLocationsIfCollectionEmpty()\n        {\n            // Arrange\n            ControllerContext context = new Mock<ControllerContext>().Object;\n            ViewEngineCollection collection = new ViewEngineCollection();\n\n            // Act\n            ViewEngineResult result = collection.FindPartialView(context, \"partial\");\n\n            // Assert\n            Assert.Null(result.View);\n            Assert.Empty(result.SearchedLocations);\n        }\n\n        [Fact]\n        public void FindPartialViewReturnsValueFromFirstSuccessfulEngine()\n        {\n            // Arrange\n            ControllerContext context = new Mock<ControllerContext>().Object;\n            ViewEngineCollection collection = new ViewEngineCollection();\n            Mock<IViewEngine> engine1 = new Mock<IViewEngine>();\n            ViewEngineResult engine1Result = new ViewEngineResult(new Mock<IView>().Object, engine1.Object);\n            engine1.Setup(e => e.FindPartialView(context, \"partial\", It.IsAny<bool>())).Returns(engine1Result);\n            Mock<IViewEngine> engine2 = new Mock<IViewEngine>();\n            ViewEngineResult engine2Result = new ViewEngineResult(new Mock<IView>().Object, engine2.Object);\n            engine2.Setup(e => e.FindPartialView(context, \"partial\", It.IsAny<bool>())).Returns(engine2Result);\n            collection.Add(engine1.Object);\n            collection.Add(engine2.Object);\n\n            // Act\n            ViewEngineResult result = collection.FindPartialView(context, \"partial\");\n\n            // Assert\n            Assert.Same(engine1Result, result);\n        }\n\n        [Fact]\n        public void FindPartialViewSuccessWithOneEngine()\n        {\n            // Arrange\n            ControllerContext context = new Mock<ControllerContext>().Object;\n            ViewEngineCollection collection = new ViewEngineCollection();\n            Mock<IViewEngine> engine = new Mock<IViewEngine>();\n            ViewEngineResult engineResult = new ViewEngineResult(new Mock<IView>().Object, engine.Object);\n            engine.Setup(e => e.FindPartialView(context, \"partial\", It.IsAny<bool>())).Returns(engineResult);\n            collection.Add(engine.Object);\n\n            // Act\n            ViewEngineResult result = collection.FindPartialView(context, \"partial\");\n\n            // Assert\n            Assert.Same(engineResult, result);\n        }\n\n        [Fact]\n        public void FindPartialViewThrowsIfPartialViewNameIsEmpty()\n        {\n            // Arrange\n            ControllerContext context = new Mock<ControllerContext>().Object;\n            ViewEngineCollection collection = new ViewEngineCollection();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => collection.FindPartialView(context, \"\"),\n                \"partialViewName\");\n        }\n\n        [Fact]\n        public void FindPartialViewThrowsIfPartialViewNameIsNull()\n        {\n            // Arrange\n            ControllerContext context = new Mock<ControllerContext>().Object;\n            ViewEngineCollection collection = new ViewEngineCollection();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => collection.FindPartialView(context, null),\n                \"partialViewName\");\n        }\n\n        [Fact]\n        public void FindPartialViewThrowsIfControllerContextIsNull()\n        {\n            // Arrange\n            ViewEngineCollection collection = new ViewEngineCollection();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => collection.FindPartialView(null, \"partial\"),\n                \"controllerContext\");\n        }\n\n        [Fact]\n        public void FindViewAggregatesAllSearchedLocationsIfAllEnginesFail()\n        {\n            // Arrange\n            ControllerContext context = new Mock<ControllerContext>().Object;\n            ViewEngineCollection collection = new ViewEngineCollection();\n            Mock<IViewEngine> engine1 = new Mock<IViewEngine>();\n            ViewEngineResult engine1Result = new ViewEngineResult(new[] { \"location1\", \"location2\" });\n            engine1.Setup(e => e.FindView(context, \"view\", \"master\", It.IsAny<bool>())).Returns(engine1Result);\n            Mock<IViewEngine> engine2 = new Mock<IViewEngine>();\n            ViewEngineResult engine2Result = new ViewEngineResult(new[] { \"location3\", \"location4\" });\n            engine2.Setup(e => e.FindView(context, \"view\", \"master\", It.IsAny<bool>())).Returns(engine2Result);\n            collection.Add(engine1.Object);\n            collection.Add(engine2.Object);\n\n            // Act\n            ViewEngineResult result = collection.FindView(context, \"view\", \"master\");\n\n            // Assert\n            Assert.Null(result.View);\n            Assert.Equal(4, result.SearchedLocations.Count());\n            Assert.Contains(\"location1\", result.SearchedLocations);\n            Assert.Contains(\"location2\", result.SearchedLocations);\n            Assert.Contains(\"location3\", result.SearchedLocations);\n            Assert.Contains(\"location4\", result.SearchedLocations);\n        }\n\n        [Fact]\n        public void FindViewFailureWithOneEngine()\n        {\n            // Arrange\n            ControllerContext context = new Mock<ControllerContext>().Object;\n            ViewEngineCollection collection = new ViewEngineCollection();\n            Mock<IViewEngine> engine = new Mock<IViewEngine>();\n            ViewEngineResult engineResult = new ViewEngineResult(new[] { \"location1\", \"location2\" });\n            engine.Setup(e => e.FindView(context, \"view\", \"master\", It.IsAny<bool>())).Returns(engineResult);\n            collection.Add(engine.Object);\n\n            // Act\n            ViewEngineResult result = collection.FindView(context, \"view\", \"master\");\n\n            // Assert\n            Assert.Null(result.View);\n            Assert.Equal(2, result.SearchedLocations.Count());\n            Assert.Contains(\"location1\", result.SearchedLocations);\n            Assert.Contains(\"location2\", result.SearchedLocations);\n        }\n\n        [Fact]\n        public void FindViewLooksAtCacheFirst()\n        {\n            // Arrange\n            ControllerContext context = new Mock<ControllerContext>().Object;\n            Mock<IViewEngine> engine = new Mock<IViewEngine>();\n            ViewEngineResult engineResult = new ViewEngineResult(new Mock<IView>().Object, engine.Object);\n            engine.Setup(e => e.FindView(context, \"view\", \"master\", true)).Returns(engineResult);\n            ViewEngineCollection collection = new ViewEngineCollection()\n            {\n                engine.Object,\n            };\n\n            // Act\n            ViewEngineResult result = collection.FindView(context, \"view\", \"master\");\n\n            // Assert\n            Assert.Same(engineResult, result);\n            engine.Verify(e => e.FindView(context, \"view\", \"master\", true), Times.Once());\n            engine.Verify(e => e.FindView(context, \"view\", \"master\", false), Times.Never());\n        }\n\n        [Fact]\n        public void FindViewLooksAtLocatorIfCacheEmpty()\n        {\n            // Arrange\n            ControllerContext context = new Mock<ControllerContext>().Object;\n            Mock<IViewEngine> engine = new Mock<IViewEngine>();\n            ViewEngineResult engineResult = new ViewEngineResult(new Mock<IView>().Object, engine.Object);\n            engine.Setup(e => e.FindView(context, \"view\", \"master\", true)).Returns(new ViewEngineResult(new[] { \"path\" }));\n            engine.Setup(e => e.FindView(context, \"view\", \"master\", false)).Returns(engineResult);\n            ViewEngineCollection collection = new ViewEngineCollection()\n            {\n                engine.Object,\n            };\n\n            // Act\n            ViewEngineResult result = collection.FindView(context, \"view\", \"master\");\n\n            // Assert\n            Assert.Same(engineResult, result);\n            engine.Verify(e => e.FindView(context, \"view\", \"master\", true), Times.Once());\n            engine.Verify(e => e.FindView(context, \"view\", \"master\", false), Times.Once());\n        }\n\n        [Fact]\n        public void FindViewIgnoresSearchLocationsFromCache()\n        {\n            // Arrange\n            ControllerContext context = new Mock<ControllerContext>().Object;\n            Mock<IViewEngine> engine = new Mock<IViewEngine>();\n            engine.Setup(e => e.FindView(context, \"view\", \"master\", true)).Returns(new ViewEngineResult(new[] { \"cachePath\" }));\n            engine.Setup(e => e.FindView(context, \"view\", \"master\", false)).Returns(new ViewEngineResult(new[] { \"locatorPath\" }));\n            ViewEngineCollection collection = new ViewEngineCollection()\n            {\n                engine.Object,\n            };\n\n            // Act\n            ViewEngineResult result = collection.FindView(context, \"view\", \"master\");\n\n            // Assert\n            string searchedLocation = Assert.Single(result.SearchedLocations);\n            Assert.Equal(\"locatorPath\", searchedLocation);\n            engine.Verify(e => e.FindView(context, \"view\", \"master\", true), Times.Once());\n            engine.Verify(e => e.FindView(context, \"view\", \"master\", false), Times.Once());\n        }\n\n        [Fact]\n        public void FindViewIteratesThroughCollectionUntilFindsSuccessfulEngine()\n        {\n            // Arrange\n            ControllerContext context = new Mock<ControllerContext>().Object;\n            ViewEngineCollection collection = new ViewEngineCollection();\n            Mock<IViewEngine> engine1 = new Mock<IViewEngine>();\n            ViewEngineResult engine1Result = new ViewEngineResult(new[] { \"location1\", \"location2\" });\n            engine1.Setup(e => e.FindView(context, \"view\", \"master\", It.IsAny<bool>())).Returns(engine1Result);\n            Mock<IViewEngine> engine2 = new Mock<IViewEngine>();\n            ViewEngineResult engine2Result = new ViewEngineResult(new Mock<IView>().Object, engine2.Object);\n            engine2.Setup(e => e.FindView(context, \"view\", \"master\", It.IsAny<bool>())).Returns(engine2Result);\n            collection.Add(engine1.Object);\n            collection.Add(engine2.Object);\n\n            // Act\n            ViewEngineResult result = collection.FindView(context, \"view\", \"master\");\n\n            // Assert\n            Assert.Same(engine2Result, result);\n        }\n\n        [Fact]\n        public void FindViewRemovesDuplicateSearchedLocationsFromMultipleEngines()\n        {\n            // Arrange\n            ControllerContext context = new Mock<ControllerContext>().Object;\n            Mock<IViewEngine> engine1 = new Mock<IViewEngine>();\n            ViewEngineResult engine1Result = new ViewEngineResult(new[] { \"repeatLocation\", \"location1\" });\n            engine1.Setup(e => e.FindView(context, \"view\", \"master\", It.IsAny<bool>())).Returns(engine1Result);\n            Mock<IViewEngine> engine2 = new Mock<IViewEngine>();\n            ViewEngineResult engine2Result = new ViewEngineResult(new[] { \"location2\", \"repeatLocation\" });\n            engine2.Setup(e => e.FindView(context, \"view\", \"master\", It.IsAny<bool>())).Returns(engine2Result);\n            ViewEngineCollection collection = new ViewEngineCollection()\n            {\n                engine1.Object,\n                engine2.Object,\n            };\n\n            // Act\n            ViewEngineResult result = collection.FindView(context, \"view\", \"master\");\n\n            // Assert\n            Assert.Null(result.View);\n            var expectedLocations = new[] { \"repeatLocation\", \"location1\", \"location2\" };\n            Assert.Equal(expectedLocations, result.SearchedLocations.ToArray());\n        }\n\n        [Fact]\n        public void FindViewReturnsNoViewAndEmptySearchedLocationsIfCollectionEmpty()\n        {\n            // Arrange\n            ControllerContext context = new Mock<ControllerContext>().Object;\n            ViewEngineCollection collection = new ViewEngineCollection();\n\n            // Act\n            ViewEngineResult result = collection.FindView(context, \"view\", null);\n\n            // Assert\n            Assert.Null(result.View);\n            Assert.Empty(result.SearchedLocations);\n        }\n\n        [Fact]\n        public void FindViewReturnsValueFromFirstSuccessfulEngine()\n        {\n            // Arrange\n            ControllerContext context = new Mock<ControllerContext>().Object;\n            ViewEngineCollection collection = new ViewEngineCollection();\n            Mock<IViewEngine> engine1 = new Mock<IViewEngine>();\n            ViewEngineResult engine1Result = new ViewEngineResult(new Mock<IView>().Object, engine1.Object);\n            engine1.Setup(e => e.FindView(context, \"view\", \"master\", It.IsAny<bool>())).Returns(engine1Result);\n            Mock<IViewEngine> engine2 = new Mock<IViewEngine>();\n            ViewEngineResult engine2Result = new ViewEngineResult(new Mock<IView>().Object, engine2.Object);\n            engine2.Setup(e => e.FindView(context, \"view\", \"master\", It.IsAny<bool>())).Returns(engine2Result);\n            collection.Add(engine1.Object);\n            collection.Add(engine2.Object);\n\n            // Act\n            ViewEngineResult result = collection.FindView(context, \"view\", \"master\");\n\n            // Assert\n            Assert.Same(engine1Result, result);\n        }\n\n        [Fact]\n        public void FindViewSuccessWithOneEngine()\n        {\n            // Arrange\n            ControllerContext context = new Mock<ControllerContext>().Object;\n            ViewEngineCollection collection = new ViewEngineCollection();\n            Mock<IViewEngine> engine = new Mock<IViewEngine>();\n            ViewEngineResult engineResult = new ViewEngineResult(new Mock<IView>().Object, engine.Object);\n            engine.Setup(e => e.FindView(context, \"view\", \"master\", It.IsAny<bool>())).Returns(engineResult);\n            collection.Add(engine.Object);\n\n            // Act\n            ViewEngineResult result = collection.FindView(context, \"view\", \"master\");\n\n            // Assert\n            Assert.Same(engineResult, result);\n        }\n\n        [Fact]\n        public void FindViewThrowsIfControllerContextIsNull()\n        {\n            // Arrange\n            ViewEngineCollection collection = new ViewEngineCollection();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => collection.FindView(null, \"view\", null),\n                \"controllerContext\"\n                );\n        }\n\n        [Fact]\n        public void FindViewThrowsIfViewNameIsEmpty()\n        {\n            // Arrange\n            ControllerContext context = new Mock<ControllerContext>().Object;\n            ViewEngineCollection collection = new ViewEngineCollection();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => collection.FindView(context, \"\", null),\n                \"viewName\"\n                );\n        }\n\n        [Fact]\n        public void FindViewThrowsIfViewNameIsNull()\n        {\n            // Arrange\n            ControllerContext context = new Mock<ControllerContext>().Object;\n            ViewEngineCollection collection = new ViewEngineCollection();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => collection.FindView(context, null, null),\n                \"viewName\"\n                );\n        }\n\n        [Fact]\n        public void FindViewDelegatesToResolver()\n        {\n            // Arrange\n            Mock<IView> view = new Mock<IView>();\n            ControllerContext context = new ControllerContext();\n            Mock<IViewEngine> locatedEngine = new Mock<IViewEngine>();\n            ViewEngineResult engineResult = new ViewEngineResult(view.Object, locatedEngine.Object);\n            locatedEngine.Setup(e => e.FindView(context, \"ViewName\", \"MasterName\", true))\n                .Returns(engineResult);\n            Mock<IViewEngine> secondEngine = new Mock<IViewEngine>();\n\n            var resolver = new Mock<IDependencyResolver>();\n            resolver.Setup(r => r.GetServices(typeof(IViewEngine))).Returns(new IViewEngine[] { locatedEngine.Object, secondEngine.Object });\n\n            ViewEngineCollection engines = new ViewEngineCollection(new IViewEngine[0], resolver.Object);\n\n            // Act\n            ViewEngineResult result = engines.FindView(context, \"ViewName\", \"MasterName\");\n\n            // Assert\n            Assert.Same(engineResult, result);\n            secondEngine.Verify(e => e.FindView(context, \"ViewName\", \"MasterName\", It.IsAny<bool>()), Times.Never());\n        }\n\n        [Fact]\n        public void FindPartialViewDelegatesToResolver()\n        {\n            // Arrange\n            Mock<IView> view = new Mock<IView>();\n            ControllerContext context = new ControllerContext();\n            Mock<IViewEngine> locatedEngine = new Mock<IViewEngine>();\n            ViewEngineResult engineResult = new ViewEngineResult(view.Object, locatedEngine.Object);\n            locatedEngine.Setup(e => e.FindPartialView(context, \"ViewName\", true))\n                .Returns(engineResult);\n            Mock<IViewEngine> secondEngine = new Mock<IViewEngine>();\n\n            var resolver = new Mock<IDependencyResolver>();\n            resolver.Setup(r => r.GetServices(typeof(IViewEngine))).Returns(new IViewEngine[] { locatedEngine.Object, secondEngine.Object });\n\n            ViewEngineCollection engines = new ViewEngineCollection(new IViewEngine[0], resolver.Object);\n\n            // Act\n            ViewEngineResult result = engines.FindPartialView(context, \"ViewName\");\n\n            // Assert\n            Assert.Same(engineResult, result);\n            secondEngine.Verify(e => e.FindPartialView(context, \"ViewName\", It.IsAny<bool>()), Times.Never());\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ViewEngineResultTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ViewEngineResultTest\n    {\n        [Fact]\n        public void ConstructorThrowsIfSearchedLocationsIsNull()\n        {\n            // Arrange\n            string[] searchedLocations = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ViewEngineResult(searchedLocations); }, \"searchedLocations\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfViewIsNull()\n        {\n            // Arrange\n            IView view = null;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ViewEngineResult(view, null); }, \"view\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfViewEngineIsNull()\n        {\n            // Arrange\n            IView view = new Mock<IView>().Object;\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                delegate { new ViewEngineResult(view, null); }, \"viewEngine\");\n        }\n\n        [Fact]\n        public void SearchedLocationsProperty()\n        {\n            // Arrange\n            string[] searchedLocations = new string[0];\n            ViewEngineResult result = new ViewEngineResult(searchedLocations);\n\n            // Act & Assert\n            Assert.Same(searchedLocations, result.SearchedLocations);\n            Assert.Null(result.View);\n        }\n\n        [Fact]\n        public void ViewProperty()\n        {\n            // Arrange\n            IView view = new Mock<IView>().Object;\n            IViewEngine viewEngine = new Mock<IViewEngine>().Object;\n            ViewEngineResult result = new ViewEngineResult(view, viewEngine);\n\n            // Act & Assert\n            Assert.Same(view, result.View);\n            Assert.Null(result.SearchedLocations);\n        }\n\n        [Fact]\n        public void ViewEngineProperty()\n        {\n            // Arrange\n            IView view = new Mock<IView>().Object;\n            IViewEngine viewEngine = new Mock<IViewEngine>().Object;\n            ViewEngineResult result = new ViewEngineResult(view, viewEngine);\n\n            // Act & Assert\n            Assert.Same(viewEngine, result.ViewEngine);\n            Assert.Null(result.SearchedLocations);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ViewEnginesTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")]\n    public class ViewEnginesTest\n    {\n        [Fact]\n        public void EnginesProperty()\n        {\n            // Act\n            ViewEngineCollection collection = ViewEngines.Engines;\n\n            // Assert\n            Assert.Equal(2, collection.Count);\n            Assert.IsType<WebFormViewEngine>(collection[0]);\n            Assert.IsType<RazorViewEngine>(collection[1]);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ViewMasterPageControlBuilderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ViewMasterPageControlBuilderTest\n    {\n        [Fact]\n        public void BuilderWithoutInheritsDoesNothing()\n        {\n            // Arrange\n            var builder = new ViewMasterPageControlBuilder();\n            var derivedType = new CodeTypeDeclaration();\n            derivedType.BaseTypes.Add(\"basetype\");\n\n            // Act\n            builder.ProcessGeneratedCode(null, null, derivedType, null, null);\n\n            // Assert\n            Assert.Equal(\"basetype\", derivedType.BaseTypes.Cast<CodeTypeReference>().Single().BaseType);\n        }\n\n        [Fact]\n        public void BuilderWithInheritsSetsBaseType()\n        {\n            // Arrange\n            var builder = new ViewMasterPageControlBuilder { Inherits = \"inheritedtype\" };\n            var derivedType = new CodeTypeDeclaration();\n            derivedType.BaseTypes.Add(\"basetype\");\n\n            // Act\n            builder.ProcessGeneratedCode(null, null, derivedType, null, null);\n\n            // Assert\n            Assert.Equal(\"inheritedtype\", derivedType.BaseTypes.Cast<CodeTypeReference>().Single().BaseType);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ViewMasterPageTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Web.Routing;\nusing System.Web.UI;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ViewMasterPageTest\n    {\n        [Fact]\n        public void GetModelFromViewPage()\n        {\n            // Arrange\n            ViewMasterPage vmp = new ViewMasterPage();\n            ViewPage vp = new ViewPage();\n            vmp.Page = vp;\n            object model = new object();\n            vp.ViewData = new ViewDataDictionary(model);\n\n            // Assert\n            Assert.Equal(model, vmp.Model);\n        }\n\n        [Fact]\n        public void GetModelFromViewPageStronglyTyped()\n        {\n            // Arrange\n            ViewMasterPage<FooModel> vmp = new ViewMasterPage<FooModel>();\n            ViewPage vp = new ViewPage();\n            vmp.Page = vp;\n            FooModel model = new FooModel();\n            vp.ViewData = new ViewDataDictionary(model);\n\n            // Assert\n            Assert.Equal(model, vmp.Model);\n        }\n\n        [Fact]\n        public void GetViewDataFromViewPage()\n        {\n            // Arrange\n            ViewMasterPage vmp = new ViewMasterPage();\n            ViewPage vp = new ViewPage();\n            vmp.Page = vp;\n            vp.ViewData = new ViewDataDictionary { { \"a\", \"123\" }, { \"b\", \"456\" } };\n\n            // Assert\n            Assert.Equal(\"123\", vmp.ViewData.Eval(\"a\"));\n            Assert.Equal(\"456\", vmp.ViewData.Eval(\"b\"));\n        }\n\n        [Fact]\n        public void GetViewItemFromViewPageTViewData()\n        {\n            // Arrange\n            MockViewMasterPageDummyViewData vmp = new MockViewMasterPageDummyViewData();\n            MockViewPageDummyViewData vp = new MockViewPageDummyViewData();\n            vmp.Page = vp;\n            vp.ViewData.Model = new DummyViewData { MyInt = 123, MyString = \"abc\" };\n\n            // Assert\n            Assert.Equal(123, vmp.ViewData.Model.MyInt);\n            Assert.Equal(\"abc\", vmp.ViewData.Model.MyString);\n        }\n\n        [Fact]\n        public void GetWriterFromViewPage()\n        {\n            // Arrange\n            bool triggered = false;\n            HtmlTextWriter writer = new HtmlTextWriter(TextWriter.Null);\n            ViewMasterPage vmp = new ViewMasterPage();\n            MockViewPage vp = new MockViewPage();\n            vp.RenderCallback = delegate()\n            {\n                triggered = true;\n                Assert.Equal(writer, vmp.Writer);\n            };\n            vmp.Page = vp;\n\n            // Act & Assert\n            Assert.Null(vmp.Writer);\n            vp.RenderControl(writer);\n            Assert.Null(vmp.Writer);\n            Assert.True(triggered);\n        }\n\n        [Fact]\n        public void GetViewDataFromPageThrows()\n        {\n            // Arrange\n            ViewMasterPage vmp = new ViewMasterPage();\n            vmp.Page = new Page();\n\n            // Assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { object foo = vmp.ViewData; },\n                \"A ViewMasterPage can be used only with content pages that derive from ViewPage or ViewPage<TModel>.\");\n        }\n\n        [Fact]\n        public void GetViewItemFromWrongGenericViewPageType()\n        {\n            // Arrange\n            MockViewMasterPageDummyViewData vmp = new MockViewMasterPageDummyViewData();\n            MockViewPageBogusViewData vp = new MockViewPageBogusViewData();\n            vmp.Page = vp;\n            vp.ViewData.Model = new SelectListItem();\n\n            // Assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { object foo = vmp.ViewData.Model; },\n                \"The model item passed into the dictionary is of type 'System.Web.Mvc.SelectListItem', but this dictionary requires a model item of type 'System.Web.Mvc.Test.ViewMasterPageTest+DummyViewData'.\");\n        }\n\n        [Fact]\n        public void GetViewDataFromNullPageThrows()\n        {\n            // Arrange\n            MockViewMasterPageDummyViewData vmp = new MockViewMasterPageDummyViewData();\n\n            // Assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { object foo = vmp.ViewData; },\n                \"A ViewMasterPage can be used only with content pages that derive from ViewPage or ViewPage<TModel>.\");\n        }\n\n        [Fact]\n        public void GetViewDataFromRegularPageThrows()\n        {\n            // Arrange\n            MockViewMasterPageDummyViewData vmp = new MockViewMasterPageDummyViewData();\n            vmp.Page = new Page();\n\n            // Assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { object foo = vmp.ViewData; },\n                \"A ViewMasterPage can be used only with content pages that derive from ViewPage or ViewPage<TModel>.\");\n        }\n\n        [Fact]\n        public void GetHtmlHelperFromViewPage()\n        {\n            // Arrange\n            ViewMasterPage vmp = new ViewMasterPage();\n            ViewPage vp = new ViewPage();\n            vmp.Page = vp;\n            ViewContext vc = new Mock<ViewContext>().Object;\n\n            HtmlHelper<object> htmlHelper = new HtmlHelper<object>(vc, vp);\n            vp.Html = htmlHelper;\n\n            // Assert\n            Assert.Equal(vmp.Html, htmlHelper);\n        }\n\n        [Fact]\n        public void GetUrlHelperFromViewPage()\n        {\n            // Arrange\n            ViewMasterPage vmp = new ViewMasterPage();\n            ViewPage vp = new ViewPage();\n            vmp.Page = vp;\n            RequestContext rc = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData());\n            UrlHelper urlHelper = new UrlHelper(rc);\n            vp.Url = urlHelper;\n\n            // Assert\n            Assert.Equal(vmp.Url, urlHelper);\n        }\n\n        [Fact]\n        public void ViewBagProperty_ReflectsViewData()\n        {\n            // Arrange\n            ViewPage page = new ViewPage();\n            ViewMasterPage masterPage = new ViewMasterPage();\n            masterPage.Page = page;\n            masterPage.ViewData[\"A\"] = 1;\n\n            // Act & Assert\n            Assert.NotNull(masterPage.ViewBag);\n            Assert.Equal(1, masterPage.ViewBag.A);\n        }\n\n        [Fact]\n        public void ViewBagProperty_PropagatesChangesToViewData()\n        {\n            // Arrange\n            ViewPage page = new ViewPage();\n            ViewMasterPage masterPage = new ViewMasterPage();\n            masterPage.Page = page;\n            masterPage.ViewData[\"A\"] = 1;\n\n            // Act\n            masterPage.ViewBag.A = \"foo\";\n            masterPage.ViewBag.B = 2;\n\n            // Assert\n            Assert.Equal(\"foo\", masterPage.ViewData[\"A\"]);\n            Assert.Equal(2, masterPage.ViewData[\"B\"]);\n        }\n\n        // Master page types\n        private sealed class MockViewMasterPageDummyViewData : ViewMasterPage<DummyViewData>\n        {\n        }\n\n        // View data types\n        private sealed class DummyViewData\n        {\n            public int MyInt { get; set; }\n            public string MyString { get; set; }\n        }\n\n        // Page types\n        private sealed class MockViewPageBogusViewData : ViewPage<SelectListItem>\n        {\n        }\n\n        private sealed class MockViewPageDummyViewData : ViewPage<DummyViewData>\n        {\n        }\n\n        private sealed class MockViewPage : ViewPage\n        {\n            public Action RenderCallback { get; set; }\n\n            protected override void RenderChildren(HtmlTextWriter writer)\n            {\n                if (RenderCallback != null)\n                {\n                    RenderCallback();\n                }\n                base.RenderChildren(writer);\n            }\n        }\n\n        private sealed class FooModel\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ViewPageControlBuilderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ViewPageControlBuilderTest\n    {\n        [Fact]\n        public void BuilderWithoutInheritsDoesNothing()\n        {\n            // Arrange\n            var builder = new ViewPageControlBuilder();\n            var derivedType = new CodeTypeDeclaration();\n            derivedType.BaseTypes.Add(\"basetype\");\n\n            // Act\n            builder.ProcessGeneratedCode(null, null, derivedType, null, null);\n\n            // Assert\n            Assert.Equal(\"basetype\", derivedType.BaseTypes.Cast<CodeTypeReference>().Single().BaseType);\n        }\n\n        [Fact]\n        public void BuilderWithInheritsSetsBaseType()\n        {\n            // Arrange\n            var builder = new ViewPageControlBuilder { Inherits = \"inheritedtype\" };\n            var derivedType = new CodeTypeDeclaration();\n            derivedType.BaseTypes.Add(\"basetype\");\n\n            // Act\n            builder.ProcessGeneratedCode(null, null, derivedType, null, null);\n\n            // Assert\n            Assert.Equal(\"inheritedtype\", derivedType.BaseTypes.Cast<CodeTypeReference>().Single().BaseType);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ViewPageTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Web.UI;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ViewPageTest\n    {\n        [Fact]\n        public void ModelProperty()\n        {\n            // Arrange\n            object model = new object();\n            ViewDataDictionary viewData = new ViewDataDictionary(model);\n            ViewPage viewPage = new ViewPage();\n            viewPage.ViewData = viewData;\n\n            // Act\n            object viewPageModel = viewPage.Model;\n\n            // Assert\n            Assert.Equal(model, viewPageModel);\n            Assert.Equal(model, viewPage.ViewData.Model);\n        }\n\n        [Fact]\n        public void ModelPropertyStronglyTypedViewPage()\n        {\n            // Arrange\n            FooModel model = new FooModel();\n            ViewDataDictionary<FooModel> viewData = new ViewDataDictionary<FooModel>(model);\n            ViewPage<FooModel> viewPage = new ViewPage<FooModel>();\n            viewPage.ViewData = viewData;\n\n            // Act\n            object viewPageModelObject = ((ViewPage)viewPage).Model;\n            FooModel viewPageModelPerson = viewPage.Model;\n\n            // Assert\n            Assert.Equal(model, viewPageModelObject);\n            Assert.Equal(model, viewPageModelPerson);\n        }\n\n        [Fact]\n        public void SetViewItemOnBaseClassPropagatesToDerivedClass()\n        {\n            // Arrange\n            ViewPage<object> vpInt = new ViewPage<object>();\n            ViewPage vp = vpInt;\n            object o = new object();\n\n            // Act\n            vp.ViewData.Model = o;\n\n            // Assert\n            Assert.Equal(o, vpInt.ViewData.Model);\n            Assert.Equal(o, vp.ViewData.Model);\n        }\n\n        [Fact]\n        public void SetViewItemOnDerivedClassPropagatesToBaseClass()\n        {\n            // Arrange\n            ViewPage<object> vpInt = new ViewPage<object>();\n            ViewPage vp = vpInt;\n            object o = new object();\n\n            // Act\n            vpInt.ViewData.Model = o;\n\n            // Assert\n            Assert.Equal(o, vpInt.ViewData.Model);\n            Assert.Equal(o, vp.ViewData.Model);\n        }\n\n        [Fact]\n        public void SetViewItemToWrongTypeThrows()\n        {\n            // Arrange\n            ViewPage vp = new ViewPage<string>();\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { vp.ViewData.Model = 50; },\n                \"The model item passed into the dictionary is of type 'System.Int32', but this dictionary requires a model item of type 'System.String'.\");\n        }\n\n        [Fact]\n        public void RenderInitsHelpersAndSetsID()\n        {\n            // Arrange\n            ViewPageWithNoProcessRequest viewPage = new ViewPageWithNoProcessRequest();\n            TextWriter writer = new StringWriter();\n\n            Mock<ViewContext> mockViewContext = new Mock<ViewContext>();\n            mockViewContext.Setup(c => c.Writer).Returns(writer);\n            mockViewContext.Setup(c => c.HttpContext.Response.Output).Returns(TextWriter.Null);\n            mockViewContext.Setup(c => c.HttpContext.Server.Execute(It.IsAny<IHttpHandler>(), It.IsAny<TextWriter>(), true))\n                .Callback<IHttpHandler, TextWriter, bool>((_h, _w, _pf) =>\n                {\n                    ViewPage.SwitchWriter switchWriter = _w as ViewPage.SwitchWriter;\n                    Assert.NotNull(switchWriter);\n                    Assert.Same(writer, switchWriter.InnerWriter);\n                })\n                .Verifiable();\n\n            // Act\n            viewPage.RenderView(mockViewContext.Object);\n\n            // Assert\n            mockViewContext.Verify();\n            Assert.NotNull(viewPage.Ajax);\n            Assert.NotNull(viewPage.Html);\n            Assert.NotNull(viewPage.Url);\n        }\n\n        [Fact]\n        public void GenericPageRenderInitsHelpersAndSetsID()\n        {\n            // Arrange\n            Mock<ViewContext> mockViewContext = new Mock<ViewContext>();\n            mockViewContext.Setup(c => c.Writer).Returns(new StringWriter());\n            mockViewContext.Setup(c => c.HttpContext.Response.Output).Returns(TextWriter.Null);\n            mockViewContext.Setup(c => c.HttpContext.Server).Returns(new Mock<HttpServerUtilityBase>().Object);\n\n            ViewPageWithNoProcessRequest<Controller> viewPage = new ViewPageWithNoProcessRequest<Controller>();\n\n            // Act\n            viewPage.RenderView(mockViewContext.Object);\n\n            // Assert\n            Assert.NotNull(viewPage.Ajax);\n            Assert.NotNull(viewPage.Html);\n            Assert.NotNull(viewPage.Url);\n            Assert.NotNull(((ViewPage)viewPage).Html);\n            Assert.NotNull(((ViewPage)viewPage).Url);\n        }\n\n        private static void WriterSetCorrectlyInternal(bool throwException)\n        {\n            // Arrange\n            bool triggered = false;\n            HtmlTextWriter writer = new HtmlTextWriter(TextWriter.Null);\n            MockViewPage vp = new MockViewPage();\n            vp.RenderCallback = delegate()\n            {\n                triggered = true;\n                Assert.Equal(writer, vp.Writer);\n                if (throwException)\n                {\n                    throw new CallbackException();\n                }\n            };\n\n            // Act & Assert\n            Assert.Null(vp.Writer);\n            try\n            {\n                vp.RenderControl(writer);\n            }\n            catch (CallbackException)\n            {\n            }\n            Assert.Null(vp.Writer);\n            Assert.True(triggered);\n        }\n\n        [Fact]\n        public void WriterSetCorrectly()\n        {\n            WriterSetCorrectlyInternal(false /* throwException */);\n        }\n\n        [Fact]\n        public void WriterSetCorrectlyThrowException()\n        {\n            WriterSetCorrectlyInternal(true /* throwException */);\n        }\n\n        private sealed class ViewPageWithNoProcessRequest : ViewPage\n        {\n            public override void ProcessRequest(HttpContext context)\n            {\n            }\n        }\n\n        private sealed class ViewPageWithNoProcessRequest<TModel> : ViewPage<TModel>\n        {\n            public override void ProcessRequest(HttpContext context)\n            {\n            }\n        }\n\n        [Fact]\n        public void ViewBagProperty_ReflectsViewData()\n        {\n            // Arrange\n            ViewPage page = new ViewPage();\n            page.ViewData[\"A\"] = 1;\n\n            // Act & Assert\n            Assert.NotNull(page.ViewBag);\n            Assert.Equal(1, page.ViewBag.A);\n        }\n\n        [Fact]\n        public void ViewBagProperty_ReflectsNewViewDataInstance()\n        {\n            // Arrange\n            ViewPage page = new ViewPage();\n            page.ViewData[\"A\"] = 1;\n            page.ViewData = new ViewDataDictionary() { { \"A\", \"bar\" } };\n\n            // Act & Assert\n            Assert.Equal(\"bar\", page.ViewBag.A);\n        }\n\n        [Fact]\n        public void ViewBagProperty_PropagatesChangesToViewData()\n        {\n            // Arrange\n            ViewPage page = new ViewPage();\n            page.ViewData[\"A\"] = 1;\n\n            // Act\n            page.ViewBag.A = \"foo\";\n            page.ViewBag.B = 2;\n\n            // Assert\n            Assert.Equal(\"foo\", page.ViewData[\"A\"]);\n            Assert.Equal(2, page.ViewData[\"B\"]);\n        }\n\n        private sealed class MockViewPage : ViewPage\n        {\n            public MockViewPage()\n            {\n            }\n\n            public Action RenderCallback { get; set; }\n\n            protected override void RenderChildren(HtmlTextWriter writer)\n            {\n                if (RenderCallback != null)\n                {\n                    RenderCallback();\n                }\n                base.RenderChildren(writer);\n            }\n        }\n\n        private sealed class FooModel\n        {\n        }\n\n        private sealed class CallbackException : Exception\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ViewResultBaseTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ViewResultBaseTest\n    {\n        [Fact]\n        public void ExecuteResultWithNullControllerContextThrows()\n        {\n            // Arrange\n            ViewResultBaseHelper result = new ViewResultBaseHelper();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => result.ExecuteResult(null),\n                \"context\");\n        }\n\n        [Fact]\n        public void TempDataProperty()\n        {\n            // Arrange\n            TempDataDictionary newDict = new TempDataDictionary();\n            ViewResultBaseHelper result = new ViewResultBaseHelper();\n\n            // Act & Assert\n            MemberHelper.TestPropertyWithDefaultInstance(result, \"TempData\", newDict);\n        }\n\n        [Fact]\n        public void ViewDataProperty()\n        {\n            // Arrange\n            ViewDataDictionary newDict = new ViewDataDictionary();\n            ViewResultBaseHelper result = new ViewResultBaseHelper();\n\n            // Act & Assert\n            MemberHelper.TestPropertyWithDefaultInstance(result, \"ViewData\", newDict);\n        }\n\n        [Fact]\n        public void ViewEngineCollectionProperty()\n        {\n            // Arrange\n            ViewEngineCollection viewEngineCollection = new ViewEngineCollection();\n            ViewResultBaseHelper result = new ViewResultBaseHelper();\n\n            // Act & Assert\n            MemberHelper.TestPropertyWithDefaultInstance(result, \"ViewEngineCollection\", viewEngineCollection);\n        }\n\n        [Fact]\n        public void ViewNameProperty()\n        {\n            // Arrange\n            ViewResultBaseHelper result = new ViewResultBaseHelper();\n\n            // Act & Assert\n            MemberHelper.TestStringProperty(result, \"ViewName\", String.Empty);\n        }\n\n        public class ViewResultBaseHelper : ViewResultBase\n        {\n            protected override ViewEngineResult FindView(ControllerContext context)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ViewResultTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Web.Routing;\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ViewResultTest\n    {\n        private const string _viewName = \"My cool view.\";\n        private const string _masterName = \"My cool master.\";\n\n        [Fact]\n        public void EmptyViewNameUsesActionNameAsViewName()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            HttpContextBase httpContext = CreateHttpContext();\n            RouteData routeData = new RouteData();\n            routeData.Values[\"action\"] = _viewName;\n            ControllerContext context = new ControllerContext(httpContext, routeData, controller);\n            Mock<IViewEngine> viewEngine = new Mock<IViewEngine>(MockBehavior.Strict);\n            Mock<IView> view = new Mock<IView>(MockBehavior.Strict);\n            List<IViewEngine> viewEngines = new List<IViewEngine>();\n            viewEngines.Add(viewEngine.Object);\n            Mock<ViewEngineCollection> viewEngineCollection = new Mock<ViewEngineCollection>(MockBehavior.Strict, viewEngines);\n            ViewResult result = new ViewResultHelper { ViewEngineCollection = viewEngineCollection.Object };\n            viewEngineCollection\n                .Setup(e => e.FindView(It.IsAny<ControllerContext>(), _viewName, _masterName))\n                .Returns(new ViewEngineResult(view.Object, viewEngine.Object));\n            viewEngine\n                .Setup(e => e.FindView(It.IsAny<ControllerContext>(), _viewName, _masterName, It.IsAny<bool>()))\n                .Callback<ControllerContext, string, string, bool>(\n                    (controllerContext, viewName, masterName, useCache) =>\n                    {\n                        Assert.Same(httpContext, controllerContext.HttpContext);\n                        Assert.Same(routeData, controllerContext.RouteData);\n                    })\n                .Returns(new ViewEngineResult(view.Object, viewEngine.Object));\n            view\n                .Setup(o => o.Render(It.IsAny<ViewContext>(), httpContext.Response.Output))\n                .Callback<ViewContext, TextWriter>(\n                    (viewContext, writer) =>\n                    {\n                        Assert.Same(view.Object, viewContext.View);\n                        Assert.Same(result.ViewData, viewContext.ViewData);\n                        Assert.Same(result.TempData, viewContext.TempData);\n                        Assert.Same(controller, viewContext.Controller);\n                    });\n            viewEngine\n                .Setup(e => e.ReleaseView(context, It.IsAny<IView>()))\n                .Callback<ControllerContext, IView>(\n                    (controllerContext, releasedView) => { Assert.Same(releasedView, view.Object); });\n\n            // Act\n            result.ExecuteResult(context);\n\n            // Assert\n            viewEngine.Verify();\n            viewEngineCollection.Verify();\n            view.Verify();\n        }\n\n        [Fact]\n        public void EngineLookupFailureThrows()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            HttpContextBase httpContext = CreateHttpContext();\n            RouteData routeData = new RouteData();\n            routeData.Values[\"action\"] = _viewName;\n            ControllerContext context = new ControllerContext(httpContext, routeData, controller);\n            Mock<IViewEngine> viewEngine = new Mock<IViewEngine>(MockBehavior.Strict);\n            List<IViewEngine> viewEngines = new List<IViewEngine>();\n            viewEngines.Add(viewEngine.Object);\n            Mock<ViewEngineCollection> viewEngineCollection = new Mock<ViewEngineCollection>(MockBehavior.Strict, viewEngines);\n            ViewResult result = new ViewResultHelper { ViewEngineCollection = viewEngineCollection.Object };\n            viewEngineCollection\n                .Setup(e => e.FindView(It.IsAny<ControllerContext>(), _viewName, _masterName))\n                .Returns(new ViewEngineResult(new[] { \"location1\", \"location2\" }));\n            viewEngine\n                .Setup(e => e.FindView(It.IsAny<ControllerContext>(), _viewName, _masterName, It.IsAny<bool>()))\n                .Callback<ControllerContext, string, string, bool>(\n                    (controllerContext, viewName, masterName, useCache) =>\n                    {\n                        Assert.Same(httpContext, controllerContext.HttpContext);\n                        Assert.Same(routeData, controllerContext.RouteData);\n                    })\n                .Returns(new ViewEngineResult(new[] { \"location1\", \"location2\" }));\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => result.ExecuteResult(context),\n                \"The view '\" + _viewName + \"' or its master was not found or no view engine supports the searched locations. The following locations were searched:\" + Environment.NewLine\n              + \"location1\" + Environment.NewLine\n              + \"location2\");\n\n            viewEngine.Verify();\n            viewEngineCollection.Verify();\n        }\n\n        [Fact]\n        public void EngineLookupSuccessRendersView()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            HttpContextBase httpContext = CreateHttpContext();\n            RouteData routeData = new RouteData();\n            ControllerContext context = new ControllerContext(httpContext, routeData, controller);\n            Mock<IViewEngine> viewEngine = new Mock<IViewEngine>(MockBehavior.Strict);\n            Mock<IView> view = new Mock<IView>(MockBehavior.Strict);\n            List<IViewEngine> viewEngines = new List<IViewEngine>();\n            viewEngines.Add(viewEngine.Object);\n            Mock<ViewEngineCollection> viewEngineCollection = new Mock<ViewEngineCollection>(MockBehavior.Strict, viewEngines);\n            ViewResult result = new ViewResultHelper { ViewName = _viewName, ViewEngineCollection = viewEngineCollection.Object };\n            view\n                .Setup(o => o.Render(It.IsAny<ViewContext>(), httpContext.Response.Output))\n                .Callback<ViewContext, TextWriter>(\n                    (viewContext, writer) =>\n                    {\n                        Assert.Same(view.Object, viewContext.View);\n                        Assert.Same(result.ViewData, viewContext.ViewData);\n                        Assert.Same(result.TempData, viewContext.TempData);\n                        Assert.Same(controller, viewContext.Controller);\n                    });\n            viewEngineCollection\n                .Setup(e => e.FindView(It.IsAny<ControllerContext>(), _viewName, _masterName))\n                .Returns(new ViewEngineResult(view.Object, viewEngine.Object));\n            viewEngine\n                .Setup(e => e.FindView(It.IsAny<ControllerContext>(), _viewName, _masterName, It.IsAny<bool>()))\n                .Callback<ControllerContext, string, string, bool>(\n                    (controllerContext, viewName, masterName, useCache) =>\n                    {\n                        Assert.Same(httpContext, controllerContext.HttpContext);\n                        Assert.Same(routeData, controllerContext.RouteData);\n                    })\n                .Returns(new ViewEngineResult(view.Object, viewEngine.Object));\n            viewEngine\n                .Setup(e => e.ReleaseView(context, It.IsAny<IView>()))\n                .Callback<ControllerContext, IView>(\n                    (controllerContext, releasedView) => { Assert.Same(releasedView, view.Object); });\n\n            // Act\n            result.ExecuteResult(context);\n\n            // Assert\n            viewEngine.Verify();\n            viewEngineCollection.Verify();\n            view.Verify();\n        }\n\n        [Fact]\n        public void ExecuteResultWithExplicitViewObject()\n        {\n            // Arrange\n            ControllerBase controller = new Mock<ControllerBase>().Object;\n            HttpContextBase httpContext = CreateHttpContext();\n            RouteData routeData = new RouteData();\n            routeData.Values[\"action\"] = _viewName;\n            ControllerContext context = new ControllerContext(httpContext, routeData, controller);\n            Mock<IView> view = new Mock<IView>(MockBehavior.Strict);\n            ViewResult result = new ViewResultHelper { View = view.Object };\n            view\n                .Setup(o => o.Render(It.IsAny<ViewContext>(), httpContext.Response.Output))\n                .Callback<ViewContext, TextWriter>(\n                    (viewContext, writer) =>\n                    {\n                        Assert.Same(view.Object, viewContext.View);\n                        Assert.Same(result.ViewData, viewContext.ViewData);\n                        Assert.Same(result.TempData, viewContext.TempData);\n                        Assert.Same(controller, viewContext.Controller);\n                    });\n\n            // Act\n            result.ExecuteResult(context);\n\n            // Assert\n            view.Verify();\n        }\n\n        [Fact]\n        public void ExecuteResultWithNullControllerContextThrows()\n        {\n            // Arrange\n            ViewResult result = new ViewResultHelper();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => result.ExecuteResult(null),\n                \"context\");\n        }\n\n        [Fact]\n        public void MasterNameProperty()\n        {\n            // Arrange\n            ViewResult result = new ViewResult();\n\n            // Act & Assert\n            MemberHelper.TestStringProperty(result, \"MasterName\", String.Empty);\n        }\n\n        private static HttpContextBase CreateHttpContext()\n        {\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(c => c.Response.Output).Returns(TextWriter.Null);\n            return mockHttpContext.Object;\n        }\n\n        private class ViewResultHelper : ViewResult\n        {\n            public ViewResultHelper()\n            {\n                ViewEngineCollection = new ViewEngineCollection(new IViewEngine[] { new WebFormViewEngine() });\n                MasterName = _masterName;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ViewStartPageTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Routing;\nusing System.Web.WebPages;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ViewStartPageTest\n    {\n        [Fact]\n        public void Html_DelegatesToChildPage()\n        {\n            // Arrange\n            MockViewStartPage viewStart = new MockViewStartPage();\n            var viewPage = new Mock<WebViewPage>() { CallBase = true };\n            var helper = new HtmlHelper<object>(new ViewContext() { ViewData = new ViewDataDictionary() }, viewPage.Object, new RouteCollection());\n            viewPage.Object.Html = helper;\n            viewStart.ChildPage = viewPage.Object;\n\n            // Act\n            var result = viewStart.Html;\n\n            // Assert\n            Assert.Same(helper, result);\n        }\n\n        [Fact]\n        public void Url_DelegatesToChildPage()\n        {\n            // Arrange\n            MockViewStartPage viewStart = new MockViewStartPage();\n            var viewPage = new Mock<WebViewPage>() { CallBase = true };\n            var helper = new UrlHelper(new RequestContext());\n            viewPage.Object.Url = helper;\n            viewStart.ChildPage = viewPage.Object;\n\n            // Act\n            var result = viewStart.Url;\n\n            // Assert\n            Assert.Same(helper, result);\n        }\n\n        [Fact]\n        public void ViewContext_DelegatesToChildPage()\n        {\n            // Arrange\n            MockViewStartPage viewStart = new MockViewStartPage();\n            var viewPage = new Mock<WebViewPage>() { CallBase = true };\n            var viewContext = new ViewContext();\n            viewPage.Object.ViewContext = viewContext;\n            viewStart.ChildPage = viewPage.Object;\n\n            // Act\n            var result = viewStart.ViewContext;\n\n            // Assert\n            Assert.Same(viewContext, result);\n        }\n\n        [Fact]\n        public void ViewStartPageChild_ThrowsOnNonMvcChildPage()\n        {\n            // Arrange\n            MockViewStartPage viewStart = new MockViewStartPage();\n            viewStart.ChildPage = new Mock<WebPage>().Object;\n\n            // Act + Assert\n            Assert.Throws<InvalidOperationException>(delegate() { var c = viewStart.ViewStartPageChild; }, \"A ViewStartPage can be used only with with a page that derives from WebViewPage or another ViewStartPage.\");\n        }\n\n        [Fact]\n        public void ViewStartPageChild_WorksWithWebViewPage()\n        {\n            // Arrange\n            MockViewStartPage viewStart = new MockViewStartPage();\n            var viewPage = new Mock<WebViewPage>();\n            viewStart.ChildPage = viewPage.Object;\n\n            // Act\n            var result = viewStart.ViewStartPageChild;\n\n            // Assert\n            Assert.Same(viewPage.Object, result);\n        }\n\n        [Fact]\n        public void ViewStartPageChild_WorksWithAnotherRazorStartPage()\n        {\n            // Arrange\n            MockViewStartPage viewStart = new MockViewStartPage();\n            var anotherViewStart = new Mock<ViewStartPage>();\n            viewStart.ChildPage = anotherViewStart.Object;\n\n            // Act\n            var result = viewStart.ViewStartPageChild;\n\n            // Assert\n            Assert.Same(anotherViewStart.Object, result);\n        }\n\n        class MockViewStartPage : ViewStartPage\n        {\n            public override void Execute()\n            {\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ViewTypeParserFilterTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.UI;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ViewTypeParserFilterTest\n    {\n        // Non-generic directives\n\n        [Fact]\n        public void NonGenericPageDirectiveDoesNotChangeInheritsDirective()\n        {\n            var filter = new ViewTypeParserFilter();\n            var attributes = new Dictionary<string, string> { { \"inherits\", \"foobar\" } };\n            var builder = new MvcBuilder();\n\n            filter.PreprocessDirective(\"page\", attributes);\n            filter.ParseComplete(builder);\n\n            Assert.Equal(\"foobar\", attributes[\"inherits\"]);\n            Assert.Null(builder.Inherits);\n        }\n\n        [Fact]\n        public void NonGenericControlDirectiveDoesNotChangeInheritsDirective()\n        {\n            var filter = new ViewTypeParserFilter();\n            var attributes = new Dictionary<string, string> { { \"inherits\", \"foobar\" } };\n            var builder = new MvcBuilder();\n\n            filter.PreprocessDirective(\"control\", attributes);\n            filter.ParseComplete(builder);\n\n            Assert.Equal(\"foobar\", attributes[\"inherits\"]);\n            Assert.Null(builder.Inherits);\n        }\n\n        [Fact]\n        public void NonGenericMasterDirectiveDoesNotChangeInheritsDirective()\n        {\n            var filter = new ViewTypeParserFilter();\n            var attributes = new Dictionary<string, string> { { \"inherits\", \"foobar\" } };\n            var builder = new MvcBuilder();\n\n            filter.PreprocessDirective(\"master\", attributes);\n            filter.ParseComplete(builder);\n\n            Assert.Equal(\"foobar\", attributes[\"inherits\"]);\n            Assert.Null(builder.Inherits);\n        }\n\n        // C#-style generic directives\n\n        [Fact]\n        public void CSGenericUnknownDirectiveDoesNotChangeInheritsDirective()\n        {\n            var filter = new ViewTypeParserFilter();\n            var attributes = new Dictionary<string, string> { { \"inherits\", \"foobar<baz>\" } };\n            var builder = new MvcBuilder();\n\n            filter.PreprocessDirective(\"unknown\", attributes);\n            filter.ParseComplete(builder);\n\n            Assert.Equal(\"foobar<baz>\", attributes[\"inherits\"]);\n            Assert.Null(builder.Inherits);\n        }\n\n        [Fact]\n        public void CSGenericPageDirectiveChangesInheritsDirective()\n        {\n            var filter = new ViewTypeParserFilter();\n            var attributes = new Dictionary<string, string> { { \"inherits\", \"foobar<baz>\" } };\n            var builder = new MvcBuilder();\n\n            filter.PreprocessDirective(\"page\", attributes);\n            filter.ParseComplete(builder);\n\n            Assert.Equal(typeof(ViewPage).FullName, attributes[\"inherits\"]);\n            Assert.Equal(\"foobar<baz>\", builder.Inherits);\n        }\n\n        [Fact]\n        public void CSGenericControlDirectiveChangesInheritsDirective()\n        {\n            var filter = new ViewTypeParserFilter();\n            var attributes = new Dictionary<string, string> { { \"inherits\", \"foobar<baz>\" } };\n            var builder = new MvcBuilder();\n\n            filter.PreprocessDirective(\"control\", attributes);\n            filter.ParseComplete(builder);\n\n            Assert.Equal(typeof(ViewUserControl).FullName, attributes[\"inherits\"]);\n            Assert.Equal(\"foobar<baz>\", builder.Inherits);\n        }\n\n        [Fact]\n        public void CSGenericMasterDirectiveChangesInheritsDirective()\n        {\n            var filter = new ViewTypeParserFilter();\n            var attributes = new Dictionary<string, string> { { \"inherits\", \"foobar<baz>\" } };\n            var builder = new MvcBuilder();\n\n            filter.PreprocessDirective(\"master\", attributes);\n            filter.ParseComplete(builder);\n\n            Assert.Equal(typeof(ViewMasterPage).FullName, attributes[\"inherits\"]);\n            Assert.Equal(\"foobar<baz>\", builder.Inherits);\n        }\n\n        [Fact]\n        public void CSDirectivesAfterPageDirectiveProperlyPreserveInheritsDirective()\n        {\n            var filter = new ViewTypeParserFilter();\n            var pageAttributes = new Dictionary<string, string> { { \"inherits\", \"foobar<baz>\" } };\n            var importAttributes = new Dictionary<string, string> { { \"inherits\", \"dummyvalue<baz>\" } };\n            var builder = new MvcBuilder();\n\n            filter.PreprocessDirective(\"page\", pageAttributes);\n            filter.PreprocessDirective(\"import\", importAttributes);\n            filter.ParseComplete(builder);\n\n            Assert.Equal(typeof(ViewPage).FullName, pageAttributes[\"inherits\"]);\n            Assert.Equal(\"foobar<baz>\", builder.Inherits);\n        }\n\n        // VB.NET-style generic directives\n\n        [Fact]\n        public void VBGenericUnknownDirectiveDoesNotChangeInheritsDirective()\n        {\n            var filter = new ViewTypeParserFilter();\n            var attributes = new Dictionary<string, string> { { \"inherits\", \"foobar(of baz)\" } };\n            var builder = new MvcBuilder();\n\n            filter.PreprocessDirective(\"unknown\", attributes);\n            filter.ParseComplete(builder);\n\n            Assert.Equal(\"foobar(of baz)\", attributes[\"inherits\"]);\n            Assert.Null(builder.Inherits);\n        }\n\n        [Fact]\n        public void VBGenericPageDirectiveChangesInheritsDirective()\n        {\n            var filter = new ViewTypeParserFilter();\n            var attributes = new Dictionary<string, string> { { \"inherits\", \"foobar(of baz)\" } };\n            var builder = new MvcBuilder();\n\n            filter.PreprocessDirective(\"page\", attributes);\n            filter.ParseComplete(builder);\n\n            Assert.Equal(typeof(ViewPage).FullName, attributes[\"inherits\"]);\n            Assert.Equal(\"foobar(of baz)\", builder.Inherits);\n        }\n\n        [Fact]\n        public void VBGenericControlDirectiveChangesInheritsDirective()\n        {\n            var filter = new ViewTypeParserFilter();\n            var attributes = new Dictionary<string, string> { { \"inherits\", \"foobar(of baz)\" } };\n            var builder = new MvcBuilder();\n\n            filter.PreprocessDirective(\"control\", attributes);\n            filter.ParseComplete(builder);\n\n            Assert.Equal(typeof(ViewUserControl).FullName, attributes[\"inherits\"]);\n            Assert.Equal(\"foobar(of baz)\", builder.Inherits);\n        }\n\n        [Fact]\n        public void VBGenericMasterDirectiveChangesInheritsDirective()\n        {\n            var filter = new ViewTypeParserFilter();\n            var attributes = new Dictionary<string, string> { { \"inherits\", \"foobar(of baz)\" } };\n            var builder = new MvcBuilder();\n\n            filter.PreprocessDirective(\"master\", attributes);\n            filter.ParseComplete(builder);\n\n            Assert.Equal(typeof(ViewMasterPage).FullName, attributes[\"inherits\"]);\n            Assert.Equal(\"foobar(of baz)\", builder.Inherits);\n        }\n\n        [Fact]\n        public void VBDirectivesAfterPageDirectiveProperlyPreserveInheritsDirective()\n        {\n            var filter = new ViewTypeParserFilter();\n            var pageAttributes = new Dictionary<string, string> { { \"inherits\", \"foobar(of baz)\" } };\n            var importAttributes = new Dictionary<string, string> { { \"inherits\", \"dummyvalue(of baz)\" } };\n            var builder = new MvcBuilder();\n\n            filter.PreprocessDirective(\"page\", pageAttributes);\n            filter.PreprocessDirective(\"import\", importAttributes);\n            filter.ParseComplete(builder);\n\n            Assert.Equal(typeof(ViewPage).FullName, pageAttributes[\"inherits\"]);\n            Assert.Equal(\"foobar(of baz)\", builder.Inherits);\n        }\n\n        // Helpers\n\n        private class MvcBuilder : RootBuilder, IMvcControlBuilder\n        {\n            public string Inherits { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ViewUserControlControlBuilderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ViewUserControlControlBuilderTest\n    {\n        [Fact]\n        public void BuilderWithoutInheritsDoesNothing()\n        {\n            // Arrange\n            var builder = new ViewUserControlControlBuilder();\n            var derivedType = new CodeTypeDeclaration();\n            derivedType.BaseTypes.Add(\"basetype\");\n\n            // Act\n            builder.ProcessGeneratedCode(null, null, derivedType, null, null);\n\n            // Assert\n            Assert.Equal(\"basetype\", derivedType.BaseTypes.Cast<CodeTypeReference>().Single().BaseType);\n        }\n\n        [Fact]\n        public void BuilderWithInheritsSetsBaseType()\n        {\n            // Arrange\n            var builder = new ViewUserControlControlBuilder { Inherits = \"inheritedtype\" };\n            var derivedType = new CodeTypeDeclaration();\n            derivedType.BaseTypes.Add(\"basetype\");\n\n            // Act\n            builder.ProcessGeneratedCode(null, null, derivedType, null, null);\n\n            // Assert\n            Assert.Equal(\"inheritedtype\", derivedType.BaseTypes.Cast<CodeTypeReference>().Single().BaseType);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/ViewUserControlTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Web.Routing;\nusing System.Web.TestUtil;\nusing System.Web.UI;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ViewUserControlTest\n    {\n        [Fact]\n        public void ModelProperty()\n        {\n            // Arrange\n            object model = new object();\n            ViewDataDictionary viewData = new ViewDataDictionary(model);\n            ViewUserControl viewUserControl = new ViewUserControl();\n            viewUserControl.ViewData = viewData;\n\n            // Act\n            object viewPageModel = viewUserControl.Model;\n\n            // Assert\n            Assert.Equal(model, viewPageModel);\n            Assert.Equal(model, viewUserControl.ViewData.Model);\n        }\n\n        [Fact]\n        public void ModelPropertyStronglyTyped()\n        {\n            // Arrange\n            FooModel model = new FooModel();\n            ViewDataDictionary<FooModel> viewData = new ViewDataDictionary<FooModel>(model);\n            ViewUserControl<FooModel> viewUserControl = new ViewUserControl<FooModel>();\n            viewUserControl.ViewData = viewData;\n\n            // Act\n            object viewPageModelObject = ((ViewUserControl)viewUserControl).Model;\n            FooModel viewPageModelPerson = viewUserControl.Model;\n\n            // Assert\n            Assert.Equal(model, viewPageModelObject);\n            Assert.Equal(model, viewPageModelPerson);\n        }\n\n        [Fact]\n        public void RenderViewAndRestoreContentType()\n        {\n            // Arrange\n            Mock<ViewContext> mockViewContext = new Mock<ViewContext>();\n            mockViewContext.SetupProperty(c => c.HttpContext.Response.ContentType);\n            ViewContext vc = mockViewContext.Object;\n\n            Mock<ViewPage> mockViewPage = new Mock<ViewPage>();\n            mockViewPage.Setup(vp => vp.RenderView(vc)).Callback(() => vc.HttpContext.Response.ContentType = \"newContentType\");\n\n            // Act\n            vc.HttpContext.Response.ContentType = \"oldContentType\";\n            ViewUserControl.RenderViewAndRestoreContentType(mockViewPage.Object, vc);\n            string postContentType = vc.HttpContext.Response.ContentType;\n\n            // Assert\n            Assert.Equal(\"oldContentType\", postContentType);\n        }\n\n        [Fact]\n        public void SetViewItem()\n        {\n            // Arrange\n            ViewUserControl vuc = new ViewUserControl();\n            object viewItem = new object();\n            vuc.ViewData = new ViewDataDictionary(viewItem);\n\n            // Act\n            vuc.ViewData.Model = viewItem;\n            object newViewItem = vuc.ViewData.Model;\n\n            // Assert\n            Assert.Same(viewItem, newViewItem);\n        }\n\n        [Fact]\n        public void SetViewItemOnBaseClassPropagatesToDerivedClass()\n        {\n            // Arrange\n            ViewUserControl<object> vucInt = new ViewUserControl<object>();\n            ViewUserControl vuc = vucInt;\n            vuc.ViewData = new ViewDataDictionary();\n            object o = new object();\n\n            // Act\n            vuc.ViewData.Model = o;\n\n            // Assert\n            Assert.Equal(o, vucInt.ViewData.Model);\n            Assert.Equal(o, vuc.ViewData.Model);\n        }\n\n        [Fact]\n        public void SetViewItemOnDerivedClassPropagatesToBaseClass()\n        {\n            // Arrange\n            ViewUserControl<object> vucInt = new ViewUserControl<object>();\n            ViewUserControl vuc = vucInt;\n            vucInt.ViewData = new ViewDataDictionary<object>();\n            object o = new object();\n\n            // Act\n            vucInt.ViewData.Model = o;\n\n            // Assert\n            Assert.Equal(o, vucInt.ViewData.Model);\n            Assert.Equal(o, vuc.ViewData.Model);\n        }\n\n        [Fact]\n        public void SetViewItemToWrongTypeThrows()\n        {\n            // Arrange\n            ViewUserControl<string> vucString = new ViewUserControl<string>();\n            vucString.ViewData = new ViewDataDictionary<string>();\n            ViewUserControl vuc = vucString;\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { vuc.ViewData.Model = 50; },\n                \"The model item passed into the dictionary is of type 'System.Int32', but this dictionary requires a model item of type 'System.String'.\");\n        }\n\n        [Fact]\n        public void GetViewDataWhenNoPageSetThrows()\n        {\n            ViewUserControl vuc = new ViewUserControl();\n            vuc.AppRelativeVirtualPath = \"~/Foo.ascx\";\n\n            Assert.Throws<InvalidOperationException>(\n                delegate { var foo = vuc.ViewData[\"Foo\"]; },\n                \"The ViewUserControl '~/Foo.ascx' cannot find an IViewDataContainer object. The ViewUserControl must be inside a ViewPage, a ViewMasterPage, or another ViewUserControl.\");\n        }\n\n        [Fact]\n        public void GetViewDataWhenRegularPageSetThrows()\n        {\n            Page p = new Page();\n            p.Controls.Add(new Control());\n            ViewUserControl vuc = new ViewUserControl();\n            p.Controls[0].Controls.Add(vuc);\n            vuc.AppRelativeVirtualPath = \"~/Foo.ascx\";\n\n            Assert.Throws<InvalidOperationException>(\n                delegate { var foo = vuc.ViewData[\"Foo\"]; },\n                \"The ViewUserControl '~/Foo.ascx' cannot find an IViewDataContainer object. The ViewUserControl must be inside a ViewPage, a ViewMasterPage, or another ViewUserControl.\");\n        }\n\n        [Fact]\n        public void GetViewDataFromViewPage()\n        {\n            // Arrange\n            ViewPage p = new ViewPage();\n            p.Controls.Add(new Control());\n            ViewUserControl vuc = new ViewUserControl();\n            p.Controls[0].Controls.Add(vuc);\n            p.ViewData = new ViewDataDictionary { { \"FirstName\", \"Joe\" }, { \"LastName\", \"Schmoe\" } };\n\n            // Act\n            object firstName = vuc.ViewData.Eval(\"FirstName\");\n            object lastName = vuc.ViewData.Eval(\"LastName\");\n\n            // Assert\n            Assert.Equal(\"Joe\", firstName);\n            Assert.Equal(\"Schmoe\", lastName);\n        }\n\n        [Fact]\n        public void GetViewDataFromViewPageWithViewDataKeyPointingToObject()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary()\n            {\n                { \"Foo\", \"FooParent\" },\n                { \"Bar\", \"BarParent\" },\n                { \"Child\", new object() }\n            };\n\n            ViewPage p = new ViewPage();\n            p.Controls.Add(new Control());\n            ViewUserControl vuc = new ViewUserControl() { ViewDataKey = \"Child\" };\n            p.Controls[0].Controls.Add(vuc);\n            p.ViewData = vdd;\n\n            // Act\n            object oFoo = vuc.ViewData.Eval(\"Foo\");\n            object oBar = vuc.ViewData.Eval(\"Bar\");\n\n            // Assert\n            Assert.Equal(vdd[\"Child\"], vuc.ViewData.Model);\n            Assert.Equal(\"FooParent\", oFoo);\n            Assert.Equal(\"BarParent\", oBar);\n        }\n\n        [Fact]\n        public void GetViewDataFromViewPageWithViewDataKeyPointingToViewDataDictionary()\n        {\n            // Arrange\n            ViewDataDictionary vdd = new ViewDataDictionary()\n            {\n                { \"Foo\", \"FooParent\" },\n                { \"Bar\", \"BarParent\" },\n                {\n                    \"Child\",\n                    new ViewDataDictionary()\n                    {\n                        { \"Foo\", \"FooChild\" },\n                        { \"Bar\", \"BarChild\" }\n                    }\n                    }\n            };\n\n            ViewPage p = new ViewPage();\n            p.Controls.Add(new Control());\n            ViewUserControl vuc = new ViewUserControl() { ViewDataKey = \"Child\" };\n            p.Controls[0].Controls.Add(vuc);\n            p.ViewData = vdd;\n\n            // Act\n            object oFoo = vuc.ViewData.Eval(\"Foo\");\n            object oBar = vuc.ViewData.Eval(\"Bar\");\n\n            // Assert\n            Assert.Equal(vdd[\"Child\"], vuc.ViewData);\n            Assert.Equal(\"FooChild\", oFoo);\n            Assert.Equal(\"BarChild\", oBar);\n        }\n\n        [Fact]\n        public void GetViewDataFromViewUserControl()\n        {\n            // Arrange\n            ViewPage p = new ViewPage();\n            p.Controls.Add(new Control());\n            ViewUserControl outerVuc = new ViewUserControl();\n            p.Controls[0].Controls.Add(outerVuc);\n            outerVuc.Controls.Add(new Control());\n            ViewUserControl vuc = new ViewUserControl();\n            outerVuc.Controls[0].Controls.Add(vuc);\n\n            p.ViewData = new ViewDataDictionary { { \"FirstName\", \"Joe\" }, { \"LastName\", \"Schmoe\" } };\n\n            // Act\n            object firstName = vuc.ViewData.Eval(\"FirstName\");\n            object lastName = vuc.ViewData.Eval(\"LastName\");\n\n            // Assert\n            Assert.Equal(\"Joe\", firstName);\n            Assert.Equal(\"Schmoe\", lastName);\n        }\n\n        [Fact]\n        public void GetViewDataFromViewUserControlWithViewDataKeyOnInnerControl()\n        {\n            // Arrange\n            ViewPage p = new ViewPage();\n            p.Controls.Add(new Control());\n            ViewUserControl outerVuc = new ViewUserControl();\n            p.Controls[0].Controls.Add(outerVuc);\n            outerVuc.Controls.Add(new Control());\n            ViewUserControl vuc = new ViewUserControl() { ViewDataKey = \"SubData\" };\n            outerVuc.Controls[0].Controls.Add(vuc);\n\n            p.ViewData = new ViewDataDictionary { { \"FirstName\", \"Joe\" }, { \"LastName\", \"Schmoe\" } };\n            p.ViewData[\"SubData\"] = new ViewDataDictionary { { \"FirstName\", \"SubJoe\" }, { \"LastName\", \"SubSchmoe\" } };\n\n            // Act\n            object firstName = vuc.ViewData.Eval(\"FirstName\");\n            object lastName = vuc.ViewData.Eval(\"LastName\");\n\n            // Assert\n            Assert.Equal(\"SubJoe\", firstName);\n            Assert.Equal(\"SubSchmoe\", lastName);\n        }\n\n        [Fact]\n        public void GetViewDataFromViewUserControlWithViewDataKeyOnOuterControl()\n        {\n            // Arrange\n            ViewPage p = new ViewPage();\n            p.Controls.Add(new Control());\n            ViewUserControl outerVuc = new ViewUserControl() { ViewDataKey = \"SubData\" };\n            p.Controls[0].Controls.Add(outerVuc);\n            outerVuc.Controls.Add(new Control());\n            ViewUserControl vuc = new ViewUserControl();\n            outerVuc.Controls[0].Controls.Add(vuc);\n\n            p.ViewData = new ViewDataDictionary { { \"FirstName\", \"Joe\" }, { \"LastName\", \"Schmoe\" } };\n            p.ViewData[\"SubData\"] = new ViewDataDictionary { { \"FirstName\", \"SubJoe\" }, { \"LastName\", \"SubSchmoe\" } };\n\n            // Act\n            object firstName = vuc.ViewData.Eval(\"FirstName\");\n            object lastName = vuc.ViewData.Eval(\"LastName\");\n\n            // Assert\n            Assert.Equal(\"SubJoe\", firstName);\n            Assert.Equal(\"SubSchmoe\", lastName);\n        }\n\n        [Fact]\n        public void ViewDataKeyProperty()\n        {\n            MemberHelper.TestStringProperty(new ViewUserControl(), \"ViewDataKey\", String.Empty, testDefaultValueAttribute: true);\n        }\n\n        [Fact]\n        public void GetWrongGenericViewItemTypeThrows()\n        {\n            // Arrange\n            ViewPage p = new ViewPage();\n            p.ViewData = new ViewDataDictionary();\n            p.ViewData[\"Foo\"] = new DummyViewData { MyInt = 123, MyString = \"Whatever\" };\n\n            MockViewUserControl<MyViewData> vuc = new MockViewUserControl<MyViewData>() { ViewDataKey = \"FOO\" };\n            vuc.AppRelativeVirtualPath = \"~/Foo.aspx\";\n            p.Controls.Add(new Control());\n            p.Controls[0].Controls.Add(vuc);\n\n            // Act\n            Assert.Throws<InvalidOperationException>(\n                delegate { var foo = vuc.ViewData.Model.IntProp; },\n                @\"The model item passed into the dictionary is of type 'System.Web.Mvc.Test.ViewUserControlTest+DummyViewData', but this dictionary requires a model item of type 'System.Web.Mvc.Test.ViewUserControlTest+MyViewData'.\");\n        }\n\n        [Fact]\n        public void GetGenericViewItemType()\n        {\n            // Arrange\n            ViewPage p = new ViewPage();\n            p.Controls.Add(new Control());\n            MockViewUserControl<MyViewData> vuc = new MockViewUserControl<MyViewData>() { ViewDataKey = \"FOO\" };\n            p.Controls[0].Controls.Add(vuc);\n            p.ViewData = new ViewDataDictionary();\n            p.ViewData[\"Foo\"] = new MyViewData { IntProp = 123, StringProp = \"miao\" };\n\n            // Act\n            int intProp = vuc.ViewData.Model.IntProp;\n            string stringProp = vuc.ViewData.Model.StringProp;\n\n            // Assert\n            Assert.Equal(123, intProp);\n            Assert.Equal(\"miao\", stringProp);\n        }\n\n        [Fact]\n        public void GetHtmlHelperFromViewPage()\n        {\n            // Arrange\n            ViewUserControl vuc = new ViewUserControl();\n            ViewPage containerPage = new ViewPage();\n            containerPage.Controls.Add(vuc);\n            ViewContext vc = new Mock<ViewContext>().Object;\n            vuc.ViewContext = vc;\n\n            // Act\n            HtmlHelper htmlHelper = vuc.Html;\n\n            // Assert\n            Assert.Equal(vc, htmlHelper.ViewContext);\n            Assert.Equal(vuc, htmlHelper.ViewDataContainer);\n        }\n\n        [Fact]\n        public void GetHtmlHelperFromRegularPage()\n        {\n            // Arrange\n            ViewUserControl vuc = new ViewUserControl();\n            Page containerPage = new Page();\n            containerPage.Controls.Add(vuc);\n\n            // Assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { HtmlHelper foo = vuc.Html; },\n                \"A ViewUserControl can be used only in pages that derive from ViewPage or ViewPage<TModel>.\");\n        }\n\n        [Fact]\n        public void GetUrlHelperFromViewPage()\n        {\n            // Arrange\n            ViewUserControl vuc = new ViewUserControl();\n            ViewPage containerPage = new ViewPage();\n            containerPage.Controls.Add(vuc);\n            RequestContext rc = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData());\n            UrlHelper urlHelper = new UrlHelper(rc);\n            containerPage.Url = urlHelper;\n\n            // Assert\n            Assert.Equal(vuc.Url, urlHelper);\n        }\n\n        [Fact]\n        public void GetUrlHelperFromRegularPage()\n        {\n            // Arrange\n            ViewUserControl vuc = new ViewUserControl();\n            Page containerPage = new Page();\n            containerPage.Controls.Add(vuc);\n\n            // Assert\n            Assert.Throws<InvalidOperationException>(\n                delegate { UrlHelper foo = vuc.Url; },\n                \"A ViewUserControl can be used only in pages that derive from ViewPage or ViewPage<TModel>.\");\n        }\n\n        [Fact]\n        public void GetWriterFromViewPage()\n        {\n            // Arrange\n            MockViewUserControl vuc = new MockViewUserControl();\n            MockViewUserControlContainerPage containerPage = new MockViewUserControlContainerPage(vuc);\n            bool triggered = false;\n            HtmlTextWriter writer = new HtmlTextWriter(TextWriter.Null);\n            containerPage.RenderCallback = delegate()\n            {\n                triggered = true;\n                Assert.Equal(writer, vuc.Writer);\n            };\n\n            // Act & Assert\n            Assert.Null(vuc.Writer);\n            containerPage.RenderControl(writer);\n            Assert.Null(vuc.Writer);\n            Assert.True(triggered);\n        }\n\n        [Fact]\n        public void GetWriterFromRegularPageThrows()\n        {\n            // Arrange\n            MockViewUserControl vuc = new MockViewUserControl();\n            Page containerPage = new Page();\n            containerPage.Controls.Add(vuc);\n\n            // Act\n            Assert.Throws<InvalidOperationException>(\n                delegate { HtmlTextWriter writer = vuc.Writer; },\n                \"A ViewUserControl can be used only in pages that derive from ViewPage or ViewPage<TModel>.\");\n        }\n\n        [Fact]\n        public void ViewBagProperty_ReflectsViewData()\n        {\n            // Arrange\n            ViewPage containerPage = new ViewPage();\n            ViewUserControl userControl = new ViewUserControl();\n            containerPage.Controls.Add(userControl);\n            userControl.ViewData[\"A\"] = 1;\n\n            // Act & Assert\n            Assert.NotNull(userControl.ViewBag);\n            Assert.Equal(1, userControl.ViewBag.A);\n        }\n\n        [Fact]\n        public void ViewBagProperty_ReflectsNewViewDataInstance()\n        {\n            // Arrange\n            ViewPage containerPage = new ViewPage();\n            ViewUserControl userControl = new ViewUserControl();\n            containerPage.Controls.Add(userControl);\n            userControl.ViewData[\"A\"] = 1;\n            userControl.ViewData = new ViewDataDictionary() { { \"A\", \"bar\" } };\n\n            // Act & Assert\n            Assert.Equal(\"bar\", userControl.ViewBag.A);\n        }\n\n        [Fact]\n        public void ViewBagProperty_PropagatesChangesToViewData()\n        {\n            // Arrange\n            ViewPage containerPage = new ViewPage();\n            ViewUserControl userControl = new ViewUserControl();\n            containerPage.Controls.Add(userControl);\n            userControl.ViewData[\"A\"] = 1;\n\n            // Act\n            userControl.ViewBag.A = \"foo\";\n            userControl.ViewBag.B = 2;\n\n            // Assert\n            Assert.Equal(\"foo\", userControl.ViewData[\"A\"]);\n            Assert.Equal(2, userControl.ViewData[\"B\"]);\n        }\n\n        private sealed class DummyViewData\n        {\n            public int MyInt { get; set; }\n            public string MyString { get; set; }\n        }\n\n        private sealed class MockViewUserControlContainerPage : ViewPage\n        {\n            public Action RenderCallback { get; set; }\n\n            public MockViewUserControlContainerPage(ViewUserControl userControl)\n            {\n                Controls.Add(userControl);\n            }\n\n            protected override void RenderChildren(HtmlTextWriter writer)\n            {\n                if (RenderCallback != null)\n                {\n                    RenderCallback();\n                }\n                base.RenderChildren(writer);\n            }\n        }\n\n        private sealed class MockViewUserControl : ViewUserControl\n        {\n        }\n\n        private sealed class MockViewUserControl<TViewData> : ViewUserControl<TViewData>\n        {\n        }\n\n        private sealed class MyViewData\n        {\n            public int IntProp { get; set; }\n            public string StringProp { get; set; }\n        }\n\n        private sealed class FooModel\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/VirtualPathProviderViewEngineTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.IO;\nusing System.Linq;\nusing System.Web.Hosting;\nusing System.Web.Routing;\nusing System.Web.WebPages;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class VirtualPathProviderViewEngineTest : IDisposable\n    {\n        private ControllerContext _context = CreateContext();\n        private ControllerContext _mobileContext = CreateContext(isMobileDevice: true);\n        private TestableVirtualPathProviderViewEngine _engine = new TestableVirtualPathProviderViewEngine();\n\n        public void Dispose()\n        {\n            // If any mock failures get reported in this method they might mask other failures that occurred in the main test body.\n            // If you are seeing any test failures, try commenting out these lines first to aid in debugging.\n            _engine.MockCache.Verify();\n            _engine.MockPathProvider.Verify();\n        }\n\n        [Fact]\n        public void CreateCacheKey_IncludesAssemblyName()\n        {\n            // Arrange\n            var engine = new DerivedVirtualPathProviderViewEngine();\n\n            // Act\n            var key = engine.CreateCacheKey(\"prefix\", \"viewName\", \"controllerName\", \"areaName\");\n\n            // Assert\n            Assert.Equal(\":ViewCacheEntry:System.Web.Mvc.Test.VirtualPathProviderViewEngineTest+DerivedVirtualPathProviderViewEngine, System.Web.Mvc.Test, Version=0.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35:prefix:viewName:controllerName:areaName:\", key);\n        }\n\n        [Fact]\n        public void FindView_NullControllerContext_Throws()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => _engine.FindView(null, \"view name\", null, false),\n                \"controllerContext\"\n                );\n        }\n\n        [Theory]\n        [InlineData(null)]\n        [InlineData(\"\")]\n        public void FindView_InvalidViewName_Throws(string viewName)\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => _engine.FindView(_context, viewName, null, false),\n                \"viewName\"\n                );\n        }\n\n        [Fact]\n        public void FindView_ControllerNameNotInRequestContext_Throws()\n        {\n            // Arrange\n            _context.RouteData.Values.Remove(\"controller\");\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => _engine.FindView(_context, \"viewName\", null, false),\n                \"The RouteData must contain an item named 'controller' with a non-empty string value.\"\n                );\n        }\n\n        [Fact]\n        public void FindView_EmptyViewLocations_Throws()\n        {\n            // Arrange\n            _engine.ClearViewLocations();\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => _engine.FindView(_context, \"viewName\", null, false),\n                \"The property 'ViewLocationFormats' cannot be null or empty.\"\n                );\n        }\n\n        [Fact]\n        public void FindView_ViewDoesNotExistAndNoMaster_ReturnsSearchedLocationsResult()\n        {\n            // Arrange\n            SetupFileDoesNotExist(\"~/vpath/controllerName/viewName.view\");\n\n            // Act\n            ViewEngineResult result = _engine.FindView(_context, \"viewName\", null, false);\n\n            // Assert\n            Assert.Null(result.View);\n            Assert.Equal(\"~/vpath/controllerName/viewName.view\", Assert.Single(result.SearchedLocations));\n        }\n\n        [Fact]\n        public void FindView_ViewExistsAndNoMaster_ReturnsView()\n        {\n            // Arrange\n            _engine.ClearMasterLocations(); // If master is not provided, master locations can be empty\n\n            SetupFileExists(\"~/vpath/controllerName/viewName.view\");\n            SetupCacheHit(CreateCacheKey(Cache.View), \"~/vpath/controllerName/viewName.view\");\n\n            SetupFileDoesNotExist(\"~/vpath/controllerName/viewName.Mobile.view\");\n            SetupCacheMiss(CreateCacheKey(Cache.View, displayMode: \"Mobile\"));\n\n            // Act\n            ViewEngineResult result = _engine.FindView(_context, \"viewName\", null, false);\n\n            // Assert\n            TestView view = Assert.IsType<TestView>(result.View);\n            Assert.Null(result.SearchedLocations);\n            Assert.Same(_context, view.ControllerContext);\n            Assert.Equal(\"~/vpath/controllerName/viewName.view\", view.Path);\n            Assert.Equal(String.Empty, view.MasterPath);\n        }\n\n        [Theory]\n        [InlineData(\"~/foo/bar.view\")]\n        [InlineData(\"/foo/bar.view\")]\n        public void FindView_PathViewExistsAndNoMaster_ReturnsView(string path)\n        {\n            // Arrange\n            _engine.ClearMasterLocations();\n\n            SetupFileExists(path);\n            SetupCacheHit(CreateCacheBaseKey(Cache.View, path, \"\", \"\"), path);\n\n            // Act\n            ViewEngineResult result = _engine.FindView(_context, path, null, false);\n\n            // Assert\n            TestView view = Assert.IsType<TestView>(result.View);\n            Assert.Null(result.SearchedLocations);\n            Assert.Same(_context, view.ControllerContext);\n            Assert.Equal(path, view.Path);\n            Assert.Equal(String.Empty, view.MasterPath);\n        }\n\n        [Theory]\n        [InlineData(\"~/foo/bar.unsupported\")]\n        [InlineData(\"/foo/bar.unsupported\")]\n        public void FindView_PathViewExistsAndNoMaster_Legacy_ReturnsView(string path)\n        {\n            // Arrange\n            _engine.FileExtensions = null; // Set FileExtensions to null to simulate View Engines that do not set this property            \n            _engine.ClearMasterLocations();\n\n            SetupFileExists(path);\n            SetupCacheHit(CreateCacheBaseKey(Cache.View, path, \"\", \"\"), path);\n\n            // Act\n            ViewEngineResult result = _engine.FindView(_context, path, null, false);\n\n            // Assert\n            TestView view = Assert.IsType<TestView>(result.View);\n            Assert.Null(result.SearchedLocations);\n            Assert.Same(_context, view.ControllerContext);\n            Assert.Equal(path, view.Path);\n            Assert.Equal(String.Empty, view.MasterPath);\n        }\n\n        [Theory]\n        [InlineData(\"~/foo/bar.view\")]\n        [InlineData(\"/foo/bar.view\")]\n        public void FindView_PathViewDoesNotExistAndNoMaster_ReturnsSearchedLocationsResult(string path)\n        {\n            // Arrange\n            SetupFileDoesNotExist(path);\n            SetupCacheMiss(CreateCacheBaseKey(Cache.View, path, \"\", \"\"));\n\n            // Act\n            ViewEngineResult result = _engine.FindView(_context, path, null, false);\n\n            // Assert\n            Assert.Null(result.View);\n            Assert.Equal(path, Assert.Single(result.SearchedLocations));\n        }\n\n        [Theory]\n        [InlineData(\"~/foo/bar.unsupported\")]\n        [InlineData(\"/foo/bar.unsupported\")]\n        public void FindView_PathViewNotSupportedAndNoMaster_ReturnsSearchedLocationsResult(string path)\n        {\n            // Arrange\n            SetupCacheMiss(CreateCacheBaseKey(Cache.View, path, \"\", \"\"));\n\n            // Act\n            ViewEngineResult result = _engine.FindView(_context, path, null, false);\n\n            // Assert\n            Assert.Null(result.View);\n            Assert.Equal(path, Assert.Single(result.SearchedLocations));\n            _engine.MockPathProvider.Verify(vpp => vpp.FileExists(path), Times.Never());\n        }\n\n        [Fact]\n        public void FindView_ViewExistsAndMasterNameProvidedButEmptyMasterLocations_Throws()\n        {\n            // Arrange\n            _engine.ClearMasterLocations();\n            SetupFileExists(\"~/vpath/controllerName/viewName.view\");\n            SetupCacheHit(CreateCacheKey(Cache.View), \"~/vpath/controllerName/viewName.view\");\n            SetupFileDoesNotExist(\"~/vpath/controllerName/viewName.Mobile.view\");\n            SetupCacheMiss(CreateCacheKey(Cache.View, displayMode: \"Mobile\"));\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => _engine.FindView(_context, \"viewName\", \"masterName\", false),\n                \"The property 'MasterLocationFormats' cannot be null or empty.\"\n                );\n        }\n\n        [Fact]\n        public void FindView_ViewDoesNotExistAndMasterDoesNotExist_ReturnsSearchedLocationsResult()\n        {\n            // Arrange\n            SetupFileDoesNotExist(\"~/vpath/controllerName/viewName.view\");\n            SetupFileDoesNotExist(\"~/vpath/controllerName/masterName.master\");\n\n            // Act\n            ViewEngineResult result = _engine.FindView(_context, \"viewName\", \"masterName\", false);\n\n            // Assert\n            Assert.Null(result.View);\n            Assert.Equal(2, result.SearchedLocations.Count()); // Both view and master locations\n            Assert.Contains(\"~/vpath/controllerName/viewName.view\", result.SearchedLocations);\n            Assert.Contains(\"~/vpath/controllerName/masterName.master\", result.SearchedLocations);\n        }\n\n        [Fact]\n        public void FindView_ViewExistsButMasterDoesNotExist_ReturnsSearchedLocationsResult()\n        {\n            // Arrange\n            SetupFileExists(\"~/vpath/controllerName/viewName.view\");\n            SetupCacheHit(CreateCacheKey(Cache.View), \"~/vpath/controllerName/viewName.view\");\n\n            SetupFileDoesNotExist(\"~/vpath/controllerName/viewName.Mobile.view\");\n            SetupCacheMiss(CreateCacheKey(Cache.View, displayMode: \"Mobile\"));\n\n            SetupFileDoesNotExist(\"~/vpath/controllerName/masterName.master\");\n\n            // Act\n            ViewEngineResult result = _engine.FindView(_context, \"viewName\", \"masterName\", false);\n\n            // Assert\n            Assert.Null(result.View);\n            // View was found, not included in 'searched locations'\n            Assert.Equal(\"~/vpath/controllerName/masterName.master\", Assert.Single(result.SearchedLocations));\n        }\n\n        [Fact]\n        public void FindView_MasterInAreaDoesNotExist_ReturnsSearchedLocationsResult()\n        {\n            // Arrange\n            _context.RouteData.DataTokens[\"area\"] = \"areaName\";\n            SetupFileExists(\"~/vpath/areaName/controllerName/viewName.view\");\n            SetupCacheHit(CreateCacheKey(Cache.View, area: \"areaName\"), \"~/vpath/areaName/controllerName/viewName.view\");\n\n            SetupFileDoesNotExist(\"~/vpath/areaName/controllerName/viewName.Mobile.view\");\n            SetupCacheMiss(CreateCacheKey(Cache.View, area: \"areaName\", displayMode: \"Mobile\"));\n\n            SetupFileDoesNotExist(\"~/vpath/areaName/controllerName/masterName.master\");\n            SetupFileDoesNotExist(\"~/vpath/controllerName/masterName.master\");\n\n            // Act\n            ViewEngineResult result = _engine.FindView(_context, \"viewName\", \"masterName\", false);\n\n            // Assert\n            Assert.Null(result.View);\n            Assert.Equal(2, result.SearchedLocations.Count()); // View was found, not included in 'searched locations'\n            Assert.Contains(\"~/vpath/areaName/controllerName/masterName.master\", result.SearchedLocations);\n            Assert.Contains(\"~/vpath/controllerName/masterName.master\", result.SearchedLocations);\n        }\n\n        [Fact]\n        public void FindView_ViewExistsAndMasterExists_ReturnsView()\n        {\n            // Arrange\n            SetupFileExists(\"~/vpath/controllerName/viewName.view\");\n            SetupCacheHit(CreateCacheKey(Cache.View), \"~/vpath/controllerName/viewName.view\");\n\n            SetupFileDoesNotExist(\"~/vpath/controllerName/viewName.Mobile.view\");\n            SetupCacheMiss(CreateCacheKey(Cache.View, displayMode: \"Mobile\"));\n\n            SetupFileExists(\"~/vpath/controllerName/masterName.master\");\n            SetupCacheHit(CreateCacheKey(Cache.Master), \"~/vpath/controllerName/masterName.master\");\n\n            SetupFileDoesNotExist(\"~/vpath/controllerName/masterName.Mobile.master\");\n            SetupCacheMiss(CreateCacheKey(Cache.Master, displayMode: \"Mobile\"));\n\n            // Act\n            ViewEngineResult result = _engine.FindView(_context, \"viewName\", \"masterName\", false);\n\n            // Assert\n            TestView view = Assert.IsType<TestView>(result.View);\n            Assert.Null(result.SearchedLocations);\n            Assert.Same(_context, view.ControllerContext);\n            Assert.Equal(\"~/vpath/controllerName/viewName.view\", view.Path);\n            Assert.Equal(\"~/vpath/controllerName/masterName.master\", view.MasterPath);\n        }\n\n        [Fact]\n        public void FindView_ViewInAreaExistsAndMasterExists_ReturnsView()\n        {\n            // Arrange\n            _context.RouteData.DataTokens[\"area\"] = \"areaName\";\n            SetupFileExists(\"~/vpath/areaName/controllerName/viewName.view\");\n            SetupCacheHit(CreateCacheKey(Cache.View, area: \"areaName\"), \"~/vpath/areaName/controllerName/viewName.view\");\n\n            SetupFileDoesNotExist(\"~/vpath/areaName/controllerName/viewName.Mobile.view\");\n            SetupCacheMiss(CreateCacheKey(Cache.View, area: \"areaName\", displayMode: \"Mobile\"));\n\n            SetupFileDoesNotExist(\"~/vpath/areaName/controllerName/masterName.master\");\n\n            SetupFileExists(\"~/vpath/controllerName/masterName.master\");\n            SetupCacheHit(CreateCacheKey(Cache.Master, area: \"areaName\"), \"~/vpath/controllerName/masterName.master\");\n\n            SetupFileDoesNotExist(\"~/vpath/controllerName/masterName.Mobile.master\");\n            SetupCacheMiss(CreateCacheKey(Cache.Master, area: \"areaName\", displayMode: \"Mobile\"));\n\n\n            // Act\n            ViewEngineResult result = _engine.FindView(_context, \"viewName\", \"masterName\", false);\n\n            // Assert\n            TestView view = Assert.IsType<TestView>(result.View);\n            Assert.Null(result.SearchedLocations);\n            Assert.Same(_context, view.ControllerContext);\n            Assert.Equal(\"~/vpath/areaName/controllerName/viewName.view\", view.Path);\n            Assert.Equal(\"~/vpath/controllerName/masterName.master\", view.MasterPath);\n        }\n\n        [Fact]\n        public void FindView_ViewInAreaExistsAndMasterExists_ReturnsView_Mobile()\n        {\n            // Arrange\n            _mobileContext.RouteData.DataTokens[\"area\"] = \"areaName\";\n            SetupFileExists(\"~/vpath/areaName/controllerName/viewName.view\");\n            SetupCacheHit(CreateCacheKey(Cache.View, area: \"areaName\"), \"~/vpath/areaName/controllerName/viewName.view\");\n\n            SetupFileExists(\"~/vpath/areaName/controllerName/viewName.Mobile.view\");\n            SetupCacheHit(CreateCacheKey(Cache.View, area: \"areaName\", displayMode: \"Mobile\"), \"~/vpath/areaName/controllerName/viewName.Mobile.view\");\n\n            SetupFileDoesNotExist(\"~/vpath/areaName/controllerName/masterName.master\");\n            SetupFileDoesNotExist(\"~/vpath/areaName/controllerName/masterName.Mobile.master\");\n\n            SetupFileExists(\"~/vpath/controllerName/masterName.master\");\n            SetupCacheHit(CreateCacheKey(Cache.Master, area: \"areaName\"), \"~/vpath/controllerName/masterName.master\");\n\n            SetupFileExists(\"~/vpath/controllerName/masterName.Mobile.master\");\n            SetupCacheHit(CreateCacheKey(Cache.Master, area: \"areaName\", displayMode: \"Mobile\"), \"~/vpath/controllerName/masterName.Mobile.master\");\n\n            // Act\n            ViewEngineResult result = _engine.FindView(_mobileContext, \"viewName\", \"masterName\", false);\n\n            // Assert\n            TestView view = Assert.IsType<TestView>(result.View);\n            Assert.Null(result.SearchedLocations);\n            Assert.Same(_mobileContext, view.ControllerContext);\n            Assert.Equal(\"~/vpath/areaName/controllerName/viewName.Mobile.view\", view.Path);\n            Assert.Equal(\"~/vpath/controllerName/masterName.Mobile.master\", view.MasterPath);\n        }\n\n        [Fact]\n        public void FindPartialView_NullControllerContext_Throws()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => _engine.FindPartialView(null, \"view name\", false),\n                \"controllerContext\"\n                );\n        }\n\n        [Theory]\n        [InlineData(null)]\n        [InlineData(\"\")]\n        public void FindPartialView_InvalidPartialViewName_Throws(string partialViewName)\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => _engine.FindPartialView(_context, partialViewName, false),\n                \"partialViewName\"\n                );\n        }\n\n        [Fact]\n        public void FindPartialView_ControllerNameNotInRequestContext_Throws()\n        {\n            // Arrange\n            _context.RouteData.Values.Remove(\"controller\");\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => _engine.FindPartialView(_context, \"partialName\", false),\n                \"The RouteData must contain an item named 'controller' with a non-empty string value.\"\n                );\n        }\n\n        [Fact]\n        public void FindPartialView_EmptyPartialViewLocations_Throws()\n        {\n            // Arrange\n            _engine.ClearPartialViewLocations();\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => _engine.FindPartialView(_context, \"partialName\", false),\n                \"The property 'PartialViewLocationFormats' cannot be null or empty.\"\n                );\n        }\n\n        [Fact]\n        public void FindPartialView_ViewDoesNotExist_ReturnsSearchLocationsResult()\n        {\n            // Arrange\n            SetupFileDoesNotExist(\"~/vpath/controllerName/partialName.partial\");\n\n            // Act\n            ViewEngineResult result = _engine.FindPartialView(_context, \"partialName\", false);\n\n            // Assert\n            Assert.Null(result.View);\n            Assert.Equal(\"~/vpath/controllerName/partialName.partial\", Assert.Single(result.SearchedLocations));\n        }\n\n        [Fact]\n        public void FindPartialView_ViewExists_ReturnsView()\n        {\n            // Arrange\n            SetupFileExists(\"~/vpath/controllerName/partialName.partial\");\n            SetupCacheHit(CreateCacheKey(Cache.Partial), \"~/vpath/controllerName/partialName.partial\");\n\n            SetupFileDoesNotExist(\"~/vpath/controllerName/partialName.Mobile.partial\");\n            SetupCacheMiss(CreateCacheKey(Cache.Partial, displayMode: \"Mobile\"));\n\n            // Act\n            ViewEngineResult result = _engine.FindPartialView(_context, \"partialName\", false);\n\n            // Assert\n            TestView view = Assert.IsType<TestView>(result.View);\n            Assert.Null(result.SearchedLocations);\n            Assert.Same(_context, view.ControllerContext);\n            Assert.Equal(\"~/vpath/controllerName/partialName.partial\", view.Path);\n        }\n\n        [Theory]\n        [InlineData(\"~/foo/bar.partial\")]\n        [InlineData(\"/foo/bar.partial\")]\n        public void FindPartialView_PathViewExists_ReturnsView(string path)\n        {\n            // Arrange\n            SetupFileExists(path);\n            SetupCacheHit(CreateCacheBaseKey(Cache.Partial, path, \"\", \"\"), path);\n\n            // Act\n            ViewEngineResult result = _engine.FindPartialView(_context, path, false);\n\n            // Assert\n            TestView view = Assert.IsType<TestView>(result.View);\n            Assert.Null(result.SearchedLocations);\n            Assert.Same(_context, view.ControllerContext);\n            Assert.Equal(path, view.Path);\n        }\n\n        [Theory]\n        [InlineData(\"/foo/bar.unsupported\")]\n        [InlineData(\"~/foo/bar.unsupported\")]\n        public void FindPartialView_PathViewExists_Legacy_ReturnsView(string path)\n        {\n            // Arrange\n            _engine.FileExtensions = null; // Set FileExtensions to null to simulate View Engines that do not set this property\n            SetupFileExists(path);\n            SetupCacheHit(CreateCacheBaseKey(Cache.Partial, path, \"\", \"\"), path);\n\n            // Act\n            ViewEngineResult result = _engine.FindPartialView(_context, path, false);\n\n            // Assert\n            TestView view = Assert.IsType<TestView>(result.View);\n            Assert.Null(result.SearchedLocations);\n            Assert.Same(_context, view.ControllerContext);\n            Assert.Equal(path, view.Path);\n        }\n\n        [Theory]\n        [InlineData(\"~/foo/bar.partial\")]\n        [InlineData(\"/foo/bar.partial\")]\n        public void FindPartialView_PathViewDoesNotExist_ReturnsSearchedLocationsResult(string path)\n        {\n            // Arrange\n            SetupFileDoesNotExist(path);\n            SetupCacheMiss(CreateCacheBaseKey(Cache.Partial, path, \"\", \"\"));\n\n            // Act\n            ViewEngineResult result = _engine.FindPartialView(_context, path, false);\n\n            // Assert\n            Assert.Null(result.View);\n            Assert.Equal(path, Assert.Single(result.SearchedLocations));\n        }\n\n        [Theory]\n        [InlineData(\"~/foo/bar.unsupported\")]\n        [InlineData(\"/foo/bar.unsupported\")]\n        public void FindPartialView_PathViewNotSupported_ReturnsSearchedLocationsResult(string path)\n        {\n            // Arrange\n            SetupCacheMiss(CreateCacheBaseKey(Cache.Partial, path, \"\", \"\"));\n\n            // Act\n            ViewEngineResult result = _engine.FindPartialView(_context, path, false);\n\n            // Assert\n            Assert.Null(result.View);\n            Assert.Equal(path, Assert.Single(result.SearchedLocations));\n            _engine.MockPathProvider.Verify(vpp => vpp.FileExists(path), Times.Never());\n        }\n\n        [Fact]\n        public void FileExtensions()\n        {\n            // Arrange + Assert\n            Assert.Null(new Mock<VirtualPathProviderViewEngine>().Object.FileExtensions);\n        }\n\n        [Fact]\n        public void GetExtensionThunk()\n        {\n            // Arrange and Assert\n            Assert.Equal(VirtualPathUtility.GetExtension, new Mock<VirtualPathProviderViewEngine>().Object.GetExtensionThunk);\n        }\n\n        [Fact]\n        public void DisplayModeSetOncePerRequest()\n        {\n            // Arrange\n            SetupFileExists(\"~/vpath/controllerName/viewName.view\");\n            SetupCacheHit(CreateCacheKey(Cache.View), \"~/vpath/controllerName/viewName.view\");\n\n            SetupFileDoesNotExist(\"~/vpath/controllerName/viewName.Mobile.view\");\n            SetupCacheMiss(CreateCacheKey(Cache.View, displayMode: \"Mobile\"));\n\n            SetupFileDoesNotExist(\"~/vpath/controllerName/partialName.partial\");\n            SetupCacheMiss(CreateCacheKey(Cache.Partial));\n\n            SetupFileExists(\"~/vpath/controllerName/partialName.Mobile.partial\");\n            _engine.MockCache\n                .Setup(c => c.InsertViewLocation(It.IsAny<HttpContextBase>(), It.IsAny<string>(), \"~/vpath/controllerName/partialName.Mobile.partial\"))\n                .Callback<HttpContextBase, string, string>((httpContext, key, virtualPath) =>\n                {\n                    _engine.MockCache\n                        .Setup(c => c.GetViewLocation(It.IsAny<HttpContextBase>(), key))\n                        .Returns(\"~/vpath/controllerName/partialName.Mobile.partial\")\n                        .Verifiable();\n                })\n                .Verifiable();\n\n            // Act\n            ViewEngineResult viewResult = _engine.FindView(_mobileContext, \"viewName\", masterName: null, useCache: false);\n\n            // Mobile display mode will be used to locate the view with and without the cache.\n            // In neither case should this set the DisplayModeId to Mobile because it has already been set.\n            ViewEngineResult partialResult = _engine.FindPartialView(_mobileContext, \"partialName\", useCache: false);\n            ViewEngineResult cachedPartialResult = _engine.FindPartialView(_mobileContext, \"partialName\", useCache: true);\n\n            // Assert\n\n            Assert.Equal(DisplayModeProvider.DefaultDisplayModeId, _mobileContext.DisplayMode.DisplayModeId);\n        }\n\n        // The core caching scenarios are covered in the FindView/FindPartialView tests. These\n        // extra tests deal with the cache itself, rather than specifics around finding views.\n\n        private const string MASTER_VIRTUAL = \"~/vpath/controllerName/name.master\";\n        private const string PARTIAL_VIRTUAL = \"~/vpath/controllerName/name.partial\";\n        private const string VIEW_VIRTUAL = \"~/vpath/controllerName/name.view\";\n        private const string MOBILE_VIEW_VIRTUAL = \"~/vpath/controllerName/name.Mobile.view\";\n\n        [Fact]\n        public void UsesDifferentKeysForViewMasterAndPartial()\n        {\n            string keyMaster = null;\n            string keyPartial = null;\n            string keyView = null;\n\n            // Arrange\n            SetupFileExists(VIEW_VIRTUAL);\n            SetupFileDoesNotExist(MOBILE_VIEW_VIRTUAL);\n            SetupCacheMiss(CreateCacheKey(Cache.View, name: \"name\", displayMode: \"Mobile\"));\n            SetupFileExists(MASTER_VIRTUAL);\n            SetupFileDoesNotExist(\"~/vpath/controllerName/name.Mobile.master\");\n            SetupCacheMiss(CreateCacheKey(Cache.Master, name: \"name\", displayMode: \"Mobile\"));\n            SetupFileExists(PARTIAL_VIRTUAL);\n            SetupFileDoesNotExist(\"~/vpath/controllerName/name.Mobile.partial\");\n            SetupCacheMiss(CreateCacheKey(Cache.Partial, name: \"name\", displayMode: \"Mobile\"));\n            _engine.MockCache\n                .Setup(c => c.InsertViewLocation(It.IsAny<HttpContextBase>(), It.IsAny<string>(), VIEW_VIRTUAL))\n                .Callback<HttpContextBase, string, string>((httpContext, key, path) => keyView = key)\n                .Verifiable();\n            _engine.MockCache\n                .Setup(c => c.InsertViewLocation(It.IsAny<HttpContextBase>(), It.IsAny<string>(), MASTER_VIRTUAL))\n                .Callback<HttpContextBase, string, string>((httpContext, key, path) => keyMaster = key)\n                .Verifiable();\n            _engine.MockCache\n                .Setup(c => c.InsertViewLocation(It.IsAny<HttpContextBase>(), It.IsAny<string>(), PARTIAL_VIRTUAL))\n                .Callback<HttpContextBase, string, string>((httpContext, key, path) => keyPartial = key)\n                .Verifiable();\n\n            // Act\n            _engine.FindView(_context, \"name\", \"name\", false);\n            _engine.FindPartialView(_context, \"name\", false);\n\n            // Assert\n            Assert.NotNull(keyMaster);\n            Assert.NotNull(keyPartial);\n            Assert.NotNull(keyView);\n            Assert.NotEqual(keyMaster, keyPartial);\n            Assert.NotEqual(keyMaster, keyView);\n            Assert.NotEqual(keyPartial, keyView);\n            _engine.MockPathProvider\n                .Verify(vpp => vpp.FileExists(VIEW_VIRTUAL), Times.AtMostOnce());\n            _engine.MockPathProvider\n                .Verify(vpp => vpp.FileExists(MASTER_VIRTUAL), Times.AtMostOnce());\n            _engine.MockPathProvider\n                .Verify(vpp => vpp.FileExists(PARTIAL_VIRTUAL), Times.AtMostOnce());\n            _engine.MockCache\n                .Verify(c => c.InsertViewLocation(It.IsAny<HttpContextBase>(), It.IsAny<string>(), VIEW_VIRTUAL), Times.AtMostOnce());\n            _engine.MockCache\n                .Verify(c => c.InsertViewLocation(It.IsAny<HttpContextBase>(), It.IsAny<string>(), MASTER_VIRTUAL), Times.AtMostOnce());\n            _engine.MockCache\n                .Verify(c => c.InsertViewLocation(It.IsAny<HttpContextBase>(), It.IsAny<string>(), PARTIAL_VIRTUAL), Times.AtMostOnce());\n        }\n\n        // This tests the protocol involved with two calls to FindView for the same view name\n        // where the request succeeds. The calls happen in this order:\n        //\n        //    FindView(\"view\")\n        //      Cache.GetViewLocation(key for \"view\") -> returns null (not found)\n        //      VirtualPathProvider.FileExists(virtual path for \"view\") -> returns true\n        //      Cache.InsertViewLocation(key for \"view\", virtual path for \"view\")\n        //    FindView(\"view\")\n        //      Cache.GetViewLocation(key for \"view\") -> returns virtual path for \"view\"\n        //\n        // The mocking code is written as it is because we don't want to make any assumptions\n        // about the format of the cache key. So we intercept the first call to Cache.GetViewLocation and\n        // take the key they gave us to set up the rest of the mock expectations.\n        // The ViewCollection class will typically place to successive calls to FindView and FindPartialView and\n        // set the useCache parameter to true/false respectively. To simulate this, both calls to FindView are executed\n        // with useCache set to true. This mimics the behavior of always going to the cache first and after finding a\n        // view, ensuring that subsequent calls from the cache are successful.\n\n        [Fact]\n        public void ValueInCacheBypassesVirtualPathProvider()\n        {\n            // Arrange\n            string cacheKey = null;\n\n            SetupFileExists(VIEW_VIRTUAL); // It wasn't found, so they call vpp.FileExists\n            SetupFileDoesNotExist(MOBILE_VIEW_VIRTUAL);\n            SetupCacheMiss(CreateCacheKey(Cache.View, name: \"name\", displayMode: \"Mobile\"));\n            _engine.MockCache // Then they set the value into the cache\n                .Setup(c => c.InsertViewLocation(It.IsAny<HttpContextBase>(), It.IsAny<string>(), VIEW_VIRTUAL))\n                .Callback<HttpContextBase, string, string>((httpContext, key, virtualPath) =>\n                {\n                    cacheKey = key;\n                    _engine.MockCache // Second time through, we give them a cache hit\n                        .Setup(c => c.GetViewLocation(It.IsAny<HttpContextBase>(), key))\n                        .Returns(VIEW_VIRTUAL)\n                        .Verifiable();\n                })\n                .Verifiable();\n\n            // Act\n            _engine.FindView(_context, \"name\", null, false); // Call it once with false to seed the cache\n            _engine.FindView(_context, \"name\", null, true); // Call it once with true to check the cache\n\n            // Assert\n\n            _engine.MockPathProvider.Verify(vpp => vpp.FileExists(VIEW_VIRTUAL), Times.AtMostOnce());\n            _engine.MockCache.Verify(c => c.InsertViewLocation(It.IsAny<HttpContextBase>(), It.IsAny<string>(), VIEW_VIRTUAL), Times.AtMostOnce());\n            _engine.MockCache.Verify(c => c.GetViewLocation(It.IsAny<HttpContextBase>(), cacheKey), Times.AtMostOnce());\n\n            // We seed the cache with all possible display modes but since the mobile view does not exist we don't insert it into the cache.\n            _engine.MockPathProvider.Verify(vpp => vpp.FileExists(MOBILE_VIEW_VIRTUAL), Times.Exactly(1));\n            _engine.MockCache.Verify(c => c.InsertViewLocation(It.IsAny<HttpContextBase>(), It.IsAny<string>(), MOBILE_VIEW_VIRTUAL), Times.Never());\n            _engine.MockCache.Verify(c => c.GetViewLocation(It.IsAny<HttpContextBase>(), VirtualPathProviderViewEngine.AppendDisplayModeToCacheKey(cacheKey, DisplayModeProvider.MobileDisplayModeId)), Times.Never());\n        }\n\n        [Fact]\n        public void ValueInCacheBypassesVirtualPathProviderForAllAvailableDisplayModesForContext()\n        {\n            // Arrange\n            string cacheKey = null;\n            string mobileCacheKey = null;\n\n            SetupFileExists(VIEW_VIRTUAL);\n            SetupFileExists(MOBILE_VIEW_VIRTUAL);\n\n            _engine.MockCache\n                .Setup(c => c.InsertViewLocation(It.IsAny<HttpContextBase>(), It.IsAny<string>(), VIEW_VIRTUAL))\n                .Callback<HttpContextBase, string, string>((httpContext, key, virtualPath) =>\n                {\n                    cacheKey = key;\n                    _engine.MockCache\n                        .Setup(c => c.GetViewLocation(It.IsAny<HttpContextBase>(), key))\n                        .Returns(MOBILE_VIEW_VIRTUAL)\n                        .Verifiable();\n                })\n                .Verifiable();\n            _engine.MockCache\n                .Setup(c => c.InsertViewLocation(It.IsAny<HttpContextBase>(), It.IsAny<string>(), MOBILE_VIEW_VIRTUAL))\n                .Callback<HttpContextBase, string, string>((httpContext, key, virtualPath) =>\n                {\n                    mobileCacheKey = key;\n                    _engine.MockCache\n                        .Setup(c => c.GetViewLocation(It.IsAny<HttpContextBase>(), key))\n                        .Returns(MOBILE_VIEW_VIRTUAL)\n                        .Verifiable();\n                })\n                .Verifiable();\n\n            // Act\n            _engine.FindView(_mobileContext, \"name\", null, false);\n            _engine.FindView(_mobileContext, \"name\", null, true);\n\n            // Assert\n\n            // DefaultDisplayMode with Mobile substitution is cached and hit on the second call to FindView\n            _engine.MockPathProvider.Verify(vpp => vpp.FileExists(MOBILE_VIEW_VIRTUAL), Times.AtMostOnce());\n            _engine.MockCache.Verify(c => c.InsertViewLocation(It.IsAny<HttpContextBase>(), It.IsAny<string>(), MOBILE_VIEW_VIRTUAL), Times.AtMostOnce());\n            _engine.MockCache.Verify(c => c.GetViewLocation(It.IsAny<HttpContextBase>(), VirtualPathProviderViewEngine.AppendDisplayModeToCacheKey(cacheKey, DisplayModeProvider.MobileDisplayModeId)), Times.AtMostOnce());\n\n            _engine.MockPathProvider.Verify(vpp => vpp.FileExists(VIEW_VIRTUAL), Times.AtMostOnce());\n            _engine.MockCache.Verify(c => c.InsertViewLocation(It.IsAny<HttpContextBase>(), It.IsAny<string>(), VIEW_VIRTUAL), Times.Exactly(1));\n\n            Assert.NotEqual(cacheKey, mobileCacheKey);\n\n            // Act\n            _engine.FindView(_context, \"name\", null, true);\n\n            // Assert\n\n            // The first call to FindView without a mobile browser results in a cache hit\n            _engine.MockPathProvider.Verify(vpp => vpp.FileExists(VIEW_VIRTUAL), Times.AtMostOnce());\n            _engine.MockCache.Verify(c => c.InsertViewLocation(It.IsAny<HttpContextBase>(), It.IsAny<string>(), VIEW_VIRTUAL), Times.Exactly(1));\n            _engine.MockCache.Verify(c => c.GetViewLocation(It.IsAny<HttpContextBase>(), cacheKey), Times.Exactly(1));\n        }\n\n        [Fact]\n        public void NoValueInCacheButFileExists_ReturnsNullIfUsingCache()\n        {\n            // Arrange\n            string mobileKey = CreateCacheKey(Cache.View, name: \"name\", displayMode: \"Mobile\");\n            _engine.MockCache\n                .Setup(c => c.GetViewLocation(It.IsAny<HttpContextBase>(), mobileKey))\n                .Returns((string)null)\n                .Verifiable();\n\n            // Act\n            IView viewNotInCache = _engine.FindView(_mobileContext, \"name\", masterName: null, useCache: true).View;\n\n            // Assert\n            Assert.Null(viewNotInCache);\n\n            // On a cache miss we should never check the file system. FindView will be called on a second pass\n            // without using the cache.\n            _engine.MockPathProvider.Verify(vpp => vpp.FileExists(MOBILE_VIEW_VIRTUAL), Times.Never());\n            _engine.MockPathProvider.Verify(vpp => vpp.FileExists(VIEW_VIRTUAL), Times.Never());\n\n            SetupFileExists(MOBILE_VIEW_VIRTUAL);\n            SetupCacheHit(CreateCacheKey(Cache.View, name: \"name\", displayMode: \"Mobile\"), MOBILE_VIEW_VIRTUAL);\n            SetupFileExists(VIEW_VIRTUAL);\n            SetupCacheHit(CreateCacheKey(Cache.View, name: \"name\"), VIEW_VIRTUAL);\n\n            // Act & Assert\n            ViewEngineResult result = _engine.FindView(_mobileContext, \"name\", masterName: null, useCache: false);\n            //At this point the view on disk should be found and cached.\n            var view = Assert.IsType<TestView>(result.View);\n            Assert.Equal(MOBILE_VIEW_VIRTUAL, view.Path);\n        }\n\n        [Fact]\n        public void NoValueInCacheAndFileDoesNotExist_ReturnsNullIfUsingCache()\n        {\n            // Arrange\n            string mobileKey = CreateCacheKey(Cache.View, name: \"name\", displayMode: \"Mobile\");\n            _engine.MockCache\n                .Setup(c => c.GetViewLocation(It.IsAny<HttpContextBase>(), mobileKey))\n                .Returns(\"\")\n                .Verifiable();\n            string desktopKey = CreateCacheKey(Cache.View, name: \"name\");\n            _engine.MockCache\n                .Setup(c => c.GetViewLocation(It.IsAny<HttpContextBase>(), desktopKey))\n                .Returns(\"\")\n                .Verifiable();\n\n            // Act\n            IView viewNotInCache = _engine.FindView(_mobileContext, \"name\", masterName: null, useCache: true).View;\n\n            // Assert\n            Assert.Null(viewNotInCache);\n        }\n\n        [Fact]\n        public void ReleaseViewCallsDispose()\n        {\n            // Arrange\n            IView view = new TestView();\n\n            // Act\n            _engine.ReleaseView(_context, view);\n\n            // Assert\n            Assert.True(((TestView)view).Disposed);\n        }\n\n        [Fact]\n        public void ViewLocationCache_RoundTrips()\n        {\n            // Arrange & Act\n            IViewLocationCache locationCache = _engine.ViewLocationCache;\n\n            // Assert\n            Assert.NotNull(locationCache);\n            Assert.Equal(_engine.MockCache.Object, _engine.ViewLocationCache);\n        }\n\n        [Fact]\n        public void ViewLocationCache_DefaultNullCache()\n        {\n            // Arrange\n            Mock<VirtualPathProviderViewEngine> engineMock = new Mock<VirtualPathProviderViewEngine>();\n            VirtualPathProviderViewEngine engine = engineMock.Object;\n\n            // Act\n            IViewLocationCache cache = engine.ViewLocationCache;\n\n            // Assert\n            Assert.NotNull(cache);\n            Assert.Equal(DefaultViewLocationCache.Null, cache);\n            Assert.IsNotType<DefaultViewLocationCache>(cache);\n        }\n\n        [Fact]\n        public void ViewLocationCache_DefaultRealCache()\n        {\n            // Arrange\n            Mock<VirtualPathProviderViewEngine> engineMock = new Mock<VirtualPathProviderViewEngine>();\n            VirtualPathProviderViewEngine engine = engineMock.Object;\n\n            HttpRequest request = new HttpRequest(\"foo.txt\", \"http://localhost\", String.Empty);\n            HttpResponse response = new HttpResponse(TextWriter.Null);\n            HttpContext context = new HttpContext(request, response);\n            HttpContext savedContext = HttpContext.Current;\n\n            // Act\n            IViewLocationCache cache;\n            try\n            {\n                HttpContext.Current = context;\n                cache = engine.ViewLocationCache;\n            }\n            finally\n            {\n                HttpContext.Current = savedContext;\n            }\n\n            // Assert\n            Assert.NotNull(cache);\n            Assert.IsType<DefaultViewLocationCache>(cache);\n        }\n\n        [Fact]\n        public void VirtualPathProvider_RoundTrips()\n        {\n            // Arrange & Act & Assert\n            Assert.Equal(_engine.MockPathProvider.Object, _engine.VirtualPathProvider);\n        }\n\n        // Not a valid production scenario -- no HostingEnvironment\n        [Fact]\n        public void VirtualPathProvider_Null()\n        {\n            // Arrange\n            TestableVirtualPathProviderViewEngine viewEngine =\n                new TestableVirtualPathProviderViewEngine(skipVPPInitialization: true);\n\n            // Act & Assert\n            Assert.Null(viewEngine.VirtualPathProvider);\n        }\n\n        [Fact]\n        public void VirtualPathProvider_VPPRegistrationChanging()\n        {\n            // Arrange\n            Mock<VirtualPathProvider> provider1 = new Mock<VirtualPathProvider>(MockBehavior.Strict);\n            Mock<VirtualPathProvider> provider2 = new Mock<VirtualPathProvider>(MockBehavior.Strict);\n            VirtualPathProvider provider = provider1.Object;\n\n            // Act\n            TestableVirtualPathProviderViewEngine viewEngine =\n                new TestableVirtualPathProviderViewEngine(skipVPPInitialization: true)\n            {\n                VirtualPathProviderFunc = () => provider,\n            };\n\n            // The moral equivalent of HostingEnvironment.RegisterVirtualPathProvider(provider2.Object)\n            provider = provider2.Object;\n\n            // Assert\n            Assert.Equal(provider2.Object, viewEngine.VirtualPathProvider);\n            provider1.Verify();\n            provider2.Verify();\n        }\n\n        [Fact]\n        public void FileExists_VPPRegistrationChanging()\n        {\n            // Arrange\n            Mock<VirtualPathProvider> provider1 = new Mock<VirtualPathProvider>(MockBehavior.Strict);\n            provider1.Setup(vpp => vpp.FileExists(It.IsAny<string>())).Returns(true);\n            Mock<VirtualPathProvider> provider2 = new Mock<VirtualPathProvider>(MockBehavior.Strict);\n            provider2.Setup(vpp => vpp.FileExists(It.IsAny<string>())).Returns(true);\n            VirtualPathProvider provider = provider1.Object;\n\n            string path = \"~/Index.cshtml\";\n            ControllerContext context = CreateContext();\n            TestableVirtualPathProviderViewEngine viewEngine =\n                new TestableVirtualPathProviderViewEngine(skipVPPInitialization: true)\n            {\n                VirtualPathProviderFunc = () => provider,\n            };\n\n            // Act\n            bool fileExists1 = viewEngine.FileExists(context, path);\n\n            // The moral equivalent of HostingEnvironment.RegisterVirtualPathProvider(provider2.Object)\n            provider = provider2.Object;\n\n            bool fileExists2 = viewEngine.FileExists(context, path);\n\n            // Assert\n            Assert.True(fileExists1);\n            provider1.Verify(vpp => vpp.FileExists(path), Times.Once());\n            Assert.True(fileExists2);\n            provider2.Verify(vpp => vpp.FileExists(path), Times.Once());\n        }\n\n        private static string CreateCacheBaseKey(string prefix, string name, string controllerName, string area)\n        {\n            var r = String.Join(\":\", prefix, name, controllerName, area) + \":\";\n            return r;\n        }\n\n        private static string CreateCacheKey(Cache prefix, string name = null, string controller = \"controllerName\", string area = \"\", string displayMode = \"\")\n        {\n            if (name == null)\n            {\n                name = prefix.ToString().ToLowerInvariant() + \"Name\";\n            }\n            var r = CreateCacheBaseKey(prefix, name, controller, area) + displayMode + \":\";\n            return r;\n        }\n\n        private static ControllerContext CreateContext(bool isMobileDevice = false)\n        {\n            RouteData routeData = new RouteData();\n            routeData.Values[\"controller\"] = \"controllerName\";\n            routeData.Values[\"action\"] = \"actionName\";\n\n            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();\n            mockControllerContext.Setup(c => c.HttpContext.Request.Browser.IsMobileDevice).Returns(isMobileDevice);\n            mockControllerContext.Setup(c => c.HttpContext.Items).Returns(new Hashtable());\n            mockControllerContext.Setup(c => c.RouteData).Returns(routeData);\n\n            mockControllerContext.Setup(c => c.HttpContext.Response.Cookies).Returns(new HttpCookieCollection());\n            mockControllerContext.Setup(c => c.HttpContext.Request.Cookies).Returns(new HttpCookieCollection());\n\n            return mockControllerContext.Object;\n        }\n\n        private void SetupFileExists(string path)\n        {\n            SetupFileExistsHelper(path, exists: true);\n        }\n\n        private void SetupFileDoesNotExist(string path)\n        {\n            SetupFileExistsHelper(path, exists: false);\n        }\n\n        private void SetupCacheHit(string key, string path)\n        {\n            _engine.MockCache\n                .Setup(c => c.InsertViewLocation(It.IsAny<HttpContextBase>(), key, path))\n                .Verifiable();\n        }\n\n        private void SetupCacheMiss(string key)\n        {\n            SetupCacheHit(key, \"\");\n        }\n\n        private void SetupFileExistsHelper(string path, bool exists)\n        {\n            _engine.MockPathProvider.Setup(vpp => vpp.FileExists(path)).Returns(exists).Verifiable();\n        }\n\n        private class Cache\n        {\n            private string _value;\n\n            private Cache(string value)\n            {\n                _value = value;\n            }\n\n            public static Cache View = new Cache(\"View\");\n            public static Cache Partial = new Cache(\"Partial\");\n            public static Cache Master = new Cache(\"Master\");\n\n            public override string ToString()\n            {\n                return _value;\n            }\n\n            public static implicit operator string(Cache c)\n            {\n                return c.ToString();\n            }\n        }\n\n        private class TestView : IView, IDisposable\n        {\n            public bool Disposed { get; set; }\n            public ControllerContext ControllerContext { get; set; }\n            public string Path { get; set; }\n            public string MasterPath { get; set; }\n\n            void IDisposable.Dispose()\n            {\n                Disposed = true;\n            }\n\n            void IView.Render(ViewContext viewContext, TextWriter writer)\n            {\n            }\n        }\n\n        private class TestableVirtualPathProviderViewEngine : VirtualPathProviderViewEngine\n        {\n            public Mock<IViewLocationCache> MockCache = new Mock<IViewLocationCache>(MockBehavior.Strict);\n            public Mock<VirtualPathProvider> MockPathProvider = new Mock<VirtualPathProvider>(MockBehavior.Strict);\n\n            public TestableVirtualPathProviderViewEngine()\n                : this(skipVPPInitialization: false)\n            {\n            }\n\n            public TestableVirtualPathProviderViewEngine(bool skipVPPInitialization)\n            {\n                MasterLocationFormats = new[] { \"~/vpath/{1}/{0}.master\" };\n                ViewLocationFormats = new[] { \"~/vpath/{1}/{0}.view\" };\n                PartialViewLocationFormats = new[] { \"~/vpath/{1}/{0}.partial\" };\n                AreaMasterLocationFormats = new[] { \"~/vpath/{2}/{1}/{0}.master\" };\n                AreaViewLocationFormats = new[] { \"~/vpath/{2}/{1}/{0}.view\" };\n                AreaPartialViewLocationFormats = new[] { \"~/vpath/{2}/{1}/{0}.partial\" };\n                FileExtensions = new[] { \"view\", \"partial\", \"master\" };\n\n                ViewLocationCache = MockCache.Object;\n                MockCache\n                    .Setup(c => c.GetViewLocation(It.IsAny<HttpContextBase>(), It.IsAny<string>()))\n                    .Returns((string)null);\n\n                if (!skipVPPInitialization)\n                {\n                    VirtualPathProvider = MockPathProvider.Object;\n                }\n\n                GetExtensionThunk = GetExtension;\n            }\n\n            public new VirtualPathProvider VirtualPathProvider\n            {\n                get\n                {\n                    return base.VirtualPathProvider;\n                }\n                private set\n                {\n                    base.VirtualPathProvider = value;\n                }\n            }\n\n            public void ClearViewLocations()\n            {\n                ViewLocationFormats = new string[0];\n            }\n\n            public void ClearMasterLocations()\n            {\n                MasterLocationFormats = new string[0];\n            }\n\n            public void ClearPartialViewLocations()\n            {\n                PartialViewLocationFormats = new string[0];\n            }\n\n            public new bool FileExists(ControllerContext controllerContext, string virtualPath)\n            {\n                return base.FileExists(controllerContext, virtualPath);\n            }\n\n            protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)\n            {\n                return new TestView() { ControllerContext = controllerContext, Path = partialPath };\n            }\n\n            protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)\n            {\n                return new TestView() { ControllerContext = controllerContext, Path = viewPath, MasterPath = masterPath };\n            }\n\n            internal override string CreateCacheKey(string prefix, string name, string controllerName, string areaName)\n            {\n                return VirtualPathProviderViewEngineTest.CreateCacheBaseKey(prefix, name, controllerName, areaName);\n            }\n\n            private static string GetExtension(string virtualPath)\n            {\n                var extension = virtualPath.Substring(virtualPath.LastIndexOf('.'));\n                return extension;\n            }\n        }\n\n        public class DerivedVirtualPathProviderViewEngine : VirtualPathProviderViewEngine\n        {\n            protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)\n            {\n                throw new NotImplementedException();\n            }\n\n            protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/WebFormViewEngineTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Hosting;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class WebFormViewEngineTest\n    {\n        [Fact]\n        public void CreatePartialViewCreatesWebFormView()\n        {\n            // Arrange\n            TestableWebFormViewEngine engine = new TestableWebFormViewEngine();\n\n            // Act\n            WebFormView result = (WebFormView)engine.CreatePartialView(\"partial path\");\n\n            // Assert\n            Assert.Equal(\"partial path\", result.ViewPath);\n            Assert.Equal(String.Empty, result.MasterPath);\n        }\n\n        [Fact]\n        public void CreateViewCreatesWebFormView()\n        {\n            // Arrange\n            TestableWebFormViewEngine engine = new TestableWebFormViewEngine();\n\n            // Act\n            WebFormView result = (WebFormView)engine.CreateView(\"view path\", \"master path\");\n\n            // Assert\n            Assert.Equal(\"view path\", result.ViewPath);\n            Assert.Equal(\"master path\", result.MasterPath);\n        }\n\n        [Fact]\n        public void WebFormViewEngineSetsViewPageActivator()\n        {\n            // Arrange\n            Mock<IViewPageActivator> viewPageActivator = new Mock<IViewPageActivator>();\n            TestableWebFormViewEngine viewEngine = new TestableWebFormViewEngine(viewPageActivator.Object);\n\n            //Act & Assert\n            Assert.Equal(viewPageActivator.Object, viewEngine.ViewPageActivator);\n        }\n\n        [Fact]\n        public void CreatePartialView_PassesViewPageActivator()\n        {\n            // Arrange\n            Mock<IViewPageActivator> viewPageActivator = new Mock<IViewPageActivator>();\n            TestableWebFormViewEngine viewEngine = new TestableWebFormViewEngine(viewPageActivator.Object);\n\n            // Act\n            WebFormView result = (WebFormView)viewEngine.CreatePartialView(\"partial path\");\n\n            // Assert\n            Assert.Equal(viewEngine.ViewPageActivator, result.ViewPageActivator);\n        }\n\n        [Fact]\n        public void CreateView_PassesViewPageActivator()\n        {\n            // Arrange\n            Mock<IViewPageActivator> viewPageActivator = new Mock<IViewPageActivator>();\n            TestableWebFormViewEngine viewEngine = new TestableWebFormViewEngine(viewPageActivator.Object);\n\n            // Act\n            WebFormView result = (WebFormView)viewEngine.CreateView(\"partial path\", \"master path\");\n\n            // Assert\n            Assert.Equal(viewEngine.ViewPageActivator, result.ViewPageActivator);\n        }\n\n        [Fact]\n        public void MasterLocationFormatsProperty()\n        {\n            // Arrange\n            string[] expected = new string[]\n            {\n                \"~/Views/{1}/{0}.master\",\n                \"~/Views/Shared/{0}.master\"\n            };\n\n            // Act\n            TestableWebFormViewEngine engine = new TestableWebFormViewEngine();\n\n            // Assert\n            Assert.Equal(expected, engine.MasterLocationFormats);\n        }\n\n        [Fact]\n        public void AreaMasterLocationFormatsProperty()\n        {\n            // Arrange\n            string[] expected = new string[]\n            {\n                \"~/Areas/{2}/Views/{1}/{0}.master\",\n                \"~/Areas/{2}/Views/Shared/{0}.master\",\n            };\n\n            // Act\n            TestableWebFormViewEngine engine = new TestableWebFormViewEngine();\n\n            // Assert\n            Assert.Equal(expected, engine.AreaMasterLocationFormats);\n        }\n\n        [Fact]\n        public void PartialViewLocationFormatsProperty()\n        {\n            // Arrange\n            string[] expected = new string[]\n            {\n                \"~/Views/{1}/{0}.aspx\",\n                \"~/Views/{1}/{0}.ascx\",\n                \"~/Views/Shared/{0}.aspx\",\n                \"~/Views/Shared/{0}.ascx\"\n            };\n\n            // Act\n            TestableWebFormViewEngine engine = new TestableWebFormViewEngine();\n\n            // Assert\n            Assert.Equal(expected, engine.PartialViewLocationFormats);\n        }\n\n        [Fact]\n        public void AreaPartialViewLocationFormatsProperty()\n        {\n            // Arrange\n            string[] expected = new string[]\n            {\n                \"~/Areas/{2}/Views/{1}/{0}.aspx\",\n                \"~/Areas/{2}/Views/{1}/{0}.ascx\",\n                \"~/Areas/{2}/Views/Shared/{0}.aspx\",\n                \"~/Areas/{2}/Views/Shared/{0}.ascx\",\n            };\n\n            // Act\n            TestableWebFormViewEngine engine = new TestableWebFormViewEngine();\n\n            // Assert\n            Assert.Equal(expected, engine.AreaPartialViewLocationFormats);\n        }\n\n        [Fact]\n        public void ViewLocationFormatsProperty()\n        {\n            // Arrange\n            string[] expected = new string[]\n            {\n                \"~/Views/{1}/{0}.aspx\",\n                \"~/Views/{1}/{0}.ascx\",\n                \"~/Views/Shared/{0}.aspx\",\n                \"~/Views/Shared/{0}.ascx\"\n            };\n\n            // Act\n            TestableWebFormViewEngine engine = new TestableWebFormViewEngine();\n\n            // Assert\n            Assert.Equal(expected, engine.ViewLocationFormats);\n        }\n\n        [Fact]\n        public void AreaViewLocationFormatsProperty()\n        {\n            // Arrange\n            string[] expected = new string[]\n            {\n                \"~/Areas/{2}/Views/{1}/{0}.aspx\",\n                \"~/Areas/{2}/Views/{1}/{0}.ascx\",\n                \"~/Areas/{2}/Views/Shared/{0}.aspx\",\n                \"~/Areas/{2}/Views/Shared/{0}.ascx\",\n            };\n\n            // Act\n            TestableWebFormViewEngine engine = new TestableWebFormViewEngine();\n\n            // Assert\n            Assert.Equal(expected, engine.AreaViewLocationFormats);\n        }\n\n        [Fact]\n        public void FileExtensionsProperty()\n        {\n            // Arrange\n            string[] expected = new string[]\n            {\n                \"aspx\",\n                \"ascx\",\n                \"master\",\n            };\n\n            // Act\n            TestableWebFormViewEngine engine = new TestableWebFormViewEngine();\n\n            // Assert\n            Assert.Equal(expected, engine.FileExtensions);\n        }\n\n        private sealed class TestableWebFormViewEngine : WebFormViewEngine\n        {\n            public TestableWebFormViewEngine()\n                : base()\n            {\n            }\n\n            public TestableWebFormViewEngine(IViewPageActivator viewPageActivator)\n                : base(viewPageActivator)\n            {\n            }\n\n            public new IViewPageActivator ViewPageActivator\n            {\n                get { return base.ViewPageActivator; }\n            }\n\n            public new VirtualPathProvider VirtualPathProvider\n            {\n                get { return base.VirtualPathProvider; }\n                set { base.VirtualPathProvider = value; }\n            }\n\n            public IView CreatePartialView(string partialPath)\n            {\n                return base.CreatePartialView(new ControllerContext(), partialPath);\n            }\n\n            public IView CreateView(string viewPath, string masterPath)\n            {\n                return base.CreateView(new ControllerContext(), viewPath, masterPath);\n            }\n\n            // This method should remain overridable in derived view engines\n            protected override bool FileExists(ControllerContext controllerContext, string virtualPath)\n            {\n                return base.FileExists(controllerContext, virtualPath);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Test/WebFormViewTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public class WebFormViewTest\n    {\n        [Fact]\n        public void GuardClauses()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => new WebFormView(new ControllerContext(), String.Empty, \"~/master\"),\n                \"viewPath\"\n                );\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmpty(\n                () => new WebFormView(new ControllerContext(), null, \"~/master\"),\n                \"viewPath\"\n                );\n\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => new WebFormView(null, \"view path\", \"~/master\"),\n                \"controllerContext\"\n                );\n        }\n\n        [Fact]\n        public void MasterPathProperty()\n        {\n            // Act\n            WebFormView view = new WebFormView(new ControllerContext(), \"view path\", \"master path\");\n\n            // Assert\n            Assert.Equal(\"master path\", view.MasterPath);\n        }\n\n        [Fact]\n        public void MasterPathPropertyReturnsEmptyStringIfMasterNotSpecified()\n        {\n            // Act\n            WebFormView view = new WebFormView(new ControllerContext(), \"view path\", null);\n\n            // Assert\n            Assert.Equal(String.Empty, view.MasterPath);\n        }\n\n        [Fact]\n        public void RenderWithUnsupportedTypeThrows()\n        {\n            // Arrange\n            ViewContext context = new Mock<ViewContext>().Object;\n            MockBuildManager buildManagerMock = new MockBuildManager(\"view path\", typeof(int));\n            WebFormView view = new WebFormView(new ControllerContext(), \"view path\", null);\n            view.BuildManager = buildManagerMock;\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => view.Render(context, null),\n                \"The view at 'view path' must derive from ViewPage, ViewPage<TModel>, ViewUserControl, or ViewUserControl<TModel>.\"\n                );\n        }\n\n        [Fact]\n        public void RenderWithViewPageAndMasterRendersView()\n        {\n            // Arrange\n            ViewContext context = new Mock<ViewContext>().Object;\n            MockBuildManager buildManager = new MockBuildManager(\"view path\", typeof(object));\n            Mock<IViewPageActivator> activator = new Mock<IViewPageActivator>(MockBehavior.Strict);\n            ControllerContext controllerContext = new ControllerContext();\n            StubViewPage viewPage = new StubViewPage();\n            activator.Setup(l => l.Create(controllerContext, typeof(object))).Returns(viewPage);\n            WebFormView view = new WebFormView(controllerContext, \"view path\", \"master path\", activator.Object);\n            view.BuildManager = buildManager;\n\n            // Act\n            view.Render(context, null);\n\n            // Assert\n            Assert.Equal(context, viewPage.ResultViewContext);\n            Assert.Equal(\"master path\", viewPage.MasterLocation);\n        }\n\n        [Fact]\n        public void RenderWithViewPageRendersView()\n        {\n            // Arrange\n            ViewContext context = new Mock<ViewContext>().Object;\n            MockBuildManager buildManager = new MockBuildManager(\"view path\", typeof(object));\n            Mock<IViewPageActivator> activator = new Mock<IViewPageActivator>(MockBehavior.Strict);\n            ControllerContext controllerContext = new ControllerContext();\n            StubViewPage viewPage = new StubViewPage();\n            activator.Setup(l => l.Create(controllerContext, typeof(object))).Returns(viewPage);\n            WebFormView view = new WebFormView(controllerContext, \"view path\", null, activator.Object);\n            view.BuildManager = buildManager;\n\n            // Act\n            view.Render(context, null);\n\n            // Assert\n            Assert.Equal(context, viewPage.ResultViewContext);\n            Assert.Equal(String.Empty, viewPage.MasterLocation);\n        }\n\n        [Fact]\n        public void RenderWithViewUserControlAndMasterThrows()\n        {\n            // Arrange\n            ViewContext context = new Mock<ViewContext>().Object;\n            MockBuildManager buildManagerMock = new MockBuildManager(\"view path\", typeof(StubViewUserControl));\n            WebFormView view = new WebFormView(new ControllerContext(), \"view path\", \"master path\");\n            view.BuildManager = buildManagerMock;\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(\n                () => view.Render(context, null),\n                \"A master name cannot be specified when the view is a ViewUserControl.\"\n                );\n        }\n\n        [Fact]\n        public void RenderWithViewUserControlRendersView()\n        {\n            // Arrange\n            ViewContext context = new Mock<ViewContext>().Object;\n            MockBuildManager buildManager = new MockBuildManager(\"view path\", typeof(object));\n            Mock<IViewPageActivator> activator = new Mock<IViewPageActivator>(MockBehavior.Strict);\n            ControllerContext controllerContext = new ControllerContext();\n            StubViewUserControl viewUserControl = new StubViewUserControl();\n            activator.Setup(l => l.Create(controllerContext, typeof(object))).Returns(viewUserControl);\n            WebFormView view = new WebFormView(controllerContext, \"view path\", null, activator.Object) { BuildManager = buildManager };\n\n            // Act\n            view.Render(context, null);\n\n            // Assert\n            Assert.Equal(context, viewUserControl.ResultViewContext);\n        }\n\n        public sealed class StubViewPage : ViewPage\n        {\n            public ViewContext ResultViewContext;\n\n            public override void RenderView(ViewContext viewContext)\n            {\n                ResultViewContext = viewContext;\n            }\n        }\n\n        public sealed class StubViewUserControl : ViewUserControl\n        {\n            public ViewContext ResultViewContext;\n\n            public override void RenderView(ViewContext viewContext)\n            {\n                ResultViewContext = viewContext;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Util/AnonymousObject.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace Microsoft.Web.UnitTestUtil\n{\n    public static class AnonymousObject\n    {\n        public static string Inspect(object obj)\n        {\n            if (obj == null)\n            {\n                return \"(null)\";\n            }\n\n            object[] args = Enumerable.Empty<Object>().ToArray();\n            IEnumerable<string> values = obj.GetType()\n                .GetProperties()\n                .Select(prop => String.Format(\"{0}: {1}\", prop.Name, prop.GetValue(obj, args)));\n\n            if (!values.Any())\n            {\n                return \"(no properties)\";\n            }\n\n            return \"{ \" + values.Aggregate((left, right) => left + \", \" + right) + \" }\";\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Util/DictionaryHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.TestUtil\n{\n    public class DictionaryHelper<TKey, TValue>\n    {\n        public IEqualityComparer<TKey> Comparer { get; set; }\n\n        public Func<IDictionary<TKey, TValue>> Creator { get; set; }\n\n        public IList<TKey> SampleKeys { get; set; }\n\n        public IList<TValue> SampleValues { get; set; }\n\n        public bool SkipItemPropertyTest { get; set; }\n\n        public bool ThrowOnKeyNotFound { get; set; }\n\n        public void Execute()\n        {\n            ValidateProperties();\n\n            Executor executor = new Executor()\n            {\n                Comparer = Comparer,\n                Creator = Creator,\n                ThrowOnKeyNotFound = ThrowOnKeyNotFound,\n                Values = SampleValues.ToArray()\n            };\n            SeparateKeys(out executor.ExcludedKey, out executor.ConflictingKeys, out executor.NonConflictingKeys);\n\n            executor.TestAdd1();\n            executor.TestAdd1ThrowsArgumentExceptionIfKeyAlreadyInDictionary();\n            executor.TestAdd2();\n            executor.TestClear();\n            executor.TestContains();\n            executor.TestContainsKey();\n            executor.TestCopyTo();\n            executor.TestCountProperty();\n            executor.TestGetEnumerator();\n            executor.TestGetEnumeratorGeneric();\n            executor.TestIsReadOnlyProperty();\n\n            if (!SkipItemPropertyTest)\n            {\n                executor.TestItemProperty();\n            }\n\n            executor.TestKeysProperty();\n            executor.TestRemove1();\n            executor.TestRemove2();\n            executor.TestTryGetValue();\n            executor.TestValuesProperty();\n        }\n\n        private void SeparateKeys(out TKey excludedKey, out TKey[] conflictingKeys, out TKey[] nonConflictingKeys)\n        {\n            List<TKey> nonConflictingKeyList = new List<TKey>();\n            TKey[] newConflictingKeys = null;\n\n            var keyLookup = SampleKeys.ToLookup(key => key, Comparer);\n            foreach (var entry in keyLookup)\n            {\n                if (entry.Count() == 1)\n                {\n                    // not a conflict\n                    nonConflictingKeyList.AddRange(entry);\n                }\n                else\n                {\n                    // conflict\n                    newConflictingKeys = entry.ToArray();\n                }\n            }\n\n            excludedKey = nonConflictingKeyList[nonConflictingKeyList.Count - 1];\n            nonConflictingKeyList.RemoveAt(nonConflictingKeyList.Count - 1);\n            conflictingKeys = newConflictingKeys;\n            nonConflictingKeys = nonConflictingKeyList.ToArray();\n        }\n\n        private void ValidateProperties()\n        {\n            if (Creator == null)\n            {\n                throw new InvalidOperationException(\"The Creator property must not be null.\");\n            }\n            if (SampleKeys == null || SampleKeys.Count < 4)\n            {\n                throw new InvalidOperationException(\"The SampleKeys property must contain at least 4 elements.\");\n            }\n            if (SampleValues == null || SampleValues.Count != SampleKeys.Count)\n            {\n                throw new InvalidOperationException(\"The SampleValues property must contain as many elements as the SampleKeys property.\");\n            }\n\n            HashSet<TKey> keys = new HashSet<TKey>(SampleKeys, Comparer);\n            if (keys.Count != SampleKeys.Count - 1)\n            {\n                throw new InvalidOperationException(\"The SampleKeys property must contain exactly one colliding keypair using the given comparer.\");\n            }\n        }\n\n        private class Executor\n        {\n            public IEqualityComparer<TKey> Comparer;\n            public Func<IDictionary<TKey, TValue>> Creator;\n            public TKey ExcludedKey;\n            public TKey[] ConflictingKeys;\n            public TKey[] NonConflictingKeys;\n            public bool ThrowOnKeyNotFound;\n            public TValue[] Values;\n\n            private IEnumerable<KeyValuePair<TKey, TValue>> MakeKeyValuePairs()\n            {\n                return MakeKeyValuePairs(false /* includeConflictingKeys */);\n            }\n\n            private IEnumerable<KeyValuePair<TKey, TValue>> MakeKeyValuePairs(bool includeConflictingKeys)\n            {\n                for (int i = 0; i < NonConflictingKeys.Length; i++)\n                {\n                    TKey key = NonConflictingKeys[i];\n                    TValue value = Values[i];\n                    yield return new KeyValuePair<TKey, TValue>(key, value);\n                }\n                if (includeConflictingKeys)\n                {\n                    for (int i = 0; i < 2; i++)\n                    {\n                        TKey key = ConflictingKeys[i];\n                        TValue value = Values[NonConflictingKeys.Length + i];\n                        yield return new KeyValuePair<TKey, TValue>(key, value);\n                    }\n                }\n            }\n\n            public void TestAdd1()\n            {\n                // Arrange\n                Dictionary<TKey, TValue> controlDictionary = new Dictionary<TKey, TValue>(Comparer);\n                IDictionary<TKey, TValue> testDictionary = Creator();\n\n                // Act\n                foreach (var entry in MakeKeyValuePairs())\n                {\n                    controlDictionary.Add(entry.Key, entry.Value);\n                    testDictionary.Add(entry.Key, entry.Value);\n                }\n\n                // Assert\n                VerifyDictionaryEntriesEqual(controlDictionary, testDictionary);\n            }\n\n            public void TestAdd1ThrowsArgumentExceptionIfKeyAlreadyInDictionary()\n            {\n                // Arrange\n                IDictionary<TKey, TValue> testDictionary = Creator();\n\n                // Act & assert\n                var pairs = MakeKeyValuePairs(true /* includeConflictingKeys */).Skip(NonConflictingKeys.Length).ToArray();\n                testDictionary.Add(pairs[0].Key, pairs[1].Value);\n\n                Assert.Throws<ArgumentException>(\n                    delegate { testDictionary.Add(pairs[1].Key, pairs[1].Value); },\n                    \"An item with the same key has already been added.\"\n                    );\n            }\n\n            public void TestAdd2()\n            {\n                // Arrange\n                Dictionary<TKey, TValue> controlDictionary = new Dictionary<TKey, TValue>(Comparer);\n                IDictionary<TKey, TValue> testDictionary = Creator();\n\n                // Act\n                foreach (var entry in MakeKeyValuePairs())\n                {\n                    ((IDictionary<TKey, TValue>)controlDictionary).Add(entry);\n                    testDictionary.Add(entry);\n                }\n\n                // Assert\n                VerifyDictionaryEntriesEqual(controlDictionary, testDictionary);\n            }\n\n            public void TestClear()\n            {\n                // Arrange\n                IDictionary<TKey, TValue> testDictionary = Creator();\n\n                // Act\n                foreach (var entry in MakeKeyValuePairs())\n                {\n                    testDictionary.Add(entry);\n                }\n                testDictionary.Clear();\n\n                // Assert\n                Assert.Empty(testDictionary);\n            }\n\n            public void TestCountProperty()\n            {\n                // Arrange\n                Dictionary<TKey, TValue> controlDictionary = new Dictionary<TKey, TValue>(Comparer);\n                IDictionary<TKey, TValue> testDictionary = Creator();\n\n                // Act & assert\n                foreach (var entry in MakeKeyValuePairs())\n                {\n                    controlDictionary.Add(entry.Key, entry.Value);\n                    testDictionary.Add(entry.Key, entry.Value);\n                    Assert.Equal(controlDictionary.Count, testDictionary.Count);\n                }\n            }\n\n            public void TestContains()\n            {\n                // Arrange\n                IDictionary<TKey, TValue> testDictionary = Creator();\n\n                // Act\n                foreach (var entry in MakeKeyValuePairs())\n                {\n                    testDictionary.Add(entry);\n                }\n\n                // Assert\n                var shouldBeFound = MakeKeyValuePairs().First();\n                var shouldNotBeFound = new KeyValuePair<TKey, TValue>(ExcludedKey, Values[Values.Length - 1]);\n                Assert.True(testDictionary.Contains(shouldBeFound), String.Format(\"Test dictionary should have contained entry for KVP '{0}'.\", shouldBeFound));\n                Assert.False(testDictionary.Contains(shouldNotBeFound), String.Format(\"Test dictionary should not have contained entry for KVP '{0}'.\", shouldNotBeFound));\n            }\n\n            public void TestContainsKey()\n            {\n                // Arrange\n                IDictionary<TKey, TValue> testDictionary = Creator();\n\n                // Act\n                foreach (var entry in MakeKeyValuePairs())\n                {\n                    testDictionary.Add(entry);\n                }\n\n                // Assert\n                Assert.True(testDictionary.ContainsKey(NonConflictingKeys[0]), String.Format(\"Test dictionary should have contained entry for key '{0}'.\", NonConflictingKeys[0]));\n                Assert.False(testDictionary.ContainsKey(ExcludedKey), String.Format(\"Test dictionary should not have contained entry for key '{0}'.\", ExcludedKey));\n            }\n\n            public void TestCopyTo()\n            {\n                // Arrange\n                IDictionary<TKey, TValue> controlDictionary = new Dictionary<TKey, TValue>(Comparer);\n                IDictionary<TKey, TValue> testDictionary = Creator();\n\n                foreach (var entry in MakeKeyValuePairs())\n                {\n                    controlDictionary.Add(entry.Key, entry.Value);\n                    testDictionary.Add(entry.Key, entry.Value);\n                }\n                KeyValuePair<TKey, TValue>[] testKvps = new KeyValuePair<TKey, TValue>[testDictionary.Count + 2];\n\n                // Act\n                testDictionary.CopyTo(testKvps, 2);\n\n                // Assert\n                for (int i = 0; i < 2; i++)\n                {\n                    var defaultValue = default(KeyValuePair<TKey, TValue>);\n                    var entry = testKvps[i];\n                    Assert.Equal(defaultValue, entry);\n                }\n                for (int i = 2; i < testKvps.Length; i++)\n                {\n                    var entry = testKvps[i];\n                    Assert.True(controlDictionary.Contains(entry), String.Format(\"The value '{0}' wasn't present in the control dictionary.\", entry));\n                    controlDictionary.Remove(entry);\n                }\n\n                Assert.Empty(controlDictionary);\n            }\n\n            public void TestGetEnumerator()\n            {\n                // Arrange\n                Dictionary<TKey, TValue> controlDictionary = new Dictionary<TKey, TValue>(Comparer);\n                IDictionary<TKey, TValue> testDictionary = Creator();\n\n                foreach (var entry in MakeKeyValuePairs())\n                {\n                    controlDictionary.Add(entry.Key, entry.Value);\n                    testDictionary.Add(entry.Key, entry.Value);\n                }\n\n                IEnumerable testDictionaryAsEnumerable = (IEnumerable)testDictionary;\n\n                // Act\n                Dictionary<TKey, TValue> newTestDictionary = new Dictionary<TKey, TValue>(Comparer);\n                foreach (object entry in testDictionaryAsEnumerable)\n                {\n                    var kvp = Assert.IsType<KeyValuePair<TKey, TValue>>(entry);\n                    newTestDictionary.Add(kvp.Key, kvp.Value);\n                }\n\n                // Assert\n                VerifyDictionaryEntriesEqual(controlDictionary, newTestDictionary);\n            }\n\n            public void TestGetEnumeratorGeneric()\n            {\n                // Arrange\n                Dictionary<TKey, TValue> controlDictionary = new Dictionary<TKey, TValue>(Comparer);\n                IDictionary<TKey, TValue> testDictionary = Creator();\n\n                foreach (var entry in MakeKeyValuePairs())\n                {\n                    controlDictionary.Add(entry.Key, entry.Value);\n                    testDictionary.Add(entry.Key, entry.Value);\n                }\n\n                // Act & assert\n                VerifyDictionaryEntriesEqual(controlDictionary, testDictionary);\n            }\n\n            public void TestIsReadOnlyProperty()\n            {\n                // Arrange\n                IDictionary<TKey, TValue> testDictionary = Creator();\n\n                // Act & assert\n                Assert.False(testDictionary.IsReadOnly, \"Dictionary should not be read only.\");\n            }\n\n            public void TestItemProperty()\n            {\n                // Arrange\n                Dictionary<TKey, TValue> controlDictionary = new Dictionary<TKey, TValue>(Comparer);\n                IDictionary<TKey, TValue> testDictionary = Creator();\n\n                var shouldBeFound = MakeKeyValuePairs().First();\n                var shouldNotBeFound = new KeyValuePair<TKey, TValue>(ExcludedKey, Values[Values.Length - 1]);\n\n                // Act & assert\n                foreach (var entry in MakeKeyValuePairs())\n                {\n                    controlDictionary.Add(entry.Key, entry.Value);\n                    testDictionary[entry.Key] = entry.Value;\n                }\n                VerifyDictionaryEntriesEqual(controlDictionary, testDictionary);\n\n                TValue value = testDictionary[shouldBeFound.Key];\n                Assert.Equal(shouldBeFound.Value, value);\n\n                if (ThrowOnKeyNotFound)\n                {\n                    Assert.Throws<KeyNotFoundException>(\n                        delegate { TValue valueNotFound = testDictionary[shouldNotBeFound.Key]; }, allowDerivedExceptions: true);\n                }\n                else\n                {\n                    TValue valueNotFound = testDictionary[shouldNotBeFound.Key];\n                    Assert.Equal(default(TValue), valueNotFound); // Should not throw\n                }\n            }\n\n            public void TestKeysProperty()\n            {\n                // Arrange\n                Dictionary<TKey, TValue> controlDictionary = new Dictionary<TKey, TValue>(Comparer);\n                IDictionary<TKey, TValue> testDictionary = Creator();\n\n                foreach (var entry in MakeKeyValuePairs())\n                {\n                    controlDictionary.Add(entry.Key, entry.Value);\n                    testDictionary.Add(entry.Key, entry.Value);\n                }\n\n                // Act\n                HashSet<TKey> controlKeys = new HashSet<TKey>(controlDictionary.Keys, Comparer);\n                HashSet<TKey> testKeys = new HashSet<TKey>(testDictionary.Keys, Comparer);\n\n                // Assert\n                Assert.True(controlKeys.SetEquals(testKeys), \"Control dictionary and test dictionary key sets were not equal.\");\n            }\n\n            public void TestRemove1()\n            {\n                // Arrange\n                Dictionary<TKey, TValue> controlDictionary = new Dictionary<TKey, TValue>(Comparer);\n                IDictionary<TKey, TValue> testDictionary = Creator();\n\n                foreach (var entry in MakeKeyValuePairs())\n                {\n                    controlDictionary.Add(entry.Key, entry.Value);\n                    testDictionary.Add(entry.Key, entry.Value);\n                }\n\n                // Act\n                bool removalSuccess = testDictionary.Remove(NonConflictingKeys[0]);\n                bool removalFailure = testDictionary.Remove(ExcludedKey);\n\n                // Assert\n                Assert.True(removalSuccess, \"Remove() should return true if the key was removed.\");\n                Assert.False(removalFailure, \"Remove() should return false if the key was not removed.\");\n\n                controlDictionary.Remove(NonConflictingKeys[0]);\n                VerifyDictionaryEntriesEqual(controlDictionary, testDictionary);\n            }\n\n            public void TestRemove2()\n            {\n                // Arrange\n                Dictionary<TKey, TValue> controlDictionary = new Dictionary<TKey, TValue>(Comparer);\n                IDictionary<TKey, TValue> testDictionary = Creator();\n\n                foreach (var entry in MakeKeyValuePairs())\n                {\n                    ((IDictionary<TKey, TValue>)controlDictionary).Add(entry);\n                    testDictionary.Add(entry);\n                }\n\n                // Act\n                var shouldBeFound = MakeKeyValuePairs().First();\n                var shouldNotBeFound = new KeyValuePair<TKey, TValue>(ExcludedKey, Values[Values.Length - 1]);\n                bool removalSuccess = testDictionary.Remove(shouldBeFound);\n                bool removalFailure = testDictionary.Remove(shouldNotBeFound);\n\n                // Assert\n                Assert.True(removalSuccess, \"Remove() should return true if the key was removed.\");\n                Assert.False(removalFailure, \"Remove() should return false if the key was not removed.\");\n\n                ((IDictionary<TKey, TValue>)controlDictionary).Remove(shouldBeFound);\n                VerifyDictionaryEntriesEqual(controlDictionary, testDictionary);\n            }\n\n            public void TestTryGetValue()\n            {\n                // Arrange\n                Dictionary<TKey, TValue> controlDictionary = new Dictionary<TKey, TValue>(Comparer);\n                IDictionary<TKey, TValue> testDictionary = Creator();\n\n                foreach (var entry in MakeKeyValuePairs())\n                {\n                    controlDictionary.Add(entry.Key, entry.Value);\n                    testDictionary.Add(entry.Key, entry.Value);\n                }\n\n                var shouldBeFound = MakeKeyValuePairs().First();\n                var shouldNotBeFound = new KeyValuePair<TKey, TValue>(ExcludedKey, Values[Values.Length - 1]);\n\n                // Act\n                TValue value1;\n                bool returned1 = testDictionary.TryGetValue(shouldBeFound.Key, out value1);\n                TValue value2;\n                bool returned2 = testDictionary.TryGetValue(shouldNotBeFound.Key, out value2);\n\n                // Assert\n                Assert.True(returned1, String.Format(\"The entry '{0}' should have been found.\", shouldBeFound));\n                Assert.Equal(shouldBeFound.Value, value1);\n                Assert.False(returned2, String.Format(\"The entry '{0}' should not have been found.\", shouldNotBeFound));\n                Assert.Equal(default(TValue), value2);\n            }\n\n            public void TestValuesProperty()\n            {\n                // Arrange\n                Dictionary<TKey, TValue> controlDictionary = new Dictionary<TKey, TValue>(Comparer);\n                IDictionary<TKey, TValue> testDictionary = Creator();\n\n                foreach (var entry in MakeKeyValuePairs())\n                {\n                    controlDictionary.Add(entry.Key, entry.Value);\n                    testDictionary.Add(entry.Key, entry.Value);\n                }\n\n                // Act\n                List<TValue> controlValues = controlDictionary.Values.ToList();\n                List<TValue> testValues = testDictionary.Values.ToList();\n\n                // Assert\n                foreach (var entry in controlValues)\n                {\n                    Assert.True(testValues.Contains(entry), String.Format(\"Test dictionary did not contain value '{0}'.\", entry));\n                }\n                foreach (var entry in testValues)\n                {\n                    Assert.True(controlValues.Contains(entry), String.Format(\"Control dictionary did not contain value '{0}'.\", entry));\n                }\n            }\n\n            private void VerifyDictionaryEntriesEqual(Dictionary<TKey, TValue> controlDictionary, IDictionary<TKey, TValue> testDictionary)\n            {\n                Assert.Equal(controlDictionary.Count, testDictionary.Count);\n\n                Dictionary<TKey, TValue> clonedControlDictionary = new Dictionary<TKey, TValue>(controlDictionary, controlDictionary.Comparer);\n\n                foreach (var entry in testDictionary)\n                {\n                    var key = entry.Key;\n                    Assert.True(clonedControlDictionary.ContainsKey(entry.Key), String.Format(\"Control dictionary did not contain key '{0}'.\", key));\n                    clonedControlDictionary.Remove(key);\n                }\n\n                foreach (var entry in clonedControlDictionary)\n                {\n                    var key = entry.Key;\n                    Assert.True(false, String.Format(\"Test dictionary did not contain key '{0}'.\", key));\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Util/HttpContextHelpers.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing Moq;\n\nnamespace System.Web.Mvc.Test\n{\n    public static class HttpContextHelpers\n    {\n        public static Mock<HttpContextBase> GetMockHttpContext()\n        {\n            Mock<HttpContextBase> mockContext = new Mock<HttpContextBase>();\n            mockContext.Setup(m => m.Items).Returns(new Dictionary<object, object>());\n            return mockContext;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Util/MvcHelper.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections;\nusing System.IO;\nusing System.Linq.Expressions;\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Web.Routing;\nusing Moq;\n\nnamespace Microsoft.Web.UnitTestUtil\n{\n    public static class MvcHelper\n    {\n        public const string AppPathModifier = \"/$(SESSION)\";\n\n        public static HtmlHelper<object> GetHtmlHelper()\n        {\n            HttpContextBase httpcontext = GetHttpContext(\"/app/\", null, null);\n            RouteCollection rt = new RouteCollection();\n            rt.Add(new Route(\"{controller}/{action}/{id}\", null) { Defaults = new RouteValueDictionary(new { id = \"defaultid\" }) });\n            rt.Add(\"namedroute\", new Route(\"named/{controller}/{action}/{id}\", null) { Defaults = new RouteValueDictionary(new { id = \"defaultid\" }) });\n            RouteData rd = new RouteData();\n            rd.Values.Add(\"controller\", \"home\");\n            rd.Values.Add(\"action\", \"oldaction\");\n\n            ViewDataDictionary vdd = new ViewDataDictionary();\n\n            ViewContext viewContext = new ViewContext()\n            {\n                HttpContext = httpcontext,\n                RouteData = rd,\n                ViewData = vdd\n            };\n            Mock<IViewDataContainer> mockVdc = new Mock<IViewDataContainer>();\n            mockVdc.Setup(vdc => vdc.ViewData).Returns(vdd);\n\n            HtmlHelper<object> htmlHelper = new HtmlHelper<object>(viewContext, mockVdc.Object, rt);\n            return htmlHelper;\n        }\n\n        public static HtmlHelper GetHtmlHelper(string protocol, int port)\n        {\n            HttpContextBase httpcontext = GetHttpContext(\"/app/\", null, null, protocol, port);\n            RouteCollection rt = new RouteCollection();\n            rt.Add(new Route(\"{controller}/{action}/{id}\", null) { Defaults = new RouteValueDictionary(new { id = \"defaultid\" }) });\n            rt.Add(\"namedroute\", new Route(\"named/{controller}/{action}/{id}\", null) { Defaults = new RouteValueDictionary(new { id = \"defaultid\" }) });\n            RouteData rd = new RouteData();\n            rd.Values.Add(\"controller\", \"home\");\n            rd.Values.Add(\"action\", \"oldaction\");\n\n            ViewDataDictionary vdd = new ViewDataDictionary();\n\n            Mock<ViewContext> mockViewContext = new Mock<ViewContext>();\n            mockViewContext.Setup(c => c.HttpContext).Returns(httpcontext);\n            mockViewContext.Setup(c => c.RouteData).Returns(rd);\n            mockViewContext.Setup(c => c.ViewData).Returns(vdd);\n            Mock<IViewDataContainer> mockVdc = new Mock<IViewDataContainer>();\n            mockVdc.Setup(vdc => vdc.ViewData).Returns(vdd);\n\n            HtmlHelper htmlHelper = new HtmlHelper(mockViewContext.Object, mockVdc.Object, rt);\n            return htmlHelper;\n        }\n\n        public static HtmlHelper GetHtmlHelper(ViewDataDictionary viewData)\n        {\n            Mock<ViewContext> mockViewContext = new Mock<ViewContext>() { CallBase = true };\n            mockViewContext.Setup(c => c.ViewData).Returns(viewData);\n            mockViewContext.Setup(c => c.HttpContext.Items).Returns(new Hashtable());\n            IViewDataContainer container = GetViewDataContainer(viewData);\n            return new HtmlHelper(mockViewContext.Object, container);\n        }\n\n        public static HtmlHelper<TModel> GetHtmlHelper<TModel>(ViewDataDictionary<TModel> viewData)\n        {\n            Mock<ViewContext> mockViewContext = new Mock<ViewContext>() { CallBase = true };\n            mockViewContext.Setup(c => c.ViewData).Returns(viewData);\n            mockViewContext.Setup(c => c.HttpContext.Items).Returns(new Hashtable());\n            IViewDataContainer container = GetViewDataContainer(viewData);\n            return new HtmlHelper<TModel>(mockViewContext.Object, container);\n        }\n\n        public static HtmlHelper GetHtmlHelperWithPath(ViewDataDictionary viewData)\n        {\n            return GetHtmlHelperWithPath(viewData, \"/\");\n        }\n\n        public static HtmlHelper GetHtmlHelperWithPath(ViewDataDictionary viewData, string appPath)\n        {\n            ViewContext viewContext = GetViewContextWithPath(appPath, viewData);\n            Mock<IViewDataContainer> mockContainer = new Mock<IViewDataContainer>();\n            mockContainer.Setup(c => c.ViewData).Returns(viewData);\n            IViewDataContainer container = mockContainer.Object;\n            return new HtmlHelper(viewContext, container, new RouteCollection());\n        }\n\n        public static HtmlHelper<TModel> GetHtmlHelperWithPath<TModel>(ViewDataDictionary<TModel> viewData, string appPath)\n        {\n            ViewContext viewContext = GetViewContextWithPath(appPath, viewData);\n            Mock<IViewDataContainer> mockContainer = new Mock<IViewDataContainer>();\n            mockContainer.Setup(c => c.ViewData).Returns(viewData);\n            IViewDataContainer container = mockContainer.Object;\n            return new HtmlHelper<TModel>(viewContext, container, new RouteCollection());\n        }\n\n        public static HtmlHelper<TModel> GetHtmlHelperWithPath<TModel>(ViewDataDictionary<TModel> viewData)\n        {\n            return GetHtmlHelperWithPath(viewData, \"/\");\n        }\n\n        public static HttpContextBase GetHttpContext(string appPath, string requestPath, string httpMethod, string protocol, int port)\n        {\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n\n            if (!String.IsNullOrEmpty(appPath))\n            {\n                mockHttpContext.Setup(o => o.Request.ApplicationPath).Returns(appPath);\n                mockHttpContext.Setup(o => o.Request.RawUrl).Returns(appPath);\n            }\n            if (!String.IsNullOrEmpty(requestPath))\n            {\n                mockHttpContext.Setup(o => o.Request.AppRelativeCurrentExecutionFilePath).Returns(requestPath);\n            }\n\n            Uri uri;\n\n            if (port >= 0)\n            {\n                uri = new Uri(protocol + \"://localhost\" + \":\" + Convert.ToString(port));\n            }\n            else\n            {\n                uri = new Uri(protocol + \"://localhost\");\n            }\n            mockHttpContext.Setup(o => o.Request.Url).Returns(uri);\n\n            mockHttpContext.Setup(o => o.Request.PathInfo).Returns(String.Empty);\n            if (!String.IsNullOrEmpty(httpMethod))\n            {\n                mockHttpContext.Setup(o => o.Request.HttpMethod).Returns(httpMethod);\n            }\n\n            mockHttpContext.Setup(o => o.Session).Returns((HttpSessionStateBase)null);\n            mockHttpContext.Setup(o => o.Response.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(r => AppPathModifier + r);\n            mockHttpContext.Setup(o => o.Items).Returns(new Hashtable());\n            return mockHttpContext.Object;\n        }\n\n        public static HttpContextBase GetHttpContext(string appPath, string requestPath, string httpMethod)\n        {\n            return GetHttpContext(appPath, requestPath, httpMethod, Uri.UriSchemeHttp.ToString(), -1);\n        }\n\n        public static ViewDataDictionary<TValue> GetNestedViewData<TModel, TValue>(ViewDataDictionary<TModel> viewData, Expression<Func<TModel, TValue>> expression)\n        {\n            var metadata = ModelMetadata.FromLambdaExpression(expression, viewData);\n            var htmlFieldName = ExpressionHelper.GetExpressionText(expression);\n\n\n            ViewDataDictionary nestedViewData = new ViewDataDictionary(viewData)\n            {\n                Model = metadata.Model,\n                ModelMetadata = metadata,\n                TemplateInfo = new TemplateInfo\n                {\n                    HtmlFieldPrefix = viewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName),\n                }\n            };\n\n            return new ViewDataDictionary<TValue>(nestedViewData);\n        }\n\n        public static ViewContext GetViewContextWithPath(string appPath, ViewDataDictionary viewData)\n        {\n            HttpContextBase httpContext = GetHttpContext(appPath, \"/request\", \"GET\");\n\n            Mock<ViewContext> mockViewContext = new Mock<ViewContext>() { DefaultValue = DefaultValue.Mock };\n            mockViewContext.Setup(c => c.HttpContext).Returns(httpContext);\n            mockViewContext.Setup(c => c.ViewData).Returns(viewData);\n            mockViewContext.Setup(c => c.Writer).Returns(new StringWriter());\n            return mockViewContext.Object;\n        }\n\n        public static ViewContext GetViewContextWithPath(ViewDataDictionary viewData)\n        {\n            return GetViewContextWithPath(\"/\", viewData);\n        }\n\n        public static IViewDataContainer GetViewDataContainer(ViewDataDictionary viewData)\n        {\n            Mock<IViewDataContainer> mockContainer = new Mock<IViewDataContainer>();\n            mockContainer.Setup(c => c.ViewData).Returns(viewData);\n            return mockContainer.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Util/Resolver.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Mvc.Test\n{\n    public class Resolver<T> : IResolver<T>\n    {\n        public T Current { get; set; }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Util/SimpleValueProvider.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.UnitTestUtil\n{\n    // just a simple value provider used for unit testing\n\n    public sealed class SimpleValueProvider : Dictionary<string, object>, IValueProvider\n    {\n        private readonly CultureInfo _culture;\n\n        public SimpleValueProvider()\n            : this(null)\n        {\n        }\n\n        public SimpleValueProvider(CultureInfo culture)\n            : base(StringComparer.OrdinalIgnoreCase)\n        {\n            _culture = culture ?? CultureInfo.InvariantCulture;\n        }\n\n        // copied from ValueProviderUtil\n        public bool ContainsPrefix(string prefix)\n        {\n            foreach (string key in Keys)\n            {\n                if (key != null)\n                {\n                    if (prefix.Length == 0)\n                    {\n                        return true; // shortcut - non-null key matches empty prefix\n                    }\n\n                    if (key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))\n                    {\n                        if (key.Length == prefix.Length)\n                        {\n                            return true; // exact match\n                        }\n                        else\n                        {\n                            switch (key[prefix.Length])\n                            {\n                                case '.': // known separator characters\n                                case '[':\n                                    return true;\n                            }\n                        }\n                    }\n                }\n            }\n\n            return false; // nothing found\n        }\n\n        public ValueProviderResult GetValue(string key)\n        {\n            object rawValue;\n            if (TryGetValue(key, out rawValue))\n            {\n                return new ValueProviderResult(rawValue, Convert.ToString(rawValue, _culture), _culture);\n            }\n            else\n            {\n                // value not found\n                return null;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/Util/SimpleViewDataContainer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc;\n\nnamespace Microsoft.Web.UnitTestUtil\n{\n    public class SimpleViewDataContainer : IViewDataContainer\n    {\n        public SimpleViewDataContainer(ViewDataDictionary viewData)\n        {\n            ViewData = viewData;\n        }\n\n        public ViewDataDictionary ViewData { get; set; }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Mvc.Test/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Castle.Core\" version=\"5.1.1\" targetFramework=\"net462\" />\n  <package id=\"Moq\" version=\"4.18.4\" targetFramework=\"net462\" />\n  <package id=\"Newtonsoft.Json\" version=\"13.0.1\" targetFramework=\"net462\" />\n  <package id=\"xunit\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.abstractions\" version=\"2.0.3\" targetFramework=\"net462\" />\n  <package id=\"xunit.analyzers\" version=\"1.1.0\" targetFramework=\"net462\" />\n  <package id=\"xunit.assert\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.execution\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.runner.visualstudio\" version=\"2.4.5\" targetFramework=\"net462\" developmentDependency=\"true\" />\n</packages>"
  },
  {
    "path": "test/System.Web.Razor.Test/CSharpRazorCodeLanguageTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing Microsoft.CSharp;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test\n{\n    public class CSharpRazorCodeLanguageTest\n    {\n        [Fact]\n        public void CreateCodeParserReturnsNewCSharpCodeParser()\n        {\n            // Arrange\n            RazorCodeLanguage service = new CSharpRazorCodeLanguage();\n\n            // Act\n            ParserBase parser = service.CreateCodeParser();\n\n            // Assert\n            Assert.NotNull(parser);\n            Assert.IsType<CSharpCodeParser>(parser);\n        }\n\n        [Fact]\n        public void CreateCodeGeneratorParserListenerReturnsNewCSharpCodeGeneratorParserListener()\n        {\n            // Arrange\n            RazorCodeLanguage service = new CSharpRazorCodeLanguage();\n\n            // Act\n            RazorEngineHost host = new RazorEngineHost(service);\n            RazorCodeGenerator generator = service.CreateCodeGenerator(\"Foo\", \"Bar\", \"Baz\", host);\n\n            // Assert\n            Assert.NotNull(generator);\n            Assert.IsType<CSharpRazorCodeGenerator>(generator);\n            Assert.Equal(\"Foo\", generator.ClassName);\n            Assert.Equal(\"Bar\", generator.RootNamespaceName);\n            Assert.Equal(\"Baz\", generator.SourceFileName);\n            Assert.Same(host, generator.Host);\n        }\n\n        [Fact]\n        public void CodeDomProviderTypeReturnsVBCodeProvider()\n        {\n            // Arrange\n            RazorCodeLanguage service = new CSharpRazorCodeLanguage();\n\n            // Assert\n            Assert.Equal(typeof(CSharpCodeProvider), service.CodeDomProviderType);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/CodeCompileUnitExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.CodeDom.Compiler;\nusing System.IO;\nusing System.Text;\n\nnamespace System.Web.Razor.Test\n{\n    internal static class CodeCompileUnitExtensions\n    {\n        public static string GenerateCode<T>(this CodeCompileUnit ccu) where T : CodeDomProvider, new()\n        {\n            StringBuilder output = new StringBuilder();\n            using (StringWriter writer = new StringWriter(output))\n            {\n                T provider = new T();\n                provider.GenerateCodeFromCompileUnit(ccu, writer, new CodeGeneratorOptions() { IndentString = \"    \" });\n            }\n\n            return output.ToString();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Editor/RazorEditorParserTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing System.Web.Razor.Editor;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Test.Utils;\nusing System.Web.Razor.Text;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.CSharp;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Razor.Test.Editor\n{\n    public class RazorEditorParserTest\n    {\n        private static readonly TestFile SimpleCSHTMLDocument = TestFile.Create(\"DesignTime.Simple.cshtml\");\n        private static readonly TestFile SimpleCSHTMLDocumentGenerated = TestFile.Create(\"DesignTime.Simple.txt\");\n        private const string TestLinePragmaFileName = \"C:\\\\This\\\\Path\\\\Is\\\\Just\\\\For\\\\Line\\\\Pragmas.cshtml\";\n\n        [Fact]\n        public void ConstructorRequiresNonNullHost()\n        {\n            Assert.ThrowsArgumentNull(() => new RazorEditorParser(null, TestLinePragmaFileName),\n                                          \"host\");\n        }\n\n        [Fact]\n        public void ConstructorRequiresNonNullPhysicalPath()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(() => new RazorEditorParser(CreateHost(), null),\n                                                 \"sourceFileName\");\n        }\n\n        [Fact]\n        public void ConstructorRequiresNonEmptyPhysicalPath()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(() => new RazorEditorParser(CreateHost(), String.Empty),\n                                                 \"sourceFileName\");\n        }\n\n        [Fact]\n        public void TreesAreDifferentReturnsTrueIfTreeStructureIsDifferent()\n        {\n            var factory = SpanFactory.CreateCsHtml();\n            Block original = new MarkupBlock(\n                factory.Markup(\"<p>\"),\n                new ExpressionBlock(\n                    factory.CodeTransition()),\n                factory.Markup(\"</p>\"));\n            Block modified = new MarkupBlock(\n                factory.Markup(\"<p>\"),\n                new ExpressionBlock(\n                    factory.CodeTransition(\"@\"),\n                    factory.Code(\"f\")\n                           .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: false)),\n                factory.Markup(\"</p>\"));\n            ITextBuffer oldBuffer = new StringTextBuffer(\"<p>@</p>\");\n            ITextBuffer newBuffer = new StringTextBuffer(\"<p>@f</p>\");\n            Assert.True(BackgroundParser.TreesAreDifferent(\n                original, modified, new[] {\n                    new TextChange(position: 4, oldLength: 0, oldBuffer: oldBuffer, newLength: 1, newBuffer: newBuffer)\n                }));\n        }\n\n        [Fact]\n        public void TreesAreDifferentReturnsFalseIfTreeStructureIsSame()\n        {\n            var factory = SpanFactory.CreateCsHtml();\n            Block original = new MarkupBlock(\n                factory.Markup(\"<p>\"),\n                new ExpressionBlock(\n                    factory.CodeTransition(),\n                    factory.Code(\"f\")\n                           .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: false)),\n                factory.Markup(\"</p>\"));\n            factory.Reset();\n            Block modified = new MarkupBlock(\n                factory.Markup(\"<p>\"),\n                new ExpressionBlock(\n                    factory.CodeTransition(),\n                    factory.Code(\"foo\")\n                           .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: false)),\n                factory.Markup(\"</p>\"));\n            original.LinkNodes();\n            modified.LinkNodes();\n            ITextBuffer oldBuffer = new StringTextBuffer(\"<p>@f</p>\");\n            ITextBuffer newBuffer = new StringTextBuffer(\"<p>@foo</p>\");\n            Assert.False(BackgroundParser.TreesAreDifferent(\n                original, modified, new[] {\n                    new TextChange(position: 5, oldLength: 0, oldBuffer: oldBuffer, newLength: 2, newBuffer: newBuffer)\n                }));\n        }\n\n        [Fact]\n        public void CheckForStructureChangesRequiresNonNullBufferInChange()\n        {\n            TextChange change = new TextChange();\n            Assert.ThrowsArgument(\n                () => new RazorEditorParser(\n                    CreateHost(),\n                    \"C:\\\\Foo.cshtml\").CheckForStructureChanges(change),\n                \"change\",\n                String.Format(RazorResources.Structure_Member_CannotBeNull, \"Buffer\", \"TextChange\"));\n        }\n\n        private static RazorEngineHost CreateHost()\n        {\n            return new RazorEngineHost(new CSharpRazorCodeLanguage()) { DesignTimeMode = true };\n        }\n\n        [Fact]\n        [ReplaceCulture]\n        public void CheckForStructureChangesStartsReparseAndFiresDocumentParseCompletedEventIfNoAdditionalChangesQueued()\n        {\n            // Arrange\n            using (RazorEditorParser parser = CreateClientParser())\n            {\n                StringTextBuffer input = new StringTextBuffer(SimpleCSHTMLDocument.ReadAllText());\n\n                DocumentParseCompleteEventArgs capturedArgs = null;\n                using (ManualResetEventSlim parseComplete = new ManualResetEventSlim(false))\n                {\n                    parser.DocumentParseComplete += (sender, args) =>\n                    {\n                        capturedArgs = args;\n                        parseComplete.Set();\n                    };\n\n                    // Act\n                    parser.CheckForStructureChanges(new TextChange(0, 0, new StringTextBuffer(String.Empty), input.Length, input));\n\n                    // Assert\n                    MiscUtils.DoWithTimeoutIfNotDebugging(parseComplete.Wait);\n\n                    string generatedCode = capturedArgs.GeneratorResults.GeneratedCode.GenerateCode<CSharpCodeProvider>();\n\n                    Assert.Equal(\n                        SimpleCSHTMLDocumentGenerated.ReadAllText(),\n                        MiscUtils.StripRuntimeVersion(generatedCode));\n                }\n            }\n        }\n\n        [Fact]\n        public void CheckForStructureChangesStartsFullReparseIfChangeOverlapsMultipleSpans()\n        {\n            // Arrange\n            using (RazorEditorParser parser = new RazorEditorParser(CreateHost(), TestLinePragmaFileName))\n            {\n                ITextBuffer original = new StringTextBuffer(\"Foo @bar Baz\");\n                ITextBuffer changed = new StringTextBuffer(\"Foo @bap Daz\");\n                TextChange change = new TextChange(7, 3, original, 3, changed);\n\n                using (ManualResetEventSlim parseComplete = new ManualResetEventSlim())\n                {\n                    int parseCount = 0;\n                    parser.DocumentParseComplete += (sender, args) =>\n                    {\n                        Interlocked.Increment(ref parseCount);\n                        parseComplete.Set();\n                    };\n\n                    Assert.Equal(PartialParseResult.Rejected, parser.CheckForStructureChanges(new TextChange(0, 0, new StringTextBuffer(String.Empty), 12, original)));\n                    MiscUtils.DoWithTimeoutIfNotDebugging(parseComplete.Wait); // Wait for the parse to finish\n                    parseComplete.Reset();\n\n                    // Act\n                    PartialParseResult result = parser.CheckForStructureChanges(change);\n\n                    // Assert\n                    Assert.Equal(PartialParseResult.Rejected, result);\n                    MiscUtils.DoWithTimeoutIfNotDebugging(parseComplete.Wait);\n                    Assert.Equal(2, parseCount);\n                }\n            }\n        }\n\n        private TextChange CreateDummyChange()\n        {\n            return new TextChange(0, 0, new StringTextBuffer(String.Empty), 3, new StringTextBuffer(\"foo\"));\n        }\n\n        private static Mock<RazorEditorParser> CreateMockParser()\n        {\n            return new Mock<RazorEditorParser>(CreateHost(), TestLinePragmaFileName) { CallBase = true };\n        }\n\n        private static RazorEditorParser CreateClientParser()\n        {\n            return new RazorEditorParser(CreateHost(), TestLinePragmaFileName);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Framework/BlockExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.Razor.Test.Framework\n{\n    public static class BlockExtensions\n    {\n        public static void LinkNodes(this Block self)\n        {\n            Span first = null;\n            Span previous = null;\n            foreach (Span span in self.Flatten())\n            {\n                if (first == null)\n                {\n                    first = span;\n                }\n                span.Previous = previous;\n\n                if (previous != null)\n                {\n                    previous.Next = span;\n                }\n                previous = span;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Framework/BlockTypes.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.Razor.Test.Framework\n{\n    // The product code doesn't need this, but having subclasses for the block types makes tests much cleaner :)\n\n    public class StatementBlock : Block\n    {\n        private const BlockType ThisBlockType = BlockType.Statement;\n\n        public StatementBlock(IBlockCodeGenerator codeGenerator, IEnumerable<SyntaxTreeNode> children)\n            : base(ThisBlockType, children, codeGenerator)\n        {\n        }\n\n        public StatementBlock(IBlockCodeGenerator codeGenerator, params SyntaxTreeNode[] children)\n            : this(codeGenerator, (IEnumerable<SyntaxTreeNode>)children)\n        {\n        }\n\n        public StatementBlock(params SyntaxTreeNode[] children)\n            : this(BlockCodeGenerator.Null, children)\n        {\n        }\n\n        public StatementBlock(IEnumerable<SyntaxTreeNode> children)\n            : this(BlockCodeGenerator.Null, children)\n        {\n        }\n    }\n\n    public class DirectiveBlock : Block\n    {\n        private const BlockType ThisBlockType = BlockType.Directive;\n\n        public DirectiveBlock(IBlockCodeGenerator codeGenerator, IEnumerable<SyntaxTreeNode> children)\n            : base(ThisBlockType, children, codeGenerator)\n        {\n        }\n\n        public DirectiveBlock(IBlockCodeGenerator codeGenerator, params SyntaxTreeNode[] children)\n            : this(codeGenerator, (IEnumerable<SyntaxTreeNode>)children)\n        {\n        }\n\n        public DirectiveBlock(params SyntaxTreeNode[] children)\n            : this(BlockCodeGenerator.Null, children)\n        {\n        }\n\n        public DirectiveBlock(IEnumerable<SyntaxTreeNode> children)\n            : this(BlockCodeGenerator.Null, children)\n        {\n        }\n    }\n\n    public class FunctionsBlock : Block\n    {\n        private const BlockType ThisBlockType = BlockType.Functions;\n\n        public FunctionsBlock(IBlockCodeGenerator codeGenerator, IEnumerable<SyntaxTreeNode> children)\n            : base(ThisBlockType, children, codeGenerator)\n        {\n        }\n\n        public FunctionsBlock(IBlockCodeGenerator codeGenerator, params SyntaxTreeNode[] children)\n            : this(codeGenerator, (IEnumerable<SyntaxTreeNode>)children)\n        {\n        }\n\n        public FunctionsBlock(params SyntaxTreeNode[] children)\n            : this(BlockCodeGenerator.Null, children)\n        {\n        }\n\n        public FunctionsBlock(IEnumerable<SyntaxTreeNode> children)\n            : this(BlockCodeGenerator.Null, children)\n        {\n        }\n    }\n\n    public class ExpressionBlock : Block\n    {\n        private const BlockType ThisBlockType = BlockType.Expression;\n\n        public ExpressionBlock(IBlockCodeGenerator codeGenerator, IEnumerable<SyntaxTreeNode> children)\n            : base(ThisBlockType, children, codeGenerator)\n        {\n        }\n\n        public ExpressionBlock(IBlockCodeGenerator codeGenerator, params SyntaxTreeNode[] children)\n            : this(codeGenerator, (IEnumerable<SyntaxTreeNode>)children)\n        {\n        }\n\n        public ExpressionBlock(params SyntaxTreeNode[] children)\n            : this(new ExpressionCodeGenerator(), children)\n        {\n        }\n\n        public ExpressionBlock(IEnumerable<SyntaxTreeNode> children)\n            : this(new ExpressionCodeGenerator(), children)\n        {\n        }\n    }\n\n    public class HelperBlock : Block\n    {\n        private const BlockType ThisBlockType = BlockType.Helper;\n\n        public HelperBlock(IBlockCodeGenerator codeGenerator, IEnumerable<SyntaxTreeNode> children)\n            : base(ThisBlockType, children, codeGenerator)\n        {\n        }\n\n        public HelperBlock(IBlockCodeGenerator codeGenerator, params SyntaxTreeNode[] children)\n            : this(codeGenerator, (IEnumerable<SyntaxTreeNode>)children)\n        {\n        }\n\n        public HelperBlock(params SyntaxTreeNode[] children)\n            : this(BlockCodeGenerator.Null, children)\n        {\n        }\n\n        public HelperBlock(IEnumerable<SyntaxTreeNode> children)\n            : this(BlockCodeGenerator.Null, children)\n        {\n        }\n    }\n\n    public class MarkupBlock : Block\n    {\n        private const BlockType ThisBlockType = BlockType.Markup;\n\n        public MarkupBlock(IBlockCodeGenerator codeGenerator, IEnumerable<SyntaxTreeNode> children)\n            : base(ThisBlockType, children, codeGenerator)\n        {\n        }\n\n        public MarkupBlock(IBlockCodeGenerator codeGenerator, params SyntaxTreeNode[] children)\n            : this(codeGenerator, (IEnumerable<SyntaxTreeNode>)children)\n        {\n        }\n\n        public MarkupBlock(params SyntaxTreeNode[] children)\n            : this(BlockCodeGenerator.Null, children)\n        {\n        }\n\n        public MarkupBlock(IEnumerable<SyntaxTreeNode> children)\n            : this(BlockCodeGenerator.Null, children)\n        {\n        }\n    }\n\n    public class SectionBlock : Block\n    {\n        private const BlockType ThisBlockType = BlockType.Section;\n\n        public SectionBlock(IBlockCodeGenerator codeGenerator, IEnumerable<SyntaxTreeNode> children)\n            : base(ThisBlockType, children, codeGenerator)\n        {\n        }\n\n        public SectionBlock(IBlockCodeGenerator codeGenerator, params SyntaxTreeNode[] children)\n            : this(codeGenerator, (IEnumerable<SyntaxTreeNode>)children)\n        {\n        }\n\n        public SectionBlock(params SyntaxTreeNode[] children)\n            : this(BlockCodeGenerator.Null, children)\n        {\n        }\n\n        public SectionBlock(IEnumerable<SyntaxTreeNode> children)\n            : this(BlockCodeGenerator.Null, children)\n        {\n        }\n    }\n\n    public class TemplateBlock : Block\n    {\n        private const BlockType ThisBlockType = BlockType.Template;\n\n        public TemplateBlock(IBlockCodeGenerator codeGenerator, IEnumerable<SyntaxTreeNode> children)\n            : base(ThisBlockType, children, codeGenerator)\n        {\n        }\n\n        public TemplateBlock(IBlockCodeGenerator codeGenerator, params SyntaxTreeNode[] children)\n            : this(codeGenerator, (IEnumerable<SyntaxTreeNode>)children)\n        {\n        }\n\n        public TemplateBlock(params SyntaxTreeNode[] children)\n            : this(new TemplateBlockCodeGenerator(), children)\n        {\n        }\n\n        public TemplateBlock(IEnumerable<SyntaxTreeNode> children)\n            : this(new TemplateBlockCodeGenerator(), children)\n        {\n        }\n    }\n\n    public class CommentBlock : Block\n    {\n        private const BlockType ThisBlockType = BlockType.Comment;\n\n        public CommentBlock(IBlockCodeGenerator codeGenerator, IEnumerable<SyntaxTreeNode> children)\n            : base(ThisBlockType, children, codeGenerator)\n        {\n        }\n\n        public CommentBlock(IBlockCodeGenerator codeGenerator, params SyntaxTreeNode[] children)\n            : this(codeGenerator, (IEnumerable<SyntaxTreeNode>)children)\n        {\n        }\n\n        public CommentBlock(params SyntaxTreeNode[] children)\n            : this(new RazorCommentCodeGenerator(), children)\n        {\n        }\n\n        public CommentBlock(IEnumerable<SyntaxTreeNode> children)\n            : this(new RazorCommentCodeGenerator(), children)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Framework/CodeParserTestBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.Razor.Test.Framework\n{\n    public abstract class CodeParserTestBase : ParserTestBase\n    {\n        protected abstract ISet<string> KeywordSet { get; }\n\n        protected override ParserBase SelectActiveParser(ParserBase codeParser, ParserBase markupParser)\n        {\n            return codeParser;\n        }\n\n        protected void ImplicitExpressionTest(string input, params RazorError[] errors)\n        {\n            ImplicitExpressionTest(input, AcceptedCharacters.NonWhiteSpace, errors);\n        }\n\n        protected void ImplicitExpressionTest(string input, AcceptedCharacters acceptedCharacters, params RazorError[] errors)\n        {\n            ImplicitExpressionTest(input, input, acceptedCharacters, errors);\n        }\n\n        protected void ImplicitExpressionTest(string input, string expected, params RazorError[] errors)\n        {\n            ImplicitExpressionTest(input, expected, AcceptedCharacters.NonWhiteSpace, errors);\n        }\n\n        protected override void SingleSpanBlockTest(string document, BlockType blockType, SpanKind spanType, AcceptedCharacters acceptedCharacters = AcceptedCharacters.Any)\n        {\n            SingleSpanBlockTest(document, blockType, spanType, acceptedCharacters, expectedError: null);\n        }\n\n        protected override void SingleSpanBlockTest(string document, string spanContent, BlockType blockType, SpanKind spanType, AcceptedCharacters acceptedCharacters = AcceptedCharacters.Any)\n        {\n            SingleSpanBlockTest(document, spanContent, blockType, spanType, acceptedCharacters, expectedErrors: null);\n        }\n\n        protected override void SingleSpanBlockTest(string document, BlockType blockType, SpanKind spanType, params RazorError[] expectedError)\n        {\n            SingleSpanBlockTest(document, document, blockType, spanType, expectedError);\n        }\n\n        protected override void SingleSpanBlockTest(string document, string spanContent, BlockType blockType, SpanKind spanType, params RazorError[] expectedErrors)\n        {\n            SingleSpanBlockTest(document, spanContent, blockType, spanType, AcceptedCharacters.Any, expectedErrors ?? new RazorError[0]);\n        }\n\n        protected override void SingleSpanBlockTest(string document, BlockType blockType, SpanKind spanType, AcceptedCharacters acceptedCharacters, params RazorError[] expectedError)\n        {\n            SingleSpanBlockTest(document, document, blockType, spanType, acceptedCharacters, expectedError);\n        }\n\n        protected override void SingleSpanBlockTest(string document, string spanContent, BlockType blockType, SpanKind spanType, AcceptedCharacters acceptedCharacters, params RazorError[] expectedErrors)\n        {\n            Block b = CreateSimpleBlockAndSpan(spanContent, blockType, spanType, acceptedCharacters);\n            ParseBlockTest(document, b, expectedErrors ?? new RazorError[0]);\n        }\n\n        protected void ImplicitExpressionTest(string input, string expected, AcceptedCharacters acceptedCharacters, params RazorError[] errors)\n        {\n            var factory = CreateSpanFactory();\n            ParseBlockTest(SyntaxConstants.TransitionString + input,\n                           new ExpressionBlock(\n                               factory.CodeTransition(),\n                               factory.Code(expected)\n                                   .AsImplicitExpression(KeywordSet)\n                                   .Accepts(acceptedCharacters)),\n                           errors);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Framework/CsHtmlCodeParserTestBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Razor.Parser;\n\nnamespace System.Web.Razor.Test.Framework\n{\n    public abstract class CsHtmlCodeParserTestBase : CodeParserTestBase\n    {\n        protected override ISet<string> KeywordSet\n        {\n            get { return CSharpCodeParser.DefaultKeywords; }\n        }\n\n        protected override SpanFactory CreateSpanFactory()\n        {\n            return SpanFactory.CreateCsHtml();\n        }\n\n        public override ParserBase CreateMarkupParser()\n        {\n            return new HtmlMarkupParser();\n        }\n\n        public override ParserBase CreateCodeParser()\n        {\n            return new CSharpCodeParser();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Framework/CsHtmlMarkupParserTestBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Razor.Parser;\n\nnamespace System.Web.Razor.Test.Framework\n{\n    public abstract class CsHtmlMarkupParserTestBase : MarkupParserTestBase\n    {\n        protected override ISet<string> KeywordSet\n        {\n            get { return CSharpCodeParser.DefaultKeywords; }\n        }\n\n        protected override SpanFactory CreateSpanFactory()\n        {\n            return SpanFactory.CreateCsHtml();\n        }\n\n        public override ParserBase CreateMarkupParser()\n        {\n            return new HtmlMarkupParser();\n        }\n\n        public override ParserBase CreateCodeParser()\n        {\n            return new CSharpCodeParser();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Framework/ErrorCollector.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Text;\nusing System.Web.Razor.Utils;\n\nnamespace System.Web.Razor.Test.Framework\n{\n    public class ErrorCollector\n    {\n        private StringBuilder _message = new StringBuilder();\n        private int _indent = 0;\n\n        public bool Success { get; private set; }\n\n        public string Message\n        {\n            get { return _message.ToString(); }\n        }\n\n        public ErrorCollector()\n        {\n            Success = true;\n        }\n\n        public void AddError(string msg, params object[] args)\n        {\n            Append(\"F\", msg, args);\n            Success = false;\n        }\n\n        public void AddMessage(string msg, params object[] args)\n        {\n            Append(\"P\", msg, args);\n        }\n\n        public IDisposable Indent()\n        {\n            _indent++;\n            return new DisposableAction(Unindent);\n        }\n\n        public void Unindent()\n        {\n            _indent--;\n        }\n\n        private void Append(string prefix, string msg, object[] args)\n        {\n            _message.Append(prefix);\n            _message.Append(\":\");\n            _message.Append(new String('\\t', _indent));\n            _message.AppendFormat(msg, args);\n            _message.AppendLine();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Framework/MarkupParserTestBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.Razor.Test.Framework\n{\n    public abstract class MarkupParserTestBase : CodeParserTestBase\n    {\n        protected override ParserBase SelectActiveParser(ParserBase codeParser, ParserBase markupParser)\n        {\n            return markupParser;\n        }\n\n        protected virtual void SingleSpanDocumentTest(string document, BlockType blockType, SpanKind spanType)\n        {\n            Block b = CreateSimpleBlockAndSpan(document, blockType, spanType);\n            ParseDocumentTest(document, b);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Framework/ParserTestBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n//#define PARSER_TRACE\n\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Text;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Framework\n{\n    public abstract class ParserTestBase\n    {\n        protected static Block IgnoreOutput = new IgnoreOutputBlock();\n\n        public SpanFactory Factory { get; private set; }\n\n        protected ParserTestBase()\n        {\n            Factory = CreateSpanFactory();\n        }\n\n        public abstract ParserBase CreateMarkupParser();\n        public abstract ParserBase CreateCodeParser();\n\n        protected abstract ParserBase SelectActiveParser(ParserBase codeParser, ParserBase markupParser);\n\n        public virtual ParserContext CreateParserContext(ITextDocument input, ParserBase codeParser, ParserBase markupParser)\n        {\n            return new ParserContext(input, codeParser, markupParser, SelectActiveParser(codeParser, markupParser));\n        }\n\n        protected abstract SpanFactory CreateSpanFactory();\n\n        protected virtual void ParseBlockTest(string document)\n        {\n            ParseBlockTest(document, null, false, new RazorError[0]);\n        }\n\n        protected virtual void ParseBlockTest(string document, bool designTimeParser)\n        {\n            ParseBlockTest(document, null, designTimeParser, new RazorError[0]);\n        }\n\n        protected virtual void ParseBlockTest(string document, params RazorError[] expectedErrors)\n        {\n            ParseBlockTest(document, false, expectedErrors);\n        }\n\n        protected virtual void ParseBlockTest(string document, bool designTimeParser, params RazorError[] expectedErrors)\n        {\n            ParseBlockTest(document, null, designTimeParser, expectedErrors);\n        }\n\n        protected virtual void ParseBlockTest(string document, Block expectedRoot)\n        {\n            ParseBlockTest(document, expectedRoot, false, null);\n        }\n\n        protected virtual void ParseBlockTest(string document, Block expectedRoot, bool designTimeParser)\n        {\n            ParseBlockTest(document, expectedRoot, designTimeParser, null);\n        }\n\n        protected virtual void ParseBlockTest(string document, Block expectedRoot, params RazorError[] expectedErrors)\n        {\n            ParseBlockTest(document, expectedRoot, false, expectedErrors);\n        }\n\n        protected virtual void ParseBlockTest(string document, Block expectedRoot, bool designTimeParser, params RazorError[] expectedErrors)\n        {\n            RunParseTest(document, parser => parser.ParseBlock, expectedRoot, (expectedErrors ?? new RazorError[0]).ToList(), designTimeParser);\n        }\n\n        protected virtual void SingleSpanBlockTest(string document, BlockType blockType, SpanKind spanType, AcceptedCharacters acceptedCharacters = AcceptedCharacters.Any)\n        {\n            SingleSpanBlockTest(document, blockType, spanType, acceptedCharacters, expectedError: null);\n        }\n\n        protected virtual void SingleSpanBlockTest(string document, string spanContent, BlockType blockType, SpanKind spanType, AcceptedCharacters acceptedCharacters = AcceptedCharacters.Any)\n        {\n            SingleSpanBlockTest(document, spanContent, blockType, spanType, acceptedCharacters, expectedErrors: null);\n        }\n\n        protected virtual void SingleSpanBlockTest(string document, BlockType blockType, SpanKind spanType, params RazorError[] expectedError)\n        {\n            SingleSpanBlockTest(document, document, blockType, spanType, expectedError);\n        }\n\n        protected virtual void SingleSpanBlockTest(string document, string spanContent, BlockType blockType, SpanKind spanType, params RazorError[] expectedErrors)\n        {\n            SingleSpanBlockTest(document, spanContent, blockType, spanType, AcceptedCharacters.Any, expectedErrors ?? new RazorError[0]);\n        }\n\n        protected virtual void SingleSpanBlockTest(string document, BlockType blockType, SpanKind spanType, AcceptedCharacters acceptedCharacters, params RazorError[] expectedError)\n        {\n            SingleSpanBlockTest(document, document, blockType, spanType, acceptedCharacters, expectedError);\n        }\n\n        protected virtual void SingleSpanBlockTest(string document, string spanContent, BlockType blockType, SpanKind spanType, AcceptedCharacters acceptedCharacters, params RazorError[] expectedErrors)\n        {\n            BlockBuilder builder = new BlockBuilder();\n            builder.Type = blockType;\n            ParseBlockTest(\n                document,\n                ConfigureAndAddSpanToBlock(\n                    builder,\n                    Factory.Span(spanType, spanContent, spanType == SpanKind.Markup)\n                           .Accepts(acceptedCharacters)),\n                expectedErrors ?? new RazorError[0]);\n        }\n\n        protected virtual void ParseDocumentTest(string document) {\n            ParseDocumentTest(document, null, false);\n        }\n\n        protected virtual void ParseDocumentTest(string document, Block expectedRoot) {\n            ParseDocumentTest(document, expectedRoot, false, null);\n        }\n\n        protected virtual void ParseDocumentTest(string document, Block expectedRoot, params RazorError[] expectedErrors) {\n            ParseDocumentTest(document, expectedRoot, false, expectedErrors);\n        }\n\n        protected virtual void ParseDocumentTest(string document, bool designTimeParser) {\n            ParseDocumentTest(document, null, designTimeParser);\n        }\n\n        protected virtual void ParseDocumentTest(string document, Block expectedRoot, bool designTimeParser) {\n            ParseDocumentTest(document, expectedRoot, designTimeParser, null);\n        }\n\n        protected virtual void ParseDocumentTest(string document, Block expectedRoot, bool designTimeParser, params RazorError[] expectedErrors) {\n            RunParseTest(document, parser => parser.ParseDocument, expectedRoot, expectedErrors, designTimeParser, parserSelector: c => c.MarkupParser);\n        }\n\n        protected virtual ParserResults ParseDocument(string document) {\n            return ParseDocument(document, designTimeParser: false);\n        }\n\n        protected virtual ParserResults ParseDocument(string document, bool designTimeParser) {\n            return RunParse(document, parser => parser.ParseDocument, designTimeParser, parserSelector: c => c.MarkupParser);\n        }\n\n        protected virtual ParserResults ParseBlock(string document) {\n            return ParseBlock(document, designTimeParser: false);\n        }\n\n        protected virtual ParserResults ParseBlock(string document, bool designTimeParser) {\n            return RunParse(document, parser => parser.ParseBlock, designTimeParser);\n        }\n\n        protected virtual ParserResults RunParse(string document, Func<ParserBase, Action> parserActionSelector, bool designTimeParser, Func<ParserContext, ParserBase> parserSelector = null)\n        {\n            parserSelector = parserSelector ?? (c => c.ActiveParser);\n\n            // Create the source\n            ParserResults results = null;\n            using (SeekableTextReader reader = new SeekableTextReader(document))\n            {\n                try\n                {\n                    ParserBase codeParser = CreateCodeParser();\n                    ParserBase markupParser = CreateMarkupParser();\n                    ParserContext context = CreateParserContext(reader, codeParser, markupParser);\n                    context.DesignTimeMode = designTimeParser;\n\n                    codeParser.Context = context;\n                    markupParser.Context = context;\n\n                    // Run the parser\n                    parserActionSelector(parserSelector(context))();\n                    results = context.CompleteParse();\n                }\n                finally\n                {\n                    if (results != null && results.Document != null)\n                    {\n                        WriteTraceLine(String.Empty);\n                        WriteTraceLine(\"Actual Parse Tree:\");\n                        WriteNode(0, results.Document);\n                    }\n                }\n            }\n            return results;\n        }\n\n        protected virtual void RunParseTest(string document, Func<ParserBase, Action> parserActionSelector, Block expectedRoot, IList<RazorError> expectedErrors, bool designTimeParser, Func<ParserContext, ParserBase> parserSelector = null)\n        {\n            // Create the source\n            ParserResults results = RunParse(document, parserActionSelector, designTimeParser, parserSelector);\n\n            // Evaluate the results\n            if (!ReferenceEquals(expectedRoot, IgnoreOutput))\n            {\n                EvaluateResults(results, expectedRoot, expectedErrors);\n            }\n        }\n\n        [Conditional(\"PARSER_TRACE\")]\n        private void WriteNode(int indent, SyntaxTreeNode node)\n        {\n            string content = node.ToString().Replace(\"\\r\", \"\\\\r\")\n                .Replace(\"\\n\", \"\\\\n\")\n                .Replace(\"{\", \"{{\")\n                .Replace(\"}\", \"}}\");\n            if (indent > 0)\n            {\n                content = new String('.', indent * 2) + content;\n            }\n            WriteTraceLine(content);\n            Block block = node as Block;\n            if (block != null)\n            {\n                foreach (SyntaxTreeNode child in block.Children)\n                {\n                    WriteNode(indent + 1, child);\n                }\n            }\n        }\n\n        public static void EvaluateResults(ParserResults results, Block expectedRoot)\n        {\n            EvaluateResults(results, expectedRoot, null);\n        }\n\n        public static void EvaluateResults(ParserResults results, Block expectedRoot, IList<RazorError> expectedErrors)\n        {\n            EvaluateParseTree(results.Document, expectedRoot);\n            EvaluateRazorErrors(results.ParserErrors, expectedErrors);\n        }\n\n        public static void EvaluateParseTree(Block actualRoot, Block expectedRoot)\n        {\n            // Evaluate the result\n            ErrorCollector collector = new ErrorCollector();\n\n            // Link all the nodes\n            expectedRoot.LinkNodes();\n\n            if (expectedRoot == null)\n            {\n                Assert.Null(actualRoot);\n            }\n            else\n            {\n                Assert.NotNull(actualRoot);\n                EvaluateSyntaxTreeNode(collector, actualRoot, expectedRoot);\n                if (collector.Success)\n                {\n                    WriteTraceLine(\"Parse Tree Validation Succeeded:\\r\\n{0}\", collector.Message);\n                }\n                else\n                {\n                    Assert.True(false, String.Format(\"\\r\\n{0}\", collector.Message));\n                }\n            }\n        }\n\n        private static void EvaluateSyntaxTreeNode(ErrorCollector collector, SyntaxTreeNode actual, SyntaxTreeNode expected)\n        {\n            if (actual == null)\n            {\n                AddNullActualError(collector, actual, expected);\n            }\n\n            if (actual.IsBlock != expected.IsBlock)\n            {\n                AddMismatchError(collector, actual, expected);\n            }\n            else\n            {\n                if (expected.IsBlock)\n                {\n                    EvaluateBlock(collector, (Block)actual, (Block)expected);\n                }\n                else\n                {\n                    EvaluateSpan(collector, (Span)actual, (Span)expected);\n                }\n            }\n        }\n\n        private static void EvaluateSpan(ErrorCollector collector, Span actual, Span expected)\n        {\n            if (!Equals(expected, actual))\n            {\n                AddMismatchError(collector, actual, expected);\n            }\n            else\n            {\n                AddPassedMessage(collector, expected);\n            }\n        }\n\n        private static void EvaluateBlock(ErrorCollector collector, Block actual, Block expected)\n        {\n            if (actual.Type != expected.Type || !expected.CodeGenerator.Equals(actual.CodeGenerator))\n            {\n                AddMismatchError(collector, actual, expected);\n            }\n            else\n            {\n                AddPassedMessage(collector, expected);\n                using (collector.Indent())\n                {\n                    IEnumerator<SyntaxTreeNode> expectedNodes = expected.Children.GetEnumerator();\n                    IEnumerator<SyntaxTreeNode> actualNodes = actual.Children.GetEnumerator();\n                    while (expectedNodes.MoveNext())\n                    {\n                        if (!actualNodes.MoveNext())\n                        {\n                            collector.AddError(\"{0} - FAILED :: No more elements at this node\", expectedNodes.Current);\n                        }\n                        else\n                        {\n                            EvaluateSyntaxTreeNode(collector, actualNodes.Current, expectedNodes.Current);\n                        }\n                    }\n                    while (actualNodes.MoveNext())\n                    {\n                        collector.AddError(\"End of Node - FAILED :: Found Node: {0}\", actualNodes.Current);\n                    }\n                }\n            }\n        }\n\n        private static void AddPassedMessage(ErrorCollector collector, SyntaxTreeNode expected)\n        {\n            collector.AddMessage(\"{0} - PASSED\", expected);\n        }\n\n        private static void AddMismatchError(ErrorCollector collector, SyntaxTreeNode actual, SyntaxTreeNode expected)\n        {\n            collector.AddError(\"{0} - FAILED :: Actual: {1}\", expected, actual);\n        }\n\n        private static void AddNullActualError(ErrorCollector collector, SyntaxTreeNode actual, SyntaxTreeNode expected)\n        {\n            collector.AddError(\"{0} - FAILED :: Actual: << Null >>\", expected);\n        }\n\n        public static void EvaluateRazorErrors(IList<RazorError> actualErrors, IList<RazorError> expectedErrors)\n        {\n            // Evaluate the errors\n            if (expectedErrors == null || expectedErrors.Count == 0)\n            {\n                Assert.True(actualErrors.Count == 0,\n                            String.Format(\"Expected that no errors would be raised, but the following errors were:\\r\\n{0}\", FormatErrors(actualErrors)));\n            }\n            else\n            {\n                Assert.True(expectedErrors.Count == actualErrors.Count,\n                            String.Format(\"Expected that {0} errors would be raised, but {1} errors were.\\r\\nExpected Errors: \\r\\n{2}\\r\\nActual Errors: \\r\\n{3}\",\n                                          expectedErrors.Count,\n                                          actualErrors.Count,\n                                          FormatErrors(expectedErrors),\n                                          FormatErrors(actualErrors)));\n                Assert.Equal(expectedErrors.ToArray(), actualErrors.ToArray());\n            }\n            WriteTraceLine(\"Expected Errors were raised:\\r\\n{0}\", FormatErrors(expectedErrors));\n        }\n\n        public static string FormatErrors(IList<RazorError> errors)\n        {\n            if (errors == null)\n            {\n                return \"\\t<< No Errors >>\";\n            }\n\n            StringBuilder builder = new StringBuilder();\n            foreach (RazorError err in errors)\n            {\n                builder.AppendFormat(\"\\t{0}\", err);\n                builder.AppendLine();\n            }\n            return builder.ToString();\n        }\n\n        [Conditional(\"PARSER_TRACE\")]\n        private static void WriteTraceLine(string format, params object[] args)\n        {\n            Trace.WriteLine(String.Format(format, args));\n        }\n\n        protected virtual Block CreateSimpleBlockAndSpan(string spanContent, BlockType blockType, SpanKind spanType, AcceptedCharacters acceptedCharacters = AcceptedCharacters.Any)\n        {\n            SpanConstructor span = Factory.Span(spanType, spanContent, spanType == SpanKind.Markup).Accepts(acceptedCharacters);\n            BlockBuilder b = new BlockBuilder()\n            {\n                Type = blockType\n            };\n            return ConfigureAndAddSpanToBlock(b, span);\n        }\n\n        protected virtual Block ConfigureAndAddSpanToBlock(BlockBuilder block, SpanConstructor span)\n        {\n            switch (block.Type)\n            {\n                case BlockType.Markup:\n                    span.With(new MarkupCodeGenerator());\n                    break;\n                case BlockType.Statement:\n                    span.With(new StatementCodeGenerator());\n                    break;\n                case BlockType.Expression:\n                    block.CodeGenerator = new ExpressionCodeGenerator();\n                    span.With(new ExpressionCodeGenerator());\n                    break;\n            }\n            block.Children.Add(span);\n            return block.Build();\n        }\n\n        private class IgnoreOutputBlock : Block\n        {\n            public IgnoreOutputBlock() : base(BlockType.Template, Enumerable.Empty<SyntaxTreeNode>(), null) { }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Framework/RawTextSymbol.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.Razor.Test.Framework\n{\n    internal class RawTextSymbol : ISymbol\n    {\n        public SourceLocation Start { get; private set; }\n        public string Content { get; private set; }\n\n        public RawTextSymbol(SourceLocation start, string content)\n        {\n            if (content == null)\n            {\n                throw new ArgumentNullException(\"content\");\n            }\n\n            Start = start;\n            Content = content;\n        }\n\n        public override bool Equals(object obj)\n        {\n            RawTextSymbol other = obj as RawTextSymbol;\n            return Equals(Start, other.Start) && Equals(Content, other.Content);\n        }\n\n        internal bool EquivalentTo(ISymbol sym)\n        {\n            return Equals(Start, sym.Start) && Equals(Content, sym.Content);\n        }\n\n        public override int GetHashCode()\n        {\n            return HashCodeCombiner.Start()\n                .Add(Start)\n                .Add(Content)\n                .CombinedHash;\n        }\n\n        public void OffsetStart(SourceLocation documentStart)\n        {\n            Start = documentStart + Start;\n        }\n\n        public void ChangeStart(SourceLocation newStart)\n        {\n            Start = newStart;\n        }\n\n        public override string ToString()\n        {\n            return String.Format(CultureInfo.InvariantCulture, \"{0} RAW - [{1}]\", Start, Content);\n        }\n\n        internal void CalculateStart(Span prev)\n        {\n            if (prev == null)\n            {\n                Start = SourceLocation.Zero;\n            }\n            else\n            {\n                Start = new SourceLocationTracker(prev.Start).UpdateLocation(prev.Content).CurrentLocation;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Framework/TestSpanBuilder.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.Razor.Editor;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Test.Framework\n{\n    public static class SpanFactoryExtensions\n    {\n        public static UnclassifiedCodeSpanConstructor EmptyCSharp(this SpanFactory self)\n        {\n            return new UnclassifiedCodeSpanConstructor(\n                self.Span(SpanKind.Code, new CSharpSymbol(self.LocationTracker.CurrentLocation, String.Empty, CSharpSymbolType.Unknown)));\n        }\n\n        public static UnclassifiedCodeSpanConstructor EmptyVB(this SpanFactory self)\n        {\n            return new UnclassifiedCodeSpanConstructor(\n                self.Span(SpanKind.Code, new VBSymbol(self.LocationTracker.CurrentLocation, String.Empty, VBSymbolType.Unknown)));\n        }\n\n        public static SpanConstructor EmptyHtml(this SpanFactory self)\n        {\n            return self.Span(SpanKind.Markup, new HtmlSymbol(self.LocationTracker.CurrentLocation, String.Empty, HtmlSymbolType.Unknown))\n                .With(new MarkupCodeGenerator());\n        }\n\n        public static UnclassifiedCodeSpanConstructor Code(this SpanFactory self, string content)\n        {\n            return new UnclassifiedCodeSpanConstructor(\n                self.Span(SpanKind.Code, content, markup: false));\n        }\n\n        public static SpanConstructor CodeTransition(this SpanFactory self)\n        {\n            return self.Span(SpanKind.Transition, SyntaxConstants.TransitionString, markup: false).Accepts(AcceptedCharacters.None);\n        }\n\n        public static SpanConstructor CodeTransition(this SpanFactory self, string content)\n        {\n            return self.Span(SpanKind.Transition, content, markup: false).Accepts(AcceptedCharacters.None);\n        }\n\n        public static SpanConstructor CodeTransition(this SpanFactory self, CSharpSymbolType type)\n        {\n            return self.Span(SpanKind.Transition, SyntaxConstants.TransitionString, type).Accepts(AcceptedCharacters.None);\n        }\n\n        public static SpanConstructor CodeTransition(this SpanFactory self, string content, CSharpSymbolType type)\n        {\n            return self.Span(SpanKind.Transition, content, type).Accepts(AcceptedCharacters.None);\n        }\n\n        public static SpanConstructor CodeTransition(this SpanFactory self, VBSymbolType type)\n        {\n            return self.Span(SpanKind.Transition, SyntaxConstants.TransitionString, type).Accepts(AcceptedCharacters.None);\n        }\n\n        public static SpanConstructor CodeTransition(this SpanFactory self, string content, VBSymbolType type)\n        {\n            return self.Span(SpanKind.Transition, content, type).Accepts(AcceptedCharacters.None);\n        }\n\n        public static SpanConstructor MarkupTransition(this SpanFactory self)\n        {\n            return self.Span(SpanKind.Transition, SyntaxConstants.TransitionString, markup: true).Accepts(AcceptedCharacters.None);\n        }\n\n        public static SpanConstructor MarkupTransition(this SpanFactory self, string content)\n        {\n            return self.Span(SpanKind.Transition, content, markup: true).Accepts(AcceptedCharacters.None);\n        }\n\n        public static SpanConstructor MarkupTransition(this SpanFactory self, HtmlSymbolType type)\n        {\n            return self.Span(SpanKind.Transition, SyntaxConstants.TransitionString, type).Accepts(AcceptedCharacters.None);\n        }\n\n        public static SpanConstructor MarkupTransition(this SpanFactory self, string content, HtmlSymbolType type)\n        {\n            return self.Span(SpanKind.Transition, content, type).Accepts(AcceptedCharacters.None);\n        }\n\n        public static SpanConstructor MetaCode(this SpanFactory self, string content)\n        {\n            return self.Span(SpanKind.MetaCode, content, markup: false);\n        }\n\n        public static SpanConstructor MetaCode(this SpanFactory self, string content, CSharpSymbolType type)\n        {\n            return self.Span(SpanKind.MetaCode, content, type);\n        }\n\n        public static SpanConstructor MetaCode(this SpanFactory self, string content, VBSymbolType type)\n        {\n            return self.Span(SpanKind.MetaCode, content, type);\n        }\n\n        public static SpanConstructor MetaMarkup(this SpanFactory self, string content)\n        {\n            return self.Span(SpanKind.MetaCode, content, markup: true);\n        }\n\n        public static SpanConstructor MetaMarkup(this SpanFactory self, string content, HtmlSymbolType type)\n        {\n            return self.Span(SpanKind.MetaCode, content, type);\n        }\n\n        public static SpanConstructor Comment(this SpanFactory self, string content, CSharpSymbolType type)\n        {\n            return self.Span(SpanKind.Comment, content, type);\n        }\n\n        public static SpanConstructor Comment(this SpanFactory self, string content, VBSymbolType type)\n        {\n            return self.Span(SpanKind.Comment, content, type);\n        }\n\n        public static SpanConstructor Comment(this SpanFactory self, string content, HtmlSymbolType type)\n        {\n            return self.Span(SpanKind.Comment, content, type);\n        }\n\n        public static SpanConstructor Markup(this SpanFactory self, string content)\n        {\n            return self.Span(SpanKind.Markup, content, markup: true).With(new MarkupCodeGenerator());\n        }\n\n        public static SpanConstructor Markup(this SpanFactory self, params string[] content)\n        {\n            return self.Span(SpanKind.Markup, content, markup: true).With(new MarkupCodeGenerator());\n        }\n\n        public static SourceLocation GetLocationAndAdvance(this SourceLocationTracker self, string content)\n        {\n            SourceLocation ret = self.CurrentLocation;\n            self.UpdateLocation(content);\n            return ret;\n        }\n    }\n\n    public class SpanFactory\n    {\n        public Func<ITextDocument, ITokenizer> MarkupTokenizerFactory { get; set; }\n        public Func<ITextDocument, ITokenizer> CodeTokenizerFactory { get; set; }\n        public SourceLocationTracker LocationTracker { get; private set; }\n\n        public static SpanFactory CreateCsHtml()\n        {\n            return new SpanFactory()\n            {\n                MarkupTokenizerFactory = doc => new HtmlTokenizer(doc),\n                CodeTokenizerFactory = doc => new CSharpTokenizer(doc)\n            };\n        }\n\n        public static SpanFactory CreateVbHtml()\n        {\n            return new SpanFactory()\n            {\n                MarkupTokenizerFactory = doc => new HtmlTokenizer(doc),\n                CodeTokenizerFactory = doc => new VBTokenizer(doc)\n            };\n        }\n\n        public SpanFactory()\n        {\n            LocationTracker = new SourceLocationTracker();\n        }\n\n        public SpanConstructor Span(SpanKind kind, string content, CSharpSymbolType type)\n        {\n            return CreateSymbolSpan(kind, content, st => new CSharpSymbol(st, content, type));\n        }\n\n        public SpanConstructor Span(SpanKind kind, string content, VBSymbolType type)\n        {\n            return CreateSymbolSpan(kind, content, st => new VBSymbol(st, content, type));\n        }\n\n        public SpanConstructor Span(SpanKind kind, string content, HtmlSymbolType type)\n        {\n            return CreateSymbolSpan(kind, content, st => new HtmlSymbol(st, content, type));\n        }\n\n        public SpanConstructor Span(SpanKind kind, string content, bool markup)\n        {\n            return new SpanConstructor(kind, Tokenize(new[] { content }, markup));\n        }\n\n        public SpanConstructor Span(SpanKind kind, string[] content, bool markup)\n        {\n            return new SpanConstructor(kind, Tokenize(content, markup));\n        }\n\n        public SpanConstructor Span(SpanKind kind, params ISymbol[] symbols)\n        {\n            return new SpanConstructor(kind, symbols);\n        }\n\n        private SpanConstructor CreateSymbolSpan(SpanKind kind, string content, Func<SourceLocation, ISymbol> ctor)\n        {\n            SourceLocation start = LocationTracker.CurrentLocation;\n            LocationTracker.UpdateLocation(content);\n            return new SpanConstructor(kind, new[] { ctor(start) });\n        }\n\n        public void Reset()\n        {\n            LocationTracker.CurrentLocation = SourceLocation.Zero;\n        }\n\n        private IEnumerable<ISymbol> Tokenize(IEnumerable<string> contentFragments, bool markup)\n        {\n            return contentFragments.SelectMany(fragment => Tokenize(fragment, markup));\n        }\n\n        private IEnumerable<ISymbol> Tokenize(string content, bool markup)\n        {\n            ITokenizer tok = MakeTokenizer(markup, new SeekableTextReader(content));\n            ISymbol sym;\n            ISymbol last = null;\n            while ((sym = tok.NextSymbol()) != null)\n            {\n                OffsetStart(sym, LocationTracker.CurrentLocation);\n                last = sym;\n                yield return sym;\n            }\n            LocationTracker.UpdateLocation(content);\n        }\n\n        private ITokenizer MakeTokenizer(bool markup, SeekableTextReader seekableTextReader)\n        {\n            if (markup)\n            {\n                return MarkupTokenizerFactory(seekableTextReader);\n            }\n            else\n            {\n                return CodeTokenizerFactory(seekableTextReader);\n            }\n        }\n\n        private void OffsetStart(ISymbol sym, SourceLocation sourceLocation)\n        {\n            sym.OffsetStart(sourceLocation);\n        }\n    }\n\n    public static class SpanConstructorExtensions\n    {\n        public static SpanConstructor Accepts(this SpanConstructor self, AcceptedCharacters accepted)\n        {\n            return self.With(eh => eh.AcceptedCharacters = accepted);\n        }\n\n        public static SpanConstructor AutoCompleteWith(this SpanConstructor self, string autoCompleteString)\n        {\n            return AutoCompleteWith(self, autoCompleteString, atEndOfSpan: false);\n        }\n\n        public static SpanConstructor AutoCompleteWith(this SpanConstructor self, string autoCompleteString, bool atEndOfSpan)\n        {\n            return self.With(new AutoCompleteEditHandler(SpanConstructor.TestTokenizer) { AutoCompleteString = autoCompleteString, AutoCompleteAtEndOfSpan = atEndOfSpan });\n        }\n\n        public static SpanConstructor WithEditorHints(this SpanConstructor self, EditorHints hints)\n        {\n            return self.With(eh => eh.EditorHints = hints);\n        }\n    }\n\n    public class UnclassifiedCodeSpanConstructor\n    {\n        SpanConstructor _self;\n\n        public UnclassifiedCodeSpanConstructor(SpanConstructor self)\n        {\n            _self = self;\n        }\n\n        public SpanConstructor AsMetaCode()\n        {\n            _self.Builder.Kind = SpanKind.MetaCode;\n            return _self;\n        }\n\n        public SpanConstructor AsStatement()\n        {\n            return _self.With(new StatementCodeGenerator());\n        }\n\n        public SpanConstructor AsExpression()\n        {\n            return _self.With(new ExpressionCodeGenerator());\n        }\n\n        public SpanConstructor AsImplicitExpression(ISet<string> keywords)\n        {\n            return AsImplicitExpression(keywords, acceptTrailingDot: false);\n        }\n\n        public SpanConstructor AsImplicitExpression(ISet<string> keywords, bool acceptTrailingDot)\n        {\n            return _self.With(new ImplicitExpressionEditHandler(SpanConstructor.TestTokenizer, keywords, acceptTrailingDot))\n                .With(new ExpressionCodeGenerator());\n        }\n\n        public SpanConstructor AsFunctionsBody()\n        {\n            return _self.With(new TypeMemberCodeGenerator());\n        }\n\n        public SpanConstructor AsNamespaceImport(string ns, int namespaceKeywordLength)\n        {\n            return _self.With(new AddImportCodeGenerator(ns, namespaceKeywordLength));\n        }\n\n        public SpanConstructor Hidden()\n        {\n            return _self.With(SpanCodeGenerator.Null);\n        }\n\n        public SpanConstructor AsBaseType(string baseType)\n        {\n            return _self.With(new SetBaseTypeCodeGenerator(baseType));\n        }\n\n        public SpanConstructor AsRazorDirectiveAttribute(string key, string value)\n        {\n            return _self.With(new RazorDirectiveAttributeCodeGenerator(key, value));\n        }\n\n        public SpanConstructor As(ISpanCodeGenerator codeGenerator)\n        {\n            return _self.With(codeGenerator);\n        }\n    }\n\n    public class SpanConstructor\n    {\n        public SpanBuilder Builder { get; private set; }\n\n        internal static IEnumerable<ISymbol> TestTokenizer(string str)\n        {\n            yield return new RawTextSymbol(SourceLocation.Zero, str);\n        }\n\n        public SpanConstructor(SpanKind kind, IEnumerable<ISymbol> symbols)\n        {\n            Builder = new SpanBuilder();\n            Builder.Kind = kind;\n            Builder.EditHandler = SpanEditHandler.CreateDefault(TestTokenizer);\n            foreach (ISymbol sym in symbols)\n            {\n                Builder.Accept(sym);\n            }\n        }\n\n        private Span Build()\n        {\n            return Builder.Build();\n        }\n\n        public SpanConstructor With(ISpanCodeGenerator generator)\n        {\n            Builder.CodeGenerator = generator;\n            return this;\n        }\n\n        public SpanConstructor With(SpanEditHandler handler)\n        {\n            Builder.EditHandler = handler;\n            return this;\n        }\n\n        public SpanConstructor With(Action<ISpanCodeGenerator> generatorConfigurer)\n        {\n            generatorConfigurer(Builder.CodeGenerator);\n            return this;\n        }\n\n        public SpanConstructor With(Action<SpanEditHandler> handlerConfigurer)\n        {\n            handlerConfigurer(Builder.EditHandler);\n            return this;\n        }\n\n        public static implicit operator Span(SpanConstructor self)\n        {\n            return self.Build();\n        }\n\n        public SpanConstructor Hidden()\n        {\n            Builder.CodeGenerator = SpanCodeGenerator.Null;\n            return this;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Framework/VBHtmlCodeParserTestBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Razor.Parser;\n\nnamespace System.Web.Razor.Test.Framework\n{\n    public abstract class VBHtmlCodeParserTestBase : CodeParserTestBase\n    {\n        protected override ISet<string> KeywordSet\n        {\n            get { return VBCodeParser.DefaultKeywords; }\n        }\n\n        protected override SpanFactory CreateSpanFactory()\n        {\n            return SpanFactory.CreateVbHtml();\n        }\n\n        public override ParserBase CreateMarkupParser()\n        {\n            return new HtmlMarkupParser();\n        }\n\n        public override ParserBase CreateCodeParser()\n        {\n            return new VBCodeParser();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Framework/VBHtmlMarkupParserTestBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Razor.Parser;\n\nnamespace System.Web.Razor.Test.Framework\n{\n    public abstract class VBHtmlMarkupParserTestBase : MarkupParserTestBase\n    {\n        protected override ISet<string> KeywordSet\n        {\n            get { return VBCodeParser.DefaultKeywords; }\n        }\n\n        protected override SpanFactory CreateSpanFactory()\n        {\n            return SpanFactory.CreateVbHtml();\n        }\n\n        public override ParserBase CreateMarkupParser()\n        {\n            return new HtmlMarkupParser();\n        }\n\n        public override ParserBase CreateCodeParser()\n        {\n            return new VBCodeParser();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Generator/CSharpRazorCodeGeneratorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Generator\n{\n    public class CSharpRazorCodeGeneratorTest : RazorCodeGeneratorTest<CSharpRazorCodeLanguage>\n    {\n        protected override string FileExtension\n        {\n            get { return \"cshtml\"; }\n        }\n\n        protected override string LanguageName\n        {\n            get { return \"CS\"; }\n        }\n\n        protected override string BaselineExtension\n        {\n            get { return \"cs\"; }\n        }\n\n        private const string TestPhysicalPath = @\"C:\\Bar.cshtml\";\n        private const string TestVirtualPath = \"~/Foo/Bar.cshtml\";\n\n        [Fact]\n        public void ConstructorRequiresNonNullClassName()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(() => new CSharpRazorCodeGenerator(null, TestRootNamespaceName, TestPhysicalPath, CreateHost()), \"className\");\n        }\n\n        [Fact]\n        public void ConstructorRequiresNonEmptyClassName()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(() => new CSharpRazorCodeGenerator(String.Empty, TestRootNamespaceName, TestPhysicalPath, CreateHost()), \"className\");\n        }\n\n        [Fact]\n        public void ConstructorRequiresNonNullRootNamespaceName()\n        {\n            Assert.ThrowsArgumentNull(() => new CSharpRazorCodeGenerator(\"Foo\", null, TestPhysicalPath, CreateHost()), \"rootNamespaceName\");\n        }\n\n        [Fact]\n        public void ConstructorAllowsEmptyRootNamespaceName()\n        {\n            new CSharpRazorCodeGenerator(\"Foo\", String.Empty, TestPhysicalPath, CreateHost());\n        }\n\n        [Fact]\n        public void ConstructorRequiresNonNullHost()\n        {\n            Assert.ThrowsArgumentNull(() => new CSharpRazorCodeGenerator(\"Foo\", TestRootNamespaceName, TestPhysicalPath, null), \"host\");\n        }\n\n        [Theory]\n        [InlineData(\"NestedCodeBlocks\")]\n        [InlineData(\"CodeBlock\")]\n        [InlineData(\"ExplicitExpression\")]\n        [InlineData(\"MarkupInCodeBlock\")]\n        [InlineData(\"Blocks\")]\n        [InlineData(\"ImplicitExpression\")]\n        [InlineData(\"Imports\")]\n        [InlineData(\"ExpressionsInCode\")]\n        [InlineData(\"FunctionsBlock\")]\n        [InlineData(\"FunctionsBlock_Tabs\")]\n        [InlineData(\"Templates\")]\n        [InlineData(\"Sections\")]\n        [InlineData(\"RazorComments\")]\n        [InlineData(\"Helpers\")]\n        [InlineData(\"HelpersMissingCloseParen\")]\n        [InlineData(\"HelpersMissingOpenBrace\")]\n        [InlineData(\"HelpersMissingOpenParen\")]\n        [InlineData(\"NestedHelpers\")]\n        [InlineData(\"InlineBlocks\")]\n        [InlineData(\"LayoutDirective\")]\n        [InlineData(\"ConditionalAttributes\")]\n        [InlineData(\"ResolveUrl\")]\n        public void CSharpCodeGeneratorCorrectlyGeneratesRunTimeCode(string testType)\n        {\n            RunTest(testType);\n        }\n\n        [Fact]\n        public void CSharpCodeGeneratorCorrectlyGeneratesMappingsForSimpleUnspacedIf()\n        {\n            RunTest(\"SimpleUnspacedIf\",\n                    \"SimpleUnspacedIf.DesignTime.Tabs\",\n                    designTimeMode: true,\n                    tabTest: TabTest.Tabs,\n                    expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n                    {\n                        /* 01 */ new GeneratedCodeMapping(1, 2, 1, 15),\n                        /* 02 */ new GeneratedCodeMapping(3, 13, 7, 3),\n                    });\n        }\n\n        [Fact]\n        public void CSharpCodeGeneratorCorrectlyGeneratesMappingsForRazorCommentsAtDesignTime()\n        {\n            RunTest(\"RazorComments\", \"RazorComments.DesignTime\", designTimeMode: true, tabTest: TabTest.NoTabs, expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(4, 3, 3, 6),\n                /* 02 */ new GeneratedCodeMapping(5, 40, 39, 22),\n                /* 03 */ new GeneratedCodeMapping(6, 50, 49, 58),\n                /* 04 */ new GeneratedCodeMapping(12, 3, 3, 24),\n                /* 05 */ new GeneratedCodeMapping(13, 46, 46, 3),\n                /* 06 */ new GeneratedCodeMapping(15, 3, 7, 1),\n                /* 07 */ new GeneratedCodeMapping(15, 8, 8, 1)\n            });\n        }\n\n        [Fact]\n        public void CSharpCodeGeneratorCorrectlyGenerateMappingForOpenedCurlyIf()\n        {\n            OpenedIf(withTabs: true);\n        }\n\n        [Fact]\n        public void CSharpCodeGeneratorCorrectlyGenerateMappingForOpenedCurlyIfSpaces()\n        {\n            OpenedIf(withTabs: false);\n        }\n\n        private void OpenedIf(bool withTabs)\n        {\n            int tabOffsetForMapping = 0;\n\n            // where the test is running with tabs, the offset into the CS buffer changes for the whitespace mapping\n            // with spaces we get 7xspace -> offset of 8 (column = offset+1)\n            // with tabs we get tab + 3 spaces -> offset of 4 chars + 1 = 5\n            if (withTabs)\n            {\n                tabOffsetForMapping = 3;\n            }\n\n            RunTest(\"OpenedIf\",\n                \"OpenedIf.DesignTime\" + (withTabs ? \".Tabs\" : \"\"),\n                    designTimeMode: true,\n                    tabTest: withTabs ? TabTest.Tabs : TabTest.NoTabs,\n                    spans: new TestSpan[]\n            {\n                new TestSpan(SpanKind.Markup, 0, 16),\n                new TestSpan(SpanKind.Transition, 16, 17),\n                new TestSpan(SpanKind.Code, 17, 31),\n                new TestSpan(SpanKind.Markup, 31, 38),\n                new TestSpan(SpanKind.Code, 38, 40),\n                new TestSpan(SpanKind.Markup, 40, 47),\n                new TestSpan(SpanKind.Code, 47, 47),\n            },\n            expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(3, 2, 1, 14),\n                /* 02 */ new GeneratedCodeMapping(4, 8, 8 - tabOffsetForMapping, 2),\n                /* 03 */ new GeneratedCodeMapping(5, 8, 8 - tabOffsetForMapping, 0),\n            });\n        }\n\n        [Fact]\n        public void CSharpCodeGeneratorCorrectlyGeneratesImportStatementsAtDesignTime()\n        {\n            RunTest(\"Imports\", \"Imports.DesignTime\", designTimeMode: true, tabTest: TabTest.NoTabs, expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(1, 2, 1, 15),\n                /* 02 */ new GeneratedCodeMapping(2, 2, 1, 32),\n                /* 03 */ new GeneratedCodeMapping(3, 2, 1, 12),\n                /* 04 */ new GeneratedCodeMapping(5, 30, 30, 21),\n                /* 05 */ new GeneratedCodeMapping(6, 36, 36, 20),\n            });\n        }\n\n        [Fact]\n        public void CSharpCodeGeneratorCorrectlyGeneratesFunctionsBlocksAtDesignTime()\n        {\n            RunTest(\"FunctionsBlock\",\n                    \"FunctionsBlock.DesignTime\",\n                    designTimeMode: true,\n                    tabTest: TabTest.NoTabs,\n                    expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(1, 13, 13, 4),\n                /* 02 */ new GeneratedCodeMapping(5, 13, 13, 104),\n                /* 03 */ new GeneratedCodeMapping(12, 26, 26, 11)\n            });\n        }\n\n        [Fact]\n        public void CSharpCodeGeneratorCorrectlyGeneratesFunctionsBlocksAtDesignTimeTabs()\n        {\n            RunTest(\"FunctionsBlock\",\n                    \"FunctionsBlock.DesignTime\" + \".Tabs\",\n                    designTimeMode: true,\n                    tabTest: TabTest.Tabs,\n                    expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(1, 13, 4, 4),\n                /* 02 */ new GeneratedCodeMapping(5, 13, 4, 104),\n                /* 03 */ new GeneratedCodeMapping(12, 26, 14, 11)\n            });\n        }\n\n        [Fact]\n        public void CSharpCodeGeneratorCorrectlyGeneratesMinimalFunctionsBlocksAtDesignTimeTabs()\n        {\n            RunTest(\"FunctionsBlockMinimal\",\n                    \"FunctionsBlockMinimal.DesignTime\" + \".Tabs\",\n                    designTimeMode: true,\n                    tabTest: TabTest.Tabs,\n                    expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(3, 13, 7, 55),\n            });\n        }\n\n        [Fact]\n        public void CSharpCodeGeneratorCorrectlyGeneratesHiddenSpansWithinCode()\n        {\n            RunTest(\"HiddenSpansInCode\", designTimeMode: true, tabTest: TabTest.NoTabs, expectedDesignTimePragmas: new List<GeneratedCodeMapping>\n            {\n                /* 01 */ new GeneratedCodeMapping(1, 3, 3, 6),\n                /* 02 */ new GeneratedCodeMapping(2, 6, 6, 5)\n            });\n        }\n\n        [Fact]\n        public void CSharpCodeGeneratorGeneratesCodeWithParserErrorsInDesignTimeMode()\n        {\n            RunTest(\"ParserError\", designTimeMode: true, expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(1, 3, 3, 31)\n            });\n        }\n\n        [Fact]\n        public void CSharpCodeGeneratorCorrectlyGeneratesInheritsAtRuntime()\n        {\n            RunTest(\"Inherits\", baselineName: \"Inherits.Runtime\");\n        }\n\n        [Fact]\n        public void CSharpCodeGeneratorCorrectlyGeneratesInheritsAtDesigntime()\n        {\n            RunTest(\"Inherits\", baselineName: \"Inherits.Designtime\", designTimeMode: true, tabTest: TabTest.NoTabs, expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(1, 2, 7, 5),\n                /* 02 */ new GeneratedCodeMapping(3, 11, 11, 25),\n            });\n        }\n\n        [Fact]\n        public void CSharpCodeGeneratorCorrectlyGeneratesDesignTimePragmasForUnfinishedExpressionsInCode()\n        {\n            RunTest(\"UnfinishedExpressionInCode\", tabTest: TabTest.NoTabs, designTimeMode: true, expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(1, 3, 3, 2),\n                /* 02 */ new GeneratedCodeMapping(2, 2, 7, 9),\n                /* 03 */ new GeneratedCodeMapping(2, 11, 11, 2)\n            });\n        }\n\n        [Fact]\n        public void CSharpCodeGeneratorCorrectlyGeneratesDesignTimePragmasForUnfinishedExpressionsInCodeTabs()\n        {\n            RunTest(\"UnfinishedExpressionInCode\",\n                    \"UnfinishedExpressionInCode.Tabs\",\n                    tabTest: TabTest.Tabs,\n                    designTimeMode: true, expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(1, 3, 3, 2),\n                /* 02 */ new GeneratedCodeMapping(2, 2, 7, 9),\n                /* 03 */ new GeneratedCodeMapping(2, 11, 5, 2)\n            });\n        }\n\n        [Fact]\n        public void CSharpCodeGeneratorCorrectlyGeneratesDesignTimePragmasMarkupAndExpressions()\n        {\n            RunTest(\"DesignTime\",\n                designTimeMode: true,\n                tabTest: TabTest.NoTabs,\n                expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(2, 14, 13, 36),\n                /* 02 */ new GeneratedCodeMapping(3, 23, 23, 1),\n                /* 03 */ new GeneratedCodeMapping(3, 28, 28, 15),\n                /* 04 */ new GeneratedCodeMapping(8, 3, 7, 12),\n                /* 05 */ new GeneratedCodeMapping(9, 2, 7, 4),\n                /* 06 */ new GeneratedCodeMapping(9, 15, 15, 3),\n                /* 07 */ new GeneratedCodeMapping(9, 26, 26, 1),\n                /* 08 */ new GeneratedCodeMapping(14, 6, 7, 3),\n                /* 09 */ new GeneratedCodeMapping(17, 9, 24, 7),\n                /* 10 */ new GeneratedCodeMapping(17, 16, 16, 26),\n                /* 11 */ new GeneratedCodeMapping(19, 19, 19, 9),\n                /* 12 */ new GeneratedCodeMapping(21, 1, 1, 1)\n            });\n        }\n\n\n        [Fact]\n        public void CSharpCodeGeneratorCorrectlyGeneratesDesignTimePragmasForImplicitExpressionStartedAtEOF()\n        {\n            RunTest(\"ImplicitExpressionAtEOF\", designTimeMode: true, expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(3, 2, 7, 0)\n            });\n        }\n\n        [Fact]\n        public void CSharpCodeGeneratorCorrectlyGeneratesDesignTimePragmasForExplicitExpressionStartedAtEOF()\n        {\n            RunTest(\"ExplicitExpressionAtEOF\", designTimeMode: true, expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(3, 3, 7, 0)\n            });\n        }\n\n        [Fact]\n        public void CSharpCodeGeneratorCorrectlyGeneratesDesignTimePragmasForCodeBlockStartedAtEOF()\n        {\n            RunTest(\"CodeBlockAtEOF\", designTimeMode: true, expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(1, 3, 3, 0)\n            });\n        }\n\n        [Fact]\n        public void CSharpCodeGeneratorCorrectlyGeneratesDesignTimePragmasForEmptyImplicitExpression()\n        {\n            RunTest(\"EmptyImplicitExpression\", designTimeMode: true, expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(3, 2, 7, 0)\n            });\n        }\n\n        [Fact]\n        public void CSharpCodeGeneratorCorrectlyGeneratesDesignTimePragmasForEmptyImplicitExpressionInCode()\n        {\n            RunTest(\"EmptyImplicitExpressionInCode\", tabTest: TabTest.NoTabs, designTimeMode: true, expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(1, 3, 3, 6),\n                /* 02 */ new GeneratedCodeMapping(2, 6, 7, 0),\n                /* 03 */ new GeneratedCodeMapping(2, 6, 6, 2)\n            });\n        }\n\n        [Fact]\n        public void CSharpCodeGeneratorCorrectlyGeneratesDesignTimePragmasForEmptyImplicitExpressionInCodeTabs()\n        {\n            RunTest(\"EmptyImplicitExpressionInCode\",\n                    \"EmptyImplicitExpressionInCode.Tabs\",\n                    tabTest: TabTest.Tabs,\n                    designTimeMode: true, expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(1, 3, 3, 6),\n                /* 02 */ new GeneratedCodeMapping(2, 6, 7, 0),\n                /* 03 */ new GeneratedCodeMapping(2, 6, 3, 2)\n            });\n        }\n\n        [Fact]\n        public void CSharpCodeGeneratorCorrectlyGeneratesDesignTimePragmasForEmptyExplicitExpression()\n        {\n            RunTest(\"EmptyExplicitExpression\", designTimeMode: true, expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(3, 3, 7, 0)\n            });\n        }\n\n        [Fact]\n        public void CSharpCodeGeneratorCorrectlyGeneratesDesignTimePragmasForEmptyCodeBlock()\n        {\n            RunTest(\"EmptyCodeBlock\", designTimeMode: true, expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(3, 3, 3, 0)\n            });\n        }\n\n        [Fact]\n        public void CSharpCodeGeneratorDoesNotRenderLinePragmasIfGenerateLinePragmasIsSetToFalse()\n        {\n            RunTest(\"NoLinePragmas\", generatePragmas: false);\n        }\n\n        [Fact]\n        public void CSharpCodeGeneratorRendersHelpersBlockCorrectlyWhenInstanceHelperRequested()\n        {\n            RunTest(\"Helpers\", baselineName: \"Helpers.Instance\", hostConfig: h => h.StaticHelpers = false);\n        }\n\n        [Fact]\n        public void CSharpCodeGeneratorCorrectlyInstrumentsRazorCodeWhenInstrumentationRequested()\n        {\n            RunTest(\"Instrumented\", hostConfig: host =>\n            {\n                host.EnableInstrumentation = true;\n                host.InstrumentedSourceFilePath = String.Format(\"~/{0}.cshtml\", host.DefaultClassName);\n            });\n        }\n\n        [Fact]\n        public void CSharpCodeGeneratorGeneratesUrlsCorrectlyWithCommentsAndQuotes()\n        {\n            RunTest(\"HtmlCommentWithQuote_Single\",\n                    tabTest: TabTest.NoTabs);\n\n            RunTest(\"HtmlCommentWithQuote_Double\",\n                    tabTest: TabTest.NoTabs);\n\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Generator/GeneratedCodeMappingTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Generator;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Generator\n{\n    public class GeneratedCodeMappingTest\n    {\n        [Fact]\n        public void GeneratedCodeMappingsAreEqualIfDataIsEqual()\n        {\n            GeneratedCodeMapping left = new GeneratedCodeMapping(12, 34, 56, 78);\n            GeneratedCodeMapping right = new GeneratedCodeMapping(12, 34, 56, 78);\n            Assert.True(left == right);\n            Assert.True(left.Equals(right));\n            Assert.True(right.Equals(left));\n            Assert.True(Equals(left, right));\n        }\n\n        [Fact]\n        public void GeneratedCodeMappingsAreNotEqualIfCodeLengthIsNotEqual()\n        {\n            GeneratedCodeMapping left = new GeneratedCodeMapping(12, 34, 56, 87);\n            GeneratedCodeMapping right = new GeneratedCodeMapping(12, 34, 56, 78);\n            Assert.False(left == right);\n            Assert.False(left.Equals(right));\n            Assert.False(right.Equals(left));\n            Assert.False(Equals(left, right));\n        }\n\n        [Fact]\n        public void GeneratedCodeMappingsAreNotEqualIfStartGeneratedColumnIsNotEqual()\n        {\n            GeneratedCodeMapping left = new GeneratedCodeMapping(12, 34, 56, 87);\n            GeneratedCodeMapping right = new GeneratedCodeMapping(12, 34, 65, 87);\n            Assert.False(left == right);\n            Assert.False(left.Equals(right));\n            Assert.False(right.Equals(left));\n            Assert.False(Equals(left, right));\n        }\n\n        [Fact]\n        public void GeneratedCodeMappingsAreNotEqualIfStartColumnIsNotEqual()\n        {\n            GeneratedCodeMapping left = new GeneratedCodeMapping(12, 34, 56, 87);\n            GeneratedCodeMapping right = new GeneratedCodeMapping(12, 43, 56, 87);\n            Assert.False(left == right);\n            Assert.False(left.Equals(right));\n            Assert.False(right.Equals(left));\n            Assert.False(Equals(left, right));\n        }\n\n        [Fact]\n        public void GeneratedCodeMappingsAreNotEqualIfStartLineIsNotEqual()\n        {\n            GeneratedCodeMapping left = new GeneratedCodeMapping(12, 34, 56, 87);\n            GeneratedCodeMapping right = new GeneratedCodeMapping(21, 34, 56, 87);\n            Assert.False(left == right);\n            Assert.False(left.Equals(right));\n            Assert.False(right.Equals(left));\n            Assert.False(Equals(left, right));\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Razor.Test/Generator/PaddingTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Linq;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Generator\n{\n    public class PaddingTest\n    {\n        [Fact]\n        public void CalculatePaddingForEmptySpanReturnsZero()\n        {\n            RazorEngineHost host = CreateHost(designTime: true);\n\n            Span span = new Span(new SpanBuilder());\n\n            int padding = CodeGeneratorPaddingHelper.CalculatePadding(host, span, 0);\n\n            Assert.Equal(0, padding);\n        }\n\n        [Theory]\n        [InlineData(true, false, 4)]\n        [InlineData(true, false, 2)]\n        [InlineData(false, true, 4)]\n        [InlineData(false, true, 2)]\n        [InlineData(false, false, 4)]\n        [InlineData(false, false, 2)]\n        [InlineData(true, true, 4)]\n        [InlineData(true, true, 2)]\n        [InlineData(true, true, 1)]\n        [InlineData(true, true, 0)]\n        public void CalculatePaddingForEmptySpanWith4Spaces(bool designTime, bool isIndentingWithTabs, int tabSize)\n        {\n            RazorEngineHost host = CreateHost(designTime: designTime, isIndentingWithTabs: isIndentingWithTabs, tabSize: tabSize);\n\n            Span span = GenerateSpan(@\"    @{\", SpanKind.Code, 3, \"\");\n\n            int padding = CodeGeneratorPaddingHelper.CalculatePadding(host, span, 0);\n\n            Assert.Equal(6, padding);\n        }\n\n        [Theory]\n        [InlineData(true, false, 4)]\n        [InlineData(true, false, 2)]\n        [InlineData(false, true, 4)]\n        [InlineData(false, true, 2)]\n        [InlineData(false, false, 4)]\n        [InlineData(false, false, 2)]\n        [InlineData(true, true, 4)]\n        [InlineData(true, true, 2)]\n        [InlineData(true, true, 1)]\n        [InlineData(true, true, 0)]\n        public void CalculatePaddingForIfSpanWith4Spaces(bool designTime, bool isIndentingWithTabs, int tabSize)\n        {\n            RazorEngineHost host = CreateHost(designTime: designTime, isIndentingWithTabs: isIndentingWithTabs, tabSize: tabSize);\n\n            Span span = GenerateSpan(@\"    @if (true)\", SpanKind.Code, 2, \"if (true)\");\n\n            int padding = CodeGeneratorPaddingHelper.CalculatePadding(host, span, 1);\n\n            Assert.Equal(4, padding);\n        }\n\n        [Theory]\n        [InlineData(true, false, 4, 0, 4)]\n        [InlineData(true, false, 2, 0, 4)]\n        [InlineData(true, true, 4, 1, 0)]\n        [InlineData(true, true, 2, 2, 0)]\n        [InlineData(true, true, 1, 4, 0)]\n        [InlineData(true, true, 0, 4, 0)]\n        [InlineData(true, true, 3, 1, 1)]\n\n        // in non design time mode padding falls back to spaces to keep runtime code identical to v2 code.\n        [InlineData(false, true, 4, 0, 5)]\n        [InlineData(false, true, 2, 0, 5)]\n\n        [InlineData(false, false, 4, 0, 5)]\n        [InlineData(false, false, 2, 0, 5)]\n        public void VerifyPaddingForIfSpanWith4Spaces(bool designTime, bool isIndentingWithTabs, int tabSize, int numTabs, int numSpaces)\n        {\n            RazorEngineHost host = CreateHost(designTime: designTime, isIndentingWithTabs: isIndentingWithTabs, tabSize: tabSize);\n\n            // no new lines involved\n            Span span = GenerateSpan(\"    @if (true)\", SpanKind.Code, 2, \"if (true)\");\n\n            int generatedStart = 1;\n            string code = \" if (true)\";\n            int paddingCharCount;\n\n            string padded = CodeGeneratorPaddingHelper.PadStatement(host, code, span, ref generatedStart, out paddingCharCount);\n\n            VerifyPadded(numTabs, numSpaces, code, padded, paddingCharCount);\n\n            // with new lines involved\n            Span newLineSpan = GenerateSpan(\"\\t<div>\\r\\n    @if (true)\", SpanKind.Code, 3, \"if (true)\");\n\n            string newLinePadded = CodeGeneratorPaddingHelper.PadStatement(host, code, span, ref generatedStart, out paddingCharCount);\n\n            VerifyPadded(numTabs, numSpaces, code, newLinePadded, paddingCharCount);\n        }\n\n        [Theory]\n        [InlineData(true, false, 4, 0, 8)]\n        [InlineData(true, false, 2, 0, 4)]\n        [InlineData(true, true, 4, 2, 0)]\n        [InlineData(true, true, 2, 2, 0)]\n        [InlineData(true, true, 1, 2, 0)]\n        [InlineData(true, true, 0, 2, 0)]\n        [InlineData(true, true, 3, 2, 0)]\n\n        // in non design time mode padding falls back to spaces to keep runtime code identical to v2 code.\n        [InlineData(false, true, 4, 0, 9)]\n        [InlineData(false, true, 2, 0, 5)]\n\n        [InlineData(false, false, 4, 0, 9)]\n        [InlineData(false, false, 2, 0, 5)]\n        public void VerifyPaddingForIfSpanWithTwoTabs(bool designTime, bool isIndentingWithTabs, int tabSize, int numTabs, int numSpaces)\n        {\n            RazorEngineHost host = CreateHost(designTime: designTime, isIndentingWithTabs: isIndentingWithTabs, tabSize: tabSize);\n\n            // no new lines involved\n            Span span = GenerateSpan(\"\\t\\t@if (true)\", SpanKind.Code, 2, \"if (true)\");\n\n            int generatedStart = 1;\n            string code = \" if (true)\";\n            int paddingCharCount;\n\n            string padded = CodeGeneratorPaddingHelper.PadStatement(host, code, span, ref generatedStart, out paddingCharCount);\n\n            VerifyPadded(numTabs, numSpaces, code, padded, paddingCharCount);\n\n            // with new lines involved\n            Span newLineSpan = GenerateSpan(\"\\t<div>\\r\\n\\t\\t@if (true)\", SpanKind.Code, 3, \"if (true)\");\n\n            string newLinePadded = CodeGeneratorPaddingHelper.PadStatement(host, code, span, ref generatedStart, out paddingCharCount);\n\n            VerifyPadded(numTabs, numSpaces, code, newLinePadded, paddingCharCount);\n        }\n\n        [Theory]\n        [InlineData(true, false, 4, 0, 8)]\n        [InlineData(true, false, 2, 0, 4)]\n        [InlineData(true, true, 4, 2, 0)]\n        [InlineData(true, true, 2, 2, 0)]\n        [InlineData(true, true, 1, 2, 0)]\n        [InlineData(true, true, 0, 2, 0)]\n\n        // in non design time mode padding falls back to spaces to keep runtime code identical to v2 code.\n        [InlineData(false, true, 4, 0, 9)]\n        [InlineData(false, true, 2, 0, 5)]\n\n        [InlineData(false, false, 4, 0, 9)]\n        [InlineData(false, false, 2, 0, 5)]\n        public void CalculatePaddingForOpenedIf(bool designTime, bool isIndentingWithTabs, int tabSize, int numTabs, int numSpaces)\n        {\n            RazorEngineHost host = CreateHost(designTime: designTime, isIndentingWithTabs: isIndentingWithTabs, tabSize: tabSize);\n\n            string text = \"\\r\\n<html>\\r\\n<body>\\r\\n\\t\\t@if (true) { \\r\\n</body>\\r\\n</html>\";\n\n            Span span = GenerateSpan(text, SpanKind.Code, 3, \"if (true) { \\r\\n\");\n\n            int generatedStart = 1;\n            string code = \" if (true) { \\r\\n\";\n            int paddingCharCount;\n            string padded = CodeGeneratorPaddingHelper.PadStatement(host, code, span, ref generatedStart, out paddingCharCount);\n\n            VerifyPadded(numTabs, numSpaces, code, padded, paddingCharCount);\n        }\n\n        private static void VerifyPadded(int numTabs, int numSpaces, string code, string padded, int paddingCharCount)\n        {\n            Assert.Equal(numTabs + numSpaces + code.Length, padded.Length);\n\n            if (numTabs > 0 || numSpaces > 0)\n            {\n                Assert.True(padded.Length > numTabs + numSpaces, \"padded string too short\");\n            }\n\n            for (int i = 0; i < numTabs; i++)\n            {\n                Assert.Equal('\\t', padded[i]);\n            }\n\n            for (int i = numTabs; i < numTabs + numSpaces; i++)\n            {\n                Assert.Equal(' ', padded[i]);\n            }\n\n            Assert.Equal(numSpaces + numTabs, paddingCharCount);\n        }\n\n        private static RazorEngineHost CreateHost(bool designTime, bool isIndentingWithTabs = false, int tabSize = 4)\n        {\n            return new RazorEngineHost(new CSharpRazorCodeLanguage())\n            {\n                DesignTimeMode = designTime,\n                IsIndentingWithTabs = isIndentingWithTabs,\n                TabSize = tabSize,\n            };\n        }\n\n        private static Span GenerateSpan(string text, SpanKind spanKind, int spanIndex, string spanText)\n        {\n            Span[] spans = GenerateSpans(text, spanKind, spanIndex, spanText);\n\n            return spans[spanIndex];\n        }\n\n        private static Span[] GenerateSpans(string text, SpanKind spanKind, int spanIndex, string spanText)\n        {\n            Assert.True(spanIndex > 0);\n\n            RazorParser parser = new RazorParser(new CSharpCodeParser(), new HtmlMarkupParser());\n\n            Span[] spans;\n\n            using (var reader = new StringReader(text))\n            {\n                ParserResults results = parser.Parse(reader);\n                spans = results.Document.Flatten().ToArray();\n            }\n\n            Assert.True(spans.Length > spanIndex);\n            Assert.Equal(spanKind, spans[spanIndex].Kind);\n            Assert.Equal(spanText, spans[spanIndex].Content);\n\n            return spans;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Generator/RazorCodeGeneratorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n//#define GENERATE_BASELINES\n\nusing System.CodeDom;\nusing System.CodeDom.Compiler;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Utils;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Generator\n{\n    public abstract class RazorCodeGeneratorTest<TLanguage>\n        where TLanguage : RazorCodeLanguage, new()\n    {\n        protected static readonly string TestRootNamespaceName = \"TestOutput\";\n\n        protected abstract string FileExtension { get; }\n        protected abstract string LanguageName { get; }\n        protected abstract string BaselineExtension { get; }\n\n        protected RazorEngineHost CreateHost()\n        {\n            return new RazorEngineHost(new TLanguage());\n        }\n\n        protected void RunTest(string name,\n                               string baselineName = null,\n                               bool generatePragmas = true,\n                               bool designTimeMode = false,\n                               IList<GeneratedCodeMapping> expectedDesignTimePragmas = null,\n                               TestSpan[] spans = null,\n                               TabTest tabTest = TabTest.Both,\n                               Action<RazorEngineHost> hostConfig = null)\n        {\n            bool testRun = false;\n\n            if ((tabTest & TabTest.Tabs) == TabTest.Tabs)\n            {\n                // CodeDOM will inject its strings into the generated file header, so we force English.\n                using (new CultureReplacer())\n                {\n                    RunTestInternal(\n                        name: name,\n                        baselineName: baselineName,\n                        generatePragmas: generatePragmas,\n                        designTimeMode: designTimeMode,\n                        expectedDesignTimePragmas: expectedDesignTimePragmas,\n                        spans: spans,\n                        withTabs: true,\n                        hostConfig: hostConfig);\n                }\n\n                testRun = true;\n            }\n\n            if ((tabTest & TabTest.NoTabs) == TabTest.NoTabs)\n            {\n                // CodeDOM will inject its strings into the generated file header, so we force English.\n                using (new CultureReplacer())\n                {\n                    RunTestInternal(\n                        name: name,\n                        baselineName: baselineName,\n                        generatePragmas: generatePragmas,\n                        designTimeMode: designTimeMode,\n                        expectedDesignTimePragmas: expectedDesignTimePragmas,\n                        spans: spans,\n                        withTabs: false,\n                        hostConfig: hostConfig);\n                }\n\n                testRun = true;\n            }\n\n            Assert.True(testRun, \"No test was run because TabTest is not set correctly\");\n        }\n\n        private void RunTestInternal(string name,\n                               string baselineName,\n                               bool generatePragmas,\n                               bool designTimeMode,\n                               IList<GeneratedCodeMapping> expectedDesignTimePragmas,\n                               TestSpan[] spans,\n                               bool withTabs,\n                               Action<RazorEngineHost> hostConfig)\n        {\n            // Load the test files\n            if (baselineName == null)\n            {\n                baselineName = name;\n            }\n\n            string source = TestFile.Create(String.Format(\"CodeGenerator.{1}.Source.{0}.{2}\", name, LanguageName, FileExtension)).ReadAllText();\n            string expectedOutput = TestFile.Create(String.Format(\"CodeGenerator.{1}.Output.{0}.{2}\", baselineName, LanguageName, BaselineExtension)).ReadAllText();\n\n            // Set up the host and engine\n            RazorEngineHost host = CreateHost();\n            host.NamespaceImports.Add(\"System\");\n            host.DesignTimeMode = designTimeMode;\n            host.StaticHelpers = true;\n            host.DefaultClassName = name;\n\n            // Add support for templates, etc.\n            host.GeneratedClassContext = new GeneratedClassContext(GeneratedClassContext.DefaultExecuteMethodName,\n                                                                   GeneratedClassContext.DefaultWriteMethodName,\n                                                                   GeneratedClassContext.DefaultWriteLiteralMethodName,\n                                                                   \"WriteTo\",\n                                                                   \"WriteLiteralTo\",\n                                                                   \"Template\",\n                                                                   \"DefineSection\",\n                                                                   \"BeginContext\",\n                                                                   \"EndContext\")\n                                                                   {\n                                                                       LayoutPropertyName = \"Layout\",\n                                                                       ResolveUrlMethodName = \"Href\"\n                                                                   };\n            if (hostConfig != null)\n            {\n                hostConfig(host);\n            }\n\n            host.IsIndentingWithTabs = withTabs;\n\n            RazorTemplateEngine engine = new RazorTemplateEngine(host);\n\n            // Generate code for the file\n            GeneratorResults results = null;\n            using (StringTextBuffer buffer = new StringTextBuffer(source))\n            {\n                results = engine.GenerateCode(buffer, className: name, rootNamespace: TestRootNamespaceName, sourceFileName: generatePragmas ? String.Format(\"{0}.{1}\", name, FileExtension) : null);\n            }\n\n            // Generate code\n            CodeCompileUnit ccu = results.GeneratedCode;\n            CodeDomProvider codeProvider = (CodeDomProvider)Activator.CreateInstance(host.CodeLanguage.CodeDomProviderType);\n\n            CodeGeneratorOptions options = new CodeGeneratorOptions();\n\n            // Both run-time and design-time use these settings. See:\n            // * $/Dev10/pu/SP_WebTools/venus/html/Razor/Impl/RazorCodeGenerator.cs:204\n            // * $/Dev10/Releases/RTMRel/ndp/fx/src/xsp/System/Web/Compilation/BuildManagerHost.cs:373\n            options.BlankLinesBetweenMembers = false;\n            options.IndentString = String.Empty;\n\n            StringBuilder output = new StringBuilder();\n            using (StringWriter writer = new StringWriter(output))\n            {\n                codeProvider.GenerateCodeFromCompileUnit(ccu, writer, options);\n            }\n\n            WriteBaseline(String.Format(@\"test\\System.Web.Razor.Test\\TestFiles\\CodeGenerator\\{0}\\Output\\{1}.{2}\", LanguageName, baselineName, BaselineExtension), MiscUtils.StripRuntimeVersion(output.ToString()));\n\n#if !GENERATE_BASELINES\n            string textOutput = MiscUtils.StripRuntimeVersion(output.ToString());\n\n            //// Verify code against baseline\n            Assert.Equal(expectedOutput, textOutput);\n#endif\n\n            IEnumerable<Span> generatedSpans = results.Document.Flatten();\n\n            foreach (var span in generatedSpans)\n            {\n                VerifyNoBrokenEndOfLines(span.Content);\n            }\n\n            // Verify design-time pragmas\n            if (designTimeMode)\n            {\n                if (spans != null)\n                {\n                    Assert.Equal(spans, generatedSpans.Select(span => new TestSpan(span)).ToArray());\n                }\n\n                if (expectedDesignTimePragmas != null)\n                {\n                    Assert.True(results.DesignTimeLineMappings != null && results.DesignTimeLineMappings.Count > 0);\n\n                    Assert.Equal(expectedDesignTimePragmas.Count, results.DesignTimeLineMappings.Count);\n\n                    Assert.Equal(\n                        expectedDesignTimePragmas.ToArray(),\n                        results.DesignTimeLineMappings\n                               .OrderBy(p => p.Key)\n                               .Select(p => p.Value)\n                               .ToArray());\n                }\n            }\n        }\n\n        [Conditional(\"GENERATE_BASELINES\")]\n        private void WriteBaseline(string baselineFile, string output)\n        {\n            string root = RecursiveFind(\"Runtime.sln\", Path.GetFullPath(\".\"));\n            string baselinePath = Path.Combine(root, baselineFile);\n\n            // Update baseline\n            // IMPORTANT! Replace this path with the local path on your machine to the baseline files!\n            if (File.Exists(baselinePath))\n            {\n                File.Delete(baselinePath);\n            }\n            File.WriteAllText(baselinePath, output.ToString());\n        }\n\n        private string RecursiveFind(string path, string start)\n        {\n            string test = Path.Combine(start, path);\n            if (File.Exists(test))\n            {\n                return start;\n            }\n            else\n            {\n                return RecursiveFind(path, new DirectoryInfo(start).Parent.FullName);\n            }\n        }\n\n        private void VerifyNoBrokenEndOfLines(string text)\n        {\n            for (int i = 0; i < text.Length; i++)\n            {\n                if (text[i] == '\\r')\n                {\n                    Assert.True(text.Length > i + 1);\n                    Assert.Equal('\\n', text[i + 1]);\n                }\n                else if (text[i] == '\\n')\n                {\n                    Assert.True(i > 0);\n                    Assert.Equal('\\r', text[i - 1]);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Generator/TabTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Razor.Test.Generator\n{\n    [Flags]\n    public enum TabTest\n    {\n        NoTabs = 1,\n        Tabs = 2,\n        Both = 3\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Generator/TestSpan.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics;\nusing System.Web.Razor.Parser.SyntaxTree;\n\nnamespace System.Web.Razor.Test.Generator\n{\n    public class TestSpan\n    {\n        /// <summary>\n        /// Test span to simplify the generation of the actual Span in test initializer.\n        /// </summary>\n        /// <param name=\"kind\">Span kind</param>\n        /// <param name=\"start\">Zero indexed start char index in the buffer.</param>\n        /// <param name=\"end\">End Column, if the text length is zero Start == End.</param>\n        public TestSpan(SpanKind kind, int start, int end)\n        {\n            Kind = kind;\n            Start = start;\n            End = end;\n        }\n\n        public TestSpan(Span span)\n            : this(span.Kind,\n                   span.Start.AbsoluteIndex,\n                   span.Start.AbsoluteIndex + span.Length)\n        {\n        }\n\n        public SpanKind Kind { get; private set; }\n        public int Start { get; private set; }\n        public int End { get; private set; }\n\n        public override string ToString()\n        {\n            return String.Format(\"{0}: {1}-{2}\", Kind, Start, End);\n        }\n\n        public override bool Equals(object obj)\n        {\n            TestSpan other = obj as TestSpan;\n\n            if (other != null)\n            {\n                return (Kind == other.Kind) &&\n                       (Start == other.Start) &&\n                       (End == other.End);\n            }\n\n            return false;\n        }\n\n        public override int GetHashCode()\n        {\n            return base.GetHashCode();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Generator/VBRazorCodeGeneratorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Razor.Generator;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Generator\n{\n    public class VBRazorCodeGeneratorTest : RazorCodeGeneratorTest<VBRazorCodeLanguage>\n    {\n        private const string TestPhysicalPath = @\"C:\\Bar.vbhtml\";\n        private const string TestVirtualPath = \"~/Foo/Bar.vbhtml\";\n\n        protected override string FileExtension\n        {\n            get { return \"vbhtml\"; }\n        }\n\n        protected override string LanguageName\n        {\n            get { return \"VB\"; }\n        }\n\n        protected override string BaselineExtension\n        {\n            get { return \"vb\"; }\n        }\n\n        [Fact]\n        public void ConstructorRequiresNonNullClassName()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(() => new VBRazorCodeGenerator(null, TestRootNamespaceName, TestPhysicalPath, CreateHost()), \"className\");\n        }\n\n        [Fact]\n        public void ConstructorRequiresNonEmptyClassName()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(() => new VBRazorCodeGenerator(String.Empty, TestRootNamespaceName, TestPhysicalPath, CreateHost()), \"className\");\n        }\n\n        [Fact]\n        public void ConstructorRequiresNonNullRootNamespaceName()\n        {\n            Assert.ThrowsArgumentNull(() => new VBRazorCodeGenerator(\"Foo\", null, TestPhysicalPath, CreateHost()), \"rootNamespaceName\");\n        }\n\n        [Fact]\n        public void ConstructorAllowsEmptyRootNamespaceName()\n        {\n            new VBRazorCodeGenerator(\"Foo\", String.Empty, TestPhysicalPath, CreateHost());\n        }\n\n        [Fact]\n        public void ConstructorRequiresNonNullHost()\n        {\n            Assert.ThrowsArgumentNull(() => new VBRazorCodeGenerator(\"Foo\", TestRootNamespaceName, TestPhysicalPath, null), \"host\");\n        }\n\n        [Theory]\n        [InlineData(\"NestedCodeBlocks\")]\n        [InlineData(\"CodeBlock\")]\n        [InlineData(\"ExplicitExpression\")]\n        [InlineData(\"MarkupInCodeBlock\")]\n        [InlineData(\"Blocks\")]\n        [InlineData(\"ImplicitExpression\")]\n        [InlineData(\"Imports\")]\n        [InlineData(\"ExpressionsInCode\")]\n        [InlineData(\"FunctionsBlock\")]\n        [InlineData(\"Options\")]\n        [InlineData(\"Templates\")]\n        [InlineData(\"RazorComments\")]\n        [InlineData(\"Sections\")]\n        [InlineData(\"EmptySection\")] // this scenario causes a crash in Razor V2.0\n        [InlineData(\"Helpers\")]\n        [InlineData(\"HelpersMissingCloseParen\")]\n        [InlineData(\"HelpersMissingOpenParen\")]\n        [InlineData(\"NestedHelpers\")]\n        [InlineData(\"LayoutDirective\")]\n        [InlineData(\"ConditionalAttributes\")]\n        [InlineData(\"ResolveUrl\")]\n        public void VBCodeGeneratorCorrectlyGeneratesRunTimeCode(string testName)\n        {\n            RunTest(testName);\n        }\n\n        [Fact]\n        public void VBCodeGeneratorCorrectlyGeneratesMappingsForRazorCommentsAtDesignTime()\n        {\n            // (4, 6) -> (?, 6) [6]\n            // ( 5, 40) -> (?, 39) [2]\n            // ( 8, 6) -> (?, 6) [33]\n            // ( 9, 46) -> (?, 46) [3]\n            // ( 12, 3) -> (?, 7) [3]\n            // ( 12, 8) -> (?, 8) [1]\n            RunTest(\"RazorComments\", \"RazorComments.DesignTime\", designTimeMode: true, tabTest: TabTest.NoTabs, expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(4, 6, 6, 6),\n                /* 02 */ new GeneratedCodeMapping(5, 40, 39, 2),\n                /* 03 */ new GeneratedCodeMapping(8, 6, 6, 33),\n                /* 04 */ new GeneratedCodeMapping(9, 46, 46, 3),\n                /* 05 */ new GeneratedCodeMapping(12, 3, 7, 1),\n                /* 06 */ new GeneratedCodeMapping(12, 8, 8, 1)\n            });\n        }\n\n        [Fact]\n        public void VBCodeGeneratorCorrectlyGeneratesHelperMissingNameAtDesignTime()\n        {\n            RunTest(\"HelpersMissingName\", designTimeMode: true);\n        }\n\n        [Fact]\n        public void VBCodeGeneratorCorrectlyGeneratesImportStatementsAtDesignTimeButCannotWrapPragmasAroundImportStatement()\n        {\n            RunTest(\"Imports\", \"Imports.DesignTime\", designTimeMode: true, tabTest: TabTest.NoTabs, expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(1, 2, 1, 19),\n                /* 02 */ new GeneratedCodeMapping(2, 2, 1, 36),\n                /* 03 */ new GeneratedCodeMapping(3, 2, 1, 16),\n                /* 04 */ new GeneratedCodeMapping(5, 30, 30, 22),\n                /* 05 */ new GeneratedCodeMapping(6, 36, 36, 21),\n            });\n        }\n\n        [Fact]\n        public void VBCodeGeneratorCorrectlyGeneratesFunctionsBlocksAtDesignTime()\n        {\n            RunTest(\"FunctionsBlock\", \"FunctionsBlock.DesignTime\", designTimeMode: true, tabTest: TabTest.NoTabs, expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(1, 11, 11, 4),\n                /* 02 */ new GeneratedCodeMapping(5, 11, 11, 129),\n                /* 03 */ new GeneratedCodeMapping(12, 26, 26, 11)\n            });\n        }\n\n        [Fact]\n        public void VBCodeGeneratorCorrectlyGeneratesFunctionsBlocksAtDesignTimeTabs()\n        {\n            RunTest(\"FunctionsBlock\", \"FunctionsBlock.DesignTime.Tabs\", designTimeMode: true, tabTest: TabTest.Tabs, expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(1, 11, 5, 4),\n                /* 02 */ new GeneratedCodeMapping(5, 11, 5, 129),\n                /* 03 */ new GeneratedCodeMapping(12, 26, 14, 11)\n            });\n        }\n\n        [Fact]\n        public void VBCodeGeneratorGeneratesCodeWithParserErrorsInDesignTimeMode()\n        {\n            RunTest(\"ParserError\", designTimeMode: true, tabTest: TabTest.NoTabs, expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(1, 6, 6, 16)\n            });\n        }\n\n        [Fact]\n        public void VBCodeGeneratorCorrectlyGeneratesInheritsAtRuntime()\n        {\n            RunTest(\"Inherits\", baselineName: \"Inherits.Runtime\");\n        }\n\n        [Fact]\n        public void VBCodeGeneratorCorrectlyGeneratesInheritsAtDesigntime()\n        {\n            RunTest(\"Inherits\", baselineName: \"Inherits.Designtime\", designTimeMode: true, expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(1, 11, 25, 27)\n            });\n        }\n\n        [Fact]\n        public void VBCodeGeneratorCorrectlyGeneratesDesignTimePragmasForUnfinishedExpressionsInCode()\n        {\n            RunTest(\"UnfinishedExpressionInCode\", designTimeMode: true, tabTest: TabTest.NoTabs, expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(1, 6, 6, 2),\n                /* 02 */ new GeneratedCodeMapping(2, 2, 7, 9),\n                /* 03 */ new GeneratedCodeMapping(2, 11, 11, 2)\n            });\n        }\n\n        [Fact]\n        public void VBCodeGeneratorCorrectlyGeneratesDesignTimePragmasMarkupAndExpressions()\n        {\n            RunTest(\"DesignTime\", designTimeMode: true, tabTest: TabTest.NoTabs, expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(2, 14, 13, 17),\n                /* 02 */ new GeneratedCodeMapping(3, 20, 20, 1),\n                /* 03 */ new GeneratedCodeMapping(3, 25, 25, 20),\n                /* 04 */ new GeneratedCodeMapping(8, 3, 7, 12),\n                /* 05 */ new GeneratedCodeMapping(9, 2, 7, 4),\n                /* 06 */ new GeneratedCodeMapping(9, 16, 16, 3),\n                /* 07 */ new GeneratedCodeMapping(9, 27, 27, 1),\n                /* 08 */ new GeneratedCodeMapping(14, 6, 7, 3),\n                /* 09 */ new GeneratedCodeMapping(17, 9, 24, 5),\n                /* 10 */ new GeneratedCodeMapping(17, 14, 14, 28),\n                /* 11 */ new GeneratedCodeMapping(19, 20, 20, 14)\n            });\n        }\n\n        [Fact]\n        public void VBCodeGeneratorCorrectlyGeneratesDesignTimePragmasForImplicitExpressionStartedAtEOF()\n        {\n            RunTest(\"ImplicitExpressionAtEOF\", designTimeMode: true, expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(3, 2, 7, 0)\n            });\n        }\n\n        [Fact]\n        public void VBCodeGeneratorCorrectlyGeneratesDesignTimePragmasForExplicitExpressionStartedAtEOF()\n        {\n            RunTest(\"ExplicitExpressionAtEOF\", designTimeMode: true, expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(3, 3, 7, 0)\n            });\n        }\n\n        [Fact]\n        public void VBCodeGeneratorCorrectlyGeneratesDesignTimePragmasForCodeBlockStartedAtEOF()\n        {\n            RunTest(\"CodeBlockAtEOF\", designTimeMode: true, tabTest: TabTest.NoTabs, expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(3, 6, 6, 0)\n            });\n        }\n\n        [Fact]\n        public void VBCodeGeneratorCorrectlyGeneratesDesignTimePragmasForEmptyImplicitExpression()\n        {\n            RunTest(\"EmptyImplicitExpression\", designTimeMode: true, expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(3, 2, 7, 0)\n            });\n        }\n\n        [Fact]\n        public void VBCodeGeneratorCorrectlyGeneratesDesignTimePragmasForEmptyImplicitExpressionInCode()\n        {\n            RunTest(\"EmptyImplicitExpressionInCode\", designTimeMode: true, tabTest: TabTest.NoTabs, expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(1, 6, 6, 6),\n                /* 02 */ new GeneratedCodeMapping(2, 6, 7, 0),\n                /* 03 */ new GeneratedCodeMapping(2, 6, 6, 2)\n            });\n        }\n\n        [Fact]\n        public void VBCodeGeneratorCorrectlyGeneratesDesignTimePragmasForEmptyExplicitExpression()\n        {\n            RunTest(\"EmptyExplicitExpression\", designTimeMode: true, expectedDesignTimePragmas: new List<GeneratedCodeMapping>()\n            {\n                /* 01 */ new GeneratedCodeMapping(3, 3, 7, 0)\n            });\n        }\n\n        [Fact]\n        public void VBCodeGeneratorDoesNotRenderLinePragmasIfGenerateLinePragmasIsSetToFalse()\n        {\n            RunTest(\"NoLinePragmas\", generatePragmas: false);\n        }\n\n        [Fact]\n        public void VBCodeGeneratorRendersHelpersBlockCorrectlyWhenInstanceHelperRequested()\n        {\n            RunTest(\"Helpers\", baselineName: \"Helpers.Instance\", hostConfig: h => h.StaticHelpers = false);\n        }\n\n        [Fact]\n        public void VBCodeGeneratorCorrectlyInstrumentsRazorCodeWhenInstrumentationRequested()\n        {\n            RunTest(\"Instrumented\", hostConfig: host =>\n            {\n                host.EnableInstrumentation = true;\n                host.InstrumentedSourceFilePath = String.Format(\"~/{0}.vbhtml\", host.DefaultClassName);\n            });\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/BlockTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser\n{\n    public class BlockTest\n    {\n        [Fact]\n        public void ConstructorWithBlockBuilderSetsParent()\n        {\n            // Arrange\n            BlockBuilder builder = new BlockBuilder() { Type = BlockType.Comment };\n            Span span = new SpanBuilder() { Kind = SpanKind.Code }.Build();\n            builder.Children.Add(span);\n\n            // Act\n            Block block = builder.Build();\n\n            // Assert\n            Assert.Same(block, span.Parent);\n        }\n\n        [Fact]\n        public void ConstructorCopiesBasicValuesFromBlockBuilder()\n        {\n            // Arrange\n            BlockBuilder builder = new BlockBuilder()\n            {\n                Name = \"Foo\",\n                Type = BlockType.Helper\n            };\n\n            // Act\n            Block actual = builder.Build();\n\n            // Assert\n            Assert.Equal(\"Foo\", actual.Name);\n            Assert.Equal(BlockType.Helper, actual.Type);\n        }\n\n        [Fact]\n        public void ConstructorTransfersInstanceOfCodeGeneratorFromBlockBuilder()\n        {\n            // Arrange\n            IBlockCodeGenerator expected = new ExpressionCodeGenerator();\n            BlockBuilder builder = new BlockBuilder()\n            {\n                Type = BlockType.Helper,\n                CodeGenerator = expected\n            };\n\n            // Act\n            Block actual = builder.Build();\n\n            // Assert\n            Assert.Same(expected, actual.CodeGenerator);\n        }\n\n        [Fact]\n        public void ConstructorTransfersChildrenFromBlockBuilder()\n        {\n            // Arrange\n            Span expected = new SpanBuilder() { Kind = SpanKind.Code }.Build();\n            BlockBuilder builder = new BlockBuilder()\n            {\n                Type = BlockType.Functions\n            };\n            builder.Children.Add(expected);\n\n            // Act\n            Block block = builder.Build();\n\n            // Assert\n            Assert.Same(expected, block.Children.Single());\n        }\n\n        [Fact]\n        public void LocateOwnerReturnsNullIfNoSpanReturnsTrueForOwnsSpan()\n        {\n            // Arrange\n            var factory = SpanFactory.CreateCsHtml();\n            Block block = new MarkupBlock(\n                factory.Markup(\"Foo \"),\n                new StatementBlock(\n                    factory.CodeTransition(),\n                    factory.Code(\"bar\").AsStatement()),\n                factory.Markup(\" Baz\"));\n            TextChange change = new TextChange(128, 1, new StringTextBuffer(\"Foo @bar Baz\"), 1, new StringTextBuffer(\"Foo @bor Baz\"));\n\n            // Act\n            Span actual = block.LocateOwner(change);\n\n            // Assert\n            Assert.Null(actual);\n        }\n\n        [Fact]\n        public void LocateOwnerReturnsNullIfChangeCrossesMultipleSpans()\n        {\n            // Arrange\n            var factory = SpanFactory.CreateCsHtml();\n            Block block = new MarkupBlock(\n                factory.Markup(\"Foo \"),\n                new StatementBlock(\n                    factory.CodeTransition(),\n                    factory.Code(\"bar\").AsStatement()),\n                factory.Markup(\" Baz\"));\n            TextChange change = new TextChange(4, 10, new StringTextBuffer(\"Foo @bar Baz\"), 10, new StringTextBuffer(\"Foo @bor Baz\"));\n\n            // Act\n            Span actual = block.LocateOwner(change);\n\n            // Assert\n            Assert.Null(actual);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/CSharp/CSharpAutoCompleteTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.CSharp\n{\n    public class CSharpAutoCompleteTest : CsHtmlCodeParserTestBase\n    {\n        [Fact]\n        public void FunctionsDirectiveAutoCompleteAtEOF()\n        {\n            ParseBlockTest(\"@functions{\",\n                           new FunctionsBlock(\n                               Factory.CodeTransition(\"@\")\n                                   .Accepts(AcceptedCharacters.None),\n                               Factory.MetaCode(\"functions{\")\n                                   .Accepts(AcceptedCharacters.None),\n                               Factory.EmptyCSharp()\n                                   .AsFunctionsBody()\n                                   .With(new AutoCompleteEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString)\n                                   {\n                                       AutoCompleteString = \"}\"\n                                   })),\n                           new RazorError(String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF, \"functions\", \"}\", \"{\"),\n                                          1, 0, 1));\n        }\n\n        [Fact]\n        public void HelperDirectiveAutoCompleteAtEOF()\n        {\n            ParseBlockTest(\"@helper Strong(string value) {\",\n                           new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"Strong(string value) {\", 8, 0, 8), headerComplete: true),\n                                           Factory.CodeTransition(),\n                                           Factory.MetaCode(\"helper \")\n                                               .Accepts(AcceptedCharacters.None),\n                                           Factory.Code(\"Strong(string value) {\")\n                                               .Hidden()\n                                               .Accepts(AcceptedCharacters.None),\n                                           new StatementBlock(\n                                               Factory.EmptyCSharp()\n                                                   .AsStatement()\n                                                   .With(new AutoCompleteEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString) { AutoCompleteString = \"}\" })\n                                               )\n                               ),\n                           new RazorError(String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF, \"helper\", \"}\", \"{\"),\n                                          1, 0, 1));\n        }\n\n        [Fact]\n        public void SectionDirectiveAutoCompleteAtEOF()\n        {\n            ParseBlockTest(\"@section Header {\",\n                new SectionBlock(new SectionCodeGenerator(\"Header\"),\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"section Header {\")\n                           .AutoCompleteWith(\"}\", atEndOfSpan: true)\n                           .Accepts(AcceptedCharacters.Any),\n                    new MarkupBlock()),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_Expected_X, \"}\"),\n                    17, 0, 17));\n        }\n\n        [Fact]\n        public void VerbatimBlockAutoCompleteAtEOF()\n        {\n            ParseBlockTest(\"@{\",\n                           new StatementBlock(\n                               Factory.CodeTransition(),\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.EmptyCSharp()\n                                   .AsStatement()\n                                   .With(new AutoCompleteEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString) { AutoCompleteString = \"}\" })\n                               ),\n                           new RazorError(String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF, RazorResources.BlockName_Code, \"}\", \"{\"),\n                                          1, 0, 1));\n        }\n\n        [Fact]\n        public void FunctionsDirectiveAutoCompleteAtStartOfFile()\n        {\n            ParseBlockTest(\"@functions{\" + Environment.NewLine\n                         + \"foo\",\n                           new FunctionsBlock(\n                               Factory.CodeTransition(\"@\")\n                                   .Accepts(AcceptedCharacters.None),\n                               Factory.MetaCode(\"functions{\")\n                                   .Accepts(AcceptedCharacters.None),\n                               Factory.Code(\"\\r\\nfoo\")\n                                   .AsFunctionsBody()\n                                   .With(new AutoCompleteEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString)\n                                   {\n                                       AutoCompleteString = \"}\"\n                                   })),\n                           new RazorError(String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF, \"functions\", \"}\", \"{\"),\n                                          1, 0, 1));\n        }\n\n        [Fact]\n        public void HelperDirectiveAutoCompleteAtStartOfFile()\n        {\n            ParseBlockTest(\"@helper Strong(string value) {\" + Environment.NewLine\n                         + \"<p></p>\",\n                           new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"Strong(string value) {\", 8, 0, 8), headerComplete: true),\n                                           Factory.CodeTransition(),\n                                           Factory.MetaCode(\"helper \")\n                                               .Accepts(AcceptedCharacters.None),\n                                           Factory.Code(\"Strong(string value) {\")\n                                               .Hidden()\n                                               .Accepts(AcceptedCharacters.None),\n                                           new StatementBlock(\n                                               Factory.Code(\"\\r\\n\")\n                                                   .AsStatement()\n                                                   .With(new AutoCompleteEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString) { AutoCompleteString = \"}\" }),\n                                               new MarkupBlock(\n                                                   Factory.Markup(@\"<p></p>\")\n                                                       .With(new MarkupCodeGenerator())\n                                                       .Accepts(AcceptedCharacters.None)\n                                                   ),\n                                               Factory.Span(SpanKind.Code, new CSharpSymbol(Factory.LocationTracker.CurrentLocation, String.Empty, CSharpSymbolType.Unknown))\n                                                   .With(new StatementCodeGenerator())\n                                               )\n                               ),\n                           new RazorError(String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF, \"helper\", \"}\", \"{\"),\n                                          1, 0, 1));\n        }\n\n        [Fact]\n        public void SectionDirectiveAutoCompleteAtStartOfFile()\n        {\n            ParseBlockTest(\"@section Header {\" + Environment.NewLine\n                         + \"<p>Foo</p>\",\n                new SectionBlock(new SectionCodeGenerator(\"Header\"),\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"section Header {\")\n                           .AutoCompleteWith(\"}\", atEndOfSpan: true)\n                           .Accepts(AcceptedCharacters.Any),\n                    new MarkupBlock(\n                        Factory.Markup(\"\\r\\n<p>Foo</p>\"))),\n                new RazorError(String.Format(RazorResources.ParseError_Expected_X, \"}\"),\n                                29, 1, 10));\n        }\n\n        [Fact]\n        public void VerbatimBlockAutoCompleteAtStartOfFile()\n        {\n            ParseBlockTest(\"@{\" + Environment.NewLine\n                         + \"<p></p>\",\n                           new StatementBlock(\n                               Factory.CodeTransition(),\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\"\\r\\n\")\n                                   .AsStatement()\n                                   .With(new AutoCompleteEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString) { AutoCompleteString = \"}\" }),\n                               new MarkupBlock(\n                                   Factory.Markup(@\"<p></p>\")\n                                       .With(new MarkupCodeGenerator())\n                                       .Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Span(SpanKind.Code, new CSharpSymbol(Factory.LocationTracker.CurrentLocation, String.Empty, CSharpSymbolType.Unknown))\n                                   .With(new StatementCodeGenerator())\n                               ),\n                           new RazorError(String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF, RazorResources.BlockName_Code, \"}\", \"{\"),\n                                          1, 0, 1));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/CSharp/CSharpBlockTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.CSharp\n{\n    public class CSharpBlockTest : CsHtmlCodeParserTestBase\n    {\n        [Fact]\n        public void ParseBlockMethodThrowsArgNullExceptionOnNullContext()\n        {\n            // Arrange\n            CSharpCodeParser parser = new CSharpCodeParser();\n\n            // Act and Assert\n            Assert.Throws<InvalidOperationException>(() => parser.ParseBlock(), RazorResources.Parser_Context_Not_Set);\n        }\n\n        [Fact]\n        public void BalancingBracketsIgnoresStringLiteralCharactersAndBracketsInsideSingleLineComments()\n        {\n            SingleSpanBlockTest(@\"if(foo) {\n    // bar } \"\" baz '\n    zoop();\n}\", BlockType.Statement, SpanKind.Code);\n        }\n\n        [Fact]\n        public void NestedCodeBlockWithAtCausesError()\n        {\n            ParseBlockTest(\"if (true) { @if(false) { } }\",\n                           new StatementBlock(\n                               Factory.Code(\"if (true) { \").AsStatement(),\n                               new StatementBlock(\n                                   Factory.CodeTransition(),\n                                   Factory.Code(\"if(false) { }\").AsStatement()\n                                   ),\n                               Factory.Code(\" }\").AsStatement()),\n                           new RazorError(\n                               String.Format(RazorResources.ParseError_Unexpected_Keyword_After_At,\n                                             \"if\"),\n                               new SourceLocation(13, 0, 13)));\n        }\n\n        [Fact]\n        public void BalancingBracketsIgnoresStringLiteralCharactersAndBracketsInsideBlockComments()\n        {\n            SingleSpanBlockTest(\n                @\"if(foo) {\n    /* bar } \"\" */ ' baz } '\n    zoop();\n}\", BlockType.Statement, SpanKind.Code);\n        }\n\n        [Fact]\n        public void ParseBlockSkipsParenthesisedExpressionAndThenBalancesBracesIfFirstIdentifierIsForKeyword()\n        {\n            SingleSpanBlockTest(\"for(int i = 0; i < 10; new Foo { Bar = \\\"baz\\\" }) { Debug.WriteLine(@\\\"foo } bar\\\"); }\", BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockSkipsParenthesisedExpressionAndThenBalancesBracesIfFirstIdentifierIsForeachKeyword()\n        {\n            SingleSpanBlockTest(\"foreach(int i = 0; i < 10; new Foo { Bar = \\\"baz\\\" }) { Debug.WriteLine(@\\\"foo } bar\\\"); }\", BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockSkipsParenthesisedExpressionAndThenBalancesBracesIfFirstIdentifierIsWhileKeyword()\n        {\n            SingleSpanBlockTest(\"while(int i = 0; i < 10; new Foo { Bar = \\\"baz\\\" }) { Debug.WriteLine(@\\\"foo } bar\\\"); }\", BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockSkipsParenthesisedExpressionAndThenBalancesBracesIfFirstIdentifierIsUsingKeywordFollowedByParen()\n        {\n            SingleSpanBlockTest(\"using(int i = 0; i < 10; new Foo { Bar = \\\"baz\\\" }) { Debug.WriteLine(@\\\"foo } bar\\\"); }\", BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsUsingsNestedWithinOtherBlocks()\n        {\n            SingleSpanBlockTest(\"if(foo) { using(int i = 0; i < 10; new Foo { Bar = \\\"baz\\\" }) { Debug.WriteLine(@\\\"foo } bar\\\"); } }\", BlockType.Statement, SpanKind.Code);\n        }\n\n        [Fact]\n        public void ParseBlockSkipsParenthesisedExpressionAndThenBalancesBracesIfFirstIdentifierIsIfKeywordWithNoElseBranches()\n        {\n            SingleSpanBlockTest(\"if(int i = 0; i < 10; new Foo { Bar = \\\"baz\\\" }) { Debug.WriteLine(@\\\"foo } bar\\\"); }\", BlockType.Statement, SpanKind.Code);\n        }\n\n        [Fact]\n        public void ParseBlockAllowsEmptyBlockStatement()\n        {\n            SingleSpanBlockTest(\"if(false) { }\", BlockType.Statement, SpanKind.Code);\n        }\n\n        [Fact]\n        public void ParseBlockTerminatesParenBalancingAtEOF()\n        {\n            ImplicitExpressionTest(\"Html.En(code()\", \"Html.En(code()\",\n                                   AcceptedCharacters.Any,\n                                   new RazorError(\n                                       String.Format(RazorResources.ParseError_Expected_CloseBracket_Before_EOF,\n                                                     \"(\", \")\"),\n                                       new SourceLocation(8, 0, 8)));\n        }\n\n        [Fact]\n        public void ParseBlockSupportsBlockCommentBetweenIfAndElseClause()\n        {\n            SingleSpanBlockTest(\"if(foo) { bar(); } /* Foo */ /* Bar */ else { baz(); }\", BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsRazorCommentBetweenIfAndElseClause()\n        {\n            RunRazorCommentBetweenClausesTest(\"if(foo) { bar(); } \", \" else { baz(); }\", acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsBlockCommentBetweenElseIfAndElseClause()\n        {\n            SingleSpanBlockTest(\"if(foo) { bar(); } else if(bar) { baz(); } /* Foo */ /* Bar */ else { biz(); }\", BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsRazorCommentBetweenElseIfAndElseClause()\n        {\n            RunRazorCommentBetweenClausesTest(\"if(foo) { bar(); } else if(bar) { baz(); } \", \" else { baz(); }\", acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsBlockCommentBetweenIfAndElseIfClause()\n        {\n            SingleSpanBlockTest(\"if(foo) { bar(); } /* Foo */ /* Bar */ else if(bar) { baz(); }\", BlockType.Statement, SpanKind.Code);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsRazorCommentBetweenIfAndElseIfClause()\n        {\n            RunRazorCommentBetweenClausesTest(\"if(foo) { bar(); } \", \" else if(bar) { baz(); }\");\n        }\n\n        [Fact]\n        public void ParseBlockSupportsLineCommentBetweenIfAndElseClause()\n        {\n            SingleSpanBlockTest(@\"if(foo) { bar(); } \n// Foo\n// Bar\nelse { baz(); }\", BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsLineCommentBetweenElseIfAndElseClause()\n        {\n            SingleSpanBlockTest(@\"if(foo) { bar(); } else if(bar) { baz(); }\n// Foo\n// Bar\nelse { biz(); }\", BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsLineCommentBetweenIfAndElseIfClause()\n        {\n            SingleSpanBlockTest(@\"if(foo) { bar(); }\n// Foo\n// Bar\nelse if(bar) { baz(); }\", BlockType.Statement, SpanKind.Code);\n        }\n\n        [Fact]\n        public void ParseBlockParsesElseIfBranchesOfIfStatement()\n        {\n            const string ifStatement = @\"if(int i = 0; i < 10; new Foo { Bar = \"\"baz\"\" }) {\n    Debug.WriteLine(@\"\"foo } bar\"\"); \n}\";\n            const string elseIfBranch = @\" else if(int i = 0; i < 10; new Foo { Bar = \"\"baz\"\" }) { \n    Debug.WriteLine(@\"\"bar } baz\"\"); \n}\";\n            const string document = ifStatement + elseIfBranch;\n\n            SingleSpanBlockTest(document, BlockType.Statement, SpanKind.Code);\n        }\n\n        [Fact]\n        public void ParseBlockParsesMultipleElseIfBranchesOfIfStatement()\n        {\n            const string ifStatement = @\"if(int i = 0; i < 10; new Foo { Bar = \"\"baz\"\" }) {\n    Debug.WriteLine(@\"\"foo } bar\"\"); \n}\";\n            const string elseIfBranch = @\" else if(int i = 0; i < 10; new Foo { Bar = \"\"baz\"\" }) { \n    Debug.WriteLine(@\"\"bar } baz\"\"); \n}\";\n            const string document = ifStatement + elseIfBranch + elseIfBranch + elseIfBranch + elseIfBranch;\n            SingleSpanBlockTest(document, BlockType.Statement, SpanKind.Code);\n        }\n\n        [Fact]\n        public void ParseBlockParsesMultipleElseIfBranchesOfIfStatementFollowedByOneElseBranch()\n        {\n            const string ifStatement = @\"if(int i = 0; i < 10; new Foo { Bar = \"\"baz\"\" }) {\n    Debug.WriteLine(@\"\"foo } bar\"\"); \n}\";\n            const string elseIfBranch = @\" else if(int i = 0; i < 10; new Foo { Bar = \"\"baz\"\" }) { \n    Debug.WriteLine(@\"\"bar } baz\"\"); \n}\";\n            const string elseBranch = @\" else { Debug.WriteLine(@\"\"bar } baz\"\"); }\";\n            const string document = ifStatement + elseIfBranch + elseIfBranch + elseBranch;\n\n            SingleSpanBlockTest(document, BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockStopsParsingCodeAfterElseBranch()\n        {\n            const string ifStatement = @\"if(int i = 0; i < 10; new Foo { Bar = \"\"baz\"\" }) {\n    Debug.WriteLine(@\"\"foo } bar\"\"); \n}\";\n            const string elseIfBranch = @\" else if(int i = 0; i < 10; new Foo { Bar = \"\"baz\"\" }) { \n    Debug.WriteLine(@\"\"bar } baz\"\"); \n}\";\n            const string elseBranch = @\" else { Debug.WriteLine(@\"\"bar } baz\"\"); }\";\n            const string document = ifStatement + elseIfBranch + elseBranch + elseIfBranch;\n            const string expected = ifStatement + elseIfBranch + elseBranch;\n\n            ParseBlockTest(document, new StatementBlock(Factory.Code(expected).AsStatement().Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockStopsParsingIfIfStatementNotFollowedByElse()\n        {\n            const string document = @\"if(int i = 0; i < 10; new Foo { Bar = \"\"baz\"\" }) {\n    Debug.WriteLine(@\"\"foo } bar\"\"); \n}\";\n\n            SingleSpanBlockTest(document, BlockType.Statement, SpanKind.Code);\n        }\n\n        [Fact]\n        public void ParseBlockAcceptsElseIfWithNoCondition()\n        {\n            // We don't want to be a full C# parser - If the else if is missing it's condition, the C# compiler can handle that, we have all the info we need to keep parsing\n            const string ifBranch = @\"if(int i = 0; i < 10; new Foo { Bar = \"\"baz\"\" }) {\n    Debug.WriteLine(@\"\"foo } bar\"\"); \n}\";\n            const string elseIfBranch = @\" else if { foo(); }\";\n            const string document = ifBranch + elseIfBranch;\n\n            SingleSpanBlockTest(document, BlockType.Statement, SpanKind.Code);\n        }\n\n        [Fact]\n        public void ParseBlockCorrectlyParsesDoWhileBlock()\n        {\n            SingleSpanBlockTest(\"do { var foo = bar; } while(foo != bar);\", BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockCorrectlyParsesDoWhileBlockMissingSemicolon()\n        {\n            SingleSpanBlockTest(\"do { var foo = bar; } while(foo != bar)\", BlockType.Statement, SpanKind.Code);\n        }\n\n        [Fact]\n        public void ParseBlockCorrectlyParsesDoWhileBlockMissingWhileCondition()\n        {\n            SingleSpanBlockTest(\"do { var foo = bar; } while\", BlockType.Statement, SpanKind.Code);\n        }\n\n        [Fact]\n        public void ParseBlockCorrectlyParsesDoWhileBlockMissingWhileConditionWithSemicolon()\n        {\n            SingleSpanBlockTest(\"do { var foo = bar; } while;\", BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockCorrectlyParsesDoWhileBlockMissingWhileClauseEntirely()\n        {\n            SingleSpanBlockTest(\"do { var foo = bar; } narf;\", \"do { var foo = bar; }\", BlockType.Statement, SpanKind.Code);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsBlockCommentBetweenDoAndWhileClause()\n        {\n            SingleSpanBlockTest(\"do { var foo = bar; } /* Foo */ /* Bar */ while(true);\", BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsLineCommentBetweenDoAndWhileClause()\n        {\n            SingleSpanBlockTest(@\"do { var foo = bar; } \n// Foo\n// Bar\nwhile(true);\", BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsRazorCommentBetweenDoAndWhileClause()\n        {\n            RunRazorCommentBetweenClausesTest(\"do { var foo = bar; } \", \" while(true);\", acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockCorrectlyParsesMarkupInDoWhileBlock()\n        {\n            ParseBlockTest(\"@do { var foo = bar; <p>Foo</p> foo++; } while (foo<bar>);\",\n                           new StatementBlock(\n                               Factory.CodeTransition(),\n                               Factory.Code(\"do { var foo = bar;\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\" <p>Foo</p> \").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\"foo++; } while (foo<bar>);\").AsStatement().Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockSkipsParenthesisedExpressionAndThenBalancesBracesIfFirstIdentifierIsSwitchKeyword()\n        {\n            SingleSpanBlockTest(@\"switch(foo) {\n    case 0:\n        break;\n    case 1:\n        {\n            break;\n        }\n    case 2:\n        return;\n    default:\n        return;\n}\", BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockSkipsParenthesisedExpressionAndThenBalancesBracesIfFirstIdentifierIsLockKeyword()\n        {\n            SingleSpanBlockTest(\"lock(foo) { Debug.WriteLine(@\\\"foo } bar\\\"); }\", BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockHasErrorsIfNamespaceImportMissingSemicolon()\n        {\n            NamespaceImportTest(\"using Foo.Bar.Baz\", \" Foo.Bar.Baz\", acceptedCharacters: AcceptedCharacters.NonWhiteSpace | AcceptedCharacters.WhiteSpace, location: new SourceLocation(17, 0, 17));\n        }\n\n        [Fact]\n        public void ParseBlockHasErrorsIfNamespaceAliasMissingSemicolon()\n        {\n            NamespaceImportTest(\"using Foo.Bar.Baz = FooBarBaz\", \" Foo.Bar.Baz = FooBarBaz\", acceptedCharacters: AcceptedCharacters.NonWhiteSpace | AcceptedCharacters.WhiteSpace, location: new SourceLocation(29, 0, 29));\n        }\n\n        [Fact]\n        public void ParseBlockParsesNamespaceImportWithSemicolonForUsingKeywordIfIsInValidFormat()\n        {\n            NamespaceImportTest(\"using Foo.Bar.Baz;\", \" Foo.Bar.Baz\", AcceptedCharacters.NonWhiteSpace | AcceptedCharacters.WhiteSpace);\n        }\n\n        [Fact]\n        public void ParseBlockDoesntCaptureWhitespaceAfterUsing()\n        {\n            ParseBlockTest(\"using Foo   \",\n                           new DirectiveBlock(\n                               Factory.Code(\"using Foo\")\n                                   .AsNamespaceImport(\" Foo\", CSharpCodeParser.UsingKeywordLength)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace | AcceptedCharacters.WhiteSpace)));\n        }\n\n        [Fact]\n        public void ParseBlockParsesNamespaceAliasWithSemicolonForUsingKeywordIfIsInValidFormat()\n        {\n            NamespaceImportTest(\"using FooBarBaz = FooBarBaz;\", \" FooBarBaz = FooBarBaz\", AcceptedCharacters.NonWhiteSpace | AcceptedCharacters.WhiteSpace);\n        }\n\n        [Fact]\n        public void ParseBlockTerminatesUsingKeywordAtEOFAndOutputsFileCodeBlock()\n        {\n            SingleSpanBlockTest(\"using                    \", BlockType.Statement, SpanKind.Code);\n        }\n\n        [Fact]\n        public void ParseBlockTerminatesSingleLineCommentAtEndOfFile()\n        {\n            const string document = \"foreach(var f in Foo) { // foo bar baz\";\n            SingleSpanBlockTest(document, document, BlockType.Statement, SpanKind.Code,\n                                new RazorError(String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF, \"foreach\", '}', '{'), SourceLocation.Zero));\n        }\n\n        [Fact]\n        public void ParseBlockTerminatesBlockCommentAtEndOfFile()\n        {\n            const string document = \"foreach(var f in Foo) { /* foo bar baz\";\n            SingleSpanBlockTest(document, document, BlockType.Statement, SpanKind.Code,\n                                new RazorError(String.Format(RazorResources.ParseError_BlockComment_Not_Terminated), 24, 0, 24),\n                                new RazorError(String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF, \"foreach\", '}', '{'), SourceLocation.Zero));\n        }\n\n        [Fact]\n        public void ParseBlockTerminatesSingleSlashAtEndOfFile()\n        {\n            const string document = \"foreach(var f in Foo) { / foo bar baz\";\n            SingleSpanBlockTest(document, document, BlockType.Statement, SpanKind.Code,\n                                new RazorError(String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF, \"foreach\", '}', '{'), SourceLocation.Zero));\n        }\n\n        [Fact]\n        public void ParseBlockSupportsBlockCommentBetweenTryAndFinallyClause()\n        {\n            SingleSpanBlockTest(\"try { bar(); } /* Foo */ /* Bar */ finally { baz(); }\", BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsRazorCommentBetweenTryAndFinallyClause()\n        {\n            RunRazorCommentBetweenClausesTest(\"try { bar(); } \", \" finally { biz(); }\", acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsBlockCommentBetweenCatchAndFinallyClause()\n        {\n            SingleSpanBlockTest(\"try { bar(); } catch(bar) { baz(); } /* Foo */ /* Bar */ finally { biz(); }\", BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsRazorCommentBetweenCatchAndFinallyClause()\n        {\n            RunRazorCommentBetweenClausesTest(\"try { bar(); } catch(bar) { baz(); } \", \" finally { biz(); }\", acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsBlockCommentBetweenTryAndCatchClause()\n        {\n            SingleSpanBlockTest(\"try { bar(); } /* Foo */ /* Bar */ catch(bar) { baz(); }\", BlockType.Statement, SpanKind.Code);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsRazorCommentBetweenTryAndCatchClause()\n        {\n            RunRazorCommentBetweenClausesTest(\"try { bar(); }\", \" catch(bar) { baz(); }\");\n        }\n\n        [Fact]\n        public void ParseBlockSupportsLineCommentBetweenTryAndFinallyClause()\n        {\n            SingleSpanBlockTest(@\"try { bar(); } \n// Foo\n// Bar\nfinally { baz(); }\", BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsLineCommentBetweenCatchAndFinallyClause()\n        {\n            SingleSpanBlockTest(@\"try { bar(); } catch(bar) { baz(); }\n// Foo\n// Bar\nfinally { biz(); }\", BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsLineCommentBetweenTryAndCatchClause()\n        {\n            SingleSpanBlockTest(@\"try { bar(); }\n// Foo\n// Bar\ncatch(bar) { baz(); }\", BlockType.Statement, SpanKind.Code);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsTryStatementWithNoAdditionalClauses()\n        {\n            SingleSpanBlockTest(\"try { var foo = new { } }\", BlockType.Statement, SpanKind.Code);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsMarkupWithinTryClause()\n        {\n            RunSimpleWrappedMarkupTest(\"try {\", \" <p>Foo</p> \", \"}\");\n        }\n\n        [Fact]\n        public void ParseBlockSupportsTryStatementWithOneCatchClause()\n        {\n            SingleSpanBlockTest(\"try { var foo = new { } } catch(Foo Bar Baz) { var foo = new { } }\", BlockType.Statement, SpanKind.Code);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsMarkupWithinCatchClause()\n        {\n            RunSimpleWrappedMarkupTest(\"try { var foo = new { } } catch(Foo Bar Baz) {\", \" <p>Foo</p> \", \"}\");\n        }\n\n        [Fact]\n        public void ParseBlockSupportsTryStatementWithMultipleCatchClause()\n        {\n            SingleSpanBlockTest(\"try { var foo = new { } } catch(Foo Bar Baz) { var foo = new { } } catch(Foo Bar Baz) { var foo = new { } } catch(Foo Bar Baz) { var foo = new { } }\", BlockType.Statement, SpanKind.Code);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsExceptionLessCatchClauses()\n        {\n            SingleSpanBlockTest(\"try { var foo = new { } } catch { var foo = new { } }\", BlockType.Statement, SpanKind.Code);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsMarkupWithinAdditionalCatchClauses()\n        {\n            RunSimpleWrappedMarkupTest(\"try { var foo = new { } } catch(Foo Bar Baz) { var foo = new { } } catch(Foo Bar Baz) { var foo = new { } } catch(Foo Bar Baz) {\", \" <p>Foo</p> \", \"}\");\n        }\n\n        [Fact]\n        public void ParseBlockSupportsTryStatementWithFinallyClause()\n        {\n            SingleSpanBlockTest(\"try { var foo = new { } } finally { var foo = new { } }\", BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsMarkupWithinFinallyClause()\n        {\n            RunSimpleWrappedMarkupTest(\"try { var foo = new { } } finally {\", \" <p>Foo</p> \", \"}\", acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockStopsParsingCatchClausesAfterFinallyBlock()\n        {\n            string expectedContent = \"try { var foo = new { } } finally { var foo = new { } }\";\n            SingleSpanBlockTest(expectedContent + \" catch(Foo Bar Baz) { }\", expectedContent, BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockDoesNotAllowMultipleFinallyBlocks()\n        {\n            string expectedContent = \"try { var foo = new { } } finally { var foo = new { } }\";\n            SingleSpanBlockTest(expectedContent + \" finally { }\", expectedContent, BlockType.Statement, SpanKind.Code, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockAcceptsTrailingDotIntoImplicitExpressionWhenEmbeddedInCode()\n        {\n            // Arrange\n            ParseBlockTest(@\"if(foo) { @foo. }\",\n                           new StatementBlock(\n                               Factory.Code(\"if(foo) { \").AsStatement(),\n                               new ExpressionBlock(\n                                   Factory.CodeTransition(),\n                                   Factory.Code(\"foo.\")\n                                       .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true)\n                                       .Accepts(AcceptedCharacters.NonWhiteSpace)\n                                   ),\n                               Factory.Code(\" }\").AsStatement()\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockParsesExpressionOnSwitchCharacterFollowedByOpenParen()\n        {\n            // Arrange\n            ParseBlockTest(@\"if(foo) { @(foo + bar) }\",\n                           new StatementBlock(\n                               Factory.Code(\"if(foo) { \").AsStatement(),\n                               new ExpressionBlock(\n                                   Factory.CodeTransition(),\n                                   Factory.MetaCode(\"(\").Accepts(AcceptedCharacters.None),\n                                   Factory.Code(\"foo + bar\").AsExpression(),\n                                   Factory.MetaCode(\")\").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\" }\").AsStatement()\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockParsesExpressionOnSwitchCharacterFollowedByIdentifierStart()\n        {\n            // Arrange\n            ParseBlockTest(@\"if(foo) { @foo[4].bar() }\",\n                           new StatementBlock(\n                               Factory.Code(\"if(foo) { \").AsStatement(),\n                               new ExpressionBlock(\n                                   Factory.CodeTransition(),\n                                   Factory.Code(\"foo[4].bar()\")\n                                       .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true)\n                                       .Accepts(AcceptedCharacters.NonWhiteSpace)\n                                   ),\n                               Factory.Code(\" }\").AsStatement()\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockTreatsDoubleAtSignAsEscapeSequenceIfAtStatementStart()\n        {\n            // Arrange\n            ParseBlockTest(@\"if(foo) { @@class.Foo() }\",\n                           new StatementBlock(\n                               Factory.Code(\"if(foo) { \").AsStatement(),\n                               Factory.Code(\"@\").Hidden(),\n                               Factory.Code(\"@class.Foo() }\").AsStatement()\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockTreatsAtSignsAfterFirstPairAsPartOfCSharpStatement()\n        {\n            // Arrange\n            ParseBlockTest(@\"if(foo) { @@@@class.Foo() }\",\n                           new StatementBlock(\n                               Factory.Code(\"if(foo) { \").AsStatement(),\n                               Factory.Code(\"@\").Hidden(),\n                               Factory.Code(\"@@@class.Foo() }\").AsStatement()\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockDoesNotParseMarkupStatementOrExpressionOnSwitchCharacterNotFollowedByOpenAngleOrColon()\n        {\n            // Arrange\n            ParseBlockTest(\"if(foo) { @\\\"Foo\\\".ToString(); }\",\n                           new StatementBlock(\n                               Factory.Code(\"if(foo) { @\\\"Foo\\\".ToString(); }\").AsStatement()));\n        }\n\n        [Fact]\n        public void ParsersCanNestRecursively()\n        {\n            // Arrange\n            ParseBlockTest(\"foreach(var c in db.Categories) {\" + Environment.NewLine\n                         + \"            <div>\" + Environment.NewLine\n                         + \"                <h1>@c.Name</h1>\" + Environment.NewLine\n                         + \"                <ul>\" + Environment.NewLine\n                         + \"                    @foreach(var p in c.Products) {\" + Environment.NewLine\n                         + \"                        <li><a href=\\\"@Html.ActionUrl(\\\"Products\\\", \\\"Detail\\\", new { id = p.Id })\\\">@p.Name</a></li>\" + Environment.NewLine\n                         + \"                    }\" + Environment.NewLine\n                         + \"                </ul>\" + Environment.NewLine\n                         + \"            </div>\" + Environment.NewLine\n                         + \"        }\",\n                new StatementBlock(\n                    Factory.Code(\"foreach(var c in db.Categories) {\\r\\n\").AsStatement(),\n                    new MarkupBlock(\n                        Factory.Markup(\"            <div>\\r\\n                <h1>\"),\n                        new ExpressionBlock(\n                            Factory.CodeTransition(),\n                            Factory.Code(\"c.Name\")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                        Factory.Markup(\"</h1>\\r\\n                <ul>\\r\\n\"),\n                        new StatementBlock(\n                            Factory.Code(@\"                    \").AsStatement(),\n                            Factory.CodeTransition(),\n                            Factory.Code(\"foreach(var p in c.Products) {\\r\\n\").AsStatement(),\n                            new MarkupBlock(\n                                Factory.Markup(\"                        <li><a\"),\n                                new MarkupBlock(new AttributeBlockCodeGenerator(\"href\", new LocationTagged<string>(\" href=\\\"\", 193, 5, 30), new LocationTagged<string>(\"\\\"\", 256, 5, 93)),\n                                    Factory.Markup(\" href=\\\"\").With(SpanCodeGenerator.Null),\n                                    new MarkupBlock(new DynamicAttributeBlockCodeGenerator(new LocationTagged<string>(String.Empty, 200, 5, 37), 200, 5, 37),\n                                        new ExpressionBlock(\n                                            Factory.CodeTransition(),\n                                            Factory.Code(\"Html.ActionUrl(\\\"Products\\\", \\\"Detail\\\", new { id = p.Id })\")\n                                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                                   .Accepts(AcceptedCharacters.NonWhiteSpace))),\n                                    Factory.Markup(\"\\\"\").With(SpanCodeGenerator.Null)),\n                                Factory.Markup(\">\"),\n                                new ExpressionBlock(\n                                    Factory.CodeTransition(),\n                                    Factory.Code(\"p.Name\")\n                                           .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                           .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                                Factory.Markup(\"</a></li>\\r\\n\").Accepts(AcceptedCharacters.None)),\n                            Factory.Code(\"                    }\\r\\n\").AsStatement().Accepts(AcceptedCharacters.None)),\n                        Factory.Markup(\"                </ul>\\r\\n            </div>\\r\\n\")\n                               .Accepts(AcceptedCharacters.None)),\n                    Factory.Code(\"        }\").AsStatement().Accepts(AcceptedCharacters.None)));\n        }\n\n        private void RunRazorCommentBetweenClausesTest(string preComment, string postComment, AcceptedCharacters acceptedCharacters = AcceptedCharacters.Any)\n        {\n            ParseBlockTest(preComment + \"@* Foo *@ @* Bar *@\" + postComment,\n                           new StatementBlock(\n                               Factory.Code(preComment).AsStatement(),\n                               new CommentBlock(\n                                   Factory.CodeTransition(CSharpSymbolType.RazorCommentTransition),\n                                   Factory.MetaCode(\"*\", CSharpSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                                   Factory.Comment(\" Foo \", CSharpSymbolType.RazorComment),\n                                   Factory.MetaCode(\"*\", CSharpSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                                   Factory.CodeTransition(CSharpSymbolType.RazorCommentTransition)\n                                   ),\n                               Factory.Code(\" \").AsStatement(),\n                               new CommentBlock(\n                                   Factory.CodeTransition(CSharpSymbolType.RazorCommentTransition),\n                                   Factory.MetaCode(\"*\", CSharpSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                                   Factory.Comment(\" Bar \", CSharpSymbolType.RazorComment),\n                                   Factory.MetaCode(\"*\", CSharpSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                                   Factory.CodeTransition(CSharpSymbolType.RazorCommentTransition)\n                                   ),\n                               Factory.Code(postComment).AsStatement().Accepts(acceptedCharacters)));\n        }\n\n        private void RunSimpleWrappedMarkupTest(string prefix, string markup, string suffix, AcceptedCharacters acceptedCharacters = AcceptedCharacters.Any)\n        {\n            ParseBlockTest(prefix + markup + suffix,\n                           new StatementBlock(\n                               Factory.Code(prefix).AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(markup).Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(suffix).AsStatement().Accepts(acceptedCharacters)\n                               ));\n        }\n\n        private void NamespaceImportTest(string content, string expectedNS, AcceptedCharacters acceptedCharacters = AcceptedCharacters.None, string errorMessage = null, SourceLocation? location = null)\n        {\n            var errors = new RazorError[0];\n            if (!String.IsNullOrEmpty(errorMessage) && location.HasValue)\n            {\n                errors = new RazorError[]\n                {\n                    new RazorError(errorMessage, location.Value)\n                };\n            }\n            ParseBlockTest(content,\n                           new DirectiveBlock(\n                               Factory.Code(content)\n                                   .AsNamespaceImport(expectedNS, CSharpCodeParser.UsingKeywordLength)\n                                   .Accepts(acceptedCharacters)),\n                           errors);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/CSharp/CSharpDirectivesTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.CSharp\n{\n    public class CSharpDirectivesTest : CsHtmlCodeParserTestBase\n    {\n        [Fact]\n        public void InheritsDirective()\n        {\n            ParseBlockTest(\"@inherits System.Web.WebPages.WebPage\",\n                new DirectiveBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(SyntaxConstants.CSharp.InheritsKeyword + \" \")\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"System.Web.WebPages.WebPage\")\n                           .AsBaseType(\"System.Web.WebPages.WebPage\")));\n        }\n\n        [Fact]\n        public void InheritsDirectiveSupportsArrays()\n        {\n            ParseBlockTest(\"@inherits string[[]][]\",\n                new DirectiveBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(SyntaxConstants.CSharp.InheritsKeyword + \" \")\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"string[[]][]\")\n                           .AsBaseType(\"string[[]][]\")));\n        }\n\n        [Fact]\n        public void InheritsDirectiveSupportsNestedGenerics()\n        {\n            ParseBlockTest(\"@inherits System.Web.Mvc.WebViewPage<IEnumerable<MvcApplication2.Models.RegisterModel>>\",\n                new DirectiveBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(SyntaxConstants.CSharp.InheritsKeyword + \" \")\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"System.Web.Mvc.WebViewPage<IEnumerable<MvcApplication2.Models.RegisterModel>>\")\n                           .AsBaseType(\"System.Web.Mvc.WebViewPage<IEnumerable<MvcApplication2.Models.RegisterModel>>\")));\n        }\n\n        [Fact]\n        public void InheritsDirectiveSupportsTypeKeywords()\n        {\n            ParseBlockTest(\"@inherits string\",\n                new DirectiveBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(SyntaxConstants.CSharp.InheritsKeyword + \" \")\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"string\")\n                           .AsBaseType(\"string\")));\n        }\n\n        [Fact]\n        public void InheritsDirectiveSupportsVSTemplateTokens()\n        {\n            ParseBlockTest(\"@inherits $rootnamespace$.MyBase\",\n                new DirectiveBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(SyntaxConstants.CSharp.InheritsKeyword + \" \")\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"$rootnamespace$.MyBase\")\n                           .AsBaseType(\"$rootnamespace$.MyBase\")));\n        }\n\n        [Fact]\n        public void SessionStateDirectiveWorks()\n        {\n            ParseBlockTest(\"@sessionstate InProc\",\n                           new DirectiveBlock(\n                               Factory.CodeTransition(),\n                               Factory.MetaCode(SyntaxConstants.CSharp.SessionStateKeyword + \" \")\n                                   .Accepts(AcceptedCharacters.None),\n                               Factory.Code(\"InProc\")\n                                      .AsRazorDirectiveAttribute(\"sessionstate\", \"InProc\")\n                               ));\n        }\n\n        [Fact]\n        public void SessionStateDirectiveParsesInvalidSessionValue()\n        {\n            ParseBlockTest(\"@sessionstate Blah\",\n                           new DirectiveBlock(\n                               Factory.CodeTransition(),\n                               Factory.MetaCode(SyntaxConstants.CSharp.SessionStateKeyword + \" \")\n                                   .Accepts(AcceptedCharacters.None),\n                               Factory.Code(\"Blah\")\n                                   .AsRazorDirectiveAttribute(\"sessionstate\", \"Blah\")\n                               ));\n        }\n\n        [Fact]\n        public void FunctionsDirective()\n        {\n            ParseBlockTest(\"@functions { foo(); bar(); }\",\n                new FunctionsBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(SyntaxConstants.CSharp.FunctionsKeyword + \" {\")\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.Code(\" foo(); bar(); \")\n                           .AsFunctionsBody(),\n                    Factory.MetaCode(\"}\")\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void EmptyFunctionsDirective()\n        {\n            ParseBlockTest(\"@functions { }\",\n                new FunctionsBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(SyntaxConstants.CSharp.FunctionsKeyword + \" {\")\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.Code(\" \")\n                           .AsFunctionsBody(),\n                    Factory.MetaCode(\"}\")\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void SectionDirective()\n        {\n            ParseBlockTest(\"@section Header { <p>F{o}o</p> }\",\n                new SectionBlock(new SectionCodeGenerator(\"Header\"),\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"section Header {\")\n                           .AutoCompleteWith(null, atEndOfSpan: true)\n                           .Accepts(AcceptedCharacters.Any),\n                    new MarkupBlock(\n                        Factory.Markup(\" <p>F\", \"{\", \"o\", \"}\", \"o\", \"</p> \")),\n                    Factory.MetaCode(\"}\")\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void HelperDirective()\n        {\n            ParseBlockTest(\"@helper Strong(string value) { foo(); }\",\n                new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"Strong(string value) {\", new SourceLocation(8, 0, 8)), headerComplete: true),\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"helper \")\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"Strong(string value) {\")\n                           .Hidden()\n                           .Accepts(AcceptedCharacters.None),\n                    new StatementBlock(\n                        Factory.Code(\" foo(); \")\n                               .AsStatement()\n                               .With(new StatementCodeGenerator())),\n                    Factory.Code(\"}\")\n                           .Hidden()\n                           .Accepts(AcceptedCharacters.None)));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/CSharp/CSharpErrorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.CSharp\n{\n    public class CSharpErrorTest : CsHtmlCodeParserTestBase\n    {\n        [Fact]\n        public void ParseBlockHandlesQuotesAfterTransition()\n        {\n            ParseBlockTest(\"@\\\"\",\n                           new ExpressionBlock(\n                               Factory.CodeTransition(),\n                               Factory.EmptyCSharp()\n                                   .AsImplicitExpression(KeywordSet)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)\n                               ),\n                           new RazorError(\n                               String.Format(RazorResources.ParseError_Unexpected_Character_At_Start_Of_CodeBlock_CS, '\"'),\n                               1, 0, 1));\n        }\n\n        [Fact]\n        public void ParseBlockCapturesWhitespaceToEndOfLineInInvalidUsingStatementAndTreatsAsFileCode()\n        {\n            ParseBlockTest(\"using          \" + Environment.NewLine\n                         + Environment.NewLine,\n                           new StatementBlock(\n                               Factory.Code(\"using          \\r\\n\").AsStatement()\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockMethodOutputsOpenCurlyAsCodeSpanIfEofFoundAfterOpenCurlyBrace()\n        {\n            ParseBlockTest(\"{\",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.EmptyCSharp()\n                                   .AsStatement()\n                                   .With(new AutoCompleteEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString) { AutoCompleteString = \"}\" })\n                               ),\n                           new RazorError(\n                               String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF,\n                                             RazorResources.BlockName_Code,\n                                             \"}\", \"{\"),\n                               SourceLocation.Zero));\n        }\n\n        [Fact]\n        public void ParseBlockMethodOutputsZeroLengthCodeSpanIfStatementBlockEmpty()\n        {\n            ParseBlockTest(\"{}\",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.EmptyCSharp().AsStatement(),\n                               Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockMethodProducesErrorIfNewlineFollowsTransition()\n        {\n            ParseBlockTest(\"@\" + Environment.NewLine,\n                           new ExpressionBlock(\n                               Factory.CodeTransition(),\n                               Factory.EmptyCSharp()\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                           new RazorError(RazorResources.ParseError_Unexpected_WhiteSpace_At_Start_Of_CodeBlock_CS, new SourceLocation(1, 0, 1)));\n        }\n\n        [Fact]\n        public void ParseBlockMethodProducesErrorIfWhitespaceBetweenTransitionAndBlockStartInEmbeddedExpression()\n        {\n            ParseBlockTest(\"{\" + Environment.NewLine\n                         + \"    @   {}\" + Environment.NewLine\n                         + \"}\",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\"\\r\\n    \").AsStatement(),\n                               new ExpressionBlock(\n                                   Factory.CodeTransition(),\n                                   Factory.EmptyCSharp()\n                                       .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true)\n                                       .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                               Factory.Code(\"   {}\\r\\n\").AsStatement(),\n                               Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)\n                               ),\n                           new RazorError(RazorResources.ParseError_Unexpected_WhiteSpace_At_Start_Of_CodeBlock_CS, 8, 1, 5));\n        }\n\n        [Fact]\n        public void ParseBlockMethodProducesErrorIfEOFAfterTransitionInEmbeddedExpression()\n        {\n            ParseBlockTest(\"{\" + Environment.NewLine\n                         + \"    @\",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\"\\r\\n    \").AsStatement(),\n                               new ExpressionBlock(\n                                   Factory.CodeTransition(),\n                                   Factory.EmptyCSharp()\n                                       .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true)\n                                       .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                               Factory.EmptyCSharp().AsStatement()\n                               ),\n                           new RazorError(RazorResources.ParseError_Unexpected_EndOfFile_At_Start_Of_CodeBlock, 8, 1, 5),\n                           new RazorError(\n                               String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF, RazorResources.BlockName_Code, \"}\", \"{\"),\n                               SourceLocation.Zero));\n        }\n\n        [Fact]\n        public void ParseBlockMethodParsesNothingIfFirstCharacterIsNotIdentifierStartOrParenOrBrace()\n        {\n            ParseBlockTest(\"@!!!\",\n                           new ExpressionBlock(\n                               Factory.CodeTransition(),\n                               Factory.EmptyCSharp()\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                           new RazorError(\n                               String.Format(RazorResources.ParseError_Unexpected_Character_At_Start_Of_CodeBlock_CS, \"!\"),\n                               1, 0, 1));\n        }\n\n        [Fact]\n        public void ParseBlockShouldReportErrorAndTerminateAtEOFIfIfParenInExplicitExpressionUnclosed()\n        {\n            ParseBlockTest(\"(foo bar\" + Environment.NewLine\n                         + \"baz\",\n                           new ExpressionBlock(\n                               Factory.MetaCode(\"(\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\"foo bar\\r\\nbaz\").AsExpression()\n                               ),\n                           new RazorError(\n                               String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF,\n                                             RazorResources.BlockName_ExplicitExpression, ')', '('),\n                               new SourceLocation(0, 0, 0)));\n        }\n\n        [Fact]\n        public void ParseBlockShouldReportErrorAndTerminateAtMarkupIfIfParenInExplicitExpressionUnclosed()\n        {\n            ParseBlockTest(\"(foo bar\" + Environment.NewLine\n                         + \"<html>\" + Environment.NewLine\n                         + \"baz\" + Environment.NewLine\n                         + \"</html\",\n                           new ExpressionBlock(\n                               Factory.MetaCode(\"(\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\"foo bar\\r\\n\").AsExpression()\n                               ),\n                           new RazorError(\n                               String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF,\n                                             RazorResources.BlockName_ExplicitExpression, ')', '('),\n                               new SourceLocation(0, 0, 0)));\n        }\n\n        [Fact]\n        public void ParseBlockCorrectlyHandlesInCorrectTransitionsIfImplicitExpressionParensUnclosed()\n        {\n            ParseBlockTest(\"Href(\" + Environment.NewLine\n                         + \"<h1>@Html.Foo(Bar);</h1>\" + Environment.NewLine,\n                           new ExpressionBlock(\n                               Factory.Code(\"Href(\\r\\n\")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                               ),\n                           new RazorError(\n                               String.Format(RazorResources.ParseError_Expected_CloseBracket_Before_EOF,\n                                             \"(\", \")\"),\n                               new SourceLocation(4, 0, 4)));\n        }\n\n        [Fact]\n        // Test for fix to Dev10 884975 - Incorrect Error Messaging\n        public void ParseBlockShouldReportErrorAndTerminateAtEOFIfParenInImplicitExpressionUnclosed()\n        {\n            ParseBlockTest(\"Foo(Bar(Baz)\" + Environment.NewLine\n                         + \"Biz\" + Environment.NewLine\n                         + \"Boz\",\n                           new ExpressionBlock(\n                               Factory.Code(\"Foo(Bar(Baz)\\r\\nBiz\\r\\nBoz\")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                               ),\n                           new RazorError(String.Format(RazorResources.ParseError_Expected_CloseBracket_Before_EOF,\n                                                        \"(\", \")\"),\n                                          new SourceLocation(3, 0, 3)));\n        }\n\n        [Fact]\n        // Test for fix to Dev10 884975 - Incorrect Error Messaging\n        public void ParseBlockShouldReportErrorAndTerminateAtMarkupIfParenInImplicitExpressionUnclosed()\n        {\n            ParseBlockTest(\"Foo(Bar(Baz)\" + Environment.NewLine\n                         + \"Biz\" + Environment.NewLine\n                         + \"<html>\" + Environment.NewLine\n                         + \"Boz\" + Environment.NewLine\n                         + \"</html>\",\n                           new ExpressionBlock(\n                               Factory.Code(\"Foo(Bar(Baz)\\r\\nBiz\\r\\n\")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                               ),\n                           new RazorError(String.Format(RazorResources.ParseError_Expected_CloseBracket_Before_EOF,\n                                                        \"(\", \")\"),\n                                          new SourceLocation(3, 0, 3)));\n        }\n\n        [Fact]\n        // Test for fix to Dev10 884975 - Incorrect Error Messaging\n        public void ParseBlockShouldReportErrorAndTerminateAtEOFIfBracketInImplicitExpressionUnclosed()\n        {\n            ParseBlockTest(\"Foo[Bar[Baz]\" + Environment.NewLine\n                         + \"Biz\" + Environment.NewLine\n                         + \"Boz\",\n                           new ExpressionBlock(\n                               Factory.Code(\"Foo[Bar[Baz]\\r\\nBiz\\r\\nBoz\")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                               ),\n                           new RazorError(\n                               String.Format(RazorResources.ParseError_Expected_CloseBracket_Before_EOF,\n                                             \"[\", \"]\"),\n                               new SourceLocation(3, 0, 3)));\n        }\n\n        [Fact]\n        // Test for fix to Dev10 884975 - Incorrect Error Messaging\n        public void ParseBlockShouldReportErrorAndTerminateAtMarkupIfBracketInImplicitExpressionUnclosed()\n        {\n            ParseBlockTest(\"Foo[Bar[Baz]\" + Environment.NewLine\n                         + \"Biz\" + Environment.NewLine\n                         + \"<b>\" + Environment.NewLine\n                         + \"Boz\" + Environment.NewLine\n                         + \"</b>\",\n                           new ExpressionBlock(\n                               Factory.Code(\"Foo[Bar[Baz]\\r\\nBiz\\r\\n\")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                               ),\n                           new RazorError(\n                               String.Format(RazorResources.ParseError_Expected_CloseBracket_Before_EOF,\n                                             \"[\", \"]\"),\n                               new SourceLocation(3, 0, 3)));\n        }\n\n        // Simple EOF handling errors:\n        [Fact]\n        public void ParseBlockReportsErrorIfExplicitCodeBlockUnterminatedAtEOF()\n        {\n            ParseBlockTest(\"{ var foo = bar; if(foo != null) { bar(); } \",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\" var foo = bar; if(foo != null) { bar(); } \").AsStatement()\n                               ),\n                           new RazorError(\n                               String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF,\n                                             RazorResources.BlockName_Code, '}', '{'),\n                               SourceLocation.Zero));\n        }\n\n        [Fact]\n        public void ParseBlockReportsErrorIfClassBlockUnterminatedAtEOF()\n        {\n            ParseBlockTest(\"functions { var foo = bar; if(foo != null) { bar(); } \",\n                           new FunctionsBlock(\n                               Factory.MetaCode(\"functions {\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\" var foo = bar; if(foo != null) { bar(); } \").AsFunctionsBody()\n                               ),\n                           new RazorError(\n                               String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF,\n                                             \"functions\", '}', '{'),\n                               SourceLocation.Zero));\n        }\n\n        [Fact]\n        public void ParseBlockReportsErrorIfIfBlockUnterminatedAtEOF()\n        {\n            RunUnterminatedSimpleKeywordBlock(\"if\");\n        }\n\n        [Fact]\n        public void ParseBlockReportsErrorIfElseBlockUnterminatedAtEOF()\n        {\n            ParseBlockTest(\"if(foo) { baz(); } else { var foo = bar; if(foo != null) { bar(); } \",\n                           new StatementBlock(\n                               Factory.Code(\"if(foo) { baz(); } else { var foo = bar; if(foo != null) { bar(); } \").AsStatement()\n                               ),\n                           new RazorError(\n                               String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF,\n                                             \"else\", '}', '{'),\n                               new SourceLocation(19, 0, 19)));\n        }\n\n        [Fact]\n        public void ParseBlockReportsErrorIfElseIfBlockUnterminatedAtEOF()\n        {\n            ParseBlockTest(\"if(foo) { baz(); } else if { var foo = bar; if(foo != null) { bar(); } \",\n                           new StatementBlock(\n                               Factory.Code(\"if(foo) { baz(); } else if { var foo = bar; if(foo != null) { bar(); } \").AsStatement()\n                               ),\n                           new RazorError(\n                               String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF,\n                                             \"else if\", '}', '{'),\n                               new SourceLocation(19, 0, 19)));\n        }\n\n        [Fact]\n        public void ParseBlockReportsErrorIfDoBlockUnterminatedAtEOF()\n        {\n            ParseBlockTest(\"do { var foo = bar; if(foo != null) { bar(); } \",\n                           new StatementBlock(\n                               Factory.Code(\"do { var foo = bar; if(foo != null) { bar(); } \").AsStatement()\n                               ),\n                           new RazorError(\n                               String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF,\n                                             \"do\", '}', '{'),\n                               SourceLocation.Zero));\n        }\n\n        [Fact]\n        public void ParseBlockReportsErrorIfTryBlockUnterminatedAtEOF()\n        {\n            ParseBlockTest(\"try { var foo = bar; if(foo != null) { bar(); } \",\n                           new StatementBlock(\n                               Factory.Code(\"try { var foo = bar; if(foo != null) { bar(); } \").AsStatement()\n                               ),\n                           new RazorError(\n                               String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF,\n                                             \"try\", '}', '{'),\n                               SourceLocation.Zero));\n        }\n\n        [Fact]\n        public void ParseBlockReportsErrorIfCatchBlockUnterminatedAtEOF()\n        {\n            ParseBlockTest(\"try { baz(); } catch(Foo) { var foo = bar; if(foo != null) { bar(); } \",\n                           new StatementBlock(\n                               Factory.Code(\"try { baz(); } catch(Foo) { var foo = bar; if(foo != null) { bar(); } \").AsStatement()\n                               ),\n                           new RazorError(\n                               String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF,\n                                             \"catch\", '}', '{'),\n                               new SourceLocation(15, 0, 15)));\n        }\n\n        [Fact]\n        public void ParseBlockReportsErrorIfFinallyBlockUnterminatedAtEOF()\n        {\n            ParseBlockTest(\"try { baz(); } finally { var foo = bar; if(foo != null) { bar(); } \",\n                           new StatementBlock(\n                               Factory.Code(\"try { baz(); } finally { var foo = bar; if(foo != null) { bar(); } \").AsStatement()\n                               ),\n                           new RazorError(\n                               String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF,\n                                             \"finally\", '}', '{'),\n                               new SourceLocation(15, 0, 15)));\n        }\n\n        [Fact]\n        public void ParseBlockReportsErrorIfForBlockUnterminatedAtEOF()\n        {\n            RunUnterminatedSimpleKeywordBlock(\"for\");\n        }\n\n        [Fact]\n        public void ParseBlockReportsErrorIfForeachBlockUnterminatedAtEOF()\n        {\n            RunUnterminatedSimpleKeywordBlock(\"foreach\");\n        }\n\n        [Fact]\n        public void ParseBlockReportsErrorIfWhileBlockUnterminatedAtEOF()\n        {\n            RunUnterminatedSimpleKeywordBlock(\"while\");\n        }\n\n        [Fact]\n        public void ParseBlockReportsErrorIfSwitchBlockUnterminatedAtEOF()\n        {\n            RunUnterminatedSimpleKeywordBlock(\"switch\");\n        }\n\n        [Fact]\n        public void ParseBlockReportsErrorIfLockBlockUnterminatedAtEOF()\n        {\n            RunUnterminatedSimpleKeywordBlock(\"lock\");\n        }\n\n        [Fact]\n        public void ParseBlockReportsErrorIfUsingBlockUnterminatedAtEOF()\n        {\n            RunUnterminatedSimpleKeywordBlock(\"using\");\n        }\n\n        [Fact]\n        public void ParseBlockRequiresControlFlowStatementsToHaveBraces()\n        {\n            string expectedMessage = String.Format(RazorResources.ParseError_SingleLine_ControlFlowStatements_Not_Allowed, \"{\", \"<\");\n            ParseBlockTest(\"if(foo) <p>Bar</p> else if(bar) <p>Baz</p> else <p>Boz</p>\",\n                           new StatementBlock(\n                               Factory.Code(\"if(foo) \").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\"<p>Bar</p> \").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\"else if(bar) \").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\"<p>Baz</p> \").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\"else \").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\"<p>Boz</p>\").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.EmptyCSharp().AsStatement()\n                               ),\n                           new RazorError(expectedMessage, 8, 0, 8),\n                           new RazorError(expectedMessage, 32, 0, 32),\n                           new RazorError(expectedMessage, 48, 0, 48));\n        }\n\n        [Fact]\n        public void ParseBlockIncludesUnexpectedCharacterInSingleStatementControlFlowStatementError()\n        {\n            ParseBlockTest(\"if(foo)) { var bar = foo; }\",\n                           new StatementBlock(\n                               Factory.Code(\"if(foo)) { var bar = foo; }\").AsStatement()\n                               ),\n                           new RazorError(\n                               String.Format(RazorResources.ParseError_SingleLine_ControlFlowStatements_Not_Allowed,\n                                             \"{\", \")\"),\n                               new SourceLocation(7, 0, 7)));\n        }\n\n        [Fact]\n        public void ParseBlockOutputsErrorIfAtSignFollowedByLessThanSignAtStatementStart()\n        {\n            ParseBlockTest(\"if(foo) { @<p>Bar</p> }\",\n                           new StatementBlock(\n                               Factory.Code(\"if(foo) {\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\" \"),\n                                   Factory.MarkupTransition(),\n                                   Factory.Markup(\"<p>Bar</p> \").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\"}\").AsStatement()\n                               ),\n                           new RazorError(\n                               RazorResources.ParseError_AtInCode_Must_Be_Followed_By_Colon_Paren_Or_Identifier_Start,\n                               10, 0, 10));\n        }\n\n        [Fact]\n        public void ParseBlockTerminatesIfBlockAtEOLWhenRecoveringFromMissingCloseParen()\n        {\n            ParseBlockTest(\"if(foo bar\" + Environment.NewLine\n                         + \"baz\",\n                           new StatementBlock(\n                               Factory.Code(\"if(foo bar\\r\\n\").AsStatement()\n                               ),\n                           new RazorError(\n                               String.Format(RazorResources.ParseError_Expected_CloseBracket_Before_EOF,\n                                             \"(\", \")\"),\n                               new SourceLocation(2, 0, 2)));\n        }\n\n        [Fact]\n        public void ParseBlockTerminatesForeachBlockAtEOLWhenRecoveringFromMissingCloseParen()\n        {\n            ParseBlockTest(\"foreach(foo bar\" + Environment.NewLine\n                         + \"baz\",\n                           new StatementBlock(\n                               Factory.Code(\"foreach(foo bar\\r\\n\").AsStatement()\n                               ),\n                           new RazorError(\n                               String.Format(RazorResources.ParseError_Expected_CloseBracket_Before_EOF,\n                                             \"(\", \")\"),\n                               new SourceLocation(7, 0, 7)));\n        }\n\n        [Fact]\n        public void ParseBlockTerminatesWhileClauseInDoStatementAtEOLWhenRecoveringFromMissingCloseParen()\n        {\n            ParseBlockTest(\"do { } while(foo bar\" + Environment.NewLine\n                         + \"baz\",\n                           new StatementBlock(\n                               Factory.Code(\"do { } while(foo bar\\r\\n\").AsStatement()\n                               ),\n                           new RazorError(\n                               String.Format(RazorResources.ParseError_Expected_CloseBracket_Before_EOF,\n                                             \"(\", \")\"),\n                               new SourceLocation(12, 0, 12)));\n        }\n\n        [Fact]\n        public void ParseBlockTerminatesUsingBlockAtEOLWhenRecoveringFromMissingCloseParen()\n        {\n            ParseBlockTest(\"using(foo bar\" + Environment.NewLine\n                         + \"baz\",\n                           new StatementBlock(\n                               Factory.Code(\"using(foo bar\\r\\n\").AsStatement()\n                               ),\n                           new RazorError(\n                               String.Format(RazorResources.ParseError_Expected_CloseBracket_Before_EOF,\n                                             \"(\", \")\"),\n                               new SourceLocation(5, 0, 5)));\n        }\n\n        [Fact]\n        public void ParseBlockResumesIfStatementAfterOpenParen()\n        {\n            ParseBlockTest(\"if(\" + Environment.NewLine\n                         + \"else { <p>Foo</p> }\",\n                           new StatementBlock(\n                               Factory.Code(\"if(\\r\\nelse {\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\" <p>Foo</p> \").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\"}\").AsStatement().Accepts(AcceptedCharacters.None)\n                               ),\n                           new RazorError(\n                               String.Format(RazorResources.ParseError_Expected_CloseBracket_Before_EOF,\n                                             \"(\", \")\"),\n                               new SourceLocation(2, 0, 2)));\n        }\n\n        [Fact]\n        public void ParseBlockTerminatesNormalCSharpStringsAtEOLIfEndQuoteMissing()\n        {\n            SingleSpanBlockTest(\"if(foo) {\" + Environment.NewLine\n                              + \"    var p = \\\"foo bar baz\" + Environment.NewLine\n                              + \";\" + Environment.NewLine\n                              + \"}\",\n                                BlockType.Statement, SpanKind.Code,\n                                new RazorError(RazorResources.ParseError_Unterminated_String_Literal, 23, 1, 12));\n        }\n\n        [Fact]\n        public void ParseBlockTerminatesNormalStringAtEndOfFile()\n        {\n            SingleSpanBlockTest(\"if(foo) { var foo = \\\"blah blah blah blah blah\", BlockType.Statement, SpanKind.Code,\n                                new RazorError(RazorResources.ParseError_Unterminated_String_Literal, 20, 0, 20),\n                                new RazorError(String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF, \"if\", '}', '{'), SourceLocation.Zero));\n        }\n\n        [Fact]\n        public void ParseBlockTerminatesVerbatimStringAtEndOfFile()\n        {\n            SingleSpanBlockTest(\"if(foo) { var foo = @\\\"blah \" + Environment.NewLine\n                              + \"blah; \" + Environment.NewLine\n                              + \"<p>Foo</p>\" + Environment.NewLine\n                              + \"blah \" + Environment.NewLine\n                              + \"blah\",\n                                BlockType.Statement, SpanKind.Code,\n                                new RazorError(RazorResources.ParseError_Unterminated_String_Literal, 20, 0, 20),\n                                new RazorError(String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF, \"if\", '}', '{'), SourceLocation.Zero));\n        }\n\n        [Fact]\n        public void ParseBlockCorrectlyParsesMarkupIncorrectyAssumedToBeWithinAStatement()\n        {\n            ParseBlockTest(\"if(foo) {\" + Environment.NewLine\n                         + \"    var foo = \\\"foo bar baz\" + Environment.NewLine\n                         + \"    <p>Foo is @foo</p>\" + Environment.NewLine\n                         + \"}\",\n                           new StatementBlock(\n                               Factory.Code(\"if(foo) {\\r\\n    var foo = \\\"foo bar baz\\r\\n    \").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\"<p>Foo is \"),\n                                   new ExpressionBlock(\n                                       Factory.CodeTransition(),\n                                       Factory.Code(\"foo\")\n                                           .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                           .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                                   Factory.Markup(\"</p>\\r\\n\").Accepts(AcceptedCharacters.None)),\n                               Factory.Code(\"}\").AsStatement()\n                               ),\n                           new RazorError(\n                               RazorResources.ParseError_Unterminated_String_Literal,\n                               25, 1, 14));\n        }\n\n        [Fact]\n        public void ParseBlockCorrectlyParsesAtSignInDelimitedBlock()\n        {\n            ParseBlockTest(\"(Request[\\\"description\\\"] ?? @photo.Description)\",\n                           new ExpressionBlock(\n                               Factory.MetaCode(\"(\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\"Request[\\\"description\\\"] ?? @photo.Description\").AsExpression(),\n                               Factory.MetaCode(\")\").Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockCorrectlyRecoversFromMissingCloseParenInExpressionWithinCode()\n        {\n            ParseBlockTest(@\"{String.Format(<html></html>}\",\n                new StatementBlock(\n                    Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"String.Format(\")\n                           .AsStatement(),\n                    new MarkupBlock(\n                        Factory.Markup(\"<html></html>\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyCSharp().AsStatement(),\n                    Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                expectedErrors: new[] {\n                    new RazorError(\n                        String.Format(RazorResources.ParseError_Expected_CloseBracket_Before_EOF, \"(\", \")\"),\n                        14, 0, 14)\n                });\n\n        }\n\n        private void RunUnterminatedSimpleKeywordBlock(string keyword)\n        {\n            SingleSpanBlockTest(keyword + \" (foo) { var foo = bar; if(foo != null) { bar(); } \", BlockType.Statement, SpanKind.Code,\n                                new RazorError(String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF, keyword, '}', '{'), SourceLocation.Zero));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/CSharp/CSharpExplicitExpressionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.CSharp\n{\n    public class CSharpExplicitExpressionTest : CsHtmlCodeParserTestBase\n    {\n        [Fact]\n        public void ParseBlockShouldOutputZeroLengthCodeSpanIfExplicitExpressionIsEmpty()\n        {\n            ParseBlockTest(\"@()\",\n                           new ExpressionBlock(\n                               Factory.CodeTransition(),\n                               Factory.MetaCode(\"(\").Accepts(AcceptedCharacters.None),\n                               Factory.EmptyCSharp().AsExpression(),\n                               Factory.MetaCode(\")\").Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockShouldOutputZeroLengthCodeSpanIfEOFOccursAfterStartOfExplicitExpression()\n        {\n            ParseBlockTest(\"@(\",\n                           new ExpressionBlock(\n                               Factory.CodeTransition(),\n                               Factory.MetaCode(\"(\").Accepts(AcceptedCharacters.None),\n                               Factory.EmptyCSharp().AsExpression()\n                               ),\n                           new RazorError(\n                               String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF,\n                                             RazorResources.BlockName_ExplicitExpression,\n                                             \")\", \"(\"),\n                               new SourceLocation(1, 0, 1)));\n        }\n\n        [Fact]\n        public void ParseBlockShouldAcceptEscapedQuoteInNonVerbatimStrings()\n        {\n            ParseBlockTest(\"@(\\\"\\\\\\\"\\\")\",\n                           new ExpressionBlock(\n                               Factory.CodeTransition(),\n                               Factory.MetaCode(\"(\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\"\\\"\\\\\\\"\\\"\").AsExpression(),\n                               Factory.MetaCode(\")\").Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockShouldAcceptEscapedQuoteInVerbatimStrings()\n        {\n            ParseBlockTest(\"@(@\\\"\\\"\\\"\\\")\",\n                           new ExpressionBlock(\n                               Factory.CodeTransition(),\n                               Factory.MetaCode(\"(\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\"@\\\"\\\"\\\"\\\"\").AsExpression(),\n                               Factory.MetaCode(\")\").Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockShouldAcceptMultipleRepeatedEscapedQuoteInVerbatimStrings()\n        {\n            ParseBlockTest(\"@(@\\\"\\\"\\\"\\\"\\\"\\\")\",\n                           new ExpressionBlock(\n                               Factory.CodeTransition(),\n                               Factory.MetaCode(\"(\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\"@\\\"\\\"\\\"\\\"\\\"\\\"\").AsExpression(),\n                               Factory.MetaCode(\")\").Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockShouldAcceptMultiLineVerbatimStrings()\n        {\n            ParseBlockTest(@\"@(@\"\"\" + Environment.NewLine\n                         + @\"Foo\" + Environment.NewLine\n                         + @\"Bar\" + Environment.NewLine\n                         + @\"Baz\" + Environment.NewLine\n                         + @\"\"\")\",\n                           new ExpressionBlock(\n                               Factory.CodeTransition(),\n                               Factory.MetaCode(\"(\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\"@\\\"\\r\\nFoo\\r\\nBar\\r\\nBaz\\r\\n\\\"\").AsExpression(),\n                               Factory.MetaCode(\")\").Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockShouldAcceptMultipleEscapedQuotesInNonVerbatimStrings()\n        {\n            ParseBlockTest(\"@(\\\"\\\\\\\"hello, world\\\\\\\"\\\")\",\n                           new ExpressionBlock(\n                               Factory.CodeTransition(),\n                               Factory.MetaCode(\"(\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\"\\\"\\\\\\\"hello, world\\\\\\\"\\\"\").AsExpression(),\n                               Factory.MetaCode(\")\").Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockShouldAcceptMultipleEscapedQuotesInVerbatimStrings()\n        {\n            ParseBlockTest(\"@(@\\\"\\\"\\\"hello, world\\\"\\\"\\\")\",\n                           new ExpressionBlock(\n                               Factory.CodeTransition(),\n                               Factory.MetaCode(\"(\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\"@\\\"\\\"\\\"hello, world\\\"\\\"\\\"\").AsExpression(),\n                               Factory.MetaCode(\")\").Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockShouldAcceptConsecutiveEscapedQuotesInNonVerbatimStrings()\n        {\n            ParseBlockTest(\"@(\\\"\\\\\\\"\\\\\\\"\\\")\",\n                           new ExpressionBlock(\n                               Factory.CodeTransition(),\n                               Factory.MetaCode(\"(\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\"\\\"\\\\\\\"\\\\\\\"\\\"\").AsExpression(),\n                               Factory.MetaCode(\")\").Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockShouldAcceptConsecutiveEscapedQuotesInVerbatimStrings()\n        {\n            ParseBlockTest(\"@(@\\\"\\\"\\\"\\\"\\\"\\\")\",\n                           new ExpressionBlock(\n                               Factory.CodeTransition(),\n                               Factory.MetaCode(\"(\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\"@\\\"\\\"\\\"\\\"\\\"\\\"\").AsExpression(),\n                               Factory.MetaCode(\")\").Accepts(AcceptedCharacters.None)\n                               ));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/CSharp/CSharpHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.CSharp\n{\n    public class CSharpHelperTest : CsHtmlMarkupParserTestBase\n    {\n        [Fact]\n        public void ParseHelperCorrectlyParsesHelperWithNoSpaceInBody()\n        {\n            ParseDocumentTest(\"@helper Foo(){@Bar()}\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"Foo(){\", 8, 0, 8), headerComplete: true),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"helper \").Accepts(AcceptedCharacters.None),\n                        Factory.Code(\"Foo(){\").Hidden().Accepts(AcceptedCharacters.None),\n                        new StatementBlock(\n                            Factory.EmptyCSharp().AsStatement(),\n                            new ExpressionBlock(\n                                Factory.CodeTransition(),\n                                Factory.Code(\"Bar()\")\n                                    .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true)\n                                    .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                            Factory.EmptyCSharp().AsStatement()),\n                        Factory.Code(\"}\").Hidden().Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void ParseHelperCorrectlyParsesIncompleteHelperPreceedingCodeBlock()\n        {\n            ParseDocumentTest(\"@helper\" + Environment.NewLine\n                            + \"@{}\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"helper\")),\n                    Factory.Markup(\"\\r\\n\"),\n                    new StatementBlock(\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                        Factory.EmptyCSharp().AsStatement(),\n                        Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()),\n                new RazorError(\n                    String.Format(\n                        RazorResources.ParseError_Unexpected_Character_At_Helper_Name_Start,\n                        RazorResources.ErrorComponent_Newline),\n                    7, 0, 7));\n        }\n\n        [Fact]\n        public void ParseHelperRequiresSpaceBeforeSignature()\n        {\n            ParseDocumentTest(\"@helper{\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"helper\")),\n                    Factory.Markup(\"{\")),\n                new RazorError(\n                    String.Format(\n                        RazorResources.ParseError_Unexpected_Character_At_Helper_Name_Start,\n                        String.Format(RazorResources.ErrorComponent_Character, \"{\")),\n                    7, 0, 7));\n        }\n\n        [Fact]\n        public void ParseHelperOutputsErrorButContinuesIfLParenFoundAfterHelperKeyword()\n        {\n            ParseDocumentTest(\"@helper () {\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"() {\", 8, 0, 8), headerComplete: true),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"helper \").Accepts(AcceptedCharacters.None),\n                        Factory.Code(\"() {\").Hidden().Accepts(AcceptedCharacters.None),\n                        new StatementBlock(\n                            Factory.EmptyCSharp()\n                                   .AsStatement()\n                                   .AutoCompleteWith(\"}\")))),\n                new RazorError(\n                    String.Format(\n                        RazorResources.ParseError_Unexpected_Character_At_Helper_Name_Start,\n                        String.Format(RazorResources.ErrorComponent_Character, \"(\")),\n                    8, 0, 8),\n                new RazorError(\n                    String.Format(\n                        RazorResources.ParseError_Expected_EndOfBlock_Before_EOF,\n                        \"helper\", \"}\", \"{\"),\n                    1, 0, 1));\n        }\n\n        [Fact]\n        public void ParseHelperStatementOutputsMarkerHelperHeaderSpanOnceKeywordComplete()\n        {\n            ParseDocumentTest(\"@helper \",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(String.Empty, 8, 0, 8), headerComplete: false),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"helper \").Accepts(AcceptedCharacters.None),\n                        Factory.EmptyCSharp().Hidden())),\n                new RazorError(\n                    String.Format(\n                        RazorResources.ParseError_Unexpected_Character_At_Helper_Name_Start,\n                        RazorResources.ErrorComponent_EndOfFile),\n                    8, 0, 8));\n        }\n\n        [Fact]\n        public void ParseHelperStatementMarksHelperSpanAsCanGrowIfMissingTrailingSpace()\n        {\n            ParseDocumentTest(\"@helper\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"helper\").Accepts(AcceptedCharacters.Any))),\n                new RazorError(\n                    String.Format(\n                        RazorResources.ParseError_Unexpected_Character_At_Helper_Name_Start,\n                        RazorResources.ErrorComponent_EndOfFile),\n                    7, 0, 7));\n        }\n\n        [Fact]\n        public void ParseHelperStatementCapturesWhitespaceToEndOfLineIfHelperStatementMissingName()\n        {\n            ParseDocumentTest(\"@helper                       \" + Environment.NewLine\n                            + \"    \",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"                      \", 8, 0, 8), headerComplete: false),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"helper \").Accepts(AcceptedCharacters.None),\n                        Factory.Code(\"                      \\r\\n\").Hidden()),\n                    Factory.Markup(@\"    \")),\n                new RazorError(\n                    String.Format(\n                        RazorResources.ParseError_Unexpected_Character_At_Helper_Name_Start,\n                        RazorResources.ErrorComponent_Newline),\n                    30, 0, 30));\n        }\n\n        [Fact]\n        public void ParseHelperStatementCapturesWhitespaceToEndOfLineIfHelperStatementMissingOpenParen()\n        {\n            ParseDocumentTest(\"@helper Foo    \" + Environment.NewLine\n                            + \"    \",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"Foo    \", 8, 0, 8), headerComplete: false),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"helper \").Accepts(AcceptedCharacters.None),\n                        Factory.Code(\"Foo    \\r\\n\").Hidden()),\n                    Factory.Markup(\"    \")),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_MissingCharAfterHelperName, \"(\"),\n                    15, 0, 15));\n        }\n\n        [Fact]\n        public void ParseHelperStatementCapturesAllContentToEndOfFileIfHelperStatementMissingCloseParenInParameterList()\n        {\n            ParseDocumentTest(\"@helper Foo(Foo Bar\" + Environment.NewLine\n                            + \"Biz\" + Environment.NewLine\n                            + \"Boz\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"Foo(Foo Bar\\r\\nBiz\\r\\nBoz\", 8, 0, 8), headerComplete: false),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"helper \").Accepts(AcceptedCharacters.None),\n                        Factory.Code(\"Foo(Foo Bar\\r\\nBiz\\r\\nBoz\").Hidden())),\n                new RazorError(\n                    RazorResources.ParseError_UnterminatedHelperParameterList,\n                    11, 0, 11));\n        }\n\n        [Fact]\n        public void ParseHelperStatementCapturesWhitespaceToEndOfLineIfHelperStatementMissingOpenBraceAfterParameterList()\n        {\n            ParseDocumentTest(\"@helper Foo(string foo)    \" + Environment.NewLine,\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"Foo(string foo)    \", 8, 0, 8), headerComplete: false),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"helper \").Accepts(AcceptedCharacters.None),\n                        Factory.Code(\"Foo(string foo)    \\r\\n\").Hidden())),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_MissingCharAfterHelperParameters, \"{\"),\n                    29, 1, 0));\n        }\n\n        [Fact]\n        public void ParseHelperStatementContinuesParsingHelperUntilEOF()\n        {\n            ParseDocumentTest(\"@helper Foo(string foo) {    \" + Environment.NewLine\n                            + \"    <p>Foo</p>\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"Foo(string foo) {\", 8, 0, 8), headerComplete: true),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"helper \").Accepts(AcceptedCharacters.None),\n                        Factory.Code(@\"Foo(string foo) {\").Hidden().Accepts(AcceptedCharacters.None),\n                        new StatementBlock(\n                            Factory.Code(\"    \\r\\n\")\n                                   .AsStatement()\n                                   .AutoCompleteWith(\"}\"),\n                            new MarkupBlock(\n                                Factory.Markup(\"    <p>Foo</p>\").Accepts(AcceptedCharacters.None)),\n                            Factory.EmptyCSharp().AsStatement()))),\n                new RazorError(\n                    String.Format(\n                        RazorResources.ParseError_Expected_EndOfBlock_Before_EOF,\n                        \"helper\", \"}\", \"{\"),\n                    1, 0, 1));\n        }\n\n        [Fact]\n        public void ParseHelperStatementCorrectlyParsesHelperWithEmbeddedCode()\n        {\n            ParseDocumentTest(\"@helper Foo(string foo) {    \" + Environment.NewLine\n                            + \"    <p>@foo</p>\" + Environment.NewLine\n                            + \"}\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"Foo(string foo) {\", 8, 0, 8), headerComplete: true),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"helper \").Accepts(AcceptedCharacters.None),\n                        Factory.Code(@\"Foo(string foo) {\").Hidden().Accepts(AcceptedCharacters.None),\n                        new StatementBlock(\n                            Factory.Code(\"    \\r\\n\").AsStatement(),\n                            new MarkupBlock(\n                                Factory.Markup(\"    <p>\"),\n                                new ExpressionBlock(\n                                    Factory.CodeTransition(),\n                                    Factory.Code(\"foo\")\n                                           .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                           .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                                Factory.Markup(\"</p>\\r\\n\").Accepts(AcceptedCharacters.None)),\n                            Factory.EmptyCSharp().AsStatement()),\n                        Factory.Code(\"}\").Hidden().Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void ParseHelperStatementCorrectlyParsesHelperWithNewlinesBetweenCloseParenAndOpenBrace()\n        {\n            ParseDocumentTest(\"@helper Foo(string foo)\" + Environment.NewLine\n                            + Environment.NewLine\n                            + Environment.NewLine\n                            + Environment.NewLine\n                            + \"{    \" + Environment.NewLine\n                            + \"    <p>@foo</p>\" + Environment.NewLine\n                            + \"}\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"Foo(string foo)\\r\\n\\r\\n\\r\\n\\r\\n{\", 8, 0, 8), headerComplete: true),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"helper \").Accepts(AcceptedCharacters.None),\n                        Factory.Code(\"Foo(string foo)\\r\\n\\r\\n\\r\\n\\r\\n{\").Hidden().Accepts(AcceptedCharacters.None),\n                        new StatementBlock(\n                            Factory.Code(\"    \\r\\n\").AsStatement(),\n                            new MarkupBlock(\n                                Factory.Markup(@\"    <p>\"),\n                                new ExpressionBlock(\n                                    Factory.CodeTransition(),\n                                    Factory.Code(\"foo\")\n                                           .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                           .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                                Factory.Markup(\"</p>\\r\\n\").Accepts(AcceptedCharacters.None)),\n                            Factory.EmptyCSharp().AsStatement()),\n                        Factory.Code(\"}\").Hidden().Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void ParseHelperStatementGivesWhitespaceAfterOpenBraceToMarkupInDesignMode()\n        {\n            ParseDocumentTest(\"@helper Foo(string foo) {    \" + Environment.NewLine\n                            + \"    \",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"Foo(string foo) {\", 8, 0, 8), headerComplete: true),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"helper \").Accepts(AcceptedCharacters.None),\n                        Factory.Code(@\"Foo(string foo) {\").Hidden().Accepts(AcceptedCharacters.None),\n                        new StatementBlock(\n                            Factory.Code(\"    \\r\\n    \")\n                                   .AsStatement()\n                                   .AutoCompleteWith(\"}\")))),\n                designTimeParser: true,\n                expectedErrors: new[]\n                {\n                    new RazorError(\n                        String.Format(\n                            RazorResources.ParseError_Expected_EndOfBlock_Before_EOF, \n                            \"helper\", \"}\", \"{\"),\n                        new SourceLocation(1, 0, 1))\n                });\n        }\n\n        [Fact]\n        public void ParseHelperAcceptsNestedHelpersButOutputsError()\n        {\n            ParseDocumentTest(@\"@helper Foo(string foo) {\" + Environment.NewLine\n                            + \"    @helper Bar(string baz) {\" + Environment.NewLine\n                            + \"    }\" + Environment.NewLine\n                            + \"}\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"Foo(string foo) {\", 8, 0, 8), headerComplete: true),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"helper \").Accepts(AcceptedCharacters.None),\n                        Factory.Code(@\"Foo(string foo) {\").Hidden().Accepts(AcceptedCharacters.None),\n                        new StatementBlock(\n                            Factory.Code(\"\\r\\n    \").AsStatement(),\n                            new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"Bar(string baz) {\", 39, 1, 12), headerComplete: true),\n                                Factory.CodeTransition(),\n                                Factory.MetaCode(\"helper \").Accepts(AcceptedCharacters.None),\n                                Factory.Code(@\"Bar(string baz) {\").Hidden().Accepts(AcceptedCharacters.None),\n                                new StatementBlock(\n                                    Factory.Code(\"\\r\\n    \").AsStatement()),\n                                Factory.Code(\"}\").Hidden().Accepts(AcceptedCharacters.None)),\n                            Factory.Code(\"\\r\\n\").AsStatement()),\n                        Factory.Code(\"}\").Hidden().Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()),\n                designTimeParser: true,\n                expectedErrors: new[]\n                {\n                    new RazorError(RazorResources.ParseError_Helpers_Cannot_Be_Nested, 38, 1, 11)\n                });\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/CSharp/CSharpImplicitExpressionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.CSharp\n{\n    public class CSharpImplicitExpressionTest : CsHtmlCodeParserTestBase\n    {\n        private const string TestExtraKeyword = \"model\";\n\n        public override ParserBase CreateCodeParser()\n        {\n            return new CSharpCodeParser();\n        }\n\n        [Fact]\n        public void NestedImplicitExpression()\n        {\n            ParseBlockTest(\"if (true) { @foo }\",\n                           new StatementBlock(\n                               Factory.Code(\"if (true) { \").AsStatement(),\n                               new ExpressionBlock(\n                                   Factory.CodeTransition(),\n                                   Factory.Code(\"foo\")\n                                       .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true)\n                                       .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                               Factory.Code(\" }\").AsStatement()));\n        }\n\n        [Fact]\n        public void ParseBlockAcceptsNonEnglishCharactersThatAreValidIdentifiers()\n        {\n            ImplicitExpressionTest(\"हळूँजद॔.\", \"हळूँजद॔\");\n        }\n\n        [Fact]\n        public void ParseBlockOutputsZeroLengthCodeSpanIfInvalidCharacterFollowsTransition()\n        {\n            ParseBlockTest(\"@/\",\n                           new ExpressionBlock(\n                               Factory.CodeTransition(),\n                               Factory.EmptyCSharp()\n                                   .AsImplicitExpression(KeywordSet)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                           new RazorError(\n                               String.Format(RazorResources.ParseError_Unexpected_Character_At_Start_Of_CodeBlock_CS, \"/\"),\n                               new SourceLocation(1, 0, 1)));\n        }\n\n        [Fact]\n        public void ParseBlockOutputsZeroLengthCodeSpanIfEOFOccursAfterTransition()\n        {\n            ParseBlockTest(\"@\",\n                           new ExpressionBlock(\n                               Factory.CodeTransition(),\n                               Factory.EmptyCSharp()\n                                   .AsImplicitExpression(KeywordSet)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                           new RazorError(\n                               RazorResources.ParseError_Unexpected_EndOfFile_At_Start_Of_CodeBlock,\n                               new SourceLocation(1, 0, 1)));\n        }\n\n        [Fact]\n        public void ParseBlockSupportsSlashesWithinComplexImplicitExpressions()\n        {\n            ImplicitExpressionTest(\"DataGridColumn.Template(\\\"Years of Service\\\", e => (int)Math.Round((DateTime.Now - dt).TotalDays / 365))\");\n        }\n\n        [Fact]\n        public void ParseBlockMethodParsesSingleIdentifierAsImplicitExpression()\n        {\n            ImplicitExpressionTest(\"foo\");\n        }\n\n        [Fact]\n        public void ParseBlockMethodDoesNotAcceptSemicolonIfExpressionTerminatedByWhitespace()\n        {\n            ImplicitExpressionTest(\"foo ;\", \"foo\");\n        }\n\n        [Fact]\n        public void ParseBlockMethodIgnoresSemicolonAtEndOfSimpleImplicitExpression()\n        {\n            RunTrailingSemicolonTest(\"foo\");\n        }\n\n        [Fact]\n        public void ParseBlockMethodParsesDottedIdentifiersAsImplicitExpression()\n        {\n            ImplicitExpressionTest(\"foo.bar.baz\");\n        }\n\n        [Fact]\n        public void ParseBlockMethodIgnoresSemicolonAtEndOfDottedIdentifiers()\n        {\n            RunTrailingSemicolonTest(\"foo.bar.baz\");\n        }\n\n        [Fact]\n        public void ParseBlockMethodDoesNotIncludeDotAtEOFInImplicitExpression()\n        {\n            ImplicitExpressionTest(\"foo.bar.\", \"foo.bar\");\n        }\n\n        [Fact]\n        public void ParseBlockMethodDoesNotIncludeDotFollowedByInvalidIdentifierCharacterInImplicitExpression()\n        {\n            ImplicitExpressionTest(\"foo.bar.0\", \"foo.bar\");\n            ImplicitExpressionTest(\"foo.bar.</p>\", \"foo.bar\");\n        }\n\n        [Fact]\n        public void ParseBlockMethodDoesNotIncludeSemicolonAfterDot()\n        {\n            ImplicitExpressionTest(\"foo.bar.;\", \"foo.bar\");\n        }\n\n        [Fact]\n        public void ParseBlockMethodTerminatesAfterIdentifierUnlessFollowedByDotOrParenInImplicitExpression()\n        {\n            ImplicitExpressionTest(\"foo.bar</p>\", \"foo.bar\");\n        }\n\n        [Fact]\n        public void ParseBlockProperlyParsesParenthesesAndBalancesThemInImplicitExpression()\n        {\n            ImplicitExpressionTest(@\"foo().bar(\"\"bi\\\"\"z\"\", 4)(\"\"chained method; call\"\").baz(@\"\"bo\"\"\"\"z\"\", '\\'', () => { return 4; }, (4+5+new { foo = bar[4] }))\");\n        }\n\n        [Fact]\n        public void ParseBlockProperlyParsesBracketsAndBalancesThemInImplicitExpression()\n        {\n            ImplicitExpressionTest(@\"foo.bar[4 * (8 + 7)][\"\"fo\\\"\"o\"\"].baz\");\n        }\n\n        [Fact]\n        public void ParseBlockTerminatesImplicitExpressionAtHtmlEndTag()\n        {\n            ImplicitExpressionTest(\"foo().bar.baz</p>zoop\", \"foo().bar.baz\");\n        }\n\n        [Fact]\n        public void ParseBlockTerminatesImplicitExpressionAtHtmlStartTag()\n        {\n            ImplicitExpressionTest(\"foo().bar.baz<p>zoop\", \"foo().bar.baz\");\n        }\n\n        [Fact]\n        public void ParseBlockTerminatesImplicitExpressionBeforeDotIfDotNotFollowedByIdentifierStartCharacter()\n        {\n            ImplicitExpressionTest(\"foo().bar.baz.42\", \"foo().bar.baz\");\n        }\n\n        [Fact]\n        public void ParseBlockStopsBalancingParenthesesAtEOF()\n        {\n            ImplicitExpressionTest(\"foo(()\", \"foo(()\",\n                                   acceptedCharacters: AcceptedCharacters.Any,\n                                   errors: new RazorError(String.Format(RazorResources.ParseError_Expected_CloseBracket_Before_EOF, \"(\", \")\"), new SourceLocation(4, 0, 4)));\n        }\n\n        [Fact]\n        public void ParseBlockTerminatesImplicitExpressionIfCloseParenFollowedByAnyWhiteSpace()\n        {\n            ImplicitExpressionTest(\"foo.bar() (baz)\", \"foo.bar()\");\n        }\n\n        [Fact]\n        public void ParseBlockTerminatesImplicitExpressionIfIdentifierFollowedByAnyWhiteSpace()\n        {\n            ImplicitExpressionTest(\"foo .bar() (baz)\", \"foo\");\n        }\n\n        [Fact]\n        public void ParseBlockTerminatesImplicitExpressionAtLastValidPointIfDotFollowedByWhitespace()\n        {\n            ImplicitExpressionTest(\"foo. bar() (baz)\", \"foo\");\n        }\n\n        [Fact]\n        public void ParseBlockOutputExpressionIfModuleTokenNotFollowedByBrace()\n        {\n            ImplicitExpressionTest(\"module.foo()\");\n        }\n\n        private void RunTrailingSemicolonTest(string expr)\n        {\n            ParseBlockTest(SyntaxConstants.TransitionString + expr + \";\",\n                           new ExpressionBlock(\n                               Factory.CodeTransition(),\n                               Factory.Code(expr)\n                                   .AsImplicitExpression(KeywordSet)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)\n                               ));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/CSharp/CSharpLayoutDirectiveTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Editor;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Framework;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.CSharp\n{\n    public class CSharpLayoutDirectiveTest : CsHtmlCodeParserTestBase\n    {\n        [Theory]\n        [InlineData(\"Layout\")]\n        [InlineData(\"LAYOUT\")]\n        [InlineData(\"layOut\")]\n        [InlineData(\"LayOut\")]\n        private void LayoutKeywordIsCaseSensitive(string word)\n        {\n            ParseBlockTest(word,\n                new ExpressionBlock(\n                    Factory.Code(word)\n                        .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                        .Accepts(AcceptedCharacters.NonWhiteSpace)\n                    ));\n        }\n\n        [Fact]\n        public void LayoutDirectiveAcceptsAllTextToEndOfLine()\n        {\n            ParseBlockTest(\"@layout Foo Bar Baz\",\n                new DirectiveBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"layout \").Accepts(AcceptedCharacters.None),\n                    Factory.MetaCode(\"Foo Bar Baz\")\n                           .With(new SetLayoutCodeGenerator(\"Foo Bar Baz\"))\n                           .WithEditorHints(EditorHints.VirtualPath | EditorHints.LayoutPage)\n                )\n            );\n        }\n\n        [Fact]\n        public void LayoutDirectiveAcceptsAnyIfNoWhitespaceFollowingLayoutKeyword()\n        {\n            ParseBlockTest(\"@layout\",\n                new DirectiveBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"layout\")\n                )\n            );\n        }\n\n        [Fact]\n        public void LayoutDirectiveOutputsMarkerSpanIfAnyWhitespaceAfterLayoutKeyword()\n        {\n            ParseBlockTest(\"@layout \",\n                new DirectiveBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"layout \").Accepts(AcceptedCharacters.None),\n                    Factory.EmptyCSharp()\n                           .AsMetaCode()\n                           .With(new SetLayoutCodeGenerator(String.Empty))\n                           .WithEditorHints(EditorHints.VirtualPath | EditorHints.LayoutPage)\n                )\n            );\n        }\n\n        [Fact]\n        public void LayoutDirectiveAcceptsTrailingNewlineButDoesNotIncludeItInLayoutPath()\n        {\n            ParseBlockTest(\"@layout Foo\" + Environment.NewLine,\n                new DirectiveBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"layout \").Accepts(AcceptedCharacters.None),\n                    Factory.MetaCode(\"Foo\\r\\n\")\n                           .With(new SetLayoutCodeGenerator(\"Foo\"))\n                           .Accepts(AcceptedCharacters.None)\n                           .WithEditorHints(EditorHints.VirtualPath | EditorHints.LayoutPage)\n                )\n            );\n        }\n\n        [Fact]\n        public void LayoutDirectiveCorrectlyRestoresContextAfterCompleting()\n        {\n            ParseDocumentTest(\"@layout Foo\" + Environment.NewLine\n                            + \"@foo\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new DirectiveBlock(\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"layout \").Accepts(AcceptedCharacters.None),\n                        Factory.MetaCode(\"Foo\\r\\n\")\n                               .With(new SetLayoutCodeGenerator(\"Foo\"))\n                               .Accepts(AcceptedCharacters.None)\n                               .WithEditorHints(EditorHints.VirtualPath | EditorHints.LayoutPage)\n                    ),\n                    Factory.EmptyHtml(),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"foo\")\n                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: false)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    Factory.EmptyHtml()));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/CSharp/CSharpNestedStatementsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Framework;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.CSharp\n{\n    public class CSharpNestedStatementsTest : CsHtmlCodeParserTestBase\n    {\n        [Fact]\n        public void NestedSimpleStatement()\n        {\n            ParseBlockTest(\"@while(true) { foo(); }\",\n                new StatementBlock(\n                    Factory.CodeTransition(),\n                    Factory.Code(\"while(true) { foo(); }\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void NestedKeywordStatement()\n        {\n            ParseBlockTest(\"@while(true) { for(int i = 0; i < 10; i++) { foo(); } }\",\n                new StatementBlock(\n                    Factory.CodeTransition(),\n                    Factory.Code(\"while(true) { for(int i = 0; i < 10; i++) { foo(); } }\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void NestedCodeBlock()\n        {\n            ParseBlockTest(\"@while(true) { { { { foo(); } } } }\",\n                new StatementBlock(\n                    Factory.CodeTransition(),\n                    Factory.Code(\"while(true) { { { { foo(); } } } }\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void NestedImplicitExpression()\n        {\n            ParseBlockTest(\"@while(true) { @foo }\",\n                new StatementBlock(\n                    Factory.CodeTransition(),\n                    Factory.Code(\"while(true) { \")\n                           .AsStatement(),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"foo\")\n                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    Factory.Code(\" }\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void NestedExplicitExpression()\n        {\n            ParseBlockTest(\"@while(true) { @(foo) }\",\n                new StatementBlock(\n                    Factory.CodeTransition(),\n                    Factory.Code(\"while(true) { \")\n                           .AsStatement(),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"(\")\n                               .Accepts(AcceptedCharacters.None),\n                        Factory.Code(\"foo\")\n                               .AsExpression(),\n                        Factory.MetaCode(\")\")\n                               .Accepts(AcceptedCharacters.None)),\n                    Factory.Code(\" }\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void NestedMarkupBlock()\n        {\n            ParseBlockTest(\"@while(true) { <p>Hello</p> }\",\n                new StatementBlock(\n                    Factory.CodeTransition(),\n                    Factory.Code(\"while(true) {\")\n                           .AsStatement(),\n                    new MarkupBlock(\n                        Factory.Markup(\" <p>Hello</p> \")\n                               .With(new MarkupCodeGenerator())\n                               .Accepts(AcceptedCharacters.None)),\n                    Factory.Code(\"}\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.None)));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/CSharp/CSharpRazorCommentsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.CSharp\n{\n    public class CSharpRazorCommentsTest : CsHtmlMarkupParserTestBase\n    {\n        [Fact]\n        public void UnterminatedRazorComment()\n        {\n            ParseDocumentTest(\"@*\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new CommentBlock(\n                        Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition)\n                               .Accepts(AcceptedCharacters.None),\n                        Factory.MetaMarkup(\"*\", HtmlSymbolType.RazorCommentStar)\n                               .Accepts(AcceptedCharacters.None),\n                        Factory.Span(SpanKind.Comment, new HtmlSymbol(\n                            Factory.LocationTracker.CurrentLocation,\n                            String.Empty,\n                            HtmlSymbolType.Unknown))\n                               .Accepts(AcceptedCharacters.Any))),\n                new RazorError(RazorResources.ParseError_RazorComment_Not_Terminated, 0, 0, 0));\n        }\n\n        [Fact]\n        public void EmptyRazorComment()\n        {\n            ParseDocumentTest(\"@**@\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new CommentBlock(\n                        Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition)\n                               .Accepts(AcceptedCharacters.None),\n                        Factory.MetaMarkup(\"*\", HtmlSymbolType.RazorCommentStar)\n                               .Accepts(AcceptedCharacters.None),\n                        Factory.Span(SpanKind.Comment, new HtmlSymbol(\n                            Factory.LocationTracker.CurrentLocation,\n                            String.Empty,\n                            HtmlSymbolType.Unknown))\n                               .Accepts(AcceptedCharacters.Any),\n                        Factory.MetaMarkup(\"*\", HtmlSymbolType.RazorCommentStar)\n                               .Accepts(AcceptedCharacters.None),\n                        Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition)\n                               .Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void RazorCommentInImplicitExpressionMethodCall()\n        {\n            ParseDocumentTest(\"@foo(\" + Environment.NewLine\n                            + \"@**@\" + Environment.NewLine,\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"foo(\\r\\n\")\n                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords),\n                        new CommentBlock(\n                            Factory.CodeTransition(CSharpSymbolType.RazorCommentTransition)\n                                   .Accepts(AcceptedCharacters.None),\n                            Factory.MetaCode(\"*\", CSharpSymbolType.RazorCommentStar)\n                                   .Accepts(AcceptedCharacters.None),\n                            Factory.Span(SpanKind.Comment, new CSharpSymbol(\n                                Factory.LocationTracker.CurrentLocation,\n                                String.Empty,\n                                CSharpSymbolType.Unknown))\n                                   .Accepts(AcceptedCharacters.Any),\n                            Factory.MetaCode(\"*\", CSharpSymbolType.RazorCommentStar)\n                                   .Accepts(AcceptedCharacters.None),\n                            Factory.CodeTransition(CSharpSymbolType.RazorCommentTransition)\n                                   .Accepts(AcceptedCharacters.None)),\n                        Factory.Code(\"\\r\\n\")\n                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords))),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_Expected_CloseBracket_Before_EOF, \"(\", \")\"),\n                    4, 0, 4));\n        }\n\n        [Fact]\n        public void UnterminatedRazorCommentInImplicitExpressionMethodCall()\n        {\n            ParseDocumentTest(\"@foo(@*\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"foo(\")\n                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords),\n                        new CommentBlock(\n                            Factory.CodeTransition(CSharpSymbolType.RazorCommentTransition)\n                                   .Accepts(AcceptedCharacters.None),\n                            Factory.MetaCode(\"*\", CSharpSymbolType.RazorCommentStar)\n                                   .Accepts(AcceptedCharacters.None),\n                            Factory.Span(SpanKind.Comment, new CSharpSymbol(\n                                Factory.LocationTracker.CurrentLocation,\n                                String.Empty,\n                                CSharpSymbolType.Unknown))\n                                    .Accepts(AcceptedCharacters.Any)))),\n                new RazorError(RazorResources.ParseError_RazorComment_Not_Terminated, 5, 0, 5),\n                new RazorError(String.Format(RazorResources.ParseError_Expected_CloseBracket_Before_EOF, \"(\", \")\"), 4, 0, 4));\n        }\n\n        [Fact]\n        public void RazorCommentInVerbatimBlock()\n        {\n            ParseDocumentTest(\"@{\" + Environment.NewLine\n                            + \"    <text\" + Environment.NewLine\n                            + \"    @**@\" + Environment.NewLine\n                            + \"}\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new StatementBlock(\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                        Factory.Code(\"\\r\\n\").AsStatement(),\n                        new MarkupBlock(\n                            Factory.Markup(\"    \"),\n                            Factory.MarkupTransition(\"<text\").Accepts(AcceptedCharacters.Any),\n                            Factory.Markup(\"\\r\\n    \"),\n                            new CommentBlock(\n                                Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition)\n                                       .Accepts(AcceptedCharacters.None),\n                                Factory.MetaMarkup(\"*\", HtmlSymbolType.RazorCommentStar)\n                                       .Accepts(AcceptedCharacters.None),\n                                Factory.Span(SpanKind.Comment, new HtmlSymbol(\n                                    Factory.LocationTracker.CurrentLocation,\n                                    String.Empty,\n                                    HtmlSymbolType.Unknown))\n                                       .Accepts(AcceptedCharacters.Any),\n                                Factory.MetaMarkup(\"*\", HtmlSymbolType.RazorCommentStar)\n                                       .Accepts(AcceptedCharacters.None),\n                                Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition)\n                                       .Accepts(AcceptedCharacters.None)),\n                            Factory.Markup(\"\\r\\n}\")))),\n                new RazorError(RazorResources.ParseError_TextTagCannotContainAttributes, 8, 1, 4),\n                new RazorError(String.Format(RazorResources.ParseError_MissingEndTag, \"text\"), 8, 1, 4),\n                new RazorError(String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF, RazorResources.BlockName_Code, \"}\", \"{\"), 1, 0, 1));\n        }\n\n        [Fact]\n        public void UnterminatedRazorCommentInVerbatimBlock()\n        {\n            ParseDocumentTest(\"@{@*\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new StatementBlock(\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                        Factory.EmptyCSharp()\n                               .AsStatement(),\n                        new CommentBlock(\n                            Factory.CodeTransition(CSharpSymbolType.RazorCommentTransition)\n                                   .Accepts(AcceptedCharacters.None),\n                            Factory.MetaCode(\"*\", CSharpSymbolType.RazorCommentStar)\n                                   .Accepts(AcceptedCharacters.None),\n                            Factory.Span(SpanKind.Comment, new CSharpSymbol(Factory.LocationTracker.CurrentLocation,\n                                                                        String.Empty,\n                                                                        CSharpSymbolType.Unknown))\n                                   .Accepts(AcceptedCharacters.Any)))),\n                new RazorError(RazorResources.ParseError_RazorComment_Not_Terminated, 2, 0, 2),\n                new RazorError(String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF, RazorResources.BlockName_Code, \"}\", \"{\"), 1, 0, 1));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/CSharp/CSharpReservedWordsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.CSharp\n{\n    public class CSharpReservedWordsTest : CsHtmlCodeParserTestBase\n    {\n        [Theory]\n        [InlineData(\"namespace\")]\n        [InlineData(\"class\")]\n        public void ReservedWords(string word)\n        {\n            ParseBlockTest(word,\n                           new DirectiveBlock(\n                               Factory.MetaCode(word).Accepts(AcceptedCharacters.None)\n                               ),\n                           new RazorError(String.Format(RazorResources.ParseError_ReservedWord, word), SourceLocation.Zero));\n        }\n\n        [Theory]\n        [InlineData(\"Namespace\")]\n        [InlineData(\"Class\")]\n        [InlineData(\"NAMESPACE\")]\n        [InlineData(\"CLASS\")]\n        [InlineData(\"nameSpace\")]\n        [InlineData(\"NameSpace\")]\n        private void ReservedWordsAreCaseSensitive(string word)\n        {\n            ParseBlockTest(word,\n                           new ExpressionBlock(\n                               Factory.Code(word)\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)\n                               ));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/CSharp/CSharpSectionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.CSharp\n{\n    public class CSharpSectionTest : CsHtmlMarkupParserTestBase\n    {\n        [Fact]\n        public void ParseSectionBlockCapturesNewlineImmediatelyFollowing()\n        {\n            ParseDocumentTest(\"@section\" + Environment.NewLine,\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(String.Empty),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section\\r\\n\"))),\n                new RazorError(\n                    String.Format(\n                        RazorResources.ParseError_Unexpected_Character_At_Section_Name_Start,\n                        RazorResources.ErrorComponent_EndOfFile),\n                    10, 1, 0));\n        }\n\n        [Fact]\n        public void ParseSectionBlockCapturesWhitespaceToEndOfLineInSectionStatementMissingOpenBrace()\n        {\n            ParseDocumentTest(\"@section Foo         \" + Environment.NewLine\n                            + \"    \",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"Foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section Foo         \\r\\n\")),\n                    Factory.Markup(\"    \")),\n                new RazorError(RazorResources.ParseError_MissingOpenBraceAfterSection, 12, 0, 12));\n        }\n\n        [Fact]\n        public void ParseSectionBlockCapturesWhitespaceToEndOfLineInSectionStatementMissingName()\n        {\n            ParseDocumentTest(\"@section         \" + Environment.NewLine\n                            + \"    \",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(String.Empty),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section         \\r\\n\")),\n                    Factory.Markup(\"    \")),\n                new RazorError(\n                    String.Format(\n                        RazorResources.ParseError_Unexpected_Character_At_Section_Name_Start,\n                        RazorResources.ErrorComponent_EndOfFile),\n                    23, 1, 4));\n        }\n\n        [Fact]\n        public void ParseSectionBlockIgnoresSectionUnlessAllLowerCase()\n        {\n            ParseDocumentTest(\"@Section foo\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"Section\")\n                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    Factory.Markup(\" foo\")));\n        }\n\n        [Fact]\n        public void ParseSectionBlockReportsErrorAndTerminatesSectionBlockIfKeywordNotFollowedByIdentifierStartCharacter()\n        {\n            ParseDocumentTest(\"@section 9 { <p>Foo</p> }\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(String.Empty),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section \")),\n                    Factory.Markup(\"9 { <p>Foo</p> }\")),\n                new RazorError(\n                    String.Format(\n                        RazorResources.ParseError_Unexpected_Character_At_Section_Name_Start,\n                        String.Format(RazorResources.ErrorComponent_Character, \"9\")),\n                    9, 0, 9));\n        }\n\n        [Fact]\n        public void ParseSectionBlockReportsErrorAndTerminatesSectionBlockIfNameNotFollowedByOpenBrace()\n        {\n            ParseDocumentTest(\"@section foo-bar { <p>Foo</p> }\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section foo\")),\n                    Factory.Markup(\"-bar { <p>Foo</p> }\")),\n                new RazorError(RazorResources.ParseError_MissingOpenBraceAfterSection, 12, 0, 12));\n        }\n        \n        [Fact]\n        public void ParserOutputsErrorOnNestedSections()\n        {\n            ParseDocumentTest(\"@section foo { @section bar { <p>Foo</p> } }\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section foo {\")\n                               .AutoCompleteWith(null, atEndOfSpan: true),\n                        new MarkupBlock(\n                            Factory.Markup(\" \"),\n                            new SectionBlock(new SectionCodeGenerator(\"bar\"),\n                                Factory.CodeTransition(),\n                                Factory.MetaCode(\"section bar {\")\n                                       .AutoCompleteWith(null, atEndOfSpan: true),\n                                new MarkupBlock(\n                                    Factory.Markup(\" <p>Foo</p> \")),\n                                Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                            Factory.Markup(\" \")),\n                        Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()),\n                new RazorError(\n                    String.Format(\n                        RazorResources.ParseError_Sections_Cannot_Be_Nested,\n                        RazorResources.SectionExample_CS),\n                    23, 0, 23));\n        }\n\n        [Fact]\n        public void ParseSectionBlockHandlesEOFAfterOpenBrace()\n        {\n            ParseDocumentTest(\"@section foo {\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section foo {\")\n                               .AutoCompleteWith(\"}\", atEndOfSpan: true),\n                        new MarkupBlock())),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_Expected_X, \"}\"),\n                    14, 0, 14));\n        }\n\n        [Fact]\n        public void ParseSectionBlockHandlesUnterminatedSection()\n        {\n            ParseDocumentTest(\"@section foo { <p>Foo{}</p>\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section foo {\")\n                               .AutoCompleteWith(\"}\", atEndOfSpan: true),\n                        new MarkupBlock(\n                // Need to provide the markup span as fragments, since the parser will split the {} into separate symbols.\n                            Factory.Markup(\" <p>Foo\", \"{\", \"}\", \"</p>\")))),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_Expected_X, \"}\"),\n                    27, 0, 27));\n        }\n\n        [Fact]\n        public void ParseSectionBlockReportsErrorAndAcceptsWhitespaceToEndOfLineIfSectionNotFollowedByOpenBrace()\n        {\n            ParseDocumentTest(\"@section foo      \" + Environment.NewLine,\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section foo      \\r\\n\"))),\n                new RazorError(RazorResources.ParseError_MissingOpenBraceAfterSection, 12, 0, 12));\n        }\n\n        [Fact]\n        public void ParseSectionBlockAcceptsOpenBraceMultipleLinesBelowSectionName()\n        {\n            ParseDocumentTest(\"@section foo      \" + Environment.NewLine\n                            + Environment.NewLine\n                            + Environment.NewLine\n                            + Environment.NewLine\n                            + Environment.NewLine\n                            + Environment.NewLine\n                            + \"{\" + Environment.NewLine\n                            + \"<p>Foo</p>\" + Environment.NewLine\n                            + \"}\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section foo      \\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n{\")\n                               .AutoCompleteWith(null, atEndOfSpan: true),\n                        new MarkupBlock(\n                            Factory.Markup(\"\\r\\n<p>Foo</p>\\r\\n\")),\n                        Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void ParseSectionBlockParsesNamedSectionCorrectly()\n        {\n            ParseDocumentTest(\"@section foo { <p>Foo</p> }\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section foo {\")\n                               .AutoCompleteWith(null, atEndOfSpan: true),\n                        new MarkupBlock(\n                            Factory.Markup(\" <p>Foo</p> \")),\n                        Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void ParseSectionBlockDoesNotRequireSpaceBetweenSectionNameAndOpenBrace()\n        {\n            ParseDocumentTest(\"@section foo{ <p>Foo</p> }\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section foo{\")\n                               .AutoCompleteWith(null, atEndOfSpan: true),\n                        new MarkupBlock(\n                            Factory.Markup(\" <p>Foo</p> \")),\n                        Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void ParseSectionBlockBalancesBraces()\n        {\n            ParseDocumentTest(\"@section foo { <script>(function foo() { return 1; })();</script> }\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section foo {\")\n                               .AutoCompleteWith(null, atEndOfSpan: true),\n                        new MarkupBlock(\n                            Factory.Markup(\" <script>(function foo() { return 1; })();</script> \")),\n                        Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void ParseSectionBlockAllowsBracesInCSharpExpression()\n        {\n            ParseDocumentTest(\"@section foo { I really want to render a close brace, so here I go: @(\\\"}\\\") }\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section foo {\")\n                               .AutoCompleteWith(null, atEndOfSpan: true),\n                        new MarkupBlock(\n                            Factory.Markup(\" I really want to render a close brace, so here I go: \"),\n                            new ExpressionBlock(\n                                Factory.CodeTransition(),\n                                Factory.MetaCode(\"(\").Accepts(AcceptedCharacters.None),\n                                Factory.Code(\"\\\"}\\\"\").AsExpression(),\n                                Factory.MetaCode(\")\").Accepts(AcceptedCharacters.None)),\n                            Factory.Markup(\" \")),\n                        Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void SectionIsCorrectlyTerminatedWhenCloseBraceImmediatelyFollowsCodeBlock()\n        {\n            ParseDocumentTest(\"@section Foo {\" + Environment.NewLine\n                            + \"@if(true) {\" + Environment.NewLine\n                            + \"}\" + Environment.NewLine\n                            + \"}\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"Foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section Foo {\")\n                               .AutoCompleteWith(null, atEndOfSpan: true),\n                        new MarkupBlock(\n                            Factory.Markup(\"\\r\\n\"),\n                            new StatementBlock(\n                                Factory.CodeTransition(),\n                                Factory.Code(\"if(true) {\\r\\n}\\r\\n\").AsStatement()\n                            )),\n                        Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void SectionIsCorrectlyTerminatedWhenCloseBraceImmediatelyFollowsCodeBlockNoWhitespace()\n        {\n            ParseDocumentTest(\"@section Foo {\" + Environment.NewLine\n                            + \"@if(true) {\" + Environment.NewLine\n                            + \"}}\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"Foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section Foo {\")\n                               .AutoCompleteWith(null, atEndOfSpan: true),\n                        new MarkupBlock(\n                            Factory.Markup(\"\\r\\n\"),\n                            new StatementBlock(\n                                Factory.CodeTransition(),\n                                Factory.Code(\"if(true) {\\r\\n}\").AsStatement()\n                            )),\n                        Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void ParseSectionBlockCorrectlyTerminatesWhenCloseBraceImmediatelyFollowsMarkup()\n        {\n            ParseDocumentTest(\"@section foo {something}\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section foo {\")\n                               .AutoCompleteWith(null, atEndOfSpan: true),\n                        new MarkupBlock(\n                            Factory.Markup(\"something\")),\n                        Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void ParseSectionBlockParsesComment()\n        {\n            ParseDocumentTest(\"@section s {<!-- -->}\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"s\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section s {\")\n                            .AutoCompleteWith(null, atEndOfSpan: true),\n                        new MarkupBlock(\n                            Factory.Markup(\"<!-- -->\")),\n                        Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        // This was a user reported bug (codeplex #710), the section parser wasn't handling\n        // comments.\n        [Fact]\n        public void ParseSectionBlockParsesCommentWithDelimiters()\n        {\n            ParseDocumentTest(\"@section s {<!-- > \\\" '-->}\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"s\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section s {\")\n                            .AutoCompleteWith(null, atEndOfSpan: true),\n                        new MarkupBlock(\n                            Factory.Markup(\"<!-- > \\\" '-->\")),\n                        Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void ParseSectionBlockCommentRecoversFromUnclosedTag()\n        {\n            ParseDocumentTest(\n                \"@section s {\" + Environment.NewLine + \"<a\" + Environment.NewLine + \"<!--  > \\\" '-->}\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"s\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section s {\")\n                            .AutoCompleteWith(null, atEndOfSpan: true),\n                        new MarkupBlock(\n                            Factory.Markup(Environment.NewLine + \"<a\" + Environment.NewLine + \"<!--  > \\\" '-->\")),\n                        Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void ParseSectionBlockParsesXmlProcessingInstruction()\n        {\n            ParseDocumentTest(\n                \"@section s { <? xml bleh ?>}\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"s\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section s {\")\n                            .AutoCompleteWith(null, atEndOfSpan: true),\n                        new MarkupBlock(\n                            Factory.Markup(\" <? xml bleh ?>\")),\n                        Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/CSharp/CSharpSpecialBlockTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.CSharp\n{\n    public class CSharpSpecialBlockTest : CsHtmlCodeParserTestBase\n    {\n        [Fact]\n        public void ParseInheritsStatementMarksInheritsSpanAsCanGrowIfMissingTrailingSpace()\n        {\n            ParseBlockTest(\"inherits\",\n                           new DirectiveBlock(\n                               Factory.MetaCode(\"inherits\").Accepts(AcceptedCharacters.Any)\n                               ),\n                           new RazorError(\n                               RazorResources.ParseError_InheritsKeyword_Must_Be_Followed_By_TypeName,\n                               new SourceLocation(8, 0, 8)));\n        }\n\n        [Fact]\n        public void InheritsBlockAcceptsMultipleGenericArguments()\n        {\n            ParseBlockTest(\"inherits Foo.Bar<Biz<Qux>, string, int>.Baz\",\n                           new DirectiveBlock(\n                               Factory.MetaCode(\"inherits \").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\"Foo.Bar<Biz<Qux>, string, int>.Baz\")\n                                   .AsBaseType(\"Foo.Bar<Biz<Qux>, string, int>.Baz\")\n                               ));\n        }\n\n        [Fact]\n        public void InheritsBlockOutputsErrorIfInheritsNotFollowedByTypeButAcceptsEntireLineAsCode()\n        {\n            ParseBlockTest(\"inherits                \" + Environment.NewLine\n                         + \"foo\",\n                           new DirectiveBlock(\n                               Factory.MetaCode(\"inherits \").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\"               \\r\\n\")\n                                   .AsBaseType(String.Empty)\n                               ),\n                           new RazorError(RazorResources.ParseError_InheritsKeyword_Must_Be_Followed_By_TypeName, 24, 0, 24));\n        }\n\n        [Fact]\n        public void NamespaceImportInsideCodeBlockCausesError()\n        {\n            ParseBlockTest(\"{ using Foo.Bar.Baz; var foo = bar; }\",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\" using Foo.Bar.Baz; var foo = bar; \").AsStatement(),\n                               Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)\n                               ),\n                           new RazorError(\n                               RazorResources.ParseError_NamespaceImportAndTypeAlias_Cannot_Exist_Within_CodeBlock,\n                               new SourceLocation(2, 0, 2)));\n        }\n\n        [Fact]\n        public void TypeAliasInsideCodeBlockIsNotHandledSpecially()\n        {\n            ParseBlockTest(\"{ using Foo = Bar.Baz; var foo = bar; }\",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\" using Foo = Bar.Baz; var foo = bar; \").AsStatement(),\n                               Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)\n                               ),\n                           new RazorError(\n                               RazorResources.ParseError_NamespaceImportAndTypeAlias_Cannot_Exist_Within_CodeBlock,\n                               new SourceLocation(2, 0, 2)));\n        }\n\n        [Fact]\n        public void Plan9FunctionsKeywordInsideCodeBlockIsNotHandledSpecially()\n        {\n            ParseBlockTest(\"{ functions Foo; }\",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\" functions Foo; \").AsStatement(),\n                               Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void NonKeywordStatementInCodeBlockIsHandledCorrectly()\n        {\n            ParseBlockTest(\"{\" + Environment.NewLine\n                         + \"    List<dynamic> photos = gallery.Photo.ToList();\" + Environment.NewLine\n                         + \"}\",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\"\\r\\n    List<dynamic> photos = gallery.Photo.ToList();\\r\\n\").AsStatement(),\n                               Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockBalancesBracesOutsideStringsIfFirstCharacterIsBraceAndReturnsSpanOfTypeCode()\n        {\n            // Arrange\n            const string code = \"foo\\\"b}ar\\\" if(condition) { String.Format(\\\"{0}\\\"); } \";\n\n            // Act/Assert\n            ParseBlockTest(\"{\" + code + \"}\",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(code).AsStatement(),\n                               Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockBalancesParensOutsideStringsIfFirstCharacterIsParenAndReturnsSpanOfTypeExpression()\n        {\n            // Arrange\n            const string code = \"foo\\\"b)ar\\\" if(condition) { String.Format(\\\"{0}\\\"); } \";\n\n            // Act/Assert\n            ParseBlockTest(\"(\" + code + \")\",\n                           new ExpressionBlock(\n                               Factory.MetaCode(\"(\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(code).AsExpression(),\n                               Factory.MetaCode(\")\").Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockBalancesBracesAndOutputsContentAsClassLevelCodeSpanIfFirstIdentifierIsFunctionsKeyword()\n        {\n            const string code = \" foo(); \\\"bar}baz\\\" \";\n            ParseBlockTest(\"functions {\" + code + \"} zoop\",\n                           new FunctionsBlock(\n                               Factory.MetaCode(\"functions {\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(code).AsFunctionsBody(),\n                               Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockDoesNoErrorRecoveryForFunctionsBlock()\n        {\n            ParseBlockTest(\"functions { { { { { } zoop\",\n                           new FunctionsBlock(\n                               Factory.MetaCode(\"functions {\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\" { { { { } zoop\").AsFunctionsBody()\n                               ),\n                           new RazorError(\n                               String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF, \"functions\", \"}\", \"{\"),\n                               SourceLocation.Zero));\n        }\n\n        [Fact]\n        public void ParseBlockIgnoresFunctionsUnlessAllLowerCase()\n        {\n            ParseBlockTest(\"Functions { foo() }\",\n                           new ExpressionBlock(\n                               Factory.Code(\"Functions\")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)));\n        }\n\n        [Fact]\n        public void ParseBlockIgnoresSingleSlashAtStart()\n        {\n            ParseBlockTest(\"@/ foo\",\n                           new ExpressionBlock(\n                               Factory.CodeTransition(),\n                               Factory.EmptyCSharp()\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                           new RazorError(\n                               String.Format(RazorResources.ParseError_Unexpected_Character_At_Start_Of_CodeBlock_CS, \"/\"),\n                               1, 0, 1));\n        }\n\n        [Fact]\n        public void ParseBlockTerminatesSingleLineCommentAtEndOfLine()\n        {\n            ParseBlockTest(\"if(!false) {\" + Environment.NewLine\n                         + \"    // Foo\" + Environment.NewLine\n                         + \"\\t<p>A real tag!</p>\" + Environment.NewLine\n                         + \"}\",\n                           new StatementBlock(\n                               Factory.Code(\"if(!false) {\\r\\n    // Foo\\r\\n\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\"\\t<p>A real tag!</p>\\r\\n\")\n                                       .Accepts(AcceptedCharacters.None)),\n                               Factory.Code(\"}\").AsStatement()\n                               ));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/CSharp/CSharpStatementTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Framework;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.CSharp\n{\n    // Basic Tests for C# Statements:\n    //  * Basic case for each statement\n    //  * Basic case for ALL clauses\n\n    // This class DOES NOT contain\n    //  * Error cases\n    //  * Tests for various types of nested statements\n    //  * Comment tests\n\n    public class CSharpStatementTest : CsHtmlCodeParserTestBase\n    {\n        [Fact]\n        public void ForStatement()\n        {\n            ParseBlockTest(\"@for(int i = 0; i++; i < length) { foo(); }\",\n                           new StatementBlock(\n                               Factory.CodeTransition(),\n                               Factory.Code(\"for(int i = 0; i++; i < length) { foo(); }\")\n                                   .AsStatement()\n                                   .Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void ForEachStatement()\n        {\n            ParseBlockTest(\"@foreach(var foo in bar) { foo(); }\",\n                           new StatementBlock(\n                               Factory.CodeTransition(),\n                               Factory.Code(\"foreach(var foo in bar) { foo(); }\")\n                                   .AsStatement()\n                                   .Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void WhileStatement()\n        {\n            ParseBlockTest(\"@while(true) { foo(); }\",\n                           new StatementBlock(\n                               Factory.CodeTransition(),\n                               Factory.Code(\"while(true) { foo(); }\")\n                                   .AsStatement()\n                                   .Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void SwitchStatement()\n        {\n            ParseBlockTest(\"@switch(foo) { foo(); }\",\n                           new StatementBlock(\n                               Factory.CodeTransition(),\n                               Factory.Code(\"switch(foo) { foo(); }\")\n                                   .AsStatement()\n                                   .Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void LockStatement()\n        {\n            ParseBlockTest(\"@lock(baz) { foo(); }\",\n                           new StatementBlock(\n                               Factory.CodeTransition(),\n                               Factory.Code(\"lock(baz) { foo(); }\")\n                                   .AsStatement()\n                                   .Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void IfStatement()\n        {\n            ParseBlockTest(\"@if(true) { foo(); }\",\n                           new StatementBlock(\n                               Factory.CodeTransition(),\n                               Factory.Code(\"if(true) { foo(); }\")\n                                   .AsStatement()\n                               ));\n        }\n\n        [Fact]\n        public void ElseIfClause()\n        {\n            ParseBlockTest(\"@if(true) { foo(); } else if(false) { foo(); } else if(!false) { foo(); }\",\n                           new StatementBlock(\n                               Factory.CodeTransition(),\n                               Factory.Code(\"if(true) { foo(); } else if(false) { foo(); } else if(!false) { foo(); }\")\n                                   .AsStatement()\n                               ));\n        }\n\n        [Fact]\n        public void ElseClause()\n        {\n            ParseBlockTest(\"@if(true) { foo(); } else { foo(); }\",\n                           new StatementBlock(\n                               Factory.CodeTransition(),\n                               Factory.Code(\"if(true) { foo(); } else { foo(); }\")\n                                   .AsStatement()\n                                   .Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void TryStatement()\n        {\n            ParseBlockTest(\"@try { foo(); }\",\n                           new StatementBlock(\n                               Factory.CodeTransition(),\n                               Factory.Code(\"try { foo(); }\")\n                                   .AsStatement()\n                               ));\n        }\n\n        [Fact]\n        public void CatchClause()\n        {\n            ParseBlockTest(\"@try { foo(); } catch(IOException ioex) { handleIO(); } catch(Exception ex) { handleOther(); }\",\n                           new StatementBlock(\n                               Factory.CodeTransition(),\n                               Factory.Code(\"try { foo(); } catch(IOException ioex) { handleIO(); } catch(Exception ex) { handleOther(); }\")\n                                   .AsStatement()\n                               ));\n        }\n\n        [Fact]\n        public void FinallyClause()\n        {\n            ParseBlockTest(\"@try { foo(); } finally { Dispose(); }\",\n                           new StatementBlock(\n                               Factory.CodeTransition(),\n                               Factory.Code(\"try { foo(); } finally { Dispose(); }\")\n                                   .AsStatement()\n                                   .Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void UsingStatement()\n        {\n            ParseBlockTest(\"@using(var foo = new Foo()) { foo.Bar(); }\",\n                           new StatementBlock(\n                               Factory.CodeTransition(),\n                               Factory.Code(\"using(var foo = new Foo()) { foo.Bar(); }\")\n                                   .AsStatement()\n                                   .Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void UsingTypeAlias()\n        {\n            ParseBlockTest(\"@using StringDictionary = System.Collections.Generic.Dictionary<string, string>\",\n                           new DirectiveBlock(\n                               Factory.CodeTransition(),\n                               Factory.Code(\"using StringDictionary = System.Collections.Generic.Dictionary<string, string>\")\n                                   .AsNamespaceImport(\" StringDictionary = System.Collections.Generic.Dictionary<string, string>\", 5)\n                                   .Accepts(AcceptedCharacters.AnyExceptNewline)\n                               ));\n        }\n\n        [Fact]\n        public void UsingNamespaceImport()\n        {\n            ParseBlockTest(\"@using System.Text.Encoding.ASCIIEncoding\",\n                           new DirectiveBlock(\n                               Factory.CodeTransition(),\n                               Factory.Code(\"using System.Text.Encoding.ASCIIEncoding\")\n                                   .AsNamespaceImport(\" System.Text.Encoding.ASCIIEncoding\", 5)\n                                   .Accepts(AcceptedCharacters.AnyExceptNewline)\n                               ));\n        }\n\n        [Fact]\n        public void DoStatement()\n        {\n            ParseBlockTest(\"@do { foo(); } while(true);\",\n                           new StatementBlock(\n                               Factory.CodeTransition(),\n                               Factory.Code(\"do { foo(); } while(true);\")\n                                   .AsStatement()\n                                   .Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void NonBlockKeywordTreatedAsImplicitExpression()\n        {\n            ParseBlockTest(\"@is foo\",\n                           new ExpressionBlock(new ExpressionCodeGenerator(),\n                                               Factory.CodeTransition(),\n                                               Factory.Code(\"is\")\n                                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                                   .Accepts(AcceptedCharacters.NonWhiteSpace)\n                               ));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/CSharp/CSharpTemplateTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Editor;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.CSharp\n{\n    public class CSharpTemplateTest : CsHtmlCodeParserTestBase\n    {\n        private const string TestTemplateCode = \" @<p>Foo #@item</p>\";\n\n        private TemplateBlock TestTemplate()\n        {\n            return new TemplateBlock(\n                new MarkupBlock(\n                    Factory.MarkupTransition(),\n                    Factory.Markup(\"<p>Foo #\"),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"item\")\n                            .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                            .Accepts(AcceptedCharacters.NonWhiteSpace)\n                        ),\n                    Factory.Markup(\"</p>\").Accepts(AcceptedCharacters.None)\n                    )\n                );\n        }\n\n        private const string TestNestedTemplateCode = \" @<p>Foo #@Html.Repeat(10, @<p>@item</p>)</p>\";\n\n        private TemplateBlock TestNestedTemplate()\n        {\n            return new TemplateBlock(\n                new MarkupBlock(\n                    Factory.MarkupTransition(),\n                    Factory.Markup(\"<p>Foo #\"),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"Html.Repeat(10, \")\n                            .AsImplicitExpression(CSharpCodeParser.DefaultKeywords),\n                        new TemplateBlock(\n                            new MarkupBlock(\n                                Factory.MarkupTransition(),\n                                Factory.Markup(\"<p>\"),\n                                new ExpressionBlock(\n                                    Factory.CodeTransition(),\n                                    Factory.Code(\"item\")\n                                        .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                        .Accepts(AcceptedCharacters.NonWhiteSpace)\n                                    ),\n                                Factory.Markup(\"</p>\").Accepts(AcceptedCharacters.None)\n                                )\n                            ),\n                        Factory.Code(\")\")\n                            .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                            .Accepts(AcceptedCharacters.NonWhiteSpace)\n                        ),\n                    Factory.Markup(\"</p>\").Accepts(AcceptedCharacters.None)\n                    )\n                );\n        }\n\n        [Fact]\n        public void ParseBlockHandlesSingleLineTemplate()\n        {\n            ParseBlockTest(\"{ var foo = @: bar\" + Environment.NewLine\n                         + \"; }\",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\" var foo = \").AsStatement(),\n                               new TemplateBlock(\n                                   new MarkupBlock(\n                                       Factory.MarkupTransition(),\n                                       Factory.MetaMarkup(\":\", HtmlSymbolType.Colon),\n                                       Factory.Markup(\" bar\\r\\n\")\n                                           .With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString))\n                                           .Accepts(AcceptedCharacters.None)\n                                       )\n                                   ),\n                               Factory.Code(\"; \").AsStatement(),\n                               Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockHandlesSingleLineImmediatelyFollowingStatementChar()\n        {\n            ParseBlockTest(\"{i@: bar\" + Environment.NewLine\n                         + \"}\",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\"i\").AsStatement(),\n                               new TemplateBlock(\n                                   new MarkupBlock(\n                                       Factory.MarkupTransition(),\n                                       Factory.MetaMarkup(\":\", HtmlSymbolType.Colon),\n                                       Factory.Markup(\" bar\\r\\n\")\n                                           .With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString))\n                                           .Accepts(AcceptedCharacters.None)\n                                       )\n                                   ),\n                               Factory.EmptyCSharp().AsStatement(),\n                               Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockHandlesSimpleTemplateInExplicitExpressionParens()\n        {\n            ParseBlockTest(\"(Html.Repeat(10,\" + TestTemplateCode + \"))\",\n                           new ExpressionBlock(\n                               Factory.MetaCode(\"(\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\"Html.Repeat(10, \").AsExpression(),\n                               TestTemplate(),\n                               Factory.Code(\")\").AsExpression(),\n                               Factory.MetaCode(\")\").Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockHandlesSimpleTemplateInImplicitExpressionParens()\n        {\n            ParseBlockTest(\"Html.Repeat(10,\" + TestTemplateCode + \")\",\n                           new ExpressionBlock(\n                               Factory.Code(\"Html.Repeat(10, \")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords),\n                               TestTemplate(),\n                               Factory.Code(\")\")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockHandlesTwoTemplatesInImplicitExpressionParens()\n        {\n            ParseBlockTest(\"Html.Repeat(10,\" + TestTemplateCode + \",\" + TestTemplateCode + \")\",\n                           new ExpressionBlock(\n                               Factory.Code(\"Html.Repeat(10, \")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords),\n                               TestTemplate(),\n                               Factory.Code(\", \")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords),\n                               TestTemplate(),\n                               Factory.Code(\")\")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockProducesErrorButCorrectlyParsesNestedTemplateInImplicitExpressionParens()\n        {\n            ParseBlockTest(\"Html.Repeat(10,\" + TestNestedTemplateCode + \")\",\n                           new ExpressionBlock(\n                               Factory.Code(\"Html.Repeat(10, \")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords),\n                               TestNestedTemplate(),\n                               Factory.Code(\")\")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)\n                               ),\n                           GetNestedTemplateError(42));\n        }\n\n        [Fact]\n        public void ParseBlockHandlesSimpleTemplateInStatementWithinCodeBlock()\n        {\n            ParseBlockTest(\"foreach(foo in Bar) { Html.ExecuteTemplate(foo,\" + TestTemplateCode + \"); }\",\n                           new StatementBlock(\n                               Factory.Code(\"foreach(foo in Bar) { Html.ExecuteTemplate(foo, \").AsStatement(),\n                               TestTemplate(),\n                               Factory.Code(\"); }\")\n                                   .AsStatement()\n                                   .Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockHandlesTwoTemplatesInStatementWithinCodeBlock()\n        {\n            ParseBlockTest(\"foreach(foo in Bar) { Html.ExecuteTemplate(foo,\" + TestTemplateCode + \",\" + TestTemplateCode + \"); }\",\n                           new StatementBlock(\n                               Factory.Code(\"foreach(foo in Bar) { Html.ExecuteTemplate(foo, \").AsStatement(),\n                               TestTemplate(),\n                               Factory.Code(\", \").AsStatement(),\n                               TestTemplate(),\n                               Factory.Code(\"); }\")\n                                   .AsStatement()\n                                   .Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockProducesErrorButCorrectlyParsesNestedTemplateInStatementWithinCodeBlock()\n        {\n            ParseBlockTest(\"foreach(foo in Bar) { Html.ExecuteTemplate(foo,\" + TestNestedTemplateCode + \"); }\",\n                           new StatementBlock(\n                               Factory.Code(\"foreach(foo in Bar) { Html.ExecuteTemplate(foo, \").AsStatement(),\n                               TestNestedTemplate(),\n                               Factory.Code(\"); }\")\n                                   .AsStatement()\n                                   .Accepts(AcceptedCharacters.None)\n                               ),\n                           GetNestedTemplateError(74));\n        }\n\n        [Fact]\n        public void ParseBlockHandlesSimpleTemplateInStatementWithinStatementBlock()\n        {\n            ParseBlockTest(\"{ var foo = bar; Html.ExecuteTemplate(foo,\" + TestTemplateCode + \"); }\",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\" var foo = bar; Html.ExecuteTemplate(foo, \").AsStatement(),\n                               TestTemplate(),\n                               Factory.Code(\"); \").AsStatement(),\n                               Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockHandlessTwoTemplatesInStatementWithinStatementBlock()\n        {\n            ParseBlockTest(\"{ var foo = bar; Html.ExecuteTemplate(foo,\" + TestTemplateCode + \",\" + TestTemplateCode + \"); }\",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\" var foo = bar; Html.ExecuteTemplate(foo, \").AsStatement(),\n                               TestTemplate(),\n                               Factory.Code(\", \").AsStatement(),\n                               TestTemplate(),\n                               Factory.Code(\"); \").AsStatement(),\n                               Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockProducesErrorButCorrectlyParsesNestedTemplateInStatementWithinStatementBlock()\n        {\n            ParseBlockTest(\"{ var foo = bar; Html.ExecuteTemplate(foo,\" + TestNestedTemplateCode + \"); }\",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\" var foo = bar; Html.ExecuteTemplate(foo, \").AsStatement(),\n                               TestNestedTemplate(),\n                               Factory.Code(\"); \").AsStatement(),\n                               Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)\n                               ),\n                           GetNestedTemplateError(69));\n        }\n\n        private static RazorError GetNestedTemplateError(int characterIndex)\n        {\n            return new RazorError(RazorResources.ParseError_InlineMarkup_Blocks_Cannot_Be_Nested, new SourceLocation(characterIndex, 0, characterIndex));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/CSharp/CSharpToMarkupSwitchTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Editor;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.CSharp\n{\n    public class CSharpToMarkupSwitchTest : CsHtmlCodeParserTestBase\n    {\n        [Fact]\n        public void SingleAngleBracketDoesNotCauseSwitchIfOuterBlockIsTerminated()\n        {\n            ParseBlockTest(\"{ List< }\",\n                new StatementBlock(\n                    Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                    Factory.Code(\" List< \").AsStatement(),\n                    Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockGivesSpacesToCodeOnAtTagTemplateTransitionInDesignTimeMode()\n        {\n            ParseBlockTest(\"Foo(    @<p>Foo</p>    )\",\n                           new ExpressionBlock(\n                               Factory.Code(\"Foo(    \")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                   .Accepts(AcceptedCharacters.Any),\n                               new TemplateBlock(\n                                   new MarkupBlock(\n                                       Factory.MarkupTransition(),\n                                       Factory.Markup(\"<p>Foo</p>\").Accepts(AcceptedCharacters.None)\n                                       )\n                                   ),\n                               Factory.Code(\"    )\")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)\n                               ), designTimeParser: true);\n        }\n\n        [Fact]\n        public void ParseBlockGivesSpacesToCodeOnAtColonTemplateTransitionInDesignTimeMode()\n        {\n            ParseBlockTest(\"Foo(    \" + Environment.NewLine\n                         + \"@:<p>Foo</p>    \" + Environment.NewLine\n                         + \")\",\n                           new ExpressionBlock(\n                               Factory.Code(\"Foo(    \\r\\n\").AsImplicitExpression(CSharpCodeParser.DefaultKeywords),\n                               new TemplateBlock(\n                                   new MarkupBlock(\n                                       Factory.MarkupTransition(),\n                                       Factory.MetaMarkup(\":\", HtmlSymbolType.Colon),\n                                       Factory.Markup(\"<p>Foo</p>    \\r\\n\")\n                                           .With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None))\n                                       )\n                                   ),\n                               Factory.Code(\")\")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)\n                               ), designTimeParser: true);\n        }\n\n        [Fact]\n        public void ParseBlockGivesSpacesToCodeOnTagTransitionInDesignTimeMode()\n        {\n            ParseBlockTest(\"{\" + Environment.NewLine\n                         + \"    <p>Foo</p>    \" + Environment.NewLine\n                         + \"}\",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\"\\r\\n    \").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\"<p>Foo</p>\").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\"    \\r\\n\").AsStatement(),\n                               Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)\n                               ), designTimeParser: true);\n        }\n\n        [Fact]\n        public void ParseBlockGivesSpacesToCodeOnInvalidAtTagTransitionInDesignTimeMode()\n        {\n            ParseBlockTest(\"{\" + Environment.NewLine\n                         + \"    @<p>Foo</p>    \" + Environment.NewLine\n                         + \"}\",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\"\\r\\n    \").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.MarkupTransition(),\n                                   Factory.Markup(\"<p>Foo</p>\").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\"    \\r\\n\").AsStatement(),\n                               Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)\n                               ), true,\n                           new RazorError(RazorResources.ParseError_AtInCode_Must_Be_Followed_By_Colon_Paren_Or_Identifier_Start, 7, 1, 4));\n        }\n\n        [Fact]\n        public void ParseBlockGivesSpacesToCodeOnAtColonTransitionInDesignTimeMode()\n        {\n            ParseBlockTest(\"{\" + Environment.NewLine\n                         + \"    @:<p>Foo</p>    \" + Environment.NewLine\n                         + \"}\",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\"\\r\\n    \").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.MarkupTransition(),\n                                   Factory.MetaMarkup(\":\", HtmlSymbolType.Colon),\n                                   Factory.Markup(\"<p>Foo</p>    \\r\\n\")\n                                       .With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None))\n                                   ),\n                               Factory.EmptyCSharp().AsStatement(),\n                               Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)\n                               ), designTimeParser: true);\n        }\n\n        [Fact]\n        public void ParseBlockShouldSupportSingleLineMarkupContainingStatementBlock()\n        {\n            ParseBlockTest(\"Repeat(10,\" + Environment.NewLine\n                         + \"    @: @{}\" + Environment.NewLine\n                         + \")\",\n                           new ExpressionBlock(\n                               Factory.Code(\"Repeat(10,\\r\\n    \")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords),\n                               new TemplateBlock(\n                                   new MarkupBlock(\n                                       Factory.MarkupTransition(),\n                                       Factory.MetaMarkup(\":\", HtmlSymbolType.Colon),\n                                       Factory.Markup(\" \")\n                                           .With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString)),\n                                       new StatementBlock(\n                                           Factory.CodeTransition(),\n                                           Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                                           Factory.EmptyCSharp().AsStatement(),\n                                           Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)\n                                           ),\n                                       Factory.Markup(\"\\r\\n\")\n                                           .With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None))\n                                       )\n                                   ),\n                               Factory.Code(\")\")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockShouldSupportMarkupWithoutPreceedingWhitespace()\n        {\n            ParseBlockTest(\"foreach(var file in files){\" + Environment.NewLine\n                         + Environment.NewLine\n                         + Environment.NewLine\n                         + \"@:Baz\" + Environment.NewLine\n                         + \"<br/>\" + Environment.NewLine\n                         + \"<a>Foo</a>\" + Environment.NewLine\n                         + \"@:Bar\" + Environment.NewLine\n                         + \"}\",\n                           new StatementBlock(\n                               Factory.Code(\"foreach(var file in files){\\r\\n\\r\\n\\r\\n\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.MarkupTransition(),\n                                   Factory.MetaMarkup(\":\", HtmlSymbolType.Colon),\n                                   Factory.Markup(\"Baz\\r\\n\")\n                                       .With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None))\n                                   ),\n                               new MarkupBlock(\n                                   Factory.Markup(\"<br/>\\r\\n\")\n                                       .Accepts(AcceptedCharacters.None)\n                                   ),\n                               new MarkupBlock(\n                                   Factory.Markup(\"<a>Foo</a>\\r\\n\")\n                                       .Accepts(AcceptedCharacters.None)\n                                   ),\n                               new MarkupBlock(\n                                   Factory.MarkupTransition(),\n                                   Factory.MetaMarkup(\":\", HtmlSymbolType.Colon),\n                                   Factory.Markup(\"Bar\\r\\n\")\n                                       .With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None))\n                                   ),\n                               Factory.Code(\"}\").AsStatement().Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockGivesAllWhitespaceOnSameLineExcludingPreceedingNewlineButIncludingTrailingNewLineToMarkup()\n        {\n            ParseBlockTest(\"if(foo) {\" + Environment.NewLine\n                         + \"    var foo = \\\"After this statement there are 10 spaces\\\";          \" + Environment.NewLine\n                         + \"    <p>\" + Environment.NewLine\n                         + \"        Foo\" + Environment.NewLine\n                         + \"        @bar\" + Environment.NewLine\n                         + \"    </p>\" + Environment.NewLine\n                         + \"    @:Hello!\" + Environment.NewLine\n                         + \"    var biz = boz;\" + Environment.NewLine\n                         + \"}\",\n                           new StatementBlock(\n                               Factory.Code(\"if(foo) {\\r\\n    var foo = \\\"After this statement there are 10 spaces\\\";          \\r\\n\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\"    <p>\\r\\n        Foo\\r\\n\"),\n                                   new ExpressionBlock(\n                                       Factory.Code(\"        \").AsStatement(),\n                                       Factory.CodeTransition(),\n                                       Factory.Code(\"bar\").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)\n                                       ),\n                                   Factory.Markup(\"\\r\\n    </p>\\r\\n\").Accepts(AcceptedCharacters.None)\n                                   ),\n                               new MarkupBlock(\n                                   Factory.Markup(\"    \"),\n                                   Factory.MarkupTransition(),\n                                   Factory.MetaMarkup(\":\", HtmlSymbolType.Colon),\n                                   Factory.Markup(\"Hello!\\r\\n\").With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None))\n                                   ),\n                               Factory.Code(\"    var biz = boz;\\r\\n}\").AsStatement()));\n        }\n\n        [Fact]\n        public void ParseBlockAllowsMarkupInIfBodyWithBraces()\n        {\n            ParseBlockTest(\"if(foo) { <p>Bar</p> } else if(bar) { <p>Baz</p> } else { <p>Boz</p> }\",\n                           new StatementBlock(\n                               Factory.Code(\"if(foo) {\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\" <p>Bar</p> \").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\"} else if(bar) {\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\" <p>Baz</p> \").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\"} else {\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\" <p>Boz</p> \").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\"}\").AsStatement().Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockAllowsMarkupInIfBodyWithBracesWithinCodeBlock()\n        {\n            ParseBlockTest(\"{ if(foo) { <p>Bar</p> } else if(bar) { <p>Baz</p> } else { <p>Boz</p> } }\",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\" if(foo) {\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\" <p>Bar</p> \").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\"} else if(bar) {\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\" <p>Baz</p> \").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\"} else {\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\" <p>Boz</p> \").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\"} \").AsStatement(),\n                               Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockSupportsMarkupInCaseAndDefaultBranchesOfSwitch()\n        {\n            // Arrange\n            ParseBlockTest(\"switch(foo) {\" + Environment.NewLine\n                         + \"    case 0:\" + Environment.NewLine\n                         + \"        <p>Foo</p>\" + Environment.NewLine\n                         + \"        break;\" + Environment.NewLine\n                         + \"    case 1:\" + Environment.NewLine\n                         + \"        <p>Bar</p>\" + Environment.NewLine\n                         + \"        return;\" + Environment.NewLine\n                         + \"    case 2:\" + Environment.NewLine\n                         + \"        {\" + Environment.NewLine\n                         + \"            <p>Baz</p>\" + Environment.NewLine\n                         + \"            <p>Boz</p>\" + Environment.NewLine\n                         + \"        }\" + Environment.NewLine\n                         + \"    default:\" + Environment.NewLine\n                         + \"        <p>Biz</p>\" + Environment.NewLine\n                         + \"}\",\n                           new StatementBlock(\n                               Factory.Code(\"switch(foo) {\\r\\n    case 0:\\r\\n\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\"        <p>Foo</p>\\r\\n\").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\"        break;\\r\\n    case 1:\\r\\n\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\"        <p>Bar</p>\\r\\n\").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\"        return;\\r\\n    case 2:\\r\\n        {\\r\\n\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\"            <p>Baz</p>\\r\\n\").Accepts(AcceptedCharacters.None)\n                                   ),\n                               new MarkupBlock(\n                                   Factory.Markup(\"            <p>Boz</p>\\r\\n\").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\"        }\\r\\n    default:\\r\\n\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\"        <p>Biz</p>\\r\\n\").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\"}\").AsStatement().Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockSupportsMarkupInCaseAndDefaultBranchesOfSwitchInCodeBlock()\n        {\n            // Arrange\n            ParseBlockTest(\"{ switch(foo) {\" + Environment.NewLine\n                         + \"    case 0:\" + Environment.NewLine\n                         + \"        <p>Foo</p>\" + Environment.NewLine\n                         + \"        break;\" + Environment.NewLine\n                         + \"    case 1:\" + Environment.NewLine\n                         + \"        <p>Bar</p>\" + Environment.NewLine\n                         + \"        return;\" + Environment.NewLine\n                         + \"    case 2:\" + Environment.NewLine\n                         + \"        {\" + Environment.NewLine\n                         + \"            <p>Baz</p>\" + Environment.NewLine\n                         + \"            <p>Boz</p>\" + Environment.NewLine\n                         + \"        }\" + Environment.NewLine\n                         + \"    default:\" + Environment.NewLine\n                         + \"        <p>Biz</p>\" + Environment.NewLine\n                         + \"} }\",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\" switch(foo) {\\r\\n    case 0:\\r\\n\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\"        <p>Foo</p>\\r\\n\").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\"        break;\\r\\n    case 1:\\r\\n\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\"        <p>Bar</p>\\r\\n\").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\"        return;\\r\\n    case 2:\\r\\n        {\\r\\n\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\"            <p>Baz</p>\\r\\n\").Accepts(AcceptedCharacters.None)\n                                   ),\n                               new MarkupBlock(\n                                   Factory.Markup(\"            <p>Boz</p>\\r\\n\").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\"        }\\r\\n    default:\\r\\n\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\"        <p>Biz</p>\\r\\n\").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\"} \").AsStatement(),\n                               Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockParsesMarkupStatementOnOpenAngleBracket()\n        {\n            ParseBlockTest(\"for(int i = 0; i < 10; i++) { <p>Foo</p> }\",\n                           new StatementBlock(\n                               Factory.Code(\"for(int i = 0; i < 10; i++) {\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\" <p>Foo</p> \").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\"}\").AsStatement().Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void ParseBlockParsesMarkupStatementOnOpenAngleBracketInCodeBlock()\n        {\n            ParseBlockTest(\"{ for(int i = 0; i < 10; i++) { <p>Foo</p> } }\",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\" for(int i = 0; i < 10; i++) {\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\" <p>Foo</p> \").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\"} \").AsStatement(),\n                               Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockParsesMarkupStatementOnSwitchCharacterFollowedByColon()\n        {\n            // Arrange\n            ParseBlockTest(\"if(foo) { @:Bar\" + Environment.NewLine\n                         + \"} zoop\",\n                           new StatementBlock(\n                               Factory.Code(\"if(foo) {\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\" \"),\n                                   Factory.MarkupTransition(),\n                                   Factory.MetaMarkup(\":\", HtmlSymbolType.Colon),\n                                   Factory.Markup(\"Bar\\r\\n\").With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None))\n                                   ),\n                               Factory.Code(\"}\").AsStatement()));\n        }\n\n        [Fact]\n        public void ParseBlockParsesMarkupStatementOnSwitchCharacterFollowedByColonInCodeBlock()\n        {\n            // Arrange\n            ParseBlockTest(\"{ if(foo) { @:Bar\" + Environment.NewLine\n                         + \"} } zoop\",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\" if(foo) {\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\" \"),\n                                   Factory.MarkupTransition(),\n                                   Factory.MetaMarkup(\":\", HtmlSymbolType.Colon),\n                                   Factory.Markup(\"Bar\\r\\n\").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\"} \").AsStatement(),\n                               Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockCorrectlyReturnsFromMarkupBlockWithPseudoTag()\n        {\n            ParseBlockTest(\"if (i > 0) { <text>;</text> }\",\n                           new StatementBlock(\n                               Factory.Code(\"if (i > 0) {\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\" \"),\n                                   Factory.MarkupTransition(\"<text>\").Accepts(AcceptedCharacters.None),\n                                   Factory.Markup(\";\"),\n                                   Factory.MarkupTransition(\"</text>\").Accepts(AcceptedCharacters.None),\n                                   Factory.Markup(\" \").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\"}\").AsStatement()));\n        }\n\n        [Fact]\n        public void ParseBlockCorrectlyReturnsFromMarkupBlockWithPseudoTagInCodeBlock()\n        {\n            ParseBlockTest(\"{ if (i > 0) { <text>;</text> } }\",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\" if (i > 0) {\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\" \"),\n                                   Factory.MarkupTransition(\"<text>\").Accepts(AcceptedCharacters.None),\n                                   Factory.Markup(\";\"),\n                                   Factory.MarkupTransition(\"</text>\").Accepts(AcceptedCharacters.None),\n                                   Factory.Markup(\" \").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\"} \").AsStatement(),\n                               Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockSupportsAllKindsOfImplicitMarkupInCodeBlock()\n        {\n            ParseBlockTest(\"{\" + Environment.NewLine\n                         + \"    if(true) {\" + Environment.NewLine\n                         + \"        @:Single Line Markup\" + Environment.NewLine\n                         + \"    }\" + Environment.NewLine\n                         + \"    foreach (var p in Enumerable.Range(1, 10)) {\" + Environment.NewLine\n                         + \"        <text>The number is @p</text>\" + Environment.NewLine\n                         + \"    }\" + Environment.NewLine\n                         + \"    if(!false) {\" + Environment.NewLine\n                         + \"        <p>A real tag!</p>\" + Environment.NewLine\n                         + \"    }\" + Environment.NewLine\n                         + \"}\",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\"\\r\\n    if(true) {\\r\\n\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\"        \"),\n                                   Factory.MarkupTransition(),\n                                   Factory.MetaMarkup(\":\", HtmlSymbolType.Colon),\n                                   Factory.Markup(\"Single Line Markup\\r\\n\").With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None))\n                                   ),\n                               Factory.Code(\"    }\\r\\n    foreach (var p in Enumerable.Range(1, 10)) {\\r\\n\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\"        \"),\n                                   Factory.MarkupTransition(\"<text>\").Accepts(AcceptedCharacters.None),\n                                   Factory.Markup(\"The number is \"),\n                                   new ExpressionBlock(\n                                       Factory.CodeTransition(),\n                                       Factory.Code(\"p\").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)\n                                       ),\n                                   Factory.MarkupTransition(\"</text>\").Accepts(AcceptedCharacters.None),\n                                   Factory.Markup(\"\\r\\n\").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\"    }\\r\\n    if(!false) {\\r\\n\").AsStatement(),\n                               new MarkupBlock(\n                                   Factory.Markup(\"        <p>A real tag!</p>\\r\\n\").Accepts(AcceptedCharacters.None)\n                                   ),\n                               Factory.Code(\"    }\\r\\n\").AsStatement(),\n                               Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/CSharp/CSharpVerbatimBlockTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.CSharp\n{\n    public class CSharpVerbatimBlockTest : CsHtmlCodeParserTestBase\n    {\n        private const string TestExtraKeyword = \"model\";\n\n        [Fact]\n        public void VerbatimBlock()\n        {\n            ParseBlockTest(\"@{ foo(); }\",\n                           new StatementBlock(\n                               Factory.CodeTransition(),\n                               Factory.MetaCode(\"{\")\n                                   .Accepts(AcceptedCharacters.None),\n                               Factory.Code(\" foo(); \")\n                                   .AsStatement(),\n                               Factory.MetaCode(\"}\")\n                                   .Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void InnerImplicitExpressionWithOnlySingleAtOutputsZeroLengthCodeSpan()\n        {\n            ParseBlockTest(\"{@}\",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.EmptyCSharp().AsStatement(),\n                               new ExpressionBlock(\n                                   Factory.CodeTransition(),\n                                   Factory.EmptyCSharp().AsImplicitExpression(KeywordSet, acceptTrailingDot: true).Accepts(AcceptedCharacters.NonWhiteSpace)\n                                   ),\n                               Factory.EmptyCSharp().AsStatement(),\n                               Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                           designTimeParser: true,\n                           expectedErrors: new[]\n                           {\n                               new RazorError(String.Format(RazorResources.ParseError_Unexpected_Character_At_Start_Of_CodeBlock_CS, \"}\"), new SourceLocation(2, 0, 2))\n                           });\n        }\n\n        [Fact]\n        public void InnerImplicitExpressionDoesNotAcceptDotAfterAt()\n        {\n            ParseBlockTest(\"{@.}\",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.EmptyCSharp().AsStatement(),\n                               new ExpressionBlock(\n                                   Factory.CodeTransition(),\n                                   Factory.EmptyCSharp().AsImplicitExpression(KeywordSet, acceptTrailingDot: true).Accepts(AcceptedCharacters.NonWhiteSpace)\n                                   ),\n                               Factory.Code(\".\").AsStatement(),\n                               Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                           designTimeParser: true,\n                           expectedErrors: new[]\n                           {\n                               new RazorError(String.Format(RazorResources.ParseError_Unexpected_Character_At_Start_Of_CodeBlock_CS, \".\"), new SourceLocation(2, 0, 2))\n                           });\n        }\n\n        [Fact]\n        public void InnerImplicitExpressionWithOnlySingleAtAcceptsSingleSpaceOrNewlineAtDesignTime()\n        {\n            ParseBlockTest(\"{\" + Environment.NewLine\n                         + \"    @\" + Environment.NewLine\n                         + \"}\",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.Code(\"\\r\\n    \").AsStatement(),\n                               new ExpressionBlock(\n                                   Factory.CodeTransition(),\n                                   Factory.EmptyCSharp().AsImplicitExpression(KeywordSet, acceptTrailingDot: true).Accepts(AcceptedCharacters.NonWhiteSpace)\n                                   ),\n                               Factory.Code(\"\\r\\n\").AsStatement(),\n                               Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                /* designTimeParser */ true,\n                           new RazorError(RazorResources.ParseError_Unexpected_WhiteSpace_At_Start_Of_CodeBlock_CS, 8, 1, 5));\n        }\n\n        [Fact]\n        public void InnerImplicitExpressionDoesNotAcceptTrailingNewlineInRunTimeMode()\n        {\n            ParseBlockTest(\"{@foo.\" + Environment.NewLine\n                         + \"}\",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.EmptyCSharp().AsStatement(),\n                               new ExpressionBlock(\n                                   Factory.CodeTransition(),\n                                   Factory.Code(\"foo.\").AsImplicitExpression(KeywordSet, acceptTrailingDot: true).Accepts(AcceptedCharacters.NonWhiteSpace)),\n                               Factory.Code(\"\\r\\n\").AsStatement(),\n                               Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void InnerImplicitExpressionAcceptsTrailingNewlineInDesignTimeMode()\n        {\n            ParseBlockTest(\"{@foo.\" + Environment.NewLine\n                         + \"}\",\n                           new StatementBlock(\n                               Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                               Factory.EmptyCSharp().AsStatement(),\n                               new ExpressionBlock(\n                                   Factory.CodeTransition(),\n                                   Factory.Code(\"foo.\").AsImplicitExpression(KeywordSet, acceptTrailingDot: true).Accepts(AcceptedCharacters.NonWhiteSpace)),\n                               Factory.Code(\"\\r\\n\").AsStatement(),\n                               Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                           designTimeParser: true);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/CSharp/CSharpWhitespaceHandlingTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.CSharp\n{\n    public class CSharpWhitespaceHandlingTest : CsHtmlMarkupParserTestBase\n    {\n        [Fact]\n        public void StatementBlockDoesNotAcceptTrailingNewlineIfNewlinesAreSignificantToAncestor()\n        {\n            ParseBlockTest(\"@: @if (true) { }\" + Environment.NewLine\n                         + \"}\",\n                           new MarkupBlock(\n                               Factory.MarkupTransition()\n                                   .Accepts(AcceptedCharacters.None),\n                               Factory.MetaMarkup(\":\", HtmlSymbolType.Colon),\n                               Factory.Markup(\" \"),\n                               new StatementBlock(\n                                   Factory.CodeTransition()\n                                       .Accepts(AcceptedCharacters.None),\n                                   Factory.Code(\"if (true) { }\")\n                                       .AsStatement()\n                                   ),\n                               Factory.Markup(\"\\r\\n\")\n                                   .Accepts(AcceptedCharacters.None)));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/CSharp/CsHtmlDocumentTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.CSharp\n{\n    public class CsHtmlDocumentTest : CsHtmlMarkupParserTestBase\n    {\n        [Fact]\n        public void UnterminatedBlockCommentCausesRazorError()\n        {\n            ParseDocumentTest(\"@* Foo Bar\",\n                              new MarkupBlock(\n                                  Factory.EmptyHtml(),\n                                  new CommentBlock(\n                                      Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition),\n                                      Factory.MetaMarkup(\"*\", HtmlSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                                      Factory.Comment(\" Foo Bar\", HtmlSymbolType.RazorComment)\n                                      )\n                                  ),\n                              new RazorError(RazorResources.ParseError_RazorComment_Not_Terminated, SourceLocation.Zero));\n        }\n\n        [Fact]\n        public void BlockCommentInMarkupDocumentIsHandledCorrectly()\n        {\n            ParseDocumentTest(\"<ul>\" + Environment.NewLine\n                            + \"                @* This is a block comment </ul> *@ foo\",\n                              new MarkupBlock(\n                                  Factory.Markup(\"<ul>\\r\\n                \"),\n                                  new CommentBlock(\n                                      Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition),\n                                      Factory.MetaMarkup(\"*\", HtmlSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                                      Factory.Comment(\" This is a block comment </ul> \", HtmlSymbolType.RazorComment),\n                                      Factory.MetaMarkup(\"*\", HtmlSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                                      Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition)\n                                      ),\n                                  Factory.Markup(\" foo\")\n                                  ));\n        }\n\n        [Fact]\n        public void BlockCommentInMarkupBlockIsHandledCorrectly()\n        {\n            ParseBlockTest(\"<ul>\" + Environment.NewLine\n                         + \"                @* This is a block comment </ul> *@ foo </ul>\",\n                           new MarkupBlock(\n                               Factory.Markup(\"<ul>\\r\\n                \"),\n                               new CommentBlock(\n                                   Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition),\n                                   Factory.MetaMarkup(\"*\", HtmlSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                                   Factory.Comment(\" This is a block comment </ul> \", HtmlSymbolType.RazorComment),\n                                   Factory.MetaMarkup(\"*\", HtmlSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                                   Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition)\n                                   ),\n                               Factory.Markup(\" foo </ul>\").Accepts(AcceptedCharacters.None)\n                               ));\n        }\n\n        [Fact]\n        public void BlockCommentAtStatementStartInCodeBlockIsHandledCorrectly()\n        {\n            ParseDocumentTest(\"@if(Request.IsAuthenticated) {\" + Environment.NewLine\n                            + \"    @* User is logged in! } *@\" + Environment.NewLine\n                            + \"    Write(\\\"Hello friend!\\\");\" + Environment.NewLine\n                            + \"}\",\n                              new MarkupBlock(\n                                  Factory.EmptyHtml(),\n                                  new StatementBlock(\n                                      Factory.CodeTransition(),\n                                      Factory.Code(\"if(Request.IsAuthenticated) {\\r\\n    \").AsStatement(),\n                                      new CommentBlock(\n                                          Factory.CodeTransition(CSharpSymbolType.RazorCommentTransition),\n                                          Factory.MetaCode(\"*\", CSharpSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                                          Factory.Comment(\" User is logged in! } \", CSharpSymbolType.RazorComment),\n                                          Factory.MetaCode(\"*\", CSharpSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                                          Factory.CodeTransition(CSharpSymbolType.RazorCommentTransition)\n                                          ),\n                                      Factory.Code(\"\\r\\n    Write(\\\"Hello friend!\\\");\\r\\n}\").AsStatement())));\n        }\n\n        [Fact]\n        public void BlockCommentInStatementInCodeBlockIsHandledCorrectly()\n        {\n            ParseDocumentTest(\"@if(Request.IsAuthenticated) {\" + Environment.NewLine\n                            + \"    var foo = @* User is logged in! ; *@;\" + Environment.NewLine\n                            + \"    Write(\\\"Hello friend!\\\");\" + Environment.NewLine\n                            + \"}\",\n                              new MarkupBlock(\n                                  Factory.EmptyHtml(),\n                                  new StatementBlock(\n                                      Factory.CodeTransition(),\n                                      Factory.Code(\"if(Request.IsAuthenticated) {\\r\\n    var foo = \").AsStatement(),\n                                      new CommentBlock(\n                                          Factory.CodeTransition(CSharpSymbolType.RazorCommentTransition),\n                                          Factory.MetaCode(\"*\", CSharpSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                                          Factory.Comment(\" User is logged in! ; \", CSharpSymbolType.RazorComment),\n                                          Factory.MetaCode(\"*\", CSharpSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                                          Factory.CodeTransition(CSharpSymbolType.RazorCommentTransition)\n                                          ),\n                                      Factory.Code(\";\\r\\n    Write(\\\"Hello friend!\\\");\\r\\n}\").AsStatement())));\n        }\n\n        [Fact]\n        public void BlockCommentInStringIsIgnored()\n        {\n            ParseDocumentTest(\"@if(Request.IsAuthenticated) {\" + Environment.NewLine\n                            + \"    var foo = \\\"@* User is logged in! ; *\\\";\" + Environment.NewLine\n                            + \"    Write(\\\"Hello friend!\\\");\" + Environment.NewLine\n                            + \"}\",\n                              new MarkupBlock(\n                                  Factory.EmptyHtml(),\n                                  new StatementBlock(\n                                      Factory.CodeTransition(),\n                                      Factory.Code(\"if(Request.IsAuthenticated) {\" + Environment.NewLine\n                                                 + \"    var foo = \\\"@* User is logged in! ; *\\\";\" + Environment.NewLine\n                                                 + \"    Write(\\\"Hello friend!\\\");\" + Environment.NewLine\n                                                 + \"}\").AsStatement())));\n        }\n\n        [Fact]\n        public void BlockCommentInCSharpBlockCommentIsIgnored()\n        {\n            ParseDocumentTest(\"@if(Request.IsAuthenticated) {\" + Environment.NewLine\n                            + \"    var foo = /*@* User is logged in! */ *@ */;\" + Environment.NewLine\n                            + \"    Write(\\\"Hello friend!\\\");\" + Environment.NewLine\n                            + \"}\",\n                              new MarkupBlock(\n                                  Factory.EmptyHtml(),\n                                  new StatementBlock(\n                                      Factory.CodeTransition(),\n                                      Factory.Code(\"if(Request.IsAuthenticated) {\" + Environment.NewLine\n                                                 + \"    var foo = /*@* User is logged in! */ *@ */;\" + Environment.NewLine\n                                                 + \"    Write(\\\"Hello friend!\\\");\" + Environment.NewLine\n                                                 + \"}\").AsStatement())));\n        }\n\n        [Fact]\n        public void BlockCommentInCSharpLineCommentIsIgnored()\n        {\n            ParseDocumentTest(\"@if(Request.IsAuthenticated) {\" + Environment.NewLine\n                            + \"    var foo = //@* User is logged in! */ *@;\" + Environment.NewLine\n                            + \"    Write(\\\"Hello friend!\\\");\" + Environment.NewLine\n                            + \"}\",\n                              new MarkupBlock(\n                                  Factory.EmptyHtml(),\n                                  new StatementBlock(\n                                      Factory.CodeTransition(),\n                                      Factory.Code(\"if(Request.IsAuthenticated) {\" + Environment.NewLine\n                                                 + \"    var foo = //@* User is logged in! */ *@;\" + Environment.NewLine\n                                                 + \"    Write(\\\"Hello friend!\\\");\" + Environment.NewLine\n                                                 + \"}\").AsStatement())));\n        }\n\n        [Fact]\n        public void BlockCommentInImplicitExpressionIsHandledCorrectly()\n        {\n            ParseDocumentTest(\"@Html.Foo@*bar*@\",\n                              new MarkupBlock(\n                                  Factory.EmptyHtml(),\n                                  new ExpressionBlock(\n                                      Factory.CodeTransition(),\n                                      Factory.Code(\"Html.Foo\").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)\n                                      ),\n                                  Factory.EmptyHtml(),\n                                  new CommentBlock(\n                                      Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition),\n                                      Factory.MetaMarkup(\"*\", HtmlSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                                      Factory.Comment(\"bar\", HtmlSymbolType.RazorComment),\n                                      Factory.MetaMarkup(\"*\", HtmlSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                                      Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition)\n                                      ),\n                                  Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void BlockCommentAfterDotOfImplicitExpressionIsHandledCorrectly()\n        {\n            ParseDocumentTest(\"@Html.@*bar*@\",\n                              new MarkupBlock(\n                                  Factory.EmptyHtml(),\n                                  new ExpressionBlock(\n                                      Factory.CodeTransition(),\n                                      Factory.Code(\"Html\").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)\n                                      ),\n                                  Factory.Markup(\".\"),\n                                  new CommentBlock(\n                                      Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition),\n                                      Factory.MetaMarkup(\"*\", HtmlSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                                      Factory.Comment(\"bar\", HtmlSymbolType.RazorComment),\n                                      Factory.MetaMarkup(\"*\", HtmlSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                                      Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition)\n                                      ),\n                                  Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void BlockCommentInParensOfImplicitExpressionIsHandledCorrectly()\n        {\n            ParseDocumentTest(\"@Html.Foo(@*bar*@ 4)\",\n                              new MarkupBlock(\n                                  Factory.EmptyHtml(),\n                                  new ExpressionBlock(\n                                      Factory.CodeTransition(),\n                                      Factory.Code(\"Html.Foo(\").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.Any),\n                                      new CommentBlock(\n                                          Factory.CodeTransition(CSharpSymbolType.RazorCommentTransition),\n                                          Factory.MetaCode(\"*\", CSharpSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                                          Factory.Comment(\"bar\", CSharpSymbolType.RazorComment),\n                                          Factory.MetaCode(\"*\", CSharpSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                                          Factory.CodeTransition(CSharpSymbolType.RazorCommentTransition)\n                                          ),\n                                      Factory.Code(\" 4)\").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)\n                                      ),\n                                  Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void BlockCommentInBracketsOfImplicitExpressionIsHandledCorrectly()\n        {\n            ParseDocumentTest(\"@Html.Foo[@*bar*@ 4]\",\n                              new MarkupBlock(\n                                  Factory.EmptyHtml(),\n                                  new ExpressionBlock(\n                                      Factory.CodeTransition(),\n                                      Factory.Code(\"Html.Foo[\").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.Any),\n                                      new CommentBlock(\n                                          Factory.CodeTransition(CSharpSymbolType.RazorCommentTransition),\n                                          Factory.MetaCode(\"*\", CSharpSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                                          Factory.Comment(\"bar\", CSharpSymbolType.RazorComment),\n                                          Factory.MetaCode(\"*\", CSharpSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                                          Factory.CodeTransition(CSharpSymbolType.RazorCommentTransition)\n                                          ),\n                                      Factory.Code(\" 4]\").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)\n                                      ),\n                                  Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void BlockCommentInParensOfConditionIsHandledCorrectly()\n        {\n            ParseDocumentTest(\"@if(@*bar*@) {}\",\n                              new MarkupBlock(\n                                  Factory.EmptyHtml(),\n                                  new StatementBlock(\n                                      Factory.CodeTransition(),\n                                      Factory.Code(\"if(\").AsStatement(),\n                                      new CommentBlock(\n                                          Factory.CodeTransition(CSharpSymbolType.RazorCommentTransition),\n                                          Factory.MetaCode(\"*\", CSharpSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                                          Factory.Comment(\"bar\", CSharpSymbolType.RazorComment),\n                                          Factory.MetaCode(\"*\", CSharpSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                                          Factory.CodeTransition(CSharpSymbolType.RazorCommentTransition)\n                                          ),\n                                      Factory.Code(\") {}\").AsStatement()\n                                      )));\n        }\n\n        [Fact]\n        public void BlockCommentInExplicitExpressionIsHandledCorrectly()\n        {\n            ParseDocumentTest(\"@(1 + @*bar*@ 1)\",\n                              new MarkupBlock(\n                                  Factory.EmptyHtml(),\n                                  new ExpressionBlock(\n                                      Factory.CodeTransition(),\n                                      Factory.MetaCode(\"(\").Accepts(AcceptedCharacters.None),\n                                      Factory.Code(\"1 + \").AsExpression(),\n                                      new CommentBlock(\n                                          Factory.CodeTransition(CSharpSymbolType.RazorCommentTransition),\n                                          Factory.MetaCode(\"*\", CSharpSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                                          Factory.Comment(\"bar\", CSharpSymbolType.RazorComment),\n                                          Factory.MetaCode(\"*\", CSharpSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                                          Factory.CodeTransition(CSharpSymbolType.RazorCommentTransition)\n                                          ),\n                                      Factory.Code(\" 1\").AsExpression(),\n                                      Factory.MetaCode(\")\").Accepts(AcceptedCharacters.None)\n                                      ),\n                                  Factory.EmptyHtml()));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/CallbackParserListenerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Razor.Test.Parser\n{\n    public class CallbackParserListenerTest\n    {\n        [Fact]\n        public void ListenerConstructedWithSpanCallbackCallsCallbackOnEndSpan()\n        {\n            RunOnEndSpanTest(callback => new CallbackVisitor(callback));\n        }\n\n        [Fact]\n        public void ListenerConstructedWithSpanCallbackDoesNotThrowOnStartBlockEndBlockOrError()\n        {\n            // Arrange\n            Action<Span> spanCallback = _ => { };\n            CallbackVisitor listener = new CallbackVisitor(spanCallback);\n\n            // Act/Assert\n            listener.VisitStartBlock(new FunctionsBlock());\n            listener.VisitError(new RazorError(\"Error\", SourceLocation.Zero));\n            listener.VisitEndBlock(new FunctionsBlock());\n        }\n\n        [Fact]\n        public void ListenerConstructedWithSpanAndErrorCallbackCallsCallbackOnEndSpan()\n        {\n            RunOnEndSpanTest(spanCallback => new CallbackVisitor(spanCallback, _ => { }));\n        }\n\n        [Fact]\n        public void ListenerConstructedWithSpanAndErrorCallbackCallsCallbackOnError()\n        {\n            RunOnErrorTest(errorCallback => new CallbackVisitor(_ => { }, errorCallback));\n        }\n\n        [Fact]\n        public void ListenerConstructedWithAllCallbacksCallsCallbackOnEndSpan()\n        {\n            RunOnEndSpanTest(spanCallback => new CallbackVisitor(spanCallback, _ => { }, _ => { }, _ => { }));\n        }\n\n        [Fact]\n        public void ListenerConstructedWithAllCallbacksCallsCallbackOnError()\n        {\n            RunOnErrorTest(errorCallback => new CallbackVisitor(_ => { }, errorCallback, _ => { }, _ => { }));\n        }\n\n        [Fact]\n        public void ListenerConstructedWithAllCallbacksCallsCallbackOnStartBlock()\n        {\n            RunOnStartBlockTest(startBlockCallback => new CallbackVisitor(_ => { }, _ => { }, startBlockCallback, _ => { }));\n        }\n\n        [Fact]\n        public void ListenerConstructedWithAllCallbacksCallsCallbackOnEndBlock()\n        {\n            RunOnEndBlockTest(endBlockCallback => new CallbackVisitor(_ => { }, _ => { }, _ => { }, endBlockCallback));\n        }\n\n        [Fact]\n        public void ListenerCallsOnEndSpanCallbackUsingSynchronizationContextIfSpecified()\n        {\n            RunSyncContextTest(new SpanBuilder().Build(),\n                               spanCallback => new CallbackVisitor(spanCallback, _ => { }, _ => { }, _ => { }),\n                               (listener, expected) => listener.VisitSpan(expected));\n        }\n\n        [Fact]\n        public void ListenerCallsOnStartBlockCallbackUsingSynchronizationContextIfSpecified()\n        {\n            RunSyncContextTest(BlockType.Template,\n                               startBlockCallback => new CallbackVisitor(_ => { }, _ => { }, startBlockCallback, _ => { }),\n                               (listener, expected) => listener.VisitStartBlock(new BlockBuilder() { Type = expected }.Build()));\n        }\n\n        [Fact]\n        public void ListenerCallsOnEndBlockCallbackUsingSynchronizationContextIfSpecified()\n        {\n            RunSyncContextTest(BlockType.Template,\n                               endBlockCallback => new CallbackVisitor(_ => { }, _ => { }, _ => { }, endBlockCallback),\n                               (listener, expected) => listener.VisitEndBlock(new BlockBuilder() { Type = expected }.Build()));\n        }\n\n        [Fact]\n        public void ListenerCallsOnErrorCallbackUsingSynchronizationContextIfSpecified()\n        {\n            RunSyncContextTest(new RazorError(\"Bar\", 42, 42, 42),\n                               errorCallback => new CallbackVisitor(_ => { }, errorCallback, _ => { }, _ => { }),\n                               (listener, expected) => listener.VisitError(expected));\n        }\n\n        private static void RunSyncContextTest<T>(T expected, Func<Action<T>, CallbackVisitor> ctor, Action<CallbackVisitor, T> call)\n        {\n            // Arrange\n            Mock<SynchronizationContext> mockContext = new Mock<SynchronizationContext>();\n            mockContext.Setup(c => c.Post(It.IsAny<SendOrPostCallback>(), It.IsAny<object>()))\n                .Callback<SendOrPostCallback, object>((callback, state) => { callback(expected); });\n\n            // Act/Assert\n            RunCallbackTest<T>(default(T), callback =>\n            {\n                CallbackVisitor listener = ctor(callback);\n                listener.SynchronizationContext = mockContext.Object;\n                return listener;\n            }, call, (original, actual) =>\n            {\n                Assert.NotEqual(original, actual);\n                Assert.Equal(expected, actual);\n            });\n        }\n\n        private static void RunOnStartBlockTest(Func<Action<BlockType>, CallbackVisitor> ctor, Action<BlockType, BlockType> verifyResults = null)\n        {\n            RunCallbackTest(BlockType.Markup, ctor, (listener, expected) => listener.VisitStartBlock(new BlockBuilder() { Type = expected }.Build()), verifyResults);\n        }\n\n        private static void RunOnEndBlockTest(Func<Action<BlockType>, CallbackVisitor> ctor, Action<BlockType, BlockType> verifyResults = null)\n        {\n            RunCallbackTest(BlockType.Markup, ctor, (listener, expected) => listener.VisitEndBlock(new BlockBuilder() { Type = expected }.Build()), verifyResults);\n        }\n\n        private static void RunOnErrorTest(Func<Action<RazorError>, CallbackVisitor> ctor, Action<RazorError, RazorError> verifyResults = null)\n        {\n            RunCallbackTest(new RazorError(\"Foo\", SourceLocation.Zero), ctor, (listener, expected) => listener.VisitError(expected), verifyResults);\n        }\n\n        private static void RunOnEndSpanTest(Func<Action<Span>, CallbackVisitor> ctor, Action<Span, Span> verifyResults = null)\n        {\n            RunCallbackTest(new SpanBuilder().Build(), ctor, (listener, expected) => listener.VisitSpan(expected), verifyResults);\n        }\n\n        private static void RunCallbackTest<T>(T expected, Func<Action<T>, CallbackVisitor> ctor, Action<CallbackVisitor, T> call, Action<T, T> verifyResults = null)\n        {\n            // Arrange\n            object actual = null;\n            Action<T> callback = t => actual = t;\n\n            CallbackVisitor listener = ctor(callback);\n\n            // Act\n            call(listener, expected);\n\n            // Assert\n            if (verifyResults == null)\n            {\n                Assert.Equal(expected, actual);\n            }\n            else\n            {\n                verifyResults(expected, (T)actual);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/Html/HtmlAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Editor;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.Html\n{\n    public class HtmlAttributeTest : CsHtmlMarkupParserTestBase\n    {\n        [Fact]\n        public void SimpleLiteralAttribute()\n        {\n            ParseBlockTest(\"<a href='Foo' />\",\n                new MarkupBlock(\n                    Factory.Markup(\"<a\"),\n                    new MarkupBlock(new AttributeBlockCodeGenerator(name: \"href\", prefix: new LocationTagged<string>(\" href='\", 2, 0, 2), suffix: new LocationTagged<string>(\"'\", 12, 0, 12)),\n                        Factory.Markup(\" href='\").With(SpanCodeGenerator.Null),\n                        Factory.Markup(\"Foo\").With(new LiteralAttributeCodeGenerator(prefix: new LocationTagged<string>(String.Empty, 9, 0, 9), value: new LocationTagged<string>(\"Foo\", 9, 0, 9))),\n                        Factory.Markup(\"'\").With(SpanCodeGenerator.Null)),\n                    Factory.Markup(\" />\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void MultiPartLiteralAttribute()\n        {\n            ParseBlockTest(\"<a href='Foo Bar Baz' />\",\n                new MarkupBlock(\n                    Factory.Markup(\"<a\"),\n                    new MarkupBlock(new AttributeBlockCodeGenerator(name: \"href\", prefix: new LocationTagged<string>(\" href='\", 2, 0, 2), suffix: new LocationTagged<string>(\"'\", 20, 0, 20)),\n                        Factory.Markup(\" href='\").With(SpanCodeGenerator.Null),\n                        Factory.Markup(\"Foo\").With(new LiteralAttributeCodeGenerator(prefix: new LocationTagged<string>(String.Empty, 9, 0, 9), value: new LocationTagged<string>(\"Foo\", 9, 0, 9))),\n                        Factory.Markup(\" Bar\").With(new LiteralAttributeCodeGenerator(prefix: new LocationTagged<string>(\" \", 12, 0, 12), value: new LocationTagged<string>(\"Bar\", 13, 0, 13))),\n                        Factory.Markup(\" Baz\").With(new LiteralAttributeCodeGenerator(prefix: new LocationTagged<string>(\" \", 16, 0, 16), value: new LocationTagged<string>(\"Baz\", 17, 0, 17))),\n                        Factory.Markup(\"'\").With(SpanCodeGenerator.Null)),\n                    Factory.Markup(\" />\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void DoubleQuotedLiteralAttribute()\n        {\n            ParseBlockTest(\"<a href=\\\"Foo Bar Baz\\\" />\",\n                new MarkupBlock(\n                    Factory.Markup(\"<a\"),\n                    new MarkupBlock(new AttributeBlockCodeGenerator(name: \"href\", prefix: new LocationTagged<string>(\" href=\\\"\", 2, 0, 2), suffix: new LocationTagged<string>(\"\\\"\", 20, 0, 20)),\n                        Factory.Markup(\" href=\\\"\").With(SpanCodeGenerator.Null),\n                        Factory.Markup(\"Foo\").With(new LiteralAttributeCodeGenerator(prefix: new LocationTagged<string>(String.Empty, 9, 0, 9), value: new LocationTagged<string>(\"Foo\", 9, 0, 9))),\n                        Factory.Markup(\" Bar\").With(new LiteralAttributeCodeGenerator(prefix: new LocationTagged<string>(\" \", 12, 0, 12), value: new LocationTagged<string>(\"Bar\", 13, 0, 13))),\n                        Factory.Markup(\" Baz\").With(new LiteralAttributeCodeGenerator(prefix: new LocationTagged<string>(\" \", 16, 0, 16), value: new LocationTagged<string>(\"Baz\", 17, 0, 17))),\n                        Factory.Markup(\"\\\"\").With(SpanCodeGenerator.Null)),\n                    Factory.Markup(\" />\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void UnquotedLiteralAttribute()\n        {\n            ParseBlockTest(\"<a href=Foo Bar Baz />\",\n                new MarkupBlock(\n                    Factory.Markup(\"<a\"),\n                    new MarkupBlock(new AttributeBlockCodeGenerator(name: \"href\", prefix: new LocationTagged<string>(\" href=\", 2, 0, 2), suffix: new LocationTagged<string>(String.Empty, 11, 0, 11)),\n                        Factory.Markup(\" href=\").With(SpanCodeGenerator.Null),\n                        Factory.Markup(\"Foo\").With(new LiteralAttributeCodeGenerator(prefix: new LocationTagged<string>(String.Empty, 8, 0, 8), value: new LocationTagged<string>(\"Foo\", 8, 0, 8)))),\n                    Factory.Markup(\" Bar Baz />\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void SimpleExpressionAttribute()\n        {\n            ParseBlockTest(\"<a href='@foo' />\",\n                new MarkupBlock(\n                    Factory.Markup(\"<a\"),\n                    new MarkupBlock(new AttributeBlockCodeGenerator(name: \"href\", prefix: new LocationTagged<string>(\" href='\", 2, 0, 2), suffix: new LocationTagged<string>(\"'\", 13, 0, 13)),\n                        Factory.Markup(\" href='\").With(SpanCodeGenerator.Null),\n                        new MarkupBlock(new DynamicAttributeBlockCodeGenerator(new LocationTagged<string>(String.Empty, 9, 0, 9), 9, 0, 9),\n                            new ExpressionBlock(\n                                Factory.CodeTransition(),\n                                Factory.Code(\"foo\")\n                                       .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                       .Accepts(AcceptedCharacters.NonWhiteSpace))),\n                        Factory.Markup(\"'\").With(SpanCodeGenerator.Null)),\n                    Factory.Markup(\" />\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void MultiValueExpressionAttribute()\n        {\n            ParseBlockTest(\"<a href='@foo bar @baz' />\",\n                new MarkupBlock(\n                    Factory.Markup(\"<a\"),\n                    new MarkupBlock(new AttributeBlockCodeGenerator(name: \"href\", prefix: new LocationTagged<string>(\" href='\", 2, 0, 2), suffix: new LocationTagged<string>(\"'\", 22, 0, 22)),\n                        Factory.Markup(\" href='\").With(SpanCodeGenerator.Null),\n                        new MarkupBlock(new DynamicAttributeBlockCodeGenerator(new LocationTagged<string>(String.Empty, 9, 0, 9), 9, 0, 9),\n                            new ExpressionBlock(\n                                Factory.CodeTransition(),\n                                Factory.Code(\"foo\")\n                                       .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                       .Accepts(AcceptedCharacters.NonWhiteSpace))),\n                        Factory.Markup(\" bar\").With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(\" \", 13, 0, 13), new LocationTagged<string>(\"bar\", 14, 0, 14))),\n                        new MarkupBlock(new DynamicAttributeBlockCodeGenerator(new LocationTagged<string>(\" \", 17, 0, 17), 18, 0, 18),\n                            Factory.Markup(\" \").With(SpanCodeGenerator.Null),\n                            new ExpressionBlock(\n                                Factory.CodeTransition(),\n                                Factory.Code(\"baz\")\n                                       .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                       .Accepts(AcceptedCharacters.NonWhiteSpace))),\n                        Factory.Markup(\"'\").With(SpanCodeGenerator.Null)),\n                    Factory.Markup(\" />\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void VirtualPathAttributesWorkWithConditionalAttributes()\n        {\n            ParseBlockTest(\"<a href='@foo ~/Foo/Bar' />\",\n                new MarkupBlock(\n                    Factory.Markup(\"<a\"),\n                    new MarkupBlock(new AttributeBlockCodeGenerator(name: \"href\", prefix: new LocationTagged<string>(\" href='\", 2, 0, 2), suffix: new LocationTagged<string>(\"'\", 23, 0, 23)),\n                        Factory.Markup(\" href='\").With(SpanCodeGenerator.Null),\n                        new MarkupBlock(new DynamicAttributeBlockCodeGenerator(new LocationTagged<string>(String.Empty, 9, 0, 9), 9, 0, 9),\n                            new ExpressionBlock(\n                                Factory.CodeTransition(),\n                                Factory.Code(\"foo\")\n                                       .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                       .Accepts(AcceptedCharacters.NonWhiteSpace))),\n                        Factory.Markup(\" ~/Foo/Bar\")\n                               .WithEditorHints(EditorHints.VirtualPath)\n                               .With(new LiteralAttributeCodeGenerator(\n                                   new LocationTagged<string>(\" \", 13, 0, 13),\n                                   new LocationTagged<SpanCodeGenerator>(new ResolveUrlCodeGenerator(), 14, 0, 14))),\n                        Factory.Markup(\"'\").With(SpanCodeGenerator.Null)),\n                    Factory.Markup(\" />\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void UnquotedAttributeWithCodeWithSpacesInBlock()\n        {\n            ParseBlockTest(\"<input value=@foo />\",\n                new MarkupBlock(\n                    Factory.Markup(\"<input\"),\n                    new MarkupBlock(new AttributeBlockCodeGenerator(name: \"value\", prefix: new LocationTagged<string>(\" value=\", 6, 0, 6), suffix: new LocationTagged<string>(String.Empty, 17, 0, 17)),\n                        Factory.Markup(\" value=\").With(SpanCodeGenerator.Null),\n                        new MarkupBlock(new DynamicAttributeBlockCodeGenerator(new LocationTagged<string>(String.Empty, 13, 0, 13), 13, 0, 13),\n                            new ExpressionBlock(\n                                Factory.CodeTransition(),\n                                Factory.Code(\"foo\")\n                                       .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                       .Accepts(AcceptedCharacters.NonWhiteSpace)))),\n                    Factory.Markup(\" />\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void UnquotedAttributeWithCodeWithSpacesInDocument()\n        {\n            ParseDocumentTest(\"<input value=@foo />\",\n                new MarkupBlock(\n                    Factory.Markup(\"<input\"),\n                    new MarkupBlock(new AttributeBlockCodeGenerator(name: \"value\", prefix: new LocationTagged<string>(\" value=\", 6, 0, 6), suffix: new LocationTagged<string>(String.Empty, 17, 0, 17)),\n                        Factory.Markup(\" value=\").With(SpanCodeGenerator.Null),\n                        new MarkupBlock(new DynamicAttributeBlockCodeGenerator(new LocationTagged<string>(String.Empty, 13, 0, 13), 13, 0, 13),\n                            new ExpressionBlock(\n                                Factory.CodeTransition(),\n                                Factory.Code(\"foo\")\n                                       .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                       .Accepts(AcceptedCharacters.NonWhiteSpace)))),\n                    Factory.Markup(\" />\")));\n        }\n\n        [Fact]\n        public void ConditionalAttributeCollapserDoesNotRemoveUrlAttributeValues()\n        {\n            // Act\n            ParserResults results = ParseDocument(\"<a href='~/Foo/Bar' />\");\n            Block rewritten = new ConditionalAttributeCollapser(new HtmlMarkupParser().BuildSpan).Rewrite(results.Document);\n            rewritten = new MarkupCollapser(new HtmlMarkupParser().BuildSpan).Rewrite(rewritten);\n\n            // Assert\n            Assert.Equal(0, results.ParserErrors.Count);\n            EvaluateParseTree(rewritten,\n                new MarkupBlock(\n                    Factory.Markup(\"<a\"),\n                    new MarkupBlock(new AttributeBlockCodeGenerator(name: \"href\", prefix: new LocationTagged<string>(\" href='\", 2, 0, 2), suffix: new LocationTagged<string>(\"'\", 18, 0, 18)),\n                        Factory.Markup(\" href='\").With(SpanCodeGenerator.Null),\n                        Factory.Markup(\"~/Foo/Bar\")\n                               .WithEditorHints(EditorHints.VirtualPath)\n                               .With(new LiteralAttributeCodeGenerator(\n                                   new LocationTagged<string>(String.Empty, 9, 0, 9),\n                                   new LocationTagged<SpanCodeGenerator>(new ResolveUrlCodeGenerator(), 9, 0, 9))),\n                        Factory.Markup(\"'\").With(SpanCodeGenerator.Null)),\n                    Factory.Markup(\" />\")));\n        }\n\n        [Fact]\n        public void ConditionalAttributesDoNotCreateExtraDataForEntirelyLiteralAttribute()\n        {\n            // Arrange\n            const string code =\n @\"<div class=\"\"sidebar\"\">\n    <h1>Title</h1>\n    <p>\n        As the author, you can <a href=\"\"/Photo/Edit/photoId\"\">edit</a>\n        or <a href=\"\"/Photo/Remove/photoId\"\">remove</a> this photo.\n    </p>\n    <dl>\n        <dt class=\"\"description\"\">Description</dt>\n        <dd class=\"\"description\"\">\n            The uploader did not provide a description for this photo.\n        </dd>\n        <dt class=\"\"uploaded-by\"\">Uploaded by</dt>\n        <dd class=\"\"uploaded-by\"\"><a href=\"\"/User/View/user.UserId\"\">user.DisplayName</a></dd>\n        <dt class=\"\"upload-date\"\">Upload date</dt>\n        <dd class=\"\"upload-date\"\">photo.UploadDate</dd>\n        <dt class=\"\"part-of-gallery\"\">Gallery</dt>\n        <dd><a href=\"\"/View/gallery.Id\"\" title=\"\"View gallery.Name gallery\"\">gallery.Name</a></dd>\n        <dt class=\"\"tags\"\">Tags</dt>\n        <dd class=\"\"tags\"\">\n            <ul class=\"\"tags\"\">\n                <li>This photo has no tags.</li>\n            </ul>\n            <a href=\"\"/Photo/EditTags/photoId\"\">edit tags</a>\n        </dd>\n    </dl>\n\n    <p>\n        <a class=\"\"download\"\" href=\"\"/Photo/Full/photoId\"\" title=\"\"Download: (photo.FileTitle + photo.FileExtension)\"\">Download full photo</a> ((photo.FileSize / 1024) KB)\n    </p>\n</div>\n<div class=\"\"main\"\">\n    <img class=\"\"large-photo\"\" alt=\"\"photo.FileTitle\"\" src=\"\"/Photo/Thumbnail\"\" />\n    <h2>Nobody has commented on this photo</h2>\n    <ol class=\"\"comments\"\">\n        <li>\n            <h3 class=\"\"comment-header\"\">\n                <a href=\"\"/User/View/comment.UserId\"\" title=\"\"View comment.DisplayName's profile\"\">comment.DisplayName</a> commented at comment.CommentDate:\n            </h3>\n            <p class=\"\"comment-body\"\">comment.CommentText</p>\n        </li>\n    </ol>\n\n    <form method=\"\"post\"\" action=\"\"\"\">\n        <fieldset id=\"\"addComment\"\">\n            <legend>Post new comment</legend>\n            <ol>\n                <li>\n                    <label for=\"\"newComment\"\">Comment</label>\n                    <textarea id=\"\"newComment\"\" name=\"\"newComment\"\" title=\"\"Your comment\"\" rows=\"\"6\"\" cols=\"\"70\"\"></textarea>\n                </li>\n            </ol>\n            <p class=\"\"form-actions\"\">\n                <input type=\"\"submit\"\" title=\"\"Add comment\"\" value=\"\"Add comment\"\" />\n            </p>\n        </fieldset>\n    </form>\n</div>\";\n\n            // Act\n            ParserResults results = ParseDocument(code);\n            Block rewritten = new ConditionalAttributeCollapser(new HtmlMarkupParser().BuildSpan).Rewrite(results.Document);\n            rewritten = new MarkupCollapser(new HtmlMarkupParser().BuildSpan).Rewrite(rewritten);\n\n            // Assert\n            Assert.Equal(0, results.ParserErrors.Count);\n            EvaluateParseTree(rewritten, new MarkupBlock(Factory.Markup(code)));\n        }\n\n        [Fact]\n        public void ConditionalAttributesAreDisabledForDataAttributesInBlock()\n        {\n            ParseBlockTest(\"<span data-foo='@foo'></span>\",\n                new MarkupBlock(\n                    Factory.Markup(\"<span\"),\n                    new MarkupBlock(\n                        Factory.Markup(\" data-foo='\"),\n                        new ExpressionBlock(\n                            Factory.CodeTransition(),\n                            Factory.Code(\"foo\")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                        Factory.Markup(\"'\")),\n                    Factory.Markup(\"></span>\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ConditionalAttributesAreDisabledForDataAttributesInDocument()\n        {\n            ParseDocumentTest(\"<span data-foo='@foo'></span>\",\n                new MarkupBlock(\n                    Factory.Markup(\"<span\"),\n                    new MarkupBlock(\n                        Factory.Markup(\" data-foo='\"),\n                        new ExpressionBlock(\n                            Factory.CodeTransition(),\n                            Factory.Code(\"foo\")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                        Factory.Markup(\"'\")),\n                    Factory.Markup(\"></span>\")));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/Html/HtmlBlockTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Editor;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.Html\n{\n    public class HtmlBlockTest : CsHtmlMarkupParserTestBase\n    {\n        [Fact]\n        public void ParseBlockMethodThrowsArgNullExceptionOnNullContext()\n        {\n            // Arrange\n            HtmlMarkupParser parser = new HtmlMarkupParser();\n\n            // Act and Assert\n            Assert.Throws<InvalidOperationException>(() => parser.ParseBlock(), RazorResources.Parser_Context_Not_Set);\n        }\n\n        [Fact]\n        public void ParseBlockHandlesOpenAngleAtEof()\n        {\n            ParseDocumentTest(\"@{\" + Environment.NewLine\n                            + \"<\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new StatementBlock(\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                        Factory.Code(\"\\r\\n\").AsStatement(),\n                        new MarkupBlock(\n                            Factory.Markup(\"<\")))),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF, RazorResources.BlockName_Code, \"}\", \"{\"),\n                    1, 0, 1));\n        }\n\n        [Fact]\n        public void ParseBlockHandlesOpenAngleWithProperTagFollowingIt()\n        {\n            ParseDocumentTest(\"@{\" + Environment.NewLine\n                            + \"<\" + Environment.NewLine\n                            + \"</html>\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new StatementBlock(\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                        Factory.Code(\"\\r\\n\").AsStatement(),\n                        new MarkupBlock(\n                            Factory.Markup(\"<\\r\\n\")\n                        ),\n                        new MarkupBlock(\n                            Factory.Markup(@\"</html>\").Accepts(AcceptedCharacters.None)\n                        ),\n                        Factory.EmptyCSharp().AsStatement()\n                    )\n                ),\n                designTimeParser: true,\n                expectedErrors: new[]\n                {\n                    new RazorError(String.Format(RazorResources.ParseError_UnexpectedEndTag, \"html\"), 7, 2, 0),\n                    new RazorError(String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF, \"code\", \"}\", \"{\"), 1, 0, 1)\n                });\n        }\n\n        [Fact]\n        public void TagWithoutCloseAngleDoesNotTerminateBlock()\n        {\n            ParseBlockTest(\"<                      \" + Environment.NewLine\n                         + \"   \",\n                new MarkupBlock(\n                    Factory.Markup(\"<                      \\r\\n   \")),\n                designTimeParser: true,\n                expectedErrors: new RazorError(String.Format(RazorResources.ParseError_UnfinishedTag, String.Empty), 0, 0, 0));\n        }\n\n        [Fact]\n        public void ParseBlockAllowsStartAndEndTagsToDifferInCase()\n        {\n            SingleSpanBlockTest(\"<li><p>Foo</P></lI>\", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockReadsToEndOfLineIfFirstCharacterAfterTransitionIsColon()\n        {\n            ParseBlockTest(\"@:<li>Foo Bar Baz\" + Environment.NewLine\n                         + \"bork\",\n                new MarkupBlock(\n                    Factory.MarkupTransition(),\n                    Factory.MetaMarkup(\":\", HtmlSymbolType.Colon),\n                    Factory.Markup(\"<li>Foo Bar Baz\\r\\n\")\n                           .With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None))\n                ));\n        }\n\n        [Fact]\n        public void ParseBlockStopsParsingSingleLineBlockAtEOFIfNoEOLReached()\n        {\n            ParseBlockTest(\"@:foo bar\",\n                new MarkupBlock(\n                    Factory.MarkupTransition(),\n                    Factory.MetaMarkup(\":\", HtmlSymbolType.Colon),\n                    Factory.Markup(@\"foo bar\")\n                           .With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString))\n                    ));\n        }\n\n        [Fact]\n        public void ParseBlockStopsAtMatchingCloseTagToStartTag()\n        {\n            SingleSpanBlockTest(\"<a><b></b></a><c></c>\", \"<a><b></b></a>\", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockParsesUntilMatchingEndTagIfFirstNonWhitespaceCharacterIsStartTag()\n        {\n            SingleSpanBlockTest(\"<baz><boz><biz></biz></boz></baz>\", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockAllowsUnclosedTagsAsLongAsItCanRecoverToAnExpectedEndTag()\n        {\n            SingleSpanBlockTest(\"<foo><bar><baz></foo>\", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockWithSelfClosingTagJustEmitsTag()\n        {\n            SingleSpanBlockTest(\"<foo />\", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockCanHandleSelfClosingTagsWithinBlock()\n        {\n            SingleSpanBlockTest(\"<foo><bar /></foo>\", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsTagsWithAttributes()\n        {\n            ParseBlockTest(\"<foo bar=\\\"baz\\\"><biz><boz zoop=zork/></biz></foo>\",\n                new MarkupBlock(\n                    Factory.Markup(\"<foo\"),\n                    new MarkupBlock(new AttributeBlockCodeGenerator(\"bar\", new LocationTagged<string>(\" bar=\\\"\", 4, 0, 4), new LocationTagged<string>(\"\\\"\", 13, 0, 13)),\n                        Factory.Markup(\" bar=\\\"\").With(SpanCodeGenerator.Null),\n                        Factory.Markup(\"baz\").With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(String.Empty, 10, 0, 10), new LocationTagged<string>(\"baz\", 10, 0, 10))),\n                        Factory.Markup(\"\\\"\").With(SpanCodeGenerator.Null)),\n                    Factory.Markup(\"><biz><boz\"),\n                    new MarkupBlock(new AttributeBlockCodeGenerator(\"zoop\", new LocationTagged<string>(\" zoop=\", 24, 0, 24), new LocationTagged<string>(String.Empty, 34, 0, 34)),\n                        Factory.Markup(\" zoop=\").With(SpanCodeGenerator.Null),\n                        Factory.Markup(\"zork\").With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(String.Empty, 30, 0, 30), new LocationTagged<string>(\"zork\", 30, 0, 30)))),\n                    Factory.Markup(\"/></biz></foo>\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockAllowsCloseAngleBracketInAttributeValueIfDoubleQuoted()\n        {\n            ParseBlockTest(\"<foo><bar baz=\\\">\\\" /></foo>\",\n                new MarkupBlock(\n                    Factory.Markup(\"<foo><bar\"),\n                    new MarkupBlock(new AttributeBlockCodeGenerator(\"baz\", new LocationTagged<string>(\" baz=\\\"\", 9, 0, 9), new LocationTagged<string>(\"\\\"\", 16, 0, 16)),\n                        Factory.Markup(\" baz=\\\"\").With(SpanCodeGenerator.Null),\n                        Factory.Markup(\">\").With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(String.Empty, 15, 0, 15), new LocationTagged<string>(\">\", 15, 0, 15))),\n                        Factory.Markup(\"\\\"\").With(SpanCodeGenerator.Null)),\n                    Factory.Markup(\" /></foo>\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockAllowsCloseAngleBracketInAttributeValueIfSingleQuoted()\n        {\n            ParseBlockTest(\"<foo><bar baz=\\'>\\' /></foo>\",\n                new MarkupBlock(\n                    Factory.Markup(\"<foo><bar\"),\n                    new MarkupBlock(new AttributeBlockCodeGenerator(\"baz\", new LocationTagged<string>(\" baz='\", 9, 0, 9), new LocationTagged<string>(\"'\", 16, 0, 16)),\n                        Factory.Markup(\" baz='\").With(SpanCodeGenerator.Null),\n                        Factory.Markup(\">\").With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(String.Empty, 15, 0, 15), new LocationTagged<string>(\">\", 15, 0, 15))),\n                        Factory.Markup(\"'\").With(SpanCodeGenerator.Null)),\n                    Factory.Markup(\" /></foo>\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockAllowsSlashInAttributeValueIfDoubleQuoted()\n        {\n            ParseBlockTest(\"<foo><bar baz=\\\"/\\\"></bar></foo>\",\n                new MarkupBlock(\n                    Factory.Markup(\"<foo><bar\"),\n                    new MarkupBlock(new AttributeBlockCodeGenerator(\"baz\", new LocationTagged<string>(\" baz=\\\"\", 9, 0, 9), new LocationTagged<string>(\"\\\"\", 16, 0, 16)),\n                        Factory.Markup(\" baz=\\\"\").With(SpanCodeGenerator.Null),\n                        Factory.Markup(\"/\").With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(String.Empty, 15, 0, 15), new LocationTagged<string>(\"/\", 15, 0, 15))),\n                        Factory.Markup(\"\\\"\").With(SpanCodeGenerator.Null)),\n                    Factory.Markup(\"></bar></foo>\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockAllowsSlashInAttributeValueIfSingleQuoted()\n        {\n            ParseBlockTest(\"<foo><bar baz=\\'/\\'></bar></foo>\",\n                new MarkupBlock(\n                    Factory.Markup(\"<foo><bar\"),\n                    new MarkupBlock(new AttributeBlockCodeGenerator(\"baz\", new LocationTagged<string>(\" baz='\", 9, 0, 9), new LocationTagged<string>(\"'\", 16, 0, 16)),\n                        Factory.Markup(\" baz='\").With(SpanCodeGenerator.Null),\n                        Factory.Markup(\"/\").With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(String.Empty, 15, 0, 15), new LocationTagged<string>(\"/\", 15, 0, 15))),\n                        Factory.Markup(\"'\").With(SpanCodeGenerator.Null)),\n                    Factory.Markup(\"></bar></foo>\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockTerminatesAtEOF()\n        {\n            SingleSpanBlockTest(\"<foo>\", \"<foo>\", BlockType.Markup, SpanKind.Markup,\n                                new RazorError(String.Format(RazorResources.ParseError_MissingEndTag, \"foo\"), new SourceLocation(0, 0, 0)));\n        }\n\n        [Fact]\n        public void ParseBlockSupportsCommentAsBlock()\n        {\n            SingleSpanBlockTest(\"<!-- foo -->\", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsCommentWithinBlock()\n        {\n            SingleSpanBlockTest(\"<foo>bar<!-- zoop -->baz</foo>\", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockProperlyBalancesCommentStartAndEndTags()\n        {\n            SingleSpanBlockTest(\"<!--<foo></bar>-->\", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockTerminatesAtEOFWhenParsingComment()\n        {\n            SingleSpanBlockTest(\"<!--<foo>\", \"<!--<foo>\", BlockType.Markup, SpanKind.Markup);\n        }\n\n        [Fact]\n        public void ParseBlockOnlyTerminatesCommentOnFullEndSequence()\n        {\n            SingleSpanBlockTest(\"<!--<foo>--</bar>-->\", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockTerminatesCommentAtFirstOccurrenceOfEndSequence()\n        {\n            SingleSpanBlockTest(\"<foo><!--<foo></bar-->--></foo>\", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockTreatsMalformedTagsAsContent()\n        {\n            SingleSpanBlockTest(\n                \"<foo></!-- bar --></foo>\",\n                \"<foo></!-- bar -->\",\n                BlockType.Markup,\n                SpanKind.Markup,\n                AcceptedCharacters.None,\n                new RazorError(String.Format(RazorResources.ParseError_MissingEndTag, \"foo\"), 0, 0, 0));\n        }\n\n\n        [Fact]\n        public void ParseBlockParsesSGMLDeclarationAsEmptyTag()\n        {\n            SingleSpanBlockTest(\"<foo><!DOCTYPE foo bar baz></foo>\", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockTerminatesSGMLDeclarationAtFirstCloseAngle()\n        {\n            SingleSpanBlockTest(\"<foo><!DOCTYPE foo bar> baz></foo>\", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockParsesXMLProcessingInstructionAsEmptyTag()\n        {\n            SingleSpanBlockTest(\"<foo><?xml foo bar baz?></foo>\", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockTerminatesXMLProcessingInstructionAtQuestionMarkCloseAnglePair()\n        {\n            SingleSpanBlockTest(\"<foo><?xml foo bar?> baz</foo>\", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockDoesNotTerminateXMLProcessingInstructionAtCloseAngleUnlessPreceededByQuestionMark()\n        {\n            SingleSpanBlockTest(\"<foo><?xml foo bar> baz?></foo>\", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsScriptTagsWithLessThanSignsInThem()\n        {\n            SingleSpanBlockTest(@\"<script>if(foo<bar) { alert(\"\"baz\"\");)</script>\", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsScriptTagsWithSpacedLessThanSignsInThem()\n        {\n            SingleSpanBlockTest(@\"<script>if(foo < bar) { alert(\"\"baz\"\");)</script>\", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockAcceptsEmptyTextTag()\n        {\n            ParseBlockTest(\"<text/>\",\n                new MarkupBlock(\n                    Factory.MarkupTransition(\"<text/>\")\n                ));\n        }\n\n        [Fact]\n        public void ParseBlockAcceptsTextTagAsOuterTagButDoesNotRender()\n        {\n            ParseBlockTest(\"<text>Foo Bar <foo> Baz</text> zoop\",\n                new MarkupBlock(\n                    Factory.MarkupTransition(\"<text>\"),\n                    Factory.Markup(\"Foo Bar <foo> Baz\"),\n                    Factory.MarkupTransition(\"</text>\"),\n                    Factory.Markup(\" \").Accepts(AcceptedCharacters.None)\n                ));\n        }\n\n        [Fact]\n        public void ParseBlockRendersLiteralTextTagIfDoubled()\n        {\n            ParseBlockTest(\"<text><text>Foo Bar <foo> Baz</text></text> zoop\",\n                new MarkupBlock(\n                    Factory.MarkupTransition(\"<text>\"),\n                    Factory.Markup(\"<text>Foo Bar <foo> Baz</text>\"),\n                    Factory.MarkupTransition(\"</text>\"),\n                    Factory.Markup(\" \").Accepts(AcceptedCharacters.None)\n                ));\n        }\n\n        [Fact]\n        public void ParseBlockDoesNotConsiderPsuedoTagWithinMarkupBlock()\n        {\n            ParseBlockTest(\"<foo><text><bar></bar></foo>\",\n                new MarkupBlock(\n                    Factory.Markup(\"<foo><text><bar></bar></foo>\").Accepts(AcceptedCharacters.None)\n                ));\n        }\n\n        [Fact]\n        public void ParseBlockStopsParsingMidEmptyTagIfEOFReached()\n        {\n            ParseBlockTest(\"<br/\",\n                new MarkupBlock(\n                    Factory.Markup(\"<br/\")\n                ),\n                new RazorError(String.Format(RazorResources.ParseError_UnfinishedTag, \"br\"), SourceLocation.Zero));\n        }\n\n        [Fact]\n        public void ParseBlockCorrectlyHandlesSingleLineOfMarkupWithEmbeddedStatement()\n        {\n            ParseBlockTest(\"<div>Foo @if(true) {} Bar</div>\",\n                new MarkupBlock(\n                    Factory.Markup(\"<div>Foo \"),\n                    new StatementBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"if(true) {}\").AsStatement()),\n                    Factory.Markup(\" Bar</div>\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockIgnoresTagsInContentsOfScriptTag()\n        {\n            ParseBlockTest(@\"<script>foo<bar baz='@boz'></script>\",\n                new MarkupBlock(\n                    Factory.Markup(\"<script>foo<bar baz='\"),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"boz\")\n                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: false)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    Factory.Markup(\"'></script>\")\n                           .Accepts(AcceptedCharacters.None)));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/Html/HtmlDocumentTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.Html\n{\n    public class HtmlDocumentTest : CsHtmlMarkupParserTestBase\n    {\n        private static readonly TestFile Nested1000 = TestFile.Create(\"nested-1000.html\");\n\n        [Fact]\n        public void ParseDocumentMethodThrowsArgNullExceptionOnNullContext()\n        {\n            // Arrange\n            HtmlMarkupParser parser = new HtmlMarkupParser();\n\n            // Act and Assert\n            Assert.Throws<InvalidOperationException>(() => parser.ParseDocument(), RazorResources.Parser_Context_Not_Set);\n        }\n\n        [Fact]\n        public void ParseSectionMethodThrowsArgNullExceptionOnNullContext()\n        {\n            // Arrange\n            HtmlMarkupParser parser = new HtmlMarkupParser();\n\n            // Act and Assert\n            Assert.Throws<InvalidOperationException>(() => parser.ParseSection(null, true), RazorResources.Parser_Context_Not_Set);\n        }\n\n        [Fact]\n        public void ParseDocumentOutputsEmptyBlockWithEmptyMarkupSpanIfContentIsEmptyString()\n        {\n            ParseDocumentTest(String.Empty, new MarkupBlock(Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void ParseDocumentOutputsWhitespaceOnlyContentAsSingleWhitespaceMarkupSpan()\n        {\n            SingleSpanDocumentTest(\"          \", BlockType.Markup, SpanKind.Markup);\n        }\n\n        [Fact]\n        public void ParseDocumentAcceptsSwapTokenAtEndOfFileAndOutputsZeroLengthCodeSpan()\n        {\n            ParseDocumentTest(\"@\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.EmptyCSharp()\n                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    Factory.EmptyHtml()),\n                new RazorError(RazorResources.ParseError_Unexpected_EndOfFile_At_Start_Of_CodeBlock, 1, 0, 1));\n        }\n\n        [Fact]\n        public void ParseDocumentCorrectlyHandlesSingleLineOfMarkupWithEmbeddedStatement()\n        {\n            ParseDocumentTest(\"<div>Foo @if(true) {} Bar</div>\",\n                new MarkupBlock(\n                    Factory.Markup(\"<div>Foo \"),\n                    new StatementBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"if(true) {}\").AsStatement()),\n                    Factory.Markup(\" Bar</div>\")));\n        }\n\n        [Fact]\n        public void ParseDocumentWithinSectionDoesNotCreateDocumentLevelSpan()\n        {\n            ParseDocumentTest(\"@section Foo {\" + Environment.NewLine\n                            + \"    <html></html>\" + Environment.NewLine\n                            + \"}\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"Foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section Foo {\")\n                               .AutoCompleteWith(null, atEndOfSpan: true),\n                        new MarkupBlock(\n                            Factory.Markup(\"\\r\\n    <html></html>\\r\\n\")),\n                        Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void ParseDocumentParsesWholeContentAsOneSpanIfNoSwapCharacterEncountered()\n        {\n            SingleSpanDocumentTest(\"foo <bar>baz</bar>\", BlockType.Markup, SpanKind.Markup);\n        }\n\n        [Fact]\n        public void ParseDocumentHandsParsingOverToCodeParserWhenAtSignEncounteredAndEmitsOutput()\n        {\n            ParseDocumentTest(\"foo @bar baz\",\n                new MarkupBlock(\n                    Factory.Markup(\"foo \"),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"bar\")\n                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    Factory.Markup(\" baz\")));\n        }\n\n        [Fact]\n        public void ParseDocumentEmitsAtSignAsMarkupIfAtEndOfFile()\n        {\n            ParseDocumentTest(\"foo @\",\n                new MarkupBlock(\n                    Factory.Markup(\"foo \"),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.EmptyCSharp()\n                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    Factory.EmptyHtml()),\n                new RazorError(RazorResources.ParseError_Unexpected_EndOfFile_At_Start_Of_CodeBlock, 5, 0, 5));\n        }\n\n        [Fact]\n        public void ParseDocumentEmitsCodeBlockIfFirstCharacterIsSwapCharacter()\n        {\n            ParseDocumentTest(\"@bar\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"bar\")\n                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void ParseDocumentDoesNotSwitchToCodeOnEmailAddressInText()\n        {\n            SingleSpanDocumentTest(\"<foo>anurse@microsoft.com</foo>\", BlockType.Markup, SpanKind.Markup);\n        }\n\n        [Fact]\n        public void ParseDocumentDoesNotSwitchToCodeOnEmailAddressInAttribute()\n        {\n            ParseDocumentTest(\"<a href=\\\"mailto:anurse@microsoft.com\\\">Email me</a>\",\n                new MarkupBlock(\n                    Factory.Markup(\"<a\"),\n                    new MarkupBlock(new AttributeBlockCodeGenerator(\"href\", new LocationTagged<string>(\" href=\\\"\", 2, 0, 2), new LocationTagged<string>(\"\\\"\", 36, 0, 36)),\n                        Factory.Markup(\" href=\\\"\").With(SpanCodeGenerator.Null),\n                        Factory.Markup(\"mailto:anurse@microsoft.com\")\n                               .With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(String.Empty, 9, 0, 9), new LocationTagged<string>(\"mailto:anurse@microsoft.com\", 9, 0, 9))),\n                        Factory.Markup(\"\\\"\").With(SpanCodeGenerator.Null)),\n                    Factory.Markup(\">Email me</a>\")));\n        }\n\n        [Fact]\n        public void ParseDocumentDoesNotReturnErrorOnMismatchedTags()\n        {\n            SingleSpanDocumentTest(\"Foo <div><p></p></p> Baz\", BlockType.Markup, SpanKind.Markup);\n        }\n\n        [Fact]\n        public void ParseDocumentReturnsOneMarkupSegmentIfNoCodeBlocksEncountered()\n        {\n            SingleSpanDocumentTest(\"Foo <p>Baz<!--Foo-->Bar<!-F> Qux\", BlockType.Markup, SpanKind.Markup);\n        }\n\n        [Fact]\n        public void ParseDocumentRendersTextPseudoTagAsMarkup()\n        {\n            SingleSpanDocumentTest(\"Foo <text>Foo</text>\", BlockType.Markup, SpanKind.Markup);\n        }\n\n        [Fact]\n        public void ParseDocumentAcceptsEndTagWithNoMatchingStartTag()\n        {\n            SingleSpanDocumentTest(\"Foo </div> Bar\", BlockType.Markup, SpanKind.Markup);\n        }\n\n        [Fact]\n        public void ParseDocumentNoLongerSupportsDollarOpenBraceCombination()\n        {\n            ParseDocumentTest(\"<foo>${bar}</foo>\",\n                new MarkupBlock(\n                    Factory.Markup(\"<foo>${bar}</foo>\")));\n        }\n\n        [Fact]\n        public void ParseDocumentIgnoresTagsInContentsOfScriptTag()\n        {\n            ParseDocumentTest(@\"<script>foo<bar baz='@boz'></script>\",\n                new MarkupBlock(\n                    Factory.Markup(\"<script>foo<bar baz='\"),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"boz\")\n                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: false)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    Factory.Markup(\"'></script>\")));\n        }\n\n        [Fact]\n        public void ParseSectionIgnoresTagsInContentsOfScriptTag()\n        {\n            ParseDocumentTest(@\"@section Foo { <script>foo<bar baz='@boz'></script> }\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"Foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section Foo {\"),\n                        new MarkupBlock(\n                            Factory.Markup(\" <script>foo<bar baz='\"),\n                            new ExpressionBlock(\n                                Factory.CodeTransition(),\n                                Factory.Code(\"boz\")\n                                       .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: false)\n                                       .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                            Factory.Markup(\"'></script> \")),\n                        Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void ParseBlockCanParse1000NestedElements()\n        {\n            string content = Nested1000.ReadAllText();\n            SingleSpanDocumentTest(content, BlockType.Markup, SpanKind.Markup);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/Html/HtmlErrorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.Html\n{\n    public class HtmlErrorTest : CsHtmlMarkupParserTestBase\n    {\n        [Fact]\n        public void ParseBlockAllowsInvalidTagNamesAsLongAsParserCanIdentifyEndTag()\n        {\n            SingleSpanBlockTest(\"<1-foo+bar>foo</1-foo+bar>\", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockThrowsErrorIfStartTextTagContainsTextAfterName()\n        {\n            ParseBlockTest(\"<text foo bar></text>\",\n                new MarkupBlock(\n                    Factory.MarkupTransition(\"<text\").Accepts(AcceptedCharacters.Any),\n                    Factory.Markup(\" foo bar>\"),\n                    Factory.MarkupTransition(\"</text>\")),\n                new RazorError(RazorResources.ParseError_TextTagCannotContainAttributes, SourceLocation.Zero));\n        }\n\n        [Fact]\n        public void ParseBlockThrowsErrorIfEndTextTagContainsTextAfterName()\n        {\n            ParseBlockTest(\"<text></text foo bar>\",\n                new MarkupBlock(\n                    Factory.MarkupTransition(\"<text>\"),\n                    Factory.MarkupTransition(\"</text\").Accepts(AcceptedCharacters.Any),\n                    Factory.Markup(\" \")),\n                new RazorError(RazorResources.ParseError_TextTagCannotContainAttributes, 6, 0, 6));\n        }\n\n        [Fact]\n        public void ParseBlockThrowsExceptionIfBlockDoesNotStartWithTag()\n        {\n            ParseBlockTest(\"foo bar <baz>\",\n                new MarkupBlock(),\n                new RazorError(RazorResources.ParseError_MarkupBlock_Must_Start_With_Tag, SourceLocation.Zero));\n        }\n\n        [Fact]\n        public void ParseBlockStartingWithEndTagProducesRazorErrorThenOutputsMarkupSegmentAndEndsBlock()\n        {\n            ParseBlockTest(\"</foo> bar baz\",\n                new MarkupBlock(\n                    Factory.Markup(\"</foo> \").Accepts(AcceptedCharacters.None)),\n                new RazorError(String.Format(RazorResources.ParseError_UnexpectedEndTag, \"foo\"), SourceLocation.Zero));\n        }\n\n        [Fact]\n        public void ParseBlockWithUnclosedTopLevelTagThrowsMissingEndTagParserExceptionOnOutermostUnclosedTag()\n        {\n            ParseBlockTest(\"<p><foo></bar>\",\n                new MarkupBlock(\n                    Factory.Markup(\"<p><foo></bar>\").Accepts(AcceptedCharacters.None)),\n                new RazorError(String.Format(RazorResources.ParseError_MissingEndTag, \"p\"), new SourceLocation(0, 0, 0)));\n        }\n\n        [Fact]\n        public void ParseBlockWithUnclosedTagAtEOFThrowsMissingEndTagException()\n        {\n            ParseBlockTest(\"<foo>blah blah blah blah blah\",\n                new MarkupBlock(\n                    Factory.Markup(\"<foo>blah blah blah blah blah\")),\n                new RazorError(String.Format(RazorResources.ParseError_MissingEndTag, \"foo\"), new SourceLocation(0, 0, 0)));\n        }\n\n        [Fact]\n        public void ParseBlockWithUnfinishedTagAtEOFThrowsIncompleteTagException()\n        {\n            ParseBlockTest(\"<foo bar=baz\",\n                new MarkupBlock(\n                    Factory.Markup(\"<foo\"),\n                    new MarkupBlock(new AttributeBlockCodeGenerator(\"bar\", new LocationTagged<string>(\" bar=\", 4, 0, 4), new LocationTagged<string>(String.Empty, 12, 0, 12)),\n                        Factory.Markup(\" bar=\").With(SpanCodeGenerator.Null),\n                        Factory.Markup(\"baz\").With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(String.Empty, 9, 0, 9), new LocationTagged<string>(\"baz\", 9, 0, 9))))),\n                new RazorError(String.Format(RazorResources.ParseError_UnfinishedTag, \"foo\"), new SourceLocation(0, 0, 0)));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/Html/HtmlParserTestUtils.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Framework;\n\nnamespace System.Web.Razor.Test.Parser.Html\n{\n    internal class HtmlParserTestUtils\n    {\n        public static void RunSingleAtEscapeTest(Action<string, Block> testMethod, AcceptedCharacters lastSpanAcceptedCharacters = AcceptedCharacters.None)\n        {\n            var factory = SpanFactory.CreateCsHtml();\n            testMethod(\"<foo>@@bar</foo>\",\n                new MarkupBlock(\n                    factory.Markup(\"<foo>\"),\n                    factory.Markup(\"@\").Hidden(),\n                    factory.Markup(\"@bar</foo>\").Accepts(lastSpanAcceptedCharacters)));\n        }\n\n        public static void RunMultiAtEscapeTest(Action<string, Block> testMethod, AcceptedCharacters lastSpanAcceptedCharacters = AcceptedCharacters.None)\n        {\n            var factory = SpanFactory.CreateCsHtml();\n            testMethod(\"<foo>@@@@@bar</foo>\",\n                new MarkupBlock(\n                    factory.Markup(\"<foo>\"),\n                    factory.Markup(\"@\").Hidden(),\n                    factory.Markup(\"@\"),\n                    factory.Markup(\"@\").Hidden(),\n                    factory.Markup(\"@\"),\n                    new ExpressionBlock(\n                        factory.CodeTransition(),\n                        factory.Code(\"bar\")\n                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    factory.Markup(\"</foo>\").Accepts(lastSpanAcceptedCharacters)));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/Html/HtmlTagsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.Html\n{\n    public class HtmlTagsTest : CsHtmlMarkupParserTestBase\n    {\n        public static IEnumerable<string[]> VoidElementNames\n        {\n            get\n            {\n                yield return new[] { \"area\" };\n                yield return new[] { \"base\" };\n                yield return new[] { \"br\" };\n                yield return new[] { \"col\" };\n                yield return new[] { \"command\" };\n                yield return new[] { \"embed\" };\n                yield return new[] { \"hr\" };\n                yield return new[] { \"img\" };\n                yield return new[] { \"input\" };\n                yield return new[] { \"keygen\" };\n                yield return new[] { \"link\" };\n                yield return new[] { \"meta\" };\n                yield return new[] { \"param\" };\n                yield return new[] { \"source\" };\n                yield return new[] { \"track\" };\n                yield return new[] { \"wbr\" };\n            }\n        }\n\n        [Fact]\n        public void EmptyTagNestsLikeNormalTag()\n        {\n            ParseBlockTest(\"<p></> Bar\",\n                new MarkupBlock(\n                    Factory.Markup(\"<p></> \").Accepts(AcceptedCharacters.None)),\n                new RazorError(String.Format(RazorResources.ParseError_MissingEndTag, \"p\"), 0, 0, 0));\n        }\n\n        [Fact]\n        public void EmptyTag()\n        {\n            ParseBlockTest(\"<></> Bar\",\n                new MarkupBlock(\n                    Factory.Markup(\"<></> \").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void CommentTag()\n        {\n            ParseBlockTest(\"<!--Foo--> Bar\",\n                new MarkupBlock(\n                    Factory.Markup(\"<!--Foo--> \").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void DocTypeTag()\n        {\n            ParseBlockTest(\"<!DOCTYPE html> foo\",\n                new MarkupBlock(\n                    Factory.Markup(\"<!DOCTYPE html> \").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ProcessingInstructionTag()\n        {\n            ParseBlockTest(\"<?xml version=\\\"1.0\\\" ?> foo\",\n                new MarkupBlock(\n                    Factory.Markup(\"<?xml version=\\\"1.0\\\" ?> \").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ElementTags()\n        {\n            ParseBlockTest(\"<p>Foo</p> Bar\",\n                new MarkupBlock(\n                    Factory.Markup(\"<p>Foo</p> \").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void TextTags()\n        {\n            ParseBlockTest(\"<text>Foo</text>}\",\n                new MarkupBlock(\n                    Factory.MarkupTransition(\"<text>\"),\n                    Factory.Markup(\"Foo\"),\n                    Factory.MarkupTransition(\"</text>\")));\n        }\n\n        [Fact]\n        public void CDataTag()\n        {\n            ParseBlockTest(\"<![CDATA[Foo]]> Bar\",\n                new MarkupBlock(\n                    Factory.Markup(\"<![CDATA[Foo]]> \").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ScriptTag()\n        {\n            ParseDocumentTest(\"<script>foo < bar && quantity.toString() !== orderQty.val()</script>\",\n                new MarkupBlock(\n                    Factory.Markup(\"<script>foo < bar && quantity.toString() !== orderQty.val()</script>\")));\n        }\n\n        [Theory]\n        [PropertyData(\"VoidElementNames\")]\n        public void VoidElementFollowedByContent(string tagName)\n        {\n            ParseBlockTest(\"<\" + tagName + \">foo\",\n                new MarkupBlock(\n                    Factory.Markup(\"<\" + tagName + \">\")\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Theory]\n        [PropertyData(\"VoidElementNames\")]\n        public void VoidElementFollowedByOtherTag(string tagName)\n        {\n            ParseBlockTest(\"<\" + tagName + \"><other>foo\",\n                new MarkupBlock(\n                    Factory.Markup(\"<\" + tagName + \">\")\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Theory]\n        [PropertyData(\"VoidElementNames\")]\n        public void VoidElementFollowedByCloseTag(string tagName)\n        {\n            ParseBlockTest(\"<\" + tagName + \"> </\" + tagName + \">foo\",\n                new MarkupBlock(\n                    Factory.Markup(\"<\" + tagName + \"> </\" + tagName + \">\")\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Theory]\n        [PropertyData(\"VoidElementNames\")]\n        public void IncompleteVoidElementEndTag(string tagName)\n        {\n            ParseBlockTest(\"<\" + tagName + \"></\" + tagName,\n                new MarkupBlock(\n                    Factory.Markup(\"<\" + tagName + \"></\" + tagName)\n                           .Accepts(AcceptedCharacters.Any)));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/Html/HtmlToCodeSwitchTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Editor;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.Html\n{\n    public class HtmlToCodeSwitchTest : CsHtmlMarkupParserTestBase\n    {\n        [Fact]\n        public void ParseBlockSwitchesWhenCharacterBeforeSwapIsNonAlphanumeric()\n        {\n            ParseBlockTest(\"<p>foo#@i</p>\",\n                new MarkupBlock(\n                    Factory.Markup(\"<p>foo#\"),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"i\").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    Factory.Markup(\"</p>\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockSwitchesToCodeWhenSwapCharacterEncounteredMidTag()\n        {\n            ParseBlockTest(\"<foo @bar />\",\n                new MarkupBlock(\n                    Factory.Markup(\"<foo \"),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"bar\")\n                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    Factory.Markup(\" />\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockSwitchesToCodeWhenSwapCharacterEncounteredInAttributeValue()\n        {\n            ParseBlockTest(\"<foo bar=\\\"@baz\\\" />\",\n                new MarkupBlock(\n                    Factory.Markup(\"<foo\"),\n                    new MarkupBlock(new AttributeBlockCodeGenerator(\"bar\", new LocationTagged<string>(\" bar=\\\"\", 4, 0, 4), new LocationTagged<string>(\"\\\"\", 14, 0, 14)),\n                        Factory.Markup(\" bar=\\\"\").With(SpanCodeGenerator.Null),\n                        new MarkupBlock(new DynamicAttributeBlockCodeGenerator(new LocationTagged<string>(String.Empty, 10, 0, 10), 10, 0, 10),\n                            new ExpressionBlock(\n                                Factory.CodeTransition(),\n                                Factory.Code(\"baz\")\n                                       .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                       .Accepts(AcceptedCharacters.NonWhiteSpace))),\n                        Factory.Markup(\"\\\"\").With(SpanCodeGenerator.Null)),\n                    Factory.Markup(\" />\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockSwitchesToCodeWhenSwapCharacterEncounteredInTagContent()\n        {\n            ParseBlockTest(\"<foo>@bar<baz>@boz</baz></foo>\",\n                new MarkupBlock(\n                    Factory.Markup(\"<foo>\"),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"bar\")\n                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    Factory.Markup(\"<baz>\"),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"boz\")\n                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    Factory.Markup(\"</baz></foo>\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockParsesCodeWithinSingleLineMarkup()\n        {\n            ParseBlockTest(\"@:<li>Foo @Bar Baz\" + Environment.NewLine\n                         + \"bork\",\n                new MarkupBlock(\n                    Factory.MarkupTransition(),\n                    Factory.MetaMarkup(\":\", HtmlSymbolType.Colon),\n                    Factory.Markup(\"<li>Foo \").With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString)),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"Bar\")\n                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    Factory.Markup(\" Baz\\r\\n\")\n                           .With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString, AcceptedCharacters.None))));\n        }\n\n        [Fact]\n        public void ParseBlockSupportsCodeWithinComment()\n        {\n            ParseBlockTest(\"<foo><!-- @foo --></foo>\",\n                new MarkupBlock(\n                    Factory.Markup(\"<foo><!-- \"),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"foo\")\n                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    Factory.Markup(\" --></foo>\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockSupportsCodeWithinSGMLDeclaration()\n        {\n            ParseBlockTest(\"<foo><!DOCTYPE foo @bar baz></foo>\",\n                new MarkupBlock(\n                    Factory.Markup(\"<foo><!DOCTYPE foo \"),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"bar\")\n                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    Factory.Markup(\" baz></foo>\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockSupportsCodeWithinCDataDeclaration()\n        {\n            ParseBlockTest(\"<foo><![CDATA[ foo @bar baz]]></foo>\",\n                new MarkupBlock(\n                    Factory.Markup(\"<foo><![CDATA[ foo \"),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"bar\")\n                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    Factory.Markup(\" baz]]></foo>\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockSupportsCodeWithinXMLProcessingInstruction()\n        {\n            ParseBlockTest(\"<foo><?xml foo @bar baz?></foo>\",\n                new MarkupBlock(\n                    Factory.Markup(\"<foo><?xml foo \"),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"bar\")\n                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    Factory.Markup(\" baz?></foo>\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockDoesNotSwitchToCodeOnEmailAddressInText()\n        {\n            SingleSpanBlockTest(\"<foo>anurse@microsoft.com</foo>\", BlockType.Markup, SpanKind.Markup, acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockDoesNotSwitchToCodeOnEmailAddressInAttribute()\n        {\n            ParseBlockTest(\"<a href=\\\"mailto:anurse@microsoft.com\\\">Email me</a>\",\n                new MarkupBlock(\n                    Factory.Markup(\"<a\"),\n                    new MarkupBlock(new AttributeBlockCodeGenerator(\"href\", new LocationTagged<string>(\" href=\\\"\", 2, 0, 2), new LocationTagged<string>(\"\\\"\", 36, 0, 36)),\n                        Factory.Markup(\" href=\\\"\").With(SpanCodeGenerator.Null),\n                        Factory.Markup(\"mailto:anurse@microsoft.com\")\n                               .With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(String.Empty, 9, 0, 9), new LocationTagged<string>(\"mailto:anurse@microsoft.com\", 9, 0, 9))),\n                        Factory.Markup(\"\\\"\").With(SpanCodeGenerator.Null)),\n                    Factory.Markup(\">Email me</a>\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockGivesWhitespacePreceedingAtToCodeIfThereIsNoMarkupOnThatLine()\n        {\n            ParseBlockTest(\"   <ul>\" + Environment.NewLine\n                         + \"    @foreach(var p in Products) {\" + Environment.NewLine\n                         + \"        <li>Product: @p.Name</li>\" + Environment.NewLine\n                         + \"    }\" + Environment.NewLine\n                         + \"    </ul>\",\n                new MarkupBlock(\n                    Factory.Markup(\"   <ul>\\r\\n\"),\n                    new StatementBlock(\n                        Factory.Code(\"    \").AsStatement(),\n                        Factory.CodeTransition(),\n                        Factory.Code(\"foreach(var p in Products) {\\r\\n\").AsStatement(),\n                        new MarkupBlock(\n                            Factory.Markup(\"        <li>Product: \"),\n                            new ExpressionBlock(\n                                Factory.CodeTransition(),\n                                Factory.Code(\"p.Name\")\n                                       .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                       .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                            Factory.Markup(\"</li>\\r\\n\").Accepts(AcceptedCharacters.None)),\n                        Factory.Code(\"    }\\r\\n\").AsStatement().Accepts(AcceptedCharacters.None)),\n                    Factory.Markup(\"    </ul>\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseDocumentGivesWhitespacePreceedingAtToCodeIfThereIsNoMarkupOnThatLine()\n        {\n            ParseDocumentTest(\"   <ul>\" + Environment.NewLine\n                            + \"    @foreach(var p in Products) {\" + Environment.NewLine\n                            + \"        <li>Product: @p.Name</li>\" + Environment.NewLine\n                            + \"    }\" + Environment.NewLine\n                            + \"    </ul>\",\n                new MarkupBlock(\n                    Factory.Markup(\"   <ul>\\r\\n\"),\n                    new StatementBlock(\n                        Factory.Code(\"    \").AsStatement(),\n                        Factory.CodeTransition(),\n                        Factory.Code(\"foreach(var p in Products) {\\r\\n\").AsStatement(),\n                        new MarkupBlock(\n                            Factory.Markup(\"        <li>Product: \"),\n                            new ExpressionBlock(\n                                Factory.CodeTransition(),\n                                Factory.Code(\"p.Name\")\n                                       .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                       .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                            Factory.Markup(\"</li>\\r\\n\").Accepts(AcceptedCharacters.None)),\n                        Factory.Code(\"    }\\r\\n\").AsStatement().Accepts(AcceptedCharacters.None)),\n                    Factory.Markup(\"    </ul>\")));\n        }\n\n        [Fact]\n        public void SectionContextGivesWhitespacePreceedingAtToCodeIfThereIsNoMarkupOnThatLine()\n        {\n            ParseDocumentTest(\"@section foo {\" + Environment.NewLine\n                            + \"    <ul>\" + Environment.NewLine\n                            + \"        @foreach(var p in Products) {\" + Environment.NewLine\n                            + \"            <li>Product: @p.Name</li>\" + Environment.NewLine\n                            + \"        }\" + Environment.NewLine\n                            + \"    </ul>\" + Environment.NewLine\n                            + \"}\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section foo {\").AutoCompleteWith(null, atEndOfSpan: true),\n                        new MarkupBlock(\n                            Factory.Markup(\"\\r\\n    <ul>\\r\\n\"),\n                            new StatementBlock(\n                                Factory.Code(\"        \").AsStatement(),\n                                Factory.CodeTransition(),\n                                Factory.Code(\"foreach(var p in Products) {\\r\\n\").AsStatement(),\n                                new MarkupBlock(\n                                    Factory.Markup(\"            <li>Product: \"),\n                                    new ExpressionBlock(\n                                        Factory.CodeTransition(),\n                                        Factory.Code(\"p.Name\")\n                                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                                    Factory.Markup(\"</li>\\r\\n\").Accepts(AcceptedCharacters.None)),\n                                Factory.Code(\"        }\\r\\n\").AsStatement().Accepts(AcceptedCharacters.None)),\n                            Factory.Markup(\"    </ul>\\r\\n\")),\n                        Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void CSharpCodeParserDoesNotAcceptLeadingOrTrailingWhitespaceInDesignMode()\n        {\n            ParseBlockTest(\"   <ul>\" + Environment.NewLine\n                         + \"    @foreach(var p in Products) {\" + Environment.NewLine\n                         + \"        <li>Product: @p.Name</li>\" + Environment.NewLine\n                         + \"    }\" + Environment.NewLine\n                         + \"    </ul>\",\n                new MarkupBlock(\n                    Factory.Markup(\"   <ul>\\r\\n    \"),\n                    new StatementBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"foreach(var p in Products) {\\r\\n        \").AsStatement(),\n                        new MarkupBlock(\n                            Factory.Markup(\"<li>Product: \"),\n                            new ExpressionBlock(\n                                Factory.CodeTransition(),\n                                Factory.Code(\"p.Name\").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)),\n                            Factory.Markup(\"</li>\").Accepts(AcceptedCharacters.None)),\n                        Factory.Code(\"\\r\\n    }\").AsStatement().Accepts(AcceptedCharacters.None)),\n                    Factory.Markup(\"\\r\\n    </ul>\").Accepts(AcceptedCharacters.None)),\n                designTimeParser: true);\n        }\n\n        // Tests for \"@@\" escape sequence:\n        [Fact]\n        public void ParseBlockTreatsTwoAtSignsAsEscapeSequence()\n        {\n            HtmlParserTestUtils.RunSingleAtEscapeTest(ParseBlockTest);\n        }\n\n        [Fact]\n        public void ParseBlockTreatsPairsOfAtSignsAsEscapeSequence()\n        {\n            HtmlParserTestUtils.RunMultiAtEscapeTest(ParseBlockTest);\n        }\n\n        [Fact]\n        public void ParseDocumentTreatsTwoAtSignsAsEscapeSequence()\n        {\n            HtmlParserTestUtils.RunSingleAtEscapeTest(ParseDocumentTest, lastSpanAcceptedCharacters: AcceptedCharacters.Any);\n        }\n\n        [Fact]\n        public void ParseDocumentTreatsPairsOfAtSignsAsEscapeSequence()\n        {\n            HtmlParserTestUtils.RunMultiAtEscapeTest(ParseDocumentTest, lastSpanAcceptedCharacters: AcceptedCharacters.Any);\n        }\n\n        [Fact]\n        public void SectionBodyTreatsTwoAtSignsAsEscapeSequence()\n        {\n            ParseDocumentTest(\"@section Foo { <foo>@@bar</foo> }\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"Foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section Foo {\").AutoCompleteWith(null, atEndOfSpan: true),\n                        new MarkupBlock(\n                            Factory.Markup(\" <foo>\"),\n                            Factory.Markup(\"@\").Hidden(),\n                            Factory.Markup(\"@bar</foo> \")),\n                        Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void SectionBodyTreatsPairsOfAtSignsAsEscapeSequence()\n        {\n            ParseDocumentTest(\"@section Foo { <foo>@@@@@bar</foo> }\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"Foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section Foo {\").AutoCompleteWith(null, atEndOfSpan: true),\n                        new MarkupBlock(\n                            Factory.Markup(\" <foo>\"),\n                            Factory.Markup(\"@\").Hidden(),\n                            Factory.Markup(\"@\"),\n                            Factory.Markup(\"@\").Hidden(),\n                            Factory.Markup(\"@\"),\n                            new ExpressionBlock(\n                                Factory.CodeTransition(),\n                                Factory.Code(\"bar\")\n                                       .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                       .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                            Factory.Markup(\"</foo> \")),\n                        Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/Html/HtmlUrlAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Editor;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.Html\n{\n    public class HtmlUrlAttributeTest : CsHtmlMarkupParserTestBase\n    {\n        [Fact]\n        public void SimpleUrlInAttributeInMarkupBlock()\n        {\n            ParseBlockTest(\"<a href='~/Foo/Bar/Baz' />\",\n                new MarkupBlock(\n                    Factory.Markup(\"<a\"),\n                    new MarkupBlock(new AttributeBlockCodeGenerator(\"href\", new LocationTagged<string>(\" href='\", 2, 0, 2), new LocationTagged<string>(\"'\", 22, 0, 22)),\n                        Factory.Markup(\" href='\").With(SpanCodeGenerator.Null),\n                        Factory.Markup(\"~/Foo/Bar/Baz\")\n                               .WithEditorHints(EditorHints.VirtualPath)\n                               .With(new LiteralAttributeCodeGenerator(\n                                   new LocationTagged<string>(String.Empty, 9, 0, 9),\n                                   new LocationTagged<SpanCodeGenerator>(new ResolveUrlCodeGenerator(), 9, 0, 9))),\n                        Factory.Markup(\"'\").With(SpanCodeGenerator.Null)),\n                    Factory.Markup(\" />\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void SimpleUrlInAttributeInMarkupDocument()\n        {\n            ParseDocumentTest(\"<a href='~/Foo/Bar/Baz' />\",\n                new MarkupBlock(\n                    Factory.Markup(\"<a\"),\n                    new MarkupBlock(new AttributeBlockCodeGenerator(\"href\", new LocationTagged<string>(\" href='\", 2, 0, 2), new LocationTagged<string>(\"'\", 22, 0, 22)),\n                        Factory.Markup(\" href='\").With(SpanCodeGenerator.Null),\n                        Factory.Markup(\"~/Foo/Bar/Baz\")\n                               .WithEditorHints(EditorHints.VirtualPath)\n                               .With(new LiteralAttributeCodeGenerator(\n                                   new LocationTagged<string>(String.Empty, 9, 0, 9),\n                                   new LocationTagged<SpanCodeGenerator>(new ResolveUrlCodeGenerator(), 9, 0, 9))),\n                        Factory.Markup(\"'\").With(SpanCodeGenerator.Null)),\n                    Factory.Markup(\" />\")));\n        }\n\n        [Fact]\n        public void SimpleUrlInAttributeInMarkupSection()\n        {\n            ParseDocumentTest(\"@section Foo { <a href='~/Foo/Bar/Baz' /> }\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"Foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section Foo {\")\n                               .AutoCompleteWith(null, atEndOfSpan: true)\n                               .Accepts(AcceptedCharacters.Any),\n                        new MarkupBlock(\n                            Factory.Markup(\" <a\"),\n                            new MarkupBlock(new AttributeBlockCodeGenerator(\"href\", new LocationTagged<string>(\" href='\", 17, 0, 17), new LocationTagged<string>(\"'\", 37, 0, 37)),\n                                Factory.Markup(\" href='\").With(SpanCodeGenerator.Null),\n                                Factory.Markup(\"~/Foo/Bar/Baz\")\n                                       .WithEditorHints(EditorHints.VirtualPath)\n                                       .With(new LiteralAttributeCodeGenerator(\n                                           new LocationTagged<string>(String.Empty, 24, 0, 24),\n                                           new LocationTagged<SpanCodeGenerator>(new ResolveUrlCodeGenerator(), 24, 0, 24))),\n                                Factory.Markup(\"'\").With(SpanCodeGenerator.Null)),\n                            Factory.Markup(\" /> \")),\n                        Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void UrlWithExpressionsInAttributeInMarkupBlock()\n        {\n            ParseBlockTest(\"<a href='~/Foo/@id/Baz' />\",\n                new MarkupBlock(\n                    Factory.Markup(\"<a\"),\n                        new MarkupBlock(new AttributeBlockCodeGenerator(\"href\", new LocationTagged<string>(\" href='\", 2, 0, 2), new LocationTagged<string>(\"'\", 22, 0, 22)),\n                            Factory.Markup(\" href='\").With(SpanCodeGenerator.Null),\n                            Factory.Markup(\"~/Foo/\")\n                                    .WithEditorHints(EditorHints.VirtualPath)\n                                    .With(new LiteralAttributeCodeGenerator(\n                                        new LocationTagged<string>(String.Empty, 9, 0, 9),\n                                        new LocationTagged<SpanCodeGenerator>(new ResolveUrlCodeGenerator(), 9, 0, 9))),\n                            new MarkupBlock(new DynamicAttributeBlockCodeGenerator(new LocationTagged<string>(String.Empty, 15, 0, 15), 15, 0, 15),\n                                new ExpressionBlock(\n                                    Factory.CodeTransition().Accepts(AcceptedCharacters.None),\n                                    Factory.Code(\"id\")\n                                           .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                           .Accepts(AcceptedCharacters.NonWhiteSpace))),\n                            Factory.Markup(\"/Baz\")\n                                   .With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(String.Empty, 18, 0, 18), new LocationTagged<string>(\"/Baz\", 18, 0, 18))),\n                            Factory.Markup(\"'\").With(SpanCodeGenerator.Null)),\n                        Factory.Markup(\" />\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void UrlWithExpressionsInAttributeInMarkupDocument()\n        {\n            ParseDocumentTest(\"<a href='~/Foo/@id/Baz' />\",\n                new MarkupBlock(\n                    Factory.Markup(\"<a\"),\n                    new MarkupBlock(new AttributeBlockCodeGenerator(\"href\", new LocationTagged<string>(\" href='\", 2, 0, 2), new LocationTagged<string>(\"'\", 22, 0, 22)),\n                        Factory.Markup(\" href='\").With(SpanCodeGenerator.Null),\n                        Factory.Markup(\"~/Foo/\")\n                               .WithEditorHints(EditorHints.VirtualPath)\n                               .With(new LiteralAttributeCodeGenerator(\n                                   new LocationTagged<string>(String.Empty, 9, 0, 9),\n                                   new LocationTagged<SpanCodeGenerator>(new ResolveUrlCodeGenerator(), 9, 0, 9))),\n                        new MarkupBlock(new DynamicAttributeBlockCodeGenerator(new LocationTagged<string>(String.Empty, 15, 0, 15), 15, 0, 15),\n                            new ExpressionBlock(\n                                Factory.CodeTransition().Accepts(AcceptedCharacters.None),\n                                Factory.Code(\"id\")\n                                       .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                       .Accepts(AcceptedCharacters.NonWhiteSpace))),\n                        Factory.Markup(\"/Baz\")\n                               .With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(String.Empty, 18, 0, 18), new LocationTagged<string>(\"/Baz\", 18, 0, 18))),\n                        Factory.Markup(\"'\").With(SpanCodeGenerator.Null)),\n                    Factory.Markup(\" />\")));\n        }\n\n        [Fact]\n        public void UrlWithExpressionsInAttributeInMarkupSection()\n        {\n            ParseDocumentTest(\"@section Foo { <a href='~/Foo/@id/Baz' /> }\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"Foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section Foo {\")\n                               .AutoCompleteWith(null, atEndOfSpan: true),\n                        new MarkupBlock(\n                            Factory.Markup(\" <a\"),\n                            new MarkupBlock(new AttributeBlockCodeGenerator(\"href\", new LocationTagged<string>(\" href='\", 17, 0, 17), new LocationTagged<string>(\"'\", 37, 0, 37)),\n                                Factory.Markup(\" href='\").With(SpanCodeGenerator.Null),\n                                Factory.Markup(\"~/Foo/\")\n                                       .WithEditorHints(EditorHints.VirtualPath)\n                                       .With(new LiteralAttributeCodeGenerator(\n                                           new LocationTagged<string>(String.Empty, 24, 0, 24),\n                                           new LocationTagged<SpanCodeGenerator>(new ResolveUrlCodeGenerator(), 24, 0, 24))),\n                                new MarkupBlock(new DynamicAttributeBlockCodeGenerator(new LocationTagged<string>(String.Empty, 30, 0, 30), 30, 0, 30),\n                                    new ExpressionBlock(\n                                        Factory.CodeTransition().Accepts(AcceptedCharacters.None),\n                                        Factory.Code(\"id\")\n                                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                               .Accepts(AcceptedCharacters.NonWhiteSpace))),\n                                Factory.Markup(\"/Baz\")\n                                       .With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(String.Empty, 33, 0, 33), new LocationTagged<string>(\"/Baz\", 33, 0, 33))),\n                                Factory.Markup(\"'\").With(SpanCodeGenerator.Null)),\n                            Factory.Markup(\" /> \")),\n                        Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void UrlWithComplexCharactersInAttributeInMarkupBlock()\n        {\n            ParseBlockTest(\"<a href='~/Foo+Bar:Baz(Biz),Boz' />\",\n                new MarkupBlock(\n                    Factory.Markup(\"<a\"),\n                    new MarkupBlock(new AttributeBlockCodeGenerator(\"href\", new LocationTagged<string>(\" href='\", 2, 0, 2), new LocationTagged<string>(\"'\", 31, 0, 31)),\n                        Factory.Markup(\" href='\").With(SpanCodeGenerator.Null),\n                        Factory.Markup(\"~/Foo+Bar:Baz(Biz),Boz\")\n                               .WithEditorHints(EditorHints.VirtualPath)\n                               .With(new LiteralAttributeCodeGenerator(\n                                   new LocationTagged<string>(String.Empty, 9, 0, 9),\n                                   new LocationTagged<SpanCodeGenerator>(new ResolveUrlCodeGenerator(), 9, 0, 9))),\n                        Factory.Markup(\"'\").With(SpanCodeGenerator.Null)),\n                    Factory.Markup(\" />\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void UrlWithComplexCharactersInAttributeInMarkupDocument()\n        {\n            ParseDocumentTest(\"<a href='~/Foo+Bar:Baz(Biz),Boz' />\",\n                new MarkupBlock(\n                    Factory.Markup(\"<a\"),\n                    new MarkupBlock(new AttributeBlockCodeGenerator(\"href\", new LocationTagged<string>(\" href='\", 2, 0, 2), new LocationTagged<string>(\"'\", 31, 0, 31)),\n                        Factory.Markup(\" href='\").With(SpanCodeGenerator.Null),\n                        Factory.Markup(\"~/Foo+Bar:Baz(Biz),Boz\")\n                               .WithEditorHints(EditorHints.VirtualPath)\n                               .With(new LiteralAttributeCodeGenerator(\n                                   new LocationTagged<string>(String.Empty, 9, 0, 9),\n                                   new LocationTagged<SpanCodeGenerator>(new ResolveUrlCodeGenerator(), 9, 0, 9))),\n                        Factory.Markup(\"'\").With(SpanCodeGenerator.Null)),\n                    Factory.Markup(\" />\")));\n        }\n\n        [Fact]\n        public void UrlInUnquotedAttributeValueInMarkupBlock()\n        {\n            ParseBlockTest(\"<a href=~/Foo+Bar:Baz(Biz),Boz/@id/Boz />\",\n                new MarkupBlock(\n                    Factory.Markup(\"<a\"),\n                    new MarkupBlock(new AttributeBlockCodeGenerator(\"href\", new LocationTagged<string>(\" href=\", 2, 0, 2), new LocationTagged<string>(String.Empty, 38, 0, 38)),\n                        Factory.Markup(\" href=\").With(SpanCodeGenerator.Null),\n                        Factory.Markup(\"~/Foo+Bar:Baz(Biz),Boz/\")\n                               .WithEditorHints(EditorHints.VirtualPath)\n                               .With(new LiteralAttributeCodeGenerator(\n                                   new LocationTagged<string>(String.Empty, 8, 0, 8),\n                                   new LocationTagged<SpanCodeGenerator>(new ResolveUrlCodeGenerator(), 8, 0, 8))),\n                        new MarkupBlock(new DynamicAttributeBlockCodeGenerator(new LocationTagged<string>(String.Empty, 31, 0, 31), 31, 0, 31),\n                            new ExpressionBlock(\n                                Factory.CodeTransition()\n                                       .Accepts(AcceptedCharacters.None),\n                                Factory.Code(\"id\")\n                                       .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                            .Accepts(AcceptedCharacters.NonWhiteSpace))),\n                        Factory.Markup(\"/Boz\").With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(String.Empty, 34, 0, 34), new LocationTagged<string>(\"/Boz\", 34, 0, 34)))),\n                    Factory.Markup(\" />\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void UrlInUnquotedAttributeValueInMarkupDocument()\n        {\n            ParseDocumentTest(\"<a href=~/Foo+Bar:Baz(Biz),Boz/@id/Boz />\",\n                new MarkupBlock(\n                    Factory.Markup(\"<a\"),\n                    new MarkupBlock(new AttributeBlockCodeGenerator(\"href\", new LocationTagged<string>(\" href=\", 2, 0, 2), new LocationTagged<string>(String.Empty, 38, 0, 38)),\n                        Factory.Markup(\" href=\").With(SpanCodeGenerator.Null),\n                        Factory.Markup(\"~/Foo+Bar:Baz(Biz),Boz/\")\n                               .WithEditorHints(EditorHints.VirtualPath)\n                               .With(new LiteralAttributeCodeGenerator(\n                                   new LocationTagged<string>(String.Empty, 8, 0, 8),\n                                   new LocationTagged<SpanCodeGenerator>(new ResolveUrlCodeGenerator(), 8, 0, 8))),\n                        new MarkupBlock(new DynamicAttributeBlockCodeGenerator(new LocationTagged<string>(String.Empty, 31, 0, 31), 31, 0, 31),\n                            new ExpressionBlock(\n                                Factory.CodeTransition()\n                                       .Accepts(AcceptedCharacters.None),\n                                Factory.Code(\"id\")\n                                       .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                            .Accepts(AcceptedCharacters.NonWhiteSpace))),\n                        Factory.Markup(\"/Boz\").With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(String.Empty, 34, 0, 34), new LocationTagged<string>(\"/Boz\", 34, 0, 34)))),\n                    Factory.Markup(\" />\")));\n        }\n\n        [Fact]\n        public void UrlInUnquotedAttributeValueInMarkupSection()\n        {\n            ParseDocumentTest(\"@section Foo { <a href=~/Foo+Bar:Baz(Biz),Boz/@id/Boz /> }\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"Foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"section Foo {\")\n                               .AutoCompleteWith(null, atEndOfSpan: true),\n                        new MarkupBlock(\n                            Factory.Markup(\" <a\"),\n                            new MarkupBlock(new AttributeBlockCodeGenerator(\"href\", new LocationTagged<string>(\" href=\", 17, 0, 17), new LocationTagged<string>(String.Empty, 53, 0, 53)),\n                                Factory.Markup(\" href=\").With(SpanCodeGenerator.Null),\n                                Factory.Markup(\"~/Foo+Bar:Baz(Biz),Boz/\")\n                                        .WithEditorHints(EditorHints.VirtualPath)\n                                        .With(new LiteralAttributeCodeGenerator(\n                                            new LocationTagged<string>(String.Empty, 23, 0, 23),\n                                            new LocationTagged<SpanCodeGenerator>(new ResolveUrlCodeGenerator(), 23, 0, 23))),\n                                new MarkupBlock(new DynamicAttributeBlockCodeGenerator(new LocationTagged<string>(String.Empty, 46, 0, 46), 46, 0, 46),\n                                    new ExpressionBlock(\n                                        Factory.CodeTransition()\n                                               .Accepts(AcceptedCharacters.None),\n                                        Factory.Code(\"id\")\n                                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                    .Accepts(AcceptedCharacters.NonWhiteSpace))),\n                                Factory.Markup(\"/Boz\").With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(String.Empty, 49, 0, 49), new LocationTagged<string>(\"/Boz\", 49, 0, 49)))),\n                            Factory.Markup(\" /> \")),\n                        Factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/ParserContextTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Razor.Test.Parser\n{\n    public class ParserContextTest\n    {\n        [Fact]\n        public void ConstructorRequiresNonNullSource()\n        {\n            var codeParser = new CSharpCodeParser();\n            Assert.ThrowsArgumentNull(() => new ParserContext(null, codeParser, new HtmlMarkupParser(), codeParser), \"source\");\n        }\n\n        [Fact]\n        public void ConstructorRequiresNonNullCodeParser()\n        {\n            var codeParser = new CSharpCodeParser();\n            Assert.ThrowsArgumentNull(() => new ParserContext(new SeekableTextReader(TextReader.Null), null, new HtmlMarkupParser(), codeParser), \"codeParser\");\n        }\n\n        [Fact]\n        public void ConstructorRequiresNonNullMarkupParser()\n        {\n            var codeParser = new CSharpCodeParser();\n            Assert.ThrowsArgumentNull(() => new ParserContext(new SeekableTextReader(TextReader.Null), codeParser, null, codeParser), \"markupParser\");\n        }\n\n        [Fact]\n        public void ConstructorRequiresNonNullActiveParser()\n        {\n            Assert.ThrowsArgumentNull(() => new ParserContext(new SeekableTextReader(TextReader.Null), new CSharpCodeParser(), new HtmlMarkupParser(), null), \"activeParser\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfActiveParserIsNotCodeOrMarkupParser()\n        {\n            Assert.ThrowsArgument(() => new ParserContext(new SeekableTextReader(TextReader.Null), new CSharpCodeParser(), new HtmlMarkupParser(), new CSharpCodeParser()),\n                                                    \"activeParser\",\n                                                    RazorResources.ActiveParser_Must_Be_Code_Or_Markup_Parser);\n        }\n\n        [Fact]\n        public void ConstructorAcceptsActiveParserIfIsSameAsEitherCodeOrMarkupParser()\n        {\n            var codeParser = new CSharpCodeParser();\n            var markupParser = new HtmlMarkupParser();\n            new ParserContext(new SeekableTextReader(TextReader.Null), codeParser, markupParser, codeParser);\n            new ParserContext(new SeekableTextReader(TextReader.Null), codeParser, markupParser, markupParser);\n        }\n\n        [Fact]\n        public void ConstructorInitializesProperties()\n        {\n            // Arrange\n            SeekableTextReader expectedBuffer = new SeekableTextReader(TextReader.Null);\n            CSharpCodeParser expectedCodeParser = new CSharpCodeParser();\n            HtmlMarkupParser expectedMarkupParser = new HtmlMarkupParser();\n\n            // Act\n            ParserContext context = new ParserContext(expectedBuffer, expectedCodeParser, expectedMarkupParser, expectedCodeParser);\n\n            // Assert\n            Assert.NotNull(context.Source);\n            Assert.Same(expectedCodeParser, context.CodeParser);\n            Assert.Same(expectedMarkupParser, context.MarkupParser);\n            Assert.Same(expectedCodeParser, context.ActiveParser);\n        }\n\n        [Fact]\n        public void CurrentCharacterReturnsCurrentCharacterInTextBuffer()\n        {\n            // Arrange\n            ParserContext context = SetupTestContext(\"bar\", b => b.Read());\n\n            // Act\n            char actual = context.CurrentCharacter;\n\n            // Assert\n            Assert.Equal('a', actual);\n        }\n\n        [Fact]\n        public void CurrentCharacterReturnsNulCharacterIfTextBufferAtEOF()\n        {\n            // Arrange\n            ParserContext context = SetupTestContext(\"bar\", b => b.ReadToEnd());\n\n            // Act\n            char actual = context.CurrentCharacter;\n\n            // Assert\n            Assert.Equal('\\0', actual);\n        }\n\n        [Fact]\n        public void EndOfFileReturnsFalseIfTextBufferNotAtEOF()\n        {\n            // Arrange\n            ParserContext context = SetupTestContext(\"bar\");\n\n            // Act/Assert\n            Assert.False(context.EndOfFile);\n        }\n\n        [Fact]\n        public void EndOfFileReturnsTrueIfTextBufferAtEOF()\n        {\n            // Arrange\n            ParserContext context = SetupTestContext(\"bar\", b => b.ReadToEnd());\n\n            // Act/Assert\n            Assert.True(context.EndOfFile);\n        }\n\n        [Fact]\n        public void StartBlockCreatesNewBlock()\n        {\n            // Arrange\n            ParserContext context = SetupTestContext(\"phoo\");\n\n            // Act\n            context.StartBlock(BlockType.Expression);\n\n            // Assert\n            BlockBuilder blockBuilder = Assert.Single(context.BlockStack);\n            Assert.Equal(BlockType.Expression, blockBuilder.Type);\n        }\n\n        [Fact]\n        public void EndBlockAddsCurrentBlockToParentBlock()\n        {\n            // Arrange\n            Mock<ParserVisitor> mockListener = new Mock<ParserVisitor>();\n            ParserContext context = SetupTestContext(\"phoo\");\n\n            // Act\n            context.StartBlock(BlockType.Expression);\n            context.StartBlock(BlockType.Statement);\n            context.EndBlock();\n\n            // Assert\n            BlockBuilder blockBuilder = Assert.Single(context.BlockStack);\n            Assert.Equal(BlockType.Expression, blockBuilder.Type);\n            SyntaxTreeNode node = Assert.Single(blockBuilder.Children);\n            Assert.Equal(BlockType.Statement, Assert.IsType<Block>(node).Type);\n        }\n\n        [Fact]\n        public void AddSpanAddsSpanToCurrentBlockBuilder()\n        {\n            // Arrange\n            var factory = SpanFactory.CreateCsHtml();\n            Mock<ParserVisitor> mockListener = new Mock<ParserVisitor>();\n            ParserContext context = SetupTestContext(\"phoo\");\n\n            SpanBuilder builder = new SpanBuilder()\n            {\n                Kind = SpanKind.Code\n            };\n            builder.Accept(new CSharpSymbol(1, 0, 1, \"foo\", CSharpSymbolType.Identifier));\n            Span added = builder.Build();\n\n            using (context.StartBlock(BlockType.Functions))\n            {\n                context.AddSpan(added);\n            }\n\n            BlockBuilder expected = new BlockBuilder()\n            {\n                Type = BlockType.Functions,\n            };\n            expected.Children.Add(added);\n\n            // Assert\n            ParserTestBase.EvaluateResults(context.CompleteParse(), expected.Build());\n        }\n\n        [Fact]\n        public void SwitchActiveParserSetsMarkupParserAsActiveIfCodeParserCurrentlyActive()\n        {\n            // Arrange\n            var codeParser = new CSharpCodeParser();\n            var markupParser = new HtmlMarkupParser();\n            ParserContext context = SetupTestContext(\"barbazbiz\", b => b.Read(), codeParser, markupParser, codeParser);\n            Assert.Same(codeParser, context.ActiveParser);\n\n            // Act\n            context.SwitchActiveParser();\n\n            // Assert\n            Assert.Same(markupParser, context.ActiveParser);\n        }\n\n        [Fact]\n        public void SwitchActiveParserSetsCodeParserAsActiveIfMarkupParserCurrentlyActive()\n        {\n            // Arrange\n            var codeParser = new CSharpCodeParser();\n            var markupParser = new HtmlMarkupParser();\n            ParserContext context = SetupTestContext(\"barbazbiz\", b => b.Read(), codeParser, markupParser, markupParser);\n            Assert.Same(markupParser, context.ActiveParser);\n\n            // Act\n            context.SwitchActiveParser();\n\n            // Assert\n            Assert.Same(codeParser, context.ActiveParser);\n        }\n\n        private ParserContext SetupTestContext(string document)\n        {\n            var codeParser = new CSharpCodeParser();\n            var markupParser = new HtmlMarkupParser();\n            return SetupTestContext(document, b => { }, codeParser, markupParser, codeParser);\n        }\n\n        private ParserContext SetupTestContext(string document, Action<TextReader> positioningAction)\n        {\n            var codeParser = new CSharpCodeParser();\n            var markupParser = new HtmlMarkupParser();\n            return SetupTestContext(document, positioningAction, codeParser, markupParser, codeParser);\n        }\n\n        private ParserContext SetupTestContext(string document, Action<TextReader> positioningAction, ParserBase codeParser, ParserBase markupParser, ParserBase activeParser)\n        {\n            ParserContext context = new ParserContext(new SeekableTextReader(new StringReader(document)), codeParser, markupParser, activeParser);\n            positioningAction(context.Source);\n            return context;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/ParserVisitorExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Razor.Test.Parser\n{\n    public class ParserVisitorExtensionsTest\n    {\n        [Fact]\n        public void VisitThrowsOnNullVisitor()\n        {\n            ParserVisitor target = null;\n            ParserResults results = new ParserResults(new BlockBuilder() { Type = BlockType.Comment }.Build(), new List<RazorError>());\n\n            Assert.ThrowsArgumentNull(() => target.Visit(results), \"self\");\n        }\n\n        [Fact]\n        public void VisitThrowsOnNullResults()\n        {\n            ParserVisitor target = new Mock<ParserVisitor>().Object;\n            Assert.ThrowsArgumentNull(() => target.Visit(null), \"result\");\n        }\n\n        [Fact]\n        public void VisitSendsDocumentToVisitor()\n        {\n            // Arrange\n            Mock<ParserVisitor> targetMock = new Mock<ParserVisitor>();\n            Block root = new BlockBuilder() { Type = BlockType.Comment }.Build();\n            ParserResults results = new ParserResults(root, new List<RazorError>());\n\n            // Act\n            targetMock.Object.Visit(results);\n\n            // Assert\n            targetMock.Verify(v => v.VisitBlock(root));\n        }\n\n        [Fact]\n        public void VisitSendsErrorsToVisitor()\n        {\n            // Arrange\n            Mock<ParserVisitor> targetMock = new Mock<ParserVisitor>();\n            Block root = new BlockBuilder() { Type = BlockType.Comment }.Build();\n            List<RazorError> errors = new List<RazorError>() {\n                new RazorError(\"Foo\", 1, 0, 1),\n                new RazorError(\"Bar\", 2, 0, 2)\n            };\n            ParserResults results = new ParserResults(root, errors);\n\n            // Act\n            targetMock.Object.Visit(results);\n\n            // Assert\n            targetMock.Verify(v => v.VisitError(errors[0]));\n            targetMock.Verify(v => v.VisitError(errors[1]));\n        }\n\n        [Fact]\n        public void VisitCallsOnCompleteWhenAllNodesHaveBeenVisited()\n        {\n            // Arrange\n            Mock<ParserVisitor> targetMock = new Mock<ParserVisitor>();\n            Block root = new BlockBuilder() { Type = BlockType.Comment }.Build();\n            List<RazorError> errors = new List<RazorError>() {\n                new RazorError(\"Foo\", 1, 0, 1),\n                new RazorError(\"Bar\", 2, 0, 2)\n            };\n            ParserResults results = new ParserResults(root, errors);\n\n            // Act\n            targetMock.Object.Visit(results);\n\n            // Assert\n            targetMock.Verify(v => v.OnComplete());\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/PartialParsing/CSharpPartialParsingTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.PartialParsing\n{\n    public class CSharpPartialParsingTest : PartialParsingTestBase<CSharpRazorCodeLanguage>\n    {\n        [Fact]\n        public void ImplicitExpressionAcceptsInnerInsertionsInStatementBlock()\n        {\n            // Arrange\n            SpanFactory factory = SpanFactory.CreateCsHtml();\n            StringTextBuffer changed = new StringTextBuffer(\"@{\" + Environment.NewLine\n                                                          + \"    @DateTime..Now\" + Environment.NewLine\n                                                          + \"}\");\n            StringTextBuffer old = new StringTextBuffer(\"@{\" + Environment.NewLine\n                                                      + \"    @DateTime.Now\" + Environment.NewLine\n                                                      + \"}\");\n\n            // Act and Assert\n            RunPartialParseTest(new TextChange(17, 0, old, 1, changed),\n                new MarkupBlock(\n                    factory.EmptyHtml(),\n                    new StatementBlock(\n                        factory.CodeTransition(),\n                        factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                        factory.Code(\"\\r\\n    \").AsStatement(),\n                        new ExpressionBlock(\n                            factory.CodeTransition(),\n                            factory.Code(\"DateTime..Now\")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                        factory.Code(\"\\r\\n\").AsStatement(),\n                        factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                    factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void ImplicitExpressionAcceptsInnerInsertions()\n        {\n            // Arrange\n            SpanFactory factory = SpanFactory.CreateCsHtml();\n            StringTextBuffer changed = new StringTextBuffer(\"foo @DateTime..Now baz\");\n            StringTextBuffer old = new StringTextBuffer(\"foo @DateTime.Now baz\");\n\n            // Act and Assert\n            RunPartialParseTest(new TextChange(13, 0, old, 1, changed),\n                new MarkupBlock(\n                    factory.Markup(\"foo \"),\n                    new ExpressionBlock(\n                        factory.CodeTransition(),\n                        factory.Code(\"DateTime..Now\").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    factory.Markup(\" baz\")), additionalFlags: PartialParseResult.Provisional);\n        }\n\n        [Fact]\n        public void ImplicitExpressionAcceptsWholeIdentifierReplacement()\n        {\n            // Arrange\n            SpanFactory factory = SpanFactory.CreateCsHtml();\n            StringTextBuffer old = new StringTextBuffer(\"foo @date baz\");\n            StringTextBuffer changed = new StringTextBuffer(\"foo @DateTime baz\");\n\n            // Act and Assert\n            RunPartialParseTest(new TextChange(5, 4, old, 8, changed),\n                new MarkupBlock(\n                    factory.Markup(\"foo \"),\n                    new ExpressionBlock(\n                        factory.CodeTransition(),\n                        factory.Code(\"DateTime\").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    factory.Markup(\" baz\")));\n        }\n\n        [Fact]\n        public void ImplicitExpressionRejectsWholeIdentifierReplacementToKeyword()\n        {\n            // Arrange\n            RazorEngineHost host = CreateHost();\n            RazorEditorParser parser = new RazorEditorParser(host, @\"C:\\This\\Is\\A\\Test\\Path\");\n\n            using (TestParserManager manager = new TestParserManager(parser))\n            {\n                StringTextBuffer old = new StringTextBuffer(\"foo @date baz\");\n                StringTextBuffer changed = new StringTextBuffer(\"foo @if baz\");\n                TextChange textChange = new TextChange(5, 4, old, 2, changed);\n                manager.InitializeWithDocument(old);\n\n                // Act\n                PartialParseResult result = manager.CheckForStructureChangesAndWait(textChange);\n\n                // Assert\n                Assert.Equal(PartialParseResult.Rejected, result);\n                Assert.Equal(2, manager.ParseCount);\n            }\n        }\n\n        [Fact]\n        public void ImplicitExpressionRejectsWholeIdentifierReplacementToDirective()\n        {\n            // Arrange\n            RazorEngineHost host = CreateHost();\n            RazorEditorParser parser = new RazorEditorParser(host, @\"C:\\This\\Is\\A\\Test\\Path\");\n\n            using (var manager = new TestParserManager(parser))\n            {\n                StringTextBuffer old = new StringTextBuffer(\"foo @date baz\");\n                StringTextBuffer changed = new StringTextBuffer(\"foo @inherits baz\");\n                TextChange textChange = new TextChange(5, 4, old, 8, changed);\n                manager.InitializeWithDocument(old);\n\n                // Act\n                PartialParseResult result = manager.CheckForStructureChangesAndWait(textChange);\n\n                // Assert\n                Assert.Equal(PartialParseResult.Rejected | PartialParseResult.SpanContextChanged, result);\n                Assert.Equal(2, manager.ParseCount);\n            }\n        }\n\n        [Fact]\n        public void ImplicitExpressionAcceptsPrefixIdentifierReplacements_SingleSymbol()\n        {\n            // Arrange\n            SpanFactory factory = SpanFactory.CreateCsHtml();\n            StringTextBuffer old = new StringTextBuffer(\"foo @dTime baz\");\n            StringTextBuffer changed = new StringTextBuffer(\"foo @DateTime baz\");\n\n            // Act and Assert\n            RunPartialParseTest(new TextChange(5, 1, old, 4, changed),\n                new MarkupBlock(\n                    factory.Markup(\"foo \"),\n                    new ExpressionBlock(\n                        factory.CodeTransition(),\n                        factory.Code(\"DateTime\").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    factory.Markup(\" baz\")));\n        }\n\n        [Fact]\n        public void ImplicitExpressionAcceptsPrefixIdentifierReplacements_MultipleSymbols()\n        {\n            // Arrange\n            SpanFactory factory = SpanFactory.CreateCsHtml();\n            StringTextBuffer old = new StringTextBuffer(\"foo @dTime.Now baz\");\n            StringTextBuffer changed = new StringTextBuffer(\"foo @DateTime.Now baz\");\n\n            // Act and Assert\n            RunPartialParseTest(new TextChange(5, 1, old, 4, changed),\n                new MarkupBlock(\n                    factory.Markup(\"foo \"),\n                    new ExpressionBlock(\n                        factory.CodeTransition(),\n                        factory.Code(\"DateTime.Now\").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    factory.Markup(\" baz\")));\n        }\n\n        [Fact]\n        public void ImplicitExpressionAcceptsSuffixIdentifierReplacements_SingleSymbol()\n        {\n            // Arrange\n            SpanFactory factory = SpanFactory.CreateCsHtml();\n            StringTextBuffer old = new StringTextBuffer(\"foo @Datet baz\");\n            StringTextBuffer changed = new StringTextBuffer(\"foo @DateTime baz\");\n\n            // Act and Assert\n            RunPartialParseTest(new TextChange(9, 1, old, 4, changed),\n                new MarkupBlock(\n                    factory.Markup(\"foo \"),\n                    new ExpressionBlock(\n                        factory.CodeTransition(),\n                        factory.Code(\"DateTime\").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    factory.Markup(\" baz\")));\n        }\n\n        [Fact]\n        public void ImplicitExpressionAcceptsSuffixIdentifierReplacements_MultipleSymbols()\n        {\n            // Arrange\n            SpanFactory factory = SpanFactory.CreateCsHtml();\n            StringTextBuffer old = new StringTextBuffer(\"foo @DateTime.n baz\");\n            StringTextBuffer changed = new StringTextBuffer(\"foo @DateTime.Now baz\");\n\n            // Act and Assert\n            RunPartialParseTest(new TextChange(14, 1, old, 3, changed),\n                new MarkupBlock(\n                    factory.Markup(\"foo \"),\n                    new ExpressionBlock(\n                        factory.CodeTransition(),\n                        factory.Code(\"DateTime.Now\").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    factory.Markup(\" baz\")));\n        }\n\n        [Fact]\n        public void ImplicitExpressionAcceptsSurroundedIdentifierReplacements()\n        {\n            // Arrange\n            SpanFactory factory = SpanFactory.CreateCsHtml();\n            StringTextBuffer old = new StringTextBuffer(\"foo @DateTime.n.ToString() baz\");\n            StringTextBuffer changed = new StringTextBuffer(\"foo @DateTime.Now.ToString() baz\");\n\n            // Act and Assert\n            RunPartialParseTest(new TextChange(14, 1, old, 3, changed),\n                new MarkupBlock(\n                    factory.Markup(\"foo \"),\n                    new ExpressionBlock(\n                        factory.CodeTransition(),\n                        factory.Code(\"DateTime.Now.ToString()\").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    factory.Markup(\" baz\")));\n        }\n\n        [Fact]\n        public void ImplicitExpressionAcceptsDotlessCommitInsertionsInStatementBlockAfterIdentifiers()\n        {\n            SpanFactory factory = SpanFactory.CreateCsHtml();\n            StringTextBuffer changed = new StringTextBuffer(\"@{\" + Environment.NewLine\n                                                          + \"    @DateTime.\" + Environment.NewLine\n                                                          + \"}\");\n            StringTextBuffer old = new StringTextBuffer(\"@{\" + Environment.NewLine\n                                                      + \"    @DateTime\" + Environment.NewLine\n                                                      + \"}\");\n\n            var textChange = new TextChange(17, 0, old, 1, changed);\n            using (TestParserManager manager = CreateParserManager())\n            {\n                Action<TextChange, PartialParseResult, string> applyAndVerifyPartialChange = (changeToApply, expectedResult, expectedCode) =>\n                {\n                    PartialParseResult result = manager.CheckForStructureChangesAndWait(textChange);\n\n                    // Assert\n                    Assert.Equal(expectedResult, result);\n                    Assert.Equal(1, manager.ParseCount);\n                    ParserTestBase.EvaluateParseTree(manager.Parser.CurrentParseTree, new MarkupBlock(\n                        factory.EmptyHtml(),\n                        new StatementBlock(\n                            factory.CodeTransition(),\n                            factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                            factory.Code(\"\\r\\n    \").AsStatement(),\n                            new ExpressionBlock(\n                                factory.CodeTransition(),\n                                factory.Code(expectedCode)\n                                       .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true)\n                                       .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                            factory.Code(\"\\r\\n\").AsStatement(),\n                            factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                        factory.EmptyHtml()));\n                };\n\n                manager.InitializeWithDocument(textChange.OldBuffer);\n\n                // This is the process of a dotless commit when doing \".\" insertions to commit intellisense changes.\n                applyAndVerifyPartialChange(textChange, PartialParseResult.Accepted, \"DateTime.\");\n\n                old = changed;\n                changed = new StringTextBuffer(\"@{\" + Environment.NewLine\n                                            + \"    @DateTime..\" + Environment.NewLine\n                                            + \"}\");\n                textChange = new TextChange(18, 0, old, 1, changed);\n\n                applyAndVerifyPartialChange(textChange, PartialParseResult.Accepted, \"DateTime..\");\n\n                old = changed;\n                changed = new StringTextBuffer(\"@{\" + Environment.NewLine\n                                            + \"    @DateTime.Now.\" + Environment.NewLine\n                                            + \"}\");\n                textChange = new TextChange(18, 0, old, 3, changed);\n\n                applyAndVerifyPartialChange(textChange, PartialParseResult.Accepted, \"DateTime.Now.\");\n            }\n        }\n\n        [Fact]\n        public void ImplicitExpressionAcceptsDotlessCommitInsertionsInStatementBlock()\n        {\n            SpanFactory factory = SpanFactory.CreateCsHtml();\n            StringTextBuffer changed = new StringTextBuffer(\"@{\" + Environment.NewLine\n                                                          + \"    @DateT.\" + Environment.NewLine\n                                                          + \"}\");\n            StringTextBuffer old = new StringTextBuffer(\"@{\" + Environment.NewLine\n                                                      + \"    @DateT\" + Environment.NewLine\n                                                      + \"}\");\n\n            var textChange = new TextChange(14, 0, old, 1, changed);\n            using (TestParserManager manager = CreateParserManager())\n            {\n                Action<TextChange, PartialParseResult, string> applyAndVerifyPartialChange = (changeToApply, expectedResult, expectedCode) =>\n                {\n                    PartialParseResult result = manager.CheckForStructureChangesAndWait(textChange);\n\n                    // Assert\n                    Assert.Equal(expectedResult, result);\n                    Assert.Equal(1, manager.ParseCount);\n                    ParserTestBase.EvaluateParseTree(manager.Parser.CurrentParseTree, new MarkupBlock(\n                        factory.EmptyHtml(),\n                        new StatementBlock(\n                            factory.CodeTransition(),\n                            factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                            factory.Code(\"\\r\\n    \").AsStatement(),\n                            new ExpressionBlock(\n                                factory.CodeTransition(),\n                                factory.Code(expectedCode)\n                                       .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true)\n                                       .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                            factory.Code(\"\\r\\n\").AsStatement(),\n                            factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                        factory.EmptyHtml()));\n                };\n\n                manager.InitializeWithDocument(textChange.OldBuffer);\n\n                // This is the process of a dotless commit when doing \".\" insertions to commit intellisense changes.\n                applyAndVerifyPartialChange(textChange, PartialParseResult.Accepted, \"DateT.\");\n\n                old = changed;\n                changed = new StringTextBuffer(\"@{\" + Environment.NewLine\n                                            + \"    @DateTime.\" + Environment.NewLine\n                                            + \"}\");\n                textChange = new TextChange(14, 0, old, 3, changed);\n\n                applyAndVerifyPartialChange(textChange, PartialParseResult.Accepted, \"DateTime.\");\n            }\n        }\n\n        [Fact]\n        public void ImplicitExpressionProvisionallyAcceptsDotlessCommitInsertions()\n        {\n            SpanFactory factory = SpanFactory.CreateCsHtml();\n            var changed = new StringTextBuffer(\"foo @DateT. baz\");\n            var old = new StringTextBuffer(\"foo @DateT baz\");\n            var textChange = new TextChange(10, 0, old, 1, changed);\n            using (TestParserManager manager = CreateParserManager())\n            {\n                Action<TextChange, PartialParseResult, string> applyAndVerifyPartialChange = (changeToApply, expectedResult, expectedCode) =>\n                {\n                    PartialParseResult result = manager.CheckForStructureChangesAndWait(textChange);\n\n                    // Assert\n                    Assert.Equal(expectedResult, result);\n                    Assert.Equal(1, manager.ParseCount);\n\n                    ParserTestBase.EvaluateParseTree(manager.Parser.CurrentParseTree, new MarkupBlock(\n                        factory.Markup(\"foo \"),\n                        new ExpressionBlock(\n                            factory.CodeTransition(),\n                            factory.Code(expectedCode).AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)),\n                        factory.Markup(\" baz\")));\n                };\n\n                manager.InitializeWithDocument(textChange.OldBuffer);\n\n                // This is the process of a dotless commit when doing \".\" insertions to commit intellisense changes.\n                applyAndVerifyPartialChange(textChange, PartialParseResult.Accepted | PartialParseResult.Provisional, \"DateT.\");\n\n                old = changed;\n                changed = new StringTextBuffer(\"foo @DateTime. baz\");\n                textChange = new TextChange(10, 0, old, 3, changed);\n\n                applyAndVerifyPartialChange(textChange, PartialParseResult.Accepted | PartialParseResult.Provisional, \"DateTime.\");\n            }\n        }\n\n        [Fact]\n        public void ImplicitExpressionProvisionallyAcceptsDotlessCommitInsertionsAfterIdentifiers()\n        {\n            SpanFactory factory = SpanFactory.CreateCsHtml();\n            var changed = new StringTextBuffer(\"foo @DateTime. baz\");\n            var old = new StringTextBuffer(\"foo @DateTime baz\");\n            var textChange = new TextChange(13, 0, old, 1, changed);\n            using (TestParserManager manager = CreateParserManager())\n            {\n                Action<TextChange, PartialParseResult, string> applyAndVerifyPartialChange = (changeToApply, expectedResult, expectedCode) =>\n                {\n                    PartialParseResult result = manager.CheckForStructureChangesAndWait(textChange);\n\n                    // Assert\n                    Assert.Equal(expectedResult, result);\n                    Assert.Equal(1, manager.ParseCount);\n\n                    ParserTestBase.EvaluateParseTree(manager.Parser.CurrentParseTree, new MarkupBlock(\n                        factory.Markup(\"foo \"),\n                        new ExpressionBlock(\n                            factory.CodeTransition(),\n                            factory.Code(expectedCode).AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)),\n                        factory.Markup(\" baz\")));\n                };\n\n                manager.InitializeWithDocument(textChange.OldBuffer);\n\n                // This is the process of a dotless commit when doing \".\" insertions to commit intellisense changes.\n                applyAndVerifyPartialChange(textChange, PartialParseResult.Accepted | PartialParseResult.Provisional, \"DateTime.\");\n\n                old = changed;\n                changed = new StringTextBuffer(\"foo @DateTime.. baz\");\n                textChange = new TextChange(14, 0, old, 1, changed);\n\n                applyAndVerifyPartialChange(textChange, PartialParseResult.Accepted | PartialParseResult.Provisional, \"DateTime..\");\n\n                old = changed;\n                changed = new StringTextBuffer(\"foo @DateTime.Now. baz\");\n                textChange = new TextChange(14, 0, old, 3, changed);\n\n                applyAndVerifyPartialChange(textChange, PartialParseResult.Accepted | PartialParseResult.Provisional, \"DateTime.Now.\");\n            }\n        }\n\n        [Fact]\n        public void ImplicitExpressionProvisionallyAcceptsCaseInsensitiveDotlessCommitInsertions_NewRoslynIntegration()\n        {\n            SpanFactory factory = SpanFactory.CreateCsHtml();\n            StringTextBuffer old = new StringTextBuffer(\"foo @date baz\");\n            StringTextBuffer changed = new StringTextBuffer(\"foo @date. baz\");\n            TextChange textChange = new TextChange(9, 0, old, 1, changed);\n            using (TestParserManager manager = CreateParserManager())\n            {\n                Action<TextChange, PartialParseResult, string> applyAndVerifyPartialChange = (changeToApply, expectedResult, expectedCode) =>\n                {\n                    PartialParseResult result = manager.CheckForStructureChangesAndWait(textChange);\n\n                    // Assert\n                    Assert.Equal(expectedResult, result);\n                    Assert.Equal(1, manager.ParseCount);\n\n                    ParserTestBase.EvaluateParseTree(manager.Parser.CurrentParseTree, new MarkupBlock(\n                        factory.Markup(\"foo \"),\n                        new ExpressionBlock(\n                            factory.CodeTransition(),\n                            factory.Code(expectedCode).AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)),\n                        factory.Markup(\" baz\")));\n                };\n\n                manager.InitializeWithDocument(textChange.OldBuffer);\n\n                // This is the process of a dotless commit when doing \".\" insertions to commit intellisense changes.\n\n                // @date => @date.\n                applyAndVerifyPartialChange(textChange, PartialParseResult.Accepted | PartialParseResult.Provisional, \"date.\");\n\n                old = changed;\n                changed = new StringTextBuffer(\"foo @date baz\");\n                textChange = new TextChange(9, 1, old, 0, changed);\n\n                // @date. => @date\n                applyAndVerifyPartialChange(textChange, PartialParseResult.Accepted, \"date\");\n\n                old = changed;\n                changed = new StringTextBuffer(\"foo @DateTime baz\");\n                textChange = new TextChange(5, 4, old, 8, changed);\n\n                // @date => @DateTime\n                applyAndVerifyPartialChange(textChange, PartialParseResult.Accepted, \"DateTime\");\n\n                old = changed;\n                changed = new StringTextBuffer(\"foo @DateTime. baz\");\n                textChange = new TextChange(13, 0, old, 1, changed);\n\n                // @DateTime => @DateTime.\n                applyAndVerifyPartialChange(textChange, PartialParseResult.Accepted | PartialParseResult.Provisional, \"DateTime.\");\n            }\n        }\n\n        [Fact]\n        public void ImplicitExpressionProvisionallyAcceptsDeleteOfIdentifierPartsIfDotRemains()\n        {\n            SpanFactory factory = SpanFactory.CreateCsHtml();\n            StringTextBuffer changed = new StringTextBuffer(\"foo @User. baz\");\n            StringTextBuffer old = new StringTextBuffer(\"foo @User.Name baz\");\n            RunPartialParseTest(new TextChange(10, 4, old, 0, changed),\n                new MarkupBlock(\n                    factory.Markup(\"foo \"),\n                    new ExpressionBlock(\n                        factory.CodeTransition(),\n                        factory.Code(\"User.\").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    factory.Markup(\" baz\")),\n                additionalFlags: PartialParseResult.Provisional);\n        }\n\n        [Fact]\n        public void ImplicitExpressionAcceptsDeleteOfIdentifierPartsIfSomeOfIdentifierRemains()\n        {\n            var factory = SpanFactory.CreateCsHtml();\n            StringTextBuffer changed = new StringTextBuffer(\"foo @Us baz\");\n            StringTextBuffer old = new StringTextBuffer(\"foo @User baz\");\n            RunPartialParseTest(new TextChange(7, 2, old, 0, changed),\n                new MarkupBlock(\n                    factory.Markup(\"foo \"),\n                    new ExpressionBlock(\n                        factory.CodeTransition(),\n                        factory.Code(\"Us\").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    factory.Markup(\" baz\")));\n        }\n\n        [Fact]\n        public void ImplicitExpressionProvisionallyAcceptsMultipleInsertionIfItCausesIdentifierExpansionAndTrailingDot()\n        {\n            var factory = SpanFactory.CreateCsHtml();\n            StringTextBuffer changed = new StringTextBuffer(\"foo @User. baz\");\n            StringTextBuffer old = new StringTextBuffer(\"foo @U baz\");\n            RunPartialParseTest(new TextChange(6, 0, old, 4, changed),\n                new MarkupBlock(\n                    factory.Markup(\"foo \"),\n                    new ExpressionBlock(\n                        factory.CodeTransition(),\n                        factory.Code(\"User.\").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    factory.Markup(\" baz\")),\n                additionalFlags: PartialParseResult.Provisional);\n        }\n\n        [Fact]\n        public void ImplicitExpressionAcceptsMultipleInsertionIfItOnlyCausesIdentifierExpansion()\n        {\n            var factory = SpanFactory.CreateCsHtml();\n            StringTextBuffer changed = new StringTextBuffer(\"foo @barbiz baz\");\n            StringTextBuffer old = new StringTextBuffer(\"foo @bar baz\");\n            RunPartialParseTest(new TextChange(8, 0, old, 3, changed),\n                new MarkupBlock(\n                    factory.Markup(\"foo \"),\n                    new ExpressionBlock(\n                        factory.CodeTransition(),\n                        factory.Code(\"barbiz\").AsImplicitExpression(CSharpCodeParser.DefaultKeywords).Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    factory.Markup(\" baz\")));\n        }\n\n        [Fact]\n        public void ImplicitExpressionAcceptsIdentifierExpansionAtEndOfNonWhitespaceCharacters()\n        {\n            var factory = SpanFactory.CreateCsHtml();\n            StringTextBuffer changed = new StringTextBuffer(\"@{\" + Environment.NewLine\n                                                          + \"    @food\" + Environment.NewLine\n                                                          + \"}\");\n            StringTextBuffer old = new StringTextBuffer(\"@{\" + Environment.NewLine\n                                                      + \"    @foo\" + Environment.NewLine\n                                                      + \"}\");\n            RunPartialParseTest(new TextChange(12, 0, old, 1, changed),\n                new MarkupBlock(\n                    factory.EmptyHtml(),\n                    new StatementBlock(\n                        factory.CodeTransition(),\n                        factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                        factory.Code(\"\\r\\n    \").AsStatement(),\n                        new ExpressionBlock(\n                            factory.CodeTransition(),\n                            factory.Code(\"food\")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                        factory.Code(\"\\r\\n\").AsStatement(),\n                        factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                    factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void ImplicitExpressionAcceptsIdentifierAfterDotAtEndOfNonWhitespaceCharacters()\n        {\n            var factory = SpanFactory.CreateCsHtml();\n            StringTextBuffer changed = new StringTextBuffer(\"@{\" + Environment.NewLine\n                                                          + \"    @foo.d\" + Environment.NewLine\n                                                          + \"}\");\n            StringTextBuffer old = new StringTextBuffer(\"@{\" + Environment.NewLine\n                                                      + \"    @foo.\" + Environment.NewLine\n                                                      + \"}\");\n            RunPartialParseTest(new TextChange(13, 0, old, 1, changed),\n                new MarkupBlock(\n                    factory.EmptyHtml(),\n                    new StatementBlock(\n                        factory.CodeTransition(),\n                        factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                        factory.Code(\"\\r\\n    \").AsStatement(),\n                        new ExpressionBlock(\n                            factory.CodeTransition(),\n                            factory.Code(\"foo.d\")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                        factory.Code(\"\\r\\n\").AsStatement(),\n                        factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                    factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void ImplicitExpressionAcceptsDotAtEndOfNonWhitespaceCharacters()\n        {\n            var factory = SpanFactory.CreateCsHtml();\n            StringTextBuffer changed = new StringTextBuffer(\"@{\" + Environment.NewLine\n                                                          + \"    @foo.\" + Environment.NewLine\n                                                          + \"}\");\n            StringTextBuffer old = new StringTextBuffer(\"@{\" + Environment.NewLine\n                                                      + \"    @foo\" + Environment.NewLine\n                                                      + \"}\");\n            RunPartialParseTest(new TextChange(12, 0, old, 1, changed),\n                new MarkupBlock(\n                    factory.EmptyHtml(),\n                    new StatementBlock(\n                        factory.CodeTransition(),\n                        factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                        factory.Code(\"\\r\\n    \").AsStatement(),\n                        new ExpressionBlock(\n                            factory.CodeTransition(),\n                            factory.Code(@\"foo.\")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                        factory.Code(\"\\r\\n\").AsStatement(),\n                        factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                    factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void ImplicitExpressionRejectsChangeWhichWouldHaveBeenAcceptedIfLastChangeWasProvisionallyAcceptedOnDifferentSpan()\n        {\n            var factory = SpanFactory.CreateCsHtml();\n\n            // Arrange\n            TextChange dotTyped = new TextChange(8, 0, new StringTextBuffer(\"foo @foo @bar\"), 1, new StringTextBuffer(\"foo @foo. @bar\"));\n            TextChange charTyped = new TextChange(14, 0, new StringTextBuffer(\"foo @foo. @bar\"), 1, new StringTextBuffer(\"foo @foo. @barb\"));\n            using (TestParserManager manager = CreateParserManager())\n            {\n                manager.InitializeWithDocument(dotTyped.OldBuffer);\n\n                // Apply the dot change\n                Assert.Equal(PartialParseResult.Provisional | PartialParseResult.Accepted, manager.CheckForStructureChangesAndWait(dotTyped));\n\n                // Act (apply the identifier start char change)\n                PartialParseResult result = manager.CheckForStructureChangesAndWait(charTyped);\n\n                // Assert\n                Assert.Equal(PartialParseResult.Rejected, result);\n                Assert.False(manager.Parser.LastResultProvisional, \"LastResultProvisional flag should have been cleared but it was not\");\n                ParserTestBase.EvaluateParseTree(manager.Parser.CurrentParseTree,\n                    new MarkupBlock(\n                        factory.Markup(\"foo \"),\n                        new ExpressionBlock(\n                            factory.CodeTransition(),\n                            factory.Code(\"foo\")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                        factory.Markup(\". \"),\n                        new ExpressionBlock(\n                            factory.CodeTransition(),\n                            factory.Code(\"barb\")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                        factory.EmptyHtml()));\n            }\n        }\n\n        [Fact]\n        public void ImplicitExpressionAcceptsIdentifierTypedAfterDotIfLastChangeWasProvisionalAcceptanceOfDot()\n        {\n            var factory = SpanFactory.CreateCsHtml();\n\n            // Arrange\n            TextChange dotTyped = new TextChange(8, 0, new StringTextBuffer(\"foo @foo bar\"), 1, new StringTextBuffer(\"foo @foo. bar\"));\n            TextChange charTyped = new TextChange(9, 0, new StringTextBuffer(\"foo @foo. bar\"), 1, new StringTextBuffer(\"foo @foo.b bar\"));\n            using (TestParserManager manager = CreateParserManager())\n            {\n                manager.InitializeWithDocument(dotTyped.OldBuffer);\n\n                // Apply the dot change\n                Assert.Equal(PartialParseResult.Provisional | PartialParseResult.Accepted, manager.CheckForStructureChangesAndWait(dotTyped));\n\n                // Act (apply the identifier start char change)\n                PartialParseResult result = manager.CheckForStructureChangesAndWait(charTyped);\n\n                // Assert\n                Assert.Equal(PartialParseResult.Accepted, result);\n                Assert.False(manager.Parser.LastResultProvisional, \"LastResultProvisional flag should have been cleared but it was not\");\n                ParserTestBase.EvaluateParseTree(manager.Parser.CurrentParseTree,\n                    new MarkupBlock(\n                        factory.Markup(\"foo \"),\n                        new ExpressionBlock(\n                            factory.CodeTransition(),\n                            factory.Code(\"foo.b\")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                        factory.Markup(\" bar\")));\n            }\n        }\n\n        [Fact]\n        public void ImplicitExpressionProvisionallyAcceptsDotAfterIdentifierInMarkup()\n        {\n            var factory = SpanFactory.CreateCsHtml();\n            StringTextBuffer changed = new StringTextBuffer(\"foo @foo. bar\");\n            StringTextBuffer old = new StringTextBuffer(\"foo @foo bar\");\n            RunPartialParseTest(new TextChange(8, 0, old, 1, changed),\n                new MarkupBlock(\n                    factory.Markup(\"foo \"),\n                    new ExpressionBlock(\n                        factory.CodeTransition(),\n                        factory.Code(\"foo.\")\n                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    factory.Markup(\" bar\")),\n                additionalFlags: PartialParseResult.Provisional);\n        }\n\n        [Fact]\n        public void ImplicitExpressionAcceptsAdditionalIdentifierCharactersIfEndOfSpanIsIdentifier()\n        {\n            var factory = SpanFactory.CreateCsHtml();\n            StringTextBuffer changed = new StringTextBuffer(\"foo @foob bar\");\n            StringTextBuffer old = new StringTextBuffer(\"foo @foo bar\");\n            RunPartialParseTest(new TextChange(8, 0, old, 1, changed),\n                new MarkupBlock(\n                    factory.Markup(\"foo \"),\n                    new ExpressionBlock(\n                        factory.CodeTransition(),\n                        factory.Code(\"foob\")\n                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    factory.Markup(\" bar\")));\n        }\n\n        [Fact]\n        public void ImplicitExpressionAcceptsAdditionalIdentifierStartCharactersIfEndOfSpanIsDot()\n        {\n            var factory = SpanFactory.CreateCsHtml();\n            StringTextBuffer changed = new StringTextBuffer(\"@{@foo.b}\");\n            StringTextBuffer old = new StringTextBuffer(\"@{@foo.}\");\n            RunPartialParseTest(new TextChange(7, 0, old, 1, changed),\n                new MarkupBlock(\n                    factory.EmptyHtml(),\n                    new StatementBlock(\n                        factory.CodeTransition(),\n                        factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                        factory.EmptyCSharp().AsStatement(),\n                        new ExpressionBlock(\n                            factory.CodeTransition(),\n                            factory.Code(\"foo.b\")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                        factory.EmptyCSharp().AsStatement(),\n                        factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                    factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void ImplicitExpressionAcceptsDotIfTrailingDotsAreAllowed()\n        {\n            var factory = SpanFactory.CreateCsHtml();\n            StringTextBuffer changed = new StringTextBuffer(\"@{@foo.}\");\n            StringTextBuffer old = new StringTextBuffer(\"@{@foo}\");\n            RunPartialParseTest(new TextChange(6, 0, old, 1, changed),\n                new MarkupBlock(\n                    factory.EmptyHtml(),\n                    new StatementBlock(\n                        factory.CodeTransition(),\n                        factory.MetaCode(\"{\").Accepts(AcceptedCharacters.None),\n                        factory.EmptyCSharp().AsStatement(),\n                        new ExpressionBlock(\n                            factory.CodeTransition(),\n                            factory.Code(\"foo.\")\n                                   .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: true)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                        factory.EmptyCSharp().AsStatement(),\n                        factory.MetaCode(\"}\").Accepts(AcceptedCharacters.None)),\n                    factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfIfKeywordTyped()\n        {\n            RunTypeKeywordTest(\"if\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfDoKeywordTyped()\n        {\n            RunTypeKeywordTest(\"do\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfTryKeywordTyped()\n        {\n            RunTypeKeywordTest(\"try\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfForKeywordTyped()\n        {\n            RunTypeKeywordTest(\"for\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfForEachKeywordTyped()\n        {\n            RunTypeKeywordTest(\"foreach\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfWhileKeywordTyped()\n        {\n            RunTypeKeywordTest(\"while\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfSwitchKeywordTyped()\n        {\n            RunTypeKeywordTest(\"switch\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfLockKeywordTyped()\n        {\n            RunTypeKeywordTest(\"lock\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfUsingKeywordTyped()\n        {\n            RunTypeKeywordTest(\"using\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfSectionKeywordTyped()\n        {\n            RunTypeKeywordTest(\"section\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfInheritsKeywordTyped()\n        {\n            RunTypeKeywordTest(\"inherits\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfHelperKeywordTyped()\n        {\n            RunTypeKeywordTest(\"helper\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfFunctionsKeywordTyped()\n        {\n            RunTypeKeywordTest(\"functions\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfNamespaceKeywordTyped()\n        {\n            RunTypeKeywordTest(\"namespace\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfClassKeywordTyped()\n        {\n            RunTypeKeywordTest(\"class\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfLayoutKeywordTyped()\n        {\n            RunTypeKeywordTest(\"layout\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/PartialParsing/PartialParsingTestBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Threading;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Test.Utils;\nusing System.Web.Razor.Text;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.PartialParsing\n{\n    public abstract class PartialParsingTestBase<TLanguage>\n        where TLanguage : RazorCodeLanguage, new()\n    {\n        private const string TestLinePragmaFileName = \"C:\\\\This\\\\Path\\\\Is\\\\Just\\\\For\\\\Line\\\\Pragmas.cshtml\";\n\n        protected static void RunFullReparseTest(TextChange change, PartialParseResult additionalFlags = (PartialParseResult)0)\n        {\n            // Arrange\n            using (TestParserManager manager = CreateParserManager())\n            {\n                manager.InitializeWithDocument(change.OldBuffer);\n\n                // Act\n                PartialParseResult result = manager.CheckForStructureChangesAndWait(change);\n\n                // Assert\n                Assert.Equal(PartialParseResult.Rejected | additionalFlags, result);\n                Assert.Equal(2, manager.ParseCount);\n            }\n        }\n\n        protected static void RunPartialParseTest(TextChange change, Block newTreeRoot, PartialParseResult additionalFlags = (PartialParseResult)0)\n        {\n            // Arrange\n            using (TestParserManager manager = CreateParserManager())\n            {\n                manager.InitializeWithDocument(change.OldBuffer);\n\n                // Act\n                PartialParseResult result = manager.CheckForStructureChangesAndWait(change);\n\n                // Assert\n                Assert.Equal(PartialParseResult.Accepted | additionalFlags, result);\n                Assert.Equal(1, manager.ParseCount);\n                ParserTestBase.EvaluateParseTree(manager.Parser.CurrentParseTree, newTreeRoot);\n            }\n        }\n\n        protected static TestParserManager CreateParserManager()\n        {\n            RazorEngineHost host = CreateHost();\n            RazorEditorParser parser = new RazorEditorParser(host, TestLinePragmaFileName);\n            return new TestParserManager(parser);\n        }\n\n        protected static RazorEngineHost CreateHost()\n        {\n            return new RazorEngineHost(new TLanguage())\n            {\n                GeneratedClassContext = new GeneratedClassContext(\"Execute\", \"Write\", \"WriteLiteral\", \"WriteTo\", \"WriteLiteralTo\", \"Template\", \"DefineSection\"),\n                DesignTimeMode = true\n            };\n        }\n\n        protected static void RunTypeKeywordTest(string keyword)\n        {\n            string before = \"@\" + keyword.Substring(0, keyword.Length - 1);\n            string after = \"@\" + keyword;\n            StringTextBuffer changed = new StringTextBuffer(after);\n            StringTextBuffer old = new StringTextBuffer(before);\n            RunFullReparseTest(new TextChange(keyword.Length, 0, old, 1, changed), additionalFlags: PartialParseResult.SpanContextChanged);\n        }\n\n        protected class TestParserManager : IDisposable\n        {\n            public RazorEditorParser Parser;\n            public ManualResetEventSlim ParserComplete;\n            public int ParseCount;\n\n            public TestParserManager(RazorEditorParser parser)\n            {\n                ParserComplete = new ManualResetEventSlim();\n                ParseCount = 0;\n                Parser = parser;\n                parser.DocumentParseComplete += (sender, args) =>\n                {\n                    Interlocked.Increment(ref ParseCount);\n                    ParserComplete.Set();\n                };\n            }\n\n            public void InitializeWithDocument(ITextBuffer startDocument)\n            {\n                CheckForStructureChangesAndWait(new TextChange(0, 0, new StringTextBuffer(String.Empty), startDocument.Length, startDocument));\n            }\n\n            public PartialParseResult CheckForStructureChangesAndWait(TextChange change)\n            {\n                PartialParseResult result = Parser.CheckForStructureChanges(change);\n                if (result.HasFlag(PartialParseResult.Rejected))\n                {\n                    WaitForParse();\n                }\n                return result;\n            }\n\n            public void WaitForParse()\n            {\n                MiscUtils.DoWithTimeoutIfNotDebugging(ParserComplete.Wait); // Wait for the parse to finish\n                ParserComplete.Reset();\n            }\n\n            public void Dispose()\n            {\n                Parser.Dispose();\n                ParserComplete.Dispose();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/PartialParsing/VBPartialParsingTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.PartialParsing\n{\n    public class VBPartialParsingTest : PartialParsingTestBase<VBRazorCodeLanguage>\n    {\n        [Fact]\n        public void ImplicitExpressionProvisionallyAcceptsDeleteOfIdentifierPartsIfDotRemains()\n        {\n            var factory = SpanFactory.CreateVbHtml();\n            StringTextBuffer changed = new StringTextBuffer(\"foo @User. baz\");\n            StringTextBuffer old = new StringTextBuffer(\"foo @User.Name baz\");\n            RunPartialParseTest(new TextChange(10, 4, old, 0, changed),\n                new MarkupBlock(\n                    factory.Markup(\"foo \"),\n                    new ExpressionBlock(\n                        factory.CodeTransition(),\n                        factory.Code(\"User.\")\n                               .AsImplicitExpression(VBCodeParser.DefaultKeywords)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    factory.Markup(\" baz\")),\n                additionalFlags: PartialParseResult.Provisional);\n        }\n\n        [Fact]\n        public void ImplicitExpressionAcceptsDeleteOfIdentifierPartsIfSomeOfIdentifierRemains()\n        {\n            var factory = SpanFactory.CreateVbHtml();\n            StringTextBuffer changed = new StringTextBuffer(\"foo @Us baz\");\n            StringTextBuffer old = new StringTextBuffer(\"foo @User baz\");\n            RunPartialParseTest(new TextChange(7, 2, old, 0, changed),\n                new MarkupBlock(\n                    factory.Markup(\"foo \"),\n                    new ExpressionBlock(\n                        factory.CodeTransition(),\n                        factory.Code(\"Us\")\n                               .AsImplicitExpression(VBCodeParser.DefaultKeywords)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    factory.Markup(\" baz\")));\n        }\n\n        [Fact]\n        public void ImplicitExpressionProvisionallyAcceptsMultipleInsertionIfItCausesIdentifierExpansionAndTrailingDot()\n        {\n            var factory = SpanFactory.CreateVbHtml();\n            StringTextBuffer changed = new StringTextBuffer(\"foo @User. baz\");\n            StringTextBuffer old = new StringTextBuffer(\"foo @U baz\");\n            RunPartialParseTest(new TextChange(6, 0, old, 4, changed),\n                new MarkupBlock(\n                    factory.Markup(\"foo \"),\n                    new ExpressionBlock(\n                        factory.CodeTransition(),\n                        factory.Code(\"User.\")\n                               .AsImplicitExpression(VBCodeParser.DefaultKeywords)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    factory.Markup(\" baz\")),\n                additionalFlags: PartialParseResult.Provisional);\n        }\n\n        [Fact]\n        public void ImplicitExpressionAcceptsMultipleInsertionIfItOnlyCausesIdentifierExpansion()\n        {\n            var factory = SpanFactory.CreateVbHtml();\n            StringTextBuffer changed = new StringTextBuffer(\"foo @barbiz baz\");\n            StringTextBuffer old = new StringTextBuffer(\"foo @bar baz\");\n            RunPartialParseTest(new TextChange(8, 0, old, 3, changed),\n                new MarkupBlock(\n                    factory.Markup(\"foo \"),\n                    new ExpressionBlock(\n                        factory.CodeTransition(),\n                        factory.Code(\"barbiz\")\n                               .AsImplicitExpression(VBCodeParser.DefaultKeywords)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    factory.Markup(\" baz\")));\n        }\n\n        [Fact]\n        public void ImplicitExpressionRejectsChangeWhichWouldHaveBeenAcceptedIfLastChangeWasProvisionallyAcceptedOnDifferentSpan()\n        {\n            var factory = SpanFactory.CreateVbHtml();\n\n            // Arrange\n            TextChange dotTyped = new TextChange(8, 0, new StringTextBuffer(\"foo @foo @bar\"), 1, new StringTextBuffer(\"foo @foo. @bar\"));\n            TextChange charTyped = new TextChange(14, 0, new StringTextBuffer(\"foo @foo. @barb\"), 1, new StringTextBuffer(\"foo @foo. @barb\"));\n            using (TestParserManager manager = CreateParserManager())\n            {\n                manager.InitializeWithDocument(dotTyped.OldBuffer);\n\n                // Apply the dot change\n                Assert.Equal(PartialParseResult.Provisional | PartialParseResult.Accepted, manager.CheckForStructureChangesAndWait(dotTyped));\n\n                // Act (apply the identifier start char change)\n                PartialParseResult result = manager.CheckForStructureChangesAndWait(charTyped);\n\n                // Assert\n                Assert.Equal(PartialParseResult.Rejected, result);\n                Assert.False(manager.Parser.LastResultProvisional, \"LastResultProvisional flag should have been cleared but it was not\");\n                ParserTestBase.EvaluateParseTree(manager.Parser.CurrentParseTree,\n                    new MarkupBlock(\n                        factory.Markup(\"foo \"),\n                        new ExpressionBlock(\n                            factory.CodeTransition(),\n                            factory.Code(\"foo\")\n                                   .AsImplicitExpression(VBCodeParser.DefaultKeywords)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                        factory.Markup(\". \"),\n                        new ExpressionBlock(\n                            factory.CodeTransition(),\n                            factory.Code(\"barb\")\n                                   .AsImplicitExpression(VBCodeParser.DefaultKeywords)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                        factory.EmptyHtml()));\n            }\n        }\n\n        [Fact]\n        public void ImplicitExpressionAcceptsIdentifierTypedAfterDotIfLastChangeWasProvisionalAcceptanceOfDot()\n        {\n            var factory = SpanFactory.CreateVbHtml();\n\n            // Arrange\n            TextChange dotTyped = new TextChange(8, 0, new StringTextBuffer(\"foo @foo bar\"), 1, new StringTextBuffer(\"foo @foo. bar\"));\n            TextChange charTyped = new TextChange(9, 0, new StringTextBuffer(\"foo @foo. bar\"), 1, new StringTextBuffer(\"foo @foo.b bar\"));\n            using (TestParserManager manager = CreateParserManager())\n            {\n                manager.InitializeWithDocument(dotTyped.OldBuffer);\n\n                // Apply the dot change\n                Assert.Equal(PartialParseResult.Provisional | PartialParseResult.Accepted, manager.CheckForStructureChangesAndWait(dotTyped));\n\n                // Act (apply the identifier start char change)\n                PartialParseResult result = manager.CheckForStructureChangesAndWait(charTyped);\n\n                // Assert\n                Assert.Equal(PartialParseResult.Accepted, result);\n                Assert.False(manager.Parser.LastResultProvisional, \"LastResultProvisional flag should have been cleared but it was not\");\n                ParserTestBase.EvaluateParseTree(manager.Parser.CurrentParseTree,\n                    new MarkupBlock(\n                        factory.Markup(\"foo \"),\n                        new ExpressionBlock(\n                            factory.CodeTransition(),\n                            factory.Code(\"foo.b\")\n                                   .AsImplicitExpression(VBCodeParser.DefaultKeywords)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                        factory.Markup(\" bar\")));\n            }\n        }\n        [Fact]\n        public void ImplicitExpressionAcceptsIdentifierExpansionAtEndOfNonWhitespaceCharacters()\n        {\n            var factory = SpanFactory.CreateVbHtml();\n            StringTextBuffer changed = new StringTextBuffer(\"@Code\" + Environment.NewLine\n                                                          + \"    @food\" + Environment.NewLine\n                                                          + \"End Code\");\n            StringTextBuffer old = new StringTextBuffer(\"@Code\" + Environment.NewLine\n                                                      + \"    @foo\" + Environment.NewLine\n                                                      + \"End Code\");\n            RunPartialParseTest(new TextChange(15, 0, old, 1, changed),\n                new MarkupBlock(\n                    factory.EmptyHtml(),\n                    new StatementBlock(\n                        factory.CodeTransition(),\n                        factory.MetaCode(\"Code\")\n                               .Accepts(AcceptedCharacters.None),\n                        factory.Code(\"\\r\\n    \").AsStatement(),\n                        new ExpressionBlock(\n                            factory.CodeTransition(),\n                            factory.Code(\"food\")\n                                   .AsImplicitExpression(VBCodeParser.DefaultKeywords, acceptTrailingDot: true)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                        factory.Code(\"\\r\\n\").AsStatement(),\n                        factory.MetaCode(\"End Code\").Accepts(AcceptedCharacters.None)),\n                    factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void ImplicitExpressionProvisionallyAcceptsDotAfterIdentifierInMarkup()\n        {\n            var factory = SpanFactory.CreateVbHtml();\n            StringTextBuffer changed = new StringTextBuffer(\"foo @foo. bar\");\n            StringTextBuffer old = new StringTextBuffer(\"foo @foo bar\");\n            RunPartialParseTest(new TextChange(8, 0, old, 1, changed),\n                new MarkupBlock(\n                    factory.Markup(\"foo \"),\n                    new ExpressionBlock(\n                        factory.CodeTransition(),\n                        factory.Code(\"foo.\")\n                               .AsImplicitExpression(VBCodeParser.DefaultKeywords)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    factory.Markup(\" bar\")),\n                additionalFlags: PartialParseResult.Provisional);\n        }\n\n        [Fact]\n        public void ImplicitExpressionAcceptsAdditionalIdentifierCharactersIfEndOfSpanIsIdentifier()\n        {\n            var factory = SpanFactory.CreateVbHtml();\n            StringTextBuffer changed = new StringTextBuffer(\"foo @foob baz\");\n            StringTextBuffer old = new StringTextBuffer(\"foo @foo bar\");\n            RunPartialParseTest(new TextChange(8, 0, old, 1, changed),\n                new MarkupBlock(\n                    factory.Markup(\"foo \"),\n                    new ExpressionBlock(\n                        factory.CodeTransition(),\n                        factory.Code(\"foob\")\n                               .AsImplicitExpression(VBCodeParser.DefaultKeywords)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    factory.Markup(\" bar\")));\n        }\n\n        [Fact]\n        public void ImplicitExpressionAcceptsAdditionalIdentifierStartCharactersIfEndOfSpanIsDot()\n        {\n            var factory = SpanFactory.CreateVbHtml();\n            StringTextBuffer changed = new StringTextBuffer(\"@Code @foo.b End Code\");\n            StringTextBuffer old = new StringTextBuffer(\"@Code @foo. End Code\");\n            RunPartialParseTest(new TextChange(11, 0, old, 1, changed),\n                new MarkupBlock(\n                    factory.EmptyHtml(),\n                    new StatementBlock(\n                        factory.CodeTransition(),\n                        factory.MetaCode(\"Code\").Accepts(AcceptedCharacters.None),\n                        factory.Code(\" \").AsStatement(),\n                        new ExpressionBlock(\n                            factory.CodeTransition(),\n                            factory.Code(\"foo.b\")\n                                   .AsImplicitExpression(VBCodeParser.DefaultKeywords, acceptTrailingDot: true)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                        factory.Code(\" \").AsStatement(),\n                        factory.MetaCode(\"End Code\").Accepts(AcceptedCharacters.None)),\n                    factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void ImplicitExpressionAcceptsDotIfTrailingDotsAreAllowed()\n        {\n            var factory = SpanFactory.CreateVbHtml();\n            StringTextBuffer changed = new StringTextBuffer(\"@Code @foo. End Code\");\n            StringTextBuffer old = new StringTextBuffer(\"@Code @foo End Code\");\n            RunPartialParseTest(new TextChange(10, 0, old, 1, changed),\n                new MarkupBlock(\n                    factory.EmptyHtml(),\n                    new StatementBlock(\n                        factory.CodeTransition(),\n                        factory.MetaCode(\"Code\").Accepts(AcceptedCharacters.None),\n                        factory.Code(\" \").AsStatement(),\n                        new ExpressionBlock(\n                            factory.CodeTransition(),\n                            factory.Code(\"foo.\")\n                                   .AsImplicitExpression(VBCodeParser.DefaultKeywords, acceptTrailingDot: true)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                        factory.Code(\" \").AsStatement(),\n                        factory.MetaCode(\"End Code\").Accepts(AcceptedCharacters.None)),\n                    factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfFunctionsKeywordTyped()\n        {\n            RunTypeKeywordTest(\"functions\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfCodeKeywordTyped()\n        {\n            RunTypeKeywordTest(\"code\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfSectionKeywordTyped()\n        {\n            RunTypeKeywordTest(\"section\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfDoKeywordTyped()\n        {\n            RunTypeKeywordTest(\"do\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfWhileKeywordTyped()\n        {\n            RunTypeKeywordTest(\"while\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfIfKeywordTyped()\n        {\n            RunTypeKeywordTest(\"if\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfSelectKeywordTyped()\n        {\n            RunTypeKeywordTest(\"select\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfForKeywordTyped()\n        {\n            RunTypeKeywordTest(\"for\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfTryKeywordTyped()\n        {\n            RunTypeKeywordTest(\"try\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfWithKeywordTyped()\n        {\n            RunTypeKeywordTest(\"with\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfSyncLockKeywordTyped()\n        {\n            RunTypeKeywordTest(\"synclock\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfUsingKeywordTyped()\n        {\n            RunTypeKeywordTest(\"using\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfImportsKeywordTyped()\n        {\n            RunTypeKeywordTest(\"imports\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfInheritsKeywordTyped()\n        {\n            RunTypeKeywordTest(\"inherits\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfOptionKeywordTyped()\n        {\n            RunTypeKeywordTest(\"option\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfHelperKeywordTyped()\n        {\n            RunTypeKeywordTest(\"helper\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfNamespaceKeywordTyped()\n        {\n            RunTypeKeywordTest(\"namespace\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfClassKeywordTyped()\n        {\n            RunTypeKeywordTest(\"class\");\n        }\n\n        [Fact]\n        public void ImplicitExpressionCorrectlyTriggersReparseIfLayoutKeywordTyped()\n        {\n            RunTypeKeywordTest(\"layout\");\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/RazorParserTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Framework;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Razor.Test.Parser\n{\n    public class RazorParserTest\n    {\n        [Fact]\n        public void ConstructorRequiresNonNullCodeParser()\n        {\n            Assert.ThrowsArgumentNull(() => new RazorParser(null, new HtmlMarkupParser()), \"codeParser\");\n        }\n\n        [Fact]\n        public void ConstructorRequiresNonNullMarkupParser()\n        {\n            Assert.ThrowsArgumentNull(() => new RazorParser(new CSharpCodeParser(), null), \"markupParser\");\n        }\n\n        [Fact]\n        public void ParseMethodCallsParseDocumentOnMarkupParserAndReturnsResults()\n        {\n            var factory = SpanFactory.CreateCsHtml();\n\n            // Arrange\n            RazorParser parser = new RazorParser(new CSharpCodeParser(), new HtmlMarkupParser());\n\n            // Act/Assert\n            ParserTestBase.EvaluateResults(parser.Parse(new StringReader(\"foo @bar baz\")),\n                new MarkupBlock(\n                    factory.Markup(\"foo \"),\n                    new ExpressionBlock(\n                        factory.CodeTransition(),\n                        factory.Code(\"bar\")\n                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    factory.Markup(\" baz\")));\n        }\n\n        [Fact]\n        public void Parse_ParsesDocumentAndInvokesVisitor()\n        {\n            // Arrange\n            var factory = SpanFactory.CreateCsHtml();\n            var visitor = new Mock<ParserVisitor> { CallBase = true };\n            var parser = new RazorParser(new CSharpCodeParser(), new HtmlMarkupParser());\n\n            // Act\n            parser.Parse(new StringReader(\"foo @bar baz\"), visitor.Object);\n\n            // Assert\n            visitor.Verify(v => v.VisitSpan(It.Is<Span>(s => s.Kind == SpanKind.Markup && s.Content == \"foo \")));\n            visitor.Verify(v => v.VisitSpan(It.Is<Span>(s => s.Kind == SpanKind.Transition && s.Content == \"@\")));\n            visitor.Verify(v => v.VisitSpan(It.Is<Span>(s => s.Kind == SpanKind.Code && s.Content == \"bar\")));\n            visitor.Verify(v => v.VisitSpan(It.Is<Span>(s => s.Kind == SpanKind.Markup && s.Content == \" baz\")));\n        }\n\n        [Fact]\n        public async Task CreateParseTask_ParsesDocumentAndInvokesVisitor()\n        {\n            // Arrange\n            var factory = SpanFactory.CreateCsHtml();\n            var visitor = new Mock<ParserVisitor> { CallBase = true };\n            var parser = new RazorParser(new CSharpCodeParser(), new HtmlMarkupParser());\n\n            // Act\n            var task = parser.CreateParseTask(new StringReader(\"foo @bar baz\"), visitor.Object);\n            task.Start();\n            await task;\n\n            // Assert\n            visitor.Verify(v => v.VisitSpan(It.Is<Span>(s => s.Kind == SpanKind.Markup && s.Content == \"foo \")));\n            visitor.Verify(v => v.VisitSpan(It.Is<Span>(s => s.Kind == SpanKind.Transition && s.Content == \"@\")));\n            visitor.Verify(v => v.VisitSpan(It.Is<Span>(s => s.Kind == SpanKind.Code && s.Content == \"bar\")));\n            visitor.Verify(v => v.VisitSpan(It.Is<Span>(s => s.Kind == SpanKind.Markup && s.Content == \" baz\")));\n        }\n\n        [Fact]\n        public async Task CreateParseTask_ReturnsWithoutThrowingIfTaskIsCancelled()\n        {\n            // Arrange\n            var factory = SpanFactory.CreateCsHtml();\n            var visitor = new Mock<ParserVisitor> { CallBase = true };\n            var parser = new RazorParser(new CSharpCodeParser(), new HtmlMarkupParser());\n            var cancelTokenSource = new CancellationTokenSource();\n            var visited = false;\n\n            // Act\n            var task = parser.CreateParseTask(new StringReader(\"foo @bar baz\"),\n                                              (span) =>\n                                              {\n                                                  visited = true;\n                                                  Assert.Equal(\"foo \", span.Content);\n                                                  cancelTokenSource.Cancel();\n                                              },\n                                              errorCallback: null,\n                                              cancelToken: cancelTokenSource.Token);\n            task.Start();\n            await task;\n\n            // Assert\n            Assert.True(visited);\n        }\n\n        [Fact]\n        public void ParseMethodUsesProvidedParserListenerIfSpecified()\n        {\n            var factory = SpanFactory.CreateCsHtml();\n\n            // Arrange\n            RazorParser parser = new RazorParser(new CSharpCodeParser(), new HtmlMarkupParser());\n\n            // Act\n            ParserResults results = parser.Parse(new StringReader(\"foo @bar baz\"));\n\n            // Assert\n            ParserTestBase.EvaluateResults(results,\n                new MarkupBlock(\n                    factory.Markup(\"foo \"),\n                    new ExpressionBlock(\n                        factory.CodeTransition(),\n                        factory.Code(\"bar\")\n                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    factory.Markup(\" baz\")));\n        }\n\n        [Fact]\n        public void ParseMethodSetsUpRunWithSpecifiedCodeParserMarkupParserAndListenerAndPassesToMarkupParser()\n        {\n            RunParseWithListenerTest((parser, reader) => parser.Parse(reader));\n        }\n\n        private static void RunParseWithListenerTest(Action<RazorParser, TextReader> parserAction)\n        {\n            // Arrange\n            ParserBase markupParser = new MockMarkupParser();\n            ParserBase codeParser = new CSharpCodeParser();\n            RazorParser parser = new RazorParser(codeParser, markupParser);\n            TextReader expectedReader = new StringReader(\"foo\");\n\n            // Act\n            parserAction(parser, expectedReader);\n\n            // Assert\n            ParserContext actualContext = markupParser.Context;\n            Assert.NotNull(actualContext);\n            Assert.Same(markupParser, actualContext.MarkupParser);\n            Assert.Same(markupParser, actualContext.ActiveParser);\n            Assert.Same(codeParser, actualContext.CodeParser);\n        }\n\n        private class MockMarkupParser : ParserBase\n        {\n            public override bool IsMarkupParser\n            {\n                get\n                {\n                    return true;\n                }\n            }\n\n            public override void ParseDocument()\n            {\n                using (Context.StartBlock(BlockType.Markup))\n                {\n                }\n            }\n\n            public override void ParseSection(Tuple<string, string> nestingSequences, bool caseSensitive = true)\n            {\n                using (Context.StartBlock(BlockType.Markup))\n                {\n                }\n            }\n\n            public override void ParseBlock()\n            {\n                using (Context.StartBlock(BlockType.Markup))\n                {\n                }\n            }\n\n            protected override ParserBase OtherParser\n            {\n                get { return Context.CodeParser; }\n            }\n\n            public override void BuildSpan(SpanBuilder span, Razor.Text.SourceLocation start, string content)\n            {\n                throw new NotImplementedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/VB/VBAutoCompleteTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.VB\n{\n    public class VBAutoCompleteTest : VBHtmlCodeParserTestBase\n    {\n        [Fact]\n        public void FunctionsDirective_AutoComplete_At_EOF()\n        {\n            ParseBlockTest(\"@Functions\",\n                new FunctionsBlock(\n                    Factory.CodeTransition(\"@\")\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.MetaCode(\"Functions\")\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.EmptyVB()\n                           .AsFunctionsBody()\n                           .With(new AutoCompleteEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString)\n                           {\n                               AutoCompleteString = SyntaxConstants.VB.EndFunctionsKeyword\n                           })),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_BlockNotTerminated, \"Functions\", \"End Functions\"),\n                    1, 0, 1));\n        }\n\n        [Fact]\n        public void HelperDirective_AutoComplete_At_EOF()\n        {\n            ParseBlockTest(\"@Helper Strong(value As String)\",\n                new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"Strong(value As String)\", 8, 0, 8), headerComplete: true),\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"Helper \")\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"Strong(value As String)\")\n                           .Hidden()\n                           .Accepts(AcceptedCharacters.None)\n                           .With(new AutoCompleteEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString) { AutoCompleteString = SyntaxConstants.VB.EndHelperKeyword }),\n                    new StatementBlock()),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_BlockNotTerminated, \"Helper\", \"End Helper\"),\n                    1, 0, 1));\n        }\n\n        [Fact]\n        public void SectionDirective_AutoComplete_At_EOF()\n        {\n            ParseBlockTest(\"@Section Header\",\n                new SectionBlock(new SectionCodeGenerator(\"Header\"),\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"Section Header\")\n                           .With(new AutoCompleteEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString) { AutoCompleteString = SyntaxConstants.VB.EndSectionKeyword }),\n                    new MarkupBlock()),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_BlockNotTerminated, \"Section\", \"End Section\"),\n                    1, 0, 1));\n        }\n\n        [Fact]\n        public void VerbatimBlock_AutoComplete_At_EOF()\n        {\n            ParseBlockTest(\"@Code\",\n                new StatementBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"Code\").Accepts(AcceptedCharacters.None),\n                    Factory.Span(SpanKind.Code, new VBSymbol(5, 0, 5, String.Empty, VBSymbolType.Unknown))\n                           .With(new StatementCodeGenerator())\n                           .With(new AutoCompleteEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString) { AutoCompleteString = SyntaxConstants.VB.EndCodeKeyword })),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_BlockNotTerminated, \"Code\", \"End Code\"),\n                    1, 0, 1));\n        }\n\n        [Fact]\n        public void FunctionsDirective_AutoComplete_At_StartOfFile()\n        {\n            ParseBlockTest(\"@Functions\" + Environment.NewLine\n                         + \"foo\",\n                new FunctionsBlock(\n                    Factory.CodeTransition(\"@\").Accepts(AcceptedCharacters.None),\n                    Factory.MetaCode(\"Functions\").Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"\\r\\nfoo\")\n                           .AsFunctionsBody()\n                           .With(new AutoCompleteEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString)\n                           {\n                               AutoCompleteString = SyntaxConstants.VB.EndFunctionsKeyword\n                           })),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_BlockNotTerminated, \"Functions\", \"End Functions\"),\n                    1, 0, 1));\n        }\n\n        [Fact]\n        public void HelperDirective_AutoComplete_At_StartOfFile()\n        {\n            ParseBlockTest(\"@Helper Strong(value As String)\" + Environment.NewLine\n                         + \"Foo\",\n                new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"Strong(value As String)\", 8, 0, 8), headerComplete: true),\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"Helper \")\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"Strong(value As String)\")\n                           .Hidden()\n                           .Accepts(AcceptedCharacters.None)\n                           .With(new AutoCompleteEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString) { AutoCompleteString = SyntaxConstants.VB.EndHelperKeyword }),\n                    new StatementBlock(\n                        Factory.Code(\"\\r\\nFoo\").AsStatement())),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_BlockNotTerminated, \"Helper\", \"End Helper\"),\n                    1, 0, 1));\n        }\n\n        [Fact]\n        public void SectionDirective_AutoComplete_At_StartOfFile()\n        {\n            ParseBlockTest(\"@Section Header\" + Environment.NewLine\n                         + \"Foo\",\n                new SectionBlock(new SectionCodeGenerator(\"Header\"),\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"Section Header\")\n                           .With(new AutoCompleteEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString) { AutoCompleteString = SyntaxConstants.VB.EndSectionKeyword }),\n                    new MarkupBlock(\n                        Factory.Markup(\"\\r\\nFoo\")\n                               .With(new MarkupCodeGenerator()))),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_BlockNotTerminated, \"Section\", \"End Section\"),\n                    1, 0, 1));\n        }\n\n        [Fact]\n        public void VerbatimBlock_AutoComplete_At_StartOfFile()\n        {\n            ParseBlockTest(\"@Code\" + Environment.NewLine\n                         + \"Foo\",\n                new StatementBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"Code\").Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"\\r\\nFoo\")\n                           .AsStatement()\n                           .With(new AutoCompleteEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString) { AutoCompleteString = SyntaxConstants.VB.EndCodeKeyword })),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_BlockNotTerminated, \"Code\", \"End Code\"),\n                    1, 0, 1));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/VB/VBBlockTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.VB\n{\n    public class VBBlockTest : VBHtmlCodeParserTestBase\n    {\n        [Fact]\n        public void ParseBlockMethodThrowsArgNullExceptionOnNullContext()\n        {\n            // Arrange\n            VBCodeParser parser = new VBCodeParser();\n\n            // Act and Assert\n            Assert.Throws<InvalidOperationException>(() => parser.ParseBlock(), RazorResources.Parser_Context_Not_Set);\n        }\n\n        [Fact]\n        public void ParseBlockAcceptsImplicitExpression()\n        {\n            ParseBlockTest(\"If True Then\" + Environment.NewLine\n                         + \"    @foo\" + Environment.NewLine\n                         + \"End If\",\n                new StatementBlock(\n                    Factory.Code(\"If True Then\\r\\n    \").AsStatement(),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"foo\")\n                               .AsImplicitExpression(VBCodeParser.DefaultKeywords, acceptTrailingDot: true)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    Factory.Code(\"\\r\\nEnd If\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockAcceptsIfStatementWithinCodeBlockIfInDesignTimeMode()\n        {\n            ParseBlockTest(\"If True Then\" + Environment.NewLine\n                         + \"    @If True Then\" + Environment.NewLine\n                         + \"    End If\" + Environment.NewLine\n                         + \"End If\",\n                new StatementBlock(\n                    Factory.Code(\"If True Then\\r\\n    \").AsStatement(),\n                    new StatementBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"If True Then\\r\\n    End If\\r\\n\")\n                               .AsStatement()\n                               .Accepts(AcceptedCharacters.None)),\n                    Factory.Code(@\"End If\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockSupportsSpacesInStrings()\n        {\n            ParseBlockTest(\"for each p in db.Query(\\\"SELECT * FROM PRODUCTS\\\")\" + Environment.NewLine\n                         + \"    @<p>@p.Name</p>\" + Environment.NewLine\n                         + \"next\",\n                new StatementBlock(\n                    Factory.Code(\"for each p in db.Query(\\\"SELECT * FROM PRODUCTS\\\")\\r\\n\")\n                           .AsStatement(),\n                    new MarkupBlock(\n                        Factory.Markup(\"    \"),\n                        Factory.MarkupTransition(),\n                        Factory.Markup(\"<p>\"),\n                        new ExpressionBlock(\n                            Factory.CodeTransition(),\n                            Factory.Code(\"p.Name\")\n                                   .AsImplicitExpression(VBCodeParser.DefaultKeywords)\n                                   .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                        Factory.Markup(\"</p>\\r\\n\").Accepts(AcceptedCharacters.None)),\n                    Factory.Code(\"next\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.WhiteSpace | AcceptedCharacters.NonWhiteSpace)));\n        }\n\n        [Fact]\n        public void ParseBlockSupportsSimpleCodeBlock()\n        {\n            ParseBlockTest(\"Code\" + Environment.NewLine\n                         + \"    If foo IsNot Nothing\" + Environment.NewLine\n                         + \"        Bar(foo)\" + Environment.NewLine\n                         + \"    End If\" + Environment.NewLine\n                         + \"End Code\",\n                new StatementBlock(\n                    Factory.MetaCode(\"Code\").Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"\\r\\n    If foo IsNot Nothing\\r\\n        Bar(foo)\\r\\n    End If\\r\\n\")\n                           .AsStatement(),\n                    Factory.MetaCode(\"End Code\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockRejectsNewlineBetweenEndAndCodeIfNotPrefixedWithUnderscore()\n        {\n            ParseBlockTest(\"Code\" + Environment.NewLine\n                         + \"    If foo IsNot Nothing\" + Environment.NewLine\n                         + \"        Bar(foo)\" + Environment.NewLine\n                         + \"    End If\" + Environment.NewLine\n                         + \"End\" + Environment.NewLine\n                         + \"Code\",\n                new StatementBlock(\n                    Factory.MetaCode(\"Code\").Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"\\r\\n    If foo IsNot Nothing\\r\\n        Bar(foo)\\r\\n    End If\\r\\nEnd\\r\\nCode\")\n                           .AsStatement()),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_BlockNotTerminated, \"Code\", \"End Code\"),\n                    SourceLocation.Zero));\n        }\n\n        [Fact]\n        public void ParseBlockAcceptsNewlineBetweenEndAndCodeIfPrefixedWithUnderscore()\n        {\n            ParseBlockTest(\"Code\" + Environment.NewLine\n                         + \"    If foo IsNot Nothing\" + Environment.NewLine\n                         + \"        Bar(foo)\" + Environment.NewLine\n                         + \"    End If\" + Environment.NewLine\n                         + \"End _\" + Environment.NewLine\n                         + \"_\" + Environment.NewLine\n                         + \" _\" + Environment.NewLine\n                         + \"Code\",\n                new StatementBlock(\n                    Factory.MetaCode(\"Code\").Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"\\r\\n    If foo IsNot Nothing\\r\\n        Bar(foo)\\r\\n    End If\\r\\n\")\n                           .AsStatement(),\n                    Factory.MetaCode(\"End _\\r\\n_\\r\\n _\\r\\nCode\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockSupportsSimpleFunctionsBlock()\n        {\n            ParseBlockTest(\"Functions\" + Environment.NewLine\n                         + \"    Public Sub Foo()\" + Environment.NewLine\n                         + \"        Bar()\" + Environment.NewLine\n                         + \"    End Sub\" + Environment.NewLine\n                         + Environment.NewLine\n                         + \"    Private Function Bar() As Object\" + Environment.NewLine\n                         + \"        Return Nothing\" + Environment.NewLine\n                         + \"    End Function\" + Environment.NewLine\n                         + \"End Functions\",\n                new FunctionsBlock(\n                    Factory.MetaCode(\"Functions\").Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"\\r\\n    Public Sub Foo()\\r\\n        Bar()\\r\\n    End Sub\\r\\n\\r\\n    Private Function Bar() As Object\\r\\n        Return Nothing\\r\\n    End Function\\r\\n\")\n                           .AsFunctionsBody(),\n                    Factory.MetaCode(\"End Functions\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockRejectsNewlineBetweenEndAndFunctionsIfNotPrefixedWithUnderscore()\n        {\n            ParseBlockTest(\"Functions\" + Environment.NewLine\n                         + \"    If foo IsNot Nothing\" + Environment.NewLine\n                         + \"        Bar(foo)\" + Environment.NewLine\n                         + \"    End If\" + Environment.NewLine\n                         + \"End\" + Environment.NewLine\n                         + \"Functions\",\n                new FunctionsBlock(\n                    Factory.MetaCode(\"Functions\").Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"\\r\\n    If foo IsNot Nothing\\r\\n        Bar(foo)\\r\\n    End If\\r\\nEnd\\r\\nFunctions\")\n                           .AsFunctionsBody()),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_BlockNotTerminated, \"Functions\", \"End Functions\"),\n                    SourceLocation.Zero));\n        }\n\n        [Fact]\n        public void ParseBlockAcceptsNewlineBetweenEndAndFunctionsIfPrefixedWithUnderscore()\n        {\n            ParseBlockTest(\"Functions\" + Environment.NewLine\n                         + \"    If foo IsNot Nothing\" + Environment.NewLine\n                         + \"        Bar(foo)\" + Environment.NewLine\n                         + \"    End If\" + Environment.NewLine\n                         + \"End _\" + Environment.NewLine\n                         + \"_\" + Environment.NewLine\n                         + \" _\" + Environment.NewLine\n                         + \"Functions\",\n                new FunctionsBlock(\n                    Factory.MetaCode(\"Functions\").Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"\\r\\n    If foo IsNot Nothing\\r\\n        Bar(foo)\\r\\n    End If\\r\\n\")\n                           .AsFunctionsBody(),\n                    Factory.MetaCode(\"End _\\r\\n_\\r\\n _\\r\\nFunctions\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockCorrectlyHandlesExtraEndsInEndCode()\n        {\n            ParseBlockTest(\"Code\" + Environment.NewLine\n                         + \"    Bar End\" + Environment.NewLine\n                         + \"End Code\",\n                new StatementBlock(\n                    Factory.MetaCode(\"Code\").Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"\\r\\n    Bar End\\r\\n\").AsStatement(),\n                    Factory.MetaCode(\"End Code\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockCorrectlyHandlesExtraEndsInEndFunctions()\n        {\n            ParseBlockTest(\"Functions\" + Environment.NewLine\n                         + \"    Bar End\" + Environment.NewLine\n                         + \"End Functions\",\n                new FunctionsBlock(\n                    Factory.MetaCode(\"Functions\").Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"\\r\\n    Bar End\\r\\n\").AsFunctionsBody().AutoCompleteWith(null, atEndOfSpan: false),\n                    Factory.MetaCode(\"End Functions\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Theory]\n        [InlineData(\"If\", \"End\", \"If\")]\n        [InlineData(\"Try\", \"End\", \"Try\")]\n        [InlineData(\"While\", \"End\", \"While\")]\n        [InlineData(\"Using\", \"End\", \"Using\")]\n        [InlineData(\"With\", \"End\", \"With\")]\n        public void KeywordAllowsNewlinesIfPrefixedByUnderscore(string startKeyword, string endKeyword1, string endKeyword2)\n        {\n            string code = startKeyword + Environment.NewLine\n                        + \"    ' In the block\" + Environment.NewLine\n                        + endKeyword1 + \" _\" + Environment.NewLine\n                        + \"_\" + Environment.NewLine\n                        + \"_\" + Environment.NewLine\n                        + \"_\" + Environment.NewLine\n                        + \"_\" + Environment.NewLine\n                        + \"_\" + Environment.NewLine\n                        + \"  \" + endKeyword2 + Environment.NewLine;\n            ParseBlockTest(code + \"foo bar baz\",\n                new StatementBlock(\n                    Factory.Code(code)\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Theory]\n        [InlineData(\"While\", \"EndWhile\", \"End While\")]\n        [InlineData(\"If\", \"EndIf\", \"End If\")]\n        [InlineData(\"Select\", \"EndSelect\", \"End Select\")]\n        [InlineData(\"Try\", \"EndTry\", \"End Try\")]\n        [InlineData(\"With\", \"EndWith\", \"End With\")]\n        [InlineData(\"Using\", \"EndUsing\", \"End Using\")]\n        public void EndTerminatedKeywordRequiresSpaceBetweenEndAndKeyword(string startKeyword, string wrongEndKeyword, string endKeyword)\n        {\n            string code = startKeyword + Environment.NewLine\n                        + \"    ' This should not end the code\" + Environment.NewLine\n                        + \"    \" + wrongEndKeyword + Environment.NewLine\n                        + \"    ' But this should\" + Environment.NewLine\n                        + endKeyword;\n            ParseBlockTest(code,\n                new StatementBlock(\n                    Factory.Code(code)\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Theory]\n        [InlineData(\"While\", \"End While\", false)]\n        [InlineData(\"Do\", \"Loop\", true)]\n        [InlineData(\"If\", \"End If\", false)]\n        [InlineData(\"Select\", \"End Select\", false)]\n        [InlineData(\"For\", \"Next\", true)]\n        [InlineData(\"Try\", \"End Try\", false)]\n        [InlineData(\"With\", \"End With\", false)]\n        [InlineData(\"Using\", \"End Using\", false)]\n        public void EndSequenceInString(string keyword, string endSequence, bool acceptToEndOfLine)\n        {\n            string code = keyword + Environment.NewLine\n                        + \"    \\\"\" + endSequence + \"\\\"\" + Environment.NewLine\n                        + endSequence + (acceptToEndOfLine ? \" foo bar baz\" : \"\") + Environment.NewLine;\n            ParseBlockTest(code + \"biz boz\",\n                new StatementBlock(\n                    Factory.Code(code).AsStatement().Accepts(GetAcceptedCharacters(acceptToEndOfLine))));\n        }\n\n        [Theory]\n        [InlineData(\"While\", \"End While\", false)]\n        [InlineData(\"Do\", \"Loop\", true)]\n        [InlineData(\"If\", \"End If\", false)]\n        [InlineData(\"Select\", \"End Select\", false)]\n        [InlineData(\"For\", \"Next\", true)]\n        [InlineData(\"Try\", \"End Try\", false)]\n        [InlineData(\"With\", \"End With\", false)]\n        [InlineData(\"Using\", \"End Using\", false)]\n        private void CommentedEndSequence(string keyword, string endSequence, bool acceptToEndOfLine)\n        {\n            string code = keyword + Environment.NewLine\n                        + \"    '\" + endSequence + Environment.NewLine\n                        + endSequence + (acceptToEndOfLine ? @\" foo bar baz\" : \"\") + Environment.NewLine;\n            ParseBlockTest(code + \"biz boz\",\n                new StatementBlock(\n                    Factory.Code(code).AsStatement().Accepts(GetAcceptedCharacters(acceptToEndOfLine))));\n        }\n\n        [Theory]\n        [InlineData(\"While\", \"End While\", false)]\n        [InlineData(\"Do\", \"Loop\", true)]\n        [InlineData(\"If\", \"End If\", false)]\n        [InlineData(\"Select\", \"End Select\", false)]\n        [InlineData(\"For\", \"Next\", true)]\n        [InlineData(\"Try\", \"End Try\", false)]\n        [InlineData(\"With\", \"End With\", false)]\n        [InlineData(\"SyncLock\", \"End SyncLock\", false)]\n        [InlineData(\"Using\", \"End Using\", false)]\n        private void NestedKeywordBlock(string keyword, string endSequence, bool acceptToEndOfLine)\n        {\n            string code = keyword + Environment.NewLine\n                        + \"    \" + keyword + Environment.NewLine\n                        + \"        Bar(foo)\" + Environment.NewLine\n                        + \"    \" + endSequence + Environment.NewLine\n                        + endSequence + (acceptToEndOfLine ? \" foo bar baz\" : \"\") + Environment.NewLine;\n            ParseBlockTest(code + \"biz boz\",\n                new StatementBlock(\n                    Factory.Code(code).AsStatement().Accepts(GetAcceptedCharacters(acceptToEndOfLine))));\n        }\n\n        [Theory]\n        [InlineData(\"While True\", \"End While\", false)]\n        [InlineData(\"Do\", \"Loop\", true)]\n        [InlineData(\"If foo IsNot Nothing\", \"End If\", false)]\n        [InlineData(\"Select Case foo\", \"End Select\", false)]\n        [InlineData(\"For Each p in Products\", \"Next\", true)]\n        [InlineData(\"Try\", \"End Try\", false)]\n        [InlineData(\"With\", \"End With\", false)]\n        [InlineData(\"SyncLock\", \"End SyncLock\", false)]\n        [InlineData(\"Using\", \"End Using\", false)]\n        private void SimpleKeywordBlock(string keyword, string endSequence, bool acceptToEndOfLine)\n        {\n            string code = keyword + Environment.NewLine\n                        + \"    Bar(foo)\" + Environment.NewLine\n                        + endSequence + (acceptToEndOfLine ? \" foo bar baz\" : \"\") + Environment.NewLine;\n            ParseBlockTest(code + \"biz boz\",\n                new StatementBlock(\n                    Factory.Code(code).AsStatement().Accepts(GetAcceptedCharacters(acceptToEndOfLine))));\n        }\n\n        [Theory]\n        [InlineData(\"While True\", \"Exit While\", \"End While\", false)]\n        [InlineData(\"Do\", \"Exit Do\", \"Loop\", true)]\n        [InlineData(\"For Each p in Products\", \"Exit For\", \"Next\", true)]\n        [InlineData(\"While True\", \"Continue While\", \"End While\", false)]\n        [InlineData(\"Do\", \"Continue Do\", \"Loop\", true)]\n        [InlineData(\"For Each p in Products\", \"Continue For\", \"Next\", true)]\n        private void KeywordWithExitOrContinue(string startKeyword, string exitKeyword, string endKeyword, bool acceptToEndOfLine)\n        {\n            string code = startKeyword + Environment.NewLine\n                         + \"    ' This is before the exit\" + Environment.NewLine\n                         + \"    \" + exitKeyword + Environment.NewLine\n                         + \"    ' This is after the exit\" + Environment.NewLine\n                         + endKeyword + Environment.NewLine;\n            ParseBlockTest(code + \"foo bar baz\",\n                new StatementBlock(\n                    Factory.Code(code).AsStatement().Accepts(GetAcceptedCharacters(acceptToEndOfLine))));\n        }\n\n        private AcceptedCharacters GetAcceptedCharacters(bool acceptToEndOfLine)\n        {\n            return acceptToEndOfLine ?\n                AcceptedCharacters.WhiteSpace | AcceptedCharacters.NonWhiteSpace :\n                AcceptedCharacters.None;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/VB/VBContinueStatementTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Framework;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.VB\n{\n    // VB Continue Statement: http://msdn.microsoft.com/en-us/library/801hyx6f.aspx\n    public class VBContinueStatementTest : VBHtmlCodeParserTestBase\n    {\n        [Fact]\n        public void VB_Do_Statement_With_Continue()\n        {\n            ParseBlockTest(\"@Do While True\" + Environment.NewLine\n                         + \"    Continue Do\" + Environment.NewLine\n                         + \"Loop\" + Environment.NewLine\n                         + \"' Not in the block!\",\n                new StatementBlock(\n                    Factory.CodeTransition(SyntaxConstants.TransitionString)\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"Do While True\\r\\n    Continue Do\\r\\nLoop\\r\\n\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.AnyExceptNewline)));\n        }\n\n        [Fact]\n        public void VB_For_Statement_With_Continue()\n        {\n            ParseBlockTest(\"@For i = 1 To 12\" + Environment.NewLine\n                         + \"    Continue For\" + Environment.NewLine\n                         + \"Next i\" + Environment.NewLine\n                         + \"' Not in the block!\",\n                new StatementBlock(\n                    Factory.CodeTransition(SyntaxConstants.TransitionString)\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"For i = 1 To 12\\r\\n    Continue For\\r\\nNext i\\r\\n\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.AnyExceptNewline)));\n        }\n\n        [Fact]\n        public void VB_While_Statement_With_Continue()\n        {\n            ParseBlockTest(\"@While True\" + Environment.NewLine\n                         + \"    Continue While\" + Environment.NewLine\n                         + \"End While\" + Environment.NewLine\n                         + \"' Not in the block!\",\n                new StatementBlock(\n                    Factory.CodeTransition(SyntaxConstants.TransitionString)\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"While True\\r\\n    Continue While\\r\\nEnd While\\r\\n\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.None)));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/VB/VBDirectiveTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.VB\n{\n    public class VBDirectiveTest : VBHtmlCodeParserTestBase\n    {\n        [Fact]\n        public void VB_Code_Directive()\n        {\n            ParseBlockTest(\"@Code\" + Environment.NewLine\n                         + \"    foo()\" + Environment.NewLine\n                         + \"End Code\" + Environment.NewLine\n                         + \"' Not part of the block\",\n                new StatementBlock(\n                    Factory.CodeTransition(SyntaxConstants.TransitionString)\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.MetaCode(\"Code\")\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"\\r\\n    foo()\\r\\n\")\n                           .AsStatement()\n                           .With(new AutoCompleteEditHandler(VBLanguageCharacteristics.Instance.TokenizeString)),\n                    Factory.MetaCode(\"End Code\")\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void VB_Functions_Directive()\n        {\n            ParseBlockTest(\"@Functions\" + Environment.NewLine\n                         + \"    Public Function Foo() As String\" + Environment.NewLine\n                         + \"        Return \\\"Foo\\\"\" + Environment.NewLine\n                         + \"    End Function\" + Environment.NewLine\n                         + Environment.NewLine\n                         + \"    Public Sub Bar()\" + Environment.NewLine\n                         + \"    End Sub\" + Environment.NewLine\n                         + \"End Functions\" + Environment.NewLine\n                         + \"' Not part of the block\",\n                new FunctionsBlock(\n                    Factory.CodeTransition(SyntaxConstants.TransitionString)\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.MetaCode(\"Functions\")\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"\\r\\n    Public Function Foo() As String\\r\\n        Return \\\"Foo\\\"\\r\\n    End Function\\r\\n\\r\\n    Public Sub Bar()\\r\\n    End Sub\\r\\n\")\n                           .AsFunctionsBody(),\n                    Factory.MetaCode(\"End Functions\")\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void VB_Section_Directive()\n        {\n            ParseBlockTest(\"@Section Header\" + Environment.NewLine\n                         + \"    <p>Foo</p>\" + Environment.NewLine\n                         + \"End Section\",\n                new SectionBlock(new SectionCodeGenerator(\"Header\"),\n                    Factory.CodeTransition(SyntaxConstants.TransitionString),\n                    Factory.MetaCode(\"Section Header\"),\n                    new MarkupBlock(\n                        Factory.Markup(\"\\r\\n    <p>Foo</p>\\r\\n\")),\n                    Factory.MetaCode(\"End Section\")\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void SessionStateDirectiveWorks()\n        {\n            ParseBlockTest(\"@SessionState InProc\" + Environment.NewLine,\n                new DirectiveBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"SessionState \")\n                        .Accepts(AcceptedCharacters.None),\n                    Factory.MetaCode(\"InProc\\r\\n\")\n                        .Accepts(AcceptedCharacters.None)\n                        .With(new RazorDirectiveAttributeCodeGenerator(\"SessionState\", \"InProc\"))\n                )\n            );\n        }\n\n        [Fact]\n        public void SessionStateDirectiveIsCaseInsensitive()\n        {\n            ParseBlockTest(\"@sessionstate disabled\" + Environment.NewLine,\n                new DirectiveBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"sessionstate \")\n                        .Accepts(AcceptedCharacters.None),\n                    Factory.MetaCode(\"disabled\\r\\n\")\n                        .Accepts(AcceptedCharacters.None)\n                        .With(new RazorDirectiveAttributeCodeGenerator(\"SessionState\", \"disabled\"))\n                )\n            );\n        }\n\n        [Fact]\n        public void VB_Helper_Directive()\n        {\n            ParseBlockTest(\"@Helper Strong(s as String)\" + Environment.NewLine\n                         + \"    s = s.ToUpperCase()\" + Environment.NewLine\n                         + \"    @<strong>s</strong>\" + Environment.NewLine\n                         + \"End Helper\",\n                new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"Strong(s as String)\", 8, 0, 8), headerComplete: true),\n                    Factory.CodeTransition(SyntaxConstants.TransitionString),\n                    Factory.MetaCode(\"Helper \")\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"Strong(s as String)\").Hidden(),\n                    new StatementBlock(\n                        Factory.Code(\"\\r\\n    s = s.ToUpperCase()\\r\\n\")\n                               .AsStatement(),\n                        new MarkupBlock(\n                            Factory.Markup(\"    \"),\n                            Factory.MarkupTransition(SyntaxConstants.TransitionString),\n                            Factory.Markup(\"<strong>s</strong>\\r\\n\")\n                                   .Accepts(AcceptedCharacters.None)),\n                        Factory.EmptyVB()\n                               .AsStatement(),\n                        Factory.MetaCode(\"End Helper\")\n                               .Accepts(AcceptedCharacters.None))));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/VB/VBErrorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Editor;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.VB\n{\n    public class VBErrorTest : VBHtmlCodeParserTestBase\n    {\n        [Fact]\n        public void ParserOutputsErrorAndRecoversToEndOfLineIfExplicitExpressionUnterminated()\n        {\n            ParseBlockTest(@\"(foo\nbar\",\n                new ExpressionBlock(\n                    Factory.MetaCode(\"(\").Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"foo\").AsExpression()),\n                new RazorError(\n                    String.Format(\n                        RazorResources.ParseError_Expected_EndOfBlock_Before_EOF,\n                        RazorResources.BlockName_ExplicitExpression,\n                        \")\", \"(\"),\n                    SourceLocation.Zero));\n        }\n\n        [Fact]\n        public void ParserOutputsZeroLengthCodeSpanIfEofReachedAfterStartOfExplicitExpression()\n        {\n            ParseBlockTest(\"(\",\n                new ExpressionBlock(\n                    Factory.MetaCode(\"(\").Accepts(AcceptedCharacters.None),\n                    Factory.EmptyVB().AsExpression()),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_Expected_EndOfBlock_Before_EOF, \"explicit expression\", \")\", \"(\"),\n                    SourceLocation.Zero));\n        }\n\n        [Fact]\n        public void ParserOutputsZeroLengthCodeSpanIfEofReachedAfterAtSign()\n        {\n            ParseBlockTest(String.Empty,\n                new ExpressionBlock(\n                    Factory.EmptyVB().AsImplicitExpression(KeywordSet).Accepts(AcceptedCharacters.NonWhiteSpace)),\n                new RazorError(\n                    RazorResources.ParseError_Unexpected_EndOfFile_At_Start_Of_CodeBlock,\n                    SourceLocation.Zero));\n        }\n\n        [Fact]\n        public void ParserOutputsZeroLengthCodeSpanIfOnlyWhitespaceFoundAfterAtSign()\n        {\n            ParseBlockTest(\" \",\n                new ExpressionBlock(\n                    Factory.EmptyVB().AsImplicitExpression(KeywordSet).Accepts(AcceptedCharacters.NonWhiteSpace)),\n                new RazorError(\n                    RazorResources.ParseError_Unexpected_WhiteSpace_At_Start_Of_CodeBlock_VB,\n                    SourceLocation.Zero));\n        }\n\n        [Fact]\n        public void ParserOutputsZeroLengthCodeSpanIfInvalidCharacterFoundAfterAtSign()\n        {\n            ParseBlockTest(\"!!!\",\n                new ExpressionBlock(\n                    Factory.EmptyVB().AsImplicitExpression(KeywordSet).Accepts(AcceptedCharacters.NonWhiteSpace)),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_Unexpected_Character_At_Start_Of_CodeBlock_VB, \"!\"),\n                    SourceLocation.Zero));\n        }\n\n        [Theory]\n        [InlineData(\"Code\", \"End Code\", true, true)]\n        [InlineData(\"Do\", \"Loop\", false, false)]\n        [InlineData(\"While\", \"End While\", false, false)]\n        [InlineData(\"If\", \"End If\", false, false)]\n        [InlineData(\"Select Case\", \"End Select\", false, false)]\n        [InlineData(\"For\", \"Next\", false, false)]\n        [InlineData(\"Try\", \"End Try\", false, false)]\n        [InlineData(\"With\", \"End With\", false, false)]\n        [InlineData(\"Using\", \"End Using\", false, false)]\n        public void EofBlock(string keyword, string expectedTerminator, bool autoComplete, bool keywordIsMetaCode)\n        {\n            EofBlockCore(keyword, expectedTerminator, autoComplete, BlockType.Statement, keywordIsMetaCode, c => c.AsStatement());\n        }\n\n        [Fact]\n        public void EofFunctionsBlock()\n        {\n            EofBlockCore(\"Functions\", \"End Functions\", true, BlockType.Functions, true, c => c.AsFunctionsBody());\n        }\n\n        private void EofBlockCore(string keyword, string expectedTerminator, bool autoComplete, BlockType blockType, bool keywordIsMetaCode, Func<UnclassifiedCodeSpanConstructor, SpanConstructor> classifier)\n        {\n            BlockBuilder expected = new BlockBuilder();\n            expected.Type = blockType;\n            if (keywordIsMetaCode)\n            {\n                expected.Children.Add(Factory.MetaCode(keyword).Accepts(AcceptedCharacters.None));\n                expected.Children.Add(\n                classifier(Factory.EmptyVB())\n                       .With((SpanEditHandler)(\n                            autoComplete ?\n                                new AutoCompleteEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString) { AutoCompleteString = expectedTerminator } :\n                                SpanEditHandler.CreateDefault())));\n            }\n            else\n            {\n                expected.Children.Add(\n                    classifier(Factory.Code(keyword))\n                           .With((SpanEditHandler)(\n                                autoComplete ?\n                                    new AutoCompleteEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString) { AutoCompleteString = expectedTerminator } :\n                                    SpanEditHandler.CreateDefault())));\n            }\n\n            ParseBlockTest(keyword,\n                expected.Build(),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_BlockNotTerminated, keyword, expectedTerminator),\n                    SourceLocation.Zero));\n        }\n\n        [Theory]\n        [InlineData(\"Code\", \"End Code\", true)]\n        [InlineData(\"Do\", \"Loop\", false)]\n        [InlineData(\"While\", \"End While\", false)]\n        [InlineData(\"If\", \"End If\", false)]\n        [InlineData(\"Select Case\", \"End Select\", false)]\n        [InlineData(\"For\", \"Next\", false)]\n        [InlineData(\"Try\", \"End Try\", false)]\n        [InlineData(\"With\", \"End With\", false)]\n        [InlineData(\"Using\", \"End Using\", false)]\n        public void UnterminatedBlock(string keyword, string expectedTerminator, bool keywordIsMetaCode)\n        {\n            UnterminatedBlockCore(keyword, expectedTerminator, BlockType.Statement, keywordIsMetaCode, c => c.AsStatement());\n        }\n\n        [Fact]\n        public void UnterminatedFunctionsBlock()\n        {\n            UnterminatedBlockCore(\"Functions\", \"End Functions\", BlockType.Functions, true, c => c.AsFunctionsBody());\n        }\n\n        private void UnterminatedBlockCore(string keyword, string expectedTerminator, BlockType blockType, bool keywordIsMetaCode, Func<UnclassifiedCodeSpanConstructor, SpanConstructor> classifier)\n        {\n            const string blockBody = @\"\n    ' This block is not correctly terminated!\";\n\n            BlockBuilder expected = new BlockBuilder();\n            expected.Type = blockType;\n            if (keywordIsMetaCode)\n            {\n                expected.Children.Add(Factory.MetaCode(keyword).Accepts(AcceptedCharacters.None));\n                expected.Children.Add(classifier(Factory.Code(blockBody)));\n            }\n            else\n            {\n                expected.Children.Add(classifier(Factory.Code(keyword + blockBody)));\n            }\n\n            ParseBlockTest(keyword + blockBody,\n                expected.Build(),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_BlockNotTerminated, keyword, expectedTerminator),\n                    SourceLocation.Zero));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/VB/VBExitStatementTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Framework;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.VB\n{\n    // VB Exit Statement: http://msdn.microsoft.com/en-us/library/t2at9t47.aspx\n    public class VBExitStatementTest : VBHtmlCodeParserTestBase\n    {\n        [Fact]\n        public void VB_Do_Statement_With_Exit()\n        {\n            ParseBlockTest(\"@Do While True\" + Environment.NewLine\n                         + \"    Exit Do\" + Environment.NewLine\n                         + \"Loop\" + Environment.NewLine\n                         + \"' Not in the block!\",\n                new StatementBlock(\n                    Factory.CodeTransition(SyntaxConstants.TransitionString)\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"Do While True\\r\\n    Exit Do\\r\\nLoop\\r\\n\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.AnyExceptNewline)));\n        }\n\n        [Fact]\n        public void VB_For_Statement_With_Exit()\n        {\n            ParseBlockTest(\"@For i = 1 To 12\" + Environment.NewLine\n                         + \"    Exit For\" + Environment.NewLine\n                         + \"Next i\" + Environment.NewLine\n                         + \"' Not in the block!\",\n                new StatementBlock(\n                    Factory.CodeTransition(SyntaxConstants.TransitionString)\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"For i = 1 To 12\\r\\n    Exit For\\r\\nNext i\\r\\n\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.AnyExceptNewline)));\n        }\n\n        [Fact]\n        public void VB_Select_Statement_With_Exit()\n        {\n            ParseBlockTest(\"@Select Case Foo\" + Environment.NewLine\n                         + \"    Case 1\" + Environment.NewLine\n                         + \"        Exit Select\" + Environment.NewLine\n                         + \"    Case 2\" + Environment.NewLine\n                         + \"        Exit Select\" + Environment.NewLine\n                         + \"End Select\" + Environment.NewLine\n                         + \"' Not in the block!\",\n                new StatementBlock(\n                    Factory.CodeTransition(SyntaxConstants.TransitionString)\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"Select Case Foo\\r\\n    Case 1\\r\\n        Exit Select\\r\\n    Case 2\\r\\n        Exit Select\\r\\nEnd Select\\r\\n\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void VB_Try_Statement_With_Exit()\n        {\n            ParseBlockTest(\"@Try\" + Environment.NewLine\n                         + \"    Foo()\" + Environment.NewLine\n                         + \"    Exit Try\" + Environment.NewLine\n                         + \"Catch Bar\" + Environment.NewLine\n                         + \"    Throw Bar\" + Environment.NewLine\n                         + \"Finally\" + Environment.NewLine\n                         + \"    Baz()\" + Environment.NewLine\n                         + \"End Try\" + Environment.NewLine\n                         + \"' Not in the block!\",\n                new StatementBlock(\n                    Factory.CodeTransition(SyntaxConstants.TransitionString)\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"Try\\r\\n    Foo()\\r\\n    Exit Try\\r\\nCatch Bar\\r\\n    Throw Bar\\r\\nFinally\\r\\n    Baz()\\r\\nEnd Try\\r\\n\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void VB_While_Statement_With_Exit()\n        {\n            ParseBlockTest(\"@While True\" + Environment.NewLine\n                         + \"    Exit While\" + Environment.NewLine\n                         + \"End While\" + Environment.NewLine\n                         + \"' Not in the block!\",\n                new StatementBlock(\n                    Factory.CodeTransition(SyntaxConstants.TransitionString)\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"While True\\r\\n    Exit While\\r\\nEnd While\\r\\n\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.None)));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/VB/VBExplicitExpressionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Framework;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.VB\n{\n    public class VBExplicitExpressionTest : VBHtmlCodeParserTestBase\n    {\n        [Fact]\n        public void VB_Simple_ExplicitExpression()\n        {\n            ParseBlockTest(\"@(foo)\",\n                new ExpressionBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"(\").Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"foo\").AsExpression(),\n                    Factory.MetaCode(\")\").Accepts(AcceptedCharacters.None)));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/VB/VBExpressionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.VB\n{\n    public class VBExpressionTest : VBHtmlCodeParserTestBase\n    {\n        [Fact]\n        public void ParseBlockCorrectlyHandlesCodeBlockInBodyOfExplicitExpressionDueToUnclosedExpression()\n        {\n            ParseBlockTest(@\"(\n@Code\n    Dim foo = bar\nEnd Code\",\n                new ExpressionBlock(\n                    Factory.MetaCode(\"(\").Accepts(AcceptedCharacters.None),\n                    Factory.EmptyVB().AsExpression()),\n                new RazorError(\n                    String.Format(\n                        RazorResources.ParseError_Expected_EndOfBlock_Before_EOF,\n                        RazorResources.BlockName_ExplicitExpression,\n                        \")\", \"(\"),\n                     SourceLocation.Zero));\n        }\n\n        [Fact]\n        public void ParseBlockAcceptsNonEnglishCharactersThatAreValidIdentifiers()\n        {\n            ImplicitExpressionTest(\"हळूँजद॔.\", \"हळूँजद॔\");\n        }\n\n        [Fact]\n        public void ParseBlockDoesNotTreatXmlAxisPropertyAsTransitionToMarkup()\n        {\n            SingleSpanBlockTest(\n                @\"If foo Is Nothing Then\n    Dim bar As XElement\n    Dim foo = bar.<foo>\nEnd If\",\n                BlockType.Statement,\n                SpanKind.Code,\n                acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockDoesNotTreatXmlAttributePropertyAsTransitionToMarkup()\n        {\n            SingleSpanBlockTest(\n                @\"If foo Is Nothing Then\n    Dim bar As XElement\n    Dim foo = bar.@foo\nEnd If\",\n                BlockType.Statement,\n                SpanKind.Code,\n                acceptedCharacters: AcceptedCharacters.None);\n        }\n\n        [Fact]\n        public void ParseBlockSupportsSimpleImplicitExpression()\n        {\n            ImplicitExpressionTest(\"Foo\");\n        }\n\n        [Fact]\n        public void ParseBlockSupportsImplicitExpressionWithDots()\n        {\n            ImplicitExpressionTest(\"Foo.Bar.Baz\");\n        }\n\n        [Fact]\n        public void ParseBlockSupportsImplicitExpressionWithParens()\n        {\n            ImplicitExpressionTest(\"Foo().Bar().Baz()\");\n        }\n\n        [Fact]\n        public void ParseBlockSupportsImplicitExpressionWithStuffInParens()\n        {\n            ImplicitExpressionTest(\"Foo().Bar(sdfkhj sdfksdfjs \\\")\\\" sjdfkjsdf).Baz()\");\n        }\n\n        [Fact]\n        public void ParseBlockSupportsImplicitExpressionWithCommentInParens()\n        {\n            ImplicitExpressionTest(\"Foo().Bar(sdfkhj sdfksdfjs \\\")\\\" '))))))))\\r\\nsjdfkjsdf).Baz()\");\n        }\n\n        [Theory]\n        [InlineData(\"Foo\")]\n        [InlineData(\"Foo(Of String).Bar(1, 2, 3).Biz\")]\n        [InlineData(\"Foo(Of String).Bar(\\\")\\\").Biz\")]\n        [InlineData(\"Foo(Of String).Bar(\\\"Foo\\\"\\\"Bar)\\\"\\\"Baz\\\").Biz\")]\n        [InlineData(\"\\\"foo\\r\\nbar\")]\n        [InlineData(\"Foo.Bar. _\\r\\nREM )\\r\\nBaz()\\r\\n\")]\n        [InlineData(\"Foo.Bar. _\\r\\n' )\\r\\nBaz()\\r\\n\")]\n        public void ValidExplicitExpressions(string body)\n        {\n            ParseBlockTest(\"(\" + body + \")\",\n                new ExpressionBlock(\n                    Factory.MetaCode(\"(\").Accepts(AcceptedCharacters.None),\n                    Factory.Code(body).AsExpression(),\n                    Factory.MetaCode(\")\").Accepts(AcceptedCharacters.None)));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/VB/VBExpressionsInCodeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.VB\n{\n    public class VBExpressionsInCodeTest : VBHtmlCodeParserTestBase\n    {\n        [Fact]\n        public void InnerImplicitExpressionWithOnlySingleAtAcceptsSingleSpaceOrNewlineAtDesignTime()\n        {\n            ParseBlockTest(\"Code\" + Environment.NewLine\n                         + \"    @\" + Environment.NewLine\n                         + \"End Code\",\n                new StatementBlock(\n                    Factory.MetaCode(\"Code\").Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"\\r\\n    \").AsStatement(),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.EmptyVB()\n                               .AsImplicitExpression(VBCodeParser.DefaultKeywords, acceptTrailingDot: true)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    Factory.Code(\"\\r\\n\").AsStatement(),\n                    Factory.MetaCode(\"End Code\").Accepts(AcceptedCharacters.None)),\n                designTimeParser: true,\n                expectedErrors: new[]\n                {\n                    new RazorError(RazorResources.ParseError_Unexpected_WhiteSpace_At_Start_Of_CodeBlock_VB, 11, 1, 5)\n                });\n        }\n\n        [Fact]\n        public void InnerImplicitExpressionDoesNotAcceptDotAfterAt()\n        {\n            ParseBlockTest(\"Code\" + Environment.NewLine\n                         + \"    @.\" + Environment.NewLine\n                         + \"End Code\",\n                new StatementBlock(\n                    Factory.MetaCode(\"Code\").Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"\\r\\n    \").AsStatement(),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.EmptyVB()\n                               .AsImplicitExpression(VBCodeParser.DefaultKeywords, acceptTrailingDot: true)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    Factory.Code(\".\\r\\n\").AsStatement(),\n                    Factory.MetaCode(\"End Code\").Accepts(AcceptedCharacters.None)),\n                designTimeParser: true,\n                expectedErrors: new[]\n                {\n                    new RazorError(\n                        String.Format(RazorResources.ParseError_Unexpected_Character_At_Start_Of_CodeBlock_VB, \".\"), \n                        11, 1, 5)\n                });\n        }\n\n        [Theory]\n        [InlineData(\"Foo.Bar.\", true)]\n        [InlineData(\"Foo\", true)]\n        [InlineData(\"Foo.Bar.Baz\", true)]\n        [InlineData(\"Foo().Bar().Baz()\", true)]\n        [InlineData(\"Foo().Bar(sdfkhj sdfksdfjs \\\")\\\" sjdfkjsdf).Baz()\", true)]\n        [InlineData(\"Foo().Bar(sdfkhj sdfksdfjs \\\")\\\" '))))))))\\r\\nsjdfkjsdf).Baz()\", true)]\n        [InlineData(\"Foo\", false)]\n        [InlineData(\"Foo(Of String).Bar(1, 2, 3).Biz\", false)]\n        [InlineData(\"Foo(Of String).Bar(\\\")\\\").Biz\", false)]\n        [InlineData(\"Foo(Of String).Bar(\\\"Foo\\\"\\\"Bar)\\\"\\\"Baz\\\").Biz\", false)]\n        [InlineData(\"Foo.Bar. _\\r\\nREM )\\r\\nBaz()\\r\\n\", false)]\n        [InlineData(\"Foo.Bar. _\\r\\n' )\\r\\nBaz()\\r\\n\", false)]\n        public void ExpressionInCode(string expression, bool isImplicit)\n        {\n            ExpressionBlock expressionBlock;\n            if (isImplicit)\n            {\n                expressionBlock =\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(expression)\n                               .AsImplicitExpression(VBCodeParser.DefaultKeywords, acceptTrailingDot: true)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace));\n            }\n            else\n            {\n                expressionBlock =\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"(\").Accepts(AcceptedCharacters.None),\n                        Factory.Code(expression).AsExpression(),\n                        Factory.MetaCode(\")\").Accepts(AcceptedCharacters.None));\n            }\n\n            string code;\n            if (isImplicit)\n            {\n                code = \"If foo IsNot Nothing Then\" + Environment.NewLine\n                     + \"    @\" + expression + Environment.NewLine\n                     + \"End If\";\n            }\n            else\n            {\n                code = \"If foo IsNot Nothing Then\" + Environment.NewLine\n                     + \"    @(\" + expression + \")\" + Environment.NewLine\n                     + \"End If\";\n            }\n\n            ParseBlockTest(code,\n                new StatementBlock(\n                    Factory.Code(\"If foo IsNot Nothing Then\\r\\n    \")\n                           .AsStatement(),\n                    expressionBlock,\n                    Factory.Code(\"\\r\\nEnd If\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.None)));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/VB/VBHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.VB\n{\n    public class VBHelperTest : VBHtmlMarkupParserTestBase\n    {\n        [Fact]\n        public void ParseHelperOutputsErrorButContinuesIfLParenFoundAfterHelperKeyword()\n        {\n            ParseDocumentTest(\"@Helper ()\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"()\", 8, 0, 8), headerComplete: true),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Helper \").Accepts(AcceptedCharacters.None),\n                        Factory.Code(\"()\").Hidden().AutoCompleteWith(SyntaxConstants.VB.EndHelperKeyword),\n                        new StatementBlock())),\n                new RazorError(\n                    String.Format(\n                        RazorResources.ParseError_Unexpected_Character_At_Helper_Name_Start,\n                        String.Format(RazorResources.ErrorComponent_Character, \"(\")),\n                    8, 0, 8),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_BlockNotTerminated, \"Helper\", \"End Helper\"),\n                    1, 0, 1));\n        }\n\n        [Fact]\n        public void ParseHelperStatementOutputsMarkerHelperHeaderSpanOnceKeywordComplete()\n        {\n            ParseDocumentTest(\"@Helper \",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(String.Empty, 8, 0, 8), headerComplete: false),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Helper \").Accepts(AcceptedCharacters.None),\n                        Factory.EmptyVB().Hidden())),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_Unexpected_Character_At_Helper_Name_Start, RazorResources.ErrorComponent_EndOfFile),\n                    8, 0, 8));\n        }\n\n        [Fact]\n        public void ParseHelperStatementMarksHelperSpanAsCanGrowIfMissingTrailingSpace()\n        {\n            ParseDocumentTest(\"@Helper\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Helper\"))),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_Unexpected_Character_At_Helper_Name_Start, RazorResources.ErrorComponent_EndOfFile),\n                    7, 0, 7));\n        }\n\n        [Fact]\n        public void ParseHelperStatementTerminatesEarlyIfHeaderNotComplete()\n        {\n            ParseDocumentTest(\"@Helper\" + Environment.NewLine\n                            + \"@Helper\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Helper\\r\\n\").Accepts(AcceptedCharacters.None),\n                        Factory.EmptyVB().Hidden()),\n                    new HelperBlock(\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Helper\"))),\n                designTimeParser: true,\n                expectedErrors: new[]\n                {\n                    new RazorError(\n                        String.Format(\n                            RazorResources.ParseError_Unexpected_Character_At_Helper_Name_Start, \n                            String.Format(RazorResources.ErrorComponent_Character, \"@\")),\n                        9, 1, 0),\n                    new RazorError(\n                        String.Format(\n                            RazorResources.ParseError_Unexpected_Character_At_Helper_Name_Start, \n                            RazorResources.ErrorComponent_EndOfFile),\n                        16, 1, 7)\n                });\n        }\n\n        [Fact]\n        public void ParseHelperStatementTerminatesEarlyIfHeaderNotCompleteWithSpace()\n        {\n            ParseDocumentTest(@\"@Helper @Helper\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(String.Empty, 8, 0, 8), headerComplete: false),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(@\"Helper \").Accepts(AcceptedCharacters.None),\n                        Factory.EmptyVB().Hidden()),\n                    new HelperBlock(\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Helper\").Accepts(AcceptedCharacters.Any))),\n                designTimeParser: true,\n                expectedErrors: new[]\n                {\n                    new RazorError(\n                        String.Format(\n                            RazorResources.ParseError_Unexpected_Character_At_Helper_Name_Start,\n                            String.Format(RazorResources.ErrorComponent_Character, \"@\")),\n                        8, 0, 8),\n                    new RazorError(\n                        String.Format(\n                            RazorResources.ParseError_Unexpected_Character_At_Helper_Name_Start, \n                            RazorResources.ErrorComponent_EndOfFile),\n                        15, 0, 15)\n                });\n        }\n\n        [Fact]\n        public void ParseHelperStatementAllowsDifferentlyCasedEndHelperKeyword()\n        {\n            ParseDocumentTest(\"@Helper Foo()\" + Environment.NewLine\n                            + \"end helper\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"Foo()\", 8, 0, 8), headerComplete: true),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Helper \").Accepts(AcceptedCharacters.None),\n                        Factory.Code(\"Foo()\").Hidden(),\n                        new StatementBlock(\n                            Factory.Code(\"\\r\\n\").AsStatement(),\n                            Factory.MetaCode(\"end helper\").Accepts(AcceptedCharacters.None))),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void ParseHelperStatementCapturesWhitespaceToEndOfLineIfHelperStatementMissingName()\n        {\n            ParseDocumentTest(\"@Helper                       \" + Environment.NewLine\n                            + \"    \",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"                      \", 8, 0, 8), headerComplete: false),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Helper \").Accepts(AcceptedCharacters.None),\n                        Factory.Code(\"                      \").Hidden()),\n                    Factory.Markup(\"\\r\\n    \")),\n                new RazorError(\n                    String.Format(\n                        RazorResources.ParseError_Unexpected_Character_At_Helper_Name_Start,\n                        RazorResources.ErrorComponent_Newline),\n                    30, 0, 30));\n        }\n\n        [Fact]\n        public void ParseHelperStatementCapturesWhitespaceToEndOfLineIfHelperStatementMissingOpenParen()\n        {\n            ParseDocumentTest(\"@Helper Foo    \" + Environment.NewLine\n                            + \"    \",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"Foo    \", 8, 0, 8), headerComplete: false),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Helper \").Accepts(AcceptedCharacters.None),\n                        Factory.Code(\"Foo    \").Hidden()),\n                    Factory.Markup(\"\\r\\n    \")),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_MissingCharAfterHelperName, \"(\"),\n                    15, 0, 15));\n        }\n\n        [Fact]\n        public void ParseHelperStatementCapturesAllContentToEndOfFileIfHelperStatementMissingCloseParenInParameterList()\n        {\n            ParseDocumentTest(\"@Helper Foo(Foo Bar\" + Environment.NewLine\n                            + \"Biz\" + Environment.NewLine\n                            + \"Boz\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"Foo(Foo Bar\\r\\nBiz\\r\\nBoz\", 8, 0, 8), headerComplete: false),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Helper \").Accepts(AcceptedCharacters.None),\n                        Factory.Code(\"Foo(Foo Bar\\r\\nBiz\\r\\nBoz\").Hidden())),\n                new RazorError(RazorResources.ParseError_UnterminatedHelperParameterList, 11, 0, 11));\n        }\n\n        [Fact]\n        public void ParseHelperStatementCapturesWhitespaceToEndOfLineIfHelperStatementMissingOpenBraceAfterParameterList()\n        {\n            ParseDocumentTest(\"@Helper Foo(foo as String)    \" + Environment.NewLine,\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"Foo(foo as String)\", 8, 0, 8), headerComplete: true),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Helper \").Accepts(AcceptedCharacters.None),\n                        Factory.Code(\"Foo(foo as String)\")\n                               .Hidden()\n                               .AutoCompleteWith(SyntaxConstants.VB.EndHelperKeyword),\n                        new StatementBlock(\n                            Factory.Code(\"    \\r\\n\").AsStatement()))),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_BlockNotTerminated, \"Helper\", \"End Helper\"),\n                    1, 0, 1));\n        }\n\n        [Fact]\n        public void ParseHelperStatementContinuesParsingHelperUntilEOF()\n        {\n            ParseDocumentTest(\"@Helper Foo(foo as String)\" + Environment.NewLine\n                            + \"    @<p>Foo</p>\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"Foo(foo as String)\", 8, 0, 8), headerComplete: true),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Helper \").Accepts(AcceptedCharacters.None),\n                        Factory.Code(\"Foo(foo as String)\")\n                               .Hidden()\n                               .AutoCompleteWith(SyntaxConstants.VB.EndHelperKeyword),\n                        new StatementBlock(\n                            Factory.Code(\"\\r\\n\").AsStatement(),\n                            new MarkupBlock(\n                                Factory.Markup(\"    \"),\n                                Factory.MarkupTransition(),\n                                Factory.Markup(\"<p>Foo</p>\").Accepts(AcceptedCharacters.None)),\n                            Factory.EmptyVB().AsStatement()))),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_BlockNotTerminated, \"Helper\", \"End Helper\"),\n                    1, 0, 1));\n        }\n\n        [Fact]\n        public void ParseHelperStatementCorrectlyParsesHelperWithEmbeddedCode()\n        {\n            ParseDocumentTest(\"@Helper Foo(foo as String, bar as String)\" + Environment.NewLine\n                            + \"    @<p>@foo</p>\" + Environment.NewLine\n                            + \"End Helper\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"Foo(foo as String, bar as String)\", 8, 0, 8), headerComplete: true),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Helper \").Accepts(AcceptedCharacters.None),\n                        Factory.Code(\"Foo(foo as String, bar as String)\").Hidden(),\n                        new StatementBlock(\n                            Factory.Code(\"\\r\\n\").AsStatement(),\n                            new MarkupBlock(\n                                Factory.Markup(\"    \"),\n                                Factory.MarkupTransition(),\n                                Factory.Markup(\"<p>\"),\n                                new ExpressionBlock(\n                                    Factory.CodeTransition(),\n                                    Factory.Code(\"foo\")\n                                           .AsImplicitExpression(VBCodeParser.DefaultKeywords)\n                                           .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                                Factory.Markup(\"</p>\\r\\n\").Accepts(AcceptedCharacters.None)),\n                            Factory.EmptyVB().AsStatement(),\n                            Factory.MetaCode(\"End Helper\").Accepts(AcceptedCharacters.None))),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void ParseHelperStatementGivesWhitespaceAfterCloseParenToMarkup()\n        {\n            ParseDocumentTest(\"@Helper Foo(string foo)     \" + Environment.NewLine\n                            + \"    \",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"Foo(string foo)\", 8, 0, 8), headerComplete: true),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Helper \").Accepts(AcceptedCharacters.None),\n                        Factory.Code(\"Foo(string foo)\")\n                               .Hidden()\n                               .AutoCompleteWith(SyntaxConstants.VB.EndHelperKeyword),\n                        new StatementBlock(\n                            Factory.Code(\"     \\r\\n    \").AsStatement()))),\n                designTimeParser: true,\n                expectedErrors:\n                    new RazorError(\n                        String.Format(\n                            RazorResources.ParseError_BlockNotTerminated,\n                            \"Helper\", \"End Helper\"),\n                        1, 0, 1));\n        }\n\n        [Fact]\n        public void ParseHelperAcceptsNestedHelpersButOutputsError()\n        {\n            ParseDocumentTest(\"@Helper Foo(string foo)\" + Environment.NewLine\n                            + \"    @Helper Bar(string baz)\" + Environment.NewLine\n                            + \"    End Helper\" + Environment.NewLine\n                            + \"End Helper\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"Foo(string foo)\", 8, 0, 8), headerComplete: true),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Helper \").Accepts(AcceptedCharacters.None),\n                        Factory.Code(\"Foo(string foo)\").Hidden(),\n                        new StatementBlock(\n                            Factory.Code(\"\\r\\n    \").AsStatement(),\n                            new HelperBlock(new HelperCodeGenerator(new LocationTagged<string>(\"Bar(string baz)\", 37, 1, 12), headerComplete: true),\n                                Factory.CodeTransition(),\n                                Factory.MetaCode(\"Helper \").Accepts(AcceptedCharacters.None),\n                                Factory.Code(\"Bar(string baz)\").Hidden(),\n                                new StatementBlock(\n                                    Factory.Code(\"\\r\\n    \").AsStatement(),\n                                    Factory.MetaCode(\"End Helper\").Accepts(AcceptedCharacters.None))),\n                            Factory.Code(\"\\r\\n\").AsStatement(),\n                            Factory.MetaCode(\"End Helper\").Accepts(AcceptedCharacters.None))),\n                    Factory.EmptyHtml()),\n                designTimeParser: true,\n                expectedErrors: new[]\n                {\n                    new RazorError(\n                        RazorResources.ParseError_Helpers_Cannot_Be_Nested,\n                        30, 1, 5)\n                });\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/VB/VBHtmlDocumentTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.VB\n{\n    public class VBHtmlDocumentTest : VBHtmlMarkupParserTestBase\n    {\n        [Fact]\n        public void BlockCommentInMarkupDocumentIsHandledCorrectly()\n        {\n            ParseDocumentTest(@\"<ul>\" + Environment.NewLine\n                            + @\"                @* This is a block comment </ul> *@ foo\",\n                new MarkupBlock(\n                    Factory.Markup(\"<ul>\" + Environment.NewLine + \"                \"),\n                    new CommentBlock(\n                        Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition),\n                        Factory.MetaMarkup(\"*\", HtmlSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                        Factory.Comment(\" This is a block comment </ul> \", HtmlSymbolType.RazorComment),\n                        Factory.MetaMarkup(\"*\", HtmlSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                        Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition)),\n                    Factory.Markup(\" foo\")));\n        }\n\n        [Fact]\n        public void BlockCommentInMarkupBlockIsHandledCorrectly()\n        {\n            ParseBlockTest(@\"<ul>\" + Environment.NewLine\n                         + @\"                @* This is a block comment </ul> *@ foo </ul>\",\n                new MarkupBlock(\n                    Factory.Markup(\"<ul>\" + Environment.NewLine + \"                \"),\n                    new CommentBlock(\n                        Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition),\n                        Factory.MetaMarkup(\"*\", HtmlSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                        Factory.Comment(\" This is a block comment </ul> \", HtmlSymbolType.RazorComment),\n                        Factory.MetaMarkup(\"*\", HtmlSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                        Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition)),\n                    Factory.Markup(\" foo </ul>\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void BlockCommentAtStatementStartInCodeBlockIsHandledCorrectly()\n        {\n            ParseDocumentTest(@\"@If Request.IsAuthenticated Then\" + Environment.NewLine\n                            + @\"    @* User is logged in! End If *@\" + Environment.NewLine\n                            + @\"    Write(\"\"Hello friend!\"\")\" + Environment.NewLine\n                            + @\"End If\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new StatementBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"If Request.IsAuthenticated Then\" + Environment.NewLine + \"    \").AsStatement(),\n                        new CommentBlock(\n                            Factory.CodeTransition(VBSymbolType.RazorCommentTransition),\n                            Factory.MetaCode(\"*\", VBSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                            Factory.Comment(\" User is logged in! End If \", VBSymbolType.RazorComment),\n                            Factory.MetaCode(\"*\", VBSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                            Factory.CodeTransition(VBSymbolType.RazorCommentTransition)),\n                        Factory.Code(\"\" + Environment.NewLine + \"    Write(\\\"Hello friend!\\\")\" + Environment.NewLine + \"End If\")\n                               .AsStatement()\n                               .Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void BlockCommentInStatementInCodeBlockIsHandledCorrectly()\n        {\n            ParseDocumentTest(@\"@If Request.IsAuthenticated Then\" + Environment.NewLine\n                            + @\"    Dim foo = @* User is logged in! End If *@ bar\" + Environment.NewLine\n                            + @\"    Write(\"\"Hello friend!\"\")\" + Environment.NewLine\n                            + @\"End If\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new StatementBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"If Request.IsAuthenticated Then\" + Environment.NewLine + \"    Dim foo = \").AsStatement(),\n                        new CommentBlock(\n                            Factory.CodeTransition(VBSymbolType.RazorCommentTransition),\n                            Factory.MetaCode(\"*\", VBSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                            Factory.Comment(\" User is logged in! End If \", VBSymbolType.RazorComment),\n                            Factory.MetaCode(\"*\", VBSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                            Factory.CodeTransition(VBSymbolType.RazorCommentTransition)),\n                        Factory.Code(\" bar\" + Environment.NewLine + \"    Write(\\\"Hello friend!\\\")\" + Environment.NewLine + \"End If\")\n                               .AsStatement()\n                               .Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void BlockCommentInStringInCodeBlockIsIgnored()\n        {\n            ParseDocumentTest(@\"@If Request.IsAuthenticated Then\" + Environment.NewLine\n                            + @\"    Dim foo = \"\"@* User is logged in! End If *@ bar\"\"\" + Environment.NewLine\n                            + @\"    Write(\"\"Hello friend!\"\")\" + Environment.NewLine\n                            + @\"End If\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new StatementBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"If Request.IsAuthenticated Then\" + Environment.NewLine + \"    Dim foo = \\\"@* User is logged in! End If *@ bar\\\"\" + Environment.NewLine + \"    Write(\\\"Hello friend!\\\")\" + Environment.NewLine + \"End If\")\n                               .AsStatement()\n                               .Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void BlockCommentInTickCommentInCodeBlockIsIgnored()\n        {\n            ParseDocumentTest(@\"@If Request.IsAuthenticated Then\" + Environment.NewLine\n                            + @\"    Dim foo = '@* User is logged in! End If *@ bar\" + Environment.NewLine\n                            + @\"    Write(\"\"Hello friend!\"\")\" + Environment.NewLine\n                            + @\"End If\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new StatementBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"If Request.IsAuthenticated Then\" + Environment.NewLine + \"    Dim foo = '@* User is logged in! End If *@ bar\" + Environment.NewLine + \"    Write(\\\"Hello friend!\\\")\" + Environment.NewLine + \"End If\")\n                               .AsStatement()\n                               .Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void BlockCommentInRemCommentInCodeBlockIsIgnored()\n        {\n            ParseDocumentTest(@\"@If Request.IsAuthenticated Then\" + Environment.NewLine\n                            + @\"    Dim foo = REM @* User is logged in! End If *@ bar\" + Environment.NewLine\n                            + @\"    Write(\"\"Hello friend!\"\")\" + Environment.NewLine\n                            + @\"End If\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new StatementBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"If Request.IsAuthenticated Then\" + Environment.NewLine + \"    Dim foo = REM @* User is logged in! End If *@ bar\" + Environment.NewLine + \"    Write(\\\"Hello friend!\\\")\" + Environment.NewLine + \"End If\")\n                               .AsStatement()\n                               .Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void BlockCommentInImplicitExpressionIsHandledCorrectly()\n        {\n            ParseDocumentTest(\"@Html.Foo@*bar*@\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"Html.Foo\")\n                               .AsImplicitExpression(KeywordSet)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    Factory.EmptyHtml(),\n                    new CommentBlock(\n                        Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition),\n                        Factory.MetaMarkup(\"*\", HtmlSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                        Factory.Comment(\"bar\", HtmlSymbolType.RazorComment),\n                        Factory.MetaMarkup(\"*\", HtmlSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                        Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void BlockCommentAfterDotOfImplicitExpressionIsHandledCorrectly()\n        {\n            ParseDocumentTest(\"@Html.@*bar*@\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"Html\")\n                               .AsImplicitExpression(KeywordSet)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    Factory.Markup(\".\"),\n                    new CommentBlock(\n                        Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition),\n                        Factory.MetaMarkup(\"*\", HtmlSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                        Factory.Comment(\"bar\", HtmlSymbolType.RazorComment),\n                        Factory.MetaMarkup(\"*\", HtmlSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                        Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void BlockCommentInParensOfImplicitExpressionIsHandledCorrectly()\n        {\n            ParseDocumentTest(\"@Html.Foo(@*bar*@ 4)\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"Html.Foo(\")\n                               .AsImplicitExpression(KeywordSet)\n                               .Accepts(AcceptedCharacters.Any),\n                        new CommentBlock(\n                            Factory.CodeTransition(VBSymbolType.RazorCommentTransition),\n                            Factory.MetaCode(\"*\", VBSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                            Factory.Comment(\"bar\", VBSymbolType.RazorComment),\n                            Factory.MetaCode(\"*\", VBSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                            Factory.CodeTransition(VBSymbolType.RazorCommentTransition)),\n                        Factory.Code(\" 4)\")\n                               .AsImplicitExpression(KeywordSet)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void BlockCommentInConditionIsHandledCorrectly()\n        {\n            ParseDocumentTest(\"@If @*bar*@ Then End If\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new StatementBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"If \").AsStatement(),\n                        new CommentBlock(\n                            Factory.CodeTransition(VBSymbolType.RazorCommentTransition),\n                            Factory.MetaCode(\"*\", VBSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                            Factory.Comment(\"bar\", VBSymbolType.RazorComment),\n                            Factory.MetaCode(\"*\", VBSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                            Factory.CodeTransition(VBSymbolType.RazorCommentTransition)),\n                        Factory.Code(\" Then End If\").AsStatement().Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void BlockCommentInExplicitExpressionIsHandledCorrectly()\n        {\n            ParseDocumentTest(@\"@(1 + @*bar*@ 1)\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"(\").Accepts(AcceptedCharacters.None),\n                        Factory.Code(@\"1 + \").AsExpression(),\n                        new CommentBlock(\n                            Factory.CodeTransition(VBSymbolType.RazorCommentTransition),\n                            Factory.MetaCode(\"*\", VBSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                            Factory.Comment(\"bar\", VBSymbolType.RazorComment),\n                            Factory.MetaCode(\"*\", VBSymbolType.RazorCommentStar).Accepts(AcceptedCharacters.None),\n                            Factory.CodeTransition(VBSymbolType.RazorCommentTransition)\n                            ),\n                        Factory.Code(\" 1\").AsExpression(),\n                        Factory.MetaCode(\")\").Accepts(AcceptedCharacters.None)\n                        ),\n                    Factory.EmptyHtml()));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/VB/VBImplicitExpressionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Framework;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.VB\n{\n    public class VBImplicitExpressionTest : VBHtmlCodeParserTestBase\n    {\n        [Fact]\n        public void VB_Simple_ImplicitExpression()\n        {\n            ParseBlockTest(\"@foo not-part-of-the-block\",\n                new ExpressionBlock(\n                    Factory.CodeTransition(),\n                    Factory.Code(\"foo\")\n                           .AsImplicitExpression(VBCodeParser.DefaultKeywords)\n                           .Accepts(AcceptedCharacters.NonWhiteSpace)));\n        }\n\n        [Fact]\n        public void VB_ImplicitExpression_With_Keyword_At_Start()\n        {\n            ParseBlockTest(\"@Partial\",\n                new ExpressionBlock(\n                    Factory.CodeTransition(),\n                    Factory.Code(\"Partial\")\n                           .AsImplicitExpression(VBCodeParser.DefaultKeywords)\n                           .Accepts(AcceptedCharacters.NonWhiteSpace)));\n        }\n\n        [Fact]\n        public void VB_ImplicitExpression_With_Keyword_In_Body()\n        {\n            ParseBlockTest(\"@Html.Partial\",\n                new ExpressionBlock(\n                    Factory.CodeTransition(),\n                    Factory.Code(\"Html.Partial\")\n                           .AsImplicitExpression(VBCodeParser.DefaultKeywords)\n                           .Accepts(AcceptedCharacters.NonWhiteSpace)));\n        }\n\n        [Fact]\n        public void VB_ImplicitExpression_With_MethodCallOrArrayIndex()\n        {\n            ParseBlockTest(\"@foo(42) not-part-of-the-block\",\n                new ExpressionBlock(\n                    Factory.CodeTransition(),\n                    Factory.Code(\"foo(42)\")\n                           .AsImplicitExpression(VBCodeParser.DefaultKeywords)\n                           .Accepts(AcceptedCharacters.NonWhiteSpace)));\n        }\n\n        [Fact]\n        public void VB_ImplicitExpression_Terminates_If_Trailing_Dot_Not_Followed_By_Valid_Token()\n        {\n            ParseBlockTest(\"@foo(42). \",\n                new ExpressionBlock(\n                    Factory.CodeTransition(),\n                    Factory.Code(\"foo(42)\")\n                           .AsImplicitExpression(VBCodeParser.DefaultKeywords)\n                           .Accepts(AcceptedCharacters.NonWhiteSpace)));\n        }\n\n        [Fact]\n        public void VB_ImplicitExpression_Supports_Complex_Expressions()\n        {\n            ParseBlockTest(\"@foo(42).bar(Biz.Boz / 42 * 8)(1).Burf not part of the block\",\n                new ExpressionBlock(\n                    Factory.CodeTransition()\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"foo(42).bar(Biz.Boz / 42 * 8)(1).Burf\")\n                           .AsImplicitExpression(VBCodeParser.DefaultKeywords)\n                           .Accepts(AcceptedCharacters.NonWhiteSpace)));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/VB/VBLayoutDirectiveTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Editor;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Framework;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.VB\n{\n    public class VBLayoutDirectiveTest : VBHtmlCodeParserTestBase\n    {\n        [Theory]\n        [InlineData(\"layout\")]\n        [InlineData(\"Layout\")]\n        [InlineData(\"LAYOUT\")]\n        [InlineData(\"layOut\")]\n        [InlineData(\"LayOut\")]\n        [InlineData(\"LaYoUt\")]\n        [InlineData(\"lAyOuT\")]\n        public void LayoutDirectiveSupportsAnyCasingOfKeyword(string keyword)\n        {\n            ParseBlockTest(\"@\" + keyword,\n                new DirectiveBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(keyword)\n                )\n            );\n        }\n\n        [Fact]\n        public void LayoutDirectiveAcceptsAllTextToEndOfLine()\n        {\n            ParseBlockTest(\"@Layout Foo Bar Baz\",\n                new DirectiveBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"Layout \").Accepts(AcceptedCharacters.None),\n                    Factory.MetaCode(\"Foo Bar Baz\")\n                           .With(new SetLayoutCodeGenerator(\"Foo Bar Baz\"))\n                           .WithEditorHints(EditorHints.VirtualPath | EditorHints.LayoutPage)\n                )\n            );\n        }\n\n        [Fact]\n        public void LayoutDirectiveAcceptsAnyIfNoWhitespaceFollowingLayoutKeyword()\n        {\n            ParseBlockTest(\"@Layout\",\n                new DirectiveBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"Layout\")\n                )\n            );\n        }\n\n        [Fact]\n        public void LayoutDirectiveOutputsMarkerSpanIfAnyWhitespaceAfterLayoutKeyword()\n        {\n            ParseBlockTest(\"@Layout \",\n                new DirectiveBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"Layout \").Accepts(AcceptedCharacters.None),\n                    Factory.EmptyVB()\n                           .AsMetaCode()\n                           .With(new SetLayoutCodeGenerator(String.Empty))\n                           .WithEditorHints(EditorHints.VirtualPath | EditorHints.LayoutPage)\n                )\n            );\n        }\n\n        [Fact]\n        public void LayoutDirectiveAcceptsTrailingNewlineButDoesNotIncludeItInLayoutPath()\n        {\n            ParseBlockTest(\"@Layout Foo\" + Environment.NewLine,\n                new DirectiveBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"Layout \").Accepts(AcceptedCharacters.None),\n                    Factory.MetaCode(\"Foo\\r\\n\")\n                           .With(new SetLayoutCodeGenerator(\"Foo\"))\n                           .Accepts(AcceptedCharacters.None)\n                           .WithEditorHints(EditorHints.VirtualPath | EditorHints.LayoutPage)\n                )\n            );\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/VB/VBNestedStatementsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.VB\n{\n    public class VBNestedStatementsTest : VBHtmlCodeParserTestBase\n    {\n        [Fact]\n        public void VB_Nested_If_Statement()\n        {\n            ParseBlockTest(\"@If True Then\" + Environment.NewLine\n                         + \"    If False Then\" + Environment.NewLine\n                         + \"    End If\" + Environment.NewLine\n                         + \"End If\",\n                new StatementBlock(\n                    Factory.CodeTransition(),\n                    Factory.Code(\"If True Then\\r\\n    If False Then\\r\\n    End If\\r\\nEnd If\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void VB_Nested_Do_Statement()\n        {\n            ParseBlockTest(\"@Do While True\" + Environment.NewLine\n                         + \"    Do\" + Environment.NewLine\n                         + \"    Loop Until False\" + Environment.NewLine\n                         + \"Loop\",\n                new StatementBlock(\n                    Factory.CodeTransition(),\n                    Factory.Code(\"Do While True\\r\\n    Do\\r\\n    Loop Until False\\r\\nLoop\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.AnyExceptNewline)));\n        }\n\n        [Fact]\n        public void VB_Nested_Markup_Statement_In_If()\n        {\n            ParseBlockTest(\"@If True Then\" + Environment.NewLine\n                         + \"    @<p>Tag</p>\" + Environment.NewLine\n                         + \"End If\",\n                new StatementBlock(\n                    Factory.CodeTransition(),\n                    Factory.Code(\"If True Then\\r\\n\")\n                           .AsStatement(),\n                    new MarkupBlock(\n                        Factory.Markup(\"    \"),\n                        Factory.MarkupTransition(),\n                        Factory.Markup(\"<p>Tag</p>\\r\\n\")\n                               .Accepts(AcceptedCharacters.None)),\n                    Factory.Code(\"End If\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void VB_Nested_Markup_Statement_In_Code()\n        {\n            ParseBlockTest(\"@Code\" + Environment.NewLine\n                         + \"    Foo()\" + Environment.NewLine\n                         + \"    @<p>Tag</p>\" + Environment.NewLine\n                         + \"    Bar()\" + Environment.NewLine\n                         + \"End Code\",\n                new StatementBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"Code\")\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"\\r\\n    Foo()\\r\\n\")\n                           .AsStatement(),\n                    new MarkupBlock(\n                        Factory.Markup(\"    \"),\n                        Factory.MarkupTransition(),\n                        Factory.Markup(\"<p>Tag</p>\\r\\n\")\n                               .Accepts(AcceptedCharacters.None)),\n                    Factory.Code(\"    Bar()\\r\\n\")\n                           .AsStatement(),\n                    Factory.MetaCode(\"End Code\")\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void VB_Nested_Markup_Statement_In_Do()\n        {\n            ParseBlockTest(\"@Do\" + Environment.NewLine\n                         + \"    @<p>Tag</p>\" + Environment.NewLine\n                         + \"Loop While True\",\n                new StatementBlock(\n                    Factory.CodeTransition(),\n                    Factory.Code(\"Do\\r\\n\")\n                           .AsStatement(),\n                    new MarkupBlock(\n                        Factory.Markup(\"    \"),\n                        Factory.MarkupTransition(),\n                        Factory.Markup(\"<p>Tag</p>\\r\\n\")\n                               .Accepts(AcceptedCharacters.None)),\n                    Factory.Code(\"Loop While True\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.AnyExceptNewline)));\n        }\n\n        [Fact]\n        public void VB_Nested_Single_Line_Markup_Statement_In_Do()\n        {\n            ParseBlockTest(\"@Do\" + Environment.NewLine\n                         + \"    @:<p>Tag\" + Environment.NewLine\n                         + \"Loop While True\",\n                new StatementBlock(\n                    Factory.CodeTransition(),\n                    Factory.Code(\"Do\\r\\n\")\n                           .AsStatement(),\n                    new MarkupBlock(\n                        Factory.Markup(\"    \"),\n                        Factory.MarkupTransition(),\n                        Factory.MetaMarkup(\":\", HtmlSymbolType.Colon),\n                        Factory.Markup(\"<p>Tag\\r\\n\")\n                               .Accepts(AcceptedCharacters.None)),\n                    Factory.Code(\"Loop While True\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.AnyExceptNewline)));\n        }\n\n        [Fact]\n        public void VB_Nested_Implicit_Expression_In_If()\n        {\n            ParseBlockTest(\"@If True Then\" + Environment.NewLine\n                         + \"    @Foo.Bar\" + Environment.NewLine\n                         + \"End If\",\n                new StatementBlock(\n                    Factory.CodeTransition(),\n                    Factory.Code(\"If True Then\\r\\n    \")\n                           .AsStatement(),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"Foo.Bar\")\n                               .AsExpression()\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    Factory.Code(\"\\r\\nEnd If\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void VB_Nested_Explicit_Expression_In_If()\n        {\n            ParseBlockTest(\"@If True Then\" + Environment.NewLine\n                         + \"    @(Foo.Bar + 42)\" + Environment.NewLine\n                         + \"End If\",\n                new StatementBlock(\n                    Factory.CodeTransition(),\n                    Factory.Code(\"If True Then\\r\\n    \")\n                           .AsStatement(),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"(\")\n                               .Accepts(AcceptedCharacters.None),\n                        Factory.Code(\"Foo.Bar + 42\")\n                               .AsExpression(),\n                        Factory.MetaCode(\")\")\n                               .Accepts(AcceptedCharacters.None)),\n                    Factory.Code(\"\\r\\nEnd If\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.None)));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/VB/VBRazorCommentsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.VB\n{\n    public class VBRazorCommentsTest : VBHtmlMarkupParserTestBase\n    {\n        [Fact]\n        public void UnterminatedRazorComment()\n        {\n            ParseDocumentTest(\"@*\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new CommentBlock(\n                        Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition)\n                               .Accepts(AcceptedCharacters.None),\n                        Factory.MetaMarkup(\"*\", HtmlSymbolType.RazorCommentStar)\n                               .Accepts(AcceptedCharacters.None),\n                        Factory.Span(SpanKind.Comment, new HtmlSymbol(\n                            Factory.LocationTracker.CurrentLocation,\n                            String.Empty,\n                            HtmlSymbolType.Unknown))\n                               .Accepts(AcceptedCharacters.Any))),\n                new RazorError(RazorResources.ParseError_RazorComment_Not_Terminated, 0, 0, 0));\n        }\n\n        [Fact]\n        public void EmptyRazorComment()\n        {\n            ParseDocumentTest(\"@**@\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new CommentBlock(\n                        Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition)\n                               .Accepts(AcceptedCharacters.None),\n                        Factory.MetaMarkup(\"*\", HtmlSymbolType.RazorCommentStar)\n                               .Accepts(AcceptedCharacters.None),\n                        Factory.Span(SpanKind.Comment, new HtmlSymbol(\n                            Factory.LocationTracker.CurrentLocation,\n                            String.Empty,\n                            HtmlSymbolType.Unknown))\n                               .Accepts(AcceptedCharacters.Any),\n                        Factory.MetaMarkup(\"*\", HtmlSymbolType.RazorCommentStar)\n                               .Accepts(AcceptedCharacters.None),\n                        Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition)\n                               .Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void RazorCommentInImplicitExpressionMethodCall()\n        {\n            ParseDocumentTest(@\"@foo(@**@\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"foo(\")\n                               .AsImplicitExpression(VBCodeParser.DefaultKeywords),\n                        new CommentBlock(\n                            Factory.CodeTransition(VBSymbolType.RazorCommentTransition)\n                                   .Accepts(AcceptedCharacters.None),\n                            Factory.MetaCode(\"*\", VBSymbolType.RazorCommentStar)\n                                   .Accepts(AcceptedCharacters.None),\n                            Factory.Span(SpanKind.Comment, new VBSymbol(\n                                Factory.LocationTracker.CurrentLocation,\n                                String.Empty,\n                                VBSymbolType.Unknown))\n                                   .Accepts(AcceptedCharacters.Any),\n                            Factory.MetaCode(\"*\", VBSymbolType.RazorCommentStar)\n                                   .Accepts(AcceptedCharacters.None),\n                            Factory.CodeTransition(VBSymbolType.RazorCommentTransition)\n                                   .Accepts(AcceptedCharacters.None)),\n                        Factory.EmptyVB()\n                               .AsImplicitExpression(VBCodeParser.DefaultKeywords))),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_Expected_CloseBracket_Before_EOF, \"(\", \")\"),\n                    4, 0, 4));\n        }\n\n        [Fact]\n        public void UnterminatedRazorCommentInImplicitExpressionMethodCall()\n        {\n            ParseDocumentTest(\"@foo(@*\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"foo(\")\n                               .AsImplicitExpression(VBCodeParser.DefaultKeywords),\n                        new CommentBlock(\n                            Factory.CodeTransition(VBSymbolType.RazorCommentTransition)\n                                   .Accepts(AcceptedCharacters.None),\n                            Factory.MetaCode(\"*\", VBSymbolType.RazorCommentStar)\n                                   .Accepts(AcceptedCharacters.None),\n                            Factory.Span(SpanKind.Comment, new VBSymbol(\n                                Factory.LocationTracker.CurrentLocation,\n                                String.Empty,\n                                VBSymbolType.Unknown))\n                                    .Accepts(AcceptedCharacters.Any)))),\n                new RazorError(RazorResources.ParseError_RazorComment_Not_Terminated, 5, 0, 5),\n                new RazorError(String.Format(RazorResources.ParseError_Expected_CloseBracket_Before_EOF, \"(\", \")\"), 4, 0, 4));\n        }\n\n        [Fact]\n        public void RazorCommentInVerbatimBlock()\n        {\n            ParseDocumentTest(\"@Code\" + Environment.NewLine\n                            + \"    @<text\" + Environment.NewLine\n                            + \"    @**@\" + Environment.NewLine\n                            + \"End Code\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new StatementBlock(\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Code\").Accepts(AcceptedCharacters.None),\n                        Factory.Code(\"\\r\\n\").AsStatement(),\n                        new MarkupBlock(\n                            Factory.Markup(\"    \"),\n                            Factory.MarkupTransition(\"@\"),\n                            Factory.MarkupTransition(\"<text\").Accepts(AcceptedCharacters.Any),\n                            Factory.Markup(\"\\r\\n    \"),\n                            new CommentBlock(\n                                Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition)\n                                       .Accepts(AcceptedCharacters.None),\n                                Factory.MetaMarkup(\"*\", HtmlSymbolType.RazorCommentStar)\n                                       .Accepts(AcceptedCharacters.None),\n                                Factory.Span(SpanKind.Comment, new HtmlSymbol(\n                                    Factory.LocationTracker.CurrentLocation,\n                                    String.Empty,\n                                    HtmlSymbolType.Unknown))\n                                       .Accepts(AcceptedCharacters.Any),\n                                Factory.MetaMarkup(\"*\", HtmlSymbolType.RazorCommentStar)\n                                       .Accepts(AcceptedCharacters.None),\n                                Factory.MarkupTransition(HtmlSymbolType.RazorCommentTransition)\n                                       .Accepts(AcceptedCharacters.None)),\n                            Factory.Markup(\"\\r\\nEnd Code\")))),\n                new RazorError(RazorResources.ParseError_TextTagCannotContainAttributes, 12, 1, 5),\n                new RazorError(String.Format(RazorResources.ParseError_MissingEndTag, \"text\"), 12, 1, 5),\n                new RazorError(String.Format(RazorResources.ParseError_BlockNotTerminated, SyntaxConstants.VB.CodeKeyword, SyntaxConstants.VB.EndCodeKeyword), 1, 0, 1));\n        }\n\n        [Fact]\n        public void UnterminatedRazorCommentInVerbatimBlock()\n        {\n            ParseDocumentTest(\"@Code\" + Environment.NewLine\n                            + \"@*\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new StatementBlock(\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Code\").Accepts(AcceptedCharacters.None),\n                        Factory.Code(\"\\r\\n\")\n                               .AsStatement(),\n                        new CommentBlock(\n                            Factory.CodeTransition(VBSymbolType.RazorCommentTransition)\n                                   .Accepts(AcceptedCharacters.None),\n                            Factory.MetaCode(\"*\", VBSymbolType.RazorCommentStar)\n                                   .Accepts(AcceptedCharacters.None),\n                            Factory.Span(SpanKind.Comment, new VBSymbol(Factory.LocationTracker.CurrentLocation,\n                                                                        String.Empty,\n                                                                        VBSymbolType.Unknown))\n                                   .Accepts(AcceptedCharacters.Any)))),\n                new RazorError(RazorResources.ParseError_RazorComment_Not_Terminated, 7, 1, 0),\n                new RazorError(String.Format(RazorResources.ParseError_BlockNotTerminated, SyntaxConstants.VB.CodeKeyword, SyntaxConstants.VB.EndCodeKeyword), 1, 0, 1));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/VB/VBReservedWordsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.VB\n{\n    public class VBReservedWordsTest : VBHtmlCodeParserTestBase\n    {\n        [Theory]\n        [InlineData(\"Namespace\")]\n        [InlineData(\"Class\")]\n        [InlineData(\"NAMESPACE\")]\n        [InlineData(\"CLASS\")]\n        [InlineData(\"NameSpace\")]\n        [InlineData(\"nameSpace\")]\n        private void ReservedWords(string word)\n        {\n            ParseBlockTest(word,\n                new DirectiveBlock(\n                    Factory.MetaCode(word).Accepts(AcceptedCharacters.None)),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_ReservedWord, word),\n                    SourceLocation.Zero));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/VB/VBSectionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.VB\n{\n    public class VBSectionTest : VBHtmlMarkupParserTestBase\n    {\n        [Fact]\n        public void ParseSectionBlockCapturesNewlineImmediatelyFollowing()\n        {\n            ParseDocumentTest(\"@Section\" + Environment.NewLine,\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(String.Empty),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Section\\r\\n\"),\n                        new MarkupBlock())),\n                new RazorError(\n                    String.Format(\n                        RazorResources.ParseError_Unexpected_Character_At_Section_Name_Start,\n                        RazorResources.ErrorComponent_EndOfFile),\n                    10, 1, 0),\n                new RazorError(\n                    String.Format(\n                        RazorResources.ParseError_BlockNotTerminated,\n                        \"Section\", \"End Section\"),\n                    1, 0, 1));\n        }\n\n        [Fact]\n        public void ParseSectionRequiresNameBeOnSameLineAsSectionKeyword()\n        {\n            ParseDocumentTest(\"@Section \" + Environment.NewLine\n                            + \"Foo\" + Environment.NewLine\n                            + \"    <p>Body</p>\" + Environment.NewLine\n                            + \"End Section\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(String.Empty),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Section \"),\n                        new MarkupBlock(\n                            Factory.Markup(\"\\r\\nFoo\\r\\n    <p>Body</p>\\r\\n\")),\n                        Factory.MetaCode(\"End Section\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()),\n                new RazorError(\n                    String.Format(\n                        RazorResources.ParseError_Unexpected_Character_At_Section_Name_Start,\n                        RazorResources.ErrorComponent_Newline),\n                    9, 0, 9));\n        }\n\n        [Fact]\n        public void ParseSectionAllowsNameToBeOnDifferentLineAsSectionKeywordIfUnderscoresUsed()\n        {\n            ParseDocumentTest(\"@Section _\" + Environment.NewLine\n                            + \"_\" + Environment.NewLine\n                            + \"Foo\" + Environment.NewLine\n                            + \"    <p>Body</p>\" + Environment.NewLine\n                            + \"End Section\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"Foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Section _\\r\\n_\\r\\nFoo\"),\n                        new MarkupBlock(\n                            Factory.Markup(\"\\r\\n    <p>Body</p>\\r\\n\")),\n                        Factory.MetaCode(\"End Section\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void ParseSectionReportsErrorAndTerminatesSectionBlockIfKeywordNotFollowedByIdentifierStartCharacter()\n        {\n            ParseDocumentTest(\"@Section 9\" + Environment.NewLine\n                            + \"    <p>Foo</p>\" + Environment.NewLine\n                            + \"End Section\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(String.Empty),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Section \"),\n                        new MarkupBlock(\n                            Factory.Markup(\"9\\r\\n    <p>Foo</p>\\r\\n\")),\n                        Factory.MetaCode(\"End Section\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()),\n                new RazorError(\n                    String.Format(\n                        RazorResources.ParseError_Unexpected_Character_At_Section_Name_Start,\n                        String.Format(RazorResources.ErrorComponent_Character, \"9\")),\n                    9, 0, 9));\n        }\n\n        [Fact]\n        public void ParserOutputsErrorOnNestedSections()\n        {\n            ParseDocumentTest(\"@Section foo\" + Environment.NewLine\n                            + \"    @Section bar\" + Environment.NewLine\n                            + \"        <p>Foo</p>\" + Environment.NewLine\n                            + \"    End Section\" + Environment.NewLine\n                            + \"End Section\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Section foo\"),\n                        new MarkupBlock(\n                            Factory.Markup(\"\\r\\n\"),\n                            new SectionBlock(new SectionCodeGenerator(\"bar\"),\n                                Factory.Code(\"    \").AsStatement(),\n                                Factory.CodeTransition(),\n                                Factory.MetaCode(\"Section bar\"),\n                                new MarkupBlock(\n                                    Factory.Markup(\"\\r\\n        <p>Foo</p>\\r\\n    \")),\n                                Factory.MetaCode(\"End Section\").Accepts(AcceptedCharacters.None)),\n                            Factory.Markup(\"\\r\\n\")),\n                        Factory.MetaCode(\"End Section\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()),\n                new RazorError(\n                    String.Format(\n                        RazorResources.ParseError_Sections_Cannot_Be_Nested,\n                        RazorResources.SectionExample_VB),\n                    26, 1, 12));\n        }\n\n        [Fact]\n        public void ParseSectionHandlesEOFAfterIdentifier()\n        {\n            ParseDocumentTest(\"@Section foo\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Section foo\")\n                               .AutoCompleteWith(SyntaxConstants.VB.EndSectionKeyword),\n                        new MarkupBlock())),\n                new RazorError(\n                    String.Format(\n                        RazorResources.ParseError_BlockNotTerminated,\n                        \"Section\", \"End Section\"),\n                    1, 0, 1));\n        }\n\n        [Fact]\n        public void ParseSectionHandlesUnterminatedSection()\n        {\n            ParseDocumentTest(\"@Section foo\" + Environment.NewLine\n                            + \"    <p>Foo</p>\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Section foo\")\n                               .AutoCompleteWith(SyntaxConstants.VB.EndSectionKeyword),\n                        new MarkupBlock(\n                            Factory.Markup(\"\\r\\n    <p>Foo</p>\")))),\n                new RazorError(\n                    String.Format(\n                        RazorResources.ParseError_BlockNotTerminated,\n                        \"Section\", \"End Section\"),\n                    1, 0, 1));\n        }\n\n        [Fact]\n        public void ParseDocumentParsesNamedSectionCorrectly()\n        {\n            ParseDocumentTest(\"@Section foo\" + Environment.NewLine\n                            + \"    <p>Foo</p>\" + Environment.NewLine\n                            + \"End Section\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Section foo\"),\n                        new MarkupBlock(\n                            Factory.Markup(\"\\r\\n    <p>Foo</p>\\r\\n\")),\n                        Factory.MetaCode(\"End Section\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void ParseSectionTerminatesOnFirstEndSection()\n        {\n            ParseDocumentTest(\"@Section foo\" + Environment.NewLine\n                            + \"    <p>End Section</p>\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Section foo\"),\n                        new MarkupBlock(\n                            Factory.Markup(\"\\r\\n    <p>\")),\n                        Factory.MetaCode(\"End Section\").Accepts(AcceptedCharacters.None)),\n                    Factory.Markup(\"</p>\")));\n        }\n\n        [Fact]\n        public void ParseSectionAllowsEndSectionInVBExpression()\n        {\n            ParseDocumentTest(\"@Section foo\" + Environment.NewLine\n                            + \"    I really want to render the word @(\\\"End Section\\\"), so this is how I do it\" + Environment.NewLine\n                            + \"End Section\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Section foo\"),\n                        new MarkupBlock(\n                            Factory.Markup(\"\\r\\n    I really want to render the word \"),\n                            new ExpressionBlock(\n                                Factory.CodeTransition(),\n                                Factory.MetaCode(\"(\").Accepts(AcceptedCharacters.None),\n                                Factory.Code(\"\\\"End Section\\\"\").AsExpression(),\n                                Factory.MetaCode(\")\").Accepts(AcceptedCharacters.None)),\n                            Factory.Markup(\", so this is how I do it\\r\\n\")),\n                        Factory.MetaCode(\"End Section\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        // These are tests that are normally in HtmlToCodeSwitchTest, but we want to verify them for VB \n        // since VB has slightly different section terminating behavior which follow slightly different\n        // code paths\n\n        [Fact]\n        public void SectionBodyTreatsTwoAtSignsAsEscapeSequence()\n        {\n            ParseDocumentTest(\"@Section Foo\" + Environment.NewLine\n                            + \"    <foo>@@bar</foo>\" + Environment.NewLine\n                            + \"End Section\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"Foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Section Foo\").AutoCompleteWith(null),\n                        new MarkupBlock(\n                            Factory.Markup(\"\\r\\n    <foo>\"),\n                            Factory.Markup(\"@\").Hidden(),\n                            Factory.Markup(\"@bar</foo>\\r\\n\")),\n                        Factory.MetaCode(\"End Section\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n\n        [Fact]\n        public void SectionBodyTreatsPairsOfAtSignsAsEscapeSequence()\n        {\n            ParseDocumentTest(\"@Section Foo\" + Environment.NewLine\n                            + \"    <foo>@@@@@bar</foo>\" + Environment.NewLine\n                            + \"End Section\",\n                new MarkupBlock(\n                    Factory.EmptyHtml(),\n                    new SectionBlock(new SectionCodeGenerator(\"Foo\"),\n                        Factory.CodeTransition(),\n                        Factory.MetaCode(\"Section Foo\").AutoCompleteWith(null),\n                        new MarkupBlock(\n                            Factory.Markup(\"\\r\\n    <foo>\"),\n                            Factory.Markup(\"@\").Hidden(),\n                            Factory.Markup(\"@\"),\n                            Factory.Markup(\"@\").Hidden(),\n                            Factory.Markup(\"@\"),\n                            new ExpressionBlock(\n                                Factory.CodeTransition(),\n                                Factory.Code(\"bar\")\n                                       .AsImplicitExpression(VBCodeParser.DefaultKeywords)\n                                       .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                            Factory.Markup(\"</foo>\\r\\n\")),\n                        Factory.MetaCode(\"End Section\").Accepts(AcceptedCharacters.None)),\n                    Factory.EmptyHtml()));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/VB/VBSpecialKeywordsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.VB\n{\n    public class VBSpecialKeywordsTest : VBHtmlCodeParserTestBase\n    {\n        [Fact]\n        public void ParseInheritsStatementMarksInheritsSpanAsCanGrowIfMissingTrailingSpace()\n        {\n            ParseBlockTest(\"inherits\",\n                new DirectiveBlock(\n                    Factory.MetaCode(\"inherits\")),\n                new RazorError(\n                    RazorResources.ParseError_InheritsKeyword_Must_Be_Followed_By_TypeName,\n                    8, 0, 8));\n        }\n\n        [Fact]\n        public void InheritsBlockAcceptsMultipleGenericArguments()\n        {\n            ParseBlockTest(\"inherits Foo.Bar(Of Biz(Of Qux), String, Integer).Baz\",\n                new DirectiveBlock(\n                    Factory.MetaCode(\"inherits \").Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"Foo.Bar(Of Biz(Of Qux), String, Integer).Baz\")\n                           .AsBaseType(\"Foo.Bar(Of Biz(Of Qux), String, Integer).Baz\")));\n        }\n\n        [Fact]\n        public void InheritsDirectiveSupportsVSTemplateTokens()\n        {\n            ParseBlockTest(\"@Inherits $rootnamespace$.MyBase\",\n                new DirectiveBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"Inherits \")\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"$rootnamespace$.MyBase\")\n                           .AsBaseType(\"$rootnamespace$.MyBase\")));\n        }\n\n        [Fact]\n        public void InheritsBlockOutputsErrorIfInheritsNotFollowedByTypeButAcceptsEntireLineAsCode()\n        {\n            ParseBlockTest(\"inherits                \" + Environment.NewLine\n                         + \"foo\",\n                new DirectiveBlock(\n                    Factory.MetaCode(\"inherits                \").Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"\\r\\n\").AsBaseType(String.Empty)),\n                new RazorError(\n                    RazorResources.ParseError_InheritsKeyword_Must_Be_Followed_By_TypeName,\n                    8, 0, 8));\n        }\n\n        [Fact]\n        public void ParseBlockShouldSupportNamespaceImports()\n        {\n            ParseBlockTest(\"Imports Foo.Bar.Baz.Biz.Boz\",\n                new DirectiveBlock(\n                    Factory.MetaCode(\"Imports Foo.Bar.Baz.Biz.Boz\")\n                           .With(new AddImportCodeGenerator(\n                               ns: \" Foo.Bar.Baz.Biz.Boz\",\n                               namespaceKeywordLength: SyntaxConstants.VB.ImportsKeywordLength))));\n        }\n\n        [Fact]\n        public void ParseBlockShowsErrorIfNamespaceNotOnSameLineAsImportsKeyword()\n        {\n            ParseBlockTest(\"Imports\" + Environment.NewLine\n                         + \"Foo\",\n                new DirectiveBlock(\n                    Factory.MetaCode(\"Imports\\r\\n\")\n                           .With(new AddImportCodeGenerator(\n                               ns: \"\\r\\n\",\n                               namespaceKeywordLength: SyntaxConstants.VB.ImportsKeywordLength))),\n                new RazorError(\n                    RazorResources.ParseError_NamespaceOrTypeAliasExpected,\n                    7, 0, 7));\n        }\n\n        [Fact]\n        public void ParseBlockShowsErrorIfTypeBeingAliasedNotOnSameLineAsImportsKeyword()\n        {\n            ParseBlockTest(\"Imports Foo =\" + Environment.NewLine\n                         + \"System.Bar\",\n                new DirectiveBlock(\n                    Factory.MetaCode(\"Imports Foo =\\r\\n\")\n                           .With(new AddImportCodeGenerator(\n                               ns: \" Foo =\\r\\n\",\n                               namespaceKeywordLength: SyntaxConstants.VB.ImportsKeywordLength))));\n        }\n\n        [Fact]\n        public void ParseBlockShouldSupportTypeAliases()\n        {\n            ParseBlockTest(\"Imports Foo = Bar.Baz.Biz.Boz\",\n                new DirectiveBlock(\n                    Factory.MetaCode(\"Imports Foo = Bar.Baz.Biz.Boz\")\n                           .With(new AddImportCodeGenerator(\n                               ns: \" Foo = Bar.Baz.Biz.Boz\",\n                               namespaceKeywordLength: SyntaxConstants.VB.ImportsKeywordLength))));\n        }\n\n        [Fact]\n        public void ParseBlockThrowsErrorIfOptionIsNotFollowedByStrictOrExplicit()\n        {\n            ParseBlockTest(\"Option FizzBuzz On\",\n                new DirectiveBlock(\n                    Factory.MetaCode(\"Option FizzBuzz On\")\n                           .With(new SetVBOptionCodeGenerator(optionName: null, value: true))),\n                new RazorError(\n                    String.Format(RazorResources.ParseError_UnknownOption, \"FizzBuzz\"),\n                    7, 0, 7));\n        }\n\n        [Fact]\n        public void ParseBlockThrowsErrorIfOptionStrictIsNotFollowedByOnOrOff()\n        {\n            ParseBlockTest(\"Option Strict Yes\",\n                new DirectiveBlock(\n                    Factory.MetaCode(\"Option Strict Yes\")\n                           .With(SetVBOptionCodeGenerator.Strict(true))),\n                new RazorError(\n                    String.Format(\n                        RazorResources.ParseError_InvalidOptionValue,\n                        \"Strict\", \"Yes\"),\n                    14, 0, 14));\n        }\n\n        [Fact]\n        public void ParseBlockReadsToAfterOnKeywordIfOptionStrictBlock()\n        {\n            ParseBlockTest(\"Option Strict On Foo Bar Baz\",\n                new DirectiveBlock(\n                    Factory.MetaCode(\"Option Strict On\")\n                           .With(SetVBOptionCodeGenerator.Strict(true))));\n        }\n\n        [Fact]\n        public void ParseBlockReadsToAfterOffKeywordIfOptionStrictBlock()\n        {\n            ParseBlockTest(\"Option Strict Off Foo Bar Baz\",\n                new DirectiveBlock(\n                    Factory.MetaCode(\"Option Strict Off\")\n                           .With(SetVBOptionCodeGenerator.Strict(false))));\n        }\n\n        [Fact]\n        public void ParseBlockReadsToAfterOnKeywordIfOptionExplicitBlock()\n        {\n            ParseBlockTest(\"Option Explicit On Foo Bar Baz\",\n                new DirectiveBlock(\n                    Factory.MetaCode(\"Option Explicit On\")\n                           .With(SetVBOptionCodeGenerator.Explicit(true))));\n        }\n\n        [Fact]\n        public void ParseBlockReadsToAfterOffKeywordIfOptionExplicitBlock()\n        {\n            ParseBlockTest(\"Option Explicit Off Foo Bar Baz\",\n                new DirectiveBlock(\n                    Factory.MetaCode(\"Option Explicit Off\")\n                           .With(SetVBOptionCodeGenerator.Explicit(false))));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/VB/VBStatementTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Framework;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.VB\n{\n    public class VBStatementTest : VBHtmlCodeParserTestBase\n    {\n        [Fact]\n        public void VB_Inherits_Statement()\n        {\n            ParseBlockTest(\"@Inherits System.Foo.Bar(Of Baz)\",\n                new DirectiveBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"Inherits \").Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"System.Foo.Bar(Of Baz)\")\n                           .AsBaseType(\"System.Foo.Bar(Of Baz)\")));\n        }\n\n        [Fact]\n        public void InheritsDirectiveSupportsArrays()\n        {\n            ParseBlockTest(\"@Inherits System.String(())()\",\n                new DirectiveBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"Inherits \")\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"System.String(())()\")\n                           .AsBaseType(\"System.String(())()\")));\n        }\n\n        [Fact]\n        public void InheritsDirectiveSupportsNestedGenerics()\n        {\n            ParseBlockTest(\"@Inherits System.Web.Mvc.WebViewPage(Of IEnumerable(Of MvcApplication2.Models.RegisterModel))\",\n                new DirectiveBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"Inherits \")\n                           .Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"System.Web.Mvc.WebViewPage(Of IEnumerable(Of MvcApplication2.Models.RegisterModel))\")\n                           .AsBaseType(\"System.Web.Mvc.WebViewPage(Of IEnumerable(Of MvcApplication2.Models.RegisterModel))\")));\n        }\n\n        [Fact]\n        public void InheritsDirectiveSupportsTypeKeywords()\n        {\n            ParseBlockTest(\"@Inherits String\",\n                new DirectiveBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"Inherits \").Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"String\").AsBaseType(\"String\")));\n        }\n\n        [Fact]\n        public void VB_Option_Strict_Statement()\n        {\n            ParseBlockTest(\"@Option Strict Off\",\n                new DirectiveBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"Option Strict Off\")\n                           .With(SetVBOptionCodeGenerator.Strict(false))));\n        }\n\n        [Fact]\n        public void VB_Option_Explicit_Statement()\n        {\n            ParseBlockTest(\"@Option Explicit Off\",\n                new DirectiveBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"Option Explicit Off\")\n                           .With(SetVBOptionCodeGenerator.Explicit(false))));\n        }\n\n        [Fact]\n        public void VB_Imports_Statement()\n        {\n            ParseBlockTest(\"@Imports Biz = System.Foo.Bar(Of Boz.Baz(Of Qux))\",\n                new DirectiveBlock(\n                    Factory.CodeTransition(),\n                    Factory.MetaCode(\"Imports Biz = System.Foo.Bar(Of Boz.Baz(Of Qux))\")\n                           .With(new AddImportCodeGenerator(\n                               ns: \" Biz = System.Foo.Bar(Of Boz.Baz(Of Qux))\",\n                               namespaceKeywordLength: SyntaxConstants.VB.ImportsKeywordLength))));\n        }\n\n        [Fact]\n        public void VB_Using_Statement()\n        {\n            ParseBlockTest(\"@Using foo as Bar\" + Environment.NewLine\n                         + \"    foo()\" + Environment.NewLine\n                         + \"End Using\",\n                new StatementBlock(\n                    Factory.CodeTransition(),\n                    Factory.Code(\"Using foo as Bar\\r\\n    foo()\\r\\nEnd Using\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void VB_Do_Loop_Statement()\n        {\n            ParseBlockTest(\"@Do\" + Environment.NewLine\n                         + \"    foo()\" + Environment.NewLine\n                         + \"Loop While True\",\n                new StatementBlock(\n                    Factory.CodeTransition(),\n                    Factory.Code(\"Do\\r\\n    foo()\\r\\nLoop While True\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.AnyExceptNewline)));\n        }\n\n        [Fact]\n        public void VB_While_Statement()\n        {\n            ParseBlockTest(\"@While True\" + Environment.NewLine\n                         + \"    foo()\" + Environment.NewLine\n                         + \"End While\",\n                new StatementBlock(\n                    Factory.CodeTransition(),\n                    Factory.Code(\"While True\\r\\n    foo()\\r\\nEnd While\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void VB_If_Statement()\n        {\n            ParseBlockTest(\"@If True Then\" + Environment.NewLine\n                         + \"    foo()\" + Environment.NewLine\n                         + \"ElseIf False Then\" + Environment.NewLine\n                         + \"    bar()\" + Environment.NewLine\n                         + \"Else\" + Environment.NewLine\n                         + \"    baz()\" + Environment.NewLine\n                         + \"End If\",\n                new StatementBlock(\n                    Factory.CodeTransition(),\n                    Factory.Code(\"If True Then\\r\\n    foo()\\r\\nElseIf False Then\\r\\n    bar()\\r\\nElse\\r\\n    baz()\\r\\nEnd If\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void VB_Select_Statement()\n        {\n            ParseBlockTest(\"@Select Case foo\" + Environment.NewLine\n                         + \"    Case 1\" + Environment.NewLine\n                         + \"        foo()\" + Environment.NewLine\n                         + \"    Case 2\" + Environment.NewLine\n                         + \"        bar()\" + Environment.NewLine\n                         + \"    Case Else\" + Environment.NewLine\n                         + \"        baz()\" + Environment.NewLine\n                         + \"End Select\",\n                new StatementBlock(\n                    Factory.CodeTransition(),\n                    Factory.Code(\"Select Case foo\\r\\n    Case 1\\r\\n        foo()\\r\\n    Case 2\\r\\n        bar()\\r\\n    Case Else\\r\\n        baz()\\r\\nEnd Select\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void VB_For_Statement()\n        {\n            ParseBlockTest(\"@For Each foo In bar\" + Environment.NewLine\n                         + \"    baz()\" + Environment.NewLine\n                         + \"Next\",\n                new StatementBlock(\n                    Factory.CodeTransition(),\n                    Factory.Code(\"For Each foo In bar\\r\\n    baz()\\r\\nNext\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.AnyExceptNewline)));\n        }\n\n        [Fact]\n        public void VB_Try_Statement()\n        {\n            ParseBlockTest(\"@Try\" + Environment.NewLine\n                         + \"    foo()\" + Environment.NewLine\n                         + \"Catch ex as Exception\" + Environment.NewLine\n                         + \"    bar()\" + Environment.NewLine\n                         + \"Finally\" + Environment.NewLine\n                         + \"    baz()\" + Environment.NewLine\n                         + \"End Try\",\n                new StatementBlock(\n                    Factory.CodeTransition(),\n                    Factory.Code(\"Try\\r\\n    foo()\\r\\nCatch ex as Exception\\r\\n    bar()\\r\\nFinally\\r\\n    baz()\\r\\nEnd Try\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void VB_With_Statement()\n        {\n            ParseBlockTest(\"@With foo\" + Environment.NewLine\n                         + \"    .bar()\" + Environment.NewLine\n                         + \"End With\",\n                new StatementBlock(\n                    Factory.CodeTransition(),\n                    Factory.Code(\"With foo\\r\\n    .bar()\\r\\nEnd With\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void VB_SyncLock_Statement()\n        {\n            ParseBlockTest(\"@SyncLock foo\" + Environment.NewLine\n                         + \"    foo.bar()\" + Environment.NewLine\n                         + \"End SyncLock\",\n                new StatementBlock(\n                    Factory.CodeTransition(),\n                    Factory.Code(\"SyncLock foo\\r\\n    foo.bar()\\r\\nEnd SyncLock\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.None)));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/VB/VBTemplateTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Test.Framework;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.VB\n{\n    public class VBTemplateTest : VBHtmlCodeParserTestBase\n    {\n        private const string TestTemplateCode = \"@@<p>Foo #@item</p>\";\n\n        private TemplateBlock TestTemplate()\n        {\n            return new TemplateBlock(new TemplateBlockCodeGenerator(),\n                new MarkupBlock(\n                    Factory.MarkupTransition(),\n                    Factory.MetaMarkup(\"@\"),\n                    Factory.Markup(\"<p>Foo #\"),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"item\")\n                               .AsImplicitExpression(VBCodeParser.DefaultKeywords)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    Factory.Markup(\"</p>\").Accepts(AcceptedCharacters.None)));\n        }\n\n        private const string TestNestedTemplateCode = \"@@<p>Foo #@Html.Repeat(10,@@<p>@item</p>)</p>\";\n\n        private TemplateBlock TestNestedTemplate()\n        {\n            return new TemplateBlock(new TemplateBlockCodeGenerator(),\n                new MarkupBlock(\n                    Factory.MarkupTransition(),\n                    Factory.MetaMarkup(\"@\"),\n                    Factory.Markup(\"<p>Foo #\"),\n                    new ExpressionBlock(\n                        Factory.CodeTransition(),\n                        Factory.Code(\"Html.Repeat(10,\")\n                               .AsImplicitExpression(VBCodeParser.DefaultKeywords)\n                               .Accepts(AcceptedCharacters.Any),\n                        new TemplateBlock(new TemplateBlockCodeGenerator(),\n                            new MarkupBlock(\n                                Factory.MarkupTransition(),\n                                Factory.MetaMarkup(\"@\"),\n                                Factory.Markup(\"<p>\"),\n                                new ExpressionBlock(\n                                    Factory.CodeTransition(),\n                                    Factory.Code(\"item\")\n                                           .AsImplicitExpression(VBCodeParser.DefaultKeywords)\n                                           .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                                Factory.Markup(\"</p>\").Accepts(AcceptedCharacters.None))),\n                        Factory.Code(\")\")\n                               .AsImplicitExpression(VBCodeParser.DefaultKeywords)\n                               .Accepts(AcceptedCharacters.NonWhiteSpace)),\n                    Factory.Markup(\"</p>\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockHandlesSimpleAnonymousSectionInExplicitExpressionParens()\n        {\n            ParseBlockTest(\"(Html.Repeat(10,\" + TestTemplateCode + \"))\",\n                new ExpressionBlock(\n                    Factory.MetaCode(\"(\").Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"Html.Repeat(10,\").AsExpression(),\n                    TestTemplate(),\n                    Factory.Code(\")\").AsExpression(),\n                    Factory.MetaCode(\")\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockHandlesSimpleAnonymousSectionInImplicitExpressionParens()\n        {\n            ParseBlockTest(\"Html.Repeat(10,\" + TestTemplateCode + \")\",\n                new ExpressionBlock(\n                    Factory.Code(\"Html.Repeat(10,\").AsImplicitExpression(KeywordSet),\n                    TestTemplate(),\n                    Factory.Code(\")\").AsImplicitExpression(KeywordSet).Accepts(AcceptedCharacters.NonWhiteSpace)));\n        }\n\n        [Fact]\n        public void ParseBlockHandlesTwoAnonymousSectionsInImplicitExpressionParens()\n        {\n            ParseBlockTest(\"Html.Repeat(10,\" + TestTemplateCode + \",\" + TestTemplateCode + \")\",\n                new ExpressionBlock(\n                    Factory.Code(\"Html.Repeat(10,\").AsImplicitExpression(KeywordSet),\n                    TestTemplate(),\n                    Factory.Code(\",\").AsImplicitExpression(KeywordSet),\n                    TestTemplate(),\n                    Factory.Code(\")\").AsImplicitExpression(KeywordSet).Accepts(AcceptedCharacters.NonWhiteSpace)));\n        }\n\n        [Fact]\n        public void ParseBlockProducesErrorButCorrectlyParsesNestedAnonymousSectionInImplicitExpressionParens()\n        {\n            ParseBlockTest(\"Html.Repeat(10,\" + TestNestedTemplateCode + \")\",\n                new ExpressionBlock(\n                    Factory.Code(\"Html.Repeat(10,\").AsImplicitExpression(KeywordSet),\n                    TestNestedTemplate(),\n                    Factory.Code(\")\").AsImplicitExpression(KeywordSet).Accepts(AcceptedCharacters.NonWhiteSpace)),\n                GetNestedSectionError(41, 0, 41));\n        }\n\n        [Fact]\n        public void ParseBlockHandlesSimpleAnonymousSectionInStatementWithinCodeBlock()\n        {\n            ParseBlockTest(\"For Each foo in Bar \" + Environment.NewLine\n                         + \"    Html.ExecuteTemplate(foo,\" + TestTemplateCode + \")\" + Environment.NewLine\n                         + \"Next foo\",\n                new StatementBlock(\n                    Factory.Code(\"For Each foo in Bar \\r\\n    Html.ExecuteTemplate(foo,\")\n                           .AsStatement(),\n                    TestTemplate(),\n                    Factory.Code(\")\\r\\nNext foo\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.WhiteSpace | AcceptedCharacters.NonWhiteSpace)));\n        }\n\n        [Fact]\n        public void ParseBlockHandlesTwoAnonymousSectionsInStatementWithinCodeBlock()\n        {\n            ParseBlockTest(\"For Each foo in Bar \" + Environment.NewLine\n                         + \"    Html.ExecuteTemplate(foo,\" + TestTemplateCode + \",\" + TestTemplateCode + \")\" + Environment.NewLine\n                         + \"Next foo\",\n                new StatementBlock(\n                    Factory.Code(\"For Each foo in Bar \\r\\n    Html.ExecuteTemplate(foo,\")\n                           .AsStatement(),\n                    TestTemplate(),\n                    Factory.Code(\",\").AsStatement(),\n                    TestTemplate(),\n                    Factory.Code(\")\\r\\nNext foo\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.WhiteSpace | AcceptedCharacters.NonWhiteSpace)));\n        }\n\n        [Fact]\n        public void ParseBlockProducesErrorButCorrectlyParsesNestedAnonymousSectionInStatementWithinCodeBlock()\n        {\n            ParseBlockTest(\"For Each foo in Bar \" + Environment.NewLine\n                         + \"    Html.ExecuteTemplate(foo,\" + TestNestedTemplateCode + \")\" + Environment.NewLine\n                         + \"Next foo\",\n                new StatementBlock(\n                    Factory.Code(\"For Each foo in Bar \\r\\n    Html.ExecuteTemplate(foo,\")\n                           .AsStatement(),\n                    TestNestedTemplate(),\n                    Factory.Code(\")\\r\\nNext foo\")\n                           .AsStatement()\n                           .Accepts(AcceptedCharacters.WhiteSpace | AcceptedCharacters.NonWhiteSpace)),\n                GetNestedSectionError(77, 1, 55));\n        }\n\n        [Fact]\n        public void ParseBlockHandlesSimpleAnonymousSectionInStatementWithinStatementBlock()\n        {\n            ParseBlockTest(\"Code \" + Environment.NewLine\n                         + \"    Dim foo = bar\" + Environment.NewLine\n                         + \"    Html.ExecuteTemplate(foo,\" + TestTemplateCode + \")\" + Environment.NewLine\n                         + \"End Code\",\n                new StatementBlock(\n                    Factory.MetaCode(\"Code\").Accepts(AcceptedCharacters.None),\n                    Factory.Code(\" \\r\\n    Dim foo = bar\\r\\n    Html.ExecuteTemplate(foo,\")\n                           .AsStatement(),\n                    TestTemplate(),\n                    Factory.Code(\")\\r\\n\").AsStatement(),\n                    Factory.MetaCode(\"End Code\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockHandlessTwoAnonymousSectionsInStatementWithinStatementBlock()\n        {\n            ParseBlockTest(\"Code\" + Environment.NewLine\n                         + \"    Dim foo = bar\" + Environment.NewLine\n                         + \"    Html.ExecuteTemplate(foo,\" + TestTemplateCode + \",\" + TestTemplateCode + \")\" + Environment.NewLine\n                         + \"End Code\",\n                new StatementBlock(\n                    Factory.MetaCode(\"Code\").Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"\\r\\n    Dim foo = bar\\r\\n    Html.ExecuteTemplate(foo,\")\n                           .AsStatement(),\n                    TestTemplate(),\n                    Factory.Code(\",\").AsStatement(),\n                    TestTemplate(),\n                    Factory.Code(\")\\r\\n\").AsStatement(),\n                    Factory.MetaCode(\"End Code\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockProducesErrorButCorrectlyParsesNestedAnonymousSectionInStatementWithinStatementBlock()\n        {\n            ParseBlockTest(\"Code\" + Environment.NewLine\n                         + \"    Dim foo = bar\" + Environment.NewLine\n                         + \"    Html.ExecuteTemplate(foo,\" + TestNestedTemplateCode + \")\" + Environment.NewLine\n                         + \"End Code\",\n                new StatementBlock(\n                    Factory.MetaCode(\"Code\").Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"\\r\\n    Dim foo = bar\\r\\n    Html.ExecuteTemplate(foo,\")\n                           .AsStatement(),\n                    TestNestedTemplate(),\n                    Factory.Code(\")\\r\\n\").AsStatement(),\n                    Factory.MetaCode(\"End Code\").Accepts(AcceptedCharacters.None)),\n                GetNestedSectionError(80, 2, 55));\n        }\n\n        private static RazorError GetNestedSectionError(int absoluteIndex, int lineIndex, int characterIndex)\n        {\n            return new RazorError(\n                RazorResources.ParseError_InlineMarkup_Blocks_Cannot_Be_Nested,\n                absoluteIndex, lineIndex, characterIndex);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/VB/VBToMarkupSwitchTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Editor;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Framework;\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser.VB\n{\n    public class VBToMarkupSwitchTest : VBHtmlCodeParserTestBase\n    {\n        [Fact]\n        public void ParseBlockSwitchesToMarkupWhenAtSignFollowedByLessThanInStatementBlock()\n        {\n            ParseBlockTest(\"Code\" + Environment.NewLine\n                         + \"    If True Then\" + Environment.NewLine\n                         + \"        @<p>It's True!</p>\" + Environment.NewLine\n                         + \"    End If\" + Environment.NewLine\n                         + \"End Code\",\n                new StatementBlock(\n                    Factory.MetaCode(\"Code\").Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"\\r\\n    If True Then\\r\\n\").AsStatement(),\n                    new MarkupBlock(\n                        Factory.Markup(\"        \"),\n                        Factory.MarkupTransition(),\n                        Factory.Markup(\"<p>It's True!</p>\\r\\n\").Accepts(AcceptedCharacters.None)),\n                    Factory.Code(\"    End If\\r\\n\").AsStatement(),\n                    Factory.MetaCode(\"End Code\").Accepts(AcceptedCharacters.None)));\n        }\n\n        [Fact]\n        public void ParseBlockGivesWhiteSpacePreceedingMarkupBlockToCodeInDesignTimeMode()\n        {\n            ParseBlockTest(\"Code\" + Environment.NewLine\n                         + \"    @<p>Foo</p>\" + Environment.NewLine\n                         + \"End Code\",\n                new StatementBlock(\n                    Factory.MetaCode(\"Code\").Accepts(AcceptedCharacters.None),\n                    Factory.Code(\"\\r\\n    \").AsStatement(),\n                    new MarkupBlock(\n                        Factory.MarkupTransition(),\n                        Factory.Markup(\"<p>Foo</p>\").Accepts(AcceptedCharacters.None)),\n                    Factory.Code(\"\\r\\n\").AsStatement(),\n                    Factory.MetaCode(\"End Code\").Accepts(AcceptedCharacters.None)),\n                designTimeParser: true);\n        }\n\n        [Theory]\n        [InlineData(\"While\", \"End While\", AcceptedCharacters.None)]\n        [InlineData(\"If\", \"End If\", AcceptedCharacters.None)]\n        [InlineData(\"Select\", \"End Select\", AcceptedCharacters.None)]\n        [InlineData(\"For\", \"Next\", AcceptedCharacters.WhiteSpace | AcceptedCharacters.NonWhiteSpace)]\n        [InlineData(\"Try\", \"End Try\", AcceptedCharacters.None)]\n        [InlineData(\"With\", \"End With\", AcceptedCharacters.None)]\n        [InlineData(\"Using\", \"End Using\", AcceptedCharacters.None)]\n        public void SimpleMarkupSwitch(string keyword, string endSequence, AcceptedCharacters acceptedCharacters)\n        {\n            ParseBlockTest(keyword + Environment.NewLine\n                         + \"    If True Then\" + Environment.NewLine\n                         + \"        @<p>It's True!</p>\" + Environment.NewLine\n                         + \"    End If\" + Environment.NewLine\n                         + endSequence,\n                new StatementBlock(\n                    Factory.Code(keyword + \"\\r\\n    If True Then\\r\\n\").AsStatement(),\n                    new MarkupBlock(\n                        Factory.Markup(\"        \"),\n                        Factory.MarkupTransition(),\n                        Factory.Markup(\"<p>It's True!</p>\\r\\n\").Accepts(AcceptedCharacters.None)),\n                    Factory.Code(\"    End If\\r\\n\" + endSequence).AsStatement().Accepts(acceptedCharacters)));\n        }\n\n        [Theory]\n        [InlineData(\"While\", \"End While\", AcceptedCharacters.None)]\n        [InlineData(\"If\", \"End If\", AcceptedCharacters.None)]\n        [InlineData(\"Select\", \"End Select\", AcceptedCharacters.None)]\n        [InlineData(\"For\", \"Next\", AcceptedCharacters.WhiteSpace | AcceptedCharacters.NonWhiteSpace)]\n        [InlineData(\"Try\", \"End Try\", AcceptedCharacters.None)]\n        [InlineData(\"With\", \"End With\", AcceptedCharacters.None)]\n        [InlineData(\"Using\", \"End Using\", AcceptedCharacters.None)]\n        public void SingleLineMarkupSwitch(string keyword, string endSequence, AcceptedCharacters acceptedCharacters)\n        {\n            ParseBlockTest(keyword + Environment.NewLine\n                         + \"    If True Then\" + Environment.NewLine\n                         + \"        @:<p>It's True!</p>\" + Environment.NewLine\n                         + \"        This is code!\" + Environment.NewLine\n                         + \"    End If\" + Environment.NewLine\n                         + endSequence,\n                new StatementBlock(\n                    Factory.Code(keyword + \"\\r\\n    If True Then\\r\\n\").AsStatement(),\n                    new MarkupBlock(\n                        Factory.Markup(\"        \"),\n                        Factory.MarkupTransition(),\n                        Factory.MetaMarkup(\":\", HtmlSymbolType.Colon),\n                        Factory.Markup(\"<p>It's True!</p>\\r\\n\")\n                                .With(new SingleLineMarkupEditHandler(CSharpLanguageCharacteristics.Instance.TokenizeString))\n                                .Accepts(AcceptedCharacters.None)),\n                    Factory.Code(\"        This is code!\\r\\n    End If\\r\\n\" + endSequence)\n                            .AsStatement()\n                            .Accepts(acceptedCharacters)));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Parser/WhitespaceRewriterTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Test.Framework;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Parser\n{\n    public class WhitespaceRewriterTest\n    {\n        [Fact]\n        public void Constructor_Requires_NonNull_SymbolConverter()\n        {\n            Assert.ThrowsArgumentNull(() => new WhiteSpaceRewriter(null), \"markupSpanFactory\");\n        }\n\n        [Fact]\n        public void Rewrite_Moves_Whitespace_Preceeding_ExpressionBlock_To_Parent_Block()\n        {\n            // Arrange\n            var factory = SpanFactory.CreateCsHtml();\n            Block start = new MarkupBlock(\n                factory.Markup(\"test\"),\n                new ExpressionBlock(\n                    factory.Code(\"    \").AsExpression(),\n                    factory.CodeTransition(SyntaxConstants.TransitionString),\n                    factory.Code(\"foo\").AsExpression()\n                    ),\n                factory.Markup(\"test\")\n                );\n            WhiteSpaceRewriter rewriter = new WhiteSpaceRewriter(new HtmlMarkupParser().BuildSpan);\n\n            // Act\n            Block actual = rewriter.Rewrite(start);\n\n            factory.Reset();\n\n            // Assert\n            ParserTestBase.EvaluateParseTree(actual, new MarkupBlock(\n                                                         factory.Markup(\"test\"),\n                                                         factory.Markup(\"    \"),\n                                                         new ExpressionBlock(\n                                                             factory.CodeTransition(SyntaxConstants.TransitionString),\n                                                             factory.Code(\"foo\").AsExpression()\n                                                             ),\n                                                         factory.Markup(\"test\")\n                                                         ));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/RazorCodeLanguageTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test\n{\n    public class RazorCodeLanguageTest\n    {\n        [Fact]\n        public void ServicesPropertyContainsEntriesForCSharpCodeLanguageService()\n        {\n            // Assert\n            Assert.Equal(2, RazorCodeLanguage.Languages.Count);\n            Assert.IsType<CSharpRazorCodeLanguage>(RazorCodeLanguage.Languages[\"cshtml\"]);\n            Assert.IsType<VBRazorCodeLanguage>(RazorCodeLanguage.Languages[\"vbhtml\"]);\n        }\n\n        [Fact]\n        public void GetServiceByExtensionReturnsEntryMatchingExtensionWithoutPreceedingDot()\n        {\n            Assert.IsType<CSharpRazorCodeLanguage>(RazorCodeLanguage.GetLanguageByExtension(\"cshtml\"));\n        }\n\n        [Fact]\n        public void GetServiceByExtensionReturnsEntryMatchingExtensionWithPreceedingDot()\n        {\n            Assert.IsType<CSharpRazorCodeLanguage>(RazorCodeLanguage.GetLanguageByExtension(\".cshtml\"));\n        }\n\n        [Fact]\n        public void GetServiceByExtensionReturnsNullIfNoServiceForSpecifiedExtension()\n        {\n            Assert.Null(RazorCodeLanguage.GetLanguageByExtension(\"foobar\"));\n        }\n\n        [Fact]\n        public void MultipleCallsToGetServiceWithSameExtensionReturnSameObject()\n        {\n            // Arrange\n            RazorCodeLanguage expected = RazorCodeLanguage.GetLanguageByExtension(\"cshtml\");\n\n            // Act\n            RazorCodeLanguage actual = RazorCodeLanguage.GetLanguageByExtension(\"cshtml\");\n\n            // Assert\n            Assert.Same(expected, actual);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/RazorDirectiveAttributeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test\n{\n    public class RazorDirectiveAttributeTest\n    {\n        [Fact]\n        public void ConstructorThrowsIfNameIsNullOrEmpty()\n        {\n            // Act and Assert\n            Assert.ThrowsArgumentNullOrEmptyString(() => new RazorDirectiveAttribute(name: null, value: \"blah\"), \"name\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => new RazorDirectiveAttribute(name: \"\", value: \"blah\"), \"name\");\n        }\n\n        [Fact]\n        public void EnsureRazorDirectiveProperties()\n        {\n            // Arrange\n            var attribute = (AttributeUsageAttribute)typeof(RazorDirectiveAttribute).GetCustomAttributes(typeof(AttributeUsageAttribute), inherit: false)\n                                                                                     .SingleOrDefault();\n\n            // Assert\n            Assert.True(attribute.AllowMultiple);\n            Assert.Equal(AttributeTargets.Class, attribute.ValidOn);\n            Assert.True(attribute.Inherited);\n        }\n\n        [Fact]\n        public void EqualsAndGetHashCodeIgnoresCase()\n        {\n            // Arrange\n            var attribute1 = new RazorDirectiveAttribute(\"foo\", \"bar\");\n            var attribute2 = new RazorDirectiveAttribute(\"fOo\", \"BAr\");\n\n            // Act\n            var hashCode1 = attribute1.GetHashCode();\n            var hashCode2 = attribute2.GetHashCode();\n\n            // Assert\n            Assert.Equal(attribute1, attribute2);\n            Assert.Equal(hashCode1, hashCode2);\n        }\n\n        [Fact]\n        public void EqualsAndGetHashCodeDoNotThrowIfValueIsNullOrEmpty()\n        {\n            // Arrange\n            var attribute1 = new RazorDirectiveAttribute(\"foo\", null);\n            var attribute2 = new RazorDirectiveAttribute(\"foo\", \"BAr\");\n\n            // Act\n            bool result = attribute1.Equals(attribute2);\n            var hashCode = attribute1.GetHashCode();\n\n            // Assert\n            Assert.False(result);\n            // If we've got this far, GetHashCode did not throw\n        }\n\n        [Fact]\n        public void EqualsAndGetHashCodeReturnDifferentValuesForNullAndEmpty()\n        {\n            // Arrange\n            var attribute1 = new RazorDirectiveAttribute(\"foo\", null);\n            var attribute2 = new RazorDirectiveAttribute(\"foo\", \"\");\n\n            // Act\n            bool result = attribute1.Equals(attribute2);\n            var hashCode1 = attribute1.GetHashCode();\n            var hashCode2 = attribute2.GetHashCode();\n\n            // Assert\n            Assert.False(result);\n            Assert.NotEqual(hashCode1, hashCode2);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/RazorEngineHostTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test\n{\n    public class RazorEngineHostTest\n    {\n        [Fact]\n        public void ConstructorRequiresNonNullCodeLanguage()\n        {\n            Assert.ThrowsArgumentNull(() => new RazorEngineHost(null), \"codeLanguage\");\n            Assert.ThrowsArgumentNull(() => new RazorEngineHost(null, () => new HtmlMarkupParser()), \"codeLanguage\");\n        }\n\n        [Fact]\n        public void ConstructorRequiresNonNullMarkupParser()\n        {\n            Assert.ThrowsArgumentNull(() => new RazorEngineHost(new CSharpRazorCodeLanguage(), null), \"markupParserFactory\");\n        }\n\n        [Fact]\n        public void ConstructorWithCodeLanguageSetsPropertiesAppropriately()\n        {\n            // Arrange\n            RazorCodeLanguage language = new CSharpRazorCodeLanguage();\n\n            // Act\n            RazorEngineHost host = new RazorEngineHost(language);\n\n            // Assert\n            VerifyCommonDefaults(host);\n            Assert.Same(language, host.CodeLanguage);\n            Assert.IsType<HtmlMarkupParser>(host.CreateMarkupParser());\n        }\n\n        [Fact]\n        public void ConstructorWithCodeLanguageAndMarkupParserSetsPropertiesAppropriately()\n        {\n            // Arrange\n            RazorCodeLanguage language = new CSharpRazorCodeLanguage();\n            ParserBase expected = new HtmlMarkupParser();\n\n            // Act\n            RazorEngineHost host = new RazorEngineHost(language, () => expected);\n\n            // Assert\n            VerifyCommonDefaults(host);\n            Assert.Same(language, host.CodeLanguage);\n            Assert.Same(expected, host.CreateMarkupParser());\n        }\n\n        [Fact]\n        public void DecorateCodeParserRequiresNonNullCodeParser()\n        {\n            Assert.ThrowsArgumentNull(() => CreateHost().DecorateCodeParser(null), \"incomingCodeParser\");\n        }\n\n        [Fact]\n        public void DecorateMarkupParserRequiresNonNullMarkupParser()\n        {\n            Assert.ThrowsArgumentNull(() => CreateHost().DecorateMarkupParser(null), \"incomingMarkupParser\");\n        }\n\n        [Fact]\n        public void DecorateCodeGeneratorRequiresNonNullCodeGenerator()\n        {\n            Assert.ThrowsArgumentNull(() => CreateHost().DecorateCodeGenerator(null), \"incomingCodeGenerator\");\n        }\n\n        [Fact]\n        public void PostProcessGeneratedCodeRequiresNonNullCompileUnit()\n        {\n            Assert.ThrowsArgumentNull(() => CreateHost().PostProcessGeneratedCode(codeCompileUnit: null,\n                                                                                      generatedNamespace: new CodeNamespace(),\n                                                                                      generatedClass: new CodeTypeDeclaration(),\n                                                                                      executeMethod: new CodeMemberMethod()),\n                                          \"codeCompileUnit\");\n        }\n\n        [Fact]\n        public void PostProcessGeneratedCodeRequiresNonNullGeneratedNamespace()\n        {\n            Assert.ThrowsArgumentNull(() => CreateHost().PostProcessGeneratedCode(codeCompileUnit: new CodeCompileUnit(),\n                                                                                      generatedNamespace: null,\n                                                                                      generatedClass: new CodeTypeDeclaration(),\n                                                                                      executeMethod: new CodeMemberMethod()),\n                                          \"generatedNamespace\");\n        }\n\n        [Fact]\n        public void PostProcessGeneratedCodeRequiresNonNullGeneratedClass()\n        {\n            Assert.ThrowsArgumentNull(() => CreateHost().PostProcessGeneratedCode(codeCompileUnit: new CodeCompileUnit(),\n                                                                                      generatedNamespace: new CodeNamespace(),\n                                                                                      generatedClass: null,\n                                                                                      executeMethod: new CodeMemberMethod()),\n                                          \"generatedClass\");\n        }\n\n        [Fact]\n        public void PostProcessGeneratedCodeRequiresNonNullExecuteMethod()\n        {\n            Assert.ThrowsArgumentNull(() => CreateHost().PostProcessGeneratedCode(codeCompileUnit: new CodeCompileUnit(),\n                                                                                      generatedNamespace: new CodeNamespace(),\n                                                                                      generatedClass: new CodeTypeDeclaration(),\n                                                                                      executeMethod: null),\n                                          \"executeMethod\");\n        }\n\n        [Fact]\n        public void DecorateCodeParserDoesNotModifyIncomingParser()\n        {\n            // Arrange\n            ParserBase expected = new CSharpCodeParser();\n\n            // Act\n            ParserBase actual = CreateHost().DecorateCodeParser(expected);\n\n            // Assert\n            Assert.Same(expected, actual);\n        }\n\n        [Fact]\n        public void DecorateMarkupParserReturnsIncomingParser()\n        {\n            // Arrange\n            ParserBase expected = new HtmlMarkupParser();\n\n            // Act\n            ParserBase actual = CreateHost().DecorateMarkupParser(expected);\n\n            // Assert\n            Assert.Same(expected, actual);\n        }\n\n        [Fact]\n        public void DecorateCodeGeneratorReturnsIncomingCodeGenerator()\n        {\n            // Arrange\n            RazorCodeGenerator expected = new CSharpRazorCodeGenerator(\"Foo\", \"Bar\", \"Baz\", CreateHost());\n\n            // Act\n            RazorCodeGenerator actual = CreateHost().DecorateCodeGenerator(expected);\n\n            // Assert\n            Assert.Same(expected, actual);\n        }\n\n        [Fact]\n        public void PostProcessGeneratedCodeDoesNotModifyCode()\n        {\n            // Arrange\n            CodeCompileUnit compileUnit = new CodeCompileUnit();\n            CodeNamespace ns = new CodeNamespace();\n            CodeTypeDeclaration typeDecl = new CodeTypeDeclaration();\n            CodeMemberMethod execMethod = new CodeMemberMethod();\n\n            // Act\n            CreateHost().PostProcessGeneratedCode(compileUnit, ns, typeDecl, execMethod);\n\n            // Assert\n            Assert.Empty(compileUnit.Namespaces);\n            Assert.Empty(ns.Imports);\n            Assert.Empty(ns.Types);\n            Assert.Empty(typeDecl.Members);\n            Assert.Empty(execMethod.Statements);\n        }\n\n        private static RazorEngineHost CreateHost()\n        {\n            return new RazorEngineHost(new CSharpRazorCodeLanguage());\n        }\n\n        private static void VerifyCommonDefaults(RazorEngineHost host)\n        {\n            Assert.Equal(GeneratedClassContext.Default, host.GeneratedClassContext);\n            Assert.Empty(host.NamespaceImports);\n            Assert.False(host.DesignTimeMode);\n            Assert.Equal(RazorEngineHost.InternalDefaultClassName, host.DefaultClassName);\n            Assert.Equal(RazorEngineHost.InternalDefaultNamespace, host.DefaultNamespace);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/RazorTemplateEngineTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Threading;\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing System.Web.Razor.Text;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Razor.Test\n{\n    public class RazorTemplateEngineTest\n    {\n        [Fact]\n        public void ConstructorRequiresNonNullHost()\n        {\n            Assert.ThrowsArgumentNull(() => new RazorTemplateEngine(null), \"host\");\n        }\n\n        [Fact]\n        public void ConstructorInitializesHost()\n        {\n            // Arrange\n            RazorEngineHost host = new RazorEngineHost(new CSharpRazorCodeLanguage());\n\n            // Act\n            RazorTemplateEngine engine = new RazorTemplateEngine(host);\n\n            // Assert\n            Assert.Same(host, engine.Host);\n        }\n\n        [Fact]\n        public void CreateParserMethodIsConstructedFromHost()\n        {\n            // Arrange\n            RazorEngineHost host = CreateHost();\n            RazorTemplateEngine engine = new RazorTemplateEngine(host);\n\n            // Act\n            RazorParser parser = engine.CreateParser();\n\n            // Assert\n            Assert.IsType<CSharpCodeParser>(parser.CodeParser);\n            Assert.IsType<HtmlMarkupParser>(parser.MarkupParser);\n        }\n\n        [Fact]\n        public void CreateParserMethodSetsParserContextToDesignTimeModeIfHostSetToDesignTimeMode()\n        {\n            // Arrange\n            RazorEngineHost host = CreateHost();\n            RazorTemplateEngine engine = new RazorTemplateEngine(host);\n            host.DesignTimeMode = true;\n\n            // Act\n            RazorParser parser = engine.CreateParser();\n\n            // Assert\n            Assert.True(parser.DesignTimeMode);\n        }\n\n        [Fact]\n        public void CreateParserMethodPassesParsersThroughDecoratorMethodsOnHost()\n        {\n            // Arrange\n            ParserBase expectedCode = new Mock<ParserBase>().Object;\n            ParserBase expectedMarkup = new Mock<ParserBase>().Object;\n\n            var mockHost = new Mock<RazorEngineHost>(new CSharpRazorCodeLanguage()) { CallBase = true };\n            mockHost.Setup(h => h.DecorateCodeParser(It.IsAny<CSharpCodeParser>()))\n                .Returns(expectedCode);\n            mockHost.Setup(h => h.DecorateMarkupParser(It.IsAny<HtmlMarkupParser>()))\n                .Returns(expectedMarkup);\n            RazorTemplateEngine engine = new RazorTemplateEngine(mockHost.Object);\n\n            // Act\n            RazorParser actual = engine.CreateParser();\n\n            // Assert\n            Assert.Equal(expectedCode, actual.CodeParser);\n            Assert.Equal(expectedMarkup, actual.MarkupParser);\n        }\n\n        [Fact]\n        public void CreateCodeGeneratorMethodPassesCodeGeneratorThroughDecorateMethodOnHost()\n        {\n            // Arrange\n            var mockHost = new Mock<RazorEngineHost>(new CSharpRazorCodeLanguage()) { CallBase = true };\n\n            RazorCodeGenerator expected = new Mock<RazorCodeGenerator>(\"Foo\", \"Bar\", \"Baz\", mockHost.Object).Object;\n\n            mockHost.Setup(h => h.DecorateCodeGenerator(It.IsAny<CSharpRazorCodeGenerator>()))\n                .Returns(expected);\n            RazorTemplateEngine engine = new RazorTemplateEngine(mockHost.Object);\n\n            // Act\n            RazorCodeGenerator actual = engine.CreateCodeGenerator(\"Foo\", \"Bar\", \"Baz\");\n\n            // Assert\n            Assert.Equal(expected, actual);\n        }\n\n        [Fact]\n        public void ParseTemplateCopiesTextReaderContentToSeekableTextReaderAndPassesToParseTemplateCore()\n        {\n            // Arrange\n            Mock<RazorTemplateEngine> mockEngine = new Mock<RazorTemplateEngine>(CreateHost());\n            TextReader reader = new StringReader(\"foo\");\n            CancellationTokenSource source = new CancellationTokenSource();\n\n            // Act\n            mockEngine.Object.ParseTemplate(reader, cancelToken: source.Token);\n\n            // Assert\n            mockEngine.Verify(e => e.ParseTemplateCore(It.Is<SeekableTextReader>(l => l.ReadToEnd() == \"foo\"),\n                                                       source.Token));\n        }\n\n        [Fact]\n        public void GenerateCodeCopiesTextReaderContentToSeekableTextReaderAndPassesToGenerateCodeCore()\n        {\n            // Arrange\n            Mock<RazorTemplateEngine> mockEngine = new Mock<RazorTemplateEngine>(CreateHost());\n            TextReader reader = new StringReader(\"foo\");\n            CancellationTokenSource source = new CancellationTokenSource();\n            string className = \"Foo\";\n            string ns = \"Bar\";\n            string src = \"Baz\";\n\n            // Act\n            mockEngine.Object.GenerateCode(reader, className: className, rootNamespace: ns, sourceFileName: src, cancelToken: source.Token);\n\n            // Assert\n            mockEngine.Verify(e => e.GenerateCodeCore(It.Is<SeekableTextReader>(l => l.ReadToEnd() == \"foo\"),\n                                                      className, ns, src, source.Token));\n        }\n\n        [Fact]\n        public void ParseTemplateOutputsResultsOfParsingProvidedTemplateSource()\n        {\n            // Arrange\n            RazorTemplateEngine engine = new RazorTemplateEngine(CreateHost());\n\n            // Act\n            ParserResults results = engine.ParseTemplate(new StringTextBuffer(\"foo @bar(\"));\n\n            // Assert\n            Assert.False(results.Success);\n            Assert.Single(results.ParserErrors);\n            Assert.NotNull(results.Document);\n        }\n\n        [Fact]\n        public void GenerateOutputsResultsOfParsingAndGeneration()\n        {\n            // Arrange\n            RazorTemplateEngine engine = new RazorTemplateEngine(CreateHost());\n\n            // Act\n            GeneratorResults results = engine.GenerateCode(new StringTextBuffer(\"foo @bar(\"));\n\n            // Assert\n            Assert.False(results.Success);\n            Assert.Single(results.ParserErrors);\n            Assert.NotNull(results.Document);\n            Assert.NotNull(results.GeneratedCode);\n            Assert.Null(results.DesignTimeLineMappings);\n        }\n\n        [Fact]\n        public void GenerateOutputsDesignTimeMappingsIfDesignTimeSetOnHost()\n        {\n            // Arrange\n            RazorTemplateEngine engine = new RazorTemplateEngine(CreateHost(designTime: true));\n\n            // Act\n            GeneratorResults results = engine.GenerateCode(new StringTextBuffer(\"foo @bar()\"), className: null, rootNamespace: null, sourceFileName: \"foo.cshtml\");\n\n            // Assert\n            Assert.True(results.Success);\n            Assert.Empty(results.ParserErrors);\n            Assert.NotNull(results.Document);\n            Assert.NotNull(results.GeneratedCode);\n            Assert.NotNull(results.DesignTimeLineMappings);\n        }\n\n        private static RazorEngineHost CreateHost(bool designTime = false)\n        {\n            return new RazorEngineHost(new CSharpRazorCodeLanguage())\n            {\n                DesignTimeMode = designTime\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/StringTextBuffer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Text;\n\nnamespace System.Web.WebPages.TestUtils\n{\n    public class StringTextBuffer : ITextBuffer, IDisposable\n    {\n        private string _buffer;\n        public bool Disposed { get; set; }\n\n        public StringTextBuffer(string buffer)\n        {\n            _buffer = buffer;\n        }\n\n        public int Length\n        {\n            get { return _buffer.Length; }\n        }\n\n        public int Position { get; set; }\n\n        public int Read()\n        {\n            if (Position >= _buffer.Length)\n            {\n                return -1;\n            }\n            return _buffer[Position++];\n        }\n\n        public int Peek()\n        {\n            if (Position >= _buffer.Length)\n            {\n                return -1;\n            }\n            return _buffer[Position];\n        }\n\n        public void Dispose()\n        {\n            Disposed = true;\n        }\n\n        public object VersionToken\n        {\n            get { return _buffer; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/System.Web.Razor.Test.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props\" Condition=\"Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" />\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" />\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{0BB62A1D-E6B5-49FA-9E3C-6AF679A66DFE}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>System.Web.Razor.Test</RootNamespace>\n    <AssemblyName>System.Web.Razor.Test</AssemblyName>\n    <OutputPath>..\\..\\bin\\$(Configuration)\\Test\\</OutputPath>\n    <NoWarn>0618</NoWarn>\n    <NuGetPackageImportStamp>\n    </NuGetPackageImportStamp>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Castle.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Castle.Core.5.1.1\\lib\\net462\\Castle.Core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"Moq, Version=4.18.0.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Moq.4.18.4\\lib\\net462\\Moq.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Core\">\n      <RequiredTargetFramework>3.5</RequiredTargetFramework>\n    </Reference>\n    <Reference Include=\"xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.abstractions.2.0.3\\lib\\net35\\xunit.abstractions.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.assert, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.assert.2.4.2\\lib\\netstandard1.1\\xunit.assert.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.core, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.core.2.4.2\\lib\\net452\\xunit.core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.execution.desktop, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.execution.2.4.2\\lib\\net452\\xunit.execution.desktop.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Analyzer Include=\"..\\..\\packages\\xunit.analyzers.1.1.0\\analyzers\\dotnet\\cs\\xunit.analyzers.dll\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"CodeCompileUnitExtensions.cs\" />\n    <Compile Include=\"Framework\\BlockExtensions.cs\" />\n    <Compile Include=\"Framework\\BlockTypes.cs\" />\n    <Compile Include=\"Framework\\CodeParserTestBase.cs\" />\n    <Compile Include=\"Framework\\CsHtmlCodeParserTestBase.cs\" />\n    <Compile Include=\"Framework\\CsHtmlMarkupParserTestBase.cs\" />\n    <Compile Include=\"Framework\\ErrorCollector.cs\" />\n    <Compile Include=\"Framework\\MarkupParserTestBase.cs\" />\n    <Compile Include=\"Framework\\ParserTestBase.cs\" />\n    <Compile Include=\"Framework\\RawTextSymbol.cs\" />\n    <Compile Include=\"Framework\\TestSpanBuilder.cs\" />\n    <Compile Include=\"Framework\\VBHtmlCodeParserTestBase.cs\" />\n    <Compile Include=\"Framework\\VBHtmlMarkupParserTestBase.cs\" />\n    <Compile Include=\"Generator\\GeneratedCodeMappingTest.cs\" />\n    <Compile Include=\"Generator\\PaddingTest.cs\" />\n    <Compile Include=\"Generator\\TabTest.cs\" />\n    <Compile Include=\"Generator\\TestSpan.cs\" />\n    <Compile Include=\"Parser\\CSharp\\CSharpAutoCompleteTest.cs\" />\n    <Compile Include=\"Parser\\CSharp\\CSharpDirectivesTest.cs\" />\n    <Compile Include=\"Parser\\CSharp\\CSharpLayoutDirectiveTest.cs\" />\n    <Compile Include=\"Parser\\CSharp\\CSharpNestedStatementsTest.cs\" />\n    <Compile Include=\"Parser\\CSharp\\CSharpRazorCommentsTest.cs\" />\n    <Compile Include=\"Parser\\CSharp\\CSharpStatementTest.cs\" />\n    <Compile Include=\"Parser\\CSharp\\CSharpTemplateTest.cs\" />\n    <Compile Include=\"Parser\\CSharp\\CSharpToMarkupSwitchTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"Parser\\CSharp\\CSharpVerbatimBlockTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"Parser\\CSharp\\CSharpWhitespaceHandlingTest.cs\" />\n    <Compile Include=\"Parser\\CSharp\\CsHtmlDocumentTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"Parser\\Html\\HtmlAttributeTest.cs\" />\n    <Compile Include=\"Parser\\Html\\HtmlUrlAttributeTest.cs\" />\n    <Compile Include=\"Parser\\ParserVisitorExtensionsTest.cs\" />\n    <Compile Include=\"Parser\\VB\\VBRazorCommentsTest.cs\" />\n    <Compile Include=\"Parser\\VB\\VBLayoutDirectiveTest.cs\" />\n    <Compile Include=\"Parser\\VB\\VBAutoCompleteTest.cs\" />\n    <Compile Include=\"Parser\\Html\\HtmlTagsTest.cs\" />\n    <Compile Include=\"Parser\\VB\\VBContinueStatementTest.cs\" />\n    <Compile Include=\"Parser\\VB\\VBDirectiveTest.cs\" />\n    <Compile Include=\"Parser\\VB\\VBExitStatementTest.cs\" />\n    <Compile Include=\"Parser\\VB\\VBExplicitExpressionTest.cs\" />\n    <Compile Include=\"Parser\\VB\\VBImplicitExpressionTest.cs\" />\n    <Compile Include=\"Parser\\VB\\VBReservedWordsTest.cs\" />\n    <Compile Include=\"Parser\\CSharp\\CSharpReservedWordsTest.cs\" />\n    <Compile Include=\"Parser\\PartialParsing\\VBPartialParsingTest.cs\" />\n    <Compile Include=\"Parser\\PartialParsing\\CSharpPartialParsingTest.cs\" />\n    <Compile Include=\"Parser\\VB\\VBHelperTest.cs\" />\n    <Compile Include=\"Parser\\CSharp\\CSharpHelperTest.cs\" />\n    <Compile Include=\"Generator\\RazorCodeGeneratorTest.cs\" />\n    <Compile Include=\"Parser\\PartialParsing\\PartialParsingTestBase.cs\" />\n    <Compile Include=\"Parser\\VB\\VBNestedStatementsTest.cs\" />\n    <Compile Include=\"Parser\\VB\\VBStatementTest.cs\" />\n    <Compile Include=\"Parser\\WhitespaceRewriterTest.cs\" />\n    <Compile Include=\"RazorCodeLanguageTest.cs\" />\n    <Compile Include=\"Parser\\VB\\VBHtmlDocumentTest.cs\" />\n    <Compile Include=\"Parser\\VB\\VBErrorTest.cs\" />\n    <Compile Include=\"Parser\\VB\\VBSectionTest.cs\" />\n    <Compile Include=\"Parser\\VB\\VBTemplateTest.cs\" />\n    <Compile Include=\"Parser\\VB\\VBExpressionsInCodeTest.cs\" />\n    <Compile Include=\"Parser\\VB\\VBSpecialKeywordsTest.cs\" />\n    <Compile Include=\"Parser\\VB\\VBBlockTest.cs\" />\n    <Compile Include=\"Parser\\VB\\VBToMarkupSwitchTest.cs\" />\n    <Compile Include=\"Editor\\RazorEditorParserTest.cs\" />\n    <Compile Include=\"RazorDirectiveAttributeTest.cs\" />\n    <Compile Include=\"RazorEngineHostTest.cs\" />\n    <Compile Include=\"RazorTemplateEngineTest.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\Blocks.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\CodeBlock.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\CodeBlockAtEOF.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\Comments.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\ConditionalAttributes.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\DesignTime.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\EmptyCodeBlock.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\EmptyExplicitExpression.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\EmptyImplicitExpression.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\EmptyImplicitExpressionInCode.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\ExplicitExpression.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\ExplicitExpressionAtEOF.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\ExpressionsInCode.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\FunctionsBlock.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\FunctionsBlock.DesignTime.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\Helpers.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\Helpers.Instance.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\HelpersMissingCloseParen.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\HelpersMissingName.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\HelpersMissingOpenBrace.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\HelpersMissingOpenParen.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\HiddenSpansInCode.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\ImplicitExpression.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\ImplicitExpressionAtEOF.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\Imports.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\Imports.DesignTime.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\Inherits.Designtime.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\Inherits.Runtime.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\InlineBlocks.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\Instrumented.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\LayoutDirective.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\MarkupInCodeBlock.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\NestedCodeBlocks.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\NestedHelpers.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\NoLinePragmas.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\ParserError.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\RazorComments.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\ResolveUrl.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\Sections.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\Templates.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\UnfinishedExpressionInCode.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\RazorComments.DesignTime.cs\" />\n    <Compile Include=\"StringTextBuffer.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\OpenedIf.DesignTime.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\OpenedIf.DesignTime.Tabs.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\UnfinishedExpressionInCode.Tabs.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\EmptyImplicitExpressionInCode.Tabs.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\DesignTime.Tabs.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\FunctionsBlock.DesignTime.Tabs.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\FunctionsBlock_Tabs.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\FunctionsBlockMinimal.DesignTime.Tabs.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\SimpleUnspacedIf.DesignTime.Tabs.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\HtmlCommentWithQuote_Single.cs\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Output\\HtmlCommentWithQuote_Double.cs\" />\n    <Compile Include=\"Text\\LineTrackingStringBufferTest.cs\" />\n    <Compile Include=\"Tokenizer\\VBTokenizerLiteralTest.cs\" />\n    <Compile Include=\"Tokenizer\\VBTokenizerIdentifierTest.cs\" />\n    <Compile Include=\"Tokenizer\\VBTokenizerCommentTest.cs\" />\n    <Compile Include=\"Tokenizer\\VBTokenizerOperatorsTest.cs\" />\n    <Compile Include=\"Tokenizer\\VBTokenizerTestBase.cs\" />\n    <Compile Include=\"Tokenizer\\VBTokenizerTest.cs\" />\n    <Compile Include=\"Tokenizer\\CSharpTokenizerCommentTest.cs\" />\n    <Compile Include=\"Tokenizer\\CSharpTokenizerLiteralTest.cs\" />\n    <Compile Include=\"Tokenizer\\CSharpTokenizerIdentifierTest.cs\" />\n    <Compile Include=\"Tokenizer\\CSharpTokenizerOperatorsTest.cs\" />\n    <Compile Include=\"Tokenizer\\CSharpTokenizerTestBase.cs\" />\n    <Compile Include=\"Tokenizer\\CSharpTokenizerTest.cs\" />\n    <Compile Include=\"Tokenizer\\TokenizerLookaheadTest.cs\" />\n    <Compile Include=\"Tokenizer\\HtmlTokenizerTest.cs\" />\n    <Compile Include=\"Tokenizer\\HtmlTokenizerTestBase.cs\" />\n    <Compile Include=\"Tokenizer\\TokenizerTestBase.cs\" />\n    <Compile Include=\"Utils\\MiscUtils.cs\" />\n    <Compile Include=\"Generator\\VBRazorCodeGeneratorTest.cs\" />\n    <Compile Include=\"Generator\\CSharpRazorCodeGeneratorTest.cs\" />\n    <Compile Include=\"CSharpRazorCodeLanguageTest.cs\" />\n    <Compile Include=\"Parser\\CallbackParserListenerTest.cs\" />\n    <Compile Include=\"Parser\\CSharp\\CSharpExplicitExpressionTest.cs\" />\n    <Compile Include=\"Parser\\CSharp\\CSharpSectionTest.cs\" />\n    <Compile Include=\"Parser\\BlockTest.cs\" />\n    <Compile Include=\"Parser\\VB\\VBExpressionTest.cs\" />\n    <Compile Include=\"Text\\BufferingTextReaderTest.cs\" />\n    <Compile Include=\"Parser\\CSharp\\CSharpErrorTest.cs\" />\n    <Compile Include=\"Parser\\CSharp\\CSharpImplicitExpressionTest.cs\" />\n    <Compile Include=\"Parser\\CSharp\\CSharpSpecialBlockTest.cs\" />\n    <Compile Include=\"Parser\\Html\\HtmlBlockTest.cs\" />\n    <Compile Include=\"Parser\\CSharp\\CSharpBlockTest.cs\" />\n    <Compile Include=\"Text\\LookaheadTextReaderTestBase.cs\" />\n    <Compile Include=\"Text\\SourceLocationTrackerTest.cs\" />\n    <Compile Include=\"Text\\TextBufferReaderTest.cs\" />\n    <Compile Include=\"Utils\\DisposableActionTest.cs\" />\n    <Compile Include=\"Parser\\Html\\HtmlDocumentTest.cs\" />\n    <Compile Include=\"Parser\\ParserContextTest.cs\" />\n    <Compile Include=\"Parser\\Html\\HtmlErrorTest.cs\" />\n    <Compile Include=\"Parser\\Html\\HtmlParserTestUtils.cs\" />\n    <Compile Include=\"Parser\\Html\\HtmlToCodeSwitchTest.cs\" />\n    <Compile Include=\"Parser\\RazorParserTest.cs\" />\n    <Compile Include=\"Text\\SourceLocationTest.cs\" />\n    <Compile Include=\"Utils\\SpanAssert.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"VBRazorCodeLanguageTest.cs\" />\n    <Compile Include=\"Text\\TextChangeTest.cs\" />\n    <Compile Include=\"Text\\TextReaderExtensionsTest.cs\" />\n    <Compile Include=\"Utils\\EnumerableUtils.cs\" />\n    <Compile Include=\"Utils\\MiscAssert.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Razor\\System.Web.Razor.csproj\">\n      <Project>{8F18041B-9410-4C36-A9C5-067813DF5F31}</Project>\n      <Name>System.Web.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\">\n      <Project>{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}</Project>\n      <Name>Microsoft.TestCommon</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\nested-1000.html\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Service Include=\"{508349B6-6B84-4DF5-91F0-309BEEBAD82D}\" />\n    <Service Include=\"{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\CodeBlock.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\ExplicitExpression.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\MarkupInCodeBlock.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\Blocks.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\ImplicitExpression.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\NoLinePragmas.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\Imports.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\ExpressionsInCode.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\FunctionsBlock.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\Options.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\Templates.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\Sections.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\DesignTime.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\Templates.cshtml\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\Blocks.cshtml\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\CodeBlock.cshtml\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\NoLinePragmas.cshtml\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\ExplicitExpression.cshtml\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\ImplicitExpression.cshtml\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\Imports.cshtml\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\MarkupInCodeBlock.cshtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\DesignTime.cshtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\ExpressionsInCode.cshtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\FunctionsBlock.cshtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\Sections.cshtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\Inherits.cshtml\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\Inherits.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\NestedHelpers.cshtml\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\NestedHelpers.vbhtml\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\Instrumented.cshtml\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\Instrumented.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\RazorComments.cshtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\RazorComments.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\ParserError.cshtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\ParserError.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\ImplicitExpressionAtEOF.cshtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\CodeBlockAtEOF.cshtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\ExplicitExpressionAtEOF.cshtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\EmptyCodeBlock.cshtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\EmptyExplicitExpression.cshtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\EmptyImplicitExpression.cshtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\CodeBlockAtEOF.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\EmptyExplicitExpression.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\EmptyImplicitExpression.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\ExplicitExpressionAtEOF.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\ImplicitExpressionAtEOF.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\UnfinishedExpressionInCode.cshtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\UnfinishedExpressionInCode.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\DesignTime\\Simple.cshtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\DesignTime\\Simple.txt\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\Helpers.cshtml\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\HelpersMissingCloseParen.cshtml\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\HelpersMissingName.cshtml\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\HelpersMissingOpenBrace.cshtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\HelpersMissingOpenParen.cshtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\HelpersMissingOpenParen.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\Helpers.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\HelpersMissingCloseParen.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\HelpersMissingName.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\NestedCodeBlocks.cshtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\NestedCodeBlocks.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\InlineBlocks.cshtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\EmptyImplicitExpressionInCode.cshtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\EmptyImplicitExpressionInCode.vbhtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\HiddenSpansInCode.cshtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\ResolveUrl.cshtml\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\ResolveUrl.vbhtml\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\LayoutDirective.cshtml\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\LayoutDirective.vbhtml\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\ConditionalAttributes.cshtml\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\ConditionalAttributes.vbhtml\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Source\\EmptySection.vbhtml\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\OpenedIf.cshtml\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\FunctionsBlock_Tabs.cshtml\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\FunctionsBlockMinimal.cshtml\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\SimpleUnspacedIf.cshtml\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\HtmlCommentWithQuote_Double.cshtml\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\CS\\Source\\HtmlCommentWithQuote_Single.cshtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\Blocks.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\CodeBlock.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\CodeBlockAtEOF.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\Comments.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\ConditionalAttributes.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\DesignTime.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\EmptyExplicitExpression.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\EmptyImplicitExpression.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\EmptyImplicitExpressionInCode.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\ExplicitExpression.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\ExplicitExpressionAtEOF.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\ExpressionsInCode.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\FunctionsBlock.DesignTime.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\FunctionsBlock.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\Helpers.Instance.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\Helpers.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\HelpersMissingCloseParen.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\HelpersMissingName.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\HelpersMissingOpenParen.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\ImplicitExpression.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\ImplicitExpressionAtEOF.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\Imports.DesignTime.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\Imports.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\Inherits.Designtime.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\Inherits.Runtime.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\Instrumented.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\LayoutDirective.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\MarkupInCodeBlock.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\NestedCodeBlocks.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\NestedHelpers.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\NoLinePragmas.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\Options.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\ParserError.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\RazorComments.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\ResolveUrl.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\Sections.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\Templates.vb\" />\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\UnfinishedExpressionInCode.vb\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\RazorComments.DesignTime.vb\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Folder Include=\"Properties\\\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\EmptySection.vb\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\CodeGenerator\\VB\\Output\\FunctionsBlock.DesignTime.Tabs.vb\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\n  <Target Name=\"EnsureNuGetPackageBuildImports\" BeforeTargets=\"PrepareForBuild\">\n    <PropertyGroup>\n      <ErrorText>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}.</ErrorText>\n    </PropertyGroup>\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props'))\" />\n  </Target>\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" />\n</Project>"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/Blocks.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class Blocks {\n#line hidden\npublic Blocks() {\n}\npublic override void Execute() {\n\n#line 1 \"Blocks.cshtml\"\n  \n    int i = 1;\n\n\n#line default\n#line hidden\nWriteLiteral(\"\\r\\n\\r\\n\");\n\n\n#line 5 \"Blocks.cshtml\"\n while(i <= 10) {\n\n\n#line default\n#line hidden\nWriteLiteral(\"    <p>Hello from C#, #\");\n\n\n#line 6 \"Blocks.cshtml\"\n                   Write(i);\n\n\n#line default\n#line hidden\nWriteLiteral(\"</p>\\r\\n\");\n\n\n#line 7 \"Blocks.cshtml\"\n    i += 1;\n}\n\n\n#line default\n#line hidden\nWriteLiteral(\"\\r\\n\");\n\n\n#line 10 \"Blocks.cshtml\"\n if(i == 11) {\n\n\n#line default\n#line hidden\nWriteLiteral(\"    <p>We wrote 10 lines!</p>\\r\\n\");\n\n\n#line 12 \"Blocks.cshtml\"\n}\n\n\n#line default\n#line hidden\nWriteLiteral(\"\\r\\n\");\n\n\n#line 14 \"Blocks.cshtml\"\n switch(i) {\n    case 11:\n\n\n#line default\n#line hidden\nWriteLiteral(\"        <p>No really, we wrote 10 lines!</p>\\r\\n\");\n\n\n#line 17 \"Blocks.cshtml\"\n        break;\n    default:\n\n\n#line default\n#line hidden\nWriteLiteral(\"        <p>Actually, we didn\\'t...</p>\\r\\n\");\n\n\n#line 20 \"Blocks.cshtml\"\n        break;\n}\n\n\n#line default\n#line hidden\nWriteLiteral(\"\\r\\n\");\n\n\n#line 23 \"Blocks.cshtml\"\n for(int j = 1; j <= 10; j += 2) {\n\n\n#line default\n#line hidden\nWriteLiteral(\"    <p>Hello again from C#, #\");\n\n\n#line 24 \"Blocks.cshtml\"\n                         Write(j);\n\n\n#line default\n#line hidden\nWriteLiteral(\"</p>\\r\\n\");\n\n\n#line 25 \"Blocks.cshtml\"\n}\n\n\n#line default\n#line hidden\nWriteLiteral(\"\\r\\n\");\n\n\n#line 27 \"Blocks.cshtml\"\n try {\n\n\n#line default\n#line hidden\nWriteLiteral(\"    <p>That time, we wrote 5 lines!</p>\\r\\n\");\n\n\n#line 29 \"Blocks.cshtml\"\n} catch(Exception ex) {\n\n\n#line default\n#line hidden\nWriteLiteral(\"    <p>Oh no! An error occurred: \");\n\n\n#line 30 \"Blocks.cshtml\"\n                             Write(ex.Message);\n\n\n#line default\n#line hidden\nWriteLiteral(\"</p>\\r\\n\");\n\n\n#line 31 \"Blocks.cshtml\"\n}\n\n\n#line default\n#line hidden\nWriteLiteral(\"\\r\\n<p>i is now \");\n\n\n#line 33 \"Blocks.cshtml\"\n       Write(i);\n\n\n#line default\n#line hidden\nWriteLiteral(\"</p>\\r\\n\\r\\n\");\n\n\n#line 35 \"Blocks.cshtml\"\n lock(new object()) {\n\n\n#line default\n#line hidden\nWriteLiteral(\"    <p>This block is locked, for your security!</p>\\r\\n\");\n\n\n#line 37 \"Blocks.cshtml\"\n}\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/CodeBlock.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class CodeBlock {\n#line hidden\npublic CodeBlock() {\n}\npublic override void Execute() {\n\n#line 1 \"CodeBlock.cshtml\"\n  \n    for(int i = 1; i <= 10; i++) {\n        Output.Write(\"<p>Hello from C#, #\" + i.ToString() + \"</p>\");\n    }\n\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/CodeBlockAtEOF.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class CodeBlockAtEOF {\n#line hidden\npublic CodeBlockAtEOF() {\n}\npublic override void Execute() {\n\n#line 1 \"CodeBlockAtEOF.cshtml\"\n  \n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/Comments.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class Comments {\npublic override void Execute() {\n\n\n#line 1 \"Comments.cshtml\"\n //This is not going to be rendered\n\n\n#line default\n#line hidden\nWriteLiteral(\"<p>This is going to be rendered</p>\\r\\n\");\n\n\n\n#line 3 \"Comments.cshtml\"\n /* Neither is this\n    nor this\n    nor this */\n\n#line default\n#line hidden\n\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/ConditionalAttributes.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class ConditionalAttributes {\n#line hidden\npublic ConditionalAttributes() {\n}\npublic override void Execute() {\n\n#line 1 \"ConditionalAttributes.cshtml\"\n  \n    var ch = true;\n    var cls = \"bar\";\n\n\n#line default\n#line hidden\nWriteLiteral(\"    <a\");\n\nWriteLiteral(\" href=\\\"Foo\\\"\");\n\nWriteLiteral(\" />\\r\\n\");\n\nWriteLiteral(\"    <p\");\n\nWriteAttribute(\"class\", Tuple.Create(\" class=\\\"\", 74), Tuple.Create(\"\\\"\", 86)\n\n#line 5 \"ConditionalAttributes.cshtml\"\n, Tuple.Create(Tuple.Create(\"\", 82), Tuple.Create<System.Object, System.Int32>(cls\n\n#line default\n#line hidden\n, 82), false)\n);\n\nWriteLiteral(\" />\\r\\n\");\n\nWriteLiteral(\"    <p\");\n\nWriteAttribute(\"class\", Tuple.Create(\" class=\\\"\", 98), Tuple.Create(\"\\\"\", 114)\n, Tuple.Create(Tuple.Create(\"\", 106), Tuple.Create(\"foo\", 106), true)\n\n#line 6 \"ConditionalAttributes.cshtml\"\n, Tuple.Create(Tuple.Create(\" \", 109), Tuple.Create<System.Object, System.Int32>(cls\n\n#line default\n#line hidden\n, 110), false)\n);\n\nWriteLiteral(\" />\\r\\n\");\n\nWriteLiteral(\"    <p\");\n\nWriteAttribute(\"class\", Tuple.Create(\" class=\\\"\", 126), Tuple.Create(\"\\\"\", 142)\n\n#line 7 \"ConditionalAttributes.cshtml\"\n, Tuple.Create(Tuple.Create(\"\", 134), Tuple.Create<System.Object, System.Int32>(cls\n\n#line default\n#line hidden\n, 134), false)\n, Tuple.Create(Tuple.Create(\" \", 138), Tuple.Create(\"foo\", 139), true)\n);\n\nWriteLiteral(\" />\\r\\n\");\n\nWriteLiteral(\"    <input\");\n\nWriteLiteral(\" type=\\\"checkbox\\\"\");\n\nWriteAttribute(\"checked\", Tuple.Create(\" checked=\\\"\", 174), Tuple.Create(\"\\\"\", 187)\n\n#line 8 \"ConditionalAttributes.cshtml\"\n, Tuple.Create(Tuple.Create(\"\", 184), Tuple.Create<System.Object, System.Int32>(ch\n\n#line default\n#line hidden\n, 184), false)\n);\n\nWriteLiteral(\" />\\r\\n\");\n\nWriteLiteral(\"    <input\");\n\nWriteLiteral(\" type=\\\"checkbox\\\"\");\n\nWriteAttribute(\"checked\", Tuple.Create(\" checked=\\\"\", 219), Tuple.Create(\"\\\"\", 236)\n, Tuple.Create(Tuple.Create(\"\", 229), Tuple.Create(\"foo\", 229), true)\n\n#line 9 \"ConditionalAttributes.cshtml\"\n, Tuple.Create(Tuple.Create(\" \", 232), Tuple.Create<System.Object, System.Int32>(ch\n\n#line default\n#line hidden\n, 233), false)\n);\n\nWriteLiteral(\" />\\r\\n\");\n\nWriteLiteral(\"    <p\");\n\nWriteAttribute(\"class\", Tuple.Create(\" class=\\\"\", 248), Tuple.Create(\"\\\"\", 281)\n, Tuple.Create(Tuple.Create(\"\", 256), Tuple.Create<System.Object, System.Int32>(new Template(__razor_attribute_value_writer => {\n\n\n#line 10 \"ConditionalAttributes.cshtml\"\n               if(cls != null) { \n\n#line default\n#line hidden\n\n#line 10 \"ConditionalAttributes.cshtml\"\nWriteTo(__razor_attribute_value_writer, cls);\n\n\n#line default\n#line hidden\n\n#line 10 \"ConditionalAttributes.cshtml\"\n                                      }\n\n#line default\n#line hidden\n}), 256), false)\n);\n\nWriteLiteral(\" />\\r\\n\");\n\nWriteLiteral(\"    <a\");\n\nWriteAttribute(\"href\", Tuple.Create(\" href=\\\"\", 293), Tuple.Create(\"\\\"\", 305)\n, Tuple.Create(Tuple.Create(\"\", 300), Tuple.Create<System.Object, System.Int32>(Href(\"~/Foo\")\n, 300), false)\n);\n\nWriteLiteral(\" />\\r\\n\");\n\nWriteLiteral(\"    <script\");\n\nWriteAttribute(\"src\", Tuple.Create(\" src=\\\"\", 322), Tuple.Create(\"\\\"\", 373)\n\n#line 12 \"ConditionalAttributes.cshtml\"\n, Tuple.Create(Tuple.Create(\"\", 328), Tuple.Create<System.Object, System.Int32>(Url.Content(\"~/Scripts/jquery-1.6.2.min.js\")\n\n#line default\n#line hidden\n, 328), false)\n);\n\nWriteLiteral(\" type=\\\"text/javascript\\\"\");\n\nWriteLiteral(\"></script>\\r\\n\");\n\nWriteLiteral(\"    <script\");\n\nWriteAttribute(\"src\", Tuple.Create(\" src=\\\"\", 420), Tuple.Create(\"\\\"\", 487)\n\n#line 13 \"ConditionalAttributes.cshtml\"\n, Tuple.Create(Tuple.Create(\"\", 426), Tuple.Create<System.Object, System.Int32>(Url.Content(\"~/Scripts/modernizr-2.0.6-development-only.js\")\n\n#line default\n#line hidden\n, 426), false)\n);\n\nWriteLiteral(\" type=\\\"text/javascript\\\"\");\n\nWriteLiteral(\"></script>\\r\\n\");\n\nWriteLiteral(\"    <script\");\n\nWriteLiteral(\" src=\\\"http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/jquery-ui.min.js\\\"\");\n\nWriteLiteral(\" type=\\\"text/javascript\\\"\");\n\nWriteLiteral(\"></script>\\r\\n\");\n\n\n#line 15 \"ConditionalAttributes.cshtml\"\n\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/DesignTime.Tabs.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class DesignTime {\nprivate static object @__o;\n#line hidden\n#line 9 \"DesignTime.cshtml\"\npublic static Template Foo() {\n#line default\n#line hidden\nreturn new Template(__razor_helper_writer => {\n\n#line 10 \"DesignTime.cshtml\"\n\t\t\t   \n    if(true) {\n        \n\n#line default\n#line hidden\n\n#line 11 \"DesignTime.cshtml\"\n\t\t\t\t  \n    }\n\n\n#line default\n#line hidden\n});\n\n#line 12 \"DesignTime.cshtml\"\n}\n#line default\n#line hidden\n\npublic DesignTime() {\n}\npublic override void Execute() {\n\n#line 1 \"DesignTime.cshtml\"\n\t\t\tfor(int i = 1; i <= 10; i++) {\n    \n\n#line default\n#line hidden\n\n#line 2 \"DesignTime.cshtml\"\n\t\t\t\t__o = i;\n\n\n#line default\n#line hidden\n\n#line 3 \"DesignTime.cshtml\"\n\t\t\t\t\t\t   \n            }\n\n#line default\n#line hidden\n\n#line 4 \"DesignTime.cshtml\"\n__o = Foo(Bar.Baz);\n\n\n#line default\n#line hidden\n\n#line 5 \"DesignTime.cshtml\"\n__o = Foo(item => new Template(__razor_template_writer => {\n\n\n#line default\n#line hidden\n\n#line 6 \"DesignTime.cshtml\"\n\t\t__o = baz;\n\n\n#line default\n#line hidden\n\n#line 7 \"DesignTime.cshtml\"\n\t\t\t\t\t   }));\n\n\n#line default\n#line hidden\nDefineSection(\"Footer\", () => {\n\n\n#line 8 \"DesignTime.cshtml\"\n__o = bar;\n\n\n#line default\n#line hidden\n});\n\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/DesignTime.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class DesignTime {\nprivate static object @__o;\n#line hidden\n#line 9 \"DesignTime.cshtml\"\npublic static Template Foo() {\n#line default\n#line hidden\nreturn new Template(__razor_helper_writer => {\n\n#line 10 \"DesignTime.cshtml\"\n               \n    if(true) {\n        \n\n#line default\n#line hidden\n\n#line 11 \"DesignTime.cshtml\"\n                  \n    }\n\n\n#line default\n#line hidden\n});\n\n#line 12 \"DesignTime.cshtml\"\n}\n#line default\n#line hidden\n\npublic DesignTime() {\n}\npublic override void Execute() {\n\n#line 1 \"DesignTime.cshtml\"\n            for(int i = 1; i <= 10; i++) {\n    \n\n#line default\n#line hidden\n\n#line 2 \"DesignTime.cshtml\"\n                __o = i;\n\n\n#line default\n#line hidden\n\n#line 3 \"DesignTime.cshtml\"\n                           \n            }\n\n#line default\n#line hidden\n\n#line 4 \"DesignTime.cshtml\"\n__o = Foo(Bar.Baz);\n\n\n#line default\n#line hidden\n\n#line 5 \"DesignTime.cshtml\"\n__o = Foo(item => new Template(__razor_template_writer => {\n\n\n#line default\n#line hidden\n\n#line 6 \"DesignTime.cshtml\"\n        __o = baz;\n\n\n#line default\n#line hidden\n\n#line 7 \"DesignTime.cshtml\"\n                       }));\n\n\n#line default\n#line hidden\nDefineSection(\"Footer\", () => {\n\n\n#line 8 \"DesignTime.cshtml\"\n__o = bar;\n\n\n#line default\n#line hidden\n});\n\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/EmptyCodeBlock.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class EmptyCodeBlock {\n#line hidden\npublic EmptyCodeBlock() {\n}\npublic override void Execute() {\n\n#line 1 \"EmptyCodeBlock.cshtml\"\n  \n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/EmptyExplicitExpression.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class EmptyExplicitExpression {\nprivate static object @__o;\n#line hidden\npublic EmptyExplicitExpression() {\n}\npublic override void Execute() {\n\n#line 1 \"EmptyExplicitExpression.cshtml\"\n__o = ;\n\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/EmptyImplicitExpression.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class EmptyImplicitExpression {\nprivate static object @__o;\n#line hidden\npublic EmptyImplicitExpression() {\n}\npublic override void Execute() {\n\n#line 1 \"EmptyImplicitExpression.cshtml\"\n__o = ;\n\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/EmptyImplicitExpressionInCode.Tabs.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class EmptyImplicitExpressionInCode {\nprivate static object @__o;\n#line hidden\npublic EmptyImplicitExpressionInCode() {\n}\npublic override void Execute() {\n\n#line 1 \"EmptyImplicitExpressionInCode.cshtml\"\n  \n    \n\n#line default\n#line hidden\n\n#line 2 \"EmptyImplicitExpressionInCode.cshtml\"\n__o = ;\n\n\n#line default\n#line hidden\n\n#line 3 \"EmptyImplicitExpressionInCode.cshtml\"\n\t \n\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/EmptyImplicitExpressionInCode.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class EmptyImplicitExpressionInCode {\nprivate static object @__o;\n#line hidden\npublic EmptyImplicitExpressionInCode() {\n}\npublic override void Execute() {\n\n#line 1 \"EmptyImplicitExpressionInCode.cshtml\"\n  \n    \n\n#line default\n#line hidden\n\n#line 2 \"EmptyImplicitExpressionInCode.cshtml\"\n__o = ;\n\n\n#line default\n#line hidden\n\n#line 3 \"EmptyImplicitExpressionInCode.cshtml\"\n     \n\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/ExplicitExpression.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class ExplicitExpression {\n#line hidden\npublic ExplicitExpression() {\n}\npublic override void Execute() {\nWriteLiteral(\"1 + 1 = \");\n\n\n#line 1 \"ExplicitExpression.cshtml\"\n    Write(1+1);\n\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/ExplicitExpressionAtEOF.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class ExplicitExpressionAtEOF {\nprivate static object @__o;\n#line hidden\npublic ExplicitExpressionAtEOF() {\n}\npublic override void Execute() {\n\n#line 1 \"ExplicitExpressionAtEOF.cshtml\"\n__o = ;\n\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/ExpressionsInCode.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class ExpressionsInCode {\n#line hidden\npublic ExpressionsInCode() {\n}\npublic override void Execute() {\n\n#line 1 \"ExpressionsInCode.cshtml\"\n  \n    object foo = null;\n    string bar = \"Foo\";\n\n\n#line default\n#line hidden\nWriteLiteral(\"\\r\\n\\r\\n\");\n\n\n#line 6 \"ExpressionsInCode.cshtml\"\n if(foo != null) {\n    \n\n#line default\n#line hidden\n\n#line 7 \"ExpressionsInCode.cshtml\"\nWrite(foo);\n\n\n#line default\n#line hidden\n\n#line 7 \"ExpressionsInCode.cshtml\"\n        \n} else {\n\n\n#line default\n#line hidden\nWriteLiteral(\"    <p>Foo is Null!</p>\\r\\n\");\n\n\n#line 10 \"ExpressionsInCode.cshtml\"\n}\n\n\n#line default\n#line hidden\nWriteLiteral(\"\\r\\n<p>\\r\\n\");\n\n\n#line 13 \"ExpressionsInCode.cshtml\"\n if(!String.IsNullOrEmpty(bar)) {\n    \n\n#line default\n#line hidden\n\n#line 14 \"ExpressionsInCode.cshtml\"\nWrite(bar.Replace(\"F\", \"B\"));\n\n\n#line default\n#line hidden\n\n#line 14 \"ExpressionsInCode.cshtml\"\n                            \n}\n\n\n#line default\n#line hidden\nWriteLiteral(\"</p>\");\n\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/FunctionsBlock.DesignTime.Tabs.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class FunctionsBlock {\nprivate static object @__o;\n#line hidden\n#line 1 \"FunctionsBlock.cshtml\"\n\t\t\t\n\n\n#line default\n#line hidden\n\n#line 2 \"FunctionsBlock.cshtml\"\n\t\t\t\n    Random _rand = new Random();\n    private int RandomInt() {\n        return _rand.Next();\n    }\n\n#line default\n#line hidden\n\npublic FunctionsBlock() {\n}\npublic override void Execute() {\n\n#line 3 \"FunctionsBlock.cshtml\"\n\t\t\t\t   __o = RandomInt();\n\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/FunctionsBlock.DesignTime.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class FunctionsBlock {\nprivate static object @__o;\n#line hidden\n#line 1 \"FunctionsBlock.cshtml\"\n            \n\n\n#line default\n#line hidden\n\n#line 2 \"FunctionsBlock.cshtml\"\n            \n    Random _rand = new Random();\n    private int RandomInt() {\n        return _rand.Next();\n    }\n\n#line default\n#line hidden\n\npublic FunctionsBlock() {\n}\npublic override void Execute() {\n\n#line 3 \"FunctionsBlock.cshtml\"\n                   __o = RandomInt();\n\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/FunctionsBlock.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class FunctionsBlock {\n#line hidden\n#line 1 \"FunctionsBlock.cshtml\"\n            \n\n\n#line default\n#line hidden\n\n#line 5 \"FunctionsBlock.cshtml\"\n            \n    Random _rand = new Random();\n    private int RandomInt() {\n        return _rand.Next();\n    }\n\n#line default\n#line hidden\n\npublic FunctionsBlock() {\n}\npublic override void Execute() {\nWriteLiteral(\"\\r\\n\");\n\nWriteLiteral(\"\\r\\nHere\\'s a random number: \");\n\n\n#line 12 \"FunctionsBlock.cshtml\"\n                   Write(RandomInt());\n\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/FunctionsBlockMinimal.DesignTime.Tabs.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class FunctionsBlockMinimal {\n#line hidden\n#line 1 \"FunctionsBlockMinimal.cshtml\"\n\t\t\t   \nstring foo(string input) {\n\treturn input + \"!\";\n}\n\n#line default\n#line hidden\n\npublic FunctionsBlockMinimal() {\n}\npublic override void Execute() {\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/FunctionsBlock_Tabs.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class FunctionsBlock_Tabs {\n#line hidden\n#line 1 \"FunctionsBlock_Tabs.cshtml\"\n            \n\n\n#line default\n#line hidden\n\n#line 5 \"FunctionsBlock_Tabs.cshtml\"\n            \n\tRandom _rand = new Random();\n\tprivate int RandomInt() {\n\t\treturn _rand.Next();\n\t}\n\n#line default\n#line hidden\n\npublic FunctionsBlock_Tabs() {\n}\npublic override void Execute() {\nWriteLiteral(\"\\r\\n\");\n\nWriteLiteral(\"\\r\\nHere\\'s a random number: \");\n\n\n#line 12 \"FunctionsBlock_Tabs.cshtml\"\n                   Write(RandomInt());\n\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/Helpers.Instance.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class Helpers {\n#line hidden\n#line 1 \"Helpers.cshtml\"\npublic Template Bold(string s) {\n#line default\n#line hidden\nreturn new Template(__razor_helper_writer => {\n\n#line 1 \"Helpers.cshtml\"\n                        \n    s = s.ToUpper();\n\n\n#line default\n#line hidden\nWriteLiteralTo(__razor_helper_writer, \"    <strong>\");\n\n\n#line 3 \"Helpers.cshtml\"\nWriteTo(__razor_helper_writer, s);\n\n\n#line default\n#line hidden\nWriteLiteralTo(__razor_helper_writer, \"</strong>\\r\\n\");\n\n\n#line 4 \"Helpers.cshtml\"\n\n\n#line default\n#line hidden\n});\n\n#line 4 \"Helpers.cshtml\"\n}\n#line default\n#line hidden\n\n#line 6 \"Helpers.cshtml\"\npublic Template Italic(string s) {\n#line default\n#line hidden\nreturn new Template(__razor_helper_writer => {\n\n#line 6 \"Helpers.cshtml\"\n                          \n    s = s.ToUpper();\n\n\n#line default\n#line hidden\nWriteLiteralTo(__razor_helper_writer, \"    <em>\");\n\n\n#line 8 \"Helpers.cshtml\"\nWriteTo(__razor_helper_writer, s);\n\n\n#line default\n#line hidden\nWriteLiteralTo(__razor_helper_writer, \"</em>\\r\\n\");\n\n\n#line 9 \"Helpers.cshtml\"\n\n\n#line default\n#line hidden\n});\n\n#line 9 \"Helpers.cshtml\"\n}\n#line default\n#line hidden\n\npublic Helpers() {\n}\npublic override void Execute() {\nWriteLiteral(\"\\r\\n\");\n\nWriteLiteral(\"\\r\\n\");\n\n\n#line 11 \"Helpers.cshtml\"\nWrite(Bold(\"Hello\"));\n\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/Helpers.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class Helpers {\n#line hidden\n#line 1 \"Helpers.cshtml\"\npublic static Template Bold(string s) {\n#line default\n#line hidden\nreturn new Template(__razor_helper_writer => {\n\n#line 1 \"Helpers.cshtml\"\n                        \n    s = s.ToUpper();\n\n\n#line default\n#line hidden\nWriteLiteralTo(__razor_helper_writer, \"    <strong>\");\n\n\n#line 3 \"Helpers.cshtml\"\nWriteTo(__razor_helper_writer, s);\n\n\n#line default\n#line hidden\nWriteLiteralTo(__razor_helper_writer, \"</strong>\\r\\n\");\n\n\n#line 4 \"Helpers.cshtml\"\n\n\n#line default\n#line hidden\n});\n\n#line 4 \"Helpers.cshtml\"\n}\n#line default\n#line hidden\n\n#line 6 \"Helpers.cshtml\"\npublic static Template Italic(string s) {\n#line default\n#line hidden\nreturn new Template(__razor_helper_writer => {\n\n#line 6 \"Helpers.cshtml\"\n                          \n    s = s.ToUpper();\n\n\n#line default\n#line hidden\nWriteLiteralTo(__razor_helper_writer, \"    <em>\");\n\n\n#line 8 \"Helpers.cshtml\"\nWriteTo(__razor_helper_writer, s);\n\n\n#line default\n#line hidden\nWriteLiteralTo(__razor_helper_writer, \"</em>\\r\\n\");\n\n\n#line 9 \"Helpers.cshtml\"\n\n\n#line default\n#line hidden\n});\n\n#line 9 \"Helpers.cshtml\"\n}\n#line default\n#line hidden\n\npublic Helpers() {\n}\npublic override void Execute() {\nWriteLiteral(\"\\r\\n\");\n\nWriteLiteral(\"\\r\\n\");\n\n\n#line 11 \"Helpers.cshtml\"\nWrite(Bold(\"Hello\"));\n\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/HelpersMissingCloseParen.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class HelpersMissingCloseParen {\n#line hidden\n#line 1 \"HelpersMissingCloseParen.cshtml\"\npublic static Template Bold(string s) {\n#line default\n#line hidden\nreturn new Template(__razor_helper_writer => {\n\n#line 1 \"HelpersMissingCloseParen.cshtml\"\n                        \n    s = s.ToUpper();\n\n\n#line default\n#line hidden\nWriteLiteralTo(__razor_helper_writer, \"    <strong>\");\n\n\n#line 3 \"HelpersMissingCloseParen.cshtml\"\nWriteTo(__razor_helper_writer, s);\n\n\n#line default\n#line hidden\nWriteLiteralTo(__razor_helper_writer, \"</strong>\\r\\n\");\n\n\n#line 4 \"HelpersMissingCloseParen.cshtml\"\n\n\n#line default\n#line hidden\n});\n\n#line 4 \"HelpersMissingCloseParen.cshtml\"\n}\n#line default\n#line hidden\n\n#line 6 \"HelpersMissingCloseParen.cshtml\"\npublic static Template Italic(string s\n@Bold(\"Hello\")\n#line default\n#line hidden\n\npublic HelpersMissingCloseParen() {\n}\npublic override void Execute() {\nWriteLiteral(\"\\r\\n\");\n\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/HelpersMissingName.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class HelpersMissingName {\n#line hidden\npublic HelpersMissingName() {\n}\npublic override void Execute() {\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/HelpersMissingOpenBrace.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class HelpersMissingOpenBrace {\n#line hidden\n#line 1 \"HelpersMissingOpenBrace.cshtml\"\npublic static Template Bold(string s) {\n#line default\n#line hidden\nreturn new Template(__razor_helper_writer => {\n\n#line 1 \"HelpersMissingOpenBrace.cshtml\"\n                        \n    s = s.ToUpper();\n\n\n#line default\n#line hidden\nWriteLiteralTo(__razor_helper_writer, \"    <strong>\");\n\n\n#line 3 \"HelpersMissingOpenBrace.cshtml\"\nWriteTo(__razor_helper_writer, s);\n\n\n#line default\n#line hidden\nWriteLiteralTo(__razor_helper_writer, \"</strong>\\r\\n\");\n\n\n#line 4 \"HelpersMissingOpenBrace.cshtml\"\n\n\n#line default\n#line hidden\n});\n\n#line 4 \"HelpersMissingOpenBrace.cshtml\"\n}\n#line default\n#line hidden\n\n#line 6 \"HelpersMissingOpenBrace.cshtml\"\npublic static Template Italic(string s) \n#line default\n#line hidden\n\npublic HelpersMissingOpenBrace() {\n}\npublic override void Execute() {\nWriteLiteral(\"\\r\\n\");\n\n\n#line 7 \"HelpersMissingOpenBrace.cshtml\"\nWrite(Italic(s));\n\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/HelpersMissingOpenParen.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class HelpersMissingOpenParen {\n#line hidden\n#line 1 \"HelpersMissingOpenParen.cshtml\"\npublic static Template Bold(string s) {\n#line default\n#line hidden\nreturn new Template(__razor_helper_writer => {\n\n#line 1 \"HelpersMissingOpenParen.cshtml\"\n                        \n    s = s.ToUpper();\n\n\n#line default\n#line hidden\nWriteLiteralTo(__razor_helper_writer, \"    <strong>\");\n\n\n#line 3 \"HelpersMissingOpenParen.cshtml\"\nWriteTo(__razor_helper_writer, s);\n\n\n#line default\n#line hidden\nWriteLiteralTo(__razor_helper_writer, \"</strong>\\r\\n\");\n\n\n#line 4 \"HelpersMissingOpenParen.cshtml\"\n\n\n#line default\n#line hidden\n});\n\n#line 4 \"HelpersMissingOpenParen.cshtml\"\n}\n#line default\n#line hidden\n\n#line 6 \"HelpersMissingOpenParen.cshtml\"\npublic static Template Italic\n#line default\n#line hidden\n\npublic HelpersMissingOpenParen() {\n}\npublic override void Execute() {\nWriteLiteral(\"\\r\\n\");\n\n\n#line 7 \"HelpersMissingOpenParen.cshtml\"\nWrite(Bold(\"Hello\"));\n\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/HiddenSpansInCode.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class HiddenSpansInCode {\n#line hidden\npublic HiddenSpansInCode() {\n}\npublic override void Execute() {\n\n#line 1 \"HiddenSpansInCode.cshtml\"\n  \n    \n\n#line default\n#line hidden\n\n#line 2 \"HiddenSpansInCode.cshtml\"\n     @Da\n\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/HtmlCommentWithQuote_Double.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class HtmlCommentWithQuote_Double {\n#line hidden\npublic HtmlCommentWithQuote_Double() {\n}\npublic override void Execute() {\nWriteLiteral(\"<!-- \\\" -->\\r\\n<img\");\n\nWriteAttribute(\"src\", Tuple.Create(\" src=\\\"\", 16), Tuple.Create(\"\\\"\", 41)\n, Tuple.Create(Tuple.Create(\"\", 22), Tuple.Create<System.Object, System.Int32>(Href(\"~/images/submit.png\")\n, 22), false)\n);\n\nWriteLiteral(\" />\");\n\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/HtmlCommentWithQuote_Single.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class HtmlCommentWithQuote_Single {\n#line hidden\npublic HtmlCommentWithQuote_Single() {\n}\npublic override void Execute() {\nWriteLiteral(\"<!-- \\' -->\\r\\n<img\");\n\nWriteAttribute(\"src\", Tuple.Create(\" src=\\\"\", 16), Tuple.Create(\"\\\"\", 41)\n, Tuple.Create(Tuple.Create(\"\", 22), Tuple.Create<System.Object, System.Int32>(Href(\"~/images/submit.png\")\n, 22), false)\n);\n\nWriteLiteral(\" />\");\n\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/ImplicitExpression.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class ImplicitExpression {\n#line hidden\npublic ImplicitExpression() {\n}\npublic override void Execute() {\n\n#line 1 \"ImplicitExpression.cshtml\"\n for(int i = 1; i <= 10; i++) {\n\n\n#line default\n#line hidden\nWriteLiteral(\"    <p>This is item #\");\n\n\n#line 2 \"ImplicitExpression.cshtml\"\n                Write(i);\n\n\n#line default\n#line hidden\nWriteLiteral(\"</p>\\r\\n\");\n\n\n#line 3 \"ImplicitExpression.cshtml\"\n}\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/ImplicitExpressionAtEOF.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class ImplicitExpressionAtEOF {\nprivate static object @__o;\n#line hidden\npublic ImplicitExpressionAtEOF() {\n}\npublic override void Execute() {\n\n#line 1 \"ImplicitExpressionAtEOF.cshtml\"\n__o = ;\n\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/Imports.DesignTime.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\n\n#line 3 \"Imports.cshtml\"\nusing System;\n\n#line default\n#line hidden\n\n#line 1 \"Imports.cshtml\"\nusing System.IO;\n\n#line default\n#line hidden\n\n#line 2 \"Imports.cshtml\"\nusing Foo = System.Text.Encoding;\n\n#line default\n#line hidden\n\npublic class Imports {\nprivate static object @__o;\n#line hidden\npublic Imports() {\n}\npublic override void Execute() {\n\n#line 4 \"Imports.cshtml\"\n                       __o = typeof(Path).FullName;\n\n\n#line default\n#line hidden\n\n#line 5 \"Imports.cshtml\"\n                             __o = typeof(Foo).FullName;\n\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/Imports.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\n\n#line 3 \"Imports.cshtml\"\nusing System;\n\n#line default\n#line hidden\n\n#line 1 \"Imports.cshtml\"\nusing System.IO;\n\n#line default\n#line hidden\n\n#line 2 \"Imports.cshtml\"\nusing Foo = System.Text.Encoding;\n\n#line default\n#line hidden\n\npublic class Imports {\n#line hidden\npublic Imports() {\n}\npublic override void Execute() {\nWriteLiteral(\"\\r\\n<p>Path\\'s full type name is \");\n\n\n#line 5 \"Imports.cshtml\"\n                       Write(typeof(Path).FullName);\n\n\n#line default\n#line hidden\nWriteLiteral(\"</p>\\r\\n<p>Foo\\'s actual full type name is \");\n\n\n#line 6 \"Imports.cshtml\"\n                             Write(typeof(Foo).FullName);\n\n\n#line default\n#line hidden\nWriteLiteral(\"</p>\");\n\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/Inherits.Designtime.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class Inherits : foo.bar<baz<biz>>.boz bar {\nprivate static object @__o;\n#line hidden\npublic Inherits() {\n}\nprivate void @__RazorDesignTimeHelpers__() {\n#pragma warning disable 219\n\n#line 2 \"Inherits.cshtml\"\n          foo.bar<baz<biz>>.boz bar __inheritsHelper = null;\n\n\n#line default\n#line hidden\n#pragma warning restore 219\n}\npublic override void Execute() {\n\n#line 1 \"Inherits.cshtml\"\n__o = foo();\n\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/Inherits.Runtime.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class Inherits : foo.bar<baz<biz>>.boz bar {\n#line hidden\npublic Inherits() {\n}\npublic override void Execute() {\n\n#line 1 \"Inherits.cshtml\"\nWrite(foo());\n\n\n#line default\n#line hidden\nWriteLiteral(\"\\r\\n\\r\\n\");\n\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/InlineBlocks.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class InlineBlocks {\n#line hidden\n#line 1 \"InlineBlocks.cshtml\"\npublic static Template Link(string link) {\n#line default\n#line hidden\nreturn new Template(__razor_helper_writer => {\n\n#line 1 \"InlineBlocks.cshtml\"\n                           \n\n\n#line default\n#line hidden\nWriteLiteralTo(__razor_helper_writer, \"    <a\");\n\nWriteAttributeTo(__razor_helper_writer, \"href\", Tuple.Create(\" href=\\\"\", 35), Tuple.Create(\"\\\"\", 93)\n, Tuple.Create(Tuple.Create(\"\", 42), Tuple.Create<System.Object, System.Int32>(new Template(__razor_attribute_value_writer => {\n\n\n#line 2 \"InlineBlocks.cshtml\"\n              if(link != null) { \n\n#line default\n#line hidden\n\n#line 2 \"InlineBlocks.cshtml\"\nWriteTo(__razor_attribute_value_writer, link);\n\n\n#line default\n#line hidden\n\n#line 2 \"InlineBlocks.cshtml\"\n                                       } else {\n\n#line default\n#line hidden\nWriteLiteralTo(__razor_attribute_value_writer, \" \");\n\nWriteLiteralTo(__razor_attribute_value_writer, \"#\");\n\nWriteLiteralTo(__razor_attribute_value_writer, \" \");\n\n\n#line 2 \"InlineBlocks.cshtml\"\n                                                               }\n\n#line default\n#line hidden\n}), 42), false)\n);\n\nWriteLiteralTo(__razor_helper_writer, \" />\\r\\n\");\n\n\n#line 3 \"InlineBlocks.cshtml\"\n\n\n#line default\n#line hidden\n});\n\n#line 3 \"InlineBlocks.cshtml\"\n}\n#line default\n#line hidden\n\npublic InlineBlocks() {\n}\npublic override void Execute() {\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/Instrumented.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class Instrumented {\n#line hidden\n#line 1 \"Instrumented.cshtml\"\npublic static Template Strong(string s) {\n#line default\n#line hidden\nreturn new Template(__razor_helper_writer => {\n\n#line 1 \"Instrumented.cshtml\"\n                          \n\n\n#line default\n#line hidden\nBeginContext(__razor_helper_writer, \"~/Instrumented.cshtml\", 28, 12, true);\n\nWriteLiteralTo(__razor_helper_writer, \"    <strong>\");\n\nEndContext(__razor_helper_writer, \"~/Instrumented.cshtml\", 28, 12, true);\n\nBeginContext(__razor_helper_writer, \"~/Instrumented.cshtml\", 41, 1, false);\n\n\n#line 2 \"Instrumented.cshtml\"\nWriteTo(__razor_helper_writer, s);\n\n\n#line default\n#line hidden\nEndContext(__razor_helper_writer, \"~/Instrumented.cshtml\", 41, 1, false);\n\nBeginContext(__razor_helper_writer, \"~/Instrumented.cshtml\", 42, 11, true);\n\nWriteLiteralTo(__razor_helper_writer, \"</strong>\\r\\n\");\n\nEndContext(__razor_helper_writer, \"~/Instrumented.cshtml\", 42, 11, true);\n\n\n#line 3 \"Instrumented.cshtml\"\n\n\n#line default\n#line hidden\n});\n\n#line 3 \"Instrumented.cshtml\"\n}\n#line default\n#line hidden\n\npublic Instrumented() {\n}\npublic override void Execute() {\nBeginContext(\"~/Instrumented.cshtml\", 56, 2, true);\n\nWriteLiteral(\"\\r\\n\");\n\nEndContext(\"~/Instrumented.cshtml\", 56, 2, true);\n\n\n#line 5 \"Instrumented.cshtml\"\n  \n    int i = 1;\n    var foo = \n\n#line default\n#line hidden\nitem => new Template(__razor_template_writer => {\n\nBeginContext(__razor_template_writer, \"~/Instrumented.cshtml\", 93, 10, true);\n\nWriteLiteralTo(__razor_template_writer, \"<p>Bar</p>\");\n\nEndContext(__razor_template_writer, \"~/Instrumented.cshtml\", 93, 10, true);\n\n})\n\n#line 7 \"Instrumented.cshtml\"\n                         ;\n\n\n#line default\n#line hidden\nBeginContext(\"~/Instrumented.cshtml\", 106, 4, true);\n\nWriteLiteral(\"    \");\n\nEndContext(\"~/Instrumented.cshtml\", 106, 4, true);\n\nBeginContext(\"~/Instrumented.cshtml\", 112, 14, true);\n\nWriteLiteral(\"Hello, World\\r\\n\");\n\nEndContext(\"~/Instrumented.cshtml\", 112, 14, true);\n\nBeginContext(\"~/Instrumented.cshtml\", 126, 25, true);\n\nWriteLiteral(\"    <p>Hello, World</p>\\r\\n\");\n\nEndContext(\"~/Instrumented.cshtml\", 126, 25, true);\n\n\n#line 10 \"Instrumented.cshtml\"\n\n\n#line default\n#line hidden\nBeginContext(\"~/Instrumented.cshtml\", 152, 4, true);\n\nWriteLiteral(\"\\r\\n\\r\\n\");\n\nEndContext(\"~/Instrumented.cshtml\", 152, 4, true);\n\n\n#line 12 \"Instrumented.cshtml\"\n while(i <= 10) {\n\n\n#line default\n#line hidden\nBeginContext(\"~/Instrumented.cshtml\", 175, 23, true);\n\nWriteLiteral(\"    <p>Hello from C#, #\");\n\nEndContext(\"~/Instrumented.cshtml\", 175, 23, true);\n\nBeginContext(\"~/Instrumented.cshtml\", 200, 1, false);\n\n\n#line 13 \"Instrumented.cshtml\"\n                   Write(i);\n\n\n#line default\n#line hidden\nEndContext(\"~/Instrumented.cshtml\", 200, 1, false);\n\nBeginContext(\"~/Instrumented.cshtml\", 202, 6, true);\n\nWriteLiteral(\"</p>\\r\\n\");\n\nEndContext(\"~/Instrumented.cshtml\", 202, 6, true);\n\n\n#line 14 \"Instrumented.cshtml\"\n    i += 1;\n}\n\n\n#line default\n#line hidden\nBeginContext(\"~/Instrumented.cshtml\", 224, 2, true);\n\nWriteLiteral(\"\\r\\n\");\n\nEndContext(\"~/Instrumented.cshtml\", 224, 2, true);\n\n\n#line 17 \"Instrumented.cshtml\"\n if(i == 11) {\n\n\n#line default\n#line hidden\nBeginContext(\"~/Instrumented.cshtml\", 242, 31, true);\n\nWriteLiteral(\"    <p>We wrote 10 lines!</p>\\r\\n\");\n\nEndContext(\"~/Instrumented.cshtml\", 242, 31, true);\n\n\n#line 19 \"Instrumented.cshtml\"\n}\n\n\n#line default\n#line hidden\nBeginContext(\"~/Instrumented.cshtml\", 276, 2, true);\n\nWriteLiteral(\"\\r\\n\");\n\nEndContext(\"~/Instrumented.cshtml\", 276, 2, true);\n\n\n#line 21 \"Instrumented.cshtml\"\n switch(i) {\n    case 11:\n\n\n#line default\n#line hidden\nBeginContext(\"~/Instrumented.cshtml\", 306, 46, true);\n\nWriteLiteral(\"        <p>No really, we wrote 10 lines!</p>\\r\\n\");\n\nEndContext(\"~/Instrumented.cshtml\", 306, 46, true);\n\n\n#line 24 \"Instrumented.cshtml\"\n        break;\n    default:\n\n\n#line default\n#line hidden\nBeginContext(\"~/Instrumented.cshtml\", 382, 39, true);\n\nWriteLiteral(\"        <p>Actually, we didn\\'t...</p>\\r\\n\");\n\nEndContext(\"~/Instrumented.cshtml\", 382, 39, true);\n\n\n#line 27 \"Instrumented.cshtml\"\n        break;\n}\n\n\n#line default\n#line hidden\nBeginContext(\"~/Instrumented.cshtml\", 440, 2, true);\n\nWriteLiteral(\"\\r\\n\");\n\nEndContext(\"~/Instrumented.cshtml\", 440, 2, true);\n\n\n#line 30 \"Instrumented.cshtml\"\n for(int j = 1; j <= 10; j += 2) {\n\n\n#line default\n#line hidden\nBeginContext(\"~/Instrumented.cshtml\", 478, 29, true);\n\nWriteLiteral(\"    <p>Hello again from C#, #\");\n\nEndContext(\"~/Instrumented.cshtml\", 478, 29, true);\n\nBeginContext(\"~/Instrumented.cshtml\", 509, 1, false);\n\n\n#line 31 \"Instrumented.cshtml\"\n                         Write(j);\n\n\n#line default\n#line hidden\nEndContext(\"~/Instrumented.cshtml\", 509, 1, false);\n\nBeginContext(\"~/Instrumented.cshtml\", 511, 6, true);\n\nWriteLiteral(\"</p>\\r\\n\");\n\nEndContext(\"~/Instrumented.cshtml\", 511, 6, true);\n\n\n#line 32 \"Instrumented.cshtml\"\n}\n\n\n#line default\n#line hidden\nBeginContext(\"~/Instrumented.cshtml\", 520, 2, true);\n\nWriteLiteral(\"\\r\\n\");\n\nEndContext(\"~/Instrumented.cshtml\", 520, 2, true);\n\n\n#line 34 \"Instrumented.cshtml\"\n try {\n\n\n#line default\n#line hidden\nBeginContext(\"~/Instrumented.cshtml\", 530, 41, true);\n\nWriteLiteral(\"    <p>That time, we wrote 5 lines!</p>\\r\\n\");\n\nEndContext(\"~/Instrumented.cshtml\", 530, 41, true);\n\n\n#line 36 \"Instrumented.cshtml\"\n} catch(Exception ex) {\n\n\n#line default\n#line hidden\nBeginContext(\"~/Instrumented.cshtml\", 596, 33, true);\n\nWriteLiteral(\"    <p>Oh no! An error occurred: \");\n\nEndContext(\"~/Instrumented.cshtml\", 596, 33, true);\n\nBeginContext(\"~/Instrumented.cshtml\", 631, 10, false);\n\n\n#line 37 \"Instrumented.cshtml\"\n                             Write(ex.Message);\n\n\n#line default\n#line hidden\nEndContext(\"~/Instrumented.cshtml\", 631, 10, false);\n\nBeginContext(\"~/Instrumented.cshtml\", 642, 6, true);\n\nWriteLiteral(\"</p>\\r\\n\");\n\nEndContext(\"~/Instrumented.cshtml\", 642, 6, true);\n\n\n#line 38 \"Instrumented.cshtml\"\n}\n\n\n#line default\n#line hidden\nBeginContext(\"~/Instrumented.cshtml\", 651, 2, true);\n\nWriteLiteral(\"\\r\\n\");\n\nEndContext(\"~/Instrumented.cshtml\", 651, 2, true);\n\n\n#line 40 \"Instrumented.cshtml\"\n lock(new object()) {\n\n\n#line default\n#line hidden\nBeginContext(\"~/Instrumented.cshtml\", 676, 53, true);\n\nWriteLiteral(\"    <p>This block is locked, for your security!</p>\\r\\n\");\n\nEndContext(\"~/Instrumented.cshtml\", 676, 53, true);\n\n\n#line 42 \"Instrumented.cshtml\"\n}\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/LayoutDirective.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class LayoutDirective {\n#line hidden\npublic LayoutDirective() {\n}\npublic override void Execute() {\nLayout = \"~/Foo/Bar/Baz\";\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/MarkupInCodeBlock.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class MarkupInCodeBlock {\n#line hidden\npublic MarkupInCodeBlock() {\n}\npublic override void Execute() {\n\n#line 1 \"MarkupInCodeBlock.cshtml\"\n  \n    for(int i = 1; i <= 10; i++) {\n\n\n#line default\n#line hidden\nWriteLiteral(\"        <p>Hello from C#, #\");\n\n\n#line 3 \"MarkupInCodeBlock.cshtml\"\n                       Write(i.ToString());\n\n\n#line default\n#line hidden\nWriteLiteral(\"</p>\\r\\n\");\n\n\n#line 4 \"MarkupInCodeBlock.cshtml\"\n    }\n\n\n#line default\n#line hidden\nWriteLiteral(\"\\r\\n\");\n\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/NestedCodeBlocks.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class NestedCodeBlocks {\n#line hidden\npublic NestedCodeBlocks() {\n}\npublic override void Execute() {\n\n#line 1 \"NestedCodeBlocks.cshtml\"\n if(foo) {\n    \n\n#line default\n#line hidden\n\n#line 2 \"NestedCodeBlocks.cshtml\"\n     if(bar) {\n    }\n\n#line default\n#line hidden\n\n#line 3 \"NestedCodeBlocks.cshtml\"\n     \n}\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/NestedHelpers.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class NestedHelpers {\n#line hidden\n#line 3 \"NestedHelpers.cshtml\"\npublic static Template Bold(string s) {\n#line default\n#line hidden\nreturn new Template(__razor_helper_writer => {\n\n#line 3 \"NestedHelpers.cshtml\"\n                            \n        s = s.ToUpper();\n\n\n#line default\n#line hidden\nWriteLiteralTo(__razor_helper_writer, \"        <strong>\");\n\n\n#line 5 \"NestedHelpers.cshtml\"\nWriteTo(__razor_helper_writer, s);\n\n\n#line default\n#line hidden\nWriteLiteralTo(__razor_helper_writer, \"</strong>\\r\\n\");\n\n\n#line 6 \"NestedHelpers.cshtml\"\n    \n\n#line default\n#line hidden\n});\n\n#line 6 \"NestedHelpers.cshtml\"\n}\n#line default\n#line hidden\n\n#line 1 \"NestedHelpers.cshtml\"\npublic static Template Italic(string s) {\n#line default\n#line hidden\nreturn new Template(__razor_helper_writer => {\n\n#line 1 \"NestedHelpers.cshtml\"\n                          \n    s = s.ToUpper();\n    \n\n#line default\n#line hidden\n\n#line 6 \"NestedHelpers.cshtml\"\n     \n\n\n#line default\n#line hidden\nWriteLiteralTo(__razor_helper_writer, \"    <em>\");\n\n\n#line 7 \"NestedHelpers.cshtml\"\nWriteTo(__razor_helper_writer, Bold(s));\n\n\n#line default\n#line hidden\nWriteLiteralTo(__razor_helper_writer, \"</em>\\r\\n\");\n\n\n#line 8 \"NestedHelpers.cshtml\"\n\n\n#line default\n#line hidden\n});\n\n#line 8 \"NestedHelpers.cshtml\"\n}\n#line default\n#line hidden\n\npublic NestedHelpers() {\n}\npublic override void Execute() {\nWriteLiteral(\"\\r\\n\");\n\n\n#line 10 \"NestedHelpers.cshtml\"\nWrite(Italic(\"Hello\"));\n\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/NoLinePragmas.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class NoLinePragmas {\n#line hidden\npublic NoLinePragmas() {\n}\npublic override void Execute() {\n  \n    int i = 1;\n\nWriteLiteral(\"\\r\\n\\r\\n\");\n\n while(i <= 10) {\n\nWriteLiteral(\"    <p>Hello from C#, #\");\n\n                   Write(i);\n\nWriteLiteral(\"</p>\\r\\n\");\n\n    i += 1;\n}\n\nWriteLiteral(\"\\r\\n\");\n\n if(i == 11) {\n\nWriteLiteral(\"    <p>We wrote 10 lines!</p>\\r\\n\");\n\n}\n\nWriteLiteral(\"\\r\\n\");\n\n switch(i) {\n    case 11:\n\nWriteLiteral(\"        <p>No really, we wrote 10 lines!</p>\\r\\n\");\n\n        break;\n    default:\n\nWriteLiteral(\"        <p>Actually, we didn\\'t...</p>\\r\\n\");\n\n        break;\n}\n\nWriteLiteral(\"\\r\\n\");\n\n for(int j = 1; j <= 10; j += 2) {\n\nWriteLiteral(\"    <p>Hello again from C#, #\");\n\n                         Write(j);\n\nWriteLiteral(\"</p>\\r\\n\");\n\n}\n\nWriteLiteral(\"\\r\\n\");\n\n try {\n\nWriteLiteral(\"    <p>That time, we wrote 5 lines!</p>\\r\\n\");\n\n} catch(Exception ex) {\n\nWriteLiteral(\"    <p>Oh no! An error occurred: \");\n\n                             Write(ex.Message);\n\nWriteLiteral(\"</p>\\r\\n\");\n\n}\n\n\n                                  \n\nWriteLiteral(\"<p>i is now \");\n\n       Write(i);\n\nWriteLiteral(\"</p>\\r\\n\\r\\n\");\n\n lock(new object()) {\n\nWriteLiteral(\"    <p>This block is locked, for your security!</p>\\r\\n\");\n\n}\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/OpenedIf.DesignTime.Tabs.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class OpenedIf {\n#line hidden\npublic OpenedIf() {\n}\npublic override void Execute() {\n\n#line 1 \"OpenedIf.cshtml\"\nif (true) { \n\n\n#line default\n#line hidden\n\n#line 2 \"OpenedIf.cshtml\"\n\t   \n\n\n#line default\n#line hidden\n\n#line 3 \"OpenedIf.cshtml\"\n\t   \n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/OpenedIf.DesignTime.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class OpenedIf {\n#line hidden\npublic OpenedIf() {\n}\npublic override void Execute() {\n\n#line 1 \"OpenedIf.cshtml\"\nif (true) { \n\n\n#line default\n#line hidden\n\n#line 2 \"OpenedIf.cshtml\"\n       \n\n\n#line default\n#line hidden\n\n#line 3 \"OpenedIf.cshtml\"\n       \n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/ParserError.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class ParserError {\n#line hidden\npublic ParserError() {\n}\npublic override void Execute() {\n\n#line 1 \"ParserError.cshtml\"\n  \n/*\nint i =10;\nint j =20;\n}\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/RazorComments.DesignTime.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class RazorComments {\nprivate static object @__o;\n#line hidden\npublic RazorComments() {\n}\npublic override void Execute() {\n\n#line 1 \"RazorComments.cshtml\"\n  \n    \n\n#line default\n#line hidden\n\n#line 2 \"RazorComments.cshtml\"\n                                      \n    Exception foo = \n\n#line default\n#line hidden\n\n#line 3 \"RazorComments.cshtml\"\n                                                 null;\n    if(foo != null) {\n        throw foo;\n    }\n\n\n#line default\n#line hidden\n\n#line 4 \"RazorComments.cshtml\"\n   var bar = \"@* bar *@\"; \n\n#line default\n#line hidden\n\n#line 5 \"RazorComments.cshtml\"\n                                       __o = bar;\n\n\n#line default\n#line hidden\n\n#line 6 \"RazorComments.cshtml\"\n__o = a\n\n#line default\n#line hidden\n\n#line 7 \"RazorComments.cshtml\"\n       b;\n\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/RazorComments.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class RazorComments {\n#line hidden\npublic RazorComments() {\n}\npublic override void Execute() {\nWriteLiteral(\"\\r\\n<p>This should \");\n\nWriteLiteral(\" be shown</p>\\r\\n\\r\\n\");\n\n\n#line 4 \"RazorComments.cshtml\"\n  \n    \n\n#line default\n#line hidden\n\n#line 5 \"RazorComments.cshtml\"\n                                       \n    Exception foo = \n\n#line default\n#line hidden\n\n#line 6 \"RazorComments.cshtml\"\n                                                  null;\n    if(foo != null) {\n        throw foo;\n    }\n\n\n#line default\n#line hidden\nWriteLiteral(\"\\r\\n\\r\\n\");\n\n\n#line 12 \"RazorComments.cshtml\"\n   var bar = \"@* bar *@\"; \n\n#line default\n#line hidden\nWriteLiteral(\"\\r\\n<p>But this should show the comment syntax: \");\n\n\n#line 13 \"RazorComments.cshtml\"\n                                       Write(bar);\n\n\n#line default\n#line hidden\nWriteLiteral(\"</p>\\r\\n\\r\\n\");\n\n\n#line 15 \"RazorComments.cshtml\"\nWrite(a\n\n#line default\n#line hidden\n\n#line 15 \"RazorComments.cshtml\"\n       b);\n\n\n#line default\n#line hidden\nWriteLiteral(\"\\r\\n\");\n\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/ResolveUrl.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class ResolveUrl {\n#line hidden\npublic ResolveUrl() {\n}\npublic override void Execute() {\nWriteLiteral(\"<a\");\n\nWriteAttribute(\"href\", Tuple.Create(\" href=\\\"\", 2), Tuple.Create(\"\\\"\", 14)\n, Tuple.Create(Tuple.Create(\"\", 9), Tuple.Create<System.Object, System.Int32>(Href(\"~/Foo\")\n, 9), false)\n);\n\nWriteLiteral(\">Foo</a>\\r\\n<a\");\n\nWriteAttribute(\"href\", Tuple.Create(\" href=\\\"\", 27), Tuple.Create(\"\\\"\", 56)\n, Tuple.Create(Tuple.Create(\"\", 34), Tuple.Create<System.Object, System.Int32>(Href(\"~/Products/\")\n, 34), false)\n\n#line 2 \"ResolveUrl.cshtml\"\n, Tuple.Create(Tuple.Create(\"\", 45), Tuple.Create<System.Object, System.Int32>(product.id\n\n#line default\n#line hidden\n, 45), false)\n);\n\nWriteLiteral(\">\");\n\n\n#line 2 \"ResolveUrl.cshtml\"\n                            Write(product.Name);\n\n\n#line default\n#line hidden\nWriteLiteral(\"</a>\\r\\n<a\");\n\nWriteAttribute(\"href\", Tuple.Create(\" href=\\\"\", 79), Tuple.Create(\"\\\"\", 115)\n, Tuple.Create(Tuple.Create(\"\", 86), Tuple.Create<System.Object, System.Int32>(Href(\"~/Products/\")\n, 86), false)\n\n#line 3 \"ResolveUrl.cshtml\"\n, Tuple.Create(Tuple.Create(\"\", 97), Tuple.Create<System.Object, System.Int32>(product.id\n\n#line default\n#line hidden\n, 97), false)\n, Tuple.Create(Tuple.Create(\"\", 108), Tuple.Create(\"/Detail\", 108), true)\n);\n\nWriteLiteral(\">Details</a>\\r\\n<a\");\n\nWriteAttribute(\"href\", Tuple.Create(\" href=\\\"\", 132), Tuple.Create(\"\\\"\", 187)\n, Tuple.Create(Tuple.Create(\"\", 139), Tuple.Create<System.Object, System.Int32>(Href(\"~/A+Really(Crazy),Url.Is:This/\")\n, 139), false)\n\n#line 4 \"ResolveUrl.cshtml\"\n, Tuple.Create(Tuple.Create(\"\", 169), Tuple.Create<System.Object, System.Int32>(product.id\n\n#line default\n#line hidden\n, 169), false)\n, Tuple.Create(Tuple.Create(\"\", 180), Tuple.Create(\"/Detail\", 180), true)\n);\n\nWriteLiteral(\">Crazy Url!</a>\\r\\n\\r\\n\");\n\n\n#line 6 \"ResolveUrl.cshtml\"\n  \n\n\n#line default\n#line hidden\nWriteLiteral(\"    \");\n\nWriteLiteral(\"\\r\\n        <a\");\n\nWriteAttribute(\"href\", Tuple.Create(\" href=\\\"\", 233), Tuple.Create(\"\\\"\", 245)\n, Tuple.Create(Tuple.Create(\"\", 240), Tuple.Create<System.Object, System.Int32>(Href(\"~/Foo\")\n, 240), false)\n);\n\nWriteLiteral(\">Foo</a>\\r\\n        <a\");\n\nWriteAttribute(\"href\", Tuple.Create(\" href=\\\"\", 266), Tuple.Create(\"\\\"\", 295)\n, Tuple.Create(Tuple.Create(\"\", 273), Tuple.Create<System.Object, System.Int32>(Href(\"~/Products/\")\n, 273), false)\n\n#line 9 \"ResolveUrl.cshtml\"\n, Tuple.Create(Tuple.Create(\"\", 284), Tuple.Create<System.Object, System.Int32>(product.id\n\n#line default\n#line hidden\n, 284), false)\n);\n\nWriteLiteral(\">\");\n\n\n#line 9 \"ResolveUrl.cshtml\"\n                                    Write(product.Name);\n\n\n#line default\n#line hidden\nWriteLiteral(\"</a>\\r\\n        <a\");\n\nWriteAttribute(\"href\", Tuple.Create(\" href=\\\"\", 326), Tuple.Create(\"\\\"\", 362)\n, Tuple.Create(Tuple.Create(\"\", 333), Tuple.Create<System.Object, System.Int32>(Href(\"~/Products/\")\n, 333), false)\n\n#line 10 \"ResolveUrl.cshtml\"\n, Tuple.Create(Tuple.Create(\"\", 344), Tuple.Create<System.Object, System.Int32>(product.id\n\n#line default\n#line hidden\n, 344), false)\n, Tuple.Create(Tuple.Create(\"\", 355), Tuple.Create(\"/Detail\", 355), true)\n);\n\nWriteLiteral(\">Details</a>\\r\\n        <a\");\n\nWriteAttribute(\"href\", Tuple.Create(\" href=\\\"\", 387), Tuple.Create(\"\\\"\", 442)\n, Tuple.Create(Tuple.Create(\"\", 394), Tuple.Create<System.Object, System.Int32>(Href(\"~/A+Really(Crazy),Url.Is:This/\")\n, 394), false)\n\n#line 11 \"ResolveUrl.cshtml\"\n, Tuple.Create(Tuple.Create(\"\", 424), Tuple.Create<System.Object, System.Int32>(product.id\n\n#line default\n#line hidden\n, 424), false)\n, Tuple.Create(Tuple.Create(\"\", 435), Tuple.Create(\"/Detail\", 435), true)\n);\n\nWriteLiteral(\">Crazy Url!</a>\\r\\n    \");\n\nWriteLiteral(\"\\r\\n\");\n\n\n#line 13 \"ResolveUrl.cshtml\"\n\n\n#line default\n#line hidden\nWriteLiteral(\"\\r\\n\\r\\n\");\n\nDefineSection(\"Foo\", () => {\n\nWriteLiteral(\"\\r\\n    <a\");\n\nWriteAttribute(\"href\", Tuple.Create(\" href=\\\"\", 500), Tuple.Create(\"\\\"\", 512)\n, Tuple.Create(Tuple.Create(\"\", 507), Tuple.Create<System.Object, System.Int32>(Href(\"~/Foo\")\n, 507), false)\n);\n\nWriteLiteral(\">Foo</a>\\r\\n    <a\");\n\nWriteAttribute(\"href\", Tuple.Create(\" href=\\\"\", 529), Tuple.Create(\"\\\"\", 558)\n, Tuple.Create(Tuple.Create(\"\", 536), Tuple.Create<System.Object, System.Int32>(Href(\"~/Products/\")\n, 536), false)\n\n#line 17 \"ResolveUrl.cshtml\"\n, Tuple.Create(Tuple.Create(\"\", 547), Tuple.Create<System.Object, System.Int32>(product.id\n\n#line default\n#line hidden\n, 547), false)\n);\n\nWriteLiteral(\">\");\n\n\n#line 17 \"ResolveUrl.cshtml\"\n                                Write(product.Name);\n\n\n#line default\n#line hidden\nWriteLiteral(\"</a>\\r\\n    <a\");\n\nWriteAttribute(\"href\", Tuple.Create(\" href=\\\"\", 585), Tuple.Create(\"\\\"\", 621)\n, Tuple.Create(Tuple.Create(\"\", 592), Tuple.Create<System.Object, System.Int32>(Href(\"~/Products/\")\n, 592), false)\n\n#line 18 \"ResolveUrl.cshtml\"\n, Tuple.Create(Tuple.Create(\"\", 603), Tuple.Create<System.Object, System.Int32>(product.id\n\n#line default\n#line hidden\n, 603), false)\n, Tuple.Create(Tuple.Create(\"\", 614), Tuple.Create(\"/Detail\", 614), true)\n);\n\nWriteLiteral(\">Details</a>\\r\\n    <a\");\n\nWriteAttribute(\"href\", Tuple.Create(\" href=\\\"\", 642), Tuple.Create(\"\\\"\", 697)\n, Tuple.Create(Tuple.Create(\"\", 649), Tuple.Create<System.Object, System.Int32>(Href(\"~/A+Really(Crazy),Url.Is:This/\")\n, 649), false)\n\n#line 19 \"ResolveUrl.cshtml\"\n, Tuple.Create(Tuple.Create(\"\", 679), Tuple.Create<System.Object, System.Int32>(product.id\n\n#line default\n#line hidden\n, 679), false)\n, Tuple.Create(Tuple.Create(\"\", 690), Tuple.Create(\"/Detail\", 690), true)\n);\n\nWriteLiteral(\">Crazy Url!</a>\\r\\n\");\n\n});\n\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/Sections.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class Sections {\n#line hidden\npublic Sections() {\n}\npublic override void Execute() {\n\n#line 1 \"Sections.cshtml\"\n  \n    Layout = \"_SectionTestLayout.cshtml\"\n\n\n#line default\n#line hidden\nWriteLiteral(\"\\r\\n\\r\\n<div>This is in the Body>\\r\\n\\r\\n\");\n\nDefineSection(\"Section2\", () => {\n\nWriteLiteral(\"\\r\\n    <div>This is in Section 2</div>\\r\\n\");\n\n});\n\nWriteLiteral(\"\\r\\n\");\n\nDefineSection(\"Section1\", () => {\n\nWriteLiteral(\"\\r\\n    <div>This is in Section 1</div>\\r\\n\");\n\n});\n\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/SimpleUnspacedIf.DesignTime.Tabs.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class SimpleUnspacedIf {\n#line hidden\npublic SimpleUnspacedIf() {\n}\npublic override void Execute() {\n\n#line 1 \"SimpleUnspacedIf.cshtml\"\nif (true)\n{\n\t\n\n#line default\n#line hidden\n\n#line 2 \"SimpleUnspacedIf.cshtml\"\n\t\t\t   \n}\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/Templates.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class Templates {\n#line hidden\n#line 1 \"Templates.cshtml\"\n            \n    public HelperResult Repeat(int times, Func<int, object> template) {\n        return new HelperResult((writer) => {\n            for(int i = 0; i < times; i++) {\n                ((HelperResult)template(i)).WriteTo(writer);\n            }\n        });\n    }\n\n#line default\n#line hidden\n\npublic Templates() {\n}\npublic override void Execute() {\nWriteLiteral(\"\\r\\n\");\n\n\n#line 11 \"Templates.cshtml\"\n  \n    Func<dynamic, object> foo = \n\n#line default\n#line hidden\nitem => new Template(__razor_template_writer => {\n\nWriteLiteralTo(__razor_template_writer, \"This works \");\n\n\n#line 12 \"Templates.cshtml\"\n                  WriteTo(__razor_template_writer, item);\n\n\n#line default\n#line hidden\nWriteLiteralTo(__razor_template_writer, \"!\");\n\n})\n\n#line 12 \"Templates.cshtml\"\n                                                               ;\n    \n\n#line default\n#line hidden\n\n#line 13 \"Templates.cshtml\"\nWrite(foo(\"\"));\n\n\n#line default\n#line hidden\n\n#line 13 \"Templates.cshtml\"\n            \n\n\n#line default\n#line hidden\nWriteLiteral(\"\\r\\n\\r\\n<ul>\\r\\n\");\n\n\n#line 17 \"Templates.cshtml\"\nWrite(Repeat(10, item => new Template(__razor_template_writer => {\n\n\n#line default\n#line hidden\nWriteLiteralTo(__razor_template_writer, \"<li>Item #\");\n\n\n#line 17 \"Templates.cshtml\"\nWriteTo(__razor_template_writer, item);\n\n\n#line default\n#line hidden\nWriteLiteralTo(__razor_template_writer, \"</li>\");\n\n\n#line 17 \"Templates.cshtml\"\n                                })));\n\n\n#line default\n#line hidden\nWriteLiteral(\"\\r\\n</ul>\\r\\n\\r\\n<p>\\r\\n\");\n\n\n#line 21 \"Templates.cshtml\"\nWrite(Repeat(10,\n    item => new Template(__razor_template_writer => {\n\n\n#line default\n#line hidden\nWriteLiteralTo(__razor_template_writer, \" This is line#\");\n\n\n#line 22 \"Templates.cshtml\"\nWriteTo(__razor_template_writer, item);\n\n\n#line default\n#line hidden\nWriteLiteralTo(__razor_template_writer, \" of markup<br/>\\r\\n\");\n\n\n#line 23 \"Templates.cshtml\"\n})));\n\n\n#line default\n#line hidden\nWriteLiteral(\"\\r\\n</p>\\r\\n\\r\\n<ul>\\r\\n\");\n\nWriteLiteral(\"    \");\n\n\n#line 27 \"Templates.cshtml\"\nWrite(Repeat(10, item => new Template(__razor_template_writer => {\n\n\n#line default\n#line hidden\nWriteLiteralTo(__razor_template_writer, \"<li>\\r\\n        Item #\");\n\n\n#line 28 \"Templates.cshtml\"\nWriteTo(__razor_template_writer, item);\n\n\n#line default\n#line hidden\nWriteLiteralTo(__razor_template_writer, \"\\r\\n\");\n\n\n#line 29 \"Templates.cshtml\"\n        \n\n#line default\n#line hidden\n\n#line 29 \"Templates.cshtml\"\n          var parent = item;\n\n#line default\n#line hidden\nWriteLiteralTo(__razor_template_writer, \"\\r\\n        <ul>\\r\\n            <li>Child Items... ?</li>\\r\\n            \");\n\nWriteLiteralTo(__razor_template_writer, \"\\r\\n        </ul>\\r\\n    </li>\");\n\n\n#line 34 \"Templates.cshtml\"\n       })));\n\n\n#line default\n#line hidden\nWriteLiteral(\"\\r\\n</ul> \");\n\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/UnfinishedExpressionInCode.Tabs.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class UnfinishedExpressionInCode {\nprivate static object @__o;\n#line hidden\npublic UnfinishedExpressionInCode() {\n}\npublic override void Execute() {\n\n#line 1 \"UnfinishedExpressionInCode.cshtml\"\n  \n\n\n#line default\n#line hidden\n\n#line 2 \"UnfinishedExpressionInCode.cshtml\"\n__o = DateTime.;\n\n\n#line default\n#line hidden\n\n#line 3 \"UnfinishedExpressionInCode.cshtml\"\n\t\t  \n\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Output/UnfinishedExpressionInCode.cs",
    "content": "//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace TestOutput {\nusing System;\n\npublic class UnfinishedExpressionInCode {\nprivate static object @__o;\n#line hidden\npublic UnfinishedExpressionInCode() {\n}\npublic override void Execute() {\n\n#line 1 \"UnfinishedExpressionInCode.cshtml\"\n  \n\n\n#line default\n#line hidden\n\n#line 2 \"UnfinishedExpressionInCode.cshtml\"\n__o = DateTime.;\n\n\n#line default\n#line hidden\n\n#line 3 \"UnfinishedExpressionInCode.cshtml\"\n          \n\n\n#line default\n#line hidden\n}\n}\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/Blocks.cshtml",
    "content": "﻿@{\n    int i = 1;\n}\n\n@while(i <= 10) {\n    <p>Hello from C#, #@(i)</p>\n    i += 1;\n}\n\n@if(i == 11) {\n    <p>We wrote 10 lines!</p>\n}\n\n@switch(i) {\n    case 11:\n        <p>No really, we wrote 10 lines!</p>\n        break;\n    default:\n        <p>Actually, we didn't...</p>\n        break;\n}\n\n@for(int j = 1; j <= 10; j += 2) {\n    <p>Hello again from C#, #@(j)</p>\n}\n\n@try {\n    <p>That time, we wrote 5 lines!</p>\n} catch(Exception ex) {\n    <p>Oh no! An error occurred: @(ex.Message)</p>\n}\n\n<p>i is now @i</p>\n\n@lock(new object()) {\n    <p>This block is locked, for your security!</p>\n}"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/CodeBlock.cshtml",
    "content": "﻿@{\n    for(int i = 1; i <= 10; i++) {\n        Output.Write(\"<p>Hello from C#, #\" + i.ToString() + \"</p>\");\n    }\n}"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/CodeBlockAtEOF.cshtml",
    "content": "﻿@{"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/ConditionalAttributes.cshtml",
    "content": "﻿@{\n    var ch = true;\n    var cls = \"bar\";\n    <a href=\"Foo\" />\n    <p class=\"@cls\" />\n    <p class=\"foo @cls\" />\n    <p class=\"@cls foo\" />\n    <input type=\"checkbox\" checked=\"@ch\" />\n    <input type=\"checkbox\" checked=\"foo @ch\" />\n    <p class=\"@if(cls != null) { @cls }\" />\n    <a href=\"~/Foo\" />\n    <script src=\"@Url.Content(\"~/Scripts/jquery-1.6.2.min.js\")\" type=\"text/javascript\"></script>\n    <script src=\"@Url.Content(\"~/Scripts/modernizr-2.0.6-development-only.js\")\" type=\"text/javascript\"></script>\n    <script src=\"http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/jquery-ui.min.js\" type=\"text/javascript\"></script>\n}"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/DesignTime.cshtml",
    "content": "﻿<div>\n            @for(int i = 1; i <= 10; i++) {\n    <p>This is item #@i</p>\n            }\n</div>\n\n<p>\n@(Foo(Bar.Baz))\n@Foo(@<p>Bar @baz Biz</p>)\n</p>\n\n@section Footer {\n    <p>Foo</p>\n    @bar\n}\n\n@helper Foo() {\n    if(true) {\n        <p>Foo</p>\n    }\n}"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/EmptyCodeBlock.cshtml",
    "content": "﻿This is markup\n\n@{}"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/EmptyExplicitExpression.cshtml",
    "content": "﻿This is markup\n\n@()"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/EmptyImplicitExpression.cshtml",
    "content": "﻿This is markup\n\n@!"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/EmptyImplicitExpressionInCode.cshtml",
    "content": "﻿@{\n    @\n}"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/ExplicitExpression.cshtml",
    "content": "﻿1 + 1 = @(1+1)"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/ExplicitExpressionAtEOF.cshtml",
    "content": "﻿This is markup\n\n@("
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/ExpressionsInCode.cshtml",
    "content": "﻿@{\n    object foo = null;\n    string bar = \"Foo\";\n}\n\n@if(foo != null) {\n    @foo\n} else {\n    <p>Foo is Null!</p>\n}\n\n<p>\n@if(!String.IsNullOrEmpty(bar)) {\n    @(bar.Replace(\"F\", \"B\"))\n}\n</p>"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/FunctionsBlock.cshtml",
    "content": "﻿@functions {\n\n}\n\n@functions {\n    Random _rand = new Random();\n    private int RandomInt() {\n        return _rand.Next();\n    }\n}\n\nHere's a random number: @RandomInt()"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/FunctionsBlockMinimal.cshtml",
    "content": "﻿\n\n\t@functions{\nstring foo(string input) {\n\treturn input + \"!\";\n}\n}"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/FunctionsBlock_Tabs.cshtml",
    "content": "﻿@functions {\n\n}\n\n@functions {\n\tRandom _rand = new Random();\n\tprivate int RandomInt() {\n\t\treturn _rand.Next();\n\t}\n}\n\nHere's a random number: @RandomInt()"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/Helpers.cshtml",
    "content": "﻿@helper Bold(string s) {\n    s = s.ToUpper();\n    <strong>@s</strong>\n}\n\n@helper Italic(string s) {\n    s = s.ToUpper();\n    <em>@s</em>\n}\n\n@Bold(\"Hello\")"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/HelpersMissingCloseParen.cshtml",
    "content": "@helper Bold(string s) {\n    s = s.ToUpper();\n    <strong>@s</strong>\n}\n\n@helper Italic(string s\n@Bold(\"Hello\")"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/HelpersMissingName.cshtml",
    "content": "@helper"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/HelpersMissingOpenBrace.cshtml",
    "content": "@helper Bold(string s) {\n    s = s.ToUpper();\n    <strong>@s</strong>\n}\n\n@helper Italic(string s) \n@Italic(s)"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/HelpersMissingOpenParen.cshtml",
    "content": "@helper Bold(string s) {\n    s = s.ToUpper();\n    <strong>@s</strong>\n}\n\n@helper Italic\n@Bold(\"Hello\")"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/HiddenSpansInCode.cshtml",
    "content": "﻿@{\n    @@Da\n}"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/HtmlCommentWithQuote_Double.cshtml",
    "content": "﻿<!-- \" -->\n<img src=\"~/images/submit.png\" />"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/HtmlCommentWithQuote_Single.cshtml",
    "content": "﻿<!-- ' -->\n<img src=\"~/images/submit.png\" />"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/ImplicitExpression.cshtml",
    "content": "﻿@for(int i = 1; i <= 10; i++) {\n    <p>This is item #@i</p>\n}"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/ImplicitExpressionAtEOF.cshtml",
    "content": "﻿This is markup\n\n@"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/Imports.cshtml",
    "content": "﻿@using System.IO\n@using Foo = System.Text.Encoding\n@using System\n\n<p>Path's full type name is @typeof(Path).FullName</p>\n<p>Foo's actual full type name is @typeof(Foo).FullName</p>"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/Inherits.cshtml",
    "content": "﻿@foo()\n\n@inherits foo.bar<baz<biz>>.boz bar\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/InlineBlocks.cshtml",
    "content": "﻿@helper Link(string link) {\n    <a href=\"@if(link != null) { @link } else { <text>#</text> }\" />\n}"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/Instrumented.cshtml",
    "content": "﻿@helper Strong(string s) {\n    <strong>@s</strong>\n}\n\n@{\n    int i = 1;\n    var foo = @<p>Bar</p>;\n    @:Hello, World\n    <p>Hello, World</p>\n}\n\n@while(i <= 10) {\n    <p>Hello from C#, #@(i)</p>\n    i += 1;\n}\n\n@if(i == 11) {\n    <p>We wrote 10 lines!</p>\n}\n\n@switch(i) {\n    case 11:\n        <p>No really, we wrote 10 lines!</p>\n        break;\n    default:\n        <p>Actually, we didn't...</p>\n        break;\n}\n\n@for(int j = 1; j <= 10; j += 2) {\n    <p>Hello again from C#, #@(j)</p>\n}\n\n@try {\n    <p>That time, we wrote 5 lines!</p>\n} catch(Exception ex) {\n    <p>Oh no! An error occurred: @(ex.Message)</p>\n}\n\n@lock(new object()) {\n    <p>This block is locked, for your security!</p>\n}"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/LayoutDirective.cshtml",
    "content": "﻿@layout ~/Foo/Bar/Baz"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/MarkupInCodeBlock.cshtml",
    "content": "﻿@{\n    for(int i = 1; i <= 10; i++) {\n        <p>Hello from C#, #@(i.ToString())</p>\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/NestedCodeBlocks.cshtml",
    "content": "﻿@if(foo) {\n    @if(bar) {\n    }\n}"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/NestedHelpers.cshtml",
    "content": "﻿@helper Italic(string s) {\n    s = s.ToUpper();\n    @helper Bold(string s) {\n        s = s.ToUpper();\n        <strong>@s</strong>\n    }\n    <em>@Bold(s)</em>\n}\n\n@Italic(\"Hello\")"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/NoLinePragmas.cshtml",
    "content": "﻿@{\n    int i = 1;\n}\n\n@while(i <= 10) {\n    <p>Hello from C#, #@(i)</p>\n    i += 1;\n}\n\n@if(i == 11) {\n    <p>We wrote 10 lines!</p>\n}\n\n@switch(i) {\n    case 11:\n        <p>No really, we wrote 10 lines!</p>\n        break;\n    default:\n        <p>Actually, we didn't...</p>\n        break;\n}\n\n@for(int j = 1; j <= 10; j += 2) {\n    <p>Hello again from C#, #@(j)</p>\n}\n\n@try {\n    <p>That time, we wrote 5 lines!</p>\n} catch(Exception ex) {\n    <p>Oh no! An error occurred: @(ex.Message)</p>\n}\n\n@* With has no equivalent in C# *@\n<p>i is now @i</p>\n\n@lock(new object()) {\n    <p>This block is locked, for your security!</p>\n}"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/OpenedIf.cshtml",
    "content": "﻿<html>\n<body>\n@if (true) { \n</body>\n</html>"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/ParserError.cshtml",
    "content": "﻿@{\n/*\nint i =10;\nint j =20;\n}"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/RazorComments.cshtml",
    "content": "﻿@*This is not going to be rendered*@\n<p>This should @* not *@ be shown</p>\n\n@{\n    @* throw new Exception(\"Oh no!\") *@\n    Exception foo = @* new Exception(\"Oh no!\") *@ null;\n    if(foo != null) {\n        throw foo;\n    }\n}\n\n@{ var bar = \"@* bar *@\"; }\n<p>But this should show the comment syntax: @bar</p>\n\n@(a@**@b)\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/ResolveUrl.cshtml",
    "content": "﻿<a href=\"~/Foo\">Foo</a>\n<a href=\"~/Products/@product.id\">@product.Name</a>\n<a href=\"~/Products/@product.id/Detail\">Details</a>\n<a href=\"~/A+Really(Crazy),Url.Is:This/@product.id/Detail\">Crazy Url!</a>\n\n@{\n    <text>\n        <a href=\"~/Foo\">Foo</a>\n        <a href=\"~/Products/@product.id\">@product.Name</a>\n        <a href=\"~/Products/@product.id/Detail\">Details</a>\n        <a href=\"~/A+Really(Crazy),Url.Is:This/@product.id/Detail\">Crazy Url!</a>\n    </text>\n}\n\n@section Foo {\n    <a href=\"~/Foo\">Foo</a>\n    <a href=\"~/Products/@product.id\">@product.Name</a>\n    <a href=\"~/Products/@product.id/Detail\">Details</a>\n    <a href=\"~/A+Really(Crazy),Url.Is:This/@product.id/Detail\">Crazy Url!</a>\n}"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/Sections.cshtml",
    "content": "﻿@{\n    Layout = \"_SectionTestLayout.cshtml\"\n}\n\n<div>This is in the Body>\n\n@section Section2 {\n    <div>This is in Section 2</div>\n}\n\n@section Section1 {\n    <div>This is in Section 1</div>\n}"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/SimpleUnspacedIf.cshtml",
    "content": "﻿@if (true)\n{\n\t<div></div>\n}"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/Templates.cshtml",
    "content": "﻿@functions {\n    public HelperResult Repeat(int times, Func<int, object> template) {\n        return new HelperResult((writer) => {\n            for(int i = 0; i < times; i++) {\n                ((HelperResult)template(i)).WriteTo(writer);\n            }\n        });\n    }\n}\n\n@{\n    Func<dynamic, object> foo = @<text>This works @item!</text>;\n    @foo(\"\")\n}\n\n<ul>\n@(Repeat(10, @<li>Item #@item</li>))\n</ul>\n\n<p>\n@Repeat(10,\n    @: This is line#@item of markup<br/>\n)\n</p>\n\n<ul>\n    @Repeat(10, @<li>\n        Item #@item\n        @{var parent = item;}\n        <ul>\n            <li>Child Items... ?</li>\n            @*Repeat(10, @<li>Item #@(parent).@item</li>)*@\n        </ul>\n    </li>)\n</ul> "
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/CS/Source/UnfinishedExpressionInCode.cshtml",
    "content": "﻿@{\n@DateTime.\n}"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/Blocks.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class Blocks\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\n\n#ExternalSource(\"Blocks.vbhtml\",1)\n     \n    Dim i as Integer = 1\n\n\n#End ExternalSource\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Blocks.vbhtml\",5)\n While i <= 10\n\n\n#End ExternalSource\nWriteLiteral(\"    \")\n\nWriteLiteral(\"<p>Hello from VB.Net, #\")\n\n\n#ExternalSource(\"Blocks.vbhtml\",6)\n                        Write(i)\n\n\n#End ExternalSource\nWriteLiteral(\"</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Blocks.vbhtml\",7)\n    i += 1\nEnd While\n\n\n#End ExternalSource\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Blocks.vbhtml\",10)\n If i = 11 Then\n\n\n#End ExternalSource\nWriteLiteral(\"    \")\n\nWriteLiteral(\"<p>We wrote 10 lines!</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Blocks.vbhtml\",12)\nEnd If\n\n\n#End ExternalSource\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Blocks.vbhtml\",14)\n Do\n\n\n#End ExternalSource\nWriteLiteral(\"    \")\n\nWriteLiteral(\"<p>Hello again: \")\n\n\n#ExternalSource(\"Blocks.vbhtml\",15)\n                Write(i)\n\n\n#End ExternalSource\nWriteLiteral(\"</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Blocks.vbhtml\",16)\n    i -= 1\nLoop While i > 0\n\n\n#End ExternalSource\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Blocks.vbhtml\",19)\n Select Case i\n    Case 11\n\n\n#End ExternalSource\nWriteLiteral(\"        \")\n\nWriteLiteral(\"<p>No really, we wrote 10 lines!</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Blocks.vbhtml\",22)\n    Case Else\n\n\n#End ExternalSource\nWriteLiteral(\"        \")\n\nWriteLiteral(\"<p>We wrote a bunch more lines too!</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Blocks.vbhtml\",24)\nEnd Select\n\n\n#End ExternalSource\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Blocks.vbhtml\",26)\n For j as Integer = 1 to 10 Step 2\n\n\n#End ExternalSource\nWriteLiteral(\"    \")\n\nWriteLiteral(\"<p>Hello again from VB.Net, #\")\n\n\n#ExternalSource(\"Blocks.vbhtml\",27)\n                              Write(j)\n\n\n#End ExternalSource\nWriteLiteral(\"</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Blocks.vbhtml\",28)\nNext j\n\n\n#End ExternalSource\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Blocks.vbhtml\",30)\n Try\n\n\n#End ExternalSource\nWriteLiteral(\"    \")\n\nWriteLiteral(\"<p>That time, we wrote 5 lines!</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Blocks.vbhtml\",32)\nCatch ex as Exception\n\n\n#End ExternalSource\nWriteLiteral(\"    \")\n\nWriteLiteral(\"<p>Oh no! An error occurred: \")\n\n\n#ExternalSource(\"Blocks.vbhtml\",33)\n                              Write(ex.Message)\n\n\n#End ExternalSource\nWriteLiteral(\"</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Blocks.vbhtml\",34)\nEnd Try\n\n\n#End ExternalSource\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Blocks.vbhtml\",36)\n With i\n\n\n#End ExternalSource\nWriteLiteral(\"    \")\n\nWriteLiteral(\"<p>i is now \")\n\n\n#ExternalSource(\"Blocks.vbhtml\",37)\n             Write(.ToString())\n\n\n#End ExternalSource\nWriteLiteral(\"</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Blocks.vbhtml\",38)\nEnd With\n\n\n#End ExternalSource\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Blocks.vbhtml\",40)\n SyncLock New Object()\n\n\n#End ExternalSource\nWriteLiteral(\"    \")\n\nWriteLiteral(\"<p>This block is locked, for your security!</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Blocks.vbhtml\",42)\nEnd SyncLock\n\n\n#End ExternalSource\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Blocks.vbhtml\",44)\n Using New System.IO.MemoryStream()\n\n\n#End ExternalSource\nWriteLiteral(\"    \")\n\nWriteLiteral(\"<p>Some random memory stream will be disposed after rendering this block</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Blocks.vbhtml\",46)\nEnd Using\n\n#End ExternalSource\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/CodeBlock.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class CodeBlock\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\n\n#ExternalSource(\"CodeBlock.vbhtml\",1)\n     \n    Test()\n\n\n#End ExternalSource\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/CodeBlockAtEOF.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class CodeBlockAtEOF\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\n\n#ExternalSource(\"CodeBlockAtEOF.vbhtml\",1)\n     \n\n#End ExternalSource\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/Comments.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class Comments\nPublic Overrides Sub Execute()\n\n\n#ExternalSource(\"Comments.vbhtml\",1)\n 'This is not going to be rendered\n\n\n#End ExternalSource\nWriteLiteral(\"<p>This is going to be rendered</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n\n#ExternalSource(\"Comments.vbhtml\",3)\n REM Neither is this\n\n\n#End ExternalSource\n\n\n#ExternalSource(\"Comments.vbhtml\",4)\n rem nor this\n\n\n#End ExternalSource\n\n\n#ExternalSource(\"Comments.vbhtml\",5)\n rEm nor this\n\n#End ExternalSource\n\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/ConditionalAttributes.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class ConditionalAttributes\n\n#ExternalSource(\"ConditionalAttributes.vbhtml\", 1)\nPublic Shared Function Link(ByVal url As String, text As String) As Template\n\n#End ExternalSource\nReturn New Template(Sub (__razor_helper_writer)\n\n#ExternalSource(\"ConditionalAttributes.vbhtml\", 1)\n                                                  \n\n\n#End ExternalSource\nWriteLiteralTo(__razor_helper_writer, \"    \")\n\nWriteLiteralTo(__razor_helper_writer, \"<a\")\n\nWriteAttributeTo(__razor_helper_writer, \"href\", Tuple.Create(\" href=\"\"\", 59), Tuple.Create(\"\"\"\", 70) _\n, Tuple.Create(Tuple.Create(\"\", 66), Tuple.Create(Of System.Object, System.Int32)(url _\n, 66), False) _\n)\n\nWriteLiteralTo(__razor_helper_writer, \">\")\n\n\n#ExternalSource(\"ConditionalAttributes.vbhtml\", 2)\nWriteTo(__razor_helper_writer, text)\n\n\n#End ExternalSource\nWriteLiteralTo(__razor_helper_writer, \"</a> \"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"ConditionalAttributes.vbhtml\", 3)\n\n\n#End ExternalSource\nEnd Sub)\nEnd Function\n\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\nWriteLiteral(\" \"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"ConditionalAttributes.vbhtml\",5)\n     \n    Dim ch = True\n    Dim cls = \"bar\"\n\n\n#End ExternalSource\nWriteLiteral(\"    \")\n\nWriteLiteral(\"<a\")\n\nWriteLiteral(\" href=\"\"Foo\"\"\")\n\nWriteLiteral(\" />\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nWriteLiteral(\"    \")\n\nWriteLiteral(\"<p\")\n\nWriteAttribute(\"class\", Tuple.Create(\" class=\"\"\", 176), Tuple.Create(\"\"\"\", 188) _\n, Tuple.Create(Tuple.Create(\"\", 184), Tuple.Create(Of System.Object, System.Int32)(cls _\n, 184), False) _\n)\n\nWriteLiteral(\" />\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nWriteLiteral(\"    \")\n\nWriteLiteral(\"<p\")\n\nWriteAttribute(\"class\", Tuple.Create(\" class=\"\"\", 201), Tuple.Create(\"\"\"\", 217) _\n, Tuple.Create(Tuple.Create(\"\", 209), Tuple.Create(\"foo\", 209), True) _\n, Tuple.Create(Tuple.Create(\" \", 212), Tuple.Create(Of System.Object, System.Int32)(cls _\n, 213), False) _\n)\n\nWriteLiteral(\" />\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nWriteLiteral(\"    \")\n\nWriteLiteral(\"<p\")\n\nWriteAttribute(\"class\", Tuple.Create(\" class=\"\"\", 230), Tuple.Create(\"\"\"\", 246) _\n, Tuple.Create(Tuple.Create(\"\", 238), Tuple.Create(Of System.Object, System.Int32)(cls _\n, 238), False) _\n, Tuple.Create(Tuple.Create(\" \", 242), Tuple.Create(\"foo\", 243), True) _\n)\n\nWriteLiteral(\" />\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nWriteLiteral(\"    \")\n\nWriteLiteral(\"<input\")\n\nWriteLiteral(\" type=\"\"checkbox\"\"\")\n\nWriteAttribute(\"checked\", Tuple.Create(\" checked=\"\"\", 279), Tuple.Create(\"\"\"\", 292) _\n, Tuple.Create(Tuple.Create(\"\", 289), Tuple.Create(Of System.Object, System.Int32)(ch _\n, 289), False) _\n)\n\nWriteLiteral(\" />\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nWriteLiteral(\"    \")\n\nWriteLiteral(\"<input\")\n\nWriteLiteral(\" type=\"\"checkbox\"\"\")\n\nWriteAttribute(\"checked\", Tuple.Create(\" checked=\"\"\", 325), Tuple.Create(\"\"\"\", 342) _\n, Tuple.Create(Tuple.Create(\"\", 335), Tuple.Create(\"foo\", 335), True) _\n, Tuple.Create(Tuple.Create(\" \", 338), Tuple.Create(Of System.Object, System.Int32)(ch _\n, 339), False) _\n)\n\nWriteLiteral(\" />\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nWriteLiteral(\"    \")\n\nWriteLiteral(\"<p\")\n\nWriteAttribute(\"class\", Tuple.Create(\" class=\"\"\", 355), Tuple.Create(\"\"\"\", 401) _\n, Tuple.Create(Tuple.Create(\"\", 363), Tuple.Create(Of System.Object, System.Int32)(New Template(Sub (__razor_attribute_value_writer)\n\n\n#ExternalSource(\"ConditionalAttributes.vbhtml\",14)\n                If cls IsNot Nothing Then \n\n#End ExternalSource\n\n#ExternalSource(\"ConditionalAttributes.vbhtml\",14)\n   WriteTo(__razor_attribute_value_writer, cls)\n\n\n#End ExternalSource\n\n#ExternalSource(\"ConditionalAttributes.vbhtml\",14)\n                                               End If\n\n#End ExternalSource\nEnd Sub), 363), False) _\n)\n\nWriteLiteral(\" />\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nWriteLiteral(\"    \")\n\nWriteLiteral(\"<a\")\n\nWriteAttribute(\"href\", Tuple.Create(\" href=\"\"\", 414), Tuple.Create(\"\"\"\", 426) _\n, Tuple.Create(Tuple.Create(\"\", 421), Tuple.Create(Of System.Object, System.Int32)(Href(\"~/Foo\") _\n, 421), False) _\n)\n\nWriteLiteral(\" />\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"ConditionalAttributes.vbhtml\",16)\n\n\n#End ExternalSource\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/DesignTime.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class DesignTime\nPrivate Shared __o As Object\n\n#ExternalSource(\"DesignTime.vbhtml\", 9)\nPublic Shared Function Foo() As Template\n\n#End ExternalSource\nReturn New Template(Sub (__razor_helper_writer)\n\n#ExternalSource(\"DesignTime.vbhtml\", 10)\n             \n    If True Then\n        \n\n#End ExternalSource\n\n#ExternalSource(\"DesignTime.vbhtml\", 11)\n                   \n    End If\n\n\n#End ExternalSource\nEnd Sub)\nEnd Function\n\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\n\n#ExternalSource(\"DesignTime.vbhtml\",1)\n            For i = 1 to 10\n\n\n#End ExternalSource\n\n#ExternalSource(\"DesignTime.vbhtml\",2)\n             __o = i\n\n\n#End ExternalSource\n\n#ExternalSource(\"DesignTime.vbhtml\",3)\n                        \n            Next\n\n\n#End ExternalSource\n\n#ExternalSource(\"DesignTime.vbhtml\",4)\n__o = Foo(Bar.Baz)\n\n\n#End ExternalSource\n\n#ExternalSource(\"DesignTime.vbhtml\",5)\n__o = Foo(Function (item) New Template(Sub (__razor_template_writer)\n\n\n#End ExternalSource\n\n#ExternalSource(\"DesignTime.vbhtml\",6)\n         __o = baz\n\n\n#End ExternalSource\n\n#ExternalSource(\"DesignTime.vbhtml\",7)\n                  End Sub))\n\n\n#End ExternalSource\nDefineSection(\"Footer\", Sub ()\n\n\n#ExternalSource(\"DesignTime.vbhtml\",8)\n__o = bar\n\n\n#End ExternalSource\nEnd Sub)\n\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/EmptyExplicitExpression.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class EmptyExplicitExpression\nPrivate Shared __o As Object\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\n\n#ExternalSource(\"EmptyExplicitExpression.vbhtml\",1)\n__o = \n\n\n#End ExternalSource\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/EmptyImplicitExpression.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class EmptyImplicitExpression\nPrivate Shared __o As Object\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\n\n#ExternalSource(\"EmptyImplicitExpression.vbhtml\",1)\n__o = \n\n\n#End ExternalSource\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/EmptyImplicitExpressionInCode.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class EmptyImplicitExpressionInCode\nPrivate Shared __o As Object\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\n\n#ExternalSource(\"EmptyImplicitExpressionInCode.vbhtml\",1)\n     \n    \n\n#End ExternalSource\n\n#ExternalSource(\"EmptyImplicitExpressionInCode.vbhtml\",2)\n__o = \n\n\n#End ExternalSource\n\n#ExternalSource(\"EmptyImplicitExpressionInCode.vbhtml\",3)\n     \n\n\n#End ExternalSource\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/EmptySection.vb",
    "content": "﻿'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class EmptySection\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\nDefineSection(\"anything\", Sub ()\n\nWriteLiteral(\" \")\n\nEnd Sub)\n\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/ExplicitExpression.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class ExplicitExpression\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\n\n#ExternalSource(\"ExplicitExpression.vbhtml\",1)\nWrite(Foo(Bar.Baz))\n\n\n#End ExternalSource\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/ExplicitExpressionAtEOF.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class ExplicitExpressionAtEOF\nPrivate Shared __o As Object\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\n\n#ExternalSource(\"ExplicitExpressionAtEOF.vbhtml\",1)\n__o = \n\n\n#End ExternalSource\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/ExpressionsInCode.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class ExpressionsInCode\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\n\n#ExternalSource(\"ExpressionsInCode.vbhtml\",1)\n     \n    Dim foo As Object = Nothing\n    Dim bar as String = \"Foo\"\n\n\n#End ExternalSource\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"ExpressionsInCode.vbhtml\",6)\n If foo IsNot Nothing Then\n    \n\n#End ExternalSource\n\n#ExternalSource(\"ExpressionsInCode.vbhtml\",7)\nWrite(foo)\n\n\n#End ExternalSource\n\n#ExternalSource(\"ExpressionsInCode.vbhtml\",7)\n        \nElse\n\n\n#End ExternalSource\nWriteLiteral(\"    \")\n\nWriteLiteral(\"<p>Foo is Null!</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"ExpressionsInCode.vbhtml\",10)\nEnd If\n\n\n#End ExternalSource\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"<p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"ExpressionsInCode.vbhtml\",13)\n If Not String.IsNullOrEmpty(bar) Then\n    \n\n#End ExternalSource\n\n#ExternalSource(\"ExpressionsInCode.vbhtml\",14)\nWrite(bar.Replace(\"F\", \"B\"))\n\n\n#End ExternalSource\n\n#ExternalSource(\"ExpressionsInCode.vbhtml\",14)\n                            \nEnd If\n\n\n#End ExternalSource\nWriteLiteral(\"</p>\")\n\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/FunctionsBlock.DesignTime.Tabs.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class FunctionsBlock\nPrivate Shared __o As Object\n\n#ExternalSource(\"FunctionsBlock.vbhtml\",1)\n\t\t  \n\n\n#End ExternalSource\n\n#ExternalSource(\"FunctionsBlock.vbhtml\",2)\n\t\t  \n    Private _rand as New Random()\n    Private Function RandomInt() as Integer\n        Return _rand.Next()\n    End Function\n\n#End ExternalSource\n\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\n\n#ExternalSource(\"FunctionsBlock.vbhtml\",3)\n\t\t\t\t   __o = RandomInt()\n\n\n#End ExternalSource\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/FunctionsBlock.DesignTime.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class FunctionsBlock\nPrivate Shared __o As Object\n\n#ExternalSource(\"FunctionsBlock.vbhtml\",1)\n          \n\n\n#End ExternalSource\n\n#ExternalSource(\"FunctionsBlock.vbhtml\",2)\n          \n    Private _rand as New Random()\n    Private Function RandomInt() as Integer\n        Return _rand.Next()\n    End Function\n\n#End ExternalSource\n\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\n\n#ExternalSource(\"FunctionsBlock.vbhtml\",3)\n                   __o = RandomInt()\n\n\n#End ExternalSource\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/FunctionsBlock.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class FunctionsBlock\n\n#ExternalSource(\"FunctionsBlock.vbhtml\",1)\n          \n\n\n#End ExternalSource\n\n#ExternalSource(\"FunctionsBlock.vbhtml\",5)\n          \n    Private _rand as New Random()\n    Private Function RandomInt() as Integer\n        Return _rand.Next()\n    End Function\n\n#End ExternalSource\n\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"Here's a random number: \")\n\n\n#ExternalSource(\"FunctionsBlock.vbhtml\",12)\n                   Write(RandomInt())\n\n\n#End ExternalSource\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/Helpers.Instance.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class Helpers\n\n#ExternalSource(\"Helpers.vbhtml\", 1)\nPublic Function Bold(s as String) As Template\n\n#End ExternalSource\nReturn New Template(Sub (__razor_helper_writer)\n\n#ExternalSource(\"Helpers.vbhtml\", 1)\n                         \n    s = s.ToUpper()\n\n\n#End ExternalSource\nWriteLiteralTo(__razor_helper_writer, \"    \")\n\nWriteLiteralTo(__razor_helper_writer, \"<strong>\")\n\n\n#ExternalSource(\"Helpers.vbhtml\", 3)\nWriteTo(__razor_helper_writer, s)\n\n\n#End ExternalSource\nWriteLiteralTo(__razor_helper_writer, \"</strong>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Helpers.vbhtml\", 4)\n\n\n#End ExternalSource\nEnd Sub)\nEnd Function\n\n#ExternalSource(\"Helpers.vbhtml\", 6)\nPublic Function Italic(s as String) As Template\n\n#End ExternalSource\nReturn New Template(Sub (__razor_helper_writer)\n\n#ExternalSource(\"Helpers.vbhtml\", 6)\n                           \n    s = s.ToUpper()\n\n\n#End ExternalSource\nWriteLiteralTo(__razor_helper_writer, \"    \")\n\nWriteLiteralTo(__razor_helper_writer, \"<em>\")\n\n\n#ExternalSource(\"Helpers.vbhtml\", 8)\nWriteTo(__razor_helper_writer, s)\n\n\n#End ExternalSource\nWriteLiteralTo(__razor_helper_writer, \"</em>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Helpers.vbhtml\", 9)\n\n\n#End ExternalSource\nEnd Sub)\nEnd Function\n\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Helpers.vbhtml\",11)\nWrite(Bold(\"Hello\"))\n\n\n#End ExternalSource\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/Helpers.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class Helpers\n\n#ExternalSource(\"Helpers.vbhtml\", 1)\nPublic Shared Function Bold(s as String) As Template\n\n#End ExternalSource\nReturn New Template(Sub (__razor_helper_writer)\n\n#ExternalSource(\"Helpers.vbhtml\", 1)\n                         \n    s = s.ToUpper()\n\n\n#End ExternalSource\nWriteLiteralTo(__razor_helper_writer, \"    \")\n\nWriteLiteralTo(__razor_helper_writer, \"<strong>\")\n\n\n#ExternalSource(\"Helpers.vbhtml\", 3)\nWriteTo(__razor_helper_writer, s)\n\n\n#End ExternalSource\nWriteLiteralTo(__razor_helper_writer, \"</strong>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Helpers.vbhtml\", 4)\n\n\n#End ExternalSource\nEnd Sub)\nEnd Function\n\n#ExternalSource(\"Helpers.vbhtml\", 6)\nPublic Shared Function Italic(s as String) As Template\n\n#End ExternalSource\nReturn New Template(Sub (__razor_helper_writer)\n\n#ExternalSource(\"Helpers.vbhtml\", 6)\n                           \n    s = s.ToUpper()\n\n\n#End ExternalSource\nWriteLiteralTo(__razor_helper_writer, \"    \")\n\nWriteLiteralTo(__razor_helper_writer, \"<em>\")\n\n\n#ExternalSource(\"Helpers.vbhtml\", 8)\nWriteTo(__razor_helper_writer, s)\n\n\n#End ExternalSource\nWriteLiteralTo(__razor_helper_writer, \"</em>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Helpers.vbhtml\", 9)\n\n\n#End ExternalSource\nEnd Sub)\nEnd Function\n\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Helpers.vbhtml\",11)\nWrite(Bold(\"Hello\"))\n\n\n#End ExternalSource\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/HelpersMissingCloseParen.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class HelpersMissingCloseParen\n\n#ExternalSource(\"HelpersMissingCloseParen.vbhtml\", 1)\nPublic Shared Function Bold(s as String) As Template\n\n#End ExternalSource\nReturn New Template(Sub (__razor_helper_writer)\n\n#ExternalSource(\"HelpersMissingCloseParen.vbhtml\", 1)\n                         \n    s = s.ToUpper()\n\n\n#End ExternalSource\nWriteLiteralTo(__razor_helper_writer, \"    \")\n\nWriteLiteralTo(__razor_helper_writer, \"<strong>\")\n\n\n#ExternalSource(\"HelpersMissingCloseParen.vbhtml\", 3)\nWriteTo(__razor_helper_writer, s)\n\n\n#End ExternalSource\nWriteLiteralTo(__razor_helper_writer, \"</strong>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"HelpersMissingCloseParen.vbhtml\", 4)\n\n\n#End ExternalSource\nEnd Sub)\nEnd Function\n\n#ExternalSource(\"HelpersMissingCloseParen.vbhtml\", 6)\nPublic Shared Function Italic(s as String\n\n@Bold(\"Hello\")\n#End ExternalSource\nEnd Function\n\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/HelpersMissingName.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class HelpersMissingName\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/HelpersMissingOpenParen.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class HelpersMissingOpenParen\n\n#ExternalSource(\"HelpersMissingOpenParen.vbhtml\", 1)\nPublic Shared Function Bold(s as String) As Template\n\n#End ExternalSource\nReturn New Template(Sub (__razor_helper_writer)\n\n#ExternalSource(\"HelpersMissingOpenParen.vbhtml\", 1)\n                         \n    s = s.ToUpper()\n\n\n#End ExternalSource\nWriteLiteralTo(__razor_helper_writer, \"    \")\n\nWriteLiteralTo(__razor_helper_writer, \"<strong>\")\n\n\n#ExternalSource(\"HelpersMissingOpenParen.vbhtml\", 3)\nWriteTo(__razor_helper_writer, s)\n\n\n#End ExternalSource\nWriteLiteralTo(__razor_helper_writer, \"</strong>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"HelpersMissingOpenParen.vbhtml\", 4)\n\n\n#End ExternalSource\nEnd Sub)\nEnd Function\n\n#ExternalSource(\"HelpersMissingOpenParen.vbhtml\", 6)\nPublic Shared Function Italic\n#End ExternalSource\nEnd Function\n\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"HelpersMissingOpenParen.vbhtml\",8)\nWrite(Bold(\"Hello\"))\n\n\n#End ExternalSource\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/ImplicitExpression.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class ImplicitExpression\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\n\n#ExternalSource(\"ImplicitExpression.vbhtml\",1)\n For i = 1 To 10\n\n\n#End ExternalSource\nWriteLiteral(\"    \")\n\nWriteLiteral(\"<p>This is item #\")\n\n\n#ExternalSource(\"ImplicitExpression.vbhtml\",2)\n                 Write(i)\n\n\n#End ExternalSource\nWriteLiteral(\"</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"ImplicitExpression.vbhtml\",3)\nNext\n\n\n#End ExternalSource\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"ImplicitExpression.vbhtml\",5)\nWrite(SyntaxSampleHelpers.CodeForLink(Me))\n\n\n#End ExternalSource\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/ImplicitExpressionAtEOF.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class ImplicitExpressionAtEOF\nPrivate Shared __o As Object\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\n\n#ExternalSource(\"ImplicitExpressionAtEOF.vbhtml\",1)\n__o = \n\n\n#End ExternalSource\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/Imports.DesignTime.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports Foo = System.Text.Encoding\n\nImports System\nImports System.IO\n\n\nNamespace TestOutput\nPublic Class [Imports]\nPrivate Shared __o As Object\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\n\n#ExternalSource(\"Imports.vbhtml\",4)\n                       __o = GetType(Path).FullName\n\n\n#End ExternalSource\n\n#ExternalSource(\"Imports.vbhtml\",5)\n                             __o = GetType(Foo).FullName\n\n\n#End ExternalSource\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/Imports.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports Foo = System.Text.Encoding\n\nImports System\nImports System.IO\n\n\nNamespace TestOutput\nPublic Class [Imports]\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"<p>Path's full type name is \")\n\n\n#ExternalSource(\"Imports.vbhtml\",5)\n                       Write(GetType(Path).FullName)\n\n\n#End ExternalSource\nWriteLiteral(\"</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"<p>Foo's actual full type name is \")\n\n\n#ExternalSource(\"Imports.vbhtml\",6)\n                             Write(GetType(Foo).FullName)\n\n\n#End ExternalSource\nWriteLiteral(\"</p>\")\n\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/Inherits.Designtime.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class [Inherits]\nInherits System.Web.WebPages.WebPage\nPublic Sub New()\nMyBase.New\nEnd Sub\nPrivate Sub __RazorDesignTimeHelpers__()\n\n\n#ExternalSource(\"Inherits.vbhtml\",1)\nDim __inheritsHelper As System.Web.WebPages.WebPage = Nothing\n\n\n#End ExternalSource\n\nEnd Sub\nPublic Overrides Sub Execute()\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/Inherits.Runtime.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class [Inherits]\nInherits System.Web.WebPages.WebPage\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/Instrumented.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class Instrumented\n\n#ExternalSource(\"Instrumented.vbhtml\", 1)\nPublic Shared Function Strong(s As String) As Template\n\n#End ExternalSource\nReturn New Template(Sub (__razor_helper_writer)\n\n#ExternalSource(\"Instrumented.vbhtml\", 1)\n                           \n\n\n#End ExternalSource\nBeginContext(__razor_helper_writer, \"~/Instrumented.vbhtml\", 29, 4, true)\n\nWriteLiteralTo(__razor_helper_writer, \"    \")\n\nEndContext(__razor_helper_writer, \"~/Instrumented.vbhtml\", 29, 4, true)\n\nBeginContext(__razor_helper_writer, \"~/Instrumented.vbhtml\", 34, 8, true)\n\nWriteLiteralTo(__razor_helper_writer, \"<strong>\")\n\nEndContext(__razor_helper_writer, \"~/Instrumented.vbhtml\", 34, 8, true)\n\nBeginContext(__razor_helper_writer, \"~/Instrumented.vbhtml\", 43, 1, false)\n\n\n#ExternalSource(\"Instrumented.vbhtml\", 2)\nWriteTo(__razor_helper_writer, s)\n\n\n#End ExternalSource\nEndContext(__razor_helper_writer, \"~/Instrumented.vbhtml\", 43, 1, false)\n\nBeginContext(__razor_helper_writer, \"~/Instrumented.vbhtml\", 44, 11, true)\n\nWriteLiteralTo(__razor_helper_writer, \"</strong>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEndContext(__razor_helper_writer, \"~/Instrumented.vbhtml\", 44, 11, true)\n\n\n#ExternalSource(\"Instrumented.vbhtml\", 3)\n\n\n#End ExternalSource\nEnd Sub)\nEnd Function\n\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\nBeginContext(\"~/Instrumented.vbhtml\", 65, 4, true)\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEndContext(\"~/Instrumented.vbhtml\", 65, 4, true)\n\n\n#ExternalSource(\"Instrumented.vbhtml\",5)\n     \n    Dim i As Integer = 1\n    Dim foo = \n\n#End ExternalSource\nFunction (item) New Template(Sub (__razor_template_writer)\n\nBeginContext(__razor_template_writer, \"~/Instrumented.vbhtml\", 118, 12, true)\n\nWriteLiteralTo(__razor_template_writer, \"<p>Foo</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEndContext(__razor_template_writer, \"~/Instrumented.vbhtml\", 118, 12, true)\n\nBeginContext(\"~/Instrumented.vbhtml\", 130, 4, true)\n\nWriteLiteral(\"    \")\n\nEndContext(\"~/Instrumented.vbhtml\", 130, 4, true)\n\nBeginContext(\"~/Instrumented.vbhtml\", 136, 15, true)\n\nWriteLiteral(\"Hello, World!\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEndContext(\"~/Instrumented.vbhtml\", 136, 15, true)\n\nBeginContext(\"~/Instrumented.vbhtml\", 151, 4, true)\n\nWriteLiteral(\"    \")\n\nEndContext(\"~/Instrumented.vbhtml\", 151, 4, true)\n\nBeginContext(\"~/Instrumented.vbhtml\", 156, 22, true)\n\nWriteLiteral(\"<p>Hello, World!</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEndContext(\"~/Instrumented.vbhtml\", 156, 22, true)\n\nEnd Sub)\n\n#ExternalSource(\"Instrumented.vbhtml\",10)\n\n\n#End ExternalSource\nBeginContext(\"~/Instrumented.vbhtml\", 186, 4, true)\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEndContext(\"~/Instrumented.vbhtml\", 186, 4, true)\n\n\n#ExternalSource(\"Instrumented.vbhtml\",12)\n While i <= 10\n\n\n#End ExternalSource\nBeginContext(\"~/Instrumented.vbhtml\", 206, 4, true)\n\nWriteLiteral(\"    \")\n\nEndContext(\"~/Instrumented.vbhtml\", 206, 4, true)\n\nBeginContext(\"~/Instrumented.vbhtml\", 211, 23, true)\n\nWriteLiteral(\"<p>Hello from VB.Net, #\")\n\nEndContext(\"~/Instrumented.vbhtml\", 211, 23, true)\n\nBeginContext(\"~/Instrumented.vbhtml\", 236, 1, false)\n\n\n#ExternalSource(\"Instrumented.vbhtml\",13)\n                        Write(i)\n\n\n#End ExternalSource\nEndContext(\"~/Instrumented.vbhtml\", 236, 1, false)\n\nBeginContext(\"~/Instrumented.vbhtml\", 238, 6, true)\n\nWriteLiteral(\"</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEndContext(\"~/Instrumented.vbhtml\", 238, 6, true)\n\n\n#ExternalSource(\"Instrumented.vbhtml\",14)\n    i += 1\nEnd While\n\n\n#End ExternalSource\nBeginContext(\"~/Instrumented.vbhtml\", 267, 2, true)\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEndContext(\"~/Instrumented.vbhtml\", 267, 2, true)\n\n\n#ExternalSource(\"Instrumented.vbhtml\",17)\n If i = 11 Then\n\n\n#End ExternalSource\nBeginContext(\"~/Instrumented.vbhtml\", 286, 4, true)\n\nWriteLiteral(\"    \")\n\nEndContext(\"~/Instrumented.vbhtml\", 286, 4, true)\n\nBeginContext(\"~/Instrumented.vbhtml\", 291, 27, true)\n\nWriteLiteral(\"<p>We wrote 10 lines!</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEndContext(\"~/Instrumented.vbhtml\", 291, 27, true)\n\n\n#ExternalSource(\"Instrumented.vbhtml\",19)\nEnd If\n\n\n#End ExternalSource\nBeginContext(\"~/Instrumented.vbhtml\", 326, 2, true)\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEndContext(\"~/Instrumented.vbhtml\", 326, 2, true)\n\n\n#ExternalSource(\"Instrumented.vbhtml\",21)\n Do\n\n\n#End ExternalSource\nBeginContext(\"~/Instrumented.vbhtml\", 333, 4, true)\n\nWriteLiteral(\"    \")\n\nEndContext(\"~/Instrumented.vbhtml\", 333, 4, true)\n\nBeginContext(\"~/Instrumented.vbhtml\", 338, 16, true)\n\nWriteLiteral(\"<p>Hello again: \")\n\nEndContext(\"~/Instrumented.vbhtml\", 338, 16, true)\n\nBeginContext(\"~/Instrumented.vbhtml\", 355, 1, false)\n\n\n#ExternalSource(\"Instrumented.vbhtml\",22)\n                Write(i)\n\n\n#End ExternalSource\nEndContext(\"~/Instrumented.vbhtml\", 355, 1, false)\n\nBeginContext(\"~/Instrumented.vbhtml\", 356, 6, true)\n\nWriteLiteral(\"</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEndContext(\"~/Instrumented.vbhtml\", 356, 6, true)\n\n\n#ExternalSource(\"Instrumented.vbhtml\",23)\n    i -= 1\nLoop While i > 0\n\n\n#End ExternalSource\nBeginContext(\"~/Instrumented.vbhtml\", 392, 2, true)\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEndContext(\"~/Instrumented.vbhtml\", 392, 2, true)\n\n\n#ExternalSource(\"Instrumented.vbhtml\",26)\n Select Case i\n    Case 11\n\n\n#End ExternalSource\nBeginContext(\"~/Instrumented.vbhtml\", 423, 8, true)\n\nWriteLiteral(\"        \")\n\nEndContext(\"~/Instrumented.vbhtml\", 423, 8, true)\n\nBeginContext(\"~/Instrumented.vbhtml\", 432, 38, true)\n\nWriteLiteral(\"<p>No really, we wrote 10 lines!</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEndContext(\"~/Instrumented.vbhtml\", 432, 38, true)\n\n\n#ExternalSource(\"Instrumented.vbhtml\",29)\n    Case Else\n\n\n#End ExternalSource\nBeginContext(\"~/Instrumented.vbhtml\", 485, 8, true)\n\nWriteLiteral(\"        \")\n\nEndContext(\"~/Instrumented.vbhtml\", 485, 8, true)\n\nBeginContext(\"~/Instrumented.vbhtml\", 494, 41, true)\n\nWriteLiteral(\"<p>We wrote a bunch more lines too!</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEndContext(\"~/Instrumented.vbhtml\", 494, 41, true)\n\n\n#ExternalSource(\"Instrumented.vbhtml\",31)\nEnd Select\n\n\n#End ExternalSource\nBeginContext(\"~/Instrumented.vbhtml\", 547, 2, true)\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEndContext(\"~/Instrumented.vbhtml\", 547, 2, true)\n\n\n#ExternalSource(\"Instrumented.vbhtml\",33)\n For j as Integer = 1 to 10 Step 2\n\n\n#End ExternalSource\nBeginContext(\"~/Instrumented.vbhtml\", 585, 4, true)\n\nWriteLiteral(\"    \")\n\nEndContext(\"~/Instrumented.vbhtml\", 585, 4, true)\n\nBeginContext(\"~/Instrumented.vbhtml\", 590, 29, true)\n\nWriteLiteral(\"<p>Hello again from VB.Net, #\")\n\nEndContext(\"~/Instrumented.vbhtml\", 590, 29, true)\n\nBeginContext(\"~/Instrumented.vbhtml\", 621, 1, false)\n\n\n#ExternalSource(\"Instrumented.vbhtml\",34)\n                              Write(j)\n\n\n#End ExternalSource\nEndContext(\"~/Instrumented.vbhtml\", 621, 1, false)\n\nBeginContext(\"~/Instrumented.vbhtml\", 623, 6, true)\n\nWriteLiteral(\"</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEndContext(\"~/Instrumented.vbhtml\", 623, 6, true)\n\n\n#ExternalSource(\"Instrumented.vbhtml\",35)\nNext j\n\n\n#End ExternalSource\nBeginContext(\"~/Instrumented.vbhtml\", 637, 2, true)\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEndContext(\"~/Instrumented.vbhtml\", 637, 2, true)\n\n\n#ExternalSource(\"Instrumented.vbhtml\",37)\n Try\n\n\n#End ExternalSource\nBeginContext(\"~/Instrumented.vbhtml\", 645, 4, true)\n\nWriteLiteral(\"    \")\n\nEndContext(\"~/Instrumented.vbhtml\", 645, 4, true)\n\nBeginContext(\"~/Instrumented.vbhtml\", 650, 37, true)\n\nWriteLiteral(\"<p>That time, we wrote 5 lines!</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEndContext(\"~/Instrumented.vbhtml\", 650, 37, true)\n\n\n#ExternalSource(\"Instrumented.vbhtml\",39)\nCatch ex as Exception\n\n\n#End ExternalSource\nBeginContext(\"~/Instrumented.vbhtml\", 710, 4, true)\n\nWriteLiteral(\"    \")\n\nEndContext(\"~/Instrumented.vbhtml\", 710, 4, true)\n\nBeginContext(\"~/Instrumented.vbhtml\", 715, 29, true)\n\nWriteLiteral(\"<p>Oh no! An error occurred: \")\n\nEndContext(\"~/Instrumented.vbhtml\", 715, 29, true)\n\nBeginContext(\"~/Instrumented.vbhtml\", 746, 10, false)\n\n\n#ExternalSource(\"Instrumented.vbhtml\",40)\n                              Write(ex.Message)\n\n\n#End ExternalSource\nEndContext(\"~/Instrumented.vbhtml\", 746, 10, false)\n\nBeginContext(\"~/Instrumented.vbhtml\", 757, 6, true)\n\nWriteLiteral(\"</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEndContext(\"~/Instrumented.vbhtml\", 757, 6, true)\n\n\n#ExternalSource(\"Instrumented.vbhtml\",41)\nEnd Try\n\n\n#End ExternalSource\nBeginContext(\"~/Instrumented.vbhtml\", 772, 2, true)\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEndContext(\"~/Instrumented.vbhtml\", 772, 2, true)\n\n\n#ExternalSource(\"Instrumented.vbhtml\",43)\n With i\n\n\n#End ExternalSource\nBeginContext(\"~/Instrumented.vbhtml\", 783, 4, true)\n\nWriteLiteral(\"    \")\n\nEndContext(\"~/Instrumented.vbhtml\", 783, 4, true)\n\nBeginContext(\"~/Instrumented.vbhtml\", 788, 12, true)\n\nWriteLiteral(\"<p>i is now \")\n\nEndContext(\"~/Instrumented.vbhtml\", 788, 12, true)\n\nBeginContext(\"~/Instrumented.vbhtml\", 802, 11, false)\n\n\n#ExternalSource(\"Instrumented.vbhtml\",44)\n             Write(.ToString())\n\n\n#End ExternalSource\nEndContext(\"~/Instrumented.vbhtml\", 802, 11, false)\n\nBeginContext(\"~/Instrumented.vbhtml\", 814, 6, true)\n\nWriteLiteral(\"</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEndContext(\"~/Instrumented.vbhtml\", 814, 6, true)\n\n\n#ExternalSource(\"Instrumented.vbhtml\",45)\nEnd With\n\n\n#End ExternalSource\nBeginContext(\"~/Instrumented.vbhtml\", 830, 2, true)\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEndContext(\"~/Instrumented.vbhtml\", 830, 2, true)\n\n\n#ExternalSource(\"Instrumented.vbhtml\",47)\n SyncLock New Object()\n\n\n#End ExternalSource\nBeginContext(\"~/Instrumented.vbhtml\", 856, 4, true)\n\nWriteLiteral(\"    \")\n\nEndContext(\"~/Instrumented.vbhtml\", 856, 4, true)\n\nBeginContext(\"~/Instrumented.vbhtml\", 861, 49, true)\n\nWriteLiteral(\"<p>This block is locked, for your security!</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEndContext(\"~/Instrumented.vbhtml\", 861, 49, true)\n\n\n#ExternalSource(\"Instrumented.vbhtml\",49)\nEnd SyncLock\n\n\n#End ExternalSource\nBeginContext(\"~/Instrumented.vbhtml\", 924, 2, true)\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEndContext(\"~/Instrumented.vbhtml\", 924, 2, true)\n\n\n#ExternalSource(\"Instrumented.vbhtml\",51)\n Using New System.IO.MemoryStream()\n\n\n#End ExternalSource\nBeginContext(\"~/Instrumented.vbhtml\", 963, 4, true)\n\nWriteLiteral(\"    \")\n\nEndContext(\"~/Instrumented.vbhtml\", 963, 4, true)\n\nBeginContext(\"~/Instrumented.vbhtml\", 968, 78, true)\n\nWriteLiteral(\"<p>Some random memory stream will be disposed after rendering this block</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEndContext(\"~/Instrumented.vbhtml\", 968, 78, true)\n\n\n#ExternalSource(\"Instrumented.vbhtml\",53)\nEnd Using\n\n#End ExternalSource\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/LayoutDirective.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class LayoutDirective\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\nLayout = \"~/Foo/Bar/Baz\"\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/MarkupInCodeBlock.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class MarkupInCodeBlock\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\n\n#ExternalSource(\"MarkupInCodeBlock.vbhtml\",1)\n     \n    For i = 1 To 10\n\n\n#End ExternalSource\nWriteLiteral(\"        \")\n\nWriteLiteral(\"<p>Hello from VB.Net, #\")\n\n\n#ExternalSource(\"MarkupInCodeBlock.vbhtml\",3)\n                            Write(i.ToString())\n\n\n#End ExternalSource\nWriteLiteral(\"</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"MarkupInCodeBlock.vbhtml\",4)\n    Next i\n\n\n#End ExternalSource\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/NestedCodeBlocks.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class NestedCodeBlocks\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\n\n#ExternalSource(\"NestedCodeBlocks.vbhtml\",1)\n If True Then\n    \n\n#End ExternalSource\n\n#ExternalSource(\"NestedCodeBlocks.vbhtml\",2)\n     If True Then\n    End If\n\n\n#End ExternalSource\n\n#ExternalSource(\"NestedCodeBlocks.vbhtml\",4)\nEnd If\n\n#End ExternalSource\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/NestedHelpers.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class NestedHelpers\n\n#ExternalSource(\"NestedHelpers.vbhtml\", 3)\nPublic Shared Function Bold(s As String) As Template\n\n#End ExternalSource\nReturn New Template(Sub (__razor_helper_writer)\n\n#ExternalSource(\"NestedHelpers.vbhtml\", 3)\n                             \n        s = s.ToUpper()\n\n\n#End ExternalSource\nWriteLiteralTo(__razor_helper_writer, \"        \")\n\nWriteLiteralTo(__razor_helper_writer, \"<strong>\")\n\n\n#ExternalSource(\"NestedHelpers.vbhtml\", 5)\nWriteTo(__razor_helper_writer, s)\n\n\n#End ExternalSource\nWriteLiteralTo(__razor_helper_writer, \"</strong>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"NestedHelpers.vbhtml\", 6)\n    \n\n#End ExternalSource\nEnd Sub)\nEnd Function\n\n#ExternalSource(\"NestedHelpers.vbhtml\", 1)\nPublic Shared Function Italic(s As String) As Template\n\n#End ExternalSource\nReturn New Template(Sub (__razor_helper_writer)\n\n#ExternalSource(\"NestedHelpers.vbhtml\", 1)\n                           \n    s = s.ToUpper()\n    \n\n#End ExternalSource\n\n#ExternalSource(\"NestedHelpers.vbhtml\", 6)\n              \n\n\n#End ExternalSource\nWriteLiteralTo(__razor_helper_writer, \"    \")\n\nWriteLiteralTo(__razor_helper_writer, \"<em>\")\n\n\n#ExternalSource(\"NestedHelpers.vbhtml\", 7)\nWriteTo(__razor_helper_writer, Bold(s))\n\n\n#End ExternalSource\nWriteLiteralTo(__razor_helper_writer, \"</em>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"NestedHelpers.vbhtml\", 8)\n\n\n#End ExternalSource\nEnd Sub)\nEnd Function\n\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"NestedHelpers.vbhtml\",10)\nWrite(Italic(\"Hello\"))\n\n\n#End ExternalSource\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/NoLinePragmas.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class NoLinePragmas\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\n     \n    Dim i as Integer = 1\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n While i <= 10\n\nWriteLiteral(\"    \")\n\nWriteLiteral(\"<p>Hello from VB.Net, #\")\n\n                        Write(i)\n\nWriteLiteral(\"</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n    i += 1\n    'End While\nEnd While\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n If i = 11 Then\n\nWriteLiteral(\"    \")\n\nWriteLiteral(\"<p>We wrote 10 lines!</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n    Dim s = \"End If\"\nEnd If\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n Select Case i\n    Case 11\n\nWriteLiteral(\"        \")\n\nWriteLiteral(\"<p>No really, we wrote 10 lines!</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n    Case Else\n\nWriteLiteral(\"        \")\n\nWriteLiteral(\"<p>Actually, we didn't...</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEnd Select\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n For j as Integer = 1 to 10 Step 2\n\nWriteLiteral(\"    \")\n\nWriteLiteral(\"<p>Hello again from VB.Net, #\")\n\n                              Write(j)\n\nWriteLiteral(\"</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nNext\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n Try\n\nWriteLiteral(\"    \")\n\nWriteLiteral(\"<p>That time, we wrote 5 lines!</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nCatch ex as Exception\n\nWriteLiteral(\"    \")\n\nWriteLiteral(\"<p>Oh no! An error occurred: \")\n\n                              Write(ex.Message)\n\nWriteLiteral(\"</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEnd Try\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n With i\n\nWriteLiteral(\"    \")\n\nWriteLiteral(\"<p>i is now \")\n\n             Write(.ToString())\n\nWriteLiteral(\"</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEnd With\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n SyncLock New Object()\n\nWriteLiteral(\"    \")\n\nWriteLiteral(\"<p>This block is locked, for your security!</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEnd SyncLock\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n Using New System.IO.MemoryStream()\n\nWriteLiteral(\"    \")\n\nWriteLiteral(\"<p>Some random memory stream will be disposed after rendering this block</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEnd Using\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nWrite(SyntaxSampleHelpers.CodeForLink(Me))\n\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/Options.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict On\nOption Explicit Off\n\nImports System\n\nNamespace TestOutput\nPublic Class Options\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"Hello, World!\")\n\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/ParserError.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class ParserError\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\n\n#ExternalSource(\"ParserError.vbhtml\",1)\n     \nFoo\n'End Code\n\n#End ExternalSource\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/RazorComments.DesignTime.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class RazorComments\nPrivate Shared __o As Object\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\n\n#ExternalSource(\"RazorComments.vbhtml\",1)\n     \n    \n\n#End ExternalSource\n\n#ExternalSource(\"RazorComments.vbhtml\",2)\n                                      \n\n\n#End ExternalSource\n\n#ExternalSource(\"RazorComments.vbhtml\",3)\n      Dim bar As String = \"@* bar *@\" \n\n#End ExternalSource\n\n#ExternalSource(\"RazorComments.vbhtml\",4)\n                                       __o = bar\n\n\n#End ExternalSource\n\n#ExternalSource(\"RazorComments.vbhtml\",5)\n__o = a _\n\n#End ExternalSource\n\n#ExternalSource(\"RazorComments.vbhtml\",6)\n       b\n\n\n#End ExternalSource\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/RazorComments.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class RazorComments\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"<p>This should \")\n\nWriteLiteral(\" be shown</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"RazorComments.vbhtml\",4)\n     \n    \n\n#End ExternalSource\n\n#ExternalSource(\"RazorComments.vbhtml\",5)\n                                       \n\n\n#End ExternalSource\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"RazorComments.vbhtml\",8)\n      Dim bar As String = \"@* bar *@\" \n\n#End ExternalSource\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"<p>But this should show the comment syntax: \")\n\n\n#ExternalSource(\"RazorComments.vbhtml\",9)\n                                       Write(bar)\n\n\n#End ExternalSource\nWriteLiteral(\"</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"<p>So should this: \")\n\nWriteLiteral(\"@* bar *\")\n\nWriteLiteral(\"@</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"RazorComments.vbhtml\",12)\nWrite(a _\n\n#End ExternalSource\n\n#ExternalSource(\"RazorComments.vbhtml\",12)\n       b)\n\n\n#End ExternalSource\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/ResolveUrl.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class ResolveUrl\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\nWriteLiteral(\"<a\")\n\nWriteAttribute(\"href\", Tuple.Create(\" href=\"\"\", 2), Tuple.Create(\"\"\"\", 14) _\n, Tuple.Create(Tuple.Create(\"\", 9), Tuple.Create(Of System.Object, System.Int32)(Href(\"~/Foo\") _\n, 9), False) _\n)\n\nWriteLiteral(\">Foo</a>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"<a\")\n\nWriteAttribute(\"href\", Tuple.Create(\" href=\"\"\", 27), Tuple.Create(\"\"\"\", 56) _\n, Tuple.Create(Tuple.Create(\"\", 34), Tuple.Create(Of System.Object, System.Int32)(Href(\"~/Products/\") _\n, 34), False) _\n, Tuple.Create(Tuple.Create(\"\", 45), Tuple.Create(Of System.Object, System.Int32)(product.id _\n, 45), False) _\n)\n\nWriteLiteral(\">\")\n\n\n#ExternalSource(\"ResolveUrl.vbhtml\",2)\n                            Write(product.Name)\n\n\n#End ExternalSource\nWriteLiteral(\"</a>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"<a\")\n\nWriteAttribute(\"href\", Tuple.Create(\" href=\"\"\", 79), Tuple.Create(\"\"\"\", 115) _\n, Tuple.Create(Tuple.Create(\"\", 86), Tuple.Create(Of System.Object, System.Int32)(Href(\"~/Products/\") _\n, 86), False) _\n, Tuple.Create(Tuple.Create(\"\", 97), Tuple.Create(Of System.Object, System.Int32)(product.id _\n, 97), False) _\n, Tuple.Create(Tuple.Create(\"\", 108), Tuple.Create(\"/Detail\", 108), True) _\n)\n\nWriteLiteral(\">Details</a>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"<a\")\n\nWriteAttribute(\"href\", Tuple.Create(\" href=\"\"\", 132), Tuple.Create(\"\"\"\", 187) _\n, Tuple.Create(Tuple.Create(\"\", 139), Tuple.Create(Of System.Object, System.Int32)(Href(\"~/A+Really(Crazy),Url.Is:This/\") _\n, 139), False) _\n, Tuple.Create(Tuple.Create(\"\", 169), Tuple.Create(Of System.Object, System.Int32)(product.id _\n, 169), False) _\n, Tuple.Create(Tuple.Create(\"\", 180), Tuple.Create(\"/Detail\", 180), True) _\n)\n\nWriteLiteral(\">Crazy Url!</a>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"ResolveUrl.vbhtml\",6)\n     \n\n\n#End ExternalSource\nWriteLiteral(\"    \")\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"        <a\")\n\nWriteAttribute(\"href\", Tuple.Create(\" href=\"\"\", 237), Tuple.Create(\"\"\"\", 249) _\n, Tuple.Create(Tuple.Create(\"\", 244), Tuple.Create(Of System.Object, System.Int32)(Href(\"~/Foo\") _\n, 244), False) _\n)\n\nWriteLiteral(\">Foo</a>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"        <a\")\n\nWriteAttribute(\"href\", Tuple.Create(\" href=\"\"\", 270), Tuple.Create(\"\"\"\", 299) _\n, Tuple.Create(Tuple.Create(\"\", 277), Tuple.Create(Of System.Object, System.Int32)(Href(\"~/Products/\") _\n, 277), False) _\n, Tuple.Create(Tuple.Create(\"\", 288), Tuple.Create(Of System.Object, System.Int32)(product.id _\n, 288), False) _\n)\n\nWriteLiteral(\">\")\n\n\n#ExternalSource(\"ResolveUrl.vbhtml\",9)\n                                    Write(product.Name)\n\n\n#End ExternalSource\nWriteLiteral(\"</a>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"        <a\")\n\nWriteAttribute(\"href\", Tuple.Create(\" href=\"\"\", 330), Tuple.Create(\"\"\"\", 366) _\n, Tuple.Create(Tuple.Create(\"\", 337), Tuple.Create(Of System.Object, System.Int32)(Href(\"~/Products/\") _\n, 337), False) _\n, Tuple.Create(Tuple.Create(\"\", 348), Tuple.Create(Of System.Object, System.Int32)(product.id _\n, 348), False) _\n, Tuple.Create(Tuple.Create(\"\", 359), Tuple.Create(\"/Detail\", 359), True) _\n)\n\nWriteLiteral(\">Details</a>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"        <a\")\n\nWriteAttribute(\"href\", Tuple.Create(\" href=\"\"\", 391), Tuple.Create(\"\"\"\", 446) _\n, Tuple.Create(Tuple.Create(\"\", 398), Tuple.Create(Of System.Object, System.Int32)(Href(\"~/A+Really(Crazy),Url.Is:This/\") _\n, 398), False) _\n, Tuple.Create(Tuple.Create(\"\", 428), Tuple.Create(Of System.Object, System.Int32)(product.id _\n, 428), False) _\n, Tuple.Create(Tuple.Create(\"\", 439), Tuple.Create(\"/Detail\", 439), True) _\n)\n\nWriteLiteral(\">Crazy Url!</a>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"    \")\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"ResolveUrl.vbhtml\",13)\n\n\n#End ExternalSource\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nDefineSection(\"Foo\", Sub ()\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"    <a\")\n\nWriteAttribute(\"href\", Tuple.Create(\" href=\"\"\", 509), Tuple.Create(\"\"\"\", 521) _\n, Tuple.Create(Tuple.Create(\"\", 516), Tuple.Create(Of System.Object, System.Int32)(Href(\"~/Foo\") _\n, 516), False) _\n)\n\nWriteLiteral(\">Foo</a>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"    <a\")\n\nWriteAttribute(\"href\", Tuple.Create(\" href=\"\"\", 538), Tuple.Create(\"\"\"\", 567) _\n, Tuple.Create(Tuple.Create(\"\", 545), Tuple.Create(Of System.Object, System.Int32)(Href(\"~/Products/\") _\n, 545), False) _\n, Tuple.Create(Tuple.Create(\"\", 556), Tuple.Create(Of System.Object, System.Int32)(product.id _\n, 556), False) _\n)\n\nWriteLiteral(\">\")\n\n\n#ExternalSource(\"ResolveUrl.vbhtml\",17)\n                                Write(product.Name)\n\n\n#End ExternalSource\nWriteLiteral(\"</a>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"    <a\")\n\nWriteAttribute(\"href\", Tuple.Create(\" href=\"\"\", 594), Tuple.Create(\"\"\"\", 630) _\n, Tuple.Create(Tuple.Create(\"\", 601), Tuple.Create(Of System.Object, System.Int32)(Href(\"~/Products/\") _\n, 601), False) _\n, Tuple.Create(Tuple.Create(\"\", 612), Tuple.Create(Of System.Object, System.Int32)(product.id _\n, 612), False) _\n, Tuple.Create(Tuple.Create(\"\", 623), Tuple.Create(\"/Detail\", 623), True) _\n)\n\nWriteLiteral(\">Details</a>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"    <a\")\n\nWriteAttribute(\"href\", Tuple.Create(\" href=\"\"\", 651), Tuple.Create(\"\"\"\", 706) _\n, Tuple.Create(Tuple.Create(\"\", 658), Tuple.Create(Of System.Object, System.Int32)(Href(\"~/A+Really(Crazy),Url.Is:This/\") _\n, 658), False) _\n, Tuple.Create(Tuple.Create(\"\", 688), Tuple.Create(Of System.Object, System.Int32)(product.id _\n, 688), False) _\n, Tuple.Create(Tuple.Create(\"\", 699), Tuple.Create(\"/Detail\", 699), True) _\n)\n\nWriteLiteral(\">Crazy Url!</a>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEnd Sub)\n\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/Sections.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class Sections\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\n\n#ExternalSource(\"Sections.vbhtml\",1)\n     \n    Layout = \"_SectionTestLayout.vbhtml\"\n\n\n#End ExternalSource\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"<div>This is in the Body>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nDefineSection(\"Section2\", Sub ()\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"    <div>This is in Section 2</div>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEnd Sub)\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nDefineSection(\"Section1\", Sub ()\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"    <div>This is in Section 1</div>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nEnd Sub)\n\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/Templates.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\nImports System.Web.Helpers\n\n\nNamespace TestOutput\nPublic Class Templates\n\n#ExternalSource(\"Templates.vbhtml\",3)\n          \n    Public Function Repeat(times As Integer, template As Func(Of Integer, object)) As HelperResult\n        Return New HelperResult(Sub(writer)\n            For i = 0 to times\n                DirectCast(template(i), HelperResult).WriteTo(writer)\n            Next i\n        End Sub)\n    End Function\n\n#End ExternalSource\n\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Templates.vbhtml\",13)\n     \n    Dim foo As Func(Of Object, Object) =\n\n#End ExternalSource\nWriteLiteral(\" \")\n\nWriteLiteral(\"This works \")\n\n\n#ExternalSource(\"Templates.vbhtml\",14)\n                                                      Write(item)\n\n\n#End ExternalSource\nWriteLiteral(\"!\")\n\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Templates.vbhtml\",15)\n    \n\n#End ExternalSource\n\n#ExternalSource(\"Templates.vbhtml\",15)\nWrite(foo(\"too\"))\n\n\n#End ExternalSource\n\n#ExternalSource(\"Templates.vbhtml\",15)\n               \n\n\n#End ExternalSource\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"<ul>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Templates.vbhtml\",19)\nWrite(Repeat(10, Function (item) New Template(Sub (__razor_template_writer)\n\n\n#End ExternalSource\nWriteLiteralTo(__razor_template_writer, \"<li>Item #\")\n\n\n#ExternalSource(\"Templates.vbhtml\",19)\nWriteTo(__razor_template_writer, item)\n\n\n#End ExternalSource\nWriteLiteralTo(__razor_template_writer, \"</li>\")\n\n\n#ExternalSource(\"Templates.vbhtml\",19)\n                           End Sub)))\n\n\n#End ExternalSource\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"</ul>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"<p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Templates.vbhtml\",23)\nWrite(Repeat(10,\n    Function (item) New Template(Sub (__razor_template_writer)\n\n\n#End ExternalSource\nWriteLiteralTo(__razor_template_writer, \" This is line#\")\n\n\n#ExternalSource(\"Templates.vbhtml\",24)\nWriteTo(__razor_template_writer, item)\n\n\n#End ExternalSource\nWriteLiteralTo(__razor_template_writer, \" of markup<br/>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Templates.vbhtml\",25)\nEnd Sub)))\n\n\n#End ExternalSource\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"</p>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"<ul>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\nWriteLiteral(\"    \")\n\n\n#ExternalSource(\"Templates.vbhtml\",29)\nWrite(Repeat(10, Function (item) New Template(Sub (__razor_template_writer)\n\n\n#End ExternalSource\nWriteLiteralTo(__razor_template_writer, \"<li>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"        Item #\")\n\n\n#ExternalSource(\"Templates.vbhtml\",30)\nWriteTo(__razor_template_writer, item)\n\n\n#End ExternalSource\nWriteLiteralTo(__razor_template_writer, \"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10))\n\n\n#ExternalSource(\"Templates.vbhtml\",31)\n        \n\n#End ExternalSource\n\n#ExternalSource(\"Templates.vbhtml\",31)\n              Dim parent = item \n\n#End ExternalSource\nWriteLiteralTo(__razor_template_writer, \"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"        <ul>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"            <li>Child Items... ?</li>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"        </ul>\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"    </li>\")\n\n\n#ExternalSource(\"Templates.vbhtml\",35)\n End Sub)))\n\n\n#End ExternalSource\nWriteLiteral(\"\"&Global.Microsoft.VisualBasic.ChrW(13)&Global.Microsoft.VisualBasic.ChrW(10)&\"</ul>\")\n\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Output/UnfinishedExpressionInCode.vb",
    "content": "'------------------------------------------------------------------------------\n' <auto-generated>\n'     This code was generated by a tool.\n'     Runtime Version:N.N.NNNNN.N\n'\n'     Changes to this file may cause incorrect behavior and will be lost if\n'     the code is regenerated.\n' </auto-generated>\n'------------------------------------------------------------------------------\n\nOption Strict Off\nOption Explicit On\n\nImports System\n\nNamespace TestOutput\nPublic Class UnfinishedExpressionInCode\nPrivate Shared __o As Object\nPublic Sub New()\nMyBase.New\nEnd Sub\nPublic Overrides Sub Execute()\n\n#ExternalSource(\"UnfinishedExpressionInCode.vbhtml\",1)\n     \n\n\n#End ExternalSource\n\n#ExternalSource(\"UnfinishedExpressionInCode.vbhtml\",2)\n__o = DateTime.\n\n\n#End ExternalSource\n\n#ExternalSource(\"UnfinishedExpressionInCode.vbhtml\",3)\n          \n\n\n#End ExternalSource\nEnd Sub\nEnd Class\nEnd Namespace\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/Blocks.vbhtml",
    "content": "﻿@Code\n    Dim i as Integer = 1\nEnd Code\n\n@While i <= 10\n    @<p>Hello from VB.Net, #@(i)</p>\n    i += 1\nEnd While\n\n@If i = 11 Then\n    @<p>We wrote 10 lines!</p>\nEnd If\n\n@Do\n    @<p>Hello again: @i</p>\n    i -= 1\nLoop While i > 0\n\n@Select Case i\n    Case 11\n        @<p>No really, we wrote 10 lines!</p>\n    Case Else\n        @<p>We wrote a bunch more lines too!</p>\nEnd Select\n\n@For j as Integer = 1 to 10 Step 2\n    @<p>Hello again from VB.Net, #@(j)</p>\nNext j\n\n@Try\n    @<p>That time, we wrote 5 lines!</p>\nCatch ex as Exception\n    @<p>Oh no! An error occurred: @(ex.Message)</p>\nEnd Try\n\n@With i\n    @<p>i is now @(.ToString())</p>\nEnd With\n\n@SyncLock New Object()\n    @<p>This block is locked, for your security!</p>\nEnd SyncLock\n\n@Using New System.IO.MemoryStream()\n    @<p>Some random memory stream will be disposed after rendering this block</p>\nEnd Using"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/CodeBlock.vbhtml",
    "content": "﻿@Code\n    Test()\nEnd Code"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/CodeBlockAtEOF.vbhtml",
    "content": "﻿This is markup\n\n@Code"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/ConditionalAttributes.vbhtml",
    "content": "﻿@Helper Link(ByVal url As String, text As String) \n    @<a href=\"@url\">@text</a> \nEnd Helper \n\n@Code\n    Dim ch = True\n    Dim cls = \"bar\"\n    @<a href=\"Foo\" />\n    @<p class=\"@cls\" />\n    @<p class=\"foo @cls\" />\n    @<p class=\"@cls foo\" />\n    @<input type=\"checkbox\" checked=\"@ch\" />\n    @<input type=\"checkbox\" checked=\"foo @ch\" />\n    @<p class=\"@If cls IsNot Nothing Then @cls End If\" />\n    @<a href=\"~/Foo\" />\nEnd Code"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/DesignTime.vbhtml",
    "content": "﻿<div>\n            @For i = 1 to 10\n@<p>This is item #@i</p>\n            Next\n</div>\n\n<p>\n@(Foo(Bar.Baz))\n@Foo(@@<p>Bar @baz Biz</p>)\n</p>\n\n@Section Footer\n    <p>Foo</p>\n    @bar\nEnd Section\n\n@Helper Foo()\n    If True Then\n        @<p>Foo</p>\n    End If\nEnd Helper"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/EmptyExplicitExpression.vbhtml",
    "content": "﻿This is markup\n\n@()"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/EmptyImplicitExpression.vbhtml",
    "content": "﻿This is markup\n\n@!"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/EmptyImplicitExpressionInCode.vbhtml",
    "content": "﻿@Code\n    @\nEnd Code"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/EmptySection.vbhtml",
    "content": "﻿@section anything End"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/ExplicitExpression.vbhtml",
    "content": "﻿@(Foo(Bar.Baz))"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/ExplicitExpressionAtEOF.vbhtml",
    "content": "﻿This is markup\n\n@("
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/ExpressionsInCode.vbhtml",
    "content": "﻿@Code\n    Dim foo As Object = Nothing\n    Dim bar as String = \"Foo\"\nEnd Code\n\n@If foo IsNot Nothing Then\n    @foo\nElse\n    @<p>Foo is Null!</p>\nEnd If\n\n<p>\n@If Not String.IsNullOrEmpty(bar) Then\n    @(bar.Replace(\"F\", \"B\"))\nEnd If\n</p>"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/FunctionsBlock.vbhtml",
    "content": "﻿@Functions\n\nEnd Functions\n\n@Functions\n    Private _rand as New Random()\n    Private Function RandomInt() as Integer\n        Return _rand.Next()\n    End Function\nEnd Functions\n\nHere's a random number: @RandomInt()"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/Helpers.vbhtml",
    "content": "﻿@Helper Bold(s as String)\n    s = s.ToUpper()\n    @<strong>@s</strong>\nEnd Helper\n\n@Helper Italic(s as String)\n    s = s.ToUpper()\n    @<em>@s</em>\nEnd Helper\n\n@Bold(\"Hello\")"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/HelpersMissingCloseParen.vbhtml",
    "content": "@Helper Bold(s as String)\n    s = s.ToUpper()\n    @<strong>@s</strong>\nEnd Helper\n\n@Helper Italic(s as String\n\n@Bold(\"Hello\")"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/HelpersMissingName.vbhtml",
    "content": "@Helper"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/HelpersMissingOpenParen.vbhtml",
    "content": "@Helper Bold(s as String)\n    s = s.ToUpper()\n    @<strong>@s</strong>\nEnd Helper\n\n@Helper Italic\n\n@Bold(\"Hello\")"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/ImplicitExpression.vbhtml",
    "content": "﻿@For i = 1 To 10\n    @<p>This is item #@i</p>\nNext\n\n@SyntaxSampleHelpers.CodeForLink(Me)"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/ImplicitExpressionAtEOF.vbhtml",
    "content": "﻿This is markup\n\n@"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/Imports.vbhtml",
    "content": "﻿@Imports System.IO\n@Imports Foo = System.Text.Encoding\n@Imports System\n\n<p>Path's full type name is @GetType(Path).FullName</p>\n<p>Foo's actual full type name is @GetType(Foo).FullName</p>"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/Inherits.vbhtml",
    "content": "﻿@Inherits System.Web.WebPages.WebPage\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/Instrumented.vbhtml",
    "content": "﻿@Helper Strong(s As String)\n    @<strong>@s</strong>\nEnd Helper\n\n@Code\n    Dim i As Integer = 1\n    Dim foo = @@<p>Foo</p>\n    @:Hello, World!\n    @<p>Hello, World!</p>\nEnd Code\n\n@While i <= 10\n    @<p>Hello from VB.Net, #@(i)</p>\n    i += 1\nEnd While\n\n@If i = 11 Then\n    @<p>We wrote 10 lines!</p>\nEnd If\n\n@Do\n    @<p>Hello again: @i</p>\n    i -= 1\nLoop While i > 0\n\n@Select Case i\n    Case 11\n        @<p>No really, we wrote 10 lines!</p>\n    Case Else\n        @<p>We wrote a bunch more lines too!</p>\nEnd Select\n\n@For j as Integer = 1 to 10 Step 2\n    @<p>Hello again from VB.Net, #@(j)</p>\nNext j\n\n@Try\n    @<p>That time, we wrote 5 lines!</p>\nCatch ex as Exception\n    @<p>Oh no! An error occurred: @(ex.Message)</p>\nEnd Try\n\n@With i\n    @<p>i is now @(.ToString())</p>\nEnd With\n\n@SyncLock New Object()\n    @<p>This block is locked, for your security!</p>\nEnd SyncLock\n\n@Using New System.IO.MemoryStream()\n    @<p>Some random memory stream will be disposed after rendering this block</p>\nEnd Using"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/LayoutDirective.vbhtml",
    "content": "﻿@Layout ~/Foo/Bar/Baz"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/MarkupInCodeBlock.vbhtml",
    "content": "﻿@Code\n    For i = 1 To 10\n        @<p>Hello from VB.Net, #@(i.ToString())</p>\n    Next i\nEnd Code\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/NestedCodeBlocks.vbhtml",
    "content": "﻿@If True Then\n    @If True Then\n    End If\nEnd If"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/NestedHelpers.vbhtml",
    "content": "﻿@Helper Italic(s As String)\n    s = s.ToUpper()\n    @Helper Bold(s As String)\n        s = s.ToUpper()\n        @<strong>@s</strong>\n    End Helper\n    @<em>@Bold(s)</em>\nEnd Helper\n\n@Italic(\"Hello\")"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/NoLinePragmas.vbhtml",
    "content": "﻿@Code\n    Dim i as Integer = 1\nEnd Code\n\n@While i <= 10\n    @<p>Hello from VB.Net, #@(i)</p>\n    i += 1\n    'End While\nEnd While\n\n@If i = 11 Then\n    @<p>We wrote 10 lines!</p>\n    Dim s = \"End If\"\nEnd If\n\n@Select Case i\n    Case 11\n        @<p>No really, we wrote 10 lines!</p>\n    Case Else\n        @<p>Actually, we didn't...</p>\nEnd Select\n\n@For j as Integer = 1 to 10 Step 2\n    @<p>Hello again from VB.Net, #@(j)</p>\nNext\n\n@Try\n    @<p>That time, we wrote 5 lines!</p>\nCatch ex as Exception\n    @<p>Oh no! An error occurred: @(ex.Message)</p>\nEnd Try\n\n@With i\n    @<p>i is now @(.ToString())</p>\nEnd With\n\n@SyncLock New Object()\n    @<p>This block is locked, for your security!</p>\nEnd SyncLock\n\n@Using New System.IO.MemoryStream()\n    @<p>Some random memory stream will be disposed after rendering this block</p>\nEnd Using\n\n@SyntaxSampleHelpers.CodeForLink(Me)"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/Options.vbhtml",
    "content": "﻿@Option Strict On\n@Option Explicit Off\n\nHello, World!"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/ParserError.vbhtml",
    "content": "﻿@Code\nFoo\n'End Code"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/RazorComments.vbhtml",
    "content": "﻿@*This is not going to be rendered*@\n<p>This should @* not *@ be shown</p>\n\n@Code\n    @* Throw new Exception(\"Oh no!\") *@\nEnd Code\n\n@Code Dim bar As String = \"@* bar *@\" End Code\n<p>But this should show the comment syntax: @bar</p>\n<p>So should this: @@* bar *@@</p>\n\n@(a@**@b)"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/ResolveUrl.vbhtml",
    "content": "﻿<a href=\"~/Foo\">Foo</a>\n<a href=\"~/Products/@product.id\">@product.Name</a>\n<a href=\"~/Products/@product.id/Detail\">Details</a>\n<a href=\"~/A+Really(Crazy),Url.Is:This/@product.id/Detail\">Crazy Url!</a>\n\n@Code\n    @<text>\n        <a href=\"~/Foo\">Foo</a>\n        <a href=\"~/Products/@product.id\">@product.Name</a>\n        <a href=\"~/Products/@product.id/Detail\">Details</a>\n        <a href=\"~/A+Really(Crazy),Url.Is:This/@product.id/Detail\">Crazy Url!</a>\n    </text>\nEnd Code\n\n@Section Foo\n    <a href=\"~/Foo\">Foo</a>\n    <a href=\"~/Products/@product.id\">@product.Name</a>\n    <a href=\"~/Products/@product.id/Detail\">Details</a>\n    <a href=\"~/A+Really(Crazy),Url.Is:This/@product.id/Detail\">Crazy Url!</a>\nEnd Section"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/Sections.vbhtml",
    "content": "﻿@Code\n    Layout = \"_SectionTestLayout.vbhtml\"\nEnd Code\n\n<div>This is in the Body>\n\n@Section Section2\n    <div>This is in Section 2</div>\nEnd Section\n\n@Section Section1\n    <div>This is in Section 1</div>\nEnd Section"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/Templates.vbhtml",
    "content": "﻿@Imports System.Web.Helpers\n\n@Functions\n    Public Function Repeat(times As Integer, template As Func(Of Integer, object)) As HelperResult\n        Return New HelperResult(Sub(writer)\n            For i = 0 to times\n                DirectCast(template(i), HelperResult).WriteTo(writer)\n            Next i\n        End Sub)\n    End Function\nEnd Functions\n\n@Code\n    Dim foo As Func(Of Object, Object) = @<text>This works @item!</text>\n    @foo(\"too\")\nEnd Code\n\n<ul>\n@(Repeat(10, @@<li>Item #@item</li>))\n</ul>\n\n<p>\n@Repeat(10,\n    @@: This is line#@item of markup<br/>\n)\n</p>\n\n<ul>\n    @Repeat(10, @@<li>\n        Item #@item\n        @Code Dim parent = item End Code\n        <ul>\n            <li>Child Items... ?</li>\n        </ul>\n    </li>)\n</ul>"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/CodeGenerator/VB/Source/UnfinishedExpressionInCode.vbhtml",
    "content": "﻿@Code\n@DateTime.\nEnd Code"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/DesignTime/Simple.cshtml",
    "content": "﻿@{\n    string hello = \"Hello, World\";\n}\n\n<html>\n    <head>\n        <title>Simple Page</title>\n    </head>\n    <body>\n        <h1>Simple Page</h1>\n        <p>@hello</p>\n        <p>\n            @foreach(char c in hello) {@c}\n        </p>\n    </body>\n</html>"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/DesignTime/Simple.txt",
    "content": "﻿//------------------------------------------------------------------------------\n// <auto-generated>\n//     This code was generated by a tool.\n//     Runtime Version:N.N.NNNNN.N\n//\n//     Changes to this file may cause incorrect behavior and will be lost if\n//     the code is regenerated.\n// </auto-generated>\n//------------------------------------------------------------------------------\n\nnamespace Razor {\n    \n    \n    public class @__CompiledTemplate {\n        \n        private static object @__o;\n        \n#line hidden\n        \n        public @__CompiledTemplate() {\n        }\n        \n        public override void Execute() {\n            \n            #line 1 \"C:\\This\\Path\\Is\\Just\\For\\Line\\Pragmas.cshtml\"\n  \n    string hello = \"Hello, World\";\n\n            \n            #line default\n            #line hidden\n            \n            #line 2 \"C:\\This\\Path\\Is\\Just\\For\\Line\\Pragmas.cshtml\"\n      __o = hello;\n\n            \n            #line default\n            #line hidden\n            \n            #line 3 \"C:\\This\\Path\\Is\\Just\\For\\Line\\Pragmas.cshtml\"\n            foreach(char c in hello) {\n            \n            #line default\n            #line hidden\n            \n            #line 4 \"C:\\This\\Path\\Is\\Just\\For\\Line\\Pragmas.cshtml\"\n                                  __o = c;\n\n            \n            #line default\n            #line hidden\n            \n            #line 5 \"C:\\This\\Path\\Is\\Just\\For\\Line\\Pragmas.cshtml\"\n                                         }\n            \n            #line default\n            #line hidden\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/TestFiles/nested-1000.html",
    "content": "﻿<outer>\n<elem-1>\n<elem-2>\n<elem-3>\n<elem-4>\n<elem-5>\n<elem-6>\n<elem-7>\n<elem-8>\n<elem-9>\n<elem-10>\n<elem-11>\n<elem-12>\n<elem-13>\n<elem-14>\n<elem-15>\n<elem-16>\n<elem-17>\n<elem-18>\n<elem-19>\n<elem-20>\n<elem-21>\n<elem-22>\n<elem-23>\n<elem-24>\n<elem-25>\n<elem-26>\n<elem-27>\n<elem-28>\n<elem-29>\n<elem-30>\n<elem-31>\n<elem-32>\n<elem-33>\n<elem-34>\n<elem-35>\n<elem-36>\n<elem-37>\n<elem-38>\n<elem-39>\n<elem-40>\n<elem-41>\n<elem-42>\n<elem-43>\n<elem-44>\n<elem-45>\n<elem-46>\n<elem-47>\n<elem-48>\n<elem-49>\n<elem-50>\n<elem-51>\n<elem-52>\n<elem-53>\n<elem-54>\n<elem-55>\n<elem-56>\n<elem-57>\n<elem-58>\n<elem-59>\n<elem-60>\n<elem-61>\n<elem-62>\n<elem-63>\n<elem-64>\n<elem-65>\n<elem-66>\n<elem-67>\n<elem-68>\n<elem-69>\n<elem-70>\n<elem-71>\n<elem-72>\n<elem-73>\n<elem-74>\n<elem-75>\n<elem-76>\n<elem-77>\n<elem-78>\n<elem-79>\n<elem-80>\n<elem-81>\n<elem-82>\n<elem-83>\n<elem-84>\n<elem-85>\n<elem-86>\n<elem-87>\n<elem-88>\n<elem-89>\n<elem-90>\n<elem-91>\n<elem-92>\n<elem-93>\n<elem-94>\n<elem-95>\n<elem-96>\n<elem-97>\n<elem-98>\n<elem-99>\n<elem-100>\n<elem-101>\n<elem-102>\n<elem-103>\n<elem-104>\n<elem-105>\n<elem-106>\n<elem-107>\n<elem-108>\n<elem-109>\n<elem-110>\n<elem-111>\n<elem-112>\n<elem-113>\n<elem-114>\n<elem-115>\n<elem-116>\n<elem-117>\n<elem-118>\n<elem-119>\n<elem-120>\n<elem-121>\n<elem-122>\n<elem-123>\n<elem-124>\n<elem-125>\n<elem-126>\n<elem-127>\n<elem-128>\n<elem-129>\n<elem-130>\n<elem-131>\n<elem-132>\n<elem-133>\n<elem-134>\n<elem-135>\n<elem-136>\n<elem-137>\n<elem-138>\n<elem-139>\n<elem-140>\n<elem-141>\n<elem-142>\n<elem-143>\n<elem-144>\n<elem-145>\n<elem-146>\n<elem-147>\n<elem-148>\n<elem-149>\n<elem-150>\n<elem-151>\n<elem-152>\n<elem-153>\n<elem-154>\n<elem-155>\n<elem-156>\n<elem-157>\n<elem-158>\n<elem-159>\n<elem-160>\n<elem-161>\n<elem-162>\n<elem-163>\n<elem-164>\n<elem-165>\n<elem-166>\n<elem-167>\n<elem-168>\n<elem-169>\n<elem-170>\n<elem-171>\n<elem-172>\n<elem-173>\n<elem-174>\n<elem-175>\n<elem-176>\n<elem-177>\n<elem-178>\n<elem-179>\n<elem-180>\n<elem-181>\n<elem-182>\n<elem-183>\n<elem-184>\n<elem-185>\n<elem-186>\n<elem-187>\n<elem-188>\n<elem-189>\n<elem-190>\n<elem-191>\n<elem-192>\n<elem-193>\n<elem-194>\n<elem-195>\n<elem-196>\n<elem-197>\n<elem-198>\n<elem-199>\n<elem-200>\n<elem-201>\n<elem-202>\n<elem-203>\n<elem-204>\n<elem-205>\n<elem-206>\n<elem-207>\n<elem-208>\n<elem-209>\n<elem-210>\n<elem-211>\n<elem-212>\n<elem-213>\n<elem-214>\n<elem-215>\n<elem-216>\n<elem-217>\n<elem-218>\n<elem-219>\n<elem-220>\n<elem-221>\n<elem-222>\n<elem-223>\n<elem-224>\n<elem-225>\n<elem-226>\n<elem-227>\n<elem-228>\n<elem-229>\n<elem-230>\n<elem-231>\n<elem-232>\n<elem-233>\n<elem-234>\n<elem-235>\n<elem-236>\n<elem-237>\n<elem-238>\n<elem-239>\n<elem-240>\n<elem-241>\n<elem-242>\n<elem-243>\n<elem-244>\n<elem-245>\n<elem-246>\n<elem-247>\n<elem-248>\n<elem-249>\n<elem-250>\n<elem-251>\n<elem-252>\n<elem-253>\n<elem-254>\n<elem-255>\n<elem-256>\n<elem-257>\n<elem-258>\n<elem-259>\n<elem-260>\n<elem-261>\n<elem-262>\n<elem-263>\n<elem-264>\n<elem-265>\n<elem-266>\n<elem-267>\n<elem-268>\n<elem-269>\n<elem-270>\n<elem-271>\n<elem-272>\n<elem-273>\n<elem-274>\n<elem-275>\n<elem-276>\n<elem-277>\n<elem-278>\n<elem-279>\n<elem-280>\n<elem-281>\n<elem-282>\n<elem-283>\n<elem-284>\n<elem-285>\n<elem-286>\n<elem-287>\n<elem-288>\n<elem-289>\n<elem-290>\n<elem-291>\n<elem-292>\n<elem-293>\n<elem-294>\n<elem-295>\n<elem-296>\n<elem-297>\n<elem-298>\n<elem-299>\n<elem-300>\n<elem-301>\n<elem-302>\n<elem-303>\n<elem-304>\n<elem-305>\n<elem-306>\n<elem-307>\n<elem-308>\n<elem-309>\n<elem-310>\n<elem-311>\n<elem-312>\n<elem-313>\n<elem-314>\n<elem-315>\n<elem-316>\n<elem-317>\n<elem-318>\n<elem-319>\n<elem-320>\n<elem-321>\n<elem-322>\n<elem-323>\n<elem-324>\n<elem-325>\n<elem-326>\n<elem-327>\n<elem-328>\n<elem-329>\n<elem-330>\n<elem-331>\n<elem-332>\n<elem-333>\n<elem-334>\n<elem-335>\n<elem-336>\n<elem-337>\n<elem-338>\n<elem-339>\n<elem-340>\n<elem-341>\n<elem-342>\n<elem-343>\n<elem-344>\n<elem-345>\n<elem-346>\n<elem-347>\n<elem-348>\n<elem-349>\n<elem-350>\n<elem-351>\n<elem-352>\n<elem-353>\n<elem-354>\n<elem-355>\n<elem-356>\n<elem-357>\n<elem-358>\n<elem-359>\n<elem-360>\n<elem-361>\n<elem-362>\n<elem-363>\n<elem-364>\n<elem-365>\n<elem-366>\n<elem-367>\n<elem-368>\n<elem-369>\n<elem-370>\n<elem-371>\n<elem-372>\n<elem-373>\n<elem-374>\n<elem-375>\n<elem-376>\n<elem-377>\n<elem-378>\n<elem-379>\n<elem-380>\n<elem-381>\n<elem-382>\n<elem-383>\n<elem-384>\n<elem-385>\n<elem-386>\n<elem-387>\n<elem-388>\n<elem-389>\n<elem-390>\n<elem-391>\n<elem-392>\n<elem-393>\n<elem-394>\n<elem-395>\n<elem-396>\n<elem-397>\n<elem-398>\n<elem-399>\n<elem-400>\n<elem-401>\n<elem-402>\n<elem-403>\n<elem-404>\n<elem-405>\n<elem-406>\n<elem-407>\n<elem-408>\n<elem-409>\n<elem-410>\n<elem-411>\n<elem-412>\n<elem-413>\n<elem-414>\n<elem-415>\n<elem-416>\n<elem-417>\n<elem-418>\n<elem-419>\n<elem-420>\n<elem-421>\n<elem-422>\n<elem-423>\n<elem-424>\n<elem-425>\n<elem-426>\n<elem-427>\n<elem-428>\n<elem-429>\n<elem-430>\n<elem-431>\n<elem-432>\n<elem-433>\n<elem-434>\n<elem-435>\n<elem-436>\n<elem-437>\n<elem-438>\n<elem-439>\n<elem-440>\n<elem-441>\n<elem-442>\n<elem-443>\n<elem-444>\n<elem-445>\n<elem-446>\n<elem-447>\n<elem-448>\n<elem-449>\n<elem-450>\n<elem-451>\n<elem-452>\n<elem-453>\n<elem-454>\n<elem-455>\n<elem-456>\n<elem-457>\n<elem-458>\n<elem-459>\n<elem-460>\n<elem-461>\n<elem-462>\n<elem-463>\n<elem-464>\n<elem-465>\n<elem-466>\n<elem-467>\n<elem-468>\n<elem-469>\n<elem-470>\n<elem-471>\n<elem-472>\n<elem-473>\n<elem-474>\n<elem-475>\n<elem-476>\n<elem-477>\n<elem-478>\n<elem-479>\n<elem-480>\n<elem-481>\n<elem-482>\n<elem-483>\n<elem-484>\n<elem-485>\n<elem-486>\n<elem-487>\n<elem-488>\n<elem-489>\n<elem-490>\n<elem-491>\n<elem-492>\n<elem-493>\n<elem-494>\n<elem-495>\n<elem-496>\n<elem-497>\n<elem-498>\n<elem-499>\n<elem-500>\n<elem-501>\n<elem-502>\n<elem-503>\n<elem-504>\n<elem-505>\n<elem-506>\n<elem-507>\n<elem-508>\n<elem-509>\n<elem-510>\n<elem-511>\n<elem-512>\n<elem-513>\n<elem-514>\n<elem-515>\n<elem-516>\n<elem-517>\n<elem-518>\n<elem-519>\n<elem-520>\n<elem-521>\n<elem-522>\n<elem-523>\n<elem-524>\n<elem-525>\n<elem-526>\n<elem-527>\n<elem-528>\n<elem-529>\n<elem-530>\n<elem-531>\n<elem-532>\n<elem-533>\n<elem-534>\n<elem-535>\n<elem-536>\n<elem-537>\n<elem-538>\n<elem-539>\n<elem-540>\n<elem-541>\n<elem-542>\n<elem-543>\n<elem-544>\n<elem-545>\n<elem-546>\n<elem-547>\n<elem-548>\n<elem-549>\n<elem-550>\n<elem-551>\n<elem-552>\n<elem-553>\n<elem-554>\n<elem-555>\n<elem-556>\n<elem-557>\n<elem-558>\n<elem-559>\n<elem-560>\n<elem-561>\n<elem-562>\n<elem-563>\n<elem-564>\n<elem-565>\n<elem-566>\n<elem-567>\n<elem-568>\n<elem-569>\n<elem-570>\n<elem-571>\n<elem-572>\n<elem-573>\n<elem-574>\n<elem-575>\n<elem-576>\n<elem-577>\n<elem-578>\n<elem-579>\n<elem-580>\n<elem-581>\n<elem-582>\n<elem-583>\n<elem-584>\n<elem-585>\n<elem-586>\n<elem-587>\n<elem-588>\n<elem-589>\n<elem-590>\n<elem-591>\n<elem-592>\n<elem-593>\n<elem-594>\n<elem-595>\n<elem-596>\n<elem-597>\n<elem-598>\n<elem-599>\n<elem-600>\n<elem-601>\n<elem-602>\n<elem-603>\n<elem-604>\n<elem-605>\n<elem-606>\n<elem-607>\n<elem-608>\n<elem-609>\n<elem-610>\n<elem-611>\n<elem-612>\n<elem-613>\n<elem-614>\n<elem-615>\n<elem-616>\n<elem-617>\n<elem-618>\n<elem-619>\n<elem-620>\n<elem-621>\n<elem-622>\n<elem-623>\n<elem-624>\n<elem-625>\n<elem-626>\n<elem-627>\n<elem-628>\n<elem-629>\n<elem-630>\n<elem-631>\n<elem-632>\n<elem-633>\n<elem-634>\n<elem-635>\n<elem-636>\n<elem-637>\n<elem-638>\n<elem-639>\n<elem-640>\n<elem-641>\n<elem-642>\n<elem-643>\n<elem-644>\n<elem-645>\n<elem-646>\n<elem-647>\n<elem-648>\n<elem-649>\n<elem-650>\n<elem-651>\n<elem-652>\n<elem-653>\n<elem-654>\n<elem-655>\n<elem-656>\n<elem-657>\n<elem-658>\n<elem-659>\n<elem-660>\n<elem-661>\n<elem-662>\n<elem-663>\n<elem-664>\n<elem-665>\n<elem-666>\n<elem-667>\n<elem-668>\n<elem-669>\n<elem-670>\n<elem-671>\n<elem-672>\n<elem-673>\n<elem-674>\n<elem-675>\n<elem-676>\n<elem-677>\n<elem-678>\n<elem-679>\n<elem-680>\n<elem-681>\n<elem-682>\n<elem-683>\n<elem-684>\n<elem-685>\n<elem-686>\n<elem-687>\n<elem-688>\n<elem-689>\n<elem-690>\n<elem-691>\n<elem-692>\n<elem-693>\n<elem-694>\n<elem-695>\n<elem-696>\n<elem-697>\n<elem-698>\n<elem-699>\n<elem-700>\n<elem-701>\n<elem-702>\n<elem-703>\n<elem-704>\n<elem-705>\n<elem-706>\n<elem-707>\n<elem-708>\n<elem-709>\n<elem-710>\n<elem-711>\n<elem-712>\n<elem-713>\n<elem-714>\n<elem-715>\n<elem-716>\n<elem-717>\n<elem-718>\n<elem-719>\n<elem-720>\n<elem-721>\n<elem-722>\n<elem-723>\n<elem-724>\n<elem-725>\n<elem-726>\n<elem-727>\n<elem-728>\n<elem-729>\n<elem-730>\n<elem-731>\n<elem-732>\n<elem-733>\n<elem-734>\n<elem-735>\n<elem-736>\n<elem-737>\n<elem-738>\n<elem-739>\n<elem-740>\n<elem-741>\n<elem-742>\n<elem-743>\n<elem-744>\n<elem-745>\n<elem-746>\n<elem-747>\n<elem-748>\n<elem-749>\n<elem-750>\n<elem-751>\n<elem-752>\n<elem-753>\n<elem-754>\n<elem-755>\n<elem-756>\n<elem-757>\n<elem-758>\n<elem-759>\n<elem-760>\n<elem-761>\n<elem-762>\n<elem-763>\n<elem-764>\n<elem-765>\n<elem-766>\n<elem-767>\n<elem-768>\n<elem-769>\n<elem-770>\n<elem-771>\n<elem-772>\n<elem-773>\n<elem-774>\n<elem-775>\n<elem-776>\n<elem-777>\n<elem-778>\n<elem-779>\n<elem-780>\n<elem-781>\n<elem-782>\n<elem-783>\n<elem-784>\n<elem-785>\n<elem-786>\n<elem-787>\n<elem-788>\n<elem-789>\n<elem-790>\n<elem-791>\n<elem-792>\n<elem-793>\n<elem-794>\n<elem-795>\n<elem-796>\n<elem-797>\n<elem-798>\n<elem-799>\n<elem-800>\n<elem-801>\n<elem-802>\n<elem-803>\n<elem-804>\n<elem-805>\n<elem-806>\n<elem-807>\n<elem-808>\n<elem-809>\n<elem-810>\n<elem-811>\n<elem-812>\n<elem-813>\n<elem-814>\n<elem-815>\n<elem-816>\n<elem-817>\n<elem-818>\n<elem-819>\n<elem-820>\n<elem-821>\n<elem-822>\n<elem-823>\n<elem-824>\n<elem-825>\n<elem-826>\n<elem-827>\n<elem-828>\n<elem-829>\n<elem-830>\n<elem-831>\n<elem-832>\n<elem-833>\n<elem-834>\n<elem-835>\n<elem-836>\n<elem-837>\n<elem-838>\n<elem-839>\n<elem-840>\n<elem-841>\n<elem-842>\n<elem-843>\n<elem-844>\n<elem-845>\n<elem-846>\n<elem-847>\n<elem-848>\n<elem-849>\n<elem-850>\n<elem-851>\n<elem-852>\n<elem-853>\n<elem-854>\n<elem-855>\n<elem-856>\n<elem-857>\n<elem-858>\n<elem-859>\n<elem-860>\n<elem-861>\n<elem-862>\n<elem-863>\n<elem-864>\n<elem-865>\n<elem-866>\n<elem-867>\n<elem-868>\n<elem-869>\n<elem-870>\n<elem-871>\n<elem-872>\n<elem-873>\n<elem-874>\n<elem-875>\n<elem-876>\n<elem-877>\n<elem-878>\n<elem-879>\n<elem-880>\n<elem-881>\n<elem-882>\n<elem-883>\n<elem-884>\n<elem-885>\n<elem-886>\n<elem-887>\n<elem-888>\n<elem-889>\n<elem-890>\n<elem-891>\n<elem-892>\n<elem-893>\n<elem-894>\n<elem-895>\n<elem-896>\n<elem-897>\n<elem-898>\n<elem-899>\n<elem-900>\n<elem-901>\n<elem-902>\n<elem-903>\n<elem-904>\n<elem-905>\n<elem-906>\n<elem-907>\n<elem-908>\n<elem-909>\n<elem-910>\n<elem-911>\n<elem-912>\n<elem-913>\n<elem-914>\n<elem-915>\n<elem-916>\n<elem-917>\n<elem-918>\n<elem-919>\n<elem-920>\n<elem-921>\n<elem-922>\n<elem-923>\n<elem-924>\n<elem-925>\n<elem-926>\n<elem-927>\n<elem-928>\n<elem-929>\n<elem-930>\n<elem-931>\n<elem-932>\n<elem-933>\n<elem-934>\n<elem-935>\n<elem-936>\n<elem-937>\n<elem-938>\n<elem-939>\n<elem-940>\n<elem-941>\n<elem-942>\n<elem-943>\n<elem-944>\n<elem-945>\n<elem-946>\n<elem-947>\n<elem-948>\n<elem-949>\n<elem-950>\n<elem-951>\n<elem-952>\n<elem-953>\n<elem-954>\n<elem-955>\n<elem-956>\n<elem-957>\n<elem-958>\n<elem-959>\n<elem-960>\n<elem-961>\n<elem-962>\n<elem-963>\n<elem-964>\n<elem-965>\n<elem-966>\n<elem-967>\n<elem-968>\n<elem-969>\n<elem-970>\n<elem-971>\n<elem-972>\n<elem-973>\n<elem-974>\n<elem-975>\n<elem-976>\n<elem-977>\n<elem-978>\n<elem-979>\n<elem-980>\n<elem-981>\n<elem-982>\n<elem-983>\n<elem-984>\n<elem-985>\n<elem-986>\n<elem-987>\n<elem-988>\n<elem-989>\n<elem-990>\n<elem-991>\n<elem-992>\n<elem-993>\n<elem-994>\n<elem-995>\n<elem-996>\n<elem-997>\n<elem-998>\n<elem-999>\n<elem-1000>\n</elem-1000>\n</elem-999>\n</elem-998>\n</elem-997>\n</elem-996>\n</elem-995>\n</elem-994>\n</elem-993>\n</elem-992>\n</elem-991>\n</elem-990>\n</elem-989>\n</elem-988>\n</elem-987>\n</elem-986>\n</elem-985>\n</elem-984>\n</elem-983>\n</elem-982>\n</elem-981>\n</elem-980>\n</elem-979>\n</elem-978>\n</elem-977>\n</elem-976>\n</elem-975>\n</elem-974>\n</elem-973>\n</elem-972>\n</elem-971>\n</elem-970>\n</elem-969>\n</elem-968>\n</elem-967>\n</elem-966>\n</elem-965>\n</elem-964>\n</elem-963>\n</elem-962>\n</elem-961>\n</elem-960>\n</elem-959>\n</elem-958>\n</elem-957>\n</elem-956>\n</elem-955>\n</elem-954>\n</elem-953>\n</elem-952>\n</elem-951>\n</elem-950>\n</elem-949>\n</elem-948>\n</elem-947>\n</elem-946>\n</elem-945>\n</elem-944>\n</elem-943>\n</elem-942>\n</elem-941>\n</elem-940>\n</elem-939>\n</elem-938>\n</elem-937>\n</elem-936>\n</elem-935>\n</elem-934>\n</elem-933>\n</elem-932>\n</elem-931>\n</elem-930>\n</elem-929>\n</elem-928>\n</elem-927>\n</elem-926>\n</elem-925>\n</elem-924>\n</elem-923>\n</elem-922>\n</elem-921>\n</elem-920>\n</elem-919>\n</elem-918>\n</elem-917>\n</elem-916>\n</elem-915>\n</elem-914>\n</elem-913>\n</elem-912>\n</elem-911>\n</elem-910>\n</elem-909>\n</elem-908>\n</elem-907>\n</elem-906>\n</elem-905>\n</elem-904>\n</elem-903>\n</elem-902>\n</elem-901>\n</elem-900>\n</elem-899>\n</elem-898>\n</elem-897>\n</elem-896>\n</elem-895>\n</elem-894>\n</elem-893>\n</elem-892>\n</elem-891>\n</elem-890>\n</elem-889>\n</elem-888>\n</elem-887>\n</elem-886>\n</elem-885>\n</elem-884>\n</elem-883>\n</elem-882>\n</elem-881>\n</elem-880>\n</elem-879>\n</elem-878>\n</elem-877>\n</elem-876>\n</elem-875>\n</elem-874>\n</elem-873>\n</elem-872>\n</elem-871>\n</elem-870>\n</elem-869>\n</elem-868>\n</elem-867>\n</elem-866>\n</elem-865>\n</elem-864>\n</elem-863>\n</elem-862>\n</elem-861>\n</elem-860>\n</elem-859>\n</elem-858>\n</elem-857>\n</elem-856>\n</elem-855>\n</elem-854>\n</elem-853>\n</elem-852>\n</elem-851>\n</elem-850>\n</elem-849>\n</elem-848>\n</elem-847>\n</elem-846>\n</elem-845>\n</elem-844>\n</elem-843>\n</elem-842>\n</elem-841>\n</elem-840>\n</elem-839>\n</elem-838>\n</elem-837>\n</elem-836>\n</elem-835>\n</elem-834>\n</elem-833>\n</elem-832>\n</elem-831>\n</elem-830>\n</elem-829>\n</elem-828>\n</elem-827>\n</elem-826>\n</elem-825>\n</elem-824>\n</elem-823>\n</elem-822>\n</elem-821>\n</elem-820>\n</elem-819>\n</elem-818>\n</elem-817>\n</elem-816>\n</elem-815>\n</elem-814>\n</elem-813>\n</elem-812>\n</elem-811>\n</elem-810>\n</elem-809>\n</elem-808>\n</elem-807>\n</elem-806>\n</elem-805>\n</elem-804>\n</elem-803>\n</elem-802>\n</elem-801>\n</elem-800>\n</elem-799>\n</elem-798>\n</elem-797>\n</elem-796>\n</elem-795>\n</elem-794>\n</elem-793>\n</elem-792>\n</elem-791>\n</elem-790>\n</elem-789>\n</elem-788>\n</elem-787>\n</elem-786>\n</elem-785>\n</elem-784>\n</elem-783>\n</elem-782>\n</elem-781>\n</elem-780>\n</elem-779>\n</elem-778>\n</elem-777>\n</elem-776>\n</elem-775>\n</elem-774>\n</elem-773>\n</elem-772>\n</elem-771>\n</elem-770>\n</elem-769>\n</elem-768>\n</elem-767>\n</elem-766>\n</elem-765>\n</elem-764>\n</elem-763>\n</elem-762>\n</elem-761>\n</elem-760>\n</elem-759>\n</elem-758>\n</elem-757>\n</elem-756>\n</elem-755>\n</elem-754>\n</elem-753>\n</elem-752>\n</elem-751>\n</elem-750>\n</elem-749>\n</elem-748>\n</elem-747>\n</elem-746>\n</elem-745>\n</elem-744>\n</elem-743>\n</elem-742>\n</elem-741>\n</elem-740>\n</elem-739>\n</elem-738>\n</elem-737>\n</elem-736>\n</elem-735>\n</elem-734>\n</elem-733>\n</elem-732>\n</elem-731>\n</elem-730>\n</elem-729>\n</elem-728>\n</elem-727>\n</elem-726>\n</elem-725>\n</elem-724>\n</elem-723>\n</elem-722>\n</elem-721>\n</elem-720>\n</elem-719>\n</elem-718>\n</elem-717>\n</elem-716>\n</elem-715>\n</elem-714>\n</elem-713>\n</elem-712>\n</elem-711>\n</elem-710>\n</elem-709>\n</elem-708>\n</elem-707>\n</elem-706>\n</elem-705>\n</elem-704>\n</elem-703>\n</elem-702>\n</elem-701>\n</elem-700>\n</elem-699>\n</elem-698>\n</elem-697>\n</elem-696>\n</elem-695>\n</elem-694>\n</elem-693>\n</elem-692>\n</elem-691>\n</elem-690>\n</elem-689>\n</elem-688>\n</elem-687>\n</elem-686>\n</elem-685>\n</elem-684>\n</elem-683>\n</elem-682>\n</elem-681>\n</elem-680>\n</elem-679>\n</elem-678>\n</elem-677>\n</elem-676>\n</elem-675>\n</elem-674>\n</elem-673>\n</elem-672>\n</elem-671>\n</elem-670>\n</elem-669>\n</elem-668>\n</elem-667>\n</elem-666>\n</elem-665>\n</elem-664>\n</elem-663>\n</elem-662>\n</elem-661>\n</elem-660>\n</elem-659>\n</elem-658>\n</elem-657>\n</elem-656>\n</elem-655>\n</elem-654>\n</elem-653>\n</elem-652>\n</elem-651>\n</elem-650>\n</elem-649>\n</elem-648>\n</elem-647>\n</elem-646>\n</elem-645>\n</elem-644>\n</elem-643>\n</elem-642>\n</elem-641>\n</elem-640>\n</elem-639>\n</elem-638>\n</elem-637>\n</elem-636>\n</elem-635>\n</elem-634>\n</elem-633>\n</elem-632>\n</elem-631>\n</elem-630>\n</elem-629>\n</elem-628>\n</elem-627>\n</elem-626>\n</elem-625>\n</elem-624>\n</elem-623>\n</elem-622>\n</elem-621>\n</elem-620>\n</elem-619>\n</elem-618>\n</elem-617>\n</elem-616>\n</elem-615>\n</elem-614>\n</elem-613>\n</elem-612>\n</elem-611>\n</elem-610>\n</elem-609>\n</elem-608>\n</elem-607>\n</elem-606>\n</elem-605>\n</elem-604>\n</elem-603>\n</elem-602>\n</elem-601>\n</elem-600>\n</elem-599>\n</elem-598>\n</elem-597>\n</elem-596>\n</elem-595>\n</elem-594>\n</elem-593>\n</elem-592>\n</elem-591>\n</elem-590>\n</elem-589>\n</elem-588>\n</elem-587>\n</elem-586>\n</elem-585>\n</elem-584>\n</elem-583>\n</elem-582>\n</elem-581>\n</elem-580>\n</elem-579>\n</elem-578>\n</elem-577>\n</elem-576>\n</elem-575>\n</elem-574>\n</elem-573>\n</elem-572>\n</elem-571>\n</elem-570>\n</elem-569>\n</elem-568>\n</elem-567>\n</elem-566>\n</elem-565>\n</elem-564>\n</elem-563>\n</elem-562>\n</elem-561>\n</elem-560>\n</elem-559>\n</elem-558>\n</elem-557>\n</elem-556>\n</elem-555>\n</elem-554>\n</elem-553>\n</elem-552>\n</elem-551>\n</elem-550>\n</elem-549>\n</elem-548>\n</elem-547>\n</elem-546>\n</elem-545>\n</elem-544>\n</elem-543>\n</elem-542>\n</elem-541>\n</elem-540>\n</elem-539>\n</elem-538>\n</elem-537>\n</elem-536>\n</elem-535>\n</elem-534>\n</elem-533>\n</elem-532>\n</elem-531>\n</elem-530>\n</elem-529>\n</elem-528>\n</elem-527>\n</elem-526>\n</elem-525>\n</elem-524>\n</elem-523>\n</elem-522>\n</elem-521>\n</elem-520>\n</elem-519>\n</elem-518>\n</elem-517>\n</elem-516>\n</elem-515>\n</elem-514>\n</elem-513>\n</elem-512>\n</elem-511>\n</elem-510>\n</elem-509>\n</elem-508>\n</elem-507>\n</elem-506>\n</elem-505>\n</elem-504>\n</elem-503>\n</elem-502>\n</elem-501>\n</elem-500>\n</elem-499>\n</elem-498>\n</elem-497>\n</elem-496>\n</elem-495>\n</elem-494>\n</elem-493>\n</elem-492>\n</elem-491>\n</elem-490>\n</elem-489>\n</elem-488>\n</elem-487>\n</elem-486>\n</elem-485>\n</elem-484>\n</elem-483>\n</elem-482>\n</elem-481>\n</elem-480>\n</elem-479>\n</elem-478>\n</elem-477>\n</elem-476>\n</elem-475>\n</elem-474>\n</elem-473>\n</elem-472>\n</elem-471>\n</elem-470>\n</elem-469>\n</elem-468>\n</elem-467>\n</elem-466>\n</elem-465>\n</elem-464>\n</elem-463>\n</elem-462>\n</elem-461>\n</elem-460>\n</elem-459>\n</elem-458>\n</elem-457>\n</elem-456>\n</elem-455>\n</elem-454>\n</elem-453>\n</elem-452>\n</elem-451>\n</elem-450>\n</elem-449>\n</elem-448>\n</elem-447>\n</elem-446>\n</elem-445>\n</elem-444>\n</elem-443>\n</elem-442>\n</elem-441>\n</elem-440>\n</elem-439>\n</elem-438>\n</elem-437>\n</elem-436>\n</elem-435>\n</elem-434>\n</elem-433>\n</elem-432>\n</elem-431>\n</elem-430>\n</elem-429>\n</elem-428>\n</elem-427>\n</elem-426>\n</elem-425>\n</elem-424>\n</elem-423>\n</elem-422>\n</elem-421>\n</elem-420>\n</elem-419>\n</elem-418>\n</elem-417>\n</elem-416>\n</elem-415>\n</elem-414>\n</elem-413>\n</elem-412>\n</elem-411>\n</elem-410>\n</elem-409>\n</elem-408>\n</elem-407>\n</elem-406>\n</elem-405>\n</elem-404>\n</elem-403>\n</elem-402>\n</elem-401>\n</elem-400>\n</elem-399>\n</elem-398>\n</elem-397>\n</elem-396>\n</elem-395>\n</elem-394>\n</elem-393>\n</elem-392>\n</elem-391>\n</elem-390>\n</elem-389>\n</elem-388>\n</elem-387>\n</elem-386>\n</elem-385>\n</elem-384>\n</elem-383>\n</elem-382>\n</elem-381>\n</elem-380>\n</elem-379>\n</elem-378>\n</elem-377>\n</elem-376>\n</elem-375>\n</elem-374>\n</elem-373>\n</elem-372>\n</elem-371>\n</elem-370>\n</elem-369>\n</elem-368>\n</elem-367>\n</elem-366>\n</elem-365>\n</elem-364>\n</elem-363>\n</elem-362>\n</elem-361>\n</elem-360>\n</elem-359>\n</elem-358>\n</elem-357>\n</elem-356>\n</elem-355>\n</elem-354>\n</elem-353>\n</elem-352>\n</elem-351>\n</elem-350>\n</elem-349>\n</elem-348>\n</elem-347>\n</elem-346>\n</elem-345>\n</elem-344>\n</elem-343>\n</elem-342>\n</elem-341>\n</elem-340>\n</elem-339>\n</elem-338>\n</elem-337>\n</elem-336>\n</elem-335>\n</elem-334>\n</elem-333>\n</elem-332>\n</elem-331>\n</elem-330>\n</elem-329>\n</elem-328>\n</elem-327>\n</elem-326>\n</elem-325>\n</elem-324>\n</elem-323>\n</elem-322>\n</elem-321>\n</elem-320>\n</elem-319>\n</elem-318>\n</elem-317>\n</elem-316>\n</elem-315>\n</elem-314>\n</elem-313>\n</elem-312>\n</elem-311>\n</elem-310>\n</elem-309>\n</elem-308>\n</elem-307>\n</elem-306>\n</elem-305>\n</elem-304>\n</elem-303>\n</elem-302>\n</elem-301>\n</elem-300>\n</elem-299>\n</elem-298>\n</elem-297>\n</elem-296>\n</elem-295>\n</elem-294>\n</elem-293>\n</elem-292>\n</elem-291>\n</elem-290>\n</elem-289>\n</elem-288>\n</elem-287>\n</elem-286>\n</elem-285>\n</elem-284>\n</elem-283>\n</elem-282>\n</elem-281>\n</elem-280>\n</elem-279>\n</elem-278>\n</elem-277>\n</elem-276>\n</elem-275>\n</elem-274>\n</elem-273>\n</elem-272>\n</elem-271>\n</elem-270>\n</elem-269>\n</elem-268>\n</elem-267>\n</elem-266>\n</elem-265>\n</elem-264>\n</elem-263>\n</elem-262>\n</elem-261>\n</elem-260>\n</elem-259>\n</elem-258>\n</elem-257>\n</elem-256>\n</elem-255>\n</elem-254>\n</elem-253>\n</elem-252>\n</elem-251>\n</elem-250>\n</elem-249>\n</elem-248>\n</elem-247>\n</elem-246>\n</elem-245>\n</elem-244>\n</elem-243>\n</elem-242>\n</elem-241>\n</elem-240>\n</elem-239>\n</elem-238>\n</elem-237>\n</elem-236>\n</elem-235>\n</elem-234>\n</elem-233>\n</elem-232>\n</elem-231>\n</elem-230>\n</elem-229>\n</elem-228>\n</elem-227>\n</elem-226>\n</elem-225>\n</elem-224>\n</elem-223>\n</elem-222>\n</elem-221>\n</elem-220>\n</elem-219>\n</elem-218>\n</elem-217>\n</elem-216>\n</elem-215>\n</elem-214>\n</elem-213>\n</elem-212>\n</elem-211>\n</elem-210>\n</elem-209>\n</elem-208>\n</elem-207>\n</elem-206>\n</elem-205>\n</elem-204>\n</elem-203>\n</elem-202>\n</elem-201>\n</elem-200>\n</elem-199>\n</elem-198>\n</elem-197>\n</elem-196>\n</elem-195>\n</elem-194>\n</elem-193>\n</elem-192>\n</elem-191>\n</elem-190>\n</elem-189>\n</elem-188>\n</elem-187>\n</elem-186>\n</elem-185>\n</elem-184>\n</elem-183>\n</elem-182>\n</elem-181>\n</elem-180>\n</elem-179>\n</elem-178>\n</elem-177>\n</elem-176>\n</elem-175>\n</elem-174>\n</elem-173>\n</elem-172>\n</elem-171>\n</elem-170>\n</elem-169>\n</elem-168>\n</elem-167>\n</elem-166>\n</elem-165>\n</elem-164>\n</elem-163>\n</elem-162>\n</elem-161>\n</elem-160>\n</elem-159>\n</elem-158>\n</elem-157>\n</elem-156>\n</elem-155>\n</elem-154>\n</elem-153>\n</elem-152>\n</elem-151>\n</elem-150>\n</elem-149>\n</elem-148>\n</elem-147>\n</elem-146>\n</elem-145>\n</elem-144>\n</elem-143>\n</elem-142>\n</elem-141>\n</elem-140>\n</elem-139>\n</elem-138>\n</elem-137>\n</elem-136>\n</elem-135>\n</elem-134>\n</elem-133>\n</elem-132>\n</elem-131>\n</elem-130>\n</elem-129>\n</elem-128>\n</elem-127>\n</elem-126>\n</elem-125>\n</elem-124>\n</elem-123>\n</elem-122>\n</elem-121>\n</elem-120>\n</elem-119>\n</elem-118>\n</elem-117>\n</elem-116>\n</elem-115>\n</elem-114>\n</elem-113>\n</elem-112>\n</elem-111>\n</elem-110>\n</elem-109>\n</elem-108>\n</elem-107>\n</elem-106>\n</elem-105>\n</elem-104>\n</elem-103>\n</elem-102>\n</elem-101>\n</elem-100>\n</elem-99>\n</elem-98>\n</elem-97>\n</elem-96>\n</elem-95>\n</elem-94>\n</elem-93>\n</elem-92>\n</elem-91>\n</elem-90>\n</elem-89>\n</elem-88>\n</elem-87>\n</elem-86>\n</elem-85>\n</elem-84>\n</elem-83>\n</elem-82>\n</elem-81>\n</elem-80>\n</elem-79>\n</elem-78>\n</elem-77>\n</elem-76>\n</elem-75>\n</elem-74>\n</elem-73>\n</elem-72>\n</elem-71>\n</elem-70>\n</elem-69>\n</elem-68>\n</elem-67>\n</elem-66>\n</elem-65>\n</elem-64>\n</elem-63>\n</elem-62>\n</elem-61>\n</elem-60>\n</elem-59>\n</elem-58>\n</elem-57>\n</elem-56>\n</elem-55>\n</elem-54>\n</elem-53>\n</elem-52>\n</elem-51>\n</elem-50>\n</elem-49>\n</elem-48>\n</elem-47>\n</elem-46>\n</elem-45>\n</elem-44>\n</elem-43>\n</elem-42>\n</elem-41>\n</elem-40>\n</elem-39>\n</elem-38>\n</elem-37>\n</elem-36>\n</elem-35>\n</elem-34>\n</elem-33>\n</elem-32>\n</elem-31>\n</elem-30>\n</elem-29>\n</elem-28>\n</elem-27>\n</elem-26>\n</elem-25>\n</elem-24>\n</elem-23>\n</elem-22>\n</elem-21>\n</elem-20>\n</elem-19>\n</elem-18>\n</elem-17>\n</elem-16>\n</elem-15>\n</elem-14>\n</elem-13>\n</elem-12>\n</elem-11>\n</elem-10>\n</elem-9>\n</elem-8>\n</elem-7>\n</elem-6>\n</elem-5>\n</elem-4>\n</elem-3>\n</elem-2>\n</elem-1>\n</outer>"
  },
  {
    "path": "test/System.Web.Razor.Test/Text/BufferingTextReaderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Web.Razor.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Text\n{\n    public class BufferingTextReaderTest : LookaheadTextReaderTestBase\n    {\n        private const string TestString = \"abcdefg\";\n\n        private class DisposeTestMockTextReader : TextReader\n        {\n            public bool Disposed { get; set; }\n\n            protected override void Dispose(bool disposing)\n            {\n                base.Dispose(disposing);\n                Disposed = true;\n            }\n        }\n\n        protected override LookaheadTextReader CreateReader(string testString)\n        {\n            return new BufferingTextReader(new StringReader(testString));\n        }\n\n        [Fact]\n        public void ConstructorRequiresNonNullSourceReader()\n        {\n            Assert.ThrowsArgumentNull(() => new BufferingTextReader(null), \"source\");\n        }\n\n        [Fact]\n        public void PeekReturnsCurrentCharacterWithoutAdvancingPosition()\n        {\n            RunPeekTest(\"abc\", peekAt: 2);\n        }\n\n        [Fact]\n        public void PeekReturnsNegativeOneAtEndOfSourceReader()\n        {\n            RunPeekTest(\"abc\", peekAt: 3);\n        }\n\n        [Fact]\n        public void ReadReturnsCurrentCharacterAndAdvancesToNextCharacter()\n        {\n            RunReadTest(\"abc\", readAt: 2);\n        }\n\n        [Fact]\n        public void EndingLookaheadReturnsReaderToPreviousLocation()\n        {\n            RunLookaheadTest(\"abcdefg\", \"abcb\",\n                             Read,\n                             Lookahead(\n                                 Read,\n                                 Read),\n                             Read);\n        }\n\n        [Fact]\n        public void MultipleLookaheadsCanBePerformed()\n        {\n            RunLookaheadTest(\"abcdefg\", \"abcbcdc\",\n                             Read,\n                             Lookahead(\n                                 Read,\n                                 Read),\n                             Read,\n                             Lookahead(\n                                 Read,\n                                 Read),\n                             Read);\n        }\n\n        [Fact]\n        public void LookaheadsCanBeNested()\n        {\n            RunLookaheadTest(\"abcdefg\", \"abcdefebc\",\n                             Read, // Appended: \"a\" Reader: \"bcdefg\"\n                             Lookahead( // Reader: \"bcdefg\"\n                                 Read, // Appended: \"b\" Reader: \"cdefg\";\n                                 Read, // Appended: \"c\" Reader: \"defg\";\n                                 Read, // Appended: \"d\" Reader: \"efg\";\n                                 Lookahead( // Reader: \"efg\"\n                                     Read, // Appended: \"e\" Reader: \"fg\";\n                                     Read // Appended: \"f\" Reader: \"g\";\n                                     ), // Reader: \"efg\"\n                                 Read // Appended: \"e\" Reader: \"fg\";\n                                 ), // Reader: \"bcdefg\"\n                             Read, // Appended: \"b\" Reader: \"cdefg\";\n                             Read); // Appended: \"c\" Reader: \"defg\";\n        }\n\n        [Fact]\n        public void SourceLocationIsZeroWhenInitialized()\n        {\n            RunSourceLocationTest(\"abcdefg\", SourceLocation.Zero, checkAt: 0);\n        }\n\n        [Fact]\n        public void CharacterAndAbsoluteIndicesIncreaseAsCharactersAreRead()\n        {\n            RunSourceLocationTest(\"abcdefg\", new SourceLocation(4, 0, 4), checkAt: 4);\n        }\n\n        [Fact]\n        public void CharacterAndAbsoluteIndicesIncreaseAsSlashRInTwoCharacterNewlineIsRead()\n        {\n            RunSourceLocationTest(\"f\\r\\nb\", new SourceLocation(2, 0, 2), checkAt: 2);\n        }\n\n        [Fact]\n        public void CharacterIndexResetsToZeroAndLineIndexIncrementsWhenSlashNInTwoCharacterNewlineIsRead()\n        {\n            RunSourceLocationTest(\"f\\r\\nb\", new SourceLocation(3, 1, 0), checkAt: 3);\n        }\n\n        [Fact]\n        public void CharacterIndexResetsToZeroAndLineIndexIncrementsWhenSlashRInSingleCharacterNewlineIsRead()\n        {\n            RunSourceLocationTest(\"f\\rb\", new SourceLocation(2, 1, 0), checkAt: 2);\n        }\n\n        [Fact]\n        public void CharacterIndexResetsToZeroAndLineIndexIncrementsWhenSlashNInSingleCharacterNewlineIsRead()\n        {\n            RunSourceLocationTest(\"f\\nb\", new SourceLocation(2, 1, 0), checkAt: 2);\n        }\n\n        [Fact]\n        public void EndingLookaheadResetsRawCharacterAndLineIndexToValuesWhenLookaheadBegan()\n        {\n            RunEndLookaheadUpdatesSourceLocationTest();\n        }\n\n        [Fact]\n        public void OnceBufferingBeginsReadsCanContinuePastEndOfBuffer()\n        {\n            RunLookaheadTest(\"abcdefg\", \"abcbcdefg\",\n                             Read,\n                             Lookahead(Read(2)),\n                             Read(2),\n                             ReadToEnd);\n        }\n\n        [Fact]\n        public void DisposeDisposesSourceReader()\n        {\n            RunDisposeTest(r => r.Dispose());\n        }\n\n        [Fact]\n        public void CloseDisposesSourceReader()\n        {\n            RunDisposeTest(r => r.Close());\n        }\n\n        [Fact]\n        public void ReadWithBufferSupportsLookahead()\n        {\n            RunBufferReadTest((reader, buffer, index, count) => reader.Read(buffer, index, count));\n        }\n\n        [Fact]\n        public void ReadBlockSupportsLookahead()\n        {\n            RunBufferReadTest((reader, buffer, index, count) => reader.ReadBlock(buffer, index, count));\n        }\n\n        [Fact]\n        public void ReadLineSupportsLookahead()\n        {\n            RunReadUntilTest(r => r.ReadLine(), expectedRaw: 8, expectedChar: 0, expectedLine: 2);\n        }\n\n        [Fact]\n        public void ReadToEndSupportsLookahead()\n        {\n            RunReadUntilTest(r => r.ReadToEnd(), expectedRaw: 11, expectedChar: 3, expectedLine: 2);\n        }\n\n        [Fact]\n        public void ReadLineMaintainsCorrectCharacterPosition()\n        {\n            RunSourceLocationTest(\"abc\\r\\ndef\", new SourceLocation(5, 1, 0), r => r.ReadLine());\n        }\n\n        [Fact]\n        public void ReadToEndWorksAsInNormalTextReader()\n        {\n            RunReadToEndTest();\n        }\n\n        [Fact]\n        public void CancelBacktrackStopsNextEndLookaheadFromBacktracking()\n        {\n            RunLookaheadTest(\"abcdefg\", \"abcdefg\",\n                             Lookahead(\n                                 Read(2),\n                                 CancelBacktrack\n                                 ),\n                             ReadToEnd);\n        }\n\n        [Fact]\n        public void CancelBacktrackThrowsInvalidOperationExceptionIfCalledOutsideOfLookahead()\n        {\n            RunCancelBacktrackOutsideLookaheadTest();\n        }\n\n        [Fact]\n        public void CancelBacktrackOnlyCancelsBacktrackingForInnermostNestedLookahead()\n        {\n            RunLookaheadTest(\"abcdefg\", \"abcdabcdefg\",\n                             Lookahead(\n                                 Read(2),\n                                 Lookahead(\n                                     Read,\n                                     CancelBacktrack\n                                     ),\n                                 Read\n                                 ),\n                             ReadToEnd);\n        }\n\n        [Fact]\n        public void BacktrackBufferIsClearedWhenEndReachedAndNoCurrentLookaheads()\n        {\n            // Arrange\n            StringReader source = new StringReader(TestString);\n            BufferingTextReader reader = new BufferingTextReader(source);\n\n            reader.Read(); // Reader: \"bcdefg\"\n            using (reader.BeginLookahead())\n            {\n                reader.Read(); // Reader: \"cdefg\"\n            } // Reader: \"bcdefg\"\n            reader.Read(); // Reader: \"cdefg\"\n            Assert.NotNull(reader.Buffer); // Verify our assumption that the buffer still exists\n\n            // Act\n            reader.Read();\n\n            // Assert\n            Assert.False(reader.Buffering, \"The buffer was not reset when the end was reached\");\n            Assert.Equal(0, reader.Buffer.Length);\n        }\n\n        private static void RunDisposeTest(Action<LookaheadTextReader> triggerAction)\n        {\n            // Arrange\n            DisposeTestMockTextReader source = new DisposeTestMockTextReader();\n            LookaheadTextReader reader = new BufferingTextReader(source);\n\n            // Act\n            triggerAction(reader);\n\n            // Assert\n            Assert.True(source.Disposed);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Text/LineTrackingStringBufferTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Text\n{\n    public class LineTrackingStringBufferTest\n    {\n        [Fact]\n        public void CtorInitializesProperties()\n        {\n            LineTrackingStringBuffer buffer = new LineTrackingStringBuffer();\n            Assert.Equal(0, buffer.Length);\n        }\n\n        [Fact]\n        public void CharAtCorrectlyReturnsLocation()\n        {\n            LineTrackingStringBuffer buffer = new LineTrackingStringBuffer();\n            buffer.Append(\"foo\\rbar\\nbaz\\r\\nbiz\");\n            LineTrackingStringBuffer.CharacterReference chr = buffer.CharAt(14);\n            Assert.Equal('i', chr.Character);\n            Assert.Equal(new SourceLocation(14, 3, 1), chr.Location);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Text/LookaheadTextReaderTestBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Text;\nusing System.Web.Razor.Resources;\nusing System.Web.Razor.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Text\n{\n    public abstract class LookaheadTextReaderTestBase\n    {\n        protected abstract LookaheadTextReader CreateReader(string testString);\n\n        protected void RunPeekTest(string input, int peekAt = 0)\n        {\n            RunPeekOrReadTest(input, peekAt, false);\n        }\n\n        protected void RunReadTest(string input, int readAt = 0)\n        {\n            RunPeekOrReadTest(input, readAt, true);\n        }\n\n        protected void RunSourceLocationTest(string input, SourceLocation expected, int checkAt = 0)\n        {\n            RunSourceLocationTest(input, expected, r => AdvanceReader(checkAt, r));\n        }\n\n        protected void RunSourceLocationTest(string input, SourceLocation expected, Action<LookaheadTextReader> readerAction)\n        {\n            // Arrange\n            LookaheadTextReader reader = CreateReader(input);\n            readerAction(reader);\n\n            // Act\n            SourceLocation actual = reader.CurrentLocation;\n\n            // Assert\n            Assert.Equal(expected, actual);\n        }\n\n        protected void RunEndLookaheadUpdatesSourceLocationTest()\n        {\n            SourceLocation? expectedLocation = null;\n            SourceLocation? actualLocation = null;\n\n            RunLookaheadTest(\"abc\\r\\ndef\\r\\nghi\", null,\n                             Read(6),\n                             CaptureSourceLocation(s => expectedLocation = s),\n                             Lookahead(Read(6)),\n                             CaptureSourceLocation(s => actualLocation = s));\n            // Assert\n            Assert.Equal(expectedLocation.Value.AbsoluteIndex, actualLocation.Value.AbsoluteIndex);\n            Assert.Equal(expectedLocation.Value.CharacterIndex, actualLocation.Value.CharacterIndex);\n            Assert.Equal(expectedLocation.Value.LineIndex, actualLocation.Value.LineIndex);\n        }\n\n        protected void RunReadToEndTest()\n        {\n            // Arrange\n            LookaheadTextReader reader = CreateReader(\"abcdefg\");\n\n            // Act\n            string str = reader.ReadToEnd();\n\n            // Assert\n            Assert.Equal(\"abcdefg\", str);\n        }\n\n        protected void RunCancelBacktrackOutsideLookaheadTest()\n        {\n            // Arrange\n            LookaheadTextReader reader = CreateReader(\"abcdefg\");\n\n            // Act and Assert\n            Assert.Throws<InvalidOperationException>(() => reader.CancelBacktrack(), RazorResources.CancelBacktrack_Must_Be_Called_Within_Lookahead);\n        }\n\n        protected Action<StringBuilder, LookaheadTextReader> CaptureSourceLocation(Action<SourceLocation> capture)\n        {\n            return (_, reader) => { capture(reader.CurrentLocation); };\n        }\n\n        protected Action<StringBuilder, LookaheadTextReader> Read(int count)\n        {\n            return (builder, reader) =>\n            {\n                for (int i = 0; i < count; i++)\n                {\n                    Read(builder, reader);\n                }\n            };\n        }\n\n        protected void Read(StringBuilder builder, LookaheadTextReader reader)\n        {\n            builder.Append((char)reader.Read());\n        }\n\n        protected void ReadToEnd(StringBuilder builder, LookaheadTextReader reader)\n        {\n            builder.Append(reader.ReadToEnd());\n        }\n\n        protected void CancelBacktrack(StringBuilder builder, LookaheadTextReader reader)\n        {\n            reader.CancelBacktrack();\n        }\n\n        protected Action<StringBuilder, LookaheadTextReader> Lookahead(params Action<StringBuilder, LookaheadTextReader>[] readerCommands)\n        {\n            return (builder, reader) =>\n            {\n                using (reader.BeginLookahead())\n                {\n                    RunAll(readerCommands, builder, reader);\n                }\n            };\n        }\n\n        protected void RunLookaheadTest(string input, string expected, params Action<StringBuilder, LookaheadTextReader>[] readerCommands)\n        {\n            // Arrange\n            StringBuilder builder = new StringBuilder();\n            using (LookaheadTextReader reader = CreateReader(input))\n            {\n                RunAll(readerCommands, builder, reader);\n            }\n\n            if (expected != null)\n            {\n                Assert.Equal(expected, builder.ToString());\n            }\n        }\n\n        protected void RunReadUntilTest(Func<LookaheadTextReader, string> readMethod, int expectedRaw, int expectedChar, int expectedLine)\n        {\n            // Arrange\n            LookaheadTextReader reader = CreateReader(\"a\\r\\nbcd\\r\\nefg\");\n\n            reader.Read(); // Reader: \"\\r\\nbcd\\r\\nefg\"\n            reader.Read(); // Reader: \"\\nbcd\\r\\nefg\"\n            reader.Read(); // Reader: \"bcd\\r\\nefg\"\n\n            // Act\n            string read = null;\n            SourceLocation actualLocation;\n            using (reader.BeginLookahead())\n            {\n                read = readMethod(reader);\n                actualLocation = reader.CurrentLocation;\n            }\n\n            // Assert\n            Assert.Equal(3, reader.CurrentLocation.AbsoluteIndex);\n            Assert.Equal(0, reader.CurrentLocation.CharacterIndex);\n            Assert.Equal(1, reader.CurrentLocation.LineIndex);\n            Assert.Equal(expectedRaw, actualLocation.AbsoluteIndex);\n            Assert.Equal(expectedChar, actualLocation.CharacterIndex);\n            Assert.Equal(expectedLine, actualLocation.LineIndex);\n            Assert.Equal('b', reader.Peek());\n            Assert.Equal(read, readMethod(reader));\n        }\n\n        protected void RunBufferReadTest(Func<LookaheadTextReader, char[], int, int, int> readMethod)\n        {\n            // Arrange\n            LookaheadTextReader reader = CreateReader(\"abcdefg\");\n\n            reader.Read(); // Reader: \"bcdefg\"\n\n            // Act\n            char[] buffer = new char[4];\n            int read = -1;\n            SourceLocation actualLocation;\n            using (reader.BeginLookahead())\n            {\n                read = readMethod(reader, buffer, 0, 4);\n                actualLocation = reader.CurrentLocation;\n            }\n\n            // Assert\n            Assert.Equal(\"bcde\", new String(buffer));\n            Assert.Equal(4, read);\n            Assert.Equal(5, actualLocation.AbsoluteIndex);\n            Assert.Equal(5, actualLocation.CharacterIndex);\n            Assert.Equal(0, actualLocation.LineIndex);\n            Assert.Equal(1, reader.CurrentLocation.CharacterIndex);\n            Assert.Equal(0, reader.CurrentLocation.LineIndex);\n            Assert.Equal('b', reader.Peek());\n        }\n\n        private static void RunAll(Action<StringBuilder, LookaheadTextReader>[] readerCommands, StringBuilder builder, LookaheadTextReader reader)\n        {\n            foreach (Action<StringBuilder, LookaheadTextReader> readerCommand in readerCommands)\n            {\n                readerCommand(builder, reader);\n            }\n        }\n\n        private void RunPeekOrReadTest(string input, int offset, bool isRead)\n        {\n            using (LookaheadTextReader reader = CreateReader(input))\n            {\n                AdvanceReader(offset, reader);\n\n                // Act\n                int? actual = null;\n                if (isRead)\n                {\n                    actual = reader.Read();\n                }\n                else\n                {\n                    actual = reader.Peek();\n                }\n\n                Assert.NotNull(actual);\n\n                // Asserts\n                AssertReaderValueCorrect(actual.Value, input, offset, \"Peek\");\n\n                if (isRead)\n                {\n                    AssertReaderValueCorrect(reader.Peek(), input, offset + 1, \"Read\");\n                }\n                else\n                {\n                    Assert.Equal(actual, reader.Peek());\n                }\n            }\n        }\n\n        private static void AdvanceReader(int offset, LookaheadTextReader reader)\n        {\n            for (int i = 0; i < offset; i++)\n            {\n                reader.Read();\n            }\n        }\n\n        private void AssertReaderValueCorrect(int actual, string input, int expectedOffset, string methodName)\n        {\n            if (expectedOffset < input.Length)\n            {\n                Assert.Equal(input[expectedOffset], actual);\n            }\n            else\n            {\n                Assert.Equal(-1, actual);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Text/SourceLocationTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Text\n{\n    public class SourceLocationTest\n    {\n        [Fact]\n        public void ConstructorWithLineAndCharacterIndexSetsAssociatedProperties()\n        {\n            // Act\n            SourceLocation loc = new SourceLocation(0, 42, 24);\n\n            // Assert\n            Assert.Equal(0, loc.AbsoluteIndex);\n            Assert.Equal(42, loc.LineIndex);\n            Assert.Equal(24, loc.CharacterIndex);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Text/SourceLocationTrackerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Text\n{\n    public class SourceLocationTrackerTest\n    {\n        private static readonly SourceLocation TestStartLocation = new SourceLocation(10, 42, 45);\n\n        [Fact]\n        public void ConstructorSetsCurrentLocationToZero()\n        {\n            Assert.Equal(SourceLocation.Zero, new SourceLocationTracker().CurrentLocation);\n        }\n\n        [Fact]\n        public void ConstructorWithSourceLocationSetsCurrentLocationToSpecifiedValue()\n        {\n            SourceLocation loc = new SourceLocation(10, 42, 4);\n            Assert.Equal(loc, new SourceLocationTracker(loc).CurrentLocation);\n        }\n\n        [Fact]\n        public void UpdateLocationAdvancesCorrectlyForMultiLineString()\n        {\n            // Arrange\n            SourceLocationTracker tracker = new SourceLocationTracker(TestStartLocation);\n\n            // Act\n            tracker.UpdateLocation(\"foo\\nbar\\rbaz\\r\\nbox\");\n\n            // Assert\n            Assert.Equal(26, tracker.CurrentLocation.AbsoluteIndex);\n            Assert.Equal(45, tracker.CurrentLocation.LineIndex);\n            Assert.Equal(3, tracker.CurrentLocation.CharacterIndex);\n        }\n\n        [Fact]\n        public void UpdateLocationAdvancesAbsoluteIndexOnNonNewlineCharacter()\n        {\n            // Arrange\n            SourceLocationTracker tracker = new SourceLocationTracker(TestStartLocation);\n\n            // Act\n            tracker.UpdateLocation('f', 'o');\n\n            // Assert\n            Assert.Equal(11, tracker.CurrentLocation.AbsoluteIndex);\n        }\n\n        [Fact]\n        public void UpdateLocationAdvancesCharacterIndexOnNonNewlineCharacter()\n        {\n            // Arrange\n            SourceLocationTracker tracker = new SourceLocationTracker(TestStartLocation);\n\n            // Act\n            tracker.UpdateLocation('f', 'o');\n\n            // Assert\n            Assert.Equal(46, tracker.CurrentLocation.CharacterIndex);\n        }\n\n        [Fact]\n        public void UpdateLocationDoesNotAdvanceLineIndexOnNonNewlineCharacter()\n        {\n            // Arrange\n            SourceLocationTracker tracker = new SourceLocationTracker(TestStartLocation);\n\n            // Act\n            tracker.UpdateLocation('f', 'o');\n\n            // Assert\n            Assert.Equal(42, tracker.CurrentLocation.LineIndex);\n        }\n\n        [Fact]\n        public void UpdateLocationAdvancesLineIndexOnSlashN()\n        {\n            // Arrange\n            SourceLocationTracker tracker = new SourceLocationTracker(TestStartLocation);\n\n            // Act\n            tracker.UpdateLocation('\\n', 'o');\n\n            // Assert\n            Assert.Equal(43, tracker.CurrentLocation.LineIndex);\n        }\n\n        [Fact]\n        public void UpdateLocationAdvancesAbsoluteIndexOnSlashN()\n        {\n            // Arrange\n            SourceLocationTracker tracker = new SourceLocationTracker(TestStartLocation);\n\n            // Act\n            tracker.UpdateLocation('\\n', 'o');\n\n            // Assert\n            Assert.Equal(11, tracker.CurrentLocation.AbsoluteIndex);\n        }\n\n        [Fact]\n        public void UpdateLocationResetsCharacterIndexOnSlashN()\n        {\n            // Arrange\n            SourceLocationTracker tracker = new SourceLocationTracker(TestStartLocation);\n\n            // Act\n            tracker.UpdateLocation('\\n', 'o');\n\n            // Assert\n            Assert.Equal(0, tracker.CurrentLocation.CharacterIndex);\n        }\n\n        [Fact]\n        public void UpdateLocationAdvancesLineIndexOnSlashRFollowedByNonNewlineCharacter()\n        {\n            // Arrange\n            SourceLocationTracker tracker = new SourceLocationTracker(TestStartLocation);\n\n            // Act\n            tracker.UpdateLocation('\\r', 'o');\n\n            // Assert\n            Assert.Equal(43, tracker.CurrentLocation.LineIndex);\n        }\n\n        [Fact]\n        public void UpdateLocationAdvancesAbsoluteIndexOnSlashRFollowedByNonNewlineCharacter()\n        {\n            // Arrange\n            SourceLocationTracker tracker = new SourceLocationTracker(TestStartLocation);\n\n            // Act\n            tracker.UpdateLocation('\\r', 'o');\n\n            // Assert\n            Assert.Equal(11, tracker.CurrentLocation.AbsoluteIndex);\n        }\n\n        [Fact]\n        public void UpdateLocationResetsCharacterIndexOnSlashRFollowedByNonNewlineCharacter()\n        {\n            // Arrange\n            SourceLocationTracker tracker = new SourceLocationTracker(TestStartLocation);\n\n            // Act\n            tracker.UpdateLocation('\\r', 'o');\n\n            // Assert\n            Assert.Equal(0, tracker.CurrentLocation.CharacterIndex);\n        }\n\n        [Fact]\n        public void UpdateLocationDoesNotAdvanceLineIndexOnSlashRFollowedBySlashN()\n        {\n            // Arrange\n            SourceLocationTracker tracker = new SourceLocationTracker(TestStartLocation);\n\n            // Act\n            tracker.UpdateLocation('\\r', '\\n');\n\n            // Assert\n            Assert.Equal(42, tracker.CurrentLocation.LineIndex);\n        }\n\n        [Fact]\n        public void UpdateLocationAdvancesAbsoluteIndexOnSlashRFollowedBySlashN()\n        {\n            // Arrange\n            SourceLocationTracker tracker = new SourceLocationTracker(TestStartLocation);\n\n            // Act\n            tracker.UpdateLocation('\\r', '\\n');\n\n            // Assert\n            Assert.Equal(11, tracker.CurrentLocation.AbsoluteIndex);\n        }\n\n        [Fact]\n        public void UpdateLocationAdvancesCharacterIndexOnSlashRFollowedBySlashN()\n        {\n            // Arrange\n            SourceLocationTracker tracker = new SourceLocationTracker(TestStartLocation);\n\n            // Act\n            tracker.UpdateLocation('\\r', '\\n');\n\n            // Assert\n            Assert.Equal(46, tracker.CurrentLocation.CharacterIndex);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Text/TextBufferReaderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Text;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Text\n{\n    public class TextBufferReaderTest : LookaheadTextReaderTestBase\n    {\n        protected override LookaheadTextReader CreateReader(string testString)\n        {\n            return new TextBufferReader(new StringTextBuffer(testString));\n        }\n\n        [Fact]\n        public void ConstructorRequiresNonNullTextBuffer()\n        {\n            Assert.ThrowsArgumentNull(() => new TextBufferReader(null), \"buffer\");\n        }\n\n        [Fact]\n        public void PeekReturnsCurrentCharacterWithoutAdvancingPosition()\n        {\n            RunPeekTest(\"abc\", peekAt: 2);\n        }\n\n        [Fact]\n        public void PeekReturnsNegativeOneAtEndOfSourceReader()\n        {\n            RunPeekTest(\"abc\", peekAt: 3);\n        }\n\n        [Fact]\n        public void ReadReturnsCurrentCharacterAndAdvancesToNextCharacter()\n        {\n            RunReadTest(\"abc\", readAt: 2);\n        }\n\n        [Fact]\n        public void EndingLookaheadReturnsReaderToPreviousLocation()\n        {\n            RunLookaheadTest(\"abcdefg\", \"abcb\",\n                             Read,\n                             Lookahead(\n                                 Read,\n                                 Read),\n                             Read);\n        }\n\n        [Fact]\n        public void MultipleLookaheadsCanBePerformed()\n        {\n            RunLookaheadTest(\"abcdefg\", \"abcbcdc\",\n                             Read,\n                             Lookahead(\n                                 Read,\n                                 Read),\n                             Read,\n                             Lookahead(\n                                 Read,\n                                 Read),\n                             Read);\n        }\n\n        [Fact]\n        public void LookaheadsCanBeNested()\n        {\n            RunLookaheadTest(\"abcdefg\", \"abcdefebc\",\n                             Read, // Appended: \"a\" Reader: \"bcdefg\"\n                             Lookahead( // Reader: \"bcdefg\"\n                                 Read, // Appended: \"b\" Reader: \"cdefg\";\n                                 Read, // Appended: \"c\" Reader: \"defg\";\n                                 Read, // Appended: \"d\" Reader: \"efg\";\n                                 Lookahead( // Reader: \"efg\"\n                                     Read, // Appended: \"e\" Reader: \"fg\";\n                                     Read // Appended: \"f\" Reader: \"g\";\n                                     ), // Reader: \"efg\"\n                                 Read // Appended: \"e\" Reader: \"fg\";\n                                 ), // Reader: \"bcdefg\"\n                             Read, // Appended: \"b\" Reader: \"cdefg\";\n                             Read); // Appended: \"c\" Reader: \"defg\";\n        }\n\n        [Fact]\n        public void SourceLocationIsZeroWhenInitialized()\n        {\n            RunSourceLocationTest(\"abcdefg\", SourceLocation.Zero, checkAt: 0);\n        }\n\n        [Fact]\n        public void CharacterAndAbsoluteIndicesIncreaseAsCharactersAreRead()\n        {\n            RunSourceLocationTest(\"abcdefg\", new SourceLocation(4, 0, 4), checkAt: 4);\n        }\n\n        [Fact]\n        public void CharacterAndAbsoluteIndicesIncreaseAsSlashRInTwoCharacterNewlineIsRead()\n        {\n            RunSourceLocationTest(\"f\\r\\nb\", new SourceLocation(2, 0, 2), checkAt: 2);\n        }\n\n        [Fact]\n        public void CharacterIndexResetsToZeroAndLineIndexIncrementsWhenSlashNInTwoCharacterNewlineIsRead()\n        {\n            RunSourceLocationTest(\"f\\r\\nb\", new SourceLocation(3, 1, 0), checkAt: 3);\n        }\n\n        [Fact]\n        public void CharacterIndexResetsToZeroAndLineIndexIncrementsWhenSlashRInSingleCharacterNewlineIsRead()\n        {\n            RunSourceLocationTest(\"f\\rb\", new SourceLocation(2, 1, 0), checkAt: 2);\n        }\n\n        [Fact]\n        public void CharacterIndexResetsToZeroAndLineIndexIncrementsWhenSlashNInSingleCharacterNewlineIsRead()\n        {\n            RunSourceLocationTest(\"f\\nb\", new SourceLocation(2, 1, 0), checkAt: 2);\n        }\n\n        [Fact]\n        public void EndingLookaheadResetsRawCharacterAndLineIndexToValuesWhenLookaheadBegan()\n        {\n            RunEndLookaheadUpdatesSourceLocationTest();\n        }\n\n        [Fact]\n        public void OnceBufferingBeginsReadsCanContinuePastEndOfBuffer()\n        {\n            RunLookaheadTest(\"abcdefg\", \"abcbcdefg\",\n                             Read,\n                             Lookahead(Read(2)),\n                             Read(2),\n                             ReadToEnd);\n        }\n\n        [Fact]\n        public void DisposeDisposesSourceReader()\n        {\n            RunDisposeTest(r => r.Dispose());\n        }\n\n        [Fact]\n        public void CloseDisposesSourceReader()\n        {\n            RunDisposeTest(r => r.Close());\n        }\n\n        [Fact]\n        public void ReadWithBufferSupportsLookahead()\n        {\n            RunBufferReadTest((reader, buffer, index, count) => reader.Read(buffer, index, count));\n        }\n\n        [Fact]\n        public void ReadBlockSupportsLookahead()\n        {\n            RunBufferReadTest((reader, buffer, index, count) => reader.ReadBlock(buffer, index, count));\n        }\n\n        [Fact]\n        public void ReadLineSupportsLookahead()\n        {\n            RunReadUntilTest(r => r.ReadLine(), expectedRaw: 8, expectedChar: 0, expectedLine: 2);\n        }\n\n        [Fact]\n        public void ReadToEndSupportsLookahead()\n        {\n            RunReadUntilTest(r => r.ReadToEnd(), expectedRaw: 11, expectedChar: 3, expectedLine: 2);\n        }\n\n        [Fact]\n        public void ReadLineMaintainsCorrectCharacterPosition()\n        {\n            RunSourceLocationTest(\"abc\\r\\ndef\", new SourceLocation(5, 1, 0), r => r.ReadLine());\n        }\n\n        [Fact]\n        public void ReadToEndWorksAsInNormalTextReader()\n        {\n            RunReadToEndTest();\n        }\n\n        [Fact]\n        public void CancelBacktrackStopsNextEndLookaheadFromBacktracking()\n        {\n            RunLookaheadTest(\"abcdefg\", \"abcdefg\",\n                             Lookahead(\n                                 Read(2),\n                                 CancelBacktrack\n                                 ),\n                             ReadToEnd);\n        }\n\n        [Fact]\n        public void CancelBacktrackThrowsInvalidOperationExceptionIfCalledOutsideOfLookahead()\n        {\n            RunCancelBacktrackOutsideLookaheadTest();\n        }\n\n        [Fact]\n        public void CancelBacktrackOnlyCancelsBacktrackingForInnermostNestedLookahead()\n        {\n            RunLookaheadTest(\"abcdefg\", \"abcdabcdefg\",\n                             Lookahead(\n                                 Read(2),\n                                 Lookahead(\n                                     Read,\n                                     CancelBacktrack\n                                     ),\n                                 Read\n                                 ),\n                             ReadToEnd);\n        }\n\n        private static void RunDisposeTest(Action<LookaheadTextReader> triggerAction)\n        {\n            // Arrange\n            StringTextBuffer source = new StringTextBuffer(\"abcdefg\");\n            LookaheadTextReader reader = new TextBufferReader(source);\n\n            // Act\n            triggerAction(reader);\n\n            // Assert\n            Assert.True(source.Disposed);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Text/TextChangeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Text;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Razor.Test.Text\n{\n    public class TextChangeTest\n    {\n        [Fact]\n        public void ConstructorRequiresNonNegativeOldPosition()\n        {\n            Assert.ThrowsArgumentOutOfRange(() => new TextChange(-1, 0, new Mock<ITextBuffer>().Object, 0, 0, new Mock<ITextBuffer>().Object), \"oldPosition\", \"Value must be greater than or equal to 0.\");\n        }\n\n        [Fact]\n        public void ConstructorRequiresNonNegativeNewPosition()\n        {\n            Assert.ThrowsArgumentOutOfRange(() => new TextChange(0, 0, new Mock<ITextBuffer>().Object, -1, 0, new Mock<ITextBuffer>().Object), \"newPosition\", \"Value must be greater than or equal to 0.\");\n        }\n\n        [Fact]\n        public void ConstructorRequiresNonNegativeOldLength()\n        {\n            Assert.ThrowsArgumentOutOfRange(() => new TextChange(0, -1, new Mock<ITextBuffer>().Object, 0, 0, new Mock<ITextBuffer>().Object), \"oldLength\", \"Value must be greater than or equal to 0.\");\n        }\n\n        [Fact]\n        public void ConstructorRequiresNonNegativeNewLength()\n        {\n            Assert.ThrowsArgumentOutOfRange(() => new TextChange(0, 0, new Mock<ITextBuffer>().Object, 0, -1, new Mock<ITextBuffer>().Object), \"newLength\", \"Value must be greater than or equal to 0.\");\n        }\n\n        [Fact]\n        public void ConstructorRequiresNonNullOldBuffer()\n        {\n            Assert.ThrowsArgumentNull(() => new TextChange(0, 0, null, 0, 0, new Mock<ITextBuffer>().Object), \"oldBuffer\");\n        }\n\n        [Fact]\n        public void ConstructorRequiresNonNullNewBuffer()\n        {\n            Assert.ThrowsArgumentNull(() => new TextChange(0, 0, new Mock<ITextBuffer>().Object, 0, 0, null), \"newBuffer\");\n        }\n\n        [Fact]\n        public void ConstructorInitializesProperties()\n        {\n            // Act\n            ITextBuffer oldBuffer = new Mock<ITextBuffer>().Object;\n            ITextBuffer newBuffer = new Mock<ITextBuffer>().Object;\n            TextChange change = new TextChange(42, 24, oldBuffer, 1337, newBuffer);\n\n            // Assert\n            Assert.Equal(42, change.OldPosition);\n            Assert.Equal(24, change.OldLength);\n            Assert.Equal(1337, change.NewLength);\n            Assert.Same(newBuffer, change.NewBuffer);\n            Assert.Same(oldBuffer, change.OldBuffer);\n        }\n\n        [Fact]\n        public void TestIsDelete()\n        {\n            // Arrange \n            ITextBuffer oldBuffer = new Mock<ITextBuffer>().Object;\n            ITextBuffer newBuffer = new Mock<ITextBuffer>().Object;\n            TextChange change = new TextChange(0, 1, oldBuffer, 0, newBuffer);\n\n            // Assert\n            Assert.True(change.IsDelete);\n        }\n\n        [Fact]\n        public void TestDeleteCreatesTheRightSizeChange()\n        {\n            // Arrange \n            ITextBuffer oldBuffer = new Mock<ITextBuffer>().Object;\n            ITextBuffer newBuffer = new Mock<ITextBuffer>().Object;\n            TextChange change = new TextChange(0, 1, oldBuffer, 0, newBuffer);\n\n            // Assert\n            Assert.Equal(0, change.NewText.Length);\n            Assert.Equal(1, change.OldText.Length);\n        }\n\n        [Fact]\n        public void TestIsInsert()\n        {\n            // Arrange \n            ITextBuffer oldBuffer = new Mock<ITextBuffer>().Object;\n            ITextBuffer newBuffer = new Mock<ITextBuffer>().Object;\n            TextChange change = new TextChange(0, 0, oldBuffer, 35, newBuffer);\n\n            // Assert\n            Assert.True(change.IsInsert);\n        }\n\n        [Fact]\n        public void TestInsertCreateTheRightSizeChange()\n        {\n            // Arrange \n            ITextBuffer oldBuffer = new Mock<ITextBuffer>().Object;\n            ITextBuffer newBuffer = new Mock<ITextBuffer>().Object;\n            TextChange change = new TextChange(0, 0, oldBuffer, 1, newBuffer);\n\n            // Assert\n            Assert.Equal(1, change.NewText.Length);\n            Assert.Equal(0, change.OldText.Length);\n        }\n\n        [Fact]\n        public void TestIsReplace()\n        {\n            // Arrange \n            ITextBuffer oldBuffer = new Mock<ITextBuffer>().Object;\n            ITextBuffer newBuffer = new Mock<ITextBuffer>().Object;\n            TextChange change = new TextChange(0, 5, oldBuffer, 10, newBuffer);\n\n            // Assert\n            Assert.True(change.IsReplace);\n        }\n\n        [Fact]\n        public void ReplaceCreatesTheRightSizeChange()\n        {\n            // Arrange \n            ITextBuffer oldBuffer = new Mock<ITextBuffer>().Object;\n            ITextBuffer newBuffer = new Mock<ITextBuffer>().Object;\n            TextChange change = new TextChange(0, 5, oldBuffer, 10, newBuffer);\n\n            // Assert\n            Assert.Equal(10, change.NewText.Length);\n            Assert.Equal(5, change.OldText.Length);\n        }\n\n        [Fact]\n        public void ReplaceCreatesTheRightSizeChange1()\n        {\n            // Arrange \n            ITextBuffer oldBuffer = new Mock<ITextBuffer>().Object;\n            ITextBuffer newBuffer = new Mock<ITextBuffer>().Object;\n            TextChange change = new TextChange(0, 5, oldBuffer, 1, newBuffer);\n\n            // Assert\n            Assert.Equal(1, change.NewText.Length);\n            Assert.Equal(5, change.OldText.Length);\n        }\n\n        [Fact]\n        public void OldTextReturnsOldSpanFromOldBuffer()\n        {\n            // Arrange\n            var newBuffer = new StringTextBuffer(\"test\");\n            var oldBuffer = new StringTextBuffer(\"text\");\n            var textChange = new TextChange(2, 1, oldBuffer, 1, newBuffer);\n\n            // Act\n            string text = textChange.OldText;\n\n            // Assert\n            Assert.Equal(\"x\", text);\n        }\n\n        [Fact]\n        public void OldTextReturnsOldSpanFromOldBuffer2()\n        {\n            // Arrange\n            var newBuffer = new StringTextBuffer(\"test\");\n            var oldBuffer = new StringTextBuffer(\"text\");\n            var textChange = new TextChange(2, 2, oldBuffer, 1, newBuffer);\n\n            // Act\n            string text = textChange.OldText;\n\n            // Assert\n            Assert.Equal(\"xt\", text);\n        }\n\n        [Fact]\n        public void NewTextWithInsertReturnsChangedTextFromBuffer()\n        {\n            // Arrange\n            var newBuffer = new StringTextBuffer(\"test\");\n            var oldBuffer = new StringTextBuffer(\"\");\n            var textChange = new TextChange(0, 0, oldBuffer, 3, newBuffer);\n\n            // Act\n            string text = textChange.NewText;\n            string oldText = textChange.OldText;\n\n            // Assert\n            Assert.Equal(\"tes\", text);\n            Assert.Equal(\"\", oldText);\n        }\n\n        [Fact]\n        public void NewTextWithDeleteReturnsEmptyString()\n        {\n            // Arrange\n            var newBuffer = new StringTextBuffer(\"test\");\n            var oldBuffer = new StringTextBuffer(\"\");\n            var textChange = new TextChange(1, 1, oldBuffer, 0, newBuffer);\n\n            // Act\n            string text = textChange.NewText;\n\n            // Assert\n            Assert.Equal(String.Empty, text);\n        }\n\n        [Fact]\n        public void NewTextWithReplaceReturnsChangedTextFromBuffer()\n        {\n            // Arrange\n            var newBuffer = new StringTextBuffer(\"test\");\n            var oldBuffer = new StringTextBuffer(\"tebb\");\n            var textChange = new TextChange(2, 2, oldBuffer, 1, newBuffer);\n\n            // Act\n            string newText = textChange.NewText;\n            string oldText = textChange.OldText;\n\n            // Assert\n            Assert.Equal(\"s\", newText);\n            Assert.Equal(\"bb\", oldText);\n        }\n\n        [Fact]\n        public void ApplyChangeWithInsertedTextReturnsNewContentWithChangeApplied()\n        {\n            // Arrange\n            var newBuffer = new StringTextBuffer(\"test\");\n            var oldBuffer = new StringTextBuffer(\"\");\n            var textChange = new TextChange(0, 0, oldBuffer, 3, newBuffer);\n\n            // Act\n            string text = textChange.ApplyChange(\"abcd\", 0);\n\n            // Assert\n            Assert.Equal(\"tesabcd\", text);\n        }\n\n        [Fact]\n        public void ApplyChangeWithRemovedTextReturnsNewContentWithChangeApplied()\n        {\n            // Arrange\n            var newBuffer = new StringTextBuffer(\"abcdefg\");\n            var oldBuffer = new StringTextBuffer(\"\");\n            var textChange = new TextChange(1, 1, oldBuffer, 0, newBuffer);\n\n            // Act\n            string text = textChange.ApplyChange(\"abcdefg\", 1);\n\n            // Assert\n            Assert.Equal(\"bcdefg\", text);\n        }\n\n        [Fact]\n        public void ApplyChangeWithReplacedTextReturnsNewContentWithChangeApplied()\n        {\n            // Arrange\n            var newBuffer = new StringTextBuffer(\"abcdefg\");\n            var oldBuffer = new StringTextBuffer(\"\");\n            var textChange = new TextChange(1, 1, oldBuffer, 2, newBuffer);\n\n            // Act\n            string text = textChange.ApplyChange(\"abcdefg\", 1);\n\n            // Assert\n            Assert.Equal(\"bcbcdefg\", text);\n        }\n\n        [Fact]\n        public void NormalizeFixesUpIntelliSenseStyleReplacements()\n        {\n            // Arrange\n            var newBuffer = new StringTextBuffer(\"Date.\");\n            var oldBuffer = new StringTextBuffer(\"Date\");\n            var original = new TextChange(0, 4, oldBuffer, 5, newBuffer);\n\n            // Act\n            TextChange normalized = original.Normalize();\n\n            // Assert\n            Assert.Equal(new TextChange(4, 0, oldBuffer, 1, newBuffer), normalized);\n        }\n\n        [Fact]\n        public void NormalizeDoesntAffectChangesWithoutCommonPrefixes()\n        {\n            // Arrange\n            var newBuffer = new StringTextBuffer(\"DateTime.\");\n            var oldBuffer = new StringTextBuffer(\"Date.\");\n            var original = new TextChange(0, 5, oldBuffer, 9, newBuffer);\n\n            // Act\n            TextChange normalized = original.Normalize();\n\n            // Assert\n            Assert.Equal(original, normalized);\n        }\n\n        [Fact]\n        public void NormalizeDoesntAffectShrinkingReplacements()\n        {\n            // Arrange\n            var newBuffer = new StringTextBuffer(\"D\");\n            var oldBuffer = new StringTextBuffer(\"DateTime\");\n            var original = new TextChange(0, 8, oldBuffer, 1, newBuffer);\n\n            // Act\n            TextChange normalized = original.Normalize();\n\n            // Assert\n            Assert.Equal(original, normalized);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Text/TextReaderExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Web.Razor.Parser;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Text\n{\n    public class TextReaderExtensionsTest\n    {\n        [Fact]\n        public void ReadUntilWithCharThrowsArgNullIfReaderNull()\n        {\n            Assert.ThrowsArgumentNull(() => TextReaderExtensions.ReadUntil(null, '@'), \"reader\");\n        }\n\n        [Fact]\n        public void ReadUntilInclusiveWithCharThrowsArgNullIfReaderNull()\n        {\n            Assert.ThrowsArgumentNull(() => TextReaderExtensions.ReadUntil(null, '@', inclusive: true), \"reader\");\n        }\n\n        [Fact]\n        public void ReadUntilWithMultipleTerminatorsThrowsArgNullIfReaderNull()\n        {\n            Assert.ThrowsArgumentNull(() => TextReaderExtensions.ReadUntil(null, '/', '>'), \"reader\");\n        }\n\n        [Fact]\n        public void ReadUntilInclusiveWithMultipleTerminatorsThrowsArgNullIfReaderNull()\n        {\n            // NOTE: Using named parameters would be difficult here, hence the inline comment\n            Assert.ThrowsArgumentNull(() => TextReaderExtensions.ReadUntil(null, /* inclusive */ true, '/', '>'), \"reader\");\n        }\n\n        [Fact]\n        public void ReadUntilWithPredicateThrowsArgNullIfReaderNull()\n        {\n            Assert.ThrowsArgumentNull(() => TextReaderExtensions.ReadUntil(null, c => true), \"reader\");\n        }\n\n        [Fact]\n        public void ReadUntilInclusiveWithPredicateThrowsArgNullIfReaderNull()\n        {\n            Assert.ThrowsArgumentNull(() => TextReaderExtensions.ReadUntil(null, c => true, inclusive: true), \"reader\");\n        }\n\n        [Fact]\n        public void ReadUntilWithPredicateThrowsArgExceptionIfPredicateNull()\n        {\n            Assert.ThrowsArgumentNull(() => TextReaderExtensions.ReadUntil(new StringReader(\"Foo\"), (Predicate<char>)null), \"condition\");\n        }\n\n        [Fact]\n        public void ReadUntilInclusiveWithPredicateThrowsArgExceptionIfPredicateNull()\n        {\n            Assert.ThrowsArgumentNull(() => TextReaderExtensions.ReadUntil(new StringReader(\"Foo\"), (Predicate<char>)null, inclusive: true), \"condition\");\n        }\n\n        [Fact]\n        public void ReadWhileWithPredicateThrowsArgNullIfReaderNull()\n        {\n            Assert.ThrowsArgumentNull(() => TextReaderExtensions.ReadWhile(null, c => true), \"reader\");\n        }\n\n        [Fact]\n        public void ReadWhileInclusiveWithPredicateThrowsArgNullIfReaderNull()\n        {\n            Assert.ThrowsArgumentNull(() => TextReaderExtensions.ReadWhile(null, c => true, inclusive: true), \"reader\");\n        }\n\n        [Fact]\n        public void ReadWhileWithPredicateThrowsArgNullIfPredicateNull()\n        {\n            Assert.ThrowsArgumentNull(() => TextReaderExtensions.ReadWhile(new StringReader(\"Foo\"), (Predicate<char>)null), \"condition\");\n        }\n\n        [Fact]\n        public void ReadWhileInclusiveWithPredicateThrowsArgNullIfPredicateNull()\n        {\n            Assert.ThrowsArgumentNull(() => TextReaderExtensions.ReadWhile(new StringReader(\"Foo\"), (Predicate<char>)null, inclusive: true), \"condition\");\n        }\n\n        [Fact]\n        public void ReadUntilWithCharReadsAllTextUpToSpecifiedCharacterButNotPast()\n        {\n            RunReaderTest(\"foo bar baz @biz\", \"foo bar baz \", '@', r => r.ReadUntil('@'));\n        }\n\n        [Fact]\n        public void ReadUntilWithCharWithInclusiveFlagReadsAllTextUpToSpecifiedCharacterButNotPastIfInclusiveFalse()\n        {\n            RunReaderTest(\"foo bar baz @biz\", \"foo bar baz \", '@', r => r.ReadUntil('@', inclusive: false));\n        }\n\n        [Fact]\n        public void ReadUntilWithCharWithInclusiveFlagReadsAllTextUpToAndIncludingSpecifiedCharacterIfInclusiveTrue()\n        {\n            RunReaderTest(\"foo bar baz @biz\", \"foo bar baz @\", 'b', r => r.ReadUntil('@', inclusive: true));\n        }\n\n        [Fact]\n        public void ReadUntilWithCharReadsToEndIfSpecifiedCharacterNotFound()\n        {\n            RunReaderTest(\"foo bar baz\", \"foo bar baz\", -1, r => r.ReadUntil('@'));\n        }\n\n        [Fact]\n        public void ReadUntilWithMultipleTerminatorsReadsUntilAnyTerminatorIsFound()\n        {\n            RunReaderTest(\"<bar/>\", \"<bar\", '/', r => r.ReadUntil('/', '>'));\n        }\n\n        [Fact]\n        public void ReadUntilWithMultipleTerminatorsHonorsInclusiveFlagWhenFalse()\n        {\n            // NOTE: Using named parameters would be difficult here, hence the inline comment\n            RunReaderTest(\"<bar/>\", \"<bar\", '/', r => r.ReadUntil(/* inclusive */ false, '/', '>'));\n        }\n\n        [Fact]\n        public void ReadUntilWithMultipleTerminatorsHonorsInclusiveFlagWhenTrue()\n        {\n            // NOTE: Using named parameters would be difficult here, hence the inline comment\n            RunReaderTest(\"<bar/>\", \"<bar/\", '>', r => r.ReadUntil(/* inclusive */ true, '/', '>'));\n        }\n\n        [Fact]\n        public void ReadUntilWithPredicateStopsWhenPredicateIsTrue()\n        {\n            RunReaderTest(\"foo bar baz 0 zoop zork zoink\", \"foo bar baz \", '0', r => r.ReadUntil(c => Char.IsDigit(c)));\n        }\n\n        [Fact]\n        public void ReadUntilWithPredicateHonorsInclusiveFlagWhenFalse()\n        {\n            RunReaderTest(\"foo bar baz 0 zoop zork zoink\", \"foo bar baz \", '0', r => r.ReadUntil(c => Char.IsDigit(c), inclusive: false));\n        }\n\n        [Fact]\n        public void ReadUntilWithPredicateHonorsInclusiveFlagWhenTrue()\n        {\n            RunReaderTest(\"foo bar baz 0 zoop zork zoink\", \"foo bar baz 0\", ' ', r => r.ReadUntil(c => Char.IsDigit(c), inclusive: true));\n        }\n\n        [Fact]\n        public void ReadWhileWithPredicateStopsWhenPredicateIsFalse()\n        {\n            RunReaderTest(\"012345a67890\", \"012345\", 'a', r => r.ReadWhile(c => Char.IsDigit(c)));\n        }\n\n        [Fact]\n        public void ReadWhileWithPredicateHonorsInclusiveFlagWhenFalse()\n        {\n            RunReaderTest(\"012345a67890\", \"012345\", 'a', r => r.ReadWhile(c => Char.IsDigit(c), inclusive: false));\n        }\n\n        [Fact]\n        public void ReadWhileWithPredicateHonorsInclusiveFlagWhenTrue()\n        {\n            RunReaderTest(\"012345a67890\", \"012345a\", '6', r => r.ReadWhile(c => Char.IsDigit(c), inclusive: true));\n        }\n\n        private static void RunReaderTest(string testString, string expectedOutput, int expectedPeek, Func<TextReader, string> action)\n        {\n            // Arrange\n            StringReader reader = new StringReader(testString);\n\n            // Act\n            string read = action(reader);\n\n            // Assert\n            Assert.Equal(expectedOutput, read);\n\n            if (expectedPeek == -1)\n            {\n                Assert.True(reader.Peek() == -1, \"Expected that the reader would be positioned at the end of the input stream\");\n            }\n            else\n            {\n                Assert.Equal((char)expectedPeek, (char)reader.Peek());\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Tokenizer/CSharpTokenizerCommentTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Tokenizer\n{\n    public class CSharpTokenizerCommentTest : CSharpTokenizerTestBase\n    {\n        [Fact]\n        public void Next_Ignores_Star_At_EOF_In_RazorComment()\n        {\n            TestTokenizer(\"@* Foo * Bar * Baz *\",\n                          new CSharpSymbol(0, 0, 0, \"@\", CSharpSymbolType.RazorCommentTransition),\n                          new CSharpSymbol(1, 0, 1, \"*\", CSharpSymbolType.RazorCommentStar),\n                          new CSharpSymbol(2, 0, 2, \" Foo * Bar * Baz *\", CSharpSymbolType.RazorComment));\n        }\n\n        [Fact]\n        public void Next_Ignores_Star_Without_Trailing_At()\n        {\n            TestTokenizer(\"@* Foo * Bar * Baz *@\",\n                          new CSharpSymbol(0, 0, 0, \"@\", CSharpSymbolType.RazorCommentTransition),\n                          new CSharpSymbol(1, 0, 1, \"*\", CSharpSymbolType.RazorCommentStar),\n                          new CSharpSymbol(2, 0, 2, \" Foo * Bar * Baz \", CSharpSymbolType.RazorComment),\n                          new CSharpSymbol(19, 0, 19, \"*\", CSharpSymbolType.RazorCommentStar),\n                          new CSharpSymbol(20, 0, 20, \"@\", CSharpSymbolType.RazorCommentTransition));\n        }\n\n        [Fact]\n        public void Next_Returns_RazorComment_Token_For_Entire_Razor_Comment()\n        {\n            TestTokenizer(\"@* Foo Bar Baz *@\",\n                          new CSharpSymbol(0, 0, 0, \"@\", CSharpSymbolType.RazorCommentTransition),\n                          new CSharpSymbol(1, 0, 1, \"*\", CSharpSymbolType.RazorCommentStar),\n                          new CSharpSymbol(2, 0, 2, \" Foo Bar Baz \", CSharpSymbolType.RazorComment),\n                          new CSharpSymbol(15, 0, 15, \"*\", CSharpSymbolType.RazorCommentStar),\n                          new CSharpSymbol(16, 0, 16, \"@\", CSharpSymbolType.RazorCommentTransition));\n        }\n\n        [Fact]\n        public void Next_Returns_Comment_Token_For_Entire_Single_Line_Comment()\n        {\n            TestTokenizer(\"// Foo Bar Baz\", new CSharpSymbol(0, 0, 0, \"// Foo Bar Baz\", CSharpSymbolType.Comment));\n        }\n\n        [Fact]\n        public void Single_Line_Comment_Is_Terminated_By_Newline()\n        {\n            TestTokenizer(\"// Foo Bar Baz\\na\", new CSharpSymbol(0, 0, 0, \"// Foo Bar Baz\", CSharpSymbolType.Comment), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Multi_Line_Comment_In_Single_Line_Comment_Has_No_Effect()\n        {\n            TestTokenizer(\"// Foo/*Bar*/ Baz\\na\", new CSharpSymbol(0, 0, 0, \"// Foo/*Bar*/ Baz\", CSharpSymbolType.Comment), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Next_Returns_Comment_Token_For_Entire_Multi_Line_Comment()\n        {\n            TestTokenizer(\"/* Foo\\nBar\\nBaz */\", new CSharpSymbol(0, 0, 0, \"/* Foo\\nBar\\nBaz */\", CSharpSymbolType.Comment));\n        }\n\n        [Fact]\n        public void Multi_Line_Comment_Is_Terminated_By_End_Sequence()\n        {\n            TestTokenizer(\"/* Foo\\nBar\\nBaz */a\", new CSharpSymbol(0, 0, 0, \"/* Foo\\nBar\\nBaz */\", CSharpSymbolType.Comment), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Unterminated_Multi_Line_Comment_Captures_To_EOF()\n        {\n            TestTokenizer(\"/* Foo\\nBar\\nBaz\", new CSharpSymbol(0, 0, 0, \"/* Foo\\nBar\\nBaz\", CSharpSymbolType.Comment), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Nested_Multi_Line_Comments_Terminated_At_First_End_Sequence()\n        {\n            TestTokenizer(\"/* Foo/*\\nBar\\nBaz*/ */\", new CSharpSymbol(0, 0, 0, \"/* Foo/*\\nBar\\nBaz*/\", CSharpSymbolType.Comment), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Nested_Multi_Line_Comments_Terminated_At_Full_End_Sequence()\n        {\n            TestTokenizer(\"/* Foo\\nBar\\nBaz* */\", new CSharpSymbol(0, 0, 0, \"/* Foo\\nBar\\nBaz* */\", CSharpSymbolType.Comment), IgnoreRemaining);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Tokenizer/CSharpTokenizerIdentifierTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Tokenizer\n{\n    public class CSharpTokenizerIdentifierTest : CSharpTokenizerTestBase\n    {\n        [Fact]\n        public void Simple_Identifier_Is_Recognized()\n        {\n            TestTokenizer(\"foo\", new CSharpSymbol(0, 0, 0, \"foo\", CSharpSymbolType.Identifier));\n        }\n\n        [Fact]\n        public void Identifier_Starting_With_Underscore_Is_Recognized()\n        {\n            TestTokenizer(\"_foo\", new CSharpSymbol(0, 0, 0, \"_foo\", CSharpSymbolType.Identifier));\n        }\n\n        [Fact]\n        public void Identifier_Can_Contain_Digits()\n        {\n            TestTokenizer(\"foo4\", new CSharpSymbol(0, 0, 0, \"foo4\", CSharpSymbolType.Identifier));\n        }\n\n        [Fact]\n        public void Identifier_Can_Start_With_Titlecase_Letter()\n        {\n            TestTokenizer(\"ῼfoo\", new CSharpSymbol(0, 0, 0, \"ῼfoo\", CSharpSymbolType.Identifier));\n        }\n\n        [Fact]\n        public void Identifier_Can_Start_With_Letter_Modifier()\n        {\n            TestTokenizer(\"ᵊfoo\", new CSharpSymbol(0, 0, 0, \"ᵊfoo\", CSharpSymbolType.Identifier));\n        }\n\n        [Fact]\n        public void Identifier_Can_Start_With_Other_Letter()\n        {\n            TestTokenizer(\"ƻfoo\", new CSharpSymbol(0, 0, 0, \"ƻfoo\", CSharpSymbolType.Identifier));\n        }\n\n        [Fact]\n        public void Identifier_Can_Start_With_Number_Letter()\n        {\n            TestTokenizer(\"Ⅽool\", new CSharpSymbol(0, 0, 0, \"Ⅽool\", CSharpSymbolType.Identifier));\n        }\n\n        [Fact]\n        public void Identifier_Can_Contain_Non_Spacing_Mark()\n        {\n            TestTokenizer(\"foo\\u0300\", new CSharpSymbol(0, 0, 0, \"foo\\u0300\", CSharpSymbolType.Identifier));\n        }\n\n        [Fact]\n        public void Identifier_Can_Contain_Spacing_Combining_Mark()\n        {\n            TestTokenizer(\"fooः\", new CSharpSymbol(0, 0, 0, \"fooः\", CSharpSymbolType.Identifier));\n        }\n\n        [Fact]\n        public void Identifier_Can_Contain_Non_English_Digit()\n        {\n            TestTokenizer(\"foo١\", new CSharpSymbol(0, 0, 0, \"foo١\", CSharpSymbolType.Identifier));\n        }\n\n        [Fact]\n        public void Identifier_Can_Contain_Connector_Punctuation()\n        {\n            TestTokenizer(\"foo‿bar\", new CSharpSymbol(0, 0, 0, \"foo‿bar\", CSharpSymbolType.Identifier));\n        }\n\n        [Fact]\n        public void Identifier_Can_Contain_Format_Character()\n        {\n            TestTokenizer(\"foo؃bar\", new CSharpSymbol(0, 0, 0, \"foo؃bar\", CSharpSymbolType.Identifier));\n        }\n\n        [Fact]\n        public void Keywords_Are_Recognized_As_Keyword_Tokens()\n        {\n            TestKeyword(\"abstract\", CSharpKeyword.Abstract);\n            TestKeyword(\"byte\", CSharpKeyword.Byte);\n            TestKeyword(\"class\", CSharpKeyword.Class);\n            TestKeyword(\"delegate\", CSharpKeyword.Delegate);\n            TestKeyword(\"event\", CSharpKeyword.Event);\n            TestKeyword(\"fixed\", CSharpKeyword.Fixed);\n            TestKeyword(\"if\", CSharpKeyword.If);\n            TestKeyword(\"internal\", CSharpKeyword.Internal);\n            TestKeyword(\"new\", CSharpKeyword.New);\n            TestKeyword(\"override\", CSharpKeyword.Override);\n            TestKeyword(\"readonly\", CSharpKeyword.Readonly);\n            TestKeyword(\"short\", CSharpKeyword.Short);\n            TestKeyword(\"struct\", CSharpKeyword.Struct);\n            TestKeyword(\"try\", CSharpKeyword.Try);\n            TestKeyword(\"unsafe\", CSharpKeyword.Unsafe);\n            TestKeyword(\"volatile\", CSharpKeyword.Volatile);\n            TestKeyword(\"as\", CSharpKeyword.As);\n            TestKeyword(\"do\", CSharpKeyword.Do);\n            TestKeyword(\"is\", CSharpKeyword.Is);\n            TestKeyword(\"params\", CSharpKeyword.Params);\n            TestKeyword(\"ref\", CSharpKeyword.Ref);\n            TestKeyword(\"switch\", CSharpKeyword.Switch);\n            TestKeyword(\"ushort\", CSharpKeyword.Ushort);\n            TestKeyword(\"while\", CSharpKeyword.While);\n            TestKeyword(\"case\", CSharpKeyword.Case);\n            TestKeyword(\"const\", CSharpKeyword.Const);\n            TestKeyword(\"explicit\", CSharpKeyword.Explicit);\n            TestKeyword(\"float\", CSharpKeyword.Float);\n            TestKeyword(\"null\", CSharpKeyword.Null);\n            TestKeyword(\"sizeof\", CSharpKeyword.Sizeof);\n            TestKeyword(\"typeof\", CSharpKeyword.Typeof);\n            TestKeyword(\"implicit\", CSharpKeyword.Implicit);\n            TestKeyword(\"private\", CSharpKeyword.Private);\n            TestKeyword(\"this\", CSharpKeyword.This);\n            TestKeyword(\"using\", CSharpKeyword.Using);\n            TestKeyword(\"extern\", CSharpKeyword.Extern);\n            TestKeyword(\"return\", CSharpKeyword.Return);\n            TestKeyword(\"stackalloc\", CSharpKeyword.Stackalloc);\n            TestKeyword(\"uint\", CSharpKeyword.Uint);\n            TestKeyword(\"base\", CSharpKeyword.Base);\n            TestKeyword(\"catch\", CSharpKeyword.Catch);\n            TestKeyword(\"continue\", CSharpKeyword.Continue);\n            TestKeyword(\"double\", CSharpKeyword.Double);\n            TestKeyword(\"for\", CSharpKeyword.For);\n            TestKeyword(\"in\", CSharpKeyword.In);\n            TestKeyword(\"lock\", CSharpKeyword.Lock);\n            TestKeyword(\"object\", CSharpKeyword.Object);\n            TestKeyword(\"protected\", CSharpKeyword.Protected);\n            TestKeyword(\"static\", CSharpKeyword.Static);\n            TestKeyword(\"false\", CSharpKeyword.False);\n            TestKeyword(\"public\", CSharpKeyword.Public);\n            TestKeyword(\"sbyte\", CSharpKeyword.Sbyte);\n            TestKeyword(\"throw\", CSharpKeyword.Throw);\n            TestKeyword(\"virtual\", CSharpKeyword.Virtual);\n            TestKeyword(\"decimal\", CSharpKeyword.Decimal);\n            TestKeyword(\"else\", CSharpKeyword.Else);\n            TestKeyword(\"operator\", CSharpKeyword.Operator);\n            TestKeyword(\"string\", CSharpKeyword.String);\n            TestKeyword(\"ulong\", CSharpKeyword.Ulong);\n            TestKeyword(\"bool\", CSharpKeyword.Bool);\n            TestKeyword(\"char\", CSharpKeyword.Char);\n            TestKeyword(\"default\", CSharpKeyword.Default);\n            TestKeyword(\"foreach\", CSharpKeyword.Foreach);\n            TestKeyword(\"long\", CSharpKeyword.Long);\n            TestKeyword(\"void\", CSharpKeyword.Void);\n            TestKeyword(\"enum\", CSharpKeyword.Enum);\n            TestKeyword(\"finally\", CSharpKeyword.Finally);\n            TestKeyword(\"int\", CSharpKeyword.Int);\n            TestKeyword(\"out\", CSharpKeyword.Out);\n            TestKeyword(\"sealed\", CSharpKeyword.Sealed);\n            TestKeyword(\"true\", CSharpKeyword.True);\n            TestKeyword(\"goto\", CSharpKeyword.Goto);\n            TestKeyword(\"unchecked\", CSharpKeyword.Unchecked);\n            TestKeyword(\"interface\", CSharpKeyword.Interface);\n            TestKeyword(\"break\", CSharpKeyword.Break);\n            TestKeyword(\"checked\", CSharpKeyword.Checked);\n            TestKeyword(\"namespace\", CSharpKeyword.Namespace);\n        }\n\n        private void TestKeyword(string keyword, CSharpKeyword keywordType)\n        {\n            TestTokenizer(keyword, new CSharpSymbol(0, 0, 0, keyword, CSharpSymbolType.Keyword) { Keyword = keywordType });\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Tokenizer/CSharpTokenizerLiteralTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Tokenizer\n{\n    public class CSharpTokenizerLiteralTest : CSharpTokenizerTestBase\n    {\n        [Fact]\n        public void Simple_Integer_Literal_Is_Recognized()\n        {\n            TestSingleToken(\"01189998819991197253\", CSharpSymbolType.IntegerLiteral);\n        }\n\n        [Fact]\n        public void Integer_Type_Suffix_Is_Recognized()\n        {\n            TestSingleToken(\"42U\", CSharpSymbolType.IntegerLiteral);\n            TestSingleToken(\"42u\", CSharpSymbolType.IntegerLiteral);\n\n            TestSingleToken(\"42L\", CSharpSymbolType.IntegerLiteral);\n            TestSingleToken(\"42l\", CSharpSymbolType.IntegerLiteral);\n\n            TestSingleToken(\"42UL\", CSharpSymbolType.IntegerLiteral);\n            TestSingleToken(\"42Ul\", CSharpSymbolType.IntegerLiteral);\n\n            TestSingleToken(\"42uL\", CSharpSymbolType.IntegerLiteral);\n            TestSingleToken(\"42ul\", CSharpSymbolType.IntegerLiteral);\n\n            TestSingleToken(\"42LU\", CSharpSymbolType.IntegerLiteral);\n            TestSingleToken(\"42Lu\", CSharpSymbolType.IntegerLiteral);\n\n            TestSingleToken(\"42lU\", CSharpSymbolType.IntegerLiteral);\n            TestSingleToken(\"42lu\", CSharpSymbolType.IntegerLiteral);\n        }\n\n        [Fact]\n        public void Trailing_Letter_Is_Not_Part_Of_Integer_Literal_If_Not_Type_Sufix()\n        {\n            TestTokenizer(\"42a\", new CSharpSymbol(0, 0, 0, \"42\", CSharpSymbolType.IntegerLiteral), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Simple_Hex_Literal_Is_Recognized()\n        {\n            TestSingleToken(\"0x0123456789ABCDEF\", CSharpSymbolType.IntegerLiteral);\n        }\n\n        [Fact]\n        public void Integer_Type_Suffix_Is_Recognized_In_Hex_Literal()\n        {\n            TestSingleToken(\"0xDEADBEEFU\", CSharpSymbolType.IntegerLiteral);\n            TestSingleToken(\"0xDEADBEEFu\", CSharpSymbolType.IntegerLiteral);\n\n            TestSingleToken(\"0xDEADBEEFL\", CSharpSymbolType.IntegerLiteral);\n            TestSingleToken(\"0xDEADBEEFl\", CSharpSymbolType.IntegerLiteral);\n\n            TestSingleToken(\"0xDEADBEEFUL\", CSharpSymbolType.IntegerLiteral);\n            TestSingleToken(\"0xDEADBEEFUl\", CSharpSymbolType.IntegerLiteral);\n\n            TestSingleToken(\"0xDEADBEEFuL\", CSharpSymbolType.IntegerLiteral);\n            TestSingleToken(\"0xDEADBEEFul\", CSharpSymbolType.IntegerLiteral);\n\n            TestSingleToken(\"0xDEADBEEFLU\", CSharpSymbolType.IntegerLiteral);\n            TestSingleToken(\"0xDEADBEEFLu\", CSharpSymbolType.IntegerLiteral);\n\n            TestSingleToken(\"0xDEADBEEFlU\", CSharpSymbolType.IntegerLiteral);\n            TestSingleToken(\"0xDEADBEEFlu\", CSharpSymbolType.IntegerLiteral);\n        }\n\n        [Fact]\n        public void Trailing_Letter_Is_Not_Part_Of_Hex_Literal_If_Not_Type_Sufix()\n        {\n            TestTokenizer(\"0xDEADBEEFz\", new CSharpSymbol(0, 0, 0, \"0xDEADBEEF\", CSharpSymbolType.IntegerLiteral), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Dot_Followed_By_Non_Digit_Is_Not_Part_Of_Real_Literal()\n        {\n            TestTokenizer(\"3.a\", new CSharpSymbol(0, 0, 0, \"3\", CSharpSymbolType.IntegerLiteral), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Simple_Real_Literal_Is_Recognized()\n        {\n            TestTokenizer(\"3.14159\", new CSharpSymbol(0, 0, 0, \"3.14159\", CSharpSymbolType.RealLiteral));\n        }\n\n        [Fact]\n        public void Real_Literal_Between_Zero_And_One_Is_Recognized()\n        {\n            TestTokenizer(\".14159\", new CSharpSymbol(0, 0, 0, \".14159\", CSharpSymbolType.RealLiteral));\n        }\n\n        [Fact]\n        public void Integer_With_Real_Type_Suffix_Is_Recognized()\n        {\n            TestSingleToken(\"42F\", CSharpSymbolType.RealLiteral);\n            TestSingleToken(\"42f\", CSharpSymbolType.RealLiteral);\n            TestSingleToken(\"42D\", CSharpSymbolType.RealLiteral);\n            TestSingleToken(\"42d\", CSharpSymbolType.RealLiteral);\n            TestSingleToken(\"42M\", CSharpSymbolType.RealLiteral);\n            TestSingleToken(\"42m\", CSharpSymbolType.RealLiteral);\n        }\n\n        [Fact]\n        public void Integer_With_Exponent_Is_Recognized()\n        {\n            TestSingleToken(\"1e10\", CSharpSymbolType.RealLiteral);\n            TestSingleToken(\"1E10\", CSharpSymbolType.RealLiteral);\n            TestSingleToken(\"1e+10\", CSharpSymbolType.RealLiteral);\n            TestSingleToken(\"1E+10\", CSharpSymbolType.RealLiteral);\n            TestSingleToken(\"1e-10\", CSharpSymbolType.RealLiteral);\n            TestSingleToken(\"1E-10\", CSharpSymbolType.RealLiteral);\n        }\n\n        [Fact]\n        public void Real_Number_With_Type_Suffix_Is_Recognized()\n        {\n            TestSingleToken(\"3.14F\", CSharpSymbolType.RealLiteral);\n            TestSingleToken(\"3.14f\", CSharpSymbolType.RealLiteral);\n            TestSingleToken(\"3.14D\", CSharpSymbolType.RealLiteral);\n            TestSingleToken(\"3.14d\", CSharpSymbolType.RealLiteral);\n            TestSingleToken(\"3.14M\", CSharpSymbolType.RealLiteral);\n            TestSingleToken(\"3.14m\", CSharpSymbolType.RealLiteral);\n        }\n\n        [Fact]\n        public void Real_Number_With_Exponent_Is_Recognized()\n        {\n            TestSingleToken(\"3.14E10\", CSharpSymbolType.RealLiteral);\n            TestSingleToken(\"3.14e10\", CSharpSymbolType.RealLiteral);\n            TestSingleToken(\"3.14E+10\", CSharpSymbolType.RealLiteral);\n            TestSingleToken(\"3.14e+10\", CSharpSymbolType.RealLiteral);\n            TestSingleToken(\"3.14E-10\", CSharpSymbolType.RealLiteral);\n            TestSingleToken(\"3.14e-10\", CSharpSymbolType.RealLiteral);\n        }\n\n        [Fact]\n        public void Real_Number_With_Exponent_And_Type_Suffix_Is_Recognized()\n        {\n            TestSingleToken(\"3.14E+10F\", CSharpSymbolType.RealLiteral);\n        }\n\n        [Fact]\n        public void Single_Character_Literal_Is_Recognized()\n        {\n            TestSingleToken(\"'f'\", CSharpSymbolType.CharacterLiteral);\n        }\n\n        [Fact]\n        public void Multi_Character_Literal_Is_Recognized()\n        {\n            TestSingleToken(\"'foo'\", CSharpSymbolType.CharacterLiteral);\n        }\n\n        [Fact]\n        public void Character_Literal_Is_Terminated_By_EOF_If_Unterminated()\n        {\n            TestSingleToken(\"'foo bar\", CSharpSymbolType.CharacterLiteral);\n        }\n\n        [Fact]\n        public void Character_Literal_Not_Terminated_By_Escaped_Quote()\n        {\n            TestSingleToken(\"'foo\\\\'bar'\", CSharpSymbolType.CharacterLiteral);\n        }\n\n        [Fact]\n        public void Character_Literal_Is_Terminated_By_EOL_If_Unterminated()\n        {\n            TestTokenizer(\"'foo\\n\", new CSharpSymbol(0, 0, 0, \"'foo\", CSharpSymbolType.CharacterLiteral), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Character_Literal_Terminated_By_EOL_Even_When_Last_Char_Is_Slash()\n        {\n            TestTokenizer(\"'foo\\\\\\n\", new CSharpSymbol(0, 0, 0, \"'foo\\\\\", CSharpSymbolType.CharacterLiteral), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Character_Literal_Terminated_By_EOL_Even_When_Last_Char_Is_Slash_And_Followed_By_Stuff()\n        {\n            TestTokenizer(\"'foo\\\\\\nflarg\", new CSharpSymbol(0, 0, 0, \"'foo\\\\\", CSharpSymbolType.CharacterLiteral), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Character_Literal_Terminated_By_CRLF_Even_When_Last_Char_Is_Slash()\n        {\n            TestTokenizer(\"'foo\\\\\\r\\n\", new CSharpSymbol(0, 0, 0, \"'foo\\\\\", CSharpSymbolType.CharacterLiteral), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Character_Literal_Terminated_By_CRLF_Even_When_Last_Char_Is_Slash_And_Followed_By_Stuff()\n        {\n            TestTokenizer(\"'foo\\\\\\r\\nflarg\", new CSharpSymbol(0, 0, 0, \"'foo\\\\\", CSharpSymbolType.CharacterLiteral), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Character_Literal_Allows_Escaped_Escape()\n        {\n            TestTokenizer(\"'foo\\\\\\\\'blah\", new CSharpSymbol(0, 0, 0, \"'foo\\\\\\\\'\", CSharpSymbolType.CharacterLiteral), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void String_Literal_Is_Recognized()\n        {\n            TestSingleToken(\"\\\"foo\\\"\", CSharpSymbolType.StringLiteral);\n        }\n\n        [Fact]\n        public void String_Literal_Is_Terminated_By_EOF_If_Unterminated()\n        {\n            TestSingleToken(\"\\\"foo bar\", CSharpSymbolType.StringLiteral);\n        }\n\n        [Fact]\n        public void String_Literal_Not_Terminated_By_Escaped_Quote()\n        {\n            TestSingleToken(\"\\\"foo\\\\\\\"bar\\\"\", CSharpSymbolType.StringLiteral);\n        }\n\n        [Fact]\n        public void String_Literal_Is_Terminated_By_EOL_If_Unterminated()\n        {\n            TestTokenizer(\"\\\"foo\\n\", new CSharpSymbol(0, 0, 0, \"\\\"foo\", CSharpSymbolType.StringLiteral), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void String_Literal_Terminated_By_EOL_Even_When_Last_Char_Is_Slash()\n        {\n            TestTokenizer(\"\\\"foo\\\\\\n\", new CSharpSymbol(0, 0, 0, \"\\\"foo\\\\\", CSharpSymbolType.StringLiteral), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void String_Literal_Terminated_By_EOL_Even_When_Last_Char_Is_Slash_And_Followed_By_Stuff()\n        {\n            TestTokenizer(\"\\\"foo\\\\\\nflarg\", new CSharpSymbol(0, 0, 0, \"\\\"foo\\\\\", CSharpSymbolType.StringLiteral), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void String_Literal_Terminated_By_CRLF_Even_When_Last_Char_Is_Slash()\n        {\n            TestTokenizer(\"\\\"foo\\\\\\r\\n\", new CSharpSymbol(0, 0, 0, \"\\\"foo\\\\\", CSharpSymbolType.StringLiteral), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void String_Literal_Terminated_By_CRLF_Even_When_Last_Char_Is_Slash_And_Followed_By_Stuff()\n        {\n            TestTokenizer(\"\\\"foo\\\\\\r\\nflarg\", new CSharpSymbol(0, 0, 0, \"\\\"foo\\\\\", CSharpSymbolType.StringLiteral), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void String_Literal_Allows_Escaped_Escape()\n        {\n            TestTokenizer(\"\\\"foo\\\\\\\\\\\"blah\", new CSharpSymbol(0, 0, 0, \"\\\"foo\\\\\\\\\\\"\", CSharpSymbolType.StringLiteral), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Verbatim_String_Literal_Can_Contain_Newlines()\n        {\n            TestSingleToken(\"@\\\"foo\\nbar\\nbaz\\\"\", CSharpSymbolType.StringLiteral);\n        }\n\n        [Fact]\n        public void Verbatim_String_Literal_Not_Terminated_By_Escaped_Double_Quote()\n        {\n            TestSingleToken(\"@\\\"foo\\\"\\\"bar\\\"\", CSharpSymbolType.StringLiteral);\n        }\n\n        [Fact]\n        public void Verbatim_String_Literal_Is_Terminated_By_Slash_Double_Quote()\n        {\n            TestTokenizer(\"@\\\"foo\\\\\\\"bar\\\"\", new CSharpSymbol(0, 0, 0, \"@\\\"foo\\\\\\\"\", CSharpSymbolType.StringLiteral), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Verbatim_String_Literal_Is_Terminated_By_EOF()\n        {\n            TestSingleToken(\"@\\\"foo\", CSharpSymbolType.StringLiteral);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Tokenizer/CSharpTokenizerOperatorsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Tokenizer\n{\n    public class CSharpTokenizerOperatorsTest : CSharpTokenizerTestBase\n    {\n        [Fact]\n        public void LeftBrace_Is_Recognized()\n        {\n            TestSingleToken(\"{\", CSharpSymbolType.LeftBrace);\n        }\n\n        [Fact]\n        public void Plus_Is_Recognized()\n        {\n            TestSingleToken(\"+\", CSharpSymbolType.Plus);\n        }\n\n        [Fact]\n        public void Assign_Is_Recognized()\n        {\n            TestSingleToken(\"=\", CSharpSymbolType.Assign);\n        }\n\n        [Fact]\n        public void Arrow_Is_Recognized()\n        {\n            TestSingleToken(\"->\", CSharpSymbolType.Arrow);\n        }\n\n        [Fact]\n        public void AndAssign_Is_Recognized()\n        {\n            TestSingleToken(\"&=\", CSharpSymbolType.AndAssign);\n        }\n\n        [Fact]\n        public void RightBrace_Is_Recognized()\n        {\n            TestSingleToken(\"}\", CSharpSymbolType.RightBrace);\n        }\n\n        [Fact]\n        public void Minus_Is_Recognized()\n        {\n            TestSingleToken(\"-\", CSharpSymbolType.Minus);\n        }\n\n        [Fact]\n        public void LessThan_Is_Recognized()\n        {\n            TestSingleToken(\"<\", CSharpSymbolType.LessThan);\n        }\n\n        [Fact]\n        public void Equals_Is_Recognized()\n        {\n            TestSingleToken(\"==\", CSharpSymbolType.Equals);\n        }\n\n        [Fact]\n        public void OrAssign_Is_Recognized()\n        {\n            TestSingleToken(\"|=\", CSharpSymbolType.OrAssign);\n        }\n\n        [Fact]\n        public void LeftBracket_Is_Recognized()\n        {\n            TestSingleToken(\"[\", CSharpSymbolType.LeftBracket);\n        }\n\n        [Fact]\n        public void Star_Is_Recognized()\n        {\n            TestSingleToken(\"*\", CSharpSymbolType.Star);\n        }\n\n        [Fact]\n        public void GreaterThan_Is_Recognized()\n        {\n            TestSingleToken(\">\", CSharpSymbolType.GreaterThan);\n        }\n\n        [Fact]\n        public void NotEqual_Is_Recognized()\n        {\n            TestSingleToken(\"!=\", CSharpSymbolType.NotEqual);\n        }\n\n        [Fact]\n        public void XorAssign_Is_Recognized()\n        {\n            TestSingleToken(\"^=\", CSharpSymbolType.XorAssign);\n        }\n\n        [Fact]\n        public void RightBracket_Is_Recognized()\n        {\n            TestSingleToken(\"]\", CSharpSymbolType.RightBracket);\n        }\n\n        [Fact]\n        public void Slash_Is_Recognized()\n        {\n            TestSingleToken(\"/\", CSharpSymbolType.Slash);\n        }\n\n        [Fact]\n        public void QuestionMark_Is_Recognized()\n        {\n            TestSingleToken(\"?\", CSharpSymbolType.QuestionMark);\n        }\n\n        [Fact]\n        public void LessThanEqual_Is_Recognized()\n        {\n            TestSingleToken(\"<=\", CSharpSymbolType.LessThanEqual);\n        }\n\n        [Fact]\n        public void LeftShift_Is_Not_Specially_Recognized()\n        {\n            TestTokenizer(\"<<\",\n                new CSharpSymbol(0, 0, 0, \"<\", CSharpSymbolType.LessThan),\n                new CSharpSymbol(1, 0, 1, \"<\", CSharpSymbolType.LessThan));\n        }\n\n        [Fact]\n        public void LeftParen_Is_Recognized()\n        {\n            TestSingleToken(\"(\", CSharpSymbolType.LeftParenthesis);\n        }\n\n        [Fact]\n        public void Modulo_Is_Recognized()\n        {\n            TestSingleToken(\"%\", CSharpSymbolType.Modulo);\n        }\n\n        [Fact]\n        public void NullCoalesce_Is_Recognized()\n        {\n            TestSingleToken(\"??\", CSharpSymbolType.NullCoalesce);\n        }\n\n        [Fact]\n        public void GreaterThanEqual_Is_Recognized()\n        {\n            TestSingleToken(\">=\", CSharpSymbolType.GreaterThanEqual);\n        }\n\n        [Fact]\n        public void EqualGreaterThan_Is_Recognized()\n        {\n            TestSingleToken(\"=>\", CSharpSymbolType.GreaterThanEqual);\n        }\n\n        [Fact]\n        public void RightParen_Is_Recognized()\n        {\n            TestSingleToken(\")\", CSharpSymbolType.RightParenthesis);\n        }\n\n        [Fact]\n        public void And_Is_Recognized()\n        {\n            TestSingleToken(\"&\", CSharpSymbolType.And);\n        }\n\n        [Fact]\n        public void DoubleColon_Is_Recognized()\n        {\n            TestSingleToken(\"::\", CSharpSymbolType.DoubleColon);\n        }\n\n        [Fact]\n        public void PlusAssign_Is_Recognized()\n        {\n            TestSingleToken(\"+=\", CSharpSymbolType.PlusAssign);\n        }\n\n        [Fact]\n        public void Semicolon_Is_Recognized()\n        {\n            TestSingleToken(\";\", CSharpSymbolType.Semicolon);\n        }\n\n        [Fact]\n        public void Tilde_Is_Recognized()\n        {\n            TestSingleToken(\"~\", CSharpSymbolType.Tilde);\n        }\n\n        [Fact]\n        public void DoubleOr_Is_Recognized()\n        {\n            TestSingleToken(\"||\", CSharpSymbolType.DoubleOr);\n        }\n\n        [Fact]\n        public void ModuloAssign_Is_Recognized()\n        {\n            TestSingleToken(\"%=\", CSharpSymbolType.ModuloAssign);\n        }\n\n        [Fact]\n        public void Colon_Is_Recognized()\n        {\n            TestSingleToken(\":\", CSharpSymbolType.Colon);\n        }\n\n        [Fact]\n        public void Not_Is_Recognized()\n        {\n            TestSingleToken(\"!\", CSharpSymbolType.Not);\n        }\n\n        [Fact]\n        public void DoubleAnd_Is_Recognized()\n        {\n            TestSingleToken(\"&&\", CSharpSymbolType.DoubleAnd);\n        }\n\n        [Fact]\n        public void DivideAssign_Is_Recognized()\n        {\n            TestSingleToken(\"/=\", CSharpSymbolType.DivideAssign);\n        }\n\n        [Fact]\n        public void Comma_Is_Recognized()\n        {\n            TestSingleToken(\",\", CSharpSymbolType.Comma);\n        }\n\n        [Fact]\n        public void Xor_Is_Recognized()\n        {\n            TestSingleToken(\"^\", CSharpSymbolType.Xor);\n        }\n\n        [Fact]\n        public void Decrement_Is_Recognized()\n        {\n            TestSingleToken(\"--\", CSharpSymbolType.Decrement);\n        }\n\n        [Fact]\n        public void MultiplyAssign_Is_Recognized()\n        {\n            TestSingleToken(\"*=\", CSharpSymbolType.MultiplyAssign);\n        }\n\n        [Fact]\n        public void Dot_Is_Recognized()\n        {\n            TestSingleToken(\".\", CSharpSymbolType.Dot);\n        }\n\n        [Fact]\n        public void Or_Is_Recognized()\n        {\n            TestSingleToken(\"|\", CSharpSymbolType.Or);\n        }\n\n        [Fact]\n        public void Increment_Is_Recognized()\n        {\n            TestSingleToken(\"++\", CSharpSymbolType.Increment);\n        }\n\n        [Fact]\n        public void MinusAssign_Is_Recognized()\n        {\n            TestSingleToken(\"-=\", CSharpSymbolType.MinusAssign);\n        }\n\n        [Fact]\n        public void RightShift_Is_Not_Specially_Recognized()\n        {\n            TestTokenizer(\">>\",\n                new CSharpSymbol(0, 0, 0, \">\", CSharpSymbolType.GreaterThan),\n                new CSharpSymbol(1, 0, 1, \">\", CSharpSymbolType.GreaterThan));\n        }\n\n        [Fact]\n        public void Hash_Is_Recognized()\n        {\n            TestSingleToken(\"#\", CSharpSymbolType.Hash);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Tokenizer/CSharpTokenizerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Tokenizer;\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Tokenizer\n{\n    public class CSharpTokenizerTest : CSharpTokenizerTestBase\n    {\n        [Fact]\n        public void Constructor_Throws_ArgNull_If_Null_Source_Provided()\n        {\n            Assert.ThrowsArgumentNull(() => new CSharpTokenizer(null), \"source\");\n        }\n\n        [Fact]\n        public void Next_Returns_Null_When_EOF_Reached()\n        {\n            TestTokenizer(\"\");\n        }\n\n        [Fact]\n        public void Next_Returns_Newline_Token_For_Single_CR()\n        {\n            TestTokenizer(\"\\r\\ra\",\n                          new CSharpSymbol(0, 0, 0, \"\\r\", CSharpSymbolType.NewLine),\n                          new CSharpSymbol(1, 1, 0, \"\\r\", CSharpSymbolType.NewLine),\n                          IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Next_Returns_Newline_Token_For_Single_LF()\n        {\n            TestTokenizer(\"\\n\\na\",\n                          new CSharpSymbol(0, 0, 0, \"\\n\", CSharpSymbolType.NewLine),\n                          new CSharpSymbol(1, 1, 0, \"\\n\", CSharpSymbolType.NewLine),\n                          IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Next_Returns_Newline_Token_For_Single_NEL()\n        {\n            // NEL: Unicode \"Next Line\" U+0085\n            TestTokenizer(\"\\u0085\\u0085a\",\n                          new CSharpSymbol(0, 0, 0, \"\\u0085\", CSharpSymbolType.NewLine),\n                          new CSharpSymbol(1, 1, 0, \"\\u0085\", CSharpSymbolType.NewLine),\n                          IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Next_Returns_Newline_Token_For_Single_Line_Separator()\n        {\n            // Unicode \"Line Separator\" U+2028\n            TestTokenizer(\"\\u2028\\u2028a\",\n                          new CSharpSymbol(0, 0, 0, \"\\u2028\", CSharpSymbolType.NewLine),\n                          new CSharpSymbol(1, 1, 0, \"\\u2028\", CSharpSymbolType.NewLine),\n                          IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Next_Returns_Newline_Token_For_Single_Paragraph_Separator()\n        {\n            // Unicode \"Paragraph Separator\" U+2029\n            TestTokenizer(\"\\u2029\\u2029a\",\n                          new CSharpSymbol(0, 0, 0, \"\\u2029\", CSharpSymbolType.NewLine),\n                          new CSharpSymbol(1, 1, 0, \"\\u2029\", CSharpSymbolType.NewLine),\n                          IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Next_Returns_Single_Newline_Token_For_CRLF()\n        {\n            TestTokenizer(\"\\r\\n\\r\\na\",\n                          new CSharpSymbol(0, 0, 0, \"\\r\\n\", CSharpSymbolType.NewLine),\n                          new CSharpSymbol(2, 1, 0, \"\\r\\n\", CSharpSymbolType.NewLine),\n                          IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Next_Returns_Token_For_Whitespace_Characters()\n        {\n            TestTokenizer(\" \\f\\t\\u000B \\n \",\n                          new CSharpSymbol(0, 0, 0, \" \\f\\t\\u000B \", CSharpSymbolType.WhiteSpace),\n                          new CSharpSymbol(5, 0, 5, \"\\n\", CSharpSymbolType.NewLine),\n                          new CSharpSymbol(6, 1, 0, \" \", CSharpSymbolType.WhiteSpace));\n        }\n\n        [Fact]\n        public void Transition_Is_Recognized()\n        {\n            TestSingleToken(\"@\", CSharpSymbolType.Transition);\n        }\n\n        [Fact]\n        public void Transition_Is_Recognized_As_SingleCharacter()\n        {\n            TestTokenizer(\"@(\",\n                          new CSharpSymbol(0, 0, 0, \"@\", CSharpSymbolType.Transition),\n                          new CSharpSymbol(1, 0, 1, \"(\", CSharpSymbolType.LeftParenthesis));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Tokenizer/CSharpTokenizerTestBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Test.Tokenizer\n{\n    public abstract class CSharpTokenizerTestBase : TokenizerTestBase<CSharpSymbol, CSharpSymbolType>\n    {\n        private static CSharpSymbol _ignoreRemaining = new CSharpSymbol(0, 0, 0, String.Empty, CSharpSymbolType.Unknown);\n\n        protected override CSharpSymbol IgnoreRemaining\n        {\n            get { return _ignoreRemaining; }\n        }\n\n        protected override Tokenizer<CSharpSymbol, CSharpSymbolType> CreateTokenizer(ITextDocument source)\n        {\n            return new CSharpTokenizer(source);\n        }\n\n        protected void TestSingleToken(string text, CSharpSymbolType expectedSymbolType)\n        {\n            TestTokenizer(text, new CSharpSymbol(0, 0, 0, text, expectedSymbolType));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Tokenizer/HtmlTokenizerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Tokenizer;\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Tokenizer\n{\n    public class HtmlTokenizerTest : HtmlTokenizerTestBase\n    {\n        [Fact]\n        public void Constructor_Throws_ArgNull_If_Null_Source_Provided()\n        {\n            Assert.ThrowsArgumentNull(() => new HtmlTokenizer(null), \"source\");\n        }\n\n        [Fact]\n        public void Next_Returns_Null_When_EOF_Reached()\n        {\n            TestTokenizer(\"\");\n        }\n\n        [Fact]\n        public void Text_Is_Recognized()\n        {\n            TestTokenizer(\"foo-9309&smlkmb;::-3029022,.sdkq92384\",\n                          new HtmlSymbol(0, 0, 0, \"foo-9309&smlkmb;::-3029022,.sdkq92384\", HtmlSymbolType.Text));\n        }\n\n        [Fact]\n        public void Whitespace_Is_Recognized()\n        {\n            TestTokenizer(\" \\t\\f \",\n                          new HtmlSymbol(0, 0, 0, \" \\t\\f \", HtmlSymbolType.WhiteSpace));\n        }\n\n        [Fact]\n        public void Newline_Is_Recognized()\n        {\n            TestTokenizer(\"\\n\\r\\r\\n\",\n                          new HtmlSymbol(0, 0, 0, \"\\n\", HtmlSymbolType.NewLine),\n                          new HtmlSymbol(1, 1, 0, \"\\r\", HtmlSymbolType.NewLine),\n                          new HtmlSymbol(2, 2, 0, \"\\r\\n\", HtmlSymbolType.NewLine));\n        }\n\n        [Fact]\n        public void Transition_Is_Not_Recognized_Mid_Text_If_Surrounded_By_Alphanumeric_Characters()\n        {\n            TestSingleToken(\"foo@bar\", HtmlSymbolType.Text);\n        }\n\n        [Fact]\n        public void OpenAngle_Is_Recognized()\n        {\n            TestSingleToken(\"<\", HtmlSymbolType.OpenAngle);\n        }\n\n        [Fact]\n        public void Bang_Is_Recognized()\n        {\n            TestSingleToken(\"!\", HtmlSymbolType.Bang);\n        }\n\n        [Fact]\n        public void Solidus_Is_Recognized()\n        {\n            TestSingleToken(\"/\", HtmlSymbolType.Solidus);\n        }\n\n        [Fact]\n        public void QuestionMark_Is_Recognized()\n        {\n            TestSingleToken(\"?\", HtmlSymbolType.QuestionMark);\n        }\n\n        [Fact]\n        public void LeftBracket_Is_Recognized()\n        {\n            TestSingleToken(\"[\", HtmlSymbolType.LeftBracket);\n        }\n\n        [Fact]\n        public void CloseAngle_Is_Recognized()\n        {\n            TestSingleToken(\">\", HtmlSymbolType.CloseAngle);\n        }\n\n        [Fact]\n        public void RightBracket_Is_Recognized()\n        {\n            TestSingleToken(\"]\", HtmlSymbolType.RightBracket);\n        }\n\n        [Fact]\n        public void Equals_Is_Recognized()\n        {\n            TestSingleToken(\"=\", HtmlSymbolType.Equals);\n        }\n\n        [Fact]\n        public void DoubleQuote_Is_Recognized()\n        {\n            TestSingleToken(\"\\\"\", HtmlSymbolType.DoubleQuote);\n        }\n\n        [Fact]\n        public void SingleQuote_Is_Recognized()\n        {\n            TestSingleToken(\"'\", HtmlSymbolType.SingleQuote);\n        }\n\n        [Fact]\n        public void Transition_Is_Recognized()\n        {\n            TestSingleToken(\"@\", HtmlSymbolType.Transition);\n        }\n\n        [Fact]\n        public void DoubleHyphen_Is_Recognized()\n        {\n            TestSingleToken(\"--\", HtmlSymbolType.DoubleHyphen);\n        }\n\n        [Fact]\n        public void SingleHyphen_Is_Not_Recognized()\n        {\n            TestSingleToken(\"-\", HtmlSymbolType.Text);\n        }\n\n        [Fact]\n        public void SingleHyphen_Mid_Text_Is_Not_Recognized_As_Separate_Token()\n        {\n            TestSingleToken(\"foo-bar\", HtmlSymbolType.Text);\n        }\n\n        [Fact]\n        public void Next_Ignores_Star_At_EOF_In_RazorComment()\n        {\n            TestTokenizer(\"@* Foo * Bar * Baz *\",\n                          new HtmlSymbol(0, 0, 0, \"@\", HtmlSymbolType.RazorCommentTransition),\n                          new HtmlSymbol(1, 0, 1, \"*\", HtmlSymbolType.RazorCommentStar),\n                          new HtmlSymbol(2, 0, 2, \" Foo * Bar * Baz *\", HtmlSymbolType.RazorComment));\n        }\n\n        [Fact]\n        public void Next_Ignores_Star_Without_Trailing_At()\n        {\n            TestTokenizer(\"@* Foo * Bar * Baz *@\",\n                          new HtmlSymbol(0, 0, 0, \"@\", HtmlSymbolType.RazorCommentTransition),\n                          new HtmlSymbol(1, 0, 1, \"*\", HtmlSymbolType.RazorCommentStar),\n                          new HtmlSymbol(2, 0, 2, \" Foo * Bar * Baz \", HtmlSymbolType.RazorComment),\n                          new HtmlSymbol(19, 0, 19, \"*\", HtmlSymbolType.RazorCommentStar),\n                          new HtmlSymbol(20, 0, 20, \"@\", HtmlSymbolType.RazorCommentTransition));\n        }\n\n        [Fact]\n        public void Next_Returns_RazorComment_Token_For_Entire_Razor_Comment()\n        {\n            TestTokenizer(\"@* Foo Bar Baz *@\",\n                          new HtmlSymbol(0, 0, 0, \"@\", HtmlSymbolType.RazorCommentTransition),\n                          new HtmlSymbol(1, 0, 1, \"*\", HtmlSymbolType.RazorCommentStar),\n                          new HtmlSymbol(2, 0, 2, \" Foo Bar Baz \", HtmlSymbolType.RazorComment),\n                          new HtmlSymbol(15, 0, 15, \"*\", HtmlSymbolType.RazorCommentStar),\n                          new HtmlSymbol(16, 0, 16, \"@\", HtmlSymbolType.RazorCommentTransition));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Tokenizer/HtmlTokenizerTestBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Test.Tokenizer\n{\n    public abstract class HtmlTokenizerTestBase : TokenizerTestBase<HtmlSymbol, HtmlSymbolType>\n    {\n        private static HtmlSymbol _ignoreRemaining = new HtmlSymbol(0, 0, 0, String.Empty, HtmlSymbolType.Unknown);\n\n        protected override HtmlSymbol IgnoreRemaining\n        {\n            get { return _ignoreRemaining; }\n        }\n\n        protected override Tokenizer<HtmlSymbol, HtmlSymbolType> CreateTokenizer(ITextDocument source)\n        {\n            return new HtmlTokenizer(source);\n        }\n\n        protected void TestSingleToken(string text, HtmlSymbolType expectedSymbolType)\n        {\n            TestTokenizer(text, new HtmlSymbol(0, 0, 0, text, expectedSymbolType));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Tokenizer/TokenizerLookaheadTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer;\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Tokenizer\n{\n    public class TokenizerLookaheadTest : HtmlTokenizerTestBase\n    {\n        [Fact]\n        public void After_Cancelling_Lookahead_Tokenizer_Returns_Same_Tokens_As_It_Did_Before_Lookahead()\n        {\n            HtmlTokenizer tokenizer = new HtmlTokenizer(new SeekableTextReader(new StringReader(\"<foo>\")));\n            using (tokenizer.Source.BeginLookahead())\n            {\n                Assert.Equal(new HtmlSymbol(0, 0, 0, \"<\", HtmlSymbolType.OpenAngle), tokenizer.NextSymbol());\n                Assert.Equal(new HtmlSymbol(1, 0, 1, \"foo\", HtmlSymbolType.Text), tokenizer.NextSymbol());\n                Assert.Equal(new HtmlSymbol(4, 0, 4, \">\", HtmlSymbolType.CloseAngle), tokenizer.NextSymbol());\n            }\n            Assert.Equal(new HtmlSymbol(0, 0, 0, \"<\", HtmlSymbolType.OpenAngle), tokenizer.NextSymbol());\n            Assert.Equal(new HtmlSymbol(1, 0, 1, \"foo\", HtmlSymbolType.Text), tokenizer.NextSymbol());\n            Assert.Equal(new HtmlSymbol(4, 0, 4, \">\", HtmlSymbolType.CloseAngle), tokenizer.NextSymbol());\n        }\n\n        [Fact]\n        public void After_Accepting_Lookahead_Tokenizer_Returns_Next_Token()\n        {\n            HtmlTokenizer tokenizer = new HtmlTokenizer(new SeekableTextReader(new StringReader(\"<foo>\")));\n            using (LookaheadToken lookahead = tokenizer.Source.BeginLookahead())\n            {\n                Assert.Equal(new HtmlSymbol(0, 0, 0, \"<\", HtmlSymbolType.OpenAngle), tokenizer.NextSymbol());\n                Assert.Equal(new HtmlSymbol(1, 0, 1, \"foo\", HtmlSymbolType.Text), tokenizer.NextSymbol());\n                lookahead.Accept();\n            }\n            Assert.Equal(new HtmlSymbol(4, 0, 4, \">\", HtmlSymbolType.CloseAngle), tokenizer.NextSymbol());\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Tokenizer/TokenizerTestBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics;\nusing System.IO;\nusing System.Text;\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer;\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Tokenizer\n{\n    public abstract class TokenizerTestBase<TSymbol, TSymbolType>\n        where TSymbol : SymbolBase<TSymbolType>\n    {\n        protected abstract TSymbol IgnoreRemaining { get; }\n        protected abstract Tokenizer<TSymbol, TSymbolType> CreateTokenizer(ITextDocument source);\n\n        protected void TestTokenizer(string input, params TSymbol[] expectedSymbols)\n        {\n            // Arrange\n            bool success = true;\n            StringBuilder output = new StringBuilder();\n            using (StringReader reader = new StringReader(input))\n            {\n                using (SeekableTextReader source = new SeekableTextReader(reader))\n                {\n                    Tokenizer<TSymbol, TSymbolType> tokenizer = CreateTokenizer(source);\n                    int counter = 0;\n                    TSymbol current = null;\n                    while ((current = tokenizer.NextSymbol()) != null)\n                    {\n                        if (counter >= expectedSymbols.Length)\n                        {\n                            output.AppendLine(String.Format(\"F: Expected: << Nothing >>; Actual: {0}\", current));\n                            success = false;\n                        }\n                        else if (ReferenceEquals(expectedSymbols[counter], IgnoreRemaining))\n                        {\n                            output.AppendLine(String.Format(\"P: Ignored {0}\", current));\n                        }\n                        else\n                        {\n                            if (!Equals(expectedSymbols[counter], current))\n                            {\n                                output.AppendLine(String.Format(\"F: Expected: {0}; Actual: {1}\", expectedSymbols[counter], current));\n                                success = false;\n                            }\n                            else\n                            {\n                                output.AppendLine(String.Format(\"P: Expected: {0}\", expectedSymbols[counter]));\n                            }\n                            counter++;\n                        }\n                    }\n                    if (counter < expectedSymbols.Length && !ReferenceEquals(expectedSymbols[counter], IgnoreRemaining))\n                    {\n                        success = false;\n                        for (; counter < expectedSymbols.Length; counter++)\n                        {\n                            output.AppendLine(String.Format(\"F: Expected: {0}; Actual: << None >>\", expectedSymbols[counter]));\n                        }\n                    }\n                }\n            }\n            Assert.True(success, \"\\r\\n\" + output.ToString());\n            WriteTraceLine(output.Replace(\"{\", \"{{\").Replace(\"}\", \"}}\").ToString());\n        }\n\n        [Conditional(\"PARSER_TRACE\")]\n        private static void WriteTraceLine(string format, params object[] args)\n        {\n            Trace.WriteLine(String.Format(format, args));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Tokenizer/VBTokenizerCommentTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Tokenizer\n{\n    public class VBTokenizerCommentTest : VBTokenizerTestBase\n    {\n        [Fact]\n        public void Next_Ignores_Star_At_EOF_In_RazorComment()\n        {\n            TestTokenizer(\"@* Foo * Bar * Baz *\",\n                          new VBSymbol(0, 0, 0, \"@\", VBSymbolType.RazorCommentTransition),\n                          new VBSymbol(1, 0, 1, \"*\", VBSymbolType.RazorCommentStar),\n                          new VBSymbol(2, 0, 2, \" Foo * Bar * Baz *\", VBSymbolType.RazorComment));\n        }\n\n        [Fact]\n        public void Next_Ignores_Star_Without_Trailing_At()\n        {\n            TestTokenizer(\"@* Foo * Bar * Baz *@\",\n                          new VBSymbol(0, 0, 0, \"@\", VBSymbolType.RazorCommentTransition),\n                          new VBSymbol(1, 0, 1, \"*\", VBSymbolType.RazorCommentStar),\n                          new VBSymbol(2, 0, 2, \" Foo * Bar * Baz \", VBSymbolType.RazorComment),\n                          new VBSymbol(19, 0, 19, \"*\", VBSymbolType.RazorCommentStar),\n                          new VBSymbol(20, 0, 20, \"@\", VBSymbolType.RazorCommentTransition));\n        }\n\n        [Fact]\n        public void Next_Returns_RazorComment_Token_For_Entire_Razor_Comment()\n        {\n            TestTokenizer(\"@* Foo Bar Baz *@\",\n                          new VBSymbol(0, 0, 0, \"@\", VBSymbolType.RazorCommentTransition),\n                          new VBSymbol(1, 0, 1, \"*\", VBSymbolType.RazorCommentStar),\n                          new VBSymbol(2, 0, 2, \" Foo Bar Baz \", VBSymbolType.RazorComment),\n                          new VBSymbol(15, 0, 15, \"*\", VBSymbolType.RazorCommentStar),\n                          new VBSymbol(16, 0, 16, \"@\", VBSymbolType.RazorCommentTransition));\n        }\n\n        [Fact]\n        public void Tick_Comment_Is_Recognized()\n        {\n            TestTokenizer(\"' Foo Bar Baz\", new VBSymbol(0, 0, 0, \"' Foo Bar Baz\", VBSymbolType.Comment));\n        }\n\n        [Fact]\n        public void Tick_Comment_Is_Terminated_By_Newline()\n        {\n            TestTokenizer(\"' Foo Bar Baz\\na\", new VBSymbol(0, 0, 0, \"' Foo Bar Baz\", VBSymbolType.Comment), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void LeftQuote_Comment_Is_Recognized()\n        {\n            // U+2018 - Left Quote: ‘\n            TestTokenizer(\"‘ Foo Bar Baz\", new VBSymbol(0, 0, 0, \"‘ Foo Bar Baz\", VBSymbolType.Comment));\n        }\n\n        [Fact]\n        public void LeftQuote_Comment_Is_Terminated_By_Newline()\n        {\n            // U+2018 - Left Quote: ‘\n            TestTokenizer(\"‘ Foo Bar Baz\\na\", new VBSymbol(0, 0, 0, \"‘ Foo Bar Baz\", VBSymbolType.Comment), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void RightQuote_Comment_Is_Recognized()\n        {\n            // U+2019 - Right Quote: ’\n            TestTokenizer(\"’ Foo Bar Baz\", new VBSymbol(0, 0, 0, \"’ Foo Bar Baz\", VBSymbolType.Comment));\n        }\n\n        [Fact]\n        public void RightQuote_Comment_Is_Terminated_By_Newline()\n        {\n            // U+2019 - Right Quote: ’\n            TestTokenizer(\"’ Foo Bar Baz\\na\", new VBSymbol(0, 0, 0, \"’ Foo Bar Baz\", VBSymbolType.Comment), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Rem_Comment_Is_Recognized()\n        {\n            TestTokenizer(\"REM Foo Bar Baz\", new VBSymbol(0, 0, 0, \"REM Foo Bar Baz\", VBSymbolType.Comment));\n        }\n\n        [Fact]\n        public void Rem_Comment_Is_Terminated_By_Newline()\n        {\n            TestTokenizer(\"REM Foo Bar Baz\\na\", new VBSymbol(0, 0, 0, \"REM Foo Bar Baz\", VBSymbolType.Comment), IgnoreRemaining);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Tokenizer/VBTokenizerIdentifierTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Tokenizer\n{\n    public class VBTokenizerIdentifierTest : VBTokenizerTestBase\n    {\n        [Fact]\n        public void Simple_Identifier_Is_Recognized()\n        {\n            TestTokenizer(\"foo\", new VBSymbol(0, 0, 0, \"foo\", VBSymbolType.Identifier));\n        }\n\n        [Fact]\n        public void Escaped_Identifier_Terminates_At_EOF()\n        {\n            TestTokenizer(\"[foo\", new VBSymbol(0, 0, 0, \"[foo\", VBSymbolType.Identifier));\n        }\n\n        [Fact]\n        public void Escaped_Identifier_Terminates_At_Whitespace()\n        {\n            TestTokenizer(\"[foo \", new VBSymbol(0, 0, 0, \"[foo\", VBSymbolType.Identifier), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Escaped_Identifier_Terminates_At_RightBracket_And_Does_Not_Read_TypeCharacter()\n        {\n            TestTokenizer(\"[foo]&\", new VBSymbol(0, 0, 0, \"[foo]\", VBSymbolType.Identifier), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Identifier_Starting_With_Underscore_Is_Recognized()\n        {\n            TestTokenizer(\"_foo\", new VBSymbol(0, 0, 0, \"_foo\", VBSymbolType.Identifier));\n        }\n\n        [Fact]\n        public void Identifier_Can_Contain_Digits()\n        {\n            TestTokenizer(\"foo4\", new VBSymbol(0, 0, 0, \"foo4\", VBSymbolType.Identifier));\n        }\n\n        [Fact]\n        public void Identifier_Can_Start_With_Titlecase_Letter()\n        {\n            TestTokenizer(\"ῼfoo\", new VBSymbol(0, 0, 0, \"ῼfoo\", VBSymbolType.Identifier));\n        }\n\n        [Fact]\n        public void Identifier_Can_Start_With_Letter_Modifier()\n        {\n            TestTokenizer(\"ᵊfoo\", new VBSymbol(0, 0, 0, \"ᵊfoo\", VBSymbolType.Identifier));\n        }\n\n        [Fact]\n        public void Identifier_Can_Start_With_Other_Letter()\n        {\n            TestTokenizer(\"ƻfoo\", new VBSymbol(0, 0, 0, \"ƻfoo\", VBSymbolType.Identifier));\n        }\n\n        [Fact]\n        public void Identifier_Can_Start_With_Number_Letter()\n        {\n            TestTokenizer(\"Ⅽool\", new VBSymbol(0, 0, 0, \"Ⅽool\", VBSymbolType.Identifier));\n        }\n\n        [Fact]\n        public void Identifier_Can_Contain_Non_Spacing_Mark()\n        {\n            TestTokenizer(\"foo\\u0300\", new VBSymbol(0, 0, 0, \"foo\\u0300\", VBSymbolType.Identifier));\n        }\n\n        [Fact]\n        public void Identifier_Can_Contain_Spacing_Combining_Mark()\n        {\n            TestTokenizer(\"fooः\", new VBSymbol(0, 0, 0, \"fooः\", VBSymbolType.Identifier));\n        }\n\n        [Fact]\n        public void Identifier_Can_Contain_Non_English_Digit()\n        {\n            TestTokenizer(\"foo١\", new VBSymbol(0, 0, 0, \"foo١\", VBSymbolType.Identifier));\n        }\n\n        [Fact]\n        public void Identifier_Can_Contain_Connector_Punctuation()\n        {\n            TestTokenizer(\"foo‿bar\", new VBSymbol(0, 0, 0, \"foo‿bar\", VBSymbolType.Identifier));\n        }\n\n        [Fact]\n        public void Identifier_Can_Contain_Format_Character()\n        {\n            TestTokenizer(\"foo؃bar\", new VBSymbol(0, 0, 0, \"foo؃bar\", VBSymbolType.Identifier));\n        }\n\n        [Fact]\n        public void Escaped_Keyword_Is_Recognized_As_Identifier()\n        {\n            TestSingleToken(\"[AddHandler]\", VBSymbolType.Identifier);\n        }\n\n        [Fact]\n        public void Keywords_Are_Recognized_As_Keyword_Tokens()\n        {\n            TestKeyword(\"AddHandler\", VBKeyword.AddHandler);\n            TestKeyword(\"AndAlso\", VBKeyword.AndAlso);\n            TestKeyword(\"Byte\", VBKeyword.Byte);\n            TestKeyword(\"Catch\", VBKeyword.Catch);\n            TestKeyword(\"CDate\", VBKeyword.CDate);\n            TestKeyword(\"CInt\", VBKeyword.CInt);\n            TestKeyword(\"Const\", VBKeyword.Const);\n            TestKeyword(\"CSng\", VBKeyword.CSng);\n            TestKeyword(\"CULng\", VBKeyword.CULng);\n            TestKeyword(\"Declare\", VBKeyword.Declare);\n            TestKeyword(\"DirectCast\", VBKeyword.DirectCast);\n            TestKeyword(\"Else\", VBKeyword.Else);\n            TestKeyword(\"Enum\", VBKeyword.Enum);\n            TestKeyword(\"Exit\", VBKeyword.Exit);\n            TestKeyword(\"Friend\", VBKeyword.Friend);\n            TestKeyword(\"GetXmlNamespace\", VBKeyword.GetXmlNamespace);\n            TestKeyword(\"Handles\", VBKeyword.Handles);\n            TestKeyword(\"In\", VBKeyword.In);\n            TestKeyword(\"Is\", VBKeyword.Is);\n            TestKeyword(\"Like\", VBKeyword.Like);\n            TestKeyword(\"Mod\", VBKeyword.Mod);\n            TestKeyword(\"MyBase\", VBKeyword.MyBase);\n            TestKeyword(\"New\", VBKeyword.New);\n            TestKeyword(\"AddressOf\", VBKeyword.AddressOf);\n            TestKeyword(\"As\", VBKeyword.As);\n            TestKeyword(\"ByVal\", VBKeyword.ByVal);\n            TestKeyword(\"CBool\", VBKeyword.CBool);\n            TestKeyword(\"CDbl\", VBKeyword.CDbl);\n            TestKeyword(\"Class\", VBKeyword.Class);\n            TestKeyword(\"Continue\", VBKeyword.Continue);\n            TestKeyword(\"CStr\", VBKeyword.CStr);\n            TestKeyword(\"CUShort\", VBKeyword.CUShort);\n            TestKeyword(\"Default\", VBKeyword.Default);\n            TestKeyword(\"Do\", VBKeyword.Do);\n            TestKeyword(\"ElseIf\", VBKeyword.ElseIf);\n            TestKeyword(\"Erase\", VBKeyword.Erase);\n            TestKeyword(\"False\", VBKeyword.False);\n            TestKeyword(\"Function\", VBKeyword.Function);\n            TestKeyword(\"Global\", VBKeyword.Global);\n            TestKeyword(\"If\", VBKeyword.If);\n            TestKeyword(\"Inherits\", VBKeyword.Inherits);\n            TestKeyword(\"IsNot\", VBKeyword.IsNot);\n            TestKeyword(\"Long\", VBKeyword.Long);\n            TestKeyword(\"Module\", VBKeyword.Module);\n            TestKeyword(\"MyClass\", VBKeyword.MyClass);\n            TestKeyword(\"Next\", VBKeyword.Next);\n            TestKeyword(\"Alias\", VBKeyword.Alias);\n            TestKeyword(\"Boolean\", VBKeyword.Boolean);\n            TestKeyword(\"Call\", VBKeyword.Call);\n            TestKeyword(\"CByte\", VBKeyword.CByte);\n            TestKeyword(\"CDec\", VBKeyword.CDec);\n            TestKeyword(\"CLng\", VBKeyword.CLng);\n            TestKeyword(\"CSByte\", VBKeyword.CSByte);\n            TestKeyword(\"CType\", VBKeyword.CType);\n            TestKeyword(\"Date\", VBKeyword.Date);\n            TestKeyword(\"Delegate\", VBKeyword.Delegate);\n            TestKeyword(\"Double\", VBKeyword.Double);\n            TestKeyword(\"End\", VBKeyword.End);\n            TestKeyword(\"Error\", VBKeyword.Error);\n            TestKeyword(\"Finally\", VBKeyword.Finally);\n            TestKeyword(\"Get\", VBKeyword.Get);\n            TestKeyword(\"GoSub\", VBKeyword.GoSub);\n            TestKeyword(\"Implements\", VBKeyword.Implements);\n            TestKeyword(\"Integer\", VBKeyword.Integer);\n            TestKeyword(\"Let\", VBKeyword.Let);\n            TestKeyword(\"Loop\", VBKeyword.Loop);\n            TestKeyword(\"MustInherit\", VBKeyword.MustInherit);\n            TestKeyword(\"Namespace\", VBKeyword.Namespace);\n            TestKeyword(\"Not\", VBKeyword.Not);\n            TestKeyword(\"And\", VBKeyword.And);\n            TestKeyword(\"ByRef\", VBKeyword.ByRef);\n            TestKeyword(\"Case\", VBKeyword.Case);\n            TestKeyword(\"CChar\", VBKeyword.CChar);\n            TestKeyword(\"Char\", VBKeyword.Char);\n            TestKeyword(\"CObj\", VBKeyword.CObj);\n            TestKeyword(\"CShort\", VBKeyword.CShort);\n            TestKeyword(\"CUInt\", VBKeyword.CUInt);\n            TestKeyword(\"Decimal\", VBKeyword.Decimal);\n            TestKeyword(\"Dim\", VBKeyword.Dim);\n            TestKeyword(\"Each\", VBKeyword.Each);\n            TestKeyword(\"EndIf\", VBKeyword.EndIf);\n            TestKeyword(\"Event\", VBKeyword.Event);\n            TestKeyword(\"For\", VBKeyword.For);\n            TestKeyword(\"GetType\", VBKeyword.GetType);\n            TestKeyword(\"GoTo\", VBKeyword.GoTo);\n            TestKeyword(\"Imports\", VBKeyword.Imports);\n            TestKeyword(\"Interface\", VBKeyword.Interface);\n            TestKeyword(\"Lib\", VBKeyword.Lib);\n            TestKeyword(\"Me\", VBKeyword.Me);\n            TestKeyword(\"MustOverride\", VBKeyword.MustOverride);\n            TestKeyword(\"Narrowing\", VBKeyword.Narrowing);\n            TestKeyword(\"Nothing\", VBKeyword.Nothing);\n            TestKeyword(\"NotInheritable\", VBKeyword.NotInheritable);\n            TestKeyword(\"On\", VBKeyword.On);\n            TestKeyword(\"Or\", VBKeyword.Or);\n            TestKeyword(\"Overrides\", VBKeyword.Overrides);\n            TestKeyword(\"Property\", VBKeyword.Property);\n            TestKeyword(\"ReadOnly\", VBKeyword.ReadOnly);\n            TestKeyword(\"Resume\", VBKeyword.Resume);\n            TestKeyword(\"Set\", VBKeyword.Set);\n            TestKeyword(\"Single\", VBKeyword.Single);\n            TestKeyword(\"String\", VBKeyword.String);\n            TestKeyword(\"Then\", VBKeyword.Then);\n            TestKeyword(\"Try\", VBKeyword.Try);\n            TestKeyword(\"ULong\", VBKeyword.ULong);\n            TestKeyword(\"Wend\", VBKeyword.Wend);\n            TestKeyword(\"With\", VBKeyword.With);\n            TestKeyword(\"NotOverridable\", VBKeyword.NotOverridable);\n            TestKeyword(\"Operator\", VBKeyword.Operator);\n            TestKeyword(\"OrElse\", VBKeyword.OrElse);\n            TestKeyword(\"ParamArray\", VBKeyword.ParamArray);\n            TestKeyword(\"Protected\", VBKeyword.Protected);\n            TestKeyword(\"ReDim\", VBKeyword.ReDim);\n            TestKeyword(\"Return\", VBKeyword.Return);\n            TestKeyword(\"Shadows\", VBKeyword.Shadows);\n            TestKeyword(\"Static\", VBKeyword.Static);\n            TestKeyword(\"Structure\", VBKeyword.Structure);\n            TestKeyword(\"Throw\", VBKeyword.Throw);\n            TestKeyword(\"TryCast\", VBKeyword.TryCast);\n            TestKeyword(\"UShort\", VBKeyword.UShort);\n            TestKeyword(\"When\", VBKeyword.When);\n            TestKeyword(\"WithEvents\", VBKeyword.WithEvents);\n            TestKeyword(\"Object\", VBKeyword.Object);\n            TestKeyword(\"Option\", VBKeyword.Option);\n            TestKeyword(\"Overloads\", VBKeyword.Overloads);\n            TestKeyword(\"Partial\", VBKeyword.Partial);\n            TestKeyword(\"Public\", VBKeyword.Public);\n            TestKeyword(\"SByte\", VBKeyword.SByte);\n            TestKeyword(\"Shared\", VBKeyword.Shared);\n            TestKeyword(\"Step\", VBKeyword.Step);\n            TestKeyword(\"Sub\", VBKeyword.Sub);\n            TestKeyword(\"To\", VBKeyword.To);\n            TestKeyword(\"TypeOf\", VBKeyword.TypeOf);\n            TestKeyword(\"Using\", VBKeyword.Using);\n            TestKeyword(\"While\", VBKeyword.While);\n            TestKeyword(\"WriteOnly\", VBKeyword.WriteOnly);\n            TestKeyword(\"Of\", VBKeyword.Of);\n            TestKeyword(\"Optional\", VBKeyword.Optional);\n            TestKeyword(\"Overridable\", VBKeyword.Overridable);\n            TestKeyword(\"Private\", VBKeyword.Private);\n            TestKeyword(\"RaiseEvent\", VBKeyword.RaiseEvent);\n            TestKeyword(\"RemoveHandler\", VBKeyword.RemoveHandler);\n            TestKeyword(\"Select\", VBKeyword.Select);\n            TestKeyword(\"Short\", VBKeyword.Short);\n            TestKeyword(\"Stop\", VBKeyword.Stop);\n            TestKeyword(\"SyncLock\", VBKeyword.SyncLock);\n            TestKeyword(\"True\", VBKeyword.True);\n            TestKeyword(\"UInteger\", VBKeyword.UInteger);\n            TestKeyword(\"Variant\", VBKeyword.Variant);\n            TestKeyword(\"Widening\", VBKeyword.Widening);\n            TestKeyword(\"Xor\", VBKeyword.Xor);\n        }\n\n        private void TestKeyword(string keyword, VBKeyword keywordType)\n        {\n            TestTokenizer(keyword, new VBSymbol(0, 0, 0, keyword, VBSymbolType.Keyword) { Keyword = keywordType });\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Tokenizer/VBTokenizerLiteralTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Tokenizer\n{\n    public class VBTokenizerLiteralTest : VBTokenizerTestBase\n    {\n        [Fact]\n        public void Decimal_Integer_Literal_Is_Recognized()\n        {\n            TestSingleToken(\"01189998819991197253\", VBSymbolType.IntegerLiteral);\n        }\n\n        [Fact]\n        public void Integer_Type_Suffixes_Are_Recognized_In_Decimal_Literal()\n        {\n            TestSingleToken(\"42S\", VBSymbolType.IntegerLiteral);\n            TestSingleToken(\"42I\", VBSymbolType.IntegerLiteral);\n            TestSingleToken(\"42L\", VBSymbolType.IntegerLiteral);\n            TestSingleToken(\"42US\", VBSymbolType.IntegerLiteral);\n            TestSingleToken(\"42UI\", VBSymbolType.IntegerLiteral);\n            TestSingleToken(\"42UL\", VBSymbolType.IntegerLiteral);\n        }\n\n        [Fact]\n        public void Hex_Integer_Literal_Is_Recognized()\n        {\n            TestSingleToken(\"&HDeadBeef\", VBSymbolType.IntegerLiteral);\n        }\n\n        [Fact]\n        public void Integer_Type_Suffixes_Are_Recognized_In_Hex_Literal()\n        {\n            TestSingleToken(\"&HDeadBeefS\", VBSymbolType.IntegerLiteral);\n            TestSingleToken(\"&HDeadBeefI\", VBSymbolType.IntegerLiteral);\n            TestSingleToken(\"&HDeadBeefL\", VBSymbolType.IntegerLiteral);\n            TestSingleToken(\"&HDeadBeefUS\", VBSymbolType.IntegerLiteral);\n            TestSingleToken(\"&HDeadBeefUI\", VBSymbolType.IntegerLiteral);\n            TestSingleToken(\"&HDeadBeefUL\", VBSymbolType.IntegerLiteral);\n        }\n\n        [Fact]\n        public void Octal_Integer_Literal_Is_Recognized()\n        {\n            TestSingleToken(\"&O77\", VBSymbolType.IntegerLiteral);\n        }\n\n        [Fact]\n        public void Integer_Type_Suffixes_Are_Recognized_In_Octal_Literal()\n        {\n            TestSingleToken(\"&O77S\", VBSymbolType.IntegerLiteral);\n            TestSingleToken(\"&O77I\", VBSymbolType.IntegerLiteral);\n            TestSingleToken(\"&O77L\", VBSymbolType.IntegerLiteral);\n            TestSingleToken(\"&O77US\", VBSymbolType.IntegerLiteral);\n            TestSingleToken(\"&O77UI\", VBSymbolType.IntegerLiteral);\n            TestSingleToken(\"&O77UL\", VBSymbolType.IntegerLiteral);\n        }\n\n        [Fact]\n        public void Incomplete_Type_Suffix_Is_Recognized()\n        {\n            TestSingleToken(\"42U\", VBSymbolType.IntegerLiteral);\n            TestSingleToken(\"&H42U\", VBSymbolType.IntegerLiteral);\n            TestSingleToken(\"&O77U\", VBSymbolType.IntegerLiteral);\n        }\n\n        [Fact]\n        public void Integer_With_FloatingPoint_Type_Suffix_Is_Recognized_As_FloatingPointLiteral()\n        {\n            TestSingleToken(\"42F\", VBSymbolType.FloatingPointLiteral);\n            TestSingleToken(\"42R\", VBSymbolType.FloatingPointLiteral);\n            TestSingleToken(\"42D\", VBSymbolType.FloatingPointLiteral);\n        }\n\n        [Fact]\n        public void Simple_FloatingPoint_Is_Recognized()\n        {\n            TestSingleToken(\"3.14159\", VBSymbolType.FloatingPointLiteral);\n        }\n\n        [Fact]\n        public void Integer_With_Exponent_Is_Recognized()\n        {\n            TestSingleToken(\"1E10\", VBSymbolType.FloatingPointLiteral);\n            TestSingleToken(\"1e10\", VBSymbolType.FloatingPointLiteral);\n            TestSingleToken(\"1E+10\", VBSymbolType.FloatingPointLiteral);\n            TestSingleToken(\"1e+10\", VBSymbolType.FloatingPointLiteral);\n            TestSingleToken(\"1E-10\", VBSymbolType.FloatingPointLiteral);\n            TestSingleToken(\"1e-10\", VBSymbolType.FloatingPointLiteral);\n        }\n\n        [Fact]\n        public void Simple_FloatingPoint_With_Exponent_Is_Recognized()\n        {\n            TestSingleToken(\"3.14159e10\", VBSymbolType.FloatingPointLiteral);\n        }\n\n        [Fact]\n        public void FloatingPoint_Between_Zero_And_One_Is_Recognized()\n        {\n            TestSingleToken(\".314159e1\", VBSymbolType.FloatingPointLiteral);\n        }\n\n        [Fact]\n        public void Simple_String_Literal_Is_Recognized()\n        {\n            TestSingleToken(\"\\\"Foo Bar Baz\\\"\", VBSymbolType.StringLiteral);\n        }\n\n        [Fact]\n        public void Two_Double_Quotes_Are_Recognized_As_Escape_Sequence()\n        {\n            TestSingleToken(\"\\\"Foo \\\"\\\"Bar\\\"\\\" Baz\\\"\", VBSymbolType.StringLiteral);\n        }\n\n        [Fact]\n        public void String_Literal_Is_Terminated_At_EOF()\n        {\n            TestSingleToken(\"\\\"Foo\", VBSymbolType.StringLiteral);\n        }\n\n        [Fact]\n        public void String_Literal_Is_Terminated_At_EOL()\n        {\n            TestTokenizer(\"\\\"Foo\\nBar\", new VBSymbol(0, 0, 0, \"\\\"Foo\", VBSymbolType.StringLiteral), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Character_Literal_Is_Recognized_By_Trailing_C_After_String_Literal()\n        {\n            TestSingleToken(\"\\\"abc\\\"c\", VBSymbolType.CharacterLiteral);\n        }\n\n        [Fact]\n        public void LeftDoubleQuote_Is_Valid_DoubleQuote()\n        {\n            // Repeat all the above tests with Unicode Left Double Quote Character U+201C: “\n            TestSingleToken(\"“Foo Bar Baz“\", VBSymbolType.StringLiteral);\n            TestSingleToken(\"“Foo ““Bar““ Baz“\", VBSymbolType.StringLiteral);\n            TestSingleToken(\"“Foo\", VBSymbolType.StringLiteral);\n            TestSingleToken(\"“abc“c\", VBSymbolType.CharacterLiteral);\n            TestTokenizer(\"“Foo\\nBar\", new VBSymbol(0, 0, 0, \"“Foo\", VBSymbolType.StringLiteral), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void RightDoubleQuote_Is_Valid_DoubleQuote()\n        {\n            // Repeat all the above tests with Unicode Right Double Quote Character U+201D: ”\n            TestSingleToken(\"”Foo Bar Baz”\", VBSymbolType.StringLiteral);\n            TestSingleToken(\"”Foo ””Bar”” Baz”\", VBSymbolType.StringLiteral);\n            TestSingleToken(\"”Foo\", VBSymbolType.StringLiteral);\n            TestSingleToken(\"”abc”c\", VBSymbolType.CharacterLiteral);\n            TestTokenizer(\"”Foo\\nBar\", new VBSymbol(0, 0, 0, \"”Foo\", VBSymbolType.StringLiteral), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void DateLiteral_Is_Recognized()\n        {\n            TestSingleToken(\"# 8/23/1970 3:45:39AM #\", VBSymbolType.DateLiteral);\n        }\n\n        [Fact]\n        public void DateLiteral_Is_Terminated_At_EndHash()\n        {\n            TestTokenizer(\"# 8/23/1970 # 3:45:39AM\", new VBSymbol(0, 0, 0, \"# 8/23/1970 #\", VBSymbolType.DateLiteral), IgnoreRemaining);\n        }\n\n        [Fact]\n        public void DateLiteral_Is_Terminated_At_EOF()\n        {\n            TestSingleToken(\"# 8/23/1970 3:45:39AM\", VBSymbolType.DateLiteral);\n        }\n\n        [Fact]\n        public void DateLiteral_Is_Terminated_At_EOL()\n        {\n            TestTokenizer(\"# 8/23/1970\\n3:45:39AM\", new VBSymbol(0, 0, 0, \"# 8/23/1970\", VBSymbolType.DateLiteral), IgnoreRemaining);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Tokenizer/VBTokenizerOperatorsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Tokenizer\n{\n    public class VBTokenizerOperatorsTest : VBTokenizerTestBase\n    {\n        [Fact]\n        public void Line_Continuation_Character_Is_Recognized()\n        {\n            TestSingleToken(\"_\", VBSymbolType.LineContinuation);\n        }\n\n        [Fact]\n        public void LeftParen_Is_Recognized()\n        {\n            TestSingleToken(\"(\", VBSymbolType.LeftParenthesis);\n        }\n\n        [Fact]\n        public void RightParen_Is_Recognized()\n        {\n            TestSingleToken(\")\", VBSymbolType.RightParenthesis);\n        }\n\n        [Fact]\n        public void LeftBracket_Is_Recognized()\n        {\n            TestSingleToken(\"[\", VBSymbolType.LeftBracket);\n        }\n\n        [Fact]\n        public void RightBracket_Is_Recognized()\n        {\n            TestSingleToken(\"]\", VBSymbolType.RightBracket);\n        }\n\n        [Fact]\n        public void LeftBrace_Is_Recognized()\n        {\n            TestSingleToken(\"{\", VBSymbolType.LeftBrace);\n        }\n\n        [Fact]\n        public void RightBrace_Is_Recognized()\n        {\n            TestSingleToken(\"}\", VBSymbolType.RightBrace);\n        }\n\n        [Fact]\n        public void Bang_Is_Recognized()\n        {\n            TestSingleToken(\"!\", VBSymbolType.Bang);\n        }\n\n        [Fact]\n        public void Hash_Is_Recognized()\n        {\n            TestSingleToken(\"#\", VBSymbolType.Hash);\n        }\n\n        [Fact]\n        public void Comma_Is_Recognized()\n        {\n            TestSingleToken(\",\", VBSymbolType.Comma);\n        }\n\n        [Fact]\n        public void Dot_Is_Recognized()\n        {\n            TestSingleToken(\".\", VBSymbolType.Dot);\n        }\n\n        [Fact]\n        public void Colon_Is_Recognized()\n        {\n            TestSingleToken(\":\", VBSymbolType.Colon);\n        }\n\n        [Fact]\n        public void QuestionMark_Is_Recognized()\n        {\n            TestSingleToken(\"?\", VBSymbolType.QuestionMark);\n        }\n\n        [Fact]\n        public void Concatenation_Is_Recognized()\n        {\n            TestSingleToken(\"&\", VBSymbolType.Concatenation);\n        }\n\n        [Fact]\n        public void Multiply_Is_Recognized()\n        {\n            TestSingleToken(\"*\", VBSymbolType.Multiply);\n        }\n\n        [Fact]\n        public void Add_Is_Recognized()\n        {\n            TestSingleToken(\"+\", VBSymbolType.Add);\n        }\n\n        [Fact]\n        public void Subtract_Is_Recognized()\n        {\n            TestSingleToken(\"-\", VBSymbolType.Subtract);\n        }\n\n        [Fact]\n        public void Divide_Is_Recognized()\n        {\n            TestSingleToken(\"/\", VBSymbolType.Divide);\n        }\n\n        [Fact]\n        public void IntegerDivide_Is_Recognized()\n        {\n            TestSingleToken(\"\\\\\", VBSymbolType.IntegerDivide);\n        }\n\n        [Fact]\n        public void Exponentiation_Is_Recognized()\n        {\n            TestSingleToken(\"^\", VBSymbolType.Exponentiation);\n        }\n\n        [Fact]\n        public void Equal_Is_Recognized()\n        {\n            TestSingleToken(\"=\", VBSymbolType.Equal);\n        }\n\n        [Fact]\n        public void LessThan_Is_Recognized()\n        {\n            TestSingleToken(\"<\", VBSymbolType.LessThan);\n        }\n\n        [Fact]\n        public void GreaterThan_Is_Recognized()\n        {\n            TestSingleToken(\">\", VBSymbolType.GreaterThan);\n        }\n\n        [Fact]\n        public void Dollar_Is_Recognized()\n        {\n            TestSingleToken(\"$\", VBSymbolType.Dollar);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Tokenizer/VBTokenizerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Tokenizer;\nusing System.Web.Razor.Tokenizer.Symbols;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Tokenizer\n{\n    public class VBTokenizerTest : VBTokenizerTestBase\n    {\n        [Fact]\n        public void Constructor_Throws_ArgNull_If_Null_Source_Provided()\n        {\n            Assert.ThrowsArgumentNull(() => new CSharpTokenizer(null), \"source\");\n        }\n\n        [Fact]\n        public void Next_Returns_Null_When_EOF_Reached()\n        {\n            TestTokenizer(\"\");\n        }\n\n        [Fact]\n        public void Next_Returns_Newline_Token_For_Single_CR()\n        {\n            TestTokenizer(\"\\r\\ra\",\n                          new VBSymbol(0, 0, 0, \"\\r\", VBSymbolType.NewLine),\n                          new VBSymbol(1, 1, 0, \"\\r\", VBSymbolType.NewLine),\n                          IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Next_Returns_Newline_Token_For_Single_LF()\n        {\n            TestTokenizer(\"\\n\\na\",\n                          new VBSymbol(0, 0, 0, \"\\n\", VBSymbolType.NewLine),\n                          new VBSymbol(1, 1, 0, \"\\n\", VBSymbolType.NewLine),\n                          IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Next_Returns_Newline_Token_For_Single_NEL()\n        {\n            // NEL: Unicode \"Next Line\" U+0085\n            TestTokenizer(\"\\u0085\\u0085a\",\n                          new VBSymbol(0, 0, 0, \"\\u0085\", VBSymbolType.NewLine),\n                          new VBSymbol(1, 1, 0, \"\\u0085\", VBSymbolType.NewLine),\n                          IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Next_Returns_Newline_Token_For_Single_Line_Separator()\n        {\n            // Unicode \"Line Separator\" U+2028\n            TestTokenizer(\"\\u2028\\u2028a\",\n                          new VBSymbol(0, 0, 0, \"\\u2028\", VBSymbolType.NewLine),\n                          new VBSymbol(1, 1, 0, \"\\u2028\", VBSymbolType.NewLine),\n                          IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Next_Returns_Newline_Token_For_Single_Paragraph_Separator()\n        {\n            // Unicode \"Paragraph Separator\" U+2029\n            TestTokenizer(\"\\u2029\\u2029a\",\n                          new VBSymbol(0, 0, 0, \"\\u2029\", VBSymbolType.NewLine),\n                          new VBSymbol(1, 1, 0, \"\\u2029\", VBSymbolType.NewLine),\n                          IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Next_Returns_Single_Newline_Token_For_CRLF()\n        {\n            TestTokenizer(\"\\r\\n\\r\\na\",\n                          new VBSymbol(0, 0, 0, \"\\r\\n\", VBSymbolType.NewLine),\n                          new VBSymbol(2, 1, 0, \"\\r\\n\", VBSymbolType.NewLine),\n                          IgnoreRemaining);\n        }\n\n        [Fact]\n        public void Next_Returns_Token_For_Whitespace_Characters()\n        {\n            TestTokenizer(\" \\f\\t\\u000B \\n \",\n                          new VBSymbol(0, 0, 0, \" \\f\\t\\u000B \", VBSymbolType.WhiteSpace),\n                          new VBSymbol(5, 0, 5, \"\\n\", VBSymbolType.NewLine),\n                          new VBSymbol(6, 1, 0, \" \", VBSymbolType.WhiteSpace));\n        }\n\n        [Fact]\n        public void Transition_Is_Recognized()\n        {\n            TestSingleToken(\"@\", VBSymbolType.Transition);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Tokenizer/VBTokenizerTestBase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Text;\nusing System.Web.Razor.Tokenizer;\nusing System.Web.Razor.Tokenizer.Symbols;\n\nnamespace System.Web.Razor.Test.Tokenizer\n{\n    public abstract class VBTokenizerTestBase : TokenizerTestBase<VBSymbol, VBSymbolType>\n    {\n        private static VBSymbol _ignoreRemaining = new VBSymbol(0, 0, 0, String.Empty, VBSymbolType.Unknown);\n\n        protected override VBSymbol IgnoreRemaining\n        {\n            get { return _ignoreRemaining; }\n        }\n\n        protected override Tokenizer<VBSymbol, VBSymbolType> CreateTokenizer(ITextDocument source)\n        {\n            return new VBTokenizer(source);\n        }\n\n        protected void TestSingleToken(string text, VBSymbolType expectedSymbolType)\n        {\n            TestTokenizer(text, new VBSymbol(0, 0, 0, text, expectedSymbolType));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Utils/DisposableActionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Utils;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Utils\n{\n    public class DisposableActionTest\n    {\n        [Fact]\n        public void ConstructorRequiresNonNullAction()\n        {\n            Assert.ThrowsArgumentNull(() => new DisposableAction(null), \"action\");\n        }\n\n        [Fact]\n        public void ActionIsExecutedOnDispose()\n        {\n            // Arrange\n            bool called = false;\n            DisposableAction action = new DisposableAction(() => { called = true; });\n\n            // Act\n            action.Dispose();\n\n            // Assert\n            Assert.True(called, \"The action was not run when the DisposableAction was disposed\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Utils/EnumerableUtils.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Razor.Test.Utils\n{\n    public static class EnumerableUtils\n    {\n        public static void RunPairwise<T, V>(IEnumerable<T> left, IEnumerable<V> right, Action<T, V> action)\n        {\n            IEnumerator<T> leftEnum = left.GetEnumerator();\n            IEnumerator<V> rightEnum = right.GetEnumerator();\n            while (leftEnum.MoveNext() && rightEnum.MoveNext())\n            {\n                action(leftEnum.Current, rightEnum.Current);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Utils/MiscAssert.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq.Expressions;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Utils\n{\n    public static class MiscAssert\n    {\n        public static void AssertBothNullOrPropertyEqual<T>(T expected, T actual, Expression<Func<T, object>> propertyExpr, string objectName)\n            where T : class\n        {\n            // Unpack convert expressions\n            Expression expr = propertyExpr.Body;\n            while (expr.NodeType == ExpressionType.Convert)\n            {\n                expr = ((UnaryExpression)expr).Operand;\n            }\n\n            string propertyName = ((MemberExpression)expr).Member.Name;\n            Func<T, object> property = propertyExpr.Compile();\n\n            if (expected == null)\n            {\n                Assert.Null(actual);\n            }\n            else\n            {\n                Assert.NotNull(actual);\n                Assert.Equal(property(expected), property(actual));\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Utils/MiscUtils.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Diagnostics;\nusing System.Text.RegularExpressions;\nusing System.Threading;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Utils\n{\n    class MiscUtils\n    {\n        public const int TimeoutInSeconds = 1;\n\n        public static string StripRuntimeVersion(string s)\n        {\n            return Regex.Replace(s, @\"Runtime Version:[\\d.]*\", \"Runtime Version:N.N.NNNNN.N\");\n        }\n\n        public static void DoWithTimeoutIfNotDebugging(Func<int, bool> withTimeout)\n        {\n#if DEBUG\n            if (Debugger.IsAttached)\n            {\n                withTimeout(Timeout.Infinite);\n            }\n            else\n            {\n#endif\n                Assert.True(withTimeout((int)TimeSpan.FromSeconds(TimeoutInSeconds).TotalMilliseconds), \"Timeout expired!\");\n#if DEBUG\n            }\n#endif\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/Utils/SpanAssert.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Text;\nusing System.Web.Razor.Parser.SyntaxTree;\nusing System.Web.Razor.Text;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Razor.Test.Utils\n{\n    public static class EventAssert\n    {\n        public static void NoMoreSpans(IEnumerator<Span> enumerator)\n        {\n            IList<Span> tokens = new List<Span>();\n            while (enumerator.MoveNext())\n            {\n                tokens.Add(enumerator.Current);\n            }\n\n            Assert.False(tokens.Count > 0, String.Format(CultureInfo.InvariantCulture, @\"There are more tokens available from the source: {0}\", FormatList(tokens)));\n        }\n\n        private static string FormatList<T>(IList<T> items)\n        {\n            StringBuilder tokenString = new StringBuilder();\n            foreach (T item in items)\n            {\n                tokenString.AppendLine(item.ToString());\n            }\n            return tokenString.ToString();\n        }\n\n        public static void NextSpanIs(IEnumerator<Span> enumerator, SpanKind type, string content, SourceLocation location)\n        {\n            Assert.True(enumerator.MoveNext(), \"There is no next token!\");\n            IsSpan(enumerator.Current, type, content, location);\n        }\n\n        public static void NextSpanIs(IEnumerator<Span> enumerator, SpanKind type, string content, int actualIndex, int lineIndex, int charIndex)\n        {\n            NextSpanIs(enumerator, type, content, new SourceLocation(actualIndex, lineIndex, charIndex));\n        }\n\n        public static void IsSpan(Span tok, SpanKind type, string content, int actualIndex, int lineIndex, int charIndex)\n        {\n            IsSpan(tok, type, content, new SourceLocation(actualIndex, lineIndex, charIndex));\n        }\n\n        public static void IsSpan(Span tok, SpanKind type, string content, SourceLocation location)\n        {\n            Assert.Equal(content, tok.Content);\n            Assert.Equal(type, tok.Kind);\n            Assert.Equal(location, tok.Start);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/VBRazorCodeLanguageTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor.Generator;\nusing System.Web.Razor.Parser;\nusing Microsoft.TestCommon;\nusing Microsoft.VisualBasic;\n\nnamespace System.Web.Razor.Test\n{\n    public class VBRazorCodeLanguageTest\n    {\n        [Fact]\n        public void CreateCodeParserReturnsNewVBCodeParser()\n        {\n            // Arrange\n            RazorCodeLanguage service = new VBRazorCodeLanguage();\n\n            // Act\n            ParserBase parser = service.CreateCodeParser();\n\n            // Assert\n            Assert.NotNull(parser);\n            Assert.IsType<VBCodeParser>(parser);\n        }\n\n        [Fact]\n        public void CreateCodeGeneratorParserListenerReturnsNewCSharpCodeGeneratorParserListener()\n        {\n            // Arrange\n            RazorCodeLanguage service = new VBRazorCodeLanguage();\n\n            // Act\n            RazorEngineHost host = new RazorEngineHost(new VBRazorCodeLanguage());\n            RazorCodeGenerator generator = service.CreateCodeGenerator(\"Foo\", \"Bar\", \"Baz\", host);\n\n            // Assert\n            Assert.NotNull(generator);\n            Assert.IsType<VBRazorCodeGenerator>(generator);\n            Assert.Equal(\"Foo\", generator.ClassName);\n            Assert.Equal(\"Bar\", generator.RootNamespaceName);\n            Assert.Equal(\"Baz\", generator.SourceFileName);\n            Assert.Same(host, generator.Host);\n        }\n\n        [Fact]\n        public void CodeDomProviderTypeReturnsVBCodeProvider()\n        {\n            // Arrange\n            RazorCodeLanguage service = new VBRazorCodeLanguage();\n\n            // Assert\n            Assert.Equal(typeof(VBCodeProvider), service.CodeDomProviderType);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.Razor.Test/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Castle.Core\" version=\"5.1.1\" targetFramework=\"net462\" />\n  <package id=\"Moq\" version=\"4.18.4\" targetFramework=\"net462\" />\n  <package id=\"xunit.abstractions\" version=\"2.0.3\" targetFramework=\"net462\" />\n  <package id=\"xunit.analyzers\" version=\"1.1.0\" targetFramework=\"net462\" />\n  <package id=\"xunit.assert\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.execution\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.runner.visualstudio\" version=\"2.4.5\" targetFramework=\"net462\" developmentDependency=\"true\" />\n</packages>"
  },
  {
    "path": "test/System.Web.WebPages.Administration.Test/AdminPackageTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing System.IO;\nusing System.Text;\nusing System.Web.Helpers;\nusing System.Web.Hosting;\nusing System.Web.Security;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Administration.Test\n{\n    public class AdminPackageTest\n    {\n        [Fact]\n        public void GetAdminVirtualPathThrowsIfPathIsNull()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => SiteAdmin.GetVirtualPath(null), \"virtualPath\");\n        }\n\n        [Fact]\n        public void GetAdminVirtualPathDoesNotAppendAdminVirtualPathIfPathStartsWithAdminVirtualPath()\n        {\n            // Act\n            string vpath = SiteAdmin.GetVirtualPath(\"~/_Admin/Foo\");\n\n            // Assert\n            Assert.Equal(\"~/_Admin/Foo\", vpath);\n        }\n\n        [Fact]\n        public void GetAdminVirtualPathAppendsAdminVirtualPath()\n        {\n            // Act\n            string vpath = SiteAdmin.GetVirtualPath(\"~/Foo\");\n\n            // Assert\n            Assert.Equal(\"~/_Admin/Foo\", vpath);\n        }\n\n        [Fact]\n        public void SetAuthCookieAddsAuthCookieToResponseCollection()\n        {\n            // Arrange\n            var mockResponse = new Mock<HttpResponseBase>();\n            var cookies = new HttpCookieCollection();\n            mockResponse.Setup(m => m.Cookies).Returns(cookies);\n\n            // Act\n            AdminSecurity.SetAuthCookie(mockResponse.Object);\n\n            // Assert\n            Assert.NotNull(cookies[\".ASPXADMINAUTH\"]);\n        }\n\n        [Fact]\n        public void GetAuthAdminCookieCreatesAnAuthTicketWithUserDataSetToAdmin()\n        {\n            // Arrange\n            var cookie = AdminSecurity.GetAuthCookie();\n\n            // Act\n            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);\n\n            // Assert\n            Assert.Equal(\".ASPXADMINAUTH\", cookie.Name);\n            Assert.True(cookie.HttpOnly);\n            Assert.Equal(2, ticket.Version);\n            Assert.Equal(\"ADMIN\", ticket.UserData);\n        }\n\n        [Fact]\n        public void IsAuthenticatedReturnsFalseIfAuthCookieNotInCollection()\n        {\n            // Arrange\n            var mockRequest = new Mock<HttpRequestBase>();\n            var cookies = new HttpCookieCollection();\n            mockRequest.Setup(m => m.Cookies).Returns(cookies);\n\n            // Act\n            bool authorized = AdminSecurity.IsAuthenticated(mockRequest.Object);\n\n            // Assert\n            Assert.False(authorized);\n        }\n\n        [Fact]\n        public void IsAuthenticatedReturnsFalseIfAuthCookieInCollectionAndIsNotAValidAdminAuthCookie()\n        {\n            // Arrange\n            var mockRequest = new Mock<HttpRequestBase>();\n            var cookies = new HttpCookieCollection();\n            mockRequest.Setup(m => m.Cookies).Returns(cookies);\n            cookies.Add(new HttpCookie(\".ASPXADMINAUTH\", \"test\"));\n\n            // Act\n            bool authorized = AdminSecurity.IsAuthenticated(mockRequest.Object);\n\n            // Assert\n            Assert.False(authorized);\n        }\n\n        [Fact]\n        public void IsAuthenticatedReturnsTrueIfAuthCookieIsValid()\n        {\n            // Arrange\n            var mockRequest = new Mock<HttpRequestBase>();\n            var cookies = new HttpCookieCollection();\n            mockRequest.Setup(m => m.Cookies).Returns(cookies);\n            cookies.Add(AdminSecurity.GetAuthCookie());\n\n            // Act\n            bool authorized = AdminSecurity.IsAuthenticated(mockRequest.Object);\n\n            // Assert\n            Assert.True(authorized);\n        }\n\n        [Fact]\n        public void GetRedirectUrlAppendsAppRelativePathAsReturnUrl()\n        {\n            // Arrange            \n            var mockRequest = new Mock<HttpRequestBase>();\n            mockRequest.Setup(m => m.RawUrl).Returns(\"~/_Admin/foo/bar/baz\");\n            mockRequest.Setup(m => m.QueryString).Returns(new NameValueCollection());\n\n            // Act\n            string redirectUrl = SiteAdmin.GetRedirectUrl(mockRequest.Object, \"register\", MakeAppRelative);\n\n            // Assert\n            Assert.Equal(\"~/_Admin/register?ReturnUrl=%7e%2f_Admin%2ffoo%2fbar%2fbaz\", redirectUrl);\n        }\n\n        [Fact]\n        public void GetRedirectUrlDoesNotAppendsAppRelativePathAsReturnUrlIfAlreadyExists()\n        {\n            // Arrange            \n            var mockRequest = new Mock<HttpRequestBase>();\n            mockRequest.Setup(m => m.RawUrl).Returns(\"~/_Admin/foo/bar/baz?ReturnUrl=~/foo\");\n            var queryString = new NameValueCollection();\n            queryString[\"ReturnUrl\"] = \"~/foo\";\n            mockRequest.Setup(m => m.QueryString).Returns(queryString);\n\n            // Act\n            string redirectUrl = SiteAdmin.GetRedirectUrl(mockRequest.Object, \"register\", MakeAppRelative);\n\n            // Assert\n            Assert.Equal(\"~/_Admin/register?ReturnUrl=%7e%2ffoo\", redirectUrl);\n        }\n\n        [Fact]\n        public void GetReturnUrlReturnsNullIfNotSet()\n        {\n            // Arrange            \n            var mockRequest = new Mock<HttpRequestBase>();\n            mockRequest.Setup(m => m.QueryString).Returns(new NameValueCollection());\n\n            // Act\n            string returlUrl = SiteAdmin.GetReturnUrl(mockRequest.Object);\n\n            // Assert\n            Assert.Null(returlUrl);\n        }\n\n        [Fact]\n        public void GetReturnUrlThrowsIfReturnUrlIsNotAppRelative()\n        {\n            // Arrange            \n            var mockRequest = new Mock<HttpRequestBase>();\n            var queryString = new NameValueCollection();\n            queryString[\"ReturnUrl\"] = \"http://www.bing.com\";\n            mockRequest.Setup(m => m.QueryString).Returns(queryString);\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(() => SiteAdmin.GetReturnUrl(mockRequest.Object), \"The return URL specified for request redirection is invalid.\");\n        }\n\n        [Fact]\n        public void GetReturnUrlReturnsReturlUrlQueryStringParameterIfItIsAppRelative()\n        {\n            // Arrange            \n            var mockRequest = new Mock<HttpRequestBase>();\n            var queryString = new NameValueCollection();\n            queryString[\"ReturnUrl\"] = \"~/_Admin/bar?foo=1\";\n            mockRequest.Setup(m => m.QueryString).Returns(queryString);\n\n            // Act\n            string returnUrl = SiteAdmin.GetReturnUrl(mockRequest.Object);\n\n            // Assert\n            Assert.Equal(\"~/_Admin/bar?foo=1\", returnUrl);\n        }\n\n        [Fact]\n        public void SaveAdminPasswordUsesCryptoToWritePasswordAndSalt()\n        {\n            // Arrange\n            var password = \"some-random-password\";\n            MemoryStream ms = new MemoryStream();\n\n            // Act\n            bool passwordSaved = AdminSecurity.SaveTemporaryPassword(password, () => ms);\n\n            // Assert\n            Assert.True(passwordSaved);\n            string savedPassword = Encoding.Default.GetString(ms.ToArray());\n            // Trim everything after the new line. Cannot use the properties from the stream since it is already closed by the writer.\n            savedPassword = savedPassword.Substring(0, savedPassword.IndexOf(Environment.NewLine));\n\n            Assert.True(Crypto.VerifyHashedPassword(savedPassword, password));\n        }\n\n        [Fact]\n        public void SaveAdminPasswordReturnsFalseIfGettingStreamThrowsUnauthorizedAccessException()\n        {\n            // Act\n            bool passwordSaved = AdminSecurity.SaveTemporaryPassword(\"password\", () => { throw new UnauthorizedAccessException(); });\n\n            // Assert\n            Assert.False(passwordSaved);\n        }\n\n        [Fact]\n        public void CheckPasswordReturnsTrueIfPasswordIsValid()\n        {\n            // Arrange\n            var ms = new MemoryStream();\n            var writer = new StreamWriter(ms);\n            writer.WriteLine(Crypto.HashPassword(\"password\"));\n            writer.Flush();\n            ms.Seek(0, SeekOrigin.Begin);\n\n            // Act\n            bool passwordIsValid = AdminSecurity.CheckPassword(\"password\", () => ms);\n\n            // Assert\n            Assert.True(passwordIsValid);\n\n            writer.Close();\n        }\n\n        [Fact]\n        public void HasAdminPasswordReturnsTrueIfAdminPasswordFileExists()\n        {\n            // Arrange\n            Mock<VirtualPathProvider> mockVpp = new Mock<VirtualPathProvider>();\n            mockVpp.Setup(m => m.FileExists(\"~/App_Data/Admin/Password.config\")).Returns(true);\n\n            // Act\n            bool hasPassword = AdminSecurity.HasAdminPassword(mockVpp.Object);\n\n            // Assert\n            Assert.True(hasPassword);\n        }\n\n        [Fact]\n        public void HasAdminPasswordReturnsFalseIfAdminPasswordFileDoesNotExists()\n        {\n            // Arrange\n            Mock<VirtualPathProvider> mockVpp = new Mock<VirtualPathProvider>();\n            mockVpp.Setup(m => m.FileExists(\"~/App_Data/Admin/Password.config\")).Returns(false);\n\n            // Act\n            bool hasPassword = AdminSecurity.HasAdminPassword(mockVpp.Object);\n\n            // Assert\n            Assert.False(hasPassword);\n        }\n\n        [Fact]\n        public void HasTemporaryPasswordReturnsTrueIfAdminPasswordFileExists()\n        {\n            // Arrange\n            Mock<VirtualPathProvider> mockVpp = new Mock<VirtualPathProvider>();\n            mockVpp.Setup(m => m.FileExists(\"~/App_Data/Admin/_Password.config\")).Returns(true);\n\n            // Act\n            bool hasPassword = AdminSecurity.HasTemporaryPassword(mockVpp.Object);\n\n            // Assert\n            Assert.True(hasPassword);\n        }\n\n        [Fact]\n        public void HasTemporaryPasswordReturnsFalseIfAdminPasswordFileDoesNotExists()\n        {\n            // Arrange\n            Mock<VirtualPathProvider> mockVpp = new Mock<VirtualPathProvider>();\n            mockVpp.Setup(m => m.FileExists(\"~/App_Data/Admin/_Password.config\")).Returns(false);\n\n            // Act\n            bool hasPassword = AdminSecurity.HasTemporaryPassword(mockVpp.Object);\n\n            // Assert\n            Assert.False(hasPassword);\n        }\n\n        [Fact]\n        public void NoPasswordOrTemporaryPasswordRedirectsToRegisterPage()\n        {\n            AssertSecure(requestUrl: \"~/\",\n                         passwordExists: false,\n                         temporaryPasswordExists: false,\n                         expectedUrl: \"~/_Admin/Register.cshtml?ReturnUrl=%7e%2f\");\n        }\n\n        [Fact]\n        public void IfPasswordExistsRedirectsToLoginPage()\n        {\n            AssertSecure(requestUrl: \"~/\",\n                         passwordExists: true,\n                         temporaryPasswordExists: false,\n                         expectedUrl: \"~/_Admin/Login.cshtml?ReturnUrl=%7e%2f\");\n        }\n\n        [Fact]\n        public void IfPasswordExistsRedirectsToLoginPageEvenIfTemporaryPasswordFileExists()\n        {\n            AssertSecure(requestUrl: \"~/\",\n                         passwordExists: true,\n                         temporaryPasswordExists: true,\n                         expectedUrl: \"~/_Admin/Login.cshtml?ReturnUrl=%7e%2f\");\n        }\n\n        [Fact]\n        public void IfTemporaryPasswordExistsRedirectsToInstructionsPage()\n        {\n            AssertSecure(requestUrl: \"~/\",\n                         passwordExists: false,\n                         temporaryPasswordExists: true,\n                         expectedUrl: \"~/_Admin/EnableInstructions.cshtml?ReturnUrl=%7e%2f\");\n        }\n\n        [Fact]\n        public void NoRedirectIfAlreadyGoingToRedirectPage()\n        {\n            AssertSecure(requestUrl: \"~/_Admin/Register.cshtml\",\n                         passwordExists: false,\n                         temporaryPasswordExists: false,\n                         expectedUrl: null);\n\n            AssertSecure(requestUrl: \"~/_Admin/Login.cshtml\",\n                         passwordExists: true,\n                         temporaryPasswordExists: false,\n                         expectedUrl: null);\n\n            AssertSecure(requestUrl: \"~/_Admin/EnableInstructions.cshtml\",\n                         passwordExists: false,\n                         temporaryPasswordExists: true,\n                         expectedUrl: null);\n        }\n\n        private static void AssertSecure(string requestUrl, bool passwordExists, bool temporaryPasswordExists, string expectedUrl)\n        {\n            // Arrange\n            var vpp = new Mock<VirtualPathProvider>();\n            if (temporaryPasswordExists)\n            {\n                vpp.Setup(m => m.FileExists(\"~/App_Data/Admin/_Password.config\")).Returns(true);\n            }\n\n            if (passwordExists)\n            {\n                vpp.Setup(m => m.FileExists(\"~/App_Data/Admin/Password.config\")).Returns(true);\n            }\n\n            string redirectUrl = null;\n            var response = new Mock<HttpResponseBase>();\n            response.Setup(m => m.Redirect(It.IsAny<string>())).Callback<string>(url => redirectUrl = url);\n            var request = new Mock<HttpRequestBase>();\n            request.Setup(m => m.QueryString).Returns(new NameValueCollection());\n            request.Setup(m => m.RawUrl).Returns(requestUrl);\n            var cookies = new HttpCookieCollection();\n            request.Setup(m => m.Cookies).Returns(cookies);\n            var context = new Mock<HttpContextBase>();\n            context.Setup(m => m.Request).Returns(request.Object);\n            context.Setup(m => m.Response).Returns(response.Object);\n            var startPage = new Mock<StartPage>() { CallBase = true };\n            var page = new Mock<WebPageRenderingBase>();\n            page.Setup(m => m.VirtualPath).Returns(requestUrl);\n            startPage.Object.ChildPage = page.Object;\n            page.Setup(m => m.Context).Returns(context.Object);\n\n            // Act\n            AdminSecurity.Authorize(startPage.Object, vpp.Object, MakeAppRelative);\n\n            // Assert\n            Assert.Equal(expectedUrl, redirectUrl);\n        }\n\n        private static string MakeAppRelative(string path)\n        {\n            return path;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Administration.Test/PackageManagerModuleTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.WebPages.Administration.PackageManager;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Administration.Test\n{\n    public class PackageManagerModuleTest\n    {\n        [Fact]\n        public void InitSourceFileDoesNotAffectSourcesFileWhenFeedIsNotNull()\n        {\n            // Arrange\n            bool sourceFileCalled = false;\n            var sourceFile = GetPackagesSourceFile();\n            sourceFile.Setup(s => s.Exists()).Returns(false);\n            sourceFile.Setup(s => s.WriteSources(It.IsAny<IEnumerable<WebPackageSource>>())).Callback(() => sourceFileCalled = true);\n            sourceFile.Setup(c => c.ReadSources()).Callback(() => sourceFileCalled = true);\n            ISet<WebPackageSource> set = new HashSet<WebPackageSource>();\n\n            // Act\n            PackageManagerModule.InitPackageSourceFile(sourceFile.Object, ref set);\n\n            // Assert\n            Assert.False(sourceFileCalled);\n        }\n\n        [Fact]\n        public void InitSourceFileWritesToDiskIfSourcesFileDoesNotExist()\n        {\n            // Arrange\n            ISet<WebPackageSource> set = null;\n            var sourceFile = GetPackagesSourceFile();\n            sourceFile.Setup(s => s.Exists()).Returns(false);\n            sourceFile.Setup(s => s.WriteSources(It.IsAny<IEnumerable<WebPackageSource>>()));\n\n            // Act\n            PackageManagerModule.InitPackageSourceFile(sourceFile.Object, ref set);\n\n            Assert.NotNull(set);\n            Assert.Equal(2, set.Count());\n            Assert.Equal(\"http://go.microsoft.com/fwlink/?LinkID=226946\", set.First().Source);\n            Assert.Equal(\"http://go.microsoft.com/fwlink/?LinkID=226948\", set.Last().Source);\n        }\n\n        [Fact]\n        public void InitSourceFileReadsFromDiskWhenFileAlreadyExists()\n        {\n            // Arrange\n            var sourceFile = GetPackagesSourceFile();\n            sourceFile.Setup(s => s.Exists()).Returns(true);\n            ISet<WebPackageSource> set = null;\n\n            // Act\n            PackageManagerModule.InitPackageSourceFile(sourceFile.Object, ref set);\n\n            // Assert\n            Assert.NotNull(set);\n            Assert.Equal(2, set.Count());\n        }\n\n        [Fact]\n        public void AddFeedWritesSourceIfItDoesNotExist()\n        {\n            // Arrange\n            bool writeCalled = false;\n            var sourceFile = GetPackagesSourceFile();\n            sourceFile.Setup(c => c.WriteSources(It.IsAny<IEnumerable<WebPackageSource>>())).Callback(() => writeCalled = true);\n            ISet<WebPackageSource> set = new HashSet<WebPackageSource>(GetSources());\n\n            // Act\n            bool returnValue = PackageManagerModule.AddPackageSource(sourceFile.Object, set, new WebPackageSource(source: \"http://www.microsoft.com/feed3\", name: \"Feed3\"));\n\n            // Assert\n            Assert.Equal(3, set.Count());\n            Assert.True(writeCalled);\n            Assert.True(returnValue);\n        }\n\n        [Fact]\n        public void AddFeedDoesNotWritesSourceIfExists()\n        {\n            // Arrange\n            bool writeCalled = false;\n            var sourceFile = GetPackagesSourceFile();\n            sourceFile.Setup(c => c.WriteSources(It.IsAny<IEnumerable<WebPackageSource>>())).Callback(() => writeCalled = true);\n            ISet<WebPackageSource> set = new HashSet<WebPackageSource>(GetSources());\n\n            // Act\n            bool returnValue = PackageManagerModule.AddPackageSource(sourceFile.Object, set, new WebPackageSource(source: \"http://www.microsoft.com/feed1\", name: \"Feed1\"));\n\n            // Assert\n            Assert.Equal(2, set.Count());\n            Assert.False(writeCalled);\n            Assert.False(returnValue);\n        }\n\n        [Fact]\n        public void RemoveFeedRemovesSourceFromSet()\n        {\n            // Arrange\n            bool writeCalled = false;\n            var sourceFile = GetPackagesSourceFile();\n            sourceFile.Setup(c => c.WriteSources(It.IsAny<IEnumerable<WebPackageSource>>())).Callback(() => writeCalled = true);\n            ISet<WebPackageSource> set = new HashSet<WebPackageSource>(GetSources());\n\n            // Act\n            PackageManagerModule.RemovePackageSource(sourceFile.Object, set, \"feed1\");\n\n            // Assert\n            Assert.Single(set);\n            Assert.DoesNotContain(set, s => s.Name == \"Feed1\");\n            Assert.True(writeCalled);\n        }\n\n        [Fact]\n        public void RemoveFeedDoesNotAffectSourceFileIsFeedDoesNotExist()\n        {\n            // Arrange\n            bool writeCalled = false;\n            var sourceFile = GetPackagesSourceFile();\n            sourceFile.Setup(c => c.WriteSources(It.IsAny<IEnumerable<WebPackageSource>>())).Callback(() => writeCalled = true);\n            ISet<WebPackageSource> set = new HashSet<WebPackageSource>(GetSources());\n\n            // Act\n            PackageManagerModule.RemovePackageSource(sourceFile.Object, set, \"feed3\");\n\n            // Assert\n            Assert.Equal(2, set.Count());\n            Assert.False(writeCalled);\n        }\n\n        private static Mock<IPackagesSourceFile> GetPackagesSourceFile()\n        {\n            var sourceFile = new Mock<IPackagesSourceFile>();\n            sourceFile.Setup(c => c.ReadSources()).Returns(GetSources());\n            return sourceFile;\n        }\n\n        private static IEnumerable<WebPackageSource> GetSources()\n        {\n            return new[]\n            {\n                new WebPackageSource(name: \"Feed1\", source: \"http://www.microsoft.com/feed1\"),\n                new WebPackageSource(name: \"Feed2\", source: \"http://www.microsoft.com/feed2\")\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Administration.Test/PackagesSourceFileTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Web.WebPages.Administration.PackageManager;\nusing System.Xml.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Administration.Test\n{\n    public class PackagesSourceFileTest\n    {\n        [Fact]\n        public void PackagesSourceFileThrowsIfTheXmlElementDoesNotContainNameAndUrl()\n        {\n            // Arrange\n            var element = new XElement(\"source\");\n\n            // Act and Assert\n            Assert.Throws<FormatException>(() => PackageSourceFile.ParsePackageSource(element));\n        }\n\n        [Fact]\n        public void PackagesSourceFileThrowsIfTheXmlElementDoesNotContainUrl()\n        {\n            // Arrange\n            var element = new XElement(\"source\", new XAttribute(\"displayname\", \"foo\"), new XAttribute(\"filterpreferred\", false));\n\n            // Act and Assert\n            Assert.Throws<FormatException>(() => PackageSourceFile.ParsePackageSource(element));\n        }\n\n        [Fact]\n        public void PackagesSourceFileThrowsIfTheXmlElementDoesNotContainName()\n        {\n            // Arrange\n            var element = new XElement(\"source\", new XAttribute(\"url\", \"http://microsoft.com\"), new XAttribute(\"filterpreferred\", false));\n\n            // Act and Assert\n            Assert.Throws<FormatException>(() => PackageSourceFile.ParsePackageSource(element));\n        }\n\n        [Fact]\n        public void PackagesSourceFileDoesNotThrowIfXmlElementDoesNotContainPreferred()\n        {\n            // Arrange\n            var element = new XElement(\"source\", new XAttribute(\"displayname\", \"foo\"), new XAttribute(\"url\", \"http://microsoft.com\"));\n\n            // Act \n            var item = PackageSourceFile.ParsePackageSource(element);\n\n            // Assert\n            Assert.NotNull(item);\n        }\n\n        [Fact]\n        public void PackagesSourceFileThrowsIfTheFeedUrlIsMalformed()\n        {\n            // Arrange\n            var element = new XElement(\"source\",\n                                       new XAttribute(\"displayname\", \"foo\"),\n                                       new XAttribute(\"url\", \"bad-url.com\"),\n                                       new XAttribute(\"filterpreferred\", false)\n                );\n\n            // Act and Assert\n            Assert.Throws<FormatException>(() => PackageSourceFile.ParsePackageSource(element));\n        }\n\n        [Fact]\n        public void PackagesSourceFileParsesXElement()\n        {\n            // Arrange\n            var element = new XElement(\"source\",\n                                       new XAttribute(\"displayname\", \"foo\"),\n                                       new XAttribute(\"url\", \"http://www.microsoft.com\"),\n                                       new XAttribute(\"filterpreferred\", true)\n                );\n\n            // Act \n            var WebPackageSource = PackageSourceFile.ParsePackageSource(element);\n\n            // Assert\n            Assert.Equal(\"foo\", WebPackageSource.Name);\n            Assert.Equal(\"http://www.microsoft.com\", WebPackageSource.Source);\n            Assert.True(WebPackageSource.FilterPreferredPackages);\n        }\n\n        [Fact]\n        public void PackagesSourceFileReadsAllFeedsFromStream()\n        {\n            // Arrange\n            var document = new XDocument(\n                new XElement(\"sources\",\n                             new XElement(\"source\", new XAttribute(\"displayname\", \"Feed1\"), new XAttribute(\"url\", \"http://www.microsoft.com/feed1\"), new XAttribute(\"filterpreferred\", true)),\n                             new XElement(\"source\", new XAttribute(\"displayname\", \"Feed2\"), new XAttribute(\"url\", \"http://www.microsoft.com/feed2\"), new XAttribute(\"filterpreferred\", true))\n                    ));\n            var stream = new MemoryStream();\n            document.Save(stream);\n            stream = new MemoryStream(stream.ToArray());\n            string xml = new StreamReader(stream).ReadToEnd().TrimEnd('\\0');\n\n            // Act \n            var result = PackageSourceFile.ReadFeeds(() => new MemoryStream(Encoding.Default.GetBytes(xml)));\n\n            // Assert\n            Assert.Equal(2, result.Count());\n            Assert.Equal(\"Feed1\", result.First().Name);\n            Assert.Equal(\"Feed2\", result.Last().Name);\n        }\n\n        [Fact]\n        public void PackagesSourceFileWritesAllFeedsToStream()\n        {\n            // Arrange\n            var packagesSources = new[]\n            {\n                new WebPackageSource(name: \"Feed1\", source: \"http://www.microsoft.com/Feed1\"),\n                new WebPackageSource(name: \"Feed2\", source: \"http://www.microsoft.com/Feed2\") { FilterPreferredPackages = true }\n            };\n            var stream = new MemoryStream();\n\n            // Act\n            PackageSourceFile.WriteFeeds(packagesSources, () => stream);\n            stream = new MemoryStream(stream.ToArray());\n            string result = new StreamReader(stream).ReadToEnd().TrimEnd('\\0');\n\n            // Assert\n            var document = XDocument.Parse(result);\n            Assert.Equal(\"sources\", document.Root.Name);\n            Assert.Equal(2, document.Root.Elements().Count());\n\n            var firstFeed = document.Root.Elements().First();\n            Assert.Equal(\"source\", firstFeed.Name);\n            Assert.Equal(\"Feed1\", firstFeed.Attribute(\"displayname\").Value);\n            Assert.Equal(\"http://www.microsoft.com/Feed1\", firstFeed.Attribute(\"url\").Value);\n            Assert.Equal(\"false\", firstFeed.Attribute(\"filterpreferred\").Value);\n\n            var secondFeed = document.Root.Elements().Last();\n            Assert.Equal(\"source\", secondFeed.Name);\n            Assert.Equal(\"Feed2\", secondFeed.Attribute(\"displayname\").Value);\n            Assert.Equal(\"http://www.microsoft.com/Feed2\", secondFeed.Attribute(\"url\").Value);\n            Assert.Equal(\"true\", secondFeed.Attribute(\"filterpreferred\").Value);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Administration.Test/PageUtilsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Web.WebPages.Administration.PackageManager;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Administration.Test\n{\n    public class PageUtilsTest\n    {\n        [Fact]\n        public void GetFilterValueReturnsNullIfValueWasNotFound()\n        {\n            // Arrange\n            var request = new Mock<HttpRequestBase>();\n            request.Setup(c => c.QueryString).Returns(new NameValueCollection());\n            request.Setup(c => c.Cookies).Returns(new HttpCookieCollection());\n\n            // Act\n            var value = PageUtils.GetFilterValue(request.Object, \"foo\", \"my-key\");\n\n            // Assert\n            Assert.Null(value);\n        }\n\n        [Fact]\n        public void GetFilterValueReturnsValueFromCookieIfQueryStringDoesNotContainKey()\n        {\n            // Arrange\n            const string key = \"my-key\";\n            const string value = \"my-cookie-value\";\n            var request = new Mock<HttpRequestBase>();\n            request.Setup(c => c.QueryString).Returns(new NameValueCollection());\n            var cookies = new HttpCookieCollection();\n            var cookie = new HttpCookie(\"foo\");\n            cookie[key] = value;\n            cookies.Add(cookie);\n            request.Setup(c => c.Cookies).Returns(cookies);\n\n            // Act\n            var returnedValue = PageUtils.GetFilterValue(request.Object, \"foo\", key);\n\n            // Assert\n            Assert.Equal(value, returnedValue);\n        }\n\n        [Fact]\n        public void GetFilterValueReturnsValueFromQueryString()\n        {\n            // Arrange\n            const string key = \"my-key\";\n            const string requestValue = \"my-request-value\";\n            const string cookieValue = \"my-cookie-value\";\n            var request = new Mock<HttpRequestBase>();\n            var queryString = new NameValueCollection();\n            queryString[key] = requestValue;\n            request.Setup(c => c.QueryString).Returns(queryString);\n            var cookies = new HttpCookieCollection();\n            var cookie = new HttpCookie(\"foo\");\n            cookie[key] = cookieValue;\n            request.Setup(c => c.Cookies).Returns(cookies);\n\n            // Act\n            var returnedValue = PageUtils.GetFilterValue(request.Object, \"foo\", key);\n\n            // Assert\n            Assert.Equal(requestValue, returnedValue);\n        }\n\n        [Fact]\n        public void PersistFilterCreatesCookieIfItDoesNotExist()\n        {\n            // Arrange\n            var cookies = new HttpCookieCollection();\n            var response = new Mock<HttpResponseBase>();\n            response.Setup(c => c.Cookies).Returns(cookies);\n\n            // Act\n            PageUtils.PersistFilter(response.Object, \"my-cookie\", new Dictionary<string, string>());\n\n            // Assert\n            Assert.NotNull(cookies[\"my-cookie\"]);\n        }\n\n        [Fact]\n        public void PersistFilterUsesExistingCookie()\n        {\n            // Arrange\n            var cookieName = \"my-cookie\";\n            var cookies = new HttpCookieCollection();\n            cookies.Add(new HttpCookie(cookieName));\n            var response = new Mock<HttpResponseBase>();\n            response.Setup(c => c.Cookies).Returns(cookies);\n\n            // Act\n            PageUtils.PersistFilter(response.Object, \"my-cookie\", new Dictionary<string, string>());\n\n            // Assert\n            Assert.Single(cookies);\n        }\n\n        [Fact]\n        public void PersistFilterAddsDictionaryEntriesToCookie()\n        {\n            // Arrange\n            var cookies = new HttpCookieCollection();\n            var response = new Mock<HttpResponseBase>();\n            response.Setup(c => c.Cookies).Returns(cookies);\n\n            // Act\n            PageUtils.PersistFilter(response.Object, \"my-cookie\", new Dictionary<string, string>() { { \"a\", \"b\" }, { \"x\", \"y\" } });\n\n            // Assert\n            var cookie = cookies[\"my-cookie\"];\n            Assert.Equal(\"b\", cookie[\"a\"]);\n            Assert.Equal(\"y\", cookie[\"x\"]);\n        }\n\n        [Fact]\n        public void IsValidLicenseUrlReturnsTrueForHttpUris()\n        {\n            // Arrange\n            var uri = new Uri(\"http://www.microsoft.com\");\n\n            // Act and Assert\n            Assert.True(PageUtils.IsValidLicenseUrl(uri));\n        }\n\n        [Fact]\n        public void IsValidLicenseUrlReturnsTrueForHttpsUris()\n        {\n            // Arrange\n            var uri = new Uri(\"HTTPs://www.asp.net\");\n\n            // Act and Assert\n            Assert.True(PageUtils.IsValidLicenseUrl(uri));\n        }\n\n        [Fact]\n        public void IsValidLicenseUrlReturnsFalseForNonHttpUris()\n        {\n            // Arrange\n            var jsUri = new Uri(\"javascript:alert('Hello world');\");\n            var fileShareUri = new Uri(@\"c:\\windows\\system32\\notepad.exe\");\n            var mailToUti = new Uri(\"mailto:invalid-email@microsoft.com\");\n\n            // Act and Assert\n            Assert.False(PageUtils.IsValidLicenseUrl(jsUri));\n            Assert.False(PageUtils.IsValidLicenseUrl(fileShareUri));\n            Assert.False(PageUtils.IsValidLicenseUrl(mailToUti));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Administration.Test/PreApplicationStartCodeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Administration.Test\n{\n    public class PreApplicationStartCodeTest\n    {\n        [Fact]\n        public void StartTest()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                var adminPackageAssembly = typeof(PreApplicationStartCode).Assembly;\n                AppDomainUtils.SetPreAppStartStage();\n                PreApplicationStartCode.Start();\n                // Call a second time to ensure multiple calls do not cause issues\n                PreApplicationStartCode.Start();\n\n                // TODO: Need a way to see if the module was actually registered\n                var registeredAssemblies = ApplicationPart.GetRegisteredParts().ToList();\n                ApplicationPart part = Assert.Single(registeredAssemblies);\n                part.Assembly.Equals(adminPackageAssembly);\n            });\n        }\n\n        [Fact]\n        public void TestPreAppStartClass()\n        {\n            PreAppStartTestHelper.TestPreAppStartClass(typeof(PreApplicationStartCode));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Administration.Test/RemoteAssemblyTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Web.WebPages.Administration.PackageManager;\nusing Microsoft.TestCommon;\nusing Moq;\nusing NuGet.Runtime;\n\nnamespace System.Web.WebPages.Administration.Test\n{\n    public class RemoteAssemblyTest\n    {\n        [Fact]\n        public void GetAssembliesForBindingRedirectReturnsEmptySequenceIfNoBinAssembliesAreFound()\n        {\n            // Act\n            var assemblies = RemoteAssembly.GetAssembliesForBindingRedirect(AppDomain.CurrentDomain, @\"x:\\site\\bin\", (_, __) => Enumerable.Empty<IAssembly>());\n\n            // Assert\n            Assert.Empty(assemblies);\n        }\n\n        [Fact]\n        public void RemoteAssemblyComparesById()\n        {\n            // Arrange\n            var assemblyA = new RemoteAssembly(\"A\", null, null, null);\n            var assemblyB = new Mock<IAssembly>(MockBehavior.Strict);\n            assemblyB.SetupGet(b => b.Name).Returns(\"Z\").Verifiable();\n\n            // Act\n            var result = RemoteAssembly.Compare(assemblyA, assemblyB.Object);\n\n            // Assert\n            Assert.Equal(-25, result);\n            assemblyB.Verify();\n        }\n\n        [Fact]\n        public void RemoteAssemblyComparesByVersionIfIdsAreIdentical()\n        {\n            // Arrange\n            var assemblyA = new RemoteAssembly(\"A\", new Version(\"2.0.0.0\"), null, null);\n            var assemblyB = new Mock<IAssembly>(MockBehavior.Strict);\n            assemblyB.SetupGet(b => b.Name).Returns(\"A\").Verifiable();\n            assemblyB.SetupGet(b => b.Version).Returns(new Version(\"1.0.0.0\")).Verifiable();\n\n            // Act\n            var result = RemoteAssembly.Compare(assemblyA, assemblyB.Object);\n\n            // Assert\n            Assert.Equal(1, result);\n            assemblyB.Verify();\n        }\n\n        [Fact]\n        public void RemoteAssemblyComparesByPublicKeyIfIdsAndVersionAreIdentical()\n        {\n            // Arrange\n            var assemblyA = new RemoteAssembly(\"A\", new Version(\"1.0.0.0\"), \"C\", null);\n            var assemblyB = new Mock<IAssembly>(MockBehavior.Strict);\n            assemblyB.SetupGet(b => b.Name).Returns(\"A\").Verifiable();\n            assemblyB.SetupGet(b => b.Version).Returns(new Version(\"1.0.0.0\")).Verifiable();\n            assemblyB.SetupGet(b => b.PublicKeyToken).Returns(\"E\").Verifiable();\n\n            // Act\n            var result = RemoteAssembly.Compare(assemblyA, assemblyB.Object);\n\n            // Assert\n            Assert.Equal(-2, result);\n            assemblyB.Verify();\n        }\n\n        [Fact]\n        public void RemoteAssemblyComparesByCultureIfIdVersionAndPublicKeyAreIdentical()\n        {\n            // Arrange\n            var assemblyA = new RemoteAssembly(\"A\", new Version(\"1.0.0.0\"), \"public-key\", \"en-us\");\n            var assemblyB = new Mock<IAssembly>(MockBehavior.Strict);\n            assemblyB.SetupGet(b => b.Name).Returns(\"A\").Verifiable();\n            assemblyB.SetupGet(b => b.Version).Returns(new Version(\"1.0.0.0\")).Verifiable();\n            assemblyB.SetupGet(b => b.PublicKeyToken).Returns(\"public-key\").Verifiable();\n            assemblyB.SetupGet(b => b.Culture).Returns(\"en-uk\").Verifiable();\n\n            // Act\n            var result = RemoteAssembly.Compare(assemblyA, assemblyB.Object);\n\n            // Assert\n            Assert.Equal(8, result);\n            assemblyB.Verify();\n        }\n\n        [Fact]\n        public void RemoteAssemblyReturns0IfAllValuesAreIdentical()\n        {\n            // Arrange\n            var assemblyA = new RemoteAssembly(\"A\", new Version(\"1.0.0.0\"), \"public-key\", \"en-us\");\n            var assemblyB = new RemoteAssembly(\"A\", new Version(\"1.0.0.0\"), \"public-key\", \"en-us\");\n\n            // Act\n            var result = RemoteAssembly.Compare(assemblyA, assemblyB);\n\n            // Assert\n            Assert.Equal(0, result);\n        }\n\n        [Fact]\n        public void RemoteAssemblyReturns1IfValueToBeComparedToIsNull()\n        {\n            // Arrange\n            RemoteAssembly assemblyA = new RemoteAssembly(\"A\", new Version(\"1.0.0.0\"), \"public-key\", \"en-us\");\n            RemoteAssembly assemblyB = null;\n\n            // Act\n            var result = assemblyA.CompareTo(assemblyB);\n\n            // Assert\n            Assert.Equal(1, result);\n        }\n\n        [Fact]\n        public void EqualReturnsTrueIfValuesAreIdentical()\n        {\n            // Arrange\n            var assemblyA = new RemoteAssembly(\"A\", new Version(\"1.0.0.0\"), \"public-key\", \"en-us\");\n            var assemblyB = new RemoteAssembly(\"A\", new Version(\"1.0.0.0\"), \"public-key\", \"en-us\");\n\n            // Act\n            var result = assemblyA.Equals(assemblyB);\n\n            // Assert\n            Assert.True(result);\n        }\n\n        [Fact]\n        public void EqualReturnsFalseIfValuesAreNotIdentical()\n        {\n            // Arrange\n            var assemblyA = new RemoteAssembly(\"A\", new Version(\"1.0.0.0\"), \"public-key\", \"en-us\");\n            var assemblyB = new RemoteAssembly(\"A\", new Version(\"1.0.0.1\"), \"public-key\", \"en-us\");\n\n            // Act\n            var result = assemblyA.Equals(assemblyB);\n\n            // Assert\n            Assert.False(result);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Administration.Test/System.Web.WebPages.Administration.Test.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props\" Condition=\"Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" />\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" />\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{21C729D6-ECF8-47EF-A236-7C6A4272EAF0}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>System.Web.WebPages.Administration.Test</RootNamespace>\n    <AssemblyName>System.Web.WebPages.Administration.Test</AssemblyName>\n    <OutputPath>..\\..\\bin\\$(Configuration)\\Test\\</OutputPath>\n    <NuGetPackageImportStamp>\n    </NuGetPackageImportStamp>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Castle.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Castle.Core.5.1.1\\lib\\net462\\Castle.Core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"Moq, Version=4.18.0.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Moq.4.18.4\\lib\\net462\\Moq.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"NuGet.Core, Version=1.6.30117.9648, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL\">\n      <Private>True</Private>\n      <HintPath>..\\..\\packages\\Nuget.Core.1.6.2\\lib\\net40\\NuGet.Core.dll</HintPath>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Core\">\n      <RequiredTargetFramework>3.5</RequiredTargetFramework>\n    </Reference>\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"System.XML\" />\n    <Reference Include=\"System.Xml.Linq\" />\n    <Reference Include=\"xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.abstractions.2.0.3\\lib\\net35\\xunit.abstractions.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.assert, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.assert.2.4.2\\lib\\netstandard1.1\\xunit.assert.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.core, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.core.2.4.2\\lib\\net452\\xunit.core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.execution.desktop, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.execution.2.4.2\\lib\\net452\\xunit.execution.desktop.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n  </ItemGroup>\n  <ItemGroup>\n    <CodeAnalysisDependentAssemblyPaths Condition=\" '$(VS100COMNTOOLS)' != '' \" Include=\"$(VS100COMNTOOLS)..\\IDE\\PrivateAssemblies\">\n      <Visible>False</Visible>\n    </CodeAnalysisDependentAssemblyPaths>\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.WebPages.Administration\\System.Web.WebPages.Administration.csproj\">\n      <Project>{C23F02FC-4538-43F5-ABBA-38BA069AEA8F}</Project>\n      <Name>System.Web.WebPages.Administration</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Helpers\\System.Web.Helpers.csproj\">\n      <Project>{9B7E3740-6161-4548-833C-4BBCA43B970E}</Project>\n      <Name>System.Web.Helpers</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.WebPages\\System.Web.WebPages.csproj\">\n      <Project>{76EFA9C5-8D7E-4FDF-B710-E20F8B6B00D2}</Project>\n      <Name>System.Web.WebPages</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\">\n      <Project>{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}</Project>\n      <Name>Microsoft.TestCommon</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"AdminPackageTest.cs\" />\n    <Compile Include=\"PackageManagerModuleTest.cs\" />\n    <Compile Include=\"PackagesSourceFileTest.cs\" />\n    <Compile Include=\"PageUtilsTest.cs\" />\n    <Compile Include=\"PreApplicationStartCodeTest.cs\" />\n    <Compile Include=\"RemoteAssemblyTest.cs\" />\n    <Compile Include=\"WebProjectManagerTest.cs\" />\n    <Compile Include=\"WebProjectSystemTest.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Service Include=\"{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Analyzer Include=\"..\\..\\packages\\xunit.analyzers.1.1.0\\analyzers\\dotnet\\cs\\xunit.analyzers.dll\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\n  <Target Name=\"EnsureNuGetPackageBuildImports\" BeforeTargets=\"PrepareForBuild\">\n    <PropertyGroup>\n      <ErrorText>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}.</ErrorText>\n    </PropertyGroup>\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props'))\" />\n  </Target>\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" />\n</Project>"
  },
  {
    "path": "test/System.Web.WebPages.Administration.Test/WebProjectManagerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.WebPages.Administration.PackageManager;\nusing Microsoft.TestCommon;\nusing Moq;\nusing NuGet;\n\nnamespace System.Web.WebPages.Administration.Test\n{\n    public class WebPackageManagerTest\n    {\n        [Fact]\n        public void ConstructorThrowsIfRemoteSourceIsNullOrEmpty()\n        {\n            // Act and Assert\n            Assert.ThrowsArgumentNullOrEmptyString(() => new WebProjectManager((string)null, \"foo\"), \"remoteSource\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => new WebProjectManager(\"\", @\"D:\\baz\"), \"remoteSource\");\n        }\n\n        [Fact]\n        public void ConstructorThrowsIfSiteRootIsNullOrEmpty()\n        {\n            // Act and Assert\n            Assert.ThrowsArgumentNullOrEmptyString(() => new WebProjectManager(\"foo\", null), \"siteRoot\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => new WebProjectManager(\"foo\", \"\"), \"siteRoot\");\n        }\n\n        [Fact]\n        public void AllowInstallingPackageWithToolsFolderDoNotThrow()\n        {\n            // Arrange\n            var projectManager = new Mock<IProjectManager>();\n            projectManager.Setup(p => p.AddPackageReference(\"A\", new SemanticVersion(\"1.0\"), false, false)).Verifiable();\n\n            var webProjectManager = new WebProjectManager(projectManager.Object, @\"x:\\\")\n            {\n                DoNotAddBindingRedirects = true\n            };\n\n            var packageFile1 = new Mock<IPackageFile>();\n            packageFile1.Setup(p => p.Path).Returns(\"tools\\\\install.ps1\");\n\n            var packageFile2 = new Mock<IPackageFile>();\n            packageFile2.Setup(p => p.Path).Returns(\"content\\\\A.txt\");\n\n            var package = new Mock<IPackage>();\n            package.Setup(p => p.Id).Returns(\"A\");\n            package.Setup(p => p.Version).Returns(new SemanticVersion(\"1.0\"));\n            package.Setup(p => p.GetFiles()).Returns(new[] { packageFile1.Object, packageFile2.Object });\n\n            // Act\n            webProjectManager.InstallPackage(package.Object, appDomain: null);\n\n            // Assert\n            projectManager.Verify();\n        }\n\n        [Fact]\n        public void GetLocalRepositoryReturnsPackagesFolderUnderAppData()\n        {\n            // Arrange\n            var siteRoot = \"my-site\";\n\n            // Act\n            var repositoryFolder = WebProjectManager.GetWebRepositoryDirectory(siteRoot);\n\n            Assert.Equal(@\"my-site\\App_Data\\packages\", repositoryFolder);\n        }\n\n        [Fact]\n        public void GetPackagesReturnsAllItemsWhenNoSearchTermIsIncluded()\n        {\n            // Arrange\n            var repository = GetRepository();\n\n            // Act\n            var result = WebProjectManager.GetPackages(repository, String.Empty);\n\n            // Assert\n            Assert.Equal(3, result.Count());\n        }\n\n        [Fact]\n        public void GetPackagesReturnsItemsContainingSomeSearchToken()\n        {\n            // Arrange\n            var repository = GetRepository();\n\n            // Act\n            var result = WebProjectManager.GetPackages(repository, \"testing .NET\");\n            var package = result.SingleOrDefault();\n\n            // Assert\n            Assert.NotNull(package);\n            Assert.Equal(\"A\", package.Id);\n        }\n\n        [Fact]\n        public void GetPackagesWithLicenseReturnsAllDependenciesWithRequiresAcceptance()\n        {\n            // Arrange\n            var remoteRepository = GetRepository();\n            var localRepository = new Mock<IPackageRepository>().Object;\n\n            // Act\n            var package = remoteRepository.GetPackages().Find(\"C\").SingleOrDefault();\n            var result = WebProjectManager.GetPackagesRequiringLicenseAcceptance(package, localRepository, remoteRepository);\n\n            // Assert\n            Assert.Equal(2, result.Count());\n            Assert.Contains(result, c => c.Id == \"C\");\n            Assert.Contains(result, c => c.Id == \"B\");\n        }\n\n        [Fact]\n        public void GetPackagesWithLicenseReturnsEmptyResultForPackageThatDoesNotRequireLicenses()\n        {\n            // Arrange\n            var remoteRepository = GetRepository();\n            var localRepository = new Mock<IPackageRepository>().Object;\n\n            // Act\n            var package = remoteRepository.GetPackages().Find(\"A\").SingleOrDefault();\n            var result = WebProjectManager.GetPackagesRequiringLicenseAcceptance(package, localRepository, remoteRepository);\n\n            // Assert\n            Assert.False(result.Any());\n        }\n\n        private static IPackageRepository GetRepository()\n        {\n            Mock<IPackageRepository> repository = new Mock<IPackageRepository>();\n            var packages = new[]\n            {\n                GetPackage(\"A\", desc: \"testing\"),\n                GetPackage(\"B\", version: \"1.1\", requiresLicense: true),\n                GetPackage(\"C\", requiresLicense: true, dependencies: new[]\n                {\n                    new PackageDependency(\"B\", new VersionSpec { MinVersion = new SemanticVersion(\"1.0\") })\n                })\n            };\n            repository.Setup(c => c.GetPackages()).Returns(packages.AsQueryable());\n\n            return repository.Object;\n        }\n\n        private static IPackage GetPackage(string id, string version = \"1.0\", string desc = null, bool requiresLicense = false, IEnumerable<PackageDependency> dependencies = null)\n        {\n            Mock<IPackage> package = new Mock<IPackage>();\n            package.SetupGet(c => c.Id).Returns(id);\n            package.SetupGet(c => c.Version).Returns(SemanticVersion.Parse(version));\n            package.SetupGet(c => c.Description).Returns(desc ?? id);\n            package.SetupGet(c => c.RequireLicenseAcceptance).Returns(requiresLicense);\n            package.SetupGet(c => c.LicenseUrl).Returns(new Uri(\"http://www.\" + id + \".com\"));\n            package.SetupGet(c => c.Dependencies).Returns(dependencies ?? Enumerable.Empty<PackageDependency>());\n            return package.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Administration.Test/WebProjectSystemTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Web.WebPages.Administration.PackageManager;\nusing System.Xml.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\nusing NuGet;\n\nnamespace System.Web.WebPages.Administration.Test\n{\n    public class WebProjectSystemTest\n    {\n        [Fact]\n        public void ResolvePathReturnsAppCodePathIfPathIsSourceFile()\n        {\n            // Arrange\n            var path = \"Foo.cs\";\n            var webProjectSystem = new WebProjectSystem(@\"x:\\\");\n\n            // Act\n            var resolvedPath = webProjectSystem.ResolvePath(path);\n\n            // Assert\n            Assert.Equal(@\"App_Code\\Foo.cs\", resolvedPath);\n        }\n\n        [Fact]\n        public void ResolvePathReturnsOriginalPathIfSourceFilePathIsAlreadyUnderAppCode()\n        {\n            // Arrange\n            var path = @\"App_Code\\Foo.cs\";\n            var webProjectSystem = new WebProjectSystem(@\"x:\\\");\n\n            // Act\n            var resolvedPath = webProjectSystem.ResolvePath(path);\n\n            // Assert\n            Assert.Equal(path, resolvedPath);\n        }\n\n        [Fact]\n        public void ResolvePathReturnsOriginalPathIfFileIsNotSource()\n        {\n            // Arrange\n            var path = @\"Foo.js\";\n            var webProjectSystem = new WebProjectSystem(@\"x:\\\");\n\n            // Act\n            var resolvedPath = webProjectSystem.ResolvePath(path);\n\n            // Assert\n            Assert.Equal(path, resolvedPath);\n        }\n\n        [Fact]\n        public void AddPackageWithFrameworkReferenceCreatesWebConfigIfItDoesNotExist()\n        {\n            // Arrange\n            string webConfigPath = @\"x:\\my-website\\web.config\";\n            MemoryStream memoryStream = new MemoryStream();\n\n            var fileSystem = new Mock<IFileSystem>();\n            fileSystem.SetupGet(f => f.Root).Returns(\"x:\\\\my-website\");\n            fileSystem.Setup(f => f.FileExists(It.Is<string>(p => p.Equals(webConfigPath)))).Returns(false).Verifiable();\n            fileSystem.Setup(f => f.AddFile(It.Is<string>(p => p.Equals(webConfigPath)), It.IsAny<Stream>()))\n                .Callback<string, Stream>((_, s) => { s.CopyTo(memoryStream); });\n\n            var references = \"System\";\n\n            // Act\n            WebProjectSystem.AddReferencesToConfig(fileSystem.Object, references);\n\n            // Assert\n            memoryStream.Seek(0, SeekOrigin.Begin);\n            XDocument document = XDocument.Load(memoryStream);\n\n            var element = document.Root;\n            Assert.Equal(\"configuration\", element.Name);\n\n            // Use SingleOrDefault to ensure there's exactly one element with that name\n            var assemblies = document.Root\n                .Elements().SingleOrDefault(e => e.Name.ToString().Equals(\"system.web\"))\n                .Elements().SingleOrDefault(e => e.Name.ToString().Equals(\"compilation\"))\n                .Elements().SingleOrDefault(e => e.Name.ToString().Equals(\"assemblies\"));\n\n            Assert.Equal(references, assemblies.Elements().First().Attribute(\"assembly\").Value);\n        }\n\n        [Fact]\n        public void AddPackageWithFrameworkReferenceCreatesWebConfigIfItExistsWithoutAssembliesNode()\n        {\n            // Arrange\n            var webConfigPath = @\"x:\\my-website\\web.config\";\n            var webConfigContent = @\"<?xml version=\"\"1.0\"\"?>\n                <configuration>\n                    <connectionStrings>\n                        <add name=\"\"test\"\" />\n                    </connectionStrings>\n                    <system.web>\n                        <profiles><add name=\"\"awesomeprofile\"\" /></profiles>\n                    </system.web>\n                </configuration>\n\n\".AsStream();\n            MemoryStream memoryStream = new MemoryStream();\n\n            var fileSystem = new Mock<IFileSystem>();\n            fileSystem.SetupGet(f => f.Root).Returns(\"x:\\\\my-website\");\n            fileSystem.Setup(f => f.FileExists(It.Is<string>(p => p.Equals(webConfigPath)))).Returns(true).Verifiable();\n            fileSystem.Setup(f => f.OpenFile(It.Is<string>(p => p.Equals(webConfigPath)))).Returns(webConfigContent);\n            fileSystem.Setup(f => f.AddFile(It.Is<string>(p => p.Equals(webConfigPath)), It.IsAny<Stream>()))\n                .Callback<string, Stream>((_, s) => { s.CopyTo(memoryStream); });\n\n            var references = \"System.Data\";\n\n            // Act\n            WebProjectSystem.AddReferencesToConfig(fileSystem.Object, references);\n\n            // Assert\n            memoryStream.Seek(0, SeekOrigin.Begin);\n            XDocument document = XDocument.Load(memoryStream);\n\n            var element = document.Root;\n            Assert.Equal(\"configuration\", element.Name);\n\n            // Use SingleOrDefault to ensure there's exactly one element with that name\n            var assemblies = document.Root\n                .Elements().SingleOrDefault(e => e.Name.ToString().Equals(\"system.web\"))\n                .Elements().SingleOrDefault(e => e.Name.ToString().Equals(\"compilation\"))\n                .Elements().SingleOrDefault(e => e.Name.ToString().Equals(\"assemblies\"));\n\n            Assert.Equal(references, assemblies.Elements().First().Attribute(\"assembly\").Value);\n\n            // Make sure the original web.config content is unaffected\n            Assert.Equal(\"test\", document.Root\n                                     .Elements().SingleOrDefault(e => e.Name.ToString().Equals(\"connectionStrings\"))\n                                     .Elements().SingleOrDefault(e => e.Name.ToString().Equals(\"add\"))\n                                     .Attributes().SingleOrDefault(e => e.Name.ToString().Equals(\"name\")).Value);\n\n            Assert.Equal(\"awesomeprofile\", document.Root.Element(\"system.web\").Element(\"profiles\").Element(\"add\").Attribute(\"name\").Value);\n        }\n\n        [Fact]\n        public void AddPackageWithFrameworkReferenceDoesNotAffectWebConfigIfReferencesAlreadyExist()\n        {\n            // Arrange\n            var webConfigPath = @\"x:\\my-website\\web.config\";\n            var memoryStream = new NeverCloseMemoryStream(@\"<?xml version=\"\"1.0\"\"?>\n                <configuration>\n                    <connectionStrings>\n                        <add name=\"\"test\"\" />\n                    </connectionStrings>\n                    <system.web>\n                        <compilation>\n                            <assemblies>\n                                <add assembly=\"\"System.Data, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\"\" />\n                            </assemblies>\n                        </compilation>\n                        <profiles><add name=\"\"awesomeprofile\"\" /></profiles>\n                    </system.web>\n                </configuration>\n\n\");\n\n            var fileSystem = new Mock<IFileSystem>();\n            fileSystem.SetupGet(f => f.Root).Returns(\"x:\\\\my-website\");\n            fileSystem.Setup(f => f.FileExists(It.Is<string>(p => p.Equals(webConfigPath)))).Returns(true);\n            fileSystem.Setup(f => f.OpenFile(It.Is<string>(p => p.Equals(webConfigPath)))).Returns(() =>\n            {\n                memoryStream.Seek(0, SeekOrigin.Begin);\n                return memoryStream;\n            });\n            fileSystem.Setup(f => f.AddFile(It.Is<string>(p => p.Equals(webConfigPath)), It.IsAny<Stream>()))\n                .Callback<string, Stream>((_, stream) => { memoryStream = new NeverCloseMemoryStream(stream.ReadToEnd()); });\n\n            // Act\n            WebProjectSystem.AddReferencesToConfig(fileSystem.Object, \"System.Data\");\n            WebProjectSystem.AddReferencesToConfig(fileSystem.Object, \"Microsoft.Abstractions\");\n\n            // Assert\n            memoryStream.Seek(0, SeekOrigin.Begin);\n            XDocument document = XDocument.Load(memoryStream);\n\n            var element = document.Root;\n            Assert.Equal(\"configuration\", element.Name);\n\n            // Use SingleOrDefault to ensure there's exactly one element with that name\n            var assemblies = document.Root\n                .Elements().SingleOrDefault(e => e.Name.ToString().Equals(\"system.web\"))\n                .Elements().SingleOrDefault(e => e.Name.ToString().Equals(\"compilation\"))\n                .Elements().SingleOrDefault(e => e.Name.ToString().Equals(\"assemblies\"));\n\n            Assert.Equal(2, assemblies.Elements(\"add\").Count());\n            Assert.Equal(\"System.Data, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\",\n                         assemblies.Elements().First().Attribute(\"assembly\").Value);\n            Assert.Equal(\"Microsoft.Abstractions\",\n                         assemblies.Elements().Last().Attribute(\"assembly\").Value);\n\n            // Make sure the original web.config content is unaffected\n            Assert.Equal(\"test\", document.Root\n                                     .Elements().SingleOrDefault(e => e.Name.ToString().Equals(\"connectionStrings\"))\n                                     .Elements().SingleOrDefault(e => e.Name.ToString().Equals(\"add\"))\n                                     .Attributes().SingleOrDefault(e => e.Name.ToString().Equals(\"name\")).Value);\n\n            Assert.Equal(\"awesomeprofile\", document.Root.Element(\"system.web\").Element(\"profiles\").Element(\"add\").Attribute(\"name\").Value);\n        }\n\n        [Fact]\n        public void ResolveAssemblyPartialNameForCommonAssemblies()\n        {\n            // Arrange\n            var commonAssemblies = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)\n            {\n                { \"System.Data\", \"System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" },\n                { \"System.Data.Linq\", \"System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" },\n                { \"System.Net\", \"System.Net, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" },\n                { \"System.Runtime.Caching\", \"System.Runtime.Caching, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" },\n                { \"System.Xml\", \"System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" },\n                { \"System.Web.DynamicData\", \"System.Web.DynamicData, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" },\n            };\n\n            // Act and Assert\n            foreach (var item in commonAssemblies)\n            {\n                var resolvedName = WebProjectSystem.ResolvePartialAssemblyName(item.Key);\n\n                Assert.Equal(item.Value, resolvedName);\n            }\n        }\n\n        private static IFileSystem GetFileSystem()\n        {\n            var fileSystem = new Mock<IFileSystem>();\n            fileSystem.Setup(c => c.Root).Returns(@\"X:\\packages\\\");\n            return fileSystem.Object;\n        }\n\n        private class NeverCloseMemoryStream : MemoryStream\n        {\n            public NeverCloseMemoryStream(string content)\n                : base(Encoding.UTF8.GetBytes(content))\n            {\n            }\n\n            protected override void Dispose(bool disposing)\n            {\n                // Do nothing\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Administration.Test/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Castle.Core\" version=\"5.1.1\" targetFramework=\"net462\" />\n  <package id=\"Moq\" version=\"4.18.4\" targetFramework=\"net462\" />\n  <package id=\"Nuget.Core\" version=\"1.6.2\" targetFramework=\"net462\" />\n  <package id=\"xunit\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.abstractions\" version=\"2.0.3\" targetFramework=\"net462\" />\n  <package id=\"xunit.analyzers\" version=\"1.1.0\" targetFramework=\"net462\" />\n  <package id=\"xunit.assert\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.execution\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.runner.visualstudio\" version=\"2.4.5\" targetFramework=\"net462\" developmentDependency=\"true\" />\n</packages>"
  },
  {
    "path": "test/System.Web.WebPages.Deployment.Test/App.Config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n</configuration>"
  },
  {
    "path": "test/System.Web.WebPages.Deployment.Test/AssemblyUtilsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Deployment.Test\n{\n    public class AssemblyUtilsTest\n    {\n        private static readonly string LatestVersion = LatestRazorVersion.LatestVersion.ToString();\n\n        private string LatestAssemblyName()\n        {\n            return AssemblyName(LatestVersion);\n        }\n\n        private string AssemblyName(string version, string culture = \"neutral\", string publicKeyToken = \"31bf3856ad364e35\")\n        {\n            return AssemblyNameFor(\"System.Web.WebPages.Deployment\", version, culture, publicKeyToken);\n        }\n\n        private string AssemblyNameFor(string name)\n        {\n            return AssemblyNameFor(name, LatestVersion);\n        }\n\n        private string AssemblyNameFor(string name, string version, string culture = \"neutral\", string publicKeyToken = \"31bf3856ad364e35\")\n        {\n            string formatString = \"{0}, Version={1}, Culture={2}, PublicKeyToken={3}\";\n\n            return string.Format(CultureInfo.InvariantCulture, formatString, name, version, culture, publicKeyToken);\n        }\n\n        [Fact]\n        public void GetMaxAssemblyVersionReturnsMaximumAvailableVersion()\n        {\n            // Arrange\n            var assemblies = new[]\n            {\n                new AssemblyName(AssemblyName(\"1.0.0.0\")),\n                new AssemblyName(AssemblyName(\"3.0.0.0\")),\n                new AssemblyName(LatestAssemblyName()),\n                new AssemblyName(AssemblyName(\"2.0.0.0\")),\n            };\n\n            // Act\n            var maxVersion = AssemblyUtils.GetMaxWebPagesVersion(assemblies);\n\n            // Assert\n            Assert.Equal(LatestRazorVersion.LatestVersion, maxVersion);\n        }\n\n        [Fact]\n        public void GetMaxAssemblyVersionMatchesExactName()\n        {\n            // Arrange\n            var assemblies = new[]\n            {\n                new AssemblyName(AssemblyName(\"1.0.0.0\")),\n                new AssemblyName(AssemblyName(\"2.2.0.0\")),\n                new AssemblyName(AssemblyName(\"2.2.0.0\", publicKeyToken: \"7777777777777777\")),\n                new AssemblyName(AssemblyName(\"2.2.0.0\", culture: \"en-US\")),\n                new AssemblyName(AssemblyName(\"3.0.0.0\")),\n                new AssemblyName(LatestAssemblyName()),\n            };\n\n            // Act\n            var maxVersion = AssemblyUtils.GetMaxWebPagesVersion(assemblies);\n\n            // Assert\n            Assert.Equal(LatestRazorVersion.LatestVersion, maxVersion);\n        }\n\n        [Fact]\n        public void GetVersionFromBinReturnsNullIfNoFileWithDeploymentAssemblyNameIsFoundInBin()\n        {\n            // Arrange\n            var binDirectory = @\"X:\\test\\project\";\n            TestFileSystem fileSystem = new TestFileSystem();\n\n            // Act\n            var binVersion = AssemblyUtils.GetVersionFromBin(binDirectory, fileSystem, getAssemblyNameThunk: null);\n\n            // Assert\n            Assert.Null(binVersion);\n        }\n\n        [Fact]\n        public void GetVersionFromBinReturnsVersionFromBinIfLower()\n        {\n            // Arrange\n            var binDirectory = @\"X:\\test\\project\";\n            TestFileSystem fileSystem = new TestFileSystem();\n            fileSystem.AddFile(Path.Combine(binDirectory, \"System.Web.WebPages.Deployment.dll\"));\n            Func<string, AssemblyName> getAssembyName = _ => new AssemblyName(AssemblyName(\"1.0.0.0\"));\n\n            // Act\n            var binVersion = AssemblyUtils.GetVersionFromBin(binDirectory, fileSystem, getAssembyName);\n\n            // Assert\n            Assert.Equal(new Version(\"1.0.0.0\"), binVersion);\n        }\n\n        [Fact]\n        public void GetVersionFromBinReturnsVersionFromBinIfSameVersion()\n        {\n            // Arrange\n            var binDirectory = @\"X:\\test\\project\";\n            TestFileSystem fileSystem = new TestFileSystem();\n            fileSystem.AddFile(Path.Combine(binDirectory, \"System.Web.WebPages.Deployment.dll\"));\n            Func<string, AssemblyName> getAssembyName = _ => new AssemblyName(LatestAssemblyName());\n\n            // Act\n            var binVersion = AssemblyUtils.GetVersionFromBin(binDirectory, fileSystem, getAssembyName);\n\n            // Assert\n            Assert.Equal(LatestRazorVersion.LatestVersion, binVersion);\n        }\n\n        [Fact]\n        public void GetVersionFromBinReturnsVersionFromBinIfHigherVersion()\n        {\n            // Arrange\n            var binDirectory = @\"X:\\test\\project\";\n            TestFileSystem fileSystem = new TestFileSystem();\n            fileSystem.AddFile(Path.Combine(binDirectory, \"System.Web.WebPages.Deployment.dll\"));\n            Func<string, AssemblyName> getAssembyName = _ => new AssemblyName(\"System.Web.WebPages.Deployment, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\");\n\n            // Act\n            var binVersion = AssemblyUtils.GetVersionFromBin(binDirectory, fileSystem, getAssembyName);\n\n            // Assert\n            Assert.Equal(new Version(\"8.0.0.0\"), binVersion);\n        }\n\n        [Fact]\n        public void GetVersionFromBinReturnsNullIfFileInBinIsNotAValidBinary()\n        {\n            // Arrange\n            var binDirectory = @\"X:\\test\\project\";\n            TestFileSystem fileSystem = new TestFileSystem();\n            fileSystem.AddFile(Path.Combine(binDirectory, \"System.Web.WebPages.Deployment.dll\"));\n            Func<string, AssemblyName> getAssembyName = _ => { throw new FileLoadException(); };\n\n            // Act\n            var binVersion = AssemblyUtils.GetVersionFromBin(binDirectory, fileSystem, getAssembyName);\n\n            // Assert\n            Assert.Null(binVersion);\n        }\n\n        [Fact]\n        public void GetAssembliesForVersionReturnsCorrectSetForV1()\n        {\n            // Arrange\n            var expectedAssemblies = new[]\n            {\n                \"Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\n                \"System.Web.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\n                \"System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\n                \"System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\n                \"System.Web.WebPages.Administration, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\n                \"System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\n                \"WebMatrix.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\n                \"WebMatrix.WebData, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"\n            };\n\n            // Act \n            var assemblies = AssemblyUtils.GetAssembliesForVersion(new Version(\"1.0.0.0\"))\n                .Select(c => c.ToString())\n                .ToArray();\n\n            // Assert\n            Assert.Equal(expectedAssemblies, assemblies);\n        }\n\n        [Fact]\n        public void GetAssembliesForVersionReturnsCorrectSetForVCurrent()\n        {\n            // Arrange\n            var expectedAssemblies = new[]\n            {\n                AssemblyNameFor(\"Microsoft.Web.Infrastructure\", \"1.0.0.0\"),\n                AssemblyNameFor(\"System.Web.Razor\"),\n                AssemblyNameFor(\"System.Web.Helpers\"),\n                AssemblyNameFor(\"System.Web.WebPages\"),\n                AssemblyNameFor(\"System.Web.WebPages.Administration\"),\n                AssemblyNameFor(\"System.Web.WebPages.Razor\"),\n                AssemblyNameFor(\"WebMatrix.Data\"),\n                AssemblyNameFor(\"WebMatrix.WebData\"),\n            };\n\n            // Act \n            var assemblies = AssemblyUtils.GetAssembliesForVersion(LatestRazorVersion.LatestVersion)\n                .Select(c => c.ToString())\n                .ToArray();\n\n            // Assert\n            Assert.Equal(expectedAssemblies, assemblies);\n        }\n\n        [Fact]\n        public void GetMatchingAssembliesReturnsEmptyDictionaryIfAssemblyReferencesCollectionIsNull()\n        {\n            // Arrange\n            Dictionary<string, IEnumerable<string>> assemblyReferences = null;\n\n            // Act\n            var referencedAssemblies = AssemblyUtils.GetAssembliesMatchingOtherVersions(assemblyReferences);\n\n            // Assert\n            Assert.Empty(referencedAssemblies);\n        }\n\n        [Fact]\n        public void GetMatchingAssembliesReturnsEmptyDictionaryIfAssemblyReferencesCollectionIsEmpty()\n        {\n            // Arrange\n            var assemblyReferences = new Dictionary<string, IEnumerable<string>>();\n\n            // Act\n            var referencedAssemblies = AssemblyUtils.GetAssembliesMatchingOtherVersions(assemblyReferences);\n\n            // Assert\n            Assert.Empty(referencedAssemblies);\n        }\n\n        [Fact]\n        public void GetMatchingAssembliesReturnsEmptyDictionaryIfNoReferencesMatchWebPagesAssemblies()\n        {\n            // Arrange\n            var assemblyReferences = new Dictionary<string, IEnumerable<string>>\n            {\n                { @\"x:\\site\\bin\\A.dll\", new List<string> { \"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null\" }},\n                { @\"x:\\site\\bin\\B.dll\", new List<string> { \"System.Web.Mvc, Version=2.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" }},\n            };\n\n            // Act\n            var referencedAssemblies = AssemblyUtils.GetAssembliesMatchingOtherVersions(assemblyReferences);\n\n            // Assert\n            Assert.Empty(referencedAssemblies);\n        }\n\n        [Fact]\n        public void GetMatchingAssembliesReturnsReferencingAssemblyAndWebPagesVersionForMatchingReferences()\n        {\n            // Arrange\n            var assemblyReferences = new Dictionary<string, IEnumerable<string>>\n            {\n                { @\"x:\\site\\bin\\A.dll\", new[] { \"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null\" }},\n                { @\"x:\\site\\bin\\B.dll\", new[] \n                    {\n                        \"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null\",\n                        AssemblyNameFor(\"System.Web.WebPages\", \"1.0.0.0\"),\n                        AssemblyNameFor(\"System.Web.Helpers\", \"1.0.0.0\"),\n                    }\n                },\n            };\n\n            // Act\n            var referencedAssemblies = AssemblyUtils.GetAssembliesMatchingOtherVersions(assemblyReferences);\n\n            // Assert\n            Assert.Equal(1, referencedAssemblies.Count);\n            Assert.Equal(@\"x:\\site\\bin\\B.dll\", referencedAssemblies.Single().Key);\n            Assert.Equal(new Version(\"1.0.0.0\"), referencedAssemblies.Single().Value);\n        }\n\n        [Fact]\n        public void GetMatchingAssembliesFiltersWebPagesVersionsThatMatch()\n        {\n            // Arrange\n            var assemblyReferences = new Dictionary<string, IEnumerable<string>>\n            {\n                { @\"x:\\site\\bin\\A.dll\", new[] { \"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null\" }},\n                { @\"x:\\site\\bin\\B.dll\", new[] \n                    { \n                        \"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null\",\n                        String.Format(CultureInfo.InvariantCulture, \"System.Web.WebPages, Version={0}, Culture=neutral, PublicKeyToken=31bf3856ad364e35\", AssemblyUtils.ThisAssemblyName.Version),\n                        String.Format(CultureInfo.InvariantCulture, \"System.Web.Helpers, Version={0}, Culture=neutral, PublicKeyToken=31bf3856ad364e35\", AssemblyUtils.ThisAssemblyName.Version)\n                    }\n                },\n                { @\"x:\\site\\bin\\C.dll\", new[] \n                    { \n                        \"mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null\",\n                        \"System.Web.WebPages.Razor, Version=1.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\n                        \"System.Web.WebPages.Razor, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\n                    }\n                },\n            };\n\n            // Act\n            var referencedAssemblies = AssemblyUtils.GetAssembliesMatchingOtherVersions(assemblyReferences);\n\n            // Assert\n            Assert.Equal(1, referencedAssemblies.Count);\n            Assert.Equal(@\"x:\\site\\bin\\C.dll\", referencedAssemblies.Single().Key);\n            Assert.Equal(new Version(\"1.2.0.0\"), referencedAssemblies.Single().Value);\n        }\n\n        private static void EnsureDirectory(string directory)\n        {\n            if (!Directory.Exists(directory))\n            {\n                Directory.CreateDirectory(directory);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Deployment.Test/DeploymentUtil.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\n\nnamespace System.Web.WebPages.Deployment.Test\n{\n    internal static class DeploymentUtil\n    {\n        public static string GetBinDirectory()\n        {\n            var tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());\n            return Path.Combine(tempDirectory, \"bin\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Deployment.Test/LatestRazorVersion.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Deployment.Test\n{\n    public static class LatestRazorVersion\n    {\n        public static readonly Version LatestVersion = VersionTestHelper.GetVersionFromAssembly(\"System.Web.Razor\", typeof(ParserResults));\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Deployment.Test/PreApplicationStartCodeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\nusing System.Text;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Deployment.Test\n{\n    public class PreApplicationStartCodeTest\n    {\n        private const string DeploymentVersionFile = \"System.Web.WebPages.Deployment\";\n\n        private readonly string LatestVersion = LatestRazorVersion.LatestVersion.ToString();\n\n        [Fact]\n        public void PreApplicationStartCodeDoesNothingIfWebPagesIsExplicitlyDisabled()\n        {\n            // Arrange\n            Version loadedVersion = null;\n            bool registeredForChangeNotification = false;\n            IEnumerable<AssemblyName> loadedAssemblies = GetAssemblies(\"1\", \"2\");\n\n            var fileSystem = new TestFileSystem();\n            var buildManager = new TestBuildManager();\n            var nameValueCollection = GetAppSettings(enabled: false, webPagesVersion: null);\n            Action<Version> loadWebPages = (version) => { loadedVersion = version; };\n            Action registerForChange = () => { registeredForChangeNotification = true; };\n\n            // Act\n            bool loaded = PreApplicationStartCode.StartCore(fileSystem, \"\", \"bin\", nameValueCollection, loadedAssemblies, buildManager, loadWebPages, registerForChange, null);\n\n            // Assert\n            Assert.False(loaded);\n            Assert.Null(loadedVersion);\n            Assert.False(registeredForChangeNotification);\n            Assert.Equal(0, buildManager.Stream.Length);\n        }\n\n        [Fact]\n        public void PreApplicationStartCodeUsesVersionSpecifiedInConfigIfWebPagesIsImplicitlyEnabled()\n        {\n            // Arrange\n            Version loadedVersion = null;\n            bool registeredForChangeNotification = false;\n            IEnumerable<AssemblyName> loadedAssemblies = GetAssemblies(\"1.12.123.1234\", LatestVersion);\n            Version webPagesVersion = new Version(\"1.12.123.1234\");\n\n            var fileSystem = new TestFileSystem();\n            fileSystem.AddFile(\"Default.cshtml\");\n            var buildManager = new TestBuildManager();\n            var nameValueCollection = GetAppSettings(enabled: null, webPagesVersion: webPagesVersion);\n            Action<Version> loadWebPages = (version) => { loadedVersion = version; };\n            Action registerForChange = () => { registeredForChangeNotification = true; };\n\n            // Act\n            bool loaded = PreApplicationStartCode.StartCore(fileSystem, \"\", \"bin\", nameValueCollection, loadedAssemblies, buildManager, loadWebPages, registerForChange, getAssemblyNameThunk: null);\n\n            // Assert\n            Assert.True(loaded);\n            Assert.Equal(webPagesVersion, loadedVersion);\n            Assert.False(registeredForChangeNotification);\n            VerifyVersionFile(buildManager, webPagesVersion);\n        }\n\n        [Fact]\n        public void PreApplicationStartCodeDoesNotLoadCurrentWebPagesIfOnlyVersionIsListedInConfigAndNoFilesAreFoundInSiteRoot()\n        {\n            // Arrange\n            Version loadedVersion = null;\n            bool registeredForChangeNotification = false;\n            Version webPagesVersion = AssemblyUtils.ThisAssemblyName.Version;\n            IEnumerable<AssemblyName> loadedAssemblies = GetAssemblies(LatestVersion);\n\n            var fileSystem = new TestFileSystem();\n            var buildManager = new TestBuildManager();\n            var nameValueCollection = GetAppSettings(enabled: null, webPagesVersion: webPagesVersion);\n            Action<Version> loadWebPages = (version) => { loadedVersion = version; };\n            Action registerForChange = () => { registeredForChangeNotification = true; };\n\n            // Arrange\n            bool loaded = PreApplicationStartCode.StartCore(fileSystem, \"\", \"bin\", nameValueCollection, loadedAssemblies, buildManager, loadWebPages, registerForChange, null);\n\n            // Assert\n            Assert.False(loaded);\n            Assert.Null(loadedVersion);\n            Assert.True(registeredForChangeNotification);\n            Assert.Equal(0, buildManager.Stream.Length);\n        }\n\n        [Fact]\n        public void PreApplicationStartCodeRegistersForChangeNotificationIfNotExplicitlyDisabledAndNoFilesFoundInSiteRoot()\n        {\n            // Arrange\n            Version loadedVersion = null;\n            bool registeredForChangeNotification = false;\n            IEnumerable<AssemblyName> loadedAssemblies = GetAssemblies(LatestVersion);\n\n            var fileSystem = new TestFileSystem();\n            var buildManager = new TestBuildManager();\n            var nameValueCollection = GetAppSettings(enabled: null, webPagesVersion: null);\n            Action<Version> loadWebPages = (version) => { loadedVersion = version; };\n            Action registerForChange = () => { registeredForChangeNotification = true; };\n\n            // Act\n            bool loaded = PreApplicationStartCode.StartCore(fileSystem, \"\", \"bin\", nameValueCollection, loadedAssemblies, buildManager, loadWebPages, registerForChange, null);\n\n            // Assert\n            Assert.False(loaded);\n            Assert.Null(loadedVersion);\n            Assert.True(registeredForChangeNotification);\n            Assert.Equal(0, buildManager.Stream.Length);\n        }\n\n        [Fact]\n        public void PreApplicationStartCodeDoesNothingIfV1IsAvailableInBinAndSiteIsExplicitlyEnabled()\n        {\n            // Arrange\n            Version loadedVersion = null;\n            bool registeredForChangeNotification = false;\n            var v1Version = new Version(\"1.0.0.0\");\n            IEnumerable<AssemblyName> loadedAssemblies = GetAssemblies(\"1.0.0.0\", LatestVersion);\n\n            var binDirectory = DeploymentUtil.GetBinDirectory();\n\n            var fileSystem = new TestFileSystem();\n            fileSystem.AddFile(Path.Combine(binDirectory, \"System.Web.WebPages.Deployment.dll\"));\n            var buildManager = new TestBuildManager();\n            var nameValueCollection = GetAppSettings(enabled: true, webPagesVersion: null);\n            Action<Version> loadWebPages = (version) => { loadedVersion = version; };\n            Action registerForChange = () => { registeredForChangeNotification = true; };\n            Func<string, AssemblyName> getAssembyName = _ => new AssemblyName(\"System.Web.WebPages.Deployment, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\");\n\n            // Act\n            bool loaded = PreApplicationStartCode.StartCore(fileSystem, \"\", binDirectory, nameValueCollection, loadedAssemblies, buildManager, loadWebPages, registerForChange, getAssembyName);\n\n            // Assert\n            Assert.False(loaded);\n            Assert.Null(loadedVersion);\n            Assert.False(registeredForChangeNotification);\n            Assert.Equal(0, buildManager.Stream.Length);\n        }\n\n        [Fact]\n        public void PreApplicationStartCodeDoesNothingIfV1IsAvailableInBinAndFileExistsInRootOfWebSite()\n        {\n            // Arrange\n            Version loadedVersion = null;\n            bool registeredForChangeNotification = false;\n            var v1Version = new Version(\"1.0.0.0\");\n            IEnumerable<AssemblyName> loadedAssemblies = GetAssemblies(\"1.0.0.0\", LatestVersion);\n\n            var binDirectory = DeploymentUtil.GetBinDirectory();\n\n            var fileSystem = new TestFileSystem();\n            var buildManager = new TestBuildManager();\n            fileSystem.AddFile(\"Default.cshtml\");\n            fileSystem.AddFile(Path.Combine(binDirectory, \"System.Web.WebPages.Deployment.dll\"));\n            var nameValueCollection = GetAppSettings(enabled: null, webPagesVersion: null);\n            Action<Version> loadWebPages = (version) => { loadedVersion = version; };\n            Action registerForChange = () => { registeredForChangeNotification = true; };\n            Func<string, AssemblyName> getAssembyName = _ => new AssemblyName(\"System.Web.WebPages.Deployment, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\");\n\n            // Act\n            bool loaded = PreApplicationStartCode.StartCore(fileSystem, \"\", binDirectory, nameValueCollection, loadedAssemblies, buildManager, loadWebPages, registerForChange, getAssembyName);\n\n            // Assert\n            Assert.False(loaded);\n            Assert.Null(loadedVersion);\n            Assert.False(registeredForChangeNotification);\n            Assert.Equal(0, buildManager.Stream.Length);\n        }\n\n        [Fact]\n        public void PreApplicationStartCodeDoesNothingIfItIsAvailableInBinAndFileExistsInRootOfWebSite()\n        {\n            // Arrange\n            Version loadedVersion = null;\n            bool registeredForChangeNotification = false;\n            var webPagesVersion = AssemblyUtils.ThisAssemblyName.Version;\n            IEnumerable<AssemblyName> loadedAssemblies = GetAssemblies(AssemblyUtils.ThisAssemblyName.Version.ToString());\n\n            var fileSystem = new TestFileSystem();\n            var binDirectory = DeploymentUtil.GetBinDirectory();\n\n            var buildManager = new TestBuildManager();\n            fileSystem.AddFile(\"Default.vbhtml\");\n            fileSystem.AddFile(Path.Combine(binDirectory, \"System.Web.WebPages.Deployment.dll\"));\n            var nameValueCollection = GetAppSettings(enabled: null, webPagesVersion: null);\n            Action<Version> loadWebPages = (version) => { loadedVersion = version; };\n            Action registerForChange = () => { registeredForChangeNotification = true; };\n            Func<string, AssemblyName> getAssembyName = _ => new AssemblyName(\"System.Web.WebPages.Deployment, Version=\" + AssemblyUtils.ThisAssemblyName.Version.ToString() + \", Culture=neutral, PublicKeyToken=31bf3856ad364e35\");\n\n            // Act\n            bool loaded = PreApplicationStartCode.StartCore(fileSystem, \"\", binDirectory, nameValueCollection, loadedAssemblies, buildManager, loadWebPages, registerForChange, getAssembyName);\n\n            // Assert\n            Assert.False(loaded);\n            Assert.Null(loadedVersion);\n            Assert.False(registeredForChangeNotification);\n            Assert.Equal(0, buildManager.Stream.Length);\n        }\n\n        [Fact]\n        public void PreApplicationStartCodeLoadsV1IfNoVersionIsSpecifiedAndCurrentAssemblyIsTheMaximumVersionAvailable()\n        {\n            // Arrange\n            Version loadedVersion = null;\n            bool registeredForChangeNotification = false;\n            var webPagesVersion = AssemblyUtils.ThisAssemblyName.Version;\n            var v1Version = new Version(\"1.0.0.0\");\n            IEnumerable<AssemblyName> loadedAssemblies = GetAssemblies(\"1.0.0.0\", LatestVersion);\n\n            // Note: For this test to work with future versions we would need to create corresponding embedded resources with that version in it.\n            var fileSystem = new TestFileSystem();\n            var buildManager = new TestBuildManager();\n            fileSystem.AddFile(\"Index.cshtml\");\n            var nameValueCollection = GetAppSettings(enabled: null, webPagesVersion: null);\n            Action<Version> loadWebPages = (version) => { loadedVersion = version; };\n            Action registerForChange = () => { registeredForChangeNotification = true; };\n\n            // Act\n            bool loaded = PreApplicationStartCode.StartCore(fileSystem, \"\", \"bin\", nameValueCollection, loadedAssemblies, buildManager, loadWebPages, registerForChange, null);\n\n            // Assert\n            Assert.True(loaded);\n            Assert.Equal(v1Version, loadedVersion);\n            Assert.False(registeredForChangeNotification);\n            VerifyVersionFile(buildManager, v1Version);\n        }\n\n        [Fact]\n        public void PreApplicationStartCodeThrowsIfNoVersionIsSpecifiedAndV1IsNotAvailable()\n        {\n            // Arrange\n            Version loadedVersion = null;\n            bool registeredForChangeNotification = false;\n            var webPagesVersion = AssemblyUtils.ThisAssemblyName.Version;\n            IEnumerable<AssemblyName> loadedAssemblies = GetAssemblies(LatestVersion);\n\n            // Note: For this test to work with future versions we would need to create corresponding embedded resources with that version in it.\n            var fileSystem = new TestFileSystem();\n            var buildManager = new TestBuildManager();\n            fileSystem.AddFile(\"Index.cshtml\");\n            var nameValueCollection = GetAppSettings(enabled: null, webPagesVersion: null);\n            Action<Version> loadWebPages = (version) => { loadedVersion = version; };\n            Action registerForChange = () => { registeredForChangeNotification = true; };\n\n            // Act and Assert\n            Assert.Throws<InvalidOperationException>(() =>\n                PreApplicationStartCode.StartCore(fileSystem, \"\", \"bin\", nameValueCollection, loadedAssemblies, buildManager, loadWebPages, registerForChange, null),\n@\"Could not determine which version of ASP.NET Web Pages to use.\n\nIn order to use this site, specify a version in the site’s web.config file. For more information, see the following article on the Microsoft support site: http://go.microsoft.com/fwlink/?LinkId=254126\");\n            Assert.False(registeredForChangeNotification);\n            Assert.Equal(0, buildManager.Stream.Length);\n        }\n\n        [Fact]\n        public void PreApplicationStartCodeDoesNotLoadIfAHigherVersionIsAvailableInBin()\n        {\n            // Arrange\n            Version loadedVersion = null;\n            bool registeredForChangeNotification = false;\n            IEnumerable<AssemblyName> loadedAssemblies = GetAssemblies(LatestVersion, \"8.0.0.0\");\n\n            var binDirectory = DeploymentUtil.GetBinDirectory();\n\n            var fileSystem = new TestFileSystem();\n            fileSystem.AddFile(\"Index.cshtml\");\n            fileSystem.AddFile(Path.Combine(binDirectory, \"System.Web.WebPages.Deployment.dll\"));\n            var buildManager = new TestBuildManager();\n            var nameValueCollection = GetAppSettings(enabled: null, webPagesVersion: null);\n            Action<Version> loadWebPages = (version) => { loadedVersion = version; };\n            Action registerForChange = () => { registeredForChangeNotification = true; };\n            Func<string, AssemblyName> getAssembyName = _ => new AssemblyName(\"System.Web.WebPages.Deployment, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\");\n\n            // Act\n            bool loaded = PreApplicationStartCode.StartCore(fileSystem, \"\", binDirectory, nameValueCollection, loadedAssemblies, buildManager, loadWebPages, registerForChange, getAssembyName);\n\n            // Assert\n            Assert.False(loaded);\n            Assert.Null(loadedVersion);\n            Assert.False(registeredForChangeNotification);\n            Assert.Equal(0, buildManager.Stream.Length);\n        }\n\n        [Fact]\n        public void PreApplicationStartCodeDoesNotLoadIfAHigherVersionIsAvailableInGac()\n        {\n            // Arrange\n            Version loadedVersion = null;\n            bool registeredForChangeNotification = false;\n            // Hopefully we'd have figured out a better way to load Plan9 by v8.\n            var webPagesVersion = new Version(\"8.0.0.0\");\n            IEnumerable<AssemblyName> loadedAssemblies = GetAssemblies(\"1.0.0.0\", LatestVersion, \"8.0.0.0\");\n\n            var fileSystem = new TestFileSystem();\n            fileSystem.AddFile(\"Index.cshtml\");\n            var buildManager = new TestBuildManager();\n            var nameValueCollection = GetAppSettings(enabled: null, webPagesVersion: null);\n            Action<Version> loadWebPages = (version) => { loadedVersion = version; };\n            Action registerForChange = () => { registeredForChangeNotification = true; };\n\n            // Act\n            bool loaded = PreApplicationStartCode.StartCore(fileSystem, \"\", \"bin\", nameValueCollection, loadedAssemblies, buildManager, loadWebPages, registerForChange, null);\n\n            // Assert\n            Assert.False(loaded);\n            Assert.Null(loadedVersion);\n            Assert.False(registeredForChangeNotification);\n            Assert.Equal(0, buildManager.Stream.Length);\n        }\n\n        [Fact]\n        public void PreApplicationStartCodeForcesRecompileIfPreviousVersionIsNotTheSameAsCurrentVersion()\n        {\n            // Arrange\n            Version loadedVersion = null;\n            bool registeredForChangeNotification = false;\n            IEnumerable<AssemblyName> loadedAssemblies = GetAssemblies(LatestVersion);\n\n            var fileSystem = new TestFileSystem();\n            fileSystem.AddFile(\"Index.cshtml\");\n            var buildManager = new TestBuildManager();\n            var content = \"1.0.0.0\" + Environment.NewLine;\n            buildManager.Stream = new MemoryStream(Encoding.Default.GetBytes(content));\n\n            var nameValueCollection = GetAppSettings(enabled: null, webPagesVersion: new Version(LatestVersion));\n            Action<Version> loadWebPages = (version) => { loadedVersion = version; };\n            Action registerForChange = () => { registeredForChangeNotification = true; };\n\n            // Act\n            var ex = Assert.Throws<HttpCompileException>(() =>\n                PreApplicationStartCode.StartCore(fileSystem, \"\", @\"site\\bin\", nameValueCollection, loadedAssemblies, buildManager, loadWebPages, registerForChange, null)\n            );\n\n            // Assert\n            Assert.Equal(\"Changes were detected in the Web Pages runtime version that require your application to be recompiled. Refresh your browser window to continue.\", ex.Message);\n            Assert.Equal((object)true, ex.Data[\"WebPages.VersionChange\"]);\n            Assert.False(registeredForChangeNotification);\n            VerifyVersionFile(buildManager, new Version(LatestVersion));\n            Assert.True(fileSystem.FileExists(@\"site\\bin\\WebPagesRecompilation.deleteme\"));\n        }\n\n        [Fact]\n        public void PreApplicationStartCodeDoesNotForceRecompileIfNewVersionIsV1AndCurrentAssemblyIsNotMaxVersion()\n        {\n            // Arrange\n            Version loadedVersion = null;\n            bool registeredForChangeNotification = false;\n            IEnumerable<AssemblyName> loadedAssemblies = GetAssemblies(LatestVersion, \"5.0.0.0\");\n\n            var fileSystem = new TestFileSystem();\n            fileSystem.AddFile(\"Index.cshtml\");\n            var buildManager = new TestBuildManager();\n            var content = AssemblyUtils.ThisAssemblyName.Version + Environment.NewLine;\n            buildManager.Stream = new MemoryStream(Encoding.Default.GetBytes(content));\n\n            var nameValueCollection = GetAppSettings(enabled: null, webPagesVersion: new Version(\"1.0.0\"));\n            Action<Version> loadWebPages = (version) => { loadedVersion = version; };\n            Action registerForChange = () => { registeredForChangeNotification = true; };\n\n            // Act\n            bool loaded = PreApplicationStartCode.StartCore(fileSystem, \"\", @\"site\\bin\", nameValueCollection, loadedAssemblies, buildManager, loadWebPages, registerForChange, null);\n\n            // Assert\n            Assert.False(loaded);\n            Assert.False(registeredForChangeNotification);\n            VerifyVersionFile(buildManager, AssemblyUtils.ThisAssemblyName.Version);\n            Assert.False(fileSystem.FileExists(@\"site\\bin\\WebPagesRecompilation.deleteme\"));\n        }\n\n        [Fact]\n        public void PreApplicationStartCodeThrowsIfWebPagesIsInBinAndDifferentVersionIsSpecifiedInConfig()\n        {\n            // Arrange\n            Version loadedVersion = null;\n            bool registeredForChangeNotification = false;\n            IEnumerable<AssemblyName> loadedAssemblies = GetAssemblies(\"1.0.0.0\", LatestVersion);\n\n            var binDirectory = DeploymentUtil.GetBinDirectory();\n\n            var fileSystem = new TestFileSystem();\n            fileSystem.AddFile(\"Index.cshtml\");\n            fileSystem.AddFile(Path.Combine(binDirectory, \"System.Web.WebPages.Deployment.dll\"));\n            var buildManager = new TestBuildManager();\n            var content = AssemblyUtils.ThisAssemblyName.Version + Environment.NewLine;\n            buildManager.Stream = new MemoryStream(Encoding.Default.GetBytes(content));\n\n            var nameValueCollection = GetAppSettings(enabled: null, webPagesVersion: new Version(LatestVersion));\n            Action<Version> loadWebPages = (version) => { loadedVersion = version; };\n            Action registerForChange = () => { registeredForChangeNotification = true; };\n            Func<string, AssemblyName> getAssembyName = _ => new AssemblyName(\"System.Web.WebPages.Deployment, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\");\n\n            // Act and Assert\n            Assert.Throws<InvalidOperationException>(() =>\n                PreApplicationStartCode.StartCore(fileSystem, \"\", binDirectory, nameValueCollection, loadedAssemblies, buildManager, loadWebPages, registerForChange, getAssembyName),\n                @\"Conflicting versions of ASP.NET Web Pages detected: specified version is \"\"\" + LatestVersion + @\"\"\", but the version in bin is \"\"1.0.0.0\"\". To continue, remove files from the application's bin directory or remove the version specification in web.config.\"\n            );\n\n            Assert.False(registeredForChangeNotification);\n            Assert.Null(loadedVersion);\n        }\n\n        [Fact]\n        public void PreApplicationStartCodeThrowsIfVersionIsSpecifiedInConfigAndDifferentVersionExistsInBin()\n        {\n            // Arrange\n            Version loadedVersion = null;\n\n            var binDirectory = DeploymentUtil.GetBinDirectory();\n            IEnumerable<AssemblyName> loadedAssemblies = GetAssemblies(\"1.0.0.0\", AssemblyUtils.ThisAssemblyName.Version.ToString());\n\n            var fileSystem = new TestFileSystem();\n            fileSystem.AddFile(\"Index.cshtml\");\n            fileSystem.AddFile(Path.Combine(binDirectory, \"System.Web.WebPages.Deployment.dll\"));\n            var buildManager = new TestBuildManager();\n            var content = AssemblyUtils.ThisAssemblyName.Version + Environment.NewLine;\n            buildManager.Stream = new MemoryStream(Encoding.Default.GetBytes(content));\n\n            var nameValueCollection = GetAppSettings(enabled: null, webPagesVersion: new Version(\"1.0.0\"));\n            Action<Version> loadWebPages = (version) => { loadedVersion = version; };\n            Action registerForChange = () => { };\n            Func<string, AssemblyName> getAssembyName = _ => new AssemblyName(\"System.Web.WebPages.Deployment, Version=\" + AssemblyUtils.ThisAssemblyName.Version + \", Culture=neutral, PublicKeyToken=31bf3856ad364e35\");\n\n            // Act and Assert\n            Assert.Throws<InvalidOperationException>(() =>\n                                                              PreApplicationStartCode.StartCore(fileSystem, \"\", binDirectory, nameValueCollection, loadedAssemblies, buildManager: buildManager, loadWebPages: loadWebPages, registerForChangeNotification: registerForChange, getAssemblyNameThunk: getAssembyName),\n                                                              String.Format(@\"Conflicting versions of ASP.NET Web Pages detected: specified version is \"\"1.0.0.0\"\", but the version in bin is \"\"{0}\"\". To continue, remove files from the application's bin directory or remove the version specification in web.config.\",\n                                                                            AssemblyUtils.ThisAssemblyName.Version));\n        }\n\n        [Fact]\n        public void PreApplicationStartCodeThrowsIfVersionSpecifiedInConfigIsNotAvailable()\n        {\n            // Arrange\n            Version loadedVersion = null;\n\n            var binDirectory = DeploymentUtil.GetBinDirectory();\n            IEnumerable<AssemblyName> loadedAssemblies = GetAssemblies(\"1.0.0.0\", AssemblyUtils.ThisAssemblyName.Version.ToString());\n\n            var fileSystem = new TestFileSystem();\n            fileSystem.AddFile(\"Index.cshtml\");\n            var buildManager = new TestBuildManager();\n            var content = AssemblyUtils.ThisAssemblyName.Version + Environment.NewLine;\n            buildManager.Stream = new MemoryStream(Encoding.Default.GetBytes(content));\n\n            var nameValueCollection = GetAppSettings(enabled: null, webPagesVersion: new Version(\"1.5\"));\n            Action<Version> loadWebPages = (version) => { loadedVersion = version; };\n            Action registerForChange = () => { };\n\n            // Act and Assert\n            Assert.Throws<InvalidOperationException>(() =>\n                                                              PreApplicationStartCode.StartCore(fileSystem, \"\", binDirectory, nameValueCollection, loadedAssemblies, buildManager: buildManager, loadWebPages: loadWebPages, registerForChangeNotification: registerForChange, getAssemblyNameThunk: null),\n                                                              String.Format(\"Specified Web Pages version \\\"1.5.0.0\\\" could not be found. Update your web.config to specify a different version. Current version: \\\"{0}\\\".\",\n                                                                            AssemblyUtils.ThisAssemblyName.Version));\n        }\n\n        [Fact]\n        public void TestPreAppStartClass()\n        {\n            PreAppStartTestHelper.TestPreAppStartClass(typeof(PreApplicationStartCode));\n        }\n\n        private static NameValueCollection GetAppSettings(bool? enabled, Version webPagesVersion)\n        {\n            var nameValueCollection = new NameValueCollection();\n            if (enabled.HasValue)\n            {\n                nameValueCollection[\"webpages:enabled\"] = enabled.Value ? \"true\" : \"false\";\n            }\n            if (webPagesVersion != null)\n            {\n                nameValueCollection[\"webpages:version\"] = webPagesVersion.ToString();\n            }\n\n            return nameValueCollection;\n        }\n\n        private static void VerifyVersionFile(TestBuildManager buildManager, Version webPagesVersion)\n        {\n            var content = Encoding.UTF8.GetString(buildManager.Stream.ToArray());\n            Version version = Version.Parse(content);\n            Assert.Equal(webPagesVersion, version);\n        }\n\n        private class TestBuildManager : IBuildManager\n        {\n            private MemoryStream _memoryStream = new MemoryStream();\n\n            public MemoryStream Stream\n            {\n                get { return _memoryStream; }\n                set { _memoryStream = value; }\n            }\n\n            public Stream CreateCachedFile(string fileName)\n            {\n                Assert.Equal(DeploymentVersionFile, fileName);\n                CopyMemoryStream();\n                return _memoryStream;\n            }\n\n            public Stream ReadCachedFile(string fileName)\n            {\n                Assert.Equal(DeploymentVersionFile, fileName);\n                CopyMemoryStream();\n                return _memoryStream;\n            }\n\n            /// <summary>\n            /// Need to do this because the MemoryStream is read and written to in consecutive calls which causes it to be closed / non-expandable.\n            /// </summary>\n            private void CopyMemoryStream()\n            {\n                var content = _memoryStream.ToArray();\n                if (content.Length > 0)\n                {\n                    _memoryStream = new MemoryStream(_memoryStream.ToArray());\n                }\n                else\n                {\n                    _memoryStream = new MemoryStream();\n                }\n            }\n        }\n\n        private static IEnumerable<AssemblyName> GetAssemblies(params string[] versions)\n        {\n            return from version in versions\n                   select new AssemblyName(\"System.Web.WebPages.Deployment, Version=\" + version + \", Culture=neutral, PublicKeyToken=31bf3856ad364e35\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Deployment.Test/System.Web.WebPages.Deployment.Test.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props\" Condition=\"Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" />\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" />\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{268DEE9D-F323-4A00-8ED8-3784388C3E3A}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>System.Web.WebPages.Deployment.Test</RootNamespace>\n    <AssemblyName>System.Web.WebPages.Deployment.Test</AssemblyName>\n    <OutputPath>..\\..\\bin\\$(Configuration)\\Test\\</OutputPath>\n    <NuGetPackageImportStamp>\n    </NuGetPackageImportStamp>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.abstractions.2.0.3\\lib\\net35\\xunit.abstractions.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.assert, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.assert.2.4.2\\lib\\netstandard1.1\\xunit.assert.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.core, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.core.2.4.2\\lib\\net452\\xunit.core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.execution.desktop, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.execution.2.4.2\\lib\\net452\\xunit.execution.desktop.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"AssemblyUtilsTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"DeploymentUtil.cs\" />\n    <Compile Include=\"LatestRazorVersion.cs\" />\n    <Compile Include=\"PreApplicationStartCodeTest.cs\" />\n    <Compile Include=\"TestFileSystem.cs\" />\n    <Compile Include=\"WebPagesDeploymentTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Razor\\System.Web.Razor.csproj\">\n      <Project>{8f18041b-9410-4c36-a9c5-067813df5f31}</Project>\n      <Name>System.Web.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.WebPages.Deployment\\System.Web.WebPages.Deployment.csproj\">\n      <Project>{22BABB60-8F02-4027-AFFC-ACF069954536}</Project>\n      <Name>System.Web.WebPages.Deployment</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\">\n      <Project>{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}</Project>\n      <Name>Microsoft.TestCommon</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"App.Config\" />\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"TestFiles\\ConfigTestAssemblies\\V2_Signed\\System.Web.WebPages.Deployment.dll\" />\n    <EmbeddedResource Include=\"TestFiles\\ConfigTestAssemblies\\V2_Unsigned\\System.Web.WebPages.Deployment.dll\" />\n    <EmbeddedResource Include=\"TestFiles\\ConfigTestSites\\CshtmlFileConfigV1\\Default.cshtml\" />\n    <EmbeddedResource Include=\"TestFiles\\ConfigTestSites\\CshtmlFileConfigV1\\web.config\" />\n    <EmbeddedResource Include=\"TestFiles\\ConfigTestSites\\CshtmlFileNoVersion\\Default.cshtml\" />\n    <EmbeddedResource Include=\"TestFiles\\ConfigTestSites\\NoCshtml\\Default.htm\" />\n    <EmbeddedResource Include=\"TestFiles\\ConfigTestSites\\NoCshtmlConfigV1\\Default.htm\" />\n    <EmbeddedResource Include=\"TestFiles\\ConfigTestSites\\NoCshtmlConfigV1\\web.config\" />\n    <EmbeddedResource Include=\"TestFiles\\ConfigTestSites\\NoCshtmlNoConfigSetting\\Default.htm\" />\n    <EmbeddedResource Include=\"TestFiles\\ConfigTestSites\\NoCshtmlNoConfigSetting\\web.config\" />\n    <EmbeddedResource Include=\"TestFiles\\ConfigTestSites\\NoCshtmlWithEnabledSetting\\Default.htm\" />\n    <EmbeddedResource Include=\"TestFiles\\ConfigTestSites\\NoCshtmlWithEnabledSetting\\web.config\" />\n    <EmbeddedResource Include=\"TestFiles\\ConfigTestSites\\NoCshtmlWithEnabledSettingFalse\\Default.htm\" />\n    <EmbeddedResource Include=\"TestFiles\\ConfigTestSites\\NoCshtmlWithEnabledSettingFalse\\web.config\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Service Include=\"{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Analyzer Include=\"..\\..\\packages\\xunit.analyzers.1.1.0\\analyzers\\dotnet\\cs\\xunit.analyzers.dll\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\n  <Target Name=\"EnsureNuGetPackageBuildImports\" BeforeTargets=\"PrepareForBuild\">\n    <PropertyGroup>\n      <ErrorText>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}.</ErrorText>\n    </PropertyGroup>\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props'))\" />\n  </Target>\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" />\n</Project>"
  },
  {
    "path": "test/System.Web.WebPages.Deployment.Test/TestFileSystem.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing Microsoft.Internal.Web.Utils;\n\nnamespace System.Web.WebPages.Deployment.Test\n{\n    public class TestFileSystem : IFileSystem\n    {\n        private readonly Dictionary<string, MemoryStream> _files = new Dictionary<string, MemoryStream>(StringComparer.OrdinalIgnoreCase);\n\n        public void AddFile(string file, MemoryStream content = null)\n        {\n            content = content ?? new MemoryStream();\n            _files[file] = content;\n        }\n\n        public bool FileExists(string path)\n        {\n            return _files.ContainsKey(path);\n        }\n\n        public Stream ReadFile(string path)\n        {\n            return _files[path];\n        }\n\n        public Stream OpenFile(string path)\n        {\n            MemoryStream memoryStream;\n            if (_files.TryGetValue(path, out memoryStream))\n            {\n                var copiedStream = new MemoryStream(memoryStream.ToArray());\n                _files[path] = copiedStream;\n            }\n            else\n            {\n                AddFile(path);\n            }\n            return _files[path];\n        }\n\n        public IEnumerable<string> EnumerateFiles(string path)\n        {\n            return from file in _files.Keys\n                   where Path.GetDirectoryName(file).Equals(path, StringComparison.OrdinalIgnoreCase)\n                   select file;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Deployment.Test/TestFiles/ConfigTestSites/CshtmlFileConfigV1/Default.cshtml",
    "content": "﻿<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n<html>\n\t<head>\n\t\t<title></title>\n\t</head>\n\t<body>\n\t    Not a plan9 app!\n\t</body>\n</html>"
  },
  {
    "path": "test/System.Web.WebPages.Deployment.Test/TestFiles/ConfigTestSites/CshtmlFileConfigV1/web.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n    <appSettings>\n        <add key=\"webpages:Version\" value=\"1.0\" />\n    </appSettings>\n</configuration>"
  },
  {
    "path": "test/System.Web.WebPages.Deployment.Test/TestFiles/ConfigTestSites/CshtmlFileNoVersion/Default.cshtml",
    "content": "﻿<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n<html>\n\t<head>\n\t\t<title></title>\n\t</head>\n\t<body>\n\t    Not a plan9 app!\n\t</body>\n</html>"
  },
  {
    "path": "test/System.Web.WebPages.Deployment.Test/TestFiles/ConfigTestSites/NoCshtml/Default.htm",
    "content": "﻿<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n<html>\n\t<head>\n\t\t<title></title>\n\t</head>\n\t<body>\n\t    Not a plan9 app!\n\t</body>\n</html>"
  },
  {
    "path": "test/System.Web.WebPages.Deployment.Test/TestFiles/ConfigTestSites/NoCshtmlConfigv1/Default.htm",
    "content": "﻿<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n<html>\n\t<head>\n\t\t<title></title>\n\t</head>\n\t<body>\n\t    Not a plan9 app!\n\t</body>\n</html>"
  },
  {
    "path": "test/System.Web.WebPages.Deployment.Test/TestFiles/ConfigTestSites/NoCshtmlConfigv1/web.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n    <appSettings>\n        <add key=\"webPages:version\" value=\"1.0\" />\n    </appSettings>\n</configuration>"
  },
  {
    "path": "test/System.Web.WebPages.Deployment.Test/TestFiles/ConfigTestSites/NoCshtmlNoConfigSetting/Default.htm",
    "content": "﻿<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n<html>\n\t<head>\n\t\t<title></title>\n\t</head>\n\t<body>\n\t    Not a plan9 app!\n\t</body>\n</html>"
  },
  {
    "path": "test/System.Web.WebPages.Deployment.Test/TestFiles/ConfigTestSites/NoCshtmlNoConfigSetting/web.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n</configuration>"
  },
  {
    "path": "test/System.Web.WebPages.Deployment.Test/TestFiles/ConfigTestSites/NoCshtmlWithEnabledSetting/Default.htm",
    "content": "﻿<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n<html>\n\t<head>\n\t\t<title></title>\n\t</head>\n\t<body>\n\t    Not a plan9 app!\n\t</body>\n</html>"
  },
  {
    "path": "test/System.Web.WebPages.Deployment.Test/TestFiles/ConfigTestSites/NoCshtmlWithEnabledSetting/web.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n    <appSettings>\n        <add key=\"webpages:Enabled\" value=\"true\" />\n    </appSettings>\n</configuration>"
  },
  {
    "path": "test/System.Web.WebPages.Deployment.Test/TestFiles/ConfigTestSites/NoCshtmlWithEnabledSettingFalse/Default.htm",
    "content": "﻿<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n<html>\n\t<head>\n\t\t<title></title>\n\t</head>\n\t<body>\n\t    Not a plan9 app!\n\t</body>\n</html>"
  },
  {
    "path": "test/System.Web.WebPages.Deployment.Test/TestFiles/ConfigTestSites/NoCshtmlWithEnabledSettingFalse/web.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n    <appSettings>\n        <add key=\"webpages:Enabled\" value=\"false\" />\n    </appSettings>\n</configuration>"
  },
  {
    "path": "test/System.Web.WebPages.Deployment.Test/WebPagesDeploymentTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.IO;\nusing System.Reflection;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Deployment.Test\n{\n    // We need to mark this type Serializable for TDD.Net to work with some of the AppDomain tests\n    [Serializable]\n    public class WebPagesDeploymentTest : IDisposable\n    {\n        private const string TestNamespacePrefix = \"System.Web.WebPages.Deployment.Test.TestFiles.\";\n\n        private static readonly IDictionary<string, string> _deploymentPaths = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)\n        {\n            { @\"ConfigTestSites.CshtmlFileNoVersion.Default.cshtml\", @\"ConfigTestSites\\CshtmlFileNoVersion\\Default.cshtml\" },\n            { @\"ConfigTestSites.NoCshtmlWithEnabledSetting.Default.htm\", @\"ConfigTestSites\\NoCshtmlWithEnabledSetting\\Default.htm\" },\n            { @\"ConfigTestSites.NoCshtmlNoConfigSetting.web.config\", @\"ConfigTestSites\\NoCshtmlNoConfigSetting\\web.config\" },\n            { @\"ConfigTestSites.NoCshtmlWithEnabledSetting.web.config\", @\"ConfigTestSites\\NoCshtmlWithEnabledSetting\\web.config\" },\n            { @\"ConfigTestSites.NoCshtmlWithEnabledSettingFalse.Default.htm\", @\"ConfigTestSites\\NoCshtmlWithEnabledSettingFalse\\Default.htm\" },\n            { @\"ConfigTestAssemblies.V2_Unsigned.System.Web.WebPages.Deployment.dll\", @\"ConfigTestAssemblies\\V2_Unsigned\\System.Web.WebPages.Deployment.dll\" },\n            { @\"ConfigTestAssemblies.V2_Signed.System.Web.WebPages.Deployment.dll\", @\"ConfigTestAssemblies\\V2_Signed\\System.Web.WebPages.Deployment.dll\" },\n            { @\"ConfigTestSites.NoCshtmlWithEnabledSettingFalse.web.config\", @\"ConfigTestSites\\NoCshtmlWithEnabledSettingFalse\\web.config\" },\n            { @\"ConfigTestSites.CshtmlFileConfigV1.Default.cshtml\", @\"ConfigTestSites\\CshtmlFileConfigV1\\Default.cshtml\" },\n            { @\"ConfigTestSites.NoCshtml.Default.htm\", @\"ConfigTestSites\\NoCshtml\\Default.htm\" },\n            { @\"ConfigTestSites.NoCshtmlNoConfigSetting.Default.htm\", @\"ConfigTestSites\\NoCshtmlNoConfigSetting\\Default.htm\" },\n            { @\"ConfigTestSites.CshtmlFileConfigV1.web.config\", @\"ConfigTestSites\\CshtmlFileConfigV1\\web.config\" },\n            { @\"ConfigTestSites.NoCshtmlConfigV1.Default.htm\", @\"ConfigTestSites\\NoCshtmlConfigV1\\Default.htm\" },\n            { @\"ConfigTestSites.NoCshtmlConfigV1.web.config\", @\"ConfigTestSites\\NoCshtmlConfigV1\\web.config\" },\n        };\n\n        private readonly string _tempPath = GetTempPath();\n\n        public WebPagesDeploymentTest()\n        {\n            var assembly = typeof(WebPagesDeploymentTest).Assembly;\n            foreach (var item in _deploymentPaths)\n            {\n                new TestFile(TestNamespacePrefix + item.Key, assembly).Save(Path.Combine(_tempPath, item.Value));\n            }\n        }\n\n        public void Dispose()\n        {\n            try\n            {\n                Directory.Delete(_tempPath, recursive: true);\n            }\n            catch\n            {\n            }\n        }\n\n        [Fact]\n        public void IsEnabledReturnsFalseIfNoCshtmlOrConfigFile()\n        {\n            Assert.False(WebPagesDeployment.IsEnabled(Path.Combine(_tempPath, @\"ConfigTestSites\\NoCshtml\")));\n        }\n\n        [Fact]\n        public void IsEnabledReturnsFalseIfNoCshtmlAndNoConfigSetting()\n        {\n            Assert.False(WebPagesDeployment.IsEnabled(Path.Combine(_tempPath, @\"ConfigTestSites\\NoCshtmlNoConfigSetting\")));\n        }\n\n        [Fact]\n        public void IsEnabledReturnsTrueIfNoCshtmlAndEnabledConfigSetting()\n        {\n            Assert.True(WebPagesDeployment.IsEnabled(Path.Combine(_tempPath, @\"ConfigTestSites\\NoCshtmlWithEnabledSetting\")));\n        }\n\n        [Fact]\n        public void IsEnabledReturnsTrueIfCshtmlFilePresent()\n        {\n            Assert.True(WebPagesDeployment.IsEnabled(Path.Combine(_tempPath, @\"ConfigTestSites\\CshtmlFileNoVersion\")));\n        }\n\n        [Fact]\n        public void IsExplicitlyDisabledReturnsTrueIfNoCshtmlAndEnabledConfigSettingSetToFalse()\n        {\n            Assert.True(WebPagesDeployment.IsExplicitlyDisabled(Path.Combine(_tempPath, @\"ConfigTestSites\\NoCshtmlWithEnabledSettingFalse\")));\n        }\n\n        [Fact]\n        public void IsExplicitlyDisabledReturnsFalseIfNoCshtmlAndEnabledConfigSettingSetToTrue()\n        {\n            Assert.False(WebPagesDeployment.IsExplicitlyDisabled(Path.Combine(_tempPath, @\"ConfigTestSites\\NoCshtmlWithEnabledSetting\")));\n        }\n\n        [Fact]\n        public void IsExplicitlyDisabledReturnsFalseIfNoCshtmlAndNoConfigSetting()\n        {\n            Assert.False(WebPagesDeployment.IsExplicitlyDisabled(Path.Combine(_tempPath, @\"ConfigTestSites\\NoCshtmlNoConfigSetting\")));\n        }\n\n        [Fact]\n        public void IsExplicitlyDisabledReturnsFalseIfNoCshtmlOrConfigFile()\n        {\n            Assert.False(WebPagesDeployment.IsExplicitlyDisabled(Path.Combine(_tempPath, @\"ConfigTestSites\\NoCshtml\")));\n        }\n\n        [Fact]\n        public void GetVersionReturnsValueFromAppSettingsIfNotExplicitlyDisabled()\n        {\n            // Arrange\n            var version = \"1.2.3.4\";\n            var appSettings = new NameValueCollection { { \"webPages:Version\", version } };\n            var maxVersion = new Version(\"2.0\");\n\n            // Act\n            var actualVersion = WebPagesDeployment.GetVersionInternal(appSettings, binVersion: null, defaultVersion: null);\n\n            // Assert\n            Assert.Equal(new Version(version), actualVersion);\n        }\n\n        [Fact]\n        public void GetVersionReturnsValueEvenIfExplicitlyDisabled()\n        {\n            // Arrange\n            var version = \"1.2.3.4\";\n            var appSettings = new NameValueCollection { { \"webPages:Version\", version }, { \"webPages:Enabled\", \"False\" } };\n            var maxVersion = new Version(\"2.0\");\n\n            // Act\n            var actualVersion = WebPagesDeployment.GetVersionInternal(appSettings, binVersion: null, defaultVersion: null);\n\n            // Assert\n            Assert.Equal(new Version(version), actualVersion);\n        }\n\n        [Fact]\n        public void GetVersionReturnsLowerVersionIfSpecifiedInConfig()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                // Arrange - Load v2 Config\n                Assembly asm = Assembly.LoadFrom(Path.Combine(_tempPath, @\"ConfigTestAssemblies\\V2_Signed\\System.Web.WebPages.Deployment.dll\"));\n                Assert.Equal(new Version(2, 0, 0, 0), asm.GetName().Version);\n                Assert.Equal(\"System.Web.WebPages.Deployment\", asm.GetName().Name);\n\n                using (WebUtils.CreateHttpRuntime(@\"~\\foo\", \".\"))\n                {\n                    string path = Path.Combine(_tempPath, @\"ConfigTestSites\\CshtmlFileConfigV1\");\n\n                    // Act\n                    Version ver = WebPagesDeployment.GetVersionWithoutEnabledCheck(path);\n                    Version explicitVersion = WebPagesDeployment.GetExplicitWebPagesVersion(path);\n\n                    // Assert\n                    Assert.Equal(new Version(1, 0, 0, 0), ver);\n                    Assert.Equal(new Version(1, 0, 0, 0), explicitVersion);\n                }\n            });\n        }\n\n        [Fact]\n        public void GetVersionReturnsLowerVersionIfSpecifiedInConfigAndNotExplicitlyDisabled()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                // Arrange - Load v2 Config\n                Assembly asm = Assembly.LoadFrom(Path.Combine(_tempPath, @\"ConfigTestAssemblies\\V2_Signed\\System.Web.WebPages.Deployment.dll\"));\n                Assert.Equal(new Version(2, 0, 0, 0), asm.GetName().Version);\n                Assert.Equal(\"System.Web.WebPages.Deployment\", asm.GetName().Name);\n\n                using (WebUtils.CreateHttpRuntime(@\"~\\foo\", \".\"))\n                {\n                    string path = Path.Combine(_tempPath, @\"ConfigTestSites\\NoCshtmlConfigV1\");\n\n                    // Act\n                    Version ver = WebPagesDeployment.GetVersionWithoutEnabledCheck(path);\n                    Version explicitVersion = WebPagesDeployment.GetExplicitWebPagesVersion(path);\n\n                    // Assert\n                    Assert.Equal(new Version(1, 0, 0, 0), ver);\n                    Assert.Equal(new Version(1, 0, 0, 0), explicitVersion);\n                }\n            });\n        }\n\n        [Fact]\n        public void GetVersionIgnoresUnsignedConfigDll()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                // Arrange - Load v2 Config\n                Assembly asm = Assembly.LoadFrom(Path.Combine(_tempPath, @\"ConfigTestAssemblies\\V2_Unsigned\\System.Web.WebPages.Deployment.dll\"));\n                Assert.Equal(new Version(2, 0, 0, 0), asm.GetName().Version);\n                Assert.Equal(\"System.Web.WebPages.Deployment\", asm.GetName().Name);\n\n                using (WebUtils.CreateHttpRuntime(@\"~\\foo\", \".\"))\n                {\n                    // Act\n                    Version ver = WebPagesDeployment.GetVersionWithoutEnabledCheck(Path.Combine(_tempPath, @\"ConfigTestSites\\CshtmlFileNoVersion\"));\n\n                    // Assert\n                    Assert.Equal(new Version(\"1.0.0.0\"), ver);\n                }\n            });\n        }\n\n        [Fact]\n        public void GetVersionReturnsV1IfCshtmlFilePresentButNoVersionIsSpecifiedInConfigOrBin()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                // Arrange - Load v2 Config\n                Assembly asm = Assembly.LoadFrom(Path.Combine(_tempPath, @\"ConfigTestAssemblies\\V2_Signed\\System.Web.WebPages.Deployment.dll\"));\n                Assert.Equal(new Version(2, 0, 0, 0), asm.GetName().Version);\n                Assert.Equal(\"System.Web.WebPages.Deployment\", asm.GetName().Name);\n\n                using (WebUtils.CreateHttpRuntime(@\"~\\foo\", \".\"))\n                {\n                    string path = Path.Combine(_tempPath, @\"ConfigTestSites\\CshtmlFileNoVersion\");\n\n                    // Act\n                    Version ver = WebPagesDeployment.GetVersionWithoutEnabledCheck(path);\n                    Version explicitVersion = WebPagesDeployment.GetExplicitWebPagesVersion(path);\n\n                    // Assert\n                    Assert.Equal(new Version(\"1.0.0.0\"), ver);\n                    Assert.Null(explicitVersion);\n                }\n            });\n        }\n\n        [Fact]\n        public void GetVersionThrowsIfPathNullOrEmpty()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(() => WebPagesDeployment.GetVersionWithoutEnabledCheck(null), \"path\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => WebPagesDeployment.GetVersionWithoutEnabledCheck(String.Empty), \"path\");\n        }\n\n        [Fact]\n        public void IsEnabledThrowsIfPathNullOrEmpty()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(() => WebPagesDeployment.IsEnabled(null), \"path\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => WebPagesDeployment.IsEnabled(String.Empty), \"path\");\n        }\n\n        [Theory]\n        [InlineData(new object[] { null })]\n        [InlineData(new object[] { \"\" })]\n        public void ObsoleteGetVersionThrowsIfPathIsNullOrEmpty(string path)\n        {\n            // Arrange\n            var fileSystem = new TestFileSystem();\n            var configuration = new NameValueCollection();\n\n            // Act and Assert\n            Assert.ThrowsArgumentNullOrEmptyString(() => WebPagesDeployment.GetObsoleteVersionInternal(path, configuration, fileSystem), \"path\");\n        }\n\n        [Fact]\n        public void ObsoleteGetVersionReturnsNullIfNoFilesInTheSite()\n        {\n            // Arrange\n            var path = \"blah\";\n            var fileSystem = new TestFileSystem();\n            var configuration = new NameValueCollection();\n\n            // Act\n            var version = WebPagesDeployment.GetObsoleteVersionInternal(path, configuration, fileSystem);\n\n            // Assert\n            Assert.Null(version);\n        }\n\n        [Fact]\n        public void ObsoleteGetVersionReturnsV1VersionIfNoValueInConfigNoFilesInBinSiteContainsCshtmlFiles()\n        {\n            // Arrange\n            var path = \"blah\";\n            var fileSystem = new TestFileSystem();\n            fileSystem.AddFile(@\"blah\\Foo.cshtml\");\n            var configuration = new NameValueCollection();\n\n            // Act\n            var version = WebPagesDeployment.GetObsoleteVersionInternal(path, configuration, fileSystem);\n\n            // Assert\n            Assert.Equal(new Version(\"1.0.0.0\"), version);\n        }\n\n        [Fact]\n        public void ObsoleteGetVersionReturnsVersionFromConfigIfDisabled()\n        {\n            // Arrange\n            var maxVersion = new Version(\"3.0.3.4\");\n            var fileSystem = new TestFileSystem();\n            var configuration = new NameValueCollection();\n            configuration[\"webPages:Enabled\"] = \"False\";\n            configuration[\"webPages:Version\"] = \"3.0\";\n            var path = \"blah\";\n\n            // Act\n            var version = WebPagesDeployment.GetObsoleteVersionInternal(path, configuration, fileSystem);\n\n            // Assert\n            Assert.Equal(new Version(\"3.0.0.0\"), version);\n        }\n\n        private static string GetTempPath()\n        {\n            return Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Deployment.Test/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"xunit\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.abstractions\" version=\"2.0.3\" targetFramework=\"net462\" />\n  <package id=\"xunit.analyzers\" version=\"1.1.0\" targetFramework=\"net462\" />\n  <package id=\"xunit.assert\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.execution\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.runner.visualstudio\" version=\"2.4.5\" targetFramework=\"net462\" developmentDependency=\"true\" />\n</packages>"
  },
  {
    "path": "test/System.Web.WebPages.Razor.Test/PreApplicationStartCodeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing System.Web.Compilation;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Razor.Test\n{\n    public class PreApplicationStartCodeTest\n    {\n        [Fact]\n        public void StartTest()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                AppDomainUtils.SetPreAppStartStage();\n                PreApplicationStartCode.Start();\n                var buildProviders = typeof(BuildProvider).GetField(\"s_dynamicallyRegisteredProviders\", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);\n                Assert.Equal(2, buildProviders.GetType().GetProperty(\"Count\", BindingFlags.Public | BindingFlags.Instance).GetValue(buildProviders, new object[] { }));\n            });\n        }\n\n        [Fact]\n        public void TestPreAppStartClass()\n        {\n            PreAppStartTestHelper.TestPreAppStartClass(typeof(PreApplicationStartCode));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Razor.Test/RazorBuildProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.CodeDom.Compiler;\nusing System.Collections;\nusing System.IO;\nusing System.Linq;\nusing System.Reflection;\nusing System.Web.Compilation;\nusing ASP;\nusing Microsoft.CSharp;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace ASP\n{\n    public class _Page_Foo_Test_cshtml\n    {\n    }\n}\n\nnamespace System.Web.WebPages.Razor.Test\n{\n    public class RazorBuildProviderTest\n    {\n        private class MockAssemblyBuilder : IAssemblyBuilder\n        {\n            public BuildProvider BuildProvider { get; private set; }\n            public CodeCompileUnit CompileUnit { get; private set; }\n            public string LastTypeFactoryGenerated { get; private set; }\n\n            public void AddCodeCompileUnit(BuildProvider buildProvider, CodeCompileUnit compileUnit)\n            {\n                BuildProvider = buildProvider;\n                CompileUnit = compileUnit;\n            }\n\n            public void GenerateTypeFactory(string typeName)\n            {\n                LastTypeFactoryGenerated = typeName;\n            }\n        }\n\n        [Fact]\n        public void CodeCompilerTypeReturnsTypeFromCodeLanguage()\n        {\n            // Arrange\n            WebPageRazorHost host = new WebPageRazorHost(\"~/Foo/Baz.cshtml\", @\"C:\\Foo\\Baz.cshtml\");\n            RazorBuildProvider provider = CreateBuildProvider(\"foo @bar baz\");\n            provider.Host = host;\n\n            // Act\n            CompilerType type = provider.CodeCompilerType;\n\n            // Assert\n            Assert.Equal(typeof(CSharpCodeProvider), type.CodeDomProviderType);\n        }\n\n        [Fact]\n        public void CodeCompilerTypeSetsDebugFlagInFullTrust()\n        {\n            // Arrange\n            WebPageRazorHost host = new WebPageRazorHost(\"~/Foo/Baz.cshtml\", @\"C:\\Foo\\Baz.cshtml\");\n            RazorBuildProvider provider = CreateBuildProvider(\"foo @bar baz\");\n            provider.Host = host;\n\n            // Act\n            CompilerType type = provider.CodeCompilerType;\n\n            // Assert\n            Assert.True(type.CompilerParameters.IncludeDebugInformation);\n        }\n\n        [Fact]\n        public void GetGeneratedTypeUsesNameAndNamespaceFromHostToExtractType()\n        {\n            // Arrange\n            WebPageRazorHost host = new WebPageRazorHost(\"~/Foo/Test.cshtml\", @\"C:\\Foo\\Test.cshtml\");\n            RazorBuildProvider provider = new RazorBuildProvider() { Host = host };\n            CompilerResults results = new CompilerResults(new TempFileCollection());\n            results.CompiledAssembly = typeof(_Page_Foo_Test_cshtml).Assembly;\n\n            // Act\n            Type typ = provider.GetGeneratedType(results);\n\n            // Assert\n            Assert.Equal(typeof(_Page_Foo_Test_cshtml), typ);\n        }\n\n        [Fact]\n        public void GenerateCodeCoreAddsGeneratedCodeToAssemblyBuilder()\n        {\n            // Arrange\n            WebPageRazorHost host = new WebPageRazorHost(\"~/Foo/Baz.cshtml\", @\"C:\\Foo\\Baz.cshtml\");\n            RazorBuildProvider provider = new RazorBuildProvider();\n            CodeCompileUnit ccu = new CodeCompileUnit();\n            MockAssemblyBuilder asmBuilder = new MockAssemblyBuilder();\n            provider.Host = host;\n            provider.GeneratedCode = ccu;\n\n            // Act\n            provider.GenerateCodeCore(asmBuilder);\n\n            // Assert\n            Assert.Same(provider, asmBuilder.BuildProvider);\n            Assert.Same(ccu, asmBuilder.CompileUnit);\n            Assert.Equal(\"ASP._Page_Foo_Baz_cshtml\", asmBuilder.LastTypeFactoryGenerated);\n        }\n\n        [Fact]\n        public void CodeGenerationStartedTest()\n        {\n            // Arrange\n            WebPageRazorHost host = new WebPageRazorHost(\"~/Foo/Baz.cshtml\", @\"C:\\Foo\\Baz.cshtml\");\n            RazorBuildProvider provider = CreateBuildProvider(\"foo @bar baz\");\n            provider.Host = host;\n\n            // Expected original base dependencies\n            var baseDependencies = new ArrayList();\n            baseDependencies.Add(\"/Samples/Foo/Baz.cshtml\");\n\n            // Expected list of dependencies after GenerateCode is called\n            var dependencies = new ArrayList();\n            dependencies.Add(baseDependencies[0]);\n            dependencies.Add(\"/Samples/Foo/Foo.cshtml\");\n\n            // Set up the event handler\n            provider.CodeGenerationStartedInternal += (sender, e) =>\n            {\n                var bp = sender as RazorBuildProvider;\n                bp.AddVirtualPathDependency(\"/Samples/Foo/Foo.cshtml\");\n            };\n\n            // Set up the base dependency\n            MockAssemblyBuilder builder = new MockAssemblyBuilder();\n            typeof(BuildProvider).GetField(\"_virtualPath\", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(provider, CreateVirtualPath(\"/Samples/Foo/Baz.cshtml\"));\n\n            // Test that VirtualPathDependencies returns the original dependency before GenerateCode is called\n            Assert.True(baseDependencies.OfType<string>().SequenceEqual(provider.VirtualPathDependencies.OfType<string>()));\n\n            // Act\n            provider.GenerateCodeCore(builder);\n\n            // Assert\n            Assert.NotNull(provider.AssemblyBuilderInternal);\n            Assert.Equal(builder, provider.AssemblyBuilderInternal);\n            Assert.True(dependencies.OfType<string>().SequenceEqual(provider.VirtualPathDependencies.OfType<string>()));\n            Assert.Equal(\"/Samples/Foo/Baz.cshtml\", provider.VirtualPath);\n        }\n\n        [Fact]\n        public void AfterGeneratedCodeEventGetsExecutedAtCorrectTime()\n        {\n            // Arrange\n            WebPageRazorHost host = new WebPageRazorHost(\"~/Foo/Baz.cshtml\", @\"C:\\Foo\\Baz.cshtml\");\n            RazorBuildProvider provider = CreateBuildProvider(\"foo @bar baz\");\n            provider.Host = host;\n\n            provider.CodeGenerationCompletedInternal += (sender, e) =>\n            {\n                Assert.Equal(\"~/Foo/Baz.cshtml\", e.VirtualPath);\n                e.GeneratedCode.Namespaces.Add(new CodeNamespace(\"DummyNamespace\"));\n            };\n\n            // Act\n            CodeCompileUnit generated = provider.GeneratedCode;\n\n            // Assert\n            Assert.NotNull(generated.Namespaces\n                               .OfType<CodeNamespace>()\n                               .SingleOrDefault(ns => String.Equals(ns.Name, \"DummyNamespace\")));\n        }\n\n        [Fact]\n        public void GeneratedCodeThrowsHttpParseExceptionForLastParserError()\n        {\n            // Arrange\n            WebPageRazorHost host = new WebPageRazorHost(\"~/Foo/Baz.cshtml\", @\"C:\\Foo\\Baz.cshtml\");\n            RazorBuildProvider provider = CreateBuildProvider(\"foo @{ if( baz\");\n            provider.Host = host;\n\n            // Act\n            Assert.Throws<HttpParseException>(() => { CodeCompileUnit ccu = provider.GeneratedCode; });\n        }\n\n        [Fact]\n        public void BuildProviderFiresEventToAlterHostBeforeBuildingPath()\n        {\n            // Arrange\n            WebPageRazorHost expected = new TestHost(\"~/Foo/Boz.cshtml\", @\"C:\\Foo\\Boz.cshtml\");\n            WebPageRazorHost expectedBefore = new WebPageRazorHost(\"~/Foo/Baz.cshtml\", @\"C:\\Foo\\Baz.cshtml\");\n            RazorBuildProvider provider = CreateBuildProvider(\"foo\");\n            typeof(BuildProvider).GetField(\"_virtualPath\", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(provider, CreateVirtualPath(\"/Samples/Foo/Baz.cshtml\"));\n            Mock.Get(provider).Setup(p => p.GetHostFromConfig()).Returns(expectedBefore);\n            bool called = false;\n            EventHandler<CompilingPathEventArgs> handler = (sender, args) =>\n            {\n                Assert.Equal(\"/Samples/Foo/Baz.cshtml\", args.VirtualPath);\n                Assert.Same(expectedBefore, args.Host);\n                args.Host = expected;\n                called = true;\n            };\n            RazorBuildProvider.CompilingPath += handler;\n\n            try\n            {\n                // Act\n                CodeCompileUnit ccu = provider.GeneratedCode;\n\n                // Assert\n                Assert.Equal(\"Test\", ccu.Namespaces[0].Name);\n                Assert.Same(expected, provider.Host);\n                Assert.True(called);\n            }\n            finally\n            {\n                RazorBuildProvider.CompilingPath -= handler;\n            }\n        }\n\n        private static object CreateVirtualPath(string path)\n        {\n            var vPath = typeof(BuildProvider).Assembly.GetType(\"System.Web.VirtualPath\");\n            var method = vPath.GetMethod(\"CreateNonRelative\", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);\n            return method.Invoke(null, new object[] { path });\n        }\n\n        private static RazorBuildProvider CreateBuildProvider(string razorContent)\n        {\n            Mock<RazorBuildProvider> mockProvider = new Mock<RazorBuildProvider>()\n            {\n                CallBase = true\n            };\n            mockProvider.Setup(p => p.InternalOpenReader())\n                .Returns(() => new StringReader(razorContent));\n            return mockProvider.Object;\n        }\n\n        private class TestHost : WebPageRazorHost\n        {\n            public TestHost(string virtualPath, string physicalPath) : base(virtualPath, physicalPath) { }\n\n            public override void PostProcessGeneratedCode(Web.Razor.Generator.CodeGeneratorContext context)\n            {\n                context.CompileUnit.Namespaces.Insert(0, new CodeNamespace(\"Test\"));\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Razor.Test/System.Web.WebPages.Razor.Test.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props\" Condition=\"Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" />\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" />\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{66A74F3C-A106-4C1E-BAA0-001908FEA2CA}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>System.Web.WebPages.Razor.Test</RootNamespace>\n    <AssemblyName>System.Web.WebPages.Razor.Test</AssemblyName>\n    <OutputPath>..\\..\\bin\\$(Configuration)\\Test\\</OutputPath>\n    <!-- Temporarily disable Obsolete Warnings as Errors -->\n    <NoWarn>0618</NoWarn>\n    <NuGetPackageImportStamp>\n    </NuGetPackageImportStamp>\n  </PropertyGroup>\n  <ItemGroup>\n    <Compile Include=\"PreApplicationStartCodeTest.cs\" />\n    <Compile Include=\"RazorBuildProviderTest.cs\" />\n    <Compile Include=\"WebCodeRazorEngineHostTest.cs\" />\n    <Compile Include=\"WebPageRazorEngineHostTest.cs\" />\n    <Compile Include=\"WebRazorHostFactoryTest.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Reference Include=\"Castle.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Castle.Core.5.1.1\\lib\\net462\\Castle.Core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"Moq, Version=4.18.0.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Moq.4.18.4\\lib\\net462\\Moq.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.abstractions.2.0.3\\lib\\net35\\xunit.abstractions.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.assert, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.assert.2.4.2\\lib\\netstandard1.1\\xunit.assert.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.core, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.core.2.4.2\\lib\\net452\\xunit.core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.execution.desktop, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.execution.2.4.2\\lib\\net452\\xunit.execution.desktop.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.WebPages\\System.Web.WebPages.csproj\">\n      <Project>{76EFA9C5-8D7E-4FDF-B710-E20F8B6B00D2}</Project>\n      <Name>System.Web.WebPages</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Razor\\System.Web.Razor.csproj\">\n      <Project>{8F18041B-9410-4C36-A9C5-067813DF5F31}</Project>\n      <Name>System.Web.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.WebPages.Razor\\System.Web.WebPages.Razor.csproj\">\n      <Project>{0939B11A-FE4E-4BA1-8AD6-D97741EE314F}</Project>\n      <Name>System.Web.WebPages.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\">\n      <Project>{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}</Project>\n      <Name>Microsoft.TestCommon</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"app.config\">\n      <SubType>Designer</SubType>\n    </None>\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Service Include=\"{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Analyzer Include=\"..\\..\\packages\\xunit.analyzers.1.1.0\\analyzers\\dotnet\\cs\\xunit.analyzers.dll\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\n  <Target Name=\"EnsureNuGetPackageBuildImports\" BeforeTargets=\"PrepareForBuild\">\n    <PropertyGroup>\n      <ErrorText>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}.</ErrorText>\n    </PropertyGroup>\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props'))\" />\n  </Target>\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" />\n</Project>"
  },
  {
    "path": "test/System.Web.WebPages.Razor.Test/WebCodeRazorEngineHostTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.Linq;\nusing System.Web.Razor.Generator;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Razor.Test\n{\n    public class WebCodeRazorEngineHostTest\n    {\n        [Fact]\n        public void ConstructorWithMalformedVirtualPathSetsDefaultProperties()\n        {\n            // Act\n            WebCodeRazorHost host = new WebCodeRazorHost(@\"~/Foo/App_Code\\Bar\\Baz\\Qux.cshtml\");\n\n            // Assert\n            Assert.Equal(\"System.Web.WebPages.HelperPage\", host.DefaultBaseClass);\n            Assert.Equal(\"ASP.Bar.Baz\", host.DefaultNamespace);\n            Assert.Equal(\"Qux\", host.DefaultClassName);\n            Assert.False(host.DefaultDebugCompilation);\n            Assert.True(host.StaticHelpers);\n        }\n\n        [Fact]\n        public void ConstructorWithFileOnlyVirtualPathSetsDefaultProperties()\n        {\n            // Act\n            WebCodeRazorHost host = new WebCodeRazorHost(@\"Foo.cshtml\");\n\n            // Assert\n            Assert.Equal(\"System.Web.WebPages.HelperPage\", host.DefaultBaseClass);\n            Assert.Equal(\"ASP\", host.DefaultNamespace);\n            Assert.Equal(\"Foo\", host.DefaultClassName);\n            Assert.False(host.DefaultDebugCompilation);\n        }\n\n        [Fact]\n        public void ConstructorWithVirtualPathSetsDefaultProperties()\n        {\n            // Act\n            WebCodeRazorHost host = new WebCodeRazorHost(\"~/Foo/App_Code/Bar/Baz/Qux.cshtml\");\n\n            // Assert\n            Assert.Equal(\"System.Web.WebPages.HelperPage\", host.DefaultBaseClass);\n            Assert.Equal(\"ASP.Bar.Baz\", host.DefaultNamespace);\n            Assert.Equal(\"Qux\", host.DefaultClassName);\n            Assert.False(host.DefaultDebugCompilation);\n        }\n\n        [Fact]\n        public void ConstructorWithVirtualAndPhysicalPathSetsDefaultProperties()\n        {\n            // Act\n            WebCodeRazorHost host = new WebCodeRazorHost(\"~/Foo/App_Code/Bar/Baz/Qux.cshtml\", @\"C:\\Qux.doodad\");\n\n            // Assert\n            Assert.Equal(\"System.Web.WebPages.HelperPage\", host.DefaultBaseClass);\n            Assert.Equal(\"ASP.Bar.Baz\", host.DefaultNamespace);\n            Assert.Equal(\"Qux\", host.DefaultClassName);\n            Assert.False(host.DefaultDebugCompilation);\n        }\n\n        [Fact]\n        public void PostProcessGeneratedCodeRemovesExecuteMethod()\n        {\n            // Arrange\n            WebCodeRazorHost host = new WebCodeRazorHost(\"Foo.cshtml\");\n            CodeGeneratorContext context = CodeGeneratorContext.Create(\n                host,\n                () => new CSharpCodeWriter(),\n                \"TestClass\",\n                \"TestNamespace\",\n                \"TestFile.cshtml\",\n                shouldGenerateLinePragmas: true);\n\n            // Act\n            host.PostProcessGeneratedCode(context);\n\n            // Assert\n            Assert.Empty(context.GeneratedClass.Members.OfType<CodeMemberMethod>());\n        }\n\n        [Fact]\n        public void PostProcessGeneratedCodeAddsStaticApplicationInstanceProperty()\n        {\n            // Arrange\n            WebCodeRazorHost host = new WebCodeRazorHost(\"Foo.cshtml\");\n            CodeGeneratorContext context =\n                CodeGeneratorContext.Create(\n                    host,\n                    () => new CSharpCodeWriter(),\n                    \"TestClass\",\n                    \"TestNamespace\",\n                    \"Foo.cshtml\",\n                    shouldGenerateLinePragmas: true);\n\n            // Act\n            host.PostProcessGeneratedCode(context);\n\n            // Assert\n            CodeMemberProperty appInstance = context.GeneratedClass\n                .Members\n                .OfType<CodeMemberProperty>()\n                .Where(p => p.Name.Equals(\"ApplicationInstance\"))\n                .SingleOrDefault();\n            Assert.NotNull(appInstance);\n            Assert.True(appInstance.Attributes.HasFlag(MemberAttributes.Static));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Razor.Test/WebPageRazorEngineHostTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.CodeDom;\nusing System.CodeDom.Compiler;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Web.Razor;\nusing System.Web.Razor.Generator;\nusing Microsoft.CSharp;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Razor.Test\n{\n    public class WebPageRazorEngineHostTest\n    {\n        [Fact]\n        public void ConstructorRequiresNonNullOrEmptyVirtualPath()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(() => new WebPageRazorHost(null), \"virtualPath\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => new WebPageRazorHost(String.Empty), \"virtualPath\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => new WebPageRazorHost(null, \"foo\"), \"virtualPath\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => new WebPageRazorHost(String.Empty, \"foo\"), \"virtualPath\");\n        }\n\n        [Fact]\n        public void ConstructorWithVirtualPathUsesItToDetermineBaseClassClassNameAndLanguage()\n        {\n            // Act\n            WebPageRazorHost host = new WebPageRazorHost(\"~/Foo/Bar.cshtml\");\n\n            // Assert\n            Assert.Equal(\"_Page_Foo_Bar_cshtml\", host.DefaultClassName);\n            Assert.Equal(\"System.Web.WebPages.WebPage\", host.DefaultBaseClass);\n            Assert.IsType<CSharpRazorCodeLanguage>(host.CodeLanguage);\n            Assert.False(host.StaticHelpers);\n        }\n\n        [Fact]\n        public void PostProcessGeneratedCodeAddsGlobalImports()\n        {\n            // Arrange\n            WebPageRazorHost.AddGlobalImport(\"Foo.Bar\");\n            WebPageRazorHost host = new WebPageRazorHost(\"Foo.cshtml\");\n            CodeGeneratorContext context = CodeGeneratorContext.Create(\n                host,\n                () => new CSharpCodeWriter(),\n                \"TestClass\",\n                \"TestNs\",\n                \"TestFile.cshtml\",\n                shouldGenerateLinePragmas: true);\n\n            // Act\n            host.PostProcessGeneratedCode(context);\n\n            // Assert\n            Assert.Contains(context.Namespace.Imports.OfType<CodeNamespaceImport>(), import => String.Equals(\"Foo.Bar\", import.Namespace));\n        }\n\n        [Fact]\n        public void PostProcessGeneratedCodeAddsApplicationInstanceProperty()\n        {\n            string expectedPropertyCode =\n                Environment.NewLine\n              + \"protected Foo.Bar ApplicationInstance {\" + Environment.NewLine\n              + \"    get {\" + Environment.NewLine\n              + \"        return ((Foo.Bar)(Context.ApplicationInstance));\" + Environment.NewLine\n              + \"    }\" + Environment.NewLine\n              + \"}\" + Environment.NewLine;\n\n            // Arrange\n            WebPageRazorHost host = new WebPageRazorHost(\"Foo.cshtml\")\n            {\n                GlobalAsaxTypeName = \"Foo.Bar\"\n            };\n            CodeGeneratorContext context = CodeGeneratorContext.Create(\n                host,\n                () => new CSharpCodeWriter(),\n                \"TestClass\",\n                \"TestNs\",\n                \"TestFile.cshtml\",\n                shouldGenerateLinePragmas: true);\n\n            // Act\n            host.PostProcessGeneratedCode(context);\n\n            // Assert\n            CodeMemberProperty property = context.GeneratedClass.Members[0] as CodeMemberProperty;\n            Assert.NotNull(property);\n\n            CSharpCodeProvider provider = new CSharpCodeProvider();\n            StringBuilder builder = new StringBuilder();\n            using (StringWriter writer = new StringWriter(builder))\n            {\n                provider.GenerateCodeFromMember(property, writer, new CodeGeneratorOptions());\n            }\n\n            Assert.Equal(expectedPropertyCode, builder.ToString());\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Razor.Test/WebRazorHostFactoryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Configuration;\nusing System.Reflection;\nusing System.Web.Configuration;\nusing System.Web.WebPages.Razor.Configuration;\nusing System.Web.WebPages.Razor.Resources;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Razor.Test\n{\n    public class WebRazorHostFactoryTest\n    {\n        public class TestFactory : WebRazorHostFactory\n        {\n            public override WebPageRazorHost CreateHost(string virtualPath, string physicalPath = null)\n            {\n                return new TestHost();\n            }\n        }\n\n        public class TestHost : WebPageRazorHost\n        {\n            public TestHost()\n                : base(\"Foo.cshtml\")\n            {\n            }\n\n            public new void RegisterSpecialFile(string fileName, Type baseType)\n            {\n                base.RegisterSpecialFile(fileName, baseType);\n            }\n\n            public new void RegisterSpecialFile(string fileName, string baseType)\n            {\n                base.RegisterSpecialFile(fileName, baseType);\n            }\n        }\n\n        [Fact]\n        public void CreateHostReturnsWebPageHostWithWebPageAsBaseClassIfVirtualPathIsNormalPage()\n        {\n            // Act\n            WebPageRazorHost host = new WebRazorHostFactory().CreateHost(\"~/Foo/Bar/Baz.cshtml\", null);\n\n            // Assert\n            Assert.IsType<WebPageRazorHost>(host);\n            Assert.Equal(WebPageRazorHost.PageBaseClass, host.DefaultBaseClass);\n        }\n\n        [Fact]\n        public void CreateHostReturnsWebPageHostWithInitPageAsBaseClassIfVirtualPathIsPageStart()\n        {\n            // Act\n            WebPageRazorHost host = new WebRazorHostFactory().CreateHost(\"~/Foo/Bar/_pagestart.cshtml\", null);\n\n            // Assert\n            Assert.IsType<WebPageRazorHost>(host);\n            Assert.Equal(typeof(StartPage).FullName, host.DefaultBaseClass);\n        }\n\n        [Fact]\n        public void CreateHostReturnsWebPageHostWithStartPageAsBaseClassIfVirtualPathIsAppStart()\n        {\n            // Act\n            WebPageRazorHost host = new WebRazorHostFactory().CreateHost(\"~/Foo/Bar/_appstart.cshtml\", null);\n\n            // Assert\n            Assert.IsType<WebPageRazorHost>(host);\n            Assert.Equal(typeof(ApplicationStartPage).FullName, host.DefaultBaseClass);\n        }\n\n        [Fact]\n        public void CreateHostPassesPhysicalPathOnToWebCodeRazorHost()\n        {\n            // Act\n            WebPageRazorHost host = new WebRazorHostFactory().CreateHost(\"~/Foo/Bar/Baz/App_Code/Bar\", @\"C:\\Foo.cshtml\");\n\n            // Assert\n            Assert.Equal(@\"C:\\Foo.cshtml\", host.PhysicalPath);\n        }\n\n        [Fact]\n        public void CreateHostPassesPhysicalPathOnToWebPageRazorHost()\n        {\n            // Act\n            WebPageRazorHost host = new WebRazorHostFactory().CreateHost(\"~/Foo/Bar/Baz/Bar\", @\"C:\\Foo.cshtml\");\n\n            // Assert\n            Assert.Equal(@\"C:\\Foo.cshtml\", host.PhysicalPath);\n        }\n\n        [Fact]\n        public void CreateHostFromConfigRequiresNonNullVirtualPath()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(() => WebRazorHostFactory.CreateHostFromConfig(virtualPath: null,\n                                                                                                physicalPath: \"foo\"), \"virtualPath\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => WebRazorHostFactory.CreateHostFromConfig(config: new RazorWebSectionGroup(),\n                                                                                                virtualPath: null,\n                                                                                                physicalPath: \"foo\"), \"virtualPath\");\n        }\n\n        [Fact]\n        public void CreateHostFromConfigRequiresNonEmptyVirtualPath()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(() => WebRazorHostFactory.CreateHostFromConfig(virtualPath: String.Empty,\n                                                                                                physicalPath: \"foo\"), \"virtualPath\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => WebRazorHostFactory.CreateHostFromConfig(config: new RazorWebSectionGroup(),\n                                                                                                virtualPath: String.Empty,\n                                                                                                physicalPath: \"foo\"), \"virtualPath\");\n        }\n\n        [Fact]\n        public void CreateHostFromConfigRequiresNonNullSectionGroup()\n        {\n            Assert.ThrowsArgumentNull(() => WebRazorHostFactory.CreateHostFromConfig(config: (RazorWebSectionGroup)null,\n                                                                                         virtualPath: String.Empty,\n                                                                                         physicalPath: \"foo\"), \"config\");\n        }\n\n        [Fact]\n        public void CreateHostFromConfigReturnsWebCodeHostIfVirtualPathStartsWithAppCode()\n        {\n            // Act\n            WebPageRazorHost host = WebRazorHostFactory.CreateHostFromConfigCore(null, \"~/App_Code/Bar.cshtml\", null);\n\n            // Assert\n            Assert.IsType<WebCodeRazorHost>(host);\n        }\n\n        [Fact]\n        public void CreateHostFromConfigUsesDefaultFactoryIfNoRazorWebSectionGroupFound()\n        {\n            // Act\n            WebPageRazorHost host = WebRazorHostFactory.CreateHostFromConfigCore(null, \"/Foo/Bar.cshtml\", null);\n\n            // Assert\n            Assert.IsType<WebPageRazorHost>(host);\n        }\n\n        [Fact]\n        public void CreateHostFromConfigUsesDefaultFactoryIfNoHostSectionFound()\n        {\n            // Arrange\n            RazorWebSectionGroup config = new RazorWebSectionGroup()\n            {\n                Host = null,\n                Pages = null\n            };\n\n            // Act\n            WebPageRazorHost host = WebRazorHostFactory.CreateHostFromConfig(config, \"/Foo/Bar.cshtml\", null);\n\n            // Assert\n            Assert.IsType<WebPageRazorHost>(host);\n        }\n\n        [Fact]\n        public void CreateHostFromConfigUsesDefaultFactoryIfNullFactoryType()\n        {\n            // Arrange\n            RazorWebSectionGroup config = new RazorWebSectionGroup()\n            {\n                Host = new HostSection()\n                {\n                    FactoryType = null\n                },\n                Pages = null\n            };\n\n            // Act\n            WebPageRazorHost host = WebRazorHostFactory.CreateHostFromConfig(config, \"/Foo/Bar.cshtml\", null);\n\n            // Assert\n            Assert.IsType<WebPageRazorHost>(host);\n        }\n\n        [Fact]\n        public void CreateHostFromConfigUsesFactorySpecifiedInConfig()\n        {\n            // Arrange\n            RazorWebSectionGroup config = new RazorWebSectionGroup()\n            {\n                Host = new HostSection()\n                {\n                    FactoryType = typeof(TestFactory).FullName\n                },\n                Pages = null\n            };\n            WebRazorHostFactory.TypeFactory = name => Assembly.GetExecutingAssembly().GetType(name, throwOnError: false);\n\n            // Act\n            WebPageRazorHost host = WebRazorHostFactory.CreateHostFromConfig(config, \"/Foo/Bar.cshtml\", null);\n\n            // Assert\n            Assert.IsType<TestHost>(host);\n        }\n\n        [Fact]\n        public void CreateHostFromConfigThrowsInvalidOperationExceptionIfFactoryTypeNotFound()\n        {\n            // Arrange\n            RazorWebSectionGroup config = new RazorWebSectionGroup()\n            {\n                Host = new HostSection()\n                {\n                    FactoryType = \"Foo\"\n                },\n                Pages = null\n            };\n            WebRazorHostFactory.TypeFactory = name => Assembly.GetExecutingAssembly().GetType(name, throwOnError: false);\n\n            // Act\n            Assert.Throws<InvalidOperationException>(\n                () => WebRazorHostFactory.CreateHostFromConfig(config, \"/Foo/Bar.cshtml\", null),\n                String.Format(RazorWebResources.Could_Not_Locate_FactoryType, \"Foo\"));\n        }\n\n        [Fact]\n        public void CreateHostFromConfigAppliesBaseTypeFromConfigToHost()\n        {\n            // Arrange\n            RazorWebSectionGroup config = new RazorWebSectionGroup()\n            {\n                Host = null,\n                Pages = new RazorPagesSection()\n                {\n                    PageBaseType = \"System.Foo.Bar\"\n                }\n            };\n            WebRazorHostFactory.TypeFactory = name => Assembly.GetExecutingAssembly().GetType(name, throwOnError: false);\n\n            // Act\n            WebPageRazorHost host = WebRazorHostFactory.CreateHostFromConfig(config, \"/Foo/Bar.cshtml\", null);\n\n            // Assert\n            Assert.Equal(\"System.Foo.Bar\", host.DefaultBaseClass);\n        }\n\n        [Fact]\n        public void CreateHostFromConfigIgnoresBaseTypeFromConfigIfPageIsPageStart()\n        {\n            // Arrange\n            RazorWebSectionGroup config = new RazorWebSectionGroup()\n            {\n                Host = null,\n                Pages = new RazorPagesSection()\n                {\n                    PageBaseType = \"System.Foo.Bar\"\n                }\n            };\n            WebRazorHostFactory.TypeFactory = name => Assembly.GetExecutingAssembly().GetType(name, throwOnError: false);\n\n            // Act\n            WebPageRazorHost host = WebRazorHostFactory.CreateHostFromConfig(config, \"/Foo/_pagestart.cshtml\", null);\n\n            // Assert\n            Assert.Equal(typeof(StartPage).FullName, host.DefaultBaseClass);\n        }\n\n        [Fact]\n        public void CreateHostFromConfigIgnoresBaseTypeFromConfigIfPageIsAppStart()\n        {\n            // Arrange\n            RazorWebSectionGroup config = new RazorWebSectionGroup()\n            {\n                Host = null,\n                Pages = new RazorPagesSection()\n                {\n                    PageBaseType = \"System.Foo.Bar\"\n                }\n            };\n            WebRazorHostFactory.TypeFactory = name => Assembly.GetExecutingAssembly().GetType(name, throwOnError: false);\n\n            // Act\n            WebPageRazorHost host = WebRazorHostFactory.CreateHostFromConfig(config, \"/Foo/_appstart.cshtml\", null);\n\n            // Assert\n            Assert.Equal(typeof(ApplicationStartPage).FullName, host.DefaultBaseClass);\n        }\n\n        [Fact]\n        public void CreateHostFromConfigMergesNamespacesFromConfigToHost()\n        {\n            // Arrange\n            RazorWebSectionGroup config = new RazorWebSectionGroup()\n            {\n                Host = null,\n                Pages = new RazorPagesSection()\n                {\n                    Namespaces = new NamespaceCollection()\n                    {\n                        new NamespaceInfo(\"System\"),\n                        new NamespaceInfo(\"Foo\")\n                    }\n                }\n            };\n            WebRazorHostFactory.TypeFactory = name => Assembly.GetExecutingAssembly().GetType(name, throwOnError: false);\n\n            // Act\n            WebPageRazorHost host = WebRazorHostFactory.CreateHostFromConfig(config, \"/Foo/Bar.cshtml\", null);\n\n            // Assert\n            Assert.True(host.NamespaceImports.Contains(\"System\"));\n            Assert.True(host.NamespaceImports.Contains(\"Foo\"));\n        }\n\n        [Fact]\n        public void HostFactoryTypeIsCorrectlyLoadedFromConfig()\n        {\n            // Act\n            RazorWebSectionGroup group = GetRazorGroup();\n            HostSection host = (HostSection)group.Host;\n\n            // Assert\n            Assert.NotNull(host);\n            Assert.Equal(\"System.Web.WebPages.Razor.Test.TestRazorHostFactory, System.Web.WebPages.Razor.Test\", host.FactoryType);\n        }\n\n        [Fact]\n        public void PageBaseTypeIsCorrectlyLoadedFromConfig()\n        {\n            // Act\n            RazorWebSectionGroup group = GetRazorGroup();\n            RazorPagesSection pages = (RazorPagesSection)group.Pages;\n\n            // Assert\n            Assert.NotNull(pages);\n            Assert.Equal(\"System.Web.WebPages.Razor.Test.TestPageBase, System.Web.WebPages.Razor.Test\", pages.PageBaseType);\n        }\n\n        [Fact]\n        public void NamespacesAreCorrectlyLoadedFromConfig()\n        {\n            // Act\n            RazorWebSectionGroup group = GetRazorGroup();\n            RazorPagesSection pages = (RazorPagesSection)group.Pages;\n\n            // Assert\n            Assert.NotNull(pages);\n            NamespaceInfo namespaceInfo = Assert.IsType<NamespaceInfo>(Assert.Single(pages.Namespaces));\n            Assert.Equal(\"System.Text.RegularExpressions\", namespaceInfo.Namespace);\n        }\n\n        [Fact]\n        public void RegisterSpecialFile_ThrowsOnNullFileName()\n        {\n            TestHost host = new TestHost();\n            Assert.ThrowsArgumentNullOrEmptyString(() => host.RegisterSpecialFile(null, typeof(string)), \"fileName\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => host.RegisterSpecialFile(null, \"string\"), \"fileName\");\n        }\n\n        [Fact]\n        public void RegisterSpecialFile_ThrowsOnEmptyFileName()\n        {\n            TestHost host = new TestHost();\n            Assert.ThrowsArgumentNullOrEmptyString(() => host.RegisterSpecialFile(String.Empty, typeof(string)), \"fileName\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => host.RegisterSpecialFile(String.Empty, \"string\"), \"fileName\");\n        }\n\n        [Fact]\n        public void RegisterSpecialFile_ThrowsOnNullBaseType()\n        {\n            TestHost host = new TestHost();\n            Assert.ThrowsArgumentNull(() => host.RegisterSpecialFile(\"file\", (Type)null), \"baseType\");\n        }\n\n        [Fact]\n        public void RegisterSpecialFile_ThrowsOnNullBaseTypeName()\n        {\n            TestHost host = new TestHost();\n            Assert.ThrowsArgumentNullOrEmptyString(() => host.RegisterSpecialFile(\"file\", (string)null), \"baseTypeName\");\n        }\n\n        [Fact]\n        public void RegisterSpecialFile_ThrowsOnEmptyBaseTypeName()\n        {\n            TestHost host = new TestHost();\n            Assert.ThrowsArgumentNullOrEmptyString(() => host.RegisterSpecialFile(\"file\", String.Empty), \"baseTypeName\");\n        }\n\n        private static RazorWebSectionGroup GetRazorGroup()\n        {\n            return (RazorWebSectionGroup)ConfigurationManager.OpenExeConfiguration(null).GetSectionGroup(RazorWebSectionGroup.GroupName);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Razor.Test/app.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n    <configSections>\n        <sectionGroup name=\"system.web.webPages.razor\" type=\"System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\">\n            <section name=\"host\" type=\"System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\" requirePermission=\"false\" />\n            <section name=\"pages\" type=\"System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\" requirePermission=\"false\" />\n        </sectionGroup>\n    </configSections>\n    <system.web.webPages.razor>\n        <host factoryType=\"System.Web.WebPages.Razor.Test.TestRazorHostFactory, System.Web.WebPages.Razor.Test\" />\n        <pages pageBaseType=\"System.Web.WebPages.Razor.Test.TestPageBase, System.Web.WebPages.Razor.Test\">\n            <namespaces>\n                <add namespace=\"System.IO.Packaging\" />\n                <clear />\n                <add namespace=\"System.Security\" />\n                <add namespace=\"System.Text.RegularExpressions\" />\n                <remove namespace=\"System.Security\" />\n            </namespaces>\n        </pages>\n    </system.web.webPages.razor>\n</configuration>"
  },
  {
    "path": "test/System.Web.WebPages.Razor.Test/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Castle.Core\" version=\"5.1.1\" targetFramework=\"net462\" />\n  <package id=\"Moq\" version=\"4.18.4\" targetFramework=\"net462\" />\n  <package id=\"xunit\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.abstractions\" version=\"2.0.3\" targetFramework=\"net462\" />\n  <package id=\"xunit.analyzers\" version=\"1.1.0\" targetFramework=\"net462\" />\n  <package id=\"xunit.assert\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.execution\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.runner.visualstudio\" version=\"2.4.5\" targetFramework=\"net462\" developmentDependency=\"true\" />\n</packages>"
  },
  {
    "path": "test/System.Web.WebPages.Test/App.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n  <system.data>\n    <DbProviderFactories>\n      <remove invariant=\"System.Data.SqlServerCe.4.0\"></remove>\n      <add name=\"Microsoft SQL Server Compact Data Provider\" invariant=\"System.Data.SqlServerCe.4.0\" description=\".NET Framework Data Provider for Microsoft SQL Server Compact\" type=\"System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91\"/>\n    </DbProviderFactories>\n  </system.data>\n  <runtime>\n    <assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\">\n      <dependentAssembly>\n        <!-- Need this because the BinarySerializer uses the TypeForwardedFrom attribute and deserializes to the original assembly (MVC 2.0) for the HttpAntiForgeryException test -->\n        <assemblyIdentity name=\"System.Web.Mvc\" publicKeyToken=\"31bf3856ad364e35\" />\n        <bindingRedirect oldVersion=\"1.0.0.0-5.3.0.0\" newVersion=\"5.3.0.0\" />\n      </dependentAssembly>\n    </assemblyBinding>\n  </runtime>\n</configuration>"
  },
  {
    "path": "test/System.Web.WebPages.Test/ApplicationParts/ApplicationPartRegistryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.WebPages.ApplicationParts;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test.ApplicationModule\n{\n    public class ApplicationPartRegistryTest\n    {\n        [Fact]\n        public void ApplicationModuleGeneratesRootRelativePaths()\n        {\n            // Arrange\n            var path1 = \"foo/bar\";\n            var path2 = \"~/xyz/pqr\";\n            var root1 = \"~/myappmodule\";\n            var root2 = \"~/myappmodule2/\";\n\n            // Act\n            var actualPath11 = ApplicationPartRegistry.GetRootRelativeVirtualPath(root1, path1);\n            var actualPath12 = ApplicationPartRegistry.GetRootRelativeVirtualPath(root1, path2);\n            var actualPath21 = ApplicationPartRegistry.GetRootRelativeVirtualPath(root2, path1);\n            var actualPath22 = ApplicationPartRegistry.GetRootRelativeVirtualPath(root2, path2);\n\n            // Assert\n            Assert.Equal(actualPath11, root1 + \"/\" + path1);\n            Assert.Equal(actualPath12, root1 + path2.TrimStart('~'));\n            Assert.Equal(actualPath21, root2 + path1);\n            Assert.Equal(actualPath22, root2 + path2.TrimStart('~', '/'));\n        }\n\n        [Fact]\n        public void ApplicationPartRegistryLooksUpPartsByName()\n        {\n            // Arrange\n            var part = new ApplicationPart(BuildAssembly(), \"~/mymodule\");\n            var dictionary = new DictionaryBasedVirtualPathFactory();\n            var registry = new ApplicationPartRegistry(dictionary);\n            Func<object> myFunc = () => \"foo\";\n\n            // Act\n            registry.Register(part, myFunc);\n\n            // Assert\n            Assert.Equal(registry[\"my-assembly\"], part);\n            Assert.Equal(registry[\"MY-aSSembly\"], part);\n        }\n\n        [Fact]\n        public void ApplicationPartRegistryLooksUpPartsByAssembly()\n        {\n            // Arrange\n            var assembly = BuildAssembly();\n            var part = new ApplicationPart(assembly, \"~/mymodule\");\n            var dictionary = new DictionaryBasedVirtualPathFactory();\n            var registry = new ApplicationPartRegistry(dictionary);\n            Func<object> myFunc = () => \"foo\";\n\n            // Act\n            registry.Register(part, myFunc);\n\n            // Assert\n            Assert.Equal(registry[assembly], part);\n        }\n\n        [Fact]\n        public void RegisterThrowsIfAssemblyAlreadyRegistered()\n        {\n            // Arrange\n            var part = new ApplicationPart(BuildAssembly(), \"~/mymodule\");\n            var dictionary = new DictionaryBasedVirtualPathFactory();\n            var registry = new ApplicationPartRegistry(dictionary);\n            Func<object> myFunc = () => \"foo\";\n\n            // Act\n            registry.Register(part, myFunc);\n\n            // Assert\n            Assert.Throws<InvalidOperationException>(() => registry.Register(part, myFunc),\n                                                              String.Format(\"The assembly \\\"{0}\\\" is already registered.\", part.Assembly.ToString()));\n        }\n\n        [Fact]\n        public void RegisterThrowsIfPathAlreadyRegistered()\n        {\n            // Arrange\n            var part = new ApplicationPart(BuildAssembly(), \"~/mymodule\");\n            var dictionary = new DictionaryBasedVirtualPathFactory();\n            var registry = new ApplicationPartRegistry(dictionary);\n            Func<object> myFunc = () => \"foo\";\n\n            // Act\n            registry.Register(part, myFunc);\n\n            // Assert\n            var newPart = new ApplicationPart(BuildAssembly(\"different-assembly\"), \"~/mymodule\");\n            Assert.Throws<InvalidOperationException>(() => registry.Register(newPart, myFunc),\n                                                              \"An application module is already registered for virtual path \\\"~/mymodule/\\\".\");\n        }\n\n        [Fact]\n        public void RegisterCreatesRoutesForValidPages()\n        {\n            // Arrange\n            var part = new ApplicationPart(BuildAssembly(), \"~/mymodule\");\n            var dictionary = new DictionaryBasedVirtualPathFactory();\n            var registry = new ApplicationPartRegistry(dictionary);\n            Func<object> myFunc = () => \"foo\";\n\n            // Act\n            registry.Register(part, myFunc);\n\n            // Assert\n            Assert.True(dictionary.Exists(\"~/mymodule/Page1\"));\n            Assert.Equal(\"foo\", dictionary.CreateInstance(\"~/mymodule/Page1\"));\n            Assert.False(dictionary.Exists(\"~/mymodule/Page2\"));\n            Assert.False(dictionary.Exists(\"~/mymodule/Page3\"));\n        }\n\n        private static IResourceAssembly BuildAssembly(string name = \"my-assembly\")\n        {\n            Mock<TestResourceAssembly> assembly = new Mock<TestResourceAssembly>();\n            assembly.SetupGet(c => c.Name).Returns(name);\n            assembly.Setup(c => c.GetHashCode()).Returns(name.GetHashCode());\n            assembly.Setup(c => c.Equals(It.IsAny<TestResourceAssembly>())).Returns((TestResourceAssembly c) => c.Name == name);\n\n            assembly.Setup(c => c.GetTypes()).Returns(new[]\n            {\n                BuildPageType(inherits: true, virtualPath: \"~/Page1\"),\n                BuildPageType(inherits: true, virtualPath: null),\n                BuildPageType(inherits: false, virtualPath: \"~/Page3\"),\n            });\n\n            return assembly.Object;\n        }\n\n        private static Type BuildPageType(bool inherits, string virtualPath)\n        {\n            Mock<Type> type = new Mock<Type>();\n            type.Setup(c => c.IsSubclassOf(typeof(WebPageRenderingBase))).Returns(inherits);\n\n            if (virtualPath != null)\n            {\n                type.Setup(c => c.GetCustomAttributes(typeof(PageVirtualPathAttribute), false))\n                    .Returns(new[] { new PageVirtualPathAttribute(virtualPath) });\n            }\n            return type.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/ApplicationParts/ApplicationPartTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class ApplicationPartTest\n    {\n        [Fact]\n        public void ApplicationPartThrowsIfRootVirtualPathIsNullOrEmpty()\n        {\n            // Arrange\n            var assembly = new Mock<TestResourceAssembly>().Object;\n\n            Assert.ThrowsArgumentNullOrEmptyString(() => new ApplicationPart(assembly, rootVirtualPath: null), \"rootVirtualPath\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => new ApplicationPart(assembly, rootVirtualPath: String.Empty), \"rootVirtualPath\");\n        }\n\n        [Fact]\n        public void ResolveVirtualPathResolvesRegularPathsUsingBaseVirtualPath()\n        {\n            // Arrange\n            var basePath = \"~/base/\";\n            var path = \"somefile\";\n            var appPartRoot = \"~/app/\";\n\n            // Act\n            var virtualPath = ApplicationPart.ResolveVirtualPath(appPartRoot, basePath, path);\n\n            // Assert\n            Assert.Equal(\"~/base/somefile\", virtualPath);\n        }\n\n        [Fact]\n        public void ResolveVirtualPathResolvesAppRelativePathsUsingAppVirtualPath()\n        {\n            // Arrange\n            var basePath = \"~/base\";\n            var path = \"@/somefile\";\n            var appPartRoot = \"~/app/\";\n\n            // Act\n            var virtualPath = ApplicationPart.ResolveVirtualPath(appPartRoot, basePath, path);\n\n            // Assert\n            Assert.Equal(\"~/app/somefile\", virtualPath);\n        }\n\n        [Fact]\n        public void ResolveVirtualPathDoesNotAffectRootRelativePaths()\n        {\n            // Arrange\n            var basePath = \"~/base\";\n            var path = \"~/somefile\";\n            var appPartRoot = \"~/app/\";\n\n            // Act\n            var virtualPath = ApplicationPart.ResolveVirtualPath(appPartRoot, basePath, path);\n\n            // Assert\n            Assert.Equal(\"~/somefile\", virtualPath);\n        }\n\n        [Fact]\n        public void GetResourceNameFromVirtualPathForTopLevelPath()\n        {\n            // Arrange\n            var moduleName = \"my-module\";\n            var path = \"foo.baz\";\n\n            // Act\n            var name = ApplicationPart.GetResourceNameFromVirtualPath(moduleName, path);\n\n            // Assert\n            Assert.Equal(name, moduleName + \".\" + path);\n        }\n\n        [Fact]\n        public void GetResourceNameFromVirtualPathForItemInSubDir()\n        {\n            // Arrange\n            var moduleName = \"my-module\";\n            var path = \"/bar/foo\";\n\n            // Act\n            var name = ApplicationPart.GetResourceNameFromVirtualPath(moduleName, path);\n\n            // Assert\n            Assert.Equal(\"my-module.bar.foo\", name);\n        }\n\n        [Fact]\n        public void GetResourceNameFromVirtualPathForItemWithSpaces()\n        {\n            // Arrange\n            var moduleName = \"my-module\";\n            var path = \"/program files/data files/my file .foo\";\n\n            // Act\n            var name = ApplicationPart.GetResourceNameFromVirtualPath(moduleName, path);\n\n            // Assert\n            Assert.Equal(\"my-module.program_files.data_files.my file .foo\", name);\n        }\n\n        [Fact]\n        public void GetResourceVirtualPathForTopLevelItem()\n        {\n            // Arrange\n            var moduleName = \"my-module\";\n            var moduleRoot = \"~/root-path\";\n            var path = moduleRoot + \"/foo.txt\";\n\n            // Act\n            var virtualPath = ApplicationPart.GetResourceVirtualPath(moduleName, moduleRoot, path);\n\n            // Assert\n            Assert.Equal(\"~/r.ashx/\" + moduleName + \"/\" + \"foo.txt\", virtualPath);\n        }\n\n        [Fact]\n        public void GetResourceVirtualPathForTopLevelItemAndModuleRootWithTrailingSlash()\n        {\n            // Arrange\n            var moduleName = \"my-module\";\n            var moduleRoot = \"~/root-path/\";\n            var path = moduleRoot + \"/foo.txt\";\n\n            // Act\n            var virtualPath = ApplicationPart.GetResourceVirtualPath(moduleName, moduleRoot, path);\n\n            // Assert\n            Assert.Equal(\"~/r.ashx/\" + moduleName + \"/\" + \"foo.txt\", virtualPath);\n        }\n\n        [Fact]\n        public void GetResourceVirtualPathForTopLevelItemAndNestedModuleRootPath()\n        {\n            // Arrange\n            var moduleName = \"my-module\";\n            var moduleRoot = \"~/root-path/sub-path\";\n            var path = moduleRoot + \"/foo.txt\";\n\n            // Act\n            var virtualPath = ApplicationPart.GetResourceVirtualPath(moduleName, moduleRoot, path);\n\n            // Assert\n            Assert.Equal(\"~/r.ashx/\" + moduleName + \"/\" + \"foo.txt\", virtualPath);\n        }\n\n        [Fact]\n        public void GetResourceVirtualPathEncodesModuleName()\n        {\n            // Arrange\n            var moduleName = \"Debugger Package v?&%\";\n            var moduleRoot = \"~/root-path/sub-path\";\n            var path = moduleRoot + \"/foo.txt\";\n\n            // Act\n            var virtualPath = ApplicationPart.GetResourceVirtualPath(moduleName, moduleRoot, path);\n\n            // Assert\n            Assert.Equal(\"~/r.ashx/\" + \"Debugger%20Package%20v?&%\" + \"/\" + \"foo.txt\", virtualPath);\n        }\n\n        [Fact]\n        public void GetResourceVirtualPathForNestedItemPath()\n        {\n            // Arrange\n            var moduleName = \"DebuggerPackage\";\n            var moduleRoot = \"~/root-path/sub-path\";\n            var itemPath = \"some-path/some-more-please/foo.txt\";\n            var path = moduleRoot + \"/\" + itemPath;\n\n            // Act\n            var virtualPath = ApplicationPart.GetResourceVirtualPath(moduleName, moduleRoot, path);\n\n            // Assert\n            Assert.Equal(\"~/r.ashx/\" + moduleName + \"/\" + itemPath, virtualPath);\n        }\n\n        [Fact]\n        public void GetResourceVirtualPathForItemPathWithParameters()\n        {\n            // Arrange\n            var moduleName = \"DebuggerPackage\";\n            var moduleRoot = \"~/root-path/sub-path\";\n            var itemPath = \"some-path/some-more-please/foo.jpg?size=45&height=20\";\n            var path = moduleRoot + \"/\" + itemPath;\n\n            // Act\n            var virtualPath = ApplicationPart.GetResourceVirtualPath(moduleName, moduleRoot, path);\n\n            // Assert\n            Assert.Equal(\"~/r.ashx/\" + moduleName + \"/\" + itemPath, virtualPath);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/ApplicationParts/MimeMappingTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.Internal.Web.Utils;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Test\n{\n    public class MimeMappingTest\n    {\n        [Fact]\n        public void MimeMappingThrowsForNullFileName()\n        {\n            // Arrange\n            string fileName = null;\n\n            // Act and Assert\n            Assert.ThrowsArgumentNull(() => MimeMapping.GetMimeMapping(fileName), \"fileName\");\n        }\n\n        [Fact]\n        public void MimeMappingReturnsGenericTypeForUnknownExtensions()\n        {\n            // Arrange\n            string fileName = \"file.does-not-exist\";\n\n            // Act\n            string mimeType = MimeMapping.GetMimeMapping(fileName);\n\n            // Assert\n            Assert.Equal(\"application/octet-stream\", mimeType);\n        }\n\n        [Fact]\n        public void MimeMappingReturnsGenericTypeForNoExtensions()\n        {\n            // Arrange\n            string fileName = \"file\";\n\n            // Act\n            string mimeType = MimeMapping.GetMimeMapping(fileName);\n\n            // Assert\n            Assert.Equal(\"application/octet-stream\", mimeType);\n        }\n\n        [Fact]\n        public void MimeMappingPerformsCaseInsensitiveSearches()\n        {\n            // Arrange\n            string fileName1 = \"file.doc\";\n            string fileName2 = \"file.dOC\";\n\n            // Act\n            string mimeType1 = MimeMapping.GetMimeMapping(fileName1);\n            string mimeType2 = MimeMapping.GetMimeMapping(fileName2);\n\n            // Assert\n            Assert.Equal(\"application/msword\", mimeType1);\n            Assert.Equal(\"application/msword\", mimeType2);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/ApplicationParts/ResourceHandlerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Text;\nusing System.Web.WebPages.ApplicationParts;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class ResourceHandlerTest\n    {\n        private const string _fileContent = \"contents of jpeg file\";\n\n        [Fact]\n        public void ResourceHandlerWritesContentsOfFileToStream()\n        {\n            // Arrange\n            var applicationPart = new ApplicationPart(BuildAssembly(), \"~/my-app-assembly\");\n            MemoryStream stream = new MemoryStream();\n            var response = new Mock<HttpResponseBase>();\n            response.SetupGet(c => c.OutputStream).Returns(stream);\n            response.SetupSet(c => c.ContentType = \"image/jpeg\").Verifiable();\n            var resourceHandler = new ResourceHandler(applicationPart, \"bar.foo.jpg\");\n\n            // Act\n            resourceHandler.ProcessRequest(response.Object);\n\n            // Assert\n            response.Verify();\n            Assert.Equal(_fileContent, Encoding.Default.GetString(stream.ToArray()));\n        }\n\n        [Fact]\n        public void ResourceHandlerThrows404IfResourceNotFound()\n        {\n            // Arrange\n            var applicationPart = new ApplicationPart(BuildAssembly(), \"~/my-app-assembly\");\n            MemoryStream stream = new MemoryStream();\n            var response = new Mock<HttpResponseBase>();\n            response.SetupGet(c => c.OutputStream).Returns(stream);\n            response.SetupSet(c => c.ContentType = \"image/jpeg\").Verifiable();\n            var resourceHandler = new ResourceHandler(applicationPart, \"does-not-exist\");\n\n            // Act and Assert\n            Assert.Throws<HttpException>(() => resourceHandler.ProcessRequest(response.Object),\n                                                  \"The resource file \\\"does-not-exist\\\" could not be found.\");\n        }\n\n        private static IResourceAssembly BuildAssembly(string name = \"my-assembly\")\n        {\n            Mock<TestResourceAssembly> assembly = new Mock<TestResourceAssembly>();\n            assembly.SetupGet(c => c.Name).Returns(\"my-assembly\");\n\n            byte[] content = Encoding.Default.GetBytes(_fileContent);\n            assembly.Setup(c => c.GetManifestResourceStream(\"my-assembly.bar.foo.jpg\")).Returns(new MemoryStream(content));\n\n            assembly.Setup(c => c.GetManifestResourceNames()).Returns(new[] { \"my-assembly.bar.foo.jpg\" });\n\n            return assembly.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/ApplicationParts/TestResourceAssembly.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Web.WebPages.ApplicationParts;\n\nnamespace System.Web.WebPages.Test\n{\n    public abstract class TestResourceAssembly : IResourceAssembly\n    {\n        public abstract string Name { get; }\n\n        public abstract Stream GetManifestResourceStream(string name);\n\n        public abstract IEnumerable<string> GetManifestResourceNames();\n\n        public abstract IEnumerable<Type> GetTypes();\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Extensions/HttpContextExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web;\nusing System.Web.WebPages;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace Microsoft.WebPages.Test.Helpers\n{\n    public class HttpContextExtensionsTest\n    {\n        class RedirectData\n        {\n            public string RequestUrl { get; set; }\n            public string RedirectUrl { get; set; }\n        }\n\n        private static HttpContextBase GetContextForRedirectLocal(RedirectData data)\n        {\n            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>();\n            contextMock.Setup(context => context.Request.Url).Returns(new Uri(data.RequestUrl));\n            contextMock.Setup(context => context.Response.Redirect(It.IsAny<string>())).Callback((string url) => data.RedirectUrl = url);\n            return contextMock.Object;\n        }\n\n        [Fact]\n        public void RedirectLocalWithNullGoesToRootTest()\n        {\n            RedirectData data = new RedirectData() { RequestUrl = \"http://foo\" };\n            var context = GetContextForRedirectLocal(data);\n            context.RedirectLocal(\"\");\n            Assert.Equal(\"~/\", data.RedirectUrl);\n        }\n\n        [Fact]\n        public void RedirectLocalWithEmptyStringGoesToRootTest()\n        {\n            RedirectData data = new RedirectData() { RequestUrl = \"http://foo\" };\n            var context = GetContextForRedirectLocal(data);\n            context.RedirectLocal(\"\");\n            Assert.Equal(\"~/\", data.RedirectUrl);\n        }\n\n        [Fact]\n        public void RedirectLocalWithNonLocalGoesToRootTest()\n        {\n            RedirectData data = new RedirectData() { RequestUrl = \"http://foo\" };\n            var context = GetContextForRedirectLocal(data);\n            context.RedirectLocal(\"\");\n            Assert.Equal(\"~/\", data.RedirectUrl);\n        }\n\n        [Fact]\n        public void RedirectLocalWithDifferentHostGoesToRootTest()\n        {\n            RedirectData data = new RedirectData() { RequestUrl = \"http://foo\" };\n            var context = GetContextForRedirectLocal(data);\n            context.RedirectLocal(\"http://bar\");\n            Assert.Equal(\"~/\", data.RedirectUrl);\n        }\n\n        [Fact]\n        public void RedirectLocalOnSameHostTest()\n        {\n            RedirectData data = new RedirectData() { RequestUrl = \"http://foo\" };\n            var context = GetContextForRedirectLocal(data);\n            context.RedirectLocal(\"http://foo/bar/baz\");\n            Assert.Equal(\"~/\", data.RedirectUrl);\n            context.RedirectLocal(\"http://foo/bar/baz/woot.htm\");\n            Assert.Equal(\"~/\", data.RedirectUrl);\n        }\n\n        [Fact]\n        public void RedirectLocalRelativeTest()\n        {\n            RedirectData data = new RedirectData() { RequestUrl = \"http://foo\" };\n            var context = GetContextForRedirectLocal(data);\n            context.RedirectLocal(\"/bar\");\n            Assert.Equal(\"/bar\", data.RedirectUrl);\n            context.RedirectLocal(\"/bar/hey.you\");\n            Assert.Equal(\"/bar/hey.you\", data.RedirectUrl);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Extensions/HttpRequestExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Web;\nusing System.Web.WebPages;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace Microsoft.WebPages.Test.Helpers\n{\n    public class HttpRequestExtensionsTest\n    {\n        private static HttpRequestBase GetRequestForIsUrlLocalToHost(string url)\n        {\n            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>();\n            contextMock.Setup(context => context.Request.Url).Returns(new Uri(url));\n            return contextMock.Object.Request;\n        }\n\n        [Fact]\n        public void IsUrlLocalToHost_ReturnsFalseOnEmpty()\n        {\n            var request = GetRequestForIsUrlLocalToHost(\"http://www.mysite.com/\");\n            Assert.False(request.IsUrlLocalToHost(null));\n            Assert.False(request.IsUrlLocalToHost(String.Empty));\n        }\n\n        [Fact]\n        public void IsUrlLocalToHost_AcceptsRootedUrls()\n        {\n            var helper = GetRequestForIsUrlLocalToHost(\"http://www.mysite.com/\");\n            Assert.True(helper.IsUrlLocalToHost(\"/foo.html\"));\n            Assert.True(helper.IsUrlLocalToHost(\"/www.hackerz.com\"));\n            Assert.True(helper.IsUrlLocalToHost(\"/\"));\n        }\n\n        [Fact]\n        public void IsUrlLocalToHost_AcceptsApplicationRelativeUrls()\n        {\n            var helper = GetRequestForIsUrlLocalToHost(\"http://www.mysite.com/\");\n            Assert.True(helper.IsUrlLocalToHost(\"~/\"));\n            Assert.True(helper.IsUrlLocalToHost(\"~/foobar.html\"));\n        }\n\n        [Fact]\n        public void IsUrlLocalToHost_RejectsRelativeUrls()\n        {\n            var helper = GetRequestForIsUrlLocalToHost(\"http://www.mysite.com/\");\n            Assert.False(helper.IsUrlLocalToHost(\"foobar.html\"));\n            Assert.False(helper.IsUrlLocalToHost(\"../foobar.html\"));\n            Assert.False(helper.IsUrlLocalToHost(\"fold/foobar.html\"));\n        }\n\n        [Fact]\n        public void IsUrlLocalToHost_RejectValidButUnsafeRelativeUrls()\n        {\n            var helper = GetRequestForIsUrlLocalToHost(\"http://www.mysite.com/\");\n            Assert.False(helper.IsUrlLocalToHost(\"http:/foobar.html\"));\n            Assert.False(helper.IsUrlLocalToHost(\"hTtP:foobar.html\"));\n            Assert.False(helper.IsUrlLocalToHost(\"http:/www.hackerz.com\"));\n            Assert.False(helper.IsUrlLocalToHost(\"HtTpS:/www.hackerz.com\"));\n        }\n\n        [Fact]\n        public void IsUrlLocalToHost_RejectsUrlsOnTheSameHost()\n        {\n            var helper = GetRequestForIsUrlLocalToHost(\"http://www.mysite.com/\");\n            Assert.False(helper.IsUrlLocalToHost(\"http://www.mysite.com/appDir/foobar.html\"));\n            Assert.False(helper.IsUrlLocalToHost(\"http://WWW.MYSITE.COM\"));\n        }\n\n        [Fact]\n        public void IsUrlLocalToHost_RejectsUrlsOnLocalHost()\n        {\n            var helper = GetRequestForIsUrlLocalToHost(\"http://www.mysite.com/\");\n            Assert.False(helper.IsUrlLocalToHost(\"http://localhost/foobar.html\"));\n            Assert.False(helper.IsUrlLocalToHost(\"http://127.0.0.1/foobar.html\"));\n        }\n\n        [Fact]\n        public void IsUrlLocalToHost_RejectsUrlsOnTheSameHostButDifferentScheme()\n        {\n            var helper = GetRequestForIsUrlLocalToHost(\"http://www.mysite.com/\");\n            Assert.False(helper.IsUrlLocalToHost(\"https://www.mysite.com/\"));\n        }\n\n        [Fact]\n        public void IsUrlLocalToHost_RejectsUrlsOnDifferentHost()\n        {\n            var helper = GetRequestForIsUrlLocalToHost(\"http://www.mysite.com/\");\n            Assert.False(helper.IsUrlLocalToHost(\"http://www.hackerz.com\"));\n            Assert.False(helper.IsUrlLocalToHost(\"https://www.hackerz.com\"));\n            Assert.False(helper.IsUrlLocalToHost(\"hTtP://www.hackerz.com\"));\n            Assert.False(helper.IsUrlLocalToHost(\"HtTpS://www.hackerz.com\"));\n        }\n\n        [Fact]\n        public void IsUrlLocalToHost_RejectsUrlsWithTooManySchemeSeparatorCharacters()\n        {\n            var helper = GetRequestForIsUrlLocalToHost(\"http://www.mysite.com/\");\n            Assert.False(helper.IsUrlLocalToHost(\"http://///www.hackerz.com/foobar.html\"));\n            Assert.False(helper.IsUrlLocalToHost(\"https://///www.hackerz.com/foobar.html\"));\n            Assert.False(helper.IsUrlLocalToHost(\"HtTpS://///www.hackerz.com/foobar.html\"));\n\n            Assert.False(helper.IsUrlLocalToHost(\"http:///www.hackerz.com/foobar.html\"));\n            Assert.False(helper.IsUrlLocalToHost(\"http:////www.hackerz.com/foobar.html\"));\n            Assert.False(helper.IsUrlLocalToHost(\"http://///www.hackerz.com/foobar.html\"));\n        }\n\n        [Fact]\n        public void IsUrlLocalToHost_RejectsUrlsWithMissingSchemeName()\n        {\n            var helper = GetRequestForIsUrlLocalToHost(\"http://www.mysite.com/\");\n            Assert.False(helper.IsUrlLocalToHost(\"//www.hackerz.com\"));\n            Assert.False(helper.IsUrlLocalToHost(\"//www.hackerz.com?\"));\n            Assert.False(helper.IsUrlLocalToHost(\"//www.hackerz.com:80\"));\n            Assert.False(helper.IsUrlLocalToHost(\"//www.hackerz.com/foobar.html\"));\n            Assert.False(helper.IsUrlLocalToHost(\"///www.hackerz.com\"));\n            Assert.False(helper.IsUrlLocalToHost(\"//////www.hackerz.com\"));\n        }\n\n        [Fact]\n        public void IsUrlLocalToHost_RejectsInvalidUrls()\n        {\n            var helper = GetRequestForIsUrlLocalToHost(\"http://www.mysite.com/\");\n            Assert.False(helper.IsUrlLocalToHost(@\"http:\\\\www.hackerz.com\"));\n            Assert.False(helper.IsUrlLocalToHost(@\"http:\\\\www.hackerz.com\\\"));\n            Assert.False(helper.IsUrlLocalToHost(@\"/\\\"));\n            Assert.False(helper.IsUrlLocalToHost(@\"/\\foo\"));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Extensions/HttpResponseExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.IO;\nusing System.Net;\nusing System.Text;\nusing System.Web;\nusing System.Web.WebPages;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace Microsoft.WebPages.Test.Helpers\n{\n    public class HttpResponseExtensionsTest\n    {\n        HttpResponseBase _response;\n        string _redirectUrl;\n        StringBuilder _output;\n        Stream _outputStream;\n\n        public HttpResponseExtensionsTest()\n        {\n            _output = new StringBuilder();\n            _outputStream = new MemoryStream();\n            Mock<HttpResponseBase> mockResponse = new Mock<HttpResponseBase>();\n            mockResponse.SetupProperty(response => response.StatusCode);\n            mockResponse.SetupProperty(response => response.ContentType);\n            mockResponse.Setup(response => response.Redirect(It.IsAny<string>())).Callback((string url) => _redirectUrl = url);\n            mockResponse.Setup(response => response.Write(It.IsAny<string>())).Callback((string str) => _output.Append(str));\n            mockResponse.Setup(response => response.OutputStream).Returns(_outputStream);\n            mockResponse.Setup(response => response.OutputStream).Returns(_outputStream);\n            mockResponse.Setup(response => response.Output).Returns(new StringWriter(_output));\n            _response = mockResponse.Object;\n        }\n\n        [Fact]\n        public void SetStatusWithIntTest()\n        {\n            int status = 200;\n            _response.SetStatus(status);\n            Assert.Equal(status, _response.StatusCode);\n        }\n\n        [Fact]\n        public void SetStatusWithHttpStatusCodeTest()\n        {\n            HttpStatusCode status = HttpStatusCode.Forbidden;\n            _response.SetStatus(status);\n            Assert.Equal((int)status, _response.StatusCode);\n        }\n\n        [Fact]\n        public void WriteBinaryTest()\n        {\n            string foo = \"I am a string, please don't mangle me!\";\n            _response.WriteBinary(ASCIIEncoding.ASCII.GetBytes(foo));\n            _outputStream.Flush();\n            _outputStream.Position = 0;\n            StreamReader reader = new StreamReader(_outputStream);\n            Assert.Equal(foo, reader.ReadToEnd());\n        }\n\n        [Fact]\n        public void WriteBinaryWithMimeTypeTest()\n        {\n            string foo = \"I am a string, please don't mangle me!\";\n            string mimeType = \"mime/foo\";\n            _response.WriteBinary(ASCIIEncoding.ASCII.GetBytes(foo), mimeType);\n            _outputStream.Flush();\n            _outputStream.Position = 0;\n            StreamReader reader = new StreamReader(_outputStream);\n            Assert.Equal(foo, reader.ReadToEnd());\n            Assert.Equal(mimeType, _response.ContentType);\n        }\n\n        [Fact]\n        public void OutputCacheSetsExpirationTimeBasedOnCurrentContext()\n        {\n            // Arrange\n            var timestamp = new DateTime(2011, 1, 1, 0, 0, 0);\n            var context = new Mock<HttpContextBase>();\n            context.SetupGet(c => c.Timestamp).Returns(timestamp);\n            var response = new Mock<HttpResponseBase>().Object;\n\n            var cache = new Mock<HttpCachePolicyBase>();\n            cache.Setup(c => c.SetCacheability(It.Is<HttpCacheability>(p => p == HttpCacheability.Public))).Verifiable();\n            cache.Setup(c => c.SetExpires(It.Is<DateTime>(p => p == timestamp.AddSeconds(20)))).Verifiable();\n            cache.Setup(c => c.SetMaxAge(It.Is<TimeSpan>(p => p == TimeSpan.FromSeconds(20)))).Verifiable();\n            cache.Setup(c => c.SetValidUntilExpires(It.Is<bool>(p => p == true))).Verifiable();\n            cache.Setup(c => c.SetLastModified(It.Is<DateTime>(p => p == timestamp))).Verifiable();\n            cache.Setup(c => c.SetSlidingExpiration(It.Is<bool>(p => p == false))).Verifiable();\n\n            // Act\n            ResponseExtensions.OutputCache(context.Object, cache.Object, 20, false, null, null, null, HttpCacheability.Public);\n\n            // Assert\n            cache.VerifyAll();\n        }\n\n        [Fact]\n        public void OutputCacheSetsVaryByValues()\n        {\n            // Arrange\n            var timestamp = new DateTime(2011, 1, 1, 0, 0, 0);\n            var context = new Mock<HttpContextBase>();\n            context.SetupGet(c => c.Timestamp).Returns(timestamp);\n            var response = new Mock<HttpResponseBase>().Object;\n\n            var varyByParams = new HttpCacheVaryByParams();\n            var varyByHeader = new HttpCacheVaryByHeaders();\n            var varyByContentEncoding = new HttpCacheVaryByContentEncodings();\n\n            var cache = new Mock<HttpCachePolicyBase>();\n            cache.SetupGet(c => c.VaryByParams).Returns(varyByParams);\n            cache.SetupGet(c => c.VaryByHeaders).Returns(varyByHeader);\n            cache.SetupGet(c => c.VaryByContentEncodings).Returns(varyByContentEncoding);\n\n            // Act\n            ResponseExtensions.OutputCache(context.Object, cache.Object, 20, false, new[] { \"foo\" }, new[] { \"bar\", \"bar2\" },\n                                           new[] { \"baz\", \"baz2\" }, HttpCacheability.Public);\n\n            // Assert\n            Assert.True(varyByParams[\"foo\"]);\n            Assert.True(varyByHeader[\"bar\"]);\n            Assert.True(varyByHeader[\"bar2\"]);\n            Assert.True(varyByContentEncoding[\"baz\"]);\n            Assert.True(varyByContentEncoding[\"baz2\"]);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Extensions/StringExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Web.TestUtil;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Test\n{\n    public class StringExtensionsTest\n    {\n        [Fact]\n        public void IsIntTests()\n        {\n            Assert.False(\"1.3\".IsInt());\n            Assert.False(\".13\".IsInt());\n            Assert.False(\"0.0\".IsInt());\n            Assert.False(\"12345678900123456\".IsInt());\n            Assert.False(\"gooblygook\".IsInt());\n            Assert.True(\"0\".IsInt());\n            Assert.True(\"123456\".IsInt());\n            Assert.True(Int32.MaxValue.ToString().IsInt());\n            Assert.True(Int32.MinValue.ToString().IsInt());\n            Assert.False(((string)null).IsInt());\n        }\n\n        [Fact]\n        public void AsIntBasicTests()\n        {\n            Assert.Equal(-123, \"-123\".AsInt());\n            Assert.Equal(12345, \"12345\".AsInt());\n            Assert.Equal(0, \"0\".AsInt());\n        }\n\n        [Fact]\n        public void AsIntDefaultTests()\n        {\n            // Illegal values default to 0\n            Assert.Equal(0, \"-100000000000000000000000\".AsInt());\n\n            // Illegal values default to 0\n            Assert.Equal(0, \"adlfkj\".AsInt());\n\n            Assert.Equal(-1, \"adlfkj\".AsInt(-1));\n            Assert.Equal(-1, \"-100000000000000000000000\".AsInt(-1));\n        }\n\n        [Fact]\n        public void IsDecimalTests()\n        {\n            Assert.True(1.3m.ToString(\"0.0\").IsDecimal());\n            Assert.True(0.13m.ToString(\".00\").IsDecimal());\n            Assert.True(0m.ToString(\"0.0\").IsDecimal());\n            Assert.True(\"12345678900123456\".IsDecimal());\n            Assert.True(\"0\".IsDecimal());\n            Assert.True(\"123456\".IsDecimal());\n            Assert.True(decimal.MaxValue.ToString().IsDecimal());\n            Assert.True(decimal.MinValue.ToString().IsDecimal());\n            Assert.False(\"gooblygook\".IsDecimal());\n            Assert.False(\"..0\".IsDecimal());\n            Assert.False(((string)null).IsDecimal());\n        }\n\n        [Fact]\n        public void AsDecimalBasicTests()\n        {\n            Assert.Equal(-123m, -123m.ToString().AsDecimal());\n            Assert.Equal(9.99m, 9.99m.ToString().AsDecimal());\n            Assert.Equal(0m, \"0\".AsDecimal());\n            Assert.Equal(-1.1111m, -1.1111m.ToString().AsDecimal());\n        }\n\n        [Fact]\n        public void AsDecimalDefaultTests()\n        {\n            // Illegal values default to 0\n            Assert.Equal(0m, \"abc\".AsDecimal());\n\n            Assert.Equal(-1.11m, \"adlfkj\".AsDecimal(-1.11m));\n        }\n\n        [Fact]\n        public void AsDecimalUsesCurrentCulture()\n        {\n            decimal value = 12345.00M;\n            using (new CultureReplacer(\"ar-DZ\"))\n            {\n                Assert.Equal(\"12345.00\", value.ToString(CultureInfo.CurrentCulture));\n                Assert.Equal(\"12345.00\", value.ToString());\n            }\n\n            using (new CultureReplacer(\"bg-BG\"))\n            {\n                Assert.Equal(\"12345,00\", value.ToString(CultureInfo.CurrentCulture));\n                Assert.Equal(\"12345,00\", value.ToString());\n            }\n        }\n\n        [Fact]\n        public void IsAndAsDecimalsUsesCurrentCulture()\n        {\n            // Pretty identical to the earlier test case. This was a post on the forums, making sure it works.\n            using (new CultureReplacer(culture: \"lt-LT\"))\n            {\n                Assert.False(\"1.2\".IsDecimal());\n                Assert.True(\"1,2\".IsDecimal());\n\n                Assert.Equal(1.2M, \"1,2\".AsDecimal());\n                Assert.Equal(0, \"1.2\".AsDecimal());\n            }\n        }\n\n        [Fact]\n        public void IsFloatTests()\n        {\n            Assert.True(1.3f.ToString(\"0.0\").IsFloat());\n            Assert.True(0.13f.ToString(\".00\").IsFloat());\n            Assert.True(0f.ToString(\"0.0\").IsFloat());\n            Assert.True(\"12345678900123456\".IsFloat());\n            Assert.True(\"0\".IsFloat());\n            Assert.True(\"123456\".IsFloat());\n            Assert.True(float.MaxValue.ToString().IsFloat());\n            Assert.True(float.MinValue.ToString().IsFloat());\n            Assert.True(float.NegativeInfinity.ToString().IsFloat());\n            Assert.True(float.PositiveInfinity.ToString().IsFloat());\n            Assert.False(\"gooblygook\".IsFloat());\n            Assert.False(((string)null).IsFloat());\n        }\n\n        [Fact]\n        public void AsFloatBasicTests()\n        {\n            Assert.Equal(-123f, -123f.ToString().AsFloat());\n            Assert.Equal(9.99f, 9.99f.ToString().AsFloat());\n            Assert.Equal(0f, \"0\".AsFloat());\n            Assert.Equal(-1.1111f, -1.1111f.ToString().AsFloat());\n        }\n\n        [Fact]\n        public void AsFloatDefaultTests()\n        {\n            // Illegal values default to 0\n            Assert.Equal(0f, \"abc\".AsFloat());\n\n            Assert.Equal(-1.11f, \"adlfkj\".AsFloat(-1.11f));\n        }\n\n        [Fact]\n        public void IsDateTimeTests()\n        {\n            using (new CultureReplacer())\n            {\n                Assert.True(\"Sat, 01 Nov 2008 19:35:00 GMT\".IsDateTime());\n                Assert.True(\"1/5/1979\".IsDateTime());\n                Assert.False(\"0\".IsDateTime());\n                Assert.True(DateTime.MaxValue.ToString().IsDateTime());\n                Assert.True(DateTime.MinValue.ToString().IsDateTime());\n                Assert.True(new DateTime(2010, 12, 21).ToUniversalTime().ToString().IsDateTime());\n                Assert.False(\"gooblygook\".IsDateTime());\n                Assert.False(((string)null).IsDateTime());\n            }\n        }\n\n        /// <remarks>Tests for bug 153439</remarks>\n        [Fact]\n        public void IsDateTimeUsesLocalCulture()\n        {\n            using (new CultureReplacer(culture: \"en-gb\"))\n            {\n                Assert.True(new DateTime(2010, 12, 21).ToString().IsDateTime());\n                Assert.True(new DateTime(2010, 12, 11).ToString().IsDateTime());\n                Assert.True(\"2010/01/01\".IsDateTime());\n                Assert.True(\"12/01/2010\".IsDateTime());\n                Assert.True(\"12/12/2010\".IsDateTime());\n                Assert.True(\"13/12/2010\".IsDateTime());\n                Assert.True(\"2010-12-01\".IsDateTime());\n                Assert.True(\"2010-12-13\".IsDateTime());\n\n                Assert.False(\"12/13/2010\".IsDateTime());\n                Assert.False(\"13/13/2010\".IsDateTime());\n                Assert.False(\"2010-13-12\".IsDateTime());\n            }\n        }\n\n        [Fact]\n        public void AsDateTimeBasicTests()\n        {\n            using (new CultureReplacer(\"en-US\"))\n            {\n                Assert.Equal(DateTime.Parse(\"1/14/1979\"), \"1/14/1979\".AsDateTime());\n                Assert.Equal(DateTime.Parse(\"Sat, 01 Nov 2008 19:35:00 GMT\"), \"Sat, 01 Nov 2008 19:35:00 GMT\".AsDateTime());\n            }\n        }\n\n        [Theory]\n        [InlineData(new object[] { \"en-us\" })]\n        [InlineData(new object[] { \"en-gb\" })]\n        [InlineData(new object[] { \"ug\" })]\n        [InlineData(new object[] { \"lt-LT\" })]\n        public void AsDateTimeDefaultTests(string culture)\n        {\n            using (new CultureReplacer(culture))\n            {\n                // Illegal values default to MinTime\n                Assert.Equal(DateTime.MinValue, \"1\".AsDateTime());\n\n                DateTime defaultV = new DateTime(1979, 01, 05);\n                Assert.Equal(defaultV, \"adlfkj\".AsDateTime(defaultV));\n                Assert.Equal(defaultV, \"Jn 69\".AsDateTime(defaultV));\n            }\n        }\n\n        [Theory]\n        [InlineData(new object[] { \"en-us\" })]\n        [InlineData(new object[] { \"en-gb\" })]\n        [InlineData(new object[] { \"lt-LT\" })]\n        public void IsDateTimeDefaultTests(string culture)\n        {\n            using (new CultureReplacer(culture))\n            {\n                var dateTime = new DateTime(2011, 10, 25, 10, 10, 00);\n                Assert.True(dateTime.ToShortDateString().IsDateTime());\n                Assert.True(dateTime.ToString().IsDateTime());\n                Assert.True(dateTime.ToLongDateString().IsDateTime());\n            }\n        }\n\n        [Fact]\n        public void IsBoolTests()\n        {\n            Assert.True(\"TRUE\".IsBool());\n            Assert.True(\"TRUE   \".IsBool());\n            Assert.True(\"false\".IsBool());\n            Assert.False(\"falsey\".IsBool());\n            Assert.False(\"gooblygook\".IsBool());\n            Assert.False(\"\".IsBool());\n            Assert.False(((string)null).IsBool());\n        }\n\n        [Fact]\n        public void AsBoolTests()\n        {\n            Assert.True(\"TRuE\".AsBool());\n            Assert.False(\"False\".AsBool());\n            Assert.False(\"Die\".AsBool(false));\n            Assert.True(\"true!\".AsBool(true));\n            Assert.False(\"\".AsBool());\n            Assert.False(((string)null).AsBool());\n            Assert.True(\"\".AsBool(true));\n            Assert.True(((string)null).AsBool(true));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Extensions/StringWriterExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class StringWriterExtensionsTest\n    {\n        [Fact]\n        public void CopiesResult()\n        {\n            // Note that a preable is not expected on the generated stream.\n            string text = \"Hello world\";\n            Byte[] textInBytes = Encoding.UTF8.GetBytes(text);\n            string outputText;\n\n            Byte[] buffer = new Byte[1024];\n\n            using (MemoryStream stream = new MemoryStream(buffer))\n            using (StringWriter writer = new StringWriter())\n            using (StreamWriter outputWriter = new StreamWriter(stream))\n            {\n                writer.Write(text);\n                writer.CopyTo(outputWriter);\n\n                outputText = writer.ToString();\n            }\n\n            Assert.Equal(text, outputText, StringComparer.Ordinal);\n\n            for (int i = 0; i < textInBytes.Length; i++)\n            {\n                Assert.Equal(textInBytes[i], buffer[i]);\n            }\n        }\n\n        [Theory]\n        [InlineData(1)]\n        [InlineData(1023)]\n        [InlineData(1024)]\n        [InlineData(1025)]\n        [InlineData(20000)]\n        [InlineData(100000)]\n        public void OnlyUsesBufferUpToSize(int count)\n        {\n            string text = new string('a', count);\n            Byte[] textInBytes = Encoding.UTF8.GetBytes(text);\n\n            Mock<StreamWriter> mock;\n\n            Byte[] buffer = new Byte[textInBytes.Length + 100];\n\n            using (MemoryStream stream = new MemoryStream(buffer))\n            {\n                StringWriter writer = new StringWriter();\n\n                mock = new Mock<StreamWriter>(MockBehavior.Strict, stream) { CallBase = true };\n                mock.Setup(sw => sw.Write(It.IsAny<char[]>(),\n                                          It.IsAny<int>(),\n                                          It.Is<int>(c => c == StringWriterExtensions.BufferSize ||\n                                                          c == textInBytes.Length % StringWriterExtensions.BufferSize)))\n                    .Verifiable();\n\n                StreamWriter outputWriter = mock.Object;\n                writer.Write(text);\n                writer.CopyTo(outputWriter);\n\n                mock.Verify();\n            }\n        }\n\n        [Theory]\n        [InlineData(1)]\n        [InlineData(1023/7)]\n        [InlineData(20000/7)]\n        [InlineData(100000/7)]\n        public void ProperlyCopiesLargeSetsOfText(int count)\n        {\n            // The char א turns into a two byte sequence so we end up with a\n            // 7 byte sequence that is not a divider or 1024.\n            string text = string.Join(string.Empty, Enumerable.Repeat(\"abcdeא\", count));\n\n            Byte[] textInBytes = Encoding.UTF8.GetBytes(text);\n            string outputText;\n\n            Byte[] buffer = new Byte[textInBytes.Length + 100];\n\n            using (MemoryStream stream = new MemoryStream(buffer))\n            using (StringWriter writer = new StringWriter())\n            {\n                using (StreamWriter outputWriter = new StreamWriter(stream))\n                {\n                    writer.Write(text);\n                    writer.CopyTo(outputWriter);\n\n                    outputText = writer.ToString();\n                }\n            }\n\n            Assert.Equal(text, outputText, StringComparer.Ordinal);\n\n            for (int i = 0; i < textInBytes.Length; i++)\n            {\n                Assert.Equal(textInBytes[i], buffer[i]);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Helpers/AntiForgeryConfigTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Helpers.Test\n{\n    public class AntiForgeryConfigTest\n    {\n        [Theory]\n        [InlineData(null, \"__RequestVerificationToken\")]\n        [InlineData(\"\", \"__RequestVerificationToken\")]\n        [InlineData(\"/\", \"__RequestVerificationToken\")]\n        [InlineData(\"/path\", \"__RequestVerificationToken_L3BhdGg1\")]\n        public void GetAntiForgeryCookieName(string appPath, string expectedCookieName)\n        {\n            // Act\n            string retVal = AntiForgeryConfig.GetAntiForgeryCookieName(appPath);\n\n            // Assert\n            Assert.Equal(expectedCookieName, retVal);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Helpers/AntiForgeryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Helpers.Test\n{\n    public class AntiForgeryTest\n    {\n        [Fact]\n        public void GetHtml_ThrowsWhenNotCalledInWebContext()\n        {\n            Assert.Throws<ArgumentException>(() => AntiForgery.GetHtml(),\n                                                    \"An HttpContext is required to perform this operation. Check that this operation is being performed during a web request.\");\n        }\n\n        [Fact]\n        public void GetTokens_ThrowsWhenNotCalledInWebContext()\n        {\n            Assert.Throws<ArgumentException>(() => { string dummy1, dummy2; AntiForgery.GetTokens(\"dummy\", out dummy1, out dummy2); },\n                                                    \"An HttpContext is required to perform this operation. Check that this operation is being performed during a web request.\");\n        }\n\n        [Fact]\n        public void Validate_ThrowsWhenNotCalledInWebContext()\n        {\n            Assert.Throws<ArgumentException>(() => AntiForgery.Validate(),\n                                                    \"An HttpContext is required to perform this operation. Check that this operation is being performed during a web request.\");\n\n            Assert.Throws<ArgumentException>(() => AntiForgery.Validate(\"cookie-token\", \"form-token\"),\n                                                    \"An HttpContext is required to perform this operation. Check that this operation is being performed during a web request.\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Helpers/AntiXsrf/AntiForgeryTokenSerializerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Text;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Helpers.AntiXsrf.Test\n{\n    public class AntiForgeryTokenSerializerTest\n    {\n        private static readonly AntiForgeryTokenSerializer _testSerializer = new AntiForgeryTokenSerializer(cryptoSystem: CreateIdentityTransformCryptoSystem());\n\n        private static readonly BinaryBlob _claimUid = new BinaryBlob(256, new byte[] { 0x6F, 0x16, 0x48, 0xE9, 0x72, 0x49, 0xAA, 0x58, 0x75, 0x40, 0x36, 0xA6, 0x7E, 0x24, 0x8C, 0xF0, 0x44, 0xF0, 0x7E, 0xCF, 0xB0, 0xED, 0x38, 0x75, 0x56, 0xCE, 0x02, 0x9A, 0x4F, 0x9A, 0x40, 0xE0 });\n        private static readonly BinaryBlob _securityToken = new BinaryBlob(128, new byte[] { 0x70, 0x5E, 0xED, 0xCC, 0x7D, 0x42, 0xF1, 0xD6, 0xB3, 0xB9, 0x8A, 0x59, 0x36, 0x25, 0xBB, 0x4C });\n\n        [Theory]\n        [InlineData(\n            \"01\" // Version\n            + \"705EEDCC7D42F1D6B3B9\" // SecurityToken\n            // (WRONG!) Stream ends too early\n            )]\n        [InlineData(\n            \"01\" // Version\n            + \"705EEDCC7D42F1D6B3B98A593625BB4C\" // SecurityToken\n            + \"01\" // IsSessionToken\n            + \"00\" // (WRONG!) Too much data in stream\n            )]\n        [InlineData(\n            \"02\" // (WRONG! - must be 0x01) Version\n            + \"705EEDCC7D42F1D6B3B98A593625BB4C\" // SecurityToken\n            + \"01\" // IsSessionToken\n            )]\n        [InlineData(\n            \"01\" // Version\n            + \"705EEDCC7D42F1D6B3B98A593625BB4C\" // SecurityToken\n            + \"00\" // IsSessionToken\n            + \"00\" // IsClaimsBased\n            + \"05\" // Username length header\n            + \"0000\" // (WRONG!) Too little data in stream\n            )]\n        public void Deserialize_BadToken(string serializedToken)\n        {\n            // Act & assert\n            var ex = Assert.Throws<HttpAntiForgeryException>(() => _testSerializer.Deserialize(serializedToken));\n            Assert.Equal(@\"The anti-forgery token could not be decrypted. If this application is hosted by a Web Farm or cluster, ensure that all machines are running the same version of ASP.NET Web Pages and that the <machineKey> configuration specifies explicit encryption and validation keys. AutoGenerate cannot be used in a cluster.\", ex.Message);\n        }\n\n        [Fact]\n        public void Serialize_FieldToken_WithClaimUid()\n        {\n            // Arrange\n            const string expectedSerializedData =\n                \"01\" // Version\n                + \"705EEDCC7D42F1D6B3B98A593625BB4C\" // SecurityToken\n                + \"00\" // IsSessionToken\n                + \"01\" // IsClaimsBased\n                + \"6F1648E97249AA58754036A67E248CF044F07ECFB0ED387556CE029A4F9A40E0\" // ClaimUid\n                + \"05\" // AdditionalData length header\n                + \"E282AC3437\"; // AdditionalData (\"€47\") as UTF8\n\n            AntiForgeryToken token = new AntiForgeryToken()\n            {\n                SecurityToken = _securityToken,\n                IsSessionToken = false,\n                ClaimUid = _claimUid,\n                AdditionalData = \"€47\"\n            };\n\n            // Act & assert - serialization\n            string actualSerializedData = _testSerializer.Serialize(token);\n            Assert.Equal(expectedSerializedData, actualSerializedData);\n\n            // Act & assert - deserialization\n            AntiForgeryToken deserializedToken = _testSerializer.Deserialize(actualSerializedData);\n            AssertTokensEqual(token, deserializedToken);\n        }\n\n        [Fact]\n        public void Serialize_FieldToken_WithUsername()\n        {\n            // Arrange\n            const string expectedSerializedData =\n                \"01\" // Version\n                + \"705EEDCC7D42F1D6B3B98A593625BB4C\" // SecurityToken\n                + \"00\" // IsSessionToken\n                + \"00\" // IsClaimsBased\n                + \"08\" // Username length header\n                + \"4AC3A972C3B46D65\" // Username (\"Jérôme\") as UTF8\n                + \"05\" // AdditionalData length header\n                + \"E282AC3437\"; // AdditionalData (\"€47\") as UTF8\n\n            AntiForgeryToken token = new AntiForgeryToken()\n            {\n                SecurityToken = _securityToken,\n                IsSessionToken = false,\n                Username = \"Jérôme\",\n                AdditionalData = \"€47\"\n            };\n\n            // Act & assert - serialization\n            string actualSerializedData = _testSerializer.Serialize(token);\n            Assert.Equal(expectedSerializedData, actualSerializedData);\n\n            // Act & assert - deserialization\n            AntiForgeryToken deserializedToken = _testSerializer.Deserialize(actualSerializedData);\n            AssertTokensEqual(token, deserializedToken);\n        }\n\n        [Fact]\n        public void Serialize_SessionToken()\n        {\n            // Arrange\n            const string expectedSerializedData =\n                \"01\" // Version\n                + \"705EEDCC7D42F1D6B3B98A593625BB4C\" // SecurityToken\n                + \"01\"; // IsSessionToken\n\n            AntiForgeryToken token = new AntiForgeryToken()\n            {\n                SecurityToken = _securityToken,\n                IsSessionToken = true\n            };\n\n            // Act & assert - serialization\n            string actualSerializedData = _testSerializer.Serialize(token);\n            Assert.Equal(expectedSerializedData, actualSerializedData);\n\n            // Act & assert - deserialization\n            AntiForgeryToken deserializedToken = _testSerializer.Deserialize(actualSerializedData);\n            AssertTokensEqual(token, deserializedToken);\n        }\n\n        private static string BytesToHex(byte[] bytes)\n        {\n            StringBuilder sb = new StringBuilder();\n            foreach (byte b in bytes)\n            {\n                sb.AppendFormat(CultureInfo.InvariantCulture, \"{0:X2}\", b);\n            }\n            return sb.ToString();\n        }\n\n        private static byte[] HexToBytes(string hex)\n        {\n            List<byte> bytes = new List<byte>();\n            for (int i = 0; i < hex.Length; i += 2)\n            {\n                byte b = Byte.Parse(hex.Substring(i, 2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture);\n                bytes.Add(b);\n            }\n            return bytes.ToArray();\n        }\n\n        private static ICryptoSystem CreateIdentityTransformCryptoSystem()\n        {\n            Mock<MockableCryptoSystem> mockCryptoSystem = new Mock<MockableCryptoSystem>();\n            mockCryptoSystem.Setup(o => o.Protect(It.IsAny<byte[]>())).Returns<byte[]>(HexUtil.HexEncode);\n            mockCryptoSystem.Setup(o => o.Unprotect(It.IsAny<string>())).Returns<string>(HexUtil.HexDecode);\n            return mockCryptoSystem.Object;\n        }\n\n        private static void AssertTokensEqual(AntiForgeryToken expected, AntiForgeryToken actual)\n        {\n            Assert.NotNull(expected);\n            Assert.NotNull(actual);\n            Assert.Equal(expected.AdditionalData, actual.AdditionalData);\n            Assert.Equal(expected.ClaimUid, actual.ClaimUid);\n            Assert.Equal(expected.IsSessionToken, actual.IsSessionToken);\n            Assert.Equal(expected.SecurityToken, actual.SecurityToken);\n            Assert.Equal(expected.Username, actual.Username);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Helpers/AntiXsrf/AntiForgeryTokenStoreTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Helpers.AntiXsrf.Test\n{\n    public class AntiForgeryTokenStoreTest\n    {\n        [Fact]\n        public void GetCookieToken_CookieDoesNotExist_ReturnsNull()\n        {\n            // Arrange\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(o => o.Request.Cookies).Returns(new HttpCookieCollection());\n\n            MockAntiForgeryConfig config = new MockAntiForgeryConfig()\n            {\n                CookieName = \"cookie-name\"\n            };\n\n            AntiForgeryTokenStore tokenStore = new AntiForgeryTokenStore(\n                config: config,\n                serializer: null);\n\n            // Act\n            AntiForgeryToken token = tokenStore.GetCookieToken(mockHttpContext.Object);\n\n            // Assert\n            Assert.Null(token);\n        }\n\n        [Fact]\n        public void GetCookieToken_CookieIsEmpty_ReturnsNull()\n        {\n            // Arrange\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(o => o.Request.Cookies).Returns(new HttpCookieCollection()\n            {\n                new HttpCookie(\"cookie-name\", \"\")\n            });\n\n            MockAntiForgeryConfig config = new MockAntiForgeryConfig()\n            {\n                CookieName = \"cookie-name\"\n            };\n\n            AntiForgeryTokenStore tokenStore = new AntiForgeryTokenStore(\n                config: config,\n                serializer: null);\n\n            // Act\n            AntiForgeryToken token = tokenStore.GetCookieToken(mockHttpContext.Object);\n\n            // Assert\n            Assert.Null(token);\n        }\n\n        [Fact]\n        public void GetCookieToken_CookieIsInvalid_PropagatesException()\n        {\n            // Arrange\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(o => o.Request.Cookies).Returns(new HttpCookieCollection()\n            {\n                new HttpCookie(\"cookie-name\", \"invalid-value\")\n            });\n\n            MockAntiForgeryConfig config = new MockAntiForgeryConfig()\n            {\n                CookieName = \"cookie-name\"\n            };\n\n            HttpAntiForgeryException expectedException = new HttpAntiForgeryException(\"some exception\");\n            Mock<MockableAntiForgeryTokenSerializer> mockSerializer = new Mock<MockableAntiForgeryTokenSerializer>();\n            mockSerializer.Setup(o => o.Deserialize(\"invalid-value\")).Throws(expectedException);\n\n            AntiForgeryTokenStore tokenStore = new AntiForgeryTokenStore(\n                config: config,\n                serializer: mockSerializer.Object);\n\n            // Act & assert\n            var ex = Assert.Throws<HttpAntiForgeryException>(() => tokenStore.GetCookieToken(mockHttpContext.Object));\n            Assert.Equal(expectedException, ex);\n        }\n\n        [Fact]\n        public void GetCookieToken_CookieIsValid_ReturnsToken()\n        {\n            // Arrange\n            AntiForgeryToken expectedToken = new AntiForgeryToken();\n\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(o => o.Request.Cookies).Returns(new HttpCookieCollection()\n            {\n                new HttpCookie(\"cookie-name\", \"valid-value\")\n            });\n\n            MockAntiForgeryConfig config = new MockAntiForgeryConfig()\n            {\n                CookieName = \"cookie-name\"\n            };\n\n            Mock<MockableAntiForgeryTokenSerializer> mockSerializer = new Mock<MockableAntiForgeryTokenSerializer>();\n            mockSerializer.Setup(o => o.Deserialize(\"valid-value\")).Returns((object)expectedToken);\n\n            AntiForgeryTokenStore tokenStore = new AntiForgeryTokenStore(\n                config: config,\n                serializer: mockSerializer.Object);\n\n            // Act\n            AntiForgeryToken retVal = tokenStore.GetCookieToken(mockHttpContext.Object);\n\n            // Assert\n            Assert.Same(expectedToken, retVal);\n        }\n\n        [Fact]\n        public void GetFormToken_FormFieldIsEmpty_ReturnsNull()\n        {\n            // Arrange\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(o => o.Request.Form.Get(\"form-field-name\")).Returns(\"\");\n\n            MockAntiForgeryConfig config = new MockAntiForgeryConfig()\n            {\n                FormFieldName = \"form-field-name\"\n            };\n\n            AntiForgeryTokenStore tokenStore = new AntiForgeryTokenStore(\n                config: config,\n                serializer: null);\n\n            // Act\n            AntiForgeryToken token = tokenStore.GetFormToken(mockHttpContext.Object);\n\n            // Assert\n            Assert.Null(token);\n        }\n\n        [Fact]\n        public void GetFormToken_FormFieldIsInvalid_PropagatesException()\n        {\n            // Arrange\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(o => o.Request.Form.Get(\"form-field-name\")).Returns(\"invalid-value\");\n\n            MockAntiForgeryConfig config = new MockAntiForgeryConfig()\n            {\n                FormFieldName = \"form-field-name\"\n            };\n\n            HttpAntiForgeryException expectedException = new HttpAntiForgeryException(\"some exception\");\n            Mock<MockableAntiForgeryTokenSerializer> mockSerializer = new Mock<MockableAntiForgeryTokenSerializer>();\n            mockSerializer.Setup(o => o.Deserialize(\"invalid-value\")).Throws(expectedException);\n\n            AntiForgeryTokenStore tokenStore = new AntiForgeryTokenStore(\n                config: config,\n                serializer: mockSerializer.Object);\n\n            // Act & assert\n            var ex = Assert.Throws<HttpAntiForgeryException>(() => tokenStore.GetFormToken(mockHttpContext.Object));\n            Assert.Same(expectedException, ex);\n        }\n\n        [Fact]\n        public void GetFormToken_FormFieldIsValid_ReturnsToken()\n        {\n            // Arrange\n            AntiForgeryToken expectedToken = new AntiForgeryToken();\n\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(o => o.Request.Form.Get(\"form-field-name\")).Returns(\"valid-value\");\n\n            MockAntiForgeryConfig config = new MockAntiForgeryConfig()\n            {\n                FormFieldName = \"form-field-name\"\n            };\n\n            Mock<MockableAntiForgeryTokenSerializer> mockSerializer = new Mock<MockableAntiForgeryTokenSerializer>();\n            mockSerializer.Setup(o => o.Deserialize(\"valid-value\")).Returns((object)expectedToken);\n\n            AntiForgeryTokenStore tokenStore = new AntiForgeryTokenStore(\n                config: config,\n                serializer: mockSerializer.Object);\n\n            // Act\n            AntiForgeryToken retVal = tokenStore.GetFormToken(mockHttpContext.Object);\n\n            // Assert\n            Assert.Same(expectedToken, retVal);\n        }\n\n        [Theory]\n        [InlineData(true, true)]\n        [InlineData(false, null)]\n        public void SaveCookieToken(bool requireSsl, bool? expectedCookieSecureFlag)\n        {\n            // Arrange\n            AntiForgeryToken token = new AntiForgeryToken();\n            HttpCookieCollection cookies = new HttpCookieCollection();\n            bool defaultCookieSecureValue = expectedCookieSecureFlag ?? new HttpCookie(\"name\", \"value\").Secure; // pulled from config; set by ctor\n\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(o => o.Response.Cookies).Returns(cookies);\n\n            Mock<MockableAntiForgeryTokenSerializer> mockSerializer = new Mock<MockableAntiForgeryTokenSerializer>();\n            mockSerializer.Setup(o => o.Serialize(token)).Returns(\"serialized-value\");\n\n            MockAntiForgeryConfig config = new MockAntiForgeryConfig()\n            {\n                CookieName = \"cookie-name\",\n                RequireSSL = requireSsl\n            };\n\n            AntiForgeryTokenStore tokenStore = new AntiForgeryTokenStore(\n                config: config,\n                serializer: mockSerializer.Object);\n\n            // Act\n            tokenStore.SaveCookieToken(mockHttpContext.Object, token);\n\n            // Assert\n            Assert.Single(cookies);\n            HttpCookie cookie = cookies[\"cookie-name\"];\n\n            Assert.NotNull(cookie);\n            Assert.Equal(\"serialized-value\", cookie.Value);\n            Assert.True(cookie.HttpOnly);\n            Assert.Equal(defaultCookieSecureValue, cookie.Secure);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Helpers/AntiXsrf/AntiForgeryTokenTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Helpers.AntiXsrf.Test\n{\n    public class AntiForgeryTokenTest\n    {\n        [Fact]\n        public void AdditionalDataProperty()\n        {\n            // Arrange\n            AntiForgeryToken token = new AntiForgeryToken();\n\n            // Act & assert - 1\n            Assert.Equal(\"\", token.AdditionalData);\n\n            // Act & assert - 2\n            token.AdditionalData = \"additional data\";\n            Assert.Equal(\"additional data\", token.AdditionalData);\n\n            // Act & assert - 3\n            token.AdditionalData = null;\n            Assert.Equal(\"\", token.AdditionalData);\n        }\n\n        [Fact]\n        public void ClaimUidProperty()\n        {\n            // Arrange\n            AntiForgeryToken token = new AntiForgeryToken();\n\n            // Act & assert - 1\n            Assert.Null(token.ClaimUid);\n\n            // Act & assert - 2\n            BinaryBlob blob = new BinaryBlob(32);\n            token.ClaimUid = blob;\n            Assert.Equal(blob, token.ClaimUid);\n\n            // Act & assert - 3\n            token.ClaimUid = null;\n            Assert.Null(token.ClaimUid);\n        }\n\n        [Fact]\n        public void IsSessionTokenProperty()\n        {\n            // Arrange\n            AntiForgeryToken token = new AntiForgeryToken();\n\n            // Act & assert - 1\n            Assert.False(token.IsSessionToken);\n\n            // Act & assert - 2\n            token.IsSessionToken = true;\n            Assert.True(token.IsSessionToken);\n\n            // Act & assert - 3\n            token.IsSessionToken = false;\n            Assert.False(token.IsSessionToken);\n        }\n\n        [Fact]\n        public void SecurityTokenProperty()\n        {\n            // Arrange\n            AntiForgeryToken token = new AntiForgeryToken();\n\n            // Act & assert - 1\n            BinaryBlob securityToken = token.SecurityToken;\n            Assert.NotNull(securityToken);\n            Assert.Equal(AntiForgeryToken.SecurityTokenBitLength, securityToken.BitLength);\n            Assert.Equal(securityToken, token.SecurityToken); // check that we're not making a new one each property call\n\n            // Act & assert - 2\n            securityToken = new BinaryBlob(64);\n            token.SecurityToken = securityToken;\n            Assert.Equal(securityToken, token.SecurityToken);\n\n            // Act & assert - 3\n            token.SecurityToken = null;\n            securityToken = token.SecurityToken;\n            Assert.NotNull(securityToken);\n            Assert.Equal(AntiForgeryToken.SecurityTokenBitLength, securityToken.BitLength);\n            Assert.Equal(securityToken, token.SecurityToken); // check that we're not making a new one each property call\n        }\n\n        [Fact]\n        public void UsernameProperty()\n        {\n            // Arrange\n            AntiForgeryToken token = new AntiForgeryToken();\n\n            // Act & assert - 1\n            Assert.Equal(\"\", token.Username);\n\n            // Act & assert - 2\n            token.Username = \"my username\";\n            Assert.Equal(\"my username\", token.Username);\n\n            // Act & assert - 3\n            token.Username = null;\n            Assert.Equal(\"\", token.Username);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Helpers/AntiXsrf/AntiForgeryWorkerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing System.IO;\nusing System.Security.Principal;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Helpers.AntiXsrf.Test\n{\n    public class AntiForgeryWorkerTest\n    {\n        [Fact]\n        public void ChecksSSL()\n        {\n            // Arrange\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(o => o.Request.IsSecureConnection).Returns(false);\n\n            IAntiForgeryConfig config = new MockAntiForgeryConfig()\n            {\n                RequireSSL = true\n            };\n\n            AntiForgeryWorker worker = new AntiForgeryWorker(\n                config: config,\n                serializer: null,\n                tokenStore: null,\n                validator: null);\n\n            // Act & assert\n            var ex = Assert.Throws<InvalidOperationException>(() => worker.Validate(mockHttpContext.Object, \"session-token\", \"field-token\"));\n            Assert.Equal(@\"The anti-forgery system has the configuration value AntiForgeryConfig.RequireSsl = true, but the current request is not an SSL request.\", ex.Message);\n\n            ex = Assert.Throws<InvalidOperationException>(() => worker.Validate(mockHttpContext.Object));\n            Assert.Equal(@\"The anti-forgery system has the configuration value AntiForgeryConfig.RequireSsl = true, but the current request is not an SSL request.\", ex.Message);\n\n            ex = Assert.Throws<InvalidOperationException>(() => worker.GetFormInputElement(mockHttpContext.Object));\n            Assert.Equal(@\"The anti-forgery system has the configuration value AntiForgeryConfig.RequireSsl = true, but the current request is not an SSL request.\", ex.Message);\n\n            ex = Assert.Throws<InvalidOperationException>(() => { string dummy1, dummy2; worker.GetTokens(mockHttpContext.Object, \"cookie-token\", out dummy1, out dummy2); });\n            Assert.Equal(@\"The anti-forgery system has the configuration value AntiForgeryConfig.RequireSsl = true, but the current request is not an SSL request.\", ex.Message);\n        }\n\n        [Fact]\n        public void GetFormInputElement_ExistingInvalidCookieToken()\n        {\n            // Arrange\n            GenericIdentity identity = new GenericIdentity(\"some-user\");\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(o => o.User).Returns(new GenericPrincipal(identity, new string[0]));\n\n            Mock<HttpResponseBase> mockResponse = new Mock<HttpResponseBase>();\n            mockResponse.Setup(r => r.Headers).Returns(new NameValueCollection());\n            mockHttpContext.Setup(o => o.Response).Returns(mockResponse.Object);\n\n            AntiForgeryToken oldCookieToken = new AntiForgeryToken() { IsSessionToken = true };\n            AntiForgeryToken newCookieToken = new AntiForgeryToken() { IsSessionToken = true };\n            AntiForgeryToken formToken = new AntiForgeryToken();\n\n            MockAntiForgeryConfig config = new MockAntiForgeryConfig()\n            {\n                FormFieldName = \"form-field-name\"\n            };\n\n            Mock<MockableAntiForgeryTokenSerializer> mockSerializer = new Mock<MockableAntiForgeryTokenSerializer>(MockBehavior.Strict);\n            mockSerializer.Setup(o => o.Serialize(formToken)).Returns(\"serialized-form-token\");\n\n            Mock<MockableTokenStore> mockTokenStore = new Mock<MockableTokenStore>(MockBehavior.Strict);\n            mockTokenStore.Setup(o => o.GetCookieToken(mockHttpContext.Object)).Returns(oldCookieToken);\n            mockTokenStore.Setup(o => o.SaveCookieToken(mockHttpContext.Object, newCookieToken)).Verifiable();\n\n            Mock<MockableTokenValidator> mockValidator = new Mock<MockableTokenValidator>(MockBehavior.Strict);\n            mockValidator.Setup(o => o.GenerateFormToken(mockHttpContext.Object, identity, newCookieToken)).Returns(formToken);\n            mockValidator.Setup(o => o.IsCookieTokenValid(oldCookieToken)).Returns(false);\n            mockValidator.Setup(o => o.IsCookieTokenValid(newCookieToken)).Returns(true);\n            mockValidator.Setup(o => o.GenerateCookieToken()).Returns(newCookieToken);\n\n            AntiForgeryWorker worker = new AntiForgeryWorker(\n                config: config,\n                serializer: mockSerializer.Object,\n                tokenStore: mockTokenStore.Object,\n                validator: mockValidator.Object);\n\n            // Act\n            TagBuilder retVal = worker.GetFormInputElement(mockHttpContext.Object);\n\n            // Assert\n            Assert.Equal(@\"<input name=\"\"form-field-name\"\" type=\"\"hidden\"\" value=\"\"serialized-form-token\"\" />\", retVal.ToString(TagRenderMode.SelfClosing));\n            mockTokenStore.Verify();\n        }\n\n        [Fact]\n        public void GetFormInputElement_ExistingInvalidCookieToken_SwallowsExceptions()\n        {\n            // Arrange\n            GenericIdentity identity = new GenericIdentity(\"some-user\");\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(o => o.User).Returns(new GenericPrincipal(identity, new string[0]));\n\n            Mock<HttpResponseBase> mockResponse = new Mock<HttpResponseBase>();\n            mockResponse.Setup(r => r.Headers).Returns(new NameValueCollection());\n            mockHttpContext.Setup(o => o.Response).Returns(mockResponse.Object);\n\n            AntiForgeryToken oldCookieToken = new AntiForgeryToken() { IsSessionToken = true };\n            AntiForgeryToken newCookieToken = new AntiForgeryToken() { IsSessionToken = true };\n            AntiForgeryToken formToken = new AntiForgeryToken();\n\n            MockAntiForgeryConfig config = new MockAntiForgeryConfig()\n            {\n                FormFieldName = \"form-field-name\"\n            };\n\n            Mock<MockableAntiForgeryTokenSerializer> mockSerializer = new Mock<MockableAntiForgeryTokenSerializer>(MockBehavior.Strict);\n            mockSerializer.Setup(o => o.Serialize(formToken)).Returns(\"serialized-form-token\");\n\n            Mock<MockableTokenStore> mockTokenStore = new Mock<MockableTokenStore>(MockBehavior.Strict);\n            mockTokenStore.Setup(o => o.GetCookieToken(mockHttpContext.Object)).Throws(new Exception(\"should be swallowed\"));\n            mockTokenStore.Setup(o => o.SaveCookieToken(mockHttpContext.Object, newCookieToken)).Verifiable();\n\n            Mock<MockableTokenValidator> mockValidator = new Mock<MockableTokenValidator>(MockBehavior.Strict);\n            mockValidator.Setup(o => o.GenerateFormToken(mockHttpContext.Object, identity, newCookieToken)).Returns(formToken);\n            mockValidator.Setup(o => o.IsCookieTokenValid(null)).Returns(false);\n            mockValidator.Setup(o => o.IsCookieTokenValid(newCookieToken)).Returns(true);\n            mockValidator.Setup(o => o.GenerateCookieToken()).Returns(newCookieToken);\n\n            AntiForgeryWorker worker = new AntiForgeryWorker(\n                config: config,\n                serializer: mockSerializer.Object,\n                tokenStore: mockTokenStore.Object,\n                validator: mockValidator.Object);\n\n            // Act\n            TagBuilder retVal = worker.GetFormInputElement(mockHttpContext.Object);\n\n            // Assert\n            Assert.Equal(@\"<input name=\"\"form-field-name\"\" type=\"\"hidden\"\" value=\"\"serialized-form-token\"\" />\", retVal.ToString(TagRenderMode.SelfClosing));\n            mockTokenStore.Verify();\n        }\n\n        [Fact]\n        public void GetFormInputElement_ExistingValidCookieToken()\n        {\n            // Arrange\n            GenericIdentity identity = new GenericIdentity(\"some-user\");\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(o => o.User).Returns(new GenericPrincipal(identity, new string[0]));\n\n            Mock<HttpResponseBase> mockResponse = new Mock<HttpResponseBase>();\n            mockResponse.Setup(r => r.Headers).Returns(new NameValueCollection());\n            mockHttpContext.Setup(o => o.Response).Returns(mockResponse.Object);\n            \n            AntiForgeryToken cookieToken = new AntiForgeryToken() { IsSessionToken = true };\n            AntiForgeryToken formToken = new AntiForgeryToken();\n\n            MockAntiForgeryConfig config = new MockAntiForgeryConfig()\n            {\n                FormFieldName = \"form-field-name\"\n            };\n\n            Mock<MockableAntiForgeryTokenSerializer> mockSerializer = new Mock<MockableAntiForgeryTokenSerializer>(MockBehavior.Strict);\n            mockSerializer.Setup(o => o.Serialize(formToken)).Returns(\"serialized-form-token\");\n\n            Mock<MockableTokenStore> mockTokenStore = new Mock<MockableTokenStore>(MockBehavior.Strict);\n            mockTokenStore.Setup(o => o.GetCookieToken(mockHttpContext.Object)).Returns(cookieToken);\n\n            Mock<MockableTokenValidator> mockValidator = new Mock<MockableTokenValidator>(MockBehavior.Strict);\n            mockValidator.Setup(o => o.GenerateFormToken(mockHttpContext.Object, identity, cookieToken)).Returns(formToken);\n            mockValidator.Setup(o => o.IsCookieTokenValid(cookieToken)).Returns(true);\n\n            AntiForgeryWorker worker = new AntiForgeryWorker(\n                config: config,\n                serializer: mockSerializer.Object,\n                tokenStore: mockTokenStore.Object,\n                validator: mockValidator.Object);\n\n            // Act\n            TagBuilder retVal = worker.GetFormInputElement(mockHttpContext.Object);\n\n            // Assert\n            Assert.Equal(@\"<input name=\"\"form-field-name\"\" type=\"\"hidden\"\" value=\"\"serialized-form-token\"\" />\", retVal.ToString(TagRenderMode.SelfClosing));\n        }\n\n        [Theory]\n        [InlineData(false, \"SAMEORIGIN\")]\n        [InlineData(true, null)]\n        public void GetFormInputElement_AddsXFrameOptionsHeader(bool suppressXFrameOptions, string expectedHeaderValue)\n        {\n            // Arrange\n            GenericIdentity identity = new GenericIdentity(\"some-user\");\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(o => o.User).Returns(new GenericPrincipal(identity, new string[0]));\n\n            NameValueCollection headers = new NameValueCollection();\n            Mock<HttpResponseBase> mockResponse = new Mock<HttpResponseBase>();\n            mockResponse.Setup(r => r.Headers).Returns(headers);\n            mockResponse.Setup(r => r.AddHeader(It.IsAny<string>(), It.IsAny<string>())).Callback<string, string>((k, v) =>\n            {\n                headers.Add(k, v);\n            });\n            mockHttpContext.Setup(o => o.Response).Returns(mockResponse.Object);\n\n            AntiForgeryToken oldCookieToken = new AntiForgeryToken() { IsSessionToken = true };\n            AntiForgeryToken newCookieToken = new AntiForgeryToken() { IsSessionToken = true };\n            AntiForgeryToken formToken = new AntiForgeryToken();\n\n            MockAntiForgeryConfig config = new MockAntiForgeryConfig()\n            {\n                FormFieldName = \"form-field-name\",\n                SuppressXFrameOptionsHeader = suppressXFrameOptions\n            };\n\n            Mock<MockableAntiForgeryTokenSerializer> mockSerializer = new Mock<MockableAntiForgeryTokenSerializer>(MockBehavior.Strict);\n            mockSerializer.Setup(o => o.Serialize(formToken)).Returns(\"serialized-form-token\");\n\n            Mock<MockableTokenStore> mockTokenStore = new Mock<MockableTokenStore>(MockBehavior.Strict);\n            mockTokenStore.Setup(o => o.GetCookieToken(mockHttpContext.Object)).Returns(oldCookieToken);\n            mockTokenStore.Setup(o => o.SaveCookieToken(mockHttpContext.Object, newCookieToken)).Verifiable();\n\n            Mock<MockableTokenValidator> mockValidator = new Mock<MockableTokenValidator>(MockBehavior.Strict);\n            mockValidator.Setup(o => o.GenerateFormToken(mockHttpContext.Object, identity, newCookieToken)).Returns(formToken);\n            mockValidator.Setup(o => o.IsCookieTokenValid(oldCookieToken)).Returns(false);\n            mockValidator.Setup(o => o.IsCookieTokenValid(newCookieToken)).Returns(true);\n            mockValidator.Setup(o => o.GenerateCookieToken()).Returns(newCookieToken);\n\n            AntiForgeryWorker worker = new AntiForgeryWorker(\n                config: config,\n                serializer: mockSerializer.Object,\n                tokenStore: mockTokenStore.Object,\n                validator: mockValidator.Object);\n            HttpContextBase context = mockHttpContext.Object;\n\n            // Act\n            TagBuilder retVal = worker.GetFormInputElement(context);\n\n            // Assert\n            string xFrameOptions = context.Response.Headers[\"X-FRAME-OPTIONS\"];\n            Assert.Equal(expectedHeaderValue, xFrameOptions);\n        }\n\n        [Fact]\n        public void GetTokens_ExistingInvalidCookieToken()\n        {\n            // Arrange\n            GenericIdentity identity = new GenericIdentity(\"some-user\");\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(o => o.User).Returns(new GenericPrincipal(identity, new string[0]));\n\n            AntiForgeryToken oldCookieToken = new AntiForgeryToken() { IsSessionToken = true };\n            AntiForgeryToken newCookieToken = new AntiForgeryToken() { IsSessionToken = true };\n            AntiForgeryToken formToken = new AntiForgeryToken();\n\n            Mock<MockableAntiForgeryTokenSerializer> mockSerializer = new Mock<MockableAntiForgeryTokenSerializer>(MockBehavior.Strict);\n            mockSerializer.Setup(o => o.Deserialize(\"serialized-old-cookie-token\")).Returns(oldCookieToken);\n            mockSerializer.Setup(o => o.Serialize(newCookieToken)).Returns(\"serialized-new-cookie-token\");\n            mockSerializer.Setup(o => o.Serialize(formToken)).Returns(\"serialized-form-token\");\n\n            Mock<MockableTokenValidator> mockValidator = new Mock<MockableTokenValidator>(MockBehavior.Strict);\n            mockValidator.Setup(o => o.GenerateFormToken(mockHttpContext.Object, identity, newCookieToken)).Returns(formToken);\n            mockValidator.Setup(o => o.IsCookieTokenValid(oldCookieToken)).Returns(false);\n            mockValidator.Setup(o => o.IsCookieTokenValid(newCookieToken)).Returns(true);\n            mockValidator.Setup(o => o.GenerateCookieToken()).Returns(newCookieToken);\n\n            AntiForgeryWorker worker = new AntiForgeryWorker(\n                config: new MockAntiForgeryConfig(),\n                serializer: mockSerializer.Object,\n                tokenStore: null,\n                validator: mockValidator.Object);\n\n            // Act\n            string serializedNewCookieToken, serializedFormToken;\n            worker.GetTokens(mockHttpContext.Object, \"serialized-old-cookie-token\", out serializedNewCookieToken, out serializedFormToken);\n\n            // Assert\n            Assert.Equal(\"serialized-new-cookie-token\", serializedNewCookieToken);\n            Assert.Equal(\"serialized-form-token\", serializedFormToken);\n        }\n\n        [Fact]\n        public void GetTokens_ExistingInvalidCookieToken_SwallowsExceptions()\n        {\n            // Arrange\n            GenericIdentity identity = new GenericIdentity(\"some-user\");\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(o => o.User).Returns(new GenericPrincipal(identity, new string[0]));\n\n            AntiForgeryToken oldCookieToken = new AntiForgeryToken() { IsSessionToken = true };\n            AntiForgeryToken newCookieToken = new AntiForgeryToken() { IsSessionToken = true };\n            AntiForgeryToken formToken = new AntiForgeryToken();\n\n            Mock<MockableAntiForgeryTokenSerializer> mockSerializer = new Mock<MockableAntiForgeryTokenSerializer>(MockBehavior.Strict);\n            mockSerializer.Setup(o => o.Deserialize(\"serialized-old-cookie-token\")).Throws(new Exception(\"should be swallowed\"));\n            mockSerializer.Setup(o => o.Serialize(newCookieToken)).Returns(\"serialized-new-cookie-token\");\n            mockSerializer.Setup(o => o.Serialize(formToken)).Returns(\"serialized-form-token\");\n\n            Mock<MockableTokenValidator> mockValidator = new Mock<MockableTokenValidator>(MockBehavior.Strict);\n            mockValidator.Setup(o => o.GenerateFormToken(mockHttpContext.Object, identity, newCookieToken)).Returns(formToken);\n            mockValidator.Setup(o => o.IsCookieTokenValid(null)).Returns(false);\n            mockValidator.Setup(o => o.IsCookieTokenValid(newCookieToken)).Returns(true);\n            mockValidator.Setup(o => o.GenerateCookieToken()).Returns(newCookieToken);\n\n            AntiForgeryWorker worker = new AntiForgeryWorker(\n                config: new MockAntiForgeryConfig(),\n                serializer: mockSerializer.Object,\n                tokenStore: null,\n                validator: mockValidator.Object);\n\n            // Act\n            string serializedNewCookieToken, serializedFormToken;\n            worker.GetTokens(mockHttpContext.Object, \"serialized-old-cookie-token\", out serializedNewCookieToken, out serializedFormToken);\n\n            // Assert\n            Assert.Equal(\"serialized-new-cookie-token\", serializedNewCookieToken);\n            Assert.Equal(\"serialized-form-token\", serializedFormToken);\n        }\n\n        [Fact]\n        public void GetTokens_ExistingValidCookieToken()\n        {\n            // Arrange\n            GenericIdentity identity = new GenericIdentity(\"some-user\");\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(o => o.User).Returns(new GenericPrincipal(identity, new string[0]));\n\n            AntiForgeryToken cookieToken = new AntiForgeryToken() { IsSessionToken = true };\n            AntiForgeryToken formToken = new AntiForgeryToken();\n\n            Mock<MockableAntiForgeryTokenSerializer> mockSerializer = new Mock<MockableAntiForgeryTokenSerializer>(MockBehavior.Strict);\n            mockSerializer.Setup(o => o.Deserialize(\"serialized-old-cookie-token\")).Returns(cookieToken);\n            mockSerializer.Setup(o => o.Serialize(formToken)).Returns(\"serialized-form-token\");\n\n            Mock<MockableTokenValidator> mockValidator = new Mock<MockableTokenValidator>(MockBehavior.Strict);\n            mockValidator.Setup(o => o.GenerateFormToken(mockHttpContext.Object, identity, cookieToken)).Returns(formToken);\n            mockValidator.Setup(o => o.IsCookieTokenValid(cookieToken)).Returns(true);\n\n            AntiForgeryWorker worker = new AntiForgeryWorker(\n                config: new MockAntiForgeryConfig(),\n                serializer: mockSerializer.Object,\n                tokenStore: null,\n                validator: mockValidator.Object);\n\n            // Act\n            string serializedNewCookieToken, serializedFormToken;\n            worker.GetTokens(mockHttpContext.Object, \"serialized-old-cookie-token\", out serializedNewCookieToken, out serializedFormToken);\n\n            // Assert\n            Assert.Null(serializedNewCookieToken);\n            Assert.Equal(\"serialized-form-token\", serializedFormToken);\n        }\n\n        [Fact]\n        public void Validate_FromStrings_Failure()\n        {\n            // Arrange\n            GenericIdentity identity = new GenericIdentity(\"some-user\");\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(o => o.User).Returns(new GenericPrincipal(identity, new string[0]));\n\n            AntiForgeryToken cookieToken = new AntiForgeryToken();\n            AntiForgeryToken formToken = new AntiForgeryToken();\n\n            Mock<MockableAntiForgeryTokenSerializer> mockSerializer = new Mock<MockableAntiForgeryTokenSerializer>();\n            mockSerializer.Setup(o => o.Deserialize(\"cookie-token\")).Returns(cookieToken);\n            mockSerializer.Setup(o => o.Deserialize(\"form-token\")).Returns(formToken);\n\n            Mock<MockableTokenValidator> mockValidator = new Mock<MockableTokenValidator>();\n            mockValidator.Setup(o => o.ValidateTokens(mockHttpContext.Object, identity, cookieToken, formToken)).Throws(new HttpAntiForgeryException(\"my-message\"));\n\n            AntiForgeryWorker worker = new AntiForgeryWorker(\n                config: new MockAntiForgeryConfig(),\n                serializer: mockSerializer.Object,\n                tokenStore: null,\n                validator: mockValidator.Object);\n\n            // Act & assert\n            var ex = Assert.Throws<HttpAntiForgeryException>(() => worker.Validate(mockHttpContext.Object, \"cookie-token\", \"form-token\"));\n            Assert.Equal(\"my-message\", ex.Message);\n        }\n\n        [Fact]\n        public void Validate_FromStrings_Success()\n        {\n            // Arrange\n            GenericIdentity identity = new GenericIdentity(\"some-user\");\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(o => o.User).Returns(new GenericPrincipal(identity, new string[0]));\n\n            AntiForgeryToken cookieToken = new AntiForgeryToken();\n            AntiForgeryToken formToken = new AntiForgeryToken();\n\n            Mock<MockableAntiForgeryTokenSerializer> mockSerializer = new Mock<MockableAntiForgeryTokenSerializer>();\n            mockSerializer.Setup(o => o.Deserialize(\"cookie-token\")).Returns(cookieToken);\n            mockSerializer.Setup(o => o.Deserialize(\"form-token\")).Returns(formToken);\n\n            Mock<MockableTokenValidator> mockValidator = new Mock<MockableTokenValidator>();\n            mockValidator.Setup(o => o.ValidateTokens(mockHttpContext.Object, identity, cookieToken, formToken)).Verifiable();\n\n            AntiForgeryWorker worker = new AntiForgeryWorker(\n                config: new MockAntiForgeryConfig(),\n                serializer: mockSerializer.Object,\n                tokenStore: null,\n                validator: mockValidator.Object);\n\n            // Act\n            worker.Validate(mockHttpContext.Object, \"cookie-token\", \"form-token\");\n\n            // Assert\n            mockValidator.Verify();\n        }\n\n        [Fact]\n        public void Validate_FromStore_Failure()\n        {\n            // Arrange\n            GenericIdentity identity = new GenericIdentity(\"some-user\");\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(o => o.User).Returns(new GenericPrincipal(identity, new string[0]));\n\n            AntiForgeryToken cookieToken = new AntiForgeryToken();\n            AntiForgeryToken formToken = new AntiForgeryToken();\n\n            Mock<MockableTokenStore> mockTokenStore = new Mock<MockableTokenStore>();\n            mockTokenStore.Setup(o => o.GetCookieToken(mockHttpContext.Object)).Returns(cookieToken);\n            mockTokenStore.Setup(o => o.GetFormToken(mockHttpContext.Object)).Returns(formToken);\n\n            Mock<MockableTokenValidator> mockValidator = new Mock<MockableTokenValidator>();\n            mockValidator.Setup(o => o.ValidateTokens(mockHttpContext.Object, identity, cookieToken, formToken)).Throws(new HttpAntiForgeryException(\"my-message\"));\n\n            AntiForgeryWorker worker = new AntiForgeryWorker(\n                config: new MockAntiForgeryConfig(),\n                serializer: null,\n                tokenStore: mockTokenStore.Object,\n                validator: mockValidator.Object);\n\n            // Act & assert\n            var ex = Assert.Throws<HttpAntiForgeryException>(() => worker.Validate(mockHttpContext.Object));\n            Assert.Equal(\"my-message\", ex.Message);\n        }\n\n        [Fact]\n        public void Validate_FromStore_Success()\n        {\n            // Arrange\n            GenericIdentity identity = new GenericIdentity(\"some-user\");\n            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();\n            mockHttpContext.Setup(o => o.User).Returns(new GenericPrincipal(identity, new string[0]));\n\n            AntiForgeryToken cookieToken = new AntiForgeryToken();\n            AntiForgeryToken formToken = new AntiForgeryToken();\n\n            Mock<MockableTokenStore> mockTokenStore = new Mock<MockableTokenStore>();\n            mockTokenStore.Setup(o => o.GetCookieToken(mockHttpContext.Object)).Returns(cookieToken);\n            mockTokenStore.Setup(o => o.GetFormToken(mockHttpContext.Object)).Returns(formToken);\n\n            Mock<MockableTokenValidator> mockValidator = new Mock<MockableTokenValidator>();\n            mockValidator.Setup(o => o.ValidateTokens(mockHttpContext.Object, identity, cookieToken, formToken)).Verifiable();\n\n            AntiForgeryWorker worker = new AntiForgeryWorker(\n                config: new MockAntiForgeryConfig(),\n                serializer: null,\n                tokenStore: mockTokenStore.Object,\n                validator: mockValidator.Object);\n\n            // Act\n            worker.Validate(mockHttpContext.Object);\n\n            // Assert\n            mockValidator.Verify();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Helpers/AntiXsrf/BinaryBlobTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Helpers.AntiXsrf.Test\n{\n    public class BinaryBlobTest\n    {\n        [Fact]\n        public void Ctor_BitLength()\n        {\n            // Act\n            BinaryBlob blob = new BinaryBlob(bitLength: 64);\n            byte[] data = blob.GetData();\n\n            // Assert\n            Assert.Equal(64, blob.BitLength);\n            Assert.Equal(64 / 8, data.Length);\n            Assert.NotEqual(new byte[64 / 8], data); // should not be a zero-filled array\n        }\n\n        [Theory]\n        [InlineData(24)]\n        [InlineData(33)]\n        public void Ctor_BitLength_Bad(int bitLength)\n        {\n            // Act & assert\n            var ex = Assert.Throws<ArgumentOutOfRangeException>(() => new BinaryBlob(bitLength));\n            Assert.Equal(\"bitLength\", ex.ParamName);\n        }\n\n        [Fact]\n        public void Ctor_BitLength_ProducesDifferentValues()\n        {\n            // Act\n            BinaryBlob blobA = new BinaryBlob(bitLength: 64);\n            BinaryBlob blobB = new BinaryBlob(bitLength: 64);\n\n            // Assert\n            Assert.NotEqual(blobA.GetData(), blobB.GetData());\n        }\n\n        [Fact]\n        public void Ctor_Data()\n        {\n            // Arrange\n            byte[] expectedData = new byte[] { 0x01, 0x02, 0x03, 0x04 };\n\n            // Act\n            BinaryBlob blob = new BinaryBlob(32, expectedData);\n\n            // Assert\n            Assert.Equal(32, blob.BitLength);\n            Assert.Equal(expectedData, blob.GetData());\n        }\n\n        [Theory]\n        [InlineData((object[])null)]\n        [InlineData(new byte[] { 0x01, 0x02, 0x03 })]\n        public void Ctor_Data_Bad(byte[] data)\n        {\n            // Act & assert\n            var ex = Assert.Throws<ArgumentOutOfRangeException>(() => new BinaryBlob(32, data));\n            Assert.Equal(\"data\", ex.ParamName);\n        }\n\n        [Fact]\n        public void Equals_DifferentData_ReturnsFalse()\n        {\n            // Arrange\n            object blobA = new BinaryBlob(32, new byte[] { 0x01, 0x02, 0x03, 0x04 });\n            object blobB = new BinaryBlob(32, new byte[] { 0x04, 0x03, 0x02, 0x01 });\n\n            // Act & assert\n            Assert.NotEqual(blobA, blobB);\n        }\n\n        [Fact]\n        public void Equals_NotABlob_ReturnsFalse()\n        {\n            // Arrange\n            object blobA = new BinaryBlob(32);\n            object blobB = \"hello\";\n\n            // Act & assert\n            Assert.NotEqual(blobA, blobB);\n        }\n\n        [Fact]\n        public void Equals_Null_ReturnsFalse()\n        {\n            // Arrange\n            object blobA = new BinaryBlob(32);\n            object blobB = null;\n\n            // Act & assert\n            Assert.NotEqual(blobA, blobB);\n        }\n\n        [Fact]\n        public void Equals_SameData_ReturnsTrue()\n        {\n            // Arrange\n            object blobA = new BinaryBlob(32, new byte[] { 0x01, 0x02, 0x03, 0x04 });\n            object blobB = new BinaryBlob(32, new byte[] { 0x01, 0x02, 0x03, 0x04 });\n\n            // Act & assert\n            Assert.Equal(blobA, blobB);\n        }\n\n        [Fact]\n        public void GetHashCodeTest()\n        {\n            // Arrange\n            byte[] blobData = new byte[] { 0x01, 0x02, 0x03, 0x04 };\n            int expectedHashCode = BitConverter.ToInt32(blobData, 0);\n\n            BinaryBlob blob = new BinaryBlob(32, blobData);\n\n            // Act\n            int actualHashCode = blob.GetHashCode();\n\n            // Assert\n            Assert.Equal(expectedHashCode, actualHashCode);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Helpers/AntiXsrf/ClaimUidExtractorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Security.Principal;\nusing System.Web.Helpers.Claims;\nusing System.Web.Helpers.Claims.Test;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Helpers.AntiXsrf.Test\n{\n    public class ClaimUidExtractorTest\n    {\n        [Fact]\n        public void ExtractClaimUid_NullIdentity()\n        {\n            // Arrange\n            ClaimUidExtractor extractor = new ClaimUidExtractor(\n                config: null,\n                claimsIdentityConverter: null);\n\n            // Act\n            BinaryBlob retVal = extractor.ExtractClaimUid(null);\n\n            // Assert\n            Assert.Null(retVal);\n        }\n\n        [Fact]\n        public void ExtractClaimUid_Unauthenticated()\n        {\n            // Arrange\n            ClaimUidExtractor extractor = new ClaimUidExtractor(\n                config: null,\n                claimsIdentityConverter: null);\n\n            Mock<IIdentity> mockIdentity = new Mock<IIdentity>();\n            mockIdentity.Setup(o => o.IsAuthenticated).Returns(false);\n\n            // Act\n            BinaryBlob retVal = extractor.ExtractClaimUid(mockIdentity.Object);\n\n            // Assert\n            Assert.Null(retVal);\n        }\n\n        [Fact]\n        public void ExtractClaimUid_ClaimsIdentityHeuristicsSuppressed()\n        {\n            // Arrange\n            GenericIdentity identity = new GenericIdentity(\"the-user\");\n            MockAntiForgeryConfig config = new MockAntiForgeryConfig()\n            {\n                SuppressIdentityHeuristicChecks = true\n            };\n\n            ClaimUidExtractor extractor = new ClaimUidExtractor(\n                config: config,\n                claimsIdentityConverter: null);\n\n            // Act\n            BinaryBlob retVal = extractor.ExtractClaimUid(identity);\n\n            // Assert\n            Assert.Null(retVal);\n        }\n\n        [Fact]\n        public void ExtractClaimUid_NotAClaimsIdentity()\n        {\n            // Arrange\n            Mock<IIdentity> mockIdentity = new Mock<IIdentity>();\n            mockIdentity.Setup(o => o.IsAuthenticated).Returns(true);\n            MockAntiForgeryConfig config = new MockAntiForgeryConfig();\n            ClaimsIdentityConverter converter = new ClaimsIdentityConverter(new Func<IIdentity, ClaimsIdentity>[0]);\n\n            ClaimUidExtractor extractor = new ClaimUidExtractor(\n                config: config,\n                claimsIdentityConverter: converter);\n\n            // Act\n            BinaryBlob retVal = extractor.ExtractClaimUid(mockIdentity.Object);\n\n            // Assert\n            Assert.Null(retVal);\n        }\n\n        [Fact]\n        public void ExtractClaimUid_ClaimsIdentity()\n        {\n            // Arrange\n            Mock<IIdentity> mockIdentity = new Mock<IIdentity>();\n            mockIdentity.Setup(o => o.IsAuthenticated).Returns(true);\n            MockAntiForgeryConfig config = new MockAntiForgeryConfig()\n            {\n                UniqueClaimTypeIdentifier = \"unique-identifier\"\n            };\n            ClaimsIdentityConverter converter = new ClaimsIdentityConverter(new Func<IIdentity, ClaimsIdentity>[] {\n               identity =>\n               {\n                   Assert.Equal(mockIdentity.Object, identity);\n                   MockClaimsIdentity claimsIdentity = new MockClaimsIdentity();\n                   claimsIdentity.AddClaim(\"unique-identifier\", \"some-value\");\n                   return claimsIdentity;\n               }\n            });\n\n            ClaimUidExtractor extractor = new ClaimUidExtractor(\n                config: config,\n                claimsIdentityConverter: converter);\n\n            // Act\n            BinaryBlob retVal = extractor.ExtractClaimUid(mockIdentity.Object);\n\n            // Assert\n            Assert.NotNull(retVal);\n            Assert.Equal(\"CA9CCFF86F903FBB7505BAAA9F222E49EC2A1E8FAD630AE73DE180BD679751ED\", HexUtil.HexEncode(retVal.GetData()));\n        }\n\n        [Theory]\n        [DefaultUniqueClaimTypes_NotPresent_Data]\n        public void DefaultUniqueClaimTypes_NotPresent_Throws(object identity)\n        {\n            // Arrange\n            ClaimsIdentity claimsIdentity = (ClaimsIdentity)identity;\n\n            // Act & assert\n            var ex = Assert.Throws<InvalidOperationException>(() => ClaimUidExtractor.GetUniqueIdentifierParameters(claimsIdentity, null));\n            Assert.Equal(@\"A claim of type 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier' or 'http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider' was not present on the provided ClaimsIdentity. To enable anti-forgery token support with claims-based authentication, please verify that the configured claims provider is providing both of these claims on the ClaimsIdentity instances it generates. If the configured claims provider instead uses a different claim type as a unique identifier, it can be configured by setting the static property AntiForgeryConfig.UniqueClaimTypeIdentifier.\", ex.Message);\n        }\n\n        [Fact]\n        public void DefaultUniqueClaimTypes_Present()\n        {\n            // Arrange\n            MockClaimsIdentity identity = new MockClaimsIdentity();\n            identity.AddClaim(\"fooClaim\", \"fooClaimValue\");\n            identity.AddClaim(ClaimUidExtractor.NameIdentifierClaimType, \"nameIdentifierValue\");\n            identity.AddClaim(ClaimUidExtractor.IdentityProviderClaimType, \"identityProviderValue\");\n\n            // Act\n            var retVal = ClaimUidExtractor.GetUniqueIdentifierParameters(identity, null);\n\n            // Assert\n            Assert.Equal(new string[] {\n                ClaimUidExtractor.NameIdentifierClaimType,\n                \"nameIdentifierValue\",\n                ClaimUidExtractor.IdentityProviderClaimType,\n                \"identityProviderValue\"\n            }, retVal);\n        }\n\n        [Fact]\n        public void ExplicitUniqueClaimType_Present()\n        {\n            // Arrange\n            MockClaimsIdentity identity = new MockClaimsIdentity();\n            identity.AddClaim(\"fooClaim\", \"fooClaimValue\");\n            identity.AddClaim(ClaimUidExtractor.NameIdentifierClaimType, \"nameIdentifierValue\");\n            identity.AddClaim(ClaimUidExtractor.IdentityProviderClaimType, \"identityProviderValue\");\n\n            // Act\n            var retVal = ClaimUidExtractor.GetUniqueIdentifierParameters(identity, \"fooClaim\");\n\n            // Assert\n            Assert.Equal(new string[] {\n                \"fooClaim\",\n                \"fooClaimValue\"\n            }, retVal);\n        }\n\n        [Theory]\n        [ExplicitUniqueClaimType_NotPresent_Data]\n        public void ExplicitUniqueClaimType_NotPresent_Throws(object identity)\n        {\n            // Arrange\n            ClaimsIdentity claimsIdentity = (ClaimsIdentity)identity;\n\n            // Act & assert\n            var ex = Assert.Throws<InvalidOperationException>(() => ClaimUidExtractor.GetUniqueIdentifierParameters(claimsIdentity, \"fooClaim\"));\n            Assert.Equal(@\"A claim of type 'fooClaim' was not present on the provided ClaimsIdentity.\", ex.Message);\n        }\n\n        private sealed class DefaultUniqueClaimTypes_NotPresent_DataAttribute : DataAttribute\n        {\n            public override IEnumerable<object[]> GetData(MethodInfo methodUnderTest, Type[] parameterTypes)\n            {\n                MockClaimsIdentity identity1 = new MockClaimsIdentity();\n                identity1.AddClaim(ClaimUidExtractor.IdentityProviderClaimType, \"identityProviderValue\");\n                yield return new object[] { identity1 };\n\n                MockClaimsIdentity identity2 = new MockClaimsIdentity();\n                identity2.AddClaim(ClaimUidExtractor.NameIdentifierClaimType, String.Empty);\n                identity2.AddClaim(ClaimUidExtractor.IdentityProviderClaimType, \"identityProviderValue\");\n                yield return new object[] { identity2 };\n\n                MockClaimsIdentity identity3 = new MockClaimsIdentity();\n                identity3.AddClaim(ClaimUidExtractor.NameIdentifierClaimType, \"nameIdentifierValue\");\n                yield return new object[] { identity3 };\n\n                MockClaimsIdentity identity4 = new MockClaimsIdentity();\n                identity4.AddClaim(ClaimUidExtractor.NameIdentifierClaimType, \"nameIdentifierValue\");\n                identity4.AddClaim(ClaimUidExtractor.IdentityProviderClaimType, String.Empty);\n                yield return new object[] { identity4 };\n\n                MockClaimsIdentity identity5 = new MockClaimsIdentity();\n                identity5.AddClaim(ClaimUidExtractor.NameIdentifierClaimType.ToUpper(), \"nameIdentifierValue\");\n                identity5.AddClaim(ClaimUidExtractor.IdentityProviderClaimType.ToUpper(), \"identityProviderValue\");\n                yield return new object[] { identity5 };\n            }\n        }\n\n        private sealed class ExplicitUniqueClaimType_NotPresent_DataAttribute : DataAttribute\n        {\n            public override IEnumerable<object[]> GetData(MethodInfo methodUnderTest, Type[] parameterTypes)\n            {\n                MockClaimsIdentity identity1 = new MockClaimsIdentity();\n                yield return new object[] { identity1 };\n\n                MockClaimsIdentity identity2 = new MockClaimsIdentity();\n                identity2.AddClaim(\"fooClaim\", String.Empty);\n                yield return new object[] { identity2 };\n\n                MockClaimsIdentity identity3 = new MockClaimsIdentity();\n                identity3.AddClaim(\"FOOCLAIM\", \"fooClaimValue\");\n                yield return new object[] { identity3 };\n\n                MockClaimsIdentity identity4 = new MockClaimsIdentity();\n                identity4.AddClaim(ClaimUidExtractor.NameIdentifierClaimType, \"nameIdentifierValue\");\n                identity4.AddClaim(ClaimUidExtractor.IdentityProviderClaimType, \"identityProviderValue\");\n                yield return new object[] { identity4 };\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Helpers/AntiXsrf/HexUtil.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Text;\n\nnamespace System.Web.Helpers.AntiXsrf.Test\n{\n    internal static class HexUtil\n    {\n        public static string HexEncode(byte[] data)\n        {\n            StringBuilder sb = new StringBuilder(data.Length * 2);\n            foreach (byte b in data)\n            {\n                sb.AppendFormat(CultureInfo.InvariantCulture, \"{0:X2}\", b);\n            }\n            return sb.ToString();\n        }\n\n        public static byte[] HexDecode(string input)\n        {\n            List<byte> bytes = new List<byte>(input.Length / 2);\n            for (int i = 0; i < input.Length; i += 2)\n            {\n                bytes.Add(Byte.Parse(input.Substring(i, 2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture));\n            }\n            return bytes.ToArray();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Helpers/AntiXsrf/MachineKey45CryptoSystemTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Helpers.AntiXsrf.Test\n{\n    public class MachineKey45CryptoSystemTest\n    {\n        [Fact]\n        public void Protect()\n        {\n            // Arrange\n            byte[] unprotectedBytes = new byte[] { 1, 2, 3, 4, 5 };\n            string unprotectedString = HttpServerUtility.UrlTokenEncode(unprotectedBytes);\n\n            MachineKey45CryptoSystem cryptoSystem = new MachineKey45CryptoSystem();\n\n            // Act\n            string protectedString = cryptoSystem.Protect(unprotectedBytes);\n\n            // Assert\n            Assert.NotEqual(unprotectedString, protectedString);\n        }\n\n        [Fact]\n        public void Unprotect()\n        {\n            // Arrange\n            byte[] unprotectedBytes = new byte[] { 1, 2, 3, 4, 5 };\n\n            MachineKey45CryptoSystem cryptoSystem = new MachineKey45CryptoSystem();\n\n            // Act\n            string protectedString = cryptoSystem.Protect(unprotectedBytes);\n            byte[] output = cryptoSystem.Unprotect(protectedString);\n\n            // Assert\n            Assert.Equal(unprotectedBytes, output);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Helpers/AntiXsrf/MockAntiForgeryConfig.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Helpers.AntiXsrf.Test\n{\n    public sealed class MockAntiForgeryConfig : IAntiForgeryConfig\n    {\n        public IAntiForgeryAdditionalDataProvider AdditionalDataProvider\n        {\n            get;\n            set;\n        }\n\n        public string CookieName\n        {\n            get;\n            set;\n        }\n\n        public string FormFieldName\n        {\n            get;\n            set;\n        }\n\n        public bool RequireSSL\n        {\n            get;\n            set;\n        }\n\n        public bool SuppressIdentityHeuristicChecks\n        {\n            get;\n            set;\n        }\n\n        public string UniqueClaimTypeIdentifier\n        {\n            get;\n            set;\n        }\n\n        public bool SuppressXFrameOptionsHeader\n        {\n            get;\n            set;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Helpers/AntiXsrf/MockableAntiForgeryTokenSerializer.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Helpers.AntiXsrf.Test\n{\n    // An IAntiForgeryTokenSerializer that can be passed to MoQ.\n    public abstract class MockableAntiForgeryTokenSerializer : IAntiForgeryTokenSerializer\n    {\n        public abstract object Deserialize(string serializedToken);\n        public abstract string Serialize(object token);\n\n        AntiForgeryToken IAntiForgeryTokenSerializer.Deserialize(string serializedToken)\n        {\n            return (AntiForgeryToken)Deserialize(serializedToken);\n        }\n\n        string IAntiForgeryTokenSerializer.Serialize(AntiForgeryToken token)\n        {\n            return Serialize(token);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Helpers/AntiXsrf/MockableClaimUidExtractor.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Security.Principal;\n\nnamespace System.Web.Helpers.AntiXsrf.Test\n{\n    // An IClaimUidExtractor that can be passed to MoQ\n    public abstract class MockableClaimUidExtractor : IClaimUidExtractor\n    {\n        public abstract object ExtractClaimUid(IIdentity identity);\n\n        BinaryBlob IClaimUidExtractor.ExtractClaimUid(IIdentity identity)\n        {\n            return (BinaryBlob)ExtractClaimUid(identity);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Helpers/AntiXsrf/MockableCryptoSystem.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace System.Web.Helpers.AntiXsrf.Test\n{\n    // An ICryptoSystem that can be passed to MoQ\n    public abstract class MockableCryptoSystem : ICryptoSystem\n    {\n        public abstract string Protect(byte[] data);\n        public abstract byte[] Unprotect(string protectedData);\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Helpers/AntiXsrf/MockableTokenStore.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\n\nnamespace System.Web.Helpers.AntiXsrf.Test\n{\n    // An ITokenStore that can be passed to MoQ\n    public abstract class MockableTokenStore : ITokenStore\n    {\n        public abstract object GetCookieToken(HttpContextBase httpContext);\n        public abstract object GetFormToken(HttpContextBase httpContext);\n        public abstract void SaveCookieToken(HttpContextBase httpContext, object token);\n\n        AntiForgeryToken ITokenStore.GetCookieToken(HttpContextBase httpContext)\n        {\n            return (AntiForgeryToken)GetCookieToken(httpContext);\n        }\n\n        AntiForgeryToken ITokenStore.GetFormToken(HttpContextBase httpContext)\n        {\n            return (AntiForgeryToken)GetFormToken(httpContext);\n        }\n\n        void ITokenStore.SaveCookieToken(HttpContextBase httpContext, AntiForgeryToken token)\n        {\n            SaveCookieToken(httpContext, (AntiForgeryToken)token);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Helpers/AntiXsrf/MockableTokenValidator.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Security.Principal;\n\nnamespace System.Web.Helpers.AntiXsrf.Test\n{\n    // An ITokenValidator that can be passed to MoQ\n    public abstract class MockableTokenValidator : ITokenValidator\n    {\n        public abstract object GenerateCookieToken();\n        public abstract object GenerateFormToken(HttpContextBase httpContext, IIdentity identity, object cookieToken);\n        public abstract bool IsCookieTokenValid(object cookieToken);\n        public abstract void ValidateTokens(HttpContextBase httpContext, IIdentity identity, object cookieToken, object formToken);\n\n        AntiForgeryToken ITokenValidator.GenerateCookieToken()\n        {\n            return (AntiForgeryToken)GenerateCookieToken();\n        }\n\n        AntiForgeryToken ITokenValidator.GenerateFormToken(HttpContextBase httpContext, IIdentity identity, AntiForgeryToken cookieToken)\n        {\n            return (AntiForgeryToken)GenerateFormToken(httpContext, identity, (AntiForgeryToken)cookieToken);\n        }\n\n        bool ITokenValidator.IsCookieTokenValid(AntiForgeryToken cookieToken)\n        {\n            return IsCookieTokenValid((AntiForgeryToken)cookieToken);\n        }\n\n        void ITokenValidator.ValidateTokens(HttpContextBase httpContext, IIdentity identity, AntiForgeryToken cookieToken, AntiForgeryToken formToken)\n        {\n            ValidateTokens(httpContext, identity, (AntiForgeryToken)cookieToken, (AntiForgeryToken)formToken);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Helpers/AntiXsrf/TokenValidatorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Security.Principal;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Helpers.AntiXsrf.Test\n{\n    public class TokenValidatorTest\n    {\n        [Fact]\n        public void GenerateCookieToken()\n        {\n            // Arrange\n            TokenValidator tokenValidator = new TokenValidator(\n                config: null,\n                claimUidExtractor: null);\n\n            // Act\n            AntiForgeryToken retVal = tokenValidator.GenerateCookieToken();\n\n            // Assert\n            Assert.NotNull(retVal);\n        }\n\n        [Fact]\n        public void GenerateFormToken_AnonymousUser()\n        {\n            // Arrange\n            AntiForgeryToken cookieToken = new AntiForgeryToken() { IsSessionToken = true };\n            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;\n            Mock<IIdentity> mockIdentity = new Mock<IIdentity>();\n            mockIdentity.Setup(o => o.IsAuthenticated).Returns(false);\n\n            IAntiForgeryConfig config = new MockAntiForgeryConfig();\n\n            TokenValidator validator = new TokenValidator(\n                config: config,\n                claimUidExtractor: null);\n\n            // Act\n            var fieldToken = validator.GenerateFormToken(httpContext, mockIdentity.Object, cookieToken);\n\n            // Assert\n            Assert.NotNull(fieldToken);\n            Assert.Equal(cookieToken.SecurityToken, fieldToken.SecurityToken);\n            Assert.False(fieldToken.IsSessionToken);\n            Assert.Equal(\"\", fieldToken.Username);\n            Assert.Null(fieldToken.ClaimUid);\n            Assert.Equal(\"\", fieldToken.AdditionalData);\n        }\n\n        [Fact]\n        public void GenerateFormToken_AuthenticatedWithoutUsernameAndNoAdditionalData_NoAdditionalData()\n        {\n            // Arrange\n            AntiForgeryToken cookieToken = new AntiForgeryToken()\n            {\n                IsSessionToken = true\n            };\n\n            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;\n            IIdentity identity = new MyAuthenticatedIdentityWithoutUsername();\n            IAntiForgeryConfig config = new MockAntiForgeryConfig();\n            IClaimUidExtractor claimUidExtractor = new Mock<MockableClaimUidExtractor>().Object;\n\n            TokenValidator validator = new TokenValidator(\n                config: config,\n                claimUidExtractor: claimUidExtractor);\n\n            // Act & assert\n            var ex = Assert.Throws<InvalidOperationException>(() => validator.GenerateFormToken(httpContext, identity, cookieToken));\n            Assert.Equal(@\"The provided identity of type 'System.Web.Helpers.AntiXsrf.Test.TokenValidatorTest+MyAuthenticatedIdentityWithoutUsername' is marked IsAuthenticated = true but does not have a value for Name. By default, the anti-forgery system requires that all authenticated identities have a unique Name. If it is not possible to provide a unique Name for this identity, consider setting the static property AntiForgeryConfig.AdditionalDataProvider to an instance of a type that can provide some form of unique identifier for the current user.\", ex.Message);\n        }\n\n        [Fact]\n        public void GenerateFormToken_AuthenticatedWithoutUsernameAndNoAdditionalData_NoAdditionalData_SuppressHeuristics()\n        {\n            // Arrange\n            AntiForgeryToken cookieToken = new AntiForgeryToken() { IsSessionToken = true };\n            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;\n            IIdentity identity = new MyAuthenticatedIdentityWithoutUsername();\n\n            IAntiForgeryConfig config = new MockAntiForgeryConfig()\n            {\n                SuppressIdentityHeuristicChecks = true\n            };\n            IClaimUidExtractor claimUidExtractor = new Mock<MockableClaimUidExtractor>().Object;\n\n            TokenValidator validator = new TokenValidator(\n                config: config,\n                claimUidExtractor: claimUidExtractor);\n\n            // Act\n            var fieldToken = validator.GenerateFormToken(httpContext, identity, cookieToken);\n\n            // Assert\n            Assert.NotNull(fieldToken);\n            Assert.Equal(cookieToken.SecurityToken, fieldToken.SecurityToken);\n            Assert.False(fieldToken.IsSessionToken);\n            Assert.Equal(\"\", fieldToken.Username);\n            Assert.Null(fieldToken.ClaimUid);\n            Assert.Equal(\"\", fieldToken.AdditionalData);\n        }\n\n        [Fact]\n        public void GenerateFormToken_AuthenticatedWithoutUsername_WithAdditionalData()\n        {\n            // Arrange\n            AntiForgeryToken cookieToken = new AntiForgeryToken() { IsSessionToken = true };\n            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;\n            IIdentity identity = new MyAuthenticatedIdentityWithoutUsername();\n\n            Mock<IAntiForgeryAdditionalDataProvider> mockAdditionalDataProvider = new Mock<IAntiForgeryAdditionalDataProvider>();\n            mockAdditionalDataProvider.Setup(o => o.GetAdditionalData(httpContext)).Returns(\"additional-data\");\n\n            IAntiForgeryConfig config = new MockAntiForgeryConfig()\n            {\n                AdditionalDataProvider = mockAdditionalDataProvider.Object\n            };\n            IClaimUidExtractor claimUidExtractor = new Mock<MockableClaimUidExtractor>().Object;\n\n            TokenValidator validator = new TokenValidator(\n                config: config,\n                claimUidExtractor: claimUidExtractor);\n\n            // Act\n            var fieldToken = validator.GenerateFormToken(httpContext, identity, cookieToken);\n\n            // Assert\n            Assert.NotNull(fieldToken);\n            Assert.Equal(cookieToken.SecurityToken, fieldToken.SecurityToken);\n            Assert.False(fieldToken.IsSessionToken);\n            Assert.Equal(\"\", fieldToken.Username);\n            Assert.Null(fieldToken.ClaimUid);\n            Assert.Equal(\"additional-data\", fieldToken.AdditionalData);\n        }\n\n        [Fact]\n        public void GenerateFormToken_ClaimsBasedIdentity()\n        {\n            // Arrange\n            AntiForgeryToken cookieToken = new AntiForgeryToken() { IsSessionToken = true };\n            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;\n            IIdentity identity = new GenericIdentity(\"some-identity\");\n\n            MockAntiForgeryConfig config = new MockAntiForgeryConfig()\n            {\n                UniqueClaimTypeIdentifier = \"unique-identifier\"\n            };\n\n            BinaryBlob expectedClaimUid = new BinaryBlob(256);\n            Mock<MockableClaimUidExtractor> mockClaimUidExtractor = new Mock<MockableClaimUidExtractor>();\n            mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity)).Returns((object)expectedClaimUid);\n\n            TokenValidator validator = new TokenValidator(\n                config: config,\n                claimUidExtractor: mockClaimUidExtractor.Object);\n\n            // Act\n            var fieldToken = validator.GenerateFormToken(httpContext, identity, cookieToken);\n\n            // Assert\n            Assert.NotNull(fieldToken);\n            Assert.Equal(cookieToken.SecurityToken, fieldToken.SecurityToken);\n            Assert.False(fieldToken.IsSessionToken);\n            Assert.Equal(\"\", fieldToken.Username);\n            Assert.Equal(expectedClaimUid, fieldToken.ClaimUid);\n            Assert.Equal(\"\", fieldToken.AdditionalData);\n        }\n\n        [Fact]\n        public void GenerateFormToken_RegularUserWithUsername()\n        {\n            // Arrange\n            AntiForgeryToken cookieToken = new AntiForgeryToken() { IsSessionToken = true };\n\n            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;\n            Mock<IIdentity> mockIdentity = new Mock<IIdentity>();\n            mockIdentity.Setup(o => o.IsAuthenticated).Returns(true);\n            mockIdentity.Setup(o => o.Name).Returns(\"my-username\");\n\n            IAntiForgeryConfig config = new MockAntiForgeryConfig();\n            IClaimUidExtractor claimUidExtractor = new Mock<MockableClaimUidExtractor>().Object;\n\n            TokenValidator validator = new TokenValidator(\n                config: config,\n                claimUidExtractor: claimUidExtractor);\n\n            // Act\n            var fieldToken = validator.GenerateFormToken(httpContext, mockIdentity.Object, cookieToken);\n\n            // Assert\n            Assert.NotNull(fieldToken);\n            Assert.Equal(cookieToken.SecurityToken, fieldToken.SecurityToken);\n            Assert.False(fieldToken.IsSessionToken);\n            Assert.Equal(\"my-username\", fieldToken.Username);\n            Assert.Null(fieldToken.ClaimUid);\n            Assert.Equal(\"\", fieldToken.AdditionalData);\n        }\n\n        [Fact]\n        public void IsCookieTokenValid_FieldToken_ReturnsFalse()\n        {\n            // Arrange\n            AntiForgeryToken cookieToken = new AntiForgeryToken()\n            {\n                IsSessionToken = false\n            };\n\n            TokenValidator validator = new TokenValidator(\n                config: null,\n                claimUidExtractor: null);\n\n            // Act\n            bool retVal = validator.IsCookieTokenValid(cookieToken);\n\n            // Assert\n            Assert.False(retVal);\n        }\n\n        [Fact]\n        public void IsCookieTokenValid_NullToken_ReturnsFalse()\n        {\n            // Arrange\n            AntiForgeryToken cookieToken = null;\n            TokenValidator validator = new TokenValidator(\n                config: null,\n                claimUidExtractor: null);\n\n            // Act\n            bool retVal = validator.IsCookieTokenValid(cookieToken);\n\n            // Assert\n            Assert.False(retVal);\n        }\n\n        [Fact]\n        public void IsCookieTokenValid_ValidToken_ReturnsTrue()\n        {\n            // Arrange\n            AntiForgeryToken cookieToken = new AntiForgeryToken()\n            {\n                IsSessionToken = true\n            };\n\n            TokenValidator validator = new TokenValidator(\n                config: null,\n                claimUidExtractor: null);\n\n            // Act\n            bool retVal = validator.IsCookieTokenValid(cookieToken);\n\n            // Assert\n            Assert.True(retVal);\n        }\n\n        [Fact]\n        public void ValidateTokens_SessionTokenMissing()\n        {\n            // Arrange\n            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;\n            IIdentity identity = new Mock<IIdentity>().Object;\n            AntiForgeryToken sessionToken = null;\n            AntiForgeryToken fieldtoken = new AntiForgeryToken() { IsSessionToken = false };\n\n            MockAntiForgeryConfig config = new MockAntiForgeryConfig()\n            {\n                CookieName = \"my-cookie-name\"\n            };\n            TokenValidator validator = new TokenValidator(\n                config: config,\n                claimUidExtractor: null);\n\n            // Act & assert\n            var ex = Assert.Throws<HttpAntiForgeryException>(() => validator.ValidateTokens(httpContext, identity, sessionToken, fieldtoken));\n            Assert.Equal(@\"The required anti-forgery cookie \"\"my-cookie-name\"\" is not present.\", ex.Message);\n        }\n\n        [Fact]\n        public void ValidateTokens_FieldTokenMissing()\n        {\n            // Arrange\n            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;\n            IIdentity identity = new Mock<IIdentity>().Object;\n            AntiForgeryToken sessionToken = new AntiForgeryToken() { IsSessionToken = true };\n            AntiForgeryToken fieldtoken = null;\n\n            MockAntiForgeryConfig config = new MockAntiForgeryConfig()\n            {\n                FormFieldName = \"my-form-field-name\"\n            };\n            TokenValidator validator = new TokenValidator(\n                config: config,\n                claimUidExtractor: null);\n\n            // Act & assert\n            var ex = Assert.Throws<HttpAntiForgeryException>(() => validator.ValidateTokens(httpContext, identity, sessionToken, fieldtoken));\n            Assert.Equal(@\"The required anti-forgery form field \"\"my-form-field-name\"\" is not present.\", ex.Message);\n        }\n\n        [Fact]\n        public void ValidateTokens_FieldAndSessionTokensSwapped()\n        {\n            // Arrange\n            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;\n            IIdentity identity = new Mock<IIdentity>().Object;\n            AntiForgeryToken sessionToken = new AntiForgeryToken() { IsSessionToken = true };\n            AntiForgeryToken fieldtoken = new AntiForgeryToken() { IsSessionToken = false };\n\n            MockAntiForgeryConfig config = new MockAntiForgeryConfig()\n            {\n                CookieName = \"my-cookie-name\",\n                FormFieldName = \"my-form-field-name\"\n            };\n            TokenValidator validator = new TokenValidator(\n                config: config,\n                claimUidExtractor: null);\n\n            // Act & assert\n            var ex1 = Assert.Throws<HttpAntiForgeryException>(() => validator.ValidateTokens(httpContext, identity, fieldtoken, fieldtoken));\n            Assert.Equal(@\"Validation of the provided anti-forgery token failed. The cookie \"\"my-cookie-name\"\" and the form field \"\"my-form-field-name\"\" were swapped.\", ex1.Message);\n\n            var ex2 = Assert.Throws<HttpAntiForgeryException>(() => validator.ValidateTokens(httpContext, identity, sessionToken, sessionToken));\n            Assert.Equal(@\"Validation of the provided anti-forgery token failed. The cookie \"\"my-cookie-name\"\" and the form field \"\"my-form-field-name\"\" were swapped.\", ex2.Message);\n        }\n\n        [Fact]\n        public void ValidateTokens_FieldAndSessionTokensHaveDifferentSecurityKeys()\n        {\n            // Arrange\n            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;\n            IIdentity identity = new Mock<IIdentity>().Object;\n            AntiForgeryToken sessionToken = new AntiForgeryToken() { IsSessionToken = true };\n            AntiForgeryToken fieldtoken = new AntiForgeryToken() { IsSessionToken = false };\n\n            TokenValidator validator = new TokenValidator(\n                config: null,\n                claimUidExtractor: null);\n\n            // Act & assert\n            var ex = Assert.Throws<HttpAntiForgeryException>(() => validator.ValidateTokens(httpContext, identity, sessionToken, fieldtoken));\n            Assert.Equal(@\"The anti-forgery cookie token and form field token do not match.\", ex.Message);\n        }\n\n        [Theory]\n        [InlineData(\"the-user\", \"the-other-user\")]\n        [InlineData(\"http://example.com/uri-casing\", \"http://example.com/URI-casing\")]\n        [InlineData(\"https://example.com/secure-uri-casing\", \"https://example.com/secure-URI-casing\")]\n        public void ValidateTokens_UsernameMismatch(string identityUsername, string embeddedUsername)\n        {\n            // Arrange\n            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;\n            IIdentity identity = new GenericIdentity(identityUsername);\n            AntiForgeryToken sessionToken = new AntiForgeryToken() { IsSessionToken = true };\n            AntiForgeryToken fieldtoken = new AntiForgeryToken() { SecurityToken = sessionToken.SecurityToken, Username = embeddedUsername, IsSessionToken = false };\n\n            Mock<MockableClaimUidExtractor> mockClaimUidExtractor = new Mock<MockableClaimUidExtractor>();\n            mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity)).Returns((object)null);\n\n            TokenValidator validator = new TokenValidator(\n                config: null,\n                claimUidExtractor: mockClaimUidExtractor.Object);\n\n            // Act & assert\n            var ex = Assert.Throws<HttpAntiForgeryException>(() => validator.ValidateTokens(httpContext, identity, sessionToken, fieldtoken));\n            Assert.Equal(@\"The provided anti-forgery token was meant for user \"\"\" + embeddedUsername + @\"\"\", but the current user is \"\"\" + identityUsername + @\"\"\".\", ex.Message);\n        }\n\n        [Fact]\n        public void ValidateTokens_ClaimUidMismatch()\n        {\n            // Arrange\n            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;\n            IIdentity identity = new GenericIdentity(\"the-user\");\n            AntiForgeryToken sessionToken = new AntiForgeryToken() { IsSessionToken = true };\n            AntiForgeryToken fieldtoken = new AntiForgeryToken() { SecurityToken = sessionToken.SecurityToken, IsSessionToken = false, ClaimUid = new BinaryBlob(256) };\n\n            Mock<MockableClaimUidExtractor> mockClaimUidExtractor = new Mock<MockableClaimUidExtractor>();\n            mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity)).Returns(new BinaryBlob(256));\n\n            TokenValidator validator = new TokenValidator(\n                config: null,\n                claimUidExtractor: mockClaimUidExtractor.Object);\n\n            // Act & assert\n            var ex = Assert.Throws<HttpAntiForgeryException>(() => validator.ValidateTokens(httpContext, identity, sessionToken, fieldtoken));\n            Assert.Equal(@\"The provided anti-forgery token was meant for a different claims-based user than the current user.\", ex.Message);\n        }\n\n        [Fact]\n        public void ValidateTokens_AdditionalDataRejected()\n        {\n            // Arrange\n            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;\n            IIdentity identity = new GenericIdentity(String.Empty);\n            AntiForgeryToken sessionToken = new AntiForgeryToken() { IsSessionToken = true };\n            AntiForgeryToken fieldtoken = new AntiForgeryToken() { SecurityToken = sessionToken.SecurityToken, Username = String.Empty, IsSessionToken = false, AdditionalData = \"some-additional-data\" };\n\n            Mock<IAntiForgeryAdditionalDataProvider> mockAdditionalDataProvider = new Mock<IAntiForgeryAdditionalDataProvider>();\n            mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, \"some-additional-data\")).Returns(false);\n\n            MockAntiForgeryConfig config = new MockAntiForgeryConfig()\n            {\n                AdditionalDataProvider = mockAdditionalDataProvider.Object\n            };\n            TokenValidator validator = new TokenValidator(\n                config: config,\n                claimUidExtractor: null);\n\n            // Act & assert\n            var ex = Assert.Throws<HttpAntiForgeryException>(() => validator.ValidateTokens(httpContext, identity, sessionToken, fieldtoken));\n            Assert.Equal(@\"The provided anti-forgery token failed a custom data check.\", ex.Message);\n        }\n\n        [Fact]\n        public void ValidateTokens_Success_AnonymousUser()\n        {\n            // Arrange\n            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;\n            IIdentity identity = new GenericIdentity(String.Empty);\n            AntiForgeryToken sessionToken = new AntiForgeryToken() { IsSessionToken = true };\n            AntiForgeryToken fieldtoken = new AntiForgeryToken() { SecurityToken = sessionToken.SecurityToken, Username = String.Empty, IsSessionToken = false, AdditionalData = \"some-additional-data\" };\n\n            Mock<IAntiForgeryAdditionalDataProvider> mockAdditionalDataProvider = new Mock<IAntiForgeryAdditionalDataProvider>();\n            mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, \"some-additional-data\")).Returns(true);\n\n            MockAntiForgeryConfig config = new MockAntiForgeryConfig()\n            {\n                AdditionalDataProvider = mockAdditionalDataProvider.Object\n            };\n            TokenValidator validator = new TokenValidator(\n                config: config,\n                claimUidExtractor: null);\n\n            // Act\n            validator.ValidateTokens(httpContext, identity, sessionToken, fieldtoken);\n\n            // Assert\n            // Nothing to assert - if we got this far, success!\n        }\n\n        [Fact]\n        public void ValidateTokens_Success_AuthenticatedUserWithUsername()\n        {\n            // Arrange\n            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;\n            IIdentity identity = new GenericIdentity(\"the-user\");\n            AntiForgeryToken sessionToken = new AntiForgeryToken() { IsSessionToken = true };\n            AntiForgeryToken fieldtoken = new AntiForgeryToken() { SecurityToken = sessionToken.SecurityToken, Username = \"THE-USER\", IsSessionToken = false, AdditionalData = \"some-additional-data\" };\n\n            Mock<IAntiForgeryAdditionalDataProvider> mockAdditionalDataProvider = new Mock<IAntiForgeryAdditionalDataProvider>();\n            mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, \"some-additional-data\")).Returns(true);\n\n            MockAntiForgeryConfig config = new MockAntiForgeryConfig()\n            {\n                AdditionalDataProvider = mockAdditionalDataProvider.Object\n            };\n            TokenValidator validator = new TokenValidator(\n                config: config,\n                claimUidExtractor: new Mock<MockableClaimUidExtractor>().Object);\n\n            // Act\n            validator.ValidateTokens(httpContext, identity, sessionToken, fieldtoken);\n\n            // Assert\n            // Nothing to assert - if we got this far, success!\n        }\n\n        [Fact]\n        public void ValidateTokens_Success_ClaimsBasedUser()\n        {\n            // Arrange\n            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;\n            IIdentity identity = new GenericIdentity(\"the-user\");\n            AntiForgeryToken sessionToken = new AntiForgeryToken() { IsSessionToken = true };\n            AntiForgeryToken fieldtoken = new AntiForgeryToken() { SecurityToken = sessionToken.SecurityToken, IsSessionToken = false, ClaimUid = new BinaryBlob(256) };\n\n            Mock<MockableClaimUidExtractor> mockClaimUidExtractor = new Mock<MockableClaimUidExtractor>();\n            mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity)).Returns(fieldtoken.ClaimUid);\n\n            MockAntiForgeryConfig config = new MockAntiForgeryConfig();\n\n            TokenValidator validator = new TokenValidator(\n                config: config,\n                claimUidExtractor: mockClaimUidExtractor.Object);\n\n            // Act\n            validator.ValidateTokens(httpContext, identity, sessionToken, fieldtoken);\n\n            // Assert\n            // Nothing to assert - if we got this far, success!\n        }\n\n        private sealed class MyAuthenticatedIdentityWithoutUsername : IIdentity\n        {\n            public string AuthenticationType\n            {\n                get { throw new NotImplementedException(); }\n            }\n\n            public bool IsAuthenticated\n            {\n                get { return true; }\n            }\n\n            public string Name\n            {\n                get { return String.Empty; }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Helpers/Claims/ClaimTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Helpers.Claims.Test\n{\n    public class ClaimTest\n    {\n        [Fact]\n        public void CtorAndProperties()\n        {\n            // Act\n            Claim claim = new Claim(\"claim-type\", \"claim-value\");\n\n            // Assert\n            Assert.Equal(\"claim-type\", claim.ClaimType);\n            Assert.Equal(\"claim-value\", claim.Value);\n        }\n\n        [Fact]\n        public void Create_WithClaimTypeProperty()\n        {\n            // Act\n            Claim claim = Claim.Create<IClaimType1>(new MyClaimType());\n\n            // Assert\n            Assert.Equal(\"my-claim-type-1\", claim.ClaimType);\n            Assert.Equal(\"my-claim-value-1\", claim.Value);\n        }\n\n        [Fact]\n        public void Create_WithTypeProperty()\n        {\n            // Act\n            Claim claim = Claim.Create<IClaimType2>(new MyClaimType());\n\n            // Assert\n            Assert.Equal(\"my-claim-type-2\", claim.ClaimType);\n            Assert.Equal(\"my-claim-value-2\", claim.Value);\n        }\n\n        private interface IClaimType1\n        {\n            string ClaimType { get; }\n            string Value { get; }\n        }\n\n        private interface IClaimType2\n        {\n            string Type { get; }\n            string Value { get; }\n        }\n\n        private sealed class MyClaimType : IClaimType1, IClaimType2\n        {\n            string IClaimType1.ClaimType { get { return \"my-claim-type-1\"; } }\n            string IClaimType1.Value { get { return \"my-claim-value-1\"; } }\n\n            string IClaimType2.Type { get { return \"my-claim-type-2\"; } }\n            string IClaimType2.Value { get { return \"my-claim-value-2\"; } }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Helpers/Claims/ClaimsIdentityConverterTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Security.Principal;\nusing System.Web.Security;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.Helpers.Claims.Test\n{\n    public class ClaimsIdentityConverterTest\n    {\n        [Fact]\n        public void TryConvert_NoMatches_ReturnsNull()\n        {\n            // Arrange\n            IIdentity identity = new Mock<IIdentity>().Object;\n            ClaimsIdentityConverter converter = new ClaimsIdentityConverter(new Func<IIdentity, ClaimsIdentity>[0]);\n\n            // Act\n            ClaimsIdentity retVal = converter.TryConvert(identity);\n\n            // Assert\n            Assert.Null(retVal);\n        }\n\n        [Fact]\n        public void TryConvert_ReturnsFirstMatch()\n        {\n            // Arrange\n            IIdentity identity = new Mock<IIdentity>().Object;\n            ClaimsIdentity claimsIdentity = new MockClaimsIdentity();\n\n            ClaimsIdentityConverter converter = new ClaimsIdentityConverter(new Func<IIdentity, ClaimsIdentity>[]\n            {\n                _ => null,\n                i => (i == identity) ? claimsIdentity : null\n            });\n\n            // Act\n            ClaimsIdentity retVal = converter.TryConvert(identity);\n\n            // Assert\n            Assert.Same(claimsIdentity, retVal);\n        }\n\n        [Theory]\n        [GrandfatheredTypesData]\n        public void TryConvert_SkipsGrandfatheredTypes(IIdentity identity)\n        {\n            // Arrange\n            ClaimsIdentityConverter converter = new ClaimsIdentityConverter(new Func<IIdentity, ClaimsIdentity>[]\n            {\n                _ => { throw new Exception(\"Should never be called.\"); }\n            });\n\n            // Act\n            ClaimsIdentity retVal = converter.TryConvert(identity);\n\n            // Assert\n            Assert.Null(retVal);\n        }\n\n        private sealed class GrandfatheredTypesDataAttribute : DataAttribute\n        {\n            // We need to subclass these types so that they implement the\n            // appropriate interface to be claims-based.\n            public override IEnumerable<object[]> GetData(MethodInfo methodUnderTest, Type[] parameterTypes)\n            {\n                yield return new object[] { new SubclassedFormsIdentity() };\n                yield return new object[] { new SubclassedGenericIdentity() };\n\n                SubclassedWindowsIdentity subclassedWindowsIdentity = null;\n                using (WindowsIdentity originalIdentity = WindowsIdentity.GetCurrent())\n                {\n                    subclassedWindowsIdentity = new SubclassedWindowsIdentity(originalIdentity.Token);\n                }\n                yield return new object[] { subclassedWindowsIdentity };\n            }\n        }\n\n        private sealed class SubclassedFormsIdentity : FormsIdentity\n        {\n            public SubclassedFormsIdentity() : base(new FormsAuthenticationTicket(\"my-name\", false, 60)) { }\n        }\n\n        private sealed class SubclassedGenericIdentity : GenericIdentity\n        {\n            public SubclassedGenericIdentity() : base(\"my-name\") { }\n        }\n\n        private sealed class SubclassedWindowsIdentity : WindowsIdentity\n        {\n            public SubclassedWindowsIdentity(IntPtr userToken) : base(userToken) { }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Helpers/Claims/ClaimsIdentityTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Security.Principal;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Helpers.Claims.Test\n{\n    public class ClaimsIdentityTest\n    {\n        [Fact]\n        public void TryConvert_GetClaims()\n        {\n            // Act\n            ClaimsIdentity claimsIdentity = ClaimsIdentity.TryConvert<IClaimsIdentity, IClaim>(new MyClaimsIdentity());\n            var claims = claimsIdentity.GetClaims().ToArray();\n\n            // Assert\n            Assert.Equal(2, claims.Length);\n            Assert.Equal(\"claim-type-1\", claims[0].ClaimType);\n            Assert.Equal(\"claim-value-1\", claims[0].Value);\n            Assert.Equal(\"claim-type-2\", claims[1].ClaimType);\n            Assert.Equal(\"claim-value-2\", claims[1].Value);\n        }\n\n        private interface IClaimsIdentity : IIdentity\n        {\n            IEnumerable<IClaim> Claims { get; }\n        }\n\n        private interface IClaim\n        {\n            string ClaimType { get; }\n            string Value { get; }\n        }\n\n        private sealed class MyClaimsIdentity : IClaimsIdentity, IIdentity\n        {\n            IEnumerable<IClaim> IClaimsIdentity.Claims\n            {\n                get\n                {\n                    return new MyClaim[]\n                    {\n                        new MyClaim() { ClaimType = \"claim-type-1\", Value = \"claim-value-1\" },\n                        new MyClaim() { ClaimType = \"claim-type-2\", Value = \"claim-value-2\" }\n                    };\n                }\n            }\n\n            string IIdentity.AuthenticationType\n            {\n                get { throw new NotImplementedException(); }\n            }\n\n            bool IIdentity.IsAuthenticated\n            {\n                get { throw new NotImplementedException(); }\n            }\n\n            string IIdentity.Name\n            {\n                get { throw new NotImplementedException(); }\n            }\n\n            private sealed class MyClaim : IClaim\n            {\n                public string ClaimType { get; set; }\n                public string Value { get; set; }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Helpers/Claims/MockClaimsIdentity.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace System.Web.Helpers.Claims.Test\n{\n    // Convenient class for mocking a ClaimsIdentity instance given some\n    // prefabricated Claim instances.\n    internal sealed class MockClaimsIdentity : ClaimsIdentity\n    {\n        private readonly List<Claim> _claims = new List<Claim>();\n\n        public void AddClaim(string claimType, string value)\n        {\n            _claims.Add(new Claim(claimType, value));\n        }\n\n        public override IEnumerable<Claim> GetClaims()\n        {\n            return _claims;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Helpers/CryptoUtilTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Helpers.Test\n{\n    public class CryptoUtilTest\n    {\n        [Theory]\n        [InlineData(new byte[0], null)]\n        [InlineData(null, new byte[0])]\n        [InlineData(new byte[0], new byte[] { 0x00 })]\n        [InlineData(new byte[] { 0x01, 0x02 }, new byte[] { 0x02, 0x01 })]\n        public void AreByteArraysEqual_False(byte[] a, byte[] b)\n        {\n            // Act\n            bool retVal = CryptoUtil.AreByteArraysEqual(a, b);\n\n            // Assert\n            Assert.NotEqual(a, b);\n        }\n\n        [Fact]\n        public void AreByteArraysEqual_True()\n        {\n            // Arrange\n            byte[] a = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06 };\n            byte[] b = (byte[])a.Clone();\n\n            // Act\n            bool retVal = CryptoUtil.AreByteArraysEqual(a, b);\n\n            // Assert\n            Assert.Equal(a, b);\n        }\n\n        [Fact]\n        public void TestVectors_Empty()\n        {\n            // Act\n            byte[] retVal = CryptoUtil.ComputeSHA256(new string[0]);\n\n            // Assert\n            Assert.Equal(\"47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=\", Convert.ToBase64String(retVal));\n        }\n\n        [Fact]\n        public void TestVectors_NonEmpty()\n        {\n            // Act\n            byte[] retVal = CryptoUtil.ComputeSHA256(new string[] { \"a parameter\", \"another parameter\" });\n\n            // Assert\n            Assert.Equal(\"Bez9yYh4Zq9jK1H5jD21wh04HTZi/vgxp6yDE7Y6cfo=\", Convert.ToBase64String(retVal));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Helpers/UnvalidatedRequestValuesTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing System.Web;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace Microsoft.WebPages.Test.Helpers\n{\n    public class UnvalidatedRequestValuesTest\n    {\n        [Fact]\n        public void Constructor_SetsPropertiesCorrectly()\n        {\n            // Arrange\n            NameValueCollection expectedForm = new NameValueCollection();\n            NameValueCollection expectedQueryString = new NameValueCollection();\n\n            Mock<System.Web.UnvalidatedRequestValuesBase> mockUnvalidatedRequestValue = new Mock<System.Web.UnvalidatedRequestValuesBase>();\n            mockUnvalidatedRequestValue.SetupGet(u => u.Form).Returns(expectedForm);\n            mockUnvalidatedRequestValue.SetupGet(u => u.QueryString).Returns(expectedQueryString);\n\n            Mock<HttpRequestBase> mockRequest = new Mock<HttpRequestBase>();\n            mockRequest.SetupGet(r => r.Unvalidated).Returns(mockUnvalidatedRequestValue.Object);\n\n            // Act\n#pragma warning disable 0618 // Obsolete System.Web.Helpers.UnvalidatedRequestValues\n            System.Web.Helpers.UnvalidatedRequestValues unvalidatedValues = new System.Web.Helpers.UnvalidatedRequestValues(mockRequest.Object);\n#pragma warning restore\n\n            // Assert\n            Assert.Same(expectedForm, unvalidatedValues.Form);\n            Assert.Same(expectedQueryString, unvalidatedValues.QueryString);\n        }\n\n        [Fact]\n        public void Indexer_LooksUpValuesInCorrectOrder()\n        {\n            // Order should be QueryString, Form, Cookies, ServerVariables\n\n            // Arrange\n            NameValueCollection queryString = new NameValueCollection()\n            {\n                { \"foo\", \"fooQueryString\" }\n            };\n\n            NameValueCollection form = new NameValueCollection()\n            {\n                { \"foo\", \"fooInForm\" },\n                { \"bar\", \"barInForm\" },\n            };\n\n            HttpCookieCollection cookies = new HttpCookieCollection()\n            {\n                new HttpCookie(\"foo\", \"fooCookie\"),\n                new HttpCookie(\"bar\", \"barCookie\"),\n                new HttpCookie(\"baz\", \"bazCookie\")\n            };\n\n            NameValueCollection serverVars = new NameValueCollection()\n            {\n                { \"foo\", \"fooServerVars\" },\n                { \"bar\", \"barServerVars\" },\n                { \"baz\", \"bazServerVars\" },\n                { \"quux\", \"quuxServerVars\" },\n            };\n\n            Mock<HttpRequestBase> mockRequest = new Mock<HttpRequestBase>();\n            mockRequest.SetupGet(r => r.ServerVariables).Returns(serverVars);\n            mockRequest.SetupGet(r => r.Form).Returns(form);\n            mockRequest.SetupGet(r => r.QueryString).Returns(queryString);\n            mockRequest.SetupGet(r => r.Cookies).Returns(cookies);\n\n            TestUnvalidatedRequestValues testUnvalidatedRequestValue = new TestUnvalidatedRequestValues(mockRequest.Object);\n\n            mockRequest.SetupGet(r => r.Unvalidated).Returns(testUnvalidatedRequestValue);\n\n#pragma warning disable 0618 // Obsolete System.Web.Helpers.UnvalidatedRequestValues\n            System.Web.Helpers.UnvalidatedRequestValues unvalidatedValues = new System.Web.Helpers.UnvalidatedRequestValues(mockRequest.Object);\n#pragma warning restore\n\n            // Act\n            string fooValue = unvalidatedValues[\"foo\"];\n            string barValue = unvalidatedValues[\"bar\"];\n            string bazValue = unvalidatedValues[\"baz\"];\n            string quuxValue = unvalidatedValues[\"quux\"];\n            string notFoundValue = unvalidatedValues[\"not-found\"];\n\n            // Assert\n            Assert.Equal(\"fooQueryString\", fooValue);\n            Assert.Equal(\"barInForm\", barValue);\n            Assert.Equal(\"bazCookie\", bazValue);\n            Assert.Equal(\"quuxServerVars\", quuxValue);\n            Assert.Null(notFoundValue);\n        }\n\n        private sealed class TestUnvalidatedRequestValues : UnvalidatedRequestValuesBase\n        {\n            HttpRequestBase _request;\n            NameValueCollection _queryString;\n            NameValueCollection _form;\n\n            public TestUnvalidatedRequestValues(HttpRequestBase request)\n            {\n                _request = request;\n            }\n\n            public override HttpCookieCollection Cookies\n            {\n                get\n                {\n                    // HttpCookieCollection copy constructor is not public, so just return it from the request.\n                    return _request.Cookies;\n                }\n            }\n\n            public override NameValueCollection QueryString\n            {\n                get\n                {\n                    if (_queryString == null)\n                    {\n                        _queryString = new NameValueCollection(_request.QueryString);\n                    }\n\n                    return _queryString;\n                }\n            }\n\n            public override NameValueCollection Form\n            {\n                get\n                {\n                    if (_form == null)\n                    {\n                        _form = new NameValueCollection(_request.Form);\n                    }\n\n                    return _form;\n                }\n            }\n\n            public override string this[string key]\n            {\n                // this item getter follows the same logic as UnvalidatedRequestValues.get_Item\n                get\n                {\n                    string queryStringValue = QueryString[key];\n                    if (queryStringValue != null)\n                    {\n                        return queryStringValue;\n                    }\n\n                    string formValue = Form[key];\n                    if (formValue != null)\n                    {\n                        return formValue;\n                    }\n\n                    HttpCookie cookie = Cookies[key];\n                    if (cookie != null)\n                    {\n                        return cookie.Value;\n                    }\n\n                    string serverVarValue = _request.ServerVariables[key];\n                    if (serverVarValue != null)\n                    {\n                        return serverVarValue;\n                    }\n\n                    return null;\n                }\n            }\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.WebPages.Test/Html/CheckBoxTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.WebPages.Html;\nusing System.Web.WebPages.Scope;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")]\n    public class CheckBoxTest : IDisposable\n    {\n        [Fact]\n        public void CheckboxWithEmptyNameThrows()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act and assert\n            Assert.ThrowsArgumentNullOrEmptyString(() => helper.CheckBox(null), \"name\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => helper.CheckBox(String.Empty), \"name\");\n        }\n\n        [Fact]\n        public void CheckboxWithDefaultArguments()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.CheckBox(\"foo\");\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckboxWithObjectAttributes()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.CheckBox(\"foo\", new { attr = \"attr-value\" });\n\n            // Assert\n            Assert.Equal(@\"<input attr=\"\"attr-value\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckboxWithDictionaryAttributes()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.CheckBox(\"foo\", new Dictionary<string, object> { { \"attr\", \"attr-value\" } });\n\n            // Assert\n            Assert.Equal(@\"<input attr=\"\"attr-value\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckboxWithExplicitChecked()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.CheckBox(\"foo\", true);\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckboxWithModelValue()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", true);\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.CheckBox(\"foo\");\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckboxWithNonBooleanModelValue()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", Boolean.TrueString);\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.CheckBox(\"foo\");\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" />\",\n                         html.ToHtmlString());\n\n            modelState.SetModelValue(\"foo\", new object());\n            helper = HtmlHelperFactory.Create(modelState);\n\n            // Act and Assert\n            Assert.Throws<InvalidOperationException>(() => helper.CheckBox(\"foo\"),\n                                                              \"The parameter conversion from type \\\"System.Object\\\" to type \\\"System.Boolean\\\" failed because no \" +\n                                                              \"type converter can convert between these types.\");\n        }\n\n        [Fact]\n        public void CheckboxWithModelAndExplictValue()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", false);\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.CheckBox(\"foo\", true);\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" />\",\n                         html.ToHtmlString());\n\n            modelState.SetModelValue(\"foo\", true);\n\n            // Act\n            html = helper.CheckBox(\"foo\", false);\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckBoxWithCheckedHtmlAttribute()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.CheckBox(\"foo\", new { @checked = \"checked\" });\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckBoxWithExplicitCheckedOverwritesHtmlAttribute()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.CheckBox(\"foo\", false, new { @checked = \"checked\" });\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckBoxWithModelStateCheckedOverwritesHtmlAttribute()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", false);\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.CheckBox(\"foo\", false, new { @checked = \"checked\" });\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckBoxWithError()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", false);\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.CheckBox(\"foo\", true);\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckBoxWithErrorAndCustomCss()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.AddError(\"foo\", \"error\");\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.CheckBox(\"foo\", true, new { @class = \"my-class\" });\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" class=\"\"input-validation-error my-class\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckBoxUsesCustomErrorClass()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.AddError(\"foo\", \"error\");\n            HtmlHelper.ValidationInputCssClassName = \"my-error-class\";\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.CheckBox(\"foo\", true, new { @class = \"my-class\" });\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" class=\"\"my-error-class my-class\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"checkbox\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckBoxOverwritesImplicitAttributes()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.CheckBox(\"foo\", true, new { type = \"fooType\", name = \"bar\" });\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"fooType\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void CheckboxAddsUnobtrusiveValidationAttributes()\n        {\n            // Arrange\n            const string fieldName = \"name\";\n            var modelStateDictionary = new ModelStateDictionary();\n            var validationHelper = new ValidationHelper(new Mock<HttpContextBase>().Object, modelStateDictionary);\n            HtmlHelper helper = HtmlHelperFactory.Create(modelStateDictionary, validationHelper);\n\n            // Act\n            validationHelper.RequireField(fieldName, \"Please specify a valid Name.\");\n            validationHelper.Add(fieldName, Validator.StringLength(30, errorMessage: \"Name cannot exceed {0} characters\"));\n            var html = helper.CheckBox(fieldName, new Dictionary<string, object> { { \"data-some-val\", \"5\" } });\n\n            // Assert\n            Assert.Equal(@\"<input data-some-val=\"\"5\"\" data-val=\"\"true\"\" data-val-length=\"\"Name cannot exceed 30 characters\"\" data-val-length-max=\"\"30\"\" data-val-required=\"\"Please specify a valid Name.\"\" id=\"\"name\"\" name=\"\"name\"\" type=\"\"checkbox\"\" />\",\n                         html.ToString());\n        }\n\n        [Fact]\n        public void CheckboxWithAttributesFromAnonymousObject_WithUnderscoreInName_TransformsUnderscoresToDashs()\n        {\n            HtmlHelperTest.AssertHelperTransformsAttributesUnderscoresToDashs((helper, attributes) =>\n                helper.CheckBox(\"foo\", attributes));\n\n            HtmlHelperTest.AssertHelperTransformsAttributesUnderscoresToDashs((helper, attributes) =>\n                helper.CheckBox(\"foo\", true, attributes));\n        }\n\n        public void Dispose()\n        {\n            // Reset ScopeStorage (written via e.g. HtmlHelper.ValidationInputCssClassName) between tests to avoid unexpected interactions.\n            ScopeStorage.CurrentProvider = new StaticScopeStorageProvider();\n            ScopeStorage.GlobalScope.Clear();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Html/HtmlHelperFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.WebPages.Html;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public static class HtmlHelperFactory\n    {\n        internal static HtmlHelper Create(ModelStateDictionary modelStateDictionary = null, ValidationHelper validationHelper = null)\n        {\n            modelStateDictionary = modelStateDictionary ?? new ModelStateDictionary();\n            var httpContext = new Mock<HttpContextBase>();\n            validationHelper = validationHelper ?? new ValidationHelper(httpContext.Object, modelStateDictionary);\n            return new HtmlHelper(modelStateDictionary, validationHelper);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Html/HtmlHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Routing;\nusing System.Web.WebPages.Html;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Test\n{\n    public class HtmlHelperTest\n    {\n        [Fact]\n        public void ValidationInputCssClassNameThrowsWhenAssignedNull()\n        {\n            // Act and Assert\n            Assert.ThrowsArgumentNull(() => HtmlHelper.ValidationInputCssClassName = null, \"value\");\n        }\n\n        [Fact]\n        public void ValidationSummaryClassNameThrowsWhenAssignedNull()\n        {\n            // Act and Assert\n            Assert.ThrowsArgumentNull(() => HtmlHelper.ValidationSummaryClass = null, \"value\");\n        }\n\n        [Fact]\n        public void EncodeObject()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create();\n            object text = \"<br />\" as object;\n\n            // Act\n            string encodedHtml = htmlHelper.Encode(text);\n\n            // Assert\n            Assert.Equal(\"&lt;br /&gt;\", encodedHtml);\n        }\n\n        [Fact]\n        public void EncodeObjectNull()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create();\n            object text = null;\n\n            // Act\n            string encodedHtml = htmlHelper.Encode(text);\n\n            // Assert\n            Assert.Equal(String.Empty, encodedHtml);\n        }\n\n        [Fact]\n        public void EncodeString()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create();\n            var text = \"<br />\";\n\n            // Act\n            string encodedHtml = htmlHelper.Encode(text);\n\n            // Assert\n            Assert.Equal(\"&lt;br /&gt;\", encodedHtml);\n        }\n\n        [Fact]\n        public void EncodeStringNull()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create();\n            string text = null;\n\n            // Act\n            string encodedHtml = htmlHelper.Encode(text);\n\n            // Assert\n            Assert.Equal(\"\", encodedHtml);\n        }\n\n        [Fact]\n        public void RawAllowsNullValue()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create();\n\n            // Act\n            IHtmlString markupHtml = htmlHelper.Raw(null);\n\n            // Assert\n            Assert.Null(markupHtml.ToString());\n            Assert.Null(markupHtml.ToHtmlString());\n        }\n\n        [Fact]\n        public void RawAllowsNullObjectValue()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create();\n\n            // Act\n            IHtmlString markupHtml = htmlHelper.Raw((object)null);\n\n            // Assert\n            Assert.Null(markupHtml.ToString());\n            Assert.Null(markupHtml.ToHtmlString());\n        }\n\n        [Fact]\n        public void RawAllowsEmptyValue()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create();\n\n            // Act\n            IHtmlString markupHtml = htmlHelper.Raw(\"\");\n\n            // Assert\n            Assert.Equal(\"\", markupHtml.ToString());\n            Assert.Equal(\"\", markupHtml.ToHtmlString());\n        }\n\n        [Fact]\n        public void RawReturnsWrapperMarkup()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create();\n            string markup = \"<b>bold</b>\";\n\n            // Act\n            IHtmlString markupHtml = htmlHelper.Raw(markup);\n\n            // Assert\n            Assert.Equal(\"<b>bold</b>\", markupHtml.ToString());\n            Assert.Equal(\"<b>bold</b>\", markupHtml.ToHtmlString());\n        }\n\n        [Fact]\n        public void RawReturnsWrapperMarkupOfObject()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create();\n            ObjectWithWrapperMarkup obj = new ObjectWithWrapperMarkup();\n\n            // Act\n            IHtmlString markupHtml = htmlHelper.Raw(obj);\n\n            // Assert\n            Assert.Equal(\"<b>boldFromObject</b>\", markupHtml.ToString());\n            Assert.Equal(\"<b>boldFromObject</b>\", markupHtml.ToHtmlString());\n        }\n\n        [Fact]\n        public void ConvertsUnderscoresInNamesToDashes()\n        {\n            // Arrange\n            var attributes = GetAttributes();\n\n            // Act\n            RouteValueDictionary result = HtmlHelper.AnonymousObjectToHtmlAttributes(attributes);\n\n            // Assert\n            Assert.Equal(7, result.Count);\n            Assert.Equal(\"Bar\", result[\"foo\"]);\n            Assert.Equal(\"pow_wow\", result[\"baz-bif\"]);\n        }\n\n        [Fact]\n        public void ObjectToDictionaryWithAnonymousTypeLooksUpProperties()\n        {\n            // Arrange\n            object obj = new { _test = \"value\", oth_er = 1 };\n\n            // Act\n            IDictionary<string, object> dictValues = HtmlHelper.ObjectToDictionary(obj);\n\n            // Assert\n            Assert.NotNull(dictValues);\n            Assert.Equal(2, dictValues.Count);\n            Assert.Equal(\"value\", dictValues[\"_test\"]);\n            Assert.Equal(1, dictValues[\"oth_er\"]);\n        }\n\n        private static object GetAttributes()\n        {\n            return new { foo = \"Bar\",\n                         baz_bif = \"pow_wow\",\n                         other1 = \"xx\",\n                         other2 = \"yy\",\n                         other3 = \"zz\",\n                         other4 = \"aa\",\n                         other5 = \"bb\",\n                       };\n        }\n\n        /// <summary>\n        /// Will invoke a helper with overload that accepts custom attribute with a name containing\n        /// and underscore as an anonymous object, and will then assert that the resulted html\n        /// has the attribute name underscore correctly transformed to a dash\n        /// </summary>\n        /// <param name=\"helperInvocation\"></param>\n        internal static void AssertHelperTransformsAttributesUnderscoresToDashs(Func<HtmlHelper, object, IHtmlString> helperInvocation)\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n            const string expected = @\"data-name=\"\"value\"\"\";\n            const string unexpected = @\"data_name=\"\"value\"\"\";\n            var attributes = new { data_name = \"value\" };\n\n            // Act\n            var htmlString = helperInvocation(helper, attributes).ToHtmlString();\n\n            // Assert\n            Assert.DoesNotContain(unexpected, htmlString);\n            Assert.Contains(expected, htmlString);\n        }\n\n        private class ObjectWithWrapperMarkup\n        {\n            public override string ToString()\n            {\n                return \"<b>boldFromObject</b>\";\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Html/InputHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Data.Linq;\nusing System.Web.WebPages.Html;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class InputHelperTest\n    {\n        private static readonly IDictionary<string, object> _attributesDictionary = new Dictionary<string, object> { { \"baz\", \"BazValue\" } };\n        private static readonly object _attributesObject = new { baz = \"BazValue\" };\n\n        [Fact]\n        public void HiddenWithBinaryArrayValueRendersBase64EncodedValue()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var result = helper.Hidden(\"ProductName\", new Binary(new byte[] { 23, 43, 53 }));\n\n            // Assert\n            Assert.Equal(\"<input id=\\\"ProductName\\\" name=\\\"ProductName\\\" type=\\\"hidden\\\" value=\\\"Fys1\\\" />\", result.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenWithEmptyNameThrows()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmptyString(() => helper.Hidden(String.Empty), \"name\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => helper.Hidden(null), \"name\");\n        }\n\n        [Fact]\n        public void HiddenWithExplicitValue()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.Hidden(\"foo\", \"DefaultFoo\");\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"DefaultFoo\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenWithExplicitValueAndAttributesDictionary()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.Hidden(\"foo\", \"DefaultFoo\", new Dictionary<string, object> { { \"attr\", \"attr-val\" } });\n\n            // Assert\n            Assert.Equal(@\"<input attr=\"\"attr-val\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"DefaultFoo\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenWithExplicitValueAndObjectDictionary()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.Hidden(\"foo\", \"DefaultFoo\", new { attr = \"attr-val\" });\n\n            // Assert\n            Assert.Equal(@\"<input attr=\"\"attr-val\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"DefaultFoo\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenWithExplicitValueNull()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.Hidden(\"foo\", value: null);\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenWithModelValue()\n        {\n            // Arrange\n            var model = new ModelStateDictionary();\n            model.SetModelValue(\"foo\", \"bar\");\n            HtmlHelper helper = HtmlHelperFactory.Create(model);\n\n            // Act\n            var html = helper.Hidden(\"foo\");\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"bar\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenWithModelValueAndAttributesDictionary()\n        {\n            // Arrange\n            var model = new ModelStateDictionary();\n            model.SetModelValue(\"foo\", \"bar\");\n            HtmlHelper helper = HtmlHelperFactory.Create(model);\n\n            // Act\n            var html = helper.Hidden(\"foo\", null, new Dictionary<string, object> { { \"attr\", \"attr-val\" } });\n\n            // Assert\n            Assert.Equal(@\"<input attr=\"\"attr-val\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"bar\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenWithImplicitValueAndAttributesObject()\n        {\n            // Arrange\n            var model = new ModelStateDictionary();\n            model.SetModelValue(\"foo\", \"bar\");\n            HtmlHelper helper = HtmlHelperFactory.Create(model);\n\n            // Act\n            var html = helper.Hidden(\"foo\", null, new { attr = \"attr-val\" });\n\n            // Assert\n            Assert.Equal(@\"<input attr=\"\"attr-val\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"bar\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenWithNameAndValue()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.Hidden(\"foo\", \"fooValue\");\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"fooValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenWithExplicitOverwritesAttributeValue()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.Hidden(\"foo\", \"fooValue\", new { value = \"barValue\" });\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"fooValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenWithModelValueOverwritesAttributeValue()\n        {\n            // Arrange\n            var model = new ModelStateDictionary();\n            model.SetModelValue(\"foo\", \"fooValue\");\n            HtmlHelper helper = HtmlHelperFactory.Create(model);\n\n            // Act\n            var html = helper.Hidden(\"foo\", null, new { value = \"barValue\" });\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"hidden\"\" value=\"\"fooValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void HiddenAddsUnobtrusiveValidationAttributes()\n        {\n            // Arrange\n            const string fieldName = \"name\";\n            var modelStateDictionary = new ModelStateDictionary();\n            var validationHelper = new ValidationHelper(new Mock<HttpContextBase>().Object, modelStateDictionary);\n            HtmlHelper helper = HtmlHelperFactory.Create(modelStateDictionary, validationHelper);\n\n            // Act\n            validationHelper.RequireField(fieldName, \"Please specify a valid Name.\");\n            validationHelper.Add(fieldName, Validator.StringLength(30, errorMessage: \"Name cannot exceed {0} characters\"));\n            var html = helper.Hidden(fieldName, value: null, htmlAttributes: new Dictionary<string, object> { { \"data-some-val\", \"5\" } });\n\n            // Assert\n            Assert.Equal(@\"<input data-some-val=\"\"5\"\" data-val=\"\"true\"\" data-val-length=\"\"Name cannot exceed 30 characters\"\" data-val-length-max=\"\"30\"\" data-val-required=\"\"Please specify a valid Name.\"\" id=\"\"name\"\" name=\"\"name\"\" type=\"\"hidden\"\" value=\"\"\"\" />\",\n                         html.ToString());\n        }\n\n        // Password\n\n        [Fact]\n        public void PasswordWithEmptyNameThrows()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmptyString(() => helper.Password(String.Empty), \"name\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => helper.Password(null), \"name\");\n        }\n\n        [Fact]\n        public void PasswordDictionaryOverridesImplicitParameters()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.Password(\"foo\", \"Some Value\", new { type = \"fooType\" });\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"fooType\"\" value=\"\"Some Value\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordExplicitParametersOverrideDictionary()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.Password(\"foo\", \"Some Value\", new { value = \"Another Value\", name = \"bar\" });\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" value=\"\"Some Value\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordWithExplicitValue()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.Password(\"foo\", \"DefaultFoo\", (object)null);\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" value=\"\"DefaultFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordWithExplicitValueAndAttributesDictionary()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.Password(\"foo\", \"DefaultFoo\", new { baz = \"BazValue\" });\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" value=\"\"DefaultFoo\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordWithExplicitValueAndAttributesObject()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.Password(\"foo\", \"DefaultFoo\", new Dictionary<string, object> { { \"baz\", \"BazValue\" } });\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" value=\"\"DefaultFoo\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordWithExplicitValueNull()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.Password(\"foo\", value: (string)null);\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordWithImplicitValue()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.Password(\"foo\");\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordWithImplicitValueAndAttributesDictionary()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.Password(\"foo\", null, _attributesDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordWithImplicitValueAndAttributesDictionaryReturnsEmptyValueIfNotFound()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.Password(\"keyNotFound\", null, _attributesDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"keyNotFound\"\" name=\"\"keyNotFound\"\" type=\"\"password\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordWithImplicitValueAndAttributesObject()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.Password(\"foo\", null, _attributesObject);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordWithNameAndValue()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.Password(\"foo\", \"fooValue\");\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"password\"\" value=\"\"fooValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void PasswordWithNullNameThrows()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmptyString(() => helper.Password(null), \"name\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => helper.Password(String.Empty), \"name\");\n        }\n\n        [Fact]\n        public void PasswordAddsUnobtrusiveValidationAttributes()\n        {\n            // Arrange\n            const string fieldName = \"name\";\n            var modelStateDictionary = new ModelStateDictionary();\n            var validationHelper = new ValidationHelper(new Mock<HttpContextBase>().Object, modelStateDictionary);\n            HtmlHelper helper = HtmlHelperFactory.Create(modelStateDictionary, validationHelper);\n\n            // Act\n            validationHelper.RequireField(fieldName, \"Please specify a valid Name.\");\n            validationHelper.Add(fieldName, Validator.StringLength(30, errorMessage: \"Name cannot exceed {0} characters\"));\n            var html = helper.Password(fieldName, value: null, htmlAttributes: new Dictionary<string, object> { { \"data-some-val\", \"5\" } });\n\n            // Assert\n            Assert.Equal(@\"<input data-some-val=\"\"5\"\" data-val=\"\"true\"\" data-val-length=\"\"Name cannot exceed 30 characters\"\" data-val-length-max=\"\"30\"\" data-val-required=\"\"Please specify a valid Name.\"\" id=\"\"name\"\" name=\"\"name\"\" type=\"\"password\"\" />\",\n                         html.ToString());\n        }\n\n        //Input \n        [Fact]\n        public void TextBoxDictionaryOverridesImplicitValues()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.TextBox(\"foo\", \"DefaultFoo\", new { type = \"fooType\" });\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"fooType\"\" value=\"\"DefaultFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxExplicitParametersOverrideDictionaryValues()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.TextBox(\"foo\", \"DefaultFoo\", new { value = \"Some other value\" });\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"DefaultFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxWithDotReplacementForId()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.TextBox(\"foo.bar.baz\", null);\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo_bar_baz\"\" name=\"\"foo.bar.baz\"\" type=\"\"text\"\" value=\"\"\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxWithEmptyNameThrows()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmptyString(() => helper.TextBox(null), \"name\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => helper.TextBox(String.Empty), \"name\");\n        }\n\n        [Fact]\n        public void TextBoxWithExplicitValue()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.TextBox(\"foo\", \"DefaultFoo\", (object)null);\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"DefaultFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxWithExplicitValueAndAttributesDictionary()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.TextBox(\"foo\", \"DefaultFoo\", _attributesDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"DefaultFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxWithExplicitValueAndAttributesObject()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.TextBox(\"foo\", \"DefaultFoo\", _attributesObject);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"DefaultFoo\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxWithExplicitValueNull()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", \"fooModelValue\");\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.TextBox(\"foo\", (string)null /* value */, (object)null);\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"fooModelValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxWithImplicitValue()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", \"fooModelValue\");\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.TextBox(\"foo\");\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"fooModelValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxWithImplicitValueAndAttributesDictionary()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", \"fooModelValue\");\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.TextBox(\"foo\", null, _attributesDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"fooModelValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxWithImplicitValueAndAttributesDictionaryReturnsEmptyValueIfNotFound()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", \"fooModelValue\");\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.TextBox(\"keyNotFound\", null, _attributesDictionary);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"keyNotFound\"\" name=\"\"keyNotFound\"\" type=\"\"text\"\" value=\"\"\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxWithImplicitValueAndAttributesObject()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", \"fooModelValue\");\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.TextBox(\"foo\", null, _attributesObject);\n\n            // Assert\n            Assert.Equal(@\"<input baz=\"\"BazValue\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"fooModelValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxWithNameAndValue()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.TextBox(\"foo\", \"fooValue\");\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"text\"\" value=\"\"fooValue\"\" />\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextBoxAddsUnobtrusiveValidationAttributes()\n        {\n            // Arrange\n            const string fieldName = \"name\";\n            var modelStateDictionary = new ModelStateDictionary();\n            var validationHelper = new ValidationHelper(new Mock<HttpContextBase>().Object, modelStateDictionary);\n            HtmlHelper helper = HtmlHelperFactory.Create(modelStateDictionary, validationHelper);\n\n            // Act\n            validationHelper.RequireField(fieldName, \"Please specify a valid Name.\");\n            validationHelper.Add(fieldName, Validator.StringLength(30, errorMessage: \"Name cannot exceed {0} characters\"));\n            var html = helper.TextBox(fieldName, value: null, htmlAttributes: new Dictionary<string, object> { { \"data-some-val\", \"5\" } });\n\n            // Assert\n            Assert.Equal(@\"<input data-some-val=\"\"5\"\" data-val=\"\"true\"\" data-val-length=\"\"Name cannot exceed 30 characters\"\" data-val-length-max=\"\"30\"\" data-val-required=\"\"Please specify a valid Name.\"\" id=\"\"name\"\" name=\"\"name\"\" type=\"\"text\"\" value=\"\"\"\" />\",\n                         html.ToString());\n        }\n\n        [Fact]\n        public void TextBoxWithAttributesFromAnonymousObject_WithUnderscoreInName_TransformsUnderscoresToDashs()\n        {\n            HtmlHelperTest.AssertHelperTransformsAttributesUnderscoresToDashs((helper, attributes) =>\n                helper.TextBox(\"foo\", \"value\", attributes));\n        }\n\n        [Fact]\n        public void HiddenTextBoxWithAttributesFromAnonymousObject_WithUnderscoreInName_TransformsUnderscoresToDashs()\n        {\n            HtmlHelperTest.AssertHelperTransformsAttributesUnderscoresToDashs((helper, attributes) =>\n                helper.Hidden(\"foo\", \"value\", attributes));\n        }\n\n        [Fact]\n        public void PasswordTextBoxWithAttributesFromAnonymousObject_WithUnderscoreInName_TransformsUnderscoresToDashs()\n        {\n            HtmlHelperTest.AssertHelperTransformsAttributesUnderscoresToDashs((helper, attributes) =>\n                helper.Password(\"foo\", \"value\", attributes));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Html/LabelHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Test\n{\n    public class LabelHelperTest\n    {\n        [Fact]\n        public void LabelWithAttributesFromAnonymousObject_WithUnderscoreInName_TransformsUnderscoresToDashs()\n        {\n            HtmlHelperTest.AssertHelperTransformsAttributesUnderscoresToDashs((helper, attributes) =>\n                helper.Label(\"foo\", attributes));\n\n            HtmlHelperTest.AssertHelperTransformsAttributesUnderscoresToDashs((helper, attributes) =>\n                helper.Label(\"foo\", \"bar\", attributes));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Html/RadioButtonTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.WebPages.Html;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class RadioButtonTest\n    {\n        [Fact]\n        public void RadioButtonWithEmptyNameThrows()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act and assert\n            Assert.ThrowsArgumentNullOrEmptyString(() => helper.RadioButton(null, null), \"name\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => helper.RadioButton(String.Empty, null), \"name\");\n        }\n\n        [Fact]\n        public void RadioButtonWithDefaultArguments()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.RadioButton(\"foo\", \"bar\", true);\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"bar\"\" />\",\n                         html.ToHtmlString());\n\n            html = helper.RadioButton(\"foo\", \"bar\", false);\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"bar\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonWithObjectAttributes()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.RadioButton(\"foo\", \"bar\", new { attr = \"attr-value\" });\n\n            // Assert\n            Assert.Equal(@\"<input attr=\"\"attr-value\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"bar\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonWithDictionaryAttributes()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.RadioButton(\"foo\", \"bar\", new Dictionary<string, object> { { \"attr\", \"attr-value\" } });\n\n            // Assert\n            Assert.Equal(@\"<input attr=\"\"attr-value\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"bar\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonUsesModelStateToAssignChecked()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", \"bar\");\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.RadioButton(\"foo\", \"bar\");\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"bar\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonUsesModelStateToRemoveChecked()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", \"not-a-bar\");\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.RadioButton(\"foo\", \"bar\", new { @checked = \"checked\" });\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"bar\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonWithoutModelStateDoesNotAffectChecked()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.RadioButton(\"foo\", \"bar\", new { @checked = \"checked\" });\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"bar\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonWithNonStringModelValue()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", new List<double>());\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.RadioButton(\"foo\", \"bar\");\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"bar\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonWithNonStringValue()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", \"bar\");\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.RadioButton(\"foo\", 2.53);\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"2.53\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonWithExplicitChecked()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", \"bar\");\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.RadioButton(\"foo\", \"not-bar\", true);\n\n            // Assert\n            Assert.Equal(@\"<input checked=\"\"checked\"\" id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"radio\"\" value=\"\"not-bar\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonOverwritesImplicitAttributes()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.RadioButton(\"foo\", \"foo-value\", new { value = \"bazValue\", type = \"fooType\", name = \"bar\" });\n\n            // Assert\n            Assert.Equal(@\"<input id=\"\"foo\"\" name=\"\"foo\"\" type=\"\"fooType\"\" value=\"\"foo-value\"\" />\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void RadioButtonAddsUnobtrusiveValidationAttributes()\n        {\n            // Arrange\n            const string fieldName = \"name\";\n            var modelStateDictionary = new ModelStateDictionary();\n            var validationHelper = new ValidationHelper(new Mock<HttpContextBase>().Object, modelStateDictionary);\n            HtmlHelper helper = HtmlHelperFactory.Create(modelStateDictionary, validationHelper);\n\n            // Act\n            validationHelper.RequireField(fieldName, \"Please specify a valid Name.\");\n            validationHelper.Add(fieldName, Validator.StringLength(30, errorMessage: \"Name cannot exceed {0} characters\"));\n            var html = helper.RadioButton(fieldName, value: 8, htmlAttributes: new Dictionary<string, object> { { \"data-some-val\", \"5\" } });\n\n            // Assert\n            Assert.Equal(@\"<input data-some-val=\"\"5\"\" data-val=\"\"true\"\" data-val-length=\"\"Name cannot exceed 30 characters\"\" data-val-length-max=\"\"30\"\" data-val-required=\"\"Please specify a valid Name.\"\" id=\"\"name\"\" name=\"\"name\"\" type=\"\"radio\"\" value=\"\"8\"\" />\",\n                         html.ToString());\n        }\n\n        [Fact]\n        public void RadioButtonWithAttributesFromAnonymousObject_WithUnderscoreInName_TransformsUnderscoresToDashs()\n        {\n            HtmlHelperTest.AssertHelperTransformsAttributesUnderscoresToDashs((helper, attributes) =>\n                helper.RadioButton(\"foo\", true, attributes));\n\n            HtmlHelperTest.AssertHelperTransformsAttributesUnderscoresToDashs((helper, attributes) =>\n                helper.RadioButton(\"foo\", true, true, attributes));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Html/SelectHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web.WebPages.Html;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class SelectExtensionsTest\n    {\n        [Fact]\n        public void DropDownListThrowsWithNoName()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act and assert\n            Assert.ThrowsArgumentNullOrEmptyString(() => helper.DropDownList(name: null, selectList: null), \"name\");\n        }\n\n        [Fact]\n        public void DropDownListWithNoSelectedItem()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.DropDownList(\"foo\", GetSelectList());\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListWithDefaultOption()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.DropDownList(\"foo\", \"select-one\", GetSelectList());\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"<option value=\\\"\\\">select-one</option>\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListWithAttributes()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.DropDownList(\"foo\", GetSelectList(), new { attr = \"attr-val\", attr2 = \"attr-val2\" });\n\n            // Assert\n            Assert.Equal(\n                \"<select attr=\\\"attr-val\\\" attr2=\\\"attr-val2\\\" id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListWithExplicitValue()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.DropDownList(\"foo\", null, GetSelectList(), \"B\", new Dictionary<string, object> { { \"attr\", \"attr-val\" } });\n\n            // Assert\n            Assert.Equal(\n                \"<select attr=\\\"attr-val\\\" id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownWithModelValue()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", \"C\");\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.DropDownList(\"foo\", GetSelectList(), new { attr = \"attr-val\" });\n\n            // Assert\n            Assert.Equal(\n                \"<select attr=\\\"attr-val\\\" id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownWithExplictAndModelValue()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", \"C\");\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.DropDownList(\"foo\", null, GetSelectList(), \"B\", new { attr = \"attr-val\" });\n\n            // Assert\n            Assert.Equal(\n                \"<select attr=\\\"attr-val\\\" id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownWithNonStringModelValue()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", 23);\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.DropDownList(\"foo\", null, GetSelectList(), new { attr = \"attr-val\" });\n\n            // Assert\n            Assert.Equal(\n                \"<select attr=\\\"attr-val\\\" id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownWithNonStringExplicitValue()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.DropDownList(\"foo\", null, GetSelectList(), new List<int>(), new { attr = \"attr-val\" });\n\n            // Assert\n            Assert.Equal(\n                \"<select attr=\\\"attr-val\\\" id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownWithErrors()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.AddError(\"foo\", \"some error\");\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.DropDownList(\"foo\", GetSelectList());\n\n            // Assert\n            Assert.Equal(\n                \"<select class=\\\"input-validation-error\\\" id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListWithErrorsAndCustomClass()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.AddError(\"foo\", \"some error\");\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.DropDownList(\"foo\", GetSelectList(), new { @class = \"my-class\" });\n\n            // Assert\n            Assert.Equal(\n                \"<select class=\\\"input-validation-error my-class\\\" id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListWithEmptyOptionLabel()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.AddError(\"foo\", \"some error\");\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.DropDownList(\"foo\", GetSelectList(), new { @class = \"my-class\" });\n\n            // Assert\n            Assert.Equal(\n                \"<select class=\\\"input-validation-error my-class\\\" id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListWithObjectDictionaryAndTitle()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.DropDownList(\"foo\", \"Select One\", GetSelectList(), new { @class = \"my-class\" });\n\n            // Assert\n            Assert.Equal(\n                \"<select class=\\\"my-class\\\" id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"<option value=\\\"\\\">Select One</option>\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownListWithDotReplacementForId()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.DropDownList(\"foo.bar\", \"Select One\", GetSelectList());\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo_bar\\\" name=\\\"foo.bar\\\">\" + Environment.NewLine\n              + \"<option value=\\\"\\\">Select One</option>\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void DropDownAddsUnobtrusiveValidationAttributes()\n        {\n            // Arrange\n            const string fieldName = \"name\";\n            var modelStateDictionary = new ModelStateDictionary();\n            var validationHelper = new ValidationHelper(new Mock<HttpContextBase>().Object, modelStateDictionary);\n            HtmlHelper helper = HtmlHelperFactory.Create(modelStateDictionary, validationHelper);\n\n            // Act\n            validationHelper.RequireField(fieldName, \"Please specify a valid Name.\");\n            validationHelper.Add(fieldName, Validator.StringLength(30, errorMessage: \"Name cannot exceed {0} characters\"));\n            var html = helper.DropDownList(fieldName, GetSelectList(), htmlAttributes: new Dictionary<string, object> { { \"data-some-val\", \"5\" } });\n\n            // Assert\n            Assert.Equal(\n                \"<select data-some-val=\\\"5\\\" data-val=\\\"true\\\" data-val-length=\\\"Name cannot exceed 30 characters\\\" data-val-length-max=\\\"30\\\" data-val-required=\\\"Please specify a valid Name.\\\" id=\\\"name\\\" name=\\\"name\\\">\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToString());\n        }\n\n        [Fact]\n        public void DropDownWithAttributesFromAnonymousObject_WithUnderscoreInName_TransformsUnderscoresToDashs()\n        {\n            HtmlHelperTest.AssertHelperTransformsAttributesUnderscoresToDashs((helper, attributes) =>\n                helper.DropDownList(\"foo\", GetSelectList(), attributes));\n\n            HtmlHelperTest.AssertHelperTransformsAttributesUnderscoresToDashs((helper, attributes) =>\n                helper.DropDownList(\"foo\", \"val\", GetSelectList(), attributes));\n\n            HtmlHelperTest.AssertHelperTransformsAttributesUnderscoresToDashs((helper, attributes) =>\n                helper.DropDownList(\"foo\", \"val\", GetSelectList(), \"val\", attributes));\n        }\n\n        // ListBox\n\n        [Fact]\n        public void ListBoxThrowsWithNoName()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act and assert\n            Assert.ThrowsArgumentNullOrEmptyString(() => helper.ListBox(name: null, selectList: null), \"name\");\n        }\n\n        [Fact]\n        public void ListBoxWithNoSelectedItem()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.ListBox(\"foo\", GetSelectList());\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithDefaultOption()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.ListBox(\"foo\", \"select-one\", GetSelectList());\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"<option value=\\\"\\\">select-one</option>\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithAttributes()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.ListBox(\"foo\", GetSelectList(), new { attr = \"attr-val\", attr2 = \"attr-val2\" });\n\n            // Assert\n            Assert.Equal(\n                \"<select attr=\\\"attr-val\\\" attr2=\\\"attr-val2\\\" id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithExplicitValue()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.ListBox(\"foo\", null, GetSelectList(), \"B\", new Dictionary<string, object> { { \"attr\", \"attr-val\" } });\n\n            // Assert\n            Assert.Equal(\n                \"<select attr=\\\"attr-val\\\" id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithModelValue()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", \"C\");\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.ListBox(\"foo\", GetSelectList(), new { attr = \"attr-val\" });\n\n            // Assert\n            Assert.Equal(\n                \"<select attr=\\\"attr-val\\\" id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithExplicitMultipleValuesAndNoMultiple()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.ListBox(\"foo\", null, GetSelectList(), new[] { \"B\", \"C\" }, new Dictionary<string, object> { { \"attr\", \"attr-val\" } });\n\n            // Assert\n            Assert.Equal(\n                \"<select attr=\\\"attr-val\\\" id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithExplicitMultipleValuesAndMultiple()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.ListBox(\"foo\", null, GetSelectList(), new[] { \"B\", \"C\" }, 4, true);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\" size=\\\"4\\\">\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithMultipleModelValue()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", new[] { \"A\", \"C\" });\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.ListBox(\"foo\", GetSelectList(), new { attr = \"attr-val\" });\n\n            // Assert\n            Assert.Equal(\n                \"<select attr=\\\"attr-val\\\" id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithModelValueAndExplicitSelectItem()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", new[] { \"C\", \"D\" });\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n            var selectList = GetSelectList().ToList();\n            selectList[1].Selected = true;\n\n            // Act\n            var html = helper.ListBox(\"foo\", selectList, new { attr = \"attr-val\" });\n\n            // Assert\n            Assert.Equal(\n                \"<select attr=\\\"attr-val\\\" id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithMultiSelectAndMultipleModelValue()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", new[] { \"A\", \"C\" });\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.ListBox(\"foo\", GetSelectList(), null, 4, true);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\" size=\\\"4\\\">\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithMultiSelectAndMultipleExplicitValues()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.ListBox(\"foo\", GetSelectList(), new[] { \"A\", \"C\" }, 4, true);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\" size=\\\"4\\\">\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithMultiSelectAndExplitSelectValue()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n            var selectList = GetSelectList().ToList();\n            selectList.First().Selected = selectList.Last().Selected = true;\n\n            // Act\n            var html = helper.ListBox(\"foo\", selectList, new[] { \"B\" }, 4, true);\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo\\\" multiple=\\\"multiple\\\" name=\\\"foo\\\" size=\\\"4\\\">\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithExplictAndModelValue()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", \"C\");\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.ListBox(\"foo\", defaultOption: null, selectList: GetSelectList(),\n                                      selectedValues: \"B\", htmlAttributes: new { attr = \"attr-val\" });\n\n            // Assert\n            Assert.Equal(\n                \"<select attr=\\\"attr-val\\\" id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option selected=\\\"selected\\\" value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithErrorAndExplictAndModelState()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", \"C\");\n            modelState.AddError(\"foo\", \"test\");\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.ListBox(\"foo.bar\", \"Select One\", GetSelectList());\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo_bar\\\" name=\\\"foo.bar\\\">\" + Environment.NewLine\n              + \"<option value=\\\"\\\">Select One</option>\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithNonStringModelValue()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", 23);\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.ListBox(\"foo\", null, GetSelectList(), new { attr = \"attr-val\" });\n\n            // Assert\n            Assert.Equal(\n                \"<select attr=\\\"attr-val\\\" id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithNonStringExplicitValue()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.ListBox(\"foo\", null, GetSelectList(), new List<int>(), new { attr = \"attr-val\" });\n\n            // Assert\n            Assert.Equal(\n                \"<select attr=\\\"attr-val\\\" id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithErrors()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.AddError(\"foo\", \"some error\");\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.ListBox(\"foo\", GetSelectList());\n\n            // Assert\n            Assert.Equal(\n                \"<select class=\\\"input-validation-error\\\" id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithErrorsAndCustomClass()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.AddError(\"foo\", \"some error\");\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.ListBox(\"foo\", GetSelectList(), new { @class = \"my-class\" });\n\n            // Assert\n            Assert.Equal(\n                \"<select class=\\\"input-validation-error my-class\\\" id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithEmptyOptionLabel()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.AddError(\"foo\", \"some error\");\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.ListBox(\"foo\", GetSelectList(), new { @class = \"my-class\" });\n\n            // Assert\n            Assert.Equal(\n                \"<select class=\\\"input-validation-error my-class\\\" id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithObjectDictionaryAndTitle()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.ListBox(\"foo\", \"Select One\", GetSelectList(), new { @class = \"my-class\" });\n\n            // Assert\n            Assert.Equal(\n                \"<select class=\\\"my-class\\\" id=\\\"foo\\\" name=\\\"foo\\\">\" + Environment.NewLine\n              + \"<option value=\\\"\\\">Select One</option>\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxWithDotReplacementForId()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.ListBox(\"foo.bar\", \"Select One\", GetSelectList());\n\n            // Assert\n            Assert.Equal(\n                \"<select id=\\\"foo_bar\\\" name=\\\"foo.bar\\\">\" + Environment.NewLine\n              + \"<option value=\\\"\\\">Select One</option>\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ListBoxAddsUnobtrusiveValidationAttributes()\n        {\n            // Arrange\n            const string fieldName = \"name\";\n            var modelStateDictionary = new ModelStateDictionary();\n            var validationHelper = new ValidationHelper(new Mock<HttpContextBase>().Object, modelStateDictionary);\n            HtmlHelper helper = HtmlHelperFactory.Create(modelStateDictionary, validationHelper);\n\n            // Act\n            validationHelper.RequireField(fieldName, \"Please specify a valid Name.\");\n            validationHelper.Add(fieldName, Validator.StringLength(30, errorMessage: \"Name cannot exceed {0} characters\"));\n            var html = helper.ListBox(fieldName, GetSelectList(), htmlAttributes: new Dictionary<string, object> { { \"data-some-val\", \"5\" } });\n\n            // Assert\n            Assert.Equal(\n                \"<select data-some-val=\\\"5\\\" data-val=\\\"true\\\" data-val-length=\\\"Name cannot exceed 30 characters\\\" data-val-length-max=\\\"30\\\" data-val-required=\\\"Please specify a valid Name.\\\" id=\\\"name\\\" name=\\\"name\\\">\" + Environment.NewLine\n              + \"<option value=\\\"A\\\">Alpha</option>\" + Environment.NewLine\n              + \"<option value=\\\"B\\\">Bravo</option>\" + Environment.NewLine\n              + \"<option value=\\\"C\\\">Charlie</option>\" + Environment.NewLine\n              + \"</select>\",\n                html.ToString());\n        }\n\n        [Fact]\n        public void ListBoxWithAttributesFromAnonymousObject_WithUnderscoreInName_TransformsUnderscoresToDashs()\n        {\n            HtmlHelperTest.AssertHelperTransformsAttributesUnderscoresToDashs((helper, attributes) =>\n                helper.ListBox(\"foo\", GetSelectList(), attributes));\n\n            HtmlHelperTest.AssertHelperTransformsAttributesUnderscoresToDashs((helper, attributes) =>\n                helper.ListBox(\"foo\", \"val\", GetSelectList(), \"val\", attributes));\n\n            HtmlHelperTest.AssertHelperTransformsAttributesUnderscoresToDashs((helper, attributes) =>\n                helper.ListBox(\"foo\", \"val\", GetSelectList(), \"val\", attributes));\n        }\n\n        private static IEnumerable<SelectListItem> GetSelectList()\n        {\n            yield return new SelectListItem() { Text = \"Alpha\", Value = \"A\" };\n            yield return new SelectListItem() { Text = \"Bravo\", Value = \"B\" };\n            yield return new SelectListItem() { Text = \"Charlie\", Value = \"C\" };\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Html/TextAreaHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.WebPages.Html;\nusing System.Web.WebPages.Scope;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")]\n    public class TextAreaExtensionsTest : IDisposable\n    {\n        [Fact]\n        public void TextAreaWithEmptyNameThrows()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act and assert\n            Assert.ThrowsArgument(() => helper.TextArea(null), \"name\", \"Value cannot be null or an empty string.\");\n\n            // Act and assert\n            Assert.ThrowsArgument(() => helper.TextArea(String.Empty), \"name\", \"Value cannot be null or an empty string.\");\n        }\n\n        [Fact]\n        public void TextAreaWithDefaultRowsAndCols()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.TextArea(\"foo\");\n\n            // Assert\n            Assert.Equal(@\"<textarea cols=\"\"20\"\" id=\"\"foo\"\" name=\"\"foo\"\" rows=\"\"2\"\"></textarea>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaWithZeroRowsAndColumns()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.TextArea(\"foo\", null, 0, 0, null);\n\n            // Assert\n            Assert.Equal(@\"<textarea id=\"\"foo\"\" name=\"\"foo\"\"></textarea>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaWithNonZeroRowsAndColumns()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = helper.TextArea(\"foo\", null, 4, 10, null);\n\n            // Assert\n            Assert.Equal(@\"<textarea cols=\"\"10\"\" id=\"\"foo\"\" name=\"\"foo\"\" rows=\"\"4\"\"></textarea>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaWithObjectAttributes()\n        {\n            // Arrange\n            ModelStateDictionary modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", \"foo-value\");\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.TextArea(\"foo\", new { attr = \"value\", cols = 6 });\n\n            // Assert\n            Assert.Equal(@\"<textarea attr=\"\"value\"\" cols=\"\"6\"\" id=\"\"foo\"\" name=\"\"foo\"\" rows=\"\"2\"\">foo-value</textarea>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaWithExplicitValue()\n        {\n            // Arrange\n            ModelStateDictionary modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", \"explicit-foo-value\");\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.TextArea(\"foo\", \"explicit-foo-value\", new { attr = \"attr-value\", cols = 6 });\n\n            // Assert\n            Assert.Equal(@\"<textarea attr=\"\"attr-value\"\" cols=\"\"6\"\" id=\"\"foo\"\" name=\"\"foo\"\" rows=\"\"2\"\">explicit-foo-value</textarea>\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaWithDictionaryAttributes()\n        {\n            // Arrange\n            ModelStateDictionary modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", \"explicit-foo-value\");\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n            var attributes = new Dictionary<string, object>() { { \"attr\", \"attr-val\" }, { \"rows\", 15 }, { \"cols\", 12 } };\n            // Act\n            var html = helper.TextArea(\"foo\", attributes);\n\n            // Assert\n            Assert.Equal(@\"<textarea attr=\"\"attr-val\"\" cols=\"\"12\"\" id=\"\"foo\"\" name=\"\"foo\"\" rows=\"\"15\"\">explicit-foo-value</textarea>\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaWithNoValueAndObjectAttributes()\n        {\n            // Arrange\n            HtmlHelper helper = HtmlHelperFactory.Create();\n            var attributes = new Dictionary<string, object>() { { \"attr\", \"attr-val\" }, { \"rows\", 15 }, { \"cols\", 12 } };\n            // Act\n            var html = helper.TextArea(\"foo\", attributes);\n\n            // Assert\n            Assert.Equal(@\"<textarea attr=\"\"attr-val\"\" cols=\"\"12\"\" id=\"\"foo\"\" name=\"\"foo\"\" rows=\"\"15\"\"></textarea>\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaWithNullValue()\n        {\n            // Arrange\n            ModelStateDictionary modelState = new ModelStateDictionary();\n            modelState.SetModelValue(\"foo\", \"explicit-foo-value\");\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n            var attributes = new Dictionary<string, object>() { { \"attr\", \"attr-val\" }, { \"rows\", 15 }, { \"cols\", 12 } };\n            // Act\n            var html = helper.TextArea(\"foo\", null, attributes);\n\n            // Assert\n            Assert.Equal(@\"<textarea attr=\"\"attr-val\"\" cols=\"\"12\"\" id=\"\"foo\"\" name=\"\"foo\"\" rows=\"\"15\"\">explicit-foo-value</textarea>\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaWithError()\n        {\n            // Arrange\n            ModelStateDictionary modelState = new ModelStateDictionary();\n            modelState.AddError(\"foo\", \"some error\");\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.TextArea(\"foo\", String.Empty);\n\n            // Assert\n            Assert.Equal(@\"<textarea class=\"\"input-validation-error\"\" cols=\"\"20\"\" id=\"\"foo\"\" name=\"\"foo\"\" rows=\"\"2\"\"></textarea>\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaWithErrorAndCustomCssClass()\n        {\n            // Arrange\n            ModelStateDictionary modelState = new ModelStateDictionary();\n            modelState.AddError(\"foo\", \"some error\");\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.TextArea(\"foo\", String.Empty, new { @class = \"my-css\" });\n\n            // Assert\n            Assert.Equal(@\"<textarea class=\"\"input-validation-error my-css\"\" cols=\"\"20\"\" id=\"\"foo\"\" name=\"\"foo\"\" rows=\"\"2\"\"></textarea>\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaWithCustomErrorClass()\n        {\n            // Arrange\n            ModelStateDictionary modelState = new ModelStateDictionary();\n            modelState.AddError(\"foo\", \"some error\");\n            HtmlHelper.ValidationInputCssClassName = \"custom-input-validation-error\";\n            HtmlHelper helper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = helper.TextArea(\"foo\", String.Empty, new { @class = \"my-css\" });\n\n            // Assert\n            Assert.Equal(@\"<textarea class=\"\"custom-input-validation-error my-css\"\" cols=\"\"20\"\" id=\"\"foo\"\" name=\"\"foo\"\" rows=\"\"2\"\"></textarea>\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void TextAreaAddsUnobtrusiveValidationAttributes()\n        {\n            // Arrange\n            const string fieldName = \"name\";\n            var modelStateDictionary = new ModelStateDictionary();\n            var validationHelper = new ValidationHelper(new Mock<HttpContextBase>().Object, modelStateDictionary);\n            HtmlHelper helper = HtmlHelperFactory.Create(modelStateDictionary, validationHelper);\n\n            // Act\n            validationHelper.RequireField(fieldName, \"Please specify a valid Name.\");\n            validationHelper.Add(fieldName, Validator.StringLength(30, errorMessage: \"Name cannot exceed {0} characters\"));\n            var html = helper.TextArea(fieldName, htmlAttributes: new Dictionary<string, object> { { \"data-some-val\", \"5\" } });\n\n            // Assert\n            Assert.Equal(@\"<textarea cols=\"\"20\"\" data-some-val=\"\"5\"\" data-val=\"\"true\"\" data-val-length=\"\"Name cannot exceed 30 characters\"\" data-val-length-max=\"\"30\"\" data-val-required=\"\"Please specify a valid Name.\"\" id=\"\"name\"\" name=\"\"name\"\" rows=\"\"2\"\"></textarea>\",\n                         html.ToString());\n        }\n\n        [Fact]\n        public void TextAreaWithAttributesFromAnonymousObject_WithUnderscoreInName_TransformsUnderscoresToDashs()\n        {\n            HtmlHelperTest.AssertHelperTransformsAttributesUnderscoresToDashs((helper, attributes) =>\n                helper.TextArea(\"foo\", attributes));\n\n            HtmlHelperTest.AssertHelperTransformsAttributesUnderscoresToDashs((helper, attributes) =>\n                helper.TextArea(\"foo\", \"value\", attributes));\n\n            HtmlHelperTest.AssertHelperTransformsAttributesUnderscoresToDashs((helper, attributes) =>\n                helper.TextArea(\"foo\", \"value\", 1, 1, attributes));\n        }\n\n        public void Dispose()\n        {\n            // Reset ScopeStorage (written via e.g. HtmlHelper.ValidationInputCssClassName) between tests to avoid unexpected interactions.\n            ScopeStorage.CurrentProvider = new StaticScopeStorageProvider();\n            ScopeStorage.GlobalScope.Clear();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Html/ValidationHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.WebPages.Html;\nusing System.Web.WebPages.Scope;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")]\n    public class ValidationHelperTest : IDisposable\n    {\n        [Fact]\n        public void ValidationMessageAllowsEmptyModelName()\n        {\n            // Arrange\n            ModelStateDictionary dictionary = new ModelStateDictionary();\n            dictionary.AddError(\"test\", \"some error text\");\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create(dictionary);\n\n            // Act\n            var html = htmlHelper.ValidationMessage(\"test\");\n\n            // Assert\n            Assert.Equal(\"<span class=\\\"field-validation-error\\\" data-valmsg-for=\\\"test\\\" data-valmsg-replace=\\\"true\\\">some error text</span>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageReturnsFirstError()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create(GetModelStateWithErrors());\n\n            // Act\n            var html = htmlHelper.ValidationMessage(\"foo\");\n\n            // Assert\n            Assert.Equal(\"<span class=\\\"field-validation-error\\\" data-valmsg-for=\\\"foo\\\" data-valmsg-replace=\\\"true\\\">foo error &lt;1&gt;</span>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageUsesValidCssClassIfFieldDoesNotHaveErrors()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create(GetModelStateWithErrors());\n\n            // Act\n            var html = htmlHelper.ValidationMessage(\"baz\");\n\n            // Assert\n            Assert.Equal(\"<span class=\\\"field-validation-valid\\\" data-valmsg-for=\\\"baz\\\" data-valmsg-replace=\\\"true\\\"></span>\", html.ToString());\n        }\n\n        [Fact]\n        public void ValidationMessageReturnsWithObjectAttributes()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create(GetModelStateWithErrors());\n\n            // Act\n            var html = htmlHelper.ValidationMessage(\"foo\", new { attr = \"attr-value\" });\n\n            // Assert\n            Assert.Equal(\"<span attr=\\\"attr-value\\\" class=\\\"field-validation-error\\\" data-valmsg-for=\\\"foo\\\" data-valmsg-replace=\\\"true\\\">foo error &lt;1&gt;</span>\",\n                         html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageReturnsWithCustomMessage()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create(GetModelStateWithErrors());\n\n            // Atc\n            var html = htmlHelper.ValidationMessage(\"foo\", \"bar error\");\n\n            // Assert\n            Assert.Equal(\"<span class=\\\"field-validation-error\\\" data-valmsg-for=\\\"foo\\\" data-valmsg-replace=\\\"false\\\">bar error</span>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageReturnsWithCustomMessageAndObjectAttributes()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create(GetModelStateWithErrors());\n\n            // Act\n            var html = htmlHelper.ValidationMessage(\"foo\", \"bar error\", new { baz = \"baz\" });\n\n            // Assert\n            Assert.Equal(\"<span baz=\\\"baz\\\" class=\\\"field-validation-error\\\" data-valmsg-for=\\\"foo\\\" data-valmsg-replace=\\\"false\\\">bar error</span>\", html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationMessageWithModelStateAndNoErrors()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create(GetModelStateWithErrors());\n\n            // Act\n            var html = htmlHelper.ValidationMessage(\"baz\");\n\n            // Assert\n            Assert.Equal(\"<span class=\\\"field-validation-valid\\\" data-valmsg-for=\\\"baz\\\" data-valmsg-replace=\\\"true\\\"></span>\", html.ToString());\n        }\n\n        [Fact]\n        public void ValidationMessageWithAttributesFromAnonymousObject_WithUnderscoreInName_TransformsUnderscoresToDashs()\n        {\n            HtmlHelperTest.AssertHelperTransformsAttributesUnderscoresToDashs((helper, attributes) =>\n                helper.ValidationMessage(\"foo\", attributes));\n\n            HtmlHelperTest.AssertHelperTransformsAttributesUnderscoresToDashs((helper, attributes) =>\n                helper.ValidationMessage(\"foo\", \"bar\", attributes));\n        }\n\n        [Fact]\n        public void ValidationSummary()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create(GetModelStateWithErrors());\n\n            // Act\n            var html = htmlHelper.ValidationSummary();\n\n            // Assert\n            Assert.Equal(\n                \"<div class=\\\"validation-summary-errors\\\" data-valmsg-summary=\\\"true\\\"><ul>\" + Environment.NewLine\n              + \"<li>foo error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>foo error &lt;2&gt;</li>\" + Environment.NewLine\n              + \"<li>bar error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>bar error &lt;2&gt;</li>\" + Environment.NewLine\n              + \"</ul></div>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationSummaryWithMessage()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create(GetModelStateWithErrors());\n\n            // Act\n            var html = htmlHelper.ValidationSummary(\"test message\");\n\n            // Assert\n            Assert.Equal(\n                \"<div class=\\\"validation-summary-errors\\\" data-valmsg-summary=\\\"true\\\"><span>test message</span>\" + Environment.NewLine\n              + \"<ul>\" + Environment.NewLine\n              + \"<li>foo error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>foo error &lt;2&gt;</li>\" + Environment.NewLine\n              + \"<li>bar error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>bar error &lt;2&gt;</li>\" + Environment.NewLine\n              + \"</ul></div>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationSummaryWithFormErrors()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create(GetModelStateWithFormErrors());\n\n            // Act\n            var html = htmlHelper.ValidationSummary();\n\n            // Assert\n            Assert.Equal(\n                \"<div class=\\\"validation-summary-errors\\\" data-valmsg-summary=\\\"true\\\"><ul>\" + Environment.NewLine\n              + \"<li>foo error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>foo error &lt;2&gt;</li>\" + Environment.NewLine\n              + \"<li>bar error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>bar error &lt;2&gt;</li>\" + Environment.NewLine\n              + \"<li>some form error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>some form error &lt;2&gt;</li>\" + Environment.NewLine\n              + \"</ul></div>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationSummaryWithFormErrorsAndExcludeFieldErrors()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create(GetModelStateWithFormErrors());\n\n            // Act\n            var html = htmlHelper.ValidationSummary(excludeFieldErrors: true);\n\n            // Assert\n            Assert.Equal(\n                \"<div class=\\\"validation-summary-errors\\\"><ul>\" + Environment.NewLine\n              + \"<li>some form error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>some form error &lt;2&gt;</li>\" + Environment.NewLine\n              + \"</ul></div>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationSummaryWithObjectProperties()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create(GetModelStateWithErrors());\n\n            // Act\n            var html = htmlHelper.ValidationSummary(new { attr = \"attr-value\", @class = \"my-class\" });\n\n            // Assert\n            Assert.Equal(\n                \"<div attr=\\\"attr-value\\\" class=\\\"validation-summary-errors my-class\\\" data-valmsg-summary=\\\"true\\\"><ul>\" + Environment.NewLine\n              + \"<li>foo error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>foo error &lt;2&gt;</li>\" + Environment.NewLine\n              + \"<li>bar error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>bar error &lt;2&gt;</li>\" + Environment.NewLine\n              + \"</ul></div>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationSummaryWithDictionary()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create(GetModelStateWithErrors());\n\n            // Act\n            var html = htmlHelper.ValidationSummary(new Dictionary<string, object> { { \"attr\", \"attr-value\" }, { \"class\", \"my-class\" } });\n\n            // Assert\n            Assert.Equal(\n                \"<div attr=\\\"attr-value\\\" class=\\\"validation-summary-errors my-class\\\" data-valmsg-summary=\\\"true\\\"><ul>\" + Environment.NewLine\n              + \"<li>foo error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>foo error &lt;2&gt;</li>\" + Environment.NewLine\n              + \"<li>bar error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>bar error &lt;2&gt;</li>\" + Environment.NewLine\n              + \"</ul></div>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationSummaryWithDictionaryAndMessage()\n        {\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create(GetModelStateWithErrors());\n\n            // Act\n            var html = htmlHelper.ValidationSummary(\"This is a message.\", new Dictionary<string, object> { { \"attr\", \"attr-value\" }, { \"class\", \"my-class\" } });\n\n            // Assert\n            Assert.Equal(\n                \"<div attr=\\\"attr-value\\\" class=\\\"validation-summary-errors my-class\\\" data-valmsg-summary=\\\"true\\\"><span>This is a message.</span>\" + Environment.NewLine\n              + \"<ul>\" + Environment.NewLine\n              + \"<li>foo error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>foo error &lt;2&gt;</li>\" + Environment.NewLine\n              + \"<li>bar error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>bar error &lt;2&gt;</li>\" + Environment.NewLine\n              + \"</ul></div>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationSummaryWithCustomValidationSummaryClass()\n        {\n            // Arrange\n            HtmlHelper.ValidationSummaryClass = \"my-val-class\";\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create(GetModelStateWithErrors());\n\n            // Act\n            var html = htmlHelper.ValidationSummary(\"This is a message.\", new Dictionary<string, object> { { \"attr\", \"attr-value\" }, { \"class\", \"my-class\" } });\n\n            // Assert\n            Assert.Equal(\n                \"<div attr=\\\"attr-value\\\" class=\\\"my-val-class my-class\\\" data-valmsg-summary=\\\"true\\\"><span>This is a message.</span>\" + Environment.NewLine\n              + \"<ul>\" + Environment.NewLine\n              + \"<li>foo error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>foo error &lt;2&gt;</li>\" + Environment.NewLine\n              + \"<li>bar error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>bar error &lt;2&gt;</li>\" + Environment.NewLine\n              + \"</ul></div>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationSummaryWithNoErrorReturnsNullIfExcludeFieldErrorsIsSetToFalse()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = htmlHelper.ValidationSummary(excludeFieldErrors: false);\n\n            // Assert\n            Assert.Equal(\n                \"<div class=\\\"validation-summary-valid\\\" data-valmsg-summary=\\\"true\\\"><ul>\" + Environment.NewLine\n              + \"</ul></div>\",\n                html.ToString());\n        }\n\n        [Fact]\n        public void ValidationSummaryWithNoErrorReturnsNull()\n        {\n            // Arrange\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create();\n\n            // Act\n            var html = htmlHelper.ValidationSummary(excludeFieldErrors: true);\n\n            // Assert\n            Assert.Null(html);\n        }\n\n        [Fact]\n        public void ValidationSummaryWithNoFormErrorsAndExcludedFieldErrorsReturnsNull()\n        {\n            // Arrange\n            ModelStateDictionary modelState = new ModelStateDictionary();\n            modelState.AddError(\"foo\", \"error\");\n            modelState.AddError(\"bar\", \"error\");\n\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = htmlHelper.ValidationSummary(excludeFieldErrors: true);\n\n            // Assert\n            Assert.Null(html);\n        }\n\n        [Fact]\n        public void ValidationSummaryWithMultipleFormErrorsAndExcludedFieldErrors()\n        {\n            // Arrange\n            ModelStateDictionary modelState = new ModelStateDictionary();\n            modelState.AddFormError(\"error <1>\");\n            modelState.AddFormError(\"error <2>\");\n\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create(modelState);\n\n            // Act\n            var html = htmlHelper.ValidationSummary(excludeFieldErrors: true);\n\n            // Assert\n            Assert.Equal(\n                \"<div class=\\\"validation-summary-errors\\\"><ul>\" + Environment.NewLine\n              + \"<li>error &lt;1&gt;</li>\" + Environment.NewLine\n              + \"<li>error &lt;2&gt;</li>\" + Environment.NewLine\n              + \"</ul></div>\",\n                html.ToHtmlString());\n        }\n\n        [Fact]\n        public void ValidationSummaryWithAttributesFromAnonymousObject_WithUnderscoreInName_TransformsUnderscoresToDashs()\n        {\n            // Arrange\n            var modelState = new ModelStateDictionary();\n            modelState.AddFormError(\"error\");\n\n            HtmlHelper htmlHelper = HtmlHelperFactory.Create(modelState);\n\n            HtmlHelperTest.AssertHelperTransformsAttributesUnderscoresToDashs((helper, attributes) =>\n                htmlHelper.ValidationSummary(attributes));\n\n            HtmlHelperTest.AssertHelperTransformsAttributesUnderscoresToDashs((helper, attributes) =>\n                htmlHelper.ValidationSummary(\"foo\", attributes));\n\n            HtmlHelperTest.AssertHelperTransformsAttributesUnderscoresToDashs((helper, attributes) =>\n                htmlHelper.ValidationSummary(\"foo\", true, attributes));\n        }\n\n        private static ModelStateDictionary GetModelStateWithErrors()\n        {\n            ModelStateDictionary modelState = new ModelStateDictionary();\n            modelState.AddError(\"foo\", \"foo error <1>\");\n            modelState.AddError(\"foo\", \"foo error <2>\");\n            modelState.AddError(\"bar\", \"bar error <1>\");\n            modelState.AddError(\"bar\", \"bar error <2>\");\n            return modelState;\n        }\n\n        private static ModelStateDictionary GetModelStateWithFormErrors()\n        {\n            ModelStateDictionary modelState = GetModelStateWithErrors();\n            modelState.AddFormError(\"some form error <1>\");\n            modelState.AddFormError(\"some form error <2>\");\n            return modelState;\n        }\n\n        public void Dispose()\n        {\n            // Reset ScopeStorage (written via e.g. HtmlHelper.ValidationSummaryClass) between tests to avoid unexpected interactions.\n            ScopeStorage.CurrentProvider = new StaticScopeStorageProvider();\n            ScopeStorage.GlobalScope.Clear();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Instrumentation/InstrumentationServiceTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Dynamic;\nusing System.IO;\nusing System.Web.WebPages.Instrumentation;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Test.Instrumentation\n{\n    public class InstrumentationServiceTest\n    {\n        [Fact]\n        public void BeginContextDelegatesToRegisteredListeners()\n        {\n            // Arrange\n            dynamic listener1 = CreateListener();\n            dynamic listener2 = CreateListener();\n            InstrumentationService inst = CreateInstrumentationService(listener1, listener2);\n            TextWriter mockWriter = new StringWriter();\n\n            // Act\n            inst.BeginContext(null, \"Foo.cshtml\", mockWriter, 42, 24, isLiteral: false);\n\n            // Assert\n            Assert.Equal(1, listener1.BeginContextCalls.Count);\n            Assert.Equal(0, listener1.EndContextCalls.Count);\n            Assert.Equal(1, listener2.BeginContextCalls.Count);\n            Assert.Equal(0, listener2.EndContextCalls.Count);\n\n            AssertContext(\"Foo.cshtml\", mockWriter, 42, 24, false, listener1.BeginContextCalls[0]);\n            AssertContext(\"Foo.cshtml\", mockWriter, 42, 24, false, listener2.BeginContextCalls[0]);\n        }\n\n        [Fact]\n        public void EndContextDelegatesToRegisteredListeners()\n        {\n            // Arrange\n            dynamic listener1 = CreateListener();\n            dynamic listener2 = CreateListener();\n            InstrumentationService inst = CreateInstrumentationService(listener1, listener2);\n            TextWriter mockWriter = new StringWriter();\n\n            // Act\n            inst.EndContext(null, \"Foo.cshtml\", mockWriter, 42, 24, isLiteral: false);\n\n            // Assert\n            Assert.Equal(1, listener1.EndContextCalls.Count);\n            Assert.Equal(0, listener1.BeginContextCalls.Count);\n            Assert.Equal(1, listener2.EndContextCalls.Count);\n            Assert.Equal(0, listener2.BeginContextCalls.Count);\n\n            AssertContext(\"Foo.cshtml\", mockWriter, 42, 24, false, listener1.EndContextCalls[0]);\n            AssertContext(\"Foo.cshtml\", mockWriter, 42, 24, false, listener2.EndContextCalls[0]);\n        }\n\n        private void AssertContext(string virtualPath, TextWriter writer, int startPosition, int length, bool isLiteral, dynamic context)\n        {\n            PageExecutionContextAdapter ctx = new PageExecutionContextAdapter(context);\n            Assert.Equal(virtualPath, ctx.VirtualPath);\n            Assert.Same(writer, ctx.TextWriter);\n            Assert.Equal(startPosition, ctx.StartPosition);\n            Assert.Equal(length, ctx.Length);\n            Assert.Equal(isLiteral, ctx.IsLiteral);\n        }\n\n        private InstrumentationService CreateInstrumentationService(params dynamic[] listeners)\n        {\n            dynamic service = new ExpandoObject();\n            service.ExecutionListeners = new List<dynamic>(listeners);\n            InstrumentationService inst = new InstrumentationService();\n            inst.IsAvailable = true;\n            inst.ExtractInstrumentationService = _ => new PageInstrumentationServiceAdapter(service);\n            inst.CreateContext = CreateExpandoContext;\n            return inst;\n        }\n\n        private dynamic CreateListener()\n        {\n            dynamic listener = new ExpandoObject();\n            listener.BeginContextCalls = new List<dynamic>();\n            listener.EndContextCalls = new List<dynamic>();\n            listener.BeginContext = (Action<dynamic>)(d => { listener.BeginContextCalls.Add(d); });\n            listener.EndContext = (Action<dynamic>)(d => { listener.EndContextCalls.Add(d); });\n            return listener;\n        }\n\n        private PageExecutionContextAdapter CreateExpandoContext(string virtualPath, TextWriter writer, int startPosition, int length, bool isLiteral)\n        {\n            dynamic ctx = new ExpandoObject();\n            ctx.VirtualPath = virtualPath;\n            ctx.TextWriter = writer;\n            ctx.StartPosition = startPosition;\n            ctx.Length = length;\n            ctx.IsLiteral = isLiteral;\n            return new PageExecutionContextAdapter(ctx);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/LatestRazorVersion.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Razor;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Test\n{\n    public static class LatestRazorVersion\n    {\n        private static readonly Version LatestVersion = VersionTestHelper.GetVersionFromAssembly(\"System.Web.Razor\", typeof(ParserResults));\n\n        public static readonly string MajorMinor = LatestVersion.Major + \".\" + LatestVersion.Minor;\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Mvc/HttpAntiForgeryExceptionTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Runtime.Serialization.Formatters.Binary;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class HttpAntiForgeryExceptionTest\n    {\n        [Fact]\n        public void ConstructorWithMessageAndInnerExceptionParameter()\n        {\n            // Arrange\n            Exception innerException = new Exception();\n\n            // Act\n            HttpAntiForgeryException ex = new HttpAntiForgeryException(\"the message\", innerException);\n\n            // Assert\n            Assert.Equal(\"the message\", ex.Message);\n            Assert.Equal(innerException, ex.InnerException);\n        }\n\n        [Fact]\n        public void ConstructorWithMessageParameter()\n        {\n            // Act\n            HttpAntiForgeryException ex = new HttpAntiForgeryException(\"the message\");\n\n            // Assert\n            Assert.Equal(\"the message\", ex.Message);\n        }\n\n        [Fact]\n        public void ConstructorWithoutParameters()\n        {\n            // Act & assert\n            Assert.Throws<HttpAntiForgeryException>(\n                delegate { throw new HttpAntiForgeryException(); });\n        }\n\n        [Fact]\n        public void TypeIsSerializable()\n        {\n            // If this ever fails with SerializationException : Unable to find assembly 'System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'\n            // (usually when the assembly version is incremented) you need to modify the App.config file in this test project to reference the new version.\n\n            // Arrange\n            MemoryStream ms = new MemoryStream();\n            BinaryFormatter formatter = new BinaryFormatter();\n            HttpAntiForgeryException ex = new HttpAntiForgeryException(\"the message\", new Exception(\"inner exception\"));\n\n            // Act\n            formatter.Serialize(ms, ex);\n            ms.Position = 0;\n            HttpAntiForgeryException deserialized = formatter.Deserialize(ms) as HttpAntiForgeryException;\n\n            // Assert\n            Assert.NotNull(deserialized);\n            Assert.Equal(\"the message\", deserialized.Message);\n            Assert.NotNull(deserialized.InnerException);\n            Assert.Equal(\"inner exception\", deserialized.InnerException.Message);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Mvc/ModelClientValidationMaxLengthRuleTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ModelClientValidationMaxLengthRuleTest\n    {\n        [Fact]\n        public void ModelClientValidationMaxLengthRuleTestAddsMaxLengthParameter()\n        {\n            // Arrange\n            var clientValidationRule = new ModelClientValidationMaxLengthRule(\"Max length error message\", 8);\n\n            // Assert\n            Assert.Equal(1, clientValidationRule.ValidationParameters.Count);\n            Assert.Equal(8, clientValidationRule.ValidationParameters[\"max\"]);\n            Assert.Equal(\"Max length error message\", clientValidationRule.ErrorMessage);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Mvc/ModelClientValidationMembershipPasswordRuleTest.cs",
    "content": "// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ModelClientValidationMembershipPasswordRuleTest\n    {\n        [Fact]\n        public void Constructor()\n        {\n            // Arrange & Act\n            var rule = new ModelClientValidationMembershipPasswordRule(\"ErrorMessage\", 10, 5, \"regex-value\");\n\n            // Assert\n            Assert.Equal(\"password\", rule.ValidationType);\n            Assert.Equal(\"ErrorMessage\", rule.ErrorMessage);\n            Assert.Equal(10, rule.ValidationParameters[\"min\"]);\n            Assert.Equal(5, rule.ValidationParameters[\"nonalphamin\"]);\n            Assert.Equal(\"regex-value\", rule.ValidationParameters[\"regex\"]);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Mvc/ModelClientValidationMinLengthRuleTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ModelClientValidationMinLengthRuleTest\n    {\n        [Fact]\n        public void ModelClientValidationMinLengthRuleTestAddsMinLengthParameter()\n        {\n            // Arrange\n            var clientValidationRule = new ModelClientValidationMinLengthRule(\"Min Length message\", 2);\n\n            // Assert\n            Assert.Equal(1, clientValidationRule.ValidationParameters.Count);\n            Assert.Equal(2, clientValidationRule.ValidationParameters[\"min\"]);\n            Assert.Equal(\"Min Length message\", clientValidationRule.ErrorMessage);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Mvc/ModelClientValidationStringLengthRuleTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class ModelClientValidationStringLengthRuleTest\n    {\n        [Fact]\n        public void ModelClientValidationStringLengthRuleTestDoesNotAddMinLengthParameterIfSpecifiedValueIs0()\n        {\n            // Arrange\n            var clientValidationRule = new ModelClientValidationStringLengthRule(\"Test message\", 0, 10);\n\n            // Assert\n            Assert.Equal(1, clientValidationRule.ValidationParameters.Count);\n            Assert.Equal(10, clientValidationRule.ValidationParameters[\"max\"]);\n        }\n\n        [Fact]\n        public void ModelClientValidationStringLengthRuleTestDoesNotAddMaxLengthIfSpecifiedValueIsMaxValue()\n        {\n            // Arrange\n            var clientValidationRule = new ModelClientValidationStringLengthRule(\"Test message\", 3, Int32.MaxValue);\n\n            // Assert\n            Assert.Equal(1, clientValidationRule.ValidationParameters.Count);\n            Assert.Equal(3, clientValidationRule.ValidationParameters[\"min\"]);\n        }\n\n        [Fact]\n        public void ModelClientValidationStringLengthRuleTestAddsMinLengthParameter()\n        {\n            // Arrange\n            string message = \"Password must contain only letters and must be between 3-8 characters long\";\n            var clientValidationRule = new ModelClientValidationStringLengthRule(message, 3, 8);\n\n            // Assert\n            Assert.Equal(2, clientValidationRule.ValidationParameters.Count);\n            Assert.Equal(message, clientValidationRule.ErrorMessage);\n            Assert.Equal(3, clientValidationRule.ValidationParameters[\"min\"]);\n            Assert.Equal(8, clientValidationRule.ValidationParameters[\"max\"]);\n        }\n\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Mvc/TagBuilderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.WebPages.Html;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.Mvc.Test\n{\n    public class TagBuilderTest\n    {\n        [Fact]\n        public void AddCssClassPrepends()\n        {\n            // Arrange\n            TagBuilder builder = new TagBuilder(\"SomeTag\");\n            builder.MergeAttribute(\"class\", \"oldA\");\n\n            // Act\n            builder.AddCssClass(\"newA\");\n\n            // Assert\n            Assert.Equal(\"newA oldA\", builder.Attributes[\"class\"]);\n        }\n\n        [Fact]\n        public void AttributesProperty()\n        {\n            // Arrange\n            TagBuilder builder = new TagBuilder(\"SomeTag\");\n\n            // Act\n            SortedDictionary<string, string> attributes = builder.Attributes as SortedDictionary<string, string>;\n\n            // Assert\n            Assert.NotNull(attributes);\n            Assert.Equal(StringComparer.Ordinal, attributes.Comparer);\n        }\n\n        [Fact]\n        public void ConstructorSetsTagNameProperty()\n        {\n            // Arrange\n            TagBuilder builder = new TagBuilder(\"SomeTag\");\n\n            // Act\n            string tagName = builder.TagName;\n\n            // Assert\n            Assert.Equal(\"SomeTag\", tagName);\n        }\n\n        [Fact]\n        public void ConstructorWithEmptyTagNameThrows()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(\n                delegate { new TagBuilder(String.Empty); }, \"tagName\");\n        }\n\n        [Fact]\n        public void ConstructorWithNullTagNameThrows()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(\n                delegate { new TagBuilder(null /* tagName */); }, \"tagName\");\n        }\n\n        [Fact]\n        public void CreateSanitizedIdThrowsIfInvalidCharReplacementIsNull()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(\n                () => TagBuilder.CreateSanitizedId(\"tagId\", null),\n                \"invalidCharReplacement\");\n        }\n\n        [Fact]\n        public void CreateSanitizedIdDefaultsToHtmlHelperIdAttributeDotReplacement()\n        {\n            // Arrange\n            String defaultReplacementChar = HtmlHelper.IdAttributeDotReplacement;\n\n            // Act\n            string sanitizedId = TagBuilder.CreateSanitizedId(\"Hello world\");\n\n            // Assert\n            Assert.Equal(\"Hello\" + defaultReplacementChar + \"world\", sanitizedId);\n        }\n\n        [Fact]\n        public void CreateSanitizedId_ReturnsNullIfOriginalIdBeginsWithNonLetter()\n        {\n            // Act\n            string retVal = TagBuilder.CreateSanitizedId(\"_DoesNotBeginWithALetter\", \"!REPL!\");\n\n            // Assert\n            Assert.Null(retVal);\n        }\n\n        [Fact]\n        public void CreateSanitizedId_ReturnsNullIfOriginalIdIsEmpty()\n        {\n            // Act\n            string retVal = TagBuilder.CreateSanitizedId(\"\", \"!REPL!\");\n\n            // Assert\n            Assert.Null(retVal);\n        }\n\n        [Fact]\n        public void CreateSanitizedId_ReturnsNullIfOriginalIdIsNull()\n        {\n            // Act\n            string retVal = TagBuilder.CreateSanitizedId(null, \"!REPL!\");\n\n            // Assert\n            Assert.Null(retVal);\n        }\n\n        [Fact]\n        public void CreateSanitizedId_ReturnsSanitizedId()\n        {\n            // Arrange\n            string expected = \"ABCXYZabcxyz012789!REPL!!REPL!!REPL!!REPL!!REPL!!REPL!!REPL!!REPL!!REPL!!REPL!-!REPL!_!REPL!!REPL!:\";\n\n            // Act\n            string retVal = TagBuilder.CreateSanitizedId(\"ABCXYZabcxyz012789!@#$%^&*()-=_+.:\", \"!REPL!\");\n\n            // Assert\n            Assert.Equal(expected, retVal);\n        }\n\n        [Fact]\n        public void GenerateId_AddsSanitizedId()\n        {\n            // Arrange\n            TagBuilder builder = new TagBuilder(\"div\");\n            builder.IdAttributeDotReplacement = \"x\";\n\n            // Act\n            builder.GenerateId(\"Hello, world.\");\n\n            // Assert\n            Assert.Equal(\"Helloxxworldx\", builder.Attributes[\"id\"]);\n        }\n\n        [Fact]\n        public void GenerateId_DoesNotAddIdIfIdAlreadyExists()\n        {\n            // Arrange\n            TagBuilder builder = new TagBuilder(\"div\");\n            builder.GenerateId(\"old\");\n\n            // Act\n            builder.GenerateId(\"new\");\n\n            // Assert\n            Assert.Equal(\"old\", builder.Attributes[\"id\"]);\n        }\n\n        [Fact]\n        public void GenerateId_DoesNotAddIdIfSanitizationReturnsNull()\n        {\n            // Arrange\n            TagBuilder builder = new TagBuilder(\"div\");\n\n            // Act\n            builder.GenerateId(\"\");\n\n            // Assert\n            Assert.False(builder.Attributes.ContainsKey(\"id\"));\n        }\n\n        [Fact]\n        public void InnerHtmlProperty()\n        {\n            // Arrange\n            TagBuilder builder = new TagBuilder(\"SomeTag\");\n\n            // Act & Assert\n            Assert.Equal(String.Empty, builder.InnerHtml);\n            builder.InnerHtml = \"foo\";\n            Assert.Equal(\"foo\", builder.InnerHtml);\n            builder.InnerHtml = null;\n            Assert.Equal(String.Empty, builder.InnerHtml);\n        }\n\n        [Fact]\n        public void MergeAttributeDoesNotOverwriteExistingValuesByDefault()\n        {\n            // Arrange\n            TagBuilder builder = new TagBuilder(\"SomeTag\");\n            builder.MergeAttribute(\"a\", \"oldA\");\n\n            // Act\n            builder.MergeAttribute(\"a\", \"newA\");\n\n            // Assert\n            Assert.Equal(\"oldA\", builder.Attributes[\"a\"]);\n        }\n\n        [Fact]\n        public void MergeAttributeOverwritesExistingValueIfAsked()\n        {\n            // Arrange\n            TagBuilder builder = new TagBuilder(\"SomeTag\");\n            builder.MergeAttribute(\"a\", \"oldA\");\n\n            // Act\n            builder.MergeAttribute(\"a\", \"newA\", true);\n\n            // Assert\n            Assert.Equal(\"newA\", builder.Attributes[\"a\"]);\n        }\n\n        [Fact]\n        public void MergeAttributeWithEmptyKeyThrows()\n        {\n            // Arrange\n            TagBuilder builder = new TagBuilder(\"SomeTag\");\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmptyString(\n                delegate { builder.MergeAttribute(String.Empty, \"value\"); }, \"key\");\n        }\n\n        [Fact]\n        public void MergeAttributeWithNullKeyThrows()\n        {\n            // Arrange\n            TagBuilder builder = new TagBuilder(\"SomeTag\");\n\n            // Act & Assert\n            Assert.ThrowsArgumentNullOrEmptyString(\n                delegate { builder.MergeAttribute(null, \"value\"); }, \"key\");\n        }\n\n        [Fact]\n        public void MergeAttributesDoesNotOverwriteExistingValuesByDefault()\n        {\n            // Arrange\n            TagBuilder builder = new TagBuilder(\"SomeTag\");\n            builder.Attributes[\"a\"] = \"oldA\";\n\n            Dictionary<string, string> newAttrs = new Dictionary<string, string>\n            {\n                { \"a\", \"newA\" },\n                { \"b\", \"newB\" }\n            };\n\n            // Act\n            builder.MergeAttributes(newAttrs);\n\n            // Assert\n            Assert.Equal(2, builder.Attributes.Count);\n            Assert.Equal(\"oldA\", builder.Attributes[\"a\"]);\n            Assert.Equal(\"newB\", builder.Attributes[\"b\"]);\n        }\n\n        [Fact]\n        public void MergeAttributesOverwritesExistingValueIfAsked()\n        {\n            // Arrange\n            TagBuilder builder = new TagBuilder(\"SomeTag\");\n            builder.Attributes[\"a\"] = \"oldA\";\n\n            Dictionary<string, string> newAttrs = new Dictionary<string, string>\n            {\n                { \"a\", \"newA\" },\n                { \"b\", \"newB\" }\n            };\n\n            // Act\n            builder.MergeAttributes(newAttrs, true);\n\n            // Assert\n            Assert.Equal(2, builder.Attributes.Count);\n            Assert.Equal(\"newA\", builder.Attributes[\"a\"]);\n            Assert.Equal(\"newB\", builder.Attributes[\"b\"]);\n        }\n\n        [Fact]\n        public void MergeAttributesWithNullAttributesDoesNothing()\n        {\n            // Arrange\n            TagBuilder builder = new TagBuilder(\"SomeTag\");\n\n            // Act\n            builder.MergeAttributes<string, string>(null);\n\n            // Assert\n            Assert.Equal(0, builder.Attributes.Count);\n        }\n\n        [Fact]\n        public void SetInnerTextEncodes()\n        {\n            // Arrange\n            TagBuilder builder = new TagBuilder(\"SomeTag\");\n\n            // Act\n            builder.SetInnerText(\"<>\");\n\n            // Assert\n            Assert.Equal(\"&lt;&gt;\", builder.InnerHtml);\n        }\n\n        [Fact]\n        public void ToStringDefaultsToNormal()\n        {\n            // Arrange\n            TagBuilder builder = new TagBuilder(\"SomeTag\")\n            {\n                InnerHtml = \"<x&y>\"\n            };\n            builder.MergeAttributes(GetAttributesDictionary());\n\n            // Act\n            string output = builder.ToString();\n\n            // Assert\n            Assert.Equal(@\"<SomeTag a=\"\"Foo\"\" b=\"\"Bar&amp;Baz\"\" c=\"\"&lt;&quot;Quux&quot;>\"\"><x&y></SomeTag>\", output);\n        }\n\n        [Fact]\n        public void ToStringDoesNotOutputEmptyIdTags()\n        {\n            // Arrange\n            TagBuilder builder = new TagBuilder(\"SomeTag\");\n            builder.Attributes[\"foo\"] = \"fooValue\";\n            builder.Attributes[\"bar\"] = \"barValue\";\n            builder.Attributes[\"id\"] = \"\";\n\n            // Act\n            string output = builder.ToString(TagRenderMode.SelfClosing);\n\n            Assert.Equal(@\"<SomeTag bar=\"\"barValue\"\" foo=\"\"fooValue\"\" />\", output);\n        }\n\n        [Fact]\n        public void ToStringEndTag()\n        {\n            // Arrange\n            TagBuilder builder = new TagBuilder(\"SomeTag\")\n            {\n                InnerHtml = \"<x&y>\"\n            };\n            builder.MergeAttributes(GetAttributesDictionary());\n\n            // Act\n            string output = builder.ToString(TagRenderMode.EndTag);\n\n            // Assert\n            Assert.Equal(@\"</SomeTag>\", output);\n        }\n\n        [Fact]\n        public void ToStringNormal()\n        {\n            // Arrange\n            TagBuilder builder = new TagBuilder(\"SomeTag\")\n            {\n                InnerHtml = \"<x&y>\"\n            };\n            builder.MergeAttributes(GetAttributesDictionary());\n\n            // Act\n            string output = builder.ToString(TagRenderMode.Normal);\n\n            // Assert\n            Assert.Equal(@\"<SomeTag a=\"\"Foo\"\" b=\"\"Bar&amp;Baz\"\" c=\"\"&lt;&quot;Quux&quot;>\"\"><x&y></SomeTag>\", output);\n        }\n\n        [Fact]\n        public void ToStringSelfClosing()\n        {\n            // Arrange\n            TagBuilder builder = new TagBuilder(\"SomeTag\")\n            {\n                InnerHtml = \"<x&y>\"\n            };\n            builder.MergeAttributes(GetAttributesDictionary());\n\n            // Act\n            string output = builder.ToString(TagRenderMode.SelfClosing);\n\n            // Assert\n            Assert.Equal(@\"<SomeTag a=\"\"Foo\"\" b=\"\"Bar&amp;Baz\"\" c=\"\"&lt;&quot;Quux&quot;>\"\" />\", output);\n        }\n\n        [Fact]\n        public void ToStringStartTag()\n        {\n            // Arrange\n            TagBuilder builder = new TagBuilder(\"SomeTag\")\n            {\n                InnerHtml = \"<x&y>\"\n            };\n            builder.MergeAttributes(GetAttributesDictionary());\n\n            // Act\n            string output = builder.ToString(TagRenderMode.StartTag);\n\n            // Assert\n            Assert.Equal(@\"<SomeTag a=\"\"Foo\"\" b=\"\"Bar&amp;Baz\"\" c=\"\"&lt;&quot;Quux&quot;>\"\">\", output);\n        }\n\n        private static IDictionary<string, string> GetAttributesDictionary()\n        {\n            return new SortedDictionary<string, string>\n            {\n                { \"a\", \"Foo\" },\n                { \"b\", \"Bar&Baz\" },\n                { \"c\", @\"<\"\"Quux\"\">\" }\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Mvc/UnobtrusiveValidationAttributesGeneratorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Test.Mvc\n{\n    public class UnobtrusiveValidationAttributesGeneratorTest\n    {\n        [Fact]\n        public void GetValidationAttributesReturnsAttributesWhenMinAndMaxLengthRulesAreApplied()\n        {\n            // Arrange\n            var clientRules = new ModelClientValidationRule[]\n            {\n                new ModelClientValidationMaxLengthRule(\"Max length message\", 8),\n                new ModelClientValidationMinLengthRule(\"Min length message\", 2)\n            };\n            var attributes = new Dictionary<string, object>();\n\n            // Act\n            UnobtrusiveValidationAttributesGenerator.GetValidationAttributes(clientRules, attributes);\n\n            // Assert\n            Assert.Equal(5, attributes.Count);\n            Assert.Equal(\"true\", attributes[\"data-val\"]);\n            Assert.Equal(\"Max length message\", attributes[\"data-val-maxlength\"]);\n            Assert.Equal(8, attributes[\"data-val-maxlength-max\"]);\n            Assert.Equal(\"Min length message\", attributes[\"data-val-minlength\"]);\n            Assert.Equal(2, attributes[\"data-val-minlength-min\"]);\n        }\n\n        [Fact]\n        public void GetValidationAttributesReturnsAttributesWhenMinAndStringLengthRulesAreApplied()\n        {\n            // Arrange\n            var clientRules = new ModelClientValidationRule[]\n            {\n                new ModelClientValidationMinLengthRule(\"Min length message\", 2),\n                new ModelClientValidationStringLengthRule(\"String length rule\", 2, 6)\n            };\n            var attributes = new Dictionary<string, object>();\n\n            // Act\n            UnobtrusiveValidationAttributesGenerator.GetValidationAttributes(clientRules, attributes);\n\n            // Assert\n            Assert.Equal(6, attributes.Count);\n            Assert.Equal(\"true\", attributes[\"data-val\"]);\n            Assert.Equal(\"String length rule\", attributes[\"data-val-length\"]);\n            Assert.Equal(2, attributes[\"data-val-length-min\"]);\n            Assert.Equal(6, attributes[\"data-val-length-max\"]);\n            Assert.Equal(\"Min length message\", attributes[\"data-val-minlength\"]);\n            Assert.Equal(2, attributes[\"data-val-minlength-min\"]);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/PreApplicationStartCodeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing System.Web.Routing;\nusing System.Web.Security;\nusing System.Web.UI;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Test\n{\n    public class PreApplicationStartCodeTest\n    {\n        [Fact]\n        public void StartTest()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                AppDomainUtils.SetPreAppStartStage();\n                PreApplicationStartCode.Start();\n                // Call a second time to ensure multiple calls do not cause issues\n                PreApplicationStartCode.Start();\n\n                Assert.False(RouteTable.Routes.RouteExistingFiles, \"We should not be setting RouteExistingFiles\");\n                Assert.Empty(RouteTable.Routes);\n\n                Assert.False(PageParser.EnableLongStringsAsResources);\n\n                string formsAuthLoginUrl = (string)typeof(FormsAuthentication).GetField(\"_LoginUrl\", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);\n                Assert.Null(formsAuthLoginUrl);\n            });\n        }\n\n        [Fact]\n        public void TestPreAppStartClass()\n        {\n            PreAppStartTestHelper.TestPreAppStartClass(typeof(PreApplicationStartCode));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/ScopeStorage/AspNetRequestScopeStorageProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.WebPages.Scope;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class AspNetRequestStorageProvider\n    {\n        [Fact]\n        public void AspNetStorageProviderReturnsApplicationStateBeforeAppStart()\n        {\n            // Arrange\n            var provider = GetProvider(() => false);\n\n            // Act and Assert\n            Assert.NotNull(provider.ApplicationScope);\n            Assert.NotNull(provider.GlobalScope);\n            Assert.Equal(provider.ApplicationScope, provider.GlobalScope);\n        }\n\n        [Fact]\n        public void AspNetStorageProviderThrowsWhenAccessingRequestScopeBeforeAppStart()\n        {\n            // Arrange\n            var provider = GetProvider(() => false);\n\n            // Act and Assert\n            Assert.Throws<InvalidOperationException>(\n                () => { var x = provider.RequestScope; },\n                \"RequestScope cannot be created when _AppStart is executing.\");\n        }\n\n        [Fact]\n        public void AspNetStorageProviderThrowsWhenAssigningScopeBeforeAppStart()\n        {\n            // Arrange\n            var provider = GetProvider(() => false);\n\n            // Act and Assert\n            Assert.Throws<InvalidOperationException>(\n                () => { provider.CurrentScope = new ScopeStorageDictionary(); },\n                \"Storage scopes cannot be created when _AppStart is executing.\");\n        }\n\n        [Fact]\n        public void AspNetStorageProviderReturnsRequestScopeAfterAppStart()\n        {\n            // Arrange\n            var provider = GetProvider();\n\n            // Act and Assert \n            Assert.NotNull(provider.RequestScope);\n            Assert.Equal(provider.RequestScope, provider.CurrentScope);\n        }\n\n        [Fact]\n        public void AspNetStorageRetrievesRequestScopeAfterSettingAnonymousScopes()\n        {\n            // Arrange\n            var provider = GetProvider();\n\n            // Act \n            var requestScope = provider.RequestScope;\n\n            var Scope = new ScopeStorageDictionary();\n            provider.CurrentScope = Scope;\n\n            Assert.Equal(provider.CurrentScope, Scope);\n            Assert.Equal(provider.RequestScope, requestScope);\n        }\n\n        [Fact]\n        public void AspNetStorageUsesApplicationScopeAsGlobalScope()\n        {\n            // Arrange\n            var provider = GetProvider();\n\n            // Act and Assert\n            Assert.Equal(provider.GlobalScope, provider.ApplicationScope);\n        }\n\n        private AspNetRequestScopeStorageProvider GetProvider(Func<bool> appStartExecuted = null)\n        {\n            Mock<HttpContextBase> context = new Mock<HttpContextBase>();\n            context.Setup(c => c.Items).Returns(new Dictionary<object, object>());\n            appStartExecuted = appStartExecuted ?? (() => true);\n\n            return new AspNetRequestScopeStorageProvider(context.Object, appStartExecuted);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/ScopeStorage/ScopeStorageDictionaryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.WebPages.Scope;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Test\n{\n    public class ScopeStorageDictionaryTest\n    {\n        [Fact]\n        public void ScopeStorageDictionaryLooksUpLocalValuesFirst()\n        {\n            // Arrange\n            var stateStorage = GetChainedStorageStateDictionary();\n\n            // Act and Assert\n            Assert.Equal(\"f2\", stateStorage[\"f\"]);\n        }\n\n        [Fact]\n        public void ScopeStorageDictionaryOverridesParentValuesWithLocalValues()\n        {\n            // Arrange\n            var stateStorage = GetChainedStorageStateDictionary();\n\n            // Act and Assert\n            Assert.Equal(\"a2\", stateStorage[\"a\"]);\n            Assert.Equal(\"d2\", stateStorage[\"d\"]);\n        }\n\n        [Fact]\n        public void ScopeStorageDictionaryLooksUpParentValuesWhenNotFoundLocally()\n        {\n            // Arrange\n            var stateStorage = GetChainedStorageStateDictionary();\n\n            // Act and Assert\n            Assert.Equal(\"c0\", stateStorage[\"c\"]);\n            Assert.Equal(\"b1\", stateStorage[\"b\"]);\n        }\n\n        [Fact]\n        public void ScopeStorageDictionaryTreatsNullAsOrdinaryValues()\n        {\n            // Arrange\n            var stateStorage = GetChainedStorageStateDictionary();\n            stateStorage[\"b\"] = null;\n\n            // Act and Assert\n            Assert.Null(stateStorage[\"b\"]);\n        }\n\n        [Fact]\n        public void ContainsKeyReturnsTrueIfItContainsKey()\n        {\n            // Arrange\n            var scopeStorage = GetChainedStorageStateDictionary();\n\n            // Act and Assert\n            Assert.True(scopeStorage.ContainsKey(\"f\"));\n        }\n\n        [Fact]\n        public void ContainsKeyReturnsTrueIfBaseContainsKey()\n        {\n            // Arrange\n            var scopeStorage = GetChainedStorageStateDictionary();\n\n            // Act and Assert\n            Assert.True(scopeStorage.ContainsKey(\"e\"));\n        }\n\n        [Fact]\n        public void ContainsKeyReturnsFalseIfItDoesNotContainKeyAndBaseIsNull()\n        {\n            // Arrange\n            var scopeStorage = new ScopeStorageDictionary() { { \"foo\", \"bar\" } };\n\n            // Act and Assert\n            Assert.False(scopeStorage.ContainsKey(\"baz\"));\n        }\n\n        [Fact]\n        public void CountReturnsCountFromCurrentAndBaseScope()\n        {\n            // Arrange\n            var scopeStorage = GetChainedStorageStateDictionary();\n\n            // Act and Assert\n            Assert.Equal(6, scopeStorage.Count);\n        }\n\n        [Fact]\n        public void ScopeStorageDictionaryGetsValuesFromCurrentAndBaseScope()\n        {\n            // Arrange\n            var scopeStorage = GetChainedStorageStateDictionary();\n\n            // Act and Assert\n            Assert.Equal(\"a2\", scopeStorage[\"a\"]);\n            Assert.Equal(\"b1\", scopeStorage[\"b\"]);\n            Assert.Equal(\"c0\", scopeStorage[\"c\"]);\n            Assert.Equal(\"d2\", scopeStorage[\"d\"]);\n            Assert.Equal(\"e1\", scopeStorage[\"e\"]);\n            Assert.Equal(\"f2\", scopeStorage[\"f\"]);\n        }\n\n        [Fact]\n        public void ClearRemovesAllItemsFromCurrentScope()\n        {\n            // Arrange\n            var dictionary = new ScopeStorageDictionary { { \"foo\", \"bar\" }, { \"foo2\", \"bar2\" } };\n\n            // Act\n            dictionary.Clear();\n\n            // Assert\n            Assert.Empty(dictionary);\n        }\n\n        [Fact]\n        public void ScopeStorageDictionaryIsNotReadOnly()\n        {\n            // Arrange\n            var dictionary = new ScopeStorageDictionary();\n\n            // Act and Assert\n            Assert.False(dictionary.IsReadOnly);\n        }\n\n        [Fact]\n        public void CopyToCopiesItemsToArrayAtSpecifiedIndex()\n        {\n            // Arrange\n            var dictionary = GetChainedStorageStateDictionary();\n            var array = new KeyValuePair<object, object>[8];\n\n            // Act\n            dictionary.CopyTo(array, 2);\n\n            // Assert\n            Assert.Equal(\"a\", array[2].Key);\n            Assert.Equal(\"a2\", array[2].Value);\n            Assert.Equal(\"f\", array[4].Key);\n            Assert.Equal(\"f2\", array[4].Value);\n            Assert.Equal(\"c\", array[7].Key);\n            Assert.Equal(\"c0\", array[7].Value);\n        }\n\n        private ScopeStorageDictionary GetChainedStorageStateDictionary()\n        {\n            var root = new ScopeStorageDictionary();\n            root[\"a\"] = \"a0\";\n            root[\"b\"] = \"b0\";\n            root[\"c\"] = \"c0\";\n\n            var firstGen = new ScopeStorageDictionary(baseScope: root);\n            firstGen[\"a\"] = \"a1\";\n            firstGen[\"b\"] = \"b1\";\n            firstGen[\"d\"] = \"d1\";\n            firstGen[\"e\"] = \"e1\";\n\n            var secondGen = new ScopeStorageDictionary(baseScope: firstGen);\n            secondGen[\"a\"] = \"a2\";\n            secondGen[\"d\"] = \"d2\";\n            secondGen[\"f\"] = \"f2\";\n\n            return secondGen;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/ScopeStorage/ScopeStorageKeyComparerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Web.WebPages.Scope;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Test\n{\n    public class ScopeStorageKeyComparerTest\n    {\n        [Fact]\n        public void ScopeStorageComparerPerformsCaseInsensitiveOrdinalComparisonForStrings()\n        {\n            // Arrange\n            var dictionary = new Dictionary<object, object>(ScopeStorageComparer.Instance) { { \"foo\", \"bar\" } };\n\n            // Act and Assert\n            Assert.Equal(\"bar\", dictionary[\"foo\"]);\n            Assert.Equal(dictionary[\"foo\"], dictionary[\"FOo\"]);\n        }\n\n        [Fact]\n        public void ScopeStorageComparerPerformsRegularComparisonForOtherTypes()\n        {\n            // Arrange\n            var stateStorage = new Dictionary<object, object> { { 4, \"4-value\" }, { new Person { ID = 10 }, \"person-value\" } };\n\n            // Act and Assert\n            Assert.Equal(\"4-value\", stateStorage[4]);\n            Assert.Equal(stateStorage[(int)8 / 2], stateStorage[4]);\n            Assert.Equal(\"person-value\", stateStorage[new Person { ID = 10 }]);\n        }\n\n        private class Person\n        {\n            public int ID { get; set; }\n\n            public override bool Equals(object o)\n            {\n                var other = o as Person;\n                return (other != null) && (other.ID == ID);\n            }\n\n            public override int GetHashCode()\n            {\n                return ID;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/ScopeStorage/WebConfigScopeStorageTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Linq;\nusing System.Reflection;\nusing System.Web.WebPages.Scope;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Test\n{\n    public class WebConfigScopeStorageTest\n    {\n        [Fact]\n        public void WebConfigScopeStorageReturnsConfigValue()\n        {\n            // Arrange\n            var stateStorage = GetWebConfigScopeStorage();\n\n            // Assert\n            Assert.Equal(\"bar1\", stateStorage[\"foo1\"]);\n            Assert.Equal(\"bar2\", stateStorage[\"foo2\"]);\n        }\n\n        [Fact]\n        public void WebConfigScopeStoragePerformsCaseInsensitiveKeyCompares()\n        {\n            // Arrange\n            var stateStorage = GetWebConfigScopeStorage();\n\n            // Assert\n            Assert.Equal(\"bar1\", stateStorage[\"FOO1\"]);\n            Assert.Equal(\"bar2\", stateStorage[\"FoO2\"]);\n        }\n\n        [Fact]\n        public void WebConfigScopeStorageThrowsWhenWriting()\n        {\n            // Arrange\n            var stateStorage = GetWebConfigScopeStorage();\n\n            // Act and Assert\n            Assert.Throws<NotSupportedException>(() => stateStorage[\"foo\"] = \"some value\", \"Storage scope is read only.\");\n            Assert.Throws<NotSupportedException>(() => stateStorage.Add(\"foo\", \"value\"), \"Storage scope is read only.\");\n            Assert.Throws<NotSupportedException>(() => stateStorage.Remove(\"foo\"), \"Storage scope is read only.\");\n            Assert.Throws<NotSupportedException>(() => stateStorage.Clear(), \"Storage scope is read only.\");\n            Assert.Throws<NotSupportedException>(() => stateStorage.Remove(new KeyValuePair<object, object>(\"foo\", \"bar\")), \"Storage scope is read only.\");\n        }\n\n        [Fact]\n        public void WebConfigStateAllowsEnumeratingOverConfigItems()\n        {\n            // Arrange\n            var dictionary = new Dictionary<string, string> { { \"a\", \"b\" }, { \"c\", \"d\" }, { \"x12\", \"y34\" } };\n            var stateStorage = GetWebConfigScopeStorage(dictionary);\n\n            // Act and Assert\n            Assert.True(dictionary.All(item => item.Value == stateStorage[item.Key] as string));\n        }\n\n        [Fact]\n        public void WebConfigScopeStorage_WithDuplicatesInUnderlyingSettings_ResolveToTheFirst()\n        {\n            // Arrange\n            // Start with a normal NameValueCollection\n            var values = new NameValueCollection();\n            values.Add(\"foo1\", \"bar1\");\n\n            // Now mess it up\n            // We are simulating what might happen in rare cases (probably during app-start and high load) - \n            // the AppSettings NameValueCollection gets messed up internally, however keep functioning normally.\n            // The duplication in AllKeys cause the bug https://aspnetwebstack.codeplex.com/workitem/912, \n            var entryType = typeof(NameObjectCollectionBase).GetNestedType(\"NameObjectEntry\", BindingFlags.NonPublic);\n            var entry = entryType.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic)[0].Invoke(new object[] { \"foo1\", \"bar2\" });\n            var entriesArray = (ArrayList)typeof(NameObjectCollectionBase).GetField(\"_entriesArray\", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(values);\n            entriesArray.Add(entry);\n            Assert.Equal(2, values.AllKeys.Length);\n\n            // Act - should not throw;\n            var stateStorage = new WebConfigScopeDictionary(values);\n\n            // Assert\n            Assert.Equal(\"bar1\", stateStorage[\"foo1\"]);\n        }\n\n        private WebConfigScopeDictionary GetWebConfigScopeStorage(IDictionary<string, string> values = null)\n        {\n            NameValueCollection collection = new NameValueCollection();\n            if (values == null)\n            {\n                collection.Add(\"foo1\", \"bar1\");\n                collection.Add(\"foo2\", \"bar2\");\n            }\n            else\n            {\n                foreach (var item in values)\n                {\n                    collection.Add(item.Key, item.Value);\n                }\n            }\n\n            return new WebConfigScopeDictionary(collection);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/System.Web.WebPages.Test.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props\" Condition=\"Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" />\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" />\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{0F4870DB-A799-4DBA-99DF-0D74BB52FEC2}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>System.Web.WebPages.Test</RootNamespace>\n    <AssemblyName>System.Web.WebPages.Test</AssemblyName>\n    <OutputPath>..\\..\\bin\\$(Configuration)\\Test\\</OutputPath>\n    <NuGetPackageImportStamp>\n    </NuGetPackageImportStamp>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Castle.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Castle.Core.5.1.1\\lib\\net462\\Castle.Core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"Moq, Version=4.18.0.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Moq.4.18.4\\lib\\net462\\Moq.dll</HintPath>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.ComponentModel.DataAnnotations\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Core\">\n      <RequiredTargetFramework>3.5</RequiredTargetFramework>\n    </Reference>\n    <Reference Include=\"System.Data.Linq\" />\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.abstractions.2.0.3\\lib\\net35\\xunit.abstractions.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.assert, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.assert.2.4.2\\lib\\netstandard1.1\\xunit.assert.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.core, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.core.2.4.2\\lib\\net452\\xunit.core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.execution.desktop, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.execution.2.4.2\\lib\\net452\\xunit.execution.desktop.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\Common\\CollectionExtensionsTest.cs\">\n      <Link>Common\\CollectionExtensionsTest.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\Common\\PathHelpersTest.cs\">\n      <Link>Common\\PathHelpersTest.cs</Link>\n    </Compile>\n    <Compile Include=\"ApplicationParts\\ApplicationPartTest.cs\" />\n    <Compile Include=\"ApplicationParts\\ApplicationPartRegistryTest.cs\" />\n    <Compile Include=\"ApplicationParts\\MimeMappingTest.cs\" />\n    <Compile Include=\"ApplicationParts\\ResourceHandlerTest.cs\" />\n    <Compile Include=\"ApplicationParts\\TestResourceAssembly.cs\" />\n    <Compile Include=\"Extensions\\StringWriterExtensionsTest.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\AntiForgeryTokenStoreTest.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\MachineKey45CryptoSystemTest.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\MockableTokenStore.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\MockableTokenValidator.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\TokenValidatorTest.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\MockableClaimUidExtractor.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\MockableCryptoSystem.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\HexUtil.cs\" />\n    <Compile Include=\"Helpers\\Claims\\ClaimTest.cs\" />\n    <Compile Include=\"Helpers\\Claims\\ClaimsIdentityTest.cs\" />\n    <Compile Include=\"Helpers\\Claims\\ClaimsIdentityConverterTest.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\ClaimUidExtractorTest.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\AntiForgeryTokenTest.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\AntiForgeryTokenSerializerTest.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\AntiForgeryWorkerTest.cs\" />\n    <Compile Include=\"Helpers\\AntiForgeryConfigTest.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\MockableAntiForgeryTokenSerializer.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\MockAntiForgeryConfig.cs\" />\n    <Compile Include=\"Helpers\\CryptoUtilTest.cs\" />\n    <Compile Include=\"Helpers\\Claims\\MockClaimsIdentity.cs\" />\n    <Compile Include=\"Helpers\\AntiXsrf\\BinaryBlobTest.cs\" />\n    <Compile Include=\"Html\\LabelHelperTest.cs\" />\n    <Compile Include=\"LatestRazorVersion.cs\" />\n    <Compile Include=\"Mvc\\ModelClientValidationMembershipPasswordRuleTest.cs\" />\n    <Compile Include=\"Mvc\\ModelClientValidationMaxLengthRuleTest.cs\" />\n    <Compile Include=\"Mvc\\ModelClientValidationMinLengthRuleTest.cs\" />\n    <Compile Include=\"Mvc\\ModelClientValidationStringLengthRuleTest.cs\" />\n    <Compile Include=\"Mvc\\UnobtrusiveValidationAttributesGeneratorTest.cs\" />\n    <Compile Include=\"Utils\\HtmlAttributePropertyHelperTest.cs\" />\n    <Compile Include=\"Utils\\PropertyHelperTest.cs\" />\n    <Compile Include=\"Utils\\SessionStateUtilTest.cs\" />\n    <Compile Include=\"Utils\\UrlRewriterHelperTest.cs\" />\n    <Compile Include=\"WebPage\\BrowserHelpersTest.cs\" />\n    <Compile Include=\"WebPage\\BrowserOverrideStoresTest.cs\" />\n    <Compile Include=\"WebPage\\CookieBrowserOverrideStoreTest.cs\" />\n    <Compile Include=\"WebPage\\DefaultDisplayModeTest.cs\" />\n    <Compile Include=\"WebPage\\DisplayInfoTest.cs\" />\n    <Compile Include=\"WebPage\\DisplayModeProviderTest.cs\" />\n    <Compile Include=\"Extensions\\HttpContextExtensionsTest.cs\" />\n    <Compile Include=\"Extensions\\HttpRequestExtensionsTest.cs\" />\n    <Compile Include=\"Extensions\\StringExtensionsTest.cs\" />\n    <Compile Include=\"Extensions\\HttpResponseExtensionsTest.cs\" />\n    <Compile Include=\"Helpers\\AntiForgeryTest.cs\" />\n    <Compile Include=\"Helpers\\UnvalidatedRequestValuesTest.cs\" />\n    <Compile Include=\"Html\\CheckBoxTest.cs\" />\n    <Compile Include=\"Html\\HtmlHelperFactory.cs\" />\n    <Compile Include=\"Html\\HtmlHelperTest.cs\" />\n    <Compile Include=\"Html\\InputHelperTest.cs\" />\n    <Compile Include=\"Html\\RadioButtonTest.cs\" />\n    <Compile Include=\"Html\\SelectHelperTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"Html\\TextAreaHelperTest.cs\">\n      <SubType>Code</SubType>\n    </Compile>\n    <Compile Include=\"Html\\ValidationHelperTest.cs\" />\n    <Compile Include=\"Instrumentation\\InstrumentationServiceTest.cs\" />\n    <Compile Include=\"Mvc\\HttpAntiForgeryExceptionTest.cs\" />\n    <Compile Include=\"Mvc\\TagBuilderTest.cs\" />\n    <Compile Include=\"PreApplicationStartCodeTest.cs\" />\n    <Compile Include=\"ScopeStorage\\AspNetRequestScopeStorageProviderTest.cs\" />\n    <Compile Include=\"ScopeStorage\\ScopeStorageDictionaryTest.cs\" />\n    <Compile Include=\"ScopeStorage\\ScopeStorageKeyComparerTest.cs\" />\n    <Compile Include=\"ScopeStorage\\WebConfigScopeStorageTest.cs\" />\n    <Compile Include=\"Utils\\CultureUtilTest.cs\" />\n    <Compile Include=\"Utils\\PathUtilTest.cs\" />\n    <Compile Include=\"Utils\\TestObjectFactory.cs\" />\n    <Compile Include=\"Utils\\TypeHelperTest.cs\" />\n    <Compile Include=\"Utils\\UrlUtilTest.cs\" />\n    <Compile Include=\"Validation\\ValidationHelperTest.cs\" />\n    <Compile Include=\"Validation\\ValidatorTest.cs\" />\n    <Compile Include=\"WebPage\\ApplicationStartPageTest.cs\" />\n    <Compile Include=\"WebPage\\DynamicHttpApplicationStateTest.cs\" />\n    <Compile Include=\"WebPage\\DynamicPageDataDictionaryTest.cs\" />\n    <Compile Include=\"WebPage\\FileExistenceCacheTest.cs\" />\n    <Compile Include=\"WebPage\\RequestBrowserOverrideStoreTest.cs\" />\n    <Compile Include=\"WebPage\\RequestResourceTrackerTest.cs\" />\n    <Compile Include=\"WebPage\\TemplateStackTest.cs\" />\n    <Compile Include=\"WebPage\\BuildManagerWrapperTest.cs\" />\n    <Compile Include=\"WebPage\\VirtualPathFactoryExtensionsTest.cs\" />\n    <Compile Include=\"WebPage\\VirtualPathFactoryManagerTest.cs\" />\n    <Compile Include=\"WebPage\\WebPageContextTest.cs\" />\n    <Compile Include=\"WebPage\\WebPageExecutingBaseTest.cs\" />\n    <Compile Include=\"WebPage\\WebPageHttpModuleTest.cs\" />\n    <Compile Include=\"WebPage\\WebPageHttpHandlerTest.cs\" />\n    <Compile Include=\"WebPage\\UrlDataTest.cs\" />\n    <Compile Include=\"WebPage\\StartPageTest.cs\" />\n    <Compile Include=\"WebPage\\Utils.cs\" />\n    <Compile Include=\"WebPage\\PageDataDictionaryTest.cs\" />\n    <Compile Include=\"WebPage\\WebPageRenderingBaseTest.cs\" />\n    <Compile Include=\"WebPage\\WebPageRouteTest.cs\" />\n    <Compile Include=\"WebPage\\RenderPageTest.cs\" />\n    <Compile Include=\"WebPage\\BuildManagerExceptionUtilTest.cs\" />\n    <Compile Include=\"WebPage\\LayoutTest.cs\" />\n    <Compile Include=\"WebPage\\WebPageTest.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Razor\\System.Web.Razor.csproj\">\n      <Project>{8F18041B-9410-4C36-A9C5-067813DF5F31}</Project>\n      <Name>System.Web.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.WebPages\\System.Web.WebPages.csproj\">\n      <Project>{76EFA9C5-8D7E-4FDF-B710-E20F8B6B00D2}</Project>\n      <Name>System.Web.WebPages</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\">\n      <Project>{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}</Project>\n      <Name>Microsoft.TestCommon</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"App.config\" />\n    <None Include=\"packages.config\" />\n    <None Include=\"TestFiles\\Deployed\\Bar\" />\n    <None Include=\"TestFiles\\Deployed\\Bar.foohtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Content Include=\"TestFiles\\Deployed\\Bar.cshtml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Service Include=\"{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Analyzer Include=\"..\\..\\packages\\xunit.analyzers.1.1.0\\analyzers\\dotnet\\cs\\xunit.analyzers.dll\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\n  <Target Name=\"EnsureNuGetPackageBuildImports\" BeforeTargets=\"PrepareForBuild\">\n    <PropertyGroup>\n      <ErrorText>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}.</ErrorText>\n    </PropertyGroup>\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props'))\" />\n  </Target>\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" />\n</Project>"
  },
  {
    "path": "test/System.Web.WebPages.Test/TestFiles/Deployed/Bar",
    "content": "﻿"
  },
  {
    "path": "test/System.Web.WebPages.Test/TestFiles/Deployed/Bar.cshtml",
    "content": "﻿"
  },
  {
    "path": "test/System.Web.WebPages.Test/TestFiles/Deployed/Bar.foohtml",
    "content": "﻿"
  },
  {
    "path": "test/System.Web.WebPages.Test/Utils/CultureUtilTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Threading;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class CultureUtilTest\n    {\n        [Fact]\n        [ReplaceCulture(Culture = \"es-PR\", UICulture = \"es-PR\")]\n        public void SetAutoCultureWithNoUserLanguagesDoesNothing()\n        {\n            // Arrange\n            var context = GetContextForSetCulture(null);\n            Thread thread = Thread.CurrentThread;\n            CultureInfo culture = thread.CurrentCulture;\n\n            // Act\n            CultureUtil.SetCulture(thread, context, \"auto\");\n\n            // Assert\n            Assert.Equal(culture, thread.CurrentCulture);\n        }\n\n        [Fact]\n        [ReplaceCulture(Culture = \"es-PR\", UICulture = \"es-PR\")]\n        public void SetAutoUICultureWithNoUserLanguagesDoesNothing()\n        {\n            // Arrange\n            var context = GetContextForSetCulture(null);\n            Thread thread = Thread.CurrentThread;\n            CultureInfo culture = thread.CurrentUICulture;\n\n            // Act\n            CultureUtil.SetUICulture(thread, context, \"auto\");\n\n            // Assert\n            Assert.Equal(culture, thread.CurrentUICulture);\n        }\n\n        [Fact]\n        [ReplaceCulture(Culture = \"es-PR\", UICulture = \"es-PR\")]\n        public void SetAutoCultureWithEmptyUserLanguagesDoesNothing()\n        {\n            // Arrange\n            var context = GetContextForSetCulture(Enumerable.Empty<string>());\n            Thread thread = Thread.CurrentThread;\n            CultureInfo culture = thread.CurrentCulture;\n\n            // Act\n            CultureUtil.SetCulture(thread, context, \"auto\");\n\n            // Assert\n            Assert.Equal(culture, thread.CurrentCulture);\n        }\n\n        [Fact]\n        [ReplaceCulture(Culture = \"es-PR\", UICulture = \"es-PR\")]\n        public void SetAutoUICultureWithEmptyUserLanguagesDoesNothing()\n        {\n            // Arrange\n            var context = GetContextForSetCulture(Enumerable.Empty<string>());\n            Thread thread = Thread.CurrentThread;\n            CultureInfo culture = thread.CurrentUICulture;\n\n            // Act\n            CultureUtil.SetUICulture(thread, context, \"auto\");\n\n            // Assert\n            Assert.Equal(culture, thread.CurrentUICulture);\n        }\n\n        [Fact]\n        [ReplaceCulture(Culture = \"es-PR\", UICulture = \"es-PR\")]\n        public void SetAutoCultureWithBlankUserLanguagesDoesNothing()\n        {\n            // Arrange\n            var context = GetContextForSetCulture(new[] { \" \" });\n            Thread thread = Thread.CurrentThread;\n            CultureInfo culture = thread.CurrentCulture;\n\n            // Act\n            CultureUtil.SetCulture(thread, context, \"auto\");\n\n            // Assert\n            Assert.Equal(culture, thread.CurrentCulture);\n        }\n\n        [Fact]\n        [ReplaceCulture(Culture = \"es-PR\", UICulture = \"es-PR\")]\n        public void SetAutoUICultureWithBlankUserLanguagesDoesNothing()\n        {\n            // Arrange\n            var context = GetContextForSetCulture(new[] { \" \" });\n            Thread thread = Thread.CurrentThread;\n            CultureInfo culture = thread.CurrentUICulture;\n\n            // Act\n            CultureUtil.SetUICulture(thread, context, \"auto\");\n\n            // Assert\n            Assert.Equal(culture, thread.CurrentUICulture);\n        }\n\n        [Fact]\n        [ReplaceCulture(Culture = \"es-PR\", UICulture = \"es-PR\")]\n        public void SetAutoCultureWithInvalidLanguageDoesNothing()\n        {\n            // Arrange\n            // \"sans-culture\" is an invalid culture name everywhere -- even on Windows 10.\n            var context = GetContextForSetCulture(new[] { \"sans-culture\", \"bb-BB\", \"cc-CC\" });\n            Thread thread = Thread.CurrentThread;\n            CultureInfo culture = thread.CurrentCulture;\n\n            // Act\n            CultureUtil.SetCulture(thread, context, \"auto\");\n\n            // Assert\n            Assert.Equal(culture, thread.CurrentCulture);\n        }\n\n        [Fact]\n        [ReplaceCulture(Culture = \"es-PR\", UICulture = \"es-PR\")]\n        public void SetAutoUICultureWithInvalidLanguageDoesNothing()\n        {\n            // Arrange\n            // \"sans-culture\" is an invalid culture name everywhere -- even on Windows 10.\n            var context = GetContextForSetCulture(new[] { \"sans-culture\", \"bb-BB\", \"cc-CC\" });\n            Thread thread = Thread.CurrentThread;\n            CultureInfo culture = thread.CurrentUICulture;\n\n            // Act\n            CultureUtil.SetUICulture(thread, context, \"auto\");\n\n            // Assert\n            Assert.Equal(culture, thread.CurrentUICulture);\n        }\n\n        [Fact]\n        [ReplaceCulture(Culture = \"es-PR\", UICulture = \"es-PR\")]\n        public void SetAutoCultureDetectsUserLanguageCulture()\n        {\n            // Arrange\n            var context = GetContextForSetCulture(new[] { \"en-GB\", \"en-US\", \"ar-eg\" });\n            Thread thread = Thread.CurrentThread;\n\n            // Act\n            CultureUtil.SetCulture(thread, context, \"auto\");\n\n            // Assert\n            Assert.Equal(CultureInfo.GetCultureInfo(\"en-GB\"), thread.CurrentCulture);\n            Assert.Equal(\"05/01/1979\", new DateTime(1979, 1, 5).ToString(\"d\", thread.CurrentCulture));\n        }\n\n        [Fact]\n        [ReplaceCulture(Culture = \"es-PR\", UICulture = \"es-PR\")]\n        public void SetAutoUICultureDetectsUserLanguageCulture()\n        {\n            // Arrange\n            var context = GetContextForSetCulture(new[] { \"en-GB\", \"en-US\", \"ar-eg\" });\n            Thread thread = Thread.CurrentThread;\n\n            // Act\n            CultureUtil.SetUICulture(thread, context, \"auto\");\n\n            // Assert\n            Assert.Equal(CultureInfo.GetCultureInfo(\"en-GB\"), thread.CurrentUICulture);\n            Assert.Equal(\"05/01/1979\", new DateTime(1979, 1, 5).ToString(\"d\", thread.CurrentUICulture));\n        }\n\n        [Fact]\n        [ReplaceCulture(Culture = \"es-PR\", UICulture = \"es-PR\")]\n        public void SetAutoCultureUserLanguageWithQParameterCulture()\n        {\n            // Arrange\n            var context = GetContextForSetCulture(new[] { \"en-GB;q=0.3\", \"en-US\", \"ar-eg;q=0.5\" });\n            Thread thread = Thread.CurrentThread;\n\n            // Act\n            CultureUtil.SetCulture(thread, context, \"auto\");\n\n            // Assert\n            Assert.Equal(CultureInfo.GetCultureInfo(\"en-GB\"), thread.CurrentCulture);\n            Assert.Equal(\"05/01/1979\", new DateTime(1979, 1, 5).ToString(\"d\", thread.CurrentCulture));\n        }\n\n        [Fact]\n        [ReplaceCulture(Culture = \"es-PR\", UICulture = \"es-PR\")]\n        public void SetAutoUICultureDetectsUserLanguageWithQParameterCulture()\n        {\n            // Arrange\n            var context = GetContextForSetCulture(new[] { \"en-GB;q=0.3\", \"en-US\", \"ar-eg;q=0.5\" });\n            Thread thread = Thread.CurrentThread;\n\n            // Act\n            CultureUtil.SetUICulture(thread, context, \"auto\");\n\n            // Assert\n            Assert.Equal(CultureInfo.GetCultureInfo(\"en-GB\"), thread.CurrentUICulture);\n            Assert.Equal(\"05/01/1979\", new DateTime(1979, 1, 5).ToString(\"d\", thread.CurrentUICulture));\n        }\n\n        [Fact]\n        [ReplaceCulture(Culture = \"es-PR\", UICulture = \"es-PR\")]\n        public void SetCultureWithInvalidCultureThrows()\n        {\n            // Arrange\n            var context = GetContextForSetCulture();\n            Thread thread = Thread.CurrentThread;\n\n            // Act and Assert\n            Assert.Throws<CultureNotFoundException>(() => CultureUtil.SetCulture(thread, context, \"sans-culture\"));\n        }\n\n        [Fact]\n        [ReplaceCulture(Culture = \"es-PR\", UICulture = \"es-PR\")]\n        public void SetUICultureWithInvalidCultureThrows()\n        {\n            // Arrange\n            var context = GetContextForSetCulture();\n            Thread thread = Thread.CurrentThread;\n\n            // Act and Assert\n            Assert.Throws<CultureNotFoundException>(() => CultureUtil.SetUICulture(thread, context, \"sans-culture\"));\n        }\n\n        [Fact]\n        [ReplaceCulture(Culture = \"es-PR\", UICulture = \"es-PR\")]\n        public void SetCultureWithValidCulture()\n        {\n            // Arrange\n            var context = GetContextForSetCulture();\n            Thread thread = Thread.CurrentThread;\n\n            // Act\n            CultureUtil.SetCulture(thread, context, \"en-GB\");\n\n            // Assert\n            Assert.Equal(CultureInfo.GetCultureInfo(\"en-GB\"), thread.CurrentCulture);\n            Assert.Equal(\"05/01/1979\", new DateTime(1979, 1, 5).ToString(\"d\", thread.CurrentCulture));\n        }\n\n        [Fact]\n        [ReplaceCulture(Culture = \"es-PR\", UICulture = \"es-PR\")]\n        public void SetUICultureWithValidCulture()\n        {\n            // Arrange\n            var context = GetContextForSetCulture();\n            Thread thread = Thread.CurrentThread;\n\n            // Act\n            CultureUtil.SetUICulture(thread, context, \"en-GB\");\n\n            // Assert\n            Assert.Equal(CultureInfo.GetCultureInfo(\"en-GB\"), thread.CurrentUICulture);\n            Assert.Equal(\"05/01/1979\", new DateTime(1979, 1, 5).ToString(\"d\", thread.CurrentUICulture));\n        }\n\n        private static HttpContextBase GetContextForSetCulture(IEnumerable<string> userLanguages = null)\n        {\n            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>();\n            contextMock.Setup(context => context.Request.UserLanguages).Returns(userLanguages == null ? null : userLanguages.ToArray());\n            return contextMock.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Utils/HtmlAttributePropertyHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Reflection;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Test\n{\n    public class HtmlAttributePropertyHelperTest\n    {\n        [Fact]\n        public void HtmlAttributePropertyHelperRenamesPropertyNames()\n        {\n            // Arrange\n            var anonymous = new { bar_baz = \"foo\" };\n            PropertyInfo property = anonymous.GetType().GetProperties().First();\n\n            // Act\n            HtmlAttributePropertyHelper helper = new HtmlAttributePropertyHelper(property);\n\n            // Assert\n            Assert.Equal(\"bar_baz\", property.Name);\n            Assert.Equal(\"bar-baz\", helper.Name);\n        }\n\n        [Fact]\n        public void HtmlAttributePropertyHelperReturnsNameCorrectly()\n        {\n            // Arrange\n            var anonymous = new { foo = \"bar\" };\n            PropertyInfo property = anonymous.GetType().GetProperties().First();\n\n            // Act\n            HtmlAttributePropertyHelper helper = new HtmlAttributePropertyHelper(property);\n\n            // Assert\n            Assert.Equal(\"foo\", property.Name);\n            Assert.Equal(\"foo\", helper.Name);\n        }\n\n        [Fact]\n        public void HtmlAttributePropertyHelperReturnsValueCorrectly()\n        {\n            // Arrange\n            var anonymous = new { bar = \"baz\" };\n            PropertyInfo property = anonymous.GetType().GetProperties().First();\n\n            // Act\n            HtmlAttributePropertyHelper helper = new HtmlAttributePropertyHelper(property);\n\n            // Assert\n            Assert.Equal(\"bar\", helper.Name);\n            Assert.Equal(\"baz\", helper.GetValue(anonymous));\n        }\n\n        [Fact]\n        public void HtmlAttributePropertyHelperReturnsValueCorrectlyForValueTypes()\n        {\n            // Arrange\n            var anonymous = new { foo = 32 };\n            PropertyInfo property = anonymous.GetType().GetProperties().First();\n\n            // Act\n            HtmlAttributePropertyHelper helper = new HtmlAttributePropertyHelper(property);\n\n            // Assert\n            Assert.Equal(\"foo\", helper.Name);\n            Assert.Equal(32, helper.GetValue(anonymous));\n        }\n\n        [Fact]\n        public void HtmlAttributePropertyHelperReturnsCachedPropertyHelper()\n        {\n            // Arrange\n            var anonymous = new { foo = \"bar\" };\n\n            // Act\n            PropertyHelper[] helpers1 = HtmlAttributePropertyHelper.GetProperties(anonymous);\n            PropertyHelper[] helpers2 = HtmlAttributePropertyHelper.GetProperties(anonymous);\n\n            // Assert\n            Assert.Single(helpers1);\n            Assert.ReferenceEquals(helpers1, helpers2);\n            Assert.ReferenceEquals(helpers1[0], helpers2[0]);\n        }\n\n        [Fact]\n        public void HtmlAttributeDoesNotShareCacheWithPropertyHelper()\n        {\n            // Arrange\n            var anonymous = new { bar_baz1 = \"foo\" };\n\n            // Act\n            PropertyHelper[] helpers1 = HtmlAttributePropertyHelper.GetProperties(anonymous);\n            PropertyHelper[] helpers2 = PropertyHelper.GetProperties(anonymous);\n\n            // Assert\n            PropertyHelper helper1 = Assert.Single(helpers1);\n            PropertyHelper helper2 = Assert.Single(helpers2);\n\n            Assert.NotEqual(helpers1, helpers2);\n            Assert.NotEqual(helper1, helper2);\n\n            Assert.IsType<HtmlAttributePropertyHelper>(helper1);\n            Assert.IsNotType<HtmlAttributePropertyHelper>(helper2);\n\n            Assert.Equal(\"bar-baz1\", helper1.Name);\n            Assert.Equal(\"bar_baz1\", helper2.Name);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Utils/PathUtilTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.Internal.Web.Utils;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Test\n{\n    public class PathUtilTest\n    {\n        [Fact]\n        public void IsSimpleNameTest()\n        {\n            Assert.True(PathUtil.IsSimpleName(\"Test.cshtml\"));\n            Assert.True(PathUtil.IsSimpleName(\"Test.Hello.cshtml\"));\n            Assert.False(PathUtil.IsSimpleName(\"~/myapp/Test/Hello.cshtml\"));\n            Assert.False(PathUtil.IsSimpleName(\"../Test/Hello.cshtml\"));\n            Assert.False(PathUtil.IsSimpleName(\"../../Test/Hello.cshtml\"));\n            Assert.False(PathUtil.IsSimpleName(\"/Test/Hello.cshtml\"));\n        }\n\n        [Fact]\n        public void GetExtensionForNullPathsReturnsNull()\n        {\n            // Arrange\n            string path = null;\n\n            // Act\n            string extension = PathUtil.GetExtension(path);\n\n            // Assert\n            Assert.Null(extension);\n        }\n\n        [Fact]\n        public void GetExtensionForEmptyPathsReturnsEmptyString()\n        {\n            // Arrange\n            string path = String.Empty;\n\n            // Act\n            string extension = PathUtil.GetExtension(path);\n\n            // Assert\n            Assert.Equal(0, extension.Length);\n        }\n\n        [Fact]\n        public void GetExtensionReturnsEmptyStringForPathsThatDoNotContainExtension()\n        {\n            // Arrange\n            string[] paths = new[] { \"SomePath\", \"SomePath/\", \"SomePath/MorePath\", \"SomePath/MorePath/\" };\n\n            // Act\n            var extensions = paths.Select(PathUtil.GetExtension);\n\n            // Assert\n            Assert.All(extensions, ext => Assert.Empty(ext));\n        }\n\n        [Fact]\n        public void GetExtensionReturnsEmptyStringForPathsContainingPathInfo()\n        {\n            // Arrange\n            string[] paths = new[] { \"SomePath.cshtml/\", \"SomePath.html/path/info\" };\n\n            // Act\n            var extensions = paths.Select(PathUtil.GetExtension);\n\n            // Assert\n            Assert.All(extensions, ext => Assert.Empty(ext));\n        }\n\n        [Fact]\n        public void GetExtensionReturnsEmptyStringForPathsTerminatingWithADot()\n        {\n            // Arrange\n            string[] paths = new[] { \"SomePath.\", \"SomeDirectory/SomePath/SomePath.\", \"SomeDirectory/SomePath.foo.\" };\n\n            // Act\n            var extensions = paths.Select(PathUtil.GetExtension);\n\n            // Assert\n            Assert.All(extensions, ext => Assert.Empty(ext));\n        }\n\n        [Fact]\n        public void GetExtensionReturnsExtensionsForPathsTerminatingInExtension()\n        {\n            // Arrange\n            string path1 = \"SomePath.cshtml\";\n            string path2 = \"SomeDir/SomePath.txt\";\n\n            // Act\n            string ext1 = PathUtil.GetExtension(path1);\n            string ext2 = PathUtil.GetExtension(path2);\n\n            // Assert\n            Assert.Equal(\".cshtml\", ext1);\n            Assert.Equal(\".txt\", ext2);\n        }\n\n        [Fact]\n        public void GetExtensionDoesNotThrowForPathsWithInvalidCharacters()\n        {\n            // Arrange\n            // Repro from test case in Bug 93828\n            string path = \"Insights/110786998958803%7C2.d24wA6Y3MiT2w8p3OT4yTw__.3600.1289415600-708897727%7CRLN-t1w9bXtKWZ_11osz15Rk_jY\";\n\n            // Act\n            string extension = PathUtil.GetExtension(path);\n\n            // Assert\n            Assert.Equal(\".1289415600-708897727%7CRLN-t1w9bXtKWZ_11osz15Rk_jY\", extension);\n        }\n\n        [Fact]\n        public void IsWithinAppRootNestedTest()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                var root = \"/subfolder1/website1\";\n                using (Utils.CreateHttpRuntime(root))\n                {\n                    Assert.True(PathUtil.IsWithinAppRoot(root, \"~/\"));\n                    Assert.True(PathUtil.IsWithinAppRoot(root, \"~/default.cshtml\"));\n                    Assert.True(PathUtil.IsWithinAppRoot(root, \"~/test/default.cshtml\"));\n                    Assert.True(PathUtil.IsWithinAppRoot(root, \"/subfolder1/website1\"));\n                    Assert.True(PathUtil.IsWithinAppRoot(root, \"/subfolder1/website1/\"));\n                    Assert.True(PathUtil.IsWithinAppRoot(root, \"/subfolder1/website1/default.cshtml\"));\n                    Assert.True(PathUtil.IsWithinAppRoot(root, \"/subfolder1/website1/test/default.cshtml\"));\n\n                    Assert.False(PathUtil.IsWithinAppRoot(root, \"/\"));\n                    Assert.False(PathUtil.IsWithinAppRoot(root, \"/subfolder1\"));\n                    Assert.False(PathUtil.IsWithinAppRoot(root, \"/subfolder1/\"));\n                    Assert.False(PathUtil.IsWithinAppRoot(root, \"/subfolder1/website2\"));\n                    Assert.False(PathUtil.IsWithinAppRoot(root, \"/subfolder2\"));\n                }\n            });\n        }\n\n        [Fact]\n        public void IsWithinAppRootTest()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                var root = \"/website1\";\n                using (Utils.CreateHttpRuntime(root))\n                {\n                    Assert.True(PathUtil.IsWithinAppRoot(root, \"~/\"));\n                    Assert.True(PathUtil.IsWithinAppRoot(root, \"~/default.cshtml\"));\n                    Assert.True(PathUtil.IsWithinAppRoot(root, \"~/test/default.cshtml\"));\n                    Assert.True(PathUtil.IsWithinAppRoot(root, \"/website1\"));\n                    Assert.True(PathUtil.IsWithinAppRoot(root, \"/website1/\"));\n                    Assert.True(PathUtil.IsWithinAppRoot(root, \"/website1/default.cshtml\"));\n                    Assert.True(PathUtil.IsWithinAppRoot(root, \"/website1/test/default.cshtml\"));\n\n                    Assert.False(PathUtil.IsWithinAppRoot(root, \"/\"));\n                    Assert.False(PathUtil.IsWithinAppRoot(root, \"/website2\"));\n                    Assert.False(PathUtil.IsWithinAppRoot(root, \"/subfolder1/\"));\n                }\n            });\n        }\n\n        private class TestVirtualPathUtility : IVirtualPathUtility\n        {\n            public string Combine(string basePath, string relativePath)\n            {\n                return basePath + \"/\" + relativePath;\n            }\n\n            public string ToAbsolute(string virtualPath)\n            {\n                return virtualPath;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Utils/PropertyHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Reflection;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Test\n{\n    public class PropertyHelperTest\n    {\n        [Fact]\n        public void PropertyHelperReturnsNameCorrectly()\n        {\n            // Arrange\n            var anonymous = new { foo = \"bar\" };\n            PropertyInfo property = anonymous.GetType().GetProperties().First();\n\n            // Act\n            PropertyHelper helper = new PropertyHelper(property);\n\n            // Assert\n            Assert.Equal(\"foo\", property.Name);\n            Assert.Equal(\"foo\", helper.Name);\n        }\n\n        [Fact]\n        public void PropertyHelperReturnsValueCorrectly()\n        {\n            // Arrange\n            var anonymous = new { bar = \"baz\" };\n            PropertyInfo property = anonymous.GetType().GetProperties().First();\n\n            // Act\n            PropertyHelper helper = new PropertyHelper(property);\n\n            // Assert\n            Assert.Equal(\"bar\", helper.Name);\n            Assert.Equal(\"baz\", helper.GetValue(anonymous));\n        }\n\n        [Fact]\n        public void PropertyHelperReturnsValueCorrectlyForValueTypes()\n        {\n            // Arrange\n            var anonymous = new { foo = 32 };\n            PropertyInfo property = anonymous.GetType().GetProperties().First();\n\n            // Act\n            PropertyHelper helper = new PropertyHelper(property);\n\n            // Assert\n            Assert.Equal(\"foo\", helper.Name);\n            Assert.Equal(32, helper.GetValue(anonymous));\n        }\n\n        [Fact]\n        public void PropertyHelperReturnsCachedPropertyHelper()\n        {\n            // Arrange\n            var anonymous = new { foo = \"bar\" };\n\n            // Act\n            PropertyHelper[] helpers1 = PropertyHelper.GetProperties(anonymous);\n            PropertyHelper[] helpers2 = PropertyHelper.GetProperties(anonymous);\n\n            // Assert\n            Assert.Single(helpers1);\n            Assert.ReferenceEquals(helpers1, helpers2);\n            Assert.ReferenceEquals(helpers1[0], helpers2[0]);\n        }\n\n        [Fact]\n        public void PropertyHelperDoesNotChangeUnderscores()\n        {\n            // Arrange\n            var anonymous = new { bar_baz2 = \"foo\" };\n\n            // Act + Assert\n            PropertyHelper helper = Assert.Single(PropertyHelper.GetProperties(anonymous));\n            Assert.Equal(\"bar_baz2\", helper.Name);\n        }\n\n        private class PrivateProperties\n        {\n            public int Prop1 { get; set; }\n            protected int Prop2 { get; set; }\n            private int Prop3 { get; set; }\n        }\n\n        [Fact]\n        public void PropertyHelperDoesNotFindPrivateProperties()\n        {\n            // Arrange\n            var anonymous = new PrivateProperties();\n\n            // Act + Assert\n            PropertyHelper helper = Assert.Single(PropertyHelper.GetProperties(anonymous));\n            Assert.Equal(\"Prop1\", helper.Name);\n        }\n\n        private class Static\n        {\n            public static int Prop2 { get; set; }\n            public int Prop5 { get; set; }\n        }\n\n        [Fact]\n        public void PropertyHelperDoesNotFindStaticProperties()\n        {\n            // Arrange\n            var anonymous = new Static();\n\n            // Act + Assert\n            PropertyHelper helper = Assert.Single(PropertyHelper.GetProperties(anonymous));\n            Assert.Equal(\"Prop5\", helper.Name);\n        }\n\n        private class SetOnly\n        {\n            public int Prop2 { set { } }\n            public int Prop6 { get; set; }\n        }\n\n        [Fact]\n        public void PropertyHelperDoesNotFindSetOnlyProperties()\n        {\n            // Arrange\n            var anonymous = new SetOnly();\n\n            // Act + Assert\n            PropertyHelper helper = Assert.Single(PropertyHelper.GetProperties(anonymous));\n            Assert.Equal(\"Prop6\", helper.Name);\n        }\n\n        private struct MyProperties\n        {\n            public int IntProp { get; set; }\n            public string StringProp { get; set; }\n        }\n\n        [Fact]\n        public void PropertyHelperWorksForStruct()\n        {\n            // Arrange\n            var anonymous = new MyProperties();\n\n            anonymous.IntProp = 3;\n            anonymous.StringProp = \"Five\";\n\n            // Act + Assert\n            PropertyHelper helper1 = Assert.Single(PropertyHelper.GetProperties(anonymous), prop => prop.Name == \"IntProp\");\n            PropertyHelper helper2 = Assert.Single(PropertyHelper.GetProperties(anonymous), prop => prop.Name == \"StringProp\");\n            Assert.Equal(3, helper1.GetValue(anonymous));\n            Assert.Equal(\"Five\", helper2.GetValue(anonymous));\n        }\n\n        public class BaseClass\n        {\n            public string PropA { get; set; }\n\n            protected string PropProtected { get; set; }\n        }\n\n        public class DerivedClass : BaseClass\n        {\n            public string PropB { get; set; }\n        }\n\n        public class BaseClassWithVirtual\n        {\n            public virtual string PropA { get; set; }\n            public string PropB { get; set; }\n        }\n\n        public class DerivedClassWithNew : BaseClassWithVirtual\n        {\n            public new string PropB { get { return \"Newed\"; } }\n        }\n\n        public class DerivedClassWithOverride : BaseClassWithVirtual\n        {\n            public override string PropA { get { return \"Overriden\"; } }\n        }\n\n        [Fact]\n        public void PropertyHelperForDerivedClass()\n        {\n            // Arrange\n            object derived = new DerivedClass { PropA = \"propAValue\", PropB = \"propBValue\" };\n\n            // Act\n            PropertyHelper[] helpers = PropertyHelper.GetProperties(derived).ToArray();\n\n            // Assert\n            Assert.NotNull(helpers);\n            Assert.Equal(2, helpers.Length);\n\n            PropertyHelper propAHelper = Assert.Single(helpers, h => h.Name == \"PropA\");\n            PropertyHelper propBHelper = Assert.Single(helpers, h => h.Name == \"PropB\");\n\n            Assert.Equal(\"propAValue\", propAHelper.GetValue(derived));\n            Assert.Equal(\"propBValue\", propBHelper.GetValue(derived));\n        }\n\n        [Fact]\n        public void PropertyHelperForDerivedClassWithNew()\n        {\n            // Arrange\n            object derived = new DerivedClassWithNew { PropA = \"propAValue\" };\n\n            // Act\n            PropertyHelper[] helpers = PropertyHelper.GetProperties(derived).ToArray();\n\n            // Assert\n            Assert.NotNull(helpers);\n            Assert.Equal(2, helpers.Length);\n\n            PropertyHelper propAHelper = Assert.Single(helpers, h => h.Name == \"PropA\");\n            PropertyHelper propBHelper = Assert.Single(helpers, h => h.Name == \"PropB\");\n\n            Assert.Equal(\"propAValue\", propAHelper.GetValue(derived));\n            Assert.Equal(\"Newed\", propBHelper.GetValue(derived));\n        }\n\n        [Fact]\n        public void PropertyHelperForDerivedWithVirtual()\n        {\n            // Arrange\n            object derived = new DerivedClassWithOverride { PropA = \"propAValue\", PropB = \"propBValue\" };\n\n            // Act\n            PropertyHelper[] helpers = PropertyHelper.GetProperties(derived).ToArray();\n\n            // Assert\n            Assert.NotNull(helpers);\n            Assert.Equal(2, helpers.Length);\n\n            PropertyHelper propAHelper = Assert.Single(helpers, h => h.Name == \"PropA\");\n            PropertyHelper propBHelper = Assert.Single(helpers, h => h.Name == \"PropB\");\n\n            Assert.Equal(\"Overriden\", propAHelper.GetValue(derived));\n            Assert.Equal(\"propBValue\", propBHelper.GetValue(derived));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Utils/SessionStateUtilTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Web.Razor;\nusing System.Web.SessionState;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class SessionStateUtilTest\n    {\n        [Fact]\n        public void SetUpSessionStateDoesNotInvokeSessionStateBehaviorIfNoPageHasDirective()\n        {\n            // Arrange\n            var page = new Mock<WebPage>(MockBehavior.Strict);\n            var startPage = new Mock<StartPage>(MockBehavior.Strict);\n            var webPageHttpHandler = new WebPageHttpHandler(page.Object, startPage: new Lazy<WebPageRenderingBase>(() => startPage.Object));\n            var context = new Mock<HttpContextBase>(MockBehavior.Strict);\n\n            // Act\n            SessionStateUtil.SetUpSessionState(context.Object, webPageHttpHandler, new ConcurrentDictionary<Type, SessionStateBehavior?>());\n\n            // Assert\n            context.Verify(c => c.SetSessionStateBehavior(It.IsAny<SessionStateBehavior>()), Times.Never());\n        }\n\n        [Fact]\n        public void SetUpSessionStateUsesSessionStateValueFromRequestingPageIfAvailable()\n        {\n            // Arrange\n            var page = new DisabledSessionWebPage();\n            var webPageHttpHandler = new WebPageHttpHandler(page, startPage: null);\n            var context = new Mock<HttpContextBase>(MockBehavior.Strict);\n            context.Setup(c => c.SetSessionStateBehavior(SessionStateBehavior.Disabled)).Verifiable();\n\n            // Act\n            SessionStateUtil.SetUpSessionState(context.Object, webPageHttpHandler, new ConcurrentDictionary<Type, SessionStateBehavior?>());\n\n            // Assert\n            context.Verify();\n        }\n\n        [Fact]\n        public void SetUpSessionStateUsesSessionStateValueFromStartPageHierarchy()\n        {\n            // Arrange\n            var page = new Mock<WebPage>(MockBehavior.Strict);\n            var startPage = new DefaultSessionWebPage\n            {\n                ChildPage = new ReadOnlySessionWebPage()\n            };\n            var webPageHttpHandler = new WebPageHttpHandler(page.Object, startPage: new Lazy<WebPageRenderingBase>(() => startPage));\n            var context = new Mock<HttpContextBase>(MockBehavior.Strict);\n            context.Setup(c => c.SetSessionStateBehavior(SessionStateBehavior.ReadOnly)).Verifiable();\n\n            // Act\n            SessionStateUtil.SetUpSessionState(context.Object, webPageHttpHandler, new ConcurrentDictionary<Type, SessionStateBehavior?>());\n\n            // Assert\n            context.Verify();\n        }\n\n        [Fact]\n        public void SetUpSessionStateThrowsIfSessionStateValueIsInvalid()\n        {\n            // Arrange\n            var page = new Mock<WebPage>(MockBehavior.Strict);\n            var startPage = new InvalidSessionState();\n            var webPageHttpHandler = new WebPageHttpHandler(page.Object, startPage: new Lazy<WebPageRenderingBase>(() => startPage));\n            var context = new Mock<HttpContextBase>(MockBehavior.Strict);\n\n            // Act\n            Assert.Throws<ArgumentException>(() => SessionStateUtil.SetUpSessionState(context.Object, webPageHttpHandler, new ConcurrentDictionary<Type, SessionStateBehavior?>()),\n                \"Value \\\"jabberwocky\\\" specified in \\\"~/_Invalid.cshtml\\\" is an invalid value for the SessionState directive. Possible values are: \\\"Default, Required, ReadOnly, Disabled\\\".\");\n        }\n\n        [Fact]\n        public void SetUpSessionStateThrowsIfMultipleSessionStateValueIsInvalid()\n        {\n            // Arrange\n            var page = new PageWithMultipleSesionStateAttributes();\n            var webPageHttpHandler = new WebPageHttpHandler(page, startPage: null);\n            var context = new Mock<HttpContextBase>(MockBehavior.Strict);\n\n            // Act\n            Assert.Throws<InvalidOperationException>(() => SessionStateUtil.SetUpSessionState(context.Object, webPageHttpHandler, new ConcurrentDictionary<Type, SessionStateBehavior?>()),\n                \"At most one SessionState value can be declared per page.\");\n        }\n\n        [Fact]\n        public void SetUpSessionStateUsesCache()\n        {\n            // Arrange\n            var page = new PageWithBadAttribute();\n            var webPageHttpHandler = new WebPageHttpHandler(page, startPage: null);\n            var context = new Mock<HttpContextBase>(MockBehavior.Strict);\n            var dictionary = new ConcurrentDictionary<Type, SessionStateBehavior?>();\n            dictionary.TryAdd(webPageHttpHandler.GetType(), SessionStateBehavior.Default);\n            context.Setup(c => c.SetSessionStateBehavior(SessionStateBehavior.Default)).Verifiable();\n\n            // Act\n            SessionStateUtil.SetUpSessionState(context.Object, webPageHttpHandler, dictionary);\n\n            // Assert\n            context.Verify();\n            Assert.Throws<Exception>(() => page.GetType().GetCustomAttributes(inherit: false), \"Can't call me!\");\n        }\n\n        [RazorDirective(\"sessionstate\", \"disabled\")]\n        private sealed class DisabledSessionWebPage : WebPage\n        {\n            public override void Execute()\n            {\n                throw new NotSupportedException();\n            }\n        }\n\n        [RazorDirective(\"sessionstate\", \"ReadOnly\")]\n        private sealed class ReadOnlySessionWebPage : StartPage\n        {\n            public override void Execute()\n            {\n                throw new NotSupportedException();\n            }\n        }\n\n        [RazorDirective(\"SessionState\", \"Default\")]\n        private sealed class DefaultSessionWebPage : StartPage\n        {\n            public override void Execute()\n            {\n                throw new NotSupportedException();\n            }\n        }\n\n        [RazorDirective(\"SessionState\", \"jabberwocky\")]\n        private sealed class InvalidSessionState : StartPage\n        {\n            public override string VirtualPath\n            {\n                get\n                {\n                    return \"~/_Invalid.cshtml\";\n                }\n                set\n                {\n                    VirtualPath = value;\n                }\n            }\n            public override void Execute()\n            {\n                throw new NotSupportedException();\n            }\n        }\n\n        private sealed class BadAttribute : Attribute\n        {\n            public BadAttribute()\n            {\n                throw new Exception(\"Can't call me!\");\n            }\n        }\n\n        [RazorDirective(\"SessionState\", \"Default\"), Bad]\n        private sealed class PageWithBadAttribute : WebPage\n        {\n            public override void Execute()\n            {\n                throw new NotSupportedException();\n            }\n        }\n\n        [RazorDirective(\"SessionState\", \"Disabled\"), RazorDirective(\"SessionState\", \"ReadOnly\")]\n        private sealed class PageWithMultipleSesionStateAttributes : WebPage\n        {\n            public override void Execute()\n            {\n                throw new NotSupportedException();\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Utils/TestObjectFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class HashVirtualPathFactory : IVirtualPathFactory\n    {\n        private IDictionary<string, object> _pages;\n\n        public HashVirtualPathFactory(params WebPageExecutingBase[] pages)\n        {\n            _pages = pages.ToDictionary(p => p.VirtualPath, p => (object)p, StringComparer.OrdinalIgnoreCase);\n        }\n\n        public bool Exists(string virtualPath)\n        {\n            return _pages.ContainsKey(virtualPath);\n        }\n\n        public object CreateInstance(string virtualPath)\n        {\n            object value;\n            if (_pages.TryGetValue(virtualPath, out value))\n            {\n                return value;\n            }\n            return null;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Utils/TypeHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Test\n{\n    public class TypeHelperTest\n    {\n        [Fact]\n        public void ObjectToDictionaryWithNullObjectReturnsEmptyDictionary()\n        {\n            // Arrange\n            object dict = null;\n\n            IDictionary<string, object> dictValues = TypeHelper.ObjectToDictionary(dict);\n\n            Assert.NotNull(dictValues);\n            Assert.Equal(0, dictValues.Count);\n        }\n\n        [Fact]\n        public void ObjectToDictionaryWithPlainObjectTypeReturnsEmptyDictionary()\n        {\n            // Arrange\n            object dict = new object();\n\n            // Act\n            IDictionary<string, object> dictValues = TypeHelper.ObjectToDictionary(dict);\n\n            // Assert\n            Assert.NotNull(dictValues);\n            Assert.Equal(0, dictValues.Count);\n        }\n\n        [Fact]\n        public void ObjectToDictionaryWithPrimitiveTypeLooksUpPublicProperties()\n        {\n            // Arrange\n            object dict = \"test\";\n\n            // Act\n            IDictionary<string, object> dictValues = TypeHelper.ObjectToDictionary(dict);\n\n            // Assert\n            Assert.NotNull(dictValues);\n            Assert.Equal(1, dictValues.Count);\n            Assert.Equal(4, dictValues[\"Length\"]);\n        }\n\n        [Fact]\n        public void ObjectToDictionaryWithAnonymousTypeLooksUpProperties()\n        {\n            // Arrange\n            object dict = new { test = \"value\", other = 1 };\n\n            // Act\n            IDictionary<string, object> dictValues = TypeHelper.ObjectToDictionary(dict);\n\n            // Assert\n            Assert.NotNull(dictValues);\n            Assert.Equal(2, dictValues.Count);\n            Assert.Equal(\"value\", dictValues[\"test\"]);\n            Assert.Equal(1, dictValues[\"other\"]);\n        }\n\n        [Fact]\n        public void ObjectToDictionaryReturnsCaseInsensitiveDictionary()\n        {\n            // Arrange\n            object dict = new { TEST = \"value\", oThEr = 1 };\n\n            // Act\n            IDictionary<string, object> dictValues = TypeHelper.ObjectToDictionary(dict);\n\n            // Assert\n            Assert.NotNull(dictValues);\n            Assert.Equal(2, dictValues.Count);\n            Assert.Equal(\"value\", dictValues[\"test\"]);\n            Assert.Equal(1, dictValues[\"other\"]);\n        }\n\n        [Fact]\n        public void AddAnonymousTypeObjectToDictionaryTest()\n        {\n            IDictionary<string, object> d = new Dictionary<string, object>();\n            d.Add(\"X\", \"Xvalue\");\n            TypeHelper.AddAnonymousObjectToDictionary(d, new { A = \"a\", B = \"b\" });\n            Assert.Equal(\"Xvalue\", d[\"X\"]);\n            Assert.Equal(\"a\", d[\"A\"]);\n            Assert.Equal(\"b\", d[\"B\"]);\n        }\n\n        [Fact]\n        public void IsAnonymousTypeTest()\n        {\n            Assert.False(TypeHelper.IsAnonymousType(typeof(object)));\n            Assert.False(TypeHelper.IsAnonymousType(typeof(string)));\n            Assert.False(TypeHelper.IsAnonymousType(typeof(IDictionary<object, object>)));\n            Assert.True(TypeHelper.IsAnonymousType((new { A = \"a\", B = \"b\" }.GetType())));\n            var x = \"x\";\n            var y = \"y\";\n            Assert.True(TypeHelper.IsAnonymousType((new { x, y }.GetType())));\n        }\n\n        [Fact]\n        public void IsAnonymousTypeNullTest()\n        {\n            Assert.ThrowsArgumentNull(() => TypeHelper.IsAnonymousType(null), \"type\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Utils/UrlRewriterHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class UrlRewriterHelperTest\n    {\n        [Fact]\n        public void WasRequestRewritten_FalseIfUrlRewriterIsTurnedOff()\n        {\n            // Arrange\n            UrlRewriterHelper helper = new UrlRewriterHelper();\n            UrlRewriteMocks request = CreateMockContext(isUrlRewriteOnForServer: false, isUrlRewriteOnForRequest: false);\n\n            // Act\n            bool result = helper.WasRequestRewritten(request.Context.Object);\n\n            // Assert\n            Assert.False(result);\n            request.WorkerRequest.Verify();\n            request.WorkerRequest.Verify(wr => wr.GetServerVariable(UrlRewriterHelper.UrlWasRewrittenServerVar), Times.Never());\n        }\n\n        [Fact]\n        public void WasRequestRewritten_FalseIfUrlRewriterIsTurnedOnButRequestWasNotRewritten()\n        {\n            // Arrange\n            UrlRewriterHelper helper = new UrlRewriterHelper();\n            UrlRewriteMocks request = CreateMockContext(isUrlRewriteOnForServer: true, isUrlRewriteOnForRequest: false);\n\n            // Act\n            bool result = helper.WasRequestRewritten(request.Context.Object);\n\n            // Assert\n            Assert.False(result);\n            request.WorkerRequest.Verify();\n        }\n\n        [Fact]\n        public void WasRequestRewritten_TrueIfUrlRewriterIsTurnedOnAndRequestWasRewritten()\n        {\n            // Arrange\n            UrlRewriterHelper helper = new UrlRewriterHelper();\n            UrlRewriteMocks request = CreateMockContext(isUrlRewriteOnForServer: true, isUrlRewriteOnForRequest: true);\n\n            // Act\n            bool result = helper.WasRequestRewritten(request.Context.Object);\n\n            // Assert\n            Assert.True(result);\n            request.WorkerRequest.Verify();\n        }\n\n        [Fact]\n        public void WasRequestRewritten_ChecksIfUrlRewriterIsTurnedOnOnlyOnce()\n        {\n            // Arrange\n            UrlRewriterHelper helper = new UrlRewriterHelper();\n            UrlRewriteMocks request1 = CreateMockContext(isUrlRewriteOnForServer: false, isUrlRewriteOnForRequest: false);\n            UrlRewriteMocks request2 = CreateMockContext(isUrlRewriteOnForServer: false, isUrlRewriteOnForRequest: false);\n\n            // Act\n            bool result1 = helper.WasRequestRewritten(request1.Context.Object);\n            bool result2 = helper.WasRequestRewritten(request2.Context.Object);\n\n            // Assert\n            request1.WorkerRequest.Verify(c => c.GetServerVariable(UrlRewriterHelper.UrlRewriterEnabledServerVar), Times.Once());\n            request2.WorkerRequest.Verify(c => c.GetServerVariable(UrlRewriterHelper.UrlRewriterEnabledServerVar), Times.Never());\n            Assert.False(result1);\n            Assert.False(result2);\n        }\n\n        [Fact]\n        public void WasRequestRewritten_ChecksRequest_OnlyOnce_Positive()\n        {\n            // Arrange\n            UrlRewriterHelper helper = new UrlRewriterHelper();\n            UrlRewriteMocks request1 = CreateMockContext(isUrlRewriteOnForServer: true, isUrlRewriteOnForRequest: true);\n\n            // Act\n            bool result1 = helper.WasRequestRewritten(request1.Context.Object);\n            bool result2 = helper.WasRequestRewritten(request1.Context.Object);\n\n            // Assert\n            request1.WorkerRequest.Verify(c => c.GetServerVariable(UrlRewriterHelper.UrlWasRewrittenServerVar), Times.Once());\n            Assert.True(result1);\n            Assert.True(result2);\n        }\n\n        [Fact]\n        public void WasRequestRewritten_ChecksRequest_OnlyOnce_Negative()\n        {\n            // Arrange\n            UrlRewriterHelper helper = new UrlRewriterHelper();\n            UrlRewriteMocks request1 = CreateMockContext(isUrlRewriteOnForServer: true, isUrlRewriteOnForRequest: false);\n\n            // Act\n            bool result1 = helper.WasRequestRewritten(request1.Context.Object);\n            bool result2 = helper.WasRequestRewritten(request1.Context.Object);\n\n            // Assert\n            request1.WorkerRequest.Verify(c => c.GetServerVariable(UrlRewriterHelper.UrlWasRewrittenServerVar), Times.Once());\n            Assert.False(result1);\n            Assert.False(result2);\n        }\n\n        private UrlRewriteMocks CreateMockContext(bool isUrlRewriteOnForServer, bool isUrlRewriteOnForRequest)\n        {\n            Mock<HttpContextBase> mockContext = new Mock<HttpContextBase>();\n\n            Mock<HttpWorkerRequest> mockWorkerRequest = new Mock<HttpWorkerRequest>();\n            mockContext.As<IServiceProvider>().Setup(sp => sp.GetService(typeof(HttpWorkerRequest))).Returns(mockWorkerRequest.Object);\n\n            if (isUrlRewriteOnForServer)\n            {\n                mockWorkerRequest.Setup(wr => wr.GetServerVariable(UrlRewriterHelper.UrlRewriterEnabledServerVar)).Returns(\"On!\").Verifiable();\n            }\n            else\n            {\n                mockWorkerRequest.Setup(wr => wr.GetServerVariable(UrlRewriterHelper.UrlRewriterEnabledServerVar)).Returns((string)null).Verifiable();\n            }\n\n            if (isUrlRewriteOnForRequest)\n            {\n                mockWorkerRequest.Setup(wr => wr.GetServerVariable(UrlRewriterHelper.UrlWasRewrittenServerVar)).Returns(\"Yup!\").Verifiable();\n            }\n            else\n            {\n                // this won't be called if rewrite is off for the server\n                mockWorkerRequest.Setup(wr => wr.GetServerVariable(UrlRewriterHelper.UrlWasRewrittenServerVar)).Returns((string)null);\n            }\n\n            NameValueCollection serverVars = new NameValueCollection();\n            mockContext.Setup(c => c.Request.ServerVariables).Returns(serverVars);\n            mockContext.Setup(c => c.Request.ApplicationPath).Returns(\"/myapp\");\n\n            mockContext.Setup(c => c.Items).Returns(new HybridDictionary());\n\n            return new UrlRewriteMocks()\n            {\n                Context = mockContext,\n                WorkerRequest = mockWorkerRequest,\n            };\n        }\n\n        private class UrlRewriteMocks\n        {\n            public Mock<HttpContextBase> Context { get; set; }\n            public Mock<HttpWorkerRequest> WorkerRequest { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Utils/UrlUtilTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class UrlUtilTest\n    {\n        [Fact]\n        public void GenerateClientUrl_ResolvesVirtualPath_WithApplicationAtRoot()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                using (IDisposable _ = Utils.CreateHttpContext(\"default.aspx\", \"http://localhost/\"),\n                                   __ = Utils.CreateHttpRuntime(\"/\"))\n                {\n                    // Arrange\n                    var vpath = \"~/\";\n                    var href = \"~/world/test.aspx\";\n                    var expected = \"/world/test.aspx\";\n                    var context = new HttpContextWrapper(HttpContext.Current);\n                    var page = new MockPage { VirtualPath = vpath, Context = context };\n\n                    // Act\n                    var actual1 = UrlUtil.GenerateClientUrl(context, vpath, href);\n                    var actual2 = page.Href(href);\n\n                    // Assert\n                    Assert.Equal(expected, actual1);\n                    Assert.Equal(expected, actual2);\n                }\n            });\n        }\n\n        [Fact]\n        public void GenerateClientUrl_ResolvesVirtualPathWithSubfolder_WithApplicationPath()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                using (IDisposable _ = Utils.CreateHttpContext(\"default.aspx\", \"http://localhost/WebSite1/subfolder1/default.aspx\"),\n                                   __ = Utils.CreateHttpRuntime(\"/WebSite1/\"))\n                {\n                    // Arrange\n                    var vpath = \"~/subfolder1/default.aspx\";\n                    var href = \"~/world/test.aspx\";\n                    var expected = \"/WebSite1/world/test.aspx\";\n                    var context = new HttpContextWrapper(HttpContext.Current);\n                    var page = new MockPage() { VirtualPath = vpath, Context = context };\n\n                    // Act\n                    var actual1 = UrlUtil.GenerateClientUrl(context, vpath, href);\n                    var actual2 = page.Href(href);\n\n                    // Assert\n                    Assert.Equal(expected, actual1);\n                    Assert.Equal(expected, actual2);\n                }\n            });\n        }\n\n        [Fact]\n        public void GenerateClientUrl_ResolvesVirtualPath_WithApplicationPath()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                using (IDisposable _ = Utils.CreateHttpContext(\"default.aspx\", \"http://localhost/WebSite1/default.aspx\"),\n                                   __ = Utils.CreateHttpRuntime(\"/WebSite1/\"))\n                {\n                    // Arrange\n                    var vpath = \"~/default.aspx\";\n                    var href = \"~/world/test.aspx\";\n                    var expected = \"/WebSite1/world/test.aspx\";\n                    var context = new HttpContextWrapper(HttpContext.Current);\n                    var page = new MockPage() { VirtualPath = vpath, Context = context };\n\n                    // Act\n                    var actual1 = UrlUtil.GenerateClientUrl(context, vpath, href);\n                    var actual2 = page.Href(href);\n\n                    // Assert\n                    Assert.Equal(expected, actual1);\n                    Assert.Equal(expected, actual2);\n                }\n            });\n        }\n\n        [Fact]\n        public void GenerateClientUrl_ResolvesRelativePathToSubfolder_WithApplicationPath()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                using (IDisposable _ = Utils.CreateHttpContext(\"default.aspx\", \"http://localhost/WebSite1/subfolder1/default.aspx\"),\n                                   __ = Utils.CreateHttpRuntime(\"/WebSite1/\"))\n                {\n                    // Arrange\n                    var vpath = \"~/subfolder1/default.aspx\";\n                    var href = \"world/test.aspx\";\n                    var expected = \"/WebSite1/subfolder1/world/test.aspx\";\n                    var context = new HttpContextWrapper(HttpContext.Current);\n                    var page = new MockPage() { VirtualPath = vpath, Context = context };\n\n                    // Act\n                    var actual1 = UrlUtil.GenerateClientUrl(context, vpath, href);\n                    var actual2 = page.Href(href);\n\n                    // Assert\n                    Assert.Equal(expected, actual1);\n                    Assert.Equal(expected, actual2);\n                }\n            });\n        }\n\n        [Fact]\n        public void GenerateClientUrl_ResolvesVirtualPath_WithUrlRewrite()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                // Arrange\n                var vpath = \"~/subfolder1/default.aspx\";\n                var href = \"world/test.aspx\";\n                var expected = \"/subfolder1/world/test.aspx\";\n                var contextMock = GetMockHttpContext(true);\n                contextMock.Setup(c => c.Request.RawUrl).Returns(\"/subfolder1/default.aspx\");\n                contextMock.Setup(c => c.Request.Path).Returns(\"/myapp/subfolder1/default.aspx\");\n                    \n                // Act\n                var actual1 = UrlUtil.GenerateClientUrl(contextMock.Object, vpath, href);\n\n                // Assert\n                Assert.Equal(expected, actual1);\n            });\n        }\n\n        [Fact]\n        public void BuildUrlEncodesPagePart()\n        {\n            // Arrange\n            var page = \"This is a really bad name for a page\";\n            var expected = \"This%20is%20a%20really%20bad%20name%20for%20a%20page\";\n\n            // Act\n            string query;\n            var path = UrlUtil.BuildUrl(page, out query);\n\n            // Assert\n            Assert.Equal(path + query, expected);\n        }\n\n        [Fact]\n        public void BuildUrlAppendsNonAnonymousTypesToPathPortion()\n        {\n            // Arrange\n            object[] pathParts = new object[] { \"part\", Decimal.One, 1.25f };\n            var page = \"home\";\n\n            // Act\n            string query;\n            var path = UrlUtil.BuildUrl(page, out query, pathParts);\n\n            // Assert\n            Assert.Equal(path + query, page + \"/part/1/1.25\");\n        }\n\n        [Fact]\n        public void BuildUrlEncodesAppendedPathPortion()\n        {\n            // Arrange\n            object[] pathParts = new object[] { \"path portion\", \"ζ\" };\n            var page = \"home\";\n\n            // Act\n            string query;\n            var path = UrlUtil.BuildUrl(page, out query, pathParts);\n\n            // Assert\n            Assert.Equal(path + query, page + \"/path%20portion/%ce%b6\");\n        }\n\n        [Fact]\n        public void BuildUrlAppendsAnonymousObjectsToQueryString()\n        {\n            // Arrange\n            var page = \"home\";\n            var queryString = new { sort = \"FName\", dir = \"desc\" };\n\n            // Act\n            string query;\n            var path = UrlUtil.BuildUrl(page, out query, queryString);\n\n            // Assert\n            Assert.Equal(path + query, page + \"?sort=FName&dir=desc\");\n        }\n\n        [Fact]\n        public void BuildUrlAppendsMultipleAnonymousObjectsToQueryString()\n        {\n            // Arrange\n            var page = \"home\";\n            var queryString1 = new { sort = \"FName\", dir = \"desc\" };\n            var queryString2 = new { view = \"Activities\", page = 7 };\n\n            // Act\n            string query;\n            var path = UrlUtil.BuildUrl(page, out query, queryString1, queryString2);\n\n            // Assert\n            Assert.Equal(path + query, page + \"?sort=FName&dir=desc&view=Activities&page=7\");\n        }\n\n        [Fact]\n        public void BuildUrlEncodesQueryStringKeysAndValues()\n        {\n            // Arrange\n            var page = \"home\";\n            var queryString = new { ζ = \"my=value&\", mykey = \"<π\" };\n\n            // Act\n            string query;\n            var path = UrlUtil.BuildUrl(page, out query, queryString);\n\n            // Assert\n            Assert.Equal(path + query, page + \"?%ce%b6=my%3dvalue%26&mykey=%3c%cf%80\");\n        }\n\n        [Fact]\n        public void BuildUrlGeneratesPathPartsAndQueryString()\n        {\n            // Arrange\n            var page = \"home\";\n\n            // Act\n            string query;\n            var path = UrlUtil.BuildUrl(page, out query, \"products\", new { cat = 37 }, \"furniture\", new { sort = \"name\", dir = \"desc\" });\n\n            // Assert\n            Assert.Equal(path + query, page + \"/products/furniture?cat=37&sort=name&dir=desc\");\n        }\n\n        [Fact]\n        public void UrlAnonymousObjectTest()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                using (IDisposable _ = Utils.CreateHttpContext(\"default.aspx\", \"http://localhost/\"),\n                                   __ = Utils.CreateHttpRuntime(\"/\"))\n                {\n                    Assert.Equal(\"/world/test.cshtml?Prop1=value1\",\n                                 UrlUtil.GenerateClientUrl(new HttpContextWrapper(HttpContext.Current), \"~/world/page.cshtml\", \"test.cshtml\", new { Prop1 = \"value1\" }));\n                    Assert.Equal(\"/world/test.cshtml?Prop1=value1&Prop2=value2\",\n                                 UrlUtil.GenerateClientUrl(new HttpContextWrapper(HttpContext.Current), \"~/world/page.cshtml\", \"test.cshtml\", new { Prop1 = \"value1\", Prop2 = \"value2\" }));\n                }\n            });\n        }\n\n        [Fact]\n        public void GenerateClientUrlWithAbsoluteContentPathAndRewritingDisabled()\n        {\n            // Arrange\n            Mock<HttpContextBase> mockHttpContext = GetMockHttpContext(isUrlRewriteOn: false);\n\n            // Act\n            string returnedUrl = UrlUtil.GenerateClientUrl(mockHttpContext.Object, \"should remain unchanged\");\n\n            // Assert\n            Assert.Equal(\"should remain unchanged\", returnedUrl);\n        }\n\n        [Fact]\n        public void GenerateClientUrlWithAbsoluteContentPathAndRewritingEnabled()\n        {\n            UrlUtil.ResetUrlRewriterHelper(); // Reset the \"is URL rewriting enabled?\" cache\n\n            // Arrange\n            Mock<HttpContextBase> mockHttpContext = GetMockHttpContext(isUrlRewriteOn: true);\n            mockHttpContext.Setup(c => c.Request.RawUrl).Returns(\"/quux/foo/bar/baz\");\n            mockHttpContext.Setup(c => c.Request.Path).Returns(\"/myapp/foo/bar/baz\");\n\n            // Act\n            string returnedUrl = UrlUtil.GenerateClientUrl(mockHttpContext.Object, \"/myapp/some/absolute/path?alpha=bravo\");\n\n            // Assert\n            Assert.Equal(\"/quux/some/absolute/path?alpha=bravo\", returnedUrl);\n        }\n\n        [Fact]\n        public void GenerateClientUrlWithAppRelativeContentPathAndRewritingDisabled()\n        {\n            // Arrange\n            Mock<HttpContextBase> mockHttpContext = GetMockHttpContext(isUrlRewriteOn: false);\n\n            // Act\n            string returnedUrl = UrlUtil.GenerateClientUrl(mockHttpContext.Object, \"~/foo/bar?alpha=bravo\");\n\n            // Assert\n            Assert.Equal(\"/myapp/foo/bar?alpha=bravo\", returnedUrl);\n        }\n\n        [Fact]\n        public void GenerateClientUrlWithAppRelativeContentPathAndRewritingEnabled()\n        {\n            UrlUtil.ResetUrlRewriterHelper(); // Reset the \"is URL rewriting enabled?\" cache\n\n            // Arrange\n            Mock<HttpContextBase> mockHttpContext = GetMockHttpContext(isUrlRewriteOn: true);\n            mockHttpContext.Setup(c => c.Request.RawUrl).Returns(\"/quux/foo/baz\");\n            mockHttpContext.Setup(c => c.Request.Path).Returns(\"/myapp/foo/baz\");\n\n            // Act\n            string returnedUrl = UrlUtil.GenerateClientUrl(mockHttpContext.Object, \"~/foo/bar?alpha=bravo\");\n\n            // Assert\n            Assert.Equal(\"/quux/foo/bar?alpha=bravo\", returnedUrl);\n        }\n\n        [Fact]\n        public void GenerateClientUrlWithEmptyContentPathReturnsEmptyString()\n        {\n            // Act\n            string returnedUrl = UrlUtil.GenerateClientUrl(null, \"\");\n\n            // Assert\n            Assert.Equal(\"\", returnedUrl);\n        }\n\n        [Fact]\n        public void GenerateClientUrlWithNullContentPathReturnsNull()\n        {\n            // Act\n            string returnedUrl = UrlUtil.GenerateClientUrl(null, null);\n\n            // Assert\n            Assert.Null(returnedUrl);\n        }\n\n        [Fact]\n        public void GenerateClientUrlWithOnlyQueryStringForContentPathReturnsOriginalContentPath()\n        {\n            // Act\n            string returnedUrl = UrlUtil.GenerateClientUrl(null, \"?foo=bar\");\n\n            // Assert\n            Assert.Equal(\"?foo=bar\", returnedUrl);\n        }\n\n        [Fact]\n        public void MakeAbsoluteFromDirectoryToParent()\n        {\n            // Act\n            string returnedUrl = UrlUtil.MakeAbsolute(\"/Account/Register\", \"../Account\");\n\n            // Assert\n            Assert.Equal(\"/Account\", returnedUrl);\n        }\n\n        [Fact]\n        public void MakeAbsoluteFromDirectoryToSelf()\n        {\n            // Act\n            string returnedUrl = UrlUtil.MakeAbsolute(\"/foo/\", \"./\");\n\n            // Assert\n            Assert.Equal(\"/foo/\", returnedUrl);\n        }\n\n        [Fact]\n        public void MakeAbsoluteFromFileToFile()\n        {\n            // Act\n            string returnedUrl = UrlUtil.MakeAbsolute(\"/foo\", \"bar\");\n\n            // Assert\n            Assert.Equal(\"/bar\", returnedUrl);\n        }\n\n        [Fact]\n        public void MakeAbsoluteFromFileWithQueryToFile()\n        {\n            // Act\n            string returnedUrl = UrlUtil.MakeAbsolute(\"/foo/bar?alpha=bravo\", \"baz\");\n\n            // Assert\n            Assert.Equal(\"/foo/baz\", returnedUrl);\n        }\n\n        [Fact]\n        public void MakeAbsoluteFromRootToSelf()\n        {\n            // Act\n            string returnedUrl = UrlUtil.MakeAbsolute(\"/\", \"./\");\n\n            // Assert\n            Assert.Equal(\"/\", returnedUrl);\n        }\n\n        [Fact]\n        public void MakeRelativeFromFileToDirectory()\n        {\n            // Act\n            string returnedUrl = UrlUtil.MakeRelative(\"/foo/bar\", \"/foo/\");\n\n            // Assert\n            Assert.Equal(\"./\", returnedUrl);\n        }\n\n        [Fact]\n        public void MakeRelativeFromFileToDirectoryWithQueryString()\n        {\n            // Act\n            string returnedUrl = UrlUtil.MakeRelative(\"/foo/bar\", \"/foo/?alpha=bravo\");\n\n            // Assert\n            Assert.Equal(\"./?alpha=bravo\", returnedUrl);\n        }\n\n        [Fact]\n        public void MakeRelativeFromFileToFile()\n        {\n            // Act\n            string returnedUrl = UrlUtil.MakeRelative(\"/foo/bar\", \"/baz/quux\");\n\n            // Assert\n            Assert.Equal(\"../baz/quux\", returnedUrl);\n        }\n\n        [Fact]\n        public void MakeRelativeFromFileToFileWithQuery()\n        {\n            // Act\n            string returnedUrl = UrlUtil.MakeRelative(\"/foo/bar\", \"/baz/quux?alpha=bravo\");\n\n            // Assert\n            Assert.Equal(\"../baz/quux?alpha=bravo\", returnedUrl);\n        }\n\n        [Fact]\n        public void MakeRelativeFromFileWithQueryToFileWithQuery()\n        {\n            // Act\n            string returnedUrl = UrlUtil.MakeRelative(\"/foo/bar?charlie=delta\", \"/baz/quux?alpha=bravo\");\n\n            // Assert\n            Assert.Equal(\"../baz/quux?alpha=bravo\", returnedUrl);\n        }\n\n        [Fact]\n        public void MakeRelativeFromRootToRoot()\n        {\n            // Act\n            string returnedUrl = UrlUtil.MakeRelative(\"/\", \"/\");\n\n            // Assert\n            Assert.Equal(\"./\", returnedUrl);\n        }\n\n        [Fact]\n        public void MakeRelativeFromRootToRootWithQueryString()\n        {\n            // Act\n            string returnedUrl = UrlUtil.MakeRelative(\"/\", \"/?foo=bar\");\n\n            // Assert\n            Assert.Equal(\"./?foo=bar\", returnedUrl);\n        }\n\n        internal static Mock<HttpContextBase> GetMockHttpContext(bool isUrlRewriteOn)\n        {\n            Mock<HttpContextBase> mockContext = new Mock<HttpContextBase>();\n\n            Mock<HttpWorkerRequest> mockWorkerRequest = new Mock<HttpWorkerRequest>();\n            mockContext.As<IServiceProvider>().Setup(sp => sp.GetService(typeof(HttpWorkerRequest))).Returns(mockWorkerRequest.Object);\n            mockWorkerRequest.Setup(wr => wr.GetServerVariable(UrlRewriterHelper.UrlRewriterEnabledServerVar)).Returns(\"On!\");\n            if (isUrlRewriteOn)\n            {\n                mockWorkerRequest.Setup(wr => wr.GetServerVariable(UrlRewriterHelper.UrlWasRewrittenServerVar)).Returns(\"Yup!\");\n            }\n\n            NameValueCollection serverVars = new NameValueCollection();\n            mockContext.Setup(c => c.Request.ServerVariables).Returns(serverVars);\n            mockContext.Setup(c => c.Request.ApplicationPath).Returns(\"/myapp\");\n\n            mockContext.Setup(c => c.Items).Returns(new HybridDictionary());\n\n            return mockContext;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Validation/ValidationHelperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing System.ComponentModel.DataAnnotations;\nusing System.Linq;\nusing System.Web.Mvc;\nusing System.Web.WebPages.Html;\nusing System.Web.WebPages.Scope;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Validation.Test\n{\n    [Xunit.Collection(\"Uses ScopeStorage or ViewEngines.Engines\")]\n    public class ValidationHelperTest : IDisposable\n    {\n        [Fact]\n        public void FormFieldKeyIsCommonToModelStateAndValidationHelper()\n        {\n            // Arrange\n            const string key = \"_FORM\";\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            ValidationHelper validationHelper = GetValidationHelper(GetContext());\n\n            // Act and Assert\n            Assert.Equal(key, ModelStateDictionary.FormFieldKey);\n            Assert.Equal(key, validationHelper.FormField);\n        }\n\n        [Fact]\n        public void AddThrowsIfFieldIsEmpty()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            ValidationHelper validationHelper = GetValidationHelper(GetContext());\n\n            // Act and Assert\n            Assert.ThrowsArgumentNullOrEmptyString(() => validationHelper.Add(field: null), \"field\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => validationHelper.Add(field: String.Empty), \"field\");\n        }\n\n        [Fact]\n        public void AddThrowsIfValidatorsParamsArrayIsNull()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            ValidationHelper validationHelper = GetValidationHelper(GetContext());\n\n            // Act and Assert\n            Assert.ThrowsArgumentNull(() => validationHelper.Add(\"foo\", null), \"validators\");\n        }\n\n        [Fact]\n        public void AddThrowsIfValidatorsAreNull()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            ValidationHelper validationHelper = GetValidationHelper(GetContext());\n\n            // Act and Assert\n            Assert.ThrowsArgumentNull(() => validationHelper.Add(\"foo\", Validator.Required(), null, Validator.Range(0, 10)), \"validators\");\n        }\n\n        [Fact]\n        public void RequiredReturnsErrorMessageIfFieldIsNotPresentInForm()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            string message = \"Foo is required.\";\n            ValidationHelper validationHelper = GetValidationHelper(GetContext());\n\n            // Act\n            validationHelper.RequireField(\"foo\", message);\n            var results = validationHelper.Validate();\n\n            // Assert\n            ValidationResult result = Assert.Single(results);\n            Assert.Equal(message, result.ErrorMessage);\n        }\n\n        [Fact]\n        public void RequiredReturnsErrorMessageIfFieldIsEmpty()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            string message = \"Foo is required.\";\n            ValidationHelper validationHelper = GetValidationHelper(GetContext(new { foo = \"\" }));\n\n            // Act\n            validationHelper.RequireField(\"foo\", message);\n            var results = validationHelper.Validate();\n\n            // Assert\n            ValidationResult result = Assert.Single(results);\n            Assert.Equal(message, result.ErrorMessage);\n        }\n\n        [Fact]\n        public void RequiredReturnsNoValidationResultsIfFieldIsPresent()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            string message = \"Foo is required.\";\n            ValidationHelper validationHelper = GetValidationHelper(GetContext(new { foo = \"some value\" }));\n\n            // Act\n            validationHelper.RequireField(\"foo\", message);\n            var results = validationHelper.Validate();\n\n            // Assert\n            Assert.Empty(results);\n        }\n\n        [Fact]\n        public void RequiredUsesDefaultErrorMessageIfNoValueIsProvided()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            ValidationHelper validationHelper = GetValidationHelper(GetContext());\n\n            // Act\n            validationHelper.RequireField(\"foo\");\n            var results = validationHelper.Validate();\n\n            // Assert\n            ValidationResult result = Assert.Single(results);\n            Assert.Equal(\"This field is required.\", result.ErrorMessage);\n        }\n\n        [Fact]\n        public void RequiredReturnsValidationResultForEachFieldThatFailed()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            string message = \"This field is required.\";\n            ValidationHelper validationHelper = GetValidationHelper(GetContext());\n\n            // Act\n            validationHelper.RequireFields(\"foo\", \"bar\");\n            var results = validationHelper.Validate();\n\n            // Assert\n            Assert.Equal(2, results.Count());\n            Assert.Equal(message, results.First().ErrorMessage);\n            Assert.Equal(\"foo\", results.First().MemberNames.Single());\n\n            Assert.Equal(message, results.Last().ErrorMessage);\n            Assert.Equal(\"bar\", results.Last().MemberNames.Single());\n        }\n\n        [Fact]\n        public void RequiredReturnsValidationResultForEachFieldThatFailedWhenFieldsIsEmpty()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            string message = \"This field is required.\";\n            ValidationHelper validationHelper = GetValidationHelper(GetContext());\n\n            // Act\n            validationHelper.RequireFields(\"foo\", \"bar\");\n            var results = validationHelper.Validate(fields: null);\n\n            // Assert\n            Assert.Equal(2, results.Count());\n            Assert.Equal(message, results.First().ErrorMessage);\n            Assert.Equal(\"foo\", results.First().MemberNames.Single());\n\n            Assert.Equal(message, results.Last().ErrorMessage);\n            Assert.Equal(\"bar\", results.Last().MemberNames.Single());\n        }\n\n        [Fact]\n        public void GetValidationHtmlThrowsIfArgumentIsNullOrEmpty()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            ValidationHelper validationHelper = GetValidationHelper(GetContext());\n\n            // Act and Assert\n            Assert.ThrowsArgumentNullOrEmptyString(() => validationHelper.For(field: null), \"field\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => validationHelper.For(field: String.Empty), \"field\");\n        }\n\n        [Fact]\n        public void RequireFieldThrowsIfValueIsNullOrEmpty()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            ValidationHelper validationHelper = GetValidationHelper(GetContext());\n\n            // Act and Assert\n            Assert.ThrowsArgumentNullOrEmptyString(() => validationHelper.RequireField(field: null), \"field\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => validationHelper.RequireField(field: String.Empty), \"field\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => validationHelper.RequireField(field: null, errorMessage: \"baz\"), \"field\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => validationHelper.RequireField(field: String.Empty, errorMessage: null), \"field\");\n        }\n\n        [Fact]\n        public void RequireFieldsThrowsIfFieldsAreNullOrHasEmptyValues()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            ValidationHelper validationHelper = GetValidationHelper(GetContext());\n\n            // Act and Assert\n            Assert.ThrowsArgumentNull(() => validationHelper.RequireFields(fields: null), \"fields\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => validationHelper.RequireFields(fields: new[] { \"foo\", null }), \"field\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => validationHelper.RequireFields(fields: new[] { \"foo\", \"\" }), \"field\");\n        }\n\n        [Fact]\n        public void AddThrowsIfFieldIsNullOrEmpty()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            ValidationHelper validationHelper = GetValidationHelper(GetContext());\n\n            // Act and Assert\n            Assert.ThrowsArgumentNullOrEmptyString(() => validationHelper.Add(field: null), \"field\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => validationHelper.Add(field: String.Empty), \"field\");\n        }\n\n        [Fact]\n        public void AddThrowsIfValidatorsIsNullOrAnyValidatorIsNull()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            ValidationHelper validationHelper = GetValidationHelper(GetContext());\n\n            // Act and Assert\n            Assert.ThrowsArgumentNull(() => validationHelper.Add(field: \"foo\", validators: null), \"validators\");\n            Assert.ThrowsArgumentNull(() => validationHelper.Add(field: \"foo\", validators: new[] { Validator.DateTime(), null }), \"validators\");\n        }\n\n        [Fact]\n        public void AddFormErrorCallsMethodInUnderlyingModelStateDictionary()\n        {\n            // Arrange\n            var message = \"This is a form error.\";\n            var dictionary = new ModelStateDictionary();\n            ValidationHelper validationHelper = GetValidationHelper(GetContext(), dictionary);\n\n            // Act\n            validationHelper.AddFormError(message);\n\n            // Assert\n            Assert.Equal(message, dictionary[\"_FORM\"].Errors.Single());\n        }\n\n        [Fact]\n        public void GetValidationHtmlForRequired()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            string message = \"Foo is required.\";\n            ValidationHelper validationHelper = GetValidationHelper(GetContext());\n\n            // Act\n            validationHelper.RequireField(\"foo\", message);\n            var validationHtml = validationHelper.For(\"foo\");\n\n            // Assert\n            Assert.Equal(@\"data-val-required=\"\"Foo is required.\"\" data-val=\"\"true\"\"\", validationHtml.ToString());\n        }\n\n        [Fact]\n        public void ValidateReturnsAnEmptySequenceIfNoValidationsAreRegistered()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            ValidationHelper validationHelper = GetValidationHelper(GetContext());\n\n            // Act\n            var results = validationHelper.Validate();\n\n            // Assert\n            Assert.False(results.Any());\n        }\n\n        [Fact]\n        public void ValidatePopulatesModelStateDictionary()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var modelStateDictionary = new ModelStateDictionary();\n            ValidationHelper validationHelper = GetValidationHelper(GetContext(), modelStateDictionary);\n\n            // Act\n            validationHelper.RequireFields(new[] { \"foo\", \"bar\" });\n            validationHelper.Validate();\n\n            // Assert\n            Assert.False(modelStateDictionary.IsValid);\n            Assert.False(modelStateDictionary.IsValidField(\"foo\"));\n            Assert.False(modelStateDictionary.IsValidField(\"bar\"));\n            Assert.Equal(\"This field is required.\", modelStateDictionary[\"foo\"].Errors.Single());\n            Assert.Equal(\"This field is required.\", modelStateDictionary[\"bar\"].Errors.Single());\n        }\n\n        [Fact]\n        public void IsValidPopulatesModelStateDictionary()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var modelStateDictionary = new ModelStateDictionary();\n            ValidationHelper validationHelper = GetValidationHelper(GetContext(), modelStateDictionary);\n\n            // Act\n            validationHelper.RequireFields(\"foo\", \"bar\");\n            validationHelper.IsValid();\n\n            // Assert\n            Assert.False(modelStateDictionary.IsValid);\n            Assert.False(modelStateDictionary.IsValidField(\"foo\"));\n            Assert.False(modelStateDictionary.IsValidField(\"bar\"));\n            Assert.Equal(\"This field is required.\", modelStateDictionary[\"foo\"].Errors.Single());\n            Assert.Equal(\"This field is required.\", modelStateDictionary[\"bar\"].Errors.Single());\n        }\n\n        [Fact]\n        public void GetErrorsPopulatesModelStateDictionary()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var modelStateDictionary = new ModelStateDictionary();\n            ValidationHelper validationHelper = GetValidationHelper(GetContext(), modelStateDictionary);\n\n            // Act\n            validationHelper.RequireFields(\"foo\", \"bar\");\n            validationHelper.GetErrors();\n\n            // Assert\n            Assert.False(modelStateDictionary.IsValid);\n            Assert.False(modelStateDictionary.IsValidField(\"foo\"));\n            Assert.False(modelStateDictionary.IsValidField(\"bar\"));\n            Assert.Equal(\"This field is required.\", modelStateDictionary[\"foo\"].Errors.Single());\n            Assert.Equal(\"This field is required.\", modelStateDictionary[\"bar\"].Errors.Single());\n        }\n\n        [Fact]\n        public void GetErrorsReturnsAnEmptySequenceIfNoValidationsAreRegistered()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            ValidationHelper validationHelper = GetValidationHelper(GetContext());\n\n            // Act\n            var results = validationHelper.GetErrors();\n\n            // Assert\n            Assert.False(results.Any());\n        }\n\n        [Fact]\n        public void GetErrorsReturnsErrorsAddedViaAddError()\n        {\n            // Arrange\n            var modelStateDictionary = new ModelStateDictionary();\n            ValidationHelper validationHelper = GetValidationHelper(GetContext(), modelStateDictionary);\n\n            // Act\n            modelStateDictionary.AddError(\"foo\", \"Foo error\");\n            var errors = validationHelper.GetErrors(\"foo\");\n\n            // Assert\n            Assert.Equal(new[] { \"Foo error\" }, errors);\n        }\n\n        [Fact]\n        public void GetErrorsReturnsFormErrors()\n        {\n            // Arrange\n            string error = \"Unable to connect to remote servers.\";\n            var modelStateDictionary = new ModelStateDictionary();\n            ValidationHelper validationHelper = GetValidationHelper(GetContext(), modelStateDictionary);\n\n            // Act\n            validationHelper.AddFormError(error);\n            var errors = validationHelper.GetErrors();\n\n            // Assert\n            Assert.Equal(error, errors.Single());\n        }\n\n        [Fact]\n        public void InvokingValidateMultipleTimesDoesNotCauseErrorMessagesToBeDuplicated()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var modelStateDictionary = new ModelStateDictionary();\n            ValidationHelper validationHelper = GetValidationHelper(GetContext(), modelStateDictionary);\n\n            // Act\n            validationHelper.RequireField(\"foo\", \"Foo is required.\");\n            validationHelper.RequireField(\"bar\", \"Bar is required.\");\n            validationHelper.Validate();\n            Assert.False(validationHelper.IsValid());\n            validationHelper.Validate();\n            validationHelper.Validate();\n\n            // Assert\n            Assert.False(modelStateDictionary.IsValid);\n            Assert.False(modelStateDictionary.IsValidField(\"foo\"));\n            Assert.False(modelStateDictionary.IsValidField(\"bar\"));\n            Assert.Equal(\"Foo is required.\", modelStateDictionary[\"foo\"].Errors.Single());\n            Assert.Equal(\"Bar is required.\", modelStateDictionary[\"bar\"].Errors.Single());\n        }\n\n        [Fact]\n        public void AddWorksForCustomValidator()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            string message = \"Foo is not an odd number.\";\n            var oddValidator = new Mock<IValidator>();\n            oddValidator.Setup(c => c.Validate(It.IsAny<ValidationContext>())).Returns<ValidationContext>(v =>\n            {\n                var context = Assert.IsAssignableFrom<HttpContextBase>(v.ObjectInstance);\n                var value = Int32.Parse(context.Request.Form[\"foo\"]);\n\n                if (value % 2 != 0)\n                {\n                    return ValidationResult.Success;\n                }\n                return new ValidationResult(message);\n            }).Verifiable();\n            ValidationHelper validationHelper = GetValidationHelper(GetContext(new { foo = \"6\" }));\n\n            // Act\n            validationHelper.Add(\"foo\", oddValidator.Object);\n            var results = validationHelper.Validate();\n\n            // Assert\n            ValidationResult result = Assert.Single(results);\n            Assert.Equal(message, result.ErrorMessage);\n            oddValidator.Verify();\n        }\n\n        [Fact]\n        public void ValidateRunsForSpecifiedFields()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            string message = \"Foo is not an odd number.\";\n            var oddValidator = new Mock<IValidator>();\n            oddValidator.Setup(c => c.Validate(It.IsAny<ValidationContext>())).Returns<ValidationContext>(v =>\n            {\n                var context = Assert.IsAssignableFrom<HttpContextBase>(v.ObjectInstance);\n                if (context.Request.Form[\"foo\"].IsEmpty())\n                {\n                    return ValidationResult.Success;\n                }\n                int value = context.Request.Form[\"foo\"].AsInt();\n                if (value % 2 != 0)\n                {\n                    return ValidationResult.Success;\n                }\n                return new ValidationResult(message);\n            }).Verifiable();\n            ValidationHelper validationHelper = GetValidationHelper(GetContext(new { foo = \"\", bar = \"\" }));\n\n            // Act\n            validationHelper.Add(new[] { \"foo\", \"bar\" }, oddValidator.Object);\n            validationHelper.RequireField(\"foo\");\n            var results = validationHelper.Validate(\"foo\");\n\n            // Assert\n            ValidationResult result = Assert.Single(results);\n            Assert.Equal(\"This field is required.\", result.ErrorMessage);\n        }\n\n        [Fact]\n        public void GetErrorsReturnsAllErrorsIfNoParametersAreSpecified()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            string message = \"Foo is not an odd number.\";\n            var oddValidator = new Mock<IValidator>();\n            oddValidator.Setup(c => c.Validate(It.IsAny<ValidationContext>())).Returns<ValidationContext>(v =>\n            {\n                var context = Assert.IsAssignableFrom<HttpContextBase>(v.ObjectInstance);\n                if (context.Request.Form[\"foo\"].IsEmpty())\n                {\n                    return ValidationResult.Success;\n                }\n                int value = context.Request.Form[\"foo\"].AsInt();\n                if (value % 2 != 0)\n                {\n                    return ValidationResult.Success;\n                }\n                return new ValidationResult(message);\n            }).Verifiable();\n            ValidationHelper validationHelper = GetValidationHelper(GetContext(new { foo = \"4\", bar = \"\" }));\n\n            // Act\n            validationHelper.Add(\"foo\", oddValidator.Object);\n            validationHelper.RequireFields(new[] { \"bar\", \"foo\" });\n            var result = validationHelper.GetErrors();\n\n            // Assert\n            Assert.Equal(2, result.Count());\n            Assert.Equal(\"Foo is not an odd number.\", result.First());\n            Assert.Equal(\"This field is required.\", result.Last());\n        }\n\n        [Fact]\n        public void IsValidReturnsTrueIfAllValuesPassValidation()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            string message = \"Foo is not an odd number.\";\n            var oddValidator = new Mock<IValidator>();\n            oddValidator.Setup(c => c.Validate(It.IsAny<ValidationContext>())).Returns<ValidationContext>(v =>\n            {\n                var context = Assert.IsAssignableFrom<HttpContextBase>(v.ObjectInstance);\n                if (context.Request.Form[\"foo\"].IsEmpty())\n                {\n                    return ValidationResult.Success;\n                }\n                int value = context.Request.Form[\"foo\"].AsInt();\n                if (value % 2 != 0)\n                {\n                    return ValidationResult.Success;\n                }\n                return new ValidationResult(message);\n            }).Verifiable();\n            ValidationHelper validationHelper = GetValidationHelper(GetContext(new { foo = \"5\", bar = \"2\" }));\n\n            // Act\n            validationHelper.Add(new[] { \"foo\", \"bar\" }, oddValidator.Object);\n            validationHelper.RequireField(\"foo\");\n            var result = validationHelper.IsValid();\n\n            // Assert\n            Assert.True(result);\n        }\n\n        [Fact]\n        public void IsValidValidatesSpecifiedFields()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            string message = \"Foo is not an odd number.\";\n            var oddValidator = new Mock<IValidator>();\n            oddValidator.Setup(c => c.Validate(It.IsAny<ValidationContext>())).Returns<ValidationContext>(v =>\n            {\n                var context = Assert.IsAssignableFrom<HttpContextBase>(v.ObjectInstance);\n                int value;\n                if (!Int32.TryParse(context.Request.Form[\"foo\"], out value))\n                {\n                    return ValidationResult.Success;\n                }\n                if (value % 2 != 0)\n                {\n                    return ValidationResult.Success;\n                }\n                return new ValidationResult(message);\n            }).Verifiable();\n            ValidationHelper validationHelper = GetValidationHelper(GetContext(new { foo = \"3\", bar = \"\" }));\n\n            // Act\n            validationHelper.Add(new[] { \"foo\", \"bar\" }, oddValidator.Object);\n            validationHelper.RequireFields(new[] { \"foo\", \"bar\" });\n            var result = validationHelper.IsValid(\"foo\");\n\n            // Assert\n            Assert.True(result);\n        }\n\n        [Fact]\n        public void GetValidationHtmlReturnsNullIfNoRulesAreRegistered()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            ValidationHelper validationHelper = GetValidationHelper(GetContext());\n\n            // Assert\n            var validationAttributes = validationHelper.For(\"bar\");\n\n            // Assert\n            Assert.Null(validationAttributes);\n        }\n\n        [Fact]\n        public void GetValidationHtmlReturnsAttributesForRegisteredValidators()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = new Mock<IValidator>();\n            var clientRules = new ModelClientValidationRule { ValidationType = \"foo\", ErrorMessage = \"Foo error.\" };\n            clientRules.ValidationParameters[\"qux\"] = \"some data\";\n            validator.Setup(c => c.ClientValidationRule).Returns(clientRules).Verifiable();\n            var expected = @\"data-val-required=\"\"This field is required.\"\" data-val-foo=\"\"Foo error.\"\" data-val-foo-qux=\"\"some data\"\" data-val=\"\"true\"\"\";\n\n            ValidationHelper validationHelper = GetValidationHelper(GetContext());\n\n            // Act\n            validationHelper.RequireField(\"foo\");\n            validationHelper.Add(\"foo\", validator.Object);\n            var validationAttributes = validationHelper.For(\"foo\");\n\n            // Assert\n            Assert.Equal(expected, validationAttributes.ToString());\n        }\n\n        [Fact]\n        public void GetValidationHtmlHtmlEncodesAttributeValues()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = new Mock<IValidator>();\n            var clientRules = new ModelClientValidationRule { ValidationType = \"biz\", ErrorMessage = \"<Biz error.>\" };\n            clientRules.ValidationParameters[\"qux\"] = \"<some ' data>\";\n            validator.Setup(c => c.ClientValidationRule).Returns(clientRules).Verifiable();\n            var expected = @\"data-val-required=\"\"This field is required.\"\" data-val-biz=\"\"&lt;Biz error.&gt;\"\" data-val-biz-qux=\"\"&lt;some &#39; data&gt;\"\" data-val=\"\"true\"\"\";\n\n            // Act\n            ValidationHelper validationHelper = GetValidationHelper(GetContext());\n\n            // Assert\n            validationHelper.RequireField(\"foo\");\n            validationHelper.Add(\"foo\", validator.Object);\n            var validationAttributes = validationHelper.For(\"foo\");\n\n            // Assert\n            Assert.Equal(expected, validationAttributes.ToString());\n        }\n\n        [Fact]\n        public void GetValidationFromClientValidationRulesThrowsIfValidationTypeIsNullOrEmpty()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var clientRule = new ModelClientValidationRule { ValidationType = null };\n\n            // Act and Assert\n            Assert.Throws<InvalidOperationException>(() => ValidationHelper.GenerateHtmlFromClientValidationRules(new[] { clientRule }),\n                                                              \"Validation type names in unobtrusive client validation rules cannot be empty. Client rule type: System.Web.Mvc.ModelClientValidationRule\");\n\n            clientRule.ValidationType = String.Empty;\n            Assert.Throws<InvalidOperationException>(() => ValidationHelper.GenerateHtmlFromClientValidationRules(new[] { clientRule }),\n                                                              \"Validation type names in unobtrusive client validation rules cannot be empty. Client rule type: System.Web.Mvc.ModelClientValidationRule\");\n        }\n\n        [Fact]\n        public void GetValidationFromClientValidationRulesThrowsIfSameValidationTypeIsSpecifiedMultipleTimes()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var clientRule1 = new ModelClientValidationRule { ValidationType = \"foo\" };\n            var clientRule2 = new ModelClientValidationRule { ValidationType = \"foo\" };\n\n            // Act and Assert\n            Assert.Throws<InvalidOperationException>(() => ValidationHelper.GenerateHtmlFromClientValidationRules(new[] { clientRule1, clientRule2 }),\n                                                              \"Validation type names in unobtrusive client validation rules must be unique. The following validation type was seen more than once: foo\");\n        }\n\n        [Fact]\n        public void GetValidationFromClientValidationRulesThrowsIfValidationTypeDoesNotContainAllLowerCaseCharacters()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var clientRule = new ModelClientValidationRule { ValidationType = \"Foo\" };\n\n            // Act and Assert\n            Assert.Throws<InvalidOperationException>(() => ValidationHelper.GenerateHtmlFromClientValidationRules(new[] { clientRule }),\n                                                              \"Validation type names in unobtrusive client validation rules must consist of only lowercase letters. Invalid name: \\\"Foo\\\", client rule type: System.Web.Mvc.ModelClientValidationRule\");\n\n            clientRule.ValidationType = \"bAr\";\n            Assert.Throws<InvalidOperationException>(() => ValidationHelper.GenerateHtmlFromClientValidationRules(new[] { clientRule }),\n                                                              \"Validation type names in unobtrusive client validation rules must consist of only lowercase letters. Invalid name: \\\"bAr\\\", client rule type: System.Web.Mvc.ModelClientValidationRule\");\n\n            clientRule.ValidationType = \"bar123\";\n            Assert.Throws<InvalidOperationException>(() => ValidationHelper.GenerateHtmlFromClientValidationRules(new[] { clientRule }),\n                                                              \"Validation type names in unobtrusive client validation rules must consist of only lowercase letters. Invalid name: \\\"bar123\\\", client rule type: System.Web.Mvc.ModelClientValidationRule\");\n        }\n\n        [Fact]\n        public void GetValidationFromClientValidationRulesThrowsIfValidationParamaterContainsNonAlphaNumericCharacters()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var clientRule = new ModelClientValidationRule { ValidationType = \"required\" };\n            clientRule.ValidationParameters[\"min^\"] = \"some-val\";\n\n            // Act and Assert\n            Assert.Throws<InvalidOperationException>(() => ValidationHelper.GenerateHtmlFromClientValidationRules(new[] { clientRule }),\n                                                              \"Validation parameter names in unobtrusive client validation rules must start with a lowercase letter and consist of only lowercase letters or digits. Validation parameter name: min^, client rule type: System.Web.Mvc.ModelClientValidationRule\");\n\n            clientRule.ValidationParameters.Clear();\n            clientRule.ValidationParameters[\"Min\"] = \"some-val\";\n\n            Assert.Throws<InvalidOperationException>(() => ValidationHelper.GenerateHtmlFromClientValidationRules(new[] { clientRule }),\n                                                              \"Validation parameter names in unobtrusive client validation rules must start with a lowercase letter and consist of only lowercase letters or digits. Validation parameter name: Min, client rule type: System.Web.Mvc.ModelClientValidationRule\");\n        }\n\n        [Fact]\n        public void DefaultValidCssClassIsNull()\n        {\n            Assert.Null(ValidationHelper.ValidCssClass);\n        }\n\n        [Fact]\n        public void DefaultInvalidCssClassIsSameAsHtmlHelper()\n        {\n            Assert.Equal(HtmlHelper.DefaultValidationInputErrorCssClass, ValidationHelper.InvalidCssClass);\n        }\n\n        [Fact]\n        public void InvalidCssClassIsNullIfExplicitlySetToNull()\n        {\n            using (ValidationHelper.OverrideScope())\n            {\n                ValidationHelper.InvalidCssClass = null;\n                Assert.Null(ValidationHelper.InvalidCssClass);\n            }\n        }\n\n        [Fact]\n        public void ValidCssClassIsScopeBacked()\n        {\n            // Set a value\n            string old = ValidationHelper.ValidCssClass;\n            ValidationHelper.ValidCssClass = \"outer\";\n            using (ScopeStorage.CreateTransientScope())\n            {\n                ValidationHelper.ValidCssClass = \"inner\";\n                Assert.Equal(\"inner\", ValidationHelper.ValidCssClass);\n            }\n            Assert.Equal(\"outer\", ValidationHelper.ValidCssClass);\n            ValidationHelper.ValidCssClass = old;\n        }\n\n        [Fact]\n        public void InvalidCssClassIsScopeBacked()\n        {\n            // Set a value\n            string old = ValidationHelper.InvalidCssClass;\n            ValidationHelper.InvalidCssClass = \"outer\";\n            using (ScopeStorage.CreateTransientScope())\n            {\n                ValidationHelper.InvalidCssClass = \"inner\";\n                Assert.Equal(\"inner\", ValidationHelper.InvalidCssClass);\n            }\n            Assert.Equal(\"outer\", ValidationHelper.InvalidCssClass);\n            ValidationHelper.InvalidCssClass = old;\n        }\n\n        [Fact]\n        public void ClassForReturnsNullIfNotPost()\n        {\n            // Arrange\n            ValidationHelper helper = GetValidationHelper();\n\n            // Act/Assert\n            Assert.Null(helper.ClassFor(\"foo\"));\n        }\n\n        [Fact]\n        public void ClassForReturnsValidClassNameIfNoErrorsAddedForField()\n        {\n            // Arrange\n            ValidationHelper helper = GetPostValidationHelper();\n\n            // Act/Assert\n            HtmlString html = helper.ClassFor(\"foo\");\n            string str = html == null ? null : html.ToHtmlString();\n            Assert.Equal(ValidationHelper.ValidCssClass, str);\n        }\n\n        [Fact]\n        public void ClassForReturnsInvalidClassNameIfFieldHasErrors()\n        {\n            // Arrange\n            ValidationHelper helper = GetPostValidationHelper();\n            helper.Add(\"foo\", new AutoFailValidator());\n\n            // Act/Assert\n            Assert.Equal(ValidationHelper.InvalidCssClass, helper.ClassFor(\"foo\").ToHtmlString());\n        }\n\n        private static ValidationHelper GetPostValidationHelper()\n        {\n            HttpContextBase context = GetContext();\n            Mock.Get(context.Request).SetupGet(c => c.HttpMethod).Returns(\"POST\");\n            ValidationHelper helper = GetValidationHelper(httpContext: context);\n            return helper;\n        }\n\n        private static HttpContextBase GetContext(object formValues = null)\n        {\n            var context = new Mock<HttpContextBase>();\n            var request = new Mock<HttpRequestBase>();\n\n            var nameValueCollection = new NameValueCollection();\n            if (formValues != null)\n            {\n                foreach (var prop in formValues.GetType().GetProperties())\n                {\n                    nameValueCollection.Add(prop.Name, prop.GetValue(formValues, null).ToString());\n                }\n            }\n            request.SetupGet(c => c.Form).Returns(nameValueCollection);\n            context.SetupGet(c => c.Request).Returns(request.Object);\n\n            return context.Object;\n        }\n\n        private static ValidationHelper GetValidationHelper(HttpContextBase httpContext = null, ModelStateDictionary modelStateDictionary = null)\n        {\n            httpContext = httpContext ?? GetContext();\n            modelStateDictionary = modelStateDictionary ?? new ModelStateDictionary();\n\n            return new ValidationHelper(httpContext, modelStateDictionary);\n        }\n\n        private class AutoFailValidator : IValidator\n        {\n            public ValidationResult Validate(ValidationContext validationContext)\n            {\n                return new ValidationResult(\"Failed!\");\n            }\n\n            public ModelClientValidationRule ClientValidationRule\n            {\n                get { throw new NotImplementedException(); }\n            }\n        }\n\n        public void Dispose()\n        {\n            // Reset ScopeStorage (written via e.g. ValidationHelper.InvalidCssClass) between tests to avoid unexpected interactions.\n            ScopeStorage.CurrentProvider = new StaticScopeStorageProvider();\n            ScopeStorage.GlobalScope.Clear();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/Validation/ValidatorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Specialized;\nusing System.ComponentModel.DataAnnotations;\nusing System.Globalization;\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Validation.Test\n{\n    public class ValidatorTest\n    {\n        [Fact]\n        public void RequiredValidatorValidatesIfStringIsNull()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var requiredValidator = Validator.Required();\n            var validationContext = GetValidationContext(GetContext(), \"foo\");\n\n            // Act\n            var result = requiredValidator.Validate(validationContext);\n\n            // Assert\n            Assert.NotEqual(ValidationResult.Success, result);\n            Assert.Equal(\"This field is required.\", result.ErrorMessage);\n            Assert.Equal(\"foo\", result.MemberNames.Single());\n        }\n\n        [Fact]\n        public void RequiredValidatorValidatesIfStringIsEmpty()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var requiredValidator = Validator.Required();\n            var validationContext = GetValidationContext(GetContext(new { foo = \"\" }), \"foo\");\n\n            // Act\n            var result = requiredValidator.Validate(validationContext);\n\n            // Assert\n            Assert.NotEqual(ValidationResult.Success, result);\n            Assert.Equal(\"This field is required.\", result.ErrorMessage);\n            Assert.Equal(\"foo\", result.MemberNames.Single());\n        }\n\n        [Fact]\n        public void RequiredValidatorReturnsCustomErrorMessagesIfSpecified()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var requiredValidator = Validator.Required(\"There is no string\");\n            var httpContext = GetContext(new { foo = \"\" });\n            var validationContext = GetValidationContext(httpContext, \"foo\");\n\n            // Act\n            var result = requiredValidator.Validate(validationContext);\n\n            // Assert\n            Assert.NotEqual(ValidationResult.Success, result);\n            Assert.Equal(\"There is no string\", result.ErrorMessage);\n            Assert.Equal(\"foo\", result.MemberNames.Single());\n        }\n\n        [Fact]\n        public void RequiredValidatorReturnsSuccessIfNoFieldIsNotNullOrEmpty()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var requiredValidator = Validator.Required(\"foo\");\n            var validationContext = GetValidationContext(GetContext(new { foo = \"some value\" }), \"foo\");\n\n            // Act\n            var result = requiredValidator.Validate(validationContext);\n\n            // Assert\n            Assert.Equal(ValidationResult.Success, result);\n        }\n\n        [Fact]\n        public void GetClientValidationRulesForRequiredValidatorWithDefaultErrorMessage()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var requiredValidator = Validator.Required();\n\n            // Act\n            var result = requiredValidator.ClientValidationRule;\n\n            // Assert\n            Assert.Equal(\"required\", result.ValidationType);\n            Assert.Equal(\"This field is required.\", result.ErrorMessage);\n            Assert.False(result.ValidationParameters.Any());\n        }\n\n        [Fact]\n        public void GetClientValidationRulesForRequiredValidatorWithCustomErrorMessage()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var requiredValidator = Validator.Required(\"custom message\");\n\n            // Act\n            var result = requiredValidator.ClientValidationRule;\n\n            // Assert\n            Assert.Equal(\"required\", result.ValidationType);\n            Assert.Equal(\"custom message\", result.ErrorMessage);\n            Assert.False(result.ValidationParameters.Any());\n        }\n\n        [Fact]\n        public void RangeValidatorReturnsSuccessIfValueIsInRange()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var rangeValidator = Validator.Range(10, 12);\n            var validationContext = GetValidationContext(GetContext(new { foo = 11 }), \"foo\");\n\n            // Act\n            var result = rangeValidator.Validate(validationContext);\n\n            // Assert\n            Assert.Equal(ValidationResult.Success, result);\n        }\n\n        [Fact]\n        public void RangeValidatorReturnsDefaultErrorMessageIfValueIsNotInRange()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var rangeValidator = Validator.Range(10, 12);\n            var validationContext = GetValidationContext(GetContext(new { foo = 7 }), \"foo\");\n\n            // Act\n            var result = rangeValidator.Validate(validationContext);\n\n            // Assert\n            Assert.NotEqual(ValidationResult.Success, result);\n            Assert.Equal(\"Value must be an integer between 10 and 12.\", result.ErrorMessage);\n            Assert.Equal(\"foo\", result.MemberNames.Single());\n        }\n\n        [Fact]\n        public void RangeValidatorReturnsDefaultErrorMessageIfValueIsNotInRangeForFloatingPointValues()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var rangeValidator = Validator.Range(10.8, 12.2);\n            var validationContext = GetValidationContext(GetContext(new { foo = 7 }), \"foo\");\n\n            // Act\n            var result = rangeValidator.Validate(validationContext);\n\n            // Assert\n            Assert.NotEqual(ValidationResult.Success, result);\n            Assert.Equal(\n                String.Format(CultureInfo.CurrentCulture, \"Value must be a decimal between {0} and {1}.\", 10.8, 12.2),\n                result.ErrorMessage);\n            Assert.Equal(\"foo\", result.MemberNames.Single());\n        }\n\n        [Fact]\n        public void RangeValidatorReturnsCustomErrorMessageIfSpecified()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var rangeValidator = Validator.Range(10, 12, \"Custom error message\");\n            var validationContext = GetValidationContext(GetContext(new { foo = 13 }), \"foo\");\n\n            // Act\n            var result = rangeValidator.Validate(validationContext);\n\n            // Assert\n            Assert.NotEqual(ValidationResult.Success, result);\n            Assert.Equal(\"Custom error message\", result.ErrorMessage);\n            Assert.Equal(\"foo\", result.MemberNames.Single());\n        }\n\n        [Fact]\n        public void RangeValidatorFormatsCustomErrorMessage()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var rangeValidator = Validator.Range(10, 12, \"Valid range: {0}-{1}\");\n            var validationContext = GetValidationContext(GetContext(new { foo = 13 }), \"foo\");\n\n            // Act\n            var result = rangeValidator.Validate(validationContext);\n\n            // Assert\n            Assert.NotEqual(ValidationResult.Success, result);\n            Assert.Equal(\"Valid range: 10-12\", result.ErrorMessage);\n            Assert.Equal(\"foo\", result.MemberNames.Single());\n        }\n\n        [Fact]\n        public void GetClientValidationRulesForRangeValidatorWithDefaultErrorMessage()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var rangeValidator = Validator.Range(10, 12);\n\n            // Act\n            var result = rangeValidator.ClientValidationRule;\n\n            // Assert\n            Assert.Equal(\"range\", result.ValidationType);\n            Assert.Equal(\"Value must be an integer between 10 and 12.\", result.ErrorMessage);\n            Assert.Equal(10, result.ValidationParameters[\"min\"]);\n            Assert.Equal(12, result.ValidationParameters[\"max\"]);\n        }\n\n        [Fact]\n        public void GetClientValidationRulesForRangeValidatorWithCustomErrorMessage()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var rangeValidator = Validator.Range(10, 11, \"Range: {0}-{1}\");\n\n            // Act\n            var result = rangeValidator.ClientValidationRule;\n\n            // Assert\n            Assert.Equal(\"range\", result.ValidationType);\n            Assert.Equal(\"Range: 10-11\", result.ErrorMessage);\n            Assert.Equal(10, result.ValidationParameters[\"min\"]);\n            Assert.Equal(11, result.ValidationParameters[\"max\"]);\n        }\n\n        [Fact]\n        public void StringLengthValidatorReturnsSuccessIfStringLengthIsSmallerThanMaxValue()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.StringLength(10);\n            var validationContext = GetValidationContext(GetContext(new { baz = \"hello\" }), \"baz\");\n\n            // Act\n            var result = validator.Validate(validationContext);\n\n            // Assert\n            Assert.Equal(ValidationResult.Success, result);\n        }\n\n        [Fact]\n        public void StringLengthValidatorReturnsSuccessIfStringLengthIsRangeOfMinAndMaxValue()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.StringLength(10, minLength: 6);\n            var validationContext = GetValidationContext(GetContext(new { bar = \"woof woof\" }), \"bar\");\n\n            // Act\n            var result = validator.Validate(validationContext);\n\n            // Assert\n            Assert.Equal(ValidationResult.Success, result);\n        }\n\n        [Fact]\n        public void StringLengthValidatorReturnsFailureIfStringLengthIsLongerThanMaxValue()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.StringLength(4);\n            var validationContext = GetValidationContext(GetContext(new { baz = \"woof woof\" }), \"baz\");\n\n            // Act\n            var result = validator.Validate(validationContext);\n\n            // Assert\n            Assert.NotEqual(ValidationResult.Success, result);\n            Assert.Equal(\"Max length: 4.\", result.ErrorMessage);\n            Assert.Equal(\"baz\", result.MemberNames.Single());\n        }\n\n        [Fact]\n        public void StringLengthValidatorReturnsCustomErrorMessageIfStringLengthIsLongerThanMaxValue()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.StringLength(4, errorMessage: \"String must be at least {0} characters long.\");\n            var validationContext = GetValidationContext(GetContext(new { baz = \"woof woof\" }), \"baz\");\n\n            // Act\n            var result = validator.Validate(validationContext);\n\n            // Assert\n            Assert.NotEqual(ValidationResult.Success, result);\n            Assert.Equal(\"String must be at least 4 characters long.\", result.ErrorMessage);\n            Assert.Equal(\"baz\", result.MemberNames.Single());\n        }\n\n        [Fact]\n        public void StringLengthValidatorReturnsFailureIfStringLengthIsNotInRange()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.StringLength(6, 4);\n            var validationContext = GetValidationContext(GetContext(new { baz = \"woof woof\" }), \"baz\");\n\n            // Act\n            var result = validator.Validate(validationContext);\n\n            // Assert\n            Assert.NotEqual(ValidationResult.Success, result);\n            Assert.Equal(\"String must be between 4 and 6 characters.\", result.ErrorMessage);\n            Assert.Equal(\"baz\", result.MemberNames.Single());\n        }\n\n        [Fact]\n        public void StringLengthValidatorReturnsCustomErrorMessageIfStringLengthIsNotInRange()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.StringLength(6, 4, \"Range {0} - {1}\");\n            var validationContext = GetValidationContext(GetContext(new { baz = \"woof woof\" }), \"baz\");\n\n            // Act\n            var result = validator.Validate(validationContext);\n\n            // Assert\n            Assert.NotEqual(ValidationResult.Success, result);\n            Assert.Equal(\"Range 4 - 6\", result.ErrorMessage);\n            Assert.Equal(\"baz\", result.MemberNames.Single());\n        }\n\n        [Fact]\n        public void GetClientValidationRulesForStringLengthValidatorWithDefaultErrorMessage()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.StringLength(6, 4);\n\n            // Act\n            var result = validator.ClientValidationRule;\n\n            // Assert\n            Assert.Equal(\"length\", result.ValidationType);\n            Assert.Equal(\"String must be between 4 and 6 characters.\", result.ErrorMessage);\n            Assert.Equal(4, result.ValidationParameters[\"min\"]);\n            Assert.Equal(6, result.ValidationParameters[\"max\"]);\n        }\n\n        [Fact]\n        public void GetClientValidationRulesForStringLengthValidatorWithCustomErrorMessage()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.StringLength(6, errorMessage: \"Must be at least 6 letters.\");\n\n            // Act\n            var result = validator.ClientValidationRule;\n\n            // Assert\n            Assert.Equal(\"length\", result.ValidationType);\n            Assert.Equal(\"Must be at least 6 letters.\", result.ErrorMessage);\n            Assert.Equal(6, result.ValidationParameters[\"max\"]);\n        }\n\n        [Fact]\n        public void RegexThrowsIfPatternIsNullOrEmpty()\n        {\n            // Act and Assert\n            Assert.ThrowsArgumentNullOrEmptyString(() => Validator.Regex(null), \"pattern\");\n            Assert.ThrowsArgumentNullOrEmptyString(() => Validator.Regex(String.Empty), \"pattern\");\n        }\n\n        [Fact]\n        public void RegexReturnsSuccessIfValueMatches()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.Regex(\"^a+b+c$\");\n            var context = GetValidationContext(GetContext(new { foo = \"aaabbc\" }), \"foo\");\n\n            // Act\n            var result = validator.Validate(context);\n\n            // Assert\n            Assert.Equal(ValidationResult.Success, result);\n        }\n\n        [Fact]\n        public void RegexReturnsDefaultErrorMessageIfValidationFails()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.Regex(\"^a+b+c$\");\n            var context = GetValidationContext(GetContext(new { foo = \"aaXabbc\" }), \"foo\");\n\n            // Act\n            var result = validator.Validate(context);\n\n            // Assert\n            Assert.NotEqual(ValidationResult.Success, result);\n            Assert.Equal(\"Value is invalid.\", result.ErrorMessage);\n            Assert.Equal(\"foo\", result.MemberNames.Single());\n        }\n\n        [Fact]\n        public void RegexReturnsCustomErrorMessageIfValidationFails()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.Regex(\"^a+b+c$\");\n            var context = GetValidationContext(GetContext(new { foo = \"aaXabbc\" }), \"foo\");\n\n            // Act\n            var result = validator.Validate(context);\n\n            // Assert\n            Assert.NotEqual(ValidationResult.Success, result);\n            Assert.Equal(\"Value is invalid.\", result.ErrorMessage);\n            Assert.Equal(\"foo\", result.MemberNames.Single());\n        }\n\n        [Fact]\n        public void IntegerReturnsSuccessIfValueIsNull()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.Integer();\n            var context = GetValidationContext(GetContext(new { Name = \"Not-Age\" }), \"age\");\n\n            // Act\n            var result = validator.Validate(context);\n\n            // Assert\n            Assert.Equal(ValidationResult.Success, result);\n        }\n\n        [Fact]\n        public void IntegerReturnsSuccessIfValueIsEmpty()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.Integer();\n            var context = GetValidationContext(GetContext(new { Age = \"\" }), \"age\");\n\n            // Act\n            var result = validator.Validate(context);\n\n            // Assert\n            Assert.Equal(ValidationResult.Success, result);\n        }\n\n        [Fact]\n        public void IntegerReturnsSuccessIfValueIsValidInteger()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.Integer();\n            var context = GetValidationContext(GetContext(new { Age = \"10\" }), \"age\");\n\n            // Act\n            var result = validator.Validate(context);\n\n            // Assert\n            Assert.Equal(ValidationResult.Success, result);\n        }\n\n        [Fact]\n        public void IntegerReturnsSuccessIfValueIsNegativeInteger()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.Integer();\n            var context = GetValidationContext(GetContext(new { Age = \"-42\" }), \"age\");\n\n            // Act\n            var result = validator.Validate(context);\n\n            // Assert\n            Assert.Equal(ValidationResult.Success, result);\n        }\n\n        [Fact]\n        public void IntegerReturnsSuccessIfValueIsZero()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.Integer();\n            var context = GetValidationContext(GetContext(new { Age = 0 }), \"age\");\n\n            // Act\n            var result = validator.Validate(context);\n\n            // Assert\n            Assert.Equal(ValidationResult.Success, result);\n        }\n\n        [Fact]\n        public void IntegerReturnsErrorMessageIfValueIsFloatingPointValue()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.Integer();\n            var context = GetValidationContext(GetContext(new { Age = 1.3 }), \"age\");\n\n            // Act\n            var result = validator.Validate(context);\n\n            // Assert\n            Assert.NotEqual(ValidationResult.Success, result);\n            Assert.Equal(\"Input format is invalid.\", result.ErrorMessage);\n            Assert.Equal(\"age\", result.MemberNames.Single());\n        }\n\n        [Fact]\n        public void IntegerReturnsErrorMessageIfValueIsNotAnInteger()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.Integer();\n            var context = GetValidationContext(GetContext(new { Age = \"2008-04-01\" }), \"age\");\n\n            // Act\n            var result = validator.Validate(context);\n\n            // Assert\n            Assert.NotEqual(ValidationResult.Success, result);\n            Assert.Equal(\"Input format is invalid.\", result.ErrorMessage);\n            Assert.Equal(\"age\", result.MemberNames.Single());\n        }\n\n        [Fact]\n        public void FloatReturnsSuccessIfValueIsNull()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.Float();\n            var context = GetValidationContext(GetContext(new { }), \"Price\");\n\n            // Act\n            var result = validator.Validate(context);\n\n            // Assert\n            Assert.Equal(ValidationResult.Success, result);\n        }\n\n        [Fact]\n        public void FloatReturnsSuccessIfValueIsEmptyString()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.Float();\n            var context = GetValidationContext(GetContext(new { Price = \"\" }), \"Price\");\n\n            // Act\n            var result = validator.Validate(context);\n\n            // Assert\n            Assert.Equal(ValidationResult.Success, result);\n        }\n\n        [Fact]\n        public void FloatReturnsSuccessIfValueIsValidFloatString()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.Float();\n            var context = GetValidationContext(GetContext(new { Price = Single.MaxValue.ToString() }), \"Price\");\n\n            // Act\n            var result = validator.Validate(context);\n\n            // Assert\n            Assert.Equal(ValidationResult.Success, result);\n        }\n\n        [Fact]\n        public void FloatReturnsSuccessIfValueIsValidInteger()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.Float();\n            var context = GetValidationContext(GetContext(new { Price = \"1\" }), \"Price\");\n\n            // Act\n            var result = validator.Validate(context);\n\n            // Assert\n            Assert.Equal(ValidationResult.Success, result);\n        }\n\n        [Fact]\n        public void FloatReturnsErrorIfValueIsNotAValidFloat()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.Float();\n            var context = GetValidationContext(GetContext(new { Price = \"Free!!!\" }), \"Price\");\n\n            // Act\n            var result = validator.Validate(context);\n\n            // Assert\n            Assert.NotEqual(ValidationResult.Success, result);\n            Assert.Equal(\"Input format is invalid.\", result.ErrorMessage);\n            Assert.Equal(\"Price\", result.MemberNames.Single());\n        }\n\n        [Fact]\n        public void DateTimeReturnsSuccessIfValueIsNull()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.DateTime();\n            var context = GetValidationContext(GetContext(new { }), \"dateOfBirth\");\n\n            // Act\n            var result = validator.Validate(context);\n\n            // Assert\n            Assert.Equal(ValidationResult.Success, result);\n        }\n\n        [Fact]\n        public void DateTimeReturnsSuccessIfValueIsEmpty()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.DateTime();\n            var context = GetValidationContext(GetContext(new { dateOfBirth = \"\" }), \"dateOfBirth\");\n\n            // Act\n            var result = validator.Validate(context);\n\n            // Assert\n            Assert.Equal(ValidationResult.Success, result);\n        }\n\n        [Fact]\n        public void DateTimeReturnsSuccessIfValueIsValidDateTime()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.DateTime();\n            var context = GetValidationContext(GetContext(new { dateOfBirth = DateTime.Now.ToString() }), \"dateOfBirth\");\n\n            // Act\n            var result = validator.Validate(context);\n\n            // Assert\n            Assert.Equal(ValidationResult.Success, result);\n        }\n\n        [Fact]\n        public void DateTimeReturnsErrorIfValueIsInvalidDateTime()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.DateTime();\n            var context = GetValidationContext(GetContext(new { dateOfBirth = \"23.28\" }), \"dateOfBirth\");\n\n            // Act\n            var result = validator.Validate(context);\n\n            // Assert\n            Assert.NotEqual(ValidationResult.Success, result);\n            Assert.Equal(\"Input format is invalid.\", result.ErrorMessage);\n            Assert.Equal(\"dateOfBirth\", result.MemberNames.Single());\n        }\n\n        [Fact]\n        public void UrlReturnsSuccessIfInputIsNull()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.Url();\n            var context = GetValidationContext(GetContext(new { }), \"blogUrl\");\n\n            // Act\n            var result = validator.Validate(context);\n\n            // Assert\n            Assert.Equal(ValidationResult.Success, result);\n        }\n\n        [Fact]\n        public void UrlReturnsSuccessIfInputIsEmptyString()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.Url();\n            var context = GetValidationContext(GetContext(new { blogUrl = \"\" }), \"blogUrl\");\n\n            // Act\n            var result = validator.Validate(context);\n\n            // Assert\n            Assert.Equal(ValidationResult.Success, result);\n        }\n\n        [Fact]\n        public void UrlReturnsSuccessIfInputIsValidUrl()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.Url();\n            var context = GetValidationContext(GetContext(new { blogUrl = \"http://www.microsoft.com?query-param=query-param-value&some-val=&quot;true&quot;\" }), \"blogUrl\");\n\n            // Act\n            var result = validator.Validate(context);\n\n            // Assert\n            Assert.Equal(ValidationResult.Success, result);\n        }\n\n        [Fact]\n        public void UrlReturnsErrorMessageIfInputIsPhysicalPath()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.Url();\n            var context = GetValidationContext(GetContext(new { blogUrl = @\"x:\\some-path\\foo.txt\" }), \"blogUrl\");\n\n            // Act\n            var result = validator.Validate(context);\n\n            // Assert\n            Assert.NotEqual(ValidationResult.Success, result);\n            Assert.Equal(\"Input format is invalid.\", result.ErrorMessage);\n            Assert.Equal(\"blogUrl\", result.MemberNames.Single());\n        }\n\n        [Fact]\n        public void UrlReturnsErrorMessageIfInputIsNetworkPath()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.Url();\n            var context = GetValidationContext(GetContext(new { blogUrl = @\"\\\\network-share\\some-path\\\" }), \"blogUrl\");\n\n            // Act\n            var result = validator.Validate(context);\n\n            // Assert\n            Assert.NotEqual(ValidationResult.Success, result);\n            Assert.Equal(\"Input format is invalid.\", result.ErrorMessage);\n            Assert.Equal(\"blogUrl\", result.MemberNames.Single());\n        }\n\n        [Fact]\n        public void UrlReturnsErrorMessageIfInputIsNotAnUrl()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.Url();\n            var context = GetValidationContext(GetContext(new { blogUrl = 65 }), \"blogUrl\");\n\n            // Act\n            var result = validator.Validate(context);\n\n            // Assert\n            Assert.NotEqual(ValidationResult.Success, result);\n            Assert.Equal(\"Input format is invalid.\", result.ErrorMessage);\n            Assert.Equal(\"blogUrl\", result.MemberNames.Single());\n        }\n\n        [Fact]\n        public void EqualsToValidatorThrowsIfFieldIsNullOrEmpty()\n        {\n            // Act and Assert\n            Assert.ThrowsArgumentNullOrEmptyString(() => Validator.EqualsTo(null), \"otherFieldName\");\n        }\n\n        [Fact]\n        public void EqualsToValidatorReturnsFalseIfEitherFieldIsEmpty()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.EqualsTo(\"password\");\n            var context = GetValidationContext(GetContext(new { password = \"\", confirmPassword = \"abcd\" }), \"confirmPassword\");\n\n            // Act\n            var result = validator.Validate(context);\n\n            // Assert\n            Assert.NotEqual(ValidationResult.Success, result);\n            Assert.Equal(\"Values do not match.\", result.ErrorMessage);\n            Assert.Equal(\"confirmPassword\", result.MemberNames.Single());\n\n            context = GetValidationContext(GetContext(new { password = \"abcd\", confirmPassword = \"\" }), \"confirmPassword\");\n\n            // Act\n            result = validator.Validate(context);\n\n            // Assert\n            Assert.NotEqual(ValidationResult.Success, result);\n            Assert.Equal(\"Values do not match.\", result.ErrorMessage);\n            Assert.Equal(\"confirmPassword\", result.MemberNames.Single());\n        }\n\n        [Fact]\n        public void EqualsToValidatorReturnsFalseIfValuesDoNotMatch()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.EqualsTo(\"password\");\n            var context = GetValidationContext(GetContext(new { password = \"password2\", confirmPassword = \"abcd\" }), \"confirmPassword\");\n\n            // Act\n            var result = validator.Validate(context);\n\n            // Assert\n            Assert.NotEqual(ValidationResult.Success, result);\n            Assert.Equal(\"Values do not match.\", result.ErrorMessage);\n            Assert.Equal(\"confirmPassword\", result.MemberNames.Single());\n        }\n\n        [Fact]\n        public void EqualsToValidatorReturnsTrueIfValuesMatch()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.EqualsTo(\"password\");\n            var context = GetValidationContext(GetContext(new { password = \"abcd\", confirmPassword = \"abcd\" }), \"confirmPassword\");\n\n            // Act\n            var result = validator.Validate(context);\n\n            // Assert\n            Assert.Equal(ValidationResult.Success, result);\n        }\n\n        [Fact]\n        public void GetClientValidationRulesForRegex()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.Regex(\"^a+b+c$\");\n\n            // Act\n            var result = validator.ClientValidationRule;\n\n            // Assert\n            Assert.Equal(\"regex\", result.ValidationType);\n            Assert.Equal(\"Value is invalid.\", result.ErrorMessage);\n            Assert.Equal(\"^a+b+c$\", result.ValidationParameters[\"pattern\"]);\n        }\n\n        [Fact]\n        public void GetClientValidationRulesForRegexWithCustomErrorMessage()\n        {\n            // Arrange\n            RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true;\n            var validator = Validator.Regex(\"^a+b+c$\", \"Example aaabbc\");\n\n            // Act\n            var result = validator.ClientValidationRule;\n\n            // Assert\n            Assert.Equal(\"regex\", result.ValidationType);\n            Assert.Equal(\"Example aaabbc\", result.ErrorMessage);\n            Assert.Equal(\"^a+b+c$\", result.ValidationParameters[\"pattern\"]);\n        }\n\n        private static HttpContextBase GetContext(object formValues = null)\n        {\n            var context = new Mock<HttpContextBase>();\n            var request = new Mock<HttpRequestBase>();\n\n            var nameValueCollection = new NameValueCollection();\n            if (formValues != null)\n            {\n                foreach (var prop in formValues.GetType().GetProperties())\n                {\n                    nameValueCollection.Add(prop.Name, prop.GetValue(formValues, null).ToString());\n                }\n            }\n            request.SetupGet(c => c.Form).Returns(nameValueCollection);\n            context.SetupGet(c => c.Request).Returns(request.Object);\n\n            return context.Object;\n        }\n\n        private static ValidationContext GetValidationContext(HttpContextBase httpContext, string memberName)\n        {\n            return new ValidationContext(httpContext, null, null) { MemberName = memberName };\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/ApplicationStartPageTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Reflection;\nusing System.Text;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class ApplicationStartPageTest\n    {\n        [Fact]\n        public void StartPageBasicTest()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                var page = new ApplicationStartPageTest().CreateStartPage(p =>\n                {\n                    p.AppState[\"x\"] = \"y\";\n                    p.WriteLiteral(\"test\");\n                });\n                page.ExecuteInternal();\n                Assert.Equal(\"y\", page.ApplicationState[\"x\"]);\n                Assert.Equal(\"test\", ApplicationStartPage.Markup.ToHtmlString());\n            });\n        }\n\n        [Fact]\n        public void StartPageDynamicAppStateBasicTest()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                var page = new ApplicationStartPageTest().CreateStartPage(p =>\n                {\n                    p.App.x = \"y\";\n                    p.WriteLiteral(\"test\");\n                });\n                page.ExecuteInternal();\n                Assert.Equal(\"y\", page.ApplicationState[\"x\"]);\n                Assert.Equal(\"y\", page.App[\"x\"]);\n                Assert.Equal(\"y\", page.App.x);\n                Assert.Equal(\"test\", ApplicationStartPage.Markup.ToHtmlString());\n            });\n        }\n\n        [Fact]\n        public void ExceptionTest()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                var msg = \"This is an error message\";\n                var e = new InvalidOperationException(msg);\n                var page = new ApplicationStartPageTest().CreateStartPage(p => { throw e; });\n                var ex = Assert.Throws<HttpException>(() => page.ExecuteStartPage());\n                Assert.Equal(msg, ex.InnerException.Message);\n                Assert.Equal(e, ApplicationStartPage.Exception);\n            });\n        }\n\n        [Fact]\n        public void HtmlEncodeTest()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                // Set HideRequestResponse to true to simulate the condition in IIS 7/7.5\n                var context = new HttpContext(new HttpRequest(\"default.cshtml\", \"http://localhost/default.cshtml\", null), new HttpResponse(new StringWriter(new StringBuilder())));\n                var hideRequestResponse = typeof(HttpContext).GetField(\"HideRequestResponse\", BindingFlags.NonPublic | BindingFlags.Instance);\n                hideRequestResponse.SetValue(context, true);\n\n                HttpContext.Current = context;\n                var page = new ApplicationStartPageTest().CreateStartPage(p => { p.Write(\"test\"); });\n                page.ExecuteStartPage();\n            });\n        }\n\n        [Fact]\n        public void GetVirtualPathTest()\n        {\n            var page = new MockStartPage();\n            Assert.Equal(ApplicationStartPage.StartPageVirtualPath, page.VirtualPath);\n        }\n\n        [Fact]\n        public void SetVirtualPathTest()\n        {\n            var page = new MockStartPage();\n            Assert.Throws<NotSupportedException>(() => { page.VirtualPath = \"~/hello.cshtml\"; });\n        }\n\n        [Fact]\n        public void ExecuteStartPageTest()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                var startPage = new MockStartPage() { ExecuteAction = p => p.AppState[\"x\"] = \"y\" };\n                var objectFactory = GetMockVirtualPathFactory(startPage);\n                ApplicationStartPage.ExecuteStartPage(new WebPageHttpApplication(),\n                                                      p => { },\n                                                      objectFactory,\n                                                      new string[] { \"cshtml\", \"vbhtml\" });\n                Assert.Equal(\"y\", startPage.ApplicationState[\"x\"]);\n            });\n        }\n\n        [Fact]\n        public void ExecuteStartPageDynamicAppStateTest()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                var startPage = new MockStartPage() { ExecuteAction = p => p.App.x = \"y\" };\n                var objectFactory = GetMockVirtualPathFactory(startPage);\n                ApplicationStartPage.ExecuteStartPage(new WebPageHttpApplication(),\n                                                      p => { },\n                                                      objectFactory,\n                                                      new string[] { \"cshtml\", \"vbhtml\" });\n                Assert.Equal(\"y\", startPage.ApplicationState[\"x\"]);\n                Assert.Equal(\"y\", startPage.App.x);\n                Assert.Equal(\"y\", startPage.App[\"x\"]);\n            });\n        }\n\n        public class MockStartPage : ApplicationStartPage\n        {\n            public Action<ApplicationStartPage> ExecuteAction { get; set; }\n            public HttpApplicationStateBase ApplicationState = new HttpApplicationStateWrapper(Activator.CreateInstance(typeof(HttpApplicationState), true) as HttpApplicationState);\n\n            public override void Execute()\n            {\n                ExecuteAction(this);\n            }\n\n            public override HttpApplicationStateBase AppState\n            {\n                get { return ApplicationState; }\n            }\n\n            public void ExecuteStartPage()\n            {\n                ExecuteStartPage(new WebPageHttpApplication(),\n                                 p => { },\n                                 GetMockVirtualPathFactory(this),\n                                 new string[] { \"cshtml\", \"vbhtml\" });\n            }\n        }\n\n        public MockStartPage CreateStartPage(Action<ApplicationStartPage> action)\n        {\n            var startPage = new MockStartPage() { ExecuteAction = action };\n            return startPage;\n        }\n\n        public sealed class WebPageHttpApplication : HttpApplication\n        {\n        }\n\n        private static IVirtualPathFactory GetMockVirtualPathFactory(ApplicationStartPage page)\n        {\n            var mockFactory = new Mock<IVirtualPathFactory>();\n            mockFactory.Setup(c => c.Exists(It.IsAny<string>())).Returns<string>(_ => true);\n            mockFactory.Setup(c => c.CreateInstance(It.IsAny<string>())).Returns<string>(_ => page);\n\n            return mockFactory.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/BrowserHelpersTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Web.Configuration;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class BrowserHelpersTest\n    {\n        [Fact]\n        public void GetOverriddenUserAgentGetsUserAgentFromHttpContext()\n        {\n            // Arrange\n            Mock<HttpContextBase> context = CookieBrowserOverrideStoreTest.CreateCookieContext();\n            string testUserAgent = \"testUserAgent\";\n\n            // Act\n            context.Object.SetOverriddenBrowser(testUserAgent);\n            Assert.Equal(testUserAgent, context.Object.GetOverriddenUserAgent());\n            context.Object.Response.Cookies.Clear();\n            context.Object.Request.Cookies.Clear();\n\n            // Assert\n            Assert.Equal(testUserAgent, context.Object.GetOverriddenUserAgent());\n        }\n\n        [Fact]\n        public void GetOverriddenUserAgentFallsBackToStoreUserAgent()\n        {\n            // Arrange\n            string testUserAgent = \"testUserAgent\";\n            HttpCookie existingOverrideCookie = new HttpCookie(CookieBrowserOverrideStore.BrowserOverrideCookieName, testUserAgent);\n            HttpContextBase context = CookieBrowserOverrideStoreTest.CreateCookieContext(requestCookie: existingOverrideCookie).Object;\n\n            // Act & Assert\n            Assert.Equal(testUserAgent, context.GetOverriddenUserAgent());\n        }\n\n        [Fact]\n        public void GetOverriddenUserAgentDefaultsToRequestUserAgent()\n        {\n            // Arrange\n            Mock<HttpContextBase> context = CookieBrowserOverrideStoreTest.CreateCookieContext();\n            context.Setup(c => c.Request.UserAgent).Returns(\"requestUserAgent\");\n\n            // Act & Assert\n            Assert.Equal(\"requestUserAgent\", context.Object.GetOverriddenUserAgent());\n        }\n\n        [Fact]\n        public void SetOverriddenBrowserWithBrowserOverrideSetBrowserMobile()\n        {\n            // Arrange\n            Mock<HttpContextBase> context = CookieBrowserOverrideStoreTest.CreateCookieContext();\n            context.Setup(c => c.Request.Browser.IsMobileDevice).Returns(false);\n\n            // Act\n            context.Object.SetOverriddenBrowser(BrowserOverride.Mobile);\n\n            // Assert\n            Assert.True(context.Object.GetOverriddenBrowser(CreateBrowserThroughFactory).IsMobileDevice);\n        }\n\n        [Fact]\n        public void SetOverriddenBrowserWithUnsupportedBrowserOverrideClearsBrowser()\n        {\n            // Arrange\n            Mock<HttpContextBase> context = CookieBrowserOverrideStoreTest.CreateCookieContext();\n            Mock<HttpBrowserCapabilitiesBase> requestBrowser = new Mock<HttpBrowserCapabilitiesBase>();\n            context.Setup(c => c.Request.Browser).Returns(requestBrowser.Object);\n\n            // Act & Assert\n            context.Object.SetOverriddenBrowser(BrowserOverride.Mobile);\n            Assert.NotSame(requestBrowser.Object, context.Object.GetOverriddenBrowser(CreateBrowserThroughFactory));\n\n            context.Object.SetOverriddenBrowser((BrowserOverride)(-1));\n            Assert.Same(requestBrowser.Object, context.Object.GetOverriddenBrowser(CreateBrowserThroughFactory));\n        }\n\n        [Fact]\n        public void SetOverriddenBrowserWithBrowserOverrideSetBrowserDesktop()\n        {\n            // Arrange\n            Mock<HttpContextBase> context = CookieBrowserOverrideStoreTest.CreateCookieContext();\n            context.Setup(c => c.Request.Browser.IsMobileDevice).Returns(true);\n\n            // Act\n            context.Object.SetOverriddenBrowser(BrowserOverride.Desktop);\n\n            // Assert\n            Assert.False(context.Object.GetOverriddenBrowser(CreateBrowserThroughFactory).IsMobileDevice);\n        }\n\n        [Fact]\n        public void SetOverriddenBrowserWithStringOverrideSetBrowser()\n        {\n            // Arrange\n            Mock<HttpContextBase> context = CookieBrowserOverrideStoreTest.CreateCookieContext();\n            context.Setup(c => c.Request.Browser.IsMobileDevice).Returns(false);\n\n            // Act\n            context.Object.SetOverriddenBrowser(\"Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16\");\n\n            // Assert\n            Assert.True(context.Object.GetOverriddenBrowser(CreateBrowserThroughFactory).IsMobileDevice);\n        }\n\n        [Fact]\n        public void SetOverriddenBrowserClearsCachedBrowser()\n        {\n            // Arrange\n            Mock<HttpContextBase> context = CookieBrowserOverrideStoreTest.CreateCookieContext();\n            context.Setup(c => c.Request.UserAgent).Returns(\"testUserAgent\");\n\n            // Act\n            context.Object.SetOverriddenBrowser(BrowserOverride.Mobile);\n            context.Object.GetOverriddenBrowser(CreateBrowserThroughFactory);\n\n            // If the browser is generated this will throw an exception because we are going through the provider.\n            // We must be getting the cached overridden browser.\n            context.Object.GetOverriddenBrowser();\n            context.Object.SetOverriddenBrowser(\"testUserAgent\");\n\n            // Assert\n\n            // The browser has been cleared from HttpContext and the user agent has been set to the original user agent.\n            // Otherwise we will either get the cached browser or an exception when trying to generate the browser from the\n            // mobile user agent.\n            Assert.Null(context.Object.GetOverriddenBrowser());\n        }\n\n        [Fact]\n        public void SetOverridenBrowserInSameOverrideClassClearsOverridenBrowser()\n        {\n            // Arrange\n            Mock<HttpContextBase> context = CookieBrowserOverrideStoreTest.CreateCookieContext();\n            context.Setup(c => c.Request.Browser.IsMobileDevice).Returns(true);\n            context.Setup(c => c.Request.UserAgent).Returns(\"sampleUserAgent\");\n\n            // Act\n            context.Object.SetOverriddenBrowser(BrowserOverride.Desktop);\n            context.Object.SetOverriddenBrowser(BrowserOverride.Mobile);\n\n            // Assert\n            Assert.Equal(\"sampleUserAgent\", context.Object.GetOverriddenUserAgent());\n        }\n\n        [Fact]\n        public void GetOverriddenBrowserGetsBrowserFromHttpContext()\n        {\n            // Arrange\n            Mock<HttpContextBase> context = CookieBrowserOverrideStoreTest.CreateCookieContext();\n\n            // Act\n            context.Object.SetOverriddenBrowser(BrowserOverride.Mobile);\n            context.Object.GetOverriddenBrowser(CreateBrowserThroughFactory);\n\n            // Assert\n\n            // If the browser is generated this will throw an exception because we are going through the provider.\n            // We must be getting the cached overridden browser.\n            Assert.True(context.Object.GetOverriddenBrowser().IsMobileDevice);\n        }\n\n        [Fact]\n        public void GetOverriddenBrowserWithStoredBrowserAndNoBrowserInContext()\n        {\n            // Arrange\n            string mobileUserAgent = \"Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16\";\n            HttpCookie existingOverrideCookie = new HttpCookie(CookieBrowserOverrideStore.BrowserOverrideCookieName, mobileUserAgent);\n            HttpContextBase context = CookieBrowserOverrideStoreTest.CreateCookieContext(requestCookie: existingOverrideCookie).Object;\n\n            // Act & Assert\n            Assert.True(context.GetOverriddenBrowser(CreateBrowserThroughFactory).IsMobileDevice);\n        }\n\n        [Fact]\n        public void GetOverriddenBrowserDefaultsToRequestBrowser()\n        {\n            // Arrange\n            Mock<HttpContextBase> context = CookieBrowserOverrideStoreTest.CreateCookieContext();\n            Mock<HttpBrowserCapabilitiesBase> currentBrowser = new Mock<HttpBrowserCapabilitiesBase>();\n            context.Setup(c => c.Request.Browser).Returns(currentBrowser.Object);\n\n            // Act & Assert\n            Assert.Same(currentBrowser.Object, context.Object.GetOverriddenBrowser());\n        }\n\n        [Fact]\n        public void ClearOverriddenBrowserClearsSetBrowser()\n        {\n            // Arrange\n            Mock<HttpContextBase> context = CookieBrowserOverrideStoreTest.CreateCookieContext();\n            Mock<HttpBrowserCapabilitiesBase> requestBrowser = new Mock<HttpBrowserCapabilitiesBase>();\n            context.Setup(c => c.Request.Browser).Returns(requestBrowser.Object);\n\n            // Act & Assert\n            context.Object.SetOverriddenBrowser(BrowserOverride.Mobile);\n            Assert.NotSame(requestBrowser.Object, context.Object.GetOverriddenBrowser(CreateBrowserThroughFactory));\n\n            context.Object.ClearOverriddenBrowser();\n            Assert.Same(requestBrowser.Object, context.Object.GetOverriddenBrowser(CreateBrowserThroughFactory));\n        }\n\n        [Fact]\n        public void ClearOverriddenBrowserWithNoSetBrowser()\n        {\n            // Arrange\n            Mock<HttpContextBase> context = CookieBrowserOverrideStoreTest.CreateCookieContext();\n            Mock<HttpBrowserCapabilitiesBase> requestBrowser = new Mock<HttpBrowserCapabilitiesBase>();\n            context.Setup(c => c.Request.Browser).Returns(requestBrowser.Object);\n\n            // Act & Assert\n            context.Object.ClearOverriddenBrowser();\n            Assert.Same(requestBrowser.Object, context.Object.GetOverriddenBrowser(CreateBrowserThroughFactory));\n        }\n\n        [Fact]\n        public void GetOverriddenBrowserVariesBySetOverriddenBrowserMobile()\n        {\n            // Arrange\n            Mock<HttpContextBase> context = CookieBrowserOverrideStoreTest.CreateCookieContext();\n            Mock<HttpBrowserCapabilitiesBase> currentBrowser = new Mock<HttpBrowserCapabilitiesBase>();\n            currentBrowser.Setup(c => c.IsMobileDevice).Returns(true);\n            context.Setup(c => c.Request.Browser).Returns(currentBrowser.Object);\n\n            // Act\n            string originalBrowserType = GetOverriddenBrowserType(context.Object, CreateBrowserThroughFactory);\n\n            context.Object.SetOverriddenBrowser(BrowserOverride.Desktop);\n            string deskTopBrowserType = GetOverriddenBrowserType(context.Object, CreateBrowserThroughFactory);\n\n            context.Object.SetOverriddenBrowser(BrowserOverride.Mobile);\n            string mobileBrowserType = GetOverriddenBrowserType(context.Object, CreateBrowserThroughFactory);\n\n            // Assert\n            Assert.Equal(originalBrowserType, mobileBrowserType);\n            Assert.NotEqual(originalBrowserType, deskTopBrowserType);\n            Assert.NotEqual(mobileBrowserType, deskTopBrowserType);\n        }\n\n        [Fact]\n        public void GetOverriddenBrowserVariesBySetOverriddenBrowserDesktop()\n        {\n            // Arrange\n            Mock<HttpContextBase> context = CookieBrowserOverrideStoreTest.CreateCookieContext();\n            Mock<HttpBrowserCapabilitiesBase> currentBrowser = new Mock<HttpBrowserCapabilitiesBase>();\n            currentBrowser.Setup(c => c.IsMobileDevice).Returns(false);\n            context.Setup(c => c.Request.Browser).Returns(currentBrowser.Object);\n\n            // Act\n            string originalBrowserType = GetOverriddenBrowserType(context.Object, CreateBrowserThroughFactory);\n\n            context.Object.SetOverriddenBrowser(BrowserOverride.Mobile);\n            string mobileBrowserType = GetOverriddenBrowserType(context.Object, CreateBrowserThroughFactory);\n\n            context.Object.SetOverriddenBrowser(BrowserOverride.Desktop);\n            string deskTopBrowserType = GetOverriddenBrowserType(context.Object, CreateBrowserThroughFactory);\n\n            // Assert\n            Assert.NotEqual(originalBrowserType, mobileBrowserType);\n            Assert.Equal(originalBrowserType, deskTopBrowserType);\n            Assert.NotEqual(mobileBrowserType, deskTopBrowserType);\n        }\n\n        [Fact]\n        public void GetOverriddenBrowser_OverridenUserAgentMatchingIsCaseInsensitive()\n        {\n            // Arrange\n            string mobileUserAgent = \"Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16\";\n            string mobileUserAgentLowerCase = mobileUserAgent.ToLowerInvariant();\n\n            HttpCookie existingOverrideCookie = new HttpCookie(CookieBrowserOverrideStore.BrowserOverrideCookieName, mobileUserAgent);\n            HttpContextBase context = CookieBrowserOverrideStoreTest.CreateCookieContext(requestCookie: existingOverrideCookie).Object;\n            Mock.Get(context).Setup(c => c.Request.UserAgent).Returns(mobileUserAgent);\n            Mock.Get(context).Setup(c => c.Request.Browser).Returns(new HttpBrowserCapabilitiesWrapper(new HttpBrowserCapabilities()));\n\n            // this will set the overriden user agent\n            context.SetOverriddenBrowser(mobileUserAgentLowerCase);\n\n            // overriden browser is only created if the overriden userAgent is different from the request's user agent\n            bool overridenBrowserWasCreated = false;\n\n            // Act\n            var overriden = context.GetOverriddenBrowser(x => { overridenBrowserWasCreated = true; return null; });\n\n            // Assert\n            Assert.False(overridenBrowserWasCreated);\n            Assert.Same(context.Request.Browser, overriden);\n        }\n\n        // We need to call the .ctor of SimpleWorkerRequest that depends on HttpRuntime so for unit testing\n        // simply create the browser capabilities by going directly through the factory.\n        private static HttpBrowserCapabilitiesBase CreateBrowserThroughFactory(string userAgent)\n        {\n            HttpBrowserCapabilities browser = new HttpBrowserCapabilities\n            {\n                Capabilities = new Dictionary<string, string>\n                {\n                    { String.Empty, userAgent }\n                }\n            };\n\n            BrowserCapabilitiesFactory factory = new BrowserCapabilitiesFactory();\n            factory.ConfigureBrowserCapabilities(new NameValueCollection(), browser);\n\n            return new HttpBrowserCapabilitiesWrapper(browser);\n        }\n\n        private static string GetOverriddenBrowserType(HttpContextBase context, Func<string, HttpBrowserCapabilitiesBase> factory)\n        {\n            return context.GetOverriddenBrowser(factory).Type;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/BrowserOverrideStoresTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class BrowserOverrideStoresTest\n    {\n        [Fact]\n        public void DefaultBrowserOverrideStoreIsCookie()\n        {\n            // Act & Assert\n            Assert.Equal(typeof(CookieBrowserOverrideStore), BrowserOverrideStores.Current.GetType());\n        }\n\n        [Fact]\n        public void SetBrowserOverrideStoreReturnsSetBrowserOverrideStore()\n        {\n            // Arrange\n            BrowserOverrideStores stores = new BrowserOverrideStores();\n            Mock<BrowserOverrideStore> store = new Mock<BrowserOverrideStore>();\n\n            // Act\n            stores.CurrentInternal = store.Object;\n\n            // Assert\n            Assert.Same(store.Object, stores.CurrentInternal);\n        }\n\n        [Fact]\n        public void SetBrowserOverrideStoreNullReturnsRequestBrowserOverrideStore()\n        {\n            //Arrange\n            BrowserOverrideStores stores = new BrowserOverrideStores();\n\n            // Act\n            stores.CurrentInternal = null;\n\n            // Assert\n            Assert.Equal(typeof(RequestBrowserOverrideStore), stores.CurrentInternal.GetType());\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/BuildManagerExceptionUtilTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Runtime.CompilerServices;\nusing System.Web.WebPages.Resources;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Test\n{\n    public class UtilTest\n    {\n        [Fact]\n        public void IsUnsupportedExtensionError()\n        {\n            Assert.False(BuildManagerExceptionUtil.IsUnsupportedExtensionError(new HttpException(\"The following file could not be rendered because its extension \\\".txt\\\" might not be supported: \\\"myfile.txt\\\".\")));\n\n            var e = CompilationUtil.GetBuildProviderException(\".txt\");\n            Assert.NotNull(e);\n            Assert.True(BuildManagerExceptionUtil.IsUnsupportedExtensionError(e));\n        }\n\n        [Fact]\n        public void IsUnsupportedExtensionThrowsTest()\n        {\n            var extension = \".txt\";\n            var virtualPath = \"Layout.txt\";\n            var e = CompilationUtil.GetBuildProviderException(extension);\n\n            Assert.Throws<HttpException>(\n                () => { BuildManagerExceptionUtil.ThrowIfUnsupportedExtension(virtualPath, e); }, String.Format(CultureInfo.CurrentCulture, WebPageResources.WebPage_FileNotSupported, extension, virtualPath));\n        }\n\n        [Fact]\n        public void CodeDomDefinedExtensionThrowsTest()\n        {\n            var extension = \".js\";\n            var virtualPath = \"Layout.js\";\n\n            Assert.Throws<HttpException>(\n                () => { BuildManagerExceptionUtil.ThrowIfCodeDomDefinedExtension(virtualPath, new HttpCompileException()); }, String.Format(CultureInfo.CurrentCulture, WebPageResources.WebPage_FileNotSupported, extension, virtualPath));\n        }\n\n        [Fact]\n        public void CodeDomDefinedExtensionDoesNotThrowTest()\n        {\n            var virtualPath = \"Layout.txt\";\n            // Should not throw an exception\n            BuildManagerExceptionUtil.ThrowIfCodeDomDefinedExtension(virtualPath, new HttpCompileException());\n        }\n    }\n\n    // Dummy class to simulate exception from CompilationUtil.GetBuildProviderTypeFromExtension\n    internal class CompilationUtil : IVirtualPathFactory\n    {\n        /// <remarks>\n        /// The method that consumes this exception walks the stack trace and uses the class name and method name to uniquely identify an exception.\n        /// In release build, the method is inlined causing the call site to appear as the method GetBuildProviderException which causes the test to fail.\n        /// These attributes prevent the compiler from inlining this method.\n        /// </remarks>\n        [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]\n        public static void GetBuildProviderTypeFromExtension(string extension)\n        {\n            throw new HttpException(extension);\n        }\n\n        public static HttpException GetBuildProviderException(string extension)\n        {\n            try\n            {\n                GetBuildProviderTypeFromExtension(extension);\n            }\n            catch (HttpException e)\n            {\n                return e;\n            }\n            return null;\n        }\n\n        public bool Exists(string virtualPath)\n        {\n            string extension = PathUtil.GetExtension(virtualPath);\n            GetBuildProviderTypeFromExtension(extension);\n            return false;\n        }\n\n        public object CreateInstance(string virtualPath)\n        {\n            throw new NotSupportedException();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/BuildManagerWrapperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Text;\nusing System.Web.Hosting;\nusing Microsoft.Internal.Web.Utils;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class BuildManagerWrapperTest\n    {\n        private const string _precompileConfigFileName = \"~/PrecompiledApp.config\";\n\n        [Fact]\n        public void CanCreateObjectFactoryReturnsFalseIfExtensionIsNotRegistered()\n        {\n            // Arrange\n            var buildManagerWrapper = CreateWrapperInstance();\n\n            // Act\n            bool supported = buildManagerWrapper.IsPathExtensionSupported(\"~/styles/index.css\");\n\n            // Assert\n            Assert.False(supported);\n        }\n\n        [Fact]\n        public void CanCreateObjectFactoryReturnsFalseIfVirtualPathIsExtensionless()\n        {\n            // Arrange\n            var buildManagerWrapper = CreateWrapperInstance();\n\n            // Act\n            bool supported = buildManagerWrapper.IsPathExtensionSupported(\"~/default\");\n\n            // Assert\n            Assert.False(supported);\n        }\n\n        [Fact]\n        public void CanCreateObjectFactoryReturnsFalseIfVirtualPathExtensionIsEmpty()\n        {\n            // Arrange\n            var buildManagerWrapper = CreateWrapperInstance();\n\n            // Act\n            bool supported = buildManagerWrapper.IsPathExtensionSupported(\"~/default.\");\n\n            // Assert\n            Assert.False(supported);\n        }\n\n        [Fact]\n        public void CanCreateObjectFactoryReturnsTrueIfVirtualPathExtensionIsRegistered()\n        {\n            // Arrange\n            var buildManagerWrapper = CreateWrapperInstance();\n\n            // Act\n            bool supported = buildManagerWrapper.IsPathExtensionSupported(\"~/default.cshtml\");\n\n            // Assert\n            Assert.True(supported);\n        }\n\n        [Fact]\n        public void CanCreateObjectFactoryPerformsCaseInsenitiveComparison()\n        {\n            // Arrange\n            var buildManagerWrapper = CreateWrapperInstance();\n\n            // Act\n            bool supported = buildManagerWrapper.IsPathExtensionSupported(\"~/default.CShTml\");\n\n            // Assert\n            Assert.True(supported);\n        }\n\n        [Fact]\n        public void CanCreateObjectFactoryWorksForAllRegisteredExtensions()\n        {\n            // Arrange\n            var buildManagerWrapper = CreateWrapperInstance();\n\n            // Act\n            bool supported = buildManagerWrapper.IsPathExtensionSupported(\"~/default.vbHtml\");\n\n            // Assert\n            Assert.True(supported);\n        }\n\n        [Fact]\n        public void IsNonPrecompiledAppReturnsFalseIfPrecompiledConfigFileDoesNotExist()\n        {\n            // Arrange\n            var vpp = new Mock<VirtualPathProvider>();\n            vpp.Setup(c => c.FileExists(It.IsAny<string>())).Returns(false);\n            var buildManagerWrapper = new BuildManagerWrapper(vpp.Object, GetVirtualPathUtility());\n\n            // Act\n            var isPrecompiled = buildManagerWrapper.IsNonUpdatablePrecompiledApp();\n\n            // Assert\n            Assert.False(isPrecompiled);\n            vpp.Verify();\n        }\n\n        [Fact]\n        public void IsNonPrecompiledAppReturnsFalseIfPrecompiledConfigFileIsNotValidXml()\n        {\n            // Arrange\n            var vpp = new Mock<VirtualPathProvider>();\n            vpp.Setup(c => c.FileExists(It.Is<string>(p => p.Equals(_precompileConfigFileName)))).Returns(true).Verifiable();\n            var file = new Mock<VirtualFile>();\n            vpp.Setup(c => c.GetFile(It.Is<string>(p => p.Equals(_precompileConfigFileName)))).Returns(GetFile(\"some random text that is clearly not xml!\"));\n            var buildManagerWrapper = new BuildManagerWrapper(vpp.Object, GetVirtualPathUtility());\n\n            // Act\n            var isPrecompiled = buildManagerWrapper.IsNonUpdatablePrecompiledApp();\n\n            // Assert\n            Assert.False(isPrecompiled);\n            vpp.Verify();\n        }\n\n        [Fact]\n        public void IsNonPrecompiledAppReturnsFalseIfConfigFileDoesNotContainExpectedElements()\n        {\n            // Arrange\n            var fileContent = @\"<?xml version=\"\"1.0\"\"?><configuration><appSettings></appSettings></configuration>\";\n            var vpp = new Mock<VirtualPathProvider>();\n            vpp.Setup(c => c.FileExists(It.Is<string>(p => p.Equals(_precompileConfigFileName)))).Returns(true).Verifiable();\n            vpp.Setup(c => c.GetFile(It.Is<string>(p => p.Equals(_precompileConfigFileName)))).Returns(GetFile(fileContent)).Verifiable();\n            var buildManagerWrapper = new BuildManagerWrapper(vpp.Object, GetVirtualPathUtility());\n\n            // Act\n            var isPrecompiled = buildManagerWrapper.IsNonUpdatablePrecompiledApp();\n\n            // Assert\n            Assert.False(isPrecompiled);\n            vpp.Verify();\n        }\n\n        [Fact]\n        public void IsNonPrecompiledAppReturnsFalseIfAppIsUpdatable()\n        {\n            // Arrange\n            var fileContent = @\"<precompiledApp version=\"\"2\"\" updatable=\"\"true\"\"/>\";\n            var vpp = new Mock<VirtualPathProvider>();\n            vpp.Setup(c => c.FileExists(It.Is<string>(p => p.Equals(_precompileConfigFileName)))).Returns(true).Verifiable();\n            vpp.Setup(c => c.GetFile(It.Is<string>(p => p.Equals(_precompileConfigFileName)))).Returns(GetFile(fileContent)).Verifiable();\n            var buildManagerWrapper = new BuildManagerWrapper(vpp.Object, GetVirtualPathUtility());\n\n            // Act\n            var isPrecompiled = buildManagerWrapper.IsNonUpdatablePrecompiledApp();\n\n            // Assert\n            Assert.False(isPrecompiled);\n            vpp.Verify();\n        }\n\n        [Fact]\n        public void IsNonPrecompiledAppReturnsTrueIfConfigFileIsValidAndIsAppIsNotUpdatable()\n        {\n            // Arrange\n            var fileContent = @\"<precompiledApp version=\"\"2\"\" updatable=\"\"false\"\"/>\";\n            var vpp = new Mock<VirtualPathProvider>();\n            vpp.Setup(c => c.FileExists(It.Is<string>(p => p.Equals(_precompileConfigFileName)))).Returns(true).Verifiable();\n            vpp.Setup(c => c.GetFile(It.Is<string>(p => p.Equals(_precompileConfigFileName)))).Returns(GetFile(fileContent)).Verifiable();\n            var buildManagerWrapper = new BuildManagerWrapper(vpp.Object, GetVirtualPathUtility());\n\n            // Act\n            var isPrecompiled = buildManagerWrapper.IsNonUpdatablePrecompiledApp();\n\n            // Assert\n            Assert.True(isPrecompiled);\n            vpp.Verify();\n        }\n\n        [Fact]\n        public void ExistsUsesVppIfSiteIfNotPrecompiled()\n        {\n            // Arrange\n            var virtualPath = \"~/default.cshtml\";\n            var vpp = new Mock<VirtualPathProvider>();\n            vpp.Setup(c => c.FileExists(It.Is<string>(p => p.Equals(_precompileConfigFileName)))).Returns(false).Verifiable();\n            vpp.Setup(c => c.FileExists(It.Is<string>(p => p.Equals(virtualPath)))).Returns(true).Verifiable();\n            var buildManagerWrapper = new BuildManagerWrapper(vpp.Object, GetVirtualPathUtility());\n\n            // Act\n            var exists = buildManagerWrapper.Exists(virtualPath);\n\n            // Assert\n            vpp.Verify();\n            Assert.True(exists);\n        }\n\n        [Fact]\n        public void ExistsUsesVppIfSiteIfSiteIsPrecompiledButUpdateable()\n        {\n            // Arrange\n            var virtualPath = \"~/default.cshtml\";\n            var fileContent = @\"<precompiledApp version=\"\"2\"\" updatable=\"\"true\"\"/>\";\n            var vpp = new Mock<VirtualPathProvider>();\n            vpp.Setup(c => c.FileExists(It.Is<string>(p => p.Equals(_precompileConfigFileName)))).Returns(true).Verifiable();\n            vpp.Setup(c => c.GetFile(It.Is<string>(p => p.Equals(_precompileConfigFileName)))).Returns(GetFile(fileContent)).Verifiable();\n            vpp.Setup(c => c.FileExists(It.Is<string>(p => p.Equals(virtualPath)))).Returns(true).Verifiable();\n            var buildManagerWrapper = new BuildManagerWrapper(vpp.Object, GetVirtualPathUtility());\n\n            // Act\n            var exists = buildManagerWrapper.Exists(virtualPath);\n\n            // Assert\n            vpp.Verify();\n            Assert.True(exists);\n        }\n\n        /// <remarks>\n        /// This method adds items to HttpRuntime.Cache. \n        /// </summary>\n        [Fact]\n        public void ExistsInPrecompiledReturnsFalseIfExtensionIsUnsupported()\n        {\n            // Arrange\n            var virtualPath = \"~/ExistsInPrecompiledReturnsFalseIfExtensionIsUnsupported.jpeg\";\n            var fileContent = @\"<precompiledApp version=\"\"2\"\" updatable=\"\"false\"\"/>\";\n            var vpp = new Mock<VirtualPathProvider>();\n            vpp.Setup(c => c.FileExists(It.Is<string>(p => p.Equals(_precompileConfigFileName)))).Returns(true).Verifiable();\n            vpp.Setup(c => c.GetFile(It.Is<string>(p => p.Equals(_precompileConfigFileName)))).Returns(GetFile(fileContent)).Verifiable();\n            var buildManagerWrapper = new BuildManagerWrapper(vpp.Object, GetVirtualPathUtility());\n\n            // Act\n            var exists = buildManagerWrapper.Exists(virtualPath);\n\n            // Assert\n            vpp.Verify();\n            Assert.False(exists);\n            object cachedValue = HttpRuntime.Cache.Get(BuildManagerWrapper.KeyGuid + \"_\" + virtualPath);\n            Assert.NotNull(cachedValue);\n            Assert.False((bool)cachedValue.GetType().GetProperty(\"Exists\").GetValue(cachedValue, null));\n        }\n\n        [Fact]\n        public void IsNonPrecompiledAppReturnsTrue_VPPRegistrationChanging()\n        {\n            // Arrange\n            string fileContent = @\"<precompiledApp version=\"\"2\"\" updatable=\"\"false\"\"/>\";\n            IVirtualPathUtility pathUtility = GetVirtualPathUtility();\n\n            Mock<VirtualPathProvider> mockProvider1 = new Mock<VirtualPathProvider>();\n            mockProvider1.Setup(c => c.FileExists(It.Is<string>(p => p.Equals(_precompileConfigFileName)))).Returns(true).Verifiable();\n            mockProvider1.Setup(c => c.GetFile(It.Is<string>(p => p.Equals(_precompileConfigFileName)))).Returns(GetFile(fileContent)).Verifiable();\n\n            Mock<VirtualPathProvider> mockProvider2 = new Mock<VirtualPathProvider>();\n            mockProvider2.Setup(c => c.FileExists(It.Is<string>(p => p.Equals(_precompileConfigFileName)))).Returns(true).Verifiable();\n            mockProvider2.Setup(c => c.GetFile(It.Is<string>(p => p.Equals(_precompileConfigFileName)))).Returns(GetFile(fileContent)).Verifiable();\n\n            VirtualPathProvider provider = mockProvider1.Object;\n\n            // Act; uses one VirtualPathProvider in constructor and the other when IsNonUpdatablePrecompiledApp() is called directly\n            BuildManagerWrapper buildManagerWrapper = new BuildManagerWrapper(() => provider, pathUtility);\n\n            // The moral equivalent of HostingEnvironment.RegisterVirtualPathProvider(provider2.Object)\n            provider = mockProvider2.Object;\n\n            bool isPrecompiled = buildManagerWrapper.IsNonUpdatablePrecompiledApp();\n\n            // Assert\n            Assert.True(isPrecompiled);\n            mockProvider1.Verify();\n            mockProvider1.Verify(vpp => vpp.FileExists(It.IsAny<string>()), Times.Once());\n            mockProvider1.Verify(vpp => vpp.GetFile(It.IsAny<string>()), Times.Once());\n            mockProvider2.Verify();\n            mockProvider2.Verify(vpp => vpp.FileExists(It.IsAny<string>()), Times.Once());\n            mockProvider2.Verify(vpp => vpp.GetFile(It.IsAny<string>()), Times.Once());\n        }\n\n        private static BuildManagerWrapper CreateWrapperInstance(IEnumerable<string> supportedExtensions = null)\n        {\n            return new BuildManagerWrapper(new Mock<VirtualPathProvider>().Object, GetVirtualPathUtility()) { SupportedExtensions = supportedExtensions ?? new[] { \"cshtml\", \"vbhtml\" } };\n        }\n\n        private static VirtualFile GetFile(string content)\n        {\n            var file = new Mock<VirtualFile>(\"test file\");\n            file.Setup(f => f.Open()).Returns(() => new MemoryStream(Encoding.UTF8.GetBytes(content)));\n            return file.Object;\n        }\n\n        private static IVirtualPathUtility GetVirtualPathUtility()\n        {\n            var utility = new Mock<VirtualPathUtilityBase>();\n            utility.Setup(c => c.ToAbsolute(It.IsAny<string>())).Returns<string>(c => c);\n\n            return utility.Object;\n        }\n    }\n\n    public abstract class VirtualPathUtilityBase : IVirtualPathUtility\n    {\n        public virtual string Combine(string basePath, string relativePath)\n        {\n            throw new NotImplementedException();\n        }\n\n        public virtual string ToAbsolute(string virtualPath)\n        {\n            throw new NotImplementedException();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/CookieBrowserOverrideStoreTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class CookieBrowserOverrideStoreTest\n    {\n        [Fact]\n        public void GetOverriddenUserAgentReturnsNullIfNoResponseOrRequestCookieIsSet()\n        {\n            // Arrange\n            CookieBrowserOverrideStore store = new CookieBrowserOverrideStore();\n\n            // Act & Assert\n            Assert.Null(store.GetOverriddenUserAgent(CreateCookieContext().Object));\n        }\n\n        [Fact]\n        public void GetOverriddenUserAgentReturnsUserAgentFromRequestCookieIfNoResponseCookie()\n        {\n            // Arrange\n            CookieBrowserOverrideStore store = new CookieBrowserOverrideStore();\n            HttpCookie existingOverrideCookie = new HttpCookie(CookieBrowserOverrideStore.BrowserOverrideCookieName, \"existingRequestAgent\");\n            HttpContextBase context = CreateCookieContext(requestCookie: existingOverrideCookie).Object;\n\n            // Act & Assert\n            Assert.Equal(\"existingRequestAgent\", store.GetOverriddenUserAgent(context));\n        }\n\n        [Fact]\n        public void SetOverriddenUserAgentWithNoExistingCookie()\n        {\n            // Arrange\n            CookieBrowserOverrideStore store = new CookieBrowserOverrideStore();\n            HttpContextBase context = CreateCookieContext().Object;\n\n            // Act\n            store.SetOverriddenUserAgent(context, \"setUserAgent\");\n\n            // Assert\n            Assert.Equal(\"setUserAgent\", store.GetOverriddenUserAgent(context));\n        }\n\n        [Fact]\n        public void SetOverriddenUserWithExistingRequestCookie()\n        {\n            // Arrange\n            CookieBrowserOverrideStore store = new CookieBrowserOverrideStore();\n            HttpCookie existingOverrideCookie = new HttpCookie(CookieBrowserOverrideStore.BrowserOverrideCookieName, \"existingRequestAgent\");\n            HttpContextBase context = CreateCookieContext(requestCookie: existingOverrideCookie).Object;\n\n            // Act\n            store.SetOverriddenUserAgent(context, \"setUserAgent\");\n\n            // Assert\n            Assert.Equal(\"setUserAgent\", store.GetOverriddenUserAgent(context));\n        }\n\n        [Fact]\n        public void SetOverriddenUserWithExistingResponseCookie()\n        {\n            // Arrange\n            CookieBrowserOverrideStore store = new CookieBrowserOverrideStore();\n            HttpContextBase context = CreateCookieContext().Object;\n\n            // Act & Assert\n            store.SetOverriddenUserAgent(context, \"testUserAgent\");\n            Assert.Equal(\"testUserAgent\", store.GetOverriddenUserAgent(context));\n\n            store.SetOverriddenUserAgent(context, \"subsequentTestUserAgent\");\n            Assert.Equal(\"subsequentTestUserAgent\", store.GetOverriddenUserAgent(context));\n        }\n\n        [Fact]\n        public void SetOverriddenUserAgentNullWithRequestCookie()\n        {\n            // Arrange\n            CookieBrowserOverrideStore store = new CookieBrowserOverrideStore();\n            HttpCookie existingOverrideCookie = new HttpCookie(CookieBrowserOverrideStore.BrowserOverrideCookieName, \"setUserAgent\");\n            HttpContextBase context = CreateCookieContext(requestCookie: existingOverrideCookie).Object;\n\n            // Act\n            store.SetOverriddenUserAgent(context, null);\n\n            // Assert\n            Assert.Null(store.GetOverriddenUserAgent(context));\n        }\n\n        [Fact]\n        public void SetOverriddenUserAgentNullWithNoExistingCookie()\n        {\n            // Arrange\n            CookieBrowserOverrideStore store = new CookieBrowserOverrideStore();\n            HttpContextBase context = CreateCookieContext().Object;\n\n            // Act\n            store.SetOverriddenUserAgent(context, null);\n\n            // Assert\n            Assert.Null(store.GetOverriddenUserAgent(context));\n        }\n\n        [Fact]\n        public void SetOverriddenUserAgentSetsExpiration()\n        {\n            // Arrange\n            CookieBrowserOverrideStore store = new CookieBrowserOverrideStore();\n            CookieBrowserOverrideStore sessionStore = new CookieBrowserOverrideStore(daysToExpire: 0);\n            CookieBrowserOverrideStore longTermStore = new CookieBrowserOverrideStore(daysToExpire: 100);\n            CookieBrowserOverrideStore negativeTermStore = new CookieBrowserOverrideStore(daysToExpire: -1);\n\n            HttpContextBase context = CreateCookieContext().Object;\n\n            // Act & Assert\n            store.SetOverriddenUserAgent(context, \"testUserAgent\");\n            Assert.True(DateTime.Now.AddDays(6.5) < context.Response.Cookies[CookieBrowserOverrideStore.BrowserOverrideCookieName].Expires &&\n                        context.Response.Cookies[CookieBrowserOverrideStore.BrowserOverrideCookieName].Expires < DateTime.Now.AddDays(7.5));\n\n            sessionStore.SetOverriddenUserAgent(context, \"testUserAgent\");\n            Assert.True(context.Response.Cookies[CookieBrowserOverrideStore.BrowserOverrideCookieName].Expires < DateTime.Now);\n\n            longTermStore.SetOverriddenUserAgent(context, \"testUserAgent\");\n            Assert.True(context.Response.Cookies[CookieBrowserOverrideStore.BrowserOverrideCookieName].Expires > DateTime.Now.AddDays(99));\n\n            negativeTermStore.SetOverriddenUserAgent(context, \"testUserAgent\");\n            Assert.True(context.Response.Cookies[CookieBrowserOverrideStore.BrowserOverrideCookieName].Expires < DateTime.Now);\n        }\n\n        internal static Mock<HttpContextBase> CreateCookieContext(HttpCookie requestCookie = null, HttpCookie responseCookie = null)\n        {\n            Mock<HttpContextBase> context = new Mock<HttpContextBase>();\n\n            HttpCookieCollection requestCookies = new HttpCookieCollection();\n            if (requestCookie != null)\n            {\n                requestCookies.Add(requestCookie);\n            }\n\n            HttpCookieCollection responseCookies = new HttpCookieCollection();\n            if (responseCookie != null)\n            {\n                responseCookies.Add(responseCookie);\n            }\n\n            context.Setup(c => c.Request.Cookies).Returns(requestCookies);\n            context.Setup(c => c.Response.Cookies).Returns(responseCookies);\n            context.Setup(c => c.Items).Returns(new Hashtable());\n\n            return context;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/DefaultDisplayModeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class DefaultDisplayModeTest\n    {\n        [Fact]\n        public void DefaultDisplayModeWithEmptySuffix()\n        {\n            // Arrange\n            DefaultDisplayMode displayMode = new DefaultDisplayMode();\n\n            // Act\n            DisplayInfo info = displayMode.GetDisplayInfo(new Mock<HttpContextBase>(MockBehavior.Strict).Object, \"/bar/baz.aspx\", virtualPath => true);\n\n            // Assert\n            Assert.Equal(String.Empty, displayMode.DisplayModeId);\n            Assert.Equal(\"/bar/baz.aspx\", info.FilePath);\n        }\n\n        [Fact]\n        public void DefaultDisplayModeWithNullSuffix()\n        {\n            // Arrange\n            DefaultDisplayMode displayMode = new DefaultDisplayMode(null);\n\n            // Act\n            DisplayInfo info = displayMode.GetDisplayInfo(new Mock<HttpContextBase>(MockBehavior.Strict).Object, \"/bar/baz.aspx\", virtualPath => true);\n\n            // Assert\n            Assert.Equal(String.Empty, displayMode.DisplayModeId);\n            Assert.Equal(\"/bar/baz.aspx\", info.FilePath);\n        }\n\n        [Fact]\n        public void DefaultDisplayModeSetSuffixAsId()\n        {\n            // Arrange\n            DefaultDisplayMode displayMode = new DefaultDisplayMode(\"foo\");\n\n            // Act & Assert\n            Assert.Equal(\"foo\", displayMode.DisplayModeId);\n        }\n\n        [Fact]\n        public void GetDisplayInfoWithNullOrEmptySuffixReturnsPathThatExists()\n        {\n            // Arrange\n            DefaultDisplayMode displayMode = new DefaultDisplayMode(\"foo\");\n\n            // Act\n            DisplayInfo info = displayMode.GetDisplayInfo(new Mock<HttpContextBase>(MockBehavior.Strict).Object, \"/bar/baz.aspx\", virtualPath => true);\n\n            // Assert\n            Assert.IsType<DefaultDisplayMode>(info.DisplayMode);\n            Assert.Equal(\"/bar/baz.foo.aspx\", info.FilePath);\n        }\n\n        [Fact]\n        public void GetDisplayInfoInsertsSuffixIntoVirtualPathThatExists()\n        {\n            // Arrange\n            DefaultDisplayMode displayMode = new DefaultDisplayMode(\"foo\");\n\n            // Act\n            DisplayInfo info = displayMode.GetDisplayInfo(new Mock<HttpContextBase>(MockBehavior.Strict).Object, \"/bar/baz.aspx\", virtualPath => true);\n\n            // Assert\n            Assert.IsType<DefaultDisplayMode>(info.DisplayMode);\n            Assert.Equal(\"/bar/baz.foo.aspx\", info.FilePath);\n        }\n\n        [Fact]\n        public void GetDisplayInfoInsertsSuffixBeforeLastSectionOfExtension()\n        {\n            // Arrange\n            DefaultDisplayMode displayMode = new DefaultDisplayMode(\"foo\");\n\n            // Act\n            DisplayInfo info = displayMode.GetDisplayInfo(new Mock<HttpContextBase>(MockBehavior.Strict).Object, \"/bar/baz.txt.aspx\", virtualPath => true);\n\n            // Assert\n            Assert.Equal(\"/bar/baz.txt.foo.aspx\", info.FilePath);\n        }\n\n        [Fact]\n        public void GetDisplayInfoSuffixesPathWithNoExtension()\n        {\n            // Arrange\n            DefaultDisplayMode displayMode = new DefaultDisplayMode(\"foo\");\n\n            // Act\n            DisplayInfo info = displayMode.GetDisplayInfo(new Mock<HttpContextBase>(MockBehavior.Strict).Object, \"/bar/baz\", virtualPath => true);\n\n            // Assert\n            Assert.Equal(\"/bar/baz.foo\", info.FilePath);\n        }\n\n        [Fact]\n        public void GetDisplayInfoWithNullVirtualPath()\n        {\n            // Arrange\n            DefaultDisplayMode displayMode = new DefaultDisplayMode(\"foo\");\n\n            // Act\n            DisplayInfo info = displayMode.GetDisplayInfo(new Mock<HttpContextBase>(MockBehavior.Strict).Object, virtualPath: null, virtualPathExists: virtualPath => true);\n\n            // Assert\n            Assert.Null(info);\n        }\n\n        [Fact]\n        public void GetDisplayInfoSuffixesPathWithEmptyVirtualPath()\n        {\n            // Arrange\n            DefaultDisplayMode displayMode = new DefaultDisplayMode(\"foo\");\n\n            // Act\n            DisplayInfo info = displayMode.GetDisplayInfo(new Mock<HttpContextBase>(MockBehavior.Strict).Object, String.Empty, virtualPath => true);\n\n            // Assert\n            Assert.Equal(String.Empty, info.FilePath);\n        }\n\n        [Fact]\n        public void GetDisplayInfoReturnsNullIfPathDoesNotExist()\n        {\n            // Arrange\n            DefaultDisplayMode displayMode = new DefaultDisplayMode(\"foo\");\n\n            // Act\n            DisplayInfo info = displayMode.GetDisplayInfo(new Mock<HttpContextBase>(MockBehavior.Strict).Object, \"/bar/baz\", virtualPath => false);\n\n            // Assert\n            Assert.Null(info);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/DisplayInfoTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class DisplayInfoTest\n    {\n        [Fact]\n        public void GuardClauses()\n        {\n            // Act & Assert\n            Assert.ThrowsArgumentNull(() => new DisplayInfo(filePath: null, displayMode: new Mock<IDisplayMode>().Object), \"filePath\");\n            Assert.ThrowsArgumentNull(() => new DisplayInfo(\"testPath\", displayMode: null), \"displayMode\");\n        }\n\n        [Fact]\n        public void ConstructorSetsDisplayInfoProperties()\n        {\n            // Arrange\n            string path = \"testPath\";\n            IDisplayMode displayMode = new Mock<IDisplayMode>().Object;\n\n            // Act\n            DisplayInfo info = new DisplayInfo(path, displayMode);\n\n            // Assert\n            Assert.Equal(path, info.FilePath);\n            Assert.Equal(displayMode, info.DisplayMode);\n        }\n\n        [Fact]\n        public void ConstructorSetsEmptyFilePath()\n        {\n            // Act & Assert\n            Assert.Equal(String.Empty, new DisplayInfo(String.Empty, new Mock<IDisplayMode>().Object).FilePath);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/DisplayModeProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class DisplayModesTest\n    {\n        [Fact]\n        public void DefaultInstanceHasDefaultModes()\n        {\n            // Act\n            IList<IDisplayMode> displayModes = DisplayModeProvider.Instance.Modes;\n\n            // Assert\n            Assert.Equal(2, displayModes.Count);\n\n            Assert.IsType<DefaultDisplayMode>(displayModes[0]);\n            Assert.Equal(displayModes[0].DisplayModeId, DisplayModeProvider.MobileDisplayModeId);\n\n            Assert.IsType<DefaultDisplayMode>(displayModes[1]);\n            Assert.Equal(displayModes[1].DisplayModeId, DisplayModeProvider.DefaultDisplayModeId);\n        }\n\n        [Fact]\n        public void GetDisplayInfoForVirtualPathReturnsDisplayInfoFromFirstDisplayModeToHandleRequest()\n        {\n            // Arrange\n            var displayModeProvider = new DisplayModeProvider();\n            displayModeProvider.Modes.Clear();\n            var displayMode1 = new Mock<IDisplayMode>(MockBehavior.Strict);\n            displayMode1.Setup(d => d.CanHandleContext(It.IsAny<HttpContextBase>())).Returns(false);\n            displayModeProvider.Modes.Add(displayMode1.Object);\n\n            var displayMode2 = new Mock<IDisplayMode>(MockBehavior.Strict);\n            displayMode2.Setup(d => d.CanHandleContext(It.IsAny<HttpContextBase>())).Returns(false);\n            displayModeProvider.Modes.Add(displayMode2.Object);\n\n            var displayMode3 = new Mock<IDisplayMode>(MockBehavior.Strict);\n            displayMode3.Setup(d => d.CanHandleContext(It.IsAny<HttpContextBase>())).Returns(true);\n            displayModeProvider.Modes.Add(displayMode3.Object);\n\n            Mock<HttpContextBase> httpContext = new Mock<HttpContextBase>(MockBehavior.Strict);\n\n            var expected = new DisplayInfo(\"Foo\", displayMode3.Object);\n            Func<string, bool> fileExists = path => true;\n            displayMode3.Setup(d => d.GetDisplayInfo(httpContext.Object, \"path\", fileExists)).Returns(expected);\n\n            // Act\n            DisplayInfo result = displayModeProvider.GetDisplayInfoForVirtualPath(\"path\", httpContext.Object, fileExists, currentDisplayMode: null);\n\n            // Assert\n            Assert.Same(expected, result);\n        }\n\n        [Fact]\n        public void GetDisplayInfoForVirtualPathWithConsistentDisplayModeBeginsSearchAtCurrentDisplayMode()\n        {\n            // Arrange\n            Mock<HttpContextBase> httpContext = new Mock<HttpContextBase>(MockBehavior.Strict);\n\n            var displayModeProvider = new DisplayModeProvider();\n            displayModeProvider.Modes.Clear();\n            var displayMode1 = new Mock<IDisplayMode>(MockBehavior.Strict);\n            displayMode1.Setup(d => d.CanHandleContext(It.IsAny<HttpContextBase>())).Returns(true);\n            displayModeProvider.Modes.Add(displayMode1.Object);\n\n            var displayMode2 = new Mock<IDisplayMode>(MockBehavior.Strict);\n            displayMode2.Setup(d => d.CanHandleContext(It.IsAny<HttpContextBase>())).Returns(false);\n            displayModeProvider.Modes.Add(displayMode2.Object);\n\n            var displayMode3 = new Mock<IDisplayMode>(MockBehavior.Strict);\n            displayMode3.Setup(d => d.CanHandleContext(It.IsAny<HttpContextBase>())).Returns(true);\n            displayModeProvider.Modes.Add(displayMode3.Object);\n\n            var displayInfo = new DisplayInfo(\"Foo\", displayMode3.Object);\n            Func<string, bool> fileExists = path => true;\n            displayMode3.Setup(d => d.GetDisplayInfo(httpContext.Object, \"path\", fileExists)).Returns(displayInfo);\n\n            // Act\n            DisplayInfo result = displayModeProvider.GetDisplayInfoForVirtualPath(\"path\", httpContext.Object, fileExists, currentDisplayMode: displayMode2.Object,\n                requireConsistentDisplayMode: true);\n\n            // Assert\n            Assert.Same(displayInfo, result);\n        }\n\n        [Fact]\n        public void GetDisplayInfoForVirtualPathWithoutConsistentDisplayModeIgnoresCurrentDisplayMode()\n        {\n            // Arrange\n            Mock<HttpContextBase> httpContext = new Mock<HttpContextBase>(MockBehavior.Strict);\n            var displayModeProvider = new DisplayModeProvider();\n            displayModeProvider.Modes.Clear();\n            var displayMode1 = new Mock<IDisplayMode>(MockBehavior.Strict);\n            displayMode1.Setup(d => d.CanHandleContext(It.IsAny<HttpContextBase>())).Returns(true);\n            displayModeProvider.Modes.Add(displayMode1.Object);\n\n            var displayMode2 = new Mock<IDisplayMode>(MockBehavior.Strict);\n            displayMode2.Setup(d => d.CanHandleContext(It.IsAny<HttpContextBase>())).Returns(false);\n            displayModeProvider.Modes.Add(displayMode2.Object);\n\n            var displayMode3 = new Mock<IDisplayMode>(MockBehavior.Strict);\n            displayMode3.Setup(d => d.CanHandleContext(It.IsAny<HttpContextBase>())).Returns(true);\n            displayModeProvider.Modes.Add(displayMode3.Object);\n\n            var displayInfo = new DisplayInfo(\"Foo\", displayMode3.Object);\n            Func<string, bool> fileExists = path => true;\n            displayMode1.Setup(d => d.GetDisplayInfo(httpContext.Object, \"path\", fileExists)).Returns(displayInfo);\n\n            // Act\n            DisplayInfo result = displayModeProvider.GetDisplayInfoForVirtualPath(\"path\", httpContext.Object, fileExists, currentDisplayMode: displayMode1.Object,\n                requireConsistentDisplayMode: false);\n\n            // Assert\n            Assert.Same(displayInfo, result);\n        }\n\n        [Fact]\n        public void GetDisplayModesForRequestReturnsNullIfNoDisplayModesHandleRequest()\n        {\n            // Arrange\n            Mock<HttpContextBase> httpContext = new Mock<HttpContextBase>(MockBehavior.Strict);\n            var displayModeProvider = new DisplayModeProvider();\n            displayModeProvider.Modes.Clear();\n            var displayMode1 = new Mock<IDisplayMode>(MockBehavior.Strict);\n            displayMode1.Setup(d => d.CanHandleContext(It.IsAny<HttpContextBase>())).Returns(false);\n            displayModeProvider.Modes.Add(displayMode1.Object);\n\n            var displayMode2 = new Mock<IDisplayMode>(MockBehavior.Strict);\n            displayMode2.Setup(d => d.CanHandleContext(It.IsAny<HttpContextBase>())).Returns(false);\n            displayModeProvider.Modes.Add(displayMode2.Object);\n\n            var displayMode3 = new Mock<IDisplayMode>(MockBehavior.Strict);\n            displayMode3.Setup(d => d.CanHandleContext(It.IsAny<HttpContextBase>())).Returns(false);\n            displayModeProvider.Modes.Add(displayMode3.Object);\n\n            // Act\n            DisplayInfo displayModeForRequest = displayModeProvider.GetDisplayInfoForVirtualPath(\"path\", httpContext.Object, path => false, currentDisplayMode: null);\n\n            // Assert\n            Assert.Null(displayModeForRequest);\n        }\n\n        [Fact]\n        public void GetAvailableDisplayModesForContextWithRestrictingPageElements()\n        {\n            // Arrange\n            Mock<HttpContextBase> httpContext = new Mock<HttpContextBase>(MockBehavior.Strict);\n            var displayModeProvider = new DisplayModeProvider();\n            displayModeProvider.Modes.Clear();\n            var displayMode1 = new Mock<IDisplayMode>(MockBehavior.Strict);\n            displayMode1.Setup(d => d.CanHandleContext(It.IsAny<HttpContextBase>())).Returns(true);\n            displayModeProvider.Modes.Add(displayMode1.Object);\n\n            var displayMode2 = new Mock<IDisplayMode>(MockBehavior.Strict);\n            displayMode2.Setup(d => d.CanHandleContext(It.IsAny<HttpContextBase>())).Returns(false);\n            displayModeProvider.Modes.Add(displayMode2.Object);\n\n            var displayMode3 = new Mock<IDisplayMode>(MockBehavior.Strict);\n            displayMode3.Setup(d => d.CanHandleContext(It.IsAny<HttpContextBase>())).Returns(true);\n            displayModeProvider.Modes.Add(displayMode3.Object);\n\n            // Act\n            var availableDisplayModes = displayModeProvider.GetAvailableDisplayModesForContext(httpContext.Object, displayMode2.Object, requireConsistentDisplayMode: true).ToList();\n\n            // Assert\n            var availableDisplayMode = Assert.Single(availableDisplayModes);\n            Assert.Equal(displayMode3.Object, availableDisplayMode);\n        }\n\n        [Fact]\n        public void GetAvailableDisplayModesForContextWithoutRestrictingPageElements()\n        {\n            // Arrange\n            Mock<HttpContextBase> httpContext = new Mock<HttpContextBase>(MockBehavior.Strict);\n            var displayModeProvider = new DisplayModeProvider();\n            displayModeProvider.Modes.Clear();\n\n            var displayMode1 = new Mock<IDisplayMode>(MockBehavior.Strict);\n            displayMode1.Setup(d => d.CanHandleContext(It.IsAny<HttpContextBase>())).Returns(true);\n            displayModeProvider.Modes.Add(displayMode1.Object);\n\n            var displayMode2 = new Mock<IDisplayMode>(MockBehavior.Strict);\n            displayMode2.Setup(d => d.CanHandleContext(It.IsAny<HttpContextBase>())).Returns(false);\n            displayModeProvider.Modes.Add(displayMode2.Object);\n\n            var displayMode3 = new Mock<IDisplayMode>(MockBehavior.Strict);\n            displayMode3.Setup(d => d.CanHandleContext(It.IsAny<HttpContextBase>())).Returns(true);\n            displayModeProvider.Modes.Add(displayMode3.Object);\n\n            // Act\n            var availableDisplayModes = displayModeProvider.GetAvailableDisplayModesForContext(httpContext.Object, displayMode2.Object, requireConsistentDisplayMode: false).ToList();\n\n            // Assert\n            Assert.Equal(2, availableDisplayModes.Count);\n            Assert.Same(displayMode1.Object, availableDisplayModes[0]);\n            Assert.Same(displayMode3.Object, availableDisplayModes[1]);\n        }\n\n        [Fact]\n        public void GetAvailableDisplayModesReturnsOnlyModesThatCanHandleContext()\n        {\n            // Arrange\n            Mock<HttpContextBase> httpContext = new Mock<HttpContextBase>(MockBehavior.Strict);\n            var displayModeProvider = new DisplayModeProvider();\n            displayModeProvider.Modes.Clear();\n            var displayMode1 = new Mock<IDisplayMode>(MockBehavior.Strict);\n            displayMode1.Setup(d => d.CanHandleContext(It.IsAny<HttpContextBase>())).Returns(false);\n            displayModeProvider.Modes.Add(displayMode1.Object);\n\n            var displayMode2 = new Mock<IDisplayMode>(MockBehavior.Strict);\n            displayMode2.Setup(d => d.CanHandleContext(It.IsAny<HttpContextBase>())).Returns(true);\n            displayModeProvider.Modes.Add(displayMode2.Object);\n\n            var displayMode3 = new Mock<IDisplayMode>(MockBehavior.Strict);\n            displayMode3.Setup(d => d.CanHandleContext(It.IsAny<HttpContextBase>())).Returns(false);\n            displayModeProvider.Modes.Add(displayMode3.Object);\n\n            // Act\n            var availableDisplayModes = displayModeProvider.GetAvailableDisplayModesForContext(httpContext.Object, displayMode1.Object, requireConsistentDisplayMode: false).ToList();\n\n            // Assert\n            IDisplayMode availableDisplayMode = Assert.Single(availableDisplayModes);\n            Assert.Equal(displayMode2.Object, availableDisplayMode);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/DynamicHttpApplicationStateTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.WebPages.Resources;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Test\n{\n    public class DynamicHttpApplicationStateTest\n    {\n        private static HttpApplicationStateBase CreateAppStateInstance()\n        {\n            return new HttpApplicationStateWrapper((HttpApplicationState)Activator.CreateInstance(typeof(HttpApplicationState), true));\n        }\n\n        [Fact]\n        public void DynamicTest()\n        {\n            HttpApplicationStateBase appState = CreateAppStateInstance();\n            dynamic d = new DynamicHttpApplicationState(appState);\n            d[\"x\"] = \"y\";\n            Assert.Equal(\"y\", d.x);\n            Assert.Equal(\"y\", d[0]);\n            d.a = \"b\";\n            Assert.Equal(\"b\", d[\"a\"]);\n            d.Foo = \"bar\";\n            Assert.Equal(\"bar\", d.Foo);\n            Assert.Null(d.XYZ);\n            Assert.Null(d[\"xyz\"]);\n            Assert.Throws<ArgumentOutOfRangeException>(() => { var x = d[5]; });\n            var a = d.Baz = 42;\n            Assert.Equal(42, a);\n            var b = d[\"test\"] = 666;\n            Assert.Equal(666, b);\n        }\n\n        [Fact]\n        public void InvalidNumberOfIndexes()\n        {\n            Assert.Throws<ArgumentException>(() =>\n            {\n                HttpApplicationStateBase appState = CreateAppStateInstance();\n                dynamic d = new DynamicHttpApplicationState(appState);\n                d[1, 2] = 3;\n            }, WebPageResources.DynamicDictionary_InvalidNumberOfIndexes);\n\n            Assert.Throws<ArgumentException>(() =>\n            {\n                HttpApplicationStateBase appState = CreateAppStateInstance();\n                dynamic d = new DynamicHttpApplicationState(appState);\n                var x = d[1, 2];\n            }, WebPageResources.DynamicDictionary_InvalidNumberOfIndexes);\n        }\n\n        [Fact]\n        public void InvalidTypeWhenSetting()\n        {\n            Assert.Throws<ArgumentException>(() =>\n            {\n                HttpApplicationStateBase appState = CreateAppStateInstance();\n                dynamic d = new DynamicHttpApplicationState(appState);\n                d[new object()] = 3;\n            }, WebPageResources.DynamicHttpApplicationState_UseOnlyStringToSet);\n        }\n\n        [Fact]\n        public void InvalidTypeWhenGetting()\n        {\n            Assert.Throws<ArgumentException>(() =>\n            {\n                HttpApplicationStateBase appState = CreateAppStateInstance();\n                dynamic d = new DynamicHttpApplicationState(appState);\n                var x = d[new object()];\n            }, WebPageResources.DynamicHttpApplicationState_UseOnlyStringOrIntToGet);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/DynamicPageDataDictionaryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Web.WebPages.Resources;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Test\n{\n    public class DynamicPageDataDictionaryTest\n    {\n        [Fact]\n        public void DynamicTest()\n        {\n            dynamic d = new DynamicPageDataDictionary<dynamic>(new PageDataDictionary<dynamic>());\n            d[\"x\"] = \"y\";\n            Assert.Equal(\"y\", d.x);\n            d.a = \"b\";\n            Assert.Equal(\"b\", d[\"a\"]);\n            d[0] = \"zero\";\n            Assert.Equal(\"zero\", d[0]);\n            d.Foo = \"bar\";\n            Assert.Equal(\"bar\", d.Foo);\n            var a = d.Baz = 42;\n            Assert.Equal(42, a);\n            var b = d[new object()] = 666;\n            Assert.Equal(666, b);\n        }\n\n        [Fact]\n        public void CastToDictionaryTest()\n        {\n            dynamic d = new DynamicPageDataDictionary<dynamic>(new PageDataDictionary<dynamic>());\n            var typeCheckCast = d as IDictionary<object, dynamic>;\n            var directCast = (IDictionary<object, dynamic>)d;\n\n            Assert.NotNull(typeCheckCast);\n            Assert.NotNull(directCast);\n        }\n\n        [Fact]\n        public void AddTest()\n        {\n            dynamic d = new DynamicPageDataDictionary<dynamic>(new PageDataDictionary<dynamic>());\n            var item = new KeyValuePair<object, object>(\"x\", 2);\n            d.Add(item);\n            Assert.True(d.Contains(item));\n            Assert.Equal(2, d.x);\n            Assert.Equal(2, d[\"x\"]);\n        }\n\n        [Fact]\n        public void AddTest1()\n        {\n            dynamic d = new DynamicPageDataDictionary<dynamic>(new PageDataDictionary<dynamic>());\n            object key = \"x\";\n            object value = 1;\n            d.Add(key, value);\n            Assert.True(d.ContainsKey(key));\n            Assert.Equal(1, d[key]);\n            Assert.Equal(1, d.x);\n        }\n\n        [Fact]\n        public void ClearTest()\n        {\n            dynamic d = new DynamicPageDataDictionary<dynamic>(new PageDataDictionary<dynamic>());\n            d.x = 2;\n            d.Clear();\n            Assert.Equal(0, d.Count);\n        }\n\n        [Fact]\n        public void ContainsTest()\n        {\n            dynamic d = new DynamicPageDataDictionary<dynamic>(new PageDataDictionary<dynamic>());\n            var item = new KeyValuePair<object, object>(\"x\", 1);\n            d.Add(item);\n            Assert.True(d.Contains(item));\n            var item2 = new KeyValuePair<object, object>(\"y\", 2);\n            Assert.False(d.Contains(item2));\n        }\n\n        [Fact]\n        public void ContainsKeyTest()\n        {\n            dynamic d = new DynamicPageDataDictionary<dynamic>(new PageDataDictionary<dynamic>());\n            object key = \"x\";\n            Assert.False(d.ContainsKey(key));\n            d.Add(key, 1);\n            Assert.True(d.ContainsKey(key));\n            Assert.True(d.ContainsKey(\"x\"));\n        }\n\n        [Fact]\n        public void CopyToTest()\n        {\n            dynamic d = new DynamicPageDataDictionary<dynamic>(new PageDataDictionary<dynamic>());\n            KeyValuePair<object, object>[] array = new KeyValuePair<object, object>[1];\n            d.Add(\"x\", 1);\n            d.CopyTo(array, 0);\n            Assert.Equal(new KeyValuePair<object, object>(\"x\", 1), array[0]);\n        }\n\n        [Fact]\n        public void GetEnumeratorTest()\n        {\n            dynamic d = new DynamicPageDataDictionary<dynamic>(new PageDataDictionary<dynamic>());\n            d.Add(\"x\", 1);\n            var e = d.GetEnumerator();\n            e.MoveNext();\n            Assert.Equal(new KeyValuePair<object, object>(\"x\", 1), e.Current);\n        }\n\n        [Fact]\n        public void RemoveTest()\n        {\n            dynamic d = new DynamicPageDataDictionary<dynamic>(new PageDataDictionary<dynamic>());\n            var key = \"x\";\n            d.Add(key, 1);\n            d.Remove(key);\n            Assert.False(d.ContainsKey(key));\n        }\n\n        [Fact]\n        public void RemoveTest1()\n        {\n            dynamic d = new DynamicPageDataDictionary<dynamic>(new PageDataDictionary<dynamic>());\n            var item = new KeyValuePair<object, object>(\"x\", 2);\n            d.Add(item);\n            Assert.True(d.Contains(item));\n            d.Remove(item);\n            Assert.False(d.Contains(item));\n        }\n\n        [Fact]\n        public void GetEnumeratorTest1()\n        {\n            dynamic d = new DynamicPageDataDictionary<dynamic>(new PageDataDictionary<dynamic>());\n            d.Add(\"x\", 1);\n            var e = ((IEnumerable)d).GetEnumerator();\n            e.MoveNext();\n            Assert.Equal(new KeyValuePair<object, object>(\"x\", 1), e.Current);\n        }\n\n        [Fact]\n        public void TryGetValueTest()\n        {\n            dynamic d = new DynamicPageDataDictionary<dynamic>(new PageDataDictionary<dynamic>());\n            object key = \"x\";\n            d.Add(key, 1);\n            object value = null;\n            Assert.True(d.TryGetValue(key, out value));\n            Assert.Equal(1, value);\n        }\n\n        [Fact]\n        public void CountTest()\n        {\n            var d = new DynamicPageDataDictionary<dynamic>(new PageDataDictionary<dynamic>());\n            dynamic dyn = d;\n            Assert.IsType<int>(dyn.Count);\n            d.Add(\"x\", 1);\n            Assert.Single(d);\n            d.Add(\"y\", 2);\n            Assert.Equal(2, d.Count);\n            dyn.Count = \"foo\";\n            Assert.Equal(\"foo\", d[\"Count\"]);\n            Assert.Equal(3, d.Count);\n        }\n\n        [Fact]\n        public void IsReadOnlyTest()\n        {\n            PageDataDictionary<dynamic> dict = new PageDataDictionary<dynamic>();\n            var d = new DynamicPageDataDictionary<dynamic>(dict);\n            dynamic dyn = d;\n            Assert.IsType<bool>(dyn.IsReadOnly);\n            Assert.Equal(dict.IsReadOnly, d.IsReadOnly);\n            dyn.IsReadOnly = \"foo\";\n            Assert.Equal(\"foo\", d[\"IsReadOnly\"]);\n            Assert.Equal(dict.IsReadOnly, d.IsReadOnly);\n            Assert.Equal(dict.IsReadOnly, dyn.IsReadOnly);\n        }\n\n        [Fact]\n        public void ItemTest()\n        {\n            dynamic d = new DynamicPageDataDictionary<dynamic>(new PageDataDictionary<dynamic>());\n            d.Add(\"x\", 1);\n            d.Add(\"y\", 2);\n            Assert.Equal(1, d[\"x\"]);\n            Assert.Equal(2, d[\"y\"]);\n        }\n\n        [Fact]\n        public void KeysTest()\n        {\n            var d = new DynamicPageDataDictionary<dynamic>(new PageDataDictionary<dynamic>());\n            dynamic dyn = d;\n            Assert.IsAssignableFrom<ICollection<object>>(dyn.Keys);\n            d.Add(\"x\", 1);\n            d.Add(\"y\", 2);\n            Assert.True(d.Keys.Contains(\"x\"));\n            Assert.True(d.Keys.Contains(\"y\"));\n            Assert.Equal(2, d.Keys.Count);\n            dyn.Keys = \"foo\";\n            Assert.Equal(\"foo\", dyn[\"Keys\"]);\n            Assert.Equal(3, d.Count);\n        }\n\n        [Fact]\n        public void ValuesTest()\n        {\n            var d = new DynamicPageDataDictionary<dynamic>(new PageDataDictionary<dynamic>());\n            dynamic dyn = d;\n            Assert.IsAssignableFrom<ICollection<dynamic>>(dyn.Values);\n            d.Add(\"x\", 1);\n            d.Add(\"y\", 2);\n            Assert.True(d.Values.Contains(1));\n            Assert.True(d.Values.Contains(2));\n            Assert.Equal(2, d.Values.Count);\n            dyn.Values = \"foo\";\n            Assert.Equal(\"foo\", dyn[\"Values\"]);\n            Assert.Equal(3, d.Count);\n        }\n\n        [Fact]\n        public void InvalidNumberOfIndexes()\n        {\n            Assert.Throws<ArgumentException>(() =>\n            {\n                dynamic d = new DynamicPageDataDictionary<dynamic>(new PageDataDictionary<dynamic>());\n                d[1, 2] = 3;\n            }, WebPageResources.DynamicDictionary_InvalidNumberOfIndexes);\n\n            Assert.Throws<ArgumentException>(() =>\n            {\n                dynamic d = new DynamicPageDataDictionary<dynamic>(new PageDataDictionary<dynamic>());\n                var x = d[1, 2];\n            }, WebPageResources.DynamicDictionary_InvalidNumberOfIndexes);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/FileExistenceCacheTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing System.Threading;\nusing System.Web.Hosting;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class FileExistenceCacheTest\n    {\n        [Fact]\n        public void ConstructorTest()\n        {\n            var ms = 1000;\n            FileExistenceCache cache;\n\n            var vpp = new Mock<VirtualPathProvider>().Object;\n            cache = new FileExistenceCache(vpp);\n            Assert.Equal(vpp, cache.VirtualPathProvider);\n            Assert.Equal(ms, cache.MilliSecondsBeforeReset);\n\n            ms = 9999;\n            cache = new FileExistenceCache(vpp, ms);\n            Assert.Equal(vpp, cache.VirtualPathProvider);\n            Assert.Equal(ms, cache.MilliSecondsBeforeReset);\n        }\n\n        // Not a valid production scenario -- no HostingEnvironment\n        [Fact]\n        public void ConstructorTestWithNull()\n        {\n            // Arrange & Act\n            FileExistenceCache cache = new FileExistenceCache(() => null);\n\n            // Assert\n            Assert.Null(cache.VirtualPathProvider);\n        }\n\n        [Fact]\n        public void ConstructorTest_VPPRegistrationChanging()\n        {\n            // Arrange\n            Mock<VirtualPathProvider> mockProvider = new Mock<VirtualPathProvider>(MockBehavior.Strict);\n            VirtualPathProvider provider = null;\n\n            // Act\n            FileExistenceCache cache = new FileExistenceCache(() => provider);\n\n            // The moral equivalent of HostingEnvironment.RegisterVirtualPathProvider(mockProvider.Object)\n            provider = mockProvider.Object;\n\n            // Assert\n            Assert.Equal(provider, cache.VirtualPathProvider);\n            mockProvider.Verify();\n        }\n\n        [Fact]\n        public void FileExistsTest_VPPRegistrationChanging()\n        {\n            // Arrange\n            string path = \"~/Index.cshtml\";\n            Mock<VirtualPathProvider> mockProvider = new Mock<VirtualPathProvider>(MockBehavior.Strict);\n            mockProvider.Setup(c => c.FileExists(It.IsAny<string>())).Returns<string>(p => p.Equals(path)).Verifiable();\n            VirtualPathProvider provider = null;\n\n            // Act\n            FileExistenceCache cache = new FileExistenceCache(() => provider);\n\n            // The moral equivalent of HostingEnvironment.RegisterVirtualPathProvider(mockProvider.Object)\n            provider = mockProvider.Object;\n\n            bool createExists = cache.FileExists(\"~/Create.cshtml\");\n            bool indexExists = cache.FileExists(path);\n\n            // Assert\n            Assert.False(createExists);\n            Assert.True(indexExists);\n            mockProvider.Verify();\n            mockProvider.Verify(vpp => vpp.FileExists(It.IsAny<string>()), Times.Exactly(2));\n        }\n\n        [Fact]\n        public void TimeExceededFalseTest()\n        {\n            var ms = 100000;\n            var cache = new FileExistenceCache(GetVpp(), ms);\n            Assert.False(cache.TimeExceeded);\n        }\n\n        [Fact]\n        public void TimeExceededTrueTest()\n        {\n            var ms = 5;\n            var cache = new FileExistenceCache(GetVpp(), ms);\n            Thread.Sleep(300);\n            Assert.True(cache.TimeExceeded);\n        }\n\n        [Fact]\n        public void ResetTest()\n        {\n            var cache = new FileExistenceCache(GetVpp());\n            var cacheInternal = cache.CacheInternal;\n            cache.Reset();\n            Assert.NotSame(cacheInternal, cache.CacheInternal);\n        }\n\n        [Fact]\n        public void FileExistsTest()\n        {\n            var path = \"~/index.cshtml\";\n            var cache = new FileExistenceCache(GetVpp(path));\n            Assert.True(cache.FileExists(path));\n            Assert.False(cache.FileExists(\"~/test.cshtml\"));\n        }\n\n        [Fact]\n        public void FileExistsVppLaterTest()\n        {\n            var path = \"~/index.cshtml\";\n            var cache = new FileExistenceCache(GetVpp(path));\n            Assert.True(cache.FileExists(path));\n            Assert.False(cache.FileExists(\"~/test.cshtml\"));\n        }\n\n        [Fact]\n        public void FileExistsTimeExceededTest()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                var path = \"~/index.cshtml\";\n                Utils.SetupVirtualPathInAppDomain(path, \"\");\n\n                var cache = new FileExistenceCache(GetVpp(path));\n                var cacheInternal = cache.CacheInternal;\n                cache.MilliSecondsBeforeReset = 5;\n                Thread.Sleep(300);\n                Assert.True(cache.FileExists(path));\n                Assert.False(cache.FileExists(\"~/test.cshtml\"));\n                Assert.NotEqual(cacheInternal, cache.CacheInternal);\n            });\n        }\n\n        private static VirtualPathProvider GetVpp(params string[] files)\n        {\n            var vpp = new Mock<VirtualPathProvider>();\n            vpp.Setup(c => c.FileExists(It.IsAny<string>())).Returns<string>(p => files.Contains(p, StringComparer.OrdinalIgnoreCase));\n            return vpp.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/LayoutTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Globalization;\nusing System.Web.WebPages.Resources;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class LayoutTest\n    {\n        [Fact]\n        public void LayoutBasicTest()\n        {\n            var layoutPath = \"~/Layout.cshtml\";\n            LayoutBasicTestInternal(layoutPath);\n        }\n\n        [Fact]\n        public void RelativeLayoutPageTest()\n        {\n            var pagePath = \"~/MyApp/index.cshtml\";\n            var layoutPath = \"~/MyFiles/Layout.cshtml\";\n            var layoutPage = \"../MyFiles/Layout.cshtml\";\n            LayoutBasicTestInternal(layoutPath, pagePath, layoutPage);\n        }\n\n        [Fact]\n        public void AppRelativeLayoutPageTest()\n        {\n            var pagePath = \"~/MyApp/index.cshtml\";\n            var layoutPath = \"~/MyFiles/Layout.cshtml\";\n            var layoutPage = \"~/MyFiles/Layout.cshtml\";\n            LayoutBasicTestInternal(layoutPath, pagePath, layoutPage);\n        }\n\n        [Fact]\n        public void SourceFileWithLayoutPageTest()\n        {\n            // Arrange\n            var pagePath = \"~/MyApp/index.cshtml\";\n            var layoutPath = \"~/MyFiles/Layout.cshtml\";\n            var layoutPage = \"~/MyFiles/Layout.cshtml\";\n            var content = \"hello world\";\n            var title = \"MyPage\";\n            var page = CreatePageWithLayout(\n                p =>\n                {\n                    p.PageData[\"Title\"] = title;\n                    p.WriteLiteral(content);\n                },\n                p =>\n                {\n                    p.WriteLiteral(p.PageData[\"Title\"]);\n                    p.Write(p.RenderBody());\n                }, pagePath, layoutPath, layoutPage);\n            var request = new Mock<HttpRequestBase>();\n            request.SetupGet(c => c.Path).Returns(\"/myapp/index.cshtml\");\n            request.SetupGet(c => c.RawUrl).Returns(\"http://localhost:8080/index.cshtml\");\n            request.SetupGet(c => c.IsLocal).Returns(true);\n            request.Setup(c => c.MapPath(It.IsAny<string>())).Returns<string>(c => c);\n            request.Setup(c => c.Browser.IsMobileDevice).Returns(false);\n            request.Setup(c => c.Cookies).Returns(new HttpCookieCollection());\n\n            var result = Utils.RenderWebPage(page, request: request.Object);\n            Assert.Equal(2, page.PageContext.SourceFiles.Count);\n            Assert.Contains(\"~/MyApp/index.cshtml\", page.PageContext.SourceFiles);\n            Assert.Contains(\"~/MyFiles/Layout.cshtml\", page.PageContext.SourceFiles);\n        }\n\n        private static void LayoutBasicTestInternal(string layoutPath, string pagePath = \"~/index.cshtml\", string layoutPage = \"Layout.cshtml\")\n        {\n            // The page ~/index.cshtml does the following:\n            // PageData[\"Title\"] = \"MyPage\";\n            // Layout = \"Layout.cshtml\";\n            // WriteLiteral(\"hello world\");\n            //\n            // The layout page ~/Layout.cshtml does the following:\n            // WriteLiteral(Title);\n            // RenderBody();\n            //\n            // Expected rendered result is \"MyPagehello world\"\n\n            var content = \"hello world\";\n            var title = \"MyPage\";\n            var result = RenderPageWithLayout(\n                p =>\n                {\n                    p.PageData[\"Title\"] = title;\n                    p.WriteLiteral(content);\n                },\n                p =>\n                {\n                    p.WriteLiteral(p.PageData[\"Title\"]);\n                    p.Write(p.RenderBody());\n                },\n                pagePath, layoutPath, layoutPage);\n\n            Assert.Equal(title + content, result);\n        }\n\n        [Fact]\n        public void LayoutNestedTest()\n        {\n            // Testing nested layout pages\n            //\n            // The page ~/index.cshtml does the following:\n            // PageData[\"Title\"] = \"MyPage\";\n            // Layout = \"Layout1.cshtml\";\n            // WriteLiteral(\"hello world\");\n            //\n            // The first layout page ~/Layout1.cshtml does the following:\n            // Layout = \"Layout2.cshtml\";\n            // WriteLiteral(\"<layout1>\");\n            // RenderBody();\n            // WriteLiteral(\"</layout1>\");\n            //\n            // The second layout page ~/Layout2.cshtml does the following:\n            // WriteLiteral(Title);\n            // WriteLiteral(\"<layout2>\");\n            // RenderBody();\n            // WriteLiteral(\"</layout2>\");\n            //\n            // Expected rendered result is \"MyPage<layout2><layout1>hello world</layout1></layout2>\"\n\n            var layout2Path = \"~/Layout2.cshtml\";\n            var layout2 = Utils.CreatePage(\n                p =>\n                {\n                    p.WriteLiteral(p.PageData[\"Title\"]);\n                    p.WriteLiteral(\"<layout2>\");\n                    p.Write(p.RenderBody());\n                    p.WriteLiteral(\"</layout2>\");\n                },\n                layout2Path);\n\n            var layout1Path = \"~/Layout1.cshtml\";\n            var layout1 = Utils.CreatePage(\n                p =>\n                {\n                    p.Layout = \"Layout2.cshtml\";\n                    p.WriteLiteral(\"<layout1>\");\n                    p.Write(p.RenderBody());\n                    p.WriteLiteral(\"</layout1>\");\n                },\n                layout1Path);\n\n            var page = Utils.CreatePage(\n                p =>\n                {\n                    p.PageData[\"Title\"] = \"MyPage\";\n                    p.Layout = \"Layout1.cshtml\";\n                    p.WriteLiteral(\"hello world\");\n                });\n\n            Utils.AssignObjectFactoriesAndDisplayModeProvider(page, layout1, layout2);\n\n            var result = Utils.RenderWebPage(page);\n            Assert.Equal(\"MyPage<layout2><layout1>hello world</layout1></layout2>\", result);\n        }\n\n        [Fact]\n        public void LayoutSectionsTest()\n        {\n            // Testing nested layout pages with sections\n            //\n            // The page ~/index.cshtml does the following:\n            // PageData[\"Title\"] = \"MyPage\";\n            // Layout = \"Layout1.cshtml\";\n            // DefineSection(\"header1\", () => {\n            //     WriteLiteral(\"index header\");\n            // });\n            // WriteLiteral(\"hello world\");\n            // DefineSection(\"footer1\", () => {\n            //     WriteLiteral(\"index footer\");\n            // });\n            //\n            // The first layout page ~/Layout1.cshtml does the following:\n            // Layout = \"Layout2.cshtml\";\n            // DefineSection(\"header2\", () => {\n            //     WriteLiteral(\"<layout1 header>\");\n            //     RenderSection(\"header1\");\n            //     WriteLiteral(\"</layout1 header>\");\n            // });\n            // WriteLiteral(\"<layout1>\");\n            // RenderBody();\n            // WriteLiteral(\"</layout1>\");\n            // DefineSection(\"footer2\", () => {\n            //     WriteLiteral(\"<layout1 footer>\");\n            //     RenderSection(\"header2\");\n            //     WriteLiteral(\"</layout1 footer>\");\n            // });\n            //\n            // The second layout page ~/Layout2.cshtml does the following:\n            // WriteLiteral(Title);\n            // WriteLiteral(\"\\n<layout2 header>\");\n            // RenderSection(\"header2\");\n            // WriteLiteral(\"</layout2 header>\\n\");\n            // WriteLiteral(\"<layout2>\");\n            // RenderBody();\n            // WriteLiteral(\"</layout2>\\n\");\n            // WriteLiteral(\"<layout2 footer>\");\n            // RenderSection(\"footer\");\n            // WriteLiteral(\"</layout2 footer>\");\n            //\n            // Expected rendered result is:\n            // MyPage\n            // <layout2 header><layout1 header>index header</layout1 header></layout2 header>\n            // <layout2><layout1>hello world</layout1></layout2>\"\n            // <layout2 footer><layout1 footer>index footer</layout1 footer></layout2 footer>\n\n            var layout2Path = \"~/Layout2.cshtml\";\n            var layout2 = Utils.CreatePage(\n                p =>\n                {\n                    p.WriteLiteral(p.PageData[\"Title\"]);\n                    p.WriteLiteral(\"\\r\\n\");\n                    p.WriteLiteral(\"<layout2 header>\");\n                    p.Write(p.RenderSection(\"header2\"));\n                    p.WriteLiteral(\"</layout2 header>\");\n                    p.WriteLiteral(\"\\r\\n\");\n\n                    p.WriteLiteral(\"<layout2>\");\n                    p.Write(p.RenderBody());\n                    p.WriteLiteral(\"</layout2>\");\n                    p.WriteLiteral(\"\\r\\n\");\n\n                    p.WriteLiteral(\"<layout2 footer>\");\n                    p.Write(p.RenderSection(\"footer2\"));\n                    p.WriteLiteral(\"</layout2 footer>\");\n                },\n                layout2Path);\n\n            var layout1Path = \"~/Layout1.cshtml\";\n            var layout1 = Utils.CreatePage(\n                p =>\n                {\n                    p.Layout = \"Layout2.cshtml\";\n                    p.DefineSection(\"header2\", () =>\n                    {\n                        p.WriteLiteral(\"<layout1 header>\");\n                        p.Write(p.RenderSection(\"header1\"));\n                        p.WriteLiteral(\"</layout1 header>\");\n                    });\n\n                    p.WriteLiteral(\"<layout1>\");\n                    p.Write(p.RenderBody());\n                    p.WriteLiteral(\"</layout1>\");\n\n                    p.DefineSection(\"footer2\", () =>\n                    {\n                        p.WriteLiteral(\"<layout1 footer>\");\n                        p.Write(p.RenderSection(\"footer1\"));\n                        p.WriteLiteral(\"</layout1 footer>\");\n                    });\n                },\n                layout1Path);\n\n            var page = Utils.CreatePage(\n                p =>\n                {\n                    p.PageData[\"Title\"] = \"MyPage\";\n                    p.Layout = \"Layout1.cshtml\";\n                    p.DefineSection(\"header1\", () => { p.WriteLiteral(\"index header\"); });\n                    p.WriteLiteral(\"hello world\");\n                    p.DefineSection(\"footer1\", () => { p.WriteLiteral(\"index footer\"); });\n                });\n\n            Utils.AssignObjectFactoriesAndDisplayModeProvider(page, layout1, layout2);\n\n            var result = Utils.RenderWebPage(page);\n            var expected = \"MyPage\" + Environment.NewLine\n                         + \"<layout2 header><layout1 header>index header</layout1 header></layout2 header>\" + Environment.NewLine\n                         + \"<layout2><layout1>hello world</layout1></layout2>\" + Environment.NewLine\n                         + \"<layout2 footer><layout1 footer>index footer</layout1 footer></layout2 footer>\";\n            Assert.Equal(expected, result);\n        }\n\n        [Fact]\n        public void LayoutSectionsNestedNamesTest()\n        {\n            // Tests nested layout using the same section names at different levels.\n            //\n            // The page ~/index.cshtml does the following:\n            // Layout = \"Layout1.cshtml\";\n            // @section body {\n            //     body in index\n            // }\n            //\n            // The page ~/layout1.cshtml does the following:\n            // Layout = \"Layout2.cshtml\";\n            // @section body {\n            //     body in layout1\n            //     @RenderSection(\"body\")\n            // }\n            //\n            // The page ~/layout2.cshtml does the following:\n            // body in layout2\n            // @RenderSection(\"body\")\n            //\n            // Expected rendered result is:\n            // body in layout2 body in layout1 body in index\n            var layout2Path = \"~/Layout2.cshtml\";\n            var layout2 = Utils.CreatePage(\n                p =>\n                {\n                    p.WriteLiteral(\"body in layout2 \");\n                    p.Write(p.RenderSection(\"body\"));\n                },\n                layout2Path);\n            var layout1Path = \"~/Layout1.cshtml\";\n            var layout1 = Utils.CreatePage(\n                p =>\n                {\n                    p.Layout = \"Layout2.cshtml\";\n                    p.DefineSection(\"body\", () =>\n                    {\n                        p.WriteLiteral(\"body in layout1 \");\n                        p.Write(p.RenderSection(\"body\"));\n                    });\n                },\n                layout1Path);\n\n            var page = Utils.CreatePage(\n                p =>\n                {\n                    p.Layout = \"Layout1.cshtml\";\n                    p.DefineSection(\"body\", () => { p.WriteLiteral(\"body in index\"); });\n                });\n\n            Utils.AssignObjectFactoriesAndDisplayModeProvider(page, layout1, layout2);\n\n            var result = Utils.RenderWebPage(page);\n            var expected = \"body in layout2 body in layout1 body in index\";\n            Assert.Equal(expected, result);\n        }\n\n        [Fact]\n        public void CaseInsensitiveSectionNamesTest()\n        {\n            var page = CreatePageWithLayout(\n                p =>\n                {\n                    p.Write(\"123\");\n                    p.DefineSection(\"abc\", () => { p.Write(\"abc\"); });\n                    p.DefineSection(\"XYZ\", () => { p.Write(\"xyz\"); });\n                    p.Write(\"456\");\n                },\n                p =>\n                {\n                    p.Write(p.RenderSection(\"AbC\"));\n                    p.Write(p.RenderSection(\"xyZ\"));\n                    p.Write(p.RenderBody());\n                });\n            var result = Utils.RenderWebPage(page);\n            var expected = \"abcxyz123456\";\n            Assert.Equal(expected, result);\n        }\n\n        [Fact]\n        public void MissingLayoutPageTest()\n        {\n            var layoutPage = \"Layout.cshtml\";\n            var page = Utils.CreatePage(\n                p =>\n                {\n                    p.PageData[\"Title\"] = \"MyPage\";\n                    p.Layout = layoutPage;\n                });\n            var layoutPath1 = \"~/Layout.cshtml\";\n\n            Assert.Throws<HttpException>(() => Utils.RenderWebPage(page),\n                                                  String.Format(CultureInfo.CurrentCulture, WebPageResources.WebPage_LayoutPageNotFound, layoutPage, layoutPath1));\n        }\n\n        [Fact]\n        public void RenderBodyAlreadyCalledTest()\n        {\n            // Layout page calls RenderBody more than once.\n            var page = CreatePageWithLayout(\n                p => { },\n                p =>\n                {\n                    p.Write(p.RenderBody());\n                    p.Write(p.RenderBody());\n                });\n\n            Assert.Throws<HttpException>(() => Utils.RenderWebPage(page), WebPageResources.WebPage_RenderBodyAlreadyCalled);\n        }\n\n        [Fact]\n        public void RenderBodyNotCalledTest()\n        {\n            // Page does not define any sections, but layout page does not call RenderBody\n            var layoutPath = \"~/Layout.cshtml\";\n            var page = CreatePageWithLayout(\n                p => { },\n                p => { },\n                layoutPath: layoutPath);\n\n            Assert.Throws<HttpException>(() => Utils.RenderWebPage(page),\n                                                  String.Format(CultureInfo.CurrentCulture, WebPageResources.WebPage_RenderBodyNotCalled, layoutPath));\n        }\n\n        [Fact]\n        public void RenderBodyCalledDirectlyTest()\n        {\n            // A Page that is not a layout page calls the RenderBody method\n            var page = Utils.CreatePage(p => { p.RenderBody(); });\n            Assert.Throws<HttpException>(() => Utils.RenderWebPage(page),\n                                                  String.Format(CultureInfo.CurrentCulture, WebPageResources.WebPage_CannotRequestDirectly, \"~/index.cshtml\", \"RenderBody\"));\n        }\n\n        [Fact]\n        public void RenderSectionCalledDirectlyTest()\n        {\n            // A Page that is not a layout page calls the RenderBody method\n            var page = Utils.CreatePage(p => { p.RenderSection(\"\"); });\n            Assert.Throws<HttpException>(() => Utils.RenderWebPage(page),\n                                                  String.Format(CultureInfo.CurrentCulture, WebPageResources.WebPage_CannotRequestDirectly, \"~/index.cshtml\", \"RenderSection\"));\n        }\n\n        [Fact]\n        public void SectionAlreadyDefinedTest()\n        {\n            // The page calls DefineSection more than once on the same name\n            var sectionName = \"header\";\n            var page = Utils.CreatePage(p =>\n            {\n                p.Layout = \"Layout.cshtml\";\n                p.DefineSection(sectionName, () => { });\n                p.DefineSection(sectionName, () => { });\n            });\n\n            Assert.Throws<HttpException>(() => Utils.RenderWebPage(page),\n                                                  String.Format(CultureInfo.InvariantCulture, WebPageResources.WebPage_SectionAleadyDefined, sectionName));\n        }\n\n        [Fact]\n        public void SectionAlreadyDefinedCaseInsensitiveTest()\n        {\n            // The page calls DefineSection more than once on the same name but with different casing\n            var name1 = \"section1\";\n            var name2 = \"SecTion1\";\n\n            var page = Utils.CreatePage(p =>\n            {\n                p.Layout = \"Layout.cshtml\";\n                p.DefineSection(name1, () => { });\n                p.DefineSection(name2, () => { });\n            });\n\n            Assert.Throws<HttpException>(() => Utils.RenderWebPage(page),\n                                                  String.Format(CultureInfo.InvariantCulture, WebPageResources.WebPage_SectionAleadyDefined, name2));\n        }\n\n        [Fact]\n        public void SectionNotDefinedTest()\n        {\n            // Layout page calls RenderSection on a name that has not been defined.\n            var sectionName = \"NoSuchSection\";\n            var page = CreatePageWithLayout(\n                p => { },\n                p => { p.Write(p.RenderSection(sectionName)); });\n\n            Assert.Throws<HttpException>(() => Utils.RenderWebPage(page),\n                                                  String.Format(CultureInfo.InvariantCulture, WebPageResources.WebPage_SectionNotDefined, sectionName));\n        }\n\n        [Fact]\n        public void SectionAlreadyRenderedTest()\n        {\n            // Layout page calls RenderSection on the same name more than once.\n            var sectionName = \"header\";\n            var page = CreatePageWithLayout(\n                p =>\n                {\n                    p.Layout = \"Layout.cshtml\";\n                    p.DefineSection(sectionName, () => { });\n                },\n                p =>\n                {\n                    p.Write(p.RenderSection(sectionName));\n                    p.Write(p.RenderSection(sectionName));\n                });\n\n            Assert.Throws<HttpException>(() => Utils.RenderWebPage(page),\n                                                  String.Format(CultureInfo.InvariantCulture, WebPageResources.WebPage_SectionAleadyRendered, sectionName));\n        }\n\n        [Fact]\n        public void SectionsNotRenderedTest()\n        {\n            // Layout page does not render all the defined sections.\n\n            var layoutPath = \"~/Layout.cshtml\";\n            var sectionName1 = \"section1\";\n            var sectionName2 = \"section2\";\n            var sectionName3 = \"section3\";\n            var sectionName4 = \"section4\";\n            var sectionName5 = \"section5\";\n            // A dummy section action that does nothing\n            SectionWriter sectionAction = () => { };\n\n            // The page defines 5 sections.\n            var page = CreatePageWithLayout(\n                p =>\n                {\n                    p.DefineSection(sectionName1, sectionAction);\n                    p.DefineSection(sectionName2, sectionAction);\n                    p.DefineSection(sectionName3, sectionAction);\n                    p.DefineSection(sectionName4, sectionAction);\n                    p.DefineSection(sectionName5, sectionAction);\n                },\n                // The layout page renders only two of the sections\n                p =>\n                {\n                    p.Write(p.RenderSection(sectionName2));\n                    p.Write(p.RenderSection(sectionName4));\n                },\n                layoutPath: layoutPath);\n\n            var sectionsNotRendered = \"section1; section3; section5\";\n            Assert.Throws<HttpException>(() => Utils.RenderWebPage(page),\n                                                  String.Format(CultureInfo.CurrentCulture, WebPageResources.WebPage_SectionsNotRendered, layoutPath, sectionsNotRendered));\n        }\n\n        [Fact]\n        public void SectionsNotRenderedRenderBodyTest()\n        {\n            // Layout page does not render all the defined sections, but it calls RenderBody.\n            var layoutPath = \"~/Layout.cshtml\";\n            var sectionName1 = \"section1\";\n            var sectionName2 = \"section2\";\n            // A dummy section action that does nothing\n            SectionWriter sectionAction = () => { };\n\n            var page = CreatePageWithLayout(\n                p =>\n                {\n                    p.DefineSection(sectionName1, sectionAction);\n                    p.DefineSection(sectionName2, sectionAction);\n                },\n                // The layout page only calls RenderBody\n                p => { p.Write(p.RenderBody()); },\n                layoutPath: layoutPath);\n\n            var sectionsNotRendered = \"section1; section2\";\n            Assert.Throws<HttpException>(() => Utils.RenderWebPage(page),\n                                                  String.Format(CultureInfo.CurrentCulture, WebPageResources.WebPage_SectionsNotRendered, layoutPath, sectionsNotRendered));\n        }\n\n        [Fact]\n        public void InvalidPageTypeTest()\n        {\n            var layoutPath = \"~/Layout.js\";\n            var contents = \"hello world\";\n            var page = Utils.CreatePage(p =>\n            {\n                p.Layout = layoutPath;\n                p.Write(contents);\n            });\n            var layoutPage = new object();\n\n            var objectFactory = new Mock<IVirtualPathFactory>();\n            objectFactory.Setup(c => c.Exists(It.IsAny<string>())).Returns<string>(p => layoutPath.Equals(p, StringComparison.OrdinalIgnoreCase));\n            objectFactory.Setup(c => c.CreateInstance(It.IsAny<string>())).Returns<string>(_ => layoutPage as WebPageBase);\n            page.VirtualPathFactory = objectFactory.Object;\n\n            Assert.Throws<HttpException>(() => Utils.RenderWebPage(page),\n                                                  String.Format(CultureInfo.CurrentCulture, WebPageResources.WebPage_InvalidPageType, layoutPath));\n\n            Assert.Throws<HttpException>(() => Utils.RenderWebPage(page),\n                                                  String.Format(CultureInfo.CurrentCulture, WebPageResources.WebPage_InvalidPageType, layoutPath));\n        }\n\n        [Fact]\n        public void ValidPageTypeTest()\n        {\n            var layoutPath = \"~/Layout.js\";\n            var contents = \"hello world\";\n            var page = Utils.CreatePage(p =>\n            {\n                p.Layout = layoutPath;\n                p.Write(contents);\n            });\n            var layoutPage = Utils.CreatePage(p => p.WriteLiteral(p.RenderBody()), layoutPath);\n\n            Utils.AssignObjectFactoriesAndDisplayModeProvider(page, layoutPage);\n\n            Assert.Equal(contents, Utils.RenderWebPage(page));\n        }\n\n        [Fact]\n        public void IsSectionDefinedTest()\n        {\n            // Tests for the IsSectionDefined method\n\n            // Only sections named section1 and section3 are defined.\n            var page = CreatePageWithLayout(\n                p =>\n                {\n                    p.DefineSection(\"section1\", () => { });\n                    p.DefineSection(\"section3\", () => { });\n                },\n                p =>\n                {\n                    p.Write(p.RenderSection(\"section1\"));\n                    p.Write(p.RenderSection(\"section3\"));\n                    p.Write(\"section1: \" + p.IsSectionDefined(\"section1\") + \"; \");\n                    p.Write(\"section2: \" + p.IsSectionDefined(\"section2\") + \"; \");\n                    p.Write(\"section3: \" + p.IsSectionDefined(\"section3\") + \"; \");\n                    p.Write(\"section4: \" + p.IsSectionDefined(\"section4\") + \"; \");\n                });\n            var result = Utils.RenderWebPage(page);\n            var expected = \"section1: True; section2: False; section3: True; section4: False; \";\n            Assert.Equal(expected, result);\n        }\n\n        [Fact]\n        public void OptionalSectionsTest()\n        {\n            // Only sections named section1 and section3 are defined.\n            var page = CreatePageWithLayout(\n                p =>\n                {\n                    p.DefineSection(\"section1\", () => { p.Write(\"section1 \"); });\n                    p.DefineSection(\"section3\", () => { p.Write(\"section3\"); });\n                },\n                p =>\n                {\n                    p.Write(p.RenderSection(\"section1\", required: false));\n                    p.Write(p.RenderSection(\"section2\", required: false));\n                    p.Write(p.RenderSection(\"section3\", required: false));\n                    p.Write(p.RenderSection(\"section4\", required: false));\n                });\n            var result = Utils.RenderWebPage(page);\n            var expected = \"section1 section3\";\n            Assert.Equal(expected, result);\n        }\n\n        [Fact]\n        public void PageDataTest()\n        {\n            // Layout page uses items in PageData set by content page\n            var contents = \"my contents\";\n            var page = CreatePageWithLayout(\n                p =>\n                {\n                    p.PageData[\"contents\"] = contents;\n                    p.Write(\" body\");\n                },\n                p =>\n                {\n                    p.Write(p.PageData[\"contents\"]);\n                    p.Write(p.RenderBody());\n                });\n            var result = Utils.RenderWebPage(page);\n            var expected = contents + \" body\";\n            Assert.Equal(expected, result);\n        }\n\n        [Fact]\n        public void RenderPageAndLayoutPage()\n        {\n            //Dev10 bug 928341 - a page that has a layout page, and the page calls RenderPage should not cause an error\n            var layoutPagePath = \"~/layout.cshtml\";\n            var page = Utils.CreatePage(p =>\n            {\n                p.DefineSection(\"foo\", () => { p.Write(\"This is foo\"); });\n                p.Write(p.RenderPage(\"bar.cshtml\"));\n                p.Layout = layoutPagePath;\n            });\n            var layoutPage = Utils.CreatePage(p =>\n            {\n                p.Write(p.RenderBody());\n                p.Write(\" \");\n                p.Write(p.RenderSection(\"foo\"));\n            }, layoutPagePath);\n\n            var subPage = Utils.CreatePage(p => p.Write(\"This is bar\"), \"~/bar.cshtml\");\n            Utils.AssignObjectFactoriesAndDisplayModeProvider(page, layoutPage, subPage);\n\n            var result = Utils.RenderWebPage(page);\n            var expected = \"This is bar This is foo\";\n            Assert.Equal(expected, result);\n        }\n\n        public static string RenderPageWithLayout(Action<WebPage> pageExecuteAction, Action<WebPage> layoutExecuteAction,\n                                                  string pagePath = \"~/index.cshtml\", string layoutPath = \"~/Layout.cshtml\", string layoutPage = \"Layout.cshtml\")\n        {\n            var page = CreatePageWithLayout(pageExecuteAction, layoutExecuteAction, pagePath, layoutPath, layoutPage);\n            return Utils.RenderWebPage(page);\n        }\n\n        public static MockPage CreatePageWithLayout(Action<WebPage> pageExecuteAction, Action<WebPage> layoutExecuteAction,\n                                                    string pagePath = \"~/index.cshtml\", string layoutPath = \"~/Layout.cshtml\", string layoutPageName = \"Layout.cshtml\")\n        {\n            var page = Utils.CreatePage(\n                p =>\n                {\n                    p.Layout = layoutPageName;\n                    pageExecuteAction(p);\n                },\n                pagePath);\n            var layoutPage = Utils.CreatePage(\n                p => { layoutExecuteAction(p); },\n                layoutPath);\n\n            Utils.AssignObjectFactoriesAndDisplayModeProvider(layoutPage, page);\n\n            return page;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/PageDataDictionaryTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Test\n{\n    public class PageDataDictionaryTest\n    {\n        [Fact]\n        public void PageDataDictionaryConstructorTest()\n        {\n            var d = new PageDataDictionary<dynamic>();\n            Assert.NotNull(d.Data);\n        }\n\n        [Fact]\n        public void AddTest()\n        {\n            var d = new PageDataDictionary<dynamic>();\n            var item = new KeyValuePair<object, object>(\"x\", 2);\n            d.Add(item);\n            Assert.True(d.Data.Contains(item));\n        }\n\n        [Fact]\n        public void AddTest1()\n        {\n            var d = new PageDataDictionary<dynamic>();\n            object key = \"x\";\n            object value = 1;\n            d.Add(key, value);\n            Assert.True(d.Data.ContainsKey(key));\n            Assert.Equal(1, d.Data[key]);\n            // Use uppercase string key\n            Assert.Equal(1, d.Data[\"X\"]);\n        }\n\n        [Fact]\n        public void ClearTest()\n        {\n            var d = new PageDataDictionary<dynamic>();\n            d.Add(\"x\", 2);\n            d.Clear();\n            Assert.Equal(0, d.Data.Count);\n        }\n\n        [Fact]\n        public void ContainsTest()\n        {\n            var d = new PageDataDictionary<dynamic>();\n            var item = new KeyValuePair<object, object>(\"x\", 1);\n            d.Add(item);\n            Assert.Contains<KeyValuePair<object, object>>(item, d);\n            var item2 = new KeyValuePair<object, object>(\"y\", 2);\n            Assert.DoesNotContain<KeyValuePair<object, object>>(item2, d);\n        }\n\n        [Fact]\n        public void ContainsKeyTest()\n        {\n            var d = new PageDataDictionary<dynamic>();\n            object key = \"x\";\n            Assert.False(d.ContainsKey(key));\n            d.Add(key, 1);\n            Assert.True(d.ContainsKey(key));\n            Assert.True(d.ContainsKey(\"X\"));\n        }\n\n        [Fact]\n        public void CopyToTest()\n        {\n            var d = new PageDataDictionary<dynamic>();\n            KeyValuePair<object, object>[] array = new KeyValuePair<object, object>[1];\n            d.Add(\"x\", 1);\n            d.CopyTo(array, 0);\n            Assert.Equal(new KeyValuePair<object, object>(\"x\", 1), array[0]);\n        }\n\n        [Fact]\n        public void GetEnumeratorTest()\n        {\n            var d = new PageDataDictionary<dynamic>();\n            d.Add(\"x\", 1);\n            var e = d.GetEnumerator();\n            e.MoveNext();\n            Assert.Equal<object>(new KeyValuePair<object, object>(\"x\", 1), e.Current);\n        }\n\n        [Fact]\n        public void RemoveTest()\n        {\n            var d = new PageDataDictionary<dynamic>();\n            var key = \"x\";\n            d.Add(key, 1);\n            d.Remove(key);\n            Assert.False(d.Data.ContainsKey(key));\n        }\n\n        [Fact]\n        public void RemoveTest1()\n        {\n            var d = new PageDataDictionary<dynamic>();\n            var item = new KeyValuePair<object, object>(\"x\", 2);\n            d.Add(item);\n            Assert.Contains<KeyValuePair<object, object>>(item, d);\n            d.Remove(item);\n            Assert.DoesNotContain<KeyValuePair<object, object>>(item, d);\n        }\n\n        [Fact]\n        public void GetEnumeratorTest1()\n        {\n            var d = new PageDataDictionary<dynamic>();\n            d.Add(\"x\", 1);\n            var e = ((IEnumerable)d).GetEnumerator();\n            e.MoveNext();\n            Assert.Equal(new KeyValuePair<object, object>(\"x\", 1), e.Current);\n        }\n\n        [Fact]\n        public void TryGetValueTest()\n        {\n            var d = new PageDataDictionary<dynamic>();\n            object key = \"x\";\n            d.Add(key, 1);\n            object value = null;\n            Assert.True(d.TryGetValue(key, out value));\n            Assert.Equal(1, value);\n        }\n\n        [Fact]\n        public void CountTest()\n        {\n            var d = new PageDataDictionary<dynamic>();\n            d.Add(\"x\", 1);\n            Assert.Single(d);\n            d.Add(\"y\", 2);\n            Assert.Equal(2, d.Count);\n        }\n\n        [Fact]\n        public void IsReadOnlyTest()\n        {\n            var d = new PageDataDictionary<dynamic>();\n            Assert.Equal(d.Data.IsReadOnly, d.IsReadOnly);\n        }\n\n        [Fact]\n        public void ItemTest()\n        {\n            var d = new PageDataDictionary<dynamic>();\n            d.Add(\"x\", 1);\n            d.Add(\"y\", 2);\n            Assert.Equal(1, d[\"x\"]);\n            Assert.Equal(2, d[\"y\"]);\n        }\n\n        [Fact]\n        public void KeysTest()\n        {\n            var d = new PageDataDictionary<dynamic>();\n            d.Add(\"x\", 1);\n            d.Add(\"y\", 2);\n            Assert.True(d.Keys.Contains(\"x\"));\n            Assert.True(d.Keys.Contains(\"y\"));\n            Assert.Equal(2, d.Keys.Count);\n        }\n\n        [Fact]\n        public void ValuesTest()\n        {\n            var d = new PageDataDictionary<dynamic>();\n            d.Add(\"x\", 1);\n            d.Add(\"y\", 2);\n            Assert.True(d.Values.Contains(1));\n            Assert.True(d.Values.Contains(2));\n            Assert.Equal(2, d.Values.Count);\n        }\n\n        [Fact]\n        public void KeysReturnsNumericKeysIfPresent()\n        {\n            // Arrange\n            var d = new PageDataDictionary<string>();\n\n            // Act\n            d[100] = \"foo\";\n            d[200] = \"bar\";\n\n            // Assert\n            Assert.Equal(2, d.Keys.Count);\n            Assert.Equal(100, d.Keys.ElementAt(0));\n            Assert.Equal(200, d.Keys.ElementAt(1));\n        }\n\n        [Fact]\n        public void KeysReturnsUniqueSetOfValues()\n        {\n            // Act\n            var innerDict = new Dictionary<string, object>()\n            {\n                { \"my-key\", \"value\" },\n                { \"test\", \"test-val\" }\n            };\n            var dict = PageDataDictionary<dynamic>.CreatePageDataFromParameters(new PageDataDictionary<dynamic>(), innerDict);\n\n            // Act\n            dict.Add(\"my-key\", \"added-value\");\n            dict[\"foo\"] = \"bar\";\n\n            // Assert\n            Assert.Equal(4, dict.Keys.Count);\n            Assert.Equal(\"my-key\", dict.Keys.ElementAt(0));\n            Assert.Equal(\"test\", dict.Keys.ElementAt(1));\n            Assert.Equal(0, dict.Keys.ElementAt(2));\n            Assert.Equal(\"foo\", dict.Keys.ElementAt(3));\n            Assert.Equal(dict[0], innerDict);\n        }\n\n        [Fact]\n        public void AddValueOverwritesIndexDictionaryIfKeyExists()\n        {\n            // Act\n            var dict = PageDataDictionary<dynamic>.CreatePageDataFromParameters(new PageDataDictionary<dynamic>(), new[] { \"index-0-orig\", \"index-1\" });\n\n            // Act\n            dict[0] = \"index-0-new\";\n\n            // Assert\n            Assert.Equal(2, dict.Keys.Count);\n            Assert.Equal(\"index-0-new\", dict[0]);\n            Assert.Equal(\"index-1\", dict[1]);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/RenderPageTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.IO;\nusing System.Web.WebPages.Resources;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class RenderPageTest\n    {\n        [Fact]\n        public void RenderBasicTest()\n        {\n            // A simple page that does the following:\n            // @{ PageData[\"Title\"] = \"MyPage\"; }\n            // @PageData[\"Title\"]\n            // hello world\n            //\n            // Expected rendered result is \"MyPagehello world\"\n\n            var content = \"hello world\";\n            var title = \"MyPage\";\n            var result = Utils.RenderWebPage(\n                p =>\n                {\n                    p.PageData[\"Title\"] = title;\n                    p.Write(p.PageData[\"Title\"]);\n                    p.Write(content);\n                });\n\n            Assert.Equal(title + content, result);\n        }\n\n        [Fact]\n        public void RenderDynamicDictionaryBasicTest()\n        {\n            // A simple page that does the following:\n            // @{ Page.Title = \"MyPage\"; }\n            // @Page.Title\n            // hello world\n            //\n            // Expected rendered result is \"MyPagehello world\"\n\n            var content = \"hello world\";\n            var title = \"MyPage\";\n            var result = Utils.RenderWebPage(\n                p =>\n                {\n                    p.Page.Title = title;\n                    p.Write(p.Page.Title);\n                    p.Write(content);\n                });\n\n            Assert.Equal(title + content, result);\n        }\n\n        [Fact]\n        public void RenderPageBasicTest()\n        {\n            // ~/index.cshtml does the following:\n            // hello\n            // @RenderPage(\"subpage.cshtml\")\n            //\n            // ~/subpage.cshtml does the following:\n            // world\n            //\n            // Expected output is \"helloworld\"\n\n            var result = Utils.RenderWebPageWithSubPage(\n                p =>\n                {\n                    p.Write(\"hello\");\n                    p.Write(p.RenderPage(\"subpage.cshtml\"));\n                },\n                p => { p.Write(\"world\"); });\n            Assert.Equal(\"helloworld\", result);\n        }\n\n        [Fact]\n        public void RenderPageAnonymousTypeTest()\n        {\n            // Test for passing an anonymous type object as an argument to RenderPage\n            //\n            // ~/index.cshtml does the following:\n            // @RenderPage(\"subpage.cshtml\", new { HelloKey = \"hellovalue\", MyKey = \"myvalue\" })\n            //\n            // ~/subpage.cshtml does the following:\n            // @PageData[\"HelloKey\"] @PageData[\"MyKey\"] @Model.HelloKey @Model.MyKey\n            //\n            // Expected result: hellovalue myvalue hellovalue myvalue\n            var result = Utils.RenderWebPageWithSubPage(\n                p => { p.Write(p.RenderPage(\"subpage.cshtml\", new { HelloKey = \"hellovalue\", MyKey = \"myvalue\" })); },\n                p =>\n                {\n                    p.Write(p.PageData[\"HelloKey\"]);\n                    p.Write(\" \");\n                    p.Write(p.PageData[\"MyKey\"]);\n                    p.Write(\" \");\n                    p.Write(p.Model.HelloKey);\n                    p.Write(\" \");\n                    p.Write(p.Model.MyKey);\n                });\n            Assert.Equal(\"hellovalue myvalue hellovalue myvalue\", result);\n        }\n\n        [Fact]\n        public void RenderPageDynamicDictionaryAnonymousTypeTest()\n        {\n            // Test for passing an anonymous type object as an argument to RenderPage\n            //\n            // ~/index.cshtml does the following:\n            // @RenderPage(\"subpage.cshtml\", new { HelloKey = \"hellovalue\", MyKey = \"myvalue\" })\n            //\n            // ~/subpage.cshtml does the following:\n            // @Page.HelloKey @Page.MyKey @Model.HelloKey @Model.MyKey\n            //\n            // Expected result: hellovalue myvalue hellovalue myvalue\n            var result = Utils.RenderWebPageWithSubPage(\n                p => { p.Write(p.RenderPage(\"subpage.cshtml\", new { HelloKey = \"hellovalue\", MyKey = \"myvalue\" })); },\n                p =>\n                {\n                    p.Write(p.Page.HelloKey);\n                    p.Write(\" \");\n                    p.Write(p.Page.MyKey);\n                    p.Write(\" \");\n                    p.Write(p.Model.HelloKey);\n                    p.Write(\" \");\n                    p.Write(p.Model.MyKey);\n                });\n            Assert.Equal(\"hellovalue myvalue hellovalue myvalue\", result);\n        }\n\n        [Fact]\n        public void RenderPageDictionaryTest()\n        {\n            // Test for passing a dictionary instance as an argument to RenderPage\n            //\n            // ~/index.cshtml does the following:\n            // @RenderPage(\"subpage.cshtml\", new Dictionary<string, object>(){ { \"foo\", 1 }, { \"bar\", \"hello\"} })\n            //\n            // ~/subpage.cshtml does the following:\n            // @PageData[\"foo\"] @PageData[\"bar\"] @PageData[0]\n            //\n            // Expected result: 1 hello System.Collections.Generic.Dictionary`2[System.String,System.Object]\n\n            var result = Utils.RenderWebPageWithSubPage(\n                p => { p.Write(p.RenderPage(\"subpage.cshtml\", new Dictionary<string, object>() { { \"foo\", 1 }, { \"bar\", \"hello\" } })); },\n                p =>\n                {\n                    p.Write(p.PageData[\"foo\"]);\n                    p.Write(\" \");\n                    p.Write(p.PageData[\"bar\"]);\n                    p.Write(\" \");\n                    p.Write(p.PageData[0]);\n                });\n            Assert.Equal(\"1 hello System.Collections.Generic.Dictionary`2[System.String,System.Object]\", result);\n        }\n\n        [Fact]\n        public void RenderPageDynamicDictionaryTest()\n        {\n            // Test for passing a dictionary instance as an argument to RenderPage\n            //\n            // ~/index.cshtml does the following:\n            // @RenderPage(\"subpage.cshtml\", new Dictionary<string, object>(){ { \"foo\", 1 }, { \"bar\", \"hello\"} })\n            //\n            // ~/subpage.cshtml does the following:\n            // @Page.foo @Page.bar @Page[0]\n            //\n            // Expected result: 1 hello System.Collections.Generic.Dictionary`2[System.String,System.Object]\n\n            var result = Utils.RenderWebPageWithSubPage(\n                p => { p.Write(p.RenderPage(\"subpage.cshtml\", new Dictionary<string, object>() { { \"foo\", 1 }, { \"bar\", \"hello\" } })); },\n                p =>\n                {\n                    p.Write(p.Page.foo);\n                    p.Write(\" \");\n                    p.Write(p.Page.bar);\n                    p.Write(\" \");\n                    p.Write(p.Page[0]);\n                });\n            Assert.Equal(\"1 hello System.Collections.Generic.Dictionary`2[System.String,System.Object]\", result);\n        }\n\n        [Fact]\n        public void RenderPageListTest()\n        {\n            // Test for passing a list of arguments to RenderPage\n            //\n            // ~/index.cshtml does the following:\n            // @RenderPage(\"subpage.cshtml\", \"hello\", \"world\", 1, 2, 3)\n            //\n            // ~/subpage.cshtml does the following:\n            // @PageData[0] @PageData[1] @PageData[2] @PageData[3] @PageData[4]\n            //\n            // Expected result: hello world 1 2 3\n\n            var result = Utils.RenderWebPageWithSubPage(\n                p => { p.Write(p.RenderPage(\"subpage.cshtml\", \"hello\", \"world\", 1, 2, 3)); },\n                p =>\n                {\n                    p.Write(p.PageData[0]);\n                    p.Write(\" \");\n                    p.Write(p.PageData[1]);\n                    p.Write(\" \");\n                    p.Write(p.PageData[2]);\n                    p.Write(\" \");\n                    p.Write(p.PageData[3]);\n                    p.Write(\" \");\n                    p.Write(p.PageData[4]);\n                });\n            Assert.Equal(\"hello world 1 2 3\", result);\n        }\n\n        [Fact]\n        public void RenderPageDynamicDictionaryListTest()\n        {\n            // Test for passing a list of arguments to RenderPage\n            //\n            // ~/index.cshtml does the following:\n            // @RenderPage(\"subpage.cshtml\", \"hello\", \"world\", 1, 2, 3)\n            //\n            // ~/subpage.cshtml does the following:\n            // @Page[0] @Page[1] @Page[2] @Page[3] @Page[4]\n            //\n            // Expected result: hello world 1 2 3\n\n            var result = Utils.RenderWebPageWithSubPage(\n                p => { p.Write(p.RenderPage(\"subpage.cshtml\", \"hello\", \"world\", 1, 2, 3)); },\n                p =>\n                {\n                    p.Write(p.Page[0]);\n                    p.Write(\" \");\n                    p.Write(p.Page[1]);\n                    p.Write(\" \");\n                    p.Write(p.Page[2]);\n                    p.Write(\" \");\n                    p.Write(p.Page[3]);\n                    p.Write(\" \");\n                    p.Write(p.Page[4]);\n                });\n            Assert.Equal(\"hello world 1 2 3\", result);\n        }\n\n        private class Person\n        {\n            public string FirstName { get; set; }\n        }\n\n        [Fact]\n        public void RenderPageDynamicValueTest()\n        {\n            // Test that PageData[key] returns a dynamic value.\n            // ~/index.cshtml does the following:\n            // @RenderPage(\"subpage.cshtml\", new Person(){ FirstName=\"MyFirstName\" })\n            //\n            // ~/subpage.cshtml does the following:\n            // @PageData[0].FirstName\n            //\n            // Expected result: MyFirstName\n            var result = Utils.RenderWebPageWithSubPage(\n                p => { p.Write(p.RenderPage(\"subpage.cshtml\", new Person() { FirstName = \"MyFirstName\" })); },\n                p => { p.Write(p.PageData[0].FirstName); });\n            Assert.Equal(\"MyFirstName\", result);\n        }\n\n        [Fact]\n        public void RenderPageDynamicDictionaryDynamicValueTest()\n        {\n            // Test that PageData[key] returns a dynamic value.\n            // ~/index.cshtml does the following:\n            // @RenderPage(\"subpage.cshtml\", new Person(){ FirstName=\"MyFirstName\" })\n            //\n            // ~/subpage.cshtml does the following:\n            // @Page[0].FirstName\n            //\n            // Expected result: MyFirstName\n            var result = Utils.RenderWebPageWithSubPage(\n                p => { p.Write(p.RenderPage(\"subpage.cshtml\", new Person() { FirstName = \"MyFirstName\" })); },\n                p => { p.Write(p.Page[0].FirstName); });\n            Assert.Equal(\"MyFirstName\", result);\n        }\n\n        [Fact]\n        public void PageDataSetByParentTest()\n        {\n            // Items set in the PageData should be accessible by the subpage\n            var result = Utils.RenderWebPageWithSubPage(\n                p =>\n                {\n                    p.PageData[\"test\"] = \"hello\";\n                    p.Write(p.RenderPage(\"subpage.cshtml\"));\n                },\n                p => { p.Write(p.PageData[\"test\"]); });\n            Assert.Equal(\"hello\", result);\n        }\n\n        [Fact]\n        public void DynamicDictionarySetByParentTest()\n        {\n            // Items set in the PageData should be accessible by the subpage\n            var result = Utils.RenderWebPageWithSubPage(\n                p =>\n                {\n                    p.Page.test = \"hello\";\n                    p.Write(p.RenderPage(\"subpage.cshtml\"));\n                },\n                p => { p.Write(p.Page.test); });\n            Assert.Equal(\"hello\", result);\n        }\n\n        [Fact]\n        public void OverridePageDataSetByParentTest()\n        {\n            // Items set in the PageData should be accessible by the subpage unless\n            // overriden by parameters passed into RenderPage, in which case the \n            // specified value should be used.\n            var result = Utils.RenderWebPageWithSubPage(\n                p =>\n                {\n                    p.PageData[\"test\"] = \"hello\";\n                    p.Write(p.RenderPage(\"subpage.cshtml\", new { Test = \"world\" }));\n                },\n                p =>\n                {\n                    p.Write(p.PageData[\"test\"]);\n                    p.Write(p.PageData[0].Test);\n                });\n            Assert.Equal(\"worldworld\", result);\n        }\n\n        [Fact]\n        public void OverrideDynamicDictionarySetByParentTest()\n        {\n            // Items set in the PageData should be accessible by the subpage unless\n            // overriden by parameters passed into RenderPage, in which case the \n            // specified value should be used.\n            var result = Utils.RenderWebPageWithSubPage(\n                p =>\n                {\n                    p.PageData[\"test\"] = \"hello\";\n                    p.Write(p.RenderPage(\"subpage.cshtml\", new { Test = \"world\" }));\n                },\n                p =>\n                {\n                    p.Write(p.Page.test);\n                    p.Write(p.Page[0].Test);\n                });\n            Assert.Equal(\"worldworld\", result);\n        }\n\n        [Fact]\n        public void RenderPageMissingKeyTest()\n        {\n            // Test that using PageData with a missing key returns null\n            //\n            // ~/index.cshtml does the following:\n            // @RenderPage(\"subpage.cshtml\", new Dictionary<string, object>(){ { \"foo\", 1 }, { \"bar\", \"hello\"} })\n            // @RenderPage(\"subpage.cshtml\", \"x\", \"y\", \"z\")\n            //\n            // ~/subpage.cshtml does the following:\n            // @(PageData[1] ?? \"null\")\n            // @(PageData[\"bar\"] ?? \"null\")\n            //\n            // Expected result: null hello y null\n\n            var result = Utils.RenderWebPageWithSubPage(\n                p =>\n                {\n                    p.Write(p.RenderPage(\"subpage.cshtml\", new Dictionary<string, object>() { { \"foo\", 1 }, { \"bar\", \"hello\" } }));\n                    p.Write(p.RenderPage(\"subpage.cshtml\", \"x\", \"y\", \"z\"));\n                },\n                p =>\n                {\n                    p.Write(p.PageData[1] ?? \"null1\");\n                    p.Write(\" \");\n                    p.Write(p.PageData[\"bar\"] ?? \"null2\");\n                    p.Write(\" \");\n                });\n            Assert.Equal(\"null1 hello y null2 \", result);\n        }\n\n        [Fact]\n        public void RenderPageDynamicDictionaryMissingKeyTest()\n        {\n            // Test that using PageData with a missing key returns null\n            //\n            // ~/index.cshtml does the following:\n            // @RenderPage(\"subpage.cshtml\", new Dictionary<string, object>(){ { \"foo\", 1 }, { \"bar\", \"hello\"} })\n            // @RenderPage(\"subpage.cshtml\", \"x\", \"y\", \"z\")\n            //\n            // ~/subpage.cshtml does the following:\n            // @(Page[1] ?? \"null\")\n            // @(Page.bar ?? \"null\")\n            //\n            // Expected result: null hello y null\n\n            Action<WebPage> subPage = p =>\n            {\n                p.Write(p.Page[1] ?? \"null1\");\n                p.Write(\" \");\n                p.Write(p.Page.bar ?? \"null2\");\n                p.Write(\" \");\n            };\n            var result = Utils.RenderWebPageWithSubPage(\n                p => { p.Write(p.RenderPage(\"subpage.cshtml\", new Dictionary<string, object>() { { \"foo\", 1 }, { \"bar\", \"hello\" } })); }, subPage);\n            Assert.Equal(\"null1 hello \", result);\n            result = Utils.RenderWebPageWithSubPage(\n                p => { p.Write(p.RenderPage(\"subpage.cshtml\", \"x\", \"y\", \"z\")); }, subPage);\n            Assert.Equal(\"y null2 \", result);\n        }\n\n        [Fact]\n        public void RenderPageNoArgumentsTest()\n        {\n            // Test that using PageData within the calling page, and also \n            // within the subppage when the calling page doesn't provide any arguments\n            //\n            // ~/index.cshtml does the following:\n            // @(PageData[\"foo\"] ?? \"null1\")\n            // @RenderPage(\"subpage.cshtml\")\n            //\n            // ~/subpage.cshtml does the following:\n            // @(PageData[1] ?? \"null2\")\n            // @(PageData[\"bar\"] ?? \"null3\")\n            //\n            // Expected result: null1 null2 null3\n\n            var result = Utils.RenderWebPageWithSubPage(\n                p =>\n                {\n                    p.Write(p.PageData[\"foo\"] ?? \"null1 \");\n                    p.Write(p.RenderPage(\"subpage.cshtml\"));\n                },\n                p =>\n                {\n                    p.Write(p.PageData[1] ?? \"null2\");\n                    p.Write(\" \");\n                    p.Write(p.PageData[\"bar\"] ?? \"null3\");\n                });\n            Assert.Equal(\"null1 null2 null3\", result);\n        }\n\n        [Fact]\n        public void RenderPageDynamicDictionaryNoArgumentsTest()\n        {\n            // Test that using PageData within the calling page, and also \n            // within the subppage when the calling page doesn't provide any arguments\n            //\n            // ~/index.cshtml does the following:\n            // @(Page.foo ?? \"null1\")\n            // @RenderPage(\"subpage.cshtml\")\n            //\n            // ~/subpage.cshtml does the following:\n            // @(Page[1] ?? \"null2\")\n            // @(Page.bar ?? \"null3\")\n            //\n            // Expected result: null1 null2 null3\n\n            var result = Utils.RenderWebPageWithSubPage(\n                p =>\n                {\n                    p.Write(p.Page.foo ?? \"null1 \");\n                    p.Write(p.RenderPage(\"subpage.cshtml\"));\n                },\n                p =>\n                {\n                    p.Write(p.Page[1] ?? \"null2\");\n                    p.Write(\" \");\n                    p.Write(p.Page.bar ?? \"null3\");\n                });\n            Assert.Equal(\"null1 null2 null3\", result);\n        }\n\n        [Fact]\n        public void RenderPageNestedSubPageListTest()\n        {\n            // Test that PageData for each level of nesting returns the values as specified in the \n            // previous calling page.\n            //\n            // ~/index.cshtml does the following:\n            // @(PageData[\"foo\"] ?? \"null\")\n            // @RenderPage(\"subpage1.cshtml\", \"a\", \"b\", \"c\")\n            //\n            // ~/subpage1.cshtml does the following:\n            // @(PageData[0] ?? \"sub1null0\")\n            // @(PageData[1] ?? \"sub1null1\")\n            // @(PageData[2] ?? \"sub1null2\")\n            // @(PageData[3] ?? \"sub1null3\")\n            // @RenderPage(\"subpage2.cshtml\", \"x\", \"y\", \"z\")\n            //\n            // ~/subpage2.cshtml does the following:\n            // @(PageData[0] ?? \"sub2null0\")\n            // @(PageData[1] ?? \"sub2null1\")\n            // @(PageData[2] ?? \"sub2null2\")\n            // @(PageData[3] ?? \"sub2null3\")\n            //\n            // Expected result: null a b c sub1null3 x y z sub2null3\n            var page = Utils.CreatePage(\n                p =>\n                {\n                    p.Write(p.PageData[\"foo\"] ?? \"null \");\n                    p.Write(p.RenderPage(\"subpage1.cshtml\", \"a\", \"b\", \"c\"));\n                });\n            var subpage1Path = \"~/subpage1.cshtml\";\n            var subpage1 = Utils.CreatePage(\n                p =>\n                {\n                    p.Write(p.PageData[0] ?? \"sub1null0\");\n                    p.Write(\" \");\n                    p.Write(p.PageData[1] ?? \"sub1null1\");\n                    p.Write(\" \");\n                    p.Write(p.PageData[2] ?? \"sub1null2\");\n                    p.Write(\" \");\n                    p.Write(p.PageData[3] ?? \"sub1null3\");\n                    p.Write(\" \");\n                    p.Write(p.RenderPage(\"subpage2.cshtml\", \"x\", \"y\", \"z\"));\n                }, subpage1Path);\n            var subpage2Path = \"~/subpage2.cshtml\";\n            var subpage2 = Utils.CreatePage(\n                p =>\n                {\n                    p.Write(p.PageData[0] ?? \"sub2null0\");\n                    p.Write(\" \");\n                    p.Write(p.PageData[1] ?? \"sub2null1\");\n                    p.Write(\" \");\n                    p.Write(p.PageData[2] ?? \"sub2null2\");\n                    p.Write(\" \");\n                    p.Write(p.PageData[3] ?? \"sub2null3\");\n                }, subpage2Path);\n\n            Utils.AssignObjectFactoriesAndDisplayModeProvider(page, subpage1, subpage2);\n\n            var result = Utils.RenderWebPage(page);\n            Assert.Equal(\"null a b c sub1null3 x y z sub2null3\", result);\n        }\n\n        [Fact]\n        public void RenderPageNestedSubPageAnonymousTypeTest()\n        {\n            // Test that PageData for each level of nesting returns the values as specified in the \n            // previous calling page.\n            //\n            // ~/index.cshtml does the following:\n            // @(PageData[\"foo\"] ?? \"null\")\n            // @RenderPage(\"subpage.cshtml\", new { foo = 1 , bar = \"hello\" })\n            //\n            // ~/subpage1.cshtml does the following:\n            // @(PageData[\"foo\"] ?? \"sub1nullfoo\")\n            // @(PageData[\"bar\"] ?? \"sub1nullbar\")\n            // @(PageData[\"x\"] ?? \"sub1nullx\")\n            // @(PageData[\"y\"] ?? \"sub1nully\")\n            // @RenderPage(\"subpage2.cshtml\", new { bar = \"world\", x = \"good\", y = \"bye\"})\n            //\n            // ~/subpage2.cshtml does the following:\n            // @(PageData[\"foo\"] ?? \"sub2nullfoo\")\n            // @(PageData[\"bar\"] ?? \"sub2nullbar\")\n            // @(PageData[\"x\"] ?? \"sub2nullx\")\n            // @(PageData[\"y\"] ?? \"sub2nully\")\n            //\n            // Expected result: null 1 hello sub1nullx sub1nully sub2nullfoo world good bye\n            var page = Utils.CreatePage(\n                p =>\n                {\n                    p.Write(p.PageData[\"foo\"] ?? \"null \");\n                    p.Write(p.RenderPage(\"subpage1.cshtml\", new { foo = 1, bar = \"hello\" }));\n                });\n            var subpage1Path = \"~/subpage1.cshtml\";\n            var subpage1 = Utils.CreatePage(\n                p =>\n                {\n                    p.Write(p.PageData[\"foo\"] ?? \"sub1nullfoo\");\n                    p.Write(\" \");\n                    p.Write(p.PageData[\"bar\"] ?? \"sub1nullbar\");\n                    p.Write(\" \");\n                    p.Write(p.PageData[\"x\"] ?? \"sub1nullx\");\n                    p.Write(\" \");\n                    p.Write(p.PageData[\"y\"] ?? \"sub1nully\");\n                    p.Write(\" \");\n                    p.Write(p.RenderPage(\"subpage2.cshtml\", new { bar = \"world\", x = \"good\", y = \"bye\" }));\n                }, subpage1Path);\n            var subpage2Path = \"~/subpage2.cshtml\";\n            var subpage2 = Utils.CreatePage(\n                p =>\n                {\n                    p.Write(p.PageData[\"foo\"] ?? \"sub2nullfoo\");\n                    p.Write(\" \");\n                    p.Write(p.PageData[\"bar\"] ?? \"sub2nullbar\");\n                    p.Write(\" \");\n                    p.Write(p.PageData[\"x\"] ?? \"sub2nullx\");\n                    p.Write(\" \");\n                    p.Write(p.PageData[\"y\"] ?? \"sub2nully\");\n                }, subpage2Path);\n\n            Utils.AssignObjectFactoriesAndDisplayModeProvider(subpage1, subpage2, page);\n\n            var result = Utils.RenderWebPage(page);\n            Assert.Equal(\"null 1 hello sub1nullx sub1nully sub2nullfoo world good bye\", result);\n        }\n\n        [Fact]\n        public void RenderPageNestedSubPageDictionaryTest()\n        {\n            // Test that PageData for each level of nesting returns the values as specified in the \n            // previous calling page.\n            //\n            // ~/index.cshtml does the following:\n            // @(PageData[\"foo\"] ?? \"null\")\n            // @RenderPage(\"subpage.cshtml\", new Dictionary<string, object>(){ { \"foo\", 1 }, { \"bar\", \"hello\"} })\n            //\n            // ~/subpage1.cshtml does the following:\n            // @(PageData[\"foo\"] ?? \"sub1nullfoo\")\n            // @(PageData[\"bar\"] ?? \"sub1nullbar\")\n            // @(PageData[\"x\"] ?? \"sub1nullx\")\n            // @(PageData[\"y\"] ?? \"sub1nully\")\n            // @RenderPage(\"subpage2.cshtml\", new Dictionary<string, object>(){ { { \"bar\", \"world\"}, {\"x\", \"good\"}, {\"y\", \"bye\"} })\n            //\n            // ~/subpage2.cshtml does the following:\n            // @(PageData[\"foo\"] ?? \"sub2nullfoo\")\n            // @(PageData[\"bar\"] ?? \"sub2nullbar\")\n            // @(PageData[\"x\"] ?? \"sub2nullx\")\n            // @(PageData[\"y\"] ?? \"sub2nully\")\n            //\n            // Expected result: null 1 hello sub1nullx sub1nully sub2nullfoo world good bye\n            var page = Utils.CreatePage(\n                p =>\n                {\n                    p.Write(p.PageData[\"foo\"] ?? \"null \");\n                    p.Write(p.RenderPage(\"subpage1.cshtml\", new Dictionary<string, object>() { { \"foo\", 1 }, { \"bar\", \"hello\" } }));\n                });\n            var subpage1Path = \"~/subpage1.cshtml\";\n            var subpage1 = Utils.CreatePage(\n                p =>\n                {\n                    p.Write(p.PageData[\"foo\"] ?? \"sub1nullfoo\");\n                    p.Write(\" \");\n                    p.Write(p.PageData[\"bar\"] ?? \"sub1nullbar\");\n                    p.Write(\" \");\n                    p.Write(p.PageData[\"x\"] ?? \"sub1nullx\");\n                    p.Write(\" \");\n                    p.Write(p.PageData[\"y\"] ?? \"sub1nully\");\n                    p.Write(\" \");\n                    p.Write(p.RenderPage(\"subpage2.cshtml\", new Dictionary<string, object>() { { \"bar\", \"world\" }, { \"x\", \"good\" }, { \"y\", \"bye\" } }));\n                }, subpage1Path);\n            var subpage2Path = \"~/subpage2.cshtml\";\n            var subpage2 = Utils.CreatePage(\n                p =>\n                {\n                    p.Write(p.PageData[\"foo\"] ?? \"sub2nullfoo\");\n                    p.Write(\" \");\n                    p.Write(p.PageData[\"bar\"] ?? \"sub2nullbar\");\n                    p.Write(\" \");\n                    p.Write(p.PageData[\"x\"] ?? \"sub2nullx\");\n                    p.Write(\" \");\n                    p.Write(p.PageData[\"y\"] ?? \"sub2nully\");\n                }, subpage2Path);\n\n            Utils.AssignObjectFactoriesAndDisplayModeProvider(page, subpage1, subpage2);\n\n            var result = Utils.RenderWebPage(page);\n            Assert.Equal(\"null 1 hello sub1nullx sub1nully sub2nullfoo world good bye\", result);\n        }\n\n        [Fact]\n        public void RenderPageNestedParentPageDataTest()\n        {\n            // PageData should return values set by parent pages.\n            var page = Utils.CreatePage(\n                p =>\n                {\n                    p.PageData[\"key1\"] = \"value1\";\n                    p.Write(p.RenderPage(\"subpage1.cshtml\"));\n                });\n            var subpage1Path = \"~/subpage1.cshtml\";\n            var subpage1 = Utils.CreatePage(\n                p =>\n                {\n                    p.WriteLiteral(\"<subpage1>\");\n                    p.Write(p.PageData[\"key1\"]);\n                    p.Write(p.RenderPage(\"subpage2.cshtml\"));\n                    p.Write(p.PageData[\"key1\"]);\n                    p.PageData[\"key1\"] = \"value2\";\n                    p.Write(p.RenderPage(\"subpage2.cshtml\"));\n                    p.WriteLiteral(\"</subpage1>\");\n                }, subpage1Path);\n            var subpage2Path = \"~/subpage2.cshtml\";\n            var subpage2 = Utils.CreatePage(\n                p =>\n                {\n                    p.WriteLiteral(\"<subpage2>\");\n                    p.Write(p.PageData[\"key1\"]);\n                    // Setting the value in the child page should\n                    // not affect the parent page\n                    p.PageData[\"key1\"] = \"value3\";\n                    p.Write(p.RenderPage(\"subpage3.cshtml\", new { Key1 = \"value4\" }));\n                    p.WriteLiteral(\"</subpage2>\");\n                }, subpage2Path);\n            var subpage3Path = \"~/subpage3.cshtml\";\n            var subpage3 = Utils.CreatePage(\n                p =>\n                {\n                    p.WriteLiteral(\"<subpage3>\");\n                    p.Write(p.PageData[\"key1\"]);\n                    p.WriteLiteral(\"</subpage3>\");\n                }, subpage3Path);\n\n            Utils.AssignObjectFactoriesAndDisplayModeProvider(subpage1, subpage2, subpage3, page);\n\n            var result = Utils.RenderWebPage(page);\n            Assert.Equal(\"<subpage1>value1<subpage2>value1<subpage3>value4</subpage3></subpage2>value1<subpage2>value2<subpage3>value4</subpage3></subpage2></subpage1>\", result);\n        }\n\n        [Fact]\n        public void WriteNullTest()\n        {\n            // Test for @null\n            var result = Utils.RenderWebPage(\n                p =>\n                {\n                    p.Write(null);\n                    p.Write((object)null);\n                    p.Write((HelperResult)null);\n                });\n\n            Assert.Equal(\"\", result);\n        }\n\n        [Fact]\n        public void WriteTest()\n        {\n            // Test for calling WebPage.Write on text and HtmlHelper\n            var text = \"Hello\";\n            var wrote = false;\n            Action<TextWriter> action = tw =>\n            {\n                tw.Write(text);\n                wrote = true;\n            };\n            var helper = new HelperResult(action);\n            var result = Utils.RenderWebPage(\n                p => { p.Write(helper); });\n            Assert.Equal(text, result);\n            Assert.True(wrote);\n        }\n\n        [Fact]\n        public void WriteLiteralTest()\n        {\n            // Test for calling WebPage.WriteLiteral on text and HtmlHelper\n            var text = \"Hello\";\n            var wrote = false;\n            Action<TextWriter> action = tw =>\n            {\n                tw.Write(text);\n                wrote = true;\n            };\n            var helper = new HelperResult(action);\n            var result = Utils.RenderWebPage(\n                p => { p.WriteLiteral(helper); });\n            Assert.Equal(text, result);\n            Assert.True(wrote);\n        }\n\n        [Fact]\n        public void ExtensionNotSupportedTest()\n        {\n            // Tests that calling RenderPage on an unsupported extension returns a new simpler error message\n            // instead of the full error about build providers in system.web.dll.\n            var vpath = \"~/hello/world.txt\";\n            var ext = \".txt\";\n            var compilationUtilThrowingBuildManager = new CompilationUtil();\n            var otherExceptionBuildManager = new Mock<IVirtualPathFactory>();\n            var msg = \"The file \\\"~/hello/world.txt\\\" could not be rendered, because it does not exist or is not a valid page.\";\n            otherExceptionBuildManager.Setup(c => c.CreateInstance(It.IsAny<string>())).Throws(new HttpException(msg));\n\n            Assert.Throws<HttpException>(() =>\n                                                  WebPage.CreateInstanceFromVirtualPath(vpath, new VirtualPathFactoryManager(compilationUtilThrowingBuildManager)),\n                                                  String.Format(CultureInfo.CurrentCulture, WebPageResources.WebPage_FileNotSupported, ext, vpath));\n\n            // Test that other error messages are thrown unmodified.\n            Assert.Throws<HttpException>(() => WebPage.CreateInstanceFromVirtualPath(vpath, otherExceptionBuildManager.Object), msg);\n        }\n\n        [Fact]\n        public void RenderBodyCalledInChildPageTest()\n        {\n            // A Page that is called by RenderPage should not be able to call RenderBody().\n\n            Assert.Throws<HttpException>(() =>\n                Utils.RenderWebPageWithSubPage(\n                    p =>\n                    {\n                        p.Write(\"hello\");\n                        p.Write(p.RenderPage(\"subpage.cshtml\"));\n                    },\n                    p =>\n                    {\n                        p.Write(\"world\");\n                        p.RenderBody();\n                    }),\n                String.Format(CultureInfo.CurrentCulture, WebPageResources.WebPage_CannotRequestDirectly, \"~/subpage.cshtml\", \"RenderBody\"));\n        }\n\n        [Fact]\n        public void RenderPageInvalidPageType()\n        {\n            var pagePath = \"~/foo.js\";\n            var page = Utils.CreatePage(p => { p.Write(p.RenderPage(pagePath)); });\n\n            var objectFactory = new Mock<IVirtualPathFactory>();\n            objectFactory.Setup(c => c.Exists(It.IsAny<string>())).Returns<string>(p => pagePath.Equals(p, StringComparison.OrdinalIgnoreCase));\n            objectFactory.Setup(c => c.CreateInstance(It.IsAny<string>())).Returns<string>(_ => null);\n            page.VirtualPathFactory = objectFactory.Object;\n\n            Assert.Throws<HttpException>(() =>\n            {\n                page.VirtualPathFactory = objectFactory.Object;\n                page.DisplayModeProvider = new DisplayModeProvider();\n                Utils.RenderWebPage(page);\n            },\n            String.Format(CultureInfo.CurrentCulture, WebPageResources.WebPage_InvalidPageType, pagePath));\n        }\n\n        [Fact]\n        public void RenderPageValidPageType()\n        {\n            var pagePath = \"~/foo.js\";\n            var page = Utils.CreatePage(p => { p.Write(p.RenderPage(pagePath)); });\n\n            var contents = \"hello world\";\n            var subPage = Utils.CreatePage(p => p.Write(contents), pagePath);\n\n            Utils.AssignObjectFactoriesAndDisplayModeProvider(page, subPage);\n\n            Assert.Equal(contents, Utils.RenderWebPage(page));\n        }\n\n        [Fact]\n        public void RenderPageNull()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(() => Utils.RenderWebPage(p => p.RenderPage(null)), \"path\");\n        }\n\n        [Fact]\n        public void RenderPageEmptyString()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(() => Utils.RenderWebPage(p => p.RenderPage(\"\")), \"path\");\n        }\n\n        [Fact]\n        public void SamePageCaseInsensitiveTest()\n        {\n            var result = Utils.RenderWebPage(\n                p =>\n                {\n                    p.PageData[\"xyz\"] = \"value\";\n                    p.PageData[\"XYZ\"] = \"VALUE\";\n                    p.Write(p.PageData[\"xYz\"]);\n                });\n\n            Assert.Equal(\"VALUE\", result);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/RequestBrowserOverrideStoreTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class RequestBrowserOverrideStoreTest\n    {\n        [Fact]\n        public void GetOverriddenUserAgentReturnsRequestUserAgent()\n        {\n            // Arrange\n            RequestBrowserOverrideStore requestStore = new RequestBrowserOverrideStore();\n            Mock<HttpContextBase> context = new Mock<HttpContextBase>();\n            context.Setup(c => c.Request.UserAgent).Returns(\"testUserAgent\");\n\n            // Act & Assert\n            Assert.Equal(\"testUserAgent\", requestStore.GetOverriddenUserAgent(context.Object));\n        }\n\n        [Fact]\n        public void SetOverriddenUserAgentDoesNotOverrideUserAgent()\n        {\n            // Arrange\n            RequestBrowserOverrideStore requestStore = new RequestBrowserOverrideStore();\n            Mock<HttpContextBase> context = new Mock<HttpContextBase>();\n            context.Setup(c => c.Request.UserAgent).Returns(\"testUserAgent\");\n\n            // Act\n            requestStore.SetOverriddenUserAgent(context.Object, \"setUserAgent\");\n\n            // Assert\n            Assert.Equal(\"testUserAgent\", requestStore.GetOverriddenUserAgent(context.Object));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/RequestResourceTrackerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class RequestResourceTrackerTest\n    {\n        [Fact]\n        public void RegisteringForDisposeDisposesObjects()\n        {\n            // Arrange\n            var context = new Mock<HttpContextBase>();\n            IDictionary items = new Hashtable();\n            context.Setup(m => m.Items).Returns(items);\n            var disposable = new Mock<IDisposable>();\n            disposable.Setup(m => m.Dispose()).Verifiable();\n\n            // Act\n            RequestResourceTracker.RegisterForDispose(context.Object, disposable.Object);\n            RequestResourceTracker.DisposeResources(context.Object);\n\n            // Assert\n            disposable.VerifyAll();\n        }\n\n        [Fact]\n        public void RegisteringForDisposeExtensionMethodNullContextThrows()\n        {\n            // Arrange\n            var disposable = new Mock<IDisposable>();\n\n            // Act\n            Assert.ThrowsArgumentNull(() => HttpContextExtensions.RegisterForDispose(null, disposable.Object), \"context\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/StartPageTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\nusing System.Web.Caching;\nusing System.Web.Compilation;\nusing System.Web.Hosting;\nusing System.Web.Profile;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class StartPageTest\n    {\n        // The page ~/_pagestart.cshtml does the following:\n        // this is the init page\n        //\n        // The page ~/index.cshtml does the following:\n        // hello world\n        // Expected result:\n        // this is the init page hello world\n        [Fact]\n        public void InitPageBasicTest()\n        {\n            var init = Utils.CreateStartPage(p =>\n                                             p.Write(\"this is the init page \"));\n            var page = Utils.CreatePage(p =>\n                                        p.Write(\"hello world\"));\n\n            init.ChildPage = page;\n\n            var result = Utils.RenderWebPage(page, init);\n            Assert.Equal(\"this is the init page hello world\", result);\n        }\n\n        // The page ~/_pagestart.cshtml does the following:\n        // this is the init page\n        //\n        // The page ~/folder1/index.cshtml does the following:\n        // hello world\n        // Expected result:\n        // this is the init page hello world\n        [Fact]\n        public void InitSubfolderTest()\n        {\n            var init = Utils.CreateStartPage(p =>\n                                             p.Write(\"this is the init page \"));\n            var page = Utils.CreatePage(p =>\n                                        p.Write(\"hello world\"), \"~/folder1/index.cshtml\");\n\n            init.ChildPage = page;\n\n            var result = Utils.RenderWebPage(page, init);\n            Assert.Equal(\"this is the init page hello world\", result);\n        }\n\n        // The page ~/_pagestart.cshtml does the following:\n        // PageData[\"Title\"] = \"InitPage\";\n        // Layout = \"Layout.cshtml\";\n        // this is the init page\n        //\n        // The page ~/index.cshtml does the following:\n        // PageData[\"Title\"] = \"IndexCshtmlPage\"\n        // hello world\n        //\n        // The layout page ~/Layout.cshtml does the following:\n        // layout start\n        // @PageData[\"Title\"]\n        // @RenderBody()\n        // layout end\n        //\n        // Expected result:\n        // layout start IndexCshtmlPage this is the init page hello world layout end\n        [Fact]\n        public void InitPageLayoutTest()\n        {\n            var init = Utils.CreateStartPage(p =>\n            {\n                p.Layout = \"Layout.cshtml\";\n                p.Write(\" this is the init page \");\n                Assert.Equal(\"~/Layout.cshtml\", p.Layout);\n            });\n            var page = Utils.CreatePage(p =>\n            {\n                p.PageData[\"Title\"] = \"IndexCshtmlPage\";\n                p.Write(\"hello world\");\n            });\n            var layoutPage = Utils.CreatePage(p =>\n            {\n                p.Write(\"layout start \");\n                p.Write(p.PageData[\"Title\"]);\n                p.WriteLiteral(p.RenderBody());\n                p.Write(\" layout end\");\n            }, \"~/Layout.cshtml\");\n\n            init.ChildPage = page;\n            Utils.AssignObjectFactoriesAndDisplayModeProvider(init, page, layoutPage);\n\n            var result = Utils.RenderWebPage(page, init);\n            Assert.Equal(\"layout start IndexCshtmlPage this is the init page hello world layout end\", result);\n        }\n\n        // _pagestart.cshtml sets the LayoutPage to be null\n        [Fact]\n        public void InitPageNullLayoutPageTest()\n        {\n            var init1 = Utils.CreateStartPage(\n                p =>\n                {\n                    p.Layout = \"~/Layout.cshtml\";\n                    p.WriteLiteral(\"<init1>\");\n                    p.RunPage();\n                    p.WriteLiteral(\"</init1>\");\n                });\n            var init2path = \"~/folder1/_pagestart.cshtml\";\n            var init2 = Utils.CreateStartPage(\n                p =>\n                {\n                    p.Layout = null;\n                    p.WriteLiteral(\"<init2>\");\n                    p.RunPage();\n                    p.WriteLiteral(\"</init2>\");\n                }, init2path);\n            var page = Utils.CreatePage(p =>\n                                        p.Write(\"hello world\"), \"~/folder1/index.cshtml\");\n            var layoutPage = Utils.CreatePage(p =>\n                                              p.Write(\"layout page\"), \"~/Layout.cshtml\");\n\n            Utils.AssignObjectFactoriesAndDisplayModeProvider(page, layoutPage, init1, init2);\n\n            init1.ChildPage = init2;\n            init2.ChildPage = page;\n\n            var result = Utils.RenderWebPage(page, init1);\n            Assert.Equal(\"<init1><init2>hello world</init2></init1>\", result);\n        }\n\n        // _pagestart.cshtml sets the LayoutPage, but page sets it to null\n        [Fact]\n        public void PageSetsNullLayoutPageTest()\n        {\n            var init1 = Utils.CreateStartPage(\n                p =>\n                {\n                    p.Layout = \"~/Layout.cshtml\";\n                    p.WriteLiteral(\"<init1>\");\n                    p.RunPage();\n                    p.WriteLiteral(\"</init1>\");\n                });\n            var layoutPage = Utils.CreatePage(p =>\n                                              p.Write(\"layout page\"), \"~/Layout.cshtml\");\n            var page = Utils.CreatePage(p =>\n            {\n                p.Layout = null;\n                p.Write(\"hello world\");\n            });\n            Utils.AssignObjectFactoriesAndDisplayModeProvider(init1, layoutPage, page);\n            init1.ChildPage = page;\n            var result = Utils.RenderWebPage(page, init1);\n            Assert.Equal(\"<init1>hello world</init1>\", result);\n        }\n\n        [Fact]\n        public void PageSetsEmptyLayoutPageTest()\n        {\n            var init1 = Utils.CreateStartPage(\n                p =>\n                {\n                    p.Layout = \"~/Layout.cshtml\";\n                    p.WriteLiteral(\"<init1>\");\n                    p.RunPage();\n                    p.WriteLiteral(\"</init1>\");\n                });\n            var layoutPage = Utils.CreatePage(p =>\n                                              p.Write(\"layout page\"), \"~/Layout.cshtml\");\n            var page = Utils.CreatePage(p =>\n            {\n                p.Layout = \"\";\n                p.Write(\"hello world\");\n            });\n            Utils.AssignObjectFactoriesAndDisplayModeProvider(init1, layoutPage, page);\n            init1.ChildPage = page;\n            var result = Utils.RenderWebPage(page, init1);\n            Assert.Equal(\"<init1>hello world</init1>\", result);\n        }\n\n        // The page ~/_pagestart.cshtml does the following:\n        // init page start\n        // @RunPage()\n        // init page end\n        //\n        // The page ~/index.cshtml does the following:\n        // hello world\n        //\n        // Expected result:\n        // init page start hello world init page end\n        [Fact]\n        public void RunPageTest()\n        {\n            var init = Utils.CreateStartPage(\n                p =>\n                {\n                    p.Write(\"init page start \");\n                    p.RunPage();\n                    p.Write(\" init page end\");\n                });\n            var page = Utils.CreatePage(p =>\n                                        p.Write(\"hello world\"));\n\n            init.ChildPage = page;\n\n            var result = Utils.RenderWebPage(page, init);\n            Assert.Equal(\"init page start hello world init page end\", result);\n        }\n\n        // The page ~/_pagestart.cshtml does the following:\n        // <init1>\n        // @RunPage()\n        // </init1>\n        //\n        // The page ~/folder1/_pagestart.cshtml does the following:\n        // <init2>\n        // @RunPage()\n        // </init2>\n        //\n        // The page ~/folder1/index.cshtml does the following:\n        // hello world\n        //\n        // Expected result:\n        // <init1><init2>hello world</init2></init1>\n        [Fact]\n        public void NestedRunPageTest()\n        {\n            var init1 = Utils.CreateStartPage(\n                p =>\n                {\n                    p.WriteLiteral(\"<init1>\");\n                    p.RunPage();\n                    p.WriteLiteral(\"</init1>\");\n                });\n            var init2path = \"~/folder1/_pagestart.cshtml\";\n            var init2 = Utils.CreateStartPage(\n                p =>\n                {\n                    p.WriteLiteral(\"<init2>\");\n                    p.RunPage();\n                    p.WriteLiteral(\"</init2>\");\n                }, init2path);\n            var page = Utils.CreatePage(p =>\n                                        p.Write(\"hello world\"), \"~/folder1/index.cshtml\");\n\n            init1.ChildPage = init2;\n            init2.ChildPage = page;\n\n            var result = Utils.RenderWebPage(page, init1);\n            Assert.Equal(\"<init1><init2>hello world</init2></init1>\", result);\n        }\n\n        // The page ~/_pagestart.cshtml does the following:\n        // PageData[\"key1\"] = \"value1\";\n        //\n        // The page ~/folder1/_pagestart.cshtml does the following:\n        // PageData[\"key2\"] = \"value2\";\n        //\n        // The page ~/folder1/index.cshtml does the following:\n        // @PageData[\"key1\"] @PageData[\"key2\"] @PageData[\"key3\"]\n        //\n        // Expected result:\n        // value1 value2\n        [Fact]\n        public void PageDataTest()\n        {\n            var init1 = Utils.CreateStartPage(p => p.PageData[\"key1\"] = \"value1\");\n            var init2path = \"~/folder1/_pagestart.cshtml\";\n            var init2 = Utils.CreateStartPage(p => p.PageData[\"key2\"] = \"value2\", init2path);\n            var page = Utils.CreatePage(\n                p =>\n                {\n                    p.Write(p.PageData[\"key1\"]);\n                    p.Write(\" \");\n                    p.Write(p.PageData[\"key2\"]);\n                },\n                \"~/folder1/index.cshtml\");\n\n            init1.ChildPage = init2;\n            init2.ChildPage = page;\n\n            var result = Utils.RenderWebPage(page, init1);\n            Assert.Equal(\"value1 value2\", result);\n        }\n\n        // The page ~/_pagestart.cshtml does the following:\n        // init page\n        // @RenderPage(\"subpage.cshtml\", \"init_data\");\n        //\n        // The page ~/subpage.cshtml does the following:\n        // subpage\n        // @PageData[0]\n        //\n        // The page ~/index.cshtml does the following:\n        // hello world\n        //\n        // Expected result:\n        // init page subpage init_data hello world\n        [Fact]\n        public void RenderPageTest()\n        {\n            var init = Utils.CreateStartPage(\n                p =>\n                {\n                    p.Write(\"init page \");\n                    p.Write(p.RenderPage(\"subpage.cshtml\", \"init_data\"));\n                });\n            var subpagePath = \"~/subpage.cshtml\";\n            var subpage = Utils.CreatePage(\n                p =>\n                {\n                    p.Write(\"subpage \");\n                    p.Write(p.PageData[0]);\n                }, subpagePath);\n            var page = Utils.CreatePage(p =>\n                                        p.Write(\" hello world\"));\n\n            init.ChildPage = page;\n            Utils.AssignObjectFactoriesAndDisplayModeProvider(init, page, subpage);\n\n            var result = Utils.RenderWebPage(page, init);\n            Assert.Equal(\"init page subpage init_data hello world\", result);\n        }\n\n        [Fact]\n        // The page ~/_pagestart.cshtml does the following:\n        // <init>\n        // @{\n        //     try {\n        //         RunPage();\n        //     } catch (Exception e) {\n        //         Write(\"Exception: \" + e.Message);\n        //     }\n        // }\n        // </init>\n        //\n        // The page ~/index.cshtml does the following:\n        // hello world\n        // @{throw new InvalidOperation(\"exception from index.cshtml\");}\n        //\n        // Expected result:\n        // <init>hello world Exception: exception from index.cshtml</init>\n        public void InitCatchExceptionTest()\n        {\n            var init = Utils.CreateStartPage(\n                p =>\n                {\n                    p.WriteLiteral(\"<init>\");\n                    try\n                    {\n                        p.RunPage();\n                    }\n                    catch (Exception e)\n                    {\n                        p.Write(\"Exception: \" + e.Message);\n                    }\n                    p.WriteLiteral(\"</init>\");\n                });\n            var page = Utils.CreatePage(\n                p =>\n                {\n                    p.WriteLiteral(\"hello world \");\n                    throw new InvalidOperationException(\"exception from index.cshtml\");\n                });\n\n            init.ChildPage = page;\n\n            var result = Utils.RenderWebPage(page, init);\n            Assert.Equal(\"<init>hello world Exception: exception from index.cshtml</init>\", result);\n        }\n\n        public class MockInitPage : MockStartPage\n        {\n            internal object GetBuildManager()\n            {\n                return typeof(BuildManager).GetField(\"_theBuildManager\", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);\n            }\n        }\n\n        // Simulate a site that is nested, eg /subfolder1/website1\n        [Fact]\n        public void ExecuteWithinInitTest()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                Utils.CreateHttpRuntime(\"/subfolder1/website1\");\n                new HostingEnvironment();\n                var stringSet = Activator.CreateInstance(typeof(BuildManager).Assembly.GetType(\"System.Web.Util.StringSet\"), true);\n                typeof(BuildManager).GetField(\"_forbiddenTopLevelDirectories\", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(new MockInitPage().GetBuildManager(), stringSet);\n                ;\n\n                var init = new MockInitPage()\n                {\n                    VirtualPath = \"~/_pagestart.cshtml\",\n                    ExecuteAction = p => { },\n                };\n                var page = Utils.CreatePage(p => { });\n\n                Utils.AssignObjectFactoriesAndDisplayModeProvider(page, init);\n\n                var result = Utils.RenderWebPage(page);\n            });\n        }\n\n        [Fact]\n        public void SetGetPropertiesTest()\n        {\n            var init = new MockInitPage();\n            var page = new MockPage();\n            init.ChildPage = page;\n\n            // Context\n            var context = new Mock<HttpContextBase>().Object;\n            init.Context = context;\n            Assert.Equal(context, init.Context);\n            Assert.Equal(context, page.Context);\n\n            // Profile/Request/Response/Server/Cache/Session/Application\n            var profile = new Mock<ProfileBase>().Object;\n            var request = new Mock<HttpRequestBase>().Object;\n            var response = new Mock<HttpResponseBase>().Object;\n            var server = new Mock<HttpServerUtilityBase>().Object;\n            var cache = new Cache();\n            var app = new Mock<HttpApplicationStateBase>().Object;\n            var session = new Mock<HttpSessionStateBase>().Object;\n\n            var contextMock = new Mock<HttpContextBase>();\n            contextMock.Setup(c => c.Profile).Returns(profile);\n            contextMock.Setup(c => c.Request).Returns(request);\n            contextMock.Setup(c => c.Response).Returns(response);\n            contextMock.Setup(c => c.Cache).Returns(cache);\n            contextMock.Setup(c => c.Server).Returns(server);\n            contextMock.Setup(c => c.Application).Returns(app);\n            contextMock.Setup(c => c.Session).Returns(session);\n\n            context = contextMock.Object;\n            page.Context = context;\n            Assert.Same(profile, init.Profile);\n            Assert.Same(request, init.Request);\n            Assert.Same(response, init.Response);\n            Assert.Same(cache, init.Cache);\n            Assert.Same(server, init.Server);\n            Assert.Same(session, init.Session);\n            Assert.Same(app, init.AppState);\n        }\n\n        [Fact]\n        public void GetDirectoryTest()\n        {\n            var initPage = new Mock<StartPage>().Object;\n            Assert.Equal(\"/website1/\", initPage.GetDirectory(\"/website1/default.cshtml\"));\n            Assert.Equal(\"~/\", initPage.GetDirectory(\"~/default.cshtml\"));\n            Assert.Equal(\"/\", initPage.GetDirectory(\"/website1/\"));\n            Assert.Null(initPage.GetDirectory(\"/\"));\n        }\n\n        [Fact]\n        public void GetStartPageReturnsStartPageFromCurrentDirectoryIfExists()\n        {\n            // Arrange\n            var initPage = Utils.CreateStartPage(p => p.Write(\"<init>\"), \"~/subdir/_pagestart.vbhtml\");\n            var page = Utils.CreatePage(p => p.Write(\"test\"), \"~/subdir/_index.cshtml\");\n            var objectFactory = Utils.AssignObjectFactoriesAndDisplayModeProvider(page, initPage);\n\n            // Act\n            var result = StartPage.GetStartPage(page, objectFactory, null, WebPageHttpHandler.StartPageFileName, new string[] { \"cshtml\", \"vbhtml\" });\n\n            // Assert\n            Assert.Equal(initPage, result);\n        }\n\n        [Fact]\n        public void GetStartPageReturnsStartPageFromParentDirectoryIfStartPageDoesNotExistInCurrentDirectory()\n        {\n            // Arrange\n            var initPage = Utils.CreateStartPage(null, \"~/subdir/_pagestart.vbhtml\");\n            var page = Utils.CreatePage(null, \"~/subdir/subsubdir/test.cshtml\");\n            var objectFactory = Utils.AssignObjectFactoriesAndDisplayModeProvider(page, initPage);\n\n            // Act\n            var result = StartPage.GetStartPage(page, objectFactory, null, WebPageHttpHandler.StartPageFileName, new string[] { \"cshtml\", \"vbhtml\" });\n\n            // Assert\n            Assert.Equal(initPage, result);\n        }\n\n        [Fact]\n        public void GetStartPageCreatesChainOfStartPages()\n        {\n            // Arrange\n            var subInitPage = Utils.CreateStartPage(null, \"~/subdir/_pagestart.vbhtml\");\n            var initPage = Utils.CreateStartPage(null, \"~/_pagestart.vbhtml\");\n            var page = Utils.CreatePage(null, \"~/subdir/subsubdir/subsubsubdir/test.cshtml\");\n            var objectFactory = Utils.AssignObjectFactoriesAndDisplayModeProvider(page, initPage, subInitPage);\n\n            // Act\n            var result = StartPage.GetStartPage(page, objectFactory, null, WebPageHttpHandler.StartPageFileName, new string[] { \"cshtml\", \"vbhtml\" });\n\n            // Assert\n            Assert.Equal(initPage, result);\n            Assert.Equal(subInitPage, (result as StartPage).ChildPage);\n        }\n\n        [Fact]\n        public void GetStartPageReturnsStartPageFromRoot()\n        {\n            // Arrange\n            var initPage = Utils.CreateStartPage(null, \"~/_pagestart.vbhtml\");\n            var page = Utils.CreatePage(null, \"~/subdir/subsubdir/subsubsubdir/subsubsubsubdir/why-does-this-remind-me-of-a-movie-title.cshtml\");\n            var objectFactory = Utils.AssignObjectFactoriesAndDisplayModeProvider(page, initPage);\n\n            // Act\n            var result = StartPage.GetStartPage(page, objectFactory, null, WebPageHttpHandler.StartPageFileName, new string[] { \"cshtml\", \"vbhtml\" });\n\n            // Assert\n            Assert.Equal(initPage, result);\n        }\n\n        [Fact]\n        public void GetStartPageUsesBothFileNamesAndExtensionsWhenDeterminingStartPage()\n        {\n            // Arrange\n            var subInitPage = Utils.CreateStartPage(null, \"~/subdir/_pagestart.jshtml\");\n            var initPage = Utils.CreateStartPage(null, \"~/_pagestart.vbhtml\");\n            var page = Utils.CreatePage(null, \"~/subdir/test.cshtml\");\n            var objectFactory = Utils.AssignObjectFactoriesAndDisplayModeProvider(page, initPage, subInitPage);\n\n            // Act\n            var result = StartPage.GetStartPage(page, objectFactory, null, WebPageHttpHandler.StartPageFileName, new string[] { \"cshtml\", \"vbhtml\" });\n\n            // Assert\n            Assert.Equal(initPage, result);\n        }\n\n        [Fact]\n        public void GetStartPage_ThrowsOnNullPage()\n        {\n            Assert.ThrowsArgumentNull(() => StartPage.GetStartPage(null, \"name\", new[] { \"cshtml\" }), \"page\");\n        }\n\n        [Fact]\n        public void GetStartPage_ThrowsOnNullFileName()\n        {\n            var page = Utils.CreatePage(p => p.Write(\"test\"));\n            Assert.ThrowsArgumentNullOrEmptyString(() => StartPage.GetStartPage(page, null, new[] { \"cshtml\" }), \"fileName\");\n        }\n\n        [Fact]\n        public void GetStartPage_ThrowsOnEmptyFileName()\n        {\n            var page = Utils.CreatePage(p => p.Write(\"test\"));\n            Assert.ThrowsArgumentNullOrEmptyString(() => StartPage.GetStartPage(page, String.Empty, new[] { \"cshtml\" }), \"fileName\");\n        }\n\n        [Fact]\n        public void GetStartPage_ThrowsOnNullSupportedExtensions()\n        {\n            var page = Utils.CreatePage(p => p.Write(\"test\"));\n            Assert.ThrowsArgumentNull(() => StartPage.GetStartPage(page, \"name\", null), \"supportedExtensions\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/TemplateStackTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class WebPageContextStackTest\n    {\n        [Fact]\n        public void GetCurrentContextReturnsNullWhenStackIsEmpty()\n        {\n            // Arrange\n            var httpContext = GetHttpContext();\n\n            // Act\n            var template = TemplateStack.GetCurrentTemplate(httpContext);\n\n            // Assert\n            Assert.Equal(1, httpContext.Items.Count);\n            Assert.Null(template);\n        }\n\n        [Fact]\n        public void GetCurrentContextReturnsCurrentContext()\n        {\n            // Arrange\n            var template = GetTemplateFile();\n            var httpContext = GetHttpContext();\n\n            // Act\n            TemplateStack.Push(httpContext, template);\n\n            // Assert\n            var currentTemplate = TemplateStack.GetCurrentTemplate(httpContext);\n            Assert.Equal(template, currentTemplate);\n        }\n\n        [Fact]\n        public void GetCurrentContextReturnsLastPushedContext()\n        {\n            // Arrange\n            var httpContext = GetHttpContext();\n            var template1 = GetTemplateFile(\"page1\");\n            var template2 = GetTemplateFile(\"page2\");\n\n            // Act\n            TemplateStack.Push(httpContext, template1);\n            TemplateStack.Push(httpContext, template2);\n\n            // Assert\n            var currentTemplate = TemplateStack.GetCurrentTemplate(httpContext);\n            Assert.Equal(template2, currentTemplate);\n        }\n\n        [Fact]\n        public void GetCurrentContextReturnsNullAfterPop()\n        {\n            // Arrange\n            var httpContext = GetHttpContext();\n            var template = GetTemplateFile();\n\n            // Act\n            TemplateStack.Push(httpContext, template);\n            TemplateStack.Pop(httpContext);\n\n            // Assert\n            Assert.Null(TemplateStack.GetCurrentTemplate(httpContext));\n        }\n\n        private static HttpContextBase GetHttpContext()\n        {\n            Mock<HttpContextBase> context = new Mock<HttpContextBase>();\n            context.Setup(c => c.Items).Returns(new Dictionary<object, object>());\n\n            return context.Object;\n        }\n\n        private static ITemplateFile GetTemplateFile(string path = null)\n        {\n            Mock<ITemplateFile> templateFile = new Mock<ITemplateFile>();\n            templateFile.Setup(f => f.TemplateInfo).Returns(new TemplateFileInfo(path));\n\n            return templateFile.Object;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/UrlDataTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Test\n{\n    public class UrlDataTest\n    {\n        [Fact]\n        public void UrlDataListConstructorTests()\n        {\n            Assert.NotNull(new UrlDataList(null));\n            Assert.NotNull(new UrlDataList(String.Empty));\n            Assert.NotNull(new UrlDataList(\"abc/foo\"));\n        }\n\n        [Fact]\n        public void AddTest()\n        {\n            var d = new UrlDataList(null);\n            var item = \"!!@#$#$\";\n            Assert.Throws<NotSupportedException>(() => { d.Add(item); }, \"The UrlData collection is read-only.\");\n        }\n\n        [Fact]\n        public void ClearTest()\n        {\n            var d = new UrlDataList(null);\n            Assert.Throws<NotSupportedException>(() => { d.Clear(); }, \"The UrlData collection is read-only.\");\n        }\n\n        [Fact]\n        public void IndexOfTest()\n        {\n            var item = \"!!@#$#$\";\n            var item2 = \"13l53125\";\n            var d = new UrlDataList(item + \"/\" + item2);\n            Assert.Equal(0, d.IndexOf(item));\n            Assert.Equal(1, d.IndexOf(item2));\n        }\n\n        [Fact]\n        public void InsertAtTest()\n        {\n            var d = new UrlDataList(\"x/y/z\");\n            Assert.Throws<NotSupportedException>(() => { d.Insert(1, \"a\"); }, \"The UrlData collection is read-only.\");\n        }\n\n        [Fact]\n        public void ContainsTest()\n        {\n            var item = \"!!@#$#$\";\n            var d = new UrlDataList(item);\n            Assert.Contains(item, d);\n        }\n\n        [Fact]\n        public void CopyToTest()\n        {\n            var d = new UrlDataList(\"x/y\");\n            string[] array = new string[2];\n            d.CopyTo(array, 0);\n            Assert.Equal(array[0], d[0]);\n            Assert.Equal(array[1], d[1]);\n        }\n\n        [Fact]\n        public void GetEnumeratorTest()\n        {\n            var d = new UrlDataList(\"x\");\n            var e = d.GetEnumerator();\n            e.MoveNext();\n            Assert.Equal(\"x\", e.Current);\n        }\n\n        [Fact]\n        public void RemoveTest()\n        {\n            var d = new UrlDataList(\"x\");\n            Assert.Throws<NotSupportedException>(() => { d.Remove(\"x\"); }, \"The UrlData collection is read-only.\");\n        }\n\n        [Fact]\n        public void RemoveAtTest()\n        {\n            var d = new UrlDataList(\"x/y\");\n            Assert.Throws<NotSupportedException>(() => { d.RemoveAt(0); }, \"The UrlData collection is read-only.\");\n        }\n\n        [Fact]\n        public void CountTest()\n        {\n            var d = new UrlDataList(\"x\");\n            Assert.Single(d);\n        }\n\n        [Fact]\n        public void IsReadOnlyTest()\n        {\n            var d = new UrlDataList(null);\n            Assert.True(d.IsReadOnly);\n        }\n\n        [Fact]\n        public void ItemTest()\n        {\n            var d = new UrlDataList(\"x/y\");\n            Assert.Equal(\"x\", d[0]);\n            Assert.Equal(\"y\", d[1]);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/Utils.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.IO;\nusing System.Reflection;\nusing System.Text;\nusing System.Web.Hosting;\nusing System.Web.WebPages.TestUtils;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public static class Utils\n    {\n        public static string RenderWebPage(WebPage page, StartPage startPage = null, HttpRequestBase request = null)\n        {\n            var writer = new StringWriter();\n\n            // Create an actual dummy HttpContext that has a request object\n            var filename = \"default.aspx\";\n            var url = \"http://localhost/default.aspx\";\n\n            request = request ?? CreateTestRequest(filename, url).Object;\n            var httpContext = CreateTestContext(request);\n\n            var pageContext = new WebPageContext { HttpContext = httpContext.Object };\n            page.ExecutePageHierarchy(pageContext, writer, startPage);\n            return writer.ToString();\n        }\n\n        public static Mock<HttpContextBase> CreateTestContext(HttpRequestBase request = null, HttpResponseBase response = null, IDictionary items = null)\n        {\n            items = items ?? new Hashtable();\n            request = request ?? CreateTestRequest(\"default.cshtml\", \"http://localhost/default.cshtml\").Object;\n\n            if (response == null)\n            {\n                var mockResponse = new Mock<HttpResponseBase>();\n                mockResponse.Setup(r => r.Cookies).Returns(new HttpCookieCollection());\n                response = mockResponse.Object;\n            }\n\n            var httpContext = new Mock<HttpContextBase>();\n            httpContext.SetupGet(c => c.Items).Returns(items);\n            httpContext.SetupGet(c => c.Request).Returns(request);\n            httpContext.SetupGet(c => c.Response).Returns(response);\n            return httpContext;\n        }\n\n        public static Mock<HttpRequestBase> CreateTestRequest(string filename, string url)\n        {\n            var mockRequest = new Mock<HttpRequestBase> { CallBase = true };\n            mockRequest.SetupGet(r => r.Path).Returns(filename);\n            mockRequest.SetupGet(r => r.RawUrl).Returns(url);\n            mockRequest.SetupGet(r => r.IsLocal).Returns(false);\n            mockRequest.SetupGet(r => r.QueryString).Returns(new NameValueCollection());\n            mockRequest.SetupGet(r => r.Browser.IsMobileDevice).Returns(false);\n            mockRequest.SetupGet(r => r.Cookies).Returns(new HttpCookieCollection());\n            mockRequest.SetupGet(r => r.UserAgent).Returns(String.Empty);\n\n            return mockRequest;\n        }\n\n        public static string RenderWebPage(Action<WebPage> pageExecuteAction, string pagePath = \"~/index.cshtml\")\n        {\n            var page = CreatePage(pageExecuteAction, pagePath);\n            return RenderWebPage(page);\n        }\n\n        public static MockPage CreatePage(Action<WebPage> pageExecuteAction, string pagePath = \"~/index.cshtml\")\n        {\n            var page = new MockPage()\n            {\n                VirtualPath = pagePath,\n                ExecuteAction = p => { pageExecuteAction(p); }\n            };\n            page.VirtualPathFactory = new HashVirtualPathFactory(page);\n            page.DisplayModeProvider = new DisplayModeProvider();\n            return page;\n        }\n\n        public static MockStartPage CreateStartPage(Action<StartPage> pageExecuteAction, string pagePath = \"~/_pagestart.cshtml\")\n        {\n            var page = new MockStartPage()\n            {\n                VirtualPath = pagePath,\n                ExecuteAction = p => { pageExecuteAction(p); }\n            };\n            page.VirtualPathFactory = new HashVirtualPathFactory(page);\n            page.DisplayModeProvider = new DisplayModeProvider();\n            return page;\n        }\n\n        public static string RenderWebPageWithSubPage(Action<WebPage> pageExecuteAction, Action<WebPage> subpageExecuteAction,\n                                                      string pagePath = \"~/index.cshtml\", string subpagePath = \"~/subpage.cshtml\")\n        {\n            var page = CreatePage(pageExecuteAction);\n            var subPage = CreatePage(subpageExecuteAction, subpagePath);\n            var virtualPathFactory = new HashVirtualPathFactory(page, subPage);\n            subPage.VirtualPathFactory = virtualPathFactory;\n            page.VirtualPathFactory = virtualPathFactory;\n            return RenderWebPage(page);\n        }\n\n        // E.g. \"default.aspx\", \"http://localhost/WebSite1/subfolder1/default.aspx\"\n\n        /// <summary>\n        /// Creates an instance of HttpContext and assigns it to HttpContext.Current. Ensure that the returned value is disposed at the end of the test.\n        /// </summary>\n        /// <returns>Returns an IDisposable that restores the original HttpContext.</returns>\n        internal static IDisposable CreateHttpContext(string filename, string url)\n        {\n            var request = new HttpRequest(filename, url, null);\n            var httpContext = new HttpContext(request, new HttpResponse(new StringWriter(new StringBuilder())));\n            HttpContext.Current = httpContext;\n\n            return new DisposableAction(RestoreHttpContext);\n        }\n\n        internal static void RestoreHttpContext()\n        {\n            HttpContext.Current = null;\n        }\n\n        internal static IDisposable CreateHttpRuntime(string appVPath)\n        {\n            return WebUtils.CreateHttpRuntime(appVPath);\n        }\n\n        public static void SetupVirtualPathInAppDomain(string vpath, string contents)\n        {\n            var file = new Mock<VirtualFile>(vpath);\n            file.Setup(f => f.Open()).Returns(new MemoryStream(ASCIIEncoding.Default.GetBytes(contents)));\n            var vpp = new Mock<VirtualPathProvider>();\n            vpp.Setup(p => p.FileExists(vpath)).Returns(true);\n            vpp.Setup(p => p.GetFile(vpath)).Returns(file.Object);\n            AppDomainUtils.SetAppData();\n            var env = new HostingEnvironment();\n\n            var register = typeof(HostingEnvironment).GetMethod(\"RegisterVirtualPathProviderInternal\", BindingFlags.Static | BindingFlags.NonPublic);\n            register.Invoke(null, new object[] { vpp.Object });\n        }\n\n        /// <summary>\n        /// Assigns a common object factory to the pages.\n        /// </summary>\n        internal static IVirtualPathFactory AssignObjectFactoriesAndDisplayModeProvider(params WebPageExecutingBase[] pages)\n        {\n            var objectFactory = new HashVirtualPathFactory(pages);\n            var displayModeProvider = new DisplayModeProvider();\n            foreach (var item in pages)\n            {\n                item.VirtualPathFactory = objectFactory;\n                var webPageRenderingBase = item as WebPageRenderingBase;\n                if (webPageRenderingBase != null)\n                {\n                    webPageRenderingBase.DisplayModeProvider = displayModeProvider;\n                }\n            }\n\n            return objectFactory;\n        }\n\n        internal static DisplayModeProvider AssignDisplayModeProvider(params WebPageRenderingBase[] pages)\n        {\n            var displayModeProvider = new DisplayModeProvider();\n            foreach (var item in pages)\n            {\n                item.DisplayModeProvider = displayModeProvider;\n            }\n            return displayModeProvider;\n        }\n    }\n\n    public class MockPageHelper\n    {\n        internal static string GetDirectory(string virtualPath)\n        {\n            var dir = Path.GetDirectoryName(virtualPath);\n            if (dir == \"~\")\n            {\n                return null;\n            }\n            return dir;\n        }\n    }\n\n    // This is a mock implementation of WebPage mainly to make the Render method work and\n    // generate a string.\n    // The Execute method simulates what is typically generated based on markup by the parsers.\n    public class MockPage : WebPage\n    {\n        public Action<WebPage> ExecuteAction { get; set; }\n\n        internal override string GetDirectory(string virtualPath)\n        {\n            return MockPageHelper.GetDirectory(virtualPath);\n        }\n\n        public override void Execute()\n        {\n            ExecuteAction(this);\n        }\n    }\n\n    public class MockStartPage : StartPage\n    {\n        public Action<StartPage> ExecuteAction { get; set; }\n\n        internal override string GetDirectory(string virtualPath)\n        {\n            return MockPageHelper.GetDirectory(virtualPath);\n        }\n\n        public override void Execute()\n        {\n            ExecuteAction(this);\n        }\n\n        public Dictionary<string, object> CombinedPageInstances\n        {\n            get\n            {\n                var combinedInstances = new Dictionary<string, object>();\n                var instances = new Dictionary<string, object>();\n                WebPageRenderingBase childPage = this;\n                while (childPage != null)\n                {\n                    if (childPage is MockStartPage)\n                    {\n                        var initPage = childPage as MockStartPage;\n                        childPage = initPage.ChildPage;\n                    }\n                    else if (childPage is MockPage)\n                    {\n                        childPage = null;\n                    }\n                    foreach (var kvp in instances)\n                    {\n                        combinedInstances.Add(kvp.Key, kvp.Value);\n                    }\n                }\n                return combinedInstances;\n            }\n        }\n    }\n\n    public class MockHttpRuntime\n    {\n        public static Version RequestValidationMode { get; set; }\n    }\n\n    public class MockHttpApplication\n    {\n        public static Type ModuleType { get; set; }\n\n        public static void RegisterModule(Type moduleType)\n        {\n            ModuleType = moduleType;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/VirtualPathFactoryExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class VirtualPathFactoryExtensionsTest\n    {\n        [Fact]\n        public void VirtualPathFactoryExtensionsSpecialCasesVirtualPathFactoryManager()\n        {\n            // Arrange\n            var virtualPath = \"~/index.cshtml\";\n            var mockPage = Utils.CreatePage(_ => { }, virtualPath);\n            var factory = new Mock<IVirtualPathFactory>();\n            factory.Setup(c => c.Exists(virtualPath)).Returns(true).Verifiable();\n            factory.Setup(c => c.CreateInstance(virtualPath)).Returns(mockPage);\n\n            // Act\n            var factoryManager = new VirtualPathFactoryManager(factory.Object);\n            var page = factoryManager.CreateInstance<WebPageBase>(virtualPath);\n\n            // Assert\n            Assert.Equal(mockPage, page);\n            factory.Verify();\n        }\n\n        [Fact]\n        public void GenericCreateInstanceLoopsOverAllRegisteredFactories()\n        {\n            // Arrange\n            var virtualPath = \"~/index.cshtml\";\n            var mockPage = Utils.CreatePage(_ => { }, virtualPath);\n            var factory1 = new HashVirtualPathFactory(mockPage);\n            var factory2 = new HashVirtualPathFactory(Utils.CreatePage(null, \"~/_admin/index.cshtml\"));\n\n            // Act\n            var factoryManager = new VirtualPathFactoryManager(factory2);\n            factoryManager.RegisterVirtualPathFactoryInternal(factory1);\n            var page = factoryManager.CreateInstance<WebPageBase>(virtualPath);\n\n            // Assert\n            Assert.Equal(mockPage, page);\n        }\n\n        [Fact]\n        public void GenericCreateInstanceReturnsNullIfNoFactoryCanCreateVirtualPath()\n        {\n            // Arrange\n            var factory1 = new HashVirtualPathFactory(Utils.CreatePage(_ => { }, \"~/index.cshtml\"));\n            var factory2 = new HashVirtualPathFactory(Utils.CreatePage(null, \"~/_admin/index.cshtml\"));\n\n            // Act\n            var factoryManager = new VirtualPathFactoryManager(factory2);\n            factoryManager.RegisterVirtualPathFactoryInternal(factory1);\n            var page = factoryManager.CreateInstance<WebPageBase>(\"~/does-not-exist.cshtml\");\n\n            // Assert\n            Assert.Null(page);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/VirtualPathFactoryManagerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class VirtualPathFactoryManagerTest\n    {\n        [Fact]\n        public void DefaultFactoryIsListedInRegisteredFactories()\n        {\n            // Arrange\n            var factory = new HashVirtualPathFactory();\n\n            // Act\n            var factoryManager = new VirtualPathFactoryManager(factory);\n\n            // Assert\n            Assert.Equal(factory, factoryManager.RegisteredFactories.Single());\n        }\n\n        [Fact]\n        public void RegisterFactoryEnsuresDefaultFactoryRemainsTheLast()\n        {\n            // Arrange\n            var defaultFactory = new HashVirtualPathFactory();\n            var factory1 = new HashVirtualPathFactory();\n            var factory2 = new HashVirtualPathFactory();\n            var factory3 = new HashVirtualPathFactory();\n\n            // Act\n            var factoryManager = new VirtualPathFactoryManager(defaultFactory);\n            factoryManager.RegisterVirtualPathFactoryInternal(factory1);\n            factoryManager.RegisterVirtualPathFactoryInternal(factory2);\n            factoryManager.RegisterVirtualPathFactoryInternal(factory3);\n\n            // Assert\n            Assert.Equal(factory1, factoryManager.RegisteredFactories.ElementAt(0));\n            Assert.Equal(factory2, factoryManager.RegisteredFactories.ElementAt(1));\n            Assert.Equal(factory3, factoryManager.RegisteredFactories.ElementAt(2));\n            Assert.Equal(defaultFactory, factoryManager.RegisteredFactories.Last());\n        }\n\n        [Fact]\n        public void CreateInstanceUsesRegisteredFactoriesForExistence()\n        {\n            // Arrange\n            var path = \"~/index.cshtml\";\n            var factory1 = new Mock<IVirtualPathFactory>();\n            factory1.Setup(c => c.Exists(path)).Returns(false).Verifiable();\n            var factory2 = new Mock<IVirtualPathFactory>();\n            factory2.Setup(c => c.Exists(path)).Returns(true).Verifiable();\n            var factory3 = new Mock<IVirtualPathFactory>();\n            factory3.Setup(c => c.Exists(path)).Throws(new Exception(\"This factory should not be called since the page has already been found in 2\"));\n            var defaultFactory = new Mock<IVirtualPathFactory>();\n            defaultFactory.Setup(c => c.Exists(path)).Throws(new Exception(\"This factory should not be called since it always called last\"));\n\n            var vpfm = new VirtualPathFactoryManager(defaultFactory.Object);\n            vpfm.RegisterVirtualPathFactoryInternal(factory1.Object);\n            vpfm.RegisterVirtualPathFactoryInternal(factory2.Object);\n            vpfm.RegisterVirtualPathFactoryInternal(factory3.Object);\n\n            // Act\n            var result = vpfm.Exists(path);\n\n            // Assert\n            Assert.True(result);\n\n            factory1.Verify();\n            factory2.Verify();\n        }\n\n        [Fact]\n        public void CreateInstanceLooksThroughAllRegisteredFactoriesForExistence()\n        {\n            // Arrange\n            var page = Utils.CreatePage(null);\n            var factory1 = new Mock<IVirtualPathFactory>();\n            factory1.Setup(c => c.Exists(page.VirtualPath)).Returns(false).Verifiable();\n            var factory2 = new Mock<IVirtualPathFactory>();\n            factory2.Setup(c => c.Exists(page.VirtualPath)).Returns(true).Verifiable();\n            factory2.Setup(c => c.CreateInstance(page.VirtualPath)).Returns(page).Verifiable();\n            var factory3 = new Mock<IVirtualPathFactory>();\n            factory3.Setup(c => c.Exists(page.VirtualPath)).Throws(new Exception(\"This factory should not be called since the page has already been found in 2\"));\n            var defaultFactory = new Mock<IVirtualPathFactory>();\n            defaultFactory.Setup(c => c.Exists(page.VirtualPath)).Throws(new Exception(\"This factory should not be called since it always called last\"));\n\n            var vpfm = new VirtualPathFactoryManager(defaultFactory.Object);\n            vpfm.RegisterVirtualPathFactoryInternal(factory1.Object);\n            vpfm.RegisterVirtualPathFactoryInternal(factory2.Object);\n            vpfm.RegisterVirtualPathFactoryInternal(factory3.Object);\n\n            // Act\n            var result = vpfm.CreateInstance(page.VirtualPath);\n\n            // Assert\n            Assert.Equal(page, result);\n\n            factory1.Verify();\n            factory2.Verify();\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/WebPageContextTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing System.IO;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class WebPageContextTest\n    {\n        [Fact]\n        public void CreateNestedPageContextCopiesPropertiesFromParentPageContext()\n        {\n            // Arrange\n            var httpContext = new Mock<HttpContextBase>();\n            var pageDataDictionary = new Dictionary<object, dynamic>();\n            var model = new { Hello = \"World\" };\n            Action<TextWriter> bodyAction = writer => { };\n            var sectionWritersStack = new Stack<Dictionary<string, SectionWriter>>();\n            var basePageContext = new WebPageContext(httpContext.Object, null, null) { BodyAction = bodyAction, SectionWritersStack = sectionWritersStack };\n\n            // Act\n            var subPageContext = WebPageContext.CreateNestedPageContext(basePageContext, pageDataDictionary, model, isLayoutPage: false);\n\n            // Assert\n            Assert.Equal(basePageContext.HttpContext, subPageContext.HttpContext);\n            Assert.Equal(basePageContext.OutputStack, subPageContext.OutputStack);\n            Assert.Equal(basePageContext.Validation, subPageContext.Validation);\n            Assert.Equal(basePageContext.ModelState, subPageContext.ModelState);\n            Assert.Equal(pageDataDictionary, subPageContext.PageData);\n            Assert.Equal(model, subPageContext.Model);\n            Assert.Null(subPageContext.BodyAction);\n        }\n\n        [Fact]\n        public void CreateNestedPageCopiesBodyActionAndSectionWritersWithOtherPropertiesFromParentPageContext()\n        {\n            // Arrange\n            var httpContext = new Mock<HttpContextBase>();\n            var pageDataDictionary = new Dictionary<object, dynamic>();\n            var model = new { Hello = \"World\" };\n            Action<TextWriter> bodyAction = writer => { };\n            var sectionWritersStack = new Stack<Dictionary<string, SectionWriter>>();\n            var basePageContext = new WebPageContext(httpContext.Object, null, null) { BodyAction = bodyAction, SectionWritersStack = sectionWritersStack };\n\n            // Act\n            var subPageContext = WebPageContext.CreateNestedPageContext(basePageContext, pageDataDictionary, model, isLayoutPage: true);\n\n            // Assert\n            Assert.Equal(basePageContext.HttpContext, subPageContext.HttpContext);\n            Assert.Equal(basePageContext.OutputStack, subPageContext.OutputStack);\n            Assert.Equal(basePageContext.Validation, subPageContext.Validation);\n            Assert.Equal(basePageContext.ModelState, subPageContext.ModelState);\n            Assert.Equal(pageDataDictionary, subPageContext.PageData);\n            Assert.Equal(model, subPageContext.Model);\n            Assert.Equal(sectionWritersStack, subPageContext.SectionWritersStack);\n            Assert.Equal(bodyAction, subPageContext.BodyAction);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/WebPageExecutingBaseTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.IO;\nusing System.Text;\nusing System.Web.WebPages.Instrumentation;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class WebPageExecutingBaseTest\n    {\n        [Fact]\n        public void NormalizeLayoutPageUsesVirtualPathFactoryManagerToDetermineIfLayoutFileExists()\n        {\n            // Arrange\n            var layoutPagePath = \"~/sitelayout.cshtml\";\n            var layoutPage = Utils.CreatePage(null, layoutPagePath);\n            var page = Utils.CreatePage(null);\n            var objectFactory = new Mock<IVirtualPathFactory>();\n            objectFactory.Setup(c => c.Exists(It.Is<string>(p => p.Equals(layoutPagePath)))).Returns(true).Verifiable();\n            page.VirtualPathFactory = objectFactory.Object;\n\n            // Act\n            var path = page.NormalizeLayoutPagePath(layoutPage.VirtualPath);\n\n            // Assert\n            objectFactory.Verify();\n            Assert.Equal(path, layoutPage.VirtualPath);\n        }\n\n        [Fact]\n        public void NormalizeLayoutPageAcceptsRelativePathsToLayoutPage()\n        {\n            // Arrange\n            var page = Utils.CreatePage(null, \"~/dir/default.cshtml\");\n            var layoutPage = Utils.CreatePage(null, \"~/layouts/sitelayout.cshtml\");\n            var objectFactory = new HashVirtualPathFactory(page, layoutPage);\n            page.VirtualPathFactory = objectFactory;\n\n            // Act\n            var path = page.NormalizeLayoutPagePath(@\"../layouts/sitelayout.cshtml\");\n\n            // Assert\n            Assert.Equal(path, layoutPage.VirtualPath);\n        }\n\n        [Fact]\n        public void BeginContextSilentlyFailsIfInstrumentationIsNotAvailable()\n        {\n            // Arrange\n            bool called = false;\n\n            var pageMock = new Mock<WebPageExecutingBase>() { CallBase = true };\n            pageMock.Setup(p => p.Context).Returns(new Mock<HttpContextBase>().Object);\n            pageMock.Object.InstrumentationService.IsAvailable = false;\n            pageMock.Object.InstrumentationService.ExtractInstrumentationService = c =>\n            {\n                called = true;\n                return null;\n            };\n\n            // Act\n            pageMock.Object.BeginContext(\"~/dir/default.cshtml\", 0, 1, true);\n\n            // Assert\n            Assert.False(called);\n        }\n\n        [Fact]\n        public void EndContextSilentlyFailsIfInstrumentationIsNotAvailable()\n        {\n            // Arrange\n            bool called = false;\n\n            var pageMock = new Mock<WebPageExecutingBase>() { CallBase = true };\n            pageMock.Setup(p => p.Context).Returns(new Mock<HttpContextBase>().Object);\n            pageMock.Object.InstrumentationService.IsAvailable = false;\n            pageMock.Object.InstrumentationService.ExtractInstrumentationService = c =>\n            {\n                called = true;\n                return null;\n            };\n\n            // Act\n            pageMock.Object.EndContext(\"~/dir/default.cshtml\", 0, 1, true);\n\n            // Assert\n            Assert.False(called);\n        }\n\n        [Fact]\n        public void WriteAttributeToWritesAttributeNormallyIfNoValuesSpecified()\n        {\n            WriteAttributeTest(\n                name: \"alt\",\n                prefix: new PositionTagged<string>(\" alt=\\\"\", 42),\n                suffix: new PositionTagged<string>(\"\\\"\", 24),\n                expected: \" alt=\\\"\\\"\");\n        }\n\n        [Fact]\n        public void WriteAttributeToWritesNothingIfSingleNullValueProvided()\n        {\n            WriteAttributeTest(\n                name: \"alt\",\n                prefix: new PositionTagged<string>(\" alt=\\\"\", 42),\n                suffix: new PositionTagged<string>(\"\\\"\", 24),\n                values: new[] {\n                    new AttributeValue(new PositionTagged<string>(String.Empty, 142), new PositionTagged<object>(null, 124), literal: true)\n                },\n                expected: \"\");\n        }\n\n        [Fact]\n        public void WriteAttributeToWritesNothingIfSingleFalseValueProvided()\n        {\n            WriteAttributeTest(\n                name: \"alt\",\n                prefix: new PositionTagged<string>(\" alt=\\\"\", 42),\n                suffix: new PositionTagged<string>(\"\\\"\", 24),\n                values: new[] {\n                    new AttributeValue(new PositionTagged<string>(String.Empty, 142), new PositionTagged<object>(false, 124), literal: true)\n                },\n                expected: \"\");\n        }\n\n        [Fact]\n        public void WriteAttributeToWritesGlobalPrefixIfSingleValueProvided()\n        {\n            WriteAttributeTest(\n                name: \"alt\",\n                prefix: new PositionTagged<string>(\" alt=\\\"\", 42),\n                suffix: new PositionTagged<string>(\"\\\"\", 24),\n                values: new[] {\n                    new AttributeValue(new PositionTagged<string>(\"    \", 142), new PositionTagged<object>(\"foo\", 124), literal: true)\n                },\n                expected: \" alt=\\\"foo\\\"\");\n        }\n\n        [Fact]\n        public void WriteAttributeToWritesLocalPrefixForSecondValueProvided()\n        {\n            WriteAttributeTest(\n                name: \"alt\",\n                prefix: new PositionTagged<string>(\" alt=\\\"\", 42),\n                suffix: new PositionTagged<string>(\"\\\"\", 24),\n                values: new[] {\n                    new AttributeValue(new PositionTagged<string>(\"    \", 142), new PositionTagged<object>(\"foo\", 124), literal: true),\n                    new AttributeValue(new PositionTagged<string>(\"glorb\", 142), new PositionTagged<object>(\"bar\", 124), literal: true)\n                },\n                expected: \" alt=\\\"fooglorbbar\\\"\");\n        }\n\n        [Fact]\n        public void WriteAttributeToWritesGlobalPrefixOnlyIfSecondValueIsFirstNonNullOrFalse()\n        {\n            WriteAttributeTest(\n                name: \"alt\",\n                prefix: new PositionTagged<string>(\" alt=\\\"\", 42),\n                suffix: new PositionTagged<string>(\"\\\"\", 24),\n                values: new[] {\n                    new AttributeValue(new PositionTagged<string>(\"    \", 142), new PositionTagged<object>(null, 124), literal: true),\n                    new AttributeValue(new PositionTagged<string>(\"glorb\", 142), new PositionTagged<object>(\"bar\", 124), literal: true)\n                },\n                expected: \" alt=\\\"bar\\\"\");\n        }\n\n        /// <remarks>\n        /// This is a regression test for Html.Raw behaving incorrectly in attributes - the code here is derived from that generated\n        /// by the Razor engine on input like the following:\n        /// \n        /// cool=\"@Html.Raw(\"this is cool text\")\"\n        /// </remarks>\n        [Fact]\n        public void WriteAttributeWithRawHtmlString()\n        {\n            string alreadyEncoded = \"Show Size 6½-8\";\n            WriteAttributeTest(\n                name: \"alt\",\n                prefix: new PositionTagged<string>(\" cool=\\\"\", 33),\n                suffix: new PositionTagged<string>(\"\\\"\", 70),\n                values: new[] {\n                    AttributeValue.FromTuple(Tuple.Create(Tuple.Create(\"\", 40), Tuple.Create<Object, Int32>(new HtmlString(alreadyEncoded), 40), false)), \n                },\n                expected: \" cool=\\\"\" + alreadyEncoded + \"\\\"\");\n        }\n\n        private void WriteAttributeTest(string name, PositionTagged<string> prefix, PositionTagged<string> suffix, string expected)\n        {\n            WriteAttributeTest(name, prefix, suffix, new AttributeValue[0], expected);\n        }\n\n        private void WriteAttributeTest(string name, PositionTagged<string> prefix, PositionTagged<string> suffix, AttributeValue[] values, string expected)\n        {\n            // Arrange\n            var pageMock = new Mock<WebPageExecutingBase>() { CallBase = true };\n            pageMock.Setup(p => p.Context).Returns(new Mock<HttpContextBase>().Object);\n            pageMock.Object.InstrumentationService.IsAvailable = false;\n\n            StringBuilder written = new StringBuilder();\n            StringWriter writer = new StringWriter(written);\n\n            // Act\n            pageMock.Object.WriteAttributeTo(writer, name, prefix, suffix, values);\n\n            // Assert\n            Assert.Equal(expected, written.ToString());\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/WebPageHttpHandlerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Specialized;\nusing System.IO;\nusing System.Security;\nusing System.Text;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class WebPageHttpHandlerTest\n    {\n        [Fact]\n        public void ConstructorThrowsWithNullPage()\n        {\n            Assert.ThrowsArgumentNull(() => new WebPageHttpHandler(null), \"webPage\");\n        }\n\n        [Fact]\n        public void IsReusableTest()\n        {\n            WebPage dummyPage = new DummyPage();\n            Assert.False(new WebPageHttpHandler(dummyPage).IsReusable);\n        }\n\n        [Fact]\n        public void ProcessRequestTest()\n        {\n            var contents = \"test\";\n            var tw = new StringWriter(new StringBuilder());\n            var httpContext = CreateTestContext(tw);\n            var page = Utils.CreatePage(p => p.Write(contents));\n            new WebPageHttpHandler(page).ProcessRequestInternal(httpContext);\n            Assert.Equal(contents, tw.ToString());\n        }\n\n        [Fact]\n        public void SourceFileHeaderTest()\n        {\n            // Arrange\n            var contents = \"test\";\n            var writer = new StringWriter();\n\n            Mock<HttpResponseBase> httpResponse = new Mock<HttpResponseBase>();\n            httpResponse.SetupGet(r => r.Output).Returns(writer);\n            Mock<HttpRequestBase> httpRequest = Utils.CreateTestRequest(\"~/index.cshtml\", \"~/index.cshtml\");\n            httpRequest.SetupGet(r => r.IsLocal).Returns(true);\n            httpRequest.Setup(r => r.MapPath(It.IsAny<string>())).Returns<string>(p => p);\n            Mock<HttpContextBase> context = Utils.CreateTestContext(httpRequest.Object, httpResponse.Object);\n            var page = Utils.CreatePage(p => p.Write(contents));\n\n            // Act\n            var webPageHttpHandler = new WebPageHttpHandler(page);\n            webPageHttpHandler.ProcessRequestInternal(context.Object);\n\n            // Assert\n            Assert.Equal(contents, writer.ToString());\n            Assert.Single(page.PageContext.SourceFiles);\n            Assert.Contains(\"~/index.cshtml\", page.PageContext.SourceFiles);\n        }\n\n        [Fact]\n        public void GenerateSourceFilesHeaderGenerates2047EncodedValue()\n        {\n            // Arrange\n            string headerKey = null, headerValue = null;\n            var context = new Mock<HttpContextBase>();\n            var response = new Mock<HttpResponseBase>();\n            response.Setup(c => c.AddHeader(It.IsAny<string>(), It.IsAny<string>())).Callback(\n                (string key, string value) =>\n                {\n                    headerKey = key;\n                    headerValue = value;\n                });\n            context.Setup(c => c.Response).Returns(response.Object);\n            context.Setup(c => c.Items).Returns(new Hashtable());\n\n            var webPageContext = new WebPageContext(context.Object, page: null, model: null);\n            webPageContext.SourceFiles.Add(\"foo\");\n            webPageContext.SourceFiles.Add(\"bar\");\n            webPageContext.SourceFiles.Add(\"λ\");\n\n            // Act\n            WebPageHttpHandler.GenerateSourceFilesHeader(webPageContext);\n\n            // Assert\n            Assert.Equal(\"X-SourceFiles\", headerKey);\n            Assert.Equal(\"=?UTF-8?B?Zm9vfGJhcnzOuw==?=\", headerValue);\n        }\n\n        [Fact]\n        public void HttpHandlerGeneratesSourceFilesHeadersIfRequestIsLocal()\n        {\n            // Arrange\n            string pagePath = \"~/index.cshtml\", layoutPath = \"~/Layout.cshtml\", layoutPageName = \"Layout.cshtml\";\n            var page = Utils.CreatePage(p => { p.Layout = layoutPageName; }, pagePath);\n            var layoutPage = Utils.CreatePage(p => { p.RenderBody(); }, layoutPath);\n            Utils.AssignObjectFactoriesAndDisplayModeProvider(layoutPage, page);\n\n\n            var headers = new NameValueCollection();\n            var request = Utils.CreateTestRequest(pagePath, pagePath);\n            request.Setup(c => c.IsLocal).Returns(true);\n            request.Setup(c => c.MapPath(It.IsAny<string>())).Returns<string>(path => path);\n            request.Setup(c => c.Cookies).Returns(new HttpCookieCollection());\n\n            var response = new Mock<HttpResponseBase>() { CallBase = true };\n            response.SetupGet(r => r.Headers).Returns(headers);\n            response.SetupGet(r => r.Output).Returns(TextWriter.Null);\n            response.Setup(r => r.AppendHeader(It.IsAny<string>(), It.IsAny<string>())).Callback<string, string>((name, value) => headers.Add(name, value));\n            response.Setup(r => r.AddHeader(It.IsAny<string>(), It.IsAny<string>())).Callback<string, string>((name, value) => headers.Add(name, value));\n            response.Setup(r => r.Cookies).Returns(new HttpCookieCollection());\n\n            var context = Utils.CreateTestContext(request.Object, response.Object);\n\n            // Act\n            var webPageHttpHandler = new WebPageHttpHandler(page);\n            webPageHttpHandler.ProcessRequestInternal(context.Object);\n\n            // Assert\n            Assert.Equal(LatestRazorVersion.MajorMinor, headers[WebPageHttpHandler.WebPagesVersionHeaderName]);\n            Assert.Equal(\"=?UTF-8?B?fi9pbmRleC5jc2h0bWx8fi9MYXlvdXQuY3NodG1s?=\", headers[\"X-SourceFiles\"]);\n        }\n\n        [Fact]\n        public void ExceptionTest()\n        {\n            var contents = \"test\";\n            var httpContext = Utils.CreateTestContext().Object;\n            var page = Utils.CreatePage(p => { throw new InvalidOperationException(contents); });\n            var e = Assert.Throws<HttpUnhandledException>(\n                () => new WebPageHttpHandler(page).ProcessRequestInternal(httpContext)\n            );\n            Assert.IsType<InvalidOperationException>(e.InnerException);\n            Assert.Equal(contents, e.InnerException.Message, StringComparer.Ordinal);\n        }\n\n        [Fact]\n        public void SecurityExceptionTest()\n        {\n            var contents = \"test\";\n            var httpContext = Utils.CreateTestContext().Object;\n            var page = Utils.CreatePage(p => { throw new SecurityException(contents); });\n            Assert.Throws<SecurityException>(\n                () => new WebPageHttpHandler(page).ProcessRequestInternal(httpContext),\n                contents);\n        }\n\n        [Fact]\n        public void CreateFromVirtualPathTest()\n        {\n            var contents = \"test\";\n            var textWriter = new StringWriter();\n\n            var httpResponse = new Mock<HttpResponseBase>();\n            httpResponse.SetupGet(r => r.Output).Returns(textWriter);\n            var httpContext = Utils.CreateTestContext(response: httpResponse.Object);\n            var mockBuildManager = new Mock<IVirtualPathFactory>();\n            var virtualPath = \"~/hello/test.cshtml\";\n            var page = Utils.CreatePage(p => p.Write(contents));\n            mockBuildManager.Setup(c => c.Exists(It.Is<string>(p => p.Equals(virtualPath)))).Returns<string>(_ => true).Verifiable();\n            mockBuildManager.Setup(c => c.CreateInstance(It.Is<string>(p => p.Equals(virtualPath)))).Returns(page).Verifiable();\n\n            // Act\n            IHttpHandler handler = WebPageHttpHandler.CreateFromVirtualPath(virtualPath, new VirtualPathFactoryManager(mockBuildManager.Object));\n            WebPageHttpHandler webPageHttpHandler = Assert.IsType<WebPageHttpHandler>(handler);\n            webPageHttpHandler.ProcessRequestInternal(httpContext.Object);\n\n            // Assert\n            Assert.Equal(contents, textWriter.ToString());\n            mockBuildManager.Verify();\n        }\n\n        [Fact]\n        public void VersionHeaderTest()\n        {\n            Mock<HttpResponseBase> mockResponse = new Mock<HttpResponseBase>();\n            mockResponse.Setup(response => response.AppendHeader(\"X-AspNetWebPages-Version\", LatestRazorVersion.MajorMinor)).Verifiable();\n\n            Mock<HttpContextBase> mockContext = new Mock<HttpContextBase>();\n            mockContext.SetupGet(context => context.Response).Returns(mockResponse.Object);\n\n            WebPageHttpHandler.AddVersionHeader(mockContext.Object);\n            mockResponse.Verify();\n        }\n\n        [Fact]\n        public void CreateFromVirtualPathNonWebPageTest()\n        {\n            // Arrange\n            var virtualPath = \"~/hello/test.cshtml\";\n            var handler = new WebPageHttpHandler(new DummyPage());\n            var mockBuildManager = new Mock<IVirtualPathFactory>();\n            mockBuildManager.Setup(c => c.CreateInstance(It.IsAny<string>())).Returns(handler);\n            mockBuildManager.Setup(c => c.Exists(It.Is<string>(p => p.Equals(virtualPath)))).Returns<string>(_ => true).Verifiable();\n\n            // Act\n            var result = WebPageHttpHandler.CreateFromVirtualPath(virtualPath, new VirtualPathFactoryManager(mockBuildManager.Object));\n\n            // Assert\n            Assert.Equal(handler, result);\n            mockBuildManager.Verify();\n        }\n\n        [Fact]\n        public void CreateFromVirtualPathReturnsIHttpHandlerIfItCannotCreateAWebPageType()\n        {\n            // Arrange\n            var pageVirtualPath = \"~/hello/test.cshtml\";\n            var handlerVirtualPath = \"~/handler.asmx\";\n            var page = new DummyPage();\n            var handler = new Mock<IHttpHandler>().Object;\n            var mockFactory = new Mock<IVirtualPathFactory>();\n            mockFactory.Setup(c => c.Exists(It.IsAny<string>())).Returns(true);\n            mockFactory.Setup(c => c.CreateInstance(pageVirtualPath)).Returns(page);\n            mockFactory.Setup(c => c.CreateInstance(handlerVirtualPath)).Returns(handler);\n\n            // Act\n            var handlerResult = WebPageHttpHandler.CreateFromVirtualPath(handlerVirtualPath, mockFactory.Object);\n            var pageResult = WebPageHttpHandler.CreateFromVirtualPath(pageVirtualPath, mockFactory.Object);\n\n            // Assert\n            Assert.Equal(handler, handlerResult);\n            Assert.NotNull(pageResult as WebPageHttpHandler);\n        }\n\n        private static HttpContextBase CreateTestContext(TextWriter textWriter)\n        {\n            var filename = \"default.aspx\";\n            var url = \"http://localhost/WebSite1/subfolder1/default.aspx\";\n            var request = Utils.CreateTestRequest(filename, url);\n\n            var response = new Mock<HttpResponseBase>();\n            response.SetupGet(r => r.Output).Returns(textWriter);\n\n            return Utils.CreateTestContext(request: request.Object, response: response.Object).Object;\n        }\n\n        private sealed class DummyPage : WebPage\n        {\n            public override void Execute()\n            {\n            }\n        }\n    }\n}"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/WebPageHttpModuleTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\n\nnamespace System.Web.WebPages.Test\n{\n    public class WebPageHttpModuleTest\n    {\n        [Fact]\n        public void InitializeApplicationTest()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                var moduleEvents = new ModuleEvents();\n                var app = new MyHttpApplication();\n                WebPageHttpModule.InitializeApplication(app,\n                                                        moduleEvents.OnApplicationPostResolveRequestCache,\n                                                        moduleEvents.Initialize);\n                Assert.True(moduleEvents.CalledInitialize);\n            });\n        }\n\n        [Fact]\n        public void StartApplicationTest()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                var moduleEvents = new ModuleEvents();\n                var app = new MyHttpApplication();\n                WebPageHttpModule.StartApplication(app, moduleEvents.ExecuteStartPage, moduleEvents.ApplicationStart);\n                Assert.Equal(1, moduleEvents.CalledExecuteStartPage);\n                Assert.Equal(1, moduleEvents.CalledApplicationStart);\n\n                // Call a second time to make sure the methods are only called once\n                WebPageHttpModule.StartApplication(app, moduleEvents.ExecuteStartPage, moduleEvents.ApplicationStart);\n                Assert.Equal(1, moduleEvents.CalledExecuteStartPage);\n                Assert.Equal(1, moduleEvents.CalledApplicationStart);\n            });\n        }\n\n        public class MyHttpApplication : HttpApplication\n        {\n            public MyHttpApplication()\n            {\n            }\n        }\n\n        public class ModuleEvents\n        {\n            public void OnApplicationPostResolveRequestCache(object sender, EventArgs e)\n            {\n            }\n\n            public void OnBeginRequest(object sender, EventArgs e)\n            {\n            }\n\n            public void OnEndRequest(object sender, EventArgs e)\n            {\n            }\n\n            public bool CalledInitialize;\n\n            public void Initialize(object sender, EventArgs e)\n            {\n                CalledInitialize = true;\n            }\n\n            public int CalledExecuteStartPage;\n\n            public void ExecuteStartPage(HttpApplication application)\n            {\n                CalledExecuteStartPage++;\n            }\n\n            public int CalledApplicationStart;\n\n            public void ApplicationStart(object sender, EventArgs e)\n            {\n                CalledApplicationStart++;\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/WebPageRenderingBaseTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class WebPageRenderingBaseTest\n    {\n        [Fact]\n        public void SetCultureThrowsIfValueIsNull()\n        {\n            // Arrange\n            string value = null;\n            var webPageRenderingBase = new Mock<WebPageRenderingBase>() { CallBase = true }.Object;\n\n            // Act and Assert\n            Assert.ThrowsArgumentNullOrEmptyString(() => webPageRenderingBase.Culture = value, \"value\");\n        }\n\n        [Fact]\n        public void SetCultureThrowsIfValueIsEmpty()\n        {\n            // Arrange\n            string value = String.Empty;\n            var webPageRenderingBase = new Mock<WebPageRenderingBase>() { CallBase = true }.Object;\n\n            // Act and Assert\n            Assert.ThrowsArgumentNullOrEmptyString(() => webPageRenderingBase.Culture = value, \"value\");\n        }\n\n        [Fact]\n        public void SetUICultureThrowsIfValueIsNull()\n        {\n            // Arrange\n            string value = null;\n            var webPageRenderingBase = new Mock<WebPageRenderingBase>() { CallBase = true }.Object;\n\n            // Act and Assert\n            Assert.ThrowsArgumentNullOrEmptyString(() => webPageRenderingBase.UICulture = value, \"value\");\n        }\n\n        [Fact]\n        public void SetUICultureThrowsIfValueIsEmpty()\n        {\n            // Arrange\n            string value = String.Empty;\n            var webPageRenderingBase = new Mock<WebPageRenderingBase>() { CallBase = true }.Object;\n\n            // Act and Assert\n            Assert.ThrowsArgumentNullOrEmptyString(() => webPageRenderingBase.UICulture = value, \"value\");\n        }\n\n        [Fact]\n        public void DisplayModePropertyWithNullContext()\n        {\n            // Arrange\n            var context = new Mock<HttpContextBase>();\n            var displayMode = new DefaultDisplayMode(\"test\");\n            var webPageRenderingBase = new Mock<WebPageRenderingBase>() { CallBase = true };\n\n            // Act & Assert\n            Assert.Null(webPageRenderingBase.Object.DisplayMode);\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/WebPageRouteTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class WebPageRouteTest\n    {\n        private class HashyBuildManager : IVirtualPathFactory\n        {\n            private readonly HashSet<string> _existingFiles;\n\n            public HashyBuildManager(IEnumerable<string> validFilePaths)\n            {\n                _existingFiles = new HashSet<string>(validFilePaths, StringComparer.InvariantCultureIgnoreCase);\n            }\n\n            public bool Exists(string virtualPath)\n            {\n                return _existingFiles.Contains(virtualPath);\n            }\n\n            public object CreateInstance(string virtualPath)\n            {\n                throw new NotSupportedException();\n            }\n        }\n\n        // Helper to test smarty route match, null match string is used for no expected match\n        private static void ConstraintTest(IEnumerable<string> validFiles, IEnumerable<string> supportedExt, string url, string match, string pathInfo, bool mobileDevice = false)\n        {\n            var objectFactory = new HashyBuildManager(validFiles);\n            var mockContext = new Mock<HttpContextBase>();\n            mockContext.Setup(context => context.Items).Returns(new Hashtable());\n            mockContext.Setup(c => c.Request.Browser.IsMobileDevice).Returns(mobileDevice);\n            mockContext.Setup(c => c.Request.Cookies).Returns(new HttpCookieCollection());\n            mockContext.Setup(c => c.Response.Cookies).Returns(new HttpCookieCollection());\n            var displayModeProvider = new DisplayModeProvider();\n\n            WebPageMatch smartyMatch = WebPageRoute.MatchRequest(url, supportedExt.ToArray(), objectFactory.Exists, mockContext.Object, displayModeProvider);\n            if (match != null)\n            {\n                Assert.NotNull(smartyMatch);\n                Assert.Equal(match, smartyMatch.MatchedPath);\n                Assert.Equal(pathInfo, smartyMatch.PathInfo);\n            }\n            else\n            {\n                Assert.Null(smartyMatch);\n            }\n        }\n\n        [Theory,\n         InlineData(\"1.1/2/3\", \"1.1/2/3.3\", \"\"),\n         InlineData(\"1/2/3/4\", \"1.one\", \"2/3/4\"),\n         InlineData(\"2/3/4\", \"2.two\", \"3/4\"),\n         InlineData(\"one/two/3/4/5/6\", \"one/two/3/4.4\", \"5/6\"),\n         InlineData(\"one/two/3/4/5/6/foo\", \"one/two/3/4.4\", \"5/6/foo\"),\n         InlineData(\"one/two/3/4/5/6/foo.htm\", null, null)]\n        public void MultipleExtensionsTest(string url, string match, string pathInfo)\n        {\n            string[] files = new[] { \"~/1.one\", \"~/2.two\", \"~/1.1/2/3.3\", \"~/one/two/3/4.4\", \"~/one/two/3/4/5/6/foo.htm\" };\n            string[] extensions = new[] { \"aspx\", \"hao\", \"one\", \"two\", \"3\", \"4\" };\n\n            ConstraintTest(files, extensions, url, match, pathInfo);\n        }\n\n        [Theory,\n         InlineData(\"1.1/2/3\", \"1.1/2/3.Mobile.3\", \"\"),\n         InlineData(\"1/2/3/4\", \"1.Mobile.one\", \"2/3/4\"),\n         InlineData(\"2/3/4\", \"2.Mobile.two\", \"3/4\"),\n         InlineData(\"one/two/3/4/5/6\", \"one/two/3/4.Mobile.4\", \"5/6\"),\n         InlineData(\"one/two/3/4/5/6/foo\", \"one/two/3/4.Mobile.4\", \"5/6/foo\"),\n         InlineData(\"one/two/3/4/5/6/foo.Mobile.htm\", null, null)]\n        public void MultipleExtensionsMobileTest(string url, string match, string pathInfo)\n        {\n            string[] files = new[]\n            {\n                \"~/1.one\", \"~/2.two\", \"~/1.1/2/3.3\", \"~/one/two/3/4.4\", \"~/one/two/3/4/5/6/foo.htm\",\n                \"~/1.Mobile.one\", \"~/2.Mobile.two\", \"~/1.1/2/3.Mobile.3\", \"~/one/two/3/4.Mobile.4\", \"~/one/two/3/4/5/6/foo.Mobile.htm\"\n            };\n            string[] extensions = new[] { \"aspx\", \"hao\", \"one\", \"two\", \"3\", \"4\" };\n\n            ConstraintTest(files, extensions, url, match, pathInfo, mobileDevice: true);\n        }\n\n        [Fact]\n        public void FilesWithLeadingUnderscoresAreNeverServed()\n        {\n            string[] files = new[] { \"~/hi.evil\", \"~/_hi.evil\", \"~/_nest/good.evil\", \"~/_nest/_hide.evil\", \"~/_ok.good\" };\n            string[] extensions = new[] { \"evil\" };\n\n            ConstraintTest(files, extensions, \"hi\", \"hi.evil\", \"\");\n            ConstraintTest(files, extensions, \"_nest/good/some/extra/path/info\", \"_nest/good.evil\", \"some/extra/path/info\");\n            Assert.Throws<HttpException>(() => { ConstraintTest(files, extensions, \"_hi\", null, null); }, \"Files with leading underscores (\\\"_\\\") cannot be served.\");\n            Assert.Throws<HttpException>(() => { ConstraintTest(files, extensions, \"_nest/_hide\", null, null); }, \"Files with leading underscores (\\\"_\\\") cannot be served.\");\n        }\n\n        [Theory]\n        [InlineData(new object[] { \"_foo\", \"_foo/default.cshtml\" })]\n        [InlineData(new object[] { \"_bar/_baz\", \"_bar/_baz/index.cshtml\" })]\n        public void DirectoriesWithLeadingUnderscoresAreServed(string requestPath, string expectedPath)\n        {\n            // Arramge\n            var files = new[] { \"~/_foo/default.cshtml\", \"~/_bar/_baz/index.cshtml\" };\n            var extensions = new[] { \"cshtml\" };\n\n            // Act\n            ConstraintTest(files, extensions, requestPath, expectedPath, \"\");\n        }\n\n        [Fact]\n        public void TransformedUnderscoreAreNotServed()\n        {\n            string[] files = new[] { \"~/_ok.Mobile.ext\", \"~/ok.ext\" };\n            string[] extensions = new[] { \"ext\" };\n\n            ConstraintTest(files, extensions, \"ok.ext\", \"ok.ext\", \"\", mobileDevice: true);\n            ConstraintTest(files, extensions, \"ok/some/extra/path/info\", \"ok.ext\", \"some/extra/path/info\", mobileDevice: true);\n\n            Assert.Throws<HttpException>(() => { ConstraintTest(files, extensions, \"_ok.Mobile.ext\", null, null, mobileDevice: true); }, \"Files with leading underscores (\\\"_\\\") cannot be served.\");\n        }\n\n        [Fact]\n        public void MobileFilesAreReturnedInthePresenceOfUnderscoreFiles()\n        {\n            string[] files = new[] { \"~/_ok.Mobile.ext\", \"~/ok.ext\", \"~/ok.mobile.ext\" };\n            string[] extensions = new[] { \"ext\" };\n\n            ConstraintTest(files, extensions, \"ok.ext\", \"ok.Mobile.ext\", \"\", mobileDevice: true);\n            ConstraintTest(files, extensions, \"ok/some/extra/path/info\", \"ok.Mobile.ext\", \"some/extra/path/info\", mobileDevice: true);\n            ConstraintTest(files, extensions, \"ok.mobile\", \"ok.mobile.ext\", \"\", mobileDevice: false);\n        }\n\n        [Fact]\n        public void UnsupportedExtensionExistingFileTest()\n        {\n            ConstraintTest(new[] { \"~/hao.aspx\", \"~/hao/hao.txt\" }, new[] { \"aspx\" }, \"hao/hao.txt\", null, null);\n        }\n\n        [Fact]\n        public void NullPathValueDoesNotMatchTest()\n        {\n            ConstraintTest(new[] { \"~/hao.aspx\", \"~/hao/hao.txt\" }, new[] { \"aspx\" }, null, null, null);\n        }\n\n        [Fact]\n        public void RightToLeftPrecedenceTest()\n        {\n            ConstraintTest(new[] { \"~/one/two/three.aspx\", \"~/one/two.aspx\", \"~/one.aspx\" }, new[] { \"aspx\" }, \"one/two/three\", \"one/two/three.aspx\", \"\");\n        }\n\n        [Fact]\n        public void DefaultPrecedenceTests()\n        {\n            string[] files = new[] { \"~/one/two/default.aspx\", \"~/one/default.aspx\", \"~/default.aspx\" };\n            string[] extensions = new[] { \"aspx\" };\n\n            // Default only tries to look at the full path level\n            ConstraintTest(files, extensions, \"one/two/three\", null, null);\n            ConstraintTest(files, extensions, \"one/two\", \"one/two/default.aspx\", \"\");\n            ConstraintTest(files, extensions, \"one\", \"one/default.aspx\", \"\");\n            ConstraintTest(files, extensions, \"\", \"default.aspx\", \"\");\n            ConstraintTest(files, extensions, \"one/two/three/four/five/six/7/8\", null, null);\n        }\n\n        [Fact]\n        public void IndexTests()\n        {\n            string[] files = new[] { \"~/one/two/index.aspx\", \"~/one/index.aspx\", \"~/index.aspq\" };\n            string[] extensions = new[] { \"aspx\", \"aspq\" };\n\n            // index only tries to look at the full path level\n            ConstraintTest(files, extensions, \"one/two/three\", null, null);\n            ConstraintTest(files, extensions, \"one/two\", \"one/two/index.aspx\", \"\");\n            ConstraintTest(files, extensions, \"one\", \"one/index.aspx\", \"\");\n            ConstraintTest(files, extensions, \"\", \"index.aspq\", \"\");\n            ConstraintTest(files, extensions, \"one/two/three/four/five/six/7/8\", null, null);\n        }\n\n        [Fact]\n        public void DefaultVsIndexNestedTest()\n        {\n            string[] files = new[] { \"~/one/two/index.aspx\", \"~/one/index.aspx\", \"~/one/default.aspx\", \"~/index.aspq\", \"~/default.aspx\" };\n            string[] extensions = new[] { \"aspx\", \"aspq\" };\n\n            ConstraintTest(files, extensions, \"one/two\", \"one/two/index.aspx\", \"\");\n            ConstraintTest(files, extensions, \"one\", \"one/default.aspx\", \"\");\n            ConstraintTest(files, extensions, \"\", \"default.aspx\", \"\");\n        }\n\n        [Fact]\n        public void DefaultVsIndexSameExtensionTest()\n        {\n            string[] files = new[] { \"~/one/two/index.aspx\", \"~/one/index.aspx\", \"~/one/default.aspx\", \"~/index.aspq\", \"~/default.aspx\" };\n            string[] extensions = new[] { \"aspx\" };\n\n            ConstraintTest(files, extensions, \"one\", \"one/default.aspx\", \"\");\n        }\n\n        [Fact]\n        public void DefaultVsIndexDifferentExtensionTest()\n        {\n            string[] files = new[] { \"~/index.aspq\", \"~/default.aspx\" };\n            string[] extensions = new[] { \"aspx\", \"aspq\" };\n\n            ConstraintTest(files, extensions, \"\", \"default.aspx\", \"\");\n        }\n\n        [Fact]\n        public void DefaultVsIndexOnlyOneExtensionTest()\n        {\n            string[] files = new[] { \"~/index.aspq\", \"~/default.aspx\" };\n            string[] extensions = new[] { \"aspq\" };\n\n            ConstraintTest(files, extensions, \"\", \"index.aspq\", \"\");\n        }\n\n        [Fact]\n        public void FullMatchNoPathInfoTest()\n        {\n            ConstraintTest(new[] { \"~/hao.aspx\" }, new[] { \"aspx\" }, \"hao\", \"hao.aspx\", \"\");\n        }\n\n        [Fact]\n        public void MatchFileWithExtensionTest()\n        {\n            string[] files = new[] { \"~/page.aspq\" };\n            string[] extensions = new[] { \"aspq\" };\n\n            ConstraintTest(files, extensions, \"page.aspq\", \"page.aspq\", \"\");\n        }\n\n        [Fact]\n        public void NoMatchFileWithWrongExtensionTest()\n        {\n            string[] files = new[] { \"~/page.aspx\" };\n            string[] extensions = new[] { \"aspq\" };\n\n            ConstraintTest(files, extensions, \"page.aspx\", null, null);\n        }\n\n        [Fact]\n        public void WebPageRouteDoesNotPerformMappingIfRootLevelIsExplicitlyDisabled()\n        {\n            // Arrange\n            var webPageRoute = new WebPageRoute { IsExplicitlyDisabled = true };\n            var context = new Mock<HttpContextBase>();\n            context.Setup(c => c.RemapHandler(It.IsAny<IHttpHandler>())).Throws(new Exception(\"Smarty route should be disabled.\"));\n            context.SetupGet(c => c.Request).Throws(new Exception(\"We do not need to use the request to identify if the app is disabled.\"));\n\n            // Act \n            webPageRoute.DoPostResolveRequestCache(context.Object);\n\n            // Assert. \n            // If we've come this far, neither of the setups threw.\n            Assert.True(true);\n        }\n\n        [Fact]\n        public void MatchRequestSetsDisplayModeOfFirstMatchPerContext()\n        {\n            // Arrange\n            var objectFactory = new HashyBuildManager(new string[] { \"~/page.Mobile.aspx\", \"~/nonMobile.aspx\" });\n            var mockContext = new Mock<HttpContextBase>();\n            mockContext.Setup(context => context.Items).Returns(new Hashtable());\n            mockContext.Setup(c => c.Request.Browser.IsMobileDevice).Returns(true);\n            mockContext.Setup(c => c.Request.Cookies).Returns(new HttpCookieCollection());\n            mockContext.Setup(c => c.Response.Cookies).Returns(new HttpCookieCollection());\n\n            var displayModeProvider = new DisplayModeProvider();\n\n            // Act\n            WebPageMatch mobileMatch = WebPageRoute.MatchRequest(\"page.aspx\", new string[] { \"aspx\" }, objectFactory.Exists, mockContext.Object, displayModeProvider);\n\n            // Assert\n            Assert.NotNull(mobileMatch.MatchedPath);\n            Assert.Equal(DisplayModeProvider.MobileDisplayModeId, DisplayModeProvider.GetDisplayMode(mockContext.Object).DisplayModeId);\n        }\n\n        [Fact]\n        public void MatchRequestDoesNotSetDisplayModeIfNoMatch()\n        {\n            // Arrange\n            var objectFactory = new HashyBuildManager(new string[] { \"~/page.Mobile.aspx\" });\n            var mockContext = new Mock<HttpContextBase>();\n            mockContext.Setup(context => context.Items).Returns(new Hashtable());\n            mockContext.Setup(c => c.Request.Browser.IsMobileDevice).Returns(true);\n            mockContext.Setup(c => c.Request.Cookies).Returns(new HttpCookieCollection());\n            mockContext.Setup(c => c.Response.Cookies).Returns(new HttpCookieCollection());\n\n            var displayModeProvider = new DisplayModeProvider();\n            var displayMode = new Mock<IDisplayMode>(MockBehavior.Strict);\n            displayMode.Setup(d => d.CanHandleContext(mockContext.Object)).Returns(false);\n            displayModeProvider.Modes.Add(displayMode.Object);\n\n            // Act\n            WebPageMatch smartyMatch = WebPageRoute.MatchRequest(\"notThere.aspx\", new string[] { \"aspx\" }, objectFactory.Exists, mockContext.Object, displayModeProvider);\n\n            // Assert\n            Assert.Null(DisplayModeProvider.GetDisplayMode(mockContext.Object));\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/WebPage/WebPageTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Linq;\nusing System.Web.Caching;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace System.Web.WebPages.Test\n{\n    public class WebPageTest\n    {\n        private const string XmlHttpRequestKey = \"X-Requested-With\";\n        private const string XmlHttpRequestValue = \"XMLHttpRequest\";\n\n        [Fact]\n        public void CreatePageFromVirtualPathAssignsVirtualPathFactory()\n        {\n            // Arrange\n            var path = \"~/index.cshtml\";\n            var page = Utils.CreatePage(null, path);\n            var factory = new HashVirtualPathFactory(page);\n\n            // Act\n            var result = WebPage.CreateInstanceFromVirtualPath(path, factory);\n\n            // Assert\n            Assert.Equal(page, result);\n            Assert.Equal(page.VirtualPathFactory, factory);\n            Assert.Equal(page.VirtualPath, path);\n        }\n\n        [Fact]\n        public void NormalizeLayoutPagePathTest()\n        {\n            var layoutPage = \"Layout.cshtml\";\n            var layoutPath1 = \"~/MyApp/Layout.cshtml\";\n            var page = new Mock<WebPage>() { CallBase = true }.Object;\n            page.VirtualPath = \"~/MyApp/index.cshtml\";\n\n            var mockBuildManager = new Mock<IVirtualPathFactory>();\n            mockBuildManager.Setup(c => c.Exists(It.IsAny<string>())).Returns<string>(p => p.Equals(layoutPath1, StringComparison.OrdinalIgnoreCase));\n            page.VirtualPathFactory = mockBuildManager.Object;\n\n            Assert.Equal(layoutPath1, page.NormalizeLayoutPagePath(layoutPage));\n\n            mockBuildManager.Setup(c => c.Exists(It.IsAny<string>())).Returns<string>(_ => false);\n\n            Assert.Throws<HttpException>(() => page.NormalizeLayoutPagePath(layoutPage),\n                                                  @\"The layout page \"\"Layout.cshtml\"\" could not be found at the following path: \"\"~/MyApp/Layout.cshtml\"\".\");\n        }\n\n        [Fact]\n        public void UrlDataBasicTests()\n        {\n            Mock<HttpContextBase> mockContext = new Mock<HttpContextBase>();\n            mockContext.Setup(context => context.Items).Returns(new Hashtable());\n            string pathInfo = String.Format(\"{0}/{1}/{2}/{3}\", \"one\", 2, 3.0, 4.0005);\n            mockContext.Object.Items[typeof(WebPageMatch)] = new WebPageMatch(\"~/a.cshtml\", pathInfo);\n            WebPage page = new Mock<WebPage>() { CallBase = true }.Object;\n            page.Context = mockContext.Object;\n\n            Assert.Equal(\"one\", page.UrlData[0]);\n            Assert.Equal(2, page.UrlData[1].AsInt());\n            Assert.Equal(3.0f, page.UrlData[2].AsFloat());\n            Assert.Equal(4.0005m, page.UrlData[3].AsDecimal());\n        }\n\n        [Fact]\n        public void UrlDataEmptyTests()\n        {\n            Mock<HttpContextBase> mockContext = new Mock<HttpContextBase>();\n            mockContext.Setup(context => context.Items).Returns(new Hashtable());\n            mockContext.Object.Items[typeof(WebPageMatch)] = new WebPageMatch(\"~/a.cshtml\", \"one///two/\");\n            WebPage page = new Mock<WebPage>() { CallBase = true }.Object;\n            page.Context = mockContext.Object;\n\n            Assert.Equal(\"one\", page.UrlData[0]);\n            Assert.True(page.UrlData[1].IsEmpty());\n            Assert.True(page.UrlData[2].IsEmpty());\n            Assert.Equal(\"two\", page.UrlData[3]);\n            Assert.True(page.UrlData[4].IsEmpty());\n        }\n\n        [Fact]\n        public void UrlDataReadOnlyTest()\n        {\n            Mock<HttpContextBase> mockContext = new Mock<HttpContextBase>();\n            mockContext.Setup(context => context.Items).Returns(new Hashtable());\n            mockContext.Object.Items[typeof(WebPageMatch)] = new WebPageMatch(\"~/a.cshtml\", \"one/2/3.0/4.0005\");\n            WebPage page = new Mock<WebPage>() { CallBase = true }.Object;\n            page.Context = mockContext.Object;\n\n            Assert.Throws<NotSupportedException>(() => { page.UrlData.Add(\"bogus\"); }, \"The UrlData collection is read-only.\");\n            Assert.Throws<NotSupportedException>(() => { page.UrlData.Insert(0, \"bogus\"); }, \"The UrlData collection is read-only.\");\n            Assert.Throws<NotSupportedException>(() => { page.UrlData.Remove(\"one\"); }, \"The UrlData collection is read-only.\");\n        }\n\n        [Fact]\n        public void UrlDataOutOfBoundsTest()\n        {\n            Mock<HttpContextBase> mockContext = new Mock<HttpContextBase>();\n            mockContext.Setup(context => context.Items).Returns(new Hashtable());\n            mockContext.Object.Items[typeof(WebPageMatch)] = new WebPageMatch(\"~/a.cshtml\", \"\");\n            WebPage page = new Mock<WebPage>() { CallBase = true }.Object;\n            page.Context = mockContext.Object;\n\n            Assert.Equal(String.Empty, page.UrlData[0]);\n            Assert.Equal(String.Empty, page.UrlData[1]);\n        }\n\n        [Fact]\n        public void NullModelTest()\n        {\n            var page = CreateMockPageWithPostContext().Object;\n            page.PageContext.Model = null;\n            Assert.Null(page.Model);\n        }\n\n        internal class ModelTestClass\n        {\n            public string Prop1 { get; set; }\n\n            public string GetProp1()\n            {\n                return Prop1;\n            }\n\n            public override string ToString()\n            {\n                return Prop1;\n            }\n        }\n\n        [Fact]\n        public void ModelTest()\n        {\n            var v = \"value1\";\n            var page = CreateMockPageWithPostContext().Object;\n            var model = new ModelTestClass() { Prop1 = v };\n            page.PageContext.Model = model;\n            Assert.NotNull(page.Model);\n            Assert.Equal(v, page.Model.Prop1);\n            Assert.Equal(v, page.Model.GetProp1());\n            Assert.Equal(v, page.Model.ToString());\n            Assert.Equal(model, (ModelTestClass)page.Model);\n            // No such property\n            Assert.Null(page.Model.Prop2);\n            // No such method\n            Assert.Throws<MissingMethodException>(() => page.Model.DoSomething());\n        }\n\n        [Fact]\n        public void AnonymousObjectModelTest()\n        {\n            var v = \"value1\";\n            var page = CreateMockPageWithPostContext().Object;\n            var model = new { Prop1 = v };\n            page.PageContext.Model = model;\n            Assert.NotNull(page.Model);\n            Assert.Equal(v, page.Model.Prop1);\n            // No such property\n            Assert.Null(page.Model.Prop2);\n            // No such method\n            Assert.Throws<MissingMethodException>(() => page.Model.DoSomething());\n        }\n\n        [Fact]\n        public void SessionPropertyTest()\n        {\n            var page = CreateMockPageWithPostContext().Object;\n#pragma warning disable xUnit2013 // Do not use equality check to check for collection size.\n            Assert.Equal(0, page.Session.Count);\n#pragma warning restore xUnit2013 // Do not use equality check to check for collection size.\n        }\n\n        [Fact]\n        public void AppStatePropertyTest()\n        {\n            var page = CreateMockPageWithPostContext().Object;\n#pragma warning disable xUnit2013 // Do not use equality check to check for collection size.\n            Assert.Equal(0, page.AppState.Count);\n#pragma warning restore xUnit2013 // Do not use equality check to check for collection size.\n        }\n\n        [Fact]\n        public void ExecutePageHierarchyTest()\n        {\n            var page = new Mock<WebPage>();\n            page.Object.TopLevelPage = true;\n\n            var executors = new List<IWebPageRequestExecutor>();\n\n            // First executor returns false\n            var executor1 = new Mock<IWebPageRequestExecutor>();\n            executor1.Setup(exec => exec.Execute(It.IsAny<WebPage>())).Returns(false);\n            executors.Add(executor1.Object);\n\n            // Second executor returns true\n            var executor2 = new Mock<IWebPageRequestExecutor>();\n            executor2.Setup(exec => exec.Execute(It.IsAny<WebPage>())).Returns(true);\n            executors.Add(executor2.Object);\n\n            // Third executor should never get called, since we stop after the first true\n            var executor3 = new Mock<IWebPageRequestExecutor>();\n            executor3.Setup(exec => exec.Execute(It.IsAny<WebPage>())).Returns(false);\n            executors.Add(executor3.Object);\n\n            page.Object.ExecutePageHierarchy(executors);\n\n            // Make sure the first two got called but not the third\n            executor1.Verify(exec => exec.Execute(It.IsAny<WebPage>()));\n            executor2.Verify(exec => exec.Execute(It.IsAny<WebPage>()));\n            executor3.Verify(exec => exec.Execute(It.IsAny<WebPage>()), Times.Never());\n        }\n\n        [Fact]\n        public void IsPostReturnsTrueWhenMethodIsPost()\n        {\n            // Arrange\n            var page = CreateMockPageWithPostContext();\n\n            // Act and Assert\n            Assert.True(page.Object.IsPost);\n        }\n\n        [Fact]\n        public void IsPostReturnsFalseWhenMethodIsNotPost()\n        {\n            // Arrange\n            var methods = new[] { \"GET\", \"DELETE\", \"PUT\", \"RANDOM\" };\n\n            // Act and Assert\n            Assert.True(methods.All(method => !CreateMockPageWithContext(method).Object.IsPost));\n        }\n\n        [Fact]\n        public void IsAjaxReturnsTrueWhenRequestContainsAjaxHeader()\n        {\n            // Arrange\n            var headers = new NameValueCollection();\n            headers.Add(\"X-Requested-With\", \"XMLHttpRequest\");\n            var context = CreateContext(\"GET\", new NameValueCollection(), headers);\n            var page = CreatePage(context);\n\n            // Act and Assert\n            Assert.True(page.Object.IsAjax);\n        }\n\n        [Fact]\n        public void IsAjaxReturnsTrueWhenRequestBodyContainsAjaxHeader()\n        {\n            // Arrange\n            var headers = new NameValueCollection();\n            headers.Add(\"X-Requested-With\", \"XMLHttpRequest\");\n            var context = CreateContext(\"POST\", headers, headers);\n            var page = CreatePage(context);\n\n            // Act and Assert\n            Assert.True(page.Object.IsAjax);\n        }\n\n        [Fact]\n        public void IsAjaxReturnsFalseWhenRequestDoesNotContainAjaxHeaders()\n        {\n            // Arrange\n            var page = CreateMockPageWithPostContext();\n\n            // Act and Assert\n            Assert.True(!page.Object.IsAjax);\n        }\n\n        private static Mock<WebPage> CreatePage(Mock<HttpContextBase> context)\n        {\n            var page = new Mock<WebPage>() { CallBase = true };\n            var pageContext = new WebPageContext();\n            page.Object.Context = context.Object;\n            page.Object.PageContext = pageContext;\n            return page;\n        }\n\n        private static Mock<WebPage> CreateMockPageWithPostContext()\n        {\n            return CreateMockPageWithContext(\"POST\");\n        }\n\n        private static Mock<WebPage> CreateMockPageWithContext(string httpMethod)\n        {\n            var context = CreateContext(httpMethod, new NameValueCollection());\n            var page = CreatePage(context);\n            return page;\n        }\n\n        private static Mock<HttpContextBase> CreateContext(string httpMethod, NameValueCollection queryString, NameValueCollection httpHeaders = null)\n        {\n            var request = new Mock<HttpRequestBase>();\n            request.Setup(r => r.HttpMethod).Returns(httpMethod);\n            request.Setup(r => r.QueryString).Returns(queryString);\n            request.Setup(r => r.Form).Returns(new NameValueCollection());\n            request.Setup(r => r.Files).Returns(new Mock<HttpFileCollectionBase>().Object);\n            request.Setup(c => c.Headers).Returns(httpHeaders);\n            var context = new Mock<HttpContextBase>();\n            context.Setup(c => c.Response).Returns(new Mock<HttpResponseBase>().Object);\n            context.Setup(c => c.Request).Returns(request.Object);\n            context.Setup(c => c.Items).Returns(new Hashtable());\n            context.Setup(c => c.Session).Returns(new Mock<HttpSessionStateBase>().Object);\n            context.Setup(c => c.Application).Returns(new Mock<HttpApplicationStateBase>().Object);\n            context.Setup(c => c.Cache).Returns(new Cache());\n            context.Setup(c => c.Server).Returns(new Mock<HttpServerUtilityBase>().Object);\n            return context;\n        }\n    }\n}\n"
  },
  {
    "path": "test/System.Web.WebPages.Test/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Castle.Core\" version=\"5.1.1\" targetFramework=\"net462\" />\n  <package id=\"Moq\" version=\"4.18.4\" targetFramework=\"net462\" />\n  <package id=\"xunit\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.abstractions\" version=\"2.0.3\" targetFramework=\"net462\" />\n  <package id=\"xunit.analyzers\" version=\"1.1.0\" targetFramework=\"net462\" />\n  <package id=\"xunit.assert\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.execution\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.runner.visualstudio\" version=\"2.4.5\" targetFramework=\"net462\" developmentDependency=\"true\" />\n</packages>"
  },
  {
    "path": "test/WebApiHelpPage.Test/Controllers/UsersController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Web.Http;\n\nnamespace WebApiHelpPageWebHost.UnitTest.Controllers\n{\n    public class User\n    {\n        public string Name { get; set; }\n\n        public List<Order> Orders { get; set; }\n\n        public Address Address { get; set; }\n    }\n\n    public class Order\n    {\n        public int Id { get; set; }\n\n        public Product[] Products { get; set; }\n    }\n\n    public class Product\n    {\n        public Guid Id { get; set; }\n\n        public string Name { get; set; }\n\n        public string Description { get; set; }\n    }\n\n    public class Address\n    {\n        public string Street { get; set; }\n\n        public string City { get; set; }\n\n        public string Country { get; set; }\n    }\n\n    /// <summary>\n    /// Resource for Users.\n    /// </summary>\n    public class UsersController : ApiController\n    {\n        public IEnumerable<User> Get()\n        {\n            return null;\n        }\n\n        public string Post(User user)\n        {\n            return null;\n        }\n    }\n}"
  },
  {
    "path": "test/WebApiHelpPage.Test/Controllers/ValuesController.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Net;\nusing System.Net.Http;\nusing System.Web.Http;\n\nnamespace WebApiHelpPageWebHost.UnitTest.Controllers\n{\n    /// <summary>\n    /// Resource for Values.\n    /// </summary>\n    public class ValuesController : ApiController\n    {\n        /// <summary>\n        /// Gets all the values.\n        /// </summary>\n        /// <returns>A list of values.</returns>\n        public IEnumerable<string> Get()\n        {\n            return new string[] { \"value1\", \"value2\" };\n        }\n\n        /// <summary>\n        /// Gets the value by id.\n        /// </summary>\n        /// <param name=\"id\">The id.</param>\n        /// <returns>A value string.</returns>\n        public string Get(int id)\n        {\n            return \"value\";\n        }\n\n        /// <summary>\n        /// Gets the value by name.\n        /// </summary>\n        /// <param name=\"name\">The name.</param>\n        /// <returns>A value identified by name.</returns>\n        public string Get(string name)\n        {\n            return \"name\";\n        }\n\n        /// <summary>\n        /// Gets the value by the point.\n        /// This is a test for a type with TypeConverter.\n        /// </summary>\n        /// <param name=\"point\">The type defined with TypeConverter.</param>\n        /// <returns>A point string.</returns>\n        public string Get([FromUri]Point point)\n        {\n            return \"point\";\n        }\n\n        /// <summary>\n        /// Create a new value.\n        /// </summary>\n        /// <param name=\"value\">The value.</param>\n        /// <returns>A response.</returns>\n        public HttpResponseMessage Post([FromBody]string value)\n        {\n            return Request.CreateResponse<string>(HttpStatusCode.OK, \"hello\");\n        }\n\n        /// <summary>\n        /// Updates the value.\n        /// </summary>\n        /// <param name=\"id\">The id.</param>\n        /// <param name=\"value\">The value.</param>\n        public void Put(int id, [FromBody]string value)\n        {\n        }\n\n        /// <summary>\n        /// Updates the value pair collection.\n        /// </summary>\n        /// <param name=\"valuePairCollection\">The value pair collection.</param>\n        public void Put(List<Tuple<int, string>> valuePairCollection)\n        {\n        }\n\n        /// <summary>\n        /// Deletes the value.\n        /// </summary>\n        /// <param name=\"id\">The id.</param>\n        public void Delete(int? id)\n        {\n        }\n\n        /// <summary>\n        /// Patches the value pair.\n        /// </summary>\n        /// <param name=\"valuePair\">The pair.</param>\n        public void Patch(Tuple<int, string> valuePair)\n        {\n        }\n\n        /// <summary>\n        /// Returns the options.\n        /// </summary>\n        /// <param name=\"request\">The request.</param>\n        /// <returns>All the options.</returns>\n        public string Options(HttpRequestMessage request)\n        {\n            return \"options\";\n        }\n\n        public string[] HeadNoDocumentation(int id)\n        {\n            return new string[] { \"value1\", \"value2\" };\n        }\n\n        /// <summary>\n        /// Resource for nested values.\n        /// </summary>\n        public class NestedValuesController : ApiController\n        {\n            public string[] Get()\n            {\n                return new string[] { \"nvalue1\", \"nvalue2\" };\n            }\n        }\n\n        public class PointConverter : TypeConverter\n        {\n            // Overrides the CanConvertFrom method of TypeConverter.\n            // The ITypeDescriptorContext interface provides the context for the\n            // conversion. Typically, this interface is used at design time to \n            // provide information about the design-time container.\n            public override bool CanConvertFrom(ITypeDescriptorContext context,\n               Type sourceType)\n            {\n                if (sourceType == typeof(string))\n                {\n                    return true;\n                }\n                return base.CanConvertFrom(context, sourceType);\n            }\n            // Overrides the ConvertFrom method of TypeConverter.\n            public override object ConvertFrom(ITypeDescriptorContext context,\n               CultureInfo culture, object value)\n            {\n                if (value is string)\n                {\n                    string[] v = ((string)value).Split(new char[] { ',' });\n                    return new Point(int.Parse(v[0]), int.Parse(v[1]));\n                }\n                return base.ConvertFrom(context, culture, value);\n            }\n            // Overrides the ConvertTo method of TypeConverter.\n            public override object ConvertTo(ITypeDescriptorContext context,\n               CultureInfo culture, object value, Type destinationType)\n            {\n                if (destinationType == typeof(string))\n                {\n                    return ((Point)value).X + \",\" + ((Point)value).Y;\n                }\n                return base.ConvertTo(context, culture, value, destinationType);\n            }\n        }\n\n        [TypeConverter(typeof(PointConverter))]\n        public class Point\n        {\n            public Point(int x, int y)\n            {\n                X = x;\n                Y = y;\n            }\n\n            public int X { get; set; }\n\n            public int Y { get; set; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/WebApiHelpPage.Test/HelpControllerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Http;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing ROOT_PROJECT_NAMESPACE.Areas.HelpPage;\nusing ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Controllers;\nusing ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions;\n\nnamespace WebApiHelpPageWebHost.UnitTest\n{\n    public class HelpControllerTest\n    {\n        [Fact]\n        public void Constructor_Default()\n        {\n            HelpController controller = new HelpController();\n            Assert.Same(GlobalConfiguration.Configuration, controller.Configuration);\n        }\n\n        [Fact]\n        public void Constructor_OneParameter()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            HelpController controller = new HelpController(config);\n            Assert.Same(config, controller.Configuration);\n        }\n\n        [Fact]\n        public void Index_ReturnsCachedModels()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            HelpController controller = new HelpController(config);\n\n            ViewResult result = Assert.IsType<ViewResult>(controller.Index());\n            ViewResult result2 = Assert.IsType<ViewResult>(controller.Index());\n\n            Assert.NotNull(result.Model);\n            Assert.NotNull(result2.Model);\n\n            // Make sure the model is cached\n            Assert.Same(config.Services.GetApiExplorer().ApiDescriptions, result.Model);\n            Assert.Same(result.Model, result2.Model);\n        }\n\n        [Theory]\n        [InlineData(\"Get-Values\")]\n        [InlineData(\"get-values\")]\n        [InlineData(\"Get-Values_name\")]\n        [InlineData(\"get-values_NAME\")]\n        [InlineData(\"Get-Values-id\")]\n        [InlineData(\"Get-Values-ID\")]\n        [InlineData(\"Post-Values\")]\n        [InlineData(\"POST-VALUES\")]\n        [InlineData(\"Put-Values-id\")]\n        [InlineData(\"Put-VALUES-ID\")]\n        [InlineData(\"Put-Values\")]\n        [InlineData(\"Put-VALUES\")]\n        [InlineData(\"Delete-Values-id\")]\n        [InlineData(\"Delete-VALUES-id\")]\n        [InlineData(\"Patch-Values\")]\n        [InlineData(\"Patch-VALUES\")]\n        [InlineData(\"Options-Values\")]\n        [InlineData(\"OpTions-VALUES\")]\n        [InlineData(\"Head-Values-id\")]\n        [InlineData(\"HEAD-VALUES-id\")]\n        public void API_ReturnsCachedModels(string apiDescriptionId)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            HelpController controller = new HelpController(config);\n\n            ViewResult result = Assert.IsType<ViewResult>(controller.Api(apiDescriptionId));\n            ViewResult result2 = Assert.IsType<ViewResult>(controller.Api(apiDescriptionId));\n\n            Assert.NotNull(result.Model);\n            Assert.NotNull(result2.Model);\n\n            // Make sure the model is cached\n            Assert.Same(config.GetHelpPageApiModel(apiDescriptionId), result.Model);\n            Assert.Same(result.Model, result2.Model);\n        }\n\n        [Theory]\n        [InlineData(\"\")]\n        [InlineData(null)]\n        [InlineData(\"@@@@@@@\")]\n        public void API_ReturnsNullModels_WhenApiIdIsInvalid(string apiDescriptionId)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            HelpController controller = new HelpController(config);\n\n            ViewResult result = Assert.IsType<ViewResult>(controller.Api(apiDescriptionId));\n            ViewResult result2 = Assert.IsType<ViewResult>(controller.Api(apiDescriptionId));\n\n            Assert.Null(result.Model);\n            Assert.Null(result2.Model);\n        }\n\n        [Theory]\n        [InlineData(\"WebApiHelpPageWebHost.UnitTest.Controllers.User\")]\n        [InlineData(\"WebApiHelpPageWebHost.UnitTest.Controllers.Order\")]\n        [InlineData(\"WebApiHelpPageWebHost.UnitTest.Controllers.Product\")]\n        [InlineData(\"WebApiHelpPageWebHost.UnitTest.Controllers.Address\")]\n        [InlineData(\"webapihelppagewebhost.unittest.controllers.user\")]\n        [InlineData(\"WEBAPIHELPPAGEWEBHOST.UNITTEST.CONTROLLERS.ORDER\")]\n        [InlineData(\"webApiHelpPageWebHost.UnitTest.Controllers.Product\")]\n        [InlineData(\"WebApiHelpPageWebHost.unittest.Controllers.ADDRESS\")]\n        public void ResourceModel_ReturnsCachedModels(string modelName)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            HelpController controller = new HelpController(config);\n            ModelDescriptionGenerator modelDescriptionGenerator = config.GetModelDescriptionGenerator();\n            ModelDescription expectedModelDescription;\n            modelDescriptionGenerator.GeneratedModels.TryGetValue(modelName, out expectedModelDescription);\n\n            ViewResult result = Assert.IsType<ViewResult>(controller.ResourceModel(modelName));\n            ViewResult result2 = Assert.IsType<ViewResult>(controller.ResourceModel(modelName));\n\n            Assert.Same(expectedModelDescription, result.Model);\n            Assert.Same(result.Model, result2.Model);\n        }\n\n        [Theory]\n        [InlineData(\"WebApiHelpPageWebHost.UnitTest.Controllers.User\")]\n        [InlineData(\"WebApiHelpPageWebHost.UnitTest.Controllers.Order\")]\n        [InlineData(\"WebApiHelpPageWebHost.UnitTest.Controllers.Product\")]\n        [InlineData(\"WebApiHelpPageWebHost.UnitTest.Controllers.Address\")]\n        [InlineData(\"webapihelppagewebhost.unittest.controllers.user\")]\n        [InlineData(\"WEBAPIHELPPAGEWEBHOST.UNITTEST.CONTROLLERS.ORDER\")]\n        [InlineData(\"webApiHelpPageWebHost.UnitTest.Controllers.Product\")]\n        [InlineData(\"WebApiHelpPageWebHost.unittest.Controllers.ADDRESS\")]\n        public void ResourceModel_ReturnsCachedModels_UnusedParameters(string modelName)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{unused}/{id}\", new { id = RouteParameter.Optional });\n            HelpController controller = new HelpController(config);\n            ModelDescriptionGenerator modelDescriptionGenerator = config.GetModelDescriptionGenerator();\n            ModelDescription expectedModelDescription;\n            modelDescriptionGenerator.GeneratedModels.TryGetValue(modelName, out expectedModelDescription);\n\n            ViewResult result = Assert.IsType<ViewResult>(controller.ResourceModel(modelName));\n            ViewResult result2 = Assert.IsType<ViewResult>(controller.ResourceModel(modelName));\n\n            Assert.Same(expectedModelDescription, result.Model);\n            Assert.Same(result.Model, result2.Model);\n        }\n\n        [Theory]\n        [InlineData(\"\")]\n        [InlineData(null)]\n        [InlineData(\"@@@@@@@\")]\n        public void ResourceModel_ReturnsNullModels_WhenAModelNameIsInvalid(string modelName)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            HelpController controller = new HelpController(config);\n\n            ViewResult result = Assert.IsType<ViewResult>(controller.ResourceModel(modelName));\n            ViewResult result2 = Assert.IsType<ViewResult>(controller.ResourceModel(modelName));\n\n            Assert.Null(result.Model);\n            Assert.Null(result2.Model);\n        }\n    }\n}\n"
  },
  {
    "path": "test/WebApiHelpPage.Test/HelpPageApiModelTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Net.Http.Headers;\nusing System.Web.Http.Description;\nusing Microsoft.TestCommon;\nusing ROOT_PROJECT_NAMESPACE.Areas.HelpPage;\nusing ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Models;\n\nnamespace WebApiHelpPageWebHost.UnitTest\n{\n    public class HelpPageApiModelTest\n    {\n        [Fact]\n        public void Default_Constructor()\n        {\n            HelpPageApiModel model = new HelpPageApiModel();\n            Assert.NotNull(model.SampleRequests);\n            Assert.NotNull(model.SampleResponses);\n            Assert.NotNull(model.ErrorMessages);\n            Assert.Null(model.ApiDescription);\n        }\n\n        [Fact]\n        public void ApiDescription_Property()\n        {\n            HelpPageApiModel model = new HelpPageApiModel();\n            ApiDescription description = new ApiDescription();\n            model.ApiDescription = description;\n            Assert.NotNull(model.ApiDescription);\n            Assert.Same(description, model.ApiDescription);\n        }\n\n        [Fact]\n        public void ErrorMessages_Property()\n        {\n            HelpPageApiModel model = new HelpPageApiModel();\n            string error = \"an error\";\n            model.ErrorMessages.Add(error);\n            Assert.NotEmpty(model.ErrorMessages);\n            Assert.Same(error, model.ErrorMessages[0]);\n        }\n\n        [Fact]\n        public void SampleRequests_Property()\n        {\n            HelpPageApiModel model = new HelpPageApiModel();\n            ImageSample sample = new ImageSample(\"http://host/image.png\");\n            model.SampleRequests.Add(new MediaTypeHeaderValue(\"text/plain\"), sample);\n            object sampleRequest;\n            model.SampleRequests.TryGetValue(new MediaTypeHeaderValue(\"text/plain\"), out sampleRequest);\n            Assert.NotEmpty(model.SampleRequests);\n            Assert.Same(sample, sampleRequest);\n        }\n\n        [Fact]\n        public void SampleResponses_Property()\n        {\n            HelpPageApiModel model = new HelpPageApiModel();\n            InvalidSample sample = new InvalidSample(\"invalid\");\n            model.SampleResponses.Add(new MediaTypeHeaderValue(\"text/xml\"), sample);\n            object sampleResponse;\n            model.SampleResponses.TryGetValue(new MediaTypeHeaderValue(\"text/xml\"), out sampleResponse);\n            Assert.NotEmpty(model.SampleResponses);\n            Assert.Same(sample, sampleResponse);\n        }\n    }\n}\n"
  },
  {
    "path": "test/WebApiHelpPage.Test/HelpPageAreaRegistrationTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Web.Mvc;\nusing System.Web.Routing;\nusing Microsoft.TestCommon;\nusing ROOT_PROJECT_NAMESPACE.Areas.HelpPage;\n\nnamespace WebApiHelpPageWebHost.UnitTest\n{\n    public class HelpPageAreaRegistrationTest\n    {\n        [Fact]\n        public void AreaName()\n        {\n            HelpPageAreaRegistration area = new HelpPageAreaRegistration();\n            Assert.Equal(\"HelpPage\", area.AreaName);\n        }\n\n        [Fact]\n        public void RegisterArea()\n        {\n            HelpPageAreaRegistration area = new HelpPageAreaRegistration();\n            AreaRegistrationContext context = new AreaRegistrationContext(\"HelpPage\", RouteTable.Routes);\n            area.RegisterArea(context);\n            Assert.NotEmpty(context.Routes);\n            Route route = Assert.IsType<Route>(context.Routes[0]);\n            Assert.Equal(\"Help/{action}/{apiId}\", route.Url);\n            Assert.Equal(\"Help\", route.Defaults[\"controller\"]);\n            Assert.Equal(\"Index\", route.Defaults[\"action\"]);\n        }\n    }\n}\n"
  },
  {
    "path": "test/WebApiHelpPage.Test/HelpPageConfigurationExtensionsTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http.Headers;\nusing System.Web.Http;\nusing System.Web.Http.Description;\nusing System.Web.Http.ModelBinding;\nusing Microsoft.TestCommon;\nusing Moq;\nusing ROOT_PROJECT_NAMESPACE.Areas.HelpPage;\nusing ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions;\nusing ROOT_PROJECT_NAMESPACE.Areas.HelpPage.Models;\n\nnamespace WebApiHelpPageWebHost.UnitTest\n{\n    public class HelpPageConfigurationExtensionsTest\n    {\n        [Theory]\n        [InlineData(\"Get-Values\")]\n        [InlineData(\"get-values\")]\n        [InlineData(\"Get-Values_Name\")]\n        [InlineData(\"get-values_NAME\")]\n        [InlineData(\"Get-Values-id\")]\n        [InlineData(\"Get-Values-ID\")]\n        [InlineData(\"Post-Values\")]\n        [InlineData(\"POST-VALUES\")]\n        [InlineData(\"Put-Values-id\")]\n        [InlineData(\"Put-VALUES-ID\")]\n        [InlineData(\"Put-Values\")]\n        [InlineData(\"Put-VALUES\")]\n        [InlineData(\"Delete-Values-id\")]\n        [InlineData(\"Delete-VALUES-id\")]\n        [InlineData(\"Patch-Values\")]\n        [InlineData(\"Patch-VALUES\")]\n        [InlineData(\"Options-Values\")]\n        [InlineData(\"OpTions-VALUES\")]\n        [InlineData(\"Head-Values-id\")]\n        [InlineData(\"HEAD-VALUES-id\")]\n        public void GetHelpPageApiModel_ReturnsTheModel_WhenIdIsValid(string apiId)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            HelpPageApiModel model = config.GetHelpPageApiModel(apiId);\n            Assert.NotNull(model);\n            Assert.Same(model, config.GetHelpPageApiModel(apiId));\n            Assert.Equal(apiId, model.ApiDescription.GetFriendlyId(), StringComparer.OrdinalIgnoreCase);\n        }\n\n        [Fact]\n        public void GetHelpPageApiModel_TypeConverterModel_GeneratesUriParameter()\n        {\n            // If class Point with properties X and Y is defined with a TypeConverter, \n            // the UriParameters should be a single parameter name \"point\" instead of two member properties X and Y,\n            // because X and Y do not appear in the Relative Path and it is the user that should specify how the query\n            // string is parsed.\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n\n            // Act\n            HelpPageApiModel model = config.GetHelpPageApiModel(\"GET-Values_point\");\n\n            // Assert\n            Assert.NotNull(model);\n            string expectedParameter = Assert.Single(model.ApiDescription.ParameterDescriptions).Name;\n            ParameterDescription parameterDescription = Assert.Single(model.UriParameters);\n            Assert.Equal(expectedParameter, parameterDescription.Name);\n        }\n\n        [Theory]\n        [InlineData(\"Get-Values-Unused\")]\n        [InlineData(\"get-values-unused\")]\n        [InlineData(\"Get-Values-Unused_Name\")]\n        [InlineData(\"get-values-unused_NAME\")]\n        [InlineData(\"Get-Values-Unused-id\")]\n        [InlineData(\"Get-Values-unused-ID\")]\n        [InlineData(\"Post-Values-Unused\")]\n        [InlineData(\"POST-VALUES-UNUSED\")]\n        [InlineData(\"Put-Values-Unused-id\")]\n        [InlineData(\"Put-VALUES-UNUSED-ID\")]\n        [InlineData(\"Put-Values-Unused\")]\n        [InlineData(\"Put-VALUES-UNUSED\")]\n        [InlineData(\"Delete-Values-Unused-id\")]\n        [InlineData(\"Delete-VALUES-UNUSED-id\")]\n        [InlineData(\"Patch-Values-Unused\")]\n        [InlineData(\"Patch-VALUES-UNUSED\")]\n        [InlineData(\"Options-Values-Unused\")]\n        [InlineData(\"OpTions-VALUES-UNUSED\")]\n        [InlineData(\"Head-Values-Unused-id\")]\n        [InlineData(\"HEAD-VALUES-UNUSED-id\")]\n        public void GetHelpPageApiModel_ReturnsTheModel_WhenIdIsValid_UnusedParameters(string apiId)\n        {\n            // Arrange\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{unused}/{id}\", new { id = RouteParameter.Optional });\n\n            // Act\n            HelpPageApiModel model = config.GetHelpPageApiModel(apiId);\n\n            // Assert\n            Assert.NotNull(model);\n            Assert.Same(model, config.GetHelpPageApiModel(apiId));\n            Assert.Equal(apiId, model.ApiDescription.GetFriendlyId(), StringComparer.OrdinalIgnoreCase);\n        }\n\n        [Theory]\n        [InlineData(\"foo\")]\n        [InlineData(\"bar\")]\n        [InlineData(\"@alpha\")]\n        [InlineData(\"GetValues/{id}/{name}\")]\n        public void GetHelpPageApiModel_ReturnsNull_WhenIdIsInvalid(string apiId)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            HelpPageApiModel model = config.GetHelpPageApiModel(apiId);\n            Assert.Null(model);\n        }\n\n        [Theory]\n        [InlineData(\"Get-Values\")]\n        [InlineData(\"get-values\")]\n        [InlineData(\"Get-Values-id\")]\n        [InlineData(\"Get-Values-ID\")]\n        public void GetHelpPageApiModel_ReturnsNull_IfNoRoute(string apiId)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            HelpPageApiModel model = config.GetHelpPageApiModel(apiId);\n            Assert.Null(model);\n        }\n\n        [Fact]\n        public void GetHelpPageApiModel_HandlesException_ThrownDuringSampleGeneration()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            Mock<HelpPageSampleGenerator> faultyGenerator = new Mock<HelpPageSampleGenerator>();\n            faultyGenerator.Setup(g => g.GetSample(It.IsAny<ApiDescription>(), It.IsAny<SampleDirection>())).Returns(() => { throw new InvalidOperationException(\"This is a faulty sample generator.\"); });\n            config.SetHelpPageSampleGenerator(faultyGenerator.Object);\n            HelpPageApiModel model = config.GetHelpPageApiModel(\"Get-Values\");\n            Assert.NotNull(model);\n            Assert.NotEmpty(model.ErrorMessages);\n            Assert.Equal(\"An exception has occurred while generating the sample. Exception message: This is a faulty sample generator.\", model.ErrorMessages[0]);\n        }\n\n        [Fact]\n        public void GetHelpPageApiModel_HandlesException_ThrownDuringSampleObjectSerialization()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Formatters.Clear();\n            config.Formatters.Add(new JQueryMvcFormUrlEncodedFormatter());\n            config.SetSampleObjects(new Dictionary<Type, object> { { typeof(string), \"sample\" } });\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            HelpPageApiModel model = config.GetHelpPageApiModel(\"Post-Values\");\n            Assert.NotNull(model);\n            Assert.NotEmpty(model.ErrorMessages);\n            Assert.Equal(\"Failed to generate the sample for media type 'application/x-www-form-urlencoded'. Cannot use formatter 'JQueryMvcFormUrlEncodedFormatter' to write type 'String'.\", model.ErrorMessages[0]);\n        }\n\n        [Fact]\n        public void GetHelpPageApiModel_UnwrapsAggregateException()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n            Mock<HelpPageSampleGenerator> faultyGenerator = new Mock<HelpPageSampleGenerator>();\n            faultyGenerator.Setup(g => g.GetSample(It.IsAny<ApiDescription>(), It.IsAny<SampleDirection>())).Returns(() => { throw new AggregateException(new InvalidOperationException(\"Sample generator failed.\")); });\n            config.SetHelpPageSampleGenerator(faultyGenerator.Object);\n            HelpPageApiModel model = config.GetHelpPageApiModel(\"Get-Values\");\n            Assert.NotNull(model);\n            Assert.NotEmpty(model.ErrorMessages);\n            Assert.Equal(\"An exception has occurred while generating the sample. Exception message: Sample generator failed.\", model.ErrorMessages[0]);\n        }\n\n        [Theory]\n        [InlineData(\"Post-Users\", true)]\n        [InlineData(\"Post-Values\", true)]\n        [InlineData(\"Put-Values\", true)]\n        [InlineData(\"Get-Values\", false)]\n        [InlineData(\"Get-Users\", false)]\n        [InlineData(\"Get-Values-id\", false)]\n        [InlineData(\"Head-Values-id\", false)]\n        public void GetHelpPageApiModel_ReturnsExpectedRequestModelDescription(string apiId, bool hasRequestModelDescription)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.Routes.MapHttpRoute(\"Default\", \"{controller}/{id}\", new { id = RouteParameter.Optional });\n\n            HelpPageApiModel model = config.GetHelpPageApiModel(apiId);\n\n            Assert.NotNull(model);\n            if (hasRequestModelDescription)\n            {\n                Assert.NotNull(model.RequestModelDescription);\n            }\n            else\n            {\n                Assert.Null(model.RequestModelDescription);\n            }\n        }\n\n        [Fact]\n        public void SetDocumentationProvider()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            Mock<IDocumentationProvider> docProviderMock = new Mock<IDocumentationProvider>();\n            IDocumentationProvider docProvider = docProviderMock.Object;\n            config.SetDocumentationProvider(docProvider);\n\n            Assert.Same(docProvider, config.Services.GetDocumentationProvider());\n        }\n\n        [Fact]\n        public void SetSampleObjects()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            Dictionary<Type, object> sampleObjects = new Dictionary<Type, object>\n            {\n                {typeof(int), 21},\n                {typeof(string), \"sample\"}\n            };\n            config.SetSampleObjects(sampleObjects);\n\n            object sampleGeneratorObj;\n            config.Properties.TryGetValue(typeof(HelpPageSampleGenerator), out sampleGeneratorObj);\n            HelpPageSampleGenerator sampleGenerator = Assert.IsType<HelpPageSampleGenerator>(sampleGeneratorObj);\n            Assert.Same(sampleObjects, sampleGenerator.SampleObjects);\n        }\n\n        [Fact]\n        public void SetSampleRequest()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            TextSample sample = new TextSample(\"test\");\n            config.SetSampleRequest(sample, new MediaTypeHeaderValue(\"application/xml\"), \"values\", \"get\");\n            object sampleGeneratorObj;\n            config.Properties.TryGetValue(typeof(HelpPageSampleGenerator), out sampleGeneratorObj);\n            HelpPageSampleGenerator sampleGenerator = Assert.IsType<HelpPageSampleGenerator>(sampleGeneratorObj);\n            Assert.NotEmpty(sampleGenerator.ActionSamples);\n            var actionSample = sampleGenerator.ActionSamples.First();\n            Assert.Equal(\"values\", actionSample.Key.ControllerName);\n            Assert.Equal(\"get\", actionSample.Key.ActionName);\n            Assert.Equal(new MediaTypeHeaderValue(\"application/xml\"), actionSample.Key.MediaType);\n            Assert.Equal(SampleDirection.Request, actionSample.Key.SampleDirection);\n            Assert.NotEmpty(actionSample.Key.ParameterNames);\n            Assert.Equal(\"*\", actionSample.Key.ParameterNames.First());\n            Assert.Same(sample, actionSample.Value);\n        }\n\n        [Fact]\n        public void SetSampleRequest_WithParameters()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            TextSample sample = new TextSample(\"test\");\n            config.SetSampleRequest(sample, new MediaTypeHeaderValue(\"application/json\"), \"values\", \"post\", \"id\", \"name\");\n            object sampleGeneratorObj;\n            config.Properties.TryGetValue(typeof(HelpPageSampleGenerator), out sampleGeneratorObj);\n            HelpPageSampleGenerator sampleGenerator = Assert.IsType<HelpPageSampleGenerator>(sampleGeneratorObj);\n            Assert.NotEmpty(sampleGenerator.ActionSamples);\n            var actionSample = sampleGenerator.ActionSamples.First();\n            Assert.Equal(\"values\", actionSample.Key.ControllerName);\n            Assert.Equal(\"post\", actionSample.Key.ActionName);\n            Assert.Equal(new MediaTypeHeaderValue(\"application/json\"), actionSample.Key.MediaType);\n            Assert.Equal(SampleDirection.Request, actionSample.Key.SampleDirection);\n            Assert.Equal(2, actionSample.Key.ParameterNames.Count);\n            Assert.True(actionSample.Key.ParameterNames.SetEquals(new[] { \"id\", \"name\" }));\n            Assert.Same(sample, actionSample.Value);\n        }\n\n        [Fact]\n        public void SetSampleResponse()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            TextSample sample = new TextSample(\"test\");\n            config.SetSampleResponse(sample, new MediaTypeHeaderValue(\"application/xml\"), \"values\", \"get\");\n            object sampleGeneratorObj;\n            config.Properties.TryGetValue(typeof(HelpPageSampleGenerator), out sampleGeneratorObj);\n            HelpPageSampleGenerator sampleGenerator = Assert.IsType<HelpPageSampleGenerator>(sampleGeneratorObj);\n            Assert.NotEmpty(sampleGenerator.ActionSamples);\n            var actionSample = sampleGenerator.ActionSamples.First();\n            Assert.Equal(\"values\", actionSample.Key.ControllerName);\n            Assert.Equal(\"get\", actionSample.Key.ActionName);\n            Assert.Equal(new MediaTypeHeaderValue(\"application/xml\"), actionSample.Key.MediaType);\n            Assert.Equal(SampleDirection.Response, actionSample.Key.SampleDirection);\n            Assert.NotEmpty(actionSample.Key.ParameterNames);\n            Assert.Equal(\"*\", actionSample.Key.ParameterNames.First());\n            Assert.Same(sample, actionSample.Value);\n        }\n\n        [Fact]\n        public void SetSampleResponse_WithParameters()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            TextSample sample = new TextSample(\"test\");\n            config.SetSampleResponse(sample, new MediaTypeHeaderValue(\"application/json\"), \"values\", \"post\", \"id\", \"name\");\n            object sampleGeneratorObj;\n            config.Properties.TryGetValue(typeof(HelpPageSampleGenerator), out sampleGeneratorObj);\n            HelpPageSampleGenerator sampleGenerator = Assert.IsType<HelpPageSampleGenerator>(sampleGeneratorObj);\n            Assert.NotEmpty(sampleGenerator.ActionSamples);\n            var actionSample = sampleGenerator.ActionSamples.First();\n            Assert.Equal(\"values\", actionSample.Key.ControllerName);\n            Assert.Equal(\"post\", actionSample.Key.ActionName);\n            Assert.Equal(new MediaTypeHeaderValue(\"application/json\"), actionSample.Key.MediaType);\n            Assert.Equal(SampleDirection.Response, actionSample.Key.SampleDirection);\n            Assert.Equal(2, actionSample.Key.ParameterNames.Count);\n            Assert.True(actionSample.Key.ParameterNames.SetEquals(new[] { \"id\", \"name\" }));\n            Assert.Same(sample, actionSample.Value);\n        }\n\n        [Fact]\n        public void SetSampleForType()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            ImageSample sample = new ImageSample(\"http://localhost/test.png\");\n            config.SetSampleForType(sample, new MediaTypeHeaderValue(\"image/png\"), typeof(string));\n            object sampleGeneratorObj;\n            config.Properties.TryGetValue(typeof(HelpPageSampleGenerator), out sampleGeneratorObj);\n            HelpPageSampleGenerator sampleGenerator = Assert.IsType<HelpPageSampleGenerator>(sampleGeneratorObj);\n            Assert.NotEmpty(sampleGenerator.ActionSamples);\n            var actionSample = sampleGenerator.ActionSamples.First();\n            Assert.Equal(String.Empty, actionSample.Key.ControllerName);\n            Assert.Equal(String.Empty, actionSample.Key.ActionName);\n            Assert.Equal(new MediaTypeHeaderValue(\"image/png\"), actionSample.Key.MediaType);\n            Assert.Null(actionSample.Key.SampleDirection);\n            Assert.Empty(actionSample.Key.ParameterNames);\n            Assert.Same(sample, actionSample.Value);\n        }\n\n        [Fact]\n        public void SetActualRequestType()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.SetActualRequestType(typeof(string), \"c\", \"a\");\n            object sampleGeneratorObj;\n            config.Properties.TryGetValue(typeof(HelpPageSampleGenerator), out sampleGeneratorObj);\n            HelpPageSampleGenerator sampleGenerator = Assert.IsType<HelpPageSampleGenerator>(sampleGeneratorObj);\n            Assert.NotEmpty(sampleGenerator.ActualHttpMessageTypes);\n            var actualType = sampleGenerator.ActualHttpMessageTypes.First();\n            Assert.Equal(\"c\", actualType.Key.ControllerName);\n            Assert.Equal(\"a\", actualType.Key.ActionName);\n            Assert.Null(actualType.Key.MediaType);\n            Assert.Equal(SampleDirection.Request, actualType.Key.SampleDirection);\n            Assert.NotEmpty(actualType.Key.ParameterNames);\n            Assert.Equal(\"*\", actualType.Key.ParameterNames.First());\n            Assert.Equal(typeof(string), actualType.Value);\n        }\n\n        [Fact]\n        public void SetActualRequestType_WithParameters()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.SetActualRequestType(typeof(string), \"c\", \"a\", \"id\");\n            object sampleGeneratorObj;\n            config.Properties.TryGetValue(typeof(HelpPageSampleGenerator), out sampleGeneratorObj);\n            HelpPageSampleGenerator sampleGenerator = Assert.IsType<HelpPageSampleGenerator>(sampleGeneratorObj);\n            Assert.NotEmpty(sampleGenerator.ActualHttpMessageTypes);\n            var actualType = sampleGenerator.ActualHttpMessageTypes.First();\n            Assert.Equal(\"c\", actualType.Key.ControllerName);\n            Assert.Equal(\"a\", actualType.Key.ActionName);\n            Assert.Null(actualType.Key.MediaType);\n            Assert.Equal(SampleDirection.Request, actualType.Key.SampleDirection);\n            Assert.NotEmpty(actualType.Key.ParameterNames);\n            Assert.Equal(\"id\", actualType.Key.ParameterNames.First());\n            Assert.Equal(typeof(string), actualType.Value);\n        }\n\n        [Fact]\n        public void SetActualResponseType()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.SetActualResponseType(typeof(int), \"c\", \"a\");\n            object sampleGeneratorObj;\n            config.Properties.TryGetValue(typeof(HelpPageSampleGenerator), out sampleGeneratorObj);\n            HelpPageSampleGenerator sampleGenerator = Assert.IsType<HelpPageSampleGenerator>(sampleGeneratorObj);\n            Assert.NotEmpty(sampleGenerator.ActualHttpMessageTypes);\n            var actualType = sampleGenerator.ActualHttpMessageTypes.First();\n            Assert.Equal(\"c\", actualType.Key.ControllerName);\n            Assert.Equal(\"a\", actualType.Key.ActionName);\n            Assert.Null(actualType.Key.MediaType);\n            Assert.Equal(SampleDirection.Response, actualType.Key.SampleDirection);\n            Assert.NotEmpty(actualType.Key.ParameterNames);\n            Assert.Equal(\"*\", actualType.Key.ParameterNames.First());\n            Assert.Equal(typeof(int), actualType.Value);\n        }\n\n        [Fact]\n        public void SetActualResponseType_WithParameters()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.SetActualResponseType(typeof(int), \"c\", \"a\", \"id\");\n            object sampleGeneratorObj;\n            config.Properties.TryGetValue(typeof(HelpPageSampleGenerator), out sampleGeneratorObj);\n            HelpPageSampleGenerator sampleGenerator = Assert.IsType<HelpPageSampleGenerator>(sampleGeneratorObj);\n            Assert.NotEmpty(sampleGenerator.ActualHttpMessageTypes);\n            var actualType = sampleGenerator.ActualHttpMessageTypes.First();\n            Assert.Equal(\"c\", actualType.Key.ControllerName);\n            Assert.Equal(\"a\", actualType.Key.ActionName);\n            Assert.Null(actualType.Key.MediaType);\n            Assert.Equal(SampleDirection.Response, actualType.Key.SampleDirection);\n            Assert.NotEmpty(actualType.Key.ParameterNames);\n            Assert.Equal(\"id\", actualType.Key.ParameterNames.First());\n            Assert.Equal(typeof(int), actualType.Value);\n        }\n\n        [Fact]\n        public void GetHelpPageSampleGenerator_ReturnsDefaultValue()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            HelpPageSampleGenerator helpPageSampleGenerator = config.GetHelpPageSampleGenerator();\n            Assert.NotNull(helpPageSampleGenerator);\n            Assert.Same(helpPageSampleGenerator, config.GetHelpPageSampleGenerator());\n        }\n\n        [Fact]\n        public void SetHelpPageSampleGenerator_ChangesTheDefault()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            Mock<HelpPageSampleGenerator> helpPageSampleGenerator = new Mock<HelpPageSampleGenerator>();\n            config.SetHelpPageSampleGenerator(helpPageSampleGenerator.Object);\n            Assert.Same(helpPageSampleGenerator.Object, config.GetHelpPageSampleGenerator());\n        }\n    }\n}"
  },
  {
    "path": "test/WebApiHelpPage.Test/HelpPageSampleKeyTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Net.Http.Headers;\nusing Microsoft.TestCommon;\nusing ROOT_PROJECT_NAMESPACE.Areas.HelpPage;\n\nnamespace WebApiHelpPageWebHost.UnitTest\n{\n    public class HelpPageSampleKeyTest\n    {\n        [Fact]\n        public void Constructor_TwoParameters()\n        {\n            HelpPageSampleKey key = new HelpPageSampleKey(new MediaTypeHeaderValue(\"application/xml\"), typeof(Tuple<int, string>));\n            Assert.Equal(new MediaTypeHeaderValue(\"application/xml\"), key.MediaType);\n            Assert.Equal(typeof(Tuple<int, string>), key.ParameterType);\n            Assert.Null(key.SampleDirection);\n            Assert.Equal(String.Empty, key.ControllerName);\n            Assert.Equal(String.Empty, key.ActionName);\n            Assert.Empty(key.ParameterNames);\n        }\n\n        [Fact]\n        public void Constructor_FourParameters()\n        {\n            HelpPageSampleKey key = new HelpPageSampleKey(SampleDirection.Request, \"myController\", \"myAction\", new[] { \"id\", \"name\" });\n            Assert.Null(key.MediaType);\n            Assert.Null(key.ParameterType);\n            Assert.Equal(SampleDirection.Request, key.SampleDirection.Value);\n            Assert.Equal(\"myController\", key.ControllerName);\n            Assert.Equal(\"myAction\", key.ActionName);\n            Assert.NotEmpty(key.ParameterNames);\n            Assert.True(key.ParameterNames.SetEquals(new[] { \"name\", \"id\" }));\n        }\n\n        [Fact]\n        public void Constructor_FiveParameters()\n        {\n            HelpPageSampleKey key = new HelpPageSampleKey(new MediaTypeHeaderValue(\"application/xml\"), SampleDirection.Request, \"myController\", \"myAction\", new[] { \"id\", \"name\" });\n            Assert.Equal(new MediaTypeHeaderValue(\"application/xml\"), key.MediaType);\n            Assert.Null(key.ParameterType);\n            Assert.Equal(SampleDirection.Request, key.SampleDirection.Value);\n            Assert.Equal(\"myController\", key.ControllerName);\n            Assert.Equal(\"myAction\", key.ActionName);\n            Assert.NotEmpty(key.ParameterNames);\n            Assert.True(key.ParameterNames.SetEquals(new[] { \"name\", \"id\" }));\n        }\n\n        public static IEnumerable<object[]> Constructor_ThrowsArgumentNullException_PropertyData\n        {\n            get\n            {\n                yield return new Func<object>[] { () => new HelpPageSampleKey(null, typeof(Tuple<int, string>)) };\n                yield return new Func<object>[] { () => new HelpPageSampleKey(new MediaTypeHeaderValue(\"application/xml\"), null) };\n\n                yield return new Func<object>[] { () => new HelpPageSampleKey(SampleDirection.Request, \"c\", \"a\", null) };\n                yield return new Func<object>[] { () => new HelpPageSampleKey(SampleDirection.Request, null, \"a\", new string[0]) };\n                yield return new Func<object>[] { () => new HelpPageSampleKey(SampleDirection.Request, \"c\", null, new string[0]) };\n\n                yield return new Func<object>[] { () => new HelpPageSampleKey(null, SampleDirection.Request, \"c\", \"a\", new string[0]) };\n                yield return new Func<object>[] { () => new HelpPageSampleKey(new MediaTypeHeaderValue(\"application/xml\"), SampleDirection.Request, \"c\", \"a\", null) };\n                yield return new Func<object>[] { () => new HelpPageSampleKey(new MediaTypeHeaderValue(\"application/xml\"), SampleDirection.Request, null, \"a\", new string[0]) };\n                yield return new Func<object>[] { () => new HelpPageSampleKey(new MediaTypeHeaderValue(\"application/xml\"), SampleDirection.Request, \"c\", null, new string[0]) };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"Constructor_ThrowsArgumentNullException_PropertyData\")]\n        public void Constructor_ThrowsArgumentNullException(Func<object> constructorDelegate)\n        {\n            Assert.Throws(typeof(ArgumentNullException), constructorDelegate);\n        }\n\n        public static IEnumerable<object[]> Constructor_ThrowsArgumentException_PropertyData\n        {\n            get\n            {\n                yield return new Func<object>[] { () => new HelpPageSampleKey(SampleDirection.Request, null, \"a\", new string[0])};\n                yield return new Func<object>[] { () => new HelpPageSampleKey(SampleDirection.Request, \"c\", null, new string[0]) };\n\n                yield return new Func<object>[] { () => new HelpPageSampleKey(new MediaTypeHeaderValue(\"application/xml\"), SampleDirection.Request, null, \"a\", new string[0]) };\n                yield return new Func<object>[] { () => new HelpPageSampleKey(new MediaTypeHeaderValue(\"application/xml\"), SampleDirection.Request, \"c\", null, new string[0]) };\n            }\n        }\n\n        public static IEnumerable<object[]> Constructor_ThrowsInvalidEnumArgumentException_PropertyData\n        {\n            get\n            {\n                yield return new Func<object>[] { () => new HelpPageSampleKey((SampleDirection)10, \"c\", \"a\", new string[0]) };\n                yield return new Func<object>[] { () => new HelpPageSampleKey(new MediaTypeHeaderValue(\"application/xml\"), (SampleDirection)9, \"c\", \"a\", new string[0]) };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"Constructor_ThrowsInvalidEnumArgumentException_PropertyData\")]\n        public void Constructor_ThrowsInvalidEnumArgumentException(Func<object> constructorDelegate)\n        {\n            Assert.Throws(typeof(InvalidEnumArgumentException), constructorDelegate);\n        }\n\n        public static IEnumerable<object[]> Equals_ReturnsTrue_PropertyData\n        {\n            get\n            {\n                HelpPageSampleKey key1 = new HelpPageSampleKey(SampleDirection.Request, \"myController\", \"myAction\", new[] { \"id\", \"name\" });\n                HelpPageSampleKey key2 = new HelpPageSampleKey(SampleDirection.Request, \"MyController\", \"myAction\", new[] { \"ID\", \"name\" });\n                yield return new object[] { key1, key2 };\n\n                key1 = new HelpPageSampleKey(SampleDirection.Request, \"myController\", \"myAction\", new[] { \"id\", \"name\" });\n                key2 = new HelpPageSampleKey((SampleDirection)0, \"MyController\", \"myAction\", new[] { \"ID\", \"name\" });\n                yield return new object[] { key1, key2 };\n\n                key1 = new HelpPageSampleKey(new MediaTypeHeaderValue(\"text/custom\"), typeof(Tuple<int, string>));\n                key2 = new HelpPageSampleKey(new MediaTypeHeaderValue(\"TEXT/custom\"), typeof(Tuple<int, string>));\n                yield return new object[] { key1, key2 };\n\n                key1 = new HelpPageSampleKey(new MediaTypeHeaderValue(\"text/custom\"), SampleDirection.Request, \"controller\", \"myAction\", new string[0]);\n                key2 = new HelpPageSampleKey(new MediaTypeHeaderValue(\"text/custom\"), SampleDirection.Request, \"CONTROLLER\", \"MYACTION\", new string[0]);\n                yield return new object[] { key1, key2 };\n\n                key1 = new HelpPageSampleKey(new MediaTypeHeaderValue(\"text/custom\"), SampleDirection.Response, \"controller\", \"myAction\", new[] { \"ID\", \"NAME\" });\n                key2 = new HelpPageSampleKey(new MediaTypeHeaderValue(\"text/custom\"), SampleDirection.Response, \"CONTROLLER\", \"MYACTION\", new[] { \"id\", \"name\" });\n                yield return new object[] { key1, key2 };\n\n                key1 = new HelpPageSampleKey(new MediaTypeHeaderValue(\"text/custom\"), SampleDirection.Request, \"controller\", \"action\", new string[0]);\n                key2 = new HelpPageSampleKey(new MediaTypeHeaderValue(\"text/custom\"), SampleDirection.Request, \"controller\", \"action\", new string[0]);\n                yield return new object[] { key1, key2 };\n\n                key1 = new HelpPageSampleKey(new MediaTypeHeaderValue(\"text/custom\"), SampleDirection.Response, \"controller\", \"action\", new string[0]);\n                key2 = new HelpPageSampleKey(new MediaTypeHeaderValue(\"text/custom\"), (SampleDirection)1, \"controller\", \"action\", new string[0]);\n                yield return new object[] { key1, key2 };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"Equals_ReturnsTrue_PropertyData\")]\n        public void Equals_ReturnsTrue(HelpPageSampleKey key1, HelpPageSampleKey key2)\n        {\n            Assert.True(key1.Equals(key2));\n        }\n\n        public static IEnumerable<object[]> Equals_ReturnsFalse_PropertyData\n        {\n            get\n            {\n                HelpPageSampleKey key1 = new HelpPageSampleKey(SampleDirection.Request, \"myController\", \"myAction\", new[] { \"id\", \"name\" });\n                HelpPageSampleKey key2 = new HelpPageSampleKey(SampleDirection.Request, \"MyController\", \"myAction\", new string[0]);\n                yield return new object[] { key1, key2 };\n\n                key1 = new HelpPageSampleKey(new MediaTypeHeaderValue(\"text/custom\"), typeof(Tuple<int, int>));\n                key2 = new HelpPageSampleKey(new MediaTypeHeaderValue(\"TEXT/custom\"), typeof(Tuple<int, string>));\n                yield return new object[] { key1, key2 };\n\n                key1 = new HelpPageSampleKey(new MediaTypeHeaderValue(\"text/custom\"), SampleDirection.Request, \"controller\", \"action\", new string[0]);\n                key2 = new HelpPageSampleKey(new MediaTypeHeaderValue(\"TEXT/custom\"), SampleDirection.Response, \"controller\", \"action\", new string[0]);\n                yield return new object[] { key1, key2 };\n\n                key1 = new HelpPageSampleKey(new MediaTypeHeaderValue(\"text/custom\"), (SampleDirection)0, \"controller\", \"action\", new string[0]);\n                key2 = new HelpPageSampleKey(new MediaTypeHeaderValue(\"TEXT/custom\"), (SampleDirection)1, \"controller\", \"action\", new string[0]);\n                yield return new object[] { key1, key2 };\n\n                key1 = new HelpPageSampleKey(new MediaTypeHeaderValue(\"text/custom\"), SampleDirection.Request, \"controller\", \"action\", new string[] { \"\" });\n                key2 = new HelpPageSampleKey(new MediaTypeHeaderValue(\"text/custom\"), SampleDirection.Request, \"controller\", \"action\", new string[0]);\n                yield return new object[] { key1, key2 };\n\n                key1 = new HelpPageSampleKey(new MediaTypeHeaderValue(\"text/custom\"), typeof(Tuple<int, int>));\n                key2 = new HelpPageSampleKey(new MediaTypeHeaderValue(\"text/custom\"), SampleDirection.Request, \"controller\", \"action\", new string[0]);\n                yield return new object[] { key1, key2 };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"Equals_ReturnsFalse_PropertyData\")]\n        public void Equals_ReturnsFalse(HelpPageSampleKey key1, HelpPageSampleKey key2)\n        {\n            Assert.False(key1.Equals(key2));\n        }\n\n        [Theory]\n        [PropertyData(\"Equals_ReturnsTrue_PropertyData\")]\n        public void GetHashCode_ReturnsSame(HelpPageSampleKey key1, HelpPageSampleKey key2)\n        {\n            Assert.Equal(key1.GetHashCode(), key2.GetHashCode());\n        }\n\n        [Theory]\n        [PropertyData(\"Equals_ReturnsFalse_PropertyData\")]\n        public void GetHashCode_ReturnsDifferent(HelpPageSampleKey key1, HelpPageSampleKey key2)\n        {\n            Assert.NotEqual(key1.GetHashCode(), key2.GetHashCode());\n        }\n    }\n}\n"
  },
  {
    "path": "test/WebApiHelpPage.Test/Helpers/ApiDescriptionHelpers.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http.Formatting;\nusing System.Web.Http;\nusing System.Web.Http.Controllers;\nusing System.Web.Http.Description;\n\nnamespace WebApiHelpPageWebHost.UnitTest.Helpers\n{\n    public static class ApiDescriptionHelpers\n    {\n        public static ApiDescription GetApiDescription(HttpConfiguration config, string controllerName, string actionName, params string[] parameterNames)\n        {\n            if (config == null)\n            {\n                config = new HttpConfiguration();\n                config.Formatters.Clear();\n                config.Formatters.Add(new XmlMediaTypeFormatter());\n                config.Formatters.Add(new JsonMediaTypeFormatter());\n                config.Routes.MapHttpRoute(\"Default\", \"{controller}\");\n            }\n            HashSet<string> parameterSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);\n            foreach (var apiDescription in config.Services.GetApiExplorer().ApiDescriptions)\n            {\n                HttpActionDescriptor actionDescriptor = apiDescription.ActionDescriptor;\n                if (String.Equals(actionDescriptor.ControllerDescriptor.ControllerName, controllerName, StringComparison.OrdinalIgnoreCase) &&\n                    String.Equals(actionDescriptor.ActionName, actionName, StringComparison.OrdinalIgnoreCase))\n                {\n                    HashSet<string> actionParameterSet = new HashSet<string>(actionDescriptor.GetParameters().Select(p => p.ParameterName), StringComparer.OrdinalIgnoreCase);\n                    if (parameterSet.SetEquals(actionParameterSet))\n                    {\n                        return apiDescription;\n                    }\n                }\n            }\n\n            return null;\n        }\n    }\n}\n"
  },
  {
    "path": "test/WebApiHelpPage.Test/Helpers/CustomTypes.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Runtime.Serialization;\nusing System.Web.Http.Description;\nusing System.Xml.Serialization;\nusing Newtonsoft.Json;\nusing ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions;\n\nnamespace WebApiHelpPageWebHost.UnitTest\n{\n    public class MyGenericType<T, T2>\n    {\n        public T MyProperty { get; set; }\n\n        public T2 MyProperty2 { get; set; }\n    }\n\n    public class Customer\n    {\n        public int Id { get; set; }\n\n        public string Name { get; set; }\n\n        public List<Order> Orders { get; set; }\n    }\n\n    public class Order\n    {\n        public Guid Id { get; set; }\n\n        public Dictionary<Item, string> Items { get; set; }\n\n        public DateTime ShipDate { get; set; }\n    }\n\n    public class Item\n    {\n        public Customer Buyer { get; set; }\n\n        public string Name { get; set; }\n\n        public double Price { get; set; }\n    }\n\n    public class ComplexTypeWithPublicFields\n    {\n        public string Name;\n        public Guid Id;\n        public Item item;\n    }\n\n    public struct ComplexStruct\n    {\n        public string Name;\n        public Guid Id;\n\n        public DateTime Time { get; set; }\n\n        public DateTimeKind Kind { get; set; }\n    }\n\n    public class TypeWithNoDefaultConstructor\n    {\n        public TypeWithNoDefaultConstructor(int id, string name)\n        {\n        }\n    }\n\n    internal class NonPublicType { }\n\n    public enum EmptyEnum { }\n\n    [ModelName(\"CustomUser\")]\n    public class User\n    {\n        /// <summary>\n        /// User name.\n        /// </summary>\n        [Required]\n        public string Name { get; set; }\n\n        /// <summary>\n        /// Age of the user.\n        /// </summary>\n        [Required]\n        [Range(1, 200)]\n        public int Age { get; set; }\n\n        /// <summary>\n        /// User comment.\n        /// </summary>\n        [StringLength(100)]\n        public string Comment { get; set; }\n\n        /// <summary>\n        /// U.S. phone number.\n        /// </summary>\n        public int PhoneNumber { get; set; }\n    }\n\n    [ModelName(\"MyAddress\")]\n    public class Address\n    {\n        [DataType(DataType.PostalCode)]\n        public string ZipCode { get; set; }\n\n        /// <summary>\n        /// Street name.\n        /// </summary>\n        [RegularExpression(\"[a-z]\")]\n        public string Street { get; set; }\n\n        /// <summary>\n        /// Geo-coordinate of the address.\n        /// </summary>\n        [MinLength(2)]\n        [MaxLength(3)]\n        public int[] Coordinates { get; set; }\n    }\n\n    [DataContract]\n    public struct StructDataContractType\n    {\n        public int NoMember { get; set; }\n\n        [DataMember]\n        public int Member { get; set; }\n\n        public int NoField { get; set; }\n\n        [DataMember]\n        public int Field { get; set; }\n    }\n\n    [DataContract]\n    public enum EnumDataContractType\n    {\n        [EnumMember]\n        Value,\n        NoValue\n    }\n\n    [DataContract]\n    public class DataContractType\n    {\n        public int NoMember { get; set; }\n\n        [DataMember]\n        public int Member { get; set; }\n\n        public int NoField { get; set; }\n\n        [DataMember]\n        public int Field { get; set; }\n    }\n\n    public class TypeWithIgnores\n    {\n        [XmlIgnore]\n        public int NoXmlMember { get; set; }\n\n        [JsonIgnore]\n        public int NoJsonMember { get; set; }\n\n        [ApiExplorerSettings(IgnoreApi = true)]\n        public int NoMember { get; set; }\n\n        [ApiExplorerSettings(IgnoreApi = false)]\n        public int Member { get; set; }\n\n        [IgnoreDataMember]\n        public int NoDataMember{ get; set; }\n\n        [DataMember]\n        public int DataMember { get; set; }\n\n        public int RegularMember { get; set; }\n\n        [XmlIgnore]\n        public int NoXmlField;\n\n        [JsonIgnore]\n        public int NoJsonField;\n\n        [IgnoreDataMember]\n        public int NoDataField;\n\n        [NonSerialized]\n        public int NoSerializedField;\n\n        [ApiExplorerSettings(IgnoreApi = true)]\n        public int NoField;\n\n        [ApiExplorerSettings(IgnoreApi = false)]\n        public int Field;\n\n        [DataMember]\n        public int DataField;\n\n        public int RegularField;\n    }\n\n    public class DerivedType : TypeWithIgnores\n    {\n        public string DerivedField;\n\n        public string DerivedMember { get; set; }\n    }\n\n    public class PropertyAliasType\n    {\n        [DataMember(Name = \"RenamedField\")]\n        public string Bar;\n\n        [JsonProperty(\"RenamedMember\")]\n        public string Foo { get; set; }\n\n        [JsonProperty(\"JsonField\")]\n        [DataMember(Name = \"XmlField\")]\n        public string FooBar;\n\n        [JsonProperty(\"JsonProperty\")]\n        [DataMember(Name = \"XmlProperty\")]\n        public string Property4 { get; set; }\n    }\n\n    [DataContract]\n    public class DataContractPropertyAliasType\n    {\n        [DataMember(Name = \"RenamedField\")]\n        public string Bar;\n\n        [JsonProperty(\"RenamedMember\")]\n        public string Foo { get; set; }\n\n        [JsonProperty(\"JsonField\")]\n        [DataMember(Name = \"XmlField\")]\n        public string FooBar;\n\n        [JsonProperty(\"JsonProperty\")]\n        [DataMember(Name = \"XmlProperty\")]\n        public string Property4 { get; set; }\n    }\n\n    public class MultipleDataAnnotations\n    {\n        [Range(1, 200)]\n        [StringLength(100)]\n        [DataType(DataType.PostalCode)]\n        [RegularExpression(\"[a-z]\")]\n        [Required]\n        [MinLength(2)]\n        [MaxLength(3)]\n        public string Property { get; set; }\n\n        [MinLength(2)]\n        [MaxLength(3)]\n        [Range(1, 200)]\n        [StringLength(100)]\n        [DataType(DataType.PostalCode)]\n        [RegularExpression(\"[a-z]\")]\n        public string OptionalProperty { get; set; }\n    }\n}\n\nnamespace WebApiHelpPageWebHost.UnitTest2\n{\n    public class Customer\n    {\n        public string Name { get; set; }\n    }\n}"
  },
  {
    "path": "test/WebApiHelpPage.Test/HelppageSampleGeneratorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.IO;\nusing System.Net;\nusing System.Net.Http;\nusing System.Net.Http.Formatting;\nusing System.Net.Http.Headers;\nusing System.Threading.Tasks;\nusing System.Web.Http.Description;\nusing Microsoft.TestCommon;\nusing Moq;\nusing ROOT_PROJECT_NAMESPACE.Areas.HelpPage;\nusing WebApiHelpPageWebHost.UnitTest.Helpers;\n\nnamespace WebApiHelpPageWebHost.UnitTest\n{\n    public class HelpPageSampleGeneratorTest\n    {\n        [Fact]\n        public void Constructor()\n        {\n            HelpPageSampleGenerator sampleGenerator = new HelpPageSampleGenerator();\n            Assert.NotNull(sampleGenerator.SampleObjects);\n            Assert.NotNull(sampleGenerator.ActionSamples);\n            Assert.NotNull(sampleGenerator.ActualHttpMessageTypes);\n        }\n\n        [Fact]\n        public void GetSampleRequests_Empty()\n        {\n            HelpPageSampleGenerator sampleGenerator = new HelpPageSampleGenerator();\n            ApiDescription apiDescription = ApiDescriptionHelpers.GetApiDescription(null, \"Values\", \"Get\");\n            IDictionary<MediaTypeHeaderValue, object> samples = sampleGenerator.GetSampleRequests(apiDescription);\n            Assert.Empty(samples);\n        }\n\n        [Fact]\n        public void GetSampleRequests_FromSampleObjects()\n        {\n            HelpPageSampleGenerator sampleGenerator = new HelpPageSampleGenerator();\n            sampleGenerator.SampleObjects.Add(typeof(string), \"sample value\");\n            ApiDescription apiDescription = ApiDescriptionHelpers.GetApiDescription(null, \"Values\", \"Post\", \"value\");\n            IDictionary<MediaTypeHeaderValue, object> samples = sampleGenerator.GetSampleRequests(apiDescription);\n            Assert.NotEmpty(samples);\n            foreach (var samplePair in samples)\n            {\n                Assert.Contains(\"sample value\", ((TextSample)samplePair.Value).Text);\n            }\n        }\n\n        [Fact]\n        public void GetSampleRequests_FromSampleObjects_AndSettingActualRequestTypes()\n        {\n            HelpPageSampleGenerator sampleGenerator = new HelpPageSampleGenerator();\n            sampleGenerator.ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, \"values\", \"options\", new[] { \"request\" }), typeof(string));\n            sampleGenerator.SampleObjects.Add(typeof(string), \"sample value\");\n            ApiDescription apiDescription = ApiDescriptionHelpers.GetApiDescription(null, \"values\", \"options\", \"request\");\n            IDictionary<MediaTypeHeaderValue, object> samples = sampleGenerator.GetSampleRequests(apiDescription);\n            Assert.NotEmpty(samples);\n            foreach (var samplePair in samples)\n            {\n                Assert.Contains(\"sample value\", ((TextSample)samplePair.Value).Text);\n            }\n        }\n\n        [Fact]\n        public void GetSampleRequests_FromActionSamples_BasedOnMediaTypeAndType()\n        {\n            HelpPageSampleGenerator sampleGenerator = new HelpPageSampleGenerator();\n            var sample = new TextSample(\"test\");\n            sampleGenerator.ActionSamples.Add(new HelpPageSampleKey(new MediaTypeHeaderValue(\"application/json\"), typeof(Tuple<int, string>)), sample);\n            ApiDescription apiDescription = ApiDescriptionHelpers.GetApiDescription(null, \"Values\", \"Patch\", \"valuePair\");\n            IDictionary<MediaTypeHeaderValue, object> samples = sampleGenerator.GetSampleRequests(apiDescription);\n            Assert.NotEmpty(samples);\n            object result;\n            samples.TryGetValue(new MediaTypeHeaderValue(\"application/json\"), out result);\n            Assert.Same(sample, result);\n            samples.TryGetValue(new MediaTypeHeaderValue(\"application/xml\"), out result);\n            Assert.NotSame(sample, result);\n        }\n\n        [Fact]\n        public void GetSampleRequests_FromActionSamples_BasedOnMediaTypeAndNames()\n        {\n            HelpPageSampleGenerator sampleGenerator = new HelpPageSampleGenerator();\n            var sample = new TextSample(\"test\");\n            sampleGenerator.ActionSamples.Add(new HelpPageSampleKey(new MediaTypeHeaderValue(\"application/xml\"), SampleDirection.Request, \"Values\", \"Put\", new[] { \"valuePairCollection\" }), sample);\n            ApiDescription apiDescription = ApiDescriptionHelpers.GetApiDescription(null, \"Values\", \"Put\", \"valuePairCollection\");\n            IDictionary<MediaTypeHeaderValue, object> samples = sampleGenerator.GetSampleRequests(apiDescription);\n            Assert.NotEmpty(samples);\n            object result;\n            samples.TryGetValue(new MediaTypeHeaderValue(\"application/xml\"), out result);\n            Assert.Same(sample, result);\n            samples.TryGetValue(new MediaTypeHeaderValue(\"application/json\"), out result);\n            Assert.NotSame(sample, result);\n        }\n\n        [Fact]\n        public void GetSampleRequests_FromActionSamples_WhenTheParameterIsHttpRequestMessage()\n        {\n            HelpPageSampleGenerator sampleGenerator = new HelpPageSampleGenerator();\n            var sample = new TextSample(\"test\");\n            sampleGenerator.ActionSamples.Add(new HelpPageSampleKey(new MediaTypeHeaderValue(\"plain/text\"), SampleDirection.Request, \"Values\", \"Options\", new[] { \"request\" }), sample);\n            ApiDescription apiDescription = ApiDescriptionHelpers.GetApiDescription(null, \"Values\", \"Options\", \"request\");\n            IDictionary<MediaTypeHeaderValue, object> samples = sampleGenerator.GetSampleRequests(apiDescription);\n            Assert.NotEmpty(samples);\n            object result;\n            samples.TryGetValue(new MediaTypeHeaderValue(\"plain/text\"), out result);\n            Assert.Same(sample, result);\n            samples.TryGetValue(new MediaTypeHeaderValue(\"application/json\"), out result);\n            Assert.Null(result);\n        }\n\n        [Fact]\n        public void GetSampleResponses_Empty()\n        {\n            HelpPageSampleGenerator sampleGenerator = new HelpPageSampleGenerator();\n            ApiDescription apiDescription = ApiDescriptionHelpers.GetApiDescription(null, \"Values\", \"Delete\", \"id\");\n            IDictionary<MediaTypeHeaderValue, object> samples = sampleGenerator.GetSampleResponses(apiDescription);\n            Assert.Empty(samples);\n        }\n\n        [Fact]\n        public void GetSampleResponses_FromSampleObjects()\n        {\n            HelpPageSampleGenerator sampleGenerator = new HelpPageSampleGenerator();\n            sampleGenerator.SampleObjects.Add(typeof(string), \"sample value\");\n            ApiDescription apiDescription = ApiDescriptionHelpers.GetApiDescription(null, \"Values\", \"Get\", \"id\");\n            IDictionary<MediaTypeHeaderValue, object> samples = sampleGenerator.GetSampleResponses(apiDescription);\n            Assert.NotEmpty(samples);\n            foreach (var samplePair in samples)\n            {\n                Assert.Contains(\"sample value\", ((TextSample)samplePair.Value).Text);\n            }\n        }\n\n        [Fact]\n        public void GetSampleResponses_FromSampleObjects_AndSettingActualResponseTypes()\n        {\n            HelpPageSampleGenerator sampleGenerator = new HelpPageSampleGenerator();\n            sampleGenerator.ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, \"values\", \"post\", new[] { \"value\" }), typeof(string));\n            sampleGenerator.SampleObjects.Add(typeof(string), \"sample value\");\n            ApiDescription apiDescription = ApiDescriptionHelpers.GetApiDescription(null, \"values\", \"post\", \"value\");\n            IDictionary<MediaTypeHeaderValue, object> samples = sampleGenerator.GetSampleResponses(apiDescription);\n            Assert.NotEmpty(samples);\n            foreach (var samplePair in samples)\n            {\n                Assert.Contains(\"sample value\", ((TextSample)samplePair.Value).Text);\n            }\n        }\n\n        [Fact]\n        public void GetSampleResponses_FromActionSamples_BasedOnMediaTypeAndType()\n        {\n            HelpPageSampleGenerator sampleGenerator = new HelpPageSampleGenerator();\n            var sample = new TextSample(\"test\");\n            sampleGenerator.ActionSamples.Add(new HelpPageSampleKey(new MediaTypeHeaderValue(\"application/json\"), typeof(IEnumerable<string>)), sample);\n            ApiDescription apiDescription = ApiDescriptionHelpers.GetApiDescription(null, \"Values\", \"Get\", new string[0]);\n            IDictionary<MediaTypeHeaderValue, object> samples = sampleGenerator.GetSampleResponses(apiDescription);\n            Assert.NotEmpty(samples);\n            object result;\n            samples.TryGetValue(new MediaTypeHeaderValue(\"application/json\"), out result);\n            Assert.Same(sample, result);\n            samples.TryGetValue(new MediaTypeHeaderValue(\"application/xml\"), out result);\n            Assert.NotSame(sample, result);\n        }\n\n        [Fact]\n        public void GetSampleResponses_FromActionSamples_BasedOnMediaTypeAndNames()\n        {\n            HelpPageSampleGenerator sampleGenerator = new HelpPageSampleGenerator();\n            var sample = new TextSample(\"test\");\n            sampleGenerator.ActionSamples.Add(new HelpPageSampleKey(new MediaTypeHeaderValue(\"application/xml\"), SampleDirection.Response, \"Values\", \"Get\", new[] { \"id\" }), sample);\n            ApiDescription apiDescription = ApiDescriptionHelpers.GetApiDescription(null, \"Values\", \"Get\", \"id\");\n            IDictionary<MediaTypeHeaderValue, object> samples = sampleGenerator.GetSampleResponses(apiDescription);\n            Assert.NotEmpty(samples);\n            object result;\n            samples.TryGetValue(new MediaTypeHeaderValue(\"application/xml\"), out result);\n            Assert.Same(sample, result);\n            samples.TryGetValue(new MediaTypeHeaderValue(\"application/json\"), out result);\n            Assert.NotSame(sample, result);\n        }\n\n        [Fact]\n        public void GetSampleResponses_FromActionSamples_WhenTheReturnTypeIsHttpResponseMessage()\n        {\n            HelpPageSampleGenerator sampleGenerator = new HelpPageSampleGenerator();\n            var sample = new TextSample(\"test\");\n            sampleGenerator.ActionSamples.Add(new HelpPageSampleKey(new MediaTypeHeaderValue(\"plain/text\"), SampleDirection.Response, \"Values\", \"Post\", new[] { \"value\" }), sample);\n            ApiDescription apiDescription = ApiDescriptionHelpers.GetApiDescription(null, \"Values\", \"Post\", \"value\");\n            IDictionary<MediaTypeHeaderValue, object> samples = sampleGenerator.GetSampleResponses(apiDescription);\n            Assert.NotEmpty(samples);\n            object result;\n            samples.TryGetValue(new MediaTypeHeaderValue(\"plain/text\"), out result);\n            Assert.Same(sample, result);\n            samples.TryGetValue(new MediaTypeHeaderValue(\"application/json\"), out result);\n            Assert.Null(result);\n        }\n\n        [Fact]\n        public void GetActionSample_ReturnNullWhenSampleNotProvided()\n        {\n            HelpPageSampleGenerator sampleGenerator = new HelpPageSampleGenerator();\n            Assert.Null(\n                sampleGenerator.GetActionSample(\n                    \"a\",\n                    \"b\",\n                    new string[0],\n                    typeof(string),\n                    new XmlMediaTypeFormatter(),\n                    new MediaTypeHeaderValue(\"text/xml\"),\n                    SampleDirection.Response\n                ));\n        }\n\n        [Fact]\n        public void WriteSampleObjectUsingFormatter_ReturnsFormatterError()\n        {\n            Mock<MediaTypeFormatter> bogusFormatter = new Mock<MediaTypeFormatter>();\n            bogusFormatter.Setup(f => f.CanWriteType(It.IsAny<Type>())).Returns(true);\n            bogusFormatter.Setup(f => f.WriteToStreamAsync(It.IsAny<Type>(), It.IsAny<object>(), It.IsAny<Stream>(), It.IsAny<HttpContent>(), It.IsAny<TransportContext>())).Returns(() =>\n            {\n                throw new ApplicationException(\"formatter failed.\");\n            });\n            HelpPageSampleGenerator sampleGenerator = new HelpPageSampleGenerator();\n            InvalidSample sampleNotProvided = Assert.IsType<InvalidSample>(\n                sampleGenerator.WriteSampleObjectUsingFormatter(\n                    bogusFormatter.Object,\n                    \"hello world\",\n                    typeof(string),\n                    new MediaTypeHeaderValue(\"text/json\")\n                ));\n            Assert.Equal(\"An exception has occurred while using the formatter 'MediaTypeFormatterProxy' to generate sample for media type 'text/json'. Exception message: formatter failed.\",\n                sampleNotProvided.ErrorMessage);\n        }\n\n        [Fact]\n        public void WriteSampleObjectUsingFormatter_TryFormattingNonXmlSamples_DoesNotThrow()\n        {\n            Mock<MediaTypeFormatter> customFormatter = new Mock<MediaTypeFormatter>();\n            customFormatter.Setup(f => f.CanWriteType(It.IsAny<Type>())).Returns(true);\n            customFormatter.Setup(f => f.WriteToStreamAsync(It.IsAny<Type>(), It.IsAny<object>(), It.IsAny<Stream>(), It.IsAny<HttpContent>(), It.IsAny<TransportContext>())).Returns(\n            (Type type, object obj, Stream stream, HttpContent content, TransportContext context) =>\n            {\n                StreamWriter writer = new StreamWriter(stream);\n                writer.Write(\"some\\r\\nnon xml string\");\n                writer.Flush();\n                TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();\n                tcs.SetResult(null);\n                return tcs.Task;\n            });\n            HelpPageSampleGenerator sampleGenerator = new HelpPageSampleGenerator();\n            TextSample sample = Assert.IsType<TextSample>(\n                sampleGenerator.WriteSampleObjectUsingFormatter(\n                    customFormatter.Object,\n                    \"hello world\",\n                    typeof(string),\n                    new MediaTypeHeaderValue(\"text/xml\")\n                ));\n            Assert.Equal(\"some\\r\\nnon xml string\", sample.Text);\n        }\n\n        [Fact]\n        public void WriteSampleObjectUsingFormatter_TryFormattingNonJsonSamples_DoesNotThrow()\n        {\n            Mock<MediaTypeFormatter> customFormatter = new Mock<MediaTypeFormatter>();\n            customFormatter.Setup(f => f.CanWriteType(It.IsAny<Type>())).Returns(true);\n            customFormatter.Setup(f => f.WriteToStreamAsync(It.IsAny<Type>(), It.IsAny<object>(), It.IsAny<Stream>(), It.IsAny<HttpContent>(), It.IsAny<TransportContext>())).Returns(\n            (Type type, object obj, Stream stream, HttpContent content, TransportContext context) =>\n            {\n                StreamWriter writer = new StreamWriter(stream);\n                writer.Write(\"some\\r\\nnon <json> string\");\n                writer.Flush();\n                TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();\n                tcs.SetResult(null);\n                return tcs.Task;\n            });\n            HelpPageSampleGenerator sampleGenerator = new HelpPageSampleGenerator();\n            TextSample sample = Assert.IsType<TextSample>(\n                sampleGenerator.WriteSampleObjectUsingFormatter(\n                    customFormatter.Object,\n                    \"hello world\",\n                    typeof(string),\n                    new MediaTypeHeaderValue(\"text/json\")\n                ));\n            Assert.Equal(\"some\\r\\nnon <json> string\", sample.Text);\n        }\n\n        [Fact]\n        public void WriteSampleObjectUsingFormatter_UnwrapsAggregateException()\n        {\n            Mock<MediaTypeFormatter> bogusFormatter = new Mock<MediaTypeFormatter>();\n            bogusFormatter.Setup(f => f.CanWriteType(It.IsAny<Type>())).Returns(true);\n            bogusFormatter.Setup(f => f.WriteToStreamAsync(It.IsAny<Type>(), It.IsAny<object>(), It.IsAny<Stream>(), It.IsAny<HttpContent>(), It.IsAny<TransportContext>())).Returns(() =>\n            {\n                throw new AggregateException(new FormatException(\"Invalid format.\"));\n            });\n            HelpPageSampleGenerator sampleGenerator = new HelpPageSampleGenerator();\n            InvalidSample sampleNotProvided = Assert.IsType<InvalidSample>(\n                sampleGenerator.WriteSampleObjectUsingFormatter(\n                    bogusFormatter.Object,\n                    \"hello world\",\n                    typeof(string),\n                    new MediaTypeHeaderValue(\"text/json\")\n                ));\n            Assert.Equal(\"An exception has occurred while using the formatter 'MediaTypeFormatterProxy' to generate sample for media type 'text/json'. Exception message: Invalid format.\",\n                sampleNotProvided.ErrorMessage);\n        }\n\n        [Fact]\n        public void ResolveType_ThrowsInvalidEnumArgumentException()\n        {\n            Assert.Throws(typeof(InvalidEnumArgumentException), () =>\n            {\n                Collection<MediaTypeFormatter> formatters;\n                HelpPageSampleGenerator sampleGenerator = new HelpPageSampleGenerator();\n                sampleGenerator.ResolveType(new ApiDescription(), \"c\", \"a\", new[] { \"p\" }, (SampleDirection)78, out formatters);\n            });\n        }\n\n        public static IEnumerable<object[]> GetSample_ThrowsArgumentNullException_PropertyData\n        {\n            get\n            {\n                yield return new Action[] { () =>\n                {\n                    HelpPageSampleGenerator sampleGenerator = new HelpPageSampleGenerator();\n                    sampleGenerator.GetSample(null, SampleDirection.Request);\n                }};\n            }\n        }\n\n        public static IEnumerable<object[]> ResolveType_ThrowsArgumentNullException_PropertyData\n        {\n            get\n            {\n                yield return new Action[] { () =>\n                {\n                    HelpPageSampleGenerator sampleGenerator = new HelpPageSampleGenerator();\n                    Collection<MediaTypeFormatter> formatters;\n                    sampleGenerator.ResolveType(null, \"a\", \"c\", new string[0], SampleDirection.Request, out formatters);\n                }};\n            }\n        }\n\n        public static IEnumerable<object[]> WriteSampleObjectUsingFormatter_ThrowsArgumentNullException_PropertyData\n        {\n            get\n            {\n                yield return new Action[] { () =>\n                {\n                    HelpPageSampleGenerator sampleGenerator = new HelpPageSampleGenerator();\n                    sampleGenerator.WriteSampleObjectUsingFormatter(null, \"sample\", typeof(string), new MediaTypeHeaderValue(\"text/xml\"));\n                }};\n                yield return new Action[] { () =>\n                {\n                    HelpPageSampleGenerator sampleGenerator = new HelpPageSampleGenerator();\n                    sampleGenerator.WriteSampleObjectUsingFormatter(new XmlMediaTypeFormatter(), \"sample\", typeof(string), null);\n                }};\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"GetSample_ThrowsArgumentNullException_PropertyData\")]\n        [PropertyData(\"ResolveType_ThrowsArgumentNullException_PropertyData\")]\n        [PropertyData(\"WriteSampleObjectUsingFormatter_ThrowsArgumentNullException_PropertyData\")]\n        public void Method_ThrowsArgumentNullException(Action constructorDelegate)\n        {\n            Assert.Throws(typeof(ArgumentNullException), constructorDelegate);\n        }\n    }\n}\n"
  },
  {
    "path": "test/WebApiHelpPage.Test/ImageSampleTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing Microsoft.TestCommon;\nusing ROOT_PROJECT_NAMESPACE.Areas.HelpPage;\n\nnamespace WebApiHelpPageWebHost.UnitTest\n{\n    public class ImageSampleTest\n    {\n        [Fact]\n        public void Constructor()\n        {\n            ImageSample sample = new ImageSample(\"http://host/image.png\");\n            Assert.Equal(\"http://host/image.png\", sample.Src);\n        }\n\n        [Fact]\n        public void Constructor_ThrowsArgumentNullException()\n        {\n            Assert.Throws<ArgumentNullException>(() => new ImageSample(null));\n        }\n\n        [Fact]\n        public void Equals_ReturnsTrue()\n        {\n            ImageSample sample = new ImageSample(\"http://host/image.png\");\n            Assert.Equal(new ImageSample(\"http://host/image.png\"), sample);\n        }\n\n        [Fact]\n        public void ToString_ReturnsSrc()\n        {\n            ImageSample sample = new ImageSample(\"http://host/image.png\");\n            Assert.Equal(\"http://host/image.png\", sample.ToString());\n        }\n\n        [Fact]\n        public void GetHashCode_ReturnsSrcHashCode()\n        {\n            ImageSample sample = new ImageSample(\"http://host/image.png\");\n            Assert.Equal(\"http://host/image.png\".GetHashCode(), sample.GetHashCode());\n        }\n    }\n}\n"
  },
  {
    "path": "test/WebApiHelpPage.Test/InvalidSampleTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing Microsoft.TestCommon;\nusing ROOT_PROJECT_NAMESPACE.Areas.HelpPage;\n\nnamespace WebApiHelpPageWebHost.UnitTest\n{\n    public class InvalidSampleTest\n    {\n        [Fact]\n        public void Constructor()\n        {\n            InvalidSample sample = new InvalidSample(\"something failed\");\n            Assert.Equal(\"something failed\", sample.ErrorMessage);\n        }\n\n        [Fact]\n        public void Constructor_ThrowsArgumentNullException()\n        {\n            Assert.Throws<ArgumentNullException>(() => new InvalidSample(null));\n        }\n\n        [Fact]\n        public void Equals_ReturnsTrue()\n        {\n            InvalidSample sample = new InvalidSample(\"something failed\");\n            Assert.Equal(new InvalidSample(\"something failed\"), sample);\n        }\n\n        [Fact]\n        public void ToString_ReturnsSrc()\n        {\n            InvalidSample sample = new InvalidSample(\"something failed\");\n            Assert.Equal(\"something failed\", sample.ToString());\n        }\n\n        [Fact]\n        public void GetHashCode_ReturnsSrcHashCode()\n        {\n            InvalidSample sample = new InvalidSample(\"something failed\");\n            Assert.Equal(\"something failed\".GetHashCode(), sample.GetHashCode());\n        }\n    }\n}\n"
  },
  {
    "path": "test/WebApiHelpPage.Test/ModelDescriptionGeneratorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Http;\nusing System.Web.Http;\nusing System.Web.Http.Description;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing ROOT_PROJECT_NAMESPACE.Areas.HelpPage;\nusing ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions;\n\nnamespace WebApiHelpPageWebHost.UnitTest\n{\n    public class ModelDescriptionGeneratorTest\n    {\n        [Theory]\n        [InlineData(typeof(bool), \"Boolean\", \"boolean\")]\n        [InlineData(typeof(byte), \"Byte\", \"byte\")]\n        [InlineData(typeof(char), \"Char\", \"character\")]\n        [InlineData(typeof(Decimal), \"Decimal\", \"decimal number\")]\n        [InlineData(typeof(double), \"Double\", \"decimal number\")]\n        [InlineData(typeof(Guid), \"Guid\", \"globally unique identifier\")]\n        [InlineData(typeof(int), \"Int32\", \"integer\")]\n        [InlineData(typeof(string), \"String\", \"string\")]\n        [InlineData(typeof(float), \"Single\", \"decimal number\")]\n        [InlineData(typeof(long), \"Int64\", \"integer\")]\n        [InlineData(typeof(uint), \"UInt32\", \"unsigned integer\")]\n        [InlineData(typeof(ulong), \"UInt64\", \"unsigned integer\")]\n        [InlineData(typeof(sbyte), \"SByte\", \"signed byte\")]\n        [InlineData(typeof(DateTime), \"DateTime\", \"date\")]\n        [InlineData(typeof(DateTimeOffset), \"DateTimeOffset\", \"date\")]\n        [InlineData(typeof(TimeSpan), \"TimeSpan\", \"time interval\")]\n        [InlineData(typeof(UInt16), \"UInt16\", \"unsigned integer\")]\n        [InlineData(typeof(Int16), \"Int16\", \"integer\")]\n        [InlineData(typeof(Uri), \"Uri\", \"URI\")]\n        public void CreateModelDescription_SimpleTypes(Type type, string expectedModelName, string expectedDocumentation)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);\n\n            SimpleTypeModelDescription simpleModel = Assert.IsType<SimpleTypeModelDescription>(modelGenerator.GetOrCreateModelDescription(type));\n\n            Assert.NotNull(simpleModel);\n            Assert.Equal(expectedModelName, simpleModel.Name);\n            Assert.Equal(type, simpleModel.ModelType);\n            Assert.Equal(expectedDocumentation, simpleModel.Documentation);\n        }\n\n        [Theory]\n        [InlineData(typeof(IEnumerable<string>), typeof(string))]\n        [InlineData(typeof(IEnumerable<List<string>>), typeof(List<string>))]\n        [InlineData(typeof(IEnumerable<int>), typeof(int))]\n        [InlineData(typeof(IEnumerable<Nullable<double>>), typeof(double))]\n        [InlineData(typeof(IEnumerable<DateTime>), typeof(DateTime))]\n        [InlineData(typeof(ICollection<string>), typeof(string))]\n        [InlineData(typeof(ICollection<int>), typeof(int))]\n        [InlineData(typeof(ICollection<Nullable<double>>), typeof(double))]\n        [InlineData(typeof(ICollection<DateTime>), typeof(DateTime))]\n        [InlineData(typeof(IList<string>), typeof(string))]\n        [InlineData(typeof(IList<int>), typeof(int))]\n        [InlineData(typeof(IList<Nullable<double>>), typeof(double))]\n        [InlineData(typeof(IList<DateTime>), typeof(DateTime))]\n        [InlineData(typeof(List<string>), typeof(string))]\n        [InlineData(typeof(List<int>), typeof(int))]\n        [InlineData(typeof(List<Nullable<double>>), typeof(double))]\n        [InlineData(typeof(List<DateTime>), typeof(DateTime))]\n        [InlineData(typeof(IEnumerable<KeyValuePair<string, int>>), typeof(KeyValuePair<string, int>))]\n        [InlineData(typeof(IEnumerable<KeyValuePair<DateTime, int?>>), typeof(KeyValuePair<DateTime, int?>))]\n        [InlineData(typeof(IEnumerable), typeof(object))]\n        [InlineData(typeof(ICollection), typeof(object))]\n        [InlineData(typeof(IList), typeof(object))]\n        [InlineData(typeof(ArrayList), typeof(object))]\n        [InlineData(typeof(HashSet<string>), typeof(string))]\n        [InlineData(typeof(IQueryable<string>), typeof(string))]\n        [InlineData(typeof(IQueryable<Customer>), typeof(Customer))]\n        [InlineData(typeof(IQueryable<HttpVerbs[]>), typeof(HttpVerbs[]))]\n        [InlineData(typeof(IQueryable<List<DateTime>>), typeof(List<DateTime>))]\n        [InlineData(typeof(IQueryable), typeof(object))]\n        [InlineData(typeof(string[]), typeof(string))]\n        [InlineData(typeof(int[]), typeof(int))]\n        [InlineData(typeof(double?[]), typeof(double))]\n        [InlineData(typeof(DateTime[]), typeof(DateTime))]\n        [InlineData(typeof(Customer[]), typeof(Customer))]\n        [InlineData(typeof(HttpVerbs[]), typeof(HttpVerbs))]\n        public void CreateModelDescription_Collection(Type collectionType, Type itemType)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);\n\n            CollectionModelDescription collectionModel = Assert.IsType<CollectionModelDescription>(modelGenerator.GetOrCreateModelDescription(collectionType));\n\n            Assert.NotNull(collectionModel);\n            Assert.Equal(collectionType, collectionModel.ModelType);\n            Assert.Equal(itemType, collectionModel.ElementDescription.ModelType);\n        }\n\n        [Theory]\n        [InlineData(typeof(Dictionary<string, int>), typeof(string), typeof(int))]\n        [InlineData(typeof(Dictionary<string, Dictionary<Customer, Order>>), typeof(string), typeof(Dictionary<Customer, Order>))]\n        [InlineData(typeof(Hashtable), typeof(object), typeof(object))]\n        [InlineData(typeof(IDictionary), typeof(object), typeof(object))]\n        [InlineData(typeof(IDictionary<string, DateTime>), typeof(string), typeof(DateTime))]\n        [InlineData(typeof(SortedDictionary<string, Guid>), typeof(string), typeof(Guid))]\n        [InlineData(typeof(OrderedDictionary), typeof(object), typeof(object))]\n        [InlineData(typeof(ConcurrentDictionary<Guid, DateTime>), typeof(Guid), typeof(DateTime))]\n        public void CreateModelDescription_Dictionary(Type dictionaryType, Type keyType, Type valueType)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);\n\n            DictionaryModelDescription dictionaryModel = Assert.IsType<DictionaryModelDescription>(modelGenerator.GetOrCreateModelDescription(dictionaryType));\n\n            Assert.NotNull(dictionaryModel);\n            Assert.Equal(dictionaryType, dictionaryModel.ModelType);\n            Assert.Equal(keyType, dictionaryModel.KeyModelDescription.ModelType);\n            Assert.Equal(valueType, dictionaryModel.ValueModelDescription.ModelType);\n        }\n\n        [Theory]\n        [InlineData(typeof(KeyValuePair<string, int>), typeof(string), typeof(int))]\n        [InlineData(typeof(KeyValuePair<Dictionary<int, string>, int>), typeof(Dictionary<int, string>), typeof(int))]\n        [InlineData(typeof(KeyValuePair<string, User>), typeof(string), typeof(User))]\n        public void CreateModelDescription_KeyValuePair(Type modelType, Type keyType, Type valueType)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);\n\n            KeyValuePairModelDescription keyValuePairModel = Assert.IsType<KeyValuePairModelDescription>(modelGenerator.GetOrCreateModelDescription(modelType));\n\n            Assert.NotNull(keyValuePairModel);\n            Assert.Equal(modelType, keyValuePairModel.ModelType);\n            Assert.Equal(keyType, keyValuePairModel.KeyModelDescription.ModelType);\n            Assert.Equal(valueType, keyValuePairModel.ValueModelDescription.ModelType);\n        }\n\n        [Theory]\n        [InlineData(typeof(HttpStatusCode), 47)]\n        [InlineData(typeof(HttpVerbs), 7)]\n        [InlineData(typeof(ApiParameterSource), 3)]\n        [InlineData(typeof(SampleDirection), 2)]\n        [InlineData(typeof(ConsoleColor), 16)]\n        [InlineData(typeof(HttpCompletionOption), 2)]\n        [InlineData(typeof(EnumDataContractType), 1)]\n        public void CreateModelDescription_Enum(Type type, int enumValueCount)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);\n\n            EnumTypeModelDescription enumModel = Assert.IsType<EnumTypeModelDescription>(modelGenerator.GetOrCreateModelDescription(type));\n\n            Assert.NotNull(enumModel);\n            Assert.Equal(type, enumModel.ModelType);\n            Assert.Equal(enumValueCount, enumModel.Values.Count);\n        }\n\n        [Theory]\n        [InlineData(typeof(ComplexTypeWithPublicFields), new[] { \"Name\", \"Id\", \"item\" })]\n        [InlineData(typeof(ComplexStruct), new[] { \"Name\", \"Id\", \"Time\", \"Kind\" })]\n        [InlineData(typeof(ApiDescription), new[] { \"HttpMethod\", \"RelativePath\", \"ActionDescriptor\", \"Route\", \"Documentation\", \"SupportedResponseFormatters\", \"SupportedRequestBodyFormatters\", \"ParameterDescriptions\", \"ResponseDescription\", \"ID\" })]\n        [InlineData(typeof(ApiParameterDescription), new[] { \"Name\", \"Documentation\", \"Source\", \"ParameterDescriptor\" })]\n        [InlineData(typeof(Customer), new[] { \"Name\", \"Id\", \"Orders\" })] // Circular reference\n        [InlineData(typeof(Order), new[] { \"Items\", \"Id\", \"ShipDate\" })] // Circular reference\n        [InlineData(typeof(Item), new[] { \"Name\", \"Buyer\", \"Price\" })] // Circular reference\n        [InlineData(typeof(DataContractType), new[] { \"Member\", \"Field\" })]\n        [InlineData(typeof(StructDataContractType), new[] { \"Member\", \"Field\" })]\n        [InlineData(typeof(TypeWithIgnores), new[] { \"Member\", \"DataMember\", \"RegularMember\", \"Field\", \"DataField\", \"RegularField\" })]\n        [InlineData(typeof(DerivedType), new[] { \"Member\", \"DataMember\", \"RegularMember\", \"Field\", \"DataField\", \"RegularField\", \"DerivedField\", \"DerivedMember\" })]\n        [InlineData(typeof(PropertyAliasType), new[] { \"RenamedMember\", \"Bar\", \"JsonField\", \"JsonProperty\" })]\n        [InlineData(typeof(DataContractPropertyAliasType), new[] { \"RenamedField\", \"JsonField\", \"JsonProperty\" })]\n        public void CreateModelDescription_ComplexType(Type type, string[] expectedPropertyNames)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);\n\n            ComplexTypeModelDescription complexModel = Assert.IsType<ComplexTypeModelDescription>(modelGenerator.GetOrCreateModelDescription(type));\n            var propertyNames = complexModel.Properties.Select(m => m.Name).ToArray();\n\n            Assert.NotNull(complexModel);\n            Assert.Equal(type, complexModel.ModelType);\n            Assert.Equal(expectedPropertyNames.Length, propertyNames.Length);\n            foreach (var expectedPropertyName in expectedPropertyNames)\n            {\n                Assert.Contains(expectedPropertyName, propertyNames);\n            }\n        }\n\n        [Theory]\n        [InlineData(typeof(ComplexTypeWithPublicFields), \"ComplexTypeWithPublicFields\")]\n        [InlineData(typeof(ComplexStruct), \"ComplexStruct\")]\n        [InlineData(typeof(Customer), \"Customer\")]\n        [InlineData(typeof(Order), \"Order\")]\n        [InlineData(typeof(Item), \"Item\")]\n        [InlineData(typeof(User), \"CustomUser\")]\n        [InlineData(typeof(Address), \"MyAddress\")]\n        public void CreateModelDescription_ComplexType_ReturnsExpectedModelName(Type type, string expectedModelName)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);\n\n            ComplexTypeModelDescription complexModel = Assert.IsType<ComplexTypeModelDescription>(modelGenerator.GetOrCreateModelDescription(type));\n\n            Assert.NotNull(complexModel);\n            Assert.Equal(type, complexModel.ModelType);\n            Assert.Equal(expectedModelName, complexModel.Name);\n        }\n\n        public static IEnumerable<object[]> CreateModelDescription_ComplexType_WithAnnotation_PropertyData\n        {\n            get\n            {\n                object type;\n                object annotationMapping;\n\n                type = typeof(User);\n                annotationMapping = new Dictionary<string, string[]>\n                {\n                    { \"Name\", new[] { \"Required\" } },\n                    { \"Age\", new[] { \"Required\", \"Range: inclusive between 1 and 200\" } },\n                    { \"Comment\", new[] { \"String length: inclusive between 0 and 100\" } },\n                    { \"PhoneNumber\", new string[0] },\n                };\n\n                yield return new[] { type, annotationMapping };\n\n                type = typeof(Address);\n                annotationMapping = new Dictionary<string, string[]>\n                {\n                    { \"ZipCode\", new[] { \"Data type: PostalCode\" } },\n                    { \"Street\", new[] { \"Matching regular expression pattern: [a-z]\" } },\n                    { \"Coordinates\", new[] { \"Max length: 3\", \"Min length: 2\" } },\n                };\n\n                yield return new[] { type, annotationMapping };\n\n                type = typeof(MultipleDataAnnotations);\n                annotationMapping = new Dictionary<string, string[]>\n                {\n                    {\n                        \"Property\", new[] {\n                            \"Required\",\n                            \"Data type: PostalCode\",\n                            \"Matching regular expression pattern: [a-z]\",\n                            \"Max length: 3\",\n                            \"Min length: 2\",\n                            \"Range: inclusive between 1 and 200\",\n                            \"String length: inclusive between 0 and 100\"}\n                    },\n                    {\n                        \"OptionalProperty\", new[] {\n                            \"Data type: PostalCode\",\n                            \"Matching regular expression pattern: [a-z]\",\n                            \"Max length: 3\",\n                            \"Min length: 2\",\n                            \"Range: inclusive between 1 and 200\",\n                            \"String length: inclusive between 0 and 100\"}\n                    }\n                };\n\n                yield return new[] { type, annotationMapping };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"CreateModelDescription_ComplexType_WithAnnotation_PropertyData\")]\n        public void CreateModelDescription_ComplexType_WithAnnotation(Type type, Dictionary<string, string[]> annotationMapping)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);\n\n            ComplexTypeModelDescription complexModel = Assert.IsType<ComplexTypeModelDescription>(modelGenerator.GetOrCreateModelDescription(type));\n\n            Assert.NotNull(complexModel);\n            Assert.Equal(type, complexModel.ModelType);\n            Assert.Equal(annotationMapping.Count, complexModel.Properties.Count);\n            foreach (var property in complexModel.Properties)\n            {\n                string[] expectedAnnotations = annotationMapping[property.Name];\n                Assert.Equal(expectedAnnotations.Length, property.Annotations.Count);\n                for (int i = 0; i < expectedAnnotations.Length; i++)\n                {\n                    Assert.Equal(expectedAnnotations[i], property.Annotations[i].Documentation);\n                }\n            }\n        }\n\n        public static IEnumerable<object[]> CreateModelDescription_ComplexType_WithDocumentation_PropertyData\n        {\n            get\n            {\n                object type;\n                object annotationMapping;\n\n                type = typeof(User);\n                annotationMapping = new Dictionary<string, string>\n                {\n                    { \"Name\", \"User name.\"},\n                    { \"Age\", \"Age of the user.\" },\n                    { \"Comment\", \"User comment.\" },\n                    { \"PhoneNumber\", \"U.S. phone number.\" },\n                };\n\n                yield return new[] { type, annotationMapping };\n\n                type = typeof(Address);\n                annotationMapping = new Dictionary<string, string>\n                {\n                    { \"ZipCode\", null },\n                    { \"Street\", \"Street name.\" },\n                    { \"Coordinates\", \"Geo-coordinate of the address.\" },\n                };\n\n                yield return new[] { type, annotationMapping };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"CreateModelDescription_ComplexType_WithDocumentation_PropertyData\")]\n        public void CreateModelDescription_ComplexType_WithDocumentation(Type type, Dictionary<string, string> documentationMapping)\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            config.SetDocumentationProvider(new XmlDocumentationProvider(\"WebApiHelpPage.Test.XML\"));\n            ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);\n\n            ComplexTypeModelDescription complexModel = Assert.IsType<ComplexTypeModelDescription>(modelGenerator.GetOrCreateModelDescription(type));\n\n            Assert.NotNull(complexModel);\n            Assert.Equal(type, complexModel.ModelType);\n            Assert.Equal(documentationMapping.Count, complexModel.Properties.Count);\n            foreach (var property in complexModel.Properties)\n            {\n                string expectedDocumentation = documentationMapping[property.Name];\n                Assert.Equal(expectedDocumentation, property.Documentation);\n            }\n        }\n\n        [Fact]\n        public void CreateModelDescription_ThrowsOnDuplicateModelName()\n        {\n            HttpConfiguration config = new HttpConfiguration();\n            ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);\n\n            Assert.Throws<InvalidOperationException>(() =>\n            {\n                modelGenerator.GetOrCreateModelDescription(typeof(Customer));\n                modelGenerator.GetOrCreateModelDescription(typeof(WebApiHelpPageWebHost.UnitTest2.Customer));\n            },\n            \"A model description could not be created. Duplicate model name 'Customer' was found for types 'WebApiHelpPageWebHost.UnitTest.Customer' and 'WebApiHelpPageWebHost.UnitTest2.Customer'. Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.\");\n        }\n    }\n}"
  },
  {
    "path": "test/WebApiHelpPage.Test/ObjectGeneratorTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Collections.Specialized;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Http;\nusing System.Web.Http.Description;\nusing System.Web.Mvc;\nusing Microsoft.TestCommon;\nusing ROOT_PROJECT_NAMESPACE.Areas.HelpPage;\n\nnamespace WebApiHelpPageWebHost.UnitTest\n{\n    public class ObjectGeneratorTest\n    {\n        [Theory]\n        [InlineData(typeof(bool))]\n        [InlineData(typeof(byte))]\n        [InlineData(typeof(char))]\n        [InlineData(typeof(DBNull))]\n        [InlineData(typeof(Decimal))]\n        [InlineData(typeof(double))]\n        [InlineData(typeof(Guid))]\n        [InlineData(typeof(int))]\n        [InlineData(typeof(string))]\n        [InlineData(typeof(float))]\n        [InlineData(typeof(long))]\n        [InlineData(typeof(uint))]\n        [InlineData(typeof(ulong))]\n        [InlineData(typeof(sbyte))]\n        [InlineData(typeof(DateTime))]\n        [InlineData(typeof(DateTimeOffset))]\n        [InlineData(typeof(TimeSpan))]\n        [InlineData(typeof(UInt16))]\n        [InlineData(typeof(Int16))]\n        [InlineData(typeof(Guid))]\n        [InlineData(typeof(Uri))]\n        public void GenerateObject_SimpleTypes(Type type)\n        {\n            ObjectGenerator objectGenerator = new ObjectGenerator();\n            object instance = objectGenerator.GenerateObject(type);\n            Assert.NotNull(instance);\n            Assert.IsType(type, instance);\n        }\n\n        [Theory]\n        [InlineData(typeof(KeyValuePair<string, int>))]\n        [InlineData(typeof(KeyValuePair<string, KeyValuePair<int, DateTime>>))]\n        [InlineData(typeof(Tuple<string>))]\n        [InlineData(typeof(Tuple<string, int>))]\n        [InlineData(typeof(Tuple<string, int, double, DateTime>))]\n        [InlineData(typeof(Tuple<string, int, double, DateTime, Tuple<int?>>))]\n        [InlineData(typeof(Tuple<string, int, double, DateTime, Tuple<int?>, Tuple<double, string>>))]\n        [InlineData(typeof(Tuple<string, int, double, Type, DateTimeOffset, byte, sbyte>))]\n        [InlineData(typeof(Tuple<string, int, double, Type, DateTimeOffset, byte, sbyte, Tuple<char, uint>>))]\n        [InlineData(typeof(MyGenericType<int, string>))]\n        [InlineData(typeof(MyGenericType<int, Tuple<string, DateTime>>))]\n        [InlineData(typeof(MyGenericType<MyGenericType<DateTime, HttpVerbs>, string>))]\n        public void GenerateObject_Generic(Type genericType)\n        {\n            ObjectGenerator objectGenerator = new ObjectGenerator();\n            object instance = objectGenerator.GenerateObject(genericType);\n            Assert.NotNull(instance);\n            Assert.IsType(genericType, instance);\n        }\n\n        [Theory]\n        [InlineData(typeof(IEnumerable<string>), typeof(string))]\n        [InlineData(typeof(IEnumerable<List<string>>), typeof(List<string>))]\n        [InlineData(typeof(IEnumerable<int>), typeof(int))]\n        [InlineData(typeof(IEnumerable<Nullable<double>>), typeof(double))]\n        [InlineData(typeof(IEnumerable<DateTime>), typeof(DateTime))]\n        [InlineData(typeof(ICollection<string>), typeof(string))]\n        [InlineData(typeof(ICollection<int>), typeof(int))]\n        [InlineData(typeof(ICollection<Nullable<double>>), typeof(double))]\n        [InlineData(typeof(ICollection<DateTime>), typeof(DateTime))]\n        [InlineData(typeof(IList<string>), typeof(string))]\n        [InlineData(typeof(IList<int>), typeof(int))]\n        [InlineData(typeof(IList<Nullable<double>>), typeof(double))]\n        [InlineData(typeof(IList<DateTime>), typeof(DateTime))]\n        [InlineData(typeof(List<string>), typeof(string))]\n        [InlineData(typeof(List<int>), typeof(int))]\n        [InlineData(typeof(List<Nullable<double>>), typeof(double))]\n        [InlineData(typeof(List<DateTime>), typeof(DateTime))]\n        [InlineData(typeof(IEnumerable<KeyValuePair<string, int>>), typeof(KeyValuePair<string, int>))]\n        [InlineData(typeof(IEnumerable<KeyValuePair<DateTime, int?>>), typeof(KeyValuePair<DateTime, int?>))]\n        [InlineData(typeof(IEnumerable), typeof(object))]\n        [InlineData(typeof(ICollection), typeof(object))]\n        [InlineData(typeof(IList), typeof(object))]\n        [InlineData(typeof(ArrayList), typeof(object))]\n        [InlineData(typeof(HashSet<string>), typeof(string))]\n        public void GenerateObject_Collection(Type collectionType, Type itemType)\n        {\n            ObjectGenerator objectGenerator = new ObjectGenerator();\n            IEnumerable collection = objectGenerator.GenerateObject(collectionType) as IEnumerable;\n            Assert.NotEmpty(collection);\n            foreach (var item in collection)\n            {\n                Assert.NotNull(item);\n                Assert.IsType(itemType, item);\n            }\n        }\n\n        [Theory]\n        [InlineData(typeof(IQueryable<string>), typeof(string))]\n        [InlineData(typeof(IQueryable<Customer>), typeof(Customer))]\n        [InlineData(typeof(IQueryable<HttpVerbs[]>), typeof(HttpVerbs[]))]\n        [InlineData(typeof(IQueryable<List<DateTime>>), typeof(List<DateTime>))]\n        [InlineData(typeof(IQueryable), typeof(object))]\n        public void GenerateObject_IQueryable(Type collectionType, Type itemType)\n        {\n            ObjectGenerator objectGenerator = new ObjectGenerator();\n            IQueryable collection = objectGenerator.GenerateObject(collectionType) as IQueryable;\n            Assert.NotEmpty(collection);\n            foreach (var item in collection)\n            {\n                Assert.NotNull(item);\n                Assert.IsType(itemType, item);\n            }\n        }\n\n        [Theory]\n        [InlineData(typeof(string[]), typeof(string))]\n        [InlineData(typeof(int[]), typeof(int))]\n        [InlineData(typeof(double?[]), typeof(double))]\n        [InlineData(typeof(DateTime[]), typeof(DateTime))]\n        [InlineData(typeof(Customer[]), typeof(Customer))]\n        [InlineData(typeof(HttpVerbs[]), typeof(HttpVerbs))]\n        public void GenerateObject_Array(Type arrayType, Type elementType)\n        {\n            ObjectGenerator objectGenerator = new ObjectGenerator();\n            Array array = objectGenerator.GenerateObject(arrayType) as Array;\n            Assert.NotEmpty(array);\n            foreach (var item in array)\n            {\n                Assert.NotNull(item);\n                Assert.IsType(elementType, item);\n            }\n        }\n\n        [Theory]\n        [InlineData(typeof(Dictionary<string, int>), typeof(string), typeof(int))]\n        [InlineData(typeof(Dictionary<string, Dictionary<Customer, Order>>), typeof(string), typeof(Dictionary<Customer, Order>))]\n        [InlineData(typeof(Hashtable), typeof(object), typeof(object))]\n        [InlineData(typeof(IDictionary), typeof(object), typeof(object))]\n        [InlineData(typeof(IDictionary<string, DateTime>), typeof(string), typeof(DateTime))]\n        [InlineData(typeof(SortedDictionary<string, Guid>), typeof(string), typeof(Guid))]\n        [InlineData(typeof(OrderedDictionary), typeof(object), typeof(object))]\n        [InlineData(typeof(ConcurrentDictionary<Guid, DateTime>), typeof(Guid), typeof(DateTime))]\n        public void GenerateObject_Dictionary(Type dictionaryType, Type keyType, Type valueType)\n        {\n            ObjectGenerator objectGenerator = new ObjectGenerator();\n            IDictionary dictionary = objectGenerator.GenerateObject(dictionaryType) as IDictionary;\n            Assert.NotEmpty(dictionary);\n            foreach (var key in dictionary.Keys)\n            {\n                Assert.NotNull(key);\n                Assert.IsType(keyType, key);\n            }\n            foreach (var value in dictionary.Values)\n            {\n                Assert.NotNull(value);\n                Assert.IsType(valueType, value);\n            }\n        }\n\n        [Theory]\n        [InlineData(typeof(HttpStatusCode))]\n        [InlineData(typeof(HttpVerbs))]\n        [InlineData(typeof(ApiParameterSource))]\n        [InlineData(typeof(SampleDirection))]\n        [InlineData(typeof(ConsoleColor))]\n        [InlineData(typeof(HttpCompletionOption))]\n        public void GenerateObject_Enum(Type type)\n        {\n            ObjectGenerator objectGenerator = new ObjectGenerator();\n            object enumValue = objectGenerator.GenerateObject(type);\n            Assert.NotNull(enumValue);\n            Assert.True(Enum.IsDefined(type, enumValue));\n        }\n\n        [Theory]\n        [InlineData(typeof(HttpResponseMessage))]\n        [InlineData(typeof(ComplexTypeWithPublicFields))]\n        [InlineData(typeof(ComplexStruct))]\n        [InlineData(typeof(ApiDescription))]\n        [InlineData(typeof(ApiParameterDescription))]\n        [InlineData(typeof(Customer))] // Circular reference\n        [InlineData(typeof(Order))] // Circular reference\n        [InlineData(typeof(Item))] // Circular reference\n        public void GenerateObject_ComplexType(Type type)\n        {\n            ObjectGenerator objectGenerator = new ObjectGenerator();\n            object instance = objectGenerator.GenerateObject(type);\n            Assert.NotNull(instance);\n            Assert.IsType(type, instance);\n        }\n\n        [Theory]\n        [InlineData(typeof(TypeWithNoDefaultConstructor))]\n        [InlineData(typeof(NonPublicType))]\n        [InlineData(typeof(EmptyEnum))]\n        [InlineData(typeof(HttpRequestMessage))]\n        [InlineData(typeof(KeyValuePair<EmptyEnum, NonPublicType>))]\n        [InlineData(typeof(Tuple<EmptyEnum, NonPublicType, TypeWithNoDefaultConstructor>))]\n        [InlineData(typeof(List<EmptyEnum>))]\n        [InlineData(typeof(Dictionary<EmptyEnum, NonPublicType>))]\n        [InlineData(typeof(EmptyEnum[]))]\n        [InlineData(typeof(IQueryable<EmptyEnum>))]\n        public void GenerateObject_ReturnsNull_WhenInstanceCannotBeCreated(Type type)\n        {\n            ObjectGenerator objectGenerator = new ObjectGenerator();\n            Assert.Null(objectGenerator.GenerateObject(type));\n        }\n    }\n}\n"
  },
  {
    "path": "test/WebApiHelpPage.Test/TextSampleTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing Microsoft.TestCommon;\nusing ROOT_PROJECT_NAMESPACE.Areas.HelpPage;\n\nnamespace WebApiHelpPageWebHost.UnitTest\n{\n    public class TextSampleTest\n    {\n        [Fact]\n        public void Constructor()\n        {\n            TextSample sample = new TextSample(\"some text\");\n            Assert.Equal(\"some text\", sample.Text);\n        }\n\n        [Fact]\n        public void Constructor_ThrowsArgumentNullException()\n        {\n            Assert.Throws<ArgumentNullException>(() => new TextSample(null));\n        }\n\n        [Fact]\n        public void Equals_ReturnsTrue()\n        {\n            TextSample sample = new TextSample(\"some text\");\n            Assert.Equal(new TextSample(\"some text\"), sample);\n        }\n\n        [Fact]\n        public void ToString_ReturnsText()\n        {\n            TextSample sample = new TextSample(\"some text\");\n            Assert.Equal(\"some text\", sample.ToString());\n        }\n\n        [Fact]\n        public void GetHashCode_ReturnsTextHashCode()\n        {\n            TextSample sample = new TextSample(\"some text\");\n            Assert.Equal(\"some text\".GetHashCode(), sample.GetHashCode());\n        }\n    }\n}\n"
  },
  {
    "path": "test/WebApiHelpPage.Test/WebApiHelpPage.Test.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props\" Condition=\"Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" />\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" />\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{291EF478-BF24-4935-BC78-E0DCCD0C9A1B}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <RootNamespace>WebApiHelpPage</RootNamespace>\n    <AssemblyName>WebApiHelpPage.Test</AssemblyName>\n    <OutputPath>..\\..\\bin\\$(Configuration)\\Test\\</OutputPath>\n    <DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>\n    <NoWarn>1591</NoWarn>\n    <NuGetPackageImportStamp>\n    </NuGetPackageImportStamp>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Castle.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Castle.Core.5.1.1\\lib\\net462\\Castle.Core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Moq, Version=4.18.0.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Moq.4.18.4\\lib\\net462\\Moq.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Newtonsoft.Json.13.0.1\\lib\\net45\\Newtonsoft.Json.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.ComponentModel.DataAnnotations\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Net.Http\" />\n    <Reference Include=\"System.Net.Http.WebRequest\" />\n    <Reference Include=\"System.Runtime.Serialization\" />\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"System.Xml.Linq\" />\n    <Reference Include=\"System.Data.DataSetExtensions\" />\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"System.Data\" />\n    <Reference Include=\"System.Xml\" />\n    <Reference Include=\"xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.abstractions.2.0.3\\lib\\net35\\xunit.abstractions.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.assert, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.assert.2.4.2\\lib\\netstandard1.1\\xunit.assert.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.core, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.core.2.4.2\\lib\\net452\\xunit.core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.execution.desktop, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.execution.2.4.2\\lib\\net452\\xunit.execution.desktop.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"Controllers\\UsersController.cs\" />\n    <Compile Include=\"Controllers\\ValuesController.cs\" />\n    <Compile Include=\"ModelDescriptionGeneratorTest.cs\" />\n    <Compile Include=\"Helpers\\CustomTypes.cs\" />\n    <Compile Include=\"ObjectGeneratorTest.cs\" />\n    <Compile Include=\"InvalidSampleTest.cs\" />\n    <Compile Include=\"HelpPageApiModelTest.cs\" />\n    <Compile Include=\"TextSampleTest.cs\" />\n    <Compile Include=\"ImageSampleTest.cs\" />\n    <Compile Include=\"HelpPageAreaRegistrationTest.cs\" />\n    <Compile Include=\"HelpPageSampleKeyTest.cs\" />\n    <Compile Include=\"Helpers\\ApiDescriptionHelpers.cs\" />\n    <Compile Include=\"HelppageSampleGeneratorTest.cs\" />\n    <Compile Include=\"HelpControllerTest.cs\" />\n    <Compile Include=\"WebConfigTest.cs\" />\n    <Compile Include=\"XmlDocumentationProviderTest.cs\" />\n    <Compile Include=\"HelpPageConfigurationExtensionsTest.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\">\n      <SubType>Designer</SubType>\n    </None>\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"..\\..\\src\\WebApiHelpPage\\Areas\\HelpPage\\Views\\Web.config\">\n      <Link>TestFiles\\Web.config</Link>\n    </EmbeddedResource>\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\..\\src\\System.Net.Http.Formatting\\System.Net.Http.Formatting.csproj\">\n      <Project>{668e9021-ce84-49d9-98fb-df125a9fcdb0}</Project>\n      <Name>System.Net.Http.Formatting</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Helpers\\System.Web.Helpers.csproj\">\n      <Project>{9b7e3740-6161-4548-833c-4bbca43b970e}</Project>\n      <Name>System.Web.Helpers</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Http.WebHost\\System.Web.Http.WebHost.csproj\">\n      <Project>{a0187bc2-8325-4bb2-8697-7f955cf4173e}</Project>\n      <Name>System.Web.Http.WebHost</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Http\\System.Web.Http.csproj\">\n      <Project>{ddc1ce0c-486e-4e35-bb3b-eab61f8f9440}</Project>\n      <Name>System.Web.Http</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Mvc\\System.Web.Mvc.csproj\">\n      <Project>{3d3ffd8a-624d-4e9b-954b-e1c105507975}</Project>\n      <Name>System.Web.Mvc</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Razor\\System.Web.Razor.csproj\">\n      <Project>{8f18041b-9410-4c36-a9c5-067813df5f31}</Project>\n      <Name>System.Web.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.WebPages.Deployment\\System.Web.WebPages.Deployment.csproj\">\n      <Project>{22babb60-8f02-4027-affc-acf069954536}</Project>\n      <Name>System.Web.WebPages.Deployment</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.WebPages.Razor\\System.Web.WebPages.Razor.csproj\">\n      <Project>{0939b11a-fe4e-4ba1-8ad6-d97741ee314f}</Project>\n      <Name>System.Web.WebPages.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.WebPages\\System.Web.WebPages.csproj\">\n      <Project>{76efa9c5-8d7e-4fdf-b710-e20f8b6b00d2}</Project>\n      <Name>System.Web.WebPages</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\WebApiHelpPage\\WebApiHelpPage.csproj\">\n      <Project>{FEDFE6CA-8282-4C5B-A756-E97189690982}</Project>\n      <Name>WebApiHelpPage</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\">\n      <Project>{fccc4cb7-baf7-4a57-9f89-e5766fe536c0}</Project>\n      <Name>Microsoft.TestCommon</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <Service Include=\"{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Analyzer Include=\"..\\..\\packages\\xunit.analyzers.1.1.0\\analyzers\\dotnet\\cs\\xunit.analyzers.dll\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  <Target Name=\"EnsureNuGetPackageBuildImports\" BeforeTargets=\"PrepareForBuild\">\n    <PropertyGroup>\n      <ErrorText>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}.</ErrorText>\n    </PropertyGroup>\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props'))\" />\n  </Target>\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" />\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.\n       Other similar extension points exist, see Microsoft.Common.targets.\n  <Target Name=\"BeforeBuild\">\n  </Target>\n  <Target Name=\"AfterBuild\">\n  </Target>\n  -->\n</Project>"
  },
  {
    "path": "test/WebApiHelpPage.Test/WebConfigTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.IO;\nusing System.Linq;\nusing System.Web.Mvc;\nusing System.Xml.Linq;\nusing Microsoft.TestCommon;\n\nnamespace WebApiHelpPageWebHost.UnitTest\n{\n    public class WebConfigTest\n    {\n        [Fact]\n        public void WebConfig_HelpPageReferencesCorrectMvcHostVersion()\n        {\n            // Arrange\n            Version mvcVersion = VersionTestHelper.GetVersionFromAssembly(\"System.Web.Mvc\", typeof(Controller));\n            string expectedFactoryType = \"System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=\" + mvcVersion\n                + \", Culture=neutral, PublicKeyToken=31BF3856AD364E35\";\n            using (Stream webConfigStream = typeof(WebConfigTest).Assembly\n                .GetManifestResourceStream(@\"WebApiHelpPage.TestFiles.Web.config\"))\n            {\n                XDocument document = XDocument.Load(webConfigStream);\n\n                // Act\n                string actualFactoryType = document.Root\n                    .Element(\"system.web.webPages.razor\")\n                    .Element(\"host\")\n                    .Attribute(\"factoryType\")\n                    .Value;\n\n                // Assert\n                Assert.Equal(expectedFactoryType, actualFactoryType);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/WebApiHelpPage.Test/XmlDocumentationProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Web.Http;\nusing System.Web.Http.Controllers;\nusing Microsoft.TestCommon;\nusing ROOT_PROJECT_NAMESPACE.Areas.HelpPage;\nusing WebApiHelpPageWebHost.UnitTest.Controllers;\n\nnamespace WebApiHelpPageWebHost.UnitTest\n{\n    public class XmlDocumentationProviderTest\n    {\n        [Fact]\n        public void Constructor_ThrowArgumentNullException()\n        {\n            Assert.Throws<ArgumentNullException>(() => new XmlDocumentationProvider(null));\n        }\n\n        public static IEnumerable<object[]> GetDocumentationForAction_PropertyData\n        {\n            get\n            {\n                ValuesController controller = new ValuesController();\n\n                Func<IEnumerable<string>> getAction = controller.Get;\n                HttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(new HttpControllerDescriptor(), getAction.Method);\n                yield return new object[] { actionDescriptor, \"Gets all the values.\" };\n\n                Func<int, string> getIdAction = controller.Get;\n                actionDescriptor = new ReflectedHttpActionDescriptor(new HttpControllerDescriptor(), getIdAction.Method);\n                yield return new object[] { actionDescriptor, \"Gets the value by id.\" };\n\n                Func<string, string> getNameAction = controller.Get;\n                actionDescriptor = new ReflectedHttpActionDescriptor(new HttpControllerDescriptor(), getNameAction.Method);\n                yield return new object[] { actionDescriptor, \"Gets the value by name.\" };\n\n                Func<string, HttpResponseMessage> postAction = controller.Post;\n                actionDescriptor = new ReflectedHttpActionDescriptor(new HttpControllerDescriptor(), postAction.Method);\n                yield return new object[] { actionDescriptor, \"Create a new value.\" };\n\n                Action<int, string> putAction = controller.Put;\n                actionDescriptor = new ReflectedHttpActionDescriptor(new HttpControllerDescriptor(), putAction.Method);\n                yield return new object[] { actionDescriptor, \"Updates the value.\" };\n\n                Action<List<Tuple<int, string>>> putCollectionAction = controller.Put;\n                actionDescriptor = new ReflectedHttpActionDescriptor(new HttpControllerDescriptor(), putCollectionAction.Method);\n                yield return new object[] { actionDescriptor, \"Updates the value pair collection.\" };\n\n                Action<int?> deleteAction = controller.Delete;\n                actionDescriptor = new ReflectedHttpActionDescriptor(new HttpControllerDescriptor(), deleteAction.Method);\n                yield return new object[] { actionDescriptor, \"Deletes the value.\" };\n\n                Action<Tuple<int, string>> patchAction = controller.Patch;\n                actionDescriptor = new ReflectedHttpActionDescriptor(new HttpControllerDescriptor(), patchAction.Method);\n                yield return new object[] { actionDescriptor, \"Patches the value pair.\" };\n\n                Func<HttpRequestMessage, string> optionsAction = controller.Options;\n                actionDescriptor = new ReflectedHttpActionDescriptor(new HttpControllerDescriptor(), optionsAction.Method);\n                yield return new object[] { actionDescriptor, \"Returns the options.\" };\n\n                Func<int, string[]> headAction = controller.HeadNoDocumentation;\n                actionDescriptor = new ReflectedHttpActionDescriptor(new HttpControllerDescriptor(), headAction.Method);\n                yield return new object[] { actionDescriptor, null };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"GetDocumentationForAction_PropertyData\")]\n        public void GetDocumentationForAction(HttpActionDescriptor actionDescriptor, string expectedString)\n        {\n            XmlDocumentationProvider provider = new XmlDocumentationProvider(\"WebApiHelpPage.Test.XML\");\n            string documentationString = provider.GetDocumentation(actionDescriptor);\n            Assert.Equal(expectedString, documentationString);\n        }\n\n        public static IEnumerable<object[]> GetDocumentationForParameters_PropertyData\n        {\n            get\n            {\n                HttpActionDescriptor[] actionDescriptors = GetDocumentationForAction_PropertyData.Select(a => (HttpActionDescriptor)a[0]).ToArray();\n                Dictionary<string, string>[] expectedResults = \n                {\n                    new Dictionary<string,string>(),\n                    new Dictionary<string, string>{{\"id\",\"The id.\"}},\n                    new Dictionary<string, string>{{\"name\",\"The name.\"}},\n                    new Dictionary<string, string>{{\"value\",\"The value.\"}},\n                    new Dictionary<string, string>{{\"id\",\"The id.\"}, {\"value\",\"The value.\"}},\n                    new Dictionary<string, string>{{\"valuePairCollection\",\"The value pair collection.\"}},\n                    new Dictionary<string, string>{{\"id\",\"The id.\"}},\n                    new Dictionary<string, string>{{\"valuePair\",\"The pair.\"}},\n                    new Dictionary<string, string>{{\"request\",\"The request.\"}},\n                    new Dictionary<string, string>{{\"id\", null}},\n                };\n\n                Assert.Equal(expectedResults.Length, actionDescriptors.Length);\n\n                for (int i = 0; i < actionDescriptors.Length; i++)\n                {\n                    var actionDescriptor = actionDescriptors[i];\n                    foreach (var parameterDescriptor in actionDescriptor.GetParameters())\n                    {\n                        yield return new object[] { parameterDescriptor, expectedResults[i][parameterDescriptor.ParameterName] };\n                    }\n                }\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"GetDocumentationForParameters_PropertyData\")]\n        public void GetDocumentationForParameters(HttpParameterDescriptor parameterDescriptor, string expectedString)\n        {\n            XmlDocumentationProvider provider = new XmlDocumentationProvider(\"WebApiHelpPage.Test.XML\");\n            string documentationString = provider.GetDocumentation(parameterDescriptor);\n            Assert.Equal(expectedString, documentationString);\n        }\n\n        public static IEnumerable<object[]> GetDocumentationForController_PropertyData\n        {\n            get\n            {\n                HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), \"Values\", typeof(ValuesController));\n                yield return new object[] { controllerDescriptor, \"Resource for Values.\" };\n\n                controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), \"NestedValues\", typeof(ValuesController.NestedValuesController));\n                yield return new object[] { controllerDescriptor, \"Resource for nested values.\" };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"GetDocumentationForController_PropertyData\")]\n        public void GetDocumentationForController(HttpControllerDescriptor controllerDescriptor, string expectedString)\n        {\n            XmlDocumentationProvider provider = new XmlDocumentationProvider(\"WebApiHelpPage.Test.XML\");\n            string documentationString = provider.GetDocumentation(controllerDescriptor);\n            Assert.Equal(expectedString, documentationString);\n        }\n\n        public static IEnumerable<object[]> GetDocumentationForActionResponse_PropertyData\n        {\n            get\n            {\n                ValuesController controller = new ValuesController();\n\n                Func<IEnumerable<string>> getAction = controller.Get;\n                HttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(new HttpControllerDescriptor(), getAction.Method);\n                yield return new object[] { actionDescriptor, \"A list of values.\" };\n\n                Func<int, string> getIdAction = controller.Get;\n                actionDescriptor = new ReflectedHttpActionDescriptor(new HttpControllerDescriptor(), getIdAction.Method);\n                yield return new object[] { actionDescriptor, \"A value string.\" };\n\n                Func<string, string> getNameAction = controller.Get;\n                actionDescriptor = new ReflectedHttpActionDescriptor(new HttpControllerDescriptor(), getNameAction.Method);\n                yield return new object[] { actionDescriptor, \"A value identified by name.\" };\n\n                Func<string, HttpResponseMessage> postAction = controller.Post;\n                actionDescriptor = new ReflectedHttpActionDescriptor(new HttpControllerDescriptor(), postAction.Method);\n                yield return new object[] { actionDescriptor, \"A response.\" };\n\n                Action<int, string> putAction = controller.Put;\n                actionDescriptor = new ReflectedHttpActionDescriptor(new HttpControllerDescriptor(), putAction.Method);\n                yield return new object[] { actionDescriptor, null };\n\n                Action<List<Tuple<int, string>>> putCollectionAction = controller.Put;\n                actionDescriptor = new ReflectedHttpActionDescriptor(new HttpControllerDescriptor(), putCollectionAction.Method);\n                yield return new object[] { actionDescriptor, null };\n\n                Action<int?> deleteAction = controller.Delete;\n                actionDescriptor = new ReflectedHttpActionDescriptor(new HttpControllerDescriptor(), deleteAction.Method);\n                yield return new object[] { actionDescriptor, null };\n\n                Action<Tuple<int, string>> patchAction = controller.Patch;\n                actionDescriptor = new ReflectedHttpActionDescriptor(new HttpControllerDescriptor(), patchAction.Method);\n                yield return new object[] { actionDescriptor, null };\n\n                Func<HttpRequestMessage, string> optionsAction = controller.Options;\n                actionDescriptor = new ReflectedHttpActionDescriptor(new HttpControllerDescriptor(), optionsAction.Method);\n                yield return new object[] { actionDescriptor, \"All the options.\" };\n\n                Func<int, string[]> headAction = controller.HeadNoDocumentation;\n                actionDescriptor = new ReflectedHttpActionDescriptor(new HttpControllerDescriptor(), headAction.Method);\n                yield return new object[] { actionDescriptor, null };\n            }\n        }\n\n        [Theory]\n        [PropertyData(\"GetDocumentationForActionResponse_PropertyData\")]\n        public void GetDocumentationForActionResponse(HttpActionDescriptor actionDescriptor, string expectedString)\n        {\n            XmlDocumentationProvider provider = new XmlDocumentationProvider(\"WebApiHelpPage.Test.XML\");\n            string documentationString = provider.GetResponseDocumentation(actionDescriptor);\n            Assert.Equal(expectedString, documentationString);\n        }\n    }\n}\n"
  },
  {
    "path": "test/WebApiHelpPage.Test/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Castle.Core\" version=\"5.1.1\" targetFramework=\"net462\" />\n  <package id=\"Microsoft.Web.Infrastructure\" version=\"1.0.0.0\" targetFramework=\"net462\" />\n  <package id=\"Moq\" version=\"4.18.4\" targetFramework=\"net462\" />\n  <package id=\"Newtonsoft.Json\" version=\"13.0.1\" targetFramework=\"net462\" />\n  <package id=\"xunit\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.abstractions\" version=\"2.0.3\" targetFramework=\"net462\" />\n  <package id=\"xunit.analyzers\" version=\"1.1.0\" targetFramework=\"net462\" />\n  <package id=\"xunit.assert\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.execution\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.runner.visualstudio\" version=\"2.4.5\" targetFramework=\"net462\" developmentDependency=\"true\" />\n</packages>"
  },
  {
    "path": "test/WebApiHelpPage.VB.Test/WebApiHelpPage.VB.Test.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props\" Condition=\"Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" />\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" />\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{41D5691F-2720-44A0-9185-EEFE928D2679}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <RootNamespace>WebApiHelpPage</RootNamespace>\n    <AssemblyName>WebApiHelpPage.VB.Test</AssemblyName>\n    <OutputPath>..\\..\\bin\\$(Configuration)\\Test\\</OutputPath>\n    <DocumentationFile>$(OutputPath)$(AssemblyName).xml</DocumentationFile>\n    <NoWarn>1591</NoWarn>\n    <NuGetPackageImportStamp>\n    </NuGetPackageImportStamp>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Castle.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Castle.Core.5.1.1\\lib\\net462\\Castle.Core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Moq, Version=4.18.0.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Moq.4.18.4\\lib\\net462\\Moq.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Newtonsoft.Json.13.0.1\\lib\\net45\\Newtonsoft.Json.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.ComponentModel.DataAnnotations\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Net.Http\" />\n    <Reference Include=\"System.Net.Http.WebRequest\" />\n    <Reference Include=\"System.Runtime.Serialization\" />\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"System.Xml.Linq\" />\n    <Reference Include=\"System.Data.DataSetExtensions\" />\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"System.Data\" />\n    <Reference Include=\"System.Xml\" />\n    <Reference Include=\"xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.abstractions.2.0.3\\lib\\net35\\xunit.abstractions.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.assert, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.assert.2.4.2\\lib\\netstandard1.1\\xunit.assert.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.core, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.core.2.4.2\\lib\\net452\\xunit.core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.execution.desktop, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.execution.2.4.2\\lib\\net452\\xunit.execution.desktop.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"..\\WebApiHelpPage.Test\\Controllers\\UsersController.cs\">\n      <Link>Controllers\\UsersController.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\WebApiHelpPage.Test\\Controllers\\ValuesController.cs\">\n      <Link>Controllers\\ValuesController.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\WebApiHelpPage.Test\\Helpers\\CustomTypes.cs\">\n      <Link>Helpers\\CustomTypes.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\WebApiHelpPage.Test\\ObjectGeneratorTest.cs\">\n      <Link>ObjectGeneratorTest.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\WebApiHelpPage.Test\\InvalidSampleTest.cs\">\n      <Link>InvalidSampleTest.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\WebApiHelpPage.Test\\HelpPageApiModelTest.cs\">\n      <Link>HelpPageApiModelTest.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\WebApiHelpPage.Test\\TextSampleTest.cs\">\n      <Link>TextSampleTest.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\WebApiHelpPage.Test\\ImageSampleTest.cs\">\n      <Link>ImageSampleTest.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\WebApiHelpPage.Test\\HelpPageAreaRegistrationTest.cs\">\n      <Link>HelpPageAreaRegistrationTest.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\WebApiHelpPage.Test\\HelpPageSampleKeyTest.cs\">\n      <Link>HelpPageSampleKeyTest.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\WebApiHelpPage.Test\\Helpers\\ApiDescriptionHelpers.cs\">\n      <Link>Helpers\\ApiDescriptionHelpers.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\WebApiHelpPage.Test\\HelppageSampleGeneratorTest.cs\">\n      <Link>HelppageSampleGeneratorTest.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\WebApiHelpPage.Test\\HelpControllerTest.cs\">\n      <Link>HelpControllerTest.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\WebApiHelpPage.Test\\XmlDocumentationProviderTest.cs\">\n      <Link>XmlDocumentationProviderTest.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\WebApiHelpPage.Test\\HelpPageConfigurationExtensionsTest.cs\">\n      <Link>HelpPageConfigurationExtensionsTest.cs</Link>\n    </Compile>\n    <Compile Include=\"..\\WebApiHelpPage.Test\\WebConfigTest.cs\">\n      <Link>WebConfigTest.cs</Link>\n    </Compile>\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"..\\WebApiHelpPage.Test\\packages.config\">\n      <Link>packages.config</Link>\n      <SubType>Designer</SubType>\n    </None>\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"..\\..\\src\\WebApiHelpPage\\VB\\Areas\\HelpPage\\Views\\Web.config\">\n      <Link>TestFiles\\Web.config</Link>\n    </EmbeddedResource>\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\..\\src\\System.Net.Http.Formatting\\System.Net.Http.Formatting.csproj\">\n      <Project>{668e9021-ce84-49d9-98fb-df125a9fcdb0}</Project>\n      <Name>System.Net.Http.Formatting</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Helpers\\System.Web.Helpers.csproj\">\n      <Project>{9b7e3740-6161-4548-833c-4bbca43b970e}</Project>\n      <Name>System.Web.Helpers</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Http.WebHost\\System.Web.Http.WebHost.csproj\">\n      <Project>{a0187bc2-8325-4bb2-8697-7f955cf4173e}</Project>\n      <Name>System.Web.Http.WebHost</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Http\\System.Web.Http.csproj\">\n      <Project>{ddc1ce0c-486e-4e35-bb3b-eab61f8f9440}</Project>\n      <Name>System.Web.Http</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Mvc\\System.Web.Mvc.csproj\">\n      <Project>{3d3ffd8a-624d-4e9b-954b-e1c105507975}</Project>\n      <Name>System.Web.Mvc</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Razor\\System.Web.Razor.csproj\">\n      <Project>{8f18041b-9410-4c36-a9c5-067813df5f31}</Project>\n      <Name>System.Web.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.WebPages.Deployment\\System.Web.WebPages.Deployment.csproj\">\n      <Project>{22babb60-8f02-4027-affc-acf069954536}</Project>\n      <Name>System.Web.WebPages.Deployment</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.WebPages.Razor\\System.Web.WebPages.Razor.csproj\">\n      <Project>{0939b11a-fe4e-4ba1-8ad6-d97741ee314f}</Project>\n      <Name>System.Web.WebPages.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.WebPages\\System.Web.WebPages.csproj\">\n      <Project>{76efa9c5-8d7e-4fdf-b710-e20f8b6b00d2}</Project>\n      <Name>System.Web.WebPages</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\WebApiHelpPage\\VB\\WebApiHelpPageVB.vbproj\">\n      <Project>{22075d5a-e9a1-4e2d-aba7-8e7cbf2a049e}</Project>\n      <Name>WebApiHelpPageVB</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\">\n      <Project>{fccc4cb7-baf7-4a57-9f89-e5766fe536c0}</Project>\n      <Name>Microsoft.TestCommon</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <Service Include=\"{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Analyzer Include=\"..\\..\\packages\\xunit.analyzers.1.1.0\\analyzers\\dotnet\\cs\\xunit.analyzers.dll\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  <Target Name=\"EnsureNuGetPackageBuildImports\" BeforeTargets=\"PrepareForBuild\">\n    <PropertyGroup>\n      <ErrorText>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}.</ErrorText>\n    </PropertyGroup>\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props'))\" />\n  </Target>\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" />\n  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.\n       Other similar extension points exist, see Microsoft.Common.targets.\n  <Target Name=\"BeforeBuild\">\n  </Target>\n  <Target Name=\"AfterBuild\">\n  </Target>\n  -->\n</Project>"
  },
  {
    "path": "test/WebMatrix.Data.Test/App.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n  <system.data>\n    <DbProviderFactories>\n      <remove invariant=\"System.Data.SqlServerCe.4.0\"></remove>\n      <add name=\"Microsoft SQL Server Compact Data Provider\" invariant=\"System.Data.SqlServerCe.4.0\" description=\".NET Framework Data Provider for Microsoft SQL Server Compact\" type=\"System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91\"/>\n    </DbProviderFactories>\n  </system.data>\n</configuration>"
  },
  {
    "path": "test/WebMatrix.Data.Test/ConfigurationManagerWrapperTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing Microsoft.TestCommon;\nusing Moq;\nusing WebMatrix.Data.Test.Mocks;\n\nnamespace WebMatrix.Data.Test\n{\n    public class ConfigurationManagerWrapperTest\n    {\n        [Fact]\n        public void GetConnectionGetsConnectionFromConfig()\n        {\n            // Arrange            \n            var configManager = new ConfigurationManagerWrapper(new Dictionary<string, IDbFileHandler>(), \"DataDirectory\");\n            Func<string, bool> fileExists = path => false;\n            Func<string, IConnectionConfiguration> getFromConfig = name => new MockConnectionConfiguration(\"connection string\");\n\n            // Act\n            IConnectionConfiguration configuration = configManager.GetConnection(\"foo\", getFromConfig, fileExists);\n\n            // Assert\n            Assert.NotNull(configuration);\n            Assert.Equal(\"connection string\", configuration.ConnectionString);\n        }\n\n        [Fact]\n        public void GetConnectionGetsConnectionFromDataDirectoryIfFileWithSupportedExtensionExists()\n        {\n            // Arrange   \n            var mockHandler = new Mock<MockDbFileHandler>();\n            mockHandler.Setup(m => m.GetConnectionConfiguration(@\"DataDirectory\\Bar.foo\")).Returns(new MockConnectionConfiguration(\"some file based connection\"));\n            var handlers = new Dictionary<string, IDbFileHandler>\n            {\n                { \".foo\", mockHandler.Object }\n            };\n            var configManager = new ConfigurationManagerWrapper(handlers, \"DataDirectory\");\n            Func<string, bool> fileExists = path => path.Equals(@\"DataDirectory\\Bar.foo\");\n            Func<string, IConnectionConfiguration> getFromConfig = name => null;\n\n            // Act\n            IConnectionConfiguration configuration = configManager.GetConnection(\"Bar\", getFromConfig, fileExists);\n\n            // Assert\n            Assert.NotNull(configuration);\n            Assert.Equal(\"some file based connection\", configuration.ConnectionString);\n        }\n\n        [Fact]\n        public void GetConnectionSdfAndMdfFile_MdfFileWins()\n        {\n            // Arrange\n            var mockSdfHandler = new Mock<MockDbFileHandler>();\n            mockSdfHandler.Setup(m => m.GetConnectionConfiguration(@\"DataDirectory\\Bar.sdf\")).Returns(new MockConnectionConfiguration(\"sdf connection\"));\n            var mockMdfHandler = new Mock<MockDbFileHandler>();\n            mockMdfHandler.Setup(m => m.GetConnectionConfiguration(@\"DataDirectory\\Bar.mdf\")).Returns(new MockConnectionConfiguration(\"mdf connection\"));\n            var handlers = new Dictionary<string, IDbFileHandler>\n            {\n                { \".sdf\", mockSdfHandler.Object },\n                { \".mdf\", mockMdfHandler.Object },\n            };\n            var configManager = new ConfigurationManagerWrapper(handlers, \"DataDirectory\");\n            Func<string, bool> fileExists = path => path.Equals(@\"DataDirectory\\Bar.mdf\") ||\n                                                    path.Equals(@\"DataDirectory\\Bar.sdf\");\n            Func<string, IConnectionConfiguration> getFromConfig = name => null;\n\n            // Act\n            IConnectionConfiguration configuration = configManager.GetConnection(\"Bar\", getFromConfig, fileExists);\n\n            // Assert\n            Assert.NotNull(configuration);\n            Assert.Equal(\"mdf connection\", configuration.ConnectionString);\n        }\n\n        [Fact]\n        public void GetConnectionReturnsNullIfNoConnectionFound()\n        {\n            // Act\n            var configManager = new ConfigurationManagerWrapper(new Dictionary<string, IDbFileHandler>(), \"DataDirectory\");\n            Func<string, bool> fileExists = path => false;\n            Func<string, IConnectionConfiguration> getFromConfig = name => null;\n\n            // Act\n            IConnectionConfiguration configuration = configManager.GetConnection(\"test\", getFromConfig, fileExists);\n\n            // Assert\n            Assert.Null(configuration);\n        }\n    }\n}\n"
  },
  {
    "path": "test/WebMatrix.Data.Test/DatabaseTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Data.Common;\nusing Microsoft.TestCommon;\nusing Moq;\nusing WebMatrix.Data.Test.Mocks;\n\nnamespace WebMatrix.Data.Test\n{\n    public class DatabaseTest\n    {\n        [Fact]\n        public void OpenWithNullConnectionStringNameThrowsException()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(() => Database.Open(null), \"name\");\n        }\n\n        [Fact]\n        public void OpenConnectionStringWithNullConnectionStringThrowsException()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(() => Database.OpenConnectionString(null), \"connectionString\");\n        }\n\n        [Fact]\n        public void OpenConnectionStringWithEmptyConnectionStringThrowsException()\n        {\n            Assert.ThrowsArgumentNullOrEmptyString(() => Database.OpenConnectionString(String.Empty), \"connectionString\");\n        }\n\n        [Fact]\n        public void OpenNamedConnectionUsesConnectionStringFromConfigurationIfExists()\n        {\n            // Arrange\n            MockConfigurationManager mockConfigurationManager = new MockConfigurationManager();\n            Mock<DbConnection> mockConnection = new Mock<DbConnection>();\n            mockConnection.Setup(m => m.ConnectionString).Returns(\"connection string\");\n            Mock<MockDbProviderFactory> mockProviderFactory = new Mock<MockDbProviderFactory>();\n            mockProviderFactory.Setup(m => m.CreateConnection(\"connection string\")).Returns(mockConnection.Object);\n            mockConfigurationManager.AddConnection(\"foo\", new ConnectionConfiguration(mockProviderFactory.Object, \"connection string\"));\n\n            // Act            \n            Database db = Database.OpenNamedConnection(\"foo\", mockConfigurationManager);\n\n            // Assert\n            Assert.Equal(\"connection string\", db.Connection.ConnectionString);\n        }\n\n        [Fact]\n        public void OpenNamedConnectionThrowsIfNoConnectionFound()\n        {\n            // Arrange\n            IConfigurationManager mockConfigurationManager = new MockConfigurationManager();\n\n            // Act & Assert\n            Assert.Throws<InvalidOperationException>(() => Database.OpenNamedConnection(\"foo\", mockConfigurationManager), \"Connection string \\\"foo\\\" was not found.\");\n        }\n\n        [Fact]\n        public void GetConnectionConfigurationGetConnectionForFileHandlersIfRegistered()\n        {\n            // Arrange\n            var mockHandler = new Mock<MockDbFileHandler>();\n            mockHandler.Setup(m => m.GetConnectionConfiguration(\"filename.foo\")).Returns(new MockConnectionConfiguration(\"some file based connection\"));\n            var handlers = new Dictionary<string, IDbFileHandler>\n            {\n                { \".foo\", mockHandler.Object }\n            };\n\n            // Act\n            IConnectionConfiguration configuration = Database.GetConnectionConfiguration(\"filename.foo\", handlers);\n\n            // Assert\n            Assert.NotNull(configuration);\n            Assert.Equal(\"some file based connection\", configuration.ConnectionString);\n        }\n\n        [Fact]\n        public void GetConnectionThrowsIfNoHandlersRegisteredForExtension()\n        {\n            // Arrange\n            var handlers = new Dictionary<string, IDbFileHandler>();\n\n            // Act\n            Assert.Throws<InvalidOperationException>(() => Database.GetConnectionConfiguration(\"filename.foo\", handlers), \"Unable to determine the provider for the database file \\\"filename.foo\\\".\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/WebMatrix.Data.Test/DynamicRecordTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Linq;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace WebMatrix.Data.Test\n{\n    public class DynamicRecordTest\n    {\n        [Fact]\n        public void GetFieldValueByNameAccessesUnderlyingRecordForValue()\n        {\n            // Arrange\n            var mockRecord = new Mock<IDataRecord>();\n            mockRecord.SetupGet(m => m[\"A\"]).Returns(1);\n            mockRecord.SetupGet(m => m[\"B\"]).Returns(2);\n\n            dynamic record = new DynamicRecord(new[] { \"A\", \"B\" }, mockRecord.Object);\n\n            // Assert\n            Assert.Equal(1, record.A);\n            Assert.Equal(2, record.B);\n        }\n\n        [Fact]\n        public void GetFieldValueByIndexAccessesUnderlyingRecordForValue()\n        {\n            // Arrange\n            var mockRecord = new Mock<IDataRecord>();\n            mockRecord.SetupGet(m => m[0]).Returns(1);\n            mockRecord.SetupGet(m => m[1]).Returns(2);\n\n            dynamic record = new DynamicRecord(new[] { \"A\", \"B\" }, mockRecord.Object);\n\n            // Assert\n            Assert.Equal(1, record[0]);\n            Assert.Equal(2, record[1]);\n        }\n\n        [Fact]\n        public void GetFieldValueByNameReturnsNullIfValueIsDbNull()\n        {\n            // Arrange\n            var mockRecord = new Mock<IDataRecord>();\n            mockRecord.SetupGet(m => m[\"A\"]).Returns(DBNull.Value);\n\n            dynamic record = new DynamicRecord(new[] { \"A\" }, mockRecord.Object);\n\n            // Assert\n            Assert.Null(record.A);\n        }\n\n        [Fact]\n        public void GetFieldValueByIndexReturnsNullIfValueIsDbNull()\n        {\n            // Arrange\n            var mockRecord = new Mock<IDataRecord>();\n            mockRecord.SetupGet(m => m[0]).Returns(DBNull.Value);\n\n            dynamic record = new DynamicRecord(new[] { \"A\" }, mockRecord.Object);\n\n            // Assert\n            Assert.Null(record[0]);\n        }\n\n        [Fact]\n        public void GetInvalidFieldValueThrows()\n        {\n            // Arrange\n            var mockRecord = new Mock<IDataRecord>();\n            dynamic record = new DynamicRecord(Enumerable.Empty<string>(), mockRecord.Object);\n\n            // Assert\n            Assert.Throws<InvalidOperationException>(() => { var value = record.C; }, \"Invalid column name \\\"C\\\".\");\n        }\n\n        [Fact]\n        public void VerfiyCustomTypeDescriptorMethods()\n        {\n            // Arrange\n            var mockRecord = new Mock<IDataRecord>();\n            mockRecord.SetupGet(m => m[\"A\"]).Returns(1);\n            mockRecord.SetupGet(m => m[\"B\"]).Returns(2);\n\n            // Act\n            ICustomTypeDescriptor record = new DynamicRecord(new[] { \"A\", \"B\" }, mockRecord.Object);\n\n            // Assert\n            Assert.Equal(AttributeCollection.Empty, record.GetAttributes());\n            Assert.Null(record.GetClassName());\n            Assert.Null(record.GetConverter());\n            Assert.Null(record.GetDefaultEvent());\n            Assert.Null(record.GetComponentName());\n            Assert.Null(record.GetDefaultProperty());\n            Assert.Null(record.GetEditor(null));\n            Assert.Equal(EventDescriptorCollection.Empty, record.GetEvents());\n            Assert.Equal(EventDescriptorCollection.Empty, record.GetEvents(null));\n            Assert.Same(record, record.GetPropertyOwner(null));\n            Assert.Equal(2, record.GetProperties().Count);\n            Assert.Equal(2, record.GetProperties(null).Count);\n            Assert.NotNull(record.GetProperties()[\"A\"]);\n            Assert.NotNull(record.GetProperties()[\"B\"]);\n        }\n\n        [Fact]\n        public void VerifyPropertyDescriptorProperties()\n        {\n            // Arrange\n            var mockRecord = new Mock<IDataRecord>();\n            mockRecord.SetupGet(m => m[\"A\"]).Returns(1);\n            mockRecord.Setup(m => m.GetOrdinal(\"A\")).Returns(0);\n            mockRecord.Setup(m => m.GetFieldType(0)).Returns(typeof(string));\n\n            // Act\n            ICustomTypeDescriptor record = new DynamicRecord(new[] { \"A\" }, mockRecord.Object);\n\n            // Assert\n            var aDescriptor = record.GetProperties().Find(\"A\", ignoreCase: false);\n\n            Assert.NotNull(aDescriptor);\n            Assert.Null(aDescriptor.GetValue(null));\n            Assert.Equal(1, aDescriptor.GetValue(record));\n            Assert.True(aDescriptor.IsReadOnly);\n            Assert.Equal(typeof(string), aDescriptor.PropertyType);\n            Assert.Equal(typeof(DynamicRecord), aDescriptor.ComponentType);\n            Assert.False(aDescriptor.ShouldSerializeValue(record));\n            Assert.False(aDescriptor.CanResetValue(record));\n        }\n\n        [Fact]\n        public void SetAndResetValueOnPropertyDescriptorThrows()\n        {\n            // Arrange\n            var mockRecord = new Mock<IDataRecord>();\n            mockRecord.SetupGet(m => m[\"A\"]).Returns(1);\n\n            // Act\n            ICustomTypeDescriptor record = new DynamicRecord(new[] { \"A\" }, mockRecord.Object);\n\n            // Assert\n            var aDescriptor = record.GetProperties().Find(\"A\", ignoreCase: false);\n            Assert.NotNull(aDescriptor);\n            Assert.Throws<InvalidOperationException>(() => aDescriptor.SetValue(record, 1), \"Unable to modify the value of column \\\"A\\\" because the record is read only.\");\n            Assert.Throws<InvalidOperationException>(() => aDescriptor.ResetValue(record), \"Unable to modify the value of column \\\"A\\\" because the record is read only.\");\n        }\n    }\n}\n"
  },
  {
    "path": "test/WebMatrix.Data.Test/FileHandlerTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.TestCommon;\n\nnamespace WebMatrix.Data.Test\n{\n    public class FileHandlerTest\n    {\n        [Fact]\n        public void SqlCeFileHandlerReturnsDataDirectoryRelativeConnectionStringIfPathIsNotRooted()\n        {\n            // Act\n            string connectionString = SqlCeDbFileHandler.GetConnectionString(\"foo.sdf\");\n\n            // Assert\n            Assert.NotNull(connectionString);\n            Assert.Equal(@\"Data Source=|DataDirectory|\\foo.sdf;File Access Retry Timeout=10\", connectionString);\n        }\n\n        [Fact]\n        public void SqlCeFileHandlerReturnsFullPathConnectionStringIfPathIsNotRooted()\n        {\n            // Act\n            string connectionString = SqlCeDbFileHandler.GetConnectionString(@\"c:\\foo.sdf\");\n\n            // Assert\n            Assert.NotNull(connectionString);\n            Assert.Equal(@\"Data Source=c:\\foo.sdf;File Access Retry Timeout=10\", connectionString);\n        }\n\n        [Fact]\n        public void SqlServerFileHandlerReturnsDataDirectoryRelativeConnectionStringIfPathIsNotRooted()\n        {\n            // Act           \n            string connectionString = SqlServerDbFileHandler.GetConnectionString(\"foo.mdf\", \"datadir\");\n\n            // Assert\n            Assert.NotNull(connectionString);\n            Assert.Equal(@\"Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\foo.mdf;Initial Catalog=datadir\\foo.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True\",\n                         connectionString);\n        }\n\n        [Fact]\n        public void SqlServerFileHandlerReturnsFullPathConnectionStringIfPathIsNotRooted()\n        {\n            // Act\n            string connectionString = SqlServerDbFileHandler.GetConnectionString(@\"c:\\foo.mdf\", \"datadir\");\n\n            // Assert\n            Assert.NotNull(connectionString);\n            Assert.Equal(@\"Data Source=.\\SQLEXPRESS;AttachDbFilename=c:\\foo.mdf;Initial Catalog=c:\\foo.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True\", connectionString);\n        }\n    }\n}\n"
  },
  {
    "path": "test/WebMatrix.Data.Test/Mocks/MockConfigurationManager.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace WebMatrix.Data.Test.Mocks\n{\n    internal class MockConfigurationManager : IConfigurationManager\n    {\n        private Dictionary<string, IConnectionConfiguration> _connectionStrings = new Dictionary<string, IConnectionConfiguration>();\n\n        public MockConfigurationManager()\n        {\n            AppSettings = new Dictionary<string, string>();\n        }\n\n        public IDictionary<string, string> AppSettings { get; private set; }\n\n        public void AddConnection(string name, IConnectionConfiguration configuration)\n        {\n            _connectionStrings.Add(name, configuration);\n        }\n\n        public IConnectionConfiguration GetConnection(string name)\n        {\n            IConnectionConfiguration configuration;\n            _connectionStrings.TryGetValue(name, out configuration);\n            return configuration;\n        }\n    }\n}\n"
  },
  {
    "path": "test/WebMatrix.Data.Test/Mocks/MockConnectionConfiguration.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace WebMatrix.Data.Test.Mocks\n{\n    public class MockConnectionConfiguration : IConnectionConfiguration\n    {\n        public MockConnectionConfiguration(string connectionString)\n        {\n            ConnectionString = connectionString;\n        }\n\n        public string ConnectionString { get; private set; }\n\n        string IConnectionConfiguration.ConnectionString\n        {\n            get { return ConnectionString; }\n        }\n\n        IDbProviderFactory IConnectionConfiguration.ProviderFactory\n        {\n            get { return null; }\n        }\n    }\n}\n"
  },
  {
    "path": "test/WebMatrix.Data.Test/Mocks/MockDbFileHandler.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nnamespace WebMatrix.Data.Test.Mocks\n{\n    public abstract class MockDbFileHandler : IDbFileHandler\n    {\n        IConnectionConfiguration IDbFileHandler.GetConnectionConfiguration(string fileName)\n        {\n            return GetConnectionConfiguration(fileName);\n        }\n\n        public abstract MockConnectionConfiguration GetConnectionConfiguration(string fileName);\n    }\n}\n"
  },
  {
    "path": "test/WebMatrix.Data.Test/Mocks/MockDbProviderFactory.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Data.Common;\n\nnamespace WebMatrix.Data.Test.Mocks\n{\n    // Needs to be public for Moq to work\n    public abstract class MockDbProviderFactory : IDbProviderFactory\n    {\n        public abstract DbConnection CreateConnection(string connectionString);\n    }\n}\n"
  },
  {
    "path": "test/WebMatrix.Data.Test/WebMatrix.Data.Test.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props\" Condition=\"Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" />\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" />\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{E2D008A9-4D1D-4F6B-8325-4ED717D6EA0A}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>WebMatrix.Data.Test</RootNamespace>\n    <AssemblyName>WebMatrix.Data.Test</AssemblyName>\n    <OutputPath>..\\..\\bin\\$(Configuration)\\Test\\</OutputPath>\n    <NuGetPackageImportStamp>\n    </NuGetPackageImportStamp>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Castle.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Castle.Core.5.1.1\\lib\\net462\\Castle.Core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"Moq, Version=4.18.0.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Moq.4.18.4\\lib\\net462\\Moq.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Configuration\" />\n    <Reference Include=\"System.Core\">\n      <RequiredTargetFramework>3.5</RequiredTargetFramework>\n    </Reference>\n    <Reference Include=\"System.Data\" />\n    <Reference Include=\"xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.abstractions.2.0.3\\lib\\net35\\xunit.abstractions.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.assert, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.assert.2.4.2\\lib\\netstandard1.1\\xunit.assert.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.core, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.core.2.4.2\\lib\\net452\\xunit.core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.execution.desktop, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.execution.2.4.2\\lib\\net452\\xunit.execution.desktop.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n  </ItemGroup>\n  <ItemGroup>\n    <CodeAnalysisDependentAssemblyPaths Condition=\" '$(VS100COMNTOOLS)' != '' \" Include=\"$(VS100COMNTOOLS)..\\IDE\\PrivateAssemblies\">\n      <Visible>False</Visible>\n    </CodeAnalysisDependentAssemblyPaths>\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\..\\src\\WebMatrix.Data\\WebMatrix.Data.csproj\">\n      <Project>{4D39BAAF-8A96-473E-AB79-C8A341885137}</Project>\n      <Name>WebMatrix.Data</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\">\n      <Project>{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}</Project>\n      <Name>Microsoft.TestCommon</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"ConfigurationManagerWrapperTest.cs\" />\n    <Compile Include=\"DynamicRecordTest.cs\" />\n    <Compile Include=\"FileHandlerTest.cs\" />\n    <Compile Include=\"Mocks\\MockConfigurationManager.cs\" />\n    <Compile Include=\"Mocks\\MockConnectionConfiguration.cs\" />\n    <Compile Include=\"Mocks\\MockDbFileHandler.cs\" />\n    <Compile Include=\"Mocks\\MockDbProviderFactory.cs\" />\n    <Compile Include=\"DatabaseTest.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Service Include=\"{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Analyzer Include=\"..\\..\\packages\\xunit.analyzers.1.1.0\\analyzers\\dotnet\\cs\\xunit.analyzers.dll\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\n  <Target Name=\"EnsureNuGetPackageBuildImports\" BeforeTargets=\"PrepareForBuild\">\n    <PropertyGroup>\n      <ErrorText>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}.</ErrorText>\n    </PropertyGroup>\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props'))\" />\n  </Target>\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" />\n</Project>"
  },
  {
    "path": "test/WebMatrix.Data.Test/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Castle.Core\" version=\"5.1.1\" targetFramework=\"net462\" />\n  <package id=\"Moq\" version=\"4.18.4\" targetFramework=\"net462\" />\n  <package id=\"xunit\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.abstractions\" version=\"2.0.3\" targetFramework=\"net462\" />\n  <package id=\"xunit.analyzers\" version=\"1.1.0\" targetFramework=\"net462\" />\n  <package id=\"xunit.assert\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.execution\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.runner.visualstudio\" version=\"2.4.5\" targetFramework=\"net462\" developmentDependency=\"true\" />\n</packages>"
  },
  {
    "path": "test/WebMatrix.WebData.Test/MockDatabase.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\n\nnamespace WebMatrix.WebData.Test\n{\n    public abstract class MockDatabase : IDatabase\n    {\n        public abstract dynamic QuerySingle(string commandText, params object[] args);\n\n        public abstract IEnumerable<dynamic> Query(string commandText, params object[] parameters);\n\n        public abstract dynamic QueryValue(string commandText, params object[] parameters);\n\n        public abstract int Execute(string commandText, params object[] args);\n\n        public void Dispose()\n        {\n            // Do nothing.\n        }\n    }\n}\n"
  },
  {
    "path": "test/WebMatrix.WebData.Test/PreApplicationStartCodeTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Configuration;\nusing System.Linq;\nusing System.Reflection;\nusing System.Web.Security;\nusing System.Web.WebPages.Razor;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\n\nnamespace WebMatrix.WebData.Test\n{\n    public class PreApplicationStartCodeTest\n    {\n        [Fact]\n        public void StartRegistersRazorNamespaces()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                AppDomainUtils.SetPreAppStartStage();\n                PreApplicationStartCode.Start();\n                // Call a second time to ensure multiple calls do not cause issues\n                PreApplicationStartCode.Start();\n\n                // Verify namespaces\n                var imports = WebPageRazorHost.GetGlobalImports();\n                Assert.Contains(imports, ns => ns.Equals(\"WebMatrix.Data\"));\n                Assert.Contains(imports, ns => ns.Equals(\"WebMatrix.WebData\"));\n            });\n        }\n\n        [Fact]\n        public void StartInitializesFormsAuthByDefault()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                AppDomainUtils.SetPreAppStartStage();\n                PreApplicationStartCode.Start();\n\n                string formsAuthLoginUrl = (string)typeof(FormsAuthentication).GetField(\"_LoginUrl\", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);\n                Assert.Equal(FormsAuthenticationSettings.DefaultLoginUrl, formsAuthLoginUrl);\n            });\n        }\n\n        [Fact]\n        public void StartDoesNotInitializeFormsAuthWhenDisabled()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                AppDomainUtils.SetPreAppStartStage();\n                ConfigurationManager.AppSettings[WebSecurity.EnableSimpleMembershipKey] = \"False\";\n                PreApplicationStartCode.Start();\n\n                string formsAuthLoginUrl = (string)typeof(FormsAuthentication).GetField(\"_LoginUrl\", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);\n                Assert.Null(formsAuthLoginUrl);\n            });\n        }\n\n        [Fact]\n        public void StartInitializesSimpleMembershipByDefault()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                AppDomainUtils.SetPreAppStartStage();\n                PreApplicationStartCode.Start();\n\n                // Verify simple membership\n                var providers = Membership.Providers;\n                Assert.NotEmpty(providers.OfType<SimpleMembershipProvider>());\n                Assert.True(Roles.Enabled);\n            });\n        }\n\n        [Fact]\n        public void StartDoesNotInitializeSimpleMembershipWhenDisabled()\n        {\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n            {\n                AppDomainUtils.SetPreAppStartStage();\n                ConfigurationManager.AppSettings[WebSecurity.EnableSimpleMembershipKey] = \"False\";\n                PreApplicationStartCode.Start();\n\n                // Verify simple membership\n                var providers = Membership.Providers;\n                Assert.Empty(providers.OfType<SimpleMembershipProvider>());\n                Assert.False(Roles.Enabled);\n            });\n        }\n\n        [Fact]\n        public void TestPreAppStartClass()\n        {\n            PreAppStartTestHelper.TestPreAppStartClass(typeof(PreApplicationStartCode));\n        }\n    }\n}\n"
  },
  {
    "path": "test/WebMatrix.WebData.Test/SimpleMembershipProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Linq;\nusing System.Security.Cryptography;\nusing System.Text;\nusing Microsoft.TestCommon;\nusing Moq;\nusing WebMatrix.Data;\n\nnamespace WebMatrix.WebData.Test\n{\n    public class SimpleMembershipProviderTest\n    {\n        [Fact]\n        public void ConfirmAccountReturnsFalseIfNoRecordExistsForToken()\n        {\n            // Arrange\n            var database = new Mock<MockDatabase>(MockBehavior.Strict);\n            database.As<IDisposable>().Setup(d => d.Dispose());\n            database.Setup(d => d.Query(\"SELECT [UserId], [ConfirmationToken] FROM webpages_Membership WHERE [ConfirmationToken] = @0\", \"foo\"))\n                .Returns(Enumerable.Empty<DynamicRecord>());\n            var simpleMembershipProvider = new TestSimpleMembershipProvider(database.Object);\n\n            // Act\n            bool result = simpleMembershipProvider.ConfirmAccount(\"foo\");\n\n            // Assert\n            Assert.False(result);\n        }\n\n        [Fact]\n        public void ConfirmAccountReturnsFalseIfConfirmationTokenDoesNotMatchInCase()\n        {\n            // Arrange\n            var database = new Mock<MockDatabase>(MockBehavior.Strict);\n            DynamicRecord record = GetRecord(98, \"Foo\");\n            database.As<IDisposable>().Setup(d => d.Dispose());\n            database.Setup(d => d.Query(\"SELECT [UserId], [ConfirmationToken] FROM webpages_Membership WHERE [ConfirmationToken] = @0\", \"foo\"))\n                .Returns(new[] { record });\n            var simpleMembershipProvider = new TestSimpleMembershipProvider(database.Object);\n\n            // Act\n            bool result = simpleMembershipProvider.ConfirmAccount(\"foo\");\n\n            // Assert\n            Assert.False(result);\n        }\n\n        [Fact]\n        public void ConfirmAccountReturnsFalseIfNoConfirmationTokenFromMultipleListMatchesInCase()\n        {\n            // Arrange\n            var database = new Mock<MockDatabase>(MockBehavior.Strict);\n            DynamicRecord recordA = GetRecord(98, \"Foo\");\n            DynamicRecord recordB = GetRecord(99, \"fOo\");\n            database.As<IDisposable>().Setup(d => d.Dispose());\n            database.Setup(d => d.Query(\"SELECT [UserId], [ConfirmationToken] FROM webpages_Membership WHERE [ConfirmationToken] = @0\", \"foo\"))\n                .Returns(new[] { recordA, recordB });\n            var simpleMembershipProvider = new TestSimpleMembershipProvider(database.Object);\n\n            // Act\n            bool result = simpleMembershipProvider.ConfirmAccount(\"foo\");\n\n            // Assert\n            Assert.False(result);\n        }\n\n        [Fact]\n        public void ConfirmAccountUpdatesIsConfirmedFieldIfConfirmationTokenMatches()\n        {\n            // Arrange\n            var database = new Mock<MockDatabase>(MockBehavior.Strict);\n            DynamicRecord record = GetRecord(100, \"foo\");\n            database.As<IDisposable>().Setup(d => d.Dispose());\n            database.Setup(d => d.Query(\"SELECT [UserId], [ConfirmationToken] FROM webpages_Membership WHERE [ConfirmationToken] = @0\", \"foo\"))\n                .Returns(new[] { record }).Verifiable();\n            database.Setup(d => d.Execute(\"UPDATE webpages_Membership SET [IsConfirmed] = 1 WHERE [UserId] = @0\", 100)).Returns(1).Verifiable();\n            var simpleMembershipProvider = new TestSimpleMembershipProvider(database.Object);\n\n            // Act\n            bool result = simpleMembershipProvider.ConfirmAccount(\"foo\");\n\n            // Assert\n            Assert.True(result);\n            database.Verify();\n        }\n\n        [Fact]\n        public void ConfirmAccountUpdatesIsConfirmedFieldIfAnyOneOfReturnRecordConfirmationTokenMatches()\n        {\n            // Arrange\n            var database = new Mock<MockDatabase>(MockBehavior.Strict);\n            DynamicRecord recordA = GetRecord(100, \"Foo\");\n            DynamicRecord recordB = GetRecord(101, \"foo\");\n            DynamicRecord recordC = GetRecord(102, \"fOo\");\n            database.As<IDisposable>().Setup(d => d.Dispose());\n            database.Setup(d => d.Query(\"SELECT [UserId], [ConfirmationToken] FROM webpages_Membership WHERE [ConfirmationToken] = @0\", \"foo\"))\n                .Returns(new[] { recordA, recordB, recordC }).Verifiable();\n            database.Setup(d => d.Execute(\"UPDATE webpages_Membership SET [IsConfirmed] = 1 WHERE [UserId] = @0\", 101)).Returns(1).Verifiable();\n            var simpleMembershipProvider = new TestSimpleMembershipProvider(database.Object);\n\n            // Act\n            bool result = simpleMembershipProvider.ConfirmAccount(\"foo\");\n\n            // Assert\n            Assert.True(result);\n            database.Verify();\n        }\n\n        [Fact]\n        public void ConfirmAccountWithUserNameReturnsFalseIfNoRecordExistsForToken()\n        {\n            // Arrange\n            var database = new Mock<MockDatabase>(MockBehavior.Strict);\n            database.As<IDisposable>().Setup(d => d.Dispose());\n            database.Setup(d => d.QuerySingle(\"SELECT m.[UserId], m.[ConfirmationToken] FROM webpages_Membership m JOIN [Users] u ON m.[UserId] = u.[UserId] WHERE m.[ConfirmationToken] = @0 AND u.[UserName] = @1\", \"foo\", \"user12\")).Returns(null);\n            var simpleMembershipProvider = new TestSimpleMembershipProvider(database.Object) { UserIdColumn = \"UserId\", UserNameColumn = \"UserName\", UserTableName = \"Users\" };\n\n            // Act\n            bool result = simpleMembershipProvider.ConfirmAccount(\"user12\", \"foo\");\n\n            // Assert\n            Assert.False(result);\n        }\n\n        [Fact]\n        public void ConfirmAccountWithUserNameReturnsFalseIfConfirmationTokenDoesNotMatchInCase()\n        {\n            // Arrange\n            var database = new Mock<MockDatabase>(MockBehavior.Strict);\n            DynamicRecord record = GetRecord(98, \"Foo\");\n            database.As<IDisposable>().Setup(d => d.Dispose());\n            database.Setup(d => d.QuerySingle(\"SELECT m.[UserId], m.[ConfirmationToken] FROM webpages_Membership m JOIN [Users_bkp2_1] u ON m.[UserId] = u.[wishlist_site_real_user_id] WHERE m.[ConfirmationToken] = @0 AND u.[wishlist_site_real_user_name] = @1\", \"foo\", \"user13\")).Returns(record);\n            var simpleMembershipProvider = new TestSimpleMembershipProvider(database.Object) { UserIdColumn = \"wishlist_site_real_user_id\", UserNameColumn = \"wishlist_site_real_user_name\", UserTableName = \"Users_bkp2_1\" };\n\n            // Act\n            bool result = simpleMembershipProvider.ConfirmAccount(\"user13\", \"foo\");\n\n            // Assert\n            Assert.False(result);\n        }\n\n        [Fact]\n        public void ConfirmAccountWithUserNameUpdatesIsConfirmedFieldIfConfirmationTokenMatches()\n        {\n            // Arrange\n            var database = new Mock<MockDatabase>(MockBehavior.Strict);\n            DynamicRecord record = GetRecord(100, \"foo\");\n            database.As<IDisposable>().Setup(d => d.Dispose());\n            database.Setup(d => d.QuerySingle(\"SELECT m.[UserId], m.[ConfirmationToken] FROM webpages_Membership m JOIN [Users] u ON m.[UserId] = u.[Id] WHERE m.[ConfirmationToken] = @0 AND u.[UserName] = @1\", \"foo\", \"user14\"))\n                .Returns(record).Verifiable();\n            database.Setup(d => d.Execute(\"UPDATE webpages_Membership SET [IsConfirmed] = 1 WHERE [UserId] = @0\", 100)).Returns(1).Verifiable();\n            var simpleMembershipProvider = new TestSimpleMembershipProvider(database.Object) { UserTableName = \"Users\", UserIdColumn = \"Id\", UserNameColumn = \"UserName\" };\n\n            // Act\n            bool result = simpleMembershipProvider.ConfirmAccount(\"user14\", \"foo\");\n\n            // Assert\n            Assert.True(result);\n            database.Verify();\n        }\n\n        [Fact]\n        public void GenerateTokenHtmlEncodesValues()\n        {\n            // Arrange\n            var generator = new Mock<RandomNumberGenerator>(MockBehavior.Strict);\n            var generatedBytes = Encoding.Default.GetBytes(\"|aÿx§#½oÿ↨îA8Eµ\");\n            generator.Setup(g => g.GetBytes(It.IsAny<byte[]>())).Callback((byte[] array) => Array.Copy(generatedBytes, array, generatedBytes.Length));\n\n            // Act\n            var result = SimpleMembershipProvider.GenerateToken(generator.Object);\n\n            // Assert\n            Assert.Equal(\"fGH/eKcjvW//P+5BOEW1\", Convert.ToBase64String(generatedBytes));\n            Assert.Equal(\"fGH_eKcjvW__P-5BOEW1AA2\", result);\n        }\n\n        [Fact]\n        public void GetUserId_WithCaseNormalization()\n        {\n            // Arrange\n            var database = new Mock<MockDatabase>(MockBehavior.Strict);\n            var expectedQuery = @\"SELECT userId FROM users WHERE (UPPER(userName) = UPPER(@0))\";\n            database.Setup(d => d.QueryValue(expectedQuery, \"zeke\")).Returns(999);\n\n            // Act\n            var result = SimpleMembershipProvider.GetUserId(\n                database.Object,\n                \"users\",\n                \"userName\",\n                \"userId\",\n                SimpleMembershipProviderCasingBehavior.NormalizeCasing,\n                \"zeke\");\n\n            // Assert\n            Assert.Equal(999, result);\n        }\n\n        [Fact]\n        public void GetUserId_WithoutCaseNormalization()\n        {\n            // Arrange\n            var database = new Mock<MockDatabase>(MockBehavior.Strict);\n            var expectedQuery = @\"SELECT userId FROM users WHERE (userName = @0)\";\n            database.Setup(d => d.QueryValue(expectedQuery, \"zeke\")).Returns(999);\n\n            // Act\n            var result = SimpleMembershipProvider.GetUserId(\n                database.Object,\n                \"users\",\n                \"userName\",\n                \"userId\",\n                SimpleMembershipProviderCasingBehavior.RelyOnDatabaseCollation,\n                \"zeke\");\n\n            // Assert\n            Assert.Equal(999, result);\n        }\n\n        [Theory]\n        [ReplaceCulture]\n        [InlineData(-1, false)]\n        [InlineData(0, true)]\n        [InlineData(1, true)]\n        [InlineData(2, false)]\n        public void SimpleMembershipProvider_CasingBehavior_ValidatesRange(int value, bool isValid)\n        {\n            // Arrange\n            var provider = new SimpleMembershipProvider();\n\n            var message =\n                \"The value of argument 'value' (\" + value + \") is invalid for Enum type \" +\n                \"'SimpleMembershipProviderCasingBehavior'.\" + Environment.NewLine +\n                \"Parameter name: value\";\n\n            // Act\n            Exception exception = null;\n\n            try\n            {\n                provider.CasingBehavior = (SimpleMembershipProviderCasingBehavior)value;\n            }\n            catch (Exception ex)\n            {\n                exception = ex;\n            }\n\n            // Assert\n            if (isValid)\n            {\n                Assert.Equal((SimpleMembershipProviderCasingBehavior)value, provider.CasingBehavior);\n            }\n            else\n            {\n                Assert.NotNull(exception);\n                Assert.IsAssignableFrom<InvalidEnumArgumentException>(exception);\n                Assert.Equal(message, exception.Message);\n            }\n        }\n\n        private static DynamicRecord GetRecord(int userId, string confirmationToken)\n        {\n            var data = new Mock<IDataRecord>(MockBehavior.Strict);\n            data.Setup(c => c[0]).Returns(userId);\n            data.Setup(c => c[1]).Returns(confirmationToken);\n            return new DynamicRecord(new[] { \"UserId\", \"ConfirmationToken\" }, data.Object);\n        }\n\n        private class TestSimpleMembershipProvider : SimpleMembershipProvider\n        {\n            private readonly IDatabase _database;\n\n            public TestSimpleMembershipProvider(IDatabase database)\n            {\n                _database = database;\n            }\n\n            internal override IDatabase ConnectToDatabase()\n            {\n                return _database;\n            }\n\n            internal override void VerifyInitialized()\n            {\n                // Do nothing.\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/WebMatrix.WebData.Test/SimpleRoleProviderTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.ComponentModel;\nusing Microsoft.TestCommon;\n\nnamespace WebMatrix.WebData.Test\n{\n    public class SimpleRoleProviderTest\n    {\n        [Theory]\n        [ReplaceCulture]\n        [InlineData(-1, false)]\n        [InlineData(0, true)]\n        [InlineData(1, true)]\n        [InlineData(2, false)]\n        public void SimpleRoleProvider_CasingBehavior_ValidatesRange(int value, bool isValid)\n        {\n            // Arrange\n            var provider = new SimpleRoleProvider();\n\n            var message =\n                \"The value of argument 'value' (\" + value + \") is invalid for Enum type \" +\n                \"'SimpleMembershipProviderCasingBehavior'.\" + Environment.NewLine +\n                \"Parameter name: value\";\n\n            // Act\n            Exception exception = null;\n\n            try\n            {\n                provider.CasingBehavior = (SimpleMembershipProviderCasingBehavior)value;\n            }\n            catch (Exception ex)\n            {\n                exception = ex;\n            }\n\n            // Assert\n            if (isValid)\n            {\n                Assert.Equal((SimpleMembershipProviderCasingBehavior)value, provider.CasingBehavior);\n            }\n            else\n            {\n                Assert.NotNull(exception);\n                Assert.IsAssignableFrom<InvalidEnumArgumentException>(exception);\n                Assert.Equal(message, exception.Message);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "test/WebMatrix.WebData.Test/WebMatrix.WebData.Test.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import Project=\"..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props\" Condition=\"Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" />\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" />\n  <Import Project=\"$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory),Runtime.sln))\\tools\\WebStack.settings.targets\" />\n  <PropertyGroup>\n    <ProjectGuid>{CD48EB41-92A5-4628-A0F7-6A43DF58827E}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>WebMatrix.WebData.Test</RootNamespace>\n    <AssemblyName>WebMatrix.WebData.Test</AssemblyName>\n    <OutputPath>..\\..\\bin\\$(Configuration)\\Test\\</OutputPath>\n    <NuGetPackageImportStamp>\n    </NuGetPackageImportStamp>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"Castle.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Castle.Core.5.1.1\\lib\\net462\\Castle.Core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"Moq, Version=4.18.0.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\Moq.4.18.4\\lib\\net462\\Moq.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.configuration\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Web\" />\n    <Reference Include=\"System.Web.ApplicationServices\" />\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"System.Data\" />\n    <Reference Include=\"xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.abstractions.2.0.3\\lib\\net35\\xunit.abstractions.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.assert, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.assert.2.4.2\\lib\\netstandard1.1\\xunit.assert.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.core, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.core.2.4.2\\lib\\net452\\xunit.core.dll</HintPath>\n      <Private>True</Private>\n    </Reference>\n    <Reference Include=\"xunit.execution.desktop, Version=2.4.2.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL\">\n      <HintPath>..\\..\\packages\\xunit.extensibility.execution.2.4.2\\lib\\net452\\xunit.execution.desktop.dll</HintPath>\n    </Reference>\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"MockDatabase.cs\" />\n    <Compile Include=\"PreApplicationStartCodeTest.cs\" />\n    <Compile Include=\"SimpleMembershipProviderTest.cs\" />\n    <Compile Include=\"SimpleRoleProviderTest.cs\" />\n    <Compile Include=\"WebSecurityTest.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.Razor\\System.Web.Razor.csproj\">\n      <Project>{8F18041B-9410-4C36-A9C5-067813DF5F31}</Project>\n      <Name>System.Web.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\System.Web.WebPages.Razor\\System.Web.WebPages.Razor.csproj\">\n      <Project>{0939B11A-FE4E-4BA1-8AD6-D97741EE314F}</Project>\n      <Name>System.Web.WebPages.Razor</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\WebMatrix.Data\\WebMatrix.Data.csproj\">\n      <Project>{4D39BAAF-8A96-473E-AB79-C8A341885137}</Project>\n      <Name>WebMatrix.Data</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\..\\src\\WebMatrix.WebData\\WebMatrix.WebData.csproj\">\n      <Project>{55A15F40-1435-4248-A7F2-2A146BB83586}</Project>\n      <Name>WebMatrix.WebData</Name>\n    </ProjectReference>\n    <ProjectReference Include=\"..\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj\">\n      <Project>{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}</Project>\n      <Name>Microsoft.TestCommon</Name>\n    </ProjectReference>\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"packages.config\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Service Include=\"{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Analyzer Include=\"..\\..\\packages\\xunit.analyzers.1.1.0\\analyzers\\dotnet\\cs\\xunit.analyzers.dll\" />\n  </ItemGroup>\n  <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\n  <Target Name=\"EnsureNuGetPackageBuildImports\" BeforeTargets=\"PrepareForBuild\">\n    <PropertyGroup>\n      <ErrorText>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}.</ErrorText>\n    </PropertyGroup>\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.props'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets'))\" />\n    <Error Condition=\"!Exists('..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props')\" Text=\"$([System.String]::Format('$(ErrorText)', '..\\..\\packages\\xunit.runner.visualstudio.2.4.5\\build\\net462\\xunit.runner.visualstudio.props'))\" />\n  </Target>\n  <Import Project=\"..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets\" Condition=\"Exists('..\\..\\packages\\xunit.core.2.4.2\\build\\xunit.core.targets')\" />\n</Project>"
  },
  {
    "path": "test/WebMatrix.WebData.Test/WebSecurityTest.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Collections.Generic;\nusing System.Configuration.Provider;\nusing System.Reflection;\nusing System.Web.Security;\nusing System.Web.WebPages.TestUtils;\nusing Microsoft.TestCommon;\nusing Moq;\n\nnamespace WebMatrix.WebData.Test\n{\n    public class WebSecurityTest\n    {\n        [Fact]\n        public void CreateUserAndAccount_WillAcceptBothObjectsAndDictionariesForExtendedParameters()\n        {\n            // since it is a static helper - you gotta love 'em\n            AppDomainUtils.RunInSeparateAppDomain(() =>\n                {\n                    // we need that in order to make sure the Membership static class is initialized correctly\n                    var discard = Membership.Provider as ProviderBase;\n\n                    // Arrange\n                    var providerMock = new Mock<ExtendedMembershipProvider>();\n                    providerMock.Setup(\n                        p => p.CreateUserAndAccount(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<IDictionary<string, object>>()))\n                                .Returns((string username, string password, bool requireConfirmation, IDictionary<string, object> values) => \"foo = \" + values[\"foo\"]);\n                    typeof(Membership).GetField(\"s_Provider\", BindingFlags.Static | BindingFlags.NonPublic).SetValue(null, providerMock.Object);\n\n                    // Act\n                    var resultWithObject = WebSecurity.CreateUserAndAccount(\"name\", \"pass\", new { foo = \"bar\" });\n                    var resultWithDictionary = WebSecurity.CreateUserAndAccount(\"name\", \"pass\", new Dictionary<string, object> { { \"foo\", \"baz\" } });\n\n                    // Assert\n                    Assert.Equal(\"foo = bar\", resultWithObject);\n                    Assert.Equal(\"foo = baz\", resultWithDictionary);\n                });\n        }\n\n        [Fact]\n        public void VerifyExtendedMembershipProviderMethodsThrowWithInvalidProvider()\n        {\n            const string errorString = \"To call this method, the \\\"Membership.Provider\\\" property must be an instance of \\\"ExtendedMembershipProvider\\\".\";\n            Assert.Throws<InvalidOperationException>(() => WebSecurity.ConfirmAccount(\"\"), errorString);\n            Assert.Throws<InvalidOperationException>(() => WebSecurity.GeneratePasswordResetToken(\"\"), errorString);\n            Assert.Throws<InvalidOperationException>(() => WebSecurity.GetUserIdFromPasswordResetToken(\"\"), errorString);\n            Assert.Throws<InvalidOperationException>(() => WebSecurity.ResetPassword(\"\", \"whatever\"), errorString);\n            Assert.Throws<InvalidOperationException>(() => WebSecurity.CreateUserAndAccount(\"\", \"whatever\"), errorString);\n            Assert.Throws<InvalidOperationException>(() => WebSecurity.CreateAccount(\"\", \"whatever\"), errorString);\n            Assert.Throws<InvalidOperationException>(() => WebSecurity.IsConfirmed(\"whatever\"), errorString);\n            Assert.Throws<InvalidOperationException>(() => WebSecurity.GetPasswordFailuresSinceLastSuccess(\"whatever\"), errorString);\n            Assert.Throws<InvalidOperationException>(() => WebSecurity.GetCreateDate(\"whatever\"), errorString);\n            Assert.Throws<InvalidOperationException>(() => WebSecurity.GetLastPasswordFailureDate(\"whatever\"), errorString);\n            Assert.Throws<InvalidOperationException>(() => WebSecurity.GetPasswordChangedDate(\"whatever\"), errorString);\n        }\n    }\n}\n"
  },
  {
    "path": "test/WebMatrix.WebData.Test/packages.config",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n  <package id=\"Castle.Core\" version=\"5.1.1\" targetFramework=\"net462\" />\n  <package id=\"Moq\" version=\"4.18.4\" targetFramework=\"net462\" />\n  <package id=\"xunit\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.abstractions\" version=\"2.0.3\" targetFramework=\"net462\" />\n  <package id=\"xunit.analyzers\" version=\"1.1.0\" targetFramework=\"net462\" />\n  <package id=\"xunit.assert\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.core\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.extensibility.execution\" version=\"2.4.2\" targetFramework=\"net462\" />\n  <package id=\"xunit.runner.visualstudio\" version=\"2.4.5\" targetFramework=\"net462\" developmentDependency=\"true\" />\n</packages>"
  },
  {
    "path": "tools/SkipStrongNames.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<assemblies defaultPublicKeyToken=\"31bf3856ad364e35\">\n  <!-- Production assemblies -->\n  <assembly name=\"Microsoft.AspNet.Facebook\"/>\n  <assembly name=\"System.Web.Cors\"/>\n  <assembly name=\"Microsoft.Web.Helpers\"/>\n  <assembly name=\"Microsoft.Web.Http.Data\"/>\n  <assembly name=\"Microsoft.Web.Http.Data.EntityFramework\"/>\n  <assembly name=\"Microsoft.Web.Http.Data.Helpers\"/>\n  <assembly name=\"Microsoft.Web.WebPages.OAuth\"/>\n  <assembly name=\"System.Json\"/>\n  <assembly name=\"System.Net.Http.Formatting\"/>\n  <assembly name=\"System.Web.Helpers\"/>\n  <assembly name=\"System.Web.Http\"/>\n  <assembly name=\"System.Web.Http.Common\"/>\n  <assembly name=\"System.Web.Http.Cors\"/>\n  <assembly name=\"System.Web.Http.OData\"/>\n  <assembly name=\"System.Web.Http.Owin\"/>\n  <assembly name=\"System.Web.Http.SelfHost\"/>\n  <assembly name=\"System.Web.Http.SignalR\"/>\n  <assembly name=\"System.Web.Http.Tracing\"/>\n  <assembly name=\"System.Web.Http.WebHost\"/>\n  <assembly name=\"System.Web.Mvc\"/>\n  <assembly name=\"System.Web.OData\"/>\n  <assembly name=\"System.Web.Razor\"/>\n  <assembly name=\"System.Web.WebPages\"/>\n  <assembly name=\"System.Web.WebPages.Administration\"/>\n  <assembly name=\"System.Web.WebPages.Deployment\"/>\n  <assembly name=\"System.Web.WebPages.Razor\"/>\n  <assembly name=\"WebApiHelpPage\"/>\n  <assembly name=\"WebApiHelpPageVB\"/>\n  <assembly name=\"WebMatrix.Data\"/>\n  <assembly name=\"WebMatrix.WebData\"/>\n\n  <!-- Unit test assemblies and helpers -->\n  <assembly name=\"Microsoft.AspNet.Facebook.Test\"/>\n  <assembly name=\"Microsoft.TestCommon\"/>\n  <assembly name=\"Microsoft.Web.Helpers.Test\"/>\n  <assembly name=\"Microsoft.Web.Http.Data.Test\"/>\n  <assembly name=\"Microsoft.Web.WebPages.OAuth.Test\"/>\n  <assembly name=\"System.Json.Test\"/>\n  <assembly name=\"System.Json.Test.Integration\"/>\n  <assembly name=\"System.Net.Http.Formatting.Test\"/>\n  <assembly name=\"System.Net.Http.Formatting.ns1_3.Test\"/>\n  <assembly name=\"System.Net.Http.Formatting.ns2_0.Test\"/>\n  <assembly name=\"System.Net.Http.Formatting.Test.Integration\"/>\n  <assembly name=\"System.Web.Cors.Test\"/>\n  <assembly name=\"System.Web.Helpers.Test\"/>\n  <assembly name=\"System.Web.Http.Common.Test\"/>\n  <assembly name=\"System.Web.Http.Cors.Test\"/>\n  <assembly name=\"System.Web.Http.Integration.Test\"/>\n  <assembly name=\"System.Web.Http.OData.Test\"/>\n  <assembly name=\"System.Web.Http.Owin.Test\"/>\n  <assembly name=\"System.Web.Http.SelfHost.Test\"/>\n  <assembly name=\"System.Web.Http.SignalR.Test\"/>\n  <assembly name=\"System.Web.Http.Test\"/>\n  <assembly name=\"System.Web.Http.Tracing.Test\"/>\n  <assembly name=\"System.Web.Http.WebHost.Test\"/>\n  <assembly name=\"System.Web.Mvc.Test\"/>\n  <assembly name=\"System.Web.OData.Test\"/>\n  <assembly name=\"System.Web.Razor.Test\"/>\n  <assembly name=\"System.Web.WebPages.Administration.Test\"/>\n  <assembly name=\"System.Web.WebPages.Deployment.Test\"/>\n  <assembly name=\"System.Web.WebPages.Razor.Test\"/>\n  <assembly name=\"System.Web.WebPages.Test\"/>\n  <assembly name=\"WebApiHelpPage.Test\"/>\n  <assembly name=\"WebApiHelpPage.VB.Test\" />\n  <assembly name=\"WebMatrix.Data.Test\"/>\n  <assembly name=\"WebMatrix.WebData.Test\"/>\n</assemblies>\n"
  },
  {
    "path": "tools/WebStack.StyleCop.targets",
    "content": "﻿<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <ItemGroup>\n    <StyleCopMsBuildRunner Include=\"$(WebStackRootPath)packages\\StyleCop.5.0.0\\**\\StyleCop.dll\"/>\n    <StyleCopAdditionalAddins Include=\"$(WebStackRootPath)packages\\Microsoft.Web.SkipStrongNames.1.0.0\\**\\Microsoft.Web.StyleCop.dll\" />\n    <StyleCopAdditionalAddinPaths Include=\"@(StyleCopAdditionalAddins -> '%(RootDir)%(Directory)')\" />\n  </ItemGroup>\n\n  <UsingTask AssemblyFile=\"@(StyleCopMsBuildRunner)\" TaskName=\"StyleCopTask\" Condition=\" '@(StyleCopMsBuildRunner)' != '' \" />\n\n  <PropertyGroup>\n    <PrepareForRunDependsOn>$(PrepareForRunDependsOn);StyleCop</PrepareForRunDependsOn>\n  </PropertyGroup>\n\n  <PropertyGroup>\n    <IsStyleCopEnabled Condition=\"'$(IsStyleCopEnabled)' == ''\">$(StyleCopEnabled)</IsStyleCopEnabled>\n    <StyleCopForceFullAnalysis Condition=\"'$(StyleCopForceFullAnalysis)' == ''\">false</StyleCopForceFullAnalysis>\n    <StyleCopCacheResults Condition=\"'$(StyleCopCacheResults)' == ''\">true</StyleCopCacheResults>\n    <StyleCopTreatErrorsAsWarnings Condition=\"'$(StyleCopTreatErrorsAsWarnings)' == ''\">true</StyleCopTreatErrorsAsWarnings>\n    <StyleCopOverrideSettingsFile Condition=\"'$(StyleCopOverrideSettingsFile)' == ''\"> </StyleCopOverrideSettingsFile>\n    <StyleCopOutputFile Condition=\"'$(StyleCopOutputFile)' == ''\">$(IntermediateOutputPath)StyleCopViolations.xml</StyleCopOutputFile>\n    <StyleCopSuccessMarkerFile Condition=\"'$(StyleCopSuccessMarkerFile)' == ''\">$(IntermediateOutputPath)StyleCop.success</StyleCopSuccessMarkerFile>\n    <!-- Specifying 0 will cause StyleCop to use the default violation count limit.\n         Specifying any positive number will cause StyleCop to use that number as the violation count limit.\n         Specifying any negative number will cause StyleCop to allow any number of violations without limit. -->\n    <StyleCopMaxViolationCount Condition=\"'$(StyleCopMaxViolationCount)' == ''\">0</StyleCopMaxViolationCount>\n  </PropertyGroup>\n\n  <!-- Define target: StyleCop -->\n  <Target Name=\"StyleCop\" Inputs=\"@(Compile)\" Outputs=\"$(StyleCopSuccessMarkerFile)\" Condition=\"'$(IsStyleCopEnabled)' == 'true'\">\n    <PropertyGroup>\n      <StyleCopMsBuildRunner>@(StyleCopMsBuildRunner)</StyleCopMsBuildRunner>\n    </PropertyGroup>\n    <Error Text=\"Multiple StyleCop copies detected. Please clean out your packages folder and try again.\"\n           Condition=\" $(StyleCopMsBuildRunner.Contains(';')) \" />\n\n    <Delete Files=\"$(StyleCopSuccessMarkerFile)\" Condition=\"Exists('$(StyleCopSuccessMarkerFile)')\" />\n\n    <Message Text=\"Running Style Analysis...\" Importance=\"high\" />\n    <Message Text=\"Forcing full StyleCop reanalysis.\" Condition=\"'$(StyleCopForceFullAnalysis)' == 'true'\" Importance=\"Low\" />\n\n    <!-- Determine what files should be checked. Take all Compile items, but exclude those that have\n        set ExcludeFromStyleCop=true or ExcludeFromSourceAnalysis=true. -->\n    <ItemGroup>\n      <StyleCopFiles Include=\"@(Compile)\" Condition=\" '%(Compile.ExcludeFromStyleCop)' != 'true' and '%(Compile.ExcludeFromSourceAnalysis)' != 'true'\" />\n      <StyleCopExcludedFiles Include=\"@(Compile)\" Condition=\" '%(Compile.ExcludeFromStyleCop)' == 'true' or '%(Compile.ExcludeFromSourceAnalysis)' == 'true'\" />\n    </ItemGroup>\n\n    <Message Text=\"Analyzing @(StyleCopFiles)\" Importance=\"Low\" />\n\n    <!-- Show list of what files should be excluded. checked. Take all Compile items, but exclude those that have\n        set ExcludeFromStyleCop=true or ExcludeFromSourceAnalysis=true. -->\n    <Message Text=\"Excluding @(StyleCopExcludedFiles)\" Importance=\"Normal\" Condition=\" '@(StyleCopExcludedFiles)' != '' \"/>\n\n    <!-- Run the StyleCop MSBuild task. -->\n    <StyleCopTask\n      ProjectFullPath=\"$(MSBuildProjectDirectory)\"\n      SourceFiles=\"@(StyleCopFiles)\"\n      AdditionalAddinPaths=\"@(StyleCopAdditionalAddinPaths)\"\n      ForceFullAnalysis=\"$(StyleCopForceFullAnalysis)\"\n      DefineConstants=\"$(DefineConstants)\"\n      TreatErrorsAsWarnings=\"$(StyleCopTreatErrorsAsWarnings)\"\n      CacheResults=\"$(StyleCopCacheResults)\"\n      OverrideSettingsFile=\"$(StyleCopOverrideSettingsFile)\"\n      OutputFile=\"$(StyleCopOutputFile)\"\n      MaxViolationCount=\"$(StyleCopMaxViolationCount)\" />\n\n    <!-- Make output files cleanable -->\n    <ItemGroup>\n      <FileWrites Include=\"$(StyleCopOutputFile)\" />\n      <FileWrites Include=\"$(StyleCopSuccessMarkerFile)\" />\n    </ItemGroup>\n\n    <Touch Files=\"$(StyleCopSuccessMarkerFile)\" AlwaysCreate=\"true\" />\n\n    <!-- Add the StyleCop.cache file to the list of files we've written - so they can be cleaned up on a Build Clean. -->\n    <CreateItem Include=\"StyleCop.Cache\" Condition=\"'$(StyleCopCacheResults)' == 'true'\">\n      <Output TaskParameter=\"Include\" ItemName=\"FileWrites\"/>\n    </CreateItem>\n  </Target>\n</Project>\n"
  },
  {
    "path": "tools/WebStack.settings.targets",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <Import\n      Project=\"$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props\"\n      Condition=\"'$(MicrosoftCommonPropsHasBeenImported)' != 'true' AND Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')\"/>\n  <Import Project=\"$(CustomBeforeWebStackTargets)\" Condition=\"Exists('$(CustomBeforeWebStackTargets)')\" Label=\"Pre-targets Build Extensibility Point\"/>\n\n  <PropertyGroup>\n    <!-- Define some basic reference paths -->\n    <WebStackRootPath>$([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)..\\'))</WebStackRootPath>\n    <WebStackToolsPath>$(MSBuildThisFileDirectory)</WebStackToolsPath>\n\n    <!-- Use CustomAfterMicrosoftCommonTargets property (defined in Microsoft.Common.targets) to\n             inject post-Common targets files without requiring the inclusion -->\n    <CustomAfterMicrosoftCommonTargets>$(WebStackToolsPath)WebStack.targets</CustomAfterMicrosoftCommonTargets>\n\n    <!-- Force rebuild if this file changes -->\n    <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>\n  </PropertyGroup>\n\n  <!-- Project Defaults -->\n  <PropertyGroup>\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\n    <OutputPath Condition=\"'$(OutputPath)' == ''\">$(WebStackRootPath)bin\\$(Configuration)\\</OutputPath>\n    <Platform Condition=\" '$(Platform)' == '' \">AnyCPU</Platform>\n    <FileAlignment>512</FileAlignment>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>4</WarningLevel>\n    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>\n\n    <!-- Variables for output redirection (localization, signing, etc)-->\n    <Language Condition=\" '$(Language)' == '' \">ENU</Language>\n    <LocalizedPath Condition=\" '$(LocalizedPath)' == '' \"></LocalizedPath>\n\n    <!-- StyleCop support -->\n    <StyleCopTreatErrorsAsWarnings Condition=\" '$(StyleCopTreatErrorsAsWarnings)' == '' \">false</StyleCopTreatErrorsAsWarnings>\n    <StyleCopEnabled Condition=\" '$(StyleCopEnabled)' == '' \">false</StyleCopEnabled>\n\n    <!-- Use latest C# compiler supported in Visual Studio 2019. -->\n    <LangVersion Condition=\" '$(MSBuildProjectExtension)' == '.csproj' \">9.0</LangVersion>\n\n    <!-- Everything is delay signed by default -->\n    <SignAssembly>true</SignAssembly>\n    <DelaySign>true</DelaySign>\n    <AssemblyOriginatorKeyFile>$(WebStackRootPath)\\tools\\35MSSharedLib1024.snk</AssemblyOriginatorKeyFile>\n  </PropertyGroup>\n\n  <!-- Per-configuration properties -->\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \">\n    <DebugSymbols>true</DebugSymbols>\n    <DebugType>full</DebugType>\n    <Optimize>false</Optimize>\n    <DefineConstants>TRACE;DEBUG;CODE_ANALYSIS</DefineConstants>\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' \">\n    <DebugType>pdbonly</DebugType>\n    <Optimize>true</Optimize>\n    <DefineConstants>TRACE</DefineConstants>\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'CodeAnalysis|AnyCPU' \">\n    <DebugType>pdbonly</DebugType>\n    <Optimize>true</Optimize>\n    <DefineConstants>TRACE;CODE_ANALYSIS</DefineConstants>\n  </PropertyGroup>\n</Project>"
  },
  {
    "path": "tools/WebStack.targets",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n    <Import Project=\"$(WebStackToolsPath)WebStack.StyleCop.targets\"/>\n    <Import Project=\"$(CustomAfterWebStackTargets)\" Condition=\"Exists('$(CustomAfterWebStackTargets)')\" Label=\"Post-targets Build Extensibility Point\" />\n</Project>"
  },
  {
    "path": "tools/WebStack.tasks.targets",
    "content": "<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <PropertyGroup>\n    <BuildTaskAssemblyReference Condition=\" '$(BuildTaskAssemblyReference)' == '' And Exists('$(MSBuildToolsPath)\\Microsoft.Build.Tasks.Core.dll') \">Microsoft.Build.Tasks.Core</BuildTaskAssemblyReference>\n    <BuildTaskAssemblyReference Condition=\" '$(BuildTaskAssemblyReference)' == '' And Exists('$(MSBuildToolsPath)\\Microsoft.Build.Tasks.v$(MSBuildToolsVersion).dll') \">Microsoft.Build.Tasks.v$(MSBuildToolsVersion)</BuildTaskAssemblyReference>\n    <BuildTaskAssemblyReference Condition=\" '$(BuildTaskAssemblyReference)' == '' And Exists('$(MSBuildToolsPath)\\Microsoft.Build.Tasks.v4.0.dll') \">Microsoft.Build.Tasks.v4.0</BuildTaskAssemblyReference>\n    <!-- Know this file does not exist. But, error message will contain meaningful information. -->\n    <BuildTaskAssemblyReference Condition=\" '$(BuildTaskAssemblyReference)' == '' \">Microsoft.Build.Tasks.Core</BuildTaskAssemblyReference>\n    <CodeTaskFactoryAssemblyFile Condition=\" '$(CodeTaskFactoryAssemblyFile)' == '' \">$(MSBuildToolsPath)\\$(BuildTaskAssemblyReference).dll</CodeTaskFactoryAssemblyFile>\n  </PropertyGroup>\n\n  <!-- This task does not support concurrent execution from multiple project files. Its use is only appropriate when\n        NuGet.exe is not in use. -->\n  <UsingTask TaskName=\"DownloadNuGet\" TaskFactory=\"CodeTaskFactory\" AssemblyFile=\"$(CodeTaskFactoryAssemblyFile)\">\n    <ParameterGroup>\n      <OutputFileName ParameterType=\"System.String\" Required=\"true\" />\n      <MinimumVersion ParameterType=\"System.String\" Required=\"true\" />\n    </ParameterGroup>\n    <Task>\n      <Reference Include=\"System.Core\" />\n      <Using Namespace=\"System\" />\n      <Using Namespace=\"System.Diagnostics\" />\n      <Using Namespace=\"System.IO\" />\n      <Using Namespace=\"System.Net\" />\n      <Using Namespace=\"Microsoft.Build.Framework\" />\n      <Using Namespace=\"Microsoft.Build.Utilities\" />\n      <Code Type=\"Fragment\" Language=\"cs\">\n        <![CDATA[\n                Version minimumRequiredVersion;\n\n                if (!Version.TryParse(MinimumVersion, out minimumRequiredVersion))\n                {\n                    Log.LogError(\"MinimumVersion '{0}' is not a valid Version.\", MinimumVersion);\n                    return false;\n                }\n\n                try\n                {\n                    OutputFileName = Path.GetFullPath(OutputFileName);\n\n                    if (File.Exists(OutputFileName))\n                    {\n                        // If NuGet.exe exists but is less than the minimum required version, delete it so that the\n                        // latest version will be downloaded.\n                        FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(OutputFileName);\n\n                        string toParse;\n\n                        if (versionInfo != null && versionInfo.ProductVersion != null)\n                        {\n                            toParse = versionInfo.ProductVersion;\n                            int index = toParse.IndexOfAny(new[] {'-', '+'});\n                            if (index > 0)\n                            {\n                                toParse = toParse.Substring(0, index);\n                            }\n                        }\n                        else\n                        {\n                            toParse = null;\n                        }\n\n                        Version current;\n                        Version parsed;\n\n                        if (toParse != null && Version.TryParse(toParse, out parsed))\n                        {\n                            current = parsed;\n                        }\n                        else\n                        {\n                            // Treat a missing or invalid version like V0.0 (which will trigger a delete and download).\n                            current = new Version(0, 0);\n                        }\n\n                        if (current < minimumRequiredVersion)\n                        {\n                            File.Delete(OutputFileName);\n                        }\n                    }\n\n                    if (!File.Exists(OutputFileName))\n                    {\n                        Log.LogMessage(MessageImportance.High, \"Downloading latest version of NuGet.exe...\");\n                        WebClient webClient = new WebClient();\n                        webClient.DownloadFile(\"https://dist.nuget.org/win-x86-commandline/latest/nuget.exe\", OutputFileName);\n                    }\n\n                    return true;\n                }\n                catch (Exception ex)\n                {\n                    Log.LogErrorFromException(ex);\n                    return false;\n                }\n            ]]>\n      </Code>\n    </Task>\n  </UsingTask>\n\n  <UsingTask TaskName=\"PrintTestRunSummary\" TaskFactory=\"CodeTaskFactory\" AssemblyFile=\"$(CodeTaskFactoryAssemblyFile)\">\n    <ParameterGroup>\n      <TestResultsDirectory ParameterType=\"System.String\" Required=\"true\" />\n    </ParameterGroup>\n    <Task>\n      <Reference Include=\"System.Xml\" />\n      <Reference Include=\"System.Xml.Linq\" />\n      <Using Namespace=\"System\" />\n      <Using Namespace=\"System.Collections.Generic\" />\n      <Using Namespace=\"System.IO\" />\n      <Using Namespace=\"System.Linq\" />\n      <Using Namespace=\"System.Text\" />\n      <Using Namespace=\"System.Text.RegularExpressions\" />\n      <Using Namespace=\"System.Xml.Linq\" />\n      <Using Namespace=\"Microsoft.Build.Framework\" />\n      <Using Namespace=\"Microsoft.Build.Utilities\" />\n      <Code Type=\"Fragment\" Language=\"cs\">\n        <![CDATA[\n                try\n                {\n                    string[] testResultFiles = Directory.GetFiles(TestResultsDirectory);\n                    Regex regex = new Regex(\"&#x(?<char>[0-9A-Fa-f]+);\",\n                        RegexOptions.Multiline | RegexOptions.Compiled);\n                    int testsPassed = 0;\n                    int testsFailed = 0;\n                    int testsSkipped = 0;\n                    decimal timeSpent = 0;\n                    List<string> testFailures = new List<string>();\n\n                    foreach (string testResultFile in testResultFiles)\n                    {\n                        // Replace potentially illegal escaped characters (if they get through validations done during Save).\n                        string fullPath = Path.GetFullPath(testResultFile);\n                        string originalText = File.ReadAllText(fullPath);\n                        bool matched = regex.IsMatch(originalText);\n\n                        if (matched)\n                        {\n                            File.SetAttributes(fullPath, File.GetAttributes(fullPath) & ~FileAttributes.ReadOnly);\n                            File.WriteAllText(fullPath, regex.Replace(originalText, \"\\0x${char}\"), Encoding.UTF8);\n                        }\n\n                        // Collect test failure information from results file.\n                        XElement xml;\n                        using (FileStream fileStream = File.OpenRead(fullPath))\n                        {\n                            xml = XElement.Load(fileStream);\n                        }\n\n                        var assemblies = xml.Elements(XName.Get(\"assembly\"));\n                        foreach (XElement assembly in assemblies)\n                        {\n                            XAttribute failed = assembly.Attribute(XName.Get(\"failed\"));\n                            if (failed == null)\n                            {\n                                // Occasionally xUnit does not write information about test assembly completion.\n                                XAttribute name = assembly.Attribute(XName.Get(\"name\"));\n                                Log.LogWarning(\n                                    \"No results in {0} for {1}.\",\n                                    testResultFile,\n                                    name == null ? \"unknown assembly\" : name.Value);\n\n                                continue;\n                            }\n\n                            int failures = Int32.Parse(failed.Value);\n                            testsFailed += failures;\n\n                            testsPassed += Int32.Parse(assembly.Attribute(XName.Get(\"passed\")).Value);\n                            testsSkipped += Int32.Parse(assembly.Attribute(XName.Get(\"skipped\")).Value);\n                            timeSpent += Decimal.Parse(assembly.Attribute(XName.Get(\"time\")).Value);\n\n                            if (failures > 0)\n                            {\n                                foreach (XElement classWithFailure in assembly.Elements(XName.Get(\"collection\"))\n                                    .Where(c => Int32.Parse(c.Attribute(XName.Get(\"failed\")).Value) > 0))\n                                {\n                                    foreach (XElement failure in classWithFailure.Elements(XName.Get(\"test\"))\n                                        .Where(test => test.Attribute(XName.Get(\"result\")).Value == \"Fail\"))\n                                    {\n                                        testFailures.Add(failure.Attribute(\"name\").Value);\n                                    }\n                                }\n                            }\n                        }\n                    }\n\n                    // Log all test failures.\n                    if (testFailures.Count > 0)\n                    {\n                        Log.LogMessage(MessageImportance.High, string.Empty);\n                        Log.LogError(\"Tests failed...\");\n                        foreach (string testFailure in testFailures)\n                        {\n                            // Provide the list of failed tests but don't repeat it in the build summary. List\n                            // is usually less helpful than errors from tests themselves (which are repeated)\n                            // because those errors include the exact failure locations. On the other hand,\n                            // this is more compact.\n                            Log.LogMessage(MessageImportance.High, testFailure);\n                        }\n                    }\n\n                    // Log summary of all results.\n                    Log.LogMessage(MessageImportance.High, string.Empty);\n                    Log.LogMessage(MessageImportance.High,\n                        \"Tests passed: {0}, Tests failed: {1}, Tests skipped: {2}\",\n                        testsPassed,\n                        testsFailed,\n                        testsSkipped);\n                    Log.LogMessage(MessageImportance.High,\n                        \"Time spent running tests: {0} seconds\", timeSpent);\n\n                    return !Log.HasLoggedErrors;\n                }\n                catch (Exception ex)\n                {\n                    Log.LogErrorFromException(ex);\n                    return false;\n                }\n            ]]>\n      </Code>\n    </Task>\n  </UsingTask>\n</Project>\n"
  },
  {
    "path": "tools/WebStack.testing.targets",
    "content": "<Project ToolsVersion=\"4.0\" DefaultTargets=\"Xunit\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <!--\n    This is a separate MSBuild file so that we can survive upgrades of the xunit NuGet package\n    and also still work with NuGet Package Restore.\n  -->\n  <Import Project=\"..\\packages\\xunit.runner.msbuild.2.4.2\\**\\xunit.runner.msbuild.props\"/>\n\n  <Target Name=\"TestAssembly\" Returns=\"@(_ExitCodes)\">\n    <xunit Assemblies=\"$(TestAssembly)\"\n        Condition=\" '$(UseVSTest)' != 'true' \"\n        IgnoreFailures=\"true\"\n        Xml=\"$(XmlPath)\">\n      <Output TaskParameter=\"ExitCode\" PropertyName=\"_ExitCode\" />\n    </xunit>\n    <Exec Command=\"dotnet vstest $(TestAssembly) --logger:&quot;xunit;LogFilePath=$(XmlPath)&quot;\"\n        Condition=\" '$(UseVSTest)' == 'true' \"\n        IgnoreExitCode=\"true\"\n        IgnoreStandardErrorWarningFormat=\"true\">\n      <Output TaskParameter=\"ExitCode\" PropertyName=\"_ExitCode\" />\n    </Exec>\n\n    <ItemGroup>\n      <_ExitCodes Include=\"$(TestAssembly)\" Code=\"$(_ExitCode)\" />\n    </ItemGroup>\n  </Target>\n</Project>\n"
  },
  {
    "path": "tools/src/Microsoft.Web.FxCop/DoNotCallProblematicMethodsOnTaskRule.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing Microsoft.FxCop.Sdk;\n\nnamespace Microsoft.Web.FxCop\n{\n    public class DoNotCallProblematicMethodsOnTaskRule : IntrospectionRule\n    {\n        private readonly Dictionary<string, string> _problematicMethods = GetProblematicMethods();\n\n        public DoNotCallProblematicMethodsOnTaskRule()\n            : base(\"DoNotCallProblematicMethodsOnTask\")\n        {\n        }\n\n        public override ProblemCollection Check(Member member)\n        {\n            var method = member as Method;\n            if (method != null)\n            {\n                VisitStatements(method.Body.Statements);\n            }\n\n            return Problems;\n        }\n\n        public override void VisitMemberBinding(MemberBinding memberBinding)\n        {\n            var method = memberBinding.BoundMember as Method;\n            if (method != null)\n            {\n                string message;\n                if (_problematicMethods.TryGetValue(method.Name.Name, out message) &&\n                    method.DeclaringType.IsTask())\n                {\n                    Problems.Add(new Problem(GetResolution(method.Name.Name, message), memberBinding.UniqueKey.ToString()));\n                }\n            }\n\n            base.VisitMemberBinding(memberBinding);\n        }\n\n        private static Dictionary<string, string> GetProblematicMethods()\n        {\n            return new Dictionary<string, string>\n            {\n                { \"get_Result\", \"Calls to this method are difficult to get correct or do not have good performance characteristics. Use the .Then(), .Catch(), or .Finally() extension method instead.\" },\n                { \"get_Factory\", \"If you need to create a Task, use the TaskHelpers class instead.\" },\n                { \"ContinueWith\", \"Calls to this method are difficult to get correct or do not have good performance characteristics. Use the .Then(), .Catch(), or .Finally() extension method instead.\" },\n                { \"Dispose\", \"Tasks should never be disposed of.\" },\n                { \"Run\", \"If you need to create a Task, use the TaskHelpers class instead.\" },\n                { \"RunSynchronously\", \"If you need to create a Task, use the TaskHelpers class instead.\" },\n                { \"Start\", \"If you need to create a Task, use the TaskHelpers class instead.\" },\n                { \"Wait\", \"This is a blocking call. Switch to an asynchronous call like .Then() instead.\" },\n                { \"WaitAll\", \"This is a blocking call. Switch to an asynchronous call like .Then() instead.\" },\n                { \"WaitAny\", \"This is a blocking call. Switch to an asynchronous call like .Then() instead.\" },\n                { \"Yield\", \"This call forces a thread transition which can hurt server performance. Do not use.\" },\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "tools/src/Microsoft.Web.FxCop/DoNotConstructTaskInstancesRule.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.FxCop.Sdk;\n\nnamespace Microsoft.Web.FxCop\n{\n    public class DoNotConstructTaskInstancesRule : IntrospectionRule\n    {\n        public DoNotConstructTaskInstancesRule()\n            : base(\"DoNotConstructTaskInstances\")\n        {\n        }\n\n        public override ProblemCollection Check(Member member)\n        {\n            var method = member as Method;\n            if (method != null)\n            {\n                VisitStatements(method.Body.Statements);\n            }\n\n            return Problems;\n        }\n\n        public override void VisitConstruct(Construct construct)\n        {\n            var memberBinding = construct.Constructor as MemberBinding;\n\n            if (memberBinding != null\n                && memberBinding.BoundMember.Name.Name == \".ctor\"\n                && memberBinding.BoundMember.DeclaringType.IsTask())\n            {\n                Problems.Add(new Problem(GetResolution(), construct.UniqueKey.ToString()));\n            }\n\n            base.VisitConstruct(construct);\n        }\n    }\n}\n"
  },
  {
    "path": "tools/src/Microsoft.Web.FxCop/DoNotUseFinalizersRule.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.FxCop.Sdk;\n\nnamespace Microsoft.Web.FxCop\n{\n    public class DoNotUseFinalizersRule : IntrospectionRule\n    {\n        public DoNotUseFinalizersRule()\n            : base(\"DoNotUseFinalizers\")\n        {\n        }\n\n        public override ProblemCollection Check(Member member)\n        {\n            if (member.NodeType == NodeType.Method && member.Name.Name == \"Finalize\")\n            {\n                Problems.Add(new Problem(GetResolution(member.DeclaringType.FullName), member));\n            }\n\n            return Problems;\n        }\n    }\n}\n"
  },
  {
    "path": "tools/src/Microsoft.Web.FxCop/DoNotUseProblematicTaskTypesRule.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Generic;\nusing Microsoft.FxCop.Sdk;\n\nnamespace Microsoft.Web.FxCop\n{\n    public class DoNotUseProblematicTaskTypesRule : IntrospectionRule\n    {\n        private readonly Dictionary<string, string> _problematicTypes = GetProblematicTypes();\n\n        public DoNotUseProblematicTaskTypesRule()\n            : base(\"DoNotUseProblematicTaskTypes\")\n        {\n        }\n\n        public override ProblemCollection Check(Member member)\n        {\n            var method = member as Method;\n            if (method != null)\n            {\n                VisitStatements(method.Body.Statements);\n            }\n\n            return Problems;\n        }\n\n        public override void VisitMemberBinding(MemberBinding memberBinding)\n        {\n            var method = memberBinding.BoundMember as Method;\n            if (method != null)\n            {\n                string message;\n                if (_problematicTypes.TryGetValue(method.DeclaringType.FullName, out message))\n                {\n                    Problems.Add(new Problem(GetResolution(method.DeclaringType.FullName, message), memberBinding.UniqueKey.ToString()));\n                }\n            }\n\n            base.VisitMemberBinding(memberBinding);\n        }\n\n        private static Dictionary<string, string> GetProblematicTypes()\n        {\n            return new Dictionary<string, string>\n            {\n                { \"System.Threading.Tasks.Parallel\", \"The methods on this type are blocking operations.\" },\n                { \"System.Threading.Tasks.TaskExtensions\", \"The .Unwrap() method does not have good performance characteristics. Use the .FastUnwrap() extension method instead.\" },\n                { \"System.Threading.Tasks.TaskFactory\", \"If you need to create a Task, use the TaskHelpers class instead.\" },\n                { \"System.Threading.Tasks.TaskScheduler\", \"If you need to create a Task, use the TaskHelpers class instead.\" }\n            };\n        }\n    }\n}\n"
  },
  {
    "path": "tools/src/Microsoft.Web.FxCop/IntrospectionRule.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing Microsoft.FxCop.Sdk;\n\nnamespace Microsoft.Web.FxCop\n{\n    public abstract class IntrospectionRule : BaseIntrospectionRule\n    {\n        protected IntrospectionRule(string name)\n            : base(name, \"Microsoft.Web.FxCop.Rules\", typeof(IntrospectionRule).Assembly)\n        {\n        }\n    }\n}\n"
  },
  {
    "path": "tools/src/Microsoft.Web.FxCop/Microsoft.Web.FxCop.csproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <PropertyGroup>\n    <Configuration Condition=\" '$(Configuration)' == '' \">Debug</Configuration>\n    <Platform Condition=\" '$(Platform)' == '' \">x86</Platform>\n    <ProductVersion>8.0.30703</ProductVersion>\n    <SchemaVersion>2.0</SchemaVersion>\n    <ProjectGuid>{F439D4E6-3FAC-4C30-9585-6D258133A2BF}</ProjectGuid>\n    <OutputType>Library</OutputType>\n    <AppDesignerFolder>Properties</AppDesignerFolder>\n    <RootNamespace>Microsoft.Web.FxCop</RootNamespace>\n    <AssemblyName>Microsoft.Web.FxCop</AssemblyName>\n    <!-- May need to be updated as FxCopSdk.dll is migrated to newer TFMs. -->\n    <TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>\n    <OutputPath Condition=\" '$(OutputPath)' == '' \">bin\\$(Configuration)</OutputPath>\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)' == 'Debug' \">\n    <PlatformTarget>x86</PlatformTarget>\n    <DebugSymbols>true</DebugSymbols>\n    <DebugType>full</DebugType>\n    <Optimize>false</Optimize>\n    <DefineConstants>DEBUG;TRACE</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>4</WarningLevel>\n  </PropertyGroup>\n  <PropertyGroup Condition=\" '$(Configuration)' == 'Release' \">\n    <PlatformTarget>x86</PlatformTarget>\n    <DebugType>pdbonly</DebugType>\n    <Optimize>true</Optimize>\n    <DefineConstants>TRACE</DefineConstants>\n    <ErrorReport>prompt</ErrorReport>\n    <WarningLevel>4</WarningLevel>\n  </PropertyGroup>\n  <PropertyGroup>\n    <FxCopLocation>$(VsInstallRoot)\\Team Tools\\Static Analysis Tools\\FxCop\\</FxCopLocation>\n  </PropertyGroup>\n  <ItemGroup>\n    <Reference Include=\"FxCopSdk\">\n      <HintPath>$(FxCopLocation)FxCopSdk.dll</HintPath>\n      <Private>False</Private>\n    </Reference>\n    <Reference Include=\"Microsoft.Cci\">\n      <HintPath>$(FxCopLocation)Microsoft.Cci.dll</HintPath>\n      <Private>False</Private>\n    </Reference>\n    <Reference Include=\"System\" />\n    <Reference Include=\"System.Core\" />\n    <Reference Include=\"System.Xml.Linq\" />\n    <Reference Include=\"System.Data.DataSetExtensions\" />\n    <Reference Include=\"Microsoft.CSharp\" />\n    <Reference Include=\"System.Data\" />\n    <Reference Include=\"System.Xml\" />\n  </ItemGroup>\n  <ItemGroup>\n    <Compile Include=\"DoNotUseFinalizersRule.cs\" />\n    <Compile Include=\"DoNotCallProblematicMethodsOnTaskRule.cs\" />\n    <Compile Include=\"DoNotConstructTaskInstancesRule.cs\" />\n    <Compile Include=\"IntrospectionRule.cs\" />\n    <Compile Include=\"UnusedResourceUsageRule.cs\" />\n    <Compile Include=\"Properties\\AssemblyInfo.cs\" />\n    <Compile Include=\"DoNotUseProblematicTaskTypesRule.cs\" />\n    <Compile Include=\"TypeNodeExtensions.cs\" />\n  </ItemGroup>\n  <ItemGroup>\n    <EmbeddedResource Include=\"Rules.xml\">\n      <SubType>Designer</SubType>\n    </EmbeddedResource>\n  </ItemGroup>\n  <Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />\n  <PropertyGroup>\n    <!-- If the FxCop SDK does not exist at all have this build no-op. -->\n    <BuildDependsOn Condition=\" !Exists('$(FxCopLocation)') \">\n    </BuildDependsOn>\n  </PropertyGroup>\n</Project>"
  },
  {
    "path": "tools/src/Microsoft.Web.FxCop/Properties/AssemblyInfo.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Reflection;\n\n[assembly: AssemblyProduct(\"Microsoft.Web.FxCop\")]\n[assembly: AssemblyDescription(\"FxCop rules used by the Microsoft ASP.NET WebStack projects\")]\n[assembly: AssemblyCompany(\".NET Foundation\")]\n[assembly: AssemblyCopyright(\"Copyright © .NET Foundation. All rights reserved.\")]\n"
  },
  {
    "path": "tools/src/Microsoft.Web.FxCop/Rules.xml",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Rules FriendlyName=\"FxCop rules used by the ASP.NET Webstack team\">\n\n    <!-- MW10xx: Resource rules -->\n    <Rule TypeName=\"UnusedResourceUsageRule\" Category=\"Microsoft.Web.FxCop\" CheckId=\"MW1000\">\n        <Name>UnusedResourceUsageRule</Name>\n        <Description>This rule fires when a resource is unused in the assembly.</Description>\n        <Url></Url>\n        <Resolution>Remove the unused resource '{0}' from '{1}'.</Resolution>\n        <Email></Email>\n        <MessageLevel Certainty=\"95\">Error</MessageLevel>\n        <FixCategories>Breaking</FixCategories>\n        <Owner></Owner>\n    </Rule>\n\n    <!-- MW11xx: Finalizer rules -->\n    <Rule TypeName=\"DoNotUseFinalizers\" Category=\"Microsoft.Web.FxCop\" CheckId=\"MW1100\">\n        <Name>Do not use finalizers</Name>\n        <Description>For performance reasons, managed types should not implement finalizers.</Description>\n        <Url></Url>\n        <Resolution>Type '{0}' has a finalizer. Use SafeHandle to contain unmanaged data instead.</Resolution>\n        <Email></Email>\n        <MessageLevel Certainty=\"100\">Error</MessageLevel>\n        <FixCategories>Breaking</FixCategories>\n        <Owner></Owner>\n    </Rule>\n\n    <!-- MW12xx: Task rules -->\n    <Rule TypeName=\"DoNotConstructTaskInstances\" Category=\"Microsoft.Web.FxCop\" CheckId=\"MW1200\">\n        <Name>Do not construct instances of the Task-related types</Name>\n        <Description>For performance reasons, all tasks should be created using the TaskHelpers library.</Description>\n        <Url></Url>\n        <Resolution>Do not construct instances of Task-related types. If you need to create a Task, use the TaskHelpers class instead.</Resolution>\n        <Email></Email>\n        <MessageLevel Certainty=\"100\">Error</MessageLevel>\n        <FixCategories>NonBreaking</FixCategories>\n        <Owner></Owner>\n    </Rule>\n    <Rule TypeName=\"DoNotCallProblematicMethodsOnTask\" Category=\"Microsoft.Web.FxCop\" CheckId=\"MW1201\">\n        <Name>Do not call problematic methods on Task</Name>\n        <Description>For performance reasons, use the TaskHelpers and TaskHelpersExtensions library rather than methods on Task.</Description>\n        <Url></Url>\n        <Resolution>Do not call the method 'Task.{0}'. {1}</Resolution>\n        <Email></Email>\n        <MessageLevel Certainty=\"100\">Error</MessageLevel>\n        <FixCategories>NonBreaking</FixCategories>\n        <Owner></Owner>\n    </Rule>\n    <Rule TypeName=\"DoNotUseProblematicTaskTypes\" Category=\"Microsoft.Web.FxCop\" CheckId=\"MW1202\">\n        <Name>Do not call use problematic Task types</Name>\n        <Description>For performance reasons, use the TaskHelpers and TaskHelpersExtensions library rather than Task-related types.</Description>\n        <Url></Url>\n        <Resolution>Do not use the type '{0}'. {1}</Resolution>\n        <Email></Email>\n        <MessageLevel Certainty=\"100\">Error</MessageLevel>\n        <FixCategories>NonBreaking</FixCategories>\n        <Owner></Owner>\n    </Rule>\n</Rules>\n"
  },
  {
    "path": "tools/src/Microsoft.Web.FxCop/TypeNodeExtensions.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Diagnostics.Contracts;\nusing System.Linq;\nusing Microsoft.FxCop.Sdk;\n\nnamespace Microsoft.Web.FxCop\n{\n    public static class TypeNodeExtensions\n    {\n        private const string TaskPortableAssembly = \"System.Threading.Tasks\";\n        private const string TaskNamespace = \"System.Threading.Tasks\";\n        private const string TaskType = \"Task\";\n        private const string TaskGenericType = \"Task`1\";\n        private static readonly object _taskLock = new object();\n\n        private static TypeNode _task;\n        private static TypeNode _taskGeneric;\n\n        public static bool IsTask(this TypeNode type)\n        {\n            if (type.IsAbstract)\n            {\n                // Short-circuit because Task is not an abstract type.\n                //\n                // This also avoids NREs when the passed type is an interface. May be passed an interface when caller\n                // encounters a method that is explicitly implemented e.g. Dispose() is not visible directly on\n                // JsonReader though JsonReader implements System.IDisposable. Interfaces such as IDisposable are\n                // defined very low in the module hierarchy, leading to NREs in GetTaskAssembly(). Therefore, use only\n                // concrete types to initialize the fields.\n                return false;\n            }\n\n            EnsureTaskTypesInitialized(type);\n            return IsTaskCore(type);\n        }\n\n        private static bool IsTaskCore(TypeNode type)\n        {\n            Contract.Assert(_task != null);\n            Contract.Assert(_taskGeneric != null);\n\n            if (type.Name.UniqueIdKey == _task.Name.UniqueIdKey)\n            {\n                return true;\n            }\n\n            if (!type.IsGeneric)\n            {\n                return false;\n            }\n\n            TypeNode targetType = _taskGeneric.GetGenericTemplateInstance(_taskGeneric.DeclaringModule, type.ConsolidatedTemplateArguments);\n            return targetType.Name.UniqueIdKey == type.Name.UniqueIdKey;\n        }\n\n        private static void EnsureTaskTypesInitialized(TypeNode type)\n        {\n            lock (_taskLock)\n            {\n                if (_task == null)\n                {\n                    Contract.Assert(_task == null);\n                    Contract.Assert(_taskGeneric == null);\n\n                    AssemblyNode taskAssembly = GetTaskAssembly(type);\n                    Contract.Assert(taskAssembly != null);\n\n                    _task = GetTypeNode(taskAssembly, TaskNamespace, TaskType);\n                    _taskGeneric = GetTypeNode(taskAssembly, TaskNamespace, TaskGenericType);\n\n                    Contract.Assert(_task != null);\n                    Contract.Assert(_taskGeneric != null);\n                }\n            }\n        }\n\n        private static TypeNode GetTypeNode(AssemblyNode assembly, string ns, string name)\n        {\n            Contract.Assert(assembly != null);\n\n            return assembly.GetType(Identifier.For(ns), Identifier.For(name));\n        }\n\n        private static AssemblyNode GetTaskAssembly(TypeNode type)\n        {\n            AssemblyNode taskAssembly = null;\n\n            // Check if the type's located in mscorlib\n            TypeNode taskTypeNode = GetTypeNode(FrameworkAssemblies.Mscorlib, TaskNamespace, TaskGenericType);\n            if (taskTypeNode != null)\n            {\n                taskAssembly = FrameworkAssemblies.Mscorlib;\n            }\n            else if (type.DeclaringModule.Name.Equals(TaskPortableAssembly))\n            {\n                // If the type is a type in the portable assembly, no need to loop through the assembly references\n                taskAssembly = type.DeclaringModule.ContainingAssembly;\n            }\n            else\n            {\n                AssemblyReference assemblyReference = type.DeclaringModule\n                                                          .AssemblyReferences\n                                                          .FirstOrDefault(reference => reference.Name.Equals(TaskPortableAssembly, StringComparison.Ordinal));\n                Contract.Assert(assemblyReference != null);\n                taskAssembly = assemblyReference.Assembly;\n            }\n\n            Contract.Assert(taskAssembly != null);\n            return taskAssembly;\n        }\n    }\n}\n"
  },
  {
    "path": "tools/src/Microsoft.Web.FxCop/UnusedResourceUsageRule.cs",
    "content": "﻿// Copyright (c) .NET Foundation. All rights reserved.\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.FxCop.Sdk;\n\nnamespace Microsoft.Web.FxCop\n{\n    public class UnusedResourceUsageRule : IntrospectionRule\n    {\n        private static readonly object _lock = new object();\n        private static readonly IDictionary<AssemblyNode, ISet<PropertyNode>> _availableResources = new ConcurrentDictionary<AssemblyNode, ISet<PropertyNode>>();\n        private static readonly IDictionary<AssemblyNode, ISet<PropertyNode>> _usedResources = new ConcurrentDictionary<AssemblyNode, ISet<PropertyNode>>();\n\n        public UnusedResourceUsageRule()\n            : base(\"UnusedResourceUsageRule\")\n        {\n        }\n\n        public override TargetVisibilities TargetVisibility\n        {\n            get { return TargetVisibilities.All; }\n        }\n\n        public override ProblemCollection Check(ModuleNode node)\n        {\n            var assemblyNode = node as AssemblyNode;\n            if (assemblyNode != null)\n            {\n                var assemblyAvailableResources = new HashSet<PropertyNode>();\n                var assemblyUsedResources = new HashSet<PropertyNode>();\n\n                _availableResources[assemblyNode] = assemblyAvailableResources;\n                _usedResources[assemblyNode] = assemblyUsedResources;\n\n                VisitAssembly(assemblyNode);\n\n                IEnumerable<PropertyNode> unusedResources = from res in assemblyAvailableResources.Except(assemblyUsedResources)\n                                                            where !IsCommonResource(res)\n                                                            select res;\n\n                foreach (PropertyNode item in unusedResources)\n                {\n                    Problems.Add(new Problem(this.GetResolution(item.Name.Name, item.DeclaringType.FullName), item.UniqueKey.ToString()));\n                }\n            }\n\n            return Problems;\n        }\n\n        public override void VisitProperty(PropertyNode property)\n        {\n            if (IsResourceType(property.DeclaringType) && IsResource(property))\n            {\n                AddItemWithLock(_availableResources[(AssemblyNode)property.DeclaringType.DeclaringModule], property);\n            }\n\n            base.VisitProperty(property);\n        }\n\n        public override void VisitMethodCall(MethodCall call)\n        {\n            MemberBinding mb = call.Callee as MemberBinding;\n            if (mb != null)\n            {\n                Method methodBeingCalled = mb.BoundMember as Method;\n                if (methodBeingCalled != null\n                        && IsResourceType(methodBeingCalled.DeclaringType)\n                        && IsResource(methodBeingCalled.DeclaringMember as PropertyNode))\n                {\n\n                    var property = methodBeingCalled.DeclaringMember as PropertyNode;\n\n                    ISet<PropertyNode> properties = null;\n                    // Look up the assembly from the dictionary. If the assembly could not be looked up, the resource must have been declared outside the current assembly\n                    if (_usedResources.TryGetValue((AssemblyNode)property.DeclaringType.DeclaringModule, out properties))\n                    {\n                        AddItemWithLock(properties, property);\n                    }\n                }\n            }\n\n            base.VisitMethodCall(call);\n        }\n\n        private static void AddItemWithLock<T>(ISet<T> item, T value)\n        {\n            lock (_lock)\n            {\n                item.Add(value);\n            }\n        }\n\n        private static bool IsResource(PropertyNode property)\n        {\n            return property != null && property.Type.FullName.Equals(typeof(System.String).FullName);\n        }\n\n        private static bool IsResourceType(TypeNode typeNode)\n        {\n            var classNode = typeNode as ClassNode;\n            return (classNode != null\n                && classNode.Attributes.Any(c => c.Type.FullName.Equals(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute).FullName))\n                && classNode.Name.Name.Contains(\"Resource\"));\n        }\n\n        /// <summary>\n        /// Hack to determine if the file is \"Common*Resources.resx\" that is shared amongst multiple WebStack projects. \n        /// Strings in this resx are ignored since they may have dependencies outside the current assembly.\n        /// </summary>\n        private static bool IsCommonResource(PropertyNode property)\n        {\n            string name = property.DeclaringType.Name.Name;\n            return name.StartsWith(\"Common\") && name.EndsWith(\"Resources\");\n        }\n    }\n}\n\n"
  },
  {
    "path": "tools/vslicense/dotnet-library-license.htm",
    "content": "<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">\n<meta name=\"Generator\" content=\"Microsoft Word 15 (filtered)\">\n<style>\n<!--\n@font-face\n\t{font-family:Wingdings}\n@font-face\n\t{font-family:\"MS Mincho\"}\n@font-face\n\t{font-family:SimSun}\n@font-face\n\t{font-family:\"Cambria Math\"}\n@font-face\n\t{font-family:Calibri}\n@font-face\n\t{font-family:Tahoma}\n@font-face\n\t{font-family:\"Trebuchet MS\"}\n@font-face\n\t{}\n@font-face\n\t{}\np.MsoNormal, li.MsoNormal, div.MsoNormal\n\t{margin-top:6.0pt;\n\tmargin-right:0in;\n\tmargin-bottom:6.0pt;\n\tmargin-left:0in;\n\tfont-size:9.5pt;\n\tfont-family:\"Tahoma\",sans-serif}\nh1\n\t{margin-top:6.0pt;\n\tmargin-right:0in;\n\tmargin-bottom:6.0pt;\n\tmargin-left:17.85pt;\n\ttext-indent:-17.85pt;\n\tfont-size:9.5pt;\n\tfont-family:\"Tahoma\",sans-serif}\nh2\n\t{margin-top:6.0pt;\n\tmargin-right:0in;\n\tmargin-bottom:6.0pt;\n\tmargin-left:.5in;\n\ttext-indent:-18.15pt;\n\tfont-size:9.5pt;\n\tfont-family:\"Tahoma\",sans-serif}\nh3\n\t{margin-top:6.0pt;\n\tmargin-right:0in;\n\tmargin-bottom:6.0pt;\n\tmargin-left:53.85pt;\n\ttext-indent:-17.85pt;\n\tfont-size:9.5pt;\n\tfont-family:\"Tahoma\",sans-serif;\n\tfont-weight:normal}\nh4\n\t{margin-top:6.0pt;\n\tmargin-right:0in;\n\tmargin-bottom:6.0pt;\n\tmargin-left:71.75pt;\n\ttext-indent:-17.9pt;\n\tfont-size:9.5pt;\n\tfont-family:\"Tahoma\",sans-serif;\n\tfont-weight:normal}\nh5\n\t{margin-top:6.0pt;\n\tmargin-right:0in;\n\tmargin-bottom:6.0pt;\n\tmargin-left:89.6pt;\n\ttext-indent:-17.85pt;\n\tfont-size:9.5pt;\n\tfont-family:\"Tahoma\",sans-serif;\n\tfont-weight:normal}\nh6\n\t{margin-top:6.0pt;\n\tmargin-right:0in;\n\tmargin-bottom:6.0pt;\n\tmargin-left:107.45pt;\n\ttext-indent:-17.85pt;\n\tfont-size:9.5pt;\n\tfont-family:\"Tahoma\",sans-serif;\n\tfont-weight:normal}\np.MsoHeading7, li.MsoHeading7, div.MsoHeading7\n\t{margin-top:6.0pt;\n\tmargin-right:0in;\n\tmargin-bottom:6.0pt;\n\tmargin-left:125.3pt;\n\ttext-indent:-17.85pt;\n\tfont-size:9.5pt;\n\tfont-family:\"Tahoma\",sans-serif}\np.MsoHeading8, li.MsoHeading8, div.MsoHeading8\n\t{margin-top:6.0pt;\n\tmargin-right:0in;\n\tmargin-bottom:6.0pt;\n\tmargin-left:143.15pt;\n\ttext-indent:-17.85pt;\n\tfont-size:9.5pt;\n\tfont-family:\"Tahoma\",sans-serif}\np.MsoHeading9, li.MsoHeading9, div.MsoHeading9\n\t{margin-top:6.0pt;\n\tmargin-right:0in;\n\tmargin-bottom:6.0pt;\n\tmargin-left:161.05pt;\n\ttext-indent:-17.9pt;\n\tfont-size:9.5pt;\n\tfont-family:\"Tahoma\",sans-serif}\np.MsoCommentText, li.MsoCommentText, div.MsoCommentText\n\t{margin-top:6.0pt;\n\tmargin-right:0in;\n\tmargin-bottom:6.0pt;\n\tmargin-left:0in;\n\tfont-size:10.0pt;\n\tfont-family:\"Tahoma\",sans-serif}\np.MsoHeader, li.MsoHeader, div.MsoHeader\n\t{margin:0in;\n\tmargin-bottom:.0001pt;\n\tfont-size:9.5pt;\n\tfont-family:\"Tahoma\",sans-serif}\np.MsoFooter, li.MsoFooter, div.MsoFooter\n\t{margin:0in;\n\tmargin-bottom:.0001pt;\n\tfont-size:9.5pt;\n\tfont-family:\"Tahoma\",sans-serif}\na:link, span.MsoHyperlink\n\t{font-family:\"Times New Roman\",serif;\n\tcolor:blue;\n\ttext-decoration:underline}\na:visited, span.MsoHyperlinkFollowed\n\t{color:purple;\n\ttext-decoration:underline}\np.MsoPlainText, li.MsoPlainText, div.MsoPlainText\n\t{margin:0in;\n\tmargin-bottom:.0001pt;\n\tfont-size:11.0pt;\n\tfont-family:\"Calibri\",sans-serif}\np.MsoCommentSubject, li.MsoCommentSubject, div.MsoCommentSubject\n\t{margin-top:6.0pt;\n\tmargin-right:0in;\n\tmargin-bottom:6.0pt;\n\tmargin-left:0in;\n\tfont-size:10.0pt;\n\tfont-family:\"Tahoma\",sans-serif;\n\tfont-weight:bold}\np.MsoAcetate, li.MsoAcetate, div.MsoAcetate\n\t{margin:0in;\n\tmargin-bottom:.0001pt;\n\tfont-size:8.0pt;\n\tfont-family:\"Tahoma\",sans-serif}\nspan.Heading1Char\n\t{font-family:\"Tahoma\",sans-serif;\n\tfont-weight:bold}\nspan.Heading2Char\n\t{font-family:\"Tahoma\",sans-serif;\n\tfont-weight:bold}\nspan.Heading3Char\n\t{font-family:\"Tahoma\",sans-serif}\nspan.Heading4Char\n\t{font-family:\"Tahoma\",sans-serif}\nspan.Heading5Char\n\t{font-family:\"Tahoma\",sans-serif}\nspan.Heading6Char\n\t{font-family:\"Tahoma\",sans-serif}\nspan.Heading7Char\n\t{font-family:\"Tahoma\",sans-serif}\nspan.Heading8Char\n\t{font-family:\"Tahoma\",sans-serif}\nspan.Heading9Char\n\t{font-family:\"Tahoma\",sans-serif}\np.Body1, li.Body1, div.Body1\n\t{margin-top:6.0pt;\n\tmargin-right:0in;\n\tmargin-bottom:6.0pt;\n\tmargin-left:17.85pt;\n\tfont-size:9.5pt;\n\tfont-family:\"Tahoma\",sans-serif}\np.Bullet2, li.Bullet2, div.Bullet2\n\t{margin-top:6.0pt;\n\tmargin-right:0in;\n\tmargin-bottom:6.0pt;\n\tmargin-left:.5in;\n\ttext-indent:-18.15pt;\n\tfont-size:9.5pt;\n\tfont-family:\"Tahoma\",sans-serif}\np.Bullet3, li.Bullet3, div.Bullet3\n\t{margin-top:6.0pt;\n\tmargin-right:0in;\n\tmargin-bottom:6.0pt;\n\tmargin-left:53.85pt;\n\ttext-indent:-17.85pt;\n\tfont-size:9.5pt;\n\tfont-family:\"Tahoma\",sans-serif}\np.HeadingEULA, li.HeadingEULA, div.HeadingEULA\n\t{margin-top:6.0pt;\n\tmargin-right:0in;\n\tmargin-bottom:6.0pt;\n\tmargin-left:0in;\n\tfont-size:14.0pt;\n\tfont-family:\"Tahoma\",sans-serif;\n\tfont-weight:bold}\np.HeadingSoftwareTitle, li.HeadingSoftwareTitle, div.HeadingSoftwareTitle\n\t{margin-top:6.0pt;\n\tmargin-right:0in;\n\tmargin-bottom:6.0pt;\n\tmargin-left:0in;\n\tborder:none;\n\tpadding:0in;\n\tfont-size:14.0pt;\n\tfont-family:\"Tahoma\",sans-serif;\n\tfont-weight:bold}\np.Preamble, li.Preamble, div.Preamble\n\t{margin-top:6.0pt;\n\tmargin-right:0in;\n\tmargin-bottom:6.0pt;\n\tmargin-left:0in;\n\tfont-size:9.5pt;\n\tfont-family:\"Tahoma\",sans-serif;\n\tfont-weight:bold}\np.PreambleBorderAbove, li.PreambleBorderAbove, div.PreambleBorderAbove\n\t{margin-top:6.0pt;\n\tmargin-right:0in;\n\tmargin-bottom:6.0pt;\n\tmargin-left:0in;\n\tborder:none;\n\tpadding:0in;\n\tfont-size:9.5pt;\n\tfont-family:\"Tahoma\",sans-serif;\n\tfont-weight:bold}\np.Body0Bold, li.Body0Bold, div.Body0Bold\n\t{margin:0in;\n\tmargin-bottom:.0001pt;\n\tfont-size:9.5pt;\n\tfont-family:\"Tahoma\",sans-serif;\n\tfont-weight:bold}\np.Body0, li.Body0, div.Body0\n\t{margin:0in;\n\tmargin-bottom:.0001pt;\n\tfont-size:9.5pt;\n\tfont-family:\"Tahoma\",sans-serif}\nspan.BalloonTextChar\n\t{font-family:\"Tahoma\",sans-serif}\np.Bullet1, li.Bullet1, div.Bullet1\n\t{margin-top:6.0pt;\n\tmargin-right:0in;\n\tmargin-bottom:6.0pt;\n\tmargin-left:17.85pt;\n\ttext-indent:-17.85pt;\n\tfont-size:9.5pt;\n\tfont-family:\"Tahoma\",sans-serif}\np.Bullet4, li.Bullet4, div.Bullet4\n\t{margin-top:6.0pt;\n\tmargin-right:0in;\n\tmargin-bottom:6.0pt;\n\tmargin-left:71.75pt;\n\ttext-indent:-17.9pt;\n\tfont-size:9.5pt;\n\tfont-family:\"Tahoma\",sans-serif}\np.Bullet5, li.Bullet5, div.Bullet5\n\t{margin-top:6.0pt;\n\tmargin-right:0in;\n\tmargin-bottom:6.0pt;\n\tmargin-left:89.6pt;\n\ttext-indent:-17.85pt;\n\tfont-size:9.5pt;\n\tfont-family:\"Tahoma\",sans-serif}\np.Heading3Bold, li.Heading3Bold, div.Heading3Bold\n\t{margin-top:6.0pt;\n\tmargin-right:0in;\n\tmargin-bottom:6.0pt;\n\tmargin-left:53.85pt;\n\ttext-indent:-17.85pt;\n\tfont-size:9.5pt;\n\tfont-family:\"Tahoma\",sans-serif;\n\tfont-weight:bold}\np.Bullet4Underline, li.Bullet4Underline, div.Bullet4Underline\n\t{margin-top:6.0pt;\n\tmargin-right:0in;\n\tmargin-bottom:6.0pt;\n\tmargin-left:71.75pt;\n\ttext-indent:-17.9pt;\n\tfont-size:9.5pt;\n\tfont-family:\"Tahoma\",sans-serif;\n\ttext-decoration:underline}\nspan.Body2Char\n\t{font-family:\"Tahoma\",sans-serif}\nspan.Body3Char\n\t{font-family:\"Tahoma\",sans-serif}\nspan.CommentTextChar\n\t{font-family:\"Tahoma\",sans-serif}\nspan.CommentSubjectChar\n\t{font-family:\"Tahoma\",sans-serif;\n\tfont-weight:bold}\nspan.Bullet3Char1\n\t{font-family:\"Tahoma\",sans-serif}\np.Bullet4Underlined, li.Bullet4Underlined, div.Bullet4Underlined\n\t{margin-top:6.0pt;\n\tmargin-right:0in;\n\tmargin-bottom:6.0pt;\n\tmargin-left:17.85pt;\n\ttext-indent:-17.85pt;\n\tfont-size:9.5pt;\n\tfont-family:\"Tahoma\",sans-serif;\n\ttext-decoration:underline}\nspan.Heading3BoldChar\n\t{font-family:\"Tahoma\",sans-serif;\n\tfont-weight:bold}\nspan.PlainTextChar\n\t{font-family:\"Calibri\",sans-serif}\nspan.HeaderChar\n\t{font-family:\"Tahoma\",sans-serif}\nspan.FooterChar\n\t{font-family:\"Tahoma\",sans-serif}\np.bullet30, li.bullet30, div.bullet30\n\t{margin-right:0in;\n\tmargin-left:0in;\n\tfont-size:12.0pt;\n\tfont-family:\"Times New Roman\",serif}\np.bullet40, li.bullet40, div.bullet40\n\t{margin-right:0in;\n\tmargin-left:0in;\n\tfont-size:12.0pt;\n\tfont-family:\"Times New Roman\",serif}\n.MsoChpDefault\n\t{font-family:\"Calibri\",sans-serif}\n.MsoPapDefault\n\t{margin-left:.25in;\n\ttext-indent:-.25in}\n@page WordSection1\n\t{margin:1.0in 1.0in 1.0in 1.0in}\ndiv.WordSection1\n\t{}\nol\n\t{margin-bottom:0in}\nul\n\t{margin-bottom:0in}\n-->\n</style>\n</head>\n<body lang=\"EN-US\" link=\"blue\" vlink=\"purple\">\n<div class=\"WordSection1\">\n<p class=\"HeadingEULA\"><span style=\"font-size:10.0pt\">MICROSOFT SOFTWARE LICENSE TERMS</span></p>\n<div style=\"border:none; border-bottom:solid windowtext 1.0pt; padding:0in 0in 1.0pt 0in\">\n<p class=\"HeadingSoftwareTitle\"><span style=\"font-size:10.0pt\">MICROSOFT .NET LIBRARY</span></p>\n</div>\n<p class=\"Preamble\"><span style=\"font-size:10.0pt; font-weight:normal\">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\n to any Microsoft services or updates for the software, except to the extent those have different terms.</span></p>\n<div style=\"border:none; border-top:solid windowtext 1.0pt; padding:1.0pt 0in 0in 0in\">\n<p class=\"PreambleBorderAbove\"><span style=\"font-size:10.0pt; text-transform:uppercase\">If you comply with these license terms, you have the rights below.</span></p>\n</div>\n<h1 style=\"margin-top:6.0pt; margin-right:0in; margin-bottom:0in; margin-left:.25in; margin-bottom:.0001pt; text-indent:-.25in\">\n<span style=\"font-size:10.0pt\">1.<span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp; </span>\n</span><span style=\"font-size:10.0pt\">INSTALLATION AND USE RIGHTS. </span></h1>\n<p class=\"Bullet3\" style=\"margin-top:0in; margin-right:0in; margin-bottom:6.0pt; margin-left:.25in; text-indent:0in\">\n<span style=\"font-size:10.0pt\">You may install and use any number of copies of the software\n</span><span style=\"font-size:10.0pt; color:black\">to develop and test your applications.&nbsp;\n</span></p>\n<h1><span style=\"font-size:10.0pt\">2.<span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp;\n</span></span><span style=\"font-size:10.0pt\">THIRD PARTY COMPONENTS. </span><span style=\"font-weight:normal\">The software may include third party components with separate legal notices or governed by other agreements, as may be described in the ThirdPartyNotices\n file(s) </span><span style=\"font-size:10.0pt; font-weight:normal\">accompanying the software.</span></h1>\n<h1><span style=\"font-size:10.0pt\">3.<span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp;\n</span></span><span style=\"font-size:10.0pt; color:black\">ADDITIONAL LICENSING REQUIREMENTS AND/OR USE RIGHTS.</span></h1>\n<h2><span style=\"font-size:10.0pt; color:black\">a.<span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp;&nbsp;\n</span></span><span style=\"font-size:10.0pt; color:black\">DISTRIBUTABLE CODE.&nbsp; </span>\n<span style=\"font-size:10.0pt; color:black; font-weight:normal\">T</span><span style=\"font-size:10.0pt; color:black; font-weight:normal\">he software is comprised of Distributable Code. Distributable Code is code that you are permitted to distribute in applications\n you develop if you comply with the terms below.</span></h2>\n<h3 style=\"margin-top:0in; margin-right:0in; margin-bottom:0in; margin-left:53.85pt; margin-bottom:.0001pt\">\n<b><span style=\"font-size:10.0pt; color:black\">i.<span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n</span></span></b><b><span style=\"font-size:10.0pt; color:black\">Right to Use and Distribute.\n</span></b></h3>\n<p class=\"bullet30\" style=\"margin-top:6.0pt; margin-right:0in; margin-bottom:6.0pt; margin-left:1.0in; text-indent:-.25in\">\n<span style=\"font-size:10.0pt; font-family:Symbol; color:black\"><span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n</span></span><span style=\"font-size:10.0pt; font-family:&quot;Tahoma&quot;,sans-serif; color:black\">You may copy and distribute the object code form of the software.</span></p>\n<p class=\"bullet30\" style=\"margin-top:6.0pt; margin-right:0in; margin-bottom:6.0pt; margin-left:1.0in; text-indent:-.25in\">\n<span style=\"font-size:10.0pt; font-family:Symbol; color:black\"><span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n</span></span><span style=\"font-size:10.0pt; font-family:&quot;Tahoma&quot;,sans-serif; color:black\">Third Party Distribution. You may permit distributors of your applications to copy and distribute the Distributable Code as part of those applications.</span></p>\n<h3 style=\"margin-top:0in; margin-right:0in; margin-bottom:0in; margin-left:53.85pt; margin-bottom:.0001pt\">\n<b><span style=\"font-size:10.0pt; color:black\">ii.<span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp;&nbsp;\n</span></span></b><b><span style=\"font-size:10.0pt; color:black\">Distribution Requirements. For any Distributable Code you distribute, you must</span></b></h3>\n<p class=\"bullet30\" style=\"margin-top:6.0pt; margin-right:0in; margin-bottom:6.0pt; margin-left:1.0in; text-indent:-.25in\">\n<span style=\"font-size:10.0pt; font-family:Symbol; color:black\"><span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n</span></span><span style=\"font-size:10.0pt; font-family:&quot;Tahoma&quot;,sans-serif; color:black\">use the Distributable Code in your applications and not as a standalone distribution;</span></p>\n<p class=\"bullet30\" style=\"margin-top:6.0pt; margin-right:0in; margin-bottom:6.0pt; margin-left:1.0in; text-indent:-.25in\">\n<span style=\"font-size:10.0pt; font-family:Symbol; color:black\"><span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n</span></span><span style=\"font-size:10.0pt; font-family:&quot;Tahoma&quot;,sans-serif; color:black\">require distributors and external end users to agree to terms that protect it at least as much as this agreement; and</span></p>\n<p class=\"bullet30\" style=\"margin-top:6.0pt; margin-right:0in; margin-bottom:6.0pt; margin-left:1.0in; text-indent:-.25in\">\n<span style=\"font-size:10.0pt; font-family:Symbol; color:black\"><span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n</span></span><span style=\"font-size:10.0pt; font-family:&quot;Tahoma&quot;,sans-serif; color:black\">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\n that any claim is based solely on the unmodified Distributable Code.</span></p>\n<h3 style=\"margin-top:0in; margin-right:0in; margin-bottom:0in; margin-left:53.85pt; margin-bottom:.0001pt\">\n<b><span style=\"font-size:10.0pt; color:black\">iii.<span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;\n</span></span></b><b><span style=\"font-size:10.0pt; color:black\">Distribution Restrictions. You may not</span></b></h3>\n<p class=\"bullet30\" style=\"margin-top:6.0pt; margin-right:0in; margin-bottom:6.0pt; margin-left:1.0in; text-indent:-.25in\">\n<span style=\"font-size:10.0pt; font-family:Symbol; color:black\"><span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n</span></span><span style=\"font-size:10.0pt; font-family:&quot;Tahoma&quot;,sans-serif; color:black\">use Microsofts trademarks in your applications names or in a way that suggests your applications come from or are endorsed by Microsoft; or</span></p>\n<p class=\"bullet30\" style=\"margin-top:6.0pt; margin-right:0in; margin-bottom:6.0pt; margin-left:1.0in; text-indent:-.25in\">\n<span style=\"font-size:10.0pt; font-family:Symbol; color:black\"><span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n</span></span><span style=\"font-size:10.0pt; font-family:&quot;Tahoma&quot;,sans-serif; color:black\">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,\n 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.</span></p>\n<h1><span style=\"font-size:10.0pt\">4.<span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp;\n</span></span><span style=\"font-size:10.0pt\">DATA.</span></h1>\n<h2><span style=\"font-size:10.0pt\">a.<span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp;&nbsp;\n</span></span><span style=\"font-size:10.0pt\">Data Collection. </span><span style=\"font-size:10.0pt; font-weight:normal\">The software may collect information about you and your use of the software, and send that to Microsoft. Microsoft may use this information\n to provide services and improve our products and services.&nbsp; You may opt-out of many of these scenarios, but not all, as described in the software documentation.&nbsp; There are also s<span style=\"color:black\">ome features in the software that may enable you and\n Microsoft to collect data from users of your applications.</span> If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with Microsofts privacy statement. Our privacy\n statement is located at </span><a href=\"https://go.microsoft.com/fwlink/?LinkID=824704\"><span style=\"font-size:10.0pt; font-weight:normal\">https://go.microsoft.com/fwlink/?LinkID=824704</span></a><span style=\"font-size:10.0pt; font-weight:normal\">. You can\n 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.</span></h2>\n<h2><span style=\"font-size:10.0pt\">b.<span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp;\n</span></span><span style=\"font-size:10.0pt\">Processing of Personal Data. </span>\n<span style=\"font-size:10.0pt; font-weight:normal\">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\n Online Services Terms to all customers effective May 25, 2018, at </span><span class=\"MsoHyperlink\"><span style=\"font-size:10.0pt; font-family:&quot;Tahoma&quot;,sans-serif; font-weight:normal\">https://docs.microsoft.com/en-us/legal/gdpr</span></span><span style=\"font-size:10.0pt; font-weight:normal\">.</span></h2>\n<h1><span style=\"font-size:10.0pt\">5.<span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp;\n</span></span><span style=\"font-size:10.0pt; text-transform:uppercase\">Scope of License</span><span style=\"font-size:10.0pt\">.</span><span style=\"font-size:10.0pt; font-weight:normal\"> The software is licensed, not sold. This agreement only gives you some rights\n 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\n in the software that only allow you to use it in certain ways. You may not</span></h1>\n<p class=\"Bullet2\"><span style=\"font-size:10.0pt; font-family:Symbol\"><span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n</span></span><span style=\"font-size:10.0pt\">work around any technical limitations in the software</span><span style=\"font-size:10.0pt\">;</span></p>\n<p class=\"Bullet2\"><span style=\"font-size:10.0pt; font-family:Symbol\"><span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n</span></span><span style=\"font-size:10.0pt\">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\n open source components that may be included in the software;</span></p>\n<p class=\"Bullet2\"><span style=\"font-size:10.0pt; font-family:Symbol\"><span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n</span></span><span style=\"font-size:10.0pt\">remove, minimize, block or modify any notices of Microsoft or its suppliers in the software;\n</span></p>\n<p class=\"Bullet2\"><span style=\"font-size:10.0pt; font-family:Symbol\"><span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n</span></span><span style=\"font-size:10.0pt\">use the software in any way that is against the law; or</span></p>\n<p class=\"Bullet2\"><span style=\"font-size:10.0pt; font-family:Symbol\"><span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n</span></span><span style=\"font-size:10.0pt\">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.</span></p>\n<h1><span class=\"MsoHyperlink\"><span style=\"font-size:10.0pt; font-family:&quot;Tahoma&quot;,sans-serif; color:windowtext; text-decoration:none\">6.<span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp;\n</span></span></span><span style=\"font-size:10.0pt; text-transform:uppercase\">Export Restrictions</span><span style=\"font-size:10.0pt\">.</span><span style=\"font-size:10.0pt; font-weight:normal\">\n</span><span style=\"font-size:10.0pt; font-weight:normal\">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\n on export restrictions, visit www.microsoft.com/exporting.</span><span class=\"MsoHyperlink\"><span style=\"font-size:10.0pt; font-weight:normal\">\n</span></span><span style=\"font-size:10.0pt; font-weight:normal\">&nbsp;</span></h1>\n<h1><span style=\"font-size:10.0pt\">7.<span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp;\n</span></span><span style=\"font-size:10.0pt; text-transform:uppercase\">SUPPORT SERVICES.</span><span style=\"font-size:10.0pt\">\n</span><span style=\"font-size:10.0pt; font-weight:normal\">Because this software is as is, we may not provide support services for it.</span></h1>\n<h1><span style=\"font-size:10.0pt\">8.<span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp;\n</span></span><span style=\"font-size:10.0pt; text-transform:uppercase\">Entire Agreement.</span><span style=\"font-size:10.0pt; font-weight:normal\"> This agreement, and the terms for supplements, updates, Internet-based services and support services that you\n use, are the entire agreement for the software and support services.</span></h1>\n<h1 style=\"margin-left:.25in; text-indent:-.25in\"><span style=\"font-size:10.0pt\">9.<span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp;\n</span></span><span style=\"font-size:10.0pt; text-transform:uppercase\">Applicable Law</span><span style=\"font-size:10.0pt\">.&nbsp;\n</span><span style=\"font-size:10.0pt; font-weight:normal\">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.\n If you acquired the software in any other country, its laws apply.</span></h1>\n<h1 style=\"margin-left:.25in; text-indent:-.25in\"><span style=\"font-size:10.0pt\">10.<span style=\"font:7.0pt &quot;Times New Roman&quot;\">\n</span></span><span style=\"font-size:10.0pt\">CONSUMER RIGHTS; REGIONAL VARIATIONS.\n</span><span style=\"font-size:10.0pt; font-weight:normal\">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,\n 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\n below regions, or mandatory country law applies, then the following provisions apply to you:</span></h1>\n<h2 style=\"margin-left:35.85pt; text-indent:-.25in\"><span style=\"font-size:10.0pt\">a)<span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp;\n</span></span><span style=\"font-size:10.0pt\">Australia. </span><span style=\"font-size:10.0pt; font-weight:normal\">You have statutory guarantees under the Australian Consumer Law and nothing in this agreement is intended to affect those rights.</span></h2>\n<h2 style=\"margin-left:35.85pt; text-indent:-.25in\"><span style=\"font-size:10.0pt\">b)<span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp;\n</span></span><span style=\"font-size:10.0pt\">Canada. </span><span style=\"font-size:10.0pt; font-weight:normal\">If you acquired this software in Canada, you may stop receiving updates by turning off the automatic update feature, disconnecting your device from\n 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\n or software.</span></h2>\n<h2 style=\"margin-left:35.85pt; text-indent:-.25in\"><span style=\"font-size:10.0pt\">c)<span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp;&nbsp;&nbsp;\n</span></span><span style=\"font-size:10.0pt\">Germany and Austria</span><span style=\"font-size:10.0pt; font-weight:normal\">.</span></h2>\n<p class=\"MsoNormal\" style=\"margin-left:35.85pt\"><b><span style=\"font-size:10.0pt\">(i)</span></b><span style=\"font-size:10.0pt\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n<b>Warranty</b>. 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.</span></p>\n<p class=\"MsoNormal\" style=\"margin-left:35.85pt\"><b><span style=\"font-size:10.0pt\">(ii)</span></b><span style=\"font-size:10.0pt\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n<b>Limitation of Liability</b>. 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.</span></p>\n<h1 style=\"margin-left:22.5pt; text-indent:0in\"><span style=\"font-size:10.0pt; font-weight:normal\">Subject to the foregoing clause (ii), Microsoft will only be liable for slight negligence if Microsoft is in breach of such material contractual obligations,\n 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 &quot;cardinal obligations&quot;). In other cases of\n slight negligence, Microsoft will not be liable for slight negligence</span></h1>\n<h1><span style=\"font-size:10.0pt; text-transform:uppercase\">11.<span style=\"font:7.0pt &quot;Times New Roman&quot;\">\n</span></span><span style=\"font-size:10.0pt; text-transform:uppercase\">Disclaimer of Warranty.</span><span style=\"font-size:10.0pt\"> THE SOFTWARE IS LICENSED AS-IS. YOU BEAR THE RISK OF USING IT. MICROSOFT GIVES NO EXPRESS WARRANTIES, GUARANTEES OR CONDITIONS.\n TO THE EXTENT PERMITTED UNDER YOUR LOCAL LAWS, MICROSOFT EXCLUDES THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.\n</span></h1>\n<h1><span style=\"font-size:10.0pt\">12.<span style=\"font:7.0pt &quot;Times New Roman&quot;\">\n</span></span><span style=\"font-size:10.0pt; text-transform:uppercase\">Limitation on and Exclusion of Remedies and Damages.\n</span><span style=\"font-size:10.0pt\">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.</span></h1>\n<p class=\"Body1\"><span style=\"font-size:10.0pt\">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\n warranty, guarantee or condition, strict liability, negligence, or other tort to the extent permitted by applicable law.</span></p>\n<p class=\"MsoNormal\" style=\"margin-left:.25in\"><span style=\"font-size:10.0pt\">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\n may not allow the exclusion or limitation of incidental, consequential or other damages.</span></p>\n<p class=\"MsoNormal\"><span style=\"font-size:10.0pt\">&nbsp;</span></p>\n</div>\n</body>\n</html>\n"
  },
  {
    "path": "tools/vslicense/dotnet-library-license.md",
    "content": "**MICROSOFT SOFTWARE LICENSE TERMS**\n\n**MICROSOFT .NET LIBRARY**\n\n------------------------------------------------------------------------------\nThese 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.\n\n------------------------------------------------------------------------------\n**IF YOU COMPLY WITH THESE LICENSE TERMS, YOU HAVE THE RIGHTS BELOW.**\n\n**1. INSTALLATION AND USE RIGHTS.**\n\n> You may install and use any number of copies of the software to develop and test your applications.\n\n**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.\n\n**3. ADDITIONAL LICENSING REQUIREMENTS AND/OR USE RIGHTS.**\n\n> **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.\n\n>> **i. Right to Use and Distribute.**\n\n>> - You may copy and distribute the object code form of the software.\n\n>> - Third Party Distribution. You may permit distributors of your applications to copy and distribute the Distributable Code as part of those applications.\n\n>> **ii. Distribution Requirements. For any Distributable Code you distribute, you must**\n\n>> - use the Distributable Code in your applications and not as a standalone distribution;\n\n>> - require distributors and external end users to agree to terms that protect it at least as much as this agreement; and\n\n>> - 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.\n\n>> **iii. Distribution Restrictions. You may not**\n\n>> - use Microsoft's trademarks in your applications' names or in a way that suggests your applications come from or are endorsed by Microsoft; or\n\n>> - 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.\n\n**4. DATA.**\n\n> **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.\n\n> **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.\n\n**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\n\n> - work around any technical limitations in the software;\n\n> - 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;\n\n> - remove, minimize, block or modify any notices of Microsoft or its suppliers in the software;\n\n> - use the software in any way that is against the law; or\n\n> - 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.\n\n**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.\n\n**7. SUPPORT SERVICES.** Because this software is \"as is\", we may not provide support services for it.\n\n**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.\n\n**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.\n\n**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:\n\n> **a) Australia.** You have statutory guarantees under the Australian Consumer Law and nothing in this agreement is intended to affect those rights.\n\n> **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.\n\n> **c) Germany and Austria.**\n\n>> **(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.\n\n>> **(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.\n\n> 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\n\n**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.**\n\n**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.**\n\nThis 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.\n\nIt 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."
  }
]